{"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/browser\/app_modal_dialog.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n\nconst std::string BEFORE_UNLOAD_HTML =\n \"beforeunload<\/title><\/head><body>\"\n \"<script>window.onbeforeunload=function(e){return 'foo'}<\/script>\"\n \"<\/body><\/html>\";\n\nconst std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE =\n L\"w=window.open(); w.onbeforeunload=function(e){return 'foo'};\";\n\nnamespace {\n\n\/\/ Given a page title, returns the expected window caption string.\nstd::wstring WindowCaptionFromPageTitle(std::wstring page_title) {\n#if defined(OS_WIN) || defined(OS_LINUX)\n if (page_title.empty())\n return l10n_util::GetString(IDS_PRODUCT_NAME);\n\n return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);\n#elif defined(OS_MACOSX)\n \/\/ On Mac, we don't want to suffix the page title with the application name.\n if (page_title.empty())\n return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);\n return page_title;\n#endif\n}\n\n\/\/ Returns the number of active RenderProcessHosts.\nint CountRenderProcessHosts() {\n int result = 0;\n for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());\n !i.IsAtEnd(); i.Advance())\n ++result;\n return result;\n}\n\n} \/\/ namespace\n\nclass BrowserTest : public InProcessBrowserTest {\n protected:\n \/\/ In RTL locales wrap the page title with RTL embedding characters so that it\n \/\/ matches the value returned by GetWindowTitle().\n std::wstring LocaleWindowCaptionFromPageTitle(\n const std::wstring& expected_title) {\n std::wstring page_title = WindowCaptionFromPageTitle(expected_title);\n#if defined(OS_WIN)\n std::string locale = g_browser_process->GetApplicationLocale();\n if (l10n_util::GetTextDirectionForLocale(locale.c_str()) ==\n l10n_util::RIGHT_TO_LEFT) {\n l10n_util::WrapStringWithLTRFormatting(&page_title);\n }\n\n return page_title;\n#else\n \/\/ Do we need to use the above code on POSIX as well?\n return page_title;\n#endif\n }\n};\n\n\/\/ Launch the app on a page with no title, check that the app title was set\n\/\/ correctly.\nIN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L\"title1.html\"),\n UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));\n string16 tab_title;\n ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));\n EXPECT_EQ(ASCIIToUTF16(\"title1.html\"), tab_title);\n}\n\n\/\/ Launch the app, navigate to a page with a title, check that the app title\n\/\/ was set correctly.\nIN_PROC_BROWSER_TEST_F(BrowserTest, Title) {\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title2.html\"));\n const std::wstring test_title(L\"Title Of Awesomeness\");\n EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),\n UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));\n string16 tab_title;\n ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));\n EXPECT_EQ(WideToUTF16(test_title), tab_title);\n}\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {\n GURL url(ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n ui_test_utils::NavigateToURL(browser(), url);\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n EXPECT_EQ(2, browser()->tab_count());\n EXPECT_EQ(0, browser()->selected_index());\n TabContents* second_tab = browser()->GetTabContentsAt(1);\n ASSERT_TRUE(second_tab);\n second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L\"\",\n L\"alert('Activate!');\");\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->CloseModalDialog();\n EXPECT_EQ(2, browser()->tab_count());\n EXPECT_EQ(1, browser()->selected_index());\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n\/\/ Create 34 tabs and verify that a lot of processes have been created. The\n\/\/ exact number of processes depends on the amount of memory. Previously we\n\/\/ had a hard limit of 31 processes and this test is mainly directed at\n\/\/ verifying that we don't crash when we pass this limit.\nIN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) {\n GURL url(ui_test_utils::GetTestUrl(L\".\", L\"title2.html\"));\n\n \/\/ There is one initial tab.\n for (int ix = 0; ix != 33; ++ix) {\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n }\n EXPECT_EQ(34, browser()->tab_count());\n\n \/\/ See browser\\renderer_host\\render_process_host.cc for the algorithm to\n \/\/ decide how many processes to create.\n if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {\n EXPECT_GE(CountRenderProcessHosts(), 24);\n } else {\n EXPECT_LE(CountRenderProcessHosts(), 23);\n }\n}\n\n\/\/ Test for crbug.com\/22004. Reloading a page with a before unload handler and\n\/\/ then canceling the dialog should not leave the throbber spinning.\nIN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {\n GURL url(\"data:text\/html,\" + BEFORE_UNLOAD_HTML);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Navigate to another page, but click cancel in the dialog. Make sure that\n \/\/ the throbber stops spinning.\n browser()->Reload();\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->CloseModalDialog();\n EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading());\n\n \/\/ Clear the beforeunload handler so the test can easily exit.\n browser()->GetSelectedTabContents()->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", L\"onbeforeunload=null;\");\n}\n\n\/\/ Test for crbug.com\/11647. A page closed with window.close() should not have\n\/\/ two beforeunload dialogs shown.\nIN_PROC_BROWSER_TEST_F(BrowserTest, SingleBeforeUnloadAfterWindowClose) {\n browser()->GetSelectedTabContents()->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", OPEN_NEW_BEFOREUNLOAD_PAGE);\n\n \/\/ Close the new window with JavaScript, which should show a single\n \/\/ beforeunload dialog. Then show another alert, to make it easy to verify\n \/\/ that a second beforeunload dialog isn't shown.\n browser()->GetTabContentsAt(0)->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", L\"w.close(); alert('bar');\");\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->AcceptWindow();\n\n alert = ui_test_utils::WaitForAppModalDialog();\n EXPECT_FALSE(alert->is_before_unload_dialog());\n alert->AcceptWindow();\n}\n\n\/\/ Test that get_process_idle_time() returns reasonable values when compared\n\/\/ with time deltas measured locally.\nIN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {\n base::TimeTicks start = base::TimeTicks::Now();\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator());\n for (; !it.IsAtEnd(); it.Advance()) {\n base::TimeDelta renderer_td =\n it.GetCurrentValue()->get_child_process_idle_time();\n base::TimeDelta browser_td = base::TimeTicks::Now() - start;\n EXPECT_TRUE(browser_td >= renderer_td);\n }\n}\n<commit_msg>Mark BrowserTest.SingleBeforeUnloadAfterWindowClose as flaky.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/browser\/app_modal_dialog.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n\nconst std::string BEFORE_UNLOAD_HTML =\n \"<html><head><title>beforeunload<\/title><\/head><body>\"\n \"<script>window.onbeforeunload=function(e){return 'foo'}<\/script>\"\n \"<\/body><\/html>\";\n\nconst std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE =\n L\"w=window.open(); w.onbeforeunload=function(e){return 'foo'};\";\n\nnamespace {\n\n\/\/ Given a page title, returns the expected window caption string.\nstd::wstring WindowCaptionFromPageTitle(std::wstring page_title) {\n#if defined(OS_WIN) || defined(OS_LINUX)\n if (page_title.empty())\n return l10n_util::GetString(IDS_PRODUCT_NAME);\n\n return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);\n#elif defined(OS_MACOSX)\n \/\/ On Mac, we don't want to suffix the page title with the application name.\n if (page_title.empty())\n return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);\n return page_title;\n#endif\n}\n\n\/\/ Returns the number of active RenderProcessHosts.\nint CountRenderProcessHosts() {\n int result = 0;\n for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());\n !i.IsAtEnd(); i.Advance())\n ++result;\n return result;\n}\n\n} \/\/ namespace\n\nclass BrowserTest : public InProcessBrowserTest {\n protected:\n \/\/ In RTL locales wrap the page title with RTL embedding characters so that it\n \/\/ matches the value returned by GetWindowTitle().\n std::wstring LocaleWindowCaptionFromPageTitle(\n const std::wstring& expected_title) {\n std::wstring page_title = WindowCaptionFromPageTitle(expected_title);\n#if defined(OS_WIN)\n std::string locale = g_browser_process->GetApplicationLocale();\n if (l10n_util::GetTextDirectionForLocale(locale.c_str()) ==\n l10n_util::RIGHT_TO_LEFT) {\n l10n_util::WrapStringWithLTRFormatting(&page_title);\n }\n\n return page_title;\n#else\n \/\/ Do we need to use the above code on POSIX as well?\n return page_title;\n#endif\n }\n};\n\n\/\/ Launch the app on a page with no title, check that the app title was set\n\/\/ correctly.\nIN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L\"title1.html\"),\n UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));\n string16 tab_title;\n ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));\n EXPECT_EQ(ASCIIToUTF16(\"title1.html\"), tab_title);\n}\n\n\/\/ Launch the app, navigate to a page with a title, check that the app title\n\/\/ was set correctly.\nIN_PROC_BROWSER_TEST_F(BrowserTest, Title) {\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title2.html\"));\n const std::wstring test_title(L\"Title Of Awesomeness\");\n EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),\n UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));\n string16 tab_title;\n ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));\n EXPECT_EQ(WideToUTF16(test_title), tab_title);\n}\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {\n GURL url(ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n ui_test_utils::NavigateToURL(browser(), url);\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n EXPECT_EQ(2, browser()->tab_count());\n EXPECT_EQ(0, browser()->selected_index());\n TabContents* second_tab = browser()->GetTabContentsAt(1);\n ASSERT_TRUE(second_tab);\n second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L\"\",\n L\"alert('Activate!');\");\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->CloseModalDialog();\n EXPECT_EQ(2, browser()->tab_count());\n EXPECT_EQ(1, browser()->selected_index());\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n\/\/ Create 34 tabs and verify that a lot of processes have been created. The\n\/\/ exact number of processes depends on the amount of memory. Previously we\n\/\/ had a hard limit of 31 processes and this test is mainly directed at\n\/\/ verifying that we don't crash when we pass this limit.\nIN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) {\n GURL url(ui_test_utils::GetTestUrl(L\".\", L\"title2.html\"));\n\n \/\/ There is one initial tab.\n for (int ix = 0; ix != 33; ++ix) {\n browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,\n true, 0, false, NULL);\n }\n EXPECT_EQ(34, browser()->tab_count());\n\n \/\/ See browser\\renderer_host\\render_process_host.cc for the algorithm to\n \/\/ decide how many processes to create.\n if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {\n EXPECT_GE(CountRenderProcessHosts(), 24);\n } else {\n EXPECT_LE(CountRenderProcessHosts(), 23);\n }\n}\n\n\/\/ Test for crbug.com\/22004. Reloading a page with a before unload handler and\n\/\/ then canceling the dialog should not leave the throbber spinning.\nIN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {\n GURL url(\"data:text\/html,\" + BEFORE_UNLOAD_HTML);\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Navigate to another page, but click cancel in the dialog. Make sure that\n \/\/ the throbber stops spinning.\n browser()->Reload();\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->CloseModalDialog();\n EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading());\n\n \/\/ Clear the beforeunload handler so the test can easily exit.\n browser()->GetSelectedTabContents()->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", L\"onbeforeunload=null;\");\n}\n\n\/\/ Test for crbug.com\/11647. A page closed with window.close() should not have\n\/\/ two beforeunload dialogs shown.\nIN_PROC_BROWSER_TEST_F(BrowserTest, FLAKY_SingleBeforeUnloadAfterWindowClose) {\n browser()->GetSelectedTabContents()->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", OPEN_NEW_BEFOREUNLOAD_PAGE);\n\n \/\/ Close the new window with JavaScript, which should show a single\n \/\/ beforeunload dialog. Then show another alert, to make it easy to verify\n \/\/ that a second beforeunload dialog isn't shown.\n browser()->GetTabContentsAt(0)->render_view_host()->\n ExecuteJavascriptInWebFrame(L\"\", L\"w.close(); alert('bar');\");\n AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();\n alert->AcceptWindow();\n\n alert = ui_test_utils::WaitForAppModalDialog();\n EXPECT_FALSE(alert->is_before_unload_dialog());\n alert->AcceptWindow();\n}\n\n\/\/ Test that get_process_idle_time() returns reasonable values when compared\n\/\/ with time deltas measured locally.\nIN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {\n base::TimeTicks start = base::TimeTicks::Now();\n ui_test_utils::NavigateToURL(browser(),\n ui_test_utils::GetTestUrl(L\".\", L\"title1.html\"));\n RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator());\n for (; !it.IsAtEnd(); it.Advance()) {\n base::TimeDelta renderer_td =\n it.GetCurrentValue()->get_child_process_idle_time();\n base::TimeDelta browser_td = base::TimeTicks::Now() - start;\n EXPECT_TRUE(browser_td >= renderer_td);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#define SCREEN_HEIGHT 480\n#define SCREEN_WIDTH 640\n\nnamespace kb {\n\n\/\/ SCENE (BASE) ================================================================\nclass Scene {\nprivate:\n\nprotected:\n sf::RenderWindow* app;\n Scene* id_scene;\n\npublic:\n virtual bool init(sf::RenderWindow* app, Scene *id);\n virtual char step();\n virtual void draw();\n};\n\n\/\/ SCENE0 ======================================================================\nclass Scene0 : public Scene {\nprivate:\n sf::Font* font;\n sf::Text* text;\n\npublic:\n bool init(sf::RenderWindow* app, Scene *id);\n char step();\n void draw();\n};\n\n\/\/ SCENE1 ======================================================================\nclass Scene1 : public Scene {\nprivate:\n sf::Sprite *image_index;\n sf::Texture* image_texture;\n\npublic:\n bool init(sf::RenderWindow* app, Scene *id);\n char step();\n void draw();\n};\n\n};\n<commit_msg>edit screen_height and screen width<commit_after>#define SCREEN_HEIGHT 640\n#define SCREEN_WIDTH 1200\n\nnamespace kb {\n\n\/\/ SCENE (BASE) ================================================================\nclass Scene {\nprivate:\n\nprotected:\n sf::RenderWindow* app;\n Scene* id_scene;\n\npublic:\n virtual bool init(sf::RenderWindow* app, Scene *id);\n virtual char step();\n virtual void draw();\n};\n\n\/\/ SCENE0 ======================================================================\nclass Scene0 : public Scene {\nprivate:\n sf::Font* font;\n sf::Text* text;\n\npublic:\n bool init(sf::RenderWindow* app, Scene *id);\n char step();\n void draw();\n};\n\n\/\/ SCENE1 ======================================================================\nclass Scene1 : public Scene {\nprivate:\n sf::Sprite *image_index;\n sf::Texture* image_texture;\n\npublic:\n bool init(sf::RenderWindow* app, Scene *id);\n char step();\n void draw();\n};\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_url_handler.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_about_handler.h\"\n#include \"chrome\/browser\/extensions\/extension_web_ui.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_web_ui_factory.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/webui\/web_ui.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ Handles rewriting view-source URLs for what we'll actually load.\nstatic bool HandleViewSource(GURL* url, Profile* profile) {\n if (url->SchemeIs(chrome::kViewSourceScheme)) {\n \/\/ Load the inner URL instead.\n *url = GURL(url->path());\n\n \/\/ Bug 26129: limit view-source to view the content and not any\n \/\/ other kind of 'active' url scheme like 'javascript' or 'data'.\n static const char* const allowed_sub_schemes[] = {\n chrome::kHttpScheme, chrome::kHttpsScheme, chrome::kFtpScheme,\n chrome::kChromeDevToolsScheme, chrome::kChromeUIScheme,\n chrome::kFileScheme\n };\n\n bool is_sub_scheme_allowed = false;\n for (size_t i = 0; i < arraysize(allowed_sub_schemes); i++) {\n if (url->SchemeIs(allowed_sub_schemes[i])) {\n is_sub_scheme_allowed = true;\n break;\n }\n }\n\n if (!is_sub_scheme_allowed) {\n *url = GURL(chrome::kAboutBlankURL);\n return false;\n }\n\n return true;\n }\n return false;\n}\n\n\/\/ Turns a non view-source URL into the corresponding view-source URL.\nstatic bool ReverseViewSource(GURL* url, Profile* profile) {\n \/\/ No action necessary if the URL is already view-source:\n if (url->SchemeIs(chrome::kViewSourceScheme))\n return false;\n\n url_canon::Replacements<char> repl;\n repl.SetScheme(chrome::kViewSourceScheme,\n url_parse::Component(0, strlen(chrome::kViewSourceScheme)));\n repl.SetPath(url->spec().c_str(),\n url_parse::Component(0, url->spec().size()));\n *url = url->ReplaceComponents(repl);\n return true;\n}\n\n\/\/ Handles rewriting Web UI URLs.\nstatic bool HandleWebUI(GURL* url, Profile* profile) {\n if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url))\n return false;\n\n \/\/ Special case the new tab page. In older versions of Chrome, the new tab\n \/\/ page was hosted at chrome-internal:<blah>. This might be in people's saved\n \/\/ sessions or bookmarks, so we say any URL with that scheme triggers the new\n \/\/ tab page.\n if (url->SchemeIs(chrome::kChromeInternalScheme)) {\n \/\/ Rewrite it with the proper new tab URL.\n *url = GURL(chrome::kChromeUINewTabURL);\n }\n\n return true;\n}\n\nstd::vector<BrowserURLHandler::HandlerPair> BrowserURLHandler::url_handlers_;\n\n\/\/ static\nvoid BrowserURLHandler::InitURLHandlers() {\n if (!url_handlers_.empty())\n return;\n\n \/\/ Visual Studio 2010 has problems converting NULL to the null pointer for\n \/\/ std::pair. See http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/520043\/error-converting-from-null-to-a-pointer-type-in-std-pair\n \/\/ It will work if we pass nullptr.\n#if defined(_MSC_VER) && _MSC_VER >= 1600\n URLHandler null_handler = nullptr;\n#else\n URLHandler null_handler = NULL;\n#endif\n\n \/\/ Add the default URL handlers.\n url_handlers_.push_back(\n HandlerPair(&ExtensionWebUI::HandleChromeURLOverride, null_handler));\n \/\/ about:\n url_handlers_.push_back(HandlerPair(&WillHandleBrowserAboutURL,\n null_handler));\n \/\/ chrome: & friends.\n url_handlers_.push_back(HandlerPair(&HandleWebUI, null_handler));\n \/\/ view-source:\n url_handlers_.push_back(HandlerPair(&HandleViewSource, &ReverseViewSource));\n}\n\n\/\/ static\nvoid BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile,\n bool* reverse_on_redirect) {\n if (url_handlers_.empty())\n InitURLHandlers();\n for (size_t i = 0; i < url_handlers_.size(); ++i) {\n if ((*url_handlers_[i].first)(url, profile)) {\n *reverse_on_redirect = (url_handlers_[i].second != NULL);\n return;\n }\n }\n}\n\n\/\/ static\nbool BrowserURLHandler::ReverseURLRewrite(\n GURL* url, const GURL& original, Profile* profile) {\n for (size_t i = 0; i < url_handlers_.size(); ++i) {\n GURL test_url(original);\n if ((*url_handlers_[i].first)(&test_url, profile)) {\n if (url_handlers_[i].second)\n return (*url_handlers_[i].second)(url, profile);\n else\n return false;\n }\n }\n return false;\n}\n<commit_msg>BMC#19078 handling of special URLs not consistent.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_url_handler.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_about_handler.h\"\n#include \"chrome\/browser\/extensions\/extension_web_ui.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_web_ui_factory.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/webui\/web_ui.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ Handles rewriting view-source URLs for what we'll actually load.\nstatic bool HandleViewSource(GURL* url, Profile* profile) {\n if (url->SchemeIs(chrome::kViewSourceScheme)) {\n \/\/ Load the inner URL instead.\n *url = GURL(url->path());\n\n \/\/ Bug 26129: limit view-source to view the content and not any\n \/\/ other kind of 'active' url scheme like 'javascript' or 'data'.\n static const char* const allowed_sub_schemes[] = {\n chrome::kHttpScheme, chrome::kHttpsScheme, chrome::kFtpScheme,\n chrome::kChromeDevToolsScheme, chrome::kChromeUIScheme,\n chrome::kFileScheme\n };\n\n bool is_sub_scheme_allowed = false;\n for (size_t i = 0; i < arraysize(allowed_sub_schemes); i++) {\n if (url->SchemeIs(allowed_sub_schemes[i])) {\n is_sub_scheme_allowed = true;\n break;\n }\n }\n\n if (!is_sub_scheme_allowed) {\n *url = GURL(chrome::kAboutBlankURL);\n return false;\n }\n\n return true;\n }\n return false;\n}\n\n\/\/ Turns a non view-source URL into the corresponding view-source URL.\nstatic bool ReverseViewSource(GURL* url, Profile* profile) {\n \/\/ No action necessary if the URL is already view-source:\n if (url->SchemeIs(chrome::kViewSourceScheme))\n return false;\n\n url_canon::Replacements<char> repl;\n repl.SetScheme(chrome::kViewSourceScheme,\n url_parse::Component(0, strlen(chrome::kViewSourceScheme)));\n repl.SetPath(url->spec().c_str(),\n url_parse::Component(0, url->spec().size()));\n *url = url->ReplaceComponents(repl);\n return true;\n}\n\n\/\/ Handles rewriting Web UI URLs.\nstatic bool HandleWebUI(GURL* url, Profile* profile) {\n#if !defined(TOOLKIT_MEEGOTOUCH)\n if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url))\n return false;\n#else\n if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url)) {\n \/\/ Let browser handle chrome:\/\/ urls like about:blank\n if(CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDisableChromeWebUi)) {\n if (url->SchemeIs(chrome::kChromeUIScheme) ||\n url->SchemeIs(chrome::kChromeDevToolsScheme) ||\n url->SchemeIs(chrome::kChromeInternalScheme)) {\n *url = GURL(chrome::kAboutBlankURL);\n }\n }\n return false;\n }\n#endif\n\n \/\/ Special case the new tab page. In older versions of Chrome, the new tab\n \/\/ page was hosted at chrome-internal:<blah>. This might be in people's saved\n \/\/ sessions or bookmarks, so we say any URL with that scheme triggers the new\n \/\/ tab page.\n if (url->SchemeIs(chrome::kChromeInternalScheme)) {\n \/\/ Rewrite it with the proper new tab URL.\n *url = GURL(chrome::kChromeUINewTabURL);\n }\n\n return true;\n}\n\nstd::vector<BrowserURLHandler::HandlerPair> BrowserURLHandler::url_handlers_;\n\n\/\/ static\nvoid BrowserURLHandler::InitURLHandlers() {\n if (!url_handlers_.empty())\n return;\n\n \/\/ Visual Studio 2010 has problems converting NULL to the null pointer for\n \/\/ std::pair. See http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/520043\/error-converting-from-null-to-a-pointer-type-in-std-pair\n \/\/ It will work if we pass nullptr.\n#if defined(_MSC_VER) && _MSC_VER >= 1600\n URLHandler null_handler = nullptr;\n#else\n URLHandler null_handler = NULL;\n#endif\n\n \/\/ Add the default URL handlers.\n url_handlers_.push_back(\n HandlerPair(&ExtensionWebUI::HandleChromeURLOverride, null_handler));\n \/\/ about:\n url_handlers_.push_back(HandlerPair(&WillHandleBrowserAboutURL,\n null_handler));\n \/\/ chrome: & friends.\n url_handlers_.push_back(HandlerPair(&HandleWebUI, null_handler));\n \/\/ view-source:\n url_handlers_.push_back(HandlerPair(&HandleViewSource, &ReverseViewSource));\n}\n\n\/\/ static\nvoid BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile,\n bool* reverse_on_redirect) {\n if (url_handlers_.empty())\n InitURLHandlers();\n for (size_t i = 0; i < url_handlers_.size(); ++i) {\n if ((*url_handlers_[i].first)(url, profile)) {\n *reverse_on_redirect = (url_handlers_[i].second != NULL);\n return;\n }\n }\n}\n\n\/\/ static\nbool BrowserURLHandler::ReverseURLRewrite(\n GURL* url, const GURL& original, Profile* profile) {\n for (size_t i = 0; i < url_handlers_.size(); ++i) {\n GURL test_url(original);\n if ((*url_handlers_[i].first)(&test_url, profile)) {\n if (url_handlers_[i].second)\n return (*url_handlers_[i].second)(url, profile);\n else\n return false;\n }\n }\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/tab_icon_view.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#include <shellapi.h>\n#endif\n\n#include \"app\/gfx\/canvas.h\"\n#include \"app\/gfx\/favicon_size.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n#if defined(OS_WIN)\n#include \"app\/gfx\/icon_util.h\"\n#endif\n\nstatic bool g_initialized = false;\nstatic SkBitmap* g_default_fav_icon = NULL;\nstatic SkBitmap* g_throbber_frames = NULL;\nstatic SkBitmap* g_throbber_frames_light = NULL;\nstatic int g_throbber_frame_count;\n\n\/\/ static\nvoid TabIconView::InitializeIfNeeded() {\n if (!g_initialized) {\n ResourceBundle &rb = ResourceBundle::GetSharedInstance();\n\n#if defined(OS_WIN)\n \/\/ The default window icon is the application icon, not the default\n \/\/ favicon.\n std::wstring exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n file_util::AppendToPath(&exe_path, L\"chrome.exe\");\n HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);\n g_default_fav_icon =\n IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));\n DestroyIcon(app_icon);\n#else\n NOTIMPLEMENTED();\n#endif\n\n g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);\n g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);\n g_throbber_frame_count = g_throbber_frames->width() \/\n g_throbber_frames->height();\n\n \/\/ Verify that our light and dark styles have the same number of frames.\n DCHECK(g_throbber_frame_count ==\n g_throbber_frames_light->width() \/ g_throbber_frames_light->height());\n g_initialized = true;\n }\n}\n\nTabIconView::TabIconView(TabIconViewModel* model)\n : model_(model),\n throbber_running_(false),\n is_light_(false),\n throbber_frame_(0) {\n InitializeIfNeeded();\n}\n\nTabIconView::~TabIconView() {\n}\n\nvoid TabIconView::Update() {\n if (throbber_running_) {\n \/\/ We think the tab is loading.\n if (!model_->ShouldTabIconViewAnimate()) {\n \/\/ Woops, tab is invalid or not loading, reset our status and schedule\n \/\/ a paint.\n throbber_running_ = false;\n SchedulePaint();\n } else {\n \/\/ The tab is still loading, increment the frame.\n throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;\n SchedulePaint();\n }\n } else if (model_->ShouldTabIconViewAnimate()) {\n \/\/ We didn't think we were loading, but the tab is loading. Reset the\n \/\/ frame and status and schedule a paint.\n throbber_running_ = true;\n throbber_frame_ = 0;\n SchedulePaint();\n }\n}\n\nvoid TabIconView::PaintThrobber(gfx::Canvas* canvas) {\n int image_size = g_throbber_frames->height();\n PaintIcon(canvas, is_light_ ? *g_throbber_frames_light : *g_throbber_frames,\n throbber_frame_ * image_size, 0, image_size, image_size, false);\n}\n\nvoid TabIconView::PaintFavIcon(gfx::Canvas* canvas, const SkBitmap& bitmap) {\n PaintIcon(canvas, bitmap, 0, 0, bitmap.width(), bitmap.height(), true);\n}\n\nvoid TabIconView::PaintIcon(gfx::Canvas* canvas,\n const SkBitmap& bitmap,\n int src_x,\n int src_y,\n int src_w,\n int src_h,\n bool filter) {\n \/\/ For source images smaller than the favicon square, scale them as if they\n \/\/ were padded to fit the favicon square, so we don't blow up tiny favicons\n \/\/ into larger or nonproportional results.\n float float_src_w = static_cast<float>(src_w);\n float float_src_h = static_cast<float>(src_h);\n float scalable_w, scalable_h;\n if (src_w <= kFavIconSize && src_h <= kFavIconSize) {\n scalable_w = scalable_h = kFavIconSize;\n } else {\n scalable_w = float_src_w;\n scalable_h = float_src_h;\n }\n\n \/\/ Scale proportionately.\n float scale = std::min(static_cast<float>(width()) \/ scalable_w,\n static_cast<float>(height()) \/ scalable_h);\n int dest_w = static_cast<int>(float_src_w * scale);\n int dest_h = static_cast<int>(float_src_h * scale);\n\n \/\/ Center the scaled image.\n canvas->DrawBitmapInt(bitmap, src_x, src_y, src_w, src_h,\n (width() - dest_w) \/ 2, (height() - dest_h) \/ 2, dest_w,\n dest_h, filter);\n}\n\nvoid TabIconView::Paint(gfx::Canvas* canvas) {\n bool rendered = false;\n\n if (throbber_running_) {\n rendered = true;\n PaintThrobber(canvas);\n } else {\n SkBitmap favicon = model_->GetFavIconForTabIconView();\n if (!favicon.isNull()) {\n rendered = true;\n PaintFavIcon(canvas, favicon);\n }\n }\n\n if (!rendered)\n PaintFavIcon(canvas, *g_default_fav_icon);\n}\n\ngfx::Size TabIconView::GetPreferredSize() {\n return gfx::Size(kFavIconSize, kFavIconSize);\n}\n<commit_msg>Another fix for issue 13724: Don't hard code chrome.exe<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/tab_icon_view.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#include <shellapi.h>\n#endif\n\n#include \"app\/gfx\/canvas.h\"\n#include \"app\/gfx\/favicon_size.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n#if defined(OS_WIN)\n#include \"app\/gfx\/icon_util.h\"\n#endif\n\nstatic bool g_initialized = false;\nstatic SkBitmap* g_default_fav_icon = NULL;\nstatic SkBitmap* g_throbber_frames = NULL;\nstatic SkBitmap* g_throbber_frames_light = NULL;\nstatic int g_throbber_frame_count;\n\n\/\/ static\nvoid TabIconView::InitializeIfNeeded() {\n if (!g_initialized) {\n ResourceBundle &rb = ResourceBundle::GetSharedInstance();\n\n#if defined(OS_WIN)\n \/\/ The default window icon is the application icon, not the default\n \/\/ favicon.\n std::wstring exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n file_util::AppendToPath(&exe_path,\n chrome::kBrowserProcessExecutableName);\n\n HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);\n g_default_fav_icon =\n IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));\n DestroyIcon(app_icon);\n#else\n NOTIMPLEMENTED();\n#endif\n\n g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);\n g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);\n g_throbber_frame_count = g_throbber_frames->width() \/\n g_throbber_frames->height();\n\n \/\/ Verify that our light and dark styles have the same number of frames.\n DCHECK(g_throbber_frame_count ==\n g_throbber_frames_light->width() \/ g_throbber_frames_light->height());\n g_initialized = true;\n }\n}\n\nTabIconView::TabIconView(TabIconViewModel* model)\n : model_(model),\n throbber_running_(false),\n is_light_(false),\n throbber_frame_(0) {\n InitializeIfNeeded();\n}\n\nTabIconView::~TabIconView() {\n}\n\nvoid TabIconView::Update() {\n if (throbber_running_) {\n \/\/ We think the tab is loading.\n if (!model_->ShouldTabIconViewAnimate()) {\n \/\/ Woops, tab is invalid or not loading, reset our status and schedule\n \/\/ a paint.\n throbber_running_ = false;\n SchedulePaint();\n } else {\n \/\/ The tab is still loading, increment the frame.\n throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;\n SchedulePaint();\n }\n } else if (model_->ShouldTabIconViewAnimate()) {\n \/\/ We didn't think we were loading, but the tab is loading. Reset the\n \/\/ frame and status and schedule a paint.\n throbber_running_ = true;\n throbber_frame_ = 0;\n SchedulePaint();\n }\n}\n\nvoid TabIconView::PaintThrobber(gfx::Canvas* canvas) {\n int image_size = g_throbber_frames->height();\n PaintIcon(canvas, is_light_ ? *g_throbber_frames_light : *g_throbber_frames,\n throbber_frame_ * image_size, 0, image_size, image_size, false);\n}\n\nvoid TabIconView::PaintFavIcon(gfx::Canvas* canvas, const SkBitmap& bitmap) {\n PaintIcon(canvas, bitmap, 0, 0, bitmap.width(), bitmap.height(), true);\n}\n\nvoid TabIconView::PaintIcon(gfx::Canvas* canvas,\n const SkBitmap& bitmap,\n int src_x,\n int src_y,\n int src_w,\n int src_h,\n bool filter) {\n \/\/ For source images smaller than the favicon square, scale them as if they\n \/\/ were padded to fit the favicon square, so we don't blow up tiny favicons\n \/\/ into larger or nonproportional results.\n float float_src_w = static_cast<float>(src_w);\n float float_src_h = static_cast<float>(src_h);\n float scalable_w, scalable_h;\n if (src_w <= kFavIconSize && src_h <= kFavIconSize) {\n scalable_w = scalable_h = kFavIconSize;\n } else {\n scalable_w = float_src_w;\n scalable_h = float_src_h;\n }\n\n \/\/ Scale proportionately.\n float scale = std::min(static_cast<float>(width()) \/ scalable_w,\n static_cast<float>(height()) \/ scalable_h);\n int dest_w = static_cast<int>(float_src_w * scale);\n int dest_h = static_cast<int>(float_src_h * scale);\n\n \/\/ Center the scaled image.\n canvas->DrawBitmapInt(bitmap, src_x, src_y, src_w, src_h,\n (width() - dest_w) \/ 2, (height() - dest_h) \/ 2, dest_w,\n dest_h, filter);\n}\n\nvoid TabIconView::Paint(gfx::Canvas* canvas) {\n bool rendered = false;\n\n if (throbber_running_) {\n rendered = true;\n PaintThrobber(canvas);\n } else {\n SkBitmap favicon = model_->GetFavIconForTabIconView();\n if (!favicon.isNull()) {\n rendered = true;\n PaintFavIcon(canvas, favicon);\n }\n }\n\n if (!rendered)\n PaintFavIcon(canvas, *g_default_fav_icon);\n}\n\ngfx::Size TabIconView::GetPreferredSize() {\n return gfx::Size(kFavIconSize, kFavIconSize);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Schema.hpp\"\n#include <sstream>\n\nstatic std::string translateType(const DataType& type) {\n std::ostringstream stream;\n if(type.typeTag == DataTypeTag::Integer) {\n stream << \"Integer\";\n } else if(type.typeTag == DataTypeTag::Numeric) {\n stream << \"Numeric<\" << (int) type.attributes.numeric.integerPlaces\n << \",\" << (int) type.attributes.numeric.decimalPlaces << \">\";\n } else if(type.typeTag == DataTypeTag::Char) {\n stream << \"Char<\" << (int) type.attributes.charLen << \">\";\n } else if(type.typeTag == DataTypeTag::VarChar) {\n stream << \"Varchar<\" << (int) type.attributes.charLen << \">\";\n } else if(type.typeTag == DataTypeTag::Date) {\n stream << \"Date\";\n } else if(type.typeTag == DataTypeTag::Timestamp) {\n stream << \"Timestamp\";\n }\n return stream.str();\n}\n\ntemplate<typename T, typename Callable>\nstatic void generateList(std::ostream& out, const std::vector<T>& elements, Callable cb, std::string seperator = \", \") {\n auto first = true;\n for(const auto& elem : elements) {\n if(!first) out << seperator;\n cb(out, elem);\n first = false;\n }\n}\n\nvoid Schema::generateCppCode(std::ostream& out) {\n out <<\n \"#ifndef H_Schema\\n\"\n \"#define H_Schema\\n\"\n \"#include <vector>\\n\"\n \"#include <map>\\n\"\n \"#include <unordered_map>\\n\"\n \"#include \\\"schema\/Types.hpp\\\"\\n\";\n for(auto& table : tables) {\n out << \"\/\/--------------------------------------------------\\n\"\n \"struct \" << table.name << \"_t {\\n\";\n \/\/ actual columns\n for(auto& column : table.columns) {\n out << \" std::vector<\" << translateType(column.type) << \"> col_\" << column.name << \";\\n\";\n }\n \/\/ primary key index\n if(!table.primaryKey.empty()) {\n if(table.primaryKeyPrefixIndexable) {\n out << \" std::map<std::tuple<\";\n } else {\n out << \" std::unordered_map<std::tuple<\";\n }\n generateList(out, table.primaryKey, [&](auto& out, auto& col){\n out << translateType(table.columns[col].type);\n });\n out << \">, size_t> primary_key_idx;\\n\";\n }\n \/\/ additional idcs\n for(auto& idx : table.indices) {\n if(idx.prefixIndexable) {\n out << \" std::map<std::tuple<\";\n } else {\n out << \" std::unordered_map<std::tuple<\";\n }\n generateList(out, idx.columns, [&](auto& out, auto& col){\n out << translateType(table.columns[col].type);\n });\n out << \">, size_t> idx_\" << idx.name << \";\\n\";\n }\n \/\/ insert\n out << \" void insert_tuple(\";\n generateList(out, table.columns, [&](auto& out, auto& column){\n out << translateType(column.type) << \" \" << column.name;\n });\n out << \") {\\n\";\n for(auto& column : table.columns) {\n out << \" this->col_\" << column.name << \".push_back(\" << column.name << \");\\n\";\n }\n auto generateIndexInsert = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){\n out << \" this->\" << idxName << \".insert(std::make_pair(std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << table.columns[col].name;\n });\n out << \"), this->col_\" << table.columns[0].name << \".size()))\\n\";\n };\n if(!table.primaryKey.empty()) {\n generateIndexInsert(\"primary_key_idx\", table.primaryKey);\n }\n for(auto& idx : table.indices) {\n generateIndexInsert(\"idx_\" + idx.name, idx.columns);\n }\n out << \" }\\n\";\n \/\/ delete\n out << \" void delete_tuple(size_t tid) {\\n\";\n for(auto& column : table.columns) {\n out << \" this->col_\" << column.name << \"[tid] = this->col_\" << column.name << \".back();\\n\";\n out << \" this->col_\" << column.name << \".pop_back();\\n\";\n }\n auto generateIndexDelete = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){\n out << \" this->\" << idxName << \".erase(std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << \"this->col_\" << table.columns[col].name << \"[tid]\";\n });\n out << \"));\\n\";\n out << \" this->\" << idxName << \"[std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << \"this->col_\" << table.columns[col].name << \".back()\";\n });\n out << \")] = tid;\\n\";\n };\n if(!table.primaryKey.empty()) {\n generateIndexDelete(\"primary_key_idx\", table.primaryKey);\n }\n for(auto& idx : table.indices) {\n generateIndexDelete(\"idx_\" + idx.name, idx.columns);\n }\n out << \" }\\n\";\n \/\/TODO: parse\n out << \"}\\n\";\n }\n out << \"\/\/--------------------------------------------------\\n\"\n \"#endif\";\n}\n<commit_msg>schema generation: bug fix in delete_tuple<commit_after>#include \"Schema.hpp\"\n#include <sstream>\n\nstatic std::string translateType(const DataType& type) {\n std::ostringstream stream;\n if(type.typeTag == DataTypeTag::Integer) {\n stream << \"Integer\";\n } else if(type.typeTag == DataTypeTag::Numeric) {\n stream << \"Numeric<\" << (int) type.attributes.numeric.integerPlaces\n << \",\" << (int) type.attributes.numeric.decimalPlaces << \">\";\n } else if(type.typeTag == DataTypeTag::Char) {\n stream << \"Char<\" << (int) type.attributes.charLen << \">\";\n } else if(type.typeTag == DataTypeTag::VarChar) {\n stream << \"Varchar<\" << (int) type.attributes.charLen << \">\";\n } else if(type.typeTag == DataTypeTag::Date) {\n stream << \"Date\";\n } else if(type.typeTag == DataTypeTag::Timestamp) {\n stream << \"Timestamp\";\n }\n return stream.str();\n}\n\ntemplate<typename T, typename Callable>\nstatic void generateList(std::ostream& out, const std::vector<T>& elements, Callable cb, std::string seperator = \", \") {\n auto first = true;\n for(const auto& elem : elements) {\n if(!first) out << seperator;\n cb(out, elem);\n first = false;\n }\n}\n\nvoid Schema::generateCppCode(std::ostream& out) {\n out <<\n \"#ifndef H_Schema\\n\"\n \"#define H_Schema\\n\"\n \"#include <vector>\\n\"\n \"#include <map>\\n\"\n \"#include <unordered_map>\\n\"\n \"#include \\\"schema\/Types.hpp\\\"\\n\";\n for(auto& table : tables) {\n out << \"\/\/--------------------------------------------------\\n\"\n \"struct \" << table.name << \"_t {\\n\";\n \/\/ actual columns\n for(auto& column : table.columns) {\n out << \" std::vector<\" << translateType(column.type) << \"> col_\" << column.name << \";\\n\";\n }\n \/\/ primary key index\n if(!table.primaryKey.empty()) {\n if(table.primaryKeyPrefixIndexable) {\n out << \" std::map<std::tuple<\";\n } else {\n out << \" std::unordered_map<std::tuple<\";\n }\n generateList(out, table.primaryKey, [&](auto& out, auto& col){\n out << translateType(table.columns[col].type);\n });\n out << \">, size_t> primary_key_idx;\\n\";\n }\n \/\/ additional idcs\n for(auto& idx : table.indices) {\n if(idx.prefixIndexable) {\n out << \" std::map<std::tuple<\";\n } else {\n out << \" std::unordered_map<std::tuple<\";\n }\n generateList(out, idx.columns, [&](auto& out, auto& col){\n out << translateType(table.columns[col].type);\n });\n out << \">, size_t> idx_\" << idx.name << \";\\n\";\n }\n \/\/ insert\n out << \" void insert_tuple(\";\n generateList(out, table.columns, [&](auto& out, auto& column){\n out << translateType(column.type) << \" \" << column.name;\n });\n out << \") {\\n\";\n for(auto& column : table.columns) {\n out << \" this->col_\" << column.name << \".push_back(\" << column.name << \");\\n\";\n }\n auto generateIndexInsert = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){\n out << \" this->\" << idxName << \".insert(std::make_pair(std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << table.columns[col].name;\n });\n out << \"), this->col_\" << table.columns[0].name << \".size()))\\n\";\n };\n if(!table.primaryKey.empty()) {\n generateIndexInsert(\"primary_key_idx\", table.primaryKey);\n }\n for(auto& idx : table.indices) {\n generateIndexInsert(\"idx_\" + idx.name, idx.columns);\n }\n out << \" }\\n\";\n \/\/ delete\n out << \" void delete_tuple(size_t tid) {\\n\";\n auto generateIndexDelete = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){\n out << \" this->\" << idxName << \".erase(std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << \"this->col_\" << table.columns[col].name << \"[tid]\";\n });\n out << \"));\\n\";\n out << \" this->\" << idxName << \"[std::make_tuple(\";\n generateList(out, idxCols, [&](auto& out, auto& col){\n out << \"this->col_\" << table.columns[col].name << \".back()\";\n });\n out << \")] = tid;\\n\";\n };\n if(!table.primaryKey.empty()) {\n generateIndexDelete(\"primary_key_idx\", table.primaryKey);\n }\n for(auto& idx : table.indices) {\n generateIndexDelete(\"idx_\" + idx.name, idx.columns);\n }\n for(auto& column : table.columns) {\n out << \" this->col_\" << column.name << \"[tid] = this->col_\" << column.name << \".back();\\n\";\n out << \" this->col_\" << column.name << \".pop_back();\\n\";\n }\n out << \" }\\n\";\n \/\/TODO: parse\n out << \"}\\n\";\n }\n out << \"\/\/--------------------------------------------------\\n\"\n \"#endif\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Alexandru-Eugen Ichim\n * Willow Garage, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_\n#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_\n\n#include \"pcl\/keypoints\/smoothed_surfaces_keypoint.h\"\n#include <pcl\/kdtree\/kdtree_flann.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (PointCloudTConstPtr &cloud,\n PointCloudNTConstPtr &normals,\n KdTreePtr &kdtree,\n float &scale)\n{\n clouds_.push_back (cloud);\n cloud_normals_.push_back (normals);\n cloud_trees_.push_back (kdtree);\n scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()\n{\n clouds_.clear ();\n cloud_normals_.clear ();\n scales_.clear ();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)\n{\n \/\/ Calculate differences for each cloud\n std::vector<std::vector<float> > diffs (scales_.size ());\n\n \/\/ The cloud with the smallest scale has no differences\n std::vector<float> aux_diffs (input_->points.size (), 0.0f);\n diffs[scales_[0].second] = aux_diffs;\n\n for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)\n {\n diffs[scale_i].resize (input_->points.size ());\n size_t cloud_i = scales_[scale_i].second,\n cloud_i_minus_one = scales_[scale_i - 1].second;\n for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)\n diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (\n clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());\n\n \/\/ Setup kdtree for this cloud\n cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);\n }\n\n\n \/\/ Find minima and maxima in differences inside the input cloud\n tree_->setInputCloud (input_);\n for (int point_i = 0; point_i < input_->points.size (); ++point_i)\n {\n std::vector<int> nn_indices;\n std::vector<float> nn_distances;\n tree_->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);\n\n bool is_min = true, is_max = true;\n for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)\n if (*nn_it != point_i)\n {\n if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])\n is_max = false;\n else\n is_min = false;\n }\n\n \/\/ If the point is a local minimum\/maximum, check if it so over all the scales\n if (is_min || is_max)\n {\n bool passed = true;\n for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)\n {\n size_t cloud_i = scales_[scale_i].second;\n \/\/ skip input cloud\n if (cloud_i == clouds_.size ())\n continue;\n\n nn_indices.clear (); nn_distances.clear ();\n cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);\n\n bool is_min_other_scale = true, is_max_other_scale = true;\n for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)\n if (*nn_it != point_i)\n {\n if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])\n is_max_other_scale = false;\n else\n is_min_other_scale = false;\n }\n\n if ( (is_min == true && is_min_other_scale == false) || (is_max == true && is_max_other_scale == false) )\n {\n passed = false;\n break;\n }\n }\n\n \/\/ check if point was minimum\/maximum over all the scales\n if (passed)\n output.points.push_back (input_->points[point_i]);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> bool\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()\n{\n if ( !PCLBase<PointT>::initCompute ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] PCLBase::initCompute failed\\n\");\n return false;\n }\n\n if (!normals_)\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\\n\");\n return false;\n }\n if (clouds_.size () == 0)\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\\n\");\n return false;\n }\n\n if (input_->points.size () != normals_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\\n\");\n return false;\n }\n\n for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)\n {\n if (clouds_[cloud_i]->points.size () != input_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\\n\", cloud_i);\n return false;\n }\n\n if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\\n\", cloud_i);\n return false;\n }\n }\n\n \/\/ Add the input cloud as the last index\n scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));\n clouds_.push_back (input_);\n cloud_normals_.push_back (normals_);\n \/\/ Sort the clouds by their scales\n sort (scales_.begin (), scales_.end (), compareScalesFunction);\n\n \/\/ Find the index of the input after sorting\n for (size_t i = 0; i < scales_.size (); ++i)\n if (scales_[i].second == scales_.size () - 1)\n {\n input_index_ = i;\n break;\n }\n\n return true;\n}\n\n\n#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;\n\n\n#endif \/* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ *\/\n<commit_msg>fixed a compiler warning<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Alexandru-Eugen Ichim\n * Willow Garage, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_\n#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_\n\n#include \"pcl\/keypoints\/smoothed_surfaces_keypoint.h\"\n#include <pcl\/kdtree\/kdtree_flann.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (PointCloudTConstPtr &cloud,\n PointCloudNTConstPtr &normals,\n KdTreePtr &kdtree,\n float &scale)\n{\n clouds_.push_back (cloud);\n cloud_normals_.push_back (normals);\n cloud_trees_.push_back (kdtree);\n scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()\n{\n clouds_.clear ();\n cloud_normals_.clear ();\n scales_.clear ();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> void\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)\n{\n \/\/ Calculate differences for each cloud\n std::vector<std::vector<float> > diffs (scales_.size ());\n\n \/\/ The cloud with the smallest scale has no differences\n std::vector<float> aux_diffs (input_->points.size (), 0.0f);\n diffs[scales_[0].second] = aux_diffs;\n\n for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)\n {\n diffs[scale_i].resize (input_->points.size ());\n size_t cloud_i = scales_[scale_i].second,\n cloud_i_minus_one = scales_[scale_i - 1].second;\n for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)\n diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (\n clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());\n\n \/\/ Setup kdtree for this cloud\n cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);\n }\n\n\n \/\/ Find minima and maxima in differences inside the input cloud\n tree_->setInputCloud (input_);\n for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)\n {\n std::vector<int> nn_indices;\n std::vector<float> nn_distances;\n tree_->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);\n\n bool is_min = true, is_max = true;\n for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)\n if (*nn_it != point_i)\n {\n if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])\n is_max = false;\n else\n is_min = false;\n }\n\n \/\/ If the point is a local minimum\/maximum, check if it so over all the scales\n if (is_min || is_max)\n {\n bool passed = true;\n for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)\n {\n size_t cloud_i = scales_[scale_i].second;\n \/\/ skip input cloud\n if (cloud_i == clouds_.size ())\n continue;\n\n nn_indices.clear (); nn_distances.clear ();\n cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);\n\n bool is_min_other_scale = true, is_max_other_scale = true;\n for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)\n if (*nn_it != point_i)\n {\n if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])\n is_max_other_scale = false;\n else\n is_min_other_scale = false;\n }\n\n if ( (is_min == true && is_min_other_scale == false) || (is_max == true && is_max_other_scale == false) )\n {\n passed = false;\n break;\n }\n }\n\n \/\/ check if point was minimum\/maximum over all the scales\n if (passed)\n output.points.push_back (input_->points[point_i]);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT, typename PointNT> bool\npcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()\n{\n if ( !PCLBase<PointT>::initCompute ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] PCLBase::initCompute failed\\n\");\n return false;\n }\n\n if (!normals_)\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\\n\");\n return false;\n }\n if (clouds_.size () == 0)\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\\n\");\n return false;\n }\n\n if (input_->points.size () != normals_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\\n\");\n return false;\n }\n\n for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)\n {\n if (clouds_[cloud_i]->points.size () != input_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\\n\", cloud_i);\n return false;\n }\n\n if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())\n {\n PCL_ERROR (\"[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\\n\", cloud_i);\n return false;\n }\n }\n\n \/\/ Add the input cloud as the last index\n scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));\n clouds_.push_back (input_);\n cloud_normals_.push_back (normals_);\n \/\/ Sort the clouds by their scales\n sort (scales_.begin (), scales_.end (), compareScalesFunction);\n\n \/\/ Find the index of the input after sorting\n for (size_t i = 0; i < scales_.size (); ++i)\n if (scales_[i].second == scales_.size () - 1)\n {\n input_index_ = i;\n break;\n }\n\n return true;\n}\n\n\n#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;\n\n\n#endif \/* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file FactorTable.hpp\n\/\/\/ @brief The FactorTable class is used to save memory. It combines\n\/\/\/ the lpf[n] (least prime factor) and mu[n] (Möbius function)\n\/\/\/ lookup tables into a single factor_table[n] which\n\/\/\/ furthermore only contains entries for numbers which are\n\/\/\/ not divisible by 2, 3, 5 and 7.\n\/\/\/ The factor table concept has first been devised and\n\/\/\/ implemented by Christian Bau in 2003.\n\/\/\/\n\/\/\/ FactorTable.lpf(index) is equal to (n = get_number(index)):\n\/\/\/\n\/\/\/ * 0 if moebius(n) = 0\n\/\/\/ * lpf if !is_prime(n) && moebius(n) = -1\n\/\/\/ * lpf-1 if !is_prime(n) && moebius(n) = 1\n\/\/\/ * n if is_prime(n) && n < T_MAX\n\/\/\/ * T_MAX if is_prime(n) && n > T_MAX\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef FACTORTABLE_HPP\n#define FACTORTABLE_HPP\n\n#include <primecount.hpp>\n#include <pmath.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <limits>\n#include <stdint.h>\n#include <vector>\n\nnamespace primecount {\n\n\/\/\/ AbstractFactorTable contains static FactorTable\n\/\/\/ data and it used to convert:\n\/\/\/ 1) A number into a FactorTable index.\n\/\/\/ 2) A FactorTable index into a number.\n\/\/\/\nclass AbstractFactorTable\n{\nprotected:\n virtual ~AbstractFactorTable() { }\n\npublic:\n \/\/\/ @pre number > 0\n static void to_index(int64_t* number)\n {\n assert(*number > 0);\n *number = get_index(*number);\n }\n\n \/\/\/ @pre number > 0\n static int64_t get_index(int64_t number)\n {\n assert(number > 0);\n int64_t quotient = number \/ 210;\n int64_t remainder = number % 210;\n return 48 * quotient + indexes_[remainder];\n }\n\n static int64_t get_number(int64_t index)\n {\n int64_t quotient = index \/ 48;\n int64_t remainder = index % 48;\n return 210 * quotient + numbers_[remainder];\n }\n\nprivate:\n static const uint8_t numbers_[48];\n static const int8_t indexes_[210];\n};\n\ntemplate <typename T>\nclass FactorTable : public AbstractFactorTable\n{\npublic:\n \/\/\/ @param y factor numbers <= y\n FactorTable(int64_t y)\n {\n if (y > max())\n throw primecount_error(\"y must be <= FactorTable::max().\");\n y = std::max<int64_t>(8, y);\n T T_MAX = std::numeric_limits<T>::max();\n init_factors(y, T_MAX);\n }\n\n static int64_t max()\n {\n int64_t T_MAX = std::numeric_limits<T>::max();\n return ipow(T_MAX - 1, 2) - 1;\n }\n\n \/\/\/ Get the least prime factor (lpf) of the number get_number(index).\n \/\/\/ The result is different from lpf in some situations:\n \/\/\/ 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.\n \/\/\/ 2) lpf(index) returns lpf minus one if mu(index) == 1.\n \/\/\/ 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.\n \/\/\/\n int64_t lpf(int64_t index) const\n {\n return factors_[index];\n }\n\n \/\/\/ Get the Möbius function value of the number get_number(index).\n \/\/\/ For performance reasons mu(index) == 0 is not supported.\n \/\/\/ @pre mu(index) != 0 (i.e. lpf(index) != 0)\n \/\/\/\n int64_t mu(int64_t index) const\n {\n assert(lpf(index) != 0);\n return (factors_[index] & 1) ? -1 : 1;\n }\n\nprivate:\n void init_factors(int64_t y, T T_MAX)\n {\n int64_t sqrty = isqrt(y);\n factors_.resize(get_index(y) + 1, T_MAX);\n factors_[0] = T_MAX - 1;\n\n for (size_t i = 1; i < factors_.size(); i++)\n {\n if (factors_[i] == T_MAX)\n {\n int64_t prime = get_number(i);\n int64_t multiple = prime * get_number(1);\n\n if (prime < T_MAX)\n factors_[i] = (T) prime;\n else if (multiple > y)\n break;\n\n for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))\n {\n int64_t index = get_index(multiple);\n \/\/ prime is the smallest factor of multiple\n if (factors_[index] == T_MAX)\n factors_[index] = (T) prime;\n \/\/ the least significant bit indicates whether multiple has\n \/\/ an even (0) or odd (1) number of prime factors\n else if (factors_[index] != 0)\n factors_[index] ^= 1;\n }\n\n \/\/ Möbius function is 0 if n has a squared prime factor\n if (prime <= sqrty)\n {\n multiple = prime * prime;\n for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))\n factors_[get_index(multiple)] = 0;\n }\n }\n }\n }\n\n std::vector<T> factors_;\n};\n\n} \/\/ namespace\n\n#endif\n<commit_msg>Update comment<commit_after>\/\/\/\n\/\/\/ @file FactorTable.hpp\n\/\/\/ @brief The FactorTable class is used to save memory. It combines\n\/\/\/ the lpf[n] (least prime factor) and mu[n] (Möbius function)\n\/\/\/ lookup tables into a single factors_[n] table which\n\/\/\/ furthermore only contains entries for numbers which are\n\/\/\/ not divisible by 2, 3, 5 and 7.\n\/\/\/ The factor table concept has first been devised and\n\/\/\/ implemented by Christian Bau in 2003.\n\/\/\/\n\/\/\/ FactorTable.lpf(index) is equal to (n = get_number(index)):\n\/\/\/\n\/\/\/ * 0 if moebius(n) = 0\n\/\/\/ * lpf if !is_prime(n) && moebius(n) = -1\n\/\/\/ * lpf-1 if !is_prime(n) && moebius(n) = 1\n\/\/\/ * n if is_prime(n) && n < T_MAX\n\/\/\/ * T_MAX if is_prime(n) && n > T_MAX\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef FACTORTABLE_HPP\n#define FACTORTABLE_HPP\n\n#include <primecount.hpp>\n#include <pmath.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <limits>\n#include <stdint.h>\n#include <vector>\n\nnamespace primecount {\n\n\/\/\/ AbstractFactorTable contains static FactorTable\n\/\/\/ data and it used to convert:\n\/\/\/ 1) A number into a FactorTable index.\n\/\/\/ 2) A FactorTable index into a number.\n\/\/\/\nclass AbstractFactorTable\n{\nprotected:\n virtual ~AbstractFactorTable() { }\n\npublic:\n \/\/\/ @pre number > 0\n static void to_index(int64_t* number)\n {\n assert(*number > 0);\n *number = get_index(*number);\n }\n\n \/\/\/ @pre number > 0\n static int64_t get_index(int64_t number)\n {\n assert(number > 0);\n int64_t quotient = number \/ 210;\n int64_t remainder = number % 210;\n return 48 * quotient + indexes_[remainder];\n }\n\n static int64_t get_number(int64_t index)\n {\n int64_t quotient = index \/ 48;\n int64_t remainder = index % 48;\n return 210 * quotient + numbers_[remainder];\n }\n\nprivate:\n static const uint8_t numbers_[48];\n static const int8_t indexes_[210];\n};\n\ntemplate <typename T>\nclass FactorTable : public AbstractFactorTable\n{\npublic:\n \/\/\/ @param y factor numbers <= y\n FactorTable(int64_t y)\n {\n if (y > max())\n throw primecount_error(\"y must be <= FactorTable::max().\");\n y = std::max<int64_t>(8, y);\n T T_MAX = std::numeric_limits<T>::max();\n init_factors(y, T_MAX);\n }\n\n static int64_t max()\n {\n int64_t T_MAX = std::numeric_limits<T>::max();\n return ipow(T_MAX - 1, 2) - 1;\n }\n\n \/\/\/ Get the least prime factor (lpf) of the number get_number(index).\n \/\/\/ The result is different from lpf in some situations:\n \/\/\/ 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.\n \/\/\/ 2) lpf(index) returns lpf minus one if mu(index) == 1.\n \/\/\/ 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.\n \/\/\/\n int64_t lpf(int64_t index) const\n {\n return factors_[index];\n }\n\n \/\/\/ Get the Möbius function value of the number get_number(index).\n \/\/\/ For performance reasons mu(index) == 0 is not supported.\n \/\/\/ @pre mu(index) != 0 (i.e. lpf(index) != 0)\n \/\/\/\n int64_t mu(int64_t index) const\n {\n assert(lpf(index) != 0);\n return (factors_[index] & 1) ? -1 : 1;\n }\n\nprivate:\n void init_factors(int64_t y, T T_MAX)\n {\n int64_t sqrty = isqrt(y);\n factors_.resize(get_index(y) + 1, T_MAX);\n factors_[0] = T_MAX - 1;\n\n for (size_t i = 1; i < factors_.size(); i++)\n {\n if (factors_[i] == T_MAX)\n {\n int64_t prime = get_number(i);\n int64_t multiple = prime * get_number(1);\n\n if (prime < T_MAX)\n factors_[i] = (T) prime;\n else if (multiple > y)\n break;\n\n for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))\n {\n int64_t index = get_index(multiple);\n \/\/ prime is the smallest factor of multiple\n if (factors_[index] == T_MAX)\n factors_[index] = (T) prime;\n \/\/ the least significant bit indicates whether multiple has\n \/\/ an even (0) or odd (1) number of prime factors\n else if (factors_[index] != 0)\n factors_[index] ^= 1;\n }\n\n \/\/ Möbius function is 0 if n has a squared prime factor\n if (prime <= sqrty)\n {\n multiple = prime * prime;\n for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))\n factors_[get_index(multiple)] = 0;\n }\n }\n }\n }\n\n std::vector<T> factors_;\n};\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"pathos\/core_minimal.h\"\n#include \"pathos\/render_minimal.h\"\n\n#include \"daeloader.h\"\n#include \"skinned_mesh.h\"\n#include <time.h>\n\nusing namespace std;\nusing namespace pathos;\n\n\/* ------------------------------------------------------------------------\n\n\t\t\t\t\t\t\t\tCONFIGURATION\n\n------------------------------------------------------------------------- *\/\n#define DAE_MODEL_ID 2\n#define LOAD_SECOND_DAE_MODEL 0\n\nconstexpr int32 WINDOW_WIDTH = 1920;\nconstexpr int32 WINDOW_HEIGHT = 1080;\nconstexpr char* WINDOW_TITLE = \"Test: Skeletal Animation\";\nconstexpr float FOVY = 60.0f;\nconst glm::vec3 CAMERA_POSITION = glm::vec3(0.0f, 0.0f, 100.0f);\nconstexpr float CAMERA_Z_NEAR = 1.0f;\nconstexpr float CAMERA_Z_FAR = 10000.0f;\n\n\/* ------------------------------------------------------------------------\n\n\t\t\t\t\t\t\t\tPROGRAM CODE\n\n------------------------------------------------------------------------- *\/\n\nCamera* cam;\nScene scene;\n\tDirectionalLight *dlight;\n\tPointLight *plight;\n\tMesh *model, *model2;\n\tSkinnedMesh *daeModel;\n\tSkinnedMesh *daeModel2;\n\nvoid loadDAE();\nvoid setupScene();\nvoid tick();\n\nint main(int argc, char** argv) {\n\tEngineConfig conf;\n\tconf.windowWidth = WINDOW_WIDTH;\n\tconf.windowHeight = WINDOW_HEIGHT;\n\tconf.title = WINDOW_TITLE;\n\tconf.rendererType = ERendererType::Deferred;\n\tconf.tick = tick;\n\tEngine::init(argc, argv, conf);\n\n\tconst float ar = static_cast<float>(conf.windowWidth) \/ static_cast<float>(conf.windowHeight);\n\tcam = new Camera(new PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR));\n\tcam->move(CAMERA_POSITION);\n\n\tloadDAE();\n\tsetupScene();\n\n\tgEngine->setWorld(&scene, cam);\n\tgEngine->start();\n\n\treturn 0;\n}\n\nvoid loadDAE() {\n\tbool invertWinding = false;\n#if DAE_MODEL_ID == 0\n\tconst std::string dir = \"models\/LOL_ashe\/\";\n\tconst std::string model = dir + \"Ashe.dae\";\n#elif DAE_MODEL_ID == 1\n\tconst std::string dir = \"models\/LOL_project_ashe\/\";\n\tconst std::string model = dir + \"Project_Ashe.dae\";\n\tinvertWinding = true;\n#else\n\tconst std::string dir = \"models\/animtest\/\";\n\tconst std::string model = dir + \"animtest.dae\";\n#endif\n\n\tDAELoader loader(model.c_str(), dir.c_str(), aiProcessPreset_TargetRealtime_MaxQuality, invertWinding);\n\tif (loader.getMesh()) {\n\t\tdaeModel = dynamic_cast<SkinnedMesh*>(loader.getMesh());\n\t\tdaeModel->getTransform().appendScale(10.0f);\n#if DAE_MODEL_ID == 2\n\t\tdaeModel->getTransform().appendScale(0.3f);\n\t\tdaeModel->getTransform().appendRotation(glm::radians(90.0f), glm::vec3(0, 1, 0));\n#endif\n\t\tdaeModel->getTransform().appendMove(0, 0, 50);\n\t\tscene.add(daeModel);\n\t} else {\n\t\tLOG(LogError, \"Failed to load model: %s\", model.c_str());\n\t}\n\n#if LOAD_SECOND_DAE_MODEL\n\tconst std::string dir2 = \"models\/Sonic\/\";\n\tconst std::string model2 = dir2 + \"Sonic.dae\";\n\tDAELoader loader2(model2.c_str(), dir2.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);\n\tdaeModel2 = dynamic_cast<SkinnedMesh*>(loader2.getMesh());\n\tdaeModel2->getTransform().appendScale(10.0f);\n\tdaeModel2->getTransform().appendMove(20.0f, 0.0f, 50.0f);\n\tscene.add(daeModel2);\n#endif\n}\n\nvoid setupScene() {\n\tplight = new PointLight(glm::vec3(0, 0, 0), glm::vec3(1.0f));\n\tdlight = new DirectionalLight(glm::vec3(0, 0, -1), glm::vec3(1.0f));\n\tscene.add(plight);\n\tscene.add(dlight);\n\n\tsrand(static_cast<unsigned int>(time(NULL)));\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create materials\n\t\/\/---------------------------------------------------------------------------------------\n\tconst char* cubeImgName[6] = {\n\t\t\"cubemap1\/pos_x.jpg\", \"cubemap1\/neg_x.jpg\",\n\t\t\"cubemap1\/pos_y.jpg\", \"cubemap1\/neg_y.jpg\",\n\t\t\"cubemap1\/pos_z.jpg\", \"cubemap1\/neg_z.jpg\"\n\t};\n\tFIBITMAP* cubeImg[6];\n\tfor (int i = 0; i < 6; i++) cubeImg[i] = loadImage(cubeImgName[i]);\n\tGLuint cubeTexture = loadCubemapTexture(cubeImg);\n\n\tGLuint tex = loadTexture(loadImage(\"154.jpg\"), true, true);\n\tGLuint tex_norm = loadTexture(loadImage(\"154_norm.jpg\"), true, false);\n\n\tauto material_texture = new TextureMaterial(tex);\n\tauto material_color = new ColorMaterial;\n\t{\n\t\tauto color = static_cast<ColorMaterial*>(material_color);\n\t\tcolor->setAlbedo(1.0f, 1.0f, 1.0f);\n\t\tcolor->setMetallic(0.6f);\n\t\tcolor->setRoughness(0.5f);\n\t}\n\tauto material_cubemap = new CubeEnvMapMaterial(cubeTexture);\n\tauto material_wireframe = new WireframeMaterial(0.0f, 1.0f, 1.0f, 0.3f);\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create geometries\n\t\/\/---------------------------------------------------------------------------------------\n\t\n\tauto geom_sphere_big = new SphereGeometry(15.0f, 30);\n\tauto geom_sphere = new SphereGeometry(5.0f, 30);\n\tauto geom_plane = new PlaneGeometry(10.f, 10.f);\n\tauto geom_cube = new CubeGeometry(glm::vec3(5.0f));\n\n\tgeom_sphere->calculateTangentBasis();\n\tgeom_sphere_big->calculateTangentBasis();\n\tgeom_plane->calculateTangentBasis();\n\tgeom_cube->calculateTangentBasis();\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create meshes\n\t\/\/---------------------------------------------------------------------------------------\n\n\tfor (int32_t i = 0; i < 8; ++i) {\n\t\tfor (int32_t j = 0; j < 4; ++j) {\n\t\t\tMesh* cube = new Mesh(geom_cube, material_color);\n\t\t\tglm::vec3 p0(-50.0f, 50.0f, -50.0f);\n\t\t\tfloat e = (rand() % 256) \/ 255.0f;\n\t\t\tfloat x = (rand() % 256) \/ 255.0f;\n\t\t\tfloat y = (rand() % 256) \/ 255.0f;\n\t\t\tfloat z = (rand() % 256) \/ 255.0f;\n\t\t\tcube->getTransform().appendRotation(e * 60.0f, glm::vec3(x, y, z));\n\t\t\tcube->getTransform().appendMove(p0 + glm::vec3(i * 15.0f, -j * 15.0f, 0.0f));\n\t\t\tscene.add(cube);\n\t\t}\n\t}\n\n\tmodel = new Mesh(geom_sphere_big, material_texture);\n\tmodel->getTransform().appendMove(-40, 0, 0);\n\n\tmodel2 = new Mesh(geom_sphere, material_color);\n\tmodel2->getTransform().appendScale(10.0f);\n\tmodel2->getTransform().appendMove(0, 50, -200);\n\n\tscene.add(model);\n\tscene.add(model2);\n\tscene.sky = new Skybox(cubeTexture);\n\tscene.godRaySource = model2;\n}\n\nvoid tick() {\n\tif (gConsole->isVisible() == false) {\n\t\tfloat speedX = 1.0f, speedY = 1.0f;\n\t\tfloat dx = gEngine->isDown('a') ? -speedX : gEngine->isDown('d') ? speedX : 0.0f;\n\t\tfloat dz = gEngine->isDown('w') ? -speedY : gEngine->isDown('s') ? speedY : 0.0f;\n\t\tfloat rotY = gEngine->isDown('q') ? -0.5f : gEngine->isDown('e') ? 0.5f : 0.0f;\n\t\tfloat rotX = gEngine->isDown('z') ? -0.5f : gEngine->isDown('x') ? 0.5f : 0.0f;\n\t\tcam->move(glm::vec3(dx, 0, dz));\n\t\tcam->rotateY(rotY);\n\t\tcam->rotateX(rotX);\n\t}\n\n\tmodel->getTransform().appendMove(0, 20, 0);\n\tmodel->getTransform().appendRotation(0.01f, glm::vec3(0, 0.5, 1));\n\tmodel->getTransform().appendMove(0, -20, 0);\n\n#if DAE_MODEL_ID == 2\n\tstatic double time = 0.0;\n\ttime += 0.01;\n\tif (time > 1.0) time = 0.0;\n\tdaeModel->updateAnimation(0, time);\n\tdaeModel->updateSoftwareSkinning();\n\tdaeModel->getTransform().prependRotation(0.003f, glm::vec3(0, 1, 0));\n#endif\n}\n<commit_msg>Fix build error for Test_SkeletalAnimation<commit_after>#include \"pathos\/core_minimal.h\"\n#include \"pathos\/render_minimal.h\"\n\n#include \"daeloader.h\"\n#include \"skinned_mesh.h\"\n#include <time.h>\n\nusing namespace std;\nusing namespace pathos;\n\n\/* ------------------------------------------------------------------------\n\n\t\t\t\t\t\t\t\tCONFIGURATION\n\n------------------------------------------------------------------------- *\/\n#define DAE_MODEL_ID 2\n#define LOAD_SECOND_DAE_MODEL 0\n\nconstexpr int32 WINDOW_WIDTH = 1920;\nconstexpr int32 WINDOW_HEIGHT = 1080;\nconstexpr char* WINDOW_TITLE = \"Test: Skeletal Animation\";\nconstexpr float FOVY = 60.0f;\nconst glm::vec3 CAMERA_POSITION = glm::vec3(0.0f, 0.0f, 100.0f);\nconstexpr float CAMERA_Z_NEAR = 1.0f;\nconstexpr float CAMERA_Z_FAR = 10000.0f;\n\n\/* ------------------------------------------------------------------------\n\n\t\t\t\t\t\t\t\tPROGRAM CODE\n\n------------------------------------------------------------------------- *\/\n\nCamera* cam;\nScene scene;\n\tDirectionalLight *dlight;\n\tPointLight *plight;\n\tMesh *model, *model2;\n\tSkinnedMesh *daeModel;\n\tSkinnedMesh *daeModel2;\n\nvoid loadDAE();\nvoid setupScene();\nvoid tick(float deltaSeconds);\n\nint main(int argc, char** argv) {\n\tEngineConfig conf;\n\tconf.windowWidth = WINDOW_WIDTH;\n\tconf.windowHeight = WINDOW_HEIGHT;\n\tconf.title = WINDOW_TITLE;\n\tconf.rendererType = ERendererType::Deferred;\n\tconf.tick = tick;\n\tEngine::init(argc, argv, conf);\n\n\tconst float ar = static_cast<float>(conf.windowWidth) \/ static_cast<float>(conf.windowHeight);\n\tcam = new Camera(new PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR));\n\tcam->move(CAMERA_POSITION);\n\n\tloadDAE();\n\tsetupScene();\n\n\tgEngine->setWorld(&scene, cam);\n\tgEngine->start();\n\n\treturn 0;\n}\n\nvoid loadDAE() {\n\tbool invertWinding = false;\n#if DAE_MODEL_ID == 0\n\tconst std::string dir = \"models\/LOL_ashe\/\";\n\tconst std::string model = dir + \"Ashe.dae\";\n#elif DAE_MODEL_ID == 1\n\tconst std::string dir = \"models\/LOL_project_ashe\/\";\n\tconst std::string model = dir + \"Project_Ashe.dae\";\n\tinvertWinding = true;\n#else\n\tconst std::string dir = \"models\/animtest\/\";\n\tconst std::string model = dir + \"animtest.dae\";\n#endif\n\n\tDAELoader loader(model.c_str(), dir.c_str(), aiProcessPreset_TargetRealtime_MaxQuality, invertWinding);\n\tif (loader.getMesh()) {\n\t\tdaeModel = dynamic_cast<SkinnedMesh*>(loader.getMesh());\n\t\tdaeModel->getTransform().setScale(10.0f);\n#if DAE_MODEL_ID == 2\n\t\tdaeModel->getTransform().setScale(5.0f);\n\t\tdaeModel->getTransform().setRotation(glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f));\n#endif\n\t\tdaeModel->getTransform().setLocation(0.0f, 0.0f, 0.0f);\n\t\tscene.add(daeModel);\n\t} else {\n\t\tLOG(LogError, \"Failed to load model: %s\", model.c_str());\n\t}\n\n#if LOAD_SECOND_DAE_MODEL\n\tconst std::string dir2 = \"models\/Sonic\/\";\n\tconst std::string model2 = dir2 + \"Sonic.dae\";\n\tDAELoader loader2(model2.c_str(), dir2.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);\n\tdaeModel2 = dynamic_cast<SkinnedMesh*>(loader2.getMesh());\n\tdaeModel2->getTransform().appendScale(10.0f);\n\tdaeModel2->getTransform().appendMove(20.0f, 0.0f, 50.0f);\n\tscene.add(daeModel2);\n#endif\n}\n\nvoid setupScene() {\n\tplight = new PointLight(glm::vec3(0, 0, 0), glm::vec3(1.0f));\n\tdlight = new DirectionalLight(glm::vec3(0, 0, -1), glm::vec3(1.0f));\n\tscene.add(plight);\n\tscene.add(dlight);\n\n\tsrand(static_cast<unsigned int>(time(NULL)));\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create materials\n\t\/\/---------------------------------------------------------------------------------------\n\tconst char* cubeImgName[6] = {\n\t\t\"cubemap1\/pos_x.jpg\", \"cubemap1\/neg_x.jpg\",\n\t\t\"cubemap1\/pos_y.jpg\", \"cubemap1\/neg_y.jpg\",\n\t\t\"cubemap1\/pos_z.jpg\", \"cubemap1\/neg_z.jpg\"\n\t};\n\tFIBITMAP* cubeImg[6];\n\tfor (int i = 0; i < 6; i++) cubeImg[i] = loadImage(cubeImgName[i]);\n\tGLuint cubeTexture = loadCubemapTexture(cubeImg);\n\n\tGLuint tex = loadTexture(loadImage(\"154.jpg\"), true, true);\n\tGLuint tex_norm = loadTexture(loadImage(\"154_norm.jpg\"), true, false);\n\n\tauto material_texture = new TextureMaterial(tex);\n\tauto material_color = new ColorMaterial;\n\t{\n\t\tauto color = static_cast<ColorMaterial*>(material_color);\n\t\tcolor->setAlbedo(1.0f, 1.0f, 1.0f);\n\t\tcolor->setMetallic(0.6f);\n\t\tcolor->setRoughness(0.5f);\n\t}\n\tauto material_cubemap = new CubeEnvMapMaterial(cubeTexture);\n\tauto material_wireframe = new WireframeMaterial(0.0f, 1.0f, 1.0f, 0.3f);\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create geometries\n\t\/\/---------------------------------------------------------------------------------------\n\t\n\tauto geom_sphere_big = new SphereGeometry(15.0f, 30);\n\tauto geom_sphere = new SphereGeometry(5.0f, 30);\n\tauto geom_plane = new PlaneGeometry(10.f, 10.f);\n\tauto geom_cube = new CubeGeometry(glm::vec3(5.0f));\n\n\tgeom_sphere->calculateTangentBasis();\n\tgeom_sphere_big->calculateTangentBasis();\n\tgeom_plane->calculateTangentBasis();\n\tgeom_cube->calculateTangentBasis();\n\n\t\/\/---------------------------------------------------------------------------------------\n\t\/\/ create meshes\n\t\/\/---------------------------------------------------------------------------------------\n\n\tfor (int32_t i = 0; i < 8; ++i) {\n\t\tfor (int32_t j = 0; j < 4; ++j) {\n\t\t\tMesh* cube = new Mesh(geom_cube, material_color);\n\t\t\tglm::vec3 p0(-50.0f, 50.0f, -50.0f);\n\t\t\tfloat e = (rand() % 256) \/ 255.0f;\n\t\t\tfloat x = (rand() % 256) \/ 255.0f;\n\t\t\tfloat y = (rand() % 256) \/ 255.0f;\n\t\t\tfloat z = (rand() % 256) \/ 255.0f;\n\t\t\tcube->getTransform().setRotation(e * 60.0f, glm::vec3(x, y, z));\n\t\t\tcube->getTransform().setLocation(p0 + glm::vec3(i * 15.0f, -j * 15.0f, 0.0f));\n\t\t\tscene.add(cube);\n\t\t}\n\t}\n\n\tmodel = new Mesh(geom_sphere_big, material_texture);\n\tmodel->getTransform().setLocation(-40, 0, 0);\n\n\tmodel2 = new Mesh(geom_sphere, material_color);\n\tmodel2->getTransform().setScale(10.0f);\n\tmodel2->getTransform().setLocation(0, 50, -200);\n\n\tscene.add(model);\n\tscene.add(model2);\n\tscene.sky = new Skybox(cubeTexture);\n\tscene.godRaySource = model2;\n}\n\nvoid tick(float deltaSeconds) {\n\tif (gConsole->isVisible() == false) {\n\t\tfloat speedX = 1.0f, speedY = 1.0f;\n\t\tfloat dx = gEngine->isDown('a') ? -speedX : gEngine->isDown('d') ? speedX : 0.0f;\n\t\tfloat dz = gEngine->isDown('w') ? -speedY : gEngine->isDown('s') ? speedY : 0.0f;\n\t\tfloat rotY = gEngine->isDown('q') ? -0.5f : gEngine->isDown('e') ? 0.5f : 0.0f;\n\t\tfloat rotX = gEngine->isDown('z') ? -0.5f : gEngine->isDown('x') ? 0.5f : 0.0f;\n\t\tcam->move(glm::vec3(dx, 0, dz));\n\t\tcam->rotateY(rotY);\n\t\tcam->rotateX(rotX);\n\t}\n\n\tmodel->getTransform().setLocation(0, 20, 0);\n\tmodel->getTransform().setRotation(0.01f, glm::vec3(0, 0.5, 1));\n\tmodel->getTransform().setLocation(0, -20, 0);\n\n#if DAE_MODEL_ID == 2\n\tstatic double time = 0.0;\n\ttime += deltaSeconds;\n\tif (time > 1.0) time = 0.0;\n\tdaeModel->updateAnimation(0, time);\n\tdaeModel->updateSoftwareSkinning();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <memory>\n#include <jsapi.h>\n#ifndef MOZJS_MAJOR_VERSION\n#include <jsversion.h>\n#endif\n#include <QtCore>\n\n#include \"webqq_calljs.hpp\"\n\nstatic JSClass global_class = {\n\t\"global\",\n\tJSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,\n\tJS_PropertyStub,\n#ifdef MOZJS_MAJOR_VERSION\n\tJS_DeletePropertyStub,\n#else\n\tJS_PropertyStub,\n#endif\n\tJS_PropertyStub,\n\tJS_StrictPropertyStub,\n\tJS_EnumerateStub,\n\tJS_ResolveStub,\n\tJS_ConvertStub,\n\tNULL,\n\tJSCLASS_NO_OPTIONAL_MEMBERS\n};\n\nstd::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)\n{\n#if MOZJS_MAJOR_VERSION >= 24\n\tstd::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};\n#else\n\tstd::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};\n#endif\n\tstd::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};\n\n\tJS_SetOptions(jsctx.get(), JS_GetOptions(jsctx.get()) |JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);\n\n#if JS_VERSION == 185\n\tJSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);\n#else\n JS::CompartmentOptions options;\n options.setVersion(JSVERSION_LATEST);\n\n\tJSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL, options);\n JSAutoCompartment ac(jsctx.get(), global_object);\n#endif\n JS_SetGlobalObject(jsctx.get(), global_object);\n\n\tJS_InitStandardClasses(jsctx.get(), global_object);\n\n#if JS_VERSION == 185\n\tJSObject * script\n#else\n\tJSScript * script\n#endif\n\t= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length, helper_file.c_str(), 0);\n\n\tJS_ExecuteScript(jsctx.get(), global_object, script, NULL);\n\n\tjsval res;\n\tstd::vector<jsval> argv;\n\tchar* res_;\n\n\tfor (auto _a : args)\n\t{\n\t\tJSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());\n\t\targv.push_back(STRING_TO_JSVAL(js_arg));\n\t}\n\n\tJS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);\n\n\tres_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));\n\tstd::string ret = res_;\n\tJS_free(jsctx.get(),res_);\n\treturn ret;\n\n}\n\n\nstd::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)\n{\n\tQFile helperfile(helper_file.c_str());\n\n\thelperfile.open(QIODevice::ReadOnly);\n\n\tauto js_content = helperfile.readAll();\n\n\treturn call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);\n\n}\n\n<commit_msg>tweak preprocessor<commit_after>\n#include <memory>\n#include <jsapi.h>\n#ifndef MOZJS_MAJOR_VERSION\n#include <jsversion.h>\n#endif\n#include <QtCore>\n\n#include \"webqq_calljs.hpp\"\n\nstatic JSClass global_class = {\n\t\"global\",\n\tJSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,\n\tJS_PropertyStub,\n#ifdef MOZJS_MAJOR_VERSION\n\tJS_DeletePropertyStub,\n#else\n\tJS_PropertyStub,\n#endif\n\tJS_PropertyStub,\n\tJS_StrictPropertyStub,\n\tJS_EnumerateStub,\n\tJS_ResolveStub,\n\tJS_ConvertStub,\n\tNULL,\n\tJSCLASS_NO_OPTIONAL_MEMBERS\n};\n\nstd::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)\n{\n#if MOZJS_MAJOR_VERSION >= 24\n\tstd::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};\n#else\n\tstd::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};\n#endif\n\tstd::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};\n\n\tJS_SetOptions(jsctx.get(), JS_GetOptions(jsctx.get()) |JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);\n\n#ifdef \tMOZJS_MAJOR_VERSION\n JS::CompartmentOptions options;\n options.setVersion(JSVERSION_LATEST);\n\n\tJSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL, options);\n JSAutoCompartment ac(jsctx.get(), global_object);\n#elif JS_VERSION == 185\n\tJSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);\n#else\n\tJSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL);\n#endif\n\n\tJS_SetGlobalObject(jsctx.get(), global_object);\n\n\tJS_InitStandardClasses(jsctx.get(), global_object);\n\n#if JS_VERSION == 185\n\tJSObject * script\n#else\n\tJSScript * script\n#endif\n\t= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length, helper_file.c_str(), 0);\n\n\tJS_ExecuteScript(jsctx.get(), global_object, script, NULL);\n\n\tjsval res;\n\tstd::vector<jsval> argv;\n\tchar* res_;\n\n\tfor (auto _a : args)\n\t{\n\t\tJSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());\n\t\targv.push_back(STRING_TO_JSVAL(js_arg));\n\t}\n\n\tJS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);\n\n\tres_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));\n\tstd::string ret = res_;\n\tJS_free(jsctx.get(),res_);\n\treturn ret;\n\n}\n\n\nstd::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)\n{\n\tQFile helperfile(helper_file.c_str());\n\n\thelperfile.open(QIODevice::ReadOnly);\n\n\tauto js_content = helperfile.readAll();\n\n\treturn call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <string>\n\nclass Persons_File {\npublic:\n\tPersons_File() : is_empty(true), file_size(0) {\n\t\t;\n\t}\n\tstd::string file_name;\n\tsize_t file_size;\n\tbool is_empty;\n\tchar * key;\n\tbool is_same;\n\tstd::fstream stream;\n\tvoid openNew(std::string _file_name) {\n\t\tfile_name = _file_name;\n\t\tstream.open(file_name, std::ios::out);\n\t}\n};\n<commit_msg>Update PersonsFile.hpp<commit_after>#include <fstream>\n#include <string>\n\nclass Persons_File {\npublic:\n\tPersons_File() : is_empty(true), file_size(0) {\n\t\t;\n\t}\n\tstd::string file_name;\n\tsize_t file_size;\n\tbool is_empty;\n\tchar * key;\n\tbool is_same;\n\tstd::fstream stream;\n\tvoid openNew(std::string const & _file_name) {\n\t\tfile_name = _file_name;\n\t\tstream.open(file_name, std::ios::out);\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include <opencv2\/features2d\/features2d.hpp>\nusing std::unique_ptr;\n\nclass BriskFeatureDetectorNodeType : public NodeType\n{\npublic:\n\tBriskFeatureDetectorNodeType()\n\t\t: _thresh(30)\n\t\t, _nOctaves(3)\n\t\t, _patternScale(1.0f)\n\t\t, _brisk(new cv::BRISK())\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const QVariant& newValue) override\n\t{\n\t\tif(propId > ID_PatternScale || propId < ID_Threshold)\n\t\t\treturn false;\n\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_Threshold:\n\t\t\t_thresh = newValue.toInt();\n\t\tcase ID_NumOctaves:\n\t\t\t_nOctaves = newValue.toInt();\n\t\tcase ID_PatternScale:\n\t\t\t_patternScale = newValue.toFloat();\n\t\t}\n\n\t\t\/\/ That's a bit cheating here - creating BRISK object takes time (approx. 200ms for PAL)\n\t\t\/\/ which if done per frame makes it slowish (more than SIFT actually)\n\t\t_brisk = unique_ptr<cv::BRISK>(new cv::BRISK(_thresh, _nOctaves, _patternScale));\n\t\treturn true;\n\t}\n\n\tQVariant property(PropertyID propId) const override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_Threshold: return _thresh;\n\t\tcase ID_NumOctaves: return _nOctaves;\n\t\tcase ID_PatternScale: return _patternScale;\n\t\t}\n\n\t\treturn QVariant();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& src = reader.readSocket(0).getImage();\n\t\tcv::KeyPoints& keypoints = writer.acquireSocket(0).getKeypoints();\n\n\t\tif(src.rows == 0 || src.cols == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t_brisk->detect(src, keypoints);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"image\", \"Image\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"FAST\/AGAST detection threshold score\", \"min:1\" },\n\t\t\t{ EPropertyType::Integer, \"Number of octaves\", \"min:0\" },\n\t\t\t{ EPropertyType::Double, \"Pattern scale\", \"min:0.0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprotected:\n\tenum EPropertyID\n\t{\n\t\tID_Threshold,\n\t\tID_NumOctaves,\n\t\tID_PatternScale\n\t};\n\n\tint _thresh;\n\tint _nOctaves;\n\tfloat _patternScale;\n\t\/\/ Must be pointer since BRISK doesn't implement copy\/move operator (they should have)\n\tunique_ptr<cv::BRISK> _brisk;\n};\n\nclass BriskFeatureExtractorNodeType : public NodeType\n{\npublic:\n\tBriskFeatureExtractorNodeType()\n\t\t: _brisk(new cv::BRISK())\n\t{\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& imageSrc = reader.readSocket(0).getImage();\n\t\tconst cv::KeyPoints& keypoints = reader.readSocket(1).getKeypoints();\n\n\t\tif(keypoints.empty() || imageSrc.cols == 0 || imageSrc.rows == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tcv::Mat& outDescriptors = writer.acquireSocket(0).getArray();\n\t\tcv::KeyPoints& outKeypoints = writer.acquireSocket(1).getKeypoints();\n\n\t\toutKeypoints = keypoints;\n\t\t_brisk->compute(imageSrc, outKeypoints, outDescriptors);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"source\", \"Image\", \"\" },\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Descriptors\", \"\" },\n\t\t\t{ ENodeFlowDataType::Keypoints, \"output\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t}\n\nprivate:\n\t\/\/ Must be pointer since BRISK doesn't implement copy\/move operator (they should have)\n\tunique_ptr<cv::BRISK> _brisk;\n};\n\nclass BriskNodeType : public BriskFeatureDetectorNodeType\n{\npublic:\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& src = reader.readSocket(0).getImage();\n\t\tcv::KeyPoints& keypoints = writer.acquireSocket(0).getKeypoints();\n\t\tcv::Mat& descriptors = writer.acquireSocket(1).getArray();\n\n\t\tif(src.rows == 0 || src.cols == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t\/\/cv::BRISK(_thresh, _nOctaves, _patternScale)\n\t\t(*_brisk)(src, cv::noArray(), keypoints, descriptors);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tBriskFeatureDetectorNodeType::configuration(nodeConfig);\n\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Descriptors\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t}\n};\n\nREGISTER_NODE(\"Features\/BRISK Extractor\", BriskFeatureExtractorNodeType)\nREGISTER_NODE(\"Features\/BRISK Detector\", BriskFeatureDetectorNodeType)\nREGISTER_NODE(\"Features\/BRISK\", BriskNodeType)<commit_msg>fixed brisk property setter<commit_after>#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include <opencv2\/features2d\/features2d.hpp>\nusing std::unique_ptr;\n\nclass BriskFeatureDetectorNodeType : public NodeType\n{\npublic:\n\tBriskFeatureDetectorNodeType()\n\t\t: _thresh(30)\n\t\t, _nOctaves(3)\n\t\t, _patternScale(1.0f)\n\t\t, _brisk(new cv::BRISK())\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const QVariant& newValue) override\n\t{\n\t\tif(propId > ID_PatternScale || propId < ID_Threshold)\n\t\t\treturn false;\n\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_Threshold:\n\t\t\t_thresh = newValue.toInt();\n\t\t\tbreak;\n\t\tcase ID_NumOctaves:\n\t\t\t_nOctaves = newValue.toInt();\n\t\t\tbreak;\n\t\tcase ID_PatternScale:\n\t\t\t_patternScale = newValue.toFloat();\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ That's a bit cheating here - creating BRISK object takes time (approx. 200ms for PAL)\n\t\t\/\/ which if done per frame makes it slowish (more than SIFT actually)\n\t\t_brisk = unique_ptr<cv::BRISK>(new cv::BRISK(_thresh, _nOctaves, _patternScale));\n\t\treturn true;\n\t}\n\n\tQVariant property(PropertyID propId) const override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_Threshold: return _thresh;\n\t\tcase ID_NumOctaves: return _nOctaves;\n\t\tcase ID_PatternScale: return _patternScale;\n\t\t}\n\n\t\treturn QVariant();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& src = reader.readSocket(0).getImage();\n\t\tcv::KeyPoints& keypoints = writer.acquireSocket(0).getKeypoints();\n\n\t\tif(src.rows == 0 || src.cols == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t_brisk->detect(src, keypoints);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"image\", \"Image\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"FAST\/AGAST detection threshold score\", \"min:1\" },\n\t\t\t{ EPropertyType::Integer, \"Number of octaves\", \"min:0\" },\n\t\t\t{ EPropertyType::Double, \"Pattern scale\", \"min:0.0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprotected:\n\tenum EPropertyID\n\t{\n\t\tID_Threshold,\n\t\tID_NumOctaves,\n\t\tID_PatternScale\n\t};\n\n\tint _thresh;\n\tint _nOctaves;\n\tfloat _patternScale;\n\t\/\/ Must be pointer since BRISK doesn't implement copy\/move operator (they should have)\n\tunique_ptr<cv::BRISK> _brisk;\n};\n\nclass BriskFeatureExtractorNodeType : public NodeType\n{\npublic:\n\tBriskFeatureExtractorNodeType()\n\t\t: _brisk(new cv::BRISK())\n\t{\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& imageSrc = reader.readSocket(0).getImage();\n\t\tconst cv::KeyPoints& keypoints = reader.readSocket(1).getKeypoints();\n\n\t\tif(keypoints.empty() || imageSrc.cols == 0 || imageSrc.rows == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tcv::Mat& outDescriptors = writer.acquireSocket(0).getArray();\n\t\tcv::KeyPoints& outKeypoints = writer.acquireSocket(1).getKeypoints();\n\n\t\toutKeypoints = keypoints;\n\t\t_brisk->compute(imageSrc, outKeypoints, outDescriptors);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"source\", \"Image\", \"\" },\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Descriptors\", \"\" },\n\t\t\t{ ENodeFlowDataType::Keypoints, \"output\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t}\n\nprivate:\n\t\/\/ Must be pointer since BRISK doesn't implement copy\/move operator (they should have)\n\tunique_ptr<cv::BRISK> _brisk;\n};\n\nclass BriskNodeType : public BriskFeatureDetectorNodeType\n{\npublic:\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\tconst cv::Mat& src = reader.readSocket(0).getImage();\n\t\tcv::KeyPoints& keypoints = writer.acquireSocket(0).getKeypoints();\n\t\tcv::Mat& descriptors = writer.acquireSocket(1).getArray();\n\n\t\tif(src.rows == 0 || src.cols == 0)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t\/\/cv::BRISK(_thresh, _nOctaves, _patternScale)\n\t\t(*_brisk)(src, cv::noArray(), keypoints, descriptors);\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tBriskFeatureDetectorNodeType::configuration(nodeConfig);\n\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Keypoints, \"keypoints\", \"Keypoints\", \"\" },\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Descriptors\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t}\n};\n\nREGISTER_NODE(\"Features\/BRISK Extractor\", BriskFeatureExtractorNodeType)\nREGISTER_NODE(\"Features\/BRISK Detector\", BriskFeatureDetectorNodeType)\nREGISTER_NODE(\"Features\/BRISK\", BriskNodeType)<|endoftext|>"} {"text":"<commit_before>\/*\n * KeyValueTable.hpp\n *\n * Created on: Jun 14, 2015\n * Author: jcassidy\n *\/\n\n#ifndef KEYVALUETABLE_HPP_\n#define KEYVALUETABLE_HPP_\n\n#include <string>\n#include <vector>\n#include <boost\/serialization\/serialization.hpp>\n\nclass KeyValueTable {\npublic:\n\tunsigned addKey(const std::string k){ return keys_.addValue(k); }\n\tunsigned addValue(const std::string v){ return values_.addValue(v); }\n\n\tconst std::string& getKey(unsigned ki){ return keys_.getValue(ki); }\n\tconst std::string& getValue(unsigned vi){ return values_.getValue(vi); }\n\n\tbool keyValid(unsigned ki) const { return keys_.valueValid(ki); }\n\tbool valueValid(unsigned vi) const { return values_.valueValid(vi); }\n\n\tstd::function<const std::string&(unsigned)> keyLookup() const { return [this](unsigned i){ return cref(keys_.getValue(i)); }; }\n\tstd::function<const std::string&(unsigned)> valueLookup() const { return [this](unsigned i){ return cref(values_.getValue(i)); }; }\n\tstd::function<std::pair<const std::string&,const std::string&>(std::pair<unsigned,unsigned>)> pairLookup() const\n\t\t\t{ return [this](const std::pair<unsigned,unsigned> p){ return std::make_pair(cref(keys_.getValue(p.first)),cref(values_.getValue(p.second))); }; }\n\n\tconst std::vector<std::string>& keys() const \t{ return keys_.values(); }\n\tconst std::vector<std::string>& values() const \t{ return values_.values(); }\n\nprivate:\n\tValueTable keys_;\n\tValueTable values_;\n\n\ttemplate<class Archive>void serialize(Archive& ar,const unsigned ver){ ar & keys_ & values_; }\n\tfriend class boost::serialization::access;\n};\n\n\n\/** A key-value table which is bound to a specific set of tags.\n *\n *\/\n\nclass BoundKeyValueTable : public KeyValueTable {\npublic:\n\tBoundKeyValueTable(OSMEntity* e=nullptr) : entity_(e){}\n\n\tvoid addTag(unsigned ki,unsigned vi)\n\t{\n\t\tassert(entity_);\n\t\tassert(keyValid(ki));\n\t\tassert(valueValid(vi));\n\n\t\tentity_->addTag(ki,vi);\n\t}\n\n\tvoid activeEntity(OSMEntity* e){ entity_=e; }\n\tOSMEntity* activeEntity() const { return entity_; }\n\nprivate:\n\tOSMEntity* entity_=nullptr;\n};\n\n\n\n\n#endif \/* KEYVALUETABLE_HPP_ *\/\n<commit_msg>Fixed missing const in KeyValueTable<commit_after>\/*\n * KeyValueTable.hpp\n *\n * Created on: Jun 14, 2015\n * Author: jcassidy\n *\/\n\n#ifndef KEYVALUETABLE_HPP_\n#define KEYVALUETABLE_HPP_\n\n#include <string>\n#include <vector>\n#include <boost\/serialization\/serialization.hpp>\n\nclass KeyValueTable {\npublic:\n\tunsigned addKey(const std::string k){ return keys_.addValue(k); }\n\tunsigned addValue(const std::string v){ return values_.addValue(v); }\n\n\tconst std::string& getKey(unsigned ki) const { return keys_.getValue(ki); }\n\tconst std::string& getValue(unsigned vi) const { return values_.getValue(vi); }\n\n\tbool keyValid(unsigned ki) const { return keys_.valueValid(ki); }\n\tbool valueValid(unsigned vi) const { return values_.valueValid(vi); }\n\n\tstd::function<const std::string&(unsigned)> keyLookup() const { return [this](unsigned i){ return cref(keys_.getValue(i)); }; }\n\tstd::function<const std::string&(unsigned)> valueLookup() const { return [this](unsigned i){ return cref(values_.getValue(i)); }; }\n\tstd::function<std::pair<const std::string&,const std::string&>(std::pair<unsigned,unsigned>)> pairLookup() const\n\t\t\t{ return [this](const std::pair<unsigned,unsigned> p){ return std::make_pair(cref(keys_.getValue(p.first)),cref(values_.getValue(p.second))); }; }\n\n\tconst std::vector<std::string>& keys() const \t{ return keys_.values(); }\n\tconst std::vector<std::string>& values() const \t{ return values_.values(); }\n\nprivate:\n\tValueTable keys_;\n\tValueTable values_;\n\n\ttemplate<class Archive>void serialize(Archive& ar,const unsigned ver){ ar & keys_ & values_; }\n\tfriend class boost::serialization::access;\n};\n\n\n\/** A key-value table which is bound to a specific set of tags.\n *\n *\/\n\nclass BoundKeyValueTable : public KeyValueTable {\npublic:\n\tBoundKeyValueTable(OSMEntity* e=nullptr) : entity_(e){}\n\n\tvoid addTag(unsigned ki,unsigned vi)\n\t{\n\t\tassert(entity_);\n\t\tassert(keyValid(ki));\n\t\tassert(valueValid(vi));\n\n\t\tentity_->addTag(ki,vi);\n\t}\n\n\tvoid activeEntity(OSMEntity* e){ entity_=e; }\n\tOSMEntity* activeEntity() const { return entity_; }\n\nprivate:\n\tOSMEntity* entity_=nullptr;\n};\n\n\n\n\n#endif \/* KEYVALUETABLE_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/kontsevich_graph_series.hpp\"\n#include \"..\/kontsevich_graph_operator.hpp\"\n#include \"..\/util\/poisson_structure.hpp\" \/\/ for poisson_structures\n#include <ginac\/ginac.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\nusing namespace std;\nusing namespace GiNaC;\n\nint main(int argc, char* argv[])\n{\n if (argc != 3 || poisson_structures.find(argv[2]) == poisson_structures.end())\n {\n cerr << \"Usage: \" << argv[0] << \" <graph-series-filename> <poisson-structure>\\n\\n\"\n << \"Poisson structures can be chosen from the following list:\\n\";\n for (auto const& entry : poisson_structures)\n {\n cerr << \"- \" << entry.first << \"\\n\";\n }\n return 1;\n }\n\n PoissonStructure const& poisson = poisson_structures[argv[2]];\n\n cout << \"Coordinates: \";\n for (symbol coordinate : poisson.coordinates)\n cout << coordinate << \" \";\n cout << \"\\n\";\n cout << \"Poisson structure matrix:\\n\";\n cout << \"[\";\n for (auto row = poisson.bivector.begin(); row != poisson.bivector.end(); ++row)\n {\n cout << \"[\";\n for (auto entry = row->begin(); entry != row->end(); ++entry)\n {\n cout << *entry;\n if (entry + 1 != row->end())\n cout << \", \";\n }\n cout << \"]\";\n if (row + 1 != poisson.bivector.end())\n cout << \"\\n\";\n }\n cout << \"]\\n\\n\";\n\n \/\/ Reading in graph series:\n string graph_series_filename(argv[1]);\n ifstream graph_series_file(graph_series_filename);\n parser coefficient_reader;\n KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });\n size_t order = graph_series.precision();\n\n for (size_t n = 0; n <= order; ++n)\n {\n cout << \"h^\" << n << \":\\n\";\n for (std::vector<size_t> indegrees : graph_series[n].in_degrees(true))\n {\n cout << \"# \";\n for (size_t j = 0; j != indegrees.size(); ++j)\n cout << indegrees[j] << \" \";\n cout << \"\\n\";\n \n map< multi_indexes, ex > coefficients;\n for (auto& term : graph_series[n][indegrees])\n {\n map_operator_coefficients_from_graph(term.second, poisson, [&coefficients, &term](multi_indexes arg_derivatives, GiNaC::ex summand) {\n ex result = (term.first * summand).expand();\n coefficients[arg_derivatives] += result;\n });\n }\n for (auto& entry : coefficients)\n {\n cout << \"# \";\n for (auto mindex = entry.first.begin(); mindex != entry.first.end(); mindex++)\n {\n cout << \"[ \";\n for (auto &index : *mindex)\n {\n cout << poisson.coordinates[index] << \" \";\n }\n cout << \"]\";\n if (mindex + 1 != entry.first.end())\n cout << \" \";\n }\n cout << \"\\n\";\n ex result = entry.second;\n cout << result << \"\\n\";\n }\n cout.flush();\n }\n }\n}\n<commit_msg>Print fewer exponents in poisson_evaluate<commit_after>#include \"..\/kontsevich_graph_series.hpp\"\n#include \"..\/kontsevich_graph_operator.hpp\"\n#include \"..\/util\/poisson_structure.hpp\" \/\/ for poisson_structures\n#include <ginac\/ginac.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\nusing namespace std;\nusing namespace GiNaC;\n\nint main(int argc, char* argv[])\n{\n if (argc != 3 || poisson_structures.find(argv[2]) == poisson_structures.end())\n {\n cerr << \"Usage: \" << argv[0] << \" <graph-series-filename> <poisson-structure>\\n\\n\"\n << \"Poisson structures can be chosen from the following list:\\n\";\n for (auto const& entry : poisson_structures)\n {\n cerr << \"- \" << entry.first << \"\\n\";\n }\n return 1;\n }\n\n PoissonStructure const& poisson = poisson_structures[argv[2]];\n\n cout << \"Coordinates: \";\n for (symbol coordinate : poisson.coordinates)\n cout << coordinate << \" \";\n cout << \"\\n\";\n cout << \"Poisson structure matrix:\\n\";\n cout << \"[\";\n for (auto row = poisson.bivector.begin(); row != poisson.bivector.end(); ++row)\n {\n cout << \"[\";\n for (auto entry = row->begin(); entry != row->end(); ++entry)\n {\n cout << *entry;\n if (entry + 1 != row->end())\n cout << \", \";\n }\n cout << \"]\";\n if (row + 1 != poisson.bivector.end())\n cout << \"\\n\";\n }\n cout << \"]\\n\\n\";\n\n \/\/ Reading in graph series:\n string graph_series_filename(argv[1]);\n ifstream graph_series_file(graph_series_filename);\n parser coefficient_reader;\n KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });\n size_t order = graph_series.precision();\n\n for (size_t n = 0; n <= order; ++n)\n {\n if (graph_series[n] != 0 || n == order)\n cout << \"h^\" << n << \":\\n\";\n for (std::vector<size_t> indegrees : graph_series[n].in_degrees(true))\n {\n cout << \"# \";\n for (size_t j = 0; j != indegrees.size(); ++j)\n cout << indegrees[j] << \" \";\n cout << \"\\n\";\n \n map< multi_indexes, ex > coefficients;\n for (auto& term : graph_series[n][indegrees])\n {\n map_operator_coefficients_from_graph(term.second, poisson, [&coefficients, &term](multi_indexes arg_derivatives, GiNaC::ex summand) {\n ex result = (term.first * summand).expand();\n coefficients[arg_derivatives] += result;\n });\n }\n for (auto& entry : coefficients)\n {\n cout << \"# \";\n for (auto mindex = entry.first.begin(); mindex != entry.first.end(); mindex++)\n {\n cout << \"[ \";\n for (auto &index : *mindex)\n {\n cout << poisson.coordinates[index] << \" \";\n }\n cout << \"]\";\n if (mindex + 1 != entry.first.end())\n cout << \" \";\n }\n cout << \"\\n\";\n ex result = entry.second;\n cout << result << \"\\n\";\n }\n cout.flush();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/search\/search.hpp\"\n#include \"..\/utils\/pool.hpp\"\n\nvoid fatal(const char*, ...);\t\/\/ utils.hpp\n\ntemplate <class D> struct Wastar : public SearchAlgorithm<D> {\n\n\ttypedef typename D::State State;\n\ttypedef typename D::PackedState PackedState;\n\ttypedef typename D::Cost Cost;\n\ttypedef typename D::Oper Oper;\n\n\tstruct Node : SearchNode<D> {\n\t\tdouble f, fprime;\n\n\t\tstatic bool pred(Node *a, Node *b) {\n\t\t\tif (a->fprime == b->fprime) {\n\t\t\t\tif (a->f == b->f)\n\t\t\t\t\treturn a->g > b->g;\n\t\t\t\treturn a->f < b->f;\n\t\t\t}\n\t\t\treturn a->fprime < b->fprime;\n\t\t}\n\t};\n\n\tWastar(int argc, const char *argv[]) :\n\t\t\tSearchAlgorithm<D>(argc, argv), dropdups(false),\n\t\t\twt(-1.0), closed(30000001) {\n\t\tfor (int i = 0; i < argc; i++) {\n\t\t\tif (i < argc - 1 && strcmp(argv[i], \"-wt\") == 0)\n\t\t\t\twt = strtod(argv[++i], NULL);\n\t\t\tif (strcmp(argv[i], \"-dropdups\") == 0)\n\t\t\t\tdropdups = true;\n\t\t}\n\n\t\tif (wt < 1)\n\t\t\tfatal(\"Must specify a weight ≥1 weight using -wt\");\n\n\t\tnodes = new Pool<Node>();\n\t}\n\n\t~Wastar() {\n\t\tdelete nodes;\n\t}\n\n\tvoid search(D &d, typename D::State &s0) {\n\t\tthis->start();\n\t\tclosed.init(d);\n\n\t\tNode *n0 = init(d, s0);\n\t\tclosed.add(n0);\n\t\topen.push(n0);\n\n\t\twhile (!open.empty() && !SearchAlgorithm<D>::limit()) {\n\t\t\tNode *n = *open.pop();\n\t\t\tState buf, &state = d.unpack(buf, n->packed);\n\n\t\t\tif (d.isgoal(state)) {\n\t\t\t\tSearchAlgorithm<D>::res.goal(d, n);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\texpand(d, n, state);\n\t\t}\n\t\tthis->finish();\n\t}\n\n\tvirtual void reset() {\n\t\tSearchAlgorithm<D>::reset();\n\t\topen.clear();\n\t\tclosed.clear();\n\t\tdelete nodes;\n\t\tnodes = new Pool<Node>();\n\t}\n\n\tvirtual void output(FILE *out) {\n\t\tSearchAlgorithm<D>::output(out);\n\t\tclosed.prstats(stdout, \"closed \");\n\t\tdfpair(stdout, \"open list type\", \"%s\", \"binary heap\");\n\t\tdfpair(stdout, \"node size\", \"%u\", sizeof(Node));\n\t\tdfpair(stdout, \"weight\", \"%g\", wt);\n\t}\n\nprivate:\n\n\tvoid expand(D &d, Node *n, State &state) {\n\t\tSearchAlgorithm<D>::res.expd++;\n\n\t\ttypename D::Operators ops(d, state);\n\t\tfor (unsigned int i = 0; i < ops.size(); i++) {\n\t\t\tif (ops[i] == n->pop)\n\t\t\t\tcontinue;\n\t\t\tSearchAlgorithm<D>::res.gend++;\n\t\t\tconsiderkid(d, n, state, ops[i]);\n\t\t}\n\t}\n\n\tvoid considerkid(D &d, Node *parent, State &state, Oper op) {\n\t\tNode *kid = nodes->construct();\n\t\ttypename D::Edge e(d, state, op);\n\t\tkid->g = parent->g + e.cost;\n\t\td.pack(kid->packed, e.state);\n\n\t\tunsigned long hash = d.hash(kid->packed);\n\t\tNode *dup = static_cast<Node*>(closed.find(kid->packed, hash));\n\t\tif (dup) {\n\t\t\tthis->res.dups++;\n\t\t\tif (dropdups && kid->g < dup->g)\n\t\t\t\tdup->parent = parent;\n\t\t\tif (dropdups || kid->g >= dup->g) {\n\t\t\t\tnodes->destruct(kid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis->res.reopnd++;\n\t\t\tdup->fprime = dup->fprime - dup->g + kid->g;\n\t\t\tdup->f = dup->f - dup->g + kid->g;\n\t\t\tdup->update(kid->g, parent, op, e.revop);\n\t\t\topen.pushupdate(dup, dup->ind);\n\t\t\tnodes->destruct(kid);\n\t\t} else {\n\t\t\ttypename D::Cost h = d.h(e.state);\n\t\t\tkid->f = kid->g + h;\n\t\t\tkid->fprime = kid->g + wt * h;\n\t\t\tkid->update(kid->g, parent, op, e.revop);\n\t\t\tclosed.add(kid, hash);\n\t\t\topen.push(kid);\n\t\t}\n\t}\n\n\tNode *init(D &d, State &s0) {\n\t\tNode *n0 = nodes->construct();\n\t\td.pack(n0->packed, s0);\n\t\tn0->g = Cost(0);\n\t\ttypename D::Cost h = d.h(s0);\n\t\tn0->f = h;\n\t\tn0->fprime = wt * h;\n\t\tn0->op = n0->pop = D::Nop;\n\t\tn0->parent = NULL;\n\t\treturn n0;\n\t}\n\n\tbool dropdups;\n\tdouble wt;\n\tBinHeap<Node, Node*> open;\n \tClosedList<SearchNode<D>, SearchNode<D>, D> closed;\n\tPool<Node> *nodes;\n};\n<commit_msg>Revert the wA* parent pointer change. This breaks a bunch of things.<commit_after>#include \"..\/search\/search.hpp\"\n#include \"..\/utils\/pool.hpp\"\n\nvoid fatal(const char*, ...);\t\/\/ utils.hpp\n\ntemplate <class D> struct Wastar : public SearchAlgorithm<D> {\n\n\ttypedef typename D::State State;\n\ttypedef typename D::PackedState PackedState;\n\ttypedef typename D::Cost Cost;\n\ttypedef typename D::Oper Oper;\n\n\tstruct Node : SearchNode<D> {\n\t\tdouble f, fprime;\n\n\t\tstatic bool pred(Node *a, Node *b) {\n\t\t\tif (a->fprime == b->fprime) {\n\t\t\t\tif (a->f == b->f)\n\t\t\t\t\treturn a->g > b->g;\n\t\t\t\treturn a->f < b->f;\n\t\t\t}\n\t\t\treturn a->fprime < b->fprime;\n\t\t}\n\t};\n\n\tWastar(int argc, const char *argv[]) :\n\t\t\tSearchAlgorithm<D>(argc, argv), dropdups(false),\n\t\t\twt(-1.0), closed(30000001) {\n\t\tfor (int i = 0; i < argc; i++) {\n\t\t\tif (i < argc - 1 && strcmp(argv[i], \"-wt\") == 0)\n\t\t\t\twt = strtod(argv[++i], NULL);\n\t\t\tif (strcmp(argv[i], \"-dropdups\") == 0)\n\t\t\t\tdropdups = true;\n\t\t}\n\n\t\tif (wt < 1)\n\t\t\tfatal(\"Must specify a weight ≥1 weight using -wt\");\n\n\t\tnodes = new Pool<Node>();\n\t}\n\n\t~Wastar() {\n\t\tdelete nodes;\n\t}\n\n\tvoid search(D &d, typename D::State &s0) {\n\t\tthis->start();\n\t\tclosed.init(d);\n\n\t\tNode *n0 = init(d, s0);\n\t\tclosed.add(n0);\n\t\topen.push(n0);\n\n\t\twhile (!open.empty() && !SearchAlgorithm<D>::limit()) {\n\t\t\tNode *n = *open.pop();\n\t\t\tState buf, &state = d.unpack(buf, n->packed);\n\n\t\t\tif (d.isgoal(state)) {\n\t\t\t\tSearchAlgorithm<D>::res.goal(d, n);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\texpand(d, n, state);\n\t\t}\n\t\tthis->finish();\n\t}\n\n\tvirtual void reset() {\n\t\tSearchAlgorithm<D>::reset();\n\t\topen.clear();\n\t\tclosed.clear();\n\t\tdelete nodes;\n\t\tnodes = new Pool<Node>();\n\t}\n\n\tvirtual void output(FILE *out) {\n\t\tSearchAlgorithm<D>::output(out);\n\t\tclosed.prstats(stdout, \"closed \");\n\t\tdfpair(stdout, \"open list type\", \"%s\", \"binary heap\");\n\t\tdfpair(stdout, \"node size\", \"%u\", sizeof(Node));\n\t\tdfpair(stdout, \"weight\", \"%g\", wt);\n\t}\n\nprivate:\n\n\tvoid expand(D &d, Node *n, State &state) {\n\t\tSearchAlgorithm<D>::res.expd++;\n\n\t\ttypename D::Operators ops(d, state);\n\t\tfor (unsigned int i = 0; i < ops.size(); i++) {\n\t\t\tif (ops[i] == n->pop)\n\t\t\t\tcontinue;\n\t\t\tSearchAlgorithm<D>::res.gend++;\n\t\t\tconsiderkid(d, n, state, ops[i]);\n\t\t}\n\t}\n\n\tvoid considerkid(D &d, Node *parent, State &state, Oper op) {\n\t\tNode *kid = nodes->construct();\n\t\ttypename D::Edge e(d, state, op);\n\t\tkid->g = parent->g + e.cost;\n\t\td.pack(kid->packed, e.state);\n\n\t\tunsigned long hash = d.hash(kid->packed);\n\t\tNode *dup = static_cast<Node*>(closed.find(kid->packed, hash));\n\t\tif (dup) {\n\t\t\tthis->res.dups++;\n\t\t\tif (dropdups || kid->g >= dup->g) {\n\t\t\t\tnodes->destruct(kid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis->res.reopnd++;\n\t\t\tdup->fprime = dup->fprime - dup->g + kid->g;\n\t\t\tdup->f = dup->f - dup->g + kid->g;\n\t\t\tdup->update(kid->g, parent, op, e.revop);\n\t\t\topen.pushupdate(dup, dup->ind);\n\t\t\tnodes->destruct(kid);\n\t\t} else {\n\t\t\ttypename D::Cost h = d.h(e.state);\n\t\t\tkid->f = kid->g + h;\n\t\t\tkid->fprime = kid->g + wt * h;\n\t\t\tkid->update(kid->g, parent, op, e.revop);\n\t\t\tclosed.add(kid, hash);\n\t\t\topen.push(kid);\n\t\t}\n\t}\n\n\tNode *init(D &d, State &s0) {\n\t\tNode *n0 = nodes->construct();\n\t\td.pack(n0->packed, s0);\n\t\tn0->g = Cost(0);\n\t\ttypename D::Cost h = d.h(s0);\n\t\tn0->f = h;\n\t\tn0->fprime = wt * h;\n\t\tn0->op = n0->pop = D::Nop;\n\t\tn0->parent = NULL;\n\t\treturn n0;\n\t}\n\n\tbool dropdups;\n\tdouble wt;\n\tBinHeap<Node, Node*> open;\n \tClosedList<SearchNode<D>, SearchNode<D>, D> closed;\n\tPool<Node> *nodes;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: AGeoBezierPgon.cxx 3 2010-11-26 17:17:31Z oxon $\n\/\/ Author: Akira Okumura 2011\/07\/08\n\n\/******************************************************************************\n * Copyright (C) 2006-, Akira Okumura *\n * All rights reserved. *\n *****************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AGeoBezierPgon\n\/\/\n\/\/ Geometry class for Pgon-like volume, but the side surfaces are defined by\n\/\/ a Bezier curve (http:\/\/en.wikipedia.org\/wiki\/Bzier_curve)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AGeoBezierPgon.h\"\n\nClassImp(AGeoBezierPgon)\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon() : TGeoPgon()\n{\n \/\/ Default constructor\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon(Double_t phi, Double_t dphi, Int_t nedges,\n Int_t nz, Double_t r1, Double_t r2, Double_t dz)\n : TGeoPgon(phi, dphi, nedges, nz), fLength(dz*2), fR1(r1), fR2(r2)\n{\n fNcontrol = 0;\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon(const char* name, Double_t phi, Double_t dphi,\n Int_t nedges, Int_t nz, Double_t r1, Double_t r2,\n Double_t dz)\n : TGeoPgon(name, phi, dphi, nedges, nz), fLength(dz*2), fR1(r1), fR2(r2)\n{\n fNcontrol = 0;\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::~AGeoBezierPgon()\n{\n \/\/ destructor\n}\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::Bezier(Double_t t, Double_t& r, Double_t& z)\n{\n TVector2 P0(0, 0);\n TVector2 B;\n if(fNcontrol == 0){\n TVector2 P1(1, 1);\n B = (1 - t)*P0 + t*P1;\n } else if(fNcontrol == 1){\n TVector2 P2(1, 1);\n B = (1 - t)*(1 - t)*P0 + 2*(1 - t)*t*fP1 + t*t*P2;\n } else if(fNcontrol == 2){\n TVector2 P3(1, 1);\n B = (1 - t)*(1 - t)*(1 - t)*P0 + 3*(1 - t)*(1 - t)*t*fP1 + 3*(1 - t)*t*t*fP2 + t*t*t*P3;\n } \/\/ if\n\n r = fR2 + B.X()*(fR1 - fR2);\n z = -fLength\/2. + B.Y()*fLength;\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetControlPoints(Double_t r1, Double_t z1)\n{\n \/\/ Set the relative coordinates of control point 1\n \/\/ (r1, z1) must be given in relative coordinates against P0 and P2\n \/\/ For example, when (r1, z1) = (0.6, 0.7), the coordinates of P1 is\n \/\/ (R, Z) = (R2 + 0.6*(R1 - R2), -DZ + 0.7*(+DZ - (-DZ)))\n \/\/ The Bezier curve becomes quadratic\n \/\/\n \/\/ Z\n \/\/ ^\n \/\/ |<--R1-->P2 (R1, +DZ)\n \/\/ | \/\n \/\/ | \/ P1\n \/\/ | \/\n \/\/ +-----P0---------> R\n \/\/ |<-R2-> (R2, -DZ)\n fNcontrol = 1;\n fP1.Set(r1, z1);\n fP2.Set(0., 0.);\n SetSections();\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetControlPoints(Double_t r1, Double_t z1, Double_t r2, Double_t z2)\n{\n \/\/ Set the relative coordinates of control points 1 and 2\n \/\/ The Bezier curve becomes cubic\n fNcontrol = 2;\n fP1.Set(r1, z1);\n fP2.Set(r2, z2);\n SetSections();\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetSections()\n{\n for(Int_t i = 0; i < fNz; i++){\n Double_t t = Double_t(i)\/(fNz - 1);\n Double_t r, z;\n Bezier(t, r, z);\n DefineSection(i, z, 0, r);\n Error(\"SetSections\", \"%d %f %f %f\", i, t, z, r);\n } \/\/ i\n}\n<commit_msg>Removed debugging message<commit_after>\/\/ $Id: AGeoBezierPgon.cxx 3 2010-11-26 17:17:31Z oxon $\n\/\/ Author: Akira Okumura 2011\/07\/08\n\n\/******************************************************************************\n * Copyright (C) 2006-, Akira Okumura *\n * All rights reserved. *\n *****************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AGeoBezierPgon\n\/\/\n\/\/ Geometry class for Pgon-like volume, but the side surfaces are defined by\n\/\/ a Bezier curve (http:\/\/en.wikipedia.org\/wiki\/Bzier_curve)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AGeoBezierPgon.h\"\n\nClassImp(AGeoBezierPgon)\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon() : TGeoPgon()\n{\n \/\/ Default constructor\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon(Double_t phi, Double_t dphi, Int_t nedges,\n Int_t nz, Double_t r1, Double_t r2, Double_t dz)\n : TGeoPgon(phi, dphi, nedges, nz), fLength(dz*2), fR1(r1), fR2(r2)\n{\n fNcontrol = 0;\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::AGeoBezierPgon(const char* name, Double_t phi, Double_t dphi,\n Int_t nedges, Int_t nz, Double_t r1, Double_t r2,\n Double_t dz)\n : TGeoPgon(name, phi, dphi, nedges, nz), fLength(dz*2), fR1(r1), fR2(r2)\n{\n fNcontrol = 0;\n}\n\n\/\/_____________________________________________________________________________\nAGeoBezierPgon::~AGeoBezierPgon()\n{\n \/\/ destructor\n}\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::Bezier(Double_t t, Double_t& r, Double_t& z)\n{\n TVector2 P0(0, 0);\n TVector2 B;\n if(fNcontrol == 0){\n TVector2 P1(1, 1);\n B = (1 - t)*P0 + t*P1;\n } else if(fNcontrol == 1){\n TVector2 P2(1, 1);\n B = (1 - t)*(1 - t)*P0 + 2*(1 - t)*t*fP1 + t*t*P2;\n } else if(fNcontrol == 2){\n TVector2 P3(1, 1);\n B = (1 - t)*(1 - t)*(1 - t)*P0 + 3*(1 - t)*(1 - t)*t*fP1 + 3*(1 - t)*t*t*fP2 + t*t*t*P3;\n } \/\/ if\n\n r = fR2 + B.X()*(fR1 - fR2);\n z = -fLength\/2. + B.Y()*fLength;\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetControlPoints(Double_t r1, Double_t z1)\n{\n \/\/ Set the relative coordinates of control point 1\n \/\/ (r1, z1) must be given in relative coordinates against P0 and P2\n \/\/ For example, when (r1, z1) = (0.6, 0.7), the coordinates of P1 is\n \/\/ (R, Z) = (R2 + 0.6*(R1 - R2), -DZ + 0.7*(+DZ - (-DZ)))\n \/\/ The Bezier curve becomes quadratic\n \/\/\n \/\/ Z\n \/\/ ^\n \/\/ |<--R1-->P2 (R1, +DZ)\n \/\/ | \/\n \/\/ | \/ P1\n \/\/ | \/\n \/\/ +-----P0---------> R\n \/\/ |<-R2-> (R2, -DZ)\n fNcontrol = 1;\n fP1.Set(r1, z1);\n fP2.Set(0., 0.);\n SetSections();\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetControlPoints(Double_t r1, Double_t z1, Double_t r2, Double_t z2)\n{\n \/\/ Set the relative coordinates of control points 1 and 2\n \/\/ The Bezier curve becomes cubic\n fNcontrol = 2;\n fP1.Set(r1, z1);\n fP2.Set(r2, z2);\n SetSections();\n}\n\n\/\/_____________________________________________________________________________\nvoid AGeoBezierPgon::SetSections()\n{\n for(Int_t i = 0; i < fNz; i++){\n Double_t t = Double_t(i)\/(fNz - 1);\n Double_t r, z;\n Bezier(t, r, z);\n DefineSection(i, z, 0, r);\n } \/\/ i\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"broker.hpp\"\n#include <base\/message_any.hpp>\n\nnamespace cossb {\nnamespace broker {\n\nunsigned int component_broker::publish(const char* service_name, cossb::message& msg)\n{\n\tunsigned int times = 0;\n\n\tif(_service_map.find(service_name)!=_service_map.end()) {\n\t\tauto range = _topic_map.equal_range(_service_map[service_name].topic);\n\t\tmsg.msg_frame.topic = _service_map[service_name].topic;\n\t\tfor(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {\n\t\t\tdriver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());\n\t\t\tif(_drv)\n\t\t\t{\n\t\t\t\tif(!_drv->mine(msg.get_from())) {\n\t\t\t\t\t_drv->request(&msg);\n\t\t\t\t\ttimes++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"{} service has no component driver. it will be removed.\", service_name));\n\t\t\t\t_service_map.erase(service_name);\n\t\t\t\t\/\/throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"No Services({}) found\", service_name));\n\n\treturn times;\n}\n\n\/\/template<typename... Args>\n\/\/unsigned int component_broker::publish(interface::icomponent* to_component, const char* topic, const char* api, const Args&... args)\n\/\/{\n\/\/\tauto range = _topic_map.equal_range(topic);\n\/\/\tunsigned int times = 0;\n\/\/\tfor(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {\n\/\/\t\tif(itr->second.compare(to_component->get_name())!=0) {\n\/\/\t\t\tdriver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());\n\/\/\t\t\tif(_drv) {\n\/\/\t\t\t\t_drv->request(api, args...);\n\/\/\t\t\t\ttimes++;\n\/\/\t\t\t}\n\/\/\t\t\telse {\n\/\/\t\t\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"<{}> has no component driver.\", to_component->get_name()));\n\/\/\t\t\t\t\/\/throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);\n\/\/\t\t\t}\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\treturn times;\n\/\/}\n\nbool component_broker::regist(cossb::service::_service_desc* const service)\n{\n\tif(service) {\n\t\tif(_service_map.find(service->name)==_service_map.end()) {\n\t\t\t_service_map.insert(service_map::value_type(service->name, *service));\n\t\t\t_topic_map.insert(topic_map::value_type(service->topic, service->component_name));\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Service Registration : topic {} \/ Service {}\", service->topic, service->name));\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\tcossb_log->log(log::loglevel::WARN, fmt::format(\"Already registered service : Topic {} \/ Service {}\", service->topic, service->name));\n\t}\n\n\treturn false;\n}\n\n} \/* namespace broker *\/\n} \/* namespace cossb *\/\n<commit_msg>- update for test<commit_after>#include \"broker.hpp\"\n#include <base\/message_any.hpp>\n\nnamespace cossb {\nnamespace broker {\n\nunsigned int component_broker::publish(const char* service_name, cossb::message& msg)\n{\n\tunsigned int times = 0;\n\n\tif(_service_map.find(service_name)!=_service_map.end()) {\n\t\tauto range = _topic_map.equal_range(_service_map[service_name].topic);\n\t\tmsg.msg_frame.topic = _service_map[service_name].topic;\n\t\tfor(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {\n\t\t\tdriver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());\n\t\t\tif(_drv)\n\t\t\t{\n\t\t\t\tif(!_drv->mine(msg.get_from())) {\n\t\t\t\t\tcossb_log->log(log::loglevel::INFO, \"Request Message\");\n\t\t\t\t\t_drv->request(&msg);\n\t\t\t\t\ttimes++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"{} service has no component driver. it will be removed.\", service_name));\n\t\t\t\t_service_map.erase(service_name);\n\t\t\t\t\/\/throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"No Services({}) found\", service_name));\n\n\treturn times;\n}\n\n\/\/template<typename... Args>\n\/\/unsigned int component_broker::publish(interface::icomponent* to_component, const char* topic, const char* api, const Args&... args)\n\/\/{\n\/\/\tauto range = _topic_map.equal_range(topic);\n\/\/\tunsigned int times = 0;\n\/\/\tfor(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {\n\/\/\t\tif(itr->second.compare(to_component->get_name())!=0) {\n\/\/\t\t\tdriver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());\n\/\/\t\t\tif(_drv) {\n\/\/\t\t\t\t_drv->request(api, args...);\n\/\/\t\t\t\ttimes++;\n\/\/\t\t\t}\n\/\/\t\t\telse {\n\/\/\t\t\t\tcossb_log->log(log::loglevel::ERROR, fmt::format(\"<{}> has no component driver.\", to_component->get_name()));\n\/\/\t\t\t\t\/\/throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);\n\/\/\t\t\t}\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\treturn times;\n\/\/}\n\nbool component_broker::regist(cossb::service::_service_desc* const service)\n{\n\tif(service) {\n\t\tif(_service_map.find(service->name)==_service_map.end()) {\n\t\t\t_service_map.insert(service_map::value_type(service->name, *service));\n\t\t\t_topic_map.insert(topic_map::value_type(service->topic, service->component_name));\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Service Registration : topic {} \/ Service {}\", service->topic, service->name));\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\tcossb_log->log(log::loglevel::WARN, fmt::format(\"Already registered service : Topic {} \/ Service {}\", service->topic, service->name));\n\t}\n\n\treturn false;\n}\n\n} \/* namespace broker *\/\n} \/* namespace cossb *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CategoryStream.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"PortabilityImpl.hh\"\n\n#ifdef LOG4CPP_HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n\n#include <log4cpp\/CategoryStream.hh>\n#include <log4cpp\/Category.hh>\n\nnamespace log4cpp {\n\n CategoryStream::CategoryStream(Category& category, Priority::Value priority) :\n _category(category),\n _priority(priority),\n _buffer(NULL) {\n }\n\n CategoryStream::~CategoryStream() { \n flush();\n }\n\n CategoryStream& CategoryStream::operator<<(CategoryStream::Separator separator) {\n flush();\n return *this;\n }\n\n void CategoryStream::flush() {\n if (_buffer) {\n getCategory().log(getPriority(), _buffer->str());\n delete _buffer;\n _buffer = NULL;\n }\n }\n std::streamsize CategoryStream::width(std::streamsize wide ) {\n if (getPriority() != Priority::NOTSET) {\n if (!_buffer) {\n if (!(_buffer = new std::ostringstream)) {\n \/\/ XXX help help help\n }\n }\n }\n return _buffer->width(wide); \n }\n CategoryStream& CategoryStream::operator<< (cspf) {\n\t\tcspf(this);\n\t\treturn *this;\n }\n CategoryStream& eol (CategoryStream& os) {\n if (os._buffer->good()) {\n os._buffer->put(os._buffer->widen('\\n'));os._buffer->flush();\n }\n return os;\n }\n CategoryStream& left (CategoryStream& os) {\n if (os._buffer->good()) {\n os._buffer->setf(std::ios::left);\n }\n return os;\n }\n}\n<commit_msg>Fix CategoryStream::eol(CategoryStream&)<commit_after>\/*\n * CategoryStream.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"PortabilityImpl.hh\"\n\n#ifdef LOG4CPP_HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n\n#include <log4cpp\/CategoryStream.hh>\n#include <log4cpp\/Category.hh>\n\nnamespace log4cpp {\n\n CategoryStream::CategoryStream(Category& category, Priority::Value priority) :\n _category(category),\n _priority(priority),\n _buffer(NULL) {\n }\n\n CategoryStream::~CategoryStream() { \n flush();\n }\n\n CategoryStream& CategoryStream::operator<<(CategoryStream::Separator separator) {\n flush();\n return *this;\n }\n\n void CategoryStream::flush() {\n if (_buffer) {\n getCategory().log(getPriority(), _buffer->str());\n delete _buffer;\n _buffer = NULL;\n }\n }\n std::streamsize CategoryStream::width(std::streamsize wide ) {\n if (getPriority() != Priority::NOTSET) {\n if (!_buffer) {\n if (!(_buffer = new std::ostringstream)) {\n \/\/ XXX help help help\n }\n }\n }\n return _buffer->width(wide); \n }\n CategoryStream& CategoryStream::operator<< (cspf pf) {\n\t\treturn (*pf)(*this);\n }\n CategoryStream& eol (CategoryStream& os) {\n if (os._buffer->good()) {\n\t\t\tos.flush();\n }\n return os;\n }\n CategoryStream& left (CategoryStream& os) {\n if (os._buffer->good()) {\n os._buffer->setf(std::ios::left);\n }\n return os;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <string>\n#include <IniLoader.h>\n#include <algorithm>\n#include <string> \n\nstatic std::string emptyString;\n\n\/\/static std::map<std::string, std::string> handlers;\nnamespace IniLoader {\n\tstatic std::string toLower(const char* str) {\n\t\tstd::string tmp(str);\n\t\tstd::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\t\treturn tmp; \/\/RVO\n\/\/\t\treturn std::move(tmp);\n\t}\n\n\tint sectionHandler(void* user, const char* _section, const char* _name, const char* value) {\n\t\tini_contents* contents = (ini_contents*)user;\n\t\tstd::string sec_name = toLower(_section);\n\t\tstd::string name = toLower(_name);\n\n\t\tauto tmp = contents->find(sec_name);\n\t\tif (tmp != contents->end()) {\n\t\t\tini_section& s = tmp->second;\n\t\t\ts.pairs.erase(name);\n\t\t\ts.pairs.insert(std::make_pair(std::move(name), std::string(value)));\n\t\t}\n\t\telse {\n\t\t\tini_section s;\n\t\t\ts.header = sec_name;\n\t\t\ts.pairs.insert(std::make_pair(std::move(name), std::string(value)));\n\t\t\tcontents->insert(std::make_pair(std::move(sec_name), std::move(s)));\n\t\t}\n\t\treturn 0;\n\t}\n\n\tContents parse(const std::string &filename) {\n\t\tContents contents;\n\t\tini_parse(filename.c_str(), §ionHandler, &contents.m_ini);\n\t\treturn contents; \/\/std::move is not a good idea here, prevents RVO\n\t}\n\n\tconst std::string& getValue(const ini_contents& c, const std::string& sec, const std::string& name) {\n\t\tauto t1 = c.find(sec);\n\t\tif (t1 == c.end()) return emptyString;\n\n\t\tconst ini_section& section = t1->second;\n\t\tauto t2 = section.pairs.find(name);\n\t\tif (t2 == section.pairs.end()) return emptyString;\n\n\t\treturn t2->second;\n\t}\n}\n\/\/\n\/\/IniRegistrar::IniRegistrar(std::string tag, std::string value) {\n\/\/\tauto t = std::make_pair(tag, value);\n\/\/\thandlers.insert(t);\n\/\/}<commit_msg>better ini file error handling<commit_after>#include <map>\n#include <string>\n#include <IniLoader.h>\n#include <algorithm>\n#include <string> \n\nstatic std::string emptyString;\n\nnamespace IniLoader {\n\tstatic std::string toLower(const char* str) {\n\t\tstd::string tmp(str);\n\t\tstd::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\t\treturn tmp; \/\/RVO\n\t}\n\n\tint sectionHandler(void* user, const char* _section, const char* _name, const char* value) {\n\t\tini_contents* contents = (ini_contents*)user;\n\t\tstd::string sec_name = toLower(_section);\n\t\tstd::string name = toLower(_name);\n\n\t\tauto tmp = contents->find(sec_name);\n\t\tif (tmp != contents->end()) {\n\t\t\tini_section& s = tmp->second;\n\t\t\ts.pairs.erase(name);\n\t\t\ts.pairs.insert(std::make_pair(std::move(name), std::string(value)));\n\t\t}\n\t\telse {\n\t\t\tini_section s;\n\t\t\ts.header = sec_name;\n\t\t\ts.pairs.insert(std::make_pair(std::move(name), std::string(value)));\n\t\t\tcontents->insert(std::make_pair(std::move(sec_name), std::move(s)));\n\t\t}\n\t\treturn 1; \/\/non-zero on success\n\t}\n\n\tContents parse(const std::string &filename) {\n\t\tContents contents;\n\t\tint r = ini_parse(filename.c_str(), §ionHandler, &contents.m_ini);\n\t\tif (r == -1) {\n\t\t\tfprintf(stderr, \"Error opening file \\\"%s\\\"\\n\", filename.c_str());\n\t\t}\n\t\telse if (r == -2) {\n\t\t\tfprintf(stderr, \"Memory alignment error opening file \\\"%s\\\"\\n\", filename.c_str());\n\t\t}\n\t\telse if (r > 0) {\n\t\t\tfprintf(stderr, \"Error on line %d in file \\\"%s\\\"\\n\", r, filename.c_str());\n\t\t}\n\t\telse if (r != 0) {\n\t\t\tfprintf(stderr, \"Unknown error opening file \\\"%s\\\"\\n\", filename.c_str() );\n\t\t}\n\t\treturn contents; \/\/std::move is not a good idea here, prevents RVO\n\t}\n\n\tconst std::string& getValue(const ini_contents& c, const std::string& sec, const std::string& name) {\n\t\tauto t1 = c.find(sec);\n\t\tif (t1 == c.end()) return emptyString;\n\n\t\tconst ini_section& section = t1->second;\n\t\tauto t2 = section.pairs.find(name);\n\t\tif (t2 == section.pairs.end()) return emptyString;\n\n\t\treturn t2->second;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/* hasher.hh -- k-mer hash functions\n *\n * Copyright (C) 2018 Camille Scott\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the MIT license. See the LICENSE file for details.\n *\/\n\n#include \"boink.hh\"\n#include \"oxli\/alphabets.hh\"\n#include \"oxli\/kmer_hash.hh\"\n\nnamespace boink {\n\ntypedef uint64_t hash_t;\ntypedef std::pair<hash_t, hash_t> full_hash_t;\n\n\nclass KmerClient {\nprotected:\n const uint16_t _K;\npublic:\n explicit KmerClient(uint16_t K) : _K(K) {}\n const uint16_t K() const { return _K; }\n};\n\n\ntemplate <class Derived,\n const std::string& Alphabet>\nclass HashShifter : public KmerClient {\npublic:\n std::deque<char> symbol_deque;\n using KmerClient::KmerClient;\n \n hash_t reset(const std::string& sequence) {\n if (sequence.length() < _K) {\n throw BoinkException(\"Sequence must be length K\");\n }\n symbol_deque.clear();\n for (size_t i = 0; i < _K; ++i) {\n symbol_deque.push_back(sequence[i]);\n }\n return derived().reset();\n }\n\n hash_t reset() {\n return derived().reset();\n }\n\n hash_t hash() {\n return derived().hash();\n }\n\n hash_t hash(std::string& sequence) {\n return derived().hash(sequence);\n }\n\n std::vector<hash_t> shift_left() {\n return derived().shift_left();\n }\n\n hash_t shift_left(const char c) {\n symbol_deque.push_front(c);\n hash_t h = derived().shift_left(c);\n symbol_deque.pop_back();\n return h;\n }\n\n std::vector<hash_t> shift_right() {\n return derived().shift_right();\n }\n\n hash_t shift_right(const char c) {\n symbol_deque.push_back(c);\n hash_t h = derived().shift_right(c);\n symbol_deque.pop_front();\n return h;\n }\n\n std::string get_cursor() {\n std::string sequence;\n for (auto c : symbol_deque) {\n sequence.append(c);\n }\n return sequence;\n }\n\nprivate:\n\n Derived& derived() {\n return *static_cast<Derived*>(this);\n }\n\n};\n\ntemplate <const std::string& Alphabet>\nclass RollingHashShifter : public HashShifter<RollingHashShifter<Alphabet>,\n Alphabet> {\n CyclicHash<hash_t> hasher;\n\npublic:\n\n using HashShifter<RollingHashShifter<Alphabet>, Alphabet>::HashShifter;\n typedef HashShifter<RollingHashShifter<Alphabet>, Alphabet> BaseShifter;\n\n RollingHashShifter(uint16_t K) :\n BaseShifter(K), hasher(K) {\n\n }\n\n hash_t reset() {\n hasher = CyclicHash<hash_t>(this->_K);\n for (auto c : this->symbol_deque) {\n hasher.eat(c);\n }\n return hasher.hashvalue;\n }\n\n hash_t hash() {\n return hasher.hashvalue;\n }\n\n hash_t hash(std::string& sequence) {\n return _hash_cyclic_forward(sequence, this->_K);\n }\n\n hash_t shift_left(const char c) {\n hasher.reverse_update(c, this->symbol_deque.back());\n return hasher.hashvalue;\n }\n\n std::vector<hash_t> shift_right() {\n std::vector<hash_t> hashes;\n const char front = this->symbol_deque.front();\n for (auto symbol : Alphabet) {\n hasher.update(front, symbol);\n hashes.push_back(hasher.hashvalue);\n hasher.reverse_update(front, symbol);\n }\n return hashes;\n }\n\n hash_t shift_right(const char c) {\n hasher.update(this->symbol_deque.front(), c);\n return hash();\n }\n\n std::vector<hash_t> shift_left() {\n std::vector<hash_t> hashes;\n const char back = this->symbol_deque.back();\n for (auto symbol : Alphabet) {\n hasher.reverse_update(symbol, back);\n hashes.push_back(hasher.hashvalue);\n hasher.update(symbol, back);\n }\n }\n};\n\ntypedef RollingHashShifter<oxli::alphabets::DNA_SIMPLE> DefaultShifter;\n\n\ntemplate <class Shifter>\nclass KmerIterator : public KmerClient {\n const std::string _seq;\n unsigned int index;\n unsigned int length;\n bool _initialized;\n Shifter shifter;\n\npublic:\n KmerIterator(const std::string seq, uint16_t K) :\n KmerClient(K), shifter(K), _seq(seq),\n index(0), _initialized(false) {\n \n }\n\n hash_t first() {\n _initialized = true;\n\n shifter.reset(_seq);\n index += 1;\n return shifter.hash();\n }\n\n hash_t next() {\n if (!_initialized) {\n return first();\n }\n\n if (done()) {\n throw BoinkException(\"past end of iterator\");\n }\n\n shifter.shift_right(_seq[index + _K - 1]);\n index += 1;\n\n return shifter.hash();\n }\n\n bool done() const {\n return (index + _K > _seq.length());\n }\n\n unsigned int get_start_pos() const {\n if (!_initialized) { return 0; }\n return index - 1;\n }\n\n unsigned int get_end_pos() const {\n if (!_initialized) { return _K; }\n return index + _K - 1;\n }\n};\n\n\n\/*\nclass FullRollingHasher {\n const char * _seq;\n const std::string _rev;\n const char _ksize;\n unsigned int index;\n unsigned int length;\n bool _initialized;\n oxli::CyclicHash<uint64_t> fwd_hasher;\n oxli::CyclicHash<uint64_t> bwd_hasher;\n\npublic:\n FullRollingHasher(const char * seq, unsigned char k) :\n _seq(seq), _rev(oxli::_revcomp(seq)), _ksize(k), index(0),\n _initialized(false), fwd_hasher(k), bwd_hasher(k)\n {\n length = strlen(_seq);\n };\n\n full_hash_t first() {\n _initialized = true;\n\n for (char i = 0; i < _ksize; ++i) {\n fwd_hasher.eat(*(_seq + i));\n bwd_hasher.eat(_rev[length - _ksize + i]);\n }\n index += 1;\n return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);\n }\n\n full_hash_t next() {\n if (!_initialized) {\n return first();\n }\n\n if (done()) {\n throw oxli_exception(\"past end of iterator\");\n }\n fwd_hasher.update(*(_seq + index - 1), *(_seq + index + _ksize - 1));\n\n \/\/ first argument is added, second is removed from the hash\n bwd_hasher.reverse_update(\n _rev[length - _ksize - index], _rev[length - index]);\n\n index += 1;\n\n return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);\n }\n\n bool done() const {\n return (index + _ksize > length);\n }\n\n unsigned int get_start_pos() const {\n if (!_initialized) { return 0; }\n return index - 1;\n }\n\n unsigned int get_end_pos() const {\n if (!_initialized) { return _ksize; }\n return index + _ksize - 1;\n }\n};\n*\/\n\n};\n<commit_msg>Fix string append, fix object reset pattern<commit_after>\/* hasher.hh -- k-mer hash functions\n *\n * Copyright (C) 2018 Camille Scott\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the MIT license. See the LICENSE file for details.\n *\/\n\n#include \"boink.hh\"\n#include \"oxli\/alphabets.hh\"\n#include \"oxli\/kmer_hash.hh\"\n\nnamespace boink {\n\ntypedef uint64_t hash_t;\ntypedef std::pair<hash_t, hash_t> full_hash_t;\n\n\nclass KmerClient {\nprotected:\n const uint16_t _K;\npublic:\n explicit KmerClient(uint16_t K) : _K(K) {}\n const uint16_t K() const { return _K; }\n};\n\n\ntemplate <class Derived,\n const std::string& Alphabet>\nclass HashShifter : public KmerClient {\npublic:\n std::deque<char> symbol_deque;\n using KmerClient::KmerClient;\n \n hash_t reset(const std::string& sequence) {\n if (sequence.length() < _K) {\n throw BoinkException(\"Sequence must be length K\");\n }\n symbol_deque.clear();\n for (size_t i = 0; i < _K; ++i) {\n symbol_deque.push_back(sequence[i]);\n }\n return derived().reset();\n }\n\n hash_t reset() {\n return derived().reset();\n }\n\n hash_t hash() {\n return derived().hash();\n }\n\n hash_t hash(std::string& sequence) {\n return derived().hash(sequence);\n }\n\n std::vector<hash_t> shift_left() {\n return derived().shift_left();\n }\n\n hash_t shift_left(const char c) {\n symbol_deque.push_front(c);\n hash_t h = derived().shift_left(c);\n symbol_deque.pop_back();\n return h;\n }\n\n std::vector<hash_t> shift_right() {\n return derived().shift_right();\n }\n\n hash_t shift_right(const char c) {\n symbol_deque.push_back(c);\n hash_t h = derived().shift_right(c);\n symbol_deque.pop_front();\n return h;\n }\n\n std::string get_cursor() {\n std::string sequence = \"\";\n for (auto c : symbol_deque) {\n sequence += c;\n }\n return sequence;\n }\n\nprivate:\n\n Derived& derived() {\n return *static_cast<Derived*>(this);\n }\n\n};\n\ntemplate <const std::string& Alphabet>\nclass RollingHashShifter : public HashShifter<RollingHashShifter<Alphabet>,\n Alphabet> {\n CyclicHash<hash_t> hasher;\n\npublic:\n\n using HashShifter<RollingHashShifter<Alphabet>, Alphabet>::HashShifter;\n using HashShifter<RollingHashShifter<Alphabet>, Alphabet>::reset;\n typedef HashShifter<RollingHashShifter<Alphabet>, Alphabet> BaseShifter;\n\n RollingHashShifter(uint16_t K) :\n BaseShifter(K), hasher(K) {\n\n }\n\n hash_t reset() {\n \/\/ This pattern \"resets\" a stack object\n \/\/ by calling its destructor and reallocating\n (&hasher)->~CyclicHash<hash_t>();\n new (&hasher) CyclicHash<hash_t>(this->_K);\n\n for (auto c : this->symbol_deque) {\n hasher.eat(c);\n }\n return hasher.hashvalue;\n }\n\n hash_t hash() {\n return hasher.hashvalue;\n }\n\n hash_t hash(std::string& sequence) {\n return _hash_cyclic_forward(sequence, this->_K);\n }\n\n hash_t shift_left(const char c) {\n hasher.reverse_update(c, this->symbol_deque.back());\n return hasher.hashvalue;\n }\n\n std::vector<hash_t> shift_right() {\n std::vector<hash_t> hashes;\n const char front = this->symbol_deque.front();\n for (auto symbol : Alphabet) {\n hasher.update(front, symbol);\n hashes.push_back(hasher.hashvalue);\n hasher.reverse_update(front, symbol);\n }\n return hashes;\n }\n\n hash_t shift_right(const char c) {\n hasher.update(this->symbol_deque.front(), c);\n return hash();\n }\n\n std::vector<hash_t> shift_left() {\n std::vector<hash_t> hashes;\n const char back = this->symbol_deque.back();\n for (auto symbol : Alphabet) {\n hasher.reverse_update(symbol, back);\n hashes.push_back(hasher.hashvalue);\n hasher.update(symbol, back);\n }\n\n return hashes;\n }\n};\n\ntypedef RollingHashShifter<oxli::alphabets::DNA_SIMPLE> DefaultShifter;\n\n\ntemplate <class Shifter>\nclass KmerIterator : public KmerClient {\n const std::string _seq;\n unsigned int index;\n unsigned int length;\n bool _initialized;\n Shifter shifter;\n\npublic:\n KmerIterator(const std::string seq, uint16_t K) :\n KmerClient(K), _seq(seq), shifter(K),\n index(0), _initialized(false) {\n \n }\n\n hash_t first() {\n _initialized = true;\n\n shifter.reset(_seq);\n index += 1;\n return shifter.hash();\n }\n\n hash_t next() {\n if (!_initialized) {\n return first();\n }\n\n if (done()) {\n throw BoinkException(\"past end of iterator\");\n }\n\n shifter.shift_right(_seq[index + _K - 1]);\n index += 1;\n\n return shifter.hash();\n }\n\n bool done() const {\n return (index + _K > _seq.length());\n }\n\n unsigned int get_start_pos() const {\n if (!_initialized) { return 0; }\n return index - 1;\n }\n\n unsigned int get_end_pos() const {\n if (!_initialized) { return _K; }\n return index + _K - 1;\n }\n};\n\n\n\/*\nclass FullRollingHasher {\n const char * _seq;\n const std::string _rev;\n const char _ksize;\n unsigned int index;\n unsigned int length;\n bool _initialized;\n oxli::CyclicHash<uint64_t> fwd_hasher;\n oxli::CyclicHash<uint64_t> bwd_hasher;\n\npublic:\n FullRollingHasher(const char * seq, unsigned char k) :\n _seq(seq), _rev(oxli::_revcomp(seq)), _ksize(k), index(0),\n _initialized(false), fwd_hasher(k), bwd_hasher(k)\n {\n length = strlen(_seq);\n };\n\n full_hash_t first() {\n _initialized = true;\n\n for (char i = 0; i < _ksize; ++i) {\n fwd_hasher.eat(*(_seq + i));\n bwd_hasher.eat(_rev[length - _ksize + i]);\n }\n index += 1;\n return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);\n }\n\n full_hash_t next() {\n if (!_initialized) {\n return first();\n }\n\n if (done()) {\n throw oxli_exception(\"past end of iterator\");\n }\n fwd_hasher.update(*(_seq + index - 1), *(_seq + index + _ksize - 1));\n\n \/\/ first argument is added, second is removed from the hash\n bwd_hasher.reverse_update(\n _rev[length - _ksize - index], _rev[length - index]);\n\n index += 1;\n\n return std::make_pair(fwd_hasher.hashvalue, bwd_hasher.hashvalue);\n }\n\n bool done() const {\n return (index + _ksize > length);\n }\n\n unsigned int get_start_pos() const {\n if (!_initialized) { return 0; }\n return index - 1;\n }\n\n unsigned int get_end_pos() const {\n if (!_initialized) { return _ksize; }\n return index + _ksize - 1;\n }\n};\n*\/\n\n};\n<|endoftext|>"} {"text":"<commit_before>#include <QDebug>\n#include <QSettings>\n#include <QFileInfo>\n#include <QDir>\n#include <QThread>\n\n#include <coreplugin\/messagemanager.h>\n\n#include \"CppcheckRunner.h\"\n#include \"Settings.h\"\n\nusing namespace QtcCppcheck::Internal;\n\nnamespace\n{\n enum ErrorField\n {\n ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId,\n ErrorFieldMessage\n };\n}\n\nCppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) :\n QObject(parent), settings_ (settings), showOutput_ (false)\n{\n Q_ASSERT (settings_ != NULL);\n\n connect (&process_, SIGNAL (readyReadStandardOutput()),\n SLOT (readOutput()));\n connect (&process_, SIGNAL (readyReadStandardError()),\n SLOT (readError()));\n connect (&process_, SIGNAL (started()),\n SLOT (started()));\n connect (&process_, SIGNAL (error(QProcess::ProcessError)),\n SLOT (error(QProcess::ProcessError)));\n connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),\n SLOT (finished(int, QProcess::ExitStatus)));\n\n \/\/ Restart checking if got queue.\n connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),\n SLOT (checkQueuedFiles ()));\n}\n\nCppcheckRunner::~CppcheckRunner()\n{\n queueTimer_.stop ();\n settings_ = NULL;\n}\n\nvoid CppcheckRunner::updateSettings()\n{\n Q_ASSERT (settings_ != NULL);\n showOutput_ = settings_->showBinaryOutput ();\n runArguments_.clear ();\n runArguments_ << QLatin1String (\"-q\");\n \/\/ Pass custom params BEFORE most of runner's to shadow if some repeat.\n runArguments_ += settings_->customParameters ().split (QLatin1Char (' '));\n QString enabled = QLatin1String (\"--enable=warning,style,performance,\"\n \"portability,information,missingInclude\");\n if (settings_->checkUnused ())\n {\n enabled += QLatin1String (\",unusedFunction\");\n }\n else \/\/TODO always check with threads but rescan for unused after finish?\n {\n runArguments_ << (QLatin1String (\"-j \") +\n QString::number (QThread::idealThreadCount ()));\n }\n runArguments_ << enabled;\n if (settings_->checkInconclusive ())\n {\n runArguments_ << QLatin1String (\"--inconclusive\");\n }\n runArguments_ << QLatin1String (\"--template={file},{line},{severity},{id},{message}\");\n}\n\nvoid CppcheckRunner::checkFiles(const QStringList &fileNames)\n{\n Q_ASSERT (!fileNames.isEmpty ());\n fileCheckQueue_ += fileNames;\n fileCheckQueue_.removeDuplicates ();\n fileCheckQueue_.sort ();\n if (process_.isOpen ())\n {\n if (fileCheckQueue_ == currentlyCheckingFiles_)\n {\n process_.kill ();\n \/\/ Rechecking will be restarted on finish signal.\n }\n return;\n }\n \/\/ Delay helps to avoid double checking same file on editor change.\n const int checkDelayInMs = 200;\n if (!queueTimer_.isActive ())\n {\n queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ()));\n }\n}\n\nvoid CppcheckRunner::stopCheckhig()\n{\n fileCheckQueue_.clear ();\n if (process_.isOpen ())\n {\n process_.kill ();\n }\n}\n\nvoid CppcheckRunner::checkQueuedFiles()\n{\n if (fileCheckQueue_.isEmpty ())\n {\n return;\n }\n QString binary = settings_->binaryFile ();\n Q_ASSERT (!binary.isEmpty ());\n QStringList arguments (runArguments_);\n arguments += fileCheckQueue_;\n currentlyCheckingFiles_ = fileCheckQueue_;\n fileCheckQueue_.clear ();\n process_.start (binary, arguments);\n}\n\nvoid CppcheckRunner::readOutput()\n{\n if (!showOutput_)\n {\n return;\n }\n process_.setReadChannel (QProcess::StandardOutput);\n\n while (!process_.atEnd ())\n {\n QByteArray rawLine = process_.readLine ();\n QString line = QString::fromUtf8 (rawLine).trimmed ();\n if (line.isEmpty ())\n {\n continue;\n }\n Core::MessageManager::write (line, Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::readError()\n{\n process_.setReadChannel (QProcess::StandardError);\n\n while (!process_.atEnd ())\n {\n QByteArray rawLine = process_.readLine ();\n QString line = QString::fromUtf8 (rawLine).trimmed ();\n if (line.isEmpty ())\n {\n continue;\n }\n if (showOutput_)\n {\n Core::MessageManager::write (line, Core::MessageManager::Silent);\n }\n QStringList details = line.split (QLatin1Char (','));\n if (details.size () <= ErrorFieldMessage)\n {\n continue;\n }\n QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile));\n int lineNumber = details.at (ErrorFieldLine).toInt ();\n char type = details.at (ErrorFieldSeverity).at (0).toAscii ();\n QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage)));\n emit newTask (type, description, file, lineNumber);\n }\n}\n\nvoid CppcheckRunner::started()\n{\n if (showOutput_)\n {\n Core::MessageManager::write (tr (\"Cppcheck started\"), Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::error(QProcess::ProcessError error)\n{\n Q_UNUSED (error);\n if (showOutput_)\n {\n Core::MessageManager::write (tr (\"Cppcheck error occured\"), Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n Q_UNUSED (exitCode);\n Q_UNUSED (exitStatus);\n process_.close ();\n if (showOutput_)\n {\n Core::MessageManager::write (tr(\"Cppcheck finished\"), Core::MessageManager::Silent);\n }\n}\n<commit_msg>User now can override --enable cppcheck options<commit_after>#include <QDebug>\n#include <QSettings>\n#include <QFileInfo>\n#include <QDir>\n#include <QThread>\n\n#include <coreplugin\/messagemanager.h>\n\n#include \"CppcheckRunner.h\"\n#include \"Settings.h\"\n\nusing namespace QtcCppcheck::Internal;\n\nnamespace\n{\n enum ErrorField\n {\n ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId,\n ErrorFieldMessage\n };\n}\n\nCppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) :\n QObject(parent), settings_ (settings), showOutput_ (false)\n{\n Q_ASSERT (settings_ != NULL);\n\n connect (&process_, SIGNAL (readyReadStandardOutput()),\n SLOT (readOutput()));\n connect (&process_, SIGNAL (readyReadStandardError()),\n SLOT (readError()));\n connect (&process_, SIGNAL (started()),\n SLOT (started()));\n connect (&process_, SIGNAL (error(QProcess::ProcessError)),\n SLOT (error(QProcess::ProcessError)));\n connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),\n SLOT (finished(int, QProcess::ExitStatus)));\n\n \/\/ Restart checking if got queue.\n connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),\n SLOT (checkQueuedFiles ()));\n}\n\nCppcheckRunner::~CppcheckRunner()\n{\n queueTimer_.stop ();\n settings_ = NULL;\n}\n\nvoid CppcheckRunner::updateSettings()\n{\n Q_ASSERT (settings_ != NULL);\n showOutput_ = settings_->showBinaryOutput ();\n runArguments_.clear ();\n runArguments_ << QLatin1String (\"-q\");\n \/\/ Pass custom params BEFORE most of runner's to shadow if some repeat.\n runArguments_ += settings_->customParameters ().split (\n QLatin1Char (' '), QString::SkipEmptyParts);\n QString enabled = QLatin1String (\"--enable=warning,style,performance,\"\n \"portability,information,missingInclude\");\n \/\/ Overwrite enable with user parameters if present\n for(int i = runArguments_.size () - 1; i >= 0; --i)\n {\n if (runArguments_.at (i).startsWith (QLatin1String (\"--enable\")))\n {\n enabled = runArguments_.takeAt (i);\n break;\n }\n }\n if (settings_->checkUnused ())\n {\n enabled += QLatin1String (\",unusedFunction\");\n }\n else \/\/TODO always check with threads but rescan for unused after finish?\n {\n runArguments_ << (QLatin1String (\"-j \") +\n QString::number (QThread::idealThreadCount ()));\n }\n runArguments_ << enabled;\n if (settings_->checkInconclusive ())\n {\n runArguments_ << QLatin1String (\"--inconclusive\");\n }\n runArguments_ << QLatin1String (\"--template={file},{line},{severity},{id},{message}\");\n}\n\nvoid CppcheckRunner::checkFiles(const QStringList &fileNames)\n{\n Q_ASSERT (!fileNames.isEmpty ());\n fileCheckQueue_ += fileNames;\n fileCheckQueue_.removeDuplicates ();\n fileCheckQueue_.sort ();\n if (process_.isOpen ())\n {\n if (fileCheckQueue_ == currentlyCheckingFiles_)\n {\n process_.kill ();\n \/\/ Rechecking will be restarted on finish signal.\n }\n return;\n }\n \/\/ Delay helps to avoid double checking same file on editor change.\n const int checkDelayInMs = 200;\n if (!queueTimer_.isActive ())\n {\n queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ()));\n }\n}\n\nvoid CppcheckRunner::stopCheckhig()\n{\n fileCheckQueue_.clear ();\n if (process_.isOpen ())\n {\n process_.kill ();\n }\n}\n\nvoid CppcheckRunner::checkQueuedFiles()\n{\n if (fileCheckQueue_.isEmpty ())\n {\n return;\n }\n QString binary = settings_->binaryFile ();\n Q_ASSERT (!binary.isEmpty ());\n QStringList arguments (runArguments_);\n arguments += fileCheckQueue_;\n currentlyCheckingFiles_ = fileCheckQueue_;\n fileCheckQueue_.clear ();\n process_.start (binary, arguments);\n}\n\nvoid CppcheckRunner::readOutput()\n{\n if (!showOutput_)\n {\n return;\n }\n process_.setReadChannel (QProcess::StandardOutput);\n\n while (!process_.atEnd ())\n {\n QByteArray rawLine = process_.readLine ();\n QString line = QString::fromUtf8 (rawLine).trimmed ();\n if (line.isEmpty ())\n {\n continue;\n }\n Core::MessageManager::write (line, Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::readError()\n{\n process_.setReadChannel (QProcess::StandardError);\n\n while (!process_.atEnd ())\n {\n QByteArray rawLine = process_.readLine ();\n QString line = QString::fromUtf8 (rawLine).trimmed ();\n if (line.isEmpty ())\n {\n continue;\n }\n if (showOutput_)\n {\n Core::MessageManager::write (line, Core::MessageManager::Silent);\n }\n QStringList details = line.split (QLatin1Char (','));\n if (details.size () <= ErrorFieldMessage)\n {\n continue;\n }\n QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile));\n int lineNumber = details.at (ErrorFieldLine).toInt ();\n char type = details.at (ErrorFieldSeverity).at (0).toAscii ();\n QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage)));\n emit newTask (type, description, file, lineNumber);\n }\n}\n\nvoid CppcheckRunner::started()\n{\n if (showOutput_)\n {\n Core::MessageManager::write (tr (\"Cppcheck started\"), Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::error(QProcess::ProcessError error)\n{\n Q_UNUSED (error);\n if (showOutput_)\n {\n Core::MessageManager::write (tr (\"Cppcheck error occured\"), Core::MessageManager::Silent);\n }\n}\n\nvoid CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n Q_UNUSED (exitCode);\n Q_UNUSED (exitStatus);\n process_.close ();\n if (showOutput_)\n {\n Core::MessageManager::write (tr(\"Cppcheck finished\"), Core::MessageManager::Silent);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include <QDebug>\n#include <QLineEdit>\n#include <QComboBox>\n\n#include \"DactMacrosMenu.hh\"\n\nDactMacrosMenu::DactMacrosMenu(QWidget *parent)\n:\n\tQMenu(parent)\n{}\n\nvoid DactMacrosMenu::setModel(QSharedPointer<DactMacrosModel> model)\n{\n\tif (d_model)\n\t\tdisconnect(d_model.data(), 0, this, 0);\n\n\td_model = model;\n\n\tconnect(d_model.data(), SIGNAL(dataChanged(QModelIndex const &, QModelIndex const &)), SLOT(reload()));\n\n\treload();\n}\n\nvoid DactMacrosMenu::reload()\n{\n\t\/\/ Remove all our dynamically added menu items.\n\tforeach (QAction *action, d_macroActions)\n\t\tremoveAction(action);\n\t\n\t\/\/ All menus have been removed, now forget them.\n\td_macroActions.clear();\n\n\t\/\/ For each macro:\n\tfor (int m_row = 0, m_end = d_model->rowCount(QModelIndex()); m_row < m_end; ++m_row)\n\t{\n\t\tQModelIndex patternIndex(d_model->index(m_row, 0));\n\t\tQModelIndex replacementIndex(d_model->index(m_row, 1));\n\n\t\t\/\/ Label the menu item.\n\t\tQAction *action = addAction(patternIndex.data(Qt::DisplayRole).toString());\n\t\td_macroActions.append(action);\n\t\n\t\t\/\/ And show the replacement in the tooltip.\n\t\taction->setToolTip(replacementIndex.data(Qt::DisplayRole).toString());\n\t\n\t\t\/\/ And remember the pattern in the data section, for easy use later on.\n\t\taction->setData(patternIndex.data(Qt::UserRole).toString());\n\n\t\t\/\/ And connect the action to the method that inserts the pattern in the focussed widget.\n\t\tconnect(action, SIGNAL(triggered()), SLOT(macroActionTriggered()));\n\t}\n\n\taddSeparator();\n\n\t\/\/ A force-reload menu action, which reloads the macro file.\n\tQAction *reloadAction = addAction(\"Reload file\");\n\td_macroActions.append(reloadAction);\n\tconnect(reloadAction, SIGNAL(triggered()), SLOT(reloadActionTriggered()));\n}\n\nvoid DactMacrosMenu::macroActionTriggered()\n{\n\tQAction *action = qobject_cast<QAction *>(sender());\n\n\tif (!action)\n\t{\n\t\tqDebug() << \"Could not cast the sender of the macroActionTriggered event to a QAction pointer\";\n\t\treturn;\t\n\t}\n\t\n\tif (QLineEdit *focussedLineEdit = qobject_cast<QLineEdit *>(QApplication::focusWidget()))\n\t\tfocussedLineEdit->insert(action->data().toString());\n\t\n\telse if (QComboBox *focussedComboBox = qobject_cast<QComboBox *>(QApplication::focusWidget()))\n\t\tfocussedComboBox->lineEdit()->insert(action->data().toString());\n}\n\nvoid DactMacrosMenu::reloadActionTriggered()\n{\n\td_model->reloadFile();\n}\n<commit_msg>Reindent DactMacrosMenu.cpp.<commit_after>#include <QApplication>\n#include <QDebug>\n#include <QLineEdit>\n#include <QComboBox>\n\n#include \"DactMacrosMenu.hh\"\n\nDactMacrosMenu::DactMacrosMenu(QWidget *parent)\n:\n QMenu(parent)\n{}\n\nvoid DactMacrosMenu::setModel(QSharedPointer<DactMacrosModel> model)\n{\n if (d_model)\n disconnect(d_model.data(), 0, this, 0);\n\n d_model = model;\n\n connect(d_model.data(), SIGNAL(dataChanged(QModelIndex const &, QModelIndex const &)), SLOT(reload()));\n\n reload();\n}\n\nvoid DactMacrosMenu::reload()\n{\n \/\/ Remove all our dynamically added menu items.\n foreach (QAction *action, d_macroActions)\n removeAction(action);\n \n \/\/ All menus have been removed, now forget them.\n d_macroActions.clear();\n\n \/\/ For each macro:\n for (int m_row = 0, m_end = d_model->rowCount(QModelIndex()); m_row < m_end; ++m_row)\n {\n QModelIndex patternIndex(d_model->index(m_row, 0));\n QModelIndex replacementIndex(d_model->index(m_row, 1));\n\n \/\/ Label the menu item.\n QAction *action = addAction(patternIndex.data(Qt::DisplayRole).toString());\n d_macroActions.append(action);\n \n \/\/ And show the replacement in the tooltip.\n action->setToolTip(replacementIndex.data(Qt::DisplayRole).toString());\n \n \/\/ And remember the pattern in the data section, for easy use later on.\n action->setData(patternIndex.data(Qt::UserRole).toString());\n\n \/\/ And connect the action to the method that inserts the pattern in the focussed widget.\n connect(action, SIGNAL(triggered()), SLOT(macroActionTriggered()));\n }\n\n addSeparator();\n\n \/\/ A force-reload menu action, which reloads the macro file.\n QAction *reloadAction = addAction(\"Reload file\");\n d_macroActions.append(reloadAction);\n connect(reloadAction, SIGNAL(triggered()), SLOT(reloadActionTriggered()));\n}\n\nvoid DactMacrosMenu::macroActionTriggered()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n\n if (!action)\n {\n qDebug() << \"Could not cast the sender of the macroActionTriggered event to a QAction pointer\";\n return; \n }\n \n if (QLineEdit *focussedLineEdit = qobject_cast<QLineEdit *>(QApplication::focusWidget()))\n focussedLineEdit->insert(action->data().toString());\n \n else if (QComboBox *focussedComboBox = qobject_cast<QComboBox *>(QApplication::focusWidget()))\n focussedComboBox->lineEdit()->insert(action->data().toString());\n}\n\nvoid DactMacrosMenu::reloadActionTriggered()\n{\n d_model->reloadFile();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"DijkstraDrawer.h\"\n#include \"Options.h\"\n\n#include <algorithm>\n\nvoid DijkstraDrawer::prepareNewState()\n{\n auto state = states[animationState];\n setChanged();\n}\n\nvoid DijkstraDrawer::createLegend()\n{\n legend.clear();\n auto &cs = Options::instance().currentColorScheme;\n legend.add(LegendType::highlightedArrow, cs.highlightedEdgeColor2, \"Minimal paths\");\n legend.add(LegendType::highlightedArrow, cs.highlightedEdgeColor1, \"Inspected\");\n legend.add(LegendType::arrow, cs.edgeColor, \"Not processed yet\");\n legend.add(LegendType::node, cs.highlightedNodeColor3, \"Finished\");\n legend.add(LegendType::node, cs.highlightedNodeColor2, \"Reached\");\n legend.add(LegendType::node, cs.highlightedNodeColor1, \"Inspected\");\n legend.add(LegendType::node, cs.nodeColor, \"Not reached yet\");\n}\n\nvoid DijkstraDrawer::prepareAnimation()\n{\n GraphAnimationDrawer::prepareAnimation();\n states = graph_algorithm_capture::edgeWeightDijkstraCaptureStates(*g, Options::instance().startNode - 1, -1);\n animationLastState = states.size();\n}\n\n\nvoid DijkstraDrawer::drawAlgorithmState()\n{\n if (animationState >= int(states.size()))\n return;\n startDrawing();\n auto state = states[animationState];\n const auto &cs = Options::instance().currentColorScheme;\n \/\/ Edges -----\n \/\/ preparing edge parameters before drawing\n std::map<std::shared_ptr<GraphEdge>, std::pair<ci::Color, float>> edgeParams;\n \/\/ by default edges are drawn with edgeColor and edgeWidth (no highlighting)\n for (int nodeIdx = 0; nodeIdx < g->getNodeCount(); ++nodeIdx)\n {\n auto &node = g->getNode(nodeIdx);\n for (auto edgePtr : node)\n {\n edgeParams[edgePtr] = std::make_pair(cs.edgeColor, Options::instance().edgeWidth);\n }\n }\n\n \/\/ now the params for all dropped edges are overwritten\n for (auto &edgePtr : state.processedEdges)\n {\n edgeParams[edgePtr] = std::make_pair(cs.darkEdgeColor, Options::instance().edgeWidth);\n }\n\n \/\/ overwriting the edges of the current best paths\n for (auto &p : state.path)\n {\n if (p.second == nullptr)\n continue;\n edgeParams[p.second] = std::make_pair(cs.highlightedEdgeColor2, Options::instance().highlighedEdgeWidth);\n }\n\n \/\/ and finally the currently inspected edge\n if (state.inspectedEdge != nullptr)\n edgeParams[state.inspectedEdge] = std::make_pair(cs.highlightedEdgeColor1, Options::instance().highlighedEdgeWidth);\n\n for (auto &p : edgeParams)\n {\n drawEdge(p.first->from, p.first->to, p.second.first, p.second.second);\n }\n\n \/\/ Nodes ---------\n \/\/ Preparing open nodes\n std::vector<ci::Color> nodeHighlight(g->getNodeCount(), cs.nodeColor);\n for (auto &p : state.openNodes)\n {\n nodeHighlight[p.second] = cs.highlightedNodeColor2;\n }\n\n \/\/ Preparing closed nodes\n for (auto &p : state.closedNodes)\n {\n nodeHighlight[p.second] = cs.highlightedNodeColor3;\n }\n\n \/\/ Preparing current node\n if (state.inspectedNode != -1)\n {\n nodeHighlight[state.inspectedNode] = cs.highlightedNodeColor1;\n }\n\n \/\/ Drawing nodes\n for (int i = 0; i < g->getNodeCount(); ++i)\n {\n nodeHandlers[i]->draw(nodeHighlight[i]);\n }\n\n \/\/ Labels -----\n \/\/ preparing edge label colors\n std::map<std::shared_ptr<GraphEdge>, ci::ColorA> edgeLabelColors; \n for (auto &edgePtr : edgeParams)\n {\n edgeLabelColors[edgePtr.first] = edgePtr.second.first;\n }\n drawLabels(edgeLabelColors);\n \n drawStepDescription(state.description); \n}\n\n\nvoid DijkstraDrawer::drawAlgorithmResult()\n{\n startDrawing();\n drawEdges();\n auto tree = edgeWeightDijkstra(*g, Options::instance().startNode - 1, -1);\n for (int i = 0; i < int(tree.size()); ++i)\n {\n auto edgePtr = tree[i].second;\n if (edgePtr == nullptr)\n continue;\n drawEdge(edgePtr->from, edgePtr->to, Options::instance().currentColorScheme.highlightedEdgeColor2, Options::instance().highlighedEdgeWidth);\n }\n drawNodes();\n drawLabels();\n}<commit_msg>Added dropped edges to Dijsktra's legend<commit_after>#include \"stdafx.h\"\n#include \"DijkstraDrawer.h\"\n#include \"Options.h\"\n\n#include <algorithm>\n\nvoid DijkstraDrawer::prepareNewState()\n{\n auto state = states[animationState];\n setChanged();\n}\n\nvoid DijkstraDrawer::createLegend()\n{\n legend.clear();\n auto &cs = Options::instance().currentColorScheme;\n legend.add(LegendType::highlightedArrow, cs.highlightedEdgeColor2, \"Minimal paths\");\n legend.add(LegendType::highlightedArrow, cs.highlightedEdgeColor1, \"Currently inspected\");\n legend.add(LegendType::arrow, cs.darkEdgeColor, \"Processed and ignored\");\n legend.add(LegendType::arrow, cs.edgeColor, \"Not processed\");\n legend.add(LegendType::node, cs.highlightedNodeColor3, \"Finished\");\n legend.add(LegendType::node, cs.highlightedNodeColor2, \"Reached but not processed\");\n legend.add(LegendType::node, cs.highlightedNodeColor1, \"Currently inspected\");\n legend.add(LegendType::node, cs.nodeColor, \"Not reached\");\n}\n\nvoid DijkstraDrawer::prepareAnimation()\n{\n GraphAnimationDrawer::prepareAnimation();\n states = graph_algorithm_capture::edgeWeightDijkstraCaptureStates(*g, Options::instance().startNode - 1, -1);\n animationLastState = states.size();\n}\n\n\nvoid DijkstraDrawer::drawAlgorithmState()\n{\n if (animationState >= int(states.size()))\n return;\n startDrawing();\n auto state = states[animationState];\n const auto &cs = Options::instance().currentColorScheme;\n \/\/ Edges -----\n \/\/ preparing edge parameters before drawing\n std::map<std::shared_ptr<GraphEdge>, std::pair<ci::Color, float>> edgeParams;\n \/\/ by default edges are drawn with edgeColor and edgeWidth (no highlighting)\n for (int nodeIdx = 0; nodeIdx < g->getNodeCount(); ++nodeIdx)\n {\n auto &node = g->getNode(nodeIdx);\n for (auto edgePtr : node)\n {\n edgeParams[edgePtr] = std::make_pair(cs.edgeColor, Options::instance().edgeWidth);\n }\n }\n\n \/\/ now the params for all dropped edges are overwritten\n for (auto &edgePtr : state.processedEdges)\n {\n edgeParams[edgePtr] = std::make_pair(cs.darkEdgeColor, Options::instance().edgeWidth);\n }\n\n \/\/ overwriting the edges of the current best paths\n for (auto &p : state.path)\n {\n if (p.second == nullptr)\n continue;\n edgeParams[p.second] = std::make_pair(cs.highlightedEdgeColor2, Options::instance().highlighedEdgeWidth);\n }\n\n \/\/ and finally the currently inspected edge\n if (state.inspectedEdge != nullptr)\n edgeParams[state.inspectedEdge] = std::make_pair(cs.highlightedEdgeColor1, Options::instance().highlighedEdgeWidth);\n\n for (auto &p : edgeParams)\n {\n drawEdge(p.first->from, p.first->to, p.second.first, p.second.second);\n }\n\n \/\/ Nodes ---------\n \/\/ Preparing open nodes\n std::vector<ci::Color> nodeHighlight(g->getNodeCount(), cs.nodeColor);\n for (auto &p : state.openNodes)\n {\n nodeHighlight[p.second] = cs.highlightedNodeColor2;\n }\n\n \/\/ Preparing closed nodes\n for (auto &p : state.closedNodes)\n {\n nodeHighlight[p.second] = cs.highlightedNodeColor3;\n }\n\n \/\/ Preparing current node\n if (state.inspectedNode != -1)\n {\n nodeHighlight[state.inspectedNode] = cs.highlightedNodeColor1;\n }\n\n \/\/ Drawing nodes\n for (int i = 0; i < g->getNodeCount(); ++i)\n {\n nodeHandlers[i]->draw(nodeHighlight[i]);\n }\n\n \/\/ Labels -----\n \/\/ preparing edge label colors\n std::map<std::shared_ptr<GraphEdge>, ci::ColorA> edgeLabelColors; \n for (auto &edgePtr : edgeParams)\n {\n edgeLabelColors[edgePtr.first] = edgePtr.second.first;\n }\n drawLabels(edgeLabelColors);\n \n drawStepDescription(state.description); \n}\n\n\nvoid DijkstraDrawer::drawAlgorithmResult()\n{\n startDrawing();\n drawEdges();\n auto tree = edgeWeightDijkstra(*g, Options::instance().startNode - 1, -1);\n for (int i = 0; i < int(tree.size()); ++i)\n {\n auto edgePtr = tree[i].second;\n if (edgePtr == nullptr)\n continue;\n drawEdge(edgePtr->from, edgePtr->to, Options::instance().currentColorScheme.highlightedEdgeColor2, Options::instance().highlighedEdgeWidth);\n }\n drawNodes();\n drawLabels();\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2012 Kolibre\n *\n * This file is part of kolibre-clientcore.\n *\n * Kolibre-clientcore is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * Kolibre-clientcore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with kolibre-clientcore. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"FileSystemNode.h\"\n#include \"DaisyBookNode.h\"\n#include \"Defines.h\"\n#include \"config.h\"\n#include \"CommandQueue2\/CommandQueue.h\"\n#include \"Commands\/InternalCommands.h\"\n#include \"Utils.h\"\n\n#include <Narrator.h>\n#include <NaviEngine.h>\n\n#include <sstream>\n#include <log4cxx\/logger.h>\n\n\/\/ create logger which will become a child to logger kolibre.clientcore\nlog4cxx::LoggerPtr fsNodeLog(log4cxx::Logger::getLogger(\"kolibre.clientcore.filesystemnode\"));\n\nusing namespace naviengine;\n\nFileSystemNode::FileSystemNode(const std::string name, const std::string path)\n{\n LOG4CXX_TRACE(fsNodeLog, \"Constructor\");\n name_ = \"FileSystem_\" + name;\n fsName_ = name;\n fsPath_ = path;\n}\n\nFileSystemNode::~FileSystemNode()\n{\n LOG4CXX_TRACE(fsNodeLog, \"Destructor\");\n}\n\n\/\/ NaviEngine functions\n\nbool FileSystemNode::next(NaviEngine& navi)\n{\n bool ret = MenuNode::next(navi);\n currentChild_ = navi.getCurrentChoice();\n announceSelection();\n return ret;\n}\n\nbool FileSystemNode::prev(NaviEngine& navi)\n{\n bool ret = MenuNode::prev(navi);\n currentChild_ = navi.getCurrentChoice();\n announceSelection();\n return ret;\n}\n\nbool FileSystemNode::menu(NaviEngine& navi)\n{\n return navi.openMenu(navi.buildContextMenu());\n}\n\nbool FileSystemNode::up(NaviEngine& navi)\n{\n bool ret = MenuNode::up(navi);\n return ret;\n}\n\nbool FileSystemNode::onOpen(NaviEngine& navi)\n{\n navi.setCurrentChoice(NULL);\n clearNodes();\n navilist_.items.clear();\n\n \/\/ Create sources defined in MediaSourceManager\n LOG4CXX_INFO(fsNodeLog, \"Searching for supported content in path '\" << fsPath_ << \"'\");\n\n std::vector<std::string> uris = Utils::recursiveSearchByFilename(fsPath_, \"ncc.html\");\n for (int i = 0; i < uris.size(); i++)\n {\n \/\/ create book node\n LOG4CXX_DEBUG(fsNodeLog, \"Creating book node: '\" << uris[i] << \"'\");\n DaisyBookNode* node = new DaisyBookNode(uris[0]);\n\n \/\/ invent a name for it\n ostringstream oss;\n oss << (i+1);\n node->name_ = \"title_\" + oss.str();\n\n \/\/ add node\n addNode(node);\n\n \/\/ create a NaviListItem and store it in list for the NaviList signal\n NaviListItem item(node->uri_, node->name_);\n navilist_.items.push_back(item);\n\n }\n\n if (navi.getCurrentChoice() == NULL && numberOfChildren() > 0)\n {\n navi.setCurrentChoice(firstChild());\n currentChild_ = firstChild();\n }\n\n currentChild_ = navi.getCurrentChoice();\n announce();\n\n if (numberOfChildren() == 1)\n {\n LOG4CXX_INFO(fsNodeLog, \"Opening the only child\");\n \/\/ wait for narrator before sending command\n usleep(500000); while (Narrator::Instance()->isSpeaking()) usleep(100000);\n cq2::Command<INTERNAL_COMMAND> c(COMMAND_DOWN);\n c();\n }\n\n return true;\n}\n\nvoid FileSystemNode::beforeOnOpen()\n{\n Narrator::Instance()->play(_N(\"updating device\"));\n}\n\nbool FileSystemNode::process(NaviEngine& navi, int command, void* data)\n{\n return false;\n}\n\nbool FileSystemNode::narrateName()\n{\n const bool isSelfNarrated = true;\n std::string lcName = Utils::toLower(fsName_);\n if (Utils::contains(lcName, \"usb\"))\n Narrator::Instance()->play(_N(\"usb device\"));\n else if (Utils::contains(lcName, \"sd\"))\n Narrator::Instance()->play(_N(\"sd device\"));\n else if (Utils::contains(lcName, \"cdrom\"))\n Narrator::Instance()->play(_N(\"cdrom device\"));\n else\n Narrator::Instance()->play(_N(\"local device\"));\n return isSelfNarrated;\n}\n\nbool FileSystemNode::narrateInfo()\n{\n const bool isSelfNarrated = true;\n Narrator::Instance()->play(_N(\"choose option using left and right arrows, open using play button\"));\n Narrator::Instance()->playLongpause();\n announceSelection();\n return isSelfNarrated;\n}\n\nbool FileSystemNode::onNarrate()\n{\n const bool isSelfNarrated = true;\n return isSelfNarrated;\n}\n\nbool FileSystemNode::onRender()\n{\n const bool isSelfRendered = true;\n return isSelfRendered;\n}\n\nvoid FileSystemNode::announce()\n{\n cq2::Command<NaviList> naviList(navilist_);\n naviList();\n\n int numItems = numberOfChildren();\n\n if (numItems == 0)\n {\n Narrator::Instance()->play(_N(\"device contains no publications\"));\n }\n else if (numItems == 1)\n {\n Narrator::Instance()->setParameter(\"1\", numItems);\n Narrator::Instance()->play(_N(\"device contains {1} publication\"));\n }\n else if (numItems > 1)\n {\n Narrator::Instance()->setParameter(\"2\", numItems);\n Narrator::Instance()->play(_N(\"device contains {2} publications\"));\n }\n Narrator::Instance()->playLongpause();\n\n announceSelection();\n}\n\nvoid FileSystemNode::announceSelection()\n{\n int currentChoice = 0;\n AnyNode* current = currentChild_;\n\n if ((firstChild() != NULL) && (current != NULL))\n {\n while (firstChild() != current)\n {\n currentChoice++;\n current = current->prev_;\n }\n\n Narrator::Instance()->setParameter(\"1\", currentChoice + 1);\n Narrator::Instance()->play(_N(\"publication no. {1}\"));\n \/\/Narrator::Instance()->play(currentChild_->name_.c_str());\n\n NaviListItem item = navilist_.items[currentChoice];\n cq2::Command<NaviListItem> naviItem(item);\n naviItem();\n }\n}\n<commit_msg>Create DaisyBookNode with correct uri<commit_after>\/*\n * Copyright (C) 2012 Kolibre\n *\n * This file is part of kolibre-clientcore.\n *\n * Kolibre-clientcore is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * Kolibre-clientcore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with kolibre-clientcore. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"FileSystemNode.h\"\n#include \"DaisyBookNode.h\"\n#include \"Defines.h\"\n#include \"config.h\"\n#include \"CommandQueue2\/CommandQueue.h\"\n#include \"Commands\/InternalCommands.h\"\n#include \"Utils.h\"\n\n#include <Narrator.h>\n#include <NaviEngine.h>\n\n#include <sstream>\n#include <log4cxx\/logger.h>\n\n\/\/ create logger which will become a child to logger kolibre.clientcore\nlog4cxx::LoggerPtr fsNodeLog(log4cxx::Logger::getLogger(\"kolibre.clientcore.filesystemnode\"));\n\nusing namespace naviengine;\n\nFileSystemNode::FileSystemNode(const std::string name, const std::string path)\n{\n LOG4CXX_TRACE(fsNodeLog, \"Constructor\");\n name_ = \"FileSystem_\" + name;\n fsName_ = name;\n fsPath_ = path;\n}\n\nFileSystemNode::~FileSystemNode()\n{\n LOG4CXX_TRACE(fsNodeLog, \"Destructor\");\n}\n\n\/\/ NaviEngine functions\n\nbool FileSystemNode::next(NaviEngine& navi)\n{\n bool ret = MenuNode::next(navi);\n currentChild_ = navi.getCurrentChoice();\n announceSelection();\n return ret;\n}\n\nbool FileSystemNode::prev(NaviEngine& navi)\n{\n bool ret = MenuNode::prev(navi);\n currentChild_ = navi.getCurrentChoice();\n announceSelection();\n return ret;\n}\n\nbool FileSystemNode::menu(NaviEngine& navi)\n{\n return navi.openMenu(navi.buildContextMenu());\n}\n\nbool FileSystemNode::up(NaviEngine& navi)\n{\n bool ret = MenuNode::up(navi);\n return ret;\n}\n\nbool FileSystemNode::onOpen(NaviEngine& navi)\n{\n navi.setCurrentChoice(NULL);\n clearNodes();\n navilist_.items.clear();\n\n \/\/ Create sources defined in MediaSourceManager\n LOG4CXX_INFO(fsNodeLog, \"Searching for supported content in path '\" << fsPath_ << \"'\");\n\n std::vector<std::string> uris = Utils::recursiveSearchByFilename(fsPath_, \"ncc.html\");\n for (int i = 0; i < uris.size(); i++)\n {\n \/\/ create book node\n LOG4CXX_DEBUG(fsNodeLog, \"Creating book node: '\" << uris[i] << \"'\");\n DaisyBookNode* node = new DaisyBookNode(uris[i]);\n\n \/\/ invent a name for it\n ostringstream oss;\n oss << (i+1);\n node->name_ = \"title_\" + oss.str();\n\n \/\/ add node\n addNode(node);\n\n \/\/ create a NaviListItem and store it in list for the NaviList signal\n NaviListItem item(node->uri_, node->name_);\n navilist_.items.push_back(item);\n\n }\n\n if (navi.getCurrentChoice() == NULL && numberOfChildren() > 0)\n {\n navi.setCurrentChoice(firstChild());\n currentChild_ = firstChild();\n }\n\n currentChild_ = navi.getCurrentChoice();\n announce();\n\n if (numberOfChildren() == 1)\n {\n LOG4CXX_INFO(fsNodeLog, \"Opening the only child\");\n \/\/ wait for narrator before sending command\n usleep(500000); while (Narrator::Instance()->isSpeaking()) usleep(100000);\n cq2::Command<INTERNAL_COMMAND> c(COMMAND_DOWN);\n c();\n }\n\n return true;\n}\n\nvoid FileSystemNode::beforeOnOpen()\n{\n Narrator::Instance()->play(_N(\"updating device\"));\n}\n\nbool FileSystemNode::process(NaviEngine& navi, int command, void* data)\n{\n return false;\n}\n\nbool FileSystemNode::narrateName()\n{\n const bool isSelfNarrated = true;\n std::string lcName = Utils::toLower(fsName_);\n if (Utils::contains(lcName, \"usb\"))\n Narrator::Instance()->play(_N(\"usb device\"));\n else if (Utils::contains(lcName, \"sd\"))\n Narrator::Instance()->play(_N(\"sd device\"));\n else if (Utils::contains(lcName, \"cdrom\"))\n Narrator::Instance()->play(_N(\"cdrom device\"));\n else\n Narrator::Instance()->play(_N(\"local device\"));\n return isSelfNarrated;\n}\n\nbool FileSystemNode::narrateInfo()\n{\n const bool isSelfNarrated = true;\n Narrator::Instance()->play(_N(\"choose option using left and right arrows, open using play button\"));\n Narrator::Instance()->playLongpause();\n announceSelection();\n return isSelfNarrated;\n}\n\nbool FileSystemNode::onNarrate()\n{\n const bool isSelfNarrated = true;\n return isSelfNarrated;\n}\n\nbool FileSystemNode::onRender()\n{\n const bool isSelfRendered = true;\n return isSelfRendered;\n}\n\nvoid FileSystemNode::announce()\n{\n cq2::Command<NaviList> naviList(navilist_);\n naviList();\n\n int numItems = numberOfChildren();\n\n if (numItems == 0)\n {\n Narrator::Instance()->play(_N(\"device contains no publications\"));\n }\n else if (numItems == 1)\n {\n Narrator::Instance()->setParameter(\"1\", numItems);\n Narrator::Instance()->play(_N(\"device contains {1} publication\"));\n }\n else if (numItems > 1)\n {\n Narrator::Instance()->setParameter(\"2\", numItems);\n Narrator::Instance()->play(_N(\"device contains {2} publications\"));\n }\n Narrator::Instance()->playLongpause();\n\n announceSelection();\n}\n\nvoid FileSystemNode::announceSelection()\n{\n int currentChoice = 0;\n AnyNode* current = currentChild_;\n\n if ((firstChild() != NULL) && (current != NULL))\n {\n while (firstChild() != current)\n {\n currentChoice++;\n current = current->prev_;\n }\n\n Narrator::Instance()->setParameter(\"1\", currentChoice + 1);\n Narrator::Instance()->play(_N(\"publication no. {1}\"));\n \/\/Narrator::Instance()->play(currentChild_->name_.c_str());\n\n NaviListItem item = navilist_.items[currentChoice];\n cq2::Command<NaviListItem> naviItem(item);\n naviItem();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <memory>\n\n#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Substitute.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n#include \"Image.h\"\n#include \"LLVM_Output.h\"\n#include \"RemoveTrivialForLoops.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ Replace the parameter objects of loads\/stores witha new parameter\n\/\/ object.\nclass ReplaceParams : public IRMutator {\n const std::map<std::string, Parameter> &replacements;\n\n using IRMutator::visit;\n\n void visit(const Load *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceParams(const std::map<std::string, Parameter> &replacements)\n : replacements(replacements) {}\n};\n\nStmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) {\n return ReplaceParams(replacements).mutate(s);\n}\n\n\nclass InjectHexagonRpc : public IRMutator {\n std::map<std::string, Expr> state_vars;\n\n Module device_code;\n\n \/** Alignment info for Int(32) variables in scope, so we don't\n * lose the information when creating Hexagon kernels. *\/\n Scope<ModulusRemainder> alignment_info;\n\n Expr state_var(const std::string& name, Type type) {\n Expr& var = state_vars[name];\n if (!var.defined()) {\n Buffer storage(type, {}, nullptr, name + \"_buf\");\n *(void **)storage.host_ptr() = nullptr;\n var = Load::make(type_of<void*>(), name + \"_buf\", 0, storage, Parameter());\n }\n return var;\n }\n\n Expr state_var_ptr(const std::string& name, Type type) {\n Expr var = state_var(name, type);\n return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic);\n }\n\n Expr module_state() {\n return state_var(\"hexagon_module_state\", type_of<void*>());\n }\n\n Expr module_state_ptr() {\n return state_var_ptr(\"hexagon_module_state\", type_of<void*>());\n }\n\n \/\/ Create a Buffer containing the given buffer\/size, and return an\n \/\/ expression for a pointer to the first element.\n Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) {\n Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name);\n memcpy(code.host_ptr(), buffer, (int)size);\n\n Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter());\n return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic);\n }\n\n Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) {\n Expr call = Call::make(Int(32), name, args, Call::Extern);\n string call_result_name = unique_name(name + \"_result\");\n Expr call_result_var = Variable::make(Int(32), call_result_name);\n return LetStmt::make(call_result_name, call,\n AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));\n }\n\n using IRMutator::visit;\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n \/\/ Unrolling or loop partitioning might generate multiple\n \/\/ loops with the same name, so we need to unique them.\n std::string hex_name = \"hex_\" + loop->name;\n\n Stmt body = remove_trivial_for_loops(loop, true \/*device_loops*\/);\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(body);\n\n \/\/ Make an argument list, and generate a function in the\n \/\/ device_code module. The hexagon runtime code expects\n \/\/ the arguments to appear in the order of (input buffers,\n \/\/ output buffers, input scalars). There's a huge hack\n \/\/ here, in that the scalars must be last for the scalar\n \/\/ arguments to shadow the symbols of the buffer.\n std::vector<LoweredArgument> input_buffers, output_buffers;\n std::map<std::string, Parameter> replacement_params;\n for (const auto& i : c.buffers) {\n if (i.second.write) {\n Argument::Kind kind = Argument::OutputBuffer;\n output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n } else {\n Argument::Kind kind = Argument::InputBuffer;\n input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n }\n\n \/\/ Build a parameter to replace.\n Parameter p(i.second.type, true, i.second.dimensions);\n \/\/ Assert that buffers are aligned to one HVX\n \/\/ vector. Generally, they should be page aligned ION\n \/\/ buffers, so this should be a reasonable\n \/\/ requirement.\n const int alignment = 128;\n p.set_host_alignment(alignment);\n \/\/ The other parameter constraints are already\n \/\/ accounted for by the closure grabbing those\n \/\/ arguments, so we only need to provide the host\n \/\/ alignment.\n replacement_params[i.first] = p;\n\n \/\/ Add an assert to the body that validates the\n \/\/ alignment of the buffer.\n if (!device_code.target().has_feature(Target::NoAsserts)) {\n Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + \".host\"));\n Expr error = Call::make(Int(32), \"halide_error_unaligned_host_ptr\",\n {i.first, alignment}, Call::Extern);\n body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body);\n }\n }\n body = replace_params(body, replacement_params);\n\n std::vector<LoweredArgument> args;\n args.insert(args.end(), input_buffers.begin(), input_buffers.end());\n args.insert(args.end(), output_buffers.begin(), output_buffers.end());\n for (const auto& i : c.vars) {\n LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0);\n if (alignment_info.contains(i.first)) {\n arg.alignment = alignment_info.get(i.first);\n }\n args.push_back(arg);\n }\n device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector<Expr> arg_sizes;\n std::vector<Expr> arg_ptrs;\n std::vector<Expr> arg_flags;\n\n for (const auto& i : c.buffers) {\n \/\/ sizeof(pointer) will always fit into int32\n arg_sizes.push_back(Expr((int32_t)sizeof(buffer_t*)));\n arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + \".buffer\"));\n int flags = 0;\n if (i.second.read) flags |= 0x1;\n if (i.second.write) flags |= 0x2;\n arg_flags.push_back(flags);\n }\n for (const auto& i : c.vars) {\n Expr arg = Variable::make(i.second, i.first);\n Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic);\n\n \/\/ sizeof(scalar-type) will always fit into int32\n arg_sizes.push_back(Expr((int32_t)i.second.bytes()));\n arg_ptrs.push_back(arg_ptr);\n arg_flags.push_back(0x0);\n }\n\n \/\/ The argument list is terminated with an argument of size 0.\n arg_sizes.push_back(Expr((int32_t)0));\n\n std::string pipeline_name = hex_name + \"_argv\";\n std::vector<Expr> params;\n params.push_back(module_state());\n params.push_back(pipeline_name);\n params.push_back(state_var_ptr(hex_name, type_of<int>()));\n params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic));\n params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic));\n params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic));\n\n stmt = call_extern_and_assert(\"halide_hexagon_run\", params);\n\n } else {\n IRMutator::visit(loop);\n }\n }\n\n void visit(const Let *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\n void visit(const LetStmt *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\npublic:\n InjectHexagonRpc(const Target &target) : device_code(\"hexagon\", target) {}\n\n Stmt inject(Stmt s) {\n s = mutate(s);\n\n \/\/ Skip if there are no device kernels.\n if (device_code.functions().empty()) {\n return s;\n }\n\n \/\/ Compile the device code.\n std::vector<uint8_t> object;\n#if 0\n compile_module_to_shared_object(device_code, object);\n \/\/compile_module_to_shared_object(device_code, \"\/tmp\/hex.so\");\n#else\n debug(1) << \"Hexagon device code module: \" << device_code << \"\\n\";\n device_code.compile(Outputs().bitcode(\"hex.bc\"));\n\n string hex_command = \"${HL_HEXAGON_TOOLS}\/bin\/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so\";\n if (device_code.target().has_feature(Target::HVX_v62)) {\n hex_command += \" -mv62\";\n }\n if (device_code.target().has_feature(Target::HVX_128)) {\n hex_command += \" -mhvx-double\";\n }\n int result = system(hex_command.c_str());\n internal_assert(result == 0) << \"hexagon-clang failed\\n\";\n\n std::ifstream so(\"hex.so\", std::ios::binary | std::ios::ate);\n object.resize(so.tellg());\n so.seekg(0, std::ios::beg);\n so.read(reinterpret_cast<char*>(&object[0]), object.size());\n#endif\n\n \/\/ Put the compiled object into a buffer.\n size_t code_size = object.size();\n Expr code_ptr = buffer_ptr(&object[0], code_size, \"hexagon_code\");\n\n \/\/ Wrap the statement in calls to halide_initialize_kernels.\n Stmt init_kernels = call_extern_and_assert(\"halide_hexagon_initialize_kernels\",\n {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)});\n s = Block::make(init_kernels, s);\n\n return s;\n }\n};\n\n}\n\nStmt inject_hexagon_rpc(Stmt s, const Target &host_target) {\n Target target(Target::NoOS, Target::Hexagon, 32);\n for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) {\n if (host_target.has_feature(i)) {\n target = target.with_feature(i);\n }\n }\n InjectHexagonRpc injector(target);\n s = injector.inject(s);\n return s;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Halide\n<commit_msg>arg_sizes need to be identical types, so use uint64_t everywhere<commit_after>#include <iostream>\n#include <fstream>\n#include <memory>\n\n#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Substitute.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n#include \"Image.h\"\n#include \"LLVM_Output.h\"\n#include \"RemoveTrivialForLoops.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ Replace the parameter objects of loads\/stores witha new parameter\n\/\/ object.\nclass ReplaceParams : public IRMutator {\n const std::map<std::string, Parameter> &replacements;\n\n using IRMutator::visit;\n\n void visit(const Load *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceParams(const std::map<std::string, Parameter> &replacements)\n : replacements(replacements) {}\n};\n\nStmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) {\n return ReplaceParams(replacements).mutate(s);\n}\n\n\nclass InjectHexagonRpc : public IRMutator {\n std::map<std::string, Expr> state_vars;\n\n Module device_code;\n\n \/** Alignment info for Int(32) variables in scope, so we don't\n * lose the information when creating Hexagon kernels. *\/\n Scope<ModulusRemainder> alignment_info;\n\n Expr state_var(const std::string& name, Type type) {\n Expr& var = state_vars[name];\n if (!var.defined()) {\n Buffer storage(type, {}, nullptr, name + \"_buf\");\n *(void **)storage.host_ptr() = nullptr;\n var = Load::make(type_of<void*>(), name + \"_buf\", 0, storage, Parameter());\n }\n return var;\n }\n\n Expr state_var_ptr(const std::string& name, Type type) {\n Expr var = state_var(name, type);\n return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic);\n }\n\n Expr module_state() {\n return state_var(\"hexagon_module_state\", type_of<void*>());\n }\n\n Expr module_state_ptr() {\n return state_var_ptr(\"hexagon_module_state\", type_of<void*>());\n }\n\n \/\/ Create a Buffer containing the given buffer\/size, and return an\n \/\/ expression for a pointer to the first element.\n Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) {\n Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name);\n memcpy(code.host_ptr(), buffer, (int)size);\n\n Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter());\n return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic);\n }\n\n Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) {\n Expr call = Call::make(Int(32), name, args, Call::Extern);\n string call_result_name = unique_name(name + \"_result\");\n Expr call_result_var = Variable::make(Int(32), call_result_name);\n return LetStmt::make(call_result_name, call,\n AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));\n }\n\n using IRMutator::visit;\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n \/\/ Unrolling or loop partitioning might generate multiple\n \/\/ loops with the same name, so we need to unique them.\n std::string hex_name = \"hex_\" + loop->name;\n\n Stmt body = remove_trivial_for_loops(loop, true \/*device_loops*\/);\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(body);\n\n \/\/ Make an argument list, and generate a function in the\n \/\/ device_code module. The hexagon runtime code expects\n \/\/ the arguments to appear in the order of (input buffers,\n \/\/ output buffers, input scalars). There's a huge hack\n \/\/ here, in that the scalars must be last for the scalar\n \/\/ arguments to shadow the symbols of the buffer.\n std::vector<LoweredArgument> input_buffers, output_buffers;\n std::map<std::string, Parameter> replacement_params;\n for (const auto& i : c.buffers) {\n if (i.second.write) {\n Argument::Kind kind = Argument::OutputBuffer;\n output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n } else {\n Argument::Kind kind = Argument::InputBuffer;\n input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n }\n\n \/\/ Build a parameter to replace.\n Parameter p(i.second.type, true, i.second.dimensions);\n \/\/ Assert that buffers are aligned to one HVX\n \/\/ vector. Generally, they should be page aligned ION\n \/\/ buffers, so this should be a reasonable\n \/\/ requirement.\n const int alignment = 128;\n p.set_host_alignment(alignment);\n \/\/ The other parameter constraints are already\n \/\/ accounted for by the closure grabbing those\n \/\/ arguments, so we only need to provide the host\n \/\/ alignment.\n replacement_params[i.first] = p;\n\n \/\/ Add an assert to the body that validates the\n \/\/ alignment of the buffer.\n if (!device_code.target().has_feature(Target::NoAsserts)) {\n Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + \".host\"));\n Expr error = Call::make(Int(32), \"halide_error_unaligned_host_ptr\",\n {i.first, alignment}, Call::Extern);\n body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body);\n }\n }\n body = replace_params(body, replacement_params);\n\n std::vector<LoweredArgument> args;\n args.insert(args.end(), input_buffers.begin(), input_buffers.end());\n args.insert(args.end(), output_buffers.begin(), output_buffers.end());\n for (const auto& i : c.vars) {\n LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0);\n if (alignment_info.contains(i.first)) {\n arg.alignment = alignment_info.get(i.first);\n }\n args.push_back(arg);\n }\n device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector<Expr> arg_sizes;\n std::vector<Expr> arg_ptrs;\n std::vector<Expr> arg_flags;\n\n for (const auto& i : c.buffers) {\n arg_sizes.push_back(Expr((uint64_t) sizeof(buffer_t*)));\n arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + \".buffer\"));\n int flags = 0;\n if (i.second.read) flags |= 0x1;\n if (i.second.write) flags |= 0x2;\n arg_flags.push_back(flags);\n }\n for (const auto& i : c.vars) {\n Expr arg = Variable::make(i.second, i.first);\n Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic);\n\n \/\/ sizeof(scalar-type) will always fit into int32\n arg_sizes.push_back(Expr((uint64_t) i.second.bytes()));\n arg_ptrs.push_back(arg_ptr);\n arg_flags.push_back(0x0);\n }\n\n \/\/ The argument list is terminated with an argument of size 0.\n arg_sizes.push_back(Expr((uint64_t) 0));\n\n std::string pipeline_name = hex_name + \"_argv\";\n std::vector<Expr> params;\n params.push_back(module_state());\n params.push_back(pipeline_name);\n params.push_back(state_var_ptr(hex_name, type_of<int>()));\n params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic));\n params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic));\n params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic));\n\n stmt = call_extern_and_assert(\"halide_hexagon_run\", params);\n\n } else {\n IRMutator::visit(loop);\n }\n }\n\n void visit(const Let *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\n void visit(const LetStmt *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\npublic:\n InjectHexagonRpc(const Target &target) : device_code(\"hexagon\", target) {}\n\n Stmt inject(Stmt s) {\n s = mutate(s);\n\n \/\/ Skip if there are no device kernels.\n if (device_code.functions().empty()) {\n return s;\n }\n\n \/\/ Compile the device code.\n std::vector<uint8_t> object;\n#if 0\n compile_module_to_shared_object(device_code, object);\n \/\/compile_module_to_shared_object(device_code, \"\/tmp\/hex.so\");\n#else\n debug(1) << \"Hexagon device code module: \" << device_code << \"\\n\";\n device_code.compile(Outputs().bitcode(\"hex.bc\"));\n\n string hex_command = \"${HL_HEXAGON_TOOLS}\/bin\/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so\";\n if (device_code.target().has_feature(Target::HVX_v62)) {\n hex_command += \" -mv62\";\n }\n if (device_code.target().has_feature(Target::HVX_128)) {\n hex_command += \" -mhvx-double\";\n }\n int result = system(hex_command.c_str());\n internal_assert(result == 0) << \"hexagon-clang failed\\n\";\n\n std::ifstream so(\"hex.so\", std::ios::binary | std::ios::ate);\n object.resize(so.tellg());\n so.seekg(0, std::ios::beg);\n so.read(reinterpret_cast<char*>(&object[0]), object.size());\n#endif\n\n \/\/ Put the compiled object into a buffer.\n size_t code_size = object.size();\n Expr code_ptr = buffer_ptr(&object[0], code_size, \"hexagon_code\");\n\n \/\/ Wrap the statement in calls to halide_initialize_kernels.\n Stmt init_kernels = call_extern_and_assert(\"halide_hexagon_initialize_kernels\",\n {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)});\n s = Block::make(init_kernels, s);\n\n return s;\n }\n};\n\n}\n\nStmt inject_hexagon_rpc(Stmt s, const Target &host_target) {\n Target target(Target::NoOS, Target::Hexagon, 32);\n for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) {\n if (host_target.has_feature(i)) {\n target = target.with_feature(i);\n }\n }\n InjectHexagonRpc injector(target);\n s = injector.inject(s);\n return s;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Halide\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <fstream>\n\n#include <sys\/stat.h>\n\n#include \"cpp_utils\/stop_watch.hpp\"\n\n#include \"trainer\/rbm_training_context.hpp\"\n#include \"layer_traits.hpp\"\n#include \"dbn_traits.hpp\"\n\nnamespace dll {\n\ntemplate <typename R>\nstruct default_rbm_watcher {\n cpp::stop_watch<std::chrono::seconds> watch;\n\n template <typename RBM = R>\n void training_begin(const RBM& rbm) {\n using rbm_t = std::decay_t<RBM>;\n\n std::cout << \"Train RBM with \\\"\" << RBM::desc::template trainer_t<RBM, false>::name() << \"\\\"\" << std::endl;\n\n rbm.display();\n\n std::cout << \"With parameters:\" << std::endl;\n\n if(std::is_same<typename rbm_t::weight, float>::value){\n std::cout << \" single-precision\" << std::endl;\n } else if(std::is_same<typename rbm_t::weight, double>::value){\n std::cout << \" double-precision\" << std::endl;\n } else {\n std::cout << \" unknown-precision (something is wrong...)\" << std::endl;\n }\n\n std::cout << \" learning_rate=\" << rbm.learning_rate << std::endl;\n std::cout << \" batch_size=\" << get_batch_size(rbm) << std::endl;\n\n if (rbm_layer_traits<RBM>::has_momentum()) {\n std::cout << \" momentum=\" << rbm.momentum << std::endl;\n }\n\n if (rbm_layer_traits<RBM>::has_clip_gradients()) {\n std::cout << \" gradient clip=\" << rbm.gradient_clip << std::endl;\n }\n\n if (w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L1)=\" << rbm.l1_weight_cost << std::endl;\n }\n\n if (w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L2)=\" << rbm.l2_weight_cost << std::endl;\n }\n\n if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) {\n std::cout << \" Sparsity (Lee): pbias=\" << rbm.pbias << std::endl;\n std::cout << \" Sparsity (Lee): pbias_lambda=\" << rbm.pbias_lambda << std::endl;\n } else if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) {\n std::cout << \" sparsity_target(Global)=\" << rbm.sparsity_target << std::endl;\n } else if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) {\n std::cout << \" sparsity_target(Local)=\" << rbm.sparsity_target << std::endl;\n }\n }\n\n template <typename RBM = R>\n void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& \/*rbm*\/) {\n char formatted[1024];\n if (rbm_layer_traits<RBM>::free_energy()) {\n snprintf(formatted, 1024, \"epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f\", epoch,\n context.reconstruction_error, context.free_energy, context.sparsity);\n } else {\n snprintf(formatted, 1024, \"epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f\", epoch, context.reconstruction_error, context.sparsity);\n }\n std::cout << formatted << std::endl;\n }\n\n template <typename RBM = R>\n void batch_end(const RBM& \/* rbm *\/, const rbm_training_context& context, std::size_t batch, std::size_t batches) {\n char formatted[1024];\n sprintf(formatted, \"Batch %ld\/%ld - Reconstruction error: %.5f - Sparsity: %.5f\", batch, batches,\n context.batch_error, context.batch_sparsity);\n std::cout << formatted << std::endl;\n }\n\n template <typename RBM = R>\n void training_end(const RBM&) {\n std::cout << \"Training took \" << watch.elapsed() << \"s\" << std::endl;\n }\n};\n\ntemplate <typename DBN>\nstruct default_dbn_watcher {\n static constexpr bool ignore_sub = false;\n static constexpr bool replace_sub = false;\n\n size_t ft_max_epochs = 0;\n dll::stop_timer ft_epoch_timer;\n dll::stop_timer ft_batch_timer;\n\n cpp::stop_watch<std::chrono::seconds> watch;\n\n void pretraining_begin(const DBN& \/*dbn*\/, std::size_t max_epochs) {\n std::cout << \"DBN: Pretraining begin for \" << max_epochs << \" epochs\" << std::endl;\n }\n\n template <typename RBM>\n void pretrain_layer(const DBN& \/*dbn*\/, std::size_t I, const RBM& rbm, std::size_t input_size) {\n if (input_size) {\n std::cout << \"DBN: Pretrain layer \" << I << \" (\" << rbm.to_short_string() << \") with \" << input_size << \" entries\" << std::endl;\n } else {\n std::cout << \"DBN: Pretrain layer \" << I << \" (\" << rbm.to_short_string() << \")\" << std::endl;\n }\n }\n\n void pretraining_end(const DBN& \/*dbn*\/) {\n std::cout << \"DBN: Pretraining finished after \" << watch.elapsed() << \"s\" << std::endl;\n }\n\n void pretraining_batch(const DBN& \/*dbn*\/, std::size_t batch) {\n std::cout << \"DBN: Pretraining batch \" << batch << std::endl;\n }\n\n \/*!\n * \\brief Fine-tuning of the given network just started\n * \\param dbn The DBN that is being trained\n * \\param max_epochs The maximum number of epochs to train the network\n *\/\n void fine_tuning_begin(const DBN& dbn, size_t max_epochs) {\n std::cout << \"Train the network with \\\"\" << DBN::desc::template trainer_t<DBN>::name() << \"\\\"\" << std::endl;\n std::cout << \"With parameters:\" << std::endl;\n std::cout << \" epochs=\" << max_epochs << std::endl;\n std::cout << \" batch_size=\" << DBN::batch_size << std::endl;\n std::cout << \" learning_rate=\" << dbn.learning_rate << std::endl;\n\n if (dbn_traits<DBN>::has_momentum()) {\n std::cout << \" momentum=\" << dbn.momentum << std::endl;\n }\n\n if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L1)=\" << dbn.l1_weight_cost << std::endl;\n }\n\n if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L2)=\" << dbn.l2_weight_cost << std::endl;\n }\n\n if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) {\n std::cout << \" lr_driver(BOLD)=\" << dbn.lr_bold_inc << \":\" << dbn.lr_bold_dec << std::endl;\n }\n\n if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) {\n std::cout << \" lr_driver(STEP)=\" << dbn.lr_step_size << \":\" << dbn.lr_step_gamma << std::endl;\n }\n\n ft_max_epochs = max_epochs;\n }\n\n \/*!\n * \\brief One fine-tuning epoch is starting\n * \\param epoch The current epoch\n * \\param dbn The network being trained\n *\/\n void ft_epoch_start(std::size_t epoch, const DBN& dbn) {\n cpp_unused(epoch);\n cpp_unused(dbn);\n ft_epoch_timer.start();\n }\n\n \/*!\n * \\brief One fine-tuning epoch is over\n * \\param epoch The current epoch\n * \\param error The current error\n * \\param loss The current loss\n * \\param dbn The network being trained\n *\/\n void ft_epoch_end(std::size_t epoch, double error, double loss, const DBN& dbn) {\n cpp_unused(dbn);\n auto duration = ft_epoch_timer.stop();\n\n if \/*constexpr*\/ (dbn_traits<DBN>::error_on_epoch()){\n printf(\"Epoch %3ld\/%ld - Classification error: %.5f Loss: %.5f Time %ldms \\n\", epoch, ft_max_epochs, error, loss, duration);\n } else {\n printf(\"Epoch %3ld\/%ld - Loss: %.5f Time %ldms \\n\", epoch, ft_max_epochs, loss, duration);\n }\n\n std::cout.flush();\n }\n\n void ft_batch_start(size_t epoch, const DBN& dbn) {\n cpp_unused(epoch);\n cpp_unused(dbn);\n ft_epoch_timer.start();\n }\n\n void ft_batch_end(size_t epoch, size_t batch, size_t batches, double batch_error, double batch_loss, const DBN&) {\n auto duration = ft_epoch_timer.stop();\n printf(\"Epoch %3ld:%ld\/%ld- B. Error: %.5f B. Loss: %.5f Time %ldms\\n\", epoch, batch, batches, batch_error, batch_loss, duration);\n std::cout.flush();\n }\n\n void ft_batch_end(size_t epoch, double batch_error, double batch_loss, const DBN&) {\n auto duration = ft_epoch_timer.stop();\n printf(\"Epoch %3ld - B.Error: %.5f B.Loss: %.5f Time %ldms\\n\", epoch, batch_error, batch_loss, duration);\n std::cout.flush();\n }\n\n void lr_adapt(const DBN& dbn) {\n printf(\"driver: learning rate adapted to %.5f \\n\", dbn.learning_rate);\n std::cout.flush();\n }\n\n void fine_tuning_end(const DBN&) {\n std::cout << \"Training took \" << watch.elapsed() << \"s\" << std::endl;\n }\n};\n\ntemplate <typename DBN>\nstruct silent_dbn_watcher : default_dbn_watcher<DBN> {\n static constexpr bool ignore_sub = true;\n static constexpr bool replace_sub = false;\n};\n\ntemplate <typename DBN>\nstruct mute_dbn_watcher {\n static constexpr bool ignore_sub = true;\n static constexpr bool replace_sub = false;\n\n void pretraining_begin(const DBN& \/*dbn*\/, std::size_t \/*max_epochs*\/) {}\n\n template <typename RBM>\n void pretrain_layer(const DBN& \/*dbn*\/, std::size_t \/*I*\/, const RBM& \/*rbm*\/, std::size_t \/*input_size*\/) {}\n\n void pretraining_end(const DBN& \/*dbn*\/) {}\n\n void pretraining_batch(const DBN& \/*dbn*\/, std::size_t \/*batch*\/) {}\n\n void fine_tuning_begin(const DBN& \/*dbn*\/, size_t \/*max_epochs*\/) {}\n\n void ft_epoch_start(std::size_t \/*epoch*\/, const DBN& \/*dbn*\/) {}\n\n void ft_epoch_end(std::size_t \/*epoch*\/, double \/*error*\/, const DBN& \/*dbn*\/) {}\n\n void ft_batch_start(size_t \/*epoch*\/, const DBN&) {}\n void ft_batch_end(size_t \/*epoch*\/, size_t \/*batch*\/, size_t \/*batches*\/, double \/*batch_error*\/, const DBN& \/*dbn*\/) {}\n void ft_batch_end(size_t \/*epoch*\/, double \/*batch_error*\/, const DBN& \/*dbn*\/) {}\n\n void lr_adapt(const DBN& \/*dbn*\/) {}\n\n void fine_tuning_end(const DBN& \/*dbn*\/) {}\n};\n\n\/\/TODO This is currently useless\n\ntemplate <typename R>\nstruct histogram_watcher {\n default_rbm_watcher<R> parent;\n\n template <typename RBM = R>\n void training_begin(const RBM& rbm) {\n parent.training_begin(rbm);\n }\n\n template <typename RBM = R>\n void epoch_end(std::size_t epoch, double error, double \/*free_energy*\/, const RBM& rbm) {\n parent.epoch_end(epoch, error, rbm);\n }\n\n template <typename RBM = R>\n void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) {\n parent.batch_end(rbm, context, batch, batches);\n }\n\n template <typename RBM = R>\n void training_end(const RBM& rbm) {\n parent.training_end(rbm);\n }\n\n void generate_hidden_images(std::size_t epoch, const R& rbm) {\n mkdir(\"reports\", 0777);\n\n auto folder = \"reports\/epoch_\" + std::to_string(epoch);\n mkdir(folder.c_str(), 0777);\n\n for (std::size_t j = 0; j < R::num_hidden; ++j) {\n auto path = folder + \"\/h_\" + std::to_string(j) + \".dat\";\n std::ofstream file(path, std::ios::out);\n\n if (!file) {\n std::cout << \"Could not open file \" << path << std::endl;\n } else {\n std::size_t i = R::num_visible;\n while (i > 0) {\n --i;\n\n auto value = rbm.w(i, j);\n file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << \" \";\n }\n\n file << std::endl;\n file.close();\n }\n }\n }\n\n void generate_histograms(std::size_t epoch, const R& rbm) {\n mkdir(\"reports\", 0777);\n\n auto folder = \"reports\/epoch_\" + std::to_string(epoch);\n mkdir(folder.c_str(), 0777);\n\n generate_histogram(folder + \"\/weights.dat\", rbm.w);\n generate_histogram(folder + \"\/visibles.dat\", rbm.a);\n generate_histogram(folder + \"\/hiddens.dat\", rbm.b);\n }\n\n template <typename Container>\n void generate_histogram(const std::string& path, const Container& weights) {\n std::ofstream file(path, std::ios::out);\n\n if (!file) {\n std::cout << \"Could not open file \" << path << std::endl;\n } else {\n for (auto& weight : weights) {\n file << weight << std::endl;\n }\n\n file << std::endl;\n file.close();\n }\n }\n};\n\n} \/\/end of dll namespace\n<commit_msg>Fix batch timings...<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <fstream>\n\n#include <sys\/stat.h>\n\n#include \"cpp_utils\/stop_watch.hpp\"\n\n#include \"trainer\/rbm_training_context.hpp\"\n#include \"layer_traits.hpp\"\n#include \"dbn_traits.hpp\"\n\nnamespace dll {\n\ntemplate <typename R>\nstruct default_rbm_watcher {\n cpp::stop_watch<std::chrono::seconds> watch;\n\n template <typename RBM = R>\n void training_begin(const RBM& rbm) {\n using rbm_t = std::decay_t<RBM>;\n\n std::cout << \"Train RBM with \\\"\" << RBM::desc::template trainer_t<RBM, false>::name() << \"\\\"\" << std::endl;\n\n rbm.display();\n\n std::cout << \"With parameters:\" << std::endl;\n\n if(std::is_same<typename rbm_t::weight, float>::value){\n std::cout << \" single-precision\" << std::endl;\n } else if(std::is_same<typename rbm_t::weight, double>::value){\n std::cout << \" double-precision\" << std::endl;\n } else {\n std::cout << \" unknown-precision (something is wrong...)\" << std::endl;\n }\n\n std::cout << \" learning_rate=\" << rbm.learning_rate << std::endl;\n std::cout << \" batch_size=\" << get_batch_size(rbm) << std::endl;\n\n if (rbm_layer_traits<RBM>::has_momentum()) {\n std::cout << \" momentum=\" << rbm.momentum << std::endl;\n }\n\n if (rbm_layer_traits<RBM>::has_clip_gradients()) {\n std::cout << \" gradient clip=\" << rbm.gradient_clip << std::endl;\n }\n\n if (w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L1)=\" << rbm.l1_weight_cost << std::endl;\n }\n\n if (w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(rbm_layer_traits<RBM>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L2)=\" << rbm.l2_weight_cost << std::endl;\n }\n\n if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) {\n std::cout << \" Sparsity (Lee): pbias=\" << rbm.pbias << std::endl;\n std::cout << \" Sparsity (Lee): pbias_lambda=\" << rbm.pbias_lambda << std::endl;\n } else if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) {\n std::cout << \" sparsity_target(Global)=\" << rbm.sparsity_target << std::endl;\n } else if (rbm_layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) {\n std::cout << \" sparsity_target(Local)=\" << rbm.sparsity_target << std::endl;\n }\n }\n\n template <typename RBM = R>\n void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& \/*rbm*\/) {\n char formatted[1024];\n if (rbm_layer_traits<RBM>::free_energy()) {\n snprintf(formatted, 1024, \"epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f\", epoch,\n context.reconstruction_error, context.free_energy, context.sparsity);\n } else {\n snprintf(formatted, 1024, \"epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f\", epoch, context.reconstruction_error, context.sparsity);\n }\n std::cout << formatted << std::endl;\n }\n\n template <typename RBM = R>\n void batch_end(const RBM& \/* rbm *\/, const rbm_training_context& context, std::size_t batch, std::size_t batches) {\n char formatted[1024];\n sprintf(formatted, \"Batch %ld\/%ld - Reconstruction error: %.5f - Sparsity: %.5f\", batch, batches,\n context.batch_error, context.batch_sparsity);\n std::cout << formatted << std::endl;\n }\n\n template <typename RBM = R>\n void training_end(const RBM&) {\n std::cout << \"Training took \" << watch.elapsed() << \"s\" << std::endl;\n }\n};\n\ntemplate <typename DBN>\nstruct default_dbn_watcher {\n static constexpr bool ignore_sub = false;\n static constexpr bool replace_sub = false;\n\n size_t ft_max_epochs = 0;\n dll::stop_timer ft_epoch_timer;\n dll::stop_timer ft_batch_timer;\n\n cpp::stop_watch<std::chrono::seconds> watch;\n\n void pretraining_begin(const DBN& \/*dbn*\/, std::size_t max_epochs) {\n std::cout << \"DBN: Pretraining begin for \" << max_epochs << \" epochs\" << std::endl;\n }\n\n template <typename RBM>\n void pretrain_layer(const DBN& \/*dbn*\/, std::size_t I, const RBM& rbm, std::size_t input_size) {\n if (input_size) {\n std::cout << \"DBN: Pretrain layer \" << I << \" (\" << rbm.to_short_string() << \") with \" << input_size << \" entries\" << std::endl;\n } else {\n std::cout << \"DBN: Pretrain layer \" << I << \" (\" << rbm.to_short_string() << \")\" << std::endl;\n }\n }\n\n void pretraining_end(const DBN& \/*dbn*\/) {\n std::cout << \"DBN: Pretraining finished after \" << watch.elapsed() << \"s\" << std::endl;\n }\n\n void pretraining_batch(const DBN& \/*dbn*\/, std::size_t batch) {\n std::cout << \"DBN: Pretraining batch \" << batch << std::endl;\n }\n\n \/*!\n * \\brief Fine-tuning of the given network just started\n * \\param dbn The DBN that is being trained\n * \\param max_epochs The maximum number of epochs to train the network\n *\/\n void fine_tuning_begin(const DBN& dbn, size_t max_epochs) {\n std::cout << \"Train the network with \\\"\" << DBN::desc::template trainer_t<DBN>::name() << \"\\\"\" << std::endl;\n std::cout << \"With parameters:\" << std::endl;\n std::cout << \" epochs=\" << max_epochs << std::endl;\n std::cout << \" batch_size=\" << DBN::batch_size << std::endl;\n std::cout << \" learning_rate=\" << dbn.learning_rate << std::endl;\n\n if (dbn_traits<DBN>::has_momentum()) {\n std::cout << \" momentum=\" << dbn.momentum << std::endl;\n }\n\n if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L1)=\" << dbn.l1_weight_cost << std::endl;\n }\n\n if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {\n std::cout << \" weight_cost(L2)=\" << dbn.l2_weight_cost << std::endl;\n }\n\n if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) {\n std::cout << \" lr_driver(BOLD)=\" << dbn.lr_bold_inc << \":\" << dbn.lr_bold_dec << std::endl;\n }\n\n if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) {\n std::cout << \" lr_driver(STEP)=\" << dbn.lr_step_size << \":\" << dbn.lr_step_gamma << std::endl;\n }\n\n ft_max_epochs = max_epochs;\n }\n\n \/*!\n * \\brief One fine-tuning epoch is starting\n * \\param epoch The current epoch\n * \\param dbn The network being trained\n *\/\n void ft_epoch_start(std::size_t epoch, const DBN& dbn) {\n cpp_unused(epoch);\n cpp_unused(dbn);\n ft_epoch_timer.start();\n }\n\n \/*!\n * \\brief One fine-tuning epoch is over\n * \\param epoch The current epoch\n * \\param error The current error\n * \\param loss The current loss\n * \\param dbn The network being trained\n *\/\n void ft_epoch_end(std::size_t epoch, double error, double loss, const DBN& dbn) {\n cpp_unused(dbn);\n auto duration = ft_epoch_timer.stop();\n\n if \/*constexpr*\/ (dbn_traits<DBN>::error_on_epoch()){\n printf(\"Epoch %3ld\/%ld - Classification error: %.5f Loss: %.5f Time %ldms \\n\", epoch, ft_max_epochs, error, loss, duration);\n } else {\n printf(\"Epoch %3ld\/%ld - Loss: %.5f Time %ldms \\n\", epoch, ft_max_epochs, loss, duration);\n }\n\n std::cout.flush();\n }\n\n void ft_batch_start(size_t epoch, const DBN& dbn) {\n cpp_unused(epoch);\n cpp_unused(dbn);\n ft_batch_timer.start();\n }\n\n void ft_batch_end(size_t epoch, size_t batch, size_t batches, double batch_error, double batch_loss, const DBN&) {\n auto duration = ft_batch_timer.stop();\n printf(\"Epoch %3ld:%ld\/%ld- B. Error: %.5f B. Loss: %.5f Time %ldms\\n\", epoch, batch, batches, batch_error, batch_loss, duration);\n std::cout.flush();\n }\n\n void ft_batch_end(size_t epoch, double batch_error, double batch_loss, const DBN&) {\n auto duration = ft_batch_timer.stop();\n printf(\"Epoch %3ld - B.Error: %.5f B.Loss: %.5f Time %ldms\\n\", epoch, batch_error, batch_loss, duration);\n std::cout.flush();\n }\n\n void lr_adapt(const DBN& dbn) {\n printf(\"driver: learning rate adapted to %.5f \\n\", dbn.learning_rate);\n std::cout.flush();\n }\n\n void fine_tuning_end(const DBN&) {\n std::cout << \"Training took \" << watch.elapsed() << \"s\" << std::endl;\n }\n};\n\ntemplate <typename DBN>\nstruct silent_dbn_watcher : default_dbn_watcher<DBN> {\n static constexpr bool ignore_sub = true;\n static constexpr bool replace_sub = false;\n};\n\ntemplate <typename DBN>\nstruct mute_dbn_watcher {\n static constexpr bool ignore_sub = true;\n static constexpr bool replace_sub = false;\n\n void pretraining_begin(const DBN& \/*dbn*\/, std::size_t \/*max_epochs*\/) {}\n\n template <typename RBM>\n void pretrain_layer(const DBN& \/*dbn*\/, std::size_t \/*I*\/, const RBM& \/*rbm*\/, std::size_t \/*input_size*\/) {}\n\n void pretraining_end(const DBN& \/*dbn*\/) {}\n\n void pretraining_batch(const DBN& \/*dbn*\/, std::size_t \/*batch*\/) {}\n\n void fine_tuning_begin(const DBN& \/*dbn*\/, size_t \/*max_epochs*\/) {}\n\n void ft_epoch_start(std::size_t \/*epoch*\/, const DBN& \/*dbn*\/) {}\n\n void ft_epoch_end(std::size_t \/*epoch*\/, double \/*error*\/, const DBN& \/*dbn*\/) {}\n\n void ft_batch_start(size_t \/*epoch*\/, const DBN&) {}\n void ft_batch_end(size_t \/*epoch*\/, size_t \/*batch*\/, size_t \/*batches*\/, double \/*batch_error*\/, const DBN& \/*dbn*\/) {}\n void ft_batch_end(size_t \/*epoch*\/, double \/*batch_error*\/, const DBN& \/*dbn*\/) {}\n\n void lr_adapt(const DBN& \/*dbn*\/) {}\n\n void fine_tuning_end(const DBN& \/*dbn*\/) {}\n};\n\n\/\/TODO This is currently useless\n\ntemplate <typename R>\nstruct histogram_watcher {\n default_rbm_watcher<R> parent;\n\n template <typename RBM = R>\n void training_begin(const RBM& rbm) {\n parent.training_begin(rbm);\n }\n\n template <typename RBM = R>\n void epoch_end(std::size_t epoch, double error, double \/*free_energy*\/, const RBM& rbm) {\n parent.epoch_end(epoch, error, rbm);\n }\n\n template <typename RBM = R>\n void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) {\n parent.batch_end(rbm, context, batch, batches);\n }\n\n template <typename RBM = R>\n void training_end(const RBM& rbm) {\n parent.training_end(rbm);\n }\n\n void generate_hidden_images(std::size_t epoch, const R& rbm) {\n mkdir(\"reports\", 0777);\n\n auto folder = \"reports\/epoch_\" + std::to_string(epoch);\n mkdir(folder.c_str(), 0777);\n\n for (std::size_t j = 0; j < R::num_hidden; ++j) {\n auto path = folder + \"\/h_\" + std::to_string(j) + \".dat\";\n std::ofstream file(path, std::ios::out);\n\n if (!file) {\n std::cout << \"Could not open file \" << path << std::endl;\n } else {\n std::size_t i = R::num_visible;\n while (i > 0) {\n --i;\n\n auto value = rbm.w(i, j);\n file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << \" \";\n }\n\n file << std::endl;\n file.close();\n }\n }\n }\n\n void generate_histograms(std::size_t epoch, const R& rbm) {\n mkdir(\"reports\", 0777);\n\n auto folder = \"reports\/epoch_\" + std::to_string(epoch);\n mkdir(folder.c_str(), 0777);\n\n generate_histogram(folder + \"\/weights.dat\", rbm.w);\n generate_histogram(folder + \"\/visibles.dat\", rbm.a);\n generate_histogram(folder + \"\/hiddens.dat\", rbm.b);\n }\n\n template <typename Container>\n void generate_histogram(const std::string& path, const Container& weights) {\n std::ofstream file(path, std::ios::out);\n\n if (!file) {\n std::cout << \"Could not open file \" << path << std::endl;\n } else {\n for (auto& weight : weights) {\n file << weight << std::endl;\n }\n\n file << std::endl;\n file.close();\n }\n }\n};\n\n} \/\/end of dll namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"Game.h\"\n\n#include \"Device.h\"\n\nnamespace fs = boost::filesystem;\n\nusing namespace RetroEnd::Model;\nusing namespace std;\n\n\/\/ The Name of the table into the DB for this Model\nstring Game::table = \"games\";\n\n\/\/ Model Class Constructor\nGame::Game() : BaseModel()\n{\n\t\/\/default values\n\tDeviceId = 0; \n\tTimesPlayed = 0;\n\tFavorite = false;\n}\n\n\/\/ Model Class Constructor from DB record\nGame::Game( sqlite3_stmt* record ) : BaseModel()\n{\n\tid\t\t\t= sqlite3_column_int(record, 0);\n\tTitle\t\t= (char*)sqlite3_column_text(record,1);\n\tDeviceId\t= sqlite3_column_int(record,2);\n\tDescription = (char*)sqlite3_column_text(record,3);\n\tDeveloper\t= (char*)sqlite3_column_text(record,4);\n\tPublisher\t= (char*)sqlite3_column_text(record,5);\n\tESRB\t\t= (char*)sqlite3_column_text(record,6);\n\tMaxPlayers\t= (char*)sqlite3_column_text(record,7);\n\tCoOp\t\t= (char*)sqlite3_column_text(record,8);\n\tReleaseDate = (char*)sqlite3_column_text(record,9);\n\tTGDBId\t\t= (char*)sqlite3_column_text(record,10);\n\tTGDBRating\t= (char*)sqlite3_column_text(record,11);\n\tImageFront\t= (char*)sqlite3_column_text(record,12);\n\tImageBack\t= (char*)sqlite3_column_text(record,13);\n\tImageScreen\t= (char*)sqlite3_column_text(record,14);\n\tImageLogo\t= (char*)sqlite3_column_text(record,15);\n\tGameFile\t= (char*)sqlite3_column_text(record,16);\n\tFileCRC\t\t= (char*)sqlite3_column_text(record,17);\n\tTimesPlayed\t= sqlite3_column_int(record, 18);\n\tFavorite\t= sqlite3_column_int(record, 19) == 1;\n}\n\n\/\/ Model Class Constructor from TGDB result\nGame::Game ( pugi::xml_node gameNode, sqlite3_int64 deviceId) : BaseModel()\n{\n\t\/\/default values\n\tTimesPlayed = 0;\n\tFavorite = false;\n\n\tDeviceId = deviceId;\n\n\tTitle = gameNode.child(\"GameTitle\").text().get();\n\tDescription = gameNode.child(\"Overview\").text().get();\n\tESRB = gameNode.child(\"ESRB\").text().get();\n\tMaxPlayers = gameNode.child(\"Players\").text().get();\n\tCoOp = gameNode.child(\"Co-op\").text().get();\n\tPublisher = gameNode.child(\"Publisher\").text().get();\n\tDeveloper = gameNode.child(\"Developer\").text().get();\n\tTGDBRating = gameNode.child(\"Rating\").text().get();\n\tReleaseDate = gameNode.child(\"ReleaseDate\").text().get();\n\tTGDBId = gameNode.child(\"id\").text().get();\n}\n\n\/\/ Model Class Distructor\nGame::~Game()\n{\n\n}\n\n\/\/ Build the query for update the DB record\nstring Game::getUpdateQuery()\n{\n\tstring query = \"UPDATE \" + table + \" SET\";\n\n\tquery += \" DEVICE_ID = \"\t+\tto_string( DeviceId )+\",\";\n\tquery += \" TITLE = '\"\t\t+\tsqlEscape( Title )+\"',\";\n\tquery += \" DESCRIPTION = '\"\t+\tsqlEscape( Description )+\"',\";\n\tquery += \" DEVELOPER = '\"\t+\tsqlEscape( Developer )+\"',\";\n\tquery += \" PUBLISHER = '\"\t+\tsqlEscape( Publisher )+\"',\";\n\tquery += \" ESRB = '\"\t\t+\tsqlEscape( ESRB )+\"',\";\n\tquery += \" PLAYERS = '\"\t\t+\tsqlEscape( MaxPlayers )+\"',\";\n\tquery += \" CO_OP = '\"\t\t+\tsqlEscape( CoOp )+\"',\";\n\tquery += \" RELEASE_DATE = '\"+\tsqlEscape( ReleaseDate )+\"',\";\n\tquery += \" TGDB_ID = '\"\t\t+\tsqlEscape( TGDBId )+\"',\";\n\tquery += \" TGDB_RATING = '\"\t+\tsqlEscape( TGDBRating )+\"',\";\n\tquery += \" IMAGE_FRONT = '\"\t+\tsqlEscape( ImageFront )+\"',\";\n\tquery += \" IMAGE_BACK = '\"\t+\tsqlEscape( ImageBack )+\"',\";\n\tquery += \" IMAGE_SCREEN = '\"+\tsqlEscape( ImageScreen )+\"',\";\n\tquery += \" IMAGE_LOGO = '\"\t+\tsqlEscape( ImageLogo )+\"',\";\n\tquery += \" GAME_FILE = '\"\t+\tsqlEscape( GameFile )+\"' ,\";\n\tquery += \" FILE_CRC = '\"\t+\tsqlEscape( FileCRC )+\"' ,\";\n\tquery += \" TIMES_PLAYED = \"\t+\tto_string( TimesPlayed )+\" ,\";\n\tquery += \" FAVORITE = \"\t\t+\tto_string( Favorite? 1 : 0 ) ;\n\n\tquery += \" WHERE id=\"+to_string( id )+\";\";\n\n\treturn query;\n}\n\n\/\/ Build the query for delete the DB record\nstring Game::getDeleteQuery()\n{\n\treturn \"DELETE FROM \" + table + \" WHERE id=\"+to_string( id )+\";\";\n}\n\n\/\/ Build the query for create the DB record\nstring Game::getInsertQuery()\n{\n\tstring query = \"INSERT into \" + table + \" (TITLE,DEVICE_ID,DESCRIPTION,DEVELOPER,PUBLISHER,ESRB,PLAYERS,CO_OP,RELEASE_DATE,TGDB_ID,TGDB_RATING,IMAGE_FRONT,IMAGE_BACK,IMAGE_SCREEN,IMAGE_LOGO, GAME_FILE, FILE_CRC, TIMES_PLAYED, FAVORITE)\";\n\tquery += \"values ('\" + sqlEscape( Title ) + \"','\" + to_string(DeviceId) + \"','\" + sqlEscape( Description ) + \"','\" + sqlEscape( Developer ) + \"','\" + sqlEscape( Publisher ) + \"','\" + sqlEscape( ESRB ) + \"','\" + sqlEscape( MaxPlayers ) + \"','\" + sqlEscape( CoOp ) + \"','\" + sqlEscape( ReleaseDate ) + \"','\" + sqlEscape( TGDBId ) + \"','\" + sqlEscape( TGDBRating ) + \"','\" + sqlEscape( ImageFront ) + \"','\" + sqlEscape( ImageBack ) + \"','\" + sqlEscape( ImageScreen ) + \"','\" + sqlEscape( ImageLogo ) + \"','\" + sqlEscape( GameFile ) + \"','\" + sqlEscape( FileCRC ) + \"', \"+to_string(TimesPlayed)+\", \" + to_string(Favorite? 1 : 0) + \")\";\n\treturn query;\n}\n\n\/\/ Build the query for create the table into the SQLite DB\n\/\/ Sould be called only on first run of the app\nvoid Game::init()\n{\n\t\/\/open db connection\n\tsqlite3* db;\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\tvector<string> queries;\n\n\t\/\/THE CREATE PART - MUST BE ALWAYS RUN (if table already exists we simply have an error)\n\tstring create = \"CREATE TABLE IF NOT EXISTS \" + Game::table + \" (\";\n\tcreate += \"ID INTEGER PRIMARY KEY, TITLE TEXT, DEVICE_ID INTEGER, DESCRIPTION TEXT, DEVELOPER TEXT, PUBLISHER TEXT, ESRB TEXT, PLAYERS TEXT, \";\n\tcreate += \"CO_OP TEXT, RELEASE_DATE TEXT, TGDB_ID TEXT, TGDB_RATING TEXT, \";\n\tcreate += \"IMAGE_FRONT TEXT, IMAGE_BACK TEXT, IMAGE_SCREEN TEXT, IMAGE_LOGO TEXT);\";\n\tqueries.push_back(create);\n\n\t\/\/THE UPDATE PART - MUST BE ALWAYS RUN (if colums already exist we simply have an error)\n\t\/\/new colums bust be added in the update part so when the app is updated we can add those to the DB\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN GAME_FILE TEXT DEFAULT '';\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN FILE_CRC TEXT DEFAULT '';\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN TIMES_PLAYED INTEGER DEFAULT 0;\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN FAVORITE INTEGER DEFAULT 0;\" );\n\n\tfor (vector<string>::iterator it = queries.begin() ; it != queries.end(); ++it) {\n\t\tstring query = *it;\n\n\t\t\/\/execute query\n\t\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t\t{\n\t\t\tsqlite3_step(statement);\n\t\t\tsqlite3_finalize(statement);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring message = sqlite3_errmsg(db);\n\n\t\t\t\/\/IF COLUMN ALREADY AXISTS IS NOT AN ERROR\n\t\t\tif( strncmp(message.c_str(), \"duplicate column\", strlen(\"duplicate column\")) != 0)\n\t\t\t\tLOG(LogLevel::Error, \"Game init : \" + message);\n\t\t}\n\t}\n\n\t\/\/close db concction\n\tsqlite3_close(db);\n}\n\n\/\/ Static method for read all the items from DB\nvector<Game> Game::getAllGames()\n{\n\tvector<Game> games;\n\n\tstring query = \"SELECT * FROM \" + Game::table;\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\twhile (result == SQLITE_ROW)\n\t\t{\n\t\t\t\/\/create and insert the new item\n\t\t\tgames.push_back(Game(statement));\n\n\t\t\t\/\/go to next record\n\t\t\tresult = sqlite3_step(statement);\n\t\t}\n\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getAllGames : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn games;\n}\n\n\/\/ Static method for read an item specified by \"id\" from DB\nGame Game::getGameById(sqlite3_int64 id)\n{\n\tGame* game = NULL;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE id = \" + to_string(id);\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\tif(result == SQLITE_ROW)\n\t\t{\n\t\t\tgame = new Game(statement);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgame = new Game();\n\t\t}\n\t\t\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGameById : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn *game;\n}\n\nGame* Game::getGameByTGDBId(string& TGDBId)\n{\n\tGame* game = NULL;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE TGDB_ID = '\" + TGDBId +\"' LIMIT 1\";\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\tif(result == SQLITE_ROW)\n\t\t{\n\t\t\tgame = new Game(statement);\n\t\t}\n\t\t\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGameById : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn game;\n}\n\nstring Game::getReleaseYear()\n{\n\tif(ReleaseDate.empty())\n\t\treturn \"\";\n\telse\n\t{\n\t\treturn ReleaseDate.substr(ReleaseDate.find_last_of(\"\/\") + 1, string::npos) + \", \";\n\t}\n}\n\nstring Game::getCleanFileName()\n{\n\tstring result = GameFile;\n\n\tregex rx1(\"\\\\(.+\\\\)\");\n\tregex rx2(\"\\\\[.+\\\\]\");\n\n\tresult = tr1::regex_replace(result, rx1, \"\");\n\tresult = tr1::regex_replace(result, rx2, \"\");\n\tresult = result.substr(0, result.find_last_of('.'));\n\tresult = trim(result);\n\treturn result;\n}\n\n\/\/ Static method for read all the items from DB for a specified Device\nvector<Game> Game::getGamesForDevice(sqlite3_int64 deviceId)\n{\n\tvector<Game> games;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE DEVICE_ID = \" + to_string(deviceId) + \" ORDER BY TITLE \";\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\twhile (result == SQLITE_ROW)\n\t\t{\n\t\t\t\/\/create and insert the new item\n\t\t\tgames.push_back(Game(statement));\n\n\t\t\t\/\/go to next record\n\t\t\tresult = sqlite3_step(statement);\n\t\t}\n\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGamesForDevice : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn games;\n}\n\nvoid Game::remove()\n{\n\t\/\/remove from DB\n\tBaseModel::remove();\n\n\tif(DeviceId != 0 && ! GameFile.empty())\n\t{\n\t\t\/\/get GameFile path\n\t\tstring romPath = Device::getDeviceById(DeviceId).getRomsPath();\n\t\t\/\/get Images path\n\n\t\t\/\/delete rom file\n\t\tfs::path file = romPath \/ fs::path(GameFile);\n\t\tif( fs::exists(file)) fs::remove(file);\n\t}\n\n\tif( ! ImageFront.empty() && fs::exists(ImageFront) ) fs::remove(ImageFront);\n\tif( ! ImageBack.empty() && fs::exists(ImageBack) ) fs::remove(ImageBack);\n\tif( ! ImageLogo.empty() && fs::exists(ImageLogo) ) fs::remove(ImageLogo);\n\tif( ! ImageScreen.empty() && fs::exists(ImageScreen) ) fs::remove(ImageScreen);\n}<commit_msg>Going to Raspberry PI<commit_after>#include \"Game.h\"\n\n#include \"Device.h\"\n\nnamespace fs = boost::filesystem;\n\nusing namespace RetroEnd::Model;\nusing namespace std;\n\n\/\/ The Name of the table into the DB for this Model\nstring Game::table = \"games\";\n\n\/\/ Model Class Constructor\nGame::Game() : BaseModel()\n{\n\t\/\/default values\n\tDeviceId = 0; \n\tTimesPlayed = 0;\n\tFavorite = false;\n}\n\n\/\/ Model Class Constructor from DB record\nGame::Game( sqlite3_stmt* record ) : BaseModel()\n{\n\tid\t\t\t= sqlite3_column_int(record, 0);\n\tTitle\t\t= (char*)sqlite3_column_text(record,1);\n\tDeviceId\t= sqlite3_column_int(record,2);\n\tDescription = (char*)sqlite3_column_text(record,3);\n\tDeveloper\t= (char*)sqlite3_column_text(record,4);\n\tPublisher\t= (char*)sqlite3_column_text(record,5);\n\tESRB\t\t= (char*)sqlite3_column_text(record,6);\n\tMaxPlayers\t= (char*)sqlite3_column_text(record,7);\n\tCoOp\t\t= (char*)sqlite3_column_text(record,8);\n\tReleaseDate = (char*)sqlite3_column_text(record,9);\n\tTGDBId\t\t= (char*)sqlite3_column_text(record,10);\n\tTGDBRating\t= (char*)sqlite3_column_text(record,11);\n\tImageFront\t= (char*)sqlite3_column_text(record,12);\n\tImageBack\t= (char*)sqlite3_column_text(record,13);\n\tImageScreen\t= (char*)sqlite3_column_text(record,14);\n\tImageLogo\t= (char*)sqlite3_column_text(record,15);\n\tGameFile\t= (char*)sqlite3_column_text(record,16);\n\tFileCRC\t\t= (char*)sqlite3_column_text(record,17);\n\tTimesPlayed\t= sqlite3_column_int(record, 18);\n\tFavorite\t= sqlite3_column_int(record, 19) == 1;\n}\n\n\/\/ Model Class Constructor from TGDB result\nGame::Game ( pugi::xml_node gameNode, sqlite3_int64 deviceId) : BaseModel()\n{\n\t\/\/default values\n\tTimesPlayed = 0;\n\tFavorite = false;\n\n\tDeviceId = deviceId;\n\n\tTitle = gameNode.child(\"GameTitle\").text().get();\n\tDescription = gameNode.child(\"Overview\").text().get();\n\tESRB = gameNode.child(\"ESRB\").text().get();\n\tMaxPlayers = gameNode.child(\"Players\").text().get();\n\tCoOp = gameNode.child(\"Co-op\").text().get();\n\tPublisher = gameNode.child(\"Publisher\").text().get();\n\tDeveloper = gameNode.child(\"Developer\").text().get();\n\tTGDBRating = gameNode.child(\"Rating\").text().get();\n\tReleaseDate = gameNode.child(\"ReleaseDate\").text().get();\n\tTGDBId = gameNode.child(\"id\").text().get();\n}\n\n\/\/ Model Class Distructor\nGame::~Game()\n{\n\n}\n\n\/\/ Build the query for update the DB record\nstring Game::getUpdateQuery()\n{\n\tstring query = \"UPDATE \" + table + \" SET\";\n\n\tquery += \" DEVICE_ID = \"\t+\tto_string( DeviceId )+\",\";\n\tquery += \" TITLE = '\"\t\t+\tsqlEscape( Title )+\"',\";\n\tquery += \" DESCRIPTION = '\"\t+\tsqlEscape( Description )+\"',\";\n\tquery += \" DEVELOPER = '\"\t+\tsqlEscape( Developer )+\"',\";\n\tquery += \" PUBLISHER = '\"\t+\tsqlEscape( Publisher )+\"',\";\n\tquery += \" ESRB = '\"\t\t+\tsqlEscape( ESRB )+\"',\";\n\tquery += \" PLAYERS = '\"\t\t+\tsqlEscape( MaxPlayers )+\"',\";\n\tquery += \" CO_OP = '\"\t\t+\tsqlEscape( CoOp )+\"',\";\n\tquery += \" RELEASE_DATE = '\"+\tsqlEscape( ReleaseDate )+\"',\";\n\tquery += \" TGDB_ID = '\"\t\t+\tsqlEscape( TGDBId )+\"',\";\n\tquery += \" TGDB_RATING = '\"\t+\tsqlEscape( TGDBRating )+\"',\";\n\tquery += \" IMAGE_FRONT = '\"\t+\tsqlEscape( ImageFront )+\"',\";\n\tquery += \" IMAGE_BACK = '\"\t+\tsqlEscape( ImageBack )+\"',\";\n\tquery += \" IMAGE_SCREEN = '\"+\tsqlEscape( ImageScreen )+\"',\";\n\tquery += \" IMAGE_LOGO = '\"\t+\tsqlEscape( ImageLogo )+\"',\";\n\tquery += \" GAME_FILE = '\"\t+\tsqlEscape( GameFile )+\"' ,\";\n\tquery += \" FILE_CRC = '\"\t+\tsqlEscape( FileCRC )+\"' ,\";\n\tquery += \" TIMES_PLAYED = \"\t+\tto_string( TimesPlayed )+\" ,\";\n\tquery += \" FAVORITE = \"\t\t+\tto_string( Favorite? 1 : 0 ) ;\n\n\tquery += \" WHERE id=\"+to_string( id )+\";\";\n\n\treturn query;\n}\n\n\/\/ Build the query for delete the DB record\nstring Game::getDeleteQuery()\n{\n\treturn \"DELETE FROM \" + table + \" WHERE id=\"+to_string( id )+\";\";\n}\n\n\/\/ Build the query for create the DB record\nstring Game::getInsertQuery()\n{\n\tstring query = \"INSERT into \" + table + \" (TITLE,DEVICE_ID,DESCRIPTION,DEVELOPER,PUBLISHER,ESRB,PLAYERS,CO_OP,RELEASE_DATE,TGDB_ID,TGDB_RATING,IMAGE_FRONT,IMAGE_BACK,IMAGE_SCREEN,IMAGE_LOGO, GAME_FILE, FILE_CRC, TIMES_PLAYED, FAVORITE)\";\n\tquery += \"values ('\" + sqlEscape( Title ) + \"','\" + to_string(DeviceId) + \"','\" + sqlEscape( Description ) + \"','\" + sqlEscape( Developer ) + \"','\" + sqlEscape( Publisher ) + \"','\" + sqlEscape( ESRB ) + \"','\" + sqlEscape( MaxPlayers ) + \"','\" + sqlEscape( CoOp ) + \"','\" + sqlEscape( ReleaseDate ) + \"','\" + sqlEscape( TGDBId ) + \"','\" + sqlEscape( TGDBRating ) + \"','\" + sqlEscape( ImageFront ) + \"','\" + sqlEscape( ImageBack ) + \"','\" + sqlEscape( ImageScreen ) + \"','\" + sqlEscape( ImageLogo ) + \"','\" + sqlEscape( GameFile ) + \"','\" + sqlEscape( FileCRC ) + \"', \"+to_string(TimesPlayed)+\", \" + to_string(Favorite? 1 : 0) + \")\";\n\treturn query;\n}\n\n\/\/ Build the query for create the table into the SQLite DB\n\/\/ Sould be called only on first run of the app\nvoid Game::init()\n{\n\t\/\/open db connection\n\tsqlite3* db;\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\tvector<string> queries;\n\n\t\/\/THE CREATE PART - MUST BE ALWAYS RUN (if table already exists we simply have an error)\n\tstring create = \"CREATE TABLE IF NOT EXISTS \" + Game::table + \" (\";\n\tcreate += \"ID INTEGER PRIMARY KEY, TITLE TEXT, DEVICE_ID INTEGER, DESCRIPTION TEXT, DEVELOPER TEXT, PUBLISHER TEXT, ESRB TEXT, PLAYERS TEXT, \";\n\tcreate += \"CO_OP TEXT, RELEASE_DATE TEXT, TGDB_ID TEXT, TGDB_RATING TEXT, \";\n\tcreate += \"IMAGE_FRONT TEXT, IMAGE_BACK TEXT, IMAGE_SCREEN TEXT, IMAGE_LOGO TEXT);\";\n\tqueries.push_back(create);\n\n\t\/\/THE UPDATE PART - MUST BE ALWAYS RUN (if colums already exist we simply have an error)\n\t\/\/new colums bust be added in the update part so when the app is updated we can add those to the DB\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN GAME_FILE TEXT DEFAULT '';\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN FILE_CRC TEXT DEFAULT '';\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN TIMES_PLAYED INTEGER DEFAULT 0;\" );\n\tqueries.push_back( \"ALTER TABLE \" +Game::table + \" ADD COLUMN FAVORITE INTEGER DEFAULT 0;\" );\n\n\tfor (vector<string>::iterator it = queries.begin() ; it != queries.end(); ++it) {\n\t\tstring query = *it;\n\n\t\t\/\/execute query\n\t\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t\t{\n\t\t\tsqlite3_step(statement);\n\t\t\tsqlite3_finalize(statement);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring message = sqlite3_errmsg(db);\n\n\t\t\t\/\/IF COLUMN ALREADY AXISTS IS NOT AN ERROR\n\t\t\tif( strncmp(message.c_str(), \"duplicate column\", strlen(\"duplicate column\")) != 0)\n\t\t\t\tLOG(LogLevel::Error, \"Game init : \" + message);\n\t\t}\n\t}\n\n\t\/\/close db concction\n\tsqlite3_close(db);\n}\n\n\/\/ Static method for read all the items from DB\nvector<Game> Game::getAllGames()\n{\n\tvector<Game> games;\n\n\tstring query = \"SELECT * FROM \" + Game::table;\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\twhile (result == SQLITE_ROW)\n\t\t{\n\t\t\t\/\/create and insert the new item\n\t\t\tgames.push_back(Game(statement));\n\n\t\t\t\/\/go to next record\n\t\t\tresult = sqlite3_step(statement);\n\t\t}\n\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getAllGames : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn games;\n}\n\n\/\/ Static method for read an item specified by \"id\" from DB\nGame Game::getGameById(sqlite3_int64 id)\n{\n\tGame* game = NULL;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE id = \" + to_string(id);\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\tif(result == SQLITE_ROW)\n\t\t{\n\t\t\tgame = new Game(statement);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgame = new Game();\n\t\t}\n\t\t\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGameById : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn *game;\n}\n\nGame* Game::getGameByTGDBId(string& TGDBId)\n{\n\tGame* game = NULL;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE TGDB_ID = '\" + TGDBId +\"' LIMIT 1\";\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\tif(result == SQLITE_ROW)\n\t\t{\n\t\t\tgame = new Game(statement);\n\t\t}\n\t\t\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGameById : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn game;\n}\n\nstring Game::getReleaseYear()\n{\n\tif(ReleaseDate.empty())\n\t\treturn \"\";\n\telse\n\t{\n\t\treturn ReleaseDate.substr(ReleaseDate.find_last_of(\"\/\") + 1, string::npos) + \", \";\n\t}\n}\n\nstring Game::getCleanFileName()\n{\n\tstring result = GameFile;\n\n\tregex rx1(\"\\\\(.+\\\\)\");\n\tregex rx2(\"\\\\[.+\\\\]\");\n\n\tresult = regex_replace(result, rx1, \"\");\n\tresult = regex_replace(result, rx2, \"\");\n\tresult = result.substr(0, result.find_last_of('.'));\n\tresult = trim(result);\n\treturn result;\n}\n\n\/\/ Static method for read all the items from DB for a specified Device\nvector<Game> Game::getGamesForDevice(sqlite3_int64 deviceId)\n{\n\tvector<Game> games;\n\n\tstring query = \"SELECT * FROM \" + Game::table + \" WHERE DEVICE_ID = \" + to_string(deviceId) + \" ORDER BY TITLE \";\n\n\tsqlite3* db;\n\n\tsqlite3_open(RetroEnd::DB_NAME.c_str(), &db);\n\n\tsqlite3_stmt *statement;\n\n\tif(sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0) == SQLITE_OK)\n\t{\n\t\tint result = sqlite3_step(statement);\n\n\t\twhile (result == SQLITE_ROW)\n\t\t{\n\t\t\t\/\/create and insert the new item\n\t\t\tgames.push_back(Game(statement));\n\n\t\t\t\/\/go to next record\n\t\t\tresult = sqlite3_step(statement);\n\t\t}\n\n\t\tsqlite3_finalize(statement);\n\t}\n\telse\n\t{\n\t\tstring message = sqlite3_errmsg(db);\n\t\tLOG(Error, \"Game getGamesForDevice : \" + message);\n\t}\n\n\tsqlite3_close(db);\n\n\treturn games;\n}\n\nvoid Game::remove()\n{\n\t\/\/remove from DB\n\tBaseModel::remove();\n\n\tif(DeviceId != 0 && ! GameFile.empty())\n\t{\n\t\t\/\/get GameFile path\n\t\tstring romPath = Device::getDeviceById(DeviceId).getRomsPath();\n\t\t\/\/get Images path\n\n\t\t\/\/delete rom file\n\t\tfs::path file = romPath \/ fs::path(GameFile);\n\t\tif( fs::exists(file)) fs::remove(file);\n\t}\n\n\tif( ! ImageFront.empty() && fs::exists(ImageFront) ) fs::remove(ImageFront);\n\tif( ! ImageBack.empty() && fs::exists(ImageBack) ) fs::remove(ImageBack);\n\tif( ! ImageLogo.empty() && fs::exists(ImageLogo) ) fs::remove(ImageLogo);\n\tif( ! ImageScreen.empty() && fs::exists(ImageScreen) ) fs::remove(ImageScreen);\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <lion\/filesystem.hpp>\n\n#include <atma\/intrusive_ptr.hpp>\n#include <atma\/vector.hpp>\n#include <atma\/atomic.hpp>\n#include <atma\/handle_table.hpp>\n#include <atma\/enable_if.hpp>\n\n#include <tuple>\n#include <type_traits>\n\n\n\/\/ forward declares\nnamespace lion\n{\n\tstruct asset_t;\n\tstruct asset_library_t;\n\ttemplate <typename> struct asset_handle_t;\n\ttemplate <typename> struct asset_weak_handle_t;\n}\n\n\n\/\/ asset_t\nnamespace lion\n{\n\tstruct asset_t\n\t{\n\t\tauto path() const -> path_t const& { return path_; }\n\t\tvirtual ~asset_t() {}\n\tprivate:\n\t\tpath_t path_;\n\t};\n}\n\n\n\n\/\/ asset_handle_t \/ asset_weak_handle_t\nnamespace lion\n{\n\ttemplate <typename T>\n\tstruct asset_handle_t\n\t{\n\t\tconstexpr asset_handle_t();\n\t\tasset_handle_t(asset_handle_t const& rhs);\n\t\tasset_handle_t(asset_handle_t&& rhs);\n\t\t~asset_handle_t();\n\n\t\texplicit asset_handle_t(asset_weak_handle_t<T> const&);\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tasset_handle_t(asset_handle_t<Y> const& rhs);\n\t\ttemplate <typename Y, typename = atma::enable_if<std::is_convertible<Y*, T*>>>\n\t\tasset_handle_t(asset_handle_t<Y>&& rhs);\n\n\n\t\tauto operator = (asset_handle_t const& rhs) -> asset_handle_t&;\n\t\tauto operator = (asset_handle_t&& rhs) -> asset_handle_t&;\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_handle_t<Y> const& rhs) -> asset_handle_t&;\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_handle_t<Y>&& rhs) -> asset_handle_t&;\n\n\t\tauto operator -> () const -> T const* { return (T const*)library_->find(id_)->asset.get(); }\n\t\tauto operator -> () -> T* { return (T *)library_->find(id_)->asset.get(); }\n\t\tauto operator *() const -> T const& { return *this->operator ->(); }\n\t\tauto operator *() -> T& { return *this->operator ->(); }\n\n\t\toperator bool() const { return id_ != 0; }\n\n\t\tauto library() const -> asset_library_t* { return library_; }\n\t\tauto id() const -> uint32 { return id_; }\n\n\tprivate:\n\t\tasset_handle_t(asset_library_t* library, uint32 id)\n\t\t\t: library_{library}, id_{id}\n\t\t{}\n\n\tprivate:\n\t\tasset_library_t* library_ = nullptr;\n\t\tuint32 id_ = 0;\n\n\t\tfriend struct asset_library_t;\n\t\ttemplate <typename> friend struct asset_handle_t;\n\t\ttemplate <typename> friend struct asset_weak_handle_t;\n\n\t\ttemplate <typename Y, typename Y2>\n\t\tfriend auto polymorphic_asset_cast(asset_handle_t<Y2> const&) -> asset_handle_t<Y>;\n\t};\n\n\tusing base_asset_handle_t = asset_handle_t<asset_t>;\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tstruct asset_weak_handle_t\n\t{\n\t\tconstexpr asset_weak_handle_t();\n\t\tasset_weak_handle_t(asset_weak_handle_t const&);\n\t\tasset_weak_handle_t(asset_weak_handle_t&&);\n\t\t~asset_weak_handle_t();\n\n\t\tasset_weak_handle_t(asset_handle_t<T> const&);\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tasset_weak_handle_t(asset_weak_handle_t<Y> const& rhs);\n\t\ttemplate <typename Y, typename = atma::enable_if<std::is_convertible<Y*, T*>>>\n\t\tasset_weak_handle_t(asset_weak_handle_t<Y>&& rhs);\n\n\t\tauto operator = (asset_weak_handle_t const&) -> asset_weak_handle_t&;\n\t\tauto operator = (asset_weak_handle_t&&) -> asset_weak_handle_t&;\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_weak_handle_t<Y> const& rhs) -> asset_weak_handle_t&;\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_weak_handle_t<Y>&& rhs) -> asset_weak_handle_t&;\n\n\t\tauto library() const -> asset_library_t* { return library_; }\n\t\tauto id() const -> uint32 { return id_; }\n\n\t\tauto expired() const -> bool;\n\t\tauto lock() const -> asset_handle_t<T>;\n\n\tprivate:\n\t\tasset_library_t* library_ = nullptr;\n\t\tuint32 id_ = 0;\n\t};\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tinline constexpr asset_handle_t<T>::asset_handle_t()\n\t{}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.retain(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_weak_handle_t<T> const& rhs)\n\t\t: library_{rhs.library_}\n\t\t, id_{rhs.expired() ? 0 : rhs.id_}\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t<Y> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\t\/\/static_assert(std::is_convertible<Y*, T*>::value, \"bad cast\");\n\t\tlibrary_->table_.retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t<Y>&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::~asset_handle_t()\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t const& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t&& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t<Y> const& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t<Y>&& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\n\n\n\ttemplate <typename Y, typename T>\n\tinline auto polymorphic_asset_cast(asset_handle_t<T> const& x) -> asset_handle_t<Y>\n\t{\n\t\tstatic_assert(std::is_base_of<T, Y>::value, \"bad cast\");\n\t\tATMA_ASSERT(nullptr != dynamic_cast<Y const*>(&*x), \"bad cast\");\n\t\treturn asset_handle_t<Y>{x.library_, x.id_};\n\t}\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tinline constexpr asset_weak_handle_t<T>::asset_weak_handle_t()\n\t{}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_handle_t<T> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t<Y> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tstatic_assert(std::is_convertible<Y*, T*>::value, \"bad cast\");\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t<Y>&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::~asset_weak_handle_t()\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t const& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t&& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t<Y> const& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t<Y>&& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::expired() const -> bool\n\t{\n\t\treturn library_->table_.expired(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::lock() const -> asset_handle_t<T>\n\t{\n\t\tif (expired())\n\t\t\treturn asset_handle_t<T>{library_, 0};\n\t\telse\n\t\t\treturn asset_handle_t<T>{library_, id_};\n\t}\n}\n\n\n\n\n\n\n\n\n\n\/\/ asset_library_t\nnamespace lion\n{\n\tstruct asset_library_t\n\t{\n\t\tasset_library_t();\n\t\tasset_library_t(vfs_t*);\n\n\t\tauto register_loader(atma::string const& regex) -> void;\n\n\t\tauto store(asset_t*) -> base_asset_handle_t;\n\n\tprivate: \/\/ table management\n\t\tstruct storage_t;\n\n\t\tauto find(uint32) -> storage_t*;\n\t\tauto find(uint32) const -> storage_t const*;\n\n\t\tatma::handle_table_t<storage_t> table_;\n\n\tprivate: \/\/ vfs\n\t\tvfs_t* vfs_ = nullptr;\n\n\tprivate:\n\t\ttemplate <typename> friend struct asset_handle_t;\n\t\ttemplate <typename> friend struct asset_weak_handle_t;\n\t};\n\n\n\tstruct asset_library_t::storage_t\n\t{\n\t\tstorage_t(asset_t* a)\n\t\t\t: asset{a}\n\t\t\t, generation{}\n\t\t{}\n\n\t\tstd::unique_ptr<asset_t> asset;\n\t\tuint8 generation;\n\t};\n\n}\n<commit_msg>prototypes for future functionality<commit_after>#pragma once\n\n#include <lion\/filesystem.hpp>\n\n#include <atma\/intrusive_ptr.hpp>\n#include <atma\/vector.hpp>\n#include <atma\/atomic.hpp>\n#include <atma\/handle_table.hpp>\n#include <atma\/enable_if.hpp>\n\n#include <tuple>\n#include <type_traits>\n\n\n\/\/ forward declares\nnamespace lion\n{\n\tstruct asset_t;\n\tstruct asset_library_t;\n\ttemplate <typename> struct asset_handle_t;\n\ttemplate <typename> struct asset_weak_handle_t;\n}\n\n\n\/\/ asset_t\nnamespace lion\n{\n\tstruct asset_t\n\t{\n\t\tauto path() const -> path_t const& { return path_; }\n\t\tvirtual ~asset_t() {}\n\tprivate:\n\t\tpath_t path_;\n\t};\n}\n\n\n\n\/\/ asset_handle_t \/ asset_weak_handle_t\nnamespace lion\n{\n\ttemplate <typename T>\n\tstruct asset_handle_t\n\t{\n\t\tconstexpr asset_handle_t();\n\t\tasset_handle_t(asset_handle_t const& rhs);\n\t\tasset_handle_t(asset_handle_t&& rhs);\n\t\t~asset_handle_t();\n\n\t\texplicit asset_handle_t(asset_weak_handle_t<T> const&);\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tasset_handle_t(asset_handle_t<Y> const& rhs);\n\t\ttemplate <typename Y, typename = atma::enable_if<std::is_convertible<Y*, T*>>>\n\t\tasset_handle_t(asset_handle_t<Y>&& rhs);\n\n\n\t\tauto operator = (asset_handle_t const& rhs) -> asset_handle_t&;\n\t\tauto operator = (asset_handle_t&& rhs) -> asset_handle_t&;\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_handle_t<Y> const& rhs) -> asset_handle_t&;\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_handle_t<Y>&& rhs) -> asset_handle_t&;\n\n\t\tauto operator -> () const -> T const* { return (T const*)library_->find(id_)->asset.get(); }\n\t\tauto operator -> () -> T* { return (T *)library_->find(id_)->asset.get(); }\n\t\tauto operator *() const -> T const& { return *this->operator ->(); }\n\t\tauto operator *() -> T& { return *this->operator ->(); }\n\n\t\toperator bool() const { return id_ != 0; }\n\n\t\tauto library() const -> asset_library_t* { return library_; }\n\t\tauto id() const -> uint32 { return id_; }\n\n\tprivate:\n\t\tasset_handle_t(asset_library_t* library, uint32 id)\n\t\t\t: library_{library}, id_{id}\n\t\t{}\n\n\tprivate:\n\t\tasset_library_t* library_ = nullptr;\n\t\tuint32 id_ = 0;\n\n\t\tfriend struct asset_library_t;\n\t\ttemplate <typename> friend struct asset_handle_t;\n\t\ttemplate <typename> friend struct asset_weak_handle_t;\n\n\t\ttemplate <typename Y, typename Y2>\n\t\tfriend auto polymorphic_asset_cast(asset_handle_t<Y2> const&) -> asset_handle_t<Y>;\n\t};\n\n\tusing base_asset_handle_t = asset_handle_t<asset_t>;\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tstruct asset_weak_handle_t\n\t{\n\t\tconstexpr asset_weak_handle_t();\n\t\tasset_weak_handle_t(asset_weak_handle_t const&);\n\t\tasset_weak_handle_t(asset_weak_handle_t&&);\n\t\t~asset_weak_handle_t();\n\n\t\tasset_weak_handle_t(asset_handle_t<T> const&);\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tasset_weak_handle_t(asset_weak_handle_t<Y> const& rhs);\n\t\ttemplate <typename Y, typename = atma::enable_if<std::is_convertible<Y*, T*>>>\n\t\tasset_weak_handle_t(asset_weak_handle_t<Y>&& rhs);\n\n\t\tauto operator = (asset_weak_handle_t const&) -> asset_weak_handle_t&;\n\t\tauto operator = (asset_weak_handle_t&&) -> asset_weak_handle_t&;\n\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_weak_handle_t<Y> const& rhs) -> asset_weak_handle_t&;\n\t\ttemplate <typename Y, typename = std::enable_if_t<std::is_convertible<Y*, T*>::value>>\n\t\tauto operator = (asset_weak_handle_t<Y>&& rhs) -> asset_weak_handle_t&;\n\n\t\tauto library() const -> asset_library_t* { return library_; }\n\t\tauto id() const -> uint32 { return id_; }\n\n\t\tauto expired() const -> bool;\n\t\tauto lock() const -> asset_handle_t<T>;\n\n\tprivate:\n\t\tasset_library_t* library_ = nullptr;\n\t\tuint32 id_ = 0;\n\t};\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tinline constexpr asset_handle_t<T>::asset_handle_t()\n\t{}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.retain(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::asset_handle_t(asset_weak_handle_t<T> const& rhs)\n\t\t: library_{rhs.library_}\n\t\t, id_{rhs.expired() ? 0 : rhs.id_}\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t<Y> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\t\/\/static_assert(std::is_convertible<Y*, T*>::value, \"bad cast\");\n\t\tlibrary_->table_.retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_handle_t<T>::asset_handle_t(asset_handle_t<Y>&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_handle_t<T>::~asset_handle_t()\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t const& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t&& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t<Y> const& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_handle_t<T>::operator = (asset_handle_t<Y>&& rhs) -> asset_handle_t&\n\t{\n\t\tthis->~asset_handle_t();\n\t\tnew (this) asset_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\n\n\n\ttemplate <typename Y, typename T>\n\tinline auto polymorphic_asset_cast(asset_handle_t<T> const& x) -> asset_handle_t<Y>\n\t{\n\t\tstatic_assert(std::is_base_of<T, Y>::value, \"bad cast\");\n\t\tATMA_ASSERT(nullptr != dynamic_cast<Y const*>(&*x), \"bad cast\");\n\t\treturn asset_handle_t<Y>{x.library_, x.id_};\n\t}\n}\n\n\nnamespace lion\n{\n\ttemplate <typename T>\n\tinline constexpr asset_weak_handle_t<T>::asset_weak_handle_t()\n\t{}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_handle_t<T> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t<Y> const& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\tstatic_assert(std::is_convertible<Y*, T*>::value, \"bad cast\");\n\t\tlibrary_->table_.weak_retain(id_);\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline asset_weak_handle_t<T>::asset_weak_handle_t(asset_weak_handle_t<Y>&& rhs)\n\t\t: library_{rhs.library_}, id_{rhs.id_}\n\t{\n\t\trhs.id_ = 0;\n\t}\n\n\ttemplate <typename T>\n\tinline asset_weak_handle_t<T>::~asset_weak_handle_t()\n\t{\n\t\tlibrary_->table_.release(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t const& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t&& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t<Y> const& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{rhs};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\ttemplate <typename Y, typename>\n\tinline auto asset_weak_handle_t<T>::operator = (asset_weak_handle_t<Y>&& rhs) -> asset_weak_handle_t&\n\t{\n\t\tthis->~asset_weak_handle_t();\n\t\tnew (this) asset_weak_handle_t{std::move(rhs)};\n\t\treturn *this;\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::expired() const -> bool\n\t{\n\t\treturn library_->table_.expired(id_);\n\t}\n\n\ttemplate <typename T>\n\tinline auto asset_weak_handle_t<T>::lock() const -> asset_handle_t<T>\n\t{\n\t\tif (expired())\n\t\t\treturn asset_handle_t<T>{library_, 0};\n\t\telse\n\t\t\treturn asset_handle_t<T>{library_, id_};\n\t}\n}\n\n\n\n\n\n\n\n\n\n\/\/ asset_library_t\nnamespace lion\n{\n\tstruct asset_library_t\n\t{\n\t\tasset_library_t();\n\t\tasset_library_t(vfs_t*);\n\n\t\tauto register_loader(atma::string const& regex) -> void;\n\n\t\tauto store(asset_t*) -> base_asset_handle_t;\n\n\t\t\/\/auto load(atma::string const& path) -> base_asset_handle_t;\n\t\t\/\/auto load(asset_collection_t, atma::string const& path) -> base_asset_handle_t;\n\n\tprivate: \/\/ table management\n\t\tstruct storage_t;\n\n\t\tauto find(uint32) -> storage_t*;\n\t\tauto find(uint32) const -> storage_t const*;\n\n\t\tatma::handle_table_t<storage_t> table_;\n\n\tprivate: \/\/ vfs\n\t\tvfs_t* vfs_ = nullptr;\n\n\tprivate:\n\t\ttemplate <typename> friend struct asset_handle_t;\n\t\ttemplate <typename> friend struct asset_weak_handle_t;\n\t};\n\n\n\tstruct asset_library_t::storage_t\n\t{\n\t\tstorage_t(asset_t* a)\n\t\t\t: asset{a}\n\t\t\t, generation{}\n\t\t{}\n\n\t\tstd::unique_ptr<asset_t> asset;\n\t\tuint8 generation;\n\t};\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __QUEUE_HPP_INCLUDED__\n#define __QUEUE_HPP_INCLUDED__\n\n#include <cstdint>\n#include <fstream>\n#include <mutex>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n\n#include \"serialization.hpp\"\n\nnamespace fs = boost::filesystem;\n\n\ntemplate <typename T>\nclass BaseQueue\n{\nprivate:\n\n virtual T getElementAt(int64_t index) = 0;\n\n virtual int64_t getElementSizeAt(int64_t index) = 0;\n\n virtual int64_t getFirstElementIndex() = 0;\n\n virtual int64_t getLastElementIndex() = 0;\n\n class Iterator\n {\n public:\n\n Iterator(BaseQueue<T> *queue_, int64_t index_)\n : queue(queue_), index(index_)\n {\n }\n\n T operator*()\n {\n return queue->getElementAt(index);\n }\n\n Iterator& operator++()\n {\n int64_t size = queue->getElementSizeAt(index);\n index += size;\n return *this;\n }\n\n bool operator!=(const Iterator& iterator)\n {\n return index != iterator.index;\n }\n\n private:\n\n BaseQueue<T> *queue;\n\n int64_t index;\n };\n\npublic:\n\n virtual void Enqueue(T e) = 0;\n\n virtual void Dequeue() = 0;\n\n virtual T Last() = 0;\n\n Iterator begin()\n {\n return Iterator(this, getFirstElementIndex());\n }\n\n Iterator end()\n {\n return Iterator(this, getLastElementIndex());\n }\n};\n\n\ntemplate <typename T>\nclass VolatileQueue : public BaseQueue<T>\n{\npublic:\n\n void Enqueue(T e)\n {\n data.push_back(e);\n }\n\n void Dequeue()\n {\n if (!data.empty())\n {\n data.erase(data.begin());\n }\n }\n\n T Last()\n {\n T empty;\n return data.size() > 0 ? data[data.size() - 1 ] : empty;\n }\n\nprivate:\n\n T getElementAt(int64_t index)\n {\n return data[index];\n }\n\n int64_t getElementSizeAt(int64_t index)\n {\n return 1;\n }\n\n int64_t getFirstElementIndex()\n {\n return 0;\n }\n\n int64_t getLastElementIndex()\n {\n return data.size();\n }\n\n std::vector<T> data;\n};\n\n\ntemplate <typename T>\nclass PersistentQueue : public BaseQueue<T>\n{\npublic:\n\n PersistentQueue(std::string filename)\n : PersistentQueue(\".\", filename)\n {\n }\n\n PersistentQueue(std::string dirname, std::string filename)\n : file((fs::path(dirname) \/ fs::path(filename)).string(),\n std::ios::out | std::ios::in | std::ios::app | std::ios::binary),\n stream(file),\n insert_file((fs::path(dirname) \/ fs::path(filename)).string(),\n std::ios::in | std::ios::out | std::ios::binary),\n insert_stream(insert_file),\n start_position(0),\n end_position(0),\n mutex()\n {\n SaveOffsets();\n LoadOffsets();\n }\n\n PersistentQueue(std::iostream& stream)\n : stream(stream),\n insert_stream(stream),\n start_position(0),\n end_position(0),\n mutex()\n {\n SaveOffsets();\n LoadOffsets();\n }\n\n ~PersistentQueue()\n {\n stream.flush();\n }\n\n void SaveOffsets()\n {\n stream.seekg(0, std::ios::end);\n if (stream.tellg() < HEADER_SIZE)\n {\n start_position = HEADER_SIZE;\n end_position = UNINITIALIZED;\n }\n\n \/\/insert_stream.seekp(0, std::ios::beg);\n insert_stream << std::setw(INDEX_SIZE) << start_position;\n insert_stream << std::setw(INDEX_SIZE) << end_position;\n insert_stream.flush();\n }\n\n void LoadOffsets()\n {\n stream.seekg(0, std::ios::beg);\n\n std::string buffer;\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n start_position = std::stoi(buffer);\n\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n end_position = std::stoi(buffer);\n }\n\n void Enqueue(T e)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n std::string element_as_string = Serialize<T>(e);\n\n LoadOffsets();\n\n stream.seekg(0, std::ios::end);\n end_position = stream.tellg();\n\n insert_stream.seekp(INDEX_SIZE, std::ios::beg);\n insert_stream << std::setw(INDEX_SIZE) << end_position;\n insert_stream.flush();\n\n stream.seekp(0, std::ios::end);\n stream << element_as_string;\n stream.flush();\n }\n\n void Dequeue()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n LoadOffsets();\n\n for (T element : *this)\n {\n start_position += Serialize<T>(element).length();\n stream.seekp(0, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << start_position;\n break;\n }\n }\n\n T Last()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n T empty;\n stream.seekg(0, std::ios::end);\n if (stream.tellg() <= HEADER_SIZE)\n {\n return empty;\n }\n\n LoadOffsets();\n\n stream.seekg(end_position, std::ios::beg);\n\n return Deserialize<T>(stream);\n }\n\nprivate:\n\n T getElementAt(int64_t index)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(index, std::ios::beg);\n return Deserialize<T>(stream);\n }\n\n int64_t getElementSizeAt(int64_t index)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(index, std::ios::beg);\n return Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n int64_t getFirstElementIndex()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n LoadOffsets();\n\n return start_position;\n }\n\n int64_t getLastElementIndex()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(0, std::ios::end);\n return stream.tellg();\n }\n\n std::fstream file;\n\n std::iostream& stream;\n\n std::fstream insert_file;\n\n std::iostream& insert_stream;\n\n std::streampos start_position;\n\n std::streampos end_position;\n\n std::recursive_mutex mutex;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 2;\n\n constexpr static const int64_t UNINITIALIZED = -1;\n};\n\n\ntemplate <typename T>\nclass RolloverQueue\n{\nprivate:\n\n std::streampos get_start_position()\n {\n stream.seekg(0 * INDEX_SIZE, std::ios::beg);\n std::string buffer;\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n return static_cast<std::streampos>(std::stoi(buffer));\n }\n\n std::streampos get_end_position()\n {\n if (file.is_open())\n {\n stream.rdbuf(file.rdbuf());\n }\n stream.seekg(1 * INDEX_SIZE, std::ios::beg);\n std::string buffer(INDEX_SIZE, '\\0');\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n return static_cast<std::streampos>(std::stoi(buffer));\n }\n\n std::streampos get_eof_position()\n {\n stream.seekg(0, std::ios::end);\n return stream.tellg();\n }\n\n std::fstream file;\n\n std::iostream& stream;\n\n std::streampos rollover_size;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t UNINITIALIZED = 0;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 2;\n\n constexpr static const int64_t DEFAULT_ROLLOVER_SIZE = 1000000000;\n\n class Iterator\n {\n public:\n\n Iterator(\n std::iostream& stream,\n std::streampos position,\n std::streampos rollover\n )\n : stream(stream),\n position(position),\n rollover(rollover)\n {\n }\n\n T operator*()\n {\n stream.seekg(position, std::ios::beg);\n\n return Deserialize<T>(stream);\n }\n\n Iterator& operator++()\n {\n if (position <= rollover)\n {\n stream.seekg(position, std::ios::beg);\n position += Serialize<T>(Deserialize<T>(stream)).length();\n }\n else\n {\n position = HEADER_SIZE;\n }\n\n return *this;\n }\n\n bool operator!=(const Iterator& iterator)\n {\n return position != iterator.position;\n }\n\n private:\n\n std::iostream& stream;\n\n std::streampos position;\n\n std::streampos rollover;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 3;\n };\n\npublic:\n\n RolloverQueue(std::string filename)\n : RolloverQueue(\".\", filename)\n {\n }\n\n RolloverQueue(\n std::string dirname,\n std::string filename,\n std::streampos rollover_size=DEFAULT_ROLLOVER_SIZE\n ) : file((boost::filesystem::path(dirname) \/\n boost::filesystem::path(filename)).string(),\n std::ios::out | std::ios::in | std::ios::binary),\n stream(file),\n rollover_size(rollover_size)\n {\n auto path = (boost::filesystem::path(dirname) \/\n boost::filesystem::path(filename)).string();\n if (!boost::filesystem::exists(path))\n {\n file.open(path, std::ios::out | std::ios::app | std::ios::binary);\n file << std::setw(INDEX_SIZE) << HEADER_SIZE;\n file << std::setw(INDEX_SIZE) << UNINITIALIZED;\n file.flush();\n file.close();\n file.open(path, std::ios::out | std::ios::in | std::ios::binary);\n }\n }\n\n RolloverQueue(\n std::iostream& stream,\n std::streampos rollover_size=DEFAULT_ROLLOVER_SIZE\n ) : stream(stream),\n rollover_size(rollover_size)\n {\n stream.seekg(0, std::ios::end);\n if (stream.tellg() < HEADER_SIZE)\n {\n stream << std::setw(INDEX_SIZE) << HEADER_SIZE;\n stream << std::setw(INDEX_SIZE) << UNINITIALIZED;\n }\n }\n\n void Enqueue(T e)\n {\n std::string element_as_string = Serialize<T>(e);\n auto size = element_as_string.length();\n\n std::streampos position = get_end_position();\n if (position == UNINITIALIZED)\n {\n position = HEADER_SIZE;\n }\n else\n {\n stream.seekg(position, std::ios::beg);\n position += Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n if (rollover_size < position + static_cast<std::streampos>(size))\n {\n std::streampos eof = get_eof_position();\n\n \/\/ rollover and over-write existing entries\n auto start = static_cast<std::streampos>(HEADER_SIZE);\n while (start - HEADER_SIZE < size && start != eof)\n {\n stream.seekg(start, std::ios::beg);\n start += Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n if (start == eof)\n {\n start = HEADER_SIZE;\n }\n\n \/\/ update start position\n stream.seekp(0 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << start;\n stream.flush();\n position = start;\n }\n\n \/\/ flush element\n stream.seekp(position, std::ios::beg);\n stream << element_as_string;\n stream.flush();\n\n \/\/ update end position\n stream.seekp(1 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << position;\n stream.flush();\n }\n\n void Dequeue()\n {\n auto position = get_start_position();\n stream.seekg(position, std::ios::beg);\n\n auto next = position + static_cast<std::streampos>(\n Serialize<T>(Deserialize<T>(stream)).length());\n\n stream.seekp(0 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << next;\n }\n\n T Last()\n {\n auto position = get_end_position();\n\n stream.seekg(position, std::ios::beg);\n return Deserialize<T>(stream);\n }\n\n Iterator begin()\n {\n return Iterator(stream, get_start_position(), rollover_size);\n }\n\n Iterator end()\n {\n auto start = get_start_position();\n auto end = get_end_position();\n auto eof = get_eof_position();\n if (end == UNINITIALIZED || end == eof)\n {\n end = start;\n }\n else\n {\n stream.seekg(end, std::ios::beg);\n end += Serialize<T>(Deserialize<T>(stream)).length();\n }\n return Iterator(stream, end, rollover_size);\n }\n};\n\n\n#endif\n<commit_msg>Update default ledger size to 4GB<commit_after>#ifndef __QUEUE_HPP_INCLUDED__\n#define __QUEUE_HPP_INCLUDED__\n\n#include <cstdint>\n#include <fstream>\n#include <mutex>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n\n#include \"serialization.hpp\"\n\nnamespace fs = boost::filesystem;\n\n\ntemplate <typename T>\nclass BaseQueue\n{\nprivate:\n\n virtual T getElementAt(int64_t index) = 0;\n\n virtual int64_t getElementSizeAt(int64_t index) = 0;\n\n virtual int64_t getFirstElementIndex() = 0;\n\n virtual int64_t getLastElementIndex() = 0;\n\n class Iterator\n {\n public:\n\n Iterator(BaseQueue<T> *queue_, int64_t index_)\n : queue(queue_), index(index_)\n {\n }\n\n T operator*()\n {\n return queue->getElementAt(index);\n }\n\n Iterator& operator++()\n {\n int64_t size = queue->getElementSizeAt(index);\n index += size;\n return *this;\n }\n\n bool operator!=(const Iterator& iterator)\n {\n return index != iterator.index;\n }\n\n private:\n\n BaseQueue<T> *queue;\n\n int64_t index;\n };\n\npublic:\n\n virtual void Enqueue(T e) = 0;\n\n virtual void Dequeue() = 0;\n\n virtual T Last() = 0;\n\n Iterator begin()\n {\n return Iterator(this, getFirstElementIndex());\n }\n\n Iterator end()\n {\n return Iterator(this, getLastElementIndex());\n }\n};\n\n\ntemplate <typename T>\nclass VolatileQueue : public BaseQueue<T>\n{\npublic:\n\n void Enqueue(T e)\n {\n data.push_back(e);\n }\n\n void Dequeue()\n {\n if (!data.empty())\n {\n data.erase(data.begin());\n }\n }\n\n T Last()\n {\n T empty;\n return data.size() > 0 ? data[data.size() - 1 ] : empty;\n }\n\nprivate:\n\n T getElementAt(int64_t index)\n {\n return data[index];\n }\n\n int64_t getElementSizeAt(int64_t index)\n {\n return 1;\n }\n\n int64_t getFirstElementIndex()\n {\n return 0;\n }\n\n int64_t getLastElementIndex()\n {\n return data.size();\n }\n\n std::vector<T> data;\n};\n\n\ntemplate <typename T>\nclass PersistentQueue : public BaseQueue<T>\n{\npublic:\n\n PersistentQueue(std::string filename)\n : PersistentQueue(\".\", filename)\n {\n }\n\n PersistentQueue(std::string dirname, std::string filename)\n : file((fs::path(dirname) \/ fs::path(filename)).string(),\n std::ios::out | std::ios::in | std::ios::app | std::ios::binary),\n stream(file),\n insert_file((fs::path(dirname) \/ fs::path(filename)).string(),\n std::ios::in | std::ios::out | std::ios::binary),\n insert_stream(insert_file),\n start_position(0),\n end_position(0),\n mutex()\n {\n SaveOffsets();\n LoadOffsets();\n }\n\n PersistentQueue(std::iostream& stream)\n : stream(stream),\n insert_stream(stream),\n start_position(0),\n end_position(0),\n mutex()\n {\n SaveOffsets();\n LoadOffsets();\n }\n\n ~PersistentQueue()\n {\n stream.flush();\n }\n\n void SaveOffsets()\n {\n stream.seekg(0, std::ios::end);\n if (stream.tellg() < HEADER_SIZE)\n {\n start_position = HEADER_SIZE;\n end_position = UNINITIALIZED;\n }\n\n \/\/insert_stream.seekp(0, std::ios::beg);\n insert_stream << std::setw(INDEX_SIZE) << start_position;\n insert_stream << std::setw(INDEX_SIZE) << end_position;\n insert_stream.flush();\n }\n\n void LoadOffsets()\n {\n stream.seekg(0, std::ios::beg);\n\n std::string buffer;\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n start_position = std::stoi(buffer);\n\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n end_position = std::stoi(buffer);\n }\n\n void Enqueue(T e)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n std::string element_as_string = Serialize<T>(e);\n\n LoadOffsets();\n\n stream.seekg(0, std::ios::end);\n end_position = stream.tellg();\n\n insert_stream.seekp(INDEX_SIZE, std::ios::beg);\n insert_stream << std::setw(INDEX_SIZE) << end_position;\n insert_stream.flush();\n\n stream.seekp(0, std::ios::end);\n stream << element_as_string;\n stream.flush();\n }\n\n void Dequeue()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n LoadOffsets();\n\n for (T element : *this)\n {\n start_position += Serialize<T>(element).length();\n stream.seekp(0, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << start_position;\n break;\n }\n }\n\n T Last()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n T empty;\n stream.seekg(0, std::ios::end);\n if (stream.tellg() <= HEADER_SIZE)\n {\n return empty;\n }\n\n LoadOffsets();\n\n stream.seekg(end_position, std::ios::beg);\n\n return Deserialize<T>(stream);\n }\n\nprivate:\n\n T getElementAt(int64_t index)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(index, std::ios::beg);\n return Deserialize<T>(stream);\n }\n\n int64_t getElementSizeAt(int64_t index)\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(index, std::ios::beg);\n return Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n int64_t getFirstElementIndex()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n LoadOffsets();\n\n return start_position;\n }\n\n int64_t getLastElementIndex()\n {\n std::lock_guard<std::recursive_mutex> lock(mutex);\n\n stream.seekg(0, std::ios::end);\n return stream.tellg();\n }\n\n std::fstream file;\n\n std::iostream& stream;\n\n std::fstream insert_file;\n\n std::iostream& insert_stream;\n\n std::streampos start_position;\n\n std::streampos end_position;\n\n std::recursive_mutex mutex;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 2;\n\n constexpr static const int64_t UNINITIALIZED = -1;\n};\n\n\ntemplate <typename T>\nclass RolloverQueue\n{\nprivate:\n\n std::streampos get_start_position()\n {\n stream.seekg(0 * INDEX_SIZE, std::ios::beg);\n std::string buffer;\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n return static_cast<std::streampos>(std::stoi(buffer));\n }\n\n std::streampos get_end_position()\n {\n if (file.is_open())\n {\n stream.rdbuf(file.rdbuf());\n }\n stream.seekg(1 * INDEX_SIZE, std::ios::beg);\n std::string buffer(INDEX_SIZE, '\\0');\n stream.read(&buffer[0], INDEX_SIZE);\n boost::trim(buffer);\n return static_cast<std::streampos>(std::stoi(buffer));\n }\n\n std::streampos get_eof_position()\n {\n stream.seekg(0, std::ios::end);\n return stream.tellg();\n }\n\n std::fstream file;\n\n std::iostream& stream;\n\n std::streampos rollover_size;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t UNINITIALIZED = 0;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 2;\n\n constexpr static const int64_t DEFAULT_ROLLOVER_SIZE = 0x400000000;\n\n class Iterator\n {\n public:\n\n Iterator(\n std::iostream& stream,\n std::streampos position,\n std::streampos rollover\n )\n : stream(stream),\n position(position),\n rollover(rollover)\n {\n }\n\n T operator*()\n {\n stream.seekg(position, std::ios::beg);\n\n return Deserialize<T>(stream);\n }\n\n Iterator& operator++()\n {\n if (position <= rollover)\n {\n stream.seekg(position, std::ios::beg);\n position += Serialize<T>(Deserialize<T>(stream)).length();\n }\n else\n {\n position = HEADER_SIZE;\n }\n\n return *this;\n }\n\n bool operator!=(const Iterator& iterator)\n {\n return position != iterator.position;\n }\n\n private:\n\n std::iostream& stream;\n\n std::streampos position;\n\n std::streampos rollover;\n\n constexpr static const int64_t INDEX_SIZE = 10;\n\n constexpr static const int64_t HEADER_SIZE = INDEX_SIZE * 3;\n };\n\npublic:\n\n RolloverQueue(std::string filename)\n : RolloverQueue(\".\", filename)\n {\n }\n\n RolloverQueue(\n std::string dirname,\n std::string filename,\n std::streampos rollover_size=DEFAULT_ROLLOVER_SIZE\n ) : file((boost::filesystem::path(dirname) \/\n boost::filesystem::path(filename)).string(),\n std::ios::out | std::ios::in | std::ios::binary),\n stream(file),\n rollover_size(rollover_size)\n {\n auto path = (boost::filesystem::path(dirname) \/\n boost::filesystem::path(filename)).string();\n if (!boost::filesystem::exists(path))\n {\n file.open(path, std::ios::out | std::ios::app | std::ios::binary);\n file << std::setw(INDEX_SIZE) << HEADER_SIZE;\n file << std::setw(INDEX_SIZE) << UNINITIALIZED;\n file.flush();\n file.close();\n file.open(path, std::ios::out | std::ios::in | std::ios::binary);\n }\n }\n\n RolloverQueue(\n std::iostream& stream,\n std::streampos rollover_size=DEFAULT_ROLLOVER_SIZE\n ) : stream(stream),\n rollover_size(rollover_size)\n {\n stream.seekg(0, std::ios::end);\n if (stream.tellg() < HEADER_SIZE)\n {\n stream << std::setw(INDEX_SIZE) << HEADER_SIZE;\n stream << std::setw(INDEX_SIZE) << UNINITIALIZED;\n }\n }\n\n void Enqueue(T e)\n {\n std::string element_as_string = Serialize<T>(e);\n auto size = element_as_string.length();\n\n std::streampos position = get_end_position();\n if (position == UNINITIALIZED)\n {\n position = HEADER_SIZE;\n }\n else\n {\n stream.seekg(position, std::ios::beg);\n position += Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n if (rollover_size < position + static_cast<std::streampos>(size))\n {\n std::streampos eof = get_eof_position();\n\n \/\/ rollover and over-write existing entries\n auto start = static_cast<std::streampos>(HEADER_SIZE);\n while (start - HEADER_SIZE < size && start != eof)\n {\n stream.seekg(start, std::ios::beg);\n start += Serialize<T>(Deserialize<T>(stream)).length();\n }\n\n if (start == eof)\n {\n start = HEADER_SIZE;\n }\n\n \/\/ update start position\n stream.seekp(0 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << start;\n stream.flush();\n position = start;\n }\n\n \/\/ flush element\n stream.seekp(position, std::ios::beg);\n stream << element_as_string;\n stream.flush();\n\n \/\/ update end position\n stream.seekp(1 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << position;\n stream.flush();\n }\n\n void Dequeue()\n {\n auto position = get_start_position();\n stream.seekg(position, std::ios::beg);\n\n auto next = position + static_cast<std::streampos>(\n Serialize<T>(Deserialize<T>(stream)).length());\n\n stream.seekp(0 * INDEX_SIZE, std::ios::beg);\n stream << std::setw(INDEX_SIZE) << next;\n }\n\n T Last()\n {\n auto position = get_end_position();\n\n stream.seekg(position, std::ios::beg);\n return Deserialize<T>(stream);\n }\n\n Iterator begin()\n {\n return Iterator(stream, get_start_position(), rollover_size);\n }\n\n Iterator end()\n {\n auto start = get_start_position();\n auto end = get_end_position();\n auto eof = get_eof_position();\n if (end == UNINITIALIZED || end == eof)\n {\n end = start;\n }\n else\n {\n stream.seekg(end, std::ios::beg);\n end += Serialize<T>(Deserialize<T>(stream)).length();\n }\n return Iterator(stream, end, rollover_size);\n }\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef SIMPLE_XDMF_HPP_INCLUDED\n#define SIMPLE_XDMF_HPP_INCLUDED\n\n#include <string>\n\nclass SimpleXdmf {\n private:\n const std::string header = R\"(<?xml version=\"1.0\" ?>\n<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>)\";\n std::string version;\n std::string content;\n\n public:\n SimpleXdmf(const std::string& _version = \"3.0\") {\n version = _version;\n\n content = header;\n }\n\n enum class DataItemType {Uniform};\n enum class TopologyType {twoDRectMesh};\n enum class GeometryType {Uniform};\n enum class AttributeType {Scalar, Vector};\n enum class AttributeCenter {Node};\n\n static void addDomain();\n\n void beginTopology(TopologyType type) {\n content += \"<Topology TopologyType=\\\"2DRectMesh\\\">\";\n }\n void endTopology() {\n content += \"<\/Topology>\";\n }\n\n void beginGeometory(GeometryType type){\n content += \"<Geometry GeometryType=\\\"2DRectMesh\\\">\";\n }\n void endGeometory(){\n content += \"<\/Geometry>\";\n }\n\n void beginDataItem(DataItemType type) {\n content += \"<DataItem ItemType=\\\"Uniform\\\">\";\n }\n void endDataItem() {\n content += \"<\/DataItem>\";\n }\n};\n\n#endif<commit_msg>NewLineCode and Indentation Management.<commit_after>#ifndef SIMPLE_XDMF_HPP_INCLUDED\n#define SIMPLE_XDMF_HPP_INCLUDED\n\n#include <string>\n#include <fstream>\n\nclass SimpleXdmf {\n private:\n const std::string header = R\"(\n<?xml version=\"1.0\" ?>\n<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n)\";\n std::string content;\n std::string version;\n std::string newLine;\n std::string indent;\n\n unsigned int currentIndentation = 0;\n bool endEdit = false;\n\n void addIndent() {\n ++currentIndentation;\n }\n\n void backIndent() {\n if (currentIndentation > 0) --currentIndentation;\n }\n\n void insertIndent() {\n for(unsigned int i = 0; i < currentIndentation; ++i) {\n content += indent;\n }\n }\n\n void beginElement() {\n addIndent();\n insertIndent();\n }\n\n void endElement() {\n backIndent();\n }\n\n public:\n SimpleXdmf(const std::string& _version = \"3.0\") {\n version = _version;\n setNewLineCode();\n setIndent();\n beginXdmf();\n }\n\n void setIndent(const int size = 4) {\n if (size == 0) {\n indent = '\\t';\n return;\n }\n\n for (int i = 0; i < size; ++i) {\n indent += ' ';\n }\n }\n\n void setNewLineCode() {\n const char CR = '\\r';\n const char LF = '\\n';\n const char* CRLF = \"\\r\\n\";\n\n newLine = LF;\n }\n\n void generate(const std::string file_name) {\n if(!endEdit) endXdmf();\n\n std::ofstream ofs(file_name, std::ios::out);\n ofs << content << std::endl;\n }\n\n void beginXdmf() {\n endEdit = false;\n content = header + \"<Xdmf Version=\\\"\" + version + \"\\\">\" + newLine;\n }\n\n void endXdmf() {\n content += \"<\/Xdmf>\";\n endEdit = true;\n }\n\n enum class DataItemType {Uniform};\n enum class TopologyType {twoDRectMesh};\n enum class GeometryType {Uniform};\n enum class AttributeType {Scalar, Vector};\n enum class AttributeCenter {Node};\n\n void beginDomain() {\n beginElement();\n content += \"<Domain>\" + newLine;\n };\n\n void endDomain() {\n insertIndent();\n content += \"<\/Domain>\" + newLine;\n endElement();\n };\n\n void beginTopology(TopologyType type = TopologyType::twoDRectMesh) {\n beginElement();\n content += \"<Topology TopologyType=\\\"2DRectMesh\\\">\" + newLine;\n }\n void endTopology() {\n insertIndent();\n content += \"<\/Topology>\" + newLine;\n endElement();\n }\n\n void beginGeometory(GeometryType type = GeometryType::Uniform){\n beginElement();\n content += \"<Geometry GeometryType=\\\"2DRectMesh\\\">\" + newLine;\n }\n void endGeometory(){\n insertIndent();\n content += \"<\/Geometry>\" + newLine;\n endElement();\n }\n\n void beginDataItem(DataItemType type = DataItemType::Uniform) {\n beginElement();\n content += \"<DataItem ItemType=\\\"Uniform\\\">\" + newLine;\n }\n void endDataItem() {\n insertIndent();\n content += \"<\/DataItem>\" + newLine;\n endElement();\n }\n};\n\n#endif<|endoftext|>"} {"text":"<commit_before>#include \"angort.h\"\n#include \"cycle.h\"\n\nnamespace angort {\n\nType *Type::head=NULL;\nstatic bool createTypesDone=false;\n\nint GarbageCollected::globalCount=0;\n\n\/\/#define tdprintf printf\n#define tdprintf if(0)printf\n\nconst char *Type::toString(bool *allocated,const Value *v) const{\n char buf[128];\n snprintf(buf,128,\"<TYPE %s:%p>\",name,v->v.s);\n *allocated=true;\n return strdup(buf);\n}\n\nfloat Type::toFloat(const Value *v) const{\n throw BadConversionException(v->t->name,Types::tFloat->name);\n}\n\nint Type::toInt(const Value *v) const {\n throw BadConversionException(v->t->name,Types::tInteger->name);\n}\n\nvoid Type::createIterator(Value *dest,Value *src){\n Iterator<Value *> *i = makeIterator(src);\n i->first();\n Types::tIter->set(dest,src,i);\n}\n\nvoid Type::clone(Value *out,const Value *in,bool deep){\n \/\/ default action is to just copy the value; collections\n \/\/ need to do more.\n out->copy(in);\n}\n\nvoid Type::add(const char *_name,const char *_id){\n if(getByName(_name))\n throw Exception().set(\"type already exists: %s\",name);\n \n const unsigned char *n = (const unsigned char *)_id;\n id = n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24);\n name = _name;\n next = head;\n head = this;\n \n \/\/ normally symbols are generated after the static initialisation\n \/\/ but before anything else, in createTypes(). This is to make sure\n \/\/ the symbol system has been initialised.\n \/\/ If this type is being added later, say by a plugin, we need to\n \/\/ do it here.\n \n if(createTypesDone){\n nameSymb = SymbolType::getSymbol(name);\n }\n}\n\nType *Type::getByID(const char *_id){\n const unsigned char *n = (const unsigned char *)_id;\n uint32_t i = n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24);\n \n for(Type *t = head;t;t=t->next)\n if(t->id == i)return t;\n return NULL;\n}\n\n\n\nchar *BlockAllocType::allocate(Value *v,int len,Type *type){\n v->clr();\n BlockAllocHeader *h = (BlockAllocHeader *)malloc(len+sizeof(BlockAllocHeader));\n h->refct=1;\n v->v.block = h;\n v->t = type;\n return (char *)(h+1);\n}\n\nbool Type::isIn(Value *v,Value *item){\n Iterator<Value *> *iter = makeIterator(v);\n \n for(iter->first();!iter->isDone();iter->next()){\n if(iter->current()->equalForHashTable(item)){\n return true;\n }\n }\n return false;\n}\n\nconst char *BlockAllocType::getData(const Value *v) const{\n return (const char *)(v->v.block+1);\n}\n\nvoid BlockAllocType::incRef(Value *v){\n BlockAllocHeader *h = v->v.block;\n h->refct++;\n if(!h->refct)\n throw RUNT(\"reference count too large\");\n}\n \nvoid BlockAllocType::decRef(Value *v){\n BlockAllocHeader *h = v->v.block;\n h->refct--;\n if(h->refct==0){\n free(h);\n }\n}\n\nvoid GCType::incRef(Value *v){\n v->v.gc->incRefCt();\n tdprintf(\"incrementing ref count of %s:%p, now %d\\n\",name,v->v.gc,v->v.gc->refct);\n}\n\nvoid GCType::decRef(Value *v){\n bool b = v->v.gc->decRefCt();\n tdprintf(\"decrementing ref count of %s:%p, now %d\\n\",name,v->v.gc,v->v.gc->refct);\n if(b){\n tdprintf(\" AND DELETING %s:%p\\n\",name,v->v.gc);\n delete v->v.gc;\n }\n}\n\nIterator<class Value *> *GCType::makeKeyIterator(Value *v){\n return v->v.gc->makeKeyIterator();\n}\nIterator<class Value *> *GCType::makeValueIterator(Value *v){\n return v->v.gc->makeValueIterator();\n}\n \n\nGarbageCollected *GCType::getGC(Value *v){\n return v->v.gc;\n}\n\nGarbageCollected::GarbageCollected(){\n refct=0;\n globalCount++;\n CycleDetector::getInstance()->add(this);\n}\n\nGarbageCollected::~GarbageCollected(){\n globalCount--;\n CycleDetector::getInstance()->remove(this);\n}\n\n\n\n\n\n\/*\n * \n * New types go down here\n * \n *\/\n\nstatic NoneType _tNone;\nNoneType *Types::tNone= &_tNone;\n\nstatic Type _tDeleted; \/\/ has to be added by hand in createTypes\nType *Types::tDeleted= &_tDeleted;\n\nstatic IntegerType _Int;\nIntegerType *Types::tInteger = &_Int;\n\nstatic FloatType _Float;\nFloatType *Types::tFloat = &_Float;\n\nstatic StringType _String;\nStringType *Types::tString = &_String;\n\nstatic CodeType _Code;\nCodeType *Types::tCode = &_Code;\n\nstatic ClosureType _Closure;\nClosureType *Types::tClosure = &_Closure;\n\nstatic RangeType<int> _IRange;\nRangeType<int> *Types::tIRange = &_IRange;\nstatic RangeType<float> _FRange;\nRangeType<float> *Types::tFRange = &_FRange;\n\nstatic ListType _List;\nListType *Types::tList = &_List;\n\nstatic HashType _Hash;\nHashType *Types::tHash = &_Hash;\n\nstatic SymbolType _Symbol;\nSymbolType *Types::tSymbol = &_Symbol;\n\nstatic NativeType _Native;\nNativeType *Types::tNative = &_Native;\n\nstatic PropType _Prop;\nPropType *Types::tProp = &_Prop;\n\n\n\nstatic IteratorType _Iterator;\nIteratorType *Types::tIter = &_Iterator;\n\n\n\nvoid Types::createTypes(){\n tDeleted->add(\"DELETED\",\"DELE\");\n \n \/\/ because of the undefined execution order of static heap\n \/\/ objects, we set up all the type names here rather than in\n \/\/ \"add\" to make sure the symbol system is already up.\n \n \/\/ IF you add types later in plugins, the system should detect\n \/\/ this.\n \n for(Type *p = Type::head;p;p=p->next){\n p->nameSymb = SymbolType::getSymbol(p->name);\n }\n createTypesDone = true;\n \n \n}\n}\n<commit_msg>Wasn't deleting the iterator for isIn()!<commit_after>#include \"angort.h\"\n#include \"cycle.h\"\n\nnamespace angort {\n\nType *Type::head=NULL;\nstatic bool createTypesDone=false;\n\nint GarbageCollected::globalCount=0;\n\n\/\/#define tdprintf printf\n#define tdprintf if(0)printf\n\nconst char *Type::toString(bool *allocated,const Value *v) const{\n char buf[128];\n snprintf(buf,128,\"<TYPE %s:%p>\",name,v->v.s);\n *allocated=true;\n return strdup(buf);\n}\n\nfloat Type::toFloat(const Value *v) const{\n throw BadConversionException(v->t->name,Types::tFloat->name);\n}\n\nint Type::toInt(const Value *v) const {\n throw BadConversionException(v->t->name,Types::tInteger->name);\n}\n\nvoid Type::createIterator(Value *dest,Value *src){\n Iterator<Value *> *i = makeIterator(src);\n i->first();\n Types::tIter->set(dest,src,i);\n}\n\nvoid Type::clone(Value *out,const Value *in,bool deep){\n \/\/ default action is to just copy the value; collections\n \/\/ need to do more.\n out->copy(in);\n}\n\nvoid Type::add(const char *_name,const char *_id){\n if(getByName(_name))\n throw Exception().set(\"type already exists: %s\",name);\n \n const unsigned char *n = (const unsigned char *)_id;\n id = n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24);\n name = _name;\n next = head;\n head = this;\n \n \/\/ normally symbols are generated after the static initialisation\n \/\/ but before anything else, in createTypes(). This is to make sure\n \/\/ the symbol system has been initialised.\n \/\/ If this type is being added later, say by a plugin, we need to\n \/\/ do it here.\n \n if(createTypesDone){\n nameSymb = SymbolType::getSymbol(name);\n }\n}\n\nType *Type::getByID(const char *_id){\n const unsigned char *n = (const unsigned char *)_id;\n uint32_t i = n[0]+(n[1]<<8)+(n[2]<<16)+(n[3]<<24);\n \n for(Type *t = head;t;t=t->next)\n if(t->id == i)return t;\n return NULL;\n}\n\n\n\nchar *BlockAllocType::allocate(Value *v,int len,Type *type){\n v->clr();\n BlockAllocHeader *h = (BlockAllocHeader *)malloc(len+sizeof(BlockAllocHeader));\n h->refct=1;\n v->v.block = h;\n v->t = type;\n return (char *)(h+1);\n}\n\nbool Type::isIn(Value *v,Value *item){\n Iterator<Value *> *iter = makeIterator(v);\n \n for(iter->first();!iter->isDone();iter->next()){\n if(iter->current()->equalForHashTable(item)){\n delete iter;\n return true;\n }\n }\n delete iter;\n return false;\n}\n\nconst char *BlockAllocType::getData(const Value *v) const{\n return (const char *)(v->v.block+1);\n}\n\nvoid BlockAllocType::incRef(Value *v){\n BlockAllocHeader *h = v->v.block;\n h->refct++;\n if(!h->refct)\n throw RUNT(\"reference count too large\");\n}\n \nvoid BlockAllocType::decRef(Value *v){\n BlockAllocHeader *h = v->v.block;\n h->refct--;\n if(h->refct==0){\n free(h);\n }\n}\n\nvoid GCType::incRef(Value *v){\n v->v.gc->incRefCt();\n tdprintf(\"incrementing ref count of %s:%p, now %d\\n\",name,v->v.gc,v->v.gc->refct);\n}\n\nvoid GCType::decRef(Value *v){\n bool b = v->v.gc->decRefCt();\n tdprintf(\"decrementing ref count of %s:%p, now %d\\n\",name,v->v.gc,v->v.gc->refct);\n if(b){\n tdprintf(\" AND DELETING %s:%p\\n\",name,v->v.gc);\n delete v->v.gc;\n }\n}\n\nIterator<class Value *> *GCType::makeKeyIterator(Value *v){\n return v->v.gc->makeKeyIterator();\n}\nIterator<class Value *> *GCType::makeValueIterator(Value *v){\n return v->v.gc->makeValueIterator();\n}\n \n\nGarbageCollected *GCType::getGC(Value *v){\n return v->v.gc;\n}\n\nGarbageCollected::GarbageCollected(){\n refct=0;\n globalCount++;\n CycleDetector::getInstance()->add(this);\n}\n\nGarbageCollected::~GarbageCollected(){\n globalCount--;\n CycleDetector::getInstance()->remove(this);\n}\n\n\n\n\n\n\/*\n * \n * New types go down here\n * \n *\/\n\nstatic NoneType _tNone;\nNoneType *Types::tNone= &_tNone;\n\nstatic Type _tDeleted; \/\/ has to be added by hand in createTypes\nType *Types::tDeleted= &_tDeleted;\n\nstatic IntegerType _Int;\nIntegerType *Types::tInteger = &_Int;\n\nstatic FloatType _Float;\nFloatType *Types::tFloat = &_Float;\n\nstatic StringType _String;\nStringType *Types::tString = &_String;\n\nstatic CodeType _Code;\nCodeType *Types::tCode = &_Code;\n\nstatic ClosureType _Closure;\nClosureType *Types::tClosure = &_Closure;\n\nstatic RangeType<int> _IRange;\nRangeType<int> *Types::tIRange = &_IRange;\nstatic RangeType<float> _FRange;\nRangeType<float> *Types::tFRange = &_FRange;\n\nstatic ListType _List;\nListType *Types::tList = &_List;\n\nstatic HashType _Hash;\nHashType *Types::tHash = &_Hash;\n\nstatic SymbolType _Symbol;\nSymbolType *Types::tSymbol = &_Symbol;\n\nstatic NativeType _Native;\nNativeType *Types::tNative = &_Native;\n\nstatic PropType _Prop;\nPropType *Types::tProp = &_Prop;\n\n\n\nstatic IteratorType _Iterator;\nIteratorType *Types::tIter = &_Iterator;\n\n\n\nvoid Types::createTypes(){\n tDeleted->add(\"DELETED\",\"DELE\");\n \n \/\/ because of the undefined execution order of static heap\n \/\/ objects, we set up all the type names here rather than in\n \/\/ \"add\" to make sure the symbol system is already up.\n \n \/\/ IF you add types later in plugins, the system should detect\n \/\/ this.\n \n for(Type *p = Type::head;p;p=p->next){\n p->nameSymb = SymbolType::getSymbol(p->name);\n }\n createTypesDone = true;\n \n \n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dataaccess.h\"\n#include \"scientist.h\"\n#include <QtSql>\n#include <iostream> \/\/ TEMP<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n#include <sstream>\n\nusing namespace std;\n\nDataAccess::DataAccess()\n{\n\n db = QSqlDatabase::addDatabase(\"QSQLITE\");\n db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n db.open();\n\n}\nvoid DataAccess::saveScientists(const vector<Scientist>& scientists) \/\/ From vector to text file\n{\n \/*\n * This function uses ofstream to save the vector of scientists to the scientists.txt file.\n *\/\n\n string sName, line, name, gender, birthYear, deathYear, age;\n \/\/char charGender;\n \/\/int intBirthYear, intDeathYear, intAge;\n\n name = \"LSKDFJLSDKFJSDLKFJSD\";\n gender = \"m\";\n birthYear = \"1555\";\n deathYear = \"1665\";\n\n\n\n sName = \"INSERT INTO Scientists(name,gender,birth,death) VALUES(\\\"\" + name\n + \"\\\",\\\"\" + gender + \"\\\",\" + birthYear + \",\" + deathYear + \")\";\n\n\n\n cout << sName;\n\n QString input = QString::fromStdString(sName);\n\n\n\n \/\/db = QSqlDatabase::addDatabase(\"QSQLITE\");\n \/\/db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n\n \/\/db.open(); \/\/ open database\n QSqlQuery query;\n query.exec(input); \/\/ open table scientists\n db.close();\n\n\n}\nvector<Scientist> DataAccess::loadScientists() \/\/ From text file to vector\n{\n \/*\n * This function uses ifstream to read from scientists.txt file and read them into a vector.\n *\/\n\n vector<Scientist> scientists;\n string line, name, gender, birthYear, deathYear, age;\n \/\/char charGender;\n int intBirthYear, intDeathYear, intAge;\n\n\n \/\/db = QSqlDatabase::addDatabase(\"QSQLITE\");\n \/\/db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n\n \/\/db.open(); \/\/ open database\n QSqlQuery query;\n query.exec(\"SELECT * FROM Scientists\"); \/\/ open table scientists\n\n while (query.next())\n {\n string name = query.value(1).toString().toStdString();\n string stringGender = query.value(2).toString().toStdString();\n int intBirthYear = query.value(3).toInt();\n int intDeathYear = query.value(4).toInt();\n char charGender = stringGender[0];\n\n Scientist scientist(name, charGender, intBirthYear, intDeathYear, intAge);\n scientists.push_back(scientist);\n }\n\n \/\/db.close();\n return scientists;\n}\n\n\n\n\/\/ OLD CODE\n\/*\nofstream file;\nfile.open(\"scientists.txt\");\n\nif(file.is_open())\n{\n for(size_t i = 0; i < scientists.size(); i++)\n {\n file << scientists[i].getName() << \",\";\n file << scientists[i].getGender() << \",\";\n file << scientists[i].getBirth() << \",\";\n file << scientists[i].getDeath() << \",\";\n file << scientists[i].getAge() << endl;\n }\n file.close( );\n}\n*\/\n\n\/*\nvector<Scientist> scientists;\n\n\nstring line, name, gender, birthYear, deathYear, age;\nconst string delimiter = \",\";\nchar charGender;\nint intBirthYear, intDeathYear, intAge, delimiterPos;\n\nifstream file;\nfile.open(\"scientists.txt\");\n\nif(file.is_open())\n{\n while(getline(file, line))\n {\n delimiterPos = line.find(delimiter);\n name = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n gender = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n birthYear = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n deathYear = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n age = line.substr(0, delimiterPos);\n\n charGender = gender[0];\n intBirthYear = atoi(birthYear.c_str());\n intDeathYear = atoi(deathYear.c_str());\n intAge = atoi(age.c_str());\n\n\n Scientist scientist(name, charGender, intBirthYear, intDeathYear, intAge);\n\n scientists.push_back(scientist);\n }\n\nfile.close( );\n}\n\n\n\nreturn scientists;\n\n*\/\n<commit_msg>Dataaccess update David G<commit_after>#include \"dataaccess.h\"\n#include \"scientist.h\"\n#include <QtSql>\n#include <iostream> \/\/ TEMP<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n#include <sstream>\n\nusing namespace std;\n\nDataAccess::DataAccess()\n{\n\n db = QSqlDatabase::addDatabase(\"QSQLITE\");\n db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n db.open();\n\n}\nvoid DataAccess::saveScientists(const vector<Scientist>& scientists) \/\/ From vector to text file\n{\n \/*\n * This function uses ofstream to save the vector of scientists to the scientists.txt file.\n *\/\n\n string sName, line, name, gender, birthYear, deathYear, age;\n \/\/char charGender;\n \/\/int intBirthYear, intDeathYear, intAge;\n\n name = \"LSKDFJLSDKFJSDLKFJSD\";\n gender = \"m\";\n birthYear = \"1555\";\n deathYear = \"1665\";\n\n\n\n sName = \"INSERT INTO Scientists(name,gender,birth,death) VALUES(\\\"\" + name\n + \"\\\",\\\"\" + gender + \"\\\",\" + birthYear + \",\" + deathYear + \")\";\n\n\n\n cout << sName;\n\n QString input = QString::fromStdString(sName);\n\n\n\n \/\/db = QSqlDatabase::addDatabase(\"QSQLITE\");\n \/\/db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n\n \/\/db.open(); \/\/ open database\n QSqlQuery query;\n query.exec(input); \/\/ open table scientists\n db.close();\n\n\n}\nvector<Scientist> DataAccess::loadScientists() \/\/ From text file to vector\n{\n \/*\n * This function uses ifstream to read from scientists.txt file and read them into a vector.\n *\/\n\n vector<Scientist> scientists;\n string line, name, gender, birthYear, deathYear, age;\n \/\/char charGender;\n int intBirthYear, intDeathYear, intAge;\n\n\n \/\/db = QSqlDatabase::addDatabase(\"QSQLITE\");\n \/\/db.setDatabaseName(\"test.sqlite\"); \/\/ witch database to select ( aka what file )\n\n\n \/\/db.open(); \/\/ open database\n QSqlQuery query;\n query.exec(\"SELECT * FROM Scientists\"); \/\/ open table scientists\n\n while (query.next())\n {\n string name = query.value(1).toString().toStdString();\n string stringGender = query.value(2).toString().toStdString();\n int intBirthYear = query.value(3).toInt();\n int intDeathYear = query.value(4).toInt();\n char charGender = stringGender[0];\n\n Scientist scientist(name, charGender, intBirthYear, intDeathYear, intAge);\n scientists.push_back(scientist);\n }\n\n \/\/db.close();\n return scientists;\n}\n\n\n\n\/\/ OLD CODE\n\/*\nofstream file;\nfile.open(\"scientists.txt\");\n\nif(file.is_open())\n{\n for(size_t i = 0; i < scientists.size(); i++)\n {\n file << scientists[i].getName() << \",\";\n file << scientists[i].getGender() << \",\";\n file << scientists[i].getBirth() << \",\";\n file << scientists[i].getDeath() << \",\";\n file << scientists[i].getAge() << endl;\n }\n file.close( );\n}\n*\/\n\n\/*\nvector<Scientist> scientists;\n\n\nstring line, name, gender, birthYear, deathYear, age;\nconst string delimiter = \",\";\nchar charGender;\nint intBirthYear, intDeathYear, intAge, delimiterPos;\n\nifstream file;\nfile.open(\"scientists.txt\");\n\nif(file.is_open())\n{\n while(getline(file, line))\n {\n delimiterPos = line.find(delimiter);\n name = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n gender = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n birthYear = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n deathYear = line.substr(0, delimiterPos);\n line.erase(0, delimiterPos + 1);\n\n delimiterPos = line.find(delimiter);\n age = line.substr(0, delimiterPos);\n\n charGender = gender[0];\n intBirthYear = atoi(birthYear.c_str());\n intDeathYear = atoi(deathYear.c_str());\n intAge = atoi(age.c_str());\n\n\n Scientist scientist(name, charGender, intBirthYear, intDeathYear, intAge);\n\n scientists.push_back(scientist);\n }\n\nfile.close( );\n}\n\n\n\nreturn scientists;\n\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <memory>\n\n#include \"server.h\"\n\n#include <node.h>\n#include <nan.h>\n\n#include <vector>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"call.h\"\n#include \"completion_queue_async_worker.h\"\n#include \"server_credentials.h\"\n#include \"timeval.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing std::unique_ptr;\nusing v8::Array;\nusing v8::Boolean;\nusing v8::Date;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nNanCallback *Server::constructor;\nPersistent<FunctionTemplate> Server::fun_tpl;\n\nclass NewCallOp : public Op {\n public:\n NewCallOp() {\n call = NULL;\n grpc_call_details_init(&details);\n grpc_metadata_array_init(&request_metadata);\n }\n\n ~NewCallOp() {\n grpc_call_details_destroy(&details);\n grpc_metadata_array_destroy(&request_metadata);\n }\n\n Handle<Value> GetNodeValue() const {\n NanEscapableScope();\n if (call == NULL) {\n return NanEscapeScope(NanNull());\n }\n Handle<Object> obj = NanNew<Object>();\n obj->Set(NanNew(\"call\"), Call::WrapStruct(call));\n obj->Set(NanNew(\"method\"), NanNew(details.method));\n obj->Set(NanNew(\"host\"), NanNew(details.host));\n obj->Set(NanNew(\"deadline\"),\n NanNew<Date>(TimespecToMilliseconds(details.deadline)));\n obj->Set(NanNew(\"metadata\"), ParseMetadata(&request_metadata));\n return NanEscapeScope(obj);\n }\n\n bool ParseOp(Handle<Value> value, grpc_op *out,\n shared_ptr<Resources> resources) {\n return true;\n }\n\n grpc_call *call;\n grpc_call_details details;\n grpc_metadata_array request_metadata;\n\n protected:\n std::string GetTypeString() const {\n return \"new_call\";\n }\n};\n\nServer::Server(grpc_server *server) : wrapped_server(server) {\n shutdown_queue = grpc_completion_queue_create(NULL);\n grpc_server_register_completion_queue(server, shutdown_queue, NULL);\n}\n\nServer::~Server() {\n this->ShutdownServer();\n grpc_completion_queue_shutdown(this->shutdown_queue);\n grpc_server_destroy(wrapped_server);\n grpc_completion_queue_destroy(this->shutdown_queue);\n}\n\nvoid Server::Init(Handle<Object> exports) {\n NanScope();\n Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);\n tpl->SetClassName(NanNew(\"Server\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n NanSetPrototypeTemplate(tpl, \"requestCall\",\n NanNew<FunctionTemplate>(RequestCall)->GetFunction());\n\n NanSetPrototypeTemplate(\n tpl, \"addHttp2Port\",\n NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction());\n\n NanSetPrototypeTemplate(tpl, \"start\",\n NanNew<FunctionTemplate>(Start)->GetFunction());\n\n NanSetPrototypeTemplate(tpl, \"shutdown\",\n NanNew<FunctionTemplate>(Shutdown)->GetFunction());\n\n NanAssignPersistent(fun_tpl, tpl);\n Handle<Function> ctr = tpl->GetFunction();\n constructor = new NanCallback(ctr);\n exports->Set(NanNew(\"Server\"), ctr);\n}\n\nbool Server::HasInstance(Handle<Value> val) {\n return NanHasInstance(fun_tpl, val);\n}\n\nvoid Server::ShutdownServer() {\n if (this->wrapped_server != NULL) {\n grpc_server_shutdown_and_notify(this->wrapped_server,\n this->shutdown_queue,\n NULL);\n grpc_completion_queue_pluck(this->shutdown_queue, NULL,\n gpr_inf_future(GPR_CLOCK_REALTIME), NULL);\n this->wrapped_server = NULL;\n }\n}\n\nNAN_METHOD(Server::New) {\n NanScope();\n\n \/* If this is not a constructor call, make a constructor call and return\n the result *\/\n if (!args.IsConstructCall()) {\n const int argc = 1;\n Local<Value> argv[argc] = {args[0]};\n NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));\n }\n grpc_server *wrapped_server;\n grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();\n if (args[0]->IsUndefined()) {\n wrapped_server = grpc_server_create(NULL, NULL);\n } else if (args[0]->IsObject()) {\n Handle<Object> args_hash(args[0]->ToObject());\n Handle<Array> keys(args_hash->GetOwnPropertyNames());\n grpc_channel_args channel_args;\n channel_args.num_args = keys->Length();\n channel_args.args = reinterpret_cast<grpc_arg *>(\n calloc(channel_args.num_args, sizeof(grpc_arg)));\n \/* These are used to keep all strings until then end of the block, then\n destroy them *\/\n std::vector<NanUtf8String *> key_strings(keys->Length());\n std::vector<NanUtf8String *> value_strings(keys->Length());\n for (unsigned int i = 0; i < channel_args.num_args; i++) {\n Handle<String> current_key(keys->Get(i)->ToString());\n Handle<Value> current_value(args_hash->Get(current_key));\n key_strings[i] = new NanUtf8String(current_key);\n channel_args.args[i].key = **key_strings[i];\n if (current_value->IsInt32()) {\n channel_args.args[i].type = GRPC_ARG_INTEGER;\n channel_args.args[i].value.integer = current_value->Int32Value();\n } else if (current_value->IsString()) {\n channel_args.args[i].type = GRPC_ARG_STRING;\n value_strings[i] = new NanUtf8String(current_value);\n channel_args.args[i].value.string = **value_strings[i];\n } else {\n free(channel_args.args);\n return NanThrowTypeError(\"Arg values must be strings\");\n }\n }\n wrapped_server = grpc_server_create(&channel_args, NULL);\n free(channel_args.args);\n } else {\n return NanThrowTypeError(\"Server expects an object\");\n }\n grpc_server_register_completion_queue(wrapped_server, queue, NULL);\n Server *server = new Server(wrapped_server);\n server->Wrap(args.This());\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(Server::RequestCall) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"requestCall can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\"requestCall cannot be called on a shut down Server\");\n }\n NewCallOp *op = new NewCallOp();\n unique_ptr<OpVec> ops(new OpVec());\n ops->push_back(unique_ptr<Op>(op));\n grpc_call_error error = grpc_server_request_call(\n server->wrapped_server, &op->call, &op->details, &op->request_metadata,\n CompletionQueueAsyncWorker::GetQueue(),\n CompletionQueueAsyncWorker::GetQueue(),\n new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),\n shared_ptr<Resources>(NULL)));\n if (error != GRPC_CALL_OK) {\n return NanThrowError(\"requestCall failed\", error);\n }\n CompletionQueueAsyncWorker::Next();\n NanReturnUndefined();\n}\n\nNAN_METHOD(Server::AddHttp2Port) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\n \"addHttp2Port can only be called on a Server\");\n }\n if (!args[0]->IsString()) {\n return NanThrowTypeError(\n \"addHttp2Port's first argument must be a String\");\n }\n if (!ServerCredentials::HasInstance(args[1])) {\n return NanThrowTypeError(\n \"addHttp2Port's second argument must be ServerCredentials\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\n \"addHttp2Port cannot be called on a shut down Server\");\n }\n ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(\n args[1]->ToObject());\n grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();\n int port;\n if (creds == NULL) {\n port = grpc_server_add_insecure_http2_port(server->wrapped_server,\n *NanUtf8String(args[0]));\n } else {\n port = grpc_server_add_secure_http2_port(server->wrapped_server,\n *NanUtf8String(args[0]),\n creds);\n }\n NanReturnValue(NanNew<Number>(port));\n}\n\nNAN_METHOD(Server::Start) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"start can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\"start cannot be called on a shut down Server\");\n }\n grpc_server_start(server->wrapped_server);\n NanReturnUndefined();\n}\n\nNAN_METHOD(ShutdownCallback) {\n NanReturnUndefined();\n}\n\nNAN_METHOD(Server::Shutdown) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"shutdown can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n server->ShutdownServer();\n NanReturnUndefined();\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<commit_msg>Reverted unintended change.<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <memory>\n\n#include \"server.h\"\n\n#include <node.h>\n#include <nan.h>\n\n#include <vector>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"call.h\"\n#include \"completion_queue_async_worker.h\"\n#include \"server_credentials.h\"\n#include \"timeval.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing std::unique_ptr;\nusing v8::Array;\nusing v8::Boolean;\nusing v8::Date;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nNanCallback *Server::constructor;\nPersistent<FunctionTemplate> Server::fun_tpl;\n\nclass NewCallOp : public Op {\n public:\n NewCallOp() {\n call = NULL;\n grpc_call_details_init(&details);\n grpc_metadata_array_init(&request_metadata);\n }\n\n ~NewCallOp() {\n grpc_call_details_destroy(&details);\n grpc_metadata_array_destroy(&request_metadata);\n }\n\n Handle<Value> GetNodeValue() const {\n NanEscapableScope();\n if (call == NULL) {\n return NanEscapeScope(NanNull());\n }\n Handle<Object> obj = NanNew<Object>();\n obj->Set(NanNew(\"call\"), Call::WrapStruct(call));\n obj->Set(NanNew(\"method\"), NanNew(details.method));\n obj->Set(NanNew(\"host\"), NanNew(details.host));\n obj->Set(NanNew(\"deadline\"),\n NanNew<Date>(TimespecToMilliseconds(details.deadline)));\n obj->Set(NanNew(\"metadata\"), ParseMetadata(&request_metadata));\n return NanEscapeScope(obj);\n }\n\n bool ParseOp(Handle<Value> value, grpc_op *out,\n shared_ptr<Resources> resources) {\n return true;\n }\n\n grpc_call *call;\n grpc_call_details details;\n grpc_metadata_array request_metadata;\n\n protected:\n std::string GetTypeString() const {\n return \"new_call\";\n }\n};\n\nServer::Server(grpc_server *server) : wrapped_server(server) {\n shutdown_queue = grpc_completion_queue_create(NULL);\n grpc_server_register_completion_queue(server, shutdown_queue, NULL);\n}\n\nServer::~Server() {\n this->ShutdownServer();\n grpc_completion_queue_shutdown(this->shutdown_queue);\n grpc_server_destroy(wrapped_server);\n grpc_completion_queue_destroy(this->shutdown_queue);\n}\n\nvoid Server::Init(Handle<Object> exports) {\n NanScope();\n Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);\n tpl->SetClassName(NanNew(\"Server\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n NanSetPrototypeTemplate(tpl, \"requestCall\",\n NanNew<FunctionTemplate>(RequestCall)->GetFunction());\n\n NanSetPrototypeTemplate(\n tpl, \"addHttp2Port\",\n NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction());\n\n NanSetPrototypeTemplate(tpl, \"start\",\n NanNew<FunctionTemplate>(Start)->GetFunction());\n\n NanSetPrototypeTemplate(tpl, \"shutdown\",\n NanNew<FunctionTemplate>(Shutdown)->GetFunction());\n\n NanAssignPersistent(fun_tpl, tpl);\n Handle<Function> ctr = tpl->GetFunction();\n constructor = new NanCallback(ctr);\n exports->Set(NanNew(\"Server\"), ctr);\n}\n\nbool Server::HasInstance(Handle<Value> val) {\n return NanHasInstance(fun_tpl, val);\n}\n\nvoid Server::ShutdownServer() {\n if (this->wrapped_server != NULL) {\n grpc_server_shutdown_and_notify(this->wrapped_server,\n this->shutdown_queue,\n NULL);\n grpc_completion_queue_pluck(this->shutdown_queue, NULL,\n gpr_inf_future(GPR_CLOCK_REALTIME), NULL);\n this->wrapped_server = NULL;\n }\n}\n\nNAN_METHOD(Server::New) {\n NanScope();\n\n \/* If this is not a constructor call, make a constructor call and return\n the result *\/\n if (!args.IsConstructCall()) {\n const int argc = 1;\n Local<Value> argv[argc] = {args[0]};\n NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));\n }\n grpc_server *wrapped_server;\n grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue();\n if (args[0]->IsUndefined()) {\n wrapped_server = grpc_server_create(NULL, NULL);\n } else if (args[0]->IsObject()) {\n Handle<Object> args_hash(args[0]->ToObject());\n Handle<Array> keys(args_hash->GetOwnPropertyNames());\n grpc_channel_args channel_args;\n channel_args.num_args = keys->Length();\n channel_args.args = reinterpret_cast<grpc_arg *>(\n calloc(channel_args.num_args, sizeof(grpc_arg)));\n \/* These are used to keep all strings until then end of the block, then\n destroy them *\/\n std::vector<NanUtf8String *> key_strings(keys->Length());\n std::vector<NanUtf8String *> value_strings(keys->Length());\n for (unsigned int i = 0; i < channel_args.num_args; i++) {\n Handle<String> current_key(keys->Get(i)->ToString());\n Handle<Value> current_value(args_hash->Get(current_key));\n key_strings[i] = new NanUtf8String(current_key);\n channel_args.args[i].key = **key_strings[i];\n if (current_value->IsInt32()) {\n channel_args.args[i].type = GRPC_ARG_INTEGER;\n channel_args.args[i].value.integer = current_value->Int32Value();\n } else if (current_value->IsString()) {\n channel_args.args[i].type = GRPC_ARG_STRING;\n value_strings[i] = new NanUtf8String(current_value);\n channel_args.args[i].value.string = **value_strings[i];\n } else {\n free(channel_args.args);\n return NanThrowTypeError(\"Arg values must be strings\");\n }\n }\n wrapped_server = grpc_server_create(&channel_args, NULL);\n free(channel_args.args);\n } else {\n return NanThrowTypeError(\"Server expects an object\");\n }\n grpc_server_register_completion_queue(wrapped_server, queue, NULL);\n Server *server = new Server(wrapped_server);\n server->Wrap(args.This());\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(Server::RequestCall) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"requestCall can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\"requestCall cannot be called on a shut down Server\");\n }\n NewCallOp *op = new NewCallOp();\n unique_ptr<OpVec> ops(new OpVec());\n ops->push_back(unique_ptr<Op>(op));\n grpc_call_error error = grpc_server_request_call(\n server->wrapped_server, &op->call, &op->details, &op->request_metadata,\n CompletionQueueAsyncWorker::GetQueue(),\n CompletionQueueAsyncWorker::GetQueue(),\n new struct tag(new NanCallback(args[0].As<Function>()), ops.release(),\n shared_ptr<Resources>(nullptr)));\n if (error != GRPC_CALL_OK) {\n return NanThrowError(\"requestCall failed\", error);\n }\n CompletionQueueAsyncWorker::Next();\n NanReturnUndefined();\n}\n\nNAN_METHOD(Server::AddHttp2Port) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\n \"addHttp2Port can only be called on a Server\");\n }\n if (!args[0]->IsString()) {\n return NanThrowTypeError(\n \"addHttp2Port's first argument must be a String\");\n }\n if (!ServerCredentials::HasInstance(args[1])) {\n return NanThrowTypeError(\n \"addHttp2Port's second argument must be ServerCredentials\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\n \"addHttp2Port cannot be called on a shut down Server\");\n }\n ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(\n args[1]->ToObject());\n grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();\n int port;\n if (creds == NULL) {\n port = grpc_server_add_insecure_http2_port(server->wrapped_server,\n *NanUtf8String(args[0]));\n } else {\n port = grpc_server_add_secure_http2_port(server->wrapped_server,\n *NanUtf8String(args[0]),\n creds);\n }\n NanReturnValue(NanNew<Number>(port));\n}\n\nNAN_METHOD(Server::Start) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"start can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n if (server->wrapped_server == NULL) {\n return NanThrowError(\"start cannot be called on a shut down Server\");\n }\n grpc_server_start(server->wrapped_server);\n NanReturnUndefined();\n}\n\nNAN_METHOD(ShutdownCallback) {\n NanReturnUndefined();\n}\n\nNAN_METHOD(Server::Shutdown) {\n NanScope();\n if (!HasInstance(args.This())) {\n return NanThrowTypeError(\"shutdown can only be called on a Server\");\n }\n Server *server = ObjectWrap::Unwrap<Server>(args.This());\n server->ShutdownServer();\n NanReturnUndefined();\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>\/*! @file window.cc\n * @brief Tests for SoundFeatureExtraction::Transforms::Window.\n * @author Markovtsev Vadim <v.markovtsev@samsung.com>\n * @version 1.0\n *\n * @section Notes\n * This code partially conforms to <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml\">Google C++ Style Guide<\/a>.\n *\n * @section Copyright\n * Copyright 2013 Samsung R&D Institute Russia\n *\/\n\n\n#include <gtest\/gtest.h>\n#include \"src\/transforms\/window.h\"\n\nusing SoundFeatureExtraction::Formats::WindowF;\nusing SoundFeatureExtraction::Formats::WindowFormatF;\nusing SoundFeatureExtraction::BuffersBase;\nusing SoundFeatureExtraction::Transforms::Window;\n\nclass UnpackRDFTTest : public Window, public testing::Test {\n public:\n BuffersBase<WindowF> Input;\n BuffersBase<WindowF> Output;\n int Size;\n\n virtual void SetUp() {\n Size = 514;\n Input.Initialize(1, Size);\n for (int i = 0; i < Size; i++) {\n Input[0]->Data.get()[i] = i;\n }\n auto format = std::make_shared<WindowFormatF>(Size * 2000 \/ 16000, 16000);\n format->SetSize(Size);\n SetInputFormat(format);\n InitializeBuffers(Input, &Output);\n }\n};\n\nTEST_F(UnpackRDFTTest, Do) {\n SetParameter(\"predft\", \"false\");\n Initialize();\n Do(Input, &Output);\n}\n\nTEST_F(UnpackRDFTTest, DoPreDft) {\n SetParameter(\"predft\", \"true\");\n Initialize();\n Do(Input, &Output);\n}\n\n#include \"tests\/google\/src\/gtest_main.cc\"\n<commit_msg>Added extra assert to Window test<commit_after>\/*! @file window.cc\n * @brief Tests for SoundFeatureExtraction::Transforms::Window.\n * @author Markovtsev Vadim <v.markovtsev@samsung.com>\n * @version 1.0\n *\n * @section Notes\n * This code partially conforms to <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml\">Google C++ Style Guide<\/a>.\n *\n * @section Copyright\n * Copyright 2013 Samsung R&D Institute Russia\n *\/\n\n\n#include <gtest\/gtest.h>\n#include \"src\/transforms\/window.h\"\n\nusing SoundFeatureExtraction::Formats::WindowF;\nusing SoundFeatureExtraction::Formats::WindowFormatF;\nusing SoundFeatureExtraction::BuffersBase;\nusing SoundFeatureExtraction::Transforms::Window;\n\nclass UnpackRDFTTest : public Window, public testing::Test {\n public:\n BuffersBase<WindowF> Input;\n BuffersBase<WindowF> Output;\n int Size;\n\n virtual void SetUp() {\n Size = 514;\n Input.Initialize(1, Size);\n for (int i = 0; i < Size; i++) {\n Input[0]->Data.get()[i] = i * (1 - 2 * (i % 2));\n }\n auto format = std::make_shared<WindowFormatF>(Size * 2000 \/ 16000, 16000);\n format->SetSize(Size);\n SetInputFormat(format);\n InitializeBuffers(Input, &Output);\n }\n};\n\nTEST_F(UnpackRDFTTest, Do) {\n SetParameter(\"predft\", \"false\");\n Initialize();\n Do(Input, &Output);\n float output_na[Size] __attribute__ ((aligned (32)));\n ApplyWindow(false, window_.get(), Size, Input[0]->Data.get(), output_na);\n ASSERT_EQ(0, memcmp(Output[0]->Data.get(), output_na,\n sizeof(float) * Size));\n}\n\nTEST_F(UnpackRDFTTest, DoPreDft) {\n SetParameter(\"predft\", \"true\");\n Initialize();\n Do(Input, &Output);\n}\n\n#include \"tests\/google\/src\/gtest_main.cc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"xml_element.hpp\"\n\/\/ #include \"xml_doc.hpp\"\n#include \"gtest\/gtest.h\"\n#include <iostream>\n#include <map>\n#include <vector>\n\nTEST( ElementTest, Name ) {\n \/\/ xmlNode is created and destroyed outside of class\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n\n XmlElement el{n};\n std::string currentName = el.name( );\n EXPECT_STREQ( \"test-node\", currentName.c_str( ) );\n\n std::string oldName = el.name( \"changed-name\" );\n EXPECT_STREQ( currentName.c_str( ), oldName.c_str( ) );\n currentName = el.name( );\n EXPECT_STREQ( \"changed-name\", currentName.c_str( ) );\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, Attribute ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n el.attribute( \"id\", \"test-value\" );\n ASSERT_TRUE( el.hasAttributes( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n el.attributes( attrs );\n ASSERT_TRUE( el.hasAttributes( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, GetAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n el.attributes( attrs );\n ASSERT_TRUE( el.hasAttributes( ) );\n\n auto props = el.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasChild ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetChildName ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch = el.child( \"child-test\" );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetChild ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement ch = el.child( \"child-test\", attrs );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n ASSERT_TRUE( ch.hasAttributes( ) );\n auto props = ch.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, Child ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch = el.child( \"child-test\" );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n el = el.child( );\n ASSERT_STREQ( \"child-test\", el.name( ).c_str( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasSiblings ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch1 = el.child( \"first-child-test\" );\n XmlElement ch2 = el.child( \"second-child-test\" );\n ASSERT_TRUE( ch1.hasSibling( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetSiblingName ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n XmlElement sibling = ch.sibling( \"sibling-test\" );\n ASSERT_TRUE( ch.hasSibling( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, SetSibling ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement sibling = ch.sibling( \"sibling-test\", attrs );\n ASSERT_TRUE( ch.hasSibling( ) );\n \/\/ ASSERT_EQ( attrs, sibling.attributes( ) );\n auto props = sibling.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, HasContent ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement sibling = ch.sibling( \"sibling-test\", attrs );\n ASSERT_TRUE( ch.hasSibling( ) );\n \/\/ ASSERT_EQ( attrs, sibling.attributes( ) );\n auto props = sibling.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n ASSERT_FALSE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, Content ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n el.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n std::cerr << el.content( ) << std::endl;\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n XmlElement ch1 = el.child( \"child\" );\n XmlElement sibling = el.child( \"sibling\" );\n XmlElement ch2 = sibling.child( \"child-of-sibling\" );\n ch2.content( \"This is some more test content\" );\n ch2.child( \"child-of-child-of-sibling\" );\n ASSERT_TRUE( el.hasContent( ) );\n std::cerr << el.content( ) << std::endl;\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n}\n\nTEST( ElementTest, AddContent ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n el.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n XmlElement ch1 = el.child( \"child\" );\n XmlElement sibling = el.child( \"sibling\" );\n XmlElement ch2 = sibling.child( \"child-of-child\" );\n ch2.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n ch1 = el.child( \"child\" );\n sibling = el.child( \"sibling\" );\n ch2 = sibling.child( \"child-of-child\" );\n ASSERT_FALSE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n<commit_msg>added relational and equality operators (for ElementSelections)<commit_after>#include \"xml_element.hpp\"\n\/\/ #include \"xml_doc.hpp\"\n#include \"gtest\/gtest.h\"\n#include <iostream>\n#include <map>\n#include <vector>\n\nTEST( ElementTest, Name ) {\n \/\/ xmlNode is created and destroyed outside of class\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n\n XmlElement el{n};\n std::string currentName = el.name( );\n EXPECT_STREQ( \"test-node\", currentName.c_str( ) );\n\n std::string oldName = el.name( \"changed-name\" );\n EXPECT_STREQ( currentName.c_str( ), oldName.c_str( ) );\n currentName = el.name( );\n EXPECT_STREQ( \"changed-name\", currentName.c_str( ) );\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, Attribute ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n el.attribute( \"id\", \"test-value\" );\n ASSERT_TRUE( el.hasAttributes( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n el.attributes( attrs );\n ASSERT_TRUE( el.hasAttributes( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, GetAttributes ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasAttributes( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n el.attributes( attrs );\n ASSERT_TRUE( el.hasAttributes( ) );\n\n auto props = el.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasChild ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetChildName ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch = el.child( \"child-test\" );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetChild ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement ch = el.child( \"child-test\", attrs );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n ASSERT_TRUE( ch.hasAttributes( ) );\n auto props = ch.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, Child ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch = el.child( \"child-test\" );\n ASSERT_TRUE( el.hasChild( ) );\n ASSERT_STREQ( \"child-test\", ch.name( ).c_str( ) );\n el = el.child( );\n ASSERT_STREQ( \"child-test\", el.name( ).c_str( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, HasSiblings ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_FALSE( el.hasChild( ) );\n XmlElement ch1 = el.child( \"first-child-test\" );\n XmlElement ch2 = el.child( \"second-child-test\" );\n ASSERT_TRUE( ch1.hasSibling( ) );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, SetSiblingName ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n XmlElement sibling = ch.sibling( \"sibling-test\" );\n ASSERT_TRUE( ch.hasSibling( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, SetSibling ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement sibling = ch.sibling( \"sibling-test\", attrs );\n ASSERT_TRUE( ch.hasSibling( ) );\n \/\/ ASSERT_EQ( attrs, sibling.attributes( ) );\n auto props = sibling.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, HasContent ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n XmlElement ch = el.child( \"child\" );\n std::map<std::string, std::string> attrs{{\"class\", \"test-class\"},\n {\"test-attr\", \"test-value\"}};\n XmlElement sibling = ch.sibling( \"sibling-test\", attrs );\n ASSERT_TRUE( ch.hasSibling( ) );\n \/\/ ASSERT_EQ( attrs, sibling.attributes( ) );\n auto props = sibling.attributes( );\n for ( auto attr : props ) {\n auto key = attr.first;\n auto value = attr.second;\n auto look = attrs.find( key );\n ASSERT_STREQ( look->second.c_str( ), value.c_str( ) );\n }\n\n ASSERT_FALSE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, Content ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n el.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n std::cerr << el.content( ) << std::endl;\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n XmlElement ch1 = el.child( \"child\" );\n XmlElement sibling = el.child( \"sibling\" );\n XmlElement ch2 = sibling.child( \"child-of-sibling\" );\n ch2.content( \"This is some more test content\" );\n ch2.child( \"child-of-child-of-sibling\" );\n ASSERT_TRUE( el.hasContent( ) );\n std::cerr << el.content( ) << std::endl;\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n}\n\nTEST( ElementTest, AddContent ) {\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n el.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n XmlElement ch1 = el.child( \"child\" );\n XmlElement sibling = el.child( \"sibling\" );\n XmlElement ch2 = sibling.child( \"child-of-child\" );\n ch2.content( \"This is some test content\" );\n ASSERT_TRUE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n n = nullptr;\n\n n = xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n el = XmlElement{n};\n ch1 = el.child( \"child\" );\n sibling = el.child( \"sibling\" );\n ch2 = sibling.child( \"child-of-child\" );\n ASSERT_FALSE( el.hasContent( ) );\n xmlFreeNode( n ); \/\/ only free's child nodes\n}\n\nTEST( ElementTest, Equality ) {\n XmlElement nullEl;\n ASSERT_TRUE( nullEl == XmlElement{} );\n\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el1{n};\n XmlElement ch1 = el1.child( \"child\" );\n ASSERT_FALSE( el1 == ch1 );\n ASSERT_FALSE( el1 == XmlElement{} );\n ASSERT_TRUE( el1 != ch1 );\n auto ch = el1.child( );\n ASSERT_TRUE( ch == ch1 );\n ASSERT_FALSE( ch != ch1 );\n ASSERT_TRUE( ch != XmlElement{} );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, StrictOrdering ) {\n XmlElement nullEl;\n ASSERT_FALSE( nullEl < XmlElement{} );\n ASSERT_FALSE( nullEl > XmlElement{} );\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_TRUE( el < nullEl );\n auto ch = el.child( \"child-node\" );\n ASSERT_TRUE( el < ch );\n ASSERT_FALSE( el < el );\n ASSERT_TRUE( ch > el );\n auto sblg = el.child( \"sibling-of-child\" );\n ASSERT_TRUE( el < sblg );\n ASSERT_TRUE( sblg > el );\n ASSERT_TRUE( ch < sblg );\n ASSERT_TRUE( sblg > ch );\n auto grch = ch.child( \"child-of-child\" );\n ASSERT_TRUE( ch < grch );\n ASSERT_TRUE( grch < sblg );\n auto grch1 = sblg.child( \"child-of-siblg\" );\n ASSERT_TRUE( grch < grch1 );\n ASSERT_TRUE( grch1 > grch );\n xmlFreeNode( n );\n}\n\nTEST( ElementTest, WeakOrdering ) {\n XmlElement nullEl;\n ASSERT_TRUE( nullEl <= XmlElement{} );\n ASSERT_TRUE( nullEl >= XmlElement{} );\n\n xmlNode *n =\n xmlNewNode( NULL, reinterpret_cast<const unsigned char *>( \"test-node\" ) );\n XmlElement el{n};\n ASSERT_TRUE( el >= el);\n ASSERT_TRUE( el <= el);\n xmlFreeNode( n );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\nusing namespace std;\n\ntemplate <typename T>\nclass vector;\n\ntemplate <typename T>\nclass Foo {\npublic:\n typedef int Int;\n typedef T BaseType;\n typedef T* BaseTypePtr;\n typedef T BasTypeArray[3];\n typedef typename std::vector<T> Vector;\n typedef typename std::vector<T>::iterator Iterator;\n\n typedef enum {\n ENUM1, ENUM2\n } DeepEnum;\n\n enum {\n MIN_DIM=5, MAX_DIM=10\n };\n\n int someArray[MAX_DIM];\n\n typedef struct {\n int i, j;\n } NestedStruct;\n\n\n typedef class irrelevantTag {\n public:\n typedef enum {\n ENUM1, ENUM2\n } VeryDeepEnum;\n\n int i, j;\n } NestedClass;\n\n template <typename T1, typename T2>\n class OtherNestedClass {\n public:\n typedef enum {\n ENUM1, ENUM2\n } VeryDeepEnum;\n T1 val1;\n T2 val2;\n };\n\n void method(NestedClass & n);\n};\n\ntemplate <typename T, int I>\nclass Bar{\npublic:\n typedef typename Foo<T>::NestedStruct MyStruct;\n\n typedef class {\n public:\n int val;\n\n } NestedClass;\n\n template<typename T1>\n class NestedClass2 {\n public:\n T1 val;\n };\n};\n\n\nclass NoTemplate {\npublic:\n typedef enum {\n ENUM1, ENUM2\n } DeepEnum;\n};\n<commit_msg>Adapted the unit test<commit_after>#include <vector>\n#include <string>\nusing namespace std;\n\ntemplate <typename T>\nclass vector;\n\n#ifdef C2NIM\n#mangle NestedClass FooNestedClass\n#endif\n\ntemplate <typename T>\nclass Foo {\npublic:\n typedef int Int;\n typedef T BaseType;\n typedef T* BaseTypePtr;\n typedef T BasTypeArray[3];\n typedef typename std::vector<T> Vector;\n typedef typename std::vector<T>::iterator Iterator;\n\n typedef enum {\n ENUM1, ENUM2\n } DeepEnum;\n\n enum {\n MIN_DIM=5, MAX_DIM=10\n };\n\n int someArray[MAX_DIM];\n\n typedef struct {\n int i, j;\n } NestedStruct;\n\n\n typedef class irrelevantTag {\n public:\n typedef enum {\n ENUM1, ENUM2\n } VeryDeepEnum;\n\n int i, j;\n } NestedClass;\n\n template <typename T1, typename T2>\n class OtherNestedClass {\n public:\n typedef enum {\n ENUM1, ENUM2\n } VeryDeepEnum;\n T1 val1;\n T2 val2;\n };\n\n void method(NestedClass & n);\n};\n\ntemplate <typename T, int I>\nclass Bar{\npublic:\n typedef typename Foo<T>::NestedStruct MyStruct;\n\n typedef class {\n public:\n int val;\n\n } NestedClass;\n\n template<typename T1>\n class NestedClass2 {\n public:\n T1 val;\n };\n};\n\n\nclass NoTemplate {\npublic:\n typedef enum {\n ENUM1, ENUM2\n } DeepEnum;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 The WebM project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n#include \"webm2pes.h\"\n\n#include <cstdint>\n#include <cstdio>\n#include <limits>\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"common\/libwebm_utils.h\"\n#include \"testing\/test_util.h\"\n\nnamespace {\n\nstruct PesOptionalHeader {\n int marker = 0;\n int scrambling = 0;\n int priority = 0;\n int data_alignment = 0;\n int copyright = 0;\n int original = 0;\n int has_pts = 0;\n int has_dts = 0;\n int unused_fields = 0;\n int remaining_size = 0;\n int pts_dts_flag = 0;\n std::uint64_t pts = 0;\n int stuffing_byte = 0;\n};\n\nstruct BcmvHeader {\n BcmvHeader() = default;\n ~BcmvHeader() = default;\n BcmvHeader(const BcmvHeader&) = delete;\n BcmvHeader(BcmvHeader&&) = delete;\n\n \/\/ Convenience ctor for quick validation of expected values via operator==\n \/\/ after parsing input.\n explicit BcmvHeader(std::uint32_t len) : length(len) {\n id[0] = 'B';\n id[1] = 'C';\n id[2] = 'M';\n id[3] = 'V';\n }\n\n bool operator==(const BcmvHeader& other) const {\n return (other.length == length && other.id[0] == id[0] &&\n other.id[1] == id[1] && other.id[2] == id[2] &&\n other.id[3] == id[3]);\n }\n\n bool Valid() const {\n return (length > 0 && length <= std::numeric_limits<std::uint16_t>::max() &&\n id[0] == 'B' && id[1] == 'C' && id[2] == 'M' && id[3] == 'V');\n }\n\n char id[4] = {0};\n std::uint32_t length = 0;\n};\n\nstruct PesHeader {\n std::uint16_t packet_length = 0;\n PesOptionalHeader opt_header;\n BcmvHeader bcmv_header;\n};\n\nclass Webm2PesTests : public ::testing::Test {\n public:\n typedef std::vector<std::uint8_t> PesFileData;\n\n enum ParseState {\n kParsePesHeader,\n kParsePesOptionalHeader,\n kParseBcmvHeader,\n };\n\n \/\/ Constants for validating known values from input data.\n const std::uint8_t kMinVideoStreamId = 0xE0;\n const std::uint8_t kMaxVideoStreamId = 0xEF;\n const std::size_t kPesHeaderSize = 6;\n const std::size_t kPesOptionalHeaderStartOffset = kPesHeaderSize;\n const std::size_t kPesOptionalHeaderSize = 9;\n const int kPesOptionalHeaderMarkerValue = 0x2;\n const std::size_t kWebm2PesOptHeaderRemainingSize = 6;\n const std::size_t kBcmvHeaderSize = 10;\n\n Webm2PesTests() : read_pos_(0), parse_state_(kParsePesHeader) {}\n\n bool CreateAndLoadTestInput() {\n libwebm::Webm2Pes converter(input_file_name_, temp_file_name_.name());\n EXPECT_TRUE(converter.ConvertToFile());\n pes_file_size_ = libwebm::test::GetFileSize(pes_file_name());\n EXPECT_GT(pes_file_size_, 0);\n pes_file_data_.reserve(pes_file_size_);\n EXPECT_EQ(pes_file_size_, pes_file_data_.capacity());\n libwebm::FilePtr file = libwebm::FilePtr(\n std::fopen(pes_file_name().c_str(), \"rb\"), libwebm::FILEDeleter());\n EXPECT_EQ(std::fread(&pes_file_data_[0], 1, pes_file_size_, file.get()),\n pes_file_size_);\n read_pos_ = 0;\n parse_state_ = kParsePesHeader;\n return true;\n }\n\n bool VerifyPacketStartCode() {\n \/\/ PES packets all start with the byte sequence 0x0 0x0 0x1.\n if (pes_file_data_[read_pos_] != 0 || pes_file_data_[read_pos_ + 1] != 0 ||\n pes_file_data_[read_pos_ + 2] != 1) {\n return false;\n }\n return true;\n }\n\n std::uint8_t ReadStreamId() { return pes_file_data_[read_pos_ + 3]; }\n\n std::uint16_t ReadPacketLength() {\n \/\/ Read and byte swap 16 bit big endian length.\n return (pes_file_data_[read_pos_ + 4] << 8) | pes_file_data_[read_pos_ + 5];\n }\n\n void ParsePesHeader(PesHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParsePesHeader, parse_state_);\n EXPECT_TRUE(VerifyPacketStartCode());\n \/\/ PES Video stream IDs start at E0.\n EXPECT_GE(ReadStreamId(), kMinVideoStreamId);\n EXPECT_LE(ReadStreamId(), kMaxVideoStreamId);\n header->packet_length = ReadPacketLength();\n read_pos_ += kPesHeaderSize;\n parse_state_ = kParsePesOptionalHeader;\n }\n\n \/\/ Parses a PES optional header.\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Packetized_elementary_stream\n \/\/ TODO(tomfinegan): Make these masks constants.\n void ParsePesOptionalHeader(PesOptionalHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParsePesOptionalHeader, parse_state_);\n std::size_t offset = read_pos_;\n EXPECT_LT(offset, pes_file_size_);\n\n header->marker = (pes_file_data_[offset] & 0x80) >> 6;\n header->scrambling = (pes_file_data_[offset] & 0x30) >> 4;\n header->priority = (pes_file_data_[offset] & 0x8) >> 3;\n header->data_alignment = (pes_file_data_[offset] & 0xc) >> 2;\n header->copyright = (pes_file_data_[offset] & 0x2) >> 1;\n header->original = pes_file_data_[offset] & 0x1;\n\n offset++;\n header->has_pts = (pes_file_data_[offset] & 0x80) >> 7;\n header->has_dts = (pes_file_data_[offset] & 0x40) >> 6;\n header->unused_fields = pes_file_data_[offset] & 0x3f;\n\n offset++;\n header->remaining_size = pes_file_data_[offset];\n EXPECT_EQ(kWebm2PesOptHeaderRemainingSize, header->remaining_size);\n\n int bytes_left = header->remaining_size;\n\n if (header->has_pts) {\n \/\/ Read PTS markers. Format:\n \/\/ PTS: 5 bytes\n \/\/ 4 bits (flag: PTS present, but no DTS): 0x2 ('0010')\n \/\/ 36 bits (90khz PTS):\n \/\/ top 3 bits\n \/\/ marker ('1')\n \/\/ middle 15 bits\n \/\/ marker ('1')\n \/\/ bottom 15 bits\n \/\/ marker ('1')\n \/\/ TODO(tomfinegan): Extract some golden timestamp values and actually\n \/\/ read the timestamp.\n offset++;\n header->pts_dts_flag = (pes_file_data_[offset] & 0x20) >> 4;\n \/\/ Check the marker bits.\n int marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n offset += 2;\n marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n offset += 2;\n marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n bytes_left -= 5;\n offset++;\n }\n\n \/\/ Validate stuffing byte(s).\n for (int i = 0; i < bytes_left; ++i)\n EXPECT_EQ(0xff, pes_file_data_[offset + i]);\n\n offset += bytes_left;\n EXPECT_EQ(kPesHeaderSize + kPesOptionalHeaderSize, offset);\n\n read_pos_ += kPesOptionalHeaderSize;\n parse_state_ = kParseBcmvHeader;\n }\n\n \/\/ Parses and validates a BCMV header.\n void ParseBcmvHeader(BcmvHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParseBcmvHeader, kParseBcmvHeader);\n std::size_t offset = read_pos_;\n header->id[0] = pes_file_data_[offset++];\n header->id[1] = pes_file_data_[offset++];\n header->id[2] = pes_file_data_[offset++];\n header->id[3] = pes_file_data_[offset++];\n\n header->length |= pes_file_data_[offset++] << 24;\n header->length |= pes_file_data_[offset++] << 16;\n header->length |= pes_file_data_[offset++] << 8;\n header->length |= pes_file_data_[offset++];\n\n \/\/ Length stored in the BCMV header is followed by 2 bytes of 0 padding.\n EXPECT_EQ(0, pes_file_data_[offset++]);\n EXPECT_EQ(0, pes_file_data_[offset++]);\n\n EXPECT_TRUE(header->Valid());\n\n \/\/ TODO(tomfinegan): Verify data instead of jumping to the next packet.\n read_pos_ += kBcmvHeaderSize + header->length;\n parse_state_ = kParsePesHeader;\n }\n\n ~Webm2PesTests() = default;\n\n const std::string& pes_file_name() const { return temp_file_name_.name(); }\n std::uint64_t pes_file_size() const { return pes_file_size_; }\n const PesFileData& pes_file_data() const { return pes_file_data_; }\n\n private:\n const libwebm::test::TempFileDeleter temp_file_name_;\n const std::string input_file_name_ =\n libwebm::test::GetTestFilePath(\"bbb_480p_vp9_opus_1second.webm\");\n std::uint64_t pes_file_size_ = 0;\n PesFileData pes_file_data_;\n std::size_t read_pos_;\n ParseState parse_state_;\n};\n\nTEST_F(Webm2PesTests, CreatePesFile) {\n ASSERT_TRUE(CreateAndLoadTestInput());\n}\n\nTEST_F(Webm2PesTests, CanParseFirstPacket) {\n ASSERT_TRUE(CreateAndLoadTestInput());\n\n \/\/\n \/\/ Parse the PES Header.\n \/\/ This is number of bytes following the final byte in the 6 byte static PES\n \/\/ header. PES optional header is 9 bytes. Payload is 83 bytes.\n PesHeader header;\n ParsePesHeader(&header);\n const std::size_t kPesOptionalHeaderLength = 9;\n const std::size_t kFirstFrameLength = 83;\n const std::size_t kPesPayloadLength =\n kPesOptionalHeaderLength + kFirstFrameLength;\n EXPECT_EQ(kPesPayloadLength, header.packet_length);\n\n \/\/\n \/\/ Parse the PES optional header.\n \/\/\n ParsePesOptionalHeader(&header.opt_header);\n\n EXPECT_EQ(kPesOptionalHeaderMarkerValue, header.opt_header.marker);\n EXPECT_EQ(0, header.opt_header.scrambling);\n EXPECT_EQ(0, header.opt_header.priority);\n EXPECT_EQ(0, header.opt_header.data_alignment);\n EXPECT_EQ(0, header.opt_header.copyright);\n EXPECT_EQ(0, header.opt_header.original);\n EXPECT_EQ(1, header.opt_header.has_pts);\n EXPECT_EQ(0, header.opt_header.has_dts);\n EXPECT_EQ(0, header.opt_header.unused_fields);\n\n \/\/\n \/\/ Parse the BCMV Header\n \/\/\n ParseBcmvHeader(&header.bcmv_header);\n EXPECT_EQ(kFirstFrameLength, header.bcmv_header.length);\n\n \/\/ Parse the next PES header to confirm correct parsing and consumption of\n \/\/ payload.\n ParsePesHeader(&header);\n}\n\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>webm2pes: Fix tests.<commit_after>\/\/ Copyright (c) 2016 The WebM project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n#include \"webm2pes.h\"\n\n#include <cstdint>\n#include <cstdio>\n#include <limits>\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"common\/libwebm_utils.h\"\n#include \"testing\/test_util.h\"\n\nnamespace {\n\nstruct PesOptionalHeader {\n int marker = 0;\n int scrambling = 0;\n int priority = 0;\n int data_alignment = 0;\n int copyright = 0;\n int original = 0;\n int has_pts = 0;\n int has_dts = 0;\n int unused_fields = 0;\n int remaining_size = 0;\n int pts_dts_flag = 0;\n std::uint64_t pts = 0;\n int stuffing_byte = 0;\n};\n\nstruct BcmvHeader {\n BcmvHeader() = default;\n ~BcmvHeader() = default;\n BcmvHeader(const BcmvHeader&) = delete;\n BcmvHeader(BcmvHeader&&) = delete;\n\n \/\/ Convenience ctor for quick validation of expected values via operator==\n \/\/ after parsing input.\n explicit BcmvHeader(std::uint32_t len) : length(len) {\n id[0] = 'B';\n id[1] = 'C';\n id[2] = 'M';\n id[3] = 'V';\n }\n\n bool operator==(const BcmvHeader& other) const {\n return (other.length == length && other.id[0] == id[0] &&\n other.id[1] == id[1] && other.id[2] == id[2] &&\n other.id[3] == id[3]);\n }\n\n bool Valid() const {\n return (length > 0 && length <= std::numeric_limits<std::uint16_t>::max() &&\n id[0] == 'B' && id[1] == 'C' && id[2] == 'M' && id[3] == 'V');\n }\n\n char id[4] = {0};\n std::uint32_t length = 0;\n};\n\nstruct PesHeader {\n std::uint16_t packet_length = 0;\n PesOptionalHeader opt_header;\n BcmvHeader bcmv_header;\n};\n\nclass Webm2PesTests : public ::testing::Test {\n public:\n typedef std::vector<std::uint8_t> PesFileData;\n\n enum ParseState {\n kParsePesHeader,\n kParsePesOptionalHeader,\n kParseBcmvHeader,\n };\n\n \/\/ Constants for validating known values from input data.\n const std::uint8_t kMinVideoStreamId = 0xE0;\n const std::uint8_t kMaxVideoStreamId = 0xEF;\n const std::size_t kPesHeaderSize = 6;\n const std::size_t kPesOptionalHeaderStartOffset = kPesHeaderSize;\n const std::size_t kPesOptionalHeaderSize = 9;\n const int kPesOptionalHeaderMarkerValue = 0x2;\n const std::size_t kWebm2PesOptHeaderRemainingSize = 6;\n const std::size_t kBcmvHeaderSize = 10;\n\n Webm2PesTests() : read_pos_(0), parse_state_(kParsePesHeader) {}\n\n void CreateAndLoadTestInput() {\n libwebm::Webm2Pes converter(input_file_name_, temp_file_name_.name());\n ASSERT_TRUE(converter.ConvertToFile());\n pes_file_size_ = libwebm::test::GetFileSize(pes_file_name());\n ASSERT_GT(pes_file_size_, 0);\n pes_file_data_.reserve(pes_file_size_);\n libwebm::FilePtr file = libwebm::FilePtr(\n std::fopen(pes_file_name().c_str(), \"rb\"), libwebm::FILEDeleter());\n\n int byte;\n while ((byte = fgetc(file.get())) != EOF)\n pes_file_data_.push_back(static_cast<std::uint8_t>(byte));\n\n ASSERT_TRUE(feof(file.get()) && !ferror(file.get()));\n ASSERT_EQ(pes_file_size_, pes_file_data_.size());\n read_pos_ = 0;\n parse_state_ = kParsePesHeader;\n }\n\n bool VerifyPacketStartCode() {\n EXPECT_LT(read_pos_ + 2, pes_file_data_.size());\n\n \/\/ PES packets all start with the byte sequence 0x0 0x0 0x1.\n if (pes_file_data_[read_pos_] != 0 || pes_file_data_[read_pos_ + 1] != 0 ||\n pes_file_data_[read_pos_ + 2] != 1) {\n return false;\n }\n return true;\n }\n\n std::uint8_t ReadStreamId() {\n EXPECT_LT(read_pos_ + 3, pes_file_data_.size());\n return pes_file_data_[read_pos_ + 3]; }\n\n std::uint16_t ReadPacketLength() {\n EXPECT_LT(read_pos_ + 5, pes_file_data_.size());\n\n \/\/ Read and byte swap 16 bit big endian length.\n return (pes_file_data_[read_pos_ + 4] << 8) | pes_file_data_[read_pos_ + 5];\n }\n\n void ParsePesHeader(PesHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParsePesHeader, parse_state_);\n EXPECT_TRUE(VerifyPacketStartCode());\n \/\/ PES Video stream IDs start at E0.\n EXPECT_GE(ReadStreamId(), kMinVideoStreamId);\n EXPECT_LE(ReadStreamId(), kMaxVideoStreamId);\n header->packet_length = ReadPacketLength();\n read_pos_ += kPesHeaderSize;\n parse_state_ = kParsePesOptionalHeader;\n }\n\n \/\/ Parses a PES optional header.\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Packetized_elementary_stream\n \/\/ TODO(tomfinegan): Make these masks constants.\n void ParsePesOptionalHeader(PesOptionalHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParsePesOptionalHeader, parse_state_);\n std::size_t offset = read_pos_;\n EXPECT_LT(offset, pes_file_size_);\n\n header->marker = (pes_file_data_[offset] & 0x80) >> 6;\n header->scrambling = (pes_file_data_[offset] & 0x30) >> 4;\n header->priority = (pes_file_data_[offset] & 0x8) >> 3;\n header->data_alignment = (pes_file_data_[offset] & 0xc) >> 2;\n header->copyright = (pes_file_data_[offset] & 0x2) >> 1;\n header->original = pes_file_data_[offset] & 0x1;\n\n offset++;\n header->has_pts = (pes_file_data_[offset] & 0x80) >> 7;\n header->has_dts = (pes_file_data_[offset] & 0x40) >> 6;\n header->unused_fields = pes_file_data_[offset] & 0x3f;\n\n offset++;\n header->remaining_size = pes_file_data_[offset];\n EXPECT_EQ(kWebm2PesOptHeaderRemainingSize, header->remaining_size);\n\n int bytes_left = header->remaining_size;\n\n if (header->has_pts) {\n \/\/ Read PTS markers. Format:\n \/\/ PTS: 5 bytes\n \/\/ 4 bits (flag: PTS present, but no DTS): 0x2 ('0010')\n \/\/ 36 bits (90khz PTS):\n \/\/ top 3 bits\n \/\/ marker ('1')\n \/\/ middle 15 bits\n \/\/ marker ('1')\n \/\/ bottom 15 bits\n \/\/ marker ('1')\n \/\/ TODO(tomfinegan): Extract some golden timestamp values and actually\n \/\/ read the timestamp.\n offset++;\n header->pts_dts_flag = (pes_file_data_[offset] & 0x20) >> 4;\n \/\/ Check the marker bits.\n int marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n offset += 2;\n marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n offset += 2;\n marker_bit = pes_file_data_[offset] & 1;\n EXPECT_EQ(1, marker_bit);\n bytes_left -= 5;\n offset++;\n }\n\n \/\/ Validate stuffing byte(s).\n for (int i = 0; i < bytes_left; ++i)\n EXPECT_EQ(0xff, pes_file_data_[offset + i]);\n\n offset += bytes_left;\n EXPECT_EQ(kPesHeaderSize + kPesOptionalHeaderSize, offset);\n\n read_pos_ += kPesOptionalHeaderSize;\n parse_state_ = kParseBcmvHeader;\n }\n\n \/\/ Parses and validates a BCMV header.\n void ParseBcmvHeader(BcmvHeader* header) {\n ASSERT_TRUE(header != nullptr);\n EXPECT_EQ(kParseBcmvHeader, kParseBcmvHeader);\n std::size_t offset = read_pos_;\n header->id[0] = pes_file_data_[offset++];\n header->id[1] = pes_file_data_[offset++];\n header->id[2] = pes_file_data_[offset++];\n header->id[3] = pes_file_data_[offset++];\n\n header->length |= pes_file_data_[offset++] << 24;\n header->length |= pes_file_data_[offset++] << 16;\n header->length |= pes_file_data_[offset++] << 8;\n header->length |= pes_file_data_[offset++];\n\n \/\/ Length stored in the BCMV header is followed by 2 bytes of 0 padding.\n EXPECT_EQ(0, pes_file_data_[offset++]);\n EXPECT_EQ(0, pes_file_data_[offset++]);\n\n EXPECT_TRUE(header->Valid());\n\n \/\/ TODO(tomfinegan): Verify data instead of jumping to the next packet.\n read_pos_ += kBcmvHeaderSize + header->length;\n parse_state_ = kParsePesHeader;\n }\n\n ~Webm2PesTests() = default;\n\n const std::string& pes_file_name() const { return temp_file_name_.name(); }\n std::uint64_t pes_file_size() const { return pes_file_size_; }\n const PesFileData& pes_file_data() const { return pes_file_data_; }\n\n private:\n const libwebm::test::TempFileDeleter temp_file_name_;\n const std::string input_file_name_ =\n libwebm::test::GetTestFilePath(\"bbb_480p_vp9_opus_1second.webm\");\n std::uint64_t pes_file_size_ = 0;\n PesFileData pes_file_data_;\n std::size_t read_pos_;\n ParseState parse_state_;\n};\n\nTEST_F(Webm2PesTests, CreatePesFile) { CreateAndLoadTestInput(); }\n\nTEST_F(Webm2PesTests, CanParseFirstPacket) {\n CreateAndLoadTestInput();\n\n \/\/\n \/\/ Parse the PES Header.\n \/\/ This is number of bytes following the final byte in the 6 byte static PES\n \/\/ header. PES optional header is 9 bytes. Payload is 83 bytes.\n PesHeader header;\n ParsePesHeader(&header);\n const std::size_t kPesOptionalHeaderLength = 9;\n const std::size_t kFirstFrameLength = 83;\n const std::size_t kPesPayloadLength =\n kPesOptionalHeaderLength + kFirstFrameLength;\n EXPECT_EQ(kPesPayloadLength, header.packet_length);\n\n \/\/\n \/\/ Parse the PES optional header.\n \/\/\n ParsePesOptionalHeader(&header.opt_header);\n\n EXPECT_EQ(kPesOptionalHeaderMarkerValue, header.opt_header.marker);\n EXPECT_EQ(0, header.opt_header.scrambling);\n EXPECT_EQ(0, header.opt_header.priority);\n EXPECT_EQ(0, header.opt_header.data_alignment);\n EXPECT_EQ(0, header.opt_header.copyright);\n EXPECT_EQ(0, header.opt_header.original);\n EXPECT_EQ(1, header.opt_header.has_pts);\n EXPECT_EQ(0, header.opt_header.has_dts);\n EXPECT_EQ(0, header.opt_header.unused_fields);\n\n \/\/\n \/\/ Parse the BCMV Header\n \/\/\n ParseBcmvHeader(&header.bcmv_header);\n EXPECT_EQ(kFirstFrameLength, header.bcmv_header.length);\n\n \/\/ Parse the next PES header to confirm correct parsing and consumption of\n \/\/ payload.\n ParsePesHeader(&header);\n}\n\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/\n\n#include <cn24.h>\n\n#include <vector>\n#include <utility>\n#include <string>\n#include <cmath>\n#include <random>\n\n\/\/ TEST SETUP\nunsigned int RANDOM_RUNS = 15;\nunsigned int SAMPLES = 2, WIDTH = 9, HEIGHT = 6, MAPS = 3;\nConv::datum epsilon = 0.005;\n\nstd::vector<std::pair<std::string, unsigned int>> test_layers_and_runs = {\n {\"maxpooling(size=3x3)\",1},\n {\"maxpooling(size=3x2)\",1},\n {\"amaxpooling(size=3x3)\",1},\n {\"amaxpooling(size=3x2)\",1},\n {\"amaxpooling(size=3x3 stride=2x2)\",1},\n {\"convolution(size=3x3 kernels=3)\",RANDOM_RUNS},\n {\"convolution(size=3x3 stride=2x2 kernels=3)\",RANDOM_RUNS},\n {\"convolution(size=3x3 group=3 kernels=9)\",RANDOM_RUNS},\n {\"hmax(mu=0.1 weight=0.0)\",1},\n \/\/ {\"hmax(mu=0.1 weight=0.2)\",1},\n {\"tanh\",1},{\"sigm\",1},{\"relu\",1},\n {\"gradientaccumulation(outputs=2)\",1},\n {\"resize(border=2x2)\",1}\n};\n\n\/\/ UTILITIES\nConv::datum SimpleSumLoss(Conv::Layer* layer, const Conv::Tensor& tensor) {\n#ifdef BUILD_OPENCL\n ((Conv::Tensor&)tensor).MoveToCPU();\n#endif\n Conv::datum sum = 0;\n \n for (unsigned int e = 0; e < tensor.elements(); e++) {\n const Conv::datum element = tensor.data_ptr_const()[e];\n sum += fabs(element);\n }\n \n return sum;\n}\n\nConv::datum SimpleSumLoss(Conv::Layer* layer, const std::vector<Conv::CombinedTensor*>& outputs) {\n Conv::datum sum = 0;\n \n for (unsigned int o = 0; o < outputs.size(); o++) {\n sum += SimpleSumLoss(layer, outputs[o]->data);\n }\n \n Conv::LossFunctionLayer* loss_layer = dynamic_cast<Conv::LossFunctionLayer*>(layer);\n if (loss_layer != NULL)\n sum += loss_layer->CalculateLossFunction();\n \n return sum;\n}\n\nvoid SimpleSumLossGradient(const std::vector<Conv::CombinedTensor*>& outputs) {\n for (unsigned int o = 0; o < outputs.size(); o++) {\n Conv::Tensor& tensor = outputs[o]->data;\n Conv::Tensor& delta_tensor = outputs[o]->delta;\n#ifdef BUILD_OPENCL\n tensor.MoveToCPU();\n delta_tensor.MoveToCPU();\n#endif\n for (unsigned int e = 0; e < tensor.elements(); e++) {\n const Conv::datum element = tensor.data_ptr_const()[e];\n const Conv::datum gradient = element > 0.0 ? 1.0 : -1.0;\n delta_tensor.data_ptr()[e] = gradient;\n }\n }\n}\n\nint main(int argc, char* argv[]) {\n if((argc > 1 && std::string(\"-v\").compare(argv[1]) == 0) || argc > 2) {\n Conv::System::Init(3);\n } else {\n Conv::System::Init();\n }\n \n std::mt19937 seed_generator(93023);\n std::uniform_real_distribution<Conv::datum> dist(1.0, 2.0);\n \n Conv::NetStatus net_status;\n net_status.SetIsTesting(true);\n \n bool test_failed = false;\n \n Conv::CombinedTensor input_data(SAMPLES, WIDTH, HEIGHT, MAPS);\n \n std::vector<std::string> test_layers;\n \n if (argc > 1) {\n std::string test_layer = argv[1];\n test_layers.push_back(test_layer);\n } else {\n for (std::pair<std::string, unsigned int>& layer_pair : test_layers_and_runs) {\n std::string& layer_descriptor = layer_pair.first;\n unsigned int runs = layer_pair.second;\n for(unsigned int i = 0; i < runs; i++) {\n \/\/ Inject random seeds\n std::string injected_descriptor = Conv::LayerFactory::InjectSeed(layer_descriptor, seed_generator());\n test_layers.push_back(injected_descriptor);\n }\n }\n }\n \n for (std::string& layer_descriptor : test_layers) {\n bool data_sign = seed_generator() % 2 == 0;\n for(unsigned int e = 0; e < input_data.data.elements(); e++) {\n if(data_sign)\n input_data.data.data_ptr()[e] = dist(seed_generator);\n else\n input_data.data.data_ptr()[e] = -dist(seed_generator);\n }\n input_data.delta.Clear(0.0);\n \n LOGINFO << \"Testing layer: \" << layer_descriptor;\n Conv::Layer* layer = Conv::LayerFactory::ConstructLayer(layer_descriptor);\n if(layer == nullptr) {\n test_failed = true;\n LOGINFO << \" Constructing...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n LOGDEBUG << \" Description: \" << layer->GetLayerDescription();\n LOGDEBUG << \" Configuration: \" << layer->GetLayerConfiguration();\n \n if (Conv::LayerFactory::ExtractConfiguration(layer_descriptor).length() > 0\n && layer->GetLayerConfiguration().length() == 0) {\n test_failed = true;\n LOGINFO << \" Testing configuration loss...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n std::vector<Conv::CombinedTensor*> outputs;\n bool createoutputs_success = layer->CreateOutputs({&input_data}, outputs);\n if(!createoutputs_success) {\n test_failed = true;\n LOGINFO << \" Creating outputs...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n for(Conv::CombinedTensor* output : outputs) {\n LOGDEBUG << \" Output: \" << output->data;\n }\n \n bool connect_success = layer->Connect({&input_data}, outputs, &net_status);\n if(!connect_success) {\n test_failed = true;\n LOGINFO << \" Connecting...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n layer->OnLayerConnect({});\n \n if(layer->parameters().size() == 0) {\n LOGDEBUG << \" Layer has no weights\";\n }\n \n \/\/ Function pointers for external gradient check\n void (*WriteLossDeltas)(const std::vector<Conv::CombinedTensor*>&) =\n SimpleSumLossGradient;\n Conv::datum (*CalculateLoss)(Conv::Layer*, const std::vector<Conv::CombinedTensor*>&) =\n SimpleSumLoss;\n \n for(Conv::CombinedTensor* weights : layer->parameters()) {\n bool gradient_success = Conv::GradientTester::DoGradientTest(layer, weights->data, weights->delta, outputs, epsilon, WriteLossDeltas, CalculateLoss);\n if(!gradient_success) {\n test_failed = true;\n LOGINFO << \" Gradient test (weights)...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n }\n \n bool gradient_success = Conv::GradientTester::DoGradientTest(layer, input_data.data, input_data.delta, outputs, epsilon, WriteLossDeltas, CalculateLoss);\n if(!gradient_success) {\n test_failed = true;\n LOGINFO << \" Gradient test (inputs)...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n delete layer;\n for(Conv::CombinedTensor* output : outputs)\n delete output;\n }\n \n Conv::System::Shutdown();\n \n return test_failed ? -1 : 0;\n}\n<commit_msg>SimpleLayerTest: Reintroduced HMax with non-zero weights<commit_after>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/\n\n#include <cn24.h>\n\n#include <vector>\n#include <utility>\n#include <string>\n#include <cmath>\n#include <random>\n\n\/\/ TEST SETUP\nunsigned int RANDOM_RUNS = 15;\nunsigned int SAMPLES = 2, WIDTH = 9, HEIGHT = 6, MAPS = 3;\nConv::datum epsilon = 0.005;\n\nstd::vector<std::pair<std::string, unsigned int>> test_layers_and_runs = {\n {\"maxpooling(size=3x3)\",1},\n {\"maxpooling(size=3x2)\",1},\n {\"amaxpooling(size=3x3)\",1},\n {\"amaxpooling(size=3x2)\",1},\n {\"amaxpooling(size=3x3 stride=2x2)\",1},\n {\"convolution(size=3x3 kernels=3)\",RANDOM_RUNS},\n {\"convolution(size=3x3 stride=2x2 kernels=3)\",RANDOM_RUNS},\n {\"convolution(size=3x3 group=3 kernels=9)\",RANDOM_RUNS},\n {\"hmax(mu=0.1 weight=0.0)\",1},\n {\"hmax(mu=0.1 weight=0.2)\",1},\n {\"tanh\",1},{\"sigm\",1},{\"relu\",1},\n {\"gradientaccumulation(outputs=2)\",1},\n {\"resize(border=2x2)\",1}\n};\n\n\/\/ UTILITIES\nConv::datum SimpleSumLoss(Conv::Layer* layer, const Conv::Tensor& tensor) {\n#ifdef BUILD_OPENCL\n ((Conv::Tensor&)tensor).MoveToCPU();\n#endif\n Conv::datum sum = 0;\n \n for (unsigned int e = 0; e < tensor.elements(); e++) {\n const Conv::datum element = tensor.data_ptr_const()[e];\n sum += fabs(element);\n }\n \n return sum;\n}\n\nConv::datum SimpleSumLoss(Conv::Layer* layer, const std::vector<Conv::CombinedTensor*>& outputs) {\n Conv::datum sum = 0;\n \n for (unsigned int o = 0; o < outputs.size(); o++) {\n sum += SimpleSumLoss(layer, outputs[o]->data);\n }\n \n Conv::LossFunctionLayer* loss_layer = dynamic_cast<Conv::LossFunctionLayer*>(layer);\n if (loss_layer != NULL)\n sum += loss_layer->CalculateLossFunction();\n \n return sum;\n}\n\nvoid SimpleSumLossGradient(const std::vector<Conv::CombinedTensor*>& outputs) {\n for (unsigned int o = 0; o < outputs.size(); o++) {\n Conv::Tensor& tensor = outputs[o]->data;\n Conv::Tensor& delta_tensor = outputs[o]->delta;\n#ifdef BUILD_OPENCL\n tensor.MoveToCPU();\n delta_tensor.MoveToCPU();\n#endif\n for (unsigned int e = 0; e < tensor.elements(); e++) {\n const Conv::datum element = tensor.data_ptr_const()[e];\n const Conv::datum gradient = element > 0.0 ? 1.0 : -1.0;\n delta_tensor.data_ptr()[e] = gradient;\n }\n }\n}\n\nint main(int argc, char* argv[]) {\n if((argc > 1 && std::string(\"-v\").compare(argv[1]) == 0) || argc > 2) {\n Conv::System::Init(3);\n } else {\n Conv::System::Init();\n }\n \n std::mt19937 seed_generator(93023);\n std::uniform_real_distribution<Conv::datum> dist(1.0, 2.0);\n \n Conv::NetStatus net_status;\n net_status.SetIsTesting(true);\n \n bool test_failed = false;\n \n Conv::CombinedTensor input_data(SAMPLES, WIDTH, HEIGHT, MAPS);\n \n std::vector<std::string> test_layers;\n \n if (argc > 1) {\n std::string test_layer = argv[1];\n test_layers.push_back(test_layer);\n } else {\n for (std::pair<std::string, unsigned int>& layer_pair : test_layers_and_runs) {\n std::string& layer_descriptor = layer_pair.first;\n unsigned int runs = layer_pair.second;\n for(unsigned int i = 0; i < runs; i++) {\n \/\/ Inject random seeds\n std::string injected_descriptor = Conv::LayerFactory::InjectSeed(layer_descriptor, seed_generator());\n test_layers.push_back(injected_descriptor);\n }\n }\n }\n \n for (std::string& layer_descriptor : test_layers) {\n bool data_sign = seed_generator() % 2 == 0;\n for(unsigned int e = 0; e < input_data.data.elements(); e++) {\n if(data_sign)\n input_data.data.data_ptr()[e] = dist(seed_generator);\n else\n input_data.data.data_ptr()[e] = -dist(seed_generator);\n }\n input_data.delta.Clear(0.0);\n \n LOGINFO << \"Testing layer: \" << layer_descriptor;\n Conv::Layer* layer = Conv::LayerFactory::ConstructLayer(layer_descriptor);\n if(layer == nullptr) {\n test_failed = true;\n LOGINFO << \" Constructing...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n LOGDEBUG << \" Description: \" << layer->GetLayerDescription();\n LOGDEBUG << \" Configuration: \" << layer->GetLayerConfiguration();\n \n if (Conv::LayerFactory::ExtractConfiguration(layer_descriptor).length() > 0\n && layer->GetLayerConfiguration().length() == 0) {\n test_failed = true;\n LOGINFO << \" Testing configuration loss...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n std::vector<Conv::CombinedTensor*> outputs;\n bool createoutputs_success = layer->CreateOutputs({&input_data}, outputs);\n if(!createoutputs_success) {\n test_failed = true;\n LOGINFO << \" Creating outputs...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n for(Conv::CombinedTensor* output : outputs) {\n LOGDEBUG << \" Output: \" << output->data;\n }\n \n bool connect_success = layer->Connect({&input_data}, outputs, &net_status);\n if(!connect_success) {\n test_failed = true;\n LOGINFO << \" Connecting...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n layer->OnLayerConnect({});\n \n if(layer->parameters().size() == 0) {\n LOGDEBUG << \" Layer has no weights\";\n }\n \n \/\/ Function pointers for external gradient check\n void (*WriteLossDeltas)(const std::vector<Conv::CombinedTensor*>&) =\n SimpleSumLossGradient;\n Conv::datum (*CalculateLoss)(Conv::Layer*, const std::vector<Conv::CombinedTensor*>&) =\n SimpleSumLoss;\n \n for(Conv::CombinedTensor* weights : layer->parameters()) {\n bool gradient_success = Conv::GradientTester::DoGradientTest(layer, weights->data, weights->delta, outputs, epsilon, WriteLossDeltas, CalculateLoss);\n if(!gradient_success) {\n test_failed = true;\n LOGINFO << \" Gradient test (weights)...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n }\n \n bool gradient_success = Conv::GradientTester::DoGradientTest(layer, input_data.data, input_data.delta, outputs, epsilon, WriteLossDeltas, CalculateLoss);\n if(!gradient_success) {\n test_failed = true;\n LOGINFO << \" Gradient test (inputs)...\";\n LOGERROR << \" FAILED\";\n continue;\n }\n \n delete layer;\n for(Conv::CombinedTensor* output : outputs)\n delete output;\n }\n \n Conv::System::Shutdown();\n \n return test_failed ? -1 : 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/equation_systems.h>\n#include <libmesh\/mesh.h>\n#include <libmesh\/mesh_generation.h>\n#include <libmesh\/elem.h>\n#include <libmesh\/dof_map.h>\n\n#include \"test_comm.h\"\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings. These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas. We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point. We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\n\/\/ This class is used by testCyclicConstraintDetection\nclass MyConstraint : public System::Constraint\n{\nprivate:\n\n System & _sys;\n\npublic:\n\n MyConstraint( System & sys ) : Constraint(), _sys(sys) {}\n\n virtual ~MyConstraint() {}\n\n void constrain()\n {\n {\n const dof_id_type constrained_dof_index = 0;\n DofConstraintRow constraint_row;\n constraint_row[1] = 1.0;\n _sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);\n }\n {\n const dof_id_type constrained_dof_index = 1;\n DofConstraintRow constraint_row;\n constraint_row[0] = 1.0;\n _sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);\n }\n }\n};\n\n\nclass DofMapTest : public CppUnit::TestCase {\npublic:\n CPPUNIT_TEST_SUITE( DofMapTest );\n\n CPPUNIT_TEST( testDofOwnerOnEdge3 );\n CPPUNIT_TEST( testDofOwnerOnQuad9 );\n CPPUNIT_TEST( testDofOwnerOnTri6 );\n CPPUNIT_TEST( testDofOwnerOnHex27 );\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n CPPUNIT_TEST( testCyclicConstraintDetection );\n#endif \/\/ LIBMESH_ENABLE_CONSTRAINTS\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\npublic:\n void setUp()\n {}\n\n void tearDown()\n {}\n\n void testDofOwner(const ElemType elem_type)\n {\n Mesh mesh(*TestCommWorld);\n\n EquationSystems es(mesh);\n System &sys = es.add_system<System> (\"SimpleSystem\");\n sys.add_variable(\"u\", THIRD, HIERARCHIC);\n\n const unsigned n_elem_per_side = 3;\n const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);\n const Real ymax = test_elem->dim() > 1;\n const Real zmax = test_elem->dim() > 2;\n const unsigned int ny = ymax * n_elem_per_side;\n const unsigned int nz = zmax * n_elem_per_side;\n\n MeshTools::Generation::build_cube (mesh,\n n_elem_per_side,\n ny,\n nz,\n 0., 1.,\n 0., ymax,\n 0., zmax,\n elem_type);\n\n es.init();\n\n DofMap & dof_map = sys.get_dof_map();\n for (dof_id_type id = 0; id != dof_map.n_dofs(); ++id)\n {\n const processor_id_type pid = dof_map.dof_owner(id);\n CPPUNIT_ASSERT(dof_map.first_dof(pid) <= id);\n CPPUNIT_ASSERT(id < dof_map.end_dof(pid));\n }\n }\n\n\n\n void testDofOwnerOnEdge3() { testDofOwner(EDGE3); }\n void testDofOwnerOnQuad9() { testDofOwner(QUAD9); }\n void testDofOwnerOnTri6() { testDofOwner(TRI6); }\n void testDofOwnerOnHex27() { testDofOwner(HEX27); }\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n void testCyclicConstraintDetection()\n {\n Mesh mesh(*TestCommWorld);\n\n EquationSystems es(mesh);\n System & sys = es.add_system<System> (\"SimpleSystem\");\n sys.add_variable(\"u\", FIRST);\n\n MyConstraint my_constraint(sys);\n sys.attach_constraint_object(my_constraint);\n\n MeshTools::Generation::build_square (mesh,4,4,-1., 1.,-1., 1., QUAD4);\n\n \/\/ Tell the dof_map to check for cyclic constraints\n DofMap & dof_map = sys.get_dof_map();\n dof_map.set_error_on_cyclic_constraint(true);\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\"Cyclic constraint not detected\", es.init(), libMesh::LogicError);\n }\n#endif \/\/ LIBMESH_ENABLE_CONSTRAINTS\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( DofMapTest );\n<commit_msg>DofMapTest: testCyclicConstraintDetection() requires exceptions.<commit_after>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/equation_systems.h>\n#include <libmesh\/mesh.h>\n#include <libmesh\/mesh_generation.h>\n#include <libmesh\/elem.h>\n#include <libmesh\/dof_map.h>\n\n#include \"test_comm.h\"\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings. These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas. We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point. We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\n\/\/ This class is used by testCyclicConstraintDetection\nclass MyConstraint : public System::Constraint\n{\nprivate:\n\n System & _sys;\n\npublic:\n\n MyConstraint( System & sys ) : Constraint(), _sys(sys) {}\n\n virtual ~MyConstraint() {}\n\n void constrain()\n {\n {\n const dof_id_type constrained_dof_index = 0;\n DofConstraintRow constraint_row;\n constraint_row[1] = 1.0;\n _sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);\n }\n {\n const dof_id_type constrained_dof_index = 1;\n DofConstraintRow constraint_row;\n constraint_row[0] = 1.0;\n _sys.get_dof_map().add_constraint_row( constrained_dof_index, constraint_row, 0., true);\n }\n }\n};\n\n\nclass DofMapTest : public CppUnit::TestCase {\npublic:\n CPPUNIT_TEST_SUITE( DofMapTest );\n\n CPPUNIT_TEST( testDofOwnerOnEdge3 );\n CPPUNIT_TEST( testDofOwnerOnQuad9 );\n CPPUNIT_TEST( testDofOwnerOnTri6 );\n CPPUNIT_TEST( testDofOwnerOnHex27 );\n\n#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS)\n CPPUNIT_TEST( testCyclicConstraintDetection );\n#endif\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\npublic:\n void setUp()\n {}\n\n void tearDown()\n {}\n\n void testDofOwner(const ElemType elem_type)\n {\n Mesh mesh(*TestCommWorld);\n\n EquationSystems es(mesh);\n System &sys = es.add_system<System> (\"SimpleSystem\");\n sys.add_variable(\"u\", THIRD, HIERARCHIC);\n\n const unsigned n_elem_per_side = 3;\n const std::unique_ptr<Elem> test_elem = Elem::build(elem_type);\n const Real ymax = test_elem->dim() > 1;\n const Real zmax = test_elem->dim() > 2;\n const unsigned int ny = ymax * n_elem_per_side;\n const unsigned int nz = zmax * n_elem_per_side;\n\n MeshTools::Generation::build_cube (mesh,\n n_elem_per_side,\n ny,\n nz,\n 0., 1.,\n 0., ymax,\n 0., zmax,\n elem_type);\n\n es.init();\n\n DofMap & dof_map = sys.get_dof_map();\n for (dof_id_type id = 0; id != dof_map.n_dofs(); ++id)\n {\n const processor_id_type pid = dof_map.dof_owner(id);\n CPPUNIT_ASSERT(dof_map.first_dof(pid) <= id);\n CPPUNIT_ASSERT(id < dof_map.end_dof(pid));\n }\n }\n\n\n\n void testDofOwnerOnEdge3() { testDofOwner(EDGE3); }\n void testDofOwnerOnQuad9() { testDofOwner(QUAD9); }\n void testDofOwnerOnTri6() { testDofOwner(TRI6); }\n void testDofOwnerOnHex27() { testDofOwner(HEX27); }\n\n#if defined(LIBMESH_ENABLE_CONSTRAINTS) && defined(LIBMESH_ENABLE_EXCEPTIONS)\n void testCyclicConstraintDetection()\n {\n Mesh mesh(*TestCommWorld);\n\n EquationSystems es(mesh);\n System & sys = es.add_system<System> (\"SimpleSystem\");\n sys.add_variable(\"u\", FIRST);\n\n MyConstraint my_constraint(sys);\n sys.attach_constraint_object(my_constraint);\n\n MeshTools::Generation::build_square (mesh,4,4,-1., 1.,-1., 1., QUAD4);\n\n \/\/ Tell the dof_map to check for cyclic constraints\n DofMap & dof_map = sys.get_dof_map();\n dof_map.set_error_on_cyclic_constraint(true);\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\"Cyclic constraint not detected\", es.init(), libMesh::LogicError);\n }\n#endif\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( DofMapTest );\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"..\/mediasource.h\"\n#include \"..\/abstractmediastream.h\"\n#include \"loadfakebackend.h\"\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QUrl>\n#include <qtest_kde.h>\n#include <QtCore\/QObject>\n\nclass MediaSourceTest : public QObject\n{\n Q_OBJECT\n private Q_SLOTS:\n void initTestCase();\n void testLocalFile();\n void testUrl();\n void testDiscType();\n void testStream();\n void testIODevice();\n void testQtResource();\n void cleanupTestCase();\n};\n\nusing namespace Phonon;\n\nvoid MediaSourceTest::initTestCase()\n{\n \/\/ no need for a backend at all\n \/\/ Phonon::loadFakeBackend();\n}\n\nvoid MediaSourceTest::testLocalFile()\n{\n QString filename(\"\/usr\/share\/sounds\/KDE_Beep.ogg\");\n AbstractMediaStream *stream = 0;\n\n MediaSource a(filename);\n QCOMPARE(a.type(), MediaSource::LocalFile);\n QCOMPARE(a.fileName(), filename);\n QCOMPARE(a.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::LocalFile);\n QCOMPARE(b.fileName(), filename);\n QCOMPARE(b.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::LocalFile);\n QCOMPARE(c.fileName(), filename);\n QCOMPARE(c.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n \/\/test that a relative file path is correctly set as an absolute URL\n filename = \"foo.ogg\";\n MediaSource relative(filename);\n \/\/QCOMPARE(relative.fileName(), filename);\n QFileInfo urlInfo(relative.url().toLocalFile());\n QVERIFY(urlInfo.isAbsolute());\n QCOMPARE(urlInfo.fileName(), filename);\n QCOMPARE(urlInfo.absolutePath(), QDir::currentPath());\n}\n\nvoid MediaSourceTest::testUrl()\n{\n QUrl url(\"http:\/\/www.example.com\/music.ogg\");\n AbstractMediaStream *stream = 0;\n\n MediaSource a(url);\n QCOMPARE(a.type(), MediaSource::Url);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), url);\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Url);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), url);\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Url);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), url);\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n}\n\nvoid MediaSourceTest::testDiscType()\n{\n for (int i = 0; i <= Phonon::Vcd; ++i) {\n Phonon::DiscType discType = static_cast<Phonon::DiscType>(i);\n AbstractMediaStream *stream = 0;\n\n MediaSource a(discType);\n\n QCOMPARE(a.type(), MediaSource::Disc);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), discType);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Disc);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), discType);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Disc);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), discType);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n }\n}\n\nclass Stream : public AbstractMediaStream\n{\n public:\n void reset() {}\n void needData() {}\n void enoughData() {}\n};\n\nvoid MediaSourceTest::testStream()\n{\n AbstractMediaStream *stream = new Stream;\n\n MediaSource a(stream);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n delete stream;\n QCOMPARE(a.type(), MediaSource::Invalid);\n QCOMPARE(b.type(), MediaSource::Invalid);\n QCOMPARE(c.type(), MediaSource::Invalid);\n const AbstractMediaStream *null = 0;\n QCOMPARE(a.stream(), null);\n QCOMPARE(b.stream(), null);\n QCOMPARE(c.stream(), null);\n}\n\nvoid MediaSourceTest::testIODevice()\n{\n const QByteArray data(\"0192380\");\n QBuffer *buffer = new QBuffer;\n buffer->setData(data);\n buffer->open(QIODevice::ReadOnly);\n\n MediaSource a(buffer);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QVERIFY(a.stream() != 0);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QVERIFY(b.stream() != 0);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QVERIFY(c.stream() != 0);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n delete buffer;\n QCOMPARE(a.type(), MediaSource::Invalid);\n QCOMPARE(b.type(), MediaSource::Invalid);\n QCOMPARE(c.type(), MediaSource::Invalid);\n const AbstractMediaStream *null = 0;\n QCOMPARE(a.stream(), null);\n QCOMPARE(b.stream(), null);\n QCOMPARE(c.stream(), null);\n}\n\nvoid MediaSourceTest::testQtResource()\n{\n const QString filename(\":\/ogg\/zero.ogg\");\n MediaSource a(filename);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QVERIFY(a.stream() != 0);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QVERIFY(b.stream() != 0);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QVERIFY(c.stream() != 0);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n}\n\nvoid MediaSourceTest::cleanupTestCase()\n{\n}\n\nQTEST_APPLESS_MAIN(MediaSourceTest)\n\n#include \"mediasourcetest.moc\"\n\/\/ vim: sw=4 sts=4 et tw=100\n<commit_msg>fix tests<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"..\/mediasource.h\"\n#include \"..\/abstractmediastream.h\"\n#include \"loadfakebackend.h\"\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QUrl>\n#include <qtest_kde.h>\n#include <QtCore\/QObject>\n\nclass MediaSourceTest : public QObject\n{\n Q_OBJECT\n private Q_SLOTS:\n void initTestCase();\n void testLocalFile();\n void testUrl();\n void testDiscType();\n void testStream();\n void testIODevice();\n void testQtResource();\n void cleanupTestCase();\n};\n\nusing namespace Phonon;\n\nvoid MediaSourceTest::initTestCase()\n{\n \/\/ no need for a backend at all\n \/\/ Phonon::loadFakeBackend();\n}\n\nvoid MediaSourceTest::testLocalFile()\n{\n QString filename(\"\/usr\/share\/sounds\/KDE_Beep.ogg\");\n AbstractMediaStream *stream = 0;\n\n MediaSource a(filename);\n QCOMPARE(a.type(), MediaSource::LocalFile);\n QCOMPARE(a.fileName(), filename);\n QCOMPARE(a.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::LocalFile);\n QCOMPARE(b.fileName(), filename);\n QCOMPARE(b.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::LocalFile);\n QCOMPARE(c.fileName(), filename);\n QCOMPARE(c.url(), QUrl::fromLocalFile(filename));\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n \/\/ non-existing files should become invalid sources\n filename = \"\/some\/invalid\/file.xyz\";\n MediaSource invalid(filename);\n QCOMPARE(invalid.type(), MediaSource::Invalid);\n QCOMPARE(invalid.fileName(), QString());\n\n \/\/test that a relative file path is correctly set as an absolute URL\n QFile testFile(\"foo.ogg\");\n bool deleteFile = false;\n if (!testFile.exists()) {\n deleteFile = true;\n testFile.open(QIODevice::WriteOnly);\n testFile.close();\n }\n filename = \"foo.ogg\";\n MediaSource relative(filename);\n \/\/QCOMPARE(relative.fileName(), filename);\n QFileInfo urlInfo(relative.url().toLocalFile());\n QVERIFY(urlInfo.isAbsolute());\n QCOMPARE(urlInfo.fileName(), filename);\n QCOMPARE(urlInfo.absolutePath(), QDir::currentPath());\n if (deleteFile) {\n testFile.remove();\n }\n}\n\nvoid MediaSourceTest::testUrl()\n{\n QUrl url(\"http:\/\/www.example.com\/music.ogg\");\n AbstractMediaStream *stream = 0;\n\n MediaSource a(url);\n QCOMPARE(a.type(), MediaSource::Url);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), url);\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Url);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), url);\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Url);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), url);\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n}\n\nvoid MediaSourceTest::testDiscType()\n{\n for (int i = 0; i <= Phonon::Vcd; ++i) {\n Phonon::DiscType discType = static_cast<Phonon::DiscType>(i);\n AbstractMediaStream *stream = 0;\n\n MediaSource a(discType);\n\n QCOMPARE(a.type(), MediaSource::Disc);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), discType);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Disc);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), discType);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Disc);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), discType);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n }\n}\n\nclass Stream : public AbstractMediaStream\n{\n public:\n void reset() {}\n void needData() {}\n void enoughData() {}\n};\n\nvoid MediaSourceTest::testStream()\n{\n AbstractMediaStream *stream = new Stream;\n\n MediaSource a(stream);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QCOMPARE(a.stream(), stream);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QCOMPARE(b.stream(), stream);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QCOMPARE(c.stream(), stream);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n delete stream;\n QCOMPARE(a.type(), MediaSource::Invalid);\n QCOMPARE(b.type(), MediaSource::Invalid);\n QCOMPARE(c.type(), MediaSource::Invalid);\n const AbstractMediaStream *null = 0;\n QCOMPARE(a.stream(), null);\n QCOMPARE(b.stream(), null);\n QCOMPARE(c.stream(), null);\n}\n\nvoid MediaSourceTest::testIODevice()\n{\n const QByteArray data(\"0192380\");\n QBuffer *buffer = new QBuffer;\n buffer->setData(data);\n buffer->open(QIODevice::ReadOnly);\n\n MediaSource a(buffer);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QVERIFY(a.stream() != 0);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QVERIFY(b.stream() != 0);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QVERIFY(c.stream() != 0);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n\n delete buffer;\n QCOMPARE(a.type(), MediaSource::Invalid);\n QCOMPARE(b.type(), MediaSource::Invalid);\n QCOMPARE(c.type(), MediaSource::Invalid);\n const AbstractMediaStream *null = 0;\n QCOMPARE(a.stream(), null);\n QCOMPARE(b.stream(), null);\n QCOMPARE(c.stream(), null);\n}\n\nvoid MediaSourceTest::testQtResource()\n{\n const QString filename(\":\/ogg\/zero.ogg\");\n MediaSource a(filename);\n QCOMPARE(a.type(), MediaSource::Stream);\n QCOMPARE(a.fileName(), QString());\n QCOMPARE(a.url(), QUrl());\n QCOMPARE(a.discType(), Phonon::NoDisc);\n QVERIFY(a.stream() != 0);\n QCOMPARE(a.deviceName(), QString());\n \/\/QCOMPARE(a.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(a.videoCaptureDevice(), VideoCaptureDevice());\n MediaSource b(a);\n MediaSource c;\n c = a;\n QCOMPARE(a, b);\n QCOMPARE(a, c);\n QCOMPARE(b, c);\n\n QCOMPARE(b.type(), MediaSource::Stream);\n QCOMPARE(b.fileName(), QString());\n QCOMPARE(b.url(), QUrl());\n QCOMPARE(b.discType(), Phonon::NoDisc);\n QVERIFY(b.stream() != 0);\n QCOMPARE(b.deviceName(), QString());\n \/\/QCOMPARE(b.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(b.videoCaptureDevice(), VideoCaptureDevice());\n\n QCOMPARE(c.type(), MediaSource::Stream);\n QCOMPARE(c.fileName(), QString());\n QCOMPARE(c.url(), QUrl());\n QCOMPARE(c.discType(), Phonon::NoDisc);\n QVERIFY(c.stream() != 0);\n QCOMPARE(c.deviceName(), QString());\n \/\/QCOMPARE(c.audioCaptureDevice(), AudioCaptureDevice());\n \/\/QCOMPARE(c.videoCaptureDevice(), VideoCaptureDevice());\n}\n\nvoid MediaSourceTest::cleanupTestCase()\n{\n}\n\nQTEST_APPLESS_MAIN(MediaSourceTest)\n\n#include \"mediasourcetest.moc\"\n\/\/ vim: sw=4 sts=4 et tw=100\n<|endoftext|>"} {"text":"<commit_before>\/* \n Mathieu Stefani, 07 février 2016\n \n Example of a REST endpoint with routing\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include <pistache\/http.h>\n#include <pistache\/router.h>\n#include <pistache\/endpoint.h>\n\n#include \"httplib.h\"\n\nusing namespace std;\nusing namespace Pistache;\n\nclass StatsEndpoint {\npublic:\n StatsEndpoint(Address addr)\n : httpEndpoint(std::make_shared<Http::Endpoint>(addr))\n { }\n\n void init(size_t thr = 2) {\n auto opts = Http::Endpoint::options()\n .threads(thr)\n .flags(Tcp::Options::InstallSignalHandler);\n httpEndpoint->init(opts);\n setupRoutes();\n }\n\n void start() {\n httpEndpoint->setHandler(router.handler());\n httpEndpoint->serveThreaded();\n }\n\n void shutdown() {\n httpEndpoint->shutdown();\n }\n\nprivate:\n void setupRoutes() {\n using namespace Rest;\n Routes::Get(router, \"\/read\/function1\", Routes::bind(&StatsEndpoint::doAuth, this));\n }\n\n void doAuth(const Rest::Request& \/*request*\/, Http::ResponseWriter response) {\n std::thread worker([](Http::ResponseWriter writer) {\n writer.send(Http::Code::Ok, \"1\");\n }, std::move(response));\n worker.detach();\n }\n\n std::shared_ptr<Http::Endpoint> httpEndpoint;\n Rest::Router router;\n};\n\nTEST(rest_server_test, basic_test) {\n Port port(9090);\n int thr = 1;\n\n Address addr(Ipv4::any(), port);\n\n StatsEndpoint stats(addr);\n\n stats.init(thr);\n stats.start();\n\n cout << \"Cores = \" << hardware_concurrency() << endl;\n cout << \"Using \" << thr << \" threads\" << endl;\n\n httplib::Client client(\"localhost\", 9090);\n auto res = client.Get(\"\/read\/function1\");\n ASSERT_EQ(res->status, 200);\n ASSERT_EQ(res->body, \"1\");\n\n stats.shutdown();\n}\n<commit_msg>Use emphemeral port for unit test.<commit_after>\/* \n Mathieu Stefani, 07 février 2016\n \n Example of a REST endpoint with routing\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include <pistache\/http.h>\n#include <pistache\/router.h>\n#include <pistache\/endpoint.h>\n\n#include \"httplib.h\"\n\nusing namespace std;\nusing namespace Pistache;\n\nclass StatsEndpoint {\npublic:\n StatsEndpoint(Address addr)\n : httpEndpoint(std::make_shared<Http::Endpoint>(addr))\n { }\n\n void init(size_t thr = 2) {\n auto opts = Http::Endpoint::options()\n .threads(thr)\n .flags(Tcp::Options::InstallSignalHandler);\n httpEndpoint->init(opts);\n setupRoutes();\n }\n\n void start() {\n httpEndpoint->setHandler(router.handler());\n httpEndpoint->serveThreaded();\n }\n\n void shutdown() {\n httpEndpoint->shutdown();\n }\n\n Port getPort() const {\n return httpEndpoint->getPort();\n }\n\nprivate:\n void setupRoutes() {\n using namespace Rest;\n Routes::Get(router, \"\/read\/function1\", Routes::bind(&StatsEndpoint::doAuth, this));\n }\n\n void doAuth(const Rest::Request& \/*request*\/, Http::ResponseWriter response) {\n std::thread worker([](Http::ResponseWriter writer) {\n writer.send(Http::Code::Ok, \"1\");\n }, std::move(response));\n worker.detach();\n }\n\n std::shared_ptr<Http::Endpoint> httpEndpoint;\n Rest::Router router;\n};\n\nTEST(rest_server_test, basic_test) {\n int thr = 1;\n\n Address addr(Ipv4::any(), Port(0));\n\n StatsEndpoint stats(addr);\n\n stats.init(thr);\n stats.start();\n Port port = stats.getPort();\n\n cout << \"Cores = \" << hardware_concurrency() << endl;\n cout << \"Using \" << thr << \" threads\" << endl;\n cout << \"Port = \" << port << endl;\n\n httplib::Client client(\"localhost\", port);\n auto res = client.Get(\"\/read\/function1\");\n ASSERT_EQ(res->status, 200);\n ASSERT_EQ(res->body, \"1\");\n\n stats.shutdown();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n Copyright 2011 Joe Hermaszewski. All rights reserved.\r\n\r\n Redistribution and use in source and binary forms, with or without modification, are\r\n permitted provided that the following conditions are met:\r\n\r\n 1. Redistributions of source code must retain the above copyright notice, this list of\r\n conditions and the following disclaimer.\r\n\r\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\r\n of conditions and the following disclaimer in the documentation and\/or other materials\r\n provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\r\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Joe Hermaszewski OR\r\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\r\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n The views and conclusions contained in the software and documentation are those of the\r\n authors and should not be interpreted as representing official policies, either expressed\r\n or implied, of Joe Hermaszewski.\r\n*\/\r\n\r\n#include <iostream>\r\n#include <joemath\/joemath.hpp>\r\n#include \"timer.hpp\"\r\n\r\nusing namespace NJoeMath;\r\n\r\nconst u32 NUM_ITERATIONS = 10000000;\r\n\r\nvoid TestRandom()\r\n{\r\n NTimer::CTimer timer;\r\n\r\n std::cout << \"Random U32, \";\r\n\r\n NJoeMath::CRandom random;\r\n random.Seed( 6 );\r\n\r\n u32 acc = 0;\r\n \r\n timer.Start();\r\n\r\n for(u32 i = 0; i < NUM_ITERATIONS; ++i)\r\n acc += random.U32();\r\n\r\n timer.Stop();\r\n\r\n std::cout << double(NUM_ITERATIONS) \/ timer.GetElapsedTime() << \", \" << acc << \"\\n\";\r\n\r\n}\r\n \r\n\r\nfloat4 AddVec(float4& a, float4& b)\r\n{\r\n return operator +<float, 1,4,float, float> (a,b);\r\n}\r\n\r\n\r\nint main( int argc, char** argv )\r\n{\r\n TestRandom();\r\n \r\n NJoeMath::CRandom random;\r\n NTimer::CTimer time;\r\n time.Start();\r\n random.Seed((u32)(time.GetElapsedTime()*0xffffffff));\r\n \r\n float4 a(1.0f, 0.0f, 0.0f, 0.0f);\r\n float4 b(1.0f, 0.0f, 0.0f, 0.0f);\r\n\r\n CMatrix<float,1,2> c;\r\n CMatrix<float,1,2> d;\r\n operator \/<float, 1,2,float, float, true> (c,d);\r\n\r\n float j = a[0];\r\n \r\n j = j\/j;\r\n \r\n float3x3 r(1.0f, 0.0f, 0.0f,\r\n 0.0f, 1.0f, 0.0f,\r\n 0.0f, 0.0f, 1.0f);\r\n \r\n float fDet = r.Determinant();\r\n \r\n CMatrix<u32,4,4> q(1,0,0,0,\r\n 0,1,0,0,\r\n 0,0,1,0,\r\n 0,0,0,1);\r\n \r\n u32 uDet = q.Determinant();\r\n \r\n CMatrix<double,6,6> dd(0.0, 1.0, 0.0, 0.0, 0.0, 0.0,\r\n 2.0, 0.0, 0.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,\r\n 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);\r\n \r\n double dDet = dd.Determinant();\r\n \r\n float3 y = r[2];\r\n\r\n \r\n a = AddVec(a,b);\r\n \r\n bool myBool = is_matrix<int>::value;\r\n\r\n myBool = is_matrix<CMatrix<float, 1,2>>::value;\r\n \r\n CMatrix<u32,2,2> mat( 1, 0,\r\n 0, 1 );\r\n \r\n u32 det = mat.Determinant();\r\n\r\n return det - det;\r\n \r\n return 0;\r\n}\r\n\r\n<commit_msg>[+] matrix inversion tests in speed test<commit_after>\/*\r\n Copyright 2011 Joe Hermaszewski. All rights reserved.\r\n\r\n Redistribution and use in source and binary forms, with or without modification, are\r\n permitted provided that the following conditions are met:\r\n\r\n 1. Redistributions of source code must retain the above copyright notice, this list of\r\n conditions and the following disclaimer.\r\n\r\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\r\n of conditions and the following disclaimer in the documentation and\/or other materials\r\n provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\r\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Joe Hermaszewski OR\r\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\r\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n The views and conclusions contained in the software and documentation are those of the\r\n authors and should not be interpreted as representing official policies, either expressed\r\n or implied, of Joe Hermaszewski.\r\n*\/\r\n\r\n#include <iostream>\r\n#include <joemath\/joemath.hpp>\r\n#include \"timer.hpp\"\r\n\r\nusing namespace NJoeMath;\r\n\r\nconst u32 NUM_ITERATIONS = 10000000;\r\n\r\nvoid TestRandom()\r\n{\r\n NTimer::CTimer timer;\r\n\r\n std::cout << \"Random U32, \";\r\n\r\n NJoeMath::CRandom random;\r\n random.Seed( 6 );\r\n\r\n u32 acc = 0;\r\n \r\n timer.Start();\r\n\r\n for(u32 i = 0; i < NUM_ITERATIONS; ++i)\r\n acc += random.U32();\r\n\r\n timer.Stop();\r\n\r\n std::cout << double(NUM_ITERATIONS) \/ timer.GetElapsedTime() << \", \" << acc << \"\\n\";\r\n\r\n}\r\n \r\n\r\nfloat4 AddVec(float4& a, float4& b)\r\n{\r\n return operator +<float, 1,4,float, float> (a,b);\r\n}\r\n\r\n\r\nint main( int argc, char** argv )\r\n{\r\n TestRandom();\r\n \r\n NJoeMath::CRandom random;\r\n NTimer::CTimer time;\r\n time.Start();\r\n random.Seed((u32)(time.GetElapsedTime()*0xffffffff));\r\n \r\n float4 a(1.0f, 0.0f, 0.0f, 0.0f);\r\n float4 b(1.0f, 0.0f, 0.0f, 0.0f);\r\n\r\n CMatrix<float,1,2> c;\r\n CMatrix<float,1,2> d;\r\n operator \/<float, 1,2,float, float, true> (c,d);\r\n\r\n float j = a[0];\r\n \r\n j = j\/j;\r\n \r\n float3x3 r(0.0f, 2.0f, 2.0f,\r\n 3.0f, 3.0f, 0.0f,\r\n 1.0f, 0.0f, 1.0f);\r\n \r\n float ttt = r.Determinant();\r\n \r\n r.Invert();\r\n \r\n float fDet = r.Determinant();\r\n \r\n CMatrix<float,4,4> q(0.0f,1.0f,0.0f,0.0f,\r\n 2.0f,0.0f,0.0f,0.0f,\r\n 0.0f,0.0f,1.0f,0.0f,\r\n 0.0f,0.0f,0.0f,1.0f);\r\n \r\n q.Invert( );\r\n \r\n u32 uDet = q.Determinant();\r\n \r\n CMatrix<double,6,6> dd(0.0, 1.0, 0.0, 0.0, 0.0, 0.0,\r\n 2.0, 0.0, 0.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,\r\n 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);\r\n \r\n double dDet = dd.Determinant();\r\n \r\n dd.Invert();\r\n \r\n float3 y = r[2];\r\n\r\n \r\n a = AddVec(a,b);\r\n \r\n bool myBool = is_matrix<int>::value;\r\n\r\n myBool = is_matrix<CMatrix<float, 1,2>>::value;\r\n \r\n CMatrix<u32,2,2> mat( 1, 0,\r\n 0, 1 );\r\n \r\n u32 det = mat.Determinant();\r\n \r\n mat.Transpose();\r\n \r\n mat.Invert();\r\n \r\n CMatrix<float,1,1> s(1.0f);\r\n s.Invert();\r\n\r\n float4 v0(1.0f, 1.0f, 1.0f, 1.0f);\r\n float4 v1(1.0f, 1.0f, 1.0f, 1.0f);\r\n \r\n u32 d0 = Dot(v0, v1);\r\n \r\n return det - det;\r\n \r\n return 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/*\n * Copyright (C) 2013 Pascal Giorgi\n *\n * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>\n *\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n#ifdef HAVE_OPENMP\n#include <omp.h>\n#define GIVARO_USES_OMP\n#include <givaro\/givtimer.h>\n#define gettime realtime\ntypedef Givaro::OMPTimer myTimer;\n#else\n#include <givaro\/givtimer.h>\n#define gettime usertime\ntypedef Givaro::Timer myTimer;\n#endif\n\n\n#include <functional>\n#include <iostream>\n#include <vector>\nusing namespace std;\n#include <linbox\/ring\/modular.h>\n#include <linbox\/randiter\/random-prime.h>\n#include <linbox\/randiter\/random-fftprime.h>\n\/\/#include <linbox\/field\/unparametric.h>\n#include <givaro\/zring.h>\n#include <recint\/rint.h>\n#include <linbox\/matrix\/matrix-domain.h>\n#include <linbox\/util\/commentator.h>\n#include <linbox\/util\/timer.h>\n#include <linbox\/matrix\/polynomial-matrix.h>\n#include <linbox\/algorithms\/polynomial-matrix\/polynomial-matrix-domain.h>\n\n\n\nusing namespace LinBox;\n\n\n\n\ntemplate <typename Rand, typename Vect>\nvoid randomVect (Rand& r, Vect& v) {\n\tsize_t s = v.size();\t\t\t\t \n\tfor (size_t i = 0; i < s; ++i)\n\t\tr.random(v[i]); \n}\n\ntemplate <typename Rand, typename Mat>\nvoid randomMat (Rand& r, Mat& m) {\n\tfor (size_t i = 0; i < m.rowdim(); ++i)\n\t\tfor (size_t j = 0; j < m.coldim(); ++j)\n\t\t\tr.random(m.refEntry(i,j));\n}\n\n\ntemplate<typename Field, typename Rand>\nvoid randomMatPol(Rand& r, PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field>& A){\n\tfor(size_t i=0;i<A.size();i++)\n\t\trandomMat(r, A[i]); \t\n}\n\ntemplate<typename Field, typename Rand>\nvoid randomMatPol(Rand& r, PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field>& A){\n\tfor(size_t i=0;i<A.rowdim()*A.coldim();i++)\n\t\trandomVect(r, A(i));\n}\n\n\n\t\ntemplate<typename MatPol>\nbool operator==(const MatPol& A, const MatPol& B){\n\tMatrixDomain<typename MatPol::Field> MD(A.field());\n\tif (A.size()!=B.size()|| A.rowdim()!= B.rowdim() || A.coldim()!=B.coldim())\n\t\treturn false;\n\tsize_t i=0;\n\twhile (i<A.size() && MD.areEqual(A[i],B[i]))\n\t\ti++;\n\n\tif (i<A.size() && A.rowdim()<10 && A.coldim()<10){\n\t\tcout<<\"first:\"<<endl<<A<<endl;\n\t\tcout<<\"second:\"<<endl<<B<<endl;\n\t}\n\n\treturn i==A.size();\n}\n\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_mul(const Field& fld, RandIter& Gen, size_t n, size_t d) { \n\tMatrixP A(fld,n,n,d),B(fld,n,n,d),C(fld,n,n,2*d-1);\n\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,B);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.mul(C,A,B);\n\treturn check_mul(C,A,B,C.size());\n}\n\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_midp(const Field& fld, RandIter& Gen, size_t n, size_t d) {\n\tMatrixP A(fld,n,n,d),C(fld,n,n,2*d-1);\t\n\tMatrixP B(fld,n,n,d);\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,C);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.midproduct(B,A,C) ;\n\treturn check_midproduct(B,A,C);\n}\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_midpgen(const Field& fld, RandIter& Gen, size_t n, size_t d) {\n\tsize_t d0,d1; \/\/ n0 must be in [d, 2d-1[\n\n\td1=d\/2;\n\td0=d-d1;\n\t\n\tMatrixP A(fld,n,n,d0+1),B(fld,n,n,d1),C(fld,n,n,d);\n\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,C);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.midproductgen(B,A,C,true,d0+1,d) ;\n\treturn check_midproduct(B,A,C,true,d0+1,d);\n}\n\n\ntemplate<typename Field>\nbool launchTest(const Field& F, size_t n, long b, long d, long seed){\n\tbool ok=true;\n\ttypename Field::RandIter G(F,b,seed);\n\ttypedef PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field> MatrixP;\n\tstd::cerr<<\"Polynomial matrix (polfirst) testing over \";F.write(std::cerr)<<std::endl;\n\tok&=check_matpol_mul<MatrixP> (F,G,n,d);\n\tok&=check_matpol_midp<MatrixP> (F,G,n,d);\n\tok&=check_matpol_midpgen<MatrixP> (F,G,n,d);\n\n\t\/\/typedef PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field> PMatrix;\n\t\/\/ std::cerr<<\"Polynomial matrix (matfirst) testing:\\n\";F.write(std::cerr)<<std::endl;\n\t\/\/ check_matpol_mul<PMatrix> (F,G,n,d);\n\t\/\/ check_matpol_midp<PMatrix> (F,G,n,d);\n\treturn ok;\n}\n\n\nbool runTest(uint64_t n, uint64_t d, long seed){\n\n\tbool ok=true;\n\t\/\/ fourier prime < 2^(53--log(n))\/2\n\t{\n\t\tsize_t bits= (53-integer(n).bitsize())\/2;\n\t\tRandomFFTPrime Rd(1<<bits,seed);\n\t\tinteger p = Rd.randomPrime(integer(d).bitsize()+1);\n\t\t\n\t\tGivaro::Modular<double> F((int32_t)p);\n\t\tok&=launchTest (F,n,bits,d,seed);\n\t\t\n\t}\n\t\n\t\/\/ normal prime < 2^(53--log(n))\/2\n\t{\n\t\tsize_t bits= (53-integer(n).bitsize())\/2;;\n\t\tRandomPrimeIter Rd(bits,seed);\n\t\tinteger p;\n\t\tRd.random(p);\n\n\t\tGivaro::Modular<double> F((int32_t)p);\n\t\tok&=launchTest (F,n,bits,d,seed);\n\t}\n\t\n\t\/\/ multi-precision prime\n\t{\n\t\tsize_t bits=114;\n\t\tRandomPrimeIter Rd(bits,seed);\n\t\tinteger p= Rd.random();\n\n\t\tGivaro::Modular<integer> F1(p);\t\t\t\n\t\tok&=launchTest (F1,n,bits,d,seed);\n\t\tGivaro::Modular<RecInt::ruint128,RecInt::ruint256> F2(p);\n\t\tok&=launchTest (F2,n,bits,d,seed);\n\t\n\t}\n\t\/\/ over the integer\n\t{\n\t\tGivaro::ZRing<integer> F;\n\t\tok&=launchTest (F,n,128,d,seed);\n\n\t}\t\n\treturn ok;\n}\n\nint main(int argc, char** argv){\n\tstatic size_t n = 16; \/\/ matrix dimension\n\tstatic size_t d = 512; \/\/ polynomial size\n\tstatic long seed = time(NULL);\n\t\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN.\", TYPE_INT, &n },\n\t\t{ 'd', \"-d D\", \"Set degree of test matrices to D.\", TYPE_INT, &d },\n\t\t{ 's', \"-s s\", \"Set the random seed to a specific value\", TYPE_INT, &seed},\n\t\tEND_OF_ARGUMENTS\n\t};\n\tparseArguments (argc, argv, args);\n\n\treturn (runTest(n,d,seed)? 0: -1);\n} \n \n\n\n\n<commit_msg>debugging<commit_after>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/*\n * Copyright (C) 2013 Pascal Giorgi\n *\n * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>\n *\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n#ifdef HAVE_OPENMP\n#include <omp.h>\n#define GIVARO_USES_OMP\n#include <givaro\/givtimer.h>\n#define gettime realtime\ntypedef Givaro::OMPTimer myTimer;\n#else\n#include <givaro\/givtimer.h>\n#define gettime usertime\ntypedef Givaro::Timer myTimer;\n#endif\n\n\n#include <functional>\n#include <iostream>\n#include <vector>\nusing namespace std;\n#include <linbox\/ring\/modular.h>\n#include <linbox\/randiter\/random-prime.h>\n#include <linbox\/randiter\/random-fftprime.h>\n\/\/#include <linbox\/field\/unparametric.h>\n#include <givaro\/zring.h>\n#include <recint\/rint.h>\n#include <linbox\/matrix\/matrix-domain.h>\n#include <linbox\/util\/commentator.h>\n#include <linbox\/util\/timer.h>\n#include <linbox\/matrix\/polynomial-matrix.h>\n#include <linbox\/algorithms\/polynomial-matrix\/polynomial-matrix-domain.h>\n\n\n\nusing namespace LinBox;\n\n\n\n\ntemplate <typename Rand, typename Vect>\nvoid randomVect (Rand& r, Vect& v) {\n\tsize_t s = v.size();\t\t\t\t \n\tfor (size_t i = 0; i < s; ++i)\n\t\tr.random(v[i]); \n}\n\ntemplate <typename Rand, typename Mat>\nvoid randomMat (Rand& r, Mat& m) {\n\tfor (size_t i = 0; i < m.rowdim(); ++i)\n\t\tfor (size_t j = 0; j < m.coldim(); ++j)\n\t\t\tr.random(m.refEntry(i,j));\n}\n\n\ntemplate<typename Field, typename Rand>\nvoid randomMatPol(Rand& r, PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field>& A){\n\tfor(size_t i=0;i<A.size();i++)\n\t\trandomMat(r, A[i]); \t\n}\n\ntemplate<typename Field, typename Rand>\nvoid randomMatPol(Rand& r, PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field>& A){\n\tfor(size_t i=0;i<A.rowdim()*A.coldim();i++)\n\t\trandomVect(r, A(i));\n}\n\n\n\t\ntemplate<typename MatPol>\nbool operator==(const MatPol& A, const MatPol& B){\n\tMatrixDomain<typename MatPol::Field> MD(A.field());\n\tif (A.size()!=B.size()|| A.rowdim()!= B.rowdim() || A.coldim()!=B.coldim())\n\t\treturn false;\n\tsize_t i=0;\n\twhile (i<A.size() && MD.areEqual(A[i],B[i]))\n\t\ti++;\n\n\tif (i<A.size() && A.rowdim()<10 && A.coldim()<10){\n\t\tcout<<\"first:\"<<endl<<A<<endl;\n\t\tcout<<\"second:\"<<endl<<B<<endl;\n\t}\n\n\treturn i==A.size();\n}\n\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_mul(const Field& fld, RandIter& Gen, size_t n, size_t d) { \n\tMatrixP A(fld,n,n,d),B(fld,n,n,d),C(fld,n,n,2*d-1);\n\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,B);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.mul(C,A,B);\n\treturn check_mul(C,A,B,C.size());\n}\n\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_midp(const Field& fld, RandIter& Gen, size_t n, size_t d) {\n\tMatrixP A(fld,n,n,d),C(fld,n,n,2*d-1);\t\n\tMatrixP B(fld,n,n,d);\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,C);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.midproduct(B,A,C) ;\n\treturn check_midproduct(B,A,C);\n}\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool check_matpol_midpgen(const Field& fld, RandIter& Gen, size_t n, size_t d) {\n\tsize_t d0,d1; \/\/ n0 must be in [d, 2d-1[\n\n\td1=d\/2;\n\td0=d-d1;\n\t\n\tMatrixP A(fld,n,n,d0+1),B(fld,n,n,d1),C(fld,n,n,d);\n\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,C);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.midproductgen(B,A,C,true,d0+1,d) ;\n\treturn check_midproduct(B,A,C,true,d0+1,d);\n}\n\n\ntemplate<typename MatrixP, typename Field, typename RandIter>\nbool debug_midpgen_dlp(const Field& fld, RandIter& Gen) {\n\tsize_t d0,d1;\n\tsize_t n0,n1;\n\n\tn0=84463;\n\tn1=168923;\n\t\n\t\t\n\tMatrixP A(fld,48,48,59061),B(fld,48,32,84461),C(fld,48,32,168923);\n\n\t\/\/ Generate random matrix of polynomial\n\trandomMatPol(Gen,A);\n\trandomMatPol(Gen,C);\n\ttypedef PolynomialMatrixDomain<Field> PolMatDom;\n\tPolMatDom PMD(fld);\n\tPMD.midproductgen(B,A,C,true,n0,n1) ;\n\treturn check_midproduct(B,A,C,true,n0,n1);\n}\n\n\n\ntemplate<typename Field>\nbool launchTest(const Field& F, size_t n, long b, long d, long seed){\n\tbool ok=true;\n\ttypename Field::RandIter G(F,b,seed);\n\ttypedef PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field> MatrixP;\n\t\/\/std::cerr<<\"Polynomial matrix (polfirst) testing over \";F.write(std::cerr)<<std::endl;\n\t\/\/ok&=check_matpol_mul<MatrixP> (F,G,n,d);\n\t\/\/ok&=check_matpol_midp<MatrixP> (F,G,n,d);\n\t\/\/ok&=check_matpol_midpgen<MatrixP> (F,G,n,d);\n\n\t\/\/typedef PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field> PMatrix;\n\t\/\/ std::cerr<<\"Polynomial matrix (matfirst) testing:\\n\";F.write(std::cerr)<<std::endl;\n\t\/\/ check_matpol_mul<PMatrix> (F,G,n,d);\n\t\/\/ check_matpol_midp<PMatrix> (F,G,n,d);\n\n\tstd::cerr<<\"Debugging midpgen for DLP over \";F.write(std::cerr)<<std::endl;\n\tdebug_midpgen_dlp<MatrixP>(F,G);\n\treturn ok;\n}\n\n\nbool runTest(uint64_t n, uint64_t d, long seed){\n\n\tbool ok=true;\n\t\/\/ fourier prime < 2^(53--log(n))\/2\n\t{\n\t\tsize_t bits= (53-integer(n).bitsize())\/2;\n\t\tRandomFFTPrime Rd(1<<bits,seed);\n\t\tinteger p = Rd.randomPrime(integer(d).bitsize()+1);\n\t\t\n\t\tGivaro::Modular<double> F((int32_t)p);\n\t\tok&=launchTest (F,n,bits,d,seed);\n\t\t\n\t}\n\t\n\t\/\/ normal prime < 2^(53--log(n))\/2\n\t{\n\t\tsize_t bits= (53-integer(n).bitsize())\/2;;\n\t\tRandomPrimeIter Rd(bits,seed);\n\t\tinteger p;\n\t\tRd.random(p);\n\n\t\tGivaro::Modular<double> F((int32_t)p);\n\t\tok&=launchTest (F,n,bits,d,seed);\n\t}\n\t\n\t\/\/ \/\/ multi-precision prime\n\t\/\/ {\n\t\/\/ \tsize_t bits=114;\n\t\/\/ \tRandomPrimeIter Rd(bits,seed);\n\t\/\/ \tinteger p= Rd.random();\n\n\t\/\/ \tGivaro::Modular<integer> F1(p);\t\t\t\n\t\/\/ \tok&=launchTest (F1,n,bits,d,seed);\n\t\/\/ \tGivaro::Modular<RecInt::ruint128,RecInt::ruint256> F2(p);\n\t\/\/ \tok&=launchTest (F2,n,bits,d,seed);\n\t\n\t\/\/ }\n\t\/\/ \/\/ over the integer\n\t\/\/ {\n\t\/\/ \tGivaro::ZRing<integer> F;\n\t\/\/ \tok&=launchTest (F,n,128,d,seed);\n\n\t\/\/ }\t\n\treturn ok;\n}\n\nint main(int argc, char** argv){\n\tstatic size_t n = 16; \/\/ matrix dimension\n\tstatic size_t d = 512; \/\/ polynomial size\n\tstatic long seed = time(NULL);\n\t\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN.\", TYPE_INT, &n },\n\t\t{ 'd', \"-d D\", \"Set degree of test matrices to D.\", TYPE_INT, &d },\n\t\t{ 's', \"-s s\", \"Set the random seed to a specific value\", TYPE_INT, &seed},\n\t\tEND_OF_ARGUMENTS\n\t};\n\tparseArguments (argc, argv, args);\n\n\treturn (runTest(n,d,seed)? 0: -1);\n} \n \n\n\n\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE TEST_TRAINER_IO\n\/*\n * There are two different macros to test an optimizer:\n * - DYNET_TRAINER_IO_TEST_CASE:\n * makes two updates of a model. Parameters of the model and the optimizer\n * are save after the first update. Then, a new model and a new optimizer\n * are created and populated with the saved data.\n * The two models must be equal after updating the second one.\n * - DYNET_TRAINER_IO_PARAM_TEST_CASE:\n * this is a save\/load test for a given attribute of the optimizer\n *\n * TODO: EGTrainer is no fully tested because the update does not change\n * the model.\n *\/\n\n#include <fstream>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/version.hpp>\n\n#include <dynet\/dynet.h>\n#include <dynet\/expr.h>\n#include <dynet\/training.h>\n#include <dynet\/io.h>\n\n#include \"test.h\"\n\nusing namespace dynet;\nusing namespace std;\n\nstruct TrainerIOTest {\n TrainerIOTest() {\n \/\/ initialize if necessary\n if(default_device == nullptr) {\n for (auto x : {\"TrainerTest\", \"--dynet-mem\", \"10\"}) {\n av.push_back(strdup(x));\n }\n ADD_EXTRA_ARGUMENTS(av)\n char **argv = &av[0];\n int argc = av.size();\n dynet::initialize(argc, argv);\n }\n ones_vals = {1.f,1.f,1.f};\n param_vals = {0.5f,0.1f,0.4f};\n }\n\n ~TrainerIOTest() {\n for (auto x : av) free(x);\n }\n\n template <class T>\n std::string print_vec(const std::vector<T> vec) {\n ostringstream oss;\n if(vec.size()) oss << vec[0];\n for(size_t i = 1; i < vec.size(); i++)\n oss << ' ' << vec[i];\n return oss.str();\n }\n\n Parameter build_pc(ParameterCollection& pc)\n {\n auto p = pc.add_parameters({3});\n TensorTools::set_elements(p.get_storage().values, param_vals);\n return p;\n }\n\n Expression build_loss(ComputationGraph& cg, Parameter& param)\n {\n auto x = parameter(cg, param);\n auto y = input(cg, {3}, ones_vals);\n return dot_product(x, y);\n }\n\n dynet::real optimize(Parameter& param, Trainer& trainer)\n {\n dynet::ComputationGraph cg;\n auto z = build_loss(cg, param);\n auto loss = as_scalar(cg.forward(z));\n cg.backward(z);\n trainer.update();\n\n return loss;\n }\n\n std::vector<float> ones_vals, param_vals, param2_vals;\n std::vector<char*> av;\n};\n\nBOOST_FIXTURE_TEST_SUITE(trainer_io_test, TrainerIOTest);\n\n#define DYNET_TRAINER_IO_TEST_CASE(name, TRAINER_TYPE) \\\nBOOST_AUTO_TEST_CASE(name) { \\\n \/* build model *\/ \\\n ParameterCollection m; \\\n TRAINER_TYPE trainer(m); \\\n auto p = build_pc(m); \\\n \/* do one update and save params *\/ \\\n float loss1; \\\n loss1 = optimize(p, trainer); \\\n { \\\n dynet::TextFileSaver s(\"test.model\"); \\\n s.save(m); \\\n std::ofstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer.save(f); \\\n f.close(); \\\n } \\\n \/* do a second update and check that the loss where different *\/ \\\n \/* i.e. that the params of the model are actually different *\/ \\\n auto loss2 = optimize(p, trainer); \\\n BOOST_CHECK(!(abs(loss1 - loss2)\/abs(loss1) <= TOL && abs(loss1 - loss2)\/abs(loss2) <= TOL)); \\\n \/*create a new model, load the save state+trainer params, *\/ \\\n \/* do one update and check that everything match *\/ \\\n ParameterCollection m2; \\\n TRAINER_TYPE trainer2(m2); \\\n auto p2 = build_pc(m2); \\\n { \\\n dynet::TextFileLoader s(\"test.model\"); \\\n s.populate(m2); \\\n std::ifstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer2.populate(f); \\\n f.close(); \\\n } \\\n auto loss3 = optimize(p2, trainer2); \\\n DYNET_CHECK_EQUAL(loss2, loss3); \\\n DYNET_CHECK_EQUAL(m2, m); \\\n} \\\n\n#define DYNET_TRAINER_IO_PARAM_TEST_CASE(name, TRAINER_TYPE, SP_NAME) \\\nBOOST_AUTO_TEST_CASE(name) \\\n{ \\\n class Trainer : public TRAINER_TYPE \\\n { \\\n public: \\\n using TRAINER_TYPE::SP_NAME; \\\n explicit Trainer(ParameterCollection& m) : \\\n TRAINER_TYPE::TRAINER_TYPE(m) \\\n {} \\\n }; \\\n \/* build model *\/ \\\n ParameterCollection m; \\\n Trainer trainer(m); \\\n auto p = build_pc(m); \\\n \/* do one update and save params *\/ \\\n optimize(p, trainer); \\\n { \\\n std::ofstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer.save(f); \\\n f.close(); \\\n } \\\n \/*create a new model, load the save state params, *\/ \\\n ParameterCollection m2; \\\n Trainer trainer2(m2); \\\n auto p2 = build_pc(m2); \\\n { \\\n std::ifstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer2.populate(f); \\\n f.close(); \\\n } \\\n DYNET_CHECK_EQUAL(trainer2.SP_NAME, trainer.SP_NAME); \\\n} \\\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(momentum_sgd_io_param_vp, MomentumSGDTrainer, vp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(momentum_sgd_io_param_vlp, MomentumSGDTrainer, vlp)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adagrad_io_param_vp, AdagradTrainer, vp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adagrad_io_param_vlp, AdagradTrainer, vlp)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hg, AdadeltaTrainer, hg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hlg, AdadeltaTrainer, hlg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hd, AdadeltaTrainer, hd)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hld, AdadeltaTrainer, hld)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(rmsprop_io_param_hmsg, RMSPropTrainer, hmsg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(rmsprop_io_param_hlmsg, RMSPropTrainer, hlmsg)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_m, AdamTrainer, m)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_lm, AdamTrainer, lm)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_v, AdamTrainer, v)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_lv, AdamTrainer, lv)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_m, AmsgradTrainer, m)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lm, AmsgradTrainer, lm)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_v, AmsgradTrainer, v)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lv, AmsgradTrainer, lv)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_vhat, AmsgradTrainer, vhat)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lvhat, AmsgradTrainer, lvhat)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_hp, EGTrainer, hp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_hlp, EGTrainer, hlp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_zeg, EGTrainer, zeg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_meg, EGTrainer, meg)\n\nDYNET_TRAINER_IO_TEST_CASE(simple_sgd_io, SimpleSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(cyclical_sgd_io, CyclicalSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(momentum_sgd_io, MomentumSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adagrad_io, AdagradTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adadelta_io, AdadeltaTrainer)\nDYNET_TRAINER_IO_TEST_CASE(rmsprop_io, RMSPropTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adam_io, AdamTrainer)\nDYNET_TRAINER_IO_TEST_CASE(amsgrad_io, AmsgradTrainer)\n\/\/DYNET_TRAINER_IO_TEST_CASE(eg_io, EGTrainer)\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Remove useless method+attribute in the trainers-io test<commit_after>#define BOOST_TEST_MODULE TEST_TRAINER_IO\n\/*\n * There are two different macros to test an optimizer:\n * - DYNET_TRAINER_IO_TEST_CASE:\n * makes two updates of a model. Parameters of the model and the optimizer\n * are save after the first update. Then, a new model and a new optimizer\n * are created and populated with the saved data.\n * The two models must be equal after updating the second one.\n * - DYNET_TRAINER_IO_PARAM_TEST_CASE:\n * this is a save\/load test for a given attribute of the optimizer\n *\n * TODO: EGTrainer is no fully tested because the update does not change\n * the model.\n *\/\n\n#include <fstream>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/version.hpp>\n\n#include <dynet\/dynet.h>\n#include <dynet\/expr.h>\n#include <dynet\/training.h>\n#include <dynet\/io.h>\n\n#include \"test.h\"\n\nusing namespace dynet;\nusing namespace std;\n\nstruct TrainerIOTest {\n TrainerIOTest() {\n \/\/ initialize if necessary\n if(default_device == nullptr) {\n for (auto x : {\"TrainerTest\", \"--dynet-mem\", \"10\"}) {\n av.push_back(strdup(x));\n }\n ADD_EXTRA_ARGUMENTS(av)\n char **argv = &av[0];\n int argc = av.size();\n dynet::initialize(argc, argv);\n }\n ones_vals = {1.f,1.f,1.f};\n param_vals = {0.5f,0.1f,0.4f};\n }\n\n ~TrainerIOTest() {\n for (auto x : av) free(x);\n }\n\n Parameter build_pc(ParameterCollection& pc)\n {\n auto p = pc.add_parameters({3});\n TensorTools::set_elements(p.get_storage().values, param_vals);\n return p;\n }\n\n Expression build_loss(ComputationGraph& cg, Parameter& param)\n {\n auto x = parameter(cg, param);\n auto y = input(cg, {3}, ones_vals);\n return dot_product(x, y);\n }\n\n dynet::real optimize(Parameter& param, Trainer& trainer)\n {\n dynet::ComputationGraph cg;\n auto z = build_loss(cg, param);\n auto loss = as_scalar(cg.forward(z));\n cg.backward(z);\n trainer.update();\n\n return loss;\n }\n\n std::vector<float> ones_vals, param_vals;\n std::vector<char*> av;\n};\n\nBOOST_FIXTURE_TEST_SUITE(trainer_io_test, TrainerIOTest);\n\n#define DYNET_TRAINER_IO_TEST_CASE(name, TRAINER_TYPE) \\\nBOOST_AUTO_TEST_CASE(name) { \\\n \/* build model *\/ \\\n ParameterCollection m; \\\n TRAINER_TYPE trainer(m); \\\n auto p = build_pc(m); \\\n \/* do one update and save params *\/ \\\n float loss1; \\\n loss1 = optimize(p, trainer); \\\n { \\\n dynet::TextFileSaver s(\"test.model\"); \\\n s.save(m); \\\n std::ofstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer.save(f); \\\n f.close(); \\\n } \\\n \/* do a second update and check that the loss where different *\/ \\\n \/* i.e. that the params of the model are actually different *\/ \\\n auto loss2 = optimize(p, trainer); \\\n BOOST_CHECK(!(abs(loss1 - loss2)\/abs(loss1) <= TOL && abs(loss1 - loss2)\/abs(loss2) <= TOL)); \\\n \/*create a new model, load the save state+trainer params, *\/ \\\n \/* do one update and check that everything match *\/ \\\n ParameterCollection m2; \\\n TRAINER_TYPE trainer2(m2); \\\n auto p2 = build_pc(m2); \\\n { \\\n dynet::TextFileLoader s(\"test.model\"); \\\n s.populate(m2); \\\n std::ifstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer2.populate(f); \\\n f.close(); \\\n } \\\n auto loss3 = optimize(p2, trainer2); \\\n DYNET_CHECK_EQUAL(loss2, loss3); \\\n DYNET_CHECK_EQUAL(m2, m); \\\n} \\\n\n#define DYNET_TRAINER_IO_PARAM_TEST_CASE(name, TRAINER_TYPE, SP_NAME) \\\nBOOST_AUTO_TEST_CASE(name) \\\n{ \\\n class Trainer : public TRAINER_TYPE \\\n { \\\n public: \\\n using TRAINER_TYPE::SP_NAME; \\\n explicit Trainer(ParameterCollection& m) : \\\n TRAINER_TYPE::TRAINER_TYPE(m) \\\n {} \\\n }; \\\n \/* build model *\/ \\\n ParameterCollection m; \\\n Trainer trainer(m); \\\n auto p = build_pc(m); \\\n \/* do one update and save params *\/ \\\n optimize(p, trainer); \\\n { \\\n std::ofstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer.save(f); \\\n f.close(); \\\n } \\\n \/*create a new model, load the save state params, *\/ \\\n ParameterCollection m2; \\\n Trainer trainer2(m2); \\\n auto p2 = build_pc(m2); \\\n { \\\n std::ifstream f; \\\n f.open(\"test.optimizer\"); \\\n trainer2.populate(f); \\\n f.close(); \\\n } \\\n DYNET_CHECK_EQUAL(trainer2.SP_NAME, trainer.SP_NAME); \\\n} \\\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(momentum_sgd_io_param_vp, MomentumSGDTrainer, vp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(momentum_sgd_io_param_vlp, MomentumSGDTrainer, vlp)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adagrad_io_param_vp, AdagradTrainer, vp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adagrad_io_param_vlp, AdagradTrainer, vlp)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hg, AdadeltaTrainer, hg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hlg, AdadeltaTrainer, hlg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hd, AdadeltaTrainer, hd)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adadelta_io_param_hld, AdadeltaTrainer, hld)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(rmsprop_io_param_hmsg, RMSPropTrainer, hmsg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(rmsprop_io_param_hlmsg, RMSPropTrainer, hlmsg)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_m, AdamTrainer, m)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_lm, AdamTrainer, lm)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_v, AdamTrainer, v)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(adam_io_param_lv, AdamTrainer, lv)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_m, AmsgradTrainer, m)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lm, AmsgradTrainer, lm)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_v, AmsgradTrainer, v)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lv, AmsgradTrainer, lv)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_vhat, AmsgradTrainer, vhat)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(amsgrad_io_param_lvhat, AmsgradTrainer, lvhat)\n\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_hp, EGTrainer, hp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_hlp, EGTrainer, hlp)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_zeg, EGTrainer, zeg)\nDYNET_TRAINER_IO_PARAM_TEST_CASE(eg_io_param_meg, EGTrainer, meg)\n\nDYNET_TRAINER_IO_TEST_CASE(simple_sgd_io, SimpleSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(cyclical_sgd_io, CyclicalSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(momentum_sgd_io, MomentumSGDTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adagrad_io, AdagradTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adadelta_io, AdadeltaTrainer)\nDYNET_TRAINER_IO_TEST_CASE(rmsprop_io, RMSPropTrainer)\nDYNET_TRAINER_IO_TEST_CASE(adam_io, AdamTrainer)\nDYNET_TRAINER_IO_TEST_CASE(amsgrad_io, AmsgradTrainer)\n\/\/DYNET_TRAINER_IO_TEST_CASE(eg_io, EGTrainer)\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\n#include <assert.h>\n#include <thread>\n#include <boost\/atomic.hpp>\n\n#include \"LinkedList.hpp\"\n\nvoid test0() {\n\tLinkedList<int> l;\n\tassert(l.empty());\n\tl._checkSanity();\n\n\tauto item = l.push_back();\n\titem->value = 42;\n\titem = NULL;\n\tl._checkSanity();\n\tassert(!l.empty());\n\tassert(l.size() == 1);\n\n\tauto ret = l.pop_front();\n\tassert(ret);\n\tassert(ret->value == 42);\n\tret = NULL;\n\n\tassert(l.empty());\n\tassert(l.size() == 0);\n\tl._checkSanity();\n}\n\n\nvoid test1() {\n\tLinkedList<int> l;\n\tl._checkSanity();\n\n\tfor(int i = 0; i < 100; ++i) {\n\t\tauto item = l.push_back();\n\t\tl._checkSanity();\n\t\titem->value = i;\n\t}\n\n\tassert(!l.empty());\n\tassert(l.size() == 100);\n\n\tfor(int i = 0; i < 100; ++i) {\n\t\tauto ret = l.pop_front();\n\t\tl._checkSanity();\n\t\tassert(ret);\n\t\tassert(ret->value == i);\n\t}\n\n\tassert(l.empty());\n}\n\n\nvoid test2() {\n\tLinkedList<int> l;\n\tl._checkSanity();\n\n\tauto producer = [&l](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tl.push_back(item);\n\t\t}\n\t};\n\n\tauto consumer = [&l](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\twhile(l.empty()) {} \/\/ wait for entry\n\t\t\tauto ret = l.pop_front();\n\t\t\tassert(ret);\n\t\t\tassert(ret->value == i);\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tstd::thread t1(producer), t2(consumer);\n\t\tt1.join();\n\t\tt2.join();\n\t\tassert(l.empty());\n\t\tl._checkSanity();\n\t}\n}\n\n\nvoid test3() {\n\tLinkedList<int> l;\n\tboost::atomic<int> state;\n\n\tauto producer = [&l, &state](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\tif(i == 50) state++;\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tl.push_back(item);\n\t\t}\n\t\tstate++;\n\t};\n\n\tauto consumer = [&l, &state](){\n\t\twhile(state == 0) {}\n\t\tfor(int i = 0; i < 40; ++i) {\n\t\t\twhile(l.empty()); \/\/ wait for entry\n\t\t\tauto ret = l.pop_front();\n\t\t\tassert(ret);\n\t\t\tassert(ret->value == i);\n\t\t}\n\t\tstate++;\n\t};\n\n\tauto reader = [&l, &state]() {\n\t\twhile(state < 3) {\n\t\t\tif(state == 0) continue;\n\t\t\tint first = -1;\n\t\t\tint old = -1;\n\t\t\tint count = 0;\n\t\t\tfor(auto v : l) {\n\t\t\t\tassert(v >= 0);\n\t\t\t\tif(first < 0) first = v;\n\t\t\t\tif(old >= 0) assert(old < v);\n\t\t\t\told = v;\n\t\t\t\t++count;\n\t\t\t}\n\t\t\tassert(count > 10);\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tstate = 0;\n\n\t\tstd::thread t1(producer), t2(consumer), t3(reader);\n\t\tt1.join();\n\t\tt2.join();\n\t\tt3.join();\n\n\t\tl._checkSanity();\n\t\tl.clear();\n\t}\n}\n\nvoid test4() {\n\tLinkedList<int> l;\n\n\tauto producer = [&l](){\n\t\tfor(int i = 3; i <= 100; ++i) {\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tif(i < 50)\n\t\t\t\tl.push_back(item);\n\t\t\telse\n\t\t\t\tl.push_front(item);\n\t\t}\n\t};\n\n\tauto reader = [&l]() {\n\t\tint endCount = 0;\n\t\twhile(true) {\n\t\t\tint old = -1;\n\t\t\tint m = 0;\n\t\t\tint count = 0;\n\t\t\tfor(auto v : l) {\n\t\t\t\tassert(v >= 1);\n\t\t\t\tif(old >= 50 && v == 1) {}\n\t\t\t\telse if(old >= 0) assert(old + 1 == v);\n\t\t\t\told = v;\n\t\t\t\tif(v > m) m = v;\n\t\t\t\t++count;\n\t\t\t}\n\t\t\tassert(count >= 2);\n\t\t\tassert(count <= 100);\n\t\t\tassert(count == m);\n\t\t\tif(count < 100) assert(endCount == 0);\n\t\t\tif(count == 100) endCount++;\n\t\t\tif(endCount >= 10) break;\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tl.push_back()->value = 1;\n\t\tl.push_back()->value = 2;\n\n\t\tstd::thread t1(producer), t3(reader);\n\t\tt1.join();\n\t\tt3.join();\n\n\t\tl._checkSanity();\n\t\tl.clear();\n\t}\n}\n\nint main() {\n\ttest0();\n\ttest1();\n\ttest2();\n\ttest3();\n\ttest4();\n}\n<commit_msg>small fix<commit_after>\n#include <assert.h>\n#include <thread>\n#include <boost\/atomic.hpp>\n\n#include \"LinkedList.hpp\"\n\nvoid test0() {\n\tLinkedList<int> l;\n\tassert(l.empty());\n\tl._checkSanity();\n\n\tauto item = l.push_back();\n\titem->value = 42;\n\titem = NULL;\n\tl._checkSanity();\n\tassert(!l.empty());\n\tassert(l.size() == 1);\n\n\tauto ret = l.pop_front();\n\tassert(ret);\n\tassert(ret->value == 42);\n\tret = NULL;\n\n\tassert(l.empty());\n\tassert(l.size() == 0);\n\tl._checkSanity();\n}\n\n\nvoid test1() {\n\tLinkedList<int> l;\n\tl._checkSanity();\n\n\tfor(int i = 0; i < 100; ++i) {\n\t\tauto item = l.push_back();\n\t\tl._checkSanity();\n\t\titem->value = i;\n\t}\n\n\tassert(!l.empty());\n\tassert(l.size() == 100);\n\n\tfor(int i = 0; i < 100; ++i) {\n\t\tauto ret = l.pop_front();\n\t\tl._checkSanity();\n\t\tassert(ret);\n\t\tassert(ret->value == i);\n\t}\n\n\tassert(l.empty());\n}\n\n\nvoid test2() {\n\tLinkedList<int> l;\n\tl._checkSanity();\n\n\tauto producer = [&l](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tl.push_back(item);\n\t\t}\n\t};\n\n\tauto consumer = [&l](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\twhile(l.empty()) {} \/\/ wait for entry\n\t\t\tauto ret = l.pop_front();\n\t\t\tassert(ret);\n\t\t\tassert(ret->value == i);\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tstd::thread t1(producer), t2(consumer);\n\t\tt1.join();\n\t\tt2.join();\n\t\tassert(l.empty());\n\t\tl._checkSanity();\n\t}\n}\n\n\nvoid test3() {\n\tLinkedList<int> l;\n\tboost::atomic<int> state;\n\n\tauto producer = [&l, &state](){\n\t\tfor(int i = 0; i < 100; ++i) {\n\t\t\tif(i == 50) state++;\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tl.push_back(item);\n\t\t}\n\t\tstate++;\n\t};\n\n\tauto consumer = [&l, &state](){\n\t\twhile(state == 0) {}\n\t\tfor(int i = 0; i < 40; ++i) {\n\t\t\twhile(l.empty()); \/\/ wait for entry\n\t\t\tauto ret = l.pop_front();\n\t\t\tassert(ret);\n\t\t\tassert(ret->value == i);\n\t\t}\n\t\tstate++;\n\t};\n\n\tauto reader = [&l, &state]() {\n\t\twhile(state < 3) {\n\t\t\tif(state == 0) continue;\n\t\t\tint first = -1;\n\t\t\tint old = -1;\n\t\t\tint count = 0;\n\t\t\tfor(auto v : l) {\n\t\t\t\tassert(v >= 0);\n\t\t\t\tif(first < 0) first = v;\n\t\t\t\tif(old >= 0) assert(old < v);\n\t\t\t\told = v;\n\t\t\t\t++count;\n\t\t\t}\n\t\t\tassert(count > 10);\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tstate = 0;\n\n\t\tstd::thread t1(producer), t2(consumer), t3(reader);\n\t\tt1.join();\n\t\tt2.join();\n\t\tt3.join();\n\n\t\tl._checkSanity();\n\t\tl.clear();\n\t}\n}\n\nvoid test4() {\n\tLinkedList<int> l;\n\n\tauto producer = [&l](){\n\t\tfor(int i = 3; i <= 100; ++i) {\n\t\t\tLinkedList<int>::ItemPtr item(new LinkedList<int>::Item);\n\t\t\titem->value = i;\n\t\t\tif(i < 50)\n\t\t\t\tl.push_back(item);\n\t\t\telse\n\t\t\t\tl.push_front(item);\n\t\t}\n\t};\n\n\tauto reader = [&l]() {\n\t\tint endCount = 0;\n\t\twhile(true) {\n\t\t\tint old = -1;\n\t\t\tint m = 0;\n\t\t\tint count = 0;\n\t\t\tfor(auto v : l) {\n\t\t\t\tassert(v >= 1);\n\t\t\t\tif(old >= 50 && v == 1) {}\n\t\t\t\telse if(old >= 50) assert(old - 1 == v);\n\t\t\t\telse if(old >= 0) assert(old + 1 == v);\n\t\t\t\told = v;\n\t\t\t\tif(v > m) m = v;\n\t\t\t\t++count;\n\t\t\t}\n\t\t\tassert(count >= 2);\n\t\t\tassert(count <= 100);\n\t\t\tassert(count == m);\n\t\t\tif(count >= 50) assert(old == 49);\n\t\t\tif(count < 100) assert(endCount == 0);\n\t\t\tif(count == 100) endCount++;\n\t\t\tif(endCount >= 10) break;\n\t\t}\n\t};\n\n\tfor(int i = 0; i < 1000; ++i) {\n\t\tl.push_back()->value = 1;\n\t\tl.push_back()->value = 2;\n\n\t\tstd::thread t1(producer), t3(reader);\n\t\tt1.join();\n\t\tt3.join();\n\n\t\tl._checkSanity();\n\t\tl.clear();\n\t}\n}\n\nint main() {\n\ttest0();\n\ttest1();\n\ttest2();\n\ttest3();\n\ttest4();\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of cdf-handler, a C++ server of OPeNDAP for access to cdf\n\/\/ data\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: Patrick West <pwest@ucar.edu>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n \n\/\/ Implementation for CDFHandlerApp.\n\/\/\n\/\/ pwest 05\/08\/03\n\n\/\/ CDFHandlerApp.cc\n\n#ifdef __GNUG__\n#pragma implementation\n#endif\n\n#include <signal.h>\n#include <unistd.h>\n\n#include <iostream>\n\nusing std::cout ;\nusing std::cerr ;\nusing std::endl ;\nusing std::flush ;\n\n#include \"CDFHandlerApp.h\"\n#include \"CDFResponseNames.h\"\n#include \"DODSFilter.h\"\n#include \"DODSCgi.h\"\n\nCDFHandlerApp::CDFHandlerApp()\n : _df( 0 )\n{\n}\n\nCDFHandlerApp::~CDFHandlerApp()\n{\n if( _df )\n {\n\tdelete _df ;\n\t_df = 0 ;\n }\n}\n\nint\nCDFHandlerApp::initialize( int argc, char **argv )\n{\n OPeNDAPBaseApp::initialize( argc, argv ) ;\n\n _df = new DODSFilter( argc, argv ) ;\n\n return 0 ;\n}\n\nint\nCDFHandlerApp::run()\n{\n DODSCgi d( CDF_NAME, *_df ) ;\n d.execute_request() ;\n\n return 0 ;\n}\n\n<commit_msg>default modules loaded in handler app<commit_after>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of cdf-handler, a C++ server of OPeNDAP for access to cdf\n\/\/ data\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: Patrick West <pwest@ucar.edu>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n \n\/\/ Implementation for CDFHandlerApp.\n\/\/\n\/\/ pwest 05\/08\/03\n\n\/\/ CDFHandlerApp.cc\n\n#ifdef __GNUG__\n#pragma implementation\n#endif\n\n#include <signal.h>\n#include <unistd.h>\n\n#include <iostream>\n\nusing std::cout ;\nusing std::cerr ;\nusing std::endl ;\nusing std::flush ;\n\n#include \"CDFHandlerApp.h\"\n#include \"CDFResponseNames.h\"\n#include \"DODSFilter.h\"\n#include \"DODSCgi.h\"\n#include \"dods_module.h\"\n#include \"opendap_commands.h\"\n\nCDFHandlerApp::CDFHandlerApp()\n : _df( 0 )\n{\n}\n\nCDFHandlerApp::~CDFHandlerApp()\n{\n if( _df )\n {\n\tdelete _df ;\n\t_df = 0 ;\n }\n}\n\nint\nCDFHandlerApp::initialize( int argc, char **argv )\n{\n dods_module::initialize( argc, argv ) ;\n opendap_commands::initialize( argc, argv ) ;\n\n OPeNDAPBaseApp::initialize( argc, argv ) ;\n\n _df = new DODSFilter( argc, argv ) ;\n\n return 0 ;\n}\n\nint\nCDFHandlerApp::run()\n{\n DODSCgi d( CDF_NAME, *_df ) ;\n d.execute_request() ;\n\n return 0 ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*Copyright 2011 George Karagoulis\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.*\/\n\n#include \"bst_t.h\"\n#include \"Core\/exception.h\"\n#include \"gassert.h\"\nGUTIL_USING_CORE_NAMESPACE(DataObjects);\nGUTIL_USING_CORE_NAMESPACE(Interfaces);\n\nbst_t::bst_t(bst_t::void_wrapper *vw)\n :root(0),\n data_access_wrapper(vw),\n m_size(0)\n{}\n\nbst_t::~bst_t()\n{\n \/\/ Note: We delete the compare interface because it has a virtual destructor\n \/\/ so the rest of the object will get deleted too.\n Clear();\n delete data_access_wrapper;\n}\n\nbst_t::void_wrapper::~void_wrapper(){}\n\nbst_node *bst_t::add(const void *const v)\n{\n bst_node *new_node;\n if(root)\n {\n \/\/ Find the place to insert, has to be a leaf node\n bst_node *cur( root );\n bst_node *next_cur( root );\n SideEnum insertion_side(LeftSide);\n while(next_cur)\n {\n cur = next_cur;\n int cmp_res( data_access_wrapper->CompareVoid(v, cur->Data) );\n\n if(cmp_res < 0)\n {\n next_cur = cur->LChild;\n insertion_side = LeftSide;\n }\n else if(cmp_res > 0)\n {\n next_cur = cur->RChild;\n insertion_side = RightSide;\n }\n else\n {\n \/\/ There's an insertion collision\n THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception,\n \"Object already exists in BST.\");\n }\n }\n\n new_node = new bst_node;\n switch(insertion_side)\n {\n case LeftSide:\n cur->LChild = new_node;\n break;\n case RightSide:\n cur->RChild = new_node;\n break;\n default:\n GASSERT(false);\n }\n new_node->Parent = cur;\n\n \/\/ Now we need to ascend the tree to the root and update the heights\n walk_parents_update_heights_rebalance(cur);\n\n _update_root_node();\n }\n else\n {\n \/\/ If the root is null, then this is the first item in the tree (easy case)\n root = new_node = new bst_node;\n }\n\n m_size++;\n\n new_node->Data = data_access_wrapper->CopyVoid(v);\n return new_node;\n}\n\nbool bst_t::remove(const const_iterator &iter)\n{\n bst_node *cur(iter.current);\n if(cur)\n {\n \/\/ Remove it. The deletion algorithm goes as follows:\n \/\/ I need to find a replacement from the leaves of the tree to\n \/\/ come take my place, then I will rebalance from the bottom of the tree.\n \/\/ I will find a replacement as the left-most item on my right side, or my\n \/\/ right-most item on my left side, whichever one is taller.\n\n \/\/ Find a replacement node\n bst_node *replacement(0);\n if(cur->Height > 0)\n {\n if(cur->HeightDifference() > 0)\n {\n \/\/ Left-heavy\n replacement = cur->LChild->RightmostChild;\n }\n else\n {\n \/\/ Right-heavy\n replacement = cur->RChild->LeftmostChild;\n }\n }\n\n\n if(root == cur)\n {\n \/\/ We have to pre-emptively adjust our root node, because we will be unable to\n \/\/ find the new root once it's deleted.\n if(root->RChild)\n root = root->RChild;\n else if(root->LChild)\n root = root->LChild;\n else\n root = 0;\n }\n\n data_access_wrapper->DeleteVoid(cur->Data);\n\n \/\/ This variable determines where to start adjusting the node height after deletion.\n bst_node *start_height_adjustment(0);\n\n if(replacement)\n {\n \/\/ If the replacement has a child (at most 1) then we move it into the replacement's place\n bst_node *replacement_child(0);\n if(replacement->RChild)\n replacement_child = replacement->RChild;\n else if(replacement->LChild)\n replacement_child = replacement->LChild;\n\n if(cur == replacement->Parent)\n start_height_adjustment = replacement;\n else\n {\n start_height_adjustment = replacement->Parent;\n switch(replacement->SideOfParent())\n {\n case RightSide:\n replacement->Parent->RChild = replacement_child;\n break;\n case LeftSide:\n replacement->Parent->LChild = replacement_child;\n break;\n default:\n break;\n }\n\n if(replacement_child)\n replacement_child->Parent = replacement->Parent;\n }\n\n replacement->Parent = cur->Parent;\n if(replacement != cur->RChild)\n replacement->RChild = cur->RChild;\n if(replacement != cur->LChild)\n replacement->LChild = cur->LChild;\n }\n else\n {\n start_height_adjustment = cur->Parent;\n }\n\n\n if(cur->RChild && cur->RChild != replacement)\n cur->RChild->Parent = replacement;\n if(cur->LChild && cur->LChild != replacement)\n cur->LChild->Parent = replacement;\n if(cur->Parent)\n {\n switch(cur->SideOfParent())\n {\n case RightSide:\n cur->Parent->RChild = replacement;\n break;\n case LeftSide:\n cur->Parent->LChild = replacement;\n break;\n default:\n break;\n }\n }\n\n \/\/ Delete the node (set children to 0 so to not delete them)\n cur->LChild = 0;\n cur->RChild = 0;\n delete cur;\n\n \/\/ Walk up the tree and update the height variables.\n walk_parents_update_heights_rebalance(start_height_adjustment);\n\n _update_root_node();\n\n m_size--;\n }\n return cur;\n}\n\nbool bst_t::remove(const void *const v)\n{\n return remove(const_iterator(search(v), data_access_wrapper));\n}\n\nbst_node *bst_t::search(const void *const v) const\n{\n return search(v, data_access_wrapper);\n}\n\nbst_node *bst_t::search(const void *const v, const IVoidComparer *vw) const\n{\n bst_node *cur( root );\n while(cur)\n {\n int cmp_res( vw->CompareVoid(cur->Data, v) );\n\n if(cmp_res < 0)\n cur = cur->RChild;\n else if(cmp_res > 0)\n cur = cur->LChild;\n else\n break;\n }\n return cur;\n}\n\nvoid bst_t::Clear()\n{\n if(root)\n {\n _cleanup_memory(root);\n root = 0;\n m_size = 0;\n }\n}\n\nvoid bst_t::_cleanup_memory(bst_node *n)\n{\n if(n->LChild)\n {\n _cleanup_memory(n->LChild);\n n->LChild = 0;\n }\n if(n->RChild)\n {\n _cleanup_memory(n->RChild);\n n->RChild = 0;\n }\n data_access_wrapper->DeleteVoid(n->Data);\n delete n;\n}\n\nbst_node *bst_t::first() const\n{\n return root ? root->LeftmostChild : 0;\n}\n\nbst_node *bst_t::last() const\n{\n return root ? root->RightmostChild : 0;\n}\n\nvoid bst_t::_update_root_node()\n{\n bst_node *n(root);\n while(n && (n = n->Parent))\n root = n;\n}\n\n\n\n\n\nbst_t::const_iterator::const_iterator()\n :current(0),\n cmp(0),\n mem_begin(0),\n mem_end(0)\n{}\n\nbst_t::const_iterator::const_iterator(bst_node *n, const IVoidComparer *const vc)\n :current(n),\n cmp(vc),\n mem_begin(0),\n mem_end(0)\n{}\n\nbst_t::const_iterator::const_iterator(const bst_t::const_iterator &o)\n :current(o.current),\n cmp(o.cmp),\n mem_begin(o.mem_begin),\n mem_end(o.mem_end)\n{}\n\n\n\nbool bst_t::const_iterator::operator == (const bst_t::const_iterator &o) const\n{\n return current == o.current &&\n (current != 0 ||\n ((mem_begin == 0 && mem_end == 0) || (o.mem_begin == 0 && o.mem_end == 0) ||\n (mem_begin == o.mem_begin && mem_end == o.mem_end)));\n}\n\nbool bst_t::const_iterator::operator != (const bst_t::const_iterator &o) const\n{\n return !(*this == o);\n}\n\nbst_t::const_iterator::operator bool() const\n{\n return current;\n}\n\nvoid bst_t::const_iterator::advance()\n{\n if(current)\n {\n if(current->RChild)\n current = current->RChild->LeftmostChild;\n else\n {\n \/\/ Ascend current's parents to find the next greater element\n bst_node *cur(current);\n do\n {\n if(cur->SideOfParent() == LeftSide)\n {\n current = cur->Parent;\n break;\n }\n }while((cur = cur->Parent));\n\n if(!cur)\n {\n \/\/ We've hit the end of the BST\n mem_end = current;\n current = 0;\n }\n }\n }\n else if(mem_begin)\n {\n current = mem_begin;\n mem_begin = 0;\n }\n else\n THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception,\n \"Can't move iterator past the end of the container.\");\n}\n\nvoid bst_t::const_iterator::retreat()\n{\n if(current)\n {\n if(current->LChild)\n current = current->LChild->RightmostChild;\n else\n {\n \/\/ Ascend current's parents to find the next lesser element\n bst_node *cur(current);\n do\n {\n if(cur->SideOfParent() == RightSide)\n {\n current = cur->Parent;\n break;\n }\n }while((cur = cur->Parent));\n\n if(!cur)\n {\n \/\/ We've hit the beginning of the BST\n mem_begin = current;\n current = 0;\n }\n }\n }\n else if(mem_end)\n {\n current = mem_end;\n mem_end = 0;\n }\n else\n THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception,\n \"Can't move iterator before the beginning of the container.\");\n}\n\nbst_t::const_iterator &bst_t::const_iterator::operator ++()\n{\n advance();\n return *this;\n}\n\nbst_t::const_iterator bst_t::const_iterator::operator ++(int)\n{\n const_iterator ret(*this);\n advance();\n return ret;\n}\n\nbst_t::const_iterator &bst_t::const_iterator::operator --()\n{\n retreat();\n return *this;\n}\n\nbst_t::const_iterator bst_t::const_iterator::operator --(int)\n{\n const_iterator ret(*this);\n retreat();\n return ret;\n}\n\nbool bst_t::const_iterator::operator <(const bst_t::const_iterator &o) const\n{\n if(current && o.current)\n {\n return cmp->CompareVoid(current->Data, o.current->Data) < 0;\n }\n else\n {\n if(current == 0 && o.current == 0){\n \/\/ I am at the beginning, o is at the end\n if(mem_begin && o.mem_end)\n return true;\n return false;\n }\n else if(current == 0)\n {\n \/\/ I am at the beginning, so I come before o\n return mem_begin;\n }\n else\n {\n \/\/ o is at the end, so I come before it\n return o.mem_end;\n }\n }\n}\n\nbool bst_t::const_iterator::operator > (const const_iterator &o) const\n{\n return !(*this <= o);\n}\n\nbool bst_t::const_iterator::operator <= (const const_iterator &o) const\n{\n return *this == o || *this < o;\n}\n\nbool bst_t::const_iterator::operator >= (const const_iterator &o) const\n{\n return !(*this < o);\n}\n\n\n\nvoid bst_t::walk_parents_update_heights_rebalance(bst_node *n)\n{\n if(n)\n {\n refresh_node_state(n);\n\n \/\/ Rebalance the node if it's unbalanced\n if(!n->Balanced())\n rebalance(n);\n\n walk_parents_update_heights_rebalance(n->Parent);\n }\n}\n\nvoid bst_t::refresh_node_state(bst_node *n)\n{\n \/\/ Update the node's height cache\n if(!n->LChild && !n->RChild)\n n->Height = 0;\n else\n {\n const int lheight(n->LChild ? n->LChild->Height : 0);\n const int rheight(n->RChild ? n->RChild->Height : 0);\n n->Height = gMax(lheight, rheight) + 1;\n }\n\n \/\/ Update the left-most and right-most child caches\n n->LeftmostChild = n->LChild ? n->LChild->LeftmostChild : n;\n n->RightmostChild = n->RChild ? n->RChild->RightmostChild : n;\n}\n\nvoid bst_t::rotate_right(bst_node *n)\n{\n bst_node *parent(n->Parent);\n if(parent)\n {\n if(parent->LChild == n)\n parent->LChild = n->LChild;\n else\n parent->RChild = n->LChild;\n }\n n->LChild->Parent = parent;\n\n bst_node *tmp(n->LChild->RChild);\n n->Parent = n->LChild;\n n->LChild->RChild = n;\n n->LChild = tmp;\n if(tmp)\n tmp->Parent = n;\n\n \/\/ Have to refresh the node we just rotated, the other one will be refreshed\n \/\/ automatically when we walk up the tree\n refresh_node_state(n);\n}\n\nvoid bst_t::rotate_left(bst_node *n)\n{\n bst_node *parent(n->Parent);\n if(parent)\n {\n if(parent->LChild == n)\n parent->LChild = n->RChild;\n else\n parent->RChild = n->RChild;\n }\n n->RChild->Parent = parent;\n\n bst_node *tmp(n->RChild->LChild);\n n->Parent = n->RChild;\n n->RChild->LChild = n;\n n->RChild = tmp;\n if(tmp)\n tmp->Parent = n;\n\n \/\/ Have to refresh the node we just rotated, the other one will be refreshed\n \/\/ automatically when we walk up the tree\n refresh_node_state(n);\n}\n\nvoid bst_t::rebalance(bst_node *n)\n{\n int height_difference = n->HeightDifference();\n if(height_difference > 1)\n {\n \/\/ The node is left-heavy\n\n \/\/ Check if it's LR imbalance so we can resolve that first.\n if(n->LChild->HeightDifference() < 0)\n rotate_left(n->LChild);\n\n \/\/ Now that the LR imbalance is fixed, do the LL rebalance.\n rotate_right(n);\n }\n else if(height_difference < -1)\n {\n \/\/ The node is right-heavy\n\n \/\/ Check if it's RL imbalance so we can resolve that first.\n if(n->RChild->HeightDifference() > 0)\n rotate_right(n->RChild);\n\n \/\/ Now that the RL imbalance is fixed, do the RR rebalance.\n rotate_left(n);\n }\n}\n\nbst_node *bst_t::const_iterator::operator->()\n{\n return current;\n}\n\nconst bst_node *bst_t::const_iterator::operator->() const\n{\n return current;\n}\nconst bst_node &bst_t::const_iterator::operator *() const\n{\n return *current;\n}\nbst_node &bst_t::const_iterator::operator *()\n{\n return *current;\n}\n<commit_msg>Do nothing if the user tries to increment the iterator past the end or before the beginning<commit_after>\/*Copyright 2011 George Karagoulis\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.*\/\n\n#include \"bst_t.h\"\n#include \"Core\/exception.h\"\n#include \"gassert.h\"\nGUTIL_USING_CORE_NAMESPACE(DataObjects);\nGUTIL_USING_CORE_NAMESPACE(Interfaces);\n\nbst_t::bst_t(bst_t::void_wrapper *vw)\n :root(0),\n data_access_wrapper(vw),\n m_size(0)\n{}\n\nbst_t::~bst_t()\n{\n \/\/ Note: We delete the compare interface because it has a virtual destructor\n \/\/ so the rest of the object will get deleted too.\n Clear();\n delete data_access_wrapper;\n}\n\nbst_t::void_wrapper::~void_wrapper(){}\n\nbst_node *bst_t::add(const void *const v)\n{\n bst_node *new_node;\n if(root)\n {\n \/\/ Find the place to insert, has to be a leaf node\n bst_node *cur( root );\n bst_node *next_cur( root );\n SideEnum insertion_side(LeftSide);\n while(next_cur)\n {\n cur = next_cur;\n int cmp_res( data_access_wrapper->CompareVoid(v, cur->Data) );\n\n if(cmp_res < 0)\n {\n next_cur = cur->LChild;\n insertion_side = LeftSide;\n }\n else if(cmp_res > 0)\n {\n next_cur = cur->RChild;\n insertion_side = RightSide;\n }\n else\n {\n \/\/ There's an insertion collision\n THROW_NEW_GUTIL_EXCEPTION2(GUtil::Core::Exception,\n \"Object already exists in BST.\");\n }\n }\n\n new_node = new bst_node;\n switch(insertion_side)\n {\n case LeftSide:\n cur->LChild = new_node;\n break;\n case RightSide:\n cur->RChild = new_node;\n break;\n default:\n GASSERT(false);\n }\n new_node->Parent = cur;\n\n \/\/ Now we need to ascend the tree to the root and update the heights\n walk_parents_update_heights_rebalance(cur);\n\n _update_root_node();\n }\n else\n {\n \/\/ If the root is null, then this is the first item in the tree (easy case)\n root = new_node = new bst_node;\n }\n\n m_size++;\n\n new_node->Data = data_access_wrapper->CopyVoid(v);\n return new_node;\n}\n\nbool bst_t::remove(const const_iterator &iter)\n{\n bst_node *cur(iter.current);\n if(cur)\n {\n \/\/ Remove it. The deletion algorithm goes as follows:\n \/\/ I need to find a replacement from the leaves of the tree to\n \/\/ come take my place, then I will rebalance from the bottom of the tree.\n \/\/ I will find a replacement as the left-most item on my right side, or my\n \/\/ right-most item on my left side, whichever one is taller.\n\n \/\/ Find a replacement node\n bst_node *replacement(0);\n if(cur->Height > 0)\n {\n if(cur->HeightDifference() > 0)\n {\n \/\/ Left-heavy\n replacement = cur->LChild->RightmostChild;\n }\n else\n {\n \/\/ Right-heavy\n replacement = cur->RChild->LeftmostChild;\n }\n }\n\n\n if(root == cur)\n {\n \/\/ We have to pre-emptively adjust our root node, because we will be unable to\n \/\/ find the new root once it's deleted.\n if(root->RChild)\n root = root->RChild;\n else if(root->LChild)\n root = root->LChild;\n else\n root = 0;\n }\n\n data_access_wrapper->DeleteVoid(cur->Data);\n\n \/\/ This variable determines where to start adjusting the node height after deletion.\n bst_node *start_height_adjustment(0);\n\n if(replacement)\n {\n \/\/ If the replacement has a child (at most 1) then we move it into the replacement's place\n bst_node *replacement_child(0);\n if(replacement->RChild)\n replacement_child = replacement->RChild;\n else if(replacement->LChild)\n replacement_child = replacement->LChild;\n\n if(cur == replacement->Parent)\n start_height_adjustment = replacement;\n else\n {\n start_height_adjustment = replacement->Parent;\n switch(replacement->SideOfParent())\n {\n case RightSide:\n replacement->Parent->RChild = replacement_child;\n break;\n case LeftSide:\n replacement->Parent->LChild = replacement_child;\n break;\n default:\n break;\n }\n\n if(replacement_child)\n replacement_child->Parent = replacement->Parent;\n }\n\n replacement->Parent = cur->Parent;\n if(replacement != cur->RChild)\n replacement->RChild = cur->RChild;\n if(replacement != cur->LChild)\n replacement->LChild = cur->LChild;\n }\n else\n {\n start_height_adjustment = cur->Parent;\n }\n\n\n if(cur->RChild && cur->RChild != replacement)\n cur->RChild->Parent = replacement;\n if(cur->LChild && cur->LChild != replacement)\n cur->LChild->Parent = replacement;\n if(cur->Parent)\n {\n switch(cur->SideOfParent())\n {\n case RightSide:\n cur->Parent->RChild = replacement;\n break;\n case LeftSide:\n cur->Parent->LChild = replacement;\n break;\n default:\n break;\n }\n }\n\n \/\/ Delete the node (set children to 0 so to not delete them)\n cur->LChild = 0;\n cur->RChild = 0;\n delete cur;\n\n \/\/ Walk up the tree and update the height variables.\n walk_parents_update_heights_rebalance(start_height_adjustment);\n\n _update_root_node();\n\n m_size--;\n }\n return cur;\n}\n\nbool bst_t::remove(const void *const v)\n{\n return remove(const_iterator(search(v), data_access_wrapper));\n}\n\nbst_node *bst_t::search(const void *const v) const\n{\n return search(v, data_access_wrapper);\n}\n\nbst_node *bst_t::search(const void *const v, const IVoidComparer *vw) const\n{\n bst_node *cur( root );\n while(cur)\n {\n int cmp_res( vw->CompareVoid(cur->Data, v) );\n\n if(cmp_res < 0)\n cur = cur->RChild;\n else if(cmp_res > 0)\n cur = cur->LChild;\n else\n break;\n }\n return cur;\n}\n\nvoid bst_t::Clear()\n{\n if(root)\n {\n _cleanup_memory(root);\n root = 0;\n m_size = 0;\n }\n}\n\nvoid bst_t::_cleanup_memory(bst_node *n)\n{\n if(n->LChild)\n {\n _cleanup_memory(n->LChild);\n n->LChild = 0;\n }\n if(n->RChild)\n {\n _cleanup_memory(n->RChild);\n n->RChild = 0;\n }\n data_access_wrapper->DeleteVoid(n->Data);\n delete n;\n}\n\nbst_node *bst_t::first() const\n{\n return root ? root->LeftmostChild : 0;\n}\n\nbst_node *bst_t::last() const\n{\n return root ? root->RightmostChild : 0;\n}\n\nvoid bst_t::_update_root_node()\n{\n bst_node *n(root);\n while(n && (n = n->Parent))\n root = n;\n}\n\n\n\n\n\nbst_t::const_iterator::const_iterator()\n :current(0),\n cmp(0),\n mem_begin(0),\n mem_end(0)\n{}\n\nbst_t::const_iterator::const_iterator(bst_node *n, const IVoidComparer *const vc)\n :current(n),\n cmp(vc),\n mem_begin(0),\n mem_end(0)\n{}\n\nbst_t::const_iterator::const_iterator(const bst_t::const_iterator &o)\n :current(o.current),\n cmp(o.cmp),\n mem_begin(o.mem_begin),\n mem_end(o.mem_end)\n{}\n\n\n\nbool bst_t::const_iterator::operator == (const bst_t::const_iterator &o) const\n{\n return current == o.current &&\n (current != 0 ||\n ((mem_begin == 0 && mem_end == 0) || (o.mem_begin == 0 && o.mem_end == 0) ||\n (mem_begin == o.mem_begin && mem_end == o.mem_end)));\n}\n\nbool bst_t::const_iterator::operator != (const bst_t::const_iterator &o) const\n{\n return !(*this == o);\n}\n\nbst_t::const_iterator::operator bool() const\n{\n return current;\n}\n\nvoid bst_t::const_iterator::advance()\n{\n if(current)\n {\n if(current->RChild)\n current = current->RChild->LeftmostChild;\n else\n {\n \/\/ Ascend current's parents to find the next greater element\n bst_node *cur(current);\n do\n {\n if(cur->SideOfParent() == LeftSide)\n {\n current = cur->Parent;\n break;\n }\n }while((cur = cur->Parent));\n\n if(!cur)\n {\n \/\/ We've hit the end of the BST\n mem_end = current;\n current = 0;\n }\n }\n }\n else if(mem_begin)\n {\n current = mem_begin;\n mem_begin = 0;\n }\n}\n\nvoid bst_t::const_iterator::retreat()\n{\n if(current)\n {\n if(current->LChild)\n current = current->LChild->RightmostChild;\n else\n {\n \/\/ Ascend current's parents to find the next lesser element\n bst_node *cur(current);\n do\n {\n if(cur->SideOfParent() == RightSide)\n {\n current = cur->Parent;\n break;\n }\n }while((cur = cur->Parent));\n\n if(!cur)\n {\n \/\/ We've hit the beginning of the BST\n mem_begin = current;\n current = 0;\n }\n }\n }\n else if(mem_end)\n {\n current = mem_end;\n mem_end = 0;\n }\n}\n\nbst_t::const_iterator &bst_t::const_iterator::operator ++()\n{\n advance();\n return *this;\n}\n\nbst_t::const_iterator bst_t::const_iterator::operator ++(int)\n{\n const_iterator ret(*this);\n advance();\n return ret;\n}\n\nbst_t::const_iterator &bst_t::const_iterator::operator --()\n{\n retreat();\n return *this;\n}\n\nbst_t::const_iterator bst_t::const_iterator::operator --(int)\n{\n const_iterator ret(*this);\n retreat();\n return ret;\n}\n\nbool bst_t::const_iterator::operator <(const bst_t::const_iterator &o) const\n{\n if(current && o.current)\n {\n return cmp->CompareVoid(current->Data, o.current->Data) < 0;\n }\n else\n {\n if(current == 0 && o.current == 0){\n \/\/ I am at the beginning, o is at the end\n if(mem_begin && o.mem_end)\n return true;\n return false;\n }\n else if(current == 0)\n {\n \/\/ I am at the beginning, so I come before o\n return mem_begin;\n }\n else\n {\n \/\/ o is at the end, so I come before it\n return o.mem_end;\n }\n }\n}\n\nbool bst_t::const_iterator::operator > (const const_iterator &o) const\n{\n return !(*this <= o);\n}\n\nbool bst_t::const_iterator::operator <= (const const_iterator &o) const\n{\n return *this == o || *this < o;\n}\n\nbool bst_t::const_iterator::operator >= (const const_iterator &o) const\n{\n return !(*this < o);\n}\n\n\n\nvoid bst_t::walk_parents_update_heights_rebalance(bst_node *n)\n{\n if(n)\n {\n refresh_node_state(n);\n\n \/\/ Rebalance the node if it's unbalanced\n if(!n->Balanced())\n rebalance(n);\n\n walk_parents_update_heights_rebalance(n->Parent);\n }\n}\n\nvoid bst_t::refresh_node_state(bst_node *n)\n{\n \/\/ Update the node's height cache\n if(!n->LChild && !n->RChild)\n n->Height = 0;\n else\n {\n const int lheight(n->LChild ? n->LChild->Height : 0);\n const int rheight(n->RChild ? n->RChild->Height : 0);\n n->Height = gMax(lheight, rheight) + 1;\n }\n\n \/\/ Update the left-most and right-most child caches\n n->LeftmostChild = n->LChild ? n->LChild->LeftmostChild : n;\n n->RightmostChild = n->RChild ? n->RChild->RightmostChild : n;\n}\n\nvoid bst_t::rotate_right(bst_node *n)\n{\n bst_node *parent(n->Parent);\n if(parent)\n {\n if(parent->LChild == n)\n parent->LChild = n->LChild;\n else\n parent->RChild = n->LChild;\n }\n n->LChild->Parent = parent;\n\n bst_node *tmp(n->LChild->RChild);\n n->Parent = n->LChild;\n n->LChild->RChild = n;\n n->LChild = tmp;\n if(tmp)\n tmp->Parent = n;\n\n \/\/ Have to refresh the node we just rotated, the other one will be refreshed\n \/\/ automatically when we walk up the tree\n refresh_node_state(n);\n}\n\nvoid bst_t::rotate_left(bst_node *n)\n{\n bst_node *parent(n->Parent);\n if(parent)\n {\n if(parent->LChild == n)\n parent->LChild = n->RChild;\n else\n parent->RChild = n->RChild;\n }\n n->RChild->Parent = parent;\n\n bst_node *tmp(n->RChild->LChild);\n n->Parent = n->RChild;\n n->RChild->LChild = n;\n n->RChild = tmp;\n if(tmp)\n tmp->Parent = n;\n\n \/\/ Have to refresh the node we just rotated, the other one will be refreshed\n \/\/ automatically when we walk up the tree\n refresh_node_state(n);\n}\n\nvoid bst_t::rebalance(bst_node *n)\n{\n int height_difference = n->HeightDifference();\n if(height_difference > 1)\n {\n \/\/ The node is left-heavy\n\n \/\/ Check if it's LR imbalance so we can resolve that first.\n if(n->LChild->HeightDifference() < 0)\n rotate_left(n->LChild);\n\n \/\/ Now that the LR imbalance is fixed, do the LL rebalance.\n rotate_right(n);\n }\n else if(height_difference < -1)\n {\n \/\/ The node is right-heavy\n\n \/\/ Check if it's RL imbalance so we can resolve that first.\n if(n->RChild->HeightDifference() > 0)\n rotate_right(n->RChild);\n\n \/\/ Now that the RL imbalance is fixed, do the RR rebalance.\n rotate_left(n);\n }\n}\n\nbst_node *bst_t::const_iterator::operator->()\n{\n return current;\n}\n\nconst bst_node *bst_t::const_iterator::operator->() const\n{\n return current;\n}\nconst bst_node &bst_t::const_iterator::operator *() const\n{\n return *current;\n}\nbst_node &bst_t::const_iterator::operator *()\n{\n return *current;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n#include <string>\n#include \"ipns_retriever.h\"\n#include \"..\/node.h\"\n#include \"..\/string_util.h\"\n#include \"..\/tree.hh\"\n\nusing std::invalid_argument;\nusing std::runtime_error;\nusing std::string;\nusing std::vector;\nusing string_util::starts_with;\nusing string_util::int_list_str_to_intVect;\n\nconst static int GROUP_STRING_LEN=128;\n\n\/**\n * The factory will call the constructor with a string. The string\n * specifies where to locate the data (e.g. a filename), but\n * interpreting the string is left up to the implementing code.\n *\/\nIpnsRetriever::IpnsRetriever(const string &str): source(str){\n if(str.size()<=0)\n throw invalid_argument(\"Cannot initialize from an empty string\");\n \n char filename[50];\n strcpy(filename,str.c_str());\n char *f_ptr;\n f_ptr = filename;\n runFile = new Runfile(f_ptr);\n if(runFile==NULL){\n \/\/handle=NULL;\n throw runtime_error(\"Opening Runfile failed\");\n }\n \n}\n\nIpnsRetriever::~IpnsRetriever(){\n \/* if(handle!=NULL){\n if(NXclose(handle)!=NX_OK)\n throw runtime_error(\"NXclose failed\");\n handle=NULL;\n }*\/\n}\n\n\/**\n * This is the method for retrieving data from a file. The whole\n * tree will be written to the new file immediately after being\n * called. Interpreting the string is left up to the implementing\n * code.\n *\/\nvoid IpnsRetriever::getData(Node &node, const std::string &location){\n if(location.size()<=0)\n throw invalid_argument(\"cannot parse empty string\");\n \n string tLocation(location);\n if(starts_with(tLocation, \"header\")) {\n Header head = runFile->getHeader();\n int dims[1];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n if( location.substr(7,location.size()-7 ) == \"runTitle\" ) {\n\tvalue = new char[81];\n\thead.RunTitle((char *)value);\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"userName\" ) {\n\tvalue = new char[21];\n\thead.UserName((char *)value);\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"startDateTime\" ) {\n\tchar date[10];\n\thead.StartDate((char *)date);\n\tchar time[9];\n\thead.StartTime((char *)time);\n\tstring sVal = this->fixDate( date, time );\n\tvalue = (void *)sVal.c_str();\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"endDateTime\" ) {\n\tchar date[10];\n\thead.EndDate((char *)date);\n\tchar time[9];\n\thead.EndTime((char *)time);\n\n\tstring sVal = this->fixDate( date, time );\n\tvalue = (void *)sVal.c_str();\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n node = Node(tLocation, value, 1, &(dims[0]), data_type);\n free(value);\n }\n \/\/ get data\n else if( location.substr(0, 5) == \"data.\" ) {\n int dims[2];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n vector<vector<float> > vdata;\n vector<int> idListVect;\n float *data;\n \/\/data retrieved from list of ids\n if ( location.substr(5, 3) == \"ids\" ) {\n\tstring idList = location.substr( 8, location.size()-8 );\n\t\/\/ find & remove brackets\n\tstring::size_type start_brkt = idList.find(\"[\");\n\tstring::size_type end_brkt = idList.find(\"]\");\n\tstring intListStr = \n\t idList.substr(start_brkt + 1, end_brkt - (start_brkt +1) );\n\t\/\/ sort this string into a vector of integers\n\tidListVect = int_list_str_to_intVect(intListStr);\n\tint id;\n\tvector<Segment *> segments = runFile->GetSegments();\n\tvdata.resize(idListVect.size());\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t vdata[id] = runFile->Get1DSpectrum(*segments[idListVect[id]], 1); \n\t \n\t}\n\n\tdata = new float[idListVect.size()*vdata[0].size()];\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t \/\/\t data[id] = new float[vdata[0].size()];\n\t if ( vdata[id].size() != vdata[0].size() ) {\n\t throw runtime_error(\"ipns_retriever: all data must match size\\n\");\n\t }\n\t for (int chan =0; chan < vdata[0].size(); chan++ ) {\n\t data[(id*vdata[0].size())+(chan)] = vdata[id][chan];\n\t }\n\t}\n }\n \n dims[1] = vdata[0].size();\n dims[0] = idListVect.size();\n data_type = NX_FLOAT32;\n data_rank =2;\n value = (void *)data;\n node = Node(tLocation, value, data_rank, &(dims[0]), data_type);\n }\n else if( location.substr(0, 9) == \"detector.\" ) {\n cout << \"reading det from \" << location.substr(9, location.size()-1);\n \/\/ node = Node(tLocation, value, 1, &(dims[0]), data_type);\n \/\/free(value);\n }\n \n\n \n}\n\nvoid IpnsRetriever::getData(const string &location, tree<Node> &tr){\n if(location.size()<=0)\n throw invalid_argument(\"cannot parse empty string\");\n Node node(\"empty\",\"empty\");\n getData(node,location);\n tr.insert(tr.begin(),node);\n}\n\nconst string IpnsRetriever::MIME_TYPE(\"application\/x-IPNS\");\n\nstring IpnsRetriever::toString() const{\n return \"[\"+MIME_TYPE+\"] \"+source;\n}\n\nstd::string IpnsRetriever::fixDate( char *date, char *time ) {\n\tint year = (date[7]-48)*10 + (date[8]-48);\n\tstring sVal;\n\tif ( year > 80) {\n\t sVal.append (1, '1');\n\t sVal.append( 1, '9');\n\t}\n\telse {\n\t sVal.append( 1, '2');\n\t sVal.append( 1, '0');\n\t}\n\tsVal.append( 1, date[7]);\n\tsVal.append( 1, date[8]);\n\tsVal.append(1, '-');\n\tif ( date[3] == 'J' ) {\n\t if ( date[4] == 'A' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '1');\n\t }\n\t else if (date[5] == 'N') {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '6');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '7');\n\t }\n\t}\n\telse if ( date[3] == 'F' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '2');\n\t}\n\telse if ( date[3] == 'M' ) {\n\t if ( date[5] == 'R' ) {\n\t sVal.append(1, '0');\n\t sVal.append(1, '3');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '5');\n\t }\n\t}\n\telse if ( date[3] == 'A' ) {\n\t if ( date[5] == 'R' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '4');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '8');\n\t }\n\t}\n\telse if ( date[3] == 'S' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '9');\n\t}\n\telse if ( date[3] == 'O' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '0');\n\t}\n\telse if ( date[3] == 'N' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '1');\n\t}\n\telse if ( date[3] == 'D' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '2');\n\t}\n\tsVal.append(1, '-');\n\tsVal.append(1, date[0]);\n\tsVal.append(1, date[1]);\n\tsVal.append(1, 'T');\n\tint ii;\n\tfor (ii = 0; ii < 8; ii++ ) {\n\t sVal.append(1, time[ii]);\n\t}\n\tsVal.append(1, '.');\n\tsVal.append(1, '0');\n\tsVal.append(1, '0');\n\tsVal.append(1, '-');\n\tsVal.append(1, '0');\n\tsVal.append(1, '6');\n\tsVal.append(1, ':');\n\tsVal.append(1, '0');\n\tsVal.append(1, '0');\n\tsVal.append(1, '\\0');\n\n return sVal;\n}\n<commit_msg>Add in stuff to get TOFs & Errors from file<commit_after>#include <stdexcept>\n#include <string>\n#include \"ipns_retriever.h\"\n#include \"..\/node.h\"\n#include \"..\/string_util.h\"\n#include \"..\/tree.hh\"\n\nusing std::invalid_argument;\nusing std::runtime_error;\nusing std::string;\nusing std::vector;\nusing string_util::starts_with;\nusing string_util::int_list_str_to_intVect;\n\nconst static int GROUP_STRING_LEN=128;\n\n\/**\n * The factory will call the constructor with a string. The string\n * specifies where to locate the data (e.g. a filename), but\n * interpreting the string is left up to the implementing code.\n *\/\nIpnsRetriever::IpnsRetriever(const string &str): source(str){\n if(str.size()<=0)\n throw invalid_argument(\"Cannot initialize from an empty string\");\n \n char filename[50];\n strcpy(filename,str.c_str());\n char *f_ptr;\n f_ptr = filename;\n runFile = new Runfile(f_ptr);\n if(runFile==NULL){\n \/\/handle=NULL;\n throw runtime_error(\"Opening Runfile failed\");\n }\n \n}\n\nIpnsRetriever::~IpnsRetriever(){\n \/* if(handle!=NULL){\n if(NXclose(handle)!=NX_OK)\n throw runtime_error(\"NXclose failed\");\n handle=NULL;\n }*\/\n}\n\n\/**\n * This is the method for retrieving data from a file. The whole\n * tree will be written to the new file immediately after being\n * called. Interpreting the string is left up to the implementing\n * code.\n *\/\nvoid IpnsRetriever::getData(Node &node, const std::string &location){\n if(location.size()<=0)\n throw invalid_argument(\"cannot parse empty string\");\n \n string tLocation(location);\n if(starts_with(tLocation, \"header\")) {\n Header head = runFile->getHeader();\n int dims[1];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n if( location.substr(7,location.size()-7 ) == \"runTitle\" ) {\n\tvalue = new char[81];\n\thead.RunTitle((char *)value);\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"userName\" ) {\n\tvalue = new char[21];\n\thead.UserName((char *)value);\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"startDateTime\" ) {\n\tchar date[10];\n\thead.StartDate((char *)date);\n\tchar time[9];\n\thead.StartTime((char *)time);\n\tstring sVal = this->fixDate( date, time );\n\tvalue = (void *)sVal.c_str();\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n if( location.substr(7,location.size()-7 ) == \"endDateTime\" ) {\n\tchar date[10];\n\thead.EndDate((char *)date);\n\tchar time[9];\n\thead.EndTime((char *)time);\n\n\tstring sVal = this->fixDate( date, time );\n\tvalue = (void *)sVal.c_str();\n\tdims[0] = (string((char *)value)).size();\n\tdata_type = NX_CHAR;\n\tdata_rank = 1;\n }\n node = Node(tLocation, value, 1, &(dims[0]), data_type);\n free(value);\n }\n \/\/ get data\n else if( location.substr(0, 5) == \"data.\" ) {\n int dims[2];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n vector<vector<float> > vdata;\n vector<int> idListVect;\n float *data;\n \/\/data retrieved from list of ids\n if ( location.substr(5, 3) == \"ids\" ) {\n\tstring idList = location.substr( 8, location.size()-8 );\n\t\/\/ find & remove brackets\n\tstring::size_type start_brkt = idList.find(\"[\");\n\tstring::size_type end_brkt = idList.find(\"]\");\n\tstring intListStr = \n\t idList.substr(start_brkt + 1, end_brkt - (start_brkt +1) );\n\t\/\/ sort this string into a vector of integers\n\tidListVect = int_list_str_to_intVect(intListStr);\n\tint id;\n\tvector<Segment *> segments = runFile->GetSegments();\n\tvdata.resize(idListVect.size());\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t vdata[id] = runFile->Get1DSpectrum(*segments[idListVect[id]], 1); \n\t \n\t}\n\n\tdata = new float[idListVect.size()*vdata[0].size()];\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t \/\/\t data[id] = new float[vdata[0].size()];\n\t if ( vdata[id].size() != vdata[0].size() ) {\n\t throw runtime_error(\"ipns_retriever: all data must match size\\n\");\n\t }\n\t for (int chan =0; chan < vdata[0].size(); chan++ ) {\n\t data[(id*vdata[0].size())+(chan)] = vdata[id][chan];\n\t }\n\t}\n }\n \n dims[1] = vdata[0].size();\n dims[0] = idListVect.size();\n data_type = NX_FLOAT32;\n data_rank =2;\n value = (void *)data;\n node = Node(tLocation, value, data_rank, &(dims[0]), data_type);\n }\n else if( location.substr(0, 5) == \"time.\" ) {\n int dims[2];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n vector<vector<float> > vdata;\n vector<int> idListVect;\n float *data;\n \/\/data retrieved from list of ids\n if ( location.substr(5, 3) == \"ids\" ) {\n\tstring idList = location.substr( 8, location.size()-8 );\n\t\/\/ find & remove brackets\n\tstring::size_type start_brkt = idList.find(\"[\");\n\tstring::size_type end_brkt = idList.find(\"]\");\n\tstring intListStr = \n\t idList.substr(start_brkt + 1, end_brkt - (start_brkt +1) );\n\t\/\/ sort this string into a vector of integers\n\tidListVect = int_list_str_to_intVect(intListStr);\n\tint id;\n\tvector<Segment *> segments = runFile->GetSegments();\n\tvdata.resize(idListVect.size());\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t vdata[id] = runFile->TimeChannelBoundaries(*segments[idListVect[id]], 1); \n\t}\n\tdata = new float[idListVect.size()*vdata[0].size()];\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t \/\/\t data[id] = new float[vdata[0].size()];\n\t if ( vdata[id].size() != vdata[0].size() ) {\n\t throw runtime_error(\"ipns_retriever: all data must match size\\n\");\n\t }\n\t for (int chan =0; chan < vdata[0].size(); chan++ ) {\n\t data[(id*vdata[0].size())+(chan)] = vdata[id][chan];\n\t }\n\t}\n }\n dims[1] = vdata[0].size();\n dims[0] = idListVect.size();\n data_type = NX_FLOAT32;\n data_rank =2;\n value = (void *)data;\n node = Node(tLocation, value, data_rank, &(dims[0]), data_type);\n }\n else if( location.substr(0, 6) == \"error.\" ) {\n int dims[2];\n const int *dim_ptr;\n dim_ptr = dims;\n void *value;\n int data_type;\n int data_rank;\n vector<vector<float> > vdata;\n vector<int> idListVect;\n float *data;\n \/\/data retrieved from list of ids\n if ( location.substr(6, 3) == \"ids\" ) {\n\tstring idList = location.substr( 8, location.size()-8 );\n\t\/\/ find & remove brackets\n\tstring::size_type start_brkt = idList.find(\"[\");\n\tstring::size_type end_brkt = idList.find(\"]\");\n\tstring intListStr = \n\t idList.substr(start_brkt + 1, end_brkt - (start_brkt +1) );\n\t\/\/ sort this string into a vector of integers\n\tidListVect = int_list_str_to_intVect(intListStr);\n\tint id;\n\tvector<Segment *> segments = runFile->GetSegments();\n\tvdata.resize(idListVect.size());\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t vdata[id] = runFile->Get1DSpectrum(*segments[idListVect[id]], 1); \n\t}\n\tdata = new float[idListVect.size()*vdata[0].size()];\n\tfor (id = 0; id < idListVect.size(); id++) {\n\t \/\/\t data[id] = new float[vdata[0].size()];\n\t if ( vdata[id].size() != vdata[0].size() ) {\n\t throw runtime_error(\"ipns_retriever: all data must match size\\n\");\n\t }\n\t for (int chan =0; chan < vdata[0].size(); chan++ ) {\n\t data[(id*vdata[0].size())+(chan)] = sqrt(vdata[id][chan]);\n\t }\n\t}\n }\n dims[1] = vdata[0].size();\n dims[0] = idListVect.size();\n data_type = NX_FLOAT32;\n data_rank =2;\n value = (void *)data;\n node = Node(tLocation, value, data_rank, &(dims[0]), data_type);\n }\n else if( location.substr(0, 9) == \"detector.\" ) {\n cout << \"reading det from \" << location.substr(9, location.size()-1);\n \/\/ node = Node(tLocation, value, 1, &(dims[0]), data_type);\n \/\/free(value);\n }\n \n\n \n}\n\nvoid IpnsRetriever::getData(const string &location, tree<Node> &tr){\n if(location.size()<=0)\n throw invalid_argument(\"cannot parse empty string\");\n Node node(\"empty\",\"empty\");\n getData(node,location);\n tr.insert(tr.begin(),node);\n}\n\nconst string IpnsRetriever::MIME_TYPE(\"application\/x-IPNS\");\n\nstring IpnsRetriever::toString() const{\n return \"[\"+MIME_TYPE+\"] \"+source;\n}\n\nstd::string IpnsRetriever::fixDate( char *date, char *time ) {\n\tint year = (date[7]-48)*10 + (date[8]-48);\n\tstring sVal;\n\tif ( year > 80) {\n\t sVal.append (1, '1');\n\t sVal.append( 1, '9');\n\t}\n\telse {\n\t sVal.append( 1, '2');\n\t sVal.append( 1, '0');\n\t}\n\tsVal.append( 1, date[7]);\n\tsVal.append( 1, date[8]);\n\tsVal.append(1, '-');\n\tif ( date[3] == 'J' ) {\n\t if ( date[4] == 'A' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '1');\n\t }\n\t else if (date[5] == 'N') {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '6');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '7');\n\t }\n\t}\n\telse if ( date[3] == 'F' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '2');\n\t}\n\telse if ( date[3] == 'M' ) {\n\t if ( date[5] == 'R' ) {\n\t sVal.append(1, '0');\n\t sVal.append(1, '3');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '5');\n\t }\n\t}\n\telse if ( date[3] == 'A' ) {\n\t if ( date[5] == 'R' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '4');\n\t }\n\t else {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '8');\n\t }\n\t}\n\telse if ( date[3] == 'S' ) {\n\t sVal.append( 1, '0');\n\t sVal.append( 1, '9');\n\t}\n\telse if ( date[3] == 'O' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '0');\n\t}\n\telse if ( date[3] == 'N' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '1');\n\t}\n\telse if ( date[3] == 'D' ) {\n\t sVal.append( 1, '1');\n\t sVal.append( 1, '2');\n\t}\n\tsVal.append(1, '-');\n\tsVal.append(1, date[0]);\n\tsVal.append(1, date[1]);\n\tsVal.append(1, 'T');\n\tint ii;\n\tfor (ii = 0; ii < 8; ii++ ) {\n\t sVal.append(1, time[ii]);\n\t}\n\tsVal.append(1, '.');\n\tsVal.append(1, '0');\n\tsVal.append(1, '0');\n\tsVal.append(1, '-');\n\tsVal.append(1, '0');\n\tsVal.append(1, '6');\n\tsVal.append(1, ':');\n\tsVal.append(1, '0');\n\tsVal.append(1, '0');\n\tsVal.append(1, '\\0');\n\n return sVal;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <V8Runtime.h>\n#include <JNIUtil.h>\n#include <TypeConverter.h>\n\nnamespace titanium\n{\n\t\/* static *\/\n\tvoid V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)\n\t{\n\t\tjobject v8Object = (jobject) parameter;\n\n\t\tref.Dispose();\n\t\tJNIUtil::getJNIEnv()->DeleteGlobalRef(v8Object);\n\t}\n\n\t\/* static *\/\n\tjobject V8Runtime::newObject(Handle<Object> object)\n\t{\n\t\tHandleScope scope;\n\n\t\tPersistent<Object> *persistent = new Persistent<Object>(object);\n\t\tJNIEnv *env = JNIUtil::getJNIEnv();\n\t\tif (!env) return NULL;\n\n\t\tjobject v8Object = env->NewGlobalRef(env->NewObject(JNIUtil::v8ObjectClass,\n\t\t\tJNIUtil::v8ObjectInitMethod, reinterpret_cast<jlong>(persistent)));\n\n\t\tpersistent->MakeWeak(reinterpret_cast<void*>(v8Object), V8Runtime::collectWeakRef);\n\t\treturn v8Object;\n\t}\n}\n\n\nextern \"C\" void\nJava_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jclass clazz)\n{\n\ttitanium::JNIUtil::initCache(env);\n}\n\nextern \"C\" jint JNI_OnLoad(JavaVM *vm, void *reserved)\n{\n\ttitanium::JNIUtil::javaVm = vm;\n\treturn JNI_VERSION_1_4;\n}\n<commit_msg>use a weak reference as well as a standard persistent handle for Java V8Objects<commit_after>#include <V8Runtime.h>\n\n#include <AndroidUtil.h>\n#include <JNIUtil.h>\n#include <TypeConverter.h>\n\n#define TAG \"V8Runtime\"\n\nnamespace titanium\n{\n\t\/* static *\/\n\tvoid V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)\n\t{\n\t\tjobject v8Object = (jobject) parameter;\n\n\t\tref.Dispose();\n\t\tJNIUtil::getJNIEnv()->DeleteGlobalRef(v8Object);\n\t}\n\n\t\/* static *\/\n\tjobject V8Runtime::newObject(Handle<Object> object)\n\t{\n\t\tHandleScope scope;\n\t\tLOGI(TAG, \"Creating new object...\");\n\n\t\tJNIEnv *env = JNIUtil::getJNIEnv();\n\t\tif (!env) return NULL;\n\n\t\tjlong ptr = reinterpret_cast<jlong>(*Persistent<Object>::New(object));\n\t\tjobject v8Object = env->NewGlobalRef(env->NewObject(JNIUtil::v8ObjectClass,\n\t\t\tJNIUtil::v8ObjectInitMethod, ptr));\n\n\t\t\/\/ make a 2nd persistent weakref so we can be informed of GC\n\t\tPersistent<Object> weak = Persistent<Object>::New(object);\n\t\tweak.MakeWeak(reinterpret_cast<void*>(v8Object), V8Runtime::collectWeakRef);\n\t\treturn v8Object;\n\t}\n}\n\n\nextern \"C\" void\nJava_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jclass clazz)\n{\n\ttitanium::JNIUtil::initCache(env);\n}\n\nextern \"C\" jint JNI_OnLoad(JavaVM *vm, void *reserved)\n{\n\ttitanium::JNIUtil::javaVm = vm;\n\treturn JNI_VERSION_1_4;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <boost\/filesystem.hpp>\n\n#include <Core\/Application\/Application.h>\n#include <Core\/CommandLine\/CommandLine.h>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <Core\/Algorithms\/Factory\/HardCodedAlgorithmFactory.h>\n#include <Dataflow\/State\/SimpleMapModuleState.h>\n#include <Dataflow\/Network\/Module.h> \/\/TODO move Reex\n#include <Dataflow\/Engine\/Scheduler\/DesktopExecutionStrategyFactory.h>\n#include <Core\/Command\/GlobalCommandBuilderFromCommandLine.h>\n#include <Core\/Logging\/Log.h>\n#include <Core\/IEPlugin\/IEPluginInit.h>\n#include <Core\/Utils\/Exception.h>\n#include <Core\/Application\/Session\/Session.h>\n\n#ifdef _WIN32\n#include <shlobj.h> \n#include <tlhelp32.h>\n#include <windows.h>\n#include <LMCons.h>\n#include <psapi.h>\n#endif\n\nusing namespace SCIRun::Core;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun::Core::CommandLine;\nusing namespace SCIRun::Core::Commands;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Modules::Factory;\nusing namespace SCIRun::Dataflow::State;\nusing namespace SCIRun::Core::Algorithms;\n\nnamespace SCIRun\n{\n namespace Core\n {\n class ApplicationPrivate\n {\n public:\n CommandLineParser parser;\n boost::filesystem::path app_filepath_;\n boost::filesystem::path app_filename_;\n ApplicationParametersHandle parameters_;\n NetworkEditorControllerHandle controller_;\n };\n }\n}\n\nCORE_SINGLETON_IMPLEMENTATION( Application )\n\nApplication::Application() :\n\tprivate_( new ApplicationPrivate )\n{\n private_->app_filepath_ = boost::filesystem::current_path();\n SessionManager::Instance().initialize(private_->app_filepath_);\n SessionManager::Instance().session()->beginSession();\n}\n\nApplication::~Application()\n{\n SessionManager::Instance().session()->endSession();\n}\n\nvoid Application::shutdown()\n{\n if (!private_)\n Log::get() << NOTICE << \"Application shutdown called with null internals\" << std::endl;\n try\n {\n private_.reset();\n }\n catch (std::exception& e)\n {\n Log::get() << EMERG << \"Unhandled exception during application shutdown: \" << e.what() << std::endl;\n }\n catch (...)\n {\n Log::get() << EMERG << \"Unknown unhandled exception during application shutdown\" << std::endl;\n }\n}\n\nstd::string Application::applicationName() const\n{\n return \"SCIRun\";\n}\n\nApplicationParametersHandle Application::parameters() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n return private_->parameters_;\n}\n\nvoid Application::readCommandLine(int argc, const char* argv[])\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n private_->app_filename_ = boost::filesystem::path( argv[0] );\n private_->app_filepath_ = private_->app_filename_.parent_path();\n private_->parameters_ = private_->parser.parse(argc, argv);\n\n Logging::Log::get().setVerbose(parameters()->verboseMode());\n}\n\nNetworkEditorControllerHandle Application::controller()\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n if (!private_->controller_)\n {\n \/\/\/ @todo: these all get configured\n ModuleFactoryHandle moduleFactory(new HardCodedModuleFactory);\n ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);\n ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory(parameters()->threadMode()));\n AlgorithmFactoryHandle algoFactory(new HardCodedAlgorithmFactory);\n ReexecuteStrategyFactoryHandle reexFactory(new DynamicReexecutionStrategyFactory(parameters()->reexecuteMode()));\n private_->controller_.reset(new NetworkEditorController(moduleFactory, sf, exe, algoFactory, reexFactory));\n\n \/\/\/ @todo: sloppy way to initialize this but similar to v4, oh well\n IEPluginManager::Initialize();\n }\n return private_->controller_;\n}\n\nvoid Application::executeCommandLineRequests(Commands::GlobalCommandFactoryHandle cmdFactory)\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n GlobalCommandBuilderFromCommandLine builder(cmdFactory);\n auto queue = builder.build(parameters());\n queue->runAll();\n}\n\nboost::filesystem::path Application::executablePath() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n return private_->app_filepath_;\n}\n\nstd::string Application::commandHelpString() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n return private_->parser.describe();\n}\n\nstd::string Application::version() const\n{\n\t\/\/\/ @todo:\n \/\/\/return CORE_APPLICATION_VERSION;\n return \"5.0.0 developer version\";\n}\n\n\/\/ following ugly code copied from Seg3D.\n\nbool Application::get_user_directory( boost::filesystem::path& user_dir, bool config_path) const\n{\n#ifdef _WIN32\n TCHAR dir[MAX_PATH];\n\n \/\/ Try to create the local application directory\n \/\/ If it already exists return the name of the directory.\n\n if( config_path )\n {\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_LOCAL_APPDATA, 0, 0, dir ) ) )\n {\n user_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n }\n else\n {\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_MYDOCUMENTS, 0, 0, dir ) ) )\n {\n user_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n }\n#else\n\n if ( getenv( \"HOME\" ) )\n {\n user_dir = boost::filesystem::path( getenv( \"HOME\" ) );\n\n if (! boost::filesystem::exists( user_dir ) )\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false; \n }\n\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n#endif\n}\n\n\nbool Application::get_user_desktop_directory( boost::filesystem::path& user_desktop_dir ) const\n{\n#ifdef _WIN32\n TCHAR dir[MAX_PATH];\n\n \/\/ Try to create the local application directory\n \/\/ If it already exists return the name of the directory.\n\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_DESKTOPDIRECTORY, 0, 0, dir ) ) )\n {\n user_desktop_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false;\n }\n\n\n#else\n\n if ( getenv( \"HOME\" ) )\n {\n user_desktop_dir = boost::filesystem::path( getenv( \"HOME\" ) ) \/ \"Desktop\" \/ \"\";\n\n if (! boost::filesystem::exists( user_desktop_dir ) )\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false; \n }\n\n\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false;\n }\n#endif\n}\n\nbool Application::get_config_directory( boost::filesystem::path& config_dir ) const\n{\n boost::filesystem::path user_dir;\n if ( !( get_user_directory( user_dir, true ) ) ) return false;\n\n#ifdef _WIN32\t\n config_dir = user_dir \/ applicationName();\n#else\n std::string dot_app_name = std::string( \".\" ) + applicationName();\n config_dir = user_dir \/ dot_app_name;\n#endif\n\n if ( !( boost::filesystem::exists( config_dir ) ) )\n {\n if ( !( boost::filesystem::create_directory( config_dir ) ) )\n {\n Log::get() << ERROR_LOG << \"Could not create directory: \" << config_dir.string();\n return false;\n }\n\n Log::get() << INFO << \"Created directory: \" << config_dir.string();\n }\n\n return true;\n}\n\nbool Application::get_user_name( std::string& user_name ) const\n{\n#ifdef _WIN32\n TCHAR name[UNLEN+1];\n DWORD length = UNLEN;\n\n if ( GetUserName( name, &length ) )\n {\n user_name = std::string( name );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not resolve user name.\";\n return false;\t\n }\n#else\n if ( getenv( \"USER\" ) )\n {\n user_name = std::string( getenv( \"USER\" ) );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not resolve user name.\";\n return false;\n }\n#endif\n\n}\n\n\/*\nint Application::GetMajorVersion()\n{\n\treturn CORE_APPLICATION_MAJOR_VERSION;\n}\n\nint Application::GetMinorVersion()\n{\n\treturn CORE_APPLICATION_MINOR_VERSION;\n}\n\nint Application::GetPatchVersion()\n{\n\treturn CORE_APPLICATION_PATCH_VERSION;\n}\n\nbool Application::Is64Bit()\n{\n\treturn ( sizeof(void *) == 8 );\n}\n\nbool Application::Is32Bit()\n{\n\treturn ( sizeof(void *) == 4 );\n}\n\nstd::string Application::GetApplicationName()\n{\n\treturn CORE_APPLICATION_NAME;\n}\n\nstd::string Application::GetReleaseName()\n{\n\treturn CORE_APPLICATION_RELEASE;\n}\n\nstd::string Application::GetApplicationNameAndVersion()\n{\n\treturn GetApplicationName() + \" \" + GetReleaseName() + \" \" + GetVersion();\n}\n\nstd::string Application::GetAbout()\n{\n\treturn CORE_APPLICATION_ABOUT;\n}\n*\/\n<commit_msg>Add rest of includes<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <boost\/filesystem.hpp>\n\n#include <Core\/Application\/Application.h>\n#include <Core\/CommandLine\/CommandLine.h>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <Core\/Algorithms\/Factory\/HardCodedAlgorithmFactory.h>\n#include <Dataflow\/State\/SimpleMapModuleState.h>\n#include <Dataflow\/Network\/Module.h> \/\/TODO move Reex\n#include <Dataflow\/Engine\/Scheduler\/DesktopExecutionStrategyFactory.h>\n#include <Core\/Command\/GlobalCommandBuilderFromCommandLine.h>\n#include <Core\/Logging\/Log.h>\n#include <Core\/IEPlugin\/IEPluginInit.h>\n#include <Core\/Utils\/Exception.h>\n#include <Core\/Application\/Session\/Session.h>\n\n\/\/ Includes for platform specific functions to get directory to store temp files and user data\n#ifdef _WIN32\n#include <shlobj.h> \n#include <tlhelp32.h>\n#include <windows.h>\n#include <LMCons.h>\n#include <psapi.h>\n#else\n#include <stdlib.h>\n#include <sys\/types.h>\n#ifndef __APPLE__\n#include <unistd.h>\n#include <sys\/sysinfo.h>\n#else\n#include <unistd.h>\n#include <sys\/utsname.h>\n#include <sys\/sysctl.h>\n#include <sys\/param.h>\n#include <sys\/mount.h>\n#endif\n#endif\n\nusing namespace SCIRun::Core;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun::Core::CommandLine;\nusing namespace SCIRun::Core::Commands;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Modules::Factory;\nusing namespace SCIRun::Dataflow::State;\nusing namespace SCIRun::Core::Algorithms;\n\nnamespace SCIRun\n{\n namespace Core\n {\n class ApplicationPrivate\n {\n public:\n CommandLineParser parser;\n boost::filesystem::path app_filepath_;\n boost::filesystem::path app_filename_;\n ApplicationParametersHandle parameters_;\n NetworkEditorControllerHandle controller_;\n };\n }\n}\n\nCORE_SINGLETON_IMPLEMENTATION( Application )\n\nApplication::Application() :\n\tprivate_( new ApplicationPrivate )\n{\n private_->app_filepath_ = boost::filesystem::current_path();\n SessionManager::Instance().initialize(private_->app_filepath_);\n SessionManager::Instance().session()->beginSession();\n}\n\nApplication::~Application()\n{\n SessionManager::Instance().session()->endSession();\n}\n\nvoid Application::shutdown()\n{\n if (!private_)\n Log::get() << NOTICE << \"Application shutdown called with null internals\" << std::endl;\n try\n {\n private_.reset();\n }\n catch (std::exception& e)\n {\n Log::get() << EMERG << \"Unhandled exception during application shutdown: \" << e.what() << std::endl;\n }\n catch (...)\n {\n Log::get() << EMERG << \"Unknown unhandled exception during application shutdown\" << std::endl;\n }\n}\n\nstd::string Application::applicationName() const\n{\n return \"SCIRun\";\n}\n\nApplicationParametersHandle Application::parameters() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n return private_->parameters_;\n}\n\nvoid Application::readCommandLine(int argc, const char* argv[])\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n private_->app_filename_ = boost::filesystem::path( argv[0] );\n private_->app_filepath_ = private_->app_filename_.parent_path();\n private_->parameters_ = private_->parser.parse(argc, argv);\n\n Logging::Log::get().setVerbose(parameters()->verboseMode());\n}\n\nNetworkEditorControllerHandle Application::controller()\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n if (!private_->controller_)\n {\n \/\/\/ @todo: these all get configured\n ModuleFactoryHandle moduleFactory(new HardCodedModuleFactory);\n ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);\n ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory(parameters()->threadMode()));\n AlgorithmFactoryHandle algoFactory(new HardCodedAlgorithmFactory);\n ReexecuteStrategyFactoryHandle reexFactory(new DynamicReexecutionStrategyFactory(parameters()->reexecuteMode()));\n private_->controller_.reset(new NetworkEditorController(moduleFactory, sf, exe, algoFactory, reexFactory));\n\n \/\/\/ @todo: sloppy way to initialize this but similar to v4, oh well\n IEPluginManager::Initialize();\n }\n return private_->controller_;\n}\n\nvoid Application::executeCommandLineRequests(Commands::GlobalCommandFactoryHandle cmdFactory)\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n GlobalCommandBuilderFromCommandLine builder(cmdFactory);\n auto queue = builder.build(parameters());\n queue->runAll();\n}\n\nboost::filesystem::path Application::executablePath() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n return private_->app_filepath_;\n}\n\nstd::string Application::commandHelpString() const\n{\n ENSURE_NOT_NULL(private_, \"Application internals are uninitialized!\");\n\n return private_->parser.describe();\n}\n\nstd::string Application::version() const\n{\n\t\/\/\/ @todo:\n \/\/\/return CORE_APPLICATION_VERSION;\n return \"5.0.0 developer version\";\n}\n\n\/\/ following ugly code copied from Seg3D.\n\nbool Application::get_user_directory( boost::filesystem::path& user_dir, bool config_path) const\n{\n#ifdef _WIN32\n TCHAR dir[MAX_PATH];\n\n \/\/ Try to create the local application directory\n \/\/ If it already exists return the name of the directory.\n\n if( config_path )\n {\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_LOCAL_APPDATA, 0, 0, dir ) ) )\n {\n user_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n }\n else\n {\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_MYDOCUMENTS, 0, 0, dir ) ) )\n {\n user_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n }\n#else\n\n if ( getenv( \"HOME\" ) )\n {\n user_dir = boost::filesystem::path( getenv( \"HOME\" ) );\n\n if (! boost::filesystem::exists( user_dir ) )\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false; \n }\n\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user directory.\";\n return false;\n }\n#endif\n}\n\n\nbool Application::get_user_desktop_directory( boost::filesystem::path& user_desktop_dir ) const\n{\n#ifdef _WIN32\n TCHAR dir[MAX_PATH];\n\n \/\/ Try to create the local application directory\n \/\/ If it already exists return the name of the directory.\n\n if ( SUCCEEDED( SHGetFolderPath( 0, CSIDL_DESKTOPDIRECTORY, 0, 0, dir ) ) )\n {\n user_desktop_dir = boost::filesystem::path( dir );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false;\n }\n\n\n#else\n\n if ( getenv( \"HOME\" ) )\n {\n user_desktop_dir = boost::filesystem::path( getenv( \"HOME\" ) ) \/ \"Desktop\" \/ \"\";\n\n if (! boost::filesystem::exists( user_desktop_dir ) )\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false; \n }\n\n\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not get user desktop directory.\";\n return false;\n }\n#endif\n}\n\nbool Application::get_config_directory( boost::filesystem::path& config_dir ) const\n{\n boost::filesystem::path user_dir;\n if ( !( get_user_directory( user_dir, true ) ) ) return false;\n\n#ifdef _WIN32\t\n config_dir = user_dir \/ applicationName();\n#else\n std::string dot_app_name = std::string( \".\" ) + applicationName();\n config_dir = user_dir \/ dot_app_name;\n#endif\n\n if ( !( boost::filesystem::exists( config_dir ) ) )\n {\n if ( !( boost::filesystem::create_directory( config_dir ) ) )\n {\n Log::get() << ERROR_LOG << \"Could not create directory: \" << config_dir.string();\n return false;\n }\n\n Log::get() << INFO << \"Created directory: \" << config_dir.string();\n }\n\n return true;\n}\n\nbool Application::get_user_name( std::string& user_name ) const\n{\n#ifdef _WIN32\n TCHAR name[UNLEN+1];\n DWORD length = UNLEN;\n\n if ( GetUserName( name, &length ) )\n {\n user_name = std::string( name );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not resolve user name.\";\n return false;\t\n }\n#else\n if ( getenv( \"USER\" ) )\n {\n user_name = std::string( getenv( \"USER\" ) );\n return true;\n }\n else\n {\n Log::get() << ERROR_LOG << \"Could not resolve user name.\";\n return false;\n }\n#endif\n\n}\n\n\/*\nint Application::GetMajorVersion()\n{\n\treturn CORE_APPLICATION_MAJOR_VERSION;\n}\n\nint Application::GetMinorVersion()\n{\n\treturn CORE_APPLICATION_MINOR_VERSION;\n}\n\nint Application::GetPatchVersion()\n{\n\treturn CORE_APPLICATION_PATCH_VERSION;\n}\n\nbool Application::Is64Bit()\n{\n\treturn ( sizeof(void *) == 8 );\n}\n\nbool Application::Is32Bit()\n{\n\treturn ( sizeof(void *) == 4 );\n}\n\nstd::string Application::GetApplicationName()\n{\n\treturn CORE_APPLICATION_NAME;\n}\n\nstd::string Application::GetReleaseName()\n{\n\treturn CORE_APPLICATION_RELEASE;\n}\n\nstd::string Application::GetApplicationNameAndVersion()\n{\n\treturn GetApplicationName() + \" \" + GetReleaseName() + \" \" + GetVersion();\n}\n\nstd::string Application::GetAbout()\n{\n\treturn CORE_APPLICATION_ABOUT;\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/window_capturer.h\"\n\n#include <assert.h>\n\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame_win.h\"\n#include \"webrtc\/modules\/desktop_capture\/win\/window_capture_utils.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\nnamespace webrtc {\n\nnamespace {\n\ntypedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);\n\n\/\/ Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if\n\/\/ error occurs.\nstd::string Utf16ToUtf8(const WCHAR* str) {\n int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n NULL, 0, NULL, NULL);\n if (len_utf8 <= 0)\n return std::string();\n std::string result(len_utf8, '\\0');\n int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n &*(result.begin()), len_utf8, NULL, NULL);\n if (rv != len_utf8)\n assert(false);\n\n return result;\n}\n\nBOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {\n WindowCapturer::WindowList* list =\n reinterpret_cast<WindowCapturer::WindowList*>(param);\n\n \/\/ Skip windows that are invisible, minimized, have no title, or are owned,\n \/\/ unless they have the app window style set.\n int len = GetWindowTextLength(hwnd);\n HWND owner = GetWindow(hwnd, GW_OWNER);\n LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||\n (owner && !(exstyle & WS_EX_APPWINDOW))) {\n return TRUE;\n }\n\n \/\/ Skip the Program Manager window and the Start button.\n const size_t kClassLength = 256;\n WCHAR class_name[kClassLength];\n GetClassName(hwnd, class_name, kClassLength);\n \/\/ Skip Program Manager window and the Start button. This is the same logic\n \/\/ that's used in Win32WindowPicker in libjingle. Consider filtering other\n \/\/ windows as well (e.g. toolbars).\n if (wcscmp(class_name, L\"Progman\") == 0 || wcscmp(class_name, L\"Button\") == 0)\n return TRUE;\n\n WindowCapturer::Window window;\n window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);\n\n const size_t kTitleLength = 500;\n WCHAR window_title[kTitleLength];\n \/\/ Truncate the title if it's longer than kTitleLength.\n GetWindowText(hwnd, window_title, kTitleLength);\n window.title = Utf16ToUtf8(window_title);\n\n \/\/ Skip windows when we failed to convert the title or it is empty.\n if (window.title.empty())\n return TRUE;\n\n list->push_back(window);\n\n return TRUE;\n}\n\nclass WindowCapturerWin : public WindowCapturer {\n public:\n WindowCapturerWin();\n virtual ~WindowCapturerWin();\n\n \/\/ WindowCapturer interface.\n virtual bool GetWindowList(WindowList* windows) OVERRIDE;\n virtual bool SelectWindow(WindowId id) OVERRIDE;\n virtual bool BringSelectedWindowToFront() OVERRIDE;\n\n \/\/ DesktopCapturer interface.\n virtual void Start(Callback* callback) OVERRIDE;\n virtual void Capture(const DesktopRegion& region) OVERRIDE;\n\n private:\n bool IsAeroEnabled();\n\n Callback* callback_;\n\n \/\/ HWND and HDC for the currently selected window or NULL if window is not\n \/\/ selected.\n HWND window_;\n\n \/\/ dwmapi.dll is used to determine if desktop compositing is enabled.\n HMODULE dwmapi_library_;\n DwmIsCompositionEnabledFunc is_composition_enabled_func_;\n\n DesktopSize previous_size_;\n\n DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);\n};\n\nWindowCapturerWin::WindowCapturerWin()\n : callback_(NULL),\n window_(NULL) {\n \/\/ Try to load dwmapi.dll dynamically since it is not available on XP.\n dwmapi_library_ = LoadLibrary(L\"dwmapi.dll\");\n if (dwmapi_library_) {\n is_composition_enabled_func_ =\n reinterpret_cast<DwmIsCompositionEnabledFunc>(\n GetProcAddress(dwmapi_library_, \"DwmIsCompositionEnabled\"));\n assert(is_composition_enabled_func_);\n } else {\n is_composition_enabled_func_ = NULL;\n }\n}\n\nWindowCapturerWin::~WindowCapturerWin() {\n if (dwmapi_library_)\n FreeLibrary(dwmapi_library_);\n}\n\nbool WindowCapturerWin::IsAeroEnabled() {\n BOOL result = FALSE;\n if (is_composition_enabled_func_)\n is_composition_enabled_func_(&result);\n return result != FALSE;\n}\n\nbool WindowCapturerWin::GetWindowList(WindowList* windows) {\n WindowList result;\n LPARAM param = reinterpret_cast<LPARAM>(&result);\n if (!EnumWindows(&WindowsEnumerationHandler, param))\n return false;\n windows->swap(result);\n return true;\n}\n\nbool WindowCapturerWin::SelectWindow(WindowId id) {\n HWND window = reinterpret_cast<HWND>(id);\n if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))\n return false;\n window_ = window;\n previous_size_.set(0, 0);\n return true;\n}\n\nbool WindowCapturerWin::BringSelectedWindowToFront() {\n if (!window_)\n return false;\n\n if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))\n return false;\n\n return SetForegroundWindow(window_) != 0;\n}\n\nvoid WindowCapturerWin::Start(Callback* callback) {\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n}\n\nvoid WindowCapturerWin::Capture(const DesktopRegion& region) {\n if (!window_) {\n LOG(LS_ERROR) << \"Window hasn't been selected: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n \/\/ Stop capturing if the window has been closed or hidden.\n if (!IsWindow(window_) || !IsWindowVisible(window_)) {\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n DesktopRect original_rect;\n DesktopRect cropped_rect;\n if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {\n LOG(LS_WARNING) << \"Failed to get window info: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC window_dc = GetWindowDC(window_);\n if (!window_dc) {\n LOG(LS_WARNING) << \"Failed to get window DC: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(\n cropped_rect.size(), NULL, window_dc));\n if (!frame.get()) {\n ReleaseDC(window_, window_dc);\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC mem_dc = CreateCompatibleDC(window_dc);\n HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());\n BOOL result = FALSE;\n\n \/\/ When desktop composition (Aero) is enabled each window is rendered to a\n \/\/ private buffer allowing BitBlt() to get the window content even if the\n \/\/ window is occluded. PrintWindow() is slower but lets rendering the window\n \/\/ contents to an off-screen device context when Aero is not available.\n \/\/ PrintWindow() is not supported by some applications.\n \/\/\n \/\/ If Aero is enabled, we prefer BitBlt() because it's faster and avoids\n \/\/ window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may\n \/\/ render occluding windows on top of the desired window.\n \/\/\n \/\/ When composition is enabled the DC returned by GetWindowDC() doesn't always\n \/\/ have window frame rendered correctly. Windows renders it only once and then\n \/\/ caches the result between captures. We hack it around by calling\n \/\/ PrintWindow() whenever window size changes, including the first time of\n \/\/ capturing - it somehow affects what we get from BitBlt() on the subsequent\n \/\/ captures.\n\n if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {\n result = PrintWindow(window_, mem_dc, 0);\n }\n\n \/\/ Aero is enabled or PrintWindow() failed, use BitBlt.\n if (!result) {\n result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),\n window_dc,\n cropped_rect.left() - original_rect.left(),\n cropped_rect.top() - original_rect.top(),\n SRCCOPY);\n }\n\n SelectObject(mem_dc, previous_object);\n DeleteDC(mem_dc);\n ReleaseDC(window_, window_dc);\n\n previous_size_ = frame->size();\n\n frame->mutable_updated_region()->SetRect(\n DesktopRect::MakeSize(frame->size()));\n\n if (!result) {\n LOG(LS_ERROR) << \"Both PrintWindow() and BitBlt() failed.\";\n frame.reset();\n }\n\n callback_->OnCaptureCompleted(frame.release());\n}\n\n} \/\/ namespace\n\n\/\/ static\nWindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {\n return new WindowCapturerWin();\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Remove trailing null character from std::string<commit_after>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/window_capturer.h\"\n\n#include <assert.h>\n\n#include \"webrtc\/base\/win32.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame_win.h\"\n#include \"webrtc\/modules\/desktop_capture\/win\/window_capture_utils.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\nnamespace webrtc {\n\nnamespace {\n\ntypedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);\n\nBOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {\n WindowCapturer::WindowList* list =\n reinterpret_cast<WindowCapturer::WindowList*>(param);\n\n \/\/ Skip windows that are invisible, minimized, have no title, or are owned,\n \/\/ unless they have the app window style set.\n int len = GetWindowTextLength(hwnd);\n HWND owner = GetWindow(hwnd, GW_OWNER);\n LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||\n (owner && !(exstyle & WS_EX_APPWINDOW))) {\n return TRUE;\n }\n\n \/\/ Skip the Program Manager window and the Start button.\n const size_t kClassLength = 256;\n WCHAR class_name[kClassLength];\n GetClassName(hwnd, class_name, kClassLength);\n \/\/ Skip Program Manager window and the Start button. This is the same logic\n \/\/ that's used in Win32WindowPicker in libjingle. Consider filtering other\n \/\/ windows as well (e.g. toolbars).\n if (wcscmp(class_name, L\"Progman\") == 0 || wcscmp(class_name, L\"Button\") == 0)\n return TRUE;\n\n WindowCapturer::Window window;\n window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);\n\n const size_t kTitleLength = 500;\n WCHAR window_title[kTitleLength];\n \/\/ Truncate the title if it's longer than kTitleLength.\n GetWindowText(hwnd, window_title, kTitleLength);\n window.title = rtc::ToUtf8(window_title);\n\n \/\/ Skip windows when we failed to convert the title or it is empty.\n if (window.title.empty())\n return TRUE;\n\n list->push_back(window);\n\n return TRUE;\n}\n\nclass WindowCapturerWin : public WindowCapturer {\n public:\n WindowCapturerWin();\n virtual ~WindowCapturerWin();\n\n \/\/ WindowCapturer interface.\n virtual bool GetWindowList(WindowList* windows) OVERRIDE;\n virtual bool SelectWindow(WindowId id) OVERRIDE;\n virtual bool BringSelectedWindowToFront() OVERRIDE;\n\n \/\/ DesktopCapturer interface.\n virtual void Start(Callback* callback) OVERRIDE;\n virtual void Capture(const DesktopRegion& region) OVERRIDE;\n\n private:\n bool IsAeroEnabled();\n\n Callback* callback_;\n\n \/\/ HWND and HDC for the currently selected window or NULL if window is not\n \/\/ selected.\n HWND window_;\n\n \/\/ dwmapi.dll is used to determine if desktop compositing is enabled.\n HMODULE dwmapi_library_;\n DwmIsCompositionEnabledFunc is_composition_enabled_func_;\n\n DesktopSize previous_size_;\n\n DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);\n};\n\nWindowCapturerWin::WindowCapturerWin()\n : callback_(NULL),\n window_(NULL) {\n \/\/ Try to load dwmapi.dll dynamically since it is not available on XP.\n dwmapi_library_ = LoadLibrary(L\"dwmapi.dll\");\n if (dwmapi_library_) {\n is_composition_enabled_func_ =\n reinterpret_cast<DwmIsCompositionEnabledFunc>(\n GetProcAddress(dwmapi_library_, \"DwmIsCompositionEnabled\"));\n assert(is_composition_enabled_func_);\n } else {\n is_composition_enabled_func_ = NULL;\n }\n}\n\nWindowCapturerWin::~WindowCapturerWin() {\n if (dwmapi_library_)\n FreeLibrary(dwmapi_library_);\n}\n\nbool WindowCapturerWin::IsAeroEnabled() {\n BOOL result = FALSE;\n if (is_composition_enabled_func_)\n is_composition_enabled_func_(&result);\n return result != FALSE;\n}\n\nbool WindowCapturerWin::GetWindowList(WindowList* windows) {\n WindowList result;\n LPARAM param = reinterpret_cast<LPARAM>(&result);\n if (!EnumWindows(&WindowsEnumerationHandler, param))\n return false;\n windows->swap(result);\n return true;\n}\n\nbool WindowCapturerWin::SelectWindow(WindowId id) {\n HWND window = reinterpret_cast<HWND>(id);\n if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))\n return false;\n window_ = window;\n previous_size_.set(0, 0);\n return true;\n}\n\nbool WindowCapturerWin::BringSelectedWindowToFront() {\n if (!window_)\n return false;\n\n if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_))\n return false;\n\n return SetForegroundWindow(window_) != 0;\n}\n\nvoid WindowCapturerWin::Start(Callback* callback) {\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n}\n\nvoid WindowCapturerWin::Capture(const DesktopRegion& region) {\n if (!window_) {\n LOG(LS_ERROR) << \"Window hasn't been selected: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n \/\/ Stop capturing if the window has been closed or hidden.\n if (!IsWindow(window_) || !IsWindowVisible(window_)) {\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n DesktopRect original_rect;\n DesktopRect cropped_rect;\n if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) {\n LOG(LS_WARNING) << \"Failed to get window info: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC window_dc = GetWindowDC(window_);\n if (!window_dc) {\n LOG(LS_WARNING) << \"Failed to get window DC: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(\n cropped_rect.size(), NULL, window_dc));\n if (!frame.get()) {\n ReleaseDC(window_, window_dc);\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC mem_dc = CreateCompatibleDC(window_dc);\n HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap());\n BOOL result = FALSE;\n\n \/\/ When desktop composition (Aero) is enabled each window is rendered to a\n \/\/ private buffer allowing BitBlt() to get the window content even if the\n \/\/ window is occluded. PrintWindow() is slower but lets rendering the window\n \/\/ contents to an off-screen device context when Aero is not available.\n \/\/ PrintWindow() is not supported by some applications.\n \/\/\n \/\/ If Aero is enabled, we prefer BitBlt() because it's faster and avoids\n \/\/ window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may\n \/\/ render occluding windows on top of the desired window.\n \/\/\n \/\/ When composition is enabled the DC returned by GetWindowDC() doesn't always\n \/\/ have window frame rendered correctly. Windows renders it only once and then\n \/\/ caches the result between captures. We hack it around by calling\n \/\/ PrintWindow() whenever window size changes, including the first time of\n \/\/ capturing - it somehow affects what we get from BitBlt() on the subsequent\n \/\/ captures.\n\n if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) {\n result = PrintWindow(window_, mem_dc, 0);\n }\n\n \/\/ Aero is enabled or PrintWindow() failed, use BitBlt.\n if (!result) {\n result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),\n window_dc,\n cropped_rect.left() - original_rect.left(),\n cropped_rect.top() - original_rect.top(),\n SRCCOPY);\n }\n\n SelectObject(mem_dc, previous_object);\n DeleteDC(mem_dc);\n ReleaseDC(window_, window_dc);\n\n previous_size_ = frame->size();\n\n frame->mutable_updated_region()->SetRect(\n DesktopRect::MakeSize(frame->size()));\n\n if (!result) {\n LOG(LS_ERROR) << \"Both PrintWindow() and BitBlt() failed.\";\n frame.reset();\n }\n\n callback_->OnCaptureCompleted(frame.release());\n}\n\n} \/\/ namespace\n\n\/\/ static\nWindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) {\n return new WindowCapturerWin();\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char const *argv[])\n{\n\tint a[] = {1, 2, 4, 5, 6};\n\n\tint size = sizeof(a)\/sizeof(a[0]);\n\tint x1 = a[0], x2 = 1;\n\tfor (int i = 1; i < size; ++i)\n\t{\n\t\tx1 ^= a[i];\n\t}\n\tfor (int i = 2; i <= size + 1; ++i)\n\t{\n\t\tx2 ^= i;\n\t}\n\tcout<<(x1^x2)<<endl;\n\n\treturn 0;\n}<commit_msg>two approaches :sunglasses:<commit_after>#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char const *argv[])\n{\n\tint a[] = {1, 2, 4, 5, 6};\n\n\tint size = sizeof(a)\/sizeof(a[0]);\n\t\/* APPROACH 1*\/\n\t\/\/ int x1 = a[0], x2 = 1;\n\t\/\/ for (int i = 1; i < size; ++i)\n\t\/\/ {\n\t\/\/ \tx1 ^= a[i];\n\t\/\/ }\n\t\/\/ for (int i = 2; i <= size + 1; ++i)\n\t\/\/ {\n\t\/\/ \tx2 ^= i;\n\t\/\/ }\n\t\/\/ cout<<(x1^x2)<<endl;\n\n\t\/* APPROACH 2*\/\n\n\tint sum = (size+1)*(size +2)\/2;\n\tint temp = 0;\n\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\ttemp += a[i];\n\t}\n\tcout<<sum - temp;\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Video.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/04\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Video.hpp\"\n\nusing namespace AppleII::Video;\n\nnamespace {\n\nstruct ScaledByteFiller {\n\tScaledByteFiller() {\n\t\tVideoBase::setup_tables();\n\t}\n} throwaway;\n\n}\n\nVideoBase::VideoBase() :\n\tcrt_(new Outputs::CRT::CRT(455, 1, Outputs::CRT::DisplayType::NTSC60, 1)) {\n\n\t\/\/ Set a composite sampling function that assumes 1bpp input, and uses just 7 bits per byte.\n\tcrt_->set_composite_sampling_function(\n\t\t\"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = texture(sampler, coordinate).r;\"\n\t\t\t\"texValue <<= int(icoordinate.x) % 7;\"\n\t\t\t\"return float(texValue & 64u);\"\n\t\t\"}\");\n\tcrt_->set_integer_coordinate_multiplier(7.0f);\n\n\t\/\/ Show only the centre 75% of the TV frame.\n\tcrt_->set_video_signal(Outputs::CRT::VideoSignal::Composite);\n\tcrt_->set_visible_area(Outputs::CRT::Rect(0.115f, 0.117f, 0.77f, 0.77f));\n}\n\nOutputs::CRT::CRT *VideoBase::get_crt() {\n\treturn crt_.get();\n}\n\nuint16_t VideoBase::scaled_byte[256];\nuint16_t VideoBase::low_resolution_patterns[2][16];\n\nvoid VideoBase::setup_tables() {\n\tfor(int c = 0; c < 128; ++c) {\n\t\tconst uint16_t value =\n\t\t\t((c & 0x01) ? 0x0003 : 0x0000) |\n\t\t\t((c & 0x02) ? 0x000c : 0x0000) |\n\t\t\t((c & 0x04) ? 0x0030 : 0x0000) |\n\t\t\t((c & 0x08) ? 0x0140 : 0x0000) |\n\t\t\t((c & 0x10) ? 0x0600 : 0x0000) |\n\t\t\t((c & 0x20) ? 0x1800 : 0x0000) |\n\t\t\t((c & 0x40) ? 0x6000 : 0x0000);\n\n\t\tuint8_t *const table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);\n\t\ttable_entry[0] = static_cast<uint8_t>(value >> 8);\n\t\ttable_entry[1] = static_cast<uint8_t>(value & 0xff);\n\t}\n\tfor(int c = 128; c < 256; ++c) {\n\t\tuint8_t *const source_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c & 0x7f]);\n\t\tuint8_t *const destination_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);\n\n\t\tdestination_table_entry[0] = static_cast<uint8_t>(source_table_entry[0] >> 1);\n\t\tdestination_table_entry[1] = static_cast<uint8_t>((source_table_entry[1] >> 1) | ((source_table_entry[0]&1) << 6));\n\t}\n\n\tfor(int c = 0; c < 16; ++c) {\n\t\t\/\/ Produce the whole 28-bit pattern that would cover two bytes.\n\t\tint pattern = 0;\n\t\tfor(int l = 0; l < 7; ++l) {\n\t\t\tpattern <<= 4;\n\t\t\tpattern |= c;\n\t\t}\n\n\t\t\/\/ Pack that 28-bit pattern into the appropriate look-up tables.\n\t\tuint8_t *const left_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[0][c]);\n\t\tuint8_t *const right_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[1][c]);\n\t\tleft_entry[0] = static_cast<uint8_t>(pattern >> 21);\n\t\tleft_entry[1] = static_cast<uint8_t>(pattern >> 14);\n\t\tright_entry[0] = static_cast<uint8_t>(pattern >> 7);\n\t\tright_entry[1] = static_cast<uint8_t>(pattern);\n\t}\n\n\tprintf(\"\");\n}\n\nvoid VideoBase::set_graphics_mode() {\n\tuse_graphics_mode_ = true;\n}\n\nvoid VideoBase::set_text_mode() {\n\tuse_graphics_mode_ = false;\n}\n\nvoid VideoBase::set_mixed_mode(bool mixed_mode) {\n\tmixed_mode_ = mixed_mode;\n}\n\nvoid VideoBase::set_video_page(int page) {\n\tvideo_page_ = page;\n}\n\nvoid VideoBase::set_low_resolution() {\n\tgraphics_mode_ = GraphicsMode::LowRes;\n}\n\nvoid VideoBase::set_high_resolution() {\n\tgraphics_mode_ = GraphicsMode::HighRes;\n}\n\nvoid VideoBase::set_character_rom(const std::vector<uint8_t> &character_rom) {\n\tcharacter_rom_ = character_rom;\n}\n<commit_msg>Reverses bit order of graphics stream; apparently the ROM is backwards.<commit_after>\/\/\n\/\/ Video.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/04\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Video.hpp\"\n\nusing namespace AppleII::Video;\n\nnamespace {\n\nstruct ScaledByteFiller {\n\tScaledByteFiller() {\n\t\tVideoBase::setup_tables();\n\t}\n} throwaway;\n\n}\n\nVideoBase::VideoBase() :\n\tcrt_(new Outputs::CRT::CRT(455, 1, Outputs::CRT::DisplayType::NTSC60, 1)) {\n\n\t\/\/ Set a composite sampling function that assumes 1bpp input, and uses just 7 bits per byte.\n\tcrt_->set_composite_sampling_function(\n\t\t\"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = texture(sampler, coordinate).r;\"\n\t\t\t\"texValue >>= int(icoordinate.x) % 7;\"\n\t\t\t\"return float(texValue & 1u);\"\n\t\t\"}\");\n\tcrt_->set_integer_coordinate_multiplier(7.0f);\n\n\t\/\/ Show only the centre 75% of the TV frame.\n\tcrt_->set_video_signal(Outputs::CRT::VideoSignal::Composite);\n\tcrt_->set_visible_area(Outputs::CRT::Rect(0.115f, 0.117f, 0.77f, 0.77f));\n}\n\nOutputs::CRT::CRT *VideoBase::get_crt() {\n\treturn crt_.get();\n}\n\nuint16_t VideoBase::scaled_byte[256];\nuint16_t VideoBase::low_resolution_patterns[2][16];\n\nvoid VideoBase::setup_tables() {\n\tfor(int c = 0; c < 128; ++c) {\n\t\tconst uint16_t value =\n\t\t\t((c & 0x01) ? 0x0003 : 0x0000) |\n\t\t\t((c & 0x02) ? 0x000c : 0x0000) |\n\t\t\t((c & 0x04) ? 0x0030 : 0x0000) |\n\t\t\t((c & 0x08) ? 0x0140 : 0x0000) |\n\t\t\t((c & 0x10) ? 0x0600 : 0x0000) |\n\t\t\t((c & 0x20) ? 0x1800 : 0x0000) |\n\t\t\t((c & 0x40) ? 0x6000 : 0x0000);\n\n\t\tuint8_t *const table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);\n\t\ttable_entry[0] = static_cast<uint8_t>(value & 0xff);\n\t\ttable_entry[1] = static_cast<uint8_t>(value >> 8);\n\t}\n\tfor(int c = 128; c < 256; ++c) {\n\t\tuint8_t *const source_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c & 0x7f]);\n\t\tuint8_t *const destination_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]);\n\n\t\tdestination_table_entry[0] = static_cast<uint8_t>(source_table_entry[0] << 1);\n\t\tdestination_table_entry[1] = static_cast<uint8_t>((source_table_entry[1] << 1) | (source_table_entry[0] >> 6));\n\t}\n\n\tfor(int c = 0; c < 16; ++c) {\n\t\t\/\/ Produce the whole 28-bit pattern that would cover two columns.\n\t\tconst int reversed_c = ((c&0x1) ? 0x8 : 0x0) | ((c&0x2) ? 0x4 : 0x0) | ((c&0x4) ? 0x2 : 0x0) | ((c&0x8) ? 0x1 : 0x0);\n\t\tint pattern = 0;\n\t\tfor(int l = 0; l < 7; ++l) {\n\t\t\tpattern <<= 4;\n\t\t\tpattern |= reversed_c;\n\t\t}\n\n\t\t\/\/ Pack that 28-bit pattern into the appropriate look-up tables.\n\t\tuint8_t *const left_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[0][c]);\n\t\tuint8_t *const right_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[1][c]);\n\t\tleft_entry[0] = static_cast<uint8_t>(pattern);;\n\t\tleft_entry[1] = static_cast<uint8_t>(pattern >> 7);\n\t\tright_entry[0] = static_cast<uint8_t>(pattern >> 14);\n\t\tright_entry[1] = static_cast<uint8_t>(pattern >> 21);\n\t}\n\n\tprintf(\"\");\n}\n\nvoid VideoBase::set_graphics_mode() {\n\tuse_graphics_mode_ = true;\n}\n\nvoid VideoBase::set_text_mode() {\n\tuse_graphics_mode_ = false;\n}\n\nvoid VideoBase::set_mixed_mode(bool mixed_mode) {\n\tmixed_mode_ = mixed_mode;\n}\n\nvoid VideoBase::set_video_page(int page) {\n\tvideo_page_ = page;\n}\n\nvoid VideoBase::set_low_resolution() {\n\tgraphics_mode_ = GraphicsMode::LowRes;\n}\n\nvoid VideoBase::set_high_resolution() {\n\tgraphics_mode_ = GraphicsMode::HighRes;\n}\n\nvoid VideoBase::set_character_rom(const std::vector<uint8_t> &character_rom) {\n\tcharacter_rom_ = character_rom;\n\tfor(auto &byte : character_rom_) {\n\t\tbyte =\n\t\t\t((byte & 0x40) ? 0x01 : 0x00) |\n\t\t\t((byte & 0x20) ? 0x02 : 0x00) |\n\t\t\t((byte & 0x10) ? 0x04 : 0x00) |\n\t\t\t((byte & 0x08) ? 0x08 : 0x00) |\n\t\t\t((byte & 0x04) ? 0x10 : 0x00) |\n\t\t\t((byte & 0x02) ? 0x20 : 0x00) |\n\t\t\t((byte & 0x01) ? 0x40 : 0x00) |\n\t\t\t(byte & 0x80);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Tobias Leibner\n\n\/\/# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1\n\/\/# define DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING 1\n\n#include \"main.hxx\"\n\n#if HAVE_DUNE_GRID\n# if HAVE_ALUGRID\n# include <dune\/grid\/alugrid.hh>\n# endif\n# include <dune\/grid\/yaspgrid.hh>\n\n# include <dune\/stuff\/common\/type_utils.hh>\n# include <dune\/stuff\/grid\/periodicview.hh>\n# include <dune\/stuff\/grid\/provider\/interface.hh>\n# include <dune\/stuff\/grid\/provider\/cube.hh>\n\nusing namespace Dune;\nusing namespace Stuff;\n\n# define YASPGRIDS \\\n YaspGrid< 1 > \\\n , YaspGrid< 2 > \\\n , YaspGrid< 3 >\n\n# if HAVE_ALUGRID\n# define ALUCUBEGRIDS \\\n ALUGrid< 2, 2, cube, nonconforming > \\\n , ALUGrid< 3, 3, cube, nonconforming >\n\n# define ALUSIMPLEXGRIDS \\\n ALUGrid< 2, 2, simplex, conforming > \\\n , ALUGrid< 3, 3, simplex, conforming >\n# endif \/\/ HAVE_ALUGRID\n\n\ntemplate< class GridImp >\nstruct PeriodicViewTestCube\n : public testing::Test\n{\n typedef GridImp GridType;\n typedef typename GridType::ctype ctype;\n typedef typename GridType::template Codim< 0 >::Geometry GeometryType;\n typedef Dune::Stuff::Grid::Providers::template Cube< GridType > GridProviderType;\n typedef typename GridType::LeafGridView GridViewType;\n typedef typename GridViewType::IndexSet IndexSet;\n typedef typename Dune::Stuff::Grid::template PeriodicGridView< GridViewType > PeriodicGridViewType;\n typedef typename PeriodicGridViewType::template Codim< 0 >::Entity EntityType;\n typedef typename PeriodicGridViewType::template Codim< 0 >::Iterator EntityIteratorType;\n typedef typename Dune::Stuff::Grid::template PeriodicIntersectionIterator< GridViewType > PeriodicIntersectionIteratorType;\n typedef typename Dune::Stuff::Grid::template PeriodicIntersection< GridViewType > PeriodicIntersectionType;\n typedef typename GridViewType::CollectiveCommunication CollectiveCommunication;\n static const size_t dimDomain = GridViewType::dimension;\n\n void check(const bool is_simplex) {\n const bool is_cube = !is_simplex;\n GridProviderType grid_provider = *(GridProviderType::create());\n const std::shared_ptr< const GridType > grid = grid_provider.grid_ptr();\n const GridViewType grid_view = grid->leafGridView();\n const GridViewType& grid_view_ref = grid_view;\n\n std::bitset< dimDomain > periodic_directions;\n \/\/create PeriodicGridviewType that actually is not periodic\n const PeriodicGridViewType non_periodic_grid_view(grid_view_ref, periodic_directions);\n \/\/create PeriodicGridviewType that is periodic only in x-direction\n periodic_directions[0] = 1;\n const PeriodicGridViewType partially_periodic_grid_view(grid_view_ref, periodic_directions);\n \/\/create PeriodicGridviewType that is periodic only in all directions\n periodic_directions.set();\n const PeriodicGridViewType fully_periodic_grid_view(grid_view_ref, periodic_directions);\n\n std::vector< const PeriodicGridViewType* > periodic_grid_view_vector(3);\n periodic_grid_view_vector[0] = &non_periodic_grid_view;\n periodic_grid_view_vector[1] = &partially_periodic_grid_view;\n periodic_grid_view_vector[2] = &fully_periodic_grid_view;\n\n for (size_t variant = 0; variant <= 2; ++variant) {\n const PeriodicGridViewType periodic_grid_view = *(periodic_grid_view_vector[variant]);\n\n \/\/ check interface\n const GridType& DUNE_UNUSED(test_grid) = periodic_grid_view.grid();\n const IndexSet& DUNE_UNUSED(test_indexSet) = periodic_grid_view.indexSet();\n const int codim0_size = periodic_grid_view.size(0);\n EXPECT_EQ(codim0_size, grid_view.size(0));\n if (dimDomain == 1)\n EXPECT_EQ(codim0_size, int(8));\n if (dimDomain == 2 && is_cube)\n EXPECT_EQ(codim0_size, int(8*8));\n if (dimDomain == 2 && is_simplex)\n EXPECT_EQ(codim0_size, int(2*8*8));\n if (dimDomain == 3 && is_cube)\n EXPECT_EQ(codim0_size, int(8*8*8));\n if (dimDomain == 3 && is_simplex)\n EXPECT_EQ(codim0_size, int(6*8*8*8));\n EXPECT_EQ(periodic_grid_view.size(Dune::cube), grid_view.size(Dune::cube));\n EXPECT_EQ(periodic_grid_view.size(Dune::simplex), grid_view.size(Dune::simplex));\n EXPECT_EQ(periodic_grid_view.overlapSize(0), grid_view.overlapSize(0));\n EXPECT_EQ(periodic_grid_view.overlapSize(1), grid_view.overlapSize(1));\n EXPECT_EQ(periodic_grid_view.ghostSize(0), grid_view.ghostSize(0));\n EXPECT_EQ(periodic_grid_view.ghostSize(1), grid_view.ghostSize(1));\n const CollectiveCommunication& DUNE_UNUSED(test_comm) = periodic_grid_view.comm();\n\n size_t neighbor_count = 0;\n size_t boundary_count = 0;\n size_t periodic_count = 0;\n \/\/ iterate over all entities\n const EntityIteratorType it_end = periodic_grid_view.template end< 0 >();\n for (EntityIteratorType it = periodic_grid_view.template begin< 0 >(); it != it_end; ++it) {\n const EntityType& entity = *it;\n EXPECT_TRUE(periodic_grid_view.contains(entity));\n \/\/ iterate over all intersections on current entity\n const PeriodicIntersectionIteratorType i_it_end = periodic_grid_view.iend(entity);\n for (PeriodicIntersectionIteratorType i_it = periodic_grid_view.ibegin(entity); i_it != i_it_end; ++i_it) {\n const PeriodicIntersectionType& intersection = *i_it;\n if (intersection.neighbor()) {\n ++neighbor_count;\n const auto outside = *(intersection.outside());\n \/\/find corresponding intersection in outside\n const auto index_in_outside = intersection.indexInOutside();\n const PeriodicIntersectionType* intersection_in_outside = periodic_grid_view.ibegin(outside).operator->();\n const PeriodicIntersectionIteratorType i_it_outside_end = periodic_grid_view.iend(outside);\n for (PeriodicIntersectionIteratorType i_it_outside = periodic_grid_view.ibegin(outside); i_it_outside != i_it_outside_end; ++i_it_outside) {\n const PeriodicIntersectionType* outside_intersection = i_it_outside.operator->();\n if (outside_intersection->indexInInside() == index_in_outside) {\n intersection_in_outside = outside_intersection;\n }\n }\n \/\/ check outside_intersection coords\n const auto coords_in_outside = intersection.geometryInOutside().center();\n const auto coords_in_outside_2 = intersection_in_outside->geometryInInside().center();\n EXPECT_TRUE(Dune::Stuff::Common::FloatCmp::eq(coords_in_outside, coords_in_outside_2));\n \/\/ check global intersection coords in periodic case\n const auto global_intersection_coords = intersection.geometry().center();\n const auto global_outside_intersection_coords = (*intersection_in_outside).geometry().center();\n size_t coord_difference_count = 0;\n size_t differing_coordinate;\n for (size_t ii = 0; ii < dimDomain; ++ii) {\n if (Dune::Stuff::Common::FloatCmp::ne(global_outside_intersection_coords[ii], global_intersection_coords[ii])) {\n ++coord_difference_count;\n differing_coordinate = ii;\n }\n }\n if (intersection.is_periodic()) {\n EXPECT_EQ(size_t(1), coord_difference_count);\n EXPECT_TRUE((Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(1)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(0)))\n || (Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(0)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(1))));\n ++periodic_count;\n if (variant == 1)\n EXPECT_EQ(size_t(0), differing_coordinate);\n }\n }\n if (intersection.boundary()) {\n ++boundary_count;\n EXPECT_FALSE(intersection.is_periodic());\n EXPECT_FALSE(intersection.neighbor());\n }\n }\n }\n\n if (dimDomain == 1) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*7),neighbor_count);\n EXPECT_EQ(size_t(2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*7+2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*7+2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2), periodic_count);\n }\n }\n if (dimDomain == 2 && is_cube) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*8*7),neighbor_count);\n EXPECT_EQ(size_t(2*8*2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8),neighbor_count);\n EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);\n EXPECT_EQ(size_t(2*8), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8*2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*8*2), periodic_count);\n }\n }\n if (dimDomain == 2 && is_simplex) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(2*8*2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);\n EXPECT_EQ(size_t(2*8), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8*2 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*8*2), periodic_count);\n }\n }\n if (dimDomain == 3 && is_cube) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*3*7*64),neighbor_count);\n EXPECT_EQ(size_t(6*64), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*3*7*64 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(6*64 - 2*64), boundary_count);\n EXPECT_EQ(size_t(2*64), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*3*7*64 + 6*64),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(6*64), periodic_count);\n }\n }\n if (dimDomain == 3 && is_simplex) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(2*6*64), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*2*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(2*6*64 - 2*2*64), boundary_count);\n EXPECT_EQ(size_t(2*2*64), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*6*64), periodic_count);\n }\n }\n }\n }\n};\n\ntemplate< class GridImp >\nstruct PeriodicViewTestSimplex\n : public PeriodicViewTestCube< GridImp >\n{};\n\ntypedef testing::Types< YASPGRIDS\n# if HAVE_ALUGRID\n , ALUCUBEGRIDS\n# endif\n > CubeGridTypes;\n\ntypedef testing::Types<\n# if HAVE_ALUGRID\n ALUSIMPLEXGRIDS\n# endif\n > SimplexGridTypes;\n\n\nTYPED_TEST_CASE(PeriodicViewTestCube, CubeGridTypes);\nTYPED_TEST(PeriodicViewTestCube, checkcube)\n{\n this->check(false);\n}\n\nTYPED_TEST_CASE(PeriodicViewTestSimplex, SimplexGridTypes);\nTYPED_TEST(PeriodicViewTestSimplex, checksimplex)\n{\n this->check(true);\n}\n\n\n#else \/\/ HAVE_DUNE_GRID\n\nTEST(DISABLED_CubeGridProvider, is_default_creatable) {}\nTEST(DISABLED_CubeGridProvider, fulfills_const_interface) {}\nTEST(DISABLED_CubeGridProvider, is_visualizable) {}\n\n#endif \/\/ HAVE_DUNE_GRID\n\n<commit_msg>[test.grid_periodicview] get intersection by value<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Tobias Leibner\n\n\/\/# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1\n\/\/# define DUNE_STUFF_TEST_MAIN_ENABLE_TIMED_LOGGING 1\n\n#include \"main.hxx\"\n\n#if HAVE_DUNE_GRID\n# if HAVE_ALUGRID\n# include <dune\/grid\/alugrid.hh>\n# endif\n# include <dune\/grid\/yaspgrid.hh>\n\n# include <dune\/stuff\/common\/type_utils.hh>\n# include <dune\/stuff\/grid\/periodicview.hh>\n# include <dune\/stuff\/grid\/provider\/interface.hh>\n# include <dune\/stuff\/grid\/provider\/cube.hh>\n\nusing namespace Dune;\nusing namespace Stuff;\n\n# define YASPGRIDS \\\n YaspGrid< 1 > \\\n , YaspGrid< 2 > \\\n , YaspGrid< 3 >\n\n# if HAVE_ALUGRID\n# define ALUCUBEGRIDS \\\n ALUGrid< 2, 2, cube, nonconforming > \\\n , ALUGrid< 3, 3, cube, nonconforming >\n\n# define ALUSIMPLEXGRIDS \\\n ALUGrid< 2, 2, simplex, conforming > \\\n , ALUGrid< 3, 3, simplex, conforming >\n# endif \/\/ HAVE_ALUGRID\n\n\ntemplate< class GridImp >\nstruct PeriodicViewTestCube\n : public testing::Test\n{\n typedef GridImp GridType;\n typedef typename GridType::ctype ctype;\n typedef typename GridType::template Codim< 0 >::Geometry GeometryType;\n typedef Dune::Stuff::Grid::Providers::template Cube< GridType > GridProviderType;\n typedef typename GridType::LeafGridView GridViewType;\n typedef typename GridViewType::IndexSet IndexSet;\n typedef typename Dune::Stuff::Grid::template PeriodicGridView< GridViewType > PeriodicGridViewType;\n typedef typename PeriodicGridViewType::template Codim< 0 >::Entity EntityType;\n typedef typename PeriodicGridViewType::template Codim< 0 >::Iterator EntityIteratorType;\n typedef typename Dune::Stuff::Grid::template PeriodicIntersectionIterator< GridViewType > PeriodicIntersectionIteratorType;\n typedef typename Dune::Stuff::Grid::template PeriodicIntersection< GridViewType > PeriodicIntersectionType;\n typedef typename GridViewType::CollectiveCommunication CollectiveCommunication;\n static const size_t dimDomain = GridViewType::dimension;\n\n void check(const bool is_simplex) {\n const bool is_cube = !is_simplex;\n GridProviderType grid_provider = *(GridProviderType::create());\n const std::shared_ptr< const GridType > grid = grid_provider.grid_ptr();\n const GridViewType grid_view = grid->leafGridView();\n const GridViewType& grid_view_ref = grid_view;\n\n std::bitset< dimDomain > periodic_directions;\n \/\/create PeriodicGridviewType that actually is not periodic\n const PeriodicGridViewType non_periodic_grid_view(grid_view_ref, periodic_directions);\n \/\/create PeriodicGridviewType that is periodic only in x-direction\n periodic_directions[0] = 1;\n const PeriodicGridViewType partially_periodic_grid_view(grid_view_ref, periodic_directions);\n \/\/create PeriodicGridviewType that is periodic only in all directions\n periodic_directions.set();\n const PeriodicGridViewType fully_periodic_grid_view(grid_view_ref, periodic_directions);\n\n std::vector< const PeriodicGridViewType* > periodic_grid_view_vector(3);\n periodic_grid_view_vector[0] = &non_periodic_grid_view;\n periodic_grid_view_vector[1] = &partially_periodic_grid_view;\n periodic_grid_view_vector[2] = &fully_periodic_grid_view;\n\n for (size_t variant = 0; variant <= 2; ++variant) {\n const PeriodicGridViewType periodic_grid_view = *(periodic_grid_view_vector[variant]);\n\n \/\/ check interface\n const GridType& DUNE_UNUSED(test_grid) = periodic_grid_view.grid();\n const IndexSet& DUNE_UNUSED(test_indexSet) = periodic_grid_view.indexSet();\n const int codim0_size = periodic_grid_view.size(0);\n EXPECT_EQ(codim0_size, grid_view.size(0));\n if (dimDomain == 1)\n EXPECT_EQ(codim0_size, int(8));\n if (dimDomain == 2 && is_cube)\n EXPECT_EQ(codim0_size, int(8*8));\n if (dimDomain == 2 && is_simplex)\n EXPECT_EQ(codim0_size, int(2*8*8));\n if (dimDomain == 3 && is_cube)\n EXPECT_EQ(codim0_size, int(8*8*8));\n if (dimDomain == 3 && is_simplex)\n EXPECT_EQ(codim0_size, int(6*8*8*8));\n EXPECT_EQ(periodic_grid_view.size(Dune::cube), grid_view.size(Dune::cube));\n EXPECT_EQ(periodic_grid_view.size(Dune::simplex), grid_view.size(Dune::simplex));\n EXPECT_EQ(periodic_grid_view.overlapSize(0), grid_view.overlapSize(0));\n EXPECT_EQ(periodic_grid_view.overlapSize(1), grid_view.overlapSize(1));\n EXPECT_EQ(periodic_grid_view.ghostSize(0), grid_view.ghostSize(0));\n EXPECT_EQ(periodic_grid_view.ghostSize(1), grid_view.ghostSize(1));\n const CollectiveCommunication& DUNE_UNUSED(test_comm) = periodic_grid_view.comm();\n\n size_t neighbor_count = 0;\n size_t boundary_count = 0;\n size_t periodic_count = 0;\n \/\/ iterate over all entities\n const EntityIteratorType it_end = periodic_grid_view.template end< 0 >();\n for (EntityIteratorType it = periodic_grid_view.template begin< 0 >(); it != it_end; ++it) {\n const EntityType& entity = *it;\n EXPECT_TRUE(periodic_grid_view.contains(entity));\n \/\/ iterate over all intersections on current entity\n const PeriodicIntersectionIteratorType i_it_end = periodic_grid_view.iend(entity);\n for (PeriodicIntersectionIteratorType i_it = periodic_grid_view.ibegin(entity); i_it != i_it_end; ++i_it) {\n const PeriodicIntersectionType& intersection = *i_it;\n if (intersection.neighbor()) {\n ++neighbor_count;\n const auto outside = *(intersection.outside());\n \/\/find corresponding intersection in outside\n const auto index_in_outside = intersection.indexInOutside();\n PeriodicIntersectionType intersection_in_outside = *(periodic_grid_view.ibegin(outside).operator->());\n const PeriodicIntersectionIteratorType i_it_outside_end = periodic_grid_view.iend(outside);\n for (PeriodicIntersectionIteratorType i_it_outside = periodic_grid_view.ibegin(outside); i_it_outside != i_it_outside_end; ++i_it_outside) {\n const PeriodicIntersectionType* outside_intersection = i_it_outside.operator->();\n if (outside_intersection->indexInInside() == index_in_outside) {\n intersection_in_outside = *outside_intersection;\n }\n }\n \/\/ check outside_intersection coords\n const auto coords_in_outside = intersection.geometryInOutside().center();\n const auto coords_in_outside_2 = intersection_in_outside.geometryInInside().center();\n EXPECT_TRUE(Dune::Stuff::Common::FloatCmp::eq(coords_in_outside, coords_in_outside_2));\n \/\/ check global intersection coords in periodic case\n const auto global_intersection_coords = intersection.geometry().center();\n const auto global_outside_intersection_coords = intersection_in_outside.geometry().center();\n size_t coord_difference_count = 0;\n size_t differing_coordinate;\n for (size_t ii = 0; ii < dimDomain; ++ii) {\n if (Dune::Stuff::Common::FloatCmp::ne(global_outside_intersection_coords[ii], global_intersection_coords[ii])) {\n ++coord_difference_count;\n differing_coordinate = ii;\n }\n }\n if (intersection.is_periodic()) {\n EXPECT_EQ(size_t(1), coord_difference_count);\n EXPECT_TRUE((Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(1)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(0)))\n || (Dune::Stuff::Common::FloatCmp::eq(global_outside_intersection_coords[differing_coordinate], ctype(0)) && Dune::Stuff::Common::FloatCmp::eq(global_intersection_coords[differing_coordinate], ctype(1))));\n ++periodic_count;\n if (variant == 1)\n EXPECT_EQ(size_t(0), differing_coordinate);\n }\n }\n if (intersection.boundary()) {\n ++boundary_count;\n EXPECT_FALSE(intersection.is_periodic());\n EXPECT_FALSE(intersection.neighbor());\n }\n }\n }\n\n if (dimDomain == 1) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*7),neighbor_count);\n EXPECT_EQ(size_t(2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*7+2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*7+2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2), periodic_count);\n }\n }\n if (dimDomain == 2 && is_cube) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*8*7),neighbor_count);\n EXPECT_EQ(size_t(2*8*2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8),neighbor_count);\n EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);\n EXPECT_EQ(size_t(2*8), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8*2),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*8*2), periodic_count);\n }\n }\n if (dimDomain == 2 && is_simplex) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(2*8*2), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(2*8*2 - 2*8), boundary_count);\n EXPECT_EQ(size_t(2*8), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*8*7 + 2*8*2 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*8*2), periodic_count);\n }\n }\n if (dimDomain == 3 && is_cube) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*3*7*64),neighbor_count);\n EXPECT_EQ(size_t(6*64), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*3*7*64 + 2*64),neighbor_count);\n EXPECT_EQ(size_t(6*64 - 2*64), boundary_count);\n EXPECT_EQ(size_t(2*64), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*3*7*64 + 6*64),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(6*64), periodic_count);\n }\n }\n if (dimDomain == 3 && is_simplex) {\n if (variant == 0) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(2*6*64), boundary_count);\n EXPECT_EQ(size_t(0), periodic_count);\n }\n if (variant == 1) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*2*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(2*6*64 - 2*2*64), boundary_count);\n EXPECT_EQ(size_t(2*2*64), periodic_count);\n }\n if (variant == 2) {\n EXPECT_EQ(size_t(2*2*3*7*64 + 2*6*64 + 2*6*8*8*8),neighbor_count);\n EXPECT_EQ(size_t(0), boundary_count);\n EXPECT_EQ(size_t(2*6*64), periodic_count);\n }\n }\n }\n }\n};\n\ntemplate< class GridImp >\nstruct PeriodicViewTestSimplex\n : public PeriodicViewTestCube< GridImp >\n{};\n\ntypedef testing::Types< YASPGRIDS\n# if HAVE_ALUGRID\n , ALUCUBEGRIDS\n# endif\n > CubeGridTypes;\n\ntypedef testing::Types<\n# if HAVE_ALUGRID\n ALUSIMPLEXGRIDS\n# endif\n > SimplexGridTypes;\n\n\nTYPED_TEST_CASE(PeriodicViewTestCube, CubeGridTypes);\nTYPED_TEST(PeriodicViewTestCube, checkcube)\n{\n this->check(false);\n}\n\nTYPED_TEST_CASE(PeriodicViewTestSimplex, SimplexGridTypes);\nTYPED_TEST(PeriodicViewTestSimplex, checksimplex)\n{\n this->check(true);\n}\n\n\n#else \/\/ HAVE_DUNE_GRID\n\nTEST(DISABLED_CubeGridProvider, is_default_creatable) {}\nTEST(DISABLED_CubeGridProvider, fulfills_const_interface) {}\nTEST(DISABLED_CubeGridProvider, is_visualizable) {}\n\n#endif \/\/ HAVE_DUNE_GRID\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Override AudioManager::MakeAudioInputStream() in NullAudioManager.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 Robert Böhm\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\n#include \"LoopingThread.hpp\"\n\n\nLoopingThread::LoopingThread() : thread(nullptr), scheduledCallbacks() {\n\n}\n\nLoopingThread::~LoopingThread() {\n if (this->thread) {\n delete this->thread;\n }\n}\n\nvoid LoopingThread::runCallbacks() {\n this->callbacksMutex.lock();\n if (this->scheduledCallbacks.size() > 0) {\n std::vector<std::function<void()>> currentCallbacks = std::move(this->scheduledCallbacks);\n this->scheduledCallbacks.clear();\n this->callbacksMutex.unlock();\n for (auto callback : currentCallbacks) {\n callback();\n }\n } else {\n this->callbacksMutex.unlock();\n }\n}\n\nvoid LoopingThread::run() {\n for (;;) {\n \/\/ This is to allow for new callbacks to be scheduled from within a callback\n this->runCallbacks();\n\n \/\/ Run the tick\n if (!this->tick()) {\n break;\n }\n }\n\n \/\/ Run pending callbacks, this might result in an infinite loop if there are more\n \/\/ callbacks scheduled from within scheduled callbacks\n this->callbacksMutex.lock();\n while (this->scheduledCallbacks.size() > 0) {\n this->callbacksMutex.unlock();\n this->runCallbacks();\n this->callbacksMutex.lock();\n }\n this->callbacksMutex.unlock();\n}\n\nvoid LoopingThread::scheduleCallback(std::function<void()> callback) {\n this->callbacksMutex.lock();\n this->scheduledCallbacks.push_back(callback);\n this->callbacksMutex.unlock();\n}\n\nvoid LoopingThread::start() {\n if (!this->thread) {\n this->thread = new std::thread(&LoopingThread::run, this);\n }\n}\n\nvoid LoopingThread::join() {\n if (this->thread && this->thread->joinable()) {\n this->thread->join();\n }\n}\n<commit_msg>Move comment to proper location.<commit_after>\/\/ Copyright (c) 2014 Robert Böhm\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\n#include \"LoopingThread.hpp\"\n\n\nLoopingThread::LoopingThread() : thread(nullptr), scheduledCallbacks() {\n\n}\n\nLoopingThread::~LoopingThread() {\n if (this->thread) {\n delete this->thread;\n }\n}\n\nvoid LoopingThread::runCallbacks() {\n this->callbacksMutex.lock();\n if (this->scheduledCallbacks.size() > 0) {\n \/\/ This is to allow for new callbacks to be scheduled from within a callback\n std::vector<std::function<void()>> currentCallbacks = std::move(this->scheduledCallbacks);\n this->scheduledCallbacks.clear();\n this->callbacksMutex.unlock();\n for (auto callback : currentCallbacks) {\n callback();\n }\n } else {\n this->callbacksMutex.unlock();\n }\n}\n\nvoid LoopingThread::run() {\n for (;;) {\n this->runCallbacks();\n\n \/\/ Run the tick\n if (!this->tick()) {\n break;\n }\n }\n\n \/\/ Run pending callbacks, this might result in an infinite loop if there are more\n \/\/ callbacks scheduled from within scheduled callbacks\n this->callbacksMutex.lock();\n while (this->scheduledCallbacks.size() > 0) {\n this->callbacksMutex.unlock();\n this->runCallbacks();\n this->callbacksMutex.lock();\n }\n this->callbacksMutex.unlock();\n}\n\nvoid LoopingThread::scheduleCallback(std::function<void()> callback) {\n this->callbacksMutex.lock();\n this->scheduledCallbacks.push_back(callback);\n this->callbacksMutex.unlock();\n}\n\nvoid LoopingThread::start() {\n if (!this->thread) {\n this->thread = new std::thread(&LoopingThread::run, this);\n }\n}\n\nvoid LoopingThread::join() {\n if (this->thread && this->thread->joinable()) {\n this->thread->join();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#include \"CppSound.hpp\"\n\n#include <cstdio>\n#include <cstring>\n\nCppSound::CppSound() : Csound(),\n go(false),\n isCompiled(false),\n isPerforming(false),\n spoutSize(0)\n{\n SetHostData((CSOUND *)0);\n}\n\nCppSound::~CppSound()\n{\n}\n\nint CppSound::compile(int argc, char **argv_)\n{\n Message(\"BEGAN CppSound::compile(%d, %p)...\\n\", argc, argv_);\n go = false;\n int returnValue = Compile(argc, argv_);\n spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT);\n if(returnValue)\n {\n isCompiled = false;\n }\n else\n {\n const char *outfilename = GetOutputFileName();\n if (outfilename) {\n renderedSoundfile = outfilename;\n }\n isCompiled = true;\n go = true;\n }\n Message(\"ENDED CppSound::compile.\\n\");\n return returnValue;\n}\n\nint CppSound::compile()\n{\n Message(\"BEGAN CppSound::compile()...\\n\");\n if(getCommand().length() <= 0)\n {\n Message(\"No Csound command.\\n\");\n return 0;\n }\n scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));\n int returnValue = compile(args.size(), &argv.front());\n Message(\"ENDED CppSound::compile.\\n\");\n return returnValue;\n}\n\nint CppSound::perform(int argc, char **argv_)\n{\n double beganAt = double(clock()) \/ double(CLOCKS_PER_SEC);\n isCompiled = false;\n go = false;\n Message(\"BEGAN CppSound::perform(%d, %p)...\\n\", argc, argv_);\n if(argc <= 0)\n {\n Message(\"ENDED CppSound::perform without compiling or performing.\\n\");\n return 0;\n }\n int result = compile(argc, argv_);\n if(result == -1)\n {\n return result;\n }\n for(result = 0; (result == 0) && go; )\n {\n result = PerformKsmps();\n }\n cleanup();\n double endedAt = double(clock()) \/ double(CLOCKS_PER_SEC);\n double elapsed = endedAt - beganAt;\n Message(\"Elapsed time = %f seconds.\\n\", elapsed);\n Message(\"ENDED CppSound::perform.\\n\");\n isCompiled = false;\n isPerforming = false;\n return 1;\n}\n\nint CppSound::perform()\n{\n int returnValue = 0;\n std::string command = getCommand();\n if(command.find(\"-\") == 0)\n {\n const char *argv_[] = {\"csound\", getFilename().c_str(), 0};\n returnValue = perform(2, (char **)argv_);\n }\n else\n {\n scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));\n returnValue = perform(args.size(), &argv.front());\n }\n return returnValue;\n}\n\nvoid CppSound::stop()\n{\n Message(\"RECEIVED CppSound::stop...\\n\");\n isCompiled = false;\n isPerforming = false;\n go = false;\n Stop();\n}\n\nCSOUND *CppSound::getCsound()\n{\n return csound;\n}\n\nint CppSound::performKsmps(bool absolute)\n{\n if(absolute){\n return PerformKsmpsAbsolute();\n }\n else {\n return PerformKsmps();\n }\n}\n\nvoid CppSound::cleanup()\n{\n Cleanup();\n Reset();\n}\n\nsize_t CppSound::getSpoutSize() const\n{\n return spoutSize;\n}\n\nstd::string CppSound::getOutputSoundfileName() const\n{\n return renderedSoundfile;\n}\n\nvoid CppSound::inputMessage(const char *istatement)\n{\n InputMessage(istatement);\n}\n\nvoid CppSound::write(const char *text)\n{\n Message(\"%s\", text);\n}\n\nlong CppSound::getThis()\n{\n return (long) this;\n}\n\nCsoundFile *CppSound::getCsoundFile()\n{\n return dynamic_cast<CsoundFile *>(this);\n}\n\nbool CppSound::getIsCompiled() const\n{\n return isCompiled;\n}\n\nvoid CppSound::setIsPerforming(bool isPerforming)\n{\n this->isPerforming = isPerforming;\n}\n\nbool CppSound::getIsPerforming() const\n{\n return isPerforming;\n}\n\nbool CppSound::getIsGo()\n{\n if(csound) {\n if(GetSpin() && GetSpout()) {\n return go;\n }\n }\n return false;\n}\n\n<commit_msg>Removed from the stop method a message which was messy if stop is called from a different thread, which it usually is.<commit_after>\/**\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#include \"CppSound.hpp\"\n\n#include <cstdio>\n#include <cstring>\n\nCppSound::CppSound() : Csound(),\n go(false),\n isCompiled(false),\n isPerforming(false),\n spoutSize(0)\n{\n SetHostData((CSOUND *)0);\n}\n\nCppSound::~CppSound()\n{\n}\n\nint CppSound::compile(int argc, char **argv_)\n{\n Message(\"BEGAN CppSound::compile(%d, %p)...\\n\", argc, argv_);\n go = false;\n int returnValue = Compile(argc, argv_);\n spoutSize = GetKsmps() * GetNchnls() * sizeof(MYFLT);\n if(returnValue)\n {\n isCompiled = false;\n }\n else\n {\n const char *outfilename = GetOutputFileName();\n if (outfilename) {\n renderedSoundfile = outfilename;\n }\n isCompiled = true;\n go = true;\n }\n Message(\"ENDED CppSound::compile.\\n\");\n return returnValue;\n}\n\nint CppSound::compile()\n{\n Message(\"BEGAN CppSound::compile()...\\n\");\n if(getCommand().length() <= 0)\n {\n Message(\"No Csound command.\\n\");\n return 0;\n }\n scatterArgs(getCommand(), const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));\n int returnValue = compile(args.size(), &argv.front());\n Message(\"ENDED CppSound::compile.\\n\");\n return returnValue;\n}\n\nint CppSound::perform(int argc, char **argv_)\n{\n double beganAt = double(clock()) \/ double(CLOCKS_PER_SEC);\n isCompiled = false;\n go = false;\n Message(\"BEGAN CppSound::perform(%d, %p)...\\n\", argc, argv_);\n if(argc <= 0)\n {\n Message(\"ENDED CppSound::perform without compiling or performing.\\n\");\n return 0;\n }\n int result = compile(argc, argv_);\n if(result == -1)\n {\n return result;\n }\n for(result = 0; (result == 0) && go; )\n {\n result = PerformKsmps();\n }\n cleanup();\n double endedAt = double(clock()) \/ double(CLOCKS_PER_SEC);\n double elapsed = endedAt - beganAt;\n Message(\"Elapsed time = %f seconds.\\n\", elapsed);\n Message(\"ENDED CppSound::perform.\\n\");\n isCompiled = false;\n isPerforming = false;\n return 1;\n}\n\nint CppSound::perform()\n{\n int returnValue = 0;\n std::string command = getCommand();\n if(command.find(\"-\") == 0)\n {\n const char *argv_[] = {\"csound\", getFilename().c_str(), 0};\n returnValue = perform(2, (char **)argv_);\n }\n else\n {\n scatterArgs(command, const_cast< std::vector<std::string> & >(args), const_cast< std::vector<char *> &>(argv));\n returnValue = perform(args.size(), &argv.front());\n }\n return returnValue;\n}\n\nvoid CppSound::stop()\n{\n isCompiled = false;\n isPerforming = false;\n go = false;\n Stop();\n}\n\nCSOUND *CppSound::getCsound()\n{\n return csound;\n}\n\nint CppSound::performKsmps(bool absolute)\n{\n if(absolute){\n return PerformKsmpsAbsolute();\n }\n else {\n return PerformKsmps();\n }\n}\n\nvoid CppSound::cleanup()\n{\n Cleanup();\n Reset();\n}\n\nsize_t CppSound::getSpoutSize() const\n{\n return spoutSize;\n}\n\nstd::string CppSound::getOutputSoundfileName() const\n{\n return renderedSoundfile;\n}\n\nvoid CppSound::inputMessage(const char *istatement)\n{\n InputMessage(istatement);\n}\n\nvoid CppSound::write(const char *text)\n{\n Message(\"%s\", text);\n}\n\nlong CppSound::getThis()\n{\n return (long) this;\n}\n\nCsoundFile *CppSound::getCsoundFile()\n{\n return dynamic_cast<CsoundFile *>(this);\n}\n\nbool CppSound::getIsCompiled() const\n{\n return isCompiled;\n}\n\nvoid CppSound::setIsPerforming(bool isPerforming)\n{\n this->isPerforming = isPerforming;\n}\n\nbool CppSound::getIsPerforming() const\n{\n return isPerforming;\n}\n\nbool CppSound::getIsGo()\n{\n if(csound) {\n if(GetSpin() && GetSpout()) {\n return go;\n }\n }\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"interface.h\"\n\nInterface::Interface() {\n ftyp = new Box_ftyp();\n moov = new Box_moov();\n mvhd = new Box_mvhd();\n trak_vide = new Box_trak();\n tkhd_vide = new Box_tkhd();\n mdia_vide = new Box_mdia();\n mdhd_vide = new Box_mdhd();\n hdlr_vide = new Box_hdlr();\n minf_vide = new Box_minf();\n vmhd_vide = new Box_vmhd();\n dinf_vide = new Box_dinf();\n dref_vide = new Box_dref();\n url_vide = new Box_url();\n stbl_vide = new Box_stbl();\n stts_vide = new Box_stts();\n stsc_vide = new Box_stsc();\n stco_vide = new Box_stco();\n stsd_vide = new Box_stsd();\n avcC_vide = new Box_avcC();\n trak_soun = new Box_trak();\n tkhd_soun = new Box_tkhd();\n mdia_soun = new Box_mdia();\n mdhd_soun = new Box_mdhd();\n hdlr_soun = new Box_hdlr();\n minf_soun = new Box_minf();\n smhd_soun = new Box_smhd();\n dinf_soun = new Box_dinf();\n dref_soun = new Box_dref();\n url_soun = new Box_url();\n stbl_soun = new Box_stbl();\n stts_soun = new Box_stts();\n stsc_soun = new Box_stsc();\n stco_soun = new Box_stco();\n stsd_soun = new Box_stsd();\n esds_soun = new Box_esds();\n}\n\nInterface::~Interface() {\n if( esds_soun ) { delete esds_soun; esds_soun = NULL; }\n if( stsd_soun ) { delete stsd_soun; stsd_soun = NULL; }\n if( stco_soun ) { delete stco_soun; stco_soun = NULL; }\n if( stsc_soun ) { delete stsc_soun; stsc_soun = NULL; }\n if( stts_soun ) { delete stts_soun; stts_soun = NULL; }\n if( stbl_soun ) { delete stbl_soun; stbl_soun = NULL; }\n if( url_soun ) { delete url_soun; url_soun = NULL; }\n if( dref_soun ) { delete dref_soun; dref_soun = NULL; }\n if( dinf_soun ) { delete dinf_soun; dinf_soun = NULL; }\n if( minf_soun ) { delete minf_soun; minf_soun = NULL; }\n if( hdlr_soun ) { delete hdlr_soun; hdlr_soun = NULL; }\n if( mdhd_soun ) { delete mdhd_soun; mdhd_soun = NULL; }\n if( mdia_soun ) { delete mdia_soun; mdia_soun = NULL; }\n if( tkhd_soun ) { delete tkhd_soun; tkhd_soun = NULL; }\n if( trak_soun ) { delete trak_soun; trak_soun = NULL; }\n if( avcC_vide ) { delete avcC_vide; avcC_vide = NULL; }\n if( stsd_vide ) { delete stsd_vide; stsd_vide = NULL; }\n if( stco_vide ) { delete stco_vide; stco_vide = NULL; }\n if( stsc_vide ) { delete stsc_vide; stsc_vide = NULL; }\n if( stts_vide ) { delete stts_vide; stts_vide = NULL; }\n if( stbl_vide ) { delete stbl_vide; stbl_vide = NULL; }\n if( url_vide ) { delete url_vide; url_vide = NULL; }\n if( dref_vide ) { delete dref_vide; dref_vide = NULL; }\n if( dinf_vide ) { delete dinf_vide; dinf_vide = NULL; }\n if( minf_vide ) { delete minf_vide; minf_vide = NULL; }\n if( hdlr_vide ) { delete hdlr_vide; hdlr_vide = NULL; }\n if( mdhd_vide ) { delete mdhd_vide; mdhd_vide = NULL; }\n if( mdia_vide ) { delete mdia_vide; mdia_vide = NULL; }\n if( tkhd_vide ) { delete tkhd_vide; tkhd_vide = NULL; }\n if( trak_vide ) { delete trak_vide; trak_vide = NULL; }\n if( mvhd ) { delete mvhd; mvhd = NULL; }\n if( moov ) { delete moov; moov = NULL; }\n if( ftyp ) { delete ftyp; ftyp = NULL; }\n}\n\nvoid Interface::link( ) {\n \/\/Linking Video Track\n stsd_vide->AddContent(avcC_vide->GetBox());\n stbl_vide->AddContent(stsd_vide->GetBox(),3);\n stbl_vide->AddContent(stco_vide->GetBox(),2);\n stbl_vide->AddContent(stsc_vide->GetBox(),1);\n stbl_vide->AddContent(stts_vide->GetBox());\n dref_vide->AddContent(url_vide->GetBox());\n dinf_vide->AddContent(dref_vide->GetBox());\n minf_vide->AddContent(stbl_vide->GetBox(),2);\n minf_vide->AddContent(dinf_vide->GetBox(),1);\n minf_vide->AddContent(vmhd_vide->GetBox());\n mdia_vide->AddContent(minf_vide->GetBox(),2);\n mdia_vide->AddContent(hdlr_vide->GetBox(),1);\n mdia_vide->AddContent(mdhd_vide->GetBox());\n trak_vide->AddContent(mdia_vide->GetBox(),1);\n trak_vide->AddContent(tkhd_vide->GetBox());\n\n \/\/Linking Sound Track\n stsd_soun->AddContent(esds_soun->GetBox());\n stbl_soun->AddContent(stsd_soun->GetBox(),3);\n stbl_soun->AddContent(stco_soun->GetBox(),2);\n stbl_soun->AddContent(stsc_soun->GetBox(),1);\n stbl_soun->AddContent(stts_soun->GetBox());\n dref_soun->AddContent(url_soun->GetBox());\n dinf_soun->AddContent(dref_soun->GetBox());\n minf_soun->AddContent(stbl_soun->GetBox(),2);\n minf_soun->AddContent(dinf_soun->GetBox(),1);\n minf_soun->AddContent(smhd_soun->GetBox());\n mdia_soun->AddContent(minf_soun->GetBox(),2);\n mdia_soun->AddContent(hdlr_soun->GetBox(),1);\n mdia_soun->AddContent(mdhd_soun->GetBox());\n trak_soun->AddContent(mdia_soun->GetBox(),1);\n trak_soun->AddContent(tkhd_soun->GetBox());\n\n \/\/Linking total file\n moov->AddContent(trak_soun->GetBox(),2);\n moov->AddContent(trak_vide->GetBox(),1);\n moov->AddContent(mvhd->GetBox());\n}\n\nuint32_t Interface::GetContentSize( ) {\n return ftyp->GetBoxedDataSize( ) + moov->GetBoxedDataSize( );\n}\n\nuint8_t * Interface::GetContents( ) {\n uint8_t * Result = new uint8_t[GetContentSize( )];\n memcpy(Result,ftyp->GetBoxedData( ),ftyp->GetBoxedDataSize( ));\n memcpy(&Result[ftyp->GetBoxedDataSize( )],moov->GetBoxedData( ),moov->GetBoxedDataSize( ));\n return Result;\n}\n<commit_msg>[Stable] Filedata functionlity in interface working<commit_after>#include \"interface.h\"\n\nInterface::Interface() {\n ftyp = new Box_ftyp();\n moov = new Box_moov();\n mvhd = new Box_mvhd();\n trak_vide = new Box_trak();\n tkhd_vide = new Box_tkhd();\n mdia_vide = new Box_mdia();\n mdhd_vide = new Box_mdhd();\n hdlr_vide = new Box_hdlr();\n minf_vide = new Box_minf();\n vmhd_vide = new Box_vmhd();\n dinf_vide = new Box_dinf();\n dref_vide = new Box_dref();\n url_vide = new Box_url();\n stbl_vide = new Box_stbl();\n stts_vide = new Box_stts();\n stsc_vide = new Box_stsc();\n stco_vide = new Box_stco();\n stsd_vide = new Box_stsd();\n avcC_vide = new Box_avcC();\n trak_soun = new Box_trak();\n tkhd_soun = new Box_tkhd();\n mdia_soun = new Box_mdia();\n mdhd_soun = new Box_mdhd();\n hdlr_soun = new Box_hdlr();\n minf_soun = new Box_minf();\n smhd_soun = new Box_smhd();\n dinf_soun = new Box_dinf();\n dref_soun = new Box_dref();\n url_soun = new Box_url();\n stbl_soun = new Box_stbl();\n stts_soun = new Box_stts();\n stsc_soun = new Box_stsc();\n stco_soun = new Box_stco();\n stsd_soun = new Box_stsd();\n esds_soun = new Box_esds();\n}\n\nInterface::~Interface() {\n if( esds_soun ) { delete esds_soun; esds_soun = NULL; }\n if( stsd_soun ) { delete stsd_soun; stsd_soun = NULL; }\n if( stco_soun ) { delete stco_soun; stco_soun = NULL; }\n if( stsc_soun ) { delete stsc_soun; stsc_soun = NULL; }\n if( stts_soun ) { delete stts_soun; stts_soun = NULL; }\n if( stbl_soun ) { delete stbl_soun; stbl_soun = NULL; }\n if( url_soun ) { delete url_soun; url_soun = NULL; }\n if( dref_soun ) { delete dref_soun; dref_soun = NULL; }\n if( dinf_soun ) { delete dinf_soun; dinf_soun = NULL; }\n if( minf_soun ) { delete minf_soun; minf_soun = NULL; }\n if( hdlr_soun ) { delete hdlr_soun; hdlr_soun = NULL; }\n if( mdhd_soun ) { delete mdhd_soun; mdhd_soun = NULL; }\n if( mdia_soun ) { delete mdia_soun; mdia_soun = NULL; }\n if( tkhd_soun ) { delete tkhd_soun; tkhd_soun = NULL; }\n if( trak_soun ) { delete trak_soun; trak_soun = NULL; }\n if( avcC_vide ) { delete avcC_vide; avcC_vide = NULL; }\n if( stsd_vide ) { delete stsd_vide; stsd_vide = NULL; }\n if( stco_vide ) { delete stco_vide; stco_vide = NULL; }\n if( stsc_vide ) { delete stsc_vide; stsc_vide = NULL; }\n if( stts_vide ) { delete stts_vide; stts_vide = NULL; }\n if( stbl_vide ) { delete stbl_vide; stbl_vide = NULL; }\n if( url_vide ) { delete url_vide; url_vide = NULL; }\n if( dref_vide ) { delete dref_vide; dref_vide = NULL; }\n if( dinf_vide ) { delete dinf_vide; dinf_vide = NULL; }\n if( minf_vide ) { delete minf_vide; minf_vide = NULL; }\n if( hdlr_vide ) { delete hdlr_vide; hdlr_vide = NULL; }\n if( mdhd_vide ) { delete mdhd_vide; mdhd_vide = NULL; }\n if( mdia_vide ) { delete mdia_vide; mdia_vide = NULL; }\n if( tkhd_vide ) { delete tkhd_vide; tkhd_vide = NULL; }\n if( trak_vide ) { delete trak_vide; trak_vide = NULL; }\n if( mvhd ) { delete mvhd; mvhd = NULL; }\n if( moov ) { delete moov; moov = NULL; }\n if( ftyp ) { delete ftyp; ftyp = NULL; }\n}\n\nvoid Interface::link( ) {\n \/\/Linking Video Track\n stsd_vide->AddContent(avcC_vide->GetBox());\n stbl_vide->AddContent(stsd_vide->GetBox(),3);\n stbl_vide->AddContent(stco_vide->GetBox(),2);\n stbl_vide->AddContent(stsc_vide->GetBox(),1);\n stbl_vide->AddContent(stts_vide->GetBox());\n dref_vide->AddContent(url_vide->GetBox());\n dinf_vide->AddContent(dref_vide->GetBox());\n minf_vide->AddContent(stbl_vide->GetBox(),2);\n minf_vide->AddContent(dinf_vide->GetBox(),1);\n minf_vide->AddContent(vmhd_vide->GetBox());\n mdia_vide->AddContent(minf_vide->GetBox(),2);\n mdia_vide->AddContent(hdlr_vide->GetBox(),1);\n mdia_vide->AddContent(mdhd_vide->GetBox());\n trak_vide->AddContent(mdia_vide->GetBox(),1);\n trak_vide->AddContent(tkhd_vide->GetBox());\n\n \/\/Linking Sound Track\n stsd_soun->AddContent(esds_soun->GetBox());\n stbl_soun->AddContent(stsd_soun->GetBox(),3);\n stbl_soun->AddContent(stco_soun->GetBox(),2);\n stbl_soun->AddContent(stsc_soun->GetBox(),1);\n stbl_soun->AddContent(stts_soun->GetBox());\n dref_soun->AddContent(url_soun->GetBox());\n dinf_soun->AddContent(dref_soun->GetBox());\n minf_soun->AddContent(stbl_soun->GetBox(),2);\n minf_soun->AddContent(dinf_soun->GetBox(),1);\n minf_soun->AddContent(smhd_soun->GetBox());\n mdia_soun->AddContent(minf_soun->GetBox(),2);\n mdia_soun->AddContent(hdlr_soun->GetBox(),1);\n mdia_soun->AddContent(mdhd_soun->GetBox());\n trak_soun->AddContent(mdia_soun->GetBox(),1);\n trak_soun->AddContent(tkhd_soun->GetBox());\n\n \/\/Linking total file\n moov->AddContent(trak_soun->GetBox(),2);\n moov->AddContent(trak_vide->GetBox(),1);\n moov->AddContent(mvhd->GetBox());\n}\n\nuint32_t Interface::GetContentSize( ) {\n return ftyp->GetBox( )->GetBoxedDataSize( ) + moov->GetBox( )->GetBoxedDataSize( );\n}\n\nuint8_t * Interface::GetContents( ) {\n uint8_t * Result = new uint8_t[GetContentSize( )];\n memcpy(Result,ftyp->GetBox( )->GetBoxedData( ),ftyp->GetBox( )->GetBoxedDataSize( ));\n memcpy(&Result[ftyp->GetBox( )->GetBoxedDataSize( )],moov->GetBox( )->GetBoxedData( ),moov->GetBox( )->GetBoxedDataSize( ));\n return Result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally. They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm);\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument. The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, a Perm of size zero is going to be returned.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`. However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs);\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n perm_getnewargs_doc },\n { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n (lenfunc)perm_length, \/* sq_length *\/\n 0, \/* sq_concat *\/\n 0, \/* sq_repeat *\/\n (ssizeargfunc)perm_item, \/* sq_item *\/\n 0, \/* sq_slice *\/\n 0, \/* sq_ass_item *\/\n 0, \/* sq_ass_slice *\/\n 0 \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n { NULL }\n};\n\/\/ clang-format on\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n PyVarObject_HEAD_INIT(NULL, 0)\n \"drudge.canonpy.Perm\",\n sizeof(Perm_object),\n 0,\n (destructor) perm_dealloc, \/* tp_dealloc *\/\n 0, \/* tp_print *\/\n 0, \/* tp_getattr *\/\n 0, \/* tp_setattr *\/\n 0, \/* tp_reserved *\/\n (reprfunc) perm_repr, \/* tp_repr *\/\n 0, \/* tp_as_number *\/\n &perm_as_sequence, \/* tp_as_sequence *\/\n 0, \/* tp_as_mapping *\/\n (hashfunc) perm_hash, \/* tp_hash *\/\n 0, \/* tp_call *\/\n 0, \/* tp_str *\/\n 0, \/* In main. *\/ \/* tp_getattro *\/\n 0, \/* tp_setattro *\/\n 0, \/* tp_as_buffer *\/\n Py_TPFLAGS_DEFAULT, \/* tp_flags *\/\n perm_doc, \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n perm_methods, \/* tp_methods *\/\n 0, \/* tp_members *\/\n perm_getsets, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n 0, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n perm_new, \/* tp_new *\/\n 0, \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring = R\"CANONPYDOC(\nCanonpy, simple wrapper over libcanon for Python.\n\n)CANONPYDOC\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canopy_exec(PyObject* m)\n{\n \/\/\n \/\/ Add the class for Perm.\n \/\/\n\n perm_type.tp_getattro = PyObject_GenericGetAttr;\n if (PyType_Ready(&perm_type) < 0)\n return NULL;\n Py_INCREF(&perm_type);\n PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n { Py_mod_exec, canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n PyModuleDef_HEAD_INIT,\n \"drudge.canonpy\",\n canonpy_docstring,\n 0, \/\/ m-size\n canonpy_methods,\n canonpy_slots,\n NULL, \/\/ Transverse\n NULL, \/\/ Clear\n NULL \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n return PyModuleDef_Init(&canonpy_module);\n}\n<commit_msg>Update docstring for canonpy module<commit_after>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally. They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm);\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument. The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, a Perm of size zero is going to be returned.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`. However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs);\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n perm_getnewargs_doc },\n { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n (lenfunc)perm_length, \/* sq_length *\/\n 0, \/* sq_concat *\/\n 0, \/* sq_repeat *\/\n (ssizeargfunc)perm_item, \/* sq_item *\/\n 0, \/* sq_slice *\/\n 0, \/* sq_ass_item *\/\n 0, \/* sq_ass_slice *\/\n 0 \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n { NULL }\n};\n\/\/ clang-format on\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n PyVarObject_HEAD_INIT(NULL, 0)\n \"drudge.canonpy.Perm\",\n sizeof(Perm_object),\n 0,\n (destructor) perm_dealloc, \/* tp_dealloc *\/\n 0, \/* tp_print *\/\n 0, \/* tp_getattr *\/\n 0, \/* tp_setattr *\/\n 0, \/* tp_reserved *\/\n (reprfunc) perm_repr, \/* tp_repr *\/\n 0, \/* tp_as_number *\/\n &perm_as_sequence, \/* tp_as_sequence *\/\n 0, \/* tp_as_mapping *\/\n (hashfunc) perm_hash, \/* tp_hash *\/\n 0, \/* tp_call *\/\n 0, \/* tp_str *\/\n 0, \/* In main. *\/ \/* tp_getattro *\/\n 0, \/* tp_setattro *\/\n 0, \/* tp_as_buffer *\/\n Py_TPFLAGS_DEFAULT, \/* tp_flags *\/\n perm_doc, \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n perm_methods, \/* tp_methods *\/\n 0, \/* tp_members *\/\n perm_getsets, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n 0, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n perm_new, \/* tp_new *\/\n 0, \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring\n = R\"__doc__(Canonpy, simple wrapper over libcanon for Python.\n\nThis wrapper of libcanon is directly targeted towards usage using drudge.\nHere, we have a class `Perm`, which wraps over the `Simple_perm` class in\nlibcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class\nfor `Simple_perm`. And we also have the function `canon_eldag` to canonicalize\nan Eldag.\n\n)__doc__\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canopy_exec(PyObject* m)\n{\n \/\/\n \/\/ Add the class for Perm.\n \/\/\n\n perm_type.tp_getattro = PyObject_GenericGetAttr;\n if (PyType_Ready(&perm_type) < 0)\n return NULL;\n Py_INCREF(&perm_type);\n PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n { Py_mod_exec, canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n PyModuleDef_HEAD_INIT,\n \"drudge.canonpy\",\n canonpy_docstring,\n 0, \/\/ m-size\n canonpy_methods,\n canonpy_slots,\n NULL, \/\/ Transverse\n NULL, \/\/ Clear\n NULL \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n return PyModuleDef_Init(&canonpy_module);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: slowdown_timer.cc,v 1.8 2001\/10\/11 13:01:27 yakovlev Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n#include \"bochs.h\"\n#include <errno.h>\n\n#if BX_USE_SLOWDOWN_TIMER\n\n\/\/These need to stay printfs because they are useless in the log file.\n#define BX_SLOWDOWN_PRINTF_FEEDBACK 0\n\n#define SECINUSEC 1000000\n#define usectosec(a) ((a)\/SECINUSEC)\n#define sectousec(a) ((a)*SECINUSEC)\n#define nsectousec(a) ((a)\/1000)\n\n#if BX_HAVE_USLEEP\n# define Qval 1000\n#else\n# define Qval SECINUSEC\n#endif\n\n#define MAXMULT 1.5\n#define REALTIME_Q SECINUSEC\n\nbx_slowdown_timer_c bx_slowdown_timer;\n\nbx_slowdown_timer_c::bx_slowdown_timer_c() {\n s.start_time=0;\n s.start_emulated_time=0;\n s.timer_handle=BX_NULL_TIMER_HANDLE;\n}\n\nint\nbx_slowdown_timer_c::init() {\n s.MAXmultiplier=MAXMULT;\n s.Q=Qval;\n\n if(s.MAXmultiplier<1)\n s.MAXmultiplier=1;\n\n s.start_time=sectousec(time(NULL));\n s.start_emulated_time = bx_pc_system.time_usec();\n s.lasttime=0;\n s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1);\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);\n return 0;\n}\n\nvoid\nbx_slowdown_timer_c::timer_handler(void * this_ptr) {\n bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;\n\n class_ptr->handle_timer();\n}\n\nvoid\nbx_slowdown_timer_c::handle_timer() {\n Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;\n Bit64u wanttime = s.lasttime+s.Q;\n Bit64u totaltime = sectousec(time(NULL)) - s.start_time;\n Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;\n\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"Entering slowdown timer handler.\\n\");\n#endif\n\n \/* Decide if we're behind.\n * Set interrupt interval accordingly. *\/\n if(totaltime > total_emu_time) {\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,\n\t\t\t\t(Bit32u)((Bit64u)\n\t\t\t\t\t (s.MAXmultiplier * (float)s.Q)),\n\t\t\t\t0);\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"running at MAX speed\\n\");\n#endif\n } else {\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,s.Q,0);\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"running at NORMAL speed\\n\");\n#endif\n }\n\n \/* Make sure we took at least one time quantum. *\/\n \/* This is a little strange. I'll try to explain.\n * We're running bochs one second ahead of real time.\n * this gives us a very precise division on whether\n * we're ahead or behind the second line.\n * Basically, here's how it works:\n * *****|******************|***********...\n * Time Time+1sec\n * <^Bochs doesn't delay.\n * ^>Bochs delays.\n * <^Bochs runs at MAX speed.\n * ^>Bochs runs at normal\n *\/\n if(wanttime > (totaltime+REALTIME_Q)) {\n#if BX_HAVE_USLEEP\n usleep(s.Q);\n#else\n sleep(usectosec(s.Q));\n#endif\n \/\/delay(wanttime-totaltime);\n \/*alternatively: delay(Q);\n * This works okay because we share the delay between\n * two time quantums.\n *\/\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"DELAYING for a quantum\\n\");\n#endif\n }\n s.lasttime=thistime;\n\n \/\/Diagnostic info:\n if(wanttime > (totaltime+REALTIME_Q)) {\n if(totaltime > total_emu_time) {\n if(0) printf(\"Solving OpenBSD problem.\\n\");\n } else {\n if(0) printf(\"too fast.\\n\");\n }\n } else {\n if(totaltime > total_emu_time) {\n if(0) printf(\"too slow.\\n\");\n } else {\n if(0) printf(\"sometimes invalid state, normally okay.\\n\");\n }\n }\n}\n\n#endif\n\n<commit_msg>commented out the diagnostic code, no use using 10 jumps for nothing, and it will take less time to re-enable it in the future than using those if(0)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: slowdown_timer.cc,v 1.9 2002\/03\/06 01:19:50 instinc Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n#include \"bochs.h\"\n#include <errno.h>\n\n#if BX_USE_SLOWDOWN_TIMER\n\n\/\/These need to stay printfs because they are useless in the log file.\n#define BX_SLOWDOWN_PRINTF_FEEDBACK 0\n\n#define SECINUSEC 1000000\n#define usectosec(a) ((a)\/SECINUSEC)\n#define sectousec(a) ((a)*SECINUSEC)\n#define nsectousec(a) ((a)\/1000)\n\n#if BX_HAVE_USLEEP\n# define Qval 1000\n#else\n# define Qval SECINUSEC\n#endif\n\n#define MAXMULT 1.5\n#define REALTIME_Q SECINUSEC\n\nbx_slowdown_timer_c bx_slowdown_timer;\n\nbx_slowdown_timer_c::bx_slowdown_timer_c() {\n s.start_time=0;\n s.start_emulated_time=0;\n s.timer_handle=BX_NULL_TIMER_HANDLE;\n}\n\nint\nbx_slowdown_timer_c::init() {\n s.MAXmultiplier=MAXMULT;\n s.Q=Qval;\n\n if(s.MAXmultiplier<1)\n s.MAXmultiplier=1;\n\n s.start_time=sectousec(time(NULL));\n s.start_emulated_time = bx_pc_system.time_usec();\n s.lasttime=0;\n s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1);\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);\n return 0;\n}\n\nvoid\nbx_slowdown_timer_c::timer_handler(void * this_ptr) {\n bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;\n\n class_ptr->handle_timer();\n}\n\nvoid\nbx_slowdown_timer_c::handle_timer() {\n Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;\n Bit64u wanttime = s.lasttime+s.Q;\n Bit64u totaltime = sectousec(time(NULL)) - s.start_time;\n Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;\n\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"Entering slowdown timer handler.\\n\");\n#endif\n\n \/* Decide if we're behind.\n * Set interrupt interval accordingly. *\/\n if(totaltime > total_emu_time) {\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,\n\t\t\t\t(Bit32u)((Bit64u)\n\t\t\t\t\t (s.MAXmultiplier * (float)s.Q)),\n\t\t\t\t0);\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"running at MAX speed\\n\");\n#endif\n } else {\n bx_pc_system.deactivate_timer(s.timer_handle);\n bx_pc_system.activate_timer(s.timer_handle,s.Q,0);\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"running at NORMAL speed\\n\");\n#endif\n }\n\n \/* Make sure we took at least one time quantum. *\/\n \/* This is a little strange. I'll try to explain.\n * We're running bochs one second ahead of real time.\n * this gives us a very precise division on whether\n * we're ahead or behind the second line.\n * Basically, here's how it works:\n * *****|******************|***********...\n * Time Time+1sec\n * <^Bochs doesn't delay.\n * ^>Bochs delays.\n * <^Bochs runs at MAX speed.\n * ^>Bochs runs at normal\n *\/\n if(wanttime > (totaltime+REALTIME_Q)) {\n#if BX_HAVE_USLEEP\n usleep(s.Q);\n#else\n sleep(usectosec(s.Q));\n#endif\n \/\/delay(wanttime-totaltime);\n \/*alternatively: delay(Q);\n * This works okay because we share the delay between\n * two time quantums.\n *\/\n#if BX_SLOWDOWN_PRINTF_FEEDBACK\n printf(\"DELAYING for a quantum\\n\");\n#endif\n }\n s.lasttime=thistime;\n\n \/\/Diagnostic info:\n#if 0\n if(wanttime > (totaltime+REALTIME_Q)) {\n if(totaltime > total_emu_time) {\n printf(\"Solving OpenBSD problem.\\n\");\n } else {\n printf(\"too fast.\\n\");\n }\n } else {\n if(totaltime > total_emu_time) {\n printf(\"too slow.\\n\");\n } else {\n printf(\"sometimes invalid state, normally okay.\\n\");\n }\n }\n#endif \/\/ Diagnostic info\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix 64-bit warnings (for 64-bit Windows build)<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"deskicon.h\"\n\n#include <QVBoxLayout>\n#include <QPainter>\n#include <QFileInfo>\n#include <QFileIconProvider>\n#include <QMouseEvent>\n\n#include <Windows.h>\n#include <ShellAPI.h>\n\nDeskIcon::DeskIcon(QWidget *parent,QString icon, int type) :\n QPushButton(parent),m_type(type)\n{\n m_lb_icon = new QLabel(this);\n m_lb_icon->setAttribute(Qt::WA_TranslucentBackground);\n\n QVBoxLayout *vlay = new QVBoxLayout(this);\n\n if ( type != PATH_NAME)\n {\n m_icon.load(icon);\n m_icon = m_icon.scaled(40,40);\n }else\n {\n QFileInfo info(icon);\n QFileIconProvider provider;\n QIcon icon = provider.icon(info);\n m_icon = icon.pixmap(20,20);\n }\n QString sheet;\n sheet = \"border-image: url(\" + icon + \");\";\n m_lb_icon->setStyleSheet(sheet);\n m_lb_icon->setPixmap(m_icon);\n vlay->setContentsMargins(0,0,0,0);\n vlay->setSpacing(5);\n\n vlay->addWidget(m_lb_icon,0,Qt::AlignHCenter);\n\n if ( type == HAVE_TEXT )\n {\n m_lb_txt = new QLabel(this);\n m_lb_txt->setAttribute(Qt::WA_TranslucentBackground);\n m_lb_txt->setStyleSheet(\"color: rgb(255, 255, 255);\");\n m_lb_txt->setWordWrap(true);\n\n vlay->addWidget(m_lb_txt,0,Qt::AlignHCenter);\n setMinimumSize(80,65);\n }else\n setMinimumSize(40,40);\n\n setLayout(vlay);\n\n setAttribute(Qt::WA_TranslucentBackground);\n\n m_color = QColor(0,0,0,0);\n\n}\n\nDeskIcon::~DeskIcon()\n{\n\n}\n\nvoid DeskIcon::setTextStyle(QString style)\n{\n m_lb_txt->setStyleSheet(style);\n}\n\nvoid DeskIcon::paintEvent(QPaintEvent *evt)\n{\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing,true);\n\n QPainterPath path;\n path.addRoundRect(rect(),20);\n painter.fillPath(path,QBrush(m_color));\n}\n\nvoid DeskIcon::enterEvent(QEvent *evt)\n{\n m_color = QColor(255, 37, 246,40);\n\n setCursor(Qt::PointingHandCursor);\n update();\n\n}\nvoid DeskIcon::leaveEvent(QEvent *evt)\n{\n m_color = QColor(0,0,0,0);\n\n setCursor(Qt::ArrowCursor);\n update();\n}\n\nvoid DeskIcon::mouseDoubleClickEvent(QMouseEvent *evt)\n{\n if ( m_type == HAVE_TEXT)\n {\n QString txt = m_lb_txt->text();\n emit dbclick(txt);\n ShellExecuteA(this->winId(),\"open\",m_path.toLocal8Bit().data(),NULL,NULL,SW_SHOWNORMAL);\n }\n}\n\nvoid DeskIcon::mousePressEvent(QMouseEvent *evt)\n{\n if ( Qt::LeftButton == evt->button())\n {\n\n m_pressed = true;\n m_movePoint = evt->globalPos() - pos();\n }\n}\n\nvoid DeskIcon::mouseReleaseEvent(QMouseEvent *evt)\n{\n m_pressed = false;\n emit click(m_txt);\n emit clicked();\n}\n\nvoid DeskIcon::mouseMoveEvent(QMouseEvent *evt)\n{\n if ( m_pressed)\n {\n move(evt->globalPos() - m_movePoint);\n }\n}\n<commit_msg>add dcode to bs url<commit_after>#include \"deskicon.h\"\n#include \"jsCore\/qjscore.h\"\n\n#include <QVBoxLayout>\n#include <QPainter>\n#include <QFileInfo>\n#include <QFileIconProvider>\n#include <QMouseEvent>\n\n#include <Windows.h>\n#include <ShellAPI.h>\n\nDeskIcon::DeskIcon(QWidget *parent,QString icon, int type) :\n QPushButton(parent),m_type(type)\n{\n m_lb_icon = new QLabel(this);\n m_lb_icon->setAttribute(Qt::WA_TranslucentBackground);\n\n QVBoxLayout *vlay = new QVBoxLayout(this);\n\n if ( type != PATH_NAME)\n {\n m_icon.load(icon);\n m_icon = m_icon.scaled(40,40);\n }else\n {\n QFileInfo info(icon);\n QFileIconProvider provider;\n QIcon icon = provider.icon(info);\n m_icon = icon.pixmap(20,20);\n }\n QString sheet;\n sheet = \"border-image: url(\" + icon + \");\";\n m_lb_icon->setStyleSheet(sheet);\n m_lb_icon->setPixmap(m_icon);\n vlay->setContentsMargins(0,0,0,0);\n vlay->setSpacing(5);\n\n vlay->addWidget(m_lb_icon,0,Qt::AlignHCenter);\n\n if ( type == HAVE_TEXT )\n {\n m_lb_txt = new QLabel(this);\n m_lb_txt->setAttribute(Qt::WA_TranslucentBackground);\n m_lb_txt->setStyleSheet(\"color: rgb(255, 255, 255);\");\n m_lb_txt->setWordWrap(true);\n\n vlay->addWidget(m_lb_txt,0,Qt::AlignHCenter);\n setMinimumSize(80,65);\n }else\n setMinimumSize(40,40);\n\n setLayout(vlay);\n\n setAttribute(Qt::WA_TranslucentBackground);\n\n m_color = QColor(0,0,0,0);\n\n}\n\nDeskIcon::~DeskIcon()\n{\n\n}\n\nvoid DeskIcon::setTextStyle(QString style)\n{\n m_lb_txt->setStyleSheet(style);\n}\n\nvoid DeskIcon::paintEvent(QPaintEvent *evt)\n{\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing,true);\n\n QPainterPath path;\n path.addRoundRect(rect(),20);\n painter.fillPath(path,QBrush(m_color));\n}\n\nvoid DeskIcon::enterEvent(QEvent *evt)\n{\n m_color = QColor(255, 37, 246,40);\n\n setCursor(Qt::PointingHandCursor);\n update();\n\n}\nvoid DeskIcon::leaveEvent(QEvent *evt)\n{\n m_color = QColor(0,0,0,0);\n\n setCursor(Qt::ArrowCursor);\n update();\n}\n\nvoid DeskIcon::mouseDoubleClickEvent(QMouseEvent *evt)\n{\n if ( m_type == HAVE_TEXT)\n {\n QString txt = m_lb_txt->text();\n emit dbclick(txt);\n if (m_path.indexOf(\"http\") >= 0)\n {\n m_path += \"?code=\" + QJSCore::ref()->getDCode();\n qDebug()<<\"URL:\"<<m_path;\n }\n ShellExecuteA(this->winId(),\"open\",m_path.toLocal8Bit().data(),NULL,NULL,SW_SHOWNORMAL);\n }\n}\n\nvoid DeskIcon::mousePressEvent(QMouseEvent *evt)\n{\n if ( Qt::LeftButton == evt->button())\n {\n\n m_pressed = true;\n m_movePoint = evt->globalPos() - pos();\n }\n}\n\nvoid DeskIcon::mouseReleaseEvent(QMouseEvent *evt)\n{\n m_pressed = false;\n emit click(m_txt);\n emit clicked();\n}\n\nvoid DeskIcon::mouseMoveEvent(QMouseEvent *evt)\n{\n if ( m_pressed)\n {\n move(evt->globalPos() - m_movePoint);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QAction>\n#include <QTranslator>\n#include <QMenu>\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/actionmanager\/actionmanager.h>\n#include <coreplugin\/actionmanager\/actioncontainer.h>\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <projectexplorer\/projectexplorer.h>\n\n#include <QtPlugin>\n\n#include \"QtcGtestPlugin.h\"\n#include \"Constants.h\"\n#include \"Settings.h\"\n#include \"OutputPane.h\"\n#include \"TestProject.h\"\n\nusing namespace QtcGtest::Internal;\n\nusing namespace Core;\nusing namespace ProjectExplorer;\n\nQtcGtestPlugin::QtcGtestPlugin():\n IPlugin (),\n testProject_ (new TestProject (this))\n{\n \/\/ Create your members\n}\n\nQtcGtestPlugin::~QtcGtestPlugin()\n{\n \/\/ Unregister objects from the plugin manager's object pool\n \/\/ Delete members\n}\n\nbool QtcGtestPlugin::initialize(const QStringList &arguments, QString *errorString)\n{\n \/\/ Register objects in the plugin manager's object pool\n \/\/ Load settings\n \/\/ Add actions to menus\n \/\/ Connect to other plugins' signals\n \/\/ In the initialize function, a plugin can be sure that the plugins it\n \/\/ depends on have initialized their members.\n\n Q_UNUSED(arguments)\n Q_UNUSED(errorString)\n\n initLanguage ();\n initMenus ();\n\n OutputPane* pane = new OutputPane;\n connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlStarted(ProjectExplorer::RunControl *)),\n pane, SLOT (handleRunStart(ProjectExplorer::RunControl *)));\n connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlFinished(ProjectExplorer::RunControl *)),\n pane, SLOT (handleRunFinish(ProjectExplorer::RunControl *)));\n addAutoReleasedObject (pane);\n\n\n connect (EditorManager::documentModel (),\n SIGNAL (dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)),\n testProject_,\n SLOT (handleDocumentsChange(const QModelIndex &, const QModelIndex &, const QVector<int> &)));\n connect (EditorManager::documentModel (),\n SIGNAL (rowsAboutToBeRemoved(const QModelIndex &, int, int)),\n testProject_,\n SLOT (handleDocumentsClose(const QModelIndex &, int, int)));\n\n return true;\n}\n\nvoid QtcGtestPlugin::initLanguage()\n{\n const QString& language = Core::ICore::userInterfaceLanguage();\n if (!language.isEmpty())\n {\n QTranslator* translator = new QTranslator (this);\n const QString& creatorTrPath = ICore::resourcePath () + QLatin1String (\"\/translations\");\n const QString& trFile = QLatin1String (\"QtcGtest_\") + language;\n if (translator->load (trFile, creatorTrPath))\n {\n qApp->installTranslator (translator);\n }\n }\n}\n\nvoid QtcGtestPlugin::initMenus()\n{\n QAction *checkProjectAction = new QAction(tr(\"Check project\"), this);\n Core::Command *checkProjectCmd = ActionManager::registerAction(\n checkProjectAction, Constants::ACTION_CHECK_PROJECT_ID,\n Context(Core::Constants::C_GLOBAL));\n checkProjectCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+A\")));\n connect(checkProjectAction, SIGNAL(triggered()), testProject_, SLOT(checkProject()));\n\n QAction *checkCurrentAction = new QAction(tr(\"Check current\"), this);\n Core::Command *checkCurrentCmd = ActionManager::registerAction(\n checkCurrentAction, Constants::ACTION_CHECK_CURRENT_ID,\n Context(Core::Constants::C_GLOBAL));\n checkCurrentCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+C\")));\n connect(checkCurrentAction, SIGNAL(triggered()), testProject_, SLOT(checkCurrent()));\n\n QAction *checkChangedAction = new QAction(tr(\"Check changed\"), this);\n Core::Command *checkChangedCmd = ActionManager::registerAction(\n checkChangedAction, Constants::ACTION_CHECK_CHANGED_ID,\n Context(Core::Constants::C_GLOBAL));\n checkChangedCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+T\")));\n connect(checkChangedAction, SIGNAL(triggered()), testProject_, SLOT(checkChanged()));\n\n ActionContainer *menu = ActionManager::createMenu(Constants::MENU_ID);\n menu->menu()->setTitle(tr(\"Google Test\"));\n menu->addAction(checkProjectCmd);\n menu->addAction(checkCurrentCmd);\n menu->addAction(checkChangedCmd);\n ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu);\n}\n\nvoid QtcGtestPlugin::extensionsInitialized()\n{\n \/\/ Retrieve objects from the plugin manager's object pool\n \/\/ In the extensionsInitialized function, a plugin can be sure that all\n \/\/ plugins that depend on it are completely initialized.\n}\n\nExtensionSystem::IPlugin::ShutdownFlag QtcGtestPlugin::aboutToShutdown()\n{\n \/\/ Save settings\n \/\/ Disconnect from signals that are not needed during shutdown\n \/\/ Hide UI (if you add UI that is not in the main window directly)\n return SynchronousShutdown;\n}\n\nQ_EXPORT_PLUGIN2(QtcGtest, QtcGtestPlugin)\n\n<commit_msg>Load translations from several paths<commit_after>#include <QAction>\n#include <QTranslator>\n#include <QMenu>\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/actionmanager\/actionmanager.h>\n#include <coreplugin\/actionmanager\/actioncontainer.h>\n#include <coreplugin\/editormanager\/editormanager.h>\n#include <projectexplorer\/projectexplorer.h>\n\n#include <QtPlugin>\n\n#include \"QtcGtestPlugin.h\"\n#include \"Constants.h\"\n#include \"Settings.h\"\n#include \"OutputPane.h\"\n#include \"TestProject.h\"\n\nusing namespace QtcGtest::Internal;\n\nusing namespace Core;\nusing namespace ProjectExplorer;\n\nQtcGtestPlugin::QtcGtestPlugin():\n IPlugin (),\n testProject_ (new TestProject (this))\n{\n \/\/ Create your members\n}\n\nQtcGtestPlugin::~QtcGtestPlugin()\n{\n \/\/ Unregister objects from the plugin manager's object pool\n \/\/ Delete members\n}\n\nbool QtcGtestPlugin::initialize(const QStringList &arguments, QString *errorString)\n{\n \/\/ Register objects in the plugin manager's object pool\n \/\/ Load settings\n \/\/ Add actions to menus\n \/\/ Connect to other plugins' signals\n \/\/ In the initialize function, a plugin can be sure that the plugins it\n \/\/ depends on have initialized their members.\n\n Q_UNUSED(arguments)\n Q_UNUSED(errorString)\n\n initLanguage ();\n initMenus ();\n\n OutputPane* pane = new OutputPane;\n connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlStarted(ProjectExplorer::RunControl *)),\n pane, SLOT (handleRunStart(ProjectExplorer::RunControl *)));\n connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlFinished(ProjectExplorer::RunControl *)),\n pane, SLOT (handleRunFinish(ProjectExplorer::RunControl *)));\n addAutoReleasedObject (pane);\n\n\n connect (EditorManager::documentModel (),\n SIGNAL (dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)),\n testProject_,\n SLOT (handleDocumentsChange(const QModelIndex &, const QModelIndex &, const QVector<int> &)));\n connect (EditorManager::documentModel (),\n SIGNAL (rowsAboutToBeRemoved(const QModelIndex &, int, int)),\n testProject_,\n SLOT (handleDocumentsClose(const QModelIndex &, int, int)));\n\n return true;\n}\n\nvoid QtcGtestPlugin::initLanguage()\n{\n const QString& language = Core::ICore::userInterfaceLanguage();\n if (!language.isEmpty())\n {\n QStringList paths;\n paths << ICore::resourcePath () << ICore::userResourcePath();\n const QString& trFile = QLatin1String (\"QtcCppcheck_\") + language;\n QTranslator* translator = new QTranslator (this);\n foreach (const QString& path, paths)\n {\n if (translator->load (trFile, path + QLatin1String (\"\/translations\")))\n {\n qApp->installTranslator (translator);\n break;\n }\n }\n }\n}\n\nvoid QtcGtestPlugin::initMenus()\n{\n QAction *checkProjectAction = new QAction(tr(\"Check project\"), this);\n Core::Command *checkProjectCmd = ActionManager::registerAction(\n checkProjectAction, Constants::ACTION_CHECK_PROJECT_ID,\n Context(Core::Constants::C_GLOBAL));\n checkProjectCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+A\")));\n connect(checkProjectAction, SIGNAL(triggered()), testProject_, SLOT(checkProject()));\n\n QAction *checkCurrentAction = new QAction(tr(\"Check current\"), this);\n Core::Command *checkCurrentCmd = ActionManager::registerAction(\n checkCurrentAction, Constants::ACTION_CHECK_CURRENT_ID,\n Context(Core::Constants::C_GLOBAL));\n checkCurrentCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+C\")));\n connect(checkCurrentAction, SIGNAL(triggered()), testProject_, SLOT(checkCurrent()));\n\n QAction *checkChangedAction = new QAction(tr(\"Check changed\"), this);\n Core::Command *checkChangedCmd = ActionManager::registerAction(\n checkChangedAction, Constants::ACTION_CHECK_CHANGED_ID,\n Context(Core::Constants::C_GLOBAL));\n checkChangedCmd->setDefaultKeySequence (QKeySequence (tr (\"Alt+T,Alt+T\")));\n connect(checkChangedAction, SIGNAL(triggered()), testProject_, SLOT(checkChanged()));\n\n ActionContainer *menu = ActionManager::createMenu(Constants::MENU_ID);\n menu->menu()->setTitle(tr(\"Google Test\"));\n menu->addAction(checkProjectCmd);\n menu->addAction(checkCurrentCmd);\n menu->addAction(checkChangedCmd);\n ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu);\n}\n\nvoid QtcGtestPlugin::extensionsInitialized()\n{\n \/\/ Retrieve objects from the plugin manager's object pool\n \/\/ In the extensionsInitialized function, a plugin can be sure that all\n \/\/ plugins that depend on it are completely initialized.\n}\n\nExtensionSystem::IPlugin::ShutdownFlag QtcGtestPlugin::aboutToShutdown()\n{\n \/\/ Save settings\n \/\/ Disconnect from signals that are not needed during shutdown\n \/\/ Hide UI (if you add UI that is not in the main window directly)\n return SynchronousShutdown;\n}\n\nQ_EXPORT_PLUGIN2(QtcGtest, QtcGtestPlugin)\n\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"ResourceLoader.h\"\n#include <iostream>\n#include \"Logger.h\"\n\nstd::string ResourceLoader::loadTextResource(HMODULE moduleHandle, int id, LPTSTR type)\n{\n HRSRC resourceHandle = ::FindResource(moduleHandle, MAKEINTRESOURCE(id), type);\n \n if (!resourceHandle)\n {\n std::string msg(\"Unable to find resource with id: [\");\n msg += std::to_string(id);\n msg += \"] because of error with code: \";\n msg += std::to_string(::GetLastError());\n\n LOG_ERROR(msg);\n throw std::runtime_error(msg);\n }\n\n HGLOBAL resourceData = ::LoadResource(moduleHandle, resourceHandle);\n LPVOID dataFirstByte = ::LockResource(resourceData);\n\n return std::string(static_cast<const char*>(dataFirstByte));\n}\n<commit_msg>Now using the size of the resource when creating the std::string<commit_after>#include \"stdafx.h\"\n#include \"ResourceLoader.h\"\n#include <iostream>\n#include \"Logger.h\"\n\nstd::string ResourceLoader::loadTextResource(HMODULE moduleHandle, int id, LPTSTR type)\n{\n HRSRC resourceHandle = ::FindResource(moduleHandle, MAKEINTRESOURCE(id), type);\n \n if (!resourceHandle)\n {\n std::string msg(\"Unable to find resource with id: [\");\n msg += std::to_string(id);\n msg += \"] because of error with code: \";\n msg += std::to_string(::GetLastError());\n\n LOG_ERROR(msg);\n throw std::runtime_error(msg);\n }\n\n HGLOBAL resourceData = ::LoadResource(moduleHandle, resourceHandle);\n LPVOID dataFirstByte = ::LockResource(resourceData);\n DWORD dataSize = ::SizeofResource(moduleHandle, resourceHandle);\n\n return {static_cast<const char*>(dataFirstByte), dataSize};\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * SubtitleStream.cpp\n * sfeMovie project\n *\n * Copyright (C) 2010-2014 Stephan Vedder\n * stephan.vedder@gmail.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\nextern \"C\"\n{\n#include <libavformat\/avformat.h>\n#include <libavcodec\/avcodec.h>\n}\n\n#include <sfeMovie\/Movie.hpp>\n#include \"SubtitleStream.hpp\"\n#include \"Log.hpp\"\n\n#include <iostream>\n#include <cassert>\n#include <stdint.h>\n\nnamespace sfe\n{\n const int RGBASize = 4;\n \n SubtitleStream::SubtitleStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer, Delegate& delegate) :\n Stream(formatCtx, stream, dataSource, timer), m_delegate(delegate), m_library(nullptr), m_renderer(nullptr), m_track(nullptr)\n {\n const AVCodecDescriptor* desc = av_codec_get_codec_descriptor(m_stream->codec);\n CHECK(desc != NULL, \"Could not get the codec descriptor!\");\n \n if((desc->props & AV_CODEC_PROP_BITMAP_SUB)==0)\n {\n\t\t\tm_library = ass_library_init();\n ass_set_message_cb(m_library, ass_log,nullptr);\n\n\t\t\tm_renderer = ass_renderer_init(m_library);\n m_track = ass_new_track(m_library);\n\n ass_set_frame_size(m_renderer, m_stream->codec->width, m_stream->codec->height);\n ass_set_fonts(m_renderer, NULL, NULL, 1, NULL , 1);\n ass_set_font_scale(m_renderer, 5.0f);\n\n ass_process_codec_private(m_track, reinterpret_cast<char*>(m_stream->codec->subtitle_header), m_stream->codec->subtitle_header_size);\n\t\t}\n }\n \n \/** Default destructor\n *\/\n SubtitleStream::~SubtitleStream()\n {\n if (m_track)\n {\n ass_free_track(m_track);\n m_track = nullptr;\n }\n\n\t\tif(m_renderer)\n\t\t{\n\t\t\tass_renderer_done(m_renderer);\n\t\t\tm_renderer = nullptr;\n\t\t}\n\t\t\n\t\tif(m_library)\n\t\t{\n\t\t\tass_library_done(m_library);\n\t\t\tm_library = nullptr;\n\t\t}\n\t\t\t\n }\n \n MediaType SubtitleStream::getStreamKind() const\n {\n return Subtitle;\n }\n \n void SubtitleStream::update()\n {\n \/\/only get new subtitles if we are running low\n if (m_status == Playing && hasPackets())\n {\n if (!onGetData())\n setStatus(Stopped);\n }\n \n if (m_pendingSubtitles.size() > 0)\n {\n \/\/activate subtitle\n if (m_pendingSubtitles.front()->start < m_timer->getOffset())\n {\n std::shared_ptr<SubtitleData> iter = m_pendingSubtitles.front();\n\n auto time = m_timer->getOffset().asMilliseconds();\n \/\/this is the case for ass subtitles\n if (iter->sprites.size() < 1)\n {\n int change = 0;\n ASS_Image* img = ass_render_frame(m_renderer, m_track, m_timer->getOffset().asMilliseconds(), &change);\n if (change)\n {\n while (img)\n {\n iter->sprites.push_back(sf::Sprite());\n iter->textures.push_back(sf::Texture());\n iter->positions.push_back(sf::Vector2i(img->dst_x, img->dst_y));\n\n sf::Sprite& sprite = iter->sprites.back();\n sf::Texture& texture = iter->textures.back();\n\n texture.create(img->w, img->h);\n texture.update(img->bitmap);\n texture.setSmooth(true);\n\n sprite.setTexture(texture);\n\n img = img->next;\n }\n }\n }\n\n m_delegate.didUpdateSubtitle(*this, iter->sprites, iter->positions);\n m_visibleSubtitles.push_back(iter);\n m_pendingSubtitles.pop_front();\n }\n }\n \n \n if (m_visibleSubtitles.size()>0)\n {\n \/\/remove subtitle\n if (m_visibleSubtitles.front()->end < m_timer->getOffset())\n {\n std::shared_ptr<SubtitleData> subtitle = m_visibleSubtitles.front();\n m_visibleSubtitles.pop_front();\n \n if (m_visibleSubtitles.size() == 0)\n {\n m_delegate.didWipeOutSubtitles(*this);\n }\n }\n }\n }\n \n bool SubtitleStream::isPassive() const\n {\n return true;\n }\n \n bool SubtitleStream::onGetData()\n {\n AVPacket* packet = popEncodedData();\n AVSubtitle sub;\n int32_t gotSub = 0;\n int32_t goOn = 0;\n int64_t pts = 0;\n \n if (packet)\n {\n goOn = 1;\n \n while (!gotSub && packet && goOn)\n {\n bool needsMoreDecoding = false;\n \n CHECK(packet != nullptr, \"inconsistency error\");\n goOn = avcodec_decode_subtitle2(m_stream->codec, &sub, &gotSub, packet);\n \n pts = 0;\n if (packet->pts != AV_NOPTS_VALUE)\n pts = packet->pts;\n \n if (gotSub && pts)\n {\n bool succeeded = false;\n std::shared_ptr<SubtitleData> sfeSub = std::make_shared<SubtitleData>(&sub, succeeded,m_track);\n \n if (succeeded)\n m_pendingSubtitles.push_back(sfeSub);\n }\n \n if (needsMoreDecoding)\n {\n prependEncodedData(packet);\n }\n else\n {\n av_free_packet(packet);\n av_free(packet);\n }\n \n if (!gotSub && goOn)\n {\n sfeLogDebug(\"no subtitle in this packet, reading further\");\n packet = popEncodedData();\n }\n }\n }\n return (goOn >= 0);\n }\n \n \n SubtitleStream::SubtitleData::SubtitleData(AVSubtitle* sub, bool& succeeded,ASS_Track* track)\n {\n assert(sub != nullptr);\n \n succeeded = false;\n start = sf::milliseconds(sub->start_display_time) + sf::microseconds(sub->pts);\n end = sf::milliseconds(sub->end_display_time) + sf::microseconds(sub->pts);\n \n for (unsigned int i = 0; i < sub->num_rects; ++i)\n { \n AVSubtitleRect* subItem = sub->rects[i];\n \n AVSubtitleType type = subItem->type;\n \n if (type == SUBTITLE_BITMAP)\n {\n sprites.push_back(sf::Sprite());\n textures.push_back(sf::Texture());\n\n sf::Sprite& sprite = sprites.back();\n sf::Texture& texture = textures.back();\n\n CHECK(subItem->pict.data != nullptr, \"FFmpeg inconcistency error\");\n CHECK(subItem->w * subItem->h > 0, \"FFmpeg inconcistency error\");\n \n positions.push_back(sf::Vector2i(subItem->x, subItem->y));\n \n std::unique_ptr<uint32_t[]> palette(new uint32_t[subItem->nb_colors]);\n for (int j = 0; j < subItem->nb_colors; j++)\n palette[j] = *(uint32_t*)&subItem->pict.data[1][j * RGBASize];\n \n texture.create(subItem->w, subItem->h);\n texture.setSmooth(true);\n \n std::unique_ptr<uint32_t[]> data(new uint32_t[subItem->w* sub->rects[i]->h]);\n for (int j = 0; j < subItem->w * subItem->h; ++j)\n data[j] = palette[subItem->pict.data[0][j]];\n \n texture.update((uint8_t*)data.get());\n sprite.setTexture(texture);\n \n succeeded = true;\n }\n else\n {\n ass_process_data(track, subItem->ass, strlen(subItem->ass));\n\n succeeded = true;\n }\n }\n }\n \n void SubtitleStream::flushBuffers()\n {\n m_delegate.didWipeOutSubtitles(*this);\n Stream::flushBuffers();\n }\n\n void SubtitleStream::ass_log(int ass_level, const char *fmt, va_list args, void *data)\n {\n char buffer[512];\n\n vsprintf(buffer, fmt, args);\n sfeLogDebug(buffer);\n }\n}\n<commit_msg>Set default font and changed rendering code<commit_after>\n\/*\n * SubtitleStream.cpp\n * sfeMovie project\n *\n * Copyright (C) 2010-2014 Stephan Vedder\n * stephan.vedder@gmail.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\nextern \"C\"\n{\n#include <libavformat\/avformat.h>\n#include <libavcodec\/avcodec.h>\n}\n\n#include <sfeMovie\/Movie.hpp>\n#include \"SubtitleStream.hpp\"\n#include \"Log.hpp\"\n\n#include <iostream>\n#include <cassert>\n#include <stdint.h>\n\n\n#define _r(c) ((c) >> 24)\n#define _g(c) (((c) >> 16) & 0xFF)\n#define _b(c) (((c) >> 8) & 0xFF)\n#define _a(c) (255 - ((c) & 0xFF))\n\nnamespace sfe\n{\n const int RGBASize = 4;\n \n SubtitleStream::SubtitleStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer, Delegate& delegate) :\n Stream(formatCtx, stream, dataSource, timer), m_delegate(delegate), m_library(nullptr), m_renderer(nullptr), m_track(nullptr)\n {\n const AVCodecDescriptor* desc = av_codec_get_codec_descriptor(m_stream->codec);\n CHECK(desc != NULL, \"Could not get the codec descriptor!\");\n \n if((desc->props & AV_CODEC_PROP_BITMAP_SUB)==0)\n {\n\t\t\tm_library = ass_library_init();\n ass_set_message_cb(m_library, ass_log,nullptr);\n\n\t\t\tm_renderer = ass_renderer_init(m_library);\n m_track = ass_new_track(m_library);\n\n ass_set_frame_size(m_renderer, m_stream->codec->width, m_stream->codec->height);\n ass_set_fonts(m_renderer, NULL, \"Sans\", 1, NULL, 1);\n ass_set_font_scale(m_renderer, 10.0f);\n\n ass_process_codec_private(m_track, reinterpret_cast<char*>(m_stream->codec->subtitle_header), m_stream->codec->subtitle_header_size);\n\t\t}\n }\n \n \/** Default destructor\n *\/\n SubtitleStream::~SubtitleStream()\n {\n if (m_track)\n {\n ass_free_track(m_track);\n m_track = nullptr;\n }\n\n\t\tif(m_renderer)\n\t\t{\n\t\t\tass_renderer_done(m_renderer);\n\t\t\tm_renderer = nullptr;\n\t\t}\n\t\t\n\t\tif(m_library)\n\t\t{\n\t\t\tass_library_done(m_library);\n\t\t\tm_library = nullptr;\n\t\t}\n\t\t\t\n }\n \n MediaType SubtitleStream::getStreamKind() const\n {\n return Subtitle;\n }\n \n void SubtitleStream::update()\n {\n \/\/only get new subtitles if we are running low\n if (m_status == Playing && hasPackets())\n {\n if (!onGetData())\n setStatus(Stopped);\n }\n \n if (m_pendingSubtitles.size() > 0)\n {\n \/\/activate subtitle\n if (m_pendingSubtitles.front()->start < m_timer->getOffset())\n {\n std::shared_ptr<SubtitleData> iter = m_pendingSubtitles.front();\n\n auto time = m_timer->getOffset().asMilliseconds();\n \/\/this is the case for ass subtitles\n if (iter->sprites.size() < 1)\n {\n int change = 0;\n ASS_Image* img = ass_render_frame(m_renderer, m_track, m_timer->getOffset().asMilliseconds(), &change);\n \n if (change)\n { \n\n while (img)\n {\n if (!img->w || !img->h) continue;\n\n uint8_t r = img->color >> 24,\n g = img->color >> 16 & 255,\n b = img->color >> 8 & 255,\n a = 255 - (img->color & 255);\n\n sf::Image buffer;\n buffer.create(img->w, img->h);\n\n iter->positions.push_back(sf::Vector2i(img->dst_x, img->dst_y));\n\n for (int y = 0; y < img->h; ++y)\n {\n const unsigned char *map = img->bitmap + y * img->stride;\n\n for (int x = 0; x < img->w; ++x)\n {\n uint8_t alpha = (unsigned)a * *map++;\n buffer.setPixel(x, y, sf::Color(r,g,b,alpha));\n }\n }\n\n img = img->next;\n\n iter->sprites.push_back(sf::Sprite());\n iter->textures.push_back(sf::Texture());\n\n\n sf::Sprite& sprite = iter->sprites.back();\n sf::Texture& texture = iter->textures.back();\n\n texture.create(buffer.getSize().x, buffer.getSize().y);\n texture.update(buffer);\n texture.setSmooth(true);\n\n sprite.setTexture(texture);\n } \n }\n }\n\n m_delegate.didUpdateSubtitle(*this, iter->sprites, iter->positions);\n m_visibleSubtitles.push_back(iter);\n m_pendingSubtitles.pop_front();\n }\n }\n \n \n if (m_visibleSubtitles.size()>0)\n {\n \/\/remove subtitle\n if (m_visibleSubtitles.front()->end < m_timer->getOffset())\n {\n std::shared_ptr<SubtitleData> subtitle = m_visibleSubtitles.front();\n m_visibleSubtitles.pop_front();\n \n if (m_visibleSubtitles.size() == 0)\n {\n m_delegate.didWipeOutSubtitles(*this);\n }\n }\n }\n }\n \n bool SubtitleStream::isPassive() const\n {\n return true;\n }\n \n bool SubtitleStream::onGetData()\n {\n AVPacket* packet = popEncodedData();\n AVSubtitle sub;\n int32_t gotSub = 0;\n int32_t goOn = 0;\n int64_t pts = 0;\n \n if (packet)\n {\n goOn = 1;\n \n while (!gotSub && packet && goOn)\n {\n bool needsMoreDecoding = false;\n \n CHECK(packet != nullptr, \"inconsistency error\");\n goOn = avcodec_decode_subtitle2(m_stream->codec, &sub, &gotSub, packet);\n \n pts = 0;\n if (packet->pts != AV_NOPTS_VALUE)\n pts = packet->pts;\n \n if (gotSub && pts)\n {\n bool succeeded = false;\n std::shared_ptr<SubtitleData> sfeSub = std::make_shared<SubtitleData>(&sub, succeeded,m_track);\n \n if (succeeded)\n m_pendingSubtitles.push_back(sfeSub);\n }\n \n if (needsMoreDecoding)\n {\n prependEncodedData(packet);\n }\n else\n {\n av_free_packet(packet);\n av_free(packet);\n }\n \n if (!gotSub && goOn)\n {\n sfeLogDebug(\"no subtitle in this packet, reading further\");\n packet = popEncodedData();\n }\n }\n }\n return (goOn >= 0);\n }\n \n \n SubtitleStream::SubtitleData::SubtitleData(AVSubtitle* sub, bool& succeeded,ASS_Track* track)\n {\n assert(sub != nullptr);\n \n succeeded = false;\n start = sf::milliseconds(sub->start_display_time) + sf::microseconds(sub->pts);\n end = sf::milliseconds(sub->end_display_time) + sf::microseconds(sub->pts);\n \n for (unsigned int i = 0; i < sub->num_rects; ++i)\n { \n AVSubtitleRect* subItem = sub->rects[i];\n \n AVSubtitleType type = subItem->type;\n \n if (type == SUBTITLE_BITMAP)\n {\n sprites.push_back(sf::Sprite());\n textures.push_back(sf::Texture());\n\n sf::Sprite& sprite = sprites.back();\n sf::Texture& texture = textures.back();\n\n CHECK(subItem->pict.data != nullptr, \"FFmpeg inconcistency error\");\n CHECK(subItem->w * subItem->h > 0, \"FFmpeg inconcistency error\");\n \n positions.push_back(sf::Vector2i(subItem->x, subItem->y));\n \n std::unique_ptr<uint32_t[]> palette(new uint32_t[subItem->nb_colors]);\n for (int j = 0; j < subItem->nb_colors; j++)\n palette[j] = *(uint32_t*)&subItem->pict.data[1][j * RGBASize];\n \n texture.create(subItem->w, subItem->h);\n texture.setSmooth(true);\n \n std::unique_ptr<uint32_t[]> data(new uint32_t[subItem->w* sub->rects[i]->h]);\n for (int j = 0; j < subItem->w * subItem->h; ++j)\n data[j] = palette[subItem->pict.data[0][j]];\n \n texture.update((uint8_t*)data.get());\n sprite.setTexture(texture);\n \n succeeded = true;\n }\n else\n {\n ass_process_data(track, subItem->ass, strlen(subItem->ass));\n\n succeeded = true;\n }\n }\n }\n \n void SubtitleStream::flushBuffers()\n {\n m_delegate.didWipeOutSubtitles(*this);\n Stream::flushBuffers();\n }\n\n void SubtitleStream::ass_log(int ass_level, const char *fmt, va_list args, void *data)\n {\n char buffer[512];\n\n vsprintf(buffer, fmt, args);\n sfeLogDebug(buffer);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/FreezeTransform.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"IECoreScene\/Primitive.h\"\n#include \"IECoreScene\/TransformOp.h\"\n\n#include \"IECore\/DespatchTypedData.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace IECoreScene;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( FreezeTransform );\n\nsize_t FreezeTransform::g_firstPlugIndex = 0;\n\nFreezeTransform::FreezeTransform( const std::string &name )\n\t:\tFilteredSceneProcessor( name, IECore::PathMatcher::EveryMatch )\n{\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\taddChild( new M44fPlug( \"__transform\", Plug::Out ) );\n\n\t\/\/ pass through the things we don't want to change\n\toutPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );\n\toutPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() );\n\toutPlug()->globalsPlug()->setInput( inPlug()->globalsPlug() );\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n\toutPlug()->setPlug()->setInput( inPlug()->setPlug() );\n}\n\nFreezeTransform::~FreezeTransform()\n{\n}\n\nGaffer::M44fPlug *FreezeTransform::transformPlug()\n{\n\treturn getChild<M44fPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::M44fPlug *FreezeTransform::transformPlug() const\n{\n\treturn getChild<M44fPlug>( g_firstPlugIndex );\n}\n\nvoid FreezeTransform::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tFilteredSceneProcessor::affects( input, outputs );\n\n\tif( input == inPlug()->transformPlug() )\n\t{\n\t\toutputs.push_back( transformPlug() );\n\t}\n\telse if( input == inPlug()->objectPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->objectPlug() );\n\t}\n\telse if(\n\t\tinput == transformPlug() ||\n\t\tinput == filterPlug()\n\t)\n\t{\n\t\toutputs.push_back( outPlug()->transformPlug() );\n\t\toutputs.push_back( outPlug()->boundPlug() );\n\t\toutputs.push_back( outPlug()->objectPlug() );\n\t}\n}\n\nvoid FreezeTransform::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tFilteredSceneProcessor::hash( output, context, h );\n\n\tif( output == transformPlug() )\n\t{\n\t\tconst ScenePath &scenePath = context->get<ScenePath>( ScenePlug::scenePathContextName );\n\t\th.append( inPlug()->fullTransformHash( scenePath ) );\n\t\th.append( outPlug()->fullTransformHash( scenePath ) );\n\t}\n}\n\nvoid FreezeTransform::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const\n{\n\tif( output == transformPlug() )\n\t{\n\t\t\/\/\/ \\todo Would it speed things up if we computed this from the parent full transforms and\n\t\t\/\/\/ the local transforms? So we don't traverse the full path at each location?\n\t\tconst ScenePath &scenePath = context->get<ScenePath>( ScenePlug::scenePathContextName );\n\t\tconst M44f inTransform = inPlug()->fullTransform( scenePath );\n\t\tconst M44f outTransform = outPlug()->fullTransform( scenePath );\n\t\tconst M44f transform = inTransform * outTransform.inverse();\n\t\tstatic_cast<M44fPlug *>( output )->setValue( transform );\n\t\treturn;\n\t}\n\n\tFilteredSceneProcessor::compute( output, context );\n}\n\nvoid FreezeTransform::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\t\/\/ if there's an ancestor match or an exact match here then we know\n\t\t\/\/ that we'll be baking in a transform into the objects below us, and\n\t\t\/\/ thus changing the bounds - so we must compute them properly from\n\t\t\/\/ children.\n\t\tSceneProcessor::hashBound( path, context, parent, h );\n\t\th.append( hashOfTransformedChildBounds( path, outPlug() ) );\n\t\t\/\/ we may also be changing the bounds at this specific location.\n\t\tinPlug()->boundPlug()->hash( h );\n\t\ttransformPlug()->hash( h );\n\t}\n\telse\n\t{\n\t\t\/\/ if there's no match, we can just pass through the bound\n\t\t\/\/ unchanged. additionally, if there's a descendant match we\n\t\t\/\/ can do the same - because the descendant will just be transferring\n\t\t\/\/ the descendant transform into the descendant bound, the overall\n\t\t\/\/ bound as we see it will actually be remaining the same.\n\t\th = inPlug()->boundPlug()->hash();\n\t}\n}\n\nImath::Box3f FreezeTransform::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tBox3f result = unionOfTransformedChildBounds( path, outPlug() );\n\t\tBox3f b = inPlug()->boundPlug()->getValue();\n\t\tb = transform( b, transformPlug()->getValue() );\n\t\tresult.extendBy( b );\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\treturn inPlug()->boundPlug()->getValue();\n\t}\n}\n\nvoid FreezeTransform::hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & IECore::PathMatcher::ExactMatch )\n\t{\n\t\tSceneProcessor::hashTransform( path, context, parent, h );\n\t}\n\telse\n\t{\n\t\th = inPlug()->transformPlug()->hash();\n\t}\n}\n\nImath::M44f FreezeTransform::computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & IECore::PathMatcher::ExactMatch )\n\t{\n\t\treturn M44f();\n\t}\n\telse\n\t{\n\t\treturn inPlug()->transformPlug()->getValue();\n\t}\n}\n\nvoid FreezeTransform::hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tFilteredSceneProcessor::hashObject( path, context, parent, h );\n\t\tinPlug()->objectPlug()->hash( h );\n\t\ttransformPlug()->hash( h );\n\t}\n\telse\n\t{\n\t\th = inPlug()->objectPlug()->hash();\n\t}\n}\n\nIECore::ConstObjectPtr FreezeTransform::computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tConstObjectPtr inputObject = inPlug()->objectPlug()->getValue();\n\t\tconst Primitive *inputPrimitive = runTimeCast<const Primitive>( inputObject.get() );\n\t\tif( !inputPrimitive )\n\t\t{\n\t\t\treturn inputObject;\n\t\t}\n\n\t\tPrimitivePtr outputPrimitive = inputPrimitive->copy();\n\n\t\t\/\/\/ \\todo This is a pain - we need functionality in Cortex to just automatically apply\n\t\t\/\/\/ the transform to all appropriate primitive variables, without having to manually\n\t\t\/\/\/ list them. At the same time, we could add a PrimitiveAlgo.h file to Cortex, allowing\n\t\t\/\/\/ us to apply a transform without having to create an Op to do it.\n\t\tvector<string> primVarNames;\n\t\tfor( PrimitiveVariableMap::const_iterator it = inputPrimitive->variables.begin(), eIt = inputPrimitive->variables.end(); it != eIt; ++it )\n\t\t{\n\t\t\tif( despatchTraitsTest<TypeTraits::IsFloatVec3VectorTypedData>( it->second.data.get() ) )\n\t\t\t{\n\t\t\t\tprimVarNames.push_back( it->first );\n\t\t\t}\n\t\t}\n\n\t\tconst M44f transform = transformPlug()->getValue();\n\n\t\tTransformOpPtr transformOp = new TransformOp;\n\t\ttransformOp->inputParameter()->setValue( outputPrimitive );\n\t\ttransformOp->copyParameter()->setTypedValue( false );\n\t\ttransformOp->matrixParameter()->setValue( new M44fData( transform ) );\n\t\ttransformOp->primVarsParameter()->setTypedValue( primVarNames );\n\t\ttransformOp->operate();\n\n\t\treturn outputPrimitive;\n\t}\n\telse\n\t{\n\t\treturn inPlug()->objectPlug()->getValue();\n\t}\n}\n<commit_msg>FreezeTransform : Replace `despatchTraitsTest()` with `DataAlgo::trait()`<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/FreezeTransform.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"IECoreScene\/Primitive.h\"\n#include \"IECoreScene\/TransformOp.h\"\n\n#include \"IECore\/DataAlgo.h\"\n#include \"IECore\/TypeTraits.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace IECoreScene;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( FreezeTransform );\n\nsize_t FreezeTransform::g_firstPlugIndex = 0;\n\nFreezeTransform::FreezeTransform( const std::string &name )\n\t:\tFilteredSceneProcessor( name, IECore::PathMatcher::EveryMatch )\n{\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\taddChild( new M44fPlug( \"__transform\", Plug::Out ) );\n\n\t\/\/ pass through the things we don't want to change\n\toutPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );\n\toutPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() );\n\toutPlug()->globalsPlug()->setInput( inPlug()->globalsPlug() );\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n\toutPlug()->setPlug()->setInput( inPlug()->setPlug() );\n}\n\nFreezeTransform::~FreezeTransform()\n{\n}\n\nGaffer::M44fPlug *FreezeTransform::transformPlug()\n{\n\treturn getChild<M44fPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::M44fPlug *FreezeTransform::transformPlug() const\n{\n\treturn getChild<M44fPlug>( g_firstPlugIndex );\n}\n\nvoid FreezeTransform::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tFilteredSceneProcessor::affects( input, outputs );\n\n\tif( input == inPlug()->transformPlug() )\n\t{\n\t\toutputs.push_back( transformPlug() );\n\t}\n\telse if( input == inPlug()->objectPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->objectPlug() );\n\t}\n\telse if(\n\t\tinput == transformPlug() ||\n\t\tinput == filterPlug()\n\t)\n\t{\n\t\toutputs.push_back( outPlug()->transformPlug() );\n\t\toutputs.push_back( outPlug()->boundPlug() );\n\t\toutputs.push_back( outPlug()->objectPlug() );\n\t}\n}\n\nvoid FreezeTransform::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tFilteredSceneProcessor::hash( output, context, h );\n\n\tif( output == transformPlug() )\n\t{\n\t\tconst ScenePath &scenePath = context->get<ScenePath>( ScenePlug::scenePathContextName );\n\t\th.append( inPlug()->fullTransformHash( scenePath ) );\n\t\th.append( outPlug()->fullTransformHash( scenePath ) );\n\t}\n}\n\nvoid FreezeTransform::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const\n{\n\tif( output == transformPlug() )\n\t{\n\t\t\/\/\/ \\todo Would it speed things up if we computed this from the parent full transforms and\n\t\t\/\/\/ the local transforms? So we don't traverse the full path at each location?\n\t\tconst ScenePath &scenePath = context->get<ScenePath>( ScenePlug::scenePathContextName );\n\t\tconst M44f inTransform = inPlug()->fullTransform( scenePath );\n\t\tconst M44f outTransform = outPlug()->fullTransform( scenePath );\n\t\tconst M44f transform = inTransform * outTransform.inverse();\n\t\tstatic_cast<M44fPlug *>( output )->setValue( transform );\n\t\treturn;\n\t}\n\n\tFilteredSceneProcessor::compute( output, context );\n}\n\nvoid FreezeTransform::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\t\/\/ if there's an ancestor match or an exact match here then we know\n\t\t\/\/ that we'll be baking in a transform into the objects below us, and\n\t\t\/\/ thus changing the bounds - so we must compute them properly from\n\t\t\/\/ children.\n\t\tSceneProcessor::hashBound( path, context, parent, h );\n\t\th.append( hashOfTransformedChildBounds( path, outPlug() ) );\n\t\t\/\/ we may also be changing the bounds at this specific location.\n\t\tinPlug()->boundPlug()->hash( h );\n\t\ttransformPlug()->hash( h );\n\t}\n\telse\n\t{\n\t\t\/\/ if there's no match, we can just pass through the bound\n\t\t\/\/ unchanged. additionally, if there's a descendant match we\n\t\t\/\/ can do the same - because the descendant will just be transferring\n\t\t\/\/ the descendant transform into the descendant bound, the overall\n\t\t\/\/ bound as we see it will actually be remaining the same.\n\t\th = inPlug()->boundPlug()->hash();\n\t}\n}\n\nImath::Box3f FreezeTransform::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tBox3f result = unionOfTransformedChildBounds( path, outPlug() );\n\t\tBox3f b = inPlug()->boundPlug()->getValue();\n\t\tb = transform( b, transformPlug()->getValue() );\n\t\tresult.extendBy( b );\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\treturn inPlug()->boundPlug()->getValue();\n\t}\n}\n\nvoid FreezeTransform::hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & IECore::PathMatcher::ExactMatch )\n\t{\n\t\tSceneProcessor::hashTransform( path, context, parent, h );\n\t}\n\telse\n\t{\n\t\th = inPlug()->transformPlug()->hash();\n\t}\n}\n\nImath::M44f FreezeTransform::computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & IECore::PathMatcher::ExactMatch )\n\t{\n\t\treturn M44f();\n\t}\n\telse\n\t{\n\t\treturn inPlug()->transformPlug()->getValue();\n\t}\n}\n\nvoid FreezeTransform::hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tFilteredSceneProcessor::hashObject( path, context, parent, h );\n\t\tinPlug()->objectPlug()->hash( h );\n\t\ttransformPlug()->hash( h );\n\t}\n\telse\n\t{\n\t\th = inPlug()->objectPlug()->hash();\n\t}\n}\n\nIECore::ConstObjectPtr FreezeTransform::computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tconst unsigned m = filterPlug()->getValue();\n\tif( m & ( IECore::PathMatcher::AncestorMatch | IECore::PathMatcher::ExactMatch ) )\n\t{\n\t\tConstObjectPtr inputObject = inPlug()->objectPlug()->getValue();\n\t\tconst Primitive *inputPrimitive = runTimeCast<const Primitive>( inputObject.get() );\n\t\tif( !inputPrimitive )\n\t\t{\n\t\t\treturn inputObject;\n\t\t}\n\n\t\tPrimitivePtr outputPrimitive = inputPrimitive->copy();\n\n\t\t\/\/\/ \\todo This is a pain - we need functionality in Cortex to just automatically apply\n\t\t\/\/\/ the transform to all appropriate primitive variables, without having to manually\n\t\t\/\/\/ list them. At the same time, we could add a PrimitiveAlgo.h file to Cortex, allowing\n\t\t\/\/\/ us to apply a transform without having to create an Op to do it.\n\t\tvector<string> primVarNames;\n\t\tfor( PrimitiveVariableMap::const_iterator it = inputPrimitive->variables.begin(), eIt = inputPrimitive->variables.end(); it != eIt; ++it )\n\t\t{\n\t\t\tif( trait<TypeTraits::IsFloatVec3VectorTypedData>( it->second.data.get() ) )\n\t\t\t{\n\t\t\t\tprimVarNames.push_back( it->first );\n\t\t\t}\n\t\t}\n\n\t\tconst M44f transform = transformPlug()->getValue();\n\n\t\tTransformOpPtr transformOp = new TransformOp;\n\t\ttransformOp->inputParameter()->setValue( outputPrimitive );\n\t\ttransformOp->copyParameter()->setTypedValue( false );\n\t\ttransformOp->matrixParameter()->setValue( new M44fData( transform ) );\n\t\ttransformOp->primVarsParameter()->setTypedValue( primVarNames );\n\t\ttransformOp->operate();\n\n\t\treturn outputPrimitive;\n\t}\n\telse\n\t{\n\t\treturn inPlug()->objectPlug()->getValue();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/* Un-comment to use buffer instead of std out *\/\n\/\/ #define USE_BUFFER_OUTPUT 1\n#include <cstdlib>\n\n#include \"CppUTest\/TestHarness.h\"\n#undef malloc\n#undef free\n#undef calloc\n#undef realloc\n\n#define far \/\/ eliminate \"meaningless type qualifier\" warning\n#include <time.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <setjmp.h>\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#undef far\n\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nstatic jmp_buf test_exit_jmp_buf[10];\nstatic int jmp_buf_index = 0;\n\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\n{\n return TestOutput::eclipse;\n}\n\nstatic void DummyRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)\n{\n result->addFailure(TestFailure(shell, \"-p doesn't work on this platform, as it is lacking fork.\\b\"));\n}\n\nvoid (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) =\n DummyRunTestInASeperateProcess;\n\nextern \"C\" {\n\nstatic int DosSetJmp(void (*function) (void* data), void* data)\n{\n if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\n jmp_buf_index++;\n function(data);\n jmp_buf_index--;\n return 1;\n }\n return 0;\n}\n\nstatic void DosLongJmp()\n{\n jmp_buf_index--;\n longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\n}\n\nstatic void DosRestoreJumpBuffer()\n{\n jmp_buf_index--;\n}\n\nint (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = DosSetJmp;\nvoid (*PlatformSpecificLongJmp)(void) = DosLongJmp;\nvoid (*PlatformSpecificRestoreJumpBuffer)(void) = DosRestoreJumpBuffer;\n\nstatic long DosTimeInMillis()\n{\n return clock() * 1000 \/ CLOCKS_PER_SEC;\n}\n\nstatic const char* TimeStringImplementation()\n{\n time_t tm = time(NULL);\n return ctime(&tm);\n}\n\nlong (*GetPlatformSpecificTimeInMillis)() = DosTimeInMillis;\nconst char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;\n\nextern int (*PlatformSpecificVSNprintf)(char *, size_t, const char*, va_list) = vsnprintf;\n\nPlatformSpecificFile DosFOpen(const char* filename, const char* flag)\n{\n return fopen(filename, flag);\n}\n\nstatic void DosFPuts(const char* str, PlatformSpecificFile file)\n{\n fputs(str, (FILE*)file);\n}\n\nstatic void DosFClose(PlatformSpecificFile file)\n{\n fclose((FILE*)file);\n}\n\nPlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = DosFOpen;\nvoid (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = DosFPuts;\nvoid (*PlatformSpecificFClose)(PlatformSpecificFile file) = DosFClose;\n\nstatic int DosPutchar(int c)\n{\n return putchar(c);\n}\n\nstatic void DosFlush()\n{\n fflush(stdout);\n}\n\nextern int (*PlatformSpecificPutchar)(int c) = DosPutchar;\nextern void (*PlatformSpecificFlush)(void) = DosFlush;\n\nstatic void* DosMalloc(size_t size)\n{\n return malloc(size);\n}\n\nstatic void* DosRealloc (void* memory, size_t size)\n{\n return realloc(memory, size);\n}\n\nstatic void DosFree(void* memory)\n{\n free(memory);\n}\n\nstatic void* DosMemCpy(void* s1, const void* s2, size_t size)\n{\n return memcpy(s1, s2, size);\n}\n\nstatic void* DosMemset(void* mem, int c, size_t size)\n{\n return memset(mem, c, size);\n}\n\nvoid* (*PlatformSpecificMalloc)(size_t size) = DosMalloc;\nvoid* (*PlatformSpecificRealloc)(void* memory, size_t size) = DosRealloc;\nvoid (*PlatformSpecificFree)(void* memory) = DosFree;\nvoid* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = DosMemCpy;\nvoid* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = DosMemset;\n\nstatic int IsNanImplementation(double d)\n{\n return isnan(d);\n}\n\nstatic int IsInfImplementation(double d)\n{\n return isinf(d);\n}\n\ndouble (*PlatformSpecificFabs)(double) = fabs;\nint (*PlatformSpecificIsNan)(double d) = IsNanImplementation;\nint (*PlatformSpecificIsInf)(double d) = IsInfImplementation;\n\nstatic PlatformSpecificMutex DummyMutexCreate(void)\n{\n return 0;\n}\n\nstatic void DummyMutexLock(PlatformSpecificMutex mtx)\n{\n}\n\nstatic void DummyMutexUnlock(PlatformSpecificMutex mtx)\n{\n}\n\nstatic void DummyMutexDestroy(PlatformSpecificMutex mtx)\n{\n}\n\nPlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;\nvoid (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;\nvoid (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;\nvoid (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;\n\n}\n<commit_msg>remove superfluous extern<commit_after>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/* Un-comment to use buffer instead of std out *\/\n\/\/ #define USE_BUFFER_OUTPUT 1\n#include <cstdlib>\n\n#include \"CppUTest\/TestHarness.h\"\n#undef malloc\n#undef free\n#undef calloc\n#undef realloc\n\n#define far \/\/ eliminate \"meaningless type qualifier\" warning\n#include <time.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <setjmp.h>\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#undef far\n\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nstatic jmp_buf test_exit_jmp_buf[10];\nstatic int jmp_buf_index = 0;\n\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\n{\n return TestOutput::eclipse;\n}\n\nstatic void DummyRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)\n{\n result->addFailure(TestFailure(shell, \"-p doesn't work on this platform, as it is lacking fork.\\b\"));\n}\n\nvoid (*PlatformSpecificRunTestInASeperateProcess)(UtestShell*, TestPlugin*, TestResult*) =\n DummyRunTestInASeperateProcess;\n\nextern \"C\" {\n\nstatic int DosSetJmp(void (*function) (void* data), void* data)\n{\n if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\n jmp_buf_index++;\n function(data);\n jmp_buf_index--;\n return 1;\n }\n return 0;\n}\n\nstatic void DosLongJmp()\n{\n jmp_buf_index--;\n longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\n}\n\nstatic void DosRestoreJumpBuffer()\n{\n jmp_buf_index--;\n}\n\nint (*PlatformSpecificSetJmp)(void (*function) (void*), void*) = DosSetJmp;\nvoid (*PlatformSpecificLongJmp)(void) = DosLongJmp;\nvoid (*PlatformSpecificRestoreJumpBuffer)(void) = DosRestoreJumpBuffer;\n\nstatic long DosTimeInMillis()\n{\n return clock() * 1000 \/ CLOCKS_PER_SEC;\n}\n\nstatic const char* TimeStringImplementation()\n{\n time_t tm = time(NULL);\n return ctime(&tm);\n}\n\nlong (*GetPlatformSpecificTimeInMillis)() = DosTimeInMillis;\nconst char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;\n\nint (*PlatformSpecificVSNprintf)(char *, size_t, const char*, va_list) = vsnprintf;\n\nPlatformSpecificFile DosFOpen(const char* filename, const char* flag)\n{\n return fopen(filename, flag);\n}\n\nstatic void DosFPuts(const char* str, PlatformSpecificFile file)\n{\n fputs(str, (FILE*)file);\n}\n\nstatic void DosFClose(PlatformSpecificFile file)\n{\n fclose((FILE*)file);\n}\n\nPlatformSpecificFile (*PlatformSpecificFOpen)(const char* filename, const char* flag) = DosFOpen;\nvoid (*PlatformSpecificFPuts)(const char* str, PlatformSpecificFile file) = DosFPuts;\nvoid (*PlatformSpecificFClose)(PlatformSpecificFile file) = DosFClose;\n\nstatic int DosPutchar(int c)\n{\n return putchar(c);\n}\n\nstatic void DosFlush()\n{\n fflush(stdout);\n}\n\nextern int (*PlatformSpecificPutchar)(int c) = DosPutchar;\nextern void (*PlatformSpecificFlush)(void) = DosFlush;\n\nstatic void* DosMalloc(size_t size)\n{\n return malloc(size);\n}\n\nstatic void* DosRealloc (void* memory, size_t size)\n{\n return realloc(memory, size);\n}\n\nstatic void DosFree(void* memory)\n{\n free(memory);\n}\n\nstatic void* DosMemCpy(void* s1, const void* s2, size_t size)\n{\n return memcpy(s1, s2, size);\n}\n\nstatic void* DosMemset(void* mem, int c, size_t size)\n{\n return memset(mem, c, size);\n}\n\nvoid* (*PlatformSpecificMalloc)(size_t size) = DosMalloc;\nvoid* (*PlatformSpecificRealloc)(void* memory, size_t size) = DosRealloc;\nvoid (*PlatformSpecificFree)(void* memory) = DosFree;\nvoid* (*PlatformSpecificMemCpy)(void* s1, const void* s2, size_t size) = DosMemCpy;\nvoid* (*PlatformSpecificMemset)(void* mem, int c, size_t size) = DosMemset;\n\nstatic int IsNanImplementation(double d)\n{\n return isnan(d);\n}\n\nstatic int IsInfImplementation(double d)\n{\n return isinf(d);\n}\n\ndouble (*PlatformSpecificFabs)(double) = fabs;\nint (*PlatformSpecificIsNan)(double d) = IsNanImplementation;\nint (*PlatformSpecificIsInf)(double d) = IsInfImplementation;\n\nstatic PlatformSpecificMutex DummyMutexCreate(void)\n{\n return 0;\n}\n\nstatic void DummyMutexLock(PlatformSpecificMutex mtx)\n{\n}\n\nstatic void DummyMutexUnlock(PlatformSpecificMutex mtx)\n{\n}\n\nstatic void DummyMutexDestroy(PlatformSpecificMutex mtx)\n{\n}\n\nPlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = DummyMutexCreate;\nvoid (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = DummyMutexLock;\nvoid (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = DummyMutexUnlock;\nvoid (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = DummyMutexDestroy;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Qumulus UML editor\n * Author: Frank Erens\n * Author: Randy Thiemann\n *\n *\/\n\n#include \"SideBar.h\"\n#include <Gui\/Widgets\/MainWindow.h>\n\n#include <QtWidgets\/QHeaderView>\n\n#include <iostream>\n\nQUML_BEGIN_NAMESPACE_GW\n\nSideBar::SideBar(MainWindow* parent, QuGD::Diagram* d) :\n QTreeView(parent),\n mDiagram(d),\n mModel(new QuGC::SideBarModel(mDiagram)){\n#ifdef Q_OS_MAC\n setStyleType(StyleType::Active);\n setAttribute(Qt::WA_MacShowFocusRect, false);\n#endif\n setMinimumWidth(100);\n QSizePolicy sideBarSizePolicy = sizePolicy();\n sideBarSizePolicy.setHorizontalPolicy(QSizePolicy::Minimum);\n setSizePolicy(sideBarSizePolicy);\n setModel(mModel);\n header()->close();\n mDiagram->diagramChanged += [this] {\n collapseAll();\n expandAll();\n };\n}\n\nSideBar::~SideBar() {\n delete mModel;\n}\n\nMainWindow* SideBar::window() {\n return static_cast<MainWindow*>(parent());\n}\n\n#ifdef Q_OS_MAC\nvoid SideBar::setStyleType(StyleType s) {\n switch(s) {\n case StyleType::Active:\n setStyleSheet(\n \"background-color: qlineargradient(\"\n \"spread:pad, x1:0, y1:0, x2:0, y2:1,\"\n \"stop:0 rgba(232, 236, 241, 255),\"\n \"stop:1 rgba(209,216,226, 255));\"\n \"selection-color: white;\"\n \"selection-background-color: qlineargradient(\"\n \"x1: 0, y1: 0, x2: 0, y2: 1,\"\n \"stop: 0 rgb(110, 165, 218),\"\n \"stop: 1 rgb(33, 108, 183));\"\n \"border-top: 1px solid silver;\"\n \"border-bottom: 1px solid silver;\"\n \"font-size: 11pt;\"\n );\n break;\n case StyleType::Inactive:\n setStyleSheet(\n \"background-color: qlineargradient(\"\n \"spread:pad, x1:0, y1:0, x2:0, y2:1,\"\n \"stop:0 rgba(247, 247, 247, 255),\"\n \"stop:1 rgba(235, 235, 235, 255));\"\n \"selection-color: white;\"\n \"selection-background-color: qlineargradient(\"\n \"x1: 0, y1: 0, x2: 0, y2: 1,\"\n \"stop: 0 rgb(110, 165, 218),\"\n \"stop: 1 rgb(33, 108, 183));\"\n \"border-top: 1px solid silver;\"\n \"border-bottom: 1px solid silver;\"\n \"font-size: 11pt;\"\n );\n break;\n }\n\n}\n#endif\n\nQUML_END_NAMESPACE_GW\n\n<commit_msg>Debug: remove all autocollapse features.<commit_after>\/*\n * Qumulus UML editor\n * Author: Frank Erens\n * Author: Randy Thiemann\n *\n *\/\n\n#include \"SideBar.h\"\n#include <Gui\/Widgets\/MainWindow.h>\n\n#include <QtWidgets\/QHeaderView>\n\n#include <iostream>\n\nQUML_BEGIN_NAMESPACE_GW\n\nSideBar::SideBar(MainWindow* parent, QuGD::Diagram* d) :\n QTreeView(parent),\n mDiagram(d),\n mModel(new QuGC::SideBarModel(mDiagram)){\n#ifdef Q_OS_MAC\n setStyleType(StyleType::Active);\n setAttribute(Qt::WA_MacShowFocusRect, false);\n#endif\n setMinimumWidth(100);\n QSizePolicy sideBarSizePolicy = sizePolicy();\n sideBarSizePolicy.setHorizontalPolicy(QSizePolicy::Minimum);\n setSizePolicy(sideBarSizePolicy);\n setModel(mModel);\n header()->close();\n \/\/ mDiagram->diagramChanged += [this] {\n \/\/ collapseAll();\n \/\/ expandAll();\n \/\/ };\n}\n\nSideBar::~SideBar() {\n delete mModel;\n}\n\nMainWindow* SideBar::window() {\n return static_cast<MainWindow*>(parent());\n}\n\n#ifdef Q_OS_MAC\nvoid SideBar::setStyleType(StyleType s) {\n switch(s) {\n case StyleType::Active:\n setStyleSheet(\n \"background-color: qlineargradient(\"\n \"spread:pad, x1:0, y1:0, x2:0, y2:1,\"\n \"stop:0 rgba(232, 236, 241, 255),\"\n \"stop:1 rgba(209,216,226, 255));\"\n \"selection-color: white;\"\n \"selection-background-color: qlineargradient(\"\n \"x1: 0, y1: 0, x2: 0, y2: 1,\"\n \"stop: 0 rgb(110, 165, 218),\"\n \"stop: 1 rgb(33, 108, 183));\"\n \"border-top: 1px solid silver;\"\n \"border-bottom: 1px solid silver;\"\n \"font-size: 11pt;\"\n );\n break;\n case StyleType::Inactive:\n setStyleSheet(\n \"background-color: qlineargradient(\"\n \"spread:pad, x1:0, y1:0, x2:0, y2:1,\"\n \"stop:0 rgba(247, 247, 247, 255),\"\n \"stop:1 rgba(235, 235, 235, 255));\"\n \"selection-color: white;\"\n \"selection-background-color: qlineargradient(\"\n \"x1: 0, y1: 0, x2: 0, y2: 1,\"\n \"stop: 0 rgb(110, 165, 218),\"\n \"stop: 1 rgb(33, 108, 183));\"\n \"border-top: 1px solid silver;\"\n \"border-bottom: 1px solid silver;\"\n \"font-size: 11pt;\"\n );\n break;\n }\n\n}\n#endif\n\nQUML_END_NAMESPACE_GW\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN__MATH__PRIM__SCAL__PROB__NORMAL_SUFFICIENT_LOG_HPP\n#define STAN__MATH__PRIM__SCAL__PROB__NORMAL_SUFFICIENT_LOG_HPP\n\n#include <stan\/math\/prim\/scal\/meta\/OperandsAndPartials.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_consistent_sizes.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_finite.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_not_nan.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive.hpp>\n#include <stan\/math\/prim\/scal\/fun\/constants.hpp>\n#include <stan\/math\/prim\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/scal\/meta\/include_summand.hpp>\n#include <stan\/math\/prim\/scal\/meta\/VectorBuilder.hpp>\n#include <stan\/math\/prim\/scal\/meta\/max_size.hpp>\n\nnamespace stan {\n\n namespace math {\n\n \/**\n * The log of the normal density for the specified scalar(s) given\n * the specified mean(s) and deviation(s). y, mu, or sigma can\n * each be either a scalar or a std vector. Any vector inputs\n * must be the same length.\n *\n * <p>The result log probability is defined to be the sum of the\n * log probabilities for each observation\/mean\/deviation triple.\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location parameter(s)\n * for the normal distribution.\n * @param sigma (Sequence of) scale parameters for the normal\n * distribution.\n * @return The log of the product of the densities.\n * @throw std::domain_error if the scale is not positive.\n * @tparam T_y Underlying type of scalar in sequence.\n * @tparam T_loc Type of location parameter.\n *\/\n template <bool propto,\n typename T_y, typename T_s, typename T_n, typename T_loc,\n typename T_scale>\n typename return_type<T_y, T_s, T_loc, T_scale>::type\n normal_sufficient_log(const T_y& y_bar, const T_s& s_squared,\n const T_n& n_obs, const T_loc& mu,\n const T_scale& sigma) {\n static const char* function = \"stan::math::normal_log(%1%)\";\n typedef typename\n stan::partials_return_type<T_y, T_s, T_n, T_loc, T_scale>::type\n T_partials_return;\n\n using std::log;\n using stan::is_constant_struct;\n using stan::math::check_positive;\n using stan::math::check_finite;\n using stan::math::check_not_nan;\n using stan::math::check_consistent_sizes;\n using stan::math::value_of;\n using stan::math::include_summand;\n\n \/\/ check if any vectors are zero length\n if (!(stan::length(y_bar)\n && stan::length(s_squared)\n && stan::length(n_obs)\n && stan::length(mu)\n && stan::length(sigma)))\n return 0.0;\n\n \/\/ set up return value accumulator\n T_partials_return logp(0.0);\n\n \/\/ validate args (here done over var, which should be OK)\n check_not_nan(function,\n \"Location parameter sufficient statistic\", y_bar);\n check_not_nan(function,\n \"Scale parameter sufficient statistic\", s_squared);\n check_not_nan(function,\n \"Number of observations\", n_obs);\n check_finite(function,\n \"Number of observations\", n_obs);\n check_positive(function,\n \"Number of observations\", n_obs);\n check_finite(function,\n \"Location parameter\", mu);\n check_positive(function, \"Scale parameter\", sigma);\n check_consistent_sizes(function,\n \"Location parameter sufficient statistic\",\n y_bar,\n \"Scale parameter sufficient statistic\",\n s_squared,\n \"Number of observations\", n_obs,\n \"Location parameter\", mu,\n \"Scale parameter\", sigma);\n \/\/ check if no variables are involved and prop-to\n if (!include_summand<propto, T_y, T_s, T_loc, T_scale>::value)\n return 0.0;\n\n \/\/ set up template expressions wrapping scalars into vector views\n OperandsAndPartials<T_y, T_s, T_loc, T_scale>\n operands_and_partials(y_bar, s_squared, mu, sigma);\n\n VectorView<const T_y> y_bar_vec(y_bar);\n VectorView<const T_s> s_squared_vec(s_squared);\n VectorView<const T_n> n_obs_vec(n_obs);\n VectorView<const T_loc> mu_vec(mu);\n VectorView<const T_scale> sigma_vec(sigma);\n size_t N = max_size(y_bar, s_squared, n_obs, mu, sigma);\n\n for (size_t i = 0; i < N; i++) {\n const T_partials_return y_bar_dbl = value_of(y_bar_vec[i]);\n const T_partials_return s_squared_dbl =\n value_of(s_squared_vec[i]);\n const T_partials_return n_obs_dbl = n_obs_vec[i];\n const T_partials_return mu_dbl = value_of(mu_vec[i]);\n const T_partials_return sigma_dbl = value_of(sigma_vec[i]);\n const T_partials_return sigma_squared = pow(sigma_dbl, 2);\n\n if (include_summand<propto>::value)\n logp += NEG_LOG_SQRT_TWO_PI * n_obs_dbl;\n\n if (include_summand<propto, T_scale>::value)\n logp -= n_obs_dbl*log(sigma_dbl);\n\n\n const T_partials_return cons_expr =\n (s_squared_dbl\n + n_obs_dbl * pow(y_bar_dbl - mu_dbl, 2));\n\n logp -= cons_expr \/ (2 * sigma_squared);\n\n\n \/\/ gradients\n if (!is_constant_struct<T_y>::value ||\n !is_constant_struct<T_loc>::value) {\n const T_partials_return common_derivative =\n n_obs_dbl * (mu_dbl - y_bar_dbl) \/ sigma_squared;\n if (!is_constant_struct<T_y>::value)\n operands_and_partials.d_x1[i] += common_derivative;\n if (!is_constant_struct<T_loc>::value)\n operands_and_partials.d_x3[i] -= common_derivative;\n }\n if (!is_constant_struct<T_s>::value)\n operands_and_partials.d_x2[i] -=\n 1 \/ (2 * sigma_squared);\n if (!is_constant_struct<T_scale>::value)\n operands_and_partials.d_x4[i]\n += cons_expr \/ pow(sigma_dbl, 3) - n_obs_dbl \/ sigma_dbl;\n }\n return\n operands_and_partials.to_var(logp, y_bar, s_squared, mu, sigma);\n }\n\n template <typename T_y, typename T_s, typename T_n,\n typename T_loc, typename T_scale>\n inline\n typename return_type<T_y, T_s, T_loc, T_scale>::type\n normal_sufficient_log(const T_y& y_bar, const T_s& s_squared,\n const T_n& n_obs, const T_loc& mu,\n const T_scale& sigma) {\n return\n normal_sufficient_log<false>(y_bar, s_squared, n_obs, mu, sigma);\n }\n\n }\n}\n#endif\n<commit_msg>822: remove double underscore<commit_after>#ifndef STAN_MATH_PRIM_SCAL_PROB_NORMAL_SUFFICIENT_LOG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NORMAL_SUFFICIENT_LOG_HPP\n\n#include <stan\/math\/prim\/scal\/meta\/OperandsAndPartials.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_consistent_sizes.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_finite.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_not_nan.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive.hpp>\n#include <stan\/math\/prim\/scal\/fun\/constants.hpp>\n#include <stan\/math\/prim\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/scal\/meta\/include_summand.hpp>\n#include <stan\/math\/prim\/scal\/meta\/VectorBuilder.hpp>\n#include <stan\/math\/prim\/scal\/meta\/max_size.hpp>\n\nnamespace stan {\n\n namespace math {\n\n \/**\n * The log of the normal density for the specified scalar(s) given\n * the specified mean(s) and deviation(s). y, mu, or sigma can\n * each be either a scalar or a std vector. Any vector inputs\n * must be the same length.\n *\n * <p>The result log probability is defined to be the sum of the\n * log probabilities for each observation\/mean\/deviation triple.\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location parameter(s)\n * for the normal distribution.\n * @param sigma (Sequence of) scale parameters for the normal\n * distribution.\n * @return The log of the product of the densities.\n * @throw std::domain_error if the scale is not positive.\n * @tparam T_y Underlying type of scalar in sequence.\n * @tparam T_loc Type of location parameter.\n *\/\n template <bool propto,\n typename T_y, typename T_s, typename T_n, typename T_loc,\n typename T_scale>\n typename return_type<T_y, T_s, T_loc, T_scale>::type\n normal_sufficient_log(const T_y& y_bar, const T_s& s_squared,\n const T_n& n_obs, const T_loc& mu,\n const T_scale& sigma) {\n static const char* function = \"stan::math::normal_log(%1%)\";\n typedef typename\n stan::partials_return_type<T_y, T_s, T_n, T_loc, T_scale>::type\n T_partials_return;\n\n using std::log;\n using stan::is_constant_struct;\n using stan::math::check_positive;\n using stan::math::check_finite;\n using stan::math::check_not_nan;\n using stan::math::check_consistent_sizes;\n using stan::math::value_of;\n using stan::math::include_summand;\n\n \/\/ check if any vectors are zero length\n if (!(stan::length(y_bar)\n && stan::length(s_squared)\n && stan::length(n_obs)\n && stan::length(mu)\n && stan::length(sigma)))\n return 0.0;\n\n \/\/ set up return value accumulator\n T_partials_return logp(0.0);\n\n \/\/ validate args (here done over var, which should be OK)\n check_not_nan(function,\n \"Location parameter sufficient statistic\", y_bar);\n check_not_nan(function,\n \"Scale parameter sufficient statistic\", s_squared);\n check_not_nan(function,\n \"Number of observations\", n_obs);\n check_finite(function,\n \"Number of observations\", n_obs);\n check_positive(function,\n \"Number of observations\", n_obs);\n check_finite(function,\n \"Location parameter\", mu);\n check_positive(function, \"Scale parameter\", sigma);\n check_consistent_sizes(function,\n \"Location parameter sufficient statistic\",\n y_bar,\n \"Scale parameter sufficient statistic\",\n s_squared,\n \"Number of observations\", n_obs,\n \"Location parameter\", mu,\n \"Scale parameter\", sigma);\n \/\/ check if no variables are involved and prop-to\n if (!include_summand<propto, T_y, T_s, T_loc, T_scale>::value)\n return 0.0;\n\n \/\/ set up template expressions wrapping scalars into vector views\n OperandsAndPartials<T_y, T_s, T_loc, T_scale>\n operands_and_partials(y_bar, s_squared, mu, sigma);\n\n VectorView<const T_y> y_bar_vec(y_bar);\n VectorView<const T_s> s_squared_vec(s_squared);\n VectorView<const T_n> n_obs_vec(n_obs);\n VectorView<const T_loc> mu_vec(mu);\n VectorView<const T_scale> sigma_vec(sigma);\n size_t N = max_size(y_bar, s_squared, n_obs, mu, sigma);\n\n for (size_t i = 0; i < N; i++) {\n const T_partials_return y_bar_dbl = value_of(y_bar_vec[i]);\n const T_partials_return s_squared_dbl =\n value_of(s_squared_vec[i]);\n const T_partials_return n_obs_dbl = n_obs_vec[i];\n const T_partials_return mu_dbl = value_of(mu_vec[i]);\n const T_partials_return sigma_dbl = value_of(sigma_vec[i]);\n const T_partials_return sigma_squared = pow(sigma_dbl, 2);\n\n if (include_summand<propto>::value)\n logp += NEG_LOG_SQRT_TWO_PI * n_obs_dbl;\n\n if (include_summand<propto, T_scale>::value)\n logp -= n_obs_dbl*log(sigma_dbl);\n\n\n const T_partials_return cons_expr =\n (s_squared_dbl\n + n_obs_dbl * pow(y_bar_dbl - mu_dbl, 2));\n\n logp -= cons_expr \/ (2 * sigma_squared);\n\n\n \/\/ gradients\n if (!is_constant_struct<T_y>::value ||\n !is_constant_struct<T_loc>::value) {\n const T_partials_return common_derivative =\n n_obs_dbl * (mu_dbl - y_bar_dbl) \/ sigma_squared;\n if (!is_constant_struct<T_y>::value)\n operands_and_partials.d_x1[i] += common_derivative;\n if (!is_constant_struct<T_loc>::value)\n operands_and_partials.d_x3[i] -= common_derivative;\n }\n if (!is_constant_struct<T_s>::value)\n operands_and_partials.d_x2[i] -=\n 1 \/ (2 * sigma_squared);\n if (!is_constant_struct<T_scale>::value)\n operands_and_partials.d_x4[i]\n += cons_expr \/ pow(sigma_dbl, 3) - n_obs_dbl \/ sigma_dbl;\n }\n return\n operands_and_partials.to_var(logp, y_bar, s_squared, mu, sigma);\n }\n\n template <typename T_y, typename T_s, typename T_n,\n typename T_loc, typename T_scale>\n inline\n typename return_type<T_y, T_s, T_loc, T_scale>::type\n normal_sufficient_log(const T_y& y_bar, const T_s& s_squared,\n const T_n& n_obs, const T_loc& mu,\n const T_scale& sigma) {\n return\n normal_sufficient_log<false>(y_bar, s_squared, n_obs, mu, sigma);\n }\n\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include \"os\/os.h\"\n#include \"can_frame.h\"\n#include \"nmranet_config.h\"\n\n#include \"os\/TempFile.hxx\"\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/SimpleNodeInfoMockUserFile.hxx\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/ConfigRepresentation.hxx\"\n#include \"utils\/ConfigUpdateListener.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n\nextern const nmranet::NodeID NODE_ID;\n\nOVERRIDE_CONST(gc_generate_newlines, 1);\nOVERRIDE_CONST(main_thread_stack_size, 2500);\nOVERRIDE_CONST(num_memory_spaces, 4);\n\nnmranet::SimpleCanStack stack(NODE_ID);\n\nnmranet::MockSNIPUserFile snip_user_file(\n \"Default user name\", \"Default user description\");\nconst char *const nmranet::SNIP_DYNAMIC_FILENAME =\n nmranet::MockSNIPUserFile::snip_user_file_path;\n\nnamespace nmranet\n{\nBEGIN_GROUP(ConsumerConfig, base);\nEXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry);\nEXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry);\nEND_GROUP(ConsumerConfig, event_off);\n\nusing AllConsumers = RepeatedGroup<ConsumerConfig, 3>;\n\nBEGIN_GROUP(ProducerConfig, base);\nEXTEND_GROUP(ProducerConfig, base, debounce, Uint8ConfigEntry);\nEXTEND_GROUP(ProducerConfig, debounce, event_on, EventConfigEntry);\nEXTEND_GROUP(ProducerConfig, event_on, event_off, EventConfigEntry);\nEND_GROUP(ProducerConfig, event_off);\n\nusing AllProducers = RepeatedGroup<ProducerConfig, 2>;\n\nBEGIN_GROUP(ConfigDef, base);\nEXTEND_GROUP(ConfigDef, base, snip_data, EmptyGroup<128>);\nEXTEND_GROUP(ConfigDef, snip_data, consumers, AllConsumers);\nEXTEND_GROUP(ConfigDef, consumers, producers, AllProducers);\nEND_GROUP(ConfigDef, consumers);\n\nstatic_assert(ConfigDef::size() <= 256, \"Need to adjust eeprom size\");\n\ntypedef bool (*getter_fn_t)();\ntypedef void (*setter_fn_t)(bool);\n\nclass ConfiguredConsumer : public ConfigUpdateListener\n{\npublic:\n class Impl : public BitEventInterface\n {\n public:\n Impl(EventId event_on, EventId event_off, getter_fn_t getter,\n setter_fn_t setter)\n : BitEventInterface(event_on, event_off)\n , getter_(getter)\n , setter_(setter)\n {\n }\n\n bool GetCurrentState() OVERRIDE\n {\n return getter_();\n }\n void SetState(bool new_value) OVERRIDE\n {\n setter_(new_value);\n }\n Node *node() OVERRIDE\n {\n return stack.node();\n }\n\n public:\n const getter_fn_t getter_;\n const setter_fn_t setter_;\n };\n\n template <class HW>\n ConfiguredConsumer(const ConsumerConfig &cfg, const HW &)\n : impl_(0, 0, &HW::get, &HW::set)\n , consumer_(&impl_)\n , cfg_(cfg)\n {\n }\n\n UpdateAction apply_configuration(\n int fd, bool initial_load, BarrierNotifiable *done)\n {\n AutoNotify n(done);\n EventId cfg_event_on = cfg_.event_on().read(fd);\n EventId cfg_event_off = cfg_.event_off().read(fd);\n if (cfg_event_off != impl_.event_off() ||\n cfg_event_on != impl_.event_on())\n {\n auto saved_setter = impl_.setter_;\n auto saved_getter = impl_.getter_;\n \/\/ Need to reinitialize the consumer. We do this with in-place\n \/\/ destruction and construction.\n consumer_.~BitEventConsumer();\n impl_.~Impl();\n new (&impl_)\n Impl(cfg_event_on, cfg_event_off, saved_getter, saved_setter);\n new (&consumer_) BitEventConsumer(&impl_);\n return REINIT_NEEDED;\n }\n return UPDATED;\n }\n\n \/\/\/@TODO(balazs.racz): implement\n void factory_reset(int fd) OVERRIDE\n {\n }\n\nprivate:\n Impl impl_;\n BitEventConsumer consumer_;\n const ConsumerConfig cfg_;\n};\n\n} \/\/ namespace nmranet\n\nGPIO_PIN(LED_RED, LedPin, F, 1);\nGPIO_PIN(LED_GREEN, LedPin, F, 3);\nGPIO_PIN(LED_BLUE, LedPin, F, 2);\n\nGPIO_PIN(SW1, GpioInputPU, F, 4);\n\nnmranet::ConfigDef cfg(0);\n\nnmranet::ConfiguredConsumer consumer_red(\n cfg.consumers().entry<0>(), LED_RED_Pin());\nnmranet::ConfiguredConsumer consumer_green(\n cfg.consumers().entry<1>(), LED_GREEN_Pin());\nnmranet::ConfiguredConsumer consumer_blue(\n cfg.consumers().entry<2>(), LED_BLUE_Pin());\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n\n\/\/ Enable this to add sniffing through the usb or serial port.\n#if defined(SNIFF_ON_USB)\n stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n stack.loop_executor();\n return 0;\n}\n<commit_msg>Adds explanation comment.<commit_after>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include \"os\/os.h\"\n#include \"can_frame.h\"\n#include \"nmranet_config.h\"\n\n#include \"os\/TempFile.hxx\"\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/SimpleNodeInfoMockUserFile.hxx\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/ConfigRepresentation.hxx\"\n#include \"utils\/ConfigUpdateListener.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n\nextern const nmranet::NodeID NODE_ID;\n\nOVERRIDE_CONST(gc_generate_newlines, 1);\nOVERRIDE_CONST(main_thread_stack_size, 2500);\nOVERRIDE_CONST(num_memory_spaces, 4);\n\nnmranet::SimpleCanStack stack(NODE_ID);\n\nnmranet::MockSNIPUserFile snip_user_file(\n \"Default user name\", \"Default user description\");\nconst char *const nmranet::SNIP_DYNAMIC_FILENAME =\n nmranet::MockSNIPUserFile::snip_user_file_path;\n\nnamespace nmranet\n{\nBEGIN_GROUP(ConsumerConfig, base);\nEXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry);\nEXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry);\nEND_GROUP(ConsumerConfig, event_off);\n\nusing AllConsumers = RepeatedGroup<ConsumerConfig, 3>;\n\nBEGIN_GROUP(ProducerConfig, base);\nEXTEND_GROUP(ProducerConfig, base, debounce, Uint8ConfigEntry);\nEXTEND_GROUP(ProducerConfig, debounce, event_on, EventConfigEntry);\nEXTEND_GROUP(ProducerConfig, event_on, event_off, EventConfigEntry);\nEND_GROUP(ProducerConfig, event_off);\n\nusing AllProducers = RepeatedGroup<ProducerConfig, 2>;\n\nBEGIN_GROUP(ConfigDef, base);\nEXTEND_GROUP(ConfigDef, base, snip_data, EmptyGroup<128>);\nEXTEND_GROUP(ConfigDef, snip_data, consumers, AllConsumers);\nEXTEND_GROUP(ConfigDef, consumers, producers, AllProducers);\nEND_GROUP(ConfigDef, consumers);\n\nstatic_assert(ConfigDef::size() <= 256, \"Need to adjust eeprom size\");\n\ntypedef bool (*getter_fn_t)();\ntypedef void (*setter_fn_t)(bool);\n\nclass ConfiguredConsumer : public ConfigUpdateListener\n{\npublic:\n class Impl : public BitEventInterface\n {\n public:\n Impl(EventId event_on, EventId event_off, getter_fn_t getter,\n setter_fn_t setter)\n : BitEventInterface(event_on, event_off)\n , getter_(getter)\n , setter_(setter)\n {\n }\n\n bool GetCurrentState() OVERRIDE\n {\n return getter_();\n }\n void SetState(bool new_value) OVERRIDE\n {\n setter_(new_value);\n }\n Node *node() OVERRIDE\n {\n return stack.node();\n }\n\n public:\n const getter_fn_t getter_;\n const setter_fn_t setter_;\n };\n\n template <class HW>\n ConfiguredConsumer(const ConsumerConfig &cfg, const HW &)\n : impl_(0, 0, &HW::get, &HW::set)\n , consumer_(&impl_)\n , cfg_(cfg)\n {\n }\n\n UpdateAction apply_configuration(\n int fd, bool initial_load, BarrierNotifiable *done)\n {\n AutoNotify n(done);\n EventId cfg_event_on = cfg_.event_on().read(fd);\n EventId cfg_event_off = cfg_.event_off().read(fd);\n if (cfg_event_off != impl_.event_off() ||\n cfg_event_on != impl_.event_on())\n {\n auto saved_setter = impl_.setter_;\n auto saved_getter = impl_.getter_;\n \/\/ Need to reinitialize the consumer. We do this with in-place\n \/\/ destruction and construction.\n consumer_.~BitEventConsumer();\n impl_.~Impl();\n new (&impl_)\n Impl(cfg_event_on, cfg_event_off, saved_getter, saved_setter);\n new (&consumer_) BitEventConsumer(&impl_);\n return REINIT_NEEDED; \/\/ Causes events identify.\n }\n return UPDATED;\n }\n\n \/\/\/@TODO(balazs.racz): implement\n void factory_reset(int fd) OVERRIDE\n {\n }\n\nprivate:\n Impl impl_;\n BitEventConsumer consumer_;\n const ConsumerConfig cfg_;\n};\n\n} \/\/ namespace nmranet\n\nGPIO_PIN(LED_RED, LedPin, F, 1);\nGPIO_PIN(LED_GREEN, LedPin, F, 3);\nGPIO_PIN(LED_BLUE, LedPin, F, 2);\n\nGPIO_PIN(SW1, GpioInputPU, F, 4);\n\nnmranet::ConfigDef cfg(0);\n\nnmranet::ConfiguredConsumer consumer_red(\n cfg.consumers().entry<0>(), LED_RED_Pin());\nnmranet::ConfiguredConsumer consumer_green(\n cfg.consumers().entry<1>(), LED_GREEN_Pin());\nnmranet::ConfiguredConsumer consumer_blue(\n cfg.consumers().entry<2>(), LED_BLUE_Pin());\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n\n\/\/ Enable this to add sniffing through the usb or serial port.\n#if defined(SNIFF_ON_USB)\n stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n stack.loop_executor();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names\n** of its contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"glwidget.h\"\n#include <QOpenGLShaderProgram>\n#include <QOpenGLTexture>\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDir>\n#include <QPainter>\n#include <QFileInfo>\n#include <QFileInfoList>\n#include <QOpenGLPaintDevice>\n#include <QOpenGLFramebufferObject>\n\nGLWidget::GLWidget(QWidget *parent)\n : QOpenGLWidget(parent),\n clearColor(Qt::black),\n program(0),\n currentTexture(0),\n currentFrame(0),\n numberOfFrames(0),\n currentFps(0),\n avgFrames(0),\n mFpsTimePerFrame(0)\n{\n connect(&mTimer, &QTimer::timeout, this, &GLWidget::updateFps);\n mTimer.start(1000);\n}\n\nGLWidget::~GLWidget()\n{\n makeCurrent();\n vbo.destroy();\n foreach(QOpenGLTexture *texture, textures)\n delete texture;\n delete program;\n doneCurrent();\n}\n\nQSize GLWidget::minimumSizeHint() const\n{\n return QSize(50, 50);\n}\n\nvoid GLWidget::setClearColor(const QColor &color)\n{\n clearColor = color;\n update();\n}\n\nvoid GLWidget::setFpsLimit(int limit)\n{\n mFpsTimePerFrame = 1000.0 \/ (limit * 1.0);\n}\n\nvoid GLWidget::initializeGL()\n{\n initializeOpenGLFunctions();\n\n makeObject();\n\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n\n#define PROGRAM_VERTEX_ATTRIBUTE 0\n#define PROGRAM_TEXCOORD_ATTRIBUTE 1\n\n QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);\n const char *vsrc =\n \"attribute highp vec4 vertex;\\n\"\n \"attribute mediump vec4 texCoord;\\n\"\n \"varying mediump vec4 texc;\\n\"\n \"uniform mediump mat4 matrix;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" gl_Position = matrix * vertex;\\n\"\n \" texc = texCoord;\\n\"\n \" gl_Position = matrix * vertex;\\n\"\n \" texc = texCoord * vec4(1.0, -1.0, 1.0, 1.0);\\n\"\n\n\n\n \"}\\n\";\n vshader->compileSourceCode(vsrc);\n\n QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);\n const char *fsrc =\n \"uniform sampler2D texture;\\n\"\n \"varying mediump vec4 texc;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" gl_FragColor = texture2D(texture, texc.st);\\n\"\n \" if (gl_FragColor.a < 0.5)\\n\"\n \" discard;\\n\"\n \"}\\n\";\n fshader->compileSourceCode(fsrc);\n\n program = new QOpenGLShaderProgram;\n program->addShader(vshader);\n program->addShader(fshader);\n program->bindAttributeLocation(\"vertex\", PROGRAM_VERTEX_ATTRIBUTE);\n program->bindAttributeLocation(\"texCoord\", PROGRAM_TEXCOORD_ATTRIBUTE);\n program->link();\n\n program->bind();\n program->setUniformValue(\"texture\", 0);\n}\n\nvoid GLWidget::paintGL()\n{\n glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n paintText();\n\n QMatrix4x4 m;\n m.ortho(-1.0f, +1.0f, +1.0f, -1.0f, 1.0f, -1.0f);\n\n program->setUniformValue(\"matrix\", m);\n program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);\n program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);\n program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,\n 3, 5 * sizeof(GLfloat));\n program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,\n 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));\n\n if (textures.size()) {\n textures[currentTexture]->bind();\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n currentTexture++;\n currentTexture %= textures.size();\n }\n\n currentFrame++;\n\n QTimer::singleShot(mFpsTimePerFrame, this, SLOT(update()));\n}\nvoid GLWidget::resizeGL(int width, int height)\n{\n qDebug() << width << \"x\" << height;\n glViewport(0, 0, width, height);\n}\n\nvoid GLWidget::paintText()\n{\n QString fpsOverlay = QString(\"FPS: %1\").arg(currentFps);\n QString avgOverlay = QString(\"AVG: %1\").arg(avgFrames);\n\n const QRect drawRect(0, 0, 150, 50);\n const QSize drawRectSize = drawRect.size();\n\n QImage img(drawRectSize, QImage::Format_ARGB32);\n img.fill(Qt::transparent);\n QPainter painter;\n\n painter.begin(&img);\n painter.setBackgroundMode(Qt::TransparentMode);\n\n painter.setBackground(Qt::transparent);\n QFont font = painter.font();\n font.setPointSize(24);\n font.setPointSize(16);\n painter.setFont(font);\n painter.setPen(Qt::green);\n painter.setBrush(QBrush());\n\n QFontMetrics fMetrics = painter.fontMetrics();\n QSize fpsMetrics = fMetrics.size( Qt::TextSingleLine, fpsOverlay );\n QRectF fpsRect( QPoint(0, 0), fpsMetrics );\n QSize avgMetrics = fMetrics.size( Qt::TextSingleLine, avgOverlay );\n QRectF avgRect( QPoint(0, fpsRect.height()), avgMetrics );\n painter.drawText(fpsRect, Qt::TextSingleLine, fpsOverlay);\n painter.drawText(avgRect, Qt::TextSingleLine, avgOverlay);\n\n painter.end();\n\n QOpenGLTexture texture(img);\n texture.bind();\n\n QMatrix4x4 m;\n m.ortho(-12.0f, +12.0f, +12.0f, -12.0f, 1.0f, -1.0f);\n\n program->setUniformValue(\"matrix\", m);\n program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);\n program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);\n program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,\n 3, 5 * sizeof(GLfloat));\n program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,\n 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));\n\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n}\n\nvoid GLWidget::updateFps()\n{\n currentFps = currentFrame;\n currentFrame = 0;\n\n avgFrames = (currentFps + numberOfFrames * avgFrames) \/ (numberOfFrames + 1);\n numberOfFrames++;\n\n qDebug() << \"FPS: \" << currentFps << \", AVG: \" << avgFrames;\n}\n\nvoid GLWidget::makeObject()\n{\n static const int coords[4][3] = {\n { +1, -1, -1 },\n { -1, -1, -1 },\n { -1, +1, -1 },\n { +1, +1, -1 }\n };\n\n QString path = QApplication::applicationDirPath();\n\n QDir dir(path, \"*.png\", QDir::IgnoreCase, QDir::Files);\n QFileInfoList files = dir.entryInfoList();\n\n foreach(QFileInfo file, files) {\n QImage img;\n if (img.load(file.absoluteFilePath())) {\n textures.append(new QOpenGLTexture(img));\n }\n }\n\n QVector<GLfloat> vertData;\n for (int j = 0; j < 4; ++j) {\n \/\/ vertex position\n vertData.append(coords[j][0]);\n vertData.append(coords[j][1]);\n vertData.append(coords[j][2]);\n \/\/ texture coordinate\n vertData.append(j == 0 || j == 3);\n vertData.append(j == 0 || j == 1);\n }\n\n vbo.create();\n vbo.bind();\n vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));\n}\n\n<commit_msg>Allowing to deactivate FPS limiter now.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names\n** of its contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"glwidget.h\"\n#include <QOpenGLShaderProgram>\n#include <QOpenGLTexture>\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDir>\n#include <QPainter>\n#include <QFileInfo>\n#include <QFileInfoList>\n#include <QOpenGLPaintDevice>\n#include <QOpenGLFramebufferObject>\n\nGLWidget::GLWidget(QWidget *parent)\n : QOpenGLWidget(parent),\n clearColor(Qt::black),\n program(0),\n currentTexture(0),\n currentFrame(0),\n numberOfFrames(0),\n currentFps(0),\n avgFrames(0),\n mFpsTimePerFrame(0)\n{\n connect(&mTimer, &QTimer::timeout, this, &GLWidget::updateFps);\n mTimer.start(1000);\n}\n\nGLWidget::~GLWidget()\n{\n makeCurrent();\n vbo.destroy();\n foreach(QOpenGLTexture *texture, textures)\n delete texture;\n delete program;\n doneCurrent();\n}\n\nQSize GLWidget::minimumSizeHint() const\n{\n return QSize(50, 50);\n}\n\nvoid GLWidget::setClearColor(const QColor &color)\n{\n clearColor = color;\n update();\n}\n\nvoid GLWidget::setFpsLimit(int limit)\n{\n if (limit > 0)\n mFpsTimePerFrame = 1000.0 \/ (limit * 1.0);\n else\n mFpsTimePerFrame = 0.0;\n}\n\nvoid GLWidget::initializeGL()\n{\n initializeOpenGLFunctions();\n\n makeObject();\n\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n\n#define PROGRAM_VERTEX_ATTRIBUTE 0\n#define PROGRAM_TEXCOORD_ATTRIBUTE 1\n\n QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);\n const char *vsrc =\n \"attribute highp vec4 vertex;\\n\"\n \"attribute mediump vec4 texCoord;\\n\"\n \"varying mediump vec4 texc;\\n\"\n \"uniform mediump mat4 matrix;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" gl_Position = matrix * vertex;\\n\"\n \" texc = texCoord;\\n\"\n \" gl_Position = matrix * vertex;\\n\"\n \" texc = texCoord * vec4(1.0, -1.0, 1.0, 1.0);\\n\"\n\n\n\n \"}\\n\";\n vshader->compileSourceCode(vsrc);\n\n QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);\n const char *fsrc =\n \"uniform sampler2D texture;\\n\"\n \"varying mediump vec4 texc;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" gl_FragColor = texture2D(texture, texc.st);\\n\"\n \" if (gl_FragColor.a < 0.5)\\n\"\n \" discard;\\n\"\n \"}\\n\";\n fshader->compileSourceCode(fsrc);\n\n program = new QOpenGLShaderProgram;\n program->addShader(vshader);\n program->addShader(fshader);\n program->bindAttributeLocation(\"vertex\", PROGRAM_VERTEX_ATTRIBUTE);\n program->bindAttributeLocation(\"texCoord\", PROGRAM_TEXCOORD_ATTRIBUTE);\n program->link();\n\n program->bind();\n program->setUniformValue(\"texture\", 0);\n}\n\nvoid GLWidget::paintGL()\n{\n glClearColor(clearColor.redF(), clearColor.greenF(), clearColor.blueF(), clearColor.alphaF());\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n paintText();\n\n QMatrix4x4 m;\n m.ortho(-1.0f, +1.0f, +1.0f, -1.0f, 1.0f, -1.0f);\n\n program->setUniformValue(\"matrix\", m);\n program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);\n program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);\n program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,\n 3, 5 * sizeof(GLfloat));\n program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,\n 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));\n\n if (textures.size()) {\n textures[currentTexture]->bind();\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n currentTexture++;\n currentTexture %= textures.size();\n }\n\n currentFrame++;\n\n QTimer::singleShot(mFpsTimePerFrame, this, SLOT(update()));\n}\nvoid GLWidget::resizeGL(int width, int height)\n{\n qDebug() << width << \"x\" << height;\n glViewport(0, 0, width, height);\n}\n\nvoid GLWidget::paintText()\n{\n QString fpsOverlay = QString(\"FPS: %1\").arg(currentFps);\n QString avgOverlay = QString(\"AVG: %1\").arg(avgFrames);\n\n const QRect drawRect(0, 0, 150, 50);\n const QSize drawRectSize = drawRect.size();\n\n QImage img(drawRectSize, QImage::Format_ARGB32);\n img.fill(Qt::transparent);\n QPainter painter;\n\n painter.begin(&img);\n painter.setBackgroundMode(Qt::TransparentMode);\n\n painter.setBackground(Qt::transparent);\n QFont font = painter.font();\n font.setPointSize(24);\n font.setPointSize(16);\n painter.setFont(font);\n painter.setPen(Qt::green);\n painter.setBrush(QBrush());\n\n QFontMetrics fMetrics = painter.fontMetrics();\n QSize fpsMetrics = fMetrics.size( Qt::TextSingleLine, fpsOverlay );\n QRectF fpsRect( QPoint(0, 0), fpsMetrics );\n QSize avgMetrics = fMetrics.size( Qt::TextSingleLine, avgOverlay );\n QRectF avgRect( QPoint(0, fpsRect.height()), avgMetrics );\n painter.drawText(fpsRect, Qt::TextSingleLine, fpsOverlay);\n painter.drawText(avgRect, Qt::TextSingleLine, avgOverlay);\n\n painter.end();\n\n QOpenGLTexture texture(img);\n texture.bind();\n\n QMatrix4x4 m;\n m.ortho(-12.0f, +12.0f, +12.0f, -12.0f, 1.0f, -1.0f);\n\n program->setUniformValue(\"matrix\", m);\n program->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);\n program->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);\n program->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0,\n 3, 5 * sizeof(GLfloat));\n program->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT,\n 3 * sizeof(GLfloat), 2, 5 * sizeof(GLfloat));\n\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n}\n\nvoid GLWidget::updateFps()\n{\n currentFps = currentFrame;\n currentFrame = 0;\n\n avgFrames = (currentFps + numberOfFrames * avgFrames) \/ (numberOfFrames + 1);\n numberOfFrames++;\n\n qDebug() << \"FPS: \" << currentFps << \", AVG: \" << avgFrames;\n}\n\nvoid GLWidget::makeObject()\n{\n static const int coords[4][3] = {\n { +1, -1, -1 },\n { -1, -1, -1 },\n { -1, +1, -1 },\n { +1, +1, -1 }\n };\n\n QString path = QApplication::applicationDirPath();\n\n QDir dir(path, \"*.png\", QDir::IgnoreCase, QDir::Files);\n QFileInfoList files = dir.entryInfoList();\n\n foreach(QFileInfo file, files) {\n QImage img;\n if (img.load(file.absoluteFilePath())) {\n textures.append(new QOpenGLTexture(img));\n }\n }\n\n QVector<GLfloat> vertData;\n for (int j = 0; j < 4; ++j) {\n \/\/ vertex position\n vertData.append(coords[j][0]);\n vertData.append(coords[j][1]);\n vertData.append(coords[j][2]);\n \/\/ texture coordinate\n vertData.append(j == 0 || j == 3);\n vertData.append(j == 0 || j == 1);\n }\n\n vbo.create();\n vbo.bind();\n vbo.allocate(vertData.constData(), vertData.count() * sizeof(GLfloat));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/tree:$Name: $:$Id: TBranchRef.cxx,v 1.1 2004\/08\/20 14:54:53 brun Exp $\n\/\/ Author: Rene Brun 19\/08\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ A Branch for the case of an array of clone objects \/\/ \/\/\n\/\/ See TTree. \/\/ \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TBranchRef.h\"\n#include \"TTree.h\"\n#include \"TBasket.h\"\n#include \"TFile.h\"\n\nClassImp(TBranchRef)\n\n\/\/______________________________________________________________________________\nTBranchRef::TBranchRef(): TBranch()\n{\n\n fRefTable = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTBranchRef::TBranchRef(TTree *tree)\n :TBranch()\n{\n \/\/ main constructor called by TTree::BranchRef\n \n if (!tree) return;\n TDirectory *dir = tree->GetDirectory();\n if (!dir) return;\n TFile *file = dir->GetFile();\n if (!file) return;\n SetName(\"TRefTable\");\n SetTitle(\"List of branch numbers with referenced objects\");\n fRefTable = new TRefTable(100);\n file->SetRefTable(fRefTable);\n \n fCompress = 1;\n fBasketSize = 32000;\n fAddress = 0;\n fBasketBytes = new Int_t[fMaxBaskets];\n fBasketEntry = new Long64_t[fMaxBaskets];\n fBasketSeek = new Long64_t[fMaxBaskets];\n\n for (Int_t i=0;i<fMaxBaskets;i++) {\n fBasketBytes[i] = 0;\n fBasketEntry[i] = 0;\n fBasketSeek[i] = 0;\n }\n\n fTree = tree;\n fDirectory = fTree->GetDirectory();\n fFileName = \"\";\n\n \/\/ Create the first basket\n TBasket *basket = new TBasket(\"TRefTable\",fTree->GetName(),this);\n fBaskets.Add(basket);\n}\n\n\n\/\/______________________________________________________________________________\nTBranchRef::~TBranchRef()\n{\n delete fRefTable;\n GetFile()->SetRefTable(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Clear(Option_t *option)\n{\n \/\/ clear entries in the TRefTable\n \n fRefTable->Clear(option);\n}\n\n\/\/______________________________________________________________________________\nInt_t TBranchRef::Fill()\n{\n \/\/ fill the branch basket with the referenced objects parent numbers\n \n Int_t nbytes = TBranch::Fill();\n return nbytes;\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::FillLeaves(TBuffer &b)\n{\n \/\/ This function called by TBranch::Fill overloads TBranch::FillLeaves\n \n fRefTable->FillBuffer(b);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Print(Option_t *option) const\n{\n \/\/ Print the TRefTable branch\n\n TBranch::Print(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::ReadLeaves(TBuffer &b)\n{\n \/\/ This function called by TBranch::GetEntry overloads TBranch::ReadLeaves\n \n fRefTable->ReadBuffer(b);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Reset(Option_t *option)\n{\n \/\/ Existing buffers are deleted\n \/\/ Entries, max and min are reset\n \/\/ TRefTable is cleared\n\n TBranch::Reset(option);\n fRefTable->Clear();\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::SetParent(const TObject *object)\n{\n \/\/ this function is called by TBranchElement::Fill when filling\n \/\/ branches that may contain referenced objects\n \n fRefTable->SetParent(object);\n}\n<commit_msg>add protection in dtor against GetFile() returning 0.<commit_after>\/\/ @(#)root\/tree:$Name: $:$Id: TBranchRef.cxx,v 1.2 2004\/08\/20 21:24:49 brun Exp $\n\/\/ Author: Rene Brun 19\/08\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ A Branch for the case of an array of clone objects \/\/ \/\/\n\/\/ See TTree. \/\/ \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TBranchRef.h\"\n#include \"TTree.h\"\n#include \"TBasket.h\"\n#include \"TFile.h\"\n\nClassImp(TBranchRef)\n\n\/\/______________________________________________________________________________\nTBranchRef::TBranchRef(): TBranch()\n{\n\n fRefTable = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTBranchRef::TBranchRef(TTree *tree)\n :TBranch()\n{\n \/\/ main constructor called by TTree::BranchRef\n\n if (!tree) return;\n TDirectory *dir = tree->GetDirectory();\n if (!dir) return;\n TFile *file = dir->GetFile();\n if (!file) return;\n SetName(\"TRefTable\");\n SetTitle(\"List of branch numbers with referenced objects\");\n fRefTable = new TRefTable(100);\n file->SetRefTable(fRefTable);\n\n fCompress = 1;\n fBasketSize = 32000;\n fAddress = 0;\n fBasketBytes = new Int_t[fMaxBaskets];\n fBasketEntry = new Long64_t[fMaxBaskets];\n fBasketSeek = new Long64_t[fMaxBaskets];\n\n for (Int_t i=0;i<fMaxBaskets;i++) {\n fBasketBytes[i] = 0;\n fBasketEntry[i] = 0;\n fBasketSeek[i] = 0;\n }\n\n fTree = tree;\n fDirectory = fTree->GetDirectory();\n fFileName = \"\";\n\n \/\/ Create the first basket\n TBasket *basket = new TBasket(\"TRefTable\",fTree->GetName(),this);\n fBaskets.Add(basket);\n}\n\n\n\/\/______________________________________________________________________________\nTBranchRef::~TBranchRef()\n{\n delete fRefTable;\n TFile *f = GetFile();\n if (f) f->SetRefTable(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Clear(Option_t *option)\n{\n \/\/ clear entries in the TRefTable\n\n fRefTable->Clear(option);\n}\n\n\/\/______________________________________________________________________________\nInt_t TBranchRef::Fill()\n{\n \/\/ fill the branch basket with the referenced objects parent numbers\n\n Int_t nbytes = TBranch::Fill();\n return nbytes;\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::FillLeaves(TBuffer &b)\n{\n \/\/ This function called by TBranch::Fill overloads TBranch::FillLeaves\n\n fRefTable->FillBuffer(b);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Print(Option_t *option) const\n{\n \/\/ Print the TRefTable branch\n\n TBranch::Print(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::ReadLeaves(TBuffer &b)\n{\n \/\/ This function called by TBranch::GetEntry overloads TBranch::ReadLeaves\n\n fRefTable->ReadBuffer(b);\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::Reset(Option_t *option)\n{\n \/\/ Existing buffers are deleted\n \/\/ Entries, max and min are reset\n \/\/ TRefTable is cleared\n\n TBranch::Reset(option);\n fRefTable->Clear();\n}\n\n\/\/______________________________________________________________________________\nvoid TBranchRef::SetParent(const TObject *object)\n{\n \/\/ this function is called by TBranchElement::Fill when filling\n \/\/ branches that may contain referenced objects\n\n fRefTable->SetParent(object);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"LRToComplex.h\"\n#include \"check_params.h\"\n#include \"lr_config.h\"\n\nnamespace edb\n{\n\nstd::string LRToComplex::Command() const\n{\n\treturn \"lr2complex\";\n}\n\nstd::string LRToComplex::Description() const\n{\n\treturn \"create complex file from lr file\";\n}\n\nstd::string LRToComplex::Usage() const\n{\n\t\/\/ lr2complex e:\/test2\/test_lr.json\n\tstd::string usage = Command() + \" [filepath]\";\n\treturn usage;\n}\n\nvoid LRToComplex::Run(int argc, char *argv[])\n{\n\tif (!check_number(this, argc, 3)) return;\n\tif (!check_file(argv[2])) return;\n\n\tRun(argv[2]);\n}\n\nvoid LRToComplex::Run(const std::string& filepath)\n{\n\tJson::Value lr_val;\n\tJson::Reader reader;\n\tstd::locale::global(std::locale(\"\"));\n\tstd::ifstream fin(filepath.c_str());\n\tstd::locale::global(std::locale(\"C\"));\n\treader.parse(fin, lr_val);\n\tfin.close();\n\n\tJson::Value complex_val;\n\/\/ \tfor (int i = 0; i < 3; ++i) {\n\/\/ \t\tLoadSpriteValue(lr_val[\"layer\"][i][\"sprite\"], complex_val[\"sprite\"]);\n\/\/ \t}\n\tint layer_idx = 0;\n\tLoadSpriteValue(lr_val[\"layer\"][layer_idx][\"sprite\"], complex_val[\"sprite\"]);\n\tstd::string name = d2d::FilenameTools::getFilename(filepath);\n\tname = \"scene_\" + name.substr(0, name.find_last_of('_'));\t\n\tcomplex_val[\"name\"] = name;\n\tcomplex_val[\"use_render_cache\"] = false;\n\tcomplex_val[\"xmax\"] = 0;\n\tcomplex_val[\"xmin\"] = 0;\n\tcomplex_val[\"ymax\"] = 0;\n\tcomplex_val[\"ymin\"] = 0;\n\n\tstd::string outfile = filepath.substr(0, filepath.find_last_of(\"_\"));\n\twxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);\n\toutfile = d2d::FilenameTools::getFilenameAddTag(outfile, tag, \"json\");\n\n\tJson::StyledStreamWriter writer;\n\tstd::locale::global(std::locale(\"\"));\n\tstd::ofstream fout(outfile.c_str());\n\tstd::locale::global(std::locale(\"C\"));\n\twriter.write(fout, complex_val);\n\tfout.close();\n}\n\nvoid LRToComplex::LoadSpriteValue(const Json::Value& src_val, Json::Value& dst_val)\n{\n\tint idx = 0;\n\tJson::Value spr_val = src_val[idx++];\n\twhile (!spr_val.isNull()) {\n\t\t\/\/ test character\n\t\tstd::string tag = spr_val[\"tag\"].asString();\n\t\tif (!tag.empty()) {\n\t\t\tspr_val = src_val[idx++];\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::string filepath = spr_val[\"filepath\"].asString();\n\t\tJson::Value spr_val_fix = spr_val;\n\n\t\tstd::string suffix = \"_shape.json\";\n\t\tint pos = filepath.find(suffix);\n\t\tif (pos!= std::string::npos) {\n\t\t\tstd::string fix_filepath = filepath.substr(0, pos) + \".png\";\n\t\t\tif (d2d::FilenameTools::isExist(fix_filepath)) {\n\t\t\t\tspr_val_fix[\"filepath\"] = fix_filepath;\n\t\t\t}\n\t\t}\n\n\t\tdst_val[dst_val.size()] = spr_val_fix;\n\n\t\tspr_val = src_val[idx++];\n\t}\n}\n\n}<commit_msg>[FIXED] lr打包加上装饰层<commit_after>#include \"LRToComplex.h\"\n#include \"check_params.h\"\n#include \"lr_config.h\"\n\nnamespace edb\n{\n\nstd::string LRToComplex::Command() const\n{\n\treturn \"lr2complex\";\n}\n\nstd::string LRToComplex::Description() const\n{\n\treturn \"create complex file from lr file\";\n}\n\nstd::string LRToComplex::Usage() const\n{\n\t\/\/ lr2complex e:\/test2\/test_lr.json\n\tstd::string usage = Command() + \" [filepath]\";\n\treturn usage;\n}\n\nvoid LRToComplex::Run(int argc, char *argv[])\n{\n\tif (!check_number(this, argc, 3)) return;\n\tif (!check_file(argv[2])) return;\n\n\tRun(argv[2]);\n}\n\nvoid LRToComplex::Run(const std::string& filepath)\n{\n\tJson::Value lr_val;\n\tJson::Reader reader;\n\tstd::locale::global(std::locale(\"\"));\n\tstd::ifstream fin(filepath.c_str());\n\tstd::locale::global(std::locale(\"C\"));\n\treader.parse(fin, lr_val);\n\tfin.close();\n\n\tJson::Value complex_val;\n\/\/ \tfor (int i = 0; i < 3; ++i) {\n\/\/ \t\tLoadSpriteValue(lr_val[\"layer\"][i][\"sprite\"], complex_val[\"sprite\"]);\n\/\/ \t}\n\tint layer_idx = 0;\n\tLoadSpriteValue(lr_val[\"layer\"][layer_idx][\"sprite\"], complex_val[\"sprite\"]);\n\tlayer_idx = 1;\n\tLoadSpriteValue(lr_val[\"layer\"][layer_idx][\"sprite\"], complex_val[\"sprite\"]);\n\tstd::string name = d2d::FilenameTools::getFilename(filepath);\n\tname = \"scene_\" + name.substr(0, name.find_last_of('_'));\t\n\tcomplex_val[\"name\"] = name;\n\tcomplex_val[\"use_render_cache\"] = false;\n\tcomplex_val[\"xmax\"] = 0;\n\tcomplex_val[\"xmin\"] = 0;\n\tcomplex_val[\"ymax\"] = 0;\n\tcomplex_val[\"ymin\"] = 0;\n\n\tstd::string outfile = filepath.substr(0, filepath.find_last_of(\"_\"));\n\twxString tag = d2d::FileNameParser::getFileTag(d2d::FileNameParser::e_complex);\n\toutfile = d2d::FilenameTools::getFilenameAddTag(outfile, tag, \"json\");\n\n\tJson::StyledStreamWriter writer;\n\tstd::locale::global(std::locale(\"\"));\n\tstd::ofstream fout(outfile.c_str());\n\tstd::locale::global(std::locale(\"C\"));\n\twriter.write(fout, complex_val);\n\tfout.close();\n}\n\nvoid LRToComplex::LoadSpriteValue(const Json::Value& src_val, Json::Value& dst_val)\n{\n\tint idx = 0;\n\tJson::Value spr_val = src_val[idx++];\n\twhile (!spr_val.isNull()) {\n\t\t\/\/ test character\n\t\tstd::string tag = spr_val[\"tag\"].asString();\n\t\tif (!tag.empty()) {\n\t\t\tspr_val = src_val[idx++];\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::string filepath = spr_val[\"filepath\"].asString();\n\n\t\tJson::Value spr_val_fix = spr_val;\n\n\t\tstd::string suffix = \"_shape.json\";\n\t\tint pos = filepath.find(suffix);\n\t\tif (pos!= std::string::npos) {\n\t\t\tstd::string fix_filepath = filepath.substr(0, pos) + \".png\";\n\t\t\tif (d2d::FilenameTools::isExist(fix_filepath)) {\n\t\t\t\tspr_val_fix[\"filepath\"] = fix_filepath;\n\t\t\t}\n\t\t}\n\n\t\tdst_val[dst_val.size()] = spr_val_fix;\n\n\t\tspr_val = src_val[idx++];\n\t}\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2022 The Chromium Authors.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"content_analysis\/sdk\/analysis_client.h\"\n\nusing content_analysis::sdk::Client;\nusing content_analysis::sdk::ContentAnalysisRequest;\nusing content_analysis::sdk::ContentAnalysisResponse;\nusing content_analysis::sdk::ContentAnalysisAcknowledgement;\n\n\/\/ Paramters used to build the request.\ncontent_analysis::sdk::AnalysisConnector connector =\n content_analysis::sdk::FILE_ATTACHED;\nstd::string request_token = \"req-12345\";\nstd::string tag = \"dlp\";\nstd::string digest = \"sha256-123456\";\nstd::string url = \"https:\/\/upload.example.com\";\nstd::vector<std::string> datas;\n\n\/\/ Command line parameters.\nconstexpr const char* kArgConnector = \"--connector=\";\nconstexpr const char* kArgRequestToken = \"--request-token=\";\nconstexpr const char* kArgTag = \"--tag=\";\nconstexpr const char* kArgDigest = \"--digest=\";\nconstexpr const char* kArgUrl = \"--url=\";\nconstexpr const char* kArgHelp = \"--help\";\n\nbool ParseCommandLine(int argc, char* argv[]) {\n for (int i = 1; i < argc; ++i) {\n const std::string arg = argv[i];\n if (arg.find(kArgConnector) == 0) {\n std::string connector_str = arg.substr(strlen(kArgConnector));\n if (connector_str == \"download\") {\n connector = content_analysis::sdk::FILE_DOWNLOADED;\n } else if (connector_str == \"attach\") {\n connector = content_analysis::sdk::FILE_ATTACHED;\n } else if (connector_str == \"bulk-data-entry\") {\n connector = content_analysis::sdk::BULK_DATA_ENTRY;\n } else if (connector_str == \"print\") {\n connector = content_analysis::sdk::PRINT;\n } else if (connector_str == \"file-transfer\") {\n connector = content_analysis::sdk::FILE_TRANSFER;\n } else {\n std::cout << \"[Demo] Incorrect command line arg: \" << arg << std::endl;\n return false;\n }\n } else if (arg.find(kArgRequestToken) == 0) {\n request_token = arg.substr(strlen(kArgRequestToken));\n } else if (arg.find(kArgTag) == 0) {\n tag = arg.substr(strlen(kArgTag));\n } else if (arg.find(kArgDigest) == 0) {\n digest = arg.substr(strlen(kArgDigest));\n } else if (arg.find(kArgUrl) == 0) {\n url = arg.substr(strlen(kArgUrl));\n } else if (arg.find(kArgHelp) == 0) {\n return false;\n } else {\n datas.push_back(arg);\n }\n }\n\n return true;\n}\n\nvoid PrintHelp() {\n std::cout\n << std::endl << std::endl\n << \"Usage: client [OPTIONS] [@]content_or_file ...\" << std::endl\n << \"A simple client to send content analysis requests to a running agent.\" << std::endl\n << \"Without @ the content to analyze is the argument itself.\" << std::endl\n << \"Otherwise the content is read from a file called 'content_or_file'.\" << std::endl\n << \"Multiple [@]content_or_file arguments may be specified, each generates one request.\" << std::endl\n << std::endl << \"Options:\" << std::endl\n << kArgConnector << \"<connector> : one of 'download', 'attach' (default), 'bulk-data-entry', 'print', or 'file-transfer'\" << std::endl\n << kArgRequestToken << \"<unique-token> : defaults to 'req-12345'\" << std::endl\n << kArgTag << \"<tag> : defaults to 'dlp'\" << std::endl\n << kArgUrl << \"<url> : defaults to 'https:\/\/upload.example.com'\" << std::endl\n << kArgDigest << \"<digest> : defaults to 'sha256-123456'\" << std::endl\n << kArgHelp << \" : prints this help message\" << std::endl;\n}\n\nContentAnalysisRequest BuildRequest(const std::string& data) {\n std::string filepath;\n std::string filename;\n if (data[0] == '@') {\n filepath = data.substr(1);\n filename = filepath.substr(filepath.find_last_of(\"\/\\\\\") + 1);\n }\n\n ContentAnalysisRequest request;\n\n request.set_analysis_connector(connector);\n request.set_request_token(request_token);\n *request.add_tags() = tag;\n\n auto request_data = request.mutable_request_data();\n request_data->set_url(url);\n request_data->set_digest(digest);\n if (!filename.empty()) {\n request_data->set_filename(filename);\n }\n\n if (!data.empty()) {\n request.set_text_content(data);\n } else if (!filepath.empty()) {\n request.set_file_path(filepath);\n } else {\n std::cout << \"[Demo] Specify text content or a file path.\" << std::endl;\n PrintHelp();\n return ContentAnalysisRequest();\n }\n\n return request;\n}\n\nvoid DumpResponse(int position, const ContentAnalysisResponse& response) {\n for (auto result : response.results()) {\n auto tag = result.has_tag() ? result.tag() : \"<no-tag>\";\n\n auto status = result.has_status()\n ? result.status()\n : ContentAnalysisResponse::Result::STATUS_UNKNOWN;\n std::string status_str;\n switch (status) {\n case ContentAnalysisResponse::Result::STATUS_UNKNOWN:\n status_str = \"Unknown\";\n break;\n case ContentAnalysisResponse::Result::SUCCESS:\n status_str = \"Success\";\n break;\n case ContentAnalysisResponse::Result::FAILURE:\n status_str = \"Failure\";\n break;\n default:\n status_str = \"<Uknown>\";\n break;\n }\n\n auto action =\n ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED;\n for (auto rule : result.triggered_rules()) {\n if (rule.has_action() && rule.action() > action)\n action = rule.action();\n }\n std::string action_str;\n switch (action) {\n case ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED:\n action_str = \"allowed\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::REPORT_ONLY:\n action_str = \"reported only\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::WARN:\n action_str = \"warned\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::BLOCK:\n action_str = \"blocked\";\n break;\n }\n\n std::cout << \"[Demo] Request \" << position << \" is \" << action_str\n << \" after \" << tag\n << \" analysis, status=\" << status_str << std::endl;\n }\n}\n\nContentAnalysisAcknowledgement BuildAcknowledgement(\n const std::string& request_token) {\n ContentAnalysisAcknowledgement ack;\n ack.set_request_token(request_token);\n ack.set_status(ContentAnalysisAcknowledgement::SUCCESS);\n return ack;\n}\n\nint HandleRequest(Client* client,\n int position,\n const ContentAnalysisRequest& request) {\n ContentAnalysisResponse response;\n int err = client->Send(request, &response);\n if (err != 0) {\n std::cout << \"[Demo] Error sending request \" << position << std::endl;\n return 1;\n } else if (response.results_size() == 0) {\n std::cout << \"[Demo] Response \" << position << \" is missing a result\"\n << std::endl;\n return 1;\n } else {\n DumpResponse(position, response);\n\n int err = client->Acknowledge(\n BuildAcknowledgement(request.request_token()));\n if (err != 0) {\n std::cout << \"[Demo] Error sending ack \" << position << std::endl;\n }\n\n return 1;\n }\n\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n if (!ParseCommandLine(argc, argv)) {\n PrintHelp();\n return 1;\n }\n\n \/\/ Each client uses a unique name to identify itself with Google Chrome.\n auto client = Client::Create({\"content_analysis_sdk\"});\n if (!client) {\n std::cout << \"[Demo] Error starting client\" << std::endl;\n return 1;\n };\n\n for (int i = 0; i < datas.size(); ++i) {\n HandleRequest(client.get(), i + 1, BuildRequest(datas[i]));\n }\n\n return 0;\n};\n<commit_msg>Fix filepath condition in demo client (#52)<commit_after>\/\/ Copyright 2022 The Chromium Authors.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"content_analysis\/sdk\/analysis_client.h\"\n\nusing content_analysis::sdk::Client;\nusing content_analysis::sdk::ContentAnalysisRequest;\nusing content_analysis::sdk::ContentAnalysisResponse;\nusing content_analysis::sdk::ContentAnalysisAcknowledgement;\n\n\/\/ Paramters used to build the request.\ncontent_analysis::sdk::AnalysisConnector connector =\n content_analysis::sdk::FILE_ATTACHED;\nstd::string request_token = \"req-12345\";\nstd::string tag = \"dlp\";\nstd::string digest = \"sha256-123456\";\nstd::string url = \"https:\/\/upload.example.com\";\nstd::vector<std::string> datas;\n\n\/\/ Command line parameters.\nconstexpr const char* kArgConnector = \"--connector=\";\nconstexpr const char* kArgRequestToken = \"--request-token=\";\nconstexpr const char* kArgTag = \"--tag=\";\nconstexpr const char* kArgDigest = \"--digest=\";\nconstexpr const char* kArgUrl = \"--url=\";\nconstexpr const char* kArgHelp = \"--help\";\n\nbool ParseCommandLine(int argc, char* argv[]) {\n for (int i = 1; i < argc; ++i) {\n const std::string arg = argv[i];\n if (arg.find(kArgConnector) == 0) {\n std::string connector_str = arg.substr(strlen(kArgConnector));\n if (connector_str == \"download\") {\n connector = content_analysis::sdk::FILE_DOWNLOADED;\n } else if (connector_str == \"attach\") {\n connector = content_analysis::sdk::FILE_ATTACHED;\n } else if (connector_str == \"bulk-data-entry\") {\n connector = content_analysis::sdk::BULK_DATA_ENTRY;\n } else if (connector_str == \"print\") {\n connector = content_analysis::sdk::PRINT;\n } else if (connector_str == \"file-transfer\") {\n connector = content_analysis::sdk::FILE_TRANSFER;\n } else {\n std::cout << \"[Demo] Incorrect command line arg: \" << arg << std::endl;\n return false;\n }\n } else if (arg.find(kArgRequestToken) == 0) {\n request_token = arg.substr(strlen(kArgRequestToken));\n } else if (arg.find(kArgTag) == 0) {\n tag = arg.substr(strlen(kArgTag));\n } else if (arg.find(kArgDigest) == 0) {\n digest = arg.substr(strlen(kArgDigest));\n } else if (arg.find(kArgUrl) == 0) {\n url = arg.substr(strlen(kArgUrl));\n } else if (arg.find(kArgHelp) == 0) {\n return false;\n } else {\n datas.push_back(arg);\n }\n }\n\n return true;\n}\n\nvoid PrintHelp() {\n std::cout\n << std::endl << std::endl\n << \"Usage: client [OPTIONS] [@]content_or_file ...\" << std::endl\n << \"A simple client to send content analysis requests to a running agent.\" << std::endl\n << \"Without @ the content to analyze is the argument itself.\" << std::endl\n << \"Otherwise the content is read from a file called 'content_or_file'.\" << std::endl\n << \"Multiple [@]content_or_file arguments may be specified, each generates one request.\" << std::endl\n << std::endl << \"Options:\" << std::endl\n << kArgConnector << \"<connector> : one of 'download', 'attach' (default), 'bulk-data-entry', 'print', or 'file-transfer'\" << std::endl\n << kArgRequestToken << \"<unique-token> : defaults to 'req-12345'\" << std::endl\n << kArgTag << \"<tag> : defaults to 'dlp'\" << std::endl\n << kArgUrl << \"<url> : defaults to 'https:\/\/upload.example.com'\" << std::endl\n << kArgDigest << \"<digest> : defaults to 'sha256-123456'\" << std::endl\n << kArgHelp << \" : prints this help message\" << std::endl;\n}\n\nContentAnalysisRequest BuildRequest(const std::string& data) {\n std::string filepath;\n std::string filename;\n if (data[0] == '@') {\n filepath = data.substr(1);\n filename = filepath.substr(filepath.find_last_of(\"\/\\\\\") + 1);\n }\n\n ContentAnalysisRequest request;\n\n request.set_analysis_connector(connector);\n request.set_request_token(request_token);\n *request.add_tags() = tag;\n\n auto request_data = request.mutable_request_data();\n request_data->set_url(url);\n request_data->set_digest(digest);\n if (!filename.empty()) {\n request_data->set_filename(filename);\n }\n\n if (!filepath.empty()) {\n request.set_file_path(filepath);\n } else if (!data.empty()) {\n request.set_text_content(data);\n } else {\n std::cout << \"[Demo] Specify text content or a file path.\" << std::endl;\n PrintHelp();\n return ContentAnalysisRequest();\n }\n\n return request;\n}\n\nvoid DumpResponse(int position, const ContentAnalysisResponse& response) {\n for (auto result : response.results()) {\n auto tag = result.has_tag() ? result.tag() : \"<no-tag>\";\n\n auto status = result.has_status()\n ? result.status()\n : ContentAnalysisResponse::Result::STATUS_UNKNOWN;\n std::string status_str;\n switch (status) {\n case ContentAnalysisResponse::Result::STATUS_UNKNOWN:\n status_str = \"Unknown\";\n break;\n case ContentAnalysisResponse::Result::SUCCESS:\n status_str = \"Success\";\n break;\n case ContentAnalysisResponse::Result::FAILURE:\n status_str = \"Failure\";\n break;\n default:\n status_str = \"<Uknown>\";\n break;\n }\n\n auto action =\n ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED;\n for (auto rule : result.triggered_rules()) {\n if (rule.has_action() && rule.action() > action)\n action = rule.action();\n }\n std::string action_str;\n switch (action) {\n case ContentAnalysisResponse::Result::TriggeredRule::ACTION_UNSPECIFIED:\n action_str = \"allowed\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::REPORT_ONLY:\n action_str = \"reported only\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::WARN:\n action_str = \"warned\";\n break;\n case ContentAnalysisResponse::Result::TriggeredRule::BLOCK:\n action_str = \"blocked\";\n break;\n }\n\n std::cout << \"[Demo] Request \" << position << \" is \" << action_str\n << \" after \" << tag\n << \" analysis, status=\" << status_str << std::endl;\n }\n}\n\nContentAnalysisAcknowledgement BuildAcknowledgement(\n const std::string& request_token) {\n ContentAnalysisAcknowledgement ack;\n ack.set_request_token(request_token);\n ack.set_status(ContentAnalysisAcknowledgement::SUCCESS);\n return ack;\n}\n\nint HandleRequest(Client* client,\n int position,\n const ContentAnalysisRequest& request) {\n ContentAnalysisResponse response;\n int err = client->Send(request, &response);\n if (err != 0) {\n std::cout << \"[Demo] Error sending request \" << position << std::endl;\n return 1;\n } else if (response.results_size() == 0) {\n std::cout << \"[Demo] Response \" << position << \" is missing a result\"\n << std::endl;\n return 1;\n } else {\n DumpResponse(position, response);\n\n int err = client->Acknowledge(\n BuildAcknowledgement(request.request_token()));\n if (err != 0) {\n std::cout << \"[Demo] Error sending ack \" << position << std::endl;\n }\n\n return 1;\n }\n\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n if (!ParseCommandLine(argc, argv)) {\n PrintHelp();\n return 1;\n }\n\n \/\/ Each client uses a unique name to identify itself with Google Chrome.\n auto client = Client::Create({\"content_analysis_sdk\"});\n if (!client) {\n std::cout << \"[Demo] Error starting client\" << std::endl;\n return 1;\n };\n\n for (int i = 0; i < datas.size(); ++i) {\n HandleRequest(client.get(), i + 1, BuildRequest(datas[i]));\n }\n\n return 0;\n};\n<|endoftext|>"} {"text":"<commit_before>#include <cubez\/cubez.h>\n#include <cubez\/timer.h>\n\n#include \"ball.h\"\n#include \"physics.h\"\n#include \"player.h\"\n#include \"log.h\"\n#include \"mesh.h\"\n#include \"mesh_builder.h\"\n#include \"input.h\"\n#include \"render.h\"\n#include \"shader.h\"\n#include \"planet.h\"\n#include \"gui.h\"\n\n#include <algorithm>\n#include <thread>\n#include <unordered_map>\n\nconst char simple_vs[] = R\"(\n#version 200\n\nin vec3 inPos;\nin vec3 inCol;\n\nout vec3 vCol;\n\nvoid main() {\n vCol = inCol;\n gl_Position = vec4(inPos, 1.0);\n}\n)\";\n\nconst char simple_fs[] = R\"(\n#version 130\n\nin vec3 vCol;\nout vec4 frag_color;\n\nvoid main() {\n frag_color = vec4(vCol, 1.0);\n}\n)\";\n\n\nvoid check_for_gl_errors() {\n GLenum error = glGetError();\n if (error) {\n const GLubyte* error_str = gluErrorString(error);\n std::cout << \"Error(\" << error << \"): \" << error_str << std::endl;\n }\n}\n\nvoid initialize_universe(qbUniverse* uni) {\n qb_init(uni);\n\n {\n logging::initialize();\n }\n\n {\n physics::Settings settings;\n physics::initialize(settings);\n }\n \n {\n render::Settings s;\n s.title = \"Cubez example\";\n s.width = 1200;\n s.height = 800;\n s.znear = 0.1f;\n s.zfar = 10000.0f;\n s.fov = 70.0f;\n render::initialize(s);\n\n render::qb_camera_setyaw(90.0f);\n render::qb_camera_setpitch(0.0f);\n render::qb_camera_setposition({400.0f, -250.0f, 250.0f});\n\n check_for_gl_errors();\n }\n \n {\n input::initialize();\n }\n {\n \/*\n\n \/\/ Operations done in the global scene (QB_GLOBAL_SCENE) will persist until\n \/\/ the game ends. By default, all API calls are executed on the global\n \/\/ scene.\n qb_scene_activate(QB_GLOBAL_SCENE);\n qb_texture_load(...);\n qb_model_load(...);\n\n \/\/ Create two scenes: one for the main menu, and then another scene that\n \/\/ holds all the game objects.\n qbScene main_menu;\n qbScene game_prefetch;\n qb_scene_create(&main_menu);\n qb_scene_create(&game_prefetch);\n\n \/\/ Sets the scene to be active. While the scene is active, all API calls\n \/\/ will only affect the active scene. The game loop will only run over\n \/\/ the active scene.\n qb_scene_activate(main_menu);\n qb_component_create(...);\n qb_entity_create(...);\n qb_material_create(...);\n qb_event_send(...);\n \n\n \/\/ \"set\"ing a scene will not run the game loop over it. All API calls\n \/\/ performed will only be executed on the \"set\" scene. The game loop will\n \/\/ NOT run over the \"set\" scene.\n qb_with_scene(game_prefetch, [](){\n qb_scene_push(game_prefetch);\n qb_entity_create(...);\n qb_model_load(...);\n qb_scene_pop();\n });\n\n ...\n\n \/\/ Once the user clicks on the \"Start Game\" button, activate the game scene\n \/\/ and purge the old scene.\n qb_button_press(\"MainMenu\/StartGame\", []() {\n qb_scene_activate(game_prefetch);\n qb_scene_destroy(main_menu);\n });\n\n *\/\n }\n\n#if 1\n qbShader mesh_shader;\n qbTexture ball_texture;\n MeshBuilder block_mesh;\n qbMaterial ball_material;\n qbMaterial red_material;\n {\n \/\/ Load resources.\n std::cout << \"Loading resources.\\n\";\n qb_shader_load(&mesh_shader, \"mesh_shader\", \"resources\/mesh.vs\", \"resources\/mesh.fs\");\n qb_texture_load(&ball_texture, \"ball_texture\", \"resources\/soccer_ball.bmp\");\n block_mesh = MeshBuilder::FromFile(\"resources\/block.obj\");\n\n qbMaterialAttr attr;\n qb_materialattr_create(&attr);\n qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 1.0, 1.0 });\n qb_materialattr_addtexture(attr, ball_texture, {0, 0}, {0, 0});\n qb_materialattr_setshader(attr, mesh_shader);\n qb_material_create(&ball_material, attr);\n qb_materialattr_destroy(&attr);\n }\n {\n qbMaterialAttr attr;\n qb_materialattr_create(&attr);\n qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 0.0, 1.0 });\n qb_materialattr_setshader(attr, mesh_shader);\n qb_material_create(&red_material, attr);\n qb_materialattr_destroy(&attr);\n }\n\n {\n ball::Settings settings;\n settings.mesh = block_mesh.BuildRenderable(qbRenderMode::QB_TRIANGLES);\n settings.collision_mesh = new Mesh(block_mesh.BuildMesh());\n settings.material = ball_material;\n settings.material_exploded = red_material;\n\n ball::initialize(settings);\n check_for_gl_errors();\n }\n#if 0\n {\n qbEntityAttr attr;\n qb_entityattr_create(&attr);\n\n physics::Transform t{{400.0f, 300.0f, -32.0f}, {}, true};\n qb_entityattr_addcomponent(attr, physics::component(), &t);\n\n qbMesh mesh;\n qb_mesh_load(&mesh, \"floor_mesh\", \"C:\\\\Users\\\\Sam\\\\Source\\\\Repos\\\\cubez\\\\windows\\\\cubez\\\\x64\\\\Release\\\\floor.obj\");\n render::create(mesh, ball_material);\n\n qbEntity unused;\n qb_entity_create(&unused, attr);\n\n qb_entityattr_destroy(&attr);\n }\n#endif\n {\n player::Settings settings;\n settings.start_pos = {0, 0, 0};\n\n player::initialize(settings);\n check_for_gl_errors();\n }\n auto new_game = [mesh_shader](const framework::JSObject&, const framework::JSArgs&) {\n planet::Settings settings;\n settings.shader = mesh_shader;\n settings.resource_folder = \"resources\/\";\n planet::Initialize(settings);\n\n return framework::JSValue();\n };\n\n {\n glm::vec2 menu_size(200, 500);\n glm::vec2 menu_pos(\n (render::window_width() \/ 2) - (menu_size.x \/ 2),\n (render::window_height() \/ 2) - (menu_size.y \/ 2)\n );\n\n gui::JSCallbackMap callbacks;\n callbacks[\"NewGame\"] = new_game;\n\n gui::FromHtml(R\"(\n<html>\n<body style='all:initial'>\n<div style='width:100%;background-color:grey;text-align:center;vertical-align: middle;' onclick='NewGame()'> New Game <\/div>\n<div style='width:100%;'> Load Game <\/div>\n<div style='width:100%;'> Exit <\/div>\n<\/body>\n<\/html>\n )\", menu_pos, menu_size, callbacks);\n }\n\n#endif\n}\n\nint main(int, char* []) {\n \/\/ Create and initialize the game engine.\n qbUniverse uni;\n initialize_universe(&uni);\n\n qb_start();\n int frame = 0;\n WindowTimer fps_timer(50);\n WindowTimer update_timer(50);\n WindowTimer render_timer(50);\n\n double t = 0.0;\n const double dt = 0.01;\n double current_time = Timer::now() * 0.000000001;\n double start_time = Timer::now();\n double accumulator = 0.0;\n\n qb_loop();\n while (1) {\n fps_timer.start();\n\n double new_time = Timer::now() * 0.000000001;\n double frame_time = new_time - current_time;\n frame_time = std::min(0.25, frame_time);\n current_time = new_time;\n\n accumulator += frame_time;\n \n input::handle_input([](SDL_Event*) {\n render::shutdown();\n SDL_Quit();\n qb_stop();\n exit(0);\n });\n while (accumulator >= dt) {\n update_timer.start();\n qb_loop();\n update_timer.stop();\n update_timer.step();\n\n accumulator -= dt;\n t += dt;\n }\n\n render_timer.start();\n\n render::RenderEvent e;\n e.frame = frame;\n e.ftimestamp_us = Timer::now() - start_time;\n e.alpha = accumulator \/ dt;\n render::present(&e);\n \n render_timer.stop();\n render_timer.step();\n\n ++frame;\n fps_timer.stop();\n fps_timer.step();\n\n double time = Timer::now();\n\n static int prev_trigger = 0;\n static int trigger = 0;\n int period = 1;\n\n prev_trigger = trigger;\n trigger = int64_t(time - start_time) \/ 1000000000;\n if (rand() % 1000000000 == 0) {\n ball::create({(float)(rand() % 500) - 250.0f,\n (float)(rand() % 500) - 250.0f,\n (float)(rand() % 500) - 250.0f}, {}, true, true);\n }\n \n\n if (trigger % period == 0 && prev_trigger != trigger) {\n if ((int)(1e9 \/ update_timer.get_avg_elapsed_ns()) < 60) {\n std::cout << \"BAD FPS\\n\";\n }\n \/\/if (true && period && prev_trigger == prev_trigger && trigger == trigger) {\n std::cout << \"Ball count \" << qb_component_getcount(ball::Component()) << std::endl;\n double total = (1\/60.0) * 1e9;\n \/\/logging::out(\n std::cout <<\n \"Frame \" + std::to_string(frame) + \"\\n\" +\n + \"Utili: \" + std::to_string(100.0 * render_timer.get_avg_elapsed_ns() \/ total)\n + \" : \" + std::to_string(100.0 * update_timer.get_avg_elapsed_ns() \/ total) + \"\\n\"\n + \"Render FPS: \" + std::to_string((int)(1e9 \/ render_timer.get_avg_elapsed_ns())) + \"\\n\"\n + \"Update FPS: \" + std::to_string((int)(1e9 \/ update_timer.get_avg_elapsed_ns())) + \"\\n\"\n + \"Total FPS: \" + std::to_string(1e9 \/ fps_timer.get_elapsed_ns()) + \"\\n\"\n + \"Accum: \" + std::to_string(accumulator) + \"\\n\"\n + \"Alpha: \" + std::to_string(accumulator \/ dt) + \"\\n\";\n }\n }\n}\n<commit_msg>Test GUI<commit_after>#include <cubez\/cubez.h>\n#include <cubez\/timer.h>\n\n#include \"ball.h\"\n#include \"physics.h\"\n#include \"player.h\"\n#include \"log.h\"\n#include \"mesh.h\"\n#include \"mesh_builder.h\"\n#include \"input.h\"\n#include \"render.h\"\n#include \"shader.h\"\n#include \"planet.h\"\n#include \"gui.h\"\n\n#include <algorithm>\n#include <thread>\n#include <unordered_map>\n\nconst char simple_vs[] = R\"(\n#version 200\n\nin vec3 inPos;\nin vec3 inCol;\n\nout vec3 vCol;\n\nvoid main() {\n vCol = inCol;\n gl_Position = vec4(inPos, 1.0);\n}\n)\";\n\nconst char simple_fs[] = R\"(\n#version 130\n\nin vec3 vCol;\nout vec4 frag_color;\n\nvoid main() {\n frag_color = vec4(vCol, 1.0);\n}\n)\";\n\n\nvoid check_for_gl_errors() {\n GLenum error = glGetError();\n if (error) {\n const GLubyte* error_str = gluErrorString(error);\n std::cout << \"Error(\" << error << \"): \" << error_str << std::endl;\n }\n}\n\nvoid initialize_universe(qbUniverse* uni) {\n qb_init(uni);\n\n {\n logging::initialize();\n }\n\n {\n physics::Settings settings;\n physics::initialize(settings);\n }\n \n {\n render::Settings s;\n s.title = \"Cubez example\";\n s.width = 1200;\n s.height = 800;\n s.znear = 0.1f;\n s.zfar = 10000.0f;\n s.fov = 70.0f;\n render::initialize(s);\n\n render::qb_camera_setyaw(90.0f);\n render::qb_camera_setpitch(0.0f);\n render::qb_camera_setposition({400.0f, -250.0f, 250.0f});\n\n check_for_gl_errors();\n }\n \n {\n input::initialize();\n }\n {\n \/*\n\n \/\/ Operations done in the global scene (QB_GLOBAL_SCENE) will persist until\n \/\/ the game ends. By default, all API calls are executed on the global\n \/\/ scene.\n qb_scene_activate(QB_GLOBAL_SCENE);\n qb_texture_load(...);\n qb_model_load(...);\n\n \/\/ Create two scenes: one for the main menu, and then another scene that\n \/\/ holds all the game objects.\n qbScene main_menu;\n qbScene game_prefetch;\n qb_scene_create(&main_menu);\n qb_scene_create(&game_prefetch);\n\n \/\/ Sets the scene to be active. While the scene is active, all API calls\n \/\/ will only affect the active scene. The game loop will only run over\n \/\/ the active scene.\n qb_scene_activate(main_menu);\n qb_component_create(...);\n qb_entity_create(...);\n qb_material_create(...);\n qb_event_send(...);\n \n\n \/\/ \"set\"ing a scene will not run the game loop over it. All API calls\n \/\/ performed will only be executed on the \"set\" scene. The game loop will\n \/\/ NOT run over the \"set\" scene.\n qb_with_scene(game_prefetch, [](){\n qb_scene_push(game_prefetch);\n qb_entity_create(...);\n qb_model_load(...);\n qb_scene_pop();\n });\n\n ...\n\n \/\/ Once the user clicks on the \"Start Game\" button, activate the game scene\n \/\/ and purge the old scene.\n qb_button_press(\"MainMenu\/StartGame\", []() {\n qb_scene_activate(game_prefetch);\n qb_scene_destroy(main_menu);\n });\n\n *\/\n }\n\n#if 1\n qbShader mesh_shader;\n qbTexture ball_texture;\n MeshBuilder block_mesh;\n qbMaterial ball_material;\n qbMaterial red_material;\n {\n \/\/ Load resources.\n std::cout << \"Loading resources.\\n\";\n qb_shader_load(&mesh_shader, \"mesh_shader\", \"resources\/mesh.vs\", \"resources\/mesh.fs\");\n qb_texture_load(&ball_texture, \"ball_texture\", \"resources\/soccer_ball.bmp\");\n block_mesh = MeshBuilder::FromFile(\"resources\/block.obj\");\n\n qbMaterialAttr attr;\n qb_materialattr_create(&attr);\n qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 1.0, 1.0 });\n qb_materialattr_addtexture(attr, ball_texture, {0, 0}, {0, 0});\n qb_materialattr_setshader(attr, mesh_shader);\n qb_material_create(&ball_material, attr);\n qb_materialattr_destroy(&attr);\n }\n {\n qbMaterialAttr attr;\n qb_materialattr_create(&attr);\n qb_materialattr_setcolor(attr, glm::vec4{ 1.0, 0.0, 0.0, 1.0 });\n qb_materialattr_setshader(attr, mesh_shader);\n qb_material_create(&red_material, attr);\n qb_materialattr_destroy(&attr);\n }\n\n {\n ball::Settings settings;\n settings.mesh = block_mesh.BuildRenderable(qbRenderMode::QB_TRIANGLES);\n settings.collision_mesh = new Mesh(block_mesh.BuildMesh());\n settings.material = ball_material;\n settings.material_exploded = red_material;\n\n ball::initialize(settings);\n check_for_gl_errors();\n }\n#if 0\n {\n qbEntityAttr attr;\n qb_entityattr_create(&attr);\n\n physics::Transform t{{400.0f, 300.0f, -32.0f}, {}, true};\n qb_entityattr_addcomponent(attr, physics::component(), &t);\n\n qbMesh mesh;\n qb_mesh_load(&mesh, \"floor_mesh\", \"C:\\\\Users\\\\Sam\\\\Source\\\\Repos\\\\cubez\\\\windows\\\\cubez\\\\x64\\\\Release\\\\floor.obj\");\n render::create(mesh, ball_material);\n\n qbEntity unused;\n qb_entity_create(&unused, attr);\n\n qb_entityattr_destroy(&attr);\n }\n#endif\n {\n player::Settings settings;\n settings.start_pos = {0, 0, 0};\n\n player::initialize(settings);\n check_for_gl_errors();\n }\n\n \/*\n \n qbScene main_menu_scene;\n\n qb_scene_create(&main_menu_scene);\n qb_scene_push(main_menu_scene);\n\n \n\n qb_scene_pop();\n\n *\/\n\n auto new_game = [mesh_shader](const framework::JSObject&, const framework::JSArgs&) {\n planet::Settings settings;\n settings.shader = mesh_shader;\n settings.resource_folder = \"resources\/\";\n planet::Initialize(settings);\n\n return framework::JSValue();\n };\n {\n planet::Settings settings;\n settings.shader = mesh_shader;\n settings.resource_folder = \"resources\/\";\n planet::Initialize(settings);\n }\n {\n glm::vec2 menu_size(render::window_width(), render::window_height());\n glm::vec2 menu_pos(0, 0);\n\n gui::JSCallbackMap callbacks;\n callbacks[\"NewGame\"] = new_game;\n\n \/\/gui::FromFile(\"file:\/\/\/game.html\", menu_pos, menu_size, callbacks);\n }\n\n#endif\n}\n\nint main(int, char* []) {\n \/\/ Create and initialize the game engine.\n qbUniverse uni;\n initialize_universe(&uni);\n\n qb_start();\n int frame = 0;\n WindowTimer fps_timer(50);\n WindowTimer update_timer(50);\n WindowTimer render_timer(50);\n\n double t = 0.0;\n const double dt = 0.01;\n double current_time = Timer::now() * 0.000000001;\n double start_time = Timer::now();\n double accumulator = 0.0;\n gui::qbRenderTarget target;\n gui::qb_rendertarget_create(&target, { 250, 0 }, { 500, 500 });\n\n qb_loop();\n while (1) {\n fps_timer.start();\n\n double new_time = Timer::now() * 0.000000001;\n double frame_time = new_time - current_time;\n frame_time = std::min(0.25, frame_time);\n current_time = new_time;\n\n accumulator += frame_time;\n \n input::handle_input([](SDL_Event*) {\n render::shutdown();\n SDL_Quit();\n qb_stop();\n exit(0);\n });\n while (accumulator >= dt) {\n update_timer.start();\n qb_loop();\n update_timer.stop();\n update_timer.step();\n\n accumulator -= dt;\n t += dt;\n }\n\n render_timer.start();\n\n render::RenderEvent e;\n e.frame = frame;\n e.ftimestamp_us = Timer::now() - start_time;\n e.alpha = accumulator \/ dt;\n render::present(&e);\n \n render_timer.stop();\n render_timer.step();\n\n ++frame;\n fps_timer.stop();\n fps_timer.step();\n\n double time = Timer::now();\n\n static int prev_trigger = 0;\n static int trigger = 0;\n int period = 1;\n\n prev_trigger = trigger;\n trigger = int64_t(time - start_time) \/ 1000000000;\n if (rand() % 1000000000 == 0) {\n ball::create({(float)(rand() % 500) - 250.0f,\n (float)(rand() % 500) - 250.0f,\n (float)(rand() % 500) - 250.0f}, {}, true, true);\n }\n \n\n if (trigger % period == 0 && prev_trigger != trigger) {\n if ((int)(1e9 \/ update_timer.get_avg_elapsed_ns()) < 60) {\n std::cout << \"BAD FPS\\n\";\n }\n \/\/if (true && period && prev_trigger == prev_trigger && trigger == trigger) {\n std::cout << \"Ball count \" << qb_component_getcount(ball::Component()) << std::endl;\n double total = (1\/60.0) * 1e9;\n \/\/logging::out(\n std::cout <<\n \"Frame \" + std::to_string(frame) + \"\\n\" +\n + \"Utili: \" + std::to_string(100.0 * render_timer.get_avg_elapsed_ns() \/ total)\n + \" : \" + std::to_string(100.0 * update_timer.get_avg_elapsed_ns() \/ total) + \"\\n\"\n + \"Render FPS: \" + std::to_string((int)(1e9 \/ render_timer.get_avg_elapsed_ns())) + \"\\n\"\n + \"Update FPS: \" + std::to_string((int)(1e9 \/ update_timer.get_avg_elapsed_ns())) + \"\\n\"\n + \"Total FPS: \" + std::to_string(1e9 \/ fps_timer.get_elapsed_ns()) + \"\\n\"\n + \"Accum: \" + std::to_string(accumulator) + \"\\n\"\n + \"Alpha: \" + std::to_string(accumulator \/ dt) + \"\\n\";\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: basicio.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2005-02-16 15:53:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_BASIC_IO_HXX_\n#define _COMPHELPER_BASIC_IO_HXX_\n\n#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_\n#include <com\/sun\/star\/io\/XPersistObject.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\nnamespace stario = ::com::sun::star::io;\nnamespace staruno = ::com::sun::star::uno;\nnamespace starawt = ::com::sun::star::awt;\n\n\/\/ sal_Bool\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Bool& _rVal);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Bool _bVal);\n\n\/\/ ::rtl::OUString\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, ::rtl::OUString& _rStr);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const ::rtl::OUString& _rStr);\n\n\/\/ sal_Int16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int16& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int16 _nValue);\n\n\/\/ sal_uInt16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt16& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt16 _nValue);\n\n\/\/ sal_uInt32\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt32& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt32 _nValue);\n\n\/\/ sal_Int16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int32& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int32 _nValue);\n\n\/\/ FontDescriptor\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& InStream, starawt::FontDescriptor& rVal);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& OutStream, const starawt::FontDescriptor& rVal);\n\n\/\/ sequences\ntemplate <class ELEMENT>\nconst staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, staruno::Sequence<ELEMENT>& _rSeq)\n{\n sal_Int32 nLen = _rxInStream->readLong();\n _rSeq.realloc(nLen);\n if (nLen)\n {\n ELEMENT* pElement = _rSeq.getArray();\n for (sal_Int32 i=0; i<nLen; ++i, ++pElement)\n _rxInStream >> *pElement;\n }\n return _rxInStream;\n}\n\ntemplate <class ELEMENT>\nconst staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const staruno::Sequence<ELEMENT>& _rSeq)\n{\n sal_Int32 nLen = _rSeq.getLength();\n _rxOutStream->writeLong(nLen);\n if (nLen)\n {\n const ELEMENT* pElement = _rSeq.getConstArray();\n for (sal_Int32 i = 0; i < nLen; ++i, ++pElement)\n _rxOutStream << *pElement;\n }\n return _rxOutStream;\n}\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ _COMPHELPER_BASIC_IO_HXX_\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.54); FILE MERGED 2005\/09\/05 15:23:38 rt 1.2.54.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: basicio.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:27:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_BASIC_IO_HXX_\n#define _COMPHELPER_BASIC_IO_HXX_\n\n#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_\n#include <com\/sun\/star\/io\/XPersistObject.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\nnamespace stario = ::com::sun::star::io;\nnamespace staruno = ::com::sun::star::uno;\nnamespace starawt = ::com::sun::star::awt;\n\n\/\/ sal_Bool\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Bool& _rVal);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Bool _bVal);\n\n\/\/ ::rtl::OUString\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, ::rtl::OUString& _rStr);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const ::rtl::OUString& _rStr);\n\n\/\/ sal_Int16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int16& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int16 _nValue);\n\n\/\/ sal_uInt16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt16& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt16 _nValue);\n\n\/\/ sal_uInt32\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_uInt32& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_uInt32 _nValue);\n\n\/\/ sal_Int16\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, sal_Int32& _rValue);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, sal_Int32 _nValue);\n\n\/\/ FontDescriptor\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& InStream, starawt::FontDescriptor& rVal);\nCOMPHELPER_DLLPUBLIC const staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& OutStream, const starawt::FontDescriptor& rVal);\n\n\/\/ sequences\ntemplate <class ELEMENT>\nconst staruno::Reference<stario::XObjectInputStream>& operator >> (const staruno::Reference<stario::XObjectInputStream>& _rxInStream, staruno::Sequence<ELEMENT>& _rSeq)\n{\n sal_Int32 nLen = _rxInStream->readLong();\n _rSeq.realloc(nLen);\n if (nLen)\n {\n ELEMENT* pElement = _rSeq.getArray();\n for (sal_Int32 i=0; i<nLen; ++i, ++pElement)\n _rxInStream >> *pElement;\n }\n return _rxInStream;\n}\n\ntemplate <class ELEMENT>\nconst staruno::Reference<stario::XObjectOutputStream>& operator << (const staruno::Reference<stario::XObjectOutputStream>& _rxOutStream, const staruno::Sequence<ELEMENT>& _rSeq)\n{\n sal_Int32 nLen = _rSeq.getLength();\n _rxOutStream->writeLong(nLen);\n if (nLen)\n {\n const ELEMENT* pElement = _rSeq.getConstArray();\n for (sal_Int32 i = 0; i < nLen; ++i, ++pElement)\n _rxOutStream << *pElement;\n }\n return _rxOutStream;\n}\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ _COMPHELPER_BASIC_IO_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>#include \"NeuralNetwork.hpp\"\n\nusing namespace std;\n\nNeuralNetwork::NeuralNetwork(const int ni, const int nh, const int no, const bool regression)\n\t: ni(ni+1), nh(nh+1), no(no), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0)\n{\n\twi = NeuralNetwork::makeMatrix(ni, nh);\n\two = NeuralNetwork::makeMatrix(nh, no);\n\n\tuniform_real_distribution<float> dist(-1, 1);\n\n\tfor (int i = 0; i < ni; i++) {\n\t\tfor (int j = 0; j < nh; j++) {\n\t\t\twi[i][j] = dist(rng);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < nh; i++) {\n\t\tfor (int j = 0; j < no; j++) {\n\t\t\two[i][j] = dist(rng);\n\t\t}\n\t}\n\n\tci = makeMatrix(ni, nh);\n\tco = makeMatrix(nh, no);\n\n\tcout << \"Number of inputs: \" << ni << endl;\n\tcout << \"Number of hidden neuron layers: \" << nh << endl;\n\tcout << \"Number of outputs: \" << no << endl;\n\n\tcout << \"Size of input weights: \" << wi.size() << endl;\n\tcout << \"Size of output weights:\" << wo.size() << endl;\n}\n\nvector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) {\n\tvector<vector<float>> matrix;\t\n\tfor (int i = 0; i < width; i++) {\n\t\tmatrix.push_back(vector<float>(height, fill));\n\t}\n\n\treturn matrix;\n}\n\nfloat NeuralNetwork::sigmoid(const float x) {\n return tanh(x);\n}\n\nfloat NeuralNetwork::dsigmoid(const float y) {\n return 1.0 - y*y;\n}\n\nvector<float> NeuralNetwork::update(const vector<float>& inputs) {\n if (inputs.size() != ni-1) {\n\t\t\tthrow string(\"wrong number of inputs\");\n\t\t}\n\n for (unsigned int i = 0; i < ni-1; i++) {\n ai[i] = inputs[i];\n\t\t}\n\n for (unsigned int j = 0; j < nh-1; j++) {\n float total = 0.0;\n for (int i = 0; i < ni; i++) {\n total += ai[i] * wi[i][j];\n\t\t\t}\n\n ah[j] = sigmoid(total);\n\t\t}\n\n for (unsigned int k = 0; k < no; k++) {\n float total = 0.0;\n for (unsigned int j = 0; j < nh; j++) {\n total += ah[j] * wo[j][k];\n\t\t\t}\n\n ao[k] = total;\n if (!regression) {\n ao[k] = sigmoid(total);\n\t\t\t}\n\t\t}\n \n return ao;\n}\n\nfloat NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) {\n\tif (targets.size() != no) {\n\t\tthrow string(\"wrong number of target values\");\n\t}\n\n\tvector<float> output_deltas(no, 1.0);\n\tfor (unsigned int k = 0; k < no; k++) {\n\t\toutput_deltas[k] = targets[k] - ao[k];\n\t\tif (!regression) {\n\t\t\toutput_deltas[k] = dsigmoid(ao[k])*output_deltas[k];\n\t\t}\n\t}\n\n\tvector<float> hidden_deltas(nh, 0.0);\n\tfor (unsigned int j = 0; j < nh; j++) {\n\t\tfloat error = 0.0;\n\t\tfor (unsigned int k = 0; k < no; k++) {\n\t\t\terror += output_deltas[k]*wo[j][k];\n\t\t}\n\n\t\thidden_deltas[j] = dsigmoid(ah[j])*error;\n\t}\n\n\tfor (unsigned int j = 0; j < nh; j++) {\n\t\tfor (unsigned int k = 0; k < no; k++) {\n\t\t\tfloat change = output_deltas[k]*ah[j];\n\t\t\two[j][k] = wo[j][k] + lr*change + mf*co[j][k];\n\t\t\tco[j][k] = change;\n\t\t}\n\t}\n\n\tfor (unsigned int i = 0; i < ni; i++) {\n\t\tfor (unsigned int j = 0; j < nh; j++) {\n\t\t\tfloat change = hidden_deltas[j]*ai[i];\n\t\t\twi[i][j] = wi[i][j] + lr*change + mf*ci[i][j];\n\t\t\tci[i][j] = change;\n\t\t}\n\t}\n\n\tfloat error = 0.0;\n\tfor (unsigned int k = 0; k < targets.size(); k++) {\n\t\terror += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k]));\n\t}\n\n\treturn error;\n}\n\nvector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) {\n\tvector<vector<float>> tmp;\n\tfor (const auto& p : patterns) {\n\t\tif (verbose) {\n\t\t\t\/\/ cout << p[0] << \" -> \" << update(p[0]);\n\t\t}\n\n\t\ttmp.push_back(update(p[0]));\n\t}\n\n\treturn tmp;\n}\n\nvoid NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) {\n\tfor (int i = 0; i < iterations; i++) {\n\t\tfloat error = 0;\n\n\t\tfor (const auto& p : patterns) {\n\t\t\tupdate(p[0]);\n\t\t\tfloat tmp = backPropagate(p[1], lr, mf);\n\t\t\terror += tmp;\n\t\t}\n\n\t\tif (i % 100 == 0) {\n\t\t\tcout << \"error rate = \" << error << endl;\n\t\t}\n\t}\n}\n\n<commit_msg>Fixed bug causing a segfault<commit_after>#include \"NeuralNetwork.hpp\"\n\nusing namespace std;\n\nNeuralNetwork::NeuralNetwork(const int nbi, const int nbh, const int nbo, const bool regression)\n\t: ni(nbi+1), nh(nbh+1), no(nbo), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0)\n{\n\twi = NeuralNetwork::makeMatrix(ni, nh);\n\two = NeuralNetwork::makeMatrix(nh, no);\n\n\tuniform_real_distribution<float> dist(-1, 1);\n\n\tfor (int i = 0; i < ni; i++) {\n\t\tfor (int j = 0; j < nh; j++) {\n\t\t\twi[i][j] = dist(rng);\n\t\t}\n\t}\n\n\tfor (int j = 0; j < nh; j++) {\n\t\tfor (int k = 0; k < no; k++) {\n\t\t\two[j][k] = dist(rng);\n\t\t}\n\t}\n\n\tci = makeMatrix(ni, nh);\n\tco = makeMatrix(nh, no);\n\n\tcout << \"Number of inputs: \" << ni << endl;\n\tcout << \"Number of hidden neuron layers: \" << nh << endl;\n\tcout << \"Number of outputs: \" << no << endl;\n\n\tcout << \"Size of input weights: \" << wi.size() << endl;\n\tcout << \"Size of output weights:\" << wo.size() << endl;\n}\n\nvector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) {\n\tvector<vector<float>> matrix;\t\n\tfor (int i = 0; i < width; i++) {\n\t\tmatrix.push_back(vector<float>(height, fill));\n\t}\n\n\treturn matrix;\n}\n\nfloat NeuralNetwork::sigmoid(const float x) {\n return tanh(x);\n}\n\nfloat NeuralNetwork::dsigmoid(const float y) {\n return 1.0 - y*y;\n}\n\nvector<float> NeuralNetwork::update(const vector<float>& inputs) {\n if (inputs.size() != ni-1) {\n\t\t\tthrow string(\"wrong number of inputs\");\n\t\t}\n\n for (unsigned int i = 0; i < ni-1; i++) {\n ai[i] = inputs[i];\n\t\t}\n\n for (unsigned int j = 0; j < nh-1; j++) {\n float total = 0.0;\n for (int i = 0; i < ni; i++) {\n total += ai[i] * wi[i][j];\n\t\t\t}\n\n ah[j] = sigmoid(total);\n\t\t}\n\n for (unsigned int k = 0; k < no; k++) {\n float total = 0.0;\n for (unsigned int j = 0; j < nh; j++) {\n total += ah[j] * wo[j][k];\n\t\t\t}\n\n ao[k] = total;\n if (!regression) {\n ao[k] = sigmoid(total);\n\t\t\t}\n\t\t}\n \n return ao;\n}\n\nfloat NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) {\n\tif (targets.size() != no) {\n\t\tthrow string(\"wrong number of target values\");\n\t}\n\n\tvector<float> output_deltas(no, 1.0);\n\tfor (unsigned int k = 0; k < no; k++) {\n\t\toutput_deltas[k] = targets[k] - ao[k];\n\t\tif (!regression) {\n\t\t\toutput_deltas[k] = dsigmoid(ao[k])*output_deltas[k];\n\t\t}\n\t}\n\n\tvector<float> hidden_deltas(nh, 0.0);\n\tfor (unsigned int j = 0; j < nh; j++) {\n\t\tfloat error = 0.0;\n\t\tfor (unsigned int k = 0; k < no; k++) {\n\t\t\terror += output_deltas[k]*wo[j][k];\n\t\t}\n\n\t\thidden_deltas[j] = dsigmoid(ah[j])*error;\n\t}\n\n\tfor (unsigned int j = 0; j < nh; j++) {\n\t\tfor (unsigned int k = 0; k < no; k++) {\n\t\t\tfloat change = output_deltas[k]*ah[j];\n\t\t\two[j][k] = wo[j][k] + lr*change + mf*co[j][k];\n\t\t\tco[j][k] = change;\n\t\t}\n\t}\n\n\tfor (unsigned int i = 0; i < ni; i++) {\n\t\tfor (unsigned int j = 0; j < nh; j++) {\n\t\t\tfloat change = hidden_deltas[j]*ai[i];\n\t\t\twi[i][j] = wi[i][j] + lr*change + mf*ci[i][j];\n\t\t\tci[i][j] = change;\n\t\t}\n\t}\n\n\tfloat error = 0.0;\n\tfor (unsigned int k = 0; k < targets.size(); k++) {\n\t\terror += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k]));\n\t}\n\n\treturn error;\n}\n\nvector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) {\n\tvector<vector<float>> tmp;\n\tfor (const auto& p : patterns) {\n\t\tif (verbose) {\n\t\t\t\/\/ cout << p[0] << \" -> \" << update(p[0]);\n\t\t}\n\n\t\ttmp.push_back(update(p[0]));\n\t}\n\n\treturn tmp;\n}\n\nvoid NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) {\n\tfor (int i = 0; i < iterations; i++) {\n\t\tfloat error = 0;\n\n\t\tfor (const auto& p : patterns) {\n\t\t\tupdate(p[0]);\n\t\t\tfloat tmp = backPropagate(p[1], lr, mf);\n\t\t\terror += tmp;\n\t\t}\n\n\t\tif (i % 100 == 0) {\n\t\t\tcout << \"error rate = \" << error << endl;\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Lech Kulina\n *\n * This file is part of the Realms Of Steel.\n * For conditions of distribution and use, see copyright details in the LICENSE file.\n *\/\n#include <iostream>\n#include <Application\/Logger.h>\n\nros::LoggerPtr ros::Logger::logger;\n\nros::LoggerPtr ros::Logger::Create(const PropertyTree& config) {\n if (logger) {\n return logger;\n }\n\n logger.reset(new Logger());\n if (!logger->Init(config)) {\n logger.reset();\n }\n\n return logger;\n}\n\nbool ros::Logger::Init(const PropertyTree& config) {\n if (!LogsSink::Init(config)) {\n return false;\n }\n\n for (PropertyConstIter iter = config.begin(); iter != config.end(); ++iter) {\n if (iter->first == \"Sink\") {\n LogsSinkPtr sink = LogsSink::Create(iter->second);\n if (sink) {\n sinks.push_back(sink);\n }\n }\n }\n\n return true;\n}\n\nbool ros::Logger::SendMessage(const LogMessage& message) {\n if (!IsMessageAccepted(message)) {\n return false;\n }\n\n for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {\n LogsSinkPtr sink = *iter;\n if (sink->IsMessageAccepted(message) && !sink->SendMessage(message)) {\n return false;\n }\n }\n\n return true;\n}\n\nvoid ros::Logger::FlushMessages() {\n for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {\n (*iter)->FlushMessages();\n }\n}\n<commit_msg>Fail logger initialization when there are not sinks available<commit_after>\/*\n * Copyright (c) 2016 Lech Kulina\n *\n * This file is part of the Realms Of Steel.\n * For conditions of distribution and use, see copyright details in the LICENSE file.\n *\/\n#include <iostream>\n#include <Application\/Logger.h>\n\nros::LoggerPtr ros::Logger::logger;\n\nros::LoggerPtr ros::Logger::Create(const PropertyTree& config) {\n if (logger) {\n return logger;\n }\n\n logger.reset(new Logger());\n if (!logger->Init(config)) {\n logger.reset();\n }\n\n return logger;\n}\n\nbool ros::Logger::Init(const PropertyTree& config) {\n if (!LogsSink::Init(config)) {\n return false;\n }\n\n for (PropertyConstIter iter = config.begin(); iter != config.end(); ++iter) {\n if (iter->first == \"Sink\") {\n LogsSinkPtr sink = LogsSink::Create(iter->second);\n if (sink) {\n sinks.push_back(sink);\n }\n }\n }\n\n if (sinks.empty()) {\n std::cerr << \"Failed to initialize logger: There are no sinks\" << std::endl;\n return false;\n }\n\n return true;\n}\n\nbool ros::Logger::SendMessage(const LogMessage& message) {\n if (!IsMessageAccepted(message)) {\n return false;\n }\n\n for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {\n LogsSinkPtr sink = *iter;\n if (sink->IsMessageAccepted(message) && !sink->SendMessage(message)) {\n return false;\n }\n }\n\n return true;\n}\n\nvoid ros::Logger::FlushMessages() {\n for (LogsSinksIter iter = sinks.begin(); iter != sinks.end(); ++iter) {\n (*iter)->FlushMessages();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"runner.hh\"\n#include <cxxabi.h>\n\n#include <stdexcept>\n#include <algorithm>\n#include <set>\n\nnamespace detail {\n__thread runner *runner_ = NULL;\nrunner::list *runners = new runner::list;\nmutex *tmutex = new mutex;\n}\n\nstatic unsigned int timespec_to_milliseconds(const timespec &ts) {\n \/\/ convert timespec to milliseconds\n unsigned int ms = ts.tv_sec * 1000;\n \/\/ 1 millisecond is 1 million nanoseconds\n ms += ts.tv_nsec \/ 1000000;\n return ms;\n}\n\nstatic std::ostream &operator << (std::ostream &o, task::deque &l) {\n o << \"[\";\n for (task::deque::iterator i=l.begin(); i!=l.end(); ++i) {\n o << *i << \",\";\n }\n o << \"]\";\n return o;\n}\n\nstatic void append_to_list(runner *r) {\n mutex::scoped_lock l(*detail::tmutex);\n detail::runners->push_back(r);\n}\n\nstatic void remove_from_list(runner *r) {\n mutex::scoped_lock l(*detail::tmutex);\n detail::runners->remove(r);\n}\n\nstatic void wakeup_all_runners() {\n mutex::scoped_lock l(*detail::tmutex);\n runner *current = runner::self();\n for (runner::list::iterator i=detail::runners->begin(); i!=detail::runners->end(); ++i) {\n if (current == *i) continue;\n (*i)->wakeup();\n }\n}\n\nstruct task_timeout_heap_compare {\n bool operator ()(const task *a, const task *b) const {\n \/\/ handle -1 case, which we want at the end\n if (a->get_timeout().tv_sec < 0) return true;\n return a->get_timeout() > b->get_timeout();\n }\n};\n\ntemplate <typename SetT> struct in_set {\n SetT &set;\n\n in_set(SetT &s) : set(s) {}\n\n bool operator()(typename SetT::key_type &k) {\n return set.count(k) > 0;\n }\n};\n\nrunner *runner::self() {\n if (detail::runner_ == NULL) {\n \/\/ this should happen in the main thread only and only once\n detail::runner_ = new runner;\n }\n return detail::runner_;\n}\n\nrunner *runner::spawn(const task::proc &f) {\n long ncpu = sysconf(_SC_NPROCESSORS_ONLN);\n mutex::scoped_lock l(*detail::tmutex);\n if (detail::runners->size() >= ncpu) {\n runner *r = detail::runners->front();\n detail::runners->pop_front();\n detail::runners->push_back(r);\n task::spawn(f, r);\n return r;\n }\n l.unlock();\n return new runner(f);\n}\n\nrunner::runner() : asleep(false), current_task(&scheduler) {\n append_to_list(this);\n tt=thread::self();\n}\n\nrunner::runner(task *t) : asleep(false), current_task(&scheduler) {\n add_to_runqueue(t);\n append_to_list(this);\n thread::create(tt, start, this);\n}\n\nrunner::runner(const task::proc &f) : asleep(false), current_task(&scheduler) {\n task::spawn(f, this);\n append_to_list(this);\n thread::create(tt, start, this);\n}\n\nvoid runner::sleep(mutex::scoped_lock &l) {\n \/\/ move to the head of the list\n \/\/ to simulate a FIFO\n \/\/ if there are too many threads\n \/\/ and not enough tasks, we can\n \/\/ use a cond.timedwait here and\n \/\/ exit a thread that times out\n\n \/\/ must set asleep here\n \/\/ another thread could add to runq\n \/\/ (a resume() for example)\n \/\/ during the unlock and if we're\n \/\/ not marked asleep, then we\n \/\/ end up sleeping while runq isn't empty\n asleep = true;\n l.unlock();\n {\n mutex::scoped_lock tl(*detail::tmutex);\n detail::runners->remove(this);\n detail::runners->push_front(this);\n }\n l.lock();\n while (asleep) {\n cond.wait(l);\n }\n}\n\n\ntypedef std::vector<epoll_event> event_vector;\n\nvoid runner::run_queued_tasks() {\n mutex::scoped_lock l(mut);\n while (!runq.empty()) {\n task *t = runq.front();\n runq.pop_front();\n l.unlock();\n task::swap(&scheduler, t);\n switch (t->get_state()) {\n case task::state_idle:\n \/\/ task wants to sleep\n l.lock();\n break;\n case task::state_running:\n t->set_state(task::state_idle, \"idle\");\n l.lock();\n runq.push_back(t);\n break;\n case task::state_exiting:\n delete t;\n l.lock();\n break;\n case task::state_migrating:\n if (t->get_runner()) {\n t->get_runner()->add_to_runqueue(t);\n } else {\n add_to_empty_runqueue(t);\n }\n l.lock();\n break;\n default:\n abort();\n break;\n }\n }\n}\n\nvoid runner::check_io() {\n event_vector events(efd.maxevents ? efd.maxevents : 1);\n if (waiters.empty()) return;\n bool done = false;\n while (!done) {\n timespec now;\n \/\/ TODO: probably should cache now for runner\n \/\/ avoid calling it every add_waiter()\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &now));\n std::make_heap(waiters.begin(), waiters.end(), task_timeout_heap_compare());\n int timeout_ms = -1;\n assert(!waiters.empty());\n if (waiters.front()->get_timeout().tv_sec > 0) {\n if (waiters.front()->get_timeout() <= now) {\n \/\/ epoll_wait must return immediately\n timeout_ms = 0;\n } else {\n timeout_ms = timespec_to_milliseconds(waiters.front()->get_timeout() - now);\n \/\/ help avoid spinning on timeouts smaller than 1 ms\n if (timeout_ms <= 0) timeout_ms = 1;\n }\n }\n\n if (events.empty()) {\n events.resize(efd.maxevents ? efd.maxevents : 1);\n }\n efd.wait(events, timeout_ms);\n\n std::set<task *> wake_tasks;\n for (event_vector::const_iterator i=events.begin();\n i!=events.end();++i)\n {\n task *t = pollfds[i->data.fd].t;\n pollfd *pfd = pollfds[i->data.fd].pfd;\n if (t && pfd) {\n pfd->revents = i->events;\n add_to_runqueue(t);\n wake_tasks.insert(t);\n } else {\n \/\/ TODO: otherwise we might want to remove fd from epoll\n fprintf(stderr, \"event for fd: %i but has no task\\n\", i->data.fd);\n }\n }\n\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &now));\n for (task_heap::iterator i=waiters.begin(); i!=waiters.end(); ++i) {\n task *t = *i;\n if (t->get_timeout().tv_sec > 0 && t->get_timeout() <= now) {\n wake_tasks.insert(t);\n add_to_runqueue(t);\n }\n }\n\n task_heap::iterator nend =\n std::remove_if(waiters.begin(), waiters.end(), in_set<std::set<task *> >(wake_tasks));\n waiters.erase(nend, waiters.end());\n \/\/ there are tasks to wake up!\n if (!wake_tasks.empty()) done = true;\n }\n}\n\nvoid runner::schedule() {\n try {\n for (;;) {\n run_queued_tasks();\n check_io();\n\n \/\/ check_io might have filled runqueue again\n mutex::scoped_lock l(mut);\n if (runq.empty()) {\n if (task::get_ntasks() > 0) {\n \/\/ block waiting for tasks to be scheduled on this runner\n sleep(l);\n } else {\n l.unlock();\n wakeup_all_runners();\n break;\n }\n }\n }\n } catch (abi::__forced_unwind&) {\n remove_from_list(detail::runner_);\n throw;\n } catch (std::exception &e) {\n remove_from_list(detail::runner_);\n throw;\n }\n remove_from_list(detail::runner_);\n}\n\nvoid *runner::start(void *arg) {\n using namespace detail;\n runner_ = (runner *)arg;\n thread::self().detach();\n try {\n detail::runner_->schedule();\n } catch (abi::__forced_unwind&) {\n throw;\n } catch (std::exception &e) {\n fprintf(stderr, \"uncaught exception in runner: %s\\n\", e.what());\n }\n delete detail::runner_;\n detail::runner_ = NULL;\n return NULL;\n}\n\nvoid runner::add_to_empty_runqueue(task *t) {\n mutex::scoped_lock l(*detail::tmutex);\n bool added = false;\n for (runner::list::iterator i=detail::runners->begin(); i!=detail::runners->end(); ++i) {\n if ((*i)->add_to_runqueue_if_asleep(t)) {\n added = true;\n break;\n }\n }\n if (!added) {\n new runner(t);\n }\n}\n\nvoid runner::add_waiter(task *t) {\n timespec abs;\n if (t->get_timeout().tv_sec != -1) {\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &abs));\n t->set_abs_timeout(t->get_timeout() + abs);\n }\n t->set_state(task::state_idle, \"waiting\");\n waiters.push_back(t);\n}\n\n<commit_msg>fix deadlock<commit_after>#include \"runner.hh\"\n#include <cxxabi.h>\n\n#include <stdexcept>\n#include <algorithm>\n#include <set>\n\nnamespace detail {\n__thread runner *runner_ = NULL;\nrunner::list *runners = new runner::list;\nmutex *tmutex = new mutex;\n}\n\nstatic unsigned int timespec_to_milliseconds(const timespec &ts) {\n \/\/ convert timespec to milliseconds\n unsigned int ms = ts.tv_sec * 1000;\n \/\/ 1 millisecond is 1 million nanoseconds\n ms += ts.tv_nsec \/ 1000000;\n return ms;\n}\n\nstatic std::ostream &operator << (std::ostream &o, task::deque &l) {\n o << \"[\";\n for (task::deque::iterator i=l.begin(); i!=l.end(); ++i) {\n o << *i << \",\";\n }\n o << \"]\";\n return o;\n}\n\nstatic void append_to_list(runner *r) {\n mutex::scoped_lock l(*detail::tmutex);\n detail::runners->push_back(r);\n}\n\nstatic void remove_from_list(runner *r) {\n mutex::scoped_lock l(*detail::tmutex);\n detail::runners->remove(r);\n}\n\nstatic void wakeup_all_runners() {\n mutex::scoped_lock l(*detail::tmutex);\n runner *current = runner::self();\n for (runner::list::iterator i=detail::runners->begin(); i!=detail::runners->end(); ++i) {\n if (current == *i) continue;\n (*i)->wakeup();\n }\n}\n\nstruct task_timeout_heap_compare {\n bool operator ()(const task *a, const task *b) const {\n \/\/ handle -1 case, which we want at the end\n if (a->get_timeout().tv_sec < 0) return true;\n return a->get_timeout() > b->get_timeout();\n }\n};\n\ntemplate <typename SetT> struct in_set {\n SetT &set;\n\n in_set(SetT &s) : set(s) {}\n\n bool operator()(typename SetT::key_type &k) {\n return set.count(k) > 0;\n }\n};\n\nrunner *runner::self() {\n if (detail::runner_ == NULL) {\n \/\/ this should happen in the main thread only and only once\n detail::runner_ = new runner;\n }\n return detail::runner_;\n}\n\nrunner *runner::spawn(const task::proc &f) {\n long ncpu = sysconf(_SC_NPROCESSORS_ONLN);\n mutex::scoped_lock l(*detail::tmutex);\n if (detail::runners->size() >= ncpu) {\n runner *r = detail::runners->front();\n detail::runners->pop_front();\n detail::runners->push_back(r);\n task::spawn(f, r);\n return r;\n }\n l.unlock();\n return new runner(f);\n}\n\nrunner::runner() : asleep(false), current_task(&scheduler) {\n append_to_list(this);\n tt=thread::self();\n}\n\nrunner::runner(task *t) : asleep(false), current_task(&scheduler) {\n add_to_runqueue(t);\n append_to_list(this);\n thread::create(tt, start, this);\n}\n\nrunner::runner(const task::proc &f) : asleep(false), current_task(&scheduler) {\n task::spawn(f, this);\n append_to_list(this);\n thread::create(tt, start, this);\n}\n\nvoid runner::sleep(mutex::scoped_lock &l) {\n \/\/ move to the head of the list\n \/\/ to simulate a FIFO\n \/\/ if there are too many threads\n \/\/ and not enough tasks, we can\n \/\/ use a cond.timedwait here and\n \/\/ exit a thread that times out\n\n \/\/ must set asleep here\n \/\/ another thread could add to runq\n \/\/ (a resume() for example)\n \/\/ during the unlock and if we're\n \/\/ not marked asleep, then we\n \/\/ end up sleeping while runq isn't empty\n asleep = true;\n l.unlock();\n {\n mutex::scoped_lock tl(*detail::tmutex);\n detail::runners->remove(this);\n detail::runners->push_front(this);\n }\n l.lock();\n while (asleep) {\n cond.wait(l);\n }\n}\n\n\ntypedef std::vector<epoll_event> event_vector;\n\nvoid runner::run_queued_tasks() {\n mutex::scoped_lock l(mut);\n while (!runq.empty()) {\n task *t = runq.front();\n runq.pop_front();\n l.unlock();\n task::swap(&scheduler, t);\n switch (t->get_state()) {\n case task::state_idle:\n \/\/ task wants to sleep\n l.lock();\n break;\n case task::state_running:\n t->set_state(task::state_idle, \"idle\");\n l.lock();\n runq.push_back(t);\n break;\n case task::state_exiting:\n delete t;\n l.lock();\n break;\n case task::state_migrating:\n if (t->get_runner()) {\n t->get_runner()->add_to_runqueue(t);\n } else {\n add_to_empty_runqueue(t);\n }\n l.lock();\n break;\n default:\n abort();\n break;\n }\n }\n}\n\nvoid runner::check_io() {\n event_vector events(efd.maxevents ? efd.maxevents : 1);\n if (waiters.empty()) return;\n bool done = false;\n while (!done) {\n timespec now;\n \/\/ TODO: probably should cache now for runner\n \/\/ avoid calling it every add_waiter()\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &now));\n std::make_heap(waiters.begin(), waiters.end(), task_timeout_heap_compare());\n int timeout_ms = -1;\n assert(!waiters.empty());\n if (waiters.front()->get_timeout().tv_sec > 0) {\n if (waiters.front()->get_timeout() <= now) {\n \/\/ epoll_wait must return immediately\n timeout_ms = 0;\n } else {\n timeout_ms = timespec_to_milliseconds(waiters.front()->get_timeout() - now);\n \/\/ help avoid spinning on timeouts smaller than 1 ms\n if (timeout_ms <= 0) timeout_ms = 1;\n }\n }\n\n if (events.empty()) {\n events.resize(efd.maxevents ? efd.maxevents : 1);\n }\n efd.wait(events, timeout_ms);\n\n std::set<task *> wake_tasks;\n for (event_vector::const_iterator i=events.begin();\n i!=events.end();++i)\n {\n task *t = pollfds[i->data.fd].t;\n pollfd *pfd = pollfds[i->data.fd].pfd;\n if (t && pfd) {\n pfd->revents = i->events;\n add_to_runqueue(t);\n wake_tasks.insert(t);\n } else {\n \/\/ TODO: otherwise we might want to remove fd from epoll\n fprintf(stderr, \"event for fd: %i but has no task\\n\", i->data.fd);\n }\n }\n\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &now));\n for (task_heap::iterator i=waiters.begin(); i!=waiters.end(); ++i) {\n task *t = *i;\n if (t->get_timeout().tv_sec > 0 && t->get_timeout() <= now) {\n wake_tasks.insert(t);\n add_to_runqueue(t);\n }\n }\n\n task_heap::iterator nend =\n std::remove_if(waiters.begin(), waiters.end(), in_set<std::set<task *> >(wake_tasks));\n waiters.erase(nend, waiters.end());\n \/\/ there are tasks to wake up!\n if (!wake_tasks.empty()) done = true;\n }\n}\n\nvoid runner::schedule() {\n try {\n for (;;) {\n run_queued_tasks();\n check_io();\n\n \/\/ check_io might have filled runqueue again\n mutex::scoped_lock l(mut);\n if (runq.empty()) {\n if (task::get_ntasks() > 0) {\n \/\/ block waiting for tasks to be scheduled on this runner\n sleep(l);\n } else {\n l.unlock();\n wakeup_all_runners();\n break;\n }\n }\n }\n } catch (abi::__forced_unwind&) {\n remove_from_list(detail::runner_);\n throw;\n } catch (std::exception &e) {\n remove_from_list(detail::runner_);\n throw;\n }\n remove_from_list(detail::runner_);\n}\n\nvoid *runner::start(void *arg) {\n using namespace detail;\n runner_ = (runner *)arg;\n thread::self().detach();\n try {\n detail::runner_->schedule();\n } catch (abi::__forced_unwind&) {\n throw;\n } catch (std::exception &e) {\n fprintf(stderr, \"uncaught exception in runner: %s\\n\", e.what());\n }\n delete detail::runner_;\n detail::runner_ = NULL;\n return NULL;\n}\n\nvoid runner::add_to_empty_runqueue(task *t) {\n mutex::scoped_lock l(*detail::tmutex);\n bool added = false;\n for (runner::list::iterator i=detail::runners->begin(); i!=detail::runners->end(); ++i) {\n if ((*i)->add_to_runqueue_if_asleep(t)) {\n added = true;\n break;\n }\n }\n if (!added) {\n l.unlock();\n new runner(t);\n }\n}\n\nvoid runner::add_waiter(task *t) {\n timespec abs;\n if (t->get_timeout().tv_sec != -1) {\n THROW_ON_ERROR(clock_gettime(CLOCK_MONOTONIC, &abs));\n t->set_abs_timeout(t->get_timeout() + abs);\n }\n t->set_state(task::state_idle, \"waiting\");\n waiters.push_back(t);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/drivers\/canbus\/can_client\/socket\/socket_can_client_raw.h\"\n\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"modules\/drivers\/canbus\/proto\/can_card_parameter.pb.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\nnamespace can {\n\nusing apollo::common::ErrorCode;\n\nTEST(SocketCanClientRawTest, simple_test) {\n CANCardParameter param;\n param.set_brand(CANCardParameter::ESD_CAN);\n param.set_channel_id(CANCardParameter::CHANNEL_ID_ZERO);\n\n SocketCanClientRaw socket_can_client;\n EXPECT_TRUE(socket_can_client.Init(param));\n EXPECT_EQ(socket_can_client.Start(), ErrorCode::CAN_CLIENT_ERROR_BASE);\n std::vector<CanFrame> frames;\n int32_t num = 0;\n EXPECT_EQ(socket_can_client.Send(frames, &num),\n ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);\n EXPECT_EQ(socket_can_client.Receive(&frames, &num),\n ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED);\n CanFrame can_frame;\n frames.push_back(can_frame);\n EXPECT_EQ(socket_can_client.SendSingleFrame(frames),\n ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);\n socket_can_client.Stop();\n}\n\n} \/\/ namespace can\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n<commit_msg>Drivers: fix socket can test (#873)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/drivers\/canbus\/can_client\/socket\/socket_can_client_raw.h\"\n\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"modules\/drivers\/canbus\/proto\/can_card_parameter.pb.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\nnamespace can {\n\nusing apollo::common::ErrorCode;\n\nTEST(SocketCanClientRawTest, simple_test) {\n CANCardParameter param;\n param.set_brand(CANCardParameter::SOCKET_CAN_RAW);\n param.set_channel_id(CANCardParameter::CHANNEL_ID_ZERO);\n\n SocketCanClientRaw socket_can_client;\n EXPECT_TRUE(socket_can_client.Init(param));\n EXPECT_EQ(socket_can_client.Start(), ErrorCode::CAN_CLIENT_ERROR_BASE);\n std::vector<CanFrame> frames;\n int32_t num = 0;\n EXPECT_EQ(socket_can_client.Send(frames, &num),\n ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);\n EXPECT_EQ(socket_can_client.Receive(&frames, &num),\n ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED);\n CanFrame can_frame;\n frames.push_back(can_frame);\n EXPECT_EQ(socket_can_client.SendSingleFrame(frames),\n ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED);\n socket_can_client.Stop();\n}\n\n} \/\/ namespace can\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"HistogramWidget.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"Utilities.h\"\n\n#include \"vtkChartHistogramColorOpacityEditor.h\"\n\n#include <vtkContextScene.h>\n#include <vtkContextView.h>\n#include <vtkControlPointsItem.h>\n#include <vtkEventQtSlotConnect.h>\n#include <vtkGenericOpenGLRenderWindow.h>\n#include <vtkPiecewiseFunction.h>\n#include <vtkRenderWindow.h>\n#include <vtkVector.h>\n\n#include <QVTKOpenGLWidget.h>\n\n#include <pqApplicationCore.h>\n#include <pqCoreUtilities.h>\n#include <pqPresetDialog.h>\n#include <pqRescaleRange.h>\n#include <pqResetScalarRangeReaction.h>\n#include <pqServerManagerModel.h>\n#include <pqView.h>\n\n#include <vtkPVDiscretizableColorTransferFunction.h>\n#include <vtkSMPropertyHelper.h>\n#include <vtkSMTransferFunctionProxy.h>\n#include <vtkSMViewProxy.h>\n\n#include <QColorDialog>\n#include <QHBoxLayout>\n#include <QToolButton>\n#include <QVBoxLayout>\n\n#include <QDebug>\n\nnamespace tomviz {\n\nHistogramWidget::HistogramWidget(QWidget* parent)\n : QWidget(parent), m_qvtk(new QVTKOpenGLWidget(this))\n{\n \/\/ Set up our little chart.\n vtkNew<vtkGenericOpenGLRenderWindow> window;\n m_qvtk->SetRenderWindow(window.Get());\n QSurfaceFormat glFormat = QVTKOpenGLWidget::defaultFormat();\n glFormat.setSamples(8);\n m_qvtk->setFormat(glFormat);\n m_histogramView->SetRenderWindow(window.Get());\n m_histogramView->SetInteractor(m_qvtk->GetInteractor());\n m_histogramView->GetScene()->AddItem(m_histogramColorOpacityEditor.Get());\n\n \/\/ Connect events from the histogram color\/opacity editor.\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::CursorChangedEvent, this,\n SLOT(histogramClicked(vtkObject*)));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::EndEvent, this,\n SLOT(onScalarOpacityFunctionChanged()));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkControlPointsItem::CurrentPointEditEvent, this,\n SLOT(onCurrentPointEditEvent()));\n\n auto hLayout = new QHBoxLayout(this);\n hLayout->addWidget(m_qvtk);\n auto vLayout = new QVBoxLayout;\n hLayout->addLayout(vLayout);\n hLayout->setContentsMargins(0, 0, 5, 0);\n\n vLayout->setContentsMargins(0, 0, 0, 0);\n vLayout->addStretch(1);\n\n auto button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRange.png\"));\n button->setToolTip(\"Reset data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onResetRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRangeCustom.png\"));\n button->setToolTip(\"Specify data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onCustomRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqInvert.png\"));\n button->setToolTip(\"Invert color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onInvertClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqFavorites.png\"));\n button->setToolTip(\"Choose preset color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onPresetClicked()));\n vLayout->addWidget(button);\n\n m_gradientOpacityButton = new QToolButton;\n m_gradientOpacityButton->setCheckable(true);\n m_gradientOpacityButton->setIcon(QIcon(\":\/icons\/gradient_opacity.png\"));\n m_gradientOpacityButton->setToolTip(\"Show\/Hide Gradient Opacity\");\n connect(m_gradientOpacityButton, SIGNAL(toggled(bool)), this,\n SIGNAL(gradientVisibilityChanged(bool)));\n vLayout->addWidget(m_gradientOpacityButton);\n\n vLayout->addStretch(1);\n\n setLayout(hLayout);\n\n \/\/ Delay setting of the device pixel ratio until after the QVTKOpenGLWidget\n \/\/ widget has been set up.\n QTimer::singleShot(0, [=] {\n int dpi = m_qvtk->physicalDpiX() * m_qvtk->devicePixelRatio();\n \/\/ Currently very empirical, scale high DPI so that fonts don't get so big.\n \/\/ In my testing they seem to be quite a bit bigger that the Qt text sizes.\n dpi = (dpi - 72) * 0.56 + 72;\n m_histogramColorOpacityEditor->SetDPI(dpi);\n });\n}\n\nHistogramWidget::~HistogramWidget() = default;\n\nvoid HistogramWidget::setLUT(vtkPVDiscretizableColorTransferFunction* lut)\n{\n if (m_LUT != lut) {\n if (m_scalarOpacityFunction) {\n m_eventLink->Disconnect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent, this,\n SLOT(onScalarOpacityFunctionChanged()));\n }\n m_LUT = lut;\n m_scalarOpacityFunction = m_LUT->GetScalarOpacityFunction();\n m_eventLink->Connect(m_scalarOpacityFunction, vtkCommand::ModifiedEvent,\n this, SLOT(onScalarOpacityFunctionChanged()));\n }\n}\n\nvoid HistogramWidget::setLUTProxy(vtkSMProxy* proxy)\n{\n if (m_LUTProxy != proxy) {\n m_LUTProxy = proxy;\n vtkPVDiscretizableColorTransferFunction* lut =\n vtkPVDiscretizableColorTransferFunction::SafeDownCast(\n proxy->GetClientSideObject());\n setLUT(lut);\n }\n}\n\nvoid HistogramWidget::setInputData(vtkTable* table, const char* x_,\n const char* y_)\n{\n m_histogramColorOpacityEditor->SetHistogramInputData(table, x_, y_);\n m_histogramColorOpacityEditor->SetOpacityFunction(m_scalarOpacityFunction);\n if (m_LUT && table) {\n m_histogramColorOpacityEditor->SetScalarVisibility(true);\n m_histogramColorOpacityEditor->SetColorTransferFunction(m_LUT);\n m_histogramColorOpacityEditor->SelectColorArray(\"image_extents\");\n }\n m_histogramView->Render();\n}\n\nvoid HistogramWidget::onScalarOpacityFunctionChanged()\n{\n auto core = pqApplicationCore::instance();\n auto smModel = core->getServerManagerModel();\n QList<pqView*> views = smModel->findItems<pqView*>();\n foreach (pqView* view, views) {\n view->render();\n }\n\n \/\/ Update the histogram\n m_histogramView->GetRenderWindow()->Render();\n\n \/\/ Update the scalar opacity function proxy as it does not update it's\n \/\/ internal state when the VTK object changes.\n if (!m_LUTProxy) {\n return;\n }\n\n vtkSMProxy* opacityMapProxy =\n vtkSMPropertyHelper(m_LUTProxy, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (!opacityMapProxy) {\n return;\n }\n\n vtkSMPropertyHelper pointsHelper(opacityMapProxy, \"Points\");\n vtkObjectBase* opacityMapObject = opacityMapProxy->GetClientSideObject();\n auto pwf = vtkPiecewiseFunction::SafeDownCast(opacityMapObject);\n if (pwf) {\n pointsHelper.SetNumberOfElements(4 * pwf->GetSize());\n for (int i = 0; i < pwf->GetSize(); ++i) {\n double value[4];\n pwf->GetNodeValue(i, value);\n pointsHelper.Set(4 * i + 0, value[0]);\n pointsHelper.Set(4 * i + 1, value[1]);\n pointsHelper.Set(4 * i + 2, value[2]);\n pointsHelper.Set(4 * i + 3, value[3]);\n }\n }\n}\n\nvoid HistogramWidget::onCurrentPointEditEvent()\n{\n double rgb[3];\n if (m_histogramColorOpacityEditor->GetCurrentControlPointColor(rgb)) {\n QColor color = QColorDialog::getColor(\n QColor::fromRgbF(rgb[0], rgb[1], rgb[2]), this,\n \"Select Color for Control Point\", QColorDialog::DontUseNativeDialog);\n if (color.isValid()) {\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n m_histogramColorOpacityEditor->SetCurrentControlPointColor(rgb);\n onScalarOpacityFunctionChanged();\n }\n }\n}\n\nvoid HistogramWidget::histogramClicked(vtkObject*)\n{\n auto activeDataSource = ActiveObjects::instance().activeDataSource();\n Q_ASSERT(activeDataSource);\n\n auto view = ActiveObjects::instance().activeView();\n if (!view) {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n typedef ModuleContour ModuleContourType;\n\n auto contour =\n qobject_cast<ModuleContourType*>(ActiveObjects::instance().activeModule());\n if (!contour) {\n QList<ModuleContourType*> contours =\n ModuleManager::instance().findModules<ModuleContourType*>(\n activeDataSource, view);\n if (contours.size() == 0) {\n contour = qobject_cast<ModuleContourType*>(\n ModuleManager::instance().createAndAddModule(\"Contour\",\n activeDataSource, view));\n } else {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(m_histogramColorOpacityEditor->GetContourValue());\n tomviz::convert<pqView*>(view)->render();\n}\n\nvoid HistogramWidget::onResetRangeClicked()\n{\n pqResetScalarRangeReaction::resetScalarRangeToData(nullptr);\n}\n\nvoid HistogramWidget::onCustomRangeClicked()\n{\n vtkVector2d range;\n vtkDiscretizableColorTransferFunction* discFunc =\n vtkDiscretizableColorTransferFunction::SafeDownCast(\n m_LUTProxy->GetClientSideObject());\n if (!discFunc) {\n return;\n }\n discFunc->GetRange(range.GetData());\n pqRescaleRange dialog(pqCoreUtilities::mainWidget());\n dialog.setRange(range[0], range[1]);\n if (dialog.exec() == QDialog::Accepted) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(\n m_LUTProxy, dialog.minimum(), dialog.maximum());\n }\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onInvertClicked()\n{\n vtkSMTransferFunctionProxy::InvertTransferFunction(m_LUTProxy);\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onPresetClicked()\n{\n pqPresetDialog dialog(pqCoreUtilities::mainWidget(),\n pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);\n dialog.setCustomizableLoadColors(true);\n dialog.setCustomizableLoadOpacities(true);\n dialog.setCustomizableUsePresetRange(true);\n dialog.setCustomizableLoadAnnotations(false);\n connect(&dialog, SIGNAL(applyPreset(const Json::Value&)),\n SLOT(applyCurrentPreset()));\n dialog.exec();\n}\n\nvoid HistogramWidget::applyCurrentPreset()\n{\n auto dialog = qobject_cast<pqPresetDialog*>(sender());\n Q_ASSERT(dialog);\n\n vtkSMProxy* lut = m_LUTProxy;\n if (!lut) {\n return;\n }\n\n if (dialog->loadColors() || dialog->loadOpacities()) {\n vtkSMProxy* sof =\n vtkSMPropertyHelper(lut, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (dialog->loadColors()) {\n vtkSMTransferFunctionProxy::ApplyPreset(lut, dialog->currentPreset(),\n !dialog->usePresetRange());\n }\n if (dialog->loadOpacities()) {\n if (sof) {\n vtkSMTransferFunctionProxy::ApplyPreset(sof, dialog->currentPreset(),\n !dialog->usePresetRange());\n } else {\n qWarning(\"Cannot load opacities since 'ScalarOpacityFunction' is not \"\n \"present.\");\n }\n }\n\n \/\/ We need to take extra care to avoid the color and opacity function ranges\n \/\/ from straying away from each other. This can happen if only one of them\n \/\/ is getting a preset and we're using the preset range.\n if (dialog->usePresetRange() &&\n (dialog->loadColors() ^ dialog->loadOpacities()) && sof) {\n double range[2];\n if (dialog->loadColors() &&\n vtkSMTransferFunctionProxy::GetRange(lut, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(sof, range);\n } else if (dialog->loadOpacities() &&\n vtkSMTransferFunctionProxy::GetRange(sof, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(lut, range);\n }\n }\n renderViews();\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::renderViews()\n{\n pqView* view =\n tomviz::convert<pqView*>(ActiveObjects::instance().activeView());\n if (view) {\n view->render();\n }\n}\n\nvoid HistogramWidget::setGradientOpacityChecked(bool checked)\n{\n m_gradientOpacityButton->setChecked(checked);\n emit m_gradientOpacityButton->toggled(checked);\n}\n\nvoid HistogramWidget::setGradientOpacityEnabled(bool enable)\n{\n m_gradientOpacityButton->setEnabled(enable);\n}\n}\n<commit_msg>Fix the widget for retina display<commit_after>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"HistogramWidget.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"ModuleContour.h\"\n#include \"ModuleManager.h\"\n#include \"Utilities.h\"\n\n#include \"vtkChartHistogramColorOpacityEditor.h\"\n\n#include <vtkContextScene.h>\n#include <vtkContextView.h>\n#include <vtkControlPointsItem.h>\n#include <vtkEventQtSlotConnect.h>\n#include <vtkGenericOpenGLRenderWindow.h>\n#include <vtkPiecewiseFunction.h>\n#include <vtkRenderWindow.h>\n#include <vtkVector.h>\n\n#include <QVTKOpenGLWidget.h>\n\n#include <pqApplicationCore.h>\n#include <pqCoreUtilities.h>\n#include <pqPresetDialog.h>\n#include <pqRescaleRange.h>\n#include <pqResetScalarRangeReaction.h>\n#include <pqServerManagerModel.h>\n#include <pqView.h>\n\n#include <vtkPVDiscretizableColorTransferFunction.h>\n#include <vtkSMPropertyHelper.h>\n#include <vtkSMTransferFunctionProxy.h>\n#include <vtkSMViewProxy.h>\n\n#include <QColorDialog>\n#include <QHBoxLayout>\n#include <QToolButton>\n#include <QVBoxLayout>\n\n#include <QDebug>\n\nnamespace tomviz {\n\nHistogramWidget::HistogramWidget(QWidget* parent)\n : QWidget(parent), m_qvtk(new QVTKOpenGLWidget(this))\n{\n \/\/ Set up our little chart.\n vtkNew<vtkGenericOpenGLRenderWindow> window;\n m_qvtk->SetRenderWindow(window.Get());\n QSurfaceFormat glFormat = QVTKOpenGLWidget::defaultFormat();\n glFormat.setSamples(8);\n m_qvtk->setFormat(glFormat);\n m_histogramView->SetRenderWindow(window.Get());\n m_histogramView->SetInteractor(m_qvtk->GetInteractor());\n m_histogramView->GetScene()->AddItem(m_histogramColorOpacityEditor.Get());\n\n \/\/ Connect events from the histogram color\/opacity editor.\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::CursorChangedEvent, this,\n SLOT(histogramClicked(vtkObject*)));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkCommand::EndEvent, this,\n SLOT(onScalarOpacityFunctionChanged()));\n m_eventLink->Connect(m_histogramColorOpacityEditor.Get(),\n vtkControlPointsItem::CurrentPointEditEvent, this,\n SLOT(onCurrentPointEditEvent()));\n\n auto hLayout = new QHBoxLayout(this);\n hLayout->addWidget(m_qvtk);\n auto vLayout = new QVBoxLayout;\n hLayout->addLayout(vLayout);\n hLayout->setContentsMargins(0, 0, 5, 0);\n\n vLayout->setContentsMargins(0, 0, 0, 0);\n vLayout->addStretch(1);\n\n auto button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRange.png\"));\n button->setToolTip(\"Reset data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onResetRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqResetRangeCustom.png\"));\n button->setToolTip(\"Specify data range\");\n connect(button, SIGNAL(clicked()), this, SLOT(onCustomRangeClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqInvert.png\"));\n button->setToolTip(\"Invert color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onInvertClicked()));\n vLayout->addWidget(button);\n\n button = new QToolButton;\n button->setIcon(QIcon(\":\/icons\/pqFavorites.png\"));\n button->setToolTip(\"Choose preset color map\");\n connect(button, SIGNAL(clicked()), this, SLOT(onPresetClicked()));\n vLayout->addWidget(button);\n\n m_gradientOpacityButton = new QToolButton;\n m_gradientOpacityButton->setCheckable(true);\n m_gradientOpacityButton->setIcon(QIcon(\":\/icons\/gradient_opacity.png\"));\n m_gradientOpacityButton->setToolTip(\"Show\/Hide Gradient Opacity\");\n connect(m_gradientOpacityButton, SIGNAL(toggled(bool)), this,\n SIGNAL(gradientVisibilityChanged(bool)));\n vLayout->addWidget(m_gradientOpacityButton);\n\n vLayout->addStretch(1);\n\n setLayout(hLayout);\n\n \/\/ Delay setting of the device pixel ratio until after the QVTKOpenGLWidget\n \/\/ widget has been set up.\n QTimer::singleShot(0, [=] {\n int dpi = m_qvtk->physicalDpiX() * m_qvtk->devicePixelRatio();\n \/\/ Currently very empirical, scale high DPI so that fonts don't get so big.\n \/\/ In my testing they seem to be quite a bit bigger that the Qt text sizes.\n dpi = (dpi - 72) * 0.56 + 72;\n m_histogramColorOpacityEditor->SetDPI(dpi);\n });\n\n \/\/ New way to do this, although it removes any option for tweaking the DPI,\n \/\/ oddly defaults to off too, so ensure it is set to on (non-retina no effect)\n \/\/ Note that the widget now clobbers any number you might set upon recreatring\n \/\/ the FBO, and so the numbers above will never be seen by the render window.\n m_qvtk->setEnableHiDPI(true);\n}\n\nHistogramWidget::~HistogramWidget() = default;\n\nvoid HistogramWidget::setLUT(vtkPVDiscretizableColorTransferFunction* lut)\n{\n if (m_LUT != lut) {\n if (m_scalarOpacityFunction) {\n m_eventLink->Disconnect(m_scalarOpacityFunction,\n vtkCommand::ModifiedEvent, this,\n SLOT(onScalarOpacityFunctionChanged()));\n }\n m_LUT = lut;\n m_scalarOpacityFunction = m_LUT->GetScalarOpacityFunction();\n m_eventLink->Connect(m_scalarOpacityFunction, vtkCommand::ModifiedEvent,\n this, SLOT(onScalarOpacityFunctionChanged()));\n }\n}\n\nvoid HistogramWidget::setLUTProxy(vtkSMProxy* proxy)\n{\n if (m_LUTProxy != proxy) {\n m_LUTProxy = proxy;\n vtkPVDiscretizableColorTransferFunction* lut =\n vtkPVDiscretizableColorTransferFunction::SafeDownCast(\n proxy->GetClientSideObject());\n setLUT(lut);\n }\n}\n\nvoid HistogramWidget::setInputData(vtkTable* table, const char* x_,\n const char* y_)\n{\n m_histogramColorOpacityEditor->SetHistogramInputData(table, x_, y_);\n m_histogramColorOpacityEditor->SetOpacityFunction(m_scalarOpacityFunction);\n if (m_LUT && table) {\n m_histogramColorOpacityEditor->SetScalarVisibility(true);\n m_histogramColorOpacityEditor->SetColorTransferFunction(m_LUT);\n m_histogramColorOpacityEditor->SelectColorArray(\"image_extents\");\n }\n m_histogramView->Render();\n}\n\nvoid HistogramWidget::onScalarOpacityFunctionChanged()\n{\n auto core = pqApplicationCore::instance();\n auto smModel = core->getServerManagerModel();\n QList<pqView*> views = smModel->findItems<pqView*>();\n foreach (pqView* view, views) {\n view->render();\n }\n\n \/\/ Update the histogram\n m_histogramView->GetRenderWindow()->Render();\n\n \/\/ Update the scalar opacity function proxy as it does not update it's\n \/\/ internal state when the VTK object changes.\n if (!m_LUTProxy) {\n return;\n }\n\n vtkSMProxy* opacityMapProxy =\n vtkSMPropertyHelper(m_LUTProxy, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (!opacityMapProxy) {\n return;\n }\n\n vtkSMPropertyHelper pointsHelper(opacityMapProxy, \"Points\");\n vtkObjectBase* opacityMapObject = opacityMapProxy->GetClientSideObject();\n auto pwf = vtkPiecewiseFunction::SafeDownCast(opacityMapObject);\n if (pwf) {\n pointsHelper.SetNumberOfElements(4 * pwf->GetSize());\n for (int i = 0; i < pwf->GetSize(); ++i) {\n double value[4];\n pwf->GetNodeValue(i, value);\n pointsHelper.Set(4 * i + 0, value[0]);\n pointsHelper.Set(4 * i + 1, value[1]);\n pointsHelper.Set(4 * i + 2, value[2]);\n pointsHelper.Set(4 * i + 3, value[3]);\n }\n }\n}\n\nvoid HistogramWidget::onCurrentPointEditEvent()\n{\n double rgb[3];\n if (m_histogramColorOpacityEditor->GetCurrentControlPointColor(rgb)) {\n QColor color = QColorDialog::getColor(\n QColor::fromRgbF(rgb[0], rgb[1], rgb[2]), this,\n \"Select Color for Control Point\", QColorDialog::DontUseNativeDialog);\n if (color.isValid()) {\n rgb[0] = color.redF();\n rgb[1] = color.greenF();\n rgb[2] = color.blueF();\n m_histogramColorOpacityEditor->SetCurrentControlPointColor(rgb);\n onScalarOpacityFunctionChanged();\n }\n }\n}\n\nvoid HistogramWidget::histogramClicked(vtkObject*)\n{\n auto activeDataSource = ActiveObjects::instance().activeDataSource();\n Q_ASSERT(activeDataSource);\n\n auto view = ActiveObjects::instance().activeView();\n if (!view) {\n return;\n }\n\n \/\/ Use active ModuleContour is possible. Otherwise, find the first existing\n \/\/ ModuleContour instance or just create a new one, if none exists.\n typedef ModuleContour ModuleContourType;\n\n auto contour =\n qobject_cast<ModuleContourType*>(ActiveObjects::instance().activeModule());\n if (!contour) {\n QList<ModuleContourType*> contours =\n ModuleManager::instance().findModules<ModuleContourType*>(\n activeDataSource, view);\n if (contours.size() == 0) {\n contour = qobject_cast<ModuleContourType*>(\n ModuleManager::instance().createAndAddModule(\"Contour\",\n activeDataSource, view));\n } else {\n contour = contours[0];\n }\n ActiveObjects::instance().setActiveModule(contour);\n }\n Q_ASSERT(contour);\n contour->setIsoValue(m_histogramColorOpacityEditor->GetContourValue());\n tomviz::convert<pqView*>(view)->render();\n}\n\nvoid HistogramWidget::onResetRangeClicked()\n{\n pqResetScalarRangeReaction::resetScalarRangeToData(nullptr);\n}\n\nvoid HistogramWidget::onCustomRangeClicked()\n{\n vtkVector2d range;\n vtkDiscretizableColorTransferFunction* discFunc =\n vtkDiscretizableColorTransferFunction::SafeDownCast(\n m_LUTProxy->GetClientSideObject());\n if (!discFunc) {\n return;\n }\n discFunc->GetRange(range.GetData());\n pqRescaleRange dialog(pqCoreUtilities::mainWidget());\n dialog.setRange(range[0], range[1]);\n if (dialog.exec() == QDialog::Accepted) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(\n m_LUTProxy, dialog.minimum(), dialog.maximum());\n }\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onInvertClicked()\n{\n vtkSMTransferFunctionProxy::InvertTransferFunction(m_LUTProxy);\n renderViews();\n emit colorMapUpdated();\n}\n\nvoid HistogramWidget::onPresetClicked()\n{\n pqPresetDialog dialog(pqCoreUtilities::mainWidget(),\n pqPresetDialog::SHOW_NON_INDEXED_COLORS_ONLY);\n dialog.setCustomizableLoadColors(true);\n dialog.setCustomizableLoadOpacities(true);\n dialog.setCustomizableUsePresetRange(true);\n dialog.setCustomizableLoadAnnotations(false);\n connect(&dialog, SIGNAL(applyPreset(const Json::Value&)),\n SLOT(applyCurrentPreset()));\n dialog.exec();\n}\n\nvoid HistogramWidget::applyCurrentPreset()\n{\n auto dialog = qobject_cast<pqPresetDialog*>(sender());\n Q_ASSERT(dialog);\n\n vtkSMProxy* lut = m_LUTProxy;\n if (!lut) {\n return;\n }\n\n if (dialog->loadColors() || dialog->loadOpacities()) {\n vtkSMProxy* sof =\n vtkSMPropertyHelper(lut, \"ScalarOpacityFunction\", true).GetAsProxy();\n if (dialog->loadColors()) {\n vtkSMTransferFunctionProxy::ApplyPreset(lut, dialog->currentPreset(),\n !dialog->usePresetRange());\n }\n if (dialog->loadOpacities()) {\n if (sof) {\n vtkSMTransferFunctionProxy::ApplyPreset(sof, dialog->currentPreset(),\n !dialog->usePresetRange());\n } else {\n qWarning(\"Cannot load opacities since 'ScalarOpacityFunction' is not \"\n \"present.\");\n }\n }\n\n \/\/ We need to take extra care to avoid the color and opacity function ranges\n \/\/ from straying away from each other. This can happen if only one of them\n \/\/ is getting a preset and we're using the preset range.\n if (dialog->usePresetRange() &&\n (dialog->loadColors() ^ dialog->loadOpacities()) && sof) {\n double range[2];\n if (dialog->loadColors() &&\n vtkSMTransferFunctionProxy::GetRange(lut, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(sof, range);\n } else if (dialog->loadOpacities() &&\n vtkSMTransferFunctionProxy::GetRange(sof, range)) {\n vtkSMTransferFunctionProxy::RescaleTransferFunction(lut, range);\n }\n }\n renderViews();\n emit colorMapUpdated();\n }\n}\n\nvoid HistogramWidget::renderViews()\n{\n pqView* view =\n tomviz::convert<pqView*>(ActiveObjects::instance().activeView());\n if (view) {\n view->render();\n }\n}\n\nvoid HistogramWidget::setGradientOpacityChecked(bool checked)\n{\n m_gradientOpacityButton->setChecked(checked);\n emit m_gradientOpacityButton->toggled(checked);\n}\n\nvoid HistogramWidget::setGradientOpacityEnabled(bool enable)\n{\n m_gradientOpacityButton->setEnabled(enable);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <math.h>\n#include <wiring.h>\n#include \"grillpid.h\"\n\n\/\/ The temperatures are averaged over 1, 2, 4 or 8 samples\n\/\/ Set this define to log2(samples) to adjust the number of samples\n#define TEMP_AVG_COUNT_LOG2 3\n\n\/\/ The minimum fan speed (%) that activates the \"long pulse\" mode\n#define MINIMUM_FAN_SPEED 10\n\n#define TEMPPROBE_AVG_SMOOTH (1.0f\/30.0f)\n#define FANSPEED_AVG_SMOOTH (1.0f\/120.0f)\n\nvoid calcExpMovingAverage(const float smooth, float *currAverage, float newValue)\n{\n if (*currAverage == -1.0f)\n *currAverage = newValue;\n else\n {\n newValue = newValue - *currAverage;\n *currAverage = *currAverage + (smooth * newValue);\n }\n}\n \ninline void TempProbe::readTemp(void)\n{\n unsigned int analog_temp = analogRead(_pin);\n _accumulator += analog_temp;\n}\n\ninline void TempProbe::calcTemp(void)\n{\n const float Rknown = 22000.0f;\n const float Vin = 1023.0f; \n\n unsigned int Vout = _accumulator >> TEMP_AVG_COUNT_LOG2;\n _accumulator = 0; \n \n if ((Vout == 0) || (Vout >= (unsigned int)Vin))\n {\n Temperature = 0.0f;\n return;\n }\n else \n {\n float R, T;\n \/\/ If you put the fixed resistor on the Vcc side of the thermistor, use the following\n R = log(Rknown \/ ((Vin \/ (float)Vout) - 1.0f));\n \/\/ If you put the thermistor on the Vcc side of the fixed resistor use the following\n \/\/ R = log(Rknown * Vin \/ (float)Vout - Rknown);\n \n \/\/ Compute degrees K \n T = 1.0f \/ ((_steinhart->C * R * R + _steinhart->B) * R + _steinhart->A);\n \n \/\/ return degrees F\n Temperature = ((T - 273.15f) * (9.0f \/ 5.0f)) + 32.0f;\n \/\/ Sanity - anything less than 0F or greater than 999F is rejected\n if (Temperature < 0.0f || Temperature > 999.0f)\n Temperature = 0.0f;\n \n if (Temperature != 0.0f)\n {\n Temperature += Offset;\n calcExpMovingAverage(TEMPPROBE_AVG_SMOOTH, &TemperatureAvg, Temperature);\n }\n } \n}\n\n\/* Calucluate the desired fan speed using the proportional–integral-derivative (PID) controller algorithm *\/\ninline void GrillPid::calcFanSpeed(TempProbe *controlProbe)\n{\n _fanSpeed = 0;\n \n float currentTemp = controlProbe->Temperature;\n \/\/ If the pit probe is registering 0 degrees, don't jack the fan up to MAX\n if (currentTemp == 0.0f)\n return;\n \/\/ If we're in lid open mode, fan should be off\n if (LidOpenResumeCountdown != 0)\n return;\n\n float error;\n float control;\n error = _setPoint - currentTemp;\n\n \/\/ anti-windup: Make sure we only adjust the I term while\n \/\/ inside the proportional control range\n \/\/ Note that I still allow the errorSum to degrade within 1 degree even if \n \/\/ the fan is off because it is much easier for the sum to increase than\n \/\/ decrease due to the fan generally being at 0 once it passes the SetPoint\n if (!(_fanSpeed >= MaxFanSpeed && error > 0) && \n !(_fanSpeed <= 0 && error < -1.0f))\n _pidErrorSum += (error * Pid[PIDI]);\n\n \/\/ the B and P terms are in 0-100 scale, but the I and D terms are dependent on degrees \n float averageTemp = controlProbe->TemperatureAvg;\n control = Pid[PIDB] + Pid[PIDP] * (error + _pidErrorSum - (Pid[PIDD] * (currentTemp - averageTemp)));\n \n if (control >= MaxFanSpeed)\n _fanSpeed = MaxFanSpeed;\n else if (control > 0.0f)\n _fanSpeed = control;\n}\n\nvoid GrillPid::commitFanSpeed(void)\n{\n calcExpMovingAverage(FANSPEED_AVG_SMOOTH, &FanSpeedAvg, _fanSpeed);\n\n \/* For anything above MINIMUM_FAN_SPEED, do a nomal PWM write.\n For below MINIMUM_FAN_SPEED we use a \"long pulse PWM\", where \n the pulse is 10 seconds in length. For each percent we are \n emulating, run the fan for one interval. *\/\n if (_fanSpeed >= MINIMUM_FAN_SPEED)\n {\n analogWrite(_blowerPin, _fanSpeed * 255 \/ 100);\n _longPwmTmr = 0;\n }\n else\n {\n \/\/ Simple PWM, ON for first [FanSpeed] intervals then OFF \n \/\/ for the remainder of the period\n unsigned char pwmVal;\n pwmVal = (_fanSpeed > _longPwmTmr) ? 255\/MINIMUM_FAN_SPEED : 0;\n \n analogWrite(_blowerPin, pwmVal);\n \/\/ Long PWM period is 10 intervals\n if (++_longPwmTmr > 9)\n _longPwmTmr = 0;\n } \/* long PWM *\/\n}\n\nboolean GrillPid::isAnyFoodProbeActive(void)\n{\n unsigned char i;\n for (i=TEMP_FOOD1; i<TEMP_COUNT; i++)\n if (Probes[i]->Temperature != 0.0f)\n return true;\n \n return false;\n}\n \nvoid GrillPid::resetLidOpenResumeCountdown(void)\n{\n LidOpenResumeCountdown = LidOpenDuration;\n _pitTemperatureReached = false;\n}\n\nvoid GrillPid::setSetPoint(int value)\n{\n _setPoint = value;\n _pitTemperatureReached = false;\n _manualFanMode = false;\n _pidErrorSum = 0;\n}\n\nvoid GrillPid::setFanSpeed(int value)\n{\n _manualFanMode = true;\n if (value < 0)\n _fanSpeed = 0;\n else if (value > 100)\n _fanSpeed = 100;\n else\n _fanSpeed = value;\n}\n\nboolean GrillPid::doWork(void)\n{\n unsigned long m = millis();\n if ((m - _lastTempRead) < (1000 >> TEMP_AVG_COUNT_LOG2))\n return false;\n _lastTempRead = m;\n\n unsigned char i;\n for (i=0; i<TEMP_COUNT; i++)\n Probes[i]->readTemp();\n \n if (++_accumulatedCount < (1 << TEMP_AVG_COUNT_LOG2))\n return false;\n \n for (i=0; i<TEMP_COUNT; i++)\n Probes[i]->calcTemp();\n\n if (!_manualFanMode)\n {\n \/\/ Always calculate the fan speed\n \/\/ calFanSpeed() will bail if it isn't supposed to be in control\n TempProbe *probePit = Probes[TEMP_PIT];\n calcFanSpeed(probePit);\n \n int pitTemp = probePit->Temperature;\n if (pitTemp >= _setPoint)\n {\n \/\/ When we first achieve temperature, reset any P sum we accumulated during startup\n \/\/ If we actually neded that sum to achieve temperature we'll rebuild it, and it\n \/\/ prevents bouncing around above the temperature when you first start up\n if (!_pitTemperatureReached)\n {\n _pitTemperatureReached = true;\n _pidErrorSum = 0.0f;\n }\n LidOpenResumeCountdown = 0;\n }\n else if (LidOpenResumeCountdown != 0)\n {\n --LidOpenResumeCountdown;\n }\n \/\/ If the pit temperature dropped has more than [lidOpenOffset] degrees \n \/\/ after reaching temp, and the fan has not been running more than 90% of \n \/\/ the average period. note that the code assumes g_LidOpenResumeCountdown <= 0\n else if (_pitTemperatureReached && ((_setPoint - pitTemp) > (int)LidOpenOffset) && FanSpeedAvg < 90.0f)\n {\n resetLidOpenResumeCountdown();\n }\n } \/* if !manualFanMode *\/\n commitFanSpeed();\n \n _accumulatedCount = 0;\n return true;\n}\n\n\r\n<commit_msg>Fix a bug in the antiwindup code which was preventing the error sum from decaying unless the error was [0,-1] degrees Remove the 1 degree grace area. This is handled by Kb.<commit_after>#include <math.h>\n#include <wiring.h>\n#include \"grillpid.h\"\n\n\/\/ The temperatures are averaged over 1, 2, 4 or 8 samples\n\/\/ Set this define to log2(samples) to adjust the number of samples\n#define TEMP_AVG_COUNT_LOG2 3\n\n\/\/ The minimum fan speed (%) that activates the \"long pulse\" mode\n#define MINIMUM_FAN_SPEED 10\n\n#define TEMPPROBE_AVG_SMOOTH (1.0f\/30.0f)\n#define FANSPEED_AVG_SMOOTH (1.0f\/120.0f)\n\nvoid calcExpMovingAverage(const float smooth, float *currAverage, float newValue)\n{\n if (*currAverage == -1.0f)\n *currAverage = newValue;\n else\n {\n newValue = newValue - *currAverage;\n *currAverage = *currAverage + (smooth * newValue);\n }\n}\n \ninline void TempProbe::readTemp(void)\n{\n unsigned int analog_temp = analogRead(_pin);\n _accumulator += analog_temp;\n}\n\ninline void TempProbe::calcTemp(void)\n{\n const float Rknown = 22000.0f;\n const float Vin = 1023.0f; \n\n unsigned int Vout = _accumulator >> TEMP_AVG_COUNT_LOG2;\n _accumulator = 0; \n \n if ((Vout == 0) || (Vout >= (unsigned int)Vin))\n {\n Temperature = 0.0f;\n return;\n }\n else \n {\n float R, T;\n \/\/ If you put the fixed resistor on the Vcc side of the thermistor, use the following\n R = log(Rknown \/ ((Vin \/ (float)Vout) - 1.0f));\n \/\/ If you put the thermistor on the Vcc side of the fixed resistor use the following\n \/\/ R = log(Rknown * Vin \/ (float)Vout - Rknown);\n \n \/\/ Compute degrees K \n T = 1.0f \/ ((_steinhart->C * R * R + _steinhart->B) * R + _steinhart->A);\n \n \/\/ return degrees F\n Temperature = ((T - 273.15f) * (9.0f \/ 5.0f)) + 32.0f;\n \/\/ Sanity - anything less than 0F or greater than 999F is rejected\n if (Temperature < 0.0f || Temperature > 999.0f)\n Temperature = 0.0f;\n \n if (Temperature != 0.0f)\n {\n Temperature += Offset;\n calcExpMovingAverage(TEMPPROBE_AVG_SMOOTH, &TemperatureAvg, Temperature);\n }\n } \n}\n\n\/* Calucluate the desired fan speed using the proportional–integral-derivative (PID) controller algorithm *\/\ninline void GrillPid::calcFanSpeed(TempProbe *controlProbe)\n{\n _fanSpeed = 0;\n \n float currentTemp = controlProbe->Temperature;\n \/\/ If the pit probe is registering 0 degrees, don't jack the fan up to MAX\n if (currentTemp == 0.0f)\n return;\n \/\/ If we're in lid open mode, fan should be off\n if (LidOpenResumeCountdown != 0)\n return;\n\n float error;\n float control;\n error = _setPoint - currentTemp;\n\n \/\/ anti-windup: Make sure we only adjust the I term while\n \/\/ inside the proportional control range\n if ((error > 0 && _fanSpeed < MaxFanSpeed) ||\n (error < 0 && _fanSpeed > 0))\n _pidErrorSum += (error * Pid[PIDI]);\n\n \/\/ the B and P terms are in 0-100 scale, but the I and D terms are dependent on degrees \n float averageTemp = controlProbe->TemperatureAvg;\n control = Pid[PIDB] + Pid[PIDP] * (error + _pidErrorSum - (Pid[PIDD] * (currentTemp - averageTemp)));\n \n if (control >= MaxFanSpeed)\n _fanSpeed = MaxFanSpeed;\n else if (control > 0.0f)\n _fanSpeed = control;\n}\n\nvoid GrillPid::commitFanSpeed(void)\n{\n calcExpMovingAverage(FANSPEED_AVG_SMOOTH, &FanSpeedAvg, _fanSpeed);\n\n \/* For anything above MINIMUM_FAN_SPEED, do a nomal PWM write.\n For below MINIMUM_FAN_SPEED we use a \"long pulse PWM\", where \n the pulse is 10 seconds in length. For each percent we are \n emulating, run the fan for one interval. *\/\n if (_fanSpeed >= MINIMUM_FAN_SPEED)\n {\n analogWrite(_blowerPin, _fanSpeed * 255 \/ 100);\n _longPwmTmr = 0;\n }\n else\n {\n \/\/ Simple PWM, ON for first [FanSpeed] intervals then OFF \n \/\/ for the remainder of the period\n unsigned char pwmVal;\n pwmVal = (_fanSpeed > _longPwmTmr) ? 255\/MINIMUM_FAN_SPEED : 0;\n \n analogWrite(_blowerPin, pwmVal);\n \/\/ Long PWM period is 10 intervals\n if (++_longPwmTmr > 9)\n _longPwmTmr = 0;\n } \/* long PWM *\/\n}\n\nboolean GrillPid::isAnyFoodProbeActive(void)\n{\n unsigned char i;\n for (i=TEMP_FOOD1; i<TEMP_COUNT; i++)\n if (Probes[i]->Temperature != 0.0f)\n return true;\n \n return false;\n}\n \nvoid GrillPid::resetLidOpenResumeCountdown(void)\n{\n LidOpenResumeCountdown = LidOpenDuration;\n _pitTemperatureReached = false;\n}\n\nvoid GrillPid::setSetPoint(int value)\n{\n _setPoint = value;\n _pitTemperatureReached = false;\n _manualFanMode = false;\n _pidErrorSum = 0;\n}\n\nvoid GrillPid::setFanSpeed(int value)\n{\n _manualFanMode = true;\n if (value < 0)\n _fanSpeed = 0;\n else if (value > 100)\n _fanSpeed = 100;\n else\n _fanSpeed = value;\n}\n\nboolean GrillPid::doWork(void)\n{\n unsigned long m = millis();\n if ((m - _lastTempRead) < (1000 >> TEMP_AVG_COUNT_LOG2))\n return false;\n _lastTempRead = m;\n\n unsigned char i;\n for (i=0; i<TEMP_COUNT; i++)\n Probes[i]->readTemp();\n \n if (++_accumulatedCount < (1 << TEMP_AVG_COUNT_LOG2))\n return false;\n \n for (i=0; i<TEMP_COUNT; i++)\n Probes[i]->calcTemp();\n\n if (!_manualFanMode)\n {\n \/\/ Always calculate the fan speed\n \/\/ calFanSpeed() will bail if it isn't supposed to be in control\n TempProbe *probePit = Probes[TEMP_PIT];\n calcFanSpeed(probePit);\n \n int pitTemp = probePit->Temperature;\n if (pitTemp >= _setPoint)\n {\n \/\/ When we first achieve temperature, reset any P sum we accumulated during startup\n \/\/ If we actually neded that sum to achieve temperature we'll rebuild it, and it\n \/\/ prevents bouncing around above the temperature when you first start up\n if (!_pitTemperatureReached)\n {\n _pitTemperatureReached = true;\n _pidErrorSum = 0.0f;\n }\n LidOpenResumeCountdown = 0;\n }\n else if (LidOpenResumeCountdown != 0)\n {\n --LidOpenResumeCountdown;\n }\n \/\/ If the pit temperature dropped has more than [lidOpenOffset] degrees \n \/\/ after reaching temp, and the fan has not been running more than 90% of \n \/\/ the average period. note that the code assumes g_LidOpenResumeCountdown <= 0\n else if (_pitTemperatureReached && ((_setPoint - pitTemp) > (int)LidOpenOffset) && FanSpeedAvg < 90.0f)\n {\n resetLidOpenResumeCountdown();\n }\n } \/* if !manualFanMode *\/\n commitFanSpeed();\n \n _accumulatedCount = 0;\n return true;\n}\n\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This program converts a set of images to a lmdb\/leveldb by storing them\n\/\/ as Datum proto buffers.\n\/\/ Usage:\n\/\/ convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\n\/\/\n\/\/ where ROOTFOLDER is the root folder that holds all the images, and LISTFILE\n\/\/ should be a list of files as well as their labels, in the format as\n\/\/ subfolder1\/file1.JPEG 7\n\/\/ ....\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n#include <leveldb\/db.h>\n#include <leveldb\/write_batch.h>\n#include <lmdb.h>\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <fstream> \/\/ NOLINT(readability\/streams)\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n#include \"caffe\/util\/rng.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\nusing std::pair;\nusing std::string;\n\nDEFINE_bool(gray, false,\n \"When this option is on, treat images as grayscale ones\");\nDEFINE_bool(shuffle, false,\n \"Randomly shuffle the order of images and their labels\");\nDEFINE_string(backend, \"lmdb\", \"The backend for storing the result\");\nDEFINE_int32(resize_width, 0, \"Width images are resized to\");\nDEFINE_int32(resize_height, 0, \"Height images are resized to\");\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n\n#ifndef GFLAGS_GFLAGS_H_\n namespace gflags = google;\n#endif\n\n gflags::SetUsageMessage(\"Convert a set of images to the leveldb\/lmdb\\n\"\n \"format used as input for Caffe.\\n\"\n \"Usage:\\n\"\n \" convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\\n\"\n \"The ImageNet dataset for the training demo is at\\n\"\n \" http:\/\/www.image-net.org\/download-images\\n\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc != 4) {\n gflags::ShowUsageWithFlagsRestrict(argv[0], \"tools\/convert_imageset\");\n return 1;\n }\n\n bool is_color = !FLAGS_gray;\n std::ifstream infile(argv[2]);\n std::vector<std::pair<string, int> > lines;\n string filename;\n int label;\n while (infile >> filename >> label) {\n lines.push_back(std::make_pair(filename, label));\n }\n if (FLAGS_shuffle) {\n \/\/ randomly shuffle data\n LOG(INFO) << \"Shuffling data\";\n shuffle(lines.begin(), lines.end());\n }\n LOG(INFO) << \"A total of \" << lines.size() << \" images.\";\n\n const string& db_backend = FLAGS_backend;\n const char* db_path = argv[3];\n\n int resize_height = std::max<int>(0, FLAGS_resize_height);\n int resize_width = std::max<int>(0, FLAGS_resize_width);\n\n \/\/ Open new db\n \/\/ lmdb\n MDB_env *mdb_env;\n MDB_dbi mdb_dbi;\n MDB_val mdb_key, mdb_data;\n MDB_txn *mdb_txn;\n \/\/ leveldb\n leveldb::DB* db;\n leveldb::Options options;\n options.error_if_exists = true;\n options.create_if_missing = true;\n options.write_buffer_size = 268435456;\n leveldb::WriteBatch* batch = NULL;\n\n \/\/ Open db\n if (db_backend == \"leveldb\") { \/\/ leveldb\n LOG(INFO) << \"Opening leveldb \" << db_path;\n leveldb::Status status = leveldb::DB::Open(\n options, db_path, &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << db_path\n << \". Is it already existing?\";\n batch = new leveldb::WriteBatch();\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n LOG(INFO) << \"Opening lmdb \" << db_path;\n CHECK_EQ(mkdir(db_path, 0744), 0)\n << \"mkdir \" << db_path << \"failed\";\n CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS) \/\/ 1TB\n << \"mdb_env_set_mapsize failed\";\n CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)\n << \"mdb_env_open failed\";\n CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_begin failed\";\n CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n << \"mdb_open failed. Does the lmdb already exist? \";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n \/\/ Storing to db\n string root_folder(argv[1]);\n Datum datum;\n int count = 0;\n const int kMaxKeyLength = 256;\n char key_cstr[kMaxKeyLength];\n int data_size;\n bool data_size_initialized = false;\n\n for (int line_id = 0; line_id < lines.size(); ++line_id) {\n if (!ReadImageToDatum(root_folder + lines[line_id].first,\n lines[line_id].second, resize_height, resize_width, is_color, &datum)) {\n continue;\n }\n if (!data_size_initialized) {\n data_size = datum.channels() * datum.height() * datum.width();\n data_size_initialized = true;\n } else {\n const string& data = datum.data();\n CHECK_EQ(data.size(), data_size) << \"Incorrect data field size \"\n << data.size();\n }\n \/\/ sequential\n snprintf(key_cstr, kMaxKeyLength, \"%08d_%s\", line_id,\n lines[line_id].first.c_str());\n string value;\n datum.SerializeToString(&value);\n string keystr(key_cstr);\n\n \/\/ Put in db\n if (db_backend == \"leveldb\") { \/\/ leveldb\n batch->Put(keystr, value);\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n mdb_data.mv_size = value.size();\n mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);\n mdb_key.mv_size = keystr.size();\n mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);\n CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)\n << \"mdb_put failed\";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n if (++count % 1000 == 0) {\n \/\/ Commit txn\n if (db_backend == \"leveldb\") { \/\/ leveldb\n db->Write(leveldb::WriteOptions(), batch);\n delete batch;\n batch = new leveldb::WriteBatch();\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_commit failed\";\n CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_begin failed\";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n \/\/ write the last batch\n if (count % 1000 != 0) {\n if (db_backend == \"leveldb\") { \/\/ leveldb\n db->Write(leveldb::WriteOptions(), batch);\n delete batch;\n delete db;\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << \"mdb_txn_commit failed\";\n mdb_close(mdb_env, mdb_dbi);\n mdb_env_close(mdb_env);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n return 0;\n}\n<commit_msg>Add flag check_size=false to convert_imageset<commit_after>\/\/ This program converts a set of images to a lmdb\/leveldb by storing them\n\/\/ as Datum proto buffers.\n\/\/ Usage:\n\/\/ convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\n\/\/\n\/\/ where ROOTFOLDER is the root folder that holds all the images, and LISTFILE\n\/\/ should be a list of files as well as their labels, in the format as\n\/\/ subfolder1\/file1.JPEG 7\n\/\/ ....\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n#include <leveldb\/db.h>\n#include <leveldb\/write_batch.h>\n#include <lmdb.h>\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <fstream> \/\/ NOLINT(readability\/streams)\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n#include \"caffe\/util\/rng.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\nusing std::pair;\nusing std::string;\n\nDEFINE_bool(gray, false,\n \"When this option is on, treat images as grayscale ones\");\nDEFINE_bool(shuffle, false,\n \"Randomly shuffle the order of images and their labels\");\nDEFINE_string(backend, \"lmdb\", \"The backend for storing the result\");\nDEFINE_int32(resize_width, 0, \"Width images are resized to\");\nDEFINE_int32(resize_height, 0, \"Height images are resized to\");\nDEFINE_bool(check_size, false,\n \"When this option is on, check that all the datum have the same size\");\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n\n#ifndef GFLAGS_GFLAGS_H_\n namespace gflags = google;\n#endif\n\n gflags::SetUsageMessage(\"Convert a set of images to the leveldb\/lmdb\\n\"\n \"format used as input for Caffe.\\n\"\n \"Usage:\\n\"\n \" convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\\n\"\n \"The ImageNet dataset for the training demo is at\\n\"\n \" http:\/\/www.image-net.org\/download-images\\n\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc != 4) {\n gflags::ShowUsageWithFlagsRestrict(argv[0], \"tools\/convert_imageset\");\n return 1;\n }\n\n bool is_color = !FLAGS_gray;\n bool check_size = FLAGS_check_size;\n std::ifstream infile(argv[2]);\n std::vector<std::pair<string, int> > lines;\n string filename;\n int label;\n while (infile >> filename >> label) {\n lines.push_back(std::make_pair(filename, label));\n }\n if (FLAGS_shuffle) {\n \/\/ randomly shuffle data\n LOG(INFO) << \"Shuffling data\";\n shuffle(lines.begin(), lines.end());\n }\n LOG(INFO) << \"A total of \" << lines.size() << \" images.\";\n\n const string& db_backend = FLAGS_backend;\n const char* db_path = argv[3];\n\n int resize_height = std::max<int>(0, FLAGS_resize_height);\n int resize_width = std::max<int>(0, FLAGS_resize_width);\n\n \/\/ Open new db\n \/\/ lmdb\n MDB_env *mdb_env;\n MDB_dbi mdb_dbi;\n MDB_val mdb_key, mdb_data;\n MDB_txn *mdb_txn;\n \/\/ leveldb\n leveldb::DB* db;\n leveldb::Options options;\n options.error_if_exists = true;\n options.create_if_missing = true;\n options.write_buffer_size = 268435456;\n leveldb::WriteBatch* batch = NULL;\n\n \/\/ Open db\n if (db_backend == \"leveldb\") { \/\/ leveldb\n LOG(INFO) << \"Opening leveldb \" << db_path;\n leveldb::Status status = leveldb::DB::Open(\n options, db_path, &db);\n CHECK(status.ok()) << \"Failed to open leveldb \" << db_path\n << \". Is it already existing?\";\n batch = new leveldb::WriteBatch();\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n LOG(INFO) << \"Opening lmdb \" << db_path;\n CHECK_EQ(mkdir(db_path, 0744), 0)\n << \"mkdir \" << db_path << \"failed\";\n CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS) \/\/ 1TB\n << \"mdb_env_set_mapsize failed\";\n CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)\n << \"mdb_env_open failed\";\n CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_begin failed\";\n CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n << \"mdb_open failed. Does the lmdb already exist? \";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n \/\/ Storing to db\n string root_folder(argv[1]);\n Datum datum;\n int count = 0;\n const int kMaxKeyLength = 256;\n char key_cstr[kMaxKeyLength];\n int data_size;\n bool data_size_initialized = false;\n\n for (int line_id = 0; line_id < lines.size(); ++line_id) {\n if (!ReadImageToDatum(root_folder + lines[line_id].first,\n lines[line_id].second, resize_height, resize_width, is_color, &datum)) {\n continue;\n }\n if (check_size) {\n if (!data_size_initialized) {\n data_size = datum.channels() * datum.height() * datum.width();\n data_size_initialized = true;\n } else {\n const string& data = datum.data();\n CHECK_EQ(data.size(), data_size) << \"Incorrect data field size \"\n << data.size();\n }\n }\n \/\/ sequential\n snprintf(key_cstr, kMaxKeyLength, \"%08d_%s\", line_id,\n lines[line_id].first.c_str());\n string value;\n datum.SerializeToString(&value);\n string keystr(key_cstr);\n\n \/\/ Put in db\n if (db_backend == \"leveldb\") { \/\/ leveldb\n batch->Put(keystr, value);\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n mdb_data.mv_size = value.size();\n mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);\n mdb_key.mv_size = keystr.size();\n mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);\n CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)\n << \"mdb_put failed\";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n\n if (++count % 1000 == 0) {\n \/\/ Commit txn\n if (db_backend == \"leveldb\") { \/\/ leveldb\n db->Write(leveldb::WriteOptions(), batch);\n delete batch;\n batch = new leveldb::WriteBatch();\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_commit failed\";\n CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)\n << \"mdb_txn_begin failed\";\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n \/\/ write the last batch\n if (count % 1000 != 0) {\n if (db_backend == \"leveldb\") { \/\/ leveldb\n db->Write(leveldb::WriteOptions(), batch);\n delete batch;\n delete db;\n } else if (db_backend == \"lmdb\") { \/\/ lmdb\n CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << \"mdb_txn_commit failed\";\n mdb_close(mdb_env, mdb_dbi);\n mdb_env_close(mdb_env);\n } else {\n LOG(FATAL) << \"Unknown db backend \" << db_backend;\n }\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * DISTRHO SoulForce, a DPF'ied SoulForce.\n * Copyright (c) 2006 Niall Moody\n * Copyright (C) 2015 Filipe Coelho <falktx@falktx.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef DISTRHO_UI_MVERB_HPP_INCLUDED\n#define DISTRHO_UI_MVERB_HPP_INCLUDED\n\n#include \"DistrhoUI.hpp\"\n\n#include \"ImageKnob.hpp\"\n#include \"ImageSlider.hpp\"\n#include \"ImageSwitch.hpp\"\n\n#include \"DistrhoArtworkSoulForce.hpp\"\n\nusing DGL::Image;\nusing DGL::ImageKnob;\nusing DGL::ImageSwitch;\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\nclass DistrhoUISoulForce : public UI,\n public ImageKnob::Callback,\n public ImageSwitch::Callback\n{\npublic:\n DistrhoUISoulForce();\n\nprotected:\n \/\/ -------------------------------------------------------------------\n \/\/ DSP Callbacks\n\n void d_parameterChanged(uint32_t index, float value) override;\n void d_programChanged(uint32_t index) override;\n\n \/\/ -------------------------------------------------------------------\n \/\/ Widget Callbacks\n\n void imageKnobDragStarted(ImageKnob* knob) override;\n void imageKnobDragFinished(ImageKnob* knob) override;\n void imageKnobValueChanged(ImageKnob* knob, float value) override;\n\n void imageSwitchClicked(ImageSwitch* imageButton, bool down) override;\n\n void onDisplay() override;\n\nprivate:\n Image fImgBackground, fImgLedOff, fImgLedOn;\n ScopedPointer<ImageKnob> fKnobShape, fKnobFBack;\n ScopedPointer<ImageSwitch> fSwitchSource, fSwitchFoot;\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(DistrhoUISoulForce)\n};\n\n\/\/ -----------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n\n#endif \/\/ DISTRHO_UI_MVERB_HPP_INCLUDED\n<commit_msg>Remove useless include<commit_after>\/*\n * DISTRHO SoulForce, a DPF'ied SoulForce.\n * Copyright (c) 2006 Niall Moody\n * Copyright (C) 2015 Filipe Coelho <falktx@falktx.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef DISTRHO_UI_MVERB_HPP_INCLUDED\n#define DISTRHO_UI_MVERB_HPP_INCLUDED\n\n#include \"DistrhoUI.hpp\"\n\n#include \"ImageKnob.hpp\"\n#include \"ImageSwitch.hpp\"\n\n#include \"DistrhoArtworkSoulForce.hpp\"\n\nusing DGL::Image;\nusing DGL::ImageKnob;\nusing DGL::ImageSwitch;\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\nclass DistrhoUISoulForce : public UI,\n public ImageKnob::Callback,\n public ImageSwitch::Callback\n{\npublic:\n DistrhoUISoulForce();\n\nprotected:\n \/\/ -------------------------------------------------------------------\n \/\/ DSP Callbacks\n\n void d_parameterChanged(uint32_t index, float value) override;\n void d_programChanged(uint32_t index) override;\n\n \/\/ -------------------------------------------------------------------\n \/\/ Widget Callbacks\n\n void imageKnobDragStarted(ImageKnob* knob) override;\n void imageKnobDragFinished(ImageKnob* knob) override;\n void imageKnobValueChanged(ImageKnob* knob, float value) override;\n\n void imageSwitchClicked(ImageSwitch* imageButton, bool down) override;\n\n void onDisplay() override;\n\nprivate:\n Image fImgBackground, fImgLedOff, fImgLedOn;\n ScopedPointer<ImageKnob> fKnobShape, fKnobFBack;\n ScopedPointer<ImageSwitch> fSwitchSource, fSwitchFoot;\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(DistrhoUISoulForce)\n};\n\n\/\/ -----------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n\n#endif \/\/ DISTRHO_UI_MVERB_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/\n\/**\n * @file makeTensorStream.cpp\n * @brief Tool to import datasets\n *\n * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)\n *\/\n\n#include <iostream>\n#include <fstream>\n\n#include <cn24.h>\n\nint main ( int argc, char** argv ) {\n if ( argc < 8 ) {\n LOGERROR << \"USAGE: \" << argv[0] << \" <dataset config file> <image list file> <image directory> <label list file> <label directory> <output file> <true\/false for direct RGB of labels>\";\n LOGEND;\n return -1;\n }\n\n \/\/ Capture command line arguments\n std::string directRGB ( argv[7] );\n std::string output_fname ( argv[6] );\n std::string label_directory ( argv[5] );\n std::string label_list_fname ( argv[4] );\n std::string image_directory ( argv[3] );\n std::string image_list_fname ( argv[2] );\n std::string dataset_config_fname ( argv[1] );\n\n if(image_directory.back() != '\/')\n image_directory += \"\/\";\n\n if(label_directory.back() != '\/')\n label_directory += \"\/\";\n\n \/\/ Open dataset configuration files\n std::ifstream dataset_config_file ( dataset_config_fname,std::ios::in );\n\n if ( !dataset_config_file.good() ) {\n FATAL ( \"Cannot open dataset configuration file!\" );\n }\n\n LOGINFO << \"Loading dataset\";\n \/\/ Load dataset\n Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration ( dataset_config_file, true );\n\n unsigned int number_of_classes = dataset->GetClasses();\n \/\/ arrays to store class colors in an easy to index way\n Conv::datum* cr = new Conv::datum[number_of_classes];\n Conv::datum* cg = new Conv::datum[number_of_classes];\n Conv::datum* cb = new Conv::datum[number_of_classes];\n\n for ( unsigned int c = 0; c < number_of_classes; c++ ) {\n const unsigned int class_color = dataset->GetClassColors() [c];\n cr[c] = DATUM_FROM_UCHAR ( ( class_color >> 16 ) & 0xFF );\n cg[c] = DATUM_FROM_UCHAR ( ( class_color >> 8 ) & 0xFF );\n cb[c] = DATUM_FROM_UCHAR ( class_color & 0xFF );\n }\n\n \/\/ Open file lists\n std::ifstream image_list_file ( image_list_fname, std::ios::in );\n\n if ( !image_list_file.good() ) {\n FATAL ( \"Cannot open image list file!\" );\n }\n\n std::ifstream label_list_file ( label_list_fname, std::ios::in );\n\n if ( !label_list_file.good() ) {\n FATAL ( \"Cannot open label list file!\" );\n }\n\n \/\/ Open output file\n std::ofstream output_file ( output_fname, std::ios::out | std::ios::binary );\n\n if ( !output_file.good() ) {\n FATAL ( \"Cannot open output file!\" );\n }\n\n \/\/ Iterate through lists of images and labels\n while ( !image_list_file.eof() ) {\n std::string image_fname;\n std::string label_fname;\n std::getline ( image_list_file, image_fname );\n std::getline ( label_list_file, label_fname );\n\n if ( image_fname.length() < 5 || label_fname.length() < 5 )\n break;\n\n LOGINFO << \"Importing files \" << image_fname << \" and \" << label_fname << \"...\";\n Conv::Tensor image_tensor ( image_directory + image_fname );\n Conv::Tensor label_rgb_tensor ( label_directory + label_fname );\n\n if ( image_tensor.width() != label_rgb_tensor.width() ||\n image_tensor.height() != label_rgb_tensor.height() ) {\n LOGERROR << \"Dimensions don't match, skipping file!\";\n continue;\n }\n \n int label_tensor_width = number_of_classes; \n if(directRGB == \"true\") {\n label_tensor_width = 3;\n }\n\t\n Conv::Tensor label_tensor ( 1, label_rgb_tensor.width(), label_rgb_tensor.height(), label_tensor_width);\n\n if(directRGB == \"true\") {\n \/\/ no classes - interpret the label tensor input as the output (no class\/color mapping)\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) { \n *label_tensor.data_ptr ( x,y,0,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n *label_tensor.data_ptr ( x,y,1,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n *label_tensor.data_ptr ( x,y,2,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n }\n }\n } else if(number_of_classes == 1) {\n \/\/ 1 class - convert RGB images into multi-channel label tensors\n const unsigned int foreground_color = dataset->GetClassColors() [0];\n const Conv::datum fr = DATUM_FROM_UCHAR ( ( foreground_color >> 16 ) & 0xFF ),\n fg = DATUM_FROM_UCHAR ( ( foreground_color >> 8 ) & 0xFF ),\n fb = DATUM_FROM_UCHAR ( foreground_color & 0xFF );\n\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) {\n Conv::datum lr, lg, lb;\n\n if ( label_rgb_tensor.maps() == 3 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n lb = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n } else if ( label_rgb_tensor.maps() == 1 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = lr;\n lb = lr;\n } else {\n FATAL ( \"Unsupported input channel count!\" );\n }\n\n const Conv::datum class1_diff = std::sqrt ( ( lr - fr ) * ( lr - fr )\n + ( lg - fg ) * ( lg - fg )\n + ( lb - fb ) * ( lb - fb ) ) \/ std::sqrt ( 3.0 );\n const Conv::datum val = 1.0 - 2.0 * class1_diff;\n *label_tensor.data_ptr ( x,y,0,0 ) = val;\n }\n }\n } else {\n \/\/ any number of other classes \n label_tensor.Clear ( 0.0 );\n\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) {\n Conv::datum lr, lg, lb;\n\n if ( label_rgb_tensor.maps() == 3 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n lb = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n } else if ( label_rgb_tensor.maps() == 1 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = lr;\n lb = lr;\n } else {\n FATAL ( \"Unsupported input channel count!\" );\n }\n\n for ( unsigned int c = 0; c <number_of_classes; c++ ) {\n if(lr == cr[c] && lg == cg[c] && lb == cb[c])\n *label_tensor.data_ptr ( x,y,c,0 ) = 1.0;\n }\n }\n }\n } \/\/ end if\n\n image_tensor.Serialize ( output_file );\n label_tensor.Serialize ( output_file );\n }\n\n LOGEND;\n}\n<commit_msg>makeTensorStream: Changed default debug level<commit_after>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/\n\/**\n * @file makeTensorStream.cpp\n * @brief Tool to import datasets\n *\n * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)\n *\/\n\n#include <iostream>\n#include <fstream>\n\n#include <cn24.h>\n\nint main ( int argc, char** argv ) {\n if ( argc < 8 ) {\n LOGERROR << \"USAGE: \" << argv[0] << \" <dataset config file> <image list file> <image directory> <label list file> <label directory> <output file> <true\/false for direct RGB of labels>\";\n LOGEND;\n return -1;\n }\n \n Conv::System::Init(3);\n\n \/\/ Capture command line arguments\n std::string directRGB ( argv[7] );\n std::string output_fname ( argv[6] );\n std::string label_directory ( argv[5] );\n std::string label_list_fname ( argv[4] );\n std::string image_directory ( argv[3] );\n std::string image_list_fname ( argv[2] );\n std::string dataset_config_fname ( argv[1] );\n\n if(image_directory.back() != '\/')\n image_directory += \"\/\";\n\n if(label_directory.back() != '\/')\n label_directory += \"\/\";\n\n \/\/ Open dataset configuration files\n std::ifstream dataset_config_file ( dataset_config_fname,std::ios::in );\n\n if ( !dataset_config_file.good() ) {\n FATAL ( \"Cannot open dataset configuration file!\" );\n }\n\n LOGINFO << \"Loading dataset\";\n \/\/ Load dataset\n Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration ( dataset_config_file, true );\n\n unsigned int number_of_classes = dataset->GetClasses();\n \/\/ arrays to store class colors in an easy to index way\n Conv::datum* cr = new Conv::datum[number_of_classes];\n Conv::datum* cg = new Conv::datum[number_of_classes];\n Conv::datum* cb = new Conv::datum[number_of_classes];\n\n for ( unsigned int c = 0; c < number_of_classes; c++ ) {\n const unsigned int class_color = dataset->GetClassColors() [c];\n cr[c] = DATUM_FROM_UCHAR ( ( class_color >> 16 ) & 0xFF );\n cg[c] = DATUM_FROM_UCHAR ( ( class_color >> 8 ) & 0xFF );\n cb[c] = DATUM_FROM_UCHAR ( class_color & 0xFF );\n }\n\n \/\/ Open file lists\n std::ifstream image_list_file ( image_list_fname, std::ios::in );\n\n if ( !image_list_file.good() ) {\n FATAL ( \"Cannot open image list file!\" );\n }\n\n std::ifstream label_list_file ( label_list_fname, std::ios::in );\n\n if ( !label_list_file.good() ) {\n FATAL ( \"Cannot open label list file!\" );\n }\n\n \/\/ Open output file\n std::ofstream output_file ( output_fname, std::ios::out | std::ios::binary );\n\n if ( !output_file.good() ) {\n FATAL ( \"Cannot open output file!\" );\n }\n\n \/\/ Iterate through lists of images and labels\n while ( !image_list_file.eof() ) {\n std::string image_fname;\n std::string label_fname;\n std::getline ( image_list_file, image_fname );\n std::getline ( label_list_file, label_fname );\n\n if ( image_fname.length() < 5 || label_fname.length() < 5 )\n break;\n\n LOGINFO << \"Importing files \" << image_fname << \" and \" << label_fname << \"...\";\n Conv::Tensor image_tensor ( image_directory + image_fname );\n Conv::Tensor label_rgb_tensor ( label_directory + label_fname );\n\n if ( image_tensor.width() != label_rgb_tensor.width() ||\n image_tensor.height() != label_rgb_tensor.height() ) {\n LOGERROR << \"Dimensions don't match, skipping file!\";\n continue;\n }\n \n int label_tensor_width = number_of_classes; \n if(directRGB == \"true\") {\n label_tensor_width = 3;\n }\n\t\n Conv::Tensor label_tensor ( 1, label_rgb_tensor.width(), label_rgb_tensor.height(), label_tensor_width);\n\n if(directRGB == \"true\") {\n \/\/ no classes - interpret the label tensor input as the output (no class\/color mapping)\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) { \n *label_tensor.data_ptr ( x,y,0,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n *label_tensor.data_ptr ( x,y,1,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n *label_tensor.data_ptr ( x,y,2,0 ) = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n }\n }\n } else if(number_of_classes == 1) {\n \/\/ 1 class - convert RGB images into multi-channel label tensors\n const unsigned int foreground_color = dataset->GetClassColors() [0];\n const Conv::datum fr = DATUM_FROM_UCHAR ( ( foreground_color >> 16 ) & 0xFF ),\n fg = DATUM_FROM_UCHAR ( ( foreground_color >> 8 ) & 0xFF ),\n fb = DATUM_FROM_UCHAR ( foreground_color & 0xFF );\n\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) {\n Conv::datum lr, lg, lb;\n\n if ( label_rgb_tensor.maps() == 3 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n lb = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n } else if ( label_rgb_tensor.maps() == 1 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = lr;\n lb = lr;\n } else {\n FATAL ( \"Unsupported input channel count!\" );\n }\n\n const Conv::datum class1_diff = std::sqrt ( ( lr - fr ) * ( lr - fr )\n + ( lg - fg ) * ( lg - fg )\n + ( lb - fb ) * ( lb - fb ) ) \/ std::sqrt ( 3.0 );\n const Conv::datum val = 1.0 - 2.0 * class1_diff;\n *label_tensor.data_ptr ( x,y,0,0 ) = val;\n }\n }\n } else {\n \/\/ any number of other classes \n label_tensor.Clear ( 0.0 );\n\n for ( unsigned int y = 0; y < label_rgb_tensor.height(); y++ ) {\n for ( unsigned int x = 0; x < label_rgb_tensor.width(); x++ ) {\n Conv::datum lr, lg, lb;\n\n if ( label_rgb_tensor.maps() == 3 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = *label_rgb_tensor.data_ptr_const ( x,y,1,0 );\n lb = *label_rgb_tensor.data_ptr_const ( x,y,2,0 );\n } else if ( label_rgb_tensor.maps() == 1 ) {\n lr = *label_rgb_tensor.data_ptr_const ( x,y,0,0 );\n lg = lr;\n lb = lr;\n } else {\n FATAL ( \"Unsupported input channel count!\" );\n }\n\n for ( unsigned int c = 0; c <number_of_classes; c++ ) {\n if(lr == cr[c] && lg == cg[c] && lb == cb[c])\n *label_tensor.data_ptr ( x,y,c,0 ) = 1.0;\n }\n }\n }\n } \/\/ end if\n\n image_tensor.Serialize ( output_file );\n label_tensor.Serialize ( output_file );\n }\n\n LOGEND;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n#include <vector>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\tasio::error_code ec;\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tstd::cout << \"address: \" << i->interface_address << std::endl\n\t\t\t<< \" mask: \" << i->netmask << std::endl\n\t\t\t<< \" flags: \";\n\t\tif (is_multicast(i->interface_address)) std::cout << \"multicast \";\n\t\tif (is_local(i->interface_address)) std::cout << \"local \";\n\t\tif (is_loopback(i->interface_address)) std::cout << \"loopback \";\n\t\tstd::cout << std::endl;\n\t}\n\n\taddress local = guess_local_address(ios);\n\n\tstd::cout << \"Local address: \" << local << std::endl;\n}\n\n<commit_msg>prints out default gateway in example<commit_after>#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n#include <vector>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\tasio::error_code ec;\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tstd::cout << \"address: \" << i->interface_address << std::endl\n\t\t\t<< \" mask: \" << i->netmask << std::endl\n\t\t\t<< \" flags: \";\n\t\tif (is_multicast(i->interface_address)) std::cout << \"multicast \";\n\t\tif (is_local(i->interface_address)) std::cout << \"local \";\n\t\tif (is_loopback(i->interface_address)) std::cout << \"loopback \";\n\t\tstd::cout << std::endl;\n\t}\n\n\taddress local = guess_local_address(ios);\n\tstd::cout << \"Local address: \" << local << std::endl;\n\n\taddress gateway = get_default_gateway(ios, local, ec);\n\tstd::cout << \"Default gateway: \" << gateway << std::endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"accountsCache.h\"\r\n#include \"utils.h\"\r\n#include <QDir>\r\n#include <QTextStream>\r\n\r\naccountsCache::accountsCache(QObject *parent) :\r\n QObject(parent)\r\n{\r\n}\r\n\r\nQStringList accountsCache::getBareJids()\r\n{\r\n QStringList list;\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n list << element.firstChildElement(\"bareJid\").text();\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n return list;\r\n}\r\n\r\nQString accountsCache::getPassword(const QString& bareJid)\r\n{\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n if(element.firstChildElement(\"bareJid\").text() == bareJid)\r\n {\r\n return element.firstChildElement(\"password\").text();\r\n }\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n return \"\";\r\n}\r\n\r\nvoid accountsCache::addAccount(const QString& bareJid, const QString& passwd)\r\n{\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n if(element.firstChildElement(\"bareJid\").text() == bareJid)\r\n {\r\n element.firstChildElement(\"password\").setNodeValue(passwd);\r\n return;\r\n }\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n QDomElement newElement = m_accountsDocument.createElement(\"account\");\r\n\r\n QDomElement newElementBareJid = m_accountsDocument.createElement(\"bareJid\");\r\n newElementBareJid.appendChild(m_accountsDocument.createTextNode(bareJid));\r\n newElement.appendChild(newElementBareJid);\r\n\r\n QDomElement newElementPasswd = m_accountsDocument.createElement(\"password\");\r\n newElementPasswd.appendChild(m_accountsDocument.createTextNode(passwd));\r\n newElement.appendChild(newElementPasswd);\r\n\r\n m_accountsDocument.appendChild(newElement);\r\n\r\n saveToFile();\r\n}\r\n\r\nvoid accountsCache::loadFromFile()\r\n{\r\n}\r\n\r\nvoid accountsCache::saveToFile()\r\n{\r\n QDir dir;\r\n if(!dir.exists(getSettingsDir()))\r\n dir.mkpath(getSettingsDir());\r\n\r\n QString fileAccounts = getSettingsDir() + \"accounts.xml\";\r\n QFile file(fileAccounts);\r\n if(file.open(QIODevice::ReadWrite))\r\n {\r\n QTextStream tstream(&file);\r\n m_accountsDocument.save(tstream, 2);\r\n file.close();\r\n }\r\n}\r\n<commit_msg>impl saveToFile<commit_after>#include \"accountsCache.h\"\r\n#include \"utils.h\"\r\n#include <QDir>\r\n#include <QTextStream>\r\n\r\naccountsCache::accountsCache(QObject *parent) :\r\n QObject(parent)\r\n{\r\n}\r\n\r\nQStringList accountsCache::getBareJids()\r\n{\r\n QStringList list;\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n list << element.firstChildElement(\"bareJid\").text();\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n return list;\r\n}\r\n\r\nQString accountsCache::getPassword(const QString& bareJid)\r\n{\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n if(element.firstChildElement(\"bareJid\").text() == bareJid)\r\n {\r\n return element.firstChildElement(\"password\").text();\r\n }\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n return \"\";\r\n}\r\n\r\nvoid accountsCache::addAccount(const QString& bareJid, const QString& passwd)\r\n{\r\n QDomElement element = m_accountsDocument.firstChildElement(\"account\");\r\n while(!element.isNull())\r\n {\r\n if(element.firstChildElement(\"bareJid\").text() == bareJid)\r\n {\r\n element.firstChildElement(\"password\").setNodeValue(passwd);\r\n return;\r\n }\r\n element = element.nextSiblingElement(\"account\");\r\n }\r\n\r\n QDomElement newElement = m_accountsDocument.createElement(\"account\");\r\n\r\n QDomElement newElementBareJid = m_accountsDocument.createElement(\"bareJid\");\r\n newElementBareJid.appendChild(m_accountsDocument.createTextNode(bareJid));\r\n newElement.appendChild(newElementBareJid);\r\n\r\n QDomElement newElementPasswd = m_accountsDocument.createElement(\"password\");\r\n newElementPasswd.appendChild(m_accountsDocument.createTextNode(passwd));\r\n newElement.appendChild(newElementPasswd);\r\n\r\n m_accountsDocument.appendChild(newElement);\r\n\r\n saveToFile();\r\n}\r\n\r\nvoid accountsCache::loadFromFile()\r\n{\r\n QDir dirSettings(getSettingsDir());\r\n if(dirSettings.exists())\r\n {\r\n QFile file(getSettingsDir()+ \"accounts.xml\");\r\n if(file.open(QIODevice::ReadOnly))\r\n {\r\n QDomDocument doc;\r\n doc.setContent(&file, true);\r\n }\r\n }\r\n}\r\n\r\nvoid accountsCache::saveToFile()\r\n{\r\n QDir dir;\r\n if(!dir.exists(getSettingsDir()))\r\n dir.mkpath(getSettingsDir());\r\n\r\n QString fileAccounts = getSettingsDir() + \"accounts.xml\";\r\n QFile file(fileAccounts);\r\n if(file.open(QIODevice::ReadWrite))\r\n {\r\n QTextStream tstream(&file);\r\n m_accountsDocument.save(tstream, 2);\r\n file.close();\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/ts\/ts.hpp>\n#include <libcomparator.hpp>\n\n\nclass IterateH : public cvtest::BaseTest\n{\npublic:\n IterateH(){}\nprotected:\n \n void run(int) {\n cv::Mat_<TYPE> mat(3, 3 * channels, 100);\n \/\/ cv::Vec<TYPE, channels> subPix;\n \/\/ subPix = static_cast<cv::Vec<TYPE, channels>>(cv::Matx<TYPE, channels, 1>::zeros());\n \/\/ mat.at<cv::Vec<TYPE, channels>>(cv::Point(3,3)) = subPix;\n mat(1,3)=0; mat(1,4)=0; mat(1,5)=0;\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n IterateProcess<TYPE> iterateProcess(mat, lightThreshold, colorThreshold, balance);\n\n std::vector<IndexTransition> result = iterateProcess.iterate_H();\n\n ASSERT_EQ(result.size(), 2);\n auto expected = IndexTransition{12, leftToRight};\n compareIndexTransition(result[0], expected);\n expected = IndexTransition{12, rightToLeft};\n compareIndexTransition(result[1], expected);\n\n \/\/ ASSERT_EQ(result[0], IndexTransition{12, rightToLeft});\n\n }\n\n void compareIndexTransition(IndexTransition& iT1, IndexTransition& iT2)\n {\n ASSERT_EQ(iT1.index, iT2.index);\n ASSERT_EQ(iT1.transition, iT2.transition);\n }\n};\nTEST(ComparatorLibSuite, IterateH) {\n IterateH iterateH;\n iterateH.safe_run();\n}\n\nclass IterateV : public cvtest::BaseTest\n{\npublic:\n IterateV(){}\nprotected:\n \n void run(int) {\n cv::Mat_<TYPE> mat(3, 3 * channels, 100);\n \/\/ cv::Vec<TYPE, channels> subPix;\n \/\/ subPix = static_cast<cv::Vec<TYPE, channels>>(cv::Matx<TYPE, channels, 1>::zeros());\n \/\/ mat.at<cv::Vec<TYPE, channels>>(cv::Point(3,3)) = subPix;\n mat(1,3)=0; mat(1,4)=0; mat(1,5)=0;\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n IterateProcess<TYPE> iterateProcess(mat, lightThreshold, colorThreshold, balance);\n\n std::vector<IndexTransition> result = iterateProcess.iterate_V();\n\n ASSERT_EQ(result.size(), 2);\n auto expected = IndexTransition{12, upToDown};\n compareIndexTransition(result[0], expected);\n expected = IndexTransition{12, downToUp};\n compareIndexTransition(result[1], expected);\n\n \/\/ ASSERT_EQ(result[0], IndexTransition{12, rightToLeft});\n\n }\n\n void compareIndexTransition(IndexTransition& iT1, IndexTransition& iT2)\n {\n ASSERT_EQ(iT1.index, iT2.index);\n ASSERT_EQ(iT1.transition, iT2.transition);\n }\n};\nTEST(ComparatorLibSuite, IterateV) {\n IterateV IterateV;\n IterateV.safe_run();\n}\n\n\n\nclass Fclassifier : public cvtest::BaseTest\n{\npublic:\n Fclassifier(){}\nprotected:\n \n void run(int) {\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {3, 3, 3};\n \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::no, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 3);\n std::fill( pix1, pix1 + channels, 10);\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::backward, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 10);\n std::fill( pix1, pix1 + channels, 3);\n classifier.copy_pix(pix0, pix1);\n if (Transition::forward != classifier.f_classifier())\n ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n \/\/check that all values are between 1 and 1 (and not Nan)\n \/\/ if (0 != cvtest::check(, 1, 1, 0) )\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);\n\n }\n};\nTEST(ComparatorLibSuite, f_classifier) {\n Fclassifier fclassifeir;\n fclassifeir.safe_run();\n}\n\n\nclass FclassifierBT : public cvtest::BaseTest\n{\npublic:\n FclassifierBT(){}\nprotected:\n \n void run(int) {\n ts->set_failed_test_info(cvtest::TS::OK);\n\n double balance[] = {2.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 4.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {3, 3, 3};\n \n classifier.copy_pix(pix0, pix1);\n if (Transition::no != classifier.f_classifier())\n ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n\n std::fill( pix0, pix0 + channels, 6);\n std::fill( pix1, pix1 + channels, 10);\n pix0[0] = 4; \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::backward, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 10);\n std::fill( pix1, pix1 + channels, 3);\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::no, classifier.f_classifier());\n\n \/\/ std::fill( pix0, pix0 + channels, 10);\n \/\/ std::fill( pix1, pix1 + channels, 3);\n \/\/ pix0[0] = 5;\n \/\/ classifier.copy_pix(pix0, pix1);\n \/\/ if (Transition::backward != classifier.f_classifier())\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n \/\/check that all values are between 1 and 1 (and not Nan)\n \/\/ if (0 != cvtest::check(, 1, 1, 0) )\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);\n\n }\n};\nTEST(ComparatorLibSuite, f_classifierbt) {\n FclassifierBT fclassifierbt;\n fclassifierbt.safe_run();\n}\n\n\n#ifdef TEST_PRIVATE_PART\n\nclass LightAndColor : public cvtest::BaseTest\n{\npublic:\n LightAndColor(){}\nprotected:\n \n void run(int) {\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {10, 10, 10};\n \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(21, classifier.light_distance());\n ASSERT_EQ(0, classifier.color_distance());\n \n pix1[0] = 13;\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(24, classifier.light_distance());\n ASSERT_EQ(6, classifier.color_distance());\n }\n};\nTEST(ComparatorPrivateLibSuite, PrivatePartClassifier) {\n LightAndColor lightAndColor;\n lightAndColor.safe_run();\n}\n#endif\n\n\/\/ TEST(ComparatorLibSuite, ATestThatFails) {\n\/\/ bool mybool = false;\n\/\/ ASSERT_TRUE(mybool);\n\/\/ }\n<commit_msg>basic test finished \tmodified: ..\/test\/comparatortest.cpp<commit_after>#include <opencv2\/ts\/ts.hpp>\n#include <libcomparator.hpp>\n\nclass IterateTestMethods : public cvtest::BaseTest\n{\npublic:\n IterateTestMethods(){}\nprotected:\n void compareIndexTransition(IndexTransition& iT1, IndexTransition& iT2)\n {\n ASSERT_EQ(iT1.index, iT2.index);\n ASSERT_EQ(iT1.transition, iT2.transition);\n }\n};\n\nclass IterateHV : public IterateTestMethods\n{\npublic:\n IterateHV(){}\nprotected:\n \n void run(int) {\n cv::Mat_<TYPE> mat(3, 3 * channels, 100);\n \/\/ cv::Vec<TYPE, channels> subPix;\n \/\/ subPix = static_cast<cv::Vec<TYPE, channels>>(cv::Matx<TYPE, channels, 1>::zeros());\n \/\/ mat.at<cv::Vec<TYPE, channels>>(cv::Point(3,3)) = subPix;\n mat(1,3)=0; mat(1,4)=0; mat(1,5)=0;\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n IterateProcess<TYPE> iterateProcess(mat, lightThreshold, colorThreshold, balance);\n\n std::vector<IndexTransition> result = iterateProcess.iterate_HV();\n\n ASSERT_EQ(result.size(), 4);\n auto expected = IndexTransition{12, leftToRight};\n compareIndexTransition(result[0], expected);\n expected = IndexTransition{12, rightToLeft};\n compareIndexTransition(result[1], expected);\n expected = IndexTransition{12, upToDown};\n compareIndexTransition(result[2], expected);\n expected = IndexTransition{12, downToUp};\n compareIndexTransition(result[3], expected);\n }\n};\nTEST(ComparatorLibSuite, IterateHV) {\n IterateHV IterateHV;\n IterateHV.safe_run();\n}\n\n\n#ifdef TEST_PRIVATE_PART\n\nclass IterateH : public IterateTestMethods\n{\npublic:\n IterateH(){}\nprotected:\n \n void run(int) {\n cv::Mat_<TYPE> mat(3, 3 * channels, 100);\n \/\/ cv::Vec<TYPE, channels> subPix;\n \/\/ subPix = static_cast<cv::Vec<TYPE, channels>>(cv::Matx<TYPE, channels, 1>::zeros());\n \/\/ mat.at<cv::Vec<TYPE, channels>>(cv::Point(3,3)) = subPix;\n mat(1,3)=0; mat(1,4)=0; mat(1,5)=0;\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n IterateProcess<TYPE> iterateProcess(mat, lightThreshold, colorThreshold, balance);\n\n std::vector<IndexTransition> result = iterateProcess.iterate_H();\n\n ASSERT_EQ(result.size(), 2);\n auto expected = IndexTransition{12, leftToRight};\n compareIndexTransition(result[0], expected);\n expected = IndexTransition{12, rightToLeft};\n compareIndexTransition(result[1], expected);\n }\n};\nTEST(ComparatorLibSuite, IterateH) {\n IterateH iterateH;\n iterateH.safe_run();\n}\n\n\nclass IterateV : public IterateTestMethods\n{\npublic:\n IterateV(){}\nprotected:\n \n void run(int) {\n cv::Mat_<TYPE> mat(3, 3 * channels, 100);\n \/\/ cv::Vec<TYPE, channels> subPix;\n \/\/ subPix = static_cast<cv::Vec<TYPE, channels>>(cv::Matx<TYPE, channels, 1>::zeros());\n \/\/ mat.at<cv::Vec<TYPE, channels>>(cv::Point(3,3)) = subPix;\n mat(1,3)=0; mat(1,4)=0; mat(1,5)=0;\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n IterateProcess<TYPE> iterateProcess(mat, lightThreshold, colorThreshold, balance);\n\n std::vector<IndexTransition> result = iterateProcess.iterate_V();\n\n ASSERT_EQ(result.size(), 2);\n auto expected = IndexTransition{12, upToDown};\n compareIndexTransition(result[0], expected);\n expected = IndexTransition{12, downToUp};\n compareIndexTransition(result[1], expected);\n }\n};\nTEST(ComparatorLibSuite, IterateV) {\n IterateV IterateV;\n IterateV.safe_run();\n}\n\n#endif\n\n\nclass Fclassifier : public cvtest::BaseTest\n{\npublic:\n Fclassifier(){}\nprotected:\n \n void run(int) {\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {3, 3, 3};\n \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::no, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 3);\n std::fill( pix1, pix1 + channels, 10);\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::backward, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 10);\n std::fill( pix1, pix1 + channels, 3);\n classifier.copy_pix(pix0, pix1);\n if (Transition::forward != classifier.f_classifier())\n ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n \/\/check that all values are between 1 and 1 (and not Nan)\n \/\/ if (0 != cvtest::check(, 1, 1, 0) )\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);\n }\n};\nTEST(ComparatorLibSuite, f_classifier) {\n Fclassifier fclassifeir;\n fclassifeir.safe_run();\n}\n\n\nclass FclassifierBT : public cvtest::BaseTest\n{\npublic:\n FclassifierBT(){}\nprotected:\n \n void run(int) {\n ts->set_failed_test_info(cvtest::TS::OK);\n\n double balance[] = {2.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 4.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {3, 3, 3};\n \n classifier.copy_pix(pix0, pix1);\n if (Transition::no != classifier.f_classifier())\n ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n\n std::fill( pix0, pix0 + channels, 6);\n std::fill( pix1, pix1 + channels, 10);\n pix0[0] = 4; \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::backward, classifier.f_classifier());\n\n std::fill( pix0, pix0 + channels, 10);\n std::fill( pix1, pix1 + channels, 3);\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(Transition::no, classifier.f_classifier());\n\n \/\/ std::fill( pix0, pix0 + channels, 10);\n \/\/ std::fill( pix1, pix1 + channels, 3);\n \/\/ pix0[0] = 5;\n \/\/ classifier.copy_pix(pix0, pix1);\n \/\/ if (Transition::backward != classifier.f_classifier())\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);\n \/\/check that all values are between 1 and 1 (and not Nan)\n \/\/ if (0 != cvtest::check(, 1, 1, 0) )\n \/\/ ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);\n\n }\n};\nTEST(ComparatorLibSuite, f_classifierbt) {\n FclassifierBT fclassifierbt;\n fclassifierbt.safe_run();\n}\n\n\n#ifdef TEST_PRIVATE_PART\n\nclass LightAndColor : public cvtest::BaseTest\n{\npublic:\n LightAndColor(){}\nprotected:\n \n void run(int) {\n double balance[] = {1.0, 1.0, 1.0};\n double lightThreshold = 1.0;\n double colorThreshold = 1.0;\n\n Classifier<TYPE> classifier(lightThreshold, colorThreshold, balance);\n\n\n TYPE pix0[] = {3, 3, 3};\n TYPE pix1[] = {10, 10, 10};\n \n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(21, classifier.light_distance());\n ASSERT_EQ(0, classifier.color_distance());\n \n pix1[0] = 13;\n classifier.copy_pix(pix0, pix1);\n ASSERT_EQ(24, classifier.light_distance());\n ASSERT_EQ(6, classifier.color_distance());\n }\n};\nTEST(ComparatorPrivateLibSuite, PrivatePartClassifier) {\n LightAndColor lightAndColor;\n lightAndColor.safe_run();\n}\n#endif\n\n\/\/ TEST(ComparatorLibSuite, ATestThatFails) {\n\/\/ bool mybool = false;\n\/\/ ASSERT_TRUE(mybool);\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 by Philip N. Garner\n *\n * See the file COPYING for the licence associated with this software.\n *\n * Author(s):\n * Phil Garner, March 2016\n *\/\n\n#include <istream>\n#include <cctype>\n#include <cstring>\n#include <lube\/var.h>\n\nnamespace libube\n{\n \/**\n * Ad-hoc JSON (JavaScript Object Notation) parser; (see http:\/\/json.org\/)\n *\/\n class JSON\n {\n public:\n var operator ()(std::istream& iStream);\n private:\n char peek(std::istream& iStream);\n var doValue(std::istream& iStream);\n var doObject(std::istream& iStream);\n var doArray(std::istream& iStream);\n var doString(std::istream& iStream);\n var doRaw(std::istream& iStream);\n };\n}\n\n\nusing namespace libube;\nusing namespace std;\n\n\/** Find the next character after whitespace *\/\nchar JSON::peek(std::istream& iStream)\n{\n char c = iStream.peek();\n while (isspace(c))\n {\n iStream.get();\n c = iStream.peek();\n }\n return c;\n}\n\nvar JSON::doValue(std::istream& iStream)\n{\n var val;\n switch (peek(iStream))\n {\n case '{':\n val = doObject(iStream);\n break;\n case '[':\n val = doArray(iStream);\n break;\n case '\"':\n val = doString(iStream);\n break;\n default:\n val = doRaw(iStream);\n }\n return val;\n}\n\nvar JSON::doObject(std::istream& iStream)\n{\n var obj;\n obj[nil];\n var key;\n char got = iStream.get();\n if (got != '{')\n throw error(\"JSON object doesn't start with {\");\n while (iStream)\n {\n switch (peek(iStream))\n {\n case '}':\n iStream.get();\n return obj;\n break;\n case '\"':\n key = doString(iStream);\n break;\n case ':':\n iStream.get();\n obj[key] = doValue(iStream);\n break;\n case ',':\n iStream.get();\n key = nil;\n break;\n default:\n throw error(\"Unknown character\");\n }\n }\n return obj;\n}\n\nvar JSON::doArray(std::istream& iStream)\n{\n var arr;\n char got = iStream.get();\n if (got != '[')\n throw error(\"JSON array doesn't start with [\");\n while (iStream)\n {\n switch (peek(iStream))\n {\n case ']':\n iStream.get();\n return arr;\n break;\n case ',':\n iStream.get();\n break;\n default:\n arr.push(doValue(iStream));\n }\n }\n return arr;\n}\n\nvar JSON::doString(std::istream& iStream)\n{\n var str;\n char got = iStream.get();\n if (got != '\\\"')\n throw error(\"JSON string doesn't start with \\\"\");\n \/\/ Not robust to escapes yet\n while (iStream.get(got))\n if (got == '\"')\n break;\n else\n str.push(got);\n return str;\n}\n\nvar JSON::doRaw(std::istream& iStream)\n{\n \/\/ Read up to a space or JSON delimiter\n var val;\n char c;\n while (iStream.get(c))\n {\n if (isspace(c))\n break;\n if (strchr(\",[]{}\", c))\n break;\n val.push(c);\n }\n\n \/\/ These values have special meanings\n if (val == \"true\")\n return 1;\n else if (val == \"false\")\n return 0;\n else if (val == \"null\")\n return nil;\n \n \/\/ It's probably a number, but return a string for the moment\n return val;\n}\n\n\/**\n * For proper JSON we should call doObject(), mandating it be in braces. In\n * calling doValue() we're allowing just raw values which is OK for lube but\n * not strictly JSON.\n *\/\nvar JSON::operator()(std::istream& iStream)\n{\n var val = doValue(iStream);\n return val;\n}\n\nstd::istream& libube::operator >>(std::istream& iStream, var& ioVar)\n{\n JSON json;\n var in = json(iStream);\n ioVar = in;\n return iStream;\n}\n<commit_msg>Make the JSON parser robust to escapes and single character strings<commit_after>\/*\n * Copyright 2016 by Philip N. Garner\n *\n * See the file COPYING for the licence associated with this software.\n *\n * Author(s):\n * Phil Garner, March 2016\n *\/\n\n#include <istream>\n#include <cctype>\n#include <cstring>\n#include <lube\/var.h>\n\nnamespace libube\n{\n \/**\n * Ad-hoc JSON (JavaScript Object Notation) parser; (see http:\/\/json.org\/)\n *\/\n class JSON\n {\n public:\n var operator ()(std::istream& iStream);\n private:\n char peek(std::istream& iStream);\n var doValue(std::istream& iStream);\n var doObject(std::istream& iStream);\n var doArray(std::istream& iStream);\n var doString(std::istream& iStream);\n var doRaw(std::istream& iStream);\n };\n}\n\n\nusing namespace libube;\nusing namespace std;\n\n\/** Find the next character after whitespace *\/\nchar JSON::peek(std::istream& iStream)\n{\n char c = iStream.peek();\n while (isspace(c))\n {\n iStream.get();\n c = iStream.peek();\n }\n return c;\n}\n\nvar JSON::doValue(std::istream& iStream)\n{\n var val;\n switch (peek(iStream))\n {\n case '{':\n val = doObject(iStream);\n break;\n case '[':\n val = doArray(iStream);\n break;\n case '\"':\n val = doString(iStream);\n break;\n default:\n val = doRaw(iStream);\n }\n return val;\n}\n\nvar JSON::doObject(std::istream& iStream)\n{\n var obj;\n obj[nil];\n var key;\n char got = iStream.get();\n if (got != '{')\n throw error(\"JSON object doesn't start with {\");\n while (iStream)\n {\n switch (peek(iStream))\n {\n case '}':\n iStream.get();\n return obj;\n break;\n case '\"':\n key = doString(iStream);\n break;\n case ':':\n iStream.get();\n obj[key] = doValue(iStream);\n break;\n case ',':\n iStream.get();\n key = nil;\n break;\n default:\n throw error(\"Unknown character\");\n }\n }\n return obj;\n}\n\nvar JSON::doArray(std::istream& iStream)\n{\n var arr;\n char got = iStream.get();\n if (got != '[')\n throw error(\"JSON array doesn't start with [\");\n while (iStream)\n {\n switch (peek(iStream))\n {\n case ']':\n iStream.get();\n return arr;\n break;\n case ',':\n iStream.get();\n break;\n default:\n arr.push(doValue(iStream));\n }\n }\n return arr;\n}\n\nvar JSON::doString(std::istream& iStream)\n{\n var str = \"\";\n char got = iStream.get();\n if (got != '\\\"')\n throw error(\"JSON string doesn't start with \\\"\");\n while (iStream.get(got))\n switch (got)\n {\n case '\\\"':\n return str;\n case '\\\\':\n \/\/ Escape character\n got = iStream.get();\n switch (got)\n {\n case '\\\"':\n str.push(got);\n break;\n default:\n throw error(\"Unrecognised JSON string escape\");\n }\n break;\n default:\n str.push(got);\n }\n throw error(\"Unterminated JSON string\");\n return nil;\n}\n\nvar JSON::doRaw(std::istream& iStream)\n{\n \/\/ Read up to a space or JSON delimiter\n var val = \"\";\n char c;\n while (iStream.get(c))\n {\n if (isspace(c))\n break;\n if (strchr(\",[]{}\", c))\n break;\n val.push(c);\n }\n\n \/\/ These values have special meanings\n if (val == \"true\")\n return 1;\n else if (val == \"false\")\n return 0;\n else if (val == \"null\")\n return nil;\n \n \/\/ It's probably a number, but return a string for the moment\n return val;\n}\n\n\/**\n * For proper JSON we should call doObject(), mandating it be in braces. In\n * calling doValue() we're allowing just raw values which is OK for lube but\n * not strictly JSON.\n *\/\nvar JSON::operator()(std::istream& iStream)\n{\n var val = doValue(iStream);\n return val;\n}\n\nstd::istream& libube::operator >>(std::istream& iStream, var& ioVar)\n{\n JSON json;\n var in = json(iStream);\n ioVar = in;\n return iStream;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#pragma once\n\n#define GLFW_INCLUDE_GLU\n#include <GLFW\/glfw3.h>\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic Data Types \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct float3 { float x, y, z; };\nstruct float2 { float x, y; };\n\nstruct rect\n{\n float x, y;\n float w, h;\n\n \/\/ Create new rect within original boundaries with give aspect ration\n rect adjust_ratio(float2 size) const\n {\n auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x \/ size.y;\n if (W > w)\n {\n auto scale = w \/ W;\n W *= scale;\n H *= scale;\n }\n\n return{ x + (w - W) \/ 2, y + (h - H) \/ 2, W, H };\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Simple font loading code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"..\/third-party\/stb_easy_font.h\"\n\ninline void draw_text(int x, int y, const char * text)\n{\n char buffer[60000]; \/\/ ~300 chars\n glEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, 16, buffer);\n glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer)));\n glDisableClientState(GL_VERTEX_ARRAY);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Image display code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass texture\n{\npublic:\n void render(const rs2::video_frame& frame, const rect& r)\n {\n upload(frame);\n show(r.adjust_ratio({ float(width), float(height) }));\n }\n\n void upload(const rs2::video_frame& frame)\n {\n if (!frame) return;\n\n if (!gl_handle)\n glGenTextures(1, &gl_handle);\n GLenum err = glGetError();\n\n auto format = frame.get_profile().format();\n width = frame.get_width();\n height = frame.get_height();\n stream = frame.get_profile().stream_type();\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_Y8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n default:\n throw std::runtime_error(\"The requested format is not supported by this demo!\");\n }\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n GLuint get_gl_handle() { return gl_handle; }\n\n void show(const rect& r) const\n {\n if (!gl_handle)\n return;\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n glEnable(GL_TEXTURE_2D);\n glBegin(GL_QUAD_STRIP);\n glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h);\n glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y);\n glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h);\n glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream));\n }\nprivate:\n GLuint gl_handle = 0;\n int width = 0;\n int height = 0;\n rs2_stream stream = RS2_STREAM_ANY;\n};\n\nclass window\n{\npublic:\n std::function<void(bool)> on_left_mouse = [](bool) {};\n std::function<void(double, double)> on_mouse_scroll = [](double, double) {};\n std::function<void(double, double)> on_mouse_move = [](double, double) {};\n std::function<void(int)> on_key_release = [](int) {};\n\n window(int width, int height, const char* title)\n : _width(width), _height(height)\n {\n glfwInit();\n win = glfwCreateWindow(width, height, title, nullptr, nullptr);\n glfwMakeContextCurrent(win);\n\n glfwSetWindowUserPointer(win, this);\n glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (button == 0) s->on_left_mouse(action == GLFW_PRESS);\n });\n\n glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_scroll(xoffset, yoffset);\n });\n\n glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_move(x, y);\n });\n\n glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (0 == action) \/\/ on key release\n {\n s->on_key_release(key);\n }\n });\n }\n\n float width() const { return float(_width); }\n float height() const { return float(_height); }\n\n operator bool()\n {\n glPopMatrix();\n glfwSwapBuffers(win);\n\n auto res = !glfwWindowShouldClose(win);\n\n glfwPollEvents();\n glfwGetFramebufferSize(win, &_width, &_height);\n\n \/\/ Clear the framebuffer\n glClear(GL_COLOR_BUFFER_BIT);\n glViewport(0, 0, _width, _height);\n\n \/\/ Draw the images\n glPushMatrix();\n glfwGetWindowSize(win, &_width, &_height);\n glOrtho(0, _width, _height, 0, -1, +1);\n\n return res;\n }\n\n ~window()\n {\n glfwDestroyWindow(win);\n glfwTerminate();\n }\n\n operator GLFWwindow*() { return win; }\n\nprivate:\n GLFWwindow* win;\n int _width, _height;\n};\n<commit_msg>Adding rendering for RGBA in example.hpp<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#pragma once\n\n#define GLFW_INCLUDE_GLU\n#include <GLFW\/glfw3.h>\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic Data Types \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct float3 { float x, y, z; };\nstruct float2 { float x, y; };\n\nstruct rect\n{\n float x, y;\n float w, h;\n\n \/\/ Create new rect within original boundaries with give aspect ration\n rect adjust_ratio(float2 size) const\n {\n auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x \/ size.y;\n if (W > w)\n {\n auto scale = w \/ W;\n W *= scale;\n H *= scale;\n }\n\n return{ x + (w - W) \/ 2, y + (h - H) \/ 2, W, H };\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Simple font loading code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"..\/third-party\/stb_easy_font.h\"\n\ninline void draw_text(int x, int y, const char * text)\n{\n char buffer[60000]; \/\/ ~300 chars\n glEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, 16, buffer);\n glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer)));\n glDisableClientState(GL_VERTEX_ARRAY);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Image display code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass texture\n{\npublic:\n void render(const rs2::video_frame& frame, const rect& r)\n {\n upload(frame);\n show(r.adjust_ratio({ float(width), float(height) }));\n }\n\n void upload(const rs2::video_frame& frame)\n {\n if (!frame) return;\n\n if (!gl_handle)\n glGenTextures(1, &gl_handle);\n GLenum err = glGetError();\n\n auto format = frame.get_profile().format();\n width = frame.get_width();\n height = frame.get_height();\n stream = frame.get_profile().stream_type();\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_RGBA8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_Y8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n default:\n throw std::runtime_error(\"The requested format is not supported by this demo!\");\n }\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n GLuint get_gl_handle() { return gl_handle; }\n\n void show(const rect& r) const\n {\n if (!gl_handle)\n return;\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n glEnable(GL_TEXTURE_2D);\n glBegin(GL_QUAD_STRIP);\n glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h);\n glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y);\n glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h);\n glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream));\n }\nprivate:\n GLuint gl_handle = 0;\n int width = 0;\n int height = 0;\n rs2_stream stream = RS2_STREAM_ANY;\n};\n\nclass window\n{\npublic:\n std::function<void(bool)> on_left_mouse = [](bool) {};\n std::function<void(double, double)> on_mouse_scroll = [](double, double) {};\n std::function<void(double, double)> on_mouse_move = [](double, double) {};\n std::function<void(int)> on_key_release = [](int) {};\n\n window(int width, int height, const char* title)\n : _width(width), _height(height)\n {\n glfwInit();\n win = glfwCreateWindow(width, height, title, nullptr, nullptr);\n glfwMakeContextCurrent(win);\n\n glfwSetWindowUserPointer(win, this);\n glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (button == 0) s->on_left_mouse(action == GLFW_PRESS);\n });\n\n glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_scroll(xoffset, yoffset);\n });\n\n glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_move(x, y);\n });\n\n glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (0 == action) \/\/ on key release\n {\n s->on_key_release(key);\n }\n });\n }\n\n float width() const { return float(_width); }\n float height() const { return float(_height); }\n\n operator bool()\n {\n glPopMatrix();\n glfwSwapBuffers(win);\n\n auto res = !glfwWindowShouldClose(win);\n\n glfwPollEvents();\n glfwGetFramebufferSize(win, &_width, &_height);\n\n \/\/ Clear the framebuffer\n glClear(GL_COLOR_BUFFER_BIT);\n glViewport(0, 0, _width, _height);\n\n \/\/ Draw the images\n glPushMatrix();\n glfwGetWindowSize(win, &_width, &_height);\n glOrtho(0, _width, _height, 0, -1, +1);\n\n return res;\n }\n\n ~window()\n {\n glfwDestroyWindow(win);\n glfwTerminate();\n }\n\n operator GLFWwindow*() { return win; }\n\nprivate:\n GLFWwindow* win;\n int _width, _height;\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011, Peter Thorson. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the WebSocket++ Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#include \"echo.hpp\"\n\n#include \"..\/..\/src\/websocketpp.hpp\"\n#include <boost\/asio.hpp>\n\n#include <iostream>\n\nusing boost::asio::ip::tcp;\n\nint main(int argc, char* argv[]) {\n\tstd::string host = \"localhost:5000\";\n\tshort port = 5000;\n\t\n\tif (argc == 3) {\n\t\t\/\/ TODO: input validation?\n\t\tport = atoi(argv[2]);\n\n\t\t\n\t\tstd::stringstream temp;\n\t\ttemp << argv[1] << \":\" << port;\n\t\t\n\t\thost = temp.str();\n\t}\n\t\n\twebsocketecho::echo_handler_ptr echo_handler(new websocketecho::echo_handler());\n\t\n\ttry {\n\t\tboost::asio::io_service io_service;\n\t\ttcp::endpoint endpoint(tcp::v6(), port);\n\t\t\n\t\twebsocketpp::server_ptr server(\n\t\t\tnew websocketpp::server(io_service,endpoint,echo_handler)\n\t\t);\n\t\t\n\t\t\/\/ setup server settings\n\t\tserver->add_host(host);\n\t\t\n\t\t\/\/ bump up max message size to maximum since we may be using the echo \n\t\t\/\/ server to test performance and protocol extremes.\n\t\tserver->set_max_message_size(websocketpp::frame::PAYLOAD_64BIT_LIMIT); \n\t\t\n\t\t\/\/ start the server\n\t\tserver->start_accept();\n\t\t\n\t\tstd::cout << \"Starting echo server on \" << host << std::endl;\n\t\t\n\t\t\/\/ start asio\n\t\tio_service.run();\n\t} catch (std::exception& e) {\n\t\tstd::cerr << \"Exception: \" << e.what() << std::endl;\n\t}\n\t\n\treturn 0;\n}\n<commit_msg>echo server now accepts `host` in addition to `host:port` as a value for the Host handshake header<commit_after>\/*\n * Copyright (c) 2011, Peter Thorson. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the WebSocket++ Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#include \"echo.hpp\"\n\n#include \"..\/..\/src\/websocketpp.hpp\"\n#include <boost\/asio.hpp>\n\n#include <iostream>\n\nusing boost::asio::ip::tcp;\n\nint main(int argc, char* argv[]) {\n\tstd::string host = \"localhost\";\n\tshort port = 5000;\n\tstd::string full_host;\n\t\n\tif (argc == 3) {\n\t\t\/\/ TODO: input validation?\n\t\thost = argv[1];\n\t\tport = atoi(argv[2]);\n\t}\n\t\n\tstd::stringstream temp;\n\t\n\ttemp << argv[1] << \":\" << port;\n\tfull_host = temp.str();\n\t\n\twebsocketecho::echo_handler_ptr echo_handler(new websocketecho::echo_handler());\n\t\n\ttry {\n\t\tboost::asio::io_service io_service;\n\t\ttcp::endpoint endpoint(tcp::v6(), port);\n\t\t\n\t\twebsocketpp::server_ptr server(\n\t\t\tnew websocketpp::server(io_service,endpoint,echo_handler)\n\t\t);\n\t\t\n\t\t\/\/ setup server settings\n\t\tserver->add_host(host);\n\t\tserver->add_host(full_host);\n\t\t\n\t\t\/\/ bump up max message size to maximum since we may be using the echo \n\t\t\/\/ server to test performance and protocol extremes.\n\t\tserver->set_max_message_size(websocketpp::frame::PAYLOAD_64BIT_LIMIT); \n\t\t\n\t\t\/\/ start the server\n\t\tserver->start_accept();\n\t\t\n\t\tstd::cout << \"Starting echo server on \" << full_host << std::endl;\n\t\t\n\t\t\/\/ start asio\n\t\tio_service.run();\n\t} catch (std::exception& e) {\n\t\tstd::cerr << \"Exception: \" << e.what() << std::endl;\n\t}\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <math.h> \/\/ fmodf\n#include \"engine.h\"\n#include \"gui.h\"\n#include \"world.h\"\n#include \"client.h\"\n#include \"menu.h\"\n#include \"cvar.h\"\n#include \"edit.h\"\n\n#include \"r_pipeline.h\"\n#include \"r_gui.h\"\n\n#include \"u_file.h\"\n#include \"u_misc.h\"\n\n\/\/ Game globals\nbool gRunning = true;\nbool gPlaying = false;\nworld::descriptor *gSelected = nullptr; \/\/ Selected world entity\nclient gClient;\nworld gWorld;\nr::pipeline gPipeline;\nm::perspective gPerspective;\n\nVAR(float, cl_fov, \"field of view\", 45.0f, 270.0f, 90.0f);\nVAR(float, cl_nearp, \"near plane\", 0.0f, 10.0f, 0.1f);\nVAR(float, cl_farp, \"far plane\", 128.0f, 4096.0f, 2048.0f);\n\nstatic void setBinds() {\n neoBindSet(\"MouseDnL\", []() {\n if (varGet<int>(\"cl_edit\").get() && (gMenuState == 0 || gMenuState == kMenuConsole))\n edit::select();\n });\n\n neoBindSet(\"EscapeDn\", []() {\n if (gPlaying && (gMenuState & kMenuMain)) {\n if (gMenuState & kMenuConsole) {\n gMenuState = kMenuConsole;\n } else {\n gMenuState &= ~kMenuMain;\n }\n } else if (!(gMenuState & kMenuEdit) && !(gMenuState & kMenuColorGrading)) {\n \/\/ If the console is opened leave it open\n if (!(gMenuState & kMenuMain)) {\n neoRelativeMouse(false);\n neoCenterMouse();\n }\n gMenuState = (gMenuState & kMenuConsole)\n ? kMenuMain | kMenuConsole\n : kMenuMain;\n } else {\n gMenuState &= ~kMenuEdit;\n gMenuState &= ~kMenuColorGrading;\n gMenuState &= ~kMenuDeveloper;\n }\n neoRelativeMouse(gPlaying && (gMenuState & ~kMenuConsole) == 0);\n menuReset();\n });\n\n neoBindSet(\"F8Dn\", []() {\n neoScreenShot();\n });\n\n neoBindSet(\"F9Dn\", []() {\n neoRelativeMouse(false);\n neoCenterMouse();\n gMenuState ^= kMenuDeveloper;\n });\n\n neoBindSet(\"F10Dn\", []() {\n if (varGet<int>(\"cl_edit\").get())\n gMenuState ^= kMenuColorGrading;\n neoRelativeMouse(!((gMenuState & kMenuEdit) || (gMenuState & kMenuColorGrading)));\n });\n\n neoBindSet(\"F11Dn\", []() {\n gMenuState ^= kMenuConsole;\n });\n\n neoBindSet(\"F12Dn\", []() {\n if (varGet<int>(\"cl_edit\").get())\n gMenuState ^= kMenuEdit;\n neoRelativeMouse(!(gMenuState & kMenuEdit));\n });\n\n neoBindSet(\"EDn\", []() {\n if (gPlaying) {\n varGet<int>(\"cl_edit\").toggle();\n gMenuState &= ~kMenuEdit;\n neoRelativeMouse(!(gMenuState & kMenuEdit));\n }\n edit::deselect();\n });\n\n neoBindSet(\"DeleteDn\", []() {\n edit::remove();\n });\n}\n\nint neoMain(frameTimer &timer, int, char **, bool &shutdown) {\n \/\/ Setup rendering pipeline\n gPerspective.fov = cl_fov;\n gPerspective.nearp = cl_nearp;\n gPerspective.farp = cl_farp;\n gPerspective.width = neoWidth();\n gPerspective.height = neoHeight();\n\n gPipeline.setWorld(m::vec3::origin);\n\n \/\/ Clear the screen as soon as possible\n gl::ClearColor(40\/255.0f, 30\/255.0f, 50\/255.0f, 0.1f);\n gl::Clear(GL_COLOR_BUFFER_BIT);\n neoSwap();\n\n setBinds();\n\n r::gui gGui;\n if (!gGui.load(\"fonts\/droidsans\"))\n neoFatal(\"failed to load font\");\n if (!gGui.upload())\n neoFatal(\"failed to initialize GUI rendering method\\n\");\n\n \/\/ Setup window and menu\n menuReset();\n neoSetWindowTitle(\"Neothyne\");\n neoCenterMouse();\n\n#if 1\n \/\/ Setup some lights\n const m::vec3 places[] = {\n m::vec3(153.04, 105.02, 197.67)\n };\n\n pointLight light;\n light.diffuse = 1.0f;\n light.ambient = 0.10f;\n light.radius = 30.0f;\n for (size_t i = 0; i < sizeof(places)\/sizeof(*places); i++) {\n light.color = { u::randf(), u::randf(), u::randf() };\n light.position = places[i];\n \/\/light.position.y -= 5.0f;\n gWorld.insert(light);\n }\n light.position = { 0, 110, 0 };\n gWorld.insert(light);\n\n \/\/ World only has one directional light\n directionalLight &dlight = gWorld.getDirectionalLight();\n dlight.color = { 0.2, 0.2, 0.2 };\n dlight.ambient = 0.10f;\n dlight.diffuse = 0.50f;\n dlight.direction = { -1.0f, 0.0f, 0.0f };\n\n \/\/ and some map models\n mapModel m;\n m.name = \"models\/iqmtest\";\n m.position = { 40, 95, 0 };\n m.rotate = { 0, -90, 0 };\n gWorld.insert(m);\n\n m.name = \"models\/cube\";\n m.position = { 85, 112, 35 };\n gWorld.insert(m);\n\n m.name = \"models\/ball\";\n m.position = { 100, 110, 90 };\n m.scale = { 10, 10, 10 };\n\n gWorld.insert(m);\n\n if (!gWorld.load(\"garden.kdgz\"))\n neoFatal(\"failed to load world\");\n#endif\n\n while (gRunning && !shutdown) {\n gClient.update(gWorld, timer.delta());\n\n gPerspective.fov = cl_fov;\n gPerspective.nearp = cl_nearp;\n gPerspective.farp = cl_farp;\n gPerspective.width = neoWidth();\n gPerspective.height = neoHeight();\n\n gPipeline.setPerspective(gPerspective);\n gPipeline.setRotation(gClient.getRotation());\n gPipeline.setPosition(gClient.getPosition());\n gPipeline.setTime(timer.ticks());\n gPipeline.setDelta(timer.delta());\n\n auto mouse = neoMouseState();\n\n \/\/ Update dragging\/moving entity\n if (mouse.button & mouseState::kMouseButtonLeft && gSelected && !(gMenuState & kMenuEdit))\n edit::move();\n\n if (gPlaying && gWorld.isLoaded()) {\n gWorld.upload(gPerspective);\n gl::ClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n gWorld.render(gPipeline);\n gGui.render(gPipeline);\n gui::begin(mouse);\n } else {\n gl::ClearColor(40\/255.0f, 30\/255.0f, 50\/255.0f, 0.1f);\n gl::Clear(GL_COLOR_BUFFER_BIT);\n gGui.render(gPipeline);\n gui::begin(mouse);\n }\n neoSwap();\n\n if (!gPlaying) {\n \/\/ Render the model (for testing only)\n r::pipeline p;\n m::perspective pp = gPerspective;\n\n const m::vec3 rot(0.0f, -(fmodf(gPipeline.time() \/ 10.0f, 361.0f)), 0.0f);\n m::quat ry(m::toRadian(rot.y), m::vec3::yAxis);\n m::mat4 rotate;\n ry.getMatrix(&rotate);\n p.setRotate(rotate);\n\n int w = neoWidth() \/ 12;\n int h = neoHeight() \/ 12;\n pp.width = w;\n pp.height = h;\n\n p.setPerspective(pp);\n p.setWorld({0, 0, 0});\n p.setPosition({0, 0, -1.5f});\n p.setScale({1, 1, 1});\n\n gui::drawModel(128 \/ neoWidth(),\n neoHeight() \/ 128 + 16, \/\/ 16 to keep above command line\n w,\n h, \"models\/icon\", p);\n }\n\n \/\/ Must come first as we want the menu to go over the cross hair if it's\n \/\/ launched after playing\n if (gPlaying && !(gMenuState & ~kMenuConsole)) {\n gui::drawLine(neoWidth() \/ 2, neoHeight() \/ 2 - 10, neoWidth() \/ 2, neoHeight() \/ 2 - 4, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2, neoHeight() \/ 2 + 4, neoWidth() \/ 2, neoHeight() \/ 2 + 10, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2 + 10, neoHeight() \/ 2, neoWidth() \/ 2 + 4, neoHeight() \/ 2, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2 - 10, neoHeight() \/ 2, neoWidth() \/ 2 - 4, neoHeight() \/ 2, 2, 0xFFFFFFE1);\n }\n if (!gPlaying) {\n const size_t w = neoWidth();\n const size_t h = (neoHeight() \/ 2);\n const size_t x = neoWidth() \/ 2 - w \/ 2; \/\/ Center on X\n const size_t y = neoHeight() - h;\n\n r::pipeline p;\n m::perspective pp = gPerspective;\n pp.width = w;\n pp.height = h;\n pp.fov = 20.0f;\n p.setPerspective(pp);\n p.setWorld({0, 0, 0});\n p.setPosition({0, 0, -130});\n p.setScale({1, 1, 1});\n\n gui::drawModel(x, y, w, h, \"models\/logo\", p);\n }\n\n menuUpdate();\n\n \/\/ Render FPS\/MSPF\n gui::drawText(neoWidth(), 10, gui::kAlignRight,\n u::format(\"%d fps : %.2f mspf\\n\", timer.fps(), timer.mspf()).c_str(),\n gui::RGBA(255, 255, 255, 255));\n\n if (varGet<int>(\"cl_edit\").get() && !(gMenuState & kMenuEdit)) {\n gui::drawText(neoWidth() \/ 2, neoHeight() - 20, gui::kAlignCenter, \"F12 to toggle edit menu\",\n gui::RGBA(0, 0, 0, 255));\n gui::drawText(neoWidth() \/ 2, neoHeight() - 40, gui::kAlignCenter, \"F10 to toggle color grading menu\",\n gui::RGBA(0, 0, 0, 255));\n }\n\n u::string inputText;\n textState text = neoTextState(inputText);\n if (text != textState::kInactive) {\n gui::drawTriangle(5, 10, 10, 10, 1, gui::RGBA(155, 155, 155, 255));\n gui::drawText(20, 10, gui::kAlignLeft,\n inputText.c_str(), gui::RGBA(255, 255, 255, 255));\n if (text == textState::kFinished) {\n auto values = u::split(inputText);\n if (values.size() == 2) {\n switch (varChange(values[0], values[1])) {\n case kVarSuccess:\n u::print(\"changed `%s' to `%s'\\n\", values[0], values[1]);\n break;\n case kVarRangeError:\n u::print(\"invalid range for `%s'\\n\", values[0]);\n break;\n case kVarTypeError:\n u::print(\"invalid type for `%s'\\n\", values[0]);\n break;\n case kVarNotFoundError:\n u::print(\"variable `%s' not found\\n\", values[0]);\n break;\n case kVarReadOnlyError:\n u::print(\"variable `%s' is read-only\\n\", values[0]);\n break;\n }\n } else if (values.size() == 1) {\n if (values[0] == \"quit\" || values[0] == \"exit\")\n gRunning = false;\n }\n }\n }\n\n \/\/ Cursor above all else\n if ((gMenuState & ~kMenuConsole || gMenuState & kMenuEdit || gMenuState & kMenuCreate) && !neoRelativeMouse())\n gui::drawImage(mouse.x, mouse.y - (32 - 3), 32, 32, \"textures\/ui\/cursor\");\n\n gui::finish();\n }\n\n return 0;\n}\n<commit_msg>Offset FPS\/MSPF 10 pixels from the edge<commit_after>#include <math.h> \/\/ fmodf\n#include \"engine.h\"\n#include \"gui.h\"\n#include \"world.h\"\n#include \"client.h\"\n#include \"menu.h\"\n#include \"cvar.h\"\n#include \"edit.h\"\n\n#include \"r_pipeline.h\"\n#include \"r_gui.h\"\n\n#include \"u_file.h\"\n#include \"u_misc.h\"\n\n\/\/ Game globals\nbool gRunning = true;\nbool gPlaying = false;\nworld::descriptor *gSelected = nullptr; \/\/ Selected world entity\nclient gClient;\nworld gWorld;\nr::pipeline gPipeline;\nm::perspective gPerspective;\n\nVAR(float, cl_fov, \"field of view\", 45.0f, 270.0f, 90.0f);\nVAR(float, cl_nearp, \"near plane\", 0.0f, 10.0f, 0.1f);\nVAR(float, cl_farp, \"far plane\", 128.0f, 4096.0f, 2048.0f);\n\nstatic void setBinds() {\n neoBindSet(\"MouseDnL\", []() {\n if (varGet<int>(\"cl_edit\").get() && (gMenuState == 0 || gMenuState == kMenuConsole))\n edit::select();\n });\n\n neoBindSet(\"EscapeDn\", []() {\n if (gPlaying && (gMenuState & kMenuMain)) {\n if (gMenuState & kMenuConsole) {\n gMenuState = kMenuConsole;\n } else {\n gMenuState &= ~kMenuMain;\n }\n } else if (!(gMenuState & kMenuEdit) && !(gMenuState & kMenuColorGrading)) {\n \/\/ If the console is opened leave it open\n if (!(gMenuState & kMenuMain)) {\n neoRelativeMouse(false);\n neoCenterMouse();\n }\n gMenuState = (gMenuState & kMenuConsole)\n ? kMenuMain | kMenuConsole\n : kMenuMain;\n } else {\n gMenuState &= ~kMenuEdit;\n gMenuState &= ~kMenuColorGrading;\n gMenuState &= ~kMenuDeveloper;\n }\n neoRelativeMouse(gPlaying && (gMenuState & ~kMenuConsole) == 0);\n menuReset();\n });\n\n neoBindSet(\"F8Dn\", []() {\n neoScreenShot();\n });\n\n neoBindSet(\"F9Dn\", []() {\n neoRelativeMouse(false);\n neoCenterMouse();\n gMenuState ^= kMenuDeveloper;\n });\n\n neoBindSet(\"F10Dn\", []() {\n if (varGet<int>(\"cl_edit\").get())\n gMenuState ^= kMenuColorGrading;\n neoRelativeMouse(!((gMenuState & kMenuEdit) || (gMenuState & kMenuColorGrading)));\n });\n\n neoBindSet(\"F11Dn\", []() {\n gMenuState ^= kMenuConsole;\n });\n\n neoBindSet(\"F12Dn\", []() {\n if (varGet<int>(\"cl_edit\").get())\n gMenuState ^= kMenuEdit;\n neoRelativeMouse(!(gMenuState & kMenuEdit));\n });\n\n neoBindSet(\"EDn\", []() {\n if (gPlaying) {\n varGet<int>(\"cl_edit\").toggle();\n gMenuState &= ~kMenuEdit;\n neoRelativeMouse(!(gMenuState & kMenuEdit));\n }\n edit::deselect();\n });\n\n neoBindSet(\"DeleteDn\", []() {\n edit::remove();\n });\n}\n\nint neoMain(frameTimer &timer, int, char **, bool &shutdown) {\n \/\/ Setup rendering pipeline\n gPerspective.fov = cl_fov;\n gPerspective.nearp = cl_nearp;\n gPerspective.farp = cl_farp;\n gPerspective.width = neoWidth();\n gPerspective.height = neoHeight();\n\n gPipeline.setWorld(m::vec3::origin);\n\n \/\/ Clear the screen as soon as possible\n gl::ClearColor(40\/255.0f, 30\/255.0f, 50\/255.0f, 0.1f);\n gl::Clear(GL_COLOR_BUFFER_BIT);\n neoSwap();\n\n setBinds();\n\n r::gui gGui;\n if (!gGui.load(\"fonts\/droidsans\"))\n neoFatal(\"failed to load font\");\n if (!gGui.upload())\n neoFatal(\"failed to initialize GUI rendering method\\n\");\n\n \/\/ Setup window and menu\n menuReset();\n neoSetWindowTitle(\"Neothyne\");\n neoCenterMouse();\n\n#if 1\n \/\/ Setup some lights\n const m::vec3 places[] = {\n m::vec3(153.04, 105.02, 197.67)\n };\n\n pointLight light;\n light.diffuse = 1.0f;\n light.ambient = 0.10f;\n light.radius = 30.0f;\n for (size_t i = 0; i < sizeof(places)\/sizeof(*places); i++) {\n light.color = { u::randf(), u::randf(), u::randf() };\n light.position = places[i];\n \/\/light.position.y -= 5.0f;\n gWorld.insert(light);\n }\n light.position = { 0, 110, 0 };\n gWorld.insert(light);\n\n \/\/ World only has one directional light\n directionalLight &dlight = gWorld.getDirectionalLight();\n dlight.color = { 0.2, 0.2, 0.2 };\n dlight.ambient = 0.10f;\n dlight.diffuse = 0.50f;\n dlight.direction = { -1.0f, 0.0f, 0.0f };\n\n \/\/ and some map models\n mapModel m;\n m.name = \"models\/iqmtest\";\n m.position = { 40, 95, 0 };\n m.rotate = { 0, -90, 0 };\n gWorld.insert(m);\n\n m.name = \"models\/cube\";\n m.position = { 85, 112, 35 };\n gWorld.insert(m);\n\n m.name = \"models\/ball\";\n m.position = { 100, 110, 90 };\n m.scale = { 10, 10, 10 };\n\n gWorld.insert(m);\n\n if (!gWorld.load(\"garden.kdgz\"))\n neoFatal(\"failed to load world\");\n#endif\n\n while (gRunning && !shutdown) {\n gClient.update(gWorld, timer.delta());\n\n gPerspective.fov = cl_fov;\n gPerspective.nearp = cl_nearp;\n gPerspective.farp = cl_farp;\n gPerspective.width = neoWidth();\n gPerspective.height = neoHeight();\n\n gPipeline.setPerspective(gPerspective);\n gPipeline.setRotation(gClient.getRotation());\n gPipeline.setPosition(gClient.getPosition());\n gPipeline.setTime(timer.ticks());\n gPipeline.setDelta(timer.delta());\n\n auto mouse = neoMouseState();\n\n \/\/ Update dragging\/moving entity\n if (mouse.button & mouseState::kMouseButtonLeft && gSelected && !(gMenuState & kMenuEdit))\n edit::move();\n\n if (gPlaying && gWorld.isLoaded()) {\n gWorld.upload(gPerspective);\n gl::ClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n gWorld.render(gPipeline);\n gGui.render(gPipeline);\n gui::begin(mouse);\n } else {\n gl::ClearColor(40\/255.0f, 30\/255.0f, 50\/255.0f, 0.1f);\n gl::Clear(GL_COLOR_BUFFER_BIT);\n gGui.render(gPipeline);\n gui::begin(mouse);\n }\n neoSwap();\n\n if (!gPlaying) {\n \/\/ Render the model (for testing only)\n r::pipeline p;\n m::perspective pp = gPerspective;\n\n const m::vec3 rot(0.0f, -(fmodf(gPipeline.time() \/ 10.0f, 361.0f)), 0.0f);\n m::quat ry(m::toRadian(rot.y), m::vec3::yAxis);\n m::mat4 rotate;\n ry.getMatrix(&rotate);\n p.setRotate(rotate);\n\n int w = neoWidth() \/ 12;\n int h = neoHeight() \/ 12;\n pp.width = w;\n pp.height = h;\n\n p.setPerspective(pp);\n p.setWorld({0, 0, 0});\n p.setPosition({0, 0, -1.5f});\n p.setScale({1, 1, 1});\n\n gui::drawModel(128 \/ neoWidth(),\n neoHeight() \/ 128 + 16, \/\/ 16 to keep above command line\n w,\n h, \"models\/icon\", p);\n }\n\n \/\/ Must come first as we want the menu to go over the cross hair if it's\n \/\/ launched after playing\n if (gPlaying && !(gMenuState & ~kMenuConsole)) {\n gui::drawLine(neoWidth() \/ 2, neoHeight() \/ 2 - 10, neoWidth() \/ 2, neoHeight() \/ 2 - 4, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2, neoHeight() \/ 2 + 4, neoWidth() \/ 2, neoHeight() \/ 2 + 10, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2 + 10, neoHeight() \/ 2, neoWidth() \/ 2 + 4, neoHeight() \/ 2, 2, 0xFFFFFFE1);\n gui::drawLine(neoWidth() \/ 2 - 10, neoHeight() \/ 2, neoWidth() \/ 2 - 4, neoHeight() \/ 2, 2, 0xFFFFFFE1);\n }\n if (!gPlaying) {\n const size_t w = neoWidth();\n const size_t h = (neoHeight() \/ 2);\n const size_t x = neoWidth() \/ 2 - w \/ 2; \/\/ Center on X\n const size_t y = neoHeight() - h;\n\n r::pipeline p;\n m::perspective pp = gPerspective;\n pp.width = w;\n pp.height = h;\n pp.fov = 20.0f;\n p.setPerspective(pp);\n p.setWorld({0, 0, 0});\n p.setPosition({0, 0, -130});\n p.setScale({1, 1, 1});\n\n gui::drawModel(x, y, w, h, \"models\/logo\", p);\n }\n\n menuUpdate();\n\n \/\/ Render FPS\/MSPF\n gui::drawText(neoWidth() - 10, 10, gui::kAlignRight,\n u::format(\"%d fps : %.2f mspf\\n\", timer.fps(), timer.mspf()).c_str(),\n gui::RGBA(255, 255, 255, 255));\n\n if (varGet<int>(\"cl_edit\").get() && !(gMenuState & kMenuEdit)) {\n gui::drawText(neoWidth() \/ 2, neoHeight() - 20, gui::kAlignCenter, \"F12 to toggle edit menu\",\n gui::RGBA(0, 0, 0, 255));\n gui::drawText(neoWidth() \/ 2, neoHeight() - 40, gui::kAlignCenter, \"F10 to toggle color grading menu\",\n gui::RGBA(0, 0, 0, 255));\n }\n\n u::string inputText;\n textState text = neoTextState(inputText);\n if (text != textState::kInactive) {\n gui::drawTriangle(5, 10, 10, 10, 1, gui::RGBA(155, 155, 155, 255));\n gui::drawText(20, 10, gui::kAlignLeft,\n inputText.c_str(), gui::RGBA(255, 255, 255, 255));\n if (text == textState::kFinished) {\n auto values = u::split(inputText);\n if (values.size() == 2) {\n switch (varChange(values[0], values[1])) {\n case kVarSuccess:\n u::print(\"changed `%s' to `%s'\\n\", values[0], values[1]);\n break;\n case kVarRangeError:\n u::print(\"invalid range for `%s'\\n\", values[0]);\n break;\n case kVarTypeError:\n u::print(\"invalid type for `%s'\\n\", values[0]);\n break;\n case kVarNotFoundError:\n u::print(\"variable `%s' not found\\n\", values[0]);\n break;\n case kVarReadOnlyError:\n u::print(\"variable `%s' is read-only\\n\", values[0]);\n break;\n }\n } else if (values.size() == 1) {\n if (values[0] == \"quit\" || values[0] == \"exit\")\n gRunning = false;\n }\n }\n }\n\n \/\/ Cursor above all else\n if ((gMenuState & ~kMenuConsole || gMenuState & kMenuEdit || gMenuState & kMenuCreate) && !neoRelativeMouse())\n gui::drawImage(mouse.x, mouse.y - (32 - 3), 32, 32, \"textures\/ui\/cursor\");\n\n gui::finish();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ STL includes\n#include <cstring>\n#include <cstdio>\n#include <iostream>\n\n#include <QHostInfo>\n\n\/\/ hyperion local includes\n#include \"LedDeviceUdpH801.h\"\n\nLedDeviceUdpH801::LedDeviceUdpH801(const Json::Value &deviceConfig)\n\t: ProviderUdp()\n{\n\tsetConfig(deviceConfig);\n}\n\nbool LedDeviceUdpH801::setConfig(const Json::Value &deviceConfig)\n{\n\t\/* The H801 port is fixed *\/\n\tProviderUdp::setConfig(deviceConfig, 30977, \"255.255.255.255\");\n\n\t\/* 10ms seems to be a safe default for the wait time *\/\n\t_LatchTime_ns = deviceConfig.get(\"latchtime\", 10000000).asInt();\n\n\t_ids.clear();\n\tfor (Json::Value::ArrayIndex i = 0; i < deviceConfig[\"lightIds\"].size(); i++) {\n\t\tQString id(deviceConfig[\"lightIds\"][i].asCString());\n\t\t_ids.push_back(id.toInt(nullptr, 16));\n\t}\n\n\t_message = QByteArray(_prefix_size + _colors + _id_size * _ids.size() + _suffix_size, 0x00);\n\t_message[0] = 0xFB;\n\t_message[1] = 0xEB;\n\n\tfor (int i = 0; i < _ids.length(); i++) {\n\t\t_message[_prefix_size + _colors + i * _id_size + 0] = (_ids[i] >> 0x00) & 0xFF;\n\t\t_message[_prefix_size + _colors + i * _id_size + 1] = (_ids[i] >> 0x08) & 0xFF;\n\t\t_message[_prefix_size + _colors + i * _id_size + 2] = (_ids[i] >> 0x10) & 0xFF;\n\t}\n\n\tDebug(_log, \"H801 using %s:%d\", _address.toString().toStdString().c_str(), _port);\n\n\treturn true;\n}\n\nLedDevice* LedDeviceUdpH801::construct(const Json::Value &deviceConfig)\n{\n\treturn new LedDeviceUdpH801(deviceConfig);\n}\n\nint LedDeviceUdpH801::write(const std::vector<ColorRgb> &ledValues)\n{\n\tColorRgb color = ledValues[0];\n\t_message[_prefix_size + 0] = color.red;\n\t_message[_prefix_size + 1] = color.green;\n\t_message[_prefix_size + 2] = color.blue;\n\n\treturn writeBytes(_message.size(), reinterpret_cast<const uint8_t*>(_message.data()));\n}\n\nint LedDeviceUdpH801::switchOff()\n{\n\treturn write(std::vector<ColorRgb>(_ledCount, ColorRgb{0, 0, 0}));\n}\n\n<commit_msg>fix last merge<commit_after>\/\/ STL includes\n#include <cstring>\n#include <cstdio>\n#include <iostream>\n\n#include <QHostInfo>\n\n\/\/ hyperion local includes\n#include \"LedDeviceUdpH801.h\"\n\nLedDeviceUdpH801::LedDeviceUdpH801(const Json::Value &deviceConfig)\n\t: ProviderUdp()\n{\n\tsetConfig(deviceConfig);\n}\n\nbool LedDeviceUdpH801::setConfig(const Json::Value &deviceConfig)\n{\n\t\/* The H801 port is fixed *\/\n\tProviderUdp::setConfig(deviceConfig, 10000000, 30977, \"255.255.255.255\");\n\n\t_ids.clear();\n\tfor (Json::Value::ArrayIndex i = 0; i < deviceConfig[\"lightIds\"].size(); i++) {\n\t\tQString id(deviceConfig[\"lightIds\"][i].asCString());\n\t\t_ids.push_back(id.toInt(nullptr, 16));\n\t}\n\n\t_message = QByteArray(_prefix_size + _colors + _id_size * _ids.size() + _suffix_size, 0x00);\n\t_message[0] = 0xFB;\n\t_message[1] = 0xEB;\n\n\tfor (int i = 0; i < _ids.length(); i++) {\n\t\t_message[_prefix_size + _colors + i * _id_size + 0] = (_ids[i] >> 0x00) & 0xFF;\n\t\t_message[_prefix_size + _colors + i * _id_size + 1] = (_ids[i] >> 0x08) & 0xFF;\n\t\t_message[_prefix_size + _colors + i * _id_size + 2] = (_ids[i] >> 0x10) & 0xFF;\n\t}\n\n\tDebug(_log, \"H801 using %s:%d\", _address.toString().toStdString().c_str(), _port);\n\n\treturn true;\n}\n\nLedDevice* LedDeviceUdpH801::construct(const Json::Value &deviceConfig)\n{\n\treturn new LedDeviceUdpH801(deviceConfig);\n}\n\nint LedDeviceUdpH801::write(const std::vector<ColorRgb> &ledValues)\n{\n\tColorRgb color = ledValues[0];\n\t_message[_prefix_size + 0] = color.red;\n\t_message[_prefix_size + 1] = color.green;\n\t_message[_prefix_size + 2] = color.blue;\n\n\treturn writeBytes(_message.size(), reinterpret_cast<const uint8_t*>(_message.data()));\n}\n\nint LedDeviceUdpH801::switchOff()\n{\n\treturn write(std::vector<ColorRgb>(_ledCount, ColorRgb{0, 0, 0}));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-\n\/*******************************************************************************************************************************************************.H.S.**\/\n\/**\n @file mandelbrot_distance_old.cpp\n @author Mitch Richling <https:\/\/www.mitchr.me>\n @brief This program draws a mandelbrot set using the \"distance\".@EOL\n @std C++20\n @copyright\n @parblock\n Copyright (c) 1988-2015, Mitchell Jay Richling <https:\/\/www.mitchr.me> All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n 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\n DAMAGE.\n @endparblock\n*\/\n\/*******************************************************************************************************************************************************.H.E.**\/\n\/** @cond exj *\/\n\n\/\/--------------------------------------------------------------------------------------------------------------------------------------------------------------\n#include \"ramCanvas.hpp\"\n\n\/\/--------------------------------------------------------------------------------------------------------------------------------------------------------------\n#define MAXITR 1000\n#define BALLSIZE 100000.0\n\n\/\/--------------------------------------------------------------------------------------------------------------------------------------------------------------\nint main(void) {\n std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();\n mjr::ramCanvas4c8b theRamCanvas = mjr::ramCanvas4c8b(1024*2, 1024*2, -1.9, 0.5, -1.2, 1.2);\n\n for(int x=0; x<theRamCanvas.getNumPixX(); x++) {\n for(int y=0; y<theRamCanvas.getNumPixY(); y++) {\n double xr = theRamCanvas.int2realX(x);\n double yr = theRamCanvas.int2realY(y);\n double zx = 0.0;\n double zy = 0.0;\n int count = 0;\n double dx = 0.0;\n double dy = 0.0;\n double tdx, tzx;\n while ((zx*zx+zy*zy<BALLSIZE) && (count<MAXITR)) {\n count++;\n tzx=zx*zx-zy*zy+xr;\n zy=2*zx*zy+yr;\n zx=tzx;\n tdx=2*(zx*dx-zy*dy)+1;\n dy=2*(zy*dx+zx*dy);\n dx=tdx;\n }\n if(count < MAXITR) {\n double dist = 0.5*log(zx*zx+zy*zy)*sqrt(zx*zx+zy*zy)\/sqrt(dx*dx+dy*dy);\n if(dist < 0.0000001)\n theRamCanvas.drawPoint(x, y, mjr::ramCanvas4c8b::colorType(255, 0, static_cast<mjr::ramCanvas4c8b::colorChanType>(count % 256)));\n }\n }\n }\n\n theRamCanvas.writeTGAfile(\"mandelbrot_distance_old.tga\");\n std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;\n std::cout << \"Total Runtime \" << runTime.count() << \" sec\" << std::endl;\n}\n\/** @endcond *\/\n<commit_msg>Removed mandelbrot_distance_old.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: VColumn.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: hr $ $Date: 2001-10-16 18:14:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::sdbcx;\nusing namespace cppu;\nusing namespace connectivity;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\/\/ using namespace ::com::sun::star::sdbc;\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)\n{\n if(isNew())\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VColumnDescription\");\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VColumn\");\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)\n{\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);\n if(isNew())\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.ColumnDescription\");\n else\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.Column\");\n\n return aSupported;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)\n{\n Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());\n const ::rtl::OUString* pSupported = aSupported.getConstArray();\n const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();\n for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)\n ;\n\n return pSupported != pEnd;\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::OColumn(sal_Bool _bCase) : OColumnDescriptor_BASE(m_aMutex)\n , ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)\n , m_Precision(0)\n , m_Type(0)\n , m_Scale(0)\n , m_IsNullable(sal_True)\n , m_IsAutoIncrement(sal_False)\n , m_IsRowVersion(sal_False)\n , m_IsCurrency(sal_False)\n{\n construct();\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::OColumn( const ::rtl::OUString& _Name,\n const ::rtl::OUString& _TypeName,\n const ::rtl::OUString& _DefaultValue,\n sal_Int32 _IsNullable,\n sal_Int32 _Precision,\n sal_Int32 _Scale,\n sal_Int32 _Type,\n sal_Bool _IsAutoIncrement,\n sal_Bool _IsRowVersion,\n sal_Bool _IsCurrency,\n sal_Bool _bCase)\n : OColumnDescriptor_BASE(m_aMutex)\n , ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)\n , m_TypeName(_TypeName)\n , m_DefaultValue(_DefaultValue)\n , m_Precision(_Precision)\n , m_Type(_Type)\n , m_Scale(_Scale)\n , m_IsNullable(_IsNullable)\n , m_IsAutoIncrement(_IsAutoIncrement)\n , m_IsRowVersion(_IsRowVersion)\n , m_IsCurrency(_IsCurrency)\n{\n m_Name = _Name;\n\n construct();\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::~OColumn()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 _nId) const\n{\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;\n describeProperties(aProps);\n changePropertyAttributte(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/ -----------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()\n{\n return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::acquire() throw()\n{\n OColumnDescriptor_BASE::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::release() throw()\n{\n OColumnDescriptor_BASE::release();\n}\n\/\/ -----------------------------------------------------------------------------\nAny SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)\n{\n Any aRet = ODescriptor::queryInterface( rType);\n if(!aRet.hasValue())\n {\n if(!isNew())\n aRet = OColumn_BASE::queryInterface(rType);\n if(!aRet.hasValue())\n aRet = OColumnDescriptor_BASE::queryInterface( rType);\n }\n return aRet;\n}\n\/\/ -------------------------------------------------------------------------\nSequence< Type > SAL_CALL OColumn::getTypes( ) throw(RuntimeException)\n{\n if(isNew())\n return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());\n\n return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OColumn::construct()\n{\n ODescriptor::construct();\n\n sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;\n\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME), PROPERTY_ID_TYPENAME, nAttrib,&m_TypeName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION), PROPERTY_ID_DESCRIPTION, nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), PROPERTY_ID_DEFAULTVALUE, nAttrib,&m_DefaultValue, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION), PROPERTY_ID_PRECISION, nAttrib,&m_Precision, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), PROPERTY_ID_SCALE, nAttrib,&m_Scale, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE), PROPERTY_ID_ISNULLABLE, nAttrib,&m_IsNullable, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT), PROPERTY_ID_ISAUTOINCREMENT, nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISROWVERSION), PROPERTY_ID_ISROWVERSION, nAttrib,&m_IsRowVersion, ::getBooleanCppuType());\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY), PROPERTY_ID_ISCURRENCY, nAttrib,&m_IsCurrency, ::getBooleanCppuType());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OColumn::disposing(void)\n{\n OPropertySetHelper::disposing();\n\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);\n\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > SAL_CALL OColumn::createDataDescriptor( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);\n\n\n OColumn* pNewColumn = new OColumn( m_Name,\n m_TypeName,\n m_DefaultValue,\n m_IsNullable,\n m_Precision,\n m_Scale,\n m_Type,\n m_IsAutoIncrement,\n m_IsRowVersion,\n m_IsCurrency,\n isCaseSensitive());\n pNewColumn->m_Description = m_Description;\n pNewColumn->setNew(sal_True);\n return pNewColumn;\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OColumn::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ XNamed\n::rtl::OUString SAL_CALL OColumn::getName( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return m_Name;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)\n{\n m_Name = aName;\n}\n\/\/ -----------------------------------------------------------------------------\n\n<commit_msg>INTEGRATION: CWS dba07 (1.13.92); FILE MERGED 2003\/05\/28 09:23:50 oj 1.13.92.1: #109965# initial value was false<commit_after>\/*************************************************************************\n *\n * $RCSfile: VColumn.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: vg $ $Date: 2003-06-06 10:51:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_\n#include <com\/sun\/star\/sdbc\/ColumnValue.hpp>\n#endif\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::sdbcx;\nusing namespace cppu;\nusing namespace connectivity;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::sdbc;\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)\n{\n if(isNew())\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VColumnDescription\");\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VColumn\");\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)\n{\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);\n if(isNew())\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.ColumnDescription\");\n else\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.Column\");\n\n return aSupported;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)\n{\n Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());\n const ::rtl::OUString* pSupported = aSupported.getConstArray();\n const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();\n for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)\n ;\n\n return pSupported != pEnd;\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::OColumn(sal_Bool _bCase) : OColumnDescriptor_BASE(m_aMutex)\n , ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)\n , m_Precision(0)\n , m_Type(0)\n , m_Scale(0)\n , m_IsNullable(ColumnValue::NULLABLE)\n , m_IsAutoIncrement(sal_False)\n , m_IsRowVersion(sal_False)\n , m_IsCurrency(sal_False)\n{\n construct();\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::OColumn( const ::rtl::OUString& _Name,\n const ::rtl::OUString& _TypeName,\n const ::rtl::OUString& _DefaultValue,\n sal_Int32 _IsNullable,\n sal_Int32 _Precision,\n sal_Int32 _Scale,\n sal_Int32 _Type,\n sal_Bool _IsAutoIncrement,\n sal_Bool _IsRowVersion,\n sal_Bool _IsCurrency,\n sal_Bool _bCase)\n : OColumnDescriptor_BASE(m_aMutex)\n , ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)\n , m_TypeName(_TypeName)\n , m_DefaultValue(_DefaultValue)\n , m_Precision(_Precision)\n , m_Type(_Type)\n , m_Scale(_Scale)\n , m_IsNullable(_IsNullable)\n , m_IsAutoIncrement(_IsAutoIncrement)\n , m_IsRowVersion(_IsRowVersion)\n , m_IsCurrency(_IsCurrency)\n{\n m_Name = _Name;\n\n construct();\n}\n\/\/ -------------------------------------------------------------------------\nOColumn::~OColumn()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 _nId) const\n{\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;\n describeProperties(aProps);\n changePropertyAttributte(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/ -----------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()\n{\n return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::acquire() throw()\n{\n OColumnDescriptor_BASE::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::release() throw()\n{\n OColumnDescriptor_BASE::release();\n}\n\/\/ -----------------------------------------------------------------------------\nAny SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)\n{\n Any aRet = ODescriptor::queryInterface( rType);\n if(!aRet.hasValue())\n {\n if(!isNew())\n aRet = OColumn_BASE::queryInterface(rType);\n if(!aRet.hasValue())\n aRet = OColumnDescriptor_BASE::queryInterface( rType);\n }\n return aRet;\n}\n\/\/ -------------------------------------------------------------------------\nSequence< Type > SAL_CALL OColumn::getTypes( ) throw(RuntimeException)\n{\n if(isNew())\n return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());\n\n return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OColumn::construct()\n{\n ODescriptor::construct();\n\n sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;\n\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME), PROPERTY_ID_TYPENAME, nAttrib,&m_TypeName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION), PROPERTY_ID_DESCRIPTION, nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), PROPERTY_ID_DEFAULTVALUE, nAttrib,&m_DefaultValue, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION), PROPERTY_ID_PRECISION, nAttrib,&m_Precision, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), PROPERTY_ID_SCALE, nAttrib,&m_Scale, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE), PROPERTY_ID_ISNULLABLE, nAttrib,&m_IsNullable, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT), PROPERTY_ID_ISAUTOINCREMENT, nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISROWVERSION), PROPERTY_ID_ISROWVERSION, nAttrib,&m_IsRowVersion, ::getBooleanCppuType());\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY), PROPERTY_ID_ISCURRENCY, nAttrib,&m_IsCurrency, ::getBooleanCppuType());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OColumn::disposing(void)\n{\n OPropertySetHelper::disposing();\n\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);\n\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > SAL_CALL OColumn::createDataDescriptor( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);\n\n\n OColumn* pNewColumn = new OColumn( m_Name,\n m_TypeName,\n m_DefaultValue,\n m_IsNullable,\n m_Precision,\n m_Scale,\n m_Type,\n m_IsAutoIncrement,\n m_IsRowVersion,\n m_IsCurrency,\n isCaseSensitive());\n pNewColumn->m_Description = m_Description;\n pNewColumn->setNew(sal_True);\n return pNewColumn;\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OColumn::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ XNamed\n::rtl::OUString SAL_CALL OColumn::getName( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return m_Name;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OColumn::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)\n{\n m_Name = aName;\n}\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef SDD_CG_HPP\n#define SDD_CG_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <cmath>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include <amgcl\/amgcl.hpp>\n#include <amgcl\/backend\/builtin.hpp>\n#include <amgcl\/adapter\/crs_tuple.hpp>\n#include <amgcl\/coarsening\/plain_aggregates.hpp>\n#include <amgcl\/coarsening\/smoothed_aggregation.hpp>\n#include <amgcl\/relaxation\/spai0.hpp>\n#include <amgcl\/solver\/bicgstabl.hpp>\n#include <amgcl\/mpi\/deflation.hpp>\n#include <amgcl\/profiler.hpp>\n\n#include \"domain_partition.hpp\"\n\n#define CONVECTION\n\nstruct linear_deflation {\n long n;\n double h;\n std::vector<long> idx;\n\n linear_deflation(long n) : n(n), h(1.0 \/ (n - 1)), idx(n * n) {}\n\n size_t dim() const { return 3; }\n\n double operator()(long i, int j) const {\n switch(j) {\n case 1:\n return h * (idx[i] % n);\n case 2:\n return h * (idx[i] \/ n);\n case 0:\n default:\n return 1;\n }\n }\n};\n\nint main(int argc, char *argv[]) {\n boost::mpi::environment env;\n boost::mpi::communicator world;\n\n const long n = argc > 1 ? atoi(argv[1]) : 1024;\n const long n2 = n * n;\n\n boost::array<long, 2> lo = { {0, 0} };\n boost::array<long, 2> hi = { {n - 1, n - 1} };\n\n amgcl::profiler<> prof;\n\n prof.tic(\"partition\");\n domain_partition<2> part(lo, hi, world.size());\n const long chunk = part.size( world.rank() );\n\n std::vector<long> domain(world.size() + 1);\n all_gather(world, chunk, &domain[1]);\n boost::partial_sum(domain, domain.begin());\n\n const long chunk_start = domain[world.rank()];\n const long chunk_end = domain[world.rank() + 1];\n\n linear_deflation lindef(n);\n std::vector<long> renum(n2);\n for(long j = 0, idx = 0; j < n; ++j) {\n for(long i = 0; i < n; ++i, ++idx) {\n boost::array<long, 2> p = {{i, j}};\n std::pair<int,long> v = part.index(p);\n renum[idx] = domain[v.first] + v.second;\n lindef.idx[renum[idx]] = idx;\n }\n }\n prof.toc(\"partition\");\n\n prof.tic(\"assemble\");\n std::vector<long> ptr;\n std::vector<long> col;\n std::vector<double> val;\n std::vector<double> rhs;\n\n ptr.reserve(chunk + 1);\n col.reserve(chunk * 5);\n val.reserve(chunk * 5);\n rhs.reserve(chunk);\n\n ptr.push_back(0);\n\n const double hinv = (n - 1);\n const double h2i = (n - 1) * (n - 1);\n for(long j = 0, idx = 0; j < n; ++j) {\n for(long i = 0; i < n; ++i, ++idx) {\n if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;\n\n if (j > 0) {\n col.push_back(renum[idx - n]);\n val.push_back(-h2i);\n }\n\n if (i > 0) {\n col.push_back(renum[idx - 1]);\n val.push_back(-h2i\n#ifdef CONVECTION\n - hinv\n#endif\n );\n }\n\n col.push_back(renum[idx]);\n val.push_back(4 * h2i\n#ifdef CONVECTION\n + hinv\n#endif\n );\n\n if (i + 1 < n) {\n col.push_back(renum[idx + 1]);\n val.push_back(-h2i);\n }\n\n if (j + 1 < n) {\n col.push_back(renum[idx + n]);\n val.push_back(-h2i);\n }\n\n rhs.push_back(1);\n ptr.push_back( col.size() );\n }\n }\n prof.toc(\"assemble\");\n\n prof.tic(\"setup\");\n typedef amgcl::mpi::subdomain_deflation<\n amgcl::backend::builtin<double>,\n amgcl::coarsening::smoothed_aggregation<\n amgcl::coarsening::plain_aggregates\n >,\n amgcl::relaxation::spai0,\n amgcl::solver::bicgstabl\n > Solver;\n\n typename Solver::AMG_params amg_prm;\n typename Solver::Solver_params slv_prm(2);\n Solver solve(world,\n boost::tie(chunk, ptr, col, val),\n lindef,\n amg_prm, slv_prm\n );\n prof.toc(\"setup\");\n\n prof.tic(\"solve\");\n std::vector<double> x(chunk, 0);\n size_t iters;\n double resid;\n boost::tie(iters, resid) = solve(rhs, x);\n prof.toc(\"solve\");\n\n prof.tic(\"save\");\n if (world.rank() == 0) {\n std::vector<double> X(n2);\n boost::copy(x, X.begin());\n\n for(int i = 1; i < world.size(); ++i)\n world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]);\n\n std::ofstream f(\"out.dat\", std::ios::binary);\n int m = n2;\n f.write((char*)&m, sizeof(int));\n for(long i = 0; i < n2; ++i)\n f.write((char*)&X[renum[i]], sizeof(double));\n } else {\n world.send(0, 42, x.data(), chunk);\n }\n prof.toc(\"save\");\n\n if (world.rank() == 0) {\n std::cout\n << \"Iterations: \" << iters << std::endl\n << \"Error: \" << resid << std::endl\n << std::endl\n << prof << std::endl;\n }\n}\n\n#endif\n<commit_msg>Add recirculation example into sibdomain_deflation.cpp<commit_after>#ifndef SDD_CG_HPP\n#define SDD_CG_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <cmath>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include <amgcl\/amgcl.hpp>\n#include <amgcl\/backend\/builtin.hpp>\n#include <amgcl\/adapter\/crs_tuple.hpp>\n#include <amgcl\/coarsening\/plain_aggregates.hpp>\n#include <amgcl\/coarsening\/smoothed_aggregation.hpp>\n#include <amgcl\/relaxation\/spai0.hpp>\n#include <amgcl\/solver\/bicgstabl.hpp>\n#include <amgcl\/mpi\/deflation.hpp>\n#include <amgcl\/profiler.hpp>\n\n#include \"domain_partition.hpp\"\n\n#define CONVECTION\n#define RECIRCULATION\n\nstruct linear_deflation {\n long n;\n double h;\n std::vector<long> idx;\n\n linear_deflation(long n) : n(n), h(1.0 \/ (n - 1)), idx(n * n) {}\n\n size_t dim() const { return 3; }\n\n double operator()(long i, int j) const {\n switch(j) {\n case 1:\n return h * (idx[i] % n);\n case 2:\n return h * (idx[i] \/ n);\n case 0:\n default:\n return 1;\n }\n }\n};\n\nint main(int argc, char *argv[]) {\n boost::mpi::environment env;\n boost::mpi::communicator world;\n\n const long n = argc > 1 ? atoi(argv[1]) : 1024;\n const long n2 = n * n;\n\n boost::array<long, 2> lo = { {0, 0} };\n boost::array<long, 2> hi = { {n - 1, n - 1} };\n\n amgcl::profiler<> prof;\n\n prof.tic(\"partition\");\n domain_partition<2> part(lo, hi, world.size());\n const long chunk = part.size( world.rank() );\n\n std::vector<long> domain(world.size() + 1);\n all_gather(world, chunk, &domain[1]);\n boost::partial_sum(domain, domain.begin());\n\n const long chunk_start = domain[world.rank()];\n const long chunk_end = domain[world.rank() + 1];\n\n linear_deflation lindef(n);\n std::vector<long> renum(n2);\n for(long j = 0, idx = 0; j < n; ++j) {\n for(long i = 0; i < n; ++i, ++idx) {\n boost::array<long, 2> p = {{i, j}};\n std::pair<int,long> v = part.index(p);\n renum[idx] = domain[v.first] + v.second;\n lindef.idx[renum[idx]] = idx;\n }\n }\n prof.toc(\"partition\");\n\n prof.tic(\"assemble\");\n std::vector<long> ptr;\n std::vector<long> col;\n std::vector<double> val;\n std::vector<double> rhs;\n\n ptr.reserve(chunk + 1);\n col.reserve(chunk * 5);\n val.reserve(chunk * 5);\n rhs.reserve(chunk);\n\n ptr.push_back(0);\n\n const double hinv = (n - 1);\n const double h = 1 \/ hinv;\n const double h2i = (n - 1) * (n - 1);\n#ifdef RECIRCULATION\n const double eps = 1e-2;\n\n for(long j = 0, idx = 0; j < n; ++j) {\n double y = h * j;\n for(long i = 0; i < n; ++i, ++idx) {\n double x = h * i;\n\n if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;\n\n if (i == 0 || j == 0 || i + 1 == n || j + 1 == n) {\n col.push_back(renum[idx]);\n val.push_back(1);\n rhs.push_back(\n sin(M_PI * x) + sin(M_PI * y) +\n sin(13 * M_PI * x) + sin(13 * M_PI * y)\n );\n } else {\n double a = -sin(M_PI * x) * cos(M_PI * y) * hinv;\n double b = sin(M_PI * y) * cos(M_PI * x) * hinv;\n\n if (j > 0) {\n col.push_back(renum[idx - n]);\n val.push_back(-eps * h2i - std::max(b, 0.0));\n }\n\n if (i > 0) {\n col.push_back(renum[idx - 1]);\n val.push_back(-eps * h2i - std::max(a, 0.0));\n }\n\n col.push_back(renum[idx]);\n val.push_back(4 * eps * h2i + fabs(a) + fabs(b));\n\n if (i + 1 < n) {\n col.push_back(renum[idx + 1]);\n val.push_back(-eps * h2i + std::min(a, 0.0));\n }\n\n if (j + 1 < n) {\n col.push_back(renum[idx + n]);\n val.push_back(-eps * h2i + std::min(b, 0.0));\n }\n\n rhs.push_back(1.0);\n }\n ptr.push_back( col.size() );\n }\n }\n#else\n for(long j = 0, idx = 0; j < n; ++j) {\n for(long i = 0; i < n; ++i, ++idx) {\n if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue;\n\n if (j > 0) {\n col.push_back(renum[idx - n]);\n val.push_back(-h2i);\n }\n\n if (i > 0) {\n col.push_back(renum[idx - 1]);\n val.push_back(-h2i - hinv);\n }\n\n col.push_back(renum[idx]);\n val.push_back(4 * h2i + hinv);\n\n if (i + 1 < n) {\n col.push_back(renum[idx + 1]);\n val.push_back(-h2i);\n }\n\n if (j + 1 < n) {\n col.push_back(renum[idx + n]);\n val.push_back(-h2i);\n }\n\n rhs.push_back(1);\n ptr.push_back( col.size() );\n }\n }\n#endif\n prof.toc(\"assemble\");\n\n prof.tic(\"setup\");\n typedef amgcl::mpi::subdomain_deflation<\n amgcl::backend::builtin<double>,\n amgcl::coarsening::smoothed_aggregation<\n amgcl::coarsening::plain_aggregates\n >,\n amgcl::relaxation::spai0,\n amgcl::solver::bicgstabl\n > Solver;\n\n typename Solver::AMG_params amg_prm;\n typename Solver::Solver_params slv_prm(2);\n Solver solve(world,\n boost::tie(chunk, ptr, col, val),\n lindef,\n amg_prm, slv_prm\n );\n prof.toc(\"setup\");\n\n prof.tic(\"solve\");\n std::vector<double> x(chunk, 0);\n size_t iters;\n double resid;\n boost::tie(iters, resid) = solve(rhs, x);\n prof.toc(\"solve\");\n\n prof.tic(\"save\");\n if (world.rank() == 0) {\n std::vector<double> X(n2);\n boost::copy(x, X.begin());\n\n for(int i = 1; i < world.size(); ++i)\n world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]);\n\n std::ofstream f(\"out.dat\", std::ios::binary);\n int m = n2;\n f.write((char*)&m, sizeof(int));\n for(long i = 0; i < n2; ++i)\n f.write((char*)&X[renum[i]], sizeof(double));\n } else {\n world.send(0, 42, x.data(), chunk);\n }\n prof.toc(\"save\");\n\n if (world.rank() == 0) {\n std::cout\n << \"Iterations: \" << iters << std::endl\n << \"Error: \" << resid << std::endl\n << std::endl\n << prof << std::endl;\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <bitcoin\/client\/watcher.hpp>\n\n\/**\n * Command-line interface to the wallet watcher service.\n *\/\nclass cli\n{\npublic:\n ~cli();\n cli();\n\n int run();\n\nprivate:\n void cmd_exit();\n void cmd_help();\n void cmd_connect(std::stringstream& args);\n void cmd_disconnect(std::stringstream& args);\n void cmd_watch(std::stringstream& args);\n void cmd_height();\n void cmd_tx_height(std::stringstream& args);\n void cmd_tx_watch(std::stringstream& args);\n void cmd_prioritize(std::stringstream& args);\n void cmd_utxos(std::stringstream& args);\n void cmd_save(std::stringstream& args);\n void cmd_load(std::stringstream& args);\n\n void callback(const libbitcoin::transaction_type& tx);\n\n bc::hash_digest read_txid(std::stringstream& args);\n bool read_address(std::stringstream& args, bc::payment_address& out);\n bool read_filename(std::stringstream& args, std::string& out);\n\n libwallet::watcher watcher;\n bool done_;\n};\n\ncli::~cli()\n{\n}\n\ncli::cli()\n : done_(false)\n{\n libwallet::watcher::callback cb =\n [this](const libbitcoin::transaction_type& tx)\n {\n callback(tx);\n };\n watcher.set_callback(cb);\n}\n\nint cli::run()\n{\n while (!done_)\n {\n std::cout << \"> \" << std::flush;\n\n char line[1000];\n std::cin.getline(line, sizeof(line));\n std::stringstream reader(line);\n std::string command;\n reader >> command;\n\n if (command == \"exit\") cmd_exit();\n else if (command == \"help\") cmd_help();\n else if (command == \"connect\") cmd_connect(reader);\n else if (command == \"disconnect\") cmd_disconnect(reader);\n else if (command == \"watch\") cmd_watch(reader);\n else if (command == \"height\") cmd_height();\n else if (command == \"txheight\") cmd_tx_height(reader);\n else if (command == \"txwatch\") cmd_tx_watch(reader);\n else if (command == \"prioritize\") cmd_prioritize(reader);\n else if (command == \"utxos\") cmd_utxos(reader);\n else if (command == \"save\") cmd_save(reader);\n else if (command == \"load\") cmd_load(reader);\n else\n std::cout << \"unknown command \" << command << std::endl;\n }\n return 0;\n}\n\nvoid cli::cmd_exit()\n{\n std::cout << \"waiting for thread to stop...\" << std::endl;\n done_ = true;\n}\n\nvoid cli::cmd_help()\n{\n std::cout << \"commands:\" << std::endl;\n std::cout << \" exit - leave the program\" << std::endl;\n std::cout << \" help - this menu\" << std::endl;\n std::cout << \" connect <server> - connect to obelisk server\" << std::endl;\n std::cout << \" disconnect - stop talking to the obelisk server\" << std::endl;\n std::cout << \" watch <address> - watch an address\" << std::endl;\n std::cout << \" prioritize [<address>] - check an address more frequently\" << std::endl;\n std::cout << \" utxos <address> - get utxos for an address\" << std::endl;\n std::cout << \" save <filename> - dump the database to disk\" << std::endl;\n std::cout << \" load <filename> - load the database from disk\" << std::endl;\n}\n\nvoid cli::cmd_connect(std::stringstream& args)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no server given\" << std::endl;\n return;\n }\n std::cout << \"connecting to \" << arg << std::endl;\n\n watcher.connect(arg);\n}\n\nvoid cli::cmd_disconnect(std::stringstream& args)\n{\n watcher.disconnect();\n}\n\nvoid cli::cmd_height()\n{\n std::cout << watcher.get_last_block_height() << std::endl;\n}\n\nvoid cli::cmd_tx_height(std::stringstream& args)\n{\n bc::hash_digest txid = read_txid(args);\n if (txid == bc::null_hash)\n return;\n std::cout << watcher.get_tx_height(txid) << std::endl;\n}\n\nvoid cli::cmd_tx_watch(std::stringstream& args)\n{\n bc::hash_digest txid = read_txid(args);\n if (txid == bc::null_hash)\n return;\n watcher.watch_tx_mem(txid);\n}\n\nvoid cli::cmd_watch(std::stringstream& args)\n{\n bc::payment_address address;\n if (!read_address(args, address))\n return;\n watcher.watch_address(address);\n}\n\nvoid cli::cmd_prioritize(std::stringstream& args)\n{\n bc::payment_address address;\n std::string arg;\n args >> arg;\n if (arg.size())\n address.set_encoded(arg);\n watcher.prioritize_address(address);\n}\n\nvoid cli::cmd_utxos(std::stringstream& args)\n{\n bc::payment_address address;\n if (!read_address(args, address))\n return;\n\n auto list = watcher.get_utxos(address);\n for (auto& utxo: list)\n std::cout << bc::encode_hex(utxo.point.hash) << \":\" <<\n utxo.point.index << std::endl;\n}\n\nvoid cli::cmd_save(std::stringstream& args)\n{\n std::string filename;\n if (!read_filename(args, filename))\n return;\n\n std::ofstream file(filename);\n if (!file.is_open())\n {\n std::cerr << \"cannot open \" << filename << std::endl;\n return;\n }\n\n auto db = watcher.serialize();\n file.write(reinterpret_cast<const char*>(db.data()), db.size());\n file.close();\n}\n\nvoid cli::cmd_load(std::stringstream& args)\n{\n std::string filename;\n if (!read_filename(args, filename))\n return;\n\n std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);\n if (!file.is_open())\n {\n std::cerr << \"cannot open \" << filename << std::endl;\n return;\n }\n\n std::streampos size = file.tellg();\n uint8_t *data = new uint8_t[size];\n file.seekg(0, std::ios::beg);\n file.read(reinterpret_cast<char*>(data), size);\n file.close();\n\n if (!watcher.load(bc::data_chunk(data, data + size)))\n std::cerr << \"error while loading data\" << std::endl;\n}\n\nvoid cli::callback(const libbitcoin::transaction_type& tx)\n{\n auto txid = libbitcoin::encode_hex(libbitcoin::hash_transaction(tx));\n std::cout << \"got transaction \" << txid << std::endl;\n}\n\nbc::hash_digest cli::read_txid(std::stringstream& args)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no txid given\" << std::endl;\n return bc::null_hash;\n }\n return bc::decode_hash(arg);\n}\n\nbool cli::read_address(std::stringstream& args, bc::payment_address& out)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no address given\" << std::endl;\n return false;\n }\n\n if (!out.set_encoded(arg))\n {\n std::cout << \"invalid address \" << arg << std::endl;\n return false;\n }\n return true;\n}\n\nbool cli::read_filename(std::stringstream& args, std::string& out)\n{\n args >> out;\n if (!out.size())\n {\n std::cout << \"no file name given\" << std::endl;\n return false;\n }\n return true;\n}\n\nint main()\n{\n cli c;\n std::cout << \"type \\\"help\\\" for instructions\" << std::endl;\n return c.run();\n}\n<commit_msg>Make some simple watcher example cleanups<commit_after>#include <iostream>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <bitcoin\/client\/watcher.hpp>\n\n\/**\n * Command-line interface to the wallet watcher service.\n *\/\nclass cli\n{\npublic:\n ~cli();\n cli();\n\n int run();\n\nprivate:\n void cmd_exit();\n void cmd_help();\n void cmd_connect(std::stringstream& args);\n void cmd_disconnect(std::stringstream& args);\n void cmd_watch(std::stringstream& args);\n void cmd_height();\n void cmd_tx_height(std::stringstream& args);\n void cmd_tx_watch(std::stringstream& args);\n void cmd_prioritize(std::stringstream& args);\n void cmd_utxos(std::stringstream& args);\n void cmd_save(std::stringstream& args);\n void cmd_load(std::stringstream& args);\n\n void callback(const libbitcoin::transaction_type& tx);\n\n bc::hash_digest read_txid(std::stringstream& args);\n bool read_address(std::stringstream& args, bc::payment_address& out);\n bool read_filename(std::stringstream& args, std::string& out);\n\n libwallet::watcher watcher;\n bool done_;\n};\n\ncli::~cli()\n{\n}\n\ncli::cli()\n : done_(false)\n{\n libwallet::watcher::callback cb =\n [this](const libbitcoin::transaction_type& tx)\n {\n callback(tx);\n };\n watcher.set_callback(cb);\n}\n\nint cli::run()\n{\n std::cout << \"type \\\"help\\\" for instructions\" << std::endl;\n\n while (!done_)\n {\n \/\/ Read a line:\n std::cout << \"> \" << std::flush;\n char line[1000];\n std::cin.getline(line, sizeof(line));\n\n \/\/ Extract the command:\n std::stringstream reader(line);\n std::string command;\n reader >> command;\n\n if (command == \"exit\") cmd_exit();\n else if (command == \"help\") cmd_help();\n else if (command == \"connect\") cmd_connect(reader);\n else if (command == \"disconnect\") cmd_disconnect(reader);\n else if (command == \"watch\") cmd_watch(reader);\n else if (command == \"height\") cmd_height();\n else if (command == \"txheight\") cmd_tx_height(reader);\n else if (command == \"txwatch\") cmd_tx_watch(reader);\n else if (command == \"prioritize\") cmd_prioritize(reader);\n else if (command == \"utxos\") cmd_utxos(reader);\n else if (command == \"save\") cmd_save(reader);\n else if (command == \"load\") cmd_load(reader);\n else\n std::cout << \"unknown command \" << command << std::endl;\n }\n return 0;\n}\n\nvoid cli::cmd_exit()\n{\n std::cout << \"waiting for thread to stop...\" << std::endl;\n done_ = true;\n}\n\nvoid cli::cmd_help()\n{\n std::cout << \"commands:\" << std::endl;\n std::cout << \" exit - leave the program\" << std::endl;\n std::cout << \" help - this menu\" << std::endl;\n std::cout << \" connect <server> - connect to obelisk server\" << std::endl;\n std::cout << \" disconnect - stop talking to the obelisk server\" << std::endl;\n std::cout << \" watch <address> - watch an address\" << std::endl;\n std::cout << \" prioritize [<address>] - check an address more frequently\" << std::endl;\n std::cout << \" utxos <address> - get utxos for an address\" << std::endl;\n std::cout << \" save <filename> - dump the database to disk\" << std::endl;\n std::cout << \" load <filename> - load the database from disk\" << std::endl;\n}\n\nvoid cli::cmd_connect(std::stringstream& args)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no server given\" << std::endl;\n return;\n }\n std::cout << \"connecting to \" << arg << std::endl;\n\n watcher.connect(arg);\n}\n\nvoid cli::cmd_disconnect(std::stringstream& args)\n{\n watcher.disconnect();\n}\n\nvoid cli::cmd_height()\n{\n std::cout << watcher.get_last_block_height() << std::endl;\n}\n\nvoid cli::cmd_tx_height(std::stringstream& args)\n{\n bc::hash_digest txid = read_txid(args);\n if (txid == bc::null_hash)\n return;\n std::cout << watcher.get_tx_height(txid) << std::endl;\n}\n\nvoid cli::cmd_tx_watch(std::stringstream& args)\n{\n bc::hash_digest txid = read_txid(args);\n if (txid == bc::null_hash)\n return;\n watcher.watch_tx_mem(txid);\n}\n\nvoid cli::cmd_watch(std::stringstream& args)\n{\n bc::payment_address address;\n if (!read_address(args, address))\n return;\n watcher.watch_address(address);\n}\n\nvoid cli::cmd_prioritize(std::stringstream& args)\n{\n bc::payment_address address;\n std::string arg;\n args >> arg;\n if (arg.size())\n address.set_encoded(arg);\n watcher.prioritize_address(address);\n}\n\nvoid cli::cmd_utxos(std::stringstream& args)\n{\n bc::payment_address address;\n if (!read_address(args, address))\n return;\n\n auto list = watcher.get_utxos(address);\n for (auto& utxo: list)\n std::cout << bc::encode_hex(utxo.point.hash) << \":\" <<\n utxo.point.index << std::endl;\n}\n\nvoid cli::cmd_save(std::stringstream& args)\n{\n std::string filename;\n if (!read_filename(args, filename))\n return;\n\n std::ofstream file(filename);\n if (!file.is_open())\n {\n std::cerr << \"cannot open \" << filename << std::endl;\n return;\n }\n\n auto db = watcher.serialize();\n file.write(reinterpret_cast<const char*>(db.data()), db.size());\n file.close();\n}\n\nvoid cli::cmd_load(std::stringstream& args)\n{\n std::string filename;\n if (!read_filename(args, filename))\n return;\n\n std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);\n if (!file.is_open())\n {\n std::cerr << \"cannot open \" << filename << std::endl;\n return;\n }\n\n std::streampos size = file.tellg();\n uint8_t *data = new uint8_t[size];\n file.seekg(0, std::ios::beg);\n file.read(reinterpret_cast<char*>(data), size);\n file.close();\n\n if (!watcher.load(bc::data_chunk(data, data + size)))\n std::cerr << \"error while loading data\" << std::endl;\n}\n\nvoid cli::callback(const libbitcoin::transaction_type& tx)\n{\n auto txid = libbitcoin::encode_hex(libbitcoin::hash_transaction(tx));\n std::cout << \"got transaction \" << txid << std::endl;\n}\n\nbc::hash_digest cli::read_txid(std::stringstream& args)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no txid given\" << std::endl;\n return bc::null_hash;\n }\n return bc::decode_hash(arg);\n}\n\nbool cli::read_address(std::stringstream& args, bc::payment_address& out)\n{\n std::string arg;\n args >> arg;\n if (!arg.size())\n {\n std::cout << \"no address given\" << std::endl;\n return false;\n }\n\n if (!out.set_encoded(arg))\n {\n std::cout << \"invalid address \" << arg << std::endl;\n return false;\n }\n return true;\n}\n\nbool cli::read_filename(std::stringstream& args, std::string& out)\n{\n args >> out;\n if (!out.size())\n {\n std::cout << \"no file name given\" << std::endl;\n return false;\n }\n return true;\n}\n\nint main()\n{\n cli c;\n return c.run();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * logger_metrics_test.cc\n * Mich, 2014-11-17\n * Copyright (c) 2014 Datacratic Inc. All rights reserved.\n *\n * Manual test for the logger metrics. Provide the proper json config and\n * run.\n **\/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/smart_ptr.hpp>\n#include <boost\/thread\/barrier.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/regex.hpp>\n\n#include \"mongo\/bson\/bson.h\"\n#include \"mongo\/bson\/bsonobj.h\"\n#include \"mongo\/client\/dbclient.h\"\n#include \"jml\/utils\/filter_streams.h\"\n#include \"soa\/service\/testing\/mongo_temporary_server.h\"\n#include \"soa\/logger\/logger_metrics_interface.h\"\n\nusing namespace ML;\nusing namespace Datacratic;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( test_logger_metrics ) {\n Mongo::MongoTemporaryServer mongo;\n setenv(\"CONFIG\", \"soa\/logger\/testing\/logger_metrics_config.json\", 1);\n shared_ptr<ILoggerMetrics> logger =\n ILoggerMetrics::setup(\"metricsLogger\", \"lalmetrics\", \"test\");\n\n logger->logMeta({\"a\", \"b\"}, \"taratapom\");\n\n Json::Value config;\n filter_istream cfgStream(\"soa\/logger\/testing\/logger_metrics_config.json\");\n cfgStream >> config;\n\n Json::Value metricsLogger = config[\"metricsLogger\"];\n auto conn = std::make_shared<mongo::DBClientConnection>();\n conn->connect(metricsLogger[\"hostAndPort\"].asString());\n string err;\n if (!conn->auth(metricsLogger[\"database\"].asString(),\n metricsLogger[\"user\"].asString(),\n metricsLogger[\"pwd\"].asString(), err)) {\n throw ML::Exception(\"Failed to log to mongo tmp server: %s\",\n err.c_str());\n }\n\n BOOST_CHECK_EQUAL(conn->count(\"test.lalmetrics\"), 1);\n auto cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p.getFieldDotted(\"meta.a.b\").String(), \"taratapom\");\n }\n\n logger->logMetrics({\"fooValue\"}, 123);\n ML::sleep(1); \/\/ Leave time for async write\n cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p[\"metrics\"][\"fooValue\"].Number(), 123);\n }\n\n Json::Value block;\n block[\"alpha\"] = 1;\n block[\"beta\"] = 2;\n block[\"coco\"] = Json::objectValue;\n block[\"coco\"][\"sanchez\"] = 3;\n logger->logMetrics(block);\n ML::sleep(1); \/\/ Leave time for async write\n cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p[\"metrics\"][\"coco\"][\"sanchez\"].Number(), 3);\n }\n}\n<commit_msg>logger_metrics_test: use \"setupFromJson\"<commit_after>\/**\n * logger_metrics_test.cc\n * Mich, 2014-11-17\n * Copyright (c) 2014 Datacratic Inc. All rights reserved.\n *\n * Manual test for the logger metrics. Provide the proper json config and\n * run.\n **\/\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/smart_ptr.hpp>\n#include <boost\/thread\/barrier.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/regex.hpp>\n\n#include \"mongo\/bson\/bson.h\"\n#include \"mongo\/bson\/bsonobj.h\"\n#include \"mongo\/client\/dbclient.h\"\n#include \"jml\/utils\/filter_streams.h\"\n#include \"soa\/service\/testing\/mongo_temporary_server.h\"\n#include \"soa\/logger\/logger_metrics_interface.h\"\n\nusing namespace ML;\nusing namespace Datacratic;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( test_logger_metrics ) {\n Mongo::MongoTemporaryServer mongo;\n string filename(\"soa\/logger\/testing\/logger_metrics_config.json\");\n Json::Value config = Json::parseFromFile(filename);\n const Json::Value & metricsLogger = config[\"metricsLogger\"];\n auto logger = ILoggerMetrics::setupFromJson(metricsLogger,\n \"lalmetrics\", \"test\");\n\n logger->logMeta({\"a\", \"b\"}, \"taratapom\");\n\n auto conn = std::make_shared<mongo::DBClientConnection>();\n conn->connect(metricsLogger[\"hostAndPort\"].asString());\n string err;\n if (!conn->auth(metricsLogger[\"database\"].asString(),\n metricsLogger[\"user\"].asString(),\n metricsLogger[\"pwd\"].asString(), err)) {\n throw ML::Exception(\"Failed to log to mongo tmp server: %s\",\n err.c_str());\n }\n\n BOOST_CHECK_EQUAL(conn->count(\"test.lalmetrics\"), 1);\n auto cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p.getFieldDotted(\"meta.a.b\").String(), \"taratapom\");\n }\n\n logger->logMetrics({\"fooValue\"}, 123);\n ML::sleep(1); \/\/ Leave time for async write\n cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p[\"metrics\"][\"fooValue\"].Number(), 123);\n }\n\n Json::Value block;\n block[\"alpha\"] = 1;\n block[\"beta\"] = 2;\n block[\"coco\"] = Json::objectValue;\n block[\"coco\"][\"sanchez\"] = 3;\n logger->logMetrics(block);\n ML::sleep(1); \/\/ Leave time for async write\n cursor = conn->query(\"test.lalmetrics\", mongo::BSONObj());\n BOOST_CHECK(cursor->more());\n {\n mongo::BSONObj p = cursor->next();\n BOOST_CHECK_EQUAL(p[\"metrics\"][\"coco\"][\"sanchez\"].Number(), 3);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * GAMS - General Algebraic Modeling System C++ API\n *\n * Copyright (c) 2017-2022 GAMS Software GmbH <support@gams.com>\n * Copyright (c) 2017-2022 GAMS Development Corp. <support@gams.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"gams.h\"\n#include <iostream>\n#include <vector>\n\nusing namespace gams;\nusing namespace std;\n\n#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)\n\n\/\/\/ \\file transport10.cpp\n\/\/\/ \\brief This is the 10th model in a series of tutorial examples.\nint main()\n{\n cout << \"---------- Transport 10 --------------\" << endl;\n cout << \"Transport 10 is a Microsoft Windows only example.\" << endl;\n return 0;\n}\n\n#else\n\n#include <QAxObject>\n#include <Windows.h> \/\/ includes \"Ole2.h\" that includes \"objbase.h\" to access CoInitialize() and CoUninitialize()\n\nstring getModelText()\n{\n return \" Sets \\n\"\n \" i canning plants \\n\"\n \" j markets \\n\"\n \" \\n\"\n \" Parameters \\n\"\n \" a(i) capacity of plant i in cases \\n\"\n \" b(j) demand at market j in cases \\n\"\n \" d(i,j) distance in thousands of miles \\n\"\n \" Scalar f freight in dollars per case per thousand miles \/90\/; \\n\"\n \" \\n\"\n \"$if not set gdxincname $abort 'no include file name for data file provided'\\n\"\n \"$gdxin %gdxincname% \\n\"\n \"$load i j a b d \\n\"\n \"$gdxin \\n\"\n \" \\n\"\n \" Parameter c(i,j) transport cost in thousands of dollars per case ; \\n\"\n \" \\n\"\n \" c(i,j) = f * d(i,j) \/ 1000 ; \\n\"\n \" \\n\"\n \" Variables \\n\"\n \" x(i,j) shipment quantities in cases \\n\"\n \" z total transportation costs in thousands of dollars ; \\n\"\n \" \\n\"\n \" Positive Variable x ; \\n\"\n \" \\n\"\n \" Equations \\n\"\n \" cost define objective function \\n\"\n \" supply(i) observe supply limit at plant i \\n\"\n \" demand(j) satisfy demand at market j ; \\n\"\n \" \\n\"\n \" cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \\n\"\n \" \\n\"\n \" supply(i) .. sum(j, x(i,j)) =l= a(i) ; \\n\"\n \" \\n\"\n \" demand(j) .. sum(i, x(i,j)) =g= b(j) ; \\n\"\n \" \\n\"\n \" Model transport \/all\/ ; \\n\"\n \" \\n\"\n \" Solve transport using lp minimizing z ; \\n\"\n \" \\n\"\n \" Display x.l, x.m ; \\n\";\n}\n\n\/\/\/ Creates an 1 dimensional GAMSParameter and transfers data from an Excel sheet (horizontal ordered)\n\/\/\/\n\/\/\/ \\param sheets The sheets object of an open Excel workbook\n\/\/\/ \\param sheetName The name of the sheet to be read\n\/\/\/ \\param db The GAMSDatabase where the GAMSParameter is created in\n\/\/\/ \\param paramName The name of the new GAMSParameter\n\/\/\/ \\param paramText The explplanatory text of the new GAMSParameter\n\/\/\/ \\param set The GAMSSet for GAMSParameter dimension\n\/\/\/ \\return The new GAMSParameter in the GAMSDatabase\n\/\/\/\nGAMSParameter sheetToParameter(QAxObject* sheets, string sheetName\n , GAMSDatabase db, string paramName, string paramText, GAMSSet set)\n{\n QAxObject* sheet = sheets->querySubObject( \"Item( string )\", sheetName.c_str() );\n GAMSParameter param = db.addParameter(paramName, paramText, set);\n\n QAxObject* usedrange = sheet->querySubObject( \"UsedRange\");\n QAxObject * columns = usedrange->querySubObject(\"Columns\");\n int intCols = columns->property(\"Count\").toInt();\n\n for (int i = 1; i <= intCols; i++) {\n std::string name = sheet->querySubObject(\"Cells( int, int )\", 1, i)->dynamicCall(\"Value()\").toString().toStdString();\n double value = sheet->querySubObject(\"Cells( int, int )\", 2, i)->dynamicCall(\"Value()\").toDouble();\n set.addRecord(name);\n GAMSParameterRecord rec = param.addRecord(name);\n rec.setValue(value);\n }\n return param;\n}\n\n\/\/\/ Creates a 2 dimensional GAMSParameter and transfers data from an Excel sheet\n\/\/\/\n\/\/\/ \\param sheets The sheets object of an open Excel workbook\n\/\/\/ \\param sheetName The name of the sheet to be read\n\/\/\/ \\param db The GAMSDatabase where the GAMSParameter is created in\n\/\/\/ \\param paramName The name of the new GAMSParameter\n\/\/\/ \\param paramText The explplanatory text of the new GAMSParameter\n\/\/\/ \\param set1 The GAMSSet for first GAMSParameter dimension\n\/\/\/ \\param set2 The GAMSSet for second GAMSParameter dimension\n\/\/\/ \\return The new GAMSParameter in the GAMSDatabase\n\/\/\/\nGAMSParameter sheetToParameter(QAxObject* sheets, string sheetName\n , GAMSDatabase db, string paramName, string paramText, GAMSSet set1, GAMSSet set2)\n{\n QAxObject* sheet = sheets->querySubObject( \"Item( string )\", sheetName.c_str() );\n vector<GAMSDomain> sets {set1, set2};\n GAMSParameter param = db.addParameter(paramName, paramText, sets);\n\n QAxObject* usedrange = sheet->querySubObject( \"UsedRange\");\n QAxObject * columns = usedrange->querySubObject(\"Columns\");\n int intCols = columns->property(\"Count\").toInt();\n QAxObject * rows = usedrange->querySubObject(\"Rows\");\n int intRows = rows->property(\"Count\").toInt();\n\n for (int j = 2; j <= intCols; j++) {\n string namej = sheet->querySubObject(\"Cells( int, int )\", 1, j)->dynamicCall(\"Value()\").toString().toStdString();\n for (int i = 2; i <= intRows; ++i) {\n string namei = sheet->querySubObject(\"Cells( int, int )\", i, 1)->dynamicCall(\"Value()\").toString().toStdString();\n GAMSParameterRecord rec = param.addRecord(namei, namej);\n double value = sheet->querySubObject(\"Cells( int, int )\", i, j)->dynamicCall(\"Value()\").toDouble();\n rec.setValue(value);\n }\n }\n return param;\n}\n\n\/\/\/ \\file transport10.cpp\n\/\/\/ \\brief This is the 10th model in a series of tutorial examples.\n\/\/\/\n\/\/\/ Here we show:\n\/\/\/ - How to fill a GAMSDatabase by reading from MS Excel\nint main(int argc, char* argv[])\n{\n cout << \"---------- Transport 10 --------------\" << endl;\n try {\n ::CoInitialize(0); \/\/ initialize thread to use ActiveX (some systems may need CoInititializeEx)\n\n GAMSWorkspaceInfo wsInfo;\n if (argc > 1)\n wsInfo.setSystemDirectory(argv[1]);\n GAMSWorkspace ws(wsInfo);\n\n \/\/ Creating the GAMSDatabase and fill with the workbook data\n GAMSDatabase db = ws.addDatabase();\n QString fileName = QString::fromStdString(ws.systemDirectory())+ cPathSep + \"apifiles\" + cPathSep + \"Data\" + cPathSep + \"transport.xls\";\n\n QAxObject* excel = new QAxObject( \"Excel.Application\", 0 );\n QAxObject* workbooks = excel->querySubObject( \"Workbooks\" );\n QAxObject* workbook = workbooks->querySubObject( \"Open(const QString&)\", fileName );\n QAxObject* sheets = workbook->querySubObject( \"Worksheets\" );\n\n GAMSSet i = db.addSet(\"i\", 1, \"Plants\");\n GAMSSet j = db.addSet(\"j\", 1, \"Markets\");\n\n \/\/ read parameters\n sheetToParameter(sheets, \"capacity\", db, \"a\", \"Capacity\", i);\n sheetToParameter(sheets, \"demand\", db, \"b\", \"Demand\", j);\n sheetToParameter(sheets, \"distance\", db, \"d\", \"Distance\", i, j);\n\n \/\/ clean up and close up\n workbook->dynamicCall(\"Close()\");\n excel->dynamicCall(\"Quit()\");\n\n\n \/\/ Create and run the GAMSJob\n GAMSOptions opt = ws.addOptions();\n GAMSJob t10 = ws.addJobFromString(getModelText());\n opt.setDefine(\"gdxincname\", db.name());\n opt.setAllModelTypes(\"xpress\");\n t10.run(opt, db);\n for (GAMSVariableRecord record : t10.outDB().getVariable(\"x\"))\n cout << \"x(\" << record.key(0) << \",\" << record.key(1) << \"): level=\" << record.level() <<\n \" marginal=\" << record.marginal() << endl;\n\n ::CoUninitialize();\n\n } catch (GAMSException &ex) {\n cout << \"GAMSException occured: \" << ex.what() << endl;\n } catch (exception &ex) {\n cout << ex.what() << endl;\n }\n\n return 0;\n}\n#endif\n<commit_msg>xls -> xlsx<commit_after>\/*\n *\n * GAMS - General Algebraic Modeling System C++ API\n *\n * Copyright (c) 2017-2022 GAMS Software GmbH <support@gams.com>\n * Copyright (c) 2017-2022 GAMS Development Corp. <support@gams.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"gams.h\"\n#include <iostream>\n#include <vector>\n\nusing namespace gams;\nusing namespace std;\n\n#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)\n\n\/\/\/ \\file transport10.cpp\n\/\/\/ \\brief This is the 10th model in a series of tutorial examples.\nint main()\n{\n cout << \"---------- Transport 10 --------------\" << endl;\n cout << \"Transport 10 is a Microsoft Windows only example.\" << endl;\n return 0;\n}\n\n#else\n\n#include <QAxObject>\n#include <Windows.h> \/\/ includes \"Ole2.h\" that includes \"objbase.h\" to access CoInitialize() and CoUninitialize()\n\nstring getModelText()\n{\n return \" Sets \\n\"\n \" i canning plants \\n\"\n \" j markets \\n\"\n \" \\n\"\n \" Parameters \\n\"\n \" a(i) capacity of plant i in cases \\n\"\n \" b(j) demand at market j in cases \\n\"\n \" d(i,j) distance in thousands of miles \\n\"\n \" Scalar f freight in dollars per case per thousand miles \/90\/; \\n\"\n \" \\n\"\n \"$if not set gdxincname $abort 'no include file name for data file provided'\\n\"\n \"$gdxin %gdxincname% \\n\"\n \"$load i j a b d \\n\"\n \"$gdxin \\n\"\n \" \\n\"\n \" Parameter c(i,j) transport cost in thousands of dollars per case ; \\n\"\n \" \\n\"\n \" c(i,j) = f * d(i,j) \/ 1000 ; \\n\"\n \" \\n\"\n \" Variables \\n\"\n \" x(i,j) shipment quantities in cases \\n\"\n \" z total transportation costs in thousands of dollars ; \\n\"\n \" \\n\"\n \" Positive Variable x ; \\n\"\n \" \\n\"\n \" Equations \\n\"\n \" cost define objective function \\n\"\n \" supply(i) observe supply limit at plant i \\n\"\n \" demand(j) satisfy demand at market j ; \\n\"\n \" \\n\"\n \" cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \\n\"\n \" \\n\"\n \" supply(i) .. sum(j, x(i,j)) =l= a(i) ; \\n\"\n \" \\n\"\n \" demand(j) .. sum(i, x(i,j)) =g= b(j) ; \\n\"\n \" \\n\"\n \" Model transport \/all\/ ; \\n\"\n \" \\n\"\n \" Solve transport using lp minimizing z ; \\n\"\n \" \\n\"\n \" Display x.l, x.m ; \\n\";\n}\n\n\/\/\/ Creates an 1 dimensional GAMSParameter and transfers data from an Excel sheet (horizontal ordered)\n\/\/\/\n\/\/\/ \\param sheets The sheets object of an open Excel workbook\n\/\/\/ \\param sheetName The name of the sheet to be read\n\/\/\/ \\param db The GAMSDatabase where the GAMSParameter is created in\n\/\/\/ \\param paramName The name of the new GAMSParameter\n\/\/\/ \\param paramText The explplanatory text of the new GAMSParameter\n\/\/\/ \\param set The GAMSSet for GAMSParameter dimension\n\/\/\/ \\return The new GAMSParameter in the GAMSDatabase\n\/\/\/\nGAMSParameter sheetToParameter(QAxObject* sheets, string sheetName\n , GAMSDatabase db, string paramName, string paramText, GAMSSet set)\n{\n QAxObject* sheet = sheets->querySubObject( \"Item( string )\", sheetName.c_str() );\n GAMSParameter param = db.addParameter(paramName, paramText, set);\n\n QAxObject* usedrange = sheet->querySubObject( \"UsedRange\");\n QAxObject * columns = usedrange->querySubObject(\"Columns\");\n int intCols = columns->property(\"Count\").toInt();\n\n for (int i = 1; i <= intCols; i++) {\n std::string name = sheet->querySubObject(\"Cells( int, int )\", 1, i)->dynamicCall(\"Value()\").toString().toStdString();\n double value = sheet->querySubObject(\"Cells( int, int )\", 2, i)->dynamicCall(\"Value()\").toDouble();\n set.addRecord(name);\n GAMSParameterRecord rec = param.addRecord(name);\n rec.setValue(value);\n }\n return param;\n}\n\n\/\/\/ Creates a 2 dimensional GAMSParameter and transfers data from an Excel sheet\n\/\/\/\n\/\/\/ \\param sheets The sheets object of an open Excel workbook\n\/\/\/ \\param sheetName The name of the sheet to be read\n\/\/\/ \\param db The GAMSDatabase where the GAMSParameter is created in\n\/\/\/ \\param paramName The name of the new GAMSParameter\n\/\/\/ \\param paramText The explplanatory text of the new GAMSParameter\n\/\/\/ \\param set1 The GAMSSet for first GAMSParameter dimension\n\/\/\/ \\param set2 The GAMSSet for second GAMSParameter dimension\n\/\/\/ \\return The new GAMSParameter in the GAMSDatabase\n\/\/\/\nGAMSParameter sheetToParameter(QAxObject* sheets, string sheetName\n , GAMSDatabase db, string paramName, string paramText, GAMSSet set1, GAMSSet set2)\n{\n QAxObject* sheet = sheets->querySubObject( \"Item( string )\", sheetName.c_str() );\n vector<GAMSDomain> sets {set1, set2};\n GAMSParameter param = db.addParameter(paramName, paramText, sets);\n\n QAxObject* usedrange = sheet->querySubObject( \"UsedRange\");\n QAxObject * columns = usedrange->querySubObject(\"Columns\");\n int intCols = columns->property(\"Count\").toInt();\n QAxObject * rows = usedrange->querySubObject(\"Rows\");\n int intRows = rows->property(\"Count\").toInt();\n\n for (int j = 2; j <= intCols; j++) {\n string namej = sheet->querySubObject(\"Cells( int, int )\", 1, j)->dynamicCall(\"Value()\").toString().toStdString();\n for (int i = 2; i <= intRows; ++i) {\n string namei = sheet->querySubObject(\"Cells( int, int )\", i, 1)->dynamicCall(\"Value()\").toString().toStdString();\n GAMSParameterRecord rec = param.addRecord(namei, namej);\n double value = sheet->querySubObject(\"Cells( int, int )\", i, j)->dynamicCall(\"Value()\").toDouble();\n rec.setValue(value);\n }\n }\n return param;\n}\n\n\/\/\/ \\file transport10.cpp\n\/\/\/ \\brief This is the 10th model in a series of tutorial examples.\n\/\/\/\n\/\/\/ Here we show:\n\/\/\/ - How to fill a GAMSDatabase by reading from MS Excel\nint main(int argc, char* argv[])\n{\n cout << \"---------- Transport 10 --------------\" << endl;\n try {\n ::CoInitialize(0); \/\/ initialize thread to use ActiveX (some systems may need CoInititializeEx)\n\n GAMSWorkspaceInfo wsInfo;\n if (argc > 1)\n wsInfo.setSystemDirectory(argv[1]);\n GAMSWorkspace ws(wsInfo);\n\n \/\/ Creating the GAMSDatabase and fill with the workbook data\n GAMSDatabase db = ws.addDatabase();\n QString fileName = QString::fromStdString(ws.systemDirectory())+ cPathSep + \"apifiles\" + cPathSep + \"Data\" + cPathSep + \"transport.xlsx\";\n\n QAxObject* excel = new QAxObject( \"Excel.Application\", 0 );\n QAxObject* workbooks = excel->querySubObject( \"Workbooks\" );\n QAxObject* workbook = workbooks->querySubObject( \"Open(const QString&)\", fileName );\n QAxObject* sheets = workbook->querySubObject( \"Worksheets\" );\n\n GAMSSet i = db.addSet(\"i\", 1, \"Plants\");\n GAMSSet j = db.addSet(\"j\", 1, \"Markets\");\n\n \/\/ read parameters\n sheetToParameter(sheets, \"capacity\", db, \"a\", \"Capacity\", i);\n sheetToParameter(sheets, \"demand\", db, \"b\", \"Demand\", j);\n sheetToParameter(sheets, \"distance\", db, \"d\", \"Distance\", i, j);\n\n \/\/ clean up and close up\n workbook->dynamicCall(\"Close()\");\n excel->dynamicCall(\"Quit()\");\n\n\n \/\/ Create and run the GAMSJob\n GAMSOptions opt = ws.addOptions();\n GAMSJob t10 = ws.addJobFromString(getModelText());\n opt.setDefine(\"gdxincname\", db.name());\n opt.setAllModelTypes(\"xpress\");\n t10.run(opt, db);\n for (GAMSVariableRecord record : t10.outDB().getVariable(\"x\"))\n cout << \"x(\" << record.key(0) << \",\" << record.key(1) << \"): level=\" << record.level() <<\n \" marginal=\" << record.marginal() << endl;\n\n ::CoUninitialize();\n\n } catch (GAMSException &ex) {\n cout << \"GAMSException occured: \" << ex.what() << endl;\n } catch (exception &ex) {\n cout << ex.what() << endl;\n }\n\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * examples\/wordcount\/word_count_user_program.cpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/api\/reduce_node.hpp>\n#include <c7a\/common\/string.hpp>\n\n\n\ntemplate <typename InStack>\nauto word_count_user(c7a::DIARef<std::string, InStack> & input) {\n \n using WordPair = std::pair<std::string, int>;\n\n auto line_to_wordpairs =\n [](std::string line, auto emit) {\n for (const std::string& word : c7a::common::split(line, ' ')) {\n if (word.size() != 0)\n emit(WordPair(word, 1));\n }\n };\n\n auto key = [](WordPair in) {\n return in.first;\n };\n\n auto red_fn =\n [](WordPair in1, WordPair in2) {\n return WordPair(in1.first, in1.second + in2.second);\n }; \n \n auto word_pairs = input.FlatMap(line_to_wordpairs);\n\n return word_pairs.ReduceBy(key, red_fn);\n}\n\n\/\/! The WordCount user program\nint word_count(c7a::Context& ctx) {\n using c7a::Context;\n using WordPair = std::pair<std::string, int>;\n \n std::cout << \"wordcount.in\" << std::endl;\n auto lines = ReadLines(\n ctx,\n \"wordcount.in\",\n [](const std::string& line) {\n return line;\n });\n\n auto red_words = word_count_user(lines);\n\n red_words.WriteToFileSystem(\n \"wordcount_\" + std::to_string(ctx.rank()) + \".out\",\n [](const WordPair& item) {\n return item.first + \": \" + std::to_string(item.second);\n });\n\n return 0;\n}\n\nint word_count_generated(c7a::Context& ctx, size_t size) {\n using c7a::Context;\n using WordPair = std::pair<std::string, int>;\n\n auto lines = GenerateFromFile(\n ctx,\n \"headwords\",\n [](const std::string& line) {\n return line;\n },\n size);\n\n auto reduced_words = word_count_user(lines);\n\n reduced_words.WriteToFileSystem(\n \"wordcount_\" + std::to_string(ctx.rank()) + \".out\",\n [](const WordPair& item) {\n return item.first + \": \" + std::to_string(item.second);\n });\n return 0;\n}\n\n\/******************************************************************************\/\n<commit_msg>Compactifying word count program<commit_after>\/*******************************************************************************\n * examples\/wordcount\/word_count_user_program.cpp\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/api\/reduce_node.hpp>\n#include <c7a\/common\/string.hpp>\n\ntemplate <typename InStack>\nauto word_count_user(c7a::DIARef<std::string, InStack> & input) {\n \n using WordCount = std::pair<std::string, int>;\n\n auto word_pairs = input.FlatMap(\n [](std::string line, auto emit) {\n \/* map lambda *\/\n for (const std::string& word : c7a::common::split(line, ' ')) {\n if (word.size() != 0)\n emit(WordCount(word, 1));\n }\n });\n\n return word_pairs.ReduceBy(\n [](const WordCount& in) {\n \/* reduction key: the word string *\/\n return in.first;\n },\n [](WordCount a, WordCount b) {\n \/* associative reduction operator: add counters *\/\n return WordCount(a.first, a.second + b.second);\n });\n}\n\n\/\/! The WordCount user program\nint word_count(c7a::Context& ctx) {\n using c7a::Context;\n using WordCount = std::pair<std::string, int>;\n \n std::cout << \"wordcount.in\" << std::endl;\n auto lines = ReadLines(\n ctx,\n \"wordcount.in\",\n [](const std::string& line) {\n return line;\n });\n\n auto red_words = word_count_user(lines);\n\n red_words.WriteToFileSystem(\n \"wordcount_\" + std::to_string(ctx.rank()) + \".out\",\n [](const WordCount& item) {\n return item.first + \": \" + std::to_string(item.second);\n });\n\n return 0;\n}\n\nint word_count_generated(c7a::Context& ctx, size_t size) {\n using c7a::Context;\n using WordCount = std::pair<std::string, int>;\n\n auto lines = GenerateFromFile(\n ctx,\n \"headwords\",\n [](const std::string& line) {\n return line;\n },\n size);\n\n auto reduced_words = word_count_user(lines);\n\n reduced_words.WriteToFileSystem(\n \"wordcount_\" + std::to_string(ctx.rank()) + \".out\",\n [](const WordCount& item) {\n return item.first + \": \" + std::to_string(item.second);\n });\n return 0;\n}\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>lost instances temporary fix<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Loggers.h\"\r\n#include \"boost\/log\/utility\/setup\/console.hpp\"\r\n#include \"boost\/log\/utility\/setup\/file.hpp\"\r\n#include \"boost\/log\/sources\/severity_channel_logger.hpp\"\r\n#include <boost\/log\/sources\/severity_feature.hpp>\r\n#include <boost\/log\/trivial.hpp>\r\n#include <boost\/log\/expressions.hpp>\r\n#include <boost\/log\/attributes.hpp>\r\n\r\nvoid ILogger::TraceFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Trace(buffer);\r\n}\r\n\r\nvoid ILogger::DebugFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Debug(buffer);\r\n}\r\nvoid ILogger::InfoFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Info(buffer);\r\n}\r\n\r\nvoid ILogger::WarningFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Warning(buffer);\r\n}\r\n\r\n\r\nvoid ILogger::ErrorFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Error(buffer);\r\n}\r\n\r\nvoid ILogger::FatalFormat(const char* format, ...)\r\n{\r\n\tchar buffer[64 * 1024];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Fatal(buffer);\r\n}\r\n\r\n\r\nclass Logger : public ILogger\r\n{\r\npublic:\r\n\tLogger(const char* component)\r\n\t\t: m_Logger(boost::log::keywords::channel = (component))\r\n\t{\r\n\t}\r\n\r\n\tvirtual void Trace(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::trace) << str;\r\n\t}\r\n\r\n\tvirtual void Debug(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::debug) << str;\r\n\t}\r\n\r\n\tvirtual void Info(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::info) << str;\r\n\t}\r\n\r\n\tvirtual void Warning(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::warning) << str;\r\n\t}\r\n\r\n\tvirtual void Error(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::error) << str;\r\n\t}\r\n\r\n\tvirtual void Fatal(const char * str) override\r\n\t{\r\n\t\tBOOST_LOG_SEV(m_Logger, boost::log::trivial::fatal) << str;\r\n\t}\r\nprotected:\r\n\tboost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level> m_Logger;\r\n};\r\n\r\nvoid LoggerFactory::InitLogger(boost::program_options::variables_map& vm)\r\n{\r\n\tstd::string logFormat = \"[%TimeStamp%]: [%Severity%] [%Message%]\";\r\n\r\n\tboost::log::core::get()->set_logging_enabled(false);\r\n\tboost::log::core::get()->add_global_attribute(\"TimeStamp\", boost::log::attributes::local_clock());\r\n\r\n\tif (!vm[\"Logging.Console\"].empty())\r\n\t{\r\n\t\tauto value = vm[\"Logging.Console\"].as<std::string>();\r\n\t\tif (vm[\"Logging.Console\"].as<std::string>() == \"true\")\r\n\t\t{\r\n\t\t\tboost::log::add_console_log(std::cout, boost::log::keywords::format = logFormat);\r\n\t\t\tboost::log::core::get()->set_logging_enabled(true);\r\n\t\t}\r\n\t}\r\n\tif (!vm[\"Logging.FileOutput\"].empty())\r\n\t{\r\n\t\tauto fileName = vm[\"Logging.FileOutput\"].as<std::string>();\r\n\t\tif (fileName != \"\")\r\n\t\t{\r\n\t\t\tboost::log::add_file_log(fileName, boost::log::keywords::format = logFormat);\r\n\t\t\tboost::log::core::get()->set_logging_enabled(true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nstd::shared_ptr<ILogger> LoggerFactory::getLogger(const char* component)\r\n{\r\n\treturn std::make_shared<Logger>(component);\r\n}\r\n<commit_msg>Poco Logger -> not yet complete<commit_after>#include \"Loggers.h\"\r\n#include \"stdarg.h\"\r\n\r\n#include \"Poco\/ConsoleChannel.h\"\r\n#include \"Poco\/SplitterChannel.h\"\r\n#include \"Poco\/FormattingChannel.h\"\r\n#include \"Poco\/PatternFormatter.h\"\r\n#include \"Poco\/FileChannel.h\"\r\n#include \"Poco\/AutoPtr.h\"\r\n#include \"Poco\/Logger.h\"\r\n\r\nconst int bufferSize = 64 * 1024;\r\n\r\nvoid ILogger::TraceFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Trace(buffer);\r\n}\r\n\r\nvoid ILogger::DebugFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Debug(buffer);\r\n}\r\nvoid ILogger::InfoFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Info(buffer);\r\n}\r\n\r\nvoid ILogger::WarningFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Warning(buffer);\r\n}\r\n\r\n\r\nvoid ILogger::ErrorFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Error(buffer);\r\n}\r\n\r\nvoid ILogger::FatalFormat(const char* format, ...)\r\n{\r\n\tchar buffer[bufferSize];\r\n\tva_list arglist;\r\n\tva_start(arglist, format);\r\n\tvsprintf(buffer, format, arglist);\r\n\tva_end(arglist);\r\n\tthis->Fatal(buffer);\r\n}\r\n\r\nclass Logger : public ILogger\r\n{\r\npublic:\r\n\tLogger(const char* component) :\r\n\t\tm_Logger(Poco::Logger::get(component))\r\n\t{\r\n\t}\r\n\r\n\tvirtual void Trace(const char * str) override\r\n\t{\r\n\t\tm_Logger.trace(str);\r\n\t}\r\n\r\n\tvirtual void Debug(const char * str) override\r\n\t{\r\n\t\tm_Logger.debug(str);\r\n\t}\r\n\r\n\tvirtual void Info(const char * str) override\r\n\t{\r\n\t\tm_Logger.information(str);\r\n\t}\r\n\r\n\tvirtual void Warning(const char * str) override\r\n\t{\r\n\t\tm_Logger.warning(str);\r\n\t}\r\n\r\n\tvirtual void Error(const char * str) override\r\n\t{\r\n\t\tm_Logger.error(str);\r\n\t}\r\n\r\n\tvirtual void Fatal(const char * str) override\r\n\t{\r\n\t\tm_Logger.fatal(str);\r\n\r\n\t}\r\nprotected:\r\n\tPoco::Logger& m_Logger;\r\n};\r\n\r\nvoid LoggerFactory::InitLogger(boost::program_options::variables_map& vm)\r\n{\r\n\tPoco::AutoPtr<Poco::SplitterChannel> sChannel(new Poco::SplitterChannel());\r\n\tPoco::Logger::root().setChannel(sChannel);\r\n\tPoco::AutoPtr<Poco::PatternFormatter> pPF(new Poco::PatternFormatter());\r\tpPF->setProperty(\"pattern\", \"%Y-%m-%d %H:%M:%S [%P:%I] [%s]:[%p]: %t\");\r\tPoco::AutoPtr<Poco::FormattingChannel> pFC(new Poco::FormattingChannel(pPF, sChannel));\r\r\n\tstd::string logFormat = \"[%TimeStamp%]: [%Severity%] [%Message%]\";\r\n\r\n\tif (!vm[\"Logging.Console\"].empty())\r\n\t{\r\n\t\tauto value = vm[\"Logging.Console\"].as<std::string>();\r\n\t\tif (vm[\"Logging.Console\"].as<std::string>() == \"true\")\r\n\t\t{\r\n\t\t\tPoco::AutoPtr<Poco::ConsoleChannel> cChannel;\r\n\t\t\tsChannel->addChannel(cChannel);\r\n\t\t}\r\n\t}\r\n\r\n\tif (!vm[\"Logging.FileOutput\"].empty())\r\n\t{\r\n\t\tauto fileName = vm[\"Logging.FileOutput\"].as<std::string>();\r\n\t\tif (fileName != \"\")\r\n\t\t{\r\n\t\t\tPoco::AutoPtr<Poco::FileChannel> pChannel(new Poco::FileChannel);\r\n\t\t\tpChannel->setProperty(\"path\", fileName);\r\n\t\t\tsChannel->addChannel(pChannel);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nstd::shared_ptr<ILogger> LoggerFactory::getLogger(const char* component)\r\n{\r\n\treturn std::make_shared<Logger>(component);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/runtime\/browser\/ui\/native_app_window_aura.h\"\n\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/browser\/web_contents\/web_contents_view.h\"\n#include \"ui\/aura\/client\/aura_constants.h\"\n#include \"ui\/wm\/core\/default_activation_client.h\"\n#include \"ui\/aura\/client\/default_capture_client.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/layout_manager.h\"\n#include \"ui\/aura\/test\/test_focus_client.h\"\n#include \"ui\/aura\/test\/test_screen.h\"\n#include \"ui\/aura\/test\/test_window_tree_client.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/aura\/window_event_dispatcher.h\"\n#include \"ui\/base\/cursor\/cursor.h\"\n#include \"ui\/base\/cursor\/image_cursors.h\"\n#include \"ui\/base\/ime\/input_method.h\"\n#include \"ui\/base\/ime\/input_method_delegate.h\"\n#include \"ui\/base\/ime\/input_method_factory.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"ui\/wm\/core\/cursor_manager.h\"\n#include \"ui\/wm\/core\/native_cursor_manager.h\"\n#include \"ui\/wm\/core\/native_cursor_manager_delegate.h\"\n\nnamespace xwalk {\n\nconst int kDefaultTestWindowWidthDip = 800;\nconst int kDefaultTestWindowHeightDip = 600;\n\nnamespace {\n\nclass FillLayout : public aura::LayoutManager {\n public:\n explicit FillLayout(aura::Window* root)\n : root_(root) {\n }\n\n virtual ~FillLayout() {}\n\n private:\n \/\/ aura::LayoutManager:\n virtual void OnWindowResized() override {\n }\n\n virtual void OnWindowAddedToLayout(aura::Window* child) override {\n child->SetBounds(root_->bounds());\n }\n\n virtual void OnWillRemoveWindowFromLayout(aura::Window* child) override {\n }\n\n virtual void OnWindowRemovedFromLayout(aura::Window* child) override {\n }\n\n virtual void OnChildWindowVisibilityChanged(aura::Window* child,\n bool visible) override {\n }\n\n virtual void SetChildBounds(aura::Window* child,\n const gfx::Rect& requested_bounds) override {\n SetChildBoundsDirect(child, requested_bounds);\n }\n\n aura::Window* root_;\n\n DISALLOW_COPY_AND_ASSIGN(FillLayout);\n};\n\n\/\/ Taken from app_shell.\n\/\/ A class that bridges the gap between CursorManager and Aura. It borrows\n\/\/ heavily from AshNativeCursorManager.\nclass ShellNativeCursorManager : public wm::NativeCursorManager {\n public:\n explicit ShellNativeCursorManager(aura::WindowTreeHost* host)\n : host_(host),\n image_cursors_(new ui::ImageCursors) {}\n virtual ~ShellNativeCursorManager() {}\n\n \/\/ wm::NativeCursorManager overrides.\n virtual void SetDisplay(\n const gfx::Display& display,\n wm::NativeCursorManagerDelegate* delegate) override {\n if (image_cursors_->SetDisplay(display, display.device_scale_factor()))\n SetCursor(delegate->GetCursor(), delegate);\n }\n\n virtual void SetCursor(\n gfx::NativeCursor cursor,\n wm::NativeCursorManagerDelegate* delegate) override {\n image_cursors_->SetPlatformCursor(&cursor);\n cursor.set_device_scale_factor(image_cursors_->GetScale());\n delegate->CommitCursor(cursor);\n\n if (delegate->IsCursorVisible())\n ApplyCursor(cursor);\n }\n\n virtual void SetVisibility(\n bool visible,\n wm::NativeCursorManagerDelegate* delegate) override {\n delegate->CommitVisibility(visible);\n\n if (visible) {\n SetCursor(delegate->GetCursor(), delegate);\n } else {\n gfx::NativeCursor invisible_cursor(ui::kCursorNone);\n image_cursors_->SetPlatformCursor(&invisible_cursor);\n ApplyCursor(invisible_cursor);\n }\n }\n\n virtual void SetCursorSet(\n ui::CursorSetType cursor_set,\n wm::NativeCursorManagerDelegate* delegate) override {\n image_cursors_->SetCursorSet(cursor_set);\n delegate->CommitCursorSet(cursor_set);\n if (delegate->IsCursorVisible())\n SetCursor(delegate->GetCursor(), delegate);\n }\n\n virtual void SetMouseEventsEnabled(\n bool enabled,\n wm::NativeCursorManagerDelegate* delegate) override {\n delegate->CommitMouseEventsEnabled(enabled);\n SetVisibility(delegate->IsCursorVisible(), delegate);\n }\n\n private:\n \/\/ Sets |cursor| as the active cursor within Aura.\n void ApplyCursor(gfx::NativeCursor cursor) {\n host_->SetCursor(cursor);\n }\n\n aura::WindowTreeHost* host_; \/\/ Not owned.\n\n scoped_ptr<ui::ImageCursors> image_cursors_;\n\n DISALLOW_COPY_AND_ASSIGN(ShellNativeCursorManager);\n};\n\nclass MinimalInputEventFilter : public ui::internal::InputMethodDelegate,\n public ui::EventHandler {\n public:\n explicit MinimalInputEventFilter(aura::WindowTreeHost* host)\n : host_(host),\n input_method_(ui::CreateInputMethod(this,\n gfx::kNullAcceleratedWidget)) {\n input_method_->Init(true);\n host_->window()->AddPreTargetHandler(this);\n host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,\n input_method_.get());\n }\n\n virtual ~MinimalInputEventFilter() {\n host_->window()->RemovePreTargetHandler(this);\n host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,\n static_cast<ui::InputMethod*>(NULL));\n }\n\n private:\n \/\/ ui::EventHandler:\n virtual void OnKeyEvent(ui::KeyEvent* event) override {\n \/\/ See the comment in InputMethodEventFilter::OnKeyEvent() for details.\n if (event->IsTranslated()) {\n event->SetTranslated(false);\n } else if (input_method_->DispatchKeyEvent(*event)) {\n event->StopPropagation();\n }\n }\n\n \/\/ ui::internal::InputMethodDelegate:\n virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override {\n \/\/ See the comment in InputMethodEventFilter::DispatchKeyEventPostIME() for\n \/\/ details.\n ui::KeyEvent aura_event(event);\n aura_event.SetTranslated(true);\n ui::EventDispatchDetails details =\n host_->dispatcher()->OnEventFromSource(&aura_event);\n return aura_event.handled() || details.dispatcher_destroyed;\n }\n\n aura::WindowTreeHost* host_;\n scoped_ptr<ui::InputMethod> input_method_;\n\n DISALLOW_COPY_AND_ASSIGN(MinimalInputEventFilter);\n};\n\n} \/\/ namespace\n\n\/\/ mimicking Shell::ShellPlatformDataAura\nNativeAppWindowAura::NativeAppWindowAura(\n const NativeAppWindow::CreateParams& create_params)\n : web_contents_(create_params.web_contents) {\n aura::Env::CreateInstance(true);\n const gfx::Size bounds =\n gfx::Size(kDefaultTestWindowWidthDip, kDefaultTestWindowHeightDip);\n host_.reset(aura::WindowTreeHost::Create(gfx::Rect(bounds)));\n host_->InitHost();\n host_->window()->SetLayoutManager(new FillLayout(host_->window()));\n\n focus_client_.reset(new aura::test::TestFocusClient());\n aura::client::SetFocusClient(host_->window(), focus_client_.get());\n\n new wm::DefaultActivationClient(host_->window());\n capture_client_.reset(\n new aura::client::DefaultCaptureClient(host_->window()));\n window_tree_client_.reset(\n new aura::test::TestWindowTreeClient(host_->window()));\n ime_filter_.reset(new MinimalInputEventFilter(host_.get()));\n\n cursor_manager_.reset(\n new wm::CursorManager(scoped_ptr<wm::NativeCursorManager>(\n new ShellNativeCursorManager(host_.get()))));\n cursor_manager_->SetDisplay(\n gfx::Screen::GetNativeScreen()->GetPrimaryDisplay());\n cursor_manager_->SetCursor(ui::kCursorPointer);\n aura::client::SetCursorClient(host_->window(), cursor_manager_.get());\n\n \/\/ mimicking Shell::PlatformSetContents\n aura::Window* content = web_contents_->GetNativeView();\n aura::Window* parent = host_->window();\n if (!parent->Contains(content))\n parent->AddChild(content);\n\n content->Show();\n parent->Show();\n\n web_contents_->Focus();\n}\n\nNativeAppWindowAura::~NativeAppWindowAura() {\n aura::Env::DeleteInstance();\n}\n\ngfx::NativeWindow NativeAppWindowAura::GetNativeWindow() const {\n return NULL;\n}\n\nvoid NativeAppWindowAura::UpdateIcon(const gfx::Image& icon) {\n}\n\nvoid NativeAppWindowAura::UpdateTitle(const base::string16& title) {\n}\n\ngfx::Rect NativeAppWindowAura::GetRestoredBounds() const {\n return gfx::Rect();\n}\n\ngfx::Rect NativeAppWindowAura::GetBounds() const {\n return host_->GetBounds();\n}\n\nvoid NativeAppWindowAura::SetBounds(const gfx::Rect& bounds) {\n host_->SetBounds(bounds);\n}\n\nvoid NativeAppWindowAura::Focus() {\n}\n\nvoid NativeAppWindowAura::Show() {\n host_->Show();\n}\n\nvoid NativeAppWindowAura::Hide() {\n host_->Hide();\n}\n\nvoid NativeAppWindowAura::Maximize() {\n}\n\nvoid NativeAppWindowAura::Minimize() {\n}\n\nvoid NativeAppWindowAura::SetFullscreen(bool fullscreen) {\n}\n\nvoid NativeAppWindowAura::Restore() {\n}\n\nvoid NativeAppWindowAura::FlashFrame(bool flash) {\n}\n\nvoid NativeAppWindowAura::Close() {\n}\n\nbool NativeAppWindowAura::IsActive() const {\n return true;\n}\n\nbool NativeAppWindowAura::IsMaximized() const {\n return true;\n}\n\nbool NativeAppWindowAura::IsMinimized() const {\n return false;\n}\n\nbool NativeAppWindowAura::IsFullscreen() const {\n return true;\n}\n\n\/\/ static\nNativeAppWindow* NativeAppWindow::Create(\n const NativeAppWindow::CreateParams& create_params) {\n return new NativeAppWindowAura(create_params);\n}\n\n\/\/ static\nvoid NativeAppWindow::Initialize() {\n \/\/ At least Athena, Content Shell and Chromecast use the \"TestScreen\" class\n \/\/ not exactly for testing but production instead. So I think we are fine on\n \/\/ using it as long they are using it as well.\n aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());\n gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);\n}\n\n} \/\/ namespace xwalk\n<commit_msg>runtime: Add cmd line option for changing native host window bounds<commit_after>\/\/ Copyright (c) 2014 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/runtime\/browser\/ui\/native_app_window_aura.h\"\n\n#include \"base\/command_line.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/browser\/web_contents\/web_contents_view.h\"\n#include \"ui\/aura\/client\/aura_constants.h\"\n#include \"ui\/wm\/core\/default_activation_client.h\"\n#include \"ui\/aura\/client\/default_capture_client.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/layout_manager.h\"\n#include \"ui\/aura\/test\/test_focus_client.h\"\n#include \"ui\/aura\/test\/test_screen.h\"\n#include \"ui\/aura\/test\/test_window_tree_client.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/aura\/window_event_dispatcher.h\"\n#include \"ui\/base\/cursor\/cursor.h\"\n#include \"ui\/base\/cursor\/image_cursors.h\"\n#include \"ui\/base\/ime\/input_method.h\"\n#include \"ui\/base\/ime\/input_method_delegate.h\"\n#include \"ui\/base\/ime\/input_method_factory.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"ui\/wm\/core\/cursor_manager.h\"\n#include \"ui\/wm\/core\/native_cursor_manager.h\"\n#include \"ui\/wm\/core\/native_cursor_manager_delegate.h\"\n\nnamespace xwalk {\n\nconst int kDefaultTestWindowWidthDip = 800;\nconst int kDefaultTestWindowHeightDip = 600;\n\nconst char kXwalkHostWindowBounds[] = \"xwalk-host-window-bounds\";\n\nnamespace {\n\nclass FillLayout : public aura::LayoutManager {\n public:\n explicit FillLayout(aura::Window* root)\n : root_(root) {\n }\n\n virtual ~FillLayout() {}\n\n private:\n \/\/ aura::LayoutManager:\n virtual void OnWindowResized() override {\n }\n\n virtual void OnWindowAddedToLayout(aura::Window* child) override {\n child->SetBounds(root_->bounds());\n }\n\n virtual void OnWillRemoveWindowFromLayout(aura::Window* child) override {\n }\n\n virtual void OnWindowRemovedFromLayout(aura::Window* child) override {\n }\n\n virtual void OnChildWindowVisibilityChanged(aura::Window* child,\n bool visible) override {\n }\n\n virtual void SetChildBounds(aura::Window* child,\n const gfx::Rect& requested_bounds) override {\n SetChildBoundsDirect(child, requested_bounds);\n }\n\n aura::Window* root_;\n\n DISALLOW_COPY_AND_ASSIGN(FillLayout);\n};\n\n\/\/ Taken from app_shell.\n\/\/ A class that bridges the gap between CursorManager and Aura. It borrows\n\/\/ heavily from AshNativeCursorManager.\nclass ShellNativeCursorManager : public wm::NativeCursorManager {\n public:\n explicit ShellNativeCursorManager(aura::WindowTreeHost* host)\n : host_(host),\n image_cursors_(new ui::ImageCursors) {}\n virtual ~ShellNativeCursorManager() {}\n\n \/\/ wm::NativeCursorManager overrides.\n virtual void SetDisplay(\n const gfx::Display& display,\n wm::NativeCursorManagerDelegate* delegate) override {\n if (image_cursors_->SetDisplay(display, display.device_scale_factor()))\n SetCursor(delegate->GetCursor(), delegate);\n }\n\n virtual void SetCursor(\n gfx::NativeCursor cursor,\n wm::NativeCursorManagerDelegate* delegate) override {\n image_cursors_->SetPlatformCursor(&cursor);\n cursor.set_device_scale_factor(image_cursors_->GetScale());\n delegate->CommitCursor(cursor);\n\n if (delegate->IsCursorVisible())\n ApplyCursor(cursor);\n }\n\n virtual void SetVisibility(\n bool visible,\n wm::NativeCursorManagerDelegate* delegate) override {\n delegate->CommitVisibility(visible);\n\n if (visible) {\n SetCursor(delegate->GetCursor(), delegate);\n } else {\n gfx::NativeCursor invisible_cursor(ui::kCursorNone);\n image_cursors_->SetPlatformCursor(&invisible_cursor);\n ApplyCursor(invisible_cursor);\n }\n }\n\n virtual void SetCursorSet(\n ui::CursorSetType cursor_set,\n wm::NativeCursorManagerDelegate* delegate) override {\n image_cursors_->SetCursorSet(cursor_set);\n delegate->CommitCursorSet(cursor_set);\n if (delegate->IsCursorVisible())\n SetCursor(delegate->GetCursor(), delegate);\n }\n\n virtual void SetMouseEventsEnabled(\n bool enabled,\n wm::NativeCursorManagerDelegate* delegate) override {\n delegate->CommitMouseEventsEnabled(enabled);\n SetVisibility(delegate->IsCursorVisible(), delegate);\n }\n\n private:\n \/\/ Sets |cursor| as the active cursor within Aura.\n void ApplyCursor(gfx::NativeCursor cursor) {\n host_->SetCursor(cursor);\n }\n\n aura::WindowTreeHost* host_; \/\/ Not owned.\n\n scoped_ptr<ui::ImageCursors> image_cursors_;\n\n DISALLOW_COPY_AND_ASSIGN(ShellNativeCursorManager);\n};\n\nclass MinimalInputEventFilter : public ui::internal::InputMethodDelegate,\n public ui::EventHandler {\n public:\n explicit MinimalInputEventFilter(aura::WindowTreeHost* host)\n : host_(host),\n input_method_(ui::CreateInputMethod(this,\n gfx::kNullAcceleratedWidget)) {\n input_method_->Init(true);\n host_->window()->AddPreTargetHandler(this);\n host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,\n input_method_.get());\n }\n\n virtual ~MinimalInputEventFilter() {\n host_->window()->RemovePreTargetHandler(this);\n host_->window()->SetProperty(aura::client::kRootWindowInputMethodKey,\n static_cast<ui::InputMethod*>(NULL));\n }\n\n private:\n \/\/ ui::EventHandler:\n virtual void OnKeyEvent(ui::KeyEvent* event) override {\n \/\/ See the comment in InputMethodEventFilter::OnKeyEvent() for details.\n if (event->IsTranslated()) {\n event->SetTranslated(false);\n } else if (input_method_->DispatchKeyEvent(*event)) {\n event->StopPropagation();\n }\n }\n\n \/\/ ui::internal::InputMethodDelegate:\n virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override {\n \/\/ See the comment in InputMethodEventFilter::DispatchKeyEventPostIME() for\n \/\/ details.\n ui::KeyEvent aura_event(event);\n aura_event.SetTranslated(true);\n ui::EventDispatchDetails details =\n host_->dispatcher()->OnEventFromSource(&aura_event);\n return aura_event.handled() || details.dispatcher_destroyed;\n }\n\n aura::WindowTreeHost* host_;\n scoped_ptr<ui::InputMethod> input_method_;\n\n DISALLOW_COPY_AND_ASSIGN(MinimalInputEventFilter);\n};\n\n} \/\/ namespace\n\n\/\/ mimicking Shell::ShellPlatformDataAura\nNativeAppWindowAura::NativeAppWindowAura(\n const NativeAppWindow::CreateParams& create_params)\n : web_contents_(create_params.web_contents) {\n aura::Env::CreateInstance(true);\n gfx::Size size;\n\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(kXwalkHostWindowBounds)) {\n const std::string size_str =\n command_line->GetSwitchValueASCII(kXwalkHostWindowBounds);\n int width, height;\n if (sscanf(size_str.c_str(), \"%d,%d\", &width, &height) == 2)\n size = gfx::Size(width, height);\n }\n\n if (size.IsEmpty())\n size = gfx::Size(kDefaultTestWindowWidthDip, kDefaultTestWindowHeightDip);\n\n host_.reset(aura::WindowTreeHost::Create(gfx::Rect(size)));\n host_->InitHost();\n host_->window()->SetLayoutManager(new FillLayout(host_->window()));\n\n focus_client_.reset(new aura::test::TestFocusClient());\n aura::client::SetFocusClient(host_->window(), focus_client_.get());\n\n new wm::DefaultActivationClient(host_->window());\n capture_client_.reset(\n new aura::client::DefaultCaptureClient(host_->window()));\n window_tree_client_.reset(\n new aura::test::TestWindowTreeClient(host_->window()));\n ime_filter_.reset(new MinimalInputEventFilter(host_.get()));\n\n cursor_manager_.reset(\n new wm::CursorManager(scoped_ptr<wm::NativeCursorManager>(\n new ShellNativeCursorManager(host_.get()))));\n cursor_manager_->SetDisplay(\n gfx::Screen::GetNativeScreen()->GetPrimaryDisplay());\n cursor_manager_->SetCursor(ui::kCursorPointer);\n aura::client::SetCursorClient(host_->window(), cursor_manager_.get());\n\n \/\/ mimicking Shell::PlatformSetContents\n aura::Window* content = web_contents_->GetNativeView();\n aura::Window* parent = host_->window();\n if (!parent->Contains(content))\n parent->AddChild(content);\n\n content->Show();\n parent->Show();\n\n web_contents_->Focus();\n}\n\nNativeAppWindowAura::~NativeAppWindowAura() {\n aura::Env::DeleteInstance();\n}\n\ngfx::NativeWindow NativeAppWindowAura::GetNativeWindow() const {\n return NULL;\n}\n\nvoid NativeAppWindowAura::UpdateIcon(const gfx::Image& icon) {\n}\n\nvoid NativeAppWindowAura::UpdateTitle(const base::string16& title) {\n}\n\ngfx::Rect NativeAppWindowAura::GetRestoredBounds() const {\n return gfx::Rect();\n}\n\ngfx::Rect NativeAppWindowAura::GetBounds() const {\n return host_->GetBounds();\n}\n\nvoid NativeAppWindowAura::SetBounds(const gfx::Rect& bounds) {\n host_->SetBounds(bounds);\n}\n\nvoid NativeAppWindowAura::Focus() {\n}\n\nvoid NativeAppWindowAura::Show() {\n host_->Show();\n}\n\nvoid NativeAppWindowAura::Hide() {\n host_->Hide();\n}\n\nvoid NativeAppWindowAura::Maximize() {\n}\n\nvoid NativeAppWindowAura::Minimize() {\n}\n\nvoid NativeAppWindowAura::SetFullscreen(bool fullscreen) {\n}\n\nvoid NativeAppWindowAura::Restore() {\n}\n\nvoid NativeAppWindowAura::FlashFrame(bool flash) {\n}\n\nvoid NativeAppWindowAura::Close() {\n}\n\nbool NativeAppWindowAura::IsActive() const {\n return true;\n}\n\nbool NativeAppWindowAura::IsMaximized() const {\n return true;\n}\n\nbool NativeAppWindowAura::IsMinimized() const {\n return false;\n}\n\nbool NativeAppWindowAura::IsFullscreen() const {\n return true;\n}\n\n\/\/ static\nNativeAppWindow* NativeAppWindow::Create(\n const NativeAppWindow::CreateParams& create_params) {\n return new NativeAppWindowAura(create_params);\n}\n\n\/\/ static\nvoid NativeAppWindow::Initialize() {\n \/\/ At least Athena, Content Shell and Chromecast use the \"TestScreen\" class\n \/\/ not exactly for testing but production instead. So I think we are fine on\n \/\/ using it as long they are using it as well.\n aura::TestScreen* screen = aura::TestScreen::Create(gfx::Size());\n gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen);\n}\n\n} \/\/ namespace xwalk\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file constrained_ik.cpp\n * @brief Basic low-level kinematics functions.\n *\n * Typically, just wrappers around the equivalent KDL calls.\n *\n * @author dsolomon\n * @date Sep 15, 2013\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2013, Southwest Research Institute\n *\n * @license Software License Agreement (Apache License)\\n\n * \\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\\n\n * \\n\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\\n\n * \\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"constrained_ik\/constrained_ik.h\"\n#include \"constrained_ik\/constraint_group.h\"\n#include <boost\/make_shared.hpp>\n\/\/#include <moveit\/collision_detection_fcl\/collision_common.h>\n#include <constrained_ik\/collision_robot_fcl_detailed.h>\n#include <constrained_ik\/constraint_results.h>\n#include <ros\/ros.h>\n\nnamespace constrained_ik\n{\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::Affine3d;\n\nConstrained_IK::Constrained_IK()\n{\n initialized_ = false;\n max_iter_ = 500; \/\/default max_iter\n joint_convergence_tol_ = 0.0001; \/\/default convergence tolerance\n debug_ = false;\n kpp_ = 1.0;\/\/ default primary proportional gain\n kpa_ = 0.5;\/\/ default auxillary proportional gain\n}\n\nconstrained_ik::ConstraintResults Constrained_IK::evalConstraint(constraint_types::ConstraintType constraint_type, const constrained_ik::SolverState &state) const\n{\n switch(constraint_type)\n {\n case constraint_types::Primary:\n return primary_constraints_.evalConstraint(state);\n case constraint_types::Auxiliary:\n return auxiliary_constraints_.evalConstraint(state);\n }\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjection(const Eigen::MatrixXd &J) const\n{\n MatrixXd J_pinv = calcDampedPseudoinverse(J);\n MatrixXd JplusJ = J_pinv * J;\n int mn = JplusJ.rows();\n MatrixXd P = MatrixXd::Identity(mn,mn)-JplusJ;\n return (P);\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjectionTheRightWay(const Eigen::MatrixXd &A) const\n{\n Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeFullV);\n MatrixXd V(svd.matrixV());\n\n \/\/ determine rank using same algorithym as latest Eigen\n \/\/ TODO replace next 10 lines of code with rnk = svd.rank(); once eigen3 is updated\n int rnk = 0;\n if(svd.singularValues().size()==0)\n {\n rnk = 0;\n }\n else\n {\n double threshold = std::min(A.rows(),A.cols())*Eigen::NumTraits<double>::epsilon();\n double premultiplied_threshold = svd.singularValues().coeff(0) * threshold;\n rnk = svd.nonzeroSingularValues()-1;\n while(rnk>=0 && svd.singularValues().coeff(rnk) < premultiplied_threshold) --rnk;\n rnk++;\n }\n\n \/\/ zero singular vectors in the range of A\n for(int i=0; i<rnk; ++i)\n {\n for(int j=0; j<A.cols(); j++) V(j,i) = 0;\n }\n\n MatrixXd P = V * V.transpose();\n return(P);\n}\n\nEigen::MatrixXd Constrained_IK::calcDampedPseudoinverse(const Eigen::MatrixXd &J) const\n{\n MatrixXd J_pinv;\n\n if (basic_kin::BasicKin::dampedPInv(J,J_pinv))\n {\n return J_pinv;\n }\n else\n {\n ROS_ERROR_STREAM(\"Not able to calculate damped pseudoinverse!\");\n throw std::runtime_error(\"Not able to calculate damped pseudoinverse! IK solution may be invalid.\");\n }\n}\n\nvoid Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n const Eigen::VectorXd &joint_seed,\n Eigen::VectorXd &joint_angles,\n int min_updates) const\n{\n calcInvKin(goal,joint_seed, planning_scene::PlanningSceneConstPtr(), joint_angles, min_updates);\n}\n\nvoid Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n const Eigen::VectorXd &joint_seed,\n const planning_scene::PlanningSceneConstPtr planning_scene,\n Eigen::VectorXd &joint_angles,\n int min_updates) const\n{\n \/\/ initialize state\n joint_angles = joint_seed; \/\/ initialize result to seed value\n constrained_ik::SolverState state = getState(goal, joint_seed); \/\/ create state vars for this IK solve\n state.condition = checkInitialized();\n state.planning_scene = planning_scene;\n if(planning_scene)\n {\n state.robot_state = robot_state::RobotStatePtr(new moveit::core::RobotState(planning_scene->getCurrentState()));\n state.collision_robot = CollisionRobotFCLDetailed::CollisionRobotFCLDetailedPtr(new CollisionRobotFCLDetailed(planning_scene->getRobotModel()));\n }\n\n if (state.condition == initialization_state::NothingInitialized || state.condition == initialization_state::AuxiliaryOnly)\n throw std::runtime_error(\"Must call init() before using Constrained_IK and have a primary constraint.\");\n\n \/\/Cache the joint angles to return if max iteration is reached.\n Eigen::VectorXd cached_joint_angles = joint_seed;\n\n \/\/ iterate until solution converges (or aborted)\n bool status = false;\n while (true)\n {\n \/\/ re-update internal state variables\n updateState(state, joint_angles);\n\n \/\/ calculate a Jacobian (relating joint-space updates\/deltas to cartesian-space errors\/deltas)\n \/\/ and the associated cartesian-space error\/delta vector\n \/\/ Primary Constraints\n constrained_ik::ConstraintResults primary = evalConstraint(constraint_types::Primary, state);\n \/\/ TODO since we already have J_p = USV, use that to get null-projection too.\n \/\/ otherwise, we are repeating the expensive calculation of the SVD\n MatrixXd Ji_p = calcDampedPseudoinverse(primary.jacobian);\n VectorXd dJoint_p = kpp_*(Ji_p*primary.error);\n if(dJoint_p.norm() > 1.0)\/\/ limit maximum update to unit size 1 radian \/meter\n {\n dJoint_p = dJoint_p\/dJoint_p.norm();\n }\n ROS_DEBUG(\"theta_p = %f ep = %f\",dJoint_p.norm(), primary.error.norm());\n\n\n \/\/ Auxiliary Constraints\n VectorXd dJoint_a;\n constrained_ik::ConstraintResults auxiliary;\n dJoint_a.setZero(dJoint_p.size());\n if (state.condition == initialization_state::PrimaryAndAuxiliary)\n {\n auxiliary = evalConstraint(constraint_types::Auxiliary, state);\n MatrixXd N_p = calcNullspaceProjectionTheRightWay(auxiliary.jacobian);\n MatrixXd Jnull_a = calcDampedPseudoinverse(auxiliary.jacobian*N_p);\n dJoint_a = kpa_*Jnull_a*(auxiliary.error-auxiliary.jacobian*dJoint_p);\n }\n\n \/\/ Check the status of convergence\n if(state.condition = initialization_state::PrimaryAndAuxiliary)\n {\n status = checkStatus(state, primary, auxiliary);\n\n if(state.iter > max_iter_*.9)\n ROS_ERROR(\"theta_p = %f theta_a = %f ep = %f ea = %f\", dJoint_p.norm(), dJoint_a.norm(), primary.error.norm(), auxiliary.error.norm());\n }\n else if(state.condition = initialization_state::PrimaryOnly)\n {\n status = checkStatus(state, primary);\n\n if(state.iter > max_iter_*.9)\n ROS_ERROR(\"theta_p = %f ep = %f \", dJoint_p.norm(), primary.error.norm());\n }\n\n if(status && min_updates<=0)\n {\n break;\n }\n else\n {\n \/\/ update joint solution by the calculated update (or a partial fraction)\n joint_angles += (dJoint_p + dJoint_a);\n clipToJointLimits(joint_angles);\n min_updates--;\n }\n }\n\n if (state.iter == max_iter_)\n joint_angles = cached_joint_angles;\n\n \/\/ checking for collision on a valid planning scene\n if(planning_scene && collision_checks_required())\n {\n moveit::core::RobotStatePtr robot_state(new moveit::core::RobotState(planning_scene->getCurrentState()));\n robot_state->setJointGroupPositions(kin_.getJointModelGroup()->getName(),joint_angles);\n robot_state->update();\n if(planning_scene->isStateColliding(*robot_state,kin_.getJointModelGroup()->getName()))\n {\n ROS_ERROR(\"Robot is in collision at this pose\");\n }\n }\n\n ROS_INFO_STREAM(\"IK solution: \" << joint_angles.transpose());\n}\n\nbool Constrained_IK::checkStatus(const constrained_ik::SolverState &state, const constrained_ik::ConstraintResults &primary) const\n{\n if (primary.status)\n return true;\n\n \/\/ check maximum iterations\n if (state.iter > max_iter_)\n throw std::runtime_error(\"Maximum iterations reached. IK solution may be invalid.\");\n\n \/\/ check for joint convergence\n \/\/ - this is an error: joints stabilize, but goal pose not reached\n if (state.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)\n {\n ROS_WARN_STREAM(\"Reached \" << state.iter << \" \/ \" << max_iter_ << \" iterations before convergence.\");\n return true;\n }\n\n return false;\n}\n\nbool Constrained_IK::checkStatus(const constrained_ik::SolverState &state, const constrained_ik::ConstraintResults &primary, const constrained_ik::ConstraintResults &auxiliary) const\n{\n if (primary.status && auxiliary.status)\n return true;\n\n \/\/ check maximum iterations\n if (state.iter > max_iter_)\n throw std::runtime_error(\"Maximum iterations reached. IK solution may be invalid.\");\n\n \/\/ check for joint convergence\n \/\/ - this is an error: joints stabilize, but goal pose not reached\n if (state.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)\n {\n ROS_WARN_STREAM(\"Reached \" << state.iter << \" \/ \" << max_iter_ << \" iterations before convergence.\");\n return true;\n }\n\n return false;\n}\n\nvoid Constrained_IK::clearConstraintList()\n{\n primary_constraints_.clear();\n auxiliary_constraints_.clear();\n}\n\nvoid Constrained_IK::clipToJointLimits(Eigen::VectorXd &joints) const\n{\n const MatrixXd limits = kin_.getLimits();\n const VectorXd orig_joints(joints);\n\n if (joints.size() != limits.rows())\n throw std::invalid_argument(\"clipToJointLimits: Unexpected number of joints\");\n\n for (size_t i=0; i<limits.rows(); ++i)\n {\n joints[i] = std::max(limits(i,0), std::min(limits(i,1), joints[i]));\n }\n if (debug_ && !joints.isApprox(orig_joints))\n ROS_WARN(\"Joints have been clipped\");\n}\n\nvoid Constrained_IK::init(const basic_kin::BasicKin &kin)\n{\n if (!kin.checkInitialized())\n throw std::invalid_argument(\"Input argument 'BasicKin' must be initialized\");\n\n ros::NodeHandle pnh(\"~\");\n pnh.getParam(\"primary_kp\", kpp_);\n pnh.getParam(\"auxiliary_kp\", kpa_);\n ROS_INFO(\"using primary kp=%f and auxiliary kp=%f\", kpp_, kpa_);\n kin_ = kin;\n initialized_ = true;\n primary_constraints_.init(this);\n auxiliary_constraints_.init(this);\n\n}\n\ndouble Constrained_IK::rangedAngle(double angle)\n{\n angle = copysign(fmod(fabs(angle),2.0*M_PI), angle);\n if (angle < -M_PI) return angle+2.*M_PI;\n if (angle > M_PI) return angle-2.*M_PI;\n return angle;\n}\n\nconstrained_ik::SolverState Constrained_IK::getState(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed) const\n{\n if (!kin_.checkJoints(joint_seed))\n throw std::invalid_argument(\"Seed doesn't match kinematic model\");\n\n if (!goal.matrix().block(0,0,3,3).isUnitary(1e-6))\n throw std::invalid_argument(\"Goal pose not proper affine\");\n\n return constrained_ik::SolverState(goal, joint_seed);\n}\n\nvoid Constrained_IK::updateState(constrained_ik::SolverState &state, const Eigen::VectorXd &joints) const\n{\n \/\/ update maximum iterations\n state.iter++;\n\n \/\/ update joint convergence\n state.joints_delta = joints - state.joints;\n state.joints = joints;\n kin_.calcFwdKin(joints, state.pose_estimate);\n\n if(state.planning_scene && state.robot_state)\n {\n state.robot_state->setJointGroupPositions(kin_.getJointModelGroup()->getName(), joints);\n state.robot_state->update();\n }\n\n if (debug_)\n state.iteration_path.push_back(joints);\n\n}\n\nbool Constrained_IK::collision_checks_required() const\n{\n return( primary_constraints_.collision_checks_required() | auxiliary_constraints_.collision_checks_required());\n}\n\n\n} \/\/ namespace constrained_ik\n\n<commit_msg>Fix syntax error in constrained_ik.cpp<commit_after>\/**\n * @file constrained_ik.cpp\n * @brief Basic low-level kinematics functions.\n *\n * Typically, just wrappers around the equivalent KDL calls.\n *\n * @author dsolomon\n * @date Sep 15, 2013\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2013, Southwest Research Institute\n *\n * @license Software License Agreement (Apache License)\\n\n * \\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\\n\n * \\n\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\\n\n * \\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"constrained_ik\/constrained_ik.h\"\n#include \"constrained_ik\/constraint_group.h\"\n#include <boost\/make_shared.hpp>\n\/\/#include <moveit\/collision_detection_fcl\/collision_common.h>\n#include <constrained_ik\/collision_robot_fcl_detailed.h>\n#include <constrained_ik\/constraint_results.h>\n#include <ros\/ros.h>\n\nnamespace constrained_ik\n{\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::Affine3d;\n\nConstrained_IK::Constrained_IK()\n{\n initialized_ = false;\n max_iter_ = 500; \/\/default max_iter\n joint_convergence_tol_ = 0.0001; \/\/default convergence tolerance\n debug_ = false;\n kpp_ = 1.0;\/\/ default primary proportional gain\n kpa_ = 0.5;\/\/ default auxillary proportional gain\n}\n\nconstrained_ik::ConstraintResults Constrained_IK::evalConstraint(constraint_types::ConstraintType constraint_type, const constrained_ik::SolverState &state) const\n{\n switch(constraint_type)\n {\n case constraint_types::Primary:\n return primary_constraints_.evalConstraint(state);\n case constraint_types::Auxiliary:\n return auxiliary_constraints_.evalConstraint(state);\n }\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjection(const Eigen::MatrixXd &J) const\n{\n MatrixXd J_pinv = calcDampedPseudoinverse(J);\n MatrixXd JplusJ = J_pinv * J;\n int mn = JplusJ.rows();\n MatrixXd P = MatrixXd::Identity(mn,mn)-JplusJ;\n return (P);\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjectionTheRightWay(const Eigen::MatrixXd &A) const\n{\n Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeFullV);\n MatrixXd V(svd.matrixV());\n\n \/\/ determine rank using same algorithym as latest Eigen\n \/\/ TODO replace next 10 lines of code with rnk = svd.rank(); once eigen3 is updated\n int rnk = 0;\n if(svd.singularValues().size()==0)\n {\n rnk = 0;\n }\n else\n {\n double threshold = std::min(A.rows(),A.cols())*Eigen::NumTraits<double>::epsilon();\n double premultiplied_threshold = svd.singularValues().coeff(0) * threshold;\n rnk = svd.nonzeroSingularValues()-1;\n while(rnk>=0 && svd.singularValues().coeff(rnk) < premultiplied_threshold) --rnk;\n rnk++;\n }\n\n \/\/ zero singular vectors in the range of A\n for(int i=0; i<rnk; ++i)\n {\n for(int j=0; j<A.cols(); j++) V(j,i) = 0;\n }\n\n MatrixXd P = V * V.transpose();\n return(P);\n}\n\nEigen::MatrixXd Constrained_IK::calcDampedPseudoinverse(const Eigen::MatrixXd &J) const\n{\n MatrixXd J_pinv;\n\n if (basic_kin::BasicKin::dampedPInv(J,J_pinv))\n {\n return J_pinv;\n }\n else\n {\n ROS_ERROR_STREAM(\"Not able to calculate damped pseudoinverse!\");\n throw std::runtime_error(\"Not able to calculate damped pseudoinverse! IK solution may be invalid.\");\n }\n}\n\nvoid Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n const Eigen::VectorXd &joint_seed,\n Eigen::VectorXd &joint_angles,\n int min_updates) const\n{\n calcInvKin(goal,joint_seed, planning_scene::PlanningSceneConstPtr(), joint_angles, min_updates);\n}\n\nvoid Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n const Eigen::VectorXd &joint_seed,\n const planning_scene::PlanningSceneConstPtr planning_scene,\n Eigen::VectorXd &joint_angles,\n int min_updates) const\n{\n \/\/ initialize state\n joint_angles = joint_seed; \/\/ initialize result to seed value\n constrained_ik::SolverState state = getState(goal, joint_seed); \/\/ create state vars for this IK solve\n state.condition = checkInitialized();\n state.planning_scene = planning_scene;\n if(planning_scene)\n {\n state.robot_state = robot_state::RobotStatePtr(new moveit::core::RobotState(planning_scene->getCurrentState()));\n state.collision_robot = CollisionRobotFCLDetailed::CollisionRobotFCLDetailedPtr(new CollisionRobotFCLDetailed(planning_scene->getRobotModel()));\n }\n\n if (state.condition == initialization_state::NothingInitialized || state.condition == initialization_state::AuxiliaryOnly)\n throw std::runtime_error(\"Must call init() before using Constrained_IK and have a primary constraint.\");\n\n \/\/Cache the joint angles to return if max iteration is reached.\n Eigen::VectorXd cached_joint_angles = joint_seed;\n\n \/\/ iterate until solution converges (or aborted)\n bool status = false;\n while (true)\n {\n \/\/ re-update internal state variables\n updateState(state, joint_angles);\n\n \/\/ calculate a Jacobian (relating joint-space updates\/deltas to cartesian-space errors\/deltas)\n \/\/ and the associated cartesian-space error\/delta vector\n \/\/ Primary Constraints\n constrained_ik::ConstraintResults primary = evalConstraint(constraint_types::Primary, state);\n \/\/ TODO since we already have J_p = USV, use that to get null-projection too.\n \/\/ otherwise, we are repeating the expensive calculation of the SVD\n MatrixXd Ji_p = calcDampedPseudoinverse(primary.jacobian);\n VectorXd dJoint_p = kpp_*(Ji_p*primary.error);\n if(dJoint_p.norm() > 1.0)\/\/ limit maximum update to unit size 1 radian \/meter\n {\n dJoint_p = dJoint_p\/dJoint_p.norm();\n }\n ROS_DEBUG(\"theta_p = %f ep = %f\",dJoint_p.norm(), primary.error.norm());\n\n\n \/\/ Auxiliary Constraints\n VectorXd dJoint_a;\n constrained_ik::ConstraintResults auxiliary;\n dJoint_a.setZero(dJoint_p.size());\n if (state.condition == initialization_state::PrimaryAndAuxiliary)\n {\n auxiliary = evalConstraint(constraint_types::Auxiliary, state);\n MatrixXd N_p = calcNullspaceProjectionTheRightWay(auxiliary.jacobian);\n MatrixXd Jnull_a = calcDampedPseudoinverse(auxiliary.jacobian*N_p);\n dJoint_a = kpa_*Jnull_a*(auxiliary.error-auxiliary.jacobian*dJoint_p);\n }\n\n \/\/ Check the status of convergence\n if(state.condition == initialization_state::PrimaryAndAuxiliary)\n {\n status = checkStatus(state, primary, auxiliary);\n\n if(state.iter > max_iter_*.9)\n ROS_ERROR(\"theta_p = %f theta_a = %f ep = %f ea = %f\", dJoint_p.norm(), dJoint_a.norm(), primary.error.norm(), auxiliary.error.norm());\n }\n else if(state.condition == initialization_state::PrimaryOnly)\n {\n status = checkStatus(state, primary);\n\n if(state.iter > max_iter_*.9)\n ROS_ERROR(\"theta_p = %f ep = %f \", dJoint_p.norm(), primary.error.norm());\n }\n\n if(status && min_updates<=0)\n {\n break;\n }\n else\n {\n \/\/ update joint solution by the calculated update (or a partial fraction)\n joint_angles += (dJoint_p + dJoint_a);\n clipToJointLimits(joint_angles);\n min_updates--;\n }\n }\n\n if (state.iter == max_iter_)\n joint_angles = cached_joint_angles;\n\n \/\/ checking for collision on a valid planning scene\n if(planning_scene && collision_checks_required())\n {\n moveit::core::RobotStatePtr robot_state(new moveit::core::RobotState(planning_scene->getCurrentState()));\n robot_state->setJointGroupPositions(kin_.getJointModelGroup()->getName(),joint_angles);\n robot_state->update();\n if(planning_scene->isStateColliding(*robot_state,kin_.getJointModelGroup()->getName()))\n {\n ROS_ERROR(\"Robot is in collision at this pose\");\n }\n }\n\n ROS_INFO_STREAM(\"IK solution: \" << joint_angles.transpose());\n}\n\nbool Constrained_IK::checkStatus(const constrained_ik::SolverState &state, const constrained_ik::ConstraintResults &primary) const\n{\n if (primary.status)\n return true;\n\n \/\/ check maximum iterations\n if (state.iter > max_iter_)\n throw std::runtime_error(\"Maximum iterations reached. IK solution may be invalid.\");\n\n \/\/ check for joint convergence\n \/\/ - this is an error: joints stabilize, but goal pose not reached\n if (state.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)\n {\n ROS_WARN_STREAM(\"Reached \" << state.iter << \" \/ \" << max_iter_ << \" iterations before convergence.\");\n return true;\n }\n\n return false;\n}\n\nbool Constrained_IK::checkStatus(const constrained_ik::SolverState &state, const constrained_ik::ConstraintResults &primary, const constrained_ik::ConstraintResults &auxiliary) const\n{\n if (primary.status && auxiliary.status)\n return true;\n\n \/\/ check maximum iterations\n if (state.iter > max_iter_)\n throw std::runtime_error(\"Maximum iterations reached. IK solution may be invalid.\");\n\n \/\/ check for joint convergence\n \/\/ - this is an error: joints stabilize, but goal pose not reached\n if (state.joints_delta.cwiseAbs().maxCoeff() < joint_convergence_tol_)\n {\n ROS_WARN_STREAM(\"Reached \" << state.iter << \" \/ \" << max_iter_ << \" iterations before convergence.\");\n return true;\n }\n\n return false;\n}\n\nvoid Constrained_IK::clearConstraintList()\n{\n primary_constraints_.clear();\n auxiliary_constraints_.clear();\n}\n\nvoid Constrained_IK::clipToJointLimits(Eigen::VectorXd &joints) const\n{\n const MatrixXd limits = kin_.getLimits();\n const VectorXd orig_joints(joints);\n\n if (joints.size() != limits.rows())\n throw std::invalid_argument(\"clipToJointLimits: Unexpected number of joints\");\n\n for (size_t i=0; i<limits.rows(); ++i)\n {\n joints[i] = std::max(limits(i,0), std::min(limits(i,1), joints[i]));\n }\n if (debug_ && !joints.isApprox(orig_joints))\n ROS_WARN(\"Joints have been clipped\");\n}\n\nvoid Constrained_IK::init(const basic_kin::BasicKin &kin)\n{\n if (!kin.checkInitialized())\n throw std::invalid_argument(\"Input argument 'BasicKin' must be initialized\");\n\n ros::NodeHandle pnh(\"~\");\n pnh.getParam(\"primary_kp\", kpp_);\n pnh.getParam(\"auxiliary_kp\", kpa_);\n ROS_INFO(\"using primary kp=%f and auxiliary kp=%f\", kpp_, kpa_);\n kin_ = kin;\n initialized_ = true;\n primary_constraints_.init(this);\n auxiliary_constraints_.init(this);\n\n}\n\ndouble Constrained_IK::rangedAngle(double angle)\n{\n angle = copysign(fmod(fabs(angle),2.0*M_PI), angle);\n if (angle < -M_PI) return angle+2.*M_PI;\n if (angle > M_PI) return angle-2.*M_PI;\n return angle;\n}\n\nconstrained_ik::SolverState Constrained_IK::getState(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed) const\n{\n if (!kin_.checkJoints(joint_seed))\n throw std::invalid_argument(\"Seed doesn't match kinematic model\");\n\n if (!goal.matrix().block(0,0,3,3).isUnitary(1e-6))\n throw std::invalid_argument(\"Goal pose not proper affine\");\n\n return constrained_ik::SolverState(goal, joint_seed);\n}\n\nvoid Constrained_IK::updateState(constrained_ik::SolverState &state, const Eigen::VectorXd &joints) const\n{\n \/\/ update maximum iterations\n state.iter++;\n\n \/\/ update joint convergence\n state.joints_delta = joints - state.joints;\n state.joints = joints;\n kin_.calcFwdKin(joints, state.pose_estimate);\n\n if(state.planning_scene && state.robot_state)\n {\n state.robot_state->setJointGroupPositions(kin_.getJointModelGroup()->getName(), joints);\n state.robot_state->update();\n }\n\n if (debug_)\n state.iteration_path.push_back(joints);\n\n}\n\nbool Constrained_IK::collision_checks_required() const\n{\n return( primary_constraints_.collision_checks_required() | auxiliary_constraints_.collision_checks_required());\n}\n\n\n} \/\/ namespace constrained_ik\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: unodoc.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2004-02-25 17:23:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ System - Includes -----------------------------------------------------\n\n#include <tools\/string.hxx>\n#include <sfx2\/docfac.hxx>\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#include \"scmod.hxx\"\n\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#include \"docsh.hxx\"\n\nusing namespace ::com::sun::star;\n\n::rtl::OUString SAL_CALL ScDocument_getImplementationName() throw()\n{\n return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.comp.Calc.SpreadsheetDocument\" ) );\n}\n\nuno::Sequence< rtl::OUString > SAL_CALL ScDocument_getSupportedServiceNames() throw()\n{\n uno::Sequence< rtl::OUString > aSeq( 1 );\n aSeq[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.sheet.SpreadsheetDocument\" ));\n return aSeq;\n}\n\nuno::Reference< uno::XInterface > SAL_CALL ScDocument_createInstance(\n const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n ScDLL::Init();\n SfxObjectShell* pShell = new ScDocShell( SFX_CREATE_MODE_STANDARD );\n return uno::Reference< uno::XInterface >( pShell->GetModel() );\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.520); FILE MERGED 2005\/09\/05 15:09:03 rt 1.6.520.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unodoc.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:51:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ System - Includes -----------------------------------------------------\n\n#include <tools\/string.hxx>\n#include <sfx2\/docfac.hxx>\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#include \"scmod.hxx\"\n\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#include \"docsh.hxx\"\n\nusing namespace ::com::sun::star;\n\n::rtl::OUString SAL_CALL ScDocument_getImplementationName() throw()\n{\n return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.comp.Calc.SpreadsheetDocument\" ) );\n}\n\nuno::Sequence< rtl::OUString > SAL_CALL ScDocument_getSupportedServiceNames() throw()\n{\n uno::Sequence< rtl::OUString > aSeq( 1 );\n aSeq[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.sheet.SpreadsheetDocument\" ));\n return aSeq;\n}\n\nuno::Reference< uno::XInterface > SAL_CALL ScDocument_createInstance(\n const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception )\n{\n ::vos::OGuard aGuard( Application::GetSolarMutex() );\n ScDLL::Init();\n SfxObjectShell* pShell = new ScDocShell( SFX_CREATE_MODE_STANDARD );\n return uno::Reference< uno::XInterface >( pShell->GetModel() );\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Pedis is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* You may obtain a copy of the License at\n*\n* http:\/\/www.gnu.org\/licenses\n*\n* Unless required by applicable law or agreed to in writing,\n* software distributed under the License is distributed on an\n* \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n* KIND, either express or implied. See the License for the\n* specific language governing permissions and limitations\n* under the License.\n* \n* Copyright (c) 2016-2026, Peng Jian, pstack@163.com. All rights reserved.\n*\n*\/\n#pragma once\n#include \"redis.hh\"\n#include \"db.hh\"\n#include \"redis.hh\"\n#include \"redis_protocol.hh\"\n#include \"core\/metrics_registration.hh\"\n#include \"core\/thread.hh\"\nnamespace redis {\nclass server {\nprivate:\n lw_shared_ptr<server_socket> _listener;\n redis_service& _redis;\n uint16_t _port;\n struct connection {\n connected_socket _socket;\n socket_address _addr;\n input_stream<char> _in;\n output_stream<char> _out;\n redis_protocol _proto;\n connection(connected_socket&& socket, socket_address addr, redis_service& redis)\n : _socket(std::move(socket))\n , _addr(addr)\n , _in(_socket.input())\n , _out(_socket.output())\n , _proto(redis)\n {\n }\n ~connection() {\n }\n };\n seastar::metrics::metric_groups _metrics;\n void setup_metrics();\n struct connection_stats {\n uint64_t _new_connection_count = 0;\n uint64_t _alived_connection_count = 0;\n };\n connection_stats _stats;\npublic:\n server(redis_service& db, uint16_t port = 6379)\n : _redis(db)\n , _port(port)\n {\n setup_metrics();\n }\n\n void start() {\n listen_options lo;\n lo.reuse_address = true;\n _listener = engine().listen(make_ipv4_address({_port}), lo);\n keep_doing([this] {\n return _listener->accept().then([this] (connected_socket fd, socket_address addr) mutable {\n return seastar::async([this, &fd, addr] {\n ++_stats._new_connection_count;\n ++_stats._alived_connection_count;\n auto conn = make_lw_shared<connection>(std::move(fd), addr, _redis);\n do_until([conn] { return conn->_in.eof(); }, [this, conn] {\n return conn->_proto.handle(conn->_in, conn->_out).then([conn] {\n return conn->_out.flush();\n });\n }).finally([this, conn] {\n --_stats._alived_connection_count;\n return conn->_out.close().finally([conn]{});\n });\n });\n });\n }).or_terminate();\n }\n future<> stop() {\n return make_ready_future<>();\n }\n};\n} \/* namespace redis *\/\n<commit_msg>not to process request in the seastar thread code<commit_after>\/*\n* Pedis is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* You may obtain a copy of the License at\n*\n* http:\/\/www.gnu.org\/licenses\n*\n* Unless required by applicable law or agreed to in writing,\n* software distributed under the License is distributed on an\n* \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n* KIND, either express or implied. See the License for the\n* specific language governing permissions and limitations\n* under the License.\n* \n* Copyright (c) 2016-2026, Peng Jian, pstack@163.com. All rights reserved.\n*\n*\/\n#pragma once\n#include \"redis.hh\"\n#include \"db.hh\"\n#include \"redis.hh\"\n#include \"redis_protocol.hh\"\n#include \"core\/metrics_registration.hh\"\n#include \"core\/thread.hh\"\nnamespace redis {\nclass server {\nprivate:\n lw_shared_ptr<server_socket> _listener;\n redis_service& _redis;\n uint16_t _port;\n struct connection {\n connected_socket _socket;\n socket_address _addr;\n input_stream<char> _in;\n output_stream<char> _out;\n redis_protocol _proto;\n connection(connected_socket&& socket, socket_address addr, redis_service& redis)\n : _socket(std::move(socket))\n , _addr(addr)\n , _in(_socket.input())\n , _out(_socket.output())\n , _proto(redis)\n {\n }\n ~connection() {\n }\n };\n seastar::metrics::metric_groups _metrics;\n void setup_metrics();\n struct connection_stats {\n uint64_t _new_connection_count = 0;\n uint64_t _alived_connection_count = 0;\n };\n connection_stats _stats;\npublic:\n server(redis_service& db, uint16_t port = 6379)\n : _redis(db)\n , _port(port)\n {\n setup_metrics();\n }\n\n void start() {\n listen_options lo;\n lo.reuse_address = true;\n _listener = engine().listen(make_ipv4_address({_port}), lo);\n keep_doing([this] {\n return _listener->accept().then([this] (connected_socket fd, socket_address addr) mutable {\n ++_stats._new_connection_count;\n ++_stats._alived_connection_count;\n auto conn = make_lw_shared<connection>(std::move(fd), addr, _redis);\n do_until([conn] { return conn->_in.eof(); }, [this, conn] {\n return conn->_proto.handle(conn->_in, conn->_out).then([conn] {\n return conn->_out.flush();\n });\n }).finally([this, conn] {\n --_stats._alived_connection_count;\n return conn->_out.close().finally([conn]{});\n });\n });\n }).or_terminate();\n }\n future<> stop() {\n return make_ready_future<>();\n }\n};\n} \/* namespace redis *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"rpcruntime_decoded_param.h\"\n#include \"rpcruntime_paramter_description.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n#include <sstream>\n\ntemplate <class Container>\nstruct Reverse_container {\n Reverse_container(Container &container)\n : container(container) {}\n auto begin() {\n return container.rbegin();\n }\n\n auto end() {\n return container.rend();\n }\n\n private:\n Container &container;\n};\n\ntemplate <class Container>\nReverse_container<Container> reverse_view(Container &container) {\n return {container};\n}\n\nRPCRuntimeDecodedParam::RPCRuntimeDecodedParam(const RPCRuntimeParameterDescription ¶meter_description, std::string field_id)\n : parameter_description(¶meter_description) {\n this->field_id = field_id;\n}\n\ntemplate <class T>\nT parse_signed_int(const std::vector<unsigned char> &data) {\n T retval = 0;\n for (auto &chr : reverse_view(data)) {\n retval <<= 8;\n retval |= chr;\n }\n return retval;\n}\n\ntemplate <>\nuint8_t parse_signed_int<uint8_t>(const std::vector<unsigned char> &data) {\n return data[0];\n}\n\ntemplate <>\nint8_t parse_signed_int<int8_t>(const std::vector<unsigned char> &data) {\n return data[0];\n}\n\nuint64_t RPCRuntimeDecodedParam::as_unsigned_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n assert(parameter_description->as_integer().is_signed == false);\n return parse_signed_int<uint64_t>(data);\n}\n\nint64_t RPCRuntimeDecodedParam::as_signed_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n assert(parameter_description->as_integer().is_signed == true);\n switch (data.size()) {\n case 1:\n return parse_signed_int<int8_t>(data);\n case 2:\n return parse_signed_int<int16_t>(data);\n case 4:\n return parse_signed_int<int32_t>(data);\n case 8:\n return parse_signed_int<int64_t>(data);\n }\n throw std::domain_error(\"RPC: Invalid amount of data to parse signed integer\");\n}\n\nint64_t RPCRuntimeDecodedParam::as_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n if (parameter_description->as_integer().is_signed == true) {\n return as_signed_integer();\n }\n assert(parameter_description->get_bit_size() < 64); \/\/make sure we don't have a uint64_t, because we cannot represent it fully in an int64_t\n return as_unsigned_integer();\n}\n\nDecoded_enum RPCRuntimeDecodedParam::as_enum() const {\n int value = parse_signed_int<int>(data);\n std::string name;\n for (auto &enum_value : parameter_description->as_enumeration().values) {\n if (enum_value.is_int()) {\n if (enum_value.to_int() == value) {\n name = enum_value.name;\n break;\n }\n }\n }\n return {name, value};\n}\n\nstd::vector<Decoded_struct> RPCRuntimeDecodedParam::as_struct() const {\n std::vector<Decoded_struct> retval;\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::structure);\n int current_data_position = 0;\n for (auto &member : parameter_description->as_structure().members) {\n retval.push_back({member.get_parameter_name(), {member, field_id + \".\" + member.get_parameter_name()}});\n auto data_size = member.get_bit_size() \/ 8;\n retval.back().type.set_data(data.data() + current_data_position, data_size);\n current_data_position += data_size;\n }\n assert(current_data_position == static_cast<int>(data.size()));\n return retval;\n}\n\nstd::vector<RPCRuntimeDecodedParam> RPCRuntimeDecodedParam::as_array() const {\n std::vector<RPCRuntimeDecodedParam> retval;\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::array);\n for (int i = 0; i < parameter_description->as_array().number_of_elements; i++) {\n retval.emplace_back(parameter_description->as_array().type, field_id + \".\" + std::to_string(i));\n retval.back().set_data(data.data() + i * parameter_description->as_array().type.get_bit_size() \/ 8,\n parameter_description->as_array().type.get_bit_size() \/ 8);\n }\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::as_full_string() const {\n std::string retval;\n retval.resize(data.size());\n std::copy(std::begin(data), std::end(data), std::begin(retval));\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::as_string() const {\n std::string retval;\n retval.reserve(data.size());\n for (auto &c : data) {\n if (c == '\\0') {\n break;\n }\n retval.push_back(c);\n }\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::get_field_id() const {\n return field_id;\n}\n\nconst RPCRuntimeParameterDescription *RPCRuntimeDecodedParam::get_desciption() const {\n return parameter_description;\n}\n\nvoid RPCRuntimeDecodedParam::set_data(std::vector<unsigned char> data) {\n this->data = std::move(data);\n}\n\nvoid RPCRuntimeDecodedParam::set_data(const unsigned char *begin, int size) {\n data.resize(size);\n std::copy(begin, begin + size, std::begin(data));\n}\n\nstd::istream &operator>>(std::istream &is, RPCRuntimeDecodedParam ¶m) {\n const auto byte_size = param.get_desciption()->get_bit_size() \/ 8;\n std::vector<unsigned char> data;\n data.resize(byte_size);\n is.read(reinterpret_cast<char *>(data.data()), byte_size);\n if (is) {\n param.set_data(std::move(data));\n }\n return is;\n}\n<commit_msg>if struct size is not generated correctly in xml, it will be a thrown exception now rather than a failing assert<commit_after>#include \"rpcruntime_decoded_param.h\"\n#include \"rpcruntime_paramter_description.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n#include <sstream>\n\ntemplate <class Container>\nstruct Reverse_container {\n Reverse_container(Container &container)\n : container(container) {}\n auto begin() {\n return container.rbegin();\n }\n\n auto end() {\n return container.rend();\n }\n\n private:\n Container &container;\n};\n\ntemplate <class Container>\nReverse_container<Container> reverse_view(Container &container) {\n return {container};\n}\n\nRPCRuntimeDecodedParam::RPCRuntimeDecodedParam(const RPCRuntimeParameterDescription ¶meter_description, std::string field_id)\n : parameter_description(¶meter_description) {\n this->field_id = field_id;\n}\n\ntemplate <class T>\nT parse_signed_int(const std::vector<unsigned char> &data) {\n T retval = 0;\n for (auto &chr : reverse_view(data)) {\n retval <<= 8;\n retval |= chr;\n }\n return retval;\n}\n\ntemplate <>\nuint8_t parse_signed_int<uint8_t>(const std::vector<unsigned char> &data) {\n return data[0];\n}\n\ntemplate <>\nint8_t parse_signed_int<int8_t>(const std::vector<unsigned char> &data) {\n return data[0];\n}\n\nuint64_t RPCRuntimeDecodedParam::as_unsigned_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n assert(parameter_description->as_integer().is_signed == false);\n return parse_signed_int<uint64_t>(data);\n}\n\nint64_t RPCRuntimeDecodedParam::as_signed_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n assert(parameter_description->as_integer().is_signed == true);\n switch (data.size()) {\n case 1:\n return parse_signed_int<int8_t>(data);\n case 2:\n return parse_signed_int<int16_t>(data);\n case 4:\n return parse_signed_int<int32_t>(data);\n case 8:\n return parse_signed_int<int64_t>(data);\n }\n throw std::domain_error(\"RPC: Invalid amount of data to parse signed integer\");\n}\n\nint64_t RPCRuntimeDecodedParam::as_integer() const {\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::integer);\n if (parameter_description->as_integer().is_signed == true) {\n return as_signed_integer();\n }\n assert(parameter_description->get_bit_size() < 64); \/\/make sure we don't have a uint64_t, because we cannot represent it fully in an int64_t\n return as_unsigned_integer();\n}\n\nDecoded_enum RPCRuntimeDecodedParam::as_enum() const {\n int value = parse_signed_int<int>(data);\n std::string name;\n for (auto &enum_value : parameter_description->as_enumeration().values) {\n if (enum_value.is_int()) {\n if (enum_value.to_int() == value) {\n name = enum_value.name;\n break;\n }\n }\n }\n return {name, value};\n}\n\nstd::vector<Decoded_struct> RPCRuntimeDecodedParam::as_struct() const {\n std::vector<Decoded_struct> retval;\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::structure);\n int current_data_position = 0;\n for (auto &member : parameter_description->as_structure().members) {\n retval.push_back({member.get_parameter_name(), {member, field_id + \".\" + member.get_parameter_name()}});\n auto data_size = member.get_bit_size() \/ 8;\n retval.back().type.set_data(data.data() + current_data_position, data_size);\n current_data_position += data_size;\n }\n if (current_data_position != static_cast<int>(data.size())) {\n throw std::runtime_error(\"RPC struct size messed up. Typename: \" + parameter_description->get_parameter_type());\n }\n assert(current_data_position == static_cast<int>(data.size()));\n return retval;\n}\n\nstd::vector<RPCRuntimeDecodedParam> RPCRuntimeDecodedParam::as_array() const {\n std::vector<RPCRuntimeDecodedParam> retval;\n assert(parameter_description->get_type() == RPCRuntimeParameterDescription::Type::array);\n for (int i = 0; i < parameter_description->as_array().number_of_elements; i++) {\n retval.emplace_back(parameter_description->as_array().type, field_id + \".\" + std::to_string(i));\n retval.back().set_data(data.data() + i * parameter_description->as_array().type.get_bit_size() \/ 8,\n parameter_description->as_array().type.get_bit_size() \/ 8);\n }\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::as_full_string() const {\n std::string retval;\n retval.resize(data.size());\n std::copy(std::begin(data), std::end(data), std::begin(retval));\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::as_string() const {\n std::string retval;\n retval.reserve(data.size());\n for (auto &c : data) {\n if (c == '\\0') {\n break;\n }\n retval.push_back(c);\n }\n return retval;\n}\n\nstd::string RPCRuntimeDecodedParam::get_field_id() const {\n return field_id;\n}\n\nconst RPCRuntimeParameterDescription *RPCRuntimeDecodedParam::get_desciption() const {\n return parameter_description;\n}\n\nvoid RPCRuntimeDecodedParam::set_data(std::vector<unsigned char> data) {\n this->data = std::move(data);\n}\n\nvoid RPCRuntimeDecodedParam::set_data(const unsigned char *begin, int size) {\n data.resize(size);\n std::copy(begin, begin + size, std::begin(data));\n}\n\nstd::istream &operator>>(std::istream &is, RPCRuntimeDecodedParam ¶m) {\n const auto byte_size = param.get_desciption()->get_bit_size() \/ 8;\n std::vector<unsigned char> data;\n data.resize(byte_size);\n is.read(reinterpret_cast<char *>(data.data()), byte_size);\n if (is) {\n param.set_data(std::move(data));\n }\n return is;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/frames\/quic_new_token_frame.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_constants.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n\nnamespace quic {\n\nQuicNewTokenFrame::QuicNewTokenFrame()\n : control_frame_id(kInvalidControlFrameId) {}\n\nQuicNewTokenFrame::QuicNewTokenFrame(QuicControlFrameId control_frame_id,\n std::string token)\n : control_frame_id(control_frame_id), token(token) {}\n\nstd::ostream& operator<<(std::ostream& os, const QuicNewTokenFrame& s) {\n os << \"{ control_frame_id: \" << s.control_frame_id << \", token: \" << s.token\n << \" }\\n\";\n return os;\n}\n\n} \/\/ namespace quic\n<commit_msg>Fix logging of QuicNewTokenFrame<commit_after>\/\/ Copyright (c) 2018 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/frames\/quic_new_token_frame.h\"\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_constants.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_text_utils.h\"\n\nnamespace quic {\n\nQuicNewTokenFrame::QuicNewTokenFrame()\n : control_frame_id(kInvalidControlFrameId) {}\n\nQuicNewTokenFrame::QuicNewTokenFrame(QuicControlFrameId control_frame_id,\n std::string token)\n : control_frame_id(control_frame_id), token(token) {}\n\nstd::ostream& operator<<(std::ostream& os, const QuicNewTokenFrame& s) {\n os << \"{ control_frame_id: \" << s.control_frame_id\n << \", token: \" << QuicTextUtils::HexEncode(s.token) << \" }\\n\";\n return os;\n}\n\n} \/\/ namespace quic\n<|endoftext|>"} {"text":"<commit_before>\/*\n * OSPRayPKDGeometry.cpp\n * Copyright (C) 2009-2017 by MegaMol Team\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"stdafx.h\"\n#include \"OSPRayPKDGeometry.h\"\n#include \"mmcore\/Call.h\"\n#include \"mmcore\/moldyn\/MultiParticleDataCall.h\"\n#include \"mmcore\/param\/EnumParam.h\"\n#include \"mmcore\/param\/FloatParam.h\"\n#include \"mmcore\/param\/IntParam.h\"\n#include \"mmcore\/param\/Vector3fParam.h\"\n#include \"vislib\/forceinline.h\"\n#include \"vislib\/sys\/Log.h\"\n\n#include \"mmcore\/view\/CallClipPlane.h\"\n#include \"mmcore\/view\/CallGetTransferFunction.h\"\n#include <ospray.h>\n#include \"OSPRay_plugin\/CallOSPRayAPIObject.h\"\n\nnamespace megamol {\nnamespace ospray { \n\n\nOSPRayPKDGeometry::OSPRayPKDGeometry(void)\n : getDataSlot(\"getdata\", \"Connects to the data source\")\n , deployStructureSlot(\"deployStructureSlot\", \"Connects to an OSPRayAPIStructure\")\n , colorTypeSlot(\"colorType\", \"Set the type of encoded color\") {\n\n this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>();\n this->MakeSlotAvailable(&this->getDataSlot);\n\n auto ep = new megamol::core::param::EnumParam(0);\n ep->SetTypePair(0, \"none\");\n ep->SetTypePair(1, \"RGBu8\");\n ep->SetTypePair(2, \"RGBAu8\");\n ep->SetTypePair(3, \"RGBf\");\n ep->SetTypePair(4, \"RGBAf\");\n ep->SetTypePair(5, \"I\");\n this->colorTypeSlot << ep;\n this->MakeSlotAvailable(&this->colorTypeSlot);\n\n this->deployStructureSlot.SetCallback(CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(0), &OSPRayPKDGeometry::getDataCallback);\n this->deployStructureSlot.SetCallback(CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(1), &OSPRayPKDGeometry::getExtendsCallback);\n this->deployStructureSlot.SetCallback(CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(2), &OSPRayPKDGeometry::getDirtyCallback);\n this->MakeSlotAvailable(&this->deployStructureSlot);\n}\n\n\nbool OSPRayPKDGeometry::getDataCallback(megamol::core::Call& call) {\n\n \/\/ read Data, calculate shape parameters, fill data vectors\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n megamol::core::moldyn::MultiParticleDataCall* cd =\n this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>();\n\n if (!(*cd)(1)) return false;\n\n auto const minFrameCount = cd->FrameCount();\n\n if (minFrameCount == 0) return false;\n\n auto frameTime = 0;\n\n if (os->FrameID() >= minFrameCount) {\n cd->SetFrameID(minFrameCount - 1, true); \/\/ isTimeForced flag set to true\n frameTime = minFrameCount - 1;\n } else {\n cd->SetFrameID(os->FrameID(), true); \/\/ isTimeForced flag set to true\n frameTime = os->FrameID();\n }\n\n if (this->datahash != cd->DataHash() || this->time != frameTime || this->InterfaceIsDirty()) {\n this->datahash = cd->DataHash();\n this->time = frameTime;\n } else {\n return true;\n }\n\n if (!(*cd)(1)) return false;\n if (!(*cd)(0)) return false;\n\n size_t listCount = cd->GetParticleListCount();\n std::vector<OSPGeometry> geo;\n for (size_t i = 0; i < listCount; i++) {\n\n core::moldyn::MultiParticleDataCall::Particles& parts = cd->AccessParticles(i);\n\n auto partCount = parts.GetCount();\n auto globalRadius = parts.GetGlobalRadius();\n auto raw = parts.GetVertexData();\n auto boundingBox = parts.GetBBox();\n\n size_t vertexLength = 3;\n size_t colorLength = 0;\n\n auto colorType = this->colorTypeSlot.Param<megamol::core::param::EnumParam>()->Value();\n if (colorType != 0) {\n colorLength = 1;\n }\n\n geo.push_back(ospNewGeometry(\"pkd_geometry\"));\n\n auto vertexData = ospNewData(partCount, OSP_FLOAT4, raw, OSP_DATA_SHARED_BUFFER);\n ospCommit(vertexData);\n\n \/\/ set bbox\n auto bboxData = ospNewData(6, OSP_FLOAT, boundingBox.PeekBounds(), OSP_DATA_SHARED_BUFFER);\n ospCommit(bboxData);\n\n ospSet1f(geo.back(), \"radius\", globalRadius);\n ospSet1i(geo.back(), \"colorType\", colorType);\n ospSetData(geo.back(), \"position\", vertexData);\n ospSetData(geo.back(), \"bbox\", bboxData);\n ospCommit(geo.back());\n\n \/\/ TODO: implement distributed stuff\n \/\/ if (this->rd_type.Param<megamol::core::param::EnumParam>()->Value() == MPI_RAYCAST) {\n \/\/ auto const half_radius = element.globalRadius * 0.5f;\n\n \/\/ auto const bbox = element.boundingBox->ObjectSpaceBBox().PeekBounds(); \/\/< TODO Not all geometries expose\n \/\/ bbox ospcommon::vec3f lower{bbox[0] - half_radius, bbox[1] - half_radius,\n \/\/ bbox[2] - half_radius}; \/\/< TODO The bbox needs to include complete sphere bound\n \/\/ ospcommon::vec3f upper{bbox[3] + half_radius, bbox[4] + half_radius, bbox[5] + half_radius};\n \/\/ \/\/ ghostRegions.emplace_back(lower, upper);\n \/\/ worldBounds.extend({lower, upper}); \/\/< TODO Possible hazard if bbox is not centered\n \/\/ regions.emplace_back(lower, upper);\n \/\/}\n }\n\n\n std::vector<void*> geo_transfer(geo.size());\n for (auto i = 0; i < geo.size(); i++) {\n geo_transfer[i] = reinterpret_cast<void*>(geo[i]);\n }\n os->setStructureType(GEOMETRY);\n os->setAPIObjects(std::move(geo_transfer));\n\n return true;\n}\n\n\nOSPRayPKDGeometry::~OSPRayPKDGeometry() { this->Release(); }\n\nbool OSPRayPKDGeometry::create() {\n auto error = ospLoadModule(\"pkd\");\n if (error != OSPError::OSP_NO_ERROR) {\n vislib::sys::Log::DefaultLog.WriteError(\n \"Unable to load OSPRay module: PKD. Error occured in %s:%d\", __FILE__, __LINE__);\n }\n return true;\n}\n\nvoid OSPRayPKDGeometry::release() {}\n\n\/*\nospray::OSPRayPKDGeometry::InterfaceIsDirty()\n*\/\nbool OSPRayPKDGeometry::InterfaceIsDirty() {\n if (this->colorTypeSlot.IsDirty()) {\n this->colorTypeSlot.ResetDirty();\n return true;\n } else {\n return false;\n }\n}\n\nbool OSPRayPKDGeometry::InterfaceIsDirtyNoReset() const { return this->colorTypeSlot.IsDirty(); }\n\n\nbool OSPRayPKDGeometry::getExtendsCallback(core::Call &call) {\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n core::moldyn::MultiParticleDataCall* cd = this->getDataSlot.CallAs<core::moldyn::MultiParticleDataCall>();\n\n if (cd == NULL) return false;\n cd->SetFrameID(os->FrameID(), true); \/\/ isTimeForced flag set to true\n \/\/ if (!(*cd)(1)) return false; \/\/ floattable returns flase at first attempt and breaks everything\n (*cd)(1);\n\n os->SetExtent(cd->FrameCount(), cd->AccessBoundingBoxes());\n\n return true;\n}\n\nbool OSPRayPKDGeometry::getDirtyCallback(core::Call& call) {\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n auto cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>();\n\n if (cd == nullptr) return false;\n if (this->InterfaceIsDirtyNoReset()) {\n os->setDirty();\n }\n if (this->datahash != cd->DataHash()) {\n os->SetDataHash(cd->DataHash());\n }\n return true;\n}\n\n\n} \/\/ namespace ospray\n} \/\/ namespace megamol<commit_msg>some cleaning<commit_after>\/*\n * OSPRayPKDGeometry.cpp\n * Copyright (C) 2009-2017 by MegaMol Team\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"stdafx.h\"\n#include \"OSPRayPKDGeometry.h\"\n#include \"mmcore\/Call.h\"\n#include \"mmcore\/moldyn\/MultiParticleDataCall.h\"\n#include \"mmcore\/param\/EnumParam.h\"\n#include \"mmcore\/param\/FloatParam.h\"\n#include \"mmcore\/param\/IntParam.h\"\n#include \"mmcore\/param\/Vector3fParam.h\"\n#include \"vislib\/forceinline.h\"\n#include \"vislib\/sys\/Log.h\"\n\n#include <ospray.h>\n#include \"OSPRay_plugin\/CallOSPRayAPIObject.h\"\n#include \"mmcore\/view\/CallClipPlane.h\"\n#include \"mmcore\/view\/CallGetTransferFunction.h\"\n\nnamespace megamol {\nnamespace ospray {\n\n\nOSPRayPKDGeometry::OSPRayPKDGeometry(void)\n : getDataSlot(\"getdata\", \"Connects to the data source\")\n , deployStructureSlot(\"deployStructureSlot\", \"Connects to an OSPRayAPIStructure\")\n , colorTypeSlot(\"colorType\", \"Set the type of encoded color\") {\n\n this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>();\n this->MakeSlotAvailable(&this->getDataSlot);\n\n auto ep = new megamol::core::param::EnumParam(0);\n ep->SetTypePair(0, \"none\");\n ep->SetTypePair(1, \"RGBu8\");\n ep->SetTypePair(2, \"RGBAu8\");\n ep->SetTypePair(3, \"RGBf\");\n ep->SetTypePair(4, \"RGBAf\");\n ep->SetTypePair(5, \"I\");\n this->colorTypeSlot << ep;\n this->MakeSlotAvailable(&this->colorTypeSlot);\n\n this->deployStructureSlot.SetCallback(\n CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(0), &OSPRayPKDGeometry::getDataCallback);\n this->deployStructureSlot.SetCallback(\n CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(1), &OSPRayPKDGeometry::getExtendsCallback);\n this->deployStructureSlot.SetCallback(\n CallOSPRayAPIObject::ClassName(), CallOSPRayAPIObject::FunctionName(2), &OSPRayPKDGeometry::getDirtyCallback);\n this->MakeSlotAvailable(&this->deployStructureSlot);\n}\n\n\nbool OSPRayPKDGeometry::getDataCallback(megamol::core::Call& call) {\n\n \/\/ read Data, calculate shape parameters, fill data vectors\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n megamol::core::moldyn::MultiParticleDataCall* cd =\n this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>();\n\n if (!(*cd)(1)) return false;\n\n auto const minFrameCount = cd->FrameCount();\n\n if (minFrameCount == 0) return false;\n\n auto frameTime = 0;\n\n if (os->FrameID() >= minFrameCount) {\n cd->SetFrameID(minFrameCount - 1, true); \/\/ isTimeForced flag set to true\n frameTime = minFrameCount - 1;\n } else {\n cd->SetFrameID(os->FrameID(), true); \/\/ isTimeForced flag set to true\n frameTime = os->FrameID();\n }\n\n if (this->datahash != cd->DataHash() || this->time != frameTime || this->InterfaceIsDirty()) {\n this->datahash = cd->DataHash();\n this->time = frameTime;\n } else {\n return true;\n }\n\n if (!(*cd)(0)) return false;\n\n size_t listCount = cd->GetParticleListCount();\n std::vector<OSPGeometry> geo;\n for (size_t i = 0; i < listCount; i++) {\n\n core::moldyn::MultiParticleDataCall::Particles& parts = cd->AccessParticles(i);\n\n auto colorType = this->colorTypeSlot.Param<megamol::core::param::EnumParam>()->Value();\n\n geo.push_back(ospNewGeometry(\"pkd_geometry\"));\n\n auto vertexData = ospNewData(parts.GetCount(), OSP_FLOAT4, parts.GetVertexData(), OSP_DATA_SHARED_BUFFER);\n ospCommit(vertexData);\n\n \/\/ set bbox\n auto bboxData = ospNewData(6, OSP_FLOAT, parts.GetBBox().PeekBounds(), OSP_DATA_SHARED_BUFFER);\n ospCommit(bboxData);\n\n ospSet1f(geo.back(), \"radius\", parts.GetGlobalRadius());\n ospSet1i(geo.back(), \"colorType\", colorType);\n ospSetData(geo.back(), \"position\", vertexData);\n \/\/ ospSetData(geo.back(), \"bbox\", bboxData);\n ospSetData(geo.back(), \"bbox\", nullptr);\n ospCommit(geo.back());\n\n \/\/ TODO: implement distributed stuff\n \/\/ if (this->rd_type.Param<megamol::core::param::EnumParam>()->Value() == MPI_RAYCAST) {\n \/\/ auto const half_radius = element.globalRadius * 0.5f;\n\n \/\/ auto const bbox = element.boundingBox->ObjectSpaceBBox().PeekBounds(); \/\/< TODO Not all geometries expose\n \/\/ bbox ospcommon::vec3f lower{bbox[0] - half_radius, bbox[1] - half_radius,\n \/\/ bbox[2] - half_radius}; \/\/< TODO The bbox needs to include complete sphere bound\n \/\/ ospcommon::vec3f upper{bbox[3] + half_radius, bbox[4] + half_radius, bbox[5] + half_radius};\n \/\/ \/\/ ghostRegions.emplace_back(lower, upper);\n \/\/ worldBounds.extend({lower, upper}); \/\/< TODO Possible hazard if bbox is not centered\n \/\/ regions.emplace_back(lower, upper);\n \/\/}\n }\n\n\n std::vector<void*> geo_transfer(geo.size());\n for (auto i = 0; i < geo.size(); i++) {\n geo_transfer[i] = reinterpret_cast<void*>(geo[i]);\n }\n os->setStructureType(GEOMETRY);\n os->setAPIObjects(std::move(geo_transfer));\n\n return true;\n}\n\n\nOSPRayPKDGeometry::~OSPRayPKDGeometry() { this->Release(); }\n\nbool OSPRayPKDGeometry::create() {\n auto error = ospLoadModule(\"pkd\");\n if (error != OSPError::OSP_NO_ERROR) {\n vislib::sys::Log::DefaultLog.WriteError(\n \"Unable to load OSPRay module: PKD. Error occured in %s:%d\", __FILE__, __LINE__);\n }\n return true;\n}\n\nvoid OSPRayPKDGeometry::release() {}\n\n\/*\nospray::OSPRayPKDGeometry::InterfaceIsDirty()\n*\/\nbool OSPRayPKDGeometry::InterfaceIsDirty() {\n if (this->colorTypeSlot.IsDirty()) {\n this->colorTypeSlot.ResetDirty();\n return true;\n } else {\n return false;\n }\n}\n\nbool OSPRayPKDGeometry::InterfaceIsDirtyNoReset() const { return this->colorTypeSlot.IsDirty(); }\n\n\nbool OSPRayPKDGeometry::getExtendsCallback(core::Call& call) {\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n core::moldyn::MultiParticleDataCall* cd = this->getDataSlot.CallAs<core::moldyn::MultiParticleDataCall>();\n\n if (cd == NULL) return false;\n cd->SetFrameID(os->FrameID(), true); \/\/ isTimeForced flag set to true\n \/\/ if (!(*cd)(1)) return false; \/\/ floattable returns flase at first attempt and breaks everything\n (*cd)(1);\n\n os->SetExtent(cd->FrameCount(), cd->AccessBoundingBoxes());\n\n return true;\n}\n\nbool OSPRayPKDGeometry::getDirtyCallback(core::Call& call) {\n auto os = dynamic_cast<CallOSPRayAPIObject*>(&call);\n auto cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>();\n\n if (cd == nullptr) return false;\n if (this->InterfaceIsDirtyNoReset()) {\n os->setDirty();\n }\n if (this->datahash != cd->DataHash()) {\n os->SetDataHash(cd->DataHash());\n }\n return true;\n}\n\n\n} \/\/ namespace ospray\n} \/\/ namespace megamol<|endoftext|>"} {"text":"<commit_before>#include \"generated_sger.o.h\"\n\n#include <Halide.h>\n#include <tiramisu\/tiramisu.h>\n#include <tiramisu\/utils.h>\n\n#include <iostream>\n#include \"benchmarks.h\"\n\n#define M_DIM M\n#define N_DIM N\n\nint sger_ref(int n, int m, double alpha, double * A, double* x, double * y)\n{\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < m; ++j)\n A[i * m + j] += alpha * x[i] * y[j];\n\n return 0;\n}\n\n\nint main(int argc, char** argv)\n{\n std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;\n\n bool run_ref = false, run_tiramisu = false;\n\n const char* env_ref = std::getenv(\"RUN_REF\");\n if (env_ref != NULL && env_ref[0] == '1')\n run_ref = true;\n\n const char* env_tiramisu = std::getenv(\"RUN_TIRAMISU\");\n if (env_tiramisu != NULL && env_tiramisu[0] == '1')\n run_tiramisu = true;\n\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \n double alpha = 2.0;\n \n Halide::Buffer<double> b_alpha(1);\n b_alpha(0) = alpha;\n \n \/\/ b_A and b_A_ref needs to be initialized in each iteration test\n Halide::Buffer<double> b_A(N_DIM, M_DIM), b_A_ref(N_DIM, M_DIM);\n \n Halide::Buffer<double> b_X(N_DIM);\n init_buffer(b_X, (double) 2);\n\n Halide::Buffer<double> b_Y(M_DIM);\n init_buffer(b_Y, (double) 3);\n \n \/**\n * We have :\n * \n * alpha : equals 2\n * b_X : size N_DIM vector with all values set to 2\n * b_Y : size M_DIM vector with all values set to 3\n * b_A : N_DIM by M_DIM matrix with all values set to 1 (initialized in each loop)\n * b_A_ref : N_DIM by M_DIM matrix with all values set to 1 (initialized in each loop)\n *\n * The result must be a N_DIM by M_DIM with all values equal to 13 \n *\/\n\n {\n for (int i = 0; i < NB_TESTS; ++i)\n {\n \/\/ b_A_ref initialized with 1\n init_buffer(b_A_ref, (double) 1);\n auto start = std::chrono::high_resolution_clock::now();\n \n if (run_ref)\n\t \tsger_ref(N_DIM, M_DIM, alpha, b_A_ref.data(), b_X.data(), b_Y.data() );\n \n auto end = std::chrono::high_resolution_clock::now();\n duration_vector_1.push_back(end - start);\n }\n }\n\n {\n for (int i = 0; i < NB_TESTS; ++i)\n {\n \/\/ b_A initialized with 1\n init_buffer(b_A, (double) 1);\n\t\t\t\n auto start = std::chrono::high_resolution_clock::now();\n\n if (run_tiramisu)\n\t \tsger(b_A.raw_buffer(), b_X.raw_buffer(), b_Y.raw_buffer(), b_alpha.raw_buffer());\n\n auto end = std::chrono::high_resolution_clock::now();\n duration_vector_2.push_back(end - start);\n }\n }\n\n print_time(\"performance_cpu.csv\", \"sger\",\n\t {\"Ref\", \"Tiramisu\"},\n\t {median(duration_vector_1), median(duration_vector_2)});\n\n if (CHECK_CORRECTNESS && run_ref && run_tiramisu)\n compare_buffers(\"sger\", b_A_ref, b_A);\n\n if (PRINT_OUTPUT)\n {\n std::cout << \"Tiramisu \" << std::endl;\n print_buffer(b_A);\n\n std::cout << \"Reference \" << std::endl;\n print_buffer(b_A_ref);\n }\n \n return 0;\n}\n<commit_msg>remove an extra line<commit_after>#include \"generated_sger.o.h\"\n\n#include <Halide.h>\n#include <tiramisu\/tiramisu.h>\n#include <tiramisu\/utils.h>\n\n#include <iostream>\n#include \"benchmarks.h\"\n\n#define M_DIM M\n#define N_DIM N\n\nint sger_ref(int n, int m, double alpha, double * A, double* x, double * y)\n{\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < m; ++j)\n A[i * m + j] += alpha * x[i] * y[j];\n\n return 0;\n}\n\nint main(int argc, char** argv)\n{\n std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;\n\n bool run_ref = false, run_tiramisu = false;\n\n const char* env_ref = std::getenv(\"RUN_REF\");\n if (env_ref != NULL && env_ref[0] == '1')\n run_ref = true;\n\n const char* env_tiramisu = std::getenv(\"RUN_TIRAMISU\");\n if (env_tiramisu != NULL && env_tiramisu[0] == '1')\n run_tiramisu = true;\n\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \/\/ ---------------------------------------------------------------------\n \n double alpha = 2.0;\n \n Halide::Buffer<double> b_alpha(1);\n b_alpha(0) = alpha;\n \n \/\/ b_A and b_A_ref needs to be initialized in each iteration test\n Halide::Buffer<double> b_A(N_DIM, M_DIM), b_A_ref(N_DIM, M_DIM);\n \n Halide::Buffer<double> b_X(N_DIM);\n init_buffer(b_X, (double) 2);\n\n Halide::Buffer<double> b_Y(M_DIM);\n init_buffer(b_Y, (double) 3);\n \n \/**\n * We have :\n * \n * alpha : equals 2\n * b_X : size N_DIM vector with all values set to 2\n * b_Y : size M_DIM vector with all values set to 3\n * b_A : N_DIM by M_DIM matrix with all values set to 1 (initialized in each loop)\n * b_A_ref : N_DIM by M_DIM matrix with all values set to 1 (initialized in each loop)\n *\n * The result must be a N_DIM by M_DIM with all values equal to 13 \n *\/\n\n {\n for (int i = 0; i < NB_TESTS; ++i)\n {\n \/\/ b_A_ref initialized with 1\n init_buffer(b_A_ref, (double) 1);\n auto start = std::chrono::high_resolution_clock::now();\n \n if (run_ref)\n\t \tsger_ref(N_DIM, M_DIM, alpha, b_A_ref.data(), b_X.data(), b_Y.data() );\n \n auto end = std::chrono::high_resolution_clock::now();\n duration_vector_1.push_back(end - start);\n }\n }\n\n {\n for (int i = 0; i < NB_TESTS; ++i)\n {\n \/\/ b_A initialized with 1\n init_buffer(b_A, (double) 1);\n\t\t\t\n auto start = std::chrono::high_resolution_clock::now();\n\n if (run_tiramisu)\n\t \tsger(b_A.raw_buffer(), b_X.raw_buffer(), b_Y.raw_buffer(), b_alpha.raw_buffer());\n\n auto end = std::chrono::high_resolution_clock::now();\n duration_vector_2.push_back(end - start);\n }\n }\n\n print_time(\"performance_cpu.csv\", \"sger\",\n\t {\"Ref\", \"Tiramisu\"},\n\t {median(duration_vector_1), median(duration_vector_2)});\n\n if (CHECK_CORRECTNESS && run_ref && run_tiramisu)\n compare_buffers(\"sger\", b_A_ref, b_A);\n\n if (PRINT_OUTPUT)\n {\n std::cout << \"Tiramisu \" << std::endl;\n print_buffer(b_A);\n\n std::cout << \"Reference \" << std::endl;\n print_buffer(b_A_ref);\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the TDDataStructures class, which represents the\n\/\/ Top-down Interprocedural closure of the data structure graph over the\n\/\/ program. This is useful (but not strictly necessary?) for applications\n\/\/ like pointer analysis.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/DataStructure.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Analysis\/DSGraph.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n RegisterAnalysis<TDDataStructures> \/\/ Register the pass\n Y(\"tddatastructure\", \"Top-down Data Structure Analysis\");\n\n Statistic<> NumTDInlines(\"tddatastructures\", \"Number of graphs inlined\");\n}\n\nvoid TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,\n hash_set<DSNode*> &Visited) {\n if (!N || Visited.count(N)) return;\n Visited.insert(N);\n\n for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {\n DSNodeHandle &NH = N->getLink(i*N->getPointerSize());\n if (DSNode *NN = NH.getNode()) {\n const std::vector<GlobalValue*> &Globals = NN->getGlobals();\n for (unsigned G = 0, e = Globals.size(); G != e; ++G)\n if (Function *F = dyn_cast<Function>(Globals[G]))\n ArgsRemainIncomplete.insert(F);\n\n markReachableFunctionsExternallyAccessible(NN, Visited);\n }\n }\n}\n\n\n\/\/ run - Calculate the top down data structure graphs for each function in the\n\/\/ program.\n\/\/\nbool TDDataStructures::run(Module &M) {\n BUDataStructures &BU = getAnalysis<BUDataStructures>();\n GlobalsGraph = new DSGraph(BU.getGlobalsGraph());\n GlobalsGraph->setPrintAuxCalls();\n\n \/\/ Figure out which functions must not mark their arguments complete because\n \/\/ they are accessible outside this compilation unit. Currently, these\n \/\/ arguments are functions which are reachable by global variables in the\n \/\/ globals graph.\n const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();\n hash_set<DSNode*> Visited;\n for (DSGraph::ScalarMapTy::const_iterator I = GGSM.begin(), E = GGSM.end();\n I != E; ++I)\n if (isa<GlobalValue>(I->first))\n markReachableFunctionsExternallyAccessible(I->second.getNode(), Visited);\n\n \/\/ Loop over unresolved call nodes. Any functions passed into (but not\n \/\/ returned!) from unresolvable call nodes may be invoked outside of the\n \/\/ current module.\n const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();\n for (unsigned i = 0, e = Calls.size(); i != e; ++i) {\n const DSCallSite &CS = Calls[i];\n for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)\n markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),\n Visited);\n }\n Visited.clear();\n\n \/\/ Functions without internal linkage also have unknown incoming arguments!\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage())\n ArgsRemainIncomplete.insert(I);\n\n \/\/ We want to traverse the call graph in reverse post-order. To do this, we\n \/\/ calculate a post-order traversal, then reverse it.\n hash_set<DSGraph*> VisitedGraph;\n std::vector<DSGraph*> PostOrder;\n const BUDataStructures::ActualCalleesTy &ActualCallees = \n getAnalysis<BUDataStructures>().getActualCallees();\n\n \/\/ Calculate top-down from main...\n if (Function *F = M.getMainFunction())\n ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);\n\n \/\/ Next calculate the graphs for each unreachable function...\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);\n\n VisitedGraph.clear(); \/\/ Release memory!\n\n \/\/ Visit each of the graphs in reverse post-order now!\n while (!PostOrder.empty()) {\n inlineGraphIntoCallees(*PostOrder.back());\n PostOrder.pop_back();\n }\n\n ArgsRemainIncomplete.clear();\n return false;\n}\n\n\nDSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {\n DSGraph *&G = DSInfo[&F];\n if (G == 0) { \/\/ Not created yet? Clone BU graph...\n G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));\n G->getAuxFunctionCalls().clear();\n G->setPrintAuxCalls();\n G->setGlobalsGraph(GlobalsGraph);\n }\n return *G;\n}\n\n\nvoid TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,\n std::vector<DSGraph*> &PostOrder,\n const BUDataStructures::ActualCalleesTy &ActualCallees) {\n if (F.isExternal()) return;\n DSGraph &G = getOrCreateDSGraph(F);\n if (Visited.count(&G)) return;\n Visited.insert(&G);\n \n \/\/ Recursively traverse all of the callee graphs.\n const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();\n\n for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {\n Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();\n std::pair<BUDataStructures::ActualCalleesTy::const_iterator,\n BUDataStructures::ActualCalleesTy::const_iterator>\n IP = ActualCallees.equal_range(CallI);\n\n for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;\n I != IP.second; ++I)\n ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);\n }\n\n PostOrder.push_back(&G);\n}\n\n\n\n\n\n\/\/ releaseMemory - If the pass pipeline is done with this pass, we can release\n\/\/ our memory... here...\n\/\/\n\/\/ FIXME: This should be releaseMemory and will work fine, except that LoadVN\n\/\/ has no way to extend the lifetime of the pass, which screws up ds-aa.\n\/\/\nvoid TDDataStructures::releaseMyMemory() {\n for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),\n E = DSInfo.end(); I != E; ++I) {\n I->second->getReturnNodes().erase(I->first);\n if (I->second->getReturnNodes().empty())\n delete I->second;\n }\n\n \/\/ Empty map so next time memory is released, data structures are not\n \/\/ re-deleted.\n DSInfo.clear();\n delete GlobalsGraph;\n GlobalsGraph = 0;\n}\n\nvoid TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {\n \/\/ Recompute the Incomplete markers and eliminate unreachable nodes.\n Graph.removeTriviallyDeadNodes();\n Graph.maskIncompleteMarkers();\n\n \/\/ If any of the functions has incomplete incoming arguments, don't mark any\n \/\/ of them as complete.\n bool HasIncompleteArgs = false;\n const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();\n for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),\n E = GraphReturnNodes.end(); I != E; ++I)\n if (ArgsRemainIncomplete.count(I->first)) {\n HasIncompleteArgs = true;\n break;\n }\n\n \/\/ Now fold in the necessary globals from the GlobalsGraph. A global G\n \/\/ must be folded in if it exists in the current graph (i.e., is not dead)\n \/\/ and it was not inlined from any of my callers. If it was inlined from\n \/\/ a caller, it would have been fully consistent with the GlobalsGraph\n \/\/ in the caller so folding in is not necessary. Otherwise, this node came\n \/\/ solely from this function's BU graph and so has to be made consistent.\n \/\/ \n Graph.updateFromGlobalGraph();\n\n \/\/ Recompute the Incomplete markers. Depends on whether args are complete\n unsigned Flags\n = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;\n Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);\n\n \/\/ Delete dead nodes. Treat globals that are unreachable as dead also.\n Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);\n\n \/\/ We are done with computing the current TD Graph! Now move on to\n \/\/ inlining the current graph into the graphs for its callees, if any.\n \/\/ \n const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();\n if (FunctionCalls.empty()) {\n DEBUG(std::cerr << \" [TD] No callees for: \" << Graph.getFunctionNames()\n << \"\\n\");\n return;\n }\n\n \/\/ Now that we have information about all of the callees, propagate the\n \/\/ current graph into the callees. Clone only the reachable subgraph at\n \/\/ each call-site, not the entire graph (even though the entire graph\n \/\/ would be cloned only once, this should still be better on average).\n \/\/\n DEBUG(std::cerr << \" [TD] Inlining '\" << Graph.getFunctionNames() <<\"' into \"\n << FunctionCalls.size() << \" call nodes.\\n\");\n\n const BUDataStructures::ActualCalleesTy &ActualCallees =\n getAnalysis<BUDataStructures>().getActualCallees();\n\n \/\/ Loop over all the call sites and all the callees at each call site. Build\n \/\/ a mapping from called DSGraph's to the call sites in this function that\n \/\/ invoke them. This is useful because we can be more efficient if there are\n \/\/ multiple call sites to the callees in the graph from this caller.\n std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;\n\n for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {\n Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();\n \/\/ For each function in the invoked function list at this call site...\n std::pair<BUDataStructures::ActualCalleesTy::const_iterator,\n BUDataStructures::ActualCalleesTy::const_iterator>\n IP = ActualCallees.equal_range(CallI);\n \/\/ Loop over each actual callee at this call site\n for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;\n I != IP.second; ++I) {\n DSGraph& CalleeGraph = getDSGraph(*I->second);\n assert(&CalleeGraph != &Graph && \"TD need not inline graph into self!\");\n\n CallSites.insert(std::make_pair(&CalleeGraph,\n std::make_pair(I->second, &FunctionCalls[i])));\n }\n }\n\n \/\/ Now that we built the mapping, actually perform the inlining a callee graph\n \/\/ at a time.\n std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;\n for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {\n DSGraph &CalleeGraph = *CSI->first;\n \/\/ Iterate through all of the call sites of this graph, cloning and merging\n \/\/ any nodes required by the call.\n ReachabilityCloner RC(CalleeGraph, Graph, DSGraph::StripModRefBits);\n\n \/\/ Clone over any global nodes that appear in both graphs.\n for (DSGraph::ScalarMapTy::const_iterator\n SI = CalleeGraph.getScalarMap().begin(),\n SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)\n if (GlobalValue *GV = dyn_cast<GlobalValue>(SI->first)) {\n DSGraph::ScalarMapTy::const_iterator GI = Graph.getScalarMap().find(GV);\n if (GI != Graph.getScalarMap().end())\n RC.merge(SI->second, GI->second);\n }\n\n \/\/ Loop over all of the distinct call sites in the caller of the callee.\n for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {\n Function &CF = *CSI->second.first;\n const DSCallSite &CS = *CSI->second.second;\n DEBUG(std::cerr << \" [TD] Resolving arguments for callee graph '\"\n << CalleeGraph.getFunctionNames()\n << \"': \" << CF.getFunctionType()->getNumParams()\n << \" args\\n at call site (DSCallSite*) 0x\" << &CS << \"\\n\");\n \n \/\/ Get the formal argument and return nodes for the called function and\n \/\/ merge them with the cloned subgraph.\n RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);\n ++NumTDInlines;\n }\n }\n\n DEBUG(std::cerr << \" [TD] Done inlining into callees for: \"\n << Graph.getFunctionNames() << \" [\" << Graph.getGraphSize() << \"+\"\n << Graph.getFunctionCalls().size() << \"]\\n\");\n}\n<commit_msg>In the TD pass, don't iterate over the scalar map to find the globals, iterate over the globals directly. This doesn't save any substantial time, however, because the globals graph only contains globals!<commit_after>\/\/===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the TDDataStructures class, which represents the\n\/\/ Top-down Interprocedural closure of the data structure graph over the\n\/\/ program. This is useful (but not strictly necessary?) for applications\n\/\/ like pointer analysis.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/DataStructure.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Analysis\/DSGraph.h\"\n#include \"Support\/Debug.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n RegisterAnalysis<TDDataStructures> \/\/ Register the pass\n Y(\"tddatastructure\", \"Top-down Data Structure Analysis\");\n\n Statistic<> NumTDInlines(\"tddatastructures\", \"Number of graphs inlined\");\n}\n\nvoid TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,\n hash_set<DSNode*> &Visited) {\n if (!N || Visited.count(N)) return;\n Visited.insert(N);\n\n for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {\n DSNodeHandle &NH = N->getLink(i*N->getPointerSize());\n if (DSNode *NN = NH.getNode()) {\n const std::vector<GlobalValue*> &Globals = NN->getGlobals();\n for (unsigned G = 0, e = Globals.size(); G != e; ++G)\n if (Function *F = dyn_cast<Function>(Globals[G]))\n ArgsRemainIncomplete.insert(F);\n\n markReachableFunctionsExternallyAccessible(NN, Visited);\n }\n }\n}\n\n\n\/\/ run - Calculate the top down data structure graphs for each function in the\n\/\/ program.\n\/\/\nbool TDDataStructures::run(Module &M) {\n BUDataStructures &BU = getAnalysis<BUDataStructures>();\n GlobalsGraph = new DSGraph(BU.getGlobalsGraph());\n GlobalsGraph->setPrintAuxCalls();\n\n \/\/ Figure out which functions must not mark their arguments complete because\n \/\/ they are accessible outside this compilation unit. Currently, these\n \/\/ arguments are functions which are reachable by global variables in the\n \/\/ globals graph.\n const DSGraph::ScalarMapTy &GGSM = GlobalsGraph->getScalarMap();\n hash_set<DSNode*> Visited;\n for (DSScalarMap::global_iterator I = GGSM.global_begin(), E = GGSM.global_end();\n I != E; ++I)\n markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(), Visited);\n\n \/\/ Loop over unresolved call nodes. Any functions passed into (but not\n \/\/ returned!) from unresolvable call nodes may be invoked outside of the\n \/\/ current module.\n const std::vector<DSCallSite> &Calls = GlobalsGraph->getAuxFunctionCalls();\n for (unsigned i = 0, e = Calls.size(); i != e; ++i) {\n const DSCallSite &CS = Calls[i];\n for (unsigned arg = 0, e = CS.getNumPtrArgs(); arg != e; ++arg)\n markReachableFunctionsExternallyAccessible(CS.getPtrArg(arg).getNode(),\n Visited);\n }\n Visited.clear();\n\n \/\/ Functions without internal linkage also have unknown incoming arguments!\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage())\n ArgsRemainIncomplete.insert(I);\n\n \/\/ We want to traverse the call graph in reverse post-order. To do this, we\n \/\/ calculate a post-order traversal, then reverse it.\n hash_set<DSGraph*> VisitedGraph;\n std::vector<DSGraph*> PostOrder;\n const BUDataStructures::ActualCalleesTy &ActualCallees = \n getAnalysis<BUDataStructures>().getActualCallees();\n\n \/\/ Calculate top-down from main...\n if (Function *F = M.getMainFunction())\n ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);\n\n \/\/ Next calculate the graphs for each unreachable function...\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);\n\n VisitedGraph.clear(); \/\/ Release memory!\n\n \/\/ Visit each of the graphs in reverse post-order now!\n while (!PostOrder.empty()) {\n inlineGraphIntoCallees(*PostOrder.back());\n PostOrder.pop_back();\n }\n\n ArgsRemainIncomplete.clear();\n return false;\n}\n\n\nDSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {\n DSGraph *&G = DSInfo[&F];\n if (G == 0) { \/\/ Not created yet? Clone BU graph...\n G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F));\n G->getAuxFunctionCalls().clear();\n G->setPrintAuxCalls();\n G->setGlobalsGraph(GlobalsGraph);\n }\n return *G;\n}\n\n\nvoid TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,\n std::vector<DSGraph*> &PostOrder,\n const BUDataStructures::ActualCalleesTy &ActualCallees) {\n if (F.isExternal()) return;\n DSGraph &G = getOrCreateDSGraph(F);\n if (Visited.count(&G)) return;\n Visited.insert(&G);\n \n \/\/ Recursively traverse all of the callee graphs.\n const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls();\n\n for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {\n Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();\n std::pair<BUDataStructures::ActualCalleesTy::const_iterator,\n BUDataStructures::ActualCalleesTy::const_iterator>\n IP = ActualCallees.equal_range(CallI);\n\n for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;\n I != IP.second; ++I)\n ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);\n }\n\n PostOrder.push_back(&G);\n}\n\n\n\n\n\n\/\/ releaseMemory - If the pass pipeline is done with this pass, we can release\n\/\/ our memory... here...\n\/\/\n\/\/ FIXME: This should be releaseMemory and will work fine, except that LoadVN\n\/\/ has no way to extend the lifetime of the pass, which screws up ds-aa.\n\/\/\nvoid TDDataStructures::releaseMyMemory() {\n for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),\n E = DSInfo.end(); I != E; ++I) {\n I->second->getReturnNodes().erase(I->first);\n if (I->second->getReturnNodes().empty())\n delete I->second;\n }\n\n \/\/ Empty map so next time memory is released, data structures are not\n \/\/ re-deleted.\n DSInfo.clear();\n delete GlobalsGraph;\n GlobalsGraph = 0;\n}\n\nvoid TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {\n \/\/ Recompute the Incomplete markers and eliminate unreachable nodes.\n Graph.removeTriviallyDeadNodes();\n Graph.maskIncompleteMarkers();\n\n \/\/ If any of the functions has incomplete incoming arguments, don't mark any\n \/\/ of them as complete.\n bool HasIncompleteArgs = false;\n const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes();\n for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(),\n E = GraphReturnNodes.end(); I != E; ++I)\n if (ArgsRemainIncomplete.count(I->first)) {\n HasIncompleteArgs = true;\n break;\n }\n\n \/\/ Now fold in the necessary globals from the GlobalsGraph. A global G\n \/\/ must be folded in if it exists in the current graph (i.e., is not dead)\n \/\/ and it was not inlined from any of my callers. If it was inlined from\n \/\/ a caller, it would have been fully consistent with the GlobalsGraph\n \/\/ in the caller so folding in is not necessary. Otherwise, this node came\n \/\/ solely from this function's BU graph and so has to be made consistent.\n \/\/ \n Graph.updateFromGlobalGraph();\n\n \/\/ Recompute the Incomplete markers. Depends on whether args are complete\n unsigned Flags\n = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;\n Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);\n\n \/\/ Delete dead nodes. Treat globals that are unreachable as dead also.\n Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);\n\n \/\/ We are done with computing the current TD Graph! Now move on to\n \/\/ inlining the current graph into the graphs for its callees, if any.\n \/\/ \n const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls();\n if (FunctionCalls.empty()) {\n DEBUG(std::cerr << \" [TD] No callees for: \" << Graph.getFunctionNames()\n << \"\\n\");\n return;\n }\n\n \/\/ Now that we have information about all of the callees, propagate the\n \/\/ current graph into the callees. Clone only the reachable subgraph at\n \/\/ each call-site, not the entire graph (even though the entire graph\n \/\/ would be cloned only once, this should still be better on average).\n \/\/\n DEBUG(std::cerr << \" [TD] Inlining '\" << Graph.getFunctionNames() <<\"' into \"\n << FunctionCalls.size() << \" call nodes.\\n\");\n\n const BUDataStructures::ActualCalleesTy &ActualCallees =\n getAnalysis<BUDataStructures>().getActualCallees();\n\n \/\/ Loop over all the call sites and all the callees at each call site. Build\n \/\/ a mapping from called DSGraph's to the call sites in this function that\n \/\/ invoke them. This is useful because we can be more efficient if there are\n \/\/ multiple call sites to the callees in the graph from this caller.\n std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;\n\n for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {\n Instruction *CallI = FunctionCalls[i].getCallSite().getInstruction();\n \/\/ For each function in the invoked function list at this call site...\n std::pair<BUDataStructures::ActualCalleesTy::const_iterator,\n BUDataStructures::ActualCalleesTy::const_iterator>\n IP = ActualCallees.equal_range(CallI);\n \/\/ Loop over each actual callee at this call site\n for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;\n I != IP.second; ++I) {\n DSGraph& CalleeGraph = getDSGraph(*I->second);\n assert(&CalleeGraph != &Graph && \"TD need not inline graph into self!\");\n\n CallSites.insert(std::make_pair(&CalleeGraph,\n std::make_pair(I->second, &FunctionCalls[i])));\n }\n }\n\n \/\/ Now that we built the mapping, actually perform the inlining a callee graph\n \/\/ at a time.\n std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;\n for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {\n DSGraph &CalleeGraph = *CSI->first;\n \/\/ Iterate through all of the call sites of this graph, cloning and merging\n \/\/ any nodes required by the call.\n ReachabilityCloner RC(CalleeGraph, Graph, DSGraph::StripModRefBits);\n\n \/\/ Clone over any global nodes that appear in both graphs.\n for (DSGraph::ScalarMapTy::const_iterator\n SI = CalleeGraph.getScalarMap().begin(),\n SE = CalleeGraph.getScalarMap().end(); SI != SE; ++SI)\n if (GlobalValue *GV = dyn_cast<GlobalValue>(SI->first)) {\n DSGraph::ScalarMapTy::const_iterator GI = Graph.getScalarMap().find(GV);\n if (GI != Graph.getScalarMap().end())\n RC.merge(SI->second, GI->second);\n }\n\n \/\/ Loop over all of the distinct call sites in the caller of the callee.\n for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {\n Function &CF = *CSI->second.first;\n const DSCallSite &CS = *CSI->second.second;\n DEBUG(std::cerr << \" [TD] Resolving arguments for callee graph '\"\n << CalleeGraph.getFunctionNames()\n << \"': \" << CF.getFunctionType()->getNumParams()\n << \" args\\n at call site (DSCallSite*) 0x\" << &CS << \"\\n\");\n \n \/\/ Get the formal argument and return nodes for the called function and\n \/\/ merge them with the cloned subgraph.\n RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);\n ++NumTDInlines;\n }\n }\n\n DEBUG(std::cerr << \" [TD] Done inlining into callees for: \"\n << Graph.getFunctionNames() << \" [\" << Graph.getGraphSize() << \"+\"\n << Graph.getFunctionCalls().size() << \"]\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n\n#include \"Timer.h\"\n#include \"InputFileStream.h\"\n#include \"LexicalReorderingTable.h\"\n\nusing namespace Moses;\n\nTimer timer;\n\nvoid printHelp()\n{\n std::cerr << \"Usage:\\n\"\n \"options: \\n\"\n \"\\t-in string -- input table file name\\n\"\n \"\\t-out string -- prefix of binary table files\\n\"\n \"If -in is not specified reads from stdin\\n\"\n \"\\n\";\n}\n\nint main(int argc, char** argv)\n{\n std::cerr << \"processLexicalTable v0.1 by Konrad Rawlik\\n\";\n std::string inFilePath;\n std::string outFilePath(\"out\");\n if(1 >= argc) {\n printHelp();\n return 1;\n }\n for(int i = 1; i < argc; ++i) {\n std::string arg(argv[i]);\n if(\"-in\" == arg && i+1 < argc) {\n ++i;\n inFilePath = argv[i];\n } else if(\"-out\" == arg && i+1 < argc) {\n ++i;\n outFilePath = argv[i];\n } else {\n \/\/somethings wrong... print help\n printHelp();\n return 1;\n }\n }\n\n if(inFilePath.empty()) {\n std::cerr << \"processing stdin to \" << outFilePath << \".*\\n\";\n return LexicalReorderingTableTree::Create(std::cin, outFilePath);\n } else {\n std::cerr << \"processing \" << inFilePath<< \" to \" << outFilePath << \".*\\n\";\n InputFileStream file(inFilePath);\n return LexicalReorderingTableTree::Create(file, outFilePath);\n }\n}\n<commit_msg>Return 0 on success and 1 on fail. Not the other way around.<commit_after>#include <iostream>\n#include <string>\n\n#include \"Timer.h\"\n#include \"InputFileStream.h\"\n#include \"LexicalReorderingTable.h\"\n\nusing namespace Moses;\n\nTimer timer;\n\nvoid printHelp()\n{\n std::cerr << \"Usage:\\n\"\n \"options: \\n\"\n \"\\t-in string -- input table file name\\n\"\n \"\\t-out string -- prefix of binary table files\\n\"\n \"If -in is not specified reads from stdin\\n\"\n \"\\n\";\n}\n\nint main(int argc, char** argv)\n{\n std::cerr << \"processLexicalTable v0.1 by Konrad Rawlik\\n\";\n std::string inFilePath;\n std::string outFilePath(\"out\");\n if(1 >= argc) {\n printHelp();\n return 1;\n }\n for(int i = 1; i < argc; ++i) {\n std::string arg(argv[i]);\n if(\"-in\" == arg && i+1 < argc) {\n ++i;\n inFilePath = argv[i];\n } else if(\"-out\" == arg && i+1 < argc) {\n ++i;\n outFilePath = argv[i];\n } else {\n \/\/somethings wrong... print help\n printHelp();\n return 1;\n }\n }\n\n if(inFilePath.empty()) {\n std::cerr << \"processing stdin to \" << outFilePath << \".*\\n\";\n return LexicalReorderingTableTree::Create(std::cin, outFilePath);\n } else {\n std::cerr << \"processing \" << inFilePath<< \" to \" << outFilePath << \".*\\n\";\n InputFileStream file(inFilePath);\n bool success = LexicalReorderingTableTree::Create(file, outFilePath);\n return (success ? 0 : 1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/disconnect_window.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n\nnamespace {\nclass DisconnectWindowLinux : public remoting::DisconnectWindow {\n public:\n DisconnectWindowLinux() {}\n virtual void Show(remoting::ChromotingHost* host,\n const std::string& username) OVERRIDE;\n virtual void Hide() OVERRIDE;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(DisconnectWindowLinux);\n};\n} \/\/ namespace\n\nvoid DisconnectWindowLinux::Show(remoting::ChromotingHost* host,\n const std::string& username) {\n NOTIMPLEMENTED();\n}\n\nvoid DisconnectWindowLinux::Hide() {\n NOTIMPLEMENTED();\n}\n\nremoting::DisconnectWindow* remoting::DisconnectWindow::Create() {\n return new DisconnectWindowLinux;\n}\n<commit_msg>Initial implementation of DisconnectWindow on Linux.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/disconnect_window.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"remoting\/host\/chromoting_host.h\"\n#include \"ui\/base\/gtk\/gtk_signal.h\"\n\nnamespace {\n\nconst char kDisconnectWindowTitle[] = \"Remoting\";\nconst char kDisconnectWindowShareText[] = \"Sharing with: \";\nconst char kDisconnectWindowButtonText[] = \"Disconnect\";\n\nclass DisconnectWindowLinux : public remoting::DisconnectWindow {\n public:\n DisconnectWindowLinux();\n\n virtual void Show(remoting::ChromotingHost* host,\n const std::string& username) OVERRIDE;\n virtual void Hide() OVERRIDE;\n\n private:\n CHROMEGTK_CALLBACK_1(DisconnectWindowLinux, gboolean, OnWindowDelete,\n GdkEvent*);\n CHROMEG_CALLBACK_0(DisconnectWindowLinux, void, OnDisconnectClicked,\n GtkButton*);\n\n void CreateWindow();\n\n remoting::ChromotingHost* host_;\n GtkWidget* disconnect_window_;\n GtkWidget* user_label_;\n\n DISALLOW_COPY_AND_ASSIGN(DisconnectWindowLinux);\n};\n} \/\/ namespace\n\nDisconnectWindowLinux::DisconnectWindowLinux()\n : host_(NULL),\n disconnect_window_(NULL) {\n}\n\nvoid DisconnectWindowLinux::CreateWindow() {\n if (disconnect_window_) return;\n\n disconnect_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n GtkWindow* window = GTK_WINDOW(disconnect_window_);\n gtk_window_set_title(window, kDisconnectWindowTitle);\n gtk_window_set_resizable(window, FALSE);\n \/\/ Try to keep the window always visible.\n gtk_window_stick(window);\n gtk_window_set_keep_above(window, TRUE);\n\n g_signal_connect(disconnect_window_, \"delete-event\",\n G_CALLBACK(OnWindowDeleteThunk), this);\n\n GtkWidget* main_area = gtk_vbox_new(FALSE, 0);\n gtk_container_add(GTK_CONTAINER(disconnect_window_), main_area);\n\n GtkWidget* username_row = gtk_hbox_new(FALSE, 0);\n gtk_container_add(GTK_CONTAINER(main_area), username_row);\n\n GtkWidget* share_label = gtk_label_new(kDisconnectWindowShareText);\n gtk_container_add(GTK_CONTAINER(username_row), share_label);\n\n user_label_ = gtk_label_new(NULL);\n gtk_container_add(GTK_CONTAINER(username_row), user_label_);\n\n GtkWidget* disconnect_box = gtk_hbox_new(FALSE, 0);\n gtk_container_add(GTK_CONTAINER(main_area), disconnect_box);\n\n GtkWidget* disconnect_button = gtk_button_new_with_label(\n kDisconnectWindowButtonText);\n gtk_box_pack_start(GTK_BOX(disconnect_box), disconnect_button,\n TRUE, FALSE, 0);\n\n g_signal_connect(disconnect_button, \"clicked\",\n G_CALLBACK(OnDisconnectClickedThunk), this);\n\n gtk_widget_show_all(main_area);\n}\n\nvoid DisconnectWindowLinux::Show(remoting::ChromotingHost* host,\n const std::string& username) {\n host_ = host;\n CreateWindow();\n gtk_label_set_text(GTK_LABEL(user_label_), username.c_str());\n gtk_window_present(GTK_WINDOW(disconnect_window_));\n}\n\nvoid DisconnectWindowLinux::Hide() {\n DCHECK(disconnect_window_);\n\n gtk_widget_hide(disconnect_window_);\n}\n\ngboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget,\n GdkEvent* event) {\n \/\/ Don't allow the window to be closed.\n return TRUE;\n}\n\nvoid DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) {\n DCHECK(host_);\n host_->Shutdown();\n}\n\nremoting::DisconnectWindow* remoting::DisconnectWindow::Create() {\n return new DisconnectWindowLinux;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMultiGroupDataSet.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMultiGroupDataSet.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkMultiGroupDataInformation.h\"\n#include \"vtkMultiGroupDataIterator.h\"\n#include \"vtkMultiGroupDataSetInternal.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkInformationIntegerKey.h\"\n\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkMultiGroupDataSet, \"1.7\");\nvtkStandardNewMacro(vtkMultiGroupDataSet);\n\nvtkInformationKeyMacro(vtkMultiGroupDataSet,GROUP,Integer);\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet::vtkMultiGroupDataSet()\n{\n this->Internal = new vtkMultiGroupDataSetInternal;\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet::~vtkMultiGroupDataSet()\n{\n this->InitializeDataSets();\n delete this->Internal;\n\n \/\/ Cannot be released with SetMultiGroupDataInformation(0) because\n \/\/ that method always allocates a new one.\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetMultiGroupDataInformation(\n vtkMultiGroupDataInformation* info)\n{\n if (info == this->MultiGroupDataInformation)\n {\n return;\n }\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n if (info)\n {\n this->MultiGroupDataInformation = info;\n info->Register(this);\n }\n else\n {\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkCompositeDataIterator* vtkMultiGroupDataSet::NewIterator()\n{\n vtkMultiGroupDataIterator* iter = vtkMultiGroupDataIterator::New();\n iter->SetDataSet(this);\n return iter;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMGDSNode* vtkMultiGroupDataSet::NewNode()\n{\n return new vtkMGDSNode;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::InitializeDataSets()\n{\n this->Internal->DataSets.clear();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::Initialize()\n{\n this->Superclass::Initialize();\n this->InitializeDataSets();\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkMultiGroupDataSet::GetNumberOfGroups()\n{\n return this->Internal->DataSets.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetNumberOfGroups(unsigned int numGroups)\n{\n if (!this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n }\n this->MultiGroupDataInformation->SetNumberOfGroups(numGroups);\n if (numGroups == this->GetNumberOfGroups())\n {\n return;\n }\n this->Internal->DataSets.resize(numGroups);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkMultiGroupDataSet::GetNumberOfDataSets(unsigned int group)\n{\n if (this->Internal->DataSets.size() <= group)\n {\n return 0;\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n\n return ldataSets.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetNumberOfDataSets(unsigned int group, \n unsigned int numDataSets)\n{\n if (!this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n }\n this->MultiGroupDataInformation->SetNumberOfDataSets(group, numDataSets);\n if (numDataSets == this->GetNumberOfDataSets(group))\n {\n return;\n }\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ We need to delete all extra nodes since we manage memory for them.\n unsigned int curNumDataSets = ldataSets.size();\n ldataSets.resize(numDataSets);\n\n \/\/ Assign NULL to all new pointers. We use this later to figure out\n \/\/ whether a node allocated for a particular entry.\n if (curNumDataSets < numDataSets)\n {\n for (unsigned int i=curNumDataSets; i<numDataSets; i++)\n {\n ldataSets[i] = 0;\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::InitializeNode(unsigned int group, \n unsigned int id)\n{\n\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ Make sure that the size of the vector for this group is big enough.\n if (ldataSets.size() <= id)\n {\n this->SetNumberOfDataSets(group, id+1);\n }\n\n ldataSets[id] = 0;\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetDataSet(unsigned int group, \n unsigned int id, \n vtkDataObject* ds)\n{\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ Make sure that the size of the vector for this group is big enough.\n if (ldataSets.size() <= id)\n {\n this->SetNumberOfDataSets(group, id+1);\n }\n \n ldataSets[id] = ds;\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::AddDataSet(vtkInformation* index, vtkDataObject* dobj)\n{\n if (index->Has(INDEX()) && index->Has(GROUP()))\n {\n this->SetDataSet(index->Get(GROUP()), index->Get(INDEX()), dobj);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkMultiGroupDataSet::GetDataSet(unsigned int group, \n unsigned int id)\n{\n if (this->Internal->DataSets.size() <= group)\n {\n return 0;\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n if (ldataSets.size() <= id)\n {\n return 0;\n }\n\n if (!ldataSets[id])\n {\n return 0;\n }\n\n return ldataSets[id];\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkMultiGroupDataSet::GetDataSet(vtkInformation* index)\n{\n if (index->Has(INDEX()) && index->Has(GROUP()))\n {\n return this->GetDataSet(index->Get(GROUP()), index->Get(INDEX()));\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::ShallowCopy(vtkDataObject *src)\n{\n if (src == this)\n {\n return;\n }\n this->InitializeDataSets();\n this->Superclass::ShallowCopy(src);\n\n vtkMultiGroupDataSet* from = vtkMultiGroupDataSet::SafeDownCast(src);\n if (from)\n {\n this->SetMultiGroupDataInformation(from->MultiGroupDataInformation);\n unsigned int numGroups = from->GetNumberOfGroups();\n this->SetNumberOfGroups(numGroups);\n for (unsigned int i=0; i<numGroups; i++)\n {\n unsigned int numDataSets = from->GetNumberOfDataSets(i);\n this->SetNumberOfDataSets(i, numDataSets);\n for (unsigned int j=0; j<numDataSets; j++)\n {\n this->SetDataSet(i, j, from->GetDataSet(i,j));\n }\n }\n }\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::DeepCopy(vtkDataObject *src)\n{\n if (src == this)\n {\n return;\n }\n this->InitializeDataSets();\n this->Superclass::ShallowCopy(src);\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n\n vtkMultiGroupDataSet* from = vtkMultiGroupDataSet::SafeDownCast(src);\n if (from)\n {\n this->MultiGroupDataInformation->DeepCopy(\n from->MultiGroupDataInformation);\n unsigned int numGroups = from->GetNumberOfGroups();\n this->SetNumberOfGroups(numGroups);\n for (unsigned int i=0; i<numGroups; i++)\n {\n unsigned int numDataSets = from->GetNumberOfDataSets(i);\n this->SetNumberOfDataSets(i, numDataSets);\n for (unsigned int j=0; j<numDataSets; j++)\n {\n vtkDataObject* ds = from->GetDataSet(i,j);\n if (ds)\n {\n vtkDataObject* copy = ds->NewInstance();\n copy->DeepCopy(ds);\n this->SetDataSet(i, j, copy);\n }\n }\n }\n }\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkMultiGroupDataSet::GetNumberOfPoints()\n{\n vtkIdType numPts = 0;\n\n vtkCompositeDataIterator* iterator = this->NewIterator();\n iterator->InitTraversal();\n while (!iterator->IsDoneWithTraversal())\n {\n vtkDataObject* dObj = iterator->GetCurrentDataObject();\n if (dObj)\n {\n vtkDataSet* ds = vtkDataSet::SafeDownCast(dObj);\n if (ds)\n {\n numPts += ds->GetNumberOfPoints();\n }\n else\n {\n vtkMultiGroupDataSet* hds = \n vtkMultiGroupDataSet::SafeDownCast(dObj);\n if (hds)\n {\n numPts += hds->GetNumberOfPoints();\n }\n }\n }\n iterator->GoToNextItem();\n }\n iterator->Delete();\n\n return numPts;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet* vtkMultiGroupDataSet::GetData(vtkInformation* info)\n{\n return\n info? vtkMultiGroupDataSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet* vtkMultiGroupDataSet::GetData(vtkInformationVector* v,\n int i)\n{\n return vtkMultiGroupDataSet::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"MultiGroupDataInformation: \";\n if (this->MultiGroupDataInformation)\n {\n os << endl;\n this->MultiGroupDataInformation->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << \"(none)\" << endl;\n }\n}\n\n<commit_msg>BUG: Attempting once again to fix the memory leak. It is a stubborn one.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMultiGroupDataSet.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMultiGroupDataSet.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkMultiGroupDataInformation.h\"\n#include \"vtkMultiGroupDataIterator.h\"\n#include \"vtkMultiGroupDataSetInternal.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkInformationIntegerKey.h\"\n\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkMultiGroupDataSet, \"1.8\");\nvtkStandardNewMacro(vtkMultiGroupDataSet);\n\nvtkInformationKeyMacro(vtkMultiGroupDataSet,GROUP,Integer);\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet::vtkMultiGroupDataSet()\n{\n this->Internal = new vtkMultiGroupDataSetInternal;\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet::~vtkMultiGroupDataSet()\n{\n this->InitializeDataSets();\n delete this->Internal;\n\n \/\/ Cannot be released with SetMultiGroupDataInformation(0) because\n \/\/ that method always allocates a new one.\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetMultiGroupDataInformation(\n vtkMultiGroupDataInformation* info)\n{\n if (info == this->MultiGroupDataInformation)\n {\n return;\n }\n if (this->MultiGroupDataInformation)\n {\n this->MultiGroupDataInformation->Delete();\n this->MultiGroupDataInformation = 0;\n }\n if (info)\n {\n this->MultiGroupDataInformation = info;\n info->Register(this);\n }\n else\n {\n this->MultiGroupDataInformation = vtkMultiGroupDataInformation::New();\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkCompositeDataIterator* vtkMultiGroupDataSet::NewIterator()\n{\n vtkMultiGroupDataIterator* iter = vtkMultiGroupDataIterator::New();\n iter->SetDataSet(this);\n return iter;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMGDSNode* vtkMultiGroupDataSet::NewNode()\n{\n return new vtkMGDSNode;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::InitializeDataSets()\n{\n this->Internal->DataSets.clear();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::Initialize()\n{\n this->Superclass::Initialize();\n this->InitializeDataSets();\n \/\/ This will create a new multigroup information.\n this->SetMultiGroupDataInformation(0);\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkMultiGroupDataSet::GetNumberOfGroups()\n{\n return this->Internal->DataSets.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetNumberOfGroups(unsigned int numGroups)\n{\n this->MultiGroupDataInformation->SetNumberOfGroups(numGroups);\n if (numGroups == this->GetNumberOfGroups())\n {\n return;\n }\n this->Internal->DataSets.resize(numGroups);\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkMultiGroupDataSet::GetNumberOfDataSets(unsigned int group)\n{\n if (this->Internal->DataSets.size() <= group)\n {\n return 0;\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n\n return ldataSets.size();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetNumberOfDataSets(unsigned int group, \n unsigned int numDataSets)\n{\n this->MultiGroupDataInformation->SetNumberOfDataSets(group, numDataSets);\n if (numDataSets == this->GetNumberOfDataSets(group))\n {\n return;\n }\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ We need to delete all extra nodes since we manage memory for them.\n unsigned int curNumDataSets = ldataSets.size();\n ldataSets.resize(numDataSets);\n\n \/\/ Assign NULL to all new pointers. We use this later to figure out\n \/\/ whether a node allocated for a particular entry.\n if (curNumDataSets < numDataSets)\n {\n for (unsigned int i=curNumDataSets; i<numDataSets; i++)\n {\n ldataSets[i] = 0;\n }\n }\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::InitializeNode(unsigned int group, \n unsigned int id)\n{\n\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ Make sure that the size of the vector for this group is big enough.\n if (ldataSets.size() <= id)\n {\n this->SetNumberOfDataSets(group, id+1);\n }\n\n ldataSets[id] = 0;\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::SetDataSet(unsigned int group, \n unsigned int id, \n vtkDataObject* ds)\n{\n \/\/ Make sure that there is a vector allocated for this group\n if (this->Internal->DataSets.size() <= group)\n {\n this->SetNumberOfGroups(group+1);\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n \n \/\/ Make sure that the size of the vector for this group is big enough.\n if (ldataSets.size() <= id)\n {\n this->SetNumberOfDataSets(group, id+1);\n }\n \n ldataSets[id] = ds;\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::AddDataSet(vtkInformation* index, vtkDataObject* dobj)\n{\n if (index->Has(INDEX()) && index->Has(GROUP()))\n {\n this->SetDataSet(index->Get(GROUP()), index->Get(INDEX()), dobj);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkMultiGroupDataSet::GetDataSet(unsigned int group, \n unsigned int id)\n{\n if (this->Internal->DataSets.size() <= group)\n {\n return 0;\n }\n\n vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets = \n this->Internal->DataSets[group];\n if (ldataSets.size() <= id)\n {\n return 0;\n }\n\n if (!ldataSets[id])\n {\n return 0;\n }\n\n return ldataSets[id];\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataObject* vtkMultiGroupDataSet::GetDataSet(vtkInformation* index)\n{\n if (index->Has(INDEX()) && index->Has(GROUP()))\n {\n return this->GetDataSet(index->Get(GROUP()), index->Get(INDEX()));\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::ShallowCopy(vtkDataObject *src)\n{\n if (src == this)\n {\n return;\n }\n this->InitializeDataSets();\n this->Superclass::ShallowCopy(src);\n\n vtkMultiGroupDataSet* from = vtkMultiGroupDataSet::SafeDownCast(src);\n if (from)\n {\n this->SetMultiGroupDataInformation(from->MultiGroupDataInformation);\n unsigned int numGroups = from->GetNumberOfGroups();\n this->SetNumberOfGroups(numGroups);\n for (unsigned int i=0; i<numGroups; i++)\n {\n unsigned int numDataSets = from->GetNumberOfDataSets(i);\n this->SetNumberOfDataSets(i, numDataSets);\n for (unsigned int j=0; j<numDataSets; j++)\n {\n this->SetDataSet(i, j, from->GetDataSet(i,j));\n }\n }\n }\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::DeepCopy(vtkDataObject *src)\n{\n if (src == this)\n {\n return;\n }\n this->InitializeDataSets();\n this->Superclass::ShallowCopy(src);\n\n \/\/ This will create a new multigroup information.\n this->SetMultiGroupDataInformation(0);\n\n vtkMultiGroupDataSet* from = vtkMultiGroupDataSet::SafeDownCast(src);\n if (from)\n {\n this->MultiGroupDataInformation->DeepCopy(\n from->MultiGroupDataInformation);\n unsigned int numGroups = from->GetNumberOfGroups();\n this->SetNumberOfGroups(numGroups);\n for (unsigned int i=0; i<numGroups; i++)\n {\n unsigned int numDataSets = from->GetNumberOfDataSets(i);\n this->SetNumberOfDataSets(i, numDataSets);\n for (unsigned int j=0; j<numDataSets; j++)\n {\n vtkDataObject* ds = from->GetDataSet(i,j);\n if (ds)\n {\n vtkDataObject* copy = ds->NewInstance();\n copy->DeepCopy(ds);\n this->SetDataSet(i, j, copy);\n }\n }\n }\n }\n\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkMultiGroupDataSet::GetNumberOfPoints()\n{\n vtkIdType numPts = 0;\n\n vtkCompositeDataIterator* iterator = this->NewIterator();\n iterator->InitTraversal();\n while (!iterator->IsDoneWithTraversal())\n {\n vtkDataObject* dObj = iterator->GetCurrentDataObject();\n if (dObj)\n {\n vtkDataSet* ds = vtkDataSet::SafeDownCast(dObj);\n if (ds)\n {\n numPts += ds->GetNumberOfPoints();\n }\n else\n {\n vtkMultiGroupDataSet* hds = \n vtkMultiGroupDataSet::SafeDownCast(dObj);\n if (hds)\n {\n numPts += hds->GetNumberOfPoints();\n }\n }\n }\n iterator->GoToNextItem();\n }\n iterator->Delete();\n\n return numPts;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet* vtkMultiGroupDataSet::GetData(vtkInformation* info)\n{\n return\n info? vtkMultiGroupDataSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkMultiGroupDataSet* vtkMultiGroupDataSet::GetData(vtkInformationVector* v,\n int i)\n{\n return vtkMultiGroupDataSet::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMultiGroupDataSet::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"MultiGroupDataInformation: \";\n if (this->MultiGroupDataInformation)\n {\n os << endl;\n this->MultiGroupDataInformation->PrintSelf(os, indent.GetNextIndent());\n }\n else\n {\n os << \"(none)\" << endl;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000 Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include <string.h>\n#include <stdio.h>\n#include \"input.h\"\n#include \"res.h\"\n#include \"global.h\"\n#include \"crypt.h\"\n#include \"video.h\"\n#include \"config.h\"\n\nconst int Config::game_version = 19;\nint Config::net_version = 23;\n\nconst int Config::major = 1;\nconst int Config::minor = 1;\nconst int Config::patchlevel = 5;\nbool Config::registered = false;\n\/* FIXME: we should remove all occurence of Config::xtreme *\/\nbool Config::xtreme = false;\nchar Config::user_name[64] = {\"\"};\n\nConfig::Config() {\n\tfname[0]=0;\n}\n\nConfig::~Config() {\n}\n\nvoid Config::default_config() {\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tinfo.language = 0;\n\tinfo.setup_player = 0;\n\tinfo.cdmusic = 1; \/\/ 0=no music 1=auto-change 2=loop all\n\tinfo.multi_level = 1;\n\tinfo.unlock_theme = 0;\n\tinfo.port_number = 3456;\n\tinfo.mouse_speed = 100;\n\tinfo.pane[0] = 2;\n\tinfo.pane[1] = 0;\n\tinfo.pane[2] = 3;\n\tinfo.update_rate = 10;\n\tmemset(info.book, sizeof(info.book), 0);\n\tinfo.game_name[0] = 0;\n\tinfo.game_type = info.level_up = info.level_start = info.combo_min = info.game_end = 0;\n\tinfo.game_public = 1;\n\tinfo.game_end_value = 1;\n\tstrcpy(info.game_server_address, \"\");\n\n\tfor(int i=0; i<3; i++) {\n\t\tsprintf(st,\"#%i\", i+1);\n\t\tstrcpy(player[i].name, st);\n\t\tplayer[i].color = i;\n\t\tplayer[i].shadow = 0;\n\t\tplayer[i].smooth = 1;\n\t\tplayer[i].repeat = -1;\n\t\tplayer2[i].h_repeat = 2;\n\t\tplayer2[i].v_repeat = 2;\n\t\tplayer2[i].continuous = 1;\n\t\tplayer[i].key[0] = KEY_LEFTARROW;\n\t\tplayer[i].key[1] = KEY_RIGHTARROW;\n\t\tplayer[i].key[2] = KEY_UPARROW;\n\t\tplayer[i].key[3] = KEY_DOWNARROW;\n\t\tplayer[i].key[4] = KEY_UPARROW;\n\t\tplayer2[i].key[0] = KEY_RSHIFT;\n\t\tplayer2[i].key[1] = KEY_SPACE;\n\t}\n}\n\nvoid Config::read() {\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tint i;\n\n\tRes_dos res(fname, RES_TRY);\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\twarning = 0;\n\tif(!res.exist) {\n\t\tdefault_config();\n\t\twarning = 1;\n\t} else {\n\t\tif(res.size() != (sizeof(version) + sizeof(info) + sizeof(player)) &&\n\t\t res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2))) {\n\t\t\tdefault_config();\n\t\t\twarning = 2;\n\t\t} else {\n\t\t\tversion = -1;\n\t\t\tres.read(&version, sizeof(version));\n\t\t\tif(version != game_version) {\n\t\t\t\tdefault_config();\n\t\t\t\twarning = 2;\n\t\t\t} else {\n\t\t\t\tres.read(&info, sizeof(info));\n\t\t\t\tres.read(player, sizeof(player));\n\t\t\t\t\/\/Those may not be present, but the default is all-zero anyway\n\t\t\t\tres.read(player2, sizeof(player2));\n\t\t\t\tres.read(&info2, sizeof(info2));\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(i=0; i<3; i++) {\n\t\tplayer[i].name[39] = 0;\n\t\tif(player[i].color<0 || player[i].color>=MAXTEAMS)\n\t\t\tplayer[i].color=i;\n\t\tif(player[i].shadow<0 || player[i].shadow>1)\n\t\t\tplayer[i].shadow=1;\n\t\tif(player[i].smooth<0 || player[i].smooth>1)\n\t\t\tplayer[i].smooth=1;\n\t\tif(player[i].repeat<-1 || player[i].repeat>3)\n\t\t\tplayer2[i].h_repeat=player2[i].v_repeat=2;\n\t\telse\n\t\t\tif(player[i].repeat>=0) {\n\t\t\t\tplayer2[i].h_repeat=player[i].repeat;\n\t\t\t\tplayer2[i].v_repeat=player[i].repeat;\n\t\t\t}\n\t\tif(player2[i].h_repeat<0 || player2[i].h_repeat>3) {\n\t\t\tplayer2[i].h_repeat=2;\n\t\t}\n\t\tif(player2[i].v_repeat<0 || player2[i].v_repeat>3) {\n\t\t\tplayer2[i].v_repeat=2;\n\t\t}\n\t\tplayer[i].repeat=-1;\n\t\tif(player2[i].continuous<0 || player2[i].continuous>1)\n\t\t\tplayer2[i].continuous=1;\n\t\tif(player2[i].handicap<0 || player2[i].handicap>4)\n\t\t\tplayer2[i].handicap=0;\n\t\tplayer2[i].ngPasswd[63]=0;\n\t\tplayer2[i].ngTeam[39]=0;\n\t\tplayer2[i].ngTeamPasswd[63]=0;\n\t}\n\tfor(i=0; i<10; i++) {\n\t\tinfo.book[i][255] = 0;\n\t}\n}\n\nvoid Config::check_register() {\n registered = true;\n}\n\nvoid fix_str(char *st, Dword len) {\n\tbool in_str=true;\n\tDword i;\n\tfor(i=0; i<len; i++)\n\t\tif(!in_str)\n\t\t\tst[i]=0;\n\t\telse\n\t\t\tif(!st[i])\n\t\t\t\tin_str=false;\n\tst[len-1]=0;\n}\n\nvoid Config::write() {\n\tint i;\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tif(!video_is_dumb) {\n\t\tRes_dos res(fname, RES_CREATE);\n\t\tif(res.exist) {\n\t\t\tversion = game_version;\n\t\t\tres.write(&version, sizeof(version));\n\t\t\tfor(i=0; i<10; i++)\n\t\t\t\tfix_str(info.book[i], 256);\n\t\t\tfix_str(info.game_name, 32);\n\t\t\tfix_str(info.game_server_address, 256);\n\t\t\tres.write(&info, sizeof(info));\n\t\t\tfor(i=0; i<3; i++) {\n\t\t\t\tfix_str(player[i].name, 40);\n\t\t\t\tfix_str(player2[i].ngPasswd, 64);\n\t\t\t\tfix_str(player2[i].ngTeam, 40);\n\t\t\t\tfix_str(player2[i].ngTeamPasswd, 64);\n\t\t\t}\n\t\t\tres.write(player, sizeof(player));\n\t\t\tres.write(player2, sizeof(player2));\n\t\t\tres.write(&info2, sizeof(info2));\n\t\t}\n\t}\n}\n\nConfig config;\n<commit_msg>Forgot to update the version number for 1.1.6!<commit_after>\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000 Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include <string.h>\n#include <stdio.h>\n#include \"input.h\"\n#include \"res.h\"\n#include \"global.h\"\n#include \"crypt.h\"\n#include \"video.h\"\n#include \"config.h\"\n\nconst int Config::game_version = 19;\nint Config::net_version = 23;\n\nconst int Config::major = 1;\nconst int Config::minor = 1;\nconst int Config::patchlevel = 6;\nbool Config::registered = false;\n\/* FIXME: we should remove all occurence of Config::xtreme *\/\nbool Config::xtreme = false;\nchar Config::user_name[64] = {\"\"};\n\nConfig::Config() {\n\tfname[0]=0;\n}\n\nConfig::~Config() {\n}\n\nvoid Config::default_config() {\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tinfo.language = 0;\n\tinfo.setup_player = 0;\n\tinfo.cdmusic = 1; \/\/ 0=no music 1=auto-change 2=loop all\n\tinfo.multi_level = 1;\n\tinfo.unlock_theme = 0;\n\tinfo.port_number = 3456;\n\tinfo.mouse_speed = 100;\n\tinfo.pane[0] = 2;\n\tinfo.pane[1] = 0;\n\tinfo.pane[2] = 3;\n\tinfo.update_rate = 10;\n\tmemset(info.book, sizeof(info.book), 0);\n\tinfo.game_name[0] = 0;\n\tinfo.game_type = info.level_up = info.level_start = info.combo_min = info.game_end = 0;\n\tinfo.game_public = 1;\n\tinfo.game_end_value = 1;\n\tstrcpy(info.game_server_address, \"\");\n\n\tfor(int i=0; i<3; i++) {\n\t\tsprintf(st,\"#%i\", i+1);\n\t\tstrcpy(player[i].name, st);\n\t\tplayer[i].color = i;\n\t\tplayer[i].shadow = 0;\n\t\tplayer[i].smooth = 1;\n\t\tplayer[i].repeat = -1;\n\t\tplayer2[i].h_repeat = 2;\n\t\tplayer2[i].v_repeat = 2;\n\t\tplayer2[i].continuous = 1;\n\t\tplayer[i].key[0] = KEY_LEFTARROW;\n\t\tplayer[i].key[1] = KEY_RIGHTARROW;\n\t\tplayer[i].key[2] = KEY_UPARROW;\n\t\tplayer[i].key[3] = KEY_DOWNARROW;\n\t\tplayer[i].key[4] = KEY_UPARROW;\n\t\tplayer2[i].key[0] = KEY_RSHIFT;\n\t\tplayer2[i].key[1] = KEY_SPACE;\n\t}\n}\n\nvoid Config::read() {\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tint i;\n\n\tRes_dos res(fname, RES_TRY);\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\twarning = 0;\n\tif(!res.exist) {\n\t\tdefault_config();\n\t\twarning = 1;\n\t} else {\n\t\tif(res.size() != (sizeof(version) + sizeof(info) + sizeof(player)) &&\n\t\t res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2))) {\n\t\t\tdefault_config();\n\t\t\twarning = 2;\n\t\t} else {\n\t\t\tversion = -1;\n\t\t\tres.read(&version, sizeof(version));\n\t\t\tif(version != game_version) {\n\t\t\t\tdefault_config();\n\t\t\t\twarning = 2;\n\t\t\t} else {\n\t\t\t\tres.read(&info, sizeof(info));\n\t\t\t\tres.read(player, sizeof(player));\n\t\t\t\t\/\/Those may not be present, but the default is all-zero anyway\n\t\t\t\tres.read(player2, sizeof(player2));\n\t\t\t\tres.read(&info2, sizeof(info2));\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(i=0; i<3; i++) {\n\t\tplayer[i].name[39] = 0;\n\t\tif(player[i].color<0 || player[i].color>=MAXTEAMS)\n\t\t\tplayer[i].color=i;\n\t\tif(player[i].shadow<0 || player[i].shadow>1)\n\t\t\tplayer[i].shadow=1;\n\t\tif(player[i].smooth<0 || player[i].smooth>1)\n\t\t\tplayer[i].smooth=1;\n\t\tif(player[i].repeat<-1 || player[i].repeat>3)\n\t\t\tplayer2[i].h_repeat=player2[i].v_repeat=2;\n\t\telse\n\t\t\tif(player[i].repeat>=0) {\n\t\t\t\tplayer2[i].h_repeat=player[i].repeat;\n\t\t\t\tplayer2[i].v_repeat=player[i].repeat;\n\t\t\t}\n\t\tif(player2[i].h_repeat<0 || player2[i].h_repeat>3) {\n\t\t\tplayer2[i].h_repeat=2;\n\t\t}\n\t\tif(player2[i].v_repeat<0 || player2[i].v_repeat>3) {\n\t\t\tplayer2[i].v_repeat=2;\n\t\t}\n\t\tplayer[i].repeat=-1;\n\t\tif(player2[i].continuous<0 || player2[i].continuous>1)\n\t\t\tplayer2[i].continuous=1;\n\t\tif(player2[i].handicap<0 || player2[i].handicap>4)\n\t\t\tplayer2[i].handicap=0;\n\t\tplayer2[i].ngPasswd[63]=0;\n\t\tplayer2[i].ngTeam[39]=0;\n\t\tplayer2[i].ngTeamPasswd[63]=0;\n\t}\n\tfor(i=0; i<10; i++) {\n\t\tinfo.book[i][255] = 0;\n\t}\n}\n\nvoid Config::check_register() {\n registered = true;\n}\n\nvoid fix_str(char *st, Dword len) {\n\tbool in_str=true;\n\tDword i;\n\tfor(i=0; i<len; i++)\n\t\tif(!in_str)\n\t\t\tst[i]=0;\n\t\telse\n\t\t\tif(!st[i])\n\t\t\t\tin_str=false;\n\tst[len-1]=0;\n}\n\nvoid Config::write() {\n\tint i;\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tif(!video_is_dumb) {\n\t\tRes_dos res(fname, RES_CREATE);\n\t\tif(res.exist) {\n\t\t\tversion = game_version;\n\t\t\tres.write(&version, sizeof(version));\n\t\t\tfor(i=0; i<10; i++)\n\t\t\t\tfix_str(info.book[i], 256);\n\t\t\tfix_str(info.game_name, 32);\n\t\t\tfix_str(info.game_server_address, 256);\n\t\t\tres.write(&info, sizeof(info));\n\t\t\tfor(i=0; i<3; i++) {\n\t\t\t\tfix_str(player[i].name, 40);\n\t\t\t\tfix_str(player2[i].ngPasswd, 64);\n\t\t\t\tfix_str(player2[i].ngTeam, 40);\n\t\t\t\tfix_str(player2[i].ngTeamPasswd, 64);\n\t\t\t}\n\t\t\tres.write(player, sizeof(player));\n\t\t\tres.write(player2, sizeof(player2));\n\t\t\tres.write(&info2, sizeof(info2));\n\t\t}\n\t}\n}\n\nConfig config;\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n* This example demonstrates how to create and work with multiple threads of program\n*\n* \n*\n* Code&Robots site: http:\/\/codrob.ru\/\n* YouTube Channel: https:\/\/www.youtube.com\/c\/code_robots\n* Social networks: https:\/\/vk.com\/codrob\n* https:\/\/www.facebook.com\/groups\/295824740787675\/\n*\n* This example code is in public domain and licensed under MIT license\n*****************************************************************************\/\n\n#include <iostream>\n#include <windows.h>\n\n#include <thread>\t\t\/\/C++11\n\nusing namespace std;\n\nvoid foo(int n)\n{ \n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tcout << \"Is Foo \" << n << \" = \" << this_thread::get_id() << endl;\n\t\tSleep(700);\n\t}\n}\n\nvoid bar(int n)\n{\n\tfor (int i = 0; i < 10; i++)\n\t{\n\t\tcout << \"Is Bar \" << n << \" = \" << this_thread::get_id() << endl;\n\t\tSleep(700);\n\t}\n}\n\nint main()\n{\n\tcout << \"Hardware concurrency: \" << thread::hardware_concurrency() << endl;\n\n\t\/\/Establishment of an independent thread\n\tthread t1 (foo, 1);\n\tthread t2 (bar, 2);\n\n\t\/\/If the thread is active at the moment\n\tif (t1.joinable())\n\t\t\/\/The main thread will wait for the completion of the flow\n\t\tt1.join();\n\n\t\/\/The main thread will not wait for the completion of this flow. It allows him to work independently\n\tt2.detach();\n\n\tcout << \"Main: \" << this_thread::get_id() << endl;\n\n\tsystem(\"pause\");\n};<commit_msg>Charset<commit_after>\/*****************************************************************************\n* This example demonstrates how to create and work with multiple threads of program\n*\n* Этот пример демонстрирует создание и работу с несколькими потоками в программе\n*\n* Code&Robots site: http:\/\/codrob.ru\/\n* YouTube Channel: https:\/\/www.youtube.com\/c\/code_robots\n* Social networks: https:\/\/vk.com\/codrob\n* https:\/\/www.facebook.com\/groups\/295824740787675\/\n*\n* This example code is in public domain and licensed under MIT license\n*****************************************************************************\/\n\n#include <iostream>\n#include <windows.h>\n\n#include <thread>\t\t\/\/C++11\n\nusing namespace std;\n\nvoid foo(int n)\n{ \n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tcout << \"Is Foo \" << n << \" = \" << this_thread::get_id() << endl;\n\t\tSleep(700);\n\t}\n}\n\nvoid bar(int n)\n{\n\tfor (int i = 0; i < 10; i++)\n\t{\n\t\tcout << \"Is Bar \" << n << \" = \" << this_thread::get_id() << endl;\n\t\tSleep(700);\n\t}\n}\n\nint main()\n{\n\tcout << \"Hardware concurrency: \" << thread::hardware_concurrency() << endl;\n\n\t\/\/Establishment of an independent thread\n\tthread t1 (foo, 1);\n\tthread t2 (bar, 2);\n\n\t\/\/If the thread is active at the moment\n\tif (t1.joinable())\n\t\t\/\/The main thread will wait for the completion of the flow\n\t\tt1.join();\n\n\t\/\/The main thread will not wait for the completion of this flow. It allows him to work independently\n\tt2.detach();\n\n\tcout << \"Main: \" << this_thread::get_id() << endl;\n\n\tsystem(\"pause\");\n};<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"Dbg.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-library modules used ---------------------------------------------------\n\n#ifdef DEBUG\n\n\/\/---- Tracer -------------------------------------------------------------------------\nint Tracer::fgLevel = 0;\nAnything Tracer::fgWDDebugContext(Storage::Global());\nROAnything Tracer::fgROWDDebugContext;\nlong Tracer::fgLowerBound = 0;\nlong Tracer::fgUpperBound = 0;\nlong Tracer::fgAlwaysOn = 0;\nbool Tracer::fgDumpAnythings = false;\nbool Tracer::fgTerminated = true;\nstatic bool fgIsInitialised = false;\n\nclass TracerHelper\n{\npublic:\n\tTracerHelper(int nLevel, Allocator *pAlloc)\n\t\t: fStrBuf(pAlloc)\n\t\t, fStream(fStrBuf) {\n\t\tTab(nLevel);\n\t}\n\t~TracerHelper() {\n\t\tfStream.flush();\n\t\tSysLog::WriteToStderr(fStrBuf);\n\t}\n\tvoid Tab(int n) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfStream << \" \";\n\t\t}\n\t}\n\tostream &GetStream() {\n\t\treturn fStream;\n\t}\n\nprivate:\n\tString fStrBuf;\n\tOStringStream fStream;\n};\n\nTracer::Tracer(const char *trigger)\n\t: fTrigger(trigger)\n\t, fpMsg(NULL)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::Tracer(const char *trigger, const char *msg)\n\t: fTrigger(trigger)\n\t, fpMsg(msg)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << fpMsg << \" --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::~Tracer()\n{\n\tif (fTriggered) {\n\t\t--fgLevel;\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \":\";\n\t\tif (fpMsg) {\n\t\t\thlp.GetStream() << \" \" << fpMsg;\n\t\t}\n\t\thlp.GetStream() << \" --- leaving ---\\n\";\n\t}\n}\n\nvoid Tracer::WDDebug(const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::IntAnyWDDebug(const ROAnything &any, TracerHelper &hlp)\n{\n\thlp.Tab(fgLevel);\n\tif (fgDumpAnythings) {\n\t\thlp.GetStream() << \"--- Start of Anything Dump ------------\\n\";\n\t\thlp.Tab(fgLevel);\n\t\tany.Export(hlp.GetStream(), fgLevel);\n\t\thlp.GetStream() << \"\\n\";\n\t\thlp.Tab(fgLevel);\n\t\thlp.GetStream() << \"--- End of Anything Dump --------------\";\n\t} else {\n\t\thlp.GetStream() << \"{ ... anything ommitted ... }\";\n\t}\n\thlp.GetStream() << \"\\n\";\n}\n\nvoid Tracer::AnyWDDebug(const ROAnything &any, const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::SubWDDebug(const char *subtrigger, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::SubAnyWDDebug(const char *subtrigger, const ROAnything &any, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::StatWDDebug(const char *trigger, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::AnythingWDDebug(const char *trigger, const ROAnything &any, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nbool Tracer::CheckWDDebug(const char *trigger, Allocator *pAlloc)\n{\n\tif (!fgIsInitialised) {\n\t\tfgIsInitialised = true;\n\t\tTracer::fgTerminated = (System::EnvGet(\"NO_DEBUG\") == \"true\") ? true : false;\n\t}\n\n\tif ( fgTerminated ) {\n\t\treturn false;\n\t}\n\tstatic bool trying = false;\t\/\/ FIXME: hack until recursive mutex are implemented\n\n\tif (fgWDDebugContext.GetType() == AnyNullType) {\n\t\tif ( trying ) {\n\t\t\treturn false;\n\t\t}\n\t\ttrying = true;\n\t\tReset();\n\t\t\/\/ try to read Dbg.any only once\n\/\/ \t\ttrying= false;\n\t}\n\n\tif (fgLowerBound > 0) {\n\t\treturn CheckTrigger(trigger, pAlloc);\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckMainSwitch(long mainSwitch, long levelSwitch, long levelAll)\n{\n\tif ( mainSwitch == 0L ) {\n\t\treturn false;\t\/\/ 0 is always off\n\t}\n\t\/\/ main switch out of range -> off\n\tif (mainSwitch < levelSwitch) {\n\t\treturn false;\n\t}\n\tif ( ( levelAll > 0 ) && (mainSwitch > levelAll) ) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Tracer::DoCheckLevel(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\t\/\/ check the main switch if it exists\n\tif ( level.IsDefined(\"MainSwitch\") ) {\n\t\tif ( enableAll ) {\n\t\t\tif ( level[\"MainSwitch\"].AsLong(0) < 0 ) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t}\n\t\tif (!CheckMainSwitch(level[\"MainSwitch\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif ( !enableAll && level.IsDefined(\"LowerBound\") ) {\n\t\tif (!CheckMainSwitch(level[\"LowerBound\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ check the enable all switch if it exists\n\tif ( levelAll > 0 ) {\n\t\tif (level.IsDefined(\"EnableAll\")) {\n\t\t\tenableAll = level[\"EnableAll\"].AsLong(0L);\n\t\t\t\/\/ enable all switch in range -> all on\n\t\t\tif ( ( enableAll > 0L ) && ( enableAll >= levelSwitch ) && ( enableAll <= levelAll ) ) {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t\tenableAll = 0;\n\t\t}\n\t} else {\n\t\tlevelAll = fgUpperBound;\n\t}\n\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n}\n\nbool Tracer::DoCheckTrigger(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\tString s(trigger, -1, pAlloc);\n\tlong pos;\n\tif ( (pos = s.StrChr('.')) != -1 ) {\n\t\tString part(s.SubString(0, pos), -1, pAlloc);\n\t\tif ( level.IsDefined(part) ) {\n\t\t\treturn DoCheckLevel(s.SubString(pos + 1), level[part], levelSwitch, levelAll, enableAll, pAlloc);\n\t\t}\n\t}\n\n\tif ( level.IsDefined(s) ) {\n\t\tlong switchValue;\n\t\tif ( level[s].IsDefined(\"MainSwitch\") ) {\n\t\t\tswitchValue = level[s][\"MainSwitch\"].AsLong(levelSwitch);\n\t\t} else {\n\t\t\tswitchValue = level[s].AsLong(levelSwitch);\n\t\t}\n\t\tif ( switchValue < 0 ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( !enableAll ) {\n\t\t\treturn DoCheckSwitch(switchValue, levelSwitch, levelAll);\n\t\t}\n\t}\n\treturn (enableAll > 0);\n}\n\nbool Tracer::DoCheckSwitch(long switchValue, long levelSwitch, long levelAll)\n{\n\t\/\/ check the switch value whether it enables tracing or not\n\tif ( switchValue >= levelSwitch && switchValue <= levelAll ) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckTrigger(const char *trigger, Allocator *pAlloc)\n{\n\treturn DoCheckLevel(trigger, fgROWDDebugContext, fgLowerBound, 0L, 0L, pAlloc);\n}\n\nvoid Tracer::Reset()\n{\n\tistream *ifp = System::OpenStream(\"Dbg\", \"any\");\n\tif (ifp) {\n\t\tfgWDDebugContext.Import(*ifp, \"Dbg\");\n\t\tfgROWDDebugContext = fgWDDebugContext;\n\t\tdelete ifp;\n\t}\n\tif (fgWDDebugContext.GetType() != AnyNullType) {\n\t\tfgLowerBound = fgWDDebugContext[\"LowerBound\"].AsLong(0);\n\t\tfgUpperBound = fgWDDebugContext[\"UpperBound\"].AsLong(0);\n\t\tfgAlwaysOn = fgWDDebugContext[\"AlwaysOn\"].AsLong(0);\n\t\tfgDumpAnythings = fgWDDebugContext[\"DumpAnythings\"].AsBool(true);\n\t}\n}\n\nvoid Tracer::Terminate()\n{\n\tfgTerminated = true;\n\tfgWDDebugContext = Anything();\n\tfgROWDDebugContext = fgWDDebugContext;\n}\n\n#endif\n<commit_msg>optimized tracing for speed - gain is around 40%<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"Dbg.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-library modules used ---------------------------------------------------\n\n#ifdef DEBUG\n\n\/\/---- Tracer -------------------------------------------------------------------------\nint Tracer::fgLevel = 0;\nAnything Tracer::fgWDDebugContext(Storage::Global());\nROAnything Tracer::fgROWDDebugContext;\nlong Tracer::fgLowerBound = 0;\nlong Tracer::fgUpperBound = 0;\nlong Tracer::fgAlwaysOn = 0;\nbool Tracer::fgDumpAnythings = false;\nbool Tracer::fgTerminated = true;\nstatic bool fgIsInitialised = false;\n\nclass TracerHelper\n{\npublic:\n\tTracerHelper(int nLevel, Allocator *pAlloc)\n\t\t: fStrBuf(128L, pAlloc)\n\t\t, fStream(fStrBuf) {\n\t\tTab(nLevel);\n\t}\n\t~TracerHelper() {\n\t\tfStream.flush();\n\t\tSysLog::WriteToStderr(fStrBuf);\n\t}\n\tvoid Tab(int n) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfStream << \" \";\n\t\t}\n\t}\n\tostream &GetStream() {\n\t\treturn fStream;\n\t}\n\nprivate:\n\tString fStrBuf;\n\tOStringStream fStream;\n};\n\nTracer::Tracer(const char *trigger)\n\t: fTrigger(trigger)\n\t, fpMsg(NULL)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::Tracer(const char *trigger, const char *msg)\n\t: fTrigger(trigger)\n\t, fpMsg(msg)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << fpMsg << \" --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::~Tracer()\n{\n\tif (fTriggered) {\n\t\t--fgLevel;\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \":\";\n\t\tif (fpMsg) {\n\t\t\thlp.GetStream() << \" \" << fpMsg;\n\t\t}\n\t\thlp.GetStream() << \" --- leaving ---\\n\";\n\t}\n}\n\nvoid Tracer::WDDebug(const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::IntAnyWDDebug(const ROAnything &any, TracerHelper &hlp)\n{\n\thlp.Tab(fgLevel);\n\tif (fgDumpAnythings) {\n\t\thlp.GetStream() << \"--- Start of Anything Dump ------------\\n\";\n\t\thlp.Tab(fgLevel);\n\t\tany.Export(hlp.GetStream(), fgLevel);\n\t\thlp.GetStream() << \"\\n\";\n\t\thlp.Tab(fgLevel);\n\t\thlp.GetStream() << \"--- End of Anything Dump --------------\";\n\t} else {\n\t\thlp.GetStream() << \"{ ... anything ommitted ... }\";\n\t}\n\thlp.GetStream() << \"\\n\";\n}\n\nvoid Tracer::AnyWDDebug(const ROAnything &any, const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::SubWDDebug(const char *subtrigger, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::SubAnyWDDebug(const char *subtrigger, const ROAnything &any, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::StatWDDebug(const char *trigger, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::AnythingWDDebug(const char *trigger, const ROAnything &any, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nbool Tracer::CheckWDDebug(const char *trigger, Allocator *pAlloc)\n{\n\tif (!fgIsInitialised) {\n\t\tfgIsInitialised = true;\n\t\tTracer::fgTerminated = (System::EnvGet(\"NO_DEBUG\") == \"true\") ? true : false;\n\t}\n\n\tif ( fgTerminated ) {\n\t\treturn false;\n\t}\n\tstatic bool trying = false;\t\/\/ FIXME: hack until recursive mutex are implemented\n\n\tif (fgWDDebugContext.GetType() == AnyNullType) {\n\t\tif ( trying ) {\n\t\t\treturn false;\n\t\t}\n\t\ttrying = true;\n\t\tReset();\n\t\t\/\/ try to read Dbg.any only once\n\/\/ \t\ttrying= false;\n\t}\n\n\tif (fgLowerBound > 0) {\n\t\treturn CheckTrigger(trigger, pAlloc);\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckMainSwitch(long mainSwitch, long levelSwitch, long levelAll)\n{\n\tif ( mainSwitch == 0L ) {\n\t\treturn false;\t\/\/ 0 is always off\n\t}\n\t\/\/ main switch out of range -> off\n\tif (mainSwitch < levelSwitch) {\n\t\treturn false;\n\t}\n\tif ( ( levelAll > 0 ) && (mainSwitch > levelAll) ) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Tracer::DoCheckLevel(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\t\/\/ check the main switch if it exists\n\tif ( level.IsDefined(\"MainSwitch\") ) {\n\t\tif ( enableAll ) {\n\t\t\tif ( level[\"MainSwitch\"].AsLong(0) < 0 ) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t}\n\t\tif (!CheckMainSwitch(level[\"MainSwitch\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif ( !enableAll && level.IsDefined(\"LowerBound\") ) {\n\t\tif (!CheckMainSwitch(level[\"LowerBound\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ check the enable all switch if it exists\n\tif ( levelAll > 0 ) {\n\t\tif (level.IsDefined(\"EnableAll\")) {\n\t\t\tenableAll = level[\"EnableAll\"].AsLong(0L);\n\t\t\t\/\/ enable all switch in range -> all on\n\t\t\tif ( ( enableAll > 0L ) && ( enableAll >= levelSwitch ) && ( enableAll <= levelAll ) ) {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t\tenableAll = 0;\n\t\t}\n\t} else {\n\t\tlevelAll = fgUpperBound;\n\t}\n\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n}\n\nbool Tracer::DoCheckTrigger(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\tchar *cPos( strchr(trigger, '.') );\n\tif ( cPos != NULL ) {\n\t\tlong lpos(cPos - trigger);\n\t\tchar pcPart[512] = { 0 };\n\t\tmemcpy(pcPart, trigger, std::min( lpos, 511L ) );\n\t\tif ( level.IsDefined(pcPart) && ( *++cPos != '\\0' ) ) {\n\t\t\treturn DoCheckLevel(cPos, level[pcPart], levelSwitch, levelAll, enableAll, pAlloc);\n\t\t}\n\t}\n\n\tif ( level.IsDefined(trigger) ) {\n\t\tlong switchValue;\n\t\tif ( level[trigger].IsDefined(\"MainSwitch\") ) {\n\t\t\tswitchValue = level[trigger][\"MainSwitch\"].AsLong(levelSwitch);\n\t\t} else {\n\t\t\tswitchValue = level[trigger].AsLong(levelSwitch);\n\t\t}\n\t\tif ( switchValue < 0 ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( !enableAll ) {\n\t\t\treturn DoCheckSwitch(switchValue, levelSwitch, levelAll);\n\t\t}\n\t}\n\treturn (enableAll > 0);\n}\n\nbool Tracer::DoCheckSwitch(long switchValue, long levelSwitch, long levelAll)\n{\n\t\/\/ check the switch value whether it enables tracing or not\n\tif ( switchValue >= levelSwitch && switchValue <= levelAll ) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckTrigger(const char *trigger, Allocator *pAlloc)\n{\n\treturn DoCheckLevel(trigger, fgROWDDebugContext, fgLowerBound, 0L, 0L, pAlloc);\n}\n\nvoid Tracer::Reset()\n{\n\tistream *ifp = System::OpenStream(\"Dbg\", \"any\");\n\tif (ifp) {\n\t\tfgWDDebugContext.Import(*ifp, \"Dbg\");\n\t\tfgROWDDebugContext = fgWDDebugContext;\n\t\tdelete ifp;\n\t}\n\tif (fgWDDebugContext.GetType() != AnyNullType) {\n\t\tfgLowerBound = fgWDDebugContext[\"LowerBound\"].AsLong(0);\n\t\tfgUpperBound = fgWDDebugContext[\"UpperBound\"].AsLong(0);\n\t\tfgAlwaysOn = fgWDDebugContext[\"AlwaysOn\"].AsLong(0);\n\t\tfgDumpAnythings = fgWDDebugContext[\"DumpAnythings\"].AsBool(true);\n\t}\n}\n\nvoid Tracer::Terminate()\n{\n\tfgTerminated = true;\n\tfgWDDebugContext = Anything();\n\tfgROWDDebugContext = fgWDDebugContext;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Fl_Rotated_Text.cxx,v 0.1\n\/\/\n\/\/ Copyright 2005 by Roman Kantor.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public License\n\/\/ version 2 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed WITHOUT ANY WARRANTY;\n\/\/ WITHOUT even the implied warranty of MERCHANTABILITY \n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Library General Public License for more details.\n\/\/ You should have received a copy of the GNU Library General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n\n#include \"Fl_Rotated_Text.H\"\n#include <string.h>\n#include <FL\/x.H>\n#include <FL\/fl_draw.H>\n#include <FL\/Fl.H>\n#include <FL\/Enumerations.H>\n\nFl_Rotated_Text::~Fl_Rotated_Text(){\n delete[] text_;\n}\nFl_Rotated_Text::Fl_Rotated_Text(const char *text , Fl_Font font , int size , uchar align , int rotation ):Fl_Bitmap((const uchar *)0, 0, 0), ar2(0){\n text_ = 0;\n set(text, font, size, align, rotation);\n}\n\n\nvoid Fl_Rotated_Text::set(const char *text, Fl_Font font, int size, uchar align, int rotation){\n\n uncache();\n if(alloc_array) delete[] ar2;\n ar2 = 0;\n array = 0;\n alloc_array = 0;\n\n\n delete[] text_;\n text_=0;\n font_ = font;\n size_ = size;\n align_ = align;\n\n if(!text || !(*text)){\n w(0);\n h(0);\n return;\n }\n\n text_ = new char[strlen(text) + 1];\n strcpy(text_, text);\n\n if(rotation >9)\n rot_ = (uchar)(((rotation+45)\/90) % 4);\n else\n rot_ = (uchar) (rotation & 3);\n int w_ = 0;\n int h_ = 0;\n int old_font = fl_font();\n int old_size = fl_size();\n fl_font(font,size);\n fl_measure(text_,w_,h_,0); \/\/ assure that w() and h() are always available\n fl_font(old_font,old_size);\n h_ += fl_height()\/2;\n if(rot_ & 1){\n w(h_);\n h(w_);\n }else{\n w(w_);\n h(h_);\n }\n \n};\n\nvoid Fl_Rotated_Text::draw(int x, int y, int W, int H, int cx, int cy){\n \n if(!text_) return;\n if(!rot_){ \/\/ standard drawing)\n int olf_font = fl_font();\n int old_size = fl_size();\n fl_font(font_,size_);\n fl_push_clip(x, y, W-cx, H-cy);\n fl_draw(text_, x - cx, y - cy, w(), h(), (Fl_Align)align_, (Fl_Image *) 0, 0);\n fl_pop_clip();\n fl_font(olf_font, old_size);\n return;\n }\n if(!array){ \/\/ not drawn yet, building rotated bitmap \"cache\"\n int w_, h_;\n if(rot_ & 1){\n w_ = h();\n h_ = w();\n }else{\n w_ = w();\n h_ = h();\n }\n int bsize = ((w()+7)\/8) * h();\n array = ar2 = new uchar[bsize];\n alloc_array = 1;\n \/\/memset(ar2, 0, bsize);\n\n int old_font = fl_font();\n int old_size = fl_size();\n\n Fl_Color old_color = fl_color();\n Fl_Offscreen offscreen = fl_create_offscreen(w_,h_);\n fl_begin_offscreen(offscreen);\n fl_color(0x000000);\n fl_rectf(0,0,w_,h_);\n fl_font(font_, size_);\n fl_color(0x00FF0000); \/\/ we use green color to plot to the offscreen\n\n fl_draw(text_,0, 0, w_, h_, (Fl_Align)align_, (Fl_Image *)0, 0);\n uchar * rgb = fl_read_image(0, 0, 0, w_, h_, 0);\n fl_end_offscreen();\n fl_delete_offscreen(offscreen);\n fl_font(old_font, old_size);\n fl_color(old_color);\n\n int i,j;\n\n uchar * start = rgb;\n int i_iter = 0;\n int j_iter = 0;\n switch(rot_){\n case 3:\n start += w_ * (h_ - 1)*3 + 1;\n i_iter = - w_ * 3;\n j_iter = 3;\n break;\n case 2:\n start += (w_ * h_ - 1)*3 + 1;\n i_iter = -3;\n j_iter = - w_ * 3;\n break;\n case 1:\n start += (w_ - 1)*3 + 1;\n i_iter = w_ * 3;\n j_iter = -3;\n break;\n }\n\n uchar * stj = start;\n uchar c;\n uchar * where;\n uchar * sti;\n\n for(j = 0; j< h(); j++, stj += j_iter){\n uchar val = 0;\n c = 8;\n where = ar2 + j*((w()+7)\/8);\n for(i = 0, sti = stj; i< w(); i++, sti +=i_iter){\n if(*sti >127) val |= c;\n if(c & (uchar)128){ \/\/ pushing value to the array\n *where = val;\n where++;\n c =1;\n val = 0;\n }else\n c <<=1;\n }\n if(w() % 8){ \/\/need to push last byte\n * where = val;\n where++;\n }\n }\n \n delete[] rgb;\n }\n\n Fl_Bitmap::draw(x, y, W, H, cx, cy); \/\/ finaly drawing the bitmap\n\n};\n\n \n \n\n\n\n<commit_msg>removed trailing semicolons. sigh<commit_after>\/\/ Fl_Rotated_Text.cxx,v 0.1\n\/\/\n\/\/ Copyright 2005 by Roman Kantor.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Library General Public License\n\/\/ version 2 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed WITHOUT ANY WARRANTY;\n\/\/ WITHOUT even the implied warranty of MERCHANTABILITY \n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Library General Public License for more details.\n\/\/ You should have received a copy of the GNU Library General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n\n\n#include \"Fl_Rotated_Text.H\"\n#include <string.h>\n#include <FL\/x.H>\n#include <FL\/fl_draw.H>\n#include <FL\/Fl.H>\n#include <FL\/Enumerations.H>\n\nFl_Rotated_Text::~Fl_Rotated_Text(){\n delete[] text_;\n}\nFl_Rotated_Text::Fl_Rotated_Text(const char *text , Fl_Font font , int size , uchar align , int rotation ):Fl_Bitmap((const uchar *)0, 0, 0), ar2(0){\n text_ = 0;\n set(text, font, size, align, rotation);\n}\n\n\nvoid Fl_Rotated_Text::set(const char *text, Fl_Font font, int size, uchar align, int rotation){\n\n uncache();\n if(alloc_array) delete[] ar2;\n ar2 = 0;\n array = 0;\n alloc_array = 0;\n\n\n delete[] text_;\n text_=0;\n font_ = font;\n size_ = size;\n align_ = align;\n\n if(!text || !(*text)){\n w(0);\n h(0);\n return;\n }\n\n text_ = new char[strlen(text) + 1];\n strcpy(text_, text);\n\n if(rotation >9)\n rot_ = (uchar)(((rotation+45)\/90) % 4);\n else\n rot_ = (uchar) (rotation & 3);\n int w_ = 0;\n int h_ = 0;\n int old_font = fl_font();\n int old_size = fl_size();\n fl_font(font,size);\n fl_measure(text_,w_,h_,0); \/\/ assure that w() and h() are always available\n fl_font(old_font,old_size);\n h_ += fl_height()\/2;\n if(rot_ & 1){\n w(h_);\n h(w_);\n }else{\n w(w_);\n h(h_);\n }\n \n}\n\nvoid Fl_Rotated_Text::draw(int x, int y, int W, int H, int cx, int cy){\n \n if(!text_) return;\n if(!rot_){ \/\/ standard drawing)\n int olf_font = fl_font();\n int old_size = fl_size();\n fl_font(font_,size_);\n fl_push_clip(x, y, W-cx, H-cy);\n fl_draw(text_, x - cx, y - cy, w(), h(), (Fl_Align)align_, (Fl_Image *) 0, 0);\n fl_pop_clip();\n fl_font(olf_font, old_size);\n return;\n }\n if(!array){ \/\/ not drawn yet, building rotated bitmap \"cache\"\n int w_, h_;\n if(rot_ & 1){\n w_ = h();\n h_ = w();\n }else{\n w_ = w();\n h_ = h();\n }\n int bsize = ((w()+7)\/8) * h();\n array = ar2 = new uchar[bsize];\n alloc_array = 1;\n \/\/memset(ar2, 0, bsize);\n\n int old_font = fl_font();\n int old_size = fl_size();\n\n Fl_Color old_color = fl_color();\n Fl_Offscreen offscreen = fl_create_offscreen(w_,h_);\n fl_begin_offscreen(offscreen);\n fl_color(0x000000);\n fl_rectf(0,0,w_,h_);\n fl_font(font_, size_);\n fl_color(0x00FF0000); \/\/ we use green color to plot to the offscreen\n\n fl_draw(text_,0, 0, w_, h_, (Fl_Align)align_, (Fl_Image *)0, 0);\n uchar * rgb = fl_read_image(0, 0, 0, w_, h_, 0);\n fl_end_offscreen();\n fl_delete_offscreen(offscreen);\n fl_font(old_font, old_size);\n fl_color(old_color);\n\n int i,j;\n\n uchar * start = rgb;\n int i_iter = 0;\n int j_iter = 0;\n switch(rot_){\n case 3:\n start += w_ * (h_ - 1)*3 + 1;\n i_iter = - w_ * 3;\n j_iter = 3;\n break;\n case 2:\n start += (w_ * h_ - 1)*3 + 1;\n i_iter = -3;\n j_iter = - w_ * 3;\n break;\n case 1:\n start += (w_ - 1)*3 + 1;\n i_iter = w_ * 3;\n j_iter = -3;\n break;\n }\n\n uchar * stj = start;\n uchar c;\n uchar * where;\n uchar * sti;\n\n for(j = 0; j< h(); j++, stj += j_iter){\n uchar val = 0;\n c = 8;\n where = ar2 + j*((w()+7)\/8);\n for(i = 0, sti = stj; i< w(); i++, sti +=i_iter){\n if(*sti >127) val |= c;\n if(c & (uchar)128){ \/\/ pushing value to the array\n *where = val;\n where++;\n c =1;\n val = 0;\n }else\n c <<=1;\n }\n if(w() % 8){ \/\/need to push last byte\n * where = val;\n where++;\n }\n }\n \n delete[] rgb;\n }\n\n Fl_Bitmap::draw(x, y, W, H, cx, cy); \/\/ finaly drawing the bitmap\n\n}\n\n \n \n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"Dbg.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-library modules used ---------------------------------------------------\n#include <cstring>\n\n#ifdef COAST_TRACE\n\n\/\/---- Tracer -------------------------------------------------------------------------\nint Tracer::fgLevel = 0;\nAnything Tracer::fgWDDebugContext(Storage::Global());\nROAnything Tracer::fgROWDDebugContext;\nlong Tracer::fgLowerBound = 0;\nlong Tracer::fgUpperBound = 0;\nbool Tracer::fgDumpAnythings = false;\nbool Tracer::fgTerminated = true;\nstatic bool fgIsInitialised = false;\n\n\/\/! <b>Utility class to keep track of trace indent<\/b>\nclass TracerHelper\n{\npublic:\n\tTracerHelper(int nLevel, Allocator *pAlloc)\n\t\t: fStrBuf(128L, pAlloc)\n\t\t, fStream(fStrBuf) {\n\t\tTab(nLevel);\n\t}\n\t~TracerHelper() {\n\t\tfStream.flush();\n\t\tSysLog::WriteToStderr(fStrBuf);\n\t}\n\tvoid Tab(int n) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfStream << \" \";\n\t\t}\n\t}\n\tostream &GetStream() {\n\t\treturn fStream;\n\t}\n\nprivate:\n\tString fStrBuf;\n\tOStringStream fStream;\n};\n\nTracer::Tracer(const char *trigger)\n\t: fTrigger(trigger)\n\t, fTriggered(false)\n\t, fpMsg(NULL)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::Tracer(const char *trigger, const char *msg)\n\t: fTrigger(trigger)\n\t, fTriggered(false)\n\t, fpMsg(msg)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << fpMsg << \" --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::~Tracer()\n{\n\tif (fTriggered) {\n\t\t--fgLevel;\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \":\";\n\t\tif (fpMsg) {\n\t\t\thlp.GetStream() << \" \" << fpMsg;\n\t\t}\n\t\thlp.GetStream() << \" --- leaving ---\\n\";\n\t}\n}\n\nvoid Tracer::WDDebug(const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::IntAnyWDDebug(const ROAnything &any, TracerHelper &hlp)\n{\n\thlp.Tab(fgLevel);\n\tif (fgDumpAnythings) {\n\t\thlp.GetStream() << \"--- Start of Anything Dump ------------\\n\";\n\t\thlp.Tab(fgLevel);\n\t\tany.Export(hlp.GetStream(), fgLevel);\n\t\thlp.GetStream() << \"\\n\";\n\t\thlp.Tab(fgLevel);\n\t\thlp.GetStream() << \"--- End of Anything Dump --------------\";\n\t} else {\n\t\thlp.GetStream() << \"{ ... anything ommitted ... }\";\n\t}\n\thlp.GetStream() << \"\\n\";\n}\n\nvoid Tracer::AnyWDDebug(const ROAnything &any, const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::SubWDDebug(const char *subtrigger, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::SubAnyWDDebug(const char *subtrigger, const ROAnything &any, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::StatWDDebug(const char *trigger, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::AnythingWDDebug(const char *trigger, const ROAnything &any, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nbool Tracer::CheckWDDebug(const char *trigger, Allocator *pAlloc)\n{\n\tif (!fgIsInitialised) {\n\t\tfgIsInitialised = true;\n\t\tTracer::fgTerminated = (System::EnvGet(\"NO_DEBUG\") == \"true\") ? true : false;\n\t}\n\n\tif ( fgTerminated ) {\n\t\treturn false;\n\t}\n\tstatic bool trying( false );\t\/\/ FIXME: hack until recursive mutex are implemented\n\n\tif (fgWDDebugContext.GetType() == AnyNullType) {\n\t\tif ( trying ) {\n\t\t\treturn false;\n\t\t}\n\t\ttrying = true;\n\t\tReset();\n\t\t\/\/ try to read Dbg.any only once\n\/\/ \t\ttrying= false;\n\t}\n\n\tif (fgLowerBound > 0) {\n\t\treturn CheckTrigger(trigger, pAlloc);\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckMainSwitch(long mainSwitch, long levelSwitch, long levelAll)\n{\n\tif ( mainSwitch == 0L ) {\n\t\treturn false;\t\/\/ 0 is always off\n\t}\n\t\/\/ main switch out of range -> off\n\tif (mainSwitch < levelSwitch) {\n\t\treturn false;\n\t}\n\tif ( ( levelAll > 0 ) && (mainSwitch > levelAll) ) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Tracer::DoCheckLevel(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\t\/\/ check the main switch if it exists\n\tif ( level.IsDefined(\"MainSwitch\") ) {\n\t\tif ( enableAll ) {\n\t\t\tif ( level[\"MainSwitch\"].AsLong(0) < 0 ) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t}\n\t\tif (!CheckMainSwitch(level[\"MainSwitch\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif ( !enableAll && level.IsDefined(\"LowerBound\") ) {\n\t\tif (!CheckMainSwitch(level[\"LowerBound\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ check the enable all switch if it exists\n\tif ( levelAll > 0 ) {\n\t\tif (level.IsDefined(\"EnableAll\")) {\n\t\t\tenableAll = level[\"EnableAll\"].AsLong(0L);\n\t\t\t\/\/ enable all switch in range -> all on\n\t\t\tif ( ( enableAll > 0L ) && ( enableAll >= levelSwitch ) && ( enableAll <= levelAll ) ) {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t\tenableAll = 0;\n\t\t}\n\t} else {\n\t\tlevelAll = fgUpperBound;\n\t}\n\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n}\n\nbool Tracer::DoCheckTrigger(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\tconst char *cPos( strchr(trigger, '.') );\n\tif ( cPos != NULL ) {\n\t\tlong lpos(cPos - trigger);\n\t\tchar pcPart[512] = { 0 };\n\t\tmemcpy(pcPart, trigger, std::min( lpos, 511L ) );\n\t\tif ( level.IsDefined(pcPart) && ( *++cPos != '\\0' ) ) {\n\t\t\treturn DoCheckLevel(cPos, level[pcPart], levelSwitch, levelAll, enableAll, pAlloc);\n\t\t}\n\t}\n\n\tif ( level.IsDefined(trigger) ) {\n\t\tlong switchValue;\n\t\tif ( level[trigger].IsDefined(\"MainSwitch\") ) {\n\t\t\tswitchValue = level[trigger][\"MainSwitch\"].AsLong(levelSwitch);\n\t\t} else {\n\t\t\tswitchValue = level[trigger].AsLong(levelSwitch);\n\t\t}\n\t\tif ( switchValue < 0 ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( !enableAll ) {\n\t\t\treturn DoCheckSwitch(switchValue, levelSwitch, levelAll);\n\t\t}\n\t}\n\treturn (enableAll > 0);\n}\n\nbool Tracer::DoCheckSwitch(long switchValue, long levelSwitch, long levelAll)\n{\n\t\/\/ check the switch value whether it enables tracing or not\n\tif ( switchValue >= levelSwitch && switchValue <= levelAll ) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckTrigger(const char *trigger, Allocator *pAlloc)\n{\n\treturn DoCheckLevel(trigger, fgROWDDebugContext, fgLowerBound, 0L, 0L, pAlloc);\n}\n\nvoid Tracer::Reset()\n{\n\tistream *ifp = System::OpenStream(\"Dbg\", \"any\");\n\tif (ifp) {\n\t\tfgWDDebugContext.Import(*ifp, \"Dbg\");\n\t\tfgROWDDebugContext = fgWDDebugContext;\n\t\tdelete ifp;\n\t}\n\tif (fgWDDebugContext.GetType() != AnyNullType) {\n\t\tfgLowerBound = fgWDDebugContext[\"LowerBound\"].AsLong(0);\n\t\tfgUpperBound = fgWDDebugContext[\"UpperBound\"].AsLong(0);\n\t\tfgDumpAnythings = fgWDDebugContext[\"DumpAnythings\"].AsBool(true);\n\t}\n}\n\nvoid Tracer::Terminate()\n{\n\tfgTerminated = true;\n\tfgWDDebugContext = Anything();\n\tfgROWDDebugContext = fgWDDebugContext;\n}\n\n#endif\n<commit_msg>eliminated error in tracing (needed line was commented out)<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"Dbg.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-library modules used ---------------------------------------------------\n#include <cstring>\n\n#ifdef COAST_TRACE\n\n\/\/---- Tracer -------------------------------------------------------------------------\nint Tracer::fgLevel = 0;\nAnything Tracer::fgWDDebugContext(Storage::Global());\nROAnything Tracer::fgROWDDebugContext;\nlong Tracer::fgLowerBound = 0;\nlong Tracer::fgUpperBound = 0;\nbool Tracer::fgDumpAnythings = false;\nbool Tracer::fgTerminated = true;\nstatic bool fgIsInitialised = false;\n\n\/\/! <b>Utility class to keep track of trace indent<\/b>\nclass TracerHelper\n{\npublic:\n\tTracerHelper(int nLevel, Allocator *pAlloc)\n\t\t: fStrBuf(128L, pAlloc)\n\t\t, fStream(fStrBuf) {\n\t\tTab(nLevel);\n\t}\n\t~TracerHelper() {\n\t\tfStream.flush();\n\t\tSysLog::WriteToStderr(fStrBuf);\n\t}\n\tvoid Tab(int n) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfStream << \" \";\n\t\t}\n\t}\n\tostream &GetStream() {\n\t\treturn fStream;\n\t}\n\nprivate:\n\tString fStrBuf;\n\tOStringStream fStream;\n};\n\nTracer::Tracer(const char *trigger)\n\t: fTrigger(trigger)\n\t, fTriggered(false)\n\t, fpMsg(NULL)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::Tracer(const char *trigger, const char *msg)\n\t: fTrigger(trigger)\n\t, fTriggered(false)\n\t, fpMsg(msg)\n\t, fpAlloc(Storage::Current())\n{\n\tfTriggered = CheckWDDebug(fTrigger, fpAlloc);\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << fpMsg << \" --- entering ---\\n\";\n\t\t++fgLevel;\n\t}\n}\n\nTracer::~Tracer()\n{\n\tif (fTriggered) {\n\t\t--fgLevel;\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \":\";\n\t\tif (fpMsg) {\n\t\t\thlp.GetStream() << \" \" << fpMsg;\n\t\t}\n\t\thlp.GetStream() << \" --- leaving ---\\n\";\n\t}\n}\n\nvoid Tracer::WDDebug(const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::IntAnyWDDebug(const ROAnything &any, TracerHelper &hlp)\n{\n\thlp.Tab(fgLevel);\n\tif (fgDumpAnythings) {\n\t\thlp.GetStream() << \"--- Start of Anything Dump ------------\\n\";\n\t\thlp.Tab(fgLevel);\n\t\tany.Export(hlp.GetStream(), fgLevel);\n\t\thlp.GetStream() << \"\\n\";\n\t\thlp.Tab(fgLevel);\n\t\thlp.GetStream() << \"--- End of Anything Dump --------------\";\n\t} else {\n\t\thlp.GetStream() << \"{ ... anything ommitted ... }\";\n\t}\n\thlp.GetStream() << \"\\n\";\n}\n\nvoid Tracer::AnyWDDebug(const ROAnything &any, const char *msg)\n{\n\tif (fTriggered) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << fTrigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::SubWDDebug(const char *subtrigger, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::SubAnyWDDebug(const char *subtrigger, const ROAnything &any, const char *msg)\n{\n\tString trigger(fTrigger, -1, fpAlloc);\n\ttrigger.Append('.').Append(subtrigger);\n\n\tif (fTriggered && Tracer::CheckWDDebug(trigger, fpAlloc)) {\n\t\tTracerHelper hlp(fgLevel, fpAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nvoid Tracer::StatWDDebug(const char *trigger, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t}\n}\n\nvoid Tracer::AnythingWDDebug(const char *trigger, const ROAnything &any, const char *msg, Allocator *pAlloc)\n{\n\tif (CheckWDDebug(trigger, pAlloc)) {\n\t\tTracerHelper hlp(fgLevel, pAlloc);\n\t\thlp.GetStream() << trigger << \": \" << msg << \"\\n\";\n\t\tIntAnyWDDebug(any, hlp);\n\t}\n}\n\nbool Tracer::CheckWDDebug(const char *trigger, Allocator *pAlloc)\n{\n\tif (!fgIsInitialised) {\n\t\tfgIsInitialised = true;\n\t\tTracer::fgTerminated = (System::EnvGet(\"NO_DEBUG\") == \"true\") ? true : false;\n\t}\n\n\tif ( fgTerminated ) {\n\t\treturn false;\n\t}\n\tstatic bool trying( false );\t\/\/ FIXME: hack until recursive mutex are implemented\n\n\tif (fgWDDebugContext.GetType() == AnyNullType) {\n\t\tif ( trying ) {\n\t\t\treturn false;\n\t\t}\n\t\ttrying = true;\n\t\tReset();\n\t\t\/\/ try to read Dbg.any only once <<- doesn't work as expected\n\t\ttrying = false;\n\t}\n\n\tif (fgLowerBound > 0) {\n\t\treturn CheckTrigger(trigger, pAlloc);\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckMainSwitch(long mainSwitch, long levelSwitch, long levelAll)\n{\n\tif ( mainSwitch == 0L ) {\n\t\treturn false;\t\/\/ 0 is always off\n\t}\n\t\/\/ main switch out of range -> off\n\tif (mainSwitch < levelSwitch) {\n\t\treturn false;\n\t}\n\tif ( ( levelAll > 0 ) && (mainSwitch > levelAll) ) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Tracer::DoCheckLevel(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\t\/\/ check the main switch if it exists\n\tif ( level.IsDefined(\"MainSwitch\") ) {\n\t\tif ( enableAll ) {\n\t\t\tif ( level[\"MainSwitch\"].AsLong(0) < 0 ) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t}\n\t\tif (!CheckMainSwitch(level[\"MainSwitch\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif ( !enableAll && level.IsDefined(\"LowerBound\") ) {\n\t\tif (!CheckMainSwitch(level[\"LowerBound\"].AsLong(0), levelSwitch, levelAll)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ check the enable all switch if it exists\n\tif ( levelAll > 0 ) {\n\t\tif (level.IsDefined(\"EnableAll\")) {\n\t\t\tenableAll = level[\"EnableAll\"].AsLong(0L);\n\t\t\t\/\/ enable all switch in range -> all on\n\t\t\tif ( ( enableAll > 0L ) && ( enableAll >= levelSwitch ) && ( enableAll <= levelAll ) ) {\n\t\t\t\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n\t\t\t}\n\t\t\tenableAll = 0;\n\t\t}\n\t} else {\n\t\tlevelAll = fgUpperBound;\n\t}\n\treturn DoCheckTrigger(trigger, level, levelSwitch, levelAll, enableAll, pAlloc);\n}\n\nbool Tracer::DoCheckTrigger(const char *trigger, const ROAnything &level, long levelSwitch, long levelAll, long enableAll, Allocator *pAlloc)\n{\n\tconst char *cPos( strchr(trigger, '.') );\n\tif ( cPos != NULL ) {\n\t\tlong lpos(cPos - trigger);\n\t\tchar pcPart[512] = { 0 };\n\t\tmemcpy(pcPart, trigger, std::min( lpos, 511L ) );\n\t\tif ( level.IsDefined(pcPart) && ( *++cPos != '\\0' ) ) {\n\t\t\treturn DoCheckLevel(cPos, level[pcPart], levelSwitch, levelAll, enableAll, pAlloc);\n\t\t}\n\t}\n\n\tif ( level.IsDefined(trigger) ) {\n\t\tlong switchValue;\n\t\tif ( level[trigger].IsDefined(\"MainSwitch\") ) {\n\t\t\tswitchValue = level[trigger][\"MainSwitch\"].AsLong(levelSwitch);\n\t\t} else {\n\t\t\tswitchValue = level[trigger].AsLong(levelSwitch);\n\t\t}\n\t\tif ( switchValue < 0 ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( !enableAll ) {\n\t\t\treturn DoCheckSwitch(switchValue, levelSwitch, levelAll);\n\t\t}\n\t}\n\treturn (enableAll > 0);\n}\n\nbool Tracer::DoCheckSwitch(long switchValue, long levelSwitch, long levelAll)\n{\n\t\/\/ check the switch value whether it enables tracing or not\n\tif ( switchValue >= levelSwitch && switchValue <= levelAll ) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool Tracer::CheckTrigger(const char *trigger, Allocator *pAlloc)\n{\n\treturn DoCheckLevel(trigger, fgROWDDebugContext, fgLowerBound, 0L, 0L, pAlloc);\n}\n\nvoid Tracer::Reset()\n{\n\tistream *ifp = System::OpenStream(\"Dbg\", \"any\");\n\tif (ifp) {\n\t\tfgWDDebugContext.Import(*ifp, \"Dbg\");\n\t\tfgROWDDebugContext = fgWDDebugContext;\n\t\tdelete ifp;\n\t}\n\tif (fgWDDebugContext.GetType() != AnyNullType) {\n\t\tfgLowerBound = fgWDDebugContext[\"LowerBound\"].AsLong(0);\n\t\tfgUpperBound = fgWDDebugContext[\"UpperBound\"].AsLong(0);\n\t\tfgDumpAnythings = fgWDDebugContext[\"DumpAnythings\"].AsBool(true);\n\t}\n}\n\nvoid Tracer::Terminate()\n{\n\tfgTerminated = true;\n\tfgWDDebugContext = Anything();\n\tfgROWDDebugContext = fgWDDebugContext;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n\n\/\/ Reproduces bug found here: http:\/\/jsfiddle.net\/R8Cu5\/1\/\n\/\/\n#include \"SkGradientShader.h\"\nstatic void test_grad(SkCanvas* canvas) {\n SkPoint pts[] = {\n { 478.544067f, -84.2041016f },\n { 602.455933f, 625.204102f },\n };\n SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, SK_ColorRED, SK_ColorRED };\n SkScalar pos[] = { 0, 0.3f, 0.3f, 1.0f };\n SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos, 4, SkShader::kClamp_TileMode);\n SkPaint p;\n p.setShader(s)->unref();\n canvas->drawPaint(p);\n}\n\nstatic SkCanvas* MakeCanvas(const SkIRect& bounds) {\n SkBitmap bm;\n bm.setConfig(SkBitmap::kARGB_8888_Config, bounds.width(), bounds.height());\n bm.allocPixels();\n bm.eraseColor(SK_ColorTRANSPARENT);\n\n SkCanvas* canvas = new SkCanvas(bm);\n canvas->translate(-SkIntToScalar(bounds.fLeft), -SkIntToScalar(bounds.fTop));\n return canvas;\n}\n\n#ifdef SK_DEBUG\nstatic void GetBitmap(const SkCanvas* canvas, SkBitmap* bm) {\n *bm = canvas->getDevice()->accessBitmap(false);\n}\n#endif\n\nstatic void compare_canvas(const SkCanvas* a, const SkCanvas* b) {\n#ifdef SK_DEBUG\n SkBitmap bma, bmb;\n GetBitmap(a, &bma);\n GetBitmap(b, &bmb);\n\n SkASSERT(bma.width() == bmb.width());\n SkASSERT(bma.height() == bmb.height());\n\n bma.lockPixels();\n bmb.lockPixels();\n for (int y = 0; y < bma.height(); ++y) {\n const SkPMColor* rowa = bma.getAddr32(0, y);\n const SkPMColor* rowb = bmb.getAddr32(0, y);\n SkASSERT(!memcmp(rowa, rowb, bma.width() << 2));\n\n for (int x = 1; x < bma.width() - 1; ++x) {\n SkASSERT(0xFF000000 == rowa[x]);\n SkASSERT(0xFF000000 == rowb[x]);\n }\n }\n#endif\n}\n\nstatic void drawRectAsPath(SkCanvas* canvas, const SkRect& r, const SkPaint& p) {\n SkPath path;\n path.addRect(r);\n canvas->drawPath(path, p);\n}\n\nstatic void test_maskFromPath(const SkPath& path) {\n SkIRect bounds;\n path.getBounds().roundOut(&bounds);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkAutoTUnref<SkCanvas> path_canvas(MakeCanvas(bounds));\n path_canvas->drawPath(path, paint);\n\n SkAutoTUnref<SkCanvas> rect_canvas(MakeCanvas(bounds));\n drawRectAsPath(rect_canvas, path.getBounds(), paint);\n\n compare_canvas(path_canvas, rect_canvas);\n}\n\nstatic void test_mask() {\n for (int i = 1; i <= 20; ++i) {\n const SkScalar dx = SK_Scalar1 \/ i;\n const SkRect constr = SkRect::MakeWH(dx, SkIntToScalar(2));\n for (int n = 2; n < 20; ++n) {\n SkPath path;\n path.setFillType(SkPath::kEvenOdd_FillType);\n SkRect r = constr;\n while (r.fRight < SkIntToScalar(4)) {\n path.addRect(r);\n r.offset(dx, 0);\n }\n test_maskFromPath(path);\n }\n }\n}\n\nnamespace skiagm {\n\n\/** Draw a 2px border around the target, then red behind the target;\n set the clip to match the target, then draw >> the target in blue.\n*\/\n\nstatic void draw (SkCanvas* canvas, SkRect& target, int x, int y) {\n SkPaint borderPaint;\n borderPaint.setColor(SkColorSetRGB(0x0, 0xDD, 0x0));\n borderPaint.setAntiAlias(true);\n SkPaint backgroundPaint;\n backgroundPaint.setColor(SkColorSetRGB(0xDD, 0x0, 0x0));\n backgroundPaint.setAntiAlias(true);\n SkPaint foregroundPaint;\n foregroundPaint.setColor(SkColorSetRGB(0x0, 0x0, 0xDD));\n foregroundPaint.setAntiAlias(true);\n\n canvas->save();\n canvas->translate(SkIntToScalar(x), SkIntToScalar(y));\n target.inset(SkIntToScalar(-2), SkIntToScalar(-2));\n canvas->drawRect(target, borderPaint);\n target.inset(SkIntToScalar(2), SkIntToScalar(2));\n canvas->drawRect(target, backgroundPaint);\n canvas->clipRect(target, SkRegion::kIntersect_Op, true);\n target.inset(SkIntToScalar(-4), SkIntToScalar(-4));\n canvas->drawRect(target, foregroundPaint);\n canvas->restore();\n}\n\nstatic void draw_square (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 10 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_column (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(1 * SK_Scalar1, 10 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_bar (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 1 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_rect_tests (SkCanvas* canvas) {\n draw_square(canvas, 10, 10);\n draw_column(canvas, 30, 10);\n draw_bar(canvas, 10, 30);\n}\n\n\/**\n Test a set of clipping problems discovered while writing blitAntiRect,\n and test all the code paths through the clipping blitters.\n Each region should show as a blue center surrounded by a 2px green\n border, with no red.\n*\/\n\nclass AAClipGM : public GM {\npublic:\n AAClipGM() {\n\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"aaclip\");\n }\n\n virtual SkISize onISize() {\n return make_isize(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n if (false) {\n test_grad(canvas); return;\n }\n if (false) { \/\/ avoid bit rot, suppress warning\n test_mask();\n }\n\n \/\/ Initial pixel-boundary-aligned draw\n draw_rect_tests(canvas);\n\n \/\/ Repeat 4x with .2, .4, .6, .8 px offsets\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n }\n\n virtual uint32_t onGetFlags() const { return kSkipPipe_Flag; }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new AAClipGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n<commit_msg>add (disabled) test for big dashing<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n\n#include \"SkDashPathEffect.h\"\nstatic void test_giant_dash(SkCanvas* canvas) {\n SkPaint paint;\n const SkScalar intervals[] = { SK_Scalar1, SK_Scalar1 };\n\n paint.setStrokeWidth(2);\n paint.setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref();\n \n SkScalar big = 500 * 1000;\n\n canvas->drawLine(10, 10, big, 10, paint);\n canvas->drawLine(-big, 20, 500, 20, paint);\n canvas->drawLine(-big, 30, big, 30, paint);\n\n const SkScalar intervals2[] = { 20, 5, 10, 5 };\n paint.setPathEffect(new SkDashPathEffect(intervals2, 4, 17))->unref();\n\n canvas->translate(0, 40);\n SkScalar x = -500;\n SkScalar width = 3173;\n for (int i = 0; i < 40; ++i) {\n if (i > 10)\n canvas->drawLine(x, 0, x + width, 0, paint);\n x += 1;\n canvas->translate(0, 4);\n }\n}\n\n\/\/ Reproduces bug found here: http:\/\/jsfiddle.net\/R8Cu5\/1\/\n\/\/\n#include \"SkGradientShader.h\"\nstatic void test_grad(SkCanvas* canvas) {\n SkPoint pts[] = {\n { 478.544067f, -84.2041016f },\n { 602.455933f, 625.204102f },\n };\n SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, SK_ColorRED, SK_ColorRED };\n SkScalar pos[] = { 0, 0.3f, 0.3f, 1.0f };\n SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos, 4, SkShader::kClamp_TileMode);\n SkPaint p;\n p.setShader(s)->unref();\n canvas->drawPaint(p);\n}\n\nstatic SkCanvas* MakeCanvas(const SkIRect& bounds) {\n SkBitmap bm;\n bm.setConfig(SkBitmap::kARGB_8888_Config, bounds.width(), bounds.height());\n bm.allocPixels();\n bm.eraseColor(SK_ColorTRANSPARENT);\n\n SkCanvas* canvas = new SkCanvas(bm);\n canvas->translate(-SkIntToScalar(bounds.fLeft), -SkIntToScalar(bounds.fTop));\n return canvas;\n}\n\n#ifdef SK_DEBUG\nstatic void GetBitmap(const SkCanvas* canvas, SkBitmap* bm) {\n *bm = canvas->getDevice()->accessBitmap(false);\n}\n#endif\n\nstatic void compare_canvas(const SkCanvas* a, const SkCanvas* b) {\n#ifdef SK_DEBUG\n SkBitmap bma, bmb;\n GetBitmap(a, &bma);\n GetBitmap(b, &bmb);\n\n SkASSERT(bma.width() == bmb.width());\n SkASSERT(bma.height() == bmb.height());\n\n bma.lockPixels();\n bmb.lockPixels();\n for (int y = 0; y < bma.height(); ++y) {\n const SkPMColor* rowa = bma.getAddr32(0, y);\n const SkPMColor* rowb = bmb.getAddr32(0, y);\n SkASSERT(!memcmp(rowa, rowb, bma.width() << 2));\n\n for (int x = 1; x < bma.width() - 1; ++x) {\n SkASSERT(0xFF000000 == rowa[x]);\n SkASSERT(0xFF000000 == rowb[x]);\n }\n }\n#endif\n}\n\nstatic void drawRectAsPath(SkCanvas* canvas, const SkRect& r, const SkPaint& p) {\n SkPath path;\n path.addRect(r);\n canvas->drawPath(path, p);\n}\n\nstatic void test_maskFromPath(const SkPath& path) {\n SkIRect bounds;\n path.getBounds().roundOut(&bounds);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkAutoTUnref<SkCanvas> path_canvas(MakeCanvas(bounds));\n path_canvas->drawPath(path, paint);\n\n SkAutoTUnref<SkCanvas> rect_canvas(MakeCanvas(bounds));\n drawRectAsPath(rect_canvas, path.getBounds(), paint);\n\n compare_canvas(path_canvas, rect_canvas);\n}\n\nstatic void test_mask() {\n for (int i = 1; i <= 20; ++i) {\n const SkScalar dx = SK_Scalar1 \/ i;\n const SkRect constr = SkRect::MakeWH(dx, SkIntToScalar(2));\n for (int n = 2; n < 20; ++n) {\n SkPath path;\n path.setFillType(SkPath::kEvenOdd_FillType);\n SkRect r = constr;\n while (r.fRight < SkIntToScalar(4)) {\n path.addRect(r);\n r.offset(dx, 0);\n }\n test_maskFromPath(path);\n }\n }\n}\n\nnamespace skiagm {\n\n\/** Draw a 2px border around the target, then red behind the target;\n set the clip to match the target, then draw >> the target in blue.\n*\/\n\nstatic void draw (SkCanvas* canvas, SkRect& target, int x, int y) {\n SkPaint borderPaint;\n borderPaint.setColor(SkColorSetRGB(0x0, 0xDD, 0x0));\n borderPaint.setAntiAlias(true);\n SkPaint backgroundPaint;\n backgroundPaint.setColor(SkColorSetRGB(0xDD, 0x0, 0x0));\n backgroundPaint.setAntiAlias(true);\n SkPaint foregroundPaint;\n foregroundPaint.setColor(SkColorSetRGB(0x0, 0x0, 0xDD));\n foregroundPaint.setAntiAlias(true);\n\n canvas->save();\n canvas->translate(SkIntToScalar(x), SkIntToScalar(y));\n target.inset(SkIntToScalar(-2), SkIntToScalar(-2));\n canvas->drawRect(target, borderPaint);\n target.inset(SkIntToScalar(2), SkIntToScalar(2));\n canvas->drawRect(target, backgroundPaint);\n canvas->clipRect(target, SkRegion::kIntersect_Op, true);\n target.inset(SkIntToScalar(-4), SkIntToScalar(-4));\n canvas->drawRect(target, foregroundPaint);\n canvas->restore();\n}\n\nstatic void draw_square (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 10 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_column (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(1 * SK_Scalar1, 10 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_bar (SkCanvas* canvas, int x, int y) {\n SkRect target (SkRect::MakeWH(10 * SK_Scalar1, 1 * SK_Scalar1));\n draw(canvas, target, x, y);\n}\n\nstatic void draw_rect_tests (SkCanvas* canvas) {\n draw_square(canvas, 10, 10);\n draw_column(canvas, 30, 10);\n draw_bar(canvas, 10, 30);\n}\n\n\/**\n Test a set of clipping problems discovered while writing blitAntiRect,\n and test all the code paths through the clipping blitters.\n Each region should show as a blue center surrounded by a 2px green\n border, with no red.\n*\/\n\nclass AAClipGM : public GM {\npublic:\n AAClipGM() {\n\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"aaclip\");\n }\n\n virtual SkISize onISize() {\n return make_isize(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n if (false) {\n test_giant_dash(canvas); return; \n }\n if (false) {\n test_grad(canvas); return;\n }\n if (false) { \/\/ avoid bit rot, suppress warning\n test_mask();\n }\n\n \/\/ Initial pixel-boundary-aligned draw\n draw_rect_tests(canvas);\n\n \/\/ Repeat 4x with .2, .4, .6, .8 px offsets\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n\n canvas->translate(SK_Scalar1 \/ 5, SK_Scalar1 \/ 5);\n canvas->translate(SkIntToScalar(50), 0);\n draw_rect_tests(canvas);\n }\n\n virtual uint32_t onGetFlags() const { return kSkipPipe_Flag; }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new AAClipGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ServerClientConnection.hpp\"\n\nnamespace et {\nServerClientConnection::ServerClientConnection(\n const std::shared_ptr<SocketHandler>& _socketHandler,\n const string& clientId, int _socketFd, const string& key)\n : Connection(_socketHandler, clientId, key) {\n socketFd = _socketFd;\n reader = shared_ptr<BackedReader>(\n new BackedReader(socketHandler,\n shared_ptr<CryptoHandler>(\n new CryptoHandler(key, CLIENT_SERVER_NONCE_MSB)),\n _socketFd));\n writer = shared_ptr<BackedWriter>(\n new BackedWriter(socketHandler,\n shared_ptr<CryptoHandler>(\n new CryptoHandler(key, SERVER_CLIENT_NONCE_MSB)),\n _socketFd));\n}\n\nServerClientConnection::~ServerClientConnection() {\n if (socketFd != -1) {\n closeSocket();\n }\n}\n\nbool ServerClientConnection::recoverClient(int newSocketFd) {\n if (socketFd != -1) {\n closeSocket();\n }\n return recover(newSocketFd);\n}\n} \/\/ namespace et\n<commit_msg>more tsan<commit_after>#include \"ServerClientConnection.hpp\"\n\nnamespace et {\nServerClientConnection::ServerClientConnection(\n const std::shared_ptr<SocketHandler>& _socketHandler,\n const string& clientId, int _socketFd, const string& key)\n : Connection(_socketHandler, clientId, key) {\n socketFd = _socketFd;\n reader = shared_ptr<BackedReader>(\n new BackedReader(socketHandler,\n shared_ptr<CryptoHandler>(\n new CryptoHandler(key, CLIENT_SERVER_NONCE_MSB)),\n _socketFd));\n writer = shared_ptr<BackedWriter>(\n new BackedWriter(socketHandler,\n shared_ptr<CryptoHandler>(\n new CryptoHandler(key, SERVER_CLIENT_NONCE_MSB)),\n _socketFd));\n}\n\nServerClientConnection::~ServerClientConnection() {\n if (socketFd != -1) {\n closeSocket();\n }\n}\n\nbool ServerClientConnection::recoverClient(int newSocketFd) {\n {\n lock_guard<std::recursive_mutex> guard(connectionMutex);\n if (socketFd != -1) {\n closeSocket();\n }\n }\n return recover(newSocketFd);\n}\n} \/\/ namespace et\n<|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n\n#include \"xz.hh\"\n\n#pragma GCC diagnostic push\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wdocumentation\"\n#pragma GCC diagnostic ignored \"-Wdocumentation-unknown-command\"\n#endif\n#define lzma_nothrow\n#include <lzma.h>\n#pragma GCC diagnostic pop\n\n\/\/ ----------------------------------------------------------------------\n\nconst unsigned char sXzSig[] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };\nconstexpr ssize_t sXzBufSize = 409600;\n\n\/\/ ----------------------------------------------------------------------\n\nbool xz_compressed(std::string input)\n{\n return std::memcmp(input.c_str(), sXzSig, sizeof(sXzSig)) == 0;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string xz_decompress(std::string buffer)\n{\n lzma_stream strm = LZMA_STREAM_INIT; \/* alloc and init lzma_stream struct *\/\n if (lzma_stream_decoder(&strm, UINT64_MAX, LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED) != LZMA_OK) {\n throw std::runtime_error(\"lzma decompression failed 1\");\n }\n\n strm.next_in = reinterpret_cast<const uint8_t *>(buffer.c_str());\n strm.avail_in = buffer.size();\n std::string output(sXzBufSize, ' ');\n ssize_t offset = 0;\n for (;;) {\n strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));\n strm.avail_out = sXzBufSize;\n auto const r = lzma_code(&strm, LZMA_FINISH);\n if (r == LZMA_STREAM_END) {\n output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);\n break;\n }\n else if (r == LZMA_OK) {\n offset += sXzBufSize;\n output.resize(static_cast<size_t>(offset + sXzBufSize));\n }\n else {\n throw std::runtime_error(\"lzma decompression failed 2\");\n }\n }\n lzma_end(&strm);\n return output;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string xz_compress(std::string input)\n{\n lzma_stream strm = LZMA_STREAM_INIT; \/* alloc and init lzma_stream struct *\/\n if (lzma_easy_encoder(&strm, 9 | LZMA_PRESET_EXTREME, LZMA_CHECK_CRC64) != LZMA_OK) {\n throw std::runtime_error(\"lzma compression failed 1\");\n }\n\n strm.next_in = reinterpret_cast<const uint8_t *>(input.c_str());\n strm.avail_in = input.size();\n std::string output(sXzBufSize, ' ');\n ssize_t offset = 0;\n for (;;) {\n strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));\n strm.avail_out = sXzBufSize;\n auto const r = lzma_code(&strm, LZMA_FINISH);\n if (r == LZMA_STREAM_END) {\n output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);\n break;\n }\n else if (r == LZMA_OK) {\n offset += sXzBufSize;\n output.resize(static_cast<size_t>(offset + sXzBufSize));\n }\n else {\n throw std::runtime_error(\"lzma compression failed 2\");\n }\n }\n lzma_end(&strm);\n return output;\n\n} \/\/ xz_compress\n\n\/\/ ----------------------------------------------------------------------\n<commit_msg>porting to gcc 4.9<commit_after>#include <stdexcept>\n#include <cstring>\n\n#include \"xz.hh\"\n\n#pragma GCC diagnostic push\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wdocumentation\"\n#pragma GCC diagnostic ignored \"-Wdocumentation-unknown-command\"\n#endif\n#define lzma_nothrow\n#include <lzma.h>\n#pragma GCC diagnostic pop\n\n\/\/ ----------------------------------------------------------------------\n\nconst unsigned char sXzSig[] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };\nconstexpr ssize_t sXzBufSize = 409600;\n\n\/\/ ----------------------------------------------------------------------\n\nbool xz_compressed(std::string input)\n{\n return std::memcmp(input.c_str(), sXzSig, sizeof(sXzSig)) == 0;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string xz_decompress(std::string buffer)\n{\n lzma_stream strm = LZMA_STREAM_INIT; \/* alloc and init lzma_stream struct *\/\n if (lzma_stream_decoder(&strm, UINT64_MAX, LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED) != LZMA_OK) {\n throw std::runtime_error(\"lzma decompression failed 1\");\n }\n\n strm.next_in = reinterpret_cast<const uint8_t *>(buffer.c_str());\n strm.avail_in = buffer.size();\n std::string output(sXzBufSize, ' ');\n ssize_t offset = 0;\n for (;;) {\n strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));\n strm.avail_out = sXzBufSize;\n auto const r = lzma_code(&strm, LZMA_FINISH);\n if (r == LZMA_STREAM_END) {\n output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);\n break;\n }\n else if (r == LZMA_OK) {\n offset += sXzBufSize;\n output.resize(static_cast<size_t>(offset + sXzBufSize));\n }\n else {\n throw std::runtime_error(\"lzma decompression failed 2\");\n }\n }\n lzma_end(&strm);\n return output;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstd::string xz_compress(std::string input)\n{\n lzma_stream strm = LZMA_STREAM_INIT; \/* alloc and init lzma_stream struct *\/\n if (lzma_easy_encoder(&strm, 9 | LZMA_PRESET_EXTREME, LZMA_CHECK_CRC64) != LZMA_OK) {\n throw std::runtime_error(\"lzma compression failed 1\");\n }\n\n strm.next_in = reinterpret_cast<const uint8_t *>(input.c_str());\n strm.avail_in = input.size();\n std::string output(sXzBufSize, ' ');\n ssize_t offset = 0;\n for (;;) {\n strm.next_out = reinterpret_cast<uint8_t *>(&*(output.begin() + offset));\n strm.avail_out = sXzBufSize;\n auto const r = lzma_code(&strm, LZMA_FINISH);\n if (r == LZMA_STREAM_END) {\n output.resize(static_cast<size_t>(offset + sXzBufSize) - strm.avail_out);\n break;\n }\n else if (r == LZMA_OK) {\n offset += sXzBufSize;\n output.resize(static_cast<size_t>(offset + sXzBufSize));\n }\n else {\n throw std::runtime_error(\"lzma compression failed 2\");\n }\n }\n lzma_end(&strm);\n return output;\n\n} \/\/ xz_compress\n\n\/\/ ----------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"Motion.hpp\"\n#include \"Cue.h\"\n\nnamespace choreograph\n{\n\nclass Timeline;\n\n\/\/\/\n\/\/\/ Options for manipulating newly created TimelineItems.\n\/\/\/ Uses CRTP so we don't lose the actual type when chaining methods.\n\/\/\/ Do not store the TimelineOptions object, as it contains a non-owning reference.\n\/\/\/\ntemplate<typename Derived>\nclass TimelineOptionsBase\n{\npublic:\n TimelineOptionsBase( TimelineItem &item ):\n _item( item )\n {}\n\n \/\/=================================================\n \/\/ TimelineItem Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set whether the item should be removed from the timeline on finish.\n Derived& removeOnFinish( bool doRemove ) { _item.setRemoveOnFinish( doRemove ); return self(); }\n\n \/\/\/ Set the rate at which time advances for Motion.\n Derived& playbackSpeed( Time speed ) { _item.setPlaybackSpeed( speed ); return self(); }\n\n \/\/\/ Set the initial time offset of the TimelineItem.\n \/\/\/ For Cues, this sets the time in the future.\n \/\/\/ For Motions, this is akin to adding a hold at the beginning of the Sequence.\n Derived& setStartTime( Time t ) { _item.setStartTime( t ); return self(); }\n\n \/\/\/ Returns a shared_ptr to the control object for the Item. Allows you to cancel the Item later.\n TimelineItemControlRef getControl() { return _item.getControl(); }\n\n \/\/\/ Returns an object that cancels the Cue when it falls out of scope.\n \/\/\/ You should store a ScopedCueRef in any class that captures [this] in a cued lambda.\n ScopedCancelRef getScopedControl() { return std::make_shared<ScopedCancel>( _item.getControl() ); }\n\nprivate:\n TimelineItem &_item;\n Derived& self() { return static_cast<Derived&>( *this ); }\n};\n\n\/\/\/\n\/\/\/ TimelineOptions with no additional behaviors beyond base.\n\/\/\/ Returned when creating cues.\n\/\/\/ Do not store the TimelineOptions object, as it contains a non-owning reference.\n\/\/\/\nclass TimelineOptions : public TimelineOptionsBase<TimelineOptions>\n{\npublic:\n TimelineOptions( TimelineItem &item )\n : TimelineOptionsBase<TimelineOptions>( item )\n {}\n};\n\n\/\/\/\n\/\/\/ MotionOptions provide a temporary facade for manipulating a timeline Motion and its underlying Sequence.\n\/\/\/ All methods return a reference back to the MotionOptions object for chaining.\n\/\/\/ Do not store the MotionOptions object, as it contains non-owning references.\n\/\/\/\ntemplate<typename T>\nclass MotionOptions : public TimelineOptionsBase<MotionOptions<T>>\n{\npublic:\n using SelfT = MotionOptions<T>;\n using MotionCallback = typename Motion<T>::Callback;\n\n MotionOptions( Motion<T> &motion, Sequence<T> &sequence, const Timeline &timeline ):\n TimelineOptionsBase<MotionOptions<T>>( motion ),\n _motion( motion ),\n _sequence( sequence ),\n _timeline( timeline )\n {}\n\n \/\/=================================================\n \/\/ Motion Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set function to be called when Motion starts. Receives reference to motion.\n SelfT& startFn( const MotionCallback &fn ) { _motion.setStartFn( fn ); return *this; }\n\n \/\/\/ Set function to be called when Motion updates. Receives current target value.\n SelfT& updateFn( const typename Motion<T>::Callback &fn ) { _motion.setUpdateFn( fn ); return *this; }\n\n \/\/\/ Set function to be called when Motion finishes. Receives reference to motion.\n SelfT& finishFn( const MotionCallback &fn ) { _motion.setFinishFn( fn ); return *this; }\n\n \/\/\/ Set a function to be called when the current inflection point is crossed.\n \/\/\/ An inflection occcurs when the Sequence moves from one Phrase to the next.\n \/\/\/ You must add a phrase after this for the inflection to occur.\n SelfT& onInflection( const MotionCallback &fn ) { return onInflection( _sequence.getPhraseCount(), fn ); }\n \/\/\/ Adds an inflection callback when the specified phrase index is crossed.\n SelfT& onInflection( size_t point, const MotionCallback &fn ) { _motion.addInflectionCallback( point, fn ); return *this; }\n\n \/\/\/ Clip the motion in \\t time from the current Motion playhead.\n \/\/\/ Also discards any phrases we have already played up to this point.\n SelfT& cutIn( Time t ) { _motion.cutIn( t ); return *this; }\n\n \/\/\/ Clip the motion at time \\t from the beginning of the Motion's Sequence.\n \/\/\/ When used after Timeline::apply, will have the same effect as cutIn().\n SelfT& cutAt( Time t ) { _motion.sliceSequence( 0, t ); return *this; }\n\n \/\/=================================================\n \/\/ Sequence Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set the current value of the Sequence. Acts as an instantaneous hold.\n SelfT& set( const T &value ) { _sequence.set( value ); return *this; }\n\n \/\/\/ Construct and append a Phrase to the Sequence.\n template<template <typename> class PhraseT, typename... Args>\n SelfT& then( const T &value, Time duration, Args&&... args ) { _sequence.template then<PhraseT>( value, duration, std::forward<Args>(args)... ); return *this; }\n\n \/\/\/ Append a phrase to the Sequence.\n SelfT& then( const PhraseRef<T> &phrase ) { _sequence.then( phrase ); return *this; }\n\n \/\/\/ Append a sequence to the Sequence.\n SelfT& then( const Sequence<T> &sequence ) { _sequence.then( sequence ); return *this; }\n\n \/\/=================================================\n \/\/ Extra Sugar.\n \/\/=================================================\n\n \/\/\/ Append a Hold to the end of the Sequence. Assumes you want to hold using the Sequence's current end value.\n SelfT& hold( Time duration ) { _sequence.template then<Hold>( _sequence.getEndValue(), duration ); return *this; }\n\n \/\/=================================================\n \/\/ Accessors to Motion and Sequence.\n \/\/=================================================\n\n Sequence<T>& getSequence() { return _sequence; }\n Motion<T>& getMotion() { return _motion; }\n\nprivate:\n Motion<T> &_motion;\n Sequence<T> &_sequence;\n const Timeline &_timeline;\n};\n\n} \/\/ namespace choreograph\n<commit_msg>Add holdUntil helper function.<commit_after>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"Motion.hpp\"\n#include \"Cue.h\"\n\nnamespace choreograph\n{\n\nclass Timeline;\n\n\/\/\/\n\/\/\/ Options for manipulating newly created TimelineItems.\n\/\/\/ Uses CRTP so we don't lose the actual type when chaining methods.\n\/\/\/ Do not store the TimelineOptions object, as it contains a non-owning reference.\n\/\/\/\ntemplate<typename Derived>\nclass TimelineOptionsBase\n{\npublic:\n TimelineOptionsBase( TimelineItem &item ):\n _item( item )\n {}\n\n \/\/=================================================\n \/\/ TimelineItem Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set whether the item should be removed from the timeline on finish.\n Derived& removeOnFinish( bool doRemove ) { _item.setRemoveOnFinish( doRemove ); return self(); }\n\n \/\/\/ Set the rate at which time advances for Motion.\n Derived& playbackSpeed( Time speed ) { _item.setPlaybackSpeed( speed ); return self(); }\n\n \/\/\/ Set the initial time offset of the TimelineItem.\n \/\/\/ For Cues, this sets the time in the future.\n \/\/\/ For Motions, this is akin to adding a hold at the beginning of the Sequence.\n Derived& setStartTime( Time t ) { _item.setStartTime( t ); return self(); }\n\n \/\/\/ Returns a shared_ptr to the control object for the Item. Allows you to cancel the Item later.\n TimelineItemControlRef getControl() { return _item.getControl(); }\n\n \/\/\/ Returns an object that cancels the Cue when it falls out of scope.\n \/\/\/ You should store a ScopedCueRef in any class that captures [this] in a cued lambda.\n ScopedCancelRef getScopedControl() { return std::make_shared<ScopedCancel>( _item.getControl() ); }\n\nprivate:\n TimelineItem &_item;\n Derived& self() { return static_cast<Derived&>( *this ); }\n};\n\n\/\/\/\n\/\/\/ TimelineOptions with no additional behaviors beyond base.\n\/\/\/ Returned when creating cues.\n\/\/\/ Do not store the TimelineOptions object, as it contains a non-owning reference.\n\/\/\/\nclass TimelineOptions : public TimelineOptionsBase<TimelineOptions>\n{\npublic:\n TimelineOptions( TimelineItem &item )\n : TimelineOptionsBase<TimelineOptions>( item )\n {}\n};\n\n\/\/\/\n\/\/\/ MotionOptions provide a temporary facade for manipulating a timeline Motion and its underlying Sequence.\n\/\/\/ All methods return a reference back to the MotionOptions object for chaining.\n\/\/\/ Do not store the MotionOptions object, as it contains non-owning references.\n\/\/\/\ntemplate<typename T>\nclass MotionOptions : public TimelineOptionsBase<MotionOptions<T>>\n{\npublic:\n using SelfT = MotionOptions<T>;\n using MotionCallback = typename Motion<T>::Callback;\n\n MotionOptions( Motion<T> &motion, Sequence<T> &sequence, const Timeline &timeline ):\n TimelineOptionsBase<MotionOptions<T>>( motion ),\n _motion( motion ),\n _sequence( sequence ),\n _timeline( timeline )\n {}\n\n \/\/=================================================\n \/\/ Motion Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set function to be called when Motion starts. Receives reference to motion.\n SelfT& startFn( const MotionCallback &fn ) { _motion.setStartFn( fn ); return *this; }\n\n \/\/\/ Set function to be called when Motion updates. Receives current target value.\n SelfT& updateFn( const typename Motion<T>::Callback &fn ) { _motion.setUpdateFn( fn ); return *this; }\n\n \/\/\/ Set function to be called when Motion finishes. Receives reference to motion.\n SelfT& finishFn( const MotionCallback &fn ) { _motion.setFinishFn( fn ); return *this; }\n\n \/\/\/ Set a function to be called when the current inflection point is crossed.\n \/\/\/ An inflection occcurs when the Sequence moves from one Phrase to the next.\n \/\/\/ You must add a phrase after this for the inflection to occur.\n SelfT& onInflection( const MotionCallback &fn ) { return onInflection( _sequence.getPhraseCount(), fn ); }\n \/\/\/ Adds an inflection callback when the specified phrase index is crossed.\n SelfT& onInflection( size_t point, const MotionCallback &fn ) { _motion.addInflectionCallback( point, fn ); return *this; }\n\n \/\/\/ Clip the motion in \\t time from the current Motion playhead.\n \/\/\/ Also discards any phrases we have already played up to this point.\n SelfT& cutIn( Time t ) { _motion.cutIn( t ); return *this; }\n\n \/\/\/ Clip the motion at time \\t from the beginning of the Motion's Sequence.\n \/\/\/ When used after Timeline::apply, will have the same effect as cutIn().\n SelfT& cutAt( Time t ) { _motion.sliceSequence( 0, t ); return *this; }\n\n \/\/=================================================\n \/\/ Sequence Interface Mirroring.\n \/\/=================================================\n\n \/\/\/ Set the current value of the Sequence. Acts as an instantaneous hold.\n SelfT& set( const T &value ) { _sequence.set( value ); return *this; }\n\n \/\/\/ Construct and append a Phrase to the Sequence.\n template<template <typename> class PhraseT, typename... Args>\n SelfT& then( const T &value, Time duration, Args&&... args ) { _sequence.template then<PhraseT>( value, duration, std::forward<Args>(args)... ); return *this; }\n\n \/\/\/ Append a phrase to the Sequence.\n SelfT& then( const PhraseRef<T> &phrase ) { _sequence.then( phrase ); return *this; }\n\n \/\/\/ Append a sequence to the Sequence.\n SelfT& then( const Sequence<T> &sequence ) { _sequence.then( sequence ); return *this; }\n\n \/\/=================================================\n \/\/ Extra Sugar.\n \/\/=================================================\n\n \/\/\/ Append a Hold to the end of the Sequence. Assumes you want to hold using the Sequence's current end value.\n SelfT& hold( Time duration ) { _sequence.template then<Hold>( _sequence.getEndValue(), duration ); return *this; }\n\n\tSelfT& holdUntil( Time time ) { _sequence.template then<Hold>( _sequence.getEndValue(), std::max<Time>( time - _sequence.getDuration(), 0 ) ); return *this; }\n\n \/\/=================================================\n \/\/ Accessors to Motion and Sequence.\n \/\/=================================================\n\n Sequence<T>& getSequence() { return _sequence; }\n Motion<T>& getMotion() { return _motion; }\n\nprivate:\n Motion<T> &_motion;\n Sequence<T> &_sequence;\n const Timeline &_timeline;\n};\n\n} \/\/ namespace choreograph\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"stdafx.h\"\n#include \"Utility.h\"\n#include <fstream>\n\nstd::vector<std::wstring> split(const std::wstring& s, char c)\n{\n\tstd::wstring::size_type i = 0;\n\tstd::wstring::size_type j = s.find(c);\n\n\tstd::vector<std::wstring> result;\n\twhile (j != std::wstring::npos)\n\t{\n\t\tresult.push_back(s.substr(i, j - i));\n\t\ti = ++j;\n\t\tj = s.find(c, j);\n\t}\n\n\tif (!s.empty())\n\t\tresult.push_back(s.substr(i, s.length()));\n\n\treturn result;\n}\n\nstd::vector<std::wstring> GetFileList(const std::wstring& pattern, bool fullPaths)\n{\n\tstd::wstring directory;\n\tif (fullPaths)\n\t{\n\t\tconst wchar_t* pFilePart = GetFilePart(pattern);\n\t\tif (pFilePart > pattern.c_str())\n\t\t{\n\t\t\tdirectory = pattern.substr(0, pFilePart - pattern.c_str());\n\t\t}\n\t}\n\tWIN32_FIND_DATA findData;\n\tHANDLE hFindFile = FindFirstFileEx(pattern.c_str(), FindExInfoStandard,\n\t\t\t\t&findData, FindExSearchNameMatch, NULL, 0);\n\n\tstd::vector<std::wstring> result;\n\tif (hFindFile != INVALID_HANDLE_VALUE)\n\t{\n\t\tdo\n\t\t{\n\t\t\tresult.push_back(directory + findData.cFileName);\n\t\t} while (FindNextFile(hFindFile, &findData));\n\n\t\tFindClose(hFindFile);\n\t}\n\n\treturn result;\n}\n\n\/\/ Load a file and convert to a string. If the file contains\n\/\/ an embedded NUL then the resulting string will be truncated.\nstd::wstring LoadFileAsText(const std::wstring& fileName)\n{\n\tstd::ifstream f;\n\tf.open(fileName, std::ios_base::binary);\n\tif (!f)\n\t\treturn L\"\";\n\n\t\/\/ Find the file length.\n\tf.seekg(0, std::ios_base::end);\n\tsize_t length = (size_t)f.tellg();\n\tf.seekg(0, std::ios_base::beg);\n\n\t\/\/ Allocate a buffer and read the file.\n\tstd::vector<char> data(length + 2);\n\tf.read(&data[0], length);\n\tif (!f)\n\t\treturn L\"\";\n\n\t\/\/ Add a multi-byte null terminator.\n\tdata[length] = 0;\n\tdata[length+1] = 0;\n\n\tconst wchar_t bom = 0xFEFF;\n\tif (memcmp(&bom, &data[0], sizeof(bom)) == 0)\n\t{\n\t\t\/\/ Assume UTF-16, strip bom, and return.\n\t\treturn reinterpret_cast<const wchar_t*>(&data[sizeof(bom)]);\n\t}\n\n\t\/\/ If not-UTF-16 then convert from ANSI to wstring and return\n\treturn AnsiToUnicode(&data[0]);\n}\n\n\nvoid WriteTextAsFile(const std::wstring& fileName, const std::wstring& text)\n{\n\tstd::ofstream outFile;\n\toutFile.open(fileName, std::ios_base::binary);\n\tif (!outFile)\n\t\treturn;\n\n\tconst wchar_t bom = 0xFEFF; \/\/ Always write a byte order mark\n\toutFile.write(reinterpret_cast<const char*>(&bom), sizeof(bom));\n\toutFile.write(reinterpret_cast<const char*>(text.c_str()), text.size() * sizeof(text[0]));\n}\n\nvoid SetRegistryDWORD(HKEY root, const std::wstring& subkey, const std::wstring& valueName, DWORD value)\n{\n\tHKEY key;\n\tLONG result = RegOpenKeyEx(root, subkey.c_str(), 0, KEY_ALL_ACCESS, &key);\n\tif (result == ERROR_SUCCESS)\n\t{\n\t\tLONG setResult = RegSetValueEx(key, valueName.c_str(), 0, REG_DWORD, reinterpret_cast<const BYTE*>(&value), sizeof(value));\n\t\tRegCloseKey(key);\n\t}\n}\n\nvoid CreateRegistryKey(HKEY root, const std::wstring& subkey, const std::wstring& newKey)\n{\n\tHKEY key;\n\tLONG result = RegOpenKeyEx(root, subkey.c_str(), 0, KEY_ALL_ACCESS, &key);\n\tif (result == ERROR_SUCCESS)\n\t{\n\t\tHKEY resultKey;\n\t\tresult = RegCreateKey(key, newKey.c_str(), &resultKey);\n\t\tif (result == ERROR_SUCCESS)\n\t\t{\n\t\t\tRegCloseKey(resultKey);\n\t\t}\n\t\tRegCloseKey(key);\n\t}\n}\n\nstd::wstring GetEditControlText(HWND hEdit)\n{\n\tstd::wstring result;\n\tint length = GetWindowTextLength(hEdit);\n\tstd::vector<wchar_t> buffer(length + 1);\n\tGetWindowText(hEdit, &buffer[0], buffer.size());\n\t\/\/ Double-verify that the buffer is null-terminated.\n\tbuffer[buffer.size() - 1] = 0;\n\treturn &buffer[0];\n}\n\nstd::wstring AnsiToUnicode(const std::string& text)\n{\n\t\/\/ Determine number of wide characters to be allocated for the\n\t\/\/ Unicode string.\n\tsize_t cCharacters = text.size() + 1;\n\n\tstd::vector<wchar_t> buffer(cCharacters);\n\n\t\/\/ Convert to Unicode.\n\tstd::wstring result;\n\tif (MultiByteToWideChar(CP_ACP, 0, text.c_str(), cCharacters, &buffer[0], cCharacters))\n\t{\n\t\t\/\/ Double-verify that the buffer is null-terminated.\n\t\tbuffer[buffer.size() - 1] = 0;\n\t\tresult = &buffer[0];\n\t\treturn result;\n\t}\n\n\treturn result;\n}\n\n\/\/ Get the next\/previous dialog item (next\/prev in window order and tab order) allowing\n\/\/ for disabled controls, invisible controls, and wrapping at the end of the tab order.\n\nstatic bool ControlOK(HWND win)\n{\n\tif (!win)\n\t\treturn false;\n\tif (!IsWindowEnabled(win))\n\t\treturn false;\n\tif (!(GetWindowLong(win, GWL_STYLE) & WS_TABSTOP))\n\t\treturn false;\n\t\/\/ You have to check for visibility of the parent window because during dialog\n\t\/\/ creation the parent window is invisible, which renders the child windows\n\t\/\/ all invisible - not good.\n\tif (!IsWindowVisible(win) && IsWindowVisible(GetParent(win)))\n\t\treturn false;\n\treturn true;\n}\n\nstatic HWND GetNextDlgItem(HWND win, bool Wrap)\n{\n\tHWND next = GetWindow(win, GW_HWNDNEXT);\n\twhile (next != win && !ControlOK(next))\n\t{\n\t\tif (next)\n\t\t\tnext = GetWindow(next, GW_HWNDNEXT);\n\t\telse\n\t\t{\n\t\t\tif (Wrap)\n\t\t\t\tnext = GetWindow(win, GW_HWNDFIRST);\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\tassert(!Wrap || next);\n\treturn next;\n}\n\nvoid SmartEnableWindow(HWND Win, BOOL Enable)\n{\n\tassert(Win);\n\tif (!Enable)\n\t{\n\t\tHWND hasfocus = GetFocus();\n\t\tbool FocusProblem = false;\n\t\tHWND focuscopy;\n\t\tfor (focuscopy = hasfocus; focuscopy; focuscopy = (GetParent)(focuscopy))\n\t\t\tif (focuscopy == Win)\n\t\t\t\tFocusProblem = true;\n\t\tif (FocusProblem)\n\t\t{\n\t\t\tHWND nextctrl = GetNextDlgItem(Win, true);\n\t\t\tif (nextctrl)\n\t\t\t\tSetFocus(nextctrl);\n\t\t}\n\t}\n\t::EnableWindow(Win, Enable);\n}\n\nconst wchar_t* GetFilePart(const std::wstring& path)\n{\n\tconst wchar_t* pLastSlash = wcsrchr(path.c_str(), '\\\\');\n\tif (pLastSlash)\n\t\treturn pLastSlash + 1;\n\t\/\/ If there's no slash then the file part is the entire string.\n\treturn path.c_str();\n}\n\nconst wchar_t* GetFileExt(const std::wstring& path)\n{\n\tconst wchar_t* pFilePart = GetFilePart(path);\n\tconst wchar_t* pLastPeriod = wcsrchr(pFilePart, '.');\n\tif (pLastPeriod)\n\t\treturn pLastPeriod;\n\treturn pFilePart + wcslen(pFilePart);\n}\n\nconst std::pair<std::wstring, std::wstring> CrackFilePart(const std::wstring& path)\n{\n\tstd::wstring filePart = GetFilePart(path);\n\tconst std::wstring extension = GetFileExt(filePart);\n\tif (!extension.empty())\n\t{\n\t\tfilePart = filePart.substr(0, filePart.size() - extension.size());\n\t}\n\n\treturn std::pair<std::wstring, std::wstring>(filePart, extension);\n}\n\nint DeleteOneFile(HWND hwnd, const std::wstring& path)\n{\n\tstd::vector<std::wstring> paths;\n\tpaths.push_back(path);\n\treturn DeleteFiles(hwnd, paths);\n}\n\nint DeleteFiles(HWND hwnd, const std::vector<std::wstring>& paths)\n{\n\tstd::vector<wchar_t> fileNames;\n\tfor (auto& path : paths)\n\t{\n\t\t\/\/ Push the file name and its NULL terminator onto the vector.\n\t\tfileNames.insert(fileNames.end(), path.c_str(), path.c_str() + path.size());\n\t\tfileNames.push_back(0);\n\t}\n\n\t\/\/ Double null-terminate.\n\tfileNames.push_back(0);\n\n\tSHFILEOPSTRUCT fileOp =\n\t{\n\t\thwnd,\n\t\tFO_DELETE,\n\t\t&fileNames[0],\n\t\tNULL,\n\t\tFOF_ALLOWUNDO | FOF_FILESONLY | FOF_NOCONFIRMATION,\n\t};\n\t\/\/ Delete using the recycle bin.\n\tint result = SHFileOperation(&fileOp);\n\n\treturn result;\n}\n\nvoid SetClipboardText(const std::wstring& text)\n{\n\tBOOL cb = OpenClipboard(GetDesktopWindow());\n\tif (!cb)\n\t\treturn;\n\n\tEmptyClipboard();\n\n\tsize_t length = (text.size() + 1) * sizeof(wchar_t);\n\tHANDLE hmem = GlobalAlloc(GMEM_MOVEABLE, length);\n\tif (hmem)\n\t{\n\t\tvoid *ptr = GlobalLock(hmem);\n\t\tif (ptr != NULL)\n\t\t{\n\t\t\tmemcpy(ptr, text.c_str(), length);\n\t\t\tGlobalUnlock(hmem);\n\n\t\t\tSetClipboardData(CF_UNICODETEXT, hmem);\n\t\t}\n\t}\n\n\tCloseClipboard();\n}\n\nint64_t GetFileSize(const std::wstring& path)\n{\n\tLARGE_INTEGER result;\n\tHANDLE hFile = CreateFile(path.c_str(), GENERIC_READ,\n\t\tFILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t\tFILE_ATTRIBUTE_NORMAL, NULL);\n\tif (hFile == INVALID_HANDLE_VALUE)\n\t\treturn 0;\n\n\tif (GetFileSizeEx(hFile, &result))\n\t{\n\t\tCloseHandle(hFile);\n\t\treturn result.QuadPart;\n\t}\n\tCloseHandle(hFile);\n\treturn 0;\n}\n\nbool Is64BitWindows()\n{\n\t\/\/ http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2005\/02\/01\/364563.aspx\n\tBOOL f64 = FALSE;\n\tbool bIsWin64 = IsWow64Process(GetCurrentProcess(), &f64) && f64;\n\treturn bIsWin64;\n}\n\nWindowsVersion GetWindowsVersion()\n{\n\tOSVERSIONINFO verInfo = { sizeof(OSVERSIONINFO) };\n#pragma warning(suppress : 4996)\t\/\/ warning C4996: 'GetVersionExA': was declared deprecated\n\tGetVersionEx(&verInfo);\n\n\t\/\/ Windows 10 preview has major version 10, if you have a compatibility\n\t\/\/ manifest for that OS, which this program should have.\n\tif (verInfo.dwMajorVersion > 6)\n\t\treturn kWindowsVersion10;\t\/\/ Or higher, I guess.\n\n\t\/\/ Windows 8.1 will only be returned if there is an appropriate\n\t\/\/ compatibility manifest.\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 3)\n\t\treturn kWindowsVersion8_1;\n\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 2)\n\t\treturn kWindowsVersion8;\n\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 1)\n\t\treturn kWindowsVersion7;\n\n\tif (verInfo.dwMajorVersion == 6)\n\t\treturn kWindowsVersionVista;\n\n\treturn kWindowsVersionXP;\n}\n\nbool IsWindowsServer()\n{\n\tOSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, { 0 }, 0, 0, 0, VER_NT_WORKSTATION };\n\tDWORDLONG const dwlConditionMask = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL);\n\n\tbool result = !VerifyVersionInfoW(&osvi, VER_PRODUCT_TYPE, dwlConditionMask);\n\treturn result;\n}\n\n\n\nstd::wstring FindPython()\n{\n#pragma warning(suppress:4996)\n\tconst wchar_t* path = _wgetenv(L\"path\");\n\tif (path)\n\t{\n\t\tstd::vector<std::wstring> pathParts = split(path, ';');\n\t\tfor (auto part : pathParts)\n\t\t{\n\t\t\tstd::wstring pythonPath = part + L\"\\\\python.exe\";\n\t\t\tif (PathFileExists(pythonPath.c_str()))\n\t\t\t{\n\t\t\t\treturn pythonPath;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ No python found.\n\treturn L\"\";\n}\n<commit_msg>Make sure UIforETW builds cleanly under \/analyze.<commit_after>\/*\nCopyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"stdafx.h\"\n#include \"Utility.h\"\n#include <fstream>\n\nstd::vector<std::wstring> split(const std::wstring& s, char c)\n{\n\tstd::wstring::size_type i = 0;\n\tstd::wstring::size_type j = s.find(c);\n\n\tstd::vector<std::wstring> result;\n\twhile (j != std::wstring::npos)\n\t{\n\t\tresult.push_back(s.substr(i, j - i));\n\t\ti = ++j;\n\t\tj = s.find(c, j);\n\t}\n\n\tif (!s.empty())\n\t\tresult.push_back(s.substr(i, s.length()));\n\n\treturn result;\n}\n\nstd::vector<std::wstring> GetFileList(const std::wstring& pattern, bool fullPaths)\n{\n\tstd::wstring directory;\n\tif (fullPaths)\n\t{\n\t\tconst wchar_t* pFilePart = GetFilePart(pattern);\n\t\tif (pFilePart > pattern.c_str())\n\t\t{\n\t\t\tdirectory = pattern.substr(0, pFilePart - pattern.c_str());\n\t\t}\n\t}\n\tWIN32_FIND_DATA findData;\n\tHANDLE hFindFile = FindFirstFileEx(pattern.c_str(), FindExInfoStandard,\n\t\t\t\t&findData, FindExSearchNameMatch, NULL, 0);\n\n\tstd::vector<std::wstring> result;\n\tif (hFindFile != INVALID_HANDLE_VALUE)\n\t{\n\t\tdo\n\t\t{\n\t\t\tresult.push_back(directory + findData.cFileName);\n\t\t} while (FindNextFile(hFindFile, &findData));\n\n\t\tFindClose(hFindFile);\n\t}\n\n\treturn result;\n}\n\n\/\/ Load a file and convert to a string. If the file contains\n\/\/ an embedded NUL then the resulting string will be truncated.\nstd::wstring LoadFileAsText(const std::wstring& fileName)\n{\n\tstd::ifstream f;\n\tf.open(fileName, std::ios_base::binary);\n\tif (!f)\n\t\treturn L\"\";\n\n\t\/\/ Find the file length.\n\tf.seekg(0, std::ios_base::end);\n\tsize_t length = (size_t)f.tellg();\n\tf.seekg(0, std::ios_base::beg);\n\n\t\/\/ Allocate a buffer and read the file.\n\tstd::vector<char> data(length + 2);\n\tf.read(&data[0], length);\n\tif (!f)\n\t\treturn L\"\";\n\n\t\/\/ Add a multi-byte null terminator.\n\tdata[length] = 0;\n\tdata[length+1] = 0;\n\n\tconst wchar_t bom = 0xFEFF;\n\tif (memcmp(&bom, &data[0], sizeof(bom)) == 0)\n\t{\n\t\t\/\/ Assume UTF-16, strip bom, and return.\n\t\treturn reinterpret_cast<const wchar_t*>(&data[sizeof(bom)]);\n\t}\n\n\t\/\/ If not-UTF-16 then convert from ANSI to wstring and return\n\treturn AnsiToUnicode(&data[0]);\n}\n\n\nvoid WriteTextAsFile(const std::wstring& fileName, const std::wstring& text)\n{\n\tstd::ofstream outFile;\n\toutFile.open(fileName, std::ios_base::binary);\n\tif (!outFile)\n\t\treturn;\n\n\tconst wchar_t bom = 0xFEFF; \/\/ Always write a byte order mark\n\toutFile.write(reinterpret_cast<const char*>(&bom), sizeof(bom));\n\toutFile.write(reinterpret_cast<const char*>(text.c_str()), text.size() * sizeof(text[0]));\n}\n\nvoid SetRegistryDWORD(HKEY root, const std::wstring& subkey, const std::wstring& valueName, DWORD value)\n{\n\tHKEY key;\n\tLONG result = RegOpenKeyEx(root, subkey.c_str(), 0, KEY_ALL_ACCESS, &key);\n\tif (result == ERROR_SUCCESS)\n\t{\n\t\tLONG setResult = RegSetValueEx(key, valueName.c_str(), 0, REG_DWORD, reinterpret_cast<const BYTE*>(&value), sizeof(value));\n\t\tRegCloseKey(key);\n\t}\n}\n\nvoid CreateRegistryKey(HKEY root, const std::wstring& subkey, const std::wstring& newKey)\n{\n\tHKEY key;\n\tLONG result = RegOpenKeyEx(root, subkey.c_str(), 0, KEY_ALL_ACCESS, &key);\n\tif (result == ERROR_SUCCESS)\n\t{\n\t\tHKEY resultKey;\n\t\tresult = RegCreateKey(key, newKey.c_str(), &resultKey);\n\t\tif (result == ERROR_SUCCESS)\n\t\t{\n\t\t\tRegCloseKey(resultKey);\n\t\t}\n\t\tRegCloseKey(key);\n\t}\n}\n\nstd::wstring GetEditControlText(HWND hEdit)\n{\n\tstd::wstring result;\n\tint length = GetWindowTextLength(hEdit);\n\tstd::vector<wchar_t> buffer(length + 1);\n\tGetWindowText(hEdit, &buffer[0], buffer.size());\n\t\/\/ Double-verify that the buffer is null-terminated.\n\tbuffer[buffer.size() - 1] = 0;\n\treturn &buffer[0];\n}\n\nstd::wstring AnsiToUnicode(const std::string& text)\n{\n\t\/\/ Determine number of wide characters to be allocated for the\n\t\/\/ Unicode string.\n\tsize_t cCharacters = text.size() + 1;\n\n\tstd::vector<wchar_t> buffer(cCharacters);\n\n\t\/\/ Convert to Unicode.\n\tstd::wstring result;\n\tif (MultiByteToWideChar(CP_ACP, 0, text.c_str(), cCharacters, &buffer[0], cCharacters))\n\t{\n\t\t\/\/ Double-verify that the buffer is null-terminated.\n\t\tbuffer[buffer.size() - 1] = 0;\n\t\tresult = &buffer[0];\n\t\treturn result;\n\t}\n\n\treturn result;\n}\n\n\/\/ Get the next\/previous dialog item (next\/prev in window order and tab order) allowing\n\/\/ for disabled controls, invisible controls, and wrapping at the end of the tab order.\n\nstatic bool ControlOK(HWND win)\n{\n\tif (!win)\n\t\treturn false;\n\tif (!IsWindowEnabled(win))\n\t\treturn false;\n\tif (!(GetWindowLong(win, GWL_STYLE) & WS_TABSTOP))\n\t\treturn false;\n\t\/\/ You have to check for visibility of the parent window because during dialog\n\t\/\/ creation the parent window is invisible, which renders the child windows\n\t\/\/ all invisible - not good.\n\tif (!IsWindowVisible(win) && IsWindowVisible(GetParent(win)))\n\t\treturn false;\n\treturn true;\n}\n\nstatic HWND GetNextDlgItem(HWND win, bool Wrap)\n{\n\tHWND next = GetWindow(win, GW_HWNDNEXT);\n\twhile (next != win && !ControlOK(next))\n\t{\n\t\tif (next)\n\t\t\tnext = GetWindow(next, GW_HWNDNEXT);\n\t\telse\n\t\t{\n\t\t\tif (Wrap)\n\t\t\t\tnext = GetWindow(win, GW_HWNDFIRST);\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\tassert(!Wrap || next);\n\treturn next;\n}\n\nvoid SmartEnableWindow(HWND Win, BOOL Enable)\n{\n\tassert(Win);\n\tif (!Enable)\n\t{\n\t\tHWND hasfocus = GetFocus();\n\t\tbool FocusProblem = false;\n\t\tHWND focuscopy;\n\t\tfor (focuscopy = hasfocus; focuscopy; focuscopy = (GetParent)(focuscopy))\n\t\t\tif (focuscopy == Win)\n\t\t\t\tFocusProblem = true;\n\t\tif (FocusProblem)\n\t\t{\n\t\t\tHWND nextctrl = GetNextDlgItem(Win, true);\n\t\t\tif (nextctrl)\n\t\t\t\tSetFocus(nextctrl);\n\t\t}\n\t}\n\t::EnableWindow(Win, Enable);\n}\n\nconst wchar_t* GetFilePart(const std::wstring& path)\n{\n\tconst wchar_t* pLastSlash = wcsrchr(path.c_str(), '\\\\');\n\tif (pLastSlash)\n\t\treturn pLastSlash + 1;\n\t\/\/ If there's no slash then the file part is the entire string.\n\treturn path.c_str();\n}\n\nconst wchar_t* GetFileExt(const std::wstring& path)\n{\n\tconst wchar_t* pFilePart = GetFilePart(path);\n\tconst wchar_t* pLastPeriod = wcsrchr(pFilePart, '.');\n\tif (pLastPeriod)\n\t\treturn pLastPeriod;\n\treturn pFilePart + wcslen(pFilePart);\n}\n\nconst std::pair<std::wstring, std::wstring> CrackFilePart(const std::wstring& path)\n{\n\tstd::wstring filePart = GetFilePart(path);\n\tconst std::wstring extension = GetFileExt(filePart);\n\tif (!extension.empty())\n\t{\n\t\tfilePart = filePart.substr(0, filePart.size() - extension.size());\n\t}\n\n\treturn std::pair<std::wstring, std::wstring>(filePart, extension);\n}\n\nint DeleteOneFile(HWND hwnd, const std::wstring& path)\n{\n\tstd::vector<std::wstring> paths;\n\tpaths.push_back(path);\n\treturn DeleteFiles(hwnd, paths);\n}\n\nint DeleteFiles(HWND hwnd, const std::vector<std::wstring>& paths)\n{\n\tstd::vector<wchar_t> fileNames;\n\tfor (auto& path : paths)\n\t{\n\t\t\/\/ Push the file name and its NULL terminator onto the vector.\n\t\tfileNames.insert(fileNames.end(), path.c_str(), path.c_str() + path.size());\n\t\tfileNames.push_back(0);\n\t}\n\n\t\/\/ Double null-terminate.\n\tfileNames.push_back(0);\n\n\tSHFILEOPSTRUCT fileOp =\n\t{\n\t\thwnd,\n\t\tFO_DELETE,\n\t\t&fileNames[0],\n\t\tNULL,\n\t\tFOF_ALLOWUNDO | FOF_FILESONLY | FOF_NOCONFIRMATION,\n\t};\n\t\/\/ Delete using the recycle bin.\n\tint result = SHFileOperation(&fileOp);\n\n\treturn result;\n}\n\nvoid SetClipboardText(const std::wstring& text)\n{\n\tBOOL cb = OpenClipboard(GetDesktopWindow());\n\tif (!cb)\n\t\treturn;\n\n\tEmptyClipboard();\n\n\tsize_t length = (text.size() + 1) * sizeof(wchar_t);\n\tHANDLE hmem = GlobalAlloc(GMEM_MOVEABLE, length);\n\tif (hmem)\n\t{\n\t\tvoid *ptr = GlobalLock(hmem);\n\t\tif (ptr != NULL)\n\t\t{\n\t\t\tmemcpy(ptr, text.c_str(), length);\n\t\t\tGlobalUnlock(hmem);\n\n\t\t\tSetClipboardData(CF_UNICODETEXT, hmem);\n\t\t}\n\t}\n\n\tCloseClipboard();\n}\n\nint64_t GetFileSize(const std::wstring& path)\n{\n\tLARGE_INTEGER result;\n\tHANDLE hFile = CreateFile(path.c_str(), GENERIC_READ,\n\t\tFILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\n\t\tFILE_ATTRIBUTE_NORMAL, NULL);\n\tif (hFile == INVALID_HANDLE_VALUE)\n\t\treturn 0;\n\n\tif (GetFileSizeEx(hFile, &result))\n\t{\n\t\tCloseHandle(hFile);\n\t\treturn result.QuadPart;\n\t}\n\tCloseHandle(hFile);\n\treturn 0;\n}\n\nbool Is64BitWindows()\n{\n\t\/\/ http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2005\/02\/01\/364563.aspx\n\tBOOL f64 = FALSE;\n\tbool bIsWin64 = IsWow64Process(GetCurrentProcess(), &f64) && f64;\n\treturn bIsWin64;\n}\n\nWindowsVersion GetWindowsVersion()\n{\n\tOSVERSIONINFO verInfo = { sizeof(OSVERSIONINFO) };\n\t\/\/ warning C4996: 'GetVersionExA': was declared deprecated\n\t\/\/ warning C28159: Consider using 'IsWindows*' instead of 'GetVersionExW'.Reason : Deprecated.Use VerifyVersionInfo* or IsWindows* macros from VersionHelpers.\n#pragma warning(suppress : 4996)\n#pragma warning(suppress : 28159)\n\tGetVersionEx(&verInfo);\n\n\t\/\/ Windows 10 preview has major version 10, if you have a compatibility\n\t\/\/ manifest for that OS, which this program should have.\n\tif (verInfo.dwMajorVersion > 6)\n\t\treturn kWindowsVersion10;\t\/\/ Or higher, I guess.\n\n\t\/\/ Windows 8.1 will only be returned if there is an appropriate\n\t\/\/ compatibility manifest.\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 3)\n\t\treturn kWindowsVersion8_1;\n\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 2)\n\t\treturn kWindowsVersion8;\n\n\tif (verInfo.dwMajorVersion == 6 && verInfo.dwMinorVersion >= 1)\n\t\treturn kWindowsVersion7;\n\n\tif (verInfo.dwMajorVersion == 6)\n\t\treturn kWindowsVersionVista;\n\n\treturn kWindowsVersionXP;\n}\n\nbool IsWindowsServer()\n{\n\tOSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, { 0 }, 0, 0, 0, VER_NT_WORKSTATION };\n\tDWORDLONG const dwlConditionMask = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL);\n\n\tbool result = !VerifyVersionInfoW(&osvi, VER_PRODUCT_TYPE, dwlConditionMask);\n\treturn result;\n}\n\n\n\nstd::wstring FindPython()\n{\n#pragma warning(suppress:4996)\n\tconst wchar_t* path = _wgetenv(L\"path\");\n\tif (path)\n\t{\n\t\tstd::vector<std::wstring> pathParts = split(path, ';');\n\t\tfor (auto part : pathParts)\n\t\t{\n\t\t\tstd::wstring pythonPath = part + L\"\\\\python.exe\";\n\t\t\tif (PathFileExists(pythonPath.c_str()))\n\t\t\t{\n\t\t\t\treturn pythonPath;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ No python found.\n\treturn L\"\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/param-nodes.h\"\n\n#include <limits>\n#include <cmath>\n#include <stdexcept>\n\n#include \"dynet\/nodes-macros.h\"\n#include \"dynet\/weight-decay.h\"\n\n#ifdef HAVE_CUDA\n#include \"dynet\/gpu-ops.h\"\n#endif\n\nusing namespace std;\n\nnamespace dynet {\n\n#ifndef __CUDACC__\n\nstring ConstParameterNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"const_parameters(\" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n return dim;\n}\n\nstring ParameterNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"parameters(\" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim ParameterNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n return dim;\n}\n\nvoid ParameterNode::accumulate_grad(const Tensor& g) {\n if(params.mp != nullptr)\n params.get()->accumulate_grad(g);\n else if(lparams.mp != nullptr)\n lparams.get()->accumulate_grad(g);\n else\n DYNET_RUNTIME_ERR(\"ConstParameterNode has neither Parameter nor LookupParameter\");\n}\n\nstring InputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"constant(\" << dim << ')';\n return s.str();\n}\n\nDim InputNode::dim_forward(const vector<Dim>& xs) const {\n return dim;\n}\n\nstring SparseInputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"sparse_constant(\" << dim << ')';\n return s.str();\n}\n\nDim SparseInputNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(ids.size() == data.size(),\n \"Mismatch between size of ids (\" << ids.size() << \") and size of data (\" << data.size() << \") in SparseInput\");\n return dim;\n}\n\nsize_t SparseInputNode::aux_storage_size() const {\n return ids.size() * (sizeof(float) + sizeof(unsigned int));\n}\n\nstring ScalarInputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"scalar_constant(\" << pdata << ')';\n return s.str();\n}\n\nDim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {\n return Dim({1});\n}\n\nstd::string LookupNode::autobatch_profile(const ComputationGraph & cg) const {\n ostringstream oss;\n oss << \"lookup \";\n dim.print_profile(oss);\n return oss.str();\n}\nstd::vector<bool> LookupNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* LookupNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n vector<unsigned> ids;\n LookupNode* ln;\n for(auto batch_id : batch_ids) {\n ln = static_cast<LookupNode*>(cg.nodes[batch_id]);\n if(ln->pindex != nullptr)\n ids.push_back(*ln->pindex);\n else\n for(auto word_id : *ln->pindices)\n ids.push_back(word_id);\n }\n return new LookupNode(ln->params, ids);\n}\n\n\nsize_t LookupNode::aux_storage_size() const {\n return dim.bd * sizeof(unsigned);\n}\n\nstring LookupNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"lookup_parameters(|x|=\" << params.get()->values.size() << \" --> \" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim LookupNode::dim_forward(const vector<Dim>& xs) const {\n return dim;\n}\n\nvoid LookupNode::accumulate_grad(const Tensor& g) {\n if(pindex) {\n params.get()->accumulate_grad(*pindex, g);\n } else {\n DYNET_ASSERT(pindices, \"Have neither index nor index vector in LookupNode\");\n params.get()->accumulate_grads(pindices->size(), &(*pindices)[0], (unsigned*)aux_mem, g.v);\n }\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid ConstParameterNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n if(params.mp != nullptr)\n fx.tvec().device(*dev.edevice) = params.get()->values.tvec() * params.mp->weight_decay.current_weight_decay();\n else if(lparams.mp != nullptr)\n fx.tvec().device(*dev.edevice) = lparams.get()->all_values.tvec() * lparams.mp->weight_decay.current_weight_decay();\n else\n DYNET_RUNTIME_ERR(\"ConstParameterNode has neither Parameter nor LookupParameter\");\n}\n\ntemplate<class MyDevice>\nvoid ConstParameterNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ConstParameterNode)\n\ntemplate<class MyDevice>\nvoid ParameterNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n\/\/ TODO\n\/\/ if (params->not_regularized) {\n\/\/ fx.v = params->values.v;\n\/\/ return;\n\/\/ }\n if(params.mp != nullptr)\n fx.tvec().device(*dev.edevice) = params.get()->values.tvec() * params.mp->weight_decay.current_weight_decay();\n else if(lparams.mp != nullptr)\n fx.tvec().device(*dev.edevice) = lparams.get()->all_values.tvec() * lparams.mp->weight_decay.current_weight_decay();\n else\n DYNET_RUNTIME_ERR(\"ParameterNode has neither Parameter nor LookupParameter\");\n}\n\ntemplate<class MyDevice>\nvoid ParameterNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ParameterNode)\n\ntemplate<class MyDevice>\nvoid InputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n#if __CUDACC__\n cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);\n#else\n \/\/ TODO memcpy is only necessary if pdata->front() points to an unaligned location\n \/\/ need to compute this value\n bool is_input_address_aligned = false;\n if (!is_input_address_aligned) {\n memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));\n } else {\n fx.v = const_cast<float*>(&pdata->front());\n }\n#endif\n}\n\ntemplate<class MyDevice>\nvoid InputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(InputNode)\n\nstd::string InputNode::autobatch_profile(const ComputationGraph & cg) const {\n return \"input\";\n}\nstd::vector<bool> InputNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* InputNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n size_t my_size = 0;\n InputNode* sin;\n for(auto bid : batch_ids) {\n sin = static_cast<InputNode*>(cg.nodes[bid]);\n my_size += sin->pdata->size();\n }\n vector<float> values(my_size);\n size_t curr_pos = 0;\n for(auto bid : batch_ids) {\n sin = static_cast<InputNode*>(cg.nodes[bid]);\n memcpy(&values[curr_pos], &(*sin->pdata)[0], sin->pdata->size() * sizeof(float));\n curr_pos += sin->pdata->size();\n }\n DYNET_ASSERT(curr_pos == values.size(), \"current position and size of values does not match\");\n return new InputNode(Dim({(unsigned int)my_size}), values);\n}\n\ntemplate<class MyDevice>\nvoid SparseInputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n fx.tvec().device(*dev.edevice) = fx.tvec().constant(defdata);\n#if __CUDACC__\n unsigned int* ids_ptr = (unsigned int*)aux_mem;\n float* data_ptr = (float*)(ids_ptr + ids.size());\n cudaMemcpyAsync(ids_ptr, &ids[0], ids.size() * sizeof(unsigned int), cudaMemcpyHostToDevice);\n cudaMemcpyAsync(data_ptr, &data[0], data.size() * sizeof(float), cudaMemcpyHostToDevice);\n dynet::gpu::dense_to_sparse_assign(ids.size(), ids_ptr, data_ptr, fx.v);\n#else\n for(size_t i = 0; i < ids.size(); ++i)\n fx.v[ids[i]] = data[i];\n#endif\n}\n\ntemplate<class MyDevice>\nvoid SparseInputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(SparseInputNode)\n\ntemplate<class MyDevice>\nvoid ScalarInputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n#if __CUDACC__\n cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);\n#else\n fx.v[0] = *pdata;\n#endif\n}\n\ntemplate<class MyDevice>\nvoid ScalarInputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ScalarInputNode)\n\nstd::string ScalarInputNode::autobatch_profile(const ComputationGraph & cg) const {\n return \"scalar_input\";\n}\nstd::vector<bool> ScalarInputNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* ScalarInputNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n vector<float> values(batch_ids.size());\n ScalarInputNode* sin;\n for(size_t i = 0; i < batch_ids.size(); ++i) {\n sin = static_cast<ScalarInputNode*>(cg.nodes[batch_ids[i]]);\n values[i] = *sin->pdata;\n }\n return new InputNode(Dim({1}, batch_ids.size()), values);\n}\n\ntemplate<class MyDevice>\nvoid LookupNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n if(pindex) {\n DYNET_ARG_CHECK(*pindex < params.get()->values.size(),\n \"Out-of-bounds attempt to access index \" << *pindex << \" for LookupParameter of size \" << params.get()->values.size());\n DYNET_ASSERT(fx.d.batch_elems() == 1, \"Batch dimension > 1 for lookup with single index\");\n fx.tvec().device(*dev.edevice) = params.get()->values[*pindex].tvec() * params.mp->weight_decay.current_weight_decay();\n } else {\n DYNET_ASSERT(pindices, \"Have neither index nor index vector in LookupNode\");\n DYNET_ARG_CHECK(fx.d.batch_elems() == pindices->size(),\n \"In LookupNode, in index vector size (\" << pindices->size() << \") \"\n \"doesn't match batch size in expressions (\" << fx.d.batch_elems() << \")\");\n#if __CUDACC__\n CUDA_CHECK(cudaMemcpyAsync((unsigned*)aux_mem, &(*pindices)[0], fx.d.bd * sizeof(unsigned), cudaMemcpyHostToDevice));\n dynet::gpu::sparse_to_dense_block_assign_and_multiply(fx.d.bd, (unsigned*)aux_mem, fx.d.batch_size(), params.mp->weight_decay.current_weight_decay(), params.get()->all_values.v, fx.v);\n#else\n for (unsigned b = 0; b < pindices->size(); ++b) {\n unsigned i = pindices->at(b);\n DYNET_ARG_CHECK(i < params.get()->values.size(),\n \"Out-of-bounds attempt to access index \" << i << \" for LookupParameter of size \" << params.get()->values.size());\n fx.tb<2>().chip<2>(b).device(*dev.edevice) = params.get()->values[i].t<2>() * params.mp->weight_decay.current_weight_decay();\n }\n#endif\n }\n}\n\ntemplate<class MyDevice>\nvoid LookupNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(LookupNode)\n\n} \/\/ namespace dynet\n<commit_msg>Fixed compile error<commit_after>#include \"dynet\/param-nodes.h\"\n\n#include <limits>\n#include <cmath>\n#include <stdexcept>\n\n#include \"dynet\/nodes-macros.h\"\n#include \"dynet\/weight-decay.h\"\n\n#ifdef HAVE_CUDA\n#include \"dynet\/gpu-ops.h\"\n#endif\n\nusing namespace std;\n\nnamespace dynet {\n\n#ifndef __CUDACC__\n\nstring ConstParameterNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"const_parameters(\" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n return dim;\n}\n\nstring ParameterNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"parameters(\" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim ParameterNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n return dim;\n}\n\nvoid ParameterNode::accumulate_grad(const Tensor& g) {\n if(params.mp != nullptr)\n params.get()->accumulate_grad(g);\n else if(lparams.mp != nullptr)\n lparams.get()->accumulate_grad(g);\n else\n DYNET_RUNTIME_ERR(\"ConstParameterNode has neither Parameter nor LookupParameter\");\n}\n\nstring InputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"constant(\" << dim << ')';\n return s.str();\n}\n\nDim InputNode::dim_forward(const vector<Dim>& xs) const {\n return dim;\n}\n\nstd::string InputNode::autobatch_profile(const ComputationGraph & cg) const {\n return \"input\";\n}\nstd::vector<bool> InputNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* InputNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n size_t my_size = 0;\n InputNode* sin;\n for(auto bid : batch_ids) {\n sin = static_cast<InputNode*>(cg.nodes[bid]);\n my_size += sin->pdata->size();\n }\n vector<float> values(my_size);\n size_t curr_pos = 0;\n for(auto bid : batch_ids) {\n sin = static_cast<InputNode*>(cg.nodes[bid]);\n memcpy(&values[curr_pos], &(*sin->pdata)[0], sin->pdata->size() * sizeof(float));\n curr_pos += sin->pdata->size();\n }\n DYNET_ASSERT(curr_pos == values.size(), \"current position and size of values does not match\");\n return new InputNode(Dim({(unsigned int)my_size}), values);\n}\n\nstring SparseInputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"sparse_constant(\" << dim << ')';\n return s.str();\n}\n\nDim SparseInputNode::dim_forward(const vector<Dim>& xs) const {\n DYNET_ARG_CHECK(ids.size() == data.size(),\n \"Mismatch between size of ids (\" << ids.size() << \") and size of data (\" << data.size() << \") in SparseInput\");\n return dim;\n}\n\nsize_t SparseInputNode::aux_storage_size() const {\n return ids.size() * (sizeof(float) + sizeof(unsigned int));\n}\n\nstring ScalarInputNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"scalar_constant(\" << pdata << ')';\n return s.str();\n}\n\nDim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {\n return Dim({1});\n}\n\nstd::string ScalarInputNode::autobatch_profile(const ComputationGraph & cg) const {\n return \"scalar_input\";\n}\nstd::vector<bool> ScalarInputNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* ScalarInputNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n vector<float> values(batch_ids.size());\n ScalarInputNode* sin;\n for(size_t i = 0; i < batch_ids.size(); ++i) {\n sin = static_cast<ScalarInputNode*>(cg.nodes[batch_ids[i]]);\n values[i] = *sin->pdata;\n }\n return new InputNode(Dim({1}, batch_ids.size()), values);\n}\n\nstd::string LookupNode::autobatch_profile(const ComputationGraph & cg) const {\n ostringstream oss;\n oss << \"lookup \";\n dim.print_profile(oss);\n return oss.str();\n}\nstd::vector<bool> LookupNode::autobatch_concat(const ComputationGraph & cg) const {\n return vector<bool>();\n}\nNode* LookupNode::autobatch_pseudo_node(const ComputationGraph & cg,\n const std::vector<VariableIndex> & batch_ids) const {\n vector<unsigned> ids;\n LookupNode* ln;\n for(auto batch_id : batch_ids) {\n ln = static_cast<LookupNode*>(cg.nodes[batch_id]);\n if(ln->pindex != nullptr)\n ids.push_back(*ln->pindex);\n else\n for(auto word_id : *ln->pindices)\n ids.push_back(word_id);\n }\n return new LookupNode(ln->params, ids);\n}\n\n\nsize_t LookupNode::aux_storage_size() const {\n return dim.bd * sizeof(unsigned);\n}\n\nstring LookupNode::as_string(const vector<string>& arg_names) const {\n ostringstream s;\n s << \"lookup_parameters(|x|=\" << params.get()->values.size() << \" --> \" << dim << \") @ \" << params.get();\n return s.str();\n}\n\nDim LookupNode::dim_forward(const vector<Dim>& xs) const {\n return dim;\n}\n\nvoid LookupNode::accumulate_grad(const Tensor& g) {\n if(pindex) {\n params.get()->accumulate_grad(*pindex, g);\n } else {\n DYNET_ASSERT(pindices, \"Have neither index nor index vector in LookupNode\");\n params.get()->accumulate_grads(pindices->size(), &(*pindices)[0], (unsigned*)aux_mem, g.v);\n }\n}\n\n#endif\n\ntemplate<class MyDevice>\nvoid ConstParameterNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n if(params.mp != nullptr)\n fx.tvec().device(*dev.edevice) = params.get()->values.tvec() * params.mp->weight_decay.current_weight_decay();\n else if(lparams.mp != nullptr)\n fx.tvec().device(*dev.edevice) = lparams.get()->all_values.tvec() * lparams.mp->weight_decay.current_weight_decay();\n else\n DYNET_RUNTIME_ERR(\"ConstParameterNode has neither Parameter nor LookupParameter\");\n}\n\ntemplate<class MyDevice>\nvoid ConstParameterNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ConstParameterNode)\n\ntemplate<class MyDevice>\nvoid ParameterNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n\/\/ TODO\n\/\/ if (params->not_regularized) {\n\/\/ fx.v = params->values.v;\n\/\/ return;\n\/\/ }\n if(params.mp != nullptr)\n fx.tvec().device(*dev.edevice) = params.get()->values.tvec() * params.mp->weight_decay.current_weight_decay();\n else if(lparams.mp != nullptr)\n fx.tvec().device(*dev.edevice) = lparams.get()->all_values.tvec() * lparams.mp->weight_decay.current_weight_decay();\n else\n DYNET_RUNTIME_ERR(\"ParameterNode has neither Parameter nor LookupParameter\");\n}\n\ntemplate<class MyDevice>\nvoid ParameterNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ParameterNode)\n\ntemplate<class MyDevice>\nvoid InputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n#if __CUDACC__\n cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);\n#else\n \/\/ TODO memcpy is only necessary if pdata->front() points to an unaligned location\n \/\/ need to compute this value\n bool is_input_address_aligned = false;\n if (!is_input_address_aligned) {\n memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));\n } else {\n fx.v = const_cast<float*>(&pdata->front());\n }\n#endif\n}\n\ntemplate<class MyDevice>\nvoid InputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(InputNode)\n\ntemplate<class MyDevice>\nvoid SparseInputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n fx.tvec().device(*dev.edevice) = fx.tvec().constant(defdata);\n#if __CUDACC__\n unsigned int* ids_ptr = (unsigned int*)aux_mem;\n float* data_ptr = (float*)(ids_ptr + ids.size());\n cudaMemcpyAsync(ids_ptr, &ids[0], ids.size() * sizeof(unsigned int), cudaMemcpyHostToDevice);\n cudaMemcpyAsync(data_ptr, &data[0], data.size() * sizeof(float), cudaMemcpyHostToDevice);\n dynet::gpu::dense_to_sparse_assign(ids.size(), ids_ptr, data_ptr, fx.v);\n#else\n for(size_t i = 0; i < ids.size(); ++i)\n fx.v[ids[i]] = data[i];\n#endif\n}\n\ntemplate<class MyDevice>\nvoid SparseInputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(SparseInputNode)\n\ntemplate<class MyDevice>\nvoid ScalarInputNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n#if __CUDACC__\n cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);\n#else\n fx.v[0] = *pdata;\n#endif\n}\n\ntemplate<class MyDevice>\nvoid ScalarInputNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(ScalarInputNode)\n\ntemplate<class MyDevice>\nvoid LookupNode::forward_dev_impl(const MyDevice & dev, const vector<const Tensor*>& xs, Tensor& fx) const {\n DYNET_ASSERT(xs.size() == 0, \"Failed dimension check in FUNCNAME\");\n if(pindex) {\n DYNET_ARG_CHECK(*pindex < params.get()->values.size(),\n \"Out-of-bounds attempt to access index \" << *pindex << \" for LookupParameter of size \" << params.get()->values.size());\n DYNET_ASSERT(fx.d.batch_elems() == 1, \"Batch dimension > 1 for lookup with single index\");\n fx.tvec().device(*dev.edevice) = params.get()->values[*pindex].tvec() * params.mp->weight_decay.current_weight_decay();\n } else {\n DYNET_ASSERT(pindices, \"Have neither index nor index vector in LookupNode\");\n DYNET_ARG_CHECK(fx.d.batch_elems() == pindices->size(),\n \"In LookupNode, in index vector size (\" << pindices->size() << \") \"\n \"doesn't match batch size in expressions (\" << fx.d.batch_elems() << \")\");\n#if __CUDACC__\n CUDA_CHECK(cudaMemcpyAsync((unsigned*)aux_mem, &(*pindices)[0], fx.d.bd * sizeof(unsigned), cudaMemcpyHostToDevice));\n dynet::gpu::sparse_to_dense_block_assign_and_multiply(fx.d.bd, (unsigned*)aux_mem, fx.d.batch_size(), params.mp->weight_decay.current_weight_decay(), params.get()->all_values.v, fx.v);\n#else\n for (unsigned b = 0; b < pindices->size(); ++b) {\n unsigned i = pindices->at(b);\n DYNET_ARG_CHECK(i < params.get()->values.size(),\n \"Out-of-bounds attempt to access index \" << i << \" for LookupParameter of size \" << params.get()->values.size());\n fx.tb<2>().chip<2>(b).device(*dev.edevice) = params.get()->values[i].t<2>() * params.mp->weight_decay.current_weight_decay();\n }\n#endif\n }\n}\n\ntemplate<class MyDevice>\nvoid LookupNode::backward_dev_impl(const MyDevice & dev,\n const vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned i,\n Tensor& dEdxi) const {\n DYNET_RUNTIME_ERR(\"called backward() on arity 0 node: i = \" << i);\n}\nDYNET_NODE_INST_DEV_IMPL(LookupNode)\n\n} \/\/ namespace dynet\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file state.cpp\n * @author Christoph Jentzsch <cj@ethdev.com>\n * @date 2014\n * State test functions.\n *\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include \"JsonSpiritHeaders.h\"\n#include <libdevcore\/CommonIO.h>\n#include <libethereum\/CanonBlockChain.h>\n#include <libethereum\/State.h>\n#include <libethereum\/ExtVM.h>\n#include <libethereum\/Defaults.h>\n#include <libevm\/VM.h>\n#include \"TestHelper.h\"\n\nusing namespace std;\nusing namespace json_spirit;\nusing namespace dev;\nusing namespace dev::eth;\n\nnamespace dev { namespace test {\n\nvoid doStateTests(json_spirit::mValue& v, bool _fillin)\n{\n\tprocessCommandLineOptions();\n\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tcerr << i.first << endl;\n\t\tmObject& o = i.second.get_obj();\n\n\t\tBOOST_REQUIRE(o.count(\"env\") > 0);\n\t\tBOOST_REQUIRE(o.count(\"pre\") > 0);\n\t\tBOOST_REQUIRE(o.count(\"transaction\") > 0);\n\n\t\tImportTest importer(o, _fillin);\n\n\t\tState theState = importer.m_statePre;\n\t\tbytes tx = importer.m_transaction.rlp();\n\t\tbytes output;\n\n\t\ttry\n\t\t{\n\t\t\ttheState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);\n\t\t}\n\t\tcatch (Exception const& _e)\n\t\t{\n\t\t\tcnote << \"state execution did throw an exception: \" << diagnostic_information(_e);\n\t\t\ttheState.commit();\n\t\t}\n\t\tcatch (std::exception const& _e)\n\t\t{\n\t\t\tcnote << \"state execution did throw an exception: \" << _e.what();\n\t\t}\n\n\t\tif (_fillin)\n\t\t{\n#if ETH_FATDB\n\t\t\timporter.exportTest(output, theState);\n#else\n\t\t\tBOOST_THROW_EXCEPTION(Exception() << errinfo_comment(\"You can not fill tests when FATDB is switched off\"));\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_REQUIRE(o.count(\"post\") > 0);\n\t\t\tBOOST_REQUIRE(o.count(\"out\") > 0);\n\n\t\t\t\/\/ check output\n\t\t\tcheckOutput(output, o);\n\n\t\t\t\/\/ check logs\n\t\t\tcheckLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);\n\n\t\t\t\/\/ check addresses\n#if ETH_FATDB\n\t\t\tcout << \"fatDB is defined\\n\";\n\t\t\tauto expectedAddrs = importer.m_statePost.addresses();\n\t\t\tauto resultAddrs = theState.addresses();\n\t\t\tfor (auto& expectedPair : expectedAddrs)\n\t\t\t{\n\t\t\t\tauto& expectedAddr = expectedPair.first;\n\t\t\t\tauto resultAddrIt = resultAddrs.find(expectedAddr);\n\t\t\t\tif (resultAddrIt == resultAddrs.end())\n\t\t\t\t\tBOOST_ERROR(\"Missing expected address \" << expectedAddr);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << \": incorrect balance \" << theState.balance(expectedAddr) << \", expected \" << importer.m_statePost.balance(expectedAddr));\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << \": incorrect txCount \" << theState.transactionsFrom(expectedAddr) << \", expected \" << importer.m_statePost.transactionsFrom(expectedAddr));\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << \": incorrect code\");\n\n\t\t\t\t\tcheckStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcheckAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);\n#endif\n\t\t\tBOOST_CHECK_MESSAGE(theState.rootHash() == h256(o[\"postStateRoot\"].get_str()), \"wrong post state root\");\n\t\t}\n\t}\n}\n} }\/\/ Namespace Close\n\nBOOST_AUTO_TEST_SUITE(StateTests)\n\nBOOST_AUTO_TEST_CASE(stExample)\n{\n\tdev::test::executeTests(\"stExample\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stSystemOperationsTest)\n{\n\tdev::test::executeTests(\"stSystemOperationsTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stPreCompiledContracts)\n{\n\tdev::test::executeTests(\"stPreCompiledContracts\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stLogTests)\n{\n\tdev::test::executeTests(\"stLogTests\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stRecursiveCreate)\n{\n\tdev::test::executeTests(\"stRecursiveCreate\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stInitCodeTest)\n{\n\tdev::test::executeTests(\"stInitCodeTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stTransactionTest)\n{\n\tdev::test::executeTests(\"stTransactionTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stSpecialTest)\n{\n\tdev::test::executeTests(\"stSpecialTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stRefundTest)\n{\n\tdev::test::executeTests(\"stRefundTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stBlockHashTest)\n{\n\tdev::test::executeTests(\"stBlockHashTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)\n{\n\t for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t {\n\t\t\t string arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\t\t if (arg == \"--quadratic\" || arg == \"--all\")\n\t\t\t {\n\t\t\t\t\t auto start = chrono::steady_clock::now();\n\n\t\t\t\t\t dev::test::executeTests(\"stQuadraticComplexityTest\", \"\/StateTests\", dev::test::doStateTests);\n\n\t\t\t\t\t auto end = chrono::steady_clock::now();\n\t\t\t\t\t auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));\n\t\t\t\t\t cnote << \"test duration: \" << duration.count() << \" milliseconds.\\n\";\n\t\t\t }\n\t }\n}\n\nBOOST_AUTO_TEST_CASE(stMemoryStressTest)\n{\n\t for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t {\n\t\t\t string arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\t\t if (arg == \"--memory\" || arg == \"--all\")\n\t\t\t {\n\t\t\t\t\t auto start = chrono::steady_clock::now();\n\n\t\t\t\t\t dev::test::executeTests(\"stMemoryStressTest\", \"\/StateTests\", dev::test::doStateTests);\n\n\t\t\t\t\t auto end = chrono::steady_clock::now();\n\t\t\t\t\t auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));\n\t\t\t\t\t cnote << \"test duration: \" << duration.count() << \" milliseconds.\\n\";\n\t\t\t }\n\t }\n}\n\n BOOST_AUTO_TEST_CASE(stSolidityTest)\n {\n\t\tdev::test::executeTests(\"stSolidityTest\", \"\/StateTests\", dev::test::doStateTests);\n }\n\nBOOST_AUTO_TEST_CASE(stMemoryTest)\n{\n\t dev::test::executeTests(\"stMemoryTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\n\nBOOST_AUTO_TEST_CASE(stCreateTest)\n{\n\tfor (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t{\n\t\tstring arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\tif (arg == \"--createtest\")\n\t\t{\n\t\t\tif (boost::unit_test::framework::master_test_suite().argc <= i + 2)\n\t\t\t{\n\t\t\t\tcnote << \"usage: .\/testeth --createtest <PathToConstructor> <PathToDestiny>\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcnote << \"Populating tests...\";\n\t\t\t\tjson_spirit::mValue v;\n\t\t\t\tstring s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));\n\t\t\t\tBOOST_REQUIRE_MESSAGE(s.length() > 0, \"Content of \" + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + \" is empty.\");\n\t\t\t\tjson_spirit::read_string(s, v);\n\t\t\t\tdev::test::doStateTests(v, true);\n\t\t\t\twriteFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));\n\t\t\t}\n\t\t\tcatch (Exception const& _e)\n\t\t\t{\n\t\t\t\tBOOST_ERROR(\"Failed state test with Exception: \" << diagnostic_information(_e));\n\t\t\t}\n\t\t\tcatch (std::exception const& _e)\n\t\t\t{\n\t\t\t\tBOOST_ERROR(\"Failed state test with Exception: \" << _e.what());\n\t\t\t}\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(userDefinedFileState)\n{\n\tdev::test::userDefinedTest(\"--singletest\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>add memory tests<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file state.cpp\n * @author Christoph Jentzsch <cj@ethdev.com>\n * @date 2014\n * State test functions.\n *\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include \"JsonSpiritHeaders.h\"\n#include <libdevcore\/CommonIO.h>\n#include <libethereum\/CanonBlockChain.h>\n#include <libethereum\/State.h>\n#include <libethereum\/ExtVM.h>\n#include <libethereum\/Defaults.h>\n#include <libevm\/VM.h>\n#include \"TestHelper.h\"\n\nusing namespace std;\nusing namespace json_spirit;\nusing namespace dev;\nusing namespace dev::eth;\n\nnamespace dev { namespace test {\n\nvoid doStateTests(json_spirit::mValue& v, bool _fillin)\n{\n\tprocessCommandLineOptions();\n\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tcerr << i.first << endl;\n\t\tmObject& o = i.second.get_obj();\n\n\t\tBOOST_REQUIRE(o.count(\"env\") > 0);\n\t\tBOOST_REQUIRE(o.count(\"pre\") > 0);\n\t\tBOOST_REQUIRE(o.count(\"transaction\") > 0);\n\n\t\tImportTest importer(o, _fillin);\n\n\t\tState theState = importer.m_statePre;\n\t\tbytes tx = importer.m_transaction.rlp();\n\t\tbytes output;\n\n\t\ttry\n\t\t{\n\t\t\ttheState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);\n\t\t}\n\t\tcatch (Exception const& _e)\n\t\t{\n\t\t\tcnote << \"state execution did throw an exception: \" << diagnostic_information(_e);\n\t\t\ttheState.commit();\n\t\t}\n\t\tcatch (std::exception const& _e)\n\t\t{\n\t\t\tcnote << \"state execution did throw an exception: \" << _e.what();\n\t\t}\n\n\t\tif (_fillin)\n\t\t{\n#if ETH_FATDB\n\t\t\timporter.exportTest(output, theState);\n#else\n\t\t\tBOOST_THROW_EXCEPTION(Exception() << errinfo_comment(\"You can not fill tests when FATDB is switched off\"));\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_REQUIRE(o.count(\"post\") > 0);\n\t\t\tBOOST_REQUIRE(o.count(\"out\") > 0);\n\n\t\t\t\/\/ check output\n\t\t\tcheckOutput(output, o);\n\n\t\t\t\/\/ check logs\n\t\t\tcheckLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);\n\n\t\t\t\/\/ check addresses\n#if ETH_FATDB\n\t\t\tauto expectedAddrs = importer.m_statePost.addresses();\n\t\t\tauto resultAddrs = theState.addresses();\n\t\t\tfor (auto& expectedPair : expectedAddrs)\n\t\t\t{\n\t\t\t\tauto& expectedAddr = expectedPair.first;\n\t\t\t\tauto resultAddrIt = resultAddrs.find(expectedAddr);\n\t\t\t\tif (resultAddrIt == resultAddrs.end())\n\t\t\t\t\tBOOST_ERROR(\"Missing expected address \" << expectedAddr);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << \": incorrect balance \" << theState.balance(expectedAddr) << \", expected \" << importer.m_statePost.balance(expectedAddr));\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << \": incorrect txCount \" << theState.transactionsFrom(expectedAddr) << \", expected \" << importer.m_statePost.transactionsFrom(expectedAddr));\n\t\t\t\t\tBOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << \": incorrect code\");\n\n\t\t\t\t\tcheckStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcheckAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);\n#endif\n\t\t\tBOOST_CHECK_MESSAGE(theState.rootHash() == h256(o[\"postStateRoot\"].get_str()), \"wrong post state root\");\n\t\t}\n\t}\n}\n} }\/\/ Namespace Close\n\nBOOST_AUTO_TEST_SUITE(StateTests)\n\nBOOST_AUTO_TEST_CASE(stExample)\n{\n\tdev::test::executeTests(\"stExample\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stSystemOperationsTest)\n{\n\tdev::test::executeTests(\"stSystemOperationsTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stPreCompiledContracts)\n{\n\tdev::test::executeTests(\"stPreCompiledContracts\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stLogTests)\n{\n\tdev::test::executeTests(\"stLogTests\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stRecursiveCreate)\n{\n\tdev::test::executeTests(\"stRecursiveCreate\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stInitCodeTest)\n{\n\tdev::test::executeTests(\"stInitCodeTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stTransactionTest)\n{\n\tdev::test::executeTests(\"stTransactionTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stSpecialTest)\n{\n\tdev::test::executeTests(\"stSpecialTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stRefundTest)\n{\n\tdev::test::executeTests(\"stRefundTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stBlockHashTest)\n{\n\tdev::test::executeTests(\"stBlockHashTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)\n{\n\t for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t {\n\t\t\t string arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\t\t if (arg == \"--quadratic\" || arg == \"--all\")\n\t\t\t {\n\t\t\t\t\t auto start = chrono::steady_clock::now();\n\n\t\t\t\t\t dev::test::executeTests(\"stQuadraticComplexityTest\", \"\/StateTests\", dev::test::doStateTests);\n\n\t\t\t\t\t auto end = chrono::steady_clock::now();\n\t\t\t\t\t auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));\n\t\t\t\t\t cnote << \"test duration: \" << duration.count() << \" milliseconds.\\n\";\n\t\t\t }\n\t }\n}\n\nBOOST_AUTO_TEST_CASE(stMemoryStressTest)\n{\n\t for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t {\n\t\t\t string arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\t\t if (arg == \"--memory\" || arg == \"--all\")\n\t\t\t {\n\t\t\t\t\t auto start = chrono::steady_clock::now();\n\n\t\t\t\t\t dev::test::executeTests(\"stMemoryStressTest\", \"\/StateTests\", dev::test::doStateTests);\n\n\t\t\t\t\t auto end = chrono::steady_clock::now();\n\t\t\t\t\t auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));\n\t\t\t\t\t cnote << \"test duration: \" << duration.count() << \" milliseconds.\\n\";\n\t\t\t }\n\t }\n}\n\n BOOST_AUTO_TEST_CASE(stSolidityTest)\n {\n\t\tdev::test::executeTests(\"stSolidityTest\", \"\/StateTests\", dev::test::doStateTests);\n }\n\nBOOST_AUTO_TEST_CASE(stMemoryTest)\n{\n\t dev::test::executeTests(\"stMemoryTest\", \"\/StateTests\", dev::test::doStateTests);\n}\n\n\nBOOST_AUTO_TEST_CASE(stCreateTest)\n{\n\tfor (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)\n\t{\n\t\tstring arg = boost::unit_test::framework::master_test_suite().argv[i];\n\t\tif (arg == \"--createtest\")\n\t\t{\n\t\t\tif (boost::unit_test::framework::master_test_suite().argc <= i + 2)\n\t\t\t{\n\t\t\t\tcnote << \"usage: .\/testeth --createtest <PathToConstructor> <PathToDestiny>\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry\n\t\t\t{\n\t\t\t\tcnote << \"Populating tests...\";\n\t\t\t\tjson_spirit::mValue v;\n\t\t\t\tstring s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));\n\t\t\t\tBOOST_REQUIRE_MESSAGE(s.length() > 0, \"Content of \" + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + \" is empty.\");\n\t\t\t\tjson_spirit::read_string(s, v);\n\t\t\t\tdev::test::doStateTests(v, true);\n\t\t\t\twriteFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));\n\t\t\t}\n\t\t\tcatch (Exception const& _e)\n\t\t\t{\n\t\t\t\tBOOST_ERROR(\"Failed state test with Exception: \" << diagnostic_information(_e));\n\t\t\t}\n\t\t\tcatch (std::exception const& _e)\n\t\t\t{\n\t\t\t\tBOOST_ERROR(\"Failed state test with Exception: \" << _e.what());\n\t\t\t}\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(userDefinedFileState)\n{\n\tdev::test::userDefinedTest(\"--singletest\", dev::test::doStateTests);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <vector>\n\n#include <google\/protobuf\/compiler\/importer.h>\n#include <google\/protobuf\/dynamic_message.h>\n#include <google\/protobuf\/io\/zero_copy_stream_impl.h>\n\n#include \"perfetto\/ext\/base\/file_utils.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n#include \"perfetto\/protozero\/field.h\"\n#include \"perfetto\/protozero\/proto_decoder.h\"\n#include \"perfetto\/protozero\/proto_utils.h\"\n#include \"third_party\/pprof\/profile.pb.h\"\n\nnamespace perfetto {\nnamespace protoprofile {\nnamespace {\n\nusing protozero::proto_utils::ProtoWireType;\nusing GLine = ::perftools::profiles::Line;\nusing GMapping = ::perftools::profiles::Mapping;\nusing GLocation = ::perftools::profiles::Location;\nusing GProfile = ::perftools::profiles::Profile;\nusing GValueType = ::perftools::profiles::ValueType;\nusing GFunction = ::perftools::profiles::Function;\nusing GSample = ::perftools::profiles::Sample;\nusing ::google::protobuf::Descriptor;\nusing ::google::protobuf::DynamicMessageFactory;\nusing ::google::protobuf::FieldDescriptor;\nusing ::google::protobuf::FileDescriptor;\nusing ::google::protobuf::Message;\nusing ::google::protobuf::compiler::DiskSourceTree;\nusing ::google::protobuf::compiler::Importer;\nusing ::google::protobuf::compiler::MultiFileErrorCollector;\n\nclass MultiFileErrorCollectorImpl : public MultiFileErrorCollector {\n public:\n ~MultiFileErrorCollectorImpl() override;\n void AddError(const std::string& filename,\n int line,\n int column,\n const std::string& message) override;\n\n void AddWarning(const std::string& filename,\n int line,\n int column,\n const std::string& message) override;\n};\n\nMultiFileErrorCollectorImpl::~MultiFileErrorCollectorImpl() = default;\n\nvoid MultiFileErrorCollectorImpl::AddError(const std::string& filename,\n int line,\n int column,\n const std::string& message) {\n PERFETTO_ELOG(\"Error %s %d:%d: %s\", filename.c_str(), line, column,\n message.c_str());\n}\n\nvoid MultiFileErrorCollectorImpl::AddWarning(const std::string& filename,\n int line,\n int column,\n const std::string& message) {\n PERFETTO_ELOG(\"Error %s %d:%d: %s\", filename.c_str(), line, column,\n message.c_str());\n}\n\nclass SizeProfileComputer {\n public:\n GProfile Compute(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor);\n\n private:\n struct StackInfo {\n std::vector<size_t> samples;\n std::vector<int> locations;\n };\n\n void ComputeInner(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor);\n void Sample(size_t size);\n int InternString(const std::string& str);\n int InternLocation(const std::string& str);\n size_t GetFieldSize(const protozero::Field& f);\n\n \/\/ Convert the current stack into a string:\n \/\/ {\"Foo\", \"#bar\", \"Bar\", \"#baz\", \"int\"} -> \"Foo$#bar$Bar$#baz$int$\"\n std::string StackToKey();\n\n \/\/ The current 'stack' we're considering as we parse the protobuf.\n \/\/ For example if we're currently looking at the varint field baz which is\n \/\/ nested inside message Bar which is in turn a field named bar on the message\n \/\/ Foo. Then the stack would be: Foo, #bar, Bar, #baz, int\n \/\/ We keep track of both the field names (#bar, #baz) and the field types\n \/\/ (Foo, Bar, int) as sometimes we are intrested in which fields are big\n \/\/ and sometimes which types are big.\n std::vector<std::string> stack_;\n\n \/\/ Information about each stack seen. Keyed by a unique string for each stack.\n std::map<std::string, StackInfo> stack_info_;\n\n \/\/ Interned strings:\n std::vector<std::string> strings_;\n std::map<std::string, int> string_to_id_;\n\n \/\/ Interned 'locations', each location is a single frame of the stack.\n std::map<std::string, int> locations_;\n};\n\nsize_t SizeProfileComputer::GetFieldSize(const protozero::Field& f) {\n uint8_t buf[10];\n switch (f.type()) {\n case protozero::proto_utils::ProtoWireType::kVarInt:\n return static_cast<size_t>(\n protozero::proto_utils::WriteVarInt(f.as_uint64(), buf) - buf);\n case protozero::proto_utils::ProtoWireType::kLengthDelimited:\n return f.size();\n case protozero::proto_utils::ProtoWireType::kFixed32:\n return 4;\n case protozero::proto_utils::ProtoWireType::kFixed64:\n return 8;\n }\n}\n\nint SizeProfileComputer::InternString(const std::string& s) {\n if (string_to_id_.count(s)) {\n return string_to_id_[s];\n }\n strings_.push_back(s);\n int id = static_cast<int>(strings_.size() - 1);\n string_to_id_[s] = id;\n return id;\n}\n\nint SizeProfileComputer::InternLocation(const std::string& s) {\n if (locations_.count(s)) {\n return locations_[s];\n }\n int id = static_cast<int>(locations_.size()) + 1;\n locations_[s] = id;\n return id;\n}\n\nstd::string SizeProfileComputer::StackToKey() {\n std::string key;\n for (const std::string& part : stack_) {\n key += part;\n key += \"$\";\n }\n return key;\n}\n\nvoid SizeProfileComputer::Sample(size_t size) {\n const std::string& key = StackToKey();\n\n if (!stack_info_.count(key)) {\n StackInfo& info = stack_info_[key];\n info.locations.resize(stack_.size());\n for (size_t i = 0; i < stack_.size(); i++) {\n info.locations[i] = InternLocation(stack_[i]);\n }\n }\n\n stack_info_[key].samples.push_back(size);\n}\n\nGProfile SizeProfileComputer::Compute(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor) {\n PERFETTO_CHECK(InternString(\"\") == 0);\n ComputeInner(ptr, size, descriptor);\n GProfile profile;\n\n GValueType* sample_type;\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"protos\"));\n sample_type->set_unit(InternString(\"count\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"max_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"min_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"median\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"total_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n \/\/ For each unique stack we've seen write out the stats:\n for (auto& id_info : stack_info_) {\n StackInfo& info = id_info.second;\n\n GSample* sample = profile.add_sample();\n for (auto it = info.locations.rbegin(); it != info.locations.rend(); ++it) {\n sample->add_location_id(static_cast<uint64_t>(*it));\n }\n\n std::sort(info.samples.begin(), info.samples.end());\n size_t count = info.samples.size();\n size_t total_size = 0;\n size_t max_size = info.samples[count - 1];\n size_t min_size = info.samples[0];\n size_t median_size = info.samples[count \/ 2];\n for (size_t i = 0; i < count; ++i)\n total_size += info.samples[i];\n \/\/ These have to be in the same order as the sample types above:\n sample->add_value(static_cast<int64_t>(count));\n sample->add_value(static_cast<int64_t>(max_size));\n sample->add_value(static_cast<int64_t>(min_size));\n sample->add_value(static_cast<int64_t>(median_size));\n sample->add_value(static_cast<int64_t>(total_size));\n }\n\n \/\/ The proto profile has a two step mapping where samples are associated with\n \/\/ locations which in turn are associated to functions. We don't currently\n \/\/ distinguish them so we make a 1:1 mapping between the locations and the\n \/\/ functions:\n for (const auto& location_id : locations_) {\n GLocation* location = profile.add_location();\n location->set_id(static_cast<uint64_t>(location_id.second));\n GLine* line = location->add_line();\n line->set_function_id(static_cast<uint64_t>(location_id.second));\n }\n\n for (const auto& location_id : locations_) {\n GFunction* function = profile.add_function();\n function->set_id(static_cast<uint64_t>(location_id.second));\n function->set_name(InternString(location_id.first));\n }\n\n \/\/ Finally the string table. We intern more strings above, so this has to be\n \/\/ last.\n for (int i = 0; i < static_cast<int>(strings_.size()); i++) {\n profile.add_string_table(strings_[static_cast<size_t>(i)]);\n }\n return profile;\n}\n\nvoid SizeProfileComputer::ComputeInner(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor) {\n size_t overhead = size;\n size_t unknown = 0;\n protozero::ProtoDecoder decoder(ptr, size);\n\n stack_.push_back(descriptor->name());\n\n \/\/ Compute the size of each sub-field of this message, subtracting it\n \/\/ from overhead and possible adding it to unknown.\n for (;;) {\n if (decoder.bytes_left() == 0)\n break;\n protozero::Field field = decoder.ReadField();\n if (!field.valid()) {\n PERFETTO_ELOG(\"Field not valid (can mean field id >1000)\");\n break;\n }\n\n int id = field.id();\n ProtoWireType type = field.type();\n size_t field_size = GetFieldSize(field);\n\n overhead -= field_size;\n const FieldDescriptor* field_descriptor = descriptor->FindFieldByNumber(id);\n if (!field_descriptor) {\n unknown += field_size;\n continue;\n }\n\n stack_.push_back(\"#\" + field_descriptor->name());\n bool is_message_type =\n field_descriptor->type() == FieldDescriptor::TYPE_MESSAGE;\n if (type == ProtoWireType::kLengthDelimited && is_message_type) {\n ComputeInner(field.data(), field.size(),\n field_descriptor->message_type());\n } else {\n stack_.push_back(field_descriptor->type_name());\n Sample(field_size);\n stack_.pop_back();\n }\n stack_.pop_back();\n }\n\n if (unknown) {\n stack_.push_back(\"#:unknown:\");\n Sample(unknown);\n stack_.pop_back();\n }\n\n \/\/ Anything not blamed on a child is overhead for this message.\n Sample(overhead);\n stack_.pop_back();\n}\n\nint PrintUsage(int, const char** argv) {\n fprintf(stderr, \"Usage: %s INPUT_PATH OUTPUT_PATH\\n\", argv[0]);\n return 1;\n}\n\nint Main(int argc, const char** argv) {\n if (argc != 3)\n return PrintUsage(argc, argv);\n\n const char* input_path = argv[1];\n const char* output_path = argv[2];\n\n base::ScopedFile proto_fd = base::OpenFile(input_path, O_RDONLY);\n if (!proto_fd) {\n PERFETTO_ELOG(\"Could not open input path (%s)\", input_path);\n return 1;\n }\n\n std::string s;\n base::ReadFileDescriptor(proto_fd.get(), &s);\n\n const Descriptor* descriptor;\n DiskSourceTree dst;\n dst.MapPath(\"perfetto\", \"protos\/perfetto\");\n MultiFileErrorCollectorImpl mfe;\n Importer importer(&dst, &mfe);\n const FileDescriptor* parsed_file =\n importer.Import(\"perfetto\/trace\/trace.proto\");\n DynamicMessageFactory dmf;\n descriptor = parsed_file->message_type(0);\n\n const uint8_t* start = reinterpret_cast<const uint8_t*>(s.data());\n size_t size = s.size();\n\n if (!descriptor) {\n PERFETTO_ELOG(\"Could not parse trace.proto\");\n return 1;\n }\n\n base::ScopedFile output_fd =\n base::OpenFile(output_path, O_WRONLY | O_TRUNC | O_CREAT, 0600);\n if (!output_fd) {\n PERFETTO_ELOG(\"Could not open output path (%s)\", output_path);\n return 1;\n }\n SizeProfileComputer computer;\n GProfile profile = computer.Compute(start, size, descriptor);\n std::string out;\n profile.SerializeToString(&out);\n base::WriteAll(output_fd.get(), out.data(), out.size());\n base::FlushFile(output_fd.get());\n\n return 0;\n}\n\n} \/\/ namespace\n} \/\/ namespace protoprofile\n} \/\/ namespace perfetto\n\nint main(int argc, const char** argv) {\n return perfetto::protoprofile::Main(argc, argv);\n}\n<commit_msg>gcc build fix for protoprofile switch am: da87520b03 am: b5f047a935 am: bc22c10f80 am: 915f4f352a<commit_after>#include <algorithm>\n#include <vector>\n\n#include <google\/protobuf\/compiler\/importer.h>\n#include <google\/protobuf\/dynamic_message.h>\n#include <google\/protobuf\/io\/zero_copy_stream_impl.h>\n\n#include \"perfetto\/ext\/base\/file_utils.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n#include \"perfetto\/protozero\/field.h\"\n#include \"perfetto\/protozero\/proto_decoder.h\"\n#include \"perfetto\/protozero\/proto_utils.h\"\n#include \"third_party\/pprof\/profile.pb.h\"\n\nnamespace perfetto {\nnamespace protoprofile {\nnamespace {\n\nusing protozero::proto_utils::ProtoWireType;\nusing GLine = ::perftools::profiles::Line;\nusing GMapping = ::perftools::profiles::Mapping;\nusing GLocation = ::perftools::profiles::Location;\nusing GProfile = ::perftools::profiles::Profile;\nusing GValueType = ::perftools::profiles::ValueType;\nusing GFunction = ::perftools::profiles::Function;\nusing GSample = ::perftools::profiles::Sample;\nusing ::google::protobuf::Descriptor;\nusing ::google::protobuf::DynamicMessageFactory;\nusing ::google::protobuf::FieldDescriptor;\nusing ::google::protobuf::FileDescriptor;\nusing ::google::protobuf::Message;\nusing ::google::protobuf::compiler::DiskSourceTree;\nusing ::google::protobuf::compiler::Importer;\nusing ::google::protobuf::compiler::MultiFileErrorCollector;\n\nclass MultiFileErrorCollectorImpl : public MultiFileErrorCollector {\n public:\n ~MultiFileErrorCollectorImpl() override;\n void AddError(const std::string& filename,\n int line,\n int column,\n const std::string& message) override;\n\n void AddWarning(const std::string& filename,\n int line,\n int column,\n const std::string& message) override;\n};\n\nMultiFileErrorCollectorImpl::~MultiFileErrorCollectorImpl() = default;\n\nvoid MultiFileErrorCollectorImpl::AddError(const std::string& filename,\n int line,\n int column,\n const std::string& message) {\n PERFETTO_ELOG(\"Error %s %d:%d: %s\", filename.c_str(), line, column,\n message.c_str());\n}\n\nvoid MultiFileErrorCollectorImpl::AddWarning(const std::string& filename,\n int line,\n int column,\n const std::string& message) {\n PERFETTO_ELOG(\"Error %s %d:%d: %s\", filename.c_str(), line, column,\n message.c_str());\n}\n\nclass SizeProfileComputer {\n public:\n GProfile Compute(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor);\n\n private:\n struct StackInfo {\n std::vector<size_t> samples;\n std::vector<int> locations;\n };\n\n void ComputeInner(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor);\n void Sample(size_t size);\n int InternString(const std::string& str);\n int InternLocation(const std::string& str);\n size_t GetFieldSize(const protozero::Field& f);\n\n \/\/ Convert the current stack into a string:\n \/\/ {\"Foo\", \"#bar\", \"Bar\", \"#baz\", \"int\"} -> \"Foo$#bar$Bar$#baz$int$\"\n std::string StackToKey();\n\n \/\/ The current 'stack' we're considering as we parse the protobuf.\n \/\/ For example if we're currently looking at the varint field baz which is\n \/\/ nested inside message Bar which is in turn a field named bar on the message\n \/\/ Foo. Then the stack would be: Foo, #bar, Bar, #baz, int\n \/\/ We keep track of both the field names (#bar, #baz) and the field types\n \/\/ (Foo, Bar, int) as sometimes we are intrested in which fields are big\n \/\/ and sometimes which types are big.\n std::vector<std::string> stack_;\n\n \/\/ Information about each stack seen. Keyed by a unique string for each stack.\n std::map<std::string, StackInfo> stack_info_;\n\n \/\/ Interned strings:\n std::vector<std::string> strings_;\n std::map<std::string, int> string_to_id_;\n\n \/\/ Interned 'locations', each location is a single frame of the stack.\n std::map<std::string, int> locations_;\n};\n\nsize_t SizeProfileComputer::GetFieldSize(const protozero::Field& f) {\n uint8_t buf[10];\n switch (f.type()) {\n case protozero::proto_utils::ProtoWireType::kVarInt:\n return static_cast<size_t>(\n protozero::proto_utils::WriteVarInt(f.as_uint64(), buf) - buf);\n case protozero::proto_utils::ProtoWireType::kLengthDelimited:\n return f.size();\n case protozero::proto_utils::ProtoWireType::kFixed32:\n return 4;\n case protozero::proto_utils::ProtoWireType::kFixed64:\n return 8;\n }\n PERFETTO_FATAL(\"unexpected field type\"); \/\/ for gcc\n}\n\nint SizeProfileComputer::InternString(const std::string& s) {\n if (string_to_id_.count(s)) {\n return string_to_id_[s];\n }\n strings_.push_back(s);\n int id = static_cast<int>(strings_.size() - 1);\n string_to_id_[s] = id;\n return id;\n}\n\nint SizeProfileComputer::InternLocation(const std::string& s) {\n if (locations_.count(s)) {\n return locations_[s];\n }\n int id = static_cast<int>(locations_.size()) + 1;\n locations_[s] = id;\n return id;\n}\n\nstd::string SizeProfileComputer::StackToKey() {\n std::string key;\n for (const std::string& part : stack_) {\n key += part;\n key += \"$\";\n }\n return key;\n}\n\nvoid SizeProfileComputer::Sample(size_t size) {\n const std::string& key = StackToKey();\n\n if (!stack_info_.count(key)) {\n StackInfo& info = stack_info_[key];\n info.locations.resize(stack_.size());\n for (size_t i = 0; i < stack_.size(); i++) {\n info.locations[i] = InternLocation(stack_[i]);\n }\n }\n\n stack_info_[key].samples.push_back(size);\n}\n\nGProfile SizeProfileComputer::Compute(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor) {\n PERFETTO_CHECK(InternString(\"\") == 0);\n ComputeInner(ptr, size, descriptor);\n GProfile profile;\n\n GValueType* sample_type;\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"protos\"));\n sample_type->set_unit(InternString(\"count\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"max_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"min_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"median\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n sample_type = profile.add_sample_type();\n sample_type->set_type(InternString(\"total_size\"));\n sample_type->set_unit(InternString(\"bytes\"));\n\n \/\/ For each unique stack we've seen write out the stats:\n for (auto& id_info : stack_info_) {\n StackInfo& info = id_info.second;\n\n GSample* sample = profile.add_sample();\n for (auto it = info.locations.rbegin(); it != info.locations.rend(); ++it) {\n sample->add_location_id(static_cast<uint64_t>(*it));\n }\n\n std::sort(info.samples.begin(), info.samples.end());\n size_t count = info.samples.size();\n size_t total_size = 0;\n size_t max_size = info.samples[count - 1];\n size_t min_size = info.samples[0];\n size_t median_size = info.samples[count \/ 2];\n for (size_t i = 0; i < count; ++i)\n total_size += info.samples[i];\n \/\/ These have to be in the same order as the sample types above:\n sample->add_value(static_cast<int64_t>(count));\n sample->add_value(static_cast<int64_t>(max_size));\n sample->add_value(static_cast<int64_t>(min_size));\n sample->add_value(static_cast<int64_t>(median_size));\n sample->add_value(static_cast<int64_t>(total_size));\n }\n\n \/\/ The proto profile has a two step mapping where samples are associated with\n \/\/ locations which in turn are associated to functions. We don't currently\n \/\/ distinguish them so we make a 1:1 mapping between the locations and the\n \/\/ functions:\n for (const auto& location_id : locations_) {\n GLocation* location = profile.add_location();\n location->set_id(static_cast<uint64_t>(location_id.second));\n GLine* line = location->add_line();\n line->set_function_id(static_cast<uint64_t>(location_id.second));\n }\n\n for (const auto& location_id : locations_) {\n GFunction* function = profile.add_function();\n function->set_id(static_cast<uint64_t>(location_id.second));\n function->set_name(InternString(location_id.first));\n }\n\n \/\/ Finally the string table. We intern more strings above, so this has to be\n \/\/ last.\n for (int i = 0; i < static_cast<int>(strings_.size()); i++) {\n profile.add_string_table(strings_[static_cast<size_t>(i)]);\n }\n return profile;\n}\n\nvoid SizeProfileComputer::ComputeInner(const uint8_t* ptr,\n size_t size,\n const Descriptor* descriptor) {\n size_t overhead = size;\n size_t unknown = 0;\n protozero::ProtoDecoder decoder(ptr, size);\n\n stack_.push_back(descriptor->name());\n\n \/\/ Compute the size of each sub-field of this message, subtracting it\n \/\/ from overhead and possible adding it to unknown.\n for (;;) {\n if (decoder.bytes_left() == 0)\n break;\n protozero::Field field = decoder.ReadField();\n if (!field.valid()) {\n PERFETTO_ELOG(\"Field not valid (can mean field id >1000)\");\n break;\n }\n\n int id = field.id();\n ProtoWireType type = field.type();\n size_t field_size = GetFieldSize(field);\n\n overhead -= field_size;\n const FieldDescriptor* field_descriptor = descriptor->FindFieldByNumber(id);\n if (!field_descriptor) {\n unknown += field_size;\n continue;\n }\n\n stack_.push_back(\"#\" + field_descriptor->name());\n bool is_message_type =\n field_descriptor->type() == FieldDescriptor::TYPE_MESSAGE;\n if (type == ProtoWireType::kLengthDelimited && is_message_type) {\n ComputeInner(field.data(), field.size(),\n field_descriptor->message_type());\n } else {\n stack_.push_back(field_descriptor->type_name());\n Sample(field_size);\n stack_.pop_back();\n }\n stack_.pop_back();\n }\n\n if (unknown) {\n stack_.push_back(\"#:unknown:\");\n Sample(unknown);\n stack_.pop_back();\n }\n\n \/\/ Anything not blamed on a child is overhead for this message.\n Sample(overhead);\n stack_.pop_back();\n}\n\nint PrintUsage(int, const char** argv) {\n fprintf(stderr, \"Usage: %s INPUT_PATH OUTPUT_PATH\\n\", argv[0]);\n return 1;\n}\n\nint Main(int argc, const char** argv) {\n if (argc != 3)\n return PrintUsage(argc, argv);\n\n const char* input_path = argv[1];\n const char* output_path = argv[2];\n\n base::ScopedFile proto_fd = base::OpenFile(input_path, O_RDONLY);\n if (!proto_fd) {\n PERFETTO_ELOG(\"Could not open input path (%s)\", input_path);\n return 1;\n }\n\n std::string s;\n base::ReadFileDescriptor(proto_fd.get(), &s);\n\n const Descriptor* descriptor;\n DiskSourceTree dst;\n dst.MapPath(\"perfetto\", \"protos\/perfetto\");\n MultiFileErrorCollectorImpl mfe;\n Importer importer(&dst, &mfe);\n const FileDescriptor* parsed_file =\n importer.Import(\"perfetto\/trace\/trace.proto\");\n DynamicMessageFactory dmf;\n descriptor = parsed_file->message_type(0);\n\n const uint8_t* start = reinterpret_cast<const uint8_t*>(s.data());\n size_t size = s.size();\n\n if (!descriptor) {\n PERFETTO_ELOG(\"Could not parse trace.proto\");\n return 1;\n }\n\n base::ScopedFile output_fd =\n base::OpenFile(output_path, O_WRONLY | O_TRUNC | O_CREAT, 0600);\n if (!output_fd) {\n PERFETTO_ELOG(\"Could not open output path (%s)\", output_path);\n return 1;\n }\n SizeProfileComputer computer;\n GProfile profile = computer.Compute(start, size, descriptor);\n std::string out;\n profile.SerializeToString(&out);\n base::WriteAll(output_fd.get(), out.data(), out.size());\n base::FlushFile(output_fd.get());\n\n return 0;\n}\n\n} \/\/ namespace\n} \/\/ namespace protoprofile\n} \/\/ namespace perfetto\n\nint main(int argc, const char** argv) {\n return perfetto::protoprofile::Main(argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ hello.cc\n\n#include <node.h>\n#include \"sql\/api.h\"\n#include \"string\"\n#include <unordered_set>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\nusing v8::Number;\nusing v8::Array;\n\nusing namespace std;\n\nvoid Exchange(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n \n if (args.Length() != 1) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string id = std::string(*param1);\n \n cout<<\"Hello World!\"<<endl;\n\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n \n unordered_map<std::string, double> *rows = db->selectExchangeWithID(id);\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"id\"),\n\t String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n\t Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n \nvoid Table(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \n if (args.Length() != 1) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string tableName = std::string(*param1);\n \n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n \n unordered_map<std::string, double> *rows = db->selectAllFromTable(tableName);\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"id\"),\n\t String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n\t Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\nvoid TickerData(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \n if (args.Length() != 0) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n \n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n\n unordered_set<std::string> majorTickers ({\n \"USDCAD=X\", \"EURJPY=X\"\n \"EURUSD=X\", \"EURCHF=X\",\n \"USDCHF=X\", \"EURGBP=X\",\n \"GBPUSD=X\", \"AUDCAD=X\",\n \"NZDUSD=X\", \"GBPCHF=X\",\n \"AUDUSD=X\", \"GBPJPY=X\",\n \"USDJPY=X\", \"CHFJPY=X\",\n \"EURCAD=X\", \"AUDJPY=X\",\n \"EURAUD=X\", \"AUDNZD=X\"\n });\n\n \n unordered_map<std::string, double> *rows = db->selectAllTickerData(); \/\/Get data\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate); \/\/JSON results Array\n \n \/\/Loop through C++ hashmap\n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Add to return array if it is a major ticker\n if (majorTickers.find(itr->first) != majorTickers.end()){\n\n \/\/ Creates a new JSON Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"ticker\"),\n String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"percentChange\"),\n Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n\n i++;\n }\n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n\nvoid ChartData(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \/\/Make sure 2 arguments. Cast to string\n if (args.Length() != 2) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string ticker = std::string(*param1);\n \n if (!args[1]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param2(args[1]->ToString());\n std::string timeframe = std::string(*param2);\n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n string interval = \"day\";\n long startDate = 1450000000;\n long endDate = 1490064000;\n vector<API::chart_info> *rows = db->selectHistoricalTickerData(ticker, interval,startDate,endDate); \/\/Database query\n \/\/unordered_map<std::string, double> *rows = db->selectHistoricalTickerData(ticker, interval); \/\/Database query\n\/\/TODO change data structure to array of struct\n\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n\n for(vector<API::chart_info>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout << itr->timestamp << \"\\t\" << itr->ticker << \"\\t\" << itr->high << \"\\t\" << itr->volume << \"\\t\"\n << itr->open << \"\\t\" << itr->low << \"\\t\" << itr->close << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"date\"),\n Number::New(isolate, itr->timestamp));\n obj->Set(String::NewFromUtf8(isolate, \"ticker\"),\n String::NewFromUtf8(isolate, itr->ticker.data()));\n obj->Set(String::NewFromUtf8(isolate, \"high\"),\n Number::New(isolate, itr->high));\n obj->Set(String::NewFromUtf8(isolate, \"volume\"),\n Number::New(isolate, itr->volume));\n obj->Set(String::NewFromUtf8(isolate, \"open\"),\n Number::New(isolate, itr->open));\n obj->Set(String::NewFromUtf8(isolate, \"low\"),\n Number::New(isolate, itr->low));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n Number::New(isolate, itr->close));\n \n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n\nvoid init(Local<Object> exports) {\n NODE_SET_METHOD(exports, \"exchange\", Exchange);\n NODE_SET_METHOD(exports, \"table\", Table);\n NODE_SET_METHOD(exports, \"tickerData\", TickerData);\n NODE_SET_METHOD(exports, \"chartData\", ChartData);\n}\n\nNODE_MODULE(addon, init)\n\n} \/\/ namespace demo\n<commit_msg>query arb<commit_after>\/\/ hello.cc\n\n#include <node.h>\n#include \"sql\/api.h\"\n#include \"string\"\n#include <unordered_set>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\nusing v8::Number;\nusing v8::Array;\n\nusing namespace std;\n\nvoid Exchange(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n \n if (args.Length() != 1) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string id = std::string(*param1);\n \n cout<<\"Hello World!\"<<endl;\n\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n \n unordered_map<std::string, double> *rows = db->selectExchangeWithID(id);\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"id\"),\n\t String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n\t Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n \nvoid Table(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \n if (args.Length() != 1) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string tableName = std::string(*param1);\n \n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n \n unordered_map<std::string, double> *rows = db->selectAllFromTable(tableName);\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"id\"),\n\t String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n\t Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\nvoid TickerData(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \n if (args.Length() != 0) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n \n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n\n unordered_set<std::string> majorTickers ({\n \"USDCAD=X\", \"EURJPY=X\"\n \"EURUSD=X\", \"EURCHF=X\",\n \"USDCHF=X\", \"EURGBP=X\",\n \"GBPUSD=X\", \"AUDCAD=X\",\n \"NZDUSD=X\", \"GBPCHF=X\",\n \"AUDUSD=X\", \"GBPJPY=X\",\n \"USDJPY=X\", \"CHFJPY=X\",\n \"EURCAD=X\", \"AUDJPY=X\",\n \"EURAUD=X\", \"AUDNZD=X\"\n });\n\n \n unordered_map<std::string, double> *rows = db->selectAllTickerData(); \/\/Get data\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate); \/\/JSON results Array\n \n \/\/Loop through C++ hashmap\n for(unordered_map<std::string, double>::iterator itr = rows->begin(); itr != rows->end(); itr++){\n cout<< itr->first << \"\\t\" << itr->second << endl;\n\n \/\/ Add to return array if it is a major ticker\n if (majorTickers.find(itr->first) != majorTickers.end()){\n\n \/\/ Creates a new JSON Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"ticker\"),\n String::NewFromUtf8(isolate, itr->first.data()));\n obj->Set(String::NewFromUtf8(isolate, \"percentChange\"),\n Number::New(isolate, itr->second));\n\n result->Set(i, obj); \n\n i++;\n }\n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n\nvoid ChartData(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \/\/Make sure 2 arguments. Cast to string\n if (args.Length() != 2) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string ticker = std::string(*param1);\n \n if (!args[1]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param2(args[1]->ToString());\n std::string timeframe = std::string(*param2);\n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n string interval = \"day\";\n long startDate = 1450000000;\n long endDate = 1490064000;\n vector<API::chart_info> *rows = db->selectHistoricalTickerData(ticker, interval,startDate,endDate); \/\/Database query\n \/\/unordered_map<std::string, double> *rows = db->selectHistoricalTickerData(ticker, interval); \/\/Database query\n\/\/TODO change data structure to array of struct\n\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n\n for(vector<API::chart_info>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout << itr->timestamp << \"\\t\" << itr->ticker << \"\\t\" << itr->high << \"\\t\" << itr->volume << \"\\t\"\n << itr->open << \"\\t\" << itr->low << \"\\t\" << itr->close << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"date\"),\n Number::New(isolate, itr->timestamp));\n obj->Set(String::NewFromUtf8(isolate, \"ticker\"),\n String::NewFromUtf8(isolate, itr->ticker.data()));\n obj->Set(String::NewFromUtf8(isolate, \"high\"),\n Number::New(isolate, itr->high));\n obj->Set(String::NewFromUtf8(isolate, \"volume\"),\n Number::New(isolate, itr->volume));\n obj->Set(String::NewFromUtf8(isolate, \"open\"),\n Number::New(isolate, itr->open));\n obj->Set(String::NewFromUtf8(isolate, \"low\"),\n Number::New(isolate, itr->low));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n Number::New(isolate, itr->close));\n \n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n\n\nvoid ArbitrageData(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n cout<<\"Number of args: \"<<args.Length()<<endl;\n\n \/\/Make sure 6 arguments. Cast to string\n if (args.Length() != 6) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong number of arguments\"));\n return;\n }\n\n if (!args[0]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param1(args[0]->ToString());\n std::string startCurr = std::string(*param1);\n \n if (!args[1]->IsString()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param2(args[1]->ToString());\n std::string endCurr = std::string(*param2);\n\n if (!args[2]->IsDouble()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param3(args[2]->ToString());\n std::string startValue = std::string(*param3);\n\n if (!args[3]->IsDouble()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param4(args[3]->ToString());\n std::string endValue = std::string(*param4);\n\n if (!args[4]->IsArray()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n std::vector<std:string> currenciesToExclude = new std::vector<std::string>();\n for(int i=0; i<args[4].length(); i++) {\n currenciesToExclude.push_back(args[4][i]->ToString());\n }\n\n if (!args[5]->IsInteger()) {\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Wrong arguments\"));\n return;\n }\n\n v8::String::Utf8Value param6(args[5]->ToString());\n std::string maxNumberExchanges = std::string(*param6);\n \n \/\/TODO: move this to init\n API *db = new API();\n int retVal = db->connect();\n if(retVal != 0){\n cout<<\"db.connect() failed with exit code \"<<retVal<<endl;\n isolate->ThrowException(v8::String::NewFromUtf8(isolate, \"Failed to connect to database\"));\n return;\n }\n\n string interval = \"day\";\n long startDate = 1450000000;\n long endDate = 1490064000;\n vector<API::chart_info> *rows = db->selectHistoricalTickerData(ticker, interval,startDate,endDate); \/\/Database query\n \/\/unordered_map<std::string, double> *rows = db->selectHistoricalTickerData(ticker, interval); \/\/Database query\n\/\/TODO change data structure to array of struct\n\n\n int i = 0;\n\n Local<Array> result = Array::New(isolate);\n \n\n for(vector<API::chart_info>::iterator itr = rows->begin(); itr != rows->end(); itr++, i++){\n cout << itr->timestamp << \"\\t\" << itr->ticker << \"\\t\" << itr->high << \"\\t\" << itr->volume << \"\\t\"\n << itr->open << \"\\t\" << itr->low << \"\\t\" << itr->close << endl;\n\n \/\/ Creates a new Object on the V8 heap\n Local<Object> obj = Object::New(isolate);\n\n \/\/Can call a pack function here to be cleaner once more data\n \/\/ Transfers the data from result, to obj (see below)\n obj->Set(String::NewFromUtf8(isolate, \"date\"),\n Number::New(isolate, itr->timestamp));\n obj->Set(String::NewFromUtf8(isolate, \"ticker\"),\n String::NewFromUtf8(isolate, itr->ticker.data()));\n obj->Set(String::NewFromUtf8(isolate, \"high\"),\n Number::New(isolate, itr->high));\n obj->Set(String::NewFromUtf8(isolate, \"volume\"),\n Number::New(isolate, itr->volume));\n obj->Set(String::NewFromUtf8(isolate, \"open\"),\n Number::New(isolate, itr->open));\n obj->Set(String::NewFromUtf8(isolate, \"low\"),\n Number::New(isolate, itr->low));\n obj->Set(String::NewFromUtf8(isolate, \"close\"),\n Number::New(isolate, itr->close));\n \n\n result->Set(i, obj); \n }\n\n args.GetReturnValue().Set(result);\n \/\/args.GetReturnValue().Set(String::NewFromUtf8(isolate, \"world\"));\n \n delete db;\n}\n\n\n\nvoid init(Local<Object> exports) {\n NODE_SET_METHOD(exports, \"exchange\", Exchange);\n NODE_SET_METHOD(exports, \"table\", Table);\n NODE_SET_METHOD(exports, \"tickerData\", TickerData);\n NODE_SET_METHOD(exports, \"chartData\", ChartData);\n}\n\nNODE_MODULE(addon, init)\n\n} \/\/ namespace demo\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_FUNCTIONS_HH\n#define DUNE_STUFF_FUNCTIONS_HH\n\n#include <string>\n#include <vector>\n\n#include <dune\/common\/parametertree.hh>\n#include <dune\/common\/exceptions.hh>\n\n#include <dune\/stuff\/common\/color.hh>\n\n#include \"functions\/interfaces.hh\"\n\/\/#include \"functions\/checkerboard.hh\"\n#include \"functions\/expression.hh\"\n\/\/#include \"functions\/spe10.hh\"\n#include \"functions\/constant.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\n\/**\n * \\brief This is a way to create new functions fulfilling the FunctionInterface using their string identifier.\n *\n * \\attention This class will not compile for all dimensions. The errors should give you a hint which specializations\n * are needed below.\n *\/\ntemplate< class E, class D, int d, class R, int rR, int rC = 1 >\nclass Functions\n{\npublic:\n static std::vector< std::string > available()\n {\n return {\n Function::Constant< E, D, d, R, rR, rC >::static_id()\n , Function::Expression< E, D, d, R, rR, rC >::static_id()\n };\n } \/\/ ... available(...)\n\n static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::defaultSettings();\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... defaultSettings(...)\n\n static LocalizableFunctionInterface< E, D, d, R, rR, rC >* create(const std::string type = available()[0],\n const Dune::ParameterTree settings = defaultSettings())\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::create(settings);\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... create(...)\n}; \/\/ class Functions\n\n\ntemplate< class E, class D, class R >\nclass Functions< E, D, 1, R, 1, 1 >\n{\n static const unsigned int d = 1;\n static const unsigned int rR = 1;\n static const unsigned int rC = 1;\npublic:\n static std::vector< std::string > available()\n {\n return {\n Function::Constant< E, D, d, R, rR, rC >::static_id()\n , Function::Expression< E, D, d, R, rR, rC >::static_id()\n };\n } \/\/ ... available(...)\n\n static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::defaultSettings();\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... defaultSettings(...)\n\n static LocalizableFunctionInterface< E, D, d, R, rR, rC >* create(const std::string type = available()[0],\n const Dune::ParameterTree settings = defaultSettings())\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::create(settings);\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... create(...)\n}; \/\/ class Functions< ..., 1, ..., 1, 1 >\n\n\n\/\/template< class D, class R >\n\/\/class Functions< D, 2, R, 1, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, 2, R, 1, 1 >::static_id()\n\/\/ , FunctionCheckerboard< D, 2, R, 1, 1 >::static_id()\n\/\/ , FunctionConstant< D, 2, R, 1, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionExpression< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionConstant< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, 2, R, 1, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 2, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionExpression< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 2, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionConstant< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 2, R, 1, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, 2, R, 1, 1 >\n\n\n\/\/template< class D, class R >\n\/\/class Functions< D, 3, R, 1, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, 3, R, 1, 1 >::static_id()\n\/\/ , FunctionCheckerboard< D, 3, R, 1, 1 >::static_id()\n\/\/ , FunctionConstant< D, 3, R, 1, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionExpression< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionConstant< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, 3, R, 1, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 3, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionExpression< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 3, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionConstant< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 3, R, 1, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, 3, R, 1, 1 >\n\n\n\/\/template< class D, int d, class R, int r >\n\/\/class Functions< D, d, R, r, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, d, R, r, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionExpression< D, d, R, r, 1 >::static_id())\n\/\/ return FunctionExpression< D, d, R, r, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, d, R, r, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionExpression< D, d, R, r, 1 >::static_id())\n\/\/ return FunctionExpression< D, d, R, r, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, d, R, r, 1 >\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_HH\n<commit_msg>[functions] readdded Checkerboard<commit_after>#ifndef DUNE_STUFF_FUNCTIONS_HH\n#define DUNE_STUFF_FUNCTIONS_HH\n\n#include <string>\n#include <vector>\n\n#include <dune\/common\/parametertree.hh>\n#include <dune\/common\/exceptions.hh>\n\n#include <dune\/stuff\/common\/color.hh>\n\n#include \"functions\/interfaces.hh\"\n#include \"functions\/checkerboard.hh\"\n#include \"functions\/expression.hh\"\n\/\/#include \"functions\/spe10.hh\"\n#include \"functions\/constant.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\n\/**\n * \\brief This is a way to create new functions fulfilling the FunctionInterface using their string identifier.\n *\n * \\attention This class will not compile for all dimensions. The errors should give you a hint which specializations\n * are needed below.\n *\/\ntemplate< class E, class D, int d, class R, int rR, int rC = 1 >\nclass Functions\n{\npublic:\n static std::vector< std::string > available()\n {\n return {\n Function::Constant< E, D, d, R, rR, rC >::static_id()\n , Function::Expression< E, D, d, R, rR, rC >::static_id()\n , Function::Checkerboard< E, D, d, R, rR, rC >::static_id()\n };\n } \/\/ ... available(...)\n\n static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Checkerboard< E, D, d, R, rR, rC >::static_id())\n return Function::Checkerboard< E, D, d, R, rR, rC >::defaultSettings();\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... defaultSettings(...)\n\n static LocalizableFunctionInterface< E, D, d, R, rR, rC >* create(const std::string type = available()[0],\n const Dune::ParameterTree settings = defaultSettings())\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Checkerboard< E, D, d, R, rR, rC >::static_id())\n return Function::Checkerboard< E, D, d, R, rR, rC >::create(settings);\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... create(...)\n}; \/\/ class Functions\n\n\ntemplate< class E, class D, class R >\nclass Functions< E, D, 1, R, 1, 1 >\n{\n static const unsigned int d = 1;\n static const unsigned int rR = 1;\n static const unsigned int rC = 1;\npublic:\n static std::vector< std::string > available()\n {\n return {\n Function::Constant< E, D, d, R, rR, rC >::static_id()\n , Function::Expression< E, D, d, R, rR, rC >::static_id()\n , Function::Checkerboard< E, D, d, R, rR, rC >::static_id()\n };\n } \/\/ ... available(...)\n\n static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::defaultSettings();\n else if (type == Function::Checkerboard< E, D, d, R, rR, rC >::static_id())\n return Function::Checkerboard< E, D, d, R, rR, rC >::defaultSettings();\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... defaultSettings(...)\n\n static LocalizableFunctionInterface< E, D, d, R, rR, rC >* create(const std::string type = available()[0],\n const Dune::ParameterTree settings = defaultSettings())\n {\n if (type == Function::Constant< E, D, d, R, rR, rC >::static_id())\n return Function::Constant< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Expression< E, D, d, R, rR, rC >::static_id())\n return Function::Expression< E, D, d, R, rR, rC >::create(settings);\n else if (type == Function::Checkerboard< E, D, d, R, rR, rC >::static_id())\n return Function::Checkerboard< E, D, d, R, rR, rC >::create(settings);\n else\n DUNE_THROW(Dune::RangeError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" unknown function '\" << type << \"' requested!\");\n } \/\/ ... create(...)\n}; \/\/ class Functions< ..., 1, ..., 1, 1 >\n\n\n\/\/template< class D, class R >\n\/\/class Functions< D, 2, R, 1, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, 2, R, 1, 1 >::static_id()\n\/\/ , FunctionCheckerboard< D, 2, R, 1, 1 >::static_id()\n\/\/ , FunctionConstant< D, 2, R, 1, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionExpression< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionConstant< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 2, R, 1, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, 2, R, 1, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 2, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionExpression< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 2, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionConstant< D, 2, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 2, R, 1, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, 2, R, 1, 1 >\n\n\n\/\/template< class D, class R >\n\/\/class Functions< D, 3, R, 1, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, 3, R, 1, 1 >::static_id()\n\/\/ , FunctionCheckerboard< D, 3, R, 1, 1 >::static_id()\n\/\/ , FunctionConstant< D, 3, R, 1, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionExpression< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else if (type == FunctionConstant< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 3, R, 1, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, 3, R, 1, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionCheckerboard< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionCheckerboard< D, 3, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionExpression< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionExpression< D, 3, R, 1, 1 >::create(settings);\n\/\/ else if (type == FunctionConstant< D, 3, R, 1, 1 >::static_id())\n\/\/ return FunctionConstant< D, 3, R, 1, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, 3, R, 1, 1 >\n\n\n\/\/template< class D, int d, class R, int r >\n\/\/class Functions< D, d, R, r, 1 >\n\/\/{\n\/\/public:\n\/\/ static std::vector< std::string > available()\n\/\/ {\n\/\/ return {\n\/\/ FunctionExpression< D, d, R, r, 1 >::static_id()\n\/\/ };\n\/\/ } \/\/ ... available(...)\n\n\/\/ static Dune::ParameterTree defaultSettings(const std::string type = available()[0])\n\/\/ {\n\/\/ if (type == FunctionExpression< D, d, R, r, 1 >::static_id())\n\/\/ return FunctionExpression< D, d, R, r, 1 >::defaultSettings();\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... defaultSettings(...)\n\n\/\/ static FunctionInterface< D, d, R, r, 1 >* create(const std::string type = available()[0],\n\/\/ const Dune::ParameterTree settings = defaultSettings())\n\/\/ {\n\/\/ if (type == FunctionExpression< D, d, R, r, 1 >::static_id())\n\/\/ return FunctionExpression< D, d, R, r, 1 >::create(settings);\n\/\/ else\n\/\/ DUNE_THROW(Dune::RangeError,\n\/\/ \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n\/\/ << \" unknown function '\" << type << \"' requested!\");\n\/\/ } \/\/ ... create(...)\n\/\/}; \/\/ class Functions< D, d, R, r, 1 >\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ ------------------------------------------------------------------------\n\/\/ eca-curses.cpp: Curses implementation of the console user interface.\n\/\/ Copyright (C) 1999-2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <iostream>\n#include <map>\n#include <string>\n\n#if defined ECA_USE_NCURSES || defined ECA_USE_TERMCAP\n\n#ifdef ECA_HAVE_NCURSES_CURSES_H\n#include <ncurses\/curses.h>\n#include <ncurses\/term.h>\n#else\n#include <curses.h>\n#include <term.h>\n#endif\n\n#define READLINE_LIBRARY\n#include <readline.h>\n#include <history.h>\n\n#include <eca-iamode-parser.h>\n#include <eca-version.h>\n#include <kvu_utils.h> \/* kvu_string_search_and_replace() *\/\n\n#include \"eca-curses.h\"\n\n#if RL_READLINE_VERSION >= 0x0402\nstatic char** ecasound_completion (const char *text, int start, int end);\nstatic char* ecasound_command_generator (const char* text, int state);\n#else \nstatic char** ecasound_completion (char *text, int start, int end);\nstatic char* ecasound_command_generator (char* text, int state);\n#endif\n\nusing namespace std;\n\nECA_CURSES::ECA_CURSES(void)\n{\n init_readline_support();\n}\n\nECA_CURSES::~ECA_CURSES(void)\n{\n}\n\nvoid ECA_CURSES::print(const std::string& msg)\n{\n cout << msg << endl;\n}\n\nvoid ECA_CURSES::print_banner(void)\n{\n cout << \"****************************************************************************\\n\";\n cout << \"*\";\n setupterm((char *)0, 1, (int *)0);\n putp(tigetstr(\"bold\"));\n cout << \" ecasound v\" \n << ecasound_library_version\n << \" (C) 1997-2002 Kai Vehmanen \";\n putp(tigetstr(\"sgr0\"));\n cout << \"\\n\";\n cout << \"****************************************************************************\\n\";\n}\n\nvoid ECA_CURSES::read_command(const string& prompt)\n{\n last_cmdchar_repp = readline(const_cast<char*>(prompt.c_str()));\n if (last_cmdchar_repp != 0) {\n add_history(last_cmdchar_repp);\n last_cmd_rep = last_cmdchar_repp;\n free(last_cmdchar_repp);\n }\n}\n\nconst string& ECA_CURSES::last_command(void) const\n{\n return(last_cmd_rep);\n}\n\nvoid ECA_CURSES::init_readline_support(void)\n{\n \/* for conditional parsing of ~\/.inputrc file. *\/\n rl_readline_name = \"ecasound\";\n\n \/* we want to attempt completion first *\/\n#if RL_READLINE_VERSION >= 0x0402\n rl_attempted_completion_function = (rl_completion_func_t*)ecasound_completion;\n#else\n rl_attempted_completion_function = (CPPFunction *)ecasound_completion;\n#endif\n}\n\n\/* **************************************************************** *\/\n\/* *\/\n\/* Interface to Readline Completion *\/\n\/* *\/\n\/* **************************************************************** *\/\n\nchar *command_generator ();\nchar **fileman_completion ();\n\n\/**\n * Attempt to complete on the contents of TEXT. START and END bound the\n * region of rl_line_buffer that contains the word to complete. TEXT is\n * the word to complete. We can use the entire contents of rl_line_buffer\n * in case we want to do some simple parsing. Return the array of matches,\n * or NULL if there aren't any.\n *\/\n#if RL_READLINE_VERSION >= 0x0402\nchar** ecasound_completion (const char *text, int start, int end)\n#else\nchar** ecasound_completion (char *text, int start, int end)\n#endif\n{\n char **matches;\n matches = (char **)NULL;\n\n \/* complete only the first command, otherwise complete files in \n * the current directory *\/\n if (start == 0) {\n#if RL_READLINE_VERSION >= 0x0402\n matches = rl_completion_matches (text, (rl_compentry_func_t *)ecasound_command_generator);\n#else\n matches = completion_matches (text, (CPFunction *)ecasound_command_generator);\n#endif\n }\n return (matches);\n}\n\n\/**\n * Generator function for command completion. STATE lets us know whether\n * to start from scratch; without any state (i.e. STATE == 0), then we\n * start at the top of the list.\n *\/\n#if RL_READLINE_VERSION >= 0x0402\nchar* ecasound_command_generator (const char* text, int state)\n#else\nchar* ecasound_command_generator (char* text, int state)\n#endif\n{\n static int list_index, len;\n static const map<string,int>& map_ref = ECA_IAMODE_PARSER::registered_commands();\n static map<string,int>::const_iterator p;\n static string cmd;\n\n \/* If this is a new word to complete, initialize now. This includes\n * saving the length of TEXT for efficiency, and initializing the index\n * variable to 0\n *\/\n if (!state) {\n list_index = 0;\n p = map_ref.begin();\n len = strlen (text);\n }\n\n \/* Return the next name which partially matches from the command list *\/\n while (p != map_ref.end()) {\n cmd = p->first;\n list_index++;\n ++p;\n if (p != map_ref.end()) {\n\tstring hyphenstr = kvu_string_search_and_replace(text, '_', '-');\n\tif (strncmp(hyphenstr.c_str(), cmd.c_str(), len) == 0) {\n\t return(strdup(cmd.c_str()));\n\t}\n }\n }\n return ((char *)0);\n}\n\n#else\n\nvoid ECA_CURSES::print(const std::string& msg) {}\nvoid ECA_CURSES::print_banner(void) {}\nvoid ECA_CURSES::read_command(const string& promp) {}\nconst string& ECA_CURSES::last_command(void) const { static std::string empty; return(empty); }\nvoid ECA_CURSES::init_readline_support(void) {}\n\n#endif \/* defined ECA_USE_NCURSES || defined ECA_USE_TERMCAP *\/\n<commit_msg>More fixes for Solaris Workshop compiler.<commit_after>\/\/ ------------------------------------------------------------------------\n\/\/ eca-curses.cpp: Curses implementation of the console user interface.\n\/\/ Copyright (C) 1999-2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <iostream>\n#include <map>\n#include <string>\n\n#if defined ECA_USE_NCURSES || defined ECA_USE_TERMCAP\n\n#ifdef ECA_HAVE_NCURSES_CURSES_H\n#include <ncurses\/curses.h>\n#include <ncurses\/term.h>\n#else\n#include <curses.h>\n#include <term.h>\n#endif\n\n#define READLINE_LIBRARY\n#include <readline.h>\n#include <history.h>\n\n#include <eca-iamode-parser.h>\n#include <eca-version.h>\n#include <kvu_utils.h> \/* kvu_string_search_and_replace() *\/\n\n#include \"eca-curses.h\"\n\n#if RL_READLINE_VERSION >= 0x0402\nstatic char** ecasound_completion (const char *text, int start, int end);\nstatic char* ecasound_command_generator (const char* text, int state);\n#else \nstatic char** ecasound_completion (char *text, int start, int end);\nstatic char* ecasound_command_generator (char* text, int state);\n#endif\n\nusing namespace std;\n\nECA_CURSES::ECA_CURSES(void)\n{\n init_readline_support();\n}\n\nECA_CURSES::~ECA_CURSES(void)\n{\n}\n\nvoid ECA_CURSES::print(const std::string& msg)\n{\n cout << msg << endl;\n}\n\nvoid ECA_CURSES::print_banner(void)\n{\n cout << \"****************************************************************************\\n\";\n cout << \"*\";\n setupterm((char *)0, 1, (int *)0);\n putp(tigetstr(\"bold\"));\n cout << \" ecasound v\" \n << ecasound_library_version\n << \" (C) 1997-2002 Kai Vehmanen \";\n putp(tigetstr(\"sgr0\"));\n cout << \"\\n\";\n cout << \"****************************************************************************\\n\";\n}\n\nvoid ECA_CURSES::read_command(const string& prompt)\n{\n last_cmdchar_repp = readline(const_cast<char*>(prompt.c_str()));\n if (last_cmdchar_repp != 0) {\n add_history(last_cmdchar_repp);\n last_cmd_rep = last_cmdchar_repp;\n free(last_cmdchar_repp);\n }\n}\n\nconst string& ECA_CURSES::last_command(void) const\n{\n return(last_cmd_rep);\n}\n\nvoid ECA_CURSES::init_readline_support(void)\n{\n \/* for conditional parsing of ~\/.inputrc file. *\/\n rl_readline_name = \"ecasound\";\n\n \/* we want to attempt completion first *\/\n#if RL_READLINE_VERSION >= 0x0402\n rl_attempted_completion_function = (rl_completion_func_t*)ecasound_completion;\n#else\n rl_attempted_completion_function = (CPPFunction *)ecasound_completion;\n#endif\n}\n\n\/* **************************************************************** *\/\n\/* *\/\n\/* Interface to Readline Completion *\/\n\/* *\/\n\/* **************************************************************** *\/\n\nchar *command_generator ();\nchar **fileman_completion ();\n\n\/**\n * Attempt to complete on the contents of TEXT. START and END bound the\n * region of rl_line_buffer that contains the word to complete. TEXT is\n * the word to complete. We can use the entire contents of rl_line_buffer\n * in case we want to do some simple parsing. Return the array of matches,\n * or NULL if there aren't any.\n *\/\n#if RL_READLINE_VERSION >= 0x0402\nchar** ecasound_completion (const char *text, int start, int end)\n#else\nchar** ecasound_completion (char *text, int start, int end)\n#endif\n{\n char **matches;\n matches = (char **)NULL;\n\n \/* complete only the first command, otherwise complete files in \n * the current directory *\/\n if (start == 0) {\n#if RL_READLINE_VERSION >= 0x0402\n matches = rl_completion_matches (text, (rl_compentry_func_t *)ecasound_command_generator);\n#else\n matches = completion_matches (text, (CPFunction *)ecasound_command_generator);\n#endif\n }\n return (matches);\n}\n\n\/**\n * Generator function for command completion. STATE lets us know whether\n * to start from scratch; without any state (i.e. STATE == 0), then we\n * start at the top of the list.\n *\/\n#if RL_READLINE_VERSION >= 0x0402\nchar* ecasound_command_generator (const char* text, int state)\n#else\nchar* ecasound_command_generator (char* text, int state)\n#endif\n{\n static int list_index, len;\n static const map<string,int>& map_ref = ECA_IAMODE_PARSER::registered_commands();\n static map<string,int>::const_iterator p;\n static string cmd;\n\n \/* If this is a new word to complete, initialize now. This includes\n * saving the length of TEXT for efficiency, and initializing the index\n * variable to 0\n *\/\n if (!state) {\n list_index = 0;\n p = map_ref.begin();\n len = strlen (text);\n }\n\n \/* Return the next name which partially matches from the command list *\/\n while (p != map_ref.end()) {\n cmd = p->first;\n list_index++;\n ++p;\n if (p != map_ref.end()) {\n\tstring hyphenstr = kvu_string_search_and_replace(text, '_', '-');\n\tif (strncmp(hyphenstr.c_str(), cmd.c_str(), len) == 0) {\n\t return(strdup(cmd.c_str()));\n\t}\n }\n }\n return ((char *)0);\n}\n\n#else\n\nECA_CURSES::ECA_CURSES(void) {}\nECA_CURSES::~ECA_CURSES(void) {}\nvoid ECA_CURSES::print(const std::string& msg) {}\nvoid ECA_CURSES::print_banner(void) {}\nvoid ECA_CURSES::read_command(const string& promp) {}\nconst string& ECA_CURSES::last_command(void) const { static std::string empty; return(empty); }\nvoid ECA_CURSES::init_readline_support(void) {}\n\n#endif \/* defined ECA_USE_NCURSES || defined ECA_USE_TERMCAP *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ PluginHelpers.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Toolbars.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#using <system.dll>\n\nusing namespace Abstractspoon::Tdl::PluginHelpers;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Toolbars::FixupButtonSizes(ToolStrip^ toolbar)\n{\n\tauto imageSize = toolbar->ImageScalingSize;\n\tint numItems = toolbar->Items->Count;\n\n\tfor (int i = 0; i < numItems; i++)\n\t{\n\t\tauto button = dynamic_cast<ToolStripButton^>(toolbar->Items[i]);\n\n\t\tif (button != nullptr)\n\t\t{\n\t\t\t\/\/ From 'Shared\\EnToolBar.cpp'\n\t\t\tint xPadding = (imageSize.Width + 7 - button->Size.Width);\n\t\t\tint yPadding = (imageSize.Height + 7 - button->Size.Height);\n\n\t\t\tSystem::Diagnostics::Trace::WriteLine(String::Format(\"Toolbars::FixupButtonSizes({0}, size({1}, {2}), padding({3}, {4}))\", \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t i, button->Size.Width, button->Size.Height, xPadding, yPadding));\n\n\t\t\tbutton->Padding = Padding(xPadding \/ 2, yPadding \/ 2, xPadding - xPadding \/ 2, yPadding - yPadding \/ 2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto sep = dynamic_cast<ToolStripSeparator^>(toolbar->Items[i]);\n\n\t\t\tif (sep != nullptr)\n\t\t\t{\n\t\t\t\tsep->AutoSize = false;\n\t\t\t\tsep->Height = (imageSize.Height + 7);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBaseToolbarRenderer::BaseToolbarRenderer() : m_DrawRowDividers(true)\n{\n\n}\n\nvoid BaseToolbarRenderer::EnableDrawRowDividers(bool enable)\n{\n\tm_DrawRowDividers = enable;\n}\n\nvoid BaseToolbarRenderer::OnRenderToolStripBackground(ToolStripRenderEventArgs^ e)\n{\n\tToolStripRenderer::OnRenderToolStripBackground(e);\n\n\tif (m_DrawRowDividers)\n\t{\n\t\tauto toolbar = e->ToolStrip;\n\t\tint numItems = toolbar->Items->Count;\n\n\t\tif (numItems > 0)\n\t\t{\n\t\t\tauto prevBtnRect = Drawing::Rectangle::Empty;\n\t\t\tint rowTop = toolbar->Top, rowBottom = 0;\n\t\t\tbool firstRow = true;\n\n\t\t\tfor (int i = 0; i < numItems; i++)\n\t\t\t{\n\t\t\t\tauto button = dynamic_cast<ToolStripButton^>(toolbar->Items[i]);\n\n\t\t\t\tif (button != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif (prevBtnRect.IsEmpty)\n\t\t\t\t\t{\n\t\t\t\t\t\tprevBtnRect = button->Bounds;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto btnRect = button->Bounds;\n\n\t\t\t\t\t\tif (btnRect.Top > prevBtnRect.Top)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trowBottom = ((btnRect.Top + prevBtnRect.Bottom) \/ 2);\n\n\t\t\t\t\t\t\tauto rowRect = gcnew Drawing::Rectangle(toolbar->Left, rowTop, toolbar->Width, (rowBottom - rowTop));\n\t\t\t\t\t\t\tDrawRowBackground(e->Graphics, rowRect, firstRow, false);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tprevBtnRect = btnRect;\n\t\t\t\t\t\t\trowTop = rowBottom + 1;\n\t\t\t\t\t\t\tfirstRow = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Last row\n\t\t\tauto rowRect = gcnew Drawing::Rectangle(toolbar->Left, rowTop, toolbar->Width, (toolbar->Bottom - rowTop));\n\t\t\tDrawRowBackground(e->Graphics, rowRect, firstRow, true);\n\t\t}\n\t}\n}\n\nvoid BaseToolbarRenderer::DrawRowBackground(Drawing::Graphics^ g, Drawing::Rectangle^ rowRect, bool firstRow, bool lastRow)\n{\n\tDrawRowDivider(g, rowRect, firstRow, lastRow);\n}\n\nvoid BaseToolbarRenderer::DrawRowDivider(Drawing::Graphics^ g, Drawing::Rectangle^ rowRect, bool firstRow, bool lastRow)\n{\n\t\/\/ Draw highlight line at top if not first row\n\tif (!firstRow)\n\t\tg->DrawLine(SystemPens::ButtonHighlight, rowRect->Left, rowRect->Top, rowRect->Right, rowRect->Top);\n\n\n\t\/\/ Draw shadow line at bottom if not last row\n\tif (!lastRow)\n\t\tg->DrawLine(SystemPens::ButtonShadow, rowRect->Left, rowRect->Bottom, rowRect->Right, rowRect->Bottom);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Comment out debug code<commit_after>\/\/ PluginHelpers.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Toolbars.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#using <system.dll>\n\nusing namespace Abstractspoon::Tdl::PluginHelpers;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Toolbars::FixupButtonSizes(ToolStrip^ toolbar)\n{\n\tauto imageSize = toolbar->ImageScalingSize;\n\tint numItems = toolbar->Items->Count;\n\n\tfor (int i = 0; i < numItems; i++)\n\t{\n\t\tauto button = dynamic_cast<ToolStripButton^>(toolbar->Items[i]);\n\n\t\tif (button != nullptr)\n\t\t{\n\t\t\t\/\/ From 'Shared\\EnToolBar.cpp'\n\t\t\tint xPadding = (imageSize.Width + 7 - button->Size.Width);\n\t\t\tint yPadding = (imageSize.Height + 7 - button->Size.Height);\n\n\t\t\t\/\/System::Diagnostics::Trace::WriteLine(String::Format(\"Toolbars::FixupButtonSizes({0}, size({1}, {2}), padding({3}, {4}))\", \n\t\t\t\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t i, button->Size.Width, button->Size.Height, xPadding, yPadding));\n\n\t\t\tbutton->Padding = Padding(xPadding \/ 2, yPadding \/ 2, xPadding - xPadding \/ 2, yPadding - yPadding \/ 2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto sep = dynamic_cast<ToolStripSeparator^>(toolbar->Items[i]);\n\n\t\t\tif (sep != nullptr)\n\t\t\t{\n\t\t\t\tsep->AutoSize = false;\n\t\t\t\tsep->Height = (imageSize.Height + 7);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBaseToolbarRenderer::BaseToolbarRenderer() : m_DrawRowDividers(true)\n{\n\n}\n\nvoid BaseToolbarRenderer::EnableDrawRowDividers(bool enable)\n{\n\tm_DrawRowDividers = enable;\n}\n\nvoid BaseToolbarRenderer::OnRenderToolStripBackground(ToolStripRenderEventArgs^ e)\n{\n\tToolStripRenderer::OnRenderToolStripBackground(e);\n\n\tif (m_DrawRowDividers)\n\t{\n\t\tauto toolbar = e->ToolStrip;\n\t\tint numItems = toolbar->Items->Count;\n\n\t\tif (numItems > 0)\n\t\t{\n\t\t\tauto prevBtnRect = Drawing::Rectangle::Empty;\n\t\t\tint rowTop = toolbar->Top, rowBottom = 0;\n\t\t\tbool firstRow = true;\n\n\t\t\tfor (int i = 0; i < numItems; i++)\n\t\t\t{\n\t\t\t\tauto button = dynamic_cast<ToolStripButton^>(toolbar->Items[i]);\n\n\t\t\t\tif (button != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif (prevBtnRect.IsEmpty)\n\t\t\t\t\t{\n\t\t\t\t\t\tprevBtnRect = button->Bounds;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto btnRect = button->Bounds;\n\n\t\t\t\t\t\tif (btnRect.Top > prevBtnRect.Top)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trowBottom = ((btnRect.Top + prevBtnRect.Bottom) \/ 2);\n\n\t\t\t\t\t\t\tauto rowRect = gcnew Drawing::Rectangle(toolbar->Left, rowTop, toolbar->Width, (rowBottom - rowTop));\n\t\t\t\t\t\t\tDrawRowBackground(e->Graphics, rowRect, firstRow, false);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tprevBtnRect = btnRect;\n\t\t\t\t\t\t\trowTop = rowBottom + 1;\n\t\t\t\t\t\t\tfirstRow = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Last row\n\t\t\tauto rowRect = gcnew Drawing::Rectangle(toolbar->Left, rowTop, toolbar->Width, (toolbar->Bottom - rowTop));\n\t\t\tDrawRowBackground(e->Graphics, rowRect, firstRow, true);\n\t\t}\n\t}\n}\n\nvoid BaseToolbarRenderer::DrawRowBackground(Drawing::Graphics^ g, Drawing::Rectangle^ rowRect, bool firstRow, bool lastRow)\n{\n\tDrawRowDivider(g, rowRect, firstRow, lastRow);\n}\n\nvoid BaseToolbarRenderer::DrawRowDivider(Drawing::Graphics^ g, Drawing::Rectangle^ rowRect, bool firstRow, bool lastRow)\n{\n\t\/\/ Draw highlight line at top if not first row\n\tif (!firstRow)\n\t\tg->DrawLine(SystemPens::ButtonHighlight, rowRect->Left, rowRect->Top, rowRect->Right, rowRect->Top);\n\n\n\t\/\/ Draw shadow line at bottom if not last row\n\tif (!lastRow)\n\t\tg->DrawLine(SystemPens::ButtonShadow, rowRect->Left, rowRect->Bottom, rowRect->Right, rowRect->Bottom);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n Copyright 2011 Joe Hermaszewski. All rights reserved.\r\n\r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions are met:\r\n\r\n 1. Redistributions of source code must retain the above copyright notice,\r\n this list of conditions and the following disclaimer.\r\n\r\n 2. Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and\/or other materials provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR\r\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\r\n EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\r\n INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\r\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n The views and conclusions contained in the software and documentation are\r\n those of the authors and should not be interpreted as representing official\r\n policies, either expressed or implied, of Joe Hermaszewski.\r\n*\/\r\n\r\n#include \"declaration.hpp\"\r\n\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <memory>\r\n#include <string>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include <compiler\/casting.hpp>\r\n#include <compiler\/parser.hpp>\r\n#include <compiler\/sema_analyzer.hpp>\r\n#include <compiler\/terminal_types.hpp>\r\n#include <compiler\/tokens\/declaration_specifier.hpp>\r\n#include <compiler\/tokens\/declarator.hpp>\r\n#include <compiler\/tokens\/definition.hpp>\r\n#include <compiler\/tokens\/token.hpp>\r\n#include <compiler\/tokens\/statements\/compound_statement.hpp>\r\n#include <compiler\/type_properties.hpp>\r\n#include <joelang\/state_assignment.hpp>\r\n#include <joelang\/technique.hpp>\r\n\r\nnamespace JoeLang\r\n{\r\nnamespace Compiler\r\n{\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ DeclarationBase\r\n\/\/------------------------------------------------------------------------------\r\n\r\nDeclarationBase::DeclarationBase( TokenTy sub_class_id )\r\n :Token( sub_class_id )\r\n{\r\n}\r\n\r\nDeclarationBase::~DeclarationBase()\r\n{\r\n}\r\n\r\nbool DeclarationBase::Parse( Parser& parser,\r\n std::unique_ptr<DeclarationBase>& token )\r\n{\r\n \/\/ Try and parse any of the top level declarations\r\n std::unique_ptr<Token> t;\r\n if( !parser.ExpectAnyOf< TechniqueDeclaration,\r\n PassDeclaration,\r\n VariableListOrFunctionDefinition,\r\n EmptyDeclaration>( t ) )\r\n return false;\r\n\r\n assert( isa<DeclarationBase>( t ) &&\r\n \"DeclarationBase parsed a non-declaration\" );\r\n \/\/ Cast it back to a DeclarationBase because ExpectAnyOf only returns Token*\r\n token.reset( static_cast<DeclarationBase*>( t.release() ) );\r\n return true;\r\n}\r\n\r\nbool DeclarationBase::classof( const Token* d )\r\n{\r\n return d->GetSubClassID() >= TokenTy::Declaration_Start &&\r\n d->GetSubClassID() <= TokenTy::Declaration_End;\r\n}\r\n\r\nbool DeclarationBase::classof( const DeclarationBase* d )\r\n{\r\n \/\/ A DeclarationBase is always a DeclarationBase\r\n return true;\r\n}\r\n\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ EmptyDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nEmptyDeclaration::EmptyDeclaration()\r\n :DeclarationBase( TokenTy::EmptyDeclaration )\r\n{\r\n}\r\n\r\nEmptyDeclaration::~EmptyDeclaration()\r\n{\r\n}\r\n\r\nbool EmptyDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n return true;\r\n}\r\n\r\nbool EmptyDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<EmptyDeclaration>& token )\r\n{\r\n \/\/ Try to parse just a semicolon\r\n if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n return false;\r\n\r\n token.reset( new EmptyDeclaration );\r\n return true;\r\n}\r\n\r\nbool EmptyDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::EmptyDeclaration;\r\n}\r\n\r\nbool EmptyDeclaration::classof( const EmptyDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ PassDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nPassDeclaration::PassDeclaration( std::string name,\r\n std::unique_ptr<PassDefinition> definition )\r\n :DeclarationBase( TokenTy::PassDeclaration )\r\n ,m_Name ( std::move(name) )\r\n ,m_Definition ( std::move(definition) )\r\n{\r\n}\r\n\r\nPassDeclaration::~PassDeclaration()\r\n{\r\n}\r\n\r\nbool PassDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n \/\/ Only declare it if it's not an anonymous pass\r\n if( !m_Name.empty() )\r\n sema.DeclarePass( m_Name, std::move(m_Definition) );\r\n else\r\n {\r\n if( sema.InGlobalScope() )\r\n sema.Error( \"Declaring an anonymous pass in global scope\" );\r\n \/\/ We haven't given the pass to sema, so it must have sema performed on\r\n \/\/ it now\r\n return m_Definition->PerformSema( sema );\r\n }\r\n return true;\r\n}\r\n\r\nconst std::string& PassDeclaration::GetName() const\r\n{\r\n return m_Name;\r\n}\r\n\r\nbool PassDeclaration::HasDefinition() const\r\n{\r\n return bool(m_Definition);\r\n}\r\n\r\nconst std::unique_ptr<PassDefinition>& PassDeclaration::GetDefinition() const\r\n{\r\n return m_Definition;\r\n}\r\n\r\nstd::unique_ptr<PassDefinition> PassDeclaration::TakeDefinition()\r\n{\r\n return std::move(m_Definition);\r\n}\r\n\r\nbool PassDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<PassDeclaration>& token )\r\n{\r\n \/\/ Needs to start with 'pass'\r\n if( !parser.ExpectTerminal( TerminalType::PASS ) )\r\n return false;\r\n\r\n \/\/ Allow anonymous passes\r\n std::string name;\r\n parser.ExpectTerminal( TerminalType::IDENTIFIER, name );\r\n\r\n \/\/ If we have a semicolon here, this pass doesn't have a definition\r\n if( parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n {\r\n token.reset( new PassDeclaration( name, nullptr ) );\r\n return true;\r\n }\r\n \/\/ We may have moved the lexer on trying to parse the semicolon\r\n CHECK_PARSER;\r\n\r\n \/\/ This declaration must have a definition\r\n std::unique_ptr< PassDefinition > definition;\r\n if( !parser.Expect<PassDefinition>( definition ) )\r\n return false;\r\n\r\n token.reset( new PassDeclaration( std::move(name),\r\n std::move(definition) ) );\r\n return true;\r\n}\r\n\r\nbool PassDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::PassDeclaration;\r\n}\r\n\r\nbool PassDeclaration::classof( const PassDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ TechniqueDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nTechniqueDeclaration::TechniqueDeclaration( std::string name,\r\n PassDeclarationVector passes )\r\n\r\n :DeclarationBase( TokenTy::TechniqueDeclaration )\r\n ,m_Name( std::move(name) )\r\n ,m_Passes( std::move(passes) )\r\n{\r\n#ifndef NDEBUG\r\n for( const auto& p : m_Passes )\r\n assert( p && \"TechniqueDeclaration given a null pass\" );\r\n#endif\r\n}\r\n\r\nTechniqueDeclaration::~TechniqueDeclaration()\r\n{\r\n}\r\n\r\nbool TechniqueDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n sema.DeclareTechnique( m_Name );\r\n SemaAnalyzer::ScopeHolder scope( sema );\r\n scope.Enter();\r\n bool good = true;\r\n for( auto& p : m_Passes )\r\n good &= p->PerformSema( sema );\r\n scope.Leave();\r\n return good;\r\n}\r\n\r\nconst std::string& TechniqueDeclaration::GetName() const\r\n{\r\n return m_Name;\r\n}\r\n\r\nTechnique TechniqueDeclaration::GenerateTechnique(\r\n CodeGenerator& code_gen ) const\r\n{\r\n std::vector<Pass> passes;\r\n for( const auto& p : m_Passes )\r\n passes.push_back( p->GeneratePass( code_gen ) );\r\n return Technique( m_Name, std::move(passes) );\r\n}\r\n\r\nbool TechniqueDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<TechniqueDeclaration>& token )\r\n{\r\n \/\/ Has to start with 'technique'\r\n if( !parser.ExpectTerminal( TerminalType::TECHNIQUE ) )\r\n return false;\r\n\r\n \/\/ Parse the technique's name into name\r\n \/\/ Don't worry if there isn't a name, techniques can be anonymous\r\n std::string name;\r\n parser.ExpectTerminal( TerminalType::IDENTIFIER, name );\r\n\r\n \/\/ Technique Declarations always have a definition\r\n\r\n \/\/ Start with an open brace\r\n if( !parser.ExpectTerminal( TerminalType::OPEN_BRACE ) )\r\n return false;\r\n\r\n \/\/ Try and parse the pass declarations\r\n PassDeclarationVector pass_declarations;\r\n parser.ExpectSequenceOf<PassDeclarationOrIdentifier>( pass_declarations );\r\n CHECK_PARSER;\r\n\r\n \/\/ End with a close brace\r\n if( !parser.ExpectTerminal( TerminalType::CLOSE_BRACE ) )\r\n return false;\r\n\r\n token.reset( new TechniqueDeclaration( std::move(name),\r\n std::move(pass_declarations) ) );\r\n return true;\r\n}\r\n\r\nbool TechniqueDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::TechniqueDeclaration;\r\n}\r\n\r\nbool TechniqueDeclaration::classof( const TechniqueDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ VariableListOrFunctionDefinition\r\n\/\/------------------------------------------------------------------------------\r\n\r\nVariableListOrFunctionDefinition::VariableListOrFunctionDefinition(\r\n TokenTy sub_class_id )\r\n :DeclarationBase( sub_class_id )\r\n{\r\n}\r\n\r\nVariableListOrFunctionDefinition::~VariableListOrFunctionDefinition()\r\n{\r\n}\r\n\r\nbool VariableListOrFunctionDefinition::Parse(\r\n Parser& parser,\r\n std::unique_ptr<VariableListOrFunctionDefinition>& token )\r\n{\r\n DeclSpecsVector decl_specs;\r\n\r\n \/\/ We need at least one declaration specifier\r\n if( !parser.ExpectSequenceOf<DeclarationSpecifier>( decl_specs ) )\r\n return false;\r\n\r\n \/\/ Try and parse some declarators\r\n DeclaratorVector declarators;\r\n if( !parser.ExpectListOf<InitDeclarator, TerminalType::COMMA>(\r\n declarators ) )\r\n return false;\r\n\r\n if( declarators.empty() )\r\n {\r\n parser.Error( \"Declaration without a declarator\" );\r\n return false;\r\n }\r\n\r\n CompoundStatement_up function_body;\r\n\r\n if( declarators.size() == 1 &&\r\n declarators[0]->IsFunctionDeclarator() &&\r\n parser.Expect<CompoundStatement>( function_body ) )\r\n {\r\n \/\/ If there was only one declarator and it's a function declarator and\r\n \/\/ there's a compound statement then we have a function definiton;\r\n token.reset( new FunctionDefinition( std::move(decl_specs),\r\n declarators[0]->TakeDeclarator(),\r\n std::move(function_body) ) );\r\n return true;\r\n }\r\n CHECK_PARSER;\r\n\r\n \/\/ variable declarations must end in a semicolon\r\n if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n return false;\r\n\r\n token.reset( new VariableDeclarationList( std::move(decl_specs),\r\n std::move(declarators) ) );\r\n return true;\r\n}\r\n\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ VariableDeclarationList\r\n\/\/------------------------------------------------------------------------------\r\n\r\nVariableDeclarationList::VariableDeclarationList( DeclSpecsVector decl_specs,\r\n DeclaratorVector declarators)\r\n :VariableListOrFunctionDefinition( TokenTy::VariableDeclarationList )\r\n ,m_DeclSpecs( std::move(decl_specs) )\r\n ,m_Declarators( std::move(declarators) )\r\n{\r\n assert( !m_DeclSpecs.empty() &&\r\n \"VariableDeclarationList given no declaration specifiers\" );\r\n}\r\n\r\nVariableDeclarationList::~VariableDeclarationList()\r\n{\r\n}\r\n\r\nbool VariableDeclarationList::PerformSema( SemaAnalyzer& sema )\r\n{\r\n DeclSpecs decl_specs;\r\n\r\n \/\/\r\n \/\/ If the decl specs were no good we can't continue\r\n \/\/\r\n if( !decl_specs.AnalyzeDeclSpecs( m_DeclSpecs, sema ) )\r\n return false;\r\n\r\n if( sema.InGlobalScope() &&\r\n !decl_specs.IsStatic() &&\r\n !decl_specs.IsVarying() )\r\n \/\/ Globals are uniform by default\r\n decl_specs.SetIsUniform( true );\r\n\r\n \/\/\r\n \/\/ Check that\r\n \/\/\r\n \r\n for( const InitDeclarator_up& declarator : m_Declarators )\r\n declarator->PerformSema( sema, decl_specs );\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ FunctionDefinition\r\n\/\/------------------------------------------------------------------------------\r\n\r\nFunctionDefinition::FunctionDefinition( DeclSpecsVector decl_specs,\r\n Declarator_up declarator,\r\n CompoundStatement_up body )\r\n :VariableListOrFunctionDefinition( TokenTy::FunctionDefinition )\r\n ,m_DeclarationSpecifiers( std::move(decl_specs) )\r\n ,m_Declarator( std::move(declarator) )\r\n ,m_Body( std::move(body) )\r\n{\r\n#if !defined(NDEBUG)\r\n assert( !m_DeclarationSpecifiers.empty() &&\r\n \"FunctionDefinition given no decl specs\" );\r\n for( const auto& d : m_DeclarationSpecifiers )\r\n assert( d && \"FunctionDefinition given a null declaration specifier\" );\r\n assert( m_Declarator && \"FunctionDefinition given a null declarator\" );\r\n assert( m_Declarator->IsFunctionDeclarator() &&\r\n \"FunctionDefinition given a non-function declarator\" );\r\n assert( m_Body && \"FunctionDefinition given a null body\" );\r\n#endif\r\n}\r\n\r\nFunctionDefinition::~FunctionDefinition()\r\n{\r\n}\r\n\r\nbool FunctionDefinition::PerformSema( SemaAnalyzer& sema )\r\n{\r\n DeclSpecs decl_specs;\r\n decl_specs.AnalyzeDeclSpecs( m_DeclarationSpecifiers, sema );\r\n\r\n \/\/ This will register the function with sema and verify that it's all ok\r\n m_Declarator->PerformSema( sema, decl_specs );\r\n\r\n SemaAnalyzer::ScopeHolder scope( sema );\r\n scope.Enter();\r\n\r\n \/\/ Register the variables with sema\r\n m_Declarator->DeclareFunctionParameters( sema );\r\n\r\n \/\/ Pass the return type to sema for generating the return statements\r\n m_Body->PerformSemaAsFunction( sema,\r\n CompleteType(\r\n decl_specs.GetType(),\r\n m_Declarator->GetArrayExtents() ) );\r\n scope.Leave();\r\n\r\n sema.DefineFunction( m_Declarator->GetIdentifier(),\r\n m_Declarator->GetFunctionParameters(),\r\n std::move(m_Body) );\r\n return true;\r\n}\r\n\r\n} \/\/ namespace Compiler\r\n} \/\/ namespace JoeLang\r\n<commit_msg>[+] Const variables are no longer uniform by default<commit_after>\/*\r\n Copyright 2011 Joe Hermaszewski. All rights reserved.\r\n\r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions are met:\r\n\r\n 1. Redistributions of source code must retain the above copyright notice,\r\n this list of conditions and the following disclaimer.\r\n\r\n 2. Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and\/or other materials provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR\r\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\r\n EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\r\n INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\r\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n The views and conclusions contained in the software and documentation are\r\n those of the authors and should not be interpreted as representing official\r\n policies, either expressed or implied, of Joe Hermaszewski.\r\n*\/\r\n\r\n#include \"declaration.hpp\"\r\n\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <memory>\r\n#include <string>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include <compiler\/casting.hpp>\r\n#include <compiler\/parser.hpp>\r\n#include <compiler\/sema_analyzer.hpp>\r\n#include <compiler\/terminal_types.hpp>\r\n#include <compiler\/tokens\/declaration_specifier.hpp>\r\n#include <compiler\/tokens\/declarator.hpp>\r\n#include <compiler\/tokens\/definition.hpp>\r\n#include <compiler\/tokens\/token.hpp>\r\n#include <compiler\/tokens\/statements\/compound_statement.hpp>\r\n#include <compiler\/type_properties.hpp>\r\n#include <joelang\/state_assignment.hpp>\r\n#include <joelang\/technique.hpp>\r\n\r\nnamespace JoeLang\r\n{\r\nnamespace Compiler\r\n{\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ DeclarationBase\r\n\/\/------------------------------------------------------------------------------\r\n\r\nDeclarationBase::DeclarationBase( TokenTy sub_class_id )\r\n :Token( sub_class_id )\r\n{\r\n}\r\n\r\nDeclarationBase::~DeclarationBase()\r\n{\r\n}\r\n\r\nbool DeclarationBase::Parse( Parser& parser,\r\n std::unique_ptr<DeclarationBase>& token )\r\n{\r\n \/\/ Try and parse any of the top level declarations\r\n std::unique_ptr<Token> t;\r\n if( !parser.ExpectAnyOf< TechniqueDeclaration,\r\n PassDeclaration,\r\n VariableListOrFunctionDefinition,\r\n EmptyDeclaration>( t ) )\r\n return false;\r\n\r\n assert( isa<DeclarationBase>( t ) &&\r\n \"DeclarationBase parsed a non-declaration\" );\r\n \/\/ Cast it back to a DeclarationBase because ExpectAnyOf only returns Token*\r\n token.reset( static_cast<DeclarationBase*>( t.release() ) );\r\n return true;\r\n}\r\n\r\nbool DeclarationBase::classof( const Token* d )\r\n{\r\n return d->GetSubClassID() >= TokenTy::Declaration_Start &&\r\n d->GetSubClassID() <= TokenTy::Declaration_End;\r\n}\r\n\r\nbool DeclarationBase::classof( const DeclarationBase* d )\r\n{\r\n \/\/ A DeclarationBase is always a DeclarationBase\r\n return true;\r\n}\r\n\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ EmptyDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nEmptyDeclaration::EmptyDeclaration()\r\n :DeclarationBase( TokenTy::EmptyDeclaration )\r\n{\r\n}\r\n\r\nEmptyDeclaration::~EmptyDeclaration()\r\n{\r\n}\r\n\r\nbool EmptyDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n return true;\r\n}\r\n\r\nbool EmptyDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<EmptyDeclaration>& token )\r\n{\r\n \/\/ Try to parse just a semicolon\r\n if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n return false;\r\n\r\n token.reset( new EmptyDeclaration );\r\n return true;\r\n}\r\n\r\nbool EmptyDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::EmptyDeclaration;\r\n}\r\n\r\nbool EmptyDeclaration::classof( const EmptyDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ PassDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nPassDeclaration::PassDeclaration( std::string name,\r\n std::unique_ptr<PassDefinition> definition )\r\n :DeclarationBase( TokenTy::PassDeclaration )\r\n ,m_Name ( std::move(name) )\r\n ,m_Definition ( std::move(definition) )\r\n{\r\n}\r\n\r\nPassDeclaration::~PassDeclaration()\r\n{\r\n}\r\n\r\nbool PassDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n \/\/ Only declare it if it's not an anonymous pass\r\n if( !m_Name.empty() )\r\n sema.DeclarePass( m_Name, std::move(m_Definition) );\r\n else\r\n {\r\n if( sema.InGlobalScope() )\r\n sema.Error( \"Declaring an anonymous pass in global scope\" );\r\n \/\/ We haven't given the pass to sema, so it must have sema performed on\r\n \/\/ it now\r\n return m_Definition->PerformSema( sema );\r\n }\r\n return true;\r\n}\r\n\r\nconst std::string& PassDeclaration::GetName() const\r\n{\r\n return m_Name;\r\n}\r\n\r\nbool PassDeclaration::HasDefinition() const\r\n{\r\n return bool(m_Definition);\r\n}\r\n\r\nconst std::unique_ptr<PassDefinition>& PassDeclaration::GetDefinition() const\r\n{\r\n return m_Definition;\r\n}\r\n\r\nstd::unique_ptr<PassDefinition> PassDeclaration::TakeDefinition()\r\n{\r\n return std::move(m_Definition);\r\n}\r\n\r\nbool PassDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<PassDeclaration>& token )\r\n{\r\n \/\/ Needs to start with 'pass'\r\n if( !parser.ExpectTerminal( TerminalType::PASS ) )\r\n return false;\r\n\r\n \/\/ Allow anonymous passes\r\n std::string name;\r\n parser.ExpectTerminal( TerminalType::IDENTIFIER, name );\r\n\r\n \/\/ If we have a semicolon here, this pass doesn't have a definition\r\n if( parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n {\r\n token.reset( new PassDeclaration( name, nullptr ) );\r\n return true;\r\n }\r\n \/\/ We may have moved the lexer on trying to parse the semicolon\r\n CHECK_PARSER;\r\n\r\n \/\/ This declaration must have a definition\r\n std::unique_ptr< PassDefinition > definition;\r\n if( !parser.Expect<PassDefinition>( definition ) )\r\n return false;\r\n\r\n token.reset( new PassDeclaration( std::move(name),\r\n std::move(definition) ) );\r\n return true;\r\n}\r\n\r\nbool PassDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::PassDeclaration;\r\n}\r\n\r\nbool PassDeclaration::classof( const PassDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ TechniqueDeclaration\r\n\/\/------------------------------------------------------------------------------\r\n\r\nTechniqueDeclaration::TechniqueDeclaration( std::string name,\r\n PassDeclarationVector passes )\r\n\r\n :DeclarationBase( TokenTy::TechniqueDeclaration )\r\n ,m_Name( std::move(name) )\r\n ,m_Passes( std::move(passes) )\r\n{\r\n#ifndef NDEBUG\r\n for( const auto& p : m_Passes )\r\n assert( p && \"TechniqueDeclaration given a null pass\" );\r\n#endif\r\n}\r\n\r\nTechniqueDeclaration::~TechniqueDeclaration()\r\n{\r\n}\r\n\r\nbool TechniqueDeclaration::PerformSema( SemaAnalyzer& sema )\r\n{\r\n sema.DeclareTechnique( m_Name );\r\n SemaAnalyzer::ScopeHolder scope( sema );\r\n scope.Enter();\r\n bool good = true;\r\n for( auto& p : m_Passes )\r\n good &= p->PerformSema( sema );\r\n scope.Leave();\r\n return good;\r\n}\r\n\r\nconst std::string& TechniqueDeclaration::GetName() const\r\n{\r\n return m_Name;\r\n}\r\n\r\nTechnique TechniqueDeclaration::GenerateTechnique(\r\n CodeGenerator& code_gen ) const\r\n{\r\n std::vector<Pass> passes;\r\n for( const auto& p : m_Passes )\r\n passes.push_back( p->GeneratePass( code_gen ) );\r\n return Technique( m_Name, std::move(passes) );\r\n}\r\n\r\nbool TechniqueDeclaration::Parse( Parser& parser,\r\n std::unique_ptr<TechniqueDeclaration>& token )\r\n{\r\n \/\/ Has to start with 'technique'\r\n if( !parser.ExpectTerminal( TerminalType::TECHNIQUE ) )\r\n return false;\r\n\r\n \/\/ Parse the technique's name into name\r\n \/\/ Don't worry if there isn't a name, techniques can be anonymous\r\n std::string name;\r\n parser.ExpectTerminal( TerminalType::IDENTIFIER, name );\r\n\r\n \/\/ Technique Declarations always have a definition\r\n\r\n \/\/ Start with an open brace\r\n if( !parser.ExpectTerminal( TerminalType::OPEN_BRACE ) )\r\n return false;\r\n\r\n \/\/ Try and parse the pass declarations\r\n PassDeclarationVector pass_declarations;\r\n parser.ExpectSequenceOf<PassDeclarationOrIdentifier>( pass_declarations );\r\n CHECK_PARSER;\r\n\r\n \/\/ End with a close brace\r\n if( !parser.ExpectTerminal( TerminalType::CLOSE_BRACE ) )\r\n return false;\r\n\r\n token.reset( new TechniqueDeclaration( std::move(name),\r\n std::move(pass_declarations) ) );\r\n return true;\r\n}\r\n\r\nbool TechniqueDeclaration::classof( const DeclarationBase* d )\r\n{\r\n return d->GetSubClassID() == TokenTy::TechniqueDeclaration;\r\n}\r\n\r\nbool TechniqueDeclaration::classof( const TechniqueDeclaration* d )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ VariableListOrFunctionDefinition\r\n\/\/------------------------------------------------------------------------------\r\n\r\nVariableListOrFunctionDefinition::VariableListOrFunctionDefinition(\r\n TokenTy sub_class_id )\r\n :DeclarationBase( sub_class_id )\r\n{\r\n}\r\n\r\nVariableListOrFunctionDefinition::~VariableListOrFunctionDefinition()\r\n{\r\n}\r\n\r\nbool VariableListOrFunctionDefinition::Parse(\r\n Parser& parser,\r\n std::unique_ptr<VariableListOrFunctionDefinition>& token )\r\n{\r\n DeclSpecsVector decl_specs;\r\n\r\n \/\/ We need at least one declaration specifier\r\n if( !parser.ExpectSequenceOf<DeclarationSpecifier>( decl_specs ) )\r\n return false;\r\n\r\n \/\/ Try and parse some declarators\r\n DeclaratorVector declarators;\r\n if( !parser.ExpectListOf<InitDeclarator, TerminalType::COMMA>(\r\n declarators ) )\r\n return false;\r\n\r\n if( declarators.empty() )\r\n {\r\n parser.Error( \"Declaration without a declarator\" );\r\n return false;\r\n }\r\n\r\n CompoundStatement_up function_body;\r\n\r\n if( declarators.size() == 1 &&\r\n declarators[0]->IsFunctionDeclarator() &&\r\n parser.Expect<CompoundStatement>( function_body ) )\r\n {\r\n \/\/ If there was only one declarator and it's a function declarator and\r\n \/\/ there's a compound statement then we have a function definiton;\r\n token.reset( new FunctionDefinition( std::move(decl_specs),\r\n declarators[0]->TakeDeclarator(),\r\n std::move(function_body) ) );\r\n return true;\r\n }\r\n CHECK_PARSER;\r\n\r\n \/\/ variable declarations must end in a semicolon\r\n if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )\r\n return false;\r\n\r\n token.reset( new VariableDeclarationList( std::move(decl_specs),\r\n std::move(declarators) ) );\r\n return true;\r\n}\r\n\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ VariableDeclarationList\r\n\/\/------------------------------------------------------------------------------\r\n\r\nVariableDeclarationList::VariableDeclarationList( DeclSpecsVector decl_specs,\r\n DeclaratorVector declarators)\r\n :VariableListOrFunctionDefinition( TokenTy::VariableDeclarationList )\r\n ,m_DeclSpecs( std::move(decl_specs) )\r\n ,m_Declarators( std::move(declarators) )\r\n{\r\n assert( !m_DeclSpecs.empty() &&\r\n \"VariableDeclarationList given no declaration specifiers\" );\r\n}\r\n\r\nVariableDeclarationList::~VariableDeclarationList()\r\n{\r\n}\r\n\r\nbool VariableDeclarationList::PerformSema( SemaAnalyzer& sema )\r\n{\r\n DeclSpecs decl_specs;\r\n\r\n \/\/\r\n \/\/ If the decl specs were no good we can't continue\r\n \/\/\r\n if( !decl_specs.AnalyzeDeclSpecs( m_DeclSpecs, sema ) )\r\n return false;\r\n\r\n if( sema.InGlobalScope() &&\r\n !decl_specs.IsStatic() &&\r\n !decl_specs.IsConst() &&\r\n !decl_specs.IsVarying() )\r\n \/\/ Globals are uniform by default\r\n decl_specs.SetIsUniform( true );\r\n\r\n \/\/\r\n \/\/ Check that\r\n \/\/\r\n \r\n for( const InitDeclarator_up& declarator : m_Declarators )\r\n declarator->PerformSema( sema, decl_specs );\r\n return true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ FunctionDefinition\r\n\/\/------------------------------------------------------------------------------\r\n\r\nFunctionDefinition::FunctionDefinition( DeclSpecsVector decl_specs,\r\n Declarator_up declarator,\r\n CompoundStatement_up body )\r\n :VariableListOrFunctionDefinition( TokenTy::FunctionDefinition )\r\n ,m_DeclarationSpecifiers( std::move(decl_specs) )\r\n ,m_Declarator( std::move(declarator) )\r\n ,m_Body( std::move(body) )\r\n{\r\n#if !defined(NDEBUG)\r\n assert( !m_DeclarationSpecifiers.empty() &&\r\n \"FunctionDefinition given no decl specs\" );\r\n for( const auto& d : m_DeclarationSpecifiers )\r\n assert( d && \"FunctionDefinition given a null declaration specifier\" );\r\n assert( m_Declarator && \"FunctionDefinition given a null declarator\" );\r\n assert( m_Declarator->IsFunctionDeclarator() &&\r\n \"FunctionDefinition given a non-function declarator\" );\r\n assert( m_Body && \"FunctionDefinition given a null body\" );\r\n#endif\r\n}\r\n\r\nFunctionDefinition::~FunctionDefinition()\r\n{\r\n}\r\n\r\nbool FunctionDefinition::PerformSema( SemaAnalyzer& sema )\r\n{\r\n DeclSpecs decl_specs;\r\n decl_specs.AnalyzeDeclSpecs( m_DeclarationSpecifiers, sema );\r\n\r\n \/\/ This will register the function with sema and verify that it's all ok\r\n m_Declarator->PerformSema( sema, decl_specs );\r\n\r\n SemaAnalyzer::ScopeHolder scope( sema );\r\n scope.Enter();\r\n\r\n \/\/ Register the variables with sema\r\n m_Declarator->DeclareFunctionParameters( sema );\r\n\r\n \/\/ Pass the return type to sema for generating the return statements\r\n m_Body->PerformSemaAsFunction( sema,\r\n CompleteType(\r\n decl_specs.GetType(),\r\n m_Declarator->GetArrayExtents() ) );\r\n scope.Leave();\r\n\r\n sema.DefineFunction( m_Declarator->GetIdentifier(),\r\n m_Declarator->GetFunctionParameters(),\r\n std::move(m_Body) );\r\n return true;\r\n}\r\n\r\n} \/\/ namespace Compiler\r\n} \/\/ namespace JoeLang\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2001-2011 by Serge Lamikhov-Center\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef ELFIO_DYNAMIC_HPP\n#define ELFIO_DYNAMIC_HPP\n\nnamespace ELFIO {\n\n\/\/------------------------------------------------------------------------------\nclass dynamic_section_accessor\n{\n public:\n\/\/------------------------------------------------------------------------------\n dynamic_section_accessor( const elfio& elf_file_, section* section_ ) :\n elf_file( elf_file_ ),\n dynamic_section( section_ )\n {\n }\n\n\/\/------------------------------------------------------------------------------\n Elf_Xword\n get_entries_num() const\n {\n Elf_Xword nRet = 0;\n\n if ( 0 != dynamic_section->get_entry_size() ) {\n nRet = dynamic_section->get_size() \/ dynamic_section->get_entry_size();\n }\n\n return nRet;\n }\n\n\/\/------------------------------------------------------------------------------\n bool\n get_entry( Elf_Xword index,\n Elf_Xword& tag,\n Elf_Xword& value,\n std::string& str ) const\n {\n if ( index >= get_entries_num() ) { \/\/ Is index valid\n return false;\n }\n\n if ( elf_file.get_class() == ELFCLASS32 ) {\n generic_get_entry_dyn< Elf32_Dyn >( index, tag, value );\n }\n else {\n generic_get_entry_dyn< Elf64_Dyn >( index, tag, value );\n }\n\n \/\/ If the tag may have a string table reference, prepare the string\n if ( tag == DT_NEEDED ||\n tag == DT_SONAME ||\n tag == DT_RPATH ||\n tag == DT_RUNPATH ) {\n string_section_accessor strsec =\n elf_file.sections[ get_string_table_index() ];\n str = strsec.get_string( value );\n }\n else {\n str.clear();\n }\n\n return true;\n }\n\n\/\/------------------------------------------------------------------------------\n void\n add_entry( Elf_Xword& tag,\n Elf_Xword& value )\n {\n if ( elf_file.get_class() == ELFCLASS32 ) {\n generic_add_entry< Elf32_Dyn >( tag, value );\n }\n else {\n generic_add_entry< Elf64_Dyn >( tag, value );\n }\n }\n\n\/\/------------------------------------------------------------------------------\n void\n add_entry( Elf_Xword& tag,\n std::string& str )\n {\n string_section_accessor strsec =\n elf_file.sections[ get_string_table_index() ];\n Elf_Xword value = strsec.add_string( str );\n add_entry( tag, value );\n }\n\n\/\/------------------------------------------------------------------------------\n private:\n\/\/------------------------------------------------------------------------------\n Elf_Half\n get_string_table_index() const\n {\n return (Elf_Half)dynamic_section->get_link();\n }\n\n\/\/------------------------------------------------------------------------------\n template< class T >\n void\n generic_get_entry_dyn( Elf_Xword index,\n Elf_Xword& tag,\n Elf_Xword& value ) const\n {\n const endianess_convertor& convertor = elf_file.get_convertor();\n\n const T* pEntry = reinterpret_cast<const T*>(\n dynamic_section->get_data() +\n index * dynamic_section->get_entry_size() );\n tag = convertor( pEntry->d_tag );\n switch ( tag ) {\n case DT_NULL:\n case DT_SYMBOLIC:\n case DT_TEXTREL:\n case DT_BIND_NOW:\n value = 0;\n break;\n case DT_NEEDED:\n case DT_PLTRELSZ:\n case DT_RELASZ:\n case DT_RELAENT:\n case DT_STRSZ:\n case DT_SYMENT:\n case DT_SONAME:\n case DT_RPATH:\n case DT_RELSZ:\n case DT_RELENT:\n case DT_PLTREL:\n case DT_INIT_ARRAYSZ:\n case DT_FINI_ARRAYSZ:\n case DT_RUNPATH:\n case DT_FLAGS:\n case DT_PREINIT_ARRAYSZ:\n value = convertor( pEntry->d_un.d_val );\n break;\n case DT_PLTGOT:\n case DT_HASH:\n case DT_STRTAB:\n case DT_SYMTAB:\n case DT_RELA:\n case DT_INIT:\n case DT_FINI:\n case DT_REL:\n case DT_DEBUG:\n case DT_JMPREL:\n case DT_INIT_ARRAY:\n case DT_FINI_ARRAY:\n case DT_PREINIT_ARRAY:\n default:\n value = convertor( pEntry->d_un.d_ptr );\n break;\n }\n }\n\n\/\/------------------------------------------------------------------------------\n template< class T >\n void\n generic_add_entry( Elf_Xword tag, Elf_Xword value )\n {\n const endianess_convertor& convertor = elf_file.get_convertor();\n\n T entry;\n\n switch ( tag ) {\n case DT_NULL:\n case DT_SYMBOLIC:\n case DT_TEXTREL:\n case DT_BIND_NOW:\n value = 0;\n case DT_NEEDED:\n case DT_PLTRELSZ:\n case DT_RELASZ:\n case DT_RELAENT:\n case DT_STRSZ:\n case DT_SYMENT:\n case DT_SONAME:\n case DT_RPATH:\n case DT_RELSZ:\n case DT_RELENT:\n case DT_PLTREL:\n case DT_INIT_ARRAYSZ:\n case DT_FINI_ARRAYSZ:\n case DT_RUNPATH:\n case DT_FLAGS:\n case DT_PREINIT_ARRAYSZ:\n entry.d_un.d_val = convertor( value );\n break;\n case DT_PLTGOT:\n case DT_HASH:\n case DT_STRTAB:\n case DT_SYMTAB:\n case DT_RELA:\n case DT_INIT:\n case DT_FINI:\n case DT_REL:\n case DT_DEBUG:\n case DT_JMPREL:\n case DT_INIT_ARRAY:\n case DT_FINI_ARRAY:\n case DT_PREINIT_ARRAY:\n default:\n entry.d_un.d_ptr = convertor( value );\n break;\n }\n\n entry.d_tag = convertor( tag );\n\n dynamic_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) );\n }\n\n\/\/------------------------------------------------------------------------------\n private:\n const elfio& elf_file;\n section* dynamic_section;\n};\n\n} \/\/ namespace ELFIO\n\n#endif \/\/ ELFIO_DYNAMIC_HPP\n<commit_msg>Add a validation for the case when dynamic section has no data<commit_after>\/*\nCopyright (C) 2001-2011 by Serge Lamikhov-Center\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef ELFIO_DYNAMIC_HPP\n#define ELFIO_DYNAMIC_HPP\n\nnamespace ELFIO {\n\n\/\/------------------------------------------------------------------------------\nclass dynamic_section_accessor\n{\n public:\n\/\/------------------------------------------------------------------------------\n dynamic_section_accessor( const elfio& elf_file_, section* section_ ) :\n elf_file( elf_file_ ),\n dynamic_section( section_ )\n {\n }\n\n\/\/------------------------------------------------------------------------------\n Elf_Xword\n get_entries_num() const\n {\n Elf_Xword nRet = 0;\n\n if ( 0 != dynamic_section->get_entry_size() ) {\n nRet = dynamic_section->get_size() \/ dynamic_section->get_entry_size();\n }\n\n return nRet;\n }\n\n\/\/------------------------------------------------------------------------------\n bool\n get_entry( Elf_Xword index,\n Elf_Xword& tag,\n Elf_Xword& value,\n std::string& str ) const\n {\n if ( index >= get_entries_num() ) { \/\/ Is index valid\n return false;\n }\n\n if ( elf_file.get_class() == ELFCLASS32 ) {\n generic_get_entry_dyn< Elf32_Dyn >( index, tag, value );\n }\n else {\n generic_get_entry_dyn< Elf64_Dyn >( index, tag, value );\n }\n\n \/\/ If the tag may have a string table reference, prepare the string\n if ( tag == DT_NEEDED ||\n tag == DT_SONAME ||\n tag == DT_RPATH ||\n tag == DT_RUNPATH ) {\n string_section_accessor strsec =\n elf_file.sections[ get_string_table_index() ];\n str = strsec.get_string( value );\n }\n else {\n str.clear();\n }\n\n return true;\n }\n\n\/\/------------------------------------------------------------------------------\n void\n add_entry( Elf_Xword& tag,\n Elf_Xword& value )\n {\n if ( elf_file.get_class() == ELFCLASS32 ) {\n generic_add_entry< Elf32_Dyn >( tag, value );\n }\n else {\n generic_add_entry< Elf64_Dyn >( tag, value );\n }\n }\n\n\/\/------------------------------------------------------------------------------\n void\n add_entry( Elf_Xword& tag,\n std::string& str )\n {\n string_section_accessor strsec =\n elf_file.sections[ get_string_table_index() ];\n Elf_Xword value = strsec.add_string( str );\n add_entry( tag, value );\n }\n\n\/\/------------------------------------------------------------------------------\n private:\n\/\/------------------------------------------------------------------------------\n Elf_Half\n get_string_table_index() const\n {\n return (Elf_Half)dynamic_section->get_link();\n }\n\n\/\/------------------------------------------------------------------------------\n template< class T >\n void\n generic_get_entry_dyn( Elf_Xword index,\n Elf_Xword& tag,\n Elf_Xword& value ) const\n {\n const endianess_convertor& convertor = elf_file.get_convertor();\n\n \/\/ Check unusual case when dynamic section has no data\n if( dynamic_section->get_data() == 0 ) {\n tag = DT_NULL;\n value = 0;\n return;\n }\n\n const T* pEntry = reinterpret_cast<const T*>(\n dynamic_section->get_data() +\n index * dynamic_section->get_entry_size() );\n tag = convertor( pEntry->d_tag );\n switch ( tag ) {\n case DT_NULL:\n case DT_SYMBOLIC:\n case DT_TEXTREL:\n case DT_BIND_NOW:\n value = 0;\n break;\n case DT_NEEDED:\n case DT_PLTRELSZ:\n case DT_RELASZ:\n case DT_RELAENT:\n case DT_STRSZ:\n case DT_SYMENT:\n case DT_SONAME:\n case DT_RPATH:\n case DT_RELSZ:\n case DT_RELENT:\n case DT_PLTREL:\n case DT_INIT_ARRAYSZ:\n case DT_FINI_ARRAYSZ:\n case DT_RUNPATH:\n case DT_FLAGS:\n case DT_PREINIT_ARRAYSZ:\n value = convertor( pEntry->d_un.d_val );\n break;\n case DT_PLTGOT:\n case DT_HASH:\n case DT_STRTAB:\n case DT_SYMTAB:\n case DT_RELA:\n case DT_INIT:\n case DT_FINI:\n case DT_REL:\n case DT_DEBUG:\n case DT_JMPREL:\n case DT_INIT_ARRAY:\n case DT_FINI_ARRAY:\n case DT_PREINIT_ARRAY:\n default:\n value = convertor( pEntry->d_un.d_ptr );\n break;\n }\n }\n\n\/\/------------------------------------------------------------------------------\n template< class T >\n void\n generic_add_entry( Elf_Xword tag, Elf_Xword value )\n {\n const endianess_convertor& convertor = elf_file.get_convertor();\n\n T entry;\n\n switch ( tag ) {\n case DT_NULL:\n case DT_SYMBOLIC:\n case DT_TEXTREL:\n case DT_BIND_NOW:\n value = 0;\n case DT_NEEDED:\n case DT_PLTRELSZ:\n case DT_RELASZ:\n case DT_RELAENT:\n case DT_STRSZ:\n case DT_SYMENT:\n case DT_SONAME:\n case DT_RPATH:\n case DT_RELSZ:\n case DT_RELENT:\n case DT_PLTREL:\n case DT_INIT_ARRAYSZ:\n case DT_FINI_ARRAYSZ:\n case DT_RUNPATH:\n case DT_FLAGS:\n case DT_PREINIT_ARRAYSZ:\n entry.d_un.d_val = convertor( value );\n break;\n case DT_PLTGOT:\n case DT_HASH:\n case DT_STRTAB:\n case DT_SYMTAB:\n case DT_RELA:\n case DT_INIT:\n case DT_FINI:\n case DT_REL:\n case DT_DEBUG:\n case DT_JMPREL:\n case DT_INIT_ARRAY:\n case DT_FINI_ARRAY:\n case DT_PREINIT_ARRAY:\n default:\n entry.d_un.d_ptr = convertor( value );\n break;\n }\n\n entry.d_tag = convertor( tag );\n\n dynamic_section->append_data( reinterpret_cast<char*>( &entry ), sizeof( entry ) );\n }\n\n\/\/------------------------------------------------------------------------------\n private:\n const elfio& elf_file;\n section* dynamic_section;\n};\n\n} \/\/ namespace ELFIO\n\n#endif \/\/ ELFIO_DYNAMIC_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------\n\/\/ Copyright Pierric Gimmig 2013-2017\n\/\/-----------------------------------\n\n#include \"TimerManager.h\"\n\n#include \"Message.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitLib.h\"\n#include \"Params.h\"\n#include \"TcpClient.h\"\n#include \"TcpForward.h\"\n#include \"Threading.h\"\n\n#ifdef _WIN32\n#include <direct.h>\n#endif\n\nstd::unique_ptr<TimerManager> GTimerManager;\n\n\/\/-----------------------------------------------------------------------------\nTimerManager::TimerManager(bool a_IsClient)\n : m_LockFreeQueue(65534), m_IsClient(a_IsClient) {\n m_Paused = false;\n m_IsFull = false;\n m_IsRecording = false;\n m_ExitRequested = false;\n m_FlushRequested = false;\n m_NumQueuedEntries = 0;\n m_NumQueuedTimers = 0;\n m_NumQueuedMessages = 0;\n m_TimerIndex = 0;\n m_NumTimersFromPreviousSession = 0;\n m_NumFlushedTimers = 0;\n\n if (m_IsClient) {\n GTcpClient->Start();\n consumerThread_ = std::thread{[this]() { SendTimers(); }};\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nTimerManager::~TimerManager() {}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StartRecording() {\n CHECK(!m_IsClient);\n\n if (m_IsRecording) {\n return;\n }\n\n if (!consumerThread_.joinable()) {\n consumerThread_ = std::thread{[this]() { ConsumeTimers(); }};\n }\n\n m_IsRecording = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StopRecording() {\n CHECK(!m_IsClient);\n m_IsRecording = false;\n FlushQueue();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StartClient() {\n CHECK(m_IsClient);\n m_IsRecording = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StopClient() {\n CHECK(m_IsClient);\n m_IsRecording = false;\n GTimerManager->FlushQueue();\n\n if (GTcpClient) {\n GTcpClient->FlushSendQueue();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::FlushQueue() {\n m_FlushRequested = true;\n\n const size_t numTimers = 4096;\n Timer Timers[numTimers];\n m_NumFlushedTimers = 0;\n\n while (!m_ExitRequested) {\n size_t numDequeued = m_LockFreeQueue.try_dequeue_bulk(Timers, numTimers);\n\n if (numDequeued == 0) break;\n\n m_NumQueuedEntries -= (int)numDequeued;\n m_NumFlushedTimers += (int)numDequeued;\n\n if (m_IsClient) {\n int numEntries = m_NumFlushedTimers;\n GTcpClient->Send(Msg_NumFlushedEntries, numEntries);\n }\n }\n\n m_FlushRequested = false;\n m_ConditionVariable.signal();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Stop() {\n m_IsRecording = false;\n m_ExitRequested = true;\n m_ConditionVariable.signal();\n\n if (consumerThread_.joinable()) {\n consumerThread_.join();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::ConsumeTimers() {\n SetCurrentThreadName(L\"OrbitConsumeTimers\");\n#ifdef _WIN32\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);\n#endif\n\n Timer Timer;\n\n while (!m_ExitRequested) {\n m_ConditionVariable.wait();\n\n while (!m_ExitRequested && !m_FlushRequested &&\n m_LockFreeQueue.try_dequeue(Timer)) {\n --m_NumQueuedEntries;\n --m_NumQueuedTimers;\n\n \/\/ if( Timer.m_SessionID == Message::GSessionID ) \/\/ TODO: re-enable\n \/\/ check.\n {\n for (TimerAddedCallback& Callback : m_TimerAddedCallbacks) {\n Callback(Timer);\n }\n }\n \/*else\n {\n ++m_NumTimersFromPreviousSession;\n }*\/\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::SendTimers() {\n SetCurrentThreadName(L\"OrbitSendTimers\");\n\n constexpr size_t numTimers = 4096;\n\n Timer timers[numTimers];\n\n while (!m_ExitRequested) {\n Message Msg(Msg_Timer);\n\n \/\/ Wait for non-empty queue\n while (m_NumQueuedEntries <= 0 && !m_ExitRequested) {\n m_ConditionVariable.wait();\n }\n\n size_t numDequeued = m_LockFreeQueue.try_dequeue_bulk(timers, numTimers);\n m_NumQueuedEntries -= (int)numDequeued;\n m_NumQueuedTimers -= (int)numDequeued;\n\n GTcpClient->Send(Msg, timers, numDequeued * sizeof(Timer));\n\n int numEntries = m_NumQueuedEntries;\n GTcpClient->Send(Msg_NumQueuedEntries, numEntries);\n\n while (m_LockFreeMessageQueue.try_dequeue(Msg) && !m_ExitRequested) {\n --m_NumQueuedEntries;\n --m_NumQueuedMessages;\n GTcpClient->Send(Msg);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const Timer& a_Timer) {\n if (m_IsRecording) {\n m_LockFreeQueue.enqueue(a_Timer);\n m_ConditionVariable.signal();\n ++m_NumQueuedEntries;\n ++m_NumQueuedTimers;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const Message& a_Message) {\n if (m_IsRecording || m_IsClient) {\n m_LockFreeMessageQueue.enqueue(a_Message);\n m_ConditionVariable.signal();\n ++m_NumQueuedEntries;\n ++m_NumQueuedMessages;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const ContextSwitch& a_CS) {\n if (m_ContextSwitchAddedCallback) m_ContextSwitchAddedCallback(a_CS);\n}\n<commit_msg>Fix crash when capture ends on Windows.<commit_after>\/\/-----------------------------------\n\/\/ Copyright Pierric Gimmig 2013-2017\n\/\/-----------------------------------\n\n#include \"TimerManager.h\"\n\n#include \"Message.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitLib.h\"\n#include \"Params.h\"\n#include \"TcpClient.h\"\n#include \"TcpForward.h\"\n#include \"Threading.h\"\n\n#ifdef _WIN32\n#include <direct.h>\n#endif\n\nstd::unique_ptr<TimerManager> GTimerManager;\n\n\/\/-----------------------------------------------------------------------------\nTimerManager::TimerManager(bool a_IsClient)\n : m_LockFreeQueue(65534), m_IsClient(a_IsClient) {\n m_Paused = false;\n m_IsFull = false;\n m_IsRecording = false;\n m_ExitRequested = false;\n m_FlushRequested = false;\n m_NumQueuedEntries = 0;\n m_NumQueuedTimers = 0;\n m_NumQueuedMessages = 0;\n m_TimerIndex = 0;\n m_NumTimersFromPreviousSession = 0;\n m_NumFlushedTimers = 0;\n\n if (m_IsClient) {\n GTcpClient->Start();\n consumerThread_ = std::thread{[this]() { SendTimers(); }};\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nTimerManager::~TimerManager() {}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StartRecording() {\n CHECK(!m_IsClient);\n\n if (m_IsRecording) {\n return;\n }\n\n if (!consumerThread_.joinable()) {\n consumerThread_ = std::thread{[this]() { ConsumeTimers(); }};\n }\n\n m_IsRecording = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StopRecording() {\n CHECK(!m_IsClient);\n m_IsRecording = false;\n FlushQueue();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StartClient() {\n CHECK(m_IsClient);\n m_IsRecording = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::StopClient() {\n if (!m_IsClient) return;\n m_IsRecording = false;\n GTimerManager->FlushQueue();\n\n if (GTcpClient) {\n GTcpClient->FlushSendQueue();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::FlushQueue() {\n m_FlushRequested = true;\n\n const size_t numTimers = 4096;\n Timer Timers[numTimers];\n m_NumFlushedTimers = 0;\n\n while (!m_ExitRequested) {\n size_t numDequeued = m_LockFreeQueue.try_dequeue_bulk(Timers, numTimers);\n\n if (numDequeued == 0) break;\n\n m_NumQueuedEntries -= (int)numDequeued;\n m_NumFlushedTimers += (int)numDequeued;\n\n if (m_IsClient) {\n int numEntries = m_NumFlushedTimers;\n GTcpClient->Send(Msg_NumFlushedEntries, numEntries);\n }\n }\n\n m_FlushRequested = false;\n m_ConditionVariable.signal();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Stop() {\n m_IsRecording = false;\n m_ExitRequested = true;\n m_ConditionVariable.signal();\n\n if (consumerThread_.joinable()) {\n consumerThread_.join();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::ConsumeTimers() {\n SetCurrentThreadName(L\"OrbitConsumeTimers\");\n#ifdef _WIN32\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);\n#endif\n\n Timer Timer;\n\n while (!m_ExitRequested) {\n m_ConditionVariable.wait();\n\n while (!m_ExitRequested && !m_FlushRequested &&\n m_LockFreeQueue.try_dequeue(Timer)) {\n --m_NumQueuedEntries;\n --m_NumQueuedTimers;\n\n \/\/ if( Timer.m_SessionID == Message::GSessionID ) \/\/ TODO: re-enable\n \/\/ check.\n {\n for (TimerAddedCallback& Callback : m_TimerAddedCallbacks) {\n Callback(Timer);\n }\n }\n \/*else\n {\n ++m_NumTimersFromPreviousSession;\n }*\/\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::SendTimers() {\n SetCurrentThreadName(L\"OrbitSendTimers\");\n\n constexpr size_t numTimers = 4096;\n\n Timer timers[numTimers];\n\n while (!m_ExitRequested) {\n Message Msg(Msg_Timer);\n\n \/\/ Wait for non-empty queue\n while (m_NumQueuedEntries <= 0 && !m_ExitRequested) {\n m_ConditionVariable.wait();\n }\n\n size_t numDequeued = m_LockFreeQueue.try_dequeue_bulk(timers, numTimers);\n m_NumQueuedEntries -= (int)numDequeued;\n m_NumQueuedTimers -= (int)numDequeued;\n\n GTcpClient->Send(Msg, timers, numDequeued * sizeof(Timer));\n\n int numEntries = m_NumQueuedEntries;\n GTcpClient->Send(Msg_NumQueuedEntries, numEntries);\n\n while (m_LockFreeMessageQueue.try_dequeue(Msg) && !m_ExitRequested) {\n --m_NumQueuedEntries;\n --m_NumQueuedMessages;\n GTcpClient->Send(Msg);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const Timer& a_Timer) {\n if (m_IsRecording) {\n m_LockFreeQueue.enqueue(a_Timer);\n m_ConditionVariable.signal();\n ++m_NumQueuedEntries;\n ++m_NumQueuedTimers;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const Message& a_Message) {\n if (m_IsRecording || m_IsClient) {\n m_LockFreeMessageQueue.enqueue(a_Message);\n m_ConditionVariable.signal();\n ++m_NumQueuedEntries;\n ++m_NumQueuedMessages;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid TimerManager::Add(const ContextSwitch& a_CS) {\n if (m_ContextSwitchAddedCallback) m_ContextSwitchAddedCallback(a_CS);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <platform_config.hpp>\n\n#include <hal_config.hpp>\n\nnamespace platform {\n\nMPU6000 imu(&SPID1, &mpu6000_spicfg);\nDefaultMultirotorVehicleSystem system(&imu, &imu);\n\nvoid init() {\n \/\/ Initialize platform HAL\n i2cPlatformInit();\n pwmPlatformInit();\n spiPlatformInit();\n usartPlatformInit();\n\n \/\/ Initialize platform devices\n imu.init();\n system.init();\n\n palSetPadMode(GPIOA, 6, PAL_MODE_OUTPUT_PUSHPULL);\n}\n\nmsg_t HeartbeatThread::main(void) {\n while(true) {\n palSetPad(GPIOA, 6);\n sleep(MS2ST(50));\n palClearPad(GPIOA, 6);\n sleep(MS2ST(950));\n }\n\n return 0;\n}\n\n}\n<commit_msg>Make heartbeat LED pattern for aerial_v3 fancier.<commit_after>#include <platform_config.hpp>\n\n#include <hal_config.hpp>\n\nnamespace platform {\n\nMPU6000 imu(&SPID1, &mpu6000_spicfg);\nDefaultMultirotorVehicleSystem system(&imu, &imu);\n\nvoid init() {\n \/\/ Initialize platform HAL\n i2cPlatformInit();\n pwmPlatformInit();\n spiPlatformInit();\n usartPlatformInit();\n\n \/\/ Initialize platform devices\n imu.init();\n system.init();\n\n palSetPadMode(GPIOA, 6, PAL_MODE_OUTPUT_PUSHPULL);\n palSetPadMode(GPIOA, 7, PAL_MODE_OUTPUT_PUSHPULL);\n}\n\nmsg_t HeartbeatThread::main(void) {\n while(true) {\n palSetPad(GPIOA, 6);\n sleep(MS2ST(50));\n palClearPad(GPIOA, 6);\n palSetPad(GPIOA, 7);\n sleep(MS2ST(50));\n palClearPad(GPIOA, 7);\n sleep(MS2ST(900));\n }\n\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"context.h\"\n\n#include \"check_macros.h\"\n#include \"detect_arm.h\"\n#include \"detect_x86.h\"\n#include \"have_built_path_for.h\"\n#include \"platform.h\"\n\nnamespace ruy {\n\nvoid Context::SetRuntimeEnabledPaths(Path paths) {\n runtime_enabled_paths_ = paths;\n}\n\nPath Context::GetRuntimeEnabledPaths() {\n \/\/ This function should always return the same value on a given machine.\n \/\/ When runtime_enabled_paths_ has its initial value kNone, it performs\n \/\/ some platform detection to resolve it to specific Path values.\n\n \/\/ Fast path: already resolved.\n if (runtime_enabled_paths_ != Path::kNone) {\n return runtime_enabled_paths_;\n }\n\n \/\/ Need to resolve now. Start by considering all paths enabled.\n runtime_enabled_paths_ = kAllPaths;\n\n#if RUY_PLATFORM(ARM)\n \/\/ Now selectively disable paths that aren't supported on this machine.\n if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {\n if (!DetectDotprod()) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(ARM)\n\n#if RUY_PLATFORM(X86)\n if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {\n if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);\n }\n }\n\n if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {\n if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(X86)\n\n \/\/ Sanity check. We can't possibly have disabled all paths, as some paths\n \/\/ are universally available (kReference, kStandardCpp).\n RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);\n return runtime_enabled_paths_;\n}\n\n} \/\/ namespace ruy\n<commit_msg>Ruy: Add mechanism to mask out paths.<commit_after>\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"context.h\"\n\n#include \"check_macros.h\"\n#include \"detect_arm.h\"\n#include \"detect_x86.h\"\n#include \"have_built_path_for.h\"\n#include \"platform.h\"\n\nnamespace ruy {\n\nvoid Context::SetRuntimeEnabledPaths(Path paths) {\n runtime_enabled_paths_ = paths;\n}\n\nPath Context::GetRuntimeEnabledPaths() {\n \/\/ This function should always return the same value on a given machine.\n \/\/ When runtime_enabled_paths_ has its initial value kNone, it performs\n \/\/ some platform detection to resolve it to specific Path values.\n\n \/\/ Fast path: already resolved.\n if (runtime_enabled_paths_ != Path::kNone) {\n return runtime_enabled_paths_;\n }\n\n \/\/ Need to resolve now. Start by considering all paths enabled.\n runtime_enabled_paths_ = kAllPaths;\n\n \/\/ This mechanism is intended to be used for testing and benchmarking. For\n \/\/ example, one can set RUY_FORCE_DISABLE_PATHS to Path::kAvx512 in order to\n \/\/ evaluate AVX2 performance on an AVX-512 machine.\n#ifdef RUY_FORCE_DISABLE_PATHS\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~(RUY_FORCE_DISABLE_PATHS);\n#endif\n\n#if RUY_PLATFORM(ARM)\n \/\/ Now selectively disable paths that aren't supported on this machine.\n if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {\n if (!DetectDotprod()) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(ARM)\n\n#if RUY_PLATFORM(X86)\n if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {\n if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);\n }\n }\n\n if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {\n if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(X86)\n\n \/\/ Sanity check. We can't possibly have disabled all paths, as some paths\n \/\/ are universally available (kReference, kStandardCpp).\n RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);\n return runtime_enabled_paths_;\n}\n\n} \/\/ namespace ruy\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * ParaViewFidesEngine.cpp\n *\n * Created on: Sep 21, 2022\n * Author: Caitlin Ross <caitlin.ross@kitware.com>\n *\/\n\n#include \"ParaViewFidesEngine.h\"\n\n#include <adios2\/engine\/inline\/InlineWriter.h>\n\n#include <catalyst.hpp>\n\n#include <iostream>\n#include <sstream>\n\nnamespace fides_plugin\n{\n\nstruct ParaViewFidesEngine::EngineImpl\n{\n adios2::core::IO *Io;\n adios2::core::Engine *Writer;\n\n std::string ScriptFileName;\n std::string JSONFileName;\n\n int Rank;\n\n EngineImpl(adios2::core::ADIOS &adios)\n {\n this->Io = &adios.DeclareIO(\"InlinePluginIO\");\n this->Io->SetEngine(\"inline\");\n this->Writer = &Io->Open(\"write\", adios2::Mode::Write);\n }\n\n void CatalystConfig()\n {\n std::cout << \"\\tCatalyst Library Version: \" << CATALYST_VERSION << \"\\n\";\n std::cout << \"\\tCatalyst ABI Version: \" << CATALYST_ABI_VERSION << \"\\n\";\n\n conduit_cpp::Node node;\n catalyst_about(conduit_cpp::c_node(&node));\n auto implementation = node.has_path(\"catalyst\/implementation\")\n ? node[\"catalyst\/implementation\"].as_string()\n : std::string(\"stub\");\n std::cout << \"\\tImplementation: \" << implementation << \"\\n\\n\";\n }\n\n void CatalystInit()\n {\n conduit_cpp::Node node;\n node[\"catalyst\/scripts\/script\/filename\"].set(this->ScriptFileName);\n\n \/\/ options to set up the fides reader in paraview\n std::ostringstream address;\n address << &Io;\n\n node[\"catalyst\/fides\/json_file\"].set(this->JSONFileName);\n node[\"catalyst\/fides\/data_source_io\/source\"].set(std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_io\/address\"].set(address.str());\n node[\"catalyst\/fides\/data_source_path\/source\"].set(\n std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_path\/path\"].set(\n std::string(\"DataReader\"));\n catalyst_initialize(conduit_cpp::c_node(&node));\n\n if (this->Rank == 0)\n {\n this->CatalystConfig();\n }\n }\n\n void CatalystExecute()\n {\n auto timestep = this->Writer->CurrentStep();\n conduit_cpp::Node node;\n node[\"catalyst\/state\/timestep\"].set(timestep);\n \/\/ catalyst requires the next one, but when using Fides as the reader\n \/\/ for Catalyst, it will grab the time from the correct adios variable\n \/\/ if it is specified in the data model\n node[\"catalyst\/state\/time\"].set(timestep);\n node[\"catalyst\/channels\/fides\/type\"].set(std::string(\"fides\"));\n\n \/\/ catalyst requires the data node on a channel, but we don't actually\n \/\/ need it when using fides, so just create a dummy object to pass\n \/\/ the validation in catalyst\n conduit_cpp::Node dummy;\n dummy[\"dummy\"].set(0);\n node[\"catalyst\/channels\/fides\/data\"].set(dummy);\n\n catalyst_execute(conduit_cpp::c_node(&node));\n }\n};\n\nParaViewFidesEngine::ParaViewFidesEngine(adios2::core::IO &io,\n const std::string &name,\n adios2::helper::Comm comm)\n: adios2::plugin::PluginEngineInterface(io, name, adios2::Mode::Write,\n comm.Duplicate()),\n Impl(new EngineImpl(io.m_ADIOS))\n{\n \/\/ Need to define the Variables in the IO object used for the inline engine\n const auto &varMap = io.GetVariables();\n for (const auto &it : varMap)\n {\n#define declare_type(T) \\\n if (it.second->m_Type == adios2::helper::GetDataType<T>()) \\\n { \\\n this->Impl->Io->DefineVariable<T>( \\\n it.first, it.second->m_Shape, it.second->m_Start, \\\n it.second->m_Count, it.second->IsConstantDims()); \\\n continue; \\\n }\n ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)\n#undef declare_type\n }\n\n this->Impl->Rank = comm.Rank();\n\n const auto &scriptIt = this->m_IO.m_Parameters.find(\"Script\");\n if (scriptIt != this->m_IO.m_Parameters.end())\n {\n this->Impl->ScriptFileName = scriptIt->second;\n }\n\n \/\/ TODO required for now, but support data model generation in the future\n const auto &fileIt = this->m_IO.m_Parameters.find(\"DataModel\");\n if (fileIt == this->m_IO.m_Parameters.end())\n {\n throw std::runtime_error(\"couldn't find DataModel in parameters!\");\n }\n this->Impl->JSONFileName = fileIt->second;\n\n this->Impl->CatalystInit();\n}\n\nParaViewFidesEngine::~ParaViewFidesEngine()\n{\n conduit_cpp::Node node;\n catalyst_finalize(conduit_cpp::c_node(&node));\n}\n\nadios2::StepStatus ParaViewFidesEngine::BeginStep(adios2::StepMode mode,\n const float timeoutSeconds)\n{\n return this->Impl->Writer->BeginStep(mode, timeoutSeconds);\n}\n\nsize_t ParaViewFidesEngine::CurrentStep() const\n{\n return this->Impl->Writer->CurrentStep();\n}\n\nvoid ParaViewFidesEngine::EndStep()\n{\n this->Impl->Writer->EndStep();\n\n this->Impl->CatalystExecute();\n}\n\nvoid ParaViewFidesEngine::PerformPuts() { this->Impl->Writer->PerformPuts(); }\n\n#define declare(T) \\\n void ParaViewFidesEngine::DoPutSync(adios2::core::Variable<T> &variable, \\\n const T *values) \\\n { \\\n adios2::core::Variable<T> *inlineVar = \\\n this->Impl->Io->InquireVariable<T>(variable.m_Name); \\\n this->Impl->Writer->Put(*inlineVar, values, adios2::Mode::Sync); \\\n } \\\n void ParaViewFidesEngine::DoPutDeferred( \\\n adios2::core::Variable<T> &variable, const T *values) \\\n { \\\n adios2::core::Variable<T> *inlineVar = \\\n this->Impl->Io->InquireVariable<T>(variable.m_Name); \\\n this->Impl->Writer->Put(*inlineVar, values); \\\n }\nADIOS2_FOREACH_STDTYPE_1ARG(declare)\n#undef declare\n\nvoid ParaViewFidesEngine::DoClose(const int transportIndex)\n{\n this->Impl->Writer->Close(transportIndex);\n}\n\n} \/\/ end namespace fides_plugin\n\nextern \"C\" {\n\nfides_plugin::ParaViewFidesEngine *EngineCreate(adios2::core::IO &io,\n const std::string &name,\n const adios2::Mode mode,\n adios2::helper::Comm comm)\n{\n (void)mode;\n return new fides_plugin::ParaViewFidesEngine(io, name, comm.Duplicate());\n}\n\nvoid EngineDestroy(fides_plugin::ParaViewFidesEngine *obj) { delete obj; }\n}\n<commit_msg>repeat setup from Init in Execute (Caitlin's fix)<commit_after>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * ParaViewFidesEngine.cpp\n *\n * Created on: Sep 21, 2022\n * Author: Caitlin Ross <caitlin.ross@kitware.com>\n *\/\n\n#include \"ParaViewFidesEngine.h\"\n\n#include <adios2\/engine\/inline\/InlineWriter.h>\n\n#include <catalyst.hpp>\n\n#include <iostream>\n#include <sstream>\n\nnamespace fides_plugin\n{\n\nstruct ParaViewFidesEngine::EngineImpl\n{\n adios2::core::IO *Io;\n adios2::core::Engine *Writer;\n\n std::string ScriptFileName;\n std::string JSONFileName;\n\n int Rank;\n\n EngineImpl(adios2::core::ADIOS &adios)\n {\n this->Io = &adios.DeclareIO(\"InlinePluginIO\");\n this->Io->SetEngine(\"inline\");\n this->Writer = &Io->Open(\"write\", adios2::Mode::Write);\n }\n\n void CatalystConfig()\n {\n std::cout << \"\\tCatalyst Library Version: \" << CATALYST_VERSION << \"\\n\";\n std::cout << \"\\tCatalyst ABI Version: \" << CATALYST_ABI_VERSION << \"\\n\";\n\n conduit_cpp::Node node;\n catalyst_about(conduit_cpp::c_node(&node));\n auto implementation = node.has_path(\"catalyst\/implementation\")\n ? node[\"catalyst\/implementation\"].as_string()\n : std::string(\"stub\");\n std::cout << \"\\tImplementation: \" << implementation << \"\\n\\n\";\n }\n\n void CatalystInit()\n {\n conduit_cpp::Node node;\n node[\"catalyst\/scripts\/script\/filename\"].set(this->ScriptFileName);\n\n \/\/ options to set up the fides reader in paraview\n std::ostringstream address;\n address << &Io;\n\n node[\"catalyst\/fides\/json_file\"].set(this->JSONFileName);\n node[\"catalyst\/fides\/data_source_io\/source\"].set(std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_io\/address\"].set(address.str());\n node[\"catalyst\/fides\/data_source_path\/source\"].set(\n std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_path\/path\"].set(\n std::string(\"DataReader\"));\n catalyst_initialize(conduit_cpp::c_node(&node));\n\n if (this->Rank == 0)\n {\n this->CatalystConfig();\n }\n }\n\n void CatalystExecute()\n {\n auto timestep = this->Writer->CurrentStep();\n conduit_cpp::Node node;\n node[\"catalyst\/state\/timestep\"].set(timestep);\n \/\/ catalyst requires the next one, but when using Fides as the reader\n \/\/ for Catalyst, it will grab the time from the correct adios variable\n \/\/ if it is specified in the data model\n node[\"catalyst\/state\/time\"].set(timestep);\n node[\"catalyst\/channels\/fides\/type\"].set(std::string(\"fides\"));\n\n \/\/ options to set up the fides reader in paraview\n std::ostringstream address;\n address << &Io;\n\n node[\"catalyst\/fides\/json_file\"].set(this->JSONFileName);\n node[\"catalyst\/fides\/data_source_io\/source\"].set(std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_io\/address\"].set(address.str());\n node[\"catalyst\/fides\/data_source_path\/source\"].set(\n std::string(\"source\"));\n node[\"catalyst\/fides\/data_source_path\/path\"].set(\n std::string(\"DataReader\"));\n\n \/\/ catalyst requires the data node on a channel, but we don't actually\n \/\/ need it when using fides, so just create a dummy object to pass\n \/\/ the validation in catalyst\n conduit_cpp::Node dummy;\n dummy[\"dummy\"].set(0);\n node[\"catalyst\/channels\/fides\/data\"].set(dummy);\n\n catalyst_execute(conduit_cpp::c_node(&node));\n }\n};\n\nParaViewFidesEngine::ParaViewFidesEngine(adios2::core::IO &io,\n const std::string &name,\n adios2::helper::Comm comm)\n: adios2::plugin::PluginEngineInterface(io, name, adios2::Mode::Write,\n comm.Duplicate()),\n Impl(new EngineImpl(io.m_ADIOS))\n{\n \/\/ Need to define the Variables in the IO object used for the inline engine\n const auto &varMap = io.GetVariables();\n for (const auto &it : varMap)\n {\n#define declare_type(T) \\\n if (it.second->m_Type == adios2::helper::GetDataType<T>()) \\\n { \\\n this->Impl->Io->DefineVariable<T>( \\\n it.first, it.second->m_Shape, it.second->m_Start, \\\n it.second->m_Count, it.second->IsConstantDims()); \\\n continue; \\\n }\n ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)\n#undef declare_type\n }\n\n this->Impl->Rank = comm.Rank();\n\n const auto &scriptIt = this->m_IO.m_Parameters.find(\"Script\");\n if (scriptIt != this->m_IO.m_Parameters.end())\n {\n this->Impl->ScriptFileName = scriptIt->second;\n }\n\n \/\/ TODO required for now, but support data model generation in the future\n const auto &fileIt = this->m_IO.m_Parameters.find(\"DataModel\");\n if (fileIt == this->m_IO.m_Parameters.end())\n {\n throw std::runtime_error(\"couldn't find DataModel in parameters!\");\n }\n this->Impl->JSONFileName = fileIt->second;\n\n this->Impl->CatalystInit();\n}\n\nParaViewFidesEngine::~ParaViewFidesEngine()\n{\n conduit_cpp::Node node;\n catalyst_finalize(conduit_cpp::c_node(&node));\n}\n\nadios2::StepStatus ParaViewFidesEngine::BeginStep(adios2::StepMode mode,\n const float timeoutSeconds)\n{\n return this->Impl->Writer->BeginStep(mode, timeoutSeconds);\n}\n\nsize_t ParaViewFidesEngine::CurrentStep() const\n{\n return this->Impl->Writer->CurrentStep();\n}\n\nvoid ParaViewFidesEngine::EndStep()\n{\n this->Impl->Writer->EndStep();\n\n this->Impl->CatalystExecute();\n}\n\nvoid ParaViewFidesEngine::PerformPuts() { this->Impl->Writer->PerformPuts(); }\n\n#define declare(T) \\\n void ParaViewFidesEngine::DoPutSync(adios2::core::Variable<T> &variable, \\\n const T *values) \\\n { \\\n adios2::core::Variable<T> *inlineVar = \\\n this->Impl->Io->InquireVariable<T>(variable.m_Name); \\\n this->Impl->Writer->Put(*inlineVar, values, adios2::Mode::Sync); \\\n } \\\n void ParaViewFidesEngine::DoPutDeferred( \\\n adios2::core::Variable<T> &variable, const T *values) \\\n { \\\n adios2::core::Variable<T> *inlineVar = \\\n this->Impl->Io->InquireVariable<T>(variable.m_Name); \\\n this->Impl->Writer->Put(*inlineVar, values); \\\n }\nADIOS2_FOREACH_STDTYPE_1ARG(declare)\n#undef declare\n\nvoid ParaViewFidesEngine::DoClose(const int transportIndex)\n{\n this->Impl->Writer->Close(transportIndex);\n}\n\n} \/\/ end namespace fides_plugin\n\nextern \"C\" {\n\nfides_plugin::ParaViewFidesEngine *EngineCreate(adios2::core::IO &io,\n const std::string &name,\n const adios2::Mode mode,\n adios2::helper::Comm comm)\n{\n (void)mode;\n return new fides_plugin::ParaViewFidesEngine(io, name, comm.Duplicate());\n}\n\nvoid EngineDestroy(fides_plugin::ParaViewFidesEngine *obj) { delete obj; }\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.\tYou may\n * obtain a copy of the License at\n * \n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"condor_config.h\"\n#include \"condor_constants.h\"\n#include \"condor_uid.h\"\n#include \"condor_md.h\"\n#include \"directory_util.h\"\n#include \"file_lock.h\"\n#include \"filename_tools.h\"\n#include \"stat_wrapper.h\"\n#include <sys\/stat.h>\n#include <stdlib.h>\n#include <string> \n\n#ifndef WIN32\n\t#include <unistd.h>\n#endif\n\n#ifdef HAVE_HTTP_PUBLIC_FILES\n\nusing namespace std;\n\nnamespace {\t\/\/ Anonymous namespace to limit scope of names to this file\n\t\nconst int HASHNAMELEN = 17;\n\n\nstatic string MakeHashName(const char* fileName, time_t fileModifiedTime) {\n\n\tunsigned char hashResult[HASHNAMELEN * 3]; \/\/ Allocate extra space for safety.\n\n\t\/\/ Convert the modified time to a string object\n\tstd::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime);\n\n\t\/\/ Create a new string which will be the source for our hash function.\n\t\/\/ This will append two strings:\n\t\/\/ 1. Full path to the file\n\t\/\/ 2. Modified time of the file\n\tunsigned char* hashSource = new unsigned char[strlen(fileName) \n\t\t\t\t\t\t\t\t\t+ strlen(modifiedTimeStr.c_str()) + 1];\n\tstrcpy( (char*) hashSource, fileName );\n\tstrcat( (char*) hashSource, modifiedTimeStr.c_str() );\n\n\t\/\/ Now calculate the hash\n\tmemcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource,\n\t\tstrlen((const char*) hashSource)), HASHNAMELEN);\n\tchar entryHashName[HASHNAMELEN * 2]; \/\/ 2 chars per hex byte\n\tentryHashName[0] = '\\0';\n\tchar letter[3];\n\tfor (int i = 0; i < HASHNAMELEN - 1; ++i) {\n\t\tsprintf(letter, \"%x\", hashResult[i]);\n\t\tstrcat(entryHashName, letter);\n\t}\n\n\treturn entryHashName;\n}\n\n\n\/\/ WARNING! This code changes priv state. Be very careful if modifying it.\n\/\/ Do not return in the block of code where the priv has been set to either\n\/\/ condor or root. -zmiller\nstatic bool MakeLink(const char* srcFilePath, const string &newLink) {\n\n\tbool retVal = false;\n\tint srcFileInodeNum;\n\tint targetLinkInodeNum;\n\tstruct stat srcFileStat;\n\tstruct stat targetLinkStat;\n\n\t\/\/ Make sure the necessary parameters are set\n\tstd::string webRootDir;\n\tparam(webRootDir, \"HTTP_PUBLIC_FILES_ROOT_DIR\");\n\tif(webRootDir.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tstd::string webRootOwner;\n\tparam(webRootOwner, \"HTTP_PUBLIC_FILES_ROOT_OWNER\");\n\tif(webRootOwner.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_OWNER \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tchar goodPath[PATH_MAX];\n\tif (realpath(webRootDir.c_str(), goodPath) == NULL) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\"not a valid path: %s. Falling back to regular file transfer.\\n\",\n\t\t\twebRootDir.c_str());\n\t\treturn (false);\n\t}\n\n\t\/\/ Determine the full path of the access file. Save it to a std::string and\n\t\/\/ deallocate the memory that dircat() returned.\n\tchar* hardLinkFilePath = dircat(goodPath, newLink.c_str());\n\tstd::string accessFilePath(hardLinkFilePath);\n\taccessFilePath += \".access\";\n\tdelete [] hardLinkFilePath;\n\t\n\t\/\/ STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING\n\t\/\/ THE ORIGINAL PRIV STATE.\n\t\n\t\/\/ Check if an access file exists (which will be the case if someone has\n\t\/\/ already sent the source file).\n\t\/\/ If it does exist, lock it so that condor_preen cannot open it while\n\t\/\/ garbage collecting.\n\t\/\/ If it does not exist, carry on. We'll create it before exiting.\n\t\n\tpriv_state original_priv = set_root_priv();\n\tFileLock *accessFileLock = NULL;\n\t\n\tif(access(accessFilePath.c_str(), F_OK) == 0) {\n\t\taccessFileLock = new FileLock(accessFilePath.c_str(), true, false);\n\n\t\t\/\/ Try to grab a lock on the access file. This should block until it \n\t\t\/\/ obtains the lock. If this fails for any reason, bail out.\n\t\tbool obtainedLock = accessFileLock->obtain(WRITE_LOCK);\n\t\tif(!obtainedLock) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Failed to obtain lock on access file with\"\n\t\t\t\t\" error code %d (%s).\\n\", errno, strerror(errno));\n\t\t\tset_priv(original_priv);\n\t\t\treturn (false);\n\t\t}\n\t}\n\t\n\t\/\/ Impersonate the user and open the file using safe_open(). This will allow\n\t\/\/ us to verify the user has privileges to access the file, and later to\n\t\/\/ verify the hard link points back to the same inode.\n\tset_user_priv();\n\t\n\tbool fileOK = false;\n\tFILE *srcFile = safe_fopen_wrapper(srcFilePath, \"r\");\n\tif (srcFile) {\n\t\tif(stat(srcFilePath, &srcFileStat) == 0) {\n\t\t\tsrcFileInodeNum = srcFileStat.st_ino;\n\t\t\tfileOK = (srcFileStat.st_mode & S_IRUSR); \/\/ Verify readable by owner\n\t\t}\n\t}\n\tif (fileOK == false) {\n\t\tdprintf(D_ALWAYS, \"MakeLink: Cannot transfer -- public input file not \"\n\t\t\t\"readable by user: %s\\n\", srcFilePath);\n\t\tset_priv(original_priv);\n\t\treturn (false);\n\t}\n\tfclose(srcFile);\n\n\t\/\/ Create the hard link using root privileges; it will automatically get\n\t\/\/ owned by the same owner of the file. If the link already exists, don't do \n\t\/\/ anything at this point, we'll check later to make sure it points to the\n\t\/\/ correct inode.\n\tconst char *const targetLinkPath = dircat(goodPath, newLink.c_str()); \/\/ needs to be freed\n\n\t\/\/ Switch to root privileges, so we can test if the link exists, and create\n\t\/\/ it if it does not\n\tset_root_priv();\n\t\n\t\/\/ Check if target link already exists\n\tFILE *targetLink = safe_fopen_wrapper(targetLinkPath, \"r\");\n\tif (targetLink) {\n\t\t\/\/ If link exists, update the .access file timestamp.\n\t\tretVal = true;\n\t\tfclose(targetLink);\n\t}\t\n\telse {\n\t\t\/\/ Link does not exist, so create it as root.\n\t\tif (link(srcFilePath, targetLinkPath) == 0) {\n\t\t\t\/\/ so far, so good!\n\t\t\tretVal = true;\n\t\t}\n\t\telse {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Could not link %s to %s, error: %s\\n\", \n\t\t\t\ttargetLinkPath, srcFilePath, strerror(errno));\n\t\t}\n\t}\n\n\t\/\/ Now we need to make sure nothing devious has happened, that the hard link \n\t\/\/ points to the file we're expecting. First, make sure that the user \n\t\/\/ specified by HTTP_PUBLIC_FILES_ROOT_OWNER is a valid user.\n\tuid_t link_uid = -1;\n\tgid_t link_gid = -1;\n\tbool isValidUser = pcache()->get_user_ids(webRootOwner.c_str(), link_uid, link_gid);\n\tif (!isValidUser) {\n\t\tdprintf(D_ALWAYS, \"Unable to look up HTTP_PUBLIC_FILES_ROOT_OWNER (%s)\"\n\t\t\t\t\" in \/etc\/passwd. Aborting.\\n\", webRootOwner.c_str());\n\t\tretVal = false;\n\t}\n\n\tif (link_uid == 0 || link_gid == 0) {\n\t\tdprintf(D_ALWAYS, \"HTTP_PUBLIC_FILES_ROOT_OWNER (%s)\"\n\t\t\t\" in \/etc\/passwd has UID 0. Aborting.\\n\", webRootOwner.c_str());\n\t\tretVal = false;\n\t}\n\n\t\/\/ Now that we've verified HTTP_PUBLIC_FILES_ROOT_OWNER is a valid user, \n\t\/\/ switch privileges to this user. Open the hard link. Verify that the\n\t\/\/ inode is the same as the file we opened earlier on.\t\n\tif (retVal == true) {\n\t\tif(setegid(link_gid) == -1) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Error switching to group ID %d\\n\", link_gid);\n\t\t\tretVal = false;\n\t\t}\n\t\tif(seteuid(link_uid) == -1) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Error switching to user ID %d\\n\", link_uid);\n\t\t\tretVal = false;\n\t\t}\n\n\t\tif (stat(targetLinkPath, &targetLinkStat) == 0) {\n\t\t\ttargetLinkInodeNum = targetLinkStat.st_ino;\n\t\t\tif (srcFileInodeNum == targetLinkInodeNum) {\n\t\t\t\tretVal = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_ALWAYS, \"Source file %s inode (%d) does not match \"\n\t\t\t\t\t\"hard link %s inode (%d), aborting.\\n\", srcFilePath, \n\t\t\t\t\tsrcFileInodeNum, targetLinkPath, targetLinkInodeNum);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tretVal = false;\n\t\t\tdprintf(D_ALWAYS, \"Cannot open hard link %s as user %s. Reverting to \"\n\t\t\t\t\"regular file transfer.\\n\", targetLinkPath, webRootOwner.c_str());\n\t\t}\n\t}\n\t\n\t\/\/ Touch the access file. This will create it if it doesn't exist, or update\n\t\/\/ the timestamp if it does.\n\tFILE* accessFile = fopen(accessFilePath.c_str(), \"w\");\n\tif (!accessFile) {\n\t\tdprintf(D_ALWAYS, \"Failed to update access file %s.\\n\", accessFilePath.c_str());\n\t}\n\tfclose(accessFile);\n\t\n\t\/\/ Release the lock on the access file\n\tif(!accessFileLock->release()) {\n\t\tdprintf(D_ALWAYS, \"MakeLink: Failed to release lock on access file with\"\n\t\t\t\" error code %d (%s).\\n\", errno, strerror(errno));\n\t}\n\n\t\/\/ Free the target link path\n\tdelete [] targetLinkPath;\n\n\t\/\/ Reset priv state\n\tset_priv(original_priv);\n\n\treturn retVal;\n}\n\nstatic string MakeAbsolutePath(const char* path, const char* initialWorkingDir) {\n\tif (is_relative_to_cwd(path)) {\n\t\tstring fullPath = initialWorkingDir;\n\t\tfullPath += DIR_DELIM_CHAR;\n\t\tfullPath += path;\n\t\treturn (fullPath);\n\t}\n\treturn (path);\n}\n\n} \/\/ end namespace\n\nvoid ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles,\n\tStringList &PubInpFiles) {\n\n\tchar *initialWorkingDir = NULL;\n\tconst char *path;\n\tMyString remap;\n\tstruct stat fileStat;\n\ttime_t fileModifiedTime = time(NULL);\n\n\tif (PubInpFiles.isEmpty() == false) {\n\t\tconst char *webServerAddress = param(\"HTTP_PUBLIC_FILES_ADDRESS\");\n\n\t\t\/\/ If a web server address is not defined, exit quickly. The file\n\t\t\/\/ transfer will go on using the regular CEDAR protocol.\n\t\tif(!webServerAddress) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS \"\n\t\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Build out the base URL for public files\n\t\tstring url = \"http:\/\/\";\n\t\turl += webServerAddress; \n\t\turl += \"\/\";\n\n\t\tPubInpFiles.rewind();\n\t\t\n\t\tif (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Job ad did not have an \"\n\t\t\t\t\"initialWorkingDir! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\t\twhile ((path = PubInpFiles.next()) != NULL) {\n\t\t\t\/\/ Determine the full path of the file to be transferred\n\t\t\tstring fullPath = MakeAbsolutePath(path, initialWorkingDir);\n\n\t\t\t\/\/ Determine the time last modified of the file to be transferred\n\t\t\tif( stat( fullPath.c_str(), &fileStat ) == 0 ) {\n\t\t\t\tstruct timespec fileTime = fileStat.st_mtim;\n\t\t\t\tfileModifiedTime = fileTime.tv_sec;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Unable to access file \"\n\t\t\t\t\t\"%s. Falling back to regular file transfer\\n\", fullPath.c_str());\n\t\t\t\tfree( initialWorkingDir );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstring hashName = MakeHashName( fullPath.c_str(), fileModifiedTime );\n\t\t\tif (MakeLink(fullPath.c_str(), hashName)) {\n\t\t\t\tInputFiles->remove(path); \/\/ Remove plain file name from InputFiles\n\t\t\t\tremap += hashName;\n\t\t\t\tremap += \"=\";\n\t\t\t\tremap += basename(path);\n\t\t\t\tremap += \";\";\n\t\t\t\thashName = url + hashName;\n\t\t\t\tconst char *const namePtr = hashName.c_str();\n\t\t\t\tif ( !InputFiles->contains(namePtr) ) {\n\t\t\t\t\tInputFiles->append(namePtr);\n\t\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Adding url to \"\n\t\t\t\t\t\t\t\t\t\t\t\t\"InputFiles: %s\\n\", namePtr);\n\t\t\t\t} \n\t\t\t\telse dprintf(D_FULLDEBUG, \"mk_cache_links.cpp: url already \"\n\t\t\t\t\t\t\t\t\t\t\t\"in InputFiles: %s\\n\", namePtr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Failed to generate \"\n\t\t\t\t\t\t\t\t\t \"hash link for %s\\n\", fullPath.c_str());\n\t\t\t}\n\t\t}\n\t\tfree( initialWorkingDir );\n\t\tif ( remap.Length() > 0 ) {\n\t\t\tMyString remapnew;\n\t\t\tchar *buf = NULL;\n\t\t\tif (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) {\n\t\t\t\tremapnew = buf;\n\t\t\t\tfree(buf);\n\t\t\t\tbuf = NULL;\n\t\t\t\tremapnew += \";\";\n\t\t\t} \n\t\t\tremapnew += remap;\n\t\t\tif (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) {\n\t\t\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: Could not add to jobAd: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"%s\\n\", remap.c_str());\n\t\t\t}\n\t\t}\n\t} \n\telse\t\n\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: No public input files.\\n\");\n}\n\n#endif\n\n<commit_msg>More Coverity fixes (#6452)<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.\tYou may\n * obtain a copy of the License at\n * \n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"condor_config.h\"\n#include \"condor_constants.h\"\n#include \"condor_uid.h\"\n#include \"condor_md.h\"\n#include \"directory_util.h\"\n#include \"file_lock.h\"\n#include \"filename_tools.h\"\n#include \"stat_wrapper.h\"\n#include <sys\/stat.h>\n#include <stdlib.h>\n#include <string> \n\n#ifndef WIN32\n\t#include <unistd.h>\n#endif\n\n#ifdef HAVE_HTTP_PUBLIC_FILES\n\nusing namespace std;\n\nnamespace {\t\/\/ Anonymous namespace to limit scope of names to this file\n\t\nconst int HASHNAMELEN = 17;\n\n\nstatic string MakeHashName(const char* fileName, time_t fileModifiedTime) {\n\n\tunsigned char hashResult[HASHNAMELEN * 3]; \/\/ Allocate extra space for safety.\n\n\t\/\/ Convert the modified time to a string object\n\tstd::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime);\n\n\t\/\/ Create a new string which will be the source for our hash function.\n\t\/\/ This will append two strings:\n\t\/\/ 1. Full path to the file\n\t\/\/ 2. Modified time of the file\n\tunsigned char* hashSource = new unsigned char[strlen(fileName) \n\t\t\t\t\t\t\t\t\t+ strlen(modifiedTimeStr.c_str()) + 1];\n\tstrcpy( (char*) hashSource, fileName );\n\tstrcat( (char*) hashSource, modifiedTimeStr.c_str() );\n\n\t\/\/ Now calculate the hash\n\tmemcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource,\n\t\tstrlen((const char*) hashSource)), HASHNAMELEN);\n\tchar entryHashName[HASHNAMELEN * 2]; \/\/ 2 chars per hex byte\n\tentryHashName[0] = '\\0';\n\tchar letter[3];\n\tfor (int i = 0; i < HASHNAMELEN - 1; ++i) {\n\t\tsprintf(letter, \"%x\", hashResult[i]);\n\t\tstrcat(entryHashName, letter);\n\t}\n\n\treturn entryHashName;\n}\n\n\n\/\/ WARNING! This code changes priv state. Be very careful if modifying it.\n\/\/ Do not return in the block of code where the priv has been set to either\n\/\/ condor or root. -zmiller\nstatic bool MakeLink(const char* srcFilePath, const string &newLink) {\n\n\tbool retVal = false;\n\tint srcFileInodeNum;\n\tint targetLinkInodeNum;\n\tstruct stat srcFileStat;\n\tstruct stat targetLinkStat;\n\n\t\/\/ Make sure the necessary parameters are set\n\tstd::string webRootDir;\n\tparam(webRootDir, \"HTTP_PUBLIC_FILES_ROOT_DIR\");\n\tif(webRootDir.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tstd::string webRootOwner;\n\tparam(webRootOwner, \"HTTP_PUBLIC_FILES_ROOT_OWNER\");\n\tif(webRootOwner.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_OWNER \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tchar goodPath[PATH_MAX];\n\tif (realpath(webRootDir.c_str(), goodPath) == NULL) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\"not a valid path: %s. Falling back to regular file transfer.\\n\",\n\t\t\twebRootDir.c_str());\n\t\treturn (false);\n\t}\n\n\t\/\/ Determine the full path of the access file. Save it to a std::string and\n\t\/\/ deallocate the memory that dircat() returned.\n\tchar* hardLinkFilePath = dircat(goodPath, newLink.c_str());\n\tstd::string accessFilePath(hardLinkFilePath);\n\taccessFilePath += \".access\";\n\tdelete [] hardLinkFilePath;\n\t\n\t\/\/ STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING\n\t\/\/ THE ORIGINAL PRIV STATE.\n\t\n\t\/\/ Check if an access file exists (which will be the case if someone has\n\t\/\/ already sent the source file).\n\t\/\/ If it does exist, lock it so that condor_preen cannot open it while\n\t\/\/ garbage collecting.\n\t\/\/ If it does not exist, carry on. We'll create it before exiting.\n\t\n\tpriv_state original_priv = set_root_priv();\n\tFileLock *accessFileLock = NULL;\n\t\n\tif(access(accessFilePath.c_str(), F_OK) == 0) {\n\t\taccessFileLock = new FileLock(accessFilePath.c_str(), true, false);\n\n\t\t\/\/ Try to grab a lock on the access file. This should block until it \n\t\t\/\/ obtains the lock. If this fails for any reason, bail out.\n\t\tbool obtainedLock = accessFileLock->obtain(WRITE_LOCK);\n\t\tif(!obtainedLock) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Failed to obtain lock on access file with\"\n\t\t\t\t\" error code %d (%s).\\n\", errno, strerror(errno));\n\t\t\tset_priv(original_priv);\n\t\t\treturn (false);\n\t\t}\n\t}\n\t\n\t\/\/ Impersonate the user and open the file using safe_open(). This will allow\n\t\/\/ us to verify the user has privileges to access the file, and later to\n\t\/\/ verify the hard link points back to the same inode.\n\tset_user_priv();\n\t\n\tbool fileOK = false;\n\tFILE *srcFile = safe_fopen_wrapper(srcFilePath, \"r\");\n\tif (srcFile) {\n\t\tif(stat(srcFilePath, &srcFileStat) == 0) {\n\t\t\tsrcFileInodeNum = srcFileStat.st_ino;\n\t\t\tfileOK = (srcFileStat.st_mode & S_IRUSR); \/\/ Verify readable by owner\n\t\t}\n\t}\n\tif (fileOK == false) {\n\t\tdprintf(D_ALWAYS, \"MakeLink: Cannot transfer -- public input file not \"\n\t\t\t\"readable by user: %s\\n\", srcFilePath);\n\t\tset_priv(original_priv);\n\t\treturn (false);\n\t}\n\tfclose(srcFile);\n\n\t\/\/ Create the hard link using root privileges; it will automatically get\n\t\/\/ owned by the same owner of the file. If the link already exists, don't do \n\t\/\/ anything at this point, we'll check later to make sure it points to the\n\t\/\/ correct inode.\n\tconst char *const targetLinkPath = dircat(goodPath, newLink.c_str()); \/\/ needs to be freed\n\n\t\/\/ Switch to root privileges, so we can test if the link exists, and create\n\t\/\/ it if it does not\n\tset_root_priv();\n\t\n\t\/\/ Check if target link already exists\n\tFILE *targetLink = safe_fopen_wrapper(targetLinkPath, \"r\");\n\tif (targetLink) {\n\t\t\/\/ If link exists, update the .access file timestamp.\n\t\tretVal = true;\n\t\tdelete [] targetLinkPath;\n\t\tfclose(targetLink);\n\t}\t\n\telse {\n\t\t\/\/ Link does not exist, so create it as root.\n\t\tif (link(srcFilePath, targetLinkPath) == 0) {\n\t\t\t\/\/ so far, so good!\n\t\t\tretVal = true;\n\t\t}\n\t\telse {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Could not link %s to %s, error: %s\\n\", \n\t\t\t\ttargetLinkPath, srcFilePath, strerror(errno));\n\t\t}\n\t}\n\n\t\/\/ Now we need to make sure nothing devious has happened, that the hard link \n\t\/\/ points to the file we're expecting. First, make sure that the user \n\t\/\/ specified by HTTP_PUBLIC_FILES_ROOT_OWNER is a valid user.\n\tuid_t link_uid = -1;\n\tgid_t link_gid = -1;\n\tbool isValidUser = pcache()->get_user_ids(webRootOwner.c_str(), link_uid, link_gid);\n\tif (!isValidUser) {\n\t\tdprintf(D_ALWAYS, \"Unable to look up HTTP_PUBLIC_FILES_ROOT_OWNER (%s)\"\n\t\t\t\t\" in \/etc\/passwd. Aborting.\\n\", webRootOwner.c_str());\n\t\tretVal = false;\n\t}\n\n\tif (link_uid == 0 || link_gid == 0) {\n\t\tdprintf(D_ALWAYS, \"HTTP_PUBLIC_FILES_ROOT_OWNER (%s)\"\n\t\t\t\" in \/etc\/passwd has UID 0. Aborting.\\n\", webRootOwner.c_str());\n\t\tretVal = false;\n\t}\n\n\t\/\/ Now that we've verified HTTP_PUBLIC_FILES_ROOT_OWNER is a valid user, \n\t\/\/ switch privileges to this user. Open the hard link. Verify that the\n\t\/\/ inode is the same as the file we opened earlier on.\t\n\tif (retVal == true) {\n\t\tif(setegid(link_gid) == -1) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Error switching to group ID %d\\n\", link_gid);\n\t\t\tretVal = false;\n\t\t}\n\t\tif(seteuid(link_uid) == -1) {\n\t\t\tdprintf(D_ALWAYS, \"MakeLink: Error switching to user ID %d\\n\", link_uid);\n\t\t\tretVal = false;\n\t\t}\n\n\t\tif (stat(targetLinkPath, &targetLinkStat) == 0) {\n\t\t\ttargetLinkInodeNum = targetLinkStat.st_ino;\n\t\t\tif (srcFileInodeNum == targetLinkInodeNum) {\n\t\t\t\tretVal = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_ALWAYS, \"Source file %s inode (%d) does not match \"\n\t\t\t\t\t\"hard link %s inode (%d), aborting.\\n\", srcFilePath, \n\t\t\t\t\tsrcFileInodeNum, targetLinkPath, targetLinkInodeNum);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tretVal = false;\n\t\t\tdprintf(D_ALWAYS, \"Cannot open hard link %s as user %s. Reverting to \"\n\t\t\t\t\"regular file transfer.\\n\", targetLinkPath, webRootOwner.c_str());\n\t\t}\n\t}\n\t\n\t\/\/ Touch the access file. This will create it if it doesn't exist, or update\n\t\/\/ the timestamp if it does.\n\tFILE* accessFile = fopen(accessFilePath.c_str(), \"w\");\n\tif (accessFile) {\n\t\tfclose(accessFile);\n\t}\n\telse {\n\t\tdprintf(D_ALWAYS, \"Failed to update access file %s.\\n\", accessFilePath.c_str());\n\t}\n\t\n\t\/\/ Release the lock on the access file\n\tif(!accessFileLock->release()) {\n\t\tdprintf(D_ALWAYS, \"MakeLink: Failed to release lock on access file with\"\n\t\t\t\" error code %d (%s).\\n\", errno, strerror(errno));\n\t}\n\n\t\/\/ Free the target link path\n\tdelete [] targetLinkPath;\n\n\t\/\/ Reset priv state\n\tset_priv(original_priv);\n\n\treturn retVal;\n}\n\nstatic string MakeAbsolutePath(const char* path, const char* initialWorkingDir) {\n\tif (is_relative_to_cwd(path)) {\n\t\tstring fullPath = initialWorkingDir;\n\t\tfullPath += DIR_DELIM_CHAR;\n\t\tfullPath += path;\n\t\treturn (fullPath);\n\t}\n\treturn (path);\n}\n\n} \/\/ end namespace\n\nvoid ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles,\n\tStringList &PubInpFiles) {\n\n\tchar *initialWorkingDir = NULL;\n\tconst char *path;\n\tMyString remap;\n\tstruct stat fileStat;\n\ttime_t fileModifiedTime = time(NULL);\n\n\tif (PubInpFiles.isEmpty() == false) {\n\t\tconst char *webServerAddress = param(\"HTTP_PUBLIC_FILES_ADDRESS\");\n\n\t\t\/\/ If a web server address is not defined, exit quickly. The file\n\t\t\/\/ transfer will go on using the regular CEDAR protocol.\n\t\tif(!webServerAddress) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS \"\n\t\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Build out the base URL for public files\n\t\tstring url = \"http:\/\/\";\n\t\turl += webServerAddress; \n\t\turl += \"\/\";\n\n\t\tPubInpFiles.rewind();\n\t\t\n\t\tif (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Job ad did not have an \"\n\t\t\t\t\"initialWorkingDir! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\t\twhile ((path = PubInpFiles.next()) != NULL) {\n\t\t\t\/\/ Determine the full path of the file to be transferred\n\t\t\tstring fullPath = MakeAbsolutePath(path, initialWorkingDir);\n\n\t\t\t\/\/ Determine the time last modified of the file to be transferred\n\t\t\tif( stat( fullPath.c_str(), &fileStat ) == 0 ) {\n\t\t\t\tstruct timespec fileTime = fileStat.st_mtim;\n\t\t\t\tfileModifiedTime = fileTime.tv_sec;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Unable to access file \"\n\t\t\t\t\t\"%s. Falling back to regular file transfer\\n\", fullPath.c_str());\n\t\t\t\tfree( initialWorkingDir );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstring hashName = MakeHashName( fullPath.c_str(), fileModifiedTime );\n\t\t\tif (MakeLink(fullPath.c_str(), hashName)) {\n\t\t\t\tInputFiles->remove(path); \/\/ Remove plain file name from InputFiles\n\t\t\t\tremap += hashName;\n\t\t\t\tremap += \"=\";\n\t\t\t\tremap += basename(path);\n\t\t\t\tremap += \";\";\n\t\t\t\thashName = url + hashName;\n\t\t\t\tconst char *const namePtr = hashName.c_str();\n\t\t\t\tif ( !InputFiles->contains(namePtr) ) {\n\t\t\t\t\tInputFiles->append(namePtr);\n\t\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Adding url to \"\n\t\t\t\t\t\t\t\t\t\t\t\t\"InputFiles: %s\\n\", namePtr);\n\t\t\t\t} \n\t\t\t\telse dprintf(D_FULLDEBUG, \"mk_cache_links.cpp: url already \"\n\t\t\t\t\t\t\t\t\t\t\t\"in InputFiles: %s\\n\", namePtr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Failed to generate \"\n\t\t\t\t\t\t\t\t\t \"hash link for %s\\n\", fullPath.c_str());\n\t\t\t}\n\t\t}\n\t\tfree( initialWorkingDir );\n\t\tif ( remap.Length() > 0 ) {\n\t\t\tMyString remapnew;\n\t\t\tchar *buf = NULL;\n\t\t\tif (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) {\n\t\t\t\tremapnew = buf;\n\t\t\t\tfree(buf);\n\t\t\t\tbuf = NULL;\n\t\t\t\tremapnew += \";\";\n\t\t\t} \n\t\t\tremapnew += remap;\n\t\t\tif (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) {\n\t\t\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: Could not add to jobAd: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"%s\\n\", remap.c_str());\n\t\t\t}\n\t\t}\n\t} \n\telse\t\n\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: No public input files.\\n\");\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/* $Id$ *\/\n\n\/\/---\n\/\/ Produces the data needed to calculate the quality assurance. \n\/\/ All data must be mergeable objects.\n\/\/ A. Mastroserio\n\/\/---\n\n\/\/ --- ROOT system ---\n#include <TClonesArray.h>\n#include <TFile.h> \n#include <TH1F.h> \n#include <TH2F.h>\n#include <TH1I.h> \n#include <TDirectory.h>\n#include <Riostream.h>\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliESDCaloCluster.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n#include \"AliHMPIDDigit.h\"\n#include \"AliHMPIDHit.h\"\n#include \"AliHMPIDCluster.h\"\n#include \"AliHMPIDQualAssDataMaker.h\"\n\nClassImp(AliHMPIDQualAssDataMaker)\n \n\/\/____________________________________________________________________________ \n AliHMPIDQualAssDataMaker::AliHMPIDQualAssDataMaker() : \n AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kHMPID), \"HMPID Quality Assurance Data Maker\"),\n fhHitQdc(0x0), \n fhSDigits(0x0),\n fhDigPcEvt(0x0),\n fhDigChEvt(0x0),\n fhDigQ(0x0),\n fhCluEvt(0x0),\n fhCluChi2(0x0),\n fhCluQ(0x0),\n fhCluFlg(0x0), \n fhCluSize(0x0), \n fhMipCluSize(0x0),\n fhCkovP(0x0),\n fhSigP(0x0),\n fhMipXY(0x0),\n fhDifXY(0x0)\n{\n \/\/ ctor\n for(Int_t i=0; i<7; i++) fhHitMap[i]=0x0;\n for(Int_t j=0; j<5; j++) fhPid[j]=0x0;\n fDetectorDir = fOutput->GetDirectory(GetName()) ; \n if (!fDetectorDir) \n fDetectorDir = fOutput->mkdir(GetName()) ; \n}\n\n\/\/____________________________________________________________________________ \nAliHMPIDQualAssDataMaker::AliHMPIDQualAssDataMaker(const AliHMPIDQualAssDataMaker& qadm) :\n AliQualAssDataMaker(), \n fhHitQdc(qadm.fhHitQdc), \n fhSDigits(qadm.fhSDigits),\n fhDigPcEvt(qadm.fhDigPcEvt),\n fhDigChEvt(qadm.fhDigChEvt),\n fhDigQ(qadm.fhDigQ),\n fhCluEvt(qadm.fhCluEvt),\n fhCluChi2(qadm.fhCluChi2),\n fhCluQ(qadm.fhCluQ),\n fhCluFlg(qadm.fhCluFlg),\n fhCluSize(qadm.fhCluSize),\n fhMipCluSize(qadm.fhMipCluSize),\n fhCkovP(qadm.fhCkovP),\n fhSigP(qadm.fhSigP),\n fhMipXY(qadm.fhMipXY),\n fhDifXY(qadm.fhDifXY)\n{\n \/\/copy ctor \n for(Int_t i=0; i<7; i++) fhHitMap[i]=qadm.fhHitMap[i];\n for(Int_t j=0; j<5; j++) fhPid[j]=qadm.fhPid[j];\n\n SetName((const char*)qadm.GetName()) ; \n SetTitle((const char*)qadm.GetTitle()); \n}\n\n\/\/__________________________________________________________________\nAliHMPIDQualAssDataMaker& AliHMPIDQualAssDataMaker::operator = (const AliHMPIDQualAssDataMaker& qadm )\n{\n \/\/ Equal operator.\n this->~AliHMPIDQualAssDataMaker();\n new(this) AliHMPIDQualAssDataMaker(qadm);\n return *this;\n}\n \n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitHits()\n{\n \/\/ create Hits histograms in Hits subdir\n fhHitQdc=new TH1F(\"HitQdc\",\"HMPID Hit Qdc all chamber;QDC\",500,0,4000);\n for(Int_t iCh=0;iCh<7;iCh++) fhHitMap[iCh]=new TH2F(Form(\"HMPID HitMap%i\",iCh),Form(\"Ch%i;x_{Hit};y_{Hit}\",iCh),162,-1,161,146,-1,145); \n}\n\n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitDigits()\n{\n \/\/ create Digits histograms in Digits subdir\n fhDigPcEvt=new TH1F(\"hDigPcEvt\",\"PC occupancy\",156,-1,77);\n fhDigChEvt=new TH1F(\"hDigChEvt\",\"Chamber occupancy\",32,-1,7);\n fhDigQ =new TH1F(\"Q \",\" digit charge \",3000,0,3000);\n}\n\n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitSDigits()\n{\n \/\/ create SDigits histograms in SDigits subdir\n fhSDigits = new TH1F(\"hHmpidSDigits\", \"SDigits Q distribution in HMPID\", 500, 0., 5000.) ; \n}\n\n\/\/____________________________________________________________________________ \n\nvoid AliHMPIDQualAssDataMaker::InitRecPoints()\n{\n \/\/ create cluster histograms in RecPoint subdir\n fhCluEvt=new TH1F(\"CluPerEvt\",\"# clusters per chamber\",16,-1,7);\n fhCluChi2 =new TH1F(\"CluChi2\" ,\"Chi2 \" ,1000,0,100);\n fhCluQ =new TH1F(\"CluQ\" ,\"Cluster charge\" ,3000,0,3000);\n fhCluFlg =new TH1F(\"CluFlg\" ,\"Cluster flag\" ,14,-1.5,12.5);\n fhCluSize =new TH1F(\"CluSize\" ,\"Raw cluster size \",100,0,100);\n fhMipCluSize =new TH1F(\"MipCluSize\" ,\"Mip cluster size \",100,0,100);\n}\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::InitESDs()\n{\n \/\/create ESDs histograms in ESDs subdir\n fhCkovP = new TH2F(\"CkovP\" , \"#theta_{c}, [rad];P, [GeV]\" , 150, 0, 7 ,100, 0, 1) ;\n fhSigP = new TH2F(\"SigP\" ,\"#sigma_{#theta_c} [mrad];[GeV]\", 150, 0, 7 ,100, 0, 1) ;\n fhMipXY = new TH2F(\"MipXY\" ,\"mip position\" , 260, 0,130 ,252, 0,126) ;\n fhDifXY = new TH2F(\"DifXY\" ,\"diff\" , 200, -10, 10 ,200,-10,10) ;\n fhPid[0] = new TH1F(\"PidE\" ,\"PID: e yellow #mu magenta\" ,100,0,1) ;\n fhPid[1] = new TH1F(\"PidMu\",\"pid of #mu\" ,100,0,1) ;\n fhPid[2] = new TH1F(\"PidPi\",\"PID: #pi red K green p blue\",100,0,1) ;\n fhPid[3] = new TH1F(\"PidK\" ,\"pid of K\" ,100,0,1) ;\n fhPid[4] = new TH1F(\"PidP\" ,\"pid of p\" ,100,0,1) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeHits(TObject * data)\n{\n \/\/fills QA histos for Hits\n TClonesArray * hits = dynamic_cast<TClonesArray *>(data) ; \n if (!hits){\n AliError(\"Wrong type of hits container\") ; \n } else {\n TIter next(hits); \n AliHMPIDHit * hit ; \n while ( (hit = dynamic_cast<AliHMPIDHit *>(next())) ) {\n if(hit->Pid()<500000) fhHitQdc->Fill(hit->Q()) ;\n if(hit->Pid()<500000) fhHitMap[hit->Ch()]->Fill(hit->LorsX(),hit->LorsY());\n }\n } \n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeDigits( TObject * data)\n{\n \/\/fills QA histos for Digits\n TObjArray *chambers = dynamic_cast<TObjArray*>(data);\n if ( !chambers) {\n AliError(\"Wrong type of digits container\") ; \n } else {\n for(Int_t i =0; i< chambers->GetEntries(); i++)\n {\n\tTClonesArray * digits = dynamic_cast<TClonesArray*>(chambers->At(i)); \n\tfhDigChEvt->Fill(i,digits->GetEntriesFast()\/(48.*80.*6.));\n\tTIter next(digits); \n\tAliHMPIDDigit * digit; \n\twhile ( (digit = dynamic_cast<AliHMPIDDigit *>(next())) ) {\n\t fhDigPcEvt->Fill(10.*i+digit->Pc(),1.\/(48.*80.));\n\t fhDigQ->Fill(digit->Q());\n\t} \n }\n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeSDigits( TObject * data)\n{\n \/\/fills QA histos for SDigits\n TClonesArray * sdigits = dynamic_cast<TClonesArray *>(data) ; \n if (!sdigits) {\n AliError(\"Wrong type of sdigits container\") ; \n } else {\n AliHMPIDDigit *ref = (AliHMPIDDigit *)sdigits->At(0);\n Float_t zero = ref->GetTrack(0); \n TIter next(sdigits) ; \n AliHMPIDDigit * sdigit ; \n while ( (sdigit = dynamic_cast<AliHMPIDDigit *>(next())) ) {\n fhSDigits->Fill(sdigit->Q()) ;\n if(zero == sdigit->GetTrack(0)) continue;\n else zero = sdigit->GetTrack(0);\n } \n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeRecPoints(TTree * clustersTree)\n{\n \/\/fills QA histos for clusters\n\n TClonesArray *clusters = new TClonesArray(\"AliHMPIDCluster\");\n for(int i=AliHMPIDParam::kMinCh;i<=AliHMPIDParam::kMaxCh;i++){\n TBranch *branch = clustersTree->GetBranch(Form(\"HMPID%d\",i));\n branch->SetAddress(&clusters);\n branch->GetEntry(0);\n\n fhCluEvt->Fill(i,clusters->GetEntries());\n TIter next(clusters);\n AliHMPIDCluster *clu;\n while ( (clu = dynamic_cast<AliHMPIDCluster *>(next())) ) {;\n fhCluFlg->Fill(clu->Status()); fhCluChi2->Fill(clu->Chi2()); fhCluSize->Fill(clu->Size());\n fhCluQ->Fill(clu->Q()); \n Int_t qCut=100;\n if(clu->Q()>qCut) {\n\tfhMipCluSize->SetTitle(Form(\"Mip cluster size at a Qcut = %i ADC\",qCut));\n\tfhMipCluSize->Fill(clu->Size());\n }\n }\n }\n\n clusters->Delete();\n delete clusters;\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeESDs(AliESDEvent * esd)\n{\n \/\/fills QA histos for ESD\n for(Int_t iTrk = 0 ; iTrk < esd->GetNumberOfTracks() ; iTrk++){\n AliESDtrack *pTrk = esd->GetTrack(iTrk) ;\n fhCkovP->Fill(pTrk->GetP(),pTrk->GetHMPIDsignal());\n fhSigP->Fill( pTrk->GetP(),TMath::Sqrt(pTrk->GetHMPIDchi2()));\n Float_t xm,ym; Int_t q,np; \n pTrk->GetHMPIDmip(xm,ym,q,np); \/\/mip info\n fhMipXY->Fill(xm,ym);\n Float_t xRad,yRad,th,ph; \n pTrk->GetHMPIDtrk(xRad,yRad,th,ph); \/\/track info at the middle of the radiator\n Float_t xPc = xRad+9.25*TMath::Tan(th)*TMath::Cos(ph); \/\/ temporar: linear extrapol (B=0!)\n Float_t yPc = yRad+9.25*TMath::Tan(th)*TMath::Sin(ph); \/\/ temporar: \"\n fhDifXY->Fill(xm-xPc,ym-yPc); \/\/track info\n Double_t pid[5] ; pTrk->GetHMPIDpid(pid) ;\n for(Int_t i = 0 ; i < 5 ; i++) fhPid[i]->Fill(pid[i]) ;\n }\n}\n\n<commit_msg>Commenting out some obsolete code. The code will revised after the Yves' presentation at the offline week<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/* $Id$ *\/\n\n\/\/---\n\/\/ Produces the data needed to calculate the quality assurance. \n\/\/ All data must be mergeable objects.\n\/\/ A. Mastroserio\n\/\/---\n\n\/\/ --- ROOT system ---\n#include <TClonesArray.h>\n#include <TFile.h> \n#include <TH1F.h> \n#include <TH2F.h>\n#include <TH1I.h> \n#include <TDirectory.h>\n#include <Riostream.h>\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliESDCaloCluster.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n#include \"AliHMPIDDigit.h\"\n#include \"AliHMPIDHit.h\"\n#include \"AliHMPIDCluster.h\"\n#include \"AliHMPIDQualAssDataMaker.h\"\n\nClassImp(AliHMPIDQualAssDataMaker)\n \n\/\/____________________________________________________________________________ \n AliHMPIDQualAssDataMaker::AliHMPIDQualAssDataMaker() : \n AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kHMPID), \"HMPID Quality Assurance Data Maker\"),\n fhHitQdc(0x0), \n fhSDigits(0x0),\n fhDigPcEvt(0x0),\n fhDigChEvt(0x0),\n fhDigQ(0x0),\n fhCluEvt(0x0),\n fhCluChi2(0x0),\n fhCluQ(0x0),\n fhCluFlg(0x0), \n fhCluSize(0x0), \n fhMipCluSize(0x0),\n fhCkovP(0x0),\n fhSigP(0x0),\n fhMipXY(0x0),\n fhDifXY(0x0)\n{\n \/\/ ctor\n for(Int_t i=0; i<7; i++) fhHitMap[i]=0x0;\n for(Int_t j=0; j<5; j++) fhPid[j]=0x0;\n\/\/ fDetectorDir = fOutput->GetDirectory(GetName()) ; \n\/\/ if (!fDetectorDir) \n\/\/ fDetectorDir = fOutput->mkdir(GetName()) ; \n}\n\n\/\/____________________________________________________________________________ \nAliHMPIDQualAssDataMaker::AliHMPIDQualAssDataMaker(const AliHMPIDQualAssDataMaker& qadm) :\n AliQualAssDataMaker(), \n fhHitQdc(qadm.fhHitQdc), \n fhSDigits(qadm.fhSDigits),\n fhDigPcEvt(qadm.fhDigPcEvt),\n fhDigChEvt(qadm.fhDigChEvt),\n fhDigQ(qadm.fhDigQ),\n fhCluEvt(qadm.fhCluEvt),\n fhCluChi2(qadm.fhCluChi2),\n fhCluQ(qadm.fhCluQ),\n fhCluFlg(qadm.fhCluFlg),\n fhCluSize(qadm.fhCluSize),\n fhMipCluSize(qadm.fhMipCluSize),\n fhCkovP(qadm.fhCkovP),\n fhSigP(qadm.fhSigP),\n fhMipXY(qadm.fhMipXY),\n fhDifXY(qadm.fhDifXY)\n{\n \/\/copy ctor \n for(Int_t i=0; i<7; i++) fhHitMap[i]=qadm.fhHitMap[i];\n for(Int_t j=0; j<5; j++) fhPid[j]=qadm.fhPid[j];\n\n SetName((const char*)qadm.GetName()) ; \n SetTitle((const char*)qadm.GetTitle()); \n}\n\n\/\/__________________________________________________________________\nAliHMPIDQualAssDataMaker& AliHMPIDQualAssDataMaker::operator = (const AliHMPIDQualAssDataMaker& qadm )\n{\n \/\/ Equal operator.\n this->~AliHMPIDQualAssDataMaker();\n new(this) AliHMPIDQualAssDataMaker(qadm);\n return *this;\n}\n \n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitHits()\n{\n \/\/ create Hits histograms in Hits subdir\n fhHitQdc=new TH1F(\"HitQdc\",\"HMPID Hit Qdc all chamber;QDC\",500,0,4000);\n for(Int_t iCh=0;iCh<7;iCh++) fhHitMap[iCh]=new TH2F(Form(\"HMPID HitMap%i\",iCh),Form(\"Ch%i;x_{Hit};y_{Hit}\",iCh),162,-1,161,146,-1,145); \n}\n\n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitDigits()\n{\n \/\/ create Digits histograms in Digits subdir\n fhDigPcEvt=new TH1F(\"hDigPcEvt\",\"PC occupancy\",156,-1,77);\n fhDigChEvt=new TH1F(\"hDigChEvt\",\"Chamber occupancy\",32,-1,7);\n fhDigQ =new TH1F(\"Q \",\" digit charge \",3000,0,3000);\n}\n\n\/\/____________________________________________________________________________ \nvoid AliHMPIDQualAssDataMaker::InitSDigits()\n{\n \/\/ create SDigits histograms in SDigits subdir\n fhSDigits = new TH1F(\"hHmpidSDigits\", \"SDigits Q distribution in HMPID\", 500, 0., 5000.) ; \n}\n\n\/\/____________________________________________________________________________ \n\nvoid AliHMPIDQualAssDataMaker::InitRecPoints()\n{\n \/\/ create cluster histograms in RecPoint subdir\n fhCluEvt=new TH1F(\"CluPerEvt\",\"# clusters per chamber\",16,-1,7);\n fhCluChi2 =new TH1F(\"CluChi2\" ,\"Chi2 \" ,1000,0,100);\n fhCluQ =new TH1F(\"CluQ\" ,\"Cluster charge\" ,3000,0,3000);\n fhCluFlg =new TH1F(\"CluFlg\" ,\"Cluster flag\" ,14,-1.5,12.5);\n fhCluSize =new TH1F(\"CluSize\" ,\"Raw cluster size \",100,0,100);\n fhMipCluSize =new TH1F(\"MipCluSize\" ,\"Mip cluster size \",100,0,100);\n}\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::InitESDs()\n{\n \/\/create ESDs histograms in ESDs subdir\n fhCkovP = new TH2F(\"CkovP\" , \"#theta_{c}, [rad];P, [GeV]\" , 150, 0, 7 ,100, 0, 1) ;\n fhSigP = new TH2F(\"SigP\" ,\"#sigma_{#theta_c} [mrad];[GeV]\", 150, 0, 7 ,100, 0, 1) ;\n fhMipXY = new TH2F(\"MipXY\" ,\"mip position\" , 260, 0,130 ,252, 0,126) ;\n fhDifXY = new TH2F(\"DifXY\" ,\"diff\" , 200, -10, 10 ,200,-10,10) ;\n fhPid[0] = new TH1F(\"PidE\" ,\"PID: e yellow #mu magenta\" ,100,0,1) ;\n fhPid[1] = new TH1F(\"PidMu\",\"pid of #mu\" ,100,0,1) ;\n fhPid[2] = new TH1F(\"PidPi\",\"PID: #pi red K green p blue\",100,0,1) ;\n fhPid[3] = new TH1F(\"PidK\" ,\"pid of K\" ,100,0,1) ;\n fhPid[4] = new TH1F(\"PidP\" ,\"pid of p\" ,100,0,1) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeHits(TObject * data)\n{\n \/\/fills QA histos for Hits\n TClonesArray * hits = dynamic_cast<TClonesArray *>(data) ; \n if (!hits){\n AliError(\"Wrong type of hits container\") ; \n } else {\n TIter next(hits); \n AliHMPIDHit * hit ; \n while ( (hit = dynamic_cast<AliHMPIDHit *>(next())) ) {\n if(hit->Pid()<500000) fhHitQdc->Fill(hit->Q()) ;\n if(hit->Pid()<500000) fhHitMap[hit->Ch()]->Fill(hit->LorsX(),hit->LorsY());\n }\n } \n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeDigits( TObject * data)\n{\n \/\/fills QA histos for Digits\n TObjArray *chambers = dynamic_cast<TObjArray*>(data);\n if ( !chambers) {\n AliError(\"Wrong type of digits container\") ; \n } else {\n for(Int_t i =0; i< chambers->GetEntries(); i++)\n {\n\tTClonesArray * digits = dynamic_cast<TClonesArray*>(chambers->At(i)); \n\tfhDigChEvt->Fill(i,digits->GetEntriesFast()\/(48.*80.*6.));\n\tTIter next(digits); \n\tAliHMPIDDigit * digit; \n\twhile ( (digit = dynamic_cast<AliHMPIDDigit *>(next())) ) {\n\t fhDigPcEvt->Fill(10.*i+digit->Pc(),1.\/(48.*80.));\n\t fhDigQ->Fill(digit->Q());\n\t} \n }\n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeSDigits( TObject * data)\n{\n \/\/fills QA histos for SDigits\n TClonesArray * sdigits = dynamic_cast<TClonesArray *>(data) ; \n if (!sdigits) {\n AliError(\"Wrong type of sdigits container\") ; \n } else {\n AliHMPIDDigit *ref = (AliHMPIDDigit *)sdigits->At(0);\n Float_t zero = ref->GetTrack(0); \n TIter next(sdigits) ; \n AliHMPIDDigit * sdigit ; \n while ( (sdigit = dynamic_cast<AliHMPIDDigit *>(next())) ) {\n fhSDigits->Fill(sdigit->Q()) ;\n if(zero == sdigit->GetTrack(0)) continue;\n else zero = sdigit->GetTrack(0);\n } \n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeRecPoints(TTree * clustersTree)\n{\n \/\/fills QA histos for clusters\n\n TClonesArray *clusters = new TClonesArray(\"AliHMPIDCluster\");\n for(int i=AliHMPIDParam::kMinCh;i<=AliHMPIDParam::kMaxCh;i++){\n TBranch *branch = clustersTree->GetBranch(Form(\"HMPID%d\",i));\n branch->SetAddress(&clusters);\n branch->GetEntry(0);\n\n fhCluEvt->Fill(i,clusters->GetEntries());\n TIter next(clusters);\n AliHMPIDCluster *clu;\n while ( (clu = dynamic_cast<AliHMPIDCluster *>(next())) ) {;\n fhCluFlg->Fill(clu->Status()); fhCluChi2->Fill(clu->Chi2()); fhCluSize->Fill(clu->Size());\n fhCluQ->Fill(clu->Q()); \n Int_t qCut=100;\n if(clu->Q()>qCut) {\n\tfhMipCluSize->SetTitle(Form(\"Mip cluster size at a Qcut = %i ADC\",qCut));\n\tfhMipCluSize->Fill(clu->Size());\n }\n }\n }\n\n clusters->Delete();\n delete clusters;\n}\n\n\/\/____________________________________________________________________________\nvoid AliHMPIDQualAssDataMaker::MakeESDs(AliESDEvent * esd)\n{\n \/\/fills QA histos for ESD\n for(Int_t iTrk = 0 ; iTrk < esd->GetNumberOfTracks() ; iTrk++){\n AliESDtrack *pTrk = esd->GetTrack(iTrk) ;\n fhCkovP->Fill(pTrk->GetP(),pTrk->GetHMPIDsignal());\n fhSigP->Fill( pTrk->GetP(),TMath::Sqrt(pTrk->GetHMPIDchi2()));\n Float_t xm,ym; Int_t q,np; \n pTrk->GetHMPIDmip(xm,ym,q,np); \/\/mip info\n fhMipXY->Fill(xm,ym);\n Float_t xRad,yRad,th,ph; \n pTrk->GetHMPIDtrk(xRad,yRad,th,ph); \/\/track info at the middle of the radiator\n Float_t xPc = xRad+9.25*TMath::Tan(th)*TMath::Cos(ph); \/\/ temporar: linear extrapol (B=0!)\n Float_t yPc = yRad+9.25*TMath::Tan(th)*TMath::Sin(ph); \/\/ temporar: \"\n fhDifXY->Fill(xm-xPc,ym-yPc); \/\/track info\n Double_t pid[5] ; pTrk->GetHMPIDpid(pid) ;\n for(Int_t i = 0 ; i < 5 ; i++) fhPid[i]->Fill(pid[i]) ;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"tp_PointGeometry.hxx\"\n#include \"TabPages.hrc\"\n#include \"res_BarGeometry.hxx\"\n#include \"ResId.hxx\"\n\n#include \"chartview\/ChartSfxItemIds.hxx\"\n\n#include <svl\/intitem.hxx>\n#include <svx\/svx3ditems.hxx>\n\nnamespace chart\n{\n\nSchLayoutTabPage::SchLayoutTabPage(Window* pWindow,const SfxItemSet& rInAttrs)\n : SfxTabPage(pWindow, \"tp_ChartType\", \"modules\/schart\/ui\/tp_ChartType.ui\", rInAttrs)\n , m_pGeometryResources(0)\n{\n m_pGeometryResources = new BarGeometryResources( this );\n}\n\nSchLayoutTabPage::~SchLayoutTabPage()\n{\n delete m_pGeometryResources;\n}\n\nSfxTabPage* SchLayoutTabPage::Create(Window* pWindow,\n const SfxItemSet* rOutAttrs)\n{\n return new SchLayoutTabPage(pWindow, *rOutAttrs);\n}\n\nbool SchLayoutTabPage::FillItemSet(SfxItemSet* rOutAttrs)\n{\n\n if(m_pGeometryResources && m_pGeometryResources->GetSelectEntryCount())\n {\n long nSegs=32;\n\n long nShape = m_pGeometryResources->GetSelectEntryPos();\n if(nShape==CHART_SHAPE3D_PYRAMID)\n nSegs=4;\n\n rOutAttrs->Put(SfxInt32Item(SCHATTR_STYLE_SHAPE,nShape));\n rOutAttrs->Put(Svx3DHorizontalSegmentsItem(nSegs));\n }\n return true;\n}\n\nvoid SchLayoutTabPage::Reset(const SfxItemSet* rInAttrs)\n{\n const SfxPoolItem *pPoolItem = NULL;\n\n if (rInAttrs->GetItemState(SCHATTR_STYLE_SHAPE,true, &pPoolItem) == SFX_ITEM_SET)\n {\n long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();\n if(m_pGeometryResources)\n {\n m_pGeometryResources->SelectEntryPos(static_cast<sal_uInt16>(nVal));\n m_pGeometryResources->Show( true );\n }\n }\n}\n\n} \/\/namespace chart\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>SchLayoutTabPage: that ctor wants a pointer<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"tp_PointGeometry.hxx\"\n#include \"TabPages.hrc\"\n#include \"res_BarGeometry.hxx\"\n#include \"ResId.hxx\"\n\n#include \"chartview\/ChartSfxItemIds.hxx\"\n\n#include <svl\/intitem.hxx>\n#include <svx\/svx3ditems.hxx>\n\nnamespace chart\n{\n\nSchLayoutTabPage::SchLayoutTabPage(Window* pWindow,const SfxItemSet& rInAttrs)\n : SfxTabPage(pWindow, \"tp_ChartType\", \"modules\/schart\/ui\/tp_ChartType.ui\", &rInAttrs)\n , m_pGeometryResources(0)\n{\n m_pGeometryResources = new BarGeometryResources( this );\n}\n\nSchLayoutTabPage::~SchLayoutTabPage()\n{\n delete m_pGeometryResources;\n}\n\nSfxTabPage* SchLayoutTabPage::Create(Window* pWindow,\n const SfxItemSet* rOutAttrs)\n{\n return new SchLayoutTabPage(pWindow, *rOutAttrs);\n}\n\nbool SchLayoutTabPage::FillItemSet(SfxItemSet* rOutAttrs)\n{\n\n if(m_pGeometryResources && m_pGeometryResources->GetSelectEntryCount())\n {\n long nSegs=32;\n\n long nShape = m_pGeometryResources->GetSelectEntryPos();\n if(nShape==CHART_SHAPE3D_PYRAMID)\n nSegs=4;\n\n rOutAttrs->Put(SfxInt32Item(SCHATTR_STYLE_SHAPE,nShape));\n rOutAttrs->Put(Svx3DHorizontalSegmentsItem(nSegs));\n }\n return true;\n}\n\nvoid SchLayoutTabPage::Reset(const SfxItemSet* rInAttrs)\n{\n const SfxPoolItem *pPoolItem = NULL;\n\n if (rInAttrs->GetItemState(SCHATTR_STYLE_SHAPE,true, &pPoolItem) == SFX_ITEM_SET)\n {\n long nVal=((const SfxInt32Item*)pPoolItem)->GetValue();\n if(m_pGeometryResources)\n {\n m_pGeometryResources->SelectEntryPos(static_cast<sal_uInt16>(nVal));\n m_pGeometryResources->Show( true );\n }\n }\n}\n\n} \/\/namespace chart\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n#include <iomanip>\n\n#include \"Bar.h\"\n#include \"ChartUtil.h\"\n\nnamespace CppChart\n{\n\tBarChart::BarChart(const std::vector<DataElement>& d, bool al, bool dv) :\n\t\tm_gap(10), m_guides(true), m_displayGuides(false), m_displayValues(dv),\n\t\tm_data(d), m_width(0), m_vSize(0.0f)\n\t{\n\t\tLogFnStart();\n\n\t\tm_max = (*max_element(m_data.begin(), m_data.end())).value;\n\t\tm_legend.m_exists = al;\n\n\t\tif (m_legend.m_exists)\n\t\t{\n\t\t\tstd::vector<DataFormat> temp;\n\t\t\tfor (auto& element : d)\n\t\t\t{\n\t\t\t\ttemp.push_back({ element.name, element.color });\n\t\t\t}\n\t\t\tm_legend.AddData(temp);\n\t\t}\n\n\t\tLogFnEnd();\n\t}\n\n\tvoid BarChart::Render()\n\t{\n\t\tLogFnStart();\n\n\t\tfloat x = m_chartOffsets.x \/ 2.0f + m_gap, y = m_chartOffsets.y \/ 2.0f;\n\t\tfloat ratio = (m_chartHeight - 2.0f * m_chartOffsets.y - m_vSize) \/ m_max;\n\t\tfloat item;\n\n\t\tsf::Text text, values;\n\t\tsf::RectangleShape guideLines;\n\n\t\tm_width = (m_chartWidth - 2.0f * m_chartOffsets.x - m_gap * static_cast<float>(m_data.size())) \/ static_cast<float>(m_data.size());\n\t\tm_vSize = m_width \/ static_cast<float>(CountDigit(m_max) + 3u);\n\n\t\tif (!m_legend.m_exists)\n\t\t{\n\t\t\ttext.setFont(m_axes.labels.font);\n\t\t\ttext.setColor(m_axes.labels.fontColor);\n\t\t\ttext.setCharacterSize(m_axes.labels.fontSize);\n\t\t}\n\n\t\tif (m_displayValues)\n\t\t{\n\t\t\tvalues.setFont(m_axes.labels.font);\n\t\t\tvalues.setCharacterSize(m_vSize);\n\t\t}\n\n\t\tif (m_guides)\n\t\t{\n\t\t\t\/\/ TODO: Fix code\n\t\t}\n\n\t\tfor (auto& d : m_data)\n\t\t{\n\t\t\titem = d.value;\n\t\t\titem *= ratio;\n\n\t\t\tm_bar.setPosition(x, m_chartHeight - y - item + m_vSize);\n\t\t\tm_bar.setSize(sf::Vector2f(m_width, item - m_axes.labels.fontSize - m_vSize));\n\t\t\tm_bar.setFillColor(d.color);\n\n\t\t\tm_chartTexture.draw(m_bar);\n\n\t\t\tif (!m_legend.m_exists)\n\t\t\t{\n\t\t\t\ttext.setString(d.name);\n\t\t\t\tSetTextAtCenter(text, x, m_chartHeight - y - 1.2f * m_axes.labels.fontSize, m_width + m_gap, m_axes.labels.fontSize);\n\t\t\t\ttext.move(sf::Vector2f(-m_gap \/ 2.0f, 0.0f));\n\t\t\t\tm_chartTexture.draw(text);\n\t\t\t}\n\n\t\t\tif (m_displayValues)\n\t\t\t{\n\t\t\t\tvalues.setColor(d.color);\n\t\t\t\tvalues.setString([&]()\n\t\t\t\t{\n\t\t\t\t\tstd::ostringstream oss;\n\t\t\t\t\toss << std::setprecision(2) << d.value;\n\t\t\t\t\treturn oss.str();\n\t\t\t\t}());\n\t\t\t\tSetTextAtCenter(values, x, m_chartHeight - y - item - m_vSize \/ 2.0f, m_width + m_gap, m_vSize);\n\t\t\t\tvalues.move(sf::Vector2f(-m_gap \/ 2.0f, 0.0f));\n\t\t\t\tm_chartTexture.draw(values);\n\t\t\t}\n\n\t\t\tx += m_width + m_gap;\n\t\t}\n\n\t\tDrawAxes();\n\n\t\tLogFnEnd();\n\t}\n}\n<commit_msg>Implement MultiBarChart's constructor<commit_after>#include <sstream>\n#include <iomanip>\n\n#include \"Bar.h\"\n#include \"ChartUtil.h\"\n#include <cassert>\n\nnamespace CppChart\n{\n\tBarChart::BarChart(const std::vector<DataElement>& d, bool al, bool dv) :\n\t\tm_gap(10), m_guides(true), m_displayGuides(false), m_displayValues(dv),\n\t\tm_data(d), m_width(0), m_vSize(0.0f)\n\t{\n\t\tLogFnStart();\n\n\t\tm_max = (*max_element(m_data.begin(), m_data.end())).value;\n\t\tm_legend.m_exists = al;\n\n\t\tif (m_legend.m_exists)\n\t\t{\n\t\t\tstd::vector<DataFormat> temp;\n\t\t\tfor (auto& element : d)\n\t\t\t{\n\t\t\t\ttemp.push_back({ element.name, element.color });\n\t\t\t}\n\t\t\tm_legend.AddData(temp);\n\t\t}\n\n\t\tLogFnEnd();\n\t}\n\n\tvoid BarChart::Render()\n\t{\n\t\tLogFnStart();\n\n\t\tfloat x = m_chartOffsets.x \/ 2.0f + m_gap, y = m_chartOffsets.y \/ 2.0f;\n\t\tfloat ratio = (m_chartHeight - 2.0f * m_chartOffsets.y - m_vSize) \/ m_max;\n\t\tfloat item;\n\n\t\tsf::Text text, values;\n\t\tsf::RectangleShape guideLines;\n\n\t\tm_width = (m_chartWidth - 2.0f * m_chartOffsets.x - m_gap * static_cast<float>(m_data.size())) \/ static_cast<float>(m_data.size());\n\t\tm_vSize = m_width \/ static_cast<float>(CountDigit(m_max) + 3u);\n\n\t\tif (!m_legend.m_exists)\n\t\t{\n\t\t\ttext.setFont(m_axes.labels.font);\n\t\t\ttext.setColor(m_axes.labels.fontColor);\n\t\t\ttext.setCharacterSize(m_axes.labels.fontSize);\n\t\t}\n\n\t\tif (m_displayValues)\n\t\t{\n\t\t\tvalues.setFont(m_axes.labels.font);\n\t\t\tvalues.setCharacterSize(m_vSize);\n\t\t}\n\n\t\tif (m_guides)\n\t\t{\n\t\t\t\/\/ TODO: Fix code\n\t\t}\n\n\t\tfor (auto& d : m_data)\n\t\t{\n\t\t\titem = d.value;\n\t\t\titem *= ratio;\n\n\t\t\tm_bar.setPosition(x, m_chartHeight - y - item + m_vSize);\n\t\t\tm_bar.setSize(sf::Vector2f(m_width, item - m_axes.labels.fontSize - m_vSize));\n\t\t\tm_bar.setFillColor(d.color);\n\n\t\t\tm_chartTexture.draw(m_bar);\n\n\t\t\tif (!m_legend.m_exists)\n\t\t\t{\n\t\t\t\ttext.setString(d.name);\n\t\t\t\tSetTextAtCenter(text, x, m_chartHeight - y - 1.2f * m_axes.labels.fontSize, m_width + m_gap, m_axes.labels.fontSize);\n\t\t\t\ttext.move(sf::Vector2f(-m_gap \/ 2.0f, 0.0f));\n\t\t\t\tm_chartTexture.draw(text);\n\t\t\t}\n\n\t\t\tif (m_displayValues)\n\t\t\t{\n\t\t\t\tvalues.setColor(d.color);\n\t\t\t\tvalues.setString([&]()\n\t\t\t\t{\n\t\t\t\t\tstd::ostringstream oss;\n\t\t\t\t\toss << std::setprecision(2) << d.value;\n\t\t\t\t\treturn oss.str();\n\t\t\t\t}());\n\t\t\t\tSetTextAtCenter(values, x, m_chartHeight - y - item - m_vSize \/ 2.0f, m_width + m_gap, m_vSize);\n\t\t\t\tvalues.move(sf::Vector2f(-m_gap \/ 2.0f, 0.0f));\n\t\t\t\tm_chartTexture.draw(values);\n\t\t\t}\n\n\t\t\tx += m_width + m_gap;\n\t\t}\n\n\t\tDrawAxes();\n\n\t\tLogFnEnd();\n\t}\n\n\tMultiBarChart::MultiBarChart(const std::vector<std::vector<float>>& md, const std::vector<std::string>& al, const std::vector<sf::Color>& bc)\n\t\t: m_gap(0.0f), m_guides(0), m_displayGuides(false), m_displayValues(true), m_multiData(md), m_axesLabels(al), m_barColors(bc), m_width(0.0f), m_vSize(0.0f)\n\t{\n\t\tLogFnStart();\n\n\t\tassert(md.size() == al.size());\n\t\tassert(md[0].size() == bc.size());\n\n\t\tfloat temp = 0.0f;\n\t\tm_max = *(max_element(md[0].begin(), md[0].end()));\n\n\t\tfor (int i = 1; i < al.size(); ++i)\n\t\t{\n\t\t\tif (temp > m_max)\n\t\t\t{\n\t\t\t\tm_max = temp;\n\t\t\t}\n\t\t}\n\n\t\tLogFnEnd();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Use bool<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include \"pcl\/point_types.h\"\n#include \"pcl\/impl\/instantiate.hpp\"\n#include \"pcl\/features\/pfh.h\"\n#include \"pcl\/features\/impl\/pfh.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::computePairFeatures (const Eigen::Vector4f &p1, const Eigen::Vector4f &n1, \n const Eigen::Vector4f &p2, const Eigen::Vector4f &n2,\n float &f1, float &f2, float &f3, float &f4)\n{\n Eigen::Vector4f dp2p1 = p2 - p1;\n dp2p1[3] = 0.0f;\n f4 = dp2p1.norm ();\n\n if (f4 == 0)\n {\n PCL_ERROR (\"Euclidean distance between points is 0!\\n\");\n f1 = f2 = f3 = f4 = 0;\n return (false);\n }\n\n Eigen::Vector4f n1_copy = n1,\n n2_copy = n2;\n n1_copy[3] = n2_copy[3] = 0.0f;\n float angle1 = n1_copy.dot (dp2p1) \/ f4,\n angle2 = -n2_copy.dot (dp2p1) \/ f4;\n\n\/* commented this to pass the unit tests\n * if (acos (angle1) > acos(angle2))\n {\n \/\/ switch p1 and p2\n n1_copy = n2;\n n2_copy = n1;\n n1_copy[3] = n2_copy[3] = 0.0f;\n dp2p1 *= (-1);\n f3 = angle2;\n }\n else*\/\n f3 = angle1;\n\n \/\/ Create a Darboux frame coordinate system u-v-w\n \/\/ u = n1; v = (p_idx - q_idx) x u \/ || (p_idx - q_idx) x u ||; w = u x v\n Eigen::Vector4f v = dp2p1.cross3 (n1_copy);\n v[3] = 0.0f;\n float v_norm = v.norm ();\n if (v_norm == 0)\n {\n PCL_ERROR (\"Norm of Delta x U is 0!\\n\");\n f1 = f2 = f3 = f4 = 0;\n return (false);\n }\n \/\/ Normalize v\n v \/= v_norm;\n\n Eigen::Vector4f w = n1_copy.cross3 (v);\n \/\/ Do not have to normalize w - it is a unit vector by construction\n\n v[3] = 0.0f;\n f2 = v.dot (n2_copy);\n w[3] = 0.0f;\n \/\/ Compute f1 = arctan (w * n2, u * n2) i.e. angle of n2 in the x=u, y=w coordinate system\n f1 = atan2f (w.dot (n2_copy), u.dot (n2_copy)); \/\/ @todo optimize this\n\n return (true);\n}\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE_PRODUCT(PFHEstimation, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((pcl::PFHSignature125)));\n\n<commit_msg>too many undos in the editor - build now works :-)<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include \"pcl\/point_types.h\"\n#include \"pcl\/impl\/instantiate.hpp\"\n#include \"pcl\/features\/pfh.h\"\n#include \"pcl\/features\/impl\/pfh.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::computePairFeatures (const Eigen::Vector4f &p1, const Eigen::Vector4f &n1, \n const Eigen::Vector4f &p2, const Eigen::Vector4f &n2,\n float &f1, float &f2, float &f3, float &f4)\n{\n Eigen::Vector4f dp2p1 = p2 - p1;\n dp2p1[3] = 0.0f;\n f4 = dp2p1.norm ();\n\n if (f4 == 0.0f)\n {\n PCL_ERROR (\"Euclidean distance between points is 0!\\n\");\n f1 = f2 = f3 = f4 = 0.0f;\n return (false);\n }\n\n Eigen::Vector4f n1_copy = n1,\n n2_copy = n2;\n n1_copy[3] = n2_copy[3] = 0.0f;\n float angle1 = n1_copy.dot (dp2p1) \/ f4,\n angle2 = -n2_copy.dot (dp2p1) \/ f4;\n\n\/* commented this to pass the unit tests\n * if (acos (angle1) > acos(angle2))\n {\n \/\/ switch p1 and p2\n n1_copy = n2;\n n2_copy = n1;\n n1_copy[3] = n2_copy[3] = 0.0f;\n dp2p1 *= (-1);\n f3 = angle2;\n }\n else*\/\n f3 = angle1;\n\n \/\/ Create a Darboux frame coordinate system u-v-w\n \/\/ u = n1; v = (p_idx - q_idx) x u \/ || (p_idx - q_idx) x u ||; w = u x v\n Eigen::Vector4f v = dp2p1.cross3 (n1_copy);\n v[3] = 0.0f;\n float v_norm = v.norm ();\n if (v_norm == 0.0f)\n {\n PCL_ERROR (\"Norm of Delta x U is 0!\\n\");\n f1 = f2 = f3 = f4 = 0.0f;\n return (false);\n }\n \/\/ Normalize v\n v \/= v_norm;\n\n Eigen::Vector4f w = n1_copy.cross3 (v);\n \/\/ Do not have to normalize w - it is a unit vector by construction\n\n v[3] = 0.0f;\n f2 = v.dot (n2_copy);\n w[3] = 0.0f;\n \/\/ Compute f1 = arctan (w * n2, u * n2) i.e. angle of n2 in the x=u, y=w coordinate system\n f1 = atan2f (w.dot (n2_copy), n1_copy.dot (n2_copy)); \/\/ @todo optimize this\n\n return (true);\n}\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE_PRODUCT(PFHEstimation, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((pcl::PFHSignature125)));\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <list>\n#include <sstream>\n\n#include \"flame\/base.h\"\n\n#include \"pyflame.h\"\n\n#define NO_IMPORT_ARRAY\n#define PY_ARRAY_UNIQUE_SYMBOL FLAME_PyArray_API\n#include <numpy\/ndarrayobject.h>\n\n\/** Translate python list of tuples to Config\n *\n * [(K,V)] -> Config\n * float -> double\n * str -> string\n * [[()]] -> vector<Config> (recurse)\n * ndarray -> vector<double>\n * TODO: [0.0] -> vector<double>\n *\/\nvoid List2Config(Config& ret, PyObject *list, unsigned depth)\n{\n if(depth>3)\n throw std::runtime_error(\"too deep for Dict2Config\");\n\n PyRef<> iter(PyObject_GetIter(list));\n while(true) {\n PyObject *item = PyIter_Next(iter.py());\n if(!item) break;\n PyRef<> itemref(item);\n const char *kname;\n PyObject *value;\n if(!PyArg_ParseTuple(item, \"sO\", &kname, &value))\n throw std::runtime_error(\"list item is not a tuple?\");\n\n if(PyArray_Check(value)) { \/\/ array as vector<double>\n PyRef<> arr(PyArray_ContiguousFromAny(value, NPY_DOUBLE, 0, 2));\n double *buf = (double*)PyArray_DATA(arr.py());\n std::vector<double> temp(PyArray_SIZE(arr.py()));\n std::copy(buf, buf+temp.size(), temp.begin());\n\n ret.swap<std::vector<double> >(kname, temp);\n\n } else if(PyNumber_Check(value)) { \/\/ scalar as double\n PyRef<> dval(PyNumber_Float(value));\n double val = PyFloat_AsDouble(dval.py());\n ret.set<double>(kname, val);\n\n } else if(PyUnicode_Check(value) || (PY_MAJOR_VERSION < 3 && PyBytes_Check(value))) { \/\/ string\n PyRef<> valref(value, borrow());\n PyCString sval(valref);\n const char *val = sval.c_str();\n\n ret.set<std::string>(kname, val);\n\n } else if(PySequence_Check(value)) { \/\/ list of dict\n Py_ssize_t N = PySequence_Size(value);\n\n Config::vector_t output;\n output.reserve(N);\n\n for(Py_ssize_t i=0; i<N; i++) {\n PyRef<> elem(PySequence_GetItem(value, i));\n\n if(PyDict_Check(elem.py())) {\n elem.reset(PyMapping_Items(elem.py()));\n }\n if(!PyList_Check(elem.py())) {\n PyTypeObject *valuetype = (PyTypeObject*)PyObject_Type(elem.py());\n throw std::invalid_argument(SB()<<\"lists must contain only dict or list of tuples, not \"<<valuetype->tp_name);\n }\n\n output.push_back(ret.new_scope());\n\n List2Config(output.back(), elem.py(), depth+1); \/\/ inheirt parent scope\n }\n\n ret.set<Config::vector_t>(kname, output);\n\n } else {\n PyTypeObject *valuetype = (PyTypeObject*)PyObject_Type(value);\n throw std::invalid_argument(SB()<<\"Must be a dict, not \"<<valuetype->tp_name);\n }\n }\n}\n\nnamespace {\n\nPyObject* pydirname(PyObject *obj)\n{\n if(!obj) return NULL;\n\n PyRef<> ospath(PyImport_ImportModule(\"os.path\"));\n return PyObject_CallMethod(ospath.py(), \"dirname\", \"O\", obj);\n}\n\nstruct confval : public boost::static_visitor<PyRef<> >\n{\n PyRef<> operator()(double v) const\n {\n return PyRef<>(PyFloat_FromDouble(v));\n }\n\n PyRef<> operator()(const std::string& v) const\n {\n return PyRef<>(PyString_FromString(v.c_str()));\n }\n\n PyRef<> operator()(const std::vector<double>& v) const\n {\n npy_intp dims[] = {(npy_intp)v.size()};\n PyRef<> obj(PyArray_SimpleNew(1, dims, NPY_DOUBLE));\n std::copy(v.begin(), v.end(), (double*)PyArray_DATA(obj.py()));\n return obj;\n }\n\n PyRef<> operator()(const Config::vector_t& v) const\n {\n PyRef<> L(PyList_New(v.size()));\n\n for(size_t i=0, N=v.size(); i<N; i++)\n {\n PyList_SetItem(L.py(), i, conf2dict(&v[i]));\n }\n return L;\n }\n};\n\n} \/\/ namespace\n\nPyObject* conf2dict(const Config *conf)\n{\n PyRef<> list(PyList_New(0));\n\n for(Config::const_iterator it=conf->begin(), end=conf->end();\n it!=end; ++it)\n {\n PyRef<> val(boost::apply_visitor(confval(), it->second));\n PyRef<> tup(Py_BuildValue(\"sO\", it->first.c_str(), val.py()));\n if(PyList_Append(list.py(), tup.py()))\n throw std::runtime_error(\"Failed to insert into dictionary from conf2dict\");\n }\n\n return list.releasePy();\n}\n\nConfig* list2conf(PyObject *dict)\n{\n if(!PyList_Check(dict))\n throw std::invalid_argument(\"Not a list\");\n std::auto_ptr<Config> conf(new Config);\n List2Config(*conf, dict);\n return conf.release();\n}\n\nPyObject* PyGLPSPrint(PyObject *, PyObject *args)\n{\n try {\n PyObject *inp;\n if(!PyArg_ParseTuple(args, \"O\", &inp))\n return NULL;\n\n PyRef<> list;\n if(PyDict_Check(inp)) {\n list.reset(PyMapping_Items(inp));\n inp = list.py();\n }\n if(!PyList_Check(inp))\n return PyErr_Format(PyExc_ValueError, \"argument must be dict or list of tuples\");\n\n Config conf;\n List2Config(conf, inp);\n std::ostringstream strm;\n GLPSPrint(strm, conf);\n return PyString_FromString(strm.str().c_str());\n }CATCH()\n}\n\n#ifndef PY_SSIZE_T_CLEAN\n#error the following assumes ssize_t is used\n#endif\n\nConfig* PyGLPSParse2Config(PyObject *, PyObject *args, PyObject *kws)\n{\n PyObject *conf = NULL, *extra_defs = Py_None;\n const char *path = NULL;\n const char *pnames[] = {\"config\", \"path\", \"extra\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"O|zO\", (char**)pnames, &conf, &path, &extra_defs))\n return NULL;\n\n GLPSParser parser;\n\n if(extra_defs==Py_None) {\n \/\/ no-op\n } else if(PyDict_Check(extra_defs)) {\n PyObject *key, *value;\n Py_ssize_t pos = 0;\n\n while(PyDict_Next(extra_defs, &pos, &key, &value)) {\n PyRef<> keyx(key, borrow());\n PyCString keystr(keyx);\n\n Config::value_t curval;\n\n if(PyNumber_Check(value)) {\n PyRef<> pyf(PyNumber_Float(value));\n curval = PyFloat_AsDouble(pyf.py());\n\n } else if(PyString_Check(value)) {\n PyRef<> valuex(value, borrow());\n PyCString valstr(valuex);\n\n curval = valstr.c_str();\n\n } else {\n PyErr_SetString(PyExc_ValueError, \"extra {} can contain only numbers or strings\");\n return NULL;\n }\n\n parser.setVar(keystr.c_str(), curval);\n }\n } else {\n PyErr_SetString(PyExc_ValueError, \"'extra' must be a dict\");\n return NULL;\n }\n\n PyGetBuf buf;\n std::auto_ptr<Config> C;\n\n PyRef<> listref;\n\n if(PyObject_HasAttrString(conf, \"read\")) { \/\/ file-like\n PyCString pyname;\n\n if(!path && PyObject_HasAttrString(conf, \"name\")) {\n path = pyname.c_str(pydirname(PyObject_GetAttrString(conf, \"name\")));\n }\n\n PyRef<> pybytes(PyObject_CallMethod(conf, \"read\", \"\"));\n if(!buf.get(pybytes.py())) {\n PyErr_SetString(PyExc_TypeError, \"read() must return a buffer\");\n return NULL;\n }\n C.reset(parser.parse_byte((const char*)buf.data(), buf.size(), path));\n\n } else if(buf.get(conf)) {\n C.reset(parser.parse_byte((const char*)buf.data(), buf.size(), path));\n\n#if PY_MAJOR_VERSION >= 3\n } else if(PyUnicode_Check(conf)) { \/\/ py3 str (aka unicode) doesn't implement buffer iface\n PyCString buf;\n const char *cbuf = buf.c_str(conf);\n\n C.reset(parser.parse_byte(cbuf, strlen(cbuf), path));\n#endif\n\n } else {\n if(PyDict_Check(conf)) {\n listref.reset(PyMapping_Items(conf));\n conf = listref.py();\n }\n if(PyList_Check(conf)) {\n C.reset(list2conf(conf));\n\n } else {\n throw std::invalid_argument(\"'config' must be dict, list of tuples, or byte buffer\");\n }\n }\n\n return C.release();\n}\n\nPyObject* PyGLPSParse(PyObject *unused, PyObject *args, PyObject *kws)\n{\n try{\n return conf2dict(PyGLPSParse2Config(unused, args, kws));\n }CATCH()\n}\n<commit_msg>python: propagate errors through conf2dict()<commit_after>\n#include <list>\n#include <sstream>\n\n#include \"flame\/base.h\"\n\n#include \"pyflame.h\"\n\n#define NO_IMPORT_ARRAY\n#define PY_ARRAY_UNIQUE_SYMBOL FLAME_PyArray_API\n#include <numpy\/ndarrayobject.h>\n\n\/** Translate python list of tuples to Config\n *\n * [(K,V)] -> Config\n * float -> double\n * str -> string\n * [[()]] -> vector<Config> (recurse)\n * ndarray -> vector<double>\n * TODO: [0.0] -> vector<double>\n *\/\nvoid List2Config(Config& ret, PyObject *list, unsigned depth)\n{\n if(depth>3)\n throw std::runtime_error(\"too deep for Dict2Config\");\n\n PyRef<> iter(PyObject_GetIter(list));\n while(true) {\n PyObject *item = PyIter_Next(iter.py());\n if(!item) break;\n PyRef<> itemref(item);\n const char *kname;\n PyObject *value;\n if(!PyArg_ParseTuple(item, \"sO\", &kname, &value))\n throw std::runtime_error(\"list item is not a tuple?\");\n\n if(PyArray_Check(value)) { \/\/ array as vector<double>\n PyRef<> arr(PyArray_ContiguousFromAny(value, NPY_DOUBLE, 0, 2));\n double *buf = (double*)PyArray_DATA(arr.py());\n std::vector<double> temp(PyArray_SIZE(arr.py()));\n std::copy(buf, buf+temp.size(), temp.begin());\n\n ret.swap<std::vector<double> >(kname, temp);\n\n } else if(PyNumber_Check(value)) { \/\/ scalar as double\n PyRef<> dval(PyNumber_Float(value));\n double val = PyFloat_AsDouble(dval.py());\n ret.set<double>(kname, val);\n\n } else if(PyUnicode_Check(value) || (PY_MAJOR_VERSION < 3 && PyBytes_Check(value))) { \/\/ string\n PyRef<> valref(value, borrow());\n PyCString sval(valref);\n const char *val = sval.c_str();\n\n ret.set<std::string>(kname, val);\n\n } else if(PySequence_Check(value)) { \/\/ list of dict\n Py_ssize_t N = PySequence_Size(value);\n\n Config::vector_t output;\n output.reserve(N);\n\n for(Py_ssize_t i=0; i<N; i++) {\n PyRef<> elem(PySequence_GetItem(value, i));\n\n if(PyDict_Check(elem.py())) {\n elem.reset(PyMapping_Items(elem.py()));\n }\n if(!PyList_Check(elem.py())) {\n PyTypeObject *valuetype = (PyTypeObject*)PyObject_Type(elem.py());\n throw std::invalid_argument(SB()<<\"lists must contain only dict or list of tuples, not \"<<valuetype->tp_name);\n }\n\n output.push_back(ret.new_scope());\n\n List2Config(output.back(), elem.py(), depth+1); \/\/ inheirt parent scope\n }\n\n ret.set<Config::vector_t>(kname, output);\n\n } else {\n PyTypeObject *valuetype = (PyTypeObject*)PyObject_Type(value);\n throw std::invalid_argument(SB()<<\"Must be a dict, not \"<<valuetype->tp_name);\n }\n }\n}\n\nnamespace {\n\nPyObject* pydirname(PyObject *obj)\n{\n if(!obj) return NULL;\n\n PyRef<> ospath(PyImport_ImportModule(\"os.path\"));\n return PyObject_CallMethod(ospath.py(), \"dirname\", \"O\", obj);\n}\n\nstruct confval : public boost::static_visitor<PyRef<> >\n{\n PyRef<> operator()(double v) const\n {\n return PyRef<>(PyFloat_FromDouble(v));\n }\n\n PyRef<> operator()(const std::string& v) const\n {\n return PyRef<>(PyString_FromString(v.c_str()));\n }\n\n PyRef<> operator()(const std::vector<double>& v) const\n {\n npy_intp dims[] = {(npy_intp)v.size()};\n PyRef<> obj(PyArray_SimpleNew(1, dims, NPY_DOUBLE));\n std::copy(v.begin(), v.end(), (double*)PyArray_DATA(obj.py()));\n return obj;\n }\n\n PyRef<> operator()(const Config::vector_t& v) const\n {\n PyRef<> L(PyList_New(v.size()));\n\n for(size_t i=0, N=v.size(); i<N; i++)\n {\n PyList_SetItem(L.py(), i, conf2dict(&v[i]));\n }\n return L;\n }\n};\n\n} \/\/ namespace\n\nPyObject* conf2dict(const Config *conf)\n{\n if(!conf)\n return NULL;\n PyRef<> list(PyList_New(0));\n\n for(Config::const_iterator it=conf->begin(), end=conf->end();\n it!=end; ++it)\n {\n PyRef<> val(boost::apply_visitor(confval(), it->second));\n PyRef<> tup(Py_BuildValue(\"sO\", it->first.c_str(), val.py()));\n if(PyList_Append(list.py(), tup.py()))\n throw std::runtime_error(\"Failed to insert into dictionary from conf2dict\");\n }\n\n return list.releasePy();\n}\n\nConfig* list2conf(PyObject *dict)\n{\n if(!PyList_Check(dict))\n throw std::invalid_argument(\"Not a list\");\n std::auto_ptr<Config> conf(new Config);\n List2Config(*conf, dict);\n return conf.release();\n}\n\nPyObject* PyGLPSPrint(PyObject *, PyObject *args)\n{\n try {\n PyObject *inp;\n if(!PyArg_ParseTuple(args, \"O\", &inp))\n return NULL;\n\n PyRef<> list;\n if(PyDict_Check(inp)) {\n list.reset(PyMapping_Items(inp));\n inp = list.py();\n }\n if(!PyList_Check(inp))\n return PyErr_Format(PyExc_ValueError, \"argument must be dict or list of tuples\");\n\n Config conf;\n List2Config(conf, inp);\n std::ostringstream strm;\n GLPSPrint(strm, conf);\n return PyString_FromString(strm.str().c_str());\n }CATCH()\n}\n\n#ifndef PY_SSIZE_T_CLEAN\n#error the following assumes ssize_t is used\n#endif\n\nConfig* PyGLPSParse2Config(PyObject *, PyObject *args, PyObject *kws)\n{\n PyObject *conf = NULL, *extra_defs = Py_None;\n const char *path = NULL;\n const char *pnames[] = {\"config\", \"path\", \"extra\", NULL};\n if(!PyArg_ParseTupleAndKeywords(args, kws, \"O|zO\", (char**)pnames, &conf, &path, &extra_defs))\n return NULL;\n\n GLPSParser parser;\n\n if(extra_defs==Py_None) {\n \/\/ no-op\n } else if(PyDict_Check(extra_defs)) {\n PyObject *key, *value;\n Py_ssize_t pos = 0;\n\n while(PyDict_Next(extra_defs, &pos, &key, &value)) {\n PyRef<> keyx(key, borrow());\n PyCString keystr(keyx);\n\n Config::value_t curval;\n\n if(PyNumber_Check(value)) {\n PyRef<> pyf(PyNumber_Float(value));\n curval = PyFloat_AsDouble(pyf.py());\n\n } else if(PyString_Check(value)) {\n PyRef<> valuex(value, borrow());\n PyCString valstr(valuex);\n\n curval = valstr.c_str();\n\n } else {\n PyErr_SetString(PyExc_ValueError, \"extra {} can contain only numbers or strings\");\n return NULL;\n }\n\n parser.setVar(keystr.c_str(), curval);\n }\n } else {\n PyErr_SetString(PyExc_ValueError, \"'extra' must be a dict\");\n return NULL;\n }\n\n PyGetBuf buf;\n std::auto_ptr<Config> C;\n\n PyRef<> listref;\n\n if(PyObject_HasAttrString(conf, \"read\")) { \/\/ file-like\n PyCString pyname;\n\n if(!path && PyObject_HasAttrString(conf, \"name\")) {\n path = pyname.c_str(pydirname(PyObject_GetAttrString(conf, \"name\")));\n }\n\n PyRef<> pybytes(PyObject_CallMethod(conf, \"read\", \"\"));\n if(!buf.get(pybytes.py())) {\n PyErr_SetString(PyExc_TypeError, \"read() must return a buffer\");\n return NULL;\n }\n C.reset(parser.parse_byte((const char*)buf.data(), buf.size(), path));\n\n } else if(buf.get(conf)) {\n C.reset(parser.parse_byte((const char*)buf.data(), buf.size(), path));\n\n#if PY_MAJOR_VERSION >= 3\n } else if(PyUnicode_Check(conf)) { \/\/ py3 str (aka unicode) doesn't implement buffer iface\n PyCString buf;\n const char *cbuf = buf.c_str(conf);\n\n C.reset(parser.parse_byte(cbuf, strlen(cbuf), path));\n#endif\n\n } else {\n if(PyDict_Check(conf)) {\n listref.reset(PyMapping_Items(conf));\n conf = listref.py();\n }\n if(PyList_Check(conf)) {\n C.reset(list2conf(conf));\n\n } else {\n throw std::invalid_argument(\"'config' must be dict, list of tuples, or byte buffer\");\n }\n }\n\n return C.release();\n}\n\nPyObject* PyGLPSParse(PyObject *unused, PyObject *args, PyObject *kws)\n{\n try{\n return conf2dict(PyGLPSParse2Config(unused, args, kws));\n }CATCH()\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fubullet.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 08:37:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fubullet.hxx\"\n\n#ifndef _BINDING_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _SFXPOOLITEM_HXX \/\/autogen\n#include <svtools\/poolitem.hxx>\n#endif\n#define ITEMID_FONT EE_CHAR_FONTINFO\n#include <svx\/fontitem.hxx>\n\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_SHELL_HXX\n#include \"DrawViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\n#ifndef _SVDOUTL_HXX \/\/autogen\n#include <svx\/svdoutl.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVX_CHARMAP_HXX \/\/autogen\n#include <svx\/charmap.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SVTOOLS_CTLOPTIONS_HXX\n#include <svtools\/ctloptions.hxx>\n#endif\n\n#ifdef IRIX\n#ifndef _SBXCLASS_HXX\n#include <basic\/sbx.hxx>\n#endif\n#endif\n#include <svx\/svxdlg.hxx>\n#include <svx\/dialogs.hrc>\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n\n#include \"app.hrc\"\n\nnamespace sd {\n\nconst sal_Unicode CHAR_HARDBLANK = ((sal_Unicode)0x00A0);\nconst sal_Unicode CHAR_HARDHYPHEN = ((sal_Unicode)0x2011);\nconst sal_Unicode CHAR_SOFTHYPHEN = ((sal_Unicode)0x00AD);\nconst sal_Unicode CHAR_RLM = ((sal_Unicode)0x200F);\nconst sal_Unicode CHAR_LRM = ((sal_Unicode)0x200E);\nconst sal_Unicode CHAR_ZWSP = ((sal_Unicode)0x200B);\nconst sal_Unicode CHAR_ZWNBSP = ((sal_Unicode)0x2060);\n\nTYPEINIT1( FuBullet, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuBullet::FuBullet (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* _pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, _pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuBullet::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuBullet( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuBullet::DoExecute( SfxRequest& rReq )\n{\n if( rReq.GetSlot() == SID_BULLET )\n InsertSpecialCharacter();\n else\n {\n sal_Unicode cMark = 0;\n switch( rReq.GetSlot() )\n {\n case FN_INSERT_SOFT_HYPHEN: cMark = CHAR_SOFTHYPHEN ; break;\n case FN_INSERT_HARDHYPHEN: cMark = CHAR_HARDHYPHEN ; break;\n case FN_INSERT_HARD_SPACE: cMark = CHAR_HARDBLANK ; break;\n case SID_INSERT_RLM : cMark = CHAR_RLM ; break;\n case SID_INSERT_LRM : cMark = CHAR_LRM ; break;\n case SID_INSERT_ZWSP : cMark = CHAR_ZWSP ; break;\n case SID_INSERT_ZWNBSP: cMark = CHAR_ZWNBSP; break;\n }\n\n DBG_ASSERT( cMark != 0, \"FuBullet::FuBullet(), illegal slot used!\" );\n\n if( cMark )\n InsertFormattingMark( cMark );\n }\n\n}\n\nvoid FuBullet::InsertFormattingMark( sal_Unicode cMark )\n{\n OutlinerView* pOV = NULL;\n ::Outliner* pOL = NULL;\n\n \/\/ depending on ViewShell set Outliner and OutlinerView\n if (mpViewShell->ISA(DrawViewShell))\n {\n pOV = mpView->GetTextEditOutlinerView();\n if (pOV)\n pOL = mpView->GetTextEditOutliner();\n }\n else if (mpViewShell->ISA(OutlineViewShell))\n {\n pOL = static_cast<OutlineView*>(mpView)->GetOutliner();\n pOV = static_cast<OutlineView*>(mpView)->GetViewByWindow(\n mpViewShell->GetActiveWindow());\n }\n\n \/\/ insert string\n if(pOV && pOL)\n {\n \/\/ prevent flickering\n pOV->HideCursor();\n pOL->SetUpdateMode(FALSE);\n\n \/\/ remove old selected text\n pOV->InsertText( aEmptyStr );\n\n \/\/ prepare undo\n SfxUndoManager& rUndoMgr = pOL->GetUndoManager();\n rUndoMgr.EnterListAction(String(SdResId(STR_UNDO_INSERT_SPECCHAR)),\n aEmptyStr );\n\n \/\/ insert given text\n String aStr( cMark );\n pOV->InsertText( cMark, TRUE);\n\n ESelection aSel = pOV->GetSelection();\n aSel.nStartPara = aSel.nEndPara;\n aSel.nStartPos = aSel.nEndPos;\n pOV->SetSelection(aSel);\n\n rUndoMgr.LeaveListAction();\n\n \/\/ restart repainting\n pOL->SetUpdateMode(TRUE);\n pOV->ShowCursor();\n }\n}\n\nvoid FuBullet::InsertSpecialCharacter()\n{\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n AbstractSvxCharacterMap* pDlg = pFact ? pFact->CreateSvxCharacterMap( NULL, RID_SVXDLG_CHARMAP, FALSE ) : 0;\n\n if( !pDlg )\n return;\n\n SfxItemSet aFontAttr( mpDoc->GetPool() );\n mpView->GetAttributes( aFontAttr );\n const SvxFontItem* pFontItem = (const SvxFontItem*)aFontAttr.GetItem( SID_ATTR_CHAR_FONT );\n if( pFontItem )\n {\n Font aCurrentFont( pFontItem->GetFamilyName(), pFontItem->GetStyleName(), Size( 1, 1 ) );\n pDlg->SetFont( aCurrentFont );\n }\n\n \/\/ Wenn Zeichen selektiert ist kann es angezeigt werden\n \/\/ pDLg->SetFont( );\n \/\/ pDlg->SetChar( );\n USHORT nResult = pDlg->Execute();\n\n \/\/char c;\n String aString;\n\n Font aFont;\n\n if( nResult == RET_OK )\n {\n aFont = pDlg->GetCharFont();\n aString = pDlg->GetCharacters();\n }\n delete( pDlg );\n\n if( nResult == RET_OK )\n {\n OutlinerView* pOV = NULL;\n ::Outliner* pOL = NULL;\n\n \/\/ je nach ViewShell Outliner und OutlinerView bestimmen\n if(mpViewShell && mpViewShell->ISA(DrawViewShell))\n {\n pOV = mpView->GetTextEditOutlinerView();\n if (pOV)\n {\n pOL = mpView->GetTextEditOutliner();\n }\n }\n else if(mpViewShell && mpViewShell->ISA(OutlineViewShell))\n {\n pOL = static_cast<OutlineView*>(mpView)->GetOutliner();\n pOV = static_cast<OutlineView*>(mpView)->GetViewByWindow(\n mpViewShell->GetActiveWindow());\n }\n\n \/\/ Sonderzeichen einfuegen\n if (pOV)\n {\n \/\/ nicht flackern\n pOV->HideCursor();\n pOL->SetUpdateMode(FALSE);\n\n \/\/ alte Attributierung merken;\n \/\/ dazu vorher selektierten Bereich loeschen, denn der muss eh weg\n \/\/ und so gibt es immer eine eindeutige Attributierung (und da es\n \/\/ kein DeleteSelected() an der OutlinerView gibt, wird durch\n \/\/ Einfuegen eines Leerstrings geloescht)\n pOV->InsertText( aEmptyStr );\n\n SfxItemSet aOldSet( mpDoc->GetPool(), ITEMID_FONT, ITEMID_FONT, 0 );\n aOldSet.Put( pOV->GetAttribs() );\n\n SfxUndoManager& rUndoMgr = pOL->GetUndoManager();\n rUndoMgr.EnterListAction(String(SdResId(STR_UNDO_INSERT_SPECCHAR)),\n aEmptyStr );\n pOV->InsertText(aString, TRUE);\n\n \/\/ attributieren (Font setzen)\n SfxItemSet aSet(pOL->GetEmptyItemSet());\n SvxFontItem aFontItem (aFont.GetFamily(), aFont.GetName(),\n aFont.GetStyleName(), aFont.GetPitch(),\n aFont.GetCharSet());\n aSet.Put(aFontItem);\n aSet.Put(aFontItem, EE_CHAR_FONTINFO_CJK);\n aSet.Put(aFontItem, EE_CHAR_FONTINFO_CTL);\n pOV->SetAttribs(aSet);\n\n ESelection aSel = pOV->GetSelection();\n aSel.nStartPara = aSel.nEndPara;\n aSel.nStartPos = aSel.nEndPos;\n pOV->SetSelection(aSel);\n\n \/\/ nicht mit Sonderzeichenattributierung weiterschreiben\n pOV->GetOutliner()->QuickSetAttribs(aOldSet, aSel);\n\n rUndoMgr.LeaveListAction();\n\n \/\/ ab jetzt wieder anzeigen\n pOL->SetUpdateMode(TRUE);\n pOV->ShowCursor();\n }\n }\n}\n\nvoid FuBullet::GetSlotState( SfxItemSet& rSet, ViewShell* pViewShell, SfxViewFrame* pViewFrame )\n{\n if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_BULLET ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_SOFT_HYPHEN ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_HARDHYPHEN ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_HARD_SPACE ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_RLM ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_LRM ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_ZWNBSP ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_ZWSP ))\n {\n ::sd::View* pView = pViewShell ? pViewShell->GetView() : 0;\n OutlinerView* pOLV = pView ? pView->GetTextEditOutlinerView() : 0;\n\n const bool bTextEdit = pOLV;\n\n SvtCTLOptions aCTLOptions;\n const sal_Bool bCtlEnabled = aCTLOptions.IsCTLFontEnabled();\n\n if(!bTextEdit )\n {\n rSet.DisableItem(SID_BULLET);\n rSet.DisableItem(FN_INSERT_SOFT_HYPHEN);\n rSet.DisableItem(FN_INSERT_HARDHYPHEN);\n rSet.DisableItem(FN_INSERT_HARD_SPACE);\n }\n\n if(!bTextEdit || !bCtlEnabled )\n {\n rSet.DisableItem(SID_INSERT_RLM);\n rSet.DisableItem(SID_INSERT_LRM);\n rSet.DisableItem(SID_INSERT_ZWNBSP);\n rSet.DisableItem(SID_INSERT_ZWSP);\n }\n\n if( pViewFrame )\n {\n SfxBindings& rBindings = pViewFrame->GetBindings();\n\n rBindings.SetVisibleState( SID_INSERT_RLM, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_LRM, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_ZWNBSP, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_ZWSP, bCtlEnabled );\n }\n }\n}\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS pchfix04 (1.10.6); FILE MERGED 2007\/02\/05 08:38:58 os 1.10.6.1: #i73604# usage of ITEMID_* removed<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fubullet.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 15:29:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fubullet.hxx\"\n\n#ifndef _BINDING_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _SFXPOOLITEM_HXX \/\/autogen\n#include <svtools\/poolitem.hxx>\n#endif\n#include <svx\/fontitem.hxx>\n\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_SHELL_HXX\n#include \"DrawViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\n#ifndef _SVDOUTL_HXX \/\/autogen\n#include <svx\/svdoutl.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVX_CHARMAP_HXX \/\/autogen\n#include <svx\/charmap.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SVTOOLS_CTLOPTIONS_HXX\n#include <svtools\/ctloptions.hxx>\n#endif\n\n#ifdef IRIX\n#ifndef _SBXCLASS_HXX\n#include <basic\/sbx.hxx>\n#endif\n#endif\n#include <svx\/svxdlg.hxx>\n#include <svx\/dialogs.hrc>\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n\n#include \"app.hrc\"\n\nnamespace sd {\n\nconst sal_Unicode CHAR_HARDBLANK = ((sal_Unicode)0x00A0);\nconst sal_Unicode CHAR_HARDHYPHEN = ((sal_Unicode)0x2011);\nconst sal_Unicode CHAR_SOFTHYPHEN = ((sal_Unicode)0x00AD);\nconst sal_Unicode CHAR_RLM = ((sal_Unicode)0x200F);\nconst sal_Unicode CHAR_LRM = ((sal_Unicode)0x200E);\nconst sal_Unicode CHAR_ZWSP = ((sal_Unicode)0x200B);\nconst sal_Unicode CHAR_ZWNBSP = ((sal_Unicode)0x2060);\n\nTYPEINIT1( FuBullet, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuBullet::FuBullet (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* _pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, _pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuBullet::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuBullet( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuBullet::DoExecute( SfxRequest& rReq )\n{\n if( rReq.GetSlot() == SID_BULLET )\n InsertSpecialCharacter();\n else\n {\n sal_Unicode cMark = 0;\n switch( rReq.GetSlot() )\n {\n case FN_INSERT_SOFT_HYPHEN: cMark = CHAR_SOFTHYPHEN ; break;\n case FN_INSERT_HARDHYPHEN: cMark = CHAR_HARDHYPHEN ; break;\n case FN_INSERT_HARD_SPACE: cMark = CHAR_HARDBLANK ; break;\n case SID_INSERT_RLM : cMark = CHAR_RLM ; break;\n case SID_INSERT_LRM : cMark = CHAR_LRM ; break;\n case SID_INSERT_ZWSP : cMark = CHAR_ZWSP ; break;\n case SID_INSERT_ZWNBSP: cMark = CHAR_ZWNBSP; break;\n }\n\n DBG_ASSERT( cMark != 0, \"FuBullet::FuBullet(), illegal slot used!\" );\n\n if( cMark )\n InsertFormattingMark( cMark );\n }\n\n}\n\nvoid FuBullet::InsertFormattingMark( sal_Unicode cMark )\n{\n OutlinerView* pOV = NULL;\n ::Outliner* pOL = NULL;\n\n \/\/ depending on ViewShell set Outliner and OutlinerView\n if (mpViewShell->ISA(DrawViewShell))\n {\n pOV = mpView->GetTextEditOutlinerView();\n if (pOV)\n pOL = mpView->GetTextEditOutliner();\n }\n else if (mpViewShell->ISA(OutlineViewShell))\n {\n pOL = static_cast<OutlineView*>(mpView)->GetOutliner();\n pOV = static_cast<OutlineView*>(mpView)->GetViewByWindow(\n mpViewShell->GetActiveWindow());\n }\n\n \/\/ insert string\n if(pOV && pOL)\n {\n \/\/ prevent flickering\n pOV->HideCursor();\n pOL->SetUpdateMode(FALSE);\n\n \/\/ remove old selected text\n pOV->InsertText( aEmptyStr );\n\n \/\/ prepare undo\n SfxUndoManager& rUndoMgr = pOL->GetUndoManager();\n rUndoMgr.EnterListAction(String(SdResId(STR_UNDO_INSERT_SPECCHAR)),\n aEmptyStr );\n\n \/\/ insert given text\n String aStr( cMark );\n pOV->InsertText( cMark, TRUE);\n\n ESelection aSel = pOV->GetSelection();\n aSel.nStartPara = aSel.nEndPara;\n aSel.nStartPos = aSel.nEndPos;\n pOV->SetSelection(aSel);\n\n rUndoMgr.LeaveListAction();\n\n \/\/ restart repainting\n pOL->SetUpdateMode(TRUE);\n pOV->ShowCursor();\n }\n}\n\nvoid FuBullet::InsertSpecialCharacter()\n{\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n AbstractSvxCharacterMap* pDlg = pFact ? pFact->CreateSvxCharacterMap( NULL, RID_SVXDLG_CHARMAP, FALSE ) : 0;\n\n if( !pDlg )\n return;\n\n SfxItemSet aFontAttr( mpDoc->GetPool() );\n mpView->GetAttributes( aFontAttr );\n const SvxFontItem* pFontItem = (const SvxFontItem*)aFontAttr.GetItem( SID_ATTR_CHAR_FONT );\n if( pFontItem )\n {\n Font aCurrentFont( pFontItem->GetFamilyName(), pFontItem->GetStyleName(), Size( 1, 1 ) );\n pDlg->SetFont( aCurrentFont );\n }\n\n \/\/ Wenn Zeichen selektiert ist kann es angezeigt werden\n \/\/ pDLg->SetFont( );\n \/\/ pDlg->SetChar( );\n USHORT nResult = pDlg->Execute();\n\n \/\/char c;\n String aString;\n\n Font aFont;\n\n if( nResult == RET_OK )\n {\n aFont = pDlg->GetCharFont();\n aString = pDlg->GetCharacters();\n }\n delete( pDlg );\n\n if( nResult == RET_OK )\n {\n OutlinerView* pOV = NULL;\n ::Outliner* pOL = NULL;\n\n \/\/ je nach ViewShell Outliner und OutlinerView bestimmen\n if(mpViewShell && mpViewShell->ISA(DrawViewShell))\n {\n pOV = mpView->GetTextEditOutlinerView();\n if (pOV)\n {\n pOL = mpView->GetTextEditOutliner();\n }\n }\n else if(mpViewShell && mpViewShell->ISA(OutlineViewShell))\n {\n pOL = static_cast<OutlineView*>(mpView)->GetOutliner();\n pOV = static_cast<OutlineView*>(mpView)->GetViewByWindow(\n mpViewShell->GetActiveWindow());\n }\n\n \/\/ Sonderzeichen einfuegen\n if (pOV)\n {\n \/\/ nicht flackern\n pOV->HideCursor();\n pOL->SetUpdateMode(FALSE);\n\n \/\/ alte Attributierung merken;\n \/\/ dazu vorher selektierten Bereich loeschen, denn der muss eh weg\n \/\/ und so gibt es immer eine eindeutige Attributierung (und da es\n \/\/ kein DeleteSelected() an der OutlinerView gibt, wird durch\n \/\/ Einfuegen eines Leerstrings geloescht)\n pOV->InsertText( aEmptyStr );\n\n SfxItemSet aOldSet( mpDoc->GetPool(), EE_CHAR_FONTINFO, EE_CHAR_FONTINFO, 0 );\n aOldSet.Put( pOV->GetAttribs() );\n\n SfxUndoManager& rUndoMgr = pOL->GetUndoManager();\n rUndoMgr.EnterListAction(String(SdResId(STR_UNDO_INSERT_SPECCHAR)),\n aEmptyStr );\n pOV->InsertText(aString, TRUE);\n\n \/\/ attributieren (Font setzen)\n SfxItemSet aSet(pOL->GetEmptyItemSet());\n SvxFontItem aFontItem (aFont.GetFamily(), aFont.GetName(),\n aFont.GetStyleName(), aFont.GetPitch(),\n aFont.GetCharSet(),\n EE_CHAR_FONTINFO);\n aSet.Put(aFontItem);\n aSet.Put(aFontItem, EE_CHAR_FONTINFO_CJK);\n aSet.Put(aFontItem, EE_CHAR_FONTINFO_CTL);\n pOV->SetAttribs(aSet);\n\n ESelection aSel = pOV->GetSelection();\n aSel.nStartPara = aSel.nEndPara;\n aSel.nStartPos = aSel.nEndPos;\n pOV->SetSelection(aSel);\n\n \/\/ nicht mit Sonderzeichenattributierung weiterschreiben\n pOV->GetOutliner()->QuickSetAttribs(aOldSet, aSel);\n\n rUndoMgr.LeaveListAction();\n\n \/\/ ab jetzt wieder anzeigen\n pOL->SetUpdateMode(TRUE);\n pOV->ShowCursor();\n }\n }\n}\n\nvoid FuBullet::GetSlotState( SfxItemSet& rSet, ViewShell* pViewShell, SfxViewFrame* pViewFrame )\n{\n if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_BULLET ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_SOFT_HYPHEN ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_HARDHYPHEN ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( FN_INSERT_HARD_SPACE ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_RLM ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_LRM ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_ZWNBSP ) ||\n SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_INSERT_ZWSP ))\n {\n ::sd::View* pView = pViewShell ? pViewShell->GetView() : 0;\n OutlinerView* pOLV = pView ? pView->GetTextEditOutlinerView() : 0;\n\n const bool bTextEdit = pOLV;\n\n SvtCTLOptions aCTLOptions;\n const sal_Bool bCtlEnabled = aCTLOptions.IsCTLFontEnabled();\n\n if(!bTextEdit )\n {\n rSet.DisableItem(SID_BULLET);\n rSet.DisableItem(FN_INSERT_SOFT_HYPHEN);\n rSet.DisableItem(FN_INSERT_HARDHYPHEN);\n rSet.DisableItem(FN_INSERT_HARD_SPACE);\n }\n\n if(!bTextEdit || !bCtlEnabled )\n {\n rSet.DisableItem(SID_INSERT_RLM);\n rSet.DisableItem(SID_INSERT_LRM);\n rSet.DisableItem(SID_INSERT_ZWNBSP);\n rSet.DisableItem(SID_INSERT_ZWSP);\n }\n\n if( pViewFrame )\n {\n SfxBindings& rBindings = pViewFrame->GetBindings();\n\n rBindings.SetVisibleState( SID_INSERT_RLM, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_LRM, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_ZWNBSP, bCtlEnabled );\n rBindings.SetVisibleState( SID_INSERT_ZWSP, bCtlEnabled );\n }\n }\n}\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuconarc.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 10:57:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"fuconarc.hxx\"\n\n#ifndef _SVDPAGV_HXX \/\/autogen\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDOCIRC_HXX \/\/autogen\n#include <svx\/svdocirc.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n#pragma hdrstop\n\n#include <svx\/svxids.hrc>\n#include <math.h>\n\n#include \"app.hrc\"\n\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"res_bmp.hrc\"\n#ifndef SD_OBJECT_BAR_MANAGER_HXX\n#include \"ObjectBarManager.hxx\"\n#endif\n\n\/\/ #97016#\n#ifndef _SXCIAITM_HXX\n#include <svx\/sxciaitm.hxx>\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuConstructArc, FuConstruct );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::FuConstructArc (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq )\n : FuConstruct( pViewSh, pWin, pView, pDoc, rReq )\n{\n pViewShell->GetObjectBarManager().SwitchObjectBar (RID_DRAW_OBJ_TOOLBOX);\n\n const SfxItemSet *pArgs = rReq.GetArgs ();\n\n if (pArgs)\n {\n SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);\n SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);\n\n Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () - pAxisY->GetValue () \/ 2,\n pCenterX->GetValue () + pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () + pAxisY->GetValue () \/ 2);\n\n Activate(); \/\/ Setzt aObjKind\n SdrCircObj* pNewCircle =\n new SdrCircObj((SdrObjKind) pView->GetCurrentObjIdentifier(),\n aNewRectangle,\n (long) (pPhiStart->GetValue () * 10.0),\n (long) (pPhiEnd->GetValue () * 10.0));\n SdrPageView *pPV = pView->GetPageViewPvNum (0);\n\n pView->InsertObject(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);\n }\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::~FuConstructArc()\n{\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );\n\n if ( rMEvt.IsLeft() && !pView->IsAction() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n pWindow->CaptureMouse();\n USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );\n pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);\n\n SdrObject* pObj = pView->GetCreateObj();\n\n if (pObj)\n {\n SfxItemSet aAttr(pDoc->GetPool());\n SetStyleSheet(aAttr, pObj);\n\n\/\/-\/ pObj->NbcSetAttributes(aAttr, FALSE);\n pObj->SetMergedItemSet(aAttr);\n }\n\n bReturn = TRUE;\n }\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )\n{\n return FuConstruct::MouseMove(rMEvt);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FALSE;\n BOOL bCreated = FALSE;\n\n if ( pView->IsCreateObj() && rMEvt.IsLeft() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n\n ULONG nCount = pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount();\n\n if (pView->EndCreateObj(SDRCREATE_NEXTPOINT) )\n {\n if (nCount != pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount())\n {\n bCreated = TRUE;\n }\n }\n\n bReturn = TRUE;\n }\n\n bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;\n\n if (!bPermanent && bCreated)\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);\n\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FuConstruct::KeyInput(rKEvt);\n return(bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Activate()\n{\n SdrObjKind aObjKind;\n\n switch( nSlotId )\n {\n case SID_DRAW_ARC :\n case SID_DRAW_CIRCLEARC:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n\n case SID_DRAW_PIE :\n case SID_DRAW_PIE_NOFILL :\n case SID_DRAW_CIRCLEPIE :\n case SID_DRAW_CIRCLEPIE_NOFILL:\n {\n aObjKind = OBJ_SECT;\n }\n break;\n\n case SID_DRAW_ELLIPSECUT :\n case SID_DRAW_ELLIPSECUT_NOFILL:\n case SID_DRAW_CIRCLECUT :\n case SID_DRAW_CIRCLECUT_NOFILL :\n {\n aObjKind = OBJ_CCUT;\n }\n break;\n\n default:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n }\n\n pView->SetCurrentObj(aObjKind);\n\n FuConstruct::Activate();\n\/\/ FuDraw::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Deactivate()\n{\n FuConstruct::Deactivate();\n\/\/ FuDraw::Deactivate();\n}\n\n\/\/ #97016#\nSdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)\n{\n \/\/ case SID_DRAW_ARC:\n \/\/ case SID_DRAW_CIRCLEARC:\n \/\/ case SID_DRAW_PIE:\n \/\/ case SID_DRAW_PIE_NOFILL:\n \/\/ case SID_DRAW_CIRCLEPIE:\n \/\/ case SID_DRAW_CIRCLEPIE_NOFILL:\n \/\/ case SID_DRAW_ELLIPSECUT:\n \/\/ case SID_DRAW_ELLIPSECUT_NOFILL:\n \/\/ case SID_DRAW_CIRCLECUT:\n \/\/ case SID_DRAW_CIRCLECUT_NOFILL:\n\n SdrObject* pObj = SdrObjFactory::MakeNewObject(\n pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),\n 0L, pDoc);\n\n if(pObj)\n {\n if(pObj->ISA(SdrCircObj))\n {\n Rectangle aRect(rRectangle);\n\n if(SID_DRAW_ARC == nID ||\n SID_DRAW_CIRCLEARC == nID ||\n SID_DRAW_CIRCLEPIE == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_CIRCLECUT == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n \/\/ force quadratic\n ImpForceQuadratic(aRect);\n }\n\n pObj->SetLogicRect(aRect);\n\n SfxItemSet aAttr(pDoc->GetPool());\n aAttr.Put(SdrCircStartAngleItem(9000));\n aAttr.Put(SdrCircEndAngleItem(0));\n\n if(SID_DRAW_PIE_NOFILL == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_ELLIPSECUT_NOFILL == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n aAttr.Put(XFillStyleItem(XFILL_NONE));\n }\n\n pObj->SetMergedItemSet(aAttr);\n }\n else\n {\n DBG_ERROR(\"Object is NO circle object\");\n }\n }\n\n return pObj;\n}\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS ooo19126 (1.9.562); FILE MERGED 2005\/09\/05 13:22:11 rt 1.9.562.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuconarc.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 04:35:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"fuconarc.hxx\"\n\n#ifndef _SVDPAGV_HXX \/\/autogen\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDOCIRC_HXX \/\/autogen\n#include <svx\/svdocirc.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n#pragma hdrstop\n\n#include <svx\/svxids.hrc>\n#include <math.h>\n\n#include \"app.hrc\"\n\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"res_bmp.hrc\"\n#ifndef SD_OBJECT_BAR_MANAGER_HXX\n#include \"ObjectBarManager.hxx\"\n#endif\n\n\/\/ #97016#\n#ifndef _SXCIAITM_HXX\n#include <svx\/sxciaitm.hxx>\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuConstructArc, FuConstruct );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::FuConstructArc (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq )\n : FuConstruct( pViewSh, pWin, pView, pDoc, rReq )\n{\n pViewShell->GetObjectBarManager().SwitchObjectBar (RID_DRAW_OBJ_TOOLBOX);\n\n const SfxItemSet *pArgs = rReq.GetArgs ();\n\n if (pArgs)\n {\n SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);\n SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);\n\n Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () - pAxisY->GetValue () \/ 2,\n pCenterX->GetValue () + pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () + pAxisY->GetValue () \/ 2);\n\n Activate(); \/\/ Setzt aObjKind\n SdrCircObj* pNewCircle =\n new SdrCircObj((SdrObjKind) pView->GetCurrentObjIdentifier(),\n aNewRectangle,\n (long) (pPhiStart->GetValue () * 10.0),\n (long) (pPhiEnd->GetValue () * 10.0));\n SdrPageView *pPV = pView->GetPageViewPvNum (0);\n\n pView->InsertObject(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);\n }\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::~FuConstructArc()\n{\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );\n\n if ( rMEvt.IsLeft() && !pView->IsAction() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n pWindow->CaptureMouse();\n USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );\n pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);\n\n SdrObject* pObj = pView->GetCreateObj();\n\n if (pObj)\n {\n SfxItemSet aAttr(pDoc->GetPool());\n SetStyleSheet(aAttr, pObj);\n\n\/\/-\/ pObj->NbcSetAttributes(aAttr, FALSE);\n pObj->SetMergedItemSet(aAttr);\n }\n\n bReturn = TRUE;\n }\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )\n{\n return FuConstruct::MouseMove(rMEvt);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FALSE;\n BOOL bCreated = FALSE;\n\n if ( pView->IsCreateObj() && rMEvt.IsLeft() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n\n ULONG nCount = pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount();\n\n if (pView->EndCreateObj(SDRCREATE_NEXTPOINT) )\n {\n if (nCount != pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount())\n {\n bCreated = TRUE;\n }\n }\n\n bReturn = TRUE;\n }\n\n bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;\n\n if (!bPermanent && bCreated)\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);\n\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FuConstruct::KeyInput(rKEvt);\n return(bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Activate()\n{\n SdrObjKind aObjKind;\n\n switch( nSlotId )\n {\n case SID_DRAW_ARC :\n case SID_DRAW_CIRCLEARC:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n\n case SID_DRAW_PIE :\n case SID_DRAW_PIE_NOFILL :\n case SID_DRAW_CIRCLEPIE :\n case SID_DRAW_CIRCLEPIE_NOFILL:\n {\n aObjKind = OBJ_SECT;\n }\n break;\n\n case SID_DRAW_ELLIPSECUT :\n case SID_DRAW_ELLIPSECUT_NOFILL:\n case SID_DRAW_CIRCLECUT :\n case SID_DRAW_CIRCLECUT_NOFILL :\n {\n aObjKind = OBJ_CCUT;\n }\n break;\n\n default:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n }\n\n pView->SetCurrentObj(aObjKind);\n\n FuConstruct::Activate();\n\/\/ FuDraw::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Deactivate()\n{\n FuConstruct::Deactivate();\n\/\/ FuDraw::Deactivate();\n}\n\n\/\/ #97016#\nSdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)\n{\n \/\/ case SID_DRAW_ARC:\n \/\/ case SID_DRAW_CIRCLEARC:\n \/\/ case SID_DRAW_PIE:\n \/\/ case SID_DRAW_PIE_NOFILL:\n \/\/ case SID_DRAW_CIRCLEPIE:\n \/\/ case SID_DRAW_CIRCLEPIE_NOFILL:\n \/\/ case SID_DRAW_ELLIPSECUT:\n \/\/ case SID_DRAW_ELLIPSECUT_NOFILL:\n \/\/ case SID_DRAW_CIRCLECUT:\n \/\/ case SID_DRAW_CIRCLECUT_NOFILL:\n\n SdrObject* pObj = SdrObjFactory::MakeNewObject(\n pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),\n 0L, pDoc);\n\n if(pObj)\n {\n if(pObj->ISA(SdrCircObj))\n {\n Rectangle aRect(rRectangle);\n\n if(SID_DRAW_ARC == nID ||\n SID_DRAW_CIRCLEARC == nID ||\n SID_DRAW_CIRCLEPIE == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_CIRCLECUT == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n \/\/ force quadratic\n ImpForceQuadratic(aRect);\n }\n\n pObj->SetLogicRect(aRect);\n\n SfxItemSet aAttr(pDoc->GetPool());\n aAttr.Put(SdrCircStartAngleItem(9000));\n aAttr.Put(SdrCircEndAngleItem(0));\n\n if(SID_DRAW_PIE_NOFILL == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_ELLIPSECUT_NOFILL == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n aAttr.Put(XFillStyleItem(XFILL_NONE));\n }\n\n pObj->SetMergedItemSet(aAttr);\n }\n else\n {\n DBG_ERROR(\"Object is NO circle object\");\n }\n }\n\n return pObj;\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/ui\/idle_logout_dialog_view.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/time.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/chromeos\/kiosk_mode\/kiosk_mode_settings.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Global singleton instance of our dialog class.\nchromeos::IdleLogoutDialogView* g_instance = NULL;\n\nconst int kIdleLogoutDialogMaxWidth = 400;\nconst int kCountdownUpdateIntervalMs = 1000;\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nIdleLogoutSettingsProvider* IdleLogoutDialogView::provider_ = NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutSettingsProvider public methods\nIdleLogoutSettingsProvider::IdleLogoutSettingsProvider() {\n}\n\nIdleLogoutSettingsProvider::~IdleLogoutSettingsProvider() {\n}\n\nbase::TimeDelta IdleLogoutSettingsProvider::GetCountdownUpdateInterval() {\n return base::TimeDelta::FromMilliseconds(kCountdownUpdateIntervalMs);\n}\n\nKioskModeSettings* IdleLogoutSettingsProvider::GetKioskModeSettings() {\n return KioskModeSettings::Get();\n}\n\nvoid IdleLogoutSettingsProvider::LogoutCurrentUser(IdleLogoutDialogView*) {\n BrowserList::ExitCleanly();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutDialogView public static methods\n\/\/ static\nvoid IdleLogoutDialogView::ShowDialog() {\n \/\/ We only show the dialog if it is not already showing. We don't want two\n \/\/ countdowns on the screen for any reason. If the dialog is closed by using\n \/\/ CloseDialog, we reset g_instance so the next Show will work correctly; in\n \/\/ case the dialog is closed by the system, DeleteDelegate is guaranteed to be\n \/\/ called, in which case we reset g_instance there if not already reset.\n if (!g_instance) {\n g_instance = new IdleLogoutDialogView();\n g_instance->Init();\n g_instance->Show();\n }\n}\n\n\/\/ static\nvoid IdleLogoutDialogView::CloseDialog() {\n if (g_instance) {\n g_instance->set_closed();\n g_instance->Close();\n g_instance = NULL;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Overridden from views::DialogDelegateView\nint IdleLogoutDialogView::GetDialogButtons() const {\n return ui::DIALOG_BUTTON_NONE;\n}\n\nui::ModalType IdleLogoutDialogView::GetModalType() const {\n return ui::MODAL_TYPE_WINDOW;\n}\n\nstring16 IdleLogoutDialogView::GetWindowTitle() const {\n return l10n_util::GetStringUTF16(IDS_IDLE_LOGOUT_TITLE);\n}\n\nviews::View* IdleLogoutDialogView::GetContentsView() {\n return this;\n}\n\nvoid IdleLogoutDialogView::DeleteDelegate() {\n \/\/ There isn't a delegate method that is called on close and is 'not' called\n \/\/ async; this can cause an issue with us setting the g_instance to NULL\n \/\/ 'after' another Show call has been called on it. So instead, we rely on\n \/\/ CloseIdleLogoutDialog to set g_instance to NULL; in the case that we get\n \/\/ closed by any other way than CloseIdleLogoutDialog, we check if our\n \/\/ 'closed' state is set - if not, then we set it and set g_instance to null,\n \/\/ since that means that CloseIdleLogoutDialog was never called.\n if (!this->is_closed()) {\n g_instance->set_closed();\n g_instance = NULL;\n }\n\n delete this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutDialog private methods\nIdleLogoutDialogView::IdleLogoutDialogView()\n : restart_label_(NULL),\n warning_label_(NULL),\n weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n if (!IdleLogoutDialogView::provider_)\n IdleLogoutDialogView::provider_ = new IdleLogoutSettingsProvider();\n}\n\nIdleLogoutDialogView::~IdleLogoutDialogView() {\n}\n\nvoid IdleLogoutDialogView::Init() {\n KioskModeSettings* settings =\n IdleLogoutDialogView::provider_->GetKioskModeSettings();\n if (!settings->is_initialized()) {\n settings->Initialize(base::Bind(&IdleLogoutDialogView::Init,\n weak_ptr_factory_.GetWeakPtr()));\n return;\n }\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n\n warning_label_ = new views::Label(\n l10n_util::GetStringUTF16(IDS_IDLE_LOGOUT_WARNING));\n warning_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n warning_label_->SetMultiLine(true);\n warning_label_->SetFont(rb.GetFont(ui::ResourceBundle::BaseFont));\n warning_label_->SizeToFit(kIdleLogoutDialogMaxWidth);\n\n restart_label_ = new views::Label();\n restart_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n restart_label_->SetFont(rb.GetFont(ui::ResourceBundle::BoldFont));\n\n views::GridLayout* layout = views::GridLayout::CreatePanel(this);\n SetLayoutManager(layout);\n\n views::ColumnSet* column_set = layout->AddColumnSet(0);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER, 1,\n views::GridLayout::USE_PREF, 0, 0);\n layout->StartRow(0, 0);\n layout->AddView(warning_label_);\n layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);\n layout->StartRow(0, 0);\n layout->AddView(restart_label_);\n}\n\nvoid IdleLogoutDialogView::Show() {\n KioskModeSettings* settings =\n IdleLogoutDialogView::provider_->GetKioskModeSettings();\n\n \/\/ Setup the countdown label before showing.\n countdown_end_time_ = base::Time::Now() +\n settings->GetIdleLogoutWarningDuration();\n\n UpdateCountdown();\n\n views::Widget::CreateWindow(this);\n GetWidget()->SetAlwaysOnTop(true);\n GetWidget()->Show();\n\n \/\/ Update countdown every 1 second.\n timer_.Start(FROM_HERE,\n IdleLogoutDialogView::provider_->GetCountdownUpdateInterval(),\n this,\n &IdleLogoutDialogView::UpdateCountdown);\n}\n\nvoid IdleLogoutDialogView::Close() {\n DCHECK(GetWidget());\n\n if (timer_.IsRunning())\n timer_.Stop();\n GetWidget()->Close();\n}\n\nvoid IdleLogoutDialogView::UpdateCountdown() {\n base::TimeDelta logout_warning_time = countdown_end_time_ -\n base::Time::Now();\n int64 seconds_left = (logout_warning_time.InMillisecondsF() \/\n base::Time::kMillisecondsPerSecond) + 0.5;\n\n if (seconds_left > 1) {\n restart_label_->SetText(l10n_util::GetStringFUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART,\n base::Int64ToString16(seconds_left)));\n } else if (seconds_left > 0) {\n restart_label_->SetText(l10n_util::GetStringUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART_1S));\n } else {\n \/\/ Set the label - the logout probably won't be instant.\n restart_label_->SetText(l10n_util::GetStringUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART_NOW));\n\n \/\/ We're done; stop the timer and logout.\n timer_.Stop();\n IdleLogoutDialogView::provider_->LogoutCurrentUser(this);\n }\n}\n\n\/\/ static\nIdleLogoutDialogView* IdleLogoutDialogView::current_instance() {\n return g_instance;\n}\n\n\/\/ static\nvoid IdleLogoutDialogView::set_settings_provider(\n IdleLogoutSettingsProvider* provider) {\n provider_ = provider;\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Make idle logout window not cause the app list to disappear. When the app list is up, create the idle logout window as a child of the app list. This way the idle logout window will still always be on top but will not cause the app list to disappear.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/ui\/idle_logout_dialog_view.h\"\n\n#include \"ash\/shell.h\"\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/time.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/chromeos\/kiosk_mode\/kiosk_mode_settings.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Global singleton instance of our dialog class.\nchromeos::IdleLogoutDialogView* g_instance = NULL;\n\nconst int kIdleLogoutDialogMaxWidth = 400;\nconst int kCountdownUpdateIntervalMs = 1000;\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nIdleLogoutSettingsProvider* IdleLogoutDialogView::provider_ = NULL;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutSettingsProvider public methods\nIdleLogoutSettingsProvider::IdleLogoutSettingsProvider() {\n}\n\nIdleLogoutSettingsProvider::~IdleLogoutSettingsProvider() {\n}\n\nbase::TimeDelta IdleLogoutSettingsProvider::GetCountdownUpdateInterval() {\n return base::TimeDelta::FromMilliseconds(kCountdownUpdateIntervalMs);\n}\n\nKioskModeSettings* IdleLogoutSettingsProvider::GetKioskModeSettings() {\n return KioskModeSettings::Get();\n}\n\nvoid IdleLogoutSettingsProvider::LogoutCurrentUser(IdleLogoutDialogView*) {\n BrowserList::ExitCleanly();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutDialogView public static methods\n\/\/ static\nvoid IdleLogoutDialogView::ShowDialog() {\n \/\/ We only show the dialog if it is not already showing. We don't want two\n \/\/ countdowns on the screen for any reason. If the dialog is closed by using\n \/\/ CloseDialog, we reset g_instance so the next Show will work correctly; in\n \/\/ case the dialog is closed by the system, DeleteDelegate is guaranteed to be\n \/\/ called, in which case we reset g_instance there if not already reset.\n if (!g_instance) {\n g_instance = new IdleLogoutDialogView();\n g_instance->Init();\n g_instance->Show();\n }\n}\n\n\/\/ static\nvoid IdleLogoutDialogView::CloseDialog() {\n if (g_instance) {\n g_instance->set_closed();\n g_instance->Close();\n g_instance = NULL;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Overridden from views::DialogDelegateView\nint IdleLogoutDialogView::GetDialogButtons() const {\n return ui::DIALOG_BUTTON_NONE;\n}\n\nui::ModalType IdleLogoutDialogView::GetModalType() const {\n return ui::MODAL_TYPE_WINDOW;\n}\n\nstring16 IdleLogoutDialogView::GetWindowTitle() const {\n return l10n_util::GetStringUTF16(IDS_IDLE_LOGOUT_TITLE);\n}\n\nviews::View* IdleLogoutDialogView::GetContentsView() {\n return this;\n}\n\nvoid IdleLogoutDialogView::DeleteDelegate() {\n \/\/ There isn't a delegate method that is called on close and is 'not' called\n \/\/ async; this can cause an issue with us setting the g_instance to NULL\n \/\/ 'after' another Show call has been called on it. So instead, we rely on\n \/\/ CloseIdleLogoutDialog to set g_instance to NULL; in the case that we get\n \/\/ closed by any other way than CloseIdleLogoutDialog, we check if our\n \/\/ 'closed' state is set - if not, then we set it and set g_instance to null,\n \/\/ since that means that CloseIdleLogoutDialog was never called.\n if (!this->is_closed()) {\n g_instance->set_closed();\n g_instance = NULL;\n }\n\n delete this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ IdleLogoutDialog private methods\nIdleLogoutDialogView::IdleLogoutDialogView()\n : restart_label_(NULL),\n warning_label_(NULL),\n weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n if (!IdleLogoutDialogView::provider_)\n IdleLogoutDialogView::provider_ = new IdleLogoutSettingsProvider();\n}\n\nIdleLogoutDialogView::~IdleLogoutDialogView() {\n}\n\nvoid IdleLogoutDialogView::Init() {\n KioskModeSettings* settings =\n IdleLogoutDialogView::provider_->GetKioskModeSettings();\n if (!settings->is_initialized()) {\n settings->Initialize(base::Bind(&IdleLogoutDialogView::Init,\n weak_ptr_factory_.GetWeakPtr()));\n return;\n }\n\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n\n warning_label_ = new views::Label(\n l10n_util::GetStringUTF16(IDS_IDLE_LOGOUT_WARNING));\n warning_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n warning_label_->SetMultiLine(true);\n warning_label_->SetFont(rb.GetFont(ui::ResourceBundle::BaseFont));\n warning_label_->SizeToFit(kIdleLogoutDialogMaxWidth);\n\n restart_label_ = new views::Label();\n restart_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n restart_label_->SetFont(rb.GetFont(ui::ResourceBundle::BoldFont));\n\n views::GridLayout* layout = views::GridLayout::CreatePanel(this);\n SetLayoutManager(layout);\n\n views::ColumnSet* column_set = layout->AddColumnSet(0);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER, 1,\n views::GridLayout::USE_PREF, 0, 0);\n layout->StartRow(0, 0);\n layout->AddView(warning_label_);\n layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);\n layout->StartRow(0, 0);\n layout->AddView(restart_label_);\n}\n\nvoid IdleLogoutDialogView::Show() {\n KioskModeSettings* settings =\n IdleLogoutDialogView::provider_->GetKioskModeSettings();\n\n \/\/ Setup the countdown label before showing.\n countdown_end_time_ = base::Time::Now() +\n settings->GetIdleLogoutWarningDuration();\n\n UpdateCountdown();\n\n \/\/ If the apps list is displayed, we should show as it's child. Not doing\n \/\/ so will cause the apps list to disappear.\n gfx::NativeWindow app_list = ash::Shell::GetInstance()->GetAppListWindow();\n if (app_list) {\n views::Widget::CreateWindowWithParent(this, app_list);\n } else {\n views::Widget::CreateWindow(this);\n GetWidget()->SetAlwaysOnTop(true);\n }\n GetWidget()->Show();\n\n \/\/ Update countdown every 1 second.\n timer_.Start(FROM_HERE,\n IdleLogoutDialogView::provider_->GetCountdownUpdateInterval(),\n this,\n &IdleLogoutDialogView::UpdateCountdown);\n}\n\nvoid IdleLogoutDialogView::Close() {\n DCHECK(GetWidget());\n\n if (timer_.IsRunning())\n timer_.Stop();\n GetWidget()->Close();\n}\n\nvoid IdleLogoutDialogView::UpdateCountdown() {\n base::TimeDelta logout_warning_time = countdown_end_time_ -\n base::Time::Now();\n int64 seconds_left = (logout_warning_time.InMillisecondsF() \/\n base::Time::kMillisecondsPerSecond) + 0.5;\n\n if (seconds_left > 1) {\n restart_label_->SetText(l10n_util::GetStringFUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART,\n base::Int64ToString16(seconds_left)));\n } else if (seconds_left > 0) {\n restart_label_->SetText(l10n_util::GetStringUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART_1S));\n } else {\n \/\/ Set the label - the logout probably won't be instant.\n restart_label_->SetText(l10n_util::GetStringUTF16(\n IDS_IDLE_LOGOUT_WARNING_RESTART_NOW));\n\n \/\/ We're done; stop the timer and logout.\n timer_.Stop();\n IdleLogoutDialogView::provider_->LogoutCurrentUser(this);\n }\n}\n\n\/\/ static\nIdleLogoutDialogView* IdleLogoutDialogView::current_instance() {\n return g_instance;\n}\n\n\/\/ static\nvoid IdleLogoutDialogView::set_settings_provider(\n IdleLogoutSettingsProvider* provider) {\n provider_ = provider;\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuconarc.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-03-21 17:15:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"fuconarc.hxx\"\n\n#ifndef _SVDPAGV_HXX \/\/autogen\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDOCIRC_HXX \/\/autogen\n#include <svx\/svdocirc.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n#pragma hdrstop\n\n#include <svx\/svxids.hrc>\n#include <math.h>\n\n#include \"app.hrc\"\n\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"res_bmp.hrc\"\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_BASE_HXX\n#include \"ViewShellBase.hxx\"\n#endif\n#ifndef SD_TOOL_BAR_MANAGER_HXX\n#include \"ToolBarManager.hxx\"\n#endif\n\n\/\/ #97016#\n#ifndef _SXCIAITM_HXX\n#include <svx\/sxciaitm.hxx>\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuConstructArc, FuConstruct );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::FuConstructArc (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq )\n : FuConstruct( pViewSh, pWin, pView, pDoc, rReq )\n{\n}\n\nFunctionReference FuConstructArc::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent )\n{\n FuConstructArc* pFunc;\n FunctionReference xFunc( pFunc = new FuConstructArc( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n pFunc->SetPermanent(bPermanent);\n return xFunc;\n}\n\nvoid FuConstructArc::DoExecute( SfxRequest& rReq )\n{\n FuConstruct::DoExecute( rReq );\n\n pViewShell->GetViewShellBase().GetToolBarManager().SetToolBar(\n ToolBarManager::TBG_FUNCTION,\n ToolBarManager::msDrawingObjectToolBar);\n\n const SfxItemSet *pArgs = rReq.GetArgs ();\n\n if (pArgs)\n {\n SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);\n SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);\n\n Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () - pAxisY->GetValue () \/ 2,\n pCenterX->GetValue () + pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () + pAxisY->GetValue () \/ 2);\n\n Activate(); \/\/ Setzt aObjKind\n SdrCircObj* pNewCircle =\n new SdrCircObj((SdrObjKind) pView->GetCurrentObjIdentifier(),\n aNewRectangle,\n (long) (pPhiStart->GetValue () * 10.0),\n (long) (pPhiEnd->GetValue () * 10.0));\n SdrPageView *pPV = pView->GetPageViewPvNum (0);\n\n pView->InsertObject(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);\n }\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );\n\n if ( rMEvt.IsLeft() && !pView->IsAction() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n pWindow->CaptureMouse();\n USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );\n pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);\n\n SdrObject* pObj = pView->GetCreateObj();\n\n if (pObj)\n {\n SfxItemSet aAttr(pDoc->GetPool());\n SetStyleSheet(aAttr, pObj);\n\n\/\/-\/ pObj->NbcSetAttributes(aAttr, FALSE);\n pObj->SetMergedItemSet(aAttr);\n }\n\n bReturn = TRUE;\n }\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )\n{\n return FuConstruct::MouseMove(rMEvt);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FALSE;\n BOOL bCreated = FALSE;\n\n if ( pView->IsCreateObj() && rMEvt.IsLeft() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n\n ULONG nCount = pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount();\n\n if (pView->EndCreateObj(SDRCREATE_NEXTPOINT) )\n {\n if (nCount != pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount())\n {\n bCreated = TRUE;\n }\n }\n\n bReturn = TRUE;\n }\n\n bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;\n\n if (!bPermanent && bCreated)\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);\n\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FuConstruct::KeyInput(rKEvt);\n return(bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Activate()\n{\n SdrObjKind aObjKind;\n\n switch( nSlotId )\n {\n case SID_DRAW_ARC :\n case SID_DRAW_CIRCLEARC:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n\n case SID_DRAW_PIE :\n case SID_DRAW_PIE_NOFILL :\n case SID_DRAW_CIRCLEPIE :\n case SID_DRAW_CIRCLEPIE_NOFILL:\n {\n aObjKind = OBJ_SECT;\n }\n break;\n\n case SID_DRAW_ELLIPSECUT :\n case SID_DRAW_ELLIPSECUT_NOFILL:\n case SID_DRAW_CIRCLECUT :\n case SID_DRAW_CIRCLECUT_NOFILL :\n {\n aObjKind = OBJ_CCUT;\n }\n break;\n\n default:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n }\n\n pView->SetCurrentObj(aObjKind);\n\n FuConstruct::Activate();\n\/\/ FuDraw::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Deactivate()\n{\n FuConstruct::Deactivate();\n\/\/ FuDraw::Deactivate();\n}\n\n\/\/ #97016#\nSdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)\n{\n \/\/ case SID_DRAW_ARC:\n \/\/ case SID_DRAW_CIRCLEARC:\n \/\/ case SID_DRAW_PIE:\n \/\/ case SID_DRAW_PIE_NOFILL:\n \/\/ case SID_DRAW_CIRCLEPIE:\n \/\/ case SID_DRAW_CIRCLEPIE_NOFILL:\n \/\/ case SID_DRAW_ELLIPSECUT:\n \/\/ case SID_DRAW_ELLIPSECUT_NOFILL:\n \/\/ case SID_DRAW_CIRCLECUT:\n \/\/ case SID_DRAW_CIRCLECUT_NOFILL:\n\n SdrObject* pObj = SdrObjFactory::MakeNewObject(\n pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),\n 0L, pDoc);\n\n if(pObj)\n {\n if(pObj->ISA(SdrCircObj))\n {\n Rectangle aRect(rRectangle);\n\n if(SID_DRAW_ARC == nID ||\n SID_DRAW_CIRCLEARC == nID ||\n SID_DRAW_CIRCLEPIE == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_CIRCLECUT == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n \/\/ force quadratic\n ImpForceQuadratic(aRect);\n }\n\n pObj->SetLogicRect(aRect);\n\n SfxItemSet aAttr(pDoc->GetPool());\n aAttr.Put(SdrCircStartAngleItem(9000));\n aAttr.Put(SdrCircEndAngleItem(0));\n\n if(SID_DRAW_PIE_NOFILL == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_ELLIPSECUT_NOFILL == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n aAttr.Put(XFillStyleItem(XFILL_NONE));\n }\n\n pObj->SetMergedItemSet(aAttr);\n }\n else\n {\n DBG_ERROR(\"Object is NO circle object\");\n }\n }\n\n return pObj;\n}\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS pchfix02 (1.12.142); FILE MERGED 2006\/09\/01 17:37:05 kaib 1.12.142.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuconarc.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 18:47:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"fuconarc.hxx\"\n\n#ifndef _SVDPAGV_HXX \/\/autogen\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDOCIRC_HXX \/\/autogen\n#include <svx\/svdocirc.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n\n#include <svx\/svxids.hrc>\n#include <math.h>\n\n#include \"app.hrc\"\n\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"res_bmp.hrc\"\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_BASE_HXX\n#include \"ViewShellBase.hxx\"\n#endif\n#ifndef SD_TOOL_BAR_MANAGER_HXX\n#include \"ToolBarManager.hxx\"\n#endif\n\n\/\/ #97016#\n#ifndef _SXCIAITM_HXX\n#include <svx\/sxciaitm.hxx>\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuConstructArc, FuConstruct );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuConstructArc::FuConstructArc (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq )\n : FuConstruct( pViewSh, pWin, pView, pDoc, rReq )\n{\n}\n\nFunctionReference FuConstructArc::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent )\n{\n FuConstructArc* pFunc;\n FunctionReference xFunc( pFunc = new FuConstructArc( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n pFunc->SetPermanent(bPermanent);\n return xFunc;\n}\n\nvoid FuConstructArc::DoExecute( SfxRequest& rReq )\n{\n FuConstruct::DoExecute( rReq );\n\n pViewShell->GetViewShellBase().GetToolBarManager().SetToolBar(\n ToolBarManager::TBG_FUNCTION,\n ToolBarManager::msDrawingObjectToolBar);\n\n const SfxItemSet *pArgs = rReq.GetArgs ();\n\n if (pArgs)\n {\n SFX_REQUEST_ARG (rReq, pCenterX, SfxUInt32Item, ID_VAL_CENTER_X, FALSE);\n SFX_REQUEST_ARG (rReq, pCenterY, SfxUInt32Item, ID_VAL_CENTER_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisX, SfxUInt32Item, ID_VAL_AXIS_X, FALSE);\n SFX_REQUEST_ARG (rReq, pAxisY, SfxUInt32Item, ID_VAL_AXIS_Y, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiStart, SfxUInt32Item, ID_VAL_ANGLESTART, FALSE);\n SFX_REQUEST_ARG (rReq, pPhiEnd, SfxUInt32Item, ID_VAL_ANGLEEND, FALSE);\n\n Rectangle aNewRectangle (pCenterX->GetValue () - pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () - pAxisY->GetValue () \/ 2,\n pCenterX->GetValue () + pAxisX->GetValue () \/ 2,\n pCenterY->GetValue () + pAxisY->GetValue () \/ 2);\n\n Activate(); \/\/ Setzt aObjKind\n SdrCircObj* pNewCircle =\n new SdrCircObj((SdrObjKind) pView->GetCurrentObjIdentifier(),\n aNewRectangle,\n (long) (pPhiStart->GetValue () * 10.0),\n (long) (pPhiEnd->GetValue () * 10.0));\n SdrPageView *pPV = pView->GetPageViewPvNum (0);\n\n pView->InsertObject(pNewCircle, *pPV, SDRINSERT_SETDEFLAYER);\n }\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonDown( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FuConstruct::MouseButtonDown( rMEvt );\n\n if ( rMEvt.IsLeft() && !pView->IsAction() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n pWindow->CaptureMouse();\n USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );\n pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);\n\n SdrObject* pObj = pView->GetCreateObj();\n\n if (pObj)\n {\n SfxItemSet aAttr(pDoc->GetPool());\n SetStyleSheet(aAttr, pObj);\n\n\/\/-\/ pObj->NbcSetAttributes(aAttr, FALSE);\n pObj->SetMergedItemSet(aAttr);\n }\n\n bReturn = TRUE;\n }\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseMove( const MouseEvent& rMEvt )\n{\n return FuConstruct::MouseMove(rMEvt);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::MouseButtonUp( const MouseEvent& rMEvt )\n{\n BOOL bReturn = FALSE;\n BOOL bCreated = FALSE;\n\n if ( pView->IsCreateObj() && rMEvt.IsLeft() )\n {\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n\n ULONG nCount = pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount();\n\n if (pView->EndCreateObj(SDRCREATE_NEXTPOINT) )\n {\n if (nCount != pView->GetPageViewPvNum(0)->GetObjList()->GetObjCount())\n {\n bCreated = TRUE;\n }\n }\n\n bReturn = TRUE;\n }\n\n bReturn = FuConstruct::MouseButtonUp (rMEvt) || bReturn;\n\n if (!bPermanent && bCreated)\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);\n\n return bReturn;\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuConstructArc::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FuConstruct::KeyInput(rKEvt);\n return(bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Activate()\n{\n SdrObjKind aObjKind;\n\n switch( nSlotId )\n {\n case SID_DRAW_ARC :\n case SID_DRAW_CIRCLEARC:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n\n case SID_DRAW_PIE :\n case SID_DRAW_PIE_NOFILL :\n case SID_DRAW_CIRCLEPIE :\n case SID_DRAW_CIRCLEPIE_NOFILL:\n {\n aObjKind = OBJ_SECT;\n }\n break;\n\n case SID_DRAW_ELLIPSECUT :\n case SID_DRAW_ELLIPSECUT_NOFILL:\n case SID_DRAW_CIRCLECUT :\n case SID_DRAW_CIRCLECUT_NOFILL :\n {\n aObjKind = OBJ_CCUT;\n }\n break;\n\n default:\n {\n aObjKind = OBJ_CARC;\n }\n break;\n }\n\n pView->SetCurrentObj(aObjKind);\n\n FuConstruct::Activate();\n\/\/ FuDraw::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuConstructArc::Deactivate()\n{\n FuConstruct::Deactivate();\n\/\/ FuDraw::Deactivate();\n}\n\n\/\/ #97016#\nSdrObject* FuConstructArc::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)\n{\n \/\/ case SID_DRAW_ARC:\n \/\/ case SID_DRAW_CIRCLEARC:\n \/\/ case SID_DRAW_PIE:\n \/\/ case SID_DRAW_PIE_NOFILL:\n \/\/ case SID_DRAW_CIRCLEPIE:\n \/\/ case SID_DRAW_CIRCLEPIE_NOFILL:\n \/\/ case SID_DRAW_ELLIPSECUT:\n \/\/ case SID_DRAW_ELLIPSECUT_NOFILL:\n \/\/ case SID_DRAW_CIRCLECUT:\n \/\/ case SID_DRAW_CIRCLECUT_NOFILL:\n\n SdrObject* pObj = SdrObjFactory::MakeNewObject(\n pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),\n 0L, pDoc);\n\n if(pObj)\n {\n if(pObj->ISA(SdrCircObj))\n {\n Rectangle aRect(rRectangle);\n\n if(SID_DRAW_ARC == nID ||\n SID_DRAW_CIRCLEARC == nID ||\n SID_DRAW_CIRCLEPIE == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_CIRCLECUT == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n \/\/ force quadratic\n ImpForceQuadratic(aRect);\n }\n\n pObj->SetLogicRect(aRect);\n\n SfxItemSet aAttr(pDoc->GetPool());\n aAttr.Put(SdrCircStartAngleItem(9000));\n aAttr.Put(SdrCircEndAngleItem(0));\n\n if(SID_DRAW_PIE_NOFILL == nID ||\n SID_DRAW_CIRCLEPIE_NOFILL == nID ||\n SID_DRAW_ELLIPSECUT_NOFILL == nID ||\n SID_DRAW_CIRCLECUT_NOFILL == nID)\n {\n aAttr.Put(XFillStyleItem(XFILL_NONE));\n }\n\n pObj->SetMergedItemSet(aAttr);\n }\n else\n {\n DBG_ERROR(\"Object is NO circle object\");\n }\n }\n\n return pObj;\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fudspord.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: aw $ $Date: 2002-03-01 09:59:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include <svx\/svxids.hrc>\n#ifndef _VCL_POINTR_HXX \/\/autogen\n#include <vcl\/pointr.hxx>\n#endif\n\n#include \"app.hrc\"\n#include \"fudspord.hxx\"\n#include \"fupoor.hxx\"\n#include \"viewshel.hxx\"\n#include \"sdview.hxx\"\n#include \"sdwindow.hxx\"\n#include \"drawdoc.hxx\"\n\nTYPEINIT1( FuDisplayOrder, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuDisplayOrder::FuDisplayOrder(SdViewShell* pViewSh,\n SdWindow* pWin,\n SdView* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq) :\n FuPoor(pViewSh, pWin, pView, pDoc, rReq),\n pUserMarker(NULL),\n pRefObj(NULL)\n{\n pUserMarker = new SdrViewUserMarker(pView);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuDisplayOrder::~FuDisplayOrder()\n{\n delete pUserMarker;\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt)\n{\n \/\/ #95491# remember button state for creation of own MouseEvents\n SetMouseButtonCode(rMEvt.GetButtons());\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt)\n{\n SdrObject* pPickObj;\n SdrPageView* pPV;\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );\n\n if ( pView->PickObj(aPnt, pPickObj, pPV) )\n {\n if (pRefObj != pPickObj)\n {\n pRefObj = pPickObj;\n pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0));\n pUserMarker->Show();\n }\n }\n else\n {\n pRefObj = NULL;\n pUserMarker->Hide();\n }\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt)\n{\n \/\/ #95491# remember button state for creation of own MouseEvents\n SetMouseButtonCode(rMEvt.GetButtons());\n\n SdrPageView* pPV = NULL;\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );\n\n if ( pView->PickObj(aPnt, pRefObj, pPV) )\n {\n if (nSlotId == SID_BEFORE_OBJ)\n {\n pView->PutMarkedInFrontOfObj(pRefObj);\n }\n else\n {\n pView->PutMarkedBehindObj(pRefObj);\n }\n }\n\n pViewShell->Cancel();\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuDisplayOrder::Activate()\n{\n aPtr = pWindow->GetPointer();\n pWindow->SetPointer( Pointer( POINTER_REFHAND ) );\n\n if (pUserMarker)\n {\n pUserMarker->Show();\n }\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuDisplayOrder::Deactivate()\n{\n if (pUserMarker)\n {\n pUserMarker->Hide();\n }\n\n pWindow->SetPointer( aPtr );\n}\n\n\n<commit_msg>INTEGRATION: CWS impress1 (1.2.224); FILE MERGED 2003\/09\/17 09:02:31 af 1.2.224.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>\/*************************************************************************\n *\n * $RCSfile: fudspord.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 11:01:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"fudspord.hxx\"\n\n#include <svx\/svxids.hrc>\n#ifndef _VCL_POINTR_HXX \/\/autogen\n#include <vcl\/pointr.hxx>\n#endif\n\n#include \"app.hrc\"\n#ifndef SD_FU_POOR_HXX\n#include \"fupoor.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n\nnamespace sd {\n\nTYPEINIT1( FuDisplayOrder, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuDisplayOrder::FuDisplayOrder (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq),\n pUserMarker(NULL),\n pRefObj(NULL)\n{\n pUserMarker = new SdrViewUserMarker(pView);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuDisplayOrder::~FuDisplayOrder()\n{\n delete pUserMarker;\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt)\n{\n \/\/ #95491# remember button state for creation of own MouseEvents\n SetMouseButtonCode(rMEvt.GetButtons());\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt)\n{\n SdrObject* pPickObj;\n SdrPageView* pPV;\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );\n\n if ( pView->PickObj(aPnt, pPickObj, pPV) )\n {\n if (pRefObj != pPickObj)\n {\n pRefObj = pPickObj;\n pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0));\n pUserMarker->Show();\n }\n }\n else\n {\n pRefObj = NULL;\n pUserMarker->Hide();\n }\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt)\n{\n \/\/ #95491# remember button state for creation of own MouseEvents\n SetMouseButtonCode(rMEvt.GetButtons());\n\n SdrPageView* pPV = NULL;\n Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );\n USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );\n\n if ( pView->PickObj(aPnt, pRefObj, pPV) )\n {\n if (nSlotId == SID_BEFORE_OBJ)\n {\n pView->PutMarkedInFrontOfObj(pRefObj);\n }\n else\n {\n pView->PutMarkedBehindObj(pRefObj);\n }\n }\n\n pViewShell->Cancel();\n\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuDisplayOrder::Activate()\n{\n aPtr = pWindow->GetPointer();\n pWindow->SetPointer( Pointer( POINTER_REFHAND ) );\n\n if (pUserMarker)\n {\n pUserMarker->Show();\n }\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuDisplayOrder::Deactivate()\n{\n if (pUserMarker)\n {\n pUserMarker->Hide();\n }\n\n pWindow->SetPointer( aPtr );\n}\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Use cross-app filter directly<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuoltext.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 11:08:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"fuoltext.hxx\"\n\n#ifndef _OUTLINER_HXX\n#include <svx\/outliner.hxx>\n#endif\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#define ITEMID_FIELD EE_FEATURE_FIELD\n#ifndef _SVX_FLDITEM_HXX \/\/autogen\n#include <svx\/flditem.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX\n#include <sfx2\/dispatch.hxx>\n#endif\n\n#include <svx\/svxids.hrc>\n#include \"app.hrc\"\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n\n#include <stdio.h> \/\/ Fuer SlotFilter-Listing\n\nnamespace sd {\n\nstatic USHORT SidArray[] = {\n SID_STYLE_FAMILY2,\n SID_STYLE_FAMILY5,\n SID_STYLE_UPDATE_BY_EXAMPLE,\n SID_CUT,\n SID_COPY,\n SID_PASTE,\n SID_SELECTALL,\n SID_ATTR_CHAR_FONT,\n SID_ATTR_CHAR_POSTURE,\n SID_ATTR_CHAR_WEIGHT,\n SID_ATTR_CHAR_UNDERLINE,\n SID_ATTR_CHAR_FONTHEIGHT,\n SID_ATTR_CHAR_COLOR,\n SID_OUTLINE_UP,\n SID_OUTLINE_DOWN,\n SID_OUTLINE_LEFT,\n SID_OUTLINE_RIGHT,\n \/\/SID_OUTLINE_FORMAT,\n SID_OUTLINE_COLLAPSE_ALL,\n \/\/SID_OUTLINE_BULLET,\n SID_OUTLINE_COLLAPSE,\n SID_OUTLINE_EXPAND_ALL,\n SID_OUTLINE_EXPAND,\n SID_SET_SUPER_SCRIPT,\n SID_SET_SUB_SCRIPT,\n SID_HYPERLINK_GETLINK,\n SID_PRESENTATION_TEMPLATES,\n SID_STATUS_PAGE,\n SID_STATUS_LAYOUT,\n SID_EXPAND_PAGE,\n SID_SUMMARY_PAGE,\n SID_PARASPACE_INCREASE,\n SID_PARASPACE_DECREASE,\n 0 };\n\nTYPEINIT1( FuOutlineText, FuOutline );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuOutlineText::FuOutlineText(ViewShell* pViewShell, ::sd::Window* pWindow,\n ::sd::View* pView, SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuOutline(pViewShell, pWindow, pView, pDoc, rReq)\n{\n\/\/ ERSTELLT SLOTFILTER-LISTING\n\/\/ FILE* pFile = fopen(\"menu.dat\", \"w\");\n\/\/ fprintf(pFile, \"SID_STYLE_FAMILY2, %6d\\n\", SID_STYLE_FAMILY2);\n\/\/ fprintf(pFile, \"SID_STYLE_FAMILY5, %6d\\n\", SID_STYLE_FAMILY5);\n\/\/ fprintf(pFile, \"SID_STYLE_UPDATE_BY_EXAMPLE, %6d\\n\", SID_STYLE_UPDATE_BY_EXAMPLE);\n\/\/ fprintf(pFile, \"SID_CUT, %6d\\n\", SID_CUT);\n\/\/ fprintf(pFile, \"SID_COPY, %6d\\n\", SID_COPY);\n\/\/ fprintf(pFile, \"SID_PASTE, %6d\\n\", SID_PASTE);\n\/\/ fprintf(pFile, \"SID_SELECTALL, %6d\\n\", SID_SELECTALL);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_FONT, %6d\\n\", SID_ATTR_CHAR_FONT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_POSTURE, %6d\\n\", SID_ATTR_CHAR_POSTURE);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_WEIGHT, %6d\\n\", SID_ATTR_CHAR_WEIGHT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_UNDERLINE, %6d\\n\", SID_ATTR_CHAR_UNDERLINE);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_FONTHEIGHT, %6d\\n\", SID_ATTR_CHAR_FONTHEIGHT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_COLOR, %6d\\n\", SID_ATTR_CHAR_COLOR);\n\/\/ fprintf(pFile, \"SID_OUTLINE_UP, %6d\\n\", SID_OUTLINE_UP);\n\/\/ fprintf(pFile, \"SID_OUTLINE_DOWN, %6d\\n\", SID_OUTLINE_DOWN);\n\/\/ fprintf(pFile, \"SID_OUTLINE_LEFT, %6d\\n\", SID_OUTLINE_LEFT);\n\/\/ fprintf(pFile, \"SID_OUTLINE_RIGHT, %6d\\n\", SID_OUTLINE_RIGHT);\n\/\/ fprintf(pFile, \"SID_OUTLINE_COLLAPSE_ALL, %6d\\n\", SID_OUTLINE_COLLAPSE_ALL);\n\/\/ fprintf(pFile, \"SID_OUTLINE_COLLAPSE, %6d\\n\", SID_OUTLINE_COLLAPSE);\n\/\/ fprintf(pFile, \"SID_OUTLINE_EXPAND_ALL, %6d\\n\", SID_OUTLINE_EXPAND_ALL);\n\/\/ fprintf(pFile, \"SID_OUTLINE_EXPAND, %6d\\n\", SID_OUTLINE_EXPAND);\n\/\/ fprintf(pFile, \"SID_SET_SUPER_SCRIPT, %6d\\n\", SID_SET_SUPER_SCRIPT);\n\/\/ fprintf(pFile, \"SID_SET_SUB_SCRIPT, %6d\\n\", SID_SET_SUB_SCRIPT);\n\/\/ fprintf(pFile, \"SID_PRESENTATION_TEMPLATES, %6d\\n\", SID_PRESENTATION_TEMPLATES);\n\/\/ fprintf(pFile, \"SID_STATUS_PAGE, %6d\\n\", SID_STATUS_PAGE);\n\/\/ fprintf(pFile, \"SID_STATUS_LAYOUT, %6d\\n\", SID_STATUS_LAYOUT);\n\/\/ fprintf(pFile, \"SID_HYPERLINK_GETLINK, %6d\\n\", SID_HYPERLINK_GETLINK);\n\/\/ fclose(pFile);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuOutlineText::~FuOutlineText()\n{\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n pWindow->GrabFocus();\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonDown(rMEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n }\n else\n {\n bReturn = FuOutline::MouseButtonDown(rMEvt);\n }\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseMove(rMEvt);\n\n if (!bReturn)\n {\n bReturn = FuOutline::MouseMove(rMEvt);\n }\n\n \/\/ MT 07\/2002: Done in OutlinerView::MouseMove\n \/*\n const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->\n GetFieldUnderMousePointer();\n const SvxFieldData* pField = NULL;\n if( pFieldItem )\n pField = pFieldItem->GetField();\n\n if( pField && pField->ISA( SvxURLField ) )\n {\n pWindow->SetPointer( Pointer( POINTER_REFHAND ) );\n }\n else\n pWindow->SetPointer( Pointer( POINTER_TEXT ) );\n *\/\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonUp(rMEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n }\n else\n {\n const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->GetFieldUnderMousePointer();\n if( pFieldItem )\n {\n const SvxFieldData* pField = pFieldItem->GetField();\n\n if( pField && pField->ISA( SvxURLField ) )\n {\n bReturn = TRUE;\n pWindow->ReleaseMouse();\n SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() );\n SfxStringItem aReferer( SID_REFERER, pDocSh->GetMedium()->GetName() );\n SfxBoolItem aBrowseItem( SID_BROWSE, TRUE );\n SfxViewFrame* pFrame = pViewShell->GetViewFrame();\n\n if ( rMEvt.IsMod1() )\n {\n \/\/ Im neuen Frame oeffnen\n pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aStrItem, &aBrowseItem, &aReferer, 0L);\n }\n else\n {\n \/\/ Im aktuellen Frame oeffnen\n SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame );\n pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L);\n }\n }\n }\n }\n\n if( !bReturn )\n bReturn = FuOutline::MouseButtonUp(rMEvt);\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FALSE;\n\n if( !pDocSh->IsReadOnly() ||\n rKEvt.GetKeyCode().GetGroup() == KEYGROUP_CURSOR )\n {\n pWindow->GrabFocus();\n\n SdPage* pCurrentPage = pOutlineViewShell->GetActualPage();\n bReturn = pOutlineView->GetViewByWindow(pWindow)->PostKeyEvent(rKEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n bool bUpdatePreview = true;\n switch (rKEvt.GetKeyCode().GetCode())\n {\n \/\/ When just the cursor has been moved the preview\n \/\/ only changes when it moved to entries of another\n \/\/ page. To prevent unnecessary updates we check this\n \/\/ here. This is an early rejection test, so missing\n \/\/ a key is not a problem.\n case KEY_UP:\n case KEY_DOWN:\n case KEY_LEFT:\n case KEY_RIGHT:\n case KEY_HOME:\n case KEY_END:\n case KEY_PAGEUP:\n case KEY_PAGEDOWN:\n bUpdatePreview =\n (pCurrentPage != pOutlineViewShell->GetActualPage());\n }\n if (bUpdatePreview)\n pOutlineViewShell->UpdatePreview (\n pOutlineViewShell->GetActualPage());\n }\n else\n {\n bReturn = FuOutline::KeyInput(rKEvt);\n }\n }\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::Activate()\n{\n FuOutline::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::Deactivate()\n{\n FuOutline::Deactivate();\n}\n\n\/*************************************************************************\n|*\n|* Cut object to clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoCut()\n{\n pOutlineView->GetViewByWindow(pWindow)->Cut();\n}\n\n\/*************************************************************************\n|*\n|* Copy object to clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoCopy()\n{\n pOutlineView->GetViewByWindow(pWindow)->Copy();\n}\n\n\/*************************************************************************\n|*\n|* Paste object from clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoPaste()\n{\n pOutlineView->GetViewByWindow(pWindow)->PasteSpecial();\n}\n\n\n\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS mav09 (1.5.82); FILE MERGED 2004\/04\/14 14:12:09 mba 1.5.82.1: #i27773#: remove so3; new storage API<commit_after>\/*************************************************************************\n *\n * $RCSfile: fuoltext.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 18:32:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"fuoltext.hxx\"\n\n#include <sfx2\/viewfrm.hxx>\n\n#ifndef _OUTLINER_HXX\n#include <svx\/outliner.hxx>\n#endif\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#define ITEMID_FIELD EE_FEATURE_FIELD\n#ifndef _SVX_FLDITEM_HXX \/\/autogen\n#include <svx\/flditem.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX\n#include <sfx2\/dispatch.hxx>\n#endif\n\n#include <svx\/svxids.hrc>\n#include \"app.hrc\"\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n\n#include <stdio.h> \/\/ Fuer SlotFilter-Listing\n\nnamespace sd {\n\nstatic USHORT SidArray[] = {\n SID_STYLE_FAMILY2,\n SID_STYLE_FAMILY5,\n SID_STYLE_UPDATE_BY_EXAMPLE,\n SID_CUT,\n SID_COPY,\n SID_PASTE,\n SID_SELECTALL,\n SID_ATTR_CHAR_FONT,\n SID_ATTR_CHAR_POSTURE,\n SID_ATTR_CHAR_WEIGHT,\n SID_ATTR_CHAR_UNDERLINE,\n SID_ATTR_CHAR_FONTHEIGHT,\n SID_ATTR_CHAR_COLOR,\n SID_OUTLINE_UP,\n SID_OUTLINE_DOWN,\n SID_OUTLINE_LEFT,\n SID_OUTLINE_RIGHT,\n \/\/SID_OUTLINE_FORMAT,\n SID_OUTLINE_COLLAPSE_ALL,\n \/\/SID_OUTLINE_BULLET,\n SID_OUTLINE_COLLAPSE,\n SID_OUTLINE_EXPAND_ALL,\n SID_OUTLINE_EXPAND,\n SID_SET_SUPER_SCRIPT,\n SID_SET_SUB_SCRIPT,\n SID_HYPERLINK_GETLINK,\n SID_PRESENTATION_TEMPLATES,\n SID_STATUS_PAGE,\n SID_STATUS_LAYOUT,\n SID_EXPAND_PAGE,\n SID_SUMMARY_PAGE,\n SID_PARASPACE_INCREASE,\n SID_PARASPACE_DECREASE,\n 0 };\n\nTYPEINIT1( FuOutlineText, FuOutline );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuOutlineText::FuOutlineText(ViewShell* pViewShell, ::sd::Window* pWindow,\n ::sd::View* pView, SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuOutline(pViewShell, pWindow, pView, pDoc, rReq)\n{\n\/\/ ERSTELLT SLOTFILTER-LISTING\n\/\/ FILE* pFile = fopen(\"menu.dat\", \"w\");\n\/\/ fprintf(pFile, \"SID_STYLE_FAMILY2, %6d\\n\", SID_STYLE_FAMILY2);\n\/\/ fprintf(pFile, \"SID_STYLE_FAMILY5, %6d\\n\", SID_STYLE_FAMILY5);\n\/\/ fprintf(pFile, \"SID_STYLE_UPDATE_BY_EXAMPLE, %6d\\n\", SID_STYLE_UPDATE_BY_EXAMPLE);\n\/\/ fprintf(pFile, \"SID_CUT, %6d\\n\", SID_CUT);\n\/\/ fprintf(pFile, \"SID_COPY, %6d\\n\", SID_COPY);\n\/\/ fprintf(pFile, \"SID_PASTE, %6d\\n\", SID_PASTE);\n\/\/ fprintf(pFile, \"SID_SELECTALL, %6d\\n\", SID_SELECTALL);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_FONT, %6d\\n\", SID_ATTR_CHAR_FONT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_POSTURE, %6d\\n\", SID_ATTR_CHAR_POSTURE);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_WEIGHT, %6d\\n\", SID_ATTR_CHAR_WEIGHT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_UNDERLINE, %6d\\n\", SID_ATTR_CHAR_UNDERLINE);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_FONTHEIGHT, %6d\\n\", SID_ATTR_CHAR_FONTHEIGHT);\n\/\/ fprintf(pFile, \"SID_ATTR_CHAR_COLOR, %6d\\n\", SID_ATTR_CHAR_COLOR);\n\/\/ fprintf(pFile, \"SID_OUTLINE_UP, %6d\\n\", SID_OUTLINE_UP);\n\/\/ fprintf(pFile, \"SID_OUTLINE_DOWN, %6d\\n\", SID_OUTLINE_DOWN);\n\/\/ fprintf(pFile, \"SID_OUTLINE_LEFT, %6d\\n\", SID_OUTLINE_LEFT);\n\/\/ fprintf(pFile, \"SID_OUTLINE_RIGHT, %6d\\n\", SID_OUTLINE_RIGHT);\n\/\/ fprintf(pFile, \"SID_OUTLINE_COLLAPSE_ALL, %6d\\n\", SID_OUTLINE_COLLAPSE_ALL);\n\/\/ fprintf(pFile, \"SID_OUTLINE_COLLAPSE, %6d\\n\", SID_OUTLINE_COLLAPSE);\n\/\/ fprintf(pFile, \"SID_OUTLINE_EXPAND_ALL, %6d\\n\", SID_OUTLINE_EXPAND_ALL);\n\/\/ fprintf(pFile, \"SID_OUTLINE_EXPAND, %6d\\n\", SID_OUTLINE_EXPAND);\n\/\/ fprintf(pFile, \"SID_SET_SUPER_SCRIPT, %6d\\n\", SID_SET_SUPER_SCRIPT);\n\/\/ fprintf(pFile, \"SID_SET_SUB_SCRIPT, %6d\\n\", SID_SET_SUB_SCRIPT);\n\/\/ fprintf(pFile, \"SID_PRESENTATION_TEMPLATES, %6d\\n\", SID_PRESENTATION_TEMPLATES);\n\/\/ fprintf(pFile, \"SID_STATUS_PAGE, %6d\\n\", SID_STATUS_PAGE);\n\/\/ fprintf(pFile, \"SID_STATUS_LAYOUT, %6d\\n\", SID_STATUS_LAYOUT);\n\/\/ fprintf(pFile, \"SID_HYPERLINK_GETLINK, %6d\\n\", SID_HYPERLINK_GETLINK);\n\/\/ fclose(pFile);\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuOutlineText::~FuOutlineText()\n{\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonDown-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n pWindow->GrabFocus();\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonDown(rMEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n }\n else\n {\n bReturn = FuOutline::MouseButtonDown(rMEvt);\n }\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* MouseMove-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseMove(rMEvt);\n\n if (!bReturn)\n {\n bReturn = FuOutline::MouseMove(rMEvt);\n }\n\n \/\/ MT 07\/2002: Done in OutlinerView::MouseMove\n \/*\n const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->\n GetFieldUnderMousePointer();\n const SvxFieldData* pField = NULL;\n if( pFieldItem )\n pField = pFieldItem->GetField();\n\n if( pField && pField->ISA( SvxURLField ) )\n {\n pWindow->SetPointer( Pointer( POINTER_REFHAND ) );\n }\n else\n pWindow->SetPointer( Pointer( POINTER_TEXT ) );\n *\/\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* MouseButtonUp-event\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt)\n{\n BOOL bReturn = FALSE;\n\n bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonUp(rMEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n }\n else\n {\n const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->GetFieldUnderMousePointer();\n if( pFieldItem )\n {\n const SvxFieldData* pField = pFieldItem->GetField();\n\n if( pField && pField->ISA( SvxURLField ) )\n {\n bReturn = TRUE;\n pWindow->ReleaseMouse();\n SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() );\n SfxStringItem aReferer( SID_REFERER, pDocSh->GetMedium()->GetName() );\n SfxBoolItem aBrowseItem( SID_BROWSE, TRUE );\n SfxViewFrame* pFrame = pViewShell->GetViewFrame();\n\n if ( rMEvt.IsMod1() )\n {\n \/\/ Im neuen Frame oeffnen\n pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aStrItem, &aBrowseItem, &aReferer, 0L);\n }\n else\n {\n \/\/ Im aktuellen Frame oeffnen\n SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame );\n pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L);\n }\n }\n }\n }\n\n if( !bReturn )\n bReturn = FuOutline::MouseButtonUp(rMEvt);\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Tastaturereignisse bearbeiten\n|*\n|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls\n|* FALSE.\n|*\n\\************************************************************************\/\n\nBOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt)\n{\n BOOL bReturn = FALSE;\n\n if( !pDocSh->IsReadOnly() ||\n rKEvt.GetKeyCode().GetGroup() == KEYGROUP_CURSOR )\n {\n pWindow->GrabFocus();\n\n SdPage* pCurrentPage = pOutlineViewShell->GetActualPage();\n bReturn = pOutlineView->GetViewByWindow(pWindow)->PostKeyEvent(rKEvt);\n\n if (bReturn)\n {\n \/\/ Attributierung der akt. Textstelle kann jetzt anders sein\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n bool bUpdatePreview = true;\n switch (rKEvt.GetKeyCode().GetCode())\n {\n \/\/ When just the cursor has been moved the preview\n \/\/ only changes when it moved to entries of another\n \/\/ page. To prevent unnecessary updates we check this\n \/\/ here. This is an early rejection test, so missing\n \/\/ a key is not a problem.\n case KEY_UP:\n case KEY_DOWN:\n case KEY_LEFT:\n case KEY_RIGHT:\n case KEY_HOME:\n case KEY_END:\n case KEY_PAGEUP:\n case KEY_PAGEDOWN:\n bUpdatePreview =\n (pCurrentPage != pOutlineViewShell->GetActualPage());\n }\n if (bUpdatePreview)\n pOutlineViewShell->UpdatePreview (\n pOutlineViewShell->GetActualPage());\n }\n else\n {\n bReturn = FuOutline::KeyInput(rKEvt);\n }\n }\n\n return (bReturn);\n}\n\n\/*************************************************************************\n|*\n|* Function aktivieren\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::Activate()\n{\n FuOutline::Activate();\n}\n\n\/*************************************************************************\n|*\n|* Function deaktivieren\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::Deactivate()\n{\n FuOutline::Deactivate();\n}\n\n\/*************************************************************************\n|*\n|* Cut object to clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoCut()\n{\n pOutlineView->GetViewByWindow(pWindow)->Cut();\n}\n\n\/*************************************************************************\n|*\n|* Copy object to clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoCopy()\n{\n pOutlineView->GetViewByWindow(pWindow)->Copy();\n}\n\n\/*************************************************************************\n|*\n|* Paste object from clipboard\n|*\n\\************************************************************************\/\n\nvoid FuOutlineText::DoPaste()\n{\n pOutlineView->GetViewByWindow(pWindow)->PasteSpecial();\n}\n\n\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuprlout.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: dl $ $Date: 2001-11-14 13:31:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SFXSMPLHINT_HXX \/\/autogen\n#include <svtools\/smplhint.hxx>\n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include <svtools\/itempool.hxx>\n#endif\n#ifndef _SVSTOR_HXX \/\/autogen\n#include <so3\/svstor.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVDUNDO_HXX \/\/autogen\n#include <svx\/svdundo.hxx>\n#endif\n\n#include \"fuprlout.hxx\"\n#include \"drawdoc.hxx\"\n#include \"sdpage.hxx\"\n#include \"pres.hxx\"\n#include \"drviewsh.hxx\"\n#include \"frmview.hxx\"\n#include \"stlpool.hxx\"\n#include \"sdview.hxx\"\n#include \"glob.hrc\"\n#include \"glob.hxx\"\n#include \"strings.hrc\"\n#include \"strmname.h\"\n#include \"app.hrc\"\n#include \"docshell.hxx\"\n#include \"unprlout.hxx\"\n#include \"unchss.hxx\"\n#include \"unmovss.hxx\"\n#include \"sdattr.hxx\"\n#include \"sdresid.hxx\"\n#include \"sdpreslt.hxx\"\n#include \"drawview.hxx\"\n#include \"eetext.hxx\"\n#include <svx\/editdata.hxx>\n\n#ifndef SO2_DECL_SVSTORAGE_DEFINED\n#define SO2_DECL_SVSTORAGE_DEFINED\nSO2_DECL_REF(SvStorage)\n#endif\n\nTYPEINIT1( FuPresentationLayout, FuPoor );\n\n#define POOL_BUFFER_SIZE (USHORT)32768\n#define DOCUMENT_BUFFER_SIZE (USHORT)32768\n#define DOCUMENT_TOKEN (sal_Unicode('#'))\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuPresentationLayout::FuPresentationLayout(SdViewShell* pViewSh,\n SdWindow* pWin, SdView* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n\n{\n \/\/ damit nicht Objekte, die gerade editiert werden oder selektiert\n \/\/ sind , verschwinden\n pView->EndTextEdit();\n\n USHORT nPgViewCount = pView->GetPageViewCount();\n for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)\n {\n pView->UnmarkAll();\n }\n\n BOOL bError = FALSE;\n\n \/\/ die aktive Seite ermitteln\n USHORT nSelectedPage = SDRPAGE_NOTFOUND;\n for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)\n {\n if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())\n {\n nSelectedPage = nPage;\n break;\n }\n }\n\n DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, \"keine selektierte Seite\");\n SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);\n String aOldPageLayoutName(pSelectedPage->GetLayoutName());\n String aOldLayoutName(aOldPageLayoutName);\n aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));\n\n \/\/ wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle\n \/\/ Seiten und Notizseiten, die das betreffende Layout benutzen\n BOOL bOnMaster = FALSE;\n if (pViewSh->ISA(SdDrawViewShell))\n {\n EditMode eEditMode = ((SdDrawViewShell*)pViewSh)->GetEditMode();\n if (eEditMode == EM_MASTERPAGE)\n bOnMaster = TRUE;\n }\n BOOL bMasterPage = bOnMaster;\n BOOL bCheckMasters = FALSE;\n\n \/\/ Dialog aufrufen\n BOOL bLoad = FALSE; \/\/ tauchen neue Masterpages auf?\n String aFile;\n SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);\n\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );\n aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));\n\n SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);\n USHORT nResult = pDlg->Execute();\n\n switch (nResult)\n {\n case RET_OK:\n {\n pDlg->GetAttr(aSet);\n if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)\n bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();\n if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )\n bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();\n if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )\n bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();\n if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)\n aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();\n }\n break;\n\n default:\n bError = TRUE;\n }\n delete pDlg;\n\n if (!bError)\n {\n pDocSh->SetWaitCursor( TRUE );\n\n \/\/ Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite\n \/\/ bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht\n \/\/ dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen\n \/\/ wird, wird jetzt blockiert.\n \/\/ That isn't quitely right. If the masterpageview is active and you are\n \/\/ removing a masterpage, it's possible that you are removing the\n \/\/ current masterpage. So you have to call ResetActualPage !\n if( pViewShell->ISA(SdDrawViewShell) && !bCheckMasters )\n ((SdDrawView*)pView)->BlockPageOrderChangedHint(TRUE);\n\n if (bLoad)\n {\n String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );\n SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );\n\n \/\/ #69581: If I chosed the standard-template I got no filename and so I get no\n \/\/ SdDrawDocument-Pointer. But the method SetMasterPage is able to handle\n \/\/ a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )\n String aLayoutName;\n if( pTempDoc )\n aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );\n\n pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);\n pDoc->CloseBookmarkDoc();\n }\n else\n {\n \/\/ MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden\n pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);\n }\n\n \/\/ Blockade wieder aufheben\n if (pViewShell->ISA(SdDrawViewShell) && !bCheckMasters )\n ((SdDrawView*)pView)->BlockPageOrderChangedHint(FALSE);\n\n \/*************************************************************************\n |* Falls dargestellte Masterpage sichtbar war, neu darstellen\n \\************************************************************************\/\n if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)\n {\n if (bOnMaster)\n {\n if (pViewShell->ISA(SdDrawViewShell))\n {\n SdView* pView = ((SdDrawViewShell*)pViewShell)->GetView();\n USHORT nPgNum = pSelectedPage->GetMasterPage(0)->GetPageNum();\n\n if (((SdDrawViewShell*)pViewShell)->GetPageKind() == PK_NOTES)\n nPgNum++;\n\n pView->HideAllPages();\n pView->ShowMasterPagePgNum(nPgNum, Point());\n }\n\n \/\/ damit TabBar aktualisiert wird\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);\n }\n else\n {\n pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());\n }\n }\n\n \/\/ fake a mode change to repaint the page tab bar\n if( pViewShell && pViewShell->ISA( SdDrawViewShell ) )\n {\n SdDrawViewShell* pDrawViewSh = (SdDrawViewShell*)pViewShell;\n EditMode eMode = pDrawViewSh->GetEditMode();\n BOOL bLayer = pDrawViewSh->GetLayerMode();\n pDrawViewSh->ChangeEditMode( eMode, !bLayer );\n pDrawViewSh->ChangeEditMode( eMode, bLayer );\n }\n\n pDocSh->SetWaitCursor( FALSE );\n }\n}\n\n\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuPresentationLayout::~FuPresentationLayout()\n{\n}\n\n\/*************************************************************************\n|*\n|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen\n|*\n\\************************************************************************\/\n\nvoid FuPresentationLayout::TransferLayoutTemplate(String aFromName,\n String aToName,\n SfxStyleSheetBasePool* pFrom,\n SfxStyleSheetBasePool* pTo)\n{\n SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);\n SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY);\n\n DBG_ASSERT(pHis, \"neue Layoutvorlage nicht gefunden\");\n\n \/\/ gibt's noch nicht: neu anlegen\n if (!pMy)\n {\n pMy = &(pTo->Make(aToName, SD_LT_FAMILY));\n }\n\n \/\/ Inhalte neu setzen\n if (pHis)\n pMy->GetItemSet().Set(pHis->GetItemSet());\n}\n\n\n<commit_msg>INTEGRATION: CWS impress1 (1.4.238); FILE MERGED 2004\/01\/09 16:32:18 af 1.4.238.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003\/09\/17 09:02:35 af 1.4.238.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>\/*************************************************************************\n *\n * $RCSfile: fuprlout.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 11:10:47 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"fuprlout.hxx\"\n\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n#ifndef _SFXSMPLHINT_HXX \/\/autogen\n#include <svtools\/smplhint.hxx>\n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include <svtools\/itempool.hxx>\n#endif\n#ifndef _SVSTOR_HXX \/\/autogen\n#include <so3\/svstor.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVDUNDO_HXX \/\/autogen\n#include <svx\/svdundo.hxx>\n#endif\n\n#include \"drawdoc.hxx\"\n#include \"sdpage.hxx\"\n#include \"pres.hxx\"\n#ifndef SD_DRAW_VIEW_SHELL_HXX\n#include \"DrawViewShell.hxx\"\n#endif\n#ifndef SD_FRAMW_VIEW_HXX\n#include \"FrameView.hxx\"\n#endif\n#include \"stlpool.hxx\"\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#include \"glob.hrc\"\n#include \"glob.hxx\"\n#include \"strings.hrc\"\n#include \"strmname.h\"\n#include \"app.hrc\"\n#include \"DrawDocShell.hxx\"\n#include \"unprlout.hxx\"\n#include \"unchss.hxx\"\n#include \"unmovss.hxx\"\n#include \"sdattr.hxx\"\n#include \"sdresid.hxx\"\n#include \"sdpreslt.hxx\"\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n#include \"eetext.hxx\"\n#include <svx\/editdata.hxx>\n\nnamespace sd {\n\n#ifndef SO2_DECL_SVSTORAGE_DEFINED\n#define SO2_DECL_SVSTORAGE_DEFINED\nSO2_DECL_REF(SvStorage)\n#endif\n\nTYPEINIT1( FuPresentationLayout, FuPoor );\n\n#define POOL_BUFFER_SIZE (USHORT)32768\n#define DOCUMENT_BUFFER_SIZE (USHORT)32768\n#define DOCUMENT_TOKEN (sal_Unicode('#'))\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuPresentationLayout::FuPresentationLayout (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n \/\/ damit nicht Objekte, die gerade editiert werden oder selektiert\n \/\/ sind , verschwinden\n pView->EndTextEdit();\n\n USHORT nPgViewCount = pView->GetPageViewCount();\n for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++)\n {\n pView->UnmarkAll();\n }\n\n BOOL bError = FALSE;\n\n \/\/ die aktive Seite ermitteln\n USHORT nSelectedPage = SDRPAGE_NOTFOUND;\n for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++)\n {\n if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected())\n {\n nSelectedPage = nPage;\n break;\n }\n }\n\n DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, \"keine selektierte Seite\");\n SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD);\n String aOldPageLayoutName(pSelectedPage->GetLayoutName());\n String aOldLayoutName(aOldPageLayoutName);\n aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR));\n\n \/\/ wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle\n \/\/ Seiten und Notizseiten, die das betreffende Layout benutzen\n BOOL bOnMaster = FALSE;\n if (pViewSh->ISA(DrawViewShell))\n {\n EditMode eEditMode =\n static_cast<DrawViewShell*>(pViewSh)->GetEditMode();\n if (eEditMode == EM_MASTERPAGE)\n bOnMaster = TRUE;\n }\n BOOL bMasterPage = bOnMaster;\n BOOL bCheckMasters = FALSE;\n\n \/\/ Dialog aufrufen\n BOOL bLoad = FALSE; \/\/ tauchen neue Masterpages auf?\n String aFile;\n SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END);\n\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad));\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) );\n aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) );\n aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName));\n\n SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet);\n USHORT nResult = pDlg->Execute();\n\n switch (nResult)\n {\n case RET_OK:\n {\n pDlg->GetAttr(aSet);\n if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET)\n bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue();\n if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET )\n bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue();\n if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET )\n bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue();\n if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET)\n aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue();\n }\n break;\n\n default:\n bError = TRUE;\n }\n delete pDlg;\n\n if (!bError)\n {\n pDocSh->SetWaitCursor( TRUE );\n\n \/\/ Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite\n \/\/ bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht\n \/\/ dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen\n \/\/ wird, wird jetzt blockiert.\n \/\/ That isn't quitely right. If the masterpageview is active and you are\n \/\/ removing a masterpage, it's possible that you are removing the\n \/\/ current masterpage. So you have to call ResetActualPage !\n if( pViewShell->ISA(DrawViewShell) && !bCheckMasters )\n static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE);\n\n if (bLoad)\n {\n String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN );\n SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName );\n\n \/\/ #69581: If I chosed the standard-template I got no filename and so I get no\n \/\/ SdDrawDocument-Pointer. But the method SetMasterPage is able to handle\n \/\/ a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage )\n String aLayoutName;\n if( pTempDoc )\n aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN );\n\n pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters);\n pDoc->CloseBookmarkDoc();\n }\n else\n {\n \/\/ MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden\n pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters);\n }\n\n \/\/ Blockade wieder aufheben\n if (pViewShell->ISA(DrawViewShell) && !bCheckMasters )\n static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE);\n\n \/*************************************************************************\n |* Falls dargestellte Masterpage sichtbar war, neu darstellen\n \\************************************************************************\/\n if (!bError && nSelectedPage != SDRPAGE_NOTFOUND)\n {\n if (bOnMaster)\n {\n if (pViewShell->ISA(DrawViewShell))\n {\n ::sd::View* pView =\n static_cast<DrawViewShell*>(pViewShell)->GetView();\n USHORT nPgNum = pSelectedPage->GetMasterPage(0)->GetPageNum();\n\n if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES)\n nPgNum++;\n\n pView->HideAllPages();\n pView->ShowMasterPagePgNum(nPgNum, Point());\n }\n\n \/\/ damit TabBar aktualisiert wird\n pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);\n }\n else\n {\n pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout());\n }\n }\n\n \/\/ fake a mode change to repaint the page tab bar\n if( pViewShell && pViewShell->ISA( DrawViewShell ) )\n {\n DrawViewShell* pDrawViewSh =\n static_cast<DrawViewShell*>(pViewShell);\n EditMode eMode = pDrawViewSh->GetEditMode();\n BOOL bLayer = pDrawViewSh->GetLayerMode();\n pDrawViewSh->ChangeEditMode( eMode, !bLayer );\n pDrawViewSh->ChangeEditMode( eMode, bLayer );\n }\n\n pDocSh->SetWaitCursor( FALSE );\n }\n}\n\n\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuPresentationLayout::~FuPresentationLayout()\n{\n}\n\n\/*************************************************************************\n|*\n|* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen\n|*\n\\************************************************************************\/\n\nvoid FuPresentationLayout::TransferLayoutTemplate(String aFromName,\n String aToName,\n SfxStyleSheetBasePool* pFrom,\n SfxStyleSheetBasePool* pTo)\n{\n SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY);\n SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY);\n\n DBG_ASSERT(pHis, \"neue Layoutvorlage nicht gefunden\");\n\n \/\/ gibt's noch nicht: neu anlegen\n if (!pMy)\n {\n pMy = &(pTo->Make(aToName, SD_LT_FAMILY));\n }\n\n \/\/ Inhalte neu setzen\n if (pHis)\n pMy->GetItemSet().Set(pHis->GetItemSet());\n}\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: drviewsh.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2004-12-23 11:02:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"DrawViewShell.hxx\"\n\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#pragma hdrstop\n\n#ifndef _SVX_FMSHELL_HXX \/\/ XXX nur temp (dg)\n#include <svx\/fmshell.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n\n#include \"app.hrc\"\n#include \"strings.hrc\"\n#include \"sdpage.hxx\"\n#ifndef SD_FRAME_VIEW\n#include \"FrameView.hxx\"\n#endif\n#include \"sdresid.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#ifndef SD_GRAPHIC_VIEW_SHELL_HXX\n#include \"GraphicViewShell.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n\nnamespace sd {\n\n#define TABCONTROL_INITIAL_SIZE 500\n\n\/*************************************************************************\n|*\n|* Sprung zu Bookmark\n|*\n\\************************************************************************\/\n\nBOOL DrawViewShell::GotoBookmark(const String& rBookmark)\n{\n BOOL bRet = FALSE;\n ::sd::DrawDocShell* pDocSh = GetDocSh();\n if( pDocSh )\n {\n if( !pDocSh->GetViewShell() ) \/\/#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink\n pDocSh->Connect(this);\n bRet = (pDocSh->GotoBookmark(rBookmark));\n }\n return bRet;\n}\n\n\/*************************************************************************\n|*\n|* Bereich sichtbar machen (Bildausschnitt scrollen)\n|*\n\\************************************************************************\/\n\nvoid DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin)\n{\n \/\/ #98568# In older versions, if in X or Y the size of the object was\n \/\/ smaller than the visible area, the user-defined zoom was\n \/\/ changed. This was decided to be a bug for 6.x, thus I developed a\n \/\/ version which instead handles X\/Y bigger\/smaller and visibility\n \/\/ questions seperately. The new behaviour is triggered with the\n \/\/ bZoomAllowed parameter which for old behaviour should be set to\n \/\/ sal_True. I looked at all uses of MakeVisible() in the application\n \/\/ and found no valid reason for really changing the zoom factor, thus I\n \/\/ decided to NOT expand (incompatible) this virtual method to get one\n \/\/ more parameter. If this is wanted in later versions, feel free to add\n \/\/ that bool to the parameter list.\n sal_Bool bZoomAllowed(sal_False);\n Size aLogicSize(rRect.GetSize());\n\n \/\/ Sichtbarer Bereich\n Size aVisSizePixel(rWin.GetOutputSizePixel());\n Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));\n Size aVisAreaSize(aVisArea.GetSize());\n\n if(!aVisArea.IsInside(rRect) && !mpSlideShow)\n {\n \/\/ Objekt liegt nicht komplett im sichtbaren Bereich\n sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());\n sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());\n\n if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))\n {\n \/\/ Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen\n SetZoomRect(rRect);\n }\n else\n {\n \/\/ #98568# allow a mode for move-only visibility without zooming.\n const sal_Int32 nPercentBorder(30);\n const Rectangle aInnerRectangle(\n aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) \/ 200),\n aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) \/ 200),\n aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) \/ 200),\n aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) \/ 200)\n );\n Point aNewPos(aVisArea.TopLeft());\n\n if(nFreeSpaceX < 0)\n {\n if(aInnerRectangle.Left() > rRect.Right())\n {\n \/\/ object moves out to the left\n aNewPos.X() -= aVisAreaSize.Width() \/ 2;\n }\n\n if(aInnerRectangle.Right() < rRect.Left())\n {\n \/\/ object moves out to the right\n aNewPos.X() += aVisAreaSize.Width() \/ 2;\n }\n }\n else\n {\n if(nFreeSpaceX > rRect.GetWidth())\n nFreeSpaceX = rRect.GetWidth();\n\n while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())\n aNewPos.X() += nFreeSpaceX;\n\n while(rRect.Left() < aNewPos.X())\n aNewPos.X() -= nFreeSpaceX;\n }\n\n if(nFreeSpaceY < 0)\n {\n if(aInnerRectangle.Top() > rRect.Bottom())\n {\n \/\/ object moves out to the top\n aNewPos.Y() -= aVisAreaSize.Height() \/ 2;\n }\n\n if(aInnerRectangle.Bottom() < rRect.Top())\n {\n \/\/ object moves out to the right\n aNewPos.Y() += aVisAreaSize.Height() \/ 2;\n }\n }\n else\n {\n if(nFreeSpaceY > rRect.GetHeight())\n nFreeSpaceY = rRect.GetHeight();\n\n while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())\n aNewPos.Y() += nFreeSpaceY;\n\n while(rRect.Top() < aNewPos.Y())\n aNewPos.Y() -= nFreeSpaceY;\n }\n\n \/\/ did position change? Does it need to be set?\n if(aNewPos != aVisArea.TopLeft())\n {\n aVisArea.SetPos(aNewPos);\n SetZoomRect(aVisArea);\n }\n }\n }\n}\n\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.8.268); FILE MERGED 2005\/09\/05 13:25:50 rt 1.8.268.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: drviewsh.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 07:13:01 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"DrawViewShell.hxx\"\n\n#ifndef _AEITEM_HXX \/\/autogen\n#include <svtools\/aeitem.hxx>\n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#pragma hdrstop\n\n#ifndef _SVX_FMSHELL_HXX \/\/ XXX nur temp (dg)\n#include <svx\/fmshell.hxx>\n#endif\n#ifndef _SFXDISPATCH_HXX \/\/autogen\n#include <sfx2\/dispatch.hxx>\n#endif\n\n#include \"app.hrc\"\n#include \"strings.hrc\"\n#include \"sdpage.hxx\"\n#ifndef SD_FRAME_VIEW\n#include \"FrameView.hxx\"\n#endif\n#include \"sdresid.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#ifndef SD_GRAPHIC_VIEW_SHELL_HXX\n#include \"GraphicViewShell.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n\nnamespace sd {\n\n#define TABCONTROL_INITIAL_SIZE 500\n\n\/*************************************************************************\n|*\n|* Sprung zu Bookmark\n|*\n\\************************************************************************\/\n\nBOOL DrawViewShell::GotoBookmark(const String& rBookmark)\n{\n BOOL bRet = FALSE;\n ::sd::DrawDocShell* pDocSh = GetDocSh();\n if( pDocSh )\n {\n if( !pDocSh->GetViewShell() ) \/\/#i26016# this case occurs if the jump-target-document was opened already with file open dialog before triggering the jump via hyperlink\n pDocSh->Connect(this);\n bRet = (pDocSh->GotoBookmark(rBookmark));\n }\n return bRet;\n}\n\n\/*************************************************************************\n|*\n|* Bereich sichtbar machen (Bildausschnitt scrollen)\n|*\n\\************************************************************************\/\n\nvoid DrawViewShell::MakeVisible(const Rectangle& rRect, ::Window& rWin)\n{\n \/\/ #98568# In older versions, if in X or Y the size of the object was\n \/\/ smaller than the visible area, the user-defined zoom was\n \/\/ changed. This was decided to be a bug for 6.x, thus I developed a\n \/\/ version which instead handles X\/Y bigger\/smaller and visibility\n \/\/ questions seperately. The new behaviour is triggered with the\n \/\/ bZoomAllowed parameter which for old behaviour should be set to\n \/\/ sal_True. I looked at all uses of MakeVisible() in the application\n \/\/ and found no valid reason for really changing the zoom factor, thus I\n \/\/ decided to NOT expand (incompatible) this virtual method to get one\n \/\/ more parameter. If this is wanted in later versions, feel free to add\n \/\/ that bool to the parameter list.\n sal_Bool bZoomAllowed(sal_False);\n Size aLogicSize(rRect.GetSize());\n\n \/\/ Sichtbarer Bereich\n Size aVisSizePixel(rWin.GetOutputSizePixel());\n Rectangle aVisArea(rWin.PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));\n Size aVisAreaSize(aVisArea.GetSize());\n\n if(!aVisArea.IsInside(rRect) && !mpSlideShow)\n {\n \/\/ Objekt liegt nicht komplett im sichtbaren Bereich\n sal_Int32 nFreeSpaceX(aVisAreaSize.Width() - aLogicSize.Width());\n sal_Int32 nFreeSpaceY(aVisAreaSize.Height() - aLogicSize.Height());\n\n if(bZoomAllowed && (nFreeSpaceX < 0 || nFreeSpaceY < 0))\n {\n \/\/ Objekt passt nicht in sichtbaren Bereich -> auf Objektgroesse zoomen\n SetZoomRect(rRect);\n }\n else\n {\n \/\/ #98568# allow a mode for move-only visibility without zooming.\n const sal_Int32 nPercentBorder(30);\n const Rectangle aInnerRectangle(\n aVisArea.Left() + ((aVisAreaSize.Width() * nPercentBorder) \/ 200),\n aVisArea.Top() + ((aVisAreaSize.Height() * nPercentBorder) \/ 200),\n aVisArea.Right() - ((aVisAreaSize.Width() * nPercentBorder) \/ 200),\n aVisArea.Bottom() - ((aVisAreaSize.Height() * nPercentBorder) \/ 200)\n );\n Point aNewPos(aVisArea.TopLeft());\n\n if(nFreeSpaceX < 0)\n {\n if(aInnerRectangle.Left() > rRect.Right())\n {\n \/\/ object moves out to the left\n aNewPos.X() -= aVisAreaSize.Width() \/ 2;\n }\n\n if(aInnerRectangle.Right() < rRect.Left())\n {\n \/\/ object moves out to the right\n aNewPos.X() += aVisAreaSize.Width() \/ 2;\n }\n }\n else\n {\n if(nFreeSpaceX > rRect.GetWidth())\n nFreeSpaceX = rRect.GetWidth();\n\n while(rRect.Right() > aNewPos.X() + aVisAreaSize.Width())\n aNewPos.X() += nFreeSpaceX;\n\n while(rRect.Left() < aNewPos.X())\n aNewPos.X() -= nFreeSpaceX;\n }\n\n if(nFreeSpaceY < 0)\n {\n if(aInnerRectangle.Top() > rRect.Bottom())\n {\n \/\/ object moves out to the top\n aNewPos.Y() -= aVisAreaSize.Height() \/ 2;\n }\n\n if(aInnerRectangle.Bottom() < rRect.Top())\n {\n \/\/ object moves out to the right\n aNewPos.Y() += aVisAreaSize.Height() \/ 2;\n }\n }\n else\n {\n if(nFreeSpaceY > rRect.GetHeight())\n nFreeSpaceY = rRect.GetHeight();\n\n while(rRect.Bottom() > aNewPos.Y() + aVisAreaSize.Height())\n aNewPos.Y() += nFreeSpaceY;\n\n while(rRect.Top() < aNewPos.Y())\n aNewPos.Y() -= nFreeSpaceY;\n }\n\n \/\/ did position change? Does it need to be set?\n if(aNewPos != aVisArea.TopLeft())\n {\n aVisArea.SetPos(aNewPos);\n SetZoomRect(aVisArea);\n }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* skeleton_modification_2d.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"skeleton_modification_2d.h\"\n#include \"scene\/2d\/skeleton_2d.h\"\n\n#include \"scene\/2d\/collision_object_2d.h\"\n#include \"scene\/2d\/collision_shape_2d.h\"\n#include \"scene\/2d\/physical_bone_2d.h\"\n\n#ifdef TOOLS_ENABLED\n#include \"editor\/editor_settings.h\"\n#endif \/\/ TOOLS_ENABLED\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Modification2D\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkeletonModification2D::_execute(float p_delta) {\n\tcall(\"_execute\", p_delta);\n\n\tif (!enabled) {\n\t\treturn;\n\t}\n}\n\nvoid SkeletonModification2D::_setup_modification(SkeletonModificationStack2D *p_stack) {\n\tstack = p_stack;\n\tif (stack) {\n\t\tis_setup = true;\n\t} else {\n\t\tWARN_PRINT(\"Could not setup modification with name \" + get_name());\n\t}\n\n\tcall(\"_setup_modification\", p_stack);\n}\n\nvoid SkeletonModification2D::_draw_editor_gizmo() {\n\tcall(\"_draw_editor_gizmo\");\n}\n\nvoid SkeletonModification2D::set_enabled(bool p_enabled) {\n\tenabled = p_enabled;\n\n#ifdef TOOLS_ENABLED\n\tif (editor_draw_gizmo) {\n\t\tif (stack) {\n\t\t\tstack->set_editor_gizmos_dirty(true);\n\t\t}\n\t}\n#endif \/\/ TOOLS_ENABLED\n}\n\nbool SkeletonModification2D::get_enabled() {\n\treturn enabled;\n}\n\nfloat SkeletonModification2D::clamp_angle(float p_angle, float p_min_bound, float p_max_bound, bool p_invert) {\n\t\/\/ Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range.\n\tif (p_angle < 0) {\n\t\tp_angle = Math_TAU + p_angle;\n\t}\n\n\t\/\/ Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order\n\tif (p_min_bound < 0) {\n\t\tp_min_bound = Math_TAU + p_min_bound;\n\t}\n\tif (p_max_bound < 0) {\n\t\tp_max_bound = Math_TAU + p_max_bound;\n\t}\n\tif (p_min_bound > p_max_bound) {\n\t\tfloat tmp = p_min_bound;\n\t\tp_min_bound = p_max_bound;\n\t\tp_max_bound = tmp;\n\t}\n\n\t\/\/ Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle.\n\tif (p_invert == false) {\n\t\tif (p_angle < p_min_bound || p_angle > p_max_bound) {\n\t\t\tVector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));\n\t\t\tVector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));\n\t\t\tVector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));\n\n\t\t\tif (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {\n\t\t\t\tp_angle = p_min_bound;\n\t\t\t} else {\n\t\t\t\tp_angle = p_max_bound;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (p_angle > p_min_bound && p_angle < p_max_bound) {\n\t\t\tVector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));\n\t\t\tVector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));\n\t\t\tVector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));\n\n\t\t\tif (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {\n\t\t\t\tp_angle = p_min_bound;\n\t\t\t} else {\n\t\t\t\tp_angle = p_max_bound;\n\t\t\t}\n\t\t}\n\t}\n\treturn p_angle;\n}\n\nvoid SkeletonModification2D::editor_draw_angle_constraints(Bone2D *p_operation_bone, float p_min_bound, float p_max_bound,\n\t\tbool p_constraint_enabled, bool p_constraint_in_localspace, bool p_constraint_inverted) {\n\tif (!p_operation_bone) {\n\t\treturn;\n\t}\n\n\tColor bone_ik_color = Color(1.0, 0.65, 0.0, 0.4);\n#ifdef TOOLS_ENABLED\n\tif (Engine::get_singleton()->is_editor_hint()) {\n\t\tbone_ik_color = EditorSettings::get_singleton()->get(\"editors\/2d\/bone_ik_color\");\n\t}\n#endif \/\/ TOOLS_ENABLED\n\n\tfloat arc_angle_min = p_min_bound;\n\tfloat arc_angle_max = p_max_bound;\n\tif (arc_angle_min < 0) {\n\t\tarc_angle_min = (Math_PI * 2) + arc_angle_min;\n\t}\n\tif (arc_angle_max < 0) {\n\t\tarc_angle_max = (Math_PI * 2) + arc_angle_max;\n\t}\n\tif (arc_angle_min > arc_angle_max) {\n\t\tfloat tmp = arc_angle_min;\n\t\tarc_angle_min = arc_angle_max;\n\t\tarc_angle_max = tmp;\n\t}\n\tarc_angle_min += p_operation_bone->get_bone_angle();\n\tarc_angle_max += p_operation_bone->get_bone_angle();\n\n\tif (p_constraint_enabled) {\n\t\tif (p_constraint_in_localspace) {\n\t\t\tNode *operation_bone_parent = p_operation_bone->get_parent();\n\t\t\tBone2D *operation_bone_parent_bone = Object::cast_to<Bone2D>(operation_bone_parent);\n\n\t\t\tif (operation_bone_parent_bone) {\n\t\t\t\tstack->skeleton->draw_set_transform(\n\t\t\t\t\t\tstack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()),\n\t\t\t\t\t\toperation_bone_parent_bone->get_global_rotation() - stack->skeleton->get_global_rotation());\n\t\t\t} else {\n\t\t\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\t\t}\n\t\t} else {\n\t\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\t}\n\n\t\tif (p_constraint_inverted) {\n\t\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),\n\t\t\t\t\tarc_angle_min + (Math_PI * 2), arc_angle_max, 32, bone_ik_color, 1.0);\n\t\t} else {\n\t\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),\n\t\t\t\t\tarc_angle_min, arc_angle_max, 32, bone_ik_color, 1.0);\n\t\t}\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_min), Math::sin(arc_angle_min)) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_max), Math::sin(arc_angle_max)) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\n\t} else {\n\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(), 0, Math_PI * 2, 32, bone_ik_color, 1.0);\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(1, 0) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\t}\n}\n\nRef<SkeletonModificationStack2D> SkeletonModification2D::get_modification_stack() {\n\treturn stack;\n}\n\nvoid SkeletonModification2D::set_is_setup(bool p_setup) {\n\tis_setup = p_setup;\n}\n\nbool SkeletonModification2D::get_is_setup() const {\n\treturn is_setup;\n}\n\nvoid SkeletonModification2D::set_execution_mode(int p_mode) {\n\texecution_mode = p_mode;\n}\n\nint SkeletonModification2D::get_execution_mode() const {\n\treturn execution_mode;\n}\n\nvoid SkeletonModification2D::set_editor_draw_gizmo(bool p_draw_gizmo) {\n\teditor_draw_gizmo = p_draw_gizmo;\n#ifdef TOOLS_ENABLED\n\tif (is_setup) {\n\t\tstack->set_editor_gizmos_dirty(true);\n\t}\n#endif \/\/ TOOLS_ENABLED\n}\n\nbool SkeletonModification2D::get_editor_draw_gizmo() const {\n\treturn editor_draw_gizmo;\n}\n\nvoid SkeletonModification2D::_bind_methods() {\n\tBIND_VMETHOD(MethodInfo(\"_execute\", PropertyInfo(Variant::FLOAT, \"delta\")));\n\tBIND_VMETHOD(MethodInfo(\"_setup_modification\", PropertyInfo(Variant::OBJECT, \"modification_stack\", PROPERTY_HINT_RESOURCE_TYPE, \"SkeletonModificationStack2D\")));\n\tBIND_VMETHOD(MethodInfo(\"_draw_editor_gizmo\"));\n\n\tClassDB::bind_method(D_METHOD(\"set_enabled\", \"enabled\"), &SkeletonModification2D::set_enabled);\n\tClassDB::bind_method(D_METHOD(\"get_enabled\"), &SkeletonModification2D::get_enabled);\n\tClassDB::bind_method(D_METHOD(\"get_modification_stack\"), &SkeletonModification2D::get_modification_stack);\n\tClassDB::bind_method(D_METHOD(\"set_is_setup\", \"is_setup\"), &SkeletonModification2D::set_is_setup);\n\tClassDB::bind_method(D_METHOD(\"get_is_setup\"), &SkeletonModification2D::get_is_setup);\n\tClassDB::bind_method(D_METHOD(\"set_execution_mode\", \"execution_mode\"), &SkeletonModification2D::set_execution_mode);\n\tClassDB::bind_method(D_METHOD(\"get_execution_mode\"), &SkeletonModification2D::get_execution_mode);\n\tClassDB::bind_method(D_METHOD(\"clamp_angle\", \"angle\", \"min\", \"max\", \"invert\"), &SkeletonModification2D::clamp_angle);\n\tClassDB::bind_method(D_METHOD(\"set_editor_draw_gizmo\", \"draw_gizmo\"), &SkeletonModification2D::set_editor_draw_gizmo);\n\tClassDB::bind_method(D_METHOD(\"get_editor_draw_gizmo\"), &SkeletonModification2D::get_editor_draw_gizmo);\n\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"enabled\"), \"set_enabled\", \"get_enabled\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"execution_mode\", PROPERTY_HINT_ENUM, \"process, physics_process\"), \"set_execution_mode\", \"get_execution_mode\");\n}\n\nSkeletonModification2D::SkeletonModification2D() {\n\tstack = nullptr;\n\tis_setup = false;\n}\n<commit_msg>Fixed crash on calling set_editor_draw without properly setup SkeletonModification<commit_after>\/*************************************************************************\/\n\/* skeleton_modification_2d.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"skeleton_modification_2d.h\"\n#include \"scene\/2d\/skeleton_2d.h\"\n\n#include \"scene\/2d\/collision_object_2d.h\"\n#include \"scene\/2d\/collision_shape_2d.h\"\n#include \"scene\/2d\/physical_bone_2d.h\"\n\n#ifdef TOOLS_ENABLED\n#include \"editor\/editor_settings.h\"\n#endif \/\/ TOOLS_ENABLED\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Modification2D\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkeletonModification2D::_execute(float p_delta) {\n\tcall(\"_execute\", p_delta);\n\n\tif (!enabled) {\n\t\treturn;\n\t}\n}\n\nvoid SkeletonModification2D::_setup_modification(SkeletonModificationStack2D *p_stack) {\n\tstack = p_stack;\n\tif (stack) {\n\t\tis_setup = true;\n\t} else {\n\t\tWARN_PRINT(\"Could not setup modification with name \" + get_name());\n\t}\n\n\tcall(\"_setup_modification\", p_stack);\n}\n\nvoid SkeletonModification2D::_draw_editor_gizmo() {\n\tcall(\"_draw_editor_gizmo\");\n}\n\nvoid SkeletonModification2D::set_enabled(bool p_enabled) {\n\tenabled = p_enabled;\n\n#ifdef TOOLS_ENABLED\n\tif (editor_draw_gizmo) {\n\t\tif (stack) {\n\t\t\tstack->set_editor_gizmos_dirty(true);\n\t\t}\n\t}\n#endif \/\/ TOOLS_ENABLED\n}\n\nbool SkeletonModification2D::get_enabled() {\n\treturn enabled;\n}\n\nfloat SkeletonModification2D::clamp_angle(float p_angle, float p_min_bound, float p_max_bound, bool p_invert) {\n\t\/\/ Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range.\n\tif (p_angle < 0) {\n\t\tp_angle = Math_TAU + p_angle;\n\t}\n\n\t\/\/ Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order\n\tif (p_min_bound < 0) {\n\t\tp_min_bound = Math_TAU + p_min_bound;\n\t}\n\tif (p_max_bound < 0) {\n\t\tp_max_bound = Math_TAU + p_max_bound;\n\t}\n\tif (p_min_bound > p_max_bound) {\n\t\tfloat tmp = p_min_bound;\n\t\tp_min_bound = p_max_bound;\n\t\tp_max_bound = tmp;\n\t}\n\n\t\/\/ Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle.\n\tif (p_invert == false) {\n\t\tif (p_angle < p_min_bound || p_angle > p_max_bound) {\n\t\t\tVector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));\n\t\t\tVector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));\n\t\t\tVector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));\n\n\t\t\tif (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {\n\t\t\t\tp_angle = p_min_bound;\n\t\t\t} else {\n\t\t\t\tp_angle = p_max_bound;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (p_angle > p_min_bound && p_angle < p_max_bound) {\n\t\t\tVector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));\n\t\t\tVector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));\n\t\t\tVector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));\n\n\t\t\tif (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {\n\t\t\t\tp_angle = p_min_bound;\n\t\t\t} else {\n\t\t\t\tp_angle = p_max_bound;\n\t\t\t}\n\t\t}\n\t}\n\treturn p_angle;\n}\n\nvoid SkeletonModification2D::editor_draw_angle_constraints(Bone2D *p_operation_bone, float p_min_bound, float p_max_bound,\n\t\tbool p_constraint_enabled, bool p_constraint_in_localspace, bool p_constraint_inverted) {\n\tif (!p_operation_bone) {\n\t\treturn;\n\t}\n\n\tColor bone_ik_color = Color(1.0, 0.65, 0.0, 0.4);\n#ifdef TOOLS_ENABLED\n\tif (Engine::get_singleton()->is_editor_hint()) {\n\t\tbone_ik_color = EditorSettings::get_singleton()->get(\"editors\/2d\/bone_ik_color\");\n\t}\n#endif \/\/ TOOLS_ENABLED\n\n\tfloat arc_angle_min = p_min_bound;\n\tfloat arc_angle_max = p_max_bound;\n\tif (arc_angle_min < 0) {\n\t\tarc_angle_min = (Math_PI * 2) + arc_angle_min;\n\t}\n\tif (arc_angle_max < 0) {\n\t\tarc_angle_max = (Math_PI * 2) + arc_angle_max;\n\t}\n\tif (arc_angle_min > arc_angle_max) {\n\t\tfloat tmp = arc_angle_min;\n\t\tarc_angle_min = arc_angle_max;\n\t\tarc_angle_max = tmp;\n\t}\n\tarc_angle_min += p_operation_bone->get_bone_angle();\n\tarc_angle_max += p_operation_bone->get_bone_angle();\n\n\tif (p_constraint_enabled) {\n\t\tif (p_constraint_in_localspace) {\n\t\t\tNode *operation_bone_parent = p_operation_bone->get_parent();\n\t\t\tBone2D *operation_bone_parent_bone = Object::cast_to<Bone2D>(operation_bone_parent);\n\n\t\t\tif (operation_bone_parent_bone) {\n\t\t\t\tstack->skeleton->draw_set_transform(\n\t\t\t\t\t\tstack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()),\n\t\t\t\t\t\toperation_bone_parent_bone->get_global_rotation() - stack->skeleton->get_global_rotation());\n\t\t\t} else {\n\t\t\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\t\t}\n\t\t} else {\n\t\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\t}\n\n\t\tif (p_constraint_inverted) {\n\t\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),\n\t\t\t\t\tarc_angle_min + (Math_PI * 2), arc_angle_max, 32, bone_ik_color, 1.0);\n\t\t} else {\n\t\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(),\n\t\t\t\t\tarc_angle_min, arc_angle_max, 32, bone_ik_color, 1.0);\n\t\t}\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_min), Math::sin(arc_angle_min)) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(Math::cos(arc_angle_max), Math::sin(arc_angle_max)) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\n\t} else {\n\t\tstack->skeleton->draw_set_transform(stack->skeleton->get_global_transform().affine_inverse().xform(p_operation_bone->get_global_position()));\n\t\tstack->skeleton->draw_arc(Vector2(0, 0), p_operation_bone->get_length(), 0, Math_PI * 2, 32, bone_ik_color, 1.0);\n\t\tstack->skeleton->draw_line(Vector2(0, 0), Vector2(1, 0) * p_operation_bone->get_length(), bone_ik_color, 1.0);\n\t}\n}\n\nRef<SkeletonModificationStack2D> SkeletonModification2D::get_modification_stack() {\n\treturn stack;\n}\n\nvoid SkeletonModification2D::set_is_setup(bool p_setup) {\n\tis_setup = p_setup;\n}\n\nbool SkeletonModification2D::get_is_setup() const {\n\treturn is_setup;\n}\n\nvoid SkeletonModification2D::set_execution_mode(int p_mode) {\n\texecution_mode = p_mode;\n}\n\nint SkeletonModification2D::get_execution_mode() const {\n\treturn execution_mode;\n}\n\nvoid SkeletonModification2D::set_editor_draw_gizmo(bool p_draw_gizmo) {\n\teditor_draw_gizmo = p_draw_gizmo;\n#ifdef TOOLS_ENABLED\n\tif (is_setup) {\n\t\tif (stack) {\n\t\t\tstack->set_editor_gizmos_dirty(true);\n\t\t}\n\t}\n#endif \/\/ TOOLS_ENABLED\n}\n\nbool SkeletonModification2D::get_editor_draw_gizmo() const {\n\treturn editor_draw_gizmo;\n}\n\nvoid SkeletonModification2D::_bind_methods() {\n\tBIND_VMETHOD(MethodInfo(\"_execute\", PropertyInfo(Variant::FLOAT, \"delta\")));\n\tBIND_VMETHOD(MethodInfo(\"_setup_modification\", PropertyInfo(Variant::OBJECT, \"modification_stack\", PROPERTY_HINT_RESOURCE_TYPE, \"SkeletonModificationStack2D\")));\n\tBIND_VMETHOD(MethodInfo(\"_draw_editor_gizmo\"));\n\n\tClassDB::bind_method(D_METHOD(\"set_enabled\", \"enabled\"), &SkeletonModification2D::set_enabled);\n\tClassDB::bind_method(D_METHOD(\"get_enabled\"), &SkeletonModification2D::get_enabled);\n\tClassDB::bind_method(D_METHOD(\"get_modification_stack\"), &SkeletonModification2D::get_modification_stack);\n\tClassDB::bind_method(D_METHOD(\"set_is_setup\", \"is_setup\"), &SkeletonModification2D::set_is_setup);\n\tClassDB::bind_method(D_METHOD(\"get_is_setup\"), &SkeletonModification2D::get_is_setup);\n\tClassDB::bind_method(D_METHOD(\"set_execution_mode\", \"execution_mode\"), &SkeletonModification2D::set_execution_mode);\n\tClassDB::bind_method(D_METHOD(\"get_execution_mode\"), &SkeletonModification2D::get_execution_mode);\n\tClassDB::bind_method(D_METHOD(\"clamp_angle\", \"angle\", \"min\", \"max\", \"invert\"), &SkeletonModification2D::clamp_angle);\n\tClassDB::bind_method(D_METHOD(\"set_editor_draw_gizmo\", \"draw_gizmo\"), &SkeletonModification2D::set_editor_draw_gizmo);\n\tClassDB::bind_method(D_METHOD(\"get_editor_draw_gizmo\"), &SkeletonModification2D::get_editor_draw_gizmo);\n\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"enabled\"), \"set_enabled\", \"get_enabled\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"execution_mode\", PROPERTY_HINT_ENUM, \"process, physics_process\"), \"set_execution_mode\", \"get_execution_mode\");\n}\n\nSkeletonModification2D::SkeletonModification2D() {\n\tstack = nullptr;\n\tis_setup = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2012 Gregory Banks\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"np.h\"\n#include \"np\/testmanager.hxx\"\n#include \"np\/testnode.hxx\"\n#include \"np\/classifier.hxx\"\n#include \"np\/spiegel\/spiegel.hxx\"\n#include \"np\/spiegel\/dwarf\/state.hxx\"\n\nnamespace np {\nusing namespace std;\n\ntestmanager_t *testmanager_t::instance_ = 0;\n\ntestmanager_t::testmanager_t()\n{\n assert(instance_ == 0);\n instance_ = this;\n}\n\ntestmanager_t::~testmanager_t()\n{\n while (classifiers_.size())\n {\n\tdelete classifiers_.back();\n\tclassifiers_.pop_back();\n }\n\n delete root_;\n root_ = 0;\n delete common_;\n common_ = 0;\n\n if (spiegel_)\n\tdelete spiegel_;\n\n assert(instance_ == this);\n instance_ = 0;\n}\n\n\ntestmanager_t *\ntestmanager_t::instance()\n{\n if (!instance_)\n {\n\tnew testmanager_t();\n\tinstance_->print_banner();\n\tinstance_->setup_classifiers();\n\tinstance_->discover_functions();\n\tinstance_->setup_builtin_intercepts();\n\t\/* TODO: check tree for a) leaves without FT_TEST\n\t * and b) non-leaves with FT_TEST *\/\n\/\/ \tinstance_->root_->dump(0);\n }\n return instance_;\n}\n\nvoid\ntestmanager_t::print_banner()\n{\n printf(\"np: NovaProva Copyright (c) Gregory Banks\\n\");\n printf(\"np: Built for O\/S \"_NP_OS\" architecture \"_NP_ARCH\"\\n\");\n}\n\nfunctype_t\ntestmanager_t::classify_function(const char *func,\n\t\t\t\t char *match_return,\n\t\t\t\t size_t maxmatch)\n{\n if (match_return)\n\tmatch_return[0] = '\\0';\n\n vector<classifier_t*>::iterator i;\n for (i = classifiers_.begin() ; i != classifiers_.end() ; ++i)\n {\n\tfunctype_t ft = (functype_t) (*i)->classify(func, match_return, maxmatch);\n\tif (ft != FT_UNKNOWN)\n\t return ft;\n\t\/* else, no match: just keep looking *\/\n }\n return FT_UNKNOWN;\n}\n\nvoid\ntestmanager_t::add_classifier(const char *re,\n\t\t\t bool case_sensitive,\n\t\t\t functype_t type)\n{\n classifier_t *cl = new classifier_t;\n if (!cl->set_regexp(re, case_sensitive))\n {\n\tdelete cl;\n\treturn;\n }\n cl->set_results(FT_UNKNOWN, type);\n classifiers_.push_back(cl);\n}\n\nvoid\ntestmanager_t::setup_classifiers()\n{\n add_classifier(\"^test_([a-z0-9].*)\", false, FT_TEST);\n add_classifier(\"^[tT]est([A-Z].*)\", false, FT_TEST);\n add_classifier(\"^[sS]etup$\", false, FT_BEFORE);\n add_classifier(\"^set_up$\", false, FT_BEFORE);\n add_classifier(\"^[iI]nit$\", false, FT_BEFORE);\n add_classifier(\"^[tT]ear[dD]own$\", false, FT_AFTER);\n add_classifier(\"^tear_down$\", false, FT_AFTER);\n add_classifier(\"^[cC]leanup$\", false, FT_AFTER);\n add_classifier(\"^mock_(.*)\", false, FT_MOCK);\n add_classifier(\"^[mM]ock([A-Z].*)\", false, FT_MOCK);\n add_classifier(\"^__np_parameter_(.*)\", false, FT_PARAM);\n}\n\nstatic string\ntest_name(np::spiegel::function_t *fn, char *submatch)\n{\n string name = fn->get_compile_unit()->get_absolute_path();\n\n \/* strip the .c or .cxx extension *\/\n size_t p = name.find_last_of('.');\n if (p != string::npos)\n\tname.resize(p);\n\n if (submatch && submatch[0])\n {\n\tname += \"\/\";\n\tname += submatch;\n }\n\n return name;\n}\n\nnp::spiegel::function_t *\ntestmanager_t::find_mock_target(string name)\n{\n vector<np::spiegel::compile_unit_t *> units = np::spiegel::get_compile_units();\n vector<np::spiegel::compile_unit_t *>::iterator i;\n for (i = units.begin() ; i != units.end() ; ++i)\n {\n\tvector<np::spiegel::function_t *> fns = (*i)->get_functions();\n\tvector<np::spiegel::function_t *>::iterator j;\n\tfor (j = fns.begin() ; j != fns.end() ; ++j)\n\t{\n\t if ((*j)->get_name() == name)\n\t\treturn *j;\n\t}\n }\n return 0;\n}\n\nstatic const struct __np_param_dec *\nget_param_dec(np::spiegel::function_t *fn)\n{\n vector<np::spiegel::value_t> args;\n np::spiegel::value_t ret = fn->invoke(args);\n return (const struct __np_param_dec *)ret.val.vpointer;\n}\n\nvoid\ntestmanager_t::discover_functions()\n{\n if (!spiegel_)\n {\n\tspiegel_ = new np::spiegel::dwarf::state_t();\n\tspiegel_->add_self();\n\tspiegel_->prepare_address_index();\n\troot_ = new testnode_t(0);\n }\n \/\/ else: splice common_ and root_ back together\n\n vector<np::spiegel::compile_unit_t *> units = np::spiegel::get_compile_units();\n vector<np::spiegel::compile_unit_t *>::iterator i;\n for (i = units.begin() ; i != units.end() ; ++i)\n {\n\/\/ fprintf(stderr, \"discover_functions: compile unit %s\\n\", (*i)->get_absolute_path().c_str());\n\tvector<np::spiegel::function_t *> fns = (*i)->get_functions();\n\tvector<np::spiegel::function_t *>::iterator j;\n\tfor (j = fns.begin() ; j != fns.end() ; ++j)\n\t{\n\t np::spiegel::function_t *fn = *j;\n\t functype_t type;\n\t char submatch[512];\n\n\t \/\/ We want functions which are defined in this compile unit\n\t if (!fn->get_address())\n\t\tcontinue;\n\n\t type = classify_function(fn->get_name().c_str(),\n\t\t\t\t submatch, sizeof(submatch));\n\t switch (type)\n\t {\n\t case FT_UNKNOWN:\n\t\tcontinue;\n\t case FT_TEST:\n\t\t\/\/ Test functions need a node name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\t\/\/ Test function return void\n\t\tif (fn->get_return_type()->get_classification() != np::spiegel::type_t::TC_VOID)\n\t\t continue;\n\t\t\/\/ Test functions take no arguments\n\t\tif (fn->get_parameter_types().size() != 0)\n\t\t continue;\n\t\troot_->make_path(test_name(fn, submatch))->set_function(type, fn);\n\t\tbreak;\n\t case FT_BEFORE:\n\t case FT_AFTER:\n\t\t\/\/ Before\/after functions go into the parent node\n\t\tassert(!submatch[0]);\n\t\t\/\/ Before\/after functions return int\n\t\tif (fn->get_return_type()->get_classification() != np::spiegel::type_t::TC_SIGNED_INT)\n\t\t continue;\n\t\t\/\/ Before\/after take no arguments\n\t\tif (fn->get_parameter_types().size() != 0)\n\t\t continue;\n\t\troot_->make_path(test_name(fn, submatch))->set_function(type, fn);\n\t\tbreak;\n\t case FT_MOCK:\n\t\t\/\/ Mock functions need a target name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\t{\n\t\t np::spiegel::function_t *target = find_mock_target(submatch);\n\t\t if (!target)\n\t\t\tcontinue;\n\t\t root_->make_path(test_name(fn, 0))->add_mock(target, fn);\n\t\t}\n\t\tbreak;\n\t case FT_PARAM:\n\t\t\/\/ Parameters need a name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\tconst struct __np_param_dec *dec = get_param_dec(fn);\n\t\troot_->make_path(test_name(fn, 0))->add_parameter(\n\t\t\t\tsubmatch, dec->var, dec->values);\n\t\tbreak;\n\t }\n\t}\n }\n\n \/\/ Calculate the effective root_ and common_\n common_ = root_;\n root_ = root_->detach_common();\n}\n\nextern void init_syslog_intercepts(testnode_t *);\n\nvoid\ntestmanager_t::setup_builtin_intercepts()\n{\n init_syslog_intercepts(root_);\n}\n\n\/\/ close the namespace\n};\n<commit_msg>Don't print the banner once per test child<commit_after>\/*\n * Copyright 2011-2012 Gregory Banks\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"np.h\"\n#include \"np\/testmanager.hxx\"\n#include \"np\/testnode.hxx\"\n#include \"np\/classifier.hxx\"\n#include \"np\/spiegel\/spiegel.hxx\"\n#include \"np\/spiegel\/dwarf\/state.hxx\"\n\nnamespace np {\nusing namespace std;\n\ntestmanager_t *testmanager_t::instance_ = 0;\n\ntestmanager_t::testmanager_t()\n{\n assert(instance_ == 0);\n instance_ = this;\n}\n\ntestmanager_t::~testmanager_t()\n{\n while (classifiers_.size())\n {\n\tdelete classifiers_.back();\n\tclassifiers_.pop_back();\n }\n\n delete root_;\n root_ = 0;\n delete common_;\n common_ = 0;\n\n if (spiegel_)\n\tdelete spiegel_;\n\n assert(instance_ == this);\n instance_ = 0;\n}\n\n\ntestmanager_t *\ntestmanager_t::instance()\n{\n if (!instance_)\n {\n\tnew testmanager_t();\n\tinstance_->print_banner();\n\tinstance_->setup_classifiers();\n\tinstance_->discover_functions();\n\tinstance_->setup_builtin_intercepts();\n\t\/* TODO: check tree for a) leaves without FT_TEST\n\t * and b) non-leaves with FT_TEST *\/\n\/\/ \tinstance_->root_->dump(0);\n }\n return instance_;\n}\n\nvoid\ntestmanager_t::print_banner()\n{\n printf(\"np: NovaProva Copyright (c) Gregory Banks\\n\");\n printf(\"np: Built for O\/S \"_NP_OS\" architecture \"_NP_ARCH\"\\n\");\n fflush(stdout);\n}\n\nfunctype_t\ntestmanager_t::classify_function(const char *func,\n\t\t\t\t char *match_return,\n\t\t\t\t size_t maxmatch)\n{\n if (match_return)\n\tmatch_return[0] = '\\0';\n\n vector<classifier_t*>::iterator i;\n for (i = classifiers_.begin() ; i != classifiers_.end() ; ++i)\n {\n\tfunctype_t ft = (functype_t) (*i)->classify(func, match_return, maxmatch);\n\tif (ft != FT_UNKNOWN)\n\t return ft;\n\t\/* else, no match: just keep looking *\/\n }\n return FT_UNKNOWN;\n}\n\nvoid\ntestmanager_t::add_classifier(const char *re,\n\t\t\t bool case_sensitive,\n\t\t\t functype_t type)\n{\n classifier_t *cl = new classifier_t;\n if (!cl->set_regexp(re, case_sensitive))\n {\n\tdelete cl;\n\treturn;\n }\n cl->set_results(FT_UNKNOWN, type);\n classifiers_.push_back(cl);\n}\n\nvoid\ntestmanager_t::setup_classifiers()\n{\n add_classifier(\"^test_([a-z0-9].*)\", false, FT_TEST);\n add_classifier(\"^[tT]est([A-Z].*)\", false, FT_TEST);\n add_classifier(\"^[sS]etup$\", false, FT_BEFORE);\n add_classifier(\"^set_up$\", false, FT_BEFORE);\n add_classifier(\"^[iI]nit$\", false, FT_BEFORE);\n add_classifier(\"^[tT]ear[dD]own$\", false, FT_AFTER);\n add_classifier(\"^tear_down$\", false, FT_AFTER);\n add_classifier(\"^[cC]leanup$\", false, FT_AFTER);\n add_classifier(\"^mock_(.*)\", false, FT_MOCK);\n add_classifier(\"^[mM]ock([A-Z].*)\", false, FT_MOCK);\n add_classifier(\"^__np_parameter_(.*)\", false, FT_PARAM);\n}\n\nstatic string\ntest_name(np::spiegel::function_t *fn, char *submatch)\n{\n string name = fn->get_compile_unit()->get_absolute_path();\n\n \/* strip the .c or .cxx extension *\/\n size_t p = name.find_last_of('.');\n if (p != string::npos)\n\tname.resize(p);\n\n if (submatch && submatch[0])\n {\n\tname += \"\/\";\n\tname += submatch;\n }\n\n return name;\n}\n\nnp::spiegel::function_t *\ntestmanager_t::find_mock_target(string name)\n{\n vector<np::spiegel::compile_unit_t *> units = np::spiegel::get_compile_units();\n vector<np::spiegel::compile_unit_t *>::iterator i;\n for (i = units.begin() ; i != units.end() ; ++i)\n {\n\tvector<np::spiegel::function_t *> fns = (*i)->get_functions();\n\tvector<np::spiegel::function_t *>::iterator j;\n\tfor (j = fns.begin() ; j != fns.end() ; ++j)\n\t{\n\t if ((*j)->get_name() == name)\n\t\treturn *j;\n\t}\n }\n return 0;\n}\n\nstatic const struct __np_param_dec *\nget_param_dec(np::spiegel::function_t *fn)\n{\n vector<np::spiegel::value_t> args;\n np::spiegel::value_t ret = fn->invoke(args);\n return (const struct __np_param_dec *)ret.val.vpointer;\n}\n\nvoid\ntestmanager_t::discover_functions()\n{\n if (!spiegel_)\n {\n\tspiegel_ = new np::spiegel::dwarf::state_t();\n\tspiegel_->add_self();\n\tspiegel_->prepare_address_index();\n\troot_ = new testnode_t(0);\n }\n \/\/ else: splice common_ and root_ back together\n\n vector<np::spiegel::compile_unit_t *> units = np::spiegel::get_compile_units();\n vector<np::spiegel::compile_unit_t *>::iterator i;\n for (i = units.begin() ; i != units.end() ; ++i)\n {\n\/\/ fprintf(stderr, \"discover_functions: compile unit %s\\n\", (*i)->get_absolute_path().c_str());\n\tvector<np::spiegel::function_t *> fns = (*i)->get_functions();\n\tvector<np::spiegel::function_t *>::iterator j;\n\tfor (j = fns.begin() ; j != fns.end() ; ++j)\n\t{\n\t np::spiegel::function_t *fn = *j;\n\t functype_t type;\n\t char submatch[512];\n\n\t \/\/ We want functions which are defined in this compile unit\n\t if (!fn->get_address())\n\t\tcontinue;\n\n\t type = classify_function(fn->get_name().c_str(),\n\t\t\t\t submatch, sizeof(submatch));\n\t switch (type)\n\t {\n\t case FT_UNKNOWN:\n\t\tcontinue;\n\t case FT_TEST:\n\t\t\/\/ Test functions need a node name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\t\/\/ Test function return void\n\t\tif (fn->get_return_type()->get_classification() != np::spiegel::type_t::TC_VOID)\n\t\t continue;\n\t\t\/\/ Test functions take no arguments\n\t\tif (fn->get_parameter_types().size() != 0)\n\t\t continue;\n\t\troot_->make_path(test_name(fn, submatch))->set_function(type, fn);\n\t\tbreak;\n\t case FT_BEFORE:\n\t case FT_AFTER:\n\t\t\/\/ Before\/after functions go into the parent node\n\t\tassert(!submatch[0]);\n\t\t\/\/ Before\/after functions return int\n\t\tif (fn->get_return_type()->get_classification() != np::spiegel::type_t::TC_SIGNED_INT)\n\t\t continue;\n\t\t\/\/ Before\/after take no arguments\n\t\tif (fn->get_parameter_types().size() != 0)\n\t\t continue;\n\t\troot_->make_path(test_name(fn, submatch))->set_function(type, fn);\n\t\tbreak;\n\t case FT_MOCK:\n\t\t\/\/ Mock functions need a target name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\t{\n\t\t np::spiegel::function_t *target = find_mock_target(submatch);\n\t\t if (!target)\n\t\t\tcontinue;\n\t\t root_->make_path(test_name(fn, 0))->add_mock(target, fn);\n\t\t}\n\t\tbreak;\n\t case FT_PARAM:\n\t\t\/\/ Parameters need a name\n\t\tif (!submatch[0])\n\t\t continue;\n\t\tconst struct __np_param_dec *dec = get_param_dec(fn);\n\t\troot_->make_path(test_name(fn, 0))->add_parameter(\n\t\t\t\tsubmatch, dec->var, dec->values);\n\t\tbreak;\n\t }\n\t}\n }\n\n \/\/ Calculate the effective root_ and common_\n common_ = root_;\n root_ = root_->detach_common();\n}\n\nextern void init_syslog_intercepts(testnode_t *);\n\nvoid\ntestmanager_t::setup_builtin_intercepts()\n{\n init_syslog_intercepts(root_);\n}\n\n\/\/ close the namespace\n};\n<|endoftext|>"} {"text":"<commit_before>#include <map.hpp>\n#include <iostream>\n#include <Windows.h>\n\nusing namespace std;\nusing namespace fabric;\n\ntypedef int(*f_loadmap)();\n\n\/\/\/TODO: Linux and Mac compatibility\n\nint Map::load(char* path) {\n\t\/\/ Load the map dll into memory\n\tHINSTANCE hGetProcIDLL = LoadLibrary(path);\n\n\tcout << path << endl;\n\n\tif (!hGetProcIDLL) {\n\t\tcout << \"Could not load DLL at \" << path << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Get adress to the loadmap function defied in the DLL\n\tf_loadmap loadmap = (f_loadmap)GetProcAddress(hGetProcIDLL, \"loadmap\");\n\n\tif (!loadmap) {\n\t\tcout << \"Could not get loadmap function\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\t\/\/Unload library\n\tFreeLibrary(hGetProcIDLL);\n\n\tloadmap();\n\n\t\/\/ Spawn all Behaviors for the gameobjs\n\tfor (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {\n\t\tEngine::get()->vLoadedGameObjects->at(i)->spawn();\n\t}\n\n\tstd::cout << \"Loaded \";\n\tstd::cout << Engine::get()->vLoadedGameObjects->size();\n\tstd::cout << \" entitie(s)\" << std::endl;\n\n\t\/\/ Call Setup on just loaded gameobjects\n\tfor (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {\n\t\tEngine::get()->vLoadedGameObjects->at(i)->setup();\n\t}\n\n\n\treturn 0;\n\n}\n\n\nint Map::unload() {\n\tstd::cout << \"Unloading...\" << std::endl;\n\tm_mMap->unload();\n\tstd::cout << \"Unloaded...\" << std::endl;\n\treturn 0;\n}\n<commit_msg>Added unload for maps<commit_after>#include <map.hpp>\n#include <iostream>\n#include <Windows.h>\n#include <vector>\n\nusing namespace std;\nusing namespace fabric;\n\ntypedef vector<GameObject *>*(*f_loadmap)();\n\n\/\/\/TODO: Linux and Mac compatibility\n\nint Map::load(char* path) {\n\t\/\/ Load the map dll into memory\n\tHINSTANCE hGetProcIDLL = LoadLibrary(path);\n\n\tcout << path << endl;\n\n\tif (!hGetProcIDLL) {\n\t\tcout << \"Could not load DLL at \" << path << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Get adress to the loadmap function defied in the DLL\n\tf_loadmap loadmap = (f_loadmap)GetProcAddress(hGetProcIDLL, \"loadmap\");\n\n\tif (!loadmap) {\n\t\tcout << \"Could not get loadmap function\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ For safety delete the vLoadedGameObjects Pointer\n\tdelete Engine::get()->vLoadedGameObjects;\n\n\t\/\/ Execute load and overwrite the vLoadedGameopjects pointer\n\tEngine::get()->vLoadedGameObjects = loadmap();\n\n\t\/\/ Spawn all Behaviors for the gameobjs\n\tfor (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {\n\t\tEngine::get()->vLoadedGameObjects->at(i)->spawn();\n\t}\n\n\tstd::cout << \"Loaded \";\n\tstd::cout << Engine::get()->vLoadedGameObjects->size();\n\tstd::cout << \" entitie(s)\" << std::endl;\n\n\tm_mMap = &hGetProcIDLL;\n\n\t\/\/ Call Setup on just loaded gameobjects\n\tfor (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {\n\t\tEngine::get()->vLoadedGameObjects->at(i)->setup();\n\t}\n\n\treturn 0;\n\n}\n\n\nint Map::unload() {\n\tstd::cout << \"Unloading...\" << std::endl;\n\t\n\tif (m_mMap) {\n\t\tFreeLibrary(*m_mMap);\n\t\tdelete m_mMap;\n\t\tm_mMap = 0;\n\t}\n\n\n\tstd::cout << \"Unloaded...\" << std::endl;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include <QApplication>\n#include <qdir.h>\n#include \"core\/log.h\"\n#include \"core\/profiler.h\"\n#include \"core\/resource_manager.h\"\n#include \"core\/resource_manager_base.h\"\n#include \"editor\/world_editor.h\"\n#include \"editor\/gizmo.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/plugin_manager.h\"\n#include <graphics\/gl_ext.h>\n#include \"graphics\/irender_device.h\"\n#include \"graphics\/pipeline.h\"\n#include \"graphics\/renderer.h\"\n#include \"physics\/physics_scene.h\"\n#include \"physics\/physics_system.h\"\n#include \"sceneview.h\"\n#include \"gameview.h\"\n#include \"wgl_render_device.h\"\n#include \"materialmanager.h\"\n\n\nclass App\n{\n\tpublic:\n\t\tApp()\n\t\t{\n\t\t\tm_game_render_device = NULL;\n\t\t\tm_edit_render_device = NULL;\n\t\t\tm_qt_app = NULL;\n\t\t\tm_main_window = NULL;\n\t\t\tm_world_editor = NULL;\n\t\t}\n\n\t\t~App()\n\t\t{\n\t\t\tdelete m_main_window;\n\t\t\tdelete m_qt_app;\n\t\t\tLumix::WorldEditor::destroy(m_world_editor);\n\t\t}\n\n\t\tvoid onUniverseCreated()\n\t\t{\n\t\t\tm_edit_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \n\t\t\tm_game_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \n\t\t}\n\n\t\tvoid onUniverseDestroyed()\n\t\t{\n\t\t\tif(m_edit_render_device)\n\t\t\t{\n\t\t\t\tm_edit_render_device->getPipeline().setScene(NULL); \n\t\t\t}\n\t\t\tif(m_game_render_device)\n\t\t\t{\n\t\t\t\tm_game_render_device->getPipeline().setScene(NULL); \n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tHGLRC createGLContext(HWND hwnd[], int count)\n\t\t{\n\t\t\tASSERT(count > 0);\n\t\t\tQWidget* widget = new QWidget();\n\t\t\tHWND gl_hwnd = (HWND)widget->winId();\n\t\t\tHDC hdc;\n\t\t\thdc = GetDC(gl_hwnd);\n\t\t\tASSERT(hdc != NULL);\n\t\t\tif (hdc == NULL)\n\t\t\t{\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get the device context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tBOOL success;\n\t\t\tPIXELFORMATDESCRIPTOR pfd =\n\t\t\t{\n\t\t\t\tsizeof(PIXELFORMATDESCRIPTOR), \/\/ size of this pfd \n\t\t\t\t1, \/\/ version number \n\t\t\t\tPFD_DRAW_TO_WINDOW | \/\/ support window \n\t\t\t\tPFD_SUPPORT_OPENGL | \/\/ support OpenGL \n\t\t\t\tPFD_DOUBLEBUFFER, \/\/ double buffered \n\t\t\t\tPFD_TYPE_RGBA, \/\/ RGBA type \n\t\t\t\t24, \/\/ 24-bit color depth \n\t\t\t\t0, 0, 0, 0, 0, 0, \/\/ color bits ignored \n\t\t\t\t0, \/\/ no alpha buffer \n\t\t\t\t0, \/\/ shift bit ignored \n\t\t\t\t0, \/\/ no accumulation buffer \n\t\t\t\t0, 0, 0, 0, \/\/ accum bits ignored \n\t\t\t\t32, \/\/ 32-bit z-buffer \n\t\t\t\t0, \/\/ no stencil buffer \n\t\t\t\t0, \/\/ no auxiliary buffer \n\t\t\t\tPFD_MAIN_PLANE, \/\/ main layer \n\t\t\t\t0, \/\/ reserved \n\t\t\t\t0, 0, 0 \/\/ layer masks ignored \n\t\t\t};\n\t\t\tint pixelformat = ChoosePixelFormat(hdc, &pfd);\n\t\t\tif (pixelformat == 0)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not choose a pixel format\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsuccess = SetPixelFormat(hdc, pixelformat, &pfd);\n\t\t\tif (success == FALSE)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not set a pixel format\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tHGLRC hglrc = wglCreateContext(hdc);\n\t\t\tif (hglrc == NULL)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not create an opengl context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsuccess = wglMakeCurrent(hdc, hglrc);\n\t\t\tif (success == FALSE)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not make the opengl context current rendering context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tUINT numFormats;\n\t\t\t\tint atrribs[] =\n\t\t\t\t{\n\t\t\t\t\tWGL_DRAW_TO_WINDOW_ARB, GL_TRUE,\n\t\t\t\t\tWGL_SUPPORT_OPENGL_ARB, GL_TRUE,\n\t\t\t\t\tWGL_DOUBLE_BUFFER_ARB, GL_TRUE,\n\t\t\t\t\tWGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,\n\t\t\t\t\tWGL_COLOR_BITS_ARB, 32,\n\t\t\t\t\tWGL_DEPTH_BITS_ARB, 24,\n\t\t\t\t\tWGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,\n\t\t\t\t\tWGL_SAMPLE_BUFFERS_ARB, GL_TRUE,\n\t\t\t\t\tWGL_SAMPLES_ARB, 4,\n\t\t\t\t\t0\n\t\t\t\t};\n\t\t\t\tPFNWGLCHOOSEPIXELFORMATARBPROC foo;\n\t\t\t\tfoo = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress(\"wglChoosePixelFormatARB\");\n\t\t\t\tif (!foo)\n\t\t\t\t{\n\t\t\t\t\tdelete widget;\n\t\t\t\t\tASSERT(false);\n\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get function wglChoosePixelFormatARB\";\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tsuccess = foo(hdc, atrribs, NULL, 1, &pixelformat, &numFormats);\n\t\t\t}\n\t\t\twglDeleteContext(hglrc);\n\t\t\thglrc = NULL;\n\t\t\tdelete widget;\n\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tif (hwnd[i])\n\t\t\t\t{\n\t\t\t\t\thdc = GetDC(hwnd[i]);\n\t\t\t\t\tChoosePixelFormat(hdc, &pfd);\n\t\t\t\t\tif (hdc == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get the device context\";\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tSetPixelFormat(hdc, pixelformat, &pfd);\n\n\t\t\t\t\tif (!hglrc)\n\t\t\t\t\t{\n\t\t\t\t\t\thglrc = wglCreateContext(hdc);\n\t\t\t\t\t\tif (hglrc == NULL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not create an opengl context\";\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsuccess = wglMakeCurrent(hdc, hglrc);\n\t\t\t\t\t\tif (success == FALSE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not make the opengl context current rendering context\";\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\treturn hglrc;\n\t\t}\t\n\n\n\t\tvoid renderPhysics()\n\t\t{\n\t\t\tLumix::PhysicsSystem* system = static_cast<Lumix::PhysicsSystem*>(m_world_editor->getEngine().getPluginManager().getPlugin(\"physics\"));\n\t\t\tif(system && system->getScene())\n\t\t\t{\n\t\t\t\tsystem->getScene()->render();\n\t\t\t}\n\t\t}\n\n\n\t\tvoid init(int argc, char* argv[])\n\t\t{\n\t\t\tm_qt_app = new QApplication(argc, argv);\n\t\t\tQFile file(\"editor\/stylesheet.qss\");\n\t\t\tfile.open(QFile::ReadOnly);\n\t\t\tm_qt_app->setStyleSheet(QLatin1String(file.readAll()));\n\n\t\t\tm_main_window = new MainWindow();\n\t\t\tm_main_window->show();\n\n\t\t\tHWND hwnd = (HWND)m_main_window->getSceneView()->getViewWidget()->winId();\n\t\t\tHWND game_hwnd = (HWND)m_main_window->getGameView()->getContentWidget()->winId();\n\t\t\tHWND hwnds[] = { hwnd, game_hwnd, (HWND)m_main_window->getMaterialManager()->getPreview()->winId() };\n\t\t\tHGLRC hglrc = createGLContext(hwnds, 3);\n\n\t\t\tm_world_editor = Lumix::WorldEditor::create(QDir::currentPath().toLocal8Bit().data());\n\t\t\tASSERT(m_world_editor);\n\t\t\tm_world_editor->tick();\n\n\t\t\tm_main_window->setWorldEditor(*m_world_editor);\n\t\t\tm_main_window->getSceneView()->setWorldEditor(m_world_editor);\n\n\t\t\tm_edit_render_device = new WGLRenderDevice(m_world_editor->getEngine(), \"pipelines\/main.json\");\n\t\t\tm_edit_render_device->m_hdc = GetDC(hwnd);\n\t\t\tm_edit_render_device->m_opengl_context = hglrc;\n\t\t\tm_edit_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \/\/\/ TODO manage scene properly\n\t\t\tm_world_editor->setEditViewRenderDevice(*m_edit_render_device);\n\t\t\tm_edit_render_device->getPipeline().addCustomCommandHandler(\"render_physics\").bind<App, &App::renderPhysics>(this);\n\n\t\t\tm_game_render_device = new\tWGLRenderDevice(m_world_editor->getEngine(), \"pipelines\/game_view.json\");\n\t\t\tm_game_render_device->m_hdc = GetDC(game_hwnd);\n\t\t\tm_game_render_device->m_opengl_context = hglrc;\n\t\t\tm_game_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \/\/\/ TODO manage scene properly\n\t\t\tm_world_editor->getEngine().getRenderer().setRenderDevice(*m_game_render_device);\n\n\t\t\tm_world_editor->universeCreated().bind<App, &App::onUniverseCreated>(this);\n\t\t\tm_world_editor->universeDestroyed().bind<App, &App::onUniverseDestroyed>(this);\n\n\t\t\tm_main_window->getSceneView()->setPipeline(m_edit_render_device->getPipeline());\n\t\t\tm_main_window->getGameView()->setPipeline(m_game_render_device->getPipeline());\n\t\t}\n\n\t\tvoid shutdown()\n\t\t{\n\t\t\tdelete m_game_render_device;\n\t\t\tm_game_render_device = NULL;\n\t\t\tdelete m_edit_render_device;\n\t\t\tm_edit_render_device = NULL;\n\t\t}\n\n\t\tvoid renderEditView()\n\t\t{\n\t\t\tPROFILE_FUNCTION();\n\t\t\tm_edit_render_device->beginFrame();\n\t\t\tm_world_editor->render(*m_edit_render_device);\n\t\t\tm_world_editor->renderIcons(*m_edit_render_device);\n\t\t\tm_world_editor->getGizmo().updateScale(m_world_editor->getEditCamera());\n\t\t\tm_world_editor->getGizmo().render(m_world_editor->getEngine().getRenderer(), *m_edit_render_device);\n\t\t\tm_edit_render_device->endFrame();\n\n\t\t\tm_main_window->getMaterialManager()->updatePreview();\n\t\t}\n\n\t\tvoid handleEvents()\n\t\t{\n\t\t\tPROFILE_FUNCTION();\n\t\t\t{\n\t\t\t\tPROFILE_BLOCK(\"qt::processEvents\");\n\t\t\t\tm_qt_app->processEvents();\n\t\t\t}\n\t\t\tBYTE keys[256];\n\t\t\tGetKeyboardState(keys);\n\t\t\tif (m_main_window->getSceneView()->getViewWidget()->hasFocus())\n\t\t\t{\n\t\t\t\t\/\/\/ TODO refactor\n\t\t\t\tif(keys[VK_CONTROL] >> 7 == 0)\n\t\t\t\t{\n\t\t\t\t\tfloat speed = m_main_window->getSceneView()->getNavivationSpeed();\n\t\t\t\t\tif (keys[VK_LSHIFT] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tspeed *= 10;\n\t\t\t\t\t}\n\t\t\t\t\tif (keys['W'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(1, 0, speed);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keys['S'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(-1, 0, speed);\n\t\t\t\t\t}\n\t\t\t\t\tif (keys['A'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(0, -1, speed);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keys['D'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(0, 1, speed);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid run()\n\t\t{\n\t\t\twhile (m_main_window->isVisible())\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tPROFILE_BLOCK(\"tick\");\n\t\t\t\t\trenderEditView();\n\t\t\t\t\tm_world_editor->getEngine().getRenderer().renderGame();\n\t\t\t\t\tm_world_editor->tick();\n\t\t\t\t\thandleEvents();\n\t\t\t\t}\n\t\t\t\t{\n\t\t\t\t\tPROFILE_BLOCK(\"tick2\");\n\t\t\t\t}\n\t\t\t\tLumix::g_profiler.frame();\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tWGLRenderDevice* m_edit_render_device;\n\t\tWGLRenderDevice* m_game_render_device;\n\t\tMainWindow* m_main_window;\n\t\tLumix::WorldEditor* m_world_editor;\n\t\tQApplication* m_qt_app;\n};\n\nint main(int argc, char* argv[])\n{\n\tApp app;\n\tapp.init(argc, argv);\n\tapp.run();\n\tapp.shutdown();\n\treturn 0;\n}\n<commit_msg>removed forgotten test code<commit_after>#include \"mainwindow.h\"\n#include <QApplication>\n#include <qdir.h>\n#include \"core\/log.h\"\n#include \"core\/profiler.h\"\n#include \"core\/resource_manager.h\"\n#include \"core\/resource_manager_base.h\"\n#include \"editor\/world_editor.h\"\n#include \"editor\/gizmo.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/plugin_manager.h\"\n#include <graphics\/gl_ext.h>\n#include \"graphics\/irender_device.h\"\n#include \"graphics\/pipeline.h\"\n#include \"graphics\/renderer.h\"\n#include \"physics\/physics_scene.h\"\n#include \"physics\/physics_system.h\"\n#include \"sceneview.h\"\n#include \"gameview.h\"\n#include \"wgl_render_device.h\"\n#include \"materialmanager.h\"\n\n\nclass App\n{\n\tpublic:\n\t\tApp()\n\t\t{\n\t\t\tm_game_render_device = NULL;\n\t\t\tm_edit_render_device = NULL;\n\t\t\tm_qt_app = NULL;\n\t\t\tm_main_window = NULL;\n\t\t\tm_world_editor = NULL;\n\t\t}\n\n\t\t~App()\n\t\t{\n\t\t\tdelete m_main_window;\n\t\t\tdelete m_qt_app;\n\t\t\tLumix::WorldEditor::destroy(m_world_editor);\n\t\t}\n\n\t\tvoid onUniverseCreated()\n\t\t{\n\t\t\tm_edit_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \n\t\t\tm_game_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \n\t\t}\n\n\t\tvoid onUniverseDestroyed()\n\t\t{\n\t\t\tif(m_edit_render_device)\n\t\t\t{\n\t\t\t\tm_edit_render_device->getPipeline().setScene(NULL); \n\t\t\t}\n\t\t\tif(m_game_render_device)\n\t\t\t{\n\t\t\t\tm_game_render_device->getPipeline().setScene(NULL); \n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tHGLRC createGLContext(HWND hwnd[], int count)\n\t\t{\n\t\t\tASSERT(count > 0);\n\t\t\tQWidget* widget = new QWidget();\n\t\t\tHWND gl_hwnd = (HWND)widget->winId();\n\t\t\tHDC hdc;\n\t\t\thdc = GetDC(gl_hwnd);\n\t\t\tASSERT(hdc != NULL);\n\t\t\tif (hdc == NULL)\n\t\t\t{\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get the device context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tBOOL success;\n\t\t\tPIXELFORMATDESCRIPTOR pfd =\n\t\t\t{\n\t\t\t\tsizeof(PIXELFORMATDESCRIPTOR), \/\/ size of this pfd \n\t\t\t\t1, \/\/ version number \n\t\t\t\tPFD_DRAW_TO_WINDOW | \/\/ support window \n\t\t\t\tPFD_SUPPORT_OPENGL | \/\/ support OpenGL \n\t\t\t\tPFD_DOUBLEBUFFER, \/\/ double buffered \n\t\t\t\tPFD_TYPE_RGBA, \/\/ RGBA type \n\t\t\t\t24, \/\/ 24-bit color depth \n\t\t\t\t0, 0, 0, 0, 0, 0, \/\/ color bits ignored \n\t\t\t\t0, \/\/ no alpha buffer \n\t\t\t\t0, \/\/ shift bit ignored \n\t\t\t\t0, \/\/ no accumulation buffer \n\t\t\t\t0, 0, 0, 0, \/\/ accum bits ignored \n\t\t\t\t32, \/\/ 32-bit z-buffer \n\t\t\t\t0, \/\/ no stencil buffer \n\t\t\t\t0, \/\/ no auxiliary buffer \n\t\t\t\tPFD_MAIN_PLANE, \/\/ main layer \n\t\t\t\t0, \/\/ reserved \n\t\t\t\t0, 0, 0 \/\/ layer masks ignored \n\t\t\t};\n\t\t\tint pixelformat = ChoosePixelFormat(hdc, &pfd);\n\t\t\tif (pixelformat == 0)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not choose a pixel format\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsuccess = SetPixelFormat(hdc, pixelformat, &pfd);\n\t\t\tif (success == FALSE)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not set a pixel format\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tHGLRC hglrc = wglCreateContext(hdc);\n\t\t\tif (hglrc == NULL)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not create an opengl context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsuccess = wglMakeCurrent(hdc, hglrc);\n\t\t\tif (success == FALSE)\n\t\t\t{\n\t\t\t\tdelete widget;\n\t\t\t\tASSERT(false);\n\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not make the opengl context current rendering context\";\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tUINT numFormats;\n\t\t\t\tint atrribs[] =\n\t\t\t\t{\n\t\t\t\t\tWGL_DRAW_TO_WINDOW_ARB, GL_TRUE,\n\t\t\t\t\tWGL_SUPPORT_OPENGL_ARB, GL_TRUE,\n\t\t\t\t\tWGL_DOUBLE_BUFFER_ARB, GL_TRUE,\n\t\t\t\t\tWGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,\n\t\t\t\t\tWGL_COLOR_BITS_ARB, 32,\n\t\t\t\t\tWGL_DEPTH_BITS_ARB, 24,\n\t\t\t\t\tWGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,\n\t\t\t\t\tWGL_SAMPLE_BUFFERS_ARB, GL_TRUE,\n\t\t\t\t\tWGL_SAMPLES_ARB, 4,\n\t\t\t\t\t0\n\t\t\t\t};\n\t\t\t\tPFNWGLCHOOSEPIXELFORMATARBPROC foo;\n\t\t\t\tfoo = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress(\"wglChoosePixelFormatARB\");\n\t\t\t\tif (!foo)\n\t\t\t\t{\n\t\t\t\t\tdelete widget;\n\t\t\t\t\tASSERT(false);\n\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get function wglChoosePixelFormatARB\";\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tsuccess = foo(hdc, atrribs, NULL, 1, &pixelformat, &numFormats);\n\t\t\t}\n\t\t\twglDeleteContext(hglrc);\n\t\t\thglrc = NULL;\n\t\t\tdelete widget;\n\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tif (hwnd[i])\n\t\t\t\t{\n\t\t\t\t\thdc = GetDC(hwnd[i]);\n\t\t\t\t\tChoosePixelFormat(hdc, &pfd);\n\t\t\t\t\tif (hdc == NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not get the device context\";\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\t\t\t\t\tSetPixelFormat(hdc, pixelformat, &pfd);\n\n\t\t\t\t\tif (!hglrc)\n\t\t\t\t\t{\n\t\t\t\t\t\thglrc = wglCreateContext(hdc);\n\t\t\t\t\t\tif (hglrc == NULL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not create an opengl context\";\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsuccess = wglMakeCurrent(hdc, hglrc);\n\t\t\t\t\t\tif (success == FALSE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tASSERT(false);\n\t\t\t\t\t\t\tLumix::g_log_error.log(\"renderer\") << \"Could not make the opengl context current rendering context\";\n\t\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\treturn hglrc;\n\t\t}\t\n\n\n\t\tvoid renderPhysics()\n\t\t{\n\t\t\tLumix::PhysicsSystem* system = static_cast<Lumix::PhysicsSystem*>(m_world_editor->getEngine().getPluginManager().getPlugin(\"physics\"));\n\t\t\tif(system && system->getScene())\n\t\t\t{\n\t\t\t\tsystem->getScene()->render();\n\t\t\t}\n\t\t}\n\n\n\t\tvoid init(int argc, char* argv[])\n\t\t{\n\t\t\tm_qt_app = new QApplication(argc, argv);\n\t\t\tQFile file(\"editor\/stylesheet.qss\");\n\t\t\tfile.open(QFile::ReadOnly);\n\t\t\tm_qt_app->setStyleSheet(QLatin1String(file.readAll()));\n\n\t\t\tm_main_window = new MainWindow();\n\t\t\tm_main_window->show();\n\n\t\t\tHWND hwnd = (HWND)m_main_window->getSceneView()->getViewWidget()->winId();\n\t\t\tHWND game_hwnd = (HWND)m_main_window->getGameView()->getContentWidget()->winId();\n\t\t\tHWND hwnds[] = { hwnd, game_hwnd, (HWND)m_main_window->getMaterialManager()->getPreview()->winId() };\n\t\t\tHGLRC hglrc = createGLContext(hwnds, 3);\n\n\t\t\tm_world_editor = Lumix::WorldEditor::create(QDir::currentPath().toLocal8Bit().data());\n\t\t\tASSERT(m_world_editor);\n\t\t\tm_world_editor->tick();\n\n\t\t\tm_main_window->setWorldEditor(*m_world_editor);\n\t\t\tm_main_window->getSceneView()->setWorldEditor(m_world_editor);\n\n\t\t\tm_edit_render_device = new WGLRenderDevice(m_world_editor->getEngine(), \"pipelines\/main.json\");\n\t\t\tm_edit_render_device->m_hdc = GetDC(hwnd);\n\t\t\tm_edit_render_device->m_opengl_context = hglrc;\n\t\t\tm_edit_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \/\/\/ TODO manage scene properly\n\t\t\tm_world_editor->setEditViewRenderDevice(*m_edit_render_device);\n\t\t\tm_edit_render_device->getPipeline().addCustomCommandHandler(\"render_physics\").bind<App, &App::renderPhysics>(this);\n\n\t\t\tm_game_render_device = new\tWGLRenderDevice(m_world_editor->getEngine(), \"pipelines\/game_view.json\");\n\t\t\tm_game_render_device->m_hdc = GetDC(game_hwnd);\n\t\t\tm_game_render_device->m_opengl_context = hglrc;\n\t\t\tm_game_render_device->getPipeline().setScene(m_world_editor->getEngine().getRenderScene()); \/\/\/ TODO manage scene properly\n\t\t\tm_world_editor->getEngine().getRenderer().setRenderDevice(*m_game_render_device);\n\n\t\t\tm_world_editor->universeCreated().bind<App, &App::onUniverseCreated>(this);\n\t\t\tm_world_editor->universeDestroyed().bind<App, &App::onUniverseDestroyed>(this);\n\n\t\t\tm_main_window->getSceneView()->setPipeline(m_edit_render_device->getPipeline());\n\t\t\tm_main_window->getGameView()->setPipeline(m_game_render_device->getPipeline());\n\t\t}\n\n\t\tvoid shutdown()\n\t\t{\n\t\t\tdelete m_game_render_device;\n\t\t\tm_game_render_device = NULL;\n\t\t\tdelete m_edit_render_device;\n\t\t\tm_edit_render_device = NULL;\n\t\t}\n\n\t\tvoid renderEditView()\n\t\t{\n\t\t\tPROFILE_FUNCTION();\n\t\t\tm_edit_render_device->beginFrame();\n\t\t\tm_world_editor->render(*m_edit_render_device);\n\t\t\tm_world_editor->renderIcons(*m_edit_render_device);\n\t\t\tm_world_editor->getGizmo().updateScale(m_world_editor->getEditCamera());\n\t\t\tm_world_editor->getGizmo().render(m_world_editor->getEngine().getRenderer(), *m_edit_render_device);\n\t\t\tm_edit_render_device->endFrame();\n\n\t\t\tm_main_window->getMaterialManager()->updatePreview();\n\t\t}\n\n\t\tvoid handleEvents()\n\t\t{\n\t\t\tPROFILE_FUNCTION();\n\t\t\t{\n\t\t\t\tPROFILE_BLOCK(\"qt::processEvents\");\n\t\t\t\tm_qt_app->processEvents();\n\t\t\t}\n\t\t\tBYTE keys[256];\n\t\t\tGetKeyboardState(keys);\n\t\t\tif (m_main_window->getSceneView()->getViewWidget()->hasFocus())\n\t\t\t{\n\t\t\t\t\/\/\/ TODO refactor\n\t\t\t\tif(keys[VK_CONTROL] >> 7 == 0)\n\t\t\t\t{\n\t\t\t\t\tfloat speed = m_main_window->getSceneView()->getNavivationSpeed();\n\t\t\t\t\tif (keys[VK_LSHIFT] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tspeed *= 10;\n\t\t\t\t\t}\n\t\t\t\t\tif (keys['W'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(1, 0, speed);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keys['S'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(-1, 0, speed);\n\t\t\t\t\t}\n\t\t\t\t\tif (keys['A'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(0, -1, speed);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keys['D'] >> 7)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_world_editor->navigate(0, 1, speed);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid run()\n\t\t{\n\t\t\twhile (m_main_window->isVisible())\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tPROFILE_BLOCK(\"tick\");\n\t\t\t\t\trenderEditView();\n\t\t\t\t\tm_world_editor->getEngine().getRenderer().renderGame();\n\t\t\t\t\tm_world_editor->tick();\n\t\t\t\t\thandleEvents();\n\t\t\t\t}\n\t\t\t\tLumix::g_profiler.frame();\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tWGLRenderDevice* m_edit_render_device;\n\t\tWGLRenderDevice* m_game_render_device;\n\t\tMainWindow* m_main_window;\n\t\tLumix::WorldEditor* m_world_editor;\n\t\tQApplication* m_qt_app;\n};\n\nint main(int argc, char* argv[])\n{\n\tApp app;\n\tapp.init(argc, argv);\n\tapp.run();\n\tapp.shutdown();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"LIBCD.H\"\n\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define DISC_IMAGE_FILENAME \"TOMB5.BIN\"\n\n#define DECODE_BCD(x) (((x) >> 4) * 10 + ((x) & 0xF))\n#define ENCODE_BCD(x) ((((x) \/ 10) << 4) | ((x) % 10))\n\nFILE* openFile = NULL;\n\ntypedef struct commandQueue\n{\n\tunsigned int mode;\n\tunsigned char* p;\n\tunsigned int processed;\n\tunsigned int count;\n};\n\n#define COMMAND_QUEUE_SIZE 256\n\ncommandQueue comQueue[COMMAND_QUEUE_SIZE];\ncommandQueue* comStart = &comQueue[0];\ncommandQueue* comEnd = &comQueue[COMMAND_QUEUE_SIZE-1];\nint comQueueIndex = 0;\nint comQueueCount = 0;\nint currentSector = 0;\nint sectorSize = 2352;\/\/TODO obtain properly from cue sheet\n\n#pragma pack(push, 1)\nstruct TOC\n{\n\tunsigned char tocEntryLength;\n\tunsigned char extEntryLength;\n\tunsigned int sectorPosition[2];\n\tunsigned int fileSize[2];\n\tunsigned char date[7];\n\tunsigned char flags;\n\tunsigned char fileUnitSize;\n\tunsigned char interleaveGapSize;\n\tunsigned short volSeqNum[2];\n\tunsigned char nameLength;\n};\n\nstruct Sector\n{\n\tunsigned char\tsync[12];\t\/\/\/ Sync pattern (usually 00 FF FF FF FF FF FF FF FF FF FF 00)\n\tunsigned char\taddr[3];\t\/\/\/ Sector address (see below for encoding details)\n\tunsigned char\tmode;\t\t\/\/\/ Mode (usually 2 for Mode 2 Form 1\/2 sectors)\n\tunsigned char\tsubHead[8];\t\/\/\/ Sub-header (00 00 08 00 00 00 08 00 for Form 1 data sectors)\n\tunsigned char\tdata[2048];\t\/\/\/ Data (form 1)\n\tunsigned char\tedc[4];\t\t\/\/\/ Error-detection code (CRC32 of data area)\n\tunsigned char\tecc[276];\t\/\/\/ Error-correction code (uses Reed-Solomon ECC algorithm)\n};\n#pragma pack(pop)\n\nCdlFILE* CdSearchFile(CdlFILE* fp, char* name)\n{\n\tmemset(fp, 0, sizeof(CdlFILE));\n\n\tif (name[0] == '\\\\')\n\t{\n\t\tname++;\n\t}\n\n\tif (openFile != NULL)\n\t{\n\t\tfseek(openFile, 22 * sectorSize, SEEK_SET);\n\n\t\tint tocLocalOffset = 0;\n\t\tSector sector;\n\t\tfread(§or, sizeof(Sector), 1, openFile);\n\t\tTOC* toc = (TOC*)§or.data[0];\n\t\twhile (toc->tocEntryLength != 0)\n\t\t{\n\t\t\tif (strcmp((char*)§or.data[tocLocalOffset + sizeof(TOC)], name) == 0)\n\t\t\t{\n\t\t\t\tmemcpy(&fp->name[0], (char*)§or.data[tocLocalOffset + sizeof(TOC)], strlen(name));\n\t\t\t\tfp->size = toc->fileSize[0];\n\t\t\t\tfseek(openFile, toc->sectorPosition[0] * sectorSize, SEEK_SET);\n\t\t\t\tfread(§or, sizeof(Sector), 1, openFile);\n\t\t\t\tfp->pos.minute = sector.addr[0];\n\t\t\t\tfp->pos.second = sector.addr[1];\n\t\t\t\tfp->pos.sector = sector.addr[2];\n\n\n#if _DEBUG\n\t\t\t\tprintf(\"CDSearchFile() Found %s\\n\", name);\n#endif\n\t\t\t\treturn fp;\n\t\t\t}\n\t\t\ttocLocalOffset += toc->tocEntryLength;\n\t\t\ttoc = (TOC*)§or.data[tocLocalOffset];\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nint mfhi(int a, int b)\n{\n\tunsigned long long temp = (long long)((long long)(int)a * (long long)(int)b);\n\n\tint lo = temp & 0xffffffff;\n\tint hi = temp >> 32;\n\treturn ((temp >> 32) & 0xFFFFFFFF);\n}\n\nCdlLOC* CdIntToPos(int i, CdlLOC* p)\n{\n\ti += 150;\n\tp->sector = i % 75;\n\tint rem = i \/ 75;\n\tp->second = rem % 60;\n\tp->minute = rem \/ 60;\n\treturn p;\n}\n\nint CdControl(u_char com, u_char * param, u_char * result)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\t\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nint CdControlB(u_char com, u_char* param, u_char* result)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nint CdControlF(u_char com, u_char * param)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\t\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nint CdPosToInt(CdlLOC* p)\n{\n\treturn\n\t\t(75 * (60 * DECODE_BCD(p->minute) + DECODE_BCD(p->second))) + DECODE_BCD(p->sector) - 150;\n}\n\nint CdRead(int sectors, u_long* buf, int mode)\n{\n\tif (comQueueIndex == COMMAND_QUEUE_SIZE)\n\t\tcomQueueIndex = 0;\n\n\tcomStart[comQueueIndex].mode = CdlReadS;\n\tcomStart[comQueueIndex].p = (unsigned char*)buf;\n\tcomStart[comQueueIndex].processed = 0;\n\tcomStart[comQueueIndex].count = sectors;\n\tcomQueueCount++;\n\tcomQueueIndex++;\n\treturn 0;\n}\n\nint CdReadSync(int mode, u_char* result)\n{\n\tfor (int i = 0; i < comQueueCount; i++)\n\t{\n\t\tif (comQueue[i].processed == 0)\n\t\t{\n\t\t\tSector sector;\n\t\t\tfread(§or, sizeof(Sector), 1, openFile);\n\n\t\t\tmemcpy(comQueue[i].p, §or.data[0], 2048);\n\t\t\tcomQueue[i].p += 2048;\n\n\t\t\tif (--comQueue[i].count == 0)\n\t\t\t{\n\t\t\t\tcomQueue[i].processed = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CdSetDebug(int level)\n{\n\treturn 0;\n}\n\nint CdSync(int mode, u_char * result)\n{\n\treturn 0;\n}\n\nint CdInit(void)\n{\n\tmemset(&comQueue, 0, sizeof(comQueue));\n\tcurrentSector = 0;\n\topenFile = fopen(DISC_IMAGE_FILENAME, \"rb\");\n\n\tif (openFile == NULL)\n\t{\n\t\tprintf(\"Error: CdInit() Failed to open disc image file! %s\\n\", DISC_IMAGE_FILENAME);\n\t}\n\n\treturn 1;\n}\n\nint CdLastCom(void)\n{\n\treturn 0;\n}\n<commit_msg>fix bcd<commit_after>#include \"LIBCD.H\"\n\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#define DISC_IMAGE_FILENAME \"TOMB5.BIN\"\n\n#define DECODE_BCD(x) (((x) >> 4) * 10 + ((x) & 0xF))\n#define ENCODE_BCD(x) ((((x) \/ 10) << 4) | ((x) % 10))\n\nFILE* openFile = NULL;\n\ntypedef struct commandQueue\n{\n\tunsigned int mode;\n\tunsigned char* p;\n\tunsigned int processed;\n\tunsigned int count;\n};\n\n#define COMMAND_QUEUE_SIZE 256\n\ncommandQueue comQueue[COMMAND_QUEUE_SIZE];\ncommandQueue* comStart = &comQueue[0];\ncommandQueue* comEnd = &comQueue[COMMAND_QUEUE_SIZE-1];\nint comQueueIndex = 0;\nint comQueueCount = 0;\nint currentSector = 0;\nint sectorSize = 2352;\/\/TODO obtain properly from cue sheet\n\n#pragma pack(push, 1)\nstruct TOC\n{\n\tunsigned char tocEntryLength;\n\tunsigned char extEntryLength;\n\tunsigned int sectorPosition[2];\n\tunsigned int fileSize[2];\n\tunsigned char date[7];\n\tunsigned char flags;\n\tunsigned char fileUnitSize;\n\tunsigned char interleaveGapSize;\n\tunsigned short volSeqNum[2];\n\tunsigned char nameLength;\n};\n\nstruct Sector\n{\n\tunsigned char\tsync[12];\t\/\/\/ Sync pattern (usually 00 FF FF FF FF FF FF FF FF FF FF 00)\n\tunsigned char\taddr[3];\t\/\/\/ Sector address (see below for encoding details)\n\tunsigned char\tmode;\t\t\/\/\/ Mode (usually 2 for Mode 2 Form 1\/2 sectors)\n\tunsigned char\tsubHead[8];\t\/\/\/ Sub-header (00 00 08 00 00 00 08 00 for Form 1 data sectors)\n\tunsigned char\tdata[2048];\t\/\/\/ Data (form 1)\n\tunsigned char\tedc[4];\t\t\/\/\/ Error-detection code (CRC32 of data area)\n\tunsigned char\tecc[276];\t\/\/\/ Error-correction code (uses Reed-Solomon ECC algorithm)\n};\n#pragma pack(pop)\n\nCdlFILE* CdSearchFile(CdlFILE* fp, char* name)\n{\n\tmemset(fp, 0, sizeof(CdlFILE));\n\n\tif (name[0] == '\\\\')\n\t{\n\t\tname++;\n\t}\n\n\tif (openFile != NULL)\n\t{\n\t\tfseek(openFile, 22 * sectorSize, SEEK_SET);\n\n\t\tint tocLocalOffset = 0;\n\t\tSector sector;\n\t\tfread(§or, sizeof(Sector), 1, openFile);\n\t\tTOC* toc = (TOC*)§or.data[0];\n\t\twhile (toc->tocEntryLength != 0)\n\t\t{\n\t\t\tif (strcmp((char*)§or.data[tocLocalOffset + sizeof(TOC)], name) == 0)\n\t\t\t{\n\t\t\t\tmemcpy(&fp->name[0], (char*)§or.data[tocLocalOffset + sizeof(TOC)], strlen(name));\n\t\t\t\tfp->size = toc->fileSize[0];\n\t\t\t\tfseek(openFile, toc->sectorPosition[0] * sectorSize, SEEK_SET);\n\t\t\t\tfread(§or, sizeof(Sector), 1, openFile);\n\t\t\t\tfp->pos.minute = sector.addr[0];\n\t\t\t\tfp->pos.second = sector.addr[1];\n\t\t\t\tfp->pos.sector = sector.addr[2];\n\n\n#if _DEBUG\n\t\t\t\tprintf(\"CDSearchFile() Found %s\\n\", name);\n#endif\n\t\t\t\treturn fp;\n\t\t\t}\n\t\t\ttocLocalOffset += toc->tocEntryLength;\n\t\t\ttoc = (TOC*)§or.data[tocLocalOffset];\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nint mfhi(int a, int b)\n{\n\tunsigned long long temp = (long long)((long long)(int)a * (long long)(int)b);\n\n\tint lo = temp & 0xffffffff;\n\tint hi = temp >> 32;\n\treturn ((temp >> 32) & 0xFFFFFFFF);\n}\n\nCdlLOC* CdIntToPos(int i, CdlLOC* p)\n{\n\ti += 150;\n\tp->sector = ENCODE_BCD(i % 75);\n\tint rem = i \/ 75;\n\tp->second = ENCODE_BCD(rem % 60);\n\tp->minute = ENCODE_BCD(rem \/ 60);\n\treturn p;\n}\n\nint CdControl(u_char com, u_char * param, u_char * result)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\t\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nint CdControlB(u_char com, u_char* param, u_char* result)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nint CdControlF(u_char com, u_char * param)\n{\n\tCdlFILE* cd = (CdlFILE*)param;\n\t\n\tswitch (com)\n\t{\n\tcase CdlSetloc:\n\t\tfseek(openFile, CdPosToInt(&cd->pos)*sectorSize, SEEK_SET);\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Uhandled command!\\n\");\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\nint CdPosToInt(CdlLOC* p)\n{\n\treturn\n\t\t(75 * (60 * DECODE_BCD(p->minute) + DECODE_BCD(p->second))) + DECODE_BCD(p->sector) - 150;\n}\n\nint CdRead(int sectors, u_long* buf, int mode)\n{\n\tif (comQueueIndex == COMMAND_QUEUE_SIZE)\n\t\tcomQueueIndex = 0;\n\n\tcomStart[comQueueIndex].mode = CdlReadS;\n\tcomStart[comQueueIndex].p = (unsigned char*)buf;\n\tcomStart[comQueueIndex].processed = 0;\n\tcomStart[comQueueIndex].count = sectors;\n\tcomQueueCount++;\n\tcomQueueIndex++;\n\treturn 0;\n}\n\nint CdReadSync(int mode, u_char* result)\n{\n\tfor (int i = 0; i < comQueueCount; i++)\n\t{\n\t\tif (comQueue[i].processed == 0)\n\t\t{\n\t\t\tSector sector;\n\t\t\tfread(§or, sizeof(Sector), 1, openFile);\n\n\t\t\tmemcpy(comQueue[i].p, §or.data[0], 2048);\n\t\t\tcomQueue[i].p += 2048;\n\n\t\t\tif (--comQueue[i].count == 0)\n\t\t\t{\n\t\t\t\tcomQueue[i].processed = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CdSetDebug(int level)\n{\n\treturn 0;\n}\n\nint CdSync(int mode, u_char * result)\n{\n\treturn 0;\n}\n\nint CdInit(void)\n{\n\tmemset(&comQueue, 0, sizeof(comQueue));\n\tcurrentSector = 0;\n\topenFile = fopen(DISC_IMAGE_FILENAME, \"rb\");\n\n\tif (openFile == NULL)\n\t{\n\t\tprintf(\"Error: CdInit() Failed to open disc image file! %s\\n\", DISC_IMAGE_FILENAME);\n\t}\n\n\treturn 1;\n}\n\nint CdLastCom(void)\n{\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_STORAGE_PATH_HPP\n#define OUZEL_STORAGE_PATH_HPP\n\n#include <cstdint>\n#include <stdexcept>\n#include <string>\n\n#if defined(_WIN32)\n# pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma push_macro(\"NOMINMAX\")\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# ifndef NOMINMAX\n# define NOMINMAX\n# endif\n# include <Windows.h>\n# pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma pop_macro(\"NOMINMAX\")\n#elif defined(__unix__) || defined(__APPLE__)\n# include <sys\/stat.h>\n#endif\n\nnamespace ouzel\n{\n namespace storage\n {\n class Path final\n {\n public:\n#if defined(_WIN32)\n static constexpr char directorySeparator = '\\\\';\n using String = std::wstring;\n#elif defined(__unix__) || defined(__APPLE__)\n static constexpr char directorySeparator = '\/';\n using String = std::string;\n#endif\n\n Path() = default;\n Path(const std::string& p):\n#if defined(_WIN32)\n path(convertToNative(toWchar(p)))\n#elif defined(__unix__) || defined(__APPLE__)\n path(p)\n#endif\n {\n \/\/ TODO: normalize\n }\n\n Path(const std::wstring& p):\n#if defined(_WIN32)\n path(convertToNative(p))\n#elif defined(__unix__) || defined(__APPLE__)\n path(toUtf8(p))\n#endif\n {\n \/\/ TODO: normalize\n }\n\n operator std::string() const\n {\n#if defined(_WIN32)\n return toUtf8(convertToUniversal(path));\n#elif defined(__unix__) || defined(__APPLE__)\n return path;\n#endif\n }\n\n Path getExtensionPart() const\n {\n const size_t pos = path.find_last_of('.');\n\n if (pos != std::string::npos)\n return path.substr(pos + 1);\n\n return String();\n }\n\n Path getFilenamePart() const\n {\n const size_t pos = path.find_last_of(directorySeparator);\n\n if (pos != String::npos)\n return path.substr(pos + 1);\n else\n return path;\n }\n\n Path getDirectoryPart() const\n {\n const size_t pos = path.find_last_of(directorySeparator);\n\n if (pos != String::npos)\n return path.substr(0, pos);\n\n return String();\n }\n\n bool isDirectory() const\n {\n#if defined(_WIN32)\n const DWORD attributes = GetFileAttributesW(path.c_str());\n if (attributes == INVALID_FILE_ATTRIBUTES)\n return false;\n\n return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;\n#elif defined(__unix__) || defined(__APPLE__)\n struct stat buf;\n if (stat(path.c_str(), &buf) == -1)\n return false;\n\n return (buf.st_mode & S_IFMT) == S_IFDIR;\n#endif\n }\n\n bool isFile() const\n {\n#if defined(_WIN32)\n const DWORD attributes = GetFileAttributesW(path.c_str());\n if (attributes == INVALID_FILE_ATTRIBUTES)\n return false;\n\n return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;\n#elif defined(__unix__) || defined(__APPLE__)\n struct stat buf;\n if (stat(path.c_str(), &buf) == -1)\n return false;\n\n return (buf.st_mode & S_IFMT) == S_IFREG;\n#endif\n }\n\n bool isAbsolute() const noexcept\n {\n#if defined(_WIN32)\n return path.size() >= 2 &&\n ((path[0] >= L'a' && path[0] <= L'z') || (path[0] >= L'A' && path[0] <= L'Z')) &&\n path[1] == L':';\n#elif defined(__unix__) || defined(__APPLE__)\n return path.size() >= 1 && path[0] == '\/';\n#endif\n }\n\n private:\n static std::string toUtf8(const std::wstring& p)\n {\n\t\t\t\tstd::string s;\n\n\t\t\t\tfor (wchar_t w : p)\n\t\t\t\t{\n\t\t\t\t\tif (w <= 0x7F)\n\t\t\t\t\t\ts.push_back(static_cast<char>(w));\n\t\t\t\t\telse if (w <= 0x7FF)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.push_back(static_cast<char>(0xC0 | ((w >> 6) & 0x1F)));\n\t\t\t\t\t\ts.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n\t\t\t\t\t}\n\t\t\t\t\telse if (w <= 0xFFFF)\n {\n s.push_back(static_cast<char>(0xE0 | ((w >> 12) & 0x0F)));\n s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n }\n#if WCHAR_MAX > 0xFFFF\n else\n {\n s.push_back(static_cast<char>(0xF0 | ((w >> 18) & 0x07)));\n s.push_back(static_cast<char>(0x80 | ((w >> 12) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n }\n#endif\n\t\t\t\t}\n\n return s;\n }\n\n static std::wstring toWchar(const std::string& p)\n {\n std::wstring s;\n \n\t\t\t\tfor (auto i = p.begin(); i != p.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tchar32_t cp = *i & 0xFF;\n\n\t\t\t\t\tif (cp <= 0x7F) \/\/ length = 1\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ do nothing\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 5) == 0x6) \/\/ length = 2\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 6) & 0x7FF) + (*i & 0x3F);\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 4) == 0xE) \/\/ length = 3\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 12) & 0xFFFF) + (((*i & 0xFF) << 6) & 0x0FFF);\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += *i & 0x3F;\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 3) == 0x1E) \/\/ length = 4\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 18) & 0x1FFFFF) + (((*i & 0xFF) << 12) & 0x3FFFF);\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += ((*i & 0xFF) << 6) & 0x0FFF;\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += (*i) & 0x3F;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (cp > WCHAR_MAX)\n\t\t\t\t\t\tthrow std::runtime_error(\"Unsupported UTF-8 character\");\n\n\t\t\t\t\ts.push_back(static_cast<wchar_t>(cp));\n\t\t\t\t}\n\n return s;\n }\n\n#if defined(_WIN32)\n static std::wstring convertToNative(const std::wstring& p)\n {\n std::wstring result = p;\n\n for (auto& c : result)\n if (c == L'\/') c = L'\\\\';\n\n return result;\n }\n\n static std::wstring convertToUniversal(const std::wstring& p)\n {\n std::wstring result = p;\n\n for (auto& c : result)\n if (c == L'\\\\') c = L'\/';\n\n return result;\n }\n#endif\n\n String path;\n };\n } \/\/ namespace storage\n} \/\/ namespace ouzel\n\n#endif\n<commit_msg>Add native getter to Path<commit_after>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_STORAGE_PATH_HPP\n#define OUZEL_STORAGE_PATH_HPP\n\n#include <cstdint>\n#include <stdexcept>\n#include <string>\n\n#if defined(_WIN32)\n# pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma push_macro(\"NOMINMAX\")\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# ifndef NOMINMAX\n# define NOMINMAX\n# endif\n# include <Windows.h>\n# pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma pop_macro(\"NOMINMAX\")\n#elif defined(__unix__) || defined(__APPLE__)\n# include <sys\/stat.h>\n#endif\n\nnamespace ouzel\n{\n namespace storage\n {\n class Path final\n {\n public:\n#if defined(_WIN32)\n static constexpr char directorySeparator = '\\\\';\n using String = std::wstring;\n#elif defined(__unix__) || defined(__APPLE__)\n static constexpr char directorySeparator = '\/';\n using String = std::string;\n#endif\n\n Path() = default;\n Path(const std::string& p):\n#if defined(_WIN32)\n path(convertToNative(toWchar(p)))\n#elif defined(__unix__) || defined(__APPLE__)\n path(p)\n#endif\n {\n \/\/ TODO: normalize\n }\n\n Path(const std::wstring& p):\n#if defined(_WIN32)\n path(convertToNative(p))\n#elif defined(__unix__) || defined(__APPLE__)\n path(toUtf8(p))\n#endif\n {\n \/\/ TODO: normalize\n }\n\n operator std::string() const\n {\n#if defined(_WIN32)\n return toUtf8(convertToUniversal(path));\n#elif defined(__unix__) || defined(__APPLE__)\n return path;\n#endif\n }\n\n const String& getNative() const noexcept\n {\n return path;\n }\n\n Path getExtensionPart() const\n {\n const size_t pos = path.find_last_of('.');\n\n if (pos != std::string::npos)\n return path.substr(pos + 1);\n\n return String();\n }\n\n Path getFilenamePart() const\n {\n const size_t pos = path.find_last_of(directorySeparator);\n\n if (pos != String::npos)\n return path.substr(pos + 1);\n else\n return path;\n }\n\n Path getDirectoryPart() const\n {\n const size_t pos = path.find_last_of(directorySeparator);\n\n if (pos != String::npos)\n return path.substr(0, pos);\n\n return String();\n }\n\n bool isDirectory() const\n {\n#if defined(_WIN32)\n const DWORD attributes = GetFileAttributesW(path.c_str());\n if (attributes == INVALID_FILE_ATTRIBUTES)\n return false;\n\n return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;\n#elif defined(__unix__) || defined(__APPLE__)\n struct stat buf;\n if (stat(path.c_str(), &buf) == -1)\n return false;\n\n return (buf.st_mode & S_IFMT) == S_IFDIR;\n#endif\n }\n\n bool isFile() const\n {\n#if defined(_WIN32)\n const DWORD attributes = GetFileAttributesW(path.c_str());\n if (attributes == INVALID_FILE_ATTRIBUTES)\n return false;\n\n return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;\n#elif defined(__unix__) || defined(__APPLE__)\n struct stat buf;\n if (stat(path.c_str(), &buf) == -1)\n return false;\n\n return (buf.st_mode & S_IFMT) == S_IFREG;\n#endif\n }\n\n bool isAbsolute() const noexcept\n {\n#if defined(_WIN32)\n return path.size() >= 2 &&\n ((path[0] >= L'a' && path[0] <= L'z') || (path[0] >= L'A' && path[0] <= L'Z')) &&\n path[1] == L':';\n#elif defined(__unix__) || defined(__APPLE__)\n return path.size() >= 1 && path[0] == '\/';\n#endif\n }\n\n private:\n static std::string toUtf8(const std::wstring& p)\n {\n\t\t\t\tstd::string s;\n\n\t\t\t\tfor (wchar_t w : p)\n\t\t\t\t{\n\t\t\t\t\tif (w <= 0x7F)\n\t\t\t\t\t\ts.push_back(static_cast<char>(w));\n\t\t\t\t\telse if (w <= 0x7FF)\n\t\t\t\t\t{\n\t\t\t\t\t\ts.push_back(static_cast<char>(0xC0 | ((w >> 6) & 0x1F)));\n\t\t\t\t\t\ts.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n\t\t\t\t\t}\n\t\t\t\t\telse if (w <= 0xFFFF)\n {\n s.push_back(static_cast<char>(0xE0 | ((w >> 12) & 0x0F)));\n s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n }\n#if WCHAR_MAX > 0xFFFF\n else\n {\n s.push_back(static_cast<char>(0xF0 | ((w >> 18) & 0x07)));\n s.push_back(static_cast<char>(0x80 | ((w >> 12) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));\n s.push_back(static_cast<char>(0x80 | (w & 0x3F)));\n }\n#endif\n\t\t\t\t}\n\n return s;\n }\n\n static std::wstring toWchar(const std::string& p)\n {\n std::wstring s;\n \n\t\t\t\tfor (auto i = p.begin(); i != p.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tchar32_t cp = *i & 0xFF;\n\n\t\t\t\t\tif (cp <= 0x7F) \/\/ length = 1\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ do nothing\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 5) == 0x6) \/\/ length = 2\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 6) & 0x7FF) + (*i & 0x3F);\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 4) == 0xE) \/\/ length = 3\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 12) & 0xFFFF) + (((*i & 0xFF) << 6) & 0x0FFF);\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += *i & 0x3F;\n\t\t\t\t\t}\n\t\t\t\t\telse if ((cp >> 3) == 0x1E) \/\/ length = 4\n\t\t\t\t\t{\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp = ((cp << 18) & 0x1FFFFF) + (((*i & 0xFF) << 12) & 0x3FFFF);\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += ((*i & 0xFF) << 6) & 0x0FFF;\n\t\t\t\t\t\tif (++i == p.end())\n\t\t\t\t\t\t\tthrow std::runtime_error(\"Invalid UTF-8 string\");\n\t\t\t\t\t\tcp += (*i) & 0x3F;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (cp > WCHAR_MAX)\n\t\t\t\t\t\tthrow std::runtime_error(\"Unsupported UTF-8 character\");\n\n\t\t\t\t\ts.push_back(static_cast<wchar_t>(cp));\n\t\t\t\t}\n\n return s;\n }\n\n#if defined(_WIN32)\n static std::wstring convertToNative(const std::wstring& p)\n {\n std::wstring result = p;\n\n for (auto& c : result)\n if (c == L'\/') c = L'\\\\';\n\n return result;\n }\n\n static std::wstring convertToUniversal(const std::wstring& p)\n {\n std::wstring result = p;\n\n for (auto& c : result)\n if (c == L'\\\\') c = L'\/';\n\n return result;\n }\n#endif\n\n String path;\n };\n } \/\/ namespace storage\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/util\/stdtypes.h>\n#include <eventql\/util\/logging.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <eventql\/util\/io\/mmappedfile.h>\n#include <eventql\/util\/protobuf\/msg.h>\n#include <eventql\/util\/wallclock.h>\n#include <eventql\/util\/application.h>\n#include <eventql\/db\/compaction_worker.h>\n#include <eventql\/db\/partition_writer.h>\n#include <eventql\/util\/protobuf\/MessageDecoder.h>\n#include <eventql\/io\/cstable\/RecordShredder.h>\n#include <eventql\/io\/cstable\/cstable_writer.h>\n\n#include \"eventql\/eventql.h\"\n\nnamespace eventql {\n\nCompactionWorker::CompactionWorker(\n PartitionMap* pmap,\n size_t nthreads) :\n pmap_(pmap),\n nthreads_(nthreads),\n queue_([] (\n const Pair<uint64_t, RefPtr<Partition>>& a,\n const Pair<uint64_t, RefPtr<Partition>>& b) {\n return a.first < b.first;\n }),\n running_(false) {\n pmap->subscribeToPartitionChanges([this] (\n RefPtr<eventql::PartitionChangeNotification> change) {\n enqueuePartition(change->partition);\n });\n\n start();\n}\n\nCompactionWorker::~CompactionWorker() {\n stop();\n}\n\nvoid CompactionWorker::enqueuePartition(\n RefPtr<Partition> partition,\n bool immediate \/* = false *\/) {\n if (immediate) {\n startImmediateCompaction(partition);\n } else {\n std::unique_lock<std::mutex> lk(mutex_);\n enqueuePartitionWithLock(partition);\n }\n}\n\nvoid CompactionWorker::startImmediateCompaction(RefPtr<Partition> partition) {\n auto uuid = partition->uuid();\n\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (immediate_set_.count(uuid) > 0) {\n return;\n }\n\n if (immediate_set_.size() > kImmediateCompactionMaxThreads) {\n enqueuePartitionWithLock(partition);\n return;\n }\n\n immediate_set_.emplace(uuid);\n }\n\n auto thread = std::thread([this, partition, uuid] {\n Application::setCurrentThreadName(\"evqld-compaction-immediate\");\n compactPartition(partition);\n\n std::unique_lock<std::mutex> lk(mutex_);\n immediate_set_.erase(uuid);\n });\n\n thread.detach();\n}\n\nvoid CompactionWorker::enqueuePartitionWithLock(\n RefPtr<Partition> partition) {\n auto interval = partition->getTable()->commitInterval();\n\n auto uuid = partition->uuid();\n if (waitset_.count(uuid) > 0) {\n return;\n }\n\n queue_.emplace(\n WallClock::unixMicros() + interval.microseconds(),\n partition);\n\n waitset_.emplace(uuid);\n cv_.notify_all();\n evqld_stats()->compaction_queue_length.set(queue_.size());\n}\n\nvoid CompactionWorker::start() {\n running_ = true;\n\n for (int i = 0; i < nthreads_; ++i) {\n threads_.emplace_back(std::bind(&CompactionWorker::work, this));\n }\n}\n\nvoid CompactionWorker::stop() {\n if (!running_) {\n return;\n }\n\n running_ = false;\n cv_.notify_all();\n\n for (auto& t : threads_) {\n t.join();\n }\n}\n\nvoid CompactionWorker::work() {\n Application::setCurrentThreadName(\"evqld-compaction\");\n\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (running_) {\n if (queue_.size() == 0) {\n cv_.wait(lk);\n }\n\n if (queue_.size() == 0) {\n continue;\n }\n\n auto now = WallClock::unixMicros();\n if (now < queue_.begin()->first) {\n cv_.wait_for(\n lk,\n std::chrono::microseconds(queue_.begin()->first - now));\n\n continue;\n }\n\n auto partition = queue_.begin()->second;\n queue_.erase(queue_.begin());\n\n bool success = true;\n {\n lk.unlock();\n success = compactPartition(partition);\n lk.lock();\n }\n\n if (success) {\n waitset_.erase(partition->uuid());\n\n if (partition->getWriter()->needsCompaction()) {\n enqueuePartitionWithLock(partition);\n }\n } else {\n auto delay = 30 * kMicrosPerSecond; \/\/ FIXPAUL increasing delay..\n queue_.emplace(now + delay, partition);\n }\n\n evqld_stats()->compaction_queue_length.set(queue_.size());\n }\n}\n\nbool CompactionWorker::compactPartition(RefPtr<Partition> partition) try {\n auto writer = partition->getWriter();\n if (writer->compact()) {\n auto change = mkRef(new PartitionChangeNotification());\n change->partition = partition;\n pmap_->publishPartitionChange(change);\n }\n\n return true;\n} catch (const StandardException& e) {\n auto snap = partition->getSnapshot();\n\n logCritical(\n \"tsdb\",\n e,\n \"CompactionWorker error for partition $0\/$1\/$2\",\n snap->state.tsdb_namespace(),\n snap->state.table_key(),\n snap->key.toString());\n\n return false;\n}\n\n} \/\/ namespace eventql\n<commit_msg>add warning<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/util\/stdtypes.h>\n#include <eventql\/util\/logging.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <eventql\/util\/io\/mmappedfile.h>\n#include <eventql\/util\/protobuf\/msg.h>\n#include <eventql\/util\/wallclock.h>\n#include <eventql\/util\/application.h>\n#include <eventql\/db\/compaction_worker.h>\n#include <eventql\/db\/partition_writer.h>\n#include <eventql\/util\/protobuf\/MessageDecoder.h>\n#include <eventql\/io\/cstable\/RecordShredder.h>\n#include <eventql\/io\/cstable\/cstable_writer.h>\n\n#include \"eventql\/eventql.h\"\n\nnamespace eventql {\n\nCompactionWorker::CompactionWorker(\n PartitionMap* pmap,\n size_t nthreads) :\n pmap_(pmap),\n nthreads_(nthreads),\n queue_([] (\n const Pair<uint64_t, RefPtr<Partition>>& a,\n const Pair<uint64_t, RefPtr<Partition>>& b) {\n return a.first < b.first;\n }),\n running_(false) {\n pmap->subscribeToPartitionChanges([this] (\n RefPtr<eventql::PartitionChangeNotification> change) {\n enqueuePartition(change->partition);\n });\n\n start();\n}\n\nCompactionWorker::~CompactionWorker() {\n stop();\n}\n\nvoid CompactionWorker::enqueuePartition(\n RefPtr<Partition> partition,\n bool immediate \/* = false *\/) {\n if (immediate) {\n startImmediateCompaction(partition);\n } else {\n std::unique_lock<std::mutex> lk(mutex_);\n enqueuePartitionWithLock(partition);\n }\n}\n\nvoid CompactionWorker::startImmediateCompaction(RefPtr<Partition> partition) {\n auto uuid = partition->uuid();\n\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (immediate_set_.count(uuid) > 0) {\n return;\n }\n\n if (immediate_set_.size() > kImmediateCompactionMaxThreads) {\n logWarning(\n \"evqld\",\n \"maximum number of immediate compaction threads reached -- \"\n \"kImmediateCompactionMaxThreads or num_compaction_threads too low?\");\n\n enqueuePartitionWithLock(partition);\n return;\n }\n\n immediate_set_.emplace(uuid);\n }\n\n auto thread = std::thread([this, partition, uuid] {\n Application::setCurrentThreadName(\"evqld-compaction-immediate\");\n compactPartition(partition);\n\n std::unique_lock<std::mutex> lk(mutex_);\n immediate_set_.erase(uuid);\n });\n\n thread.detach();\n}\n\nvoid CompactionWorker::enqueuePartitionWithLock(\n RefPtr<Partition> partition) {\n auto interval = partition->getTable()->commitInterval();\n\n auto uuid = partition->uuid();\n if (waitset_.count(uuid) > 0) {\n return;\n }\n\n queue_.emplace(\n WallClock::unixMicros() + interval.microseconds(),\n partition);\n\n waitset_.emplace(uuid);\n cv_.notify_all();\n evqld_stats()->compaction_queue_length.set(queue_.size());\n}\n\nvoid CompactionWorker::start() {\n running_ = true;\n\n for (int i = 0; i < nthreads_; ++i) {\n threads_.emplace_back(std::bind(&CompactionWorker::work, this));\n }\n}\n\nvoid CompactionWorker::stop() {\n if (!running_) {\n return;\n }\n\n running_ = false;\n cv_.notify_all();\n\n for (auto& t : threads_) {\n t.join();\n }\n}\n\nvoid CompactionWorker::work() {\n Application::setCurrentThreadName(\"evqld-compaction\");\n\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (running_) {\n if (queue_.size() == 0) {\n cv_.wait(lk);\n }\n\n if (queue_.size() == 0) {\n continue;\n }\n\n auto now = WallClock::unixMicros();\n if (now < queue_.begin()->first) {\n cv_.wait_for(\n lk,\n std::chrono::microseconds(queue_.begin()->first - now));\n\n continue;\n }\n\n auto partition = queue_.begin()->second;\n queue_.erase(queue_.begin());\n\n bool success = true;\n {\n lk.unlock();\n success = compactPartition(partition);\n lk.lock();\n }\n\n if (success) {\n waitset_.erase(partition->uuid());\n\n if (partition->getWriter()->needsCompaction()) {\n enqueuePartitionWithLock(partition);\n }\n } else {\n auto delay = 30 * kMicrosPerSecond; \/\/ FIXPAUL increasing delay..\n queue_.emplace(now + delay, partition);\n }\n\n evqld_stats()->compaction_queue_length.set(queue_.size());\n }\n}\n\nbool CompactionWorker::compactPartition(RefPtr<Partition> partition) try {\n auto writer = partition->getWriter();\n if (writer->compact()) {\n auto change = mkRef(new PartitionChangeNotification());\n change->partition = partition;\n pmap_->publishPartitionChange(change);\n }\n\n return true;\n} catch (const StandardException& e) {\n auto snap = partition->getSnapshot();\n\n logCritical(\n \"tsdb\",\n e,\n \"CompactionWorker error for partition $0\/$1\/$2\",\n snap->state.tsdb_namespace(),\n snap->state.table_key(),\n snap->key.toString());\n\n return false;\n}\n\n} \/\/ namespace eventql\n<|endoftext|>"} {"text":"<commit_before>\/**\n @file PlotStack.cc\n\n Source file of PlotStack, including the functions used for creating the histograms.\n\n @author Daniel Abercrombie <dabercro@mit.edu>\n*\/\n\n#include <algorithm>\n\n#include \"TFile.h\"\n#include \"TLegend.h\"\n#include \"TProfile.h\"\n\n#include \"HistHolder.h\"\n#include \"PlotStack.h\"\n\nClassImp(PlotStack)\n\n\/\/--------------------------------------------------------------------\n\n\/**\n The default constructor for PlotStack.\n It changes the value of PlotBase::fMakeRatio to be true by default.\n *\/\n\nPlotStack::PlotStack()\n{\n fMakeRatio = true;\n}\n\n\/\/--------------------------------------------------------------------\nPlotStack::~PlotStack()\n{ }\n\n\/\/--------------------------------------------------------------------\nvoid\nPlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t *XBins,\n TString XLabel, TString YLabel, Bool_t logY)\n{\n DisplayFunc(__func__);\n Message(eInfo, \"Making File : %s\", FileBase.Data());\n Message(eInfo, \"Plotting : %s\", fDefaultExpr.Data());\n Message(eInfo, \"Labeled : %s\", XLabel.Data());\n Message(eInfo, \"With cut : %s\", fDefaultCut.GetTitle());\n\n if (YLabel == \"\") {\n if (fEventsPer == 0)\n YLabel = \"Events\/Bin\";\n else if (fEventsPer < 1.0)\n YLabel.Form(\"Events\/%.2f\", fEventsPer);\n else\n YLabel.Form(\"Events\/%.1f\", fEventsPer);\n }\n\n SetLumiLabel(float(fLuminosity\/1000.0));\n ResetLegend();\n\n fRatioLines.clear();\n\n std::vector<TFile*> TemplateFiles;\n TFile *templateFile = NULL;\n\n Message(eDebug, \"Number of Templates: %i\", fTemplateEntries.size());\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp) {\n Message(eDebug, \"Getting template: %i\", iTemp);\n templateFile = TFile::Open(fTemplateFiles[iTemp]);\n TemplateFiles.push_back(templateFile);\n }\n\n SetIncludeErrorBars(true);\n std::vector<TH1D*> DataHists = GetHistList(NumXBins, XBins, kData);\n Message(eDebug, \"Number of Data Histograms: %i\", DataHists.size());\n SetIncludeErrorBars(false);\n std::vector<TH1D*> MCHists = GetHistList(NumXBins, XBins, kBackground);\n Message(eDebug, \"Number of MC Histograms: %i\", MCHists.size());\n std::vector<TH1D*> SignalHists;\n if (fSignalFileInfo.size() != 0)\n SignalHists = GetHistList(NumXBins, XBins, kSignal);\n Message(eDebug, \"Number of Signal Histograms: %i\", SignalHists.size());\n\n SetLegendFill(true);\n TH1D *DataHist = (TH1D*) DataHists[0]->Clone(\"DataHist\");\n Message(eDebug, \"Final Data Histogram created at %p\", DataHist);\n DataHist->Reset(\"M\");\n\n for (UInt_t iHist = 0; iHist < DataHists.size(); iHist++)\n DataHist->Add(DataHists[iHist]);\n\n Message(eInfo, \"Number of data events: %i, integral: %f\", (Int_t) DataHist->GetEntries(), DataHist->Integral(\"width\"));\n\n TString previousEntry = \"\";\n TH1D *tempMCHist = NULL;\n HistHolder *tempHistHolder = NULL;\n std::vector<HistHolder*> HistHolders;\n\n for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist) {\n\n Message(eDebug, \"About to process Histogram %i out of %i\", iHist, MCHists.size()); \n Message(eDebug, \"Entry is \\\"%s\\\". Previous entry is \\\"%s\\\"\",\n fMCFileInfo[iHist]->fEntry.Data(), previousEntry.Data());\n\n if (fMCFileInfo[iHist]->fEntry != previousEntry) {\n\n Message(eDebug, \"Creating a new histogram\");\n\n previousEntry = fMCFileInfo[iHist]->fEntry;\n TString tempName;\n tempName.Format(\"StackedHist_%d\",iHist);\n tempMCHist = (TH1D*) MCHists[iHist]->Clone(tempName);\n tempHistHolder = new HistHolder(tempMCHist, fMCFileInfo[iHist]->fEntry,\n fMCFileInfo[iHist]->fColorStyle,\n fMCFileInfo[iHist]->fTreeName,\n (fForceTop == fMCFileInfo[iHist]->fEntry));\n HistHolders.push_back(tempHistHolder);\n\n } else {\n\n tempMCHist->Add(MCHists[iHist]);\n Message(eDebug, \"Added to previous histogram.\");\n\n }\n\n Message(eDebug, \"Number of unique entries so far: %i\", HistHolders.size());\n\n }\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp) {\n\n for (UInt_t iHist = 0; iHist != HistHolders.size(); ++iHist) {\n\n if (fTemplateEntries[iTemp] == HistHolders[iHist]->fEntry) {\n\n Message(eInfo, \"Replacing histogram %s with a template\",\n fTemplateEntries[iTemp].Data());\n\n TH1D *templateHist = (TH1D*) TemplateFiles[iTemp]->Get(fTemplateHists[iTemp]);\n TH1D *toFormat = (TH1D*) templateHist->Rebin(NumXBins, \"\", XBins);\n toFormat->SetFillStyle(HistHolders[iHist]->fHist->GetFillStyle());\n toFormat->SetFillColor(HistHolders[iHist]->fHist->GetFillColor());\n toFormat->SetMarkerSize(HistHolders[iHist]->fHist->GetMarkerSize());\n HistHolders[iHist]->fHist = toFormat;\n\n }\n }\n }\n\n if (fDumpRootName != \"\") {\n\n Message(eInfo, \"Dumping histograms into %s\", fDumpRootName.Data());\n\n TH1D* tempHist;\n TFile* dumpFile = new TFile(fDumpRootName,\"RECREATE\");\n\n \/\/ Background Histograms\n\n for (UInt_t iHist = 0; iHist != HistHolders.size(); ++iHist) {\n\n tempHist = (TH1D*) HistHolders[iHist]->fHist->Clone();\n\n Message(eInfo, \"%s : %f\", HistHolders[iHist]->fEntry.Data(),\n tempHist->Integral(0, NumXBins + 1, \"width\"));\n\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-%s\",\n fDefaultExpr.Data(),\n HistHolders[iHist]->fTree.Data()\n )\n );\n }\n\n \/\/ Signal Histograms\n\n for (UInt_t iHist = 0; iHist != SignalHists.size(); ++iHist) {\n\n tempHist = (TH1D*) SignalHists[iHist]->Clone();\n\n Message(eInfo, \"%s : %f\", fSignalFileInfo[iHist]->fTreeName.Data(),\n tempHist->Integral(0, NumXBins + 1, \"width\"));\n\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-%s\",\n fDefaultExpr.Data(),\n fSignalFileInfo[iHist]->fTreeName.Data()\n )\n );\n\n }\n\n \/\/ Data Histogram\n\n tempHist = (TH1D*) DataHist->Clone();\n Message(eInfo, \"Data : %f\", tempHist->Integral(0, NumXBins + 1, \"width\"));\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-data\", fDefaultExpr.Data()));\n dumpFile->Close();\n\n }\n\n if (fSortBackground) {\n std::sort(HistHolders.begin(), HistHolders.end(), SortHistHolders);\n Message(eInfo, \"Backgrounds sorted\");\n }\n\n Message(eDebug, \"Number of unique histograms: %i\", HistHolders.size());\n\n std::vector<TH1D*> AllHists;\n for (UInt_t iLarger = 0; iLarger != HistHolders.size(); ++iLarger) {\n\n Message(eDebug, \"Stacking up histogram: %i\", iLarger);\n Message(eInfo, \"Entry %s has total integral %f\",\n HistHolders[iLarger]->fEntry.Data(),\n HistHolders[iLarger]->fHist->Integral(\"width\"));\n\n for (UInt_t iSmaller = iLarger + 1; iSmaller != HistHolders.size(); ++iSmaller) {\n Message(eDebug, \"Adding %i to %i\", iSmaller, iLarger);\n HistHolders[iLarger]->fHist->Add(HistHolders[iSmaller]->fHist);\n }\n\n Message(eDebug, \"Histogram %i has integral %f\", iLarger, HistHolders[iLarger]->fHist->Integral());\n\n if (HistHolders[iLarger]->fHist->Integral() > 0 || iLarger == 0) {\n\n if (iLarger != 0)\n SetZeroError(HistHolders[iLarger]->fHist);\n AllHists.push_back(HistHolders[iLarger]->fHist);\n\n if ((HistHolders[iLarger]->fHist->Integral() > fMinLegendFrac * HistHolders[0]->fHist->Integral()) || \/\/ If more than the fraction set\n (iLarger == HistHolders.size() - 1)) \/\/ or the last histogram\n AddLegendEntry(HistHolders[iLarger]->fEntry, 1, fStackLineWidth, 1); \/\/ Add legend properly\n else if ((HistHolders[iLarger]->fHist->Integral() > fIgnoreInLinear * HistHolders[0]->fHist->Integral()) ||\n logY) { \/\/ Otherwise if not ignored\n if (HistHolders[iLarger + 1]->fHist->Integral() > 0) { \/\/ Check if the next histogram contribute\n if (fOthersColor != 0)\n HistHolders[iLarger]->fHist->SetFillColor(fOthersColor);\n AddLegendEntry(\"Others\", 1, fStackLineWidth, 1); \/\/ If so, make others legend\n }\n else \/\/ If not,\n AddLegendEntry(HistHolders[iLarger]->fEntry, HistHolders[iLarger]->fColor, 1, 1); \/\/ Make normal legend entry\n break; \/\/ Stop adding histograms\n } else {\n AllHists.pop_back();\n break;\n }\n }\n\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n\n }\n\n Message(eInfo, \"Total background contribution: %f\", HistHolders[0]->fHist->Integral(\"width\"));\n\n AddLegendEntry(\"Data\", 1);\n SetDataIndex(int(AllHists.size()));\n AllHists.push_back(DataHist);\n\n for (UInt_t iHist = 0; iHist != SignalHists.size(); ++iHist) {\n Message(eDebug, \"Processing Signal Hist %i of %i\", iHist, SignalHists.size());\n\n if (fAddSignal) { \/\/ Do some clever things if we're adding signal to backgrounds\n\n if (fMakeRatio) \/\/ All possible signals show up on the ratio pad\n AddRatioLine(int(AllHists.size()));\n if (AllHists.size() > 1)\n SignalHists[iHist]->Add(AllHists[0]); \/\/ Add the background to the signals\n\n }\n\n AllHists.push_back(SignalHists[iHist]);\n AddLegendEntry(fSignalFileInfo[iHist]->fEntry, 1, 2, fSignalFileInfo[iHist]->fColorStyle);\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n }\n\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n\n if (fMakeRatio)\n AddRatioLine(fDataIndex);\n\n SetRatioIndex(0);\n\n BaseCanvas(AddOutDir(FileBase), AllHists, XLabel, YLabel, logY);\n\n for (UInt_t iHist = 0; iHist != AllHists.size(); ++iHist)\n delete AllHists[iHist];\n for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist)\n delete MCHists[iHist];\n for (UInt_t iHist = 0; iHist != DataHists.size(); ++iHist)\n delete DataHists[iHist];\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp)\n TemplateFiles[iTemp]->Close();\n\n CloseFiles();\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nPlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t MinX, Double_t MaxX,\n TString XLabel, TString YLabel, Bool_t logY)\n{\n Double_t XBins[NumXBins+1];\n ConvertToArray(NumXBins,MinX,MaxX,XBins);\n MakeCanvas(FileBase,NumXBins,XBins,XLabel,YLabel,logY);\n}\n\n\/\/--------------------------------------------------------------------\nPlotStack*\nPlotStack::Copy()\n{\n PlotStack *newPlotter = new PlotStack();\n *newPlotter = *this;\n return newPlotter;\n}\n<commit_msg>Slightly nicer formatting.<commit_after>\/**\n @file PlotStack.cc\n\n Source file of PlotStack, including the functions used for creating the histograms.\n\n @author Daniel Abercrombie <dabercro@mit.edu>\n*\/\n\n#include <algorithm>\n\n#include \"TFile.h\"\n#include \"TLegend.h\"\n#include \"TProfile.h\"\n\n#include \"HistHolder.h\"\n#include \"PlotStack.h\"\n\nClassImp(PlotStack)\n\n\/\/--------------------------------------------------------------------\n\n\/**\n The default constructor for PlotStack.\n It changes the value of PlotBase::fMakeRatio to be true by default.\n *\/\n\nPlotStack::PlotStack()\n{\n fMakeRatio = true;\n}\n\n\/\/--------------------------------------------------------------------\nPlotStack::~PlotStack()\n{ }\n\n\/\/--------------------------------------------------------------------\nvoid\nPlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t *XBins,\n TString XLabel, TString YLabel, Bool_t logY)\n{\n DisplayFunc(__func__);\n Message(eInfo, \"Making File : %s\", FileBase.Data());\n Message(eInfo, \"Plotting : %s\", fDefaultExpr.Data());\n Message(eInfo, \"Labeled : %s\", XLabel.Data());\n Message(eInfo, \"With cut : %s\", fDefaultCut.GetTitle());\n\n if (YLabel == \"\") {\n if (fEventsPer == 0)\n YLabel = \"Events\/Bin\";\n else if (fEventsPer >= 10)\n YLabel.Form(\"Events\/%.0f\", fEventsPer);\n else if (fEventsPer < 1.0)\n YLabel.Form(\"Events\/%.2f\", fEventsPer);\n else\n YLabel.Form(\"Events\/%.1f\", fEventsPer);\n }\n\n SetLumiLabel(float(fLuminosity\/1000.0));\n ResetLegend();\n\n fRatioLines.clear();\n\n std::vector<TFile*> TemplateFiles;\n TFile *templateFile = NULL;\n\n Message(eDebug, \"Number of Templates: %i\", fTemplateEntries.size());\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp) {\n Message(eDebug, \"Getting template: %i\", iTemp);\n templateFile = TFile::Open(fTemplateFiles[iTemp]);\n TemplateFiles.push_back(templateFile);\n }\n\n SetIncludeErrorBars(true);\n std::vector<TH1D*> DataHists = GetHistList(NumXBins, XBins, kData);\n Message(eDebug, \"Number of Data Histograms: %i\", DataHists.size());\n SetIncludeErrorBars(false);\n std::vector<TH1D*> MCHists = GetHistList(NumXBins, XBins, kBackground);\n Message(eDebug, \"Number of MC Histograms: %i\", MCHists.size());\n std::vector<TH1D*> SignalHists;\n if (fSignalFileInfo.size() != 0)\n SignalHists = GetHistList(NumXBins, XBins, kSignal);\n Message(eDebug, \"Number of Signal Histograms: %i\", SignalHists.size());\n\n SetLegendFill(true);\n TH1D *DataHist = (TH1D*) DataHists[0]->Clone(\"DataHist\");\n Message(eDebug, \"Final Data Histogram created at %p\", DataHist);\n DataHist->Reset(\"M\");\n\n for (UInt_t iHist = 0; iHist < DataHists.size(); iHist++)\n DataHist->Add(DataHists[iHist]);\n\n Message(eInfo, \"Number of data events: %i, integral: %f\", (Int_t) DataHist->GetEntries(), DataHist->Integral(\"width\"));\n\n TString previousEntry = \"\";\n TH1D *tempMCHist = NULL;\n HistHolder *tempHistHolder = NULL;\n std::vector<HistHolder*> HistHolders;\n\n for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist) {\n\n Message(eDebug, \"About to process Histogram %i out of %i\", iHist, MCHists.size()); \n Message(eDebug, \"Entry is \\\"%s\\\". Previous entry is \\\"%s\\\"\",\n fMCFileInfo[iHist]->fEntry.Data(), previousEntry.Data());\n\n if (fMCFileInfo[iHist]->fEntry != previousEntry) {\n\n Message(eDebug, \"Creating a new histogram\");\n\n previousEntry = fMCFileInfo[iHist]->fEntry;\n TString tempName;\n tempName.Format(\"StackedHist_%d\",iHist);\n tempMCHist = (TH1D*) MCHists[iHist]->Clone(tempName);\n tempHistHolder = new HistHolder(tempMCHist, fMCFileInfo[iHist]->fEntry,\n fMCFileInfo[iHist]->fColorStyle,\n fMCFileInfo[iHist]->fTreeName,\n (fForceTop == fMCFileInfo[iHist]->fEntry));\n HistHolders.push_back(tempHistHolder);\n\n } else {\n\n tempMCHist->Add(MCHists[iHist]);\n Message(eDebug, \"Added to previous histogram.\");\n\n }\n\n Message(eDebug, \"Number of unique entries so far: %i\", HistHolders.size());\n\n }\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp) {\n\n for (UInt_t iHist = 0; iHist != HistHolders.size(); ++iHist) {\n\n if (fTemplateEntries[iTemp] == HistHolders[iHist]->fEntry) {\n\n Message(eInfo, \"Replacing histogram %s with a template\",\n fTemplateEntries[iTemp].Data());\n\n TH1D *templateHist = (TH1D*) TemplateFiles[iTemp]->Get(fTemplateHists[iTemp]);\n TH1D *toFormat = (TH1D*) templateHist->Rebin(NumXBins, \"\", XBins);\n toFormat->SetFillStyle(HistHolders[iHist]->fHist->GetFillStyle());\n toFormat->SetFillColor(HistHolders[iHist]->fHist->GetFillColor());\n toFormat->SetMarkerSize(HistHolders[iHist]->fHist->GetMarkerSize());\n HistHolders[iHist]->fHist = toFormat;\n\n }\n }\n }\n\n if (fDumpRootName != \"\") {\n\n Message(eInfo, \"Dumping histograms into %s\", fDumpRootName.Data());\n\n TH1D* tempHist;\n TFile* dumpFile = new TFile(fDumpRootName,\"RECREATE\");\n\n \/\/ Background Histograms\n\n for (UInt_t iHist = 0; iHist != HistHolders.size(); ++iHist) {\n\n tempHist = (TH1D*) HistHolders[iHist]->fHist->Clone();\n\n Message(eInfo, \"%s : %f\", HistHolders[iHist]->fEntry.Data(),\n tempHist->Integral(0, NumXBins + 1, \"width\"));\n\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-%s\",\n fDefaultExpr.Data(),\n HistHolders[iHist]->fTree.Data()\n )\n );\n }\n\n \/\/ Signal Histograms\n\n for (UInt_t iHist = 0; iHist != SignalHists.size(); ++iHist) {\n\n tempHist = (TH1D*) SignalHists[iHist]->Clone();\n\n Message(eInfo, \"%s : %f\", fSignalFileInfo[iHist]->fTreeName.Data(),\n tempHist->Integral(0, NumXBins + 1, \"width\"));\n\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-%s\",\n fDefaultExpr.Data(),\n fSignalFileInfo[iHist]->fTreeName.Data()\n )\n );\n\n }\n\n \/\/ Data Histogram\n\n tempHist = (TH1D*) DataHist->Clone();\n Message(eInfo, \"Data : %f\", tempHist->Integral(0, NumXBins + 1, \"width\"));\n dumpFile->WriteTObject(tempHist, TString::Format(\"%s-data\", fDefaultExpr.Data()));\n dumpFile->Close();\n\n }\n\n if (fSortBackground) {\n std::sort(HistHolders.begin(), HistHolders.end(), SortHistHolders);\n Message(eInfo, \"Backgrounds sorted\");\n }\n\n Message(eDebug, \"Number of unique histograms: %i\", HistHolders.size());\n\n std::vector<TH1D*> AllHists;\n for (UInt_t iLarger = 0; iLarger != HistHolders.size(); ++iLarger) {\n\n Message(eDebug, \"Stacking up histogram: %i\", iLarger);\n Message(eInfo, \"Entry %s has total integral %f\",\n HistHolders[iLarger]->fEntry.Data(),\n HistHolders[iLarger]->fHist->Integral(\"width\"));\n\n for (UInt_t iSmaller = iLarger + 1; iSmaller != HistHolders.size(); ++iSmaller) {\n Message(eDebug, \"Adding %i to %i\", iSmaller, iLarger);\n HistHolders[iLarger]->fHist->Add(HistHolders[iSmaller]->fHist);\n }\n\n Message(eDebug, \"Histogram %i has integral %f\", iLarger, HistHolders[iLarger]->fHist->Integral());\n\n if (HistHolders[iLarger]->fHist->Integral() > 0 || iLarger == 0) {\n\n if (iLarger != 0)\n SetZeroError(HistHolders[iLarger]->fHist);\n AllHists.push_back(HistHolders[iLarger]->fHist);\n\n if ((HistHolders[iLarger]->fHist->Integral() > fMinLegendFrac * HistHolders[0]->fHist->Integral()) || \/\/ If more than the fraction set\n (iLarger == HistHolders.size() - 1)) \/\/ or the last histogram\n AddLegendEntry(HistHolders[iLarger]->fEntry, 1, fStackLineWidth, 1); \/\/ Add legend properly\n else if ((HistHolders[iLarger]->fHist->Integral() > fIgnoreInLinear * HistHolders[0]->fHist->Integral()) ||\n logY) { \/\/ Otherwise if not ignored\n if (HistHolders[iLarger + 1]->fHist->Integral() > 0) { \/\/ Check if the next histogram contribute\n if (fOthersColor != 0)\n HistHolders[iLarger]->fHist->SetFillColor(fOthersColor);\n AddLegendEntry(\"Others\", 1, fStackLineWidth, 1); \/\/ If so, make others legend\n }\n else \/\/ If not,\n AddLegendEntry(HistHolders[iLarger]->fEntry, HistHolders[iLarger]->fColor, 1, 1); \/\/ Make normal legend entry\n break; \/\/ Stop adding histograms\n } else {\n AllHists.pop_back();\n break;\n }\n }\n\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n\n }\n\n Message(eInfo, \"Total background contribution: %f\", HistHolders[0]->fHist->Integral(\"width\"));\n\n AddLegendEntry(\"Data\", 1);\n SetDataIndex(int(AllHists.size()));\n AllHists.push_back(DataHist);\n\n for (UInt_t iHist = 0; iHist != SignalHists.size(); ++iHist) {\n Message(eDebug, \"Processing Signal Hist %i of %i\", iHist, SignalHists.size());\n\n if (fAddSignal) { \/\/ Do some clever things if we're adding signal to backgrounds\n\n if (fMakeRatio) \/\/ All possible signals show up on the ratio pad\n AddRatioLine(int(AllHists.size()));\n if (AllHists.size() > 1)\n SignalHists[iHist]->Add(AllHists[0]); \/\/ Add the background to the signals\n\n }\n\n AllHists.push_back(SignalHists[iHist]);\n AddLegendEntry(fSignalFileInfo[iHist]->fEntry, 1, 2, fSignalFileInfo[iHist]->fColorStyle);\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n }\n\n Message(eDebug, \"There are now %i total histograms to plot.\", AllHists.size());\n\n if (fMakeRatio)\n AddRatioLine(fDataIndex);\n\n SetRatioIndex(0);\n\n BaseCanvas(AddOutDir(FileBase), AllHists, XLabel, YLabel, logY);\n\n for (UInt_t iHist = 0; iHist != AllHists.size(); ++iHist)\n delete AllHists[iHist];\n for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist)\n delete MCHists[iHist];\n for (UInt_t iHist = 0; iHist != DataHists.size(); ++iHist)\n delete DataHists[iHist];\n\n for (UInt_t iTemp = 0; iTemp != fTemplateEntries.size(); ++iTemp)\n TemplateFiles[iTemp]->Close();\n\n CloseFiles();\n}\n\n\/\/--------------------------------------------------------------------\nvoid\nPlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t MinX, Double_t MaxX,\n TString XLabel, TString YLabel, Bool_t logY)\n{\n bool reset_per = (fEventsPer == 0);\n if (reset_per)\n SetEventsPer((MaxX - MinX)\/NumXBins);\n\n Double_t XBins[NumXBins+1];\n ConvertToArray(NumXBins, MinX, MaxX, XBins);\n MakeCanvas(FileBase, NumXBins, XBins, XLabel, YLabel, logY);\n\n if (reset_per)\n SetEventsPer(0);\n}\n\n\/\/--------------------------------------------------------------------\nPlotStack*\nPlotStack::Copy()\n{\n PlotStack *newPlotter = new PlotStack();\n *newPlotter = *this;\n return newPlotter;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#ifndef HAVE_LIBVLC\n# error This file requires libvlc\n#endif\n\n#include \"Directory.h\"\n#include \"File.h\"\n#include \"utils\/Filename.h\"\n#include \"utils\/Url.h\"\n#include \"utils\/VLCInstance.h\"\n#include \"medialibrary\/filesystem\/Errors.h\"\n#include \"logging\/Logger.h\"\n#include \"medialibrary\/filesystem\/IFileSystemFactory.h\"\n\n#include \"compat\/ConditionVariable.h\"\n#include \"compat\/Mutex.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#ifdef _WIN32\n# include \"utils\/Charsets.h\"\n#endif\n\n#include <vlcpp\/vlc.hpp>\n\nnamespace medialibrary\n{\nnamespace fs\n{\nnamespace libvlc\n{\n\nDirectory::Directory( std::string mrl, fs::IFileSystemFactory& fsFactory )\n : CommonDirectory( fsFactory )\n , m_mrl( utils::file::toFolderPath(\n utils::url::encode(\n utils::url::decode( std::move( mrl ) ) ) ) )\n{\n}\n\nconst std::string& Directory::mrl() const\n{\n return m_mrl;\n}\n\nvoid Directory::read() const\n{\n VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );\n assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );\n\n compat::Mutex mutex;\n compat::ConditionVariable cond;\n VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;\n\n media.addOption( \":show-hiddenfiles=true\" );\n media.addOption( \":ignore-filetypes=''\" );\n media.addOption( \":sub-autodetect-fuzzy=2\" );\n\n auto eventHandler = media.eventManager().onParsedChanged(\n [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {\n std::lock_guard<compat::Mutex> lock( mutex );\n res = status;\n cond.notify_all();\n });\n\n bool success;\n {\n std::unique_lock<compat::Mutex> lock( mutex );\n media.parseWithOptions( VLC::Media::ParseFlags::Network |\n VLC::Media::ParseFlags::Local, -1 );\n success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {\n return res != VLC::Media::ParsedStatus::Skipped;\n });\n }\n eventHandler->unregister();\n if ( success == false )\n throw errors::System{ ETIMEDOUT,\n \"Failed to browse network directory: Network is too slow\" };\n if ( res == VLC::Media::ParsedStatus::Failed )\n throw errors::System{ EIO,\n \"Failed to browse network directory: Unknown error\" };\n auto subItems = media.subitems();\n for ( auto i = 0; i < subItems->count(); ++i )\n {\n auto m = subItems->itemAtIndex( i );\n auto fileName = utils::file::fileName( m->mrl() );\n if ( fileName[0] == '.' )\n {\n \/*\n * We need to expose the .nomedia file to the discoverer, but we don't\n * want to bother with hidden files & folders since they would be ignored\n * later on.\n * However, we consider something starting with '..' as a non-hidden\n * file or folder, see #218\n *\/\n if ( strcasecmp( fileName.c_str(), \".nomedia\" ) != 0 &&\n fileName.compare( 0, 2, \"..\" ) != 0 )\n continue;\n }\n if ( m->type() == VLC::Media::Type::Directory )\n m_dirs.push_back( std::make_shared<Directory>( m->mrl(), m_fsFactory ) );\n else\n {\n int64_t fileSize = 0;\n int64_t fileMtime = 0;\n#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)\n auto fileSizeTpl = m->fileStat( VLC::Media::FileStat::Size );\n auto fileMtimeTpl = m->fileStat( VLC::Media::FileStat::Mtime );\n fileSize = std::get<1>( fileSizeTpl );\n fileMtime = std::get<1>( fileMtimeTpl );\n#endif\n addFile( m->mrl(), IFile::LinkedFileType::None, {}, fileMtime, fileSize );\n for ( const auto& am : m->slaves() )\n {\n IFile::LinkedFileType linkedType;\n if ( am.type() == VLC::MediaSlave::Type::Audio )\n linkedType = IFile::LinkedFileType::SoundTrack;\n else\n {\n assert( am.type() == VLC::MediaSlave::Type::Subtitle );\n linkedType = IFile::LinkedFileType::Subtitles;\n }\n addFile( am.uri(), linkedType, m->mrl(), 0, 0 );\n }\n }\n }\n}\n\nvoid Directory::addFile( std::string mrl, fs::IFile::LinkedFileType linkedType,\n std::string linkedWith, time_t lastModificationDate,\n int64_t fileSize ) const\n{\n if ( m_fsFactory.isNetworkFileSystem() == false && lastModificationDate == 0 &&\n fileSize == 0 )\n {\n auto path = utils::url::toLocalPath( mrl );\n\n#ifdef _WIN32\n \/* We can't use _wstat here, see #323 *\/\n WIN32_FILE_ATTRIBUTE_DATA attributes;\n if ( GetFileAttributesExW( charset::ToWide( path.c_str() ).get(),\n GetFileExInfoStandard, &attributes ) == 0 )\n {\n LOG_ERROR( \"Failed to get \", path, \" attributes\" );\n throw errors::System{ GetLastError(), \"Failed to get stats\" };\n }\n LARGE_INTEGER li;\n li.u.LowPart = attributes.ftLastWriteTime.dwLowDateTime;\n li.u.HighPart = attributes.ftLastWriteTime.dwHighDateTime;\n lastModificationDate = li.QuadPart \/ 10000000ULL - 11644473600ULL;\n if ( ( attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n fileSize = 0;\n else\n {\n li.u.LowPart = attributes.nFileSizeLow;\n li.u.HighPart = attributes.nFileSizeHigh;\n fileSize = li.QuadPart;\n }\n#else\n struct stat s;\n if ( lstat( path.c_str(), &s ) != 0 )\n {\n if ( errno == EACCES )\n return;\n \/\/ some Android devices will list folder content, but will yield\n \/\/ ENOENT when accessing those.\n \/\/ See https:\/\/trac.videolan.org\/vlc\/ticket\/19909\n if ( errno == ENOENT )\n {\n LOG_WARN( \"Ignoring unexpected ENOENT while listing folder content.\" );\n return;\n }\n LOG_ERROR( \"Failed to get file \", mrl, \" info\" );\n throw errors::System{ errno, \"Failed to get file info\" };\n }\n lastModificationDate = s.st_mtime;\n fileSize = s.st_size;\n#endif\n }\n if ( linkedType == IFile::LinkedFileType::None )\n m_files.push_back( std::make_shared<File>( std::move( mrl ),\n m_fsFactory, lastModificationDate, fileSize ) );\n else\n m_files.push_back( std::make_shared<File>( std::move( mrl ),\n m_fsFactory, lastModificationDate, fileSize,\n linkedType, std::move( linkedWith ) ) );\n}\n\n}\n}\n}\n<commit_msg>fs: libvlc: Fix API usage<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#ifndef HAVE_LIBVLC\n# error This file requires libvlc\n#endif\n\n#include \"Directory.h\"\n#include \"File.h\"\n#include \"utils\/Filename.h\"\n#include \"utils\/Url.h\"\n#include \"utils\/VLCInstance.h\"\n#include \"medialibrary\/filesystem\/Errors.h\"\n#include \"logging\/Logger.h\"\n#include \"medialibrary\/filesystem\/IFileSystemFactory.h\"\n\n#include \"compat\/ConditionVariable.h\"\n#include \"compat\/Mutex.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#ifdef _WIN32\n# include \"utils\/Charsets.h\"\n#endif\n\n#include <vlcpp\/vlc.hpp>\n\nnamespace medialibrary\n{\nnamespace fs\n{\nnamespace libvlc\n{\n\nDirectory::Directory( std::string mrl, fs::IFileSystemFactory& fsFactory )\n : CommonDirectory( fsFactory )\n , m_mrl( utils::file::toFolderPath(\n utils::url::encode(\n utils::url::decode( std::move( mrl ) ) ) ) )\n{\n}\n\nconst std::string& Directory::mrl() const\n{\n return m_mrl;\n}\n\nvoid Directory::read() const\n{\n#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)\n VLC::Media media( m_mrl, VLC::Media::FromLocation );\n assert( media.parsedStatus( VLCInstance::get() ) != VLC::Media::ParsedStatus::Done );\n#else\n VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );\n assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );\n#endif\n\n compat::Mutex mutex;\n compat::ConditionVariable cond;\n VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;\n\n media.addOption( \":show-hiddenfiles=true\" );\n media.addOption( \":ignore-filetypes=''\" );\n media.addOption( \":sub-autodetect-fuzzy=2\" );\n\n auto eventHandler = media.eventManager().onParsedChanged(\n [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {\n std::lock_guard<compat::Mutex> lock( mutex );\n res = status;\n cond.notify_all();\n });\n\n bool success;\n {\n std::unique_lock<compat::Mutex> lock( mutex );\n#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)\n media.parseRequest( VLCInstance::get(), VLC::Media::ParseFlags::Network |\n VLC::Media::ParseFlags::Local, -1 );\n#else\n media.parseWithOptions( VLC::Media::ParseFlags::Network |\n VLC::Media::ParseFlags::Local, -1 );\n#endif\n success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {\n return res != VLC::Media::ParsedStatus::Skipped;\n });\n }\n eventHandler->unregister();\n if ( success == false )\n throw errors::System{ ETIMEDOUT,\n \"Failed to browse network directory: Network is too slow\" };\n if ( res == VLC::Media::ParsedStatus::Failed )\n throw errors::System{ EIO,\n \"Failed to browse network directory: Unknown error\" };\n auto subItems = media.subitems();\n for ( auto i = 0; i < subItems->count(); ++i )\n {\n auto m = subItems->itemAtIndex( i );\n auto fileName = utils::file::fileName( m->mrl() );\n if ( fileName[0] == '.' )\n {\n \/*\n * We need to expose the .nomedia file to the discoverer, but we don't\n * want to bother with hidden files & folders since they would be ignored\n * later on.\n * However, we consider something starting with '..' as a non-hidden\n * file or folder, see #218\n *\/\n if ( strcasecmp( fileName.c_str(), \".nomedia\" ) != 0 &&\n fileName.compare( 0, 2, \"..\" ) != 0 )\n continue;\n }\n if ( m->type() == VLC::Media::Type::Directory )\n m_dirs.push_back( std::make_shared<Directory>( m->mrl(), m_fsFactory ) );\n else\n {\n int64_t fileSize = 0;\n int64_t fileMtime = 0;\n#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)\n auto fileSizeTpl = m->fileStat( VLC::Media::FileStat::Size );\n auto fileMtimeTpl = m->fileStat( VLC::Media::FileStat::Mtime );\n fileSize = std::get<1>( fileSizeTpl );\n fileMtime = std::get<1>( fileMtimeTpl );\n#endif\n addFile( m->mrl(), IFile::LinkedFileType::None, {}, fileMtime, fileSize );\n for ( const auto& am : m->slaves() )\n {\n IFile::LinkedFileType linkedType;\n if ( am.type() == VLC::MediaSlave::Type::Audio )\n linkedType = IFile::LinkedFileType::SoundTrack;\n else\n {\n assert( am.type() == VLC::MediaSlave::Type::Subtitle );\n linkedType = IFile::LinkedFileType::Subtitles;\n }\n addFile( am.uri(), linkedType, m->mrl(), 0, 0 );\n }\n }\n }\n}\n\nvoid Directory::addFile( std::string mrl, fs::IFile::LinkedFileType linkedType,\n std::string linkedWith, time_t lastModificationDate,\n int64_t fileSize ) const\n{\n if ( m_fsFactory.isNetworkFileSystem() == false && lastModificationDate == 0 &&\n fileSize == 0 )\n {\n auto path = utils::url::toLocalPath( mrl );\n\n#ifdef _WIN32\n \/* We can't use _wstat here, see #323 *\/\n WIN32_FILE_ATTRIBUTE_DATA attributes;\n if ( GetFileAttributesExW( charset::ToWide( path.c_str() ).get(),\n GetFileExInfoStandard, &attributes ) == 0 )\n {\n LOG_ERROR( \"Failed to get \", path, \" attributes\" );\n throw errors::System{ GetLastError(), \"Failed to get stats\" };\n }\n LARGE_INTEGER li;\n li.u.LowPart = attributes.ftLastWriteTime.dwLowDateTime;\n li.u.HighPart = attributes.ftLastWriteTime.dwHighDateTime;\n lastModificationDate = li.QuadPart \/ 10000000ULL - 11644473600ULL;\n if ( ( attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n fileSize = 0;\n else\n {\n li.u.LowPart = attributes.nFileSizeLow;\n li.u.HighPart = attributes.nFileSizeHigh;\n fileSize = li.QuadPart;\n }\n#else\n struct stat s;\n if ( lstat( path.c_str(), &s ) != 0 )\n {\n if ( errno == EACCES )\n return;\n \/\/ some Android devices will list folder content, but will yield\n \/\/ ENOENT when accessing those.\n \/\/ See https:\/\/trac.videolan.org\/vlc\/ticket\/19909\n if ( errno == ENOENT )\n {\n LOG_WARN( \"Ignoring unexpected ENOENT while listing folder content.\" );\n return;\n }\n LOG_ERROR( \"Failed to get file \", mrl, \" info\" );\n throw errors::System{ errno, \"Failed to get file info\" };\n }\n lastModificationDate = s.st_mtime;\n fileSize = s.st_size;\n#endif\n }\n if ( linkedType == IFile::LinkedFileType::None )\n m_files.push_back( std::make_shared<File>( std::move( mrl ),\n m_fsFactory, lastModificationDate, fileSize ) );\n else\n m_files.push_back( std::make_shared<File>( std::move( mrl ),\n m_fsFactory, lastModificationDate, fileSize,\n linkedType, std::move( linkedWith ) ) );\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#pragma once\n\n#include <hwloc.h>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\nusing namespace std;\n\n\/*\n * The processor architecture of machines in our cluster (Cube0-5)\n *\n * $numactl --hardware\n * available: 2 nodes (0-1)\n * node 0 cpus: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38\n * node 0 size: 64265 MB\n * node 0 free: 19744 MB\n * node 1 cpus: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39\n * node 1 size: 64503 MB\n * node 1 free: 53586 MB\n * node distances:\n * node 0 1\n * 0: 10 21\n * 1: 21 10\n *\n *\n * $cat config\n * global_num_proxies 4\n * global_num_engines 16\n *\n * $cat core.bind\n * 0 1 4 5 6 7 8 9 10 11\n * 2 3 12 13 14 15 16 17 18 19\n *\n *\/\n\nvector<vector<int>> cpu_topo;\nvector<int> default_bindings;\nint num_cores = 0;\n\nvoid dump_node_topo(vector<vector<int>> topo)\n{\n\tcout << \"TOPO: \" << topo.size() << \"nodes\" << endl;\n\tfor (int nid = 0; nid < topo.size(); nid++) {\n\t\tcout << \" node \" << nid << \" cores: \";\n\t\tfor (int cid = 0; cid < topo[nid].size(); cid++)\n\t\t\tcout << topo[nid][cid] << \" \";\n\t\tcout << endl;\n\t}\n}\n\nvoid load_node_topo(void)\n{\n\thwloc_topology_t topology;\n\n\thwloc_topology_init(&topology);\n\thwloc_topology_load(topology);\n\n\tint nnodes = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NUMANODE);\n\tcpu_topo.resize(nnodes);\n\tfor (int i = 0; i < nnodes; i++) {\n\t\thwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);\n\t\thwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);\n\n\t\tunsigned int core = 0;\n\t\thwloc_bitmap_foreach_begin(core, cpuset);\n\t\tcpu_topo[i].push_back(core);\n\t\tdefault_bindings.push_back(core);\n\t\thwloc_bitmap_foreach_end();\n\n\t\thwloc_bitmap_free(cpuset);\n\t}\n\tnum_cores = default_bindings.size();\n\n\tdump_node_topo(cpu_topo);\n}\n\nbool enable_binding = false;\nmap<int, int> core_bindings;\n\nbool load_core_binding(string fname)\n{\n\tint nbs = 0;\n\n\t\/\/load file of core binding\n\tifstream file(fname.c_str());\n\tif (!file) {\n\t\tcout << \"ERROR: \" << fname << \" does not exist.\" << endl;\n\t\treturn false;\n\t}\n\n\tint nnodes = cpu_topo.size(), i = 0;\n\tstring line;\n\twhile (std::getline(file, line)) {\n\t\tif (boost::starts_with(line, \"#\"))\n\t\t\tcontinue; \/\/ skip comments and blank lines\n\n\t\tistringstream iss(line); \/\/ one node per line\n\t\tint ncores = cpu_topo[i].size(), j = 0, tid;\n\t\twhile (iss >> tid) {\n\t\t\t\/\/cout << tid << \" \" << cpu_topo[i % nnodes][j % ncores] << endl;\n\t\t\tcore_bindings[tid] = cpu_topo[i % nnodes][j++ % ncores];\n\t\t\tnbs++;\n\t\t}\n\n\t\ti++; \/\/ next node\n\t}\n\n\tif (nbs < global_num_threads)\n\t\tcout << \"WARNING: #threads (in \\'config\\') exceeds #bindings (in \\'bind\\')!\" << endl;\n\n\treturn true;\n}\n\nvoid bind_to_core(size_t core)\n{\n\tcpu_set_t mask;\n\tCPU_ZERO(&mask);\n\tCPU_SET(core, &mask);\n\tif (sched_setaffinity(0, sizeof(mask), &mask) != 0)\n\t\tcout << \"Failed to set affinity (core: \" << core << \")\" << endl;\n}\n\n<commit_msg>core binding bug fixed<commit_after>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#pragma once\n\n#include <hwloc.h>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\nusing namespace std;\n\n\/*\n * The processor architecture of machines in our cluster (Cube0-5)\n *\n * $numactl --hardware\n * available: 2 nodes (0-1)\n * node 0 cpus: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38\n * node 0 size: 64265 MB\n * node 0 free: 19744 MB\n * node 1 cpus: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39\n * node 1 size: 64503 MB\n * node 1 free: 53586 MB\n * node distances:\n * node 0 1\n * 0: 10 21\n * 1: 21 10\n *\n *\n * $cat config\n * global_num_proxies 4\n * global_num_engines 16\n *\n * $cat core.bind\n * 0 1 4 5 6 7 8 9 10 11\n * 2 3 12 13 14 15 16 17 18 19\n *\n *\/\n\nvector<vector<int>> cpu_topo;\nvector<int> default_bindings;\nint num_cores = 0;\n\nvoid dump_node_topo(vector<vector<int>> topo)\n{\n\tcout << \"TOPO: \" << topo.size() << \"nodes\" << endl;\n\tfor (int nid = 0; nid < topo.size(); nid++) {\n\t\tcout << \" node \" << nid << \" cores: \";\n\t\tfor (int cid = 0; cid < topo[nid].size(); cid++)\n\t\t\tcout << topo[nid][cid] << \" \";\n\t\tcout << endl;\n\t}\n}\n\nvoid load_node_topo(void)\n{\n\thwloc_topology_t topology;\n\n\thwloc_topology_init(&topology);\n\thwloc_topology_load(topology);\n\n\t\/\/currently, nnodes may return 0 while the NUMANODEs in cpulist is 1(hwloc think there is actually no numa-node)\n\t\/\/but it can detect the number of processing units(PU) correctly\n\t\/\/when multi-thread processing is on, the number of PU will be twice as number of cores\n\tint nnodes = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NUMANODE);\n\tif(nnodes != 0){\n\t\tcpu_topo.resize(nnodes);\n\t\tfor (int i = 0; i < nnodes; i++) {\n\t\t\thwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);\n\t\t\thwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);\n\t\n\t\t\tunsigned int core = 0;\n\t\t\thwloc_bitmap_foreach_begin(core, cpuset);\n\t\t\tcpu_topo[i].push_back(core);\n\t\t\tdefault_bindings.push_back(core);\n\t\t\thwloc_bitmap_foreach_end();\n\t\n\t\t\thwloc_bitmap_free(cpuset);\n\t\t}\n\t}\n\telse{\n\t\tcpu_topo.resize(1);\n\t\tint nPUs = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);\n\t\tfor (int i = 0; i < nPUs; i++) {\n\t\t\thwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, i);\n\t\t\thwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);\n\t\n\t\t\tunsigned int core = 0;\n\t\t\thwloc_bitmap_foreach_begin(core, cpuset);\n\t\t\tcpu_topo[0].push_back(core);\n\t\t\tdefault_bindings.push_back(core);\n\t\t\thwloc_bitmap_foreach_end();\n\t\n\t\t\thwloc_bitmap_free(cpuset);\n\t\t}\n\t}\n\tnum_cores = default_bindings.size();\n\n\tdump_node_topo(cpu_topo);\n}\n\nbool enable_binding = false;\nmap<int, int> core_bindings;\n\nbool load_core_binding(string fname)\n{\n\tint nbs = 0;\n\n\t\/\/load file of core binding\n\tifstream file(fname.c_str());\n\tif (!file) {\n\t\tcout << \"ERROR: \" << fname << \" does not exist.\" << endl;\n\t\treturn false;\n\t}\n\n\tint nnodes = cpu_topo.size(), i = 0;\n\tstring line;\n\twhile (std::getline(file, line)) {\n\t\tif (boost::starts_with(line, \"#\"))\n\t\t\tcontinue; \/\/ skip comments and blank lines\n\n\t\tistringstream iss(line); \/\/ one node per line\n\t\tint ncores = cpu_topo[i].size(), j = 0, tid;\n\t\twhile (iss >> tid) {\n\t\t\t\/\/cout << tid << \" \" << cpu_topo[i % nnodes][j % ncores] << endl;\n\t\t\tcore_bindings[tid] = cpu_topo[i % nnodes][j++ % ncores];\n\t\t\tnbs++;\n\t\t}\n\n\t\ti++; \/\/ next node\n\t}\n\n\tif(i < nnodes){\n\t\tcout << \"WARNING: #bindings (in \\'core.bind\\') did not use all of the NUMANODEs!\" << endl;\n\t}\n\tif(i > nnodes){\n\t\tcout << \"WARNING: #bindings (in \\'core.bind\\') exceeds number of the NUMANODEs!\" << endl;\n\t}\n\tif (nbs < global_num_threads)\n\t\tcout << \"WARNING: #threads (in \\'config\\') exceeds #bindings (in \\'bind\\')!\" << endl;\n\n\treturn true;\n}\n\nvoid bind_to_core(size_t core)\n{\n\tcpu_set_t mask;\n\tCPU_ZERO(&mask);\n\tCPU_SET(core, &mask);\n\tif (sched_setaffinity(0, sizeof(mask), &mask) != 0)\n\t\tcout << \"Failed to set affinity (core: \" << core << \")\" << endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/enhanced_bookmarks\/image_store.h\"\n\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"components\/enhanced_bookmarks\/image_store_util.h\"\n#include \"components\/enhanced_bookmarks\/persistent_image_store.h\"\n#include \"components\/enhanced_bookmarks\/test_image_store.h\"\n#include \"testing\/platform_test.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\ngfx::Image CreateImage(int width, int height, int a, int r, int g, int b) {\n SkBitmap bitmap;\n bitmap.allocN32Pixels(width, height);\n bitmap.eraseARGB(a, r, g, b);\n gfx::Image image(gfx::Image::CreateFrom1xBitmap(bitmap));\n\n#if defined(OS_IOS)\n \/\/ Make sure the image has a kImageRepCocoaTouch.\n image.ToUIImage();\n#endif \/\/ defined(OS_IOS)\n\n return image;\n}\n\ngfx::Image GenerateWhiteImage() {\n return CreateImage(42, 24, 255, 255, 255, 255);\n}\n\ngfx::Image GenerateBlackImage(int width, int height) {\n return CreateImage(width, height, 255, 0, 0, 0);\n}\n\ngfx::Image GenerateBlackImage() {\n return GenerateBlackImage(42, 24);\n}\n\n\/\/ Returns true if the two images are identical.\nbool CompareImages(const gfx::Image& image_1, const gfx::Image& image_2) {\n if (image_1.IsEmpty() && image_2.IsEmpty())\n return true;\n\n if (image_1.IsEmpty() || image_2.IsEmpty())\n return false;\n\n scoped_refptr<base::RefCountedMemory> image_1_bytes =\n enhanced_bookmarks::BytesForImage(image_1);\n scoped_refptr<base::RefCountedMemory> image_2_bytes =\n enhanced_bookmarks::BytesForImage(image_2);\n\n if (image_1_bytes->size() != image_2_bytes->size())\n return false;\n\n return !memcmp(image_1_bytes->front(),\n image_2_bytes->front(),\n image_1_bytes->size());\n}\n\n\/\/ Factory functions for creating instances of the implementations.\ntemplate <class T>\nImageStore* CreateStore(base::ScopedTempDir& folder);\n\ntemplate <>\nImageStore* CreateStore<TestImageStore>(\n base::ScopedTempDir& folder) {\n return new TestImageStore();\n}\n\ntemplate <>\nImageStore* CreateStore<PersistentImageStore>(\n base::ScopedTempDir& folder) {\n return new PersistentImageStore(folder.path());\n}\n\n\/\/ Methods to check if persistence is on or not.\ntemplate <class T> bool ShouldPersist();\ntemplate <> bool ShouldPersist<TestImageStore>() { return false; }\ntemplate <> bool ShouldPersist<PersistentImageStore>() { return true; }\n\n\/\/ Test fixture class template for the abstract API.\ntemplate <class T>\nclass ImageStoreUnitTest : public PlatformTest {\n protected:\n ImageStoreUnitTest() {}\n virtual ~ImageStoreUnitTest() {}\n\n virtual void SetUp() override {\n bool success = tempDir_.CreateUniqueTempDir();\n ASSERT_TRUE(success);\n store_.reset(CreateStore<T>(tempDir_));\n }\n\n virtual void TearDown() override {\n if (store_ && use_persistent_store())\n store_->ClearAll();\n }\n\n bool use_persistent_store() const { return ShouldPersist<T>(); }\n void ResetStore() { store_.reset(CreateStore<T>(tempDir_)); }\n\n \/\/ The directory the database is saved into.\n base::ScopedTempDir tempDir_;\n \/\/ The object the fixture is testing, via its base interface.\n scoped_ptr<ImageStore> store_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(ImageStoreUnitTest);\n};\n\n\/\/ The list of implementations of the abstract API that are going to be tested.\ntypedef testing::Types<TestImageStore,\n PersistentImageStore> Implementations;\n\nTYPED_TEST_CASE(ImageStoreUnitTest, Implementations);\n\n\/\/ All those tests are run on all the implementations.\nTYPED_TEST(ImageStoreUnitTest, StartsEmpty) {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, StoreOne) {\n this->store_->Insert(GURL(\"foo:\/\/bar\"), GURL(\"a.jpg\"), GenerateBlackImage());\n\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(GURL(\"foo:\/\/bar\"), *all_urls.begin());\n EXPECT_TRUE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Retrieve) {\n gfx::Image src_image = GenerateBlackImage(42, 24);\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n gfx::Size size = this->store_->GetSize(url);\n\n EXPECT_EQ(size.width(), 42);\n EXPECT_EQ(size.height(), 24);\n EXPECT_EQ(image_url, image_info.second);\n EXPECT_TRUE(CompareImages(src_image, image_info.first));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Erase) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n this->store_->Erase(url);\n\n EXPECT_FALSE(this->store_->HasKey(url));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, ClearAll) {\n const GURL url_foo(\"http:\/\/foo\");\n this->store_->Insert(url_foo, GURL(\"foo.jpg\"), GenerateBlackImage());\n const GURL url_bar(\"http:\/\/bar\");\n this->store_->Insert(url_foo, GURL(\"bar.jpg\"), GenerateWhiteImage());\n\n this->store_->ClearAll();\n\n EXPECT_FALSE(this->store_->HasKey(url_foo));\n EXPECT_FALSE(this->store_->HasKey(url_bar));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, Update) {\n gfx::Image src_image1 = GenerateWhiteImage();\n gfx::Image src_image2 = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url1(\"1.jpg\");\n this->store_->Insert(url, image_url1, src_image1);\n\n const GURL image_url2(\"2.jpg\");\n this->store_->Insert(url, image_url2, src_image2);\n\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n\n EXPECT_TRUE(this->store_->HasKey(url));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(image_url2, image_info.second);\n EXPECT_TRUE(CompareImages(src_image2, image_info.first));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Persistence) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n\n this->ResetStore();\n if (this->use_persistent_store()) {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(GURL(\"foo:\/\/bar\"), *all_urls.begin());\n EXPECT_TRUE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n\n EXPECT_EQ(image_url, image_info.second);\n EXPECT_TRUE(CompareImages(src_image, image_info.first));\n } else {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n EXPECT_FALSE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n }\n}\n\nTYPED_TEST(ImageStoreUnitTest, GetSize) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n\n int64 size = 0;\n if (this->use_persistent_store()) {\n \/\/ File shouldn't exist before we actually start using it since we do lazy\n \/\/ initialization.\n EXPECT_EQ(this->store_->GetStoreSizeInBytes(), -1);\n } else {\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 1024);\n }\n for (int i = 0; i < 100; ++i) {\n this->store_->Insert(\n GURL(url.spec() + '\/' + base::IntToString(i)), image_url, src_image);\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), size);\n size = this->store_->GetStoreSizeInBytes();\n }\n\n if (this->use_persistent_store()) {\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), 90 * 1024); \/\/ 90kb\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 200 * 1024); \/\/ 200kb\n } else {\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), 400 * 1024); \/\/ 400kb\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 500 * 1024); \/\/ 500kb\n }\n}\n\n} \/\/ namespace\n<commit_msg>Fix ImageStoreUnitTest.GetSize on iOS<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/enhanced_bookmarks\/image_store.h\"\n\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"components\/enhanced_bookmarks\/image_store_util.h\"\n#include \"components\/enhanced_bookmarks\/persistent_image_store.h\"\n#include \"components\/enhanced_bookmarks\/test_image_store.h\"\n#include \"testing\/platform_test.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\ngfx::Image CreateImage(int width, int height, int a, int r, int g, int b) {\n SkBitmap bitmap;\n bitmap.allocN32Pixels(width, height);\n bitmap.eraseARGB(a, r, g, b);\n gfx::Image image(gfx::Image::CreateFrom1xBitmap(bitmap));\n\n#if defined(OS_IOS)\n \/\/ Make sure the image has a kImageRepCocoaTouch.\n image.ToUIImage();\n#endif \/\/ defined(OS_IOS)\n\n return image;\n}\n\ngfx::Image GenerateWhiteImage() {\n return CreateImage(42, 24, 255, 255, 255, 255);\n}\n\ngfx::Image GenerateBlackImage(int width, int height) {\n return CreateImage(width, height, 255, 0, 0, 0);\n}\n\ngfx::Image GenerateBlackImage() {\n return GenerateBlackImage(42, 24);\n}\n\n\/\/ Returns true if the two images are identical.\nbool CompareImages(const gfx::Image& image_1, const gfx::Image& image_2) {\n if (image_1.IsEmpty() && image_2.IsEmpty())\n return true;\n\n if (image_1.IsEmpty() || image_2.IsEmpty())\n return false;\n\n scoped_refptr<base::RefCountedMemory> image_1_bytes =\n enhanced_bookmarks::BytesForImage(image_1);\n scoped_refptr<base::RefCountedMemory> image_2_bytes =\n enhanced_bookmarks::BytesForImage(image_2);\n\n if (image_1_bytes->size() != image_2_bytes->size())\n return false;\n\n return !memcmp(image_1_bytes->front(),\n image_2_bytes->front(),\n image_1_bytes->size());\n}\n\n\/\/ Factory functions for creating instances of the implementations.\ntemplate <class T>\nImageStore* CreateStore(base::ScopedTempDir& folder);\n\ntemplate <>\nImageStore* CreateStore<TestImageStore>(\n base::ScopedTempDir& folder) {\n return new TestImageStore();\n}\n\ntemplate <>\nImageStore* CreateStore<PersistentImageStore>(\n base::ScopedTempDir& folder) {\n return new PersistentImageStore(folder.path());\n}\n\n\/\/ Methods to check if persistence is on or not.\ntemplate <class T> bool ShouldPersist();\ntemplate <> bool ShouldPersist<TestImageStore>() { return false; }\ntemplate <> bool ShouldPersist<PersistentImageStore>() { return true; }\n\n\/\/ Test fixture class template for the abstract API.\ntemplate <class T>\nclass ImageStoreUnitTest : public PlatformTest {\n protected:\n ImageStoreUnitTest() {}\n virtual ~ImageStoreUnitTest() {}\n\n virtual void SetUp() override {\n bool success = tempDir_.CreateUniqueTempDir();\n ASSERT_TRUE(success);\n store_.reset(CreateStore<T>(tempDir_));\n }\n\n virtual void TearDown() override {\n if (store_ && use_persistent_store())\n store_->ClearAll();\n }\n\n bool use_persistent_store() const { return ShouldPersist<T>(); }\n void ResetStore() { store_.reset(CreateStore<T>(tempDir_)); }\n\n \/\/ The directory the database is saved into.\n base::ScopedTempDir tempDir_;\n \/\/ The object the fixture is testing, via its base interface.\n scoped_ptr<ImageStore> store_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(ImageStoreUnitTest);\n};\n\n\/\/ The list of implementations of the abstract API that are going to be tested.\ntypedef testing::Types<TestImageStore,\n PersistentImageStore> Implementations;\n\nTYPED_TEST_CASE(ImageStoreUnitTest, Implementations);\n\n\/\/ All those tests are run on all the implementations.\nTYPED_TEST(ImageStoreUnitTest, StartsEmpty) {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, StoreOne) {\n this->store_->Insert(GURL(\"foo:\/\/bar\"), GURL(\"a.jpg\"), GenerateBlackImage());\n\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(GURL(\"foo:\/\/bar\"), *all_urls.begin());\n EXPECT_TRUE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Retrieve) {\n gfx::Image src_image = GenerateBlackImage(42, 24);\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n gfx::Size size = this->store_->GetSize(url);\n\n EXPECT_EQ(size.width(), 42);\n EXPECT_EQ(size.height(), 24);\n EXPECT_EQ(image_url, image_info.second);\n EXPECT_TRUE(CompareImages(src_image, image_info.first));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Erase) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n this->store_->Erase(url);\n\n EXPECT_FALSE(this->store_->HasKey(url));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, ClearAll) {\n const GURL url_foo(\"http:\/\/foo\");\n this->store_->Insert(url_foo, GURL(\"foo.jpg\"), GenerateBlackImage());\n const GURL url_bar(\"http:\/\/bar\");\n this->store_->Insert(url_foo, GURL(\"bar.jpg\"), GenerateWhiteImage());\n\n this->store_->ClearAll();\n\n EXPECT_FALSE(this->store_->HasKey(url_foo));\n EXPECT_FALSE(this->store_->HasKey(url_bar));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n}\n\nTYPED_TEST(ImageStoreUnitTest, Update) {\n gfx::Image src_image1 = GenerateWhiteImage();\n gfx::Image src_image2 = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url1(\"1.jpg\");\n this->store_->Insert(url, image_url1, src_image1);\n\n const GURL image_url2(\"2.jpg\");\n this->store_->Insert(url, image_url2, src_image2);\n\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n\n EXPECT_TRUE(this->store_->HasKey(url));\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(image_url2, image_info.second);\n EXPECT_TRUE(CompareImages(src_image2, image_info.first));\n}\n\nTYPED_TEST(ImageStoreUnitTest, Persistence) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n this->store_->Insert(url, image_url, src_image);\n\n this->ResetStore();\n if (this->use_persistent_store()) {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(1u, all_urls.size());\n EXPECT_EQ(GURL(\"foo:\/\/bar\"), *all_urls.begin());\n EXPECT_TRUE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);\n\n EXPECT_EQ(image_url, image_info.second);\n EXPECT_TRUE(CompareImages(src_image, image_info.first));\n } else {\n std::set<GURL> all_urls;\n this->store_->GetAllPageUrls(&all_urls);\n EXPECT_EQ(0u, all_urls.size());\n EXPECT_FALSE(this->store_->HasKey(GURL(\"foo:\/\/bar\")));\n }\n}\n\nTYPED_TEST(ImageStoreUnitTest, GetSize) {\n gfx::Image src_image = GenerateBlackImage();\n const GURL url(\"foo:\/\/bar\");\n const GURL image_url(\"a.jpg\");\n\n int64 size = 0;\n if (this->use_persistent_store()) {\n \/\/ File shouldn't exist before we actually start using it since we do lazy\n \/\/ initialization.\n EXPECT_EQ(this->store_->GetStoreSizeInBytes(), -1);\n } else {\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 1024);\n }\n for (int i = 0; i < 100; ++i) {\n this->store_->Insert(\n GURL(url.spec() + '\/' + base::IntToString(i)), image_url, src_image);\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), size);\n size = this->store_->GetStoreSizeInBytes();\n }\n\n if (this->use_persistent_store()) {\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), 80 * 1024); \/\/ 80kb\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 200 * 1024); \/\/ 200kb\n } else {\n EXPECT_GE(this->store_->GetStoreSizeInBytes(), 400 * 1024); \/\/ 400kb\n EXPECT_LE(this->store_->GetStoreSizeInBytes(), 500 * 1024); \/\/ 500kb\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/combobox_model.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_login_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_network_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/network_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_screen_observer.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/view_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_screen.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/button\/text_button.h\"\n#include \"views\/controls\/combobox\/combobox.h\"\n\nnamespace chromeos {\nusing ::testing::AnyNumber;\nusing ::testing::InvokeWithoutArgs;\nusing ::testing::Return;\nusing ::testing::ReturnRef;\nusing ::testing::_;\nusing ::testing::A;\nusing views::Button;\n\nclass DummyButtonListener : public views::ButtonListener {\n public:\n virtual void ButtonPressed(views::Button* sender,\n const views::Event& event) {}\n};\n\nclass NetworkScreenTest : public WizardInProcessBrowserTest {\n public:\n NetworkScreenTest(): WizardInProcessBrowserTest(\"network\"),\n mock_login_library_(NULL),\n mock_network_library_(NULL) {\n }\n\n protected:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n mock_network_library_ = cros_mock_->mock_network_library();\n mock_login_library_ = new MockLoginLibrary();\n cros_mock_->test_api()->SetLoginLibrary(mock_login_library_, true);\n EXPECT_CALL(*mock_login_library_, EmitLoginPromptReady())\n .Times(1);\n\n \/\/ Minimal set of expectations needed on NetworkScreen initialization.\n \/\/ Status bar expectations are defined with RetiresOnSaturation() so\n \/\/ these mocks will be active once status bar is initialized.\n EXPECT_CALL(*mock_network_library_, active_network())\n .Times(1)\n .WillRepeatedly((Return((const Network*)(NULL))))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .Times(1)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .Times(1)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, cellular_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, ethernet_available())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, ethernet_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, wifi_available())\n .Times(1)\n .WillRepeatedly((Return(false)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, wifi_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, cellular_available())\n .Times(1)\n .WillRepeatedly((Return(false)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, cellular_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n\n \/\/ Add a Connecting for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, Connecting())\n .Times(1)\n .WillRepeatedly(Return(false));\n \/\/ Add a Connected for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, Connected())\n .Times(4)\n .WillRepeatedly(Return(false));\n \/\/ Add an Observer for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, AddNetworkManagerObserver(_))\n .Times(3);\n EXPECT_CALL(*mock_network_library_, RemoveNetworkManagerObserver(_))\n .Times(2);\n\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void TearDownInProcessBrowserTestFixture() {\n CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();\n cros_mock_->test_api()->SetLoginLibrary(NULL, false);\n }\n\n void EmulateContinueButtonExit(NetworkScreen* network_screen) {\n scoped_ptr<MockScreenObserver>\n mock_screen_observer(new MockScreenObserver());\n EXPECT_CALL(*mock_screen_observer,\n OnExit(ScreenObserver::NETWORK_CONNECTED))\n .Times(1);\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n controller()->set_observer(mock_screen_observer.get());\n DummyButtonListener button_listener;\n views::TextButton button(&button_listener, L\"Button\");\n views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,\n 0, 0,\n views::Event::EF_LEFT_BUTTON_DOWN);\n network_screen->ButtonPressed(&button, event);\n ui_test_utils::RunAllPendingInMessageLoop();\n controller()->set_observer(NULL);\n }\n\n MockLoginLibrary* mock_login_library_;\n MockNetworkLibrary* mock_network_library_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);\n};\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(true)));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<WifiNetwork> wifi(new WifiNetwork());\n EXPECT_CALL(*mock_network_library_, wifi_network())\n .WillOnce(Return(wifi.get()));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<CellularNetwork> cellular(new CellularNetwork());\n EXPECT_CALL(*mock_network_library_, cellular_network())\n .WillOnce(Return(cellular.get()));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Timeout) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<WifiNetwork> wifi(new WifiNetwork());\n EXPECT_CALL(*mock_network_library_, wifi_network())\n .WillOnce(Return(wifi.get()));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(false));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n network_screen->OnConnectionTimeout();\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n \/\/ Close infobubble with error message - it makes test stable.\n network_screen->ClearErrors();\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Fix another test. BUG=None TEST=None TBR=stevenjb@chromium.org Review URL: http:\/\/codereview.chromium.org\/5145005<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/combobox_model.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_login_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_network_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/network_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_screen_observer.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/view_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_screen.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/button\/text_button.h\"\n#include \"views\/controls\/combobox\/combobox.h\"\n\nnamespace chromeos {\nusing ::testing::AnyNumber;\nusing ::testing::InvokeWithoutArgs;\nusing ::testing::Return;\nusing ::testing::ReturnRef;\nusing ::testing::_;\nusing ::testing::A;\nusing views::Button;\n\nclass DummyButtonListener : public views::ButtonListener {\n public:\n virtual void ButtonPressed(views::Button* sender,\n const views::Event& event) {}\n};\n\nclass NetworkScreenTest : public WizardInProcessBrowserTest {\n public:\n NetworkScreenTest(): WizardInProcessBrowserTest(\"network\"),\n mock_login_library_(NULL),\n mock_network_library_(NULL) {\n }\n\n protected:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n mock_network_library_ = cros_mock_->mock_network_library();\n mock_login_library_ = new MockLoginLibrary();\n cros_mock_->test_api()->SetLoginLibrary(mock_login_library_, true);\n EXPECT_CALL(*mock_login_library_, EmitLoginPromptReady())\n .Times(1);\n\n \/\/ Minimal set of expectations needed on NetworkScreen initialization.\n \/\/ Status bar expectations are defined with RetiresOnSaturation() so\n \/\/ these mocks will be active once status bar is initialized.\n EXPECT_CALL(*mock_network_library_, active_network())\n .Times(AnyNumber())\n .WillRepeatedly((Return((const Network*)(NULL))))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .Times(1)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .Times(1)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, cellular_connecting())\n .Times(2)\n .WillRepeatedly(Return(false));\n EXPECT_CALL(*mock_network_library_, ethernet_available())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, ethernet_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, wifi_available())\n .Times(1)\n .WillRepeatedly((Return(false)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, wifi_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, cellular_available())\n .Times(1)\n .WillRepeatedly((Return(false)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_network_library_, cellular_enabled())\n .Times(1)\n .WillRepeatedly((Return(true)))\n .RetiresOnSaturation();\n\n \/\/ Add a Connecting for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, Connecting())\n .Times(1)\n .WillRepeatedly(Return(false));\n \/\/ Add a Connected for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, Connected())\n .Times(4)\n .WillRepeatedly(Return(false));\n \/\/ Add an Observer for prewarming auth url check.\n EXPECT_CALL(*mock_network_library_, AddNetworkManagerObserver(_))\n .Times(3);\n EXPECT_CALL(*mock_network_library_, RemoveNetworkManagerObserver(_))\n .Times(2);\n\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void TearDownInProcessBrowserTestFixture() {\n CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();\n cros_mock_->test_api()->SetLoginLibrary(NULL, false);\n }\n\n void EmulateContinueButtonExit(NetworkScreen* network_screen) {\n scoped_ptr<MockScreenObserver>\n mock_screen_observer(new MockScreenObserver());\n EXPECT_CALL(*mock_screen_observer,\n OnExit(ScreenObserver::NETWORK_CONNECTED))\n .Times(1);\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n controller()->set_observer(mock_screen_observer.get());\n DummyButtonListener button_listener;\n views::TextButton button(&button_listener, L\"Button\");\n views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,\n 0, 0,\n views::Event::EF_LEFT_BUTTON_DOWN);\n network_screen->ButtonPressed(&button, event);\n ui_test_utils::RunAllPendingInMessageLoop();\n controller()->set_observer(NULL);\n }\n\n MockLoginLibrary* mock_login_library_;\n MockNetworkLibrary* mock_network_library_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);\n};\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(true)));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<WifiNetwork> wifi(new WifiNetwork());\n EXPECT_CALL(*mock_network_library_, wifi_network())\n .WillOnce(Return(wifi.get()));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<CellularNetwork> cellular(new CellularNetwork());\n EXPECT_CALL(*mock_network_library_, cellular_network())\n .WillOnce(Return(cellular.get()));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce(Return(true));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(true));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_TRUE(network_view->IsContinueEnabled());\n\n EmulateContinueButtonExit(network_screen);\n}\n\nIN_PROC_BROWSER_TEST_F(NetworkScreenTest, Timeout) {\n ASSERT_TRUE(controller());\n NetworkScreen* network_screen = controller()->GetNetworkScreen();\n ASSERT_TRUE(network_screen != NULL);\n ASSERT_EQ(network_screen, controller()->current_screen());\n\n NetworkSelectionView* network_view = network_screen->view();\n ASSERT_TRUE(network_view != NULL);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n\n EXPECT_CALL(*mock_network_library_, ethernet_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, cellular_connected())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, ethernet_connecting())\n .WillOnce((Return(false)));\n EXPECT_CALL(*mock_network_library_, wifi_connecting())\n .WillOnce((Return(true)));\n scoped_ptr<WifiNetwork> wifi(new WifiNetwork());\n EXPECT_CALL(*mock_network_library_, wifi_network())\n .WillOnce(Return(wifi.get()));\n EXPECT_CALL(*mock_network_library_, Connected())\n .WillOnce(Return(false));\n\n network_screen->OnNetworkManagerChanged(mock_network_library_);\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n network_screen->OnConnectionTimeout();\n EXPECT_FALSE(network_view->IsContinueEnabled());\n EXPECT_FALSE(network_view->IsConnecting());\n\n \/\/ Close infobubble with error message - it makes test stable.\n network_screen->ClearErrors();\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/**\n * AuthModule\n *\n * Copyright 2013 Thincast Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <winpr\/crt.h>\n#include <winpr\/wlog.h>\n#include <winpr\/library.h>\n\n#include <freerds\/auth.h>\n\n#include \"appcontext\/ApplicationContext.h\"\n\n#include \"AuthModule.h\"\n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tnamespace module\n\t\t{\n\t\t\tstatic wLog* logger_Module = WLog_Get(\"freerds.sessionmanager.module.authmodule\");\n\n\t\t\tAuthModule::AuthModule()\n\t\t\t\t: mAuth(NULL),\n\t\t\t\t mModuleEntry(NULL)\n\t\t\t{\n\t\t\t\tZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));\n\t\t\t}\n\n\t\t\tint AuthModule::initModule(pRdsAuthModuleEntry moduleEntry)\n\t\t\t{\n\t\t\t\tint status = 0;\n\t\t\t\tmModuleEntry = moduleEntry;\n\n\t\t\t\tZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));\n\t\t\t\tmEntryPoints.Version = RDS_AUTH_MODULE_INTERFACE_VERSION;\n\n\t\t\t\tstatus = mModuleEntry(&mEntryPoints);\n\n\t\t\t\tif (status < 0)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tmAuth = mEntryPoints.New();\n\n\t\t\t\tif (!mAuth)\n\t\t\t\t\treturn -1;\n\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tAuthModule::~AuthModule()\n\t\t\t{\n\t\t\t\tif (mEntryPoints.Free)\n\t\t\t\t{\n\t\t\t\t\tmEntryPoints.Free(mAuth);\n\t\t\t\t\tmAuth = NULL;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint AuthModule::logonUser(std::string username, std::string domain, std::string password)\n\t\t\t{\n\t\t\t\tint status;\n\n\t\t\t\tif (!mEntryPoints.LogonUser)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tstatus = mEntryPoints.LogonUser(mAuth, username.c_str(), domain.size() == 0 ? NULL : domain.c_str(), password.size() == 0 ? NULL : password.c_str());\n\n\t\t\t\treturn status;\n\t\t\t}\n\n\t\t\tpRdsAuthModuleEntry AuthModule::loadModuleEntry(std::string filename)\n\t\t\t{\n\t\t\t\tHINSTANCE library;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tlibrary = LoadLibraryA(filename.c_str());\n\n\t\t\t\tif (!library)\n\t\t\t\t\treturn (pRdsAuthModuleEntry) NULL;\n\n\t\t\t\tmoduleEntry = (pRdsAuthModuleEntry) GetProcAddress(library, RDS_AUTH_MODULE_ENTRY_POINT_NAME);\n\n\t\t\t\tif (moduleEntry)\n\t\t\t\t\treturn moduleEntry;\n\n\t\t\t\tFreeLibrary(library);\n\n\t\t\t\treturn (pRdsAuthModuleEntry) NULL;\n\t\t\t}\n\n\t\t\tAuthModule* AuthModule::loadFromFileName(std::string filename)\n\t\t\t{\n\t\t\t\tAuthModule* module;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tmoduleEntry = AuthModule::loadModuleEntry(filename.c_str());\n\n\t\t\t\tif (!moduleEntry)\n\t\t\t\t\treturn (AuthModule*) NULL;\n\n\t\t\t\tmodule = new AuthModule();\n\t\t\t\tmodule->initModule(moduleEntry);\n\n\t\t\t\treturn module;\n\t\t\t}\n\n\t\t\tAuthModule* AuthModule::loadFromName(std::string name)\n\t\t\t{\n\t\t\t\tint length;\n\t\t\t\tchar* filename;\n\t\t\t\tchar* lowerName;\n\t\t\t\tstd::string libraryPath;\n\t\t\t\tAuthModule* module;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tlibraryPath = APP_CONTEXT.getLibraryPath();\n\n\t\t\t\tlowerName = _strdup(name.c_str());\n\t\t\t\tCharLowerA(lowerName);\n\n\t\t\t\tlength = strlen(lowerName) + libraryPath.size() + 64;\n\t\t\t\tfilename = (char*) malloc(length + 1);\n\n\t\t\t\tsprintf_s(filename, length, \"%s\/libfreerds-auth-%s.so\", libraryPath.c_str(), lowerName);\n\t\t\t\tfree(lowerName);\n\n\t\t\t\tmodule = AuthModule::loadFromFileName(filename);\n\n\t\t\t\tfree(filename);\n\n\t\t\t\treturn module;\n\t\t\t}\n\t\t}\n\t}\n}\n\n<commit_msg>Prevented the LogonUser entry point from getting called if the username is empty.<commit_after>\/**\n * AuthModule\n *\n * Copyright 2013 Thincast Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <winpr\/crt.h>\n#include <winpr\/wlog.h>\n#include <winpr\/library.h>\n\n#include <freerds\/auth.h>\n\n#include \"appcontext\/ApplicationContext.h\"\n\n#include \"AuthModule.h\"\n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tnamespace module\n\t\t{\n\t\t\tstatic wLog* logger_Module = WLog_Get(\"freerds.sessionmanager.module.authmodule\");\n\n\t\t\tAuthModule::AuthModule()\n\t\t\t\t: mAuth(NULL),\n\t\t\t\t mModuleEntry(NULL)\n\t\t\t{\n\t\t\t\tZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));\n\t\t\t}\n\n\t\t\tint AuthModule::initModule(pRdsAuthModuleEntry moduleEntry)\n\t\t\t{\n\t\t\t\tint status = 0;\n\t\t\t\tmModuleEntry = moduleEntry;\n\n\t\t\t\tZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));\n\t\t\t\tmEntryPoints.Version = RDS_AUTH_MODULE_INTERFACE_VERSION;\n\n\t\t\t\tstatus = mModuleEntry(&mEntryPoints);\n\n\t\t\t\tif (status < 0)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tmAuth = mEntryPoints.New();\n\n\t\t\t\tif (!mAuth)\n\t\t\t\t\treturn -1;\n\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tAuthModule::~AuthModule()\n\t\t\t{\n\t\t\t\tif (mEntryPoints.Free)\n\t\t\t\t{\n\t\t\t\t\tmEntryPoints.Free(mAuth);\n\t\t\t\t\tmAuth = NULL;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint AuthModule::logonUser(std::string username, std::string domain, std::string password)\n\t\t\t{\n\t\t\t\tint status;\n\n\t\t\t\tif (!mEntryPoints.LogonUser)\n\t\t\t\t\treturn -1;\n\n\t\t\t\tif (username.empty())\n\t\t\t\t\treturn -1;\n\n\t\t\t\tstatus = mEntryPoints.LogonUser(mAuth, username.c_str(), domain.size() == 0 ? NULL : domain.c_str(), password.size() == 0 ? NULL : password.c_str());\n\n\t\t\t\treturn status;\n\t\t\t}\n\n\t\t\tpRdsAuthModuleEntry AuthModule::loadModuleEntry(std::string filename)\n\t\t\t{\n\t\t\t\tHINSTANCE library;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tlibrary = LoadLibraryA(filename.c_str());\n\n\t\t\t\tif (!library)\n\t\t\t\t\treturn (pRdsAuthModuleEntry) NULL;\n\n\t\t\t\tmoduleEntry = (pRdsAuthModuleEntry) GetProcAddress(library, RDS_AUTH_MODULE_ENTRY_POINT_NAME);\n\n\t\t\t\tif (moduleEntry)\n\t\t\t\t\treturn moduleEntry;\n\n\t\t\t\tFreeLibrary(library);\n\n\t\t\t\treturn (pRdsAuthModuleEntry) NULL;\n\t\t\t}\n\n\t\t\tAuthModule* AuthModule::loadFromFileName(std::string filename)\n\t\t\t{\n\t\t\t\tAuthModule* module;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tmoduleEntry = AuthModule::loadModuleEntry(filename.c_str());\n\n\t\t\t\tif (!moduleEntry)\n\t\t\t\t\treturn (AuthModule*) NULL;\n\n\t\t\t\tmodule = new AuthModule();\n\t\t\t\tmodule->initModule(moduleEntry);\n\n\t\t\t\treturn module;\n\t\t\t}\n\n\t\t\tAuthModule* AuthModule::loadFromName(std::string name)\n\t\t\t{\n\t\t\t\tint length;\n\t\t\t\tchar* filename;\n\t\t\t\tchar* lowerName;\n\t\t\t\tstd::string libraryPath;\n\t\t\t\tAuthModule* module;\n\t\t\t\tpRdsAuthModuleEntry moduleEntry;\n\n\t\t\t\tlibraryPath = APP_CONTEXT.getLibraryPath();\n\n\t\t\t\tlowerName = _strdup(name.c_str());\n\t\t\t\tCharLowerA(lowerName);\n\n\t\t\t\tlength = strlen(lowerName) + libraryPath.size() + 64;\n\t\t\t\tfilename = (char*) malloc(length + 1);\n\n\t\t\t\tsprintf_s(filename, length, \"%s\/libfreerds-auth-%s.so\", libraryPath.c_str(), lowerName);\n\t\t\t\tfree(lowerName);\n\n\t\t\t\tmodule = AuthModule::loadFromFileName(filename);\n\n\t\t\t\tfree(filename);\n\n\t\t\t\treturn module;\n\t\t\t}\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/password_manager_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#if defined(OS_WIN) && defined(USE_ASH)\n#include \"chrome\/browser\/ui\/ash\/ash_util.h\"\n#endif\n#include \"chrome\/browser\/ui\/passwords\/manage_passwords_view_utils.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"components\/autofill\/core\/common\/password_form.h\"\n#include \"components\/password_manager\/core\/common\/experiments.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace options {\n\nPasswordManagerHandler::PasswordManagerHandler()\n : password_manager_presenter_(this) {}\n\nPasswordManagerHandler::~PasswordManagerHandler() {}\n\nProfile* PasswordManagerHandler::GetProfile() {\n return Profile::FromWebUI(web_ui());\n}\n\n#if !defined(OS_ANDROID)\ngfx::NativeWindow PasswordManagerHandler::GetNativeWindow() const {\n return web_ui()->GetWebContents()->GetTopLevelNativeWindow();\n}\n#endif\n\nvoid PasswordManagerHandler::GetLocalizedValues(\n base::DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n\n static const OptionsStringResource resources[] = {\n { \"autoSigninTitle\",\n IDS_PASSWORDS_AUTO_SIGNIN_TITLE },\n { \"autoSigninDescription\",\n IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION },\n { \"savedPasswordsTitle\",\n IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },\n { \"passwordExceptionsTitle\",\n IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },\n { \"passwordSearchPlaceholder\",\n IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },\n { \"passwordShowButton\",\n IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },\n { \"passwordHideButton\",\n IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },\n { \"passwordsNoPasswordsDescription\",\n IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },\n { \"passwordsNoExceptionsDescription\",\n IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },\n };\n\n RegisterStrings(localized_strings, resources, arraysize(resources));\n RegisterTitle(localized_strings, \"passwordsPage\",\n IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);\n\n localized_strings->SetString(\"passwordManagerLearnMoreURL\",\n chrome::kPasswordManagerLearnMoreURL);\n localized_strings->SetString(\"passwordsManagePasswordsLink\",\n chrome::kPasswordManagerAccountDashboardURL);\n\n std::vector<base::string16> pieces;\n base::SplitStringDontTrim(\n l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_REMOTE_TEXT),\n '|', \/\/ separator\n &pieces);\n DCHECK_EQ(3U, pieces.size());\n localized_strings->SetString(\"passwordsManagePasswordsBeforeLinkText\",\n pieces[0]);\n localized_strings->SetString(\"passwordsManagePasswordsLinkText\", pieces[1]);\n localized_strings->SetString(\"passwordsManagePasswordsAfterLinkText\",\n pieces[2]);\n\n bool disable_show_passwords = false;\n\n#if defined(OS_WIN) && defined(USE_ASH)\n \/\/ We disable the ability to show passwords when running in Windows Metro\n \/\/ interface. This is because we cannot pop native Win32 dialogs from the\n \/\/ Metro process.\n \/\/ TODO(wfh): Revisit this if Metro usage grows.\n if (chrome::IsNativeWindowInAsh(GetNativeWindow()))\n disable_show_passwords = true;\n#endif\n\n localized_strings->SetBoolean(\"disableShowPasswords\", disable_show_passwords);\n localized_strings->SetBoolean(\n \"enableCredentialManagerAPI\",\n base::CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableCredentialManagerAPI));\n}\n\nvoid PasswordManagerHandler::RegisterMessages() {\n web_ui()->RegisterMessageCallback(\n \"updatePasswordLists\",\n base::Bind(&PasswordManagerHandler::HandleUpdatePasswordLists,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"removeSavedPassword\",\n base::Bind(&PasswordManagerHandler::HandleRemoveSavedPassword,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"removePasswordException\",\n base::Bind(&PasswordManagerHandler::HandleRemovePasswordException,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"requestShowPassword\",\n base::Bind(&PasswordManagerHandler::HandleRequestShowPassword,\n base::Unretained(this)));\n}\n\nvoid PasswordManagerHandler::InitializeHandler() {\n password_manager_presenter_.Initialize();\n}\n\nvoid PasswordManagerHandler::InitializePage() {\n base::FundamentalValue visible(\n password_manager::ManageAccountLinkExperimentEnabled());\n web_ui()->CallJavascriptFunction(\n \"PasswordManager.setManageAccountLinkVisibility\", visible);\n}\n\nvoid PasswordManagerHandler::HandleRemoveSavedPassword(\n const base::ListValue* args) {\n std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));\n int index;\n if (base::StringToInt(string_value, &index) && index >= 0) {\n password_manager_presenter_.RemoveSavedPassword(static_cast<size_t>(index));\n }\n}\n\nvoid PasswordManagerHandler::HandleRemovePasswordException(\n const base::ListValue* args) {\n std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));\n int index;\n if (base::StringToInt(string_value, &index) && index >= 0) {\n password_manager_presenter_.RemovePasswordException(\n static_cast<size_t>(index));\n }\n}\n\nvoid PasswordManagerHandler::HandleRequestShowPassword(\n const base::ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index))\n NOTREACHED();\n\n password_manager_presenter_.RequestShowPassword(static_cast<size_t>(index));\n}\n\nvoid PasswordManagerHandler::ShowPassword(\n size_t index,\n const base::string16& password_value) {\n \/\/ Call back the front end to reveal the password.\n web_ui()->CallJavascriptFunction(\n \"PasswordManager.showPassword\",\n base::FundamentalValue(static_cast<int>(index)),\n base::StringValue(password_value));\n}\n\nvoid PasswordManagerHandler::HandleUpdatePasswordLists(\n const base::ListValue* args) {\n password_manager_presenter_.UpdatePasswordLists();\n}\n\nvoid PasswordManagerHandler::SetPasswordList(\n const ScopedVector<autofill::PasswordForm>& password_list,\n bool show_passwords) {\n base::ListValue entries;\n languages_ = GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);\n base::string16 placeholder(base::ASCIIToUTF16(\" \"));\n for (size_t i = 0; i < password_list.size(); ++i) {\n base::ListValue* entry = new base::ListValue();\n entry->AppendString(GetHumanReadableOrigin(*password_list[i], languages_));\n entry->AppendString(password_list[i]->username_value);\n if (show_passwords) {\n entry->AppendString(password_list[i]->password_value);\n } else {\n \/\/ Use a placeholder value with the same length as the password.\n entry->AppendString(\n base::string16(password_list[i]->password_value.length(), ' '));\n }\n const GURL& federation_url = password_list[i]->federation_url;\n if (!federation_url.is_empty()) {\n entry->AppendString(l10n_util::GetStringFUTF16(\n IDS_PASSWORDS_VIA_FEDERATION,\n base::UTF8ToUTF16(federation_url.host())));\n }\n entries.Append(entry);\n }\n\n web_ui()->CallJavascriptFunction(\"PasswordManager.setSavedPasswordsList\",\n entries);\n}\n\nvoid PasswordManagerHandler::SetPasswordExceptionList(\n const ScopedVector<autofill::PasswordForm>& password_exception_list) {\n base::ListValue entries;\n for (size_t i = 0; i < password_exception_list.size(); ++i) {\n entries.Append(new base::StringValue(\n net::FormatUrl(password_exception_list[i]->origin, languages_)));\n }\n\n web_ui()->CallJavascriptFunction(\"PasswordManager.setPasswordExceptionsList\",\n entries);\n}\n\n} \/\/ namespace options\n<commit_msg>Prettify URIs for blacklisted entries on the chrome:\/\/settings\/passwords page.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/password_manager_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#if defined(OS_WIN) && defined(USE_ASH)\n#include \"chrome\/browser\/ui\/ash\/ash_util.h\"\n#endif\n#include \"chrome\/browser\/ui\/passwords\/manage_passwords_view_utils.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"components\/autofill\/core\/common\/password_form.h\"\n#include \"components\/password_manager\/core\/common\/experiments.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace options {\n\nPasswordManagerHandler::PasswordManagerHandler()\n : password_manager_presenter_(this) {}\n\nPasswordManagerHandler::~PasswordManagerHandler() {}\n\nProfile* PasswordManagerHandler::GetProfile() {\n return Profile::FromWebUI(web_ui());\n}\n\n#if !defined(OS_ANDROID)\ngfx::NativeWindow PasswordManagerHandler::GetNativeWindow() const {\n return web_ui()->GetWebContents()->GetTopLevelNativeWindow();\n}\n#endif\n\nvoid PasswordManagerHandler::GetLocalizedValues(\n base::DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n\n static const OptionsStringResource resources[] = {\n { \"autoSigninTitle\",\n IDS_PASSWORDS_AUTO_SIGNIN_TITLE },\n { \"autoSigninDescription\",\n IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION },\n { \"savedPasswordsTitle\",\n IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },\n { \"passwordExceptionsTitle\",\n IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },\n { \"passwordSearchPlaceholder\",\n IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },\n { \"passwordShowButton\",\n IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },\n { \"passwordHideButton\",\n IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },\n { \"passwordsNoPasswordsDescription\",\n IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },\n { \"passwordsNoExceptionsDescription\",\n IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },\n };\n\n RegisterStrings(localized_strings, resources, arraysize(resources));\n RegisterTitle(localized_strings, \"passwordsPage\",\n IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);\n\n localized_strings->SetString(\"passwordManagerLearnMoreURL\",\n chrome::kPasswordManagerLearnMoreURL);\n localized_strings->SetString(\"passwordsManagePasswordsLink\",\n chrome::kPasswordManagerAccountDashboardURL);\n\n std::vector<base::string16> pieces;\n base::SplitStringDontTrim(\n l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_REMOTE_TEXT),\n '|', \/\/ separator\n &pieces);\n DCHECK_EQ(3U, pieces.size());\n localized_strings->SetString(\"passwordsManagePasswordsBeforeLinkText\",\n pieces[0]);\n localized_strings->SetString(\"passwordsManagePasswordsLinkText\", pieces[1]);\n localized_strings->SetString(\"passwordsManagePasswordsAfterLinkText\",\n pieces[2]);\n\n bool disable_show_passwords = false;\n\n#if defined(OS_WIN) && defined(USE_ASH)\n \/\/ We disable the ability to show passwords when running in Windows Metro\n \/\/ interface. This is because we cannot pop native Win32 dialogs from the\n \/\/ Metro process.\n \/\/ TODO(wfh): Revisit this if Metro usage grows.\n if (chrome::IsNativeWindowInAsh(GetNativeWindow()))\n disable_show_passwords = true;\n#endif\n\n localized_strings->SetBoolean(\"disableShowPasswords\", disable_show_passwords);\n localized_strings->SetBoolean(\n \"enableCredentialManagerAPI\",\n base::CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableCredentialManagerAPI));\n}\n\nvoid PasswordManagerHandler::RegisterMessages() {\n web_ui()->RegisterMessageCallback(\n \"updatePasswordLists\",\n base::Bind(&PasswordManagerHandler::HandleUpdatePasswordLists,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"removeSavedPassword\",\n base::Bind(&PasswordManagerHandler::HandleRemoveSavedPassword,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"removePasswordException\",\n base::Bind(&PasswordManagerHandler::HandleRemovePasswordException,\n base::Unretained(this)));\n web_ui()->RegisterMessageCallback(\n \"requestShowPassword\",\n base::Bind(&PasswordManagerHandler::HandleRequestShowPassword,\n base::Unretained(this)));\n}\n\nvoid PasswordManagerHandler::InitializeHandler() {\n password_manager_presenter_.Initialize();\n}\n\nvoid PasswordManagerHandler::InitializePage() {\n base::FundamentalValue visible(\n password_manager::ManageAccountLinkExperimentEnabled());\n web_ui()->CallJavascriptFunction(\n \"PasswordManager.setManageAccountLinkVisibility\", visible);\n}\n\nvoid PasswordManagerHandler::HandleRemoveSavedPassword(\n const base::ListValue* args) {\n std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));\n int index;\n if (base::StringToInt(string_value, &index) && index >= 0) {\n password_manager_presenter_.RemoveSavedPassword(static_cast<size_t>(index));\n }\n}\n\nvoid PasswordManagerHandler::HandleRemovePasswordException(\n const base::ListValue* args) {\n std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));\n int index;\n if (base::StringToInt(string_value, &index) && index >= 0) {\n password_manager_presenter_.RemovePasswordException(\n static_cast<size_t>(index));\n }\n}\n\nvoid PasswordManagerHandler::HandleRequestShowPassword(\n const base::ListValue* args) {\n int index;\n if (!ExtractIntegerValue(args, &index))\n NOTREACHED();\n\n password_manager_presenter_.RequestShowPassword(static_cast<size_t>(index));\n}\n\nvoid PasswordManagerHandler::ShowPassword(\n size_t index,\n const base::string16& password_value) {\n \/\/ Call back the front end to reveal the password.\n web_ui()->CallJavascriptFunction(\n \"PasswordManager.showPassword\",\n base::FundamentalValue(static_cast<int>(index)),\n base::StringValue(password_value));\n}\n\nvoid PasswordManagerHandler::HandleUpdatePasswordLists(\n const base::ListValue* args) {\n password_manager_presenter_.UpdatePasswordLists();\n}\n\nvoid PasswordManagerHandler::SetPasswordList(\n const ScopedVector<autofill::PasswordForm>& password_list,\n bool show_passwords) {\n base::ListValue entries;\n languages_ = GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);\n base::string16 placeholder(base::ASCIIToUTF16(\" \"));\n for (size_t i = 0; i < password_list.size(); ++i) {\n base::ListValue* entry = new base::ListValue();\n entry->AppendString(GetHumanReadableOrigin(*password_list[i], languages_));\n entry->AppendString(password_list[i]->username_value);\n if (show_passwords) {\n entry->AppendString(password_list[i]->password_value);\n } else {\n \/\/ Use a placeholder value with the same length as the password.\n entry->AppendString(\n base::string16(password_list[i]->password_value.length(), ' '));\n }\n const GURL& federation_url = password_list[i]->federation_url;\n if (!federation_url.is_empty()) {\n entry->AppendString(l10n_util::GetStringFUTF16(\n IDS_PASSWORDS_VIA_FEDERATION,\n base::UTF8ToUTF16(federation_url.host())));\n }\n entries.Append(entry);\n }\n\n web_ui()->CallJavascriptFunction(\"PasswordManager.setSavedPasswordsList\",\n entries);\n}\n\nvoid PasswordManagerHandler::SetPasswordExceptionList(\n const ScopedVector<autofill::PasswordForm>& password_exception_list) {\n base::ListValue entries;\n for (size_t i = 0; i < password_exception_list.size(); ++i) {\n entries.AppendString(\n GetHumanReadableOrigin(*password_exception_list[i], languages_));\n }\n\n web_ui()->CallJavascriptFunction(\"PasswordManager.setPasswordExceptionsList\",\n entries);\n}\n\n} \/\/ namespace options\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options2\/options_ui2_browsertest.h\"\n\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace options2 {\n\nOptionsBrowserTest::OptionsBrowserTest() {\n EnableDOMAutomation();\n}\n\nvoid OptionsBrowserTest::NavigateToSettings() {\n const GURL& url = GURL(chrome::kChromeUISettingsURL);\n ui_test_utils::NavigateToURL(browser(), url);\n}\n\nvoid OptionsBrowserTest::VerifyNavbar() {\n bool navbar_exist = false;\n EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedWebContents()->GetRenderViewHost(),\n L\"\",\n L\"domAutomationController.send(\"\n L\"!!document.getElementById('navigation'))\", &navbar_exist));\n EXPECT_EQ(true, navbar_exist);\n}\n\nvoid OptionsBrowserTest::VerifyTitle() {\n string16 title = browser()->GetSelectedWebContents()->GetTitle();\n string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);\n EXPECT_NE(title.find(expected_title), string16::npos);\n}\n\n\/\/ If this flakes, use http:\/\/crbug.com\/119671\nIN_PROC_BROWSER_TEST_F(OptionsBrowserTest, LoadOptionsByURL) {\n NavigateToSettings();\n VerifyTitle();\n VerifyNavbar();\n}\n\n} \/\/ namespace options2\n<commit_msg>Mark OptionsBrowserTest.LoadOptionsByURL flaky on Win and Mac<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options2\/options_ui2_browsertest.h\"\n\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace options2 {\n\nOptionsBrowserTest::OptionsBrowserTest() {\n EnableDOMAutomation();\n}\n\nvoid OptionsBrowserTest::NavigateToSettings() {\n const GURL& url = GURL(chrome::kChromeUISettingsURL);\n ui_test_utils::NavigateToURL(browser(), url);\n}\n\nvoid OptionsBrowserTest::VerifyNavbar() {\n bool navbar_exist = false;\n EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedWebContents()->GetRenderViewHost(),\n L\"\",\n L\"domAutomationController.send(\"\n L\"!!document.getElementById('navigation'))\", &navbar_exist));\n EXPECT_EQ(true, navbar_exist);\n}\n\nvoid OptionsBrowserTest::VerifyTitle() {\n string16 title = browser()->GetSelectedWebContents()->GetTitle();\n string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);\n EXPECT_NE(title.find(expected_title), string16::npos);\n}\n\n\/\/ Observed flaky on Win and Mac, see http:\/\/crbug.com\/119671.\n#if defined(OS_WIN) || defined(OS_MACOSX)\n#define MAYBE_LoadOptionsByURL FLAKY_LoadOptionsByURL\n#else\n#define MAYBE_LoadOptionsByURL LoadOptionsByURL\n#endif\n\nIN_PROC_BROWSER_TEST_F(OptionsBrowserTest, MAYBE_LoadOptionsByURL) {\n NavigateToSettings();\n VerifyTitle();\n VerifyNavbar();\n}\n\n} \/\/ namespace options2\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ZipPackageStream.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: mtg $ $Date: 2001-11-15 20:27:48 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_STREAM_HXX\n#define _ZIP_PACKAGE_STREAM_HXX\n\n#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_\n#include <com\/sun\/star\/io\/XActiveDataSink.hpp>\n#endif\n#ifndef _ZIP_PACKAGE_ENTRY_HXX\n#include <ZipPackageEntry.hxx>\n#endif\n#ifndef _VOS_REF_H_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _ENCRYPTION_DATA_HXX_\n#include <EncryptionData.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n\nclass ZipPackage;\nstruct ZipEntry;\nclass ZipPackageStream : public cppu::ImplInheritanceHelper1\n<\n ZipPackageEntry,\n ::com::sun::star::io::XActiveDataSink\n>\n{\n static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;\nprotected:\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;\n ZipPackage &rZipPackage;\n sal_Bool bToBeCompressed, bToBeEncrypted, bPackageMember, bHaveOwnKey, bIsEncrypted;\n vos::ORef < EncryptionData > xEncryptionData;\npublic:\n sal_Bool HasOwnKey () { return bHaveOwnKey;}\n sal_Bool IsToBeCompressed () { return bToBeCompressed;}\n sal_Bool IsToBeEncrypted () { return bToBeEncrypted;}\n sal_Bool IsEncrypted () { return bIsEncrypted;}\n sal_Bool IsPackageMember () { return bPackageMember;}\n vos::ORef < EncryptionData > & getEncryptionData ()\n { return xEncryptionData;}\n const com::sun::star::uno::Sequence < sal_Int8 >& getKey ()\n { return xEncryptionData->aKey;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector ()\n { return xEncryptionData->aInitVector;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest ()\n { return xEncryptionData->aDigest;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt ()\n { return xEncryptionData->aSalt;}\n const sal_Int32 getIterationCount ()\n { return xEncryptionData->nIterationCount;}\n const sal_Int32 getSize ()\n { return aEntry.nSize;}\n\n void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;}\n void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;}\n void SetToBeEncrypted (sal_Bool bNewValue)\n {\n bToBeEncrypted = bNewValue;\n if ( bToBeEncrypted && xEncryptionData.isEmpty())\n xEncryptionData = new EncryptionData;\n else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() )\n xEncryptionData.unbind();\n }\n void SetPackageMember (sal_Bool bNewValue) { bPackageMember = bNewValue;}\n void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey )\n { xEncryptionData->aKey = rNewKey;}\n void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector )\n { xEncryptionData->aInitVector = rNewVector;}\n void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt )\n { xEncryptionData->aSalt = rNewSalt;}\n void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest )\n { xEncryptionData->aDigest = rNewDigest;}\n void setIterationCount (const sal_Int32 nNewCount)\n { xEncryptionData->nIterationCount = nNewCount;}\n void setSize (const sal_Int32 nNewSize);\n\n ZipPackageStream (ZipPackage & rNewPackage);\n virtual ~ZipPackageStream( void );\n\n void setZipEntry( const ZipEntry &rInEntry);\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream( )\n throw(::com::sun::star::uno::RuntimeException);\n\n static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId()\n {\n return aImplementationId;\n }\n\n \/\/ XActiveDataSink\n virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw (::com::sun::star::uno::RuntimeException);\n};\n#endif\n<commit_msg>#101685#,#i6886# merge OOO_STABLE_1_PORTS (1.11-1.11.10.1) -> HEAD<commit_after>\/*************************************************************************\n *\n * $RCSfile: ZipPackageStream.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2002-08-20 13:04:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_PACKAGE_STREAM_HXX\n#define _ZIP_PACKAGE_STREAM_HXX\n\n#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_\n#include <com\/sun\/star\/io\/XActiveDataSink.hpp>\n#endif\n#ifndef _ZIP_PACKAGE_ENTRY_HXX\n#include <ZipPackageEntry.hxx>\n#endif\n#ifndef _VOS_REF_H_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _ENCRYPTION_DATA_HXX_\n#include <EncryptionData.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n\nclass ZipPackage;\nstruct ZipEntry;\n#ifdef MACOSX\nclass ZipPackageStream : public ZipPackageEntry,\n public ::cppu::OWeakObject,\n public ::com::sun::star::io::XActiveDataSink\n#else\nclass ZipPackageStream : public cppu::ImplInheritanceHelper1\n<\n ZipPackageEntry,\n ::com::sun::star::io::XActiveDataSink\n>\n#endif\n{\n static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;\nprotected:\n com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;\n ZipPackage &rZipPackage;\n sal_Bool bToBeCompressed, bToBeEncrypted, bPackageMember, bHaveOwnKey, bIsEncrypted;\n vos::ORef < EncryptionData > xEncryptionData;\npublic:\n sal_Bool HasOwnKey () { return bHaveOwnKey;}\n sal_Bool IsToBeCompressed () { return bToBeCompressed;}\n sal_Bool IsToBeEncrypted () { return bToBeEncrypted;}\n sal_Bool IsEncrypted () { return bIsEncrypted;}\n sal_Bool IsPackageMember () { return bPackageMember;}\n vos::ORef < EncryptionData > & getEncryptionData ()\n { return xEncryptionData;}\n const com::sun::star::uno::Sequence < sal_Int8 >& getKey ()\n { return xEncryptionData->aKey;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector ()\n { return xEncryptionData->aInitVector;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest ()\n { return xEncryptionData->aDigest;}\n const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt ()\n { return xEncryptionData->aSalt;}\n const sal_Int32 getIterationCount ()\n { return xEncryptionData->nIterationCount;}\n const sal_Int32 getSize ()\n { return aEntry.nSize;}\n\n void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;}\n void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;}\n void SetToBeEncrypted (sal_Bool bNewValue)\n {\n bToBeEncrypted = bNewValue;\n if ( bToBeEncrypted && xEncryptionData.isEmpty())\n xEncryptionData = new EncryptionData;\n else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() )\n xEncryptionData.unbind();\n }\n void SetPackageMember (sal_Bool bNewValue) { bPackageMember = bNewValue;}\n void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey )\n { xEncryptionData->aKey = rNewKey;}\n void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector )\n { xEncryptionData->aInitVector = rNewVector;}\n void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt )\n { xEncryptionData->aSalt = rNewSalt;}\n void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest )\n { xEncryptionData->aDigest = rNewDigest;}\n void setIterationCount (const sal_Int32 nNewCount)\n { xEncryptionData->nIterationCount = nNewCount;}\n void setSize (const sal_Int32 nNewSize);\n\n ZipPackageStream (ZipPackage & rNewPackage);\n virtual ~ZipPackageStream( void );\n\n void setZipEntry( const ZipEntry &rInEntry);\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream( )\n throw(::com::sun::star::uno::RuntimeException);\n\n static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId()\n {\n return aImplementationId;\n }\n\n#ifdef MACOSX\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire( )\n throw();\n virtual void SAL_CALL release( )\n throw();\n#endif\n\n \/\/ XActiveDataSink\n virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw (::com::sun::star::uno::RuntimeException);\n};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Jia Haipeng, jiahaipeng95@gmail.com\n\/\/ Xiaopeng Fu, xiaopeng@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other oclMaterials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"precomp.hpp\"\n#include <vector>\n\nusing namespace cv;\nusing namespace cv::ocl;\nusing namespace std;\n\n\nnamespace cv\n{\nnamespace ocl\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/OpenCL kernel strings\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern const char *stereobm;\n\n}\n}\nnamespace cv\n{\nnamespace ocl\n{\nnamespace stereoBM\n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/prefilter_xsbel\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid prefilter_xsobel(const oclMat &input, oclMat &output, int prefilterCap)\n{\n Context *clCxt = input.clCxt;\n\n string kernelName = \"prefilter_xsobel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n size_t blockSize = 1;\n size_t globalThreads[3] = { input.cols, input.rows, 1 };\n size_t localThreads[3] = { blockSize, blockSize, 1 };\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&input.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&output.data));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&input.rows));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&input.cols));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_int), (void *)&prefilterCap));\n\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/common\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define N_DISPARITIES 8\n#define ROWSperTHREAD 21\n#define BLOCK_W 128\nstatic inline int divUp(int total, int grain)\n{\n return (total + grain - 1) \/ grain;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/stereoBM_GPU\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid stereo_bm(const oclMat &left, const oclMat &right, oclMat &disp,\n int maxdisp, int winSize, oclMat &minSSD_buf)\n{\n int winsz2 = winSize >> 1;\n\n \/\/if(winsz2 == 0 || winsz2 >= calles_num)\n \/\/cv::ocl:error(\"Unsupported window size\", __FILE__, __LINE__, __FUNCTION__);\n\n Context *clCxt = left.clCxt;\n\n string kernelName = \"stereoKernel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n disp.setTo(Scalar_<unsigned char>::all(0));\n minSSD_buf.setTo(Scalar_<unsigned int>::all(0xFFFFFFFF));\n\n size_t minssd_step = minSSD_buf.step \/ minSSD_buf.elemSize();\n size_t local_mem_size = (BLOCK_W + N_DISPARITIES * (BLOCK_W + 2 * winsz2)) *\n sizeof(cl_uint);\n \/\/size_t blockSize = 1;\n size_t localThreads[] = { BLOCK_W, 1,1};\n size_t globalThreads[] = { divUp(left.cols - maxdisp - 2 * winsz2, BLOCK_W) *BLOCK_W,\n divUp(left.rows - 2 * winsz2, ROWSperTHREAD),\n 1\n };\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&left.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&right.data));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&minSSD_buf.data));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&minssd_step));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *)&disp.data));\n openCLSafeCall(clSetKernelArg(kernel, 5, sizeof(cl_int), (void *)&disp.step));\n openCLSafeCall(clSetKernelArg(kernel, 6, sizeof(cl_int), (void *)&left.cols));\n openCLSafeCall(clSetKernelArg(kernel, 7, sizeof(cl_int), (void *)&left.rows));\n openCLSafeCall(clSetKernelArg(kernel, 8, sizeof(cl_int), (void *)&left.step));\n openCLSafeCall(clSetKernelArg(kernel, 9, sizeof(cl_int), (void *)&maxdisp));\n openCLSafeCall(clSetKernelArg(kernel, 10, sizeof(cl_int), (void *)&winsz2));\n openCLSafeCall(clSetKernelArg(kernel, 11, local_mem_size, (void *)NULL));\n\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 2, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/postfilter_textureness\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid postfilter_textureness(oclMat &left, int winSize,\n float avergeTexThreshold, oclMat &disparity)\n{\n Context *clCxt = left.clCxt;\n\n string kernelName = \"textureness_kernel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n size_t blockSize = 1;\n size_t localThreads[] = { BLOCK_W, blockSize ,1};\n size_t globalThreads[] = { divUp(left.cols, BLOCK_W) *BLOCK_W,\n divUp(left.rows, 2 * ROWSperTHREAD),\n 1\n };\n\n size_t local_mem_size = (localThreads[0] + localThreads[0] + (winSize \/ 2) * 2) * sizeof(float);\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&disparity.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_int), (void *)&disparity.rows));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&disparity.cols));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&disparity.step));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *)&left.data));\n openCLSafeCall(clSetKernelArg(kernel, 5, sizeof(cl_int), (void *)&left.rows));\n openCLSafeCall(clSetKernelArg(kernel, 6, sizeof(cl_int), (void *)&left.cols));\n openCLSafeCall(clSetKernelArg(kernel, 7, sizeof(cl_int), (void *)&winSize));\n openCLSafeCall(clSetKernelArg(kernel, 8, sizeof(cl_float), (void *)&avergeTexThreshold));\n openCLSafeCall(clSetKernelArg(kernel, 9, local_mem_size, NULL));\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 2, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/operator\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid operator_(oclMat &minSSD, oclMat &leBuf, oclMat &riBuf, int preset, int ndisp,\n int winSize, float avergeTexThreshold, const oclMat &left,\n const oclMat &right, oclMat &disparity)\n\n{\n CV_DbgAssert(left.rows == right.rows && left.cols == right.cols);\n CV_DbgAssert(left.type() == CV_8UC1);\n CV_DbgAssert(right.type() == CV_8UC1);\n\n disparity.create(left.size(), CV_8UC1);\n minSSD.create(left.size(), CV_32SC1);\n\n oclMat le_for_bm = left;\n oclMat ri_for_bm = right;\n\n if (preset == cv::ocl::StereoBM_OCL::PREFILTER_XSOBEL)\n {\n leBuf.create( left.size(), left.type());\n riBuf.create(right.size(), right.type());\n\n prefilter_xsobel( left, leBuf, 31);\n prefilter_xsobel(right, riBuf, 31);\n\n le_for_bm = leBuf;\n ri_for_bm = riBuf;\n }\n\n stereo_bm(le_for_bm, ri_for_bm, disparity, ndisp, winSize, minSSD);\n\n if (avergeTexThreshold)\n {\n postfilter_textureness(le_for_bm, winSize, avergeTexThreshold, disparity);\n }\n}\n}\n}\n}\nconst float defaultAvgTexThreshold = 3;\n\ncv::ocl::StereoBM_OCL::StereoBM_OCL()\n : preset(BASIC_PRESET), ndisp(DEFAULT_NDISP), winSize(DEFAULT_WINSZ),\n avergeTexThreshold(defaultAvgTexThreshold) {}\n\ncv::ocl::StereoBM_OCL::StereoBM_OCL(int preset_, int ndisparities_, int winSize_)\n : preset(preset_), ndisp(ndisparities_), winSize(winSize_),\n avergeTexThreshold(defaultAvgTexThreshold)\n{\n const int max_supported_ndisp = 1 << (sizeof(unsigned char) * 8);\n CV_Assert(0 < ndisp && ndisp <= max_supported_ndisp);\n CV_Assert(ndisp % 8 == 0);\n CV_Assert(winSize % 2 == 1);\n}\n\nbool cv::ocl::StereoBM_OCL::checkIfGpuCallReasonable()\n{\n return true;\n}\n\nvoid cv::ocl::StereoBM_OCL::operator() ( const oclMat &left, const oclMat &right,\n oclMat &disparity)\n{\n cv::ocl::stereoBM::operator_(minSSD, leBuf, riBuf, preset, ndisp, winSize, avergeTexThreshold, left, right, disparity);\n}\n\n<commit_msg>fix warnings on Linux<commit_after>\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Jia Haipeng, jiahaipeng95@gmail.com\n\/\/ Xiaopeng Fu, xiaopeng@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other oclMaterials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"precomp.hpp\"\n#include <vector>\n\nusing namespace cv;\nusing namespace cv::ocl;\nusing namespace std;\n\n\nnamespace cv\n{\nnamespace ocl\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/OpenCL kernel strings\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nextern const char *stereobm;\n\n}\n}\nnamespace cv\n{\nnamespace ocl\n{\nnamespace stereoBM\n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/prefilter_xsbel\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void prefilter_xsobel(const oclMat &input, oclMat &output, int prefilterCap)\n{\n Context *clCxt = input.clCxt;\n\n string kernelName = \"prefilter_xsobel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n size_t blockSize = 1;\n size_t globalThreads[3] = { input.cols, input.rows, 1 };\n size_t localThreads[3] = { blockSize, blockSize, 1 };\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&input.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&output.data));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&input.rows));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&input.cols));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_int), (void *)&prefilterCap));\n\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 3, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/common\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define N_DISPARITIES 8\n#define ROWSperTHREAD 21\n#define BLOCK_W 128\nstatic inline int divUp(int total, int grain)\n{\n return (total + grain - 1) \/ grain;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/stereoBM_GPU\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void stereo_bm(const oclMat &left, const oclMat &right, oclMat &disp,\n int maxdisp, int winSize, oclMat &minSSD_buf)\n{\n int winsz2 = winSize >> 1;\n\n \/\/if(winsz2 == 0 || winsz2 >= calles_num)\n \/\/cv::ocl:error(\"Unsupported window size\", __FILE__, __LINE__, __FUNCTION__);\n\n Context *clCxt = left.clCxt;\n\n string kernelName = \"stereoKernel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n disp.setTo(Scalar_<unsigned char>::all(0));\n minSSD_buf.setTo(Scalar_<unsigned int>::all(0xFFFFFFFF));\n\n size_t minssd_step = minSSD_buf.step \/ minSSD_buf.elemSize();\n size_t local_mem_size = (BLOCK_W + N_DISPARITIES * (BLOCK_W + 2 * winsz2)) *\n sizeof(cl_uint);\n \/\/size_t blockSize = 1;\n size_t localThreads[] = { BLOCK_W, 1,1};\n size_t globalThreads[] = { divUp(left.cols - maxdisp - 2 * winsz2, BLOCK_W) *BLOCK_W,\n divUp(left.rows - 2 * winsz2, ROWSperTHREAD),\n 1\n };\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&left.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&right.data));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&minSSD_buf.data));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&minssd_step));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *)&disp.data));\n openCLSafeCall(clSetKernelArg(kernel, 5, sizeof(cl_int), (void *)&disp.step));\n openCLSafeCall(clSetKernelArg(kernel, 6, sizeof(cl_int), (void *)&left.cols));\n openCLSafeCall(clSetKernelArg(kernel, 7, sizeof(cl_int), (void *)&left.rows));\n openCLSafeCall(clSetKernelArg(kernel, 8, sizeof(cl_int), (void *)&left.step));\n openCLSafeCall(clSetKernelArg(kernel, 9, sizeof(cl_int), (void *)&maxdisp));\n openCLSafeCall(clSetKernelArg(kernel, 10, sizeof(cl_int), (void *)&winsz2));\n openCLSafeCall(clSetKernelArg(kernel, 11, local_mem_size, (void *)NULL));\n\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 2, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/postfilter_textureness\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void postfilter_textureness(oclMat &left, int winSize,\n float avergeTexThreshold, oclMat &disparity)\n{\n Context *clCxt = left.clCxt;\n\n string kernelName = \"textureness_kernel\";\n cl_kernel kernel = openCLGetKernelFromSource(clCxt, &stereobm, kernelName);\n\n size_t blockSize = 1;\n size_t localThreads[] = { BLOCK_W, blockSize ,1};\n size_t globalThreads[] = { divUp(left.cols, BLOCK_W) *BLOCK_W,\n divUp(left.rows, 2 * ROWSperTHREAD),\n 1\n };\n\n size_t local_mem_size = (localThreads[0] + localThreads[0] + (winSize \/ 2) * 2) * sizeof(float);\n\n openCLVerifyKernel(clCxt, kernel, localThreads);\n openCLSafeCall(clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&disparity.data));\n openCLSafeCall(clSetKernelArg(kernel, 1, sizeof(cl_int), (void *)&disparity.rows));\n openCLSafeCall(clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&disparity.cols));\n openCLSafeCall(clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&disparity.step));\n openCLSafeCall(clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *)&left.data));\n openCLSafeCall(clSetKernelArg(kernel, 5, sizeof(cl_int), (void *)&left.rows));\n openCLSafeCall(clSetKernelArg(kernel, 6, sizeof(cl_int), (void *)&left.cols));\n openCLSafeCall(clSetKernelArg(kernel, 7, sizeof(cl_int), (void *)&winSize));\n openCLSafeCall(clSetKernelArg(kernel, 8, sizeof(cl_float), (void *)&avergeTexThreshold));\n openCLSafeCall(clSetKernelArg(kernel, 9, local_mem_size, NULL));\n openCLSafeCall(clEnqueueNDRangeKernel(clCxt->impl->clCmdQueue, kernel, 2, NULL,\n globalThreads, localThreads, 0, NULL, NULL));\n\n clFinish(clCxt->impl->clCmdQueue);\n openCLSafeCall(clReleaseKernel(kernel));\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/operator\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void operator_(oclMat &minSSD, oclMat &leBuf, oclMat &riBuf, int preset, int ndisp,\n int winSize, float avergeTexThreshold, const oclMat &left,\n const oclMat &right, oclMat &disparity)\n\n{\n CV_DbgAssert(left.rows == right.rows && left.cols == right.cols);\n CV_DbgAssert(left.type() == CV_8UC1);\n CV_DbgAssert(right.type() == CV_8UC1);\n\n disparity.create(left.size(), CV_8UC1);\n minSSD.create(left.size(), CV_32SC1);\n\n oclMat le_for_bm = left;\n oclMat ri_for_bm = right;\n\n if (preset == cv::ocl::StereoBM_OCL::PREFILTER_XSOBEL)\n {\n leBuf.create( left.size(), left.type());\n riBuf.create(right.size(), right.type());\n\n prefilter_xsobel( left, leBuf, 31);\n prefilter_xsobel(right, riBuf, 31);\n\n le_for_bm = leBuf;\n ri_for_bm = riBuf;\n }\n\n stereo_bm(le_for_bm, ri_for_bm, disparity, ndisp, winSize, minSSD);\n\n if (avergeTexThreshold)\n {\n postfilter_textureness(le_for_bm, winSize, avergeTexThreshold, disparity);\n }\n}\n}\n}\n}\nconst float defaultAvgTexThreshold = 3;\n\ncv::ocl::StereoBM_OCL::StereoBM_OCL()\n : preset(BASIC_PRESET), ndisp(DEFAULT_NDISP), winSize(DEFAULT_WINSZ),\n avergeTexThreshold(defaultAvgTexThreshold) {}\n\ncv::ocl::StereoBM_OCL::StereoBM_OCL(int preset_, int ndisparities_, int winSize_)\n : preset(preset_), ndisp(ndisparities_), winSize(winSize_),\n avergeTexThreshold(defaultAvgTexThreshold)\n{\n const int max_supported_ndisp = 1 << (sizeof(unsigned char) * 8);\n CV_Assert(0 < ndisp && ndisp <= max_supported_ndisp);\n CV_Assert(ndisp % 8 == 0);\n CV_Assert(winSize % 2 == 1);\n}\n\nbool cv::ocl::StereoBM_OCL::checkIfGpuCallReasonable()\n{\n return true;\n}\n\nvoid cv::ocl::StereoBM_OCL::operator() ( const oclMat &left, const oclMat &right,\n oclMat &disparity)\n{\n cv::ocl::stereoBM::operator_(minSSD, leBuf, riBuf, preset, ndisp, winSize, avergeTexThreshold, left, right, disparity);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/planning.h\"\n\n#include <algorithm>\n\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/planner\/em\/em_planner.h\"\n#include \"modules\/planning\/planner\/rtk\/rtk_replay_planner.h\"\n#include \"modules\/planning\/trajectory_stitcher\/trajectory_stitcher.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::VehicleState;\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::time::Clock;\n\nstd::string Planning::Name() const { return \"planning\"; }\n\nvoid Planning::RegisterPlanners() {\n planner_factory_.Register(\n PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });\n planner_factory_.Register(PlanningConfig::EM,\n []() -> Planner* { return new EMPlanner(); });\n}\n\nconst Frame* Planning::GetFrame() const { return frame_.get(); }\nconst hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); }\n\nbool Planning::InitFrame(const uint32_t sequence_num) {\n frame_.reset(new Frame(sequence_num));\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"Routing is empty\";\n return false;\n }\n common::TrajectoryPoint point;\n frame_->SetVehicleInitPose(VehicleState::instance()->pose());\n frame_->SetRoutingResult(\n AdapterManager::GetRoutingResult()->GetLatestObserved());\n if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) {\n const auto& prediction =\n AdapterManager::GetPrediction()->GetLatestObserved();\n frame_->SetPrediction(prediction);\n ADEBUG << \"Get prediction\";\n }\n\n if (!frame_->Init()) {\n AERROR << \"failed to init frame\";\n return false;\n }\n return true;\n}\n\nStatus Planning::Init() {\n pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename));\n Frame::SetMap(pnc_map_.get());\n\n if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_)) {\n AERROR << \"failed to load planning config file \"\n << FLAGS_planning_config_file;\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"failed to load planning config file: \" + FLAGS_planning_config_file);\n }\n\n AdapterManager::Init(FLAGS_adapter_config_path);\n if (AdapterManager::GetLocalization() == nullptr) {\n std::string error_msg(\"Localization is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetChassis() == nullptr) {\n std::string error_msg(\"Chassis is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetRoutingResult() == nullptr) {\n std::string error_msg(\"RoutingResult is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n \/\/ TODO(all) temporarily use the offline routing data.\n if (!AdapterManager::GetRoutingResult()->HasReceived()) {\n if (!AdapterManager::GetRoutingResult()->FeedFile(\n FLAGS_offline_routing_file)) {\n auto error_msg = common::util::StrCat(\n \"Failed to load offline routing file \", FLAGS_offline_routing_file);\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n } else {\n AWARN << \"Using offline routing file \" << FLAGS_offline_routing_file;\n }\n }\n if (AdapterManager::GetPrediction() == nullptr) {\n std::string error_msg(\"Prediction is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n\n RegisterPlanners();\n planner_ = planner_factory_.CreateObject(config_.planner_type());\n if (!planner_) {\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"planning is not initialized with config : \" + config_.DebugString());\n }\n\n return planner_->Init(config_);\n}\n\nStatus Planning::Start() {\n static ros::Rate loop_rate(FLAGS_planning_loop_rate);\n while (ros::ok()) {\n RunOnce();\n ros::spinOnce();\n loop_rate.sleep();\n }\n return Status::OK();\n}\n\nvoid Planning::RecordInput(ADCTrajectory* trajectory_pb) {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto& routing_result =\n AdapterManager::GetRoutingResult()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_result);\n}\n\nvoid Planning::RunOnce() {\n AdapterManager::Observe();\n if (AdapterManager::GetLocalization()->Empty()) {\n AERROR << \"Localization is not available; skip the planning cycle\";\n return;\n }\n\n if (AdapterManager::GetChassis()->Empty()) {\n AERROR << \"Chassis is not available; skip the planning cycle\";\n return;\n }\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"RoutingResult is not available; skip the planning cycle\";\n return;\n }\n\n \/\/ FIXME(all): enable prediction check when perception and prediction is\n \/\/ ready.\n \/\/ if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {\n \/\/ AERROR << \"Prediction is not available; skip the planning cycle\";\n \/\/ return;\n \/\/ }\n\n AINFO << \"Start planning ...\";\n const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());\n\n \/\/ localization\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n ADEBUG << \"Get localization:\" << localization.DebugString();\n\n \/\/ chassis\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n ADEBUG << \"Get chassis:\" << chassis.DebugString();\n\n common::VehicleState::instance()->Update(localization, chassis);\n\n const double planning_cycle_time = 1.0 \/ FLAGS_planning_loop_rate;\n\n ADCTrajectory trajectory_pb;\n RecordInput(&trajectory_pb);\n\n const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1;\n if (!InitFrame(frame_num)) {\n AERROR << \"Init frame failed\";\n return;\n }\n\n bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;\n bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time,\n &trajectory_pb);\n\n const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());\n const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;\n trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);\n ADEBUG << \"Planning latency: \" << trajectory_pb.latency_stats().DebugString();\n\n if (res_planning) {\n AdapterManager::FillPlanningHeader(\"planning\", &trajectory_pb);\n trajectory_pb.mutable_header()->set_timestamp_sec(start_timestamp);\n AdapterManager::PublishPlanning(trajectory_pb);\n ADEBUG << \"Planning succeeded:\" << trajectory_pb.header().DebugString();\n } else {\n AERROR << \"Planning failed\";\n }\n}\n\nvoid Planning::Stop() {}\n\nbool Planning::Plan(const bool is_on_auto_mode,\n const double current_time_stamp,\n const double planning_cycle_time,\n ADCTrajectory* trajectory_pb) {\n\n const auto& stitching_trajectory =\n TrajectoryStitcher::compute_stitching_trajectory(\n is_on_auto_mode, current_time_stamp, planning_cycle_time,\n last_publishable_trajectory_);\n\n frame_->SetPlanningStartPoint(stitching_trajectory.back());\n\n PublishableTrajectory publishable_trajectory;\n auto status = planner_->Plan(stitching_trajectory.back(),\n frame_.get(), &publishable_trajectory, trajectory_pb->mutable_debug(),\n trajectory_pb->mutable_latency_stats());\n\n if (status != Status::OK()) {\n AERROR << \"planner failed to make a driving plan\";\n last_publishable_trajectory_.Clear();\n return false;\n }\n\n publishable_trajectory.prepend_trajectory_points(\n stitching_trajectory.begin(), stitching_trajectory.end() - 1);\n\n publishable_trajectory.set_header_time(current_time_stamp);\n\n publishable_trajectory.populate_trajectory_protobuf(trajectory_pb);\n\n \/\/ update last publishable trajectory;\n last_publishable_trajectory_ = std::move(publishable_trajectory);\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning passes GEAR_DRIVE.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/planning.h\"\n\n#include <algorithm>\n\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/planner\/em\/em_planner.h\"\n#include \"modules\/planning\/planner\/rtk\/rtk_replay_planner.h\"\n#include \"modules\/planning\/trajectory_stitcher\/trajectory_stitcher.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::VehicleState;\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::time::Clock;\n\nstd::string Planning::Name() const { return \"planning\"; }\n\nvoid Planning::RegisterPlanners() {\n planner_factory_.Register(\n PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });\n planner_factory_.Register(PlanningConfig::EM,\n []() -> Planner* { return new EMPlanner(); });\n}\n\nconst Frame* Planning::GetFrame() const { return frame_.get(); }\nconst hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); }\n\nbool Planning::InitFrame(const uint32_t sequence_num) {\n frame_.reset(new Frame(sequence_num));\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"Routing is empty\";\n return false;\n }\n common::TrajectoryPoint point;\n frame_->SetVehicleInitPose(VehicleState::instance()->pose());\n frame_->SetRoutingResult(\n AdapterManager::GetRoutingResult()->GetLatestObserved());\n if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) {\n const auto& prediction =\n AdapterManager::GetPrediction()->GetLatestObserved();\n frame_->SetPrediction(prediction);\n ADEBUG << \"Get prediction\";\n }\n\n if (!frame_->Init()) {\n AERROR << \"failed to init frame\";\n return false;\n }\n return true;\n}\n\nStatus Planning::Init() {\n pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename));\n Frame::SetMap(pnc_map_.get());\n\n if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_)) {\n AERROR << \"failed to load planning config file \"\n << FLAGS_planning_config_file;\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"failed to load planning config file: \" + FLAGS_planning_config_file);\n }\n\n AdapterManager::Init(FLAGS_adapter_config_path);\n if (AdapterManager::GetLocalization() == nullptr) {\n std::string error_msg(\"Localization is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetChassis() == nullptr) {\n std::string error_msg(\"Chassis is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetRoutingResult() == nullptr) {\n std::string error_msg(\"RoutingResult is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n \/\/ TODO(all) temporarily use the offline routing data.\n if (!AdapterManager::GetRoutingResult()->HasReceived()) {\n if (!AdapterManager::GetRoutingResult()->FeedFile(\n FLAGS_offline_routing_file)) {\n auto error_msg = common::util::StrCat(\n \"Failed to load offline routing file \", FLAGS_offline_routing_file);\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n } else {\n AWARN << \"Using offline routing file \" << FLAGS_offline_routing_file;\n }\n }\n if (AdapterManager::GetPrediction() == nullptr) {\n std::string error_msg(\"Prediction is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n\n RegisterPlanners();\n planner_ = planner_factory_.CreateObject(config_.planner_type());\n if (!planner_) {\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"planning is not initialized with config : \" + config_.DebugString());\n }\n\n return planner_->Init(config_);\n}\n\nStatus Planning::Start() {\n static ros::Rate loop_rate(FLAGS_planning_loop_rate);\n while (ros::ok()) {\n RunOnce();\n ros::spinOnce();\n loop_rate.sleep();\n }\n return Status::OK();\n}\n\nvoid Planning::RecordInput(ADCTrajectory* trajectory_pb) {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto& routing_result =\n AdapterManager::GetRoutingResult()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_result);\n}\n\nvoid Planning::RunOnce() {\n AdapterManager::Observe();\n if (AdapterManager::GetLocalization()->Empty()) {\n AERROR << \"Localization is not available; skip the planning cycle\";\n return;\n }\n\n if (AdapterManager::GetChassis()->Empty()) {\n AERROR << \"Chassis is not available; skip the planning cycle\";\n return;\n }\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"RoutingResult is not available; skip the planning cycle\";\n return;\n }\n\n \/\/ FIXME(all): enable prediction check when perception and prediction is\n \/\/ ready.\n \/\/ if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {\n \/\/ AERROR << \"Prediction is not available; skip the planning cycle\";\n \/\/ return;\n \/\/ }\n\n AINFO << \"Start planning ...\";\n const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());\n\n \/\/ localization\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n ADEBUG << \"Get localization:\" << localization.DebugString();\n\n \/\/ chassis\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n ADEBUG << \"Get chassis:\" << chassis.DebugString();\n\n common::VehicleState::instance()->Update(localization, chassis);\n\n const double planning_cycle_time = 1.0 \/ FLAGS_planning_loop_rate;\n\n ADCTrajectory trajectory_pb;\n RecordInput(&trajectory_pb);\n\n const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1;\n if (!InitFrame(frame_num)) {\n AERROR << \"Init frame failed\";\n return;\n }\n\n bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;\n bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time,\n &trajectory_pb);\n\n const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());\n const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;\n trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);\n ADEBUG << \"Planning latency: \" << trajectory_pb.latency_stats().DebugString();\n\n if (res_planning) {\n AdapterManager::FillPlanningHeader(\"planning\", &trajectory_pb);\n trajectory_pb.mutable_header()->set_timestamp_sec(start_timestamp);\n \/\/ TODO(all): integrate reverse gear\n trajectory_pb.set_gear(canbus::Chassis::GEAR_DRIVE);\n AdapterManager::PublishPlanning(trajectory_pb);\n ADEBUG << \"Planning succeeded:\" << trajectory_pb.header().DebugString();\n } else {\n AERROR << \"Planning failed\";\n }\n}\n\nvoid Planning::Stop() {}\n\nbool Planning::Plan(const bool is_on_auto_mode,\n const double current_time_stamp,\n const double planning_cycle_time,\n ADCTrajectory* trajectory_pb) {\n\n const auto& stitching_trajectory =\n TrajectoryStitcher::compute_stitching_trajectory(\n is_on_auto_mode, current_time_stamp, planning_cycle_time,\n last_publishable_trajectory_);\n\n frame_->SetPlanningStartPoint(stitching_trajectory.back());\n\n PublishableTrajectory publishable_trajectory;\n auto status = planner_->Plan(stitching_trajectory.back(),\n frame_.get(), &publishable_trajectory, trajectory_pb->mutable_debug(),\n trajectory_pb->mutable_latency_stats());\n\n if (status != Status::OK()) {\n AERROR << \"planner failed to make a driving plan\";\n last_publishable_trajectory_.Clear();\n return false;\n }\n\n publishable_trajectory.prepend_trajectory_points(\n stitching_trajectory.begin(), stitching_trajectory.end() - 1);\n\n publishable_trajectory.set_header_time(current_time_stamp);\n\n publishable_trajectory.populate_trajectory_protobuf(trajectory_pb);\n\n \/\/ update last publishable trajectory;\n last_publishable_trajectory_ = std::move(publishable_trajectory);\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/planning.h\"\n\n#include <algorithm>\n\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/data_center.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/planner\/em\/em_planner.h\"\n#include \"modules\/planning\/planner\/rtk\/rtk_replay_planner.h\"\n#include \"modules\/planning\/trajectory_stitcher\/trajectory_stitcher.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::time::Clock;\nusing apollo::common::Status;\nusing apollo::common::ErrorCode;\n\nstd::string Planning::Name() const { return \"planning\"; }\n\nvoid Planning::RegisterPlanners() {\n planner_factory_.Register(\n PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });\n planner_factory_.Register(PlanningConfig::EM,\n []() -> Planner* { return new EMPlanner(); });\n}\n\nStatus Planning::Init() {\n if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_)) {\n AERROR << \"failed to load planning config file \"\n << FLAGS_planning_config_file;\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"failed to load planning config file: \" + FLAGS_planning_config_file);\n }\n\n AdapterManager::Init(FLAGS_adapter_config_path);\n if (AdapterManager::GetLocalization() == nullptr) {\n std::string error_msg(\"Localization is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetChassis() == nullptr) {\n std::string error_msg(\"Chassis is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetRoutingResult() == nullptr) {\n std::string error_msg(\"RoutingResult is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n \/\/ TODO(all) temporarily use the offline routing data.\n if (!AdapterManager::GetRoutingResult()->HasReceived()) {\n if (!AdapterManager::GetRoutingResult()->FeedFile(\n FLAGS_offline_routing_file)) {\n auto error_msg = common::util::StrCat(\n \"Failed to load offline routing file \", FLAGS_offline_routing_file);\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n } else {\n AWARN << \"Using offline routing file \" << FLAGS_offline_routing_file;\n }\n }\n if (AdapterManager::GetPrediction() == nullptr) {\n std::string error_msg(\"Prediction is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n\n RegisterPlanners();\n planner_ = planner_factory_.CreateObject(config_.planner_type());\n if (!planner_) {\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"planning is not initialized with config : \" + config_.DebugString());\n }\n\n return planner_->Init(config_);\n}\n\nStatus Planning::Start() {\n static ros::Rate loop_rate(FLAGS_planning_loop_rate);\n while (ros::ok()) {\n RunOnce();\n ros::spinOnce();\n loop_rate.sleep();\n }\n return Status::OK();\n}\n\nvoid Planning::RecordInput(ADCTrajectory* trajectory_pb) {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto& routing_result =\n AdapterManager::GetRoutingResult()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_result);\n}\n\nvoid Planning::RunOnce() {\n AdapterManager::Observe();\n if (AdapterManager::GetLocalization()->Empty()) {\n AERROR << \"Localization is not available; skip the planning cycle\";\n return;\n }\n\n if (AdapterManager::GetChassis()->Empty()) {\n AERROR << \"Chassis is not available; skip the planning cycle\";\n return;\n }\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"RoutingResult is not available; skip the planning cycle\";\n return;\n }\n\n \/\/ FIXME(all): enable prediction check when perception and prediction is\n \/\/ ready.\n \/\/ if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {\n \/\/ AERROR << \"Prediction is not available; skip the planning cycle\";\n \/\/ return;\n \/\/ }\n\n AINFO << \"Start planning ...\";\n const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());\n\n \/\/ localization\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n ADEBUG << \"Get localization:\" << localization.DebugString();\n\n \/\/ chassis\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n ADEBUG << \"Get chassis:\" << chassis.DebugString();\n\n common::VehicleState::instance()->Update(localization, chassis);\n\n double planning_cycle_time = 1.0 \/ FLAGS_planning_loop_rate;\n \/\/ the execution_start_time is the estimated time when the planned trajectory\n \/\/ will be executed by the controller.\n double execution_start_time =\n apollo::common::time::ToSecond(apollo::common::time::Clock::Now()) +\n planning_cycle_time;\n\n ADCTrajectory trajectory_pb;\n RecordInput(&trajectory_pb);\n\n if (!DataCenter::instance()->init_current_frame(\n AdapterManager::GetPlanning()->GetSeqNum() + 1)) {\n AERROR << \"DataCenter init frame failed\";\n return;\n }\n\n bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;\n bool res_planning = Plan(is_auto_mode, execution_start_time, &trajectory_pb);\n\n const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());\n const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;\n trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);\n ADEBUG << \"Planning latency: \" << trajectory_pb.latency_stats().DebugString();\n\n if (res_planning) {\n AdapterManager::FillPlanningHeader(\"planning\",\n trajectory_pb.mutable_header());\n trajectory_pb.mutable_header()->set_timestamp_sec(execution_start_time);\n AdapterManager::PublishPlanning(trajectory_pb);\n ADEBUG << \"Planning succeeded:\" << trajectory_pb.header().DebugString();\n } else {\n AERROR << \"Planning failed\";\n }\n}\n\nvoid Planning::Stop() {}\n\nbool Planning::Plan(const bool is_on_auto_mode, const double publish_time,\n ADCTrajectory* trajectory_pb) {\n \/\/ if 1. the auto-driving mode is off or\n \/\/ 2. we don't have the trajectory from last planning cycle or\n \/\/ 3. the position deviation from actual and target is too high\n \/\/ then planning from current vehicle state.\n auto stitching_trajectory = TrajectoryStitcher::compute_stitching_trajectory(\n last_publishable_trajectory_);\n\n auto planning_start_point = stitching_trajectory.back();\n\n if (FLAGS_enable_record_debug) {\n trajectory_pb->mutable_debug()\n ->mutable_planning_data()\n ->mutable_init_point()\n ->CopyFrom(stitching_trajectory.back());\n trajectory_pb->mutable_debug()->mutable_planning_data()->set_is_replan(\n true);\n }\n\n auto status = planner_->Plan(planning_start_point, trajectory_pb);\n if (status != Status::OK()) {\n AERROR << \"planner failed to make a driving plan\";\n last_publishable_trajectory_.Clear();\n return false;\n }\n\n InsertFrontTrajectoryPoints(trajectory_pb, stitching_trajectory);\n\n \/\/ update last publishable trajectory;\n last_publishable_trajectory_.Clear();\n for (int i = 0; i < trajectory_pb->trajectory_point_size(); ++i) {\n last_publishable_trajectory_.add_trajectory_point(\n trajectory_pb->trajectory_point(i));\n }\n last_publishable_trajectory_.set_header_time(\n trajectory_pb->header().timestamp_sec());\n return true;\n}\n\nvoid Planning::InsertFrontTrajectoryPoints(\n ADCTrajectory* trajectory_pb,\n const std::vector<apollo::common::TrajectoryPoint>& points) const {\n if (points.empty()) {\n AINFO << \"stitch points are empty\";\n return;\n }\n\n int i = 0;\n int j = trajectory_pb->trajectory_point_size() - 1;\n while (i < j) {\n trajectory_pb->mutable_trajectory_point()->SwapElements(i, j);\n ++i;\n --j;\n }\n\n j = points.size() - 1;\n while (j >= 0) {\n trajectory_pb->add_trajectory_point()->CopyFrom(points[j]);\n --j;\n }\n\n i = 0;\n j = trajectory_pb->trajectory_point_size() - 1;\n while (i < j) {\n trajectory_pb->mutable_trajectory_point()->SwapElements(i, j);\n ++i;\n --j;\n }\n return;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>Fixed the merging error in trajectory stitching<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/planning.h\"\n\n#include <algorithm>\n\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/data_center.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/planner\/em\/em_planner.h\"\n#include \"modules\/planning\/planner\/rtk\/rtk_replay_planner.h\"\n#include \"modules\/planning\/trajectory_stitcher\/trajectory_stitcher.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::time::Clock;\nusing apollo::common::Status;\nusing apollo::common::ErrorCode;\n\nstd::string Planning::Name() const { return \"planning\"; }\n\nvoid Planning::RegisterPlanners() {\n planner_factory_.Register(\n PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); });\n planner_factory_.Register(PlanningConfig::EM,\n []() -> Planner* { return new EMPlanner(); });\n}\n\nStatus Planning::Init() {\n if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_)) {\n AERROR << \"failed to load planning config file \"\n << FLAGS_planning_config_file;\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"failed to load planning config file: \" + FLAGS_planning_config_file);\n }\n\n AdapterManager::Init(FLAGS_adapter_config_path);\n if (AdapterManager::GetLocalization() == nullptr) {\n std::string error_msg(\"Localization is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetChassis() == nullptr) {\n std::string error_msg(\"Chassis is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n if (AdapterManager::GetRoutingResult() == nullptr) {\n std::string error_msg(\"RoutingResult is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n \/\/ TODO(all) temporarily use the offline routing data.\n if (!AdapterManager::GetRoutingResult()->HasReceived()) {\n if (!AdapterManager::GetRoutingResult()->FeedFile(\n FLAGS_offline_routing_file)) {\n auto error_msg = common::util::StrCat(\n \"Failed to load offline routing file \", FLAGS_offline_routing_file);\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n } else {\n AWARN << \"Using offline routing file \" << FLAGS_offline_routing_file;\n }\n }\n if (AdapterManager::GetPrediction() == nullptr) {\n std::string error_msg(\"Prediction is not registered\");\n AERROR << error_msg;\n return Status(ErrorCode::PLANNING_ERROR, error_msg);\n }\n\n RegisterPlanners();\n planner_ = planner_factory_.CreateObject(config_.planner_type());\n if (!planner_) {\n return Status(\n ErrorCode::PLANNING_ERROR,\n \"planning is not initialized with config : \" + config_.DebugString());\n }\n\n return planner_->Init(config_);\n}\n\nStatus Planning::Start() {\n static ros::Rate loop_rate(FLAGS_planning_loop_rate);\n while (ros::ok()) {\n RunOnce();\n ros::spinOnce();\n loop_rate.sleep();\n }\n return Status::OK();\n}\n\nvoid Planning::RecordInput(ADCTrajectory* trajectory_pb) {\n if (!FLAGS_enable_record_debug) {\n ADEBUG << \"Skip record input into debug\";\n return;\n }\n auto planning_data = trajectory_pb->mutable_debug()->mutable_planning_data();\n auto adc_position = planning_data->mutable_adc_position();\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n adc_position->CopyFrom(localization);\n\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n auto debug_chassis = planning_data->mutable_chassis();\n debug_chassis->CopyFrom(chassis);\n\n const auto& routing_result =\n AdapterManager::GetRoutingResult()->GetLatestObserved();\n\n auto debug_routing = planning_data->mutable_routing();\n debug_routing->CopyFrom(routing_result);\n}\n\nvoid Planning::RunOnce() {\n AdapterManager::Observe();\n if (AdapterManager::GetLocalization()->Empty()) {\n AERROR << \"Localization is not available; skip the planning cycle\";\n return;\n }\n\n if (AdapterManager::GetChassis()->Empty()) {\n AERROR << \"Chassis is not available; skip the planning cycle\";\n return;\n }\n if (AdapterManager::GetRoutingResult()->Empty()) {\n AERROR << \"RoutingResult is not available; skip the planning cycle\";\n return;\n }\n\n \/\/ FIXME(all): enable prediction check when perception and prediction is\n \/\/ ready.\n \/\/ if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) {\n \/\/ AERROR << \"Prediction is not available; skip the planning cycle\";\n \/\/ return;\n \/\/ }\n\n AINFO << \"Start planning ...\";\n const double start_timestamp = apollo::common::time::ToSecond(Clock::Now());\n\n \/\/ localization\n const auto& localization =\n AdapterManager::GetLocalization()->GetLatestObserved();\n ADEBUG << \"Get localization:\" << localization.DebugString();\n\n \/\/ chassis\n const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved();\n ADEBUG << \"Get chassis:\" << chassis.DebugString();\n\n common::VehicleState::instance()->Update(localization, chassis);\n\n double planning_cycle_time = 1.0 \/ FLAGS_planning_loop_rate;\n \/\/ the execution_start_time is the estimated time when the planned trajectory\n \/\/ will be executed by the controller.\n double execution_start_time =\n apollo::common::time::ToSecond(apollo::common::time::Clock::Now()) +\n planning_cycle_time;\n\n ADCTrajectory trajectory_pb;\n RecordInput(&trajectory_pb);\n\n if (!DataCenter::instance()->init_current_frame(\n AdapterManager::GetPlanning()->GetSeqNum() + 1)) {\n AERROR << \"DataCenter init frame failed\";\n return;\n }\n\n bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE;\n bool res_planning = Plan(is_auto_mode, execution_start_time, &trajectory_pb);\n\n const double end_timestamp = apollo::common::time::ToSecond(Clock::Now());\n const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;\n trajectory_pb.mutable_latency_stats()->set_total_time_ms(time_diff_ms);\n ADEBUG << \"Planning latency: \" << trajectory_pb.latency_stats().DebugString();\n\n if (res_planning) {\n AdapterManager::FillPlanningHeader(\"planning\",\n trajectory_pb.mutable_header());\n trajectory_pb.mutable_header()->set_timestamp_sec(execution_start_time);\n AdapterManager::PublishPlanning(trajectory_pb);\n ADEBUG << \"Planning succeeded:\" << trajectory_pb.header().DebugString();\n } else {\n AERROR << \"Planning failed\";\n }\n}\n\nvoid Planning::Stop() {}\n\nbool Planning::Plan(const bool is_on_auto_mode, const double publish_time,\n ADCTrajectory* trajectory_pb) {\n \/\/ if 1. the auto-driving mode is off or\n \/\/ 2. we don't have the trajectory from last planning cycle or\n \/\/ 3. the position deviation from actual and target is too high\n \/\/ then planning from current vehicle state.\n auto stitching_trajectory = TrajectoryStitcher::compute_stitching_trajectory(\n last_publishable_trajectory_);\n\n auto planning_start_point = stitching_trajectory.back();\n\n if (FLAGS_enable_record_debug) {\n trajectory_pb->mutable_debug()\n ->mutable_planning_data()\n ->mutable_init_point()\n ->CopyFrom(stitching_trajectory.back());\n trajectory_pb->mutable_debug()->mutable_planning_data()->set_is_replan(\n true);\n }\n\n auto status = planner_->Plan(planning_start_point, trajectory_pb);\n if (status != Status::OK()) {\n AERROR << \"planner failed to make a driving plan\";\n last_publishable_trajectory_.Clear();\n return false;\n }\n\n InsertFrontTrajectoryPoints(trajectory_pb,\n std::vector<decltype(planning_start_point)>(\n stitching_trajectory.begin(),\n stitching_trajectory.end() - 1));\n\n \/\/ update last publishable trajectory;\n last_publishable_trajectory_.Clear();\n for (int i = 0; i < trajectory_pb->trajectory_point_size(); ++i) {\n last_publishable_trajectory_.add_trajectory_point(\n trajectory_pb->trajectory_point(i));\n }\n last_publishable_trajectory_.set_header_time(\n trajectory_pb->header().timestamp_sec());\n return true;\n}\n\nvoid Planning::InsertFrontTrajectoryPoints(\n ADCTrajectory* trajectory_pb,\n const std::vector<apollo::common::TrajectoryPoint>& points) const {\n if (points.empty()) {\n AINFO << \"stitch points are empty\";\n return;\n }\n\n int i = 0;\n int j = trajectory_pb->trajectory_point_size() - 1;\n while (i < j) {\n trajectory_pb->mutable_trajectory_point()->SwapElements(i, j);\n ++i;\n --j;\n }\n\n j = points.size() - 1;\n while (j >= 0) {\n trajectory_pb->add_trajectory_point()->CopyFrom(points[j]);\n --j;\n }\n\n i = 0;\n j = trajectory_pb->trajectory_point_size() - 1;\n while (i < j) {\n trajectory_pb->mutable_trajectory_point()->SwapElements(i, j);\n ++i;\n --j;\n }\n return;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\r\n\/\/ WorldStorage.cpp\r\n\r\n\/\/ Implements the cWorldStorage class representing the chunk loading \/ saving thread\r\n\r\n\/\/ To add a new storage schema, implement a cWSSchema descendant and add it to cWorldStorage::InitSchemas()\r\n\r\n#include \"Globals.h\"\r\n#include \"WorldStorage.h\"\r\n#include \"WSSCompact.h\"\r\n#include \"cWorld.h\"\r\n#include \"cChunkGenerator.h\"\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Example storage schema - forgets all chunks ;)\r\nclass cWSSForgetful :\r\n\tpublic cWSSchema\r\n{\r\npublic:\r\n\tcWSSForgetful(cWorld * a_World) : cWSSchema(a_World) {}\r\n\t\r\nprotected:\r\n\t\/\/ cWSSchema overrides:\r\n\tvirtual bool LoadChunk(const cChunkPtr & a_Chunk) override {return false; }\r\n\tvirtual bool SaveChunk(const cChunkPtr & a_Chunk) override {return true; }\r\n\tvirtual const AString GetName(void) const override {return \"forgetful\"; }\r\n} ;\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ cWorldStorage:\r\n\r\ncWorldStorage::cWorldStorage(void) :\r\n\tsuper(\"cWorldStorage\"),\r\n\tm_World(NULL),\r\n\tm_SaveSchema(NULL)\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\ncWorldStorage::~cWorldStorage()\r\n{\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tdelete *itr;\r\n\t} \/\/ for itr - m_Schemas[]\r\n\tm_LoadQueue.clear();\r\n\tm_SaveQueue.clear();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cWorldStorage::Start(cWorld * a_World, const AString & a_StorageSchemaName)\r\n{\r\n\tm_World = a_World;\r\n\tm_StorageSchemaName = a_StorageSchemaName;\r\n\tInitSchemas();\r\n\t\r\n\treturn super::Start();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::WaitForFinish(void)\r\n{\r\n\tLOG(\"Waiting for the world storage to finish saving\");\r\n\t\r\n\t\/\/ Cancel all loading requests:\r\n\tcCSLock Lock(m_CSLoadQueue);\r\n\tm_LoadQueue.clear();\r\n\t\r\n\t\/\/ Wait for the thread to finish:\r\n\tmShouldTerminate = true;\r\n\tm_Event.Set();\r\n\tsuper::Wait();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::QueueLoadChunk(cChunkPtr & a_Chunk)\r\n{\r\n\t\/\/ Queues the chunk for loading; if not loaded, the chunk will be generated\r\n\tcCSLock Lock(m_CSLoadQueue);\r\n\tm_LoadQueue.remove(a_Chunk); \/\/ Don't add twice\r\n\tm_LoadQueue.push_back(a_Chunk);\r\n\tm_Event.Set();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::QueueSaveChunk(cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSSaveQueue);\r\n\tm_SaveQueue.remove(a_Chunk); \/\/ Don't add twice\r\n\tm_SaveQueue.push_back(a_Chunk);\r\n\tm_Event.Set();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::UnqueueLoad(const cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSLoadQueue);\r\n\tm_LoadQueue.remove(a_Chunk);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::UnqueueSave(const cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSSaveQueue);\r\n\tm_SaveQueue.remove(a_Chunk);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::InitSchemas(void)\r\n{\r\n\t\/\/ The first schema added is considered the default\r\n\tm_Schemas.push_back(new cWSSCompact(m_World));\r\n\tm_Schemas.push_back(new cWSSForgetful(m_World));\r\n\t\/\/ Add new schemas here\r\n\t\r\n\tif (m_StorageSchemaName == \"Default\")\r\n\t{\r\n\t\tm_SaveSchema = m_Schemas.front();\r\n\t\treturn;\r\n\t}\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tif ((*itr)->GetName() == m_StorageSchemaName)\r\n\t\t{\r\n\t\t\tm_SaveSchema = *itr;\r\n\t\t\treturn;\r\n\t\t}\r\n\t} \/\/ for itr - m_Schemas[]\r\n\t\r\n\t\/\/ Unknown schema selected, let the admin know:\r\n\tLOGWARNING(\"Unknown storage schema name \\\"%s\\\". Using default. Available schemas:\", m_StorageSchemaName.c_str());\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tLOGWARNING(\"\\t\\\"%s\\\"\", (*itr)->GetName().c_str());\r\n\t}\r\n\tm_SaveSchema = m_Schemas.front();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::Execute(void)\r\n{\r\n\twhile (!mShouldTerminate)\r\n\t{\r\n\t\tm_Event.Wait();\r\n\t\t\r\n\t\t\/\/ Process both queues until they are empty again:\r\n\t\tbool HasMore;\r\n\t\tdo\r\n\t\t{\r\n\t\t\tHasMore = false;\r\n\t\t\tif (mShouldTerminate)\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\/\/ Load 1 chunk:\r\n\t\t\tcChunkPtr ToLoad;\r\n\t\t\t{\r\n\t\t\t\tcCSLock Lock(m_CSLoadQueue);\r\n\t\t\t\tif (m_LoadQueue.size() > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tToLoad = m_LoadQueue.front();\r\n\t\t\t\t\tm_LoadQueue.pop_front();\r\n\t\t\t\t}\r\n\t\t\t\tHasMore = (m_LoadQueue.size() > 0);\r\n\t\t\t}\r\n\t\t\tif ((ToLoad != NULL) && !LoadChunk(ToLoad))\r\n\t\t\t{\r\n\t\t\t\t\/\/ The chunk couldn't be loaded, generate it:\r\n\t\t\t\tm_World->GetGenerator().GenerateChunk(ToLoad->GetPosX(), ToLoad->GetPosZ());\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\/\/ Save 1 chunk:\r\n\t\t\tcChunkPtr Save;\r\n\t\t\t{\r\n\t\t\t\tcCSLock Lock(m_CSSaveQueue);\r\n\t\t\t\tif (m_SaveQueue.size() > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tSave = m_SaveQueue.front();\r\n\t\t\t\t\tm_SaveQueue.pop_front();\r\n\t\t\t\t}\r\n\t\t\t\tHasMore = HasMore || (m_SaveQueue.size() > 0);\r\n\t\t\t}\r\n\t\t\tif ((Save != NULL) && (!m_SaveSchema->SaveChunk(Save)))\r\n\t\t\t{\r\n\t\t\t\tLOGWARNING(\"Cannot save chunk [%d, %d]\", Save->GetPosX(), Save->GetPosZ());\r\n\t\t\t}\r\n\t\t} while (HasMore);\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cWorldStorage::LoadChunk(const cChunkPtr & a_Chunk)\r\n{\r\n\tif (a_Chunk->IsValid())\r\n\t{\r\n\t\t\/\/ Already loaded (can happen, since the queue is async)\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tif (m_SaveSchema->LoadChunk(a_Chunk))\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tif ((*itr)->LoadChunk(a_Chunk))\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\n\r\n<commit_msg>Fixed a deadlock in WorldStorage<commit_after>\r\n\/\/ WorldStorage.cpp\r\n\r\n\/\/ Implements the cWorldStorage class representing the chunk loading \/ saving thread\r\n\r\n\/\/ To add a new storage schema, implement a cWSSchema descendant and add it to cWorldStorage::InitSchemas()\r\n\r\n#include \"Globals.h\"\r\n#include \"WorldStorage.h\"\r\n#include \"WSSCompact.h\"\r\n#include \"cWorld.h\"\r\n#include \"cChunkGenerator.h\"\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Example storage schema - forgets all chunks ;)\r\nclass cWSSForgetful :\r\n\tpublic cWSSchema\r\n{\r\npublic:\r\n\tcWSSForgetful(cWorld * a_World) : cWSSchema(a_World) {}\r\n\t\r\nprotected:\r\n\t\/\/ cWSSchema overrides:\r\n\tvirtual bool LoadChunk(const cChunkPtr & a_Chunk) override {return false; }\r\n\tvirtual bool SaveChunk(const cChunkPtr & a_Chunk) override {return true; }\r\n\tvirtual const AString GetName(void) const override {return \"forgetful\"; }\r\n} ;\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ cWorldStorage:\r\n\r\ncWorldStorage::cWorldStorage(void) :\r\n\tsuper(\"cWorldStorage\"),\r\n\tm_World(NULL),\r\n\tm_SaveSchema(NULL)\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\ncWorldStorage::~cWorldStorage()\r\n{\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tdelete *itr;\r\n\t} \/\/ for itr - m_Schemas[]\r\n\tm_LoadQueue.clear();\r\n\tm_SaveQueue.clear();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cWorldStorage::Start(cWorld * a_World, const AString & a_StorageSchemaName)\r\n{\r\n\tm_World = a_World;\r\n\tm_StorageSchemaName = a_StorageSchemaName;\r\n\tInitSchemas();\r\n\t\r\n\treturn super::Start();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::WaitForFinish(void)\r\n{\r\n\tLOG(\"Waiting for the world storage to finish saving\");\r\n\t\r\n\t{\r\n\t\t\/\/ Cancel all loading requests:\r\n\t\tcCSLock Lock(m_CSLoadQueue);\r\n\t\tm_LoadQueue.clear();\r\n\t}\r\n\t\r\n\t\/\/ Wait for the thread to finish:\r\n\tmShouldTerminate = true;\r\n\tm_Event.Set();\r\n\tsuper::Wait();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::QueueLoadChunk(cChunkPtr & a_Chunk)\r\n{\r\n\t\/\/ Queues the chunk for loading; if not loaded, the chunk will be generated\r\n\tcCSLock Lock(m_CSLoadQueue);\r\n\tm_LoadQueue.remove(a_Chunk); \/\/ Don't add twice\r\n\tm_LoadQueue.push_back(a_Chunk);\r\n\tm_Event.Set();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::QueueSaveChunk(cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSSaveQueue);\r\n\tm_SaveQueue.remove(a_Chunk); \/\/ Don't add twice\r\n\tm_SaveQueue.push_back(a_Chunk);\r\n\tm_Event.Set();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::UnqueueLoad(const cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSLoadQueue);\r\n\tm_LoadQueue.remove(a_Chunk);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::UnqueueSave(const cChunkPtr & a_Chunk)\r\n{\r\n\tcCSLock Lock(m_CSSaveQueue);\r\n\tm_SaveQueue.remove(a_Chunk);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::InitSchemas(void)\r\n{\r\n\t\/\/ The first schema added is considered the default\r\n\tm_Schemas.push_back(new cWSSCompact(m_World));\r\n\tm_Schemas.push_back(new cWSSForgetful(m_World));\r\n\t\/\/ Add new schemas here\r\n\t\r\n\tif (m_StorageSchemaName == \"Default\")\r\n\t{\r\n\t\tm_SaveSchema = m_Schemas.front();\r\n\t\treturn;\r\n\t}\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tif ((*itr)->GetName() == m_StorageSchemaName)\r\n\t\t{\r\n\t\t\tm_SaveSchema = *itr;\r\n\t\t\treturn;\r\n\t\t}\r\n\t} \/\/ for itr - m_Schemas[]\r\n\t\r\n\t\/\/ Unknown schema selected, let the admin know:\r\n\tLOGWARNING(\"Unknown storage schema name \\\"%s\\\". Using default. Available schemas:\", m_StorageSchemaName.c_str());\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tLOGWARNING(\"\\t\\\"%s\\\"\", (*itr)->GetName().c_str());\r\n\t}\r\n\tm_SaveSchema = m_Schemas.front();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cWorldStorage::Execute(void)\r\n{\r\n\twhile (!mShouldTerminate)\r\n\t{\r\n\t\tm_Event.Wait();\r\n\t\t\r\n\t\t\/\/ Process both queues until they are empty again:\r\n\t\tbool HasMore;\r\n\t\tdo\r\n\t\t{\r\n\t\t\tHasMore = false;\r\n\t\t\tif (mShouldTerminate)\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\/\/ Load 1 chunk:\r\n\t\t\tcChunkPtr ToLoad;\r\n\t\t\t{\r\n\t\t\t\tcCSLock Lock(m_CSLoadQueue);\r\n\t\t\t\tif (m_LoadQueue.size() > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tToLoad = m_LoadQueue.front();\r\n\t\t\t\t\tm_LoadQueue.pop_front();\r\n\t\t\t\t}\r\n\t\t\t\tHasMore = (m_LoadQueue.size() > 0);\r\n\t\t\t}\r\n\t\t\tif ((ToLoad != NULL) && !LoadChunk(ToLoad))\r\n\t\t\t{\r\n\t\t\t\t\/\/ The chunk couldn't be loaded, generate it:\r\n\t\t\t\tm_World->GetGenerator().GenerateChunk(ToLoad->GetPosX(), ToLoad->GetPosZ());\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\/\/ Save 1 chunk:\r\n\t\t\tcChunkPtr Save;\r\n\t\t\t{\r\n\t\t\t\tcCSLock Lock(m_CSSaveQueue);\r\n\t\t\t\tif (m_SaveQueue.size() > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tSave = m_SaveQueue.front();\r\n\t\t\t\t\tm_SaveQueue.pop_front();\r\n\t\t\t\t}\r\n\t\t\t\tHasMore = HasMore || (m_SaveQueue.size() > 0);\r\n\t\t\t}\r\n\t\t\tif ((Save != NULL) && (!m_SaveSchema->SaveChunk(Save)))\r\n\t\t\t{\r\n\t\t\t\tLOGWARNING(\"Cannot save chunk [%d, %d]\", Save->GetPosX(), Save->GetPosZ());\r\n\t\t\t}\r\n\t\t} while (HasMore);\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cWorldStorage::LoadChunk(const cChunkPtr & a_Chunk)\r\n{\r\n\tif (a_Chunk->IsValid())\r\n\t{\r\n\t\t\/\/ Already loaded (can happen, since the queue is async)\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tif (m_SaveSchema->LoadChunk(a_Chunk))\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tfor (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)\r\n\t{\r\n\t\tif ((*itr)->LoadChunk(a_Chunk))\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <tchar.h>\n#include <D3DX9.h>\n\n#include \"dx9font.h\"\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Custom vertex types for rendering text\n\/\/-----------------------------------------------------------------------------\n#define MAX_NUM_VERTICES 50*6\n\nstruct FONT2DVERTEX { D3DXVECTOR4 p; DWORD color; FLOAT tu, tv; };\nstruct FONT3DVERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; FLOAT tu, tv; };\n\n#define D3DFVF_FONT2DVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)\n#define D3DFVF_FONT3DVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)\n\ninline FONT2DVERTEX InitFont2DVertex( const D3DXVECTOR4& p, D3DCOLOR color,\n FLOAT tu, FLOAT tv )\n{\n FONT2DVERTEX v; v.p = p; v.color = color; v.tu = tu; v.tv = tv;\n return v;\n}\n\ninline FONT3DVERTEX InitFont3DVertex( const D3DXVECTOR3& p, const D3DXVECTOR3& n,\n FLOAT tu, FLOAT tv )\n{\n FONT3DVERTEX v; v.p = p; v.n = n; v.tu = tu; v.tv = tv;\n return v;\n}\n\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: CD3DFont()\n\/\/ Desc: Font class constructor\n\/\/-----------------------------------------------------------------------------\nDx9Font::Dx9Font(\n LPDIRECT3DDEVICE9 pd3dDevice\n )\n{\n m_pd3dDevice = NULL;\n m_pTexture = NULL;\n m_pVB = NULL;\n\n m_pStateBlockSaved = NULL;\n m_pStateBlockDrawText = NULL;\n\n \/\/ Keep a local copy of the device\n m_pd3dDevice = pd3dDevice;\n}\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: ~CD3DFont()\n\/\/ Desc: Font class destructor\n\/\/-----------------------------------------------------------------------------\nDx9Font::~Dx9Font()\n{\n InvalidateDeviceObjects();\n DeleteDeviceObjects();\n}\n\n\nDWORD\nDx9Font::GetMaxTextureWidth()\n{\n D3DCAPS9 d3dCaps;\n\n m_pd3dDevice->GetDeviceCaps( &d3dCaps );\n\n return d3dCaps.MaxTextureWidth;\n}\n\n\nHRESULT\nDx9Font::CreateTexture()\n{\n HRESULT hr;\n D3DFORMAT format;\n\n if (PIXEL_DEPTH == 16)\n format = D3DFMT_A4R4G4B4;\n else if (PIXEL_DEPTH == 32)\n format = D3DFMT_A8R8G8B8;\n\n hr = m_pd3dDevice->CreateTexture(\n m_dwTexWidth,\n m_dwTexHeight,\n 1,\n 0,\n format,\n D3DPOOL_MANAGED,\n &m_pTexture,\n NULL\n );\n\n return hr;\n}\n\n\nVOID\nDx9Font::LockTexture(\n D3DLOCKED_RECT* pLockedRect\n )\n{\n m_pTexture->LockRect( 0, pLockedRect, 0, 0 );\n}\n\n\nVOID\nDx9Font::UnlockTexture()\n{\n m_pTexture->UnlockRect(0);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: RestoreDeviceObjects()\n\/\/ Desc:\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::RestoreDeviceObjects()\n{\n HRESULT hr;\n\n \/\/ Create vertex buffer for the letters\n int vertexSize = max( sizeof(FONT2DVERTEX), sizeof(FONT3DVERTEX ) );\n if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer( MAX_NUM_VERTICES * vertexSize,\n D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, 0,\n D3DPOOL_DEFAULT, &m_pVB, NULL ) ) )\n {\n return hr;\n }\n\n \/\/ Create the state blocks for rendering text\n for( UINT which=0; which<2; which++ )\n {\n m_pd3dDevice->BeginStateBlock();\n m_pd3dDevice->SetTexture( 0, m_pTexture );\n\n if ( D3DFONT_ZENABLE & m_dwFontFlags )\n m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );\n else\n m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE );\n\n m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );\n m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x08 );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );\n m_pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );\n m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );\n m_pd3dDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_CLIPPING, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_DISABLE );\n m_pd3dDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_COLORWRITEENABLE,\n D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN |\n D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );\n m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );\n m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_POINT );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE );\n m_pd3dDevice->SetFVF( D3DFVF_FONT2DVERTEX );\n m_pd3dDevice->SetPixelShader( NULL );\n\n if( which==0 )\n m_pd3dDevice->EndStateBlock( &m_pStateBlockSaved );\n else\n m_pd3dDevice->EndStateBlock( &m_pStateBlockDrawText );\n }\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: InvalidateDeviceObjects()\n\/\/ Desc: Destroys all device-dependent objects\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::InvalidateDeviceObjects()\n{\n if (m_pVB)\n m_pVB->Release();\n\n if (m_pStateBlockSaved)\n m_pStateBlockSaved->Release();\n\n if (m_pStateBlockDrawText)\n m_pStateBlockDrawText->Release();\n\n m_pVB = NULL;\n m_pStateBlockSaved = NULL;\n m_pStateBlockDrawText = NULL;\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: DeleteDeviceObjects()\n\/\/ Desc: Destroys all device-dependent objects\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::DeleteDeviceObjects()\n{\n if (m_pTexture)\n m_pTexture->Release();\n\n m_pTexture = NULL;\n m_pd3dDevice = NULL;\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: DrawText()\n\/\/ Desc: Draws 2D text. Note that sx and sy are in pixels\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::DrawText( FLOAT sx, FLOAT sy, DWORD dwColor, TCHAR* strText, DWORD dwFlags )\n{\n if( m_pd3dDevice == NULL )\n return E_FAIL;\n\n \/\/ Setup renderstate\n m_pStateBlockSaved->Capture();\n m_pStateBlockDrawText->Apply();\n \/\/m_pd3dDevice->SetFVF( D3DFVF_FONT2DVERTEX );\n \/\/m_pd3dDevice->SetPixelShader( NULL );\n m_pd3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof(FONT2DVERTEX) );\n\n \/\/ Set filter states\n if( dwFlags & D3DFONT_FILTERED )\n {\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );\n }\n\n if( dwFlags & D3DFONT_RIGHT ) {\n SIZE sz;\n GetTextExtent( strText, &sz );\n sx -= (FLOAT)sz.cx;\n } else if( dwFlags & D3DFONT_CENTERED ) {\n SIZE sz;\n GetTextExtent( strText, &sz );\n sx -= (FLOAT)sz.cx\/2.0f;\n }\n\n \/\/ Adjust for character spacing\n sx -= m_dwSpacing;\n FLOAT fStartX = sx;\n\n \/\/ Fill vertex buffer\n FONT2DVERTEX* pVertices = NULL;\n DWORD dwNumTriangles = 0;\n m_pVB->Lock( 0, 0, (void**)&pVertices, D3DLOCK_DISCARD );\n\n while( *strText )\n {\n TCHAR c = *strText++;\n\n if( c == _T('\\n') )\n {\n sx = fStartX;\n sy += (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight;\n }\n\n if( (c-32) < 0 || (c-32) >= (NUMBER_OF_CHARACTERS+1)-32 )\n continue;\n\n FLOAT tx1 = m_fTexCoords[c-32][0];\n FLOAT ty1 = m_fTexCoords[c-32][1];\n FLOAT tx2 = m_fTexCoords[c-32][2];\n FLOAT ty2 = m_fTexCoords[c-32][3];\n\n FLOAT w = (tx2-tx1) * m_dwTexWidth \/ m_fTextScale;\n FLOAT h = (ty2-ty1) * m_dwTexHeight \/ m_fTextScale;\n\n if( c != _T(' ') )\n {\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx1, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx2, ty1 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );\n dwNumTriangles += 2;\n\n if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) )\n {\n \/\/ Unlock, render, and relock the vertex buffer\n m_pVB->Unlock();\n m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );\n pVertices = NULL;\n m_pVB->Lock( 0, 0, (void**)&pVertices, D3DLOCK_DISCARD );\n dwNumTriangles = 0L;\n }\n }\n\n sx += w - (2 * m_dwSpacing);\n }\n\n \/\/ Unlock and render the vertex buffer\n m_pVB->Unlock();\n if( dwNumTriangles > 0 )\n m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );\n\n \/\/ Restore the modified renderstates\n m_pStateBlockSaved->Apply();\n\n return S_OK;\n}\n<commit_msg>fixed overlay not working on IDirect3DDevice9Ex based games; more specifically HL2 engine based games<commit_after>#include <stdio.h>\n#include <tchar.h>\n#include <D3DX9.h>\n\n#include \"dx9font.h\"\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Custom vertex types for rendering text\n\/\/-----------------------------------------------------------------------------\n#define MAX_NUM_VERTICES 50*6\n\nstruct FONT2DVERTEX { D3DXVECTOR4 p; DWORD color; FLOAT tu, tv; };\nstruct FONT3DVERTEX { D3DXVECTOR3 p; D3DXVECTOR3 n; FLOAT tu, tv; };\n\n#define D3DFVF_FONT2DVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1)\n#define D3DFVF_FONT3DVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)\n\ninline FONT2DVERTEX InitFont2DVertex( const D3DXVECTOR4& p, D3DCOLOR color,\n FLOAT tu, FLOAT tv )\n{\n FONT2DVERTEX v; v.p = p; v.color = color; v.tu = tu; v.tv = tv;\n return v;\n}\n\ninline FONT3DVERTEX InitFont3DVertex( const D3DXVECTOR3& p, const D3DXVECTOR3& n,\n FLOAT tu, FLOAT tv )\n{\n FONT3DVERTEX v; v.p = p; v.n = n; v.tu = tu; v.tv = tv;\n return v;\n}\n\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: CD3DFont()\n\/\/ Desc: Font class constructor\n\/\/-----------------------------------------------------------------------------\nDx9Font::Dx9Font(\n LPDIRECT3DDEVICE9 pd3dDevice\n )\n{\n m_pd3dDevice = NULL;\n m_pTexture = NULL;\n m_pVB = NULL;\n\n m_pStateBlockSaved = NULL;\n m_pStateBlockDrawText = NULL;\n\n \/\/ Keep a local copy of the device\n m_pd3dDevice = pd3dDevice;\n}\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: ~CD3DFont()\n\/\/ Desc: Font class destructor\n\/\/-----------------------------------------------------------------------------\nDx9Font::~Dx9Font()\n{\n InvalidateDeviceObjects();\n DeleteDeviceObjects();\n}\n\n\nDWORD\nDx9Font::GetMaxTextureWidth()\n{\n D3DCAPS9 d3dCaps;\n\n m_pd3dDevice->GetDeviceCaps( &d3dCaps );\n\n return d3dCaps.MaxTextureWidth;\n}\n\n\nHRESULT\nDx9Font::CreateTexture()\n{\n HRESULT hr;\n D3DFORMAT format;\n\n if (PIXEL_DEPTH == 16)\n format = D3DFMT_A4R4G4B4;\n else if (PIXEL_DEPTH == 32)\n format = D3DFMT_A8R8G8B8;\n\n hr = m_pd3dDevice->CreateTexture(\n m_dwTexWidth, \n m_dwTexHeight, \n 1, \n D3DUSAGE_DYNAMIC, \n format, \n D3DPOOL_DEFAULT, \n &m_pTexture, \n NULL\n );\n\n return hr;\n}\n\n\nVOID\nDx9Font::LockTexture(\n D3DLOCKED_RECT* pLockedRect\n )\n{\n m_pTexture->LockRect( 0, pLockedRect, 0, 0 );\n}\n\n\nVOID\nDx9Font::UnlockTexture()\n{\n m_pTexture->UnlockRect(0);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: RestoreDeviceObjects()\n\/\/ Desc:\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::RestoreDeviceObjects()\n{\n HRESULT hr;\n\n \/\/ Create vertex buffer for the letters\n int vertexSize = max( sizeof(FONT2DVERTEX), sizeof(FONT3DVERTEX ) );\n if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer( MAX_NUM_VERTICES * vertexSize,\n D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC, 0,\n D3DPOOL_DEFAULT, &m_pVB, NULL ) ) )\n {\n return hr;\n }\n\n \/\/ Create the state blocks for rendering text\n for( UINT which=0; which<2; which++ )\n {\n m_pd3dDevice->BeginStateBlock();\n m_pd3dDevice->SetTexture( 0, m_pTexture );\n\n if ( D3DFONT_ZENABLE & m_dwFontFlags )\n m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );\n else\n m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE );\n\n m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );\n m_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x08 );\n m_pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );\n m_pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );\n m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );\n m_pd3dDevice->SetRenderState( D3DRS_STENCILENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_CLIPPING, TRUE );\n m_pd3dDevice->SetRenderState( D3DRS_CLIPPLANEENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_DISABLE );\n m_pd3dDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE );\n m_pd3dDevice->SetRenderState( D3DRS_COLORWRITEENABLE,\n D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN |\n D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 );\n m_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );\n m_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );\n m_pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_POINT );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE );\n m_pd3dDevice->SetFVF( D3DFVF_FONT2DVERTEX );\n m_pd3dDevice->SetPixelShader( NULL );\n\n if( which==0 )\n m_pd3dDevice->EndStateBlock( &m_pStateBlockSaved );\n else\n m_pd3dDevice->EndStateBlock( &m_pStateBlockDrawText );\n }\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: InvalidateDeviceObjects()\n\/\/ Desc: Destroys all device-dependent objects\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::InvalidateDeviceObjects()\n{\n if (m_pVB)\n m_pVB->Release();\n\n if (m_pStateBlockSaved)\n m_pStateBlockSaved->Release();\n\n if (m_pStateBlockDrawText)\n m_pStateBlockDrawText->Release();\n\n m_pVB = NULL;\n m_pStateBlockSaved = NULL;\n m_pStateBlockDrawText = NULL;\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: DeleteDeviceObjects()\n\/\/ Desc: Destroys all device-dependent objects\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::DeleteDeviceObjects()\n{\n if (m_pTexture)\n m_pTexture->Release();\n\n m_pTexture = NULL;\n m_pd3dDevice = NULL;\n\n return S_OK;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Name: DrawText()\n\/\/ Desc: Draws 2D text. Note that sx and sy are in pixels\n\/\/-----------------------------------------------------------------------------\nHRESULT Dx9Font::DrawText( FLOAT sx, FLOAT sy, DWORD dwColor, TCHAR* strText, DWORD dwFlags )\n{\n if( m_pd3dDevice == NULL )\n return E_FAIL;\n\n \/\/ Setup renderstate\n m_pStateBlockSaved->Capture();\n m_pStateBlockDrawText->Apply();\n \/\/m_pd3dDevice->SetFVF( D3DFVF_FONT2DVERTEX );\n \/\/m_pd3dDevice->SetPixelShader( NULL );\n m_pd3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof(FONT2DVERTEX) );\n\n \/\/ Set filter states\n if( dwFlags & D3DFONT_FILTERED )\n {\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );\n m_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );\n }\n\n if( dwFlags & D3DFONT_RIGHT ) {\n SIZE sz;\n GetTextExtent( strText, &sz );\n sx -= (FLOAT)sz.cx;\n } else if( dwFlags & D3DFONT_CENTERED ) {\n SIZE sz;\n GetTextExtent( strText, &sz );\n sx -= (FLOAT)sz.cx\/2.0f;\n }\n\n \/\/ Adjust for character spacing\n sx -= m_dwSpacing;\n FLOAT fStartX = sx;\n\n \/\/ Fill vertex buffer\n FONT2DVERTEX* pVertices = NULL;\n DWORD dwNumTriangles = 0;\n m_pVB->Lock( 0, 0, (void**)&pVertices, D3DLOCK_DISCARD );\n\n while( *strText )\n {\n TCHAR c = *strText++;\n\n if( c == _T('\\n') )\n {\n sx = fStartX;\n sy += (m_fTexCoords[0][3]-m_fTexCoords[0][1])*m_dwTexHeight;\n }\n\n if( (c-32) < 0 || (c-32) >= (NUMBER_OF_CHARACTERS+1)-32 )\n continue;\n\n FLOAT tx1 = m_fTexCoords[c-32][0];\n FLOAT ty1 = m_fTexCoords[c-32][1];\n FLOAT tx2 = m_fTexCoords[c-32][2];\n FLOAT ty2 = m_fTexCoords[c-32][3];\n\n FLOAT w = (tx2-tx1) * m_dwTexWidth \/ m_fTextScale;\n FLOAT h = (ty2-ty1) * m_dwTexHeight \/ m_fTextScale;\n\n if( c != _T(' ') )\n {\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx1, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx2, ty1 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+w-0.5f,sy+h-0.5f,0.9f,1.0f), dwColor, tx2, ty2 );\n *pVertices++ = InitFont2DVertex( D3DXVECTOR4(sx+0-0.5f,sy+0-0.5f,0.9f,1.0f), dwColor, tx1, ty1 );\n dwNumTriangles += 2;\n\n if( dwNumTriangles*3 > (MAX_NUM_VERTICES-6) )\n {\n \/\/ Unlock, render, and relock the vertex buffer\n m_pVB->Unlock();\n m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );\n pVertices = NULL;\n m_pVB->Lock( 0, 0, (void**)&pVertices, D3DLOCK_DISCARD );\n dwNumTriangles = 0L;\n }\n }\n\n sx += w - (2 * m_dwSpacing);\n }\n\n \/\/ Unlock and render the vertex buffer\n m_pVB->Unlock();\n if( dwNumTriangles > 0 )\n m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, dwNumTriangles );\n\n \/\/ Restore the modified renderstates\n m_pStateBlockSaved->Apply();\n\n return S_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ cgp-projects\n\/\/\n\/\/ Created by HUJI Computer Graphics course staff, 2013.\n\/\/ Tweaked by HUJI Computer Games Programming staff 2014\n\/\/ Expanded by Amir Blum 2015\n\n\/\/ OpenGL Headers\n#include <GL\/glew.h>\n#ifdef __APPLE__\n#include <GLUT\/glut.h>\n#else\n#include <GL\/freeglut.h>\n#endif\n\n\/\/ OpenAL Headers\n#ifdef __APPLE__\n#include <OpenAL\/al.h>\n#include <OpenAL\/alc.h>\n#else\n#include <AL\/al.h>\n#include <AL\/alc.h>\n#endif\n#include <AL\/alut.h>\n\n\/\/ GLM headers\n#define GLM_FORCE_RADIANS\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp> \/\/ for glm::value_ptr\n\nusing namespace glm;\n\n#include \"World.h\"\n\n#include \"ShaderIO.h\"\n#include \"InputManager.h\"\n#include \"Camera.h\"\n\n#include <iostream>\n\n\/** Internal Definitions *\/\n\n#define\tWINDOW_WIDTH (1024) \/\/ initial width of the window \/\/\n#define\tWINDOW_HEIGHT (768) \/\/ initial height of the window \/\/\n#define\tWINDOW_POS_X (100) \/\/ initial X position of the window \/\/\n#define\tWINDOW_POS_Y (100) \/\/ initial Y position of the window \/\/\n\n#define RC_OK (0) \/\/ Everything went ok \/\/\n#define RC_INVALID_ARGUMENTS (1) \/\/ Invalid arguments given to the program \/\/\n#define RC_INPUT_ERROR (2) \/\/ Invalid input to the program \/\/\n\n#define\tARGUMENTS_PROGRAM (0) \/\/ program name position on argv \/\/\n#define\tARGUMENTS_INPUTFILE (1) \/\/ given input file position on argv \/\/\n#define\tARGUMENTS_REQUIRED (2) \/\/ number of required arguments \/\/\n\n\/** Key definitions *\/\n\n#define KEY_ESC ('\\e') \/\/ Key used to terminate the program - ESC \/\/\n#define KEY_RESET ('r')\n#define KEY_FULLSCREEN ('f')\n\n\/** display callback *\/\nvoid display(void);\n\n\/** window reshape callback *\/\nvoid windowResize(int width, int height);\n\n\/** keyboardDown callback *\/\nvoid keyboardDown(unsigned char key, int x, int y);\n\n\/** keyboardUp callback *\/\nvoid keyboardUp(unsigned char key, int x, int y);\n\n\/** mouse click callback *\/\nvoid mouse(int button, int state, int x, int y) ;\n\n\/** mouse dragging callback *\/\nvoid motion(int x, int y) ;\n\n\/\/ Game-related objects\nWorld *_world;\n\n\/** main function *\/\nint main(int argc, char* argv[])\n{\n std::cout << \"Starting ex4...\" << std::endl;\n \n \/\/ Initialize GLUT\n glutInit(&argc, argv) ;\n#ifdef __APPLE__\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_3_2_CORE_PROFILE) ;\n#else\n glutInitContextVersion(3, 3);\n glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);\n glutInitContextProfile(GLUT_CORE_PROFILE);\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);\n#endif\n glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);\n glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y);\n glutCreateWindow(\"CGP Ex 3\");\n \n \/\/ Initialize GLEW\n glewExperimental = GL_TRUE;\n int glewStatus = glewInit();\n if (glewStatus != GLEW_OK) {\n std::cerr << \"Unable to initialize GLEW ... exiting\" << std::endl;\n exit(1);\n }\n \n \/\/ GLEW has a \"bug\" where it sets a glError. According to the wiki this\n \/\/ can be safely ignored, so we clear the error here:\n glGetError();\n \n#ifdef __APPLE__\n GLint sync = 1;\n CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync);\n#endif\n \n \/\/ Enable opengl drawing features\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n \n \/\/ Set callback functions:\n glutDisplayFunc(display) ;\n glutReshapeFunc(windowResize) ;\n glutKeyboardFunc(keyboardDown);\n glutKeyboardUpFunc(keyboardUp);\n glutMouseFunc(mouse);\n glutMotionFunc(motion);\n glutPassiveMotionFunc(motion);\n \n glutSetCursor(GLUT_CURSOR_NONE);\n \n \/\/ Initialize ALUT (& background music)\n alutInit(&argc, argv);\n \n \/\/ Initialize random seed\n srand(time(NULL));\n \n \/\/ Set up game\n _world = new World();\n \n \/\/ Set clear color to black:\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n \n \/\/ Start events\/drawing loop\n glutMainLoop();\n \n return 0;\n}\n\n\/\/ Time\nint oldTimeSinceStart = 0;\nfloat physicsTimeStep = 1.0f \/ 50.0f;\nfloat accumulator = 0.0f;\n\n\/\/ FPS\nint frames = 0;\nint fpsCounter = 0;\n\nvoid display(void)\n{\n \/\/ Update the delta\n int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);\n int deltaTime = timeSinceStart - oldTimeSinceStart;\n oldTimeSinceStart = timeSinceStart;\n \n float dt = (float)deltaTime \/ 1000.0f;\n if (dt > 0.25f) {\n dt = 0.25f;\n }\n \n \/\/ We fix the physics timestep based on the information in the following\n \/\/ article: http:\/\/gafferongames.com\/game-physics\/fix-your-timestep\/\n accumulator += dt;\n while (accumulator >= physicsTimeStep) {\n\/\/ std::cout << \"physics update\" << std::endl;\n _world->recursiveFixedUpdate(physicsTimeStep);\n accumulator -= physicsTimeStep;\n }\n \n const double physicsInterpolation = accumulator \/ physicsTimeStep;\n\n \/\/ Update the game state\n _world->recursiveUpdate(dt);\n \n \n \/\/ Drawing time\n \n \/\/ Clear the screen buffer\n glClearColor(0.15f, 0.0f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n \n \/\/ Tell the world to draw itself\n _world->recursiveRender();\n \n \/\/ Print fps\n frames++;\n fpsCounter += deltaTime;\n if (fpsCounter > 1000) {\n std::cout << (frames * 1000) \/ fpsCounter << \" FPS\" << std::endl;\n fpsCounter = fpsCounter - 1000;\n frames = 0;\n }\n \n \/\/ Swap those buffers so someone will actually see the results... \/\/\n glutSwapBuffers();\n \n \/\/ Refresh the display\n glutPostRedisplay();\n}\n\n\/\/ This method is called when the window is resized\nint _screenWidth, _screenHeight;\nvoid windowResize(int w, int h)\n{\n _screenWidth = w;\n _screenHeight = h;\n \n \/\/ set the new viewport \/\/\n glViewport(0, 0, w, h);\n \n \/\/ set the perspective of the camera\n Camera::MainCamera()->resize(w, h);\n \n \/\/ Refresh the display \/\/\n glutPostRedisplay();\n}\n\nvoid toggleFullscreen()\n{\n static bool fullscreen = false;\n static int previousWidth, previousHeight;\n static int previousX, previousY;\n \n if (!fullscreen) {\n previousWidth = _screenWidth;\n previousHeight = _screenHeight;\n previousX = glutGet(GLUT_WINDOW_X);\n previousY = glutGet(GLUT_WINDOW_Y);\n \n glutFullScreen();\n \n fullscreen = true;\n } else {\n glutReshapeWindow(previousWidth, previousHeight);\n glutPositionWindow(previousX, previousY);\n \n fullscreen = false;\n }\n}\n\n\/********************************************************************\n * Function :\tkeyboard\n * Arguments :\tkey : the key that was pressed\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles all the keyboard input from the user.\n * It supports terminating the application when the KEY_QUIT is pressed.\n *\n \\******************************************************************\/\nvoid keyboardDown(unsigned char key, int x, int y)\n{\n unsigned int lower_key = tolower(key);\n \n if (lower_key == KEY_ESC)\n {\n exit(RC_OK);\n }\n else if (lower_key == KEY_RESET)\n {\n delete _world;\n _world = new World;\n Camera::MainCamera()->resize(_screenWidth, _screenHeight);\n }\n else if (lower_key == KEY_FULLSCREEN)\n {\n toggleFullscreen();\n }\n \n InputManager::Instance().handleKeyDown(lower_key, x, y);\n}\n\n\/********************************************************************\n * Function :\tkeyboardUp\n * Arguments :\tkey : the key that was relased\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles all the keyboard input from the user.\n * It supports terminating the application when the KEY_QUIT is pressed.\n *\n \\******************************************************************\/\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n unsigned int lower_key = tolower(key);\n \n InputManager::Instance().handleKeyUp(lower_key, x, y);\n}\n\n\/********************************************************************\n * Function : mouse\n * Arguments : button : the button that was engaged in some action\n * state : the new state of that button\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles mouse actions.\n *\n \\******************************************************************\/\nvoid mouse(int button, int state, int x, int y)\n{\n if(button == GLUT_LEFT_BUTTON)\n {\n \n }\n else if (button == GLUT_RIGHT_BUTTON)\n {\n \n }\n \n return;\n}\n\n\n\/********************************************************************\n * Function : motion\n * Arguments : x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles mouse dragging events.\n *\n \\******************************************************************\/\nvoid motion(int x, int y)\n{\n float oglX = x \/ _screenWidth;\n float oglY = y \/ _screenHeight;\n \n oglX = oglX * 2.0f - 1.0f;\n oglY = oglY * -2.0f + 1.0f;\n \n InputManager::Instance().handleMouseMove(oglX, oglY);\n}\n<commit_msg>Don't start physics until game has started<commit_after>\/\/\n\/\/ cgp-projects\n\/\/\n\/\/ Created by HUJI Computer Graphics course staff, 2013.\n\/\/ Tweaked by HUJI Computer Games Programming staff 2014\n\/\/ Expanded by Amir Blum 2015\n\n\/\/ OpenGL Headers\n#include <GL\/glew.h>\n#ifdef __APPLE__\n#include <GLUT\/glut.h>\n#else\n#include <GL\/freeglut.h>\n#endif\n\n\/\/ OpenAL Headers\n#ifdef __APPLE__\n#include <OpenAL\/al.h>\n#include <OpenAL\/alc.h>\n#else\n#include <AL\/al.h>\n#include <AL\/alc.h>\n#endif\n#include <AL\/alut.h>\n\n\/\/ GLM headers\n#define GLM_FORCE_RADIANS\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp> \/\/ for glm::value_ptr\n\nusing namespace glm;\n\n#include \"World.h\"\n\n#include \"ShaderIO.h\"\n#include \"InputManager.h\"\n#include \"GameState.h\"\n#include \"Camera.h\"\n\n#include <iostream>\n\n\/** Internal Definitions *\/\n\n#define\tWINDOW_WIDTH (1024) \/\/ initial width of the window \/\/\n#define\tWINDOW_HEIGHT (768) \/\/ initial height of the window \/\/\n#define\tWINDOW_POS_X (100) \/\/ initial X position of the window \/\/\n#define\tWINDOW_POS_Y (100) \/\/ initial Y position of the window \/\/\n\n#define RC_OK (0) \/\/ Everything went ok \/\/\n#define RC_INVALID_ARGUMENTS (1) \/\/ Invalid arguments given to the program \/\/\n#define RC_INPUT_ERROR (2) \/\/ Invalid input to the program \/\/\n\n#define\tARGUMENTS_PROGRAM (0) \/\/ program name position on argv \/\/\n#define\tARGUMENTS_INPUTFILE (1) \/\/ given input file position on argv \/\/\n#define\tARGUMENTS_REQUIRED (2) \/\/ number of required arguments \/\/\n\n\/** Key definitions *\/\n\n#define KEY_ESC ('\\e') \/\/ Key used to terminate the program - ESC \/\/\n#define KEY_RESET ('r')\n#define KEY_FULLSCREEN ('f')\n\n\/** display callback *\/\nvoid display(void);\n\n\/** window reshape callback *\/\nvoid windowResize(int width, int height);\n\n\/** keyboardDown callback *\/\nvoid keyboardDown(unsigned char key, int x, int y);\n\n\/** keyboardUp callback *\/\nvoid keyboardUp(unsigned char key, int x, int y);\n\n\/** mouse click callback *\/\nvoid mouse(int button, int state, int x, int y) ;\n\n\/** mouse dragging callback *\/\nvoid motion(int x, int y) ;\n\n\/\/ Game-related objects\nWorld *_world;\n\n\/** main function *\/\nint main(int argc, char* argv[])\n{\n std::cout << \"Starting ex4...\" << std::endl;\n \n \/\/ Initialize GLUT\n glutInit(&argc, argv) ;\n#ifdef __APPLE__\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_3_2_CORE_PROFILE) ;\n#else\n glutInitContextVersion(3, 3);\n glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);\n glutInitContextProfile(GLUT_CORE_PROFILE);\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);\n#endif\n glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);\n glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y);\n glutCreateWindow(\"CGP Ex 3\");\n \n \/\/ Initialize GLEW\n glewExperimental = GL_TRUE;\n int glewStatus = glewInit();\n if (glewStatus != GLEW_OK) {\n std::cerr << \"Unable to initialize GLEW ... exiting\" << std::endl;\n exit(1);\n }\n \n \/\/ GLEW has a \"bug\" where it sets a glError. According to the wiki this\n \/\/ can be safely ignored, so we clear the error here:\n glGetError();\n \n#ifdef __APPLE__\n GLint sync = 1;\n CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync);\n#endif\n \n \/\/ Enable opengl drawing features\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n \n \/\/ Set callback functions:\n glutDisplayFunc(display) ;\n glutReshapeFunc(windowResize) ;\n glutKeyboardFunc(keyboardDown);\n glutKeyboardUpFunc(keyboardUp);\n glutMouseFunc(mouse);\n glutMotionFunc(motion);\n glutPassiveMotionFunc(motion);\n \n glutSetCursor(GLUT_CURSOR_NONE);\n \n \/\/ Initialize ALUT (& background music)\n alutInit(&argc, argv);\n \n \/\/ Initialize random seed\n srand(time(NULL));\n \n \/\/ Set up game\n _world = new World();\n \n \/\/ Set clear color to black:\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n \n \/\/ Start events\/drawing loop\n glutMainLoop();\n \n return 0;\n}\n\n\/\/ Time\nint oldTimeSinceStart = 0;\nfloat physicsTimeStep = 1.0f \/ 50.0f;\nfloat accumulator = 0.0f;\n\n\/\/ FPS\nint frames = 0;\nint fpsCounter = 0;\n\nvoid display(void)\n{\n \/\/ Update the delta\n int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);\n int deltaTime = timeSinceStart - oldTimeSinceStart;\n oldTimeSinceStart = timeSinceStart;\n \n float dt = (float)deltaTime \/ 1000.0f;\n if (dt > 0.25f) {\n dt = 0.25f;\n }\n \n if (GameState::Instance().gameStarted) {\n \/\/ We fix the physics timestep based on the information in the following\n \/\/ article: http:\/\/gafferongames.com\/game-physics\/fix-your-timestep\/\n accumulator += dt;\n while (accumulator >= physicsTimeStep) {\n \/\/ std::cout << \"physics update\" << std::endl;\n _world->recursiveFixedUpdate(physicsTimeStep);\n accumulator -= physicsTimeStep;\n }\n }\n \n const double physicsInterpolation = accumulator \/ physicsTimeStep;\n\n \/\/ Update the game state\n _world->recursiveUpdate(dt);\n \n \n \/\/ Drawing time\n \n \/\/ Clear the screen buffer\n glClearColor(0.15f, 0.0f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n \n \/\/ Tell the world to draw itself\n _world->recursiveRender();\n \n \/\/ Print fps\n frames++;\n fpsCounter += deltaTime;\n if (fpsCounter > 1000) {\n std::cout << (frames * 1000) \/ fpsCounter << \" FPS\" << std::endl;\n fpsCounter = fpsCounter - 1000;\n frames = 0;\n }\n \n \/\/ Swap those buffers so someone will actually see the results... \/\/\n glutSwapBuffers();\n \n \/\/ Refresh the display\n glutPostRedisplay();\n}\n\n\/\/ This method is called when the window is resized\nint _screenWidth, _screenHeight;\nvoid windowResize(int w, int h)\n{\n _screenWidth = w;\n _screenHeight = h;\n \n \/\/ set the new viewport \/\/\n glViewport(0, 0, w, h);\n \n \/\/ set the perspective of the camera\n Camera::MainCamera()->resize(w, h);\n \n \/\/ Refresh the display \/\/\n glutPostRedisplay();\n}\n\nvoid toggleFullscreen()\n{\n static bool fullscreen = false;\n static int previousWidth, previousHeight;\n static int previousX, previousY;\n \n if (!fullscreen) {\n previousWidth = _screenWidth;\n previousHeight = _screenHeight;\n previousX = glutGet(GLUT_WINDOW_X);\n previousY = glutGet(GLUT_WINDOW_Y);\n \n glutFullScreen();\n \n fullscreen = true;\n } else {\n glutReshapeWindow(previousWidth, previousHeight);\n glutPositionWindow(previousX, previousY);\n \n fullscreen = false;\n }\n}\n\n\/********************************************************************\n * Function :\tkeyboard\n * Arguments :\tkey : the key that was pressed\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles all the keyboard input from the user.\n * It supports terminating the application when the KEY_QUIT is pressed.\n *\n \\******************************************************************\/\nvoid keyboardDown(unsigned char key, int x, int y)\n{\n unsigned int lower_key = tolower(key);\n \n if (lower_key == KEY_ESC)\n {\n exit(RC_OK);\n }\n else if (lower_key == KEY_RESET)\n {\n delete _world;\n _world = new World;\n Camera::MainCamera()->resize(_screenWidth, _screenHeight);\n }\n else if (lower_key == KEY_FULLSCREEN)\n {\n toggleFullscreen();\n }\n \n InputManager::Instance().handleKeyDown(lower_key, x, y);\n}\n\n\/********************************************************************\n * Function :\tkeyboardUp\n * Arguments :\tkey : the key that was relased\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles all the keyboard input from the user.\n * It supports terminating the application when the KEY_QUIT is pressed.\n *\n \\******************************************************************\/\nvoid keyboardUp(unsigned char key, int x, int y)\n{\n unsigned int lower_key = tolower(key);\n \n InputManager::Instance().handleKeyUp(lower_key, x, y);\n}\n\n\/********************************************************************\n * Function : mouse\n * Arguments : button : the button that was engaged in some action\n * state : the new state of that button\n * x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles mouse actions.\n *\n \\******************************************************************\/\nvoid mouse(int button, int state, int x, int y)\n{\n if(button == GLUT_LEFT_BUTTON)\n {\n \n }\n else if (button == GLUT_RIGHT_BUTTON)\n {\n \n }\n \n return;\n}\n\n\n\/********************************************************************\n * Function : motion\n * Arguments : x : x value of the current mouse location\n * y : y value of the current mouse location\n * Returns : n\/a\n * Throws : n\/a\n *\n * Purpose : This function handles mouse dragging events.\n *\n \\******************************************************************\/\nvoid motion(int x, int y)\n{\n float oglX = x \/ _screenWidth;\n float oglY = y \/ _screenHeight;\n \n oglX = oglX * 2.0f - 1.0f;\n oglY = oglY * -2.0f + 1.0f;\n \n InputManager::Instance().handleMouseMove(oglX, oglY);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Accounts model item, represents an account in the contactlist tree\n * This file is based on TelepathyQtYell Models\n *\n * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>\n * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"accounts-model-item.h\"\n\n#include <TelepathyQt\/Account>\n#include <TelepathyQt\/ContactManager>\n\n#include \"accounts-model.h\"\n#include \"contact-model-item.h\"\n\nstruct AccountsModelItem::Private\n{\n Private(const Tp::AccountPtr &account)\n : mAccount(account),\n mOnlineCount(0)\n {\n }\n\n void setStatus(const QString &value);\n void setStatusMessage(const QString &value);\n\n Tp::AccountPtr mAccount;\n int mOnlineCount;\n};\n\nvoid AccountsModelItem::Private::setStatus(const QString &value)\n{\n Tp::Presence presence = mAccount->currentPresence().barePresence();\n presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString());\n mAccount->setRequestedPresence(presence);\n}\n\nvoid AccountsModelItem::Private::setStatusMessage(const QString &value)\n{\n Tp::Presence presence = mAccount->currentPresence().barePresence();\n presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value);\n mAccount->setRequestedPresence(presence);\n}\n\nAccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account)\n : mPriv(new Private(account))\n{\n if (!mPriv->mAccount->connection().isNull()) {\n QTimer::singleShot(0, this, SLOT(onNewConnection()));\n }\n\n connect(mPriv->mAccount.data(),\n SIGNAL(removed()),\n SLOT(onRemoved()));\n connect(mPriv->mAccount.data(),\n SIGNAL(serviceNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(profileChanged(Tp::ProfilePtr)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(iconNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(nicknameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(normalizedNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(validityChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(stateChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectsAutomaticallyPropertyChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(parametersChanged(QVariantMap)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(changingPresence(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(automaticPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(currentPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(requestedPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(onlinenessChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(avatarChanged(Tp::Avatar)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(onlinenessChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),\n SLOT(onStatusChanged(Tp::ConnectionStatus)));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n}\n\nAccountsModelItem::~AccountsModelItem()\n{\n delete mPriv;\n}\n\nQVariant AccountsModelItem::data(int role) const\n{\n switch (role) {\n case AccountsModel::ItemRole:\n return QVariant::fromValue((AccountsModelItem*)this);\n case AccountsModel::IdRole:\n return mPriv->mAccount->uniqueIdentifier();\n case AccountsModel::AvatarRole:\n return QVariant::fromValue(mPriv->mAccount->avatar());\n case AccountsModel::ValidRole:\n return mPriv->mAccount->isValid();\n case AccountsModel::EnabledRole:\n return mPriv->mAccount->isEnabled();\n case AccountsModel::ConnectionManagerNameRole:\n return mPriv->mAccount->cmName();\n case AccountsModel::ProtocolNameRole:\n return mPriv->mAccount->protocolName();\n case AccountsModel::DisplayNameRole:\n case Qt::DisplayRole:\n return mPriv->mAccount->displayName();\n case AccountsModel::IconRole:\n return mPriv->mAccount->iconName();\n case AccountsModel::NicknameRole:\n return mPriv->mAccount->nickname();\n case AccountsModel::ConnectsAutomaticallyRole:\n return mPriv->mAccount->connectsAutomatically();\n case AccountsModel::ChangingPresenceRole:\n return mPriv->mAccount->isChangingPresence();\n case AccountsModel::AutomaticPresenceRole:\n return mPriv->mAccount->automaticPresence().status();\n case AccountsModel::AutomaticPresenceTypeRole:\n return mPriv->mAccount->automaticPresence().type();\n case AccountsModel::AutomaticPresenceStatusMessageRole:\n return mPriv->mAccount->automaticPresence().statusMessage();\n case AccountsModel::CurrentPresenceRole:\n return mPriv->mAccount->currentPresence().status();\n case AccountsModel::CurrentPresenceTypeRole:\n return mPriv->mAccount->currentPresence().type();\n case AccountsModel::CurrentPresenceStatusMessageRole:\n return mPriv->mAccount->currentPresence().statusMessage();\n case AccountsModel::RequestedPresenceRole:\n return mPriv->mAccount->requestedPresence().status();\n case AccountsModel::RequestedPresenceTypeRole:\n return mPriv->mAccount->requestedPresence().type();\n case AccountsModel::RequestedPresenceStatusMessageRole:\n return mPriv->mAccount->requestedPresence().statusMessage();\n case AccountsModel::ConnectionStatusRole:\n return mPriv->mAccount->connectionStatus();\n case AccountsModel::ConnectionStatusReasonRole:\n return mPriv->mAccount->connectionStatusReason();\n case AccountsModel::TotalUsersCountRole:\n return size();\n case AccountsModel::OnlineUsersCountRole:\n return mPriv->mOnlineCount;\n default:\n return QVariant();\n }\n}\n\nbool AccountsModelItem::setData(int role, const QVariant &value)\n{\n switch (role) {\n case AccountsModel::EnabledRole:\n setEnabled(value.toBool());\n return true;\n case AccountsModel::RequestedPresenceRole:\n mPriv->setStatus(value.toString());\n return true;\n case AccountsModel::RequestedPresenceStatusMessageRole:\n mPriv->setStatusMessage(value.toString());\n return true;\n case AccountsModel::NicknameRole:\n setNickname(value.toString());\n return true;\n case AccountsModel::AvatarRole:\n mPriv->mAccount->setAvatar(value.value<Tp::Avatar>());\n return true;\n default:\n return false;\n }\n}\n\nTp::AccountPtr AccountsModelItem::account() const\n{\n return mPriv->mAccount;\n}\n\nvoid AccountsModelItem::setEnabled(bool value)\n{\n mPriv->mAccount->setEnabled(value);\n}\n\nvoid AccountsModelItem::setNickname(const QString &value)\n{\n mPriv->mAccount->setNickname(value);\n}\n\nvoid AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage)\n{\n Tp::Presence presence;\n presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);\n mPriv->mAccount->setAutomaticPresence(presence);\n}\n\nvoid AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage)\n{\n Tp::Presence presence;\n presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);\n mPriv->mAccount->setRequestedPresence(presence);\n}\n\nvoid AccountsModelItem::onRemoved()\n{\n int index = parent()->indexOf(this);\n Q_EMIT childrenRemoved(parent(), index, index);\n}\n\nvoid AccountsModelItem::onChanged()\n{\n Q_EMIT changed(this);\n}\n\nvoid AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts,\n const Tp::Contacts &removedContacts)\n{\n Q_FOREACH (const Tp::ContactPtr &contact, removedContacts) {\n for (int i = 0; i < size(); ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item->contact() == contact) {\n Q_EMIT childrenRemoved(this, i, i);\n break;\n }\n }\n }\n\n \/\/ get the list of contact ids in the children\n QStringList idList;\n int numElems = size();\n for (int i = 0; i < numElems; ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n idList.append(item->contact()->id());\n }\n }\n\n QList<TreeNode *> newNodes;\n Q_FOREACH (const Tp::ContactPtr &contact, addedContacts) {\n if (!idList.contains(contact->id())) {\n newNodes.append(new ContactModelItem(contact));\n }\n }\n if (!newNodes.isEmpty()) {\n Q_EMIT childrenAdded(this, newNodes);\n }\n\n countOnlineContacts();\n}\n\nvoid AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status)\n{\n onChanged();\n\n Q_EMIT connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status);\n}\n\nvoid AccountsModelItem::onNewConnection()\n{\n onConnectionChanged(mPriv->mAccount->connection());\n}\n\nvoid AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection)\n{\n onChanged();\n\n \/\/ if the connection is invalid or disconnected, clear the contacts list\n if (connection.isNull()\n || !connection->isValid()\n || connection->status() == Tp::ConnectionStatusDisconnected) {\n if (size() > 0) {\n Q_EMIT childrenRemoved(this, 0, size() - 1);\n }\n return;\n }\n\n Tp::ContactManagerPtr manager = connection->contactManager();\n\n connect(manager.data(),\n SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,\n Tp::Channel::GroupMemberChangeDetails)),\n SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));\n\n connect(manager.data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n onContactManagerStateChanged(manager->state());\n}\n\nvoid AccountsModelItem::onContactManagerStateChanged(Tp::ContactListState state)\n{\n if (state == Tp::ContactListStateSuccess) {\n clearContacts();\n addKnownContacts();\n }\n}\n\n\n\nvoid AccountsModelItem::clearContacts()\n{\n if (!mPriv->mAccount->connection().isNull() &&\n mPriv->mAccount->connection()->isValid()) {\n Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();\n Tp::Contacts contacts = manager->allKnownContacts();\n\n \/\/ remove the items no longer present\n for (int i = 0; i < size(); ++i) {\n bool exists = false;\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n Tp::ContactPtr itemContact = item->contact();\n if (contacts.contains(itemContact)) {\n exists = true;\n }\n }\n if (!exists) {\n Q_EMIT childrenRemoved(this, i, i);\n }\n }\n }\n}\n\nvoid AccountsModelItem::addKnownContacts()\n{\n \/\/ reload the known contacts if it has a connection\n QList<TreeNode *> newNodes;\n if (!mPriv->mAccount->connection().isNull() &&\n mPriv->mAccount->connection()->isValid()) {\n Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();\n Tp::Contacts contacts = manager->allKnownContacts();\n\n \/\/ get the list of contact ids in the children\n QStringList idList;\n int numElems = size();\n\n for (int i = 0; i < numElems; ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n idList.append(item->contact()->id());\n }\n }\n\n \/\/ only add the contact item if it is new\n Q_FOREACH (const Tp::ContactPtr &contact, contacts) {\n if (!idList.contains(contact->id())) {\n newNodes.append(new ContactModelItem(contact));\n }\n }\n }\n\n if (newNodes.count() > 0) {\n Q_EMIT childrenAdded(this, newNodes);\n }\n\n countOnlineContacts();\n}\n\nvoid AccountsModelItem::countOnlineContacts()\n{\n int tmpCounter = 0;\n for (int i = 0; i < size(); ++i) {\n ContactModelItem* contactNode = qobject_cast<ContactModelItem*>(childAt(i));\n Q_ASSERT(contactNode);\n if (contactNode->data(AccountsModel::PresenceTypeRole).toUInt() != Tp::ConnectionPresenceTypeOffline\n && contactNode->data(AccountsModel::PresenceTypeRole).toUInt() != Tp::ConnectionPresenceTypeUnknown) {\n tmpCounter++;\n }\n }\n\n mPriv->mOnlineCount = tmpCounter;\n}\n\n#include \"accounts-model-item.moc\"\n<commit_msg>Add decoration role to accounts model<commit_after>\/*\n * Accounts model item, represents an account in the contactlist tree\n * This file is based on TelepathyQtYell Models\n *\n * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>\n * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"accounts-model-item.h\"\n\n#include <TelepathyQt\/Account>\n#include <TelepathyQt\/ContactManager>\n\n#include \"accounts-model.h\"\n#include \"contact-model-item.h\"\n\n#include <KIcon>\n\nstruct AccountsModelItem::Private\n{\n Private(const Tp::AccountPtr &account)\n : mAccount(account),\n mOnlineCount(0)\n {\n }\n\n void setStatus(const QString &value);\n void setStatusMessage(const QString &value);\n\n Tp::AccountPtr mAccount;\n int mOnlineCount;\n};\n\nvoid AccountsModelItem::Private::setStatus(const QString &value)\n{\n Tp::Presence presence = mAccount->currentPresence().barePresence();\n presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString());\n mAccount->setRequestedPresence(presence);\n}\n\nvoid AccountsModelItem::Private::setStatusMessage(const QString &value)\n{\n Tp::Presence presence = mAccount->currentPresence().barePresence();\n presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value);\n mAccount->setRequestedPresence(presence);\n}\n\nAccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account)\n : mPriv(new Private(account))\n{\n if (!mPriv->mAccount->connection().isNull()) {\n QTimer::singleShot(0, this, SLOT(onNewConnection()));\n }\n\n connect(mPriv->mAccount.data(),\n SIGNAL(removed()),\n SLOT(onRemoved()));\n connect(mPriv->mAccount.data(),\n SIGNAL(serviceNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(profileChanged(Tp::ProfilePtr)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(iconNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(nicknameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(normalizedNameChanged(QString)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(validityChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(stateChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectsAutomaticallyPropertyChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(parametersChanged(QVariantMap)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(changingPresence(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(automaticPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(currentPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(requestedPresenceChanged(Tp::Presence)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(onlinenessChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(avatarChanged(Tp::Avatar)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(onlinenessChanged(bool)),\n SLOT(onChanged()));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),\n SLOT(onStatusChanged(Tp::ConnectionStatus)));\n connect(mPriv->mAccount.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n}\n\nAccountsModelItem::~AccountsModelItem()\n{\n delete mPriv;\n}\n\nQVariant AccountsModelItem::data(int role) const\n{\n switch (role) {\n case AccountsModel::ItemRole:\n return QVariant::fromValue((AccountsModelItem*)this);\n case AccountsModel::IdRole:\n return mPriv->mAccount->uniqueIdentifier();\n case AccountsModel::AvatarRole:\n return QVariant::fromValue(mPriv->mAccount->avatar());\n case AccountsModel::ValidRole:\n return mPriv->mAccount->isValid();\n case AccountsModel::EnabledRole:\n return mPriv->mAccount->isEnabled();\n case AccountsModel::ConnectionManagerNameRole:\n return mPriv->mAccount->cmName();\n case AccountsModel::ProtocolNameRole:\n return mPriv->mAccount->protocolName();\n case AccountsModel::DisplayNameRole:\n case Qt::DisplayRole:\n return mPriv->mAccount->displayName();\n case Qt::DecorationRole:\n return KIcon(mPriv->mAccount->iconName());\n case AccountsModel::IconRole:\n return mPriv->mAccount->iconName();\n case AccountsModel::NicknameRole:\n return mPriv->mAccount->nickname();\n case AccountsModel::ConnectsAutomaticallyRole:\n return mPriv->mAccount->connectsAutomatically();\n case AccountsModel::ChangingPresenceRole:\n return mPriv->mAccount->isChangingPresence();\n case AccountsModel::AutomaticPresenceRole:\n return mPriv->mAccount->automaticPresence().status();\n case AccountsModel::AutomaticPresenceTypeRole:\n return mPriv->mAccount->automaticPresence().type();\n case AccountsModel::AutomaticPresenceStatusMessageRole:\n return mPriv->mAccount->automaticPresence().statusMessage();\n case AccountsModel::CurrentPresenceRole:\n return mPriv->mAccount->currentPresence().status();\n case AccountsModel::CurrentPresenceTypeRole:\n return mPriv->mAccount->currentPresence().type();\n case AccountsModel::CurrentPresenceStatusMessageRole:\n return mPriv->mAccount->currentPresence().statusMessage();\n case AccountsModel::RequestedPresenceRole:\n return mPriv->mAccount->requestedPresence().status();\n case AccountsModel::RequestedPresenceTypeRole:\n return mPriv->mAccount->requestedPresence().type();\n case AccountsModel::RequestedPresenceStatusMessageRole:\n return mPriv->mAccount->requestedPresence().statusMessage();\n case AccountsModel::ConnectionStatusRole:\n return mPriv->mAccount->connectionStatus();\n case AccountsModel::ConnectionStatusReasonRole:\n return mPriv->mAccount->connectionStatusReason();\n case AccountsModel::TotalUsersCountRole:\n return size();\n case AccountsModel::OnlineUsersCountRole:\n return mPriv->mOnlineCount;\n default:\n return QVariant();\n }\n}\n\nbool AccountsModelItem::setData(int role, const QVariant &value)\n{\n switch (role) {\n case AccountsModel::EnabledRole:\n setEnabled(value.toBool());\n return true;\n case AccountsModel::RequestedPresenceRole:\n mPriv->setStatus(value.toString());\n return true;\n case AccountsModel::RequestedPresenceStatusMessageRole:\n mPriv->setStatusMessage(value.toString());\n return true;\n case AccountsModel::NicknameRole:\n setNickname(value.toString());\n return true;\n case AccountsModel::AvatarRole:\n mPriv->mAccount->setAvatar(value.value<Tp::Avatar>());\n return true;\n default:\n return false;\n }\n}\n\nTp::AccountPtr AccountsModelItem::account() const\n{\n return mPriv->mAccount;\n}\n\nvoid AccountsModelItem::setEnabled(bool value)\n{\n mPriv->mAccount->setEnabled(value);\n}\n\nvoid AccountsModelItem::setNickname(const QString &value)\n{\n mPriv->mAccount->setNickname(value);\n}\n\nvoid AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage)\n{\n Tp::Presence presence;\n presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);\n mPriv->mAccount->setAutomaticPresence(presence);\n}\n\nvoid AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage)\n{\n Tp::Presence presence;\n presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage);\n mPriv->mAccount->setRequestedPresence(presence);\n}\n\nvoid AccountsModelItem::onRemoved()\n{\n int index = parent()->indexOf(this);\n Q_EMIT childrenRemoved(parent(), index, index);\n}\n\nvoid AccountsModelItem::onChanged()\n{\n Q_EMIT changed(this);\n}\n\nvoid AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts,\n const Tp::Contacts &removedContacts)\n{\n Q_FOREACH (const Tp::ContactPtr &contact, removedContacts) {\n for (int i = 0; i < size(); ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item->contact() == contact) {\n Q_EMIT childrenRemoved(this, i, i);\n break;\n }\n }\n }\n\n \/\/ get the list of contact ids in the children\n QStringList idList;\n int numElems = size();\n for (int i = 0; i < numElems; ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n idList.append(item->contact()->id());\n }\n }\n\n QList<TreeNode *> newNodes;\n Q_FOREACH (const Tp::ContactPtr &contact, addedContacts) {\n if (!idList.contains(contact->id())) {\n newNodes.append(new ContactModelItem(contact));\n }\n }\n if (!newNodes.isEmpty()) {\n Q_EMIT childrenAdded(this, newNodes);\n }\n\n countOnlineContacts();\n}\n\nvoid AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status)\n{\n onChanged();\n\n Q_EMIT connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status);\n}\n\nvoid AccountsModelItem::onNewConnection()\n{\n onConnectionChanged(mPriv->mAccount->connection());\n}\n\nvoid AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection)\n{\n onChanged();\n\n \/\/ if the connection is invalid or disconnected, clear the contacts list\n if (connection.isNull()\n || !connection->isValid()\n || connection->status() == Tp::ConnectionStatusDisconnected) {\n if (size() > 0) {\n Q_EMIT childrenRemoved(this, 0, size() - 1);\n }\n return;\n }\n\n Tp::ContactManagerPtr manager = connection->contactManager();\n\n connect(manager.data(),\n SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,\n Tp::Channel::GroupMemberChangeDetails)),\n SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts)));\n\n connect(manager.data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n onContactManagerStateChanged(manager->state());\n}\n\nvoid AccountsModelItem::onContactManagerStateChanged(Tp::ContactListState state)\n{\n if (state == Tp::ContactListStateSuccess) {\n clearContacts();\n addKnownContacts();\n }\n}\n\n\n\nvoid AccountsModelItem::clearContacts()\n{\n if (!mPriv->mAccount->connection().isNull() &&\n mPriv->mAccount->connection()->isValid()) {\n Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();\n Tp::Contacts contacts = manager->allKnownContacts();\n\n \/\/ remove the items no longer present\n for (int i = 0; i < size(); ++i) {\n bool exists = false;\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n Tp::ContactPtr itemContact = item->contact();\n if (contacts.contains(itemContact)) {\n exists = true;\n }\n }\n if (!exists) {\n Q_EMIT childrenRemoved(this, i, i);\n }\n }\n }\n}\n\nvoid AccountsModelItem::addKnownContacts()\n{\n \/\/ reload the known contacts if it has a connection\n QList<TreeNode *> newNodes;\n if (!mPriv->mAccount->connection().isNull() &&\n mPriv->mAccount->connection()->isValid()) {\n Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager();\n Tp::Contacts contacts = manager->allKnownContacts();\n\n \/\/ get the list of contact ids in the children\n QStringList idList;\n int numElems = size();\n\n for (int i = 0; i < numElems; ++i) {\n ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i));\n if (item) {\n idList.append(item->contact()->id());\n }\n }\n\n \/\/ only add the contact item if it is new\n Q_FOREACH (const Tp::ContactPtr &contact, contacts) {\n if (!idList.contains(contact->id())) {\n newNodes.append(new ContactModelItem(contact));\n }\n }\n }\n\n if (newNodes.count() > 0) {\n Q_EMIT childrenAdded(this, newNodes);\n }\n\n countOnlineContacts();\n}\n\nvoid AccountsModelItem::countOnlineContacts()\n{\n int tmpCounter = 0;\n for (int i = 0; i < size(); ++i) {\n ContactModelItem* contactNode = qobject_cast<ContactModelItem*>(childAt(i));\n Q_ASSERT(contactNode);\n if (contactNode->data(AccountsModel::PresenceTypeRole).toUInt() != Tp::ConnectionPresenceTypeOffline\n && contactNode->data(AccountsModel::PresenceTypeRole).toUInt() != Tp::ConnectionPresenceTypeUnknown) {\n tmpCounter++;\n }\n }\n\n mPriv->mOnlineCount = tmpCounter;\n}\n\n#include \"accounts-model-item.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"FKDTree.h\"\n#include \"KDPoint.h\"\n#include <chrono>\n#include \"KDTreeLinkerAlgoT.h\"\n#include <sstream>\n#include <unistd.h>\n#include <thread>\ntypedef struct float4\n{\n\tfloat x;\n\tfloat y;\n\tfloat z;\n\tfloat w;\n} float4;\nstatic void show_usage(std::string name)\n{\n\tstd::cerr << \"\\nUsage: \" << name << \" <option(s)>\" << \" Options:\\n\"\n\t\t\t<< \"\\t-h,--help\\t\\tShow this help message\\n\"\n\t\t\t<< \"\\t-n <number of points>\\tSpecify the number of points to use for the kdtree\\n\"\n\t\t\t<< \"\\t-t \\tRun the validity tests\\n\"\n\t\t\t<< \"\\t-s \\tRun the sequential algo\\n\"\n\t\t\t<< \"\\t-c \\tRun the vanilla cmssw algo\\n\"\n\t\t\t<< \"\\t-f \\tRun FKDtree algo\\n\"\n\t\t\t<< \"\\t-a \\tRun all the algos\\n\"\n\t\t\t<< std::endl;\n\n}\nint main(int argc, char* argv[])\n{\n\tif (argc < 3)\n\t{\n\t\tshow_usage(argv[0]);\n\t\treturn 1;\n\t}\n\n\tint nPoints;\n\tbool runTheTests = false;\n\tbool runSequential = false;\n\tbool runFKDTree = false;\n\tbool runOldKDTree = false;\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstd::string arg = argv[i];\n\t\tif ((arg == \"-h\") || (arg == \"--help\"))\n\t\t{\n\t\t\tshow_usage(argv[0]);\n\t\t\treturn 0;\n\t\t}\n\n\t\telse if (arg == \"-n\")\n\t\t{\n\t\t\tif (i + 1 < argc) \/\/ Make sure we aren't at the end of argv!\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tstd::istringstream ss(argv[i]);\n\t\t\t\tif (!(ss >> nPoints))\n\t\t\t\t\tstd::cerr << \"Invalid number \" << argv[i] << '\\n';\n\t\t\t}\n\t\t}\n\t\telse if (arg == \"-t\")\n\t\t{\n\t\t\trunTheTests = true;\n\t\t}\n\t\telse if (arg == \"-s\")\n\t\t{\n\t\t\trunSequential = true;\n\t\t}\n\t\telse if (arg == \"-f\")\n\t\t{\n\t\t\trunFKDTree = true;\n\t\t}\n\t\telse if (arg == \"-c\")\n\t\t{\n\t\t\trunOldKDTree = true;\n\t\t}\n\t\telse if (arg == \"-a\")\n\t\t{\n\t\t\trunOldKDTree = true;\n\t\t\trunFKDTree = true;\n\t\t\trunSequential = true;\n\t\t}\n\t}\n\n\tstd::vector<KDPoint<float, 3> > points;\n\tstd::vector<KDPoint<float, 3> > minPoints;\n\tstd::vector<KDPoint<float, 3> > maxPoints;\n\n\tfloat range_x = 1;\n\tfloat range_y = 2;\n\tfloat range_z = 1;\n\n\tKDPoint<float, 3> minPoint(0, 1, 8);\n\tKDPoint<float, 3> maxPoint(1, 2, 8.3);\n\tfor (int i = 0; i < nPoints; ++i)\n\t{\n\t\tfloat x = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\t;\n\t\tfloat y = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\t;\n\t\tfloat z = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\tKDPoint<float, 3> Point(x, y, z);\n\t\tPoint.setId(i);\n\n\t\tpoints.push_back(Point);\n\t\tKDPoint<float, 3> m(x - range_x, y - range_y, z - range_z);\n\t\tminPoints.push_back(m);\n\t\tKDPoint<float, 3> M(x + range_x, y + range_y, z + range_z);\n\t\tmaxPoints.push_back(M);\n\n\t}\n\n\tstd::cout << \"Cloud of points generated.\\n\" << std::endl;\n\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\n\tif (runFKDTree)\n\t{\n\t\tlong int pointsFound=0;\n\t\tstd::cout << \"FKDTree run will start in 1 second.\\n\" << std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\n\t\tstd::chrono::steady_clock::time_point start_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tFKDTree<float, 3> kdtree(nPoints, points);\n\n\t\tkdtree.build();\n\t\tstd::chrono::steady_clock::time_point end_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tstd::cout << \"building kdtree with \" << nPoints << \" points took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_building - start_building).count() << \"ms\" << std::endl;\n\t\tif (runTheTests)\n\t\t{\n\t\t\tif (kdtree.test_correct_build())\n\t\t\t\tstd::cout << \"KDTree built correctly\" << std::endl;\n\t\t\telse\n\t\t\t\tstd::cerr << \"KDTree wrong\" << std::endl;\n\t\t}\n\n\t\tstd::chrono::steady_clock::time_point start_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t\tpointsFound+=kdtree.search_in_the_box(minPoints[i], maxPoints[i]).size();\n\t\tstd::chrono::steady_clock::time_point end_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tstd::cout << \"searching points using kdtree took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count()<< \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\"\n\t\t\t\t\t\t<< std::endl;\n\t}\n\/\/\tint pointsFoundNaive = 0;\n\/\/\n\tif (runSequential)\n\t{\n\t\tstd::cout << \"Sequential run will start in 1 second.\\n\" << std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tstd::chrono::steady_clock::time_point start_sequential =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tlong int pointsFound = 0;\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tfor (auto p : points)\n\t\t\t{\n\n\t\t\t\tbool inTheBox = true;\n\n\t\t\t\tfor (int d = 0; d < 3; ++d)\n\t\t\t\t{\n\n\t\t\t\t\tinTheBox &= (p[d] <= maxPoints[i][d]\n\t\t\t\t\t\t\t&& p[d] >= minPoints[i][d]);\n\n\t\t\t\t}\n\t\t\t\tpointsFound += inTheBox;\n\t\t\t}\n\n\t\t}\n\n\t\tstd::chrono::steady_clock::time_point end_sequential =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tstd::cout << \"Sequential search algorithm took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_sequential - start_sequential).count() << \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\" << std::endl;\n\t}\n\n\tif (runOldKDTree)\n\t{\n\n\t\tfloat4* cmssw_points;\n\t\tcmssw_points = new float4[nPoints];\n\t\tfor (int j = 0; j < nPoints; j++)\n\t\t{\n\t\t\tcmssw_points[j].x = points[j][0];\n\t\t\tcmssw_points[j].y = points[j][1];\n\t\t\tcmssw_points[j].z = points[j][2];\n\t\t\tcmssw_points[j].w = j; \/\/Use this to save the index\n\n\t\t}\n\t\tstd::cout << \"Vanilla CMSSW KDTree run will start in 1 second.\\n\"\n\t\t\t\t<< std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tstd::chrono::steady_clock::time_point start_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tKDTreeLinkerAlgo<unsigned, 3> vanilla_tree;\n\t\tstd::vector<KDTreeNodeInfoT<unsigned, 3> > vanilla_nodes;\n\t\tstd::vector<KDTreeNodeInfoT<unsigned, 3> > vanilla_founds;\n\n\t\tstd::array<float, 3> minpos\n\t\t{\n\t\t{ 0.0f, 0.0f, 0.0f } }, maxpos\n\t\t{\n\t\t{ 0.0f, 0.0f, 0.0f } };\n\n\t\tvanilla_tree.clear();\n\t\tvanilla_founds.clear();\n\t\tfor (unsigned i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tfloat4 pos = cmssw_points[i];\n\t\t\tvanilla_nodes.emplace_back(i, (float) pos.x, (float) pos.y,\n\t\t\t\t\t(float) pos.z);\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t\tminpos[0] = pos.x;\n\t\t\t\tminpos[1] = pos.y;\n\t\t\t\tminpos[2] = pos.z;\n\t\t\t\tmaxpos[0] = pos.x;\n\t\t\t\tmaxpos[1] = pos.y;\n\t\t\t\tmaxpos[2] = pos.z;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tminpos[0] = std::min((float) pos.x, minpos[0]);\n\t\t\t\tminpos[1] = std::min((float) pos.y, minpos[1]);\n\t\t\t\tminpos[2] = std::min((float) pos.z, minpos[2]);\n\t\t\t\tmaxpos[0] = std::max((float) pos.x, maxpos[0]);\n\t\t\t\tmaxpos[1] = std::max((float) pos.y, maxpos[1]);\n\t\t\t\tmaxpos[2] = std::max((float) pos.z, maxpos[2]);\n\t\t\t}\n\t\t}\n\n\t\tKDTreeCube cluster_bounds = KDTreeCube(minpos[0], maxpos[0], minpos[1],\n\t\t\t\tmaxpos[1], minpos[2], maxpos[2]);\n\n\t\tvanilla_tree.build(vanilla_nodes, cluster_bounds);\n\t\tstd::chrono::steady_clock::time_point end_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tlong int pointsFound = 0;\n\t\tstd::chrono::steady_clock::time_point start_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tKDTreeCube kd_searchcube(minPoints[i][0], maxPoints[i][0],\n\t\t\t\t\tminPoints[i][1], maxPoints[i][1], minPoints[i][2],\n\t\t\t\t\tmaxPoints[i][2]);\n\t\t\tvanilla_tree.search(kd_searchcube, vanilla_founds);\n\t\t\tpointsFound += vanilla_founds.size();\n\t\t\tvanilla_founds.clear();\n\t\t}\n\t\tstd::chrono::steady_clock::time_point end_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tstd::cout << \"building cmssw kdtree with \" << nPoints << \" points took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_building - start_building).count() << \"ms\" << std::endl;\n\t\tstd::cout << \"searching points using cmssw kdtree took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count() << \"ms\"\n\t\t\t\t\t\t<< std::endl;\n\t\tstd::cout << pointsFound << \" points found cmssw in \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count() << \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\"\n\n\t\t\t\t\t\t<< std::endl;\n\n\t\tdelete[] cmssw_points;\n\t}\n\treturn 0;\n}\n<commit_msg>small adjustments<commit_after>#include \"FKDTree.h\"\n#include \"KDPoint.h\"\n#include <chrono>\n#include \"KDTreeLinkerAlgoT.h\"\n#include <sstream>\n#include <unistd.h>\n#include <thread>\ntypedef struct float4\n{\n\tfloat x;\n\tfloat y;\n\tfloat z;\n\tfloat w;\n} float4;\nstatic void show_usage(std::string name)\n{\n\tstd::cerr << \"\\nUsage: \" << name << \" <option(s)>\" << \" Options:\\n\"\n\t\t\t<< \"\\t-h,--help\\t\\tShow this help message\\n\"\n\t\t\t<< \"\\t-n <number of points>\\tSpecify the number of points to use for the kdtree\\n\"\n\t\t\t<< \"\\t-t \\tRun the validity tests\\n\"\n\t\t\t<< \"\\t-s \\tRun the sequential algo\\n\"\n\t\t\t<< \"\\t-c \\tRun the vanilla cmssw algo\\n\"\n\t\t\t<< \"\\t-f \\tRun FKDtree algo\\n\"\n\t\t\t<< \"\\t-a \\tRun all the algos\\n\"\n\t\t\t<< std::endl;\n\n}\nint main(int argc, char* argv[])\n{\n\tif (argc < 3)\n\t{\n\t\tshow_usage(argv[0]);\n\t\treturn 1;\n\t}\n\n\tint nPoints=100000;\n\tbool runTheTests = false;\n\tbool runSequential = false;\n\tbool runFKDTree = false;\n\tbool runOldKDTree = false;\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstd::string arg = argv[i];\n\t\tif ((arg == \"-h\") || (arg == \"--help\"))\n\t\t{\n\t\t\tshow_usage(argv[0]);\n\t\t\treturn 0;\n\t\t}\n\n\t\telse if (arg == \"-n\")\n\t\t{\n\t\t\tif (i + 1 < argc) \/\/ Make sure we aren't at the end of argv!\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tstd::istringstream ss(argv[i]);\n\t\t\t\tif (!(ss >> nPoints))\n\t\t\t\t\tstd::cerr << \"Invalid number \" << argv[i] << '\\n';\n\t\t\t}\n\t\t}\n\t\telse if (arg == \"-t\")\n\t\t{\n\t\t\trunTheTests = true;\n\t\t}\n\t\telse if (arg == \"-s\")\n\t\t{\n\t\t\trunSequential = true;\n\t\t}\n\t\telse if (arg == \"-f\")\n\t\t{\n\t\t\trunFKDTree = true;\n\t\t}\n\t\telse if (arg == \"-c\")\n\t\t{\n\t\t\trunOldKDTree = true;\n\t\t}\n\t\telse if (arg == \"-a\")\n\t\t{\n\t\t\trunOldKDTree = true;\n\t\t\trunFKDTree = true;\n\t\t\trunSequential = true;\n\t\t}\n\t}\n\n\tstd::vector<KDPoint<float, 3> > points;\n\tstd::vector<KDPoint<float, 3> > minPoints;\n\tstd::vector<KDPoint<float, 3> > maxPoints;\n\n\tfloat range_x = 1;\n\tfloat range_y = 2;\n\tfloat range_z = 1;\n\n\tKDPoint<float, 3> minPoint(0, 1, 8);\n\tKDPoint<float, 3> maxPoint(1, 2, 8.3);\n\tfor (int i = 0; i < nPoints; ++i)\n\t{\n\t\tfloat x = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\t;\n\t\tfloat y = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\t;\n\t\tfloat z = static_cast<float>(rand())\n\t\t\t\t\/ (static_cast<float>(RAND_MAX \/ 10.1));\n\t\tKDPoint<float, 3> Point(x, y, z);\n\t\tPoint.setId(i);\n\n\t\tpoints.push_back(Point);\n\t\tKDPoint<float, 3> m(x - range_x, y - range_y, z - range_z);\n\t\tminPoints.push_back(m);\n\t\tKDPoint<float, 3> M(x + range_x, y + range_y, z + range_z);\n\t\tmaxPoints.push_back(M);\n\n\t}\n\/\/needed by the vanilla algo\n\tfloat4* cmssw_points;\n\tcmssw_points = new float4[nPoints];\n\tfor (int j = 0; j < nPoints; j++)\n\t{\n\t\tcmssw_points[j].x = points[j][0];\n\t\tcmssw_points[j].y = points[j][1];\n\t\tcmssw_points[j].z = points[j][2];\n\t\tcmssw_points[j].w = j; \/\/Use this to save the index\n\n\t}\n\n\tstd::cout << \"Cloud of points generated.\\n\" << std::endl;\n\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\n\tif (runFKDTree)\n\t{\n\t\tlong int pointsFound=0;\n\t\tstd::cout << \"FKDTree run will start in 1 second.\\n\" << std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\n\t\tstd::chrono::steady_clock::time_point start_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tFKDTree<float, 3> kdtree(nPoints, points);\n\n\t\tkdtree.build();\n\t\tstd::chrono::steady_clock::time_point end_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tstd::cout << \"building FKDTree with \" << nPoints << \" points took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_building - start_building).count() << \"ms\" << std::endl;\n\t\tif (runTheTests)\n\t\t{\n\t\t\tif (kdtree.test_correct_build())\n\t\t\t\tstd::cout << \"FKDTree built correctly\" << std::endl;\n\t\t\telse\n\t\t\t\tstd::cerr << \"FKDTree wrong\" << std::endl;\n\t\t}\n\n\t\tstd::chrono::steady_clock::time_point start_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t\tpointsFound+=kdtree.search_in_the_box(minPoints[i], maxPoints[i]).size();\n\t\tstd::chrono::steady_clock::time_point end_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tstd::cout << \"searching points using FKDTree took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count()<< \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\"\n\t\t\t\t\t\t<< std::endl;\n\t}\n\/\/\tint pointsFoundNaive = 0;\n\/\/\n\tif (runSequential)\n\t{\n\t\tstd::cout << \"Sequential run will start in 1 second.\\n\" << std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tstd::chrono::steady_clock::time_point start_sequential =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tlong int pointsFound = 0;\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tfor (auto p : points)\n\t\t\t{\n\n\t\t\t\tbool inTheBox = true;\n\n\t\t\t\tfor (int d = 0; d < 3; ++d)\n\t\t\t\t{\n\n\t\t\t\t\tinTheBox &= (p[d] <= maxPoints[i][d]\n\t\t\t\t\t\t\t&& p[d] >= minPoints[i][d]);\n\n\t\t\t\t}\n\t\t\t\tpointsFound += inTheBox;\n\t\t\t}\n\n\t\t}\n\n\t\tstd::chrono::steady_clock::time_point end_sequential =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tstd::cout << \"Sequential search algorithm took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_sequential - start_sequential).count() << \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\" << std::endl;\n\t}\n\n\tif (runOldKDTree)\n\t{\n\n\n\t\tstd::cout << \"Vanilla CMSSW KDTree run will start in 1 second.\\n\"\n\t\t\t\t<< std::endl;\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tstd::chrono::steady_clock::time_point start_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tKDTreeLinkerAlgo<unsigned, 3> vanilla_tree;\n\t\tstd::vector<KDTreeNodeInfoT<unsigned, 3> > vanilla_nodes;\n\t\tstd::vector<KDTreeNodeInfoT<unsigned, 3> > vanilla_founds;\n\n\t\tstd::array<float, 3> minpos\n\t\t{\n\t\t{ 0.0f, 0.0f, 0.0f } }, maxpos\n\t\t{\n\t\t{ 0.0f, 0.0f, 0.0f } };\n\n\t\tvanilla_tree.clear();\n\t\tvanilla_founds.clear();\n\t\tfor (unsigned i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tfloat4 pos = cmssw_points[i];\n\t\t\tvanilla_nodes.emplace_back(i, (float) pos.x, (float) pos.y,\n\t\t\t\t\t(float) pos.z);\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t\tminpos[0] = pos.x;\n\t\t\t\tminpos[1] = pos.y;\n\t\t\t\tminpos[2] = pos.z;\n\t\t\t\tmaxpos[0] = pos.x;\n\t\t\t\tmaxpos[1] = pos.y;\n\t\t\t\tmaxpos[2] = pos.z;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tminpos[0] = std::min((float) pos.x, minpos[0]);\n\t\t\t\tminpos[1] = std::min((float) pos.y, minpos[1]);\n\t\t\t\tminpos[2] = std::min((float) pos.z, minpos[2]);\n\t\t\t\tmaxpos[0] = std::max((float) pos.x, maxpos[0]);\n\t\t\t\tmaxpos[1] = std::max((float) pos.y, maxpos[1]);\n\t\t\t\tmaxpos[2] = std::max((float) pos.z, maxpos[2]);\n\t\t\t}\n\t\t}\n\n\t\tKDTreeCube cluster_bounds = KDTreeCube(minpos[0], maxpos[0], minpos[1],\n\t\t\t\tmaxpos[1], minpos[2], maxpos[2]);\n\n\t\tvanilla_tree.build(vanilla_nodes, cluster_bounds);\n\t\tstd::chrono::steady_clock::time_point end_building =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tlong int pointsFound = 0;\n\t\tstd::chrono::steady_clock::time_point start_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < nPoints; ++i)\n\t\t{\n\t\t\tKDTreeCube kd_searchcube(minPoints[i][0], maxPoints[i][0],\n\t\t\t\t\tminPoints[i][1], maxPoints[i][1], minPoints[i][2],\n\t\t\t\t\tmaxPoints[i][2]);\n\t\t\tvanilla_tree.search(kd_searchcube, vanilla_founds);\n\t\t\tpointsFound += vanilla_founds.size();\n\t\t\tvanilla_founds.clear();\n\t\t}\n\t\tstd::chrono::steady_clock::time_point end_searching =\n\t\t\t\tstd::chrono::steady_clock::now();\n\n\t\tstd::cout << \"building Vanilla CMSSW KDTree with \" << nPoints << \" points took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_building - start_building).count() << \"ms\" << std::endl;\n\t\tstd::cout << \"searching points using Vanilla CMSSW KDTree took \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count() << \"ms\"\n\t\t\t\t\t\t<< std::endl;\n\t\tstd::cout << pointsFound << \" points found using Vanilla CMSSW KDTree in \"\n\t\t\t\t<< std::chrono::duration_cast < std::chrono::milliseconds\n\t\t\t\t> (end_searching - start_searching).count() << \"ms\\n\"\n\t\t\t\t<< \" found points: \" << pointsFound<< \"\\n******************************\\n\"\n\n\t\t\t\t\t\t<< std::endl;\n\n\t\tdelete[] cmssw_points;\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/filters\/ffmpeg_audio_decoder.h\"\n\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/limits.h\"\n#include \"media\/ffmpeg\/ffmpeg_common.h\"\n#include \"media\/filters\/ffmpeg_demuxer.h\"\n\nnamespace media {\n\n\/\/ Size of the decoded audio buffer.\nconst size_t FFmpegAudioDecoder::kOutputBufferSize =\n AVCODEC_MAX_AUDIO_FRAME_SIZE;\n\nFFmpegAudioDecoder::FFmpegAudioDecoder()\n : codec_context_(NULL) {\n}\n\nFFmpegAudioDecoder::~FFmpegAudioDecoder() {\n}\n\n\/\/ static\nbool FFmpegAudioDecoder::IsMediaFormatSupported(const MediaFormat& format) {\n std::string mime_type;\n return format.GetAsString(MediaFormat::kMimeType, &mime_type) &&\n mime_type::kFFmpegAudio == mime_type;\n}\n\nvoid FFmpegAudioDecoder::DoInitialize(DemuxerStream* demuxer_stream,\n bool* success,\n Task* done_cb) {\n AutoTaskRunner done_runner(done_cb);\n *success = false;\n\n \/\/ Get the AVStream by querying for the provider interface.\n AVStreamProvider* av_stream_provider;\n if (!demuxer_stream->QueryInterface(&av_stream_provider)) {\n return;\n }\n AVStream* av_stream = av_stream_provider->GetAVStream();\n\n \/\/ Grab the AVStream's codec context and make sure we have sensible values.\n codec_context_ = av_stream->codec;\n int bps = av_get_bits_per_sample_format(codec_context_->sample_fmt);\n DCHECK_GT(codec_context_->channels, 0);\n DCHECK_GT(bps, 0);\n DCHECK_GT(codec_context_->sample_rate, 0);\n if (codec_context_->channels == 0 ||\n static_cast<size_t>(codec_context_->channels) > Limits::kMaxChannels ||\n bps == 0 ||\n static_cast<size_t>(bps) > Limits::kMaxBPS ||\n codec_context_->sample_rate == 0 ||\n (static_cast<size_t>(codec_context_->sample_rate) >\n Limits::kMaxSampleRate)) {\n return;\n }\n\n \/\/ Serialize calls to avcodec_open().\n AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);\n if (!codec || avcodec_open(codec_context_, codec) < 0) {\n return;\n }\n\n \/\/ When calling avcodec_find_decoder(), |codec_context_| might be altered by\n \/\/ the decoder to give more accurate values of the output format of the\n \/\/ decoder. So set the media format after a decoder is allocated.\n \/\/ TODO(hclam): Reuse the information provided by the demuxer for now, we may\n \/\/ need to wait until the first buffer is decoded to know the correct\n \/\/ information.\n media_format_.SetAsInteger(MediaFormat::kChannels, codec_context_->channels);\n media_format_.SetAsInteger(MediaFormat::kSampleBits,\n av_get_bits_per_sample_format(codec_context_->sample_fmt));\n media_format_.SetAsInteger(MediaFormat::kSampleRate,\n codec_context_->sample_rate);\n media_format_.SetAsString(MediaFormat::kMimeType,\n mime_type::kUncompressedAudio);\n\n \/\/ Prepare the output buffer.\n output_buffer_.reset(static_cast<uint8*>(av_malloc(kOutputBufferSize)));\n if (!output_buffer_.get()) {\n host()->SetError(PIPELINE_ERROR_OUT_OF_MEMORY);\n return;\n }\n *success = true;\n}\n\nvoid FFmpegAudioDecoder::DoSeek(base::TimeDelta time, Task* done_cb) {\n avcodec_flush_buffers(codec_context_);\n estimated_next_timestamp_ = StreamSample::kInvalidTimestamp;\n done_cb->Run();\n delete done_cb;\n}\n\nvoid FFmpegAudioDecoder::DoDecode(Buffer* input, Task* done_cb) {\n AutoTaskRunner done_runner(done_cb);\n\n \/\/ Due to FFmpeg API changes we no longer have const read-only pointers.\n AVPacket packet;\n av_init_packet(&packet);\n packet.data = const_cast<uint8*>(input->GetData());\n packet.size = input->GetDataSize();\n\n int16_t* output_buffer = reinterpret_cast<int16_t*>(output_buffer_.get());\n int output_buffer_size = kOutputBufferSize;\n int result = avcodec_decode_audio3(codec_context_,\n output_buffer,\n &output_buffer_size,\n &packet);\n\n \/\/ TODO(ajwong): Consider if kOutputBufferSize should just be an int instead\n \/\/ of a size_t.\n if (result < 0 ||\n output_buffer_size < 0 ||\n static_cast<size_t>(output_buffer_size) > kOutputBufferSize) {\n LOG(INFO) << \"Error decoding an audio frame with timestamp: \"\n << input->GetTimestamp().InMicroseconds() << \" us\"\n << \" , duration: \"\n << input->GetDuration().InMicroseconds() << \" us\"\n << \" , packet size: \"\n << input->GetDataSize() << \" bytes\";\n return;\n }\n\n \/\/ If we have decoded something, enqueue the result.\n if (output_buffer_size) {\n DataBuffer* result_buffer = new DataBuffer(output_buffer_size);\n result_buffer->SetDataSize(output_buffer_size);\n uint8* data = result_buffer->GetWritableData();\n memcpy(data, output_buffer, output_buffer_size);\n\n \/\/ Determine the duration if the demuxer couldn't figure it out, otherwise\n \/\/ copy it over.\n if (input->GetDuration().ToInternalValue() == 0) {\n result_buffer->SetDuration(CalculateDuration(output_buffer_size));\n } else {\n DCHECK(input->GetDuration() != StreamSample::kInvalidTimestamp);\n result_buffer->SetDuration(input->GetDuration());\n }\n\n \/\/ Use our estimate for the timestamp if |input| does not have one.\n \/\/ Otherwise, copy over the timestamp.\n if (input->GetTimestamp() == StreamSample::kInvalidTimestamp) {\n result_buffer->SetTimestamp(estimated_next_timestamp_);\n } else {\n result_buffer->SetTimestamp(input->GetTimestamp());\n }\n\n \/\/ Only use the timestamp of |result_buffer| to estimate the next timestamp\n \/\/ if it is valid (i.e. != StreamSample::kInvalidTimestamp). Otherwise the\n \/\/ error will stack together and we will get a series of incorrect\n \/\/ timestamps. In this case, this will maintain a series of zero\n \/\/ timestamps.\n if (result_buffer->GetTimestamp() != StreamSample::kInvalidTimestamp) {\n \/\/ Update our estimated timestamp for the next packet.\n estimated_next_timestamp_ = result_buffer->GetTimestamp() +\n result_buffer->GetDuration();\n }\n\n EnqueueResult(result_buffer);\n return;\n }\n\n \/\/ We can get a positive result but no decoded data. This is ok because this\n \/\/ this can be a marker packet that only contains timestamp. In this case we\n \/\/ save the timestamp for later use.\n if (result && !input->IsEndOfStream() &&\n input->GetTimestamp() != StreamSample::kInvalidTimestamp &&\n input->GetDuration() != StreamSample::kInvalidTimestamp) {\n estimated_next_timestamp_ = input->GetTimestamp() + input->GetDuration();\n return;\n }\n\n \/\/ Three conditions to meet to declare end of stream for this decoder:\n \/\/ 1. FFmpeg didn't read anything.\n \/\/ 2. FFmpeg didn't output anything.\n \/\/ 3. An end of stream buffer is received.\n if (result == 0 && output_buffer_size == 0 && input->IsEndOfStream()) {\n DataBuffer* result_buffer = new DataBuffer(0);\n result_buffer->SetTimestamp(input->GetTimestamp());\n result_buffer->SetDuration(input->GetDuration());\n EnqueueResult(result_buffer);\n }\n}\n\nbase::TimeDelta FFmpegAudioDecoder::CalculateDuration(size_t size) {\n int64 denominator = codec_context_->channels *\n av_get_bits_per_sample_format(codec_context_->sample_fmt) \/ 8 *\n codec_context_->sample_rate;\n double microseconds = size \/\n (denominator \/ static_cast<double>(base::Time::kMicrosecondsPerSecond));\n return base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds));\n}\n\n} \/\/ namespace\n<commit_msg>Clean up the audio timestamp and duration code.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/filters\/ffmpeg_audio_decoder.h\"\n\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/limits.h\"\n#include \"media\/ffmpeg\/ffmpeg_common.h\"\n#include \"media\/filters\/ffmpeg_demuxer.h\"\n\nnamespace media {\n\n\/\/ Size of the decoded audio buffer.\nconst size_t FFmpegAudioDecoder::kOutputBufferSize =\n AVCODEC_MAX_AUDIO_FRAME_SIZE;\n\nFFmpegAudioDecoder::FFmpegAudioDecoder()\n : codec_context_(NULL),\n estimated_next_timestamp_(StreamSample::kInvalidTimestamp) {\n}\n\nFFmpegAudioDecoder::~FFmpegAudioDecoder() {\n}\n\n\/\/ static\nbool FFmpegAudioDecoder::IsMediaFormatSupported(const MediaFormat& format) {\n std::string mime_type;\n return format.GetAsString(MediaFormat::kMimeType, &mime_type) &&\n mime_type::kFFmpegAudio == mime_type;\n}\n\nvoid FFmpegAudioDecoder::DoInitialize(DemuxerStream* demuxer_stream,\n bool* success,\n Task* done_cb) {\n AutoTaskRunner done_runner(done_cb);\n *success = false;\n\n \/\/ Get the AVStream by querying for the provider interface.\n AVStreamProvider* av_stream_provider;\n if (!demuxer_stream->QueryInterface(&av_stream_provider)) {\n return;\n }\n AVStream* av_stream = av_stream_provider->GetAVStream();\n\n \/\/ Grab the AVStream's codec context and make sure we have sensible values.\n codec_context_ = av_stream->codec;\n int bps = av_get_bits_per_sample_format(codec_context_->sample_fmt);\n DCHECK_GT(codec_context_->channels, 0);\n DCHECK_GT(bps, 0);\n DCHECK_GT(codec_context_->sample_rate, 0);\n if (codec_context_->channels == 0 ||\n static_cast<size_t>(codec_context_->channels) > Limits::kMaxChannels ||\n bps == 0 ||\n static_cast<size_t>(bps) > Limits::kMaxBPS ||\n codec_context_->sample_rate == 0 ||\n (static_cast<size_t>(codec_context_->sample_rate) >\n Limits::kMaxSampleRate)) {\n return;\n }\n\n \/\/ Serialize calls to avcodec_open().\n AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);\n if (!codec || avcodec_open(codec_context_, codec) < 0) {\n return;\n }\n\n \/\/ When calling avcodec_find_decoder(), |codec_context_| might be altered by\n \/\/ the decoder to give more accurate values of the output format of the\n \/\/ decoder. So set the media format after a decoder is allocated.\n \/\/ TODO(hclam): Reuse the information provided by the demuxer for now, we may\n \/\/ need to wait until the first buffer is decoded to know the correct\n \/\/ information.\n media_format_.SetAsInteger(MediaFormat::kChannels, codec_context_->channels);\n media_format_.SetAsInteger(MediaFormat::kSampleBits,\n av_get_bits_per_sample_format(codec_context_->sample_fmt));\n media_format_.SetAsInteger(MediaFormat::kSampleRate,\n codec_context_->sample_rate);\n media_format_.SetAsString(MediaFormat::kMimeType,\n mime_type::kUncompressedAudio);\n\n \/\/ Prepare the output buffer.\n output_buffer_.reset(static_cast<uint8*>(av_malloc(kOutputBufferSize)));\n if (!output_buffer_.get()) {\n host()->SetError(PIPELINE_ERROR_OUT_OF_MEMORY);\n return;\n }\n *success = true;\n}\n\nvoid FFmpegAudioDecoder::DoSeek(base::TimeDelta time, Task* done_cb) {\n avcodec_flush_buffers(codec_context_);\n estimated_next_timestamp_ = StreamSample::kInvalidTimestamp;\n done_cb->Run();\n delete done_cb;\n}\n\nvoid FFmpegAudioDecoder::DoDecode(Buffer* input, Task* done_cb) {\n AutoTaskRunner done_runner(done_cb);\n\n \/\/ Due to FFmpeg API changes we no longer have const read-only pointers.\n AVPacket packet;\n av_init_packet(&packet);\n packet.data = const_cast<uint8*>(input->GetData());\n packet.size = input->GetDataSize();\n\n int16_t* output_buffer = reinterpret_cast<int16_t*>(output_buffer_.get());\n int output_buffer_size = kOutputBufferSize;\n int result = avcodec_decode_audio3(codec_context_,\n output_buffer,\n &output_buffer_size,\n &packet);\n\n \/\/ TODO(ajwong): Consider if kOutputBufferSize should just be an int instead\n \/\/ of a size_t.\n if (result < 0 ||\n output_buffer_size < 0 ||\n static_cast<size_t>(output_buffer_size) > kOutputBufferSize) {\n LOG(INFO) << \"Error decoding an audio frame with timestamp: \"\n << input->GetTimestamp().InMicroseconds() << \" us\"\n << \" , duration: \"\n << input->GetDuration().InMicroseconds() << \" us\"\n << \" , packet size: \"\n << input->GetDataSize() << \" bytes\";\n return;\n }\n\n \/\/ If we have decoded something, enqueue the result.\n if (output_buffer_size) {\n DataBuffer* result_buffer = new DataBuffer(output_buffer_size);\n result_buffer->SetDataSize(output_buffer_size);\n uint8* data = result_buffer->GetWritableData();\n memcpy(data, output_buffer, output_buffer_size);\n\n \/\/ We don't trust the demuxer, so always calculate the duration based on\n \/\/ the actual number of samples decoded.\n base::TimeDelta duration = CalculateDuration(output_buffer_size);\n result_buffer->SetDuration(duration);\n\n \/\/ Use an estimated timestamp unless the incoming buffer has a valid one.\n if (input->GetTimestamp() == StreamSample::kInvalidTimestamp) {\n result_buffer->SetTimestamp(estimated_next_timestamp_);\n\n \/\/ Keep the estimated timestamp invalid until we get an incoming buffer\n \/\/ with a valid timestamp. This can happen during seeks, etc...\n if (estimated_next_timestamp_ != StreamSample::kInvalidTimestamp) {\n estimated_next_timestamp_ += duration;\n }\n } else {\n result_buffer->SetTimestamp(input->GetTimestamp());\n estimated_next_timestamp_ = input->GetTimestamp() + duration;\n }\n\n EnqueueResult(result_buffer);\n return;\n }\n\n \/\/ We can get a positive result but no decoded data. This is ok because this\n \/\/ this can be a marker packet that only contains timestamp. In this case we\n \/\/ save the timestamp for later use.\n if (result && !input->IsEndOfStream() &&\n input->GetTimestamp() != StreamSample::kInvalidTimestamp &&\n input->GetDuration() != StreamSample::kInvalidTimestamp) {\n estimated_next_timestamp_ = input->GetTimestamp() + input->GetDuration();\n return;\n }\n\n \/\/ Three conditions to meet to declare end of stream for this decoder:\n \/\/ 1. FFmpeg didn't read anything.\n \/\/ 2. FFmpeg didn't output anything.\n \/\/ 3. An end of stream buffer is received.\n if (result == 0 && output_buffer_size == 0 && input->IsEndOfStream()) {\n DataBuffer* result_buffer = new DataBuffer(0);\n result_buffer->SetTimestamp(input->GetTimestamp());\n result_buffer->SetDuration(input->GetDuration());\n EnqueueResult(result_buffer);\n }\n}\n\nbase::TimeDelta FFmpegAudioDecoder::CalculateDuration(size_t size) {\n int64 denominator = codec_context_->channels *\n av_get_bits_per_sample_format(codec_context_->sample_fmt) \/ 8 *\n codec_context_->sample_rate;\n double microseconds = size \/\n (denominator \/ static_cast<double>(base::Time::kMicrosecondsPerSecond));\n return base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011, Image Engine Design Inc. All rights reserved.\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This must come before the Cortex includes, because on OSX headers included\n\/\/ by TBB define macros which conflict with the inline functions in ai_types.h.\n#include \"ai.h\"\n\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/DespatchTypedData.h\"\n\n#include \"IECoreArnold\/ToArnoldConverter.h\"\n\nusing namespace IECore;\nusing namespace IECoreArnold;\n\nIE_CORE_DEFINERUNTIMETYPED( ToArnoldConverter );\n\nToArnoldConverter::ToArnoldConverter( const std::string &description, IECore::TypeId supportedType )\n\t:\tIECore::FromCoreConverter( description, supportedType )\n{\n}\n\nToArnoldConverter::~ToArnoldConverter()\n{\n}\n\nAtNode *ToArnoldConverter::convert() const\n{\n\tIECore::ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<IECore::CompoundObject>();\n\treturn doConversion( srcParameter()->getValidatedValue(), operands );\n}\n\nvoid ToArnoldConverter::setParameter( AtNode *node, const AtParamEntry *parameter, const IECore::Data *value )\n{\n\tbool isArray = false;\n\tint type = AiParamGetType( parameter );\n\tif( type == AI_TYPE_ARRAY )\n\t{\n\t\ttype = AiParamGetDefault( parameter )->ARRAY->type;\n\t\tisArray = true;\n\t}\n\t\n\tsetParameterInternal( node, AiParamGetName( parameter ), type, isArray, value );\n}\n\nvoid ToArnoldConverter::setParameter( AtNode *node, const char *name, const IECore::Data *value )\n{\n\tconst AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );\n\tif( parameter )\n\t{\n\t\tsetParameter( node, parameter, value );\n\t}\n\telse\n\t{\n\t\tbool array = false;\n\t\tint type = parameterType( value->typeId(), array );\n\t\tif( type != AI_TYPE_NONE )\n\t\t{\n\t\t\tstd::string typeString = \"constant \";\n\t\t\tif( array )\n\t\t\t{\n\t\t\t\ttypeString += \"ARRAY \";\n\t\t\t}\n\t\t\ttypeString += AiParamGetTypeName( type );\n\t\t\tAiNodeDeclare( node, name, typeString.c_str() );\n\t\t\tsetParameterInternal( node, name, type, array, value );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg(\n\t\t\t\tMsg::Warning,\n\t\t\t\t\"ToArnoldConverter::setParameter\",\n\t\t\t\tboost::format( \"Unsupported data type \\\"%s\\\" for name \\\"%s\\\"\" ) % value->typeName() % name\n\t\t\t);\n\t\t}\n\t}\n}\n\nvoid ToArnoldConverter::setParameters( AtNode *node, const IECore::CompoundDataMap &values )\n{\n\tfor( CompoundDataMap::const_iterator it=values.begin(); it!=values.end(); it++ )\n\t{\n\t\tsetParameter( node, it->first.value().c_str(), it->second );\n\t}\n}\n\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const AtParamEntry *parameter )\n{\n\treturn getParameterInternal( node, AiParamGetName( parameter ), AiParamGetType( parameter ) );\n}\n\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const AtUserParamEntry *parameter )\n{\n\treturn getParameterInternal( node, AiUserParamGetName( parameter ), AiUserParamGetType( parameter ) );\n}\n\t\t\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const char *name )\n{\n\tconst AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );\n\tif( parameter )\n\t{\n\t\treturn getParameter( node, parameter );\n\t}\n\telse\n\t{\n\t\tconst AtUserParamEntry *userParameter = AiNodeLookUpUserParameter( node, name );\n\t\tif( userParameter )\n\t\t{\n\t\t\treturn getParameter( node, userParameter );\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nvoid ToArnoldConverter::getParameters( AtNode *node, IECore::CompoundDataMap &values )\n{\n\t\/\/\/ \\todo Non-user parameters\n\n\tAtUserParamIterator *it = AiNodeGetUserParamIterator( node ); \t\n\twhile( const AtUserParamEntry *param = AiUserParamIteratorGetNext( it ) )\n\t{\n\t\tDataPtr d = getParameter( node, param );\n\t\tif( d )\n\t\t{\n\t\t\tvalues[AiUserParamGetName( param )] = d;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg(\n\t\t\t\tMsg::Warning,\n\t\t\t\t\"ToArnoldConverter::getParameters\",\n\t\t\t\tboost::format( \"Unable to convert user parameter \\\"%s\\\"\" ) % AiUserParamGetName( param )\n\t\t\t);\n\t\t}\n\t}\n\tAiUserParamIteratorDestroy( it );\n}\n\nint ToArnoldConverter::parameterType( IECore::TypeId dataType, bool &array )\n{\n\tswitch( dataType )\n\t{\n\t\t\/\/ non-array types\n\n\t\tcase IntDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_INT;\n\t\tcase FloatDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_FLOAT;\n\t\tcase StringDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_STRING;\n\t\tcase Color3fDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_RGB;\n\t\tcase BoolDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_BOOLEAN;\n\n\t\t\/\/ array types\n\n\t\tcase IntVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_INT;\n\t\tcase FloatVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_FLOAT;\n\t\tcase StringVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_STRING;\n\t\tcase Color3fVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_RGB;\n\t\tcase BoolVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_BOOLEAN;\n\t\tdefault :\n\t\t\treturn AI_TYPE_NONE;\n\t}\n}\n\nAtArray *ToArnoldConverter::dataToArray( const IECore::Data *data )\n{\n\tbool isArray = false;\n\tint type = parameterType( data->typeId(), isArray );\n\tif( type == AI_TYPE_NONE || !isArray )\n\t{\n\t\treturn 0;\n\t}\n\t\n\tconst void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( DataPtr( const_cast<Data *>( data ) ) );\n\tsize_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( DataPtr( const_cast<Data *>( data ) ) );\n\treturn AiArrayConvert( dataSize, 1, type, dataAddress );\n}\n\ntemplate<typename T>\nstatic inline const T *dataCast( const char *name, const IECore::Data *data )\n{\n\tconst T *result = runTimeCast<const T>( data );\n\tif( result )\n\t{\n\t\treturn result;\n\t}\n\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unsupported value type \\\"%s\\\" for parameter \\\"%s\\\" (expected %s).\" ) % data->typeName() % name % T::staticTypeName() );\t\t\t\n\treturn 0;\n}\n\nvoid ToArnoldConverter::setParameterInternal( AtNode *node, const char *name, int parameterType, bool array, const IECore::Data *value )\n{\n\tif( array )\n\t{\n\t\tAtArray *a = dataToArray( value );\n\t\tif( !a )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unable to create array from data of type \\\"%s\\\" for parameter \\\"%s\\\"\" ) % value->typeName() % name );\t\t\t\n\t\t\treturn;\n\t\t}\n\t\tif( a->type != parameterType )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unable to create array of type %s from data of type \\\"%s\\\" for parameter \\\"%s\\\"\" ) % AiParamGetTypeName( parameterType ) % value->typeName() % name );\t\t\t\n\t\t\treturn;\t\t\n\t\t}\n\t\tAiNodeSetArray( node, name, a );\t\n\t}\n\telse\n\t{\n\t\tswitch( parameterType )\n\t\t{\n\t\t\tcase AI_TYPE_INT :\n\t\t\t\tif( const IntData *data = dataCast<IntData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetInt( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_FLOAT :\n\t\t\t\tif( const FloatData *data = dataCast<FloatData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetFlt( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_STRING :\n\t\t\t\tif( const StringData *data = dataCast<StringData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetStr( node, name, data->readable().c_str() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_RGB :\n\t\t\t\tif( const Color3fData *data = dataCast<Color3fData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tconst Imath::Color3f &c = data->readable();\n\t\t\t\t\tAiNodeSetRGB( node, name, c[0], c[1], c[2] );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_ENUM :\n\t\t\t\tif( const StringData *data = dataCast<StringData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetStr( node, name, data->readable().c_str() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_BOOLEAN :\n\t\t\t{\n\t\t\t\tif( const BoolData *data = dataCast<BoolData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetBool( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault :\n\t\t\t{\n\t\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Arnold parameter \\\"%s\\\" has unsupported type \\\"%s\\\".\" ) % name % AiParamGetTypeName( parameterType ) );\t\n\t\t\t}\n\t\t}\n\t}\n}\n\nIECore::DataPtr ToArnoldConverter::getParameterInternal( AtNode *node, const char *name, int parameterType )\n{\n\tswitch( parameterType )\n\t{\n\t\tcase AI_TYPE_BOOLEAN :\n\t\t\treturn new BoolData( AiNodeGetBool( node, name ) );\n\t\tcase AI_TYPE_INT :\n\t\t\treturn new IntData( AiNodeGetInt( node, name ) );\n\t\tcase AI_TYPE_FLOAT :\n\t\t\treturn new FloatData( AiNodeGetFlt( node, name ) );\n\t\tcase AI_TYPE_STRING :\n\t\t\treturn new StringData( AiNodeGetStr( node, name ) );\n\t}\n\treturn 0;\n}\n\nToArnoldConverterPtr ToArnoldConverter::create( IECore::ObjectPtr object )\n{\n\tconst CreatorMap &m = creators();\n\tCreatorMap::const_iterator it = m.find( object->typeId() );\n\tif( it != m.end() )\n\t{\n\t\treturn it->second( object );\n\t}\n\treturn 0;\n}\n\nToArnoldConverter::CreatorMap &ToArnoldConverter::creators()\n{\n\tstatic CreatorMap m;\n\treturn m;\n}\n\n<commit_msg>added AI_TYPE_BYTE case to ToArnoldConverter.cpp<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011, Image Engine Design Inc. All rights reserved.\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This must come before the Cortex includes, because on OSX headers included\n\/\/ by TBB define macros which conflict with the inline functions in ai_types.h.\n#include \"ai.h\"\n\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/DespatchTypedData.h\"\n\n#include \"IECoreArnold\/ToArnoldConverter.h\"\n\nusing namespace IECore;\nusing namespace IECoreArnold;\n\nIE_CORE_DEFINERUNTIMETYPED( ToArnoldConverter );\n\nToArnoldConverter::ToArnoldConverter( const std::string &description, IECore::TypeId supportedType )\n\t:\tIECore::FromCoreConverter( description, supportedType )\n{\n}\n\nToArnoldConverter::~ToArnoldConverter()\n{\n}\n\nAtNode *ToArnoldConverter::convert() const\n{\n\tIECore::ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<IECore::CompoundObject>();\n\treturn doConversion( srcParameter()->getValidatedValue(), operands );\n}\n\nvoid ToArnoldConverter::setParameter( AtNode *node, const AtParamEntry *parameter, const IECore::Data *value )\n{\n\tbool isArray = false;\n\tint type = AiParamGetType( parameter );\n\tif( type == AI_TYPE_ARRAY )\n\t{\n\t\ttype = AiParamGetDefault( parameter )->ARRAY->type;\n\t\tisArray = true;\n\t}\n\t\n\tsetParameterInternal( node, AiParamGetName( parameter ), type, isArray, value );\n}\n\nvoid ToArnoldConverter::setParameter( AtNode *node, const char *name, const IECore::Data *value )\n{\n\tconst AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );\n\tif( parameter )\n\t{\n\t\tsetParameter( node, parameter, value );\n\t}\n\telse\n\t{\n\t\tbool array = false;\n\t\tint type = parameterType( value->typeId(), array );\n\t\tif( type != AI_TYPE_NONE )\n\t\t{\n\t\t\tstd::string typeString = \"constant \";\n\t\t\tif( array )\n\t\t\t{\n\t\t\t\ttypeString += \"ARRAY \";\n\t\t\t}\n\t\t\ttypeString += AiParamGetTypeName( type );\n\t\t\tAiNodeDeclare( node, name, typeString.c_str() );\n\t\t\tsetParameterInternal( node, name, type, array, value );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg(\n\t\t\t\tMsg::Warning,\n\t\t\t\t\"ToArnoldConverter::setParameter\",\n\t\t\t\tboost::format( \"Unsupported data type \\\"%s\\\" for name \\\"%s\\\"\" ) % value->typeName() % name\n\t\t\t);\n\t\t}\n\t}\n}\n\nvoid ToArnoldConverter::setParameters( AtNode *node, const IECore::CompoundDataMap &values )\n{\n\tfor( CompoundDataMap::const_iterator it=values.begin(); it!=values.end(); it++ )\n\t{\n\t\tsetParameter( node, it->first.value().c_str(), it->second );\n\t}\n}\n\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const AtParamEntry *parameter )\n{\n\treturn getParameterInternal( node, AiParamGetName( parameter ), AiParamGetType( parameter ) );\n}\n\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const AtUserParamEntry *parameter )\n{\n\treturn getParameterInternal( node, AiUserParamGetName( parameter ), AiUserParamGetType( parameter ) );\n}\n\t\t\nIECore::DataPtr ToArnoldConverter::getParameter( AtNode *node, const char *name )\n{\n\tconst AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );\n\tif( parameter )\n\t{\n\t\treturn getParameter( node, parameter );\n\t}\n\telse\n\t{\n\t\tconst AtUserParamEntry *userParameter = AiNodeLookUpUserParameter( node, name );\n\t\tif( userParameter )\n\t\t{\n\t\t\treturn getParameter( node, userParameter );\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nvoid ToArnoldConverter::getParameters( AtNode *node, IECore::CompoundDataMap &values )\n{\n\t\/\/\/ \\todo Non-user parameters\n\n\tAtUserParamIterator *it = AiNodeGetUserParamIterator( node ); \t\n\twhile( const AtUserParamEntry *param = AiUserParamIteratorGetNext( it ) )\n\t{\n\t\tDataPtr d = getParameter( node, param );\n\t\tif( d )\n\t\t{\n\t\t\tvalues[AiUserParamGetName( param )] = d;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg(\n\t\t\t\tMsg::Warning,\n\t\t\t\t\"ToArnoldConverter::getParameters\",\n\t\t\t\tboost::format( \"Unable to convert user parameter \\\"%s\\\"\" ) % AiUserParamGetName( param )\n\t\t\t);\n\t\t}\n\t}\n\tAiUserParamIteratorDestroy( it );\n}\n\nint ToArnoldConverter::parameterType( IECore::TypeId dataType, bool &array )\n{\n\tswitch( dataType )\n\t{\n\t\t\/\/ non-array types\n\n\t\tcase IntDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_INT;\n\t\tcase FloatDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_FLOAT;\n\t\tcase StringDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_STRING;\n\t\tcase Color3fDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_RGB;\n\t\tcase BoolDataTypeId :\n\t\t\tarray = false;\n\t\t\treturn AI_TYPE_BOOLEAN;\n\n\t\t\/\/ array types\n\n\t\tcase IntVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_INT;\n\t\tcase FloatVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_FLOAT;\n\t\tcase StringVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_STRING;\n\t\tcase Color3fVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_RGB;\n\t\tcase BoolVectorDataTypeId :\n\t\t\tarray = true;\n\t\t\treturn AI_TYPE_BOOLEAN;\n\t\tdefault :\n\t\t\treturn AI_TYPE_NONE;\n\t}\n}\n\nAtArray *ToArnoldConverter::dataToArray( const IECore::Data *data )\n{\n\tbool isArray = false;\n\tint type = parameterType( data->typeId(), isArray );\n\tif( type == AI_TYPE_NONE || !isArray )\n\t{\n\t\treturn 0;\n\t}\n\t\n\tconst void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( DataPtr( const_cast<Data *>( data ) ) );\n\tsize_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( DataPtr( const_cast<Data *>( data ) ) );\n\treturn AiArrayConvert( dataSize, 1, type, dataAddress );\n}\n\ntemplate<typename T>\nstatic inline const T *dataCast( const char *name, const IECore::Data *data )\n{\n\tconst T *result = runTimeCast<const T>( data );\n\tif( result )\n\t{\n\t\treturn result;\n\t}\n\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unsupported value type \\\"%s\\\" for parameter \\\"%s\\\" (expected %s).\" ) % data->typeName() % name % T::staticTypeName() );\t\t\t\n\treturn 0;\n}\n\nvoid ToArnoldConverter::setParameterInternal( AtNode *node, const char *name, int parameterType, bool array, const IECore::Data *value )\n{\n\tif( array )\n\t{\n\t\tAtArray *a = dataToArray( value );\n\t\tif( !a )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unable to create array from data of type \\\"%s\\\" for parameter \\\"%s\\\"\" ) % value->typeName() % name );\t\t\t\n\t\t\treturn;\n\t\t}\n\t\tif( a->type != parameterType )\n\t\t{\n\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Unable to create array of type %s from data of type \\\"%s\\\" for parameter \\\"%s\\\"\" ) % AiParamGetTypeName( parameterType ) % value->typeName() % name );\t\t\t\n\t\t\treturn;\t\t\n\t\t}\n\t\tAiNodeSetArray( node, name, a );\t\n\t}\n\telse\n\t{\n\t\tswitch( parameterType )\n\t\t{\n\t\t\tcase AI_TYPE_INT :\n\t\t\t\tif( const IntData *data = dataCast<IntData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetInt( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_BYTE :\n\t\t\t\tif( const IntData *data = dataCast<IntData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetByte( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_FLOAT :\n\t\t\t\tif( const FloatData *data = dataCast<FloatData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetFlt( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_STRING :\n\t\t\t\tif( const StringData *data = dataCast<StringData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetStr( node, name, data->readable().c_str() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_RGB :\n\t\t\t\tif( const Color3fData *data = dataCast<Color3fData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tconst Imath::Color3f &c = data->readable();\n\t\t\t\t\tAiNodeSetRGB( node, name, c[0], c[1], c[2] );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_ENUM :\n\t\t\t\tif( const StringData *data = dataCast<StringData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetStr( node, name, data->readable().c_str() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AI_TYPE_BOOLEAN :\n\t\t\t{\n\t\t\t\tif( const BoolData *data = dataCast<BoolData>( name, value ) )\n\t\t\t\t{\n\t\t\t\t\tAiNodeSetBool( node, name, data->readable() );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault :\n\t\t\t{\n\t\t\t\tmsg( Msg::Warning, \"ToArnoldConverter::setParameter\", boost::format( \"Arnold parameter \\\"%s\\\" has unsupported type \\\"%s\\\".\" ) % name % AiParamGetTypeName( parameterType ) );\t\n\t\t\t}\n\t\t}\n\t}\n}\n\nIECore::DataPtr ToArnoldConverter::getParameterInternal( AtNode *node, const char *name, int parameterType )\n{\n\tswitch( parameterType )\n\t{\n\t\tcase AI_TYPE_BOOLEAN :\n\t\t\treturn new BoolData( AiNodeGetBool( node, name ) );\n\t\tcase AI_TYPE_INT :\n\t\t\treturn new IntData( AiNodeGetInt( node, name ) );\n\t\tcase AI_TYPE_FLOAT :\n\t\t\treturn new FloatData( AiNodeGetFlt( node, name ) );\n\t\tcase AI_TYPE_STRING :\n\t\t\treturn new StringData( AiNodeGetStr( node, name ) );\n\t}\n\treturn 0;\n}\n\nToArnoldConverterPtr ToArnoldConverter::create( IECore::ObjectPtr object )\n{\n\tconst CreatorMap &m = creators();\n\tCreatorMap::const_iterator it = m.find( object->typeId() );\n\tif( it != m.end() )\n\t{\n\t\treturn it->second( object );\n\t}\n\treturn 0;\n}\n\nToArnoldConverter::CreatorMap &ToArnoldConverter::creators()\n{\n\tstatic CreatorMap m;\n\treturn m;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <CL\/cl.h>\n\n#include \"cl_util.h\"\n\nconst char *source =\n \"__kernel void saxpy(float a, __global float *x, __global float \"\n \"*y)\"\n \"{\"\n \" uint id = get_global_id(0);\"\n \" y[id] = a * x[id] + y[id];\"\n \"}\";\n\nint main()\n{\n \/\/ input data\n const size_t inputSize = 100000000;\n float a = 7;\n std::vector<float> x(inputSize, 4);\n std::vector<float> y(inputSize, 5);\n\n const auto device =\n cl::chooseDevice(cl::allDevices(), CL_DEVICE_MAX_COMPUTE_UNITS);\n cl::printDeviceInfo(device);\n cl_int error = 0;\n\n cl_context context =\n clCreateContext(nullptr, 1, &device, nullptr, nullptr, &error);\n cl_command_queue queue = clCreateCommandQueue(context, device, 0, &error);\n cl_program program =\n clCreateProgramWithSource(context, 1, &source, nullptr, &error);\n clBuildProgram(program, 1, &device, nullptr, nullptr, nullptr);\n\n size_t logSize;\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, nullptr,\n &logSize);\n std::vector<char> infoLog(logSize);\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize,\n infoLog.data(), nullptr);\n std::cout << std::string{infoLog.begin(), infoLog.end()} << std::endl;\n\n cl_kernel kernel = clCreateKernel(program, \"saxpy\", nullptr);\n cl_mem bufferX =\n clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,\n sizeof(float) * x.size(), x.data(), &error);\n cl_mem bufferY =\n clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n sizeof(float) * y.size(), y.data(), &error);\n\n clSetKernelArg(kernel, 0, sizeof(a), static_cast<void *>(&a));\n clSetKernelArg(kernel, 1, sizeof(bufferX), static_cast<void *>(&bufferX));\n clSetKernelArg(kernel, 2, sizeof(bufferY), static_cast<void *>(&bufferY));\n\n clEnqueueNDRangeKernel(queue, kernel, 1, nullptr, &inputSize, nullptr, 0,\n nullptr, nullptr);\n clFinish(queue);\n\n auto data = static_cast<cl_float *>(clEnqueueMapBuffer(\n queue, bufferY, CL_TRUE, CL_MAP_READ, 0, sizeof(float) * inputSize, 0,\n nullptr, nullptr, &error));\n\n for (int i = 0; i < 20; ++i)\n {\n std::cout << data[i] << std::endl;\n }\n}\n<commit_msg>Add context error callback<commit_after>#include <iostream>\n\n#include <CL\/cl.h>\n\n#include \"cl_util.h\"\n\nconst char *source =\n \"__kernel void saxpy(float a, __global float *x, __global float *y)\"\n \"{\"\n \" uint id = get_global_id(0);\"\n \" y[id] = a * x[id] + y[id];\"\n \"}\";\n\nvoid errorCallback(const char *errinfo, const void *private_info, size_t cb,\n void *user_data)\n{\n std::cout << \"ContextError: \" << errinfo << std::endl;\n}\n\nint main()\n{\n \/\/ input data\n const size_t inputSize = 100000000;\n float a = 7;\n std::vector<float> x(inputSize, 4);\n std::vector<float> y(inputSize, 5);\n\n const auto device =\n cl::chooseDevice(cl::allDevices(), CL_DEVICE_MAX_COMPUTE_UNITS);\n cl::printDeviceInfo(device);\n cl_int error = 0;\n\n cl_context context =\n clCreateContext(nullptr, 1, &device, errorCallback, nullptr, &error);\n cl_command_queue queue = clCreateCommandQueue(context, device, 0, &error);\n cl_program program =\n clCreateProgramWithSource(context, 1, &source, nullptr, &error);\n clBuildProgram(program, 1, &device, nullptr, nullptr, nullptr);\n\n size_t logSize;\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, nullptr,\n &logSize);\n std::vector<char> infoLog(logSize);\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize,\n infoLog.data(), nullptr);\n std::cout << std::string{infoLog.begin(), infoLog.end()} << std::endl;\n\n cl_kernel kernel = clCreateKernel(program, \"saxpy\", nullptr);\n cl_mem bufferX =\n clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,\n sizeof(float) * x.size(), x.data(), &error);\n cl_mem bufferY =\n clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n sizeof(float) * y.size(), y.data(), &error);\n\n clSetKernelArg(kernel, 0, sizeof(a), static_cast<void *>(&a));\n clSetKernelArg(kernel, 1, sizeof(bufferX), static_cast<void *>(&bufferX));\n clSetKernelArg(kernel, 2, sizeof(bufferY), static_cast<void *>(&bufferY));\n\n clEnqueueNDRangeKernel(queue, kernel, 1, nullptr, &inputSize, nullptr, 0,\n nullptr, nullptr);\n clFinish(queue);\n\n auto data = static_cast<cl_float *>(clEnqueueMapBuffer(\n queue, bufferY, CL_TRUE, CL_MAP_READ, 0, sizeof(float) * inputSize, 0,\n nullptr, nullptr, &error));\n\n for (int i = 0; i < 20; ++i)\n {\n std::cout << data[i] << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <string.h>\n#include <fstream>\n#include \"overlapgraph.h\"\n\n#define VERTEX_INACTIVE 0\n#define VERTEX_ACTIVE 1\n#define VERTEX_ELIMINATED -1\n#define FUZZ 10\n\nusing namespace std;\n\nOverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)\n{\n\treads = readvector;\n\toverlaps = overlapvector;\n}\n\nvoid OverlapGraph::initialize()\n{\n\tgraph.resize(reads.size());\n\treducedGraph.resize(reads.size());\n\tnonContainedReads.resize(reads.size());\n\tnonContainedReads.assign(reads.size(), 1);\n\n\tfor(int i=0;i<overlaps.size();i++)\n\t{\n\t\toverlap o = overlaps[i];\n\n\n\t\t\/\/removing contained reads\n\t\tif(o.ahg > 0 & o.bhg > 0)\n\t\t\tgraph[o.read1].push_back(o);\n\t\telse if (o.ahg < 0 & o.bhg < 0)\n\t\t\tgraph[o.read2].push_back(o);\n\t\telse if (o.ahg >= 0 & o.bhg <= 0)\n\t\t\tnonContainedReads[o.read2] = 0;\n\t\telse if (o.ahg <= 0 & o.bhg>=0)\n\t\t\tnonContainedReads[o.read1] = 0;\n\t}\n}\n\nvoid OverlapGraph::runUnitigging()\n{\n\tint N = reads.size();\n\n\t\n\tinitialize();\n\n\tint *vertexstatus = (int *)malloc(N*sizeof(int));\n\tmemset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));\n\tvector< vector<bool> > reduceflags(N);\n\n\tfor (int i = 0; i < N; i++)\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t\treduceflags[i].push_back(false);\n\n\tfor (int I = 0; I < N; I++)\n\t{\n\t\tif (graph[I].size() == 0)\n\t\t\tcontinue;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t\tvertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;\n\n\t\tint longest = 0;\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (graph[I][j].bhg > longest)\n\t\t\t\tlongest = graph[I][j].bhg;\n\t\t}\n\n\t\tlongest += FUZZ;\n\t\tcout << longest << endl;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)\n\t\t\t{\n\t\t\t\tint x = graph[I][j].read2;\n\t\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t\t{\n\t\t\t\t\tif (graph[I][j].bhg + graph[x][k].bhg <= longest)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tint x = graph[I][j].read2;\n\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t{\n\t\t\t\tif (graph[x][k].bhg < FUZZ)\n\t\t\t\t{\n\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)\n\t\t\t{\n\t\t\t\treduceflags[I][j] = true;\n\t\t\t}\n\t\t\tvertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;\n\t\t}\n\t}\n\n\tfor(int i=0;i<graph.size();i++)\n {\n for(int j=0;j<graph[i].size();j++)\n {\n\t\t\tif (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){\n\t\t\t\t\/\/ Add edge to the reduced graph\n\t\t\t\treducedGraph[i].push_back(graph[i][j]);\n\t\t\t\tcout << graph[i][j].read1 << \" -> \" << graph[i][j].read2 << endl;\n\t\t\t}\n }\n }\n\tuniqueJoinCollapsing();\n\n\tfree(vertexstatus);\n\treturn;\n}\n\nvoid OverlapGraph::unitigsPrinting()\n{\n\tofstream output(\"unitigsPrinting.afg\");\n\t\n\tint counter = 1;\n\n\toutput << \"Unitigs{\" << endl;\n\n\tfor (Chunk c : collapsedReducedGraph)\n\t{\n\t\toutput << \"\\t\" << counter << \"{\" << endl;\n\t\t\n\t\tfor (int a : c.members)\n\t\t{\n\t\t}\n\n\t\toutput << c.members[1] << endl;\n\t\toutput << \"\\t\" << \"}\" << endl;\n\t}\n\n\toutput << \"}\" << endl;\n}\n\nvoid OverlapGraph::printLayouts()\n{\n\tofstream output(\"layouts.afg\");\n\tofstream pretty(\"pretty.afg\");\n\tint *offsets = (int *)malloc(reads.size()*sizeof(int));\n\tmemset(offsets, 0, reads.size()*sizeof(int));\n\n\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t{\n\t\t\toverlap o = graph[i][j];\n\t\t\tif (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {\n\t\t\t\toffsets[o.read2] = offsets[o.read1] + o.ahg;\n\t\t\t}\n\t\t}\n\t}\n\n\toutput << \"{LAY\" << endl;\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tif (nonContainedReads[i]) \n\t\t{\n\t\t\toutput << \"{TLE\" << endl;\n\t\t\toutput << \"clr:0,\" << reads[i].length() << endl;\n\t\t\toutput << \"off:\" << offsets[i] << endl;\n\t\t\toutput << \"src:\" << i + 1 << endl;\n\t\t\toutput << \"}\" << endl;\n\n\t\t\tpretty << string(offsets[i], ' ') + reads[i] << endl;\n\t\t\t\/\/pretty <<reads[i] << endl;\n\n\t\t}\n\t}\n\n\toutput << \"}\" << endl;\n\toutput.close();\n\n\tfree(offsets);\n}\n\nvoid OverlapGraph::uniqueJoinCollapsing(){\n\n\treducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);\n\n\t\/\/ Calculate references to vertexes\n\tfor (int i = 0; i < reducedGraph.size(); i++){\n\t\tfor (int j = 0; j < reducedGraph[i].size(); j++){\n\t\t\treducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;\n\t\t}\n\t}\n\n\t\/\/ Find first \"juncture\" vertex\n\tint startingVertex = 0;\n\tbool startingVertexFound = false;\n\twhile (startingVertex < reducedGraph.size()){\n\t\tif (reducedGraph[startingVertex].size() > 0){\n\t\t\tstartingVertexFound = true;\n\t\t\tbreak;\n\t\t}\n\t\tstartingVertex++;\n\t}\n\tif (startingVertexFound){\n\t\tcalculateChunks(startingVertex);\n\t}\n}\n\nvoid OverlapGraph::calculateChunks(int chunkStartingVertexId){\n\t\n\tint currentVertexId = chunkStartingVertexId;\n\n\tif (vertexAlreadyInChunk(currentVertexId)){\n\t\treturn;\n\t}\n\n\t\/\/ create new chunk\n\tChunk chunk;\n\n\twhile (true){\n\t\tif (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){\n\t\t\t\/\/ special case: juncture vertex (not part of our chunk)\n\t\t\tcalculateChunks(currentVertexId);\n\t\t\tbreak;\n\t\t}\n\n\t\tchunk.members.push_back(currentVertexId);\n\n\t\tif (reducedGraph[currentVertexId].size() < 1){\n\t\t\t\/\/ dead end\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reducedGraph[currentVertexId].size() > 1){\n\t\t\t\/\/ juncture point - each path vertex represents a new chunk start\n\t\t\tfor (int i = 0; i < reducedGraph[currentVertexId].size(); i++){\n\t\t\t\tcalculateChunks(reducedGraph[currentVertexId][i].read2);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcurrentVertexId = reducedGraph[currentVertexId][0].read2;\n\t}\n\tcollapsedReducedGraph.push_back(chunk);\n\n\treturn;\n}\n\n\nbool OverlapGraph::vertexAlreadyInChunk(int vertexId){\n\tfor (int i = 0; i < collapsedReducedGraph.size(); ++i){\n\t\tfor (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){\n\t\t\tif (vertexId == collapsedReducedGraph[i].members[j]){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}<commit_msg>Unitigs printing function - implementing<commit_after>#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <string.h>\n#include <fstream>\n#include \"overlapgraph.h\"\n\n#define VERTEX_INACTIVE 0\n#define VERTEX_ACTIVE 1\n#define VERTEX_ELIMINATED -1\n#define FUZZ 10\n\nusing namespace std;\n\nOverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)\n{\n\treads = readvector;\n\toverlaps = overlapvector;\n}\n\nvoid OverlapGraph::initialize()\n{\n\tgraph.resize(reads.size());\n\treducedGraph.resize(reads.size());\n\tnonContainedReads.resize(reads.size());\n\tnonContainedReads.assign(reads.size(), 1);\n\n\tfor(int i=0;i<overlaps.size();i++)\n\t{\n\t\toverlap o = overlaps[i];\n\n\n\t\t\/\/removing contained reads\n\t\tif(o.ahg > 0 & o.bhg > 0)\n\t\t\tgraph[o.read1].push_back(o);\n\t\telse if (o.ahg < 0 & o.bhg < 0)\n\t\t\tgraph[o.read2].push_back(o);\n\t\telse if (o.ahg >= 0 & o.bhg <= 0)\n\t\t\tnonContainedReads[o.read2] = 0;\n\t\telse if (o.ahg <= 0 & o.bhg>=0)\n\t\t\tnonContainedReads[o.read1] = 0;\n\t}\n}\n\nvoid OverlapGraph::runUnitigging()\n{\n\tint N = reads.size();\n\n\t\n\tinitialize();\n\n\tint *vertexstatus = (int *)malloc(N*sizeof(int));\n\tmemset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));\n\tvector< vector<bool> > reduceflags(N);\n\n\tfor (int i = 0; i < N; i++)\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t\treduceflags[i].push_back(false);\n\n\tfor (int I = 0; I < N; I++)\n\t{\n\t\tif (graph[I].size() == 0)\n\t\t\tcontinue;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t\tvertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;\n\n\t\tint longest = 0;\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (graph[I][j].bhg > longest)\n\t\t\t\tlongest = graph[I][j].bhg;\n\t\t}\n\n\t\tlongest += FUZZ;\n\t\tcout << longest << endl;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)\n\t\t\t{\n\t\t\t\tint x = graph[I][j].read2;\n\t\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t\t{\n\t\t\t\t\tif (graph[I][j].bhg + graph[x][k].bhg <= longest)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tint x = graph[I][j].read2;\n\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t{\n\t\t\t\tif (graph[x][k].bhg < FUZZ)\n\t\t\t\t{\n\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)\n\t\t\t{\n\t\t\t\treduceflags[I][j] = true;\n\t\t\t}\n\t\t\tvertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;\n\t\t}\n\t}\n\n\tfor(int i=0;i<graph.size();i++)\n {\n for(int j=0;j<graph[i].size();j++)\n {\n\t\t\tif (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){\n\t\t\t\t\/\/ Add edge to the reduced graph\n\t\t\t\treducedGraph[i].push_back(graph[i][j]);\n\t\t\t\tcout << graph[i][j].read1 << \" -> \" << graph[i][j].read2 << endl;\n\t\t\t}\n }\n }\n\tuniqueJoinCollapsing();\n\n\tfree(vertexstatus);\n\treturn;\n}\n\nvoid OverlapGraph::unitigsPrinting()\n{\n\tofstream output(\"unitigsPrinting.afg\");\n\t\n\tint counter = 1;\n\n\toutput << \"Unitigs{\" << endl;\n\n\tfor (Chunk c : collapsedReducedGraph)\n\t{\n\t\toutput << \"\\t\" << counter << \"{\" << endl;\n\t\toutput << \"\\t\\t members: \";\n\t\tfor (int a : c.members)\n\t\t{\n\t\t\toutput << a << \" \";\n\t\t}\n\n\t\toutput << endl;\n\t\toutput << \"\\t\" << \"}\" << endl;\n\t}\n\n\toutput << \"}\" << endl;\n}\n\nvoid OverlapGraph::printLayouts()\n{\n\tofstream output(\"layouts.afg\");\n\tofstream pretty(\"pretty.afg\");\n\tint *offsets = (int *)malloc(reads.size()*sizeof(int));\n\tmemset(offsets, 0, reads.size()*sizeof(int));\n\n\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t{\n\t\t\toverlap o = graph[i][j];\n\t\t\tif (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {\n\t\t\t\toffsets[o.read2] = offsets[o.read1] + o.ahg;\n\t\t\t}\n\t\t}\n\t}\n\n\toutput << \"{LAY\" << endl;\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tif (nonContainedReads[i]) \n\t\t{\n\t\t\toutput << \"{TLE\" << endl;\n\t\t\toutput << \"clr:0,\" << reads[i].length() << endl;\n\t\t\toutput << \"off:\" << offsets[i] << endl;\n\t\t\toutput << \"src:\" << i + 1 << endl;\n\t\t\toutput << \"}\" << endl;\n\n\t\t\tpretty << string(offsets[i], ' ') + reads[i] << endl;\n\t\t\t\/\/pretty <<reads[i] << endl;\n\n\t\t}\n\t}\n\n\toutput << \"}\" << endl;\n\toutput.close();\n\n\tfree(offsets);\n}\n\nvoid OverlapGraph::uniqueJoinCollapsing(){\n\n\treducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);\n\n\t\/\/ Calculate references to vertexes\n\tfor (int i = 0; i < reducedGraph.size(); i++){\n\t\tfor (int j = 0; j < reducedGraph[i].size(); j++){\n\t\t\treducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;\n\t\t}\n\t}\n\n\t\/\/ Find first \"juncture\" vertex\n\tint startingVertex = 0;\n\tbool startingVertexFound = false;\n\twhile (startingVertex < reducedGraph.size()){\n\t\tif (reducedGraph[startingVertex].size() > 0){\n\t\t\tstartingVertexFound = true;\n\t\t\tbreak;\n\t\t}\n\t\tstartingVertex++;\n\t}\n\tif (startingVertexFound){\n\t\tcalculateChunks(startingVertex);\n\t}\n}\n\nvoid OverlapGraph::calculateChunks(int chunkStartingVertexId){\n\t\n\tint currentVertexId = chunkStartingVertexId;\n\n\tif (vertexAlreadyInChunk(currentVertexId)){\n\t\treturn;\n\t}\n\n\t\/\/ create new chunk\n\tChunk chunk;\n\n\twhile (true){\n\t\tif (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){\n\t\t\t\/\/ special case: juncture vertex (not part of our chunk)\n\t\t\tcalculateChunks(currentVertexId);\n\t\t\tbreak;\n\t\t}\n\n\t\tchunk.members.push_back(currentVertexId);\n\n\t\tif (reducedGraph[currentVertexId].size() < 1){\n\t\t\t\/\/ dead end\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reducedGraph[currentVertexId].size() > 1){\n\t\t\t\/\/ juncture point - each path vertex represents a new chunk start\n\t\t\tfor (int i = 0; i < reducedGraph[currentVertexId].size(); i++){\n\t\t\t\tcalculateChunks(reducedGraph[currentVertexId][i].read2);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcurrentVertexId = reducedGraph[currentVertexId][0].read2;\n\t}\n\tcollapsedReducedGraph.push_back(chunk);\n\n\treturn;\n}\n\n\nbool OverlapGraph::vertexAlreadyInChunk(int vertexId){\n\tfor (int i = 0; i < collapsedReducedGraph.size(); ++i){\n\t\tfor (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){\n\t\t\tif (vertexId == collapsedReducedGraph[i].members[j]){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}<|endoftext|>"} {"text":"<commit_before>#include \"ResourcePool.h\"\n\n#include <osgDB\/ReadFile>\n\n\nusing namespace troen;\n\nResourcePool::ResourcePool() {}\n\nResourcePool::~ResourcePool() {}\n\nvoid ResourcePool::readData()\n{\n\tm_dataAlreadyRead = true;\n\n\tstd::string folder = \"data\/models\/cycle\/\";\n\n\tstd::string textureFileNames[m_textureCount] = {\n\t\t\"MG_MovieCycle_Body_SPEC.tga\",\n\t\t\"MG_MovieCycle_BodyHeadLight_EMSS.tga\",\n\t\t\"MG_MovieCycle_Body_NORM.tga\",\n\t\t\"MG_Player_Body_SPEC.tga\",\n\t\t\"MG_Player_Body_EMSS.tga\",\n\t\t\"MG_Player_Body_NORM.tga\",\n\t\t\"MG_MovieCycle_Tire_DIFF.tga\",\n\t\t\"MG_MovieCycle_Tire_EMSS.tga\",\n\t\t\"MG_MovieCycle_Tire_NORM.tga\",\n\t\t\"MG_Player_Helmet_SPEC.tga\",\n\t\t\"MG_Player_Helmet_EMSS.tga\",\n\t\t\"MG_Player_Helmet_NORM.tga\",\n\t\t\"MG_Player_Disc_SPEC.tga\",\n\t\t\"MG_Player_Disc_EMSS.tga\",\n\t\t\"MG_Player_Disc_NORM.tga\",\n\t\t\"Glass.tga\",\n\t\t\"MG_MovieCycle_Engine_EMSS.tga\",\n\t\t\"MG_MovieCycle_Engine_NORM.tga\",\n\t\t\"MG_Player_Baton_SPEC.tga\",\n\t\t\"MG_Player_Baton_EMSS.tga\",\n\t\t\"MG_Player_Baton_NORM.tga\"\n\t};\n\n\tfor (int i = 0; i < m_textureCount; ++i)\n\t{\n\t\tconst std::string filePath = folder + textureFileNames[i];\n\t\t\/\/m_images[i] = osgDB::readImageFile(filePath);\n\t\t\n\t\tosg::ref_ptr<osg::Image> img = osgDB::readImageFile(filePath);\n\t\tm_images[i] = img.release();\n\t\t\n\t}\n\n\n\tstd::string objFileNames[m_objectCount] = {\n\t\t\"MG_MovieCycle_Body_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerBody_MI.ive\",\n\t\t\"MG_MovieCycle_Tire_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerHelmet_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerDisc_MI.ive\",\n\t\t\"MG_MovieCycle_Glass_MI.ive\",\n\t\t\"MG_MovieCycle_Engine_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerBaton_MI.ive\"\n\t};\n\n\tfor (int i = 0; i < m_objectCount; ++i)\n\t{\n\t\tconst std::string filePath = folder + objFileNames[i];\n\t\tstd::cout << \"[TroenGame::bikeView] Loading Model \\\"\" << filePath << \"\\\"\" << std::endl;\n\t\tm_objects[i] = osgDB::readNodeFile(filePath);\n\t}\n\n}\n\nosg::Image* ResourcePool::getImage(TextureResource texture)\n{\n\tif (!m_dataAlreadyRead)\n\t\treadData();\n\n\tif (!m_images[texture]->valid() || !m_images[texture]) {\n\t\tstd::cout << \"rereading data for texture: \" << texture << std::endl;\n\t\treadData();\n\t}\n\n\treturn m_images[texture];\n}\n\n\nosg::Node* ResourcePool::getNode(ModelResource model)\n{\n\tif (!m_dataAlreadyRead)\n\t\treadData();\n\n\tconst osg::CopyOp copyOp(osg::CopyOp::SHALLOW_COPY);\n\treturn dynamic_cast<osg::Node*>(m_objects[model]->clone(copyOp));\n}<commit_msg>yet another check for valid resources; hopefully fixes #73<commit_after>#include \"ResourcePool.h\"\n\n#include <osgDB\/ReadFile>\n\n\nusing namespace troen;\n\nResourcePool::ResourcePool() {}\n\nResourcePool::~ResourcePool() {}\n\nvoid ResourcePool::readData()\n{\n\tm_dataAlreadyRead = true;\n\n\tstd::string folder = \"data\/models\/cycle\/\";\n\n\tstd::string textureFileNames[m_textureCount] = {\n\t\t\"MG_MovieCycle_Body_SPEC.tga\",\n\t\t\"MG_MovieCycle_BodyHeadLight_EMSS.tga\",\n\t\t\"MG_MovieCycle_Body_NORM.tga\",\n\t\t\"MG_Player_Body_SPEC.tga\",\n\t\t\"MG_Player_Body_EMSS.tga\",\n\t\t\"MG_Player_Body_NORM.tga\",\n\t\t\"MG_MovieCycle_Tire_DIFF.tga\",\n\t\t\"MG_MovieCycle_Tire_EMSS.tga\",\n\t\t\"MG_MovieCycle_Tire_NORM.tga\",\n\t\t\"MG_Player_Helmet_SPEC.tga\",\n\t\t\"MG_Player_Helmet_EMSS.tga\",\n\t\t\"MG_Player_Helmet_NORM.tga\",\n\t\t\"MG_Player_Disc_SPEC.tga\",\n\t\t\"MG_Player_Disc_EMSS.tga\",\n\t\t\"MG_Player_Disc_NORM.tga\",\n\t\t\"Glass.tga\",\n\t\t\"MG_MovieCycle_Engine_EMSS.tga\",\n\t\t\"MG_MovieCycle_Engine_NORM.tga\",\n\t\t\"MG_Player_Baton_SPEC.tga\",\n\t\t\"MG_Player_Baton_EMSS.tga\",\n\t\t\"MG_Player_Baton_NORM.tga\"\n\t};\n\n\tfor (int i = 0; i < m_textureCount; ++i)\n\t{\n\t\tconst std::string filePath = folder + textureFileNames[i];\n\t\t\/\/m_images[i] = osgDB::readImageFile(filePath);\n\t\t\n\t\tosg::ref_ptr<osg::Image> img = osgDB::readImageFile(filePath);\n\t\tm_images[i] = img.release();\n\t\t\n\t}\n\n\n\tstd::string objFileNames[m_objectCount] = {\n\t\t\"MG_MovieCycle_Body_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerBody_MI.ive\",\n\t\t\"MG_MovieCycle_Tire_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerHelmet_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerDisc_MI.ive\",\n\t\t\"MG_MovieCycle_Glass_MI.ive\",\n\t\t\"MG_MovieCycle_Engine_MI.ive\",\n\t\t\"MG_MovieCycle_PlayerBaton_MI.ive\"\n\t};\n\n\tfor (int i = 0; i < m_objectCount; ++i)\n\t{\n\t\tconst std::string filePath = folder + objFileNames[i];\n\t\tstd::cout << \"[TroenGame::bikeView] Loading Model \\\"\" << filePath << \"\\\"\" << std::endl;\n\t\tm_objects[i] = osgDB::readNodeFile(filePath);\n\t}\n\n}\n\nosg::Image* ResourcePool::getImage(TextureResource texture)\n{\n\tif (!m_dataAlreadyRead)\n\t\treadData();\n\n\tif (!m_images[texture]->valid() || !m_images[texture] || m_images[texture]->getImageSizeInBytes() <= 0) {\n\t\tstd::cout << \"rereading data for texture: \" << texture << std::endl;\n\t\treadData();\t\n\t}\n\n\treturn m_images[texture];\n}\n\n\nosg::Node* ResourcePool::getNode(ModelResource model)\n{\n\tif (!m_dataAlreadyRead)\n\t\treadData();\n\n\tconst osg::CopyOp copyOp(osg::CopyOp::SHALLOW_COPY);\n\treturn dynamic_cast<osg::Node*>(m_objects[model]->clone(copyOp));\n}<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file ws.cpp\n \\brief WebSocket C++ Library implementation\n \\author Ivan Shynkarenka\n \\date 22.05.2019\n \\copyright MIT License\n*\/\n\n#include \"server\/ws\/ws.h\"\n\n#include \"string\/encoding.h\"\n#include \"string\/format.h\"\n\n#include <algorithm>\n#include <openssl\/sha.h>\n\nnamespace CppServer {\nnamespace WS {\n\nbool WebSocket::PerformClientUpgrade(const HTTP::HTTPResponse& response, const CppCommon::UUID& id)\n{\n if (response.status() != 101)\n return false;\n\n bool error = false;\n bool accept = false;\n bool connection = false;\n bool upgrade = false;\n\n \/\/ Validate WebSocket handshake headers\n for (size_t i = 0; i < response.headers(); ++i)\n {\n auto header = response.header(i);\n auto key = std::get<0>(header);\n auto value = std::get<1>(header);\n\n if (key == \"Connection\")\n {\n if (value != \"Upgrade\")\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'\");\n break;\n }\n\n connection = true;\n }\n else if (key == \"Upgrade\")\n {\n if (value != \"websocket\")\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'\");\n break;\n }\n\n upgrade = true;\n }\n else if (key == \"Sec-WebSocket-Accept\")\n {\n \/\/ Calculate the original WebSocket hash\n std::string wskey = CppCommon::Encoding::Base64Encode(id.string()) + \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n char wshash[SHA_DIGEST_LENGTH];\n SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash);\n\n \/\/ Get the received WebSocket hash\n wskey = CppCommon::Encoding::Base64Decode(value);\n\n \/\/ Compare original and received hashes\n if (std::strncmp(wskey.data(), wshash, std::min(wskey.size(), sizeof(wshash))) != 0)\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed\");\n break;\n }\n\n accept = true;\n }\n }\n\n \/\/ Failed to perfrom WebSocket handshake\n if (!accept || !connection || !upgrade)\n {\n if (!error)\n onWSError(\"Invalid WebSocket response\");\n return false;\n }\n\n \/\/ WebSocket successfully handshaked!\n _ws_handshaked = true;\n *((uint32_t*)_ws_send_mask) = rand();\n onWSConnected(response);\n\n return true;\n}\n\nbool WebSocket::PerformServerUpgrade(const HTTP::HTTPRequest& request, HTTP::HTTPResponse& response)\n{\n if (request.method() != \"GET\")\n return false;\n\n bool error = false;\n bool connection = false;\n bool upgrade = false;\n bool ws_key = false;\n bool ws_version = false;\n\n std::string accept;\n\n \/\/ Validate WebSocket handshake headers\n for (size_t i = 0; i < request.headers(); ++i)\n {\n auto header = request.header(i);\n auto key = std::get<0>(header);\n auto value = std::get<1>(header);\n\n if (key == \"Connection\")\n {\n if ((value != \"Upgrade\") && (value != \"keep-alive, Upgrade\"))\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Connection' header value must be 'Upgrade' or 'keep-alive, Upgrade'\", 400);\n break;\n }\n\n connection = true;\n }\n else if (key == \"Upgrade\")\n {\n if (value != \"websocket\")\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Upgrade' header value must be 'websocket'\", 400);\n break;\n }\n\n upgrade = true;\n }\n else if (key == \"Sec-WebSocket-Key\")\n {\n if (value.empty())\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Sec-WebSocket-Key' header value must be non empty\", 400);\n break;\n }\n\n \/\/ Calculate WebSocket accept value\n std::string wskey = std::string(value) + \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n char wshash[SHA_DIGEST_LENGTH];\n SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash);\n\n accept = CppCommon::Encoding::Base64Encode(std::string(wshash, sizeof(wshash)));\n\n ws_key = true;\n }\n else if (key == \"Sec-WebSocket-Version\")\n {\n if (value != \"13\")\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Sec-WebSocket-Version' header value must be '13'\", 400);\n break;\n }\n\n ws_version = true;\n }\n }\n\n \/\/ Filter out non WebSocket handshake requests\n if (!connection && !upgrade && !ws_key && !ws_version)\n return false;\n\n \/\/ Failed to perfrom WebSocket handshake\n if (!connection || !upgrade || !ws_key || !ws_version)\n {\n if (!error)\n response.MakeErrorResponse(\"Invalid WebSocket response\", 400);\n SendResponse(response);\n return false;\n }\n\n \/\/ Prepare WebSocket upgrade success response\n response.Clear();\n response.SetBegin(101);\n response.SetHeader(\"Connection\", \"Upgrade\");\n response.SetHeader(\"Upgrade\", \"websocket\");\n response.SetHeader(\"Sec-WebSocket-Accept\", accept);\n response.SetBody();\n\n \/\/ Validate WebSocket upgrade request and response\n if (!onWSConnecting(request, response))\n return false;\n\n \/\/ Send WebSocket upgrade response\n SendResponse(response);\n\n \/\/ WebSocket successfully handshaked!\n _ws_handshaked = true;\n *((uint32_t*)_ws_send_mask) = 0;\n onWSConnected(request);\n\n return true;\n}\n\nvoid WebSocket::PrepareSendFrame(uint8_t opcode, bool mask, const void* buffer, size_t size, int status)\n{\n \/\/ Clear the previous WebSocket send buffer\n _ws_send_buffer.clear();\n\n \/\/ Append WebSocket frame opcode\n _ws_send_buffer.push_back(opcode);\n\n \/\/ Append WebSocket frame size\n if (size <= 125)\n _ws_send_buffer.push_back((size & 0xFF) | (mask ? 0x80 : 0));\n else if (size <= 65535)\n {\n _ws_send_buffer.push_back(126 | (mask ? 0x80 : 0));\n _ws_send_buffer.push_back((size >> 8) & 0xFF);\n _ws_send_buffer.push_back(size & 0xFF);\n }\n else\n {\n _ws_send_buffer.push_back(127 | (mask ? 0x80 : 0));\n for (int i = 7; i >= 0; --i)\n _ws_send_buffer.push_back((size >> (8 * i)) & 0xFF);\n }\n\n if (mask)\n {\n \/\/ Append WebSocket frame mask\n _ws_send_buffer.push_back(_ws_send_mask[0]);\n _ws_send_buffer.push_back(_ws_send_mask[1]);\n _ws_send_buffer.push_back(_ws_send_mask[2]);\n _ws_send_buffer.push_back(_ws_send_mask[3]);\n }\n\n \/\/ Resize WebSocket frame buffer\n size_t offset = _ws_send_buffer.size();\n _ws_send_buffer.resize(offset + size);\n\n \/\/ Mask WebSocket frame content\n const uint8_t* data = (const uint8_t*)buffer;\n for (size_t i = 0; i < size; ++i)\n _ws_send_buffer[offset + i] = data[i] ^ _ws_send_mask[i % 4];\n}\n\nvoid WebSocket::PrepareReceiveFrame(const void* buffer, size_t size)\n{\n const uint8_t* data = (const uint8_t*)buffer;\n\n \/\/ Clear received data after WebSocket frame was processed\n if (_ws_received)\n {\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n }\n\n while (size > 0)\n {\n \/\/ Clear received data after WebSocket frame was processed\n if (_ws_received)\n {\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n }\n\n \/\/ Prepare WebSocket frame opcode and mask flag\n if (_ws_receive_buffer.size() < 2)\n {\n for (size_t i = 0; i < 2; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n uint8_t opcode = _ws_receive_buffer[0] & 0x0F;\n [[maybe_unused]] bool fin = ((_ws_receive_buffer[0] >> 7) & 0x01) != 0;\n bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0;\n size_t payload = _ws_receive_buffer[1] & (~0x80);\n\n \/\/ Prepare WebSocket frame size\n if (payload <= 125)\n {\n _ws_header_size = 2 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n else if (payload == 126)\n {\n if (_ws_receive_buffer.size() < 4)\n {\n for (size_t i = 0; i < 2; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n payload = (((size_t)_ws_receive_buffer[2] << 8) | ((size_t)_ws_receive_buffer[3] << 0));\n _ws_header_size = 4 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n else if (payload == 127)\n {\n if (_ws_receive_buffer.size() < 10)\n {\n for (size_t i = 0; i < 8; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n payload = (((size_t)_ws_receive_buffer[2] << 56) | ((size_t)_ws_receive_buffer[3] << 48) | ((size_t)_ws_receive_buffer[4] << 40) | ((size_t)_ws_receive_buffer[5] << 32) | ((size_t)_ws_receive_buffer[6] << 24) | ((size_t)_ws_receive_buffer[7] << 16) | ((size_t)_ws_receive_buffer[8] << 8) | ((size_t)_ws_receive_buffer[9] << 0));\n _ws_header_size = 10 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n\n \/\/ Prepare WebSocket frame mask\n if (mask)\n {\n if (_ws_receive_buffer.size() < _ws_header_size)\n {\n for (size_t i = 0; i < 4; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n _ws_receive_mask[i] = *data;\n }\n }\n }\n\n size_t total = _ws_header_size + _ws_payload_size;\n size_t length = std::min(total - _ws_receive_buffer.size(), size);\n\n \/\/ Prepare WebSocket frame payload\n _ws_receive_buffer.insert(_ws_receive_buffer.end(), data, data + length);\n data += length;\n size -= length;\n\n \/\/ Process WebSocket frame\n if (_ws_receive_buffer.size() == total)\n {\n size_t offset = _ws_header_size;\n\n \/\/ Unmask WebSocket frame content\n if (mask)\n for (size_t i = 0; i < _ws_payload_size; ++i)\n _ws_receive_buffer[offset + i] ^= _ws_receive_mask[i % 4];\n\n _ws_received = true;\n\n if ((opcode & WS_PING) == WS_PING)\n {\n \/\/ Call the WebSocket ping handler\n onWSPing(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if ((opcode & WS_PONG) == WS_PONG)\n {\n \/\/ Call the WebSocket pong handler\n onWSPong(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if ((opcode & WS_CLOSE) == WS_CLOSE)\n {\n \/\/ Call the WebSocket close handler\n onWSClose(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if (((opcode & WS_TEXT) == WS_TEXT) || ((opcode & WS_BINARY) == WS_BINARY))\n {\n \/\/ Call the WebSocket received handler\n onWSReceived(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n }\n }\n}\n\nsize_t WebSocket::RequiredReceiveFrameSize()\n{\n if (_ws_received)\n return 0;\n\n \/\/ Required WebSocket frame opcode and mask flag\n if (_ws_receive_buffer.size() < 2)\n return 2 - _ws_receive_buffer.size();\n\n bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0;\n size_t payload = _ws_receive_buffer[1] & (~0x80);\n\n \/\/ Required WebSocket frame size\n if ((payload == 126) && (_ws_receive_buffer.size() < 4))\n return 4 - _ws_receive_buffer.size();\n if ((payload == 127) && (_ws_receive_buffer.size() < 10))\n return 10 - _ws_receive_buffer.size();\n\n \/\/ Required WebSocket frame mask\n if ((mask) && (_ws_receive_buffer.size() < _ws_header_size))\n return _ws_header_size - _ws_receive_buffer.size();\n\n \/\/ Required WebSocket frame payload\n return _ws_header_size + _ws_payload_size - _ws_receive_buffer.size();\n}\n\nvoid WebSocket::ClearWSBuffers()\n{\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n\n std::scoped_lock locker(_ws_send_lock);\n\n _ws_send_buffer.clear();\n *((uint32_t*)_ws_send_mask) = 0;\n}\n\n} \/\/ namespace WS\n} \/\/ namespace CppServer\n<commit_msg>Fixed WebSockets for Firefox<commit_after>\/*!\n \\file ws.cpp\n \\brief WebSocket C++ Library implementation\n \\author Ivan Shynkarenka\n \\date 22.05.2019\n \\copyright MIT License\n*\/\n\n#include \"server\/ws\/ws.h\"\n\n#include \"string\/encoding.h\"\n#include \"string\/format.h\"\n\n#include <algorithm>\n#include <openssl\/sha.h>\n\nnamespace CppServer {\nnamespace WS {\n\nbool WebSocket::PerformClientUpgrade(const HTTP::HTTPResponse& response, const CppCommon::UUID& id)\n{\n if (response.status() != 101)\n return false;\n\n bool error = false;\n bool accept = false;\n bool connection = false;\n bool upgrade = false;\n\n \/\/ Validate WebSocket handshake headers\n for (size_t i = 0; i < response.headers(); ++i)\n {\n auto header = response.header(i);\n auto key = std::get<0>(header);\n auto value = std::get<1>(header);\n\n if (key == \"Connection\")\n {\n if (value != \"Upgrade\")\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'\");\n break;\n }\n\n connection = true;\n }\n else if (key == \"Upgrade\")\n {\n if (value != \"websocket\")\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'\");\n break;\n }\n\n upgrade = true;\n }\n else if (key == \"Sec-WebSocket-Accept\")\n {\n \/\/ Calculate the original WebSocket hash\n std::string wskey = CppCommon::Encoding::Base64Encode(id.string()) + \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n char wshash[SHA_DIGEST_LENGTH];\n SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash);\n\n \/\/ Get the received WebSocket hash\n wskey = CppCommon::Encoding::Base64Decode(value);\n\n \/\/ Compare original and received hashes\n if (std::strncmp(wskey.data(), wshash, std::min(wskey.size(), sizeof(wshash))) != 0)\n {\n error = true;\n onWSError(\"Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed\");\n break;\n }\n\n accept = true;\n }\n }\n\n \/\/ Failed to perfrom WebSocket handshake\n if (!accept || !connection || !upgrade)\n {\n if (!error)\n onWSError(\"Invalid WebSocket response\");\n return false;\n }\n\n \/\/ WebSocket successfully handshaked!\n _ws_handshaked = true;\n *((uint32_t*)_ws_send_mask) = rand();\n onWSConnected(response);\n\n return true;\n}\n\nbool WebSocket::PerformServerUpgrade(const HTTP::HTTPRequest& request, HTTP::HTTPResponse& response)\n{\n if (request.method() != \"GET\")\n return false;\n\n bool error = false;\n bool connection = false;\n bool upgrade = false;\n bool ws_key = false;\n bool ws_version = false;\n\n std::string accept;\n\n \/\/ Validate WebSocket handshake headers\n for (size_t i = 0; i < request.headers(); ++i)\n {\n auto header = request.header(i);\n auto key = std::get<0>(header);\n auto value = std::get<1>(header);\n\n if (key == \"Connection\")\n {\n if ((value != \"Upgrade\") && (value != \"keep-alive, Upgrade\"))\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Connection' header value must be 'Upgrade' or 'keep-alive, Upgrade'\", 400);\n break;\n }\n\n connection = true;\n }\n else if (key == \"Upgrade\")\n {\n if (value != \"websocket\")\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Upgrade' header value must be 'websocket'\", 400);\n break;\n }\n\n upgrade = true;\n }\n else if (key == \"Sec-WebSocket-Key\")\n {\n if (value.empty())\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Sec-WebSocket-Key' header value must be non empty\", 400);\n break;\n }\n\n \/\/ Calculate WebSocket accept value\n std::string wskey = std::string(value) + \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n char wshash[SHA_DIGEST_LENGTH];\n SHA1((const unsigned char*)wskey.data(), wskey.size(), (unsigned char*)wshash);\n\n accept = CppCommon::Encoding::Base64Encode(std::string(wshash, sizeof(wshash)));\n\n ws_key = true;\n }\n else if (key == \"Sec-WebSocket-Version\")\n {\n if (value != \"13\")\n {\n error = true;\n response.MakeErrorResponse(\"Invalid WebSocket handshaked request: 'Sec-WebSocket-Version' header value must be '13'\", 400);\n break;\n }\n\n ws_version = true;\n }\n }\n\n \/\/ Filter out non WebSocket handshake requests\n if (!connection && !upgrade && !ws_key && !ws_version)\n return false;\n\n \/\/ Failed to perfrom WebSocket handshake\n if (!connection || !upgrade || !ws_key || !ws_version)\n {\n if (!error)\n response.MakeErrorResponse(\"Invalid WebSocket response\", 400);\n SendResponse(response);\n return false;\n }\n\n \/\/ Prepare WebSocket upgrade success response\n response.Clear();\n response.SetBegin(101, \"HTTP\/1.1\");\n response.SetHeader(\"Connection\", \"Upgrade\");\n response.SetHeader(\"Upgrade\", \"websocket\");\n response.SetHeader(\"Sec-WebSocket-Accept\", accept);\n response.SetBody();\n\n \/\/ Validate WebSocket upgrade request and response\n if (!onWSConnecting(request, response))\n return false;\n\n \/\/ Send WebSocket upgrade response\n SendResponse(response);\n\n \/\/ WebSocket successfully handshaked!\n _ws_handshaked = true;\n *((uint32_t*)_ws_send_mask) = 0;\n onWSConnected(request);\n\n return true;\n}\n\nvoid WebSocket::PrepareSendFrame(uint8_t opcode, bool mask, const void* buffer, size_t size, int status)\n{\n \/\/ Clear the previous WebSocket send buffer\n _ws_send_buffer.clear();\n\n \/\/ Append WebSocket frame opcode\n _ws_send_buffer.push_back(opcode);\n\n \/\/ Append WebSocket frame size\n if (size <= 125)\n _ws_send_buffer.push_back((size & 0xFF) | (mask ? 0x80 : 0));\n else if (size <= 65535)\n {\n _ws_send_buffer.push_back(126 | (mask ? 0x80 : 0));\n _ws_send_buffer.push_back((size >> 8) & 0xFF);\n _ws_send_buffer.push_back(size & 0xFF);\n }\n else\n {\n _ws_send_buffer.push_back(127 | (mask ? 0x80 : 0));\n for (int i = 7; i >= 0; --i)\n _ws_send_buffer.push_back((size >> (8 * i)) & 0xFF);\n }\n\n if (mask)\n {\n \/\/ Append WebSocket frame mask\n _ws_send_buffer.push_back(_ws_send_mask[0]);\n _ws_send_buffer.push_back(_ws_send_mask[1]);\n _ws_send_buffer.push_back(_ws_send_mask[2]);\n _ws_send_buffer.push_back(_ws_send_mask[3]);\n }\n\n \/\/ Resize WebSocket frame buffer\n size_t offset = _ws_send_buffer.size();\n _ws_send_buffer.resize(offset + size);\n\n \/\/ Mask WebSocket frame content\n const uint8_t* data = (const uint8_t*)buffer;\n for (size_t i = 0; i < size; ++i)\n _ws_send_buffer[offset + i] = data[i] ^ _ws_send_mask[i % 4];\n}\n\nvoid WebSocket::PrepareReceiveFrame(const void* buffer, size_t size)\n{\n const uint8_t* data = (const uint8_t*)buffer;\n\n \/\/ Clear received data after WebSocket frame was processed\n if (_ws_received)\n {\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n }\n\n while (size > 0)\n {\n \/\/ Clear received data after WebSocket frame was processed\n if (_ws_received)\n {\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n }\n\n \/\/ Prepare WebSocket frame opcode and mask flag\n if (_ws_receive_buffer.size() < 2)\n {\n for (size_t i = 0; i < 2; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n uint8_t opcode = _ws_receive_buffer[0] & 0x0F;\n [[maybe_unused]] bool fin = ((_ws_receive_buffer[0] >> 7) & 0x01) != 0;\n bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0;\n size_t payload = _ws_receive_buffer[1] & (~0x80);\n\n \/\/ Prepare WebSocket frame size\n if (payload <= 125)\n {\n _ws_header_size = 2 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n else if (payload == 126)\n {\n if (_ws_receive_buffer.size() < 4)\n {\n for (size_t i = 0; i < 2; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n payload = (((size_t)_ws_receive_buffer[2] << 8) | ((size_t)_ws_receive_buffer[3] << 0));\n _ws_header_size = 4 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n else if (payload == 127)\n {\n if (_ws_receive_buffer.size() < 10)\n {\n for (size_t i = 0; i < 8; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n }\n }\n\n payload = (((size_t)_ws_receive_buffer[2] << 56) | ((size_t)_ws_receive_buffer[3] << 48) | ((size_t)_ws_receive_buffer[4] << 40) | ((size_t)_ws_receive_buffer[5] << 32) | ((size_t)_ws_receive_buffer[6] << 24) | ((size_t)_ws_receive_buffer[7] << 16) | ((size_t)_ws_receive_buffer[8] << 8) | ((size_t)_ws_receive_buffer[9] << 0));\n _ws_header_size = 10 + (mask ? 4 : 0);\n _ws_payload_size = payload;\n _ws_receive_buffer.reserve(_ws_header_size + _ws_payload_size);\n }\n\n \/\/ Prepare WebSocket frame mask\n if (mask)\n {\n if (_ws_receive_buffer.size() < _ws_header_size)\n {\n for (size_t i = 0; i < 4; ++i, ++data, --size)\n {\n if (size == 0)\n return;\n _ws_receive_buffer.push_back(*data);\n _ws_receive_mask[i] = *data;\n }\n }\n }\n\n size_t total = _ws_header_size + _ws_payload_size;\n size_t length = std::min(total - _ws_receive_buffer.size(), size);\n\n \/\/ Prepare WebSocket frame payload\n _ws_receive_buffer.insert(_ws_receive_buffer.end(), data, data + length);\n data += length;\n size -= length;\n\n \/\/ Process WebSocket frame\n if (_ws_receive_buffer.size() == total)\n {\n size_t offset = _ws_header_size;\n\n \/\/ Unmask WebSocket frame content\n if (mask)\n for (size_t i = 0; i < _ws_payload_size; ++i)\n _ws_receive_buffer[offset + i] ^= _ws_receive_mask[i % 4];\n\n _ws_received = true;\n\n if ((opcode & WS_PING) == WS_PING)\n {\n \/\/ Call the WebSocket ping handler\n onWSPing(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if ((opcode & WS_PONG) == WS_PONG)\n {\n \/\/ Call the WebSocket pong handler\n onWSPong(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if ((opcode & WS_CLOSE) == WS_CLOSE)\n {\n \/\/ Call the WebSocket close handler\n onWSClose(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n else if (((opcode & WS_TEXT) == WS_TEXT) || ((opcode & WS_BINARY) == WS_BINARY))\n {\n \/\/ Call the WebSocket received handler\n onWSReceived(_ws_receive_buffer.data() + offset, _ws_payload_size);\n }\n }\n }\n}\n\nsize_t WebSocket::RequiredReceiveFrameSize()\n{\n if (_ws_received)\n return 0;\n\n \/\/ Required WebSocket frame opcode and mask flag\n if (_ws_receive_buffer.size() < 2)\n return 2 - _ws_receive_buffer.size();\n\n bool mask = ((_ws_receive_buffer[1] >> 7) & 0x01) != 0;\n size_t payload = _ws_receive_buffer[1] & (~0x80);\n\n \/\/ Required WebSocket frame size\n if ((payload == 126) && (_ws_receive_buffer.size() < 4))\n return 4 - _ws_receive_buffer.size();\n if ((payload == 127) && (_ws_receive_buffer.size() < 10))\n return 10 - _ws_receive_buffer.size();\n\n \/\/ Required WebSocket frame mask\n if ((mask) && (_ws_receive_buffer.size() < _ws_header_size))\n return _ws_header_size - _ws_receive_buffer.size();\n\n \/\/ Required WebSocket frame payload\n return _ws_header_size + _ws_payload_size - _ws_receive_buffer.size();\n}\n\nvoid WebSocket::ClearWSBuffers()\n{\n _ws_received = false;\n _ws_header_size = 0;\n _ws_payload_size = 0;\n _ws_receive_buffer.clear();\n *((uint32_t*)_ws_receive_mask) = 0;\n\n std::scoped_lock locker(_ws_send_lock);\n\n _ws_send_buffer.clear();\n *((uint32_t*)_ws_send_mask) = 0;\n}\n\n} \/\/ namespace WS\n} \/\/ namespace CppServer\n<|endoftext|>"} {"text":"<commit_before>#include \"map.h\"\n\nMap::Map(Vector2i mapSize, Vector2f blockSize) {\n\tthis->size = mapSize;\n\n\tthis->renderTex.create(this->size.x * blockSize.x, this->size.y * blockSize.y);\n\n\tfor (int row = 0; row < mapSize.x; row++) {\n\t\tthis->mapData.push_back(std::vector<int>());\n\n\t\tfor (int col = 0; col < mapSize.y; col++) {\n\t\t\tthis->mapData[row].push_back(255);\n\t\t}\n\t}\n\n\tblock.setSize(blockSize);\n}\n\nMap::~Map() {}\n\nvoid Map::Save(std::string fileName) {\n\t\/\/ SAVE BLOCK HEIGHTS\n\tthis->renderTex.clear();\n\n\tRectangleShape block;\n\n\tfor (unsigned int row = 0; row < this->size.x; row++) {\n\t\tfor (unsigned int col = 0; col < this->size.y; col++) {\n\t\t\tblock.setFillColor(Color(this->mapData[row][col], this->mapData[row][col], this->mapData[row][col], 255));\n\t\t\tblock.setPosition(Vector2f(row * block.getSize().x, col * block.getSize().y));\n\t\t\trenderTex.draw(block);\n\t\t}\n\t}\n\n\tthis->renderTex.display();\n\n\tsf::Image image;\n\timage.create(size.x, size.y, sf::Color::Black);\n\n\tfor (unsigned int row = 0; row < this->size.x; row++) {\n\t\tfor (unsigned int col = 0; col < this->size.y; col++) {\n\t\t\timage.setPixel(row, col, Color(mapData[row][col], mapData[row][col], mapData[row][col], 255));\n\t\t}\n\t}\n\n\timage.saveToFile(\"maps\/\" + fileName + \".png\");\n\n\t\/\/ SAVE OBJECT DATA\n\tstd::ofstream out;\n\n\tout.open(\"maps\/\" + fileName + \".toobj\");\n\n\tif (out.is_open()) {\n\t\tfor (size_t i = 0; i < this->enemySpawners.size(); i++) {\n\t\t\tout << enemySpawners[i].position.x << \" \" << enemySpawners[i].position.y << \" \" << enemySpawners[i].eCount << \" \" << enemySpawners[i].eHP << \"\\n\";\n\t\t}\n\t} else\n\t\tstd::cout << \"ERROR OPENING FILE \" << (fileName) << \"\\n\";\n\n\tout.close();\n}\n\nvoid Map::Draw(RenderTarget& target) {\n\tthis->renderTex.clear(Color::White);\n\n\tfor (unsigned int row = 0; row < this->size.x; row++) {\n\t\tfor (unsigned int col = 0; col < this->size.y; col++) {\n\t\t\tblock.setFillColor(Color(this->mapData[row][col], this->mapData[row][col], this->mapData[row][col], 255));\n\t\t\tblock.setPosition(Vector2f(row * block.getSize().x, col * block.getSize().y));\n\t\t\trenderTex.draw(block);\n\n\t\t\t\/*std::cout << block.getPosition().x << \" \" << block.getPosition().y << \"\\n\";*\/\n\t\t}\n\t}\n\n\tthis->renderTex.display();\n\n\tthis->renderSprite.setTexture(this->renderTex.getTexture());\n\n\ttarget.draw(this->renderSprite);\n}\n<commit_msg>Fixed int compare thingy<commit_after>#include \"map.h\"\n\nMap::Map(Vector2i mapSize, Vector2f blockSize) {\n\tthis->size = mapSize;\n\n\tthis->renderTex.create(this->size.x * blockSize.x, this->size.y * blockSize.y);\n\n\tfor (int row = 0; row < mapSize.x; row++) {\n\t\tthis->mapData.push_back(std::vector<int>());\n\n\t\tfor (int col = 0; col < mapSize.y; col++) {\n\t\t\tthis->mapData[row].push_back(255);\n\t\t}\n\t}\n\n\tblock.setSize(blockSize);\n}\n\nMap::~Map() {}\n\nvoid Map::Save(std::string fileName) {\n\t\/\/ SAVE BLOCK HEIGHTS\n\tthis->renderTex.clear();\n\n\tRectangleShape block;\n\n\tfor (int row = 0; row < this->size.x; row++) {\n\t\tfor (int col = 0; col < this->size.y; col++) {\n\t\t\tblock.setFillColor(Color(this->mapData[row][col], this->mapData[row][col], this->mapData[row][col], 255));\n\t\t\tblock.setPosition(Vector2f(row * block.getSize().x, col * block.getSize().y));\n\t\t\trenderTex.draw(block);\n\t\t}\n\t}\n\n\tthis->renderTex.display();\n\n\tsf::Image image;\n\timage.create(size.x, size.y, sf::Color::Black);\n\n\tfor (int row = 0; row < this->size.x; row++) {\n\t\tfor (int col = 0; col < this->size.y; col++) {\n\t\t\timage.setPixel(row, col, Color(mapData[row][col], mapData[row][col], mapData[row][col], 255));\n\t\t}\n\t}\n\n\timage.saveToFile(\"maps\/\" + fileName + \".png\");\n\n\t\/\/ SAVE OBJECT DATA\n\tstd::ofstream out;\n\n\tout.open(\"maps\/\" + fileName + \".toobj\");\n\n\tif (out.is_open()) {\n\t\tfor (size_t i = 0; i < this->enemySpawners.size(); i++) {\n\t\t\tout << enemySpawners[i].position.x << \" \" << enemySpawners[i].position.y << \" \" << enemySpawners[i].eCount << \" \" << enemySpawners[i].eHP << \"\\n\";\n\t\t}\n\t} else\n\t\tstd::cout << \"ERROR OPENING FILE \" << (fileName) << \"\\n\";\n\n\tout.close();\n}\n\nvoid Map::Draw(RenderTarget& target) {\n\tthis->renderTex.clear(Color::White);\n\n\tfor (int row = 0; row < this->size.x; row++) {\n\t\tfor (int col = 0; col < this->size.y; col++) {\n\t\t\tblock.setFillColor(Color(this->mapData[row][col], this->mapData[row][col], this->mapData[row][col], 255));\n\t\t\tblock.setPosition(Vector2f(row * block.getSize().x, col * block.getSize().y));\n\t\t\trenderTex.draw(block);\n\n\t\t\t\/*std::cout << block.getPosition().x << \" \" << block.getPosition().y << \"\\n\";*\/\n\t\t}\n\t}\n\n\tthis->renderTex.display();\n\n\tthis->renderSprite.setTexture(this->renderTex.getTexture());\n\n\ttarget.draw(this->renderSprite);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"main.h\"\n#include \"primitives\/transaction.h\"\n#include \"consensus\/validation.h\"\n\nTEST(checktransaction_tests, check_vpub_not_both_nonzero) {\n CMutableTransaction tx;\n tx.nVersion = 2;\n\n {\n \/\/ Ensure that values within the pour are well-formed.\n CMutableTransaction newTx(tx);\n CValidationState state;\n state.SetPerformPourVerification(false); \/\/ don't verify the snark\n\n newTx.vpour.push_back(CPourTx());\n\n CPourTx *pourtx = &newTx.vpour[0];\n pourtx->vpub_old = 1;\n pourtx->vpub_new = 1;\n\n EXPECT_FALSE(CheckTransaction(newTx, state));\n EXPECT_EQ(state.GetRejectReason(), \"bad-txns-vpubs-both-nonzero\");\n }\n}\n\nclass MockCValidationState : public CValidationState {\npublic:\n MOCK_METHOD5(DoS, bool(int level, bool ret,\n unsigned char chRejectCodeIn, std::string strRejectReasonIn,\n bool corruptionIn));\n MOCK_METHOD1(SetPerformPourVerification, bool(bool pourVerifyIn));\n MOCK_METHOD0(PerformPourVerification, bool());\n MOCK_METHOD3(Invalid, bool(bool ret,\n unsigned char _chRejectCode, std::string _strRejectReason));\n MOCK_METHOD1(Error, bool(std::string strRejectReasonIn));\n MOCK_CONST_METHOD0(IsValid, bool());\n MOCK_CONST_METHOD0(IsInvalid, bool());\n MOCK_CONST_METHOD0(IsError, bool());\n MOCK_CONST_METHOD1(IsInvalid, bool(int &nDoSOut));\n MOCK_CONST_METHOD0(CorruptionPossible, bool());\n MOCK_CONST_METHOD0(GetRejectCode, unsigned char());\n MOCK_CONST_METHOD0(GetRejectReason, std::string());\n};\n\nTEST(checktransaction_tests, mock_proof_of_concept) {\n CTransaction tx;\n MockCValidationState state;\n EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, \"bad-txns-vin-empty\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n<commit_msg>WIP: Add mock test coverage of CheckTransaction<commit_after>#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"main.h\"\n#include \"primitives\/transaction.h\"\n#include \"consensus\/validation.h\"\n\nTEST(checktransaction_tests, check_vpub_not_both_nonzero) {\n CMutableTransaction tx;\n tx.nVersion = 2;\n\n {\n \/\/ Ensure that values within the pour are well-formed.\n CMutableTransaction newTx(tx);\n CValidationState state;\n state.SetPerformPourVerification(false); \/\/ don't verify the snark\n\n newTx.vpour.push_back(CPourTx());\n\n CPourTx *pourtx = &newTx.vpour[0];\n pourtx->vpub_old = 1;\n pourtx->vpub_new = 1;\n\n EXPECT_FALSE(CheckTransaction(newTx, state));\n EXPECT_EQ(state.GetRejectReason(), \"bad-txns-vpubs-both-nonzero\");\n }\n}\n\nclass MockCValidationState : public CValidationState {\npublic:\n MOCK_METHOD5(DoS, bool(int level, bool ret,\n unsigned char chRejectCodeIn, std::string strRejectReasonIn,\n bool corruptionIn));\n MOCK_METHOD1(SetPerformPourVerification, bool(bool pourVerifyIn));\n MOCK_METHOD0(PerformPourVerification, bool());\n MOCK_METHOD3(Invalid, bool(bool ret,\n unsigned char _chRejectCode, std::string _strRejectReason));\n MOCK_METHOD1(Error, bool(std::string strRejectReasonIn));\n MOCK_CONST_METHOD0(IsValid, bool());\n MOCK_CONST_METHOD0(IsInvalid, bool());\n MOCK_CONST_METHOD0(IsError, bool());\n MOCK_CONST_METHOD1(IsInvalid, bool(int &nDoSOut));\n MOCK_CONST_METHOD0(CorruptionPossible, bool());\n MOCK_CONST_METHOD0(GetRejectCode, unsigned char());\n MOCK_CONST_METHOD0(GetRejectReason, std::string());\n};\n\n\nCMutableTransaction GetValidTransaction() {\n CMutableTransaction mtx;\n mtx.vin.resize(2);\n mtx.vin[0].prevout.hash = uint256S(\"0000000000000000000000000000000000000000000000000000000000000000\");\n mtx.vin[0].prevout.n = 0;\n mtx.vin[1].prevout.hash = uint256S(\"0000000000000000000000000000000000000000000000000000000000000001\");\n mtx.vin[1].prevout.n = 0;\n mtx.vout.resize(2);\n \/\/ mtx.vout[0].scriptPubKey = \n mtx.vout[0].nValue = 0;\n mtx.vout[1].nValue = 0;\n mtx.vpour.resize(2);\n mtx.vpour[0].serials.at(0) = uint256S(\"0000000000000000000000000000000000000000000000000000000000000000\");\n mtx.vpour[0].serials.at(1) = uint256S(\"0000000000000000000000000000000000000000000000000000000000000001\");\n mtx.vpour[1].serials.at(0) = uint256S(\"0000000000000000000000000000000000000000000000000000000000000002\");\n mtx.vpour[1].serials.at(1) = uint256S(\"0000000000000000000000000000000000000000000000000000000000000003\");\n return mtx;\n}\n\nTEST(checktransaction_tests, valid_transaction) {\n CMutableTransaction mtx = GetValidTransaction();\n CTransaction tx(mtx);\n MockCValidationState state;\n EXPECT_TRUE(CheckTransaction(tx, state));\n}\n\nTEST(checktransaction_tests, bad_txns_vin_empty) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour.resize(0);\n mtx.vin.resize(0);\n\n CTransaction tx(mtx);\n MockCValidationState state;\n EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, \"bad-txns-vin-empty\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vout_empty) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour.resize(0);\n mtx.vout.resize(0);\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(10, false, REJECT_INVALID, \"bad-txns-vout-empty\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_oversize) {\n CMutableTransaction mtx = GetValidTransaction();\n\n mtx.vin[0].scriptSig = CScript();\n \/\/ 18 * (520char + DROP) + OP_1 = 9433 bytes\n std::vector<unsigned char> vchData(520);\n for (unsigned int i = 0; i < 2000; ++i)\n mtx.vin[0].scriptSig << vchData << OP_DROP;\n mtx.vin[0].scriptSig << OP_1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-oversize\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vout_negative) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vout[0].nValue = -1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vout-negative\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vout_toolarge) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vout[0].nValue = MAX_MONEY + 1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vout-toolarge\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_txouttotal_toolarge_outputs) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vout[0].nValue = MAX_MONEY;\n mtx.vout[1].nValue = 1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-txouttotal-toolarge\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_txouttotal_toolarge_joinsplit) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vout[0].nValue = 1;\n mtx.vpour[0].vpub_new = MAX_MONEY;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-txouttotal-toolarge\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vpub_old_negative) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour[0].vpub_old = -1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vpub_old-negative\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vpub_new_negative) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour[0].vpub_new = -1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vpub_new-negative\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vpub_old_toolarge) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour[0].vpub_old = MAX_MONEY + 1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vpub_old-toolarge\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vpub_new_toolarge) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour[0].vpub_new = MAX_MONEY + 1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vpub_new-toolarge\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n\nTEST(checktransaction_tests, bad_txns_vpubs_both_nonzero) {\n CMutableTransaction mtx = GetValidTransaction();\n mtx.vpour[0].vpub_old = 1;\n mtx.vpour[0].vpub_new = 1;\n\n CTransaction tx(mtx);\n\n MockCValidationState state;\n EXPECT_CALL(state, DoS(100, false, REJECT_INVALID, \"bad-txns-vpubs-both-nonzero\", false)).Times(1);\n CheckTransaction(tx, state);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n\r\n#include <seqan\/store.h>\r\n#include <seqan\/misc\/misc_cmdparser.h>\r\n#include <seqan\/misc\/misc_svg.h>\r\n\r\nusing namespace seqan;\r\n\r\nint main(int argc, const char *argv[])\r\n{\r\n\ttypedef FragmentStore<> TFragStore;\r\n\ttypedef TFragStore::TContigPos TContigPos;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Define options\r\n\tCommandLineParser parser;\r\n\taddUsageLine(parser, \"[OPTION]... <SAM file> <SVG file>\");\r\n\taddUsageLine(parser, \"[OPTION]... <SAM file> <GENOME file> <SVG file>\");\r\n\t\r\n\taddOption(parser, CommandLineOption(\"c\", \"contig\", \"display only contig #NUM (default: show all contigs)\", OptionType::Int | OptionType::Label | OptionType::List));\r\n\taddOption(parser, CommandLineOption(\"p\", \"pos\", 2, \"set begin and end position (default: show whole strands)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"l\", \"lines\", 2, \"set first and last line of the alignment (default: show whole alignment)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"a\", \"ascii\", \"output alignment in ASCII format instead of SVG\", OptionType::Bool | OptionType::Label));\r\n\trequiredArguments(parser, 2);\r\n\r\n\tbool stop = !parse(parser, argc, argv, std::cerr);\r\n\tif (stop) return 0;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Extract and check options\t\r\n\tString<unsigned> contigs;\r\n\tTContigPos left = 0;\r\n\tTContigPos right = SupremumValue<TContigPos>::VALUE;\r\n\tunsigned firstLine = 0;\r\n\tunsigned lastLine = SupremumValue<unsigned>::VALUE;\r\n\tbool inASCII = false;\r\n\t\r\n\tif (isSetLong(parser, \"pos\"))\r\n\t{\r\n\t\t__int64 l = 0, r = 0;\r\n\t\tgetOptionValueLong(parser, \"pos\", 0, l);\r\n\t\tgetOptionValueLong(parser, \"pos\", 1, r);\r\n\t\tif ((l >= r) && (stop = true))\r\n\t\t\tstd::cerr << \"Begin position must be less than end position.\" << std::endl;\r\n\t\tleft = l;\r\n\t\tright = r;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"lines\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"lines\", 0, firstLine);\r\n\t\tgetOptionValueLong(parser, \"lines\", 1, lastLine);\r\n\t\tif ((firstLine >= lastLine) && (stop = true))\r\n\t\t\tstd::cerr << \"First line must be less or equal than last line.\" << std::endl;\r\n\t}\r\n\r\n\tTFragStore store;\r\n\tstd::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);\r\n\tstd::ofstream ascii;\r\n\tSVGFile svg;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome file\r\n\tuint outArgNo = 1;\r\n\tif (argumentCount(parser) > 2)\r\n\t{\r\n\t\tif (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))\r\n\t\t\tstd::cerr << \"Failed to load genome.\" << std::endl;\r\n\t\t++outArgNo;\r\n\t}\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Load SAM file\r\n\tif (!stop) read(samFile, store, SAM());\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Choose contigs\r\n\tif (isSetLong(parser, \"contig\"))\r\n\t{\r\n\t\tresize(contigs, length(getOptionValuesLong(parser, \"contig\")));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tgetOptionValueLong(parser, \"contig\", i, contigs[i]);\r\n\t} else {\r\n\t\tresize(contigs, length(store.contigStore));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tcontigs[i] = i;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"ascii\"))\r\n\t\tinASCII = true;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome and open SVG file for writing\r\n\tif (!stop)\r\n\t{\r\n\t\tif (inASCII)\r\n\t\t{\r\n\t\t\tascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);\r\n\t\t\tif (!ascii.is_open()) stop = true;\r\n\t\t} else\r\n\t\t\tif (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;\r\n\t\t\r\n\t\tif (stop) std::cerr << \"Failed to open output file for writing.\" << std::endl;\r\n\t}\r\n\t\r\n\t\/\/ something went wrong\r\n\tif (stop)\r\n\t{\r\n\t\tstd::cerr << \"Exiting ...\" << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tfor(unsigned o=0;o<length(store.contigStore);++o)\r\n\tstd::cerr<<store.contigNameStore[o]<<std::endl;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Output alignment\r\n\tAlignedReadLayout layout;\r\n\tstd::cout << \"Layouting reads ... \" << std::flush;\r\n\tlayoutAlignment(layout, store);\r\n\tstd::cout << \"done\" << std::endl;\r\n\r\n\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\tif (i < length(store.contigStore))\r\n\t\t{\r\n\t\t\tstd::cout << \"Writing contig \" << contigs[i] << \" ... \" << std::flush;\r\n\t\t\tTContigPos right_ = right;\r\n\t\t\tif (right_ == SupremumValue<TContigPos>::VALUE)\r\n\t\t\t{\r\n\t\t\t\tright_ = 0;\r\n\t\t\t\tfor (unsigned j = 0; j < length(layout.contigRows[i]); ++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned id = back(layout.contigRows[i][j]);\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].beginPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].beginPos;\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].endPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].endPos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstd::cout << left<<'\\t'<<right_<<'\\t'<<firstLine<<'\\t'<<lastLine<<std::endl;\r\n\t\t\tif (inASCII)\r\n\t\t\t\tprintAlignment(ascii, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);\r\n\t\t\telse\r\n\t\t\t\tprintAlignment(svg, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);\r\n\t\t\t\r\n\t\t\tstd::cout << \"done\" << std::endl;\r\n\t\t}\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>fixed compilation bug<commit_after>\/\/\/A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n\r\n#include <seqan\/store.h>\r\n#include <seqan\/misc\/misc_cmdparser.h>\r\n#include <seqan\/misc\/misc_svg.h>\r\n\r\nusing namespace seqan;\r\n\r\nint main(int argc, const char *argv[])\r\n{\r\n\ttypedef FragmentStore<> TFragStore;\r\n\ttypedef TFragStore::TContigPos TContigPos;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Define options\r\n\tCommandLineParser parser;\r\n\taddUsageLine(parser, \"[OPTION]... <SAM file> <SVG file>\");\r\n\taddUsageLine(parser, \"[OPTION]... <SAM file> <GENOME file> <SVG file>\");\r\n\r\n\taddOption(parser, CommandLineOption(\"c\", \"contig\", \"display only contig #NUM (default: show all contigs)\", OptionType::Int | OptionType::Label | OptionType::List));\r\n\taddOption(parser, CommandLineOption(\"p\", \"pos\", 2, \"set begin and end position (default: show whole strands)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"l\", \"lines\", 2, \"set first and last line of the alignment (default: show whole alignment)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"a\", \"ascii\", \"output alignment in ASCII format instead of SVG\", OptionType::Bool | OptionType::Label));\r\n\trequiredArguments(parser, 2);\r\n\r\n\tbool stop = !parse(parser, argc, argv, std::cerr);\r\n\tif (stop) return 0;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Extract and check options\r\n\tString<unsigned> contigs;\r\n\tTContigPos left = 0;\r\n\tTContigPos right = SupremumValue<TContigPos>::VALUE;\r\n\tunsigned firstLine = 0;\r\n\tunsigned lastLine = SupremumValue<unsigned>::VALUE;\r\n\tbool inASCII = false;\r\n\r\n\tif (isSetLong(parser, \"pos\"))\r\n\t{\r\n\t\t__int64 l = 0, r = 0;\r\n\t\tgetOptionValueLong(parser, \"pos\", 0, l);\r\n\t\tgetOptionValueLong(parser, \"pos\", 1, r);\r\n\t\tif ((l >= r) && (stop = true))\r\n\t\t\tstd::cerr << \"Begin position must be less than end position.\" << std::endl;\r\n\t\tleft = l;\r\n\t\tright = r;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"lines\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"lines\", 0, firstLine);\r\n\t\tgetOptionValueLong(parser, \"lines\", 1, lastLine);\r\n\t\tif ((firstLine >= lastLine) && (stop = true))\r\n\t\t\tstd::cerr << \"First line must be less or equal than last line.\" << std::endl;\r\n\t}\r\n\r\n\tTFragStore store;\r\n\tstd::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);\r\n\tstd::ofstream ascii;\r\n\tSVGFile svg;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome file\r\n\tunsigned outArgNo = 1;\r\n\tif (argumentCount(parser) > 2)\r\n\t{\r\n\t\tif (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))\r\n\t\t\tstd::cerr << \"Failed to load genome.\" << std::endl;\r\n\t\t++outArgNo;\r\n\t}\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Load SAM file\r\n\tif (!stop) read(samFile, store, SAM());\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Choose contigs\r\n\tif (isSetLong(parser, \"contig\"))\r\n\t{\r\n\t\tresize(contigs, length(getOptionValuesLong(parser, \"contig\")));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tgetOptionValueLong(parser, \"contig\", i, contigs[i]);\r\n\t} else {\r\n\t\tresize(contigs, length(store.contigStore));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tcontigs[i] = i;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"ascii\"))\r\n\t\tinASCII = true;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome and open SVG file for writing\r\n\tif (!stop)\r\n\t{\r\n\t\tif (inASCII)\r\n\t\t{\r\n\t\t\tascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);\r\n\t\t\tif (!ascii.is_open()) stop = true;\r\n\t\t} else\r\n\t\t\tif (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;\r\n\r\n\t\tif (stop) std::cerr << \"Failed to open output file for writing.\" << std::endl;\r\n\t}\r\n\r\n\t\/\/ something went wrong\r\n\tif (stop)\r\n\t{\r\n\t\tstd::cerr << \"Exiting ...\" << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tfor(unsigned o=0;o<length(store.contigStore);++o)\r\n\tstd::cerr<<store.contigNameStore[o]<<std::endl;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Output alignment\r\n\tAlignedReadLayout layout;\r\n\tstd::cout << \"Layouting reads ... \" << std::flush;\r\n\tlayoutAlignment(layout, store);\r\n\tstd::cout << \"done\" << std::endl;\r\n\r\n\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\tif (i < length(store.contigStore))\r\n\t\t{\r\n\t\t\tstd::cout << \"Writing contig \" << contigs[i] << \" ... \" << std::flush;\r\n\t\t\tTContigPos right_ = right;\r\n\t\t\tif (right_ == SupremumValue<TContigPos>::VALUE)\r\n\t\t\t{\r\n\t\t\t\tright_ = 0;\r\n\t\t\t\tfor (unsigned j = 0; j < length(layout.contigRows[i]); ++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned id = back(layout.contigRows[i][j]);\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].beginPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].beginPos;\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].endPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].endPos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstd::cout << left<<'\\t'<<right_<<'\\t'<<firstLine<<'\\t'<<lastLine<<std::endl;\r\n\t\t\tif (inASCII)\r\n\t\t\t\tprintAlignment(ascii, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);\r\n\t\t\telse\r\n\t\t\t\tprintAlignment(svg, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);\r\n\r\n\t\t\tstd::cout << \"done\" << std::endl;\r\n\t\t}\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * OlaServer.cpp\n * OlaServer is the main OLA Server class\n * Copyright (C) 2005-2008 Simon Newton\n *\/\n\n#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <errno.h>\n#include <signal.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include <vector>\n\n#include \"ola\/network\/Socket.h\"\n#include \"common\/protocol\/Ola.pb.h\"\n#include \"common\/rpc\/StreamRpcChannel.h\"\n#include \"ola\/BaseTypes.h\"\n#include \"ola\/ExportMap.h\"\n#include \"ola\/Logging.h\"\n#include \"ola\/network\/InterfacePicker.h\"\n#include \"ola\/rdm\/UID.h\"\n#include \"olad\/Client.h\"\n#include \"olad\/DeviceManager.h\"\n#include \"olad\/ClientBroker.h\"\n#include \"olad\/OlaServer.h\"\n#include \"olad\/OlaServerServiceImpl.h\"\n#include \"olad\/Plugin.h\"\n#include \"olad\/PluginAdaptor.h\"\n#include \"olad\/PluginManager.h\"\n#include \"olad\/Port.h\"\n#include \"olad\/PortBroker.h\"\n#include \"olad\/PortManager.h\"\n#include \"olad\/Preferences.h\"\n#include \"olad\/Universe.h\"\n#include \"olad\/UniverseStore.h\"\n\n#ifdef HAVE_LIBMICROHTTPD\n#include \"olad\/OlaHttpServer.h\"\n#endif\n\nnamespace ola {\n\nusing ola::rpc::StreamRpcChannel;\nusing std::pair;\n\nconst char OlaServer::UNIVERSE_PREFERENCES[] = \"universe\";\nconst char OlaServer::K_CLIENT_VAR[] = \"clients-connected\";\nconst char OlaServer::K_UID_VAR[] = \"server-uid\";\nconst unsigned int OlaServer::K_HOUSEKEEPING_TIMEOUT_MS = 10000;\n\n\n\/*\n * Create a new OlaServer\n * @param factory the factory to use to create OlaService objects\n * @param m_plugin_loader the loader to use for the plugins\n * @param socket the socket to listen on for new connections\n *\/\nOlaServer::OlaServer(OlaClientServiceFactory *factory,\n const vector<PluginLoader*> &plugin_loaders,\n PreferencesFactory *preferences_factory,\n ola::network::SelectServer *select_server,\n ola_server_options *ola_options,\n ola::network::AcceptingSocket *socket,\n ExportMap *export_map)\n : m_service_factory(factory),\n m_plugin_loaders(plugin_loaders),\n m_ss(select_server),\n m_accepting_socket(socket),\n m_device_manager(NULL),\n m_plugin_manager(NULL),\n m_plugin_adaptor(NULL),\n m_preferences_factory(preferences_factory),\n m_universe_preferences(NULL),\n m_universe_store(NULL),\n m_export_map(export_map),\n m_port_manager(NULL),\n m_service_impl(NULL),\n m_broker(NULL),\n m_port_broker(NULL),\n m_reload_plugins(false),\n m_init_run(false),\n m_free_export_map(false),\n m_housekeeping_timeout(ola::network::INVALID_TIMEOUT),\n m_httpd(NULL),\n m_options(*ola_options),\n m_default_uid(OPEN_LIGHTING_ESTA_CODE, 0) {\n if (!m_export_map) {\n m_export_map = new ExportMap();\n m_free_export_map = true;\n }\n\n if (!m_options.http_port)\n m_options.http_port = DEFAULT_HTTP_PORT;\n\n m_export_map->GetIntegerVar(K_CLIENT_VAR);\n}\n\n\n\/*\n * Shutdown the server\n *\/\nOlaServer::~OlaServer() {\n#ifdef HAVE_LIBMICROHTTPD\n if (m_httpd) {\n m_httpd->Stop();\n delete m_httpd;\n m_httpd = NULL;\n }\n#endif\n\n if (m_housekeeping_timeout != ola::network::INVALID_TIMEOUT)\n m_ss->RemoveTimeout(m_housekeeping_timeout);\n\n StopPlugins();\n\n map<int, OlaClientService*>::iterator iter;\n for (iter = m_sd_to_service.begin(); iter != m_sd_to_service.end(); ++iter) {\n CleanupConnection(iter->second);\n \/\/ TODO(simon): close the socket here\n\n \/*Socket *socket = ;\n m_ss->RemoveReadDescriptor(socket);\n socket->Close();\n *\/\n }\n\n if (m_broker)\n delete m_broker;\n\n if (m_port_broker)\n delete m_port_broker;\n\n if (m_accepting_socket &&\n m_accepting_socket->ValidReadDescriptor())\n m_ss->RemoveReadDescriptor(m_accepting_socket);\n\n if (m_universe_store) {\n m_universe_store->DeleteAll();\n delete m_universe_store;\n }\n\n if (m_universe_preferences) {\n m_universe_preferences->Save();\n }\n\n delete m_port_manager;\n delete m_plugin_adaptor;\n delete m_device_manager;\n delete m_plugin_manager;\n delete m_service_impl;\n\n if (m_free_export_map)\n delete m_export_map;\n}\n\n\n\/*\n * Initialise the server\n * * @return true on success, false on failure\n *\/\nbool OlaServer::Init() {\n if (m_init_run)\n return false;\n\n if (!m_service_factory || !m_ss)\n return false;\n\n \/\/ TODO(simon): run without preferences & PluginLoader\n if (m_plugin_loaders.empty() || !m_preferences_factory)\n return false;\n\n if (m_accepting_socket) {\n if (!m_accepting_socket->Listen()) {\n OLA_FATAL << \"Could not listen on the RPC port, you probably have \" <<\n \"another instance of olad running\";\n return false;\n }\n m_accepting_socket->SetOnAccept(\n ola::NewCallback(this, &OlaServer::NewConnection));\n m_ss->AddReadDescriptor(m_accepting_socket);\n }\n\n#ifndef WIN32\n signal(SIGPIPE, SIG_IGN);\n#endif\n\n \/\/ fetch the interface info\n ola::network::Interface iface;\n ola::network::InterfacePicker *picker =\n ola::network::InterfacePicker::NewPicker();\n if (!picker->ChooseInterface(&iface, \"\")) {\n OLA_WARN << \"No network interface found\";\n } else {\n \/\/ default to using the ip as a id\n m_default_uid = ola::rdm::UID(OPEN_LIGHTING_ESTA_CODE,\n iface.ip_address.AsInt());\n }\n delete picker;\n m_export_map->GetStringVar(K_UID_VAR)->Set(m_default_uid.ToString());\n OLA_INFO << \"Server UID is \" << m_default_uid;\n\n m_universe_preferences = m_preferences_factory->NewPreference(\n UNIVERSE_PREFERENCES);\n m_universe_preferences->Load();\n m_universe_store = new UniverseStore(m_universe_preferences, m_export_map);\n\n m_port_broker = new PortBroker();\n m_port_manager = new PortManager(m_universe_store, m_port_broker);\n m_broker = new ClientBroker();\n\n \/\/ setup the objects\n m_device_manager = new DeviceManager(m_preferences_factory, m_port_manager);\n m_plugin_adaptor = new PluginAdaptor(m_device_manager,\n m_ss,\n m_preferences_factory,\n m_port_broker);\n\n m_plugin_manager = new PluginManager(m_plugin_loaders, m_plugin_adaptor);\n m_service_impl = new OlaServerServiceImpl(\n m_universe_store,\n m_device_manager,\n m_plugin_manager,\n m_export_map,\n m_port_manager,\n m_broker,\n m_ss->WakeUpTime(),\n m_default_uid);\n\n if (!m_port_broker || !m_universe_store || !m_device_manager ||\n !m_plugin_adaptor || !m_port_manager || !m_plugin_manager || !m_broker ||\n !m_service_impl) {\n delete m_plugin_adaptor;\n delete m_device_manager;\n delete m_port_manager;\n delete m_universe_store;\n delete m_plugin_manager;\n return false;\n }\n\n m_plugin_manager->LoadAll();\n\n#ifdef HAVE_LIBMICROHTTPD\n if (!StartHttpServer(iface))\n OLA_WARN << \"Failed to start the HTTP server.\";\n#endif\n\n m_housekeeping_timeout = m_ss->RegisterRepeatingTimeout(\n K_HOUSEKEEPING_TIMEOUT_MS,\n ola::NewCallback(this, &OlaServer::RunHousekeeping));\n m_ss->RunInLoop(ola::NewCallback(this, &OlaServer::CheckForReload));\n\n m_init_run = true;\n return true;\n}\n\n\n\/*\n * Reload all plugins, this can be called from a separate thread or in an\n * interrupt handler.\n *\/\nvoid OlaServer::ReloadPlugins() {\n m_reload_plugins = true;\n}\n\n\n\/*\n * Add a new ConnectedDescriptor to this Server.\n * @param socket the new ConnectedDescriptor\n *\/\nvoid OlaServer::NewConnection(ola::network::ConnectedDescriptor *socket) {\n if (!socket)\n return;\n\n StreamRpcChannel *channel = new StreamRpcChannel(NULL, socket, m_export_map);\n socket->SetOnClose(NewSingleCallback(this, &OlaServer::SocketClosed, socket));\n OlaClientService_Stub *stub = new OlaClientService_Stub(channel);\n Client *client = new Client(stub);\n OlaClientService *service = m_service_factory->New(client, m_service_impl);\n m_broker->AddClient(client);\n channel->SetService(service);\n\n map<int, OlaClientService*>::const_iterator iter;\n iter = m_sd_to_service.find(socket->ReadDescriptor());\n\n if (iter != m_sd_to_service.end())\n OLA_INFO << \"New socket but the client already exists!\";\n\n pair<int, OlaClientService*> pair(socket->ReadDescriptor(), service);\n m_sd_to_service.insert(pair);\n\n \/\/ This hands off ownership to the select server\n m_ss->AddReadDescriptor(socket, true);\n (*m_export_map->GetIntegerVar(K_CLIENT_VAR))++;\n}\n\n\n\/*\n * Called when a socket is closed\n *\/\nvoid OlaServer::SocketClosed(ola::network::ConnectedDescriptor *socket) {\n map<int, OlaClientService*>::iterator iter;\n iter = m_sd_to_service.find(socket->ReadDescriptor());\n\n if (iter == m_sd_to_service.end())\n OLA_INFO << \"A socket was closed but we didn't find the client\";\n\n (*m_export_map->GetIntegerVar(K_CLIENT_VAR))--;\n CleanupConnection(iter->second);\n m_sd_to_service.erase(iter);\n}\n\n\n\/*\n * Run the garbage collector\n *\/\nbool OlaServer::RunHousekeeping() {\n OLA_DEBUG << \"Garbage collecting\";\n m_universe_store->GarbageCollectUniverses();\n return true;\n}\n\n\n\/*\n * Called once per loop iteration\n *\/\nvoid OlaServer::CheckForReload() {\n if (m_reload_plugins) {\n m_reload_plugins = false;\n OLA_INFO << \"Reloading plugins\";\n StopPlugins();\n m_plugin_manager->LoadAll();\n }\n}\n\n\n\/*\n * Setup the HTTP server if required.\n * @param interface the primary interface that the server is using.\n *\/\n#ifdef HAVE_LIBMICROHTTPD\nbool OlaServer::StartHttpServer(const ola::network::Interface &iface) {\n if (!m_options.http_enable)\n return true;\n\n \/\/ create a pipe socket for the http server to communicate with the main\n \/\/ server on.\n ola::network::PipeDescriptor *pipe_descriptor =\n new ola::network::PipeDescriptor();\n if (!pipe_descriptor->Init()) {\n delete pipe_descriptor;\n return false;\n }\n\n \/\/ ownership of the pipe_descriptor is transferred here.\n m_httpd = new OlaHttpServer(m_export_map,\n pipe_descriptor->OppositeEnd(),\n this,\n m_options.http_port,\n m_options.http_enable_quit,\n m_options.http_data_dir,\n iface);\n\n if (m_httpd->Init()) {\n m_httpd->Start();\n \/\/ register the pipe descriptor as a client\n NewConnection(pipe_descriptor);\n return true;\n } else {\n pipe_descriptor->Close();\n delete pipe_descriptor;\n delete m_httpd;\n m_httpd = NULL;\n return false;\n }\n}\n#endif\n\n\n\/*\n * Stop and unload all the plugins\n *\/\nvoid OlaServer::StopPlugins() {\n if (m_plugin_manager)\n m_plugin_manager->UnloadAll();\n if (m_device_manager) {\n if (m_device_manager->DeviceCount()) {\n OLA_WARN << \"Some devices failed to unload, we're probably leaking \"\n << \"memory now\";\n }\n m_device_manager->UnregisterAllDevices();\n }\n}\n\n\n\/*\n * Cleanup everything related to a client connection\n *\/\nvoid OlaServer::CleanupConnection(OlaClientService *service) {\n Client *client = service->GetClient();\n m_broker->RemoveClient(client);\n\n vector<Universe*> universe_list;\n m_universe_store->GetList(&universe_list);\n vector<Universe*>::iterator uni_iter;\n\n \/\/ O(universes * clients). Clean this up sometime.\n for (uni_iter = universe_list.begin();\n uni_iter != universe_list.end();\n ++uni_iter) {\n (*uni_iter)->RemoveSourceClient(client);\n (*uni_iter)->RemoveSinkClient(client);\n }\n delete client->Stub()->channel();\n delete client->Stub();\n delete client;\n delete service;\n}\n} \/\/ ola\n<commit_msg> * server: load plugins in the main loop<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * OlaServer.cpp\n * OlaServer is the main OLA Server class\n * Copyright (C) 2005-2008 Simon Newton\n *\/\n\n#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <errno.h>\n#include <signal.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include <vector>\n\n#include \"ola\/network\/Socket.h\"\n#include \"common\/protocol\/Ola.pb.h\"\n#include \"common\/rpc\/StreamRpcChannel.h\"\n#include \"ola\/BaseTypes.h\"\n#include \"ola\/ExportMap.h\"\n#include \"ola\/Logging.h\"\n#include \"ola\/network\/InterfacePicker.h\"\n#include \"ola\/rdm\/UID.h\"\n#include \"olad\/Client.h\"\n#include \"olad\/DeviceManager.h\"\n#include \"olad\/ClientBroker.h\"\n#include \"olad\/OlaServer.h\"\n#include \"olad\/OlaServerServiceImpl.h\"\n#include \"olad\/Plugin.h\"\n#include \"olad\/PluginAdaptor.h\"\n#include \"olad\/PluginManager.h\"\n#include \"olad\/Port.h\"\n#include \"olad\/PortBroker.h\"\n#include \"olad\/PortManager.h\"\n#include \"olad\/Preferences.h\"\n#include \"olad\/Universe.h\"\n#include \"olad\/UniverseStore.h\"\n\n#ifdef HAVE_LIBMICROHTTPD\n#include \"olad\/OlaHttpServer.h\"\n#endif\n\nnamespace ola {\n\nusing ola::rpc::StreamRpcChannel;\nusing std::pair;\n\nconst char OlaServer::UNIVERSE_PREFERENCES[] = \"universe\";\nconst char OlaServer::K_CLIENT_VAR[] = \"clients-connected\";\nconst char OlaServer::K_UID_VAR[] = \"server-uid\";\nconst unsigned int OlaServer::K_HOUSEKEEPING_TIMEOUT_MS = 10000;\n\n\n\/*\n * Create a new OlaServer\n * @param factory the factory to use to create OlaService objects\n * @param m_plugin_loader the loader to use for the plugins\n * @param socket the socket to listen on for new connections\n *\/\nOlaServer::OlaServer(OlaClientServiceFactory *factory,\n const vector<PluginLoader*> &plugin_loaders,\n PreferencesFactory *preferences_factory,\n ola::network::SelectServer *select_server,\n ola_server_options *ola_options,\n ola::network::AcceptingSocket *socket,\n ExportMap *export_map)\n : m_service_factory(factory),\n m_plugin_loaders(plugin_loaders),\n m_ss(select_server),\n m_accepting_socket(socket),\n m_device_manager(NULL),\n m_plugin_manager(NULL),\n m_plugin_adaptor(NULL),\n m_preferences_factory(preferences_factory),\n m_universe_preferences(NULL),\n m_universe_store(NULL),\n m_export_map(export_map),\n m_port_manager(NULL),\n m_service_impl(NULL),\n m_broker(NULL),\n m_port_broker(NULL),\n m_reload_plugins(false),\n m_init_run(false),\n m_free_export_map(false),\n m_housekeeping_timeout(ola::network::INVALID_TIMEOUT),\n m_httpd(NULL),\n m_options(*ola_options),\n m_default_uid(OPEN_LIGHTING_ESTA_CODE, 0) {\n if (!m_export_map) {\n m_export_map = new ExportMap();\n m_free_export_map = true;\n }\n\n if (!m_options.http_port)\n m_options.http_port = DEFAULT_HTTP_PORT;\n\n m_export_map->GetIntegerVar(K_CLIENT_VAR);\n}\n\n\n\/*\n * Shutdown the server\n *\/\nOlaServer::~OlaServer() {\n#ifdef HAVE_LIBMICROHTTPD\n if (m_httpd) {\n m_httpd->Stop();\n delete m_httpd;\n m_httpd = NULL;\n }\n#endif\n\n if (m_housekeeping_timeout != ola::network::INVALID_TIMEOUT)\n m_ss->RemoveTimeout(m_housekeeping_timeout);\n\n StopPlugins();\n\n map<int, OlaClientService*>::iterator iter;\n for (iter = m_sd_to_service.begin(); iter != m_sd_to_service.end(); ++iter) {\n CleanupConnection(iter->second);\n \/\/ TODO(simon): close the socket here\n\n \/*Socket *socket = ;\n m_ss->RemoveReadDescriptor(socket);\n socket->Close();\n *\/\n }\n\n if (m_broker)\n delete m_broker;\n\n if (m_port_broker)\n delete m_port_broker;\n\n if (m_accepting_socket &&\n m_accepting_socket->ValidReadDescriptor())\n m_ss->RemoveReadDescriptor(m_accepting_socket);\n\n if (m_universe_store) {\n m_universe_store->DeleteAll();\n delete m_universe_store;\n }\n\n if (m_universe_preferences) {\n m_universe_preferences->Save();\n }\n\n delete m_port_manager;\n delete m_plugin_adaptor;\n delete m_device_manager;\n delete m_plugin_manager;\n delete m_service_impl;\n\n if (m_free_export_map)\n delete m_export_map;\n}\n\n\n\/*\n * Initialise the server\n * * @return true on success, false on failure\n *\/\nbool OlaServer::Init() {\n if (m_init_run)\n return false;\n\n if (!m_service_factory || !m_ss)\n return false;\n\n \/\/ TODO(simon): run without preferences & PluginLoader\n if (m_plugin_loaders.empty() || !m_preferences_factory)\n return false;\n\n if (m_accepting_socket) {\n if (!m_accepting_socket->Listen()) {\n OLA_FATAL << \"Could not listen on the RPC port, you probably have \" <<\n \"another instance of olad running\";\n return false;\n }\n m_accepting_socket->SetOnAccept(\n ola::NewCallback(this, &OlaServer::NewConnection));\n m_ss->AddReadDescriptor(m_accepting_socket);\n }\n\n#ifndef WIN32\n signal(SIGPIPE, SIG_IGN);\n#endif\n\n \/\/ fetch the interface info\n ola::network::Interface iface;\n ola::network::InterfacePicker *picker =\n ola::network::InterfacePicker::NewPicker();\n if (!picker->ChooseInterface(&iface, \"\")) {\n OLA_WARN << \"No network interface found\";\n } else {\n \/\/ default to using the ip as a id\n m_default_uid = ola::rdm::UID(OPEN_LIGHTING_ESTA_CODE,\n iface.ip_address.AsInt());\n }\n delete picker;\n m_export_map->GetStringVar(K_UID_VAR)->Set(m_default_uid.ToString());\n OLA_INFO << \"Server UID is \" << m_default_uid;\n\n m_universe_preferences = m_preferences_factory->NewPreference(\n UNIVERSE_PREFERENCES);\n m_universe_preferences->Load();\n m_universe_store = new UniverseStore(m_universe_preferences, m_export_map);\n\n m_port_broker = new PortBroker();\n m_port_manager = new PortManager(m_universe_store, m_port_broker);\n m_broker = new ClientBroker();\n\n \/\/ setup the objects\n m_device_manager = new DeviceManager(m_preferences_factory, m_port_manager);\n m_plugin_adaptor = new PluginAdaptor(m_device_manager,\n m_ss,\n m_preferences_factory,\n m_port_broker);\n\n m_plugin_manager = new PluginManager(m_plugin_loaders, m_plugin_adaptor);\n m_service_impl = new OlaServerServiceImpl(\n m_universe_store,\n m_device_manager,\n m_plugin_manager,\n m_export_map,\n m_port_manager,\n m_broker,\n m_ss->WakeUpTime(),\n m_default_uid);\n\n if (!m_port_broker || !m_universe_store || !m_device_manager ||\n !m_plugin_adaptor || !m_port_manager || !m_plugin_manager || !m_broker ||\n !m_service_impl) {\n delete m_plugin_adaptor;\n delete m_device_manager;\n delete m_port_manager;\n delete m_universe_store;\n delete m_plugin_manager;\n return false;\n }\n\n \/\/ The plugin load procedure can take a while so we run it in the main loop.\n m_ss->Execute(\n ola::NewCallback(m_plugin_manager, &PluginManager::LoadAll));\n\n#ifdef HAVE_LIBMICROHTTPD\n if (!StartHttpServer(iface))\n OLA_WARN << \"Failed to start the HTTP server.\";\n#endif\n\n m_housekeeping_timeout = m_ss->RegisterRepeatingTimeout(\n K_HOUSEKEEPING_TIMEOUT_MS,\n ola::NewCallback(this, &OlaServer::RunHousekeeping));\n m_ss->RunInLoop(ola::NewCallback(this, &OlaServer::CheckForReload));\n\n m_init_run = true;\n return true;\n}\n\n\n\/*\n * Reload all plugins, this can be called from a separate thread or in an\n * interrupt handler.\n *\/\nvoid OlaServer::ReloadPlugins() {\n m_reload_plugins = true;\n}\n\n\n\/*\n * Add a new ConnectedDescriptor to this Server.\n * @param socket the new ConnectedDescriptor\n *\/\nvoid OlaServer::NewConnection(ola::network::ConnectedDescriptor *socket) {\n if (!socket)\n return;\n\n StreamRpcChannel *channel = new StreamRpcChannel(NULL, socket, m_export_map);\n socket->SetOnClose(NewSingleCallback(this, &OlaServer::SocketClosed, socket));\n OlaClientService_Stub *stub = new OlaClientService_Stub(channel);\n Client *client = new Client(stub);\n OlaClientService *service = m_service_factory->New(client, m_service_impl);\n m_broker->AddClient(client);\n channel->SetService(service);\n\n map<int, OlaClientService*>::const_iterator iter;\n iter = m_sd_to_service.find(socket->ReadDescriptor());\n\n if (iter != m_sd_to_service.end())\n OLA_INFO << \"New socket but the client already exists!\";\n\n pair<int, OlaClientService*> pair(socket->ReadDescriptor(), service);\n m_sd_to_service.insert(pair);\n\n \/\/ This hands off ownership to the select server\n m_ss->AddReadDescriptor(socket, true);\n (*m_export_map->GetIntegerVar(K_CLIENT_VAR))++;\n}\n\n\n\/*\n * Called when a socket is closed\n *\/\nvoid OlaServer::SocketClosed(ola::network::ConnectedDescriptor *socket) {\n map<int, OlaClientService*>::iterator iter;\n iter = m_sd_to_service.find(socket->ReadDescriptor());\n\n if (iter == m_sd_to_service.end())\n OLA_INFO << \"A socket was closed but we didn't find the client\";\n\n (*m_export_map->GetIntegerVar(K_CLIENT_VAR))--;\n CleanupConnection(iter->second);\n m_sd_to_service.erase(iter);\n}\n\n\n\/*\n * Run the garbage collector\n *\/\nbool OlaServer::RunHousekeeping() {\n OLA_DEBUG << \"Garbage collecting\";\n m_universe_store->GarbageCollectUniverses();\n return true;\n}\n\n\n\/*\n * Called once per loop iteration\n *\/\nvoid OlaServer::CheckForReload() {\n if (m_reload_plugins) {\n m_reload_plugins = false;\n OLA_INFO << \"Reloading plugins\";\n StopPlugins();\n m_plugin_manager->LoadAll();\n }\n}\n\n\n\/*\n * Setup the HTTP server if required.\n * @param interface the primary interface that the server is using.\n *\/\n#ifdef HAVE_LIBMICROHTTPD\nbool OlaServer::StartHttpServer(const ola::network::Interface &iface) {\n if (!m_options.http_enable)\n return true;\n\n \/\/ create a pipe socket for the http server to communicate with the main\n \/\/ server on.\n ola::network::PipeDescriptor *pipe_descriptor =\n new ola::network::PipeDescriptor();\n if (!pipe_descriptor->Init()) {\n delete pipe_descriptor;\n return false;\n }\n\n \/\/ ownership of the pipe_descriptor is transferred here.\n m_httpd = new OlaHttpServer(m_export_map,\n pipe_descriptor->OppositeEnd(),\n this,\n m_options.http_port,\n m_options.http_enable_quit,\n m_options.http_data_dir,\n iface);\n\n if (m_httpd->Init()) {\n m_httpd->Start();\n \/\/ register the pipe descriptor as a client\n NewConnection(pipe_descriptor);\n return true;\n } else {\n pipe_descriptor->Close();\n delete pipe_descriptor;\n delete m_httpd;\n m_httpd = NULL;\n return false;\n }\n}\n#endif\n\n\n\/*\n * Stop and unload all the plugins\n *\/\nvoid OlaServer::StopPlugins() {\n if (m_plugin_manager)\n m_plugin_manager->UnloadAll();\n if (m_device_manager) {\n if (m_device_manager->DeviceCount()) {\n OLA_WARN << \"Some devices failed to unload, we're probably leaking \"\n << \"memory now\";\n }\n m_device_manager->UnregisterAllDevices();\n }\n}\n\n\n\/*\n * Cleanup everything related to a client connection\n *\/\nvoid OlaServer::CleanupConnection(OlaClientService *service) {\n Client *client = service->GetClient();\n m_broker->RemoveClient(client);\n\n vector<Universe*> universe_list;\n m_universe_store->GetList(&universe_list);\n vector<Universe*>::iterator uni_iter;\n\n \/\/ O(universes * clients). Clean this up sometime.\n for (uni_iter = universe_list.begin();\n uni_iter != universe_list.end();\n ++uni_iter) {\n (*uni_iter)->RemoveSourceClient(client);\n (*uni_iter)->RemoveSinkClient(client);\n }\n delete client->Stub()->channel();\n delete client->Stub();\n delete client;\n delete service;\n}\n} \/\/ ola\n<|endoftext|>"} {"text":"<commit_before>\n#include \"api\/constants.hpp\"\n#include \"api\/IBuffer.hpp\"\n#include \"api\/IRequest.hpp\"\n#include \"api\/IModuleManager.hpp\"\n#include \"api\/IModule.hpp\"\n#include \"utils\/Path.hpp\"\n#include \"utils\/Logger.hpp\"\n#include \"utils\/macros.hpp\"\n#include \"config.hpp\"\n\n#include \"DirListing.hpp\"\n\nusing namespace zhttpd;\nusing namespace zhttpd::mod;\n\nDirListing::DirListing(api::IModuleManager*)\n{\n}\n\nDirListing::~DirListing()\n{\n}\n\nbool DirListing::processRequest(api::event::Type event, api::IRequest* request, api::IBuffer*)\n{\n if (event == api::event::ON_END)\n {\n Path dir(request->getFilePath());\n std::list<std::string> files = dir.getDirectoryContent();\n std::string slash(\"\/\");\n std::string const& path = request->getRequestQuery(); \/\/ XXX stop at '?' or '#'\n if (path == \"\/\")\n slash.clear();\n std::string out =\n \"<!DOCTYPE html PUBLIC \\\"-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN\" \"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd\\\">\\n\"\n \"<html xmlns=\\\"http:\/\/www.w3.org\/1999\/xhtml\\\" xml:lang=\\\"fr\\\">\\n\"\n \"<head>\\n\"\n \"<title>Index of \" + path + \"<\/title>\\n\"\n \"<style type=\\\"text\/css\\\">\\n\"\n \"body { font-family: Verdana; font-size: 13px; }\\n\"\n \"a:link { color: #c00; text-decoration: none; }\\n\"\n \"a:hover, a:active, a:focus { color: #c00; background-color: #ccc; text-decoration: none; }\\n\"\n \"a:visited { color: #c00; text-decoration: underline; }\\n\"\n \"<\/style>\\n\"\n \"<\/head>\\n\"\n \"<body>\\n\"\n \"<h3> Index of \" + path + \"<\/h3>\\n\"\n \"<hr \/>\\n\"\n \"<ul>\\n\"\n \"<li><a href=\\\"\" + path + slash + \"..\/\\\">..<\/a><\/li>\";\n\n std::list<std::string>::const_iterator it = files.begin();\n std::list<std::string>::const_iterator itEnd = files.end();\n for (; it != itEnd; ++it)\n out += \"<li><a href=\\\"\" + path + slash + *it + \"\\\">\" + *it + \"<\/a><\/li>\\n\"; \/\/ XXX replace '\"' in path !\n\n out += \"<\/ul>\\n\"\n \"<hr \/>\\n\"\n \"<p>\"\n ZHTTPD_FULLNAME\n \"<\/p>\\n\"\n \"<\/body>\\n\"\n \"<\/html>\";\n request->giveData(request->getBufferManager().allocate(out.data(), out.size()));\n request->raiseEnd();\n return true;\n }\n return false;\n}\n\n<commit_msg>dirlisting send html5 now<commit_after>\n#include \"api\/constants.hpp\"\n#include \"api\/IBuffer.hpp\"\n#include \"api\/IRequest.hpp\"\n#include \"api\/IModuleManager.hpp\"\n#include \"api\/IModule.hpp\"\n#include \"utils\/Path.hpp\"\n#include \"utils\/Logger.hpp\"\n#include \"utils\/macros.hpp\"\n#include \"config.hpp\"\n\n#include \"DirListing.hpp\"\n\nusing namespace zhttpd;\nusing namespace zhttpd::mod;\n\nDirListing::DirListing(api::IModuleManager*)\n{\n}\n\nDirListing::~DirListing()\n{\n}\n\nbool DirListing::processRequest(api::event::Type event, api::IRequest* request, api::IBuffer*)\n{\n if (event == api::event::ON_END)\n {\n Path dir(request->getFilePath());\n std::list<std::string> files = dir.getDirectoryContent();\n std::string slash(\"\/\");\n std::string const& path = request->getRequestQuery(); \/\/ XXX stop at '?' or '#'\n if (path == \"\/\")\n slash.clear();\n std::string out =\n \"<!DOCTYPE html>\\n\"\n \"<html xmlns=\\\"http:\/\/www.w3.org\/1999\/xhtml\\\" xml:lang=\\\"fr\\\">\\n\"\n \"<head>\\n\"\n \"<title>Index of \" + path + \"<\/title>\\n\"\n \"<style type=\\\"text\/css\\\">\\n\"\n \"body { font-family: Verdana; font-size: 13px; }\\n\"\n \"a:link { color: #c00; text-decoration: none; }\\n\"\n \"a:hover, a:active, a:focus { color: #c00; background-color: #ccc; text-decoration: none; }\\n\"\n \"a:visited { color: #c00; text-decoration: underline; }\\n\"\n \"<\/style>\\n\"\n \"<\/head>\\n\"\n \"<body>\\n\"\n \"<h3> Index of \" + path + \"<\/h3>\\n\"\n \"<hr \/>\\n\"\n \"<ul>\\n\"\n \"<li><a href=\\\"\" + path + slash + \"..\/\\\">..<\/a><\/li>\";\n\n std::list<std::string>::const_iterator it = files.begin();\n std::list<std::string>::const_iterator itEnd = files.end();\n for (; it != itEnd; ++it)\n out += \"<li><a href=\\\"\" + path + slash + *it + \"\\\">\" + *it + \"<\/a><\/li>\\n\"; \/\/ XXX replace '\"' in path !\n\n out += \"<\/ul>\\n\"\n \"<hr \/>\\n\"\n \"<p>\"\n ZHTTPD_FULLNAME\n \"<\/p>\\n\"\n \"<\/body>\\n\"\n \"<\/html>\";\n request->giveData(request->getBufferManager().allocate(out.data(), out.size()));\n request->raiseEnd();\n return true;\n }\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_HASH_FNV1_HPP\n#define OUZEL_HASH_FNV1_HPP\n\n#include <cstdint>\n\nnamespace ouzel::hash::fnv1\n{\n inline namespace detail\n {\n template <typename T> struct prime;\n template <typename T> struct offsetBasis;\n\n template <> struct prime<std::uint32_t>\n {\n static constexpr std::uint32_t value = 16777619U;\n };\n\n template <> struct offsetBasis<std::uint32_t>\n {\n static constexpr std::uint32_t value = 2166136261U;\n };\n\n template <> struct prime<std::uint64_t>\n {\n static constexpr std::uint64_t value = 1099511628211ULL;\n };\n\n template <> struct offsetBasis<std::uint64_t>\n {\n static constexpr std::uint64_t value = 14695981039346656037ULL;\n };\n }\n\n template <typename Result, typename Value>\n constexpr Result hash(const Value value, const std::size_t i = 0,\n const Result result = offsetBasis<Result>::value) noexcept\n {\n return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * prime<Result>::value) ^ ((value >> (i * 8)) & 0xFF)) : result;\n }\n}\n\n#endif \/\/ OUZEL_HASH_FNV1_HPP\n<commit_msg>Move the constants to a single struct<commit_after>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_HASH_FNV1_HPP\n#define OUZEL_HASH_FNV1_HPP\n\n#include <cstdint>\n\nnamespace ouzel::hash::fnv1\n{\n inline namespace detail\n {\n template <typename T> struct Constants;\n\n template <> struct Constants<std::uint32_t>\n {\n static constexpr std::uint32_t prime = 16777619U;\n static constexpr std::uint32_t offsetBasis = 2166136261U;\n };\n\n template <> struct Constants<std::uint64_t>\n {\n static constexpr std::uint64_t prime = 1099511628211ULL;\n static constexpr std::uint64_t offsetBasis = 14695981039346656037ULL;\n };\n }\n\n template <typename Result, typename Value>\n constexpr Result hash(const Value value, const std::size_t i = 0,\n const Result result = Constants<Result>::offsetBasis) noexcept\n {\n return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * Constants<Result>::prime) ^ ((value >> (i * 8)) & 0xFF)) : result;\n }\n}\n\n#endif \/\/ OUZEL_HASH_FNV1_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include <cassert>\n\/\/ StdAir\n#include <stdair\/stdair_inventory_types.hpp>\n#include <stdair\/basic\/BasFileMgr.hpp>\n#include <stdair\/basic\/BasChronometer.hpp>\n#include <stdair\/bom\/BomManager.hpp>\n#include <stdair\/bom\/LegCabin.hpp>\n#include <stdair\/command\/CmdBomManager.hpp>\n#include <stdair\/service\/Logger.hpp>\n#include <stdair\/STDAIR_Service.hpp>\n\/\/ RMOL\n#include <rmol\/basic\/BasConst_RMOL_Service.hpp>\n#include <rmol\/factory\/FacSupervisor.hpp>\n#include <rmol\/factory\/FacRmolServiceContext.hpp>\n#include <rmol\/command\/Optimiser.hpp>\n#include <rmol\/command\/Unconstrainer.hpp>\n#include <rmol\/command\/Forecaster.hpp>\n#include <rmol\/service\/RMOL_ServiceContext.hpp>\n#include <rmol\/RMOL_Service.hpp>\n\nnamespace RMOL {\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service () : _rmolServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const RMOL_Service& iService) :\n _rmolServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const stdair::BasLogParams& iLogParams,\n const stdair::CabinCapacity_T& iCabinCapacity) :\n _rmolServiceContext (NULL) {\n\n \/\/ Initialise the service context\n initServiceContext ();\n\n \/\/ Initialise the STDAIR service handler\n initStdAirService (iLogParams);\n\n \/\/ Build a dummy inventory with a leg-cabin which has the given capacity.\n buildInventorySample (iCabinCapacity);\n \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const stdair::BasLogParams& iLogParams) :\n _rmolServiceContext (NULL) {\n\n \/\/ Initialise the service context\n initServiceContext ();\n\n \/\/ Initialise the STDAIR service handler\n initStdAirService (iLogParams); \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service:: RMOL_Service (stdair::STDAIR_ServicePtr_T ioSTDAIRServicePtr)\n : _rmolServiceContext (NULL) {\n \n \/\/ Initialise the context\n initServiceContext ();\n \n \/\/ Add the StdAir service context to the RMOL service context\n addStdAirService (ioSTDAIRServicePtr);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::~RMOL_Service () {\n \/\/ Clean all the RMOL-scoped objects\n FacSupervisor::cleanFactory();\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::initServiceContext () {\n \/\/ Initialise the service context\n RMOL_ServiceContext& lRMOL_ServiceContext = \n FacRmolServiceContext::instance().create ();\n _rmolServiceContext = &lRMOL_ServiceContext;\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n initStdAirService (const stdair::BasLogParams& iLogParams) {\n assert (_rmolServiceContext != NULL);\n \n \/\/ Initialise the STDAIR service handler\n \/\/ Note that the track on the object memory is kept thanks to the Boost\n \/\/ Smart Pointers component.\n STDAIR_ServicePtr_T lSTDAIR_Service = \n STDAIR_ServicePtr_T (new stdair::STDAIR_Service (iLogParams));\n\n \/\/ Store the STDAIR service object within the (RMOL) service context\n addStdAirService (lSTDAIR_Service);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr) {\n\n \/\/ Retrieve the RMOL service context\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext =\n *_rmolServiceContext;\n\n \/\/ Store the STDAIR service object within the (AIRINV) service context\n lRMOL_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n buildInventorySample (const stdair::CabinCapacity_T& iCabinCapacity) {\n \/\/ Retrieve the BomRoot.\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n stdair::STDAIR_Service& lSTDAIR_Service =\n lRMOL_ServiceContext.getSTDAIR_Service ();\n stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot ();\n\n stdair::CmdBomManager::buildSampleBomForRMOL (lBomRoot, iCabinCapacity);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::readFromInputFile (const std::string& iInputFileName) {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n lRMOL_ServiceContext.readFromInputFile (iInputFileName);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::reset () {\n \/\/ Retrieve the RMOL service context\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n lRMOL_ServiceContext.reset();\n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n optimalOptimisationByMCIntegration (const int K) {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample();\n\n stdair::BasChronometer lOptimisationChronometer;\n lOptimisationChronometer.start();\n\n Optimiser::optimalOptimisationByMCIntegration (K, lLegCabin);\n\n const double lOptimisationMeasure = lOptimisationChronometer.elapsed();\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Optimisation by Monte-Carlo performed in \"\n << lOptimisationMeasure);\n \/\/STDAIR_LOG_DEBUG (\"Resulting buckets: \" << oBucketHolder_ptr->display());\n\n std::ostringstream logStream;\n stdair::BidPriceVector_T lBidPriceVector = lLegCabin.getBidPriceVector();\n logStream << \"Bid-Price Vector (BPV): \";\n unsigned int size = lBidPriceVector.size();\n \n for (unsigned int i = 0; i < size; ++i) {\n const double bidPrice = lBidPriceVector.at(i);\n logStream << std::fixed << std::setprecision (2) << bidPrice << \", \";\n }\n STDAIR_LOG_DEBUG (logStream.str());\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n optimalOptimisationByDP () {\n \n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsr () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample();\n\n stdair::BasChronometer lOptimisationChronometer;\n lOptimisationChronometer.start();\n \n Optimiser::heuristicOptimisationByEmsr (lLegCabin);\n \n const double lOptimisationMeasure = lOptimisationChronometer.elapsed();\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Optimisation EMSR performed in \"\n << lOptimisationMeasure);\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n\n std::ostringstream logStream;\n stdair::BidPriceVector_T lBidPriceVector = lLegCabin.getBidPriceVector();\n logStream << \"Bid-Price Vector (BPV): \";\n unsigned int size = lBidPriceVector.size();\n \n for (unsigned int i = 0; i < size; ++i) {\n const double bidPrice = lBidPriceVector.at(i);\n logStream << std::fixed << std::setprecision (2) << bidPrice << \", \";\n }\n STDAIR_LOG_DEBUG (logStream.str());\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsrA () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample(); \n\n Optimiser::heuristicOptimisationByEmsrA (lLegCabin);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsrB () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample(); \n\n Optimiser::heuristicOptimisationByEmsrB (lLegCabin);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n }\n\n}\n<commit_msg>[Dev] Made a constant 'const'.<commit_after>\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include <cassert>\n\/\/ StdAir\n#include <stdair\/stdair_inventory_types.hpp>\n#include <stdair\/basic\/BasFileMgr.hpp>\n#include <stdair\/basic\/BasChronometer.hpp>\n#include <stdair\/bom\/BomManager.hpp>\n#include <stdair\/bom\/LegCabin.hpp>\n#include <stdair\/command\/CmdBomManager.hpp>\n#include <stdair\/service\/Logger.hpp>\n#include <stdair\/STDAIR_Service.hpp>\n\/\/ RMOL\n#include <rmol\/basic\/BasConst_RMOL_Service.hpp>\n#include <rmol\/factory\/FacSupervisor.hpp>\n#include <rmol\/factory\/FacRmolServiceContext.hpp>\n#include <rmol\/command\/Optimiser.hpp>\n#include <rmol\/command\/Unconstrainer.hpp>\n#include <rmol\/command\/Forecaster.hpp>\n#include <rmol\/service\/RMOL_ServiceContext.hpp>\n#include <rmol\/RMOL_Service.hpp>\n\nnamespace RMOL {\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service () : _rmolServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const RMOL_Service& iService) :\n _rmolServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const stdair::BasLogParams& iLogParams,\n const stdair::CabinCapacity_T& iCabinCapacity) :\n _rmolServiceContext (NULL) {\n\n \/\/ Initialise the service context\n initServiceContext ();\n\n \/\/ Initialise the STDAIR service handler\n initStdAirService (iLogParams);\n\n \/\/ Build a dummy inventory with a leg-cabin which has the given capacity.\n buildInventorySample (iCabinCapacity);\n \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::RMOL_Service (const stdair::BasLogParams& iLogParams) :\n _rmolServiceContext (NULL) {\n\n \/\/ Initialise the service context\n initServiceContext ();\n\n \/\/ Initialise the STDAIR service handler\n initStdAirService (iLogParams); \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service:: RMOL_Service (stdair::STDAIR_ServicePtr_T ioSTDAIRServicePtr)\n : _rmolServiceContext (NULL) {\n \n \/\/ Initialise the context\n initServiceContext ();\n \n \/\/ Add the StdAir service context to the RMOL service context\n addStdAirService (ioSTDAIRServicePtr);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n RMOL_Service::~RMOL_Service () {\n \/\/ Clean all the RMOL-scoped objects\n FacSupervisor::cleanFactory();\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::initServiceContext () {\n \/\/ Initialise the service context\n RMOL_ServiceContext& lRMOL_ServiceContext = \n FacRmolServiceContext::instance().create ();\n _rmolServiceContext = &lRMOL_ServiceContext;\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n initStdAirService (const stdair::BasLogParams& iLogParams) {\n assert (_rmolServiceContext != NULL);\n \n \/\/ Initialise the STDAIR service handler\n \/\/ Note that the track on the object memory is kept thanks to the Boost\n \/\/ Smart Pointers component.\n STDAIR_ServicePtr_T lSTDAIR_Service = \n STDAIR_ServicePtr_T (new stdair::STDAIR_Service (iLogParams));\n\n \/\/ Store the STDAIR service object within the (RMOL) service context\n addStdAirService (lSTDAIR_Service);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr) {\n\n \/\/ Retrieve the RMOL service context\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext =\n *_rmolServiceContext;\n\n \/\/ Store the STDAIR service object within the (AIRINV) service context\n lRMOL_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n buildInventorySample (const stdair::CabinCapacity_T& iCabinCapacity) {\n \/\/ Retrieve the BomRoot.\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n stdair::STDAIR_Service& lSTDAIR_Service =\n lRMOL_ServiceContext.getSTDAIR_Service ();\n stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot ();\n\n stdair::CmdBomManager::buildSampleBomForRMOL (lBomRoot, iCabinCapacity);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::readFromInputFile (const std::string& iInputFileName) {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n lRMOL_ServiceContext.readFromInputFile (iInputFileName);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::reset () {\n \/\/ Retrieve the RMOL service context\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n lRMOL_ServiceContext.reset();\n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n optimalOptimisationByMCIntegration (const int K) {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample();\n\n stdair::BasChronometer lOptimisationChronometer;\n lOptimisationChronometer.start();\n\n Optimiser::optimalOptimisationByMCIntegration (K, lLegCabin);\n\n const double lOptimisationMeasure = lOptimisationChronometer.elapsed();\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Optimisation by Monte-Carlo performed in \"\n << lOptimisationMeasure);\n \/\/STDAIR_LOG_DEBUG (\"Resulting buckets: \" << oBucketHolder_ptr->display());\n\n std::ostringstream logStream;\n stdair::BidPriceVector_T lBidPriceVector = lLegCabin.getBidPriceVector();\n logStream << \"Bid-Price Vector (BPV): \";\n unsigned int size = lBidPriceVector.size();\n \n for (unsigned int i = 0; i < size; ++i) {\n const double bidPrice = lBidPriceVector.at(i);\n logStream << std::fixed << std::setprecision (2) << bidPrice << \", \";\n }\n STDAIR_LOG_DEBUG (logStream.str());\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::\n optimalOptimisationByDP () {\n \n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsr () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample();\n\n stdair::BasChronometer lOptimisationChronometer;\n lOptimisationChronometer.start();\n \n Optimiser::heuristicOptimisationByEmsr (lLegCabin);\n \n const double lOptimisationMeasure = lOptimisationChronometer.elapsed();\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Optimisation EMSR performed in \"\n << lOptimisationMeasure);\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n\n std::ostringstream logStream;\n stdair::BidPriceVector_T lBidPriceVector = lLegCabin.getBidPriceVector();\n logStream << \"Bid-Price Vector (BPV): \";\n const unsigned int size = lBidPriceVector.size();\n \n for (unsigned int i = 0; i < size; ++i) {\n const double bidPrice = lBidPriceVector.at(i);\n logStream << std::fixed << std::setprecision (2) << bidPrice << \", \";\n }\n STDAIR_LOG_DEBUG (logStream.str());\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsrA () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample(); \n\n Optimiser::heuristicOptimisationByEmsrA (lLegCabin);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n \n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void RMOL_Service::heuristicOptimisationByEmsrB () {\n assert (_rmolServiceContext != NULL);\n RMOL_ServiceContext& lRMOL_ServiceContext = *_rmolServiceContext;\n\n stdair::LegCabin& lLegCabin = lRMOL_ServiceContext.getLegCabinSample(); \n\n Optimiser::heuristicOptimisationByEmsrB (lLegCabin);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Result: \" << lLegCabin.displayVirtualClassList());\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*-Mode: C++;-*-\n\/\/ $Id$\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ $Source$\n\/\/\n\/\/ Purpose:\n\/\/ Class for reading and representing hpcrun profile data.\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/ Author:\n\/\/ Written by John Mellor-Crummey and Nathan Tallent, Rice University.\n\/\/\n\/\/ Adapted from parts of The Visual Profiler by Curtis L. Janssen\n\/\/ (vmonfile.cc).\n\/\/\n\/\/***************************************************************************\n\n#ifdef __GNUC__\n#pragma implementation\n#endif\n\n\/\/************************* System Include Files ****************************\n\n#include <iostream>\n#include <string>\n\n#include <stdio.h>\n#include <sys\/stat.h>\n\n\/\/*************************** User Include Files ****************************\n\n#include \"hpcrun.h\"\n#include \"proffile.h\"\n#include \"io.h\"\n\n\/\/*************************** Forward Declarations **************************\n\n\/\/#define PROFREADER_TEST\n\nusing namespace std;\n\nstatic int read_string(FILE *fp, std::string& str);\n\n\n\/\/***************************************************************************\n\nProfFile::ProfFile()\n{\n mtime_ = 0;\n}\n\nProfFile::~ProfFile()\n{\n}\n\nint\nProfFile::read(const string &filename)\n{\n FILE *fp;\n\n mtime_ = 0;\n\n struct stat statbuf;\n if (stat(filename.c_str(), &statbuf)) {\n return 1;\n }\n name_ = filename;\n mtime_ = statbuf.st_mtime;\n\n fp = fopen(filename.c_str(), \"r\");\n\n \/\/ <header>\n char magic_str[HPCRUNFILE_MAGIC_STR_LEN];\n char version[HPCRUNFILE_VERSION_LEN];\n char endian;\n int c;\n size_t sz;\n\n sz = fread((char*)magic_str, 1, HPCRUNFILE_MAGIC_STR_LEN, fp);\n if (sz != HPCRUNFILE_MAGIC_STR_LEN) { return 1; }\n \n sz = fread((char*)version, 1, HPCRUNFILE_VERSION_LEN, fp);\n if (sz != HPCRUNFILE_VERSION_LEN) { return 1; }\n \n if ((c = fgetc(fp)) == EOF) { return 1; }\n endian = (char)c;\n \n \/\/ sanity check header\n if (strncmp(magic_str, HPCRUNFILE_MAGIC_STR, \n\t HPCRUNFILE_MAGIC_STR_LEN) != 0) { \n return 1; \n }\n if (strncmp(version, HPCRUNFILE_VERSION, HPCRUNFILE_VERSION_LEN) != 0) { \n return 1; \n }\n if (endian != HPCRUNFILE_ENDIAN) { return 1; }\n\n\n \/\/ <loadmodule_list>\n uint32_t count;\n\n sz = hpc_fread_le4(&count, fp);\n if (sz != sizeof(count)) { return 1; }\n \n lmvec_.resize(count);\n for (unsigned int i = 0; i < count; ++i) {\n if (lmvec_[i].read(fp) != 0) { return 1; }\n }\n\n fclose(fp);\n return 0;\n}\n\nvoid\nProfFile::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"--- ProfFile Dump ---\" << endl;\n o << p << \"{ ProfFile: \" << name_ << \", modtime: \" << mtime_ << \" }\" \n << endl;\n\n for (unsigned int i = 0; i < num_load_modules(); ++i) {\n const ProfFileLM& proflm = load_module(i);\n proflm.dump(o, p1.c_str());\n }\n}\n\n\/\/***************************************************************************\n\nProfFileLM::ProfFileLM()\n{\n}\n\nProfFileLM::~ProfFileLM()\n{\n}\n\n#undef DEBUG\n\nint\nProfFileLM::read(FILE *fp)\n{\n size_t sz;\n \n \/\/ <loadmodule_name>, <loadmodule_loadoffset>\n if (read_string(fp, name_) != 0) { return 1; }\n#ifdef DEBUG\n cerr << name_ << \" \"; \n#endif\n \n sz = hpc_fread_le8(&load_addr_, fp);\n if (sz != sizeof(load_addr_)) { return 1; }\n#ifdef DEBUG\n cerr << \"load address=\" << load_addr_ << endl; \n#endif\n \n \/\/ <loadmodule_eventcount>\n unsigned int count = 1;\n sz = hpc_fread_le4(&count, fp);\n if (sz != sizeof(count)) { return 1; }\n eventvec_.resize(count);\n \n \/\/ Event data\n for (unsigned int i = 0; i < count; ++i) {\n if (eventvec_[i].read(fp, load_addr_) != 0) { return 1; }\n }\n \n return 0;\n}\n\nvoid\nProfFileLM::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"{ ProfFileLM: \" << name_ << \", loadAddr: 0x\" << hex \n << load_addr_ << dec << \" }\" << endl;\n \n for (unsigned int i = 0; i < num_events(); ++i) {\n const ProfFileEvent& profevent = event(i);\n profevent.dump(o, p1.c_str());\n }\n}\n\n\/\/***************************************************************************\n\nProfFileEvent::ProfFileEvent()\n{\n}\n\nProfFileEvent::~ProfFileEvent()\n{\n}\n\nint\nProfFileEvent::read(FILE *fp, uint64_t load_addr)\n{\n size_t sz;\n \n \/\/ <event_x_name> <event_x_description> <event_x_period>\n if (read_string(fp, name_) != 0) { return 1; }\n if (read_string(fp, desc_) != 0) { return 1; }\n \n sz = hpc_fread_le8(&period_, fp);\n if (sz != sizeof(period_)) { return 1; }\n \n \/\/ <event_x_data>\n dat_.clear();\n outofrange_ = 0;\n overflow_ = 0;\n \n \/\/ <histogram_non_zero_bucket_count>\n unsigned int ndat; \/\/ number of profile entries\n sz = hpc_fread_le4(&ndat, fp);\n if (sz != sizeof(ndat)) { return 1; }\n#ifdef DEBUG\n cerr << \"ndat =\" << ndat << endl; \n#endif\n dat_.resize(ndat);\n\n \/\/ <histogram_non_zero_bucket_x_value> \n \/\/ <histogram_non_zero_bucket_x_offset>\n unsigned int count; \/\/ profile count\n unsigned int offset; \/\/ offset from load address\n for (unsigned int i = 0; i < ndat; ++i) {\n sz = hpc_fread_le4(&count, fp); \/\/ count\n if (sz != sizeof(count)) { return 1; }\n\n sz = hpc_fread_le4(&offset, fp); \/\/ offset\n if (sz != sizeof(offset)) { return 1; }\n#ifdef DEBUG\n cerr << \" (cnt,offset)=(\" << count << \",\" << offset << \")\" << endl; \n#endif\n \n pprof_off_t pc = load_addr + offset;\n dat_[i] = make_pair(pc, count);\n }\n\n return 0;\n}\n\nvoid\nProfFileEvent::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"{ ProfFileEvent: \" << name() << \", period: \" << period() \n << \", outofrange: \" << outofrange() << \", overflow: \" << overflow()\n << \" }\" << endl;\n \n for (unsigned int i = 0; i < num_data(); ++i) {\n const ProfFileEventDatum& dat = datum(i);\n o << p1 << \"{ 0x\" << hex << dat.first << \": \" << dec\n << dat.second << \" }\" << endl;\n }\n}\n\n\/\/***************************************************************************\n\nstatic int\nread_string(FILE *fp, std::string& str)\n{\n size_t sz;\n uint32_t len; \/\/ string length \n int c;\n\n \/\/ <string_length> <string_without_terminator>\n sz = hpc_fread_le4(&len, fp);\n if (sz != sizeof(len)) { return 1; }\n \n str.resize(len);\n for (unsigned int n = 0; n < len; ++n) { \n if ((c = fgetc(fp)) == EOF) { return 1; }\n str[n] = (char)c;\n } \n return 0;\n}\n\n\/\/***************************************************************************\n\n#ifdef PROFREADER_TEST\n\nint main(int argc, char **argv)\n{\n std::string filename = argv[1];\n ProfFile f;\n\n int ret = f.read(filename);\n\n if (ret == 0) {\n cerr << \"successfully read file!\";\n } else {\n cerr << \"error reading file!\";\n }\n\n cout << \"File dump:\" << endl;\n f.dump(cout);\n}\n\n#endif\n<commit_msg>When writing profile data, record load module offsets as 8 bytes (necessary for 64 bit address spaces)<commit_after>\/\/ -*-Mode: C++;-*-\n\/\/ $Id$\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ $Source$\n\/\/\n\/\/ Purpose:\n\/\/ Class for reading and representing hpcrun profile data.\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/ Author:\n\/\/ Written by John Mellor-Crummey and Nathan Tallent, Rice University.\n\/\/\n\/\/ Adapted from parts of The Visual Profiler by Curtis L. Janssen\n\/\/ (vmonfile.cc).\n\/\/\n\/\/***************************************************************************\n\n#ifdef __GNUC__\n#pragma implementation\n#endif\n\n\/\/************************* System Include Files ****************************\n\n#include <iostream>\n#include <string>\n\n#include <stdio.h>\n#include <sys\/stat.h>\n\n\/\/*************************** User Include Files ****************************\n\n#include \"hpcrun.h\"\n#include \"proffile.h\"\n#include \"io.h\"\n\n\/\/*************************** Forward Declarations **************************\n\n\/\/#define PROFREADER_TEST\n\nusing namespace std;\n\nstatic int read_string(FILE *fp, std::string& str);\n\n\n\/\/***************************************************************************\n\nProfFile::ProfFile()\n{\n mtime_ = 0;\n}\n\nProfFile::~ProfFile()\n{\n}\n\nint\nProfFile::read(const string &filename)\n{\n FILE *fp;\n\n mtime_ = 0;\n\n struct stat statbuf;\n if (stat(filename.c_str(), &statbuf)) {\n return 1;\n }\n name_ = filename;\n mtime_ = statbuf.st_mtime;\n\n fp = fopen(filename.c_str(), \"r\");\n\n \/\/ <header>\n char magic_str[HPCRUNFILE_MAGIC_STR_LEN];\n char version[HPCRUNFILE_VERSION_LEN];\n char endian;\n int c;\n size_t sz;\n\n sz = fread((char*)magic_str, 1, HPCRUNFILE_MAGIC_STR_LEN, fp);\n if (sz != HPCRUNFILE_MAGIC_STR_LEN) { return 1; }\n \n sz = fread((char*)version, 1, HPCRUNFILE_VERSION_LEN, fp);\n if (sz != HPCRUNFILE_VERSION_LEN) { return 1; }\n \n if ((c = fgetc(fp)) == EOF) { return 1; }\n endian = (char)c;\n \n \/\/ sanity check header\n if (strncmp(magic_str, HPCRUNFILE_MAGIC_STR, \n\t HPCRUNFILE_MAGIC_STR_LEN) != 0) { \n return 1; \n }\n if (strncmp(version, HPCRUNFILE_VERSION, HPCRUNFILE_VERSION_LEN) != 0) { \n return 1; \n }\n if (endian != HPCRUNFILE_ENDIAN) { return 1; }\n\n\n \/\/ <loadmodule_list>\n uint32_t count;\n\n sz = hpc_fread_le4(&count, fp);\n if (sz != sizeof(count)) { return 1; }\n \n lmvec_.resize(count);\n for (unsigned int i = 0; i < count; ++i) {\n if (lmvec_[i].read(fp) != 0) { return 1; }\n }\n\n fclose(fp);\n return 0;\n}\n\nvoid\nProfFile::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"--- ProfFile Dump ---\" << endl;\n o << p << \"{ ProfFile: \" << name_ << \", modtime: \" << mtime_ << \" }\" \n << endl;\n\n for (unsigned int i = 0; i < num_load_modules(); ++i) {\n const ProfFileLM& proflm = load_module(i);\n proflm.dump(o, p1.c_str());\n }\n o << p << \"--- End ProfFile Dump ---\" << endl;\n}\n\n\/\/***************************************************************************\n\nProfFileLM::ProfFileLM()\n{\n}\n\nProfFileLM::~ProfFileLM()\n{\n}\n\n#undef DEBUG\n\nint\nProfFileLM::read(FILE *fp)\n{\n size_t sz;\n \n \/\/ <loadmodule_name>, <loadmodule_loadoffset>\n if (read_string(fp, name_) != 0) { return 1; }\n#ifdef DEBUG\n cerr << name_ << \" \"; \n#endif\n \n sz = hpc_fread_le8(&load_addr_, fp);\n if (sz != sizeof(load_addr_)) { return 1; }\n#ifdef DEBUG\n cerr << \"load address=\" << load_addr_ << endl; \n#endif\n \n \/\/ <loadmodule_eventcount>\n unsigned int count = 1;\n sz = hpc_fread_le4(&count, fp);\n if (sz != sizeof(count)) { return 1; }\n eventvec_.resize(count);\n \n \/\/ Event data\n for (unsigned int i = 0; i < count; ++i) {\n if (eventvec_[i].read(fp, load_addr_) != 0) { return 1; }\n }\n \n return 0;\n}\n\nvoid\nProfFileLM::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"{ ProfFileLM: \" << name_ << \", loadAddr: 0x\" << hex \n << load_addr_ << dec << \" }\" << endl;\n \n for (unsigned int i = 0; i < num_events(); ++i) {\n const ProfFileEvent& profevent = event(i);\n profevent.dump(o, p1.c_str());\n }\n}\n\n\/\/***************************************************************************\n\nProfFileEvent::ProfFileEvent()\n{\n}\n\nProfFileEvent::~ProfFileEvent()\n{\n}\n\nint\nProfFileEvent::read(FILE *fp, uint64_t load_addr)\n{\n size_t sz;\n \n \/\/ <event_x_name> <event_x_description> <event_x_period>\n if (read_string(fp, name_) != 0) { return 1; }\n if (read_string(fp, desc_) != 0) { return 1; }\n \n sz = hpc_fread_le8(&period_, fp);\n if (sz != sizeof(period_)) { return 1; }\n \n \/\/ <event_x_data>\n dat_.clear();\n outofrange_ = 0;\n overflow_ = 0;\n \n \/\/ <histogram_non_zero_bucket_count>\n uint64_t ndat; \/\/ number of profile entries\n sz = hpc_fread_le8(&ndat, fp);\n if (sz != sizeof(ndat)) { return 1; }\n#ifdef DEBUG\n cerr << \"ndat =\" << ndat << endl; \n#endif\n dat_.resize(ndat);\n\n \/\/ <histogram_non_zero_bucket_x_value> \n \/\/ <histogram_non_zero_bucket_x_offset>\n uint32_t count; \/\/ profile count\n uint64_t offset; \/\/ offset from load address\n for (unsigned int i = 0; i < ndat; ++i) {\n sz = hpc_fread_le4(&count, fp); \/\/ count\n if (sz != sizeof(count)) { return 1; }\n\n sz = hpc_fread_le8(&offset, fp); \/\/ offset\n if (sz != sizeof(offset)) { return 1; }\n#ifdef DEBUG\n cerr << \" (cnt,offset)=(\" << count << \",\" << offset << \")\" << endl; \n#endif\n \n pprof_off_t pc = load_addr + offset;\n dat_[i] = make_pair(pc, count);\n }\n\n return 0;\n}\n\nvoid\nProfFileEvent::dump(std::ostream& o, const char* pre) const\n{\n string p = pre;\n string p1 = p + \" \";\n\n o << p << \"{ ProfFileEvent: \" << name() << \", period: \" << period() \n << \", outofrange: \" << outofrange() << \", overflow: \" << overflow()\n << \" }\" << endl;\n \n for (unsigned int i = 0; i < num_data(); ++i) {\n const ProfFileEventDatum& dat = datum(i);\n o << p1 << \"{ 0x\" << hex << dat.first << \": \" << dec\n << dat.second << \" }\" << endl;\n }\n}\n\n\/\/***************************************************************************\n\nstatic int\nread_string(FILE *fp, std::string& str)\n{\n size_t sz;\n uint32_t len; \/\/ string length \n int c;\n\n \/\/ <string_length> <string_without_terminator>\n sz = hpc_fread_le4(&len, fp);\n if (sz != sizeof(len)) { return 1; }\n \n str.resize(len);\n for (unsigned int n = 0; n < len; ++n) { \n if ((c = fgetc(fp)) == EOF) { return 1; }\n str[n] = (char)c;\n } \n return 0;\n}\n\n\/\/***************************************************************************\n\n#ifdef PROFREADER_TEST\n\nint main(int argc, char **argv)\n{\n std::string filename = argv[1];\n ProfFile f;\n\n int ret = f.read(filename);\n\n if (ret == 0) {\n cerr << \"successfully read file!\";\n } else {\n cerr << \"error reading file!\";\n }\n\n cout << \"File dump:\" << endl;\n f.dump(cout);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Copyright (C) 2012-2016, Ryan P. Wilson\n\/\/\n\/\/ Authority FX, Inc.\n\/\/ www.authorityfx.com\n\n#include <DDImage\/Iop.h>\n#include <DDImage\/Row.h>\n#include <DDImage\/Knobs.h>\n#include <DDImage\/ImagePlane.h>\n#include <DDImage\/Thread.h>\n#include <DDImage\/NukeWrapper.h>\n\n#include <stdexcept>\n\n#include <boost\/bind.hpp>\n#include <math.h>\n\n#include \"threading.h\"\n#include \"image.h\"\n#include \"nuke_helper.h\"\n#include \"mlaa.h\"\n\n\/\/ The class name must match exactly what is in the meny.py: nuke.createNode(CLASS)\nstatic const char* CLASS = \"AFXAntiAlias\";\nstatic const char* HELP = \"Anti Alias\";\n\n#define ThisClass AFXAntiAlias\n\nusing namespace DD::Image;\n\nclass ThisClass : public Iop {\nprivate:\n\n \/\/ members to store knob values\n float k_threshold_;\n\n \/\/ members to store processed knob values\n boost::mutex mutex_;\n bool first_time_CPU_;\n Lock lock_;\n\n afx::Bounds info_bnds, req_bnds_, format_bnds_, format_f_bnds_;\n float proxy_scale_;\n\n afx::ImageArray out_imgs_;\n\n afx::Threader threader_;\n\n void MetricsCPU(afx::Bounds region, const ImagePlane& source, const ImagePlane& matte, float* ref_hsv, double* sum_rgb, double* sum, double* sum_sqrs, unsigned int& num);\n void ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row);\n\npublic:\n ThisClass(Node* node);\n void knobs(Knob_Callback);\n const char* Class() const;\n const char* node_help() const;\n static const Iop::Description d;\n\n void _validate(bool);\n void _request(int x, int y, int r, int t, ChannelMask channels, int count);\n void _open();\n void _close();\n void engine(int y, int x, int r, ChannelMask channels, Row& row);\n};\nThisClass::ThisClass(Node* node) : Iop(node) {\n inputs(1);\n\n first_time_CPU_ = true;\n\n \/\/initialize knobs\n k_threshold_ = 0.25f;\n}\nvoid ThisClass::knobs(Knob_Callback f) {\n\n Float_knob(f, &k_threshold_, \"threshold\", \"Threshold\");\n Tooltip(f, \"Anti Alias Threshold\");\n SetRange(f, 0.0, 1.0);\n\n}\nconst char* ThisClass::Class() const { return CLASS; }\nconst char* ThisClass::node_help() const { return HELP; }\nstatic Iop* build(Node* node) { return (new NukeWrapper(new ThisClass(node)))->channelsRGBoptionalAlpha(); }\nconst Op::Description ThisClass::d(CLASS, \"AuthorityFX\/AFX Anti Alias\", build);\n\nvoid ThisClass::_validate(bool) {\n copy_info(0);\n\n format_bnds_ = afx::BoxToBounds(input(0)->format());\n format_f_bnds_ = afx::BoxToBounds(input(0)->full_size_format());\n proxy_scale_ = (float)format_bnds_.GetWidth() \/ (float)format_f_bnds_.GetWidth();\n\n info_bnds = afx::BoxToBounds(info_.box());\n}\nvoid ThisClass::_request(int x, int y, int r, int t, ChannelMask channels, int count) {\n \/\/Request source\n Box req_box(x + 50, + 50, r + 50, t + 50); \/\/expand this\n input0().request(req_box, channels, count);\n req_bnds_.SetBounds(x, y, r - 1, t - 1);\n}\nvoid ThisClass::_open() {\n first_time_CPU_ = true;\n}\nvoid ThisClass::_close() {\n first_time_CPU_ = true;\n out_imgs_.Clear();\n}\nvoid ThisClass::engine(int y, int x, int r, ChannelMask channels, Row& row) {\n callCloseAfter(0);\n try {\n ProcessCPU(y, x, r, channels, row);\n } catch (std::exception const& e) {\n foreach (z, channels) {\n memset(row.writable(z) + x, 0, (r - x) * sizeof(float));\n }\n }\n}\nvoid ThisClass::ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row) {\n afx::Bounds row_bnds(x, y, r - 1, y);\n\n if (first_time_CPU_) {\n Guard guard(lock_);\n if (first_time_CPU_) {\n afx::Bounds req_pad_bnds = req_bnds_.GetPadBounds(50);\n req_pad_bnds.Intersect(info_bnds);\n\n ImagePlane source_plane(afx::BoundsToBox(req_pad_bnds), false, channels); \/\/ Create plane \"false\" = non-packed.\n input0().fetchPlane(source_plane); \/\/ Fetch plane\n out_imgs_.Clear();\n afx::Image in_img(req_pad_bnds);\n foreach (z, source_plane.channels()) { \/\/ For each channel in plane\n in_img.MemCpyIn(&source_plane.readable()[source_plane.chanNo(z) * source_plane.chanStride()], source_plane.rowStride() * sizeof(float), in_img.GetBounds());\n out_imgs_.AddImage(req_pad_bnds);\n out_imgs_.GetBackPtr()->AddAttribute(\"channel\", z);\n out_imgs_.GetBackPtr()->MemCpyIn(in_img.GetPtr(), in_img.GetPitch(), in_img.GetBounds());\n afx::MorphAA aa;\n aa.Process(in_img, *out_imgs_.GetBackPtr(), k_threshold_, threader_);\n }\n first_time_CPU_ = false;\n }\n } \/\/ End first time guard\n\n if (aborted()) { return; }\n\n foreach (z, channels) {\n afx::Image* plane_ptr = out_imgs_.GetPtrByAttribute(\"channel\", z);\n plane_ptr->MemCpyOut(row.writable(z) + row_bnds.x1(), row_bnds.GetWidth() * sizeof(float), row_bnds);\n\/\/ float* out_ptr = row.writable(z) + row_bnds.x1();\n\/\/ for (int x = row_bnds.x1(); x <= row_bnds.x2(); ++x) {\n\/\/ *out_ptr++ = plane_ptr->GetVal(x, y);\n\/\/ }\n }\n}\n<commit_msg>Bounds issue<commit_after>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Copyright (C) 2012-2016, Ryan P. Wilson\n\/\/\n\/\/ Authority FX, Inc.\n\/\/ www.authorityfx.com\n\n#include <DDImage\/Iop.h>\n#include <DDImage\/Row.h>\n#include <DDImage\/Knobs.h>\n#include <DDImage\/ImagePlane.h>\n#include <DDImage\/Thread.h>\n#include <DDImage\/NukeWrapper.h>\n\n#include <stdexcept>\n\n#include <boost\/bind.hpp>\n#include <math.h>\n\n#include \"threading.h\"\n#include \"image.h\"\n#include \"nuke_helper.h\"\n#include \"mlaa.h\"\n\n\/\/ The class name must match exactly what is in the meny.py: nuke.createNode(CLASS)\nstatic const char* CLASS = \"AFXAntiAlias\";\nstatic const char* HELP = \"Anti Alias\";\n\n#define ThisClass AFXAntiAlias\n\nusing namespace DD::Image;\n\nclass ThisClass : public Iop {\nprivate:\n\n \/\/ members to store knob values\n float k_threshold_;\n\n \/\/ members to store processed knob values\n boost::mutex mutex_;\n bool first_time_CPU_;\n Lock lock_;\n\n afx::Bounds info_bnds, req_bnds_, format_bnds_, format_f_bnds_;\n float proxy_scale_;\n\n afx::ImageArray out_imgs_;\n\n afx::Threader threader_;\n\n void MetricsCPU(afx::Bounds region, const ImagePlane& source, const ImagePlane& matte, float* ref_hsv, double* sum_rgb, double* sum, double* sum_sqrs, unsigned int& num);\n void ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row);\n\npublic:\n ThisClass(Node* node);\n void knobs(Knob_Callback);\n const char* Class() const;\n const char* node_help() const;\n static const Iop::Description d;\n\n void _validate(bool);\n void _request(int x, int y, int r, int t, ChannelMask channels, int count);\n void _open();\n void _close();\n void engine(int y, int x, int r, ChannelMask channels, Row& row);\n};\nThisClass::ThisClass(Node* node) : Iop(node) {\n inputs(1);\n\n first_time_CPU_ = true;\n\n \/\/initialize knobs\n k_threshold_ = 0.25f;\n}\nvoid ThisClass::knobs(Knob_Callback f) {\n\n Float_knob(f, &k_threshold_, \"threshold\", \"Threshold\");\n Tooltip(f, \"Anti Alias Threshold\");\n SetRange(f, 0.0, 1.0);\n\n}\nconst char* ThisClass::Class() const { return CLASS; }\nconst char* ThisClass::node_help() const { return HELP; }\nstatic Iop* build(Node* node) { return (new NukeWrapper(new ThisClass(node)))->channelsRGBoptionalAlpha(); }\nconst Op::Description ThisClass::d(CLASS, \"AuthorityFX\/AFX Anti Alias\", build);\n\nvoid ThisClass::_validate(bool) {\n copy_info(0);\n\n format_bnds_ = afx::BoxToBounds(input(0)->format());\n format_f_bnds_ = afx::BoxToBounds(input(0)->full_size_format());\n proxy_scale_ = (float)format_bnds_.GetWidth() \/ (float)format_f_bnds_.GetWidth();\n\n}\nvoid ThisClass::_request(int x, int y, int r, int t, ChannelMask channels, int count) {\n \/\/Request source\n Box req_box(x + 50, + 50, r + 50, t + 50); \/\/expand this\n input0().request(req_box, channels, count);\n req_bnds_.SetBounds(x, y, r - 1, t - 1);\n}\nvoid ThisClass::_open() {\n first_time_CPU_ = true;\n}\nvoid ThisClass::_close() {\n first_time_CPU_ = true;\n out_imgs_.Clear();\n}\nvoid ThisClass::engine(int y, int x, int r, ChannelMask channels, Row& row) {\n callCloseAfter(0);\n try {\n ProcessCPU(y, x, r, channels, row);\n } catch (std::exception const& e) {\n foreach (z, channels) {\n memset(row.writable(z) + x, 0, (r - x) * sizeof(float));\n }\n }\n}\nvoid ThisClass::ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row) {\n afx::Bounds row_bnds(x, y, r - 1, y);\n\n if (first_time_CPU_) {\n Guard guard(lock_);\n if (first_time_CPU_) {\n afx::Bounds req_pad_bnds = req_bnds_.GetPadBounds(50);\n req_pad_bnds.Intersect(afx::BoxToBounds(input(0)->info().box()));\n\n ImagePlane source_plane(afx::BoundsToBox(req_pad_bnds), false, channels); \/\/ Create plane \"false\" = non-packed.\n input0().fetchPlane(source_plane); \/\/ Fetch plane\n out_imgs_.Clear();\n afx::Image in_img(req_pad_bnds);\n foreach (z, source_plane.channels()) { \/\/ For each channel in plane\n in_img.MemCpyIn(&source_plane.readable()[source_plane.chanNo(z) * source_plane.chanStride()], source_plane.rowStride() * sizeof(float), in_img.GetBounds());\n out_imgs_.AddImage(req_pad_bnds);\n out_imgs_.GetBackPtr()->AddAttribute(\"channel\", z);\n out_imgs_.GetBackPtr()->MemCpyIn(in_img.GetPtr(), in_img.GetPitch(), in_img.GetBounds());\n afx::MorphAA aa;\n aa.Process(in_img, *out_imgs_.GetBackPtr(), k_threshold_, threader_);\n }\n first_time_CPU_ = false;\n }\n } \/\/ End first time guard\n\n if (aborted()) { return; }\n\n foreach (z, channels) {\n afx::Image* plane_ptr = out_imgs_.GetPtrByAttribute(\"channel\", z);\n plane_ptr->MemCpyOut(row.writable(z) + row_bnds.x1(), row_bnds.GetWidth() * sizeof(float), row_bnds);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n intersectMain.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\nusing namespace std;\n\n#include \"intersectFile.h\"\n#include \"Context.h\"\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools intersect\"\n\nvoid intersect_help(void);\n\nint intersect_main(int argc, char* argv[]) {\n\n Context *context = new Context();\n if (!context->parseCmdArgs(argc, argv, 1) || context->getShowHelp() || !context->isValidState()) {\n \tif (!context->getErrorMsg().empty()) {\n \t\tcerr << context->getErrorMsg() << endl;\n \t}\n \tintersect_help();\n \tdelete context;\n \treturn 0;\n }\n\tFileIntersect *fileIntersect = new FileIntersect(context);\n\n\tbool retVal = fileIntersect->intersectFiles();\n\tdelete fileIntersect;\n\tdelete context;\n\treturn retVal ? 0 : 1;\n}\n\nvoid intersect_help(void) {\n\n cerr << \"\\nTool: bedtools intersect (aka intersectBed)\" << endl;\n cerr << \"Version: \" << VERSION << \"\\n\"; \n cerr << \"Summary: Report overlaps between two feature files.\" << endl << endl;\n\n cerr << \"Usage: \" << PROGRAM_NAME << \" [OPTIONS] -a <bed\/gff\/vcf> -b <bed\/gff\/vcf>\" << endl << endl;\n\n cerr << \"Options: \" << endl;\n\n cerr << \"\\t-abam\\t\" << \"The A input file is in BAM format. Output will be BAM as well.\" << endl << endl;\n\n cerr << \"\\t-ubam\\t\" << \"Write uncompressed BAM output. Default writes compressed BAM.\" << endl << endl;\n\n cerr << \"\\t-bed\\t\" << \"When using BAM input (-abam), write output as BED. The default\" << endl;\n cerr << \"\\t\\tis to write output in BAM when using -abam.\" << endl << endl;\n\n cerr << \"\\t-wa\\t\" << \"Write the original entry in A for each overlap.\" << endl << endl;\n\n cerr << \"\\t-wb\\t\" << \"Write the original entry in B for each overlap.\" << endl;\n cerr << \"\\t\\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r.\" << endl << endl;\n \n cerr << \"\\t-loj\\t\" << \"Perform a \\\"left outer join\\\". That is, for each feature in A\" << endl;\n cerr << \"\\t\\treport each overlap with B. If no overlaps are found, \" << endl;\n cerr << \"\\t\\treport a NULL feature for B.\" << endl << endl;\n\n cerr << \"\\t-wo\\t\" << \"Write the original A and B entries plus the number of base\" << endl;\n cerr << \"\\t\\tpairs of overlap between the two features.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl;\n cerr << \"\\t\\t Only A features with overlap are reported.\" << endl << endl;\n\n cerr << \"\\t-wao\\t\" << \"Write the original A and B entries plus the number of base\" << endl;\n cerr << \"\\t\\tpairs of overlap between the two features.\" << endl;\n cerr << \"\\t\\t- Overlapping features restricted by -f and -r.\" << endl;\n cerr << \"\\t\\t However, A features w\/o overlap are also reported\" << endl;\n cerr << \"\\t\\t with a NULL B feature and overlap = 0.\" << endl << endl;\n\n cerr << \"\\t-u\\t\" << \"Write the original A entry _once_ if _any_ overlaps found in B.\" << endl;\n cerr << \"\\t\\t- In other words, just report the fact >=1 hit was found.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n cerr << \"\\t-c\\t\" << \"For each entry in A, report the number of overlaps with B.\" << endl;\n cerr << \"\\t\\t- Reports 0 for A entries that have no overlap with B.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n cerr << \"\\t-v\\t\" << \"Only report those entries in A that have _no overlaps_ with B.\" << endl;\n cerr << \"\\t\\t- Similar to \\\"grep -v\\\" (an homage).\" << endl << endl;\n\n cerr << \"\\t-f\\t\" << \"Minimum overlap required as a fraction of A.\" << endl;\n cerr << \"\\t\\t- Default is 1E-9 (i.e., 1bp).\" << endl;\n cerr << \"\\t\\t- FLOAT (e.g. 0.50)\" << endl << endl;\n\n cerr << \"\\t-r\\t\" << \"Require that the fraction overlap be reciprocal for A and B.\" << endl;\n cerr << \"\\t\\t- In other words, if -f is 0.90 and -r is used, this requires\" << endl;\n cerr << \"\\t\\t that B overlap 90% of A and A _also_ overlaps 90% of B.\" << endl << endl;\n\n cerr << \"\\t-s\\t\" << \"Require same strandedness. That is, only report hits in B\" << endl;\n cerr << \"\\t\\tthat overlap A on the _same_ strand.\" << endl;\n cerr << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n cerr << \"\\t-S\\t\" << \"Require different strandedness. That is, only report hits in B\" << endl;\n cerr << \"\\t\\tthat overlap A on the _opposite_ strand.\" << endl;\n cerr << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n cerr << \"\\t-split\\t\" << \"Treat \\\"split\\\" BAM or BED12 entries as distinct BED intervals.\" << endl << endl;\n\n cerr << \"\\t-sorted\\t\" << \"Use the \\\"chromsweep\\\" algorithm for sorted (-k1,1 -k2,2n) input.\" << endl << endl;\n \n cerr << \"\\t-g\\t\" \t\t<< \"Provide a genome file to enforce consistent chromosome sort order\" << endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tacross input files. Only applies when used with -sorted option.\" << endl << endl;\n\n cerr << \"\\t-header\\t\" << \"Print the header from the A file prior to results.\" << endl << endl;\n \n cerr << \"Notes: \" << endl;\n cerr << \"\\t(1) When a BAM file is used for the A file, the alignment is retained if overlaps exist,\" << endl;\n cerr << \"\\tand exlcuded if an overlap cannot be found. If multiple overlaps exist, they are not\" << endl;\n cerr << \"\\treported, as we are only testing for one or more overlaps.\" << endl << endl;\n\n \/\/ end the program here\n exit(1);\n\n}\n<commit_msg>Added -nobuf option and definition to intersect help menu.<commit_after>\/*****************************************************************************\n intersectMain.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\nusing namespace std;\n\n#include \"intersectFile.h\"\n#include \"Context.h\"\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools intersect\"\n\nvoid intersect_help(void);\n\nint intersect_main(int argc, char* argv[]) {\n\n Context *context = new Context();\n if (!context->parseCmdArgs(argc, argv, 1) || context->getShowHelp() || !context->isValidState()) {\n \tif (!context->getErrorMsg().empty()) {\n \t\tcerr << context->getErrorMsg() << endl;\n \t}\n \tintersect_help();\n \tdelete context;\n \treturn 0;\n }\n\tFileIntersect *fileIntersect = new FileIntersect(context);\n\n\tbool retVal = fileIntersect->intersectFiles();\n\tdelete fileIntersect;\n\tdelete context;\n\treturn retVal ? 0 : 1;\n}\n\nvoid intersect_help(void) {\n\n cerr << \"\\nTool: bedtools intersect (aka intersectBed)\" << endl;\n cerr << \"Version: \" << VERSION << \"\\n\"; \n cerr << \"Summary: Report overlaps between two feature files.\" << endl << endl;\n\n cerr << \"Usage: \" << PROGRAM_NAME << \" [OPTIONS] -a <bed\/gff\/vcf> -b <bed\/gff\/vcf>\" << endl << endl;\n\n cerr << \"Options: \" << endl;\n\n cerr << \"\\t-abam\\t\" << \"The A input file is in BAM format. Output will be BAM as well.\" << endl << endl;\n\n cerr << \"\\t-ubam\\t\" << \"Write uncompressed BAM output. Default writes compressed BAM.\" << endl << endl;\n\n cerr << \"\\t-bed\\t\" << \"When using BAM input (-abam), write output as BED. The default\" << endl;\n cerr << \"\\t\\tis to write output in BAM when using -abam.\" << endl << endl;\n\n cerr << \"\\t-wa\\t\" << \"Write the original entry in A for each overlap.\" << endl << endl;\n\n cerr << \"\\t-wb\\t\" << \"Write the original entry in B for each overlap.\" << endl;\n cerr << \"\\t\\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r.\" << endl << endl;\n \n cerr << \"\\t-loj\\t\" << \"Perform a \\\"left outer join\\\". That is, for each feature in A\" << endl;\n cerr << \"\\t\\treport each overlap with B. If no overlaps are found, \" << endl;\n cerr << \"\\t\\treport a NULL feature for B.\" << endl << endl;\n\n cerr << \"\\t-wo\\t\" << \"Write the original A and B entries plus the number of base\" << endl;\n cerr << \"\\t\\tpairs of overlap between the two features.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl;\n cerr << \"\\t\\t Only A features with overlap are reported.\" << endl << endl;\n\n cerr << \"\\t-wao\\t\" << \"Write the original A and B entries plus the number of base\" << endl;\n cerr << \"\\t\\tpairs of overlap between the two features.\" << endl;\n cerr << \"\\t\\t- Overlapping features restricted by -f and -r.\" << endl;\n cerr << \"\\t\\t However, A features w\/o overlap are also reported\" << endl;\n cerr << \"\\t\\t with a NULL B feature and overlap = 0.\" << endl << endl;\n\n cerr << \"\\t-u\\t\" << \"Write the original A entry _once_ if _any_ overlaps found in B.\" << endl;\n cerr << \"\\t\\t- In other words, just report the fact >=1 hit was found.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n cerr << \"\\t-c\\t\" << \"For each entry in A, report the number of overlaps with B.\" << endl;\n cerr << \"\\t\\t- Reports 0 for A entries that have no overlap with B.\" << endl;\n cerr << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n cerr << \"\\t-v\\t\" << \"Only report those entries in A that have _no overlaps_ with B.\" << endl;\n cerr << \"\\t\\t- Similar to \\\"grep -v\\\" (an homage).\" << endl << endl;\n\n cerr << \"\\t-f\\t\" << \"Minimum overlap required as a fraction of A.\" << endl;\n cerr << \"\\t\\t- Default is 1E-9 (i.e., 1bp).\" << endl;\n cerr << \"\\t\\t- FLOAT (e.g. 0.50)\" << endl << endl;\n\n cerr << \"\\t-r\\t\" << \"Require that the fraction overlap be reciprocal for A and B.\" << endl;\n cerr << \"\\t\\t- In other words, if -f is 0.90 and -r is used, this requires\" << endl;\n cerr << \"\\t\\t that B overlap 90% of A and A _also_ overlaps 90% of B.\" << endl << endl;\n\n cerr << \"\\t-s\\t\" << \"Require same strandedness. That is, only report hits in B\" << endl;\n cerr << \"\\t\\tthat overlap A on the _same_ strand.\" << endl;\n cerr << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n cerr << \"\\t-S\\t\" << \"Require different strandedness. That is, only report hits in B\" << endl;\n cerr << \"\\t\\tthat overlap A on the _opposite_ strand.\" << endl;\n cerr << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n cerr << \"\\t-split\\t\" << \"Treat \\\"split\\\" BAM or BED12 entries as distinct BED intervals.\" << endl << endl;\n\n cerr << \"\\t-sorted\\t\" << \"Use the \\\"chromsweep\\\" algorithm for sorted (-k1,1 -k2,2n) input.\" << endl << endl;\n \n cerr << \"\\t-g\\t\" \t\t<< \"Provide a genome file to enforce consistent chromosome sort order\" << endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tacross input files. Only applies when used with -sorted option.\" << endl << endl;\n\n cerr << \"\\t-header\\t\" << \"Print the header from the A file prior to results.\" << endl << endl;\n\n cerr << \"\\t-nobuf\\t\" << \"Disable buffered output. Using this option will cause each line\"<< endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tof output to be printed as it is generated, rather than saved\" << endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tin a buffer. This will make printing large output files \" << endl;\n\n cerr \t\t\t\t\t\t<<\"\\t\\tnoticeably slower, but can be useful in conjunction with\" << endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tother software tools and scripts that need to process one\" << endl;\n cerr \t\t\t\t\t\t<<\"\\t\\tline of bedtools output at a time.\" << endl << endl;\n\n cerr << \"Notes: \" << endl;\n cerr << \"\\t(1) When a BAM file is used for the A file, the alignment is retained if overlaps exist,\" << endl;\n cerr << \"\\tand exlcuded if an overlap cannot be found. If multiple overlaps exist, they are not\" << endl;\n cerr << \"\\treported, as we are only testing for one or more overlaps.\" << endl << endl;\n\n \/\/ end the program here\n exit(1);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n#define IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n\n#include <cstdint>\n\nnamespace iox\n{\nnamespace popo\n{\ntemplate <typename T, typename base_publisher_t>\nTypedPublisher<T, base_publisher_t>::TypedPublisher(const capro::ServiceDescription& service)\n : base_publisher_t(service)\n{\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline uid_t TypedPublisher<T, base_publisher_t>::getUid() const noexcept\n{\n return base_publisher_t::getUid();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::expected<Sample<T>, AllocationError> TypedPublisher<T, base_publisher_t>::loan() noexcept\n{\n return base_publisher_t::loan(sizeof(T));\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::publish(Sample<T>&& sample) noexcept\n{\n return base_publisher_t::publish(std::forward<Sample<T>>(sample));\n}\n\ntemplate <typename T, typename base_publisher_t>\ntemplate <typename Callable, typename... ArgTypes>\ninline cxx::expected<AllocationError> TypedPublisher<T, base_publisher_t>::publishResultOf(Callable c,\n ArgTypes... args) noexcept\n{\n static_assert(\n cxx::is_callable<Callable, T*, ArgTypes...>::value,\n \"TypedPublisher<T>::publishResultOf expects a valid callable with a specific signature as the first argument\");\n static_assert(cxx::has_signature<Callable, void(T*, ArgTypes...)>::value,\n \"callable provided to TypedPublisher<T>::publishResultOf must have signature void(T*, ArgsTypes...)\");\n\n return loan().and_then([&](Sample<T>& sample) {\n c(sample.get(), std::forward<ArgTypes>(args)...);\n publish(std::move(sample));\n });\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::expected<AllocationError> TypedPublisher<T, base_publisher_t>::publishCopyOf(const T& val) noexcept\n{\n return loan().and_then([&](Sample<T>& sample) {\n *sample.get() = val; \/\/ Copy assignment of value into sample's memory allocation.\n publish(std::move(sample));\n });\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::optional<Sample<T>> TypedPublisher<T, base_publisher_t>::loanPreviousSample() noexcept\n{\n return base_publisher_t::loanPreviousSample();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::offer() noexcept\n{\n return base_publisher_t::offer();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::stopOffer() noexcept\n{\n return base_publisher_t::stopOffer();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline bool TypedPublisher<T, base_publisher_t>::isOffered() const noexcept\n{\n return base_publisher_t::isOffered();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline bool TypedPublisher<T, base_publisher_t>::hasSubscribers() const noexcept\n{\n return base_publisher_t::hasSubscribers();\n}\n\n} \/\/ namespace popo\n} \/\/ namespace iox\n\n#endif \/\/ IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n<commit_msg>iox-#218 Use type traits from master.<commit_after>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n#define IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n\n#include <cstdint>\n\nnamespace iox\n{\nnamespace popo\n{\ntemplate <typename T, typename base_publisher_t>\nTypedPublisher<T, base_publisher_t>::TypedPublisher(const capro::ServiceDescription& service)\n : base_publisher_t(service)\n{\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline uid_t TypedPublisher<T, base_publisher_t>::getUid() const noexcept\n{\n return base_publisher_t::getUid();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::expected<Sample<T>, AllocationError> TypedPublisher<T, base_publisher_t>::loan() noexcept\n{\n return base_publisher_t::loan(sizeof(T));\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::publish(Sample<T>&& sample) noexcept\n{\n return base_publisher_t::publish(std::forward<Sample<T>>(sample));\n}\n\ntemplate <typename T, typename base_publisher_t>\ntemplate <typename Callable, typename... ArgTypes>\ninline cxx::expected<AllocationError> TypedPublisher<T, base_publisher_t>::publishResultOf(Callable c,\n ArgTypes... args) noexcept\n{\n static_assert(\n cxx::is_invocable<Callable, T*, ArgTypes...>::value,\n \"TypedPublisher<T>::publishResultOf expects a valid callable with a specific signature as the first argument\");\n static_assert(cxx::has_signature<Callable, void(T*, ArgTypes...)>::value,\n \"callable provided to TypedPublisher<T>::publishResultOf must have signature void(T*, ArgsTypes...)\");\n\n return loan().and_then([&](Sample<T>& sample) {\n c(sample.get(), std::forward<ArgTypes>(args)...);\n publish(std::move(sample));\n });\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::expected<AllocationError> TypedPublisher<T, base_publisher_t>::publishCopyOf(const T& val) noexcept\n{\n return loan().and_then([&](Sample<T>& sample) {\n *sample.get() = val; \/\/ Copy assignment of value into sample's memory allocation.\n publish(std::move(sample));\n });\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline cxx::optional<Sample<T>> TypedPublisher<T, base_publisher_t>::loanPreviousSample() noexcept\n{\n return base_publisher_t::loanPreviousSample();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::offer() noexcept\n{\n return base_publisher_t::offer();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline void TypedPublisher<T, base_publisher_t>::stopOffer() noexcept\n{\n return base_publisher_t::stopOffer();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline bool TypedPublisher<T, base_publisher_t>::isOffered() const noexcept\n{\n return base_publisher_t::isOffered();\n}\n\ntemplate <typename T, typename base_publisher_t>\ninline bool TypedPublisher<T, base_publisher_t>::hasSubscribers() const noexcept\n{\n return base_publisher_t::hasSubscribers();\n}\n\n} \/\/ namespace popo\n} \/\/ namespace iox\n\n#endif \/\/ IOX_EXPERIMENTAL_POSH_POPO_TYPED_PUBLISHER_INL\n<|endoftext|>"} {"text":"<commit_before>#ifndef OPCODE_BASE_H\n#define OPCODE_BASE_H\n#include \"csoundCore.h\"\n#include <cstdarg>\n\n\/**\n* Template base class, or pseudo-virtual base class,\n* for writing Csound opcodes in C++.\n* Derive opcode implementation classes like this:\n*\n* DerivedClass : public OpcodeBase<DerivedClass>\n* {\n* public:\n* \/\/ All output fields must be declared first as MYFLT *:\n* MYFLT *aret1;\n* \/\/ All input fields must be declared next as MYFLT *:\n* MYFLT *iarg1;\n* MYFLT *karg2;\n* MYFLT *aarg3;\n* \/\/ All internal state variables must be declared after that:\n* size_t state1;\n* double state2;\n* MYFLT state3;\n* \/\/ Declare and implement only whichever of these are required:\n* void initialize();\n* void kontrol();\n* void audio;\n* void deinitialize();\n* };\n*\/\ntemplate<typename T>\nclass OpcodeBase\n{\npublic:\n int init(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int init_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->init(reinterpret_cast<ENVIRON *>(csound));\n }\n int kontrol(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int kontrol_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->kontrol(reinterpret_cast<ENVIRON *>(csound));\n }\n int audio(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int audio_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->audio(reinterpret_cast<ENVIRON *>(csound));\n }\n int deinit(void *csound)\n {\n return NOTOK;\n }\n static int deinit_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->deinit(reinterpret_cast<ENVIRON *>(csound));\n }\n void log(ENVIRON *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n csound->MessageV(csound, 0, format, args);\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n void warn(ENVIRON *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n if(csound->GetMessageLevel(csound) & WARNMSG ||\n csound->GetDebug(csound)) {\n csound->MessageV(csound, 0, format, args);\n }\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n OPDS h;\n};\n\n#endif\n<commit_msg>Changed to use new deinit callback, removed deinit OENTRY member.<commit_after>#ifndef OPCODE_BASE_H\n#define OPCODE_BASE_H\n#include \"csoundCore.h\"\n#include <cstdarg>\n\n\/**\n * Template base class, or pseudo-virtual base class,\n * for writing Csound opcodes in C++.\n * Derive opcode implementation classes like this:\n *\n * DerivedClass : public OpcodeBase<DerivedClass>\n * {\n * public:\n * \/\/ All output fields must be declared first as MYFLT *:\n * MYFLT *aret1;\n * \/\/ All input fields must be declared next as MYFLT *:\n * MYFLT *iarg1;\n * MYFLT *karg2;\n * MYFLT *aarg3;\n * \/\/ All internal state variables must be declared after that:\n * size_t state1;\n * double state2;\n * MYFLT state3;\n * \/\/ Declare and implement only whichever of these are required:\n * void init();\n * void kontrol();\n * void audio;\n * void noteoff();\n * void deinit();\n * };\n *\/\ntemplate<typename T>\nclass OpcodeBase\n{\npublic:\n int init(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int init_(void *csound_, void *opcode_)\n {\n ENVIRON *csound = reinterpret_cast<ENVIRON *>(csound_);\n T *opcode = reinterpret_cast<T *>(opcode_);\n csound->RegisterDeinitCallback(csound, &opcode->h, OpcodeBase<T>::noteoff_);\n return opcode->init(csound);\n }\n int kontrol(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int kontrol_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->kontrol(reinterpret_cast<ENVIRON *>(csound));\n }\n int audio(ENVIRON *csound)\n {\n return NOTOK;\n }\n static int audio_(void *csound, void *opcode)\n {\n return reinterpret_cast<T *>(opcode)->audio(reinterpret_cast<ENVIRON *>(csound));\n }\n int noteoff(ENVIRON *csound)\n {\n return OK;\n }\n static int noteoff_(void *csound, void *opcode)\n {\n return reinterpret_cast< OpcodeBase<T> *>(opcode)->noteoff(reinterpret_cast<ENVIRON *>(csound));\n }\n void log(ENVIRON *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n csound->MessageV(csound, 0, format, args);\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n void warn(ENVIRON *csound, const char *format,...)\n {\n va_list args;\n va_start(args, format);\n if(csound) {\n if(csound->GetMessageLevel(csound) & WARNMSG ||\n\t csound->GetDebug(csound)) {\n\tcsound->MessageV(csound, 0, format, args);\n }\n }\n else {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n }\n OPDS h;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"storage_manager.hpp\"\n\nnamespace opossum {\n\nvoid storage_manager::add_table(std::string name, std::shared_ptr<table> tp) {\n\t_tables.insert(std::make_pair(name, std::move(tp)));\n}\n\nvoid storage_manager::print(std::ostream &out) const {\n\tout << \"===== Tables \" << std::endl;\n\n\tauto cnt = 0;\n\tfor(auto const &tab : _tables) {\n\t\tout << \"\\t table #\" << cnt << \": \\t\" << tab.first;\n\t\t\/\/ out << \"(\" << tab.second->col_count() << \"columns, \" << tab.second->row_count() << \" rows)\" << std::endl;\n\t\tout << std::endl;\n\t\tcnt++;\n\t}\n}\n\n}<commit_msg>Finished first version of storage manager's print<commit_after>#include \"storage_manager.hpp\"\n\nnamespace opossum {\n\nvoid storage_manager::add_table(std::string name, std::shared_ptr<table> tp) {\n\t_tables.insert(std::make_pair(name, std::move(tp)));\n}\n\nvoid storage_manager::print(std::ostream &out) const {\n\tout << \"==================\" << std::endl;\n\tout << \"===== Tables =====\" << std::endl << std::endl;\n\n\tauto cnt = 0;\n\tfor(auto const &tab : _tables) {\n\t\tout << \"==== table >> \" << tab.first << \" <<\";\n\t\tout << \" (\" << tab.second->col_count() << \" columns, \" << tab.second->row_count() << \" rows)\";\n\t\tout << std::endl << std::endl;\n\t\ttab.second->print();\n\t\tcnt++;\n\t}\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines);\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines);\n\ndouble deg2rad(double deg);\n\nvoid LineFollowing::detect_lines(Mat &original_frame) {\n\n Mat hsv;\n Mat mask;\n width = original_frame.cols;\n height = original_frame.rows;\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n \/\/ printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n vector<Vec2f> tmp = condense_lines(lines);\n if (tmp.size() > 0) {\n found_lines = tmp;\n }\n draw_lines(original_frame, found_lines);\n\n\n}\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines) {\n vector<Vec2f> condensed;\n vector<Vec2f> tmp_list;\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < deg2rad(20)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n return condensed;\n}\n\ndouble deg2rad(double deg) {\n return deg * (CV_PI \/ 180.0);\n}\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines) {\n for (size_t i = 0; i < lines.size(); i++) {\n float theta = lines[i][0], rho = lines[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n \/\/ cout << \"line following\\n\";\n detect_lines(control_ptr->image);\n\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n if (found_lines.size() < 1) {\n \/\/I found no lines\n \/\/ printf(\"Found nothing\\n\");\n return;\n }\n double calculated_distance = distance_from_center(found_lines[0][1], found_lines[0][0], control_ptr->image.cols,\n control_ptr->image.rows);\n\n \/\/ printf(\"calc dist of %f \", calculated_distance);\n int origin_x = 0 + (control_ptr->image.cols \/ 2);\n int origin_y = 0 + (control_ptr->image.rows \/ 2);\n Point pt1 = cvPoint(origin_x, origin_y);\n Point pt2 = cvPoint(origin_x + cvRound(calculated_distance), origin_y);\n line(control_ptr->image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n\n if (found_lines.size() > 1) {\n \/\/ I need to turn\n \/\/TODO: move until line is centered\n \/\/TODO: look for symbol, and turn\n\n Vec2i point = find_intersection(found_lines[0], found_lines[1]);\n printf(\"My coords are x: %3d y %3d\\n\", point[0], point[1]);\n line(control_ptr->image, cvPoint(point[0]+10, point[1]), cvPoint(point[0]-10, point[1]), Scalar(0, 255,0 ), 3, CV_AA);\n line(control_ptr->image, cvPoint(point[0], point[1]+10), cvPoint(point[0], point[1]-10), Scalar(0, 255,0), 3, CV_AA);\n return;\n }\n\n else {\n \/\/ I need to snap myself to the line\n if (found_lines[0][0] >= deg2rad(5)) {\n control_ptr->velocities.vr = -.2;\n printf(\"Turning Right\\n\");\n }\n else if (found_lines[0][0] <= deg2rad(-1 * 5)) {\n control_ptr->velocities.vr = .2;\n printf(\"Turning Left\\n\");\n } else {\n printf(\"Checking Distance\\n\");\n\n double offset = calculated_distance;\n \/\/ printf(\"Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\\n\", offset,\n \/\/ found_lines[0][1],\n \/\/ (double) control_ptr->image.cols, (control_ptr->image.cols \/ 2.0));\n if (-100 <= offset && offset <= 100) {\n printf(\"No need to move\\n\");\n } else if (offset < 0) {\n \/\/we are to the right of the line\n \/\/we need to move left\n control_ptr->velocities.vy = 1;\n printf(\"Move left\\n\");\n } else {\n \/\/we need to move right\n control_ptr->velocities.vy = -1;\n printf(\"Move right\\n\");\n }\n }\n }\n\n\n return;\n}\n\ndouble LineFollowing::distance_from_center(float rho, float theta, double width, double height) {\n \/\/ printf(\"width: %f height: %f\\n\", width, height);\n theta = -1 * (theta);\n double rh = rho * cos(theta);\n double rv = rho * sin(theta);\n \/\/ rh = abs(rh);\n \/\/ rv *= -1;\n double excess = (width \/ 2.0) - rh;\n \/\/ excess *=-1;\n double lv = rv + (height \/ 2.0);\n double lh = lv * tan(theta);\n \/\/ lh = abs(lh);\n double x = lh - excess;\n\n \/\/ printf(\"ro: %4f th: %4f rh: %4f rv: %4f ex: %4f lv: %4f lh: %4f x: %4f\\n\", rho, theta ,rh, rv, excess, lv,lh,x);\n\n return x;\n}\n\ncv::Vec2i LineFollowing::find_intersection(cv::Vec2f a, cv::Vec2f b) {\n Vec2i rv;\n float theta1, theta2, rho1, rho2;\n theta1 = a[0];\n rho1 = a[1];\n theta2 = b[0];\n rho2 = b[1];\n float a1 = 1 \/ atan(theta1);\n float a2 = 1 \/ atan(theta2);\n float b1 = rho1;\n float b2 = rho2;\n float x = (b2 - b1) \/ (a1 - a2);\n float y = (a1 * b2 - a2 * b1) \/ (a1 - a2);\n rv[0] = (int) round(x);\n rv[1] = (int) round(y);\n\n return rv;\n}\n<commit_msg>should have correct coordinate system for the intersection<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines);\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines);\n\ndouble deg2rad(double deg);\n\nvoid LineFollowing::detect_lines(Mat &original_frame) {\n\n Mat hsv;\n Mat mask;\n width = original_frame.cols;\n height = original_frame.rows;\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n \/\/ printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n vector<Vec2f> tmp = condense_lines(lines);\n if (tmp.size() > 0) {\n found_lines = tmp;\n }\n draw_lines(original_frame, found_lines);\n\n\n}\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines) {\n vector<Vec2f> condensed;\n vector<Vec2f> tmp_list;\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < deg2rad(20)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n return condensed;\n}\n\ndouble deg2rad(double deg) {\n return deg * (CV_PI \/ 180.0);\n}\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines) {\n for (size_t i = 0; i < lines.size(); i++) {\n float theta = lines[i][0], rho = lines[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n \/\/ cout << \"line following\\n\";\n detect_lines(control_ptr->image);\n\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n if (found_lines.size() < 1) {\n \/\/I found no lines\n \/\/ printf(\"Found nothing\\n\");\n return;\n }\n double calculated_distance = distance_from_center(found_lines[0][1], found_lines[0][0], control_ptr->image.cols,\n control_ptr->image.rows);\n\n \/\/ printf(\"calc dist of %f \", calculated_distance);\n int origin_x = 0 + (control_ptr->image.cols \/ 2);\n int origin_y = 0 + (control_ptr->image.rows \/ 2);\n Point pt1 = cvPoint(origin_x, origin_y);\n Point pt2 = cvPoint(origin_x + cvRound(calculated_distance), origin_y);\n line(control_ptr->image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n\n if (found_lines.size() > 1) {\n \/\/ I need to turn\n \/\/TODO: move until line is centered\n \/\/TODO: look for symbol, and turn\n\n Vec2i point = find_intersection(found_lines[0], found_lines[1]);\n printf(\"My coords are x: %3d y %3d\\n\", point[0], point[1]);\n line(control_ptr->image, cvPoint(origin_x + point[0]+10, origin_y+point[1]), cvPoint(origin_x+point[0]-10, origin_y+point[1]), Scalar(0, 255,0 ), 3, CV_AA);\n line(control_ptr->image, cvPoint(origin_x+point[0], origin_y+point[1]+10), cvPoint(origin_x+point[0], origin_y+point[1]-10), Scalar(0, 255,0), 3, CV_AA);\n return;\n }\n\n else {\n \/\/ I need to snap myself to the line\n if (found_lines[0][0] >= deg2rad(5)) {\n control_ptr->velocities.vr = -.2;\n printf(\"Turning Right\\n\");\n }\n else if (found_lines[0][0] <= deg2rad(-1 * 5)) {\n control_ptr->velocities.vr = .2;\n printf(\"Turning Left\\n\");\n } else {\n printf(\"Checking Distance\\n\");\n\n double offset = calculated_distance;\n \/\/ printf(\"Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\\n\", offset,\n \/\/ found_lines[0][1],\n \/\/ (double) control_ptr->image.cols, (control_ptr->image.cols \/ 2.0));\n if (-100 <= offset && offset <= 100) {\n printf(\"No need to move\\n\");\n } else if (offset < 0) {\n \/\/we are to the right of the line\n \/\/we need to move left\n control_ptr->velocities.vy = 1;\n printf(\"Move left\\n\");\n } else {\n \/\/we need to move right\n control_ptr->velocities.vy = -1;\n printf(\"Move right\\n\");\n }\n }\n }\n\n\n return;\n}\n\ndouble LineFollowing::distance_from_center(float rho, float theta, double width, double height) {\n \/\/ printf(\"width: %f height: %f\\n\", width, height);\n theta = -1 * (theta);\n double rh = rho * cos(theta);\n double rv = rho * sin(theta);\n \/\/ rh = abs(rh);\n \/\/ rv *= -1;\n double excess = (width \/ 2.0) - rh;\n \/\/ excess *=-1;\n double lv = rv + (height \/ 2.0);\n double lh = lv * tan(theta);\n \/\/ lh = abs(lh);\n double x = lh - excess;\n\n \/\/ printf(\"ro: %4f th: %4f rh: %4f rv: %4f ex: %4f lv: %4f lh: %4f x: %4f\\n\", rho, theta ,rh, rv, excess, lv,lh,x);\n\n return x;\n}\n\ncv::Vec2i LineFollowing::find_intersection(cv::Vec2f a, cv::Vec2f b) {\n Vec2i rv;\n float theta1, theta2, rho1, rho2;\n theta1 = a[0];\n rho1 = a[1];\n theta2 = b[0];\n rho2 = b[1];\n float a1 = 1 \/ atan(theta1);\n float a2 = 1 \/ atan(theta2);\n float b1 = rho1;\n float b2 = rho2;\n float x = (b2 - b1) \/ (a1 - a2);\n float y = (a1 * b2 - a2 * b1) \/ (a1 - a2);\n rv[0] = (int) round(x);\n rv[1] = (int) round(y);\n\n return rv;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2014, 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file gnss.cpp\n *\n * @author Pavel Kirienko <pavel.kirienko@gmail.com>\n * @author Andrew Chambers <achamber@gmail.com>\n *\n *\/\n\n#include \"gnss.hpp\"\n#include <drivers\/drv_hrt.h>\n#include <systemlib\/err.h>\n#include <mathlib\/mathlib.h>\n\nconst char *const UavcanGnssBridge::NAME = \"gnss\";\n\nUavcanGnssBridge::UavcanGnssBridge(uavcan::INode &node) :\n\t_node(node),\n\t_sub_fix(node),\n\t_sub_fix2(node),\n\t_report_pub(nullptr)\n{\n}\n\nint UavcanGnssBridge::init()\n{\n\tint res = _sub_fix.start(FixCbBinder(this, &UavcanGnssBridge::gnss_fix_sub_cb));\n\tif (res < 0) {\n\t\twarnx(\"GNSS fix sub failed %i\", res);\n\t\treturn res;\n\t}\n\n\tres = _sub_fix2.start(Fix2CbBinder(this, &UavcanGnssBridge::gnss_fix2_sub_cb));\n\tif (res < 0) {\n\t\twarnx(\"GNSS fix2 sub failed %i\", res);\n\t\treturn res;\n\t}\n\n\treturn res;\n}\n\nunsigned UavcanGnssBridge::get_num_redundant_channels() const\n{\n\treturn (_receiver_node_id < 0) ? 0 : 1;\n}\n\nvoid UavcanGnssBridge::print_status() const\n{\n\tprintf(\"RX errors: %d, receiver node id: \", _sub_fix.getFailureCount());\n\n\tif (_receiver_node_id < 0) {\n\t\tprintf(\"N\/A\\n\");\n\n\t} else {\n\t\tprintf(\"%d\\n\", _receiver_node_id);\n\t}\n}\n\nvoid UavcanGnssBridge::gnss_fix_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::gnss::Fix> &msg)\n{\n\tconst bool valid_pos_cov = !msg.position_covariance.empty();\n\tconst bool valid_vel_cov = !msg.velocity_covariance.empty();\n\n\tfloat pos_cov[9];\n\tmsg.position_covariance.unpackSquareMatrix(pos_cov);\n\n\tfloat vel_cov[9];\n\tmsg.velocity_covariance.unpackSquareMatrix(vel_cov);\n\n\tprocess_fixx(msg, pos_cov, vel_cov, valid_pos_cov, valid_vel_cov);\n}\n\nvoid UavcanGnssBridge::gnss_fix2_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::gnss::Fix2> &msg)\n{\n\tif (_old_fix_subscriber_active) {\n\t\twarnx(\"GNSS Fix2 message detected, disabling support for the old Fix message\");\n\t\t_sub_fix.stop();\n\t\t_old_fix_subscriber_active = false;\n\t\t_receiver_node_id = -1;\n\t}\n\n\tfloat pos_cov[9]{};\n\tfloat vel_cov[9]{};\n\tbool valid_covariances = true;\n\n\tswitch (msg.covariance.size()) {\n\t\/\/ Scalar matrix\n\tcase 1: {\n\t\tconst auto x = msg.covariance[0];\n\n\t\tpos_cov[0] = x;\n\t\tpos_cov[4] = x;\n\t\tpos_cov[8] = x;\n\n\t\tvel_cov[0] = x;\n\t\tvel_cov[4] = x;\n\t\tvel_cov[8] = x;\n\t\tbreak;\n\t}\n\n\t\/\/ Diagonal matrix (the most common case)\n\tcase 6: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[4] = msg.covariance[1];\n\t\tpos_cov[8] = msg.covariance[2];\n\n\t\tvel_cov[0] = msg.covariance[3];\n\t\tvel_cov[4] = msg.covariance[4];\n\t\tvel_cov[8] = msg.covariance[5];\n\t\tbreak;\n\t}\n\n\t\/\/ Upper triangular matrix.\n\t\/\/ This code has been carefully optimized by hand. We could use unpackSquareMatrix(), but it's slow.\n\t\/\/ Sub-matrix indexes (empty squares contain velocity-position covariance data):\n\t\/\/ 0 1 2\n\t\/\/ 1 6 7\n\t\/\/ 2 7 11\n\t\/\/ 15 16 17\n\t\/\/ 16 18 19\n\t\/\/ 17 19 20\n\tcase 21: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[1] = msg.covariance[1];\n\t\tpos_cov[2] = msg.covariance[2];\n\t\tpos_cov[3] = msg.covariance[1];\n\t\tpos_cov[4] = msg.covariance[6];\n\t\tpos_cov[5] = msg.covariance[7];\n\t\tpos_cov[6] = msg.covariance[2];\n\t\tpos_cov[7] = msg.covariance[7];\n\t\tpos_cov[8] = msg.covariance[11];\n\n\t\tvel_cov[0] = msg.covariance[15];\n\t\tvel_cov[1] = msg.covariance[16];\n\t\tvel_cov[2] = msg.covariance[17];\n\t\tvel_cov[3] = msg.covariance[16];\n\t\tvel_cov[4] = msg.covariance[18];\n\t\tvel_cov[5] = msg.covariance[19];\n\t\tvel_cov[6] = msg.covariance[17];\n\t\tvel_cov[7] = msg.covariance[19];\n\t\tvel_cov[8] = msg.covariance[20];\n\t}\n\n\t\/\/ Full matrix 6x6.\n\t\/\/ This code has been carefully optimized by hand. We could use unpackSquareMatrix(), but it's slow.\n\t\/\/ Sub-matrix indexes (empty squares contain velocity-position covariance data):\n\t\/\/ 0 1 2\n\t\/\/ 6 7 8\n\t\/\/ 12 13 14\n\t\/\/ 21 22 23\n\t\/\/ 27 28 29\n\t\/\/ 33 34 35\n\tcase 36: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[1] = msg.covariance[1];\n\t\tpos_cov[2] = msg.covariance[2];\n\t\tpos_cov[3] = msg.covariance[6];\n\t\tpos_cov[4] = msg.covariance[7];\n\t\tpos_cov[5] = msg.covariance[8];\n\t\tpos_cov[6] = msg.covariance[12];\n\t\tpos_cov[7] = msg.covariance[13];\n\t\tpos_cov[8] = msg.covariance[14];\n\n\t\tvel_cov[0] = msg.covariance[21];\n\t\tvel_cov[1] = msg.covariance[22];\n\t\tvel_cov[2] = msg.covariance[23];\n\t\tvel_cov[3] = msg.covariance[27];\n\t\tvel_cov[4] = msg.covariance[28];\n\t\tvel_cov[5] = msg.covariance[29];\n\t\tvel_cov[6] = msg.covariance[33];\n\t\tvel_cov[7] = msg.covariance[34];\n\t\tvel_cov[8] = msg.covariance[35];\n\t}\n\n\t\/\/ Either empty or invalid sized, interpret as zero matrix\n\tdefault: {\n\t\tvalid_covariances = false;\n\t\tbreak;\t\/\/ Nothing to do\n\t}\n\t}\n\n\tprocess_fixx(msg, pos_cov, vel_cov, valid_covariances, valid_covariances);\n}\n\ntemplate <typename FixType>\nvoid UavcanGnssBridge::process_fixx(const uavcan::ReceivedDataStructure<FixType> &msg,\n const float (&pos_cov)[9],\n const float (&vel_cov)[9],\n const bool valid_pos_cov,\n const bool valid_vel_cov)\n{\n\t\/\/ This bridge does not support redundant GNSS receivers yet.\n\tif (_receiver_node_id < 0) {\n\t\t_receiver_node_id = msg.getSrcNodeID().get();\n\t\twarnx(\"GNSS receiver node ID: %d\", _receiver_node_id);\n\n\t} else {\n\t\tif (_receiver_node_id != msg.getSrcNodeID().get()) {\n\t\t\treturn; \/\/ This GNSS receiver is the redundant one, ignore it.\n\t\t}\n\t}\n\n\tauto report = ::vehicle_gps_position_s();\n\n\t\/*\n\t * FIXME HACK\n\t * There used to be the following line of code:\n\t * \treport.timestamp_position = msg.getMonotonicTimestamp().toUSec();\n\t * It stopped working when the time sync feature has been introduced, because it caused libuavcan\n\t * to use an independent time source (based on hardware TIM5) instead of HRT.\n\t * The proper solution is to be developed.\n\t *\/\n\treport.timestamp = hrt_absolute_time();\n\treport.lat = msg.latitude_deg_1e8 \/ 10;\n\treport.lon = msg.longitude_deg_1e8 \/ 10;\n\treport.alt = msg.height_msl_mm;\n\n\tif (valid_pos_cov) {\n\t\t\/\/ Horizontal position uncertainty\n\t\tconst float horizontal_pos_variance = math::max(pos_cov[0], pos_cov[4]);\n\t\treport.eph = (horizontal_pos_variance > 0) ? sqrtf(horizontal_pos_variance) : -1.0F;\n\n\t\t\/\/ Vertical position uncertainty\n\t\treport.epv = (pos_cov[8] > 0) ? sqrtf(pos_cov[8]) : -1.0F;\n\n\t} else {\n\t\treport.eph = -1.0F;\n\t\treport.epv = -1.0F;\n\t}\n\n\tif (valid_vel_cov) {\n\t\treport.s_variance_m_s = math::max(math::max(vel_cov[0], vel_cov[4]), vel_cov[8]);\n\n\t\t\/* There is a nonlinear relationship between the velocity vector and the heading.\n\t\t * Use Jacobian to transform velocity covariance to heading covariance\n\t\t *\n\t\t * Nonlinear equation:\n\t\t * heading = atan2(vel_e_m_s, vel_n_m_s)\n\t\t * For math, see http:\/\/en.wikipedia.org\/wiki\/Atan2#Derivative\n\t\t *\n\t\t * To calculate the variance of heading from the variance of velocity,\n\t\t * cov(heading) = J(velocity)*cov(velocity)*J(velocity)^T\n\t\t *\/\n\t\tfloat vel_n = msg.ned_velocity[0];\n\t\tfloat vel_e = msg.ned_velocity[1];\n\t\tfloat vel_n_sq = vel_n * vel_n;\n\t\tfloat vel_e_sq = vel_e * vel_e;\n\t\treport.c_variance_rad =\n\t\t\t(vel_e_sq * vel_cov[0] +\n\t\t\t -2 * vel_n * vel_e * vel_cov[1] +\t\/\/ Covariance matrix is symmetric\n\t\t\t vel_n_sq * vel_cov[4]) \/ ((vel_n_sq + vel_e_sq) * (vel_n_sq + vel_e_sq));\n\n\t} else {\n\t\treport.s_variance_m_s = -1.0F;\n\t\treport.c_variance_rad = -1.0F;\n\t}\n\n\treport.fix_type = msg.status;\n\n\treport.vel_n_m_s = msg.ned_velocity[0];\n\treport.vel_e_m_s = msg.ned_velocity[1];\n\treport.vel_d_m_s = msg.ned_velocity[2];\n\treport.vel_m_s = sqrtf(report.vel_n_m_s * report.vel_n_m_s +\n\t report.vel_e_m_s * report.vel_e_m_s +\n\t report.vel_d_m_s * report.vel_d_m_s);\n\treport.cog_rad = atan2f(report.vel_e_m_s, report.vel_n_m_s);\n\treport.vel_ned_valid = true;\n\n\treport.timestamp_time_relative = 0;\n\treport.time_utc_usec = uavcan::UtcTime(msg.gnss_timestamp).toUSec();\t\/\/ Convert to microseconds\n\n\treport.satellites_used = msg.sats_used;\n\n\t\/\/ Using PDOP for HDOP and VDOP\n\t\/\/ Relevant discussion: https:\/\/github.com\/PX4\/Firmware\/issues\/5153\n\treport.hdop = msg.pdop;\n\treport.vdop = msg.pdop;\n\n\t\/\/ Publish to a multi-topic\n\tint32_t gps_orb_instance;\n\torb_publish_auto(ORB_ID(vehicle_gps_position), &_report_pub, &report, &gps_orb_instance,\n\t\t\t\t ORB_PRIO_HIGH);\n}\n<commit_msg>UAVCAN GNSS bridge status output shows whether support for the old Fix message is active<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2014, 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file gnss.cpp\n *\n * @author Pavel Kirienko <pavel.kirienko@gmail.com>\n * @author Andrew Chambers <achamber@gmail.com>\n *\n *\/\n\n#include \"gnss.hpp\"\n#include <drivers\/drv_hrt.h>\n#include <systemlib\/err.h>\n#include <mathlib\/mathlib.h>\n\nconst char *const UavcanGnssBridge::NAME = \"gnss\";\n\nUavcanGnssBridge::UavcanGnssBridge(uavcan::INode &node) :\n\t_node(node),\n\t_sub_fix(node),\n\t_sub_fix2(node),\n\t_report_pub(nullptr)\n{\n}\n\nint UavcanGnssBridge::init()\n{\n\tint res = _sub_fix.start(FixCbBinder(this, &UavcanGnssBridge::gnss_fix_sub_cb));\n\tif (res < 0) {\n\t\twarnx(\"GNSS fix sub failed %i\", res);\n\t\treturn res;\n\t}\n\n\tres = _sub_fix2.start(Fix2CbBinder(this, &UavcanGnssBridge::gnss_fix2_sub_cb));\n\tif (res < 0) {\n\t\twarnx(\"GNSS fix2 sub failed %i\", res);\n\t\treturn res;\n\t}\n\n\treturn res;\n}\n\nunsigned UavcanGnssBridge::get_num_redundant_channels() const\n{\n\treturn (_receiver_node_id < 0) ? 0 : 1;\n}\n\nvoid UavcanGnssBridge::print_status() const\n{\n\tprintf(\"RX errors: %d, using old Fix: %d, receiver node id: \",\n\t\t_sub_fix.getFailureCount(), int(_old_fix_subscriber_active));\n\n\tif (_receiver_node_id < 0) {\n\t\tprintf(\"N\/A\\n\");\n\n\t} else {\n\t\tprintf(\"%d\\n\", _receiver_node_id);\n\t}\n}\n\nvoid UavcanGnssBridge::gnss_fix_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::gnss::Fix> &msg)\n{\n\tconst bool valid_pos_cov = !msg.position_covariance.empty();\n\tconst bool valid_vel_cov = !msg.velocity_covariance.empty();\n\n\tfloat pos_cov[9];\n\tmsg.position_covariance.unpackSquareMatrix(pos_cov);\n\n\tfloat vel_cov[9];\n\tmsg.velocity_covariance.unpackSquareMatrix(vel_cov);\n\n\tprocess_fixx(msg, pos_cov, vel_cov, valid_pos_cov, valid_vel_cov);\n}\n\nvoid UavcanGnssBridge::gnss_fix2_sub_cb(const uavcan::ReceivedDataStructure<uavcan::equipment::gnss::Fix2> &msg)\n{\n\tif (_old_fix_subscriber_active) {\n\t\twarnx(\"GNSS Fix2 message detected, disabling support for the old Fix message\");\n\t\t_sub_fix.stop();\n\t\t_old_fix_subscriber_active = false;\n\t\t_receiver_node_id = -1;\n\t}\n\n\tfloat pos_cov[9]{};\n\tfloat vel_cov[9]{};\n\tbool valid_covariances = true;\n\n\tswitch (msg.covariance.size()) {\n\t\/\/ Scalar matrix\n\tcase 1: {\n\t\tconst auto x = msg.covariance[0];\n\n\t\tpos_cov[0] = x;\n\t\tpos_cov[4] = x;\n\t\tpos_cov[8] = x;\n\n\t\tvel_cov[0] = x;\n\t\tvel_cov[4] = x;\n\t\tvel_cov[8] = x;\n\t\tbreak;\n\t}\n\n\t\/\/ Diagonal matrix (the most common case)\n\tcase 6: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[4] = msg.covariance[1];\n\t\tpos_cov[8] = msg.covariance[2];\n\n\t\tvel_cov[0] = msg.covariance[3];\n\t\tvel_cov[4] = msg.covariance[4];\n\t\tvel_cov[8] = msg.covariance[5];\n\t\tbreak;\n\t}\n\n\t\/\/ Upper triangular matrix.\n\t\/\/ This code has been carefully optimized by hand. We could use unpackSquareMatrix(), but it's slow.\n\t\/\/ Sub-matrix indexes (empty squares contain velocity-position covariance data):\n\t\/\/ 0 1 2\n\t\/\/ 1 6 7\n\t\/\/ 2 7 11\n\t\/\/ 15 16 17\n\t\/\/ 16 18 19\n\t\/\/ 17 19 20\n\tcase 21: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[1] = msg.covariance[1];\n\t\tpos_cov[2] = msg.covariance[2];\n\t\tpos_cov[3] = msg.covariance[1];\n\t\tpos_cov[4] = msg.covariance[6];\n\t\tpos_cov[5] = msg.covariance[7];\n\t\tpos_cov[6] = msg.covariance[2];\n\t\tpos_cov[7] = msg.covariance[7];\n\t\tpos_cov[8] = msg.covariance[11];\n\n\t\tvel_cov[0] = msg.covariance[15];\n\t\tvel_cov[1] = msg.covariance[16];\n\t\tvel_cov[2] = msg.covariance[17];\n\t\tvel_cov[3] = msg.covariance[16];\n\t\tvel_cov[4] = msg.covariance[18];\n\t\tvel_cov[5] = msg.covariance[19];\n\t\tvel_cov[6] = msg.covariance[17];\n\t\tvel_cov[7] = msg.covariance[19];\n\t\tvel_cov[8] = msg.covariance[20];\n\t}\n\n\t\/\/ Full matrix 6x6.\n\t\/\/ This code has been carefully optimized by hand. We could use unpackSquareMatrix(), but it's slow.\n\t\/\/ Sub-matrix indexes (empty squares contain velocity-position covariance data):\n\t\/\/ 0 1 2\n\t\/\/ 6 7 8\n\t\/\/ 12 13 14\n\t\/\/ 21 22 23\n\t\/\/ 27 28 29\n\t\/\/ 33 34 35\n\tcase 36: {\n\t\tpos_cov[0] = msg.covariance[0];\n\t\tpos_cov[1] = msg.covariance[1];\n\t\tpos_cov[2] = msg.covariance[2];\n\t\tpos_cov[3] = msg.covariance[6];\n\t\tpos_cov[4] = msg.covariance[7];\n\t\tpos_cov[5] = msg.covariance[8];\n\t\tpos_cov[6] = msg.covariance[12];\n\t\tpos_cov[7] = msg.covariance[13];\n\t\tpos_cov[8] = msg.covariance[14];\n\n\t\tvel_cov[0] = msg.covariance[21];\n\t\tvel_cov[1] = msg.covariance[22];\n\t\tvel_cov[2] = msg.covariance[23];\n\t\tvel_cov[3] = msg.covariance[27];\n\t\tvel_cov[4] = msg.covariance[28];\n\t\tvel_cov[5] = msg.covariance[29];\n\t\tvel_cov[6] = msg.covariance[33];\n\t\tvel_cov[7] = msg.covariance[34];\n\t\tvel_cov[8] = msg.covariance[35];\n\t}\n\n\t\/\/ Either empty or invalid sized, interpret as zero matrix\n\tdefault: {\n\t\tvalid_covariances = false;\n\t\tbreak;\t\/\/ Nothing to do\n\t}\n\t}\n\n\tprocess_fixx(msg, pos_cov, vel_cov, valid_covariances, valid_covariances);\n}\n\ntemplate <typename FixType>\nvoid UavcanGnssBridge::process_fixx(const uavcan::ReceivedDataStructure<FixType> &msg,\n const float (&pos_cov)[9],\n const float (&vel_cov)[9],\n const bool valid_pos_cov,\n const bool valid_vel_cov)\n{\n\t\/\/ This bridge does not support redundant GNSS receivers yet.\n\tif (_receiver_node_id < 0) {\n\t\t_receiver_node_id = msg.getSrcNodeID().get();\n\t\twarnx(\"GNSS receiver node ID: %d\", _receiver_node_id);\n\n\t} else {\n\t\tif (_receiver_node_id != msg.getSrcNodeID().get()) {\n\t\t\treturn; \/\/ This GNSS receiver is the redundant one, ignore it.\n\t\t}\n\t}\n\n\tauto report = ::vehicle_gps_position_s();\n\n\t\/*\n\t * FIXME HACK\n\t * There used to be the following line of code:\n\t * \treport.timestamp_position = msg.getMonotonicTimestamp().toUSec();\n\t * It stopped working when the time sync feature has been introduced, because it caused libuavcan\n\t * to use an independent time source (based on hardware TIM5) instead of HRT.\n\t * The proper solution is to be developed.\n\t *\/\n\treport.timestamp = hrt_absolute_time();\n\treport.lat = msg.latitude_deg_1e8 \/ 10;\n\treport.lon = msg.longitude_deg_1e8 \/ 10;\n\treport.alt = msg.height_msl_mm;\n\n\tif (valid_pos_cov) {\n\t\t\/\/ Horizontal position uncertainty\n\t\tconst float horizontal_pos_variance = math::max(pos_cov[0], pos_cov[4]);\n\t\treport.eph = (horizontal_pos_variance > 0) ? sqrtf(horizontal_pos_variance) : -1.0F;\n\n\t\t\/\/ Vertical position uncertainty\n\t\treport.epv = (pos_cov[8] > 0) ? sqrtf(pos_cov[8]) : -1.0F;\n\n\t} else {\n\t\treport.eph = -1.0F;\n\t\treport.epv = -1.0F;\n\t}\n\n\tif (valid_vel_cov) {\n\t\treport.s_variance_m_s = math::max(math::max(vel_cov[0], vel_cov[4]), vel_cov[8]);\n\n\t\t\/* There is a nonlinear relationship between the velocity vector and the heading.\n\t\t * Use Jacobian to transform velocity covariance to heading covariance\n\t\t *\n\t\t * Nonlinear equation:\n\t\t * heading = atan2(vel_e_m_s, vel_n_m_s)\n\t\t * For math, see http:\/\/en.wikipedia.org\/wiki\/Atan2#Derivative\n\t\t *\n\t\t * To calculate the variance of heading from the variance of velocity,\n\t\t * cov(heading) = J(velocity)*cov(velocity)*J(velocity)^T\n\t\t *\/\n\t\tfloat vel_n = msg.ned_velocity[0];\n\t\tfloat vel_e = msg.ned_velocity[1];\n\t\tfloat vel_n_sq = vel_n * vel_n;\n\t\tfloat vel_e_sq = vel_e * vel_e;\n\t\treport.c_variance_rad =\n\t\t\t(vel_e_sq * vel_cov[0] +\n\t\t\t -2 * vel_n * vel_e * vel_cov[1] +\t\/\/ Covariance matrix is symmetric\n\t\t\t vel_n_sq * vel_cov[4]) \/ ((vel_n_sq + vel_e_sq) * (vel_n_sq + vel_e_sq));\n\n\t} else {\n\t\treport.s_variance_m_s = -1.0F;\n\t\treport.c_variance_rad = -1.0F;\n\t}\n\n\treport.fix_type = msg.status;\n\n\treport.vel_n_m_s = msg.ned_velocity[0];\n\treport.vel_e_m_s = msg.ned_velocity[1];\n\treport.vel_d_m_s = msg.ned_velocity[2];\n\treport.vel_m_s = sqrtf(report.vel_n_m_s * report.vel_n_m_s +\n\t report.vel_e_m_s * report.vel_e_m_s +\n\t report.vel_d_m_s * report.vel_d_m_s);\n\treport.cog_rad = atan2f(report.vel_e_m_s, report.vel_n_m_s);\n\treport.vel_ned_valid = true;\n\n\treport.timestamp_time_relative = 0;\n\treport.time_utc_usec = uavcan::UtcTime(msg.gnss_timestamp).toUSec();\t\/\/ Convert to microseconds\n\n\treport.satellites_used = msg.sats_used;\n\n\t\/\/ Using PDOP for HDOP and VDOP\n\t\/\/ Relevant discussion: https:\/\/github.com\/PX4\/Firmware\/issues\/5153\n\treport.hdop = msg.pdop;\n\treport.vdop = msg.pdop;\n\n\t\/\/ Publish to a multi-topic\n\tint32_t gps_orb_instance;\n\torb_publish_auto(ORB_ID(vehicle_gps_position), &_report_pub, &report, &gps_orb_instance,\n\t\t\t\t ORB_PRIO_HIGH);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"NavigationBar.h\"\n\n\nvoid NavigationBar::setup() {\n\tdefaultPos_ = ofVec2f(450, 20);\n\tbarPos_ = ofVec2f(0, 0);\n\tbarSize_ = ofVec2f(1, 8);\n\ttextPos_ = ofVec2f(defaultPos_);\n\tcount_ = 0;\n\ttextSwitch_ = 0;\n\tmoveSwitch_ = 0;\n\n\tloadFiles();\n\n\tofAddListener(ofEvents().update, this, &NavigationBar::moveText);\n}\n\nvoid NavigationBar::loadFiles() {\n\tloadXml();\n\tloadFont();\n\n\tmainBarImage_.load(mainBarFilename_);\n\tsideBarImage_.load(sideBarFilename_);\n}\n\nvoid NavigationBar::loadXml() {\n\txml_.load(\"Select\/NaviSettings.xml\");\n\txml_.pushTag(\"group\");\n\n\tint textValue_ = xml_.getNumTags(\"Navi\");\n\tfor (int i = 0; i < textValue_; i++) {\n\t\ttextList_.push_back(xml_.getValue(\"Navi\", \"none\", i));\n\t}\n\n\tdefaultPos_.x = xml_.getValue(\"TextStopPosX\", 0);\n\tdefaultPos_.y = xml_.getValue(\"TextStopPosY\", 0);\n\tbarPos_.x = xml_.getValue(\"BarPositionX\", 0);\n\tbarPos_.y = xml_.getValue(\"BarPositionY\", 0);\n\tbarSize_.x = xml_.getValue(\"BarSizeX\", 0);\n\tbarSize_.y = xml_.getValue(\"BarSizeY\", 0);\n\tmainBarFilename_ = xml_.getValue(\"MainBar\", \"none\");\n\tsideBarFilename_ = xml_.getValue(\"SideBar\", \"none\");\n\tfontSize_ = xml_.getValue(\"FontSize\", 0);\n\tfontScale_ = xml_.getValue(\"FontScale\", 0);\n\tfontFilename_ = xml_.getValue(\"Font\", \"none\");\n\twaitTime_ = xml_.getValue(\"TextWaitTime\", 0);\n\tmoveValue_ = xml_.getValue(\"TextMoveValue\", 0);\n\txml_.popTag();\n\n}\n\nvoid NavigationBar::loadFont() {\n\tfont_.load(fontFilename_, fontSize_);\n}\n\nvoid NavigationBar::moveText(ofEventArgs &args) {\n\tswitch (moveSwitch_) {\n\tcase 0:\n\t\tframeOutTextStart();\n\t\tbreak;\n\n\tcase 1:\n\t\tframeInTextStart();\n\t\tbreak;\n\t}\n}\n\nvoid NavigationBar::frameOutTextStart() {\n\tcount_ += ofGetLastFrameTime() * 100;\n\tif (count_ >= waitTime_ * 60) {\n\t\tmoveTextPos();\n\t\tif (textPos_.x <= -ofGetWindowWidth()) {\n\t\t\tframeOutTextEnd();\n\t\t}\n\t}\n}\n\nvoid NavigationBar::frameOutTextEnd() {\n\ttextPos_.x = ofGetWindowWidth();\n\tcount_ = 0;\n\tmoveSwitch_ = 1;\n\ttextSwitch_ += 1;\n\tif (textSwitch_ >= textList_.size()) { textSwitch_ = 0; }\n}\n\nvoid NavigationBar::frameInTextStart() {\n\tmoveTextPos();\n\tif (textPos_.x <= ofVec2f(defaultPos_).x) {\n\t\tframeInTextEnd();\n\t}\n}\n\nvoid NavigationBar::frameInTextEnd() {\n\ttextPos_ = ofVec2f(defaultPos_);\n\tmoveSwitch_ = 0;\n}\n\nvoid NavigationBar::moveTextPos() {\n\ttextPos_.x -= float(moveValue_)* (ofGetLastFrameTime() * 100);\n}\n\nvoid NavigationBar::draw() {\n\tmainBarImage_.draw(ofVec2f(barPos_), ofGetWindowWidth() \/ ofVec2f(barSize_).x, ofGetWindowHeight() \/ ofVec2f(barSize_).y);\n\n\tdrawSwitchText();\n\n\tsideBarImage_.draw(ofVec2f(barPos_), ofGetWindowWidth() \/ ofVec2f(barSize_).x, ofGetWindowHeight() \/ ofVec2f(barSize_).y);\n}\n\nvoid NavigationBar::drawGui() {\n\tImGui::Begin(\"NavigationBar\");\n\tif (ImGui::Button(\"Save\")) {\n\t\tsaveXml();\n\t}\n\tif (ImGui::Button(\"Load\")) {\n\t\tloadXml();\n\t}\n\tImGui::DragFloat2(\"TextStopPos\", defaultPos_.getPtr());\n\tImGui::DragFloat(\"FontScale\", &fontScale_, 1.0f, 500, 1000);\n\tImGui::DragInt(\"TextWaitTime\", &waitTime_, 1.0f, 1, 100);\n\tImGui::DragFloat(\"TextMoveValue\", &moveValue_, 1.0f, 15, 100);\n\tImGui::DragFloat2(\"BarPosition\", barPos_.getPtr());\n\tImGui::DragFloat2(\"BarSize\", barSize_.getPtr());\n\tImGui::End();\n}\n\nvoid NavigationBar::saveXml() {\n\txml_.pushTag(\"group\");\n\txml_.setValue(\"TextStopPosX\", defaultPos_.x);\n\txml_.setValue(\"TextStopPosY\", defaultPos_.y);\n\txml_.setValue(\"BarPositionX\", barPos_.x);\n\txml_.setValue(\"BarPositionY\", barPos_.y);\n\txml_.setValue(\"BarSizeX\", barSize_.x);\n\txml_.setValue(\"BarSizeY\", barSize_.y);\n\txml_.setValue(\"FontScale\", fontScale_);\n\txml_.setValue(\"TextWaitTime\", waitTime_);\n\txml_.setValue(\"TextMoveValue\", moveValue_);\n\txml_.popTag();\n\txml_.saveFile(\"settings.xml\");\n}\n\nvoid NavigationBar::drawSwitchText() {\n\tfor (textSwitch_; textSwitch_ < textList_.size();) {\n\t\tofSetColor(255, 255, 255);\n\n\t\tdrawText(textList_[textSwitch_]);\n\t\tbreak;\n\t}\n}\n\nvoid NavigationBar::drawText(string& text) {\n\tofPushMatrix();\n\n\tfloat fontWidth = font_.stringWidth(text);\n\tfloat fontHeight = font_.stringHeight(text);\n\n\tofTranslate(textPos_);\n\tofScale((ofGetWindowWidth() \/ (fontScale_)),\n\t\t(ofGetWindowHeight() \/ fontScale_), 1);\n\tfont_.drawString(text, -fontWidth \/ 2, fontHeight);\n\n\tofPopMatrix();\n}\n<commit_msg>update<commit_after>\n#include \"navigationBar.h\"\n\n\nvoid NavigationBar::setup() {\n\tdefaultPos_ = ofVec2f(450, 20);\n\tbarPos_ = ofVec2f(0, 0);\n\tbarSize_ = ofVec2f(1, 8);\n\ttextPos_ = ofVec2f(defaultPos_);\n\tcount_ = 0;\n\ttextSwitch_ = 0;\n\tmoveSwitch_ = 0;\n\n\tloadFiles();\n\n\tofAddListener(ofEvents().update, this, &NavigationBar::moveText);\n}\n\nvoid NavigationBar::loadFiles() {\n\tloadXml();\n\tloadFont();\n\n\tmainBarImage_.load(mainBarFilename_);\n\tsideBarImage_.load(sideBarFilename_);\n}\n\nvoid NavigationBar::loadXml() {\n\txml_.load(\"Select\/NaviSettings.xml\");\n\txml_.pushTag(\"group\");\n\n\tint textValue_ = xml_.getNumTags(\"Navi\");\n\tfor (int i = 0; i < textValue_; i++) {\n\t\ttextList_.push_back(xml_.getValue(\"Navi\", \"none\", i));\n\t}\n\n\tdefaultPos_.x = xml_.getValue(\"TextStopPosX\", 0);\n\tdefaultPos_.y = xml_.getValue(\"TextStopPosY\", 0);\n\tbarPos_.x = xml_.getValue(\"BarPositionX\", 0);\n\tbarPos_.y = xml_.getValue(\"BarPositionY\", 0);\n\tbarSize_.x = xml_.getValue(\"BarSizeX\", 0);\n\tbarSize_.y = xml_.getValue(\"BarSizeY\", 0);\n\tmainBarFilename_ = xml_.getValue(\"MainBar\", \"none\");\n\tsideBarFilename_ = xml_.getValue(\"SideBar\", \"none\");\n\tfontSize_ = xml_.getValue(\"FontSize\", 0);\n\tfontScale_ = xml_.getValue(\"FontScale\", 0);\n\tfontFilename_ = xml_.getValue(\"Font\", \"none\");\n\twaitTime_ = xml_.getValue(\"TextWaitTime\", 0);\n\tmoveValue_ = xml_.getValue(\"TextMoveValue\", 0);\n\txml_.popTag();\n\n}\n\nvoid NavigationBar::loadFont() {\n\tfont_.load(fontFilename_, fontSize_);\n}\n\nvoid NavigationBar::moveText(ofEventArgs &args) {\n\tswitch (moveSwitch_) {\n\tcase 0:\n\t\tframeOutTextStart();\n\t\tbreak;\n\n\tcase 1:\n\t\tframeInTextStart();\n\t\tbreak;\n\t}\n}\n\nvoid NavigationBar::frameOutTextStart() {\n\tcount_ += ofGetLastFrameTime() * 100;\n\tif (count_ >= waitTime_ * 60) {\n\t\tmoveTextPos();\n\t\tif (textPos_.x <= -ofGetWindowWidth()) {\n\t\t\tframeOutTextEnd();\n\t\t}\n\t}\n}\n\nvoid NavigationBar::frameOutTextEnd() {\n\ttextPos_.x = ofGetWindowWidth();\n\tcount_ = 0;\n\tmoveSwitch_ = 1;\n\ttextSwitch_ += 1;\n\tif (textSwitch_ >= textList_.size()) { textSwitch_ = 0; }\n}\n\nvoid NavigationBar::frameInTextStart() {\n\tmoveTextPos();\n\tif (textPos_.x <= ofVec2f(defaultPos_).x) {\n\t\tframeInTextEnd();\n\t}\n}\n\nvoid NavigationBar::frameInTextEnd() {\n\ttextPos_ = ofVec2f(defaultPos_);\n\tmoveSwitch_ = 0;\n}\n\nvoid NavigationBar::moveTextPos() {\n\ttextPos_.x -= float(moveValue_)* (ofGetLastFrameTime() * 100);\n}\n\nvoid NavigationBar::draw() {\n\tmainBarImage_.draw(ofVec2f(barPos_), ofGetWindowWidth() \/ ofVec2f(barSize_).x, ofGetWindowHeight() \/ ofVec2f(barSize_).y);\n\n\tdrawSwitchText();\n\n\tsideBarImage_.draw(ofVec2f(barPos_), ofGetWindowWidth() \/ ofVec2f(barSize_).x, ofGetWindowHeight() \/ ofVec2f(barSize_).y);\n}\n\nvoid NavigationBar::drawGui() {\n\tImGui::Begin(\"NavigationBar\");\n\tif (ImGui::Button(\"Save\")) {\n\t\tsaveXml();\n\t}\n\tif (ImGui::Button(\"Load\")) {\n\t\tloadXml();\n\t}\n\tImGui::DragFloat2(\"TextStopPos\", defaultPos_.getPtr());\n\tImGui::DragFloat(\"FontScale\", &fontScale_, 1.0f, 500, 1000);\n\tImGui::DragInt(\"TextWaitTime\", &waitTime_, 1.0f, 1, 100);\n\tImGui::DragFloat(\"TextMoveValue\", &moveValue_, 1.0f, 15, 100);\n\tImGui::DragFloat2(\"BarPosition\", barPos_.getPtr());\n\tImGui::DragFloat2(\"BarSize\", barSize_.getPtr());\n\tImGui::End();\n}\n\nvoid NavigationBar::saveXml() {\n\txml_.pushTag(\"group\");\n\txml_.setValue(\"TextStopPosX\", defaultPos_.x);\n\txml_.setValue(\"TextStopPosY\", defaultPos_.y);\n\txml_.setValue(\"BarPositionX\", barPos_.x);\n\txml_.setValue(\"BarPositionY\", barPos_.y);\n\txml_.setValue(\"BarSizeX\", barSize_.x);\n\txml_.setValue(\"BarSizeY\", barSize_.y);\n\txml_.setValue(\"FontScale\", fontScale_);\n\txml_.setValue(\"TextWaitTime\", waitTime_);\n\txml_.setValue(\"TextMoveValue\", moveValue_);\n\txml_.popTag();\n\txml_.saveFile(\"settings.xml\");\n}\n\nvoid NavigationBar::drawSwitchText() {\n\tfor (textSwitch_; textSwitch_ < textList_.size();) {\n\t\tofSetColor(255, 255, 255);\n\n\t\tdrawText(textList_[textSwitch_]);\n\t\tbreak;\n\t}\n}\n\nvoid NavigationBar::drawText(string& text) {\n\tofPushMatrix();\n\n\tfloat fontWidth = font_.stringWidth(text);\n\tfloat fontHeight = font_.stringHeight(text);\n\n\tofTranslate(textPos_);\n\tofScale((ofGetWindowWidth() \/ (fontScale_)),\n\t\t(ofGetWindowHeight() \/ fontScale_), 1);\n\tfont_.drawString(text, -fontWidth \/ 2, fontHeight);\n\n\tofPopMatrix();\n}\n<|endoftext|>"} {"text":"<commit_before>#define EIGEN_USE_MKL_ALL\n\n#include <iostream> \/\/ for standard output\n#include <vector> \/\/ vector objects\n#include <eigen3\/Eigen\/Dense> \/\/ linear algebra library\n#include <eigen3\/unsupported\/Eigen\/KroneckerProduct> \/\/ provides tensor product\n#include <eigen3\/unsupported\/Eigen\/MatrixFunctions> \/\/ provides matrix functions\n\n#include \"constants.h\"\n#include \"qp-math.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Matrix functions\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ tensor product of many matrices\nMatrixXcd tp(const initializer_list<MatrixXcd>& list) {\n MatrixXcd out = I1;\n for (MatrixXcd elem: list) {\n out = tp(out,elem);\n }\n return out;\n}\n\n\/\/ remove numerical artifacts from a matrix\nMatrixXcd remove_artifacts(const MatrixXcd& A, const double threshold) {\n MatrixXcd B = MatrixXcd::Zero(A.rows(),A.cols());\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n B(m,n) += round(A(m,n).real()\/threshold)*threshold;\n B(m,n) += round(A(m,n).imag()\/threshold)*threshold*j;\n }\n }\n return B;\n}\n\n\/\/ get global phase of matrix\ncomplex<double> get_phase(const MatrixXcd& A, const double threshold) {\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n if (abs(A(m,n)) > threshold) {\n const complex<double> phase = A(m,n)\/abs(A(m,n));\n return phase;\n }\n }\n }\n return 1;\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Operator manipulation\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ generate matrix B to act A on qbits qs_act out of qbits_new\nMatrixXcd act(const MatrixXcd& A, const vector<uint>& qs_act, const uint qbits_new) {\n assert(A.rows() == A.cols()); \/\/ A should be square\n\n if (qs_act.size() == qbits_new) {\n bool do_nothing = true;\n for (uint i = 0; i < qbits_new; i++) {\n if (i != qs_act.at(i)) {\n do_nothing = false;\n break;\n }\n }\n if (do_nothing) return A;\n }\n\n \/\/ number of qbits A acted on\n const uint qbits_old = qs_act.size();\n assert(qbits_old == log2(A.rows()));\n\n \/\/ vector of qubits we are ignoring\n vector<uint> qs_ignore;\n for (uint i = 0; i < qbits_new; i++) {\n if (!in_vector(i,qs_act)) {\n qs_ignore.push_back(i);\n }\n }\n\n \/\/ initialize B (output) to the zero matrix\n MatrixXcd B = MatrixXcd::Zero(pow(2,qbits_new),pow(2,qbits_new));\n\n \/\/ loop over all entries A(m,n)\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n\n \/\/ get contribution of substates |m-><n-| to indices of B\n uint b_m = 0, b_n = 0;\n for (uint q = 0; q < qbits_old; q++) {\n if (qbit_state(q,qbits_old,m)) b_m += bit_int(qs_act.at(q),qbits_new);\n if (qbit_state(q,qbits_old,n)) b_n += bit_int(qs_act.at(q),qbits_new);\n }\n\n \/\/ loop over all elements of the form |ms><ns| in B\n for (uint s = 0; s < pow(2,qs_ignore.size()); s++) {\n uint b_out = b_m, b_in = b_n;\n for (uint q = 0; q < qs_ignore.size(); q++) {\n if (qbit_state(q,qs_ignore.size(),s)) {\n b_out += bit_int(qs_ignore.at(q),qbits_new);\n b_in += bit_int(qs_ignore.at(q),qbits_new);\n }\n }\n B(b_out,b_in) = A(m,n);\n }\n }\n }\n return B;\n}\n\n\/\/ perform a partial trace over qbits qs_trace\nMatrixXcd ptrace(const MatrixXcd& A, const vector<uint>& qs_trace) {\n assert(A.rows() == A.cols()); \/\/ A should be square\n\n \/\/ number of qbits A acted on\n const uint qbits_old = log2(A.rows());\n const uint qbits_new = qbits_old - qs_trace.size();\n\n \/\/ vector of qubits we are keeping\n vector<uint> qs_keep;\n for (uint i = 0; i < qbits_old; i++) {\n if (!in_vector(i,qs_trace)) qs_keep.push_back(i);\n }\n assert(qbits_new == qs_keep.size());\n\n \/\/ initialize B (output) to the zero matrix\n MatrixXcd B = MatrixXcd::Zero(pow(2,qbits_new),pow(2,qbits_new));\n\n \/\/ loop over all entries B(m,n)\n for (uint m = 0; m < B.rows(); m++) {\n for (uint n = 0; n < B.cols(); n++) {\n\n \/\/ get contribution of substates |m-><n-| to indices of A\n uint a_m = 0, a_n = 0;\n for (uint q = 0; q < qbits_new; q++) {\n if (qbit_state(q,qbits_new,m)) a_m += bit_int(qs_keep.at(q),qbits_old);\n if (qbit_state(q,qbits_new,n)) a_n += bit_int(qs_keep.at(q),qbits_old);\n }\n\n \/\/ loop over all elements of the form |ms><ns| in A\n for (uint s = 0; s < pow(2,qs_trace.size()); s++) {\n uint a_out = a_m, a_in = a_n;\n for (uint q = 0; q < qs_trace.size(); q++) {\n if (qbit_state(q,qs_trace.size(),s)) {\n a_out += bit_int(qs_trace.at(q),qbits_old);\n a_in += bit_int(qs_trace.at(q),qbits_old);\n }\n }\n B(m,n) += A(a_out,a_in);\n }\n }\n }\n return B;\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Gate decomposition and fidelity\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ returns basis element p for an operator acting on a system with N spins\nMatrixXcd U_basis_element(const uint p, const uint N) {\n const vector<MatrixXcd> spins = {I2, sx, sy, sz};\n MatrixXcd b_p = I1;\n for (uint n = 0; n < N; n++) {\n b_p = tp(b_p,spins.at(int_bit(p,2*n)+2*int_bit(p,2*n+1)));\n }\n return b_p;\n}\n\n\/\/ returns element p of a basis for operators acting on a system with N qubits\nstring U_basis_element_text(const uint p, const uint N) {\n const vector<char> spins = {'I','X','Y','Z'};\n stringstream stream;\n for (uint n = 0; n < N; n++) {\n stream << spins.at(int_bit(p,2*n)+2*int_bit(p,2*n+1));\n }\n return stream.str();\n}\n\n\/\/ returns matrix whose columns are basis Hamiltonians for a system of N spins\nMatrixXcd U_basis_matrix(const uint N) {\n MatrixXcd out = MatrixXcd::Zero(pow(4,N),pow(4,N));\n for (int p = 0; p < pow(4,N); p++) {\n out.col(p) = flatten(U_basis_element(p,N));\n }\n return out;\n}\n\n\/\/ decompose an operator into its basis elements\nVectorXcd U_decompose(const MatrixXcd& U, const bool fast) {\n const uint N = log2(U.rows());\n if (fast) return U_basis_matrix(N).householderQr().solve(flatten(U));\n else return U_basis_matrix(N).fullPivLu().solve(flatten(U));\n}\n\n\/\/ compute mean fidelity of gate U with respect to G, i.e. how well U approximates G\ndouble gate_fidelity(const MatrixXcd& U, const MatrixXcd& G) {\n assert(U.size() == G.size());\n\n const MatrixXcd Uc = remove_phase(U);\n const MatrixXcd Gc = remove_phase(G);\n\n const uint D = U.rows();\n const uint N = log2(D);\n double fidelity = D*D;\n\n for (uint i = 0; i < D*D; i++) {\n const MatrixXcd B_i = U_basis_element(i,N);\n fidelity += real(trace(Uc*B_i.adjoint()*Uc.adjoint()*Gc*B_i*Gc.adjoint()));\n }\n fidelity \/= D*D*(D+1);\n\n return fidelity;\n}\n\n\/\/ compute mean fidelity of propagator acting on system_qubits\ndouble gate_fidelity(const MatrixXcd& U, const MatrixXcd& G, const vector<uint>& nuclei) {\n assert(U.size() == G.size());\n\n const uint spins = log2(G.rows());\n vector<uint> system_qubits = {0};\n for (uint n: nuclei) system_qubits.push_back(n+1);\n\n const MatrixXcd U_err = G.adjoint() * U;\n const VectorXcd H_err_vec = U_decompose(j*log(U_err));\n\n MatrixXcd H_env = MatrixXcd::Zero(pow(2,spins),pow(2,spins));\n for (uint h = 0; h < H_err_vec.size(); h++) {\n bool add_this_element = true;\n for (uint q: system_qubits) {\n if (int_bit(h,2*q) + int_bit(h,2*q+1)) {\n add_this_element = false;\n break;\n }\n }\n if (add_this_element) H_env += H_err_vec(h)*U_basis_element(h,spins);\n }\n return gate_fidelity(U*exp(j*H_env),G);\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Matrix vectors\n\/\/ ---------------------------------------------------------------------------------------\n\nmvec operator*(const MatrixXcd& G, const mvec& v) {\n vector<MatrixXcd> out;\n for (uint i = 0; i < v.size(); i++) {\n out.push_back(G*v.at(i));\n }\n return mvec(out);\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Printing methods\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ print operator in human-readable form\nvoid U_print(const MatrixXcd& U, const double threshold) {\n const int N = log2(U.rows());\n const VectorXcd hs = remove_artifacts(U_decompose(U), threshold);\n for (int p = 0; p < pow(4,N); p++) {\n if (abs(hs(p)) != 0) {\n cout << U_basis_element_text(p,N) << \": \" << hs(p) << endl;\n }\n }\n cout << endl;\n}\n\n\/\/ print state vector in human readable form\nvoid state_print(const MatrixXcd& psi) {\n const uint N = psi.size();\n const uint qbits = log2(N);\n for (uint n = 0; n < N; n++) {\n if (abs(psi(n)) != 0) {\n cout << \"|\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,n)?\"d\":\"u\");\n }\n cout << \"> \" << psi(n) << endl;\n }\n }\n cout << endl;\n}\n\n\/\/ print matrix in human readable form\nvoid matrix_print(const MatrixXcd& M) {\n const uint qbits = log2(M.rows());\n for (uint m = 0; m < M.rows(); m++) {\n for (uint n = 0; n < M.cols(); n++) {\n if (abs(M(m,n)) != 0) {\n cout << \"|\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,m)?\"d\":\"u\");\n }\n cout << \"><\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,n)?\"d\":\"u\");\n }\n cout << \"| \" << M(m,n) << endl;\n }\n }\n }\n cout << endl;\n}\n<commit_msg>changed int to uint<commit_after>#define EIGEN_USE_MKL_ALL\n\n#include <iostream> \/\/ for standard output\n#include <vector> \/\/ vector objects\n#include <eigen3\/Eigen\/Dense> \/\/ linear algebra library\n#include <eigen3\/unsupported\/Eigen\/KroneckerProduct> \/\/ provides tensor product\n#include <eigen3\/unsupported\/Eigen\/MatrixFunctions> \/\/ provides matrix functions\n\n#include \"constants.h\"\n#include \"qp-math.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Matrix functions\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ tensor product of many matrices\nMatrixXcd tp(const initializer_list<MatrixXcd>& list) {\n MatrixXcd out = I1;\n for (MatrixXcd elem: list) {\n out = tp(out,elem);\n }\n return out;\n}\n\n\/\/ remove numerical artifacts from a matrix\nMatrixXcd remove_artifacts(const MatrixXcd& A, const double threshold) {\n MatrixXcd B = MatrixXcd::Zero(A.rows(),A.cols());\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n B(m,n) += round(A(m,n).real()\/threshold)*threshold;\n B(m,n) += round(A(m,n).imag()\/threshold)*threshold*j;\n }\n }\n return B;\n}\n\n\/\/ get global phase of matrix\ncomplex<double> get_phase(const MatrixXcd& A, const double threshold) {\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n if (abs(A(m,n)) > threshold) {\n const complex<double> phase = A(m,n)\/abs(A(m,n));\n return phase;\n }\n }\n }\n return 1;\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Operator manipulation\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ generate matrix B to act A on qbits qs_act out of qbits_new\nMatrixXcd act(const MatrixXcd& A, const vector<uint>& qs_act, const uint qbits_new) {\n assert(A.rows() == A.cols()); \/\/ A should be square\n\n if (qs_act.size() == qbits_new) {\n bool do_nothing = true;\n for (uint i = 0; i < qbits_new; i++) {\n if (i != qs_act.at(i)) {\n do_nothing = false;\n break;\n }\n }\n if (do_nothing) return A;\n }\n\n \/\/ number of qbits A acted on\n const uint qbits_old = qs_act.size();\n assert(qbits_old == log2(A.rows()));\n\n \/\/ vector of qubits we are ignoring\n vector<uint> qs_ignore;\n for (uint i = 0; i < qbits_new; i++) {\n if (!in_vector(i,qs_act)) {\n qs_ignore.push_back(i);\n }\n }\n\n \/\/ initialize B (output) to the zero matrix\n MatrixXcd B = MatrixXcd::Zero(pow(2,qbits_new),pow(2,qbits_new));\n\n \/\/ loop over all entries A(m,n)\n for (uint m = 0; m < A.rows(); m++) {\n for (uint n = 0; n < A.cols(); n++) {\n\n \/\/ get contribution of substates |m-><n-| to indices of B\n uint b_m = 0, b_n = 0;\n for (uint q = 0; q < qbits_old; q++) {\n if (qbit_state(q,qbits_old,m)) b_m += bit_int(qs_act.at(q),qbits_new);\n if (qbit_state(q,qbits_old,n)) b_n += bit_int(qs_act.at(q),qbits_new);\n }\n\n \/\/ loop over all elements of the form |ms><ns| in B\n for (uint s = 0; s < pow(2,qs_ignore.size()); s++) {\n uint b_out = b_m, b_in = b_n;\n for (uint q = 0; q < qs_ignore.size(); q++) {\n if (qbit_state(q,qs_ignore.size(),s)) {\n b_out += bit_int(qs_ignore.at(q),qbits_new);\n b_in += bit_int(qs_ignore.at(q),qbits_new);\n }\n }\n B(b_out,b_in) = A(m,n);\n }\n }\n }\n return B;\n}\n\n\/\/ perform a partial trace over qbits qs_trace\nMatrixXcd ptrace(const MatrixXcd& A, const vector<uint>& qs_trace) {\n assert(A.rows() == A.cols()); \/\/ A should be square\n\n \/\/ number of qbits A acted on\n const uint qbits_old = log2(A.rows());\n const uint qbits_new = qbits_old - qs_trace.size();\n\n \/\/ vector of qubits we are keeping\n vector<uint> qs_keep;\n for (uint i = 0; i < qbits_old; i++) {\n if (!in_vector(i,qs_trace)) qs_keep.push_back(i);\n }\n assert(qbits_new == qs_keep.size());\n\n \/\/ initialize B (output) to the zero matrix\n MatrixXcd B = MatrixXcd::Zero(pow(2,qbits_new),pow(2,qbits_new));\n\n \/\/ loop over all entries B(m,n)\n for (uint m = 0; m < B.rows(); m++) {\n for (uint n = 0; n < B.cols(); n++) {\n\n \/\/ get contribution of substates |m-><n-| to indices of A\n uint a_m = 0, a_n = 0;\n for (uint q = 0; q < qbits_new; q++) {\n if (qbit_state(q,qbits_new,m)) a_m += bit_int(qs_keep.at(q),qbits_old);\n if (qbit_state(q,qbits_new,n)) a_n += bit_int(qs_keep.at(q),qbits_old);\n }\n\n \/\/ loop over all elements of the form |ms><ns| in A\n for (uint s = 0; s < pow(2,qs_trace.size()); s++) {\n uint a_out = a_m, a_in = a_n;\n for (uint q = 0; q < qs_trace.size(); q++) {\n if (qbit_state(q,qs_trace.size(),s)) {\n a_out += bit_int(qs_trace.at(q),qbits_old);\n a_in += bit_int(qs_trace.at(q),qbits_old);\n }\n }\n B(m,n) += A(a_out,a_in);\n }\n }\n }\n return B;\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Gate decomposition and fidelity\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ returns basis element p for an operator acting on a system with N spins\nMatrixXcd U_basis_element(const uint p, const uint N) {\n const vector<MatrixXcd> spins = {I2, sx, sy, sz};\n MatrixXcd b_p = I1;\n for (uint n = 0; n < N; n++) {\n b_p = tp(b_p,spins.at(int_bit(p,2*n)+2*int_bit(p,2*n+1)));\n }\n return b_p;\n}\n\n\/\/ returns element p of a basis for operators acting on a system with N qubits\nstring U_basis_element_text(const uint p, const uint N) {\n const vector<char> spins = {'I','X','Y','Z'};\n stringstream stream;\n for (uint n = 0; n < N; n++) {\n stream << spins.at(int_bit(p,2*n)+2*int_bit(p,2*n+1));\n }\n return stream.str();\n}\n\n\/\/ returns matrix whose columns are basis Hamiltonians for a system of N spins\nMatrixXcd U_basis_matrix(const uint N) {\n MatrixXcd out = MatrixXcd::Zero(pow(4,N),pow(4,N));\n for (uint p = 0; p < pow(4,N); p++) {\n out.col(p) = flatten(U_basis_element(p,N));\n }\n return out;\n}\n\n\/\/ decompose an operator into its basis elements\nVectorXcd U_decompose(const MatrixXcd& U, const bool fast) {\n const uint N = log2(U.rows());\n if (fast) return U_basis_matrix(N).householderQr().solve(flatten(U));\n else return U_basis_matrix(N).fullPivLu().solve(flatten(U));\n}\n\n\/\/ compute mean fidelity of gate U with respect to G, i.e. how well U approximates G\ndouble gate_fidelity(const MatrixXcd& U, const MatrixXcd& G) {\n assert(U.size() == G.size());\n\n const MatrixXcd Uc = remove_phase(U);\n const MatrixXcd Gc = remove_phase(G);\n\n const uint D = U.rows();\n const uint N = log2(D);\n double fidelity = D*D;\n\n for (uint i = 0; i < D*D; i++) {\n const MatrixXcd B_i = U_basis_element(i,N);\n fidelity += real(trace(Uc*B_i.adjoint()*Uc.adjoint()*Gc*B_i*Gc.adjoint()));\n }\n fidelity \/= D*D*(D+1);\n\n return fidelity;\n}\n\n\/\/ compute mean fidelity of propagator acting on system_qubits\ndouble gate_fidelity(const MatrixXcd& U, const MatrixXcd& G, const vector<uint>& nuclei) {\n assert(U.size() == G.size());\n\n const uint spins = log2(G.rows());\n vector<uint> system_qubits = {0};\n for (uint n: nuclei) system_qubits.push_back(n+1);\n\n const MatrixXcd U_err = G.adjoint() * U;\n const VectorXcd H_err_vec = U_decompose(j*log(U_err));\n\n MatrixXcd H_env = MatrixXcd::Zero(pow(2,spins),pow(2,spins));\n for (uint h = 0; h < H_err_vec.size(); h++) {\n bool add_this_element = true;\n for (uint q: system_qubits) {\n if (int_bit(h,2*q) + int_bit(h,2*q+1)) {\n add_this_element = false;\n break;\n }\n }\n if (add_this_element) H_env += H_err_vec(h)*U_basis_element(h,spins);\n }\n return gate_fidelity(U*exp(j*H_env),G);\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Matrix vectors\n\/\/ ---------------------------------------------------------------------------------------\n\nmvec operator*(const MatrixXcd& G, const mvec& v) {\n vector<MatrixXcd> out;\n for (uint i = 0; i < v.size(); i++) {\n out.push_back(G*v.at(i));\n }\n return mvec(out);\n}\n\n\/\/ ---------------------------------------------------------------------------------------\n\/\/ Printing methods\n\/\/ ---------------------------------------------------------------------------------------\n\n\/\/ print operator in human-readable form\nvoid U_print(const MatrixXcd& U, const double threshold) {\n const int N = log2(U.rows());\n const VectorXcd hs = remove_artifacts(U_decompose(U), threshold);\n for (int p = 0; p < pow(4,N); p++) {\n if (abs(hs(p)) != 0) {\n cout << U_basis_element_text(p,N) << \": \" << hs(p) << endl;\n }\n }\n cout << endl;\n}\n\n\/\/ print state vector in human readable form\nvoid state_print(const MatrixXcd& psi) {\n const uint N = psi.size();\n const uint qbits = log2(N);\n for (uint n = 0; n < N; n++) {\n if (abs(psi(n)) != 0) {\n cout << \"|\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,n)?\"d\":\"u\");\n }\n cout << \"> \" << psi(n) << endl;\n }\n }\n cout << endl;\n}\n\n\/\/ print matrix in human readable form\nvoid matrix_print(const MatrixXcd& M) {\n const uint qbits = log2(M.rows());\n for (uint m = 0; m < M.rows(); m++) {\n for (uint n = 0; n < M.cols(); n++) {\n if (abs(M(m,n)) != 0) {\n cout << \"|\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,m)?\"d\":\"u\");\n }\n cout << \"><\";\n for (uint q = 0; q < qbits; q++) {\n cout << (qbit_state(q,qbits,n)?\"d\":\"u\");\n }\n cout << \"| \" << M(m,n) << endl;\n }\n }\n }\n cout << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"command.hh\"\n#include \"store-api.hh\"\n#include \"references.hh\"\n\nusing namespace nix;\n\nstruct CmdMakeContentAddressable : StorePathsCommand\n{\n CmdMakeContentAddressable()\n {\n realiseMode = Build;\n }\n\n std::string name() override\n {\n return \"make-content-addressable\";\n }\n\n std::string description() override\n {\n return \"rewrite a path or closure to content-addressable form\";\n }\n\n Examples examples() override\n {\n return {\n Example{\n \"To create a content-addressable representation of GNU Hello (but not its dependencies):\",\n \"nix make-content-addressable nixpkgs.hello\"\n },\n Example{\n \"To compute a content-addressable representation of the current NixOS system closure:\",\n \"nix make-content-addressable -r \/run\/current-system\"\n },\n };\n }\n void run(ref<Store> store, Paths storePaths) override\n {\n auto paths = store->topoSortPaths(PathSet(storePaths.begin(), storePaths.end()));\n\n paths.reverse();\n\n std::map<Path, Path> remappings;\n\n for (auto & path : paths) {\n auto oldInfo = store->queryPathInfo(path);\n auto oldHashPart = storePathToHash(path);\n auto name = storePathToName(path);\n\n StringSink sink;\n store->narFromPath(path, sink);\n\n StringMap rewrites;\n\n ValidPathInfo info;\n for (auto & ref : oldInfo->references) {\n if (ref == path)\n info.references.insert(\"self\");\n else {\n auto replacement = get(remappings, ref, ref);\n \/\/ FIXME: warn about unremapped paths?\n info.references.insert(replacement);\n if (replacement != ref)\n rewrites[storePathToHash(ref)] = storePathToHash(replacement);\n }\n }\n\n *sink.s = rewriteStrings(*sink.s, rewrites);\n\n HashModuloSink hashModuloSink(htSHA256, oldHashPart);\n hashModuloSink((unsigned char *) sink.s->data(), sink.s->size());\n\n info.narHash = hashModuloSink.finish().first;\n info.narSize = sink.s->size();\n replaceInSet(info.references, path, std::string(\"self\"));\n info.path = store->makeFixedOutputPath(true, info.narHash, name, info.references);\n replaceInSet(info.references, std::string(\"self\"), info.path);\n info.ca = makeFixedOutputCA(true, info.narHash);\n\n printError(\"rewrote '%s' to '%s'\", path, info.path);\n\n auto source = sinkToSource([&](Sink & nextSink) {\n RewritingSink rsink2(oldHashPart, storePathToHash(info.path), nextSink);\n rsink2((unsigned char *) sink.s->data(), sink.s->size());\n rsink2.flush();\n });\n\n store->addToStore(info, *source);\n\n remappings[path] = info.path;\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref<CmdMakeContentAddressable>());\n<commit_msg>Revert \"nix make-content-addressable: Add examples\"<commit_after>#include \"command.hh\"\n#include \"store-api.hh\"\n#include \"references.hh\"\n\nusing namespace nix;\n\nstruct CmdMakeContentAddressable : StorePathsCommand\n{\n CmdMakeContentAddressable()\n {\n realiseMode = Build;\n }\n\n std::string name() override\n {\n return \"make-content-addressable\";\n }\n\n std::string description() override\n {\n return \"test\";\n }\n\n void run(ref<Store> store, Paths storePaths) override\n {\n auto paths = store->topoSortPaths(PathSet(storePaths.begin(), storePaths.end()));\n\n paths.reverse();\n\n std::map<Path, Path> remappings;\n\n for (auto & path : paths) {\n auto oldInfo = store->queryPathInfo(path);\n auto oldHashPart = storePathToHash(path);\n auto name = storePathToName(path);\n\n StringSink sink;\n store->narFromPath(path, sink);\n\n StringMap rewrites;\n\n ValidPathInfo info;\n for (auto & ref : oldInfo->references) {\n if (ref == path)\n info.references.insert(\"self\");\n else {\n auto replacement = get(remappings, ref, ref);\n \/\/ FIXME: warn about unremapped paths?\n info.references.insert(replacement);\n if (replacement != ref)\n rewrites[storePathToHash(ref)] = storePathToHash(replacement);\n }\n }\n\n *sink.s = rewriteStrings(*sink.s, rewrites);\n\n HashModuloSink hashModuloSink(htSHA256, oldHashPart);\n hashModuloSink((unsigned char *) sink.s->data(), sink.s->size());\n\n info.narHash = hashModuloSink.finish().first;\n info.narSize = sink.s->size();\n replaceInSet(info.references, path, std::string(\"self\"));\n info.path = store->makeFixedOutputPath(true, info.narHash, name, info.references);\n replaceInSet(info.references, std::string(\"self\"), info.path);\n info.ca = makeFixedOutputCA(true, info.narHash);\n\n printError(\"rewrote '%s' to '%s'\", path, info.path);\n\n auto source = sinkToSource([&](Sink & nextSink) {\n RewritingSink rsink2(oldHashPart, storePathToHash(info.path), nextSink);\n rsink2((unsigned char *) sink.s->data(), sink.s->size());\n rsink2.flush();\n });\n\n store->addToStore(info, *source);\n\n remappings[path] = info.path;\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref<CmdMakeContentAddressable>());\n<|endoftext|>"} {"text":"<commit_before><commit_msg>adjustment implementation<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ (C) Copyright 2017, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream> \/\/ for cout\n\n#include \"include_gunit.h\"\n#include \"scanutils.h\"\n\nnamespace {\n\nclass ScanutilsTest : public ::testing::Test {\n protected:\n void SetUp() override {\n }\n};\n\nTEST_F(ScanutilsTest, DoesScanf) {\n \/\/ This test verifies that tfscanf does Scanf the same as stdio fscanf.\n \/\/ There are probably a gazillion more test cases that could be added, but\n \/\/ these brought the tesseract and unittest test results in line.\n std::string filename = file::JoinPath(TESTDATA_DIR, \"scanftest.txt\");\n FILE* fp1 = fopen(filename.c_str(), \"r\");\n if (fp1 == nullptr) {\n std::cout << \"Failed to open file \" << filename << '\\n';\n GTEST_SKIP();\n return;\n }\n FILE* fp2 = fopen(filename.c_str(), \"r\");\n if (fp2 == nullptr) {\n std::cout << \"Failed to open file \" << filename << '\\n';\n GTEST_SKIP();\n fclose(fp1);\n return;\n }\n \/\/ The file contains this:\n \/\/ 42.5 17 0.001000 -0.001000\n \/\/ 0 1 123 -123 0x100\n \/\/ abcdefghijklmnopqrstuvwxyz\n \/\/ abcdefghijklmnopqrstuvwxyz\n \/\/ MF 25 6.25e-2 0.5e5 -1e+4\n \/\/ 42 MF 25 6.25e-2 0.5\n \/\/ 24\n const int kNumFloats = 4;\n float f1[kNumFloats], f2[kNumFloats];\n int r1 = fscanf(fp1, \"%f %f %f %f\", &f1[0], &f1[1], &f1[2], &f1[3]);\n int r2 = tfscanf(fp2, \"%f %f %f %f\", &f2[0], &f2[1], &f2[2], &f2[3]);\n EXPECT_EQ(r1, kNumFloats);\n EXPECT_EQ(r2, kNumFloats);\n if (r1 == r2) {\n for (int i = 0; i < r1; ++i) {\n EXPECT_FLOAT_EQ(f1[i], f2[i]);\n }\n }\n const int kNumInts = 5;\n int i1[kNumInts], i2[kNumInts];\n r1 = fscanf(fp1, \"%d %d %d %d %i\", &i1[0], &i1[1], &i1[2], &i1[3], &i1[4]);\n r2 = tfscanf(fp2, \"%d %d %d %d %i\", &i2[0], &i2[1], &i2[2], &i2[3], &i2[4]);\n EXPECT_EQ(r1, kNumInts);\n EXPECT_EQ(r2, kNumInts);\n if (r1 == r2) {\n for (int i = 0; i < kNumInts; ++i) {\n EXPECT_EQ(i1[i], i2[i]);\n }\n }\n const int kStrLen = 1024;\n char s1[kStrLen];\n char s2[kStrLen];\n r1 = fscanf(fp1, \"%1023s\", s1);\n r2 = tfscanf(fp2, \"%1023s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(26, strlen(s2));\n r1 = fscanf(fp1, \"%20s\", s1);\n r2 = tfscanf(fp2, \"%20s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(20, strlen(s2));\n \/\/ Now read the rest of the alphabet.\n r1 = fscanf(fp1, \"%s\", s1);\n r2 = tfscanf(fp2, \"%s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(6, strlen(s2));\n r1 = fscanf(fp1, \"%s\", s1);\n r2 = tfscanf(fp2, \"%s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(2, strlen(s2));\n r1 = fscanf(fp1, \"%f %f %f %f\", &f1[0], &f1[1], &f1[2], &f1[3]);\n r2 = tfscanf(fp2, \"%f %f %f %f\", &f2[0], &f2[1], &f2[2], &f2[3]);\n EXPECT_EQ(r1, r2);\n for (int i = 0; i < kNumFloats; ++i) EXPECT_FLOAT_EQ(f1[i], f2[i]);\n \/\/ Test the * for field suppression.\n r1 = fscanf(fp1, \"%d %*s %*d %*f %*f\", &i1[0]);\n r2 = tfscanf(fp2, \"%d %*s %*d %*f %*f\", &i2[0]);\n EXPECT_EQ(r1, r2);\n EXPECT_EQ(i1[0], i2[0]);\n \/\/ We should still see the next value and no phantoms.\n r1 = fscanf(fp1, \"%d %s\", &i1[0], s1);\n r2 = tfscanf(fp2, \"%d %s\", &i2[0], s2);\n EXPECT_EQ(r1, r2);\n EXPECT_EQ(1, r2);\n EXPECT_EQ(i1[0], i2[0]);\n fclose(fp2);\n fclose(fp1);\n}\n\n} \/\/ namespace\n<commit_msg>unittest: Add missing precision specifiers (CID 1402752)<commit_after>\/\/ (C) Copyright 2017, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream> \/\/ for cout\n\n#include \"include_gunit.h\"\n#include \"scanutils.h\"\n\nnamespace {\n\nclass ScanutilsTest : public ::testing::Test {\n protected:\n void SetUp() override {\n }\n};\n\nTEST_F(ScanutilsTest, DoesScanf) {\n \/\/ This test verifies that tfscanf does Scanf the same as stdio fscanf.\n \/\/ There are probably a gazillion more test cases that could be added, but\n \/\/ these brought the tesseract and unittest test results in line.\n std::string filename = file::JoinPath(TESTDATA_DIR, \"scanftest.txt\");\n FILE* fp1 = fopen(filename.c_str(), \"r\");\n if (fp1 == nullptr) {\n std::cout << \"Failed to open file \" << filename << '\\n';\n GTEST_SKIP();\n return;\n }\n FILE* fp2 = fopen(filename.c_str(), \"r\");\n if (fp2 == nullptr) {\n std::cout << \"Failed to open file \" << filename << '\\n';\n GTEST_SKIP();\n fclose(fp1);\n return;\n }\n \/\/ The file contains this:\n \/\/ 42.5 17 0.001000 -0.001000\n \/\/ 0 1 123 -123 0x100\n \/\/ abcdefghijklmnopqrstuvwxyz\n \/\/ abcdefghijklmnopqrstuvwxyz\n \/\/ MF 25 6.25e-2 0.5e5 -1e+4\n \/\/ 42 MF 25 6.25e-2 0.5\n \/\/ 24\n const int kNumFloats = 4;\n float f1[kNumFloats], f2[kNumFloats];\n int r1 = fscanf(fp1, \"%f %f %f %f\", &f1[0], &f1[1], &f1[2], &f1[3]);\n int r2 = tfscanf(fp2, \"%f %f %f %f\", &f2[0], &f2[1], &f2[2], &f2[3]);\n EXPECT_EQ(r1, kNumFloats);\n EXPECT_EQ(r2, kNumFloats);\n if (r1 == r2) {\n for (int i = 0; i < r1; ++i) {\n EXPECT_FLOAT_EQ(f1[i], f2[i]);\n }\n }\n const int kNumInts = 5;\n int i1[kNumInts], i2[kNumInts];\n r1 = fscanf(fp1, \"%d %d %d %d %i\", &i1[0], &i1[1], &i1[2], &i1[3], &i1[4]);\n r2 = tfscanf(fp2, \"%d %d %d %d %i\", &i2[0], &i2[1], &i2[2], &i2[3], &i2[4]);\n EXPECT_EQ(r1, kNumInts);\n EXPECT_EQ(r2, kNumInts);\n if (r1 == r2) {\n for (int i = 0; i < kNumInts; ++i) {\n EXPECT_EQ(i1[i], i2[i]);\n }\n }\n const int kStrLen = 1024;\n char s1[kStrLen];\n char s2[kStrLen];\n r1 = fscanf(fp1, \"%1023s\", s1);\n r2 = tfscanf(fp2, \"%1023s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(26, strlen(s2));\n r1 = fscanf(fp1, \"%20s\", s1);\n r2 = tfscanf(fp2, \"%20s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(20, strlen(s2));\n \/\/ Now read the rest of the alphabet.\n r1 = fscanf(fp1, \"%1023s\", s1);\n r2 = tfscanf(fp2, \"%1023s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(6, strlen(s2));\n r1 = fscanf(fp1, \"%1023s\", s1);\n r2 = tfscanf(fp2, \"%1023s\", s2);\n EXPECT_EQ(r1, r2);\n EXPECT_STREQ(s1, s2);\n EXPECT_EQ(2, strlen(s2));\n r1 = fscanf(fp1, \"%f %f %f %f\", &f1[0], &f1[1], &f1[2], &f1[3]);\n r2 = tfscanf(fp2, \"%f %f %f %f\", &f2[0], &f2[1], &f2[2], &f2[3]);\n EXPECT_EQ(r1, r2);\n for (int i = 0; i < kNumFloats; ++i) EXPECT_FLOAT_EQ(f1[i], f2[i]);\n \/\/ Test the * for field suppression.\n r1 = fscanf(fp1, \"%d %*s %*d %*f %*f\", &i1[0]);\n r2 = tfscanf(fp2, \"%d %*s %*d %*f %*f\", &i2[0]);\n EXPECT_EQ(r1, r2);\n EXPECT_EQ(i1[0], i2[0]);\n \/\/ We should still see the next value and no phantoms.\n r1 = fscanf(fp1, \"%d %1023s\", &i1[0], s1);\n r2 = tfscanf(fp2, \"%d %1023s\", &i2[0], s2);\n EXPECT_EQ(r1, r2);\n EXPECT_EQ(1, r2);\n EXPECT_EQ(i1[0], i2[0]);\n fclose(fp2);\n fclose(fp1);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before><commit_msg>vcldemo: include new text demo<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attr.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: ihi $ $Date: 2008-02-04 13:55:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"attr.hxx\"\n#include \"element.hxx\"\n#include <com\/sun\/star\/xml\/dom\/DOMException.hdl>\n#include <string.h>\n\nnamespace DOM\n{\n CAttr::CAttr(const xmlAttrPtr pAttr)\n {\n m_aAttrPtr = pAttr;\n m_aNodeType = NodeType_ATTRIBUTE_NODE;\n init_node((xmlNodePtr)pAttr);\n }\n\n OUString SAL_CALL CAttr::getNodeName()\n throw (RuntimeException)\n {\n return getName();\n }\n OUString SAL_CALL CAttr::getNodeValue()\n throw (RuntimeException)\n {\n return getValue();\n }\n\n\n \/**\n Returns the name of this attribute.\n *\/\n OUString SAL_CALL CAttr::getName() throw (RuntimeException)\n {\n OUString aName;\n if (m_aAttrPtr != NULL)\n {\n aName = OUString((char*)m_aAttrPtr->name, strlen((char*)m_aAttrPtr->name), RTL_TEXTENCODING_UTF8);\n }\n return aName;\n }\n\n \/**\n The Element node this attribute is attached to or null if this\n attribute is not in use.\n *\/\n Reference< XElement > SAL_CALL CAttr::getOwnerElement()\n throw (RuntimeException)\n {\n Reference< XElement > aElement;\n if (m_aAttrPtr != NULL && m_aAttrPtr->parent != NULL)\n {\n aElement = Reference< XElement >(static_cast< CElement* >(CNode::get(m_aAttrPtr->parent)));\n }\n return aElement;\n }\n\n \/**\n If this attribute was explicitly given a value in the original\n document, this is true; otherwise, it is false.\n *\/\n sal_Bool SAL_CALL CAttr::getSpecified()\n throw (RuntimeException)\n {\n \/\/ XXX what is this supposed do exactly?\n return sal_False;\n }\n\n \/**\n On retrieval, the value of the attribute is returned as a string.\n *\/\n OUString SAL_CALL CAttr::getValue()\n throw (RuntimeException)\n {\n OUString aName;\n if (m_aAttrPtr != NULL && m_aAttrPtr->children != NULL)\n {\n aName = OUString((char*)m_aAttrPtr->children->content, strlen((char*)m_aAttrPtr->children->content),\n RTL_TEXTENCODING_UTF8);\n }\n return aName;\n }\n\n \/**\n Sets the value of the attribute from a string.\n *\/\n void SAL_CALL CAttr::setValue(const OUString& value)\n throw (RuntimeException, DOMException)\n {\n \/\/ remember old value (for mutation event)\n OUString sOldValue = getValue();\n\n OString o1 = OUStringToOString(value, RTL_TEXTENCODING_UTF8);\n xmlChar* xValue = (xmlChar*)o1.getStr();\n \/\/ xmlChar* xName = OUStringToOString(m_aAttrPtr->name, RTL_TEXTENCODING_UTF8).getStr();\n \/\/ this does not work if the attribute was created anew\n \/\/ xmlNodePtr pNode = m_aAttrPtr->parent;\n \/\/ xmlSetProp(pNode, m_aAttrPtr->name, xValue);\n xmlChar *buffer = xmlEncodeEntitiesReentrant(m_aAttrPtr->doc, xValue);\n m_aAttrPtr->children = xmlStringGetNodeList(m_aAttrPtr->doc, buffer);\n xmlNodePtr tmp = m_aAttrPtr->children;\n while (tmp != NULL) {\n tmp->parent = (xmlNodePtr) m_aNodePtr;\n tmp->doc = m_aAttrPtr->doc;\n if (tmp->next == NULL)\n m_aNodePtr->last = tmp;\n tmp = tmp->next;\n }\n\n \/\/ dispatch DOM events to signal change in attribute value\n \/\/ dispatch DomAttrModified + DOMSubtreeModified\n OUString sEventName( RTL_CONSTASCII_USTRINGPARAM(\"DOMAttrModified\") );\n Reference< XDocumentEvent > docevent(getOwnerDocument(), UNO_QUERY);\n Reference< XMutationEvent > event(docevent->createEvent(sEventName),UNO_QUERY);\n event->initMutationEvent(\n sEventName, sal_True, sal_False,\n Reference<XNode>( static_cast<XAttr*>( this ) ),\n sOldValue, value, getName(), AttrChangeType_MODIFICATION );\n dispatchEvent(Reference< XEvent >(event, UNO_QUERY));\n dispatchSubtreeModified();\n xmlFree(buffer);\n }\n\n}\n<commit_msg>INTEGRATION: CWS custommeta (1.6.58); FILE MERGED 2008\/02\/26 10:40:38 mst 1.6.58.3: RESYNC: (1.7-1.8); FILE MERGED 2008\/02\/01 10:36:04 mst 1.6.58.2: RESYNC: (1.6-1.7); FILE MERGED 2007\/12\/07 14:05:56 mst 1.6.58.1: - unoxml\/source\/dom\/document.{hxx,cxx}: implement interface css::xml::sax::XSAXSerializable - unoxml\/source\/dom\/*.{hxx,cxx}: add virtual method saxify() on all subclasses of CNode add missing implementations of getLocalName()<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attr.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2008-02-26 14:46:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"attr.hxx\"\n#include \"element.hxx\"\n#include <com\/sun\/star\/xml\/dom\/DOMException.hdl>\n#include <string.h>\n\nnamespace DOM\n{\n CAttr::CAttr(const xmlAttrPtr pAttr)\n {\n m_aAttrPtr = pAttr;\n m_aNodeType = NodeType_ATTRIBUTE_NODE;\n init_node((xmlNodePtr)pAttr);\n }\n\n OUString SAL_CALL CAttr::getNodeName()\n throw (RuntimeException)\n {\n return getName();\n }\n OUString SAL_CALL CAttr::getNodeValue()\n throw (RuntimeException)\n {\n return getValue();\n }\n OUString SAL_CALL CAttr::getLocalName()\n throw (RuntimeException)\n {\n return getName();\n }\n\n\n \/**\n Returns the name of this attribute.\n *\/\n OUString SAL_CALL CAttr::getName() throw (RuntimeException)\n {\n OUString aName;\n if (m_aAttrPtr != NULL)\n {\n aName = OUString((char*)m_aAttrPtr->name, strlen((char*)m_aAttrPtr->name), RTL_TEXTENCODING_UTF8);\n }\n return aName;\n }\n\n \/**\n The Element node this attribute is attached to or null if this\n attribute is not in use.\n *\/\n Reference< XElement > SAL_CALL CAttr::getOwnerElement()\n throw (RuntimeException)\n {\n Reference< XElement > aElement;\n if (m_aAttrPtr != NULL && m_aAttrPtr->parent != NULL)\n {\n aElement = Reference< XElement >(static_cast< CElement* >(CNode::get(m_aAttrPtr->parent)));\n }\n return aElement;\n }\n\n \/**\n If this attribute was explicitly given a value in the original\n document, this is true; otherwise, it is false.\n *\/\n sal_Bool SAL_CALL CAttr::getSpecified()\n throw (RuntimeException)\n {\n \/\/ XXX what is this supposed do exactly?\n return sal_False;\n }\n\n \/**\n On retrieval, the value of the attribute is returned as a string.\n *\/\n OUString SAL_CALL CAttr::getValue()\n throw (RuntimeException)\n {\n OUString aName;\n if (m_aAttrPtr != NULL && m_aAttrPtr->children != NULL)\n {\n aName = OUString((char*)m_aAttrPtr->children->content, strlen((char*)m_aAttrPtr->children->content),\n RTL_TEXTENCODING_UTF8);\n }\n return aName;\n }\n\n \/**\n Sets the value of the attribute from a string.\n *\/\n void SAL_CALL CAttr::setValue(const OUString& value)\n throw (RuntimeException, DOMException)\n {\n \/\/ remember old value (for mutation event)\n OUString sOldValue = getValue();\n\n OString o1 = OUStringToOString(value, RTL_TEXTENCODING_UTF8);\n xmlChar* xValue = (xmlChar*)o1.getStr();\n \/\/ xmlChar* xName = OUStringToOString(m_aAttrPtr->name, RTL_TEXTENCODING_UTF8).getStr();\n \/\/ this does not work if the attribute was created anew\n \/\/ xmlNodePtr pNode = m_aAttrPtr->parent;\n \/\/ xmlSetProp(pNode, m_aAttrPtr->name, xValue);\n xmlChar *buffer = xmlEncodeEntitiesReentrant(m_aAttrPtr->doc, xValue);\n m_aAttrPtr->children = xmlStringGetNodeList(m_aAttrPtr->doc, buffer);\n xmlNodePtr tmp = m_aAttrPtr->children;\n while (tmp != NULL) {\n tmp->parent = (xmlNodePtr) m_aNodePtr;\n tmp->doc = m_aAttrPtr->doc;\n if (tmp->next == NULL)\n m_aNodePtr->last = tmp;\n tmp = tmp->next;\n }\n\n \/\/ dispatch DOM events to signal change in attribute value\n \/\/ dispatch DomAttrModified + DOMSubtreeModified\n OUString sEventName( RTL_CONSTASCII_USTRINGPARAM(\"DOMAttrModified\") );\n Reference< XDocumentEvent > docevent(getOwnerDocument(), UNO_QUERY);\n Reference< XMutationEvent > event(docevent->createEvent(sEventName),UNO_QUERY);\n event->initMutationEvent(\n sEventName, sal_True, sal_False,\n Reference<XNode>( static_cast<XAttr*>( this ) ),\n sOldValue, value, getName(), AttrChangeType_MODIFICATION );\n dispatchEvent(Reference< XEvent >(event, UNO_QUERY));\n dispatchSubtreeModified();\n xmlFree(buffer);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\n\/*\n * $Log$\n * Revision 1.10 2001\/08\/01 19:11:01 tng\n * Add full schema constraint checking flag to the samples and the parser.\n *\n * Revision 1.9 2001\/05\/11 13:24:55 tng\n * Copyright update.\n *\n * Revision 1.8 2001\/05\/03 15:59:40 tng\n * Schema: samples update with schema\n *\n * Revision 1.7 2000\/09\/11 18:43:48 aruna1\n * OS390 related updates\n *\n * Revision 1.6 2000\/03\/02 19:53:42 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.5 2000\/02\/11 02:37:01 abagchi\n * Removed StrX::transcode\n *\n * Revision 1.4 2000\/02\/06 07:47:19 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/12 00:27:00 roddey\n * Updates to work with the new URL and input source scheme.\n *\n * Revision 1.2 1999\/11\/20 01:09:55 rahulj\n * Fixed usage message.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:49 twl\n * Initial checkin\n *\n * Revision 1.7 1999\/11\/08 20:43:36 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/**\n * This sample program illustrates how one can use a memory buffer as the\n * input to parser. The memory buffer contains raw bytes representing XML\n * statements.\n *\n * Look at the API documentation for 'MemBufInputSource' for more information\n * on parameters to the constructor.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <parsers\/SAXParser.hpp>\n#include <framework\/MemBufInputSource.hpp>\n#include \"MemParse.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local const data\n\/\/\n\/\/ gXMLInMemBuf\n\/\/ Defines the memory buffer contents here which parsed by the XML\n\/\/ parser. This is the cheap way to do it, instead of reading it from\n\/\/ somewhere. For this demo, its fine.\n\/\/\n\/\/ NOTE: This will NOT work if your compiler's default char type is not\n\/\/ ASCII, since we indicate in the encoding that its ascii.\n\/\/\n\/\/ gMemBufId\n\/\/ A simple name to give as the system id for the memory buffer. This\n\/\/ just for indentification purposes in case of errors. Its not a real\n\/\/ system id (and the parser knows that.)\n\/\/ ---------------------------------------------------------------------------\n\n#ifdef OS390\nstatic const char* gXMLInMemBuf =\n\"\\\n<?xml version='1.0' encoding='ibm-1047-s390'?>\\n\\\n<!DOCTYPE company [\\n\\\n<!ELEMENT company (product,category,developedAt)>\\n\\\n<!ELEMENT product (#PCDATA)>\\n\\\n<!ELEMENT category (#PCDATA)>\\n\\\n<!ATTLIST category idea CDATA #IMPLIED>\\n\\\n<!ELEMENT developedAt (#PCDATA)>\\n\\\n]>\\n\\n\\\n<company>\\n\\\n <product>XML4C<\/product>\\n\\\n <category idea='great'>XML Parsing Tools<\/category>\\n\\\n <developedAt>\\n\\\n IBM Center for Java Technology, Silicon Valley, Cupertino, CA\\n\\\n <\/developedAt>\\n\\\n<\/company>\\\n\";\n#else\nstatic const char* gXMLInMemBuf =\n\"\\\n<?xml version='1.0' encoding='ascii'?>\\n\\\n<!DOCTYPE company [\\n\\\n<!ELEMENT company (product,category,developedAt)>\\n\\\n<!ELEMENT product (#PCDATA)>\\n\\\n<!ELEMENT category (#PCDATA)>\\n\\\n<!ATTLIST category idea CDATA #IMPLIED>\\n\\\n<!ELEMENT developedAt (#PCDATA)>\\n\\\n]>\\n\\n\\\n<company>\\n\\\n <product>XML4C<\/product>\\n\\\n <category idea='great'>XML Parsing Tools<\/category>\\n\\\n <developedAt>\\n\\\n IBM Center for Java Technology, Silicon Valley, Cupertino, CA\\n\\\n <\/developedAt>\\n\\\n<\/company>\\\n\";\n#endif\n\nstatic const char* gMemBufId = \"prodInfo\";\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid usage()\n{\n cout << \"\\nUsage:\\n\"\n << \" MemParse [-v]\\n\"\n << \"This program uses the SAX Parser to parse a memory buffer\\n\"\n << \"containing XML statements, and reports the number of\\n\"\n << \"elements and attributes found.\\n\"\n << \"\\nOptions:\\n\"\n << \" -v=xxx Validation scheme [always | never | auto*]\\n\"\n << \" -n Enable namespace processing. Defaults to off.\\n\"\n << \" -s Enable schema processing. Defaults to off.\\n\"\n << \" -f Enable full schema constraint checking. Defaults to off.\\n\\n\"\n << \" * = Default if not provided explicitly\\n\"\n << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Program entry point\n\/\/ ---------------------------------------------------------------------------\nint main(int argC, char* argV[])\n{\n \/\/ Initialize the XML4C2 system\n try\n {\n XMLPlatformUtils::Initialize();\n }\n catch (const XMLException& toCatch)\n {\n cerr << \"Error during initialization! Message:\\n\"\n << StrX(toCatch.getMessage()) << endl;\n return 1;\n }\n\n SAXParser::ValSchemes valScheme = SAXParser::Val_Auto;\n bool doNamespaces = false;\n bool doSchema = false;\n bool schemaFullChecking = false;\n if (argC > 1)\n {\n \/\/ See if non validating dom parser configuration is requested.\n if ((argC == 2) && !strcmp(argV[1], \"-?\"))\n {\n usage();\n return 2;\n }\n\n int argInd;\n for (argInd = 1; argInd < argC; argInd++)\n {\n if (!strncmp(argV[argInd], \"-v=\", 3)\n || !strncmp(argV[argInd], \"-V=\", 3))\n {\n const char* const parm = &argV[argInd][3];\n\n if (!strcmp(parm, \"never\"))\n valScheme = SAXParser::Val_Never;\n else if (!strcmp(parm, \"auto\"))\n valScheme = SAXParser::Val_Auto;\n else if (!strcmp(parm, \"always\"))\n valScheme = SAXParser::Val_Always;\n else\n {\n cerr << \"Unknown -v= value: \" << parm << endl;\n return 2;\n }\n }\n else if (!strcmp(argV[argInd], \"-n\")\n || !strcmp(argV[argInd], \"-N\"))\n {\n doNamespaces = true;\n }\n else if (!strcmp(argV[argInd], \"-s\")\n || !strcmp(argV[argInd], \"-S\"))\n {\n doSchema = true;\n }\n else if (!strcmp(argV[argInd], \"-f\")\n || !strcmp(argV[argInd], \"-F\"))\n {\n schemaFullChecking = true;\n }\n else\n {\n cerr << \"Unknown option '\" << argV[argInd]\n << \"', ignoring it\\n\" << endl;\n }\n }\n }\n\n \/\/\n \/\/ Create a SAX parser object. Then, according to what we were told on\n \/\/ the command line, set it to validate or not.\n \/\/\n SAXParser parser;\n parser.setValidationScheme(valScheme);\n parser.setDoNamespaces(doNamespaces);\n parser.setDoSchema(doSchema);\n parser.setValidationSchemaFullChecking(schemaFullChecking);\n\n \/\/\n \/\/ Create our SAX handler object and install it on the parser, as the\n \/\/ document and error handlers.\n \/\/\n MemParseHandlers handler;\n parser.setDocumentHandler(&handler);\n parser.setErrorHandler(&handler);\n\n \/\/\n \/\/ Create MemBufferInputSource from the buffer containing the XML\n \/\/ statements.\n \/\/\n \/\/ NOTE: We are using strlen() here, since we know that the chars in\n \/\/ our hard coded buffer are single byte chars!!! The parameter wants\n \/\/ the number of BYTES, not chars, so when you create a memory buffer\n \/\/ give it the byte size (which just happens to be the same here.)\n \/\/\n MemBufInputSource* memBufIS = new MemBufInputSource\n (\n (const XMLByte*)gXMLInMemBuf\n , strlen(gXMLInMemBuf)\n , gMemBufId\n , false\n );\n\n \/\/\n \/\/ Get the starting time and kick off the parse of the indicated\n \/\/ file. Catch any exceptions that might propogate out of it.\n \/\/\n unsigned long duration;\n try\n {\n const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();\n parser.parse(*memBufIS);\n const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();\n duration = endMillis - startMillis;\n }\n\n catch (const XMLException& e)\n {\n cerr << \"\\nError during parsing memory stream:\\n\"\n << \"Exception message is: \\n\"\n << StrX(e.getMessage()) << \"\\n\" << endl;\n return -1;\n }\n\n \/\/ Print out the stats that we collected and time taken.\n cout << \"\\nFinished parsing the memory buffer containing the following \"\n << \"XML statements:\\n\\n\"\n << gXMLInMemBuf\n << \"\\n\\n\\n\"\n << \"Parsing took \" << duration << \" ms (\"\n << handler.getElementCount() << \" elements, \"\n << handler.getAttrCount() << \" attributes, \"\n << handler.getSpaceCount() << \" spaces, \"\n << handler.getCharacterCount() << \" characters).\\n\" << endl;\n\n \/\/ And call the termination method\n XMLPlatformUtils::Terminate();\n\n return 0;\n}\n\n<commit_msg>Pulled the hardcoded \"encoding\" out of the document itself and made it a #define to make it easier to support other encodings. Patch from David McCreedy. And other modification for consistent help display and return code across samples.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\n\/*\n * $Log$\n * Revision 1.11 2001\/10\/19 18:56:08 tng\n * Pulled the hardcoded \"encoding\" out of the document itself and made it a #define\n * to make it easier to support other encodings. Patch from David McCreedy.\n * And other modification for consistent help display and return code across samples.\n *\n * Revision 1.10 2001\/08\/01 19:11:01 tng\n * Add full schema constraint checking flag to the samples and the parser.\n *\n * Revision 1.9 2001\/05\/11 13:24:55 tng\n * Copyright update.\n *\n * Revision 1.8 2001\/05\/03 15:59:40 tng\n * Schema: samples update with schema\n *\n * Revision 1.7 2000\/09\/11 18:43:48 aruna1\n * OS390 related updates\n *\n * Revision 1.6 2000\/03\/02 19:53:42 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.5 2000\/02\/11 02:37:01 abagchi\n * Removed StrX::transcode\n *\n * Revision 1.4 2000\/02\/06 07:47:19 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/12 00:27:00 roddey\n * Updates to work with the new URL and input source scheme.\n *\n * Revision 1.2 1999\/11\/20 01:09:55 rahulj\n * Fixed usage message.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:49 twl\n * Initial checkin\n *\n * Revision 1.7 1999\/11\/08 20:43:36 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/**\n * This sample program illustrates how one can use a memory buffer as the\n * input to parser. The memory buffer contains raw bytes representing XML\n * statements.\n *\n * Look at the API documentation for 'MemBufInputSource' for more information\n * on parameters to the constructor.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <parsers\/SAXParser.hpp>\n#include <framework\/MemBufInputSource.hpp>\n#include \"MemParse.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local const data\n\/\/\n\/\/ gXMLInMemBuf\n\/\/ Defines the memory buffer contents here which parsed by the XML\n\/\/ parser. This is the cheap way to do it, instead of reading it from\n\/\/ somewhere. For this demo, its fine.\n\/\/\n\/\/ NOTE: If your encoding is not ascii you will need to change\n\/\/ the MEMPARSE_ENCODING #define\n\/\/\n\/\/ gMemBufId\n\/\/ A simple name to give as the system id for the memory buffer. This\n\/\/ just for indentification purposes in case of errors. Its not a real\n\/\/ system id (and the parser knows that.)\n\/\/ ---------------------------------------------------------------------------\n\n#ifndef MEMPARSE_ENCODING\n #if defined(OS390)\n #define MEMPARSE_ENCODING \"ibm-1047-s390\"\n #else\n #define MEMPARSE_ENCODING \"ascii\"\n #endif\n#endif \/* ifndef MEMPARSE_ENCODING *\/\n\nstatic const char* gXMLInMemBuf =\n\"\\\n<?xml version='1.0' encoding='\" MEMPARSE_ENCODING \"'?>\\n\\\n<!DOCTYPE company [\\n\\\n<!ELEMENT company (product,category,developedAt)>\\n\\\n<!ELEMENT product (#PCDATA)>\\n\\\n<!ELEMENT category (#PCDATA)>\\n\\\n<!ATTLIST category idea CDATA #IMPLIED>\\n\\\n<!ELEMENT developedAt (#PCDATA)>\\n\\\n]>\\n\\n\\\n<company>\\n\\\n <product>XML4C<\/product>\\n\\\n <category idea='great'>XML Parsing Tools<\/category>\\n\\\n <developedAt>\\n\\\n IBM Center for Java Technology, Silicon Valley, Cupertino, CA\\n\\\n <\/developedAt>\\n\\\n<\/company>\\\n\";\n\nstatic const char* gMemBufId = \"prodInfo\";\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid usage()\n{\n cout << \"\\nUsage:\\n\"\n \" MemParse [options]\\n\\n\"\n \"This program uses the SAX Parser to parse a memory buffer\\n\"\n \"containing XML statements, and reports the number of\\n\"\n \"elements and attributes found.\\n\\n\"\n \"Options:\\n\"\n \" -v=xxx Validation scheme [always | never | auto*].\\n\"\n \" -n Enable namespace processing. Defaults to off.\\n\"\n \" -s Enable schema processing. Defaults to off.\\n\"\n \" -f Enable full schema constraint checking. Defaults to off.\\n\"\n\t\t \" -? Show this help.\\n\\n\"\n \" * = Default if not provided explicitly.\\n\"\n << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Program entry point\n\/\/ ---------------------------------------------------------------------------\nint main(int argC, char* argV[])\n{\n \/\/ Initialize the XML4C2 system\n try\n {\n XMLPlatformUtils::Initialize();\n }\n catch (const XMLException& toCatch)\n {\n cerr << \"Error during initialization! Message:\\n\"\n << StrX(toCatch.getMessage()) << endl;\n return 1;\n }\n\n SAXParser::ValSchemes valScheme = SAXParser::Val_Auto;\n bool doNamespaces = false;\n bool doSchema = false;\n bool schemaFullChecking = false;\n\n int argInd;\n for (argInd = 1; argInd < argC; argInd++)\n {\n \/\/ Break out on first parm not starting with a dash\n if (argV[argInd][0] != '-')\n {\n usage();\n XMLPlatformUtils::Terminate();\n return 1;\n }\n\n \/\/ Watch for special case help request\n if (!strcmp(argV[argInd], \"-?\"))\n {\n usage();\n XMLPlatformUtils::Terminate();\n return 1;\n }\n else if (!strncmp(argV[argInd], \"-v=\", 3)\n || !strncmp(argV[argInd], \"-V=\", 3))\n {\n const char* const parm = &argV[argInd][3];\n\n if (!strcmp(parm, \"never\"))\n valScheme = SAXParser::Val_Never;\n else if (!strcmp(parm, \"auto\"))\n valScheme = SAXParser::Val_Auto;\n else if (!strcmp(parm, \"always\"))\n valScheme = SAXParser::Val_Always;\n else\n {\n cerr << \"Unknown -v= value: \" << parm << endl;\n return 2;\n }\n }\n else if (!strcmp(argV[argInd], \"-n\")\n || !strcmp(argV[argInd], \"-N\"))\n {\n doNamespaces = true;\n }\n else if (!strcmp(argV[argInd], \"-s\")\n || !strcmp(argV[argInd], \"-S\"))\n {\n doSchema = true;\n }\n else if (!strcmp(argV[argInd], \"-f\")\n || !strcmp(argV[argInd], \"-F\"))\n {\n schemaFullChecking = true;\n }\n else\n {\n cerr << \"Unknown option '\" << argV[argInd]\n << \"', ignoring it\\n\" << endl;\n }\n }\n\n \/\/\n \/\/ Create a SAX parser object. Then, according to what we were told on\n \/\/ the command line, set it to validate or not.\n \/\/\n SAXParser parser;\n parser.setValidationScheme(valScheme);\n parser.setDoNamespaces(doNamespaces);\n parser.setDoSchema(doSchema);\n parser.setValidationSchemaFullChecking(schemaFullChecking);\n\n \/\/\n \/\/ Create our SAX handler object and install it on the parser, as the\n \/\/ document and error handlers.\n \/\/\n MemParseHandlers handler;\n parser.setDocumentHandler(&handler);\n parser.setErrorHandler(&handler);\n\n \/\/\n \/\/ Create MemBufferInputSource from the buffer containing the XML\n \/\/ statements.\n \/\/\n \/\/ NOTE: We are using strlen() here, since we know that the chars in\n \/\/ our hard coded buffer are single byte chars!!! The parameter wants\n \/\/ the number of BYTES, not chars, so when you create a memory buffer\n \/\/ give it the byte size (which just happens to be the same here.)\n \/\/\n MemBufInputSource* memBufIS = new MemBufInputSource\n (\n (const XMLByte*)gXMLInMemBuf\n , strlen(gXMLInMemBuf)\n , gMemBufId\n , false\n );\n\n \/\/\n \/\/ Get the starting time and kick off the parse of the indicated\n \/\/ file. Catch any exceptions that might propogate out of it.\n \/\/\n unsigned long duration;\n int errorCount = 0;\n try\n {\n const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();\n parser.parse(*memBufIS);\n const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();\n duration = endMillis - startMillis;\n errorCount = parser.getErrorCount();\n }\n\n catch (const XMLException& e)\n {\n cerr << \"\\nError during parsing memory stream:\\n\"\n << \"Exception message is: \\n\"\n << StrX(e.getMessage()) << \"\\n\" << endl;\n return 4;\n }\n\n \/\/ Print out the stats that we collected and time taken.\n if (!errorCount) {\n cout << \"\\nFinished parsing the memory buffer containing the following \"\n << \"XML statements:\\n\\n\"\n << gXMLInMemBuf\n << \"\\n\\n\\n\"\n << \"Parsing took \" << duration << \" ms (\"\n << handler.getElementCount() << \" elements, \"\n << handler.getAttrCount() << \" attributes, \"\n << handler.getSpaceCount() << \" spaces, \"\n << handler.getCharacterCount() << \" characters).\\n\" << endl;\n }\n\n \/\/ And call the termination method\n XMLPlatformUtils::Terminate();\n\n if (errorCount > 0)\n return 4;\n else\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT7_RAttrAxis\n#define ROOT7_RAttrAxis\n\n#include <ROOT\/RAttrBase.hxx>\n#include <ROOT\/RAttrLine.hxx>\n#include <ROOT\/RAttrText.hxx>\n#include <ROOT\/RAttrValue.hxx>\n#include <ROOT\/RPadLength.hxx>\n#include <cmath>\n\nnamespace ROOT {\nnamespace Experimental {\n\n\/** \\class RAttrAxis\n\\ingroup GpadROOT7\n\\author Sergey Linev <s.linev@gsi.de>\n\\date 2020-02-20\n\\brief All supported axes attributes for: line, ticks, labels, title, min\/max, log, reverse, ...\n\\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!\n*\/\n\nclass RAttrAxis : public RAttrBase {\n\n RAttrValue<double> fMin{this, \"min\", 0.}; \/\/\/<! axis min\n RAttrValue<double> fMax{this, \"max\", 0.}; \/\/\/<! axis max\n RAttrValue<double> fZoomMin{this, \"zoommin\", 0.}; \/\/\/<! axis zoom min\n RAttrValue<double> fZoomMax{this, \"zoommax\", 0.}; \/\/\/<! axis zoom max\n RAttrValue<double> fLog{this, \"log\", 0}; \/\/\/<! log scale, <1 off, 1 - base10, 2 - base 2, 2.71 - exp, 3, 4, ...\n RAttrValue<bool> fReverse{this, \"reverse\", false}; \/\/\/<! reverse scale\n RAttrValue<bool> fTimeDisplay{this, \"time\", false}; \/\/\/<! time display\n RAttrValue<double> fTimeOffset{this, \"time_offset\", 0}; \/\/\/<! time offset to display\n RAttrValue<std::string> fTimeFormat{this, \"time_format\", \"\"}; \/\/\/<! time format\n RAttrLine fAttrLine{this, \"line\"}; \/\/\/<! line attributes\n RAttrValue<std::string> fEndingStyle{this, \"ending_style\", \"\"}; \/\/\/<! axis ending style - none, arrow, circle\n RAttrValue<RPadLength> fEndingSize{this, \"ending_size\", 0.02_normal}; \/\/\/<! axis ending size\n RAttrValue<std::string> fTicksSide{this, \"ticks_side\", \"normal\"}; \/\/\/<! ticks position - normal, invert, both\n RAttrValue<RPadLength> fTicksSize{this, \"ticks_size\", 0.02_normal}; \/\/\/<! ticks size\n RAttrValue<RColor> fTicksColor{this, \"ticks_color\", RColor::kBlack}; \/\/\/<! ticks color\n RAttrValue<int> fTicksWidth{this, \"ticks_width\", 1}; \/\/\/<! ticks width\n RAttrText fLabelsAttr{this, \"labels\"}; \/\/\/<! text attributes for labels\n RAttrValue<RPadLength> fLabelsOffset{this, \"labels_offset\", {}}; \/\/\/<! axis labels offset - relative\n RAttrValue<bool> fLabelsCenter{this, \"labels_center\", false}; \/\/\/<! center labels\n RAttrText fTitleAttr{this, \"title\"}; \/\/\/<! axis title text attributes\n RAttrValue<std::string> fTitle{this, \"title\", \"\"}; \/\/\/<! axis title\n RAttrValue<std::string> fTitlePos{this, \"title_position\", \"right\"}; \/\/\/<! axis title position - left, right, center\n RAttrValue<RPadLength> fTitleOffset{this, \"title_offset\", {}}; \/\/\/<! axis title offset - relative\n\n R__ATTR_CLASS(RAttrAxis, \"axis\");\n\n RAttrAxis &SetMin(double min) { fMin = min; return *this; }\n RAttrAxis &SetMax(double max) { fMax = max; return *this; }\n double GetMin() const { return fMin; }\n double GetMax() const { return fMax; }\n bool HasMin() const { return fMin.Has(); }\n bool HasMax() const { return fMax.Has(); }\n\n RAttrAxis &SetMinMax(double min, double max) { SetMin(min); SetMax(max); return *this; }\n void ClearMinMax() { fMin.Clear(); fMax.Clear(); }\n\n RAttrAxis &SetZoomMin(double min) { fZoomMin = min; return *this; }\n RAttrAxis &SetZoomMax(double max) { fZoomMax = max; return *this; }\n double GetZoomMin() const { return fZoomMin; }\n double GetZoomMax() const { return fZoomMax; }\n bool HasZoomMin() const { return fZoomMin.Has(); }\n bool HasZoomMax() const { return fZoomMax.Has(); }\n\n RAttrAxis &SetZoom(double min, double max) { SetZoomMin(min); SetZoomMax(max); return *this; }\n void ClearZoom() { fZoomMin.Clear(); fZoomMax.Clear(); }\n\n RAttrAxis &SetLog(double base = 10) { fLog = (base < 1) ? 0 : base; return *this; }\n double GetLog() const { return fLog; }\n bool IsLogScale() const { return GetLog() > 0.999999; }\n bool IsLog10() const { auto l = GetLog(); return (std::fabs(l-1.) < 1e-6) || (std::fabs(l-10.) < 1e-6); }\n bool IsLog2() const { return std::fabs(GetLog() - 2.) < 1e-6; }\n bool IsLn() const { return std::fabs(GetLog() - 2.71828) < 0.1; }\n\n RAttrAxis &SetReverse(bool on = true) { fReverse = on; return *this; }\n bool GetReverse() const { return fReverse; }\n\n RAttrAxis &SetTimeDisplay(const std::string &fmt = \"\", double offset = -1)\n {\n fTimeDisplay = true;\n if (!fmt.empty()) fTimeFormat = fmt;\n if (offset >= 0) fTimeOffset = offset;\n return *this;\n }\n bool GetTimeDisplay() const { return fTimeDisplay; }\n void ClearTimeDisplay()\n {\n fTimeDisplay.Clear();\n fTimeOffset.Clear();\n fTimeFormat.Clear();\n }\n\n const RAttrLine &GetAttrLine() const { return fAttrLine; }\n RAttrAxis &SetAttrLine(const RAttrLine &line) { fAttrLine = line; return *this; }\n RAttrLine &AttrLine() { return fAttrLine; }\n\n RAttrAxis &SetEndingSize(const RPadLength &sz) { fEndingSize = sz; return *this; }\n RPadLength GetEndingSize() const { return fEndingSize; }\n\n RAttrAxis &SetEndingStyle(const std::string &st) { fEndingStyle = st; return *this; }\n RAttrAxis &SetEndingArrow() { return SetEndingStyle(\"arrow\"); }\n RAttrAxis &SetEndingCircle() { return SetEndingStyle(\"cicrle\"); }\n std::string GetEndingStyle() const { return fEndingStyle; }\n\n RAttrAxis &SetTicksSize(const RPadLength &sz) { fTicksSize = sz; return *this; }\n RPadLength GetTicksSize() const { return fTicksSize; }\n\n RAttrAxis &SetTicksSide(const std::string &side) { fTicksSide = side; return *this; }\n RAttrAxis &SetTicksNormal() { return SetTicksSide(\"normal\"); }\n RAttrAxis &SetTicksInvert() { return SetTicksSide(\"invert\"); }\n RAttrAxis &SetTicksBoth() { return SetTicksSide(\"both\"); }\n std::string GetTicksSide() const { return fTicksSide; }\n\n RAttrAxis &SetTicksColor(const RColor &color) { fTicksColor = color; return *this; }\n RColor GetTicksColor() const { return fTicksColor; }\n\n RAttrAxis &SetTicksWidth(int width) { fTicksWidth = width; return *this; }\n int GetTicksWidth() const { return fTicksWidth; }\n\n RAttrAxis &SetLabelsOffset(const RPadLength &len) { fLabelsOffset = len; return *this; }\n RPadLength GetLabelsOffset() const { return fLabelsOffset; }\n\n const RAttrText &GetLabelsAttr() const { return fLabelsAttr; }\n RAttrAxis &SetLabelsAttr(const RAttrText &attr) { fLabelsAttr = attr; return *this; }\n RAttrText &LabelsAttr() { return fLabelsAttr; }\n\n RAttrAxis &SetLabelsCenter(bool on = true) { fLabelsCenter = on; return *this; }\n bool GetLabelsCenter() const { return fLabelsCenter; }\n\n const RAttrText &GetTitleAttr() const { return fTitleAttr; }\n RAttrAxis &SetTitleAttr(const RAttrText &attr) { fTitleAttr = attr; return *this; }\n RAttrText &TitleAttr() { return fTitleAttr; }\n\n RAttrAxis &SetTitle(const std::string &title) { fTitle = title; return *this; }\n std::string GetTitle() const { return fTitle; }\n\n RAttrAxis &SetTitlePos(const std::string &pos) { fTitlePos = pos; return *this; }\n RAttrAxis &SetTitleLeft() { return SetTitlePos(\"left\"); }\n RAttrAxis &SetTitleCenter() { return SetTitlePos(\"center\"); }\n RAttrAxis &SetTitleRight() { return SetTitlePos(\"right\"); }\n std::string GetTitlePos() const { return fTitlePos; }\n\n RAttrAxis &SetTitleOffset(const RPadLength &len) { fTitleOffset = len; return *this; }\n RPadLength GetTitleOffset() const { return fTitleOffset; }\n};\n\n} \/\/ namespace Experimental\n} \/\/ namespace ROOT\n\n#endif\n<commit_msg>[raxis] add symlog attribute for RAxis<commit_after>\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT7_RAttrAxis\n#define ROOT7_RAttrAxis\n\n#include <ROOT\/RAttrBase.hxx>\n#include <ROOT\/RAttrLine.hxx>\n#include <ROOT\/RAttrText.hxx>\n#include <ROOT\/RAttrValue.hxx>\n#include <ROOT\/RPadLength.hxx>\n#include <cmath>\n\nnamespace ROOT {\nnamespace Experimental {\n\n\/** \\class RAttrAxis\n\\ingroup GpadROOT7\n\\author Sergey Linev <s.linev@gsi.de>\n\\date 2020-02-20\n\\brief All supported axes attributes for: line, ticks, labels, title, min\/max, log, reverse, ...\n\\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!\n*\/\n\nclass RAttrAxis : public RAttrBase {\n\n RAttrValue<double> fMin{this, \"min\", 0.}; \/\/\/<! axis min\n RAttrValue<double> fMax{this, \"max\", 0.}; \/\/\/<! axis max\n RAttrValue<double> fZoomMin{this, \"zoommin\", 0.}; \/\/\/<! axis zoom min\n RAttrValue<double> fZoomMax{this, \"zoommax\", 0.}; \/\/\/<! axis zoom max\n RAttrValue<double> fLog{this, \"log\", 0}; \/\/\/<! log scale, <1 off, 1 - base10, 2 - base 2, 2.71 - exp, 3, 4, ...\n RAttrValue<double> fSymlog{this, \"symlog\", 0}; \/\/\/<! symlog scale constant, 0 - off\n RAttrValue<bool> fReverse{this, \"reverse\", false}; \/\/\/<! reverse scale\n RAttrValue<bool> fTimeDisplay{this, \"time\", false}; \/\/\/<! time display\n RAttrValue<double> fTimeOffset{this, \"time_offset\", 0}; \/\/\/<! time offset to display\n RAttrValue<std::string> fTimeFormat{this, \"time_format\", \"\"}; \/\/\/<! time format\n RAttrLine fAttrLine{this, \"line\"}; \/\/\/<! line attributes\n RAttrValue<std::string> fEndingStyle{this, \"ending_style\", \"\"}; \/\/\/<! axis ending style - none, arrow, circle\n RAttrValue<RPadLength> fEndingSize{this, \"ending_size\", 0.02_normal}; \/\/\/<! axis ending size\n RAttrValue<std::string> fTicksSide{this, \"ticks_side\", \"normal\"}; \/\/\/<! ticks position - normal, invert, both\n RAttrValue<RPadLength> fTicksSize{this, \"ticks_size\", 0.02_normal}; \/\/\/<! ticks size\n RAttrValue<RColor> fTicksColor{this, \"ticks_color\", RColor::kBlack}; \/\/\/<! ticks color\n RAttrValue<int> fTicksWidth{this, \"ticks_width\", 1}; \/\/\/<! ticks width\n RAttrText fLabelsAttr{this, \"labels\"}; \/\/\/<! text attributes for labels\n RAttrValue<RPadLength> fLabelsOffset{this, \"labels_offset\", {}}; \/\/\/<! axis labels offset - relative\n RAttrValue<bool> fLabelsCenter{this, \"labels_center\", false}; \/\/\/<! center labels\n RAttrText fTitleAttr{this, \"title\"}; \/\/\/<! axis title text attributes\n RAttrValue<std::string> fTitle{this, \"title\", \"\"}; \/\/\/<! axis title\n RAttrValue<std::string> fTitlePos{this, \"title_position\", \"right\"}; \/\/\/<! axis title position - left, right, center\n RAttrValue<RPadLength> fTitleOffset{this, \"title_offset\", {}}; \/\/\/<! axis title offset - relative\n\n R__ATTR_CLASS(RAttrAxis, \"axis\");\n\n RAttrAxis &SetMin(double min) { fMin = min; return *this; }\n RAttrAxis &SetMax(double max) { fMax = max; return *this; }\n double GetMin() const { return fMin; }\n double GetMax() const { return fMax; }\n bool HasMin() const { return fMin.Has(); }\n bool HasMax() const { return fMax.Has(); }\n\n RAttrAxis &SetMinMax(double min, double max) { SetMin(min); SetMax(max); return *this; }\n void ClearMinMax() { fMin.Clear(); fMax.Clear(); }\n\n RAttrAxis &SetZoomMin(double min) { fZoomMin = min; return *this; }\n RAttrAxis &SetZoomMax(double max) { fZoomMax = max; return *this; }\n double GetZoomMin() const { return fZoomMin; }\n double GetZoomMax() const { return fZoomMax; }\n bool HasZoomMin() const { return fZoomMin.Has(); }\n bool HasZoomMax() const { return fZoomMax.Has(); }\n\n RAttrAxis &SetZoom(double min, double max) { SetZoomMin(min); SetZoomMax(max); return *this; }\n void ClearZoom() { fZoomMin.Clear(); fZoomMax.Clear(); }\n\n RAttrAxis &SetLog(double base = 10) { fLog = (base < 1) ? 0 : base; return *this; }\n double GetLog() const { return fLog; }\n bool IsLogScale() const { return GetLog() > 0.999999; }\n bool IsLog10() const { auto l = GetLog(); return (std::fabs(l-1.) < 1e-6) || (std::fabs(l-10.) < 1e-6); }\n bool IsLog2() const { return std::fabs(GetLog() - 2.) < 1e-6; }\n bool IsLn() const { return std::fabs(GetLog() - 2.71828) < 0.1; }\n\n RAttrAxis &SetSymlog(double const_value = 0.01)\n {\n if (const_value <= 0.)\n fSymlog.Clear();\n else\n fSymlog = const_value;\n return *this;\n }\n double GetSymlog() const { return fSymlog; }\n bool HasSymlog() const { return fSymlog.Has(); }\n void ClearSymlog() { fSymlog.Clear(); }\n\n RAttrAxis &SetReverse(bool on = true) { fReverse = on; return *this; }\n bool GetReverse() const { return fReverse; }\n\n RAttrAxis &SetTimeDisplay(const std::string &fmt = \"\", double offset = -1)\n {\n fTimeDisplay = true;\n if (!fmt.empty()) fTimeFormat = fmt;\n if (offset >= 0) fTimeOffset = offset;\n return *this;\n }\n bool GetTimeDisplay() const { return fTimeDisplay; }\n void ClearTimeDisplay()\n {\n fTimeDisplay.Clear();\n fTimeOffset.Clear();\n fTimeFormat.Clear();\n }\n\n const RAttrLine &GetAttrLine() const { return fAttrLine; }\n RAttrAxis &SetAttrLine(const RAttrLine &line) { fAttrLine = line; return *this; }\n RAttrLine &AttrLine() { return fAttrLine; }\n\n RAttrAxis &SetEndingSize(const RPadLength &sz) { fEndingSize = sz; return *this; }\n RPadLength GetEndingSize() const { return fEndingSize; }\n\n RAttrAxis &SetEndingStyle(const std::string &st) { fEndingStyle = st; return *this; }\n RAttrAxis &SetEndingArrow() { return SetEndingStyle(\"arrow\"); }\n RAttrAxis &SetEndingCircle() { return SetEndingStyle(\"cicrle\"); }\n std::string GetEndingStyle() const { return fEndingStyle; }\n\n RAttrAxis &SetTicksSize(const RPadLength &sz) { fTicksSize = sz; return *this; }\n RPadLength GetTicksSize() const { return fTicksSize; }\n\n RAttrAxis &SetTicksSide(const std::string &side) { fTicksSide = side; return *this; }\n RAttrAxis &SetTicksNormal() { return SetTicksSide(\"normal\"); }\n RAttrAxis &SetTicksInvert() { return SetTicksSide(\"invert\"); }\n RAttrAxis &SetTicksBoth() { return SetTicksSide(\"both\"); }\n std::string GetTicksSide() const { return fTicksSide; }\n\n RAttrAxis &SetTicksColor(const RColor &color) { fTicksColor = color; return *this; }\n RColor GetTicksColor() const { return fTicksColor; }\n\n RAttrAxis &SetTicksWidth(int width) { fTicksWidth = width; return *this; }\n int GetTicksWidth() const { return fTicksWidth; }\n\n RAttrAxis &SetLabelsOffset(const RPadLength &len) { fLabelsOffset = len; return *this; }\n RPadLength GetLabelsOffset() const { return fLabelsOffset; }\n\n const RAttrText &GetLabelsAttr() const { return fLabelsAttr; }\n RAttrAxis &SetLabelsAttr(const RAttrText &attr) { fLabelsAttr = attr; return *this; }\n RAttrText &LabelsAttr() { return fLabelsAttr; }\n\n RAttrAxis &SetLabelsCenter(bool on = true) { fLabelsCenter = on; return *this; }\n bool GetLabelsCenter() const { return fLabelsCenter; }\n\n const RAttrText &GetTitleAttr() const { return fTitleAttr; }\n RAttrAxis &SetTitleAttr(const RAttrText &attr) { fTitleAttr = attr; return *this; }\n RAttrText &TitleAttr() { return fTitleAttr; }\n\n RAttrAxis &SetTitle(const std::string &title) { fTitle = title; return *this; }\n std::string GetTitle() const { return fTitle; }\n\n RAttrAxis &SetTitlePos(const std::string &pos) { fTitlePos = pos; return *this; }\n RAttrAxis &SetTitleLeft() { return SetTitlePos(\"left\"); }\n RAttrAxis &SetTitleCenter() { return SetTitlePos(\"center\"); }\n RAttrAxis &SetTitleRight() { return SetTitlePos(\"right\"); }\n std::string GetTitlePos() const { return fTitlePos; }\n\n RAttrAxis &SetTitleOffset(const RPadLength &len) { fTitleOffset = len; return *this; }\n RPadLength GetTitleOffset() const { return fTitleOffset; }\n};\n\n} \/\/ namespace Experimental\n} \/\/ namespace ROOT\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n#include <iomanip>\n\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n _service.getScientists(); \/\/ gets information from file so it's used from the beginning.\n}\n\n\/\/ Should not contain logic for individual commands, that should be in separate functions!\nvoid ConsoleUI::run()\n{\n\n\n string command;\n while(true)\n {\n cout << \"Select one of the following options: \" << endl;\n cout << \"=====================================\" << endl;\n cout << \"Add - add a programmer\/computer scientist\" << endl;\n cout << \"Remove - remove a programmer\/computer scientist\" << endl;\n cout << \"List - show a list of all programmer's\/computer scientist's\" << endl;\n cout << \"Search - search the list of programmer's\/computer scientist's\" << endl;\n cout << \"Sort - sort list by name, gender, age or year of death\" << endl;\n cout << \"Quit - end program\" << endl;\n\n\n cin >> command;\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n\n if(command == \"add\")\n {\n userMenuAdd();\n }\n else if(command == \"remove\")\n {\n userMenuRemove();\n }\n else if(command == \"list\")\n {\n userMenuList();\n }\n else if(command == \"search\")\n {\n userMenuSearch();\n }\n else if(command == \"sort\")\n {\n userMenuSort();\n }\n else if(command == \"quit\")\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n\n\n}\nvoid ConsoleUI::userMenuAdd()\n{\n string name;\n char gender;\n int birthYear;\n int deathYear = 0;\n int age = 0;\n int a;\n\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's name: \";\n cin.ignore();\n getline(cin, name);\n\n \/\/ Check for gender\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n cin >> gender;\n\n if((gender != 'm') && (gender != 'f'))\n {\n cout << \"Invalid input\" << endl;\n }\n else\n {\n break;\n }\n\n }\n\n \/\/ Check year of birth\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n cin >> birthYear;\n if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n \/\/ Check when year of death (if dead)\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n cin >> deathYear;\n if (deathYear == 0)\n {\n break;\n }\n else if(deathYear >= birthYear)\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n\n \/\/ Check if input is correct\n cout << \"Name: \" << name << endl << \"Gender: \" << gender << endl << \"Born: \" << birthYear << endl;\n\n if(deathYear != 0)\n {\n cout << \"Died: \" << deathYear << endl;\n }\n else\n {\n cout << endl;\n }\n\n a = userCheckInput();\n if (a == 0)\n {\n _service.addScientist(name, gender, birthYear, deathYear, age);\n break;\n }\n else if (a == 2)\n {\n break;\n }\n\n }\n cout << endl;\n\n}\nvoid ConsoleUI::userMenuList()\n{\n vector<Scientist> scientist = _service.getScientists();\n userMenuPrint(scientist);\n}\nvoid ConsoleUI::userMenuSearch()\n{\n string command;\n cout << \"Select a search option: \" << endl;\n cout << \"Name - Search by name\" << endl;\n cout << \"Gender - Search by gender\" << endl;\n cout << \"Age - Search by age\" << endl;\n cout << \"Birth - search by year of birth\" << endl;\n cout << \"Death - search by year of death\" << endl;\n cin >> command;\n cout << endl;\n\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n\n if(command == \"name\")\n {\n string userInputName;\n cout << \"Search by name: \";\n cin.ignore();\n getline(cin, userInputName);\n\n vector<Scientist> scientist = _service.findScientistByName(userInputName);\n userMenuPrint(scientist);\n\n }\n else if(command == \"gender\") \/\/ findScientistByGender\n {\n char userInputGender;\n cout << \"Search by gender: \";\n cin >> userInputGender;\n\n vector<Scientist> scientist = _service.findScientistByGender(userInputGender);\n userMenuPrint(scientist);\n }\n else if(command == \"age\") \/\/ findScientistByGender\n {\n int userInputAge;\n cout << \"Search by age: \";\n cin >> userInputAge;\n\n vector<Scientist> scientist = _service.findScientistByAge(userInputAge);\n userMenuPrint(scientist);\n }\n else if(command == \"birth\")\n {\n int userInputBirth;\n cout << \"Search by year of birth: \";\n cin >> userInputBirth;\n\n vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth);\n userMenuPrint(scientist);\n }\n else if(command == \"death\")\n {\n int userInputDeath;\n cout << \"Search by year of death (0 for still alive): \";\n cin >> userInputDeath;\n\n vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath);\n userMenuPrint(scientist);\n }\n cout << endl;\n\n}\nvoid ConsoleUI::userMenuSort()\n{\n int userInput;\n cout << \"Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)\" << endl;\n cin >> userInput;\n _service.scientistSort(userInput);\n userMenuList();\n}\nvoid ConsoleUI::userMenuPrint(vector<Scientist>scientist)\n{\n<<<<<<< HEAD\n cout << endl;\n cout << \"Scientist name: gender: born: died: age: \" << endl;\n cout << \"========================================================\" << endl;\n for (size_t i = 0; i< scientist.size(); ++i)\n {\n cout << left << setw(25) << scientist[i].getName()\n << setw(5) << right << scientist[i].getGender()\n << setw(10) << scientist[i].getBirth();\n=======\n cout << string( 100, '\\n' );\n cout << \"Scientist name: gender: born: died: age: \" << endl;\n cout << \"====================================================\" << endl;\n for (size_t i = 0; i< scientist.size(); ++i)\n {\n cout << scientist[i].getName() << \"\\t\"\n << scientist[i].getGender() << \"\\t\"\n << scientist[i].getBirth() << \"\\t\";\n>>>>>>> 63b34c887dc6041917c649b2ebf30425f00c9d25\n\n\n if(scientist[i].getDeath() == 0)\n {\n cout << setw(8) << \"-\";\n }\n else\n {\n cout << setw(8) << scientist[i].getDeath();\n }\n cout << setw(8) << scientist[i].getAge() << endl;\n\n\n }\n cout << endl;\n}\nint ConsoleUI::userCheckInput()\n{\n \/\/ Check if all data is correct\n while(true)\n {\n char answear;\n cout << \"Is this data correct? (input y\/n) or press q to quit\" << endl;\n cin >> answear;\n\n if(answear == 'y')\n {\n return 0;\n }\n else if (answear == 'n')\n {\n return 1;\n }\n else if (answear == 'q')\n {\n return 2;\n }\n else\n {\n cout << \"Invalid input!\";\n }\n\n }\n}\nvoid ConsoleUI::userMenuRemove()\n{\n string userInputName;\n cout << \"Remove a programmer\/computer scientist: \";\n cin.ignore();\n getline(cin, userInputName);\n\n _service.removeScientist(userInputName);\n}\n<commit_msg>fixed merge<commit_after>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n#include <iomanip>\n\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n _service.getScientists(); \/\/ gets information from file so it's used from the beginning.\n}\n\n\/\/ Should not contain logic for individual commands, that should be in separate functions!\nvoid ConsoleUI::run()\n{\n\n\n string command;\n while(true)\n {\n cout << \"Select one of the following options: \" << endl;\n cout << \"=====================================\" << endl;\n cout << \"Add - add a programmer\/computer scientist\" << endl;\n cout << \"Remove - remove a programmer\/computer scientist\" << endl;\n cout << \"List - show a list of all programmer's\/computer scientist's\" << endl;\n cout << \"Search - search the list of programmer's\/computer scientist's\" << endl;\n cout << \"Sort - sort list by name, gender, age or year of death\" << endl;\n cout << \"Quit - end program\" << endl;\n\n\n cin >> command;\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n\n if(command == \"add\")\n {\n userMenuAdd();\n }\n else if(command == \"remove\")\n {\n userMenuRemove();\n }\n else if(command == \"list\")\n {\n userMenuList();\n }\n else if(command == \"search\")\n {\n userMenuSearch();\n }\n else if(command == \"sort\")\n {\n userMenuSort();\n }\n else if(command == \"quit\")\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n\n\n}\nvoid ConsoleUI::userMenuAdd()\n{\n string name;\n char gender;\n int birthYear;\n int deathYear = 0;\n int age = 0;\n int a;\n\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's name: \";\n cin.ignore();\n getline(cin, name);\n\n \/\/ Check for gender\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n cin >> gender;\n\n if((gender != 'm') && (gender != 'f'))\n {\n cout << \"Invalid input\" << endl;\n }\n else\n {\n break;\n }\n\n }\n\n \/\/ Check year of birth\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n cin >> birthYear;\n if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n \/\/ Check when year of death (if dead)\n while(true)\n {\n cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n cin >> deathYear;\n if (deathYear == 0)\n {\n break;\n }\n else if(deathYear >= birthYear)\n {\n break;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }\n\n\n \/\/ Check if input is correct\n cout << \"Name: \" << name << endl << \"Gender: \" << gender << endl << \"Born: \" << birthYear << endl;\n\n if(deathYear != 0)\n {\n cout << \"Died: \" << deathYear << endl;\n }\n else\n {\n cout << endl;\n }\n\n a = userCheckInput();\n if (a == 0)\n {\n _service.addScientist(name, gender, birthYear, deathYear, age);\n break;\n }\n else if (a == 2)\n {\n break;\n }\n\n }\n cout << endl;\n\n}\nvoid ConsoleUI::userMenuList()\n{\n vector<Scientist> scientist = _service.getScientists();\n userMenuPrint(scientist);\n}\nvoid ConsoleUI::userMenuSearch()\n{\n string command;\n cout << \"Select a search option: \" << endl;\n cout << \"Name - Search by name\" << endl;\n cout << \"Gender - Search by gender\" << endl;\n cout << \"Age - Search by age\" << endl;\n cout << \"Birth - search by year of birth\" << endl;\n cout << \"Death - search by year of death\" << endl;\n cin >> command;\n cout << endl;\n\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n\n if(command == \"name\")\n {\n string userInputName;\n cout << \"Search by name: \";\n cin.ignore();\n getline(cin, userInputName);\n\n vector<Scientist> scientist = _service.findScientistByName(userInputName);\n userMenuPrint(scientist);\n\n }\n else if(command == \"gender\") \/\/ findScientistByGender\n {\n char userInputGender;\n cout << \"Search by gender: \";\n cin >> userInputGender;\n\n vector<Scientist> scientist = _service.findScientistByGender(userInputGender);\n userMenuPrint(scientist);\n }\n else if(command == \"age\") \/\/ findScientistByGender\n {\n int userInputAge;\n cout << \"Search by age: \";\n cin >> userInputAge;\n\n vector<Scientist> scientist = _service.findScientistByAge(userInputAge);\n userMenuPrint(scientist);\n }\n else if(command == \"birth\")\n {\n int userInputBirth;\n cout << \"Search by year of birth: \";\n cin >> userInputBirth;\n\n vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth);\n userMenuPrint(scientist);\n }\n else if(command == \"death\")\n {\n int userInputDeath;\n cout << \"Search by year of death (0 for still alive): \";\n cin >> userInputDeath;\n\n vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath);\n userMenuPrint(scientist);\n }\n cout << endl;\n\n}\nvoid ConsoleUI::userMenuSort()\n{\n int userInput;\n cout << \"Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)\" << endl;\n cin >> userInput;\n _service.scientistSort(userInput);\n userMenuList();\n}\nvoid ConsoleUI::userMenuPrint(vector<Scientist>scientist)\n{\n cout << string( 100, '\\n' );\n cout << \"Scientist name: gender: born: died: age: \" << endl;\n cout << \"========================================================\" << endl;\n for (size_t i = 0; i< scientist.size(); ++i)\n {\n cout << left << setw(25) << scientist[i].getName()\n << setw(5) << right << scientist[i].getGender()\n << setw(10) << scientist[i].getBirth();\n\n\n if(scientist[i].getDeath() == 0)\n {\n cout << setw(8) << \"-\";\n }\n else\n {\n cout << setw(8) << scientist[i].getDeath();\n }\n cout << setw(8) << scientist[i].getAge() << endl;\n\n\n }\n cout << endl;\n}\nint ConsoleUI::userCheckInput()\n{\n \/\/ Check if all data is correct\n while(true)\n {\n char answear;\n cout << \"Is this data correct? (input y\/n) or press q to quit\" << endl;\n cin >> answear;\n\n if(answear == 'y')\n {\n return 0;\n }\n else if (answear == 'n')\n {\n return 1;\n }\n else if (answear == 'q')\n {\n return 2;\n }\n else\n {\n cout << \"Invalid input!\";\n }\n\n }\n}\nvoid ConsoleUI::userMenuRemove()\n{\n string userInputName;\n cout << \"Remove a programmer\/computer scientist: \";\n cin.ignore();\n getline(cin, userInputName);\n\n _service.removeScientist(userInputName);\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_FEATURES_DESCRIPTOR_HPP\n#define OPENMVG_FEATURES_DESCRIPTOR_HPP\n\n#include \"openMVG\/numeric\/numeric.h\"\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <exception>\n\nnamespace openMVG {\nnamespace features {\n\n\/**\n * Class that handle descriptor (a data container of N values of type T).\n * SiftDescriptor => <uchar,128> or <float,128>\n\n * Surf 64 => <float,64>\n *\/\ntemplate <typename T, std::size_t N>\nclass Descriptor\n{\npublic:\n typedef Descriptor<T, N> This;\n typedef T value_type;\n typedef T bin_type;\n typedef std::size_t size_type;\n\n \/\/\/ Compile-time length of the descriptor\n static const size_type static_size = N;\n\n \/\/\/ Constructor\n inline Descriptor() {}\n\n inline Descriptor(T defaultValue)\n {\n for(size_type i = 0; i < N; ++i)\n data[i] = defaultValue;\n }\n\n \/\/\/ capacity\n inline size_type size() const { return N; }\n\n \/\/\/ Mutable and non-mutable bin getters\n inline bin_type& operator[](std::size_t i) { return data[i]; }\n inline bin_type operator[](std::size_t i) const { return data[i]; }\n\n \/\/ Atomic addition between two descriptors\n inline This& operator+=(const This other)\n {\n for(size_type i = 0; i < size(); ++i)\n data[i] += other[i];\n return *this;\n }\n\n \/\/ Division between two descriptors\n inline This operator\/(const This other) const\n {\n This res;\n for(size_type i = 0; i < size(); ++i)\n res[i] = data[i] \/ other[i];\n return res;\n }\n\n inline bin_type* getData() const {return (bin_type* ) (&data[0]);}\n\n \/\/\/ Ostream interface\n std::ostream& print(std::ostream& os) const;\n \/\/\/ Istream interface\n std::istream& read(std::istream& in);\n\n template<class Archive>\n void save(Archive & archive) const\n {\n std::vector<T> array(data,data+N);\n archive( array );\n }\n\n template<class Archive>\n void load(Archive & archive)\n {\n std::vector<T> array(N);\n archive( array );\n std::memcpy(data, array.data(), sizeof(T)*N);\n }\n\nprivate:\n bin_type data[N];\n};\n\n\/\/ Output stream definition\ntemplate <typename T, std::size_t N>\ninline std::ostream& operator<<(std::ostream& out, const Descriptor<T, N>& obj)\n{\n return obj.print(out); \/\/simply call the print method.\n}\n\n\/\/ Input stream definition\ntemplate <typename T, std::size_t N>\ninline std::istream& operator>>(std::istream& in, Descriptor<T, N>& obj)\n{\n return obj.read(in); \/\/simply call the read method.\n}\n\n\/\/-- Use specialization to handle unsigned char case.\n\/\/-- We do not want confuse unsigned char value with the spaces written in the file\n\ntemplate<typename T>\ninline std::ostream& printT(std::ostream& os, T *tab, size_t N)\n{\n std::copy( tab, &tab[N], std::ostream_iterator<T>(os,\" \"));\n return os;\n}\n\ntemplate<>\ninline std::ostream& printT<unsigned char>(std::ostream& os, unsigned char *tab, size_t N)\n{\n for(size_t i=0; i < N; ++i)\n os << (int)tab[i] << \" \";\n return os;\n}\n\ntemplate<typename T>\ninline std::istream& readT(std::istream& is, T *tab, size_t N)\n{\n for(size_t i=0; i<N; ++i) is >> tab[i];\n return is;\n}\n\ntemplate<>\ninline std::istream& readT<unsigned char>(std::istream& is, unsigned char *tab, size_t N)\n{\n int temp = -1;\n for(size_t i=0; i < N; ++i){\n is >> temp; tab[i] = (unsigned char)temp;\n }\n return is;\n}\n\ntemplate<typename T, std::size_t N>\nstd::ostream& Descriptor<T,N>::print(std::ostream& os) const\n{\n return printT<T>(os, (T*) &data[0], N);\n}\n\ntemplate<typename T, std::size_t N>\nstd::istream& Descriptor<T,N>::read(std::istream& in)\n{\n return readT<T>(in, (T*) &data[0], N);\n}\n\n\/\/\/ Read descriptors from file\ntemplate<typename DescriptorsT >\nstatic bool loadDescsFromFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n vec_desc.clear();\n\n std::ifstream fileIn(sfileNameDescs.c_str());\n std::copy(\n std::istream_iterator<typename DescriptorsT::value_type >(fileIn),\n std::istream_iterator<typename DescriptorsT::value_type >(),\n std::back_inserter(vec_desc));\n bool bOk = !fileIn.bad();\n fileIn.close();\n return bOk;\n}\n\n\/\/\/ Write descriptors to file\ntemplate<typename DescriptorsT >\nstatic bool saveDescsToFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n std::ofstream file(sfileNameDescs.c_str());\n std::copy(vec_desc.begin(), vec_desc.end(),\n std::ostream_iterator<typename DescriptorsT::value_type >(file,\"\\n\"));\n bool bOk = file.good();\n file.close();\n return bOk;\n}\n\n\n\/\/\/ Read descriptors from file (in binary mode)\ntemplate<typename DescriptorsT >\nstatic bool loadDescsFromBinFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc,\n bool append = false)\n{\n typedef typename DescriptorsT::value_type VALUE;\n\n if( !append ) \/\/ for compatibility\n vec_desc.clear();\n\n std::ifstream fileIn(sfileNameDescs.c_str(), std::ios::in | std::ios::binary);\n \n if(!fileIn.is_open())\n {\n std::cerr << \"Unable to open file \" << sfileNameDescs << std::endl;\n throw std::invalid_argument(\"Unable to open file \" + sfileNameDescs);\n }\n \n \/\/Read the number of descriptor in the file\n std::size_t cardDesc = 0;\n fileIn.read((char*) &cardDesc, sizeof(std::size_t));\n \/\/ Reserve is necessary to avoid iterator problems in case of cleared vector\n vec_desc.reserve(vec_desc.size() + cardDesc);\n typename DescriptorsT::const_iterator begin = vec_desc.end();\n vec_desc.resize(vec_desc.size() + cardDesc);\n for (typename DescriptorsT::const_iterator iter = begin;\n iter != vec_desc.end(); ++iter)\n {\n fileIn.read((char*) (*iter).getData(),\n VALUE::static_size*sizeof(typename VALUE::bin_type));\n }\n bool bOk = !fileIn.bad();\n fileIn.close();\n return bOk;\n}\n\n\/\/\/ Write descriptors to file (in binary mode)\ntemplate<typename DescriptorsT >\nstatic bool saveDescsToBinFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n typedef typename DescriptorsT::value_type VALUE;\n\n std::ofstream file(sfileNameDescs.c_str(), std::ios::out | std::ios::binary);\n \/\/Write the number of descriptor\n const std::size_t cardDesc = vec_desc.size();\n file.write((const char*) &cardDesc, sizeof(std::size_t));\n for (typename DescriptorsT::const_iterator iter = vec_desc.begin();\n iter != vec_desc.end(); ++iter) {\n file.write((const char*) (*iter).getData(),\n VALUE::static_size*sizeof(typename VALUE::bin_type));\n }\n bool bOk = file.good();\n file.close();\n return bOk;\n}\n\n} \/\/ namespace features\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_FEATURES_DESCRIPTOR_HPP\n<commit_msg>[features] add scaling operator to descriptor<commit_after>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_FEATURES_DESCRIPTOR_HPP\n#define OPENMVG_FEATURES_DESCRIPTOR_HPP\n\n#include \"openMVG\/numeric\/numeric.h\"\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <exception>\n\nnamespace openMVG {\nnamespace features {\n\n\/**\n * Class that handle descriptor (a data container of N values of type T).\n * SiftDescriptor => <uchar,128> or <float,128>\n\n * Surf 64 => <float,64>\n *\/\ntemplate <typename T, std::size_t N>\nclass Descriptor\n{\npublic:\n typedef Descriptor<T, N> This;\n typedef T value_type;\n typedef T bin_type;\n typedef std::size_t size_type;\n\n \/\/\/ Compile-time length of the descriptor\n static const size_type static_size = N;\n\n \/\/\/ Constructor\n inline Descriptor() {}\n\n inline Descriptor(T defaultValue)\n {\n for(size_type i = 0; i < N; ++i)\n data[i] = defaultValue;\n }\n\n \/\/\/ capacity\n inline size_type size() const { return N; }\n\n \/\/\/ Mutable and non-mutable bin getters\n inline bin_type& operator[](std::size_t i) { return data[i]; }\n inline bin_type operator[](std::size_t i) const { return data[i]; }\n\n \/\/ Atomic addition between two descriptors\n inline This& operator+=(const This other)\n {\n for(size_type i = 0; i < size(); ++i)\n data[i] += other[i];\n return *this;\n }\n\n \/\/ Division between two descriptors\n inline This operator\/(const This other) const\n {\n This res;\n for(size_type i = 0; i < size(); ++i)\n res[i] = data[i] \/ other[i];\n return res;\n }\n \n inline This& operator*=(const value_type scalar) \n {\n for(size_type i = 0; i < size(); ++i)\n data[i] *= scalar;\n return *this;\n }\n\n inline bin_type* getData() const {return (bin_type* ) (&data[0]);}\n\n \/\/\/ Ostream interface\n std::ostream& print(std::ostream& os) const;\n \/\/\/ Istream interface\n std::istream& read(std::istream& in);\n\n template<class Archive>\n void save(Archive & archive) const\n {\n std::vector<T> array(data,data+N);\n archive( array );\n }\n\n template<class Archive>\n void load(Archive & archive)\n {\n std::vector<T> array(N);\n archive( array );\n std::memcpy(data, array.data(), sizeof(T)*N);\n }\n\nprivate:\n bin_type data[N];\n};\n\n\/\/ Output stream definition\ntemplate <typename T, std::size_t N>\ninline std::ostream& operator<<(std::ostream& out, const Descriptor<T, N>& obj)\n{\n return obj.print(out); \/\/simply call the print method.\n}\n\n\/\/ Input stream definition\ntemplate <typename T, std::size_t N>\ninline std::istream& operator>>(std::istream& in, Descriptor<T, N>& obj)\n{\n return obj.read(in); \/\/simply call the read method.\n}\n\n\/\/-- Use specialization to handle unsigned char case.\n\/\/-- We do not want confuse unsigned char value with the spaces written in the file\n\ntemplate<typename T>\ninline std::ostream& printT(std::ostream& os, T *tab, size_t N)\n{\n std::copy( tab, &tab[N], std::ostream_iterator<T>(os,\" \"));\n return os;\n}\n\ntemplate<>\ninline std::ostream& printT<unsigned char>(std::ostream& os, unsigned char *tab, size_t N)\n{\n for(size_t i=0; i < N; ++i)\n os << (int)tab[i] << \" \";\n return os;\n}\n\ntemplate<typename T>\ninline std::istream& readT(std::istream& is, T *tab, size_t N)\n{\n for(size_t i=0; i<N; ++i) is >> tab[i];\n return is;\n}\n\ntemplate<>\ninline std::istream& readT<unsigned char>(std::istream& is, unsigned char *tab, size_t N)\n{\n int temp = -1;\n for(size_t i=0; i < N; ++i){\n is >> temp; tab[i] = (unsigned char)temp;\n }\n return is;\n}\n\ntemplate<typename T, std::size_t N>\nstd::ostream& Descriptor<T,N>::print(std::ostream& os) const\n{\n return printT<T>(os, (T*) &data[0], N);\n}\n\ntemplate<typename T, std::size_t N>\nstd::istream& Descriptor<T,N>::read(std::istream& in)\n{\n return readT<T>(in, (T*) &data[0], N);\n}\n\n\/\/\/ Read descriptors from file\ntemplate<typename DescriptorsT >\nstatic bool loadDescsFromFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n vec_desc.clear();\n\n std::ifstream fileIn(sfileNameDescs.c_str());\n std::copy(\n std::istream_iterator<typename DescriptorsT::value_type >(fileIn),\n std::istream_iterator<typename DescriptorsT::value_type >(),\n std::back_inserter(vec_desc));\n bool bOk = !fileIn.bad();\n fileIn.close();\n return bOk;\n}\n\n\/\/\/ Write descriptors to file\ntemplate<typename DescriptorsT >\nstatic bool saveDescsToFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n std::ofstream file(sfileNameDescs.c_str());\n std::copy(vec_desc.begin(), vec_desc.end(),\n std::ostream_iterator<typename DescriptorsT::value_type >(file,\"\\n\"));\n bool bOk = file.good();\n file.close();\n return bOk;\n}\n\n\n\/\/\/ Read descriptors from file (in binary mode)\ntemplate<typename DescriptorsT >\nstatic bool loadDescsFromBinFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc,\n bool append = false)\n{\n typedef typename DescriptorsT::value_type VALUE;\n\n if( !append ) \/\/ for compatibility\n vec_desc.clear();\n\n std::ifstream fileIn(sfileNameDescs.c_str(), std::ios::in | std::ios::binary);\n \n if(!fileIn.is_open())\n {\n std::cerr << \"Unable to open file \" << sfileNameDescs << std::endl;\n throw std::invalid_argument(\"Unable to open file \" + sfileNameDescs);\n }\n \n \/\/Read the number of descriptor in the file\n std::size_t cardDesc = 0;\n fileIn.read((char*) &cardDesc, sizeof(std::size_t));\n \/\/ Reserve is necessary to avoid iterator problems in case of cleared vector\n vec_desc.reserve(vec_desc.size() + cardDesc);\n typename DescriptorsT::const_iterator begin = vec_desc.end();\n vec_desc.resize(vec_desc.size() + cardDesc);\n for (typename DescriptorsT::const_iterator iter = begin;\n iter != vec_desc.end(); ++iter)\n {\n fileIn.read((char*) (*iter).getData(),\n VALUE::static_size*sizeof(typename VALUE::bin_type));\n }\n bool bOk = !fileIn.bad();\n fileIn.close();\n return bOk;\n}\n\n\/\/\/ Write descriptors to file (in binary mode)\ntemplate<typename DescriptorsT >\nstatic bool saveDescsToBinFile(\n const std::string & sfileNameDescs,\n DescriptorsT & vec_desc)\n{\n typedef typename DescriptorsT::value_type VALUE;\n\n std::ofstream file(sfileNameDescs.c_str(), std::ios::out | std::ios::binary);\n \/\/Write the number of descriptor\n const std::size_t cardDesc = vec_desc.size();\n file.write((const char*) &cardDesc, sizeof(std::size_t));\n for (typename DescriptorsT::const_iterator iter = vec_desc.begin();\n iter != vec_desc.end(); ++iter) {\n file.write((const char*) (*iter).getData(),\n VALUE::static_size*sizeof(typename VALUE::bin_type));\n }\n bool bOk = file.good();\n file.close();\n return bOk;\n}\n\n} \/\/ namespace features\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_FEATURES_DESCRIPTOR_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2008-2016 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"mainwindow.h\"\n#include \"settingspage.h\"\n#include \"systemmonitor.h\"\n#include \"pluginloader.h\"\n#include \"textdocument.h\"\n#include \"connectpage.h\"\n#include \"bufferview.h\"\n#include \"helppopup.h\"\n#include \"chatpage.h\"\n#include \"dock.h\"\n#include <IrcCommandQueue>\n#include <IrcBufferModel>\n#include <IrcConnection>\n#include <QApplication>\n#include <QCloseEvent>\n#include <QPushButton>\n#include <IrcBuffer>\n#include <QShortcut>\n#include <QSettings>\n#include <QMenuBar>\n#include <QTimer>\n#include <QUuid>\n#include <QMenu>\n#include <QDir>\n\nMainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)\n{\n d.view = 0;\n d.save = false;\n\n \/\/ TODO\n QDir::addSearchPath(\"black\", \":\/images\/black\");\n QDir::addSearchPath(\"gray\", \":\/images\/gray\");\n QDir::addSearchPath(\"white\", \":\/images\/white\");\n\n#ifndef Q_OS_MAC\n QIcon icon;\n icon.addFile(\":\/communi-16.png\");\n icon.addFile(\":\/communi-24.png\");\n icon.addFile(\":\/communi-32.png\");\n icon.addFile(\":\/communi-48.png\");\n icon.addFile(\":\/communi-64.png\");\n icon.addFile(\":\/communi-128.png\");\n icon.addFile(\":\/communi-256.png\");\n icon.addFile(\":\/communi-512.png\");\n setWindowIcon(icon);\n qApp->setWindowIcon(icon);\n#endif \/\/ Q_OS_MAC\n\n d.stack = new QStackedWidget(this);\n connect(d.stack, SIGNAL(currentChanged(int)), this, SLOT(updateTitle()));\n\n setCentralWidget(d.stack);\n\n d.chatPage = new ChatPage(this);\n setCurrentView(d.chatPage->currentView());\n connect(d.chatPage, SIGNAL(currentBufferChanged(IrcBuffer*)), this, SLOT(updateTitle()));\n connect(d.chatPage, SIGNAL(currentViewChanged(BufferView*)), this, SLOT(setCurrentView(BufferView*)));\n connect(this, SIGNAL(connectionAdded(IrcConnection*)), d.chatPage, SLOT(addConnection(IrcConnection*)));\n connect(this, SIGNAL(connectionRemoved(IrcConnection*)), d.chatPage, SLOT(removeConnection(IrcConnection*)));\n connect(this, SIGNAL(connectionRemoved(IrcConnection*)), this, SLOT(removeConnection(IrcConnection*)));\n\n d.stack->addWidget(d.chatPage);\n\n d.settingsPage = new SettingsPage(0);\n connect(d.settingsPage, SIGNAL(accepted()), this, SLOT(onSettingsAccepted()));\n connect(d.settingsPage, SIGNAL(rejected()), this, SLOT(pop()));\n\n QShortcut* shortcut = new QShortcut(QKeySequence::Quit, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(close()));\n\n shortcut = new QShortcut(QKeySequence::New, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(doConnect()));\n\n shortcut = new QShortcut(QKeySequence::Preferences, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(showSettings()));\n\n shortcut = new QShortcut(QKeySequence::Close, d.chatPage);\n connect(shortcut, SIGNAL(activated()), d.chatPage, SLOT(closeBuffer()));\n\n d.dock = new Dock(this);\n connect(d.chatPage, SIGNAL(alert(IrcMessage*)), d.dock, SLOT(alert(IrcMessage*)));\n\n d.monitor = new SystemMonitor(this);\n connect(d.monitor, SIGNAL(screenLocked()), d.dock, SLOT(activateAlert()));\n connect(d.monitor, SIGNAL(screenUnlocked()), d.dock, SLOT(deactivateAlert()));\n connect(d.monitor, SIGNAL(screenSaverStarted()), d.dock, SLOT(activateAlert()));\n connect(d.monitor, SIGNAL(screenSaverStopped()), d.dock, SLOT(deactivateAlert()));\n\n PluginLoader::instance()->windowCreated(this);\n PluginLoader::instance()->setConnectionsList(&(d.connections));\n\n restoreState();\n d.save = true;\n\n if (d.connections.isEmpty())\n doConnect();\n\n}\n\nMainWindow::~MainWindow()\n{\n PluginLoader::instance()->windowDestroyed(this);\n delete d.settingsPage;\n}\n\nvoid MainWindow::saveState()\n{\n if (!d.save)\n return;\n\n QSettings settings;\n settings.setValue(\"geometry\", saveGeometry());\n settings.setValue(\"settings\", d.chatPage->saveSettings());\n settings.setValue(\"state\", d.chatPage->saveState());\n\n QVariantList states;\n foreach (IrcConnection* connection, d.connections) {\n QVariantMap state;\n state.insert(\"connection\", connection->saveState());\n IrcBufferModel* model = connection->findChild<IrcBufferModel*>();\n if (model)\n state.insert(\"model\", model->saveState());\n states += state;\n }\n settings.setValue(\"connections\", states);\n}\n\nvoid MainWindow::restoreState()\n{\n QSettings settings;\n if (settings.contains(\"geometry\"))\n restoreGeometry(settings.value(\"geometry\").toByteArray());\n\n d.chatPage->restoreSettings(settings.value(\"settings\").toByteArray());\n\n foreach (const QVariant& v, settings.value(\"connections\").toList()) {\n QVariantMap state = v.toMap();\n IrcConnection* connection = new IrcConnection(d.chatPage);\n connection->restoreState(state.value(\"connection\").toByteArray());\n addConnection(connection);\n IrcBufferModel* model = connection->findChild<IrcBufferModel*>();\n if (model)\n model->restoreState(state.value(\"model\").toByteArray());\n }\n\n d.chatPage->restoreState(settings.value(\"state\").toByteArray());\n\n if (!settings.value(\"loggingLocation\").isValid()) {\n settings.setValue(\"loggingLocation\", QDir::homePath() + \"\/communi-irc-logs\");\n }\n\n d.settingsPage->setTheme(d.chatPage->theme());\n d.settingsPage->setLoggingEnabled(settings.value(\"loggingEnabled\", false).toBool());\n d.settingsPage->setLoggingLocation(settings.value(\"loggingLocation\").toString());\n\n PluginLoader::instance()->settingsChanged();\n\n if (d.settingsPage->loggingEnabled()) {\n PluginLoader::instance()->enablePlugin(\"libloggerplugin\");\n }\n else {\n PluginLoader::instance()->disablePlugin(\"libloggerplugin\");\n }\n}\n\nBufferView* MainWindow::currentView() const\n{\n return d.view;\n}\n\nvoid MainWindow::setCurrentView(BufferView* view)\n{\n if (d.view != view) {\n d.view = view;\n emit currentViewChanged(view);\n }\n}\n\nQList<IrcConnection*> MainWindow::connections() const\n{\n return d.connections;\n}\n\nvoid MainWindow::addConnection(IrcConnection* connection)\n{\n QVariantMap ud = connection->userData();\n if (!ud.contains(\"uuid\")) {\n ud.insert(\"uuid\", QUuid::createUuid());\n connection->setUserData(ud);\n }\n\n connection->setReconnectDelay(15);\n connection->network()->setRequestedCapabilities(Irc::supportedCapabilities());\n\n IrcCommandQueue* queue = new IrcCommandQueue(connection);\n queue->setConnection(connection);\n\n \/\/ backwards compatibility\n if (connection->nickNames().isEmpty())\n connection->setNickNames(QStringList() << connection->nickName());\n if (connection->servers().isEmpty())\n connection->setServers(QStringList() << QString(\"%1 %2%3\").arg(connection->host())\n .arg(connection->isSecure() ? \"+\" : \"\")\n .arg(connection->port()));\n\n connect(d.monitor, SIGNAL(wake()), connection, SLOT(open()));\n connect(d.monitor, SIGNAL(online()), connection, SLOT(open()));\n\n connect(d.monitor, SIGNAL(sleep()), connection, SLOT(quit()));\n connect(d.monitor, SIGNAL(sleep()), connection, SLOT(close()));\n\n connect(d.monitor, SIGNAL(offline()), connection, SLOT(close()));\n\n d.connections += connection;\n connect(connection, SIGNAL(enabledChanged(bool)), this, SLOT(saveState()));\n connect(connection, SIGNAL(destroyed(IrcConnection*)), this, SLOT(removeConnection(IrcConnection*)));\n emit connectionAdded(connection);\n\n saveState();\n}\n\nvoid MainWindow::removeConnection(IrcConnection* connection)\n{\n if (d.connections.removeOne(connection))\n emit connectionRemoved(connection);\n if (d.connections.isEmpty())\n doConnect();\n else\n saveState();\n}\n\nvoid MainWindow::push(QWidget* page)\n{\n QWidget* prev = d.stack->currentWidget();\n\n if (prev == page)\n return;\n\n if (prev) {\n prev->setProperty(\"__focus_widget__\", QVariant::fromValue(prev->focusWidget()));\n prev->setEnabled(false);\n }\n d.stack->addWidget(page);\n d.stack->setCurrentWidget(page);\n page->setFocus();\n}\n\nvoid MainWindow::pop()\n{\n QWidget* page = d.stack->currentWidget();\n if (!qobject_cast<ChatPage*>(page)) {\n d.stack->removeWidget(page);\n d.stack->setCurrentIndex(d.stack->count() - 1);\n QWidget* current = d.stack->currentWidget();\n if (current) {\n current->setEnabled(true);\n QWidget* fw = current->property(\"__focus_widget__\").value<QWidget*>();\n if (fw)\n fw->setFocus();\n }\n\n \/\/ Don't delete the settings page, it has a single instance\n if (page != d.settingsPage)\n page->deleteLater();\n }\n}\n\nQSize MainWindow::sizeHint() const\n{\n return QSize(800, 600);\n}\n\nbool MainWindow::event(QEvent* event)\n{\n if (event->type() == QEvent::ActivationChange) {\n if (isActiveWindow())\n emit activated();\n }\n return QMainWindow::event(event);\n}\n\nvoid MainWindow::closeEvent(QCloseEvent* event)\n{\n if (isVisible()) {\n saveState();\n d.save = false;\n\n foreach (IrcConnection* connection, d.connections) {\n connection->quit(qApp->property(\"description\").toString());\n connection->close();\n }\n\n \/\/ let the sessions close in the background\n hide();\n event->ignore();\n QTimer::singleShot(1000, qApp, SLOT(quit()));\n }\n}\n\nvoid MainWindow::showEvent(QShowEvent* event)\n{\n PluginLoader::instance()->windowShowEvent(this, event);\n}\n\nvoid MainWindow::doConnect()\n{\n for (int i = 0; i < d.stack->count(); ++i) {\n ConnectPage* page = qobject_cast<ConnectPage*>(d.stack->widget(i));\n if (page) {\n d.stack->setCurrentWidget(page);\n return;\n }\n }\n\n ConnectPage* page = new ConnectPage(this);\n page->buttonBox()->button(QDialogButtonBox::Cancel)->setEnabled(!d.connections.isEmpty());\n connect(page, SIGNAL(accepted()), this, SLOT(onConnectAccepted()));\n connect(page, SIGNAL(rejected()), this, SLOT(pop()));\n push(page);\n}\n\nvoid MainWindow::onEditAccepted()\n{\n ConnectPage* page = qobject_cast<ConnectPage*>(sender());\n if (page) {\n IrcConnection* connection = page->connection();\n connection->setServers(page->servers());\n connection->setNickNames(page->nickNames());\n connection->setRealName(page->realName());\n connection->setUserName(page->userName());\n connection->setDisplayName(page->displayName());\n connection->setPassword(page->password());\n connection->setSaslMechanism(page->saslMechanism());\n saveState();\n pop();\n }\n}\n\nvoid MainWindow::onConnectAccepted()\n{\n ConnectPage* page = qobject_cast<ConnectPage*>(sender());\n if (page) {\n IrcConnection* connection = new IrcConnection(d.chatPage);\n connection->setServers(page->servers());\n connection->setNickNames(page->nickNames());\n connection->setRealName(page->realName());\n connection->setUserName(page->userName());\n connection->setDisplayName(page->displayName());\n connection->setPassword(page->password());\n connection->setSaslMechanism(page->saslMechanism());\n addConnection(connection);\n pop();\n }\n}\n\nvoid MainWindow::onSettingsAccepted()\n{\n SettingsPage* page = qobject_cast<SettingsPage*>(sender());\n if (page) {\n d.chatPage->setTheme(page->theme());\n saveState();\n pop();\n\n QSettings settings;\n settings.setValue(\"loggingEnabled\", page->loggingEnabled());\n settings.setValue(\"loggingLocation\", page->loggingLocation());\n\n PluginLoader::instance()->settingsChanged();\n\n if (page->loggingEnabled()) {\n PluginLoader::instance()->enablePlugin(\"libloggerplugin\");\n }\n else {\n PluginLoader::instance()->disablePlugin(\"libloggerplugin\");\n }\n }\n}\n\nvoid MainWindow::updateTitle()\n{\n IrcBuffer* buffer = d.chatPage->currentBuffer();\n if (!buffer || d.stack->currentWidget() != d.chatPage)\n setWindowTitle(QCoreApplication::applicationName());\n else\n setWindowTitle(tr(\"%1 - %2\").arg(buffer->title(), QCoreApplication::applicationName()));\n}\n\nvoid MainWindow::showSettings()\n{\n push(d.settingsPage);\n}\n\nvoid MainWindow::showHelp()\n{\n HelpPopup* help = new HelpPopup(this);\n help->popup();\n}\n\nvoid MainWindow::editConnection(IrcConnection* connection)\n{\n ConnectPage* page = new ConnectPage(connection, this);\n connect(page, SIGNAL(accepted()), this, SLOT(onEditAccepted()));\n connect(page, SIGNAL(rejected()), this, SLOT(pop()));\n page->setServers(connection->servers());\n page->setNickNames(connection->nickNames());\n page->setRealName(connection->realName());\n page->setUserName(connection->userName());\n page->setDisplayName(connection->displayName());\n page->setPassword(connection->password());\n page->setSaslMechanism(connection->saslMechanism());\n push(page);\n}\n\nvoid MainWindow::toggleFullScreen()\n{\n if (!isFullScreen()) {\n showFullScreen();\n } else {\n showNormal();\n }\n}\n<commit_msg>Use QStandardPaths::writableLocation(AppDataLocation) for logs<commit_after>\/*\n Copyright (C) 2008-2016 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"mainwindow.h\"\n#include \"settingspage.h\"\n#include \"systemmonitor.h\"\n#include \"pluginloader.h\"\n#include \"textdocument.h\"\n#include \"connectpage.h\"\n#include \"bufferview.h\"\n#include \"helppopup.h\"\n#include \"chatpage.h\"\n#include \"dock.h\"\n#include <IrcCommandQueue>\n#include <IrcBufferModel>\n#include <QStandardPaths>\n#include <IrcConnection>\n#include <QApplication>\n#include <QCloseEvent>\n#include <QPushButton>\n#include <IrcBuffer>\n#include <QShortcut>\n#include <QSettings>\n#include <QMenuBar>\n#include <QTimer>\n#include <QUuid>\n#include <QMenu>\n#include <QDir>\n\nMainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)\n{\n d.view = 0;\n d.save = false;\n\n \/\/ TODO\n QDir::addSearchPath(\"black\", \":\/images\/black\");\n QDir::addSearchPath(\"gray\", \":\/images\/gray\");\n QDir::addSearchPath(\"white\", \":\/images\/white\");\n\n#ifndef Q_OS_MAC\n QIcon icon;\n icon.addFile(\":\/communi-16.png\");\n icon.addFile(\":\/communi-24.png\");\n icon.addFile(\":\/communi-32.png\");\n icon.addFile(\":\/communi-48.png\");\n icon.addFile(\":\/communi-64.png\");\n icon.addFile(\":\/communi-128.png\");\n icon.addFile(\":\/communi-256.png\");\n icon.addFile(\":\/communi-512.png\");\n setWindowIcon(icon);\n qApp->setWindowIcon(icon);\n#endif \/\/ Q_OS_MAC\n\n d.stack = new QStackedWidget(this);\n connect(d.stack, SIGNAL(currentChanged(int)), this, SLOT(updateTitle()));\n\n setCentralWidget(d.stack);\n\n d.chatPage = new ChatPage(this);\n setCurrentView(d.chatPage->currentView());\n connect(d.chatPage, SIGNAL(currentBufferChanged(IrcBuffer*)), this, SLOT(updateTitle()));\n connect(d.chatPage, SIGNAL(currentViewChanged(BufferView*)), this, SLOT(setCurrentView(BufferView*)));\n connect(this, SIGNAL(connectionAdded(IrcConnection*)), d.chatPage, SLOT(addConnection(IrcConnection*)));\n connect(this, SIGNAL(connectionRemoved(IrcConnection*)), d.chatPage, SLOT(removeConnection(IrcConnection*)));\n connect(this, SIGNAL(connectionRemoved(IrcConnection*)), this, SLOT(removeConnection(IrcConnection*)));\n\n d.stack->addWidget(d.chatPage);\n\n d.settingsPage = new SettingsPage(0);\n connect(d.settingsPage, SIGNAL(accepted()), this, SLOT(onSettingsAccepted()));\n connect(d.settingsPage, SIGNAL(rejected()), this, SLOT(pop()));\n\n QShortcut* shortcut = new QShortcut(QKeySequence::Quit, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(close()));\n\n shortcut = new QShortcut(QKeySequence::New, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(doConnect()));\n\n shortcut = new QShortcut(QKeySequence::Preferences, this);\n connect(shortcut, SIGNAL(activated()), this, SLOT(showSettings()));\n\n shortcut = new QShortcut(QKeySequence::Close, d.chatPage);\n connect(shortcut, SIGNAL(activated()), d.chatPage, SLOT(closeBuffer()));\n\n d.dock = new Dock(this);\n connect(d.chatPage, SIGNAL(alert(IrcMessage*)), d.dock, SLOT(alert(IrcMessage*)));\n\n d.monitor = new SystemMonitor(this);\n connect(d.monitor, SIGNAL(screenLocked()), d.dock, SLOT(activateAlert()));\n connect(d.monitor, SIGNAL(screenUnlocked()), d.dock, SLOT(deactivateAlert()));\n connect(d.monitor, SIGNAL(screenSaverStarted()), d.dock, SLOT(activateAlert()));\n connect(d.monitor, SIGNAL(screenSaverStopped()), d.dock, SLOT(deactivateAlert()));\n\n PluginLoader::instance()->windowCreated(this);\n PluginLoader::instance()->setConnectionsList(&(d.connections));\n\n restoreState();\n d.save = true;\n\n if (d.connections.isEmpty())\n doConnect();\n\n}\n\nMainWindow::~MainWindow()\n{\n PluginLoader::instance()->windowDestroyed(this);\n delete d.settingsPage;\n}\n\nvoid MainWindow::saveState()\n{\n if (!d.save)\n return;\n\n QSettings settings;\n settings.setValue(\"geometry\", saveGeometry());\n settings.setValue(\"settings\", d.chatPage->saveSettings());\n settings.setValue(\"state\", d.chatPage->saveState());\n\n QVariantList states;\n foreach (IrcConnection* connection, d.connections) {\n QVariantMap state;\n state.insert(\"connection\", connection->saveState());\n IrcBufferModel* model = connection->findChild<IrcBufferModel*>();\n if (model)\n state.insert(\"model\", model->saveState());\n states += state;\n }\n settings.setValue(\"connections\", states);\n}\n\nvoid MainWindow::restoreState()\n{\n QSettings settings;\n if (settings.contains(\"geometry\"))\n restoreGeometry(settings.value(\"geometry\").toByteArray());\n\n d.chatPage->restoreSettings(settings.value(\"settings\").toByteArray());\n\n foreach (const QVariant& v, settings.value(\"connections\").toList()) {\n QVariantMap state = v.toMap();\n IrcConnection* connection = new IrcConnection(d.chatPage);\n connection->restoreState(state.value(\"connection\").toByteArray());\n addConnection(connection);\n IrcBufferModel* model = connection->findChild<IrcBufferModel*>();\n if (model)\n model->restoreState(state.value(\"model\").toByteArray());\n }\n\n d.chatPage->restoreState(settings.value(\"state\").toByteArray());\n\n if (!settings.value(\"loggingLocation\").isValid()) {\n#if QT_VERSION >= 0x050400\n settings.setValue(\"loggingLocation\", QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"\/logs\");\n#else\n settings.setValue(\"loggingLocation\", QStandardPaths::writableLocation(QStandardPaths::DataLocation) + \"\/logs\");\n#endif\n }\n\n d.settingsPage->setTheme(d.chatPage->theme());\n d.settingsPage->setLoggingEnabled(settings.value(\"loggingEnabled\", false).toBool());\n d.settingsPage->setLoggingLocation(settings.value(\"loggingLocation\").toString());\n\n PluginLoader::instance()->settingsChanged();\n\n if (d.settingsPage->loggingEnabled()) {\n PluginLoader::instance()->enablePlugin(\"libloggerplugin\");\n }\n else {\n PluginLoader::instance()->disablePlugin(\"libloggerplugin\");\n }\n}\n\nBufferView* MainWindow::currentView() const\n{\n return d.view;\n}\n\nvoid MainWindow::setCurrentView(BufferView* view)\n{\n if (d.view != view) {\n d.view = view;\n emit currentViewChanged(view);\n }\n}\n\nQList<IrcConnection*> MainWindow::connections() const\n{\n return d.connections;\n}\n\nvoid MainWindow::addConnection(IrcConnection* connection)\n{\n QVariantMap ud = connection->userData();\n if (!ud.contains(\"uuid\")) {\n ud.insert(\"uuid\", QUuid::createUuid());\n connection->setUserData(ud);\n }\n\n connection->setReconnectDelay(15);\n connection->network()->setRequestedCapabilities(Irc::supportedCapabilities());\n\n IrcCommandQueue* queue = new IrcCommandQueue(connection);\n queue->setConnection(connection);\n\n \/\/ backwards compatibility\n if (connection->nickNames().isEmpty())\n connection->setNickNames(QStringList() << connection->nickName());\n if (connection->servers().isEmpty())\n connection->setServers(QStringList() << QString(\"%1 %2%3\").arg(connection->host())\n .arg(connection->isSecure() ? \"+\" : \"\")\n .arg(connection->port()));\n\n connect(d.monitor, SIGNAL(wake()), connection, SLOT(open()));\n connect(d.monitor, SIGNAL(online()), connection, SLOT(open()));\n\n connect(d.monitor, SIGNAL(sleep()), connection, SLOT(quit()));\n connect(d.monitor, SIGNAL(sleep()), connection, SLOT(close()));\n\n connect(d.monitor, SIGNAL(offline()), connection, SLOT(close()));\n\n d.connections += connection;\n connect(connection, SIGNAL(enabledChanged(bool)), this, SLOT(saveState()));\n connect(connection, SIGNAL(destroyed(IrcConnection*)), this, SLOT(removeConnection(IrcConnection*)));\n emit connectionAdded(connection);\n\n saveState();\n}\n\nvoid MainWindow::removeConnection(IrcConnection* connection)\n{\n if (d.connections.removeOne(connection))\n emit connectionRemoved(connection);\n if (d.connections.isEmpty())\n doConnect();\n else\n saveState();\n}\n\nvoid MainWindow::push(QWidget* page)\n{\n QWidget* prev = d.stack->currentWidget();\n\n if (prev == page)\n return;\n\n if (prev) {\n prev->setProperty(\"__focus_widget__\", QVariant::fromValue(prev->focusWidget()));\n prev->setEnabled(false);\n }\n d.stack->addWidget(page);\n d.stack->setCurrentWidget(page);\n page->setFocus();\n}\n\nvoid MainWindow::pop()\n{\n QWidget* page = d.stack->currentWidget();\n if (!qobject_cast<ChatPage*>(page)) {\n d.stack->removeWidget(page);\n d.stack->setCurrentIndex(d.stack->count() - 1);\n QWidget* current = d.stack->currentWidget();\n if (current) {\n current->setEnabled(true);\n QWidget* fw = current->property(\"__focus_widget__\").value<QWidget*>();\n if (fw)\n fw->setFocus();\n }\n\n \/\/ Don't delete the settings page, it has a single instance\n if (page != d.settingsPage)\n page->deleteLater();\n }\n}\n\nQSize MainWindow::sizeHint() const\n{\n return QSize(800, 600);\n}\n\nbool MainWindow::event(QEvent* event)\n{\n if (event->type() == QEvent::ActivationChange) {\n if (isActiveWindow())\n emit activated();\n }\n return QMainWindow::event(event);\n}\n\nvoid MainWindow::closeEvent(QCloseEvent* event)\n{\n if (isVisible()) {\n saveState();\n d.save = false;\n\n foreach (IrcConnection* connection, d.connections) {\n connection->quit(qApp->property(\"description\").toString());\n connection->close();\n }\n\n \/\/ let the sessions close in the background\n hide();\n event->ignore();\n QTimer::singleShot(1000, qApp, SLOT(quit()));\n }\n}\n\nvoid MainWindow::showEvent(QShowEvent* event)\n{\n PluginLoader::instance()->windowShowEvent(this, event);\n}\n\nvoid MainWindow::doConnect()\n{\n for (int i = 0; i < d.stack->count(); ++i) {\n ConnectPage* page = qobject_cast<ConnectPage*>(d.stack->widget(i));\n if (page) {\n d.stack->setCurrentWidget(page);\n return;\n }\n }\n\n ConnectPage* page = new ConnectPage(this);\n page->buttonBox()->button(QDialogButtonBox::Cancel)->setEnabled(!d.connections.isEmpty());\n connect(page, SIGNAL(accepted()), this, SLOT(onConnectAccepted()));\n connect(page, SIGNAL(rejected()), this, SLOT(pop()));\n push(page);\n}\n\nvoid MainWindow::onEditAccepted()\n{\n ConnectPage* page = qobject_cast<ConnectPage*>(sender());\n if (page) {\n IrcConnection* connection = page->connection();\n connection->setServers(page->servers());\n connection->setNickNames(page->nickNames());\n connection->setRealName(page->realName());\n connection->setUserName(page->userName());\n connection->setDisplayName(page->displayName());\n connection->setPassword(page->password());\n connection->setSaslMechanism(page->saslMechanism());\n saveState();\n pop();\n }\n}\n\nvoid MainWindow::onConnectAccepted()\n{\n ConnectPage* page = qobject_cast<ConnectPage*>(sender());\n if (page) {\n IrcConnection* connection = new IrcConnection(d.chatPage);\n connection->setServers(page->servers());\n connection->setNickNames(page->nickNames());\n connection->setRealName(page->realName());\n connection->setUserName(page->userName());\n connection->setDisplayName(page->displayName());\n connection->setPassword(page->password());\n connection->setSaslMechanism(page->saslMechanism());\n addConnection(connection);\n pop();\n }\n}\n\nvoid MainWindow::onSettingsAccepted()\n{\n SettingsPage* page = qobject_cast<SettingsPage*>(sender());\n if (page) {\n d.chatPage->setTheme(page->theme());\n saveState();\n pop();\n\n QSettings settings;\n settings.setValue(\"loggingEnabled\", page->loggingEnabled());\n settings.setValue(\"loggingLocation\", page->loggingLocation());\n\n PluginLoader::instance()->settingsChanged();\n\n if (page->loggingEnabled()) {\n PluginLoader::instance()->enablePlugin(\"libloggerplugin\");\n }\n else {\n PluginLoader::instance()->disablePlugin(\"libloggerplugin\");\n }\n }\n}\n\nvoid MainWindow::updateTitle()\n{\n IrcBuffer* buffer = d.chatPage->currentBuffer();\n if (!buffer || d.stack->currentWidget() != d.chatPage)\n setWindowTitle(QCoreApplication::applicationName());\n else\n setWindowTitle(tr(\"%1 - %2\").arg(buffer->title(), QCoreApplication::applicationName()));\n}\n\nvoid MainWindow::showSettings()\n{\n push(d.settingsPage);\n}\n\nvoid MainWindow::showHelp()\n{\n HelpPopup* help = new HelpPopup(this);\n help->popup();\n}\n\nvoid MainWindow::editConnection(IrcConnection* connection)\n{\n ConnectPage* page = new ConnectPage(connection, this);\n connect(page, SIGNAL(accepted()), this, SLOT(onEditAccepted()));\n connect(page, SIGNAL(rejected()), this, SLOT(pop()));\n page->setServers(connection->servers());\n page->setNickNames(connection->nickNames());\n page->setRealName(connection->realName());\n page->setUserName(connection->userName());\n page->setDisplayName(connection->displayName());\n page->setPassword(connection->password());\n page->setSaslMechanism(connection->saslMechanism());\n push(page);\n}\n\nvoid MainWindow::toggleFullScreen()\n{\n if (!isFullScreen()) {\n showFullScreen();\n } else {\n showNormal();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: refernce.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 15:18:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include <limits.h>\n#include <vos\/diagnose.hxx>\n\n#include <vos\/refernce.hxx>\n\n#ifdef _USE_NAMESPACE\nusing namespace vos;\n#endif\n\nORefCount::~ORefCount()\n{\n\n}\n\n\nOReference::OReference()\n{\n}\n\nOReference::~OReference()\n{\n VOS_ASSERT(m_RefCount.referenced() == 0);\n}\n\nIReference::RefCount OReference::acquire()\n{\n return (m_RefCount.acquire());\n}\n\nIReference::RefCount OReference::release()\n{\n RefCount Count = m_RefCount.release();\n\n if (Count == 0)\n delete this;\n\n return (Count);\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.150); FILE MERGED 2005\/09\/05 17:40:17 rt 1.1.1.1.150.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: refernce.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 09:09:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include <limits.h>\n#include <vos\/diagnose.hxx>\n\n#include <vos\/refernce.hxx>\n\n#ifdef _USE_NAMESPACE\nusing namespace vos;\n#endif\n\nORefCount::~ORefCount()\n{\n\n}\n\n\nOReference::OReference()\n{\n}\n\nOReference::~OReference()\n{\n VOS_ASSERT(m_RefCount.referenced() == 0);\n}\n\nIReference::RefCount OReference::acquire()\n{\n return (m_RefCount.acquire());\n}\n\nIReference::RefCount OReference::release()\n{\n RefCount Count = m_RefCount.release();\n\n if (Count == 0)\n delete this;\n\n return (Count);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010-2011 OTClient <https:\/\/github.com\/edubart\/otclient>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"spritemanager.h\"\n#include <framework\/core\/resourcemanager.h>\n#include <framework\/graphics\/graphics.h>\n\nSpriteManager g_sprites;\n\nSpriteManager::SpriteManager()\n{\n m_spritesCount = 0;\n m_signature = 0;\n}\n\nbool SpriteManager::load(const std::string& file)\n{\n try {\n g_resources.loadFile(file, m_fin);\n m_signature = Fw::getU32(m_fin);\n m_spritesCount = Fw::getU16(m_fin);\n m_sprites.resize(m_spritesCount);\n return true;\n } catch(std::exception& e) {\n logError(\"faile to load sprites from '\", file, \"': \", e.what());\n return false;\n }\n}\n\nvoid SpriteManager::unload()\n{\n m_sprites.clear();\n m_spritesCount = 0;\n m_signature = 0;\n}\n\nTexturePtr SpriteManager::loadSpriteTexture(int id)\n{\n m_fin.seekg(((id-1) * 4) + 6, std::ios_base::beg);\n\n uint32 spriteAddress = Fw::getU32(m_fin);\n\n \/\/ no sprite? return an empty texture\n if(spriteAddress == 0)\n return g_graphics.getEmptyTexture();\n\n m_fin.seekg(spriteAddress, std::ios_base::beg);\n assert(m_fin.good());\n\n \/\/ skip color key\n Fw::getU8(m_fin);\n Fw::getU8(m_fin);\n Fw::getU8(m_fin);\n\n uint16 pixelDataSize = Fw::getU16(m_fin);\n\n uchar pixels[4096];\n int writePos = 0;\n int read = 0;\n\n \/\/ decompress pixels\n while(read < pixelDataSize) {\n uint16 transparentPixels, coloredPixels;\n m_fin.read((char*)&transparentPixels, 2);\n m_fin.read((char*)&coloredPixels, 2);\n\n for(int i = 0; i < transparentPixels; i++) {\n pixels[writePos + 0] = 0x00;\n pixels[writePos + 1] = 0x00;\n pixels[writePos + 2] = 0x00;\n pixels[writePos + 3] = 0x00;\n writePos += 4;\n }\n\n for(int i = 0; i < coloredPixels; i++) {\n pixels[writePos + 0] = Fw::getU8(m_fin);\n pixels[writePos + 1] = Fw::getU8(m_fin);\n pixels[writePos + 2] = Fw::getU8(m_fin);\n pixels[writePos + 3] = 0xFF;\n\n writePos += 4;\n }\n\n read += 4 + (3 * coloredPixels);\n }\n\n \/\/ fill remaining pixels with alpha\n while(writePos < 4096) {\n pixels[writePos + 0] = 0x00;\n pixels[writePos + 1] = 0x00;\n pixels[writePos + 2] = 0x00;\n pixels[writePos + 3] = 0x00;\n writePos += 4;\n }\n\n return TexturePtr(new Texture(32, 32, 4, pixels));\n}\n\nTexturePtr SpriteManager::loadSpriteMask(TexturePtr spriteTex, Otc::SpriteMask mask)\n{\n auto pixels = spriteTex->getPixels();\n\n static uint32 maskColors[4] = { Fw::red, Fw::green, Fw::blue, Fw::yellow };\n uint32 maskColor = maskColors[mask];\n uint32 whiteColor = Fw::white;\n uint32 alphaColor = Fw::alpha;\n\n \/\/ convert pixels\n \/\/ masked color -> white color\n \/\/ any other color -> alpha color\n for(int i=0;i<4096;i+=4) {\n uint32& currentColor = *(uint32*)&pixels[i];\n if(currentColor == maskColor)\n currentColor = whiteColor;\n else\n currentColor = alphaColor;\n }\n\n return TexturePtr(new Texture(32, 32, 4, &pixels[0]));\n}\n\nTexturePtr SpriteManager::getSpriteTexture(int id, Otc::SpriteMask mask)\n{\n if(id == 0)\n return g_graphics.getEmptyTexture();\n\n assert(id > 0 && id <= m_spritesCount);\n\n \/\/ load sprites on demand\n Sprite& sprite = m_sprites[id-1];\n if(!sprite.texture)\n sprite.texture = loadSpriteTexture(id);\n\n \/\/TODO: release unused sprites textures after X seconds\n \/\/ to avoid massive texture allocations\n\n if(mask != Otc::SpriteNoMask) {\n if(!sprite.masks[mask])\n sprite.masks[mask] = loadSpriteMask(sprite.texture, mask);\n return sprite.masks[mask];\n } else\n return sprite.texture;\n}\n<commit_msg>small fix to sprite loading<commit_after>\/*\n * Copyright (c) 2010-2011 OTClient <https:\/\/github.com\/edubart\/otclient>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"spritemanager.h\"\n#include <framework\/core\/resourcemanager.h>\n#include <framework\/graphics\/graphics.h>\n\nSpriteManager g_sprites;\n\nSpriteManager::SpriteManager()\n{\n m_spritesCount = 0;\n m_signature = 0;\n}\n\nbool SpriteManager::load(const std::string& file)\n{\n try {\n g_resources.loadFile(file, m_fin);\n m_signature = Fw::getU32(m_fin);\n m_spritesCount = Fw::getU16(m_fin);\n m_sprites.resize(m_spritesCount);\n return true;\n } catch(std::exception& e) {\n logError(\"faile to load sprites from '\", file, \"': \", e.what());\n return false;\n }\n}\n\nvoid SpriteManager::unload()\n{\n m_sprites.clear();\n m_spritesCount = 0;\n m_signature = 0;\n}\n\nTexturePtr SpriteManager::loadSpriteTexture(int id)\n{\n m_fin.seekg(((id-1) * 4) + 6, std::ios_base::beg);\n\n uint32 spriteAddress = Fw::getU32(m_fin);\n\n \/\/ no sprite? return an empty texture\n if(spriteAddress == 0)\n return g_graphics.getEmptyTexture();\n\n m_fin.seekg(spriteAddress, std::ios_base::beg);\n assert(m_fin.good());\n\n \/\/ skip color key\n Fw::getU8(m_fin);\n Fw::getU8(m_fin);\n Fw::getU8(m_fin);\n\n uint16 pixelDataSize = Fw::getU16(m_fin);\n\n uchar pixels[4096];\n int writePos = 0;\n int read = 0;\n\n \/\/ decompress pixels\n while(read < pixelDataSize) {\n uint16 transparentPixels, coloredPixels;\n m_fin.read((char*)&transparentPixels, 2);\n m_fin.read((char*)&coloredPixels, 2);\n\n if(writePos + transparentPixels*4 + coloredPixels*3 >= 4096)\n return g_graphics.getEmptyTexture();\n\n for(int i = 0; i < transparentPixels; i++) {\n pixels[writePos + 0] = 0x00;\n pixels[writePos + 1] = 0x00;\n pixels[writePos + 2] = 0x00;\n pixels[writePos + 3] = 0x00;\n writePos += 4;\n }\n\n for(int i = 0; i < coloredPixels; i++) {\n pixels[writePos + 0] = Fw::getU8(m_fin);\n pixels[writePos + 1] = Fw::getU8(m_fin);\n pixels[writePos + 2] = Fw::getU8(m_fin);\n pixels[writePos + 3] = 0xFF;\n\n writePos += 4;\n }\n\n read += 4 + (3 * coloredPixels);\n }\n\n \/\/ fill remaining pixels with alpha\n while(writePos < 4096) {\n pixels[writePos + 0] = 0x00;\n pixels[writePos + 1] = 0x00;\n pixels[writePos + 2] = 0x00;\n pixels[writePos + 3] = 0x00;\n writePos += 4;\n }\n\n return TexturePtr(new Texture(32, 32, 4, pixels));\n}\n\nTexturePtr SpriteManager::loadSpriteMask(TexturePtr spriteTex, Otc::SpriteMask mask)\n{\n auto pixels = spriteTex->getPixels();\n\n static uint32 maskColors[4] = { Fw::red, Fw::green, Fw::blue, Fw::yellow };\n uint32 maskColor = maskColors[mask];\n uint32 whiteColor = Fw::white;\n uint32 alphaColor = Fw::alpha;\n\n \/\/ convert pixels\n \/\/ masked color -> white color\n \/\/ any other color -> alpha color\n for(int i=0;i<4096;i+=4) {\n uint32& currentColor = *(uint32*)&pixels[i];\n if(currentColor == maskColor)\n currentColor = whiteColor;\n else\n currentColor = alphaColor;\n }\n\n return TexturePtr(new Texture(32, 32, 4, &pixels[0]));\n}\n\nTexturePtr SpriteManager::getSpriteTexture(int id, Otc::SpriteMask mask)\n{\n if(id == 0)\n return g_graphics.getEmptyTexture();\n\n assert(id > 0 && id <= m_spritesCount);\n\n \/\/ load sprites on demand\n Sprite& sprite = m_sprites[id-1];\n if(!sprite.texture)\n sprite.texture = loadSpriteTexture(id);\n\n \/\/TODO: release unused sprites textures after X seconds\n \/\/ to avoid massive texture allocations\n\n if(mask != Otc::SpriteNoMask) {\n if(!sprite.masks[mask])\n sprite.masks[mask] = loadSpriteMask(sprite.texture, mask);\n return sprite.masks[mask];\n } else\n return sprite.texture;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n* Copyright (C) 2016 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"repo_property_tree.h\"\n#include \"..\/core\/\/model\/repo_node_utils.h\"\n\nusing namespace repo::lib;\n\nstatic const std::string XML_ATTR_TAG = \"<xmlattr>\";\n\nPropertyTree::PropertyTree() :\n\thackStrings(true)\n{\n}\n\nPropertyTree::PropertyTree(const bool &enableJSONWorkAround) :\n\thackStrings(false)\n{}\n\n\nPropertyTree::~PropertyTree()\n{\n}\n\n\/\/see http:\/\/stackoverflow.com\/questions\/2855741\/why-boost-property-tree-write-json-saves-everything-as-string-is-it-possible-to\nstruct stringTranslator\n{\n\ttypedef std::string internal_type;\n\ttypedef std::string external_type;\n\n\tboost::optional<std::string> get_value(const std::string &v) { return v.substr(1, v.size() - 2); }\n\tboost::optional<std::string> put_value(const std::string &v) { return '\"' + v + '\"'; }\n};\n\ntemplate <>\nvoid PropertyTree::addFieldAttribute(\n\tconst std::string &label,\n\tconst std::string &attribute,\n\tconst std::string &value\n\t)\n{\n\tstd::string actualLabel = XML_ATTR_TAG;\n\n\tif (!label.empty())\n\t\tactualLabel = label + \".\" + actualLabel;\n\n\taddToTree(actualLabel + \".\" + attribute, value);\n}\n\n\ntemplate <>\nvoid PropertyTree::addFieldAttribute(\n\tconst std::string &label,\n\tconst std::string &attribute,\n\tconst repo_vector_t &value\n\t)\n{\n\n\tstd::stringstream ss;\n\tss << value.x << \",\" << value.x << \",\" << value.z ;\n\n\n\taddFieldAttribute(label, attribute, ss.str());\n}\n\n\ntemplate <>\nvoid PropertyTree::addToTree<std::string>(\n\tconst std::string &label,\n\tconst std::string &value)\n{\n\tif (hackStrings)\n\t{\n\t\tif (label.empty())\n\t\t\ttree.put(label, value, stringTranslator());\n\t\telse\n\t\t\ttree.add(label, value, stringTranslator());\n\t}\n\telse\n\t{\n\t\tif (label.empty())\n\t\t\ttree.put(label, value);\n\t\telse\n\t\t\ttree.add(label, value);\n\t}\n\t\n}\n<commit_msg>#76 fix bbox<commit_after>\/**\n* Copyright (C) 2016 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"repo_property_tree.h\"\n#include \"..\/core\/\/model\/repo_node_utils.h\"\n\nusing namespace repo::lib;\n\nstatic const std::string XML_ATTR_TAG = \"<xmlattr>\";\n\nPropertyTree::PropertyTree() :\n\thackStrings(true)\n{\n}\n\nPropertyTree::PropertyTree(const bool &enableJSONWorkAround) :\n\thackStrings(false)\n{}\n\n\nPropertyTree::~PropertyTree()\n{\n}\n\n\/\/see http:\/\/stackoverflow.com\/questions\/2855741\/why-boost-property-tree-write-json-saves-everything-as-string-is-it-possible-to\nstruct stringTranslator\n{\n\ttypedef std::string internal_type;\n\ttypedef std::string external_type;\n\n\tboost::optional<std::string> get_value(const std::string &v) { return v.substr(1, v.size() - 2); }\n\tboost::optional<std::string> put_value(const std::string &v) { return '\"' + v + '\"'; }\n};\n\ntemplate <>\nvoid PropertyTree::addFieldAttribute(\n\tconst std::string &label,\n\tconst std::string &attribute,\n\tconst std::string &value\n\t)\n{\n\tstd::string actualLabel = XML_ATTR_TAG;\n\n\tif (!label.empty())\n\t\tactualLabel = label + \".\" + actualLabel;\n\n\taddToTree(actualLabel + \".\" + attribute, value);\n}\n\n\ntemplate <>\nvoid PropertyTree::addFieldAttribute(\n\tconst std::string &label,\n\tconst std::string &attribute,\n\tconst repo_vector_t &value\n\t)\n{\n\n\tstd::stringstream ss;\n\tss << value.x << \",\" << value.y << \",\" << value.z ;\n\n\n\taddFieldAttribute(label, attribute, ss.str());\n}\n\n\ntemplate <>\nvoid PropertyTree::addToTree<std::string>(\n\tconst std::string &label,\n\tconst std::string &value)\n{\n\tif (hackStrings)\n\t{\n\t\tif (label.empty())\n\t\t\ttree.put(label, value, stringTranslator());\n\t\telse\n\t\t\ttree.add(label, value, stringTranslator());\n\t}\n\telse\n\t{\n\t\tif (label.empty())\n\t\t\ttree.put(label, value);\n\t\telse\n\t\t\ttree.add(label, value);\n\t}\n\t\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DepthSensor.h\"\r\n#include \"librealsense\/rs.hpp\"\r\n\r\n#include \"cinder\/app\/app.h\"\r\n#include \"cinder\/Log.h\"\r\n\r\nusing namespace ci;\r\nusing namespace ci::app;\r\nusing namespace std;\r\nusing namespace Kinect;\r\n\r\nstruct DeviceRealSense : public Device\r\n{\r\n rs::context ctx;\r\n rs::device* dev = nullptr;\r\n float depthScale;\r\n\r\n const int32_t kWidth = 640;\r\n const int32_t kHeight = 480;\r\n\r\n static uint32_t getDeviceCount()\r\n {\r\n \/\/ TODO:\r\n return 1;\r\n }\r\n\r\n virtual float getDepthToMmScale()\r\n {\r\n return depthScale;\r\n }\r\n\r\n ~DeviceRealSense()\r\n {\r\n }\r\n\r\n \/\/ TODO:\r\n ivec2 getDepthSize() const\r\n {\r\n return{ kWidth, kHeight };\r\n }\r\n\r\n bool isValid() const\r\n {\r\n return dev != nullptr;;\r\n }\r\n\r\n DeviceRealSense(Option option)\r\n {\r\n this->option = option;\r\n\r\n if (ctx.get_device_count() == 0)\r\n {\r\n CI_LOG_E(\"Failed to connect to RealSense devices.\");\r\n return;\r\n }\r\n\r\n dev = ctx.get_device(option.deviceId);\r\n printf(\"\\nUsing device %s, an %s\\n\", option.deviceId, dev->get_name());\r\n printf(\" Serial number: %s\\n\", dev->get_serial());\r\n printf(\" Firmware version: %s\\n\", dev->get_firmware_version());\r\n\r\n if (option.enableDepth)\r\n {\r\n dev->enable_stream(rs::stream::depth, kWidth, kHeight, rs::format::z16, 60);\r\n depthScale = dev->get_depth_scale() * 1000;\r\n }\r\n\r\n if (option.enableColor)\r\n {\r\n dev->enable_stream(rs::stream::color, kWidth, kHeight, rs::format::rgb8, 60);\r\n }\r\n\r\n if (option.enableInfrared)\r\n {\r\n dev->enable_stream(rs::stream::infrared, kWidth, kHeight, rs::format::y8, 60);\r\n }\r\n\r\n dev->start();\r\n\r\n App::get()->getSignalUpdate().connect(std::bind(&DeviceRealSense::update, this));\r\n }\r\n\r\n void update()\r\n {\r\n if (option.enableDepth)\r\n {\r\n dev->wait_for_frames();\r\n\r\n if (option.enableDepth)\r\n {\r\n uint16_t* data = (uint16_t*)dev->get_frame_data(rs::stream::depth);\r\n depthChannel = Channel16u(kWidth, kHeight, sizeof(uint16_t) * kWidth, 1, data);\r\n signalDepthDirty.emit();\r\n }\r\n\r\n if (option.enableInfrared)\r\n {\r\n uint8_t* data = (uint8_t*)dev->get_frame_data(rs::stream::infrared);\r\n infraredChannel.is16bit = false;\r\n infraredChannel.u8 = Channel8u(kWidth, kHeight, sizeof(uint16_t) * kWidth, 1, data);\r\n }\r\n\r\n if (option.enableColor)\r\n {\r\n uint8_t* data = (uint8_t*)dev->get_frame_data(rs::stream::color);\r\n colorSurface = Surface8u(data, kWidth, kHeight, sizeof(uint8_t) * 3 * kWidth, SurfaceChannelOrder::RGB);\r\n }\r\n }\r\n }\r\n};\r\n\r\nuint32_t getRealSenseCount()\r\n{\r\n return DeviceRealSense::getDeviceCount();\r\n}\r\n\r\nDeviceRef createRealSense(Device::Option option)\r\n{\r\n return DeviceRef(new DeviceRealSense(option));\r\n}\r\n<commit_msg>Fix infrared stream for real sense.<commit_after>#include \"DepthSensor.h\"\r\n#include \"librealsense\/rs.hpp\"\r\n\r\n#include \"cinder\/app\/app.h\"\r\n#include \"cinder\/Log.h\"\r\n\r\nusing namespace ci;\r\nusing namespace ci::app;\r\nusing namespace std;\r\nusing namespace Kinect;\r\n\r\nstruct DeviceRealSense : public Device\r\n{\r\n rs::context ctx;\r\n rs::device* dev = nullptr;\r\n float depthScale;\r\n\r\n const int32_t kWidth = 640;\r\n const int32_t kHeight = 480;\r\n\r\n static uint32_t getDeviceCount()\r\n {\r\n \/\/ TODO:\r\n return 1;\r\n }\r\n\r\n virtual float getDepthToMmScale()\r\n {\r\n return depthScale;\r\n }\r\n\r\n ~DeviceRealSense()\r\n {\r\n }\r\n\r\n \/\/ TODO:\r\n ivec2 getDepthSize() const\r\n {\r\n return{ kWidth, kHeight };\r\n }\r\n\r\n bool isValid() const\r\n {\r\n return dev != nullptr;;\r\n }\r\n\r\n DeviceRealSense(Option option)\r\n {\r\n this->option = option;\r\n\r\n if (ctx.get_device_count() == 0)\r\n {\r\n CI_LOG_E(\"Failed to connect to RealSense devices.\");\r\n return;\r\n }\r\n\r\n dev = ctx.get_device(option.deviceId);\r\n printf(\"\\nUsing device %s, an %s\\n\", option.deviceId, dev->get_name());\r\n printf(\" Serial number: %s\\n\", dev->get_serial());\r\n printf(\" Firmware version: %s\\n\", dev->get_firmware_version());\r\n\r\n if (option.enableDepth)\r\n {\r\n dev->enable_stream(rs::stream::depth, kWidth, kHeight, rs::format::z16, 60);\r\n depthScale = dev->get_depth_scale() * 1000;\r\n }\r\n\r\n if (option.enableColor)\r\n {\r\n dev->enable_stream(rs::stream::color, kWidth, kHeight, rs::format::rgb8, 60);\r\n }\r\n\r\n if (option.enableInfrared)\r\n {\r\n dev->enable_stream(rs::stream::infrared, kWidth, kHeight, rs::format::y16, 60);\r\n }\r\n\r\n dev->start();\r\n\r\n App::get()->getSignalUpdate().connect(std::bind(&DeviceRealSense::update, this));\r\n }\r\n\r\n void update()\r\n {\r\n dev->wait_for_frames();\r\n\r\n if (option.enableDepth)\r\n {\r\n auto data = (uint16_t*)dev->get_frame_data(rs::stream::depth);\r\n depthChannel = Channel16u(kWidth, kHeight, sizeof(uint16_t) * kWidth, 1, data);\r\n signalDepthDirty.emit();\r\n }\r\n\r\n if (option.enableInfrared)\r\n {\r\n auto data = (uint16_t*)dev->get_frame_data(rs::stream::infrared);\r\n infraredChannel.is16bit = true;\r\n infraredChannel.u16 = Channel16u(kWidth, kHeight, sizeof(uint16_t) * kWidth, 1, data);\r\n signalInfraredDirty.emit();\r\n }\r\n\r\n if (option.enableColor)\r\n {\r\n uint8_t* data = (uint8_t*)dev->get_frame_data(rs::stream::color);\r\n colorSurface = Surface8u(data, kWidth, kHeight, sizeof(uint8_t) * 3 * kWidth, SurfaceChannelOrder::RGB);\r\n signalColorDirty.emit();\r\n }\r\n }\r\n};\r\n\r\nuint32_t getRealSenseCount()\r\n{\r\n return DeviceRealSense::getDeviceCount();\r\n}\r\n\r\nDeviceRef createRealSense(Device::Option option)\r\n{\r\n return DeviceRef(new DeviceRealSense(option));\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/===- OutputSections.cpp -------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OutputSections.h\"\n\n#include \"Config.h\"\n#include \"InputFiles.h\"\n#include \"OutputSegment.h\"\n#include \"SymbolTable.h\"\n#include \"lld\/Common\/ErrorHandler.h\"\n#include \"lld\/Common\/Memory.h\"\n#include \"lld\/Common\/Threads.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/LEB128.h\"\n\n#define DEBUG_TYPE \"lld\"\n\nusing namespace llvm;\nusing namespace llvm::wasm;\nusing namespace lld;\nusing namespace lld::wasm;\n\nenum class RelocEncoding {\n Uleb128,\n Sleb128,\n I32,\n};\n\nstatic StringRef sectionTypeToString(uint32_t SectionType) {\n switch (SectionType) {\n case WASM_SEC_CUSTOM:\n return \"CUSTOM\";\n case WASM_SEC_TYPE:\n return \"TYPE\";\n case WASM_SEC_IMPORT:\n return \"IMPORT\";\n case WASM_SEC_FUNCTION:\n return \"FUNCTION\";\n case WASM_SEC_TABLE:\n return \"TABLE\";\n case WASM_SEC_MEMORY:\n return \"MEMORY\";\n case WASM_SEC_GLOBAL:\n return \"GLOBAL\";\n case WASM_SEC_EXPORT:\n return \"EXPORT\";\n case WASM_SEC_START:\n return \"START\";\n case WASM_SEC_ELEM:\n return \"ELEM\";\n case WASM_SEC_CODE:\n return \"CODE\";\n case WASM_SEC_DATA:\n return \"DATA\";\n default:\n fatal(\"invalid section type\");\n }\n}\n\nstd::string lld::toString(OutputSection *Section) {\n std::string rtn = sectionTypeToString(Section->Type);\n if (!Section->Name.empty())\n rtn += \"(\" + Section->Name + \")\";\n return rtn;\n}\n\nstatic void applyRelocation(uint8_t *Buf, const OutputRelocation &Reloc) {\n DEBUG(dbgs() << \"write reloc: type=\" << Reloc.Reloc.Type\n << \" index=\" << Reloc.Reloc.Index << \" value=\" << Reloc.Value\n << \" offset=\" << Reloc.Reloc.Offset << \"\\n\");\n Buf += Reloc.Reloc.Offset;\n int64_t ExistingValue;\n switch (Reloc.Reloc.Type) {\n case R_WEBASSEMBLY_TYPE_INDEX_LEB:\n case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:\n ExistingValue = decodeULEB128(Buf);\n if (ExistingValue != Reloc.Reloc.Index) {\n DEBUG(dbgs() << \"existing value: \" << decodeULEB128(Buf) << \"\\n\");\n assert(decodeULEB128(Buf) == Reloc.Reloc.Index);\n }\n LLVM_FALLTHROUGH;\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:\n encodeULEB128(Reloc.Value, Buf, 5);\n break;\n case R_WEBASSEMBLY_TABLE_INDEX_SLEB:\n ExistingValue = decodeSLEB128(Buf);\n if (ExistingValue != Reloc.Reloc.Index) {\n DEBUG(dbgs() << \"existing value: \" << decodeSLEB128(Buf) << \"\\n\");\n assert(decodeSLEB128(Buf) == Reloc.Reloc.Index);\n }\n LLVM_FALLTHROUGH;\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n encodeSLEB128(static_cast<int32_t>(Reloc.Value), Buf, 5);\n break;\n case R_WEBASSEMBLY_TABLE_INDEX_I32:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n support::endian::write32<support::little>(Buf, Reloc.Value);\n break;\n default:\n llvm_unreachable(\"unknown relocation type\");\n }\n}\n\nstatic void applyRelocations(uint8_t *Buf,\n ArrayRef<OutputRelocation> Relocs) {\n log(\"applyRelocations: count=\" + Twine(Relocs.size()));\n for (const OutputRelocation &Reloc : Relocs) {\n applyRelocation(Buf, Reloc);\n }\n}\n\n\/\/ Relocations contain an index into the function, global or table index\n\/\/ space of the input file. This function takes a relocation and returns the\n\/\/ relocated index (i.e. translates from the input index space to the output\n\/\/ index space).\nstatic uint32_t calcNewIndex(const ObjFile &File, const WasmRelocation &Reloc) {\n switch (Reloc.Type) {\n case R_WEBASSEMBLY_TYPE_INDEX_LEB:\n return File.relocateTypeIndex(Reloc.Index);\n case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:\n return File.relocateFunctionIndex(Reloc.Index);\n case R_WEBASSEMBLY_TABLE_INDEX_I32:\n case R_WEBASSEMBLY_TABLE_INDEX_SLEB:\n return File.relocateTableIndex(Reloc.Index);\n case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n return File.relocateGlobalIndex(Reloc.Index);\n default:\n llvm_unreachable(\"unknown relocation type\");\n }\n}\n\n\/\/ Take a vector of relocations from an input file and create output\n\/\/ relocations based on them. Calculates the updated index and offset for\n\/\/ each relocation as well as the value to write out in the final binary.\nstatic void calcRelocations(const ObjFile &File,\n ArrayRef<WasmRelocation> Relocs,\n std::vector<OutputRelocation> &OutputRelocs,\n int32_t OutputOffset) {\n log(\"calcRelocations: \" + File.getName() + \" offset=\" + Twine(OutputOffset));\n for (const WasmRelocation &Reloc : Relocs) {\n OutputRelocation NewReloc;\n NewReloc.Reloc = Reloc;\n NewReloc.Reloc.Offset += OutputOffset;\n DEBUG(dbgs() << \"reloc: type=\" << Reloc.Type << \" index=\" << Reloc.Index\n << \" offset=\" << Reloc.Offset\n << \" newOffset=\" << NewReloc.Reloc.Offset << \"\\n\");\n\n if (Config->EmitRelocs)\n NewReloc.NewIndex = calcNewIndex(File, Reloc);\n else\n NewReloc.NewIndex = UINT32_MAX;\n\n switch (Reloc.Type) {\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n NewReloc.Value = File.getRelocatedAddress(Reloc.Index);\n if (NewReloc.Value != UINT32_MAX)\n NewReloc.Value += Reloc.Addend;\n break;\n default:\n NewReloc.Value = calcNewIndex(File, Reloc);\n break;\n }\n\n OutputRelocs.emplace_back(NewReloc);\n }\n}\n\nvoid OutputSection::createHeader(size_t BodySize) {\n raw_string_ostream OS(Header);\n debugWrite(OS.tell(),\n \"section type [\" + Twine(sectionTypeToString(Type)) + \"]\");\n writeUleb128(OS, Type, nullptr);\n writeUleb128(OS, BodySize, \"section size\");\n OS.flush();\n log(\"createHeader: \" + toString(this) + \" body=\" + Twine(BodySize) +\n \" total=\" + Twine(getSize()));\n}\n\nCodeSection::CodeSection(uint32_t NumFunctions, ArrayRef<ObjFile *> Objs)\n : OutputSection(WASM_SEC_CODE), InputObjects(Objs) {\n raw_string_ostream OS(CodeSectionHeader);\n writeUleb128(OS, NumFunctions, \"function count\");\n OS.flush();\n BodySize = CodeSectionHeader.size();\n\n for (ObjFile *File : InputObjects) {\n if (!File->CodeSection)\n continue;\n\n File->CodeOffset = BodySize;\n ArrayRef<uint8_t> Content = File->CodeSection->Content;\n unsigned HeaderSize = 0;\n decodeULEB128(Content.data(), &HeaderSize);\n\n calcRelocations(*File, File->CodeSection->Relocations,\n File->CodeRelocations, BodySize - HeaderSize);\n\n size_t PayloadSize = Content.size() - HeaderSize;\n BodySize += PayloadSize;\n }\n\n createHeader(BodySize);\n}\n\nvoid CodeSection::writeTo(uint8_t *Buf) {\n log(\"writing \" + toString(this));\n log(\" size=\" + Twine(getSize()));\n Buf += Offset;\n\n \/\/ Write section header\n memcpy(Buf, Header.data(), Header.size());\n Buf += Header.size();\n\n uint8_t *ContentsStart = Buf;\n\n \/\/ Write code section headers\n memcpy(Buf, CodeSectionHeader.data(), CodeSectionHeader.size());\n Buf += CodeSectionHeader.size();\n\n \/\/ Write code section bodies\n parallelForEach(InputObjects, [ContentsStart](ObjFile *File) {\n if (!File->CodeSection)\n return;\n\n ArrayRef<uint8_t> Content(File->CodeSection->Content);\n\n \/\/ Payload doesn't include the initial header (function count)\n unsigned HeaderSize = 0;\n decodeULEB128(Content.data(), &HeaderSize);\n\n size_t PayloadSize = Content.size() - HeaderSize;\n memcpy(ContentsStart + File->CodeOffset, Content.data() + HeaderSize,\n PayloadSize);\n\n log(\"applying relocations for: \" + File->getName());\n if (File->CodeRelocations.size())\n applyRelocations(ContentsStart, File->CodeRelocations);\n });\n}\n\nuint32_t CodeSection::numRelocations() const {\n uint32_t Count = 0;\n for (ObjFile *File : InputObjects)\n Count += File->CodeRelocations.size();\n return Count;\n}\n\nvoid CodeSection::writeRelocations(raw_ostream &OS) const {\n for (ObjFile *File : InputObjects)\n for (const OutputRelocation &Reloc : File->CodeRelocations)\n writeReloc(OS, Reloc);\n}\n\nDataSection::DataSection(ArrayRef<OutputSegment *> Segments)\n : OutputSection(WASM_SEC_DATA), Segments(Segments) {\n raw_string_ostream OS(DataSectionHeader);\n\n writeUleb128(OS, Segments.size(), \"data segment count\");\n OS.flush();\n BodySize = DataSectionHeader.size();\n\n for (OutputSegment *Segment : Segments) {\n raw_string_ostream OS(Segment->Header);\n writeUleb128(OS, 0, \"memory index\");\n writeUleb128(OS, WASM_OPCODE_I32_CONST, \"opcode:i32const\");\n writeSleb128(OS, Segment->StartVA, \"memory offset\");\n writeUleb128(OS, WASM_OPCODE_END, \"opcode:end\");\n writeUleb128(OS, Segment->Size, \"segment size\");\n OS.flush();\n Segment->setSectionOffset(BodySize);\n BodySize += Segment->Header.size();\n log(\"Data segment: size=\" + Twine(Segment->Size));\n for (const InputSegment *InputSeg : Segment->InputSegments) {\n uint32_t InputOffset = InputSeg->getInputSectionOffset();\n uint32_t OutputOffset = Segment->getSectionOffset() +\n Segment->Header.size() +\n InputSeg->getOutputSegmentOffset();\n calcRelocations(*InputSeg->File, InputSeg->Relocations, Relocations,\n OutputOffset - InputOffset);\n }\n BodySize += Segment->Size;\n }\n\n createHeader(BodySize);\n}\n\nvoid DataSection::writeTo(uint8_t *Buf) {\n log(\"writing \" + toString(this) + \" size=\" + Twine(getSize()) +\n \" body=\" + Twine(BodySize));\n Buf += Offset;\n\n \/\/ Write section header\n memcpy(Buf, Header.data(), Header.size());\n Buf += Header.size();\n\n uint8_t *ContentsStart = Buf;\n\n \/\/ Write data section headers\n memcpy(Buf, DataSectionHeader.data(), DataSectionHeader.size());\n\n parallelForEach(Segments, [ContentsStart](const OutputSegment *Segment) {\n \/\/ Write data segment header\n uint8_t *SegStart = ContentsStart + Segment->getSectionOffset();\n memcpy(SegStart, Segment->Header.data(), Segment->Header.size());\n\n \/\/ Write segment data payload\n for (const InputSegment *Input : Segment->InputSegments) {\n ArrayRef<uint8_t> Content(Input->Segment->Data.Content);\n memcpy(SegStart + Segment->Header.size() +\n Input->getOutputSegmentOffset(),\n Content.data(), Content.size());\n }\n });\n\n applyRelocations(ContentsStart, Relocations);\n}\n\nvoid DataSection::writeRelocations(raw_ostream &OS) const {\n for (const OutputRelocation &Reloc : Relocations)\n writeReloc(OS, Reloc);\n}\n<commit_msg>[WebAssebmly] Fix the single clang-format issue in `wasm` directory<commit_after>\/\/===- OutputSections.cpp -------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OutputSections.h\"\n\n#include \"Config.h\"\n#include \"InputFiles.h\"\n#include \"OutputSegment.h\"\n#include \"SymbolTable.h\"\n#include \"lld\/Common\/ErrorHandler.h\"\n#include \"lld\/Common\/Memory.h\"\n#include \"lld\/Common\/Threads.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/LEB128.h\"\n\n#define DEBUG_TYPE \"lld\"\n\nusing namespace llvm;\nusing namespace llvm::wasm;\nusing namespace lld;\nusing namespace lld::wasm;\n\nenum class RelocEncoding {\n Uleb128,\n Sleb128,\n I32,\n};\n\nstatic StringRef sectionTypeToString(uint32_t SectionType) {\n switch (SectionType) {\n case WASM_SEC_CUSTOM:\n return \"CUSTOM\";\n case WASM_SEC_TYPE:\n return \"TYPE\";\n case WASM_SEC_IMPORT:\n return \"IMPORT\";\n case WASM_SEC_FUNCTION:\n return \"FUNCTION\";\n case WASM_SEC_TABLE:\n return \"TABLE\";\n case WASM_SEC_MEMORY:\n return \"MEMORY\";\n case WASM_SEC_GLOBAL:\n return \"GLOBAL\";\n case WASM_SEC_EXPORT:\n return \"EXPORT\";\n case WASM_SEC_START:\n return \"START\";\n case WASM_SEC_ELEM:\n return \"ELEM\";\n case WASM_SEC_CODE:\n return \"CODE\";\n case WASM_SEC_DATA:\n return \"DATA\";\n default:\n fatal(\"invalid section type\");\n }\n}\n\nstd::string lld::toString(OutputSection *Section) {\n std::string rtn = sectionTypeToString(Section->Type);\n if (!Section->Name.empty())\n rtn += \"(\" + Section->Name + \")\";\n return rtn;\n}\n\nstatic void applyRelocation(uint8_t *Buf, const OutputRelocation &Reloc) {\n DEBUG(dbgs() << \"write reloc: type=\" << Reloc.Reloc.Type\n << \" index=\" << Reloc.Reloc.Index << \" value=\" << Reloc.Value\n << \" offset=\" << Reloc.Reloc.Offset << \"\\n\");\n Buf += Reloc.Reloc.Offset;\n int64_t ExistingValue;\n switch (Reloc.Reloc.Type) {\n case R_WEBASSEMBLY_TYPE_INDEX_LEB:\n case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:\n ExistingValue = decodeULEB128(Buf);\n if (ExistingValue != Reloc.Reloc.Index) {\n DEBUG(dbgs() << \"existing value: \" << decodeULEB128(Buf) << \"\\n\");\n assert(decodeULEB128(Buf) == Reloc.Reloc.Index);\n }\n LLVM_FALLTHROUGH;\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:\n encodeULEB128(Reloc.Value, Buf, 5);\n break;\n case R_WEBASSEMBLY_TABLE_INDEX_SLEB:\n ExistingValue = decodeSLEB128(Buf);\n if (ExistingValue != Reloc.Reloc.Index) {\n DEBUG(dbgs() << \"existing value: \" << decodeSLEB128(Buf) << \"\\n\");\n assert(decodeSLEB128(Buf) == Reloc.Reloc.Index);\n }\n LLVM_FALLTHROUGH;\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n encodeSLEB128(static_cast<int32_t>(Reloc.Value), Buf, 5);\n break;\n case R_WEBASSEMBLY_TABLE_INDEX_I32:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n support::endian::write32<support::little>(Buf, Reloc.Value);\n break;\n default:\n llvm_unreachable(\"unknown relocation type\");\n }\n}\n\nstatic void applyRelocations(uint8_t *Buf, ArrayRef<OutputRelocation> Relocs) {\n log(\"applyRelocations: count=\" + Twine(Relocs.size()));\n for (const OutputRelocation &Reloc : Relocs) {\n applyRelocation(Buf, Reloc);\n }\n}\n\n\/\/ Relocations contain an index into the function, global or table index\n\/\/ space of the input file. This function takes a relocation and returns the\n\/\/ relocated index (i.e. translates from the input index space to the output\n\/\/ index space).\nstatic uint32_t calcNewIndex(const ObjFile &File, const WasmRelocation &Reloc) {\n switch (Reloc.Type) {\n case R_WEBASSEMBLY_TYPE_INDEX_LEB:\n return File.relocateTypeIndex(Reloc.Index);\n case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:\n return File.relocateFunctionIndex(Reloc.Index);\n case R_WEBASSEMBLY_TABLE_INDEX_I32:\n case R_WEBASSEMBLY_TABLE_INDEX_SLEB:\n return File.relocateTableIndex(Reloc.Index);\n case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n return File.relocateGlobalIndex(Reloc.Index);\n default:\n llvm_unreachable(\"unknown relocation type\");\n }\n}\n\n\/\/ Take a vector of relocations from an input file and create output\n\/\/ relocations based on them. Calculates the updated index and offset for\n\/\/ each relocation as well as the value to write out in the final binary.\nstatic void calcRelocations(const ObjFile &File,\n ArrayRef<WasmRelocation> Relocs,\n std::vector<OutputRelocation> &OutputRelocs,\n int32_t OutputOffset) {\n log(\"calcRelocations: \" + File.getName() + \" offset=\" + Twine(OutputOffset));\n for (const WasmRelocation &Reloc : Relocs) {\n OutputRelocation NewReloc;\n NewReloc.Reloc = Reloc;\n NewReloc.Reloc.Offset += OutputOffset;\n DEBUG(dbgs() << \"reloc: type=\" << Reloc.Type << \" index=\" << Reloc.Index\n << \" offset=\" << Reloc.Offset\n << \" newOffset=\" << NewReloc.Reloc.Offset << \"\\n\");\n\n if (Config->EmitRelocs)\n NewReloc.NewIndex = calcNewIndex(File, Reloc);\n else\n NewReloc.NewIndex = UINT32_MAX;\n\n switch (Reloc.Type) {\n case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:\n case R_WEBASSEMBLY_MEMORY_ADDR_I32:\n case R_WEBASSEMBLY_MEMORY_ADDR_LEB:\n NewReloc.Value = File.getRelocatedAddress(Reloc.Index);\n if (NewReloc.Value != UINT32_MAX)\n NewReloc.Value += Reloc.Addend;\n break;\n default:\n NewReloc.Value = calcNewIndex(File, Reloc);\n break;\n }\n\n OutputRelocs.emplace_back(NewReloc);\n }\n}\n\nvoid OutputSection::createHeader(size_t BodySize) {\n raw_string_ostream OS(Header);\n debugWrite(OS.tell(),\n \"section type [\" + Twine(sectionTypeToString(Type)) + \"]\");\n writeUleb128(OS, Type, nullptr);\n writeUleb128(OS, BodySize, \"section size\");\n OS.flush();\n log(\"createHeader: \" + toString(this) + \" body=\" + Twine(BodySize) +\n \" total=\" + Twine(getSize()));\n}\n\nCodeSection::CodeSection(uint32_t NumFunctions, ArrayRef<ObjFile *> Objs)\n : OutputSection(WASM_SEC_CODE), InputObjects(Objs) {\n raw_string_ostream OS(CodeSectionHeader);\n writeUleb128(OS, NumFunctions, \"function count\");\n OS.flush();\n BodySize = CodeSectionHeader.size();\n\n for (ObjFile *File : InputObjects) {\n if (!File->CodeSection)\n continue;\n\n File->CodeOffset = BodySize;\n ArrayRef<uint8_t> Content = File->CodeSection->Content;\n unsigned HeaderSize = 0;\n decodeULEB128(Content.data(), &HeaderSize);\n\n calcRelocations(*File, File->CodeSection->Relocations,\n File->CodeRelocations, BodySize - HeaderSize);\n\n size_t PayloadSize = Content.size() - HeaderSize;\n BodySize += PayloadSize;\n }\n\n createHeader(BodySize);\n}\n\nvoid CodeSection::writeTo(uint8_t *Buf) {\n log(\"writing \" + toString(this));\n log(\" size=\" + Twine(getSize()));\n Buf += Offset;\n\n \/\/ Write section header\n memcpy(Buf, Header.data(), Header.size());\n Buf += Header.size();\n\n uint8_t *ContentsStart = Buf;\n\n \/\/ Write code section headers\n memcpy(Buf, CodeSectionHeader.data(), CodeSectionHeader.size());\n Buf += CodeSectionHeader.size();\n\n \/\/ Write code section bodies\n parallelForEach(InputObjects, [ContentsStart](ObjFile *File) {\n if (!File->CodeSection)\n return;\n\n ArrayRef<uint8_t> Content(File->CodeSection->Content);\n\n \/\/ Payload doesn't include the initial header (function count)\n unsigned HeaderSize = 0;\n decodeULEB128(Content.data(), &HeaderSize);\n\n size_t PayloadSize = Content.size() - HeaderSize;\n memcpy(ContentsStart + File->CodeOffset, Content.data() + HeaderSize,\n PayloadSize);\n\n log(\"applying relocations for: \" + File->getName());\n if (File->CodeRelocations.size())\n applyRelocations(ContentsStart, File->CodeRelocations);\n });\n}\n\nuint32_t CodeSection::numRelocations() const {\n uint32_t Count = 0;\n for (ObjFile *File : InputObjects)\n Count += File->CodeRelocations.size();\n return Count;\n}\n\nvoid CodeSection::writeRelocations(raw_ostream &OS) const {\n for (ObjFile *File : InputObjects)\n for (const OutputRelocation &Reloc : File->CodeRelocations)\n writeReloc(OS, Reloc);\n}\n\nDataSection::DataSection(ArrayRef<OutputSegment *> Segments)\n : OutputSection(WASM_SEC_DATA), Segments(Segments) {\n raw_string_ostream OS(DataSectionHeader);\n\n writeUleb128(OS, Segments.size(), \"data segment count\");\n OS.flush();\n BodySize = DataSectionHeader.size();\n\n for (OutputSegment *Segment : Segments) {\n raw_string_ostream OS(Segment->Header);\n writeUleb128(OS, 0, \"memory index\");\n writeUleb128(OS, WASM_OPCODE_I32_CONST, \"opcode:i32const\");\n writeSleb128(OS, Segment->StartVA, \"memory offset\");\n writeUleb128(OS, WASM_OPCODE_END, \"opcode:end\");\n writeUleb128(OS, Segment->Size, \"segment size\");\n OS.flush();\n Segment->setSectionOffset(BodySize);\n BodySize += Segment->Header.size();\n log(\"Data segment: size=\" + Twine(Segment->Size));\n for (const InputSegment *InputSeg : Segment->InputSegments) {\n uint32_t InputOffset = InputSeg->getInputSectionOffset();\n uint32_t OutputOffset = Segment->getSectionOffset() +\n Segment->Header.size() +\n InputSeg->getOutputSegmentOffset();\n calcRelocations(*InputSeg->File, InputSeg->Relocations, Relocations,\n OutputOffset - InputOffset);\n }\n BodySize += Segment->Size;\n }\n\n createHeader(BodySize);\n}\n\nvoid DataSection::writeTo(uint8_t *Buf) {\n log(\"writing \" + toString(this) + \" size=\" + Twine(getSize()) +\n \" body=\" + Twine(BodySize));\n Buf += Offset;\n\n \/\/ Write section header\n memcpy(Buf, Header.data(), Header.size());\n Buf += Header.size();\n\n uint8_t *ContentsStart = Buf;\n\n \/\/ Write data section headers\n memcpy(Buf, DataSectionHeader.data(), DataSectionHeader.size());\n\n parallelForEach(Segments, [ContentsStart](const OutputSegment *Segment) {\n \/\/ Write data segment header\n uint8_t *SegStart = ContentsStart + Segment->getSectionOffset();\n memcpy(SegStart, Segment->Header.data(), Segment->Header.size());\n\n \/\/ Write segment data payload\n for (const InputSegment *Input : Segment->InputSegments) {\n ArrayRef<uint8_t> Content(Input->Segment->Data.Content);\n memcpy(SegStart + Segment->Header.size() +\n Input->getOutputSegmentOffset(),\n Content.data(), Content.size());\n }\n });\n\n applyRelocations(ContentsStart, Relocations);\n}\n\nvoid DataSection::writeRelocations(raw_ostream &OS) const {\n for (const OutputRelocation &Reloc : Relocations)\n writeReloc(OS, Reloc);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"adapter.h\"\n\nstatic VALUE cSwiftAdapter;\n\nstatic void adapter_free(dbi::Handle *handle) {\n if (handle) {\n handle->conn()->cleanup();\n delete handle;\n }\n}\n\nVALUE adapter_alloc(VALUE klass) {\n dbi::Handle *handle = 0;\n return Data_Wrap_Struct(klass, 0, adapter_free, handle);\n}\n\ndbi::Handle* adapter_handle(VALUE self) {\n dbi::Handle *handle;\n Data_Get_Struct(self, dbi::Handle, handle);\n if (!handle) rb_raise(eSwiftRuntimeError, \"Invalid object, did you forget to call #super?\");\n\n return handle;\n}\n\nstatic VALUE adapter_begin(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n rb_scan_args(argc, argv, \"01\", &save_point);\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n NIL_P(save_point) ? handle->begin() : handle->begin(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\nstatic VALUE adapter_close(VALUE self) {\n dbi::Handle *handle = adapter_handle(self);\n try { handle->close(); } CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\n\/\/ TODO:\nstatic VALUE adapter_clone(VALUE self) {\n rb_raise(eSwiftRuntimeError, \"clone is not allowed.\");\n}\n\nstatic VALUE adapter_commit(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n rb_scan_args(argc, argv, \"01\", &save_point);\n dbi::Handle *handle = adapter_handle(self);\n\n try {\n NIL_P(save_point) ? handle->commit() : handle->commit(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\n\/\/ TODO:\nstatic VALUE adapter_dup(VALUE self) {\n rb_raise(eSwiftRuntimeError, \"dup is not allowed.\");\n}\n\n\/\/ TODO: Attempt TO_S() before escaping?\nstatic VALUE adapter_escape(VALUE self, VALUE value) {\n if (TYPE(value) != T_STRING) rb_raise(eSwiftArgumentError, \"Cannot escape non-string value.\");\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n std::string safe = handle->escape(std::string(RSTRING_PTR(value), RSTRING_LEN(value)));\n return rb_str_new(safe.data(), safe.length());\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\n\/\/ TODO: Change bind_values to an array in the interface? Avoid array -> splat -> array.\nstatic VALUE adapter_execute(int argc, VALUE *argv, VALUE self) {\n VALUE statement, bind_values, block, rows;\n\n dbi::Handle *handle = adapter_handle(self);\n rb_scan_args(argc, argv, \"1*&\", &statement, &bind_values, &block);\n\n try {\n Query query;\n query.sql = CSTRING(statement);\n query.handle = handle;\n\n if (RARRAY_LEN(bind_values) > 0) query_bind_values(&query, bind_values, handle->driver());\n if (dbi::_trace) dbi::logMessage(dbi::_trace_fd, dbi::formatParams(query.sql, query.bind));\n\n if ((rows = rb_thread_blocking_region(((VALUE (*)(void*))query_execute), &query, RUBY_UBF_IO, 0)) == Qfalse)\n rb_raise(eSwiftRuntimeError, \"%s\", query.error);\n\n if (rb_block_given_p()) {\n dbi::AbstractResult *result = handle->results();\n return result_wrap_handle(cSwiftResult, self, result, false);\n }\n else\n return rows;\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nstatic VALUE adapter_initialize(VALUE self, VALUE options) {\n VALUE db = rb_hash_aref(options, ID2SYM(rb_intern(\"db\")));\n VALUE driver = rb_hash_aref(options, ID2SYM(rb_intern(\"driver\")));\n VALUE user = rb_hash_aref(options, ID2SYM(rb_intern(\"user\")));\n\n if (NIL_P(db)) rb_raise(eSwiftArgumentError, \"Adapter#new called without :db\");\n if (NIL_P(driver)) rb_raise(eSwiftArgumentError, \"Adapter#new called without :driver\");\n\n user = NIL_P(user) ? rb_str_new2(getlogin()) : user;\n\n try {\n DATA_PTR(self) = new dbi::Handle(\n CSTRING(driver),\n CSTRING(user),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"password\")))),\n CSTRING(db),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"host\")))),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"port\"))))\n );\n }\n CATCH_DBI_EXCEPTIONS();\n\n rb_iv_set(self, \"@options\", options);\n return Qnil;\n}\n\nstatic VALUE adapter_prepare(int argc, VALUE *argv, VALUE self) {\n VALUE sql, scheme, prepared;\n dbi::AbstractStatement *statement;\n\n rb_scan_args(argc, argv, \"11\", &scheme, &sql);\n if (TYPE(scheme) != T_CLASS) {\n sql = scheme;\n scheme = Qnil;\n }\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n \/\/ TODO: Move to statement_* constructor.\n statement = handle->conn()->prepare(CSTRING(sql));\n prepared = statement_wrap_handle(cSwiftStatement, self, statement);\n rb_iv_set(prepared, \"@scheme\", scheme);\n return prepared;\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nstatic VALUE adapter_rollback(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n dbi::Handle *handle = adapter_handle(self);\n rb_scan_args(argc, argv, \"01\", &save_point);\n\n try {\n NIL_P(save_point) ? handle->rollback() : handle->rollback(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\nstatic VALUE adapter_transaction(int argc, VALUE *argv, VALUE self) {\n int status;\n VALUE sp, block;\n\n dbi::Handle *handle = adapter_handle(self);\n\n rb_scan_args(argc, argv, \"01&\", &sp, &block);\n\n if (NIL_P(block)) rb_raise(eSwiftArgumentError, \"Transaction called without a block.\");\n std::string save_point = NIL_P(sp) ? \"SP\" + dbi::generateCompactUUID() : CSTRING(sp);\n\n try {\n handle->begin(save_point);\n rb_protect(rb_yield, self, &status);\n if (!status && handle->transactions().size() > 0) {\n handle->commit(save_point);\n }\n else if (status && handle->transactions().size() > 0) {\n handle->rollback(save_point);\n rb_jump_tag(status);\n }\n }\n CATCH_DBI_EXCEPTIONS();\n\n return Qtrue;\n}\n\nstatic VALUE adapter_write(int argc, VALUE *argv, VALUE self) {\n uint64_t rows = 0;\n VALUE stream, table, fields;\n dbi::Handle *handle = adapter_handle(self);\n\n rb_scan_args(argc, argv, \"30\", &table, &fields, &stream);\n if (TYPE(stream) != T_STRING && !rb_respond_to(stream, rb_intern(\"read\")))\n rb_raise(eSwiftArgumentError, \"Stream must be a String or IO object.\");\n if (TYPE(fields) != T_ARRAY)\n rb_raise(eSwiftArgumentError, \"Fields must be an Array.\");\n\n try {\n dbi::FieldSet write_fields;\n for (int i = 0; i < RARRAY_LEN(fields); i++) {\n VALUE field = TO_S(rb_ary_entry(fields, i));\n write_fields << std::string(RSTRING_PTR(field), RSTRING_LEN(field));\n }\n\n \/*\n TODO: Adapter specific code is balls.\n This is just for the friggin mysql support - mysql does not like a statement close command being send on a\n handle when the writing has started.\n *\/\n rb_gc();\n\n if (TYPE(stream) == T_STRING) {\n dbi::IOStream io(RSTRING_PTR(stream), RSTRING_LEN(stream));\n rows = handle->write(RSTRING_PTR(table), write_fields, &io);\n }\n else {\n IOStream io(stream);\n rows = handle->write(RSTRING_PTR(table), write_fields, &io);\n }\n return SIZET2NUM(rows);\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nVALUE adapter_results(VALUE self) {\n dbi::Handle *handle = adapter_handle(self);\n try {\n dbi::AbstractResult *result = handle->results();\n return result_wrap_handle(cSwiftResult, self, result, false);\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nvoid init_swift_adapter() {\n VALUE mSwift = rb_define_module(\"Swift\");\n cSwiftAdapter = rb_define_class_under(mSwift, \"Adapter\", rb_cObject);\n\n rb_define_method(cSwiftAdapter, \"begin\", RUBY_METHOD_FUNC(adapter_begin), -1);\n rb_define_method(cSwiftAdapter, \"clone\", RUBY_METHOD_FUNC(adapter_clone), 0);\n rb_define_method(cSwiftAdapter, \"close\", RUBY_METHOD_FUNC(adapter_close), 0);\n rb_define_method(cSwiftAdapter, \"commit\", RUBY_METHOD_FUNC(adapter_commit), -1);\n rb_define_method(cSwiftAdapter, \"dup\", RUBY_METHOD_FUNC(adapter_dup), 0);\n rb_define_method(cSwiftAdapter, \"escape\", RUBY_METHOD_FUNC(adapter_escape), 1);\n rb_define_method(cSwiftAdapter, \"execute\", RUBY_METHOD_FUNC(adapter_execute), -1);\n rb_define_method(cSwiftAdapter, \"initialize\", RUBY_METHOD_FUNC(adapter_initialize), 1);\n rb_define_method(cSwiftAdapter, \"prepare\", RUBY_METHOD_FUNC(adapter_prepare), -1);\n rb_define_method(cSwiftAdapter, \"rollback\", RUBY_METHOD_FUNC(adapter_rollback), -1);\n rb_define_method(cSwiftAdapter, \"transaction\", RUBY_METHOD_FUNC(adapter_transaction), -1);\n rb_define_method(cSwiftAdapter, \"write\", RUBY_METHOD_FUNC(adapter_write), -1);\n\n rb_define_alloc_func(cSwiftAdapter, adapter_alloc);\n\n \/\/ TODO Figure out how to avoid race conditions.\n rb_define_method(cSwiftAdapter, \"results\", RUBY_METHOD_FUNC(adapter_results), 0);\n}\n\n\n<commit_msg>fix: return result_each from adapter#execute<commit_after>#include \"adapter.h\"\n\nstatic VALUE cSwiftAdapter;\n\nstatic void adapter_free(dbi::Handle *handle) {\n if (handle) {\n handle->conn()->cleanup();\n delete handle;\n }\n}\n\nVALUE adapter_alloc(VALUE klass) {\n dbi::Handle *handle = 0;\n return Data_Wrap_Struct(klass, 0, adapter_free, handle);\n}\n\ndbi::Handle* adapter_handle(VALUE self) {\n dbi::Handle *handle;\n Data_Get_Struct(self, dbi::Handle, handle);\n if (!handle) rb_raise(eSwiftRuntimeError, \"Invalid object, did you forget to call #super?\");\n\n return handle;\n}\n\nstatic VALUE adapter_begin(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n rb_scan_args(argc, argv, \"01\", &save_point);\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n NIL_P(save_point) ? handle->begin() : handle->begin(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\nstatic VALUE adapter_close(VALUE self) {\n dbi::Handle *handle = adapter_handle(self);\n try { handle->close(); } CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\n\/\/ TODO:\nstatic VALUE adapter_clone(VALUE self) {\n rb_raise(eSwiftRuntimeError, \"clone is not allowed.\");\n}\n\nstatic VALUE adapter_commit(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n rb_scan_args(argc, argv, \"01\", &save_point);\n dbi::Handle *handle = adapter_handle(self);\n\n try {\n NIL_P(save_point) ? handle->commit() : handle->commit(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\n\/\/ TODO:\nstatic VALUE adapter_dup(VALUE self) {\n rb_raise(eSwiftRuntimeError, \"dup is not allowed.\");\n}\n\n\/\/ TODO: Attempt TO_S() before escaping?\nstatic VALUE adapter_escape(VALUE self, VALUE value) {\n if (TYPE(value) != T_STRING) rb_raise(eSwiftArgumentError, \"Cannot escape non-string value.\");\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n std::string safe = handle->escape(std::string(RSTRING_PTR(value), RSTRING_LEN(value)));\n return rb_str_new(safe.data(), safe.length());\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\n\/\/ TODO: Change bind_values to an array in the interface? Avoid array -> splat -> array.\nstatic VALUE adapter_execute(int argc, VALUE *argv, VALUE self) {\n VALUE statement, bind_values, block, rows;\n\n dbi::Handle *handle = adapter_handle(self);\n rb_scan_args(argc, argv, \"1*&\", &statement, &bind_values, &block);\n\n try {\n Query query;\n query.sql = CSTRING(statement);\n query.handle = handle;\n\n if (RARRAY_LEN(bind_values) > 0) query_bind_values(&query, bind_values, handle->driver());\n if (dbi::_trace) dbi::logMessage(dbi::_trace_fd, dbi::formatParams(query.sql, query.bind));\n\n if ((rows = rb_thread_blocking_region(((VALUE (*)(void*))query_execute), &query, RUBY_UBF_IO, 0)) == Qfalse)\n rb_raise(eSwiftRuntimeError, \"%s\", query.error);\n\n if (rb_block_given_p()) {\n dbi::AbstractResult *result = handle->results();\n return result_each(result_wrap_handle(cSwiftResult, self, result, false));\n }\n else\n return rows;\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nstatic VALUE adapter_initialize(VALUE self, VALUE options) {\n VALUE db = rb_hash_aref(options, ID2SYM(rb_intern(\"db\")));\n VALUE driver = rb_hash_aref(options, ID2SYM(rb_intern(\"driver\")));\n VALUE user = rb_hash_aref(options, ID2SYM(rb_intern(\"user\")));\n\n if (NIL_P(db)) rb_raise(eSwiftArgumentError, \"Adapter#new called without :db\");\n if (NIL_P(driver)) rb_raise(eSwiftArgumentError, \"Adapter#new called without :driver\");\n\n user = NIL_P(user) ? rb_str_new2(getlogin()) : user;\n\n try {\n DATA_PTR(self) = new dbi::Handle(\n CSTRING(driver),\n CSTRING(user),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"password\")))),\n CSTRING(db),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"host\")))),\n CSTRING(rb_hash_aref(options, ID2SYM(rb_intern(\"port\"))))\n );\n }\n CATCH_DBI_EXCEPTIONS();\n\n rb_iv_set(self, \"@options\", options);\n return Qnil;\n}\n\nstatic VALUE adapter_prepare(int argc, VALUE *argv, VALUE self) {\n VALUE sql, scheme, prepared;\n dbi::AbstractStatement *statement;\n\n rb_scan_args(argc, argv, \"11\", &scheme, &sql);\n if (TYPE(scheme) != T_CLASS) {\n sql = scheme;\n scheme = Qnil;\n }\n\n dbi::Handle *handle = adapter_handle(self);\n try {\n \/\/ TODO: Move to statement_* constructor.\n statement = handle->conn()->prepare(CSTRING(sql));\n prepared = statement_wrap_handle(cSwiftStatement, self, statement);\n rb_iv_set(prepared, \"@scheme\", scheme);\n return prepared;\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nstatic VALUE adapter_rollback(int argc, VALUE *argv, VALUE self) {\n VALUE save_point;\n dbi::Handle *handle = adapter_handle(self);\n rb_scan_args(argc, argv, \"01\", &save_point);\n\n try {\n NIL_P(save_point) ? handle->rollback() : handle->rollback(CSTRING(save_point));\n }\n CATCH_DBI_EXCEPTIONS();\n return Qtrue;\n}\n\nstatic VALUE adapter_transaction(int argc, VALUE *argv, VALUE self) {\n int status;\n VALUE sp, block;\n\n dbi::Handle *handle = adapter_handle(self);\n\n rb_scan_args(argc, argv, \"01&\", &sp, &block);\n\n if (NIL_P(block)) rb_raise(eSwiftArgumentError, \"Transaction called without a block.\");\n std::string save_point = NIL_P(sp) ? \"SP\" + dbi::generateCompactUUID() : CSTRING(sp);\n\n try {\n handle->begin(save_point);\n rb_protect(rb_yield, self, &status);\n if (!status && handle->transactions().size() > 0) {\n handle->commit(save_point);\n }\n else if (status && handle->transactions().size() > 0) {\n handle->rollback(save_point);\n rb_jump_tag(status);\n }\n }\n CATCH_DBI_EXCEPTIONS();\n\n return Qtrue;\n}\n\nstatic VALUE adapter_write(int argc, VALUE *argv, VALUE self) {\n uint64_t rows = 0;\n VALUE stream, table, fields;\n dbi::Handle *handle = adapter_handle(self);\n\n rb_scan_args(argc, argv, \"30\", &table, &fields, &stream);\n if (TYPE(stream) != T_STRING && !rb_respond_to(stream, rb_intern(\"read\")))\n rb_raise(eSwiftArgumentError, \"Stream must be a String or IO object.\");\n if (TYPE(fields) != T_ARRAY)\n rb_raise(eSwiftArgumentError, \"Fields must be an Array.\");\n\n try {\n dbi::FieldSet write_fields;\n for (int i = 0; i < RARRAY_LEN(fields); i++) {\n VALUE field = TO_S(rb_ary_entry(fields, i));\n write_fields << std::string(RSTRING_PTR(field), RSTRING_LEN(field));\n }\n\n \/*\n TODO: Adapter specific code is balls.\n This is just for the friggin mysql support - mysql does not like a statement close command being send on a\n handle when the writing has started.\n *\/\n rb_gc();\n\n if (TYPE(stream) == T_STRING) {\n dbi::IOStream io(RSTRING_PTR(stream), RSTRING_LEN(stream));\n rows = handle->write(RSTRING_PTR(table), write_fields, &io);\n }\n else {\n IOStream io(stream);\n rows = handle->write(RSTRING_PTR(table), write_fields, &io);\n }\n return SIZET2NUM(rows);\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nVALUE adapter_results(VALUE self) {\n dbi::Handle *handle = adapter_handle(self);\n try {\n dbi::AbstractResult *result = handle->results();\n return result_wrap_handle(cSwiftResult, self, result, false);\n }\n CATCH_DBI_EXCEPTIONS();\n}\n\nvoid init_swift_adapter() {\n VALUE mSwift = rb_define_module(\"Swift\");\n cSwiftAdapter = rb_define_class_under(mSwift, \"Adapter\", rb_cObject);\n\n rb_define_method(cSwiftAdapter, \"begin\", RUBY_METHOD_FUNC(adapter_begin), -1);\n rb_define_method(cSwiftAdapter, \"clone\", RUBY_METHOD_FUNC(adapter_clone), 0);\n rb_define_method(cSwiftAdapter, \"close\", RUBY_METHOD_FUNC(adapter_close), 0);\n rb_define_method(cSwiftAdapter, \"commit\", RUBY_METHOD_FUNC(adapter_commit), -1);\n rb_define_method(cSwiftAdapter, \"dup\", RUBY_METHOD_FUNC(adapter_dup), 0);\n rb_define_method(cSwiftAdapter, \"escape\", RUBY_METHOD_FUNC(adapter_escape), 1);\n rb_define_method(cSwiftAdapter, \"execute\", RUBY_METHOD_FUNC(adapter_execute), -1);\n rb_define_method(cSwiftAdapter, \"initialize\", RUBY_METHOD_FUNC(adapter_initialize), 1);\n rb_define_method(cSwiftAdapter, \"prepare\", RUBY_METHOD_FUNC(adapter_prepare), -1);\n rb_define_method(cSwiftAdapter, \"rollback\", RUBY_METHOD_FUNC(adapter_rollback), -1);\n rb_define_method(cSwiftAdapter, \"transaction\", RUBY_METHOD_FUNC(adapter_transaction), -1);\n rb_define_method(cSwiftAdapter, \"write\", RUBY_METHOD_FUNC(adapter_write), -1);\n\n rb_define_alloc_func(cSwiftAdapter, adapter_alloc);\n\n \/\/ TODO Figure out how to avoid race conditions.\n rb_define_method(cSwiftAdapter, \"results\", RUBY_METHOD_FUNC(adapter_results), 0);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <gmock\/gmock.h>\n\n\n#include <globjects\/base\/ref_ptr.h>\n\nclass ref_ptr_test : public testing::Test\n{\npublic:\n};\n\nclass ReferencedMock : public globjects::Referenced\n{\npublic:\n MOCK_METHOD0(Die, void());\n virtual ~ReferencedMock() { Die(); }\n};\n\nTEST_F(ref_ptr_test, DeletesItsReferenced)\n{\n \/\/ the ReferencedMock instance should be deleted on function exit\n\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n}\n\nTEST_F(ref_ptr_test, SurvivesWhenReferenced)\n{\n globjects::ref_ptr<ReferencedMock> owned;\n {\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n owned = ref;\n EXPECT_EQ(owned->refCounter(), 2);\n }\n EXPECT_EQ(owned->refCounter(), 1);\n}\n\nTEST_F(ref_ptr_test, ReferencesSameInstanceWhenPassedOn)\n{\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n\n globjects::ref_ptr<ReferencedMock> a = ref;\n globjects::ref_ptr<ReferencedMock> b = ref;\n\n EXPECT_EQ(ref->refCounter(), 3);\n EXPECT_TRUE(a == b);\n}\n\nTEST_F(ref_ptr_test, ReferenceComparisonConstComparisonsCompile)\n{\n return; \/\/ Just test compilation, not actual behavior\n\n ReferencedMock * t = new ReferencedMock;\n const ReferencedMock * const_t = new ReferencedMock;\n\n globjects::ref_ptr<ReferencedMock> ref_t = new ReferencedMock;\n const globjects::ref_ptr<ReferencedMock> const_ref_t = new ReferencedMock;\n globjects::ref_ptr<const ReferencedMock> ref_const_t = new ReferencedMock;\n const globjects::ref_ptr<const ReferencedMock> const_ref_const_t = new ReferencedMock;\n\n bool success1 = true;\n bool success2 = true;\n\n if (t == ref_t || t == const_ref_t || t == ref_const_t || t == const_ref_const_t)\n if (const_t == ref_t || const_t == const_ref_t || const_t == ref_const_t || const_t == const_ref_const_t)\n if (ref_t == const_ref_t || ref_t == ref_const_t || ref_t == const_ref_const_t)\n if (const_ref_t == ref_const_t || const_ref_t == const_ref_const_t)\n if (ref_const_t == const_ref_const_t)\n {\n success1 = false;\n }\n\n if (ref_t == t || const_ref_t == t || ref_const_t == t || const_ref_const_t == t)\n if (ref_t == const_t || const_ref_t == const_t || ref_const_t == const_t || const_ref_const_t == const_t)\n if (const_ref_t == ref_t || ref_const_t == ref_t || const_ref_const_t == ref_t)\n if (ref_const_t == const_ref_t || const_ref_const_t == const_ref_t)\n if (const_ref_const_t == ref_const_t)\n {\n success2 = false;\n }\n\n EXPECT_TRUE(success1 && success2);\n\n delete t;\n delete const_t;\n}\n<commit_msg>Fix CID #89085<commit_after>\n#include <gmock\/gmock.h>\n\n\n#include <globjects\/base\/ref_ptr.h>\n\nclass ref_ptr_test : public testing::Test\n{\npublic:\n};\n\nclass ReferencedMock : public globjects::Referenced\n{\npublic:\n MOCK_METHOD0(Die, void());\n virtual ~ReferencedMock() { Die(); }\n};\n\nTEST_F(ref_ptr_test, DeletesItsReferenced)\n{\n \/\/ the ReferencedMock instance should be deleted on function exit\n\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n}\n\nTEST_F(ref_ptr_test, SurvivesWhenReferenced)\n{\n globjects::ref_ptr<ReferencedMock> owned;\n {\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n owned = ref;\n EXPECT_EQ(owned->refCounter(), 2);\n }\n EXPECT_EQ(owned->refCounter(), 1);\n}\n\nTEST_F(ref_ptr_test, ReferencesSameInstanceWhenPassedOn)\n{\n globjects::ref_ptr<ReferencedMock> ref = new ReferencedMock;\n EXPECT_CALL(*ref, Die()).Times(1);\n\n globjects::ref_ptr<ReferencedMock> a = ref;\n globjects::ref_ptr<ReferencedMock> b = ref;\n\n EXPECT_EQ(ref->refCounter(), 3);\n EXPECT_TRUE(a == b);\n}\n\nTEST_F(ref_ptr_test, ReferenceComparisonConstComparisonsCompile)\n{\n SUCCEED(); \/\/ Just test compilation, not actual behavior\n\n ReferencedMock * t = new ReferencedMock;\n const ReferencedMock * const_t = new ReferencedMock;\n\n globjects::ref_ptr<ReferencedMock> ref_t = new ReferencedMock;\n const globjects::ref_ptr<ReferencedMock> const_ref_t = new ReferencedMock;\n globjects::ref_ptr<const ReferencedMock> ref_const_t = new ReferencedMock;\n const globjects::ref_ptr<const ReferencedMock> const_ref_const_t = new ReferencedMock;\n\n bool success1 = true;\n bool success2 = true;\n\n if (t == ref_t || t == const_ref_t || t == ref_const_t || t == const_ref_const_t)\n if (const_t == ref_t || const_t == const_ref_t || const_t == ref_const_t || const_t == const_ref_const_t)\n if (ref_t == const_ref_t || ref_t == ref_const_t || ref_t == const_ref_const_t)\n if (const_ref_t == ref_const_t || const_ref_t == const_ref_const_t)\n if (ref_const_t == const_ref_const_t)\n {\n success1 = false;\n }\n\n if (ref_t == t || const_ref_t == t || ref_const_t == t || const_ref_const_t == t)\n if (ref_t == const_t || const_ref_t == const_t || ref_const_t == const_t || const_ref_const_t == const_t)\n if (const_ref_t == ref_t || ref_const_t == ref_t || const_ref_const_t == ref_t)\n if (ref_const_t == const_ref_t || const_ref_const_t == const_ref_t)\n if (const_ref_const_t == ref_const_t)\n {\n success2 = false;\n }\n\n EXPECT_TRUE(success1 && success2);\n\n delete t;\n delete const_t;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FTGL - OpenGL font library\n *\n * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * Alternatively, you can redistribute and\/or modify this software under\n * the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License,\n * or (at your option) any later version.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"config.h\"\n\n#include <cassert>\n#include <string> \/\/ For memset\n\n#include \"FTInternals.h\"\n\n#include \"FTGLTextureFont.h\"\n#include \"FTTextureGlyph.h\"\n\n\ninline GLuint NextPowerOf2( GLuint in)\n{\n in -= 1;\n\n in |= in >> 16;\n in |= in >> 8;\n in |= in >> 4;\n in |= in >> 2;\n in |= in >> 1;\n\n return in + 1;\n}\n\n\nFTGLTextureFont::FTGLTextureFont( const char* fontFilePath)\n: FTFont( fontFilePath),\n maximumGLTextureSize(0),\n textureWidth(0),\n textureHeight(0),\n glyphHeight(0),\n glyphWidth(0),\n padding(3),\n xOffset(0),\n yOffset(0)\n{\n remGlyphs = numGlyphs = face.GlyphCount();\n}\n\n\nFTGLTextureFont::FTGLTextureFont( const unsigned char *pBufferBytes, size_t bufferSizeInBytes)\n: FTFont( pBufferBytes, bufferSizeInBytes),\n maximumGLTextureSize(0),\n textureWidth(0),\n textureHeight(0),\n glyphHeight(0),\n glyphWidth(0),\n padding(3),\n xOffset(0),\n yOffset(0)\n{\n remGlyphs = numGlyphs = face.GlyphCount();\n}\n\n\nFTGLTextureFont::~FTGLTextureFont()\n{\n glDeleteTextures( textureIDList.size(), (const GLuint*)&textureIDList[0]);\n}\n\n\nFTGlyph* FTGLTextureFont::MakeGlyph( unsigned int glyphIndex)\n{\n FT_GlyphSlot ftGlyph = face.Glyph( glyphIndex, FT_LOAD_NO_HINTING);\n \n if( ftGlyph)\n {\n glyphHeight = static_cast<int>( charSize.Height());\n glyphWidth = static_cast<int>( charSize.Width());\n \n if( textureIDList.empty())\n {\n textureIDList.push_back( CreateTexture());\n xOffset = yOffset = padding;\n }\n \n if( xOffset > ( textureWidth - glyphWidth))\n {\n xOffset = padding;\n yOffset += glyphHeight;\n \n if( yOffset > ( textureHeight - glyphHeight))\n {\n textureIDList.push_back( CreateTexture());\n yOffset = padding;\n }\n }\n \n FTTextureGlyph* tempGlyph = new FTTextureGlyph( ftGlyph, textureIDList[textureIDList.size() - 1],\n xOffset, yOffset, textureWidth, textureHeight);\n xOffset += static_cast<int>( tempGlyph->BBox().upperX - tempGlyph->BBox().lowerX + padding);\n \n --remGlyphs;\n return tempGlyph;\n }\n \n err = face.Error();\n return NULL;\n}\n\n\nvoid FTGLTextureFont::CalculateTextureSize()\n{\n if( !maximumGLTextureSize)\n {\n glGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maximumGLTextureSize);\n assert(maximumGLTextureSize); \/\/ If you hit this then you have an invalid OpenGL context.\n }\n \n textureWidth = NextPowerOf2( (remGlyphs * glyphWidth) + ( padding * 2));\n textureWidth = textureWidth > maximumGLTextureSize ? maximumGLTextureSize : textureWidth;\n \n int h = static_cast<int>( (textureWidth - ( padding * 2)) \/ glyphWidth);\n \n textureHeight = NextPowerOf2( (( numGlyphs \/ h) + 1) * glyphHeight);\n textureHeight = textureHeight > maximumGLTextureSize ? maximumGLTextureSize : textureHeight;\n}\n\n\nGLuint FTGLTextureFont::CreateTexture()\n{ \n CalculateTextureSize();\n \n int totalMemory = textureWidth * textureHeight;\n unsigned char* textureMemory = new unsigned char[totalMemory];\n memset( textureMemory, 0, totalMemory);\n\n GLuint textID;\n glGenTextures( 1, (GLuint*)&textID);\n\n glBindTexture( GL_TEXTURE_2D, textID);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureMemory);\n\n delete [] textureMemory;\n\n return textID;\n}\n\n\nbool FTGLTextureFont::FaceSize( const unsigned int size, const unsigned int res)\n{\n if( !textureIDList.empty())\n {\n glDeleteTextures( textureIDList.size(), (const GLuint*)&textureIDList[0]);\n textureIDList.clear();\n remGlyphs = numGlyphs = face.GlyphCount();\n }\n\n return FTFont::FaceSize( size, res);\n}\n\n\ntemplate <typename T>\ninline void FTGLTextureFont::RenderI(const T* string)\n{ \n glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);\n \n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n\n FTTextureGlyph::ResetActiveTexture();\n \n FTFont::Render(string);\n\n glPopAttrib();\n}\n\n\nvoid FTGLTextureFont::Render(const char* string)\n{\n RenderI(string);\n}\n\n\nvoid FTGLTextureFont::Render(const wchar_t* string)\n{\n RenderI(string);\n}\n\n\nnamespace C\n{\n extern \"C\" FTGLfont* ftglCreateTextureFont(const char *fontname)\n {\n FTGLfont *ftgl = createFTFont(Texture, fontname);\n return ftgl;\n }\n}\n\n<commit_msg> * Turn off the color buffer bit in the TextureFont renderer to increase performance. Patch by Ton Roosendaal, from Blender commit r5362.<commit_after>\/*\n * FTGL - OpenGL font library\n *\n * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * Alternatively, you can redistribute and\/or modify this software under\n * the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License,\n * or (at your option) any later version.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"config.h\"\n\n#include <cassert>\n#include <string> \/\/ For memset\n\n#include \"FTInternals.h\"\n\n#include \"FTGLTextureFont.h\"\n#include \"FTTextureGlyph.h\"\n\n\ninline GLuint NextPowerOf2( GLuint in)\n{\n in -= 1;\n\n in |= in >> 16;\n in |= in >> 8;\n in |= in >> 4;\n in |= in >> 2;\n in |= in >> 1;\n\n return in + 1;\n}\n\n\nFTGLTextureFont::FTGLTextureFont( const char* fontFilePath)\n: FTFont( fontFilePath),\n maximumGLTextureSize(0),\n textureWidth(0),\n textureHeight(0),\n glyphHeight(0),\n glyphWidth(0),\n padding(3),\n xOffset(0),\n yOffset(0)\n{\n remGlyphs = numGlyphs = face.GlyphCount();\n}\n\n\nFTGLTextureFont::FTGLTextureFont( const unsigned char *pBufferBytes, size_t bufferSizeInBytes)\n: FTFont( pBufferBytes, bufferSizeInBytes),\n maximumGLTextureSize(0),\n textureWidth(0),\n textureHeight(0),\n glyphHeight(0),\n glyphWidth(0),\n padding(3),\n xOffset(0),\n yOffset(0)\n{\n remGlyphs = numGlyphs = face.GlyphCount();\n}\n\n\nFTGLTextureFont::~FTGLTextureFont()\n{\n glDeleteTextures( textureIDList.size(), (const GLuint*)&textureIDList[0]);\n}\n\n\nFTGlyph* FTGLTextureFont::MakeGlyph( unsigned int glyphIndex)\n{\n FT_GlyphSlot ftGlyph = face.Glyph( glyphIndex, FT_LOAD_NO_HINTING);\n \n if( ftGlyph)\n {\n glyphHeight = static_cast<int>( charSize.Height());\n glyphWidth = static_cast<int>( charSize.Width());\n \n if( textureIDList.empty())\n {\n textureIDList.push_back( CreateTexture());\n xOffset = yOffset = padding;\n }\n \n if( xOffset > ( textureWidth - glyphWidth))\n {\n xOffset = padding;\n yOffset += glyphHeight;\n \n if( yOffset > ( textureHeight - glyphHeight))\n {\n textureIDList.push_back( CreateTexture());\n yOffset = padding;\n }\n }\n \n FTTextureGlyph* tempGlyph = new FTTextureGlyph( ftGlyph, textureIDList[textureIDList.size() - 1],\n xOffset, yOffset, textureWidth, textureHeight);\n xOffset += static_cast<int>( tempGlyph->BBox().upperX - tempGlyph->BBox().lowerX + padding);\n \n --remGlyphs;\n return tempGlyph;\n }\n \n err = face.Error();\n return NULL;\n}\n\n\nvoid FTGLTextureFont::CalculateTextureSize()\n{\n if( !maximumGLTextureSize)\n {\n glGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maximumGLTextureSize);\n assert(maximumGLTextureSize); \/\/ If you hit this then you have an invalid OpenGL context.\n }\n \n textureWidth = NextPowerOf2( (remGlyphs * glyphWidth) + ( padding * 2));\n textureWidth = textureWidth > maximumGLTextureSize ? maximumGLTextureSize : textureWidth;\n \n int h = static_cast<int>( (textureWidth - ( padding * 2)) \/ glyphWidth);\n \n textureHeight = NextPowerOf2( (( numGlyphs \/ h) + 1) * glyphHeight);\n textureHeight = textureHeight > maximumGLTextureSize ? maximumGLTextureSize : textureHeight;\n}\n\n\nGLuint FTGLTextureFont::CreateTexture()\n{ \n CalculateTextureSize();\n \n int totalMemory = textureWidth * textureHeight;\n unsigned char* textureMemory = new unsigned char[totalMemory];\n memset( textureMemory, 0, totalMemory);\n\n GLuint textID;\n glGenTextures( 1, (GLuint*)&textID);\n\n glBindTexture( GL_TEXTURE_2D, textID);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureMemory);\n\n delete [] textureMemory;\n\n return textID;\n}\n\n\nbool FTGLTextureFont::FaceSize( const unsigned int size, const unsigned int res)\n{\n if( !textureIDList.empty())\n {\n glDeleteTextures( textureIDList.size(), (const GLuint*)&textureIDList[0]);\n textureIDList.clear();\n remGlyphs = numGlyphs = face.GlyphCount();\n }\n\n return FTFont::FaceSize( size, res);\n}\n\n\ntemplate <typename T>\ninline void FTGLTextureFont::RenderI(const T* string)\n{\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n\n FTTextureGlyph::ResetActiveTexture();\n\n FTFont::Render(string);\n}\n\n\nvoid FTGLTextureFont::Render(const char* string)\n{\n RenderI(string);\n}\n\n\nvoid FTGLTextureFont::Render(const wchar_t* string)\n{\n RenderI(string);\n}\n\n\nnamespace C\n{\n extern \"C\" FTGLfont* ftglCreateTextureFont(const char *fontname)\n {\n FTGLfont *ftgl = createFTFont(Texture, fontname);\n return ftgl;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include\t\"FTGLTextureFont.h\"\n#include\t\"FTGlyphContainer.h\"\n#include\t\"FTTextureGlyph.h\"\n\nusing namespace std;\n\ntypedef unsigned long\tUInt32; \/\/ a mac thing?\n\ninline UInt32 NextPowerOf2( UInt32 in)\n{\n in -= 1;\n\n in |= in >> 16;\n in |= in >> 8;\n in |= in >> 4;\n in |= in >> 2;\n in |= in >> 1;\n\n return in + 1;\n}\n\n\nFTGLTextureFont::FTGLTextureFont()\n:\tnumTextures(1),\n\ttextMem(0),\n\tpadding(1),\n\ttempGlyph(0),\n\tmaxTextSize(0),\n\ttextureWidth(0),\n\ttextureHeight(0),\n\tglyphHeight(0),\n\tglyphWidth(0)\n{}\n\n\nFTGLTextureFont::~FTGLTextureFont()\n{\n\tglDeleteTextures( numTextures, (const GLuint*)glTextureID);\n}\n\n\nbool FTGLTextureFont::MakeGlyphList()\n{\n\tif( !maxTextSize)\n\t\tglGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maxTextSize);\n\t\n\tglyphHeight = ( charSize.Height()) + padding;\n\tglyphWidth = ( charSize.Width()) + padding;\n\t\n\tGetSize();\n\tint totalMem;\n\t\n\tif( textureHeight > maxTextSize)\n\t{\n\t\tnumTextures = static_cast<int>( textureHeight \/ maxTextSize) + 1;\n\t\tif( numTextures > 15) \/\/ FIXME\n\t\t\tnumTextures = 15;\n\t\t\n\t\tint heightRemain = NextPowerOf2( textureHeight % maxTextSize);\n\t\ttotalMem = ((maxTextSize * ( numTextures - 1)) + heightRemain) * textureWidth;\n\n\t\tglGenTextures( numTextures, (GLuint*)&glTextureID[0]);\n\n\t\ttextMem = new unsigned char[totalMem]; \/\/ GL_ALPHA texture;\n\t\tmemset( textMem, 0, totalMem);\n\t\t\t\n\t\tunsigned int glyphNum = 0;\n\t\tunsigned char* currTextPtr = textMem;\n\t\t\n\t\tfor( int x = 0; x < numTextures - 1; ++x)\n\t\t{\n\t\t\tglyphNum = FillGlyphs( glyphNum, glTextureID[x], textureWidth, maxTextSize, currTextPtr);\n\t\t\t\n\t\t\tCreateTexture( x, textureWidth, maxTextSize, currTextPtr);\n\t\t\t\n\t\t\tcurrTextPtr += ( textureWidth * maxTextSize);\n\t\t\t++glyphNum;\n\t\t}\n\t\t\n\t\tglyphNum = FillGlyphs( glyphNum, glTextureID[numTextures - 1], textureWidth, heightRemain, currTextPtr);\n\t\tCreateTexture( numTextures - 1, textureWidth, heightRemain, currTextPtr);\n\t}\n\telse\n\t{\n\t\ttextureHeight = NextPowerOf2( textureHeight);\n\t\ttotalMem = textureWidth * textureHeight;\n\t\t\n\t\tglGenTextures( numTextures, (GLuint*)&glTextureID[0]);\n\n\t\ttextMem = new unsigned char[totalMem]; \/\/ GL_ALPHA texture;\n\t\tmemset( textMem, 0, totalMem);\n\n\t\tFillGlyphs( 0, glTextureID[0], textureWidth, textureHeight, textMem);\n\t\tCreateTexture( 0, textureWidth, textureHeight, textMem);\n\t}\n\n\tdelete [] textMem;\n\treturn !err;\n}\n\n\nunsigned int FTGLTextureFont::FillGlyphs( unsigned int glyphStart, int id, int width, int height, unsigned char* textdata)\n{\n\tint currentTextX = padding;\n\tint currentTextY = padding;\/\/ + padding;\n\t\n\tfloat currTextU = (float)padding \/ (float)width;\n\tfloat currTextV = (float)padding \/ (float)height;\n\t\n\/\/\tnumGlyphs = 256; \/\/ FIXME hack\n\tunsigned int n;\n\t\n\tfor( n = glyphStart; n <= numGlyphs; ++n)\n\t{\n\t\tFT_Glyph* ftGlyph = face.Glyph( n, FT_LOAD_NO_HINTING);\n\t\t\n\t\tif( ftGlyph)\n\t\t{\n\t\t\tunsigned char* data = textdata + (( currentTextY * width) + currentTextX);\n\t\t\t\n\t\t\tcurrTextU = (float)currentTextX \/ (float)width;\n\t\t\t\n\t\t\ttempGlyph = new FTTextureGlyph( *ftGlyph, id, data, width, height, currTextU, currTextV);\n\t\t\tglyphList->Add( tempGlyph);\n\n\t\t\tcurrentTextX += glyphWidth;\n\t\t\tif( currentTextX > ( width - glyphWidth))\n\t\t\t{\n\t\t\t\tcurrentTextY += glyphHeight;\n\t\t\t\tif( currentTextY > ( height - glyphHeight))\n\t\t\t\t\treturn n;\n\t\t\t\t\t\n\t\t\t\tcurrentTextX = padding;\n\t\t\t\tcurrTextV = (float)currentTextY \/ (float)height;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terr = face.Error();\n\t\t}\n\t}\n\n\treturn n;\n}\n\n\nvoid FTGLTextureFont::GetSize()\n{\n\t\/\/work out the max width. Most likely maxTextSize\n\ttextureWidth = NextPowerOf2( numGlyphs * glyphWidth);\n\tif( textureWidth > maxTextSize)\n\t{\n\t\ttextureWidth = maxTextSize;\n\t}\n\t\n\tint h = static_cast<int>( textureWidth \/ glyphWidth);\n\ttextureHeight = (( numGlyphs \/ h) + 1) * glyphHeight;\n}\n\n\nvoid FTGLTextureFont::CreateTexture( int id, int width, int height, unsigned char* data)\n{\n\tglPixelStorei( GL_UNPACK_ALIGNMENT, 1); \/\/What does this do exactly?\n\tglBindTexture( GL_TEXTURE_2D, glTextureID[id]);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tglTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);\n}\n\n\nvoid FTGLTextureFont::render( const char* string)\n{\t\n\tglPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);\n\t\n\tglEnable(GL_BLEND);\n \tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n \t\n\tglBindTexture( GL_TEXTURE_2D, (GLuint)FTTextureGlyph::activeTextureID);\n\n \t\/\/ QUADS are faster!? Less function call overhead?\n \tglBegin( GL_QUADS);\n \t\tFTFont::render( string);\n \tglEnd();\n\t\n\tglPopAttrib();\n}\n\n\nvoid FTGLTextureFont::render( const wchar_t* string)\n{\t\n\tglPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);\n\t\n\tglEnable(GL_BLEND);\n \tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n \t\n\tglBindTexture( GL_TEXTURE_2D, (GLuint)FTTextureGlyph::activeTextureID);\n\n \t\/\/ QUADS are faster!? Less function call overhead?\n \tglBegin( GL_QUADS);\n \t\tFTFont::render( string);\n \tglEnd();\n\t\n\tglPopAttrib();\n}\n\n<commit_msg>Enable texturing<commit_after>#include\t\"FTGLTextureFont.h\"\n#include\t\"FTGlyphContainer.h\"\n#include\t\"FTTextureGlyph.h\"\n\nusing namespace std;\n\ntypedef unsigned long\tUInt32; \/\/ a mac thing?\n\ninline UInt32 NextPowerOf2( UInt32 in)\n{\n in -= 1;\n\n in |= in >> 16;\n in |= in >> 8;\n in |= in >> 4;\n in |= in >> 2;\n in |= in >> 1;\n\n return in + 1;\n}\n\n\nFTGLTextureFont::FTGLTextureFont()\n:\tnumTextures(1),\n\ttextMem(0),\n\tpadding(1),\n\ttempGlyph(0),\n\tmaxTextSize(0),\n\ttextureWidth(0),\n\ttextureHeight(0),\n\tglyphHeight(0),\n\tglyphWidth(0)\n{}\n\n\nFTGLTextureFont::~FTGLTextureFont()\n{\n\tglDeleteTextures( numTextures, (const GLuint*)glTextureID);\n}\n\n\nbool FTGLTextureFont::MakeGlyphList()\n{\n\tglEnable( GL_TEXTURE_2D);\n\t\n\tif( !maxTextSize)\n\t\tglGetIntegerv( GL_MAX_TEXTURE_SIZE, (GLint*)&maxTextSize);\n\t\t\n\tglyphHeight = ( charSize.Height()) + padding;\n\tglyphWidth = ( charSize.Width()) + padding;\n\t\n\tGetSize();\n\tint totalMem;\n\t\n\tif( textureHeight > maxTextSize)\n\t{\n\t\tnumTextures = static_cast<int>( textureHeight \/ maxTextSize) + 1;\n\t\tif( numTextures > 15) \/\/ FIXME\n\t\t\tnumTextures = 15;\n\t\t\n\t\tint heightRemain = NextPowerOf2( textureHeight % maxTextSize);\n\t\ttotalMem = ((maxTextSize * ( numTextures - 1)) + heightRemain) * textureWidth;\n\n\t\tglGenTextures( numTextures, (GLuint*)&glTextureID[0]);\n\n\t\ttextMem = new unsigned char[totalMem]; \/\/ GL_ALPHA texture;\n\t\tmemset( textMem, 0, totalMem);\n\t\t\t\n\t\tunsigned int glyphNum = 0;\n\t\tunsigned char* currTextPtr = textMem;\n\t\t\n\t\tfor( int x = 0; x < numTextures - 1; ++x)\n\t\t{\n\t\t\tglyphNum = FillGlyphs( glyphNum, glTextureID[x], textureWidth, maxTextSize, currTextPtr);\n\t\t\t\n\t\t\tCreateTexture( x, textureWidth, maxTextSize, currTextPtr);\n\t\t\t\n\t\t\tcurrTextPtr += ( textureWidth * maxTextSize);\n\t\t\t++glyphNum;\n\t\t}\n\t\t\n\t\tglyphNum = FillGlyphs( glyphNum, glTextureID[numTextures - 1], textureWidth, heightRemain, currTextPtr);\n\t\tCreateTexture( numTextures - 1, textureWidth, heightRemain, currTextPtr);\n\t}\n\telse\n\t{\n\t\ttextureHeight = NextPowerOf2( textureHeight);\n\t\ttotalMem = textureWidth * textureHeight;\n\t\t\n\t\tglGenTextures( numTextures, (GLuint*)&glTextureID[0]);\n\n\t\ttextMem = new unsigned char[totalMem]; \/\/ GL_ALPHA texture;\n\t\tmemset( textMem, 0, totalMem);\n\n\t\tFillGlyphs( 0, glTextureID[0], textureWidth, textureHeight, textMem);\n\t\tCreateTexture( 0, textureWidth, textureHeight, textMem);\n\t}\n\n\tdelete [] textMem;\n\treturn !err;\n}\n\n\nunsigned int FTGLTextureFont::FillGlyphs( unsigned int glyphStart, int id, int width, int height, unsigned char* textdata)\n{\n\tint currentTextX = padding;\n\tint currentTextY = padding;\/\/ + padding;\n\t\n\tfloat currTextU = (float)padding \/ (float)width;\n\tfloat currTextV = (float)padding \/ (float)height;\n\t\n\/\/\tnumGlyphs = 256; \/\/ FIXME hack\n\tunsigned int n;\n\t\n\tfor( n = glyphStart; n <= numGlyphs; ++n)\n\t{\n\t\tFT_Glyph* ftGlyph = face.Glyph( n, FT_LOAD_NO_HINTING);\n\t\t\n\t\tif( ftGlyph)\n\t\t{\n\t\t\tunsigned char* data = textdata + (( currentTextY * width) + currentTextX);\n\t\t\t\n\t\t\tcurrTextU = (float)currentTextX \/ (float)width;\n\t\t\t\n\t\t\ttempGlyph = new FTTextureGlyph( *ftGlyph, id, data, width, height, currTextU, currTextV);\n\t\t\tglyphList->Add( tempGlyph);\n\n\t\t\tcurrentTextX += glyphWidth;\n\t\t\tif( currentTextX > ( width - glyphWidth))\n\t\t\t{\n\t\t\t\tcurrentTextY += glyphHeight;\n\t\t\t\tif( currentTextY > ( height - glyphHeight))\n\t\t\t\t\treturn n;\n\t\t\t\t\t\n\t\t\t\tcurrentTextX = padding;\n\t\t\t\tcurrTextV = (float)currentTextY \/ (float)height;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terr = face.Error();\n\t\t}\n\t}\n\n\treturn n;\n}\n\n\nvoid FTGLTextureFont::GetSize()\n{\n\t\/\/work out the max width. Most likely maxTextSize\n\ttextureWidth = NextPowerOf2( numGlyphs * glyphWidth);\n\tif( textureWidth > maxTextSize)\n\t{\n\t\ttextureWidth = maxTextSize;\n\t}\n\t\n\tint h = static_cast<int>( textureWidth \/ glyphWidth);\n\ttextureHeight = (( numGlyphs \/ h) + 1) * glyphHeight;\n}\n\n\nvoid FTGLTextureFont::CreateTexture( int id, int width, int height, unsigned char* data)\n{\n\tglPixelStorei( GL_UNPACK_ALIGNMENT, 1); \/\/What does this do exactly?\n\tglBindTexture( GL_TEXTURE_2D, glTextureID[id]);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tglTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);\n}\n\n\nvoid FTGLTextureFont::render( const char* string)\n{\t\n\tglPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);\n\t\n\tglEnable(GL_BLEND);\n \tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n \t\n\tglBindTexture( GL_TEXTURE_2D, (GLuint)FTTextureGlyph::activeTextureID);\n\n \t\/\/ QUADS are faster!? Less function call overhead?\n \tglBegin( GL_QUADS);\n \t\tFTFont::render( string);\n \tglEnd();\n\t\n\tglPopAttrib();\n}\n\n\nvoid FTGLTextureFont::render( const wchar_t* string)\n{\t\n\tglPushAttrib( GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT | GL_PIXEL_MODE_BIT);\n\t\n\tglEnable(GL_BLEND);\n \tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ GL_ONE\n \t\n\tglBindTexture( GL_TEXTURE_2D, (GLuint)FTTextureGlyph::activeTextureID);\n\n \t\/\/ QUADS are faster!? Less function call overhead?\n \tglBegin( GL_QUADS);\n \t\tFTFont::render( string);\n \tglEnd();\n\t\n\tglPopAttrib();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Base class for a sprocket template with gear profile composed of circular\n\/\/ arcs and a flat seat, suitable for interaction with double-pin track shoes.\n\/\/\n\/\/ =============================================================================\n\n#include <cmath>\n\n#include \"chrono_vehicle\/tracked_vehicle\/sprocket\/ChSprocketDoublePin.h\"\n#include \"chrono_vehicle\/tracked_vehicle\/track_shoe\/ChTrackShoeDoublePin.h\"\n#include \"chrono_vehicle\/tracked_vehicle\/ChTrackAssembly.h\"\n\nnamespace chrono {\nnamespace vehicle {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nclass SprocketDoublePinContactCB : public ChSystem::ChCustomComputeCollisionCallback {\n public:\n SprocketDoublePinContactCB(ChTrackAssembly* track, \/\/\/< containing track assembly\n double envelope, \/\/\/< collision detection envelope\n int gear_nteeth, \/\/\/< number of teeth of the sprocket gear\n double gear_RO, \/\/\/< radius if the addendum circle\n double gear_R, \/\/\/< radius of the tooth arc profile\n double gear_C, \/\/\/< height of profile arcs\n double gear_W, \/\/\/< offset of profile arcs\n double separation, \/\/\/< separation between sprocket gears\n double shoe_len, \/\/\/< length of track shoe connector\n double shoe_R \/\/\/< radius of track shoe connector\n )\n : m_track(track),\n m_envelope(envelope),\n m_sprocket(m_track->GetSprocket()),\n m_gear_nteeth(gear_nteeth),\n m_gear_RO(gear_RO),\n m_gear_R(gear_R),\n m_gear_C(gear_C),\n m_gear_W(gear_W),\n m_gear_Rhat(gear_R - envelope),\n m_separation(separation),\n m_shoe_len(shoe_len),\n m_shoe_R(shoe_R),\n m_shoe_Rhat(shoe_R + envelope) {}\n\n virtual void PerformCustomCollision(ChSystem* system) override;\n\n private:\n ChTrackAssembly* m_track; \/\/ pointer to containing track assembly\n std::shared_ptr<ChSprocket> m_sprocket; \/\/ handle to the sprocket\n\n double m_envelope; \/\/ collision detection envelope\n\n int m_gear_nteeth; \/\/ sprocket gear, number of teeth\n double m_gear_RO; \/\/ sprocket gear, outer radius (radius of addendum circle)\n double m_gear_R; \/\/ sprocket gear, arc radius\n double m_gear_C; \/\/ sprocket gear, arc center height\n double m_gear_W; \/\/ sprocket gear, arc center offset\n double m_separation; \/\/ separation distance between sprocket gears\n double m_shoe_len; \/\/ length of track shoe connector\n double m_shoe_R; \/\/ radius of track shoe connector\n\n double m_gear_Rhat; \/\/ adjusted gear arc radius\n double m_shoe_Rhat; \/\/ adjusted she cylinder radius\n};\n\nvoid SprocketDoublePinContactCB::PerformCustomCollision(ChSystem* system) {\n \/\/ Return now if collision disabled on sproket or track shoes.\n if (!m_sprocket->GetGearBody()->GetCollide() || !m_track->GetTrackShoe(0)->GetShoeBody()->GetCollide())\n return;\n\n \/\/\/\/ TODO\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nChSprocketDoublePin::ChSprocketDoublePin(const std::string& name) : ChSprocket(name) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nChSystem::ChCustomComputeCollisionCallback* ChSprocketDoublePin::GetCollisionCallback(ChTrackAssembly* track) {\n \/\/ Check compatibility between this type of sprocket and the track shoes.\n \/\/ We expect track shoes of type ChSinglePinShoe.\n auto shoe = std::dynamic_pointer_cast<ChTrackShoeDoublePin>(track->GetTrackShoe(0));\n assert(shoe);\n\n \/\/ Extract parameterization of gear profile\n int gear_nteeth = GetNumTeeth();\n double gear_RO = GetOuterRadius();\n double gear_R = GetArcRadius();\n double gear_C = GetArcCenterHeight();\n double gear_W = GetArcCenterOffset();\n\n \/\/ Extract parameterization of the shoe contact geometry.\n double shoe_len = shoe->GetConnectorLength();\n double shoe_R = shoe->GetConnectorRadius();\n\n \/\/ Create and return the callback object. Note: this pointer will be freed by the base class.\n return new SprocketDoublePinContactCB(track, 0.005, gear_nteeth, gear_RO, gear_R, gear_C, gear_W, GetSeparation(),\n shoe_len, shoe_R);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create and return the sprocket gear profile.\n\/\/ -----------------------------------------------------------------------------\nstd::shared_ptr<geometry::ChLinePath> ChSprocketDoublePin::GetProfile() {\n auto profile = std::make_shared<geometry::ChLinePath>();\n\n int num_teeth = GetNumTeeth();\n double R_T = GetOuterRadius();\n double C = GetArcCenterHeight();\n double W = GetArcCenterOffset();\n double R_C = std::sqrt(C * C + W * W);\n double R = GetArcRadius();\n double D = W - R;\n\n double beta = CH_C_2PI \/ num_teeth;\n double sbeta = std::sin(beta \/ 2);\n double cbeta = std::cos(beta \/ 2);\n\n for (int i = 0; i < num_teeth; ++i) {\n ChVector<> p0L(-(R_T - D) * sbeta, (R_T - D) * cbeta, 0);\n ChVector<> p0R(+(R_T - D) * sbeta, (R_T - D) * cbeta, 0);\n\n ChVector<> p1L = p0L + ChVector<>(+D * cbeta, D * sbeta, 0);\n ChVector<> p1R = p0R + ChVector<>(-D * cbeta, D * sbeta, 0);\n\n ChVector<> p2L = ChVector<>(-C*sbeta, C*cbeta, 0) + ChVector<>(+D * cbeta, D * sbeta, 0);\n ChVector<> p2R = ChVector<>(+C*sbeta, C*cbeta, 0) + ChVector<>(-D * cbeta, D * sbeta, 0);\n\n ChVector<> p3L = p2L + ChVector<>(+R * cbeta, R * sbeta, 0);\n ChVector<> p3R = p2R + ChVector<>(-R * cbeta, R * sbeta, 0);\n\n ChVector<> p4L = p3L - ChVector<>(0, R, 0);\n ChVector<> p4R = p3R - ChVector<>(0, R, 0);\n\n double alpha = -i * beta;\n ChMatrix33<> rot(alpha, ChVector<>(0, 0, 1));\n\n p0L = rot * p0L;\n p1L = rot * p1L;\n p2L = rot * p2L;\n p3L = rot * p3L;\n p4L = rot * p4L;\n\n p0R = rot * p0R;\n p1R = rot * p1R;\n p2R = rot * p2R;\n p3R = rot * p3R;\n p4R = rot * p4R;\n\n geometry::ChLineArc arc1(ChCoordsys<>(p0L), D, alpha + CH_C_PI_2 + beta \/ 2, alpha + beta \/ 2);\n geometry::ChLineSegment seg2(p1L, p2L);\n geometry::ChLineArc arc3(ChCoordsys<>(p3L), R, alpha + CH_C_PI + beta \/ 2, alpha + 1.5 * CH_C_PI, true);\n geometry::ChLineSegment seg4(p4L, p4R);\n geometry::ChLineArc arc5(ChCoordsys<>(p3R), R, alpha + 1.5 * CH_C_PI, alpha + CH_C_2PI - beta \/ 2, true);\n geometry::ChLineSegment seg6(p2R, p1R);\n geometry::ChLineArc arc7(ChCoordsys<>(p0R), D, alpha + CH_C_PI - beta \/ 2, alpha + CH_C_PI_2 - beta \/ 2);\n\n profile->AddSubLine(arc1);\n profile->AddSubLine(seg2);\n profile->AddSubLine(arc3);\n profile->AddSubLine(seg4);\n profile->AddSubLine(arc5);\n profile->AddSubLine(seg6);\n profile->AddSubLine(arc7);\n }\n\n return profile;\n}\n\n} \/\/ end namespace vehicle\n} \/\/ end namespace chrono\n<commit_msg>Partial implementation of custom contact callback for double-pin sprocket-shoe contact (WIP)<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Base class for a sprocket template with gear profile composed of circular\n\/\/ arcs and a flat seat, suitable for interaction with double-pin track shoes.\n\/\/\n\/\/ =============================================================================\n\n#include <cmath>\n\n#include \"chrono_vehicle\/tracked_vehicle\/sprocket\/ChSprocketDoublePin.h\"\n#include \"chrono_vehicle\/tracked_vehicle\/track_shoe\/ChTrackShoeDoublePin.h\"\n#include \"chrono_vehicle\/tracked_vehicle\/ChTrackAssembly.h\"\n\nnamespace chrono {\nnamespace vehicle {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nclass SprocketDoublePinContactCB : public ChSystem::ChCustomComputeCollisionCallback {\n public:\n SprocketDoublePinContactCB(ChTrackAssembly* track, \/\/\/< containing track assembly\n double envelope, \/\/\/< collision detection envelope\n int gear_nteeth, \/\/\/< number of teeth of the sprocket gear\n double gear_RT, \/\/\/< radius if the addendum circle\n double gear_R, \/\/\/< radius of the tooth arc profile\n double gear_C, \/\/\/< height of profile arcs\n double gear_W, \/\/\/< offset of profile arcs\n double separation, \/\/\/< separation between sprocket gears\n double shoe_len, \/\/\/< length of track shoe connector\n double shoe_R \/\/\/< radius of track shoe connector\n )\n : m_track(track),\n m_envelope(envelope),\n m_sprocket(m_track->GetSprocket()),\n m_gear_nteeth(gear_nteeth),\n m_gear_RT(gear_RT),\n m_gear_R(gear_R),\n m_gear_C(gear_C),\n m_gear_W(gear_W),\n m_gear_Rhat(gear_R - envelope),\n m_separation(separation),\n m_shoe_len(shoe_len),\n m_shoe_R(shoe_R),\n m_shoe_Rhat(shoe_R + envelope) {\n m_R_sum = (m_shoe_len + 2 * m_shoe_R) + m_gear_RT;\n m_gear_RC = std::sqrt(m_gear_C * m_gear_C + m_gear_W * m_gear_W);\n m_gear_D = m_gear_W - m_gear_R;\n m_beta = CH_C_2PI \/ m_gear_nteeth;\n m_sbeta = std::sin(m_beta \/ 2);\n m_cbeta = std::cos(m_beta \/ 2);\n\n }\n\n virtual void PerformCustomCollision(ChSystem* system) override;\n\n private:\n \/\/ Test collision between a connector body and the sprocket's gear profiles.\n void CheckConnectorSprocket(std::shared_ptr<ChBody> connector, \/\/ connector body\n const ChVector<>& locS_abs \/\/ center of sprocket (global frame)\n );\n\n \/\/ Test collision between a circle and the gear profile (in the plane of the gear).\n void CheckCircleProfile(std::shared_ptr<ChBody> connector, \/\/ connector body\n const ChVector<>& loc, \/\/ center of circular connector end\n const ChVector<>& p1L,\n const ChVector<>& p2L,\n const ChVector<>& p3L,\n const ChVector<>& p1R,\n const ChVector<>& p2R,\n const ChVector<>& p3R);\n\n ChTrackAssembly* m_track; \/\/ pointer to containing track assembly\n std::shared_ptr<ChSprocket> m_sprocket; \/\/ handle to the sprocket\n\n double m_envelope; \/\/ collision detection envelope\n\n int m_gear_nteeth; \/\/ sprocket gear, number of teeth\n double m_gear_RT; \/\/ sprocket gear, outer tooth radius (radius of addendum circle)\n double m_gear_R; \/\/ sprocket gear, arc radius\n double m_gear_C; \/\/ sprocket gear, arc center height\n double m_gear_W; \/\/ sprocket gear, arc center offset\n double m_separation; \/\/ separation distance between sprocket gears\n\n double m_gear_D; \/\/ tooth width (D = W - R)\n double m_gear_RC; \/\/ radius of arc centers circle (RC^2 = C^2 + W^2)\n\n double m_beta; \/\/ angle between two consecutive gear teeth\n double m_sbeta; \/\/ sin(beta\/2)\n double m_cbeta; \/\/ cos(beta\/2)\n\n double m_shoe_len; \/\/ length of track shoe connector\n double m_shoe_R; \/\/ radius of track shoe connector\n\n double m_gear_Rhat; \/\/ adjusted gear arc radius\n double m_shoe_Rhat; \/\/ adjusted shoe cylinder radius\n\n double m_R_sum; \/\/ test quantity for broadphase check\n};\n\n\/\/ Add contacts between the sprocket and track shoes.\nvoid SprocketDoublePinContactCB::PerformCustomCollision(ChSystem* system) {\n \/\/ Return now if collision disabled on sproket.\n if (!m_sprocket->GetGearBody()->GetCollide())\n return;\n\n \/\/ Sprocket gear center location (expressed in global frame)\n ChVector<> locS_abs = m_sprocket->GetGearBody()->GetPos();\n\n \/\/ Loop over all track shoes in the associated track\n for (size_t is = 0; is < m_track->GetNumTrackShoes(); ++is) {\n auto shoe = std::static_pointer_cast<ChTrackShoeDoublePin>(m_track->GetTrackShoe(is));\n \n \/\/ Perform collision test for the \"left\" connector body\n CheckConnectorSprocket(shoe->m_connector_L, locS_abs);\n\n \/\/ Perform collision test for the \"right\" connector body\n CheckConnectorSprocket(shoe->m_connector_R, locS_abs);\n }\n}\n\n\/\/ Perform collision test between the specified connector body and the associated sprocket.\nvoid SprocketDoublePinContactCB::CheckConnectorSprocket(std::shared_ptr<ChBody> connector, const ChVector<>& locS_abs) {\n \/\/ (1) Express the center of the connector body in the sprocket frame\n ChVector<> loc = m_sprocket->GetGearBody()->TransformPointParentToLocal(connector->GetPos());\n\n \/\/ (2) Broadphase collision test: no contact if the connector's center is too far from the\n \/\/ center of the gear (test perfomed in the sprocket's x-z plane).\n if (loc.x * loc.x + loc.z * loc.z > m_R_sum * m_R_sum)\n return;\n\n \/\/ (3) Working in the frame of the sprocket, find the candidate tooth space.\n \/\/ This is the closest tooth space to the connector center point.\n\n \/\/ Angle formed by 'locC' and the line z>0\n double angle = std::atan2(loc.x, loc.z);\n \/\/ Find angle of closest tooth space\n double alpha = m_beta * std::round(angle \/ m_beta);\n \/\/ Convert to degrees\n double alpha_deg = alpha * 180 \/ CH_C_PI;\n\n \/\/ (4) Calculate the points that define the current tooth space.\n \/\/ Note that all these points will have Y = locC.y\n ChVector<> p0L(-(m_gear_RT - m_gear_D) * m_sbeta, loc.y, (m_gear_RT - m_gear_D) * m_cbeta);\n ChVector<> p0R(+(m_gear_RT - m_gear_D) * m_sbeta, loc.y, (m_gear_RT - m_gear_D) * m_cbeta);\n\n ChVector<> p1L = p0L + ChVector<>(+m_gear_D * m_cbeta, 0, m_gear_D * m_sbeta);\n ChVector<> p1R = p0R + ChVector<>(-m_gear_D * m_cbeta, 0, m_gear_D * m_sbeta);\n\n ChVector<> p2L = ChVector<>(-m_gear_C * m_sbeta, loc.y, m_gear_C * m_cbeta) +\n ChVector<>(+m_gear_D * m_cbeta, 0, m_gear_D * m_sbeta);\n ChVector<> p2R = ChVector<>(+m_gear_C * m_sbeta, loc.y, m_gear_C * m_cbeta) +\n ChVector<>(-m_gear_D * m_cbeta, 0, m_gear_D * m_sbeta);\n\n ChVector<> p3L = p2L + ChVector<>(+m_gear_R * m_cbeta, 0, m_gear_R * m_sbeta);\n ChVector<> p3R = p2R + ChVector<>(-m_gear_R * m_cbeta, 0, m_gear_R * m_sbeta);\n\n ChVector<> p4L = p3L - ChVector<>(0, 0, m_gear_R);\n ChVector<> p4R = p3R - ChVector<>(0, 0, m_gear_R);\n\n ChMatrix33<> rot(alpha, ChVector<>(0, 1, 0));\n\n p0L = rot * p0L;\n p1L = rot * p1L;\n p2L = rot * p2L;\n p3L = rot * p3L;\n p4L = rot * p4L;\n\n p0R = rot * p0R;\n p1R = rot * p1R;\n p2R = rot * p2R;\n p3R = rot * p3R;\n p4R = rot * p4R;\n\n \/\/ (5) Express the centers of the two connector end-caps in the sprocket frame.\n ChVector<> P1_abs = connector->TransformPointLocalToParent(ChVector<>(m_shoe_len \/ 2, 0, 0));\n ChVector<> P2_abs = connector->TransformPointLocalToParent(ChVector<>(-m_shoe_len \/ 2, 0, 0));\n ChVector<> P1 = m_sprocket->GetGearBody()->TransformPointParentToLocal(P1_abs);\n ChVector<> P2 = m_sprocket->GetGearBody()->TransformPointParentToLocal(P2_abs);\n\n \/\/\/\/if (loc.y > 0) {\n \/\/\/\/ std::cout << loc.x << \" \" << loc.y << \" \" << loc.z << std::endl;\n \/\/\/\/ std::cout << P1.x << \" \" << P1.y << \" \" << P1.z << std::endl;\n \/\/\/\/ std::cout << P2.x << \" \" << P2.y << \" \" << P2.z << std::endl;\n \/\/\/\/ std::cout << p0L.x << \" \" << p0L.y << \" \" << p0L.z << std::endl;\n \/\/\/\/ std::cout << p1L.x << \" \" << p1L.y << \" \" << p1L.z << std::endl;\n \/\/\/\/ std::cout << p2L.x << \" \" << p2L.y << \" \" << p2L.z << std::endl;\n \/\/\/\/ std::cout << p3L.x << \" \" << p3L.y << \" \" << p3L.z << std::endl;\n \/\/\/\/ std::cout << p4L.x << \" \" << p4L.y << \" \" << p4L.z << std::endl;\n \/\/\/\/ std::cout << p0R.x << \" \" << p0R.y << \" \" << p0R.z << std::endl;\n \/\/\/\/ std::cout << p1R.x << \" \" << p1R.y << \" \" << p1R.z << std::endl;\n \/\/\/\/ std::cout << p2R.x << \" \" << p2R.y << \" \" << p2R.z << std::endl;\n \/\/\/\/ std::cout << p3R.x << \" \" << p3R.y << \" \" << p3R.z << std::endl;\n \/\/\/\/ std::cout << p4R.x << \" \" << p4R.y << \" \" << p4R.z << std::endl;\n \/\/\/\/ std::cout << std::endl;\n \/\/\/\/}\n\n \/\/ (6) Perform collision test between the front end of the connector and the gear profile.\n CheckCircleProfile(connector, P1, p1L, p2L, p3L, p1R, p2R, p3R);\n\n \/\/ (7) Perform collision test between the rear end of the connector and the gear profile.\n CheckCircleProfile(connector, P2, p1L, p2L, p3L, p1R, p2R, p3R);\n}\n\n\/\/ Working in the (x-z) plane of the gear, perform a 2D collision test between a circle\n\/\/ of radius m_shoe_R centered at the specified location and the gear profile.\nvoid SprocketDoublePinContactCB::CheckCircleProfile(std::shared_ptr<ChBody> connector,\n const ChVector<>& loc,\n const ChVector<>& p1L,\n const ChVector<>& p2L,\n const ChVector<>& p3L,\n const ChVector<>& p1R,\n const ChVector<>& p2R,\n const ChVector<>& p3R) { \n \/\/ Check circle against arc centered at p3L.\n\n \/\/ Check circle against arc centered at p3R.\n\n \/\/ Check circle against segment p1L - p2L.\n\n \/\/ Check circle against segment p1R - p2R.\n\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nChSprocketDoublePin::ChSprocketDoublePin(const std::string& name) : ChSprocket(name) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nChSystem::ChCustomComputeCollisionCallback* ChSprocketDoublePin::GetCollisionCallback(ChTrackAssembly* track) {\n \/\/ Check compatibility between this type of sprocket and the track shoes.\n \/\/ We expect track shoes of type ChSinglePinShoe.\n auto shoe = std::dynamic_pointer_cast<ChTrackShoeDoublePin>(track->GetTrackShoe(0));\n assert(shoe);\n\n \/\/ Extract parameterization of gear profile\n int gear_nteeth = GetNumTeeth();\n double gear_RT = GetOuterRadius();\n double gear_R = GetArcRadius();\n double gear_C = GetArcCenterHeight();\n double gear_W = GetArcCenterOffset();\n\n \/\/ Extract parameterization of the shoe connector contact geometry.\n double shoe_len = shoe->GetConnectorLength();\n double shoe_R = shoe->GetConnectorRadius();\n\n \/\/ Create and return the callback object. Note: this pointer will be freed by the base class.\n return new SprocketDoublePinContactCB(track, 0.005, gear_nteeth, gear_RT, gear_R, gear_C, gear_W, GetSeparation(),\n shoe_len, shoe_R);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create and return the sprocket gear profile.\n\/\/ -----------------------------------------------------------------------------\nstd::shared_ptr<geometry::ChLinePath> ChSprocketDoublePin::GetProfile() {\n auto profile = std::make_shared<geometry::ChLinePath>();\n\n int num_teeth = GetNumTeeth();\n double R_T = GetOuterRadius();\n double C = GetArcCenterHeight();\n double W = GetArcCenterOffset();\n double R_C = std::sqrt(C * C + W * W);\n double R = GetArcRadius();\n double D = W - R;\n\n double beta = CH_C_2PI \/ num_teeth;\n double sbeta = std::sin(beta \/ 2);\n double cbeta = std::cos(beta \/ 2);\n\n for (int i = 0; i < num_teeth; ++i) {\n ChVector<> p0L(-(R_T - D) * sbeta, (R_T - D) * cbeta, 0);\n ChVector<> p0R(+(R_T - D) * sbeta, (R_T - D) * cbeta, 0);\n\n ChVector<> p1L = p0L + ChVector<>(+D * cbeta, D * sbeta, 0);\n ChVector<> p1R = p0R + ChVector<>(-D * cbeta, D * sbeta, 0);\n\n ChVector<> p2L = ChVector<>(-C*sbeta, C*cbeta, 0) + ChVector<>(+D * cbeta, D * sbeta, 0);\n ChVector<> p2R = ChVector<>(+C*sbeta, C*cbeta, 0) + ChVector<>(-D * cbeta, D * sbeta, 0);\n\n ChVector<> p3L = p2L + ChVector<>(+R * cbeta, R * sbeta, 0);\n ChVector<> p3R = p2R + ChVector<>(-R * cbeta, R * sbeta, 0);\n\n ChVector<> p4L = p3L - ChVector<>(0, R, 0);\n ChVector<> p4R = p3R - ChVector<>(0, R, 0);\n\n double alpha = -i * beta;\n ChMatrix33<> rot(alpha, ChVector<>(0, 0, 1));\n\n p0L = rot * p0L;\n p1L = rot * p1L;\n p2L = rot * p2L;\n p3L = rot * p3L;\n p4L = rot * p4L;\n\n p0R = rot * p0R;\n p1R = rot * p1R;\n p2R = rot * p2R;\n p3R = rot * p3R;\n p4R = rot * p4R;\n\n geometry::ChLineArc arc1(ChCoordsys<>(p0L), D, alpha + CH_C_PI_2 + beta \/ 2, alpha + beta \/ 2);\n geometry::ChLineSegment seg2(p1L, p2L);\n geometry::ChLineArc arc3(ChCoordsys<>(p3L), R, alpha + CH_C_PI + beta \/ 2, alpha + 1.5 * CH_C_PI, true);\n geometry::ChLineSegment seg4(p4L, p4R);\n geometry::ChLineArc arc5(ChCoordsys<>(p3R), R, alpha + 1.5 * CH_C_PI, alpha + CH_C_2PI - beta \/ 2, true);\n geometry::ChLineSegment seg6(p2R, p1R);\n geometry::ChLineArc arc7(ChCoordsys<>(p0R), D, alpha + CH_C_PI - beta \/ 2, alpha + CH_C_PI_2 - beta \/ 2);\n\n profile->AddSubLine(arc1);\n profile->AddSubLine(seg2);\n profile->AddSubLine(arc3);\n profile->AddSubLine(seg4);\n profile->AddSubLine(arc5);\n profile->AddSubLine(seg6);\n profile->AddSubLine(arc7);\n }\n\n return profile;\n}\n\n} \/\/ end namespace vehicle\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"<commit_before>#include <Poco\/Exception.h>\n\n#include \"di\/Injectable.h\"\n#include \"model\/ModuleType.h\"\n#include \"provider\/DeviceInfoProvider.h\"\n#include \"util\/DevicesSAXHandler.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::XML;\nusing namespace BeeeOn;\n\nBEEEON_OBJECT_BEGIN(BeeeOn, DeviceInfoProvider)\nBEEEON_OBJECT_CASTABLE(InfoProvider<DeviceInfo>)\nBEEEON_OBJECT_PROPERTY(\"devicesFile\", &DeviceInfoProvider::setDevicesFile)\nBEEEON_OBJECT_PROPERTY(\"typeInfoProvider\", &DeviceInfoProvider::setTypeInfoProvider)\nBEEEON_OBJECT_PROPERTY(\"subtypeInfoProvider\", &DeviceInfoProvider::setSubtypeInfoProvider)\nBEEEON_OBJECT_HOOK(\"done\", &DeviceInfoProvider::loadInfo)\nBEEEON_OBJECT_END(BeeeOn, DeviceInfoProvider)\n\nDeviceInfoProvider::DeviceInfoProvider():\n\tm_typeProvider(&NullInfoProvider<TypeInfo>::instance()),\n\tm_subtypeProvider(&NullInfoProvider<SubtypeInfo>::instance())\n{\n}\n\nvoid DeviceInfoProvider::setDevicesFile(const std::string &devicesFile)\n{\n\tm_devicesFile = devicesFile;\n}\n\nvoid DeviceInfoProvider::setTypeInfoProvider(InfoProvider<TypeInfo> *provider)\n{\n\tm_typeProvider = provider == NULL?\n\t\t&NullInfoProvider<TypeInfo>::instance() : provider;\n}\n\nvoid DeviceInfoProvider::setSubtypeInfoProvider(InfoProvider<SubtypeInfo> *provider)\n{\n\tm_subtypeProvider = provider == NULL?\n\t\t&NullInfoProvider<SubtypeInfo>::instance() : provider;\n}\n\nDeviceInfo DeviceInfoProvider::resolveTypes(const DeviceInfo &device)\n{\n\tstatic const TypeInfoID TYPE_ENUM_ID = ModuleType::Type::TYPE_ENUM;\n\n\tDeviceInfo result(device);\n\tresult.clear();\n\n\tfor (auto &module : device) {\n\t\tconst TypeInfoID &id = module.type()->id();\n\t\tconst SharedPtr<TypeInfo> info = m_typeProvider->findById(id);\n\n\t\tif (info.isNull()) {\n\t\t\tthrow IllegalStateException(\n\t\t\t\t\"could not resolve type \" + id.toString()\n\t\t\t\t+ \" for device \" + device);\n\t\t}\n\n\t\tModuleInfo copy(module);\n\t\tcopy.setType(info);\n\n\t\tif (id == TYPE_ENUM_ID) {\n\t\t\tif (module.subtype().isNull()) {\n\t\t\t\tthrow IllegalStateException(\n\t\t\t\t\t\"missing subtype for enum for device \" + device);\n\t\t\t}\n\n\t\t\tconst SubtypeInfoID &id = module.subtype()->id();\n\t\t\tconst SharedPtr<SubtypeInfo> subtypeInfo = m_subtypeProvider->findById(id);\n\n\t\t\tif (subtypeInfo.isNull()) {\n\t\t\t\tthrow IllegalStateException(\n\t\t\t\t\t\"no such subtype \" + id.toString() + \" for device \" + device);\n\t\t\t}\n\n\t\t\tcopy.setSubtype(subtypeInfo);\n\t\t}\n\n\t\tresult.add(copy);\n\t}\n\n\treturn result;\n}\n\nvoid DeviceInfoProvider::loadInfo()\n{\n\tparseFile<DevicesSAXHandler>(m_devicesFile, \"device\");\n\n\tInfoProvider<DeviceInfo>::InfoSet set;\n\n\tfor (auto &device : infoSet())\n\t\tset.insert(new DeviceInfo(resolveTypes(*device)));\n\n\tinfoSet() = set;\n}\n\nconst SharedPtr<DeviceInfo> DeviceInfoProvider::findByNameAndVendor(\n\t\tconst std::string &name, const std::string &vendor) const\n{\n\tfor (auto info : infoSet()) {\n\t\tif (info->match(name, vendor))\n\t\t\treturn info;\n\t}\n\n\treturn NULL;\n}\n<commit_msg>DeviceInfoProvider: handle subtype for TYPE_BITMAP as well<commit_after>#include <Poco\/Exception.h>\n\n#include \"di\/Injectable.h\"\n#include \"model\/ModuleType.h\"\n#include \"provider\/DeviceInfoProvider.h\"\n#include \"util\/DevicesSAXHandler.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::XML;\nusing namespace BeeeOn;\n\nBEEEON_OBJECT_BEGIN(BeeeOn, DeviceInfoProvider)\nBEEEON_OBJECT_CASTABLE(InfoProvider<DeviceInfo>)\nBEEEON_OBJECT_PROPERTY(\"devicesFile\", &DeviceInfoProvider::setDevicesFile)\nBEEEON_OBJECT_PROPERTY(\"typeInfoProvider\", &DeviceInfoProvider::setTypeInfoProvider)\nBEEEON_OBJECT_PROPERTY(\"subtypeInfoProvider\", &DeviceInfoProvider::setSubtypeInfoProvider)\nBEEEON_OBJECT_HOOK(\"done\", &DeviceInfoProvider::loadInfo)\nBEEEON_OBJECT_END(BeeeOn, DeviceInfoProvider)\n\nDeviceInfoProvider::DeviceInfoProvider():\n\tm_typeProvider(&NullInfoProvider<TypeInfo>::instance()),\n\tm_subtypeProvider(&NullInfoProvider<SubtypeInfo>::instance())\n{\n}\n\nvoid DeviceInfoProvider::setDevicesFile(const std::string &devicesFile)\n{\n\tm_devicesFile = devicesFile;\n}\n\nvoid DeviceInfoProvider::setTypeInfoProvider(InfoProvider<TypeInfo> *provider)\n{\n\tm_typeProvider = provider == NULL?\n\t\t&NullInfoProvider<TypeInfo>::instance() : provider;\n}\n\nvoid DeviceInfoProvider::setSubtypeInfoProvider(InfoProvider<SubtypeInfo> *provider)\n{\n\tm_subtypeProvider = provider == NULL?\n\t\t&NullInfoProvider<SubtypeInfo>::instance() : provider;\n}\n\nDeviceInfo DeviceInfoProvider::resolveTypes(const DeviceInfo &device)\n{\n\tstatic const TypeInfoID TYPE_ENUM_ID = ModuleType::Type::TYPE_ENUM;\n\tstatic const TypeInfoID TYPE_BITMAP_ID = ModuleType::Type::TYPE_BITMAP;\n\n\tDeviceInfo result(device);\n\tresult.clear();\n\n\tfor (auto &module : device) {\n\t\tconst TypeInfoID &id = module.type()->id();\n\t\tconst SharedPtr<TypeInfo> info = m_typeProvider->findById(id);\n\n\t\tif (info.isNull()) {\n\t\t\tthrow IllegalStateException(\n\t\t\t\t\"could not resolve type \" + id.toString()\n\t\t\t\t+ \" for device \" + device);\n\t\t}\n\n\t\tModuleInfo copy(module);\n\t\tcopy.setType(info);\n\n\t\tif (id == TYPE_ENUM_ID || id == TYPE_BITMAP_ID) {\n\t\t\tif (module.subtype().isNull()) {\n\t\t\t\tthrow IllegalStateException(\n\t\t\t\t\t\"missing subtype for enum for device \" + device);\n\t\t\t}\n\n\t\t\tconst SubtypeInfoID &id = module.subtype()->id();\n\t\t\tconst SharedPtr<SubtypeInfo> subtypeInfo = m_subtypeProvider->findById(id);\n\n\t\t\tif (subtypeInfo.isNull()) {\n\t\t\t\tthrow IllegalStateException(\n\t\t\t\t\t\"no such subtype \" + id.toString() + \" for device \" + device);\n\t\t\t}\n\n\t\t\tcopy.setSubtype(subtypeInfo);\n\t\t}\n\n\t\tresult.add(copy);\n\t}\n\n\treturn result;\n}\n\nvoid DeviceInfoProvider::loadInfo()\n{\n\tparseFile<DevicesSAXHandler>(m_devicesFile, \"device\");\n\n\tInfoProvider<DeviceInfo>::InfoSet set;\n\n\tfor (auto &device : infoSet())\n\t\tset.insert(new DeviceInfo(resolveTypes(*device)));\n\n\tinfoSet() = set;\n}\n\nconst SharedPtr<DeviceInfo> DeviceInfoProvider::findByNameAndVendor(\n\t\tconst std::string &name, const std::string &vendor) const\n{\n\tfor (auto info : infoSet()) {\n\t\tif (info->match(name, vendor))\n\t\t\treturn info;\n\t}\n\n\treturn NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <inviwo\/qt\/widgets\/eventconverterqt.h>\n\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QInputEvent>\n#include <QKeyEvent>\n#ifndef QT_NO_GESTURES\n#include <QGesture>\n#endif\n\nnamespace inviwo {\n\nEventConverterQt::EventConverterQt() {}\nEventConverterQt::~EventConverterQt() {}\n\nMouseEvent::MouseButton inviwo::EventConverterQt::getMouseButton(const QMouseEvent* e) {\n if (e->buttons() == Qt::LeftButton)\n return MouseEvent::MOUSE_BUTTON_LEFT;\n else if (e->buttons() == Qt::RightButton)\n return MouseEvent::MOUSE_BUTTON_RIGHT;\n else if (e->buttons() == Qt::MiddleButton)\n return MouseEvent::MOUSE_BUTTON_MIDDLE;\n\n return MouseEvent::MOUSE_BUTTON_NONE;\n}\n\nMouseEvent::MouseButton EventConverterQt::getMouseButtonCausingEvent(const QMouseEvent* e) {\n\t\/\/ QMouseEvent::getButtons does not\n\t\/\/ include the button that caused the event.\n\t\/\/ The QMouseEvent::getButton function\n\t\/\/ returns the button that caused the event\n\tif (e->button() == Qt::LeftButton)\n\t\treturn MouseEvent::MOUSE_BUTTON_LEFT;\n\telse if (e->buttons() == Qt::RightButton)\n\t\treturn MouseEvent::MOUSE_BUTTON_RIGHT;\n\telse if (e->buttons() == Qt::MiddleButton)\n\t\treturn MouseEvent::MOUSE_BUTTON_MIDDLE;\n\n\treturn MouseEvent::MOUSE_BUTTON_NONE;\n}\n\nMouseEvent::MouseButton inviwo::EventConverterQt::getMouseWheelButton(const QWheelEvent* e) {\n if (e->buttons() == Qt::LeftButton)\n return MouseEvent::MOUSE_BUTTON_LEFT;\n else if (e->buttons() == Qt::RightButton)\n return MouseEvent::MOUSE_BUTTON_RIGHT;\n else if (e->buttons() == Qt::MiddleButton)\n return MouseEvent::MOUSE_BUTTON_MIDDLE;\n\n return MouseEvent::MOUSE_BUTTON_NONE;\n}\n\n#ifndef QT_NO_GESTURES\nGestureEvent::GestureState inviwo::EventConverterQt::getGestureState(const QGesture* gesture){\n if (gesture->state() == Qt::GestureStarted)\n return GestureEvent::GESTURE_STATE_STARTED;\n else if (gesture->state() == Qt::GestureUpdated)\n return GestureEvent::GESTURE_STATE_UPDATED;\n else if (gesture->state() == Qt::GestureFinished)\n return GestureEvent::GESTURE_STATE_ENDED;\n else if (gesture->state() == Qt::GestureCanceled)\n return GestureEvent::GESTURE_STATE_CANCELED;\n\n return GestureEvent::GESTURE_STATE_NONE;\n}\n#endif\n\nInteractionEvent::Modifier inviwo::EventConverterQt::getModifier(const QInputEvent* e) {\n if (e->modifiers() == Qt::ShiftModifier)\n return InteractionEvent::MODIFIER_SHIFT;\n else if (e->modifiers() == Qt::ControlModifier)\n return InteractionEvent::MODIFIER_CTRL;\n else if (e->modifiers() == Qt::AltModifier)\n return InteractionEvent::MODIFIER_ALT;\n\n return InteractionEvent::MODIFIER_NONE;\n}\n\nint EventConverterQt::getKeyButton(const QKeyEvent* e) {\n return e->key();\n \n\/\/ This does not work on OSX and makes no sense. \n\/\/ char key = toupper(e->nativeVirtualKey());\n\/\/\n\/\/ if ((key >= '0' && key <= '9')||(key >= 'A' && key <= 'Z'))\n\/\/ return key;\n\/\/ else\n\/\/ return 0;\n}\n\n} \/\/ namespace<commit_msg>Qt: Fixed release event button for all buttons.<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <inviwo\/qt\/widgets\/eventconverterqt.h>\n\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QInputEvent>\n#include <QKeyEvent>\n#ifndef QT_NO_GESTURES\n#include <QGesture>\n#endif\n\nnamespace inviwo {\n\nEventConverterQt::EventConverterQt() {}\nEventConverterQt::~EventConverterQt() {}\n\nMouseEvent::MouseButton inviwo::EventConverterQt::getMouseButton(const QMouseEvent* e) {\n\tswitch (e->buttons())\n\t{\n\tcase Qt::LeftButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_LEFT;\n\tcase Qt::RightButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_RIGHT;\n\tcase Qt::MiddleButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_MIDDLE;\n\tdefault:\n\t\treturn MouseEvent::MOUSE_BUTTON_NONE;\n\t}\n}\n\nMouseEvent::MouseButton EventConverterQt::getMouseButtonCausingEvent(const QMouseEvent* e) {\n\t\/\/ QMouseEvent::getButtons does not\n\t\/\/ include the button that caused the event.\n\t\/\/ The QMouseEvent::getButton function\n\t\/\/ returns the button that caused the event\n\tswitch (e->button())\n\t{\n\tcase Qt::LeftButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_LEFT;\n\tcase Qt::RightButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_RIGHT;\n\tcase Qt::MiddleButton:\n\t\treturn MouseEvent::MOUSE_BUTTON_MIDDLE;\n\tdefault:\n\t\treturn MouseEvent::MOUSE_BUTTON_NONE;\n\t}\n}\n\nMouseEvent::MouseButton inviwo::EventConverterQt::getMouseWheelButton(const QWheelEvent* e) {\n if (e->buttons() == Qt::LeftButton)\n return MouseEvent::MOUSE_BUTTON_LEFT;\n else if (e->buttons() == Qt::RightButton)\n return MouseEvent::MOUSE_BUTTON_RIGHT;\n else if (e->buttons() == Qt::MiddleButton)\n return MouseEvent::MOUSE_BUTTON_MIDDLE;\n\n return MouseEvent::MOUSE_BUTTON_NONE;\n}\n\n#ifndef QT_NO_GESTURES\nGestureEvent::GestureState inviwo::EventConverterQt::getGestureState(const QGesture* gesture){\n if (gesture->state() == Qt::GestureStarted)\n return GestureEvent::GESTURE_STATE_STARTED;\n else if (gesture->state() == Qt::GestureUpdated)\n return GestureEvent::GESTURE_STATE_UPDATED;\n else if (gesture->state() == Qt::GestureFinished)\n return GestureEvent::GESTURE_STATE_ENDED;\n else if (gesture->state() == Qt::GestureCanceled)\n return GestureEvent::GESTURE_STATE_CANCELED;\n\n return GestureEvent::GESTURE_STATE_NONE;\n}\n#endif\n\nInteractionEvent::Modifier inviwo::EventConverterQt::getModifier(const QInputEvent* e) {\n if (e->modifiers() == Qt::ShiftModifier)\n return InteractionEvent::MODIFIER_SHIFT;\n else if (e->modifiers() == Qt::ControlModifier)\n return InteractionEvent::MODIFIER_CTRL;\n else if (e->modifiers() == Qt::AltModifier)\n return InteractionEvent::MODIFIER_ALT;\n\n return InteractionEvent::MODIFIER_NONE;\n}\n\nint EventConverterQt::getKeyButton(const QKeyEvent* e) {\n return e->key();\n \n\/\/ This does not work on OSX and makes no sense. \n\/\/ char key = toupper(e->nativeVirtualKey());\n\/\/\n\/\/ if ((key >= '0' && key <= '9')||(key >= 'A' && key <= 'Z'))\n\/\/ return key;\n\/\/ else\n\/\/ return 0;\n}\n\n} \/\/ namespace<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = C_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = C_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the core stop state\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attribtes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<commit_msg>Update p9_query_cache_access_state to use the correct scom register<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = EQ_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = EQ_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the core stop state\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attribtes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rdb_protocol\/serialize_datum.hpp\"\n\n#include <string>\n#include <vector>\n\n#include \"containers\/archive\/stl_types.hpp\"\n#include \"containers\/archive\/versioned.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n\nnamespace ql {\n\n\nenum class datum_serialized_type_t {\n R_ARRAY = 1,\n R_BOOL = 2,\n R_NULL = 3,\n DOUBLE = 4,\n R_OBJECT = 5,\n R_STR = 6,\n INT_NEGATIVE = 7,\n INT_POSITIVE = 8,\n};\n\nARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(datum_serialized_type_t, int8_t,\n datum_serialized_type_t::R_ARRAY,\n datum_serialized_type_t::INT_POSITIVE);\n\nvoid datum_serialize(write_message_t *wm, datum_serialized_type_t type) {\n serialize<cluster_version_t::LATEST_OVERALL>(wm, type);\n}\n\nMUST_USE archive_result_t datum_deserialize(read_stream_t *s,\n datum_serialized_type_t *type) {\n return deserialize<cluster_version_t::LATEST_OVERALL>(s, type);\n}\n\n\/\/ This looks like it duplicates code of other deserialization functions. It does.\n\/\/ Keeping this separate means that we don't have to worry about whether datum\n\/\/ serialization has changed from cluster version to cluster version.\n\n\/\/ Keep in sync with datum_serialize.\nsize_t datum_serialized_size(const std::vector<counted_t<const datum_t> > &v) {\n size_t ret = varint_uint64_serialized_size(v.size());\n for (auto it = v.begin(), e = v.end(); it != e; ++it) {\n ret += datum_serialized_size(*it);\n }\n return ret;\n}\n\n\n\/\/ Keep in sync with datum_serialized_size.\nvoid datum_serialize(write_message_t *wm,\n const std::vector<counted_t<const datum_t> > &v) {\n serialize_varint_uint64(wm, v.size());\n for (auto it = v.begin(), e = v.end(); it != e; ++it) {\n datum_serialize(wm, *it);\n }\n}\n\nMUST_USE archive_result_t\ndatum_deserialize(read_stream_t *s, std::vector<counted_t<const datum_t> > *v) {\n v->clear();\n\n uint64_t sz;\n archive_result_t res = deserialize_varint_uint64(s, &sz);\n if (bad(res)) { return res; }\n\n if (sz > std::numeric_limits<size_t>::max()) {\n return archive_result_t::RANGE_ERROR;\n }\n\n v->resize(sz);\n for (uint64_t i = 0; i < sz; ++i) {\n res = datum_deserialize(s, &(*v)[i]);\n if (bad(res)) { return res; }\n }\n\n return archive_result_t::SUCCESS;\n}\n\nsize_t datum_serialized_size(const std::string &s) {\n return serialize_universal_size(s);\n}\nvoid datum_serialize(write_message_t *wm, const std::string &s) {\n serialize_universal(wm, s);\n}\nMUST_USE archive_result_t datum_deserialize(read_stream_t *s, std::string *out) {\n return deserialize_universal(s, out);\n}\n\n\nsize_t datum_serialized_size(\n const std::map<std::string, counted_t<const datum_t> > &m) {\n size_t ret = varint_uint64_serialized_size(m.size());\n for (auto it = m.begin(), e = m.end(); it != e; ++it) {\n ret += datum_serialized_size(it->first);\n ret += datum_serialized_size(it->second);\n }\n return ret;\n}\n\nvoid datum_serialize(write_message_t *wm,\n const std::map<std::string, counted_t<const datum_t> > &m) {\n serialize_varint_uint64(wm, m.size());\n for (auto it = m.begin(), e = m.end(); it != e; ++it) {\n datum_serialize(wm, it->first);\n datum_serialize(wm, it->second);\n }\n}\n\nMUST_USE archive_result_t datum_deserialize(\n read_stream_t *s,\n std::map<std::string, counted_t<const datum_t> > *m) {\n m->clear();\n\n uint64_t sz;\n archive_result_t res = deserialize_varint_uint64(s, &sz);\n if (bad(res)) { return res; }\n\n if (sz > std::numeric_limits<size_t>::max()) {\n return archive_result_t::RANGE_ERROR;\n }\n\n \/\/ Using position should make this function take linear time, not\n \/\/ sz*log(sz) time.\n auto position = m->begin();\n\n for (uint64_t i = 0; i < sz; ++i) {\n std::pair<std::string, counted_t<const datum_t> > p;\n res = datum_deserialize(s, &p.first);\n if (bad(res)) { return res; }\n res = datum_deserialize(s, &p.second);\n if (bad(res)) { return res; }\n position = m->insert(position, std::move(p));\n }\n\n return archive_result_t::SUCCESS;\n}\n\n\n\n\nsize_t datum_serialized_size(const counted_t<const datum_t> &datum) {\n r_sanity_check(datum.has());\n size_t sz = 1; \/\/ 1 byte for the type\n switch (datum->get_type()) {\n case datum_t::R_ARRAY: {\n sz += datum_serialized_size(datum->as_array());\n } break;\n case datum_t::R_BOOL: {\n sz += serialize_universal_size_t<bool>::value;\n } break;\n case datum_t::R_NULL: break;\n case datum_t::R_NUM: {\n double d = datum->as_num();\n int64_t i;\n if (number_as_integer(d, &i)) {\n sz += varint_uint64_serialized_size(i < 0 ? -i : i);\n } else {\n sz += serialize_universal_size_t<double>::value;\n }\n } break;\n case datum_t::R_OBJECT: {\n sz += datum_serialized_size(datum->as_object());\n } break;\n case datum_t::R_STR: {\n sz += datum_serialized_size(datum->as_str());\n } break;\n case datum_t::UNINITIALIZED: \/\/ fall through\n default:\n unreachable();\n }\n return sz;\n}\nvoid datum_serialize(write_message_t *wm, const counted_t<const datum_t> &datum) {\n r_sanity_check(datum.has());\n switch (datum->get_type()) {\n case datum_t::R_ARRAY: {\n datum_serialize(wm, datum_serialized_type_t::R_ARRAY);\n const std::vector<counted_t<const datum_t> > &value = datum->as_array();\n datum_serialize(wm, value);\n } break;\n case datum_t::R_BOOL: {\n datum_serialize(wm, datum_serialized_type_t::R_BOOL);\n bool value = datum->as_bool();\n serialize_universal(wm, value);\n } break;\n case datum_t::R_NULL: {\n datum_serialize(wm, datum_serialized_type_t::R_NULL);\n } break;\n case datum_t::R_NUM: {\n double value = datum->as_num();\n int64_t i;\n if (number_as_integer(value, &i)) {\n \/\/ We serialize the signed-zero double, -0.0, with INT_NEGATIVE.\n\n \/\/ so we can use `signbit` in a GCC 4.4.3-compatible way\n using namespace std; \/\/ NOLINT(build\/namespaces)\n if (signbit(value)) {\n datum_serialize(wm, datum_serialized_type_t::INT_NEGATIVE);\n serialize_varint_uint64(wm, -i);\n } else {\n datum_serialize(wm, datum_serialized_type_t::INT_POSITIVE);\n serialize_varint_uint64(wm, i);\n }\n } else {\n datum_serialize(wm, datum_serialized_type_t::DOUBLE);\n serialize_universal(wm, value);\n }\n } break;\n case datum_t::R_OBJECT: {\n datum_serialize(wm, datum_serialized_type_t::R_OBJECT);\n datum_serialize(wm, datum->as_object());\n } break;\n case datum_t::R_STR: {\n datum_serialize(wm, datum_serialized_type_t::R_STR);\n const wire_string_t &value = datum->as_str();\n datum_serialize(wm, value);\n } break;\n case datum_t::UNINITIALIZED: \/\/ fall through\n default:\n unreachable();\n }\n}\narchive_result_t datum_deserialize(read_stream_t *s, counted_t<const datum_t> *datum) {\n datum_serialized_type_t type;\n archive_result_t res = datum_deserialize(s, &type);\n if (bad(res)) {\n return res;\n }\n\n switch (type) {\n case datum_serialized_type_t::R_ARRAY: {\n std::vector<counted_t<const datum_t> > value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_BOOL: {\n bool value;\n res = deserialize_universal(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(datum_t::R_BOOL, value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_NULL: {\n datum->reset(new datum_t(datum_t::R_NULL));\n } break;\n case datum_serialized_type_t::DOUBLE: {\n double value;\n res = deserialize_universal(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::INT_NEGATIVE: \/\/ fall through\n case datum_serialized_type_t::INT_POSITIVE: {\n uint64_t unsigned_value;\n res = deserialize_varint_uint64(s, &unsigned_value);\n if (bad(res)) {\n return res;\n }\n if (unsigned_value > max_dbl_int) {\n return archive_result_t::RANGE_ERROR;\n }\n const double d = unsigned_value;\n double value;\n if (type == datum_serialized_type_t::INT_NEGATIVE) {\n \/\/ This might deserialize the signed-zero double, -0.0.\n value = -d;\n } else {\n value = d;\n }\n try {\n datum->reset(new datum_t(value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_OBJECT: {\n std::map<std::string, counted_t<const datum_t> > value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_STR: {\n scoped_ptr_t<wire_string_t> value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n rassert(value.has());\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n default:\n return archive_result_t::RANGE_ERROR;\n }\n\n return archive_result_t::SUCCESS;\n}\n\n\ntemplate <cluster_version_t W>\nvoid serialize(write_message_t *wm,\n const empty_ok_t<const counted_t<const datum_t> > &datum) {\n const counted_t<const datum_t> *pointer = datum.get();\n const bool has = pointer->has();\n serialize<W>(wm, has);\n if (has) {\n serialize<W>(wm, *pointer);\n }\n}\n\nINSTANTIATE_SERIALIZE_FOR_CLUSTER_AND_DISK(empty_ok_t<const counted_t<const datum_t> >);\n\ntemplate <cluster_version_t W>\narchive_result_t deserialize(read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum) {\n bool has;\n archive_result_t res = deserialize<W>(s, &has);\n if (bad(res)) {\n return res;\n }\n\n counted_t<const datum_t> *pointer = datum.get();\n\n if (!has) {\n pointer->reset();\n return archive_result_t::SUCCESS;\n } else {\n return deserialize<W>(s, pointer);\n }\n}\n\ntemplate archive_result_t deserialize<cluster_version_t::v1_13>(\n read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum);\ntemplate archive_result_t deserialize<cluster_version_t::v1_13_2_is_latest>(\n read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum);\n\n\n} \/\/ namespace ql\n<commit_msg>Add an include in serialize_datum.cc.<commit_after>#include \"rdb_protocol\/serialize_datum.hpp\"\n\n#include <cmath>\n#include <string>\n#include <vector>\n\n#include \"containers\/archive\/stl_types.hpp\"\n#include \"containers\/archive\/versioned.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n\nnamespace ql {\n\n\nenum class datum_serialized_type_t {\n R_ARRAY = 1,\n R_BOOL = 2,\n R_NULL = 3,\n DOUBLE = 4,\n R_OBJECT = 5,\n R_STR = 6,\n INT_NEGATIVE = 7,\n INT_POSITIVE = 8,\n};\n\nARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(datum_serialized_type_t, int8_t,\n datum_serialized_type_t::R_ARRAY,\n datum_serialized_type_t::INT_POSITIVE);\n\nvoid datum_serialize(write_message_t *wm, datum_serialized_type_t type) {\n serialize<cluster_version_t::LATEST_OVERALL>(wm, type);\n}\n\nMUST_USE archive_result_t datum_deserialize(read_stream_t *s,\n datum_serialized_type_t *type) {\n return deserialize<cluster_version_t::LATEST_OVERALL>(s, type);\n}\n\n\/\/ This looks like it duplicates code of other deserialization functions. It does.\n\/\/ Keeping this separate means that we don't have to worry about whether datum\n\/\/ serialization has changed from cluster version to cluster version.\n\n\/\/ Keep in sync with datum_serialize.\nsize_t datum_serialized_size(const std::vector<counted_t<const datum_t> > &v) {\n size_t ret = varint_uint64_serialized_size(v.size());\n for (auto it = v.begin(), e = v.end(); it != e; ++it) {\n ret += datum_serialized_size(*it);\n }\n return ret;\n}\n\n\n\/\/ Keep in sync with datum_serialized_size.\nvoid datum_serialize(write_message_t *wm,\n const std::vector<counted_t<const datum_t> > &v) {\n serialize_varint_uint64(wm, v.size());\n for (auto it = v.begin(), e = v.end(); it != e; ++it) {\n datum_serialize(wm, *it);\n }\n}\n\nMUST_USE archive_result_t\ndatum_deserialize(read_stream_t *s, std::vector<counted_t<const datum_t> > *v) {\n v->clear();\n\n uint64_t sz;\n archive_result_t res = deserialize_varint_uint64(s, &sz);\n if (bad(res)) { return res; }\n\n if (sz > std::numeric_limits<size_t>::max()) {\n return archive_result_t::RANGE_ERROR;\n }\n\n v->resize(sz);\n for (uint64_t i = 0; i < sz; ++i) {\n res = datum_deserialize(s, &(*v)[i]);\n if (bad(res)) { return res; }\n }\n\n return archive_result_t::SUCCESS;\n}\n\nsize_t datum_serialized_size(const std::string &s) {\n return serialize_universal_size(s);\n}\nvoid datum_serialize(write_message_t *wm, const std::string &s) {\n serialize_universal(wm, s);\n}\nMUST_USE archive_result_t datum_deserialize(read_stream_t *s, std::string *out) {\n return deserialize_universal(s, out);\n}\n\n\nsize_t datum_serialized_size(\n const std::map<std::string, counted_t<const datum_t> > &m) {\n size_t ret = varint_uint64_serialized_size(m.size());\n for (auto it = m.begin(), e = m.end(); it != e; ++it) {\n ret += datum_serialized_size(it->first);\n ret += datum_serialized_size(it->second);\n }\n return ret;\n}\n\nvoid datum_serialize(write_message_t *wm,\n const std::map<std::string, counted_t<const datum_t> > &m) {\n serialize_varint_uint64(wm, m.size());\n for (auto it = m.begin(), e = m.end(); it != e; ++it) {\n datum_serialize(wm, it->first);\n datum_serialize(wm, it->second);\n }\n}\n\nMUST_USE archive_result_t datum_deserialize(\n read_stream_t *s,\n std::map<std::string, counted_t<const datum_t> > *m) {\n m->clear();\n\n uint64_t sz;\n archive_result_t res = deserialize_varint_uint64(s, &sz);\n if (bad(res)) { return res; }\n\n if (sz > std::numeric_limits<size_t>::max()) {\n return archive_result_t::RANGE_ERROR;\n }\n\n \/\/ Using position should make this function take linear time, not\n \/\/ sz*log(sz) time.\n auto position = m->begin();\n\n for (uint64_t i = 0; i < sz; ++i) {\n std::pair<std::string, counted_t<const datum_t> > p;\n res = datum_deserialize(s, &p.first);\n if (bad(res)) { return res; }\n res = datum_deserialize(s, &p.second);\n if (bad(res)) { return res; }\n position = m->insert(position, std::move(p));\n }\n\n return archive_result_t::SUCCESS;\n}\n\n\n\n\nsize_t datum_serialized_size(const counted_t<const datum_t> &datum) {\n r_sanity_check(datum.has());\n size_t sz = 1; \/\/ 1 byte for the type\n switch (datum->get_type()) {\n case datum_t::R_ARRAY: {\n sz += datum_serialized_size(datum->as_array());\n } break;\n case datum_t::R_BOOL: {\n sz += serialize_universal_size_t<bool>::value;\n } break;\n case datum_t::R_NULL: break;\n case datum_t::R_NUM: {\n double d = datum->as_num();\n int64_t i;\n if (number_as_integer(d, &i)) {\n sz += varint_uint64_serialized_size(i < 0 ? -i : i);\n } else {\n sz += serialize_universal_size_t<double>::value;\n }\n } break;\n case datum_t::R_OBJECT: {\n sz += datum_serialized_size(datum->as_object());\n } break;\n case datum_t::R_STR: {\n sz += datum_serialized_size(datum->as_str());\n } break;\n case datum_t::UNINITIALIZED: \/\/ fall through\n default:\n unreachable();\n }\n return sz;\n}\nvoid datum_serialize(write_message_t *wm, const counted_t<const datum_t> &datum) {\n r_sanity_check(datum.has());\n switch (datum->get_type()) {\n case datum_t::R_ARRAY: {\n datum_serialize(wm, datum_serialized_type_t::R_ARRAY);\n const std::vector<counted_t<const datum_t> > &value = datum->as_array();\n datum_serialize(wm, value);\n } break;\n case datum_t::R_BOOL: {\n datum_serialize(wm, datum_serialized_type_t::R_BOOL);\n bool value = datum->as_bool();\n serialize_universal(wm, value);\n } break;\n case datum_t::R_NULL: {\n datum_serialize(wm, datum_serialized_type_t::R_NULL);\n } break;\n case datum_t::R_NUM: {\n double value = datum->as_num();\n int64_t i;\n if (number_as_integer(value, &i)) {\n \/\/ We serialize the signed-zero double, -0.0, with INT_NEGATIVE.\n\n \/\/ so we can use `signbit` in a GCC 4.4.3-compatible way\n using namespace std; \/\/ NOLINT(build\/namespaces)\n if (signbit(value)) {\n datum_serialize(wm, datum_serialized_type_t::INT_NEGATIVE);\n serialize_varint_uint64(wm, -i);\n } else {\n datum_serialize(wm, datum_serialized_type_t::INT_POSITIVE);\n serialize_varint_uint64(wm, i);\n }\n } else {\n datum_serialize(wm, datum_serialized_type_t::DOUBLE);\n serialize_universal(wm, value);\n }\n } break;\n case datum_t::R_OBJECT: {\n datum_serialize(wm, datum_serialized_type_t::R_OBJECT);\n datum_serialize(wm, datum->as_object());\n } break;\n case datum_t::R_STR: {\n datum_serialize(wm, datum_serialized_type_t::R_STR);\n const wire_string_t &value = datum->as_str();\n datum_serialize(wm, value);\n } break;\n case datum_t::UNINITIALIZED: \/\/ fall through\n default:\n unreachable();\n }\n}\narchive_result_t datum_deserialize(read_stream_t *s, counted_t<const datum_t> *datum) {\n datum_serialized_type_t type;\n archive_result_t res = datum_deserialize(s, &type);\n if (bad(res)) {\n return res;\n }\n\n switch (type) {\n case datum_serialized_type_t::R_ARRAY: {\n std::vector<counted_t<const datum_t> > value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_BOOL: {\n bool value;\n res = deserialize_universal(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(datum_t::R_BOOL, value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_NULL: {\n datum->reset(new datum_t(datum_t::R_NULL));\n } break;\n case datum_serialized_type_t::DOUBLE: {\n double value;\n res = deserialize_universal(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::INT_NEGATIVE: \/\/ fall through\n case datum_serialized_type_t::INT_POSITIVE: {\n uint64_t unsigned_value;\n res = deserialize_varint_uint64(s, &unsigned_value);\n if (bad(res)) {\n return res;\n }\n if (unsigned_value > max_dbl_int) {\n return archive_result_t::RANGE_ERROR;\n }\n const double d = unsigned_value;\n double value;\n if (type == datum_serialized_type_t::INT_NEGATIVE) {\n \/\/ This might deserialize the signed-zero double, -0.0.\n value = -d;\n } else {\n value = d;\n }\n try {\n datum->reset(new datum_t(value));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_OBJECT: {\n std::map<std::string, counted_t<const datum_t> > value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n case datum_serialized_type_t::R_STR: {\n scoped_ptr_t<wire_string_t> value;\n res = datum_deserialize(s, &value);\n if (bad(res)) {\n return res;\n }\n rassert(value.has());\n try {\n datum->reset(new datum_t(std::move(value)));\n } catch (const base_exc_t &) {\n return archive_result_t::RANGE_ERROR;\n }\n } break;\n default:\n return archive_result_t::RANGE_ERROR;\n }\n\n return archive_result_t::SUCCESS;\n}\n\n\ntemplate <cluster_version_t W>\nvoid serialize(write_message_t *wm,\n const empty_ok_t<const counted_t<const datum_t> > &datum) {\n const counted_t<const datum_t> *pointer = datum.get();\n const bool has = pointer->has();\n serialize<W>(wm, has);\n if (has) {\n serialize<W>(wm, *pointer);\n }\n}\n\nINSTANTIATE_SERIALIZE_FOR_CLUSTER_AND_DISK(empty_ok_t<const counted_t<const datum_t> >);\n\ntemplate <cluster_version_t W>\narchive_result_t deserialize(read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum) {\n bool has;\n archive_result_t res = deserialize<W>(s, &has);\n if (bad(res)) {\n return res;\n }\n\n counted_t<const datum_t> *pointer = datum.get();\n\n if (!has) {\n pointer->reset();\n return archive_result_t::SUCCESS;\n } else {\n return deserialize<W>(s, pointer);\n }\n}\n\ntemplate archive_result_t deserialize<cluster_version_t::v1_13>(\n read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum);\ntemplate archive_result_t deserialize<cluster_version_t::v1_13_2_is_latest>(\n read_stream_t *s,\n empty_ok_ref_t<counted_t<const datum_t> > datum);\n\n\n} \/\/ namespace ql\n<|endoftext|>"} {"text":"<commit_before>\/\/ This code is part of the project \"Ligra: A Lightweight Graph Processing\n\/\/ Framework for Shared Memory\", presented at Principles and Practice of \n\/\/ Parallel Programming, 2013.\n\/\/ Copyright (c) 2013 Julian Shun and Guy Blelloch\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights (to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n\/\/ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\/\/ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n\/\/ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#include \"ligra.h\"\n\nstruct BFS_F {\n uintE* Parents;\n BFS_F(uintE* _Parents) : Parents(_Parents) {}\n inline bool update (uintE s, uintE d) { \/\/Update\n if(Parents[d] == UINT_E_MAX) { Parents[d] = s; return 1; }\n else return 0;\n }\n inline bool updateAtomic (uintE s, uintE d){ \/\/atomic version of Update\n return (CAS(&Parents[d],UINT_E_MAX,s));\n }\n \/\/cond function checks if vertex has been visited yet\n inline bool cond (uintE d) { return (Parents[d] == UINT_E_MAX); } \n};\n\ntemplate <class vertex>\nvoid Compute(graph<vertex>& GA, commandLine P) {\n long start = P.getOptionLongValue(\"-r\",0);\n long n = GA.n;\n \/\/creates Parents array, initialized to all -1, except for start\n uintE* Parents = newA(uintE,n);\n parallel_for(long i=0;i<n;i++) Parents[i] = UINT_E_MAX;\n Parents[start] = start;\n vertexSubset Frontier(n,start); \/\/creates initial frontier\n while(!Frontier.isEmpty()){ \/\/loop until frontier is empty\n vertexSubset output = edgeMap(GA, Frontier, BFS_F(Parents)); \n Frontier.del();\n Frontier = output; \/\/set new frontier\n } \n Frontier.del();\n free(Parents); \n}\n<commit_msg>[trace] apps: BFS: trace partens property access<commit_after>\/\/ This code is part of the project \"Ligra: A Lightweight Graph Processing\n\/\/ Framework for Shared Memory\", presented at Principles and Practice of \n\/\/ Parallel Programming, 2013.\n\/\/ Copyright (c) 2013 Julian Shun and Guy Blelloch\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights (to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n\/\/ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\/\/ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n\/\/ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#include \"ligra.h\"\n\nstruct BFS_F {\n uintE* Parents;\n BFS_F(uintE* _Parents) : Parents(_Parents) {}\n inline bool update (uintE s, uintE d) { \/\/Update\n TRACE_PROP_READ(d);\n if(Parents[d] == UINT_E_MAX) { TRACE_PROP_WRITE(d); Parents[d] = s; return 1; }\n else return 0;\n }\n inline bool updateAtomic (uintE s, uintE d){ \/\/atomic version of Update\n TRACE_PROP_RW(d);\n return (CAS(&Parents[d],UINT_E_MAX,s));\n }\n \/\/cond function checks if vertex has been visited yet\n inline bool cond (uintE d) { TRACE_PROP_READ(d); return (Parents[d] == UINT_E_MAX); }\n};\n\ntemplate <class vertex>\nvoid Compute(graph<vertex>& GA, commandLine P) {\n long start = P.getOptionLongValue(\"-r\",0);\n long n = GA.n;\n \/\/creates Parents array, initialized to all -1, except for start\n uintE* Parents = newA(uintE,n);\n parallel_for(long i=0;i<n;i++) {TRACE_PROP_WRITE(i); Parents[i] = UINT_E_MAX; }\n Parents[start] = start; TRACE_PROP_WRITE(start);\n vertexSubset Frontier(n,start); \/\/creates initial frontier\n while(!Frontier.isEmpty()){ \/\/loop until frontier is empty\n vertexSubset output = edgeMap(GA, Frontier, BFS_F(Parents)); \n Frontier.del();\n Frontier = output; \/\/set new frontier\n } \n Frontier.del();\n free(Parents); \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ See LICENSE file for copyright and license details.\n\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n#include <cassert>\n#include <ctime>\n#include \"core\/core.h\"\n\nCore::Core()\n : mPathfinder(*this)\n{\n}\n\nCore::~Core() {\n}\n\nconst std::list<Player*>& Core::players() {\n return mPlayers;\n}\n\nconst Event& Core::currentEvent() {\n return *mCurrentEvent;\n}\n\nconst Player& Core::currentPlayer() {\n return *mCurrentPlayer;\n}\n\nUnit* Core::selectedUnit() {\n return mSelectedUnit;\n}\n\nstd::list<Unit*>& Core::units() {\n return mUnits;\n}\n\nPathfinder& Core::pathfinder() {\n return mPathfinder;\n}\n\nvoid Core::setSelectedUnit(Unit* unit) {\n mSelectedUnit = unit;\n}\n\nvoid Core::setCurrentEvent(Event* event) {\n mCurrentEvent = event;\n}\n\nvoid Core::setCurrentPlayer(Player* player) {\n mCurrentPlayer = player;\n}\n \nvoid Core::createLocalHuman(int id) {\n auto p = new Player;\n mPlayers.push_back(p);\n p->id = id;\n p->lastSeenEventID = HAVE_NOT_SEEN_ANY_EVENTS;\n}\n\nvoid Core::initLocalPlayers(std::vector<int> unitIDs) {\n for (int id : unitIDs) {\n createLocalHuman(id);\n }\n mCurrentPlayer = mPlayers.back();\n}\n\nbool Core::inboard(const V2i& p) const {\n return p.x() >= 0 && p.y() >= 0\n && p.x() < MAP_X && p.y() < MAP_Y;\n}\n\nTile& Core::tile(const V2i& p) {\n assert(inboard(p));\n return mMap[p.y()][p.x()];\n}\n\nV2i Core::incV2i(const V2i& pos) const {\n assert(inboard(pos));\n V2i newPos = pos;\n newPos.setX(pos.x() + 1);\n if (newPos.x() == MAP_X) {\n newPos.setX(0);\n newPos.setY(newPos.y() + 1);\n }\n return newPos;\n}\n\nint Core::getNewEventID() {\n if (!mEvents.empty()) {\n return mEvents.back()->id + 1;\n } else {\n return 0;\n }\n}\n\nvoid Core::refreshUnits(int playerID) {\n for (auto u : units()) {\n if (u->playerID == playerID) {\n u->actionPoints = getUnitType(u->typeID).actionPoints;\n }\n }\n}\n\n\/\/ Undo all events that this player have not seen yet\nvoid Core::undoUnshownEvents() {\n if (mEvents.size() == 0) {\n return;\n }\n auto i = mEvents.end();\n --i;\n while (i != mEvents.begin()) {\n auto event = *i;\n if (event->id == mCurrentPlayer->lastSeenEventID) {\n break;\n }\n undoEvent(*event);\n --i;\n }\n}\n\nvoid Core::applyEvent(const Event& e) {\n mCurrentPlayer->lastSeenEventID = e.id;\n switch (e.t) {\n case EventTypeID::MOVE:\n applyEventMove(*this, e.e.move);\n break;\n case EventTypeID::END_TURN:\n applyEventEndTurn(*this, e.e.endTurn);\n break;\n default:\n die(\"event: applyEvent(): \"\n \"unknown event '%d'\\n\", e.t);\n break;\n }\n \/\/ updateUnitsVisibility();\n}\n\n\nbool Core::isEventVisible(const Event& e) const {\n switch (e.t) {\n case EventTypeID::MOVE:\n return isVisibleEventMove(*this, e.e.move);\n case EventTypeID::END_TURN:\n return true;\n default:\n die(\"event: isEventVisible(): \"\n \"unknown event '%d'\\n\", e.t);\n return true;\n }\n}\n\n\/\/ TODO simplify\nvoid Core::applyInvisibleEvents() {\n Event* e = getNextEventNode();\n while (e) {\n assert(e);\n if (!isEventVisible(*e)) {\n applyEvent(*e);\n } else {\n break;\n }\n e = getNext(mEvents, e);\n assert(e);\n }\n}\n\n\/\/ TODO: Called before getNextEvent\nbool Core::unshownEventsLeft() {\n applyInvisibleEvents();\n if (mEvents.size() == 0) {\n return false;\n } else {\n auto e = mEvents.back();\n return e->id != mCurrentPlayer->lastSeenEventID;\n }\n}\n\n\/\/ Always called after applyInvisibleEvents\nEvent* Core::getNextEvent() {\n int id = mCurrentPlayer->lastSeenEventID; \/\/ shortcut\n assert(mEvents.size() > 0);\n if (id == HAVE_NOT_SEEN_ANY_EVENTS) {\n return mEvents.front();\n }\n for (auto e : mEvents) {\n if (e->id == id) {\n return getNext(mEvents, e);\n }\n }\n return nullptr;\n}\n\nvoid Core::addEvent(Event* e) {\n assert(e);\n e->id = getNewEventID();\n mEvents.push_back(e);\n \/\/ event2log(*e);\n#if 0\n \/\/ TODO\n if (!isLocal) {\n sendEvent(e);\n }\n#else\n \/\/ UNUSED(sendEvent);\n#endif\n}\n\nbool Core::isLosClear(const V2i& from, const V2i& to) {\n Los los(from, to);\n for (V2i p = los.getNext(); !los.isFinished(); p = los.getNext()) {\n if (unitAt(p) || tile(p).obstacle) {\n return false;\n }\n }\n return true;\n}\n\n#define FOR_EACH_TILE(p) \\\n for (p = V2i(0, 0); inboard(p); p = incV2i(p))\n\nvoid Core::cleanFow() {\n V2i p;\n FOR_EACH_TILE(p) {\n tile(p).fow = 0;\n }\n}\n\nvoid Core::calculateFow() {\n assert(mCurrentPlayer);\n cleanFow();\n V2i p;\n FOR_EACH_TILE(p) {\n for (auto u : mUnits) {\n int maxDist = getUnitType(u->typeID).rangeOfVision;\n bool isPlayerOk = (u->playerID == mCurrentPlayer->id);\n bool isDistanceOk = (p.distance(u->pos) < maxDist);\n bool isLosOk = isLosClear(p, u->pos);\n if (isPlayerOk && isDistanceOk && isLosOk) {\n tile(p).fow++;\n }\n }\n }\n}\n\nUnit* Core::unitAt(const V2i& pos) {\n for (auto u : mUnits) {\n if (u->pos == pos) {\n return u;\n }\n }\n return nullptr;\n}\n\nUnit* Core::id2unit(int id) {\n for (auto u : mUnits) {\n if (u->id == id) {\n return u;\n }\n }\n return nullptr;\n}\n\nint Core::getNewUnitID() {\n if (mUnits.size() > 0) {\n auto lastUnit = mUnits.back();\n return lastUnit->id + 1;\n } else {\n return 0;\n }\n}\n\nvoid Core::addUnit(const V2i& p, int playerID) {\n auto u = new Unit;\n assert(inboard(p));\n assert(playerID >= 0 && playerID < 16);\n u->id = getNewUnitID();\n u->pos = p;\n u->playerID = playerID;\n u->dir = static_cast<Dir>(rnd(0, 7));\n u->typeID = rnd(0, (int)UnitTypeID::COUNT - 1);\n u->actionPoints = getUnitType(u->typeID).actionPoints;\n mUnits.push_back(u);\n calculateFow();\n#if 0\n buildFowArray(&vaFogOfWar);\n#endif\n}\n\nvoid Core::killUnit(Unit* u) {\n \/\/ deleteNode(&units, data2node(units, u));\n mUnits.remove(u);\n delete u;\n if (mSelectedUnit) {\n mPathfinder.fillMap(*mSelectedUnit);\n calculateFow();\n#if 0\n buildWalkableArray(&vaWalkableMap);\n buildFowArray(&vaFogOfWar);\n#endif\n }\n}\n\nvoid Core::shoot(Unit *shooter, Unit *target) {\n if (isLosClear(shooter->pos, target->pos)) {\n killUnit(target);\n }\n}\n\nvoid Core::initUnits() {\n mSelectedUnit = nullptr;\n for (int i = 0; i < 8; i++) {\n V2i p = V2i(rnd(0, MAP_X - 1), rnd(0, MAP_Y - 1));\n if (!tile(p).obstacle && !unitAt(p)) {\n addUnit(p, rnd(0, 1));\n } else {\n i--;\n }\n }\n}\n\nvoid Core::initObstacles() {\n V2i p;\n FOR_EACH_TILE(p) {\n tile(p).obstacle = ((rand() % 100) > 85);\n }\n}\n\nvoid Core::initPlayers() {\n initLocalPlayers({0, 1});\n}\n\nvoid Core::initLogic() {\n srand(time(nullptr));\n initUnitTypes();\n mPathfinder.cleanMap();\n cleanFow();\n initPlayers();\n initObstacles();\n initUnits();\n calculateFow();\n}\n\nvoid Core::undoEvent(const Event& e) {\n switch (e.t) {\n case EventTypeID::MOVE:\n undoEventMove(*this, e.e.move);\n break;\n case EventTypeID::END_TURN:\n \/\/ empty\n \/\/ TODO: die()?\n break;\n default:\n die(\"event: undoEvent(): \"\n \"unknown event type '%d'\\n\", e.t);\n break;\n }\n \/\/ updateUnitsVisibility();\n}\n\n\/\/ TODO: rename.\nEvent* Core::getNextEventNode() {\n \/\/ Node *node;\n int id = mCurrentPlayer->lastSeenEventID; \/\/ shortcut\n if (mEvents.size() == 0) {\n return nullptr;\n }\n if (id == HAVE_NOT_SEEN_ANY_EVENTS) {\n return mEvents.front();\n }\n \/\/ find last seen event\n Event *e = nullptr;\n for (auto e : mEvents) {\n if (e->id == id) {\n break;\n }\n }\n if (!e) {\n return nullptr;\n } else {\n return getNext(mEvents, e);\n }\n}\n\nvoid Core::event2log(const Event& e) {\n UNUSED(e);\n \/\/ TODO\n}\n\nvoid Core::sendEvent(const Event& e) {\n UNUSED(e);\n \/\/ TODO\n}\n<commit_msg>Fixed initial unit rotation<commit_after>\/\/ See LICENSE file for copyright and license details.\n\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n#include <cassert>\n#include <ctime>\n#include \"core\/core.h\"\n\nCore::Core()\n : mPathfinder(*this)\n{\n}\n\nCore::~Core() {\n}\n\nconst std::list<Player*>& Core::players() {\n return mPlayers;\n}\n\nconst Event& Core::currentEvent() {\n return *mCurrentEvent;\n}\n\nconst Player& Core::currentPlayer() {\n return *mCurrentPlayer;\n}\n\nUnit* Core::selectedUnit() {\n return mSelectedUnit;\n}\n\nstd::list<Unit*>& Core::units() {\n return mUnits;\n}\n\nPathfinder& Core::pathfinder() {\n return mPathfinder;\n}\n\nvoid Core::setSelectedUnit(Unit* unit) {\n mSelectedUnit = unit;\n}\n\nvoid Core::setCurrentEvent(Event* event) {\n mCurrentEvent = event;\n}\n\nvoid Core::setCurrentPlayer(Player* player) {\n mCurrentPlayer = player;\n}\n \nvoid Core::createLocalHuman(int id) {\n auto p = new Player;\n mPlayers.push_back(p);\n p->id = id;\n p->lastSeenEventID = HAVE_NOT_SEEN_ANY_EVENTS;\n}\n\nvoid Core::initLocalPlayers(std::vector<int> unitIDs) {\n for (int id : unitIDs) {\n createLocalHuman(id);\n }\n mCurrentPlayer = mPlayers.back();\n}\n\nbool Core::inboard(const V2i& p) const {\n return p.x() >= 0 && p.y() >= 0\n && p.x() < MAP_X && p.y() < MAP_Y;\n}\n\nTile& Core::tile(const V2i& p) {\n assert(inboard(p));\n return mMap[p.y()][p.x()];\n}\n\nV2i Core::incV2i(const V2i& pos) const {\n assert(inboard(pos));\n V2i newPos = pos;\n newPos.setX(pos.x() + 1);\n if (newPos.x() == MAP_X) {\n newPos.setX(0);\n newPos.setY(newPos.y() + 1);\n }\n return newPos;\n}\n\nint Core::getNewEventID() {\n if (!mEvents.empty()) {\n return mEvents.back()->id + 1;\n } else {\n return 0;\n }\n}\n\nvoid Core::refreshUnits(int playerID) {\n for (auto u : units()) {\n if (u->playerID == playerID) {\n u->actionPoints = getUnitType(u->typeID).actionPoints;\n }\n }\n}\n\n\/\/ Undo all events that this player have not seen yet\nvoid Core::undoUnshownEvents() {\n if (mEvents.size() == 0) {\n return;\n }\n auto i = mEvents.end();\n --i;\n while (i != mEvents.begin()) {\n auto event = *i;\n if (event->id == mCurrentPlayer->lastSeenEventID) {\n break;\n }\n undoEvent(*event);\n --i;\n }\n}\n\nvoid Core::applyEvent(const Event& e) {\n mCurrentPlayer->lastSeenEventID = e.id;\n switch (e.t) {\n case EventTypeID::MOVE:\n applyEventMove(*this, e.e.move);\n break;\n case EventTypeID::END_TURN:\n applyEventEndTurn(*this, e.e.endTurn);\n break;\n default:\n die(\"event: applyEvent(): \"\n \"unknown event '%d'\\n\", e.t);\n break;\n }\n \/\/ updateUnitsVisibility();\n}\n\n\nbool Core::isEventVisible(const Event& e) const {\n switch (e.t) {\n case EventTypeID::MOVE:\n return isVisibleEventMove(*this, e.e.move);\n case EventTypeID::END_TURN:\n return true;\n default:\n die(\"event: isEventVisible(): \"\n \"unknown event '%d'\\n\", e.t);\n return true;\n }\n}\n\n\/\/ TODO simplify\nvoid Core::applyInvisibleEvents() {\n Event* e = getNextEventNode();\n while (e) {\n assert(e);\n if (!isEventVisible(*e)) {\n applyEvent(*e);\n } else {\n break;\n }\n e = getNext(mEvents, e);\n assert(e);\n }\n}\n\n\/\/ TODO: Called before getNextEvent\nbool Core::unshownEventsLeft() {\n applyInvisibleEvents();\n if (mEvents.size() == 0) {\n return false;\n } else {\n auto e = mEvents.back();\n return e->id != mCurrentPlayer->lastSeenEventID;\n }\n}\n\n\/\/ Always called after applyInvisibleEvents\nEvent* Core::getNextEvent() {\n int id = mCurrentPlayer->lastSeenEventID; \/\/ shortcut\n assert(mEvents.size() > 0);\n if (id == HAVE_NOT_SEEN_ANY_EVENTS) {\n return mEvents.front();\n }\n for (auto e : mEvents) {\n if (e->id == id) {\n return getNext(mEvents, e);\n }\n }\n return nullptr;\n}\n\nvoid Core::addEvent(Event* e) {\n assert(e);\n e->id = getNewEventID();\n mEvents.push_back(e);\n \/\/ event2log(*e);\n#if 0\n \/\/ TODO\n if (!isLocal) {\n sendEvent(e);\n }\n#else\n \/\/ UNUSED(sendEvent);\n#endif\n}\n\nbool Core::isLosClear(const V2i& from, const V2i& to) {\n Los los(from, to);\n for (V2i p = los.getNext(); !los.isFinished(); p = los.getNext()) {\n if (unitAt(p) || tile(p).obstacle) {\n return false;\n }\n }\n return true;\n}\n\n#define FOR_EACH_TILE(p) \\\n for (p = V2i(0, 0); inboard(p); p = incV2i(p))\n\nvoid Core::cleanFow() {\n V2i p;\n FOR_EACH_TILE(p) {\n tile(p).fow = 0;\n }\n}\n\nvoid Core::calculateFow() {\n assert(mCurrentPlayer);\n cleanFow();\n V2i p;\n FOR_EACH_TILE(p) {\n for (auto u : mUnits) {\n int maxDist = getUnitType(u->typeID).rangeOfVision;\n bool isPlayerOk = (u->playerID == mCurrentPlayer->id);\n bool isDistanceOk = (p.distance(u->pos) < maxDist);\n bool isLosOk = isLosClear(p, u->pos);\n if (isPlayerOk && isDistanceOk && isLosOk) {\n tile(p).fow++;\n }\n }\n }\n}\n\nUnit* Core::unitAt(const V2i& pos) {\n for (auto u : mUnits) {\n if (u->pos == pos) {\n return u;\n }\n }\n return nullptr;\n}\n\nUnit* Core::id2unit(int id) {\n for (auto u : mUnits) {\n if (u->id == id) {\n return u;\n }\n }\n return nullptr;\n}\n\nint Core::getNewUnitID() {\n if (mUnits.size() > 0) {\n auto lastUnit = mUnits.back();\n return lastUnit->id + 1;\n } else {\n return 0;\n }\n}\n\nvoid Core::addUnit(const V2i& p, int playerID) {\n auto u = new Unit;\n assert(inboard(p));\n assert(playerID >= 0 && playerID < 16);\n u->id = getNewUnitID();\n u->pos = p;\n u->playerID = playerID;\n u->dir = static_cast<Dir>(rnd(0, 6 - 1));\n u->typeID = rnd(0, (int)UnitTypeID::COUNT - 1);\n u->actionPoints = getUnitType(u->typeID).actionPoints;\n mUnits.push_back(u);\n calculateFow();\n#if 0\n buildFowArray(&vaFogOfWar);\n#endif\n}\n\nvoid Core::killUnit(Unit* u) {\n \/\/ deleteNode(&units, data2node(units, u));\n mUnits.remove(u);\n delete u;\n if (mSelectedUnit) {\n mPathfinder.fillMap(*mSelectedUnit);\n calculateFow();\n#if 0\n buildWalkableArray(&vaWalkableMap);\n buildFowArray(&vaFogOfWar);\n#endif\n }\n}\n\nvoid Core::shoot(Unit *shooter, Unit *target) {\n if (isLosClear(shooter->pos, target->pos)) {\n killUnit(target);\n }\n}\n\nvoid Core::initUnits() {\n mSelectedUnit = nullptr;\n for (int i = 0; i < 8; i++) {\n V2i p = V2i(rnd(0, MAP_X - 1), rnd(0, MAP_Y - 1));\n if (!tile(p).obstacle && !unitAt(p)) {\n addUnit(p, rnd(0, 1));\n } else {\n i--;\n }\n }\n}\n\nvoid Core::initObstacles() {\n V2i p;\n FOR_EACH_TILE(p) {\n tile(p).obstacle = ((rand() % 100) > 85);\n }\n}\n\nvoid Core::initPlayers() {\n initLocalPlayers({0, 1});\n}\n\nvoid Core::initLogic() {\n srand(time(nullptr));\n initUnitTypes();\n mPathfinder.cleanMap();\n cleanFow();\n initPlayers();\n initObstacles();\n initUnits();\n calculateFow();\n}\n\nvoid Core::undoEvent(const Event& e) {\n switch (e.t) {\n case EventTypeID::MOVE:\n undoEventMove(*this, e.e.move);\n break;\n case EventTypeID::END_TURN:\n \/\/ empty\n \/\/ TODO: die()?\n break;\n default:\n die(\"event: undoEvent(): \"\n \"unknown event type '%d'\\n\", e.t);\n break;\n }\n \/\/ updateUnitsVisibility();\n}\n\n\/\/ TODO: rename.\nEvent* Core::getNextEventNode() {\n \/\/ Node *node;\n int id = mCurrentPlayer->lastSeenEventID; \/\/ shortcut\n if (mEvents.size() == 0) {\n return nullptr;\n }\n if (id == HAVE_NOT_SEEN_ANY_EVENTS) {\n return mEvents.front();\n }\n \/\/ find last seen event\n Event *e = nullptr;\n for (auto e : mEvents) {\n if (e->id == id) {\n break;\n }\n }\n if (!e) {\n return nullptr;\n } else {\n return getNext(mEvents, e);\n }\n}\n\nvoid Core::event2log(const Event& e) {\n UNUSED(e);\n \/\/ TODO\n}\n\nvoid Core::sendEvent(const Event& e) {\n UNUSED(e);\n \/\/ TODO\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/image.h\"\n\n#include <iostream>\n\n#include \"core\/assert.h\"\n#include \"core\/numeric.h\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#define STBI_FAILURE_USERMSG\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image.h\"\n#include \"stb_image_write.h\"\n\n#include \"core\/log.h\"\n#include \"core\/decompress.h\"\n\nnamespace euphoria::core\n{\n LOG_SPECIFY_DEFAULT_LOGGER(\"core.image\")\n\n void\n Image::MakeInvalid()\n {\n components.resize(0);\n width_ = 0;\n height_ = 0;\n has_alpha_ = false;\n\n ASSERT(!IsValid());\n }\n\n int\n Image::GetPixelByteSize() const\n {\n return has_alpha_ ? 4 : 3;\n }\n\n void\n Image::SetupWithAlphaSupport(\n int image_width,\n int image_height,\n int default_value)\n {\n Setup(image_width, image_height, true, default_value);\n }\n\n void\n Image::SetupNoAlphaSupport(\n int image_width,\n int image_height,\n int default_value)\n {\n Setup(image_width, image_height, false, default_value);\n }\n\n void\n Image::Setup(\n int image_width,\n int image_height,\n bool alpha,\n int default_value)\n {\n ASSERTX(image_width > 0, image_width);\n ASSERTX(image_height > 0, image_height);\n\n width_ = image_width;\n height_ = image_height;\n has_alpha_ = alpha;\n\n components.resize(0); \/\/ clear all pixels\n const unsigned int size = width_ * height_ * GetPixelByteSize();\n if(default_value < 0)\n {\n components.resize(size);\n }\n else\n {\n ASSERT(default_value <= 255);\n components.resize(size, static_cast<unsigned char>(default_value));\n }\n\n ASSERT(IsValid());\n }\n\n int\n Image::GetPixelIndex(int x, int y) const\n {\n ASSERT(x >= 0 && x < width_);\n ASSERT(y >= 0 && y < height_);\n\n return (y * width_ + x) * GetPixelByteSize();\n }\n\n void\n Image::SetPixel(int x, int y, const Rgbai& color)\n {\n SetPixel(x, y, color.r, color.g, color.b, color.a);\n }\n\n void\n Image::SetPixel(\n int x,\n int y,\n unsigned char r,\n unsigned char g,\n unsigned char b,\n unsigned char a)\n {\n ASSERTX(IsWithinInclusivei(0, x, GetWidth() - 1), x, GetWidth() - 1);\n ASSERTX(IsWithinInclusivei(0, y, GetHeight() - 1), y, GetHeight() - 1);\n\n const auto base_index = GetPixelIndex(x, y);\n components[base_index + 0] = r;\n components[base_index + 1] = g;\n components[base_index + 2] = b;\n\n if(has_alpha_)\n {\n components[base_index + 3] = a;\n }\n }\n\n Rgbai\n Image::GetPixel(int x, int y) const\n {\n ASSERT(IsWithinInclusivei(0, x, GetWidth() - 1));\n ASSERT(IsWithinInclusivei(0, y, GetHeight() - 1));\n\n const auto base_index = GetPixelIndex(x, y);\n\n const auto red = components[base_index + 0];\n const auto green = components[base_index + 1];\n const auto blue = components[base_index + 2];\n\n if(has_alpha_)\n {\n const auto alpha = components[base_index + 3];\n return Rgbai {Rgbi {red, green, blue}, alpha};\n }\n else\n {\n return Rgbi {red, green, blue};\n }\n }\n\n bool\n Image::IsValid() const\n {\n return width_ > 0 && height_ > 0;\n }\n\n int\n Image::GetWidth() const\n {\n return width_;\n }\n\n int\n Image::GetHeight() const\n {\n return height_;\n }\n\n bool\n Image::HasAlpha() const\n {\n return has_alpha_;\n }\n\n const unsigned char*\n Image::GetPixelData() const\n {\n return &components[0];\n }\n\n namespace \/\/ local\n {\n void\n DetermineImageSize(void* context, void* \/*unused*\/, int size)\n {\n ASSERT(size >= 0);\n auto* total_size = static_cast<int*>(context);\n *total_size += size;\n }\n\n void\n WriteToMemoryChunkFile(void* context, void* data, int size)\n {\n ASSERT(size >= 0);\n auto* file = static_cast<MemoryChunkFile*>(context);\n file->Write(data, size);\n }\n } \/\/ namespace\n\n int\n WriteImageData(\n stbi_write_func* func,\n void* context,\n int w,\n int h,\n int comp,\n const void* data,\n ImageWriteFormat format,\n int jpeg_quality)\n {\n switch(format)\n {\n case ImageWriteFormat::PNG:\n return stbi_write_png_to_func(func, context, w, h, comp, data, 0);\n case ImageWriteFormat::BMP:\n return stbi_write_bmp_to_func(func, context, w, h, comp, data);\n case ImageWriteFormat::TGA:\n return stbi_write_tga_to_func(func, context, w, h, comp, data);\n case ImageWriteFormat::JPEG:\n return stbi_write_jpg_to_func(\n func, context, w, h, comp, data, jpeg_quality);\n default: DIE(\"Unhandled case\"); return 0;\n }\n }\n\n std::shared_ptr<MemoryChunk>\n Image::Write(ImageWriteFormat format, int jpeg_quality) const\n {\n const int number_of_components = has_alpha_ ? 4 : 3;\n\n std::vector<unsigned char> pixels(\n width_ * height_ * number_of_components, 0);\n for(int y = 0; y < height_; y += 1)\n {\n const int iy = height_ - (y + 1);\n\n ASSERTX(IsWithinInclusivei(0, iy, height_ - 1), iy, y, height_);\n for(int x = 0; x < width_; x += 1)\n {\n const int target_index\n = (x + width_ * y) * number_of_components;\n const int source_index\n = (x + width_ * iy) * number_of_components;\n for(int component = 0; component < number_of_components;\n component += 1)\n {\n pixels[target_index + component]\n = components[source_index + component];\n }\n }\n }\n\n int size = 0;\n int size_result = WriteImageData(\n DetermineImageSize,\n &size,\n GetWidth(),\n GetHeight(),\n number_of_components,\n &pixels[0],\n format,\n jpeg_quality);\n if(size_result == 0)\n {\n return MemoryChunk::Null();\n }\n\n ASSERT(size > 0);\n MemoryChunkFile file {MemoryChunk::Alloc(size)};\n int write_result = WriteImageData(\n WriteToMemoryChunkFile,\n &file,\n GetWidth(),\n GetHeight(),\n number_of_components,\n &pixels[0],\n format,\n jpeg_quality);\n if(write_result == 0)\n {\n return MemoryChunk::Null();\n }\n\n return file.data;\n }\n\n namespace\n {\n unsigned char\n Select(int ch,\n unsigned char a,\n unsigned char b,\n unsigned char c,\n unsigned char d)\n {\n switch(ch)\n {\n case 1: \/\/ grey\n return a;\n case 2: \/\/ grey, alpha\n return b;\n case 3: \/\/ red, green, blue\n return c;\n case 4: \/\/ red, green, blue, alpha\n return d;\n default: DIE(\"unhandled Select channel\"); return 0;\n }\n }\n } \/\/ namespace\n\n ImageLoadResult\n LoadImage(vfs::FileSystem* fs, const std::string& path, AlphaLoad alpha)\n {\n auto file_memory = fs->ReadFile(path);\n if(file_memory == nullptr)\n {\n ImageLoadResult result;\n result.error = \"File doesnt exist\";\n result.image.MakeInvalid();\n LOG_ERROR(\"Failed to open \" << path << \": File doesnt exist.\");\n return result;\n }\n\n return LoadImage(file_memory, path, alpha);\n }\n\n ImageLoadResult\n LoadImage(\n std::shared_ptr<MemoryChunk> file_memory,\n const std::string& path,\n AlphaLoad alpha)\n {\n int channels = 0;\n int image_width = 0;\n int image_height = 0;\n\n \/\/ signed to unsigned cast is probably ok since both are considered to be\n \/\/ a chuck of memory\n \/\/ https:\/\/stackoverflow.com\/questions\/310451\/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever\n unsigned char* data = stbi_load_from_memory(\n reinterpret_cast<unsigned char*>(\n file_memory->GetData()), \/\/ NOLINT\n file_memory->GetSize(),\n &image_width,\n &image_height,\n &channels,\n 0);\n\n if(data == nullptr)\n {\n ImageLoadResult result;\n result.error = stbi_failure_reason();\n result.image.MakeInvalid();\n LOG_ERROR(\"Failed to read \" << path << \": \" << result.error);\n return result;\n }\n\n bool has_alpha = false;\n if(alpha == AlphaLoad::Keep)\n {\n has_alpha = channels == 2 || channels == 4;\n }\n\n LOG_INFO(\n \"Image: \" << path << \" \" << image_width << \"x\" << image_height\n << \" alpha \" << has_alpha << \" channels \"\n << channels);\n\n ImageLoadResult result;\n if(has_alpha)\n {\n result.image.SetupWithAlphaSupport(image_width, image_height, -1);\n }\n else\n {\n result.image.SetupNoAlphaSupport(image_width, image_height, -1);\n }\n\n for(int y = 0; y < image_height; ++y)\n {\n for(int x = 0; x < image_width; ++x)\n {\n const int src_index = (y * image_width + x) * channels;\n\n \/\/ get component values\n const unsigned char zero = 0;\n const unsigned char c1\n = data[src_index + 0]; \/\/ NOLINT no garbage value\n const unsigned char c2\n = (channels <= 1) ? zero : data[src_index + 1];\n const unsigned char c3\n = (channels <= 2) ? zero : data[src_index + 2];\n const unsigned char c4\n = (channels <= 3) ? zero : data[src_index + 3];\n\n \/\/ Gray, Gray+alpha, RGB, RGB+alpha: gr gra rgb rgba\n const unsigned char r = c1; \/\/ c1 c1 c1 c1\n const unsigned char g = Select(channels, c1, c1, c2, c2);\n const unsigned char b = Select(channels, c1, c1, c3, c3);\n const unsigned char a = Select(channels, 255, c2, 255, c4);\n\n result.image.SetPixel(x, image_height - (y + 1), r, g, b, a);\n }\n }\n\n stbi_image_free(data);\n return result;\n }\n\n ImageLoadResult\n LoadImage(\n void* compressed_data,\n int compressed_size,\n const std::string& path,\n AlphaLoad alpha)\n {\n Decompress dec;\n const unsigned int decompressed_size = Decompress::stb_decompress_length((const unsigned char*)compressed_data);\n auto decompressed = MemoryChunk::Alloc(decompressed_size);\n const auto len = dec.stb_decompress(reinterpret_cast<unsigned char*>(decompressed->GetData()),\n reinterpret_cast<const unsigned char*>(compressed_data),\n static_cast<unsigned int>(compressed_size));\n if(len == 0)\n {\n ImageLoadResult result;\n result.error = \"failed to decompress before loading image\";\n result.image.MakeInvalid();\n return result;\n }\n\n return LoadImage(decompressed, path, alpha);\n }\n\n} \/\/ namespace euphoria::core\n<commit_msg>replaced assert with assertx for easier debugging<commit_after>#include \"core\/image.h\"\n\n#include <iostream>\n\n#include \"core\/assert.h\"\n#include \"core\/numeric.h\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#define STBI_FAILURE_USERMSG\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image.h\"\n#include \"stb_image_write.h\"\n\n#include \"core\/log.h\"\n#include \"core\/decompress.h\"\n\nnamespace euphoria::core\n{\n LOG_SPECIFY_DEFAULT_LOGGER(\"core.image\")\n\n void\n Image::MakeInvalid()\n {\n components.resize(0);\n width_ = 0;\n height_ = 0;\n has_alpha_ = false;\n\n ASSERT(!IsValid());\n }\n\n int\n Image::GetPixelByteSize() const\n {\n return has_alpha_ ? 4 : 3;\n }\n\n void\n Image::SetupWithAlphaSupport(\n int image_width,\n int image_height,\n int default_value)\n {\n Setup(image_width, image_height, true, default_value);\n }\n\n void\n Image::SetupNoAlphaSupport(\n int image_width,\n int image_height,\n int default_value)\n {\n Setup(image_width, image_height, false, default_value);\n }\n\n void\n Image::Setup(\n int image_width,\n int image_height,\n bool alpha,\n int default_value)\n {\n ASSERTX(image_width > 0, image_width);\n ASSERTX(image_height > 0, image_height);\n\n width_ = image_width;\n height_ = image_height;\n has_alpha_ = alpha;\n\n components.resize(0); \/\/ clear all pixels\n const unsigned int size = width_ * height_ * GetPixelByteSize();\n if(default_value < 0)\n {\n components.resize(size);\n }\n else\n {\n ASSERT(default_value <= 255);\n components.resize(size, static_cast<unsigned char>(default_value));\n }\n\n ASSERT(IsValid());\n }\n\n int\n Image::GetPixelIndex(int x, int y) const\n {\n ASSERT(x >= 0 && x < width_);\n ASSERT(y >= 0 && y < height_);\n\n return (y * width_ + x) * GetPixelByteSize();\n }\n\n void\n Image::SetPixel(int x, int y, const Rgbai& color)\n {\n SetPixel(x, y, color.r, color.g, color.b, color.a);\n }\n\n void\n Image::SetPixel(\n int x,\n int y,\n unsigned char r,\n unsigned char g,\n unsigned char b,\n unsigned char a)\n {\n ASSERTX(IsWithinInclusivei(0, x, GetWidth() - 1), x, GetWidth() - 1);\n ASSERTX(IsWithinInclusivei(0, y, GetHeight() - 1), y, GetHeight() - 1);\n\n const auto base_index = GetPixelIndex(x, y);\n components[base_index + 0] = r;\n components[base_index + 1] = g;\n components[base_index + 2] = b;\n\n if(has_alpha_)\n {\n components[base_index + 3] = a;\n }\n }\n\n Rgbai\n Image::GetPixel(int x, int y) const\n {\n ASSERTX(IsWithinInclusivei(0, x, GetWidth() - 1), x, GetWidth());\n ASSERTX(IsWithinInclusivei(0, y, GetHeight() - 1), y, GetHeight());\n\n const auto base_index = GetPixelIndex(x, y);\n\n const auto red = components[base_index + 0];\n const auto green = components[base_index + 1];\n const auto blue = components[base_index + 2];\n\n if(has_alpha_)\n {\n const auto alpha = components[base_index + 3];\n return Rgbai {Rgbi {red, green, blue}, alpha};\n }\n else\n {\n return Rgbi {red, green, blue};\n }\n }\n\n bool\n Image::IsValid() const\n {\n return width_ > 0 && height_ > 0;\n }\n\n int\n Image::GetWidth() const\n {\n return width_;\n }\n\n int\n Image::GetHeight() const\n {\n return height_;\n }\n\n bool\n Image::HasAlpha() const\n {\n return has_alpha_;\n }\n\n const unsigned char*\n Image::GetPixelData() const\n {\n return &components[0];\n }\n\n namespace \/\/ local\n {\n void\n DetermineImageSize(void* context, void* \/*unused*\/, int size)\n {\n ASSERT(size >= 0);\n auto* total_size = static_cast<int*>(context);\n *total_size += size;\n }\n\n void\n WriteToMemoryChunkFile(void* context, void* data, int size)\n {\n ASSERT(size >= 0);\n auto* file = static_cast<MemoryChunkFile*>(context);\n file->Write(data, size);\n }\n } \/\/ namespace\n\n int\n WriteImageData(\n stbi_write_func* func,\n void* context,\n int w,\n int h,\n int comp,\n const void* data,\n ImageWriteFormat format,\n int jpeg_quality)\n {\n switch(format)\n {\n case ImageWriteFormat::PNG:\n return stbi_write_png_to_func(func, context, w, h, comp, data, 0);\n case ImageWriteFormat::BMP:\n return stbi_write_bmp_to_func(func, context, w, h, comp, data);\n case ImageWriteFormat::TGA:\n return stbi_write_tga_to_func(func, context, w, h, comp, data);\n case ImageWriteFormat::JPEG:\n return stbi_write_jpg_to_func(\n func, context, w, h, comp, data, jpeg_quality);\n default: DIE(\"Unhandled case\"); return 0;\n }\n }\n\n std::shared_ptr<MemoryChunk>\n Image::Write(ImageWriteFormat format, int jpeg_quality) const\n {\n const int number_of_components = has_alpha_ ? 4 : 3;\n\n std::vector<unsigned char> pixels(\n width_ * height_ * number_of_components, 0);\n for(int y = 0; y < height_; y += 1)\n {\n const int iy = height_ - (y + 1);\n\n ASSERTX(IsWithinInclusivei(0, iy, height_ - 1), iy, y, height_);\n for(int x = 0; x < width_; x += 1)\n {\n const int target_index\n = (x + width_ * y) * number_of_components;\n const int source_index\n = (x + width_ * iy) * number_of_components;\n for(int component = 0; component < number_of_components;\n component += 1)\n {\n pixels[target_index + component]\n = components[source_index + component];\n }\n }\n }\n\n int size = 0;\n int size_result = WriteImageData(\n DetermineImageSize,\n &size,\n GetWidth(),\n GetHeight(),\n number_of_components,\n &pixels[0],\n format,\n jpeg_quality);\n if(size_result == 0)\n {\n return MemoryChunk::Null();\n }\n\n ASSERT(size > 0);\n MemoryChunkFile file {MemoryChunk::Alloc(size)};\n int write_result = WriteImageData(\n WriteToMemoryChunkFile,\n &file,\n GetWidth(),\n GetHeight(),\n number_of_components,\n &pixels[0],\n format,\n jpeg_quality);\n if(write_result == 0)\n {\n return MemoryChunk::Null();\n }\n\n return file.data;\n }\n\n namespace\n {\n unsigned char\n Select(int ch,\n unsigned char a,\n unsigned char b,\n unsigned char c,\n unsigned char d)\n {\n switch(ch)\n {\n case 1: \/\/ grey\n return a;\n case 2: \/\/ grey, alpha\n return b;\n case 3: \/\/ red, green, blue\n return c;\n case 4: \/\/ red, green, blue, alpha\n return d;\n default: DIE(\"unhandled Select channel\"); return 0;\n }\n }\n } \/\/ namespace\n\n ImageLoadResult\n LoadImage(vfs::FileSystem* fs, const std::string& path, AlphaLoad alpha)\n {\n auto file_memory = fs->ReadFile(path);\n if(file_memory == nullptr)\n {\n ImageLoadResult result;\n result.error = \"File doesnt exist\";\n result.image.MakeInvalid();\n LOG_ERROR(\"Failed to open \" << path << \": File doesnt exist.\");\n return result;\n }\n\n return LoadImage(file_memory, path, alpha);\n }\n\n ImageLoadResult\n LoadImage(\n std::shared_ptr<MemoryChunk> file_memory,\n const std::string& path,\n AlphaLoad alpha)\n {\n int channels = 0;\n int image_width = 0;\n int image_height = 0;\n\n \/\/ signed to unsigned cast is probably ok since both are considered to be\n \/\/ a chuck of memory\n \/\/ https:\/\/stackoverflow.com\/questions\/310451\/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever\n unsigned char* data = stbi_load_from_memory(\n reinterpret_cast<unsigned char*>(\n file_memory->GetData()), \/\/ NOLINT\n file_memory->GetSize(),\n &image_width,\n &image_height,\n &channels,\n 0);\n\n if(data == nullptr)\n {\n ImageLoadResult result;\n result.error = stbi_failure_reason();\n result.image.MakeInvalid();\n LOG_ERROR(\"Failed to read \" << path << \": \" << result.error);\n return result;\n }\n\n bool has_alpha = false;\n if(alpha == AlphaLoad::Keep)\n {\n has_alpha = channels == 2 || channels == 4;\n }\n\n LOG_INFO(\n \"Image: \" << path << \" \" << image_width << \"x\" << image_height\n << \" alpha \" << has_alpha << \" channels \"\n << channels);\n\n ImageLoadResult result;\n if(has_alpha)\n {\n result.image.SetupWithAlphaSupport(image_width, image_height, -1);\n }\n else\n {\n result.image.SetupNoAlphaSupport(image_width, image_height, -1);\n }\n\n for(int y = 0; y < image_height; ++y)\n {\n for(int x = 0; x < image_width; ++x)\n {\n const int src_index = (y * image_width + x) * channels;\n\n \/\/ get component values\n const unsigned char zero = 0;\n const unsigned char c1\n = data[src_index + 0]; \/\/ NOLINT no garbage value\n const unsigned char c2\n = (channels <= 1) ? zero : data[src_index + 1];\n const unsigned char c3\n = (channels <= 2) ? zero : data[src_index + 2];\n const unsigned char c4\n = (channels <= 3) ? zero : data[src_index + 3];\n\n \/\/ Gray, Gray+alpha, RGB, RGB+alpha: gr gra rgb rgba\n const unsigned char r = c1; \/\/ c1 c1 c1 c1\n const unsigned char g = Select(channels, c1, c1, c2, c2);\n const unsigned char b = Select(channels, c1, c1, c3, c3);\n const unsigned char a = Select(channels, 255, c2, 255, c4);\n\n result.image.SetPixel(x, image_height - (y + 1), r, g, b, a);\n }\n }\n\n stbi_image_free(data);\n return result;\n }\n\n ImageLoadResult\n LoadImage(\n void* compressed_data,\n int compressed_size,\n const std::string& path,\n AlphaLoad alpha)\n {\n Decompress dec;\n const unsigned int decompressed_size = Decompress::stb_decompress_length((const unsigned char*)compressed_data);\n auto decompressed = MemoryChunk::Alloc(decompressed_size);\n const auto len = dec.stb_decompress(reinterpret_cast<unsigned char*>(decompressed->GetData()),\n reinterpret_cast<const unsigned char*>(compressed_data),\n static_cast<unsigned int>(compressed_size));\n if(len == 0)\n {\n ImageLoadResult result;\n result.error = \"failed to decompress before loading image\";\n result.image.MakeInvalid();\n return result;\n }\n\n return LoadImage(decompressed, path, alpha);\n }\n\n} \/\/ namespace euphoria::core\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/graf:$Name: $:$Id: TMarker.cxx,v 1.4 2000\/11\/21 20:26:41 brun Exp $\n\/\/ Author: Rene Brun 12\/05\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <stdlib.h>\n#include <fstream.h>\n#include <iostream.h>\n\n#include \"TROOT.h\"\n#include \"TVirtualPad.h\"\n#include \"TMarker.h\"\n#include \"TVirtualX.h\"\n#include \"TMath.h\"\n#include \"TPoint.h\"\n#include \"TText.h\"\n\nClassImp(TMarker)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Manages Markers. Marker attributes are managed by TAttMarker.\n\/\/ The list of standard ROOT markers is shown in this picture\n\/\/Begin_Html\n\/*\n<img src=\"gif\/markers.gif\">\n*\/\n\/\/End_Html\n\/\/\n\n\/\/______________________________________________________________________________\nTMarker::TMarker(): TObject(), TAttMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==========================\n fX = 0;\n fY = 0;\n}\n\/\/______________________________________________________________________________\nTMarker::TMarker(Double_t x, Double_t y, Int_t marker)\n :TObject(), TAttMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================\n fX = x;\n fY = y;\n fMarkerStyle = marker;\n}\n\n\/\/______________________________________________________________________________\nTMarker::~TMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================\n}\n\n\/\/______________________________________________________________________________\nTMarker::TMarker(const TMarker &marker)\n{\n ((TMarker&)marker).Copy(*this);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Copy(TObject &obj)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Copy this marker to marker*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==========================\n\n TObject::Copy(obj);\n TAttMarker::Copy(((TMarker&)obj));\n ((TMarker&)obj).fX = fX;\n ((TMarker&)obj).fY = fY;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::DisplayMarkerTypes()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Display the table of markers with their numbers*-*-*-*\n\/\/*-* ===============================================\n\n TMarker *marker = new TMarker();\n marker->SetMarkerSize(3);\n TText *text = new TText();\n text->SetTextFont(62);\n text->SetTextAlign(22);\n text->SetTextSize(0.1);\n char atext[] = \" \";\n Double_t x = 0;\n Double_t dx = 1\/12.0;\n for (Int_t i=1;i<12;i++) {\n x += dx;\n sprintf(atext,\"%d\",i);\n marker->SetMarkerStyle(i);\n marker->DrawMarker(x,.35);\n text->DrawText(x,.17,atext);\n sprintf(atext,\"%d\",i+19);\n marker->SetMarkerStyle(i+19);\n marker->DrawMarker(x,.8);\n text->DrawText(x,.62,atext);\n }\n delete marker;\n delete text;\n}\n\n\/\/______________________________________________________________________________\nInt_t TMarker::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Compute distance from point px,py to a marker*-*-*-*-*-*\n\/\/*-* ===========================================\n\/\/ Compute the closest distance of approach from point px,py to this marker.\n\/\/ The distance is computed in pixels units.\n\/\/\n\n const Int_t kMaxDiff = 10;\n Int_t pxm = gPad->XtoAbsPixel(fX);\n Int_t pym = gPad->YtoAbsPixel(fY);\n Int_t dist = (px-pxm)*(px-pxm) + (py-pym)*(py-pym);\n\n if (dist > kMaxDiff) return 9999;\n return dist;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with its current attributes*-*-*-*-*-*-*\n\/\/*-* ============================================\n\n AppendPad(option);\n\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::DrawMarker(Double_t x, Double_t y)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with new coordinates*-*-*-*-*-*-*-*-*-*\n\/\/*-* =====================================\n TMarker *newmarker = new TMarker(x, y, 1);\n TAttMarker::Copy(*newmarker);\n newmarker->SetBit(kCanDelete);\n newmarker->AppendPad();\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::ExecuteEvent(Int_t event, Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-* =========================================\n\/\/ This member function is called when a marker is clicked with the locator\n\/\/\n\/\/ If Left button is clicked on a marker, the marker is moved to\n\/\/ a new position when the mouse button is released.\n\/\/\n\n TPoint p;\n static Int_t pxold, pyold;\n\n if (!gPad->IsEditable()) return;\n\n switch (event) {\n\n\n case kButton1Down:\n gVirtualX->SetTextColor(-1); \/\/ invalidate current text color (use xor mode)\n TAttMarker::Modify(); \/\/Change marker attributes only if necessary\n\n \/\/ No break !!!\n\n case kMouseMotion:\n pxold = px; pyold = py;\n gPad->SetCursor(kMove);\n break;\n\n case kButton1Motion:\n p.fX = pxold; p.fY = pyold;\n gVirtualX->DrawPolyMarker(1, &p);\n p.fX = px; p.fY = py;\n gVirtualX->DrawPolyMarker(1, &p);\n pxold = px; pyold = py;\n break;\n\n case kButton1Up:\n fX = gPad->AbsPixeltoX(px);\n fY = gPad->AbsPixeltoY(py);\n gPad->Modified(kTRUE);\n gVirtualX->SetTextColor(-1);\n break;\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::ls(Option_t *) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*List this marker with its attributes*-*-*-*-*-*-*-*-*\n\/\/*-* ====================================\n TROOT::IndentLevel();\n printf(\"Marker X=%f Y=%f marker type=%d\\n\",fX,fY,fMarkerStyle);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Paint(Option_t *)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Paint this marker with its current attributes*-*-*-*-*-*-*\n\/\/*-* =============================================\n PaintMarker(fX,fY);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::PaintMarker(Double_t x, Double_t y)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with new coordinates*-*-*-*-*-*-*-*-*-*\n\/\/*-* =====================================\n\n TAttMarker::Modify(); \/\/Change line attributes only if necessary\n gPad->PaintPolyMarker(1,&x,&y,\"\");\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::PaintMarkerNDC(Double_t, Double_t)\n{\n\/\/*-*-*-*-*-*-*-*Draw this marker with new coordinates in NDC*-*-*-*-*-*-*-*-*-*\n\/\/*-* ============================================\n\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Print(Option_t *) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Dump this marker with its attributes*-*-*-*-*-*-*-*-*-*\n\/\/*-* ====================================\n\n printf(\"Marker X=%f Y=%f\",fX,fY);\n if (GetMarkerColor() != 1) printf(\" Color=%d\",GetMarkerColor());\n if (GetMarkerStyle() != 1) printf(\" MarkerStyle=%d\",GetMarkerStyle());\n if (GetMarkerSize() != 1) printf(\" MarkerSize=%f\",GetMarkerSize());\n printf(\"\\n\");\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::SavePrimitive(ofstream &out, Option_t *)\n{\n \/\/ Save primitive as a C++ statement(s) on output stream out\n\n if (gROOT->ClassSaved(TMarker::Class())) {\n out<<\" \";\n } else {\n out<<\" TMarker *\";\n }\n out<<\"marker = new TMarker(\"<<fX<<\",\"<<fY<<\",\"<<fMarkerStyle<<\");\"<<endl;\n\n SaveMarkerAttributes(out,\"marker\",1,1,1);\n\n out<<\" marker->Draw();\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TMarker.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 1) {\n TMarker::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TObject::Streamer(R__b);\n TAttMarker::Streamer(R__b);\n Float_t x,y;\n R__b >> x; fX = x;\n R__b >> y; fY = y;\n \/\/====end of old versions\n \n } else {\n TMarker::Class()->WriteBuffer(R__b,this);\n }\n}\n<commit_msg>In TMarker::Paintmarker, disable clip to frame by default. TMarkers may be used by TLegend and should not be clipped in this case to the frame boundary.<commit_after>\/\/ @(#)root\/graf:$Name: $:$Id: TMarker.cxx,v 1.5 2000\/12\/13 15:13:50 brun Exp $\n\/\/ Author: Rene Brun 12\/05\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <stdlib.h>\n#include <fstream.h>\n#include <iostream.h>\n\n#include \"TROOT.h\"\n#include \"TVirtualPad.h\"\n#include \"TMarker.h\"\n#include \"TVirtualX.h\"\n#include \"TMath.h\"\n#include \"TPoint.h\"\n#include \"TText.h\"\n\nClassImp(TMarker)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Manages Markers. Marker attributes are managed by TAttMarker.\n\/\/ The list of standard ROOT markers is shown in this picture\n\/\/Begin_Html\n\/*\n<img src=\"gif\/markers.gif\">\n*\/\n\/\/End_Html\n\/\/\n\n\/\/______________________________________________________________________________\nTMarker::TMarker(): TObject(), TAttMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==========================\n fX = 0;\n fY = 0;\n}\n\/\/______________________________________________________________________________\nTMarker::TMarker(Double_t x, Double_t y, Int_t marker)\n :TObject(), TAttMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================\n fX = x;\n fY = y;\n fMarkerStyle = marker;\n}\n\n\/\/______________________________________________________________________________\nTMarker::~TMarker()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Marker default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================\n}\n\n\/\/______________________________________________________________________________\nTMarker::TMarker(const TMarker &marker)\n{\n ((TMarker&)marker).Copy(*this);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Copy(TObject &obj)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Copy this marker to marker*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ==========================\n\n TObject::Copy(obj);\n TAttMarker::Copy(((TMarker&)obj));\n ((TMarker&)obj).fX = fX;\n ((TMarker&)obj).fY = fY;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::DisplayMarkerTypes()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Display the table of markers with their numbers*-*-*-*\n\/\/*-* ===============================================\n\n TMarker *marker = new TMarker();\n marker->SetMarkerSize(3);\n TText *text = new TText();\n text->SetTextFont(62);\n text->SetTextAlign(22);\n text->SetTextSize(0.1);\n char atext[] = \" \";\n Double_t x = 0;\n Double_t dx = 1\/12.0;\n for (Int_t i=1;i<12;i++) {\n x += dx;\n sprintf(atext,\"%d\",i);\n marker->SetMarkerStyle(i);\n marker->DrawMarker(x,.35);\n text->DrawText(x,.17,atext);\n sprintf(atext,\"%d\",i+19);\n marker->SetMarkerStyle(i+19);\n marker->DrawMarker(x,.8);\n text->DrawText(x,.62,atext);\n }\n delete marker;\n delete text;\n}\n\n\/\/______________________________________________________________________________\nInt_t TMarker::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Compute distance from point px,py to a marker*-*-*-*-*-*\n\/\/*-* ===========================================\n\/\/ Compute the closest distance of approach from point px,py to this marker.\n\/\/ The distance is computed in pixels units.\n\/\/\n\n const Int_t kMaxDiff = 10;\n Int_t pxm = gPad->XtoAbsPixel(fX);\n Int_t pym = gPad->YtoAbsPixel(fY);\n Int_t dist = (px-pxm)*(px-pxm) + (py-pym)*(py-pym);\n\n if (dist > kMaxDiff) return 9999;\n return dist;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with its current attributes*-*-*-*-*-*-*\n\/\/*-* ============================================\n\n AppendPad(option);\n\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::DrawMarker(Double_t x, Double_t y)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with new coordinates*-*-*-*-*-*-*-*-*-*\n\/\/*-* =====================================\n TMarker *newmarker = new TMarker(x, y, 1);\n TAttMarker::Copy(*newmarker);\n newmarker->SetBit(kCanDelete);\n newmarker->AppendPad();\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::ExecuteEvent(Int_t event, Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-* =========================================\n\/\/ This member function is called when a marker is clicked with the locator\n\/\/\n\/\/ If Left button is clicked on a marker, the marker is moved to\n\/\/ a new position when the mouse button is released.\n\/\/\n\n TPoint p;\n static Int_t pxold, pyold;\n\n if (!gPad->IsEditable()) return;\n\n switch (event) {\n\n\n case kButton1Down:\n gVirtualX->SetTextColor(-1); \/\/ invalidate current text color (use xor mode)\n TAttMarker::Modify(); \/\/Change marker attributes only if necessary\n\n \/\/ No break !!!\n\n case kMouseMotion:\n pxold = px; pyold = py;\n gPad->SetCursor(kMove);\n break;\n\n case kButton1Motion:\n p.fX = pxold; p.fY = pyold;\n gVirtualX->DrawPolyMarker(1, &p);\n p.fX = px; p.fY = py;\n gVirtualX->DrawPolyMarker(1, &p);\n pxold = px; pyold = py;\n break;\n\n case kButton1Up:\n fX = gPad->AbsPixeltoX(px);\n fY = gPad->AbsPixeltoY(py);\n gPad->Modified(kTRUE);\n gVirtualX->SetTextColor(-1);\n break;\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::ls(Option_t *) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*List this marker with its attributes*-*-*-*-*-*-*-*-*\n\/\/*-* ====================================\n TROOT::IndentLevel();\n printf(\"Marker X=%f Y=%f marker type=%d\\n\",fX,fY,fMarkerStyle);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Paint(Option_t *)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Paint this marker with its current attributes*-*-*-*-*-*-*\n\/\/*-* =============================================\n PaintMarker(fX,fY);\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::PaintMarker(Double_t x, Double_t y)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this marker with new coordinates*-*-*-*-*-*-*-*-*-*\n\/\/*-* =====================================\n\n TAttMarker::Modify(); \/\/Change line attributes only if necessary\n gPad->PaintPolyMarker(-1,&x,&y,\"\");\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::PaintMarkerNDC(Double_t, Double_t)\n{\n\/\/*-*-*-*-*-*-*-*Draw this marker with new coordinates in NDC*-*-*-*-*-*-*-*-*-*\n\/\/*-* ============================================\n\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Print(Option_t *) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Dump this marker with its attributes*-*-*-*-*-*-*-*-*-*\n\/\/*-* ====================================\n\n printf(\"Marker X=%f Y=%f\",fX,fY);\n if (GetMarkerColor() != 1) printf(\" Color=%d\",GetMarkerColor());\n if (GetMarkerStyle() != 1) printf(\" MarkerStyle=%d\",GetMarkerStyle());\n if (GetMarkerSize() != 1) printf(\" MarkerSize=%f\",GetMarkerSize());\n printf(\"\\n\");\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::SavePrimitive(ofstream &out, Option_t *)\n{\n \/\/ Save primitive as a C++ statement(s) on output stream out\n\n if (gROOT->ClassSaved(TMarker::Class())) {\n out<<\" \";\n } else {\n out<<\" TMarker *\";\n }\n out<<\"marker = new TMarker(\"<<fX<<\",\"<<fY<<\",\"<<fMarkerStyle<<\");\"<<endl;\n\n SaveMarkerAttributes(out,\"marker\",1,1,1);\n\n out<<\" marker->Draw();\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid TMarker::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TMarker.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 1) {\n TMarker::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TObject::Streamer(R__b);\n TAttMarker::Streamer(R__b);\n Float_t x,y;\n R__b >> x; fX = x;\n R__b >> y; fY = y;\n \/\/====end of old versions\n \n } else {\n TMarker::Class()->WriteBuffer(R__b,this);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <src\/global\/qbuildcfg.h>\n#include \"qsensorpluginloader_p.h\"\n#include <QtCore\/qcoreapplication.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qdebug.h>\n\n#include \"qsensorplugin.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQSensorPluginLoader::QSensorPluginLoader(const char *iid, const QString &location)\n : m_iid(iid)\n{\n m_location = location + QLatin1String(\"\/\");\n load();\n}\n\nQSensorPluginLoader::~QSensorPluginLoader()\n{\n Q_FOREACH (QPluginLoader *loader, m_loaders) {\n bool ok = loader->unload();\n if (!ok) qWarning() << \"Cannot unload\" << loader->fileName();\n delete loader;\n }\n}\n\nvoid QSensorPluginLoader::load()\n{\n if (!m_plugins.isEmpty())\n return;\n\n QStringList paths = QCoreApplication::libraryPaths();\n QString val = qt_mobility_configure_prefix_path_str;\n if(val.length() > 0){\n val += \"\/plugins\";\n paths << val;\n }\n\n Q_FOREACH (QString const &path, paths) {\n QString pluginPathName(path + m_location);\n QDir pluginDir(pluginPathName);\n\n if (!pluginDir.exists())\n continue;\n\n Q_FOREACH (QString pluginLib, pluginDir.entryList(QDir::Files)) {\n QPluginLoader *loader = new QPluginLoader(pluginPathName + pluginLib);\n\n QObject *o = loader->instance();\n if (o != 0 && o->qt_metacast(m_iid) != 0) {\n QSensorPluginInterface *p = qobject_cast<QSensorPluginInterface*>(o);\n if (p != 0) {\n m_plugins << p;\n m_loaders << loader;\n } else {\n loader->unload();\n delete loader;\n }\n\n continue;\n } else {\n qWarning() << \"QSensorPluginLoader: Failed to load plugin: \" << pluginLib << loader->errorString();\n }\n delete o;\n loader->unload();\n delete loader;\n }\n }\n}\n\nQTM_END_NAMESPACE\n\n<commit_msg>Fix some raw latin1 strings that got introduced.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <src\/global\/qbuildcfg.h>\n#include \"qsensorpluginloader_p.h\"\n#include <QtCore\/qcoreapplication.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qdebug.h>\n\n#include \"qsensorplugin.h\"\n\nQTM_BEGIN_NAMESPACE\n\nQSensorPluginLoader::QSensorPluginLoader(const char *iid, const QString &location)\n : m_iid(iid)\n{\n m_location = location + QLatin1String(\"\/\");\n load();\n}\n\nQSensorPluginLoader::~QSensorPluginLoader()\n{\n Q_FOREACH (QPluginLoader *loader, m_loaders) {\n bool ok = loader->unload();\n if (!ok) qWarning() << \"Cannot unload\" << loader->fileName();\n delete loader;\n }\n}\n\nvoid QSensorPluginLoader::load()\n{\n if (!m_plugins.isEmpty())\n return;\n\n QStringList paths = QCoreApplication::libraryPaths();\n QString val = QLatin1String(qt_mobility_configure_prefix_path_str);\n if(val.length() > 0){\n val += QLatin1String(\"\/plugins\");\n paths << val;\n }\n\n Q_FOREACH (QString const &path, paths) {\n QString pluginPathName(path + m_location);\n QDir pluginDir(pluginPathName);\n\n if (!pluginDir.exists())\n continue;\n\n Q_FOREACH (QString pluginLib, pluginDir.entryList(QDir::Files)) {\n QPluginLoader *loader = new QPluginLoader(pluginPathName + pluginLib);\n\n QObject *o = loader->instance();\n if (o != 0 && o->qt_metacast(m_iid) != 0) {\n QSensorPluginInterface *p = qobject_cast<QSensorPluginInterface*>(o);\n if (p != 0) {\n m_plugins << p;\n m_loaders << loader;\n } else {\n loader->unload();\n delete loader;\n }\n\n continue;\n } else {\n qWarning() << \"QSensorPluginLoader: Failed to load plugin: \" << pluginLib << loader->errorString();\n }\n delete o;\n loader->unload();\n delete loader;\n }\n }\n}\n\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsensorpluginloader_p.h\"\n#include <QtCore\/qcoreapplication.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qdebug.h>\n\n#include \"qsensorplugin.h\"\n#include \"qmobilitypluginsearch.h\"\n\nQT_BEGIN_NAMESPACE\n\nQSensorPluginLoader::QSensorPluginLoader()\n{\n load();\n}\n\nQSensorPluginLoader::~QSensorPluginLoader()\n{\n Q_FOREACH (QPluginLoader *loader, m_loaders) {\n bool ok = loader->unload();\n if (!ok) qWarning() << \"Cannot unload\" << loader->fileName();\n delete loader;\n }\n}\n\nQList<QObject*> QSensorPluginLoader::plugins() const\n{\n return m_plugins;\n}\n\nvoid QSensorPluginLoader::load()\n{\n if (!m_plugins.isEmpty())\n return;\n\n QStringList plugins = mobilityPlugins(QLatin1String(\"sensors\"));\n\n \/* Now discover the dynamic plugins *\/\n for (int i = 0; i < plugins.count(); i++) {\n QPluginLoader *loader = new QPluginLoader(plugins.at(i));\n\n QObject *o = loader->instance();\n if (o != 0) {\n QSensorPluginInterface *p = qobject_cast<QSensorPluginInterface*>(o);\n if (p != 0) {\n m_plugins << o;\n m_loaders << loader;\n } else {\n loader->unload();\n delete loader;\n }\n\n continue;\n }\n delete o;\n loader->unload();\n delete loader;\n }\n}\n\nQT_END_NAMESPACE\n\n<commit_msg>report errors when plugins can't be loaded<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsensorpluginloader_p.h\"\n#include <QtCore\/qcoreapplication.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qdebug.h>\n\n#include \"qsensorplugin.h\"\n#include \"qmobilitypluginsearch.h\"\n\nQT_BEGIN_NAMESPACE\n\nQSensorPluginLoader::QSensorPluginLoader()\n{\n load();\n}\n\nQSensorPluginLoader::~QSensorPluginLoader()\n{\n Q_FOREACH (QPluginLoader *loader, m_loaders) {\n bool ok = loader->unload();\n if (!ok) qWarning() << \"Cannot unload\" << loader->fileName();\n delete loader;\n }\n}\n\nQList<QObject*> QSensorPluginLoader::plugins() const\n{\n return m_plugins;\n}\n\nvoid QSensorPluginLoader::load()\n{\n if (!m_plugins.isEmpty())\n return;\n\n QStringList plugins = mobilityPlugins(QLatin1String(\"sensors\"));\n bool reportErrors = (qgetenv(\"QT_DEBUG_PLUGINS\") == \"1\");\n\n \/* Now discover the dynamic plugins *\/\n for (int i = 0; i < plugins.count(); i++) {\n QPluginLoader *loader = new QPluginLoader(plugins.at(i));\n\n QObject *o = loader->instance();\n if (o != 0) {\n QSensorPluginInterface *p = qobject_cast<QSensorPluginInterface*>(o);\n if (p != 0) {\n m_plugins << o;\n m_loaders << loader;\n } else {\n if (reportErrors) {\n qWarning() << plugins.at(i) << \"is not a QSensorPluginInterface\";\n }\n loader->unload();\n delete loader;\n }\n\n continue;\n } else {\n if (reportErrors) {\n qWarning() << loader->errorString();\n }\n }\n delete o;\n loader->unload();\n delete loader;\n }\n}\n\nQT_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ `krbn::dispatcher::dispatcher` can be used safely in a multi-threaded environment.\n\n#include \"dispatcher\/object_id.hpp\"\n#include \"thread_utility.hpp\"\n\nnamespace krbn {\nnamespace dispatcher {\nclass dispatcher final {\npublic:\n dispatcher(const dispatcher&) = delete;\n\n dispatcher(void) : exit_(false) {\n worker_thread_ = std::thread([this] {\n worker_thread_id_ = std::this_thread::get_id();\n worker_thread_id_wait_.notify();\n\n while (true) {\n std::function<void(void)> function;\n\n {\n std::unique_lock<std::mutex> lock(mutex_);\n\n cv_.wait(lock, [this] {\n return exit_ || !queue_.empty();\n });\n\n if (exit_ && queue_.empty()) {\n break;\n }\n\n if (!queue_.empty()) {\n function = queue_.front();\n queue_.pop();\n }\n }\n\n if (function) {\n std::lock_guard<std::mutex> lock(function_mutex_);\n\n function();\n }\n }\n });\n\n worker_thread_id_wait_.wait_notice();\n }\n\n ~dispatcher(void) {\n if (worker_thread_.joinable()) {\n logger::get_logger().error(\"Call `dispatcher::terminate` before destroy `dispatcher`\");\n terminate();\n }\n }\n\n void attach(const object_id& object_id) {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n object_ids_.insert(object_id.get());\n }\n\n void detach(const object_id& object_id) {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(object_id.get())) {\n return;\n }\n\n object_ids_.erase(object_id.get());\n }\n\n if (!is_dispatcher_thread()) {\n \/\/ Wait until current running function is finised.\n std::lock_guard<std::mutex> lock(function_mutex_);\n }\n }\n\n void detach(const object_id& object_id,\n const std::function<void(void)>& function) {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(object_id.get())) {\n return;\n }\n }\n\n if (is_dispatcher_thread()) {\n function();\n } else {\n thread_utility::wait w;\n\n enqueue(object_id,\n [&w, &function] {\n function();\n w.notify();\n });\n\n w.wait_notice();\n }\n\n detach(object_id);\n }\n\n bool is_dispatcher_thread(void) const {\n return std::this_thread::get_id() == worker_thread_id_;\n }\n\n void terminate(void) {\n \/\/ We should separate `~dispatcher` and `terminate` to ensure dispatcher exists until all jobs are processed.\n \/\/\n \/\/ Example:\n \/\/ ----------------------------------------\n \/\/ class example final {\n \/\/ public:\n \/\/ example(void) : object_id_(krbn::dispatcher::make_new_object_id()) {\n \/\/ dispatcher_ = std::make_unique<krbn::dispatcher::dispatcher>();\n \/\/ dispatcher_->attach(object_id_);\n \/\/\n \/\/ dispatcher_->enqueue(\n \/\/ object_id_,\n \/\/ [this] {\n \/\/ \/\/ `dispatcher_` might be nullptr if we call `terminate` before `dispatcher_ = nullptr`.\n \/\/ dispatcher_->enqueue(\n \/\/ object_id_,\n \/\/ [] {\n \/\/ std::cout << \"hello\" << std::endl;\n \/\/ });\n \/\/ });\n \/\/\n \/\/ dispatcher_->terminate(); \/\/ SEGV if comment out this line\n \/\/ dispatcher_ = nullptr;\n \/\/ }\n \/\/\n \/\/ private:\n \/\/ krbn::dispatcher::object_id object_id_;\n \/\/ std::unique_ptr<krbn::dispatcher::dispatcher> dispatcher_;\n \/\/ };\n \/\/ ----------------------------------------\n\n if (is_dispatcher_thread()) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n exit_ = true;\n queue_.empty();\n }\n\n worker_thread_.detach();\n\n } else {\n if (worker_thread_.joinable()) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n exit_ = true;\n }\n\n cv_.notify_one();\n worker_thread_.join();\n }\n }\n }\n\n void enqueue(const object_id& object_id,\n const std::function<void(void)>& function) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n auto id = object_id.get();\n queue_.push([this, id, function] {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(id)) {\n return;\n }\n }\n\n function();\n });\n }\n\n cv_.notify_one();\n }\n\nprivate:\n bool attached(const uint64_t object_id_value) {\n auto it = object_ids_.find(object_id_value);\n return it != std::end(object_ids_);\n }\n\n std::thread worker_thread_;\n std::thread::id worker_thread_id_;\n thread_utility::wait worker_thread_id_wait_;\n\n std::queue<std::function<void(void)>> queue_;\n bool exit_;\n std::mutex mutex_;\n std::condition_variable cv_;\n\n std::unordered_set<uint64_t> object_ids_;\n std::mutex object_ids_mutex_;\n\n std::mutex function_mutex_;\n};\n} \/\/ namespace dispatcher\n} \/\/ namespace krbn\n<commit_msg>add dispatcher::entry<commit_after>#pragma once\n\n\/\/ `krbn::dispatcher::dispatcher` can be used safely in a multi-threaded environment.\n\n#include \"dispatcher\/object_id.hpp\"\n#include \"thread_utility.hpp\"\n#include \"types\/absolute_time.hpp\"\n#include <deque>\n\nnamespace krbn {\nnamespace dispatcher {\nclass dispatcher final {\npublic:\n dispatcher(const dispatcher&) = delete;\n\n dispatcher(void) : exit_(false) {\n worker_thread_ = std::thread([this] {\n worker_thread_id_ = std::this_thread::get_id();\n worker_thread_id_wait_.notify();\n\n while (true) {\n std::shared_ptr<entry> e;\n\n {\n std::unique_lock<std::mutex> lock(mutex_);\n\n cv_.wait(lock, [this] {\n return exit_ || !queue_.empty();\n });\n\n if (exit_ && queue_.empty()) {\n break;\n }\n\n if (!queue_.empty()) {\n e = queue_.front();\n queue_.pop_front();\n }\n }\n\n if (e) {\n std::lock_guard<std::mutex> lock(function_mutex_);\n\n e->call_function();\n }\n }\n });\n\n worker_thread_id_wait_.wait_notice();\n }\n\n ~dispatcher(void) {\n if (worker_thread_.joinable()) {\n logger::get_logger().error(\"Call `dispatcher::terminate` before destroy `dispatcher`\");\n terminate();\n }\n }\n\n void attach(const object_id& object_id) {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n object_ids_.insert(object_id.get());\n }\n\n void detach(const object_id& object_id) {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(object_id.get())) {\n return;\n }\n\n object_ids_.erase(object_id.get());\n }\n\n if (!is_dispatcher_thread()) {\n \/\/ Wait until current running function is finised.\n std::lock_guard<std::mutex> lock(function_mutex_);\n }\n }\n\n void detach(const object_id& object_id,\n const std::function<void(void)>& function) {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(object_id.get())) {\n return;\n }\n }\n\n if (is_dispatcher_thread()) {\n function();\n } else {\n thread_utility::wait w;\n\n enqueue(object_id,\n [&w, &function] {\n function();\n w.notify();\n });\n\n w.wait_notice();\n }\n\n detach(object_id);\n }\n\n bool is_dispatcher_thread(void) const {\n return std::this_thread::get_id() == worker_thread_id_;\n }\n\n void terminate(void) {\n \/\/ We should separate `~dispatcher` and `terminate` to ensure dispatcher exists until all jobs are processed.\n \/\/\n \/\/ Example:\n \/\/ ----------------------------------------\n \/\/ class example final {\n \/\/ public:\n \/\/ example(void) : object_id_(krbn::dispatcher::make_new_object_id()) {\n \/\/ dispatcher_ = std::make_unique<krbn::dispatcher::dispatcher>();\n \/\/ dispatcher_->attach(object_id_);\n \/\/\n \/\/ dispatcher_->enqueue(\n \/\/ object_id_,\n \/\/ [this] {\n \/\/ \/\/ `dispatcher_` might be nullptr if we call `terminate` before `dispatcher_ = nullptr`.\n \/\/ dispatcher_->enqueue(\n \/\/ object_id_,\n \/\/ [] {\n \/\/ std::cout << \"hello\" << std::endl;\n \/\/ });\n \/\/ });\n \/\/\n \/\/ dispatcher_->terminate(); \/\/ SEGV if comment out this line\n \/\/ dispatcher_ = nullptr;\n \/\/ }\n \/\/\n \/\/ private:\n \/\/ krbn::dispatcher::object_id object_id_;\n \/\/ std::unique_ptr<krbn::dispatcher::dispatcher> dispatcher_;\n \/\/ };\n \/\/ ----------------------------------------\n\n if (is_dispatcher_thread()) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n exit_ = true;\n queue_.empty();\n }\n\n worker_thread_.detach();\n\n } else {\n if (worker_thread_.joinable()) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n exit_ = true;\n }\n\n cv_.notify_one();\n worker_thread_.join();\n }\n }\n }\n\n void enqueue(const object_id& object_id,\n const std::function<void(void)>& function,\n absolute_time when = absolute_time(0)) {\n {\n std::lock_guard<std::mutex> lock(mutex_);\n\n auto id = object_id.get();\n queue_.push_back(std::make_shared<entry>(\n [this, id, function] {\n {\n std::lock_guard<std::mutex> lock(object_ids_mutex_);\n\n if (!attached(id)) {\n return;\n }\n }\n\n function();\n },\n when));\n\n std::stable_sort(std::begin(queue_),\n std::end(queue_),\n [](auto& a, auto& b) {\n return a->get_when() < b->get_when();\n });\n }\n\n cv_.notify_one();\n }\n\nprivate:\n class entry final {\n public:\n entry(const std::function<void(void)>& function,\n absolute_time when) : function_(function),\n when_(when) {\n }\n\n absolute_time get_when(void) const {\n return when_;\n }\n\n void call_function(void) const {\n function_();\n }\n\n private:\n std::function<void(void)> function_;\n absolute_time when_;\n };\n\n bool attached(const uint64_t object_id_value) {\n auto it = object_ids_.find(object_id_value);\n return it != std::end(object_ids_);\n }\n\n std::thread worker_thread_;\n std::thread::id worker_thread_id_;\n thread_utility::wait worker_thread_id_wait_;\n\n std::deque<std::shared_ptr<entry>> queue_;\n bool exit_;\n std::mutex mutex_;\n std::condition_variable cv_;\n\n std::unordered_set<uint64_t> object_ids_;\n std::mutex object_ids_mutex_;\n\n std::mutex function_mutex_;\n};\n} \/\/ namespace dispatcher\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>\/\/ Xerus - A General Purpose Tensor Library\n\/\/ Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf. \n\/\/ \n\/\/ Xerus is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published\n\/\/ by the Free Software Foundation, either version 3 of the License,\n\/\/ or (at your option) any later version.\n\/\/ \n\/\/ Xerus is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Xerus. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\/\/ For further information on Xerus visit https:\/\/libXerus.org \n\/\/ or contact us at contact@libXerus.org.\n\n#ifdef TEST_\n\n #include \"standard.h\"\n #include \"exceptions.h\"\n #include <iostream>\n #include <iomanip>\n #include <chrono>\n #include <signal.h>\n #include <sstream>\n\n #include <string.h> \/\/ for strsignal\n\n #include \"testManager.h\"\n #include \"stringUtilities.h\"\n#include <sys\/stat.h>\n\n std::map<std::string, std::map<std::string, std::function<bool ()>>> *___UnitTest::tests;\n\tstd::map<___RequiredTest::identifier, size_t> *___RequiredTest::tests;\n\n bool ___test(const std::pair<std::string, std::function<bool ()>> &_t) {\n bool passed = false;\n \n std::cout << \"| \" << _t.first << \" starting: \" << std::flush;\n \n std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();\n try {\n passed = _t.second(); \/\/ executes the test\n } catch (const MISC::generic_error &e) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught xerus::generic_error():\" << std::endl;\n std::cerr << e.what() << std::endl;\n passed = false;\n } catch (const std::exception &e) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught std::exception:\" << std::endl;\n std::cerr << e.what() << std::endl;\n passed = false;\n } catch (...) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught unknown exception...\" << std::endl;\n passed = false;\n }\n std::chrono::microseconds::rep time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();\n \n if (passed) { \n std::cout << std::endl << \"| \" << _t.first << \":\\033[1;32m passed!\\033[0m (\" << std::fixed << std::setprecision(3) << (double)time\/1000.0 << \" ms)\" << std::endl << \"| \" << std::endl;\n } else {\n std::cout << std::endl << \"| \" << _t.first << \":\\033[1;31m FAILED!\\033[0m (\" << std::fixed << std::setprecision(3) << (double)time\/1000.0 << \" ms)\" << std::endl << \"| \" << std::endl;\n }\n \n return passed;\n }\n\n void ___print_group_name(std::string _g) {\n int a = (77-(int)_g.size())\/2; if (a<0) a=0;\n int b = 77-(77+(int)_g.size())\/2; if (b<0) b=0;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n std::cout << \"|\" << std::string((size_t)a, ' ') << \"\\033[1m\" << _g << \"\\033[0m\" << std::string((size_t)b, ' ') << ' ' << std::endl;\n std::cout << \"|\" << std::endl;\n \/\/std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n }\n\n void ___print_group_summary(std::string _g, unsigned _passes, unsigned _total) {\n std::stringstream ts;\n ts.str(\"\"); ts.clear();\n ts << _g << \" summary \" << (_passes == _total?\"\\033[1;32m\":\"\\033[1;31m\") << _passes << \" of \" << _total << \" passed\\033[0m\";\n int a = (77-((int)ts.str().size()-11))\/2; if (a<0) a=0;\n int b = 77-(77+((int)ts.str().size()-11))\/2; if (b<0) b=0;\n \/\/std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n std::cout << \"|\" << std::endl;\n std::cout << \"|\" << std::string((size_t)a, ' ') << ts.str() << std::string((size_t)b, ' ') << ' ' << std::endl;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n }\n\n _noreturn_ void ___catch_signals(int _sig) {\n XERUS_THROW(MISC::generic_error() << \"signal \" << _sig << \" = \" << strsignal(_sig) << \"callstack:\\n\" << MISC::get_call_stack());\n }\n\n #undef main\n int main(int argc, char* argv[]) {\n \/\/ \tsignal(SIGINT, ___catch_signals); \/\/ users ctrl+c should actually terminate the program\n \/\/ \tsignal(SIGTERM, ___catch_signals);\n \/\/ \tsignal(SIGHUP, ___catch_signals);\n \/\/signal(SIGABRT,___catch_signals); \/\/ common source of abort is \"double free or corurption\" in which case we cannot continue\n signal(SIGFPE,___catch_signals);\n signal(SIGILL,___catch_signals);\n signal(SIGSEGV,___catch_signals);\n \n \/\/Calculate complete time\n std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now();\n \n std::cout << \"###############################################################################\" << std::endl;\n std::cout << \"# unit-testing #\" << std::endl;\n std::cout << \"###############################################################################\" << std::endl;\n if (argc < 2) {\n std::cout << \"usage:\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" [groupname] ...\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" [groupname]:[testname] ...\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" all\" << std::endl << std::endl;\n std::cout << \"available groups:\" << std::endl;\n for (const auto &p : *___UnitTest::tests) {\n std::cout << \"# \" << p.first << std::endl;\n }\n return 0;\n }\n \n unsigned passCount=0;\n unsigned totalPassCount=0; \n unsigned totalCount=0;\n \n for (int currArg = 1; currArg < argc; ++currArg) {\n std::string grp = argv[currArg];\n \/\/ do all unit tests\n if (grp == \"all\") {\n for (const auto &p : *___UnitTest::tests) {\n ___print_group_name(p.first);\n passCount=0;\n for (const auto &t : p.second) {\n totalCount += 1;\n if (___test(t)) {\n passCount += 1;\n totalPassCount += 1;\n }\n }\n ___print_group_summary(p.first, passCount, (unsigned)p.second.size());\n }\n break;\n }\n \/\/ explicit test inside a group?\n std::vector<std::string> cmd = MISC_NAMESPACE::explode(grp,':');\n if (cmd.size()>1) {\n if ((*___UnitTest::tests)[cmd[0]].count(cmd[1]) == 0) {\n std::cout << \"########## \\033[1;31munknown unittest '\" << cmd[0] << \":\" << cmd[1] << \"'\\033[0m\" << std::endl;\n continue;\n }\n totalCount += 1;\n if (___test({grp, (*___UnitTest::tests)[cmd[0]][cmd[1]]}) ) {\n totalPassCount += 1;\n }\n } else {\n \/\/ unknown group\n if (___UnitTest::tests->count(grp) == 0) {\n std::cout << \"########## \\033[1;31munknown group or unittest '\" << grp << \"'\\033[0m\" << std::endl;\n continue;\n }\n \/\/ one (whole) group\n ___print_group_name(grp);\n passCount=0; \n for (const auto &t : (*___UnitTest::tests)[grp]) {\n totalCount += 1;\n if (___test(t)) {\n passCount += 1;\n totalPassCount += 1;\n }\n }\n ___print_group_summary(grp, passCount, (unsigned)(*___UnitTest::tests)[grp].size());\n }\n }\n \n \/\/Calc total elapsed time\n std::chrono::microseconds::rep totalTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - startTime).count();\n \n ___print_group_summary(\"total\", totalPassCount, totalCount);\n \n std::cout << \"|\" << std::endl;\n std::cout << \"|\" << std::string(23, ' ') << \"Total time elapsed: \" << (double)totalTime\/1000.0 << \" ms\" << std::string(50, ' ') << ' ' << std::endl;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t\/\/ check whether all REQUIRED_TESTs were tested\n\t\tstd::map<std::string, std::pair<size_t, size_t>> perFile;\n\t\t\n\t\tfor (auto &t : (*___RequiredTest::tests)) {\n\/\/ \t\t\tstd::cout << MISC::demangle_cxa(t.first.functionName) << \" (\" << t.first.filename << \":\" << t.first.lineNumber << \")\" << t.second << std::endl;\n\t\t\tstd::pair<size_t, size_t> &pf = perFile[t.first.filename];\n\t\t\tpf.second += 1;\n\t\t\tif (t.second == 0) {\n\t\t\t\tstd::cout << \"\\033[1;31m missing test for function \\033[0m\" \n\t\t\t\t\t<< MISC::demangle_cxa(t.first.functionName) << \" (\" << t.first.filename << \":\" << t.first.lineNumber << \")\" << std::endl;\n\t\t\t} else {\n\t\t\t\tpf.first += 1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (auto &f : perFile) {\n\t\t\tstd::pair<size_t, size_t> &fstats = f.second;\n\t\t\tif (fstats.first == fstats.second) {\n\t\t\t\tstd::cout << \"file \" << f.first << \" :\\033[1;32m \" << fstats.first << \" of \" << fstats.second << \" tests performed\\033[0m\" << std::endl;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"file \" << f.first << \" :\\033[1;31m \" << fstats.first << \" of \" << fstats.second << \" tests performed\\033[0m\" << std::endl;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ destroy all stored tests to make memory-leak detection simpler\n\t\tdelete ___UnitTest::tests;\n\t\tdelete ___RequiredTest::tests;\n \n return totalPassCount != totalCount;\n }\n\n #define main(...) ___horst_main_will_not_be_called( __VA_ARGS__ )\n#endif\n<commit_msg>closes #30 - test.cpp correctly detects if the map of unittests was never created (ie. no unit tests defined)<commit_after>\/\/ Xerus - A General Purpose Tensor Library\n\/\/ Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf. \n\/\/ \n\/\/ Xerus is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published\n\/\/ by the Free Software Foundation, either version 3 of the License,\n\/\/ or (at your option) any later version.\n\/\/ \n\/\/ Xerus is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Xerus. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\/\/ For further information on Xerus visit https:\/\/libXerus.org \n\/\/ or contact us at contact@libXerus.org.\n\n#ifdef TEST_\n\n #include \"standard.h\"\n #include \"exceptions.h\"\n #include <iostream>\n #include <iomanip>\n #include <chrono>\n #include <signal.h>\n #include <sstream>\n\n #include <string.h> \/\/ for strsignal\n\n #include \"testManager.h\"\n #include \"stringUtilities.h\"\n#include <sys\/stat.h>\n\n std::map<std::string, std::map<std::string, std::function<bool ()>>> *___UnitTest::tests;\n\tstd::map<___RequiredTest::identifier, size_t> *___RequiredTest::tests;\n\n bool ___test(const std::pair<std::string, std::function<bool ()>> &_t) {\n bool passed = false;\n \n std::cout << \"| \" << _t.first << \" starting: \" << std::flush;\n \n std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();\n try {\n passed = _t.second(); \/\/ executes the test\n } catch (const MISC::generic_error &e) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught xerus::generic_error():\" << std::endl;\n std::cerr << e.what() << std::endl;\n passed = false;\n } catch (const std::exception &e) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught std::exception:\" << std::endl;\n std::cerr << e.what() << std::endl;\n passed = false;\n } catch (...) {\n std::cout << u8\"\\033[1;31m\\u2717 \\033[0m\" << std::endl;\n std::cerr << \"| Test has thrown an uncaught unknown exception...\" << std::endl;\n passed = false;\n }\n std::chrono::microseconds::rep time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();\n \n if (passed) { \n std::cout << std::endl << \"| \" << _t.first << \":\\033[1;32m passed!\\033[0m (\" << std::fixed << std::setprecision(3) << (double)time\/1000.0 << \" ms)\" << std::endl << \"| \" << std::endl;\n } else {\n std::cout << std::endl << \"| \" << _t.first << \":\\033[1;31m FAILED!\\033[0m (\" << std::fixed << std::setprecision(3) << (double)time\/1000.0 << \" ms)\" << std::endl << \"| \" << std::endl;\n }\n \n return passed;\n }\n\n void ___print_group_name(std::string _g) {\n int a = (77-(int)_g.size())\/2; if (a<0) a=0;\n int b = 77-(77+(int)_g.size())\/2; if (b<0) b=0;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n std::cout << \"|\" << std::string((size_t)a, ' ') << \"\\033[1m\" << _g << \"\\033[0m\" << std::string((size_t)b, ' ') << ' ' << std::endl;\n std::cout << \"|\" << std::endl;\n \/\/std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n }\n\n void ___print_group_summary(std::string _g, unsigned _passes, unsigned _total) {\n std::stringstream ts;\n ts.str(\"\"); ts.clear();\n ts << _g << \" summary \" << (_passes == _total?\"\\033[1;32m\":\"\\033[1;31m\") << _passes << \" of \" << _total << \" passed\\033[0m\";\n int a = (77-((int)ts.str().size()-11))\/2; if (a<0) a=0;\n int b = 77-(77+((int)ts.str().size()-11))\/2; if (b<0) b=0;\n \/\/std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n std::cout << \"|\" << std::endl;\n std::cout << \"|\" << std::string((size_t)a, ' ') << ts.str() << std::string((size_t)b, ' ') << ' ' << std::endl;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n }\n\n _noreturn_ void ___catch_signals(int _sig) {\n XERUS_THROW(MISC::generic_error() << \"signal \" << _sig << \" = \" << strsignal(_sig) << \"callstack:\\n\" << MISC::get_call_stack());\n }\n\n #undef main\n int main(int argc, char* argv[]) {\n \/\/ \tsignal(SIGINT, ___catch_signals); \/\/ users ctrl+c should actually terminate the program\n \/\/ \tsignal(SIGTERM, ___catch_signals);\n \/\/ \tsignal(SIGHUP, ___catch_signals);\n \/\/signal(SIGABRT,___catch_signals); \/\/ common source of abort is \"double free or corurption\" in which case we cannot continue\n signal(SIGFPE,___catch_signals);\n signal(SIGILL,___catch_signals);\n signal(SIGSEGV,___catch_signals);\n \n \/\/Calculate complete time\n std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now();\n \n std::cout << \"###############################################################################\" << std::endl;\n std::cout << \"# unit-testing #\" << std::endl;\n std::cout << \"###############################################################################\" << std::endl;\n\t\t\/\/ no unittests defined (ie. the map tests does not exist!)\n\t\tif (!___UnitTest::tests) {\n\t\t\tstd::cout << \"no unittests defined.\" << std::endl;\n\t\t\tstd::cout << \"use the macro UNIT_TEST(group, testname, ...) to define unittests inside the sourcecode.\" << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\t\n if (argc < 2) {\n std::cout << \"usage:\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" [groupname] ...\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" [groupname]:[testname] ...\" << std::endl;\n std::cout << \" \" << MISC_NAMESPACE::explode(argv[0],'\/').back() << \" all\" << std::endl << std::endl;\n std::cout << \"available groups:\" << std::endl;\n for (const auto &p : *___UnitTest::tests) {\n std::cout << \"# \" << p.first << std::endl;\n }\n return 0;\n }\n \n unsigned passCount=0;\n unsigned totalPassCount=0; \n unsigned totalCount=0;\n \n for (int currArg = 1; currArg < argc; ++currArg) {\n std::string grp = argv[currArg];\n \/\/ do all unit tests\n if (grp == \"all\") {\n for (const auto &p : *___UnitTest::tests) {\n ___print_group_name(p.first);\n passCount=0;\n for (const auto &t : p.second) {\n totalCount += 1;\n if (___test(t)) {\n passCount += 1;\n totalPassCount += 1;\n }\n }\n ___print_group_summary(p.first, passCount, (unsigned)p.second.size());\n }\n break;\n }\n \/\/ explicit test inside a group?\n std::vector<std::string> cmd = MISC_NAMESPACE::explode(grp,':');\n if (cmd.size()>1) {\n\t\t\t\tif (cmd.size()>2) {\n std::cout << \"########## \\033[1;31munknown syntax '\" << grp << \"'\\033[0m\" << std::endl;\n continue;\n }\n if (!___UnitTest::tests->count(cmd[0]) || (*___UnitTest::tests)[cmd[0]].count(cmd[1]) == 0) {\n std::cout << \"########## \\033[1;31munknown unittest '\" << cmd[0] << \":\" << cmd[1] << \"'\\033[0m\" << std::endl;\n continue;\n }\n totalCount += 1;\n if (___test({grp, (*___UnitTest::tests)[cmd[0]][cmd[1]]}) ) {\n totalPassCount += 1;\n }\n } else {\n \/\/ unknown group\n if (___UnitTest::tests->count(grp) == 0) {\n std::cout << \"########## \\033[1;31munknown group or unittest '\" << grp << \"'\\033[0m\" << std::endl;\n continue;\n }\n \/\/ one (whole) group\n ___print_group_name(grp);\n passCount=0; \n for (const auto &t : (*___UnitTest::tests)[grp]) {\n totalCount += 1;\n if (___test(t)) {\n passCount += 1;\n totalPassCount += 1;\n }\n }\n ___print_group_summary(grp, passCount, (unsigned)(*___UnitTest::tests)[grp].size());\n }\n }\n \n \/\/Calc total elapsed time\n std::chrono::microseconds::rep totalTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - startTime).count();\n \n ___print_group_summary(\"total\", totalPassCount, totalCount);\n \n std::cout << \"|\" << std::endl;\n std::cout << \"|\" << std::string(23, ' ') << \"Total time elapsed: \" << (double)totalTime\/1000.0 << \" ms\" << std::string(50, ' ') << ' ' << std::endl;\n std::cout << \"-------------------------------------------------------------------------------\" << std::endl;\n\t\t\n\t\t\/\/ check whether all REQUIRED_TESTs were tested\n\t\tstd::map<std::string, std::pair<size_t, size_t>> perFile;\n\t\t\n\t\tfor (auto &t : (*___RequiredTest::tests)) {\n\/\/ \t\t\tstd::cout << MISC::demangle_cxa(t.first.functionName) << \" (\" << t.first.filename << \":\" << t.first.lineNumber << \")\" << t.second << std::endl;\n\t\t\tstd::pair<size_t, size_t> &pf = perFile[t.first.filename];\n\t\t\tpf.second += 1;\n\t\t\tif (t.second == 0) {\n\t\t\t\tstd::cout << \"\\033[1;31m missing test for function \\033[0m\" \n\t\t\t\t\t<< MISC::demangle_cxa(t.first.functionName) << \" (\" << t.first.filename << \":\" << t.first.lineNumber << \")\" << std::endl;\n\t\t\t} else {\n\t\t\t\tpf.first += 1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (auto &f : perFile) {\n\t\t\tstd::pair<size_t, size_t> &fstats = f.second;\n\t\t\tif (fstats.first == fstats.second) {\n\t\t\t\tstd::cout << \"file \" << f.first << \" :\\033[1;32m \" << fstats.first << \" of \" << fstats.second << \" tests performed\\033[0m\" << std::endl;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"file \" << f.first << \" :\\033[1;31m \" << fstats.first << \" of \" << fstats.second << \" tests performed\\033[0m\" << std::endl;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ destroy all stored tests to make memory-leak detection simpler\n\t\tdelete ___UnitTest::tests;\n\t\tdelete ___RequiredTest::tests;\n \n return totalPassCount != totalCount;\n }\n\n #define main(...) ___horst_main_will_not_be_called( __VA_ARGS__ )\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include <QDataStream>\n\n#include \"QXmppCodec.h\"\n#include \"QXmppJingleIq.h\"\n#include \"QXmppRtpChannel.h\"\n\n\/\/#define QXMPP_DEBUG_RTP\n#define SAMPLE_BYTES 2\n\nconst quint8 RTP_VERSION = 0x02;\n\nclass QXmppRtpChannelPrivate\n{\npublic:\n QXmppRtpChannelPrivate();\n\n \/\/ signals\n bool signalsEmitted;\n qint64 writtenSinceLastEmit;\n\n \/\/ RTP\n QXmppCodec *codec;\n QHostAddress remoteHost;\n quint16 remotePort;\n\n QByteArray incomingBuffer;\n bool incomingBuffering;\n int incomingMinimum;\n int incomingMaximum;\n quint16 incomingSequence;\n quint32 incomingStamp;\n\n quint16 outgoingChunk;\n QByteArray outgoingBuffer;\n bool outgoingMarker;\n quint16 outgoingSequence;\n quint32 outgoingStamp;\n\n quint32 ssrc;\n QXmppJinglePayloadType payloadType;\n};\n\nQXmppRtpChannelPrivate::QXmppRtpChannelPrivate()\n : signalsEmitted(false),\n writtenSinceLastEmit(0),\n codec(0),\n incomingBuffering(true),\n incomingMinimum(0),\n incomingMaximum(0),\n incomingSequence(0),\n incomingStamp(0),\n outgoingMarker(true),\n outgoingSequence(0),\n outgoingStamp(0),\n ssrc(0)\n{\n ssrc = qrand();\n}\n\n\/\/\/ Creates a new RTP channel.\n\/\/\/\n\/\/\/ \\param parent\n\nQXmppRtpChannel::QXmppRtpChannel(QObject *parent)\n : QIODevice(parent),\n d(new QXmppRtpChannelPrivate)\n{\n QXmppLoggable *logParent = qobject_cast<QXmppLoggable*>(parent);\n if (logParent) {\n connect(this, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),\n logParent, SIGNAL(logMessage(QXmppLogger::MessageType,QString)));\n }\n}\n\n\/\/\/ Destroys an RTP channel.\n\/\/\/\n\nQXmppRtpChannel::~QXmppRtpChannel()\n{\n delete d;\n}\n\n\/\/\/ Returns the number of bytes that are available for reading.\n\/\/\/\n\nqint64 QXmppRtpChannel::bytesAvailable() const\n{\n return d->incomingBuffer.size();\n}\n\n\/\/\/ Processes an incoming RTP packet.\n\/\/\/\n\/\/\/ \\param ba\nvoid QXmppRtpChannel::datagramReceived(const QByteArray &ba)\n{\n if (!d->codec)\n {\n warning(\"QXmppRtpChannel::datagramReceived before codec selection\");\n return;\n }\n\n if (ba.size() < 12 || (quint8(ba.at(0)) >> 6) != RTP_VERSION)\n {\n warning(\"QXmppRtpChannel::datagramReceived got an invalid RTP packet\");\n return;\n }\n\n \/\/ parse RTP header\n QDataStream stream(ba);\n quint8 version, marker_type;\n quint32 ssrc;\n quint16 sequence;\n quint32 stamp;\n stream >> version;\n stream >> marker_type;\n stream >> sequence;\n stream >> stamp;\n stream >> ssrc;\n const bool marker = marker_type & 0x80;\n const quint8 type = marker_type & 0x7f;\n const qint64 packetLength = ba.size() - 12;\n\n#ifdef QXMPP_DEBUG_RTP\n logReceived(QString(\"RTP packet seq %1 stamp %2 marker %3 type %4 size %5\").arg(\n QString::number(sequence),\n QString::number(stamp),\n QString::number(marker),\n QString::number(type),\n QString::number(packetLength)));\n#endif\n\n \/\/ check type\n if (type != d->payloadType.id())\n {\n warning(QString(\"RTP packet seq %1 has unknown type %2\")\n .arg(QString::number(sequence))\n .arg(QString::number(type)));\n return;\n }\n\n \/\/ check sequence number\n if (!marker && sequence != d->incomingSequence + 1)\n warning(QString(\"RTP packet seq %1 is out of order, previous was %2\")\n .arg(QString::number(sequence))\n .arg(QString::number(d->incomingSequence)));\n d->incomingSequence = sequence;\n\n \/\/ determine packet's position in the buffer (in bytes)\n qint64 packetOffset = 0;\n if (!d->incomingBuffer.isEmpty())\n {\n packetOffset = (stamp - d->incomingStamp) * SAMPLE_BYTES;\n if (packetOffset < 0)\n {\n warning(QString(\"RTP packet stamp %1 is too old, buffer start is %2\")\n .arg(QString::number(stamp))\n .arg(QString::number(d->incomingStamp)));\n return;\n }\n } else {\n d->incomingStamp = stamp;\n }\n\n \/\/ allocate space for new packet\n if (packetOffset + packetLength > d->incomingBuffer.size())\n d->incomingBuffer += QByteArray(packetOffset + packetLength - d->incomingBuffer.size(), 0);\n QDataStream output(&d->incomingBuffer, QIODevice::WriteOnly);\n output.device()->seek(packetOffset);\n output.setByteOrder(QDataStream::LittleEndian);\n d->codec->decode(stream, output);\n\n \/\/ check whether we are running late\n if (d->incomingBuffer.size() > d->incomingMaximum)\n {\n const qint64 droppedSize = d->incomingBuffer.size() - d->incomingMinimum;\n debug(QString(\"RTP buffer is too full, dropping %1 bytes\")\n .arg(QString::number(droppedSize)));\n d->incomingBuffer = d->incomingBuffer.right(d->incomingMinimum);\n d->incomingStamp += droppedSize \/ SAMPLE_BYTES;\n }\n \/\/ check whether we have filled the initial buffer\n if (d->incomingBuffer.size() >= d->incomingMinimum)\n d->incomingBuffering = false;\n if (!d->incomingBuffering)\n emit readyRead();\n}\n\nvoid QXmppRtpChannel::emitSignals()\n{\n emit bytesWritten(d->writtenSinceLastEmit);\n d->writtenSinceLastEmit = 0;\n d->signalsEmitted = false;\n}\n\n\/\/\/ Returns true, as the RTP channel is a sequential device.\n\/\/\/\n\nbool QXmppRtpChannel::isSequential() const\n{\n return true;\n}\n\nqint64 QXmppRtpChannel::readData(char * data, qint64 maxSize)\n{\n \/\/ if we are filling the buffer, return empty samples\n if (d->incomingBuffering)\n {\n memset(data, 0, maxSize);\n return maxSize;\n }\n\n qint64 readSize = qMin(maxSize, qint64(d->incomingBuffer.size()));\n memcpy(data, d->incomingBuffer.constData(), readSize);\n d->incomingBuffer.remove(0, readSize);\n if (readSize < maxSize)\n {\n#ifdef QXMPP_DEBUG_RTP\n debug(QString(\"QXmppRtpChannel::readData missing %1 bytes\").arg(QString::number(maxSize - readSize)));\n#endif\n memset(data + readSize, 0, maxSize - readSize);\n }\n d->incomingStamp += readSize \/ SAMPLE_BYTES;\n return maxSize;\n}\n\n\/\/\/ Returns the RTP channel's payload type.\n\/\/\/\n\/\/\/ You can use this to determine the QAudioFormat to use with your\n\/\/\/ QAudioInput\/QAudioOutput.\n\nQXmppJinglePayloadType QXmppRtpChannel::payloadType() const\n{\n return d->payloadType;\n}\n\n\/\/\/ Sets the RTP channel's payload type.\n\/\/\/\n\/\/\/ \\param payloadType\n\nvoid QXmppRtpChannel::setPayloadType(const QXmppJinglePayloadType &payloadType)\n{\n d->payloadType = payloadType;\n if (payloadType.id() == G711u)\n d->codec = new QXmppG711uCodec(payloadType.clockrate());\n else if (payloadType.id() == G711a)\n d->codec = new QXmppG711aCodec(payloadType.clockrate());\n#ifdef QXMPP_USE_SPEEX\n else if (payloadType.name().toLower() == \"speex\")\n d->codec = new QXmppSpeexCodec(payloadType.clockrate());\n#endif\n else\n {\n warning(QString(\"QXmppCall got an unknown codec : %1 (%2)\")\n .arg(QString::number(payloadType.id()))\n .arg(payloadType.name()));\n return;\n }\n\n \/\/ size in bytes of an unencoded packet\n d->outgoingChunk = SAMPLE_BYTES * payloadType.ptime() * payloadType.clockrate() \/ 1000;\n\n \/\/ initial number of bytes to buffer\n d->incomingMinimum = d->outgoingChunk * 5;\n d->incomingMaximum = d->outgoingChunk * 8;\n\n open(QIODevice::ReadWrite | QIODevice::Unbuffered);\n}\n\n\/\/\/ Returns the list of supported payload types.\n\/\/\/\n\nQList<QXmppJinglePayloadType> QXmppRtpChannel::supportedPayloadTypes() const\n{\n QList<QXmppJinglePayloadType> payloads;\n QXmppJinglePayloadType payload;\n\n#ifdef QXMPP_USE_SPEEX\n payload.setId(96);\n payload.setChannels(1);\n payload.setName(\"SPEEX\");\n payload.setClockrate(16000);\n payloads << payload;\n\n payload.setId(97);\n payload.setChannels(1);\n payload.setName(\"SPEEX\");\n payload.setClockrate(8000);\n payloads << payload;\n#endif\n\n payload.setId(QXmppRtpChannel::G711u);\n payload.setChannels(1);\n payload.setName(\"PCMU\");\n payload.setClockrate(8000);\n payloads << payload;\n\n payload.setId(QXmppRtpChannel::G711a);\n payload.setChannels(1);\n payload.setName(\"PCMA\");\n payload.setClockrate(8000);\n payloads << payload;\n\n return payloads;\n}\n\nqint64 QXmppRtpChannel::writeData(const char * data, qint64 maxSize)\n{\n if (!d->codec)\n {\n warning(\"QXmppRtpChannel::writeData before codec was set\");\n return -1;\n }\n\n d->outgoingBuffer += QByteArray::fromRawData(data, maxSize);\n while (d->outgoingBuffer.size() >= d->outgoingChunk)\n {\n QByteArray header;\n QDataStream stream(&header, QIODevice::WriteOnly);\n quint8 version = RTP_VERSION << 6;\n stream << version;\n quint8 marker_type = d->payloadType.id();\n if (d->outgoingMarker)\n {\n marker_type |= 0x80;\n d->outgoingMarker= false;\n }\n stream << marker_type;\n stream << ++d->outgoingSequence;\n stream << d->outgoingStamp;\n stream << d->ssrc;\n\n QByteArray chunk = d->outgoingBuffer.left(d->outgoingChunk);\n QDataStream input(chunk);\n input.setByteOrder(QDataStream::LittleEndian);\n d->outgoingStamp += d->codec->encode(input, stream);\n\n#ifdef QXMPP_DEBUG_RTP\n logSent(QString(\"RTP packet seq %1 stamp %2 marker %3 type %4 size %5\").arg(\n QString::number(d->outgoingSequence),\n QString::number(d->outgoingStamp),\n QString::number(marker_type & 0x80 != 0),\n QString::number(marker_type & 0x7f),\n QString::number(header.size() - 12)));\n#endif\n emit sendDatagram(header);\n\n d->outgoingBuffer.remove(0, chunk.size());\n }\n\n d->writtenSinceLastEmit += maxSize;\n if (!d->signalsEmitted && !signalsBlocked()) {\n d->signalsEmitted = true;\n QMetaObject::invokeMethod(this, \"emitSignals\", Qt::QueuedConnection);\n }\n\n return maxSize;\n}\n<commit_msg>fix a spurious RTP warning<commit_after>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include <QDataStream>\n\n#include \"QXmppCodec.h\"\n#include \"QXmppJingleIq.h\"\n#include \"QXmppRtpChannel.h\"\n\n\/\/#define QXMPP_DEBUG_RTP\n#define SAMPLE_BYTES 2\n\nconst quint8 RTP_VERSION = 0x02;\n\nclass QXmppRtpChannelPrivate\n{\npublic:\n QXmppRtpChannelPrivate();\n\n \/\/ signals\n bool signalsEmitted;\n qint64 writtenSinceLastEmit;\n\n \/\/ RTP\n QXmppCodec *codec;\n QHostAddress remoteHost;\n quint16 remotePort;\n\n QByteArray incomingBuffer;\n bool incomingBuffering;\n int incomingMinimum;\n int incomingMaximum;\n quint16 incomingSequence;\n quint32 incomingStamp;\n\n quint16 outgoingChunk;\n QByteArray outgoingBuffer;\n bool outgoingMarker;\n quint16 outgoingSequence;\n quint32 outgoingStamp;\n\n quint32 ssrc;\n QXmppJinglePayloadType payloadType;\n};\n\nQXmppRtpChannelPrivate::QXmppRtpChannelPrivate()\n : signalsEmitted(false),\n writtenSinceLastEmit(0),\n codec(0),\n incomingBuffering(true),\n incomingMinimum(0),\n incomingMaximum(0),\n incomingSequence(0),\n incomingStamp(0),\n outgoingMarker(true),\n outgoingSequence(0),\n outgoingStamp(0),\n ssrc(0)\n{\n ssrc = qrand();\n}\n\n\/\/\/ Creates a new RTP channel.\n\/\/\/\n\/\/\/ \\param parent\n\nQXmppRtpChannel::QXmppRtpChannel(QObject *parent)\n : QIODevice(parent),\n d(new QXmppRtpChannelPrivate)\n{\n QXmppLoggable *logParent = qobject_cast<QXmppLoggable*>(parent);\n if (logParent) {\n connect(this, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),\n logParent, SIGNAL(logMessage(QXmppLogger::MessageType,QString)));\n }\n}\n\n\/\/\/ Destroys an RTP channel.\n\/\/\/\n\nQXmppRtpChannel::~QXmppRtpChannel()\n{\n delete d;\n}\n\n\/\/\/ Returns the number of bytes that are available for reading.\n\/\/\/\n\nqint64 QXmppRtpChannel::bytesAvailable() const\n{\n return d->incomingBuffer.size();\n}\n\n\/\/\/ Processes an incoming RTP packet.\n\/\/\/\n\/\/\/ \\param ba\nvoid QXmppRtpChannel::datagramReceived(const QByteArray &ba)\n{\n if (!d->codec)\n {\n warning(\"QXmppRtpChannel::datagramReceived before codec selection\");\n return;\n }\n\n if (ba.size() < 12 || (quint8(ba.at(0)) >> 6) != RTP_VERSION)\n {\n warning(\"QXmppRtpChannel::datagramReceived got an invalid RTP packet\");\n return;\n }\n\n \/\/ parse RTP header\n QDataStream stream(ba);\n quint8 version, marker_type;\n quint32 ssrc;\n quint16 sequence;\n quint32 stamp;\n stream >> version;\n stream >> marker_type;\n stream >> sequence;\n stream >> stamp;\n stream >> ssrc;\n const bool marker = marker_type & 0x80;\n const quint8 type = marker_type & 0x7f;\n const qint64 packetLength = ba.size() - 12;\n\n#ifdef QXMPP_DEBUG_RTP\n logReceived(QString(\"RTP packet seq %1 stamp %2 marker %3 type %4 size %5\").arg(\n QString::number(sequence),\n QString::number(stamp),\n QString::number(marker),\n QString::number(type),\n QString::number(packetLength)));\n#endif\n\n \/\/ check type\n if (type != d->payloadType.id())\n {\n warning(QString(\"RTP packet seq %1 has unknown type %2\")\n .arg(QString::number(sequence))\n .arg(QString::number(type)));\n return;\n }\n\n \/\/ check sequence number\n if (d->incomingSequence && sequence != d->incomingSequence + 1)\n warning(QString(\"RTP packet seq %1 is out of order, previous was %2\")\n .arg(QString::number(sequence))\n .arg(QString::number(d->incomingSequence)));\n d->incomingSequence = sequence;\n\n \/\/ determine packet's position in the buffer (in bytes)\n qint64 packetOffset = 0;\n if (!d->incomingBuffer.isEmpty())\n {\n packetOffset = (stamp - d->incomingStamp) * SAMPLE_BYTES;\n if (packetOffset < 0)\n {\n warning(QString(\"RTP packet stamp %1 is too old, buffer start is %2\")\n .arg(QString::number(stamp))\n .arg(QString::number(d->incomingStamp)));\n return;\n }\n } else {\n d->incomingStamp = stamp;\n }\n\n \/\/ allocate space for new packet\n if (packetOffset + packetLength > d->incomingBuffer.size())\n d->incomingBuffer += QByteArray(packetOffset + packetLength - d->incomingBuffer.size(), 0);\n QDataStream output(&d->incomingBuffer, QIODevice::WriteOnly);\n output.device()->seek(packetOffset);\n output.setByteOrder(QDataStream::LittleEndian);\n d->codec->decode(stream, output);\n\n \/\/ check whether we are running late\n if (d->incomingBuffer.size() > d->incomingMaximum)\n {\n const qint64 droppedSize = d->incomingBuffer.size() - d->incomingMinimum;\n debug(QString(\"RTP buffer is too full, dropping %1 bytes\")\n .arg(QString::number(droppedSize)));\n d->incomingBuffer = d->incomingBuffer.right(d->incomingMinimum);\n d->incomingStamp += droppedSize \/ SAMPLE_BYTES;\n }\n \/\/ check whether we have filled the initial buffer\n if (d->incomingBuffer.size() >= d->incomingMinimum)\n d->incomingBuffering = false;\n if (!d->incomingBuffering)\n emit readyRead();\n}\n\nvoid QXmppRtpChannel::emitSignals()\n{\n emit bytesWritten(d->writtenSinceLastEmit);\n d->writtenSinceLastEmit = 0;\n d->signalsEmitted = false;\n}\n\n\/\/\/ Returns true, as the RTP channel is a sequential device.\n\/\/\/\n\nbool QXmppRtpChannel::isSequential() const\n{\n return true;\n}\n\nqint64 QXmppRtpChannel::readData(char * data, qint64 maxSize)\n{\n \/\/ if we are filling the buffer, return empty samples\n if (d->incomingBuffering)\n {\n memset(data, 0, maxSize);\n return maxSize;\n }\n\n qint64 readSize = qMin(maxSize, qint64(d->incomingBuffer.size()));\n memcpy(data, d->incomingBuffer.constData(), readSize);\n d->incomingBuffer.remove(0, readSize);\n if (readSize < maxSize)\n {\n#ifdef QXMPP_DEBUG_RTP\n debug(QString(\"QXmppRtpChannel::readData missing %1 bytes\").arg(QString::number(maxSize - readSize)));\n#endif\n memset(data + readSize, 0, maxSize - readSize);\n }\n d->incomingStamp += readSize \/ SAMPLE_BYTES;\n return maxSize;\n}\n\n\/\/\/ Returns the RTP channel's payload type.\n\/\/\/\n\/\/\/ You can use this to determine the QAudioFormat to use with your\n\/\/\/ QAudioInput\/QAudioOutput.\n\nQXmppJinglePayloadType QXmppRtpChannel::payloadType() const\n{\n return d->payloadType;\n}\n\n\/\/\/ Sets the RTP channel's payload type.\n\/\/\/\n\/\/\/ \\param payloadType\n\nvoid QXmppRtpChannel::setPayloadType(const QXmppJinglePayloadType &payloadType)\n{\n d->payloadType = payloadType;\n if (payloadType.id() == G711u)\n d->codec = new QXmppG711uCodec(payloadType.clockrate());\n else if (payloadType.id() == G711a)\n d->codec = new QXmppG711aCodec(payloadType.clockrate());\n#ifdef QXMPP_USE_SPEEX\n else if (payloadType.name().toLower() == \"speex\")\n d->codec = new QXmppSpeexCodec(payloadType.clockrate());\n#endif\n else\n {\n warning(QString(\"QXmppCall got an unknown codec : %1 (%2)\")\n .arg(QString::number(payloadType.id()))\n .arg(payloadType.name()));\n return;\n }\n\n \/\/ size in bytes of an unencoded packet\n d->outgoingChunk = SAMPLE_BYTES * payloadType.ptime() * payloadType.clockrate() \/ 1000;\n\n \/\/ initial number of bytes to buffer\n d->incomingMinimum = d->outgoingChunk * 5;\n d->incomingMaximum = d->outgoingChunk * 8;\n\n open(QIODevice::ReadWrite | QIODevice::Unbuffered);\n}\n\n\/\/\/ Returns the list of supported payload types.\n\/\/\/\n\nQList<QXmppJinglePayloadType> QXmppRtpChannel::supportedPayloadTypes() const\n{\n QList<QXmppJinglePayloadType> payloads;\n QXmppJinglePayloadType payload;\n\n#ifdef QXMPP_USE_SPEEX\n payload.setId(96);\n payload.setChannels(1);\n payload.setName(\"SPEEX\");\n payload.setClockrate(16000);\n payloads << payload;\n\n payload.setId(97);\n payload.setChannels(1);\n payload.setName(\"SPEEX\");\n payload.setClockrate(8000);\n payloads << payload;\n#endif\n\n payload.setId(QXmppRtpChannel::G711u);\n payload.setChannels(1);\n payload.setName(\"PCMU\");\n payload.setClockrate(8000);\n payloads << payload;\n\n payload.setId(QXmppRtpChannel::G711a);\n payload.setChannels(1);\n payload.setName(\"PCMA\");\n payload.setClockrate(8000);\n payloads << payload;\n\n return payloads;\n}\n\nqint64 QXmppRtpChannel::writeData(const char * data, qint64 maxSize)\n{\n if (!d->codec)\n {\n warning(\"QXmppRtpChannel::writeData before codec was set\");\n return -1;\n }\n\n d->outgoingBuffer += QByteArray::fromRawData(data, maxSize);\n while (d->outgoingBuffer.size() >= d->outgoingChunk)\n {\n QByteArray header;\n QDataStream stream(&header, QIODevice::WriteOnly);\n quint8 version = RTP_VERSION << 6;\n stream << version;\n quint8 marker_type = d->payloadType.id();\n if (d->outgoingMarker)\n {\n marker_type |= 0x80;\n d->outgoingMarker= false;\n }\n stream << marker_type;\n stream << ++d->outgoingSequence;\n stream << d->outgoingStamp;\n stream << d->ssrc;\n\n QByteArray chunk = d->outgoingBuffer.left(d->outgoingChunk);\n QDataStream input(chunk);\n input.setByteOrder(QDataStream::LittleEndian);\n d->outgoingStamp += d->codec->encode(input, stream);\n\n#ifdef QXMPP_DEBUG_RTP\n logSent(QString(\"RTP packet seq %1 stamp %2 marker %3 type %4 size %5\").arg(\n QString::number(d->outgoingSequence),\n QString::number(d->outgoingStamp),\n QString::number(marker_type & 0x80 != 0),\n QString::number(marker_type & 0x7f),\n QString::number(header.size() - 12)));\n#endif\n emit sendDatagram(header);\n\n d->outgoingBuffer.remove(0, chunk.size());\n }\n\n d->writtenSinceLastEmit += maxSize;\n if (!d->signalsEmitted && !signalsBlocked()) {\n d->signalsEmitted = true;\n QMetaObject::invokeMethod(this, \"emitSignals\", Qt::QueuedConnection);\n }\n\n return maxSize;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* MIT License\n*\n* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>\n*\n* This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\/\n\n#include \"Recorder.h\"\n#include \"Common\/config.h\"\n#include \"MP4Recorder.h\"\n#include \"HlsRecorder.h\"\n\nusing namespace toolkit;\n\nnamespace mediakit {\n\nMediaSinkInterface *createHlsRecorder(const string &strVhost_tmp, const string &strApp, const string &strId) {\n#if defined(ENABLE_HLS)\n GET_CONFIG(bool, enableVhost, General::kEnableVhost);\n GET_CONFIG(string, hlsPath, Hls::kFilePath);\n\n string strVhost = strVhost_tmp;\n if (trim(strVhost).empty()) {\n \/\/如果strVhost为空,则强制为默认虚拟主机\n strVhost = DEFAULT_VHOST;\n }\n\n string m3u8FilePath;\n string params;\n if (enableVhost) {\n m3u8FilePath = strVhost + \"\/\" + strApp + \"\/\" + strId + \"\/hls.m3u8\";\n params = string(VHOST_KEY) + \"=\" + strVhost;\n } else {\n m3u8FilePath = strApp + \"\/\" + strId + \"\/hls.m3u8\";\n }\n m3u8FilePath = File::absolutePath(m3u8FilePath, hlsPath);\n return new HlsRecorder(m3u8FilePath, params);\n#else\n return nullptr;\n#endif \/\/defined(ENABLE_HLS)\n}\n\nMediaSinkInterface *createMP4Recorder(const string &strVhost_tmp, const string &strApp, const string &strId) {\n#if defined(ENABLE_MP4RECORD)\n GET_CONFIG(bool, enableVhost, General::kEnableVhost);\n GET_CONFIG(string, recordPath, Record::kFilePath);\n GET_CONFIG(string, recordAppName, Record::kAppName);\n\n string strVhost = strVhost_tmp;\n if (trim(strVhost).empty()) {\n \/\/如果strVhost为空,则强制为默认虚拟主机\n strVhost = DEFAULT_VHOST;\n }\n\n string mp4FilePath;\n if (enableVhost) {\n mp4FilePath = strVhost + \"\/\" + recordAppName + \"\/\" + strApp + \"\/\" + strId + \"\/\";\n } else {\n mp4FilePath = recordAppName + \"\/\" + strApp + \"\/\" + strId + \"\/\";\n }\n mp4FilePath = File::absolutePath(mp4FilePath, recordPath);\n return new MP4Recorder(mp4FilePath, strVhost, strApp, strId);\n#else\n return nullptr;\n#endif \/\/defined(ENABLE_MP4RECORD)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass RecorderHelper {\npublic:\n typedef std::shared_ptr<RecorderHelper> Ptr;\n\n \/**\n * 构建函数\n * @param bContinueRecord false表明hls录制从头开始录制(意味着hls临时文件在媒体反注册时会被删除)\n *\/\n RecorderHelper(const MediaSinkInterface::Ptr &recorder, vector<Track::Ptr> &&tracks , bool bContinueRecord, const string &schema) {\n _recorder = recorder;\n _continueRecord = bContinueRecord;\n _schema = schema;\n attachTracks(std::move(tracks));\n }\n\n ~RecorderHelper() {\n resetTracks();\n }\n\n \/\/ 附则于track上\n void attachTracks(vector<Track::Ptr> &&tracks){\n if(isTracksSame(tracks)){\n return;\n }\n resetTracks();\n _tracks = std::move(tracks);\n for (auto &track : _tracks) {\n _recorder->addTrack(track);\n track->addDelegate(_recorder);\n }\n }\n\n\n \/\/ 判断新的tracks是否与之前的一致\n bool isTracksSame(const vector<Track::Ptr> &tracks){\n if(tracks.size() != _tracks.size()) {\n return false;\n }\n int i = 0;\n for(auto &track : tracks){\n if(track != _tracks[i++]){\n return false;\n }\n }\n return true;\n }\n\n \/\/ 重置所有track\n void resetTracks(){\n if(_tracks.empty()){\n return;\n }\n for (auto &track : _tracks) {\n track->delDelegate(_recorder.get());\n }\n _tracks.clear();\n _recorder->resetTracks();\n }\n\n \/\/ 返回false表明hls录制从头开始录制(意味着hls临时文件在媒体反注册时会被删除)\n bool continueRecord(){\n return _continueRecord;\n }\n\n bool isRecording() {\n return !_tracks.empty();\n }\n\n const string &getSchema() const{\n return _schema;\n }\nprivate:\n MediaSinkInterface::Ptr _recorder;\n vector<Track::Ptr> _tracks;\n bool _continueRecord;\n string _schema;\n};\n\n\ntemplate<Recorder::type type>\nclass MediaSourceWatcher {\npublic:\n static MediaSourceWatcher& Instance(){\n static MediaSourceWatcher instance;\n return instance;\n }\n\n Recorder::status getRecordStatus(const string &vhost, const string &app, const string &stream_id) {\n return getRecordStatus_l(getRecorderKey(vhost, app, stream_id));\n }\n\n int startRecord(const string &vhost, const string &app, const string &stream_id, bool waitForRecord, bool continueRecord) {\n auto key = getRecorderKey(vhost, app, stream_id);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n if (getRecordStatus_l(key) != Recorder::status_not_record) {\n \/\/ 已经在录制了\n return 0;\n }\n\n string schema;\n auto tracks = findTracks(vhost, app, stream_id,schema);\n if (!waitForRecord && tracks.empty()) {\n \/\/ 暂时无法开启录制\n return -1;\n }\n\n auto recorder = MediaSinkInterface::Ptr(createRecorder(vhost, app, stream_id));\n if (!recorder) {\n \/\/ 创建录制器失败\n return -2;\n }\n _recorder_map[key] = std::make_shared<RecorderHelper>(recorder, std::move(tracks), continueRecord, schema);\n return 0;\n }\n\n void stopRecord(const string &vhost, const string &app, const string &stream_id) {\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n _recorder_map.erase(getRecorderKey(vhost, app, stream_id));\n }\n\nprivate:\n MediaSourceWatcher(){\n NoticeCenter::Instance().addListener(this,Broadcast::kBroadcastMediaChanged,[this](BroadcastMediaChangedArgs){\n if(bRegist){\n onRegist(schema,vhost,app,stream,sender);\n }else{\n onUnRegist(schema,vhost,app,stream,sender);\n }\n });\n NoticeCenter::Instance().addListener(this,Broadcast::kBroadcastMediaResetTracks,[this](BroadcastMediaResetTracksArgs){\n onRegist(schema,vhost,app,stream,sender);\n });\n }\n\n ~MediaSourceWatcher(){\n NoticeCenter::Instance().delListener(this,Broadcast::kBroadcastMediaChanged);\n NoticeCenter::Instance().delListener(this,Broadcast::kBroadcastMediaResetTracks);\n }\n\n void onRegist(const string &schema,const string &vhost,const string &app,const string &stream,MediaSource &sender){\n auto key = getRecorderKey(vhost,app,stream);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n auto it = _recorder_map.find(key);\n if(it == _recorder_map.end()){\n \/\/ 录像记录不存在\n return;\n }\n\n auto tracks = sender.getTracks(true);\n if (tracks.empty()) {\n \/\/ 无有效的tracks\n return;\n }\n\n if(it->second->getSchema() == schema){\n \/\/ 绑定的协议一致,替换tracks\n it->second->attachTracks(std::move(tracks));\n }\n\n }\n\n void onUnRegist(const string &schema,const string &vhost,const string &app,const string &stream,MediaSource &sender){\n auto key = getRecorderKey(vhost,app,stream);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n auto it = _recorder_map.find(key);\n if(it == _recorder_map.end()){\n \/\/ 录像记录不存在\n return;\n }\n\n if(it->second->getSchema() != schema){\n \/\/ 绑定的协议不一致\n return;\n }\n if(it->second->continueRecord()){\n \/\/ 如果可以继续录制,那么只重置tracks,不删除对象\n it->second->resetTracks();\n }else{\n \/\/ 删除对象(意味着可能删除hls临时文件)\n _recorder_map.erase(it);\n }\n }\n\n Recorder::status getRecordStatus_l(const string &key) {\n auto it = _recorder_map.find(key);\n if (it == _recorder_map.end()) {\n return Recorder::status_not_record;\n }\n return it->second->isRecording() ? Recorder::status_recording : Recorder::status_wait_record;\n }\n\n \/\/ 查找MediaSource以便录制\n vector<Track::Ptr> findTracks(const string &vhost, const string &app, const string &stream_id,string &schema) {\n auto src = MediaSource::find(RTMP_SCHEMA, vhost, app, stream_id);\n if (src) {\n auto ret = src->getTracks(true);\n if (!ret.empty()) {\n schema = RTMP_SCHEMA;\n return std::move(ret);\n }\n }\n\n src = MediaSource::find(RTSP_SCHEMA, vhost, app, stream_id);\n if (src) {\n schema = RTSP_SCHEMA;\n return src->getTracks(true);\n }\n return vector<Track::Ptr>();\n }\n\n string getRecorderKey(const string &vhost, const string &app, const string &stream_id) {\n return vhost + \"\/\" + app + \"\/\" + stream_id;\n }\n\n MediaSinkInterface *createRecorder(const string &vhost, const string &app, const string &stream_id) {\n MediaSinkInterface *ret = nullptr;\n switch (type) {\n case Recorder::type_hls:\n ret = createHlsRecorder(vhost, app, stream_id);\n break;\n case Recorder::type_mp4:\n ret = createMP4Recorder(vhost, app, stream_id);\n break;\n default:\n break;\n }\n if(!ret){\n WarnL << \"can not recorder of: \" << type;\n }\n return ret;\n }\nprivate:\n recursive_mutex _recorder_mtx;\n unordered_map<string, RecorderHelper::Ptr> _recorder_map;\n};\n\n\nRecorder::status Recorder::getRecordStatus(Recorder::type type, const string &vhost, const string &app, const string &stream_id) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().getRecordStatus(vhost,app,stream_id);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().getRecordStatus(vhost,app,stream_id);\n }\n return status_not_record;\n}\n\nint Recorder::startRecord(Recorder::type type, const string &vhost, const string &app, const string &stream_id, bool waitForRecord, bool continueRecord) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().startRecord(vhost,app,stream_id,waitForRecord,continueRecord);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().startRecord(vhost,app,stream_id,waitForRecord,continueRecord);\n }\n return -3;\n}\n\nvoid Recorder::stopRecord(Recorder::type type, const string &vhost, const string &app, const string &stream_id) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().stopRecord(vhost,app,stream_id);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().stopRecord(vhost,app,stream_id);\n }\n}\n\n} \/* namespace mediakit *\/\n<commit_msg>修复无法延后录制的bug<commit_after>\/*\n* MIT License\n*\n* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>\n*\n* This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\/\n\n#include \"Recorder.h\"\n#include \"Common\/config.h\"\n#include \"MP4Recorder.h\"\n#include \"HlsRecorder.h\"\n\nusing namespace toolkit;\n\nnamespace mediakit {\n\nMediaSinkInterface *createHlsRecorder(const string &strVhost_tmp, const string &strApp, const string &strId) {\n#if defined(ENABLE_HLS)\n GET_CONFIG(bool, enableVhost, General::kEnableVhost);\n GET_CONFIG(string, hlsPath, Hls::kFilePath);\n\n string strVhost = strVhost_tmp;\n if (trim(strVhost).empty()) {\n \/\/如果strVhost为空,则强制为默认虚拟主机\n strVhost = DEFAULT_VHOST;\n }\n\n string m3u8FilePath;\n string params;\n if (enableVhost) {\n m3u8FilePath = strVhost + \"\/\" + strApp + \"\/\" + strId + \"\/hls.m3u8\";\n params = string(VHOST_KEY) + \"=\" + strVhost;\n } else {\n m3u8FilePath = strApp + \"\/\" + strId + \"\/hls.m3u8\";\n }\n m3u8FilePath = File::absolutePath(m3u8FilePath, hlsPath);\n return new HlsRecorder(m3u8FilePath, params);\n#else\n return nullptr;\n#endif \/\/defined(ENABLE_HLS)\n}\n\nMediaSinkInterface *createMP4Recorder(const string &strVhost_tmp, const string &strApp, const string &strId) {\n#if defined(ENABLE_MP4RECORD)\n GET_CONFIG(bool, enableVhost, General::kEnableVhost);\n GET_CONFIG(string, recordPath, Record::kFilePath);\n GET_CONFIG(string, recordAppName, Record::kAppName);\n\n string strVhost = strVhost_tmp;\n if (trim(strVhost).empty()) {\n \/\/如果strVhost为空,则强制为默认虚拟主机\n strVhost = DEFAULT_VHOST;\n }\n\n string mp4FilePath;\n if (enableVhost) {\n mp4FilePath = strVhost + \"\/\" + recordAppName + \"\/\" + strApp + \"\/\" + strId + \"\/\";\n } else {\n mp4FilePath = recordAppName + \"\/\" + strApp + \"\/\" + strId + \"\/\";\n }\n mp4FilePath = File::absolutePath(mp4FilePath, recordPath);\n return new MP4Recorder(mp4FilePath, strVhost, strApp, strId);\n#else\n return nullptr;\n#endif \/\/defined(ENABLE_MP4RECORD)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass RecorderHelper {\npublic:\n typedef std::shared_ptr<RecorderHelper> Ptr;\n\n \/**\n * 构建函数\n * @param bContinueRecord false表明hls录制从头开始录制(意味着hls临时文件在媒体反注册时会被删除)\n *\/\n RecorderHelper(const MediaSinkInterface::Ptr &recorder, vector<Track::Ptr> &&tracks , bool bContinueRecord, const string &schema) {\n _recorder = recorder;\n _continueRecord = bContinueRecord;\n attachTracks(std::move(tracks),schema);\n }\n\n ~RecorderHelper() {\n resetTracks();\n }\n\n \/\/ 附则于track上\n void attachTracks(vector<Track::Ptr> &&tracks, const string &schema){\n if(isTracksSame(tracks)){\n return;\n }\n resetTracks();\n _tracks = std::move(tracks);\n _schema = schema;\n for (auto &track : _tracks) {\n _recorder->addTrack(track);\n track->addDelegate(_recorder);\n }\n }\n\n\n \/\/ 判断新的tracks是否与之前的一致\n bool isTracksSame(const vector<Track::Ptr> &tracks){\n if(tracks.size() != _tracks.size()) {\n return false;\n }\n int i = 0;\n for(auto &track : tracks){\n if(track != _tracks[i++]){\n return false;\n }\n }\n return true;\n }\n\n \/\/ 重置所有track\n void resetTracks(){\n if(_tracks.empty()){\n return;\n }\n for (auto &track : _tracks) {\n track->delDelegate(_recorder.get());\n }\n _tracks.clear();\n _recorder->resetTracks();\n }\n\n \/\/ 返回false表明hls录制从头开始录制(意味着hls临时文件在媒体反注册时会被删除)\n bool continueRecord(){\n return _continueRecord;\n }\n\n bool isRecording() {\n return !_tracks.empty();\n }\n\n const string &getSchema() const{\n return _schema;\n }\nprivate:\n MediaSinkInterface::Ptr _recorder;\n vector<Track::Ptr> _tracks;\n bool _continueRecord;\n string _schema;\n};\n\n\ntemplate<Recorder::type type>\nclass MediaSourceWatcher {\npublic:\n static MediaSourceWatcher& Instance(){\n static MediaSourceWatcher instance;\n return instance;\n }\n\n Recorder::status getRecordStatus(const string &vhost, const string &app, const string &stream_id) {\n return getRecordStatus_l(getRecorderKey(vhost, app, stream_id));\n }\n\n int startRecord(const string &vhost, const string &app, const string &stream_id, bool waitForRecord, bool continueRecord) {\n auto key = getRecorderKey(vhost, app, stream_id);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n if (getRecordStatus_l(key) != Recorder::status_not_record) {\n \/\/ 已经在录制了\n return 0;\n }\n\n string schema;\n auto tracks = findTracks(vhost, app, stream_id,schema);\n if (!waitForRecord && tracks.empty()) {\n \/\/ 暂时无法开启录制\n return -1;\n }\n\n auto recorder = MediaSinkInterface::Ptr(createRecorder(vhost, app, stream_id));\n if (!recorder) {\n \/\/ 创建录制器失败\n return -2;\n }\n _recorder_map[key] = std::make_shared<RecorderHelper>(recorder, std::move(tracks), continueRecord, schema);\n return 0;\n }\n\n void stopRecord(const string &vhost, const string &app, const string &stream_id) {\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n _recorder_map.erase(getRecorderKey(vhost, app, stream_id));\n }\n\nprivate:\n MediaSourceWatcher(){\n NoticeCenter::Instance().addListener(this,Broadcast::kBroadcastMediaChanged,[this](BroadcastMediaChangedArgs){\n if(bRegist){\n onRegist(schema,vhost,app,stream,sender);\n }else{\n onUnRegist(schema,vhost,app,stream,sender);\n }\n });\n NoticeCenter::Instance().addListener(this,Broadcast::kBroadcastMediaResetTracks,[this](BroadcastMediaResetTracksArgs){\n onRegist(schema,vhost,app,stream,sender);\n });\n }\n\n ~MediaSourceWatcher(){\n NoticeCenter::Instance().delListener(this,Broadcast::kBroadcastMediaChanged);\n NoticeCenter::Instance().delListener(this,Broadcast::kBroadcastMediaResetTracks);\n }\n\n void onRegist(const string &schema,const string &vhost,const string &app,const string &stream,MediaSource &sender){\n auto key = getRecorderKey(vhost,app,stream);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n auto it = _recorder_map.find(key);\n if(it == _recorder_map.end()){\n \/\/ 录像记录不存在\n return;\n }\n\n auto tracks = sender.getTracks(true);\n if (tracks.empty()) {\n \/\/ 无有效的tracks\n return;\n }\n\n if(!it->second->isRecording() || it->second->getSchema() == schema){\n \/\/ 绑定的协议一致,替换tracks\n it->second->attachTracks(std::move(tracks),schema);\n }\n\n }\n\n void onUnRegist(const string &schema,const string &vhost,const string &app,const string &stream,MediaSource &sender){\n auto key = getRecorderKey(vhost,app,stream);\n lock_guard<decltype(_recorder_mtx)> lck(_recorder_mtx);\n auto it = _recorder_map.find(key);\n if(it == _recorder_map.end()){\n \/\/ 录像记录不存在\n return;\n }\n\n if(it->second->getSchema() != schema){\n \/\/ 绑定的协议不一致\n return;\n }\n if(it->second->continueRecord()){\n \/\/ 如果可以继续录制,那么只重置tracks,不删除对象\n it->second->resetTracks();\n }else{\n \/\/ 删除对象(意味着可能删除hls临时文件)\n _recorder_map.erase(it);\n }\n }\n\n Recorder::status getRecordStatus_l(const string &key) {\n auto it = _recorder_map.find(key);\n if (it == _recorder_map.end()) {\n return Recorder::status_not_record;\n }\n return it->second->isRecording() ? Recorder::status_recording : Recorder::status_wait_record;\n }\n\n \/\/ 查找MediaSource以便录制\n vector<Track::Ptr> findTracks(const string &vhost, const string &app, const string &stream_id,string &schema) {\n auto src = MediaSource::find(RTMP_SCHEMA, vhost, app, stream_id);\n if (src) {\n auto ret = src->getTracks(true);\n if (!ret.empty()) {\n schema = RTMP_SCHEMA;\n return std::move(ret);\n }\n }\n\n src = MediaSource::find(RTSP_SCHEMA, vhost, app, stream_id);\n if (src) {\n schema = RTSP_SCHEMA;\n return src->getTracks(true);\n }\n return vector<Track::Ptr>();\n }\n\n string getRecorderKey(const string &vhost, const string &app, const string &stream_id) {\n return vhost + \"\/\" + app + \"\/\" + stream_id;\n }\n\n MediaSinkInterface *createRecorder(const string &vhost, const string &app, const string &stream_id) {\n MediaSinkInterface *ret = nullptr;\n switch (type) {\n case Recorder::type_hls:\n ret = createHlsRecorder(vhost, app, stream_id);\n break;\n case Recorder::type_mp4:\n ret = createMP4Recorder(vhost, app, stream_id);\n break;\n default:\n break;\n }\n if(!ret){\n WarnL << \"can not recorder of: \" << type;\n }\n return ret;\n }\nprivate:\n recursive_mutex _recorder_mtx;\n unordered_map<string, RecorderHelper::Ptr> _recorder_map;\n};\n\n\nRecorder::status Recorder::getRecordStatus(Recorder::type type, const string &vhost, const string &app, const string &stream_id) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().getRecordStatus(vhost,app,stream_id);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().getRecordStatus(vhost,app,stream_id);\n }\n return status_not_record;\n}\n\nint Recorder::startRecord(Recorder::type type, const string &vhost, const string &app, const string &stream_id, bool waitForRecord, bool continueRecord) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().startRecord(vhost,app,stream_id,waitForRecord,continueRecord);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().startRecord(vhost,app,stream_id,waitForRecord,continueRecord);\n }\n return -3;\n}\n\nvoid Recorder::stopRecord(Recorder::type type, const string &vhost, const string &app, const string &stream_id) {\n switch (type){\n case type_mp4:\n return MediaSourceWatcher<type_mp4>::Instance().stopRecord(vhost,app,stream_id);\n case type_hls:\n return MediaSourceWatcher<type_hls>::Instance().stopRecord(vhost,app,stream_id);\n }\n}\n\n} \/* namespace mediakit *\/\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.osgeo.org\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/geom\/util\/CoordinateOperation.h>\n#include <geos\/geom\/CoordinateSequence.h>\n#include <geos\/geom\/LinearRing.h>\n#include <geos\/geom\/LineString.h>\n#include <geos\/geom\/Point.h>\n#include <geos\/geom\/Geometry.h>\n#include <geos\/geom\/GeometryFactory.h>\n\nnamespace geos {\nnamespace geom { \/\/ geos.geom\nnamespace util { \/\/ geos.geom.util\n\nGeometry*\nCoordinateOperation::edit(const Geometry *geometry,\n\t\tconst GeometryFactory *factory)\n{\n\t\tconst LinearRing *ring = dynamic_cast<const LinearRing *>(geometry);\n\t\tif (ring) {\n\t\t\tconst CoordinateSequence *coords = ring->getCoordinatesRO();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n \/\/ LinearRing instance takes over ownership of newCoords instance\n\t\t\treturn factory->createLinearRing(newCoords);\n\t\t}\n\t\tconst LineString *line = dynamic_cast<const LineString *>(geometry);\n\t\tif (line) {\n\t\t\tconst CoordinateSequence *coords = line->getCoordinatesRO();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n\t\t\treturn factory->createLineString(newCoords);\n\t\t}\n\t\tif (typeid(*geometry)==typeid(Point)) {\n\t\t\tCoordinateSequence *coords = geometry->getCoordinates();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n\t\t\tdelete coords;\n\t\t\treturn factory->createPoint(newCoords);\n\t\t}\n\n\t\treturn geometry->clone();\n}\n\n\n} \/\/ namespace geos.geom.util\n} \/\/ namespace geos.geom\n} \/\/ namespace geos\n<commit_msg>Fixes for build on both windows and Linux<commit_after>\/**********************************************************************\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.osgeo.org\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#ifndef _MSC_VER\n#include <typeinfo>\n#endif\n\n#include <geos\/geom\/util\/CoordinateOperation.h>\n#include <geos\/geom\/CoordinateSequence.h>\n#include <geos\/geom\/LinearRing.h>\n#include <geos\/geom\/LineString.h>\n#include <geos\/geom\/Point.h>\n#include <geos\/geom\/Geometry.h>\n#include <geos\/geom\/GeometryFactory.h>\n\nnamespace geos {\nnamespace geom { \/\/ geos.geom\nnamespace util { \/\/ geos.geom.util\n\nGeometry*\nCoordinateOperation::edit(const Geometry *geometry,\n\t\tconst GeometryFactory *factory)\n{\n\t\tconst LinearRing *ring = dynamic_cast<const LinearRing *>(geometry);\n\t\tif (ring) {\n\t\t\tconst CoordinateSequence *coords = ring->getCoordinatesRO();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n \/\/ LinearRing instance takes over ownership of newCoords instance\n\t\t\treturn factory->createLinearRing(newCoords);\n\t\t}\n\t\tconst LineString *line = dynamic_cast<const LineString *>(geometry);\n\t\tif (line) {\n\t\t\tconst CoordinateSequence *coords = line->getCoordinatesRO();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n\t\t\treturn factory->createLineString(newCoords);\n\t\t}\n\t\tif (typeid(*geometry)==typeid(Point)) {\n\t\t\tCoordinateSequence *coords = geometry->getCoordinates();\n\t\t\tCoordinateSequence *newCoords = edit(coords,geometry);\n\t\t\tdelete coords;\n\t\t\treturn factory->createPoint(newCoords);\n\t\t}\n\n\t\treturn geometry->clone();\n}\n\n\n} \/\/ namespace geos.geom.util\n} \/\/ namespace geos.geom\n} \/\/ namespace geos\n<|endoftext|>"} {"text":"<commit_before>#include \"openMVG\/sfm\/sfm.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include \"software\/SfM\/io_readGT.hpp\"\n#include \"software\/SfM\/tools_precisionEvaluationToGt.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\n#include <vector>\n#include <iostream>\n\nusing namespace openMVG;\nusing namespace openMVG::sfm;\n\nint main(int argc, char **argv)\n{\n\t\/\/ Command line configuration\n\t\/\/\n\tCmdLine cmd;\n\n std::string\n sSfmFile,\n sGTDirectory,\n sOutFile = \"\";\n bool mayaTransform = false;\n\n\n cmd.add( make_option('i', sSfmFile, \"sfm\") );\n cmd.add( make_option('g', sGTDirectory, \"gt\") );\n cmd.add( make_option('o', sOutFile, \"output\") );\n cmd.add( make_option('m', mayaTransform, \"maya\") );\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfm] path (OpenMVG Json file, ouput from SfMInit_ImageListing)\\n\"\n << \"[-g|--gt] path (where ground truth camera trajectory are saved)\\n\"\n << \"[-o|--output] path (where export file, .json or .abc, will be save)\\n\"\n << \"[-m|--maya] enable [1,-1,-1] transformation if ground truth comes from Maya\\n\"\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Setup the camera type and the appropriate camera reader\n \/\/\n bool (*fcnReadCamPtr)(const std::string&, Pinhole_Intrinsic&, geometry::Pose3&);\n int camType;\n std::string suffix;\n\n if (!stlplus::folder_wildcard(sGTDirectory, \"*.bin\", false, true).empty())\n camType = 1;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.png.camera\", false, true).empty())\n camType = 2;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.jpg.camera\", false, true).empty())\n camType = 3;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.PNG.camera\", false, true).empty())\n camType = 4;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.JPG.camera\", false, true).empty())\n camType = 5;\n else\n camType = std::numeric_limits<int>::infinity();\n switch (camType)\n {\n case 1:\n std::cout << \"\\nusing openMVG Camera\";\n fcnReadCamPtr = &read_openMVG_Camera;\n suffix = \"bin\";\n break;\n case 2:\n std::cout << \"\\nusing Strechas Camera (png)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"png.camera\";\n break;\n case 3:\n std::cout << \"\\nusing Strechas Camera (jpg)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"jpg.camera\";\n break;\n case 4:\n std::cout << \"\\nusing Strechas Camera (PNG)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"PNG.camera\";\n break;\n case 5:\n std::cout << \"\\nusing Strechas Camera (JPG)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"JPG.camera\";\n break;\n default:\n std::cerr << \"Unsupported camera type. Please write your camera reader.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Load JSON\n \/\/\n SfM_Data sfm_data_in;\n if (!Load(sfm_data_in, sSfmFile, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)))\n {\n \tstd::cerr << \"ERROR\" << std::endl;\n \tstd::cerr << \"The input SfM_Data file \\\"\" << sSfmFile << \"\\\" cannot be read.\" << std::endl;\n \treturn EXIT_FAILURE;\n }\n\n \/\/ Load GT\n \/\/\n SfM_Data sfm_data_gt;\n std::vector<std::string> vec_fileNames;\n readGt(fcnReadCamPtr, sGTDirectory, suffix, vec_fileNames, sfm_data_gt.poses, sfm_data_gt.intrinsics);\n std:cout << sfm_data_gt.poses.size() << \" gt cameras have been found\" << std::endl;\n \n \/\/ Fill sfm_data_in with poses from sfm_data_gt\n \/\/\n for(const auto &iter : sfm_data_in.GetViews())\n {\n \tconst auto &view = iter.second;\n \tconst std::string sImageName = stlplus::filename_part(view->s_Img_path);\n \tint idGT = findIdGT(sImageName, vec_fileNames);\n \tif(idGT == -1)\n \t{\n \t\tstd::cerr << \"No ground truth for file: \" << sImageName << std::endl;\n \t\tcontinue;\n \t}\n \telse\n \t{\n \t\tgeometry::Pose3 poseGT = sfm_data_gt.GetPoses().at(idGT);\n \t\tVec3 vecMaya;\n \t\tif(mayaTransform)\n \t\t\tvecMaya = {1,-1,-1};\n \t\telse\n \t\t\tvecMaya = {1,1,1};\n \t\tgeometry::Pose3 poseIN(vecMaya.asDiagonal() * poseGT.rotation(), poseGT.center());\n\n \t\tsfm_data_in.poses.emplace(view->id_pose, poseIN);\n \t\tsfm_data_in.intrinsics[view->id_intrinsic] = sfm_data_gt.intrinsics.at(idGT);\n \t}\n }\n\n std::cout << \"Saved: \" << Save(sfm_data_in, sOutFile, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)) << std::endl;\n\n\treturn 0;\n}\n\n<commit_msg>change tabs for spaces<commit_after>#include \"openMVG\/sfm\/sfm.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include \"software\/SfM\/io_readGT.hpp\"\n#include \"software\/SfM\/tools_precisionEvaluationToGt.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\n#include <vector>\n#include <iostream>\n\nusing namespace openMVG;\nusing namespace openMVG::sfm;\n\nint main(int argc, char **argv)\n{\n \/\/ Command line configuration\n \/\/\n CmdLine cmd;\n\n std::string\n sSfmFile,\n sGTDirectory,\n sOutFile = \"\";\n bool mayaTransform = false;\n\n\n cmd.add( make_option('i', sSfmFile, \"sfm\") );\n cmd.add( make_option('g', sGTDirectory, \"gt\") );\n cmd.add( make_option('o', sOutFile, \"output\") );\n cmd.add( make_option('m', mayaTransform, \"maya\") );\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfm] path (OpenMVG Json file, ouput from SfMInit_ImageListing)\\n\"\n << \"[-g|--gt] path (where ground truth camera trajectory are saved)\\n\"\n << \"[-o|--output] path (where export file, .json or .abc, will be save)\\n\"\n << \"[-m|--maya] enable [1,-1,-1] transformation if ground truth comes from Maya\\n\"\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Setup the camera type and the appropriate camera reader\n \/\/\n bool (*fcnReadCamPtr)(const std::string&, Pinhole_Intrinsic&, geometry::Pose3&);\n int camType;\n std::string suffix;\n\n if (!stlplus::folder_wildcard(sGTDirectory, \"*.bin\", false, true).empty())\n camType = 1;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.png.camera\", false, true).empty())\n camType = 2;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.jpg.camera\", false, true).empty())\n camType = 3;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.PNG.camera\", false, true).empty())\n camType = 4;\n else if (!stlplus::folder_wildcard(sGTDirectory, \"*.JPG.camera\", false, true).empty())\n camType = 5;\n else\n camType = std::numeric_limits<int>::infinity();\n switch (camType)\n {\n case 1:\n std::cout << \"\\nusing openMVG Camera\";\n fcnReadCamPtr = &read_openMVG_Camera;\n suffix = \"bin\";\n break;\n case 2:\n std::cout << \"\\nusing Strechas Camera (png)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"png.camera\";\n break;\n case 3:\n std::cout << \"\\nusing Strechas Camera (jpg)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"jpg.camera\";\n break;\n case 4:\n std::cout << \"\\nusing Strechas Camera (PNG)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"PNG.camera\";\n break;\n case 5:\n std::cout << \"\\nusing Strechas Camera (JPG)\";\n fcnReadCamPtr = &read_Strecha_Camera;\n suffix = \"JPG.camera\";\n break;\n default:\n std::cerr << \"Unsupported camera type. Please write your camera reader.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Load JSON\n \/\/\n SfM_Data sfm_data_in;\n if (!Load(sfm_data_in, sSfmFile, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)))\n {\n std::cerr << \"ERROR\" << std::endl;\n std::cerr << \"The input SfM_Data file \\\"\" << sSfmFile << \"\\\" cannot be read.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Load GT\n \/\/\n SfM_Data sfm_data_gt;\n std::vector<std::string> vec_fileNames;\n readGt(fcnReadCamPtr, sGTDirectory, suffix, vec_fileNames, sfm_data_gt.poses, sfm_data_gt.intrinsics);\n std:cout << sfm_data_gt.poses.size() << \" gt cameras have been found\" << std::endl;\n \n \/\/ Fill sfm_data_in with poses from sfm_data_gt\n \/\/\n for(const auto &iter : sfm_data_in.GetViews())\n {\n const auto &view = iter.second;\n const std::string sImageName = stlplus::filename_part(view->s_Img_path);\n int idGT = findIdGT(sImageName, vec_fileNames);\n if(idGT == -1)\n {\n std::cerr << \"No ground truth for file: \" << sImageName << std::endl;\n continue;\n }\n else\n {\n geometry::Pose3 poseGT = sfm_data_gt.GetPoses().at(idGT);\n Vec3 vecMaya;\n if(mayaTransform)\n vecMaya = {1,-1,-1};\n else\n vecMaya = {1,1,1};\n geometry::Pose3 poseIN(vecMaya.asDiagonal() * poseGT.rotation(), poseGT.center());\n\n sfm_data_in.poses.emplace(view->id_pose, poseIN);\n sfm_data_in.intrinsics[view->id_intrinsic] = sfm_data_gt.intrinsics.at(idGT);\n }\n }\n\n std::cout << \"Saved: \" << Save(sfm_data_in, sOutFile, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)) << std::endl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n#if !PETSC_VERSION_LESS_THAN(3,2,0)\n\n\/\/ Local includes\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/system.h\"\n\nEXTERN_C_FOR_PETSC_BEGIN\n# include <petscksp.h>\nEXTERN_C_FOR_PETSC_END\n\n\/\/ C++ includes\n\nnamespace {\n\nvoid indices_to_fieldsplit (const libMesh::Parallel::Communicator& comm,\n const std::vector<dof_id_type>& indices, \n PC my_pc,\n const std::string& field_name)\n{\n const PetscInt *idx = PETSC_NULL;\n if (!indices.empty())\n idx = reinterpret_cast<const PetscInt*>(&indices[0]);\n\n IS is;\n int ierr = ISCreateLibMesh(comm.get(), indices.size(),\n idx, PETSC_COPY_VALUES, &is);\n CHKERRABORT(comm.get(), ierr);\n\n ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is);\n CHKERRABORT(comm.get(), ierr);\n}\n\n}\n\nnamespace libMesh\n{\n\nvoid petsc_auto_fieldsplit (PC my_pc,\n const System &sys)\n{\n std::string sys_prefix = \"--solver_group_\";\n\n if (libMesh::on_command_line(\"--solver_system_names\"))\n {\n sys_prefix = sys_prefix + sys.name() + \"_\";\n }\n\n std::map<std::string, std::vector<dof_id_type> > group_indices;\n\n if (libMesh::on_command_line(\"--solver_variable_names\"))\n {\n for (unsigned int v = 0; v != sys.n_vars(); ++v)\n {\n const std::string& var_name = sys.variable_name(v);\n\n std::vector<dof_id_type> var_idx;\n sys.get_dof_map().local_variable_indices\n (var_idx, sys.get_mesh(), v);\n\n std::string group_command = sys_prefix + var_name;\n\n if (libMesh::on_command_line (group_command))\n {\n std::string group_name = libMesh::command_line_value\n (group_command, std::string());\n\n std::vector<dof_id_type> &indices =\n group_indices[group_name];\n const bool prior_indices = !indices.empty();\n indices.insert(indices.end(), var_idx.begin(),\n var_idx.end());\n if (prior_indices)\n std::sort(indices.begin(), indices.end());\n }\n else\n {\n indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name);\n }\n }\n }\n\n for (std::map<std::string, std::vector<dof_id_type> >::const_iterator\n i = group_indices.begin(); i != group_indices.end(); ++i)\n {\n indices_to_fieldsplit(sys.comm(), i->second, my_pc, i->first);\n }\n}\n\n} \/\/ namespace libMesh\n\n\n#else \/\/ #PETSC_VERSION < 3.2.0\nvoid assign_solver_fieldsplit_names (PC my_pc,\n const System &sys)\n{\n if (libMesh::on_command_line(\"--solver_variable_names\"))\n {\n libmesh_do_once(\n libMesh::out <<\n \"WARNING: libMesh does not support setting field splits\" <<\n std::endl << \"with PETSc \" <<\n LIBMESH_DETECTED_PETSC_VERSION_MAJOR << '.'\n LIBMESH_DETECTED_PETSC_VERSION_MINOR << '.'\n LIBMESH_DETECTED_PETSC_VERSION_SUBMINOR << std::endl;);\n }\n}\n#endif \/\/ #PETSC_VERSION > 3.2.0\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<commit_msg>Use consistent name for old PETSc case<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n#if !PETSC_VERSION_LESS_THAN(3,2,0)\n\n\/\/ Local includes\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/system.h\"\n\nEXTERN_C_FOR_PETSC_BEGIN\n# include <petscksp.h>\nEXTERN_C_FOR_PETSC_END\n\n\/\/ C++ includes\n\nnamespace {\n\nvoid indices_to_fieldsplit (const libMesh::Parallel::Communicator& comm,\n const std::vector<dof_id_type>& indices, \n PC my_pc,\n const std::string& field_name)\n{\n const PetscInt *idx = PETSC_NULL;\n if (!indices.empty())\n idx = reinterpret_cast<const PetscInt*>(&indices[0]);\n\n IS is;\n int ierr = ISCreateLibMesh(comm.get(), indices.size(),\n idx, PETSC_COPY_VALUES, &is);\n CHKERRABORT(comm.get(), ierr);\n\n ierr = PCFieldSplitSetIS(my_pc, field_name.c_str(), is);\n CHKERRABORT(comm.get(), ierr);\n}\n\n}\n\nnamespace libMesh\n{\n\nvoid petsc_auto_fieldsplit (PC my_pc,\n const System &sys)\n{\n std::string sys_prefix = \"--solver_group_\";\n\n if (libMesh::on_command_line(\"--solver_system_names\"))\n {\n sys_prefix = sys_prefix + sys.name() + \"_\";\n }\n\n std::map<std::string, std::vector<dof_id_type> > group_indices;\n\n if (libMesh::on_command_line(\"--solver_variable_names\"))\n {\n for (unsigned int v = 0; v != sys.n_vars(); ++v)\n {\n const std::string& var_name = sys.variable_name(v);\n\n std::vector<dof_id_type> var_idx;\n sys.get_dof_map().local_variable_indices\n (var_idx, sys.get_mesh(), v);\n\n std::string group_command = sys_prefix + var_name;\n\n if (libMesh::on_command_line (group_command))\n {\n std::string group_name = libMesh::command_line_value\n (group_command, std::string());\n\n std::vector<dof_id_type> &indices =\n group_indices[group_name];\n const bool prior_indices = !indices.empty();\n indices.insert(indices.end(), var_idx.begin(),\n var_idx.end());\n if (prior_indices)\n std::sort(indices.begin(), indices.end());\n }\n else\n {\n indices_to_fieldsplit (sys.comm(), var_idx, my_pc, var_name);\n }\n }\n }\n\n for (std::map<std::string, std::vector<dof_id_type> >::const_iterator\n i = group_indices.begin(); i != group_indices.end(); ++i)\n {\n indices_to_fieldsplit(sys.comm(), i->second, my_pc, i->first);\n }\n}\n\n} \/\/ namespace libMesh\n\n\n#else \/\/ #PETSC_VERSION < 3.2.0\nvoid petsc_auto_fieldsplit (PC my_pc,\n const System &sys)\n{\n if (libMesh::on_command_line(\"--solver_variable_names\"))\n {\n libmesh_do_once(\n libMesh::out <<\n \"WARNING: libMesh does not support setting field splits\" <<\n std::endl << \"with PETSc \" <<\n LIBMESH_DETECTED_PETSC_VERSION_MAJOR << '.'\n LIBMESH_DETECTED_PETSC_VERSION_MINOR << '.'\n LIBMESH_DETECTED_PETSC_VERSION_SUBMINOR << std::endl;);\n }\n}\n#endif \/\/ #PETSC_VERSION > 3.2.0\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\n\n#include <Debugger.h>\n\n#include <DebuggerIO.h>\n#include <LocalIO.h>\n#include <SerialIO.h>\n\n#include <utilities\/StaticString.h>\n\n#include <processor\/Processor.h>\n#include <machine\/Machine.h>\n\n#include <Log.h>\n#include <utilities\/utility.h>\n\nstatic size_t newlineCount(const char *pString)\n{\n size_t nNewlines = 0;\n while (*pString != '\\0')\n if (*pString++ == '\\n')\n ++nNewlines;\n\n return nNewlines;\n}\n\n\/\/ TODO: We might want a separate parameter for a stacktrace\/register dump\nvoid _panic( const char* msg, DebuggerIO* pScreen )\n{\n static HugeStaticString panic_output;\n panic_output.clear();\n\n panic_output.append( \"PANIC: \" );\n panic_output.append( msg );\n\n \/\/ write the final string to the screen\n pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black );\n\n size_t nLines = newlineCount(panic_output) + 2;\n\n Log &log = Log::instance();\n Log::SeverityLevel level;\n static NormalStaticString Line;\n\n size_t iEntry = 0, iUsedEntries = 0;\n if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount()))\n iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1;\n bool bPrintThisLine = false;\n for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ )\n {\n if( iEntry < log.getStaticEntryCount() )\n {\n const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry);\n level = entry.type;\n\n\/\/ if( level == Log::Fatal || level == Log::Error )\n\/\/ {\n Line.clear();\n Line.append(\"[\");\n Line.append(entry.timestamp, 10, 8, '0');\n Line.append(\"] \");\n Line.append(entry.str);\n Line.append( \"\\n\" );\n\n bPrintThisLine = true;\n\/\/ }\n }\n else\n {\n const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry);\n level = entry.type;\n\n\/\/ if( level == Log::Fatal || level == Log::Error )\n\/\/ {\n Line.clear();\n Line.append(\"[\");\n Line.append(entry.timestamp, 10, 8, '0');\n Line.append(\"] \");\n Line.append(entry.str);\n Line.append( \"\\n\" );\n\n bPrintThisLine = true;\n\/\/ }\n }\n\n \/\/ print the line\n if( bPrintThisLine == true )\n {\n ++iUsedEntries;\n pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black );\n bPrintThisLine = false;\n }\n }\n}\n\nvoid panic( const char* msg )\n{\n \/*\n * I\/O implementations.\n *\/\n SerialIO serialIO(Machine::instance().getSerial(0));\n\n DebuggerIO *pInterfaces[2] = {0};\n\n int nInterfaces = 0;\n if(Machine::instance().getNumVga()) \/\/ Not all machines have \"VGA\", so handle that\n {\n static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard());\n#ifdef DONT_LOG_TO_SERIAL\n pInterfaces[0] = &localIO;\n nInterfaces = 1;\n#else\n pInterfaces[0] = &localIO;\n pInterfaces[1] = &serialIO;\n nInterfaces = 2;\n#endif\n }\n#ifndef DONT_LOG_TO_SERIAL\n else\n {\n pInterfaces[0] = &serialIO;\n nInterfaces = 1;\n }\n#endif\n\n for( int nIFace = 0; nIFace < nInterfaces; nIFace++ )\n _panic( msg, pInterfaces[nIFace] );\n\n \/\/ Halt the processor\n Processor::halt();\n}\n<commit_msg>Fixed panic to drop out of a graphics mode if one is being used.<commit_after>\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n\n\n#include <Debugger.h>\n\n#include <DebuggerIO.h>\n#include <LocalIO.h>\n#include <SerialIO.h>\n\n#include <utilities\/StaticString.h>\n\n#include <processor\/Processor.h>\n#include <machine\/Machine.h>\n\n#include <Log.h>\n#include <utilities\/utility.h>\n\n#include <graphics\/GraphicsService.h>\n\nstatic size_t newlineCount(const char *pString)\n{\n size_t nNewlines = 0;\n while (*pString != '\\0')\n if (*pString++ == '\\n')\n ++nNewlines;\n\n return nNewlines;\n}\n\n\/\/ TODO: We might want a separate parameter for a stacktrace\/register dump\nvoid _panic( const char* msg, DebuggerIO* pScreen )\n{\n static HugeStaticString panic_output;\n panic_output.clear();\n\n panic_output.append( \"PANIC: \" );\n panic_output.append( msg );\n\n \/\/ write the final string to the screen\n pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black );\n\n size_t nLines = newlineCount(panic_output) + 2;\n\n Log &log = Log::instance();\n Log::SeverityLevel level;\n static NormalStaticString Line;\n\n size_t iEntry = 0, iUsedEntries = 0;\n if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount()))\n iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1;\n bool bPrintThisLine = false;\n for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ )\n {\n if( iEntry < log.getStaticEntryCount() )\n {\n const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry);\n level = entry.type;\n\n\/\/ if( level == Log::Fatal || level == Log::Error )\n\/\/ {\n Line.clear();\n Line.append(\"[\");\n Line.append(entry.timestamp, 10, 8, '0');\n Line.append(\"] \");\n Line.append(entry.str);\n Line.append( \"\\n\" );\n\n bPrintThisLine = true;\n\/\/ }\n }\n else\n {\n const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry);\n level = entry.type;\n\n\/\/ if( level == Log::Fatal || level == Log::Error )\n\/\/ {\n Line.clear();\n Line.append(\"[\");\n Line.append(entry.timestamp, 10, 8, '0');\n Line.append(\"] \");\n Line.append(entry.str);\n Line.append( \"\\n\" );\n\n bPrintThisLine = true;\n\/\/ }\n }\n\n \/\/ print the line\n if( bPrintThisLine == true )\n {\n ++iUsedEntries;\n pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black );\n bPrintThisLine = false;\n }\n }\n}\n\nvoid panic( const char* msg )\n{\n \/\/ Drop out of whatever graphics mode we were in\n GraphicsService::GraphicsProvider provider;\n memset(&provider, 0, sizeof(provider));\n provider.bTextModes = true;\n \n ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String(\"graphics\"));\n Service *pService = ServiceManager::instance().getService(String(\"graphics\"));\n bool bSuccess = false;\n if(pFeatures->provides(ServiceFeatures::probe))\n if(pService)\n bSuccess = pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&provider), sizeof(provider));\n \n if(bSuccess && !provider.bTextModes)\n provider.pDisplay->setScreenMode(0);\n\n#ifdef MULTIPROCESSOR\n Machine::instance().stopAllOtherProcessors();\n#endif\n\n \/*\n * I\/O implementations.\n *\/\n SerialIO serialIO(Machine::instance().getSerial(0));\n\n DebuggerIO *pInterfaces[2] = {0};\n\n int nInterfaces = 0;\n if(Machine::instance().getNumVga()) \/\/ Not all machines have \"VGA\", so handle that\n {\n static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard());\n#ifdef DONT_LOG_TO_SERIAL\n pInterfaces[0] = &localIO;\n nInterfaces = 1;\n#else\n pInterfaces[0] = &localIO;\n pInterfaces[1] = &serialIO;\n nInterfaces = 2;\n#endif\n }\n#ifndef DONT_LOG_TO_SERIAL\n else\n {\n pInterfaces[0] = &serialIO;\n nInterfaces = 1;\n }\n#endif\n\n for( int nIFace = 0; nIFace < nInterfaces; nIFace++ )\n _panic( msg, pInterfaces[nIFace] );\n\n \/\/ Halt the processor\n Processor::halt();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2011 StormMQ Limited\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include <TestHarness.h>\n#include \"Transport\/Frame\/Frame.h\"\n#include \"Transport\/Frame\/FrameTestSupport.h\"\n\n#include \"Codec\/Decode\/Decode.h\"\n#include \"debug_helper.h\"\n\nSUITE(Frame)\n{\n TEST_FIXTURE(FrameFixture, multiple_symbol_null)\n {\n test_data::multiple_symbol_null.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_null(type));\n }\n\n TEST_FIXTURE(FrameFixture, multiple_symbol_one_value)\n {\n test_data::multiple_symbol_one_value.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_symbol(type));\n }\n\n TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)\n {\n test_data::multiple_symbol_many_values.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_array(type));\n CHECK_EQUAL(3U, type->value.array.count);\n CHECK(amqp_type_is_symbol(type->value.array.elements[0]));\n }\n\n TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)\n {\n test_data::multiple_symbol_many_values.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_array(type));\n CHECK_EQUAL(3U, type->value.array.count);\n CHECK(amqp_type_is_symbol(type->value.array.elements[0]));\n }\n}\n<commit_msg>Add test data for multiple symbols.<commit_after>\/*\n Copyright 2011 StormMQ Limited\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include <TestHarness.h>\n#include \"Transport\/Frame\/Frame.h\"\n#include \"Transport\/Frame\/FrameTestSupport.h\"\n\n#include \"Codec\/Decode\/Decode.h\"\n#include \"debug_helper.h\"\n\nSUITE(Frame)\n{\n TEST_FIXTURE(FrameFixture, multiple_symbol_null)\n {\n test_data::multiple_symbol_null.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_null(type));\n }\n\n TEST_FIXTURE(FrameFixture, multiple_symbol_one_value)\n {\n test_data::multiple_symbol_one_value.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_symbol(type));\n }\n\n TEST_FIXTURE(FrameFixture, multiple_symbol_many_values)\n {\n test_data::multiple_symbol_many_values.transfer_to(buffer);\n type = amqp_decode(context, buffer);\n\n CHECK(amqp_type_is_array(type));\n CHECK_EQUAL(3U, type->value.array.count);\n CHECK(amqp_type_is_symbol(type->value.array.elements[0]));\n }\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n Copyright (c) 2011-2017 Andreas F. Borchert\n All rights reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and\/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include \"parser.hpp\"\n#include \"scanner.hpp\"\n#include \"symtable.hpp\"\n#include \"yytname.hpp\"\n\nusing namespace CSP;\n\nvoid usage(const char* cmdname) {\n std::cerr << \"Usage: \" << cmdname << \" [-epv] source.csp\" << std::endl;\n exit(1);\n}\n\nint main(int argc, char** argv) {\n const char* cmdname = *argv++; --argc;\n if (argc == 0) usage(cmdname);\n\n \/\/ permit verbose process output to be suppressed\n bool opt_a = true; \/\/ print alphabet at the beginning\n bool opt_e = false; \/\/ print events if accepted\n bool opt_p = true; \/\/ print current process after each event\n bool opt_v = true; \/\/ print current set of acceptable events\n while (argc > 0 && **argv == '-') {\n for (char* cp = *argv + 1; *cp; ++cp) {\n\t switch (*cp) {\n\t case 'a':\n\t opt_a = false; break;\n\t case 'e':\n\t opt_e = true; break;\n\t case 'p':\n\t opt_p = false; break;\n\t case 'v':\n\t opt_v = false; break;\n\t default:\n\t usage(cmdname); break;\n\t }\n }\n --argc; ++argv;\n }\n if (argc != 1) usage(cmdname);\n\n const char* fname = *argv++; --argc;\n std::ifstream fin(fname);\n if (!fin) {\n std::cerr << cmdname << \": unable to open \" << fname <<\n\t \" for reading\" << std::endl;\n exit(1);\n }\n SymTable symtab;\n std::string filename(fname);\n Scanner scanner(fin, filename, symtab);\n\n ProcessPtr process;\n parser p(scanner, symtab, process);\n if (p.parse() == 0) {\n if (opt_p) {\n\t std::cout << \"Tracing: \" << process << std::endl;\n }\n if (opt_a) {\n\t std::cout << \"Alphabet: \" << process->get_alphabet() << std::endl;\n }\n if (opt_v) {\n\t std::cout << \"Acceptable: \" << process->acceptable() << std::endl;\n }\n if (!process->accepts_success()) {\n\t std::string event;\n\t while (std::cin >> event) {\n\t if (process->get_alphabet().is_member(event)) {\n\t process = process->proceed(event);\n\t if (!process) {\n\t\t std::cerr << \"cannot accept \" << event << std::endl;\n\t\t exit(1);\n\t }\n\t if (process->accepts_success()) break;\n\t if (opt_e) {\n\t\t std::cout << event << std::endl;\n\t }\n\t if (opt_p) {\n\t\t std::cout << \"Process: \" << process << std::endl;\n\t }\n\t if (opt_v) {\n\t\t std::cout << \"Acceptable: \" << process->acceptable() <<\n\t\t std::endl;\n\t }\n\t } else {\n\t std::cout << \"Not in alphabet: \" << event << std::endl;\n\t }\n\t }\n }\n std::cout << \"OK\" << std::endl;\n }\n}\n<commit_msg>usage message extended<commit_after>\/* \n Copyright (c) 2011-2017 Andreas F. Borchert\n All rights reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and\/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include \"parser.hpp\"\n#include \"scanner.hpp\"\n#include \"symtable.hpp\"\n#include \"yytname.hpp\"\n\nusing namespace CSP;\n\nvoid usage(const char* cmdname) {\n std::cerr << \"Usage: \" << cmdname << \" [-aepv] source.csp\" << std::endl;\n std::cerr << \"Options:\" << std::endl;\n std::cerr << \" -a do not print the alphabet at the beginning\" << std::endl;\n std::cerr << \" -e print events, if accepted\" << std::endl;\n std::cerr << \" -p do not print current process after each event\" <<\n std::endl;\n std::cerr << \" -v do not print the set of acceptable events\" <<\n std::endl;\n exit(1);\n}\n\nint main(int argc, char** argv) {\n const char* cmdname = *argv++; --argc;\n if (argc == 0) usage(cmdname);\n\n \/\/ permit verbose process output to be suppressed\n bool opt_a = true; \/\/ print alphabet at the beginning\n bool opt_e = false; \/\/ print events if accepted\n bool opt_p = true; \/\/ print current process after each event\n bool opt_v = true; \/\/ print current set of acceptable events\n while (argc > 0 && **argv == '-') {\n for (char* cp = *argv + 1; *cp; ++cp) {\n\t switch (*cp) {\n\t case 'a':\n\t opt_a = false; break;\n\t case 'e':\n\t opt_e = true; break;\n\t case 'p':\n\t opt_p = false; break;\n\t case 'v':\n\t opt_v = false; break;\n\t default:\n\t usage(cmdname); break;\n\t }\n }\n --argc; ++argv;\n }\n if (argc != 1) usage(cmdname);\n\n const char* fname = *argv++; --argc;\n std::ifstream fin(fname);\n if (!fin) {\n std::cerr << cmdname << \": unable to open \" << fname <<\n\t \" for reading\" << std::endl;\n exit(1);\n }\n SymTable symtab;\n std::string filename(fname);\n Scanner scanner(fin, filename, symtab);\n\n ProcessPtr process;\n parser p(scanner, symtab, process);\n if (p.parse() == 0) {\n if (opt_p) {\n\t std::cout << \"Tracing: \" << process << std::endl;\n }\n if (opt_a) {\n\t std::cout << \"Alphabet: \" << process->get_alphabet() << std::endl;\n }\n if (opt_v) {\n\t std::cout << \"Acceptable: \" << process->acceptable() << std::endl;\n }\n if (!process->accepts_success()) {\n\t std::string event;\n\t while (std::cin >> event) {\n\t if (process->get_alphabet().is_member(event)) {\n\t process = process->proceed(event);\n\t if (!process) {\n\t\t std::cerr << \"cannot accept \" << event << std::endl;\n\t\t exit(1);\n\t }\n\t if (process->accepts_success()) break;\n\t if (opt_e) {\n\t\t std::cout << event << std::endl;\n\t }\n\t if (opt_p) {\n\t\t std::cout << \"Process: \" << process << std::endl;\n\t }\n\t if (opt_v) {\n\t\t std::cout << \"Acceptable: \" << process->acceptable() <<\n\t\t std::endl;\n\t }\n\t } else {\n\t std::cout << \"Not in alphabet: \" << event << std::endl;\n\t }\n\t }\n }\n std::cout << \"OK\" << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"agent_impl.h\"\n#include \"setting_utils.h\"\n\n#include <sofa\/pbrpc\/pbrpc.h>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n\n#include <sys\/types.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <vector>\n\nDECLARE_string(agent_port);\n\nstatic volatile bool s_quit = false;\nstatic void SignalIntHandler(int \/*sig*\/)\n{\n s_quit = true;\n}\n\nvoid SigChldHandler(int \/*sig*\/)\n{\n int status = 0;\n while (true) {\n pid_t pid = ::waitpid(-1, &status, WNOHANG);\n if (pid == -1 || pid == 0) {\n return;\n }\n }\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ set umask\n umask(22);\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n baidu::galaxy::SetupLog(\"agent\");\n baidu::galaxy::AgentImpl* agent = new baidu::galaxy::AgentImpl();\n sofa::pbrpc::RpcServerOptions options;\n sofa::pbrpc::RpcServer rpc_server(options);\n\n if (!rpc_server.RegisterService(static_cast<baidu::galaxy::proto::Agent*>(agent))) {\n LOG(WARNING) << \"failed to register agent service\";\n exit(-1);\n }\n\n std::string endpoint = \"0.0.0.0:\" + FLAGS_agent_port;\n agent->Setup();\n\n if (!rpc_server.Start(endpoint)) {\n LOG(WARNING) << \"failed to start server on \" << endpoint;\n exit(-2);\n }\n\n\n signal(SIGINT, SignalIntHandler);\n signal(SIGTERM, SignalIntHandler);\n signal(SIGCHLD, SigChldHandler);\n LOG(INFO) << \"agent started.\";\n\n while (!s_quit) {\n sleep(1);\n }\n\n return 0;\n}\n\n\n<commit_msg>use defaule umask<commit_after>\/\/ Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"agent_impl.h\"\n#include \"setting_utils.h\"\n\n#include <sofa\/pbrpc\/pbrpc.h>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n\n#include <sys\/types.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <vector>\n\nDECLARE_string(agent_port);\n\nstatic volatile bool s_quit = false;\nstatic void SignalIntHandler(int \/*sig*\/)\n{\n s_quit = true;\n}\n\nvoid SigChldHandler(int \/*sig*\/)\n{\n int status = 0;\n while (true) {\n pid_t pid = ::waitpid(-1, &status, WNOHANG);\n if (pid == -1 || pid == 0) {\n return;\n }\n }\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ set umask\n \/\/umask(22);\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n baidu::galaxy::SetupLog(\"agent\");\n baidu::galaxy::AgentImpl* agent = new baidu::galaxy::AgentImpl();\n sofa::pbrpc::RpcServerOptions options;\n sofa::pbrpc::RpcServer rpc_server(options);\n\n if (!rpc_server.RegisterService(static_cast<baidu::galaxy::proto::Agent*>(agent))) {\n LOG(WARNING) << \"failed to register agent service\";\n exit(-1);\n }\n\n std::string endpoint = \"0.0.0.0:\" + FLAGS_agent_port;\n agent->Setup();\n\n if (!rpc_server.Start(endpoint)) {\n LOG(WARNING) << \"failed to start server on \" << endpoint;\n exit(-2);\n }\n\n\n signal(SIGINT, SignalIntHandler);\n signal(SIGTERM, SignalIntHandler);\n signal(SIGCHLD, SigChldHandler);\n LOG(INFO) << \"agent started.\";\n\n while (!s_quit) {\n sleep(1);\n }\n\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include <signal.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"gflags\/gflags.h\"\n#include \"sofa\/pbrpc\/pbrpc.h\"\n#include \"utils\/http_server.h\"\n#include \"agent\/agent_impl.h\"\n#include \"utils\/build_info.h\"\n#include \"logging.h\"\n\nvolatile static bool s_is_stop = false;\n\nDECLARE_bool(v);\nDECLARE_string(agent_port);\nDECLARE_int32(agent_http_port);\nDECLARE_string(agent_work_dir);\nDECLARE_string(agent_gc_dir);\nDECLARE_string(agent_coredump_dir);\nDECLARE_string(log_file);\nDECLARE_int32(log_size);\nDECLARE_int32(log_cnt);\n\nvoid StopSigHandler(int \/*sig*\/) {\n s_is_stop = true;\n}\n\nvoid SigChldHandler(int \/*sig*\/) {\n int status = 0;\n while (true) {\n pid_t pid = ::waitpid(-1, &status, WNOHANG); \n if (pid == -1 || pid == 0) {\n return; \n }\n } \n}\n\nint main (int argc, char* argv[]) {\n\n using baidu::common::Log;\n using baidu::common::FATAL;\n using baidu::common::INFO;\n using baidu::common::WARNING;\n\n ::google::ParseCommandLineFlags(&argc, &argv, true);\n if (FLAGS_v) {\n fprintf(stdout, \"build version : %s\\n\", baidu::galaxy::GetVersion());\n fprintf(stdout, \"build time : %s\\n\", baidu::galaxy::GetBuildTime());\n return 0;\n }\n if (FLAGS_log_file != \"\") {\n baidu::common::SetLogFile(FLAGS_log_file.c_str());\n baidu::common::SetLogSize(FLAGS_log_size);\n baidu::common::SetLogCnt(FLAGS_log_cnt);\n }\n sofa::pbrpc::RpcServerOptions options;\n sofa::pbrpc::RpcServer rpc_server(options);\n\n baidu::galaxy::AgentImpl* agent_service = \n new baidu::galaxy::AgentImpl();\n if (!agent_service->Init()) {\n LOG(WARNING, \"agent service init failed\"); \n return EXIT_FAILURE;\n }\n\n if (!rpc_server.RegisterService(agent_service)) {\n LOG(WARNING, \"rpc server regist failed\"); \n return EXIT_FAILURE;\n }\n std::string server_host = std::string(\"0.0.0.0:\") \n + FLAGS_agent_port;\n\n if (!rpc_server.Start(server_host)) {\n LOG(WARNING, \"Rpc Server Start failed\");\n return EXIT_FAILURE;\n }\n std::vector<std::pair<std::string, std::string> > router;\n router.push_back(std::make_pair(\"\/gc\", FLAGS_agent_gc_dir));\n router.push_back(std::make_pair(\"\/container\", FLAGS_agent_work_dir));\n router.push_back(std::make_pair(\"\/coredump\", FLAGS_agent_coredump_dir));\n ::baidu::galaxy::HttpFileServer http_server(router, FLAGS_agent_http_port);\n http_server.Start(10);\n LOG(INFO, \"start http server on %d\", FLAGS_agent_http_port);\n signal(SIGINT, StopSigHandler);\n signal(SIGTERM, StopSigHandler);\n signal(SIGCHLD, SigChldHandler);\n while (!s_is_stop) {\n sleep(5); \n }\n\n return EXIT_SUCCESS; \n}\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<commit_msg>set total log cnt<commit_after>\/\/ Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include <signal.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"gflags\/gflags.h\"\n#include \"sofa\/pbrpc\/pbrpc.h\"\n#include \"utils\/http_server.h\"\n#include \"agent\/agent_impl.h\"\n#include \"utils\/build_info.h\"\n#include \"logging.h\"\n\nvolatile static bool s_is_stop = false;\n\nDECLARE_bool(v);\nDECLARE_string(agent_port);\nDECLARE_int32(agent_http_port);\nDECLARE_string(agent_work_dir);\nDECLARE_string(agent_gc_dir);\nDECLARE_string(agent_coredump_dir);\nDECLARE_string(log_file);\nDECLARE_int32(log_size);\nDECLARE_int32(log_cnt);\n\nvoid StopSigHandler(int \/*sig*\/) {\n s_is_stop = true;\n}\n\nvoid SigChldHandler(int \/*sig*\/) {\n int status = 0;\n while (true) {\n pid_t pid = ::waitpid(-1, &status, WNOHANG); \n if (pid == -1 || pid == 0) {\n return; \n }\n } \n}\n\nint main (int argc, char* argv[]) {\n\n using baidu::common::Log;\n using baidu::common::FATAL;\n using baidu::common::INFO;\n using baidu::common::WARNING;\n\n ::google::ParseCommandLineFlags(&argc, &argv, true);\n if (FLAGS_v) {\n fprintf(stdout, \"build version : %s\\n\", baidu::galaxy::GetVersion());\n fprintf(stdout, \"build time : %s\\n\", baidu::galaxy::GetBuildTime());\n return 0;\n }\n if (FLAGS_log_file != \"\") {\n baidu::common::SetLogCnt(FLAGS_log_cnt);\n baidu::common::SetLogFile(FLAGS_log_file.c_str());\n baidu::common::SetLogSize(FLAGS_log_size);\n }\n sofa::pbrpc::RpcServerOptions options;\n sofa::pbrpc::RpcServer rpc_server(options);\n\n baidu::galaxy::AgentImpl* agent_service = \n new baidu::galaxy::AgentImpl();\n if (!agent_service->Init()) {\n LOG(WARNING, \"agent service init failed\"); \n return EXIT_FAILURE;\n }\n\n if (!rpc_server.RegisterService(agent_service)) {\n LOG(WARNING, \"rpc server regist failed\"); \n return EXIT_FAILURE;\n }\n std::string server_host = std::string(\"0.0.0.0:\") \n + FLAGS_agent_port;\n\n if (!rpc_server.Start(server_host)) {\n LOG(WARNING, \"Rpc Server Start failed\");\n return EXIT_FAILURE;\n }\n std::vector<std::pair<std::string, std::string> > router;\n router.push_back(std::make_pair(\"\/gc\", FLAGS_agent_gc_dir));\n router.push_back(std::make_pair(\"\/container\", FLAGS_agent_work_dir));\n router.push_back(std::make_pair(\"\/coredump\", FLAGS_agent_coredump_dir));\n ::baidu::galaxy::HttpFileServer http_server(router, FLAGS_agent_http_port);\n http_server.Start(10);\n LOG(INFO, \"start http server on %d\", FLAGS_agent_http_port);\n signal(SIGINT, StopSigHandler);\n signal(SIGTERM, StopSigHandler);\n signal(SIGCHLD, SigChldHandler);\n while (!s_is_stop) {\n sleep(5); \n }\n\n return EXIT_SUCCESS; \n}\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetInputImageListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetInputImageListParameter::QtWidgetInputImageListParameter(InputImageListParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(m),\n m_InputImageListParam(param)\n{\n}\n\nQtWidgetInputImageListParameter::~QtWidgetInputImageListParameter()\n{\n}\n\nvoid QtWidgetInputImageListParameter::DoUpdateGUI()\n{\n\n}\n\nvoid QtWidgetInputImageListParameter::DoCreateWidget()\n{\nhg m_FileSelectionList.clear();\n const unsigned int sp(2);\n const unsigned int buttonSize(30);\n\n \/\/ Global layout\n QHBoxLayout * hLayout = new QHBoxLayout;\n hLayout->setSpacing(sp);\n hLayout->setContentsMargins(sp, sp, sp, sp);\n \n \/\/ Button layout\n QVBoxLayout * buttonLayout = new QVBoxLayout;\n buttonLayout->setSpacing(sp);\n buttonLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * addSupLayout = new QHBoxLayout;\n addSupLayout->setSpacing(sp);\n addSupLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * upDownLayout = new QHBoxLayout;\n upDownLayout->setSpacing(sp);\n upDownLayout->setContentsMargins(sp, sp, sp, sp);\n\n \/\/ Add file button\n QPushButton * addButton = new QPushButton;\n addButton->setText(\"+\");\n addButton->setFixedWidth(buttonSize);\n addButton->setToolTip(\"Add a file selector...\");\n addButton->setMaximumWidth(addButton->width());\n connect( addButton, SIGNAL(clicked()), this, SLOT(AddFile()) );\n addSupLayout->addWidget(addButton);\n\n \/\/ Supress file button\n QPushButton * supButton = new QPushButton;\n supButton->setText(\"-\");\n supButton->setFixedWidth(buttonSize);\n supButton->setToolTip(\"Supress the selected file...\");\n supButton->setMaximumWidth(supButton->width());\n connect( supButton, SIGNAL(clicked()), this, SLOT(SupressFile()) );\n addSupLayout->addWidget(supButton);\n buttonLayout->addLayout(addSupLayout);\n\n \/\/ Up file edit\n QPushButton * upButton = new QPushButton;\n upButton->setText(\"Up\");\n upButton->setFixedWidth(buttonSize);\n upButton->setToolTip(\"Up the selected file in the list...\");\n upButton->setMaximumWidth(upButton->width());\n connect( upButton, SIGNAL(clicked()), this, SLOT(UpFile()) );\n upDownLayout->addWidget(upButton);\n\n \/\/ Down file edit\n QPushButton * downButton = new QPushButton;\n downButton->setText(\"Down\");\n downButton->setFixedWidth(buttonSize);\n downButton->setToolTip(\"Down the selected file in the list...\");\n downButton->setMaximumWidth(downButton->width());\n connect( downButton, SIGNAL(clicked()), this, SLOT(DownFile()) );\n upDownLayout->addWidget(downButton);\n buttonLayout->addLayout(upDownLayout);\n\n \/\/ Erase file edit\n QPushButton * eraseButton = new QPushButton;\n eraseButton->setText(\"Erase\");\n eraseButton->setFixedWidth(2*buttonSize);\n eraseButton->setToolTip(\"Erase the selected file of the list...\");\n eraseButton->setMaximumWidth(eraseButton->width());\n connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseFile()) );\n buttonLayout->addWidget(eraseButton);\n\n QVBoxLayout * fileLayout = new QVBoxLayout();\n fileLayout->setSpacing(0);\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget(m_InputImageListParam);\n fileSelection->setFixedHeight(40);\n fileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(fileLayout);\n QScrollArea * scroll = new QScrollArea();\n scroll->setWidget(mainGroup);\n \/\/scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n\n hLayout->addWidget(scroll);\n hLayout->addLayout(buttonLayout);\n\n hLayout->addStretch();\n \n this->setLayout(hLayout);\n\n m_FileLayout = fileLayout;\n m_HLayout = hLayout;\n m_Scroll = scroll;\n\n}\n\n\nvoid\nQtWidgetInputImageListParameter::UpFile()\n{\n if(m_FileSelectionList.size() < 2 )\n return;\n\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(2);\n m_FileLayout->addStretch();\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n \n \/\/ Init map\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n idMap[i] = i;\n }\n \n \/\/ If the first item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_FileSelectionList[0]->IsChecked() )\n {\n m_FileSelectionList[0]->SetChecked(false);\n }\n\n \n \/\/ If other item are checked, up the index\n \/\/ Starts at 1 because the first item mustn't move\n for(unsigned int i=1; i<m_FileSelectionList.size(); i++ )\n {\n if( m_FileSelectionList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i-1;\n idMap[idMap[i-1]] = tmp;\n }\n }\n\n this->UpdateFileList( idMap );\n \n this->RecreateImageList();\n}\n\nvoid\nQtWidgetInputImageListParameter::DownFile()\n{\n if(m_FileSelectionList.size() < 2 )\n return;\n\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n \n \/\/ Init map\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n idMap[i] = i;\n }\n \n \/\/ If the last item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_FileSelectionList[m_FileSelectionList.size()-1]->IsChecked() )\n {\n m_FileSelectionList[m_FileSelectionList.size()-1]->SetChecked(false);\n }\n\n \n \/\/ If other item are checked, up the index\n \/\/ Stops at size-1 because the last item mustn't move\n for(int i=m_FileSelectionList.size()-2; i>=0; i-- )\n {\n if( m_FileSelectionList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i+1;\n idMap[idMap[i+1]] = tmp;\n }\n }\n \n this->UpdateFileList( idMap );\n\n this->RecreateImageList();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::UpdateFileList( std::map<unsigned int, unsigned int> idMap )\n{\n std::vector<QtFileSelectionWidget *> tmpList;\n \/\/ Keys become values and inverse\n std::map<unsigned int, unsigned int> idMapBis;\n for(unsigned int i=0; i<idMap.size(); i++ )\n {\n idMapBis[ idMap[i] ] = i;\n }\n \n \/\/ Create the new item list\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n m_FileLayout->addWidget( m_FileSelectionList[ idMapBis[i] ] );\n tmpList.push_back(m_FileSelectionList[ idMapBis[i] ]);\n }\n \n \n m_FileSelectionList = tmpList;\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n \n this->update();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::AddFile()\n{\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n m_FileLayout->addWidget( m_FileSelectionList[i] );\n }\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();\n fileSelection->setFixedHeight( 30 ); \n m_FileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\nvoid\nQtWidgetInputImageListParameter::SupressFile()\n{\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n std::vector<QtFileSelectionWidget *> tmpList;\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n if( !m_FileSelectionList[i]->IsChecked() )\n {\n m_FileLayout->addWidget( m_FileSelectionList[i] );\n tmpList.push_back(m_FileSelectionList[i]);\n }\n }\n \n m_FileSelectionList = tmpList;\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::EraseFile()\n{\n m_FileSelectionList.clear();\n\n m_FileLayout = new QVBoxLayout();\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();\n fileSelection->setFixedHeight( 40 );\n m_FileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\n\nvoid QtWidgetInputImageListParameter::RecreateImageList()\n{\n \/\/ save value\n m_InputImageListParam->Clear();\n for(unsigned int j=0; j<m_FileSelectionList.size(); j++ )\n {\n if( m_FileSelectionList[j]->GetFilename() != \"\" )\n m_InputImageListParam->AddFromFileName(m_FileSelectionList[j]->GetFilename());\n }\n\n \/\/ notify of value change\n QString key( QString::fromStdString(m_InputImageListParam->GetKey()) );\n emit ParameterChanged(key);\n}\n\n\n\n}\n}\n<commit_msg>COMP: error in file<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetInputImageListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetInputImageListParameter::QtWidgetInputImageListParameter(InputImageListParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(m),\n m_InputImageListParam(param)\n{\n}\n\nQtWidgetInputImageListParameter::~QtWidgetInputImageListParameter()\n{\n}\n\nvoid QtWidgetInputImageListParameter::DoUpdateGUI()\n{\n\n}\n\nvoid QtWidgetInputImageListParameter::DoCreateWidget()\n{\n m_FileSelectionList.clear();\n const unsigned int sp(2);\n const unsigned int buttonSize(30);\n\n \/\/ Global layout\n QHBoxLayout * hLayout = new QHBoxLayout;\n hLayout->setSpacing(sp);\n hLayout->setContentsMargins(sp, sp, sp, sp);\n \n \/\/ Button layout\n QVBoxLayout * buttonLayout = new QVBoxLayout;\n buttonLayout->setSpacing(sp);\n buttonLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * addSupLayout = new QHBoxLayout;\n addSupLayout->setSpacing(sp);\n addSupLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * upDownLayout = new QHBoxLayout;\n upDownLayout->setSpacing(sp);\n upDownLayout->setContentsMargins(sp, sp, sp, sp);\n\n \/\/ Add file button\n QPushButton * addButton = new QPushButton;\n addButton->setText(\"+\");\n addButton->setFixedWidth(buttonSize);\n addButton->setToolTip(\"Add a file selector...\");\n addButton->setMaximumWidth(addButton->width());\n connect( addButton, SIGNAL(clicked()), this, SLOT(AddFile()) );\n addSupLayout->addWidget(addButton);\n\n \/\/ Supress file button\n QPushButton * supButton = new QPushButton;\n supButton->setText(\"-\");\n supButton->setFixedWidth(buttonSize);\n supButton->setToolTip(\"Supress the selected file...\");\n supButton->setMaximumWidth(supButton->width());\n connect( supButton, SIGNAL(clicked()), this, SLOT(SupressFile()) );\n addSupLayout->addWidget(supButton);\n buttonLayout->addLayout(addSupLayout);\n\n \/\/ Up file edit\n QPushButton * upButton = new QPushButton;\n upButton->setText(\"Up\");\n upButton->setFixedWidth(buttonSize);\n upButton->setToolTip(\"Up the selected file in the list...\");\n upButton->setMaximumWidth(upButton->width());\n connect( upButton, SIGNAL(clicked()), this, SLOT(UpFile()) );\n upDownLayout->addWidget(upButton);\n\n \/\/ Down file edit\n QPushButton * downButton = new QPushButton;\n downButton->setText(\"Down\");\n downButton->setFixedWidth(buttonSize);\n downButton->setToolTip(\"Down the selected file in the list...\");\n downButton->setMaximumWidth(downButton->width());\n connect( downButton, SIGNAL(clicked()), this, SLOT(DownFile()) );\n upDownLayout->addWidget(downButton);\n buttonLayout->addLayout(upDownLayout);\n\n \/\/ Erase file edit\n QPushButton * eraseButton = new QPushButton;\n eraseButton->setText(\"Erase\");\n eraseButton->setFixedWidth(2*buttonSize);\n eraseButton->setToolTip(\"Erase the selected file of the list...\");\n eraseButton->setMaximumWidth(eraseButton->width());\n connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseFile()) );\n buttonLayout->addWidget(eraseButton);\n\n QVBoxLayout * fileLayout = new QVBoxLayout();\n fileLayout->setSpacing(0);\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget(m_InputImageListParam);\n fileSelection->setFixedHeight(40);\n fileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(fileLayout);\n QScrollArea * scroll = new QScrollArea();\n scroll->setWidget(mainGroup);\n \/\/scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n\n hLayout->addWidget(scroll);\n hLayout->addLayout(buttonLayout);\n\n hLayout->addStretch();\n \n this->setLayout(hLayout);\n\n m_FileLayout = fileLayout;\n m_HLayout = hLayout;\n m_Scroll = scroll;\n\n}\n\n\nvoid\nQtWidgetInputImageListParameter::UpFile()\n{\n if(m_FileSelectionList.size() < 2 )\n return;\n\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(2);\n m_FileLayout->addStretch();\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n \n \/\/ Init map\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n idMap[i] = i;\n }\n \n \/\/ If the first item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_FileSelectionList[0]->IsChecked() )\n {\n m_FileSelectionList[0]->SetChecked(false);\n }\n\n \n \/\/ If other item are checked, up the index\n \/\/ Starts at 1 because the first item mustn't move\n for(unsigned int i=1; i<m_FileSelectionList.size(); i++ )\n {\n if( m_FileSelectionList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i-1;\n idMap[idMap[i-1]] = tmp;\n }\n }\n\n this->UpdateFileList( idMap );\n \n this->RecreateImageList();\n}\n\nvoid\nQtWidgetInputImageListParameter::DownFile()\n{\n if(m_FileSelectionList.size() < 2 )\n return;\n\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n \n \/\/ Init map\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n idMap[i] = i;\n }\n \n \/\/ If the last item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_FileSelectionList[m_FileSelectionList.size()-1]->IsChecked() )\n {\n m_FileSelectionList[m_FileSelectionList.size()-1]->SetChecked(false);\n }\n\n \n \/\/ If other item are checked, up the index\n \/\/ Stops at size-1 because the last item mustn't move\n for(int i=m_FileSelectionList.size()-2; i>=0; i-- )\n {\n if( m_FileSelectionList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i+1;\n idMap[idMap[i+1]] = tmp;\n }\n }\n \n this->UpdateFileList( idMap );\n\n this->RecreateImageList();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::UpdateFileList( std::map<unsigned int, unsigned int> idMap )\n{\n std::vector<QtFileSelectionWidget *> tmpList;\n \/\/ Keys become values and inverse\n std::map<unsigned int, unsigned int> idMapBis;\n for(unsigned int i=0; i<idMap.size(); i++ )\n {\n idMapBis[ idMap[i] ] = i;\n }\n \n \/\/ Create the new item list\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n m_FileLayout->addWidget( m_FileSelectionList[ idMapBis[i] ] );\n tmpList.push_back(m_FileSelectionList[ idMapBis[i] ]);\n }\n \n \n m_FileSelectionList = tmpList;\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n \n this->update();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::AddFile()\n{\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n m_FileLayout->addWidget( m_FileSelectionList[i] );\n }\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();\n fileSelection->setFixedHeight( 30 ); \n m_FileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\nvoid\nQtWidgetInputImageListParameter::SupressFile()\n{\n m_FileLayout = new QVBoxLayout();\n m_FileLayout->setSpacing(0);\n m_FileLayout->addStretch();\n std::vector<QtFileSelectionWidget *> tmpList;\n for(unsigned int i=0; i<m_FileSelectionList.size(); i++ )\n {\n if( !m_FileSelectionList[i]->IsChecked() )\n {\n m_FileLayout->addWidget( m_FileSelectionList[i] );\n tmpList.push_back(m_FileSelectionList[i]);\n }\n }\n \n m_FileSelectionList = tmpList;\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\n\nvoid\nQtWidgetInputImageListParameter::EraseFile()\n{\n m_FileSelectionList.clear();\n\n m_FileLayout = new QVBoxLayout();\n\n QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget();\n fileSelection->setFixedHeight( 40 );\n m_FileLayout->addWidget( fileSelection );\n m_FileSelectionList.push_back(fileSelection);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_FileLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateImageList();\n}\n\n\nvoid QtWidgetInputImageListParameter::RecreateImageList()\n{\n \/\/ save value\n m_InputImageListParam->Clear();\n for(unsigned int j=0; j<m_FileSelectionList.size(); j++ )\n {\n if( m_FileSelectionList[j]->GetFilename() != \"\" )\n m_InputImageListParam->AddFromFileName(m_FileSelectionList[j]->GetFilename());\n }\n\n \/\/ notify of value change\n QString key( QString::fromStdString(m_InputImageListParam->GetKey()) );\n emit ParameterChanged(key);\n}\n\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <string>\n#include <assert.h>\n#include \"phstream.h\"\n#include <mpi.h>\n\n#ifndef PHSTREAM_TIMERS_ON\n#define PHSTREAM_TIMERS_ON 0\n#endif\n\nnamespace {\n inline double getTime() {\n return MPI_Wtime();\n }\n inline bool isRankZero() {\n int rank = 0;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n return !rank;\n }\n inline void printTime(const char* key, double t) {\n (void) key;\n (void) t;\n#if PHSTREAM_TIMERS_ON==1\n if( isRankZero() )\n fprintf(stderr, \"%s %f seconds\\n\", key, t);\n#endif\n }\n}\n\nextern \"C\" {\n struct RStream{\n char* restart;\n size_t rSz;\n };\n}\n\nextern \"C\" {\n struct GRStream{\n char *geom, *restart;\n size_t gSz, rSz;\n };\n}\n\nRStream* makeRStream() {\n const double t0 = getTime();\n RStream* rs = (RStream*) malloc(sizeof(RStream));\n rs->restart = NULL;\n rs->rSz = 0;\n printTime(__func__, getTime()-t0);\n return rs;\n}\n\n#ifdef __APPLE__\nFILE* openRStreamRead(RStream* rs) {\n return NULL;\n}\n#else\nFILE* openRStreamRead(RStream* rs) {\n const double t0 = getTime();\n FILE* f = fmemopen(rs->restart, rs->rSz, \"r\");\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\n#ifdef __APPLE__\nFILE* openRStreamWrite(RStream* rs) {\n return NULL;\n}\n#else\nFILE* openRStreamWrite(RStream* rs) {\n const double t0 = getTime();\n FILE* f = open_memstream(&(rs->restart), &(rs->rSz));\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\nvoid clearRStream(RStream* rs) {\n const double t0 = getTime();\n if(rs->restart) {\n free(rs->restart);\n rs->restart = NULL;\n rs->rSz = 0;\n }\n printTime(__func__, getTime()-t0);\n}\n\nvoid destroyRStream(RStream* rs) {\n const double t0 = getTime();\n clearRStream(rs);\n free(rs);\n printTime(__func__, getTime()-t0);\n}\n\nvoid attachRStream(GRStream* grs, RStream* rs) {\n const double t0 = getTime();\n rs->restart = grs->restart;\n rs->rSz = grs->rSz;\n grs->restart = NULL;\n grs->rSz = 0;\n printTime(__func__, getTime()-t0);\n}\n\n\nGRStream* makeGRStream() {\n const double t0 = getTime();\n GRStream* grs = (GRStream*) malloc(sizeof(GRStream));\n grs->geom = NULL;\n grs->gSz = 0;\n grs->restart = NULL;\n grs->rSz = 0;\n printTime(__func__, getTime()-t0);\n return grs;\n}\n\nvoid whichStream(const char* name, bool& isR, bool& isG) {\n const double t0 = getTime();\n std::string fname(name);\n std::string restartStr(\"restart\");\n std::string geombcStr(\"geombc\");\n isR = (fname.find(restartStr) != std::string::npos);\n isG = (fname.find(geombcStr) != std::string::npos);\n assert(isR != isG);\n printTime(__func__, getTime()-t0);\n}\n\nvoid writeUnknown(const char* fname) {\n fprintf(stderr,\n \"ERROR %s type of stream %s is unknown... exiting\\n\",\n __func__, fname);\n}\n\n#ifdef __APPLE__\nFILE* openGRStreamRead(GRStream* grs, const char* named) {\n return NULL;\n}\n#else\nFILE* openGRStreamRead(GRStream* grs, const char* named) {\n const double t0 = getTime();\n bool isR, isG;\n whichStream(named, isR, isG);\n FILE* f = NULL;\n if( isR && !isG )\n f = fmemopen(grs->restart, grs->rSz, \"r\");\n else if( isG && !isR )\n f = fmemopen(grs->geom, grs->gSz, \"r\");\n else {\n writeUnknown(named);\n exit(1);\n }\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\n#ifdef __APPLE__\nFILE* openGRStreamWrite(GRStream* grs, const char* named) {\n return NULL;\n}\n#else\nFILE* openGRStreamWrite(GRStream* grs, const char* named) {\n const double t0 = getTime();\n bool isR, isG;\n whichStream(named, isR, isG);\n FILE* f = NULL;\n if( isR && !isG )\n f = open_memstream(&(grs->restart), &(grs->rSz));\n else if( isG && !isR )\n f = open_memstream(&(grs->geom), &(grs->gSz));\n else {\n writeUnknown(named);\n exit(1);\n }\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\nvoid clearGRStream(GRStream* grs) {\n const double t0 = getTime();\n if(grs->geom) {\n free(grs->geom);\n grs->geom = NULL;\n grs->gSz = 0;\n }\n if(grs->restart) {\n free(grs->restart);\n grs->restart = NULL;\n grs->rSz = 0;\n }\n printTime(__func__, getTime()-t0);\n}\n\nvoid destroyGRStream(GRStream* grs) {\n const double t0 = getTime();\n clearGRStream(grs);\n free(grs);\n printTime(__func__, getTime()-t0);\n}\n\n<commit_msg>phstream : silence unused variable errors<commit_after>#include <stdlib.h>\n#include <string>\n#include <assert.h>\n#include \"phstream.h\"\n#include <mpi.h>\n\n#ifndef PHSTREAM_TIMERS_ON\n#define PHSTREAM_TIMERS_ON 0\n#endif\n\nnamespace {\n inline double getTime() {\n return MPI_Wtime();\n }\n#if PHSTREAM_TIMERS_ON==1\n inline bool isRankZero() {\n int rank = 0;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n return !rank;\n }\n#endif\n inline void printTime(const char* key, double t) {\n (void) key;\n (void) t;\n#if PHSTREAM_TIMERS_ON==1\n if( isRankZero() )\n fprintf(stderr, \"%s %f seconds\\n\", key, t);\n#endif\n }\n}\n\nextern \"C\" {\n struct RStream{\n char* restart;\n size_t rSz;\n };\n}\n\nextern \"C\" {\n struct GRStream{\n char *geom, *restart;\n size_t gSz, rSz;\n };\n}\n\nRStream* makeRStream() {\n const double t0 = getTime();\n RStream* rs = (RStream*) malloc(sizeof(RStream));\n rs->restart = NULL;\n rs->rSz = 0;\n printTime(__func__, getTime()-t0);\n return rs;\n}\n\n#ifdef __APPLE__\nFILE* openRStreamRead(RStream*) {\n return NULL;\n}\n#else\nFILE* openRStreamRead(RStream* rs) {\n const double t0 = getTime();\n FILE* f = fmemopen(rs->restart, rs->rSz, \"r\");\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\n#ifdef __APPLE__\nFILE* openRStreamWrite(RStream*) {\n return NULL;\n}\n#else\nFILE* openRStreamWrite(RStream* rs) {\n const double t0 = getTime();\n FILE* f = open_memstream(&(rs->restart), &(rs->rSz));\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\nvoid clearRStream(RStream* rs) {\n const double t0 = getTime();\n if(rs->restart) {\n free(rs->restart);\n rs->restart = NULL;\n rs->rSz = 0;\n }\n printTime(__func__, getTime()-t0);\n}\n\nvoid destroyRStream(RStream* rs) {\n const double t0 = getTime();\n clearRStream(rs);\n free(rs);\n printTime(__func__, getTime()-t0);\n}\n\nvoid attachRStream(GRStream* grs, RStream* rs) {\n const double t0 = getTime();\n rs->restart = grs->restart;\n rs->rSz = grs->rSz;\n grs->restart = NULL;\n grs->rSz = 0;\n printTime(__func__, getTime()-t0);\n}\n\n\nGRStream* makeGRStream() {\n const double t0 = getTime();\n GRStream* grs = (GRStream*) malloc(sizeof(GRStream));\n grs->geom = NULL;\n grs->gSz = 0;\n grs->restart = NULL;\n grs->rSz = 0;\n printTime(__func__, getTime()-t0);\n return grs;\n}\n\nvoid whichStream(const char* name, bool& isR, bool& isG) {\n const double t0 = getTime();\n std::string fname(name);\n std::string restartStr(\"restart\");\n std::string geombcStr(\"geombc\");\n isR = (fname.find(restartStr) != std::string::npos);\n isG = (fname.find(geombcStr) != std::string::npos);\n assert(isR != isG);\n printTime(__func__, getTime()-t0);\n}\n\nvoid writeUnknown(const char* fname) {\n fprintf(stderr,\n \"ERROR %s type of stream %s is unknown... exiting\\n\",\n __func__, fname);\n}\n\n#ifdef __APPLE__\nFILE* openGRStreamRead(GRStream*, const char*) {\n return NULL;\n}\n#else\nFILE* openGRStreamRead(GRStream* grs, const char* named) {\n const double t0 = getTime();\n bool isR, isG;\n whichStream(named, isR, isG);\n FILE* f = NULL;\n if( isR && !isG )\n f = fmemopen(grs->restart, grs->rSz, \"r\");\n else if( isG && !isR )\n f = fmemopen(grs->geom, grs->gSz, \"r\");\n else {\n writeUnknown(named);\n exit(1);\n }\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\n#ifdef __APPLE__\nFILE* openGRStreamWrite(GRStream*, const char*) {\n return NULL;\n}\n#else\nFILE* openGRStreamWrite(GRStream* grs, const char* named) {\n const double t0 = getTime();\n bool isR, isG;\n whichStream(named, isR, isG);\n FILE* f = NULL;\n if( isR && !isG )\n f = open_memstream(&(grs->restart), &(grs->rSz));\n else if( isG && !isR )\n f = open_memstream(&(grs->geom), &(grs->gSz));\n else {\n writeUnknown(named);\n exit(1);\n }\n printTime(__func__, getTime()-t0);\n return f;\n}\n#endif\n\nvoid clearGRStream(GRStream* grs) {\n const double t0 = getTime();\n if(grs->geom) {\n free(grs->geom);\n grs->geom = NULL;\n grs->gSz = 0;\n }\n if(grs->restart) {\n free(grs->restart);\n grs->restart = NULL;\n grs->rSz = 0;\n }\n printTime(__func__, getTime()-t0);\n}\n\nvoid destroyGRStream(GRStream* grs) {\n const double t0 = getTime();\n clearGRStream(grs);\n free(grs);\n printTime(__func__, getTime()-t0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2015 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include \"guids.hpp\"\n\n#include \"gtest\/gtest.h\"\n\n\n#define GUID_ENTRY(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8,name) \\\n TEST(guids, name_##name) { \\\n static const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; \\\n EXPECT_STREQ(#name, getGuidName(name)); \\\n }\n\n#include \"guids_entries.h\"\n\n\nTEST(guids, name_generic) {\n static const GUID dummy = {0x01234567,0x89AB,0xCDEF,{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF}};\n EXPECT_STREQ(\"uuid(01234567-89ab-cdef-0123-456789abcdef)\",\n getGuidName(dummy));\n}\n\n\nint\nmain(int argc, char **argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>guids: Single test for all known GUIDs.<commit_after>\/**************************************************************************\n *\n * Copyright 2015 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include \"guids.hpp\"\n\n#include \"gtest\/gtest.h\"\n\n\nTEST(guids, name_known)\n{\n\n# define GUID_ENTRY(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8,name) \\\n static const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; \\\n EXPECT_STREQ(#name, getGuidName(name));\n\n# include \"guids_entries.h\"\n\n}\n\n\nTEST(guids, name_unknown)\n{\n static const GUID dummy = {0x01234567,0x89AB,0xCDEF,{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF}};\n EXPECT_STREQ(\"uuid(01234567-89ab-cdef-0123-456789abcdef)\",\n getGuidName(dummy));\n}\n\n\nint\nmain(int argc, char **argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"structmember.h\"\n#include <stdexcept>\n\n#include \"neuron.hpp\"\n#include \"network.hpp\"\n\nint glob_argc;\nchar **glob_argv;\n\n\nvoid parse_iterable(std::vector<double> &arr, PyObject *iter)\n{\n while (true) {\n PyObject *next = PyIter_Next(iter);\n if (!next) {\n \/\/ nothing left in the iterator\n break;\n }\n\n if (!PyFloat_Check(next)) {\n throw std::invalid_argument(\"One of the arguments contains an illegal value (other than float)\");\n }\n\n double val = PyFloat_AsDouble(next);\n arr.push_back(val);\n }\n}\n\ntypedef struct {\n PyObject_HEAD\n Network * ptrObj;\n} PyNetwork;\n\ntypedef struct {\n PyObject_HEAD\n Neuron * ptrObj;\n} PyNeuron;\n\nstatic int PyNetwork_init(PyNetwork *self, PyObject *args, PyObject *kwargs)\n{\n int size;\n int input_dim = 0;\n int output_dim = 0;\n double connectivity = 0.01;\n int precision = 2;\n int randomly_fire = false;\n int dynamic_output = false;\n int visualization = false;\n double decay_factor = 1.0;\n\n static char *kwlist[] = {\"size\", \"input_dim\", \"output_dim\", \"connectivity\", \"precision\", \"randomly_fire\", \"dynamic_output\", \"visualization\", \"decay_factor\", NULL};\n\n if (! PyArg_ParseTupleAndKeywords(args, kwargs, \"i|iidipppd\", kwlist, &size, &input_dim, &output_dim, &connectivity, &precision, &randomly_fire, &dynamic_output, &visualization, &decay_factor))\n return -1;\n\n self->ptrObj = new Network(size, input_dim, output_dim, connectivity, precision, randomly_fire, dynamic_output, visualization, decay_factor);\n\n return 0;\n}\n\nstatic int PyNeuron_init(PyNeuron *self, PyObject *args)\n{\n PyNetwork * network;\n\n if (! PyArg_ParseTuple(args, \"O\", &network))\n return -1;\n\n self->ptrObj = new Neuron(*network->ptrObj);\n\n return 0;\n}\n\nstatic void PyNetwork_dealloc(PyNetwork * self)\n{\n delete self->ptrObj;\n Py_TYPE(self)->tp_free(self);\n}\n\nstatic void PyNeuron_dealloc(PyNeuron * self)\n{\n delete self->ptrObj;\n Py_TYPE(self)->tp_free(self);\n}\n\nstatic PyObject * PyNetwork_load(PyNetwork* self, PyObject* args, PyObject *kwargs)\n{\n std::vector<double> input_arr;\n std::vector<double> output_arr;\n PyObject *input_obj;\n PyObject *output_obj = Py_None;\n\n static char *kwlist[] = {\"input_obj\", \"output_obj\", NULL};\n\n if (! PyArg_ParseTupleAndKeywords(args, kwargs, \"O|O\", kwlist, &input_obj, &output_obj))\n throw std::invalid_argument(\"Wrong type of argument\");\n\n PyObject *input_iter = PyObject_GetIter(input_obj);\n if (!input_iter) {\n throw std::invalid_argument(\"Input argument is not iterable\");\n }\n parse_iterable(input_arr, input_iter);\n\n if (output_obj != Py_None) {\n PyObject *output_iter = PyObject_GetIter(output_obj);\n if (!output_iter) {\n throw std::invalid_argument(\"Output argument is not iterable\");\n }\n parse_iterable(output_arr, output_iter);\n }\n\n (self->ptrObj)->load(input_arr, output_arr);\n\n return Py_BuildValue(\"\");\n}\n\nstatic PyObject * PyNetwork_freeze(PyNetwork* self)\n{\n (self->ptrObj)->freeze();\n\n return Py_BuildValue(\"\");\n}\n\nstatic PyObject * PyNetwork_get_precision(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->precision);\n}\n\nstatic PyObject * PyNetwork_get_connectivity(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->connectivity);\n}\n\nstatic PyObject * PyNetwork_get_connectivity_sqrt(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->connectivity_sqrt);\n}\n\nstatic PyObject * PyNetwork_get_input_dim(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->input_dim);\n}\n\nstatic PyObject * PyNetwork_get_output_dim(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->output_dim);\n}\n\nstatic PyObject * PyNetwork_get_randomly_fire(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->randomly_fire);\n}\n\nstatic PyObject * PyNetwork_get_motor_randomly_fire_rate(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->motor_randomly_fire_rate);\n}\n\nstatic PyObject * PyNetwork_get_dynamic_output(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->dynamic_output);\n}\n\nstatic PyObject * PyNetwork_get_decay_factor(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"d\", self->ptrObj->decay_factor);\n}\n\nstatic PyObject * PyNetwork_get_initiated_neurons(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->initiated_neurons);\n}\n\nstatic PyObject * PyNetwork_get_freezer(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->freezer);\n}\n\nstatic PyObject * PyNetwork_get_thread_kill_signal(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->thread_kill_signal);\n}\n\nstatic PyObject * PyNetwork_get_wave_counter(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"l\", self->ptrObj->wave_counter);\n}\n\nstatic PyObject * PyNetwork_get_fire_counter(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"l\", self->ptrObj->fire_counter);\n}\n\nstatic PyObject * PyNetwork_get_output(PyNetwork *self, void *closure)\n{\n std::vector<double> output;\n\n output = (self->ptrObj)->get_output();\n\n PyObject *PList = PyList_New(0);\n std::vector<int>::const_iterator it;\n\n for (const auto& i: output)\n PyList_Append(PList, Py_BuildValue(\"d\", i));\n\n return PList;\n}\n\nstatic PyObject * PyNetwork_get_neurons(PyNetwork *self, void *closure)\n{\n std::vector<Neuron*> neurons = (self->ptrObj)->neurons;\n\n PyObject *PList = PyList_New(0);\n std::vector<int>::const_iterator it;\n\n for (const auto& i: neurons)\n PyList_Append(PList, Py_BuildValue(\"O\", i));\n\n return PList;\n}\n\nstatic PyMethodDef PyNetwork_methods[] = {\n {\"load\", (PyCFunction)PyNetwork_load, METH_VARARGS | METH_KEYWORDS, \"Load input and output into the neural network\" },\n {\"freeze\", (PyCFunction)PyNetwork_freeze, METH_NOARGS, \"Freeze the neural network\" },\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMethodDef PyNeuron_methods[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMemberDef PyNetwork_members[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMemberDef PyNeuron_members[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyGetSetDef PyNetwork_getseters[] = {\n {\"precision\", (getter)PyNetwork_get_precision, NULL, \"Precision of the network\", NULL},\n {\"connectivity\", (getter)PyNetwork_get_connectivity, NULL, \"Connectivity of the network\", NULL},\n {\"connectivity_sqrt\", (getter)PyNetwork_get_connectivity_sqrt, NULL, \"Square root of the connectivity of the network\", NULL},\n {\"input_dim\", (getter)PyNetwork_get_input_dim, NULL, \"Input dimension of the network\", NULL},\n {\"output_dim\", (getter)PyNetwork_get_output_dim, NULL, \"Output dimension of the network\", NULL},\n {\"randomly_fire\", (getter)PyNetwork_get_randomly_fire, NULL, \"Is randomly fire enabled for the network?\", NULL},\n {\"motor_randomly_fire_rate\", (getter)PyNetwork_get_motor_randomly_fire_rate, NULL, \"Motor neurons' randomly fire rate\", NULL},\n {\"dynamic_output\", (getter)PyNetwork_get_dynamic_output, NULL, \"Is dynamic output enabled for the network?\", NULL},\n {\"decay_factor\", (getter)PyNetwork_get_decay_factor, NULL, \"Decay factor of the network\", NULL},\n {\"initiated_neurons\", (getter)PyNetwork_get_initiated_neurons, NULL, \"Initiated neuron count of the network\", NULL},\n {\"freezer\", (getter)PyNetwork_get_freezer, NULL, \"Is freezing enabled for the network?\", NULL},\n {\"thread_kill_signal\", (getter)PyNetwork_get_thread_kill_signal, NULL, \"Are threads signalled for kill?\", NULL},\n {\"wave_counter\", (getter)PyNetwork_get_wave_counter, NULL, \"Holds the integer value of how many waves executed throughout the network\", NULL},\n {\"fire_counter\", (getter)PyNetwork_get_fire_counter, NULL, \"Holds the integer value of how many neurons fired during the training\", NULL},\n {\"output\", (getter)PyNetwork_get_output, NULL, \"Shows the output of the neural network\", NULL},\n {\"neurons\", (getter)PyNetwork_get_neurons, NULL, \"Holds the neurons in the neural network\", NULL},\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyTypeObject PyNetworkType = { PyVarObject_HEAD_INIT(NULL, 0)\n \"plexus.Network\" \/* tp_name *\/\n};\n\nstatic PyTypeObject PyNeuronType = { PyVarObject_HEAD_INIT(NULL, 0)\n \"plexus.Neuron\" \/* tp_name *\/\n};\n\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"cplexus\", \/* name of module *\/\n \"\", \/* module documentation, may be NULL *\/\n -1, \/* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. *\/\n NULL, NULL, NULL, NULL, NULL\n};\n\nPyMODINIT_FUNC PyInit_cplexus(void)\n\/\/ create the module\n{\n PyObject* m;\n\n PyNetworkType.tp_new = PyType_GenericNew;\n PyNetworkType.tp_basicsize=sizeof(PyNetwork);\n PyNetworkType.tp_dealloc=(destructor) PyNetwork_dealloc;\n PyNetworkType.tp_flags=Py_TPFLAGS_DEFAULT;\n PyNetworkType.tp_doc=\"Network objects\";\n PyNetworkType.tp_methods=PyNetwork_methods;\n PyNetworkType.tp_members=PyNetwork_members;\n PyNetworkType.tp_getset=PyNetwork_getseters;\n PyNetworkType.tp_init=(initproc)PyNetwork_init;\n\n PyNeuronType.tp_new = PyType_GenericNew;\n PyNeuronType.tp_basicsize=sizeof(PyNeuron);\n PyNeuronType.tp_dealloc=(destructor) PyNeuron_dealloc;\n PyNeuronType.tp_flags=Py_TPFLAGS_DEFAULT;\n PyNeuronType.tp_doc=\"Neuron objects\";\n PyNeuronType.tp_methods=PyNeuron_methods;\n PyNeuronType.tp_members=PyNeuron_members;\n PyNeuronType.tp_init=(initproc)PyNeuron_init;\n\n if (PyType_Ready(&PyNetworkType) < 0)\n return NULL;\n\n if (PyType_Ready(&PyNeuronType) < 0)\n return NULL;\n\n m = PyModule_Create(&moduledef);\n if (m == NULL)\n return NULL;\n\n Py_INCREF(&PyNetworkType);\n Py_INCREF(&PyNeuronType);\n PyModule_AddObject(m, \"Network\", (PyObject *)&PyNetworkType); \/\/ Add Network object to the module\n PyModule_AddObject(m, \"Neuron\", (PyObject *)&PyNeuronType); \/\/ Add Neuron object to the module\n return m;\n}\n\nvoid initcplexus(void)\n{\n PyInit_cplexus();\n}\n\nint main(int argc, char *argv[])\n{\n glob_argc = argc;\n glob_argv = argv;\n\n wchar_t *program = Py_DecodeLocale(argv[0], NULL);\n\n \/* Pass argv[0] to the Python interpreter *\/\n Py_SetProgramName(program);\n\n \/* Initialize the Python interpreter. Required. *\/\n Py_Initialize();\n\n \/* Add a static module *\/\n initcplexus();\n}\n<commit_msg>Append PyNeuron instead of Neuron to PyList in PyNetwork_get_neurons() function<commit_after>#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"structmember.h\"\n#include <stdexcept>\n\n#include \"neuron.hpp\"\n#include \"network.hpp\"\n\nint glob_argc;\nchar **glob_argv;\n\n\nvoid parse_iterable(std::vector<double> &arr, PyObject *iter)\n{\n while (true) {\n PyObject *next = PyIter_Next(iter);\n if (!next) {\n \/\/ nothing left in the iterator\n break;\n }\n\n if (!PyFloat_Check(next)) {\n throw std::invalid_argument(\"One of the arguments contains an illegal value (other than float)\");\n }\n\n double val = PyFloat_AsDouble(next);\n arr.push_back(val);\n }\n}\n\ntypedef struct {\n PyObject_HEAD\n Network * ptrObj;\n} PyNetwork;\n\ntypedef struct {\n PyObject_HEAD\n Neuron * ptrObj;\n} PyNeuron;\n\nstatic int PyNetwork_init(PyNetwork *self, PyObject *args, PyObject *kwargs)\n{\n int size;\n int input_dim = 0;\n int output_dim = 0;\n double connectivity = 0.01;\n int precision = 2;\n int randomly_fire = false;\n int dynamic_output = false;\n int visualization = false;\n double decay_factor = 1.0;\n\n static char *kwlist[] = {\"size\", \"input_dim\", \"output_dim\", \"connectivity\", \"precision\", \"randomly_fire\", \"dynamic_output\", \"visualization\", \"decay_factor\", NULL};\n\n if (! PyArg_ParseTupleAndKeywords(args, kwargs, \"i|iidipppd\", kwlist, &size, &input_dim, &output_dim, &connectivity, &precision, &randomly_fire, &dynamic_output, &visualization, &decay_factor))\n return -1;\n\n self->ptrObj = new Network(size, input_dim, output_dim, connectivity, precision, randomly_fire, dynamic_output, visualization, decay_factor);\n\n return 0;\n}\n\nstatic int PyNeuron_init(PyNeuron *self, PyObject *args)\n{\n PyNetwork * network;\n\n if (! PyArg_ParseTuple(args, \"O\", &network))\n return -1;\n\n self->ptrObj = new Neuron(*network->ptrObj);\n\n return 0;\n}\n\nstatic void PyNetwork_dealloc(PyNetwork * self)\n{\n delete self->ptrObj;\n Py_TYPE(self)->tp_free(self);\n}\n\nstatic void PyNeuron_dealloc(PyNeuron * self)\n{\n delete self->ptrObj;\n Py_TYPE(self)->tp_free(self);\n}\n\nstatic PyObject * PyNetwork_load(PyNetwork* self, PyObject* args, PyObject *kwargs)\n{\n std::vector<double> input_arr;\n std::vector<double> output_arr;\n PyObject *input_obj;\n PyObject *output_obj = Py_None;\n\n static char *kwlist[] = {\"input_obj\", \"output_obj\", NULL};\n\n if (! PyArg_ParseTupleAndKeywords(args, kwargs, \"O|O\", kwlist, &input_obj, &output_obj))\n throw std::invalid_argument(\"Wrong type of argument\");\n\n PyObject *input_iter = PyObject_GetIter(input_obj);\n if (!input_iter) {\n throw std::invalid_argument(\"Input argument is not iterable\");\n }\n parse_iterable(input_arr, input_iter);\n\n if (output_obj != Py_None) {\n PyObject *output_iter = PyObject_GetIter(output_obj);\n if (!output_iter) {\n throw std::invalid_argument(\"Output argument is not iterable\");\n }\n parse_iterable(output_arr, output_iter);\n }\n\n (self->ptrObj)->load(input_arr, output_arr);\n\n return Py_BuildValue(\"\");\n}\n\nstatic PyObject * PyNetwork_freeze(PyNetwork* self)\n{\n (self->ptrObj)->freeze();\n\n return Py_BuildValue(\"\");\n}\n\nstatic PyObject * PyNetwork_get_precision(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->precision);\n}\n\nstatic PyObject * PyNetwork_get_connectivity(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->connectivity);\n}\n\nstatic PyObject * PyNetwork_get_connectivity_sqrt(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->connectivity_sqrt);\n}\n\nstatic PyObject * PyNetwork_get_input_dim(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->input_dim);\n}\n\nstatic PyObject * PyNetwork_get_output_dim(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->output_dim);\n}\n\nstatic PyObject * PyNetwork_get_randomly_fire(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->randomly_fire);\n}\n\nstatic PyObject * PyNetwork_get_motor_randomly_fire_rate(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->motor_randomly_fire_rate);\n}\n\nstatic PyObject * PyNetwork_get_dynamic_output(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->dynamic_output);\n}\n\nstatic PyObject * PyNetwork_get_decay_factor(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"d\", self->ptrObj->decay_factor);\n}\n\nstatic PyObject * PyNetwork_get_initiated_neurons(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"i\", self->ptrObj->initiated_neurons);\n}\n\nstatic PyObject * PyNetwork_get_freezer(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->freezer);\n}\n\nstatic PyObject * PyNetwork_get_thread_kill_signal(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"b\", self->ptrObj->thread_kill_signal);\n}\n\nstatic PyObject * PyNetwork_get_wave_counter(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"l\", self->ptrObj->wave_counter);\n}\n\nstatic PyObject * PyNetwork_get_fire_counter(PyNetwork *self, void *closure)\n{\n return Py_BuildValue(\"l\", self->ptrObj->fire_counter);\n}\n\nstatic PyObject * PyNetwork_get_output(PyNetwork *self, void *closure)\n{\n std::vector<double> output;\n\n output = (self->ptrObj)->get_output();\n\n PyObject *PList = PyList_New(0);\n std::vector<int>::const_iterator it;\n\n for (const auto& i: output)\n PyList_Append(PList, Py_BuildValue(\"d\", i));\n\n return PList;\n}\n\nstatic PyObject * PyNetwork_get_neurons(PyNetwork *self, void *closure)\n{\n std::vector<Neuron*> neurons = (self->ptrObj)->neurons;\n\n PyObject *PList = PyList_New(0);\n std::vector<int>::const_iterator it;\n\n for (const auto& i: neurons) {\n PyNeuron * neuron = new PyNeuron;\n neuron->ptrObj = i;\n PyList_Append(PList, Py_BuildValue(\"O\", neuron));\n }\n return PList;\n}\n\nstatic PyMethodDef PyNetwork_methods[] = {\n {\"load\", (PyCFunction)PyNetwork_load, METH_VARARGS | METH_KEYWORDS, \"Load input and output into the neural network\" },\n {\"freeze\", (PyCFunction)PyNetwork_freeze, METH_NOARGS, \"Freeze the neural network\" },\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMethodDef PyNeuron_methods[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMemberDef PyNetwork_members[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyMemberDef PyNeuron_members[] = {\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyGetSetDef PyNetwork_getseters[] = {\n {\"precision\", (getter)PyNetwork_get_precision, NULL, \"Precision of the network\", NULL},\n {\"connectivity\", (getter)PyNetwork_get_connectivity, NULL, \"Connectivity of the network\", NULL},\n {\"connectivity_sqrt\", (getter)PyNetwork_get_connectivity_sqrt, NULL, \"Square root of the connectivity of the network\", NULL},\n {\"input_dim\", (getter)PyNetwork_get_input_dim, NULL, \"Input dimension of the network\", NULL},\n {\"output_dim\", (getter)PyNetwork_get_output_dim, NULL, \"Output dimension of the network\", NULL},\n {\"randomly_fire\", (getter)PyNetwork_get_randomly_fire, NULL, \"Is randomly fire enabled for the network?\", NULL},\n {\"motor_randomly_fire_rate\", (getter)PyNetwork_get_motor_randomly_fire_rate, NULL, \"Motor neurons' randomly fire rate\", NULL},\n {\"dynamic_output\", (getter)PyNetwork_get_dynamic_output, NULL, \"Is dynamic output enabled for the network?\", NULL},\n {\"decay_factor\", (getter)PyNetwork_get_decay_factor, NULL, \"Decay factor of the network\", NULL},\n {\"initiated_neurons\", (getter)PyNetwork_get_initiated_neurons, NULL, \"Initiated neuron count of the network\", NULL},\n {\"freezer\", (getter)PyNetwork_get_freezer, NULL, \"Is freezing enabled for the network?\", NULL},\n {\"thread_kill_signal\", (getter)PyNetwork_get_thread_kill_signal, NULL, \"Are threads signalled for kill?\", NULL},\n {\"wave_counter\", (getter)PyNetwork_get_wave_counter, NULL, \"Holds the integer value of how many waves executed throughout the network\", NULL},\n {\"fire_counter\", (getter)PyNetwork_get_fire_counter, NULL, \"Holds the integer value of how many neurons fired during the training\", NULL},\n {\"output\", (getter)PyNetwork_get_output, NULL, \"Shows the output of the neural network\", NULL},\n {\"neurons\", (getter)PyNetwork_get_neurons, NULL, \"Holds the neurons in the neural network\", NULL},\n {NULL} \/* Sentinel *\/\n};\n\nstatic PyTypeObject PyNetworkType = { PyVarObject_HEAD_INIT(NULL, 0)\n \"plexus.Network\" \/* tp_name *\/\n};\n\nstatic PyTypeObject PyNeuronType = { PyVarObject_HEAD_INIT(NULL, 0)\n \"plexus.Neuron\" \/* tp_name *\/\n};\n\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n \"cplexus\", \/* name of module *\/\n \"\", \/* module documentation, may be NULL *\/\n -1, \/* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. *\/\n NULL, NULL, NULL, NULL, NULL\n};\n\nPyMODINIT_FUNC PyInit_cplexus(void)\n\/\/ create the module\n{\n PyObject* m;\n\n PyNetworkType.tp_new = PyType_GenericNew;\n PyNetworkType.tp_basicsize=sizeof(PyNetwork);\n PyNetworkType.tp_dealloc=(destructor) PyNetwork_dealloc;\n PyNetworkType.tp_flags=Py_TPFLAGS_DEFAULT;\n PyNetworkType.tp_doc=\"Network objects\";\n PyNetworkType.tp_methods=PyNetwork_methods;\n PyNetworkType.tp_members=PyNetwork_members;\n PyNetworkType.tp_getset=PyNetwork_getseters;\n PyNetworkType.tp_init=(initproc)PyNetwork_init;\n\n PyNeuronType.tp_new = PyType_GenericNew;\n PyNeuronType.tp_basicsize=sizeof(PyNeuron);\n PyNeuronType.tp_dealloc=(destructor) PyNeuron_dealloc;\n PyNeuronType.tp_flags=Py_TPFLAGS_DEFAULT;\n PyNeuronType.tp_doc=\"Neuron objects\";\n PyNeuronType.tp_methods=PyNeuron_methods;\n PyNeuronType.tp_members=PyNeuron_members;\n PyNeuronType.tp_init=(initproc)PyNeuron_init;\n\n if (PyType_Ready(&PyNetworkType) < 0)\n return NULL;\n\n if (PyType_Ready(&PyNeuronType) < 0)\n return NULL;\n\n m = PyModule_Create(&moduledef);\n if (m == NULL)\n return NULL;\n\n Py_INCREF(&PyNetworkType);\n Py_INCREF(&PyNeuronType);\n PyModule_AddObject(m, \"Network\", (PyObject *)&PyNetworkType); \/\/ Add Network object to the module\n PyModule_AddObject(m, \"Neuron\", (PyObject *)&PyNeuronType); \/\/ Add Neuron object to the module\n return m;\n}\n\nvoid initcplexus(void)\n{\n PyInit_cplexus();\n}\n\nint main(int argc, char *argv[])\n{\n glob_argc = argc;\n glob_argv = argv;\n\n wchar_t *program = Py_DecodeLocale(argv[0], NULL);\n\n \/* Pass argv[0] to the Python interpreter *\/\n Py_SetProgramName(program);\n\n \/* Initialize the Python interpreter. Required. *\/\n Py_Initialize();\n\n \/* Add a static module *\/\n initcplexus();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 Baidu, Inc.G\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Lei He (helei@qiyi.com)\n\n#include <cmath>\n#include <gflags\/gflags.h>\n#include \"brpc\/errno.pb.h\"\n#include \"brpc\/policy\/auto_concurrency_limiter.h\"\n\nnamespace brpc {\nnamespace policy {\n\nDEFINE_int32(auto_cl_sample_window_size_ms, 1000, \"Duration of the sampling window.\");\nDEFINE_int32(auto_cl_min_sample_count, 100,\n \"During the duration of the sampling window, if the number of \"\n \"requests collected is less than this value, the sampling window \"\n \"will be discarded.\");\nDEFINE_int32(auto_cl_max_sample_count, 500,\n \"During the duration of the sampling window, once the number of \"\n \"requests collected is greater than this value, even if the \"\n \"duration of the window has not ended, the max_concurrency will \"\n \"be updated and a new sampling window will be started.\");\nDEFINE_double(auto_cl_sampling_interval_ms, 0.1, \n \"Interval for sampling request in auto concurrency limiter\");\nDEFINE_int32(auto_cl_initial_max_concurrency, 40,\n \"Initial max concurrency for grandient concurrency limiter\");\nDEFINE_int32(auto_cl_noload_latency_remeasure_interval_ms, 50000, \n \"Interval for remeasurement of noload_latency. In the period of \"\n \"remeasurement of noload_latency will halve max_concurrency.\");\nDEFINE_double(auto_cl_alpha_factor_for_ema, 0.1,\n \"The smoothing coefficient used in the calculation of ema, \"\n \"the value range is 0-1. The smaller the value, the smaller \"\n \"the effect of a single sample_window on max_concurrency.\");\nDEFINE_double(auto_cl_overload_threshold, 0.3, \n \"Expected ratio of latency fluctuations\");\nDEFINE_bool(auto_cl_enable_error_punish, true,\n \"Whether to consider failed requests when calculating maximum concurrency\");\nDEFINE_double(auto_cl_fail_punish_ratio, 1.0,\n \"Use the failed requests to punish normal requests. The larger \"\n \"the configuration item, the more aggressive the penalty strategy.\");\n\nstatic int32_t cast_max_concurrency(void* arg) {\n return *(int32_t*) arg;\n}\n\nAutoConcurrencyLimiter::AutoConcurrencyLimiter()\n : _remeasure_start_us(NextResetTime(butil::gettimeofday_us()))\n , _reset_latency_us(0)\n , _min_latency_us(-1)\n , _ema_peak_qps(-1)\n , _ema_factor(FLAGS_auto_cl_alpha_factor_for_ema)\n , _overload_threshold(FLAGS_auto_cl_overload_threshold)\n , _max_concurrency_bvar(cast_max_concurrency, &_max_concurrency)\n , _last_sampling_time_us(0)\n , _total_succ_req(0)\n , _current_concurrency(0) {\n _max_concurrency = FLAGS_auto_cl_initial_max_concurrency;\n}\n\nint AutoConcurrencyLimiter::Expose(const butil::StringPiece& prefix) {\n if (_max_concurrency_bvar.expose_as(prefix, \"auto_cl_max_concurrency\") != 0) {\n return -1;\n }\n return 0;\n}\n\nAutoConcurrencyLimiter* AutoConcurrencyLimiter::New() const {\n return new (std::nothrow) AutoConcurrencyLimiter;\n}\n\nvoid AutoConcurrencyLimiter::Destroy() {\n delete this;\n}\n\nbool AutoConcurrencyLimiter::OnRequested() {\n const int32_t current_concurrency = \n _current_concurrency.fetch_add(1, butil::memory_order_relaxed);\n if (current_concurrency >= _max_concurrency) {\n return false;\n }\n return true;\n}\n\nvoid AutoConcurrencyLimiter::OnResponded(int error_code, int64_t latency_us) {\n _current_concurrency.fetch_sub(1, butil::memory_order_relaxed);\n if (0 == error_code) {\n _total_succ_req.fetch_add(1, butil::memory_order_relaxed);\n } else if (ELIMIT == error_code) {\n return;\n }\n\n int64_t now_time_us = butil::gettimeofday_us();\n int64_t last_sampling_time_us = \n _last_sampling_time_us.load(butil::memory_order_relaxed);\n\n if (last_sampling_time_us == 0 || \n now_time_us - last_sampling_time_us >= \n FLAGS_auto_cl_sampling_interval_ms * 1000) {\n bool sample_this_call = _last_sampling_time_us.compare_exchange_strong(\n last_sampling_time_us, now_time_us, butil::memory_order_relaxed);\n if (sample_this_call) {\n int32_t max_concurrency = AddSample(error_code, latency_us, now_time_us);\n if (max_concurrency != 0) {\n LOG_EVERY_N(INFO, 60) \n << \"MaxConcurrency updated by auto limiter,\"\n << \"current_max_concurrency:\" << max_concurrency << \" \" << _min_latency_us;\n }\n }\n }\n}\n\nint64_t AutoConcurrencyLimiter::NextResetTime(int64_t sampling_time_us) {\n int64_t reset_start_us = sampling_time_us + \n (FLAGS_auto_cl_noload_latency_remeasure_interval_ms \/ 2 + \n butil::fast_rand_less_than(FLAGS_auto_cl_noload_latency_remeasure_interval_ms \/ 2)) * 1000;\n return reset_start_us;\n}\n\nint32_t AutoConcurrencyLimiter::AddSample(int error_code, \n int64_t latency_us, \n int64_t sampling_time_us) {\n std::unique_lock<butil::Mutex> lock_guard(_sw_mutex);\n \/\/ Waiting for the current concurrent decline\n if (_reset_latency_us > sampling_time_us) {\n return 0;\n }\n\n \/\/ Remeasure min_latency when concurrency has dropped to low load\n if (_reset_latency_us > 0) {\n _min_latency_us = -1;\n _reset_latency_us = 0;\n _remeasure_start_us = NextResetTime(sampling_time_us);\n ResetSampleWindow(sampling_time_us);\n }\n\n if (_sw.start_time_us == 0) {\n _sw.start_time_us = sampling_time_us;\n }\n\n if (error_code != 0 && FLAGS_auto_cl_enable_error_punish) {\n ++_sw.failed_count;\n _sw.total_failed_us += latency_us;\n } else if (error_code == 0) {\n ++_sw.succ_count;\n _sw.total_succ_us += latency_us;\n }\n\n if (_sw.succ_count + _sw.failed_count < FLAGS_auto_cl_min_sample_count) {\n if (sampling_time_us - _sw.start_time_us >= \n FLAGS_auto_cl_sample_window_size_ms * 1000) {\n \/\/ If the sample size is insufficient at the end of the sampling \n \/\/ window, discard the entire sampling window\n ResetSampleWindow(sampling_time_us);\n }\n return 0;\n } \n if (sampling_time_us - _sw.start_time_us < \n FLAGS_auto_cl_sample_window_size_ms * 1000 &&\n _sw.succ_count + _sw.failed_count < FLAGS_auto_cl_max_sample_count) {\n return 0;\n }\n\n if(_sw.succ_count > 0) {\n int max_concurrency = UpdateMaxConcurrency(sampling_time_us);\n ResetSampleWindow(sampling_time_us);\n return max_concurrency;\n } else {\n \/\/ All request failed\n _max_concurrency \/= 2;\n ResetSampleWindow(sampling_time_us);\n return 0;\n }\n}\n\nvoid AutoConcurrencyLimiter::ResetSampleWindow(int64_t sampling_time_us) {\n _sw.start_time_us = sampling_time_us;\n _sw.succ_count = 0;\n _sw.failed_count = 0;\n _sw.total_failed_us = 0;\n _sw.total_succ_us = 0;\n}\n\nvoid AutoConcurrencyLimiter::UpdateMinLatency(int64_t latency_us) {\n if (_min_latency_us <= 0) {\n _min_latency_us = latency_us;\n } else if (latency_us < _min_latency_us) {\n _min_latency_us = latency_us * _ema_factor + _min_latency_us * (1 - _ema_factor);\n }\n}\n\nvoid AutoConcurrencyLimiter::UpdateQps(int32_t succ_count, \n int64_t sampling_time_us) {\n double qps = 1000000.0 * succ_count \/ (sampling_time_us - _sw.start_time_us);\n\n if (qps >= _ema_peak_qps) {\n _ema_peak_qps = qps;\n } else {\n _ema_peak_qps = \n qps * (_ema_factor \/ 10) + _ema_peak_qps * (1 - _ema_factor \/ 10);\n }\n}\n\nint32_t AutoConcurrencyLimiter::UpdateMaxConcurrency(int64_t sampling_time_us) {\n int32_t total_succ_req = \n _total_succ_req.exchange(0, butil::memory_order_relaxed);\n double failed_punish = \n _sw.total_failed_us * FLAGS_auto_cl_fail_punish_ratio;\n int64_t avg_latency = \n std::ceil((failed_punish + _sw.total_succ_us) \/ _sw.succ_count);\n UpdateMinLatency(avg_latency);\n UpdateQps(total_succ_req, sampling_time_us);\n\n\n int next_max_concurrency = 0;\n \/\/ Remeasure min_latency at regular intervals\n if (_remeasure_start_us <= sampling_time_us) {\n _reset_latency_us = sampling_time_us + avg_latency * 2;\n next_max_concurrency = _max_concurrency * 0.75;\n } else {\n int32_t noload_concurrency = \n std::ceil(_min_latency_us * _ema_peak_qps \/ 1000000);\n if (avg_latency < (1.0 + _overload_threshold) * _min_latency_us) {\n next_max_concurrency = std::ceil(noload_concurrency * \n (2.0 + _overload_threshold - double(avg_latency) \/ _min_latency_us));\n } else {\n next_max_concurrency = noload_concurrency;\n }\n }\n\n if (next_max_concurrency != _max_concurrency) {\n _max_concurrency = next_max_concurrency;\n }\n return next_max_concurrency;\n}\n\n} \/\/ namespace policy\n} \/\/ namespace brpc\n<commit_msg>Modify the default value of auto_cl_max_sample_count<commit_after>\/\/ Copyright (c) 2014 Baidu, Inc.G\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Lei He (helei@qiyi.com)\n\n#include <cmath>\n#include <gflags\/gflags.h>\n#include \"brpc\/errno.pb.h\"\n#include \"brpc\/policy\/auto_concurrency_limiter.h\"\n\nnamespace brpc {\nnamespace policy {\n\nDEFINE_int32(auto_cl_sample_window_size_ms, 1000, \"Duration of the sampling window.\");\nDEFINE_int32(auto_cl_min_sample_count, 100,\n \"During the duration of the sampling window, if the number of \"\n \"requests collected is less than this value, the sampling window \"\n \"will be discarded.\");\nDEFINE_int32(auto_cl_max_sample_count, 200,\n \"During the duration of the sampling window, once the number of \"\n \"requests collected is greater than this value, even if the \"\n \"duration of the window has not ended, the max_concurrency will \"\n \"be updated and a new sampling window will be started.\");\nDEFINE_double(auto_cl_sampling_interval_ms, 0.1, \n \"Interval for sampling request in auto concurrency limiter\");\nDEFINE_int32(auto_cl_initial_max_concurrency, 40,\n \"Initial max concurrency for grandient concurrency limiter\");\nDEFINE_int32(auto_cl_noload_latency_remeasure_interval_ms, 50000, \n \"Interval for remeasurement of noload_latency. In the period of \"\n \"remeasurement of noload_latency will halve max_concurrency.\");\nDEFINE_double(auto_cl_alpha_factor_for_ema, 0.1,\n \"The smoothing coefficient used in the calculation of ema, \"\n \"the value range is 0-1. The smaller the value, the smaller \"\n \"the effect of a single sample_window on max_concurrency.\");\nDEFINE_double(auto_cl_overload_threshold, 0.3, \n \"Expected ratio of latency fluctuations\");\nDEFINE_bool(auto_cl_enable_error_punish, true,\n \"Whether to consider failed requests when calculating maximum concurrency\");\nDEFINE_double(auto_cl_fail_punish_ratio, 1.0,\n \"Use the failed requests to punish normal requests. The larger \"\n \"the configuration item, the more aggressive the penalty strategy.\");\n\nstatic int32_t cast_max_concurrency(void* arg) {\n return *(int32_t*) arg;\n}\n\nAutoConcurrencyLimiter::AutoConcurrencyLimiter()\n : _remeasure_start_us(NextResetTime(butil::gettimeofday_us()))\n , _reset_latency_us(0)\n , _min_latency_us(-1)\n , _ema_peak_qps(-1)\n , _ema_factor(FLAGS_auto_cl_alpha_factor_for_ema)\n , _overload_threshold(FLAGS_auto_cl_overload_threshold)\n , _max_concurrency_bvar(cast_max_concurrency, &_max_concurrency)\n , _last_sampling_time_us(0)\n , _total_succ_req(0)\n , _current_concurrency(0) {\n _max_concurrency = FLAGS_auto_cl_initial_max_concurrency;\n}\n\nint AutoConcurrencyLimiter::Expose(const butil::StringPiece& prefix) {\n if (_max_concurrency_bvar.expose_as(prefix, \"auto_cl_max_concurrency\") != 0) {\n return -1;\n }\n return 0;\n}\n\nAutoConcurrencyLimiter* AutoConcurrencyLimiter::New() const {\n return new (std::nothrow) AutoConcurrencyLimiter;\n}\n\nvoid AutoConcurrencyLimiter::Destroy() {\n delete this;\n}\n\nbool AutoConcurrencyLimiter::OnRequested() {\n const int32_t current_concurrency = \n _current_concurrency.fetch_add(1, butil::memory_order_relaxed);\n if (current_concurrency >= _max_concurrency) {\n return false;\n }\n return true;\n}\n\nvoid AutoConcurrencyLimiter::OnResponded(int error_code, int64_t latency_us) {\n _current_concurrency.fetch_sub(1, butil::memory_order_relaxed);\n if (0 == error_code) {\n _total_succ_req.fetch_add(1, butil::memory_order_relaxed);\n } else if (ELIMIT == error_code) {\n return;\n }\n\n int64_t now_time_us = butil::gettimeofday_us();\n int64_t last_sampling_time_us = \n _last_sampling_time_us.load(butil::memory_order_relaxed);\n\n if (last_sampling_time_us == 0 || \n now_time_us - last_sampling_time_us >= \n FLAGS_auto_cl_sampling_interval_ms * 1000) {\n bool sample_this_call = _last_sampling_time_us.compare_exchange_strong(\n last_sampling_time_us, now_time_us, butil::memory_order_relaxed);\n if (sample_this_call) {\n int32_t max_concurrency = AddSample(error_code, latency_us, now_time_us);\n if (max_concurrency != 0) {\n LOG_EVERY_N(INFO, 60) \n << \"MaxConcurrency updated by auto limiter,\"\n << \"current_max_concurrency:\" << max_concurrency \n << \", min_latency_us: \" << _min_latency_us;\n }\n }\n }\n}\n\nint64_t AutoConcurrencyLimiter::NextResetTime(int64_t sampling_time_us) {\n int64_t reset_start_us = sampling_time_us + \n (FLAGS_auto_cl_noload_latency_remeasure_interval_ms \/ 2 + \n butil::fast_rand_less_than(FLAGS_auto_cl_noload_latency_remeasure_interval_ms \/ 2)) * 1000;\n return reset_start_us;\n}\n\nint32_t AutoConcurrencyLimiter::AddSample(int error_code, \n int64_t latency_us, \n int64_t sampling_time_us) {\n std::unique_lock<butil::Mutex> lock_guard(_sw_mutex);\n \/\/ Waiting for the current concurrent decline\n if (_reset_latency_us > sampling_time_us) {\n return 0;\n }\n\n \/\/ Remeasure min_latency when concurrency has dropped to low load\n if (_reset_latency_us > 0) {\n _min_latency_us = -1;\n _reset_latency_us = 0;\n _remeasure_start_us = NextResetTime(sampling_time_us);\n ResetSampleWindow(sampling_time_us);\n }\n\n if (_sw.start_time_us == 0) {\n _sw.start_time_us = sampling_time_us;\n }\n\n if (error_code != 0 && FLAGS_auto_cl_enable_error_punish) {\n ++_sw.failed_count;\n _sw.total_failed_us += latency_us;\n } else if (error_code == 0) {\n ++_sw.succ_count;\n _sw.total_succ_us += latency_us;\n }\n\n if (_sw.succ_count + _sw.failed_count < FLAGS_auto_cl_min_sample_count) {\n if (sampling_time_us - _sw.start_time_us >= \n FLAGS_auto_cl_sample_window_size_ms * 1000) {\n \/\/ If the sample size is insufficient at the end of the sampling \n \/\/ window, discard the entire sampling window\n ResetSampleWindow(sampling_time_us);\n }\n return 0;\n } \n if (sampling_time_us - _sw.start_time_us < \n FLAGS_auto_cl_sample_window_size_ms * 1000 &&\n _sw.succ_count + _sw.failed_count < FLAGS_auto_cl_max_sample_count) {\n return 0;\n }\n\n if(_sw.succ_count > 0) {\n int max_concurrency = UpdateMaxConcurrency(sampling_time_us);\n ResetSampleWindow(sampling_time_us);\n return max_concurrency;\n } else {\n \/\/ All request failed\n _max_concurrency \/= 2;\n ResetSampleWindow(sampling_time_us);\n return 0;\n }\n}\n\nvoid AutoConcurrencyLimiter::ResetSampleWindow(int64_t sampling_time_us) {\n _sw.start_time_us = sampling_time_us;\n _sw.succ_count = 0;\n _sw.failed_count = 0;\n _sw.total_failed_us = 0;\n _sw.total_succ_us = 0;\n}\n\nvoid AutoConcurrencyLimiter::UpdateMinLatency(int64_t latency_us) {\n if (_min_latency_us <= 0) {\n _min_latency_us = latency_us;\n } else if (latency_us < _min_latency_us) {\n _min_latency_us = latency_us * _ema_factor + _min_latency_us * (1 - _ema_factor);\n }\n}\n\nvoid AutoConcurrencyLimiter::UpdateQps(int32_t succ_count, \n int64_t sampling_time_us) {\n double qps = 1000000.0 * succ_count \/ (sampling_time_us - _sw.start_time_us);\n\n if (qps >= _ema_peak_qps) {\n _ema_peak_qps = qps;\n } else {\n _ema_peak_qps = \n qps * (_ema_factor \/ 10) + _ema_peak_qps * (1 - _ema_factor \/ 10);\n }\n}\n\nint32_t AutoConcurrencyLimiter::UpdateMaxConcurrency(int64_t sampling_time_us) {\n int32_t total_succ_req = \n _total_succ_req.exchange(0, butil::memory_order_relaxed);\n double failed_punish = \n _sw.total_failed_us * FLAGS_auto_cl_fail_punish_ratio;\n int64_t avg_latency = \n std::ceil((failed_punish + _sw.total_succ_us) \/ _sw.succ_count);\n UpdateMinLatency(avg_latency);\n UpdateQps(total_succ_req, sampling_time_us);\n\n\n int next_max_concurrency = 0;\n \/\/ Remeasure min_latency at regular intervals\n if (_remeasure_start_us <= sampling_time_us) {\n _reset_latency_us = sampling_time_us + avg_latency * 2;\n next_max_concurrency = _max_concurrency * 0.75;\n } else {\n int32_t noload_concurrency = \n std::ceil(_min_latency_us * _ema_peak_qps \/ 1000000);\n if (avg_latency < (1.0 + _overload_threshold) * _min_latency_us) {\n next_max_concurrency = std::ceil(noload_concurrency * \n (2.0 + _overload_threshold - double(avg_latency) \/ _min_latency_us));\n } else {\n next_max_concurrency = noload_concurrency;\n }\n }\n\n if (next_max_concurrency != _max_concurrency) {\n _max_concurrency = next_max_concurrency;\n }\n return next_max_concurrency;\n}\n\n} \/\/ namespace policy\n} \/\/ namespace brpc\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2016 Sergio Martins <smartins@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"function-args-by-value.h\"\n#include \"Utils.h\"\n#include \"checkmanager.h\"\n#include \"StringUtils.h\"\n#include \"TypeUtils.h\"\n#include \"FixItUtils.h\"\n\n#include <clang\/AST\/AST.h>\n#include <clang\/Lex\/Lexer.h>\n\nusing namespace clang;\nusing namespace std;\n\nenum Fixit {\n FixitNone = 0,\n FixitAll = 0x1 \/\/ More granularity isn't needed I guess\n};\n\n\/\/ TODO, go over all these\nstatic bool shouldIgnoreClass(CXXRecordDecl *record)\n{\n if (!record)\n return false;\n\n if (Utils::isSharedPointer(record))\n return true;\n\n static const vector<string> ignoreList = {\"QDebug\", \/\/ Too many warnings\n \"QGenericReturnArgument\",\n \"QColor\", \/\/ TODO: Remove in Qt6\n \"QStringRef\", \/\/ TODO: Remove in Qt6\n \"QList::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QJsonArray::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QList<QString>::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QtMetaTypePrivate::QSequentialIterableImpl\",\n \"QtMetaTypePrivate::QAssociativeIterableImpl\",\n \"QVariantComparisonHelper\",\n \"QHashDummyValue\", \"QCharRef\", \"QString::Null\"\n };\n return clazy_std::contains(ignoreList, record->getQualifiedNameAsString());\n}\n\nstatic bool shouldIgnoreFunction(clang::FunctionDecl *function)\n{\n \/\/ Too many warnings in operator<<\n static const vector<string> ignoreList = {\"operator<<\"};\n static const vector<string> qualifiedIgnoreList = {\"QDBusMessage::createErrorReply\", \/\/ Fixed in Qt6\n \"QMenu::exec\", \/\/ Fixed in Qt6\n \"QTextFrame::iterator\", \/\/ Fixed in Qt6\n \"QGraphicsWidget::addActions\", \/\/ Fixed in Qt6\n \"QListWidget::mimeData\", \/\/ Fixed in Qt6\n \"QTableWidget::mimeData\", \/\/ Fixed in Qt6\n \"QTreeWidget::mimeData\", \/\/ Fixed in Qt6\n \"QWidget::addActions\", \/\/ Fixed in Qt6\n \"QSslCertificate::verify\", \/\/ Fixed in Qt6\n \"QSslConfiguration::setAllowedNextProtocols\" \/\/ Fixed in Qt6\n };\n if (clazy_std::contains(ignoreList, function->getNameAsString()))\n return true;\n\n return clazy_std::contains(qualifiedIgnoreList, function->getQualifiedNameAsString());\n}\n\nFunctionArgsByValue::FunctionArgsByValue(const std::string &name, ClazyContext *context)\n : CheckBase(name, context)\n{\n m_filesToIgnore = {\"\/c++\/\",\n \"qimage.cpp\", \/\/ TODO: Uncomment in Qt6\n \"qimage.h\", \/\/ TODO: Uncomment in Qt6\n \"qevent.h\", \/\/ TODO: Uncomment in Qt6\n \"avxintrin.h\",\n \"avx2intrin.h\",\n \"qnoncontiguousbytedevice.cpp\",\n \"qlocale_unix.cpp\",\n \"\/clang\/\",\n \"qmetatype.h\", \/\/ TODO: fix in Qt\n \"qbytearray.h\" \/\/ TODO: fix in Qt\n };\n}\n\nvoid FunctionArgsByValue::VisitDecl(Decl *decl)\n{\n processFunction(dyn_cast<FunctionDecl>(decl));\n}\n\nvoid FunctionArgsByValue::VisitStmt(Stmt *stmt)\n{\n if (LambdaExpr *lambda = dyn_cast<LambdaExpr>(stmt)) {\n if (!shouldIgnoreFile(stmt->getLocStart()))\n processFunction(lambda->getCallOperator());\n }\n}\n\nvoid FunctionArgsByValue::processFunction(FunctionDecl *func)\n{\n if (!func || shouldIgnoreFunction(func) ||\n !func->isThisDeclarationADefinition() || func->isDeleted())\n return;\n\n if (shouldIgnoreFile(func->getLocStart()))\n return;\n\n Stmt *body = func->getBody();\n\n int i = -1;\n for (auto param : Utils::functionParameters(func)) {\n i++;\n QualType paramQt = TypeUtils::unrefQualType(param->getType());\n const Type *paramType = paramQt.getTypePtrOrNull();\n if (!paramType || paramType->isIncompleteType() || paramType->isDependentType())\n continue;\n\n if (shouldIgnoreClass(paramType->getAsCXXRecordDecl()))\n continue;\n\n TypeUtils::QualTypeClassification classif;\n bool success = TypeUtils::classifyQualType(&m_astContext, param, classif, body);\n if (!success)\n continue;\n\n if (classif.passSmallTrivialByValue) {\n std::vector<FixItHint> fixits;\n if (isFixitEnabled(FixitAll)) {\n for (auto redecl : func->redecls()) { \/\/ Fix in both header and .cpp\n FunctionDecl *fdecl = dyn_cast<FunctionDecl>(redecl);\n const ParmVarDecl *param = fdecl->getParamDecl(i);\n fixits.push_back(fixit(fdecl, param, classif));\n }\n }\n\n const string paramStr = param->getType().getAsString();\n string error = \"Pass small and trivially-copyable type by value (\" + paramStr + ')';\n emitWarning(param->getLocStart(), error.c_str(), fixits);\n }\n }\n}\n\nFixItHint FunctionArgsByValue::fixit(FunctionDecl *func, const ParmVarDecl *param,\n TypeUtils::QualTypeClassification)\n{\n QualType qt = TypeUtils::unrefQualType(param->getType());\n qt.removeLocalConst();\n const string typeName = qt.getAsString(PrintingPolicy(lo()));\n string replacement = typeName + ' ' + string(param->getName());\n SourceLocation startLoc = param->getLocStart();\n SourceLocation endLoc = param->getLocEnd();\n\n const int numRedeclarations = std::distance(func->redecls_begin(), func->redecls_end());\n const bool definitionIsAlsoDeclaration = numRedeclarations == 1;\n const bool isDeclarationButNotDefinition = !func->doesThisDeclarationHaveABody();\n\n if (param->hasDefaultArg() && (isDeclarationButNotDefinition || definitionIsAlsoDeclaration)) {\n endLoc = param->getDefaultArg()->getLocStart().getLocWithOffset(-1);\n replacement += \" =\";\n }\n\n if (!startLoc.isValid() || !endLoc.isValid()) {\n llvm::errs() << \"Internal error could not apply fixit \" << startLoc.printToString(sm())\n << ';' << endLoc.printToString(sm()) << \"\\n\";\n return {};\n }\n\n return FixItUtils::createReplacement({ startLoc, endLoc }, replacement);\n}\n\nREGISTER_CHECK(\"function-args-by-value\", FunctionArgsByValue, CheckLevel2)\n<commit_msg>function-args-by-value: Don't warn in copy-ctors<commit_after>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2016-2017 Sergio Martins <smartins@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"function-args-by-value.h\"\n#include \"Utils.h\"\n#include \"checkmanager.h\"\n#include \"StringUtils.h\"\n#include \"TypeUtils.h\"\n#include \"FixItUtils.h\"\n\n#include <clang\/AST\/AST.h>\n#include <clang\/Lex\/Lexer.h>\n\nusing namespace clang;\nusing namespace std;\n\nenum Fixit {\n FixitNone = 0,\n FixitAll = 0x1 \/\/ More granularity isn't needed I guess\n};\n\n\/\/ TODO, go over all these\nstatic bool shouldIgnoreClass(CXXRecordDecl *record)\n{\n if (!record)\n return false;\n\n if (Utils::isSharedPointer(record))\n return true;\n\n static const vector<string> ignoreList = {\"QDebug\", \/\/ Too many warnings\n \"QGenericReturnArgument\",\n \"QColor\", \/\/ TODO: Remove in Qt6\n \"QStringRef\", \/\/ TODO: Remove in Qt6\n \"QList::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QJsonArray::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QList<QString>::const_iterator\", \/\/ TODO: Remove in Qt6\n \"QtMetaTypePrivate::QSequentialIterableImpl\",\n \"QtMetaTypePrivate::QAssociativeIterableImpl\",\n \"QVariantComparisonHelper\",\n \"QHashDummyValue\", \"QCharRef\", \"QString::Null\"\n };\n return clazy_std::contains(ignoreList, record->getQualifiedNameAsString());\n}\n\nstatic bool shouldIgnoreFunction(clang::FunctionDecl *function)\n{\n \/\/ Too many warnings in operator<<\n static const vector<string> ignoreList = {\"operator<<\"};\n static const vector<string> qualifiedIgnoreList = {\"QDBusMessage::createErrorReply\", \/\/ Fixed in Qt6\n \"QMenu::exec\", \/\/ Fixed in Qt6\n \"QTextFrame::iterator\", \/\/ Fixed in Qt6\n \"QGraphicsWidget::addActions\", \/\/ Fixed in Qt6\n \"QListWidget::mimeData\", \/\/ Fixed in Qt6\n \"QTableWidget::mimeData\", \/\/ Fixed in Qt6\n \"QTreeWidget::mimeData\", \/\/ Fixed in Qt6\n \"QWidget::addActions\", \/\/ Fixed in Qt6\n \"QSslCertificate::verify\", \/\/ Fixed in Qt6\n \"QSslConfiguration::setAllowedNextProtocols\" \/\/ Fixed in Qt6\n };\n if (clazy_std::contains(ignoreList, function->getNameAsString()))\n return true;\n\n return clazy_std::contains(qualifiedIgnoreList, function->getQualifiedNameAsString());\n}\n\nFunctionArgsByValue::FunctionArgsByValue(const std::string &name, ClazyContext *context)\n : CheckBase(name, context)\n{\n m_filesToIgnore = {\"\/c++\/\",\n \"qimage.cpp\", \/\/ TODO: Uncomment in Qt6\n \"qimage.h\", \/\/ TODO: Uncomment in Qt6\n \"qevent.h\", \/\/ TODO: Uncomment in Qt6\n \"avxintrin.h\",\n \"avx2intrin.h\",\n \"qnoncontiguousbytedevice.cpp\",\n \"qlocale_unix.cpp\",\n \"\/clang\/\",\n \"qmetatype.h\", \/\/ TODO: fix in Qt\n \"qbytearray.h\" \/\/ TODO: fix in Qt\n };\n}\n\nvoid FunctionArgsByValue::VisitDecl(Decl *decl)\n{\n processFunction(dyn_cast<FunctionDecl>(decl));\n}\n\nvoid FunctionArgsByValue::VisitStmt(Stmt *stmt)\n{\n if (LambdaExpr *lambda = dyn_cast<LambdaExpr>(stmt)) {\n if (!shouldIgnoreFile(stmt->getLocStart()))\n processFunction(lambda->getCallOperator());\n }\n}\n\nvoid FunctionArgsByValue::processFunction(FunctionDecl *func)\n{\n if (!func || shouldIgnoreFunction(func) ||\n !func->isThisDeclarationADefinition() || func->isDeleted())\n return;\n\n if (shouldIgnoreFile(func->getLocStart()))\n return;\n\n if (auto ctor = dyn_cast<CXXConstructorDecl>(func)) {\n if (ctor->isCopyConstructor())\n return; \/\/ copy-ctor must take by ref\n }\n\n Stmt *body = func->getBody();\n\n int i = -1;\n for (auto param : Utils::functionParameters(func)) {\n i++;\n QualType paramQt = TypeUtils::unrefQualType(param->getType());\n const Type *paramType = paramQt.getTypePtrOrNull();\n if (!paramType || paramType->isIncompleteType() || paramType->isDependentType())\n continue;\n\n if (shouldIgnoreClass(paramType->getAsCXXRecordDecl()))\n continue;\n\n TypeUtils::QualTypeClassification classif;\n bool success = TypeUtils::classifyQualType(&m_astContext, param, classif, body);\n if (!success)\n continue;\n\n if (classif.passSmallTrivialByValue) {\n std::vector<FixItHint> fixits;\n if (isFixitEnabled(FixitAll)) {\n for (auto redecl : func->redecls()) { \/\/ Fix in both header and .cpp\n FunctionDecl *fdecl = dyn_cast<FunctionDecl>(redecl);\n const ParmVarDecl *param = fdecl->getParamDecl(i);\n fixits.push_back(fixit(fdecl, param, classif));\n }\n }\n\n const string paramStr = param->getType().getAsString();\n string error = \"Pass small and trivially-copyable type by value (\" + paramStr + ')';\n emitWarning(param->getLocStart(), error.c_str(), fixits);\n }\n }\n}\n\nFixItHint FunctionArgsByValue::fixit(FunctionDecl *func, const ParmVarDecl *param,\n TypeUtils::QualTypeClassification)\n{\n QualType qt = TypeUtils::unrefQualType(param->getType());\n qt.removeLocalConst();\n const string typeName = qt.getAsString(PrintingPolicy(lo()));\n string replacement = typeName + ' ' + string(param->getName());\n SourceLocation startLoc = param->getLocStart();\n SourceLocation endLoc = param->getLocEnd();\n\n const int numRedeclarations = std::distance(func->redecls_begin(), func->redecls_end());\n const bool definitionIsAlsoDeclaration = numRedeclarations == 1;\n const bool isDeclarationButNotDefinition = !func->doesThisDeclarationHaveABody();\n\n if (param->hasDefaultArg() && (isDeclarationButNotDefinition || definitionIsAlsoDeclaration)) {\n endLoc = param->getDefaultArg()->getLocStart().getLocWithOffset(-1);\n replacement += \" =\";\n }\n\n if (!startLoc.isValid() || !endLoc.isValid()) {\n llvm::errs() << \"Internal error could not apply fixit \" << startLoc.printToString(sm())\n << ';' << endLoc.printToString(sm()) << \"\\n\";\n return {};\n }\n\n return FixItUtils::createReplacement({ startLoc, endLoc }, replacement);\n}\n\nREGISTER_CHECK(\"function-args-by-value\", FunctionArgsByValue, CheckLevel2)\n<|endoftext|>"} {"text":"<commit_before>#include <getopt.h>\n#include <string>\n#include <math.h>\n\n#include <boost\/lexical_cast.hpp>\n\n#include <boost\/asio.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <libwatcher\/client.h>\n#include <libwatcher\/gpsMessage.h>\n#include <libwatcher\/labelMessage.h>\n#include <libwatcher\/edgeMessage.h>\n#include <libwatcher\/watcherColors.h>\n#include \"logger.h\"\n#include \"sendMessageHandler.h\"\n\nusing namespace std;\nusing namespace watcher;\nusing namespace watcher::event;\nusing namespace boost;\n\n#define PI (3.141592653589793) \/\/ Isn't this #DEFINEd somewhere?\n\nvoid usage(const char *progName)\n{ \n fprintf(stderr, \"Usage: %s [args]\\n\", basename(progName)); \n fprintf(stderr, \"Args:\\n\");\n fprintf(stderr, \" -s, --server=address The addres of the node running watcherd\\n\"); \n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Optional args:\\n\");\n fprintf(stderr, \" -p, --logProps log.properties file, which controls logging for this program\\n\");\n fprintf(stderr, \" -r, --radius The radius of the circle in some unknown unit\\n\"); \n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" -h, --help Show this message\\n\"); \n\n exit(1); \n}\n\nint main(int argc, char **argv)\n{\n TRACE_ENTER();\n\n int c;\n string server;\n string logProps(string(basename(argv[0]))+string(\".log.properties\"));\n double radius=50.0; \n\n while (true) \n {\n int option_index = 0;\n static struct option long_options[] = {\n {\"server\", required_argument, 0, 's'},\n {\"logProps\", required_argument, 0, 'p'},\n {\"radius\", required_argument, 0, 'r'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n };\n\n c = getopt_long(argc, argv, \"r:s:p:hH?\", long_options, &option_index);\n\n if (c == -1)\n break;\n\n switch(c)\n {\n case 's': \n server=optarg; \n break;\n case 'p': \n logProps=optarg; \n break;\n case 'r':\n radius=lexical_cast<double>(optarg);\n break;\n case 'h':\n case 'H':\n case '?':\n default:\n usage(argv[0]); \n break;\n }\n }\n\n if (server==\"\")\n {\n usage(argv[0]);\n exit(1); \n }\n\n \/\/\n \/\/ Now do some actual work.\n \/\/ \n LOAD_LOG_PROPS(logProps);\n\n Client client(server); \n LOG_INFO(\"Connecting to \" << server << \" and sending message.\"); \n \/\/ Do not add empty handler - default Client handler does not close connection.\n \/\/ client.addMessageHandler(SendMessageHandler::create());\n\n unsigned int loopTime=1; \n \/\/ Create hour, min, sec, and center nodes.\n NodeIdentifier centerId=NodeIdentifier::from_string(\"192.168.1.100\");\n NodeIdentifier hourId=NodeIdentifier::from_string(\"192.168.1.101\");\n NodeIdentifier minId=NodeIdentifier::from_string(\"192.168.1.102\");\n NodeIdentifier secId=NodeIdentifier::from_string(\"192.168.1.103\");\n\n const GUILayer layer(\"Clock\"); \n const double step=(2*PI)\/60;\n struct \n {\n double theta;\n NodeIdentifier *id;\n const char *label;\n Color color;\n } nodeData[]=\n {\n { 0, &hourId, \"hour\", Color::red }, \n { 0, &minId, \"min\", Color::blue }, \n { 0, &secId, \"sec\", Color::green }, \n };\n while (true) \/\/ draw everything all the time as we don't know when watcher will start\n {\n \/\/ Draw center node\n GPSMessagePtr gpsMess(new GPSMessage(radius, radius, 0));\n gpsMess->layer=layer;\n gpsMess->fromNodeID=centerId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n \/\/ draw hour, min, and second nodes, connecting them to center.\n for (unsigned int i=0; i<sizeof(nodeData)\/sizeof(nodeData[0]); i++)\n {\n \/\/ update location offsets by current time.\n time_t nowInSecs=time(NULL);\n struct tm *now=localtime(&nowInSecs);\n if (*nodeData[i].id==hourId)\n nodeData[i].theta=step*((now->tm_hour*(60\/12))+(now->tm_min\/12));\n else if(*nodeData[i].id==minId)\n nodeData[i].theta=step*now->tm_min;\n else if(*nodeData[i].id==secId)\n nodeData[i].theta=step*now->tm_sec;\n\n \/\/ Move hour. min, and sec nodes to appropriate locations. \n GPSMessagePtr gpsMess(new GPSMessage((sin(nodeData[i].theta)*radius)+radius, (cos(nodeData[i].theta)*radius)+radius, 0.0));\n gpsMess->layer=layer;\n gpsMess->fromNodeID=*nodeData[i].id;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n\n LabelMessagePtr labMess(new LabelMessage(nodeData[i].label));\n labMess->layer=layer;\n labMess->expiration=loopTime*2000; \/\/ 2000 to stop blinking\n EdgeMessagePtr edgeMess(new EdgeMessage(centerId, *nodeData[i].id, layer, nodeData[i].color, 2));\n edgeMess->middleLabel=labMess;\n if(!client.sendMessage(edgeMess))\n {\n LOG_ERROR(\"Error sending edge message: \" << *edgeMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ add nodes at clock face number locations.\n double theta=(2*PI)\/12;\n for (unsigned int i=0; i<12; i++, theta+=(2*PI)\/12)\n {\n NodeIdentifier thisId=NodeIdentifier::from_string(\"192.168.2.\" + lexical_cast<string>(i+1));\n double faceRad=radius*1.15;\n GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); \n gpsMess->layer=layer;\n gpsMess->fromNodeID=thisId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ add nodes at clock face second locations.\n theta=(2*PI)\/60;\n for (unsigned int i=0; i<60; i++, theta+=(2*PI)\/60)\n {\n NodeIdentifier thisId=NodeIdentifier::from_string(\"192.168.3.\" + lexical_cast<string>(i+1));\n double faceRad=radius*1.35;\n GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); \n gpsMess->layer=layer;\n gpsMess->fromNodeID=thisId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n sleep(loopTime); \n }\n\n client.wait();\n\n TRACE_EXIT_RET(EXIT_SUCCESS);\n return EXIT_SUCCESS;\n}\n\n<commit_msg>stagger \"hands\" slightly on the z axis, so the colors blend when they are on top of each other.<commit_after>#include <getopt.h>\n#include <string>\n#include <math.h>\n\n#include <boost\/lexical_cast.hpp>\n\n#include <boost\/asio.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <libwatcher\/client.h>\n#include <libwatcher\/gpsMessage.h>\n#include <libwatcher\/labelMessage.h>\n#include <libwatcher\/edgeMessage.h>\n#include <libwatcher\/watcherColors.h>\n#include \"logger.h\"\n#include \"sendMessageHandler.h\"\n\nusing namespace std;\nusing namespace watcher;\nusing namespace watcher::event;\nusing namespace boost;\n\n#define PI (3.141592653589793) \/\/ Isn't this #DEFINEd somewhere?\n\nvoid usage(const char *progName)\n{ \n fprintf(stderr, \"Usage: %s [args]\\n\", basename(progName)); \n fprintf(stderr, \"Args:\\n\");\n fprintf(stderr, \" -s, --server=address The addres of the node running watcherd\\n\"); \n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Optional args:\\n\");\n fprintf(stderr, \" -p, --logProps log.properties file, which controls logging for this program\\n\");\n fprintf(stderr, \" -r, --radius The radius of the circle in some unknown unit\\n\"); \n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" -h, --help Show this message\\n\"); \n\n exit(1); \n}\n\nint main(int argc, char **argv)\n{\n TRACE_ENTER();\n\n int c;\n string server;\n string logProps(string(basename(argv[0]))+string(\".log.properties\"));\n double radius=50.0; \n\n while (true) \n {\n int option_index = 0;\n static struct option long_options[] = {\n {\"server\", required_argument, 0, 's'},\n {\"logProps\", required_argument, 0, 'p'},\n {\"radius\", required_argument, 0, 'r'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n };\n\n c = getopt_long(argc, argv, \"r:s:p:hH?\", long_options, &option_index);\n\n if (c == -1)\n break;\n\n switch(c)\n {\n case 's': \n server=optarg; \n break;\n case 'p': \n logProps=optarg; \n break;\n case 'r':\n radius=lexical_cast<double>(optarg);\n break;\n case 'h':\n case 'H':\n case '?':\n default:\n usage(argv[0]); \n break;\n }\n }\n\n if (server==\"\")\n {\n usage(argv[0]);\n exit(1); \n }\n\n \/\/\n \/\/ Now do some actual work.\n \/\/ \n LOAD_LOG_PROPS(logProps);\n\n Client client(server); \n LOG_INFO(\"Connecting to \" << server << \" and sending message.\"); \n \/\/ Do not add empty handler - default Client handler does not close connection.\n \/\/ client.addMessageHandler(SendMessageHandler::create());\n\n unsigned int loopTime=1; \n \/\/ Create hour, min, sec, and center nodes.\n NodeIdentifier centerId=NodeIdentifier::from_string(\"192.168.1.100\");\n NodeIdentifier hourId=NodeIdentifier::from_string(\"192.168.1.101\");\n NodeIdentifier minId=NodeIdentifier::from_string(\"192.168.1.102\");\n NodeIdentifier secId=NodeIdentifier::from_string(\"192.168.1.103\");\n\n const GUILayer layer(\"Clock\"); \n const double step=(2*PI)\/60;\n struct \n {\n double theta;\n NodeIdentifier *id;\n const char *label;\n Color color;\n } nodeData[]=\n {\n { 0, &hourId, \"hour\", Color::red }, \n { 0, &minId, \"min\", Color::blue }, \n { 0, &secId, \"sec\", Color::green }, \n };\n while (true) \/\/ draw everything all the time as we don't know when watcher will start\n {\n \/\/ Draw center node\n GPSMessagePtr gpsMess(new GPSMessage(radius, radius, 0));\n gpsMess->layer=layer;\n gpsMess->fromNodeID=centerId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n \/\/ draw hour, min, and second nodes, connecting them to center.\n for (unsigned int i=0; i<sizeof(nodeData)\/sizeof(nodeData[0]); i++)\n {\n \/\/ update location offsets by current time.\n time_t nowInSecs=time(NULL);\n struct tm *now=localtime(&nowInSecs);\n if (*nodeData[i].id==hourId)\n nodeData[i].theta=step*((now->tm_hour*(60\/12))+(now->tm_min\/12));\n else if(*nodeData[i].id==minId)\n nodeData[i].theta=step*now->tm_min;\n else if(*nodeData[i].id==secId)\n nodeData[i].theta=step*now->tm_sec;\n\n \/\/ Move hour. min, and sec nodes to appropriate locations. \n GPSMessagePtr gpsMess(new GPSMessage((sin(nodeData[i].theta)*radius)+radius, (cos(nodeData[i].theta)*radius)+radius, (double)i));\n gpsMess->layer=layer;\n gpsMess->fromNodeID=*nodeData[i].id;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n\n LabelMessagePtr labMess(new LabelMessage(nodeData[i].label));\n labMess->layer=layer;\n labMess->expiration=loopTime*2000; \/\/ 2000 to stop blinking\n EdgeMessagePtr edgeMess(new EdgeMessage(centerId, *nodeData[i].id, layer, nodeData[i].color, 2));\n edgeMess->middleLabel=labMess;\n if(!client.sendMessage(edgeMess))\n {\n LOG_ERROR(\"Error sending edge message: \" << *edgeMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ add nodes at clock face number locations.\n double theta=(2*PI)\/12;\n for (unsigned int i=0; i<12; i++, theta+=(2*PI)\/12)\n {\n NodeIdentifier thisId=NodeIdentifier::from_string(\"192.168.2.\" + lexical_cast<string>(i+1));\n double faceRad=radius*1.15;\n GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); \n gpsMess->layer=layer;\n gpsMess->fromNodeID=thisId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ add nodes at clock face second locations.\n theta=(2*PI)\/60;\n for (unsigned int i=0; i<60; i++, theta+=(2*PI)\/60)\n {\n NodeIdentifier thisId=NodeIdentifier::from_string(\"192.168.3.\" + lexical_cast<string>(i+1));\n double faceRad=radius*1.35;\n GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); \n gpsMess->layer=layer;\n gpsMess->fromNodeID=thisId;\n if(!client.sendMessage(gpsMess))\n {\n LOG_ERROR(\"Error sending gps message: \" << *gpsMess);\n TRACE_EXIT_RET(EXIT_FAILURE);\n return EXIT_FAILURE;\n }\n }\n sleep(loopTime); \n }\n\n client.wait();\n\n TRACE_EXIT_RET(EXIT_SUCCESS);\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file SimpleActiveSocketState.cpp\n * \\date Apr 6, 2010\n * \\author samael\n *\/\n\n#include <cstdio>\n#include <cstring>\n#include <errno.h>\n#include <arpa\/inet.h>\n#include \"SimpleActiveSocketState.h\"\n#include \"ClosedSocketState.h\"\n#include \"ConnectedSocketState.h\"\n#include \"BoundSocketState.h\"\n#include \"TCPSocket.h\"\n#include \"UDPSocket.h\"\n#include \"SingletonAutoDestructor.h\"\n\nnamespace cml\n{\n\nSINGLETON_REGISTRATION(SimpleActiveSocketState);\nSINGLETON_REGISTRATION_END();\n\nbool SimpleActiveSocketState::activeOpen(AbstractSocket *sock,\n\t\tconst HostAddress &addr, uint16_t port)\n{\n\t\/\/ Clear and set address\/port.\n\tsockaddr_in inaddr;\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = addr.toInetAddr();\n\tinaddr.sin_port = htons(port);\n\n\t\/\/ Perform connection.\n\tPINF_3(\"Connecting to a remote host.\");\n\tif (connect(sock->sockfd(), (struct sockaddr *)&inaddr, sizeof(inaddr)) != 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::activeOpen()\");\n\t\treturn false;\n\t}\n\n\tsock->changeState(ConnectedSocketState::instance());\n\treturn true;\n}\n\nbool SimpleActiveSocketState::passiveOpen(AbstractSocket *sock,\n\t\tuint16_t port, int qlen)\n{\n\t\/\/ Clear and set inet address\/port.\n\tsockaddr_in inaddr;\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = INADDR_ANY;\n\tinaddr.sin_port = htons(port);\n\n\t\/\/ Perform binding.\n\tPINF_3(\"Binding a port.\");\n\tif (bind(sock->sockfd(), (struct sockaddr *)&inaddr, sizeof(inaddr)) != 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::passiveOpen()\");\n\t\treturn false;\n\t}\n\n\t\/\/ Perform listen if it's a TCP socket.\n\tif ((dynamic_cast<TCPSocket *>(sock))) {\n\t\tPINF_3(\"Listening for connections.\");\n\t\tif (listen(sock->sockfd(), qlen) < 0) {\n\t\t\tperror(\"Error: SimpleActiveSocketState::passiveOpen()\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tsock->changeState(BoundSocketState::instance());\n\treturn true;\n}\n\nbool SimpleActiveSocketState::close(AbstractSocket *sock)\n{\n\tPINF_3(\"Closing the socket.\");\n\tif (::close(sock->sockfd()) != 0) {\n\t\tperror(\"Error: ConnectedSocketState::close(): close\");\n\t\treturn false;\n\t}\n\n\tsock->changeState(ClosedSocketState::instance());\n\treturn true;\n}\n\nssize_t SimpleActiveSocketState::recvfrom(AbstractSocket *sock, char *buf,\n\t\tsize_t size, HostAddress *addr, uint16_t *port)\n{\n\tif (!(dynamic_cast<UDPSocket *>(sock))) {\n\t\tPERR(\"recvfrom is only suitable for UDP sockets.\");\n\t\treturn -1;\n\t}\n\n\tssize_t result;\n\tstruct sockaddr_in inaddr;\n\tsocklen_t alen = sizeof(inaddr);\n\n\tPINF_3(\"Receiving an incoming message.\");\n\tif ((result = ::recvfrom(sock->sockfd(), buf, size, 0,\n\t\t\t(struct sockaddr *)&inaddr, &alen)) < 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::recvfrom()\");\n\t}\n\tPINF_3(result << \" bytes received.\");\n\n\taddr->setAddr(inaddr.sin_addr.s_addr);\n\t*port = ntohs(inaddr.sin_port);\n\n\treturn result;\n}\n\nssize_t SimpleActiveSocketState::sendto(AbstractSocket *sock, const char *buf,\n\t\tsize_t size, const HostAddress &addr, uint16_t port)\n{\n\tif (!(dynamic_cast<UDPSocket *>(sock))) {\n\t\tPERR(\"sendto is only suitable for UDP sockets.\");\n\t\treturn -1;\n\t}\n\n\tssize_t result;\n\tsockaddr_in inaddr;\n\n\t\/\/ Clear and set address\/port.\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = addr.toInetAddr();\n\tinaddr.sin_port = htons(port);\n\n\tPINF_3(\"Sending an outgoing message.\");\n\tif ((result = ::sendto(sock->sockfd(), buf, size, 0,\n\t\t\t(struct sockaddr *)&inaddr,\tsizeof(inaddr))) < 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::sendto()\");\n\t}\n\tPINF_3(result << \" bytes sent.\");\n\n\treturn result;\n}\n\n\n\n}\n<commit_msg><commit_after>\/**\n * \\file SimpleActiveSocketState.cpp\n * \\date Apr 6, 2010\n * \\author samael\n *\/\n\n#include <cstdio>\n#include <cstring>\n#include <errno.h>\n#include <arpa\/inet.h>\n#include \"SimpleActiveSocketState.h\"\n#include \"ClosedSocketState.h\"\n#include \"ConnectedSocketState.h\"\n#include \"BoundSocketState.h\"\n#include \"TCPSocket.h\"\n#include \"UDPSocket.h\"\n#include \"SingletonAutoDestructor.h\"\n\nnamespace cml\n{\n\nSINGLETON_REGISTRATION(SimpleActiveSocketState);\nSINGLETON_REGISTRATION_END();\n\nbool SimpleActiveSocketState::activeOpen(AbstractSocket *sock,\n\t\tconst HostAddress &addr, uint16_t port)\n{\n\t\/\/ Clear and set address\/port.\n\tsockaddr_in inaddr;\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = addr.toInetAddr();\n\tinaddr.sin_port = htons(port);\n\n\t\/\/ Perform connection.\n\tPINF_3(\"Connecting to a remote host.\");\n\tif (connect(sock->sockfd(), (struct sockaddr *)&inaddr, sizeof(inaddr)) != 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::activeOpen()\");\n\t\treturn false;\n\t}\n\n\tsock->changeState(ConnectedSocketState::instance());\n\treturn true;\n}\n\nbool SimpleActiveSocketState::passiveOpen(AbstractSocket *sock,\n\t\tuint16_t port, int qlen)\n{\n\t\/\/ Clear and set inet address\/port.\n\tsockaddr_in inaddr;\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = INADDR_ANY;\n\tinaddr.sin_port = htons(port);\n\n\t\/\/ Reuse port.\n socklen_t reuseaddr_len;\n\tsetsockopt(sock->sockfd(), SOL_SOCKET, SO_REUSEADDR, &reuseaddr,\n\t\t\treuseaddr_len);\n\n\t\/\/ Perform binding.\n\tint reuseaddr = 1;\n\tPINF_3(\"Binding a port.\");\n\tif (bind(sock->sockfd(), (struct sockaddr *)&inaddr, sizeof(inaddr)) != 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::passiveOpen()\");\n\t\treturn false;\n\t}\n\n\t\/\/ Perform listen if it's a TCP socket.\n\tif ((dynamic_cast<TCPSocket *>(sock))) {\n\t\tPINF_3(\"Listening for connections.\");\n\t\tif (listen(sock->sockfd(), qlen) < 0) {\n\t\t\tperror(\"Error: SimpleActiveSocketState::passiveOpen()\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tsock->changeState(BoundSocketState::instance());\n\treturn true;\n}\n\nbool SimpleActiveSocketState::close(AbstractSocket *sock)\n{\n\tPINF_3(\"Closing the socket.\");\n\tif (::close(sock->sockfd()) != 0) {\n\t\tperror(\"Error: ConnectedSocketState::close(): close\");\n\t\treturn false;\n\t}\n\n\tsock->changeState(ClosedSocketState::instance());\n\treturn true;\n}\n\nssize_t SimpleActiveSocketState::recvfrom(AbstractSocket *sock, char *buf,\n\t\tsize_t size, HostAddress *addr, uint16_t *port)\n{\n\tif (!(dynamic_cast<UDPSocket *>(sock))) {\n\t\tPERR(\"recvfrom is only suitable for UDP sockets.\");\n\t\treturn -1;\n\t}\n\n\tssize_t result;\n\tstruct sockaddr_in inaddr;\n\tsocklen_t alen = sizeof(inaddr);\n\n\tPINF_3(\"Receiving an incoming message.\");\n\tif ((result = ::recvfrom(sock->sockfd(), buf, size, 0,\n\t\t\t(struct sockaddr *)&inaddr, &alen)) < 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::recvfrom()\");\n\t}\n\tPINF_3(result << \" bytes received.\");\n\n\taddr->setAddr(inaddr.sin_addr.s_addr);\n\t*port = ntohs(inaddr.sin_port);\n\n\treturn result;\n}\n\nssize_t SimpleActiveSocketState::sendto(AbstractSocket *sock, const char *buf,\n\t\tsize_t size, const HostAddress &addr, uint16_t port)\n{\n\tif (!(dynamic_cast<UDPSocket *>(sock))) {\n\t\tPERR(\"sendto is only suitable for UDP sockets.\");\n\t\treturn -1;\n\t}\n\n\tssize_t result;\n\tsockaddr_in inaddr;\n\n\t\/\/ Clear and set address\/port.\n\tmemset(&inaddr, 0, sizeof(inaddr));\n\tinaddr.sin_family = AF_INET;\n\tinaddr.sin_addr.s_addr = addr.toInetAddr();\n\tinaddr.sin_port = htons(port);\n\n\tPINF_3(\"Sending an outgoing message.\");\n\tif ((result = ::sendto(sock->sockfd(), buf, size, 0,\n\t\t\t(struct sockaddr *)&inaddr,\tsizeof(inaddr))) < 0) {\n\t\tperror(\"Error: SimpleActiveSocketState::sendto()\");\n\t}\n\tPINF_3(result << \" bytes sent.\");\n\n\treturn result;\n}\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"port\/port_posix.h\"\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include \"util\/logging.h\"\n\nnamespace leveldb {\nnamespace port {\n\nstatic void PthreadCall(const char* label, int result) {\n if (result != 0) {\n fprintf(stderr, \"pthread %s: %s\\n\", label, strerror(result));\n abort();\n }\n}\n\nMutex::Mutex(bool recursive) {\n if (recursive) {\n pthread_mutexattr_t attr;\n\n PthreadCall(\"init mutex attr\", pthread_mutexattr_init(&attr));\n PthreadCall(\"set mutex recursive\", pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));\n PthreadCall(\"init recursive mutex\", pthread_mutex_init(&mu_, &attr));\n PthreadCall(\"destroy mutex attr\", pthread_mutexattr_destroy(&attr));\n }\n else {\n PthreadCall(\"init mutex\", pthread_mutex_init(&mu_, NULL));\n }\n}\n\nMutex::~Mutex() { PthreadCall(\"destroy mutex\", pthread_mutex_destroy(&mu_)); }\n\nvoid Mutex::Lock() { PthreadCall(\"lock\", pthread_mutex_lock(&mu_)); }\n\nvoid Mutex::Unlock() { PthreadCall(\"unlock\", pthread_mutex_unlock(&mu_)); }\n\n#if defined(_POSIX_SPIN_LOCKS) && 0<_POSIX_SPIN_LOCKS\nSpin::Spin() { PthreadCall(\"init spinlock\", pthread_spin_init(&sp_, PTHREAD_PROCESS_PRIVATE)); }\n\nSpin::~Spin() { PthreadCall(\"destroy spinlock\", pthread_spin_destroy(&sp_)); }\n\nvoid Spin::Lock() { PthreadCall(\"lock spin\", pthread_spin_lock(&sp_)); }\n\nvoid Spin::Unlock() { PthreadCall(\"unlock spin\", pthread_spin_unlock(&sp_)); }\n#endif\n\nCondVar::CondVar(Mutex* mu)\n : mu_(mu) {\n PthreadCall(\"init cv\", pthread_cond_init(&cv_, NULL));\n}\n\nCondVar::~CondVar() { PthreadCall(\"destroy cv\", pthread_cond_destroy(&cv_)); }\n\nvoid CondVar::Wait() {\n PthreadCall(\"wait\", pthread_cond_wait(&cv_, &mu_->mu_));\n}\n\nbool CondVar::Wait(struct timespec* pTimespec) {\n bool signaled = true;\n int result = pthread_cond_timedwait(&cv_, &mu_->mu_, pTimespec);\n if (0 != result) {\n signaled = false;\n\n \/\/ the only expected errno is ETIMEDOUT; anything else is a real error\n if (ETIMEDOUT != result) {\n PthreadCall(\"timed wait\", result);\n }\n }\n return signaled;\n}\n\nvoid CondVar::Signal() {\n PthreadCall(\"signal\", pthread_cond_signal(&cv_));\n}\n\nvoid CondVar::SignalAll() {\n PthreadCall(\"broadcast\", pthread_cond_broadcast(&cv_));\n}\n\nvoid InitOnce(OnceType* once, void (*initializer)()) {\n PthreadCall(\"once\", pthread_once(once, initializer));\n}\n\nRWMutex::RWMutex() { PthreadCall(\"init mutex\", pthread_rwlock_init(&mu_, NULL)); }\n\nRWMutex::~RWMutex() { PthreadCall(\"destroy mutex\", pthread_rwlock_destroy(&mu_)); }\n\nvoid RWMutex::ReadLock() { PthreadCall(\"read lock\", pthread_rwlock_rdlock(&mu_)); }\n\nvoid RWMutex::WriteLock() { PthreadCall(\"write lock\", pthread_rwlock_wrlock(&mu_)); }\n\nvoid RWMutex::Unlock() { PthreadCall(\"unlock\", pthread_rwlock_unlock(&mu_)); }\n\n} \/\/ namespace port\n} \/\/ namespace leveldb\n<commit_msg>have pthread functions use default leveldb LOG(NULL ...) construct that push messages to syslog.<commit_after>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"port\/port_posix.h\"\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include \"leveldb\/env.h\"\n#include \"util\/logging.h\"\n\nnamespace leveldb {\nnamespace port {\n\nstatic void PthreadCall(const char* label, int result) {\n if (result != 0) {\n fprintf(stderr, \"pthread %s: %s\\n\", label, strerror(result));\n Log(NULL, \"pthread %s: %s\\n\", label, strerror(result));\n abort();\n }\n}\n\nMutex::Mutex(bool recursive) {\n if (recursive) {\n pthread_mutexattr_t attr;\n\n PthreadCall(\"init mutex attr\", pthread_mutexattr_init(&attr));\n PthreadCall(\"set mutex recursive\", pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE));\n PthreadCall(\"init recursive mutex\", pthread_mutex_init(&mu_, &attr));\n PthreadCall(\"destroy mutex attr\", pthread_mutexattr_destroy(&attr));\n }\n else {\n PthreadCall(\"init mutex\", pthread_mutex_init(&mu_, NULL));\n }\n}\n\nMutex::~Mutex() { PthreadCall(\"destroy mutex\", pthread_mutex_destroy(&mu_)); }\n\nvoid Mutex::Lock() { PthreadCall(\"lock\", pthread_mutex_lock(&mu_)); }\n\nvoid Mutex::Unlock() { PthreadCall(\"unlock\", pthread_mutex_unlock(&mu_)); }\n\n#if defined(_POSIX_SPIN_LOCKS) && 0<_POSIX_SPIN_LOCKS\nSpin::Spin() { PthreadCall(\"init spinlock\", pthread_spin_init(&sp_, PTHREAD_PROCESS_PRIVATE)); }\n\nSpin::~Spin() { PthreadCall(\"destroy spinlock\", pthread_spin_destroy(&sp_)); }\n\nvoid Spin::Lock() { PthreadCall(\"lock spin\", pthread_spin_lock(&sp_)); }\n\nvoid Spin::Unlock() { PthreadCall(\"unlock spin\", pthread_spin_unlock(&sp_)); }\n#endif\n\nCondVar::CondVar(Mutex* mu)\n : mu_(mu) {\n PthreadCall(\"init cv\", pthread_cond_init(&cv_, NULL));\n}\n\nCondVar::~CondVar() { PthreadCall(\"destroy cv\", pthread_cond_destroy(&cv_)); }\n\nvoid CondVar::Wait() {\n PthreadCall(\"wait\", pthread_cond_wait(&cv_, &mu_->mu_));\n}\n\nbool CondVar::Wait(struct timespec* pTimespec) {\n bool signaled = true;\n int result = pthread_cond_timedwait(&cv_, &mu_->mu_, pTimespec);\n if (0 != result) {\n signaled = false;\n\n \/\/ the only expected errno is ETIMEDOUT; anything else is a real error\n if (ETIMEDOUT != result) {\n PthreadCall(\"timed wait\", result);\n }\n }\n return signaled;\n}\n\nvoid CondVar::Signal() {\n PthreadCall(\"signal\", pthread_cond_signal(&cv_));\n}\n\nvoid CondVar::SignalAll() {\n PthreadCall(\"broadcast\", pthread_cond_broadcast(&cv_));\n}\n\nvoid InitOnce(OnceType* once, void (*initializer)()) {\n PthreadCall(\"once\", pthread_once(once, initializer));\n}\n\nRWMutex::RWMutex() { PthreadCall(\"init mutex\", pthread_rwlock_init(&mu_, NULL)); }\n\nRWMutex::~RWMutex() { PthreadCall(\"destroy mutex\", pthread_rwlock_destroy(&mu_)); }\n\nvoid RWMutex::ReadLock() { PthreadCall(\"read lock\", pthread_rwlock_rdlock(&mu_)); }\n\nvoid RWMutex::WriteLock() { PthreadCall(\"write lock\", pthread_rwlock_wrlock(&mu_)); }\n\nvoid RWMutex::Unlock() { PthreadCall(\"unlock\", pthread_rwlock_unlock(&mu_)); }\n\n} \/\/ namespace port\n} \/\/ namespace leveldb\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/ pow.hpp: pow functions for posits\n\/\/\n\/\/ Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n\nnamespace sw {\n\tnamespace unum {\n\n\t\t\/\/ the current shims are NON-COMPLIANT with the posit standard, which says that every function must be\n\t\t\/\/ correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.\n\n\t\ttemplate<size_t nbits, size_t es>\n\t\tposit<nbits,es> pow(posit<nbits,es> x, posit<nbits, es> y) {\n\t\t\treturn posit<nbits,es>(std::pow(double(x), double(y)));\n\t\t}\n\t\t\n\t\ttemplate<size_t nbits, size_t es>\n\t\tposit<nbits,es> pow(posit<nbits,es> x, int y) {\n\t\t\treturn posit<nbits,es>(std::pow(double(x), double(y)));\n\t\t}\n\n\n\t} \/\/ namespace unum\n\n} \/\/ namespace sw\n<commit_msg>WIP: additional mathematical function shims<commit_after>#pragma once\n\/\/ pow.hpp: pow functions for posits\n\/\/\n\/\/ Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n\nnamespace sw {\n\tnamespace unum {\n\n\t\t\/\/ the current shims are NON-COMPLIANT with the posit standard, which says that every function must be\n\t\t\/\/ correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.\n\n\t\ttemplate<size_t nbits, size_t es>\n\t\tposit<nbits,es> pow(posit<nbits,es> x, posit<nbits, es> y) {\n\t\t\treturn posit<nbits,es>(std::pow(double(x), double(y)));\n\t\t}\n\t\t\n\t\ttemplate<size_t nbits, size_t es>\n\t\tposit<nbits,es> pow(posit<nbits,es> x, int y) {\n\t\t\treturn posit<nbits,es>(std::pow(double(x), double(y)));\n\t\t}\n\t\t\n\t\ttemplate<size_t nbits, size_t es>\n\t\tposit<nbits,es> pow(posit<nbits,es> x, double y) {\n\t\t\treturn posit<nbits,es>(std::pow(double(x), y));\n\t\t}\n\n\t} \/\/ namespace unum\n\n} \/\/ namespace sw\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ prel\n\/\/\n\/\/ Created by George Oblapenko on 11\/11\/14.\n\/\/ Copyright (c) 2014 George Oblapenko. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <kineticlib.h>\n\nint main(int argc, const char * argv[]) {\n\tdouble start_T = 2000.; \/\/ the start temperature\n\tdouble end_T = 10000.0; \/\/ the end temperature\n\tdouble p = 100000.0; \/\/ atmospheric pressure\n\tdouble xN = 0.5; \/\/ the relative numeric density of atomic nitrogen\n\tdouble xN2 = 1. - xN;\n\t\n\tstd::string cs_model = \"VSS\"; \/\/ the dissociation cross-section model\n\tbool vl_dependent = false; \/\/ whether the dissociation cross-section is dependent on the vibrational level of the dissociating molecule\n\n\tint points_amt = 50; \/\/ the amount of points\n\tarma::vec T_array = arma::linspace<arma::vec>(start_T, end_T, points_amt); \/\/ start value of T, end value of T, amount of steps\n\tarma::vec prel = arma::zeros(50); \/\/ array of relaxation pressure values\n\n\tklib::MoleculeOneT N2 = klib::MoleculeOneT(\"N2\");\n\tklib::Atom N = klib::Atom(\"N\");\n\tarma::vec idata_N2N2 = klib::load_elastic_parameters(N2, N2); \/\/ N2 + N2 elastic interaction data\n\tarma::vec idata_N2N = klib::load_elastic_parameters(N2, N); \/\/ N2 + N elastic interaction data\n\tarma::vec ddata_N2N2 = klib::load_dissociation_parameters(N2, N2); \/\/ N2 + N2 dissociation data\n\tarma::vec ddata_N2N = klib::load_dissociation_parameters(N2, N); \/\/ N2 + N dissociation data\n\tarma::mat33 beta_matrix; \/\/ the matrix of beta integral brackets\n\tarma::vec3 right_parts; \/\/ the right-hand side of the system\n\tarma::vec3 results; \/\/ the values of the expansion coefficients g_{c,pq} - the order is g_{N2,10}, g_{N2,01}, g_{N,10}\n\t \n\tdouble R_react_N2, R_react_N; \/\/ relaxation terms\n\tdouble T, n, rho, omega11_N2N, tau_rot_N2N, tau_rot_N2N2, eta_zeta_N2N2, eta_zeta_N2N, cV, SJsl, PJsl, SJslN2, PJslN2; \/\/ the numeric density of the mixture, the density of the mixture, Omega^{(1,1)}_{N2,N}, rotational relaxation times for N2+N and N2+N2, the quantity 4T \\pi \/ (\\eta_{cd} * \\xi_{cd}), the quantity dE\/dT\n\tdouble tmp_int00 = 0.0;\n\tbeta_matrix.at(0, 0) = 1.5 * (1. - xN);\n\tbeta_matrix.at(0, 2) = 1.5 * xN; \/\/ these appear due to the constraint conditions and are independent of temperature\n\tbeta_matrix.zeros();\n\tright_parts[0] = 0.;\n\tfor (int i = 0; i < points_amt; i++) {\n\t\tT = T_array[i];\n\t\tn = p \/ (KLIB_CONST_K * T);\n\t\tN2.renorm(T, xN2 * n);\n\t\trho = xN2 * n * N2.mass + xN * n * N.mass;\n\t\tomega11_N2N = klib::omega(T, 1, 1, idata_N2N, \"ESA\", true, true); \/\/ we set nokt to true so that the result is of order 10e-07 instead of 10e-16\n\t\ttau_rot_N2N = klib::rot_rel_time_vss(T, idata_N2N, N2, n);\n\t\ttau_rot_N2N2 = klib::rot_rel_time_vss(T, idata_N2N2, N2, n);\n\t\teta_zeta_N2N2 = 1. \/ (n * KLIB_CONST_K * tau_rot_N2N2);\n\t\teta_zeta_N2N = 1. \/ (n * KLIB_CONST_K * tau_rot_N2N);\n\t\tcV = 1.5 * KLIB_CONST_K * n \/ rho + xN2 * (N2.mass * n \/ rho) * (N2.crot + N2.E_vibr_dT(T));\n\t\tbeta_matrix.at(0, 1) = xN2 * klib::wt_poly_norm(T, N2);\n\n\t\tbeta_matrix.at(1, 0) = -xN2 * N2.mass * N2.crot * (xN * (0.33333) * eta_zeta_N2N + xN2 * eta_zeta_N2N2); \/\/ does vibrational relaxation time play any significant role?\n\t\tbeta_matrix.at(1, 1) = xN2 * N2.mass * N2.crot * (xN * eta_zeta_N2N + xN2 * eta_zeta_N2N2);\n\t\tbeta_matrix.at(2, 0) = (2. \/ 9.) * xN2 * xN * (-16 * omega11_N2N + sqrt(1. \/ (KLIB_CONST_K * T)) * N2.mass * N2.crot * eta_zeta_N2N);\n\t\tbeta_matrix.at(2, 2) = (2. \/ 9.) * xN2 * xN * (16 * omega11_N2N + sqrt(1. \/ (KLIB_CONST_K * T)) * N2.mass * N2.crot * eta_zeta_N2N);\n\n\t\tbeta_matrix.at(1, 0) \/= sqrt(KLIB_CONST_K * T);\n\t\tbeta_matrix.at(1, 1) \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N2 = -klib::diss_rate_treanor_marrone(T, ddata_N2N, N2) * (xN * n) * (xN2 * n);\n\t\t\n\t\tR_react_N2 \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N = -2 * R_react_N2; \/\/ this is a binary mixture and the relaxation terms are related in a simple way\n\n\t\tSJsl = 0.0;\n\t\tPJsl = 0.0;\n\t\tSJslN2 = 0.0;\n\t\tPJslN2 = 0.0;\n\n\t\tfor (int vl = 0; vl <= N2.num_vibr; vl++) {\n\t\t\ttmp_int00 = klib::diss_integral(T, 0, idata_N2N, N2, vl, true, vl_dependent, cs_model, true);\n\t\t\tSJsl += (1. \/ 3.) * (12 * tmp_int00 - klib::diss_integral(T, 1, idata_N2N, N2, vl, true, true, cs_model, true)) * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t\tPJsl += (N2.avg_vibr_energy(T, false) - N2.vibr[vl] \/ (KLIB_CONST_K * T)) * 8 * tmp_int00 * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\n\t\t\ttmp_int00 = klib::diss_integral(T, 0, idata_N2N2, N2, vl, true, vl_dependent, cs_model, true);\n\t\t\tSJslN2 += (1. \/ 2.) * (12 * tmp_int00 - 8 * klib::diss_integral(T, 1, idata_N2N2, N2, vl, true, vl_dependent, cs_model, true)) * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t\tPJslN2 += (N2.avg_vibr_energy(T, false) - N2.vibr[vl] \/ (KLIB_CONST_K * T)) * 8 * tmp_int00 * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t}\n\n\t\tright_parts[1] = xN2 * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * klib::wt_poly_norm(T, N2) \/ (rho * T * cV) + PJsl * (xN * xN2) * n;\n\t\tright_parts[2] = xN * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * 1.5 \/ (rho * T * cV) - 2 * 1.5 * SJsl * (xN * xN2) * n;\n\t\tresults = arma::solve(beta_matrix, right_parts);\n\t\tstd::cout << \"\\nprel_{N2+N}=\" << -KLIB_CONST_K * T * (xN2 * results[0] + xN * results[2]) * klib::Gamma_diss(T, N2, N, N, xN2 * n, xN * n, xN * n);\n\n\t\tR_react_N2 = klib::diss_rate_treanor_marrone(T, ddata_N2N2, N2) * (xN2 * n) * (xN2 * n);\n\t\tR_react_N2 \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N = -2 * R_react_N2;\n\t\tright_parts[1] = xN2 * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * klib::wt_poly_norm(T, N2) \/ (rho * T * cV) + PJslN2 * (xN2 * xN2) * n;\n\t\tright_parts[2] = xN * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * 1.5 \/ (rho * T * cV) - 2 * 1.5 * SJslN2 * (xN2 * xN2) * n;\n\t\tresults = arma::solve(beta_matrix, right_parts);\n\t\tstd::cout << \"; prel_{N2+N2}=\" << -KLIB_CONST_K * T * (xN2 * results[0] + xN * results[2]) * klib::Gamma_diss(T, N2, N, N, xN2 * n, xN * n, xN * n);\n\t}\n}\n<commit_msg>fixed N2+N2 reaction<commit_after>\/\/\n\/\/ main.cpp\n\/\/ prel\n\/\/\n\/\/ Created by George Oblapenko on 11\/11\/14.\n\/\/ Copyright (c) 2014 George Oblapenko. All rights reserved.\n\/\/\n\n#include <iostream>\n#include <kineticlib.h>\n\nint main(int argc, const char * argv[]) {\n\tdouble start_T = 2000.; \/\/ the start temperature\n\tdouble end_T = 10000.0; \/\/ the end temperature\n\tdouble p = 100000.0; \/\/ atmospheric pressure\n\tdouble xN = 0.5; \/\/ the relative numeric density of atomic nitrogen\n\tdouble xN2 = 1. - xN;\n\t\n\tstd::string cs_model = \"VSS\"; \/\/ the dissociation cross-section model\n\tbool vl_dependent = false; \/\/ whether the dissociation cross-section is dependent on the vibrational level of the dissociating molecule\n\n\tint points_amt = 50; \/\/ the amount of points\n\tarma::vec T_array = arma::linspace<arma::vec>(start_T, end_T, points_amt); \/\/ start value of T, end value of T, amount of steps\n\tarma::vec prel = arma::zeros(50); \/\/ array of relaxation pressure values\n\n\tklib::MoleculeOneT N2 = klib::MoleculeOneT(\"N2\");\n\tklib::Atom N = klib::Atom(\"N\");\n\tarma::vec idata_N2N2 = klib::load_elastic_parameters(N2, N2); \/\/ N2 + N2 elastic interaction data\n\tarma::vec idata_N2N = klib::load_elastic_parameters(N2, N); \/\/ N2 + N elastic interaction data\n\tarma::vec ddata_N2N2 = klib::load_dissociation_parameters(N2, N2); \/\/ N2 + N2 dissociation data\n\tarma::vec ddata_N2N = klib::load_dissociation_parameters(N2, N); \/\/ N2 + N dissociation data\n\tarma::mat33 beta_matrix; \/\/ the matrix of beta integral brackets\n\tarma::vec3 right_parts; \/\/ the right-hand side of the system\n\tarma::vec3 results; \/\/ the values of the expansion coefficients g_{c,pq} - the order is g_{N2,10}, g_{N2,01}, g_{N,10}\n\t \n\tdouble R_react_N2, R_react_N; \/\/ relaxation terms\n\tdouble T, n, rho, omega11_N2N, tau_rot_N2N, tau_rot_N2N2, eta_zeta_N2N2, eta_zeta_N2N, cV, SJsl, PJsl, SJslN2, PJslN2; \/\/ the numeric density of the mixture, the density of the mixture, Omega^{(1,1)}_{N2,N}, rotational relaxation times for N2+N and N2+N2, the quantity 4T \\pi \/ (\\eta_{cd} * \\xi_{cd}), the quantity dE\/dT\n\tdouble tmp_int00 = 0.0;\n\tbeta_matrix.at(0, 0) = 1.5 * (1. - xN);\n\tbeta_matrix.at(0, 2) = 1.5 * xN; \/\/ these appear due to the constraint conditions and are independent of temperature\n\tbeta_matrix.zeros();\n\tright_parts[0] = 0.;\n\tfor (int i = 0; i < points_amt; i++) {\n\t\tT = T_array[i];\n\t\tn = p \/ (KLIB_CONST_K * T);\n\t\tN2.renorm(T, xN2 * n);\n\t\trho = xN2 * n * N2.mass + xN * n * N.mass;\n\t\tomega11_N2N = klib::omega(T, 1, 1, idata_N2N, \"ESA\", true, true); \/\/ we set nokt to true so that the result is of order 10e-07 instead of 10e-16\n\t\ttau_rot_N2N = klib::rot_rel_time_vss(T, idata_N2N, N2, n);\n\t\ttau_rot_N2N2 = klib::rot_rel_time_vss(T, idata_N2N2, N2, n);\n\t\teta_zeta_N2N2 = 1. \/ (n * KLIB_CONST_K * tau_rot_N2N2);\n\t\teta_zeta_N2N = 1. \/ (n * KLIB_CONST_K * tau_rot_N2N);\n\t\tcV = 1.5 * KLIB_CONST_K * n \/ rho + xN2 * (N2.mass * n \/ rho) * (N2.crot + N2.E_vibr_dT(T));\n\t\tbeta_matrix.at(0, 1) = xN2 * klib::wt_poly_norm(T, N2);\n\n\t\tbeta_matrix.at(1, 0) = -xN2 * N2.mass * N2.crot * (xN * (0.33333) * eta_zeta_N2N + xN2 * eta_zeta_N2N2); \/\/ does vibrational relaxation time play any significant role?\n\t\tbeta_matrix.at(1, 1) = xN2 * N2.mass * N2.crot * (xN * eta_zeta_N2N + xN2 * eta_zeta_N2N2);\n\t\tbeta_matrix.at(2, 0) = (2. \/ 9.) * xN2 * xN * (-16 * omega11_N2N + sqrt(1. \/ (KLIB_CONST_K * T)) * N2.mass * N2.crot * eta_zeta_N2N);\n\t\tbeta_matrix.at(2, 2) = (2. \/ 9.) * xN2 * xN * (16 * omega11_N2N + sqrt(1. \/ (KLIB_CONST_K * T)) * N2.mass * N2.crot * eta_zeta_N2N);\n\n\t\tbeta_matrix.at(1, 0) \/= sqrt(KLIB_CONST_K * T);\n\t\tbeta_matrix.at(1, 1) \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N2 = -klib::diss_rate_treanor_marrone(T, ddata_N2N, N2) * (xN * n) * (xN2 * n);\n\t\t\n\t\tR_react_N2 \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N = -2 * R_react_N2; \/\/ this is a binary mixture and the relaxation terms are related in a simple way\n\n\t\tSJsl = 0.0;\n\t\tPJsl = 0.0;\n\t\tSJslN2 = 0.0;\n\t\tPJslN2 = 0.0;\n\n\t\tfor (int vl = 0; vl <= N2.num_vibr; vl++) {\n\t\t\ttmp_int00 = klib::diss_integral(T, 0, idata_N2N, N2, vl, true, vl_dependent, cs_model, true);\n\t\t\tSJsl += (1. \/ 3.) * (12 * tmp_int00 - klib::diss_integral(T, 1, idata_N2N, N2, vl, true, true, cs_model, true)) * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t\tPJsl += (N2.avg_vibr_energy(T, false) - N2.vibr[vl] \/ (KLIB_CONST_K * T)) * 8 * tmp_int00 * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\n\t\t\ttmp_int00 = klib::diss_integral(T, 0, idata_N2N2, N2, vl, true, vl_dependent, cs_model, true);\n\t\t\tSJslN2 += (1. \/ 2.) * (12 * tmp_int00 - 8 * klib::diss_integral(T, 1, idata_N2N2, N2, vl, true, vl_dependent, cs_model, true)) * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t\tPJslN2 += (N2.avg_vibr_energy(T, false) - N2.vibr[vl] \/ (KLIB_CONST_K * T)) * 8 * tmp_int00 * N2.vibr_exp(T, vl) \/ N2.Z_vibr(T);\n\t\t}\n\n\t\tright_parts[1] = xN2 * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * klib::wt_poly_norm(T, N2) \/ (rho * T * cV) + PJsl * (xN * xN2) * n;\n\t\tright_parts[2] = xN * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * 1.5 \/ (rho * T * cV) - 2 * 1.5 * SJsl * (xN * xN2) * n;\n\t\tresults = arma::solve(beta_matrix, right_parts);\n\t\tstd::cout << \"\\nprel_{N2+N}=\" << -KLIB_CONST_K * T * (xN2 * results[0] + xN * results[2]) * klib::Gamma_diss(T, N2, N, N, xN2 * n, xN * n, xN * n);\n\n\t\tR_react_N2 = klib::diss_rate_treanor_marrone(T, ddata_N2N2, N2) * (xN2 * n) * (xN2 * n);\n\t\tR_react_N2 \/= sqrt(KLIB_CONST_K * T);\n\t\tR_react_N = -2 * R_react_N2;\n\t\tright_parts[1] = xN2 * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * klib::wt_poly_norm(T, N2) \/ (rho * T * cV) + PJslN2 * (xN2 * xN2) * n;\n\t\tright_parts[2] = xN * (R_react_N2 * (1.5 * KLIB_CONST_K * T + N2.avg_full_energy(T) + N2.form)\n\t\t\t+ R_react_N * (1.5 * KLIB_CONST_K * T + N.form)) * 1.5 \/ (rho * T * cV);\n\t\tresults = arma::solve(beta_matrix, right_parts);\n\t\tstd::cout << \"; prel_{N2+N2}=\" << -KLIB_CONST_K * T * (xN2 * results[0] + xN * results[2]) * klib::Gamma_diss(T, N2, N, N, xN2 * n, xN * n, xN * n);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef assembler_class_hpp\n#define assembler_class_hpp\n\n\n#include \"misc_includes.hpp\"\n\n\n#include \"symbol_table_class.hpp\"\n\n\nnamespace flare32\n{\n\nclass Assembler\n{\nprivate:\t\t\/\/ classes\n\nprivate:\t\t\/\/ variables\n\tSymbolTable __builtin_sym_tbl, __user_sym_tbl;\n\tInstructionTable __instr_tbl;\n\n\t\/\/ Where are we in the file?\n\tsize_t __addr = 0;\n\tsize_t __line_num = 1;\n\n\tint __next_char = ' ';\n\tPTok __next_tok = nullptr;\n\tstd::string __next_sym_str;\n\ts64 __next_num = -1;\n\n\t\/\/bool __changed = false;\n\ts32 __pass = 0;\n\n\tchar* __input_filename = nullptr;\n\tstd::FILE* __infile = nullptr;\n\npublic:\t\t\/\/ functions\n\tAssembler(char* s_input_filename);\n\n\tint operator () ();\n\n\n\nprivate:\t\t\/\/ functions\n\tgen_getter_by_ref(builtin_sym_tbl)\n\tgen_getter_by_ref(user_sym_tbl)\n\tgen_getter_by_ref(instr_tbl)\n\n\tgen_getter_and_setter_by_val(addr)\n\tgen_getter_and_setter_by_val(line_num)\n\tgen_getter_and_setter_by_val(next_char)\n\tgen_getter_and_setter_by_val(next_tok)\n\tgen_getter_and_setter_by_con_ref(next_sym_str)\n\tgen_getter_and_setter_by_val(next_num)\n\t\/\/gen_getter_and_setter_by_val(changed)\n\tgen_getter_and_setter_by_val(pass)\n\tgen_getter_and_setter_by_val(input_filename)\n\tgen_getter_and_setter_by_val(infile)\n\n\tvoid reinit();\n\tvoid fill_builtin_sym_tbl();\n\n\ttemplate<typename... ArgTypes>\n\tvoid err_suffix(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\", On line \", line_num(), \": \", args..., \"\\n\");\n\t\texit(1);\n\t}\n\ttemplate<typename... ArgTypes>\n\tvoid err(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\"Error\");\n\t\terr_suffix(args...);\n\t}\n\n\ttemplate<typename... ArgTypes>\n\tvoid expected(ArgTypes&&... args) const\n\t{\n\t\terr(\"Expected \", args...);\n\t}\n\n\n\tvoid __expected_tokens_innards() const\n\t{\n\t}\n\ttemplate<typename... RemArgTypes>\n\tvoid __expected_tokens_innards(PTok tok, RemArgTypes&&... rem_args)\n\t\tconst\n\t{\n\t\tprinterr(\"\\\"\", tok->str(), \"\\\"\");\n\n\t\tif (sizeof...(rem_args) > 0)\n\t\t{\n\t\t\tprinterr(\" or \");\n\t\t\t__expected_tokens_innards(rem_args...);\n\t\t}\n\t}\n\t\n\ttemplate<typename... ArgTypes>\n\tvoid expected_tokens(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\"Expected token of type \");\n\t\t__expected_tokens_innards(args...);\n\t\tprinterr(\"!\\n\");\n\t\texit(1);\n\t}\n\n\n\tvoid need(PTok tok);\n\n\tvoid advance();\n\tvoid lex();\n\n\tvoid line();\n\n\n\ts64 handle_term();\n\ts64 handle_factor();\n\ts64 handle_expr();\n\n\tbool tok_is_punct(PTok some_tok) const;\n\tbool tok_is_ident_ish(PTok some_tok) const;\n\n\tinline bool next_tok_is_punct() const\n\t{\n\t\treturn tok_is_punct(next_tok());\n\t}\n\tinline bool next_tok_is_ident_ish() const\n\t{\n\t\treturn tok_is_ident_ish(next_tok());\n\t}\n\n\n};\n\n}\n\n#endif\t\t\/\/ assembler_class_hpp\n<commit_msg>More stuffs<commit_after>#ifndef assembler_class_hpp\n#define assembler_class_hpp\n\n\n#include \"misc_includes.hpp\"\n\n\n#include \"symbol_table_class.hpp\"\n\n\nnamespace flare32\n{\n\nclass Assembler\n{\nprivate:\t\t\/\/ classes\n\tclass ParseNode\n\t{\n\tpublic:\t\t\/\/ variables\n\t\tPTok next_tok = nullptr;\n\t\tstd::string next_sym_str;\n\t\ts64 next_num = -1;\n\n\tpublic:\t\t\/\/ functions\n\t\tinline ParseNode()\n\t\t{\n\t\t}\n\n\n\t\tinline ParseNode(PTok s_next_tok, \n\t\t\tconst std::string& s_next_sym_str, s64 s_next_num)\n\t\t\t: next_tok(s_next_tok), next_sym_str(s_next_sym_str),\n\t\t\tnext_num(s_next_num)\n\t\t{\n\t\t}\n\n\t\tinline ParseNode(const ParseNode& to_copy) = default;\n\t\tinline ParseNode(ParseNode&& to_move) = default;\n\t\tinline ParseNode& operator = (const ParseNode& to_copy) = default;\n\t\tinline ParseNode& operator = (ParseNode&& to_move) = default;\n\t};\n\nprivate:\t\t\/\/ variables\n\tSymbolTable __builtin_sym_tbl, __user_sym_tbl;\n\tInstructionTable __instr_tbl;\n\n\t\/\/ Where are we in the file?\n\tsize_t __addr = 0;\n\tsize_t __line_num = 1;\n\n\tint __next_char = ' ';\n\tPTok __next_tok = nullptr;\n\tstd::string __next_sym_str;\n\ts64 __next_num = -1;\n\n\t\/\/bool __changed = false;\n\ts32 __pass = 0;\n\n\tchar* __input_filename = nullptr;\n\tstd::FILE* __infile = nullptr;\n\npublic:\t\t\/\/ functions\n\tAssembler(char* s_input_filename);\n\n\tint operator () ();\n\n\n\nprivate:\t\t\/\/ functions\n\tgen_getter_by_ref(builtin_sym_tbl)\n\tgen_getter_by_ref(user_sym_tbl)\n\tgen_getter_by_ref(instr_tbl)\n\n\tgen_getter_and_setter_by_val(addr)\n\tgen_getter_and_setter_by_val(line_num)\n\tgen_getter_and_setter_by_val(next_char)\n\tgen_getter_and_setter_by_val(next_tok)\n\tgen_getter_and_setter_by_con_ref(next_sym_str)\n\tgen_getter_and_setter_by_val(next_num)\n\t\/\/gen_getter_and_setter_by_val(changed)\n\tgen_getter_and_setter_by_val(pass)\n\tgen_getter_and_setter_by_val(input_filename)\n\tgen_getter_and_setter_by_val(infile)\n\n\tvoid reinit();\n\tvoid fill_builtin_sym_tbl();\n\n\ttemplate<typename... ArgTypes>\n\tvoid err_suffix(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\", On line \", line_num(), \": \", args..., \"\\n\");\n\t\texit(1);\n\t}\n\ttemplate<typename... ArgTypes>\n\tvoid err(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\"Error\");\n\t\terr_suffix(args...);\n\t}\n\n\ttemplate<typename... ArgTypes>\n\tvoid expected(ArgTypes&&... args) const\n\t{\n\t\terr(\"Expected \", args...);\n\t}\n\n\n\tvoid __expected_tokens_innards() const\n\t{\n\t}\n\ttemplate<typename... RemArgTypes>\n\tvoid __expected_tokens_innards(PTok tok, RemArgTypes&&... rem_args)\n\t\tconst\n\t{\n\t\tprinterr(\"\\\"\", tok->str(), \"\\\"\");\n\n\t\tif (sizeof...(rem_args) > 0)\n\t\t{\n\t\t\tprinterr(\" or \");\n\t\t\t__expected_tokens_innards(rem_args...);\n\t\t}\n\t}\n\t\n\ttemplate<typename... ArgTypes>\n\tvoid expected_tokens(ArgTypes&&... args) const\n\t{\n\t\tprinterr(\"Expected token of type \");\n\t\t__expected_tokens_innards(args...);\n\t\tprinterr(\"!\\n\");\n\t\texit(1);\n\t}\n\n\n\tvoid need(PTok tok);\n\n\tvoid advance();\n\tvoid lex();\n\n\tvoid line();\n\n\n\ts64 handle_term();\n\ts64 handle_factor();\n\ts64 handle_expr();\n\n\tbool tok_is_punct(PTok some_tok) const;\n\tbool tok_is_ident_ish(PTok some_tok) const;\n\n\tinline bool next_tok_is_punct() const\n\t{\n\t\treturn tok_is_punct(next_tok());\n\t}\n\tinline bool next_tok_is_ident_ish() const\n\t{\n\t\treturn tok_is_ident_ish(next_tok());\n\t}\n\n\n};\n\n}\n\n#endif\t\t\/\/ assembler_class_hpp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015-2016 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <iostream>\n\n#include \"node_dumper.h\"\n#include \"node.h\"\n\nnamespace ydsh {\nnamespace ast {\n\nvoid NodeDumper::dump(const char *fieldName, const char *value) {\n std::string str(value);\n this->dump(fieldName, str);\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::string &value) {\n this->writeName(fieldName);\n\n this->stream << '\"';\n for(char ch : value) {\n bool escape = true;\n switch(ch) {\n case '\\t':\n ch = 't';\n break;\n case '\\r':\n ch = 'r';\n break;\n case '\\n':\n ch = 'n';\n break;\n case '\"':\n ch = '\"';\n break;\n case '\\\\':\n ch = '\\\\';\n break;\n default:\n escape = false;\n break;\n }\n if(escape) {\n this->stream << '\\\\';\n }\n this->stream << ch;\n }\n this->stream << '\"' << std::endl;\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::vector<Node *> &nodes) {\n this->writeName(fieldName);\n this->stream << std::endl;\n\n this->enterIndent();\n for(Node *node : nodes) {\n this->indent();\n this->stream << \"- \";\n this->dumpNodeHeader(*node, true);\n this->enterIndent();\n node->dump(*this);\n this->leaveIndent();\n }\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::list<Node *> &nodes) {\n this->writeName(fieldName);\n this->stream << std::endl;\n\n this->enterIndent();\n for(Node *node : nodes) {\n this->indent();\n this->stream << \"- \";\n this->dumpNodeHeader(*node, true);\n this->enterIndent();\n node->dump(*this);\n this->leaveIndent();\n }\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const Node &node) {\n \/\/ write field name\n this->writeName(fieldName);\n\n \/\/ write node body\n this->stream << std::endl;\n this->enterIndent();\n this->dump(node);\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const DSType &type) {\n this->writeName(fieldName);\n this->stream << this->pool.getTypeName(type) << std::endl;\n}\n\nvoid NodeDumper::dumpNull(const char *fieldName) {\n this->writeName(fieldName);\n this->stream << std::endl;\n}\n\nvoid NodeDumper::dump(const Node &node) {\n this->indent();\n this->dumpNodeHeader(node);\n node.dump(*this);\n}\n\nvoid NodeDumper::enterIndent() {\n this->indentLevel++;\n}\n\nvoid NodeDumper::leaveIndent() {\n this->indentLevel--;\n}\n\nvoid NodeDumper::indent() {\n for(unsigned int i = 0; i < this->indentLevel; i++) {\n this->stream << \" \";\n }\n}\n\nvoid NodeDumper::dumpNodeHeader(const Node &node, bool inArray) {\n std::string className = misc::Demangle()(typeid(node));\n\n this->stream << \"__Node: \" << std::endl;\n this->enterIndent();\n if(inArray) {\n this->enterIndent();\n }\n\n this->indent(); this->stream << \"__typeid: \" << className << std::endl;\n this->indent(); this->stream << \"pos: \" << node.getStartPos() << std::endl;\n this->indent(); this->stream << \"size: \" << node.getSize() << std::endl;\n this->indent(); this->stream << \"type: \" <<\n (!node.isUntyped() ? this->pool.getTypeName(node.getType()) : \"\") << std::endl;\n\n this->leaveIndent();\n if(inArray) {\n this->leaveIndent();\n }\n}\n\nvoid NodeDumper::writeName(const char *fieldName) {\n this->indent(); this->stream << fieldName << \": \";\n}\n\nvoid NodeDumper::operator()(const RootNode &rootNode) {\n this->dump(rootNode);\n}\n\nvoid NodeDumper::dump(std::ostream &out, TypePool &pool, const RootNode &rootNode) {\n NodeDumper writer(out, pool);\n writer(rootNode);\n}\n\n} \/\/ namespace ast\n} \/\/ namespace ydsh<commit_msg>fix ast dump format<commit_after>\/*\n * Copyright (C) 2015-2016 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <iostream>\n\n#include \"node_dumper.h\"\n#include \"node.h\"\n\nnamespace ydsh {\nnamespace ast {\n\nvoid NodeDumper::dump(const char *fieldName, const char *value) {\n std::string str(value);\n this->dump(fieldName, str);\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::string &value) {\n this->writeName(fieldName);\n\n this->stream << '\"';\n for(char ch : value) {\n bool escape = true;\n switch(ch) {\n case '\\t':\n ch = 't';\n break;\n case '\\r':\n ch = 'r';\n break;\n case '\\n':\n ch = 'n';\n break;\n case '\"':\n ch = '\"';\n break;\n case '\\\\':\n ch = '\\\\';\n break;\n default:\n escape = false;\n break;\n }\n if(escape) {\n this->stream << '\\\\';\n }\n this->stream << ch;\n }\n this->stream << '\"' << std::endl;\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::vector<Node *> &nodes) {\n this->writeName(fieldName);\n this->stream << std::endl;\n\n this->enterIndent();\n for(Node *node : nodes) {\n this->indent();\n this->stream << \"- \";\n this->dumpNodeHeader(*node, true);\n this->enterIndent();\n node->dump(*this);\n this->leaveIndent();\n }\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const std::list<Node *> &nodes) {\n this->writeName(fieldName);\n this->stream << std::endl;\n\n this->enterIndent();\n for(Node *node : nodes) {\n this->indent();\n this->stream << \"- \";\n this->dumpNodeHeader(*node, true);\n this->enterIndent();\n node->dump(*this);\n this->leaveIndent();\n }\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const Node &node) {\n \/\/ write field name\n this->writeName(fieldName);\n\n \/\/ write node body\n this->stream << std::endl;\n this->enterIndent();\n this->dump(node);\n this->leaveIndent();\n}\n\nvoid NodeDumper::dump(const char *fieldName, const DSType &type) {\n this->writeName(fieldName);\n this->stream << this->pool.getTypeName(type) << std::endl;\n}\n\nvoid NodeDumper::dumpNull(const char *fieldName) {\n this->writeName(fieldName);\n this->stream << std::endl;\n}\n\nvoid NodeDumper::dump(const Node &node) {\n this->indent();\n this->dumpNodeHeader(node);\n node.dump(*this);\n}\n\nvoid NodeDumper::enterIndent() {\n this->indentLevel++;\n}\n\nvoid NodeDumper::leaveIndent() {\n this->indentLevel--;\n}\n\nvoid NodeDumper::indent() {\n for(unsigned int i = 0; i < this->indentLevel; i++) {\n this->stream << \" \";\n }\n}\n\nvoid NodeDumper::dumpNodeHeader(const Node &node, bool inArray) {\n std::string className = misc::Demangle()(typeid(node));\n\n this->stream << \"__Node: \" << std::endl;\n this->enterIndent();\n if(inArray) {\n this->enterIndent();\n }\n\n this->indent(); this->stream << \"__typeid: \" << strrchr(className.c_str(), ':') + 1 << std::endl;\n this->indent(); this->stream << \"pos: \" << node.getStartPos() << std::endl;\n this->indent(); this->stream << \"size: \" << node.getSize() << std::endl;\n this->indent(); this->stream << \"type: \" <<\n (!node.isUntyped() ? this->pool.getTypeName(node.getType()) : \"\") << std::endl;\n\n this->leaveIndent();\n if(inArray) {\n this->leaveIndent();\n }\n}\n\nvoid NodeDumper::writeName(const char *fieldName) {\n this->indent(); this->stream << fieldName << \": \";\n}\n\nvoid NodeDumper::operator()(const RootNode &rootNode) {\n this->dump(rootNode);\n}\n\nvoid NodeDumper::dump(std::ostream &out, TypePool &pool, const RootNode &rootNode) {\n NodeDumper writer(out, pool);\n writer(rootNode);\n}\n\n} \/\/ namespace ast\n} \/\/ namespace ydsh<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\r\n#include \"utility\/memory_cast.hpp\"\r\n\r\n#include \"sha3.h\"\r\n\r\n#include <assert.h>\r\n#include <array>\r\n#include <stdint.h>\r\n\r\ntemplate <size_t NBits>\r\nclass Sha3_Hasher {\r\npublic:\r\n\tSha3_Hasher() noexcept\r\n\t{\r\n\t\tif constexpr (NBits == 256)\r\n\t\t\tsha3_Init256(&_c);\r\n\t\telse if constexpr (NBits == 384)\r\n\t\t\tsha3_Init384(&_c);\r\n\t\telse if constexpr (NBits == 256)\r\n\t\t\tsha3_Init512(&_c);\r\n\t\telse\r\n\t\t\tstatic_assert(NBits == 256, \"The following SHA3 width is supported: 256, 384, 512 bits\");\r\n\t}\r\n\r\n\tvoid update(const void * const bufIn, const size_t len) noexcept\r\n\t{\r\n\t\tassert(!_finalized);\r\n\t\tif (len > 0) \/\/ it's unclear whether sha3_Update support 0 length. In fact, it seems to underflow it and enter an [almost] infinite loop.\r\n\t\t\tsha3_Update(&_c, bufIn, len);\r\n\t\telse\r\n\t\t\tassert(len > 0);\r\n\t}\r\n\r\n\tvoid update(const std::string& str) noexcept\r\n\t{\r\n\t\tthis->update(str.data(), str.size());\r\n\t}\r\n\r\n\ttemplate <typename T, typename = std::enable_if_t<is_trivially_serializable_v<std::remove_reference_t<T>>>>\r\n\tvoid update(T&& value) noexcept\r\n\t{\r\n\t\tstatic_assert(is_trivially_serializable_v<std::remove_reference_t<T>>);\r\n\t\tthis->update(std::addressof(value), sizeof(value));\r\n\t}\r\n\r\n\tstd::array<uint8_t, NBits \/ 8> getHash() noexcept\r\n\t{\r\n\t\tassert(!_finalized);\r\n\r\n\t\tconst void* const hashData = sha3_Finalize(&_c);\r\n\t\tstd::array<uint8_t, NBits \/ 8> hashDataArray;\r\n\t\t::memcpy(hashDataArray.data(), hashData, hashDataArray.size());\r\n\t\t_finalized = true;\r\n\t\treturn hashDataArray;\r\n\t}\r\n\r\n\tuint64_t get64BitHash() noexcept\r\n\t{\r\n\t\tconst auto fullHash = getHash();\r\n\r\n\t\tuint64_t hash64 = 0;\r\n\t\tfor (size_t offset = 0; offset < fullHash.size(); offset += sizeof(uint64_t))\r\n\t\t{\r\n\t\t\tconst auto eightBytes = memory_cast<uint64_t>(fullHash.data() + offset);\r\n\t\t\thash64 ^= eightBytes;\r\n\t\t}\r\n\r\n\t\treturn hash64;\r\n\t}\r\n\r\nprivate:\r\n\tsha3_context _c;\r\n\tbool _finalized = false;\r\n};\r\n\r\ninline uint64_t sha3_64bit(const void * const bufIn, const size_t len) noexcept\r\n{\r\n\tSha3_Hasher<256> hasher;\r\n\thasher.update(bufIn, len);\r\n\treturn hasher.get64BitHash();\r\n}\r\n<commit_msg>Sha3_Hasher<512> bug fixed<commit_after>#pragma once\r\n\r\n#include \"utility\/memory_cast.hpp\"\r\n\r\n#include \"sha3.h\"\r\n\r\n#include <assert.h>\r\n#include <array>\r\n#include <stdint.h>\r\n\r\ntemplate <size_t NBits>\r\nclass Sha3_Hasher {\r\npublic:\r\n\tSha3_Hasher() noexcept\r\n\t{\r\n\t\tif constexpr (NBits == 256)\r\n\t\t\tsha3_Init256(&_c);\r\n\t\telse if constexpr (NBits == 384)\r\n\t\t\tsha3_Init384(&_c);\r\n\t\telse if constexpr (NBits == 512)\r\n\t\t\tsha3_Init512(&_c);\r\n\t\telse\r\n\t\t\tstatic_assert(NBits == 256, \"The following SHA3 width is supported: 256, 384, 512 bits\");\r\n\t}\r\n\r\n\tvoid update(const void * const bufIn, const size_t len) noexcept\r\n\t{\r\n\t\tassert(!_finalized);\r\n\t\tif (len > 0) \/\/ it's unclear whether sha3_Update support 0 length. In fact, it seems to underflow it and enter an [almost] infinite loop.\r\n\t\t\tsha3_Update(&_c, bufIn, len);\r\n\t\telse\r\n\t\t\tassert(len > 0);\r\n\t}\r\n\r\n\tvoid update(const std::string& str) noexcept\r\n\t{\r\n\t\tthis->update(str.data(), str.size());\r\n\t}\r\n\r\n\ttemplate <typename T, typename = std::enable_if_t<is_trivially_serializable_v<std::remove_reference_t<T>>>>\r\n\tvoid update(T&& value) noexcept\r\n\t{\r\n\t\tstatic_assert(is_trivially_serializable_v<std::remove_reference_t<T>>);\r\n\t\tthis->update(std::addressof(value), sizeof(value));\r\n\t}\r\n\r\n\tstd::array<uint8_t, NBits \/ 8> getHash() noexcept\r\n\t{\r\n\t\tassert(!_finalized);\r\n\r\n\t\tconst void* const hashData = sha3_Finalize(&_c);\r\n\t\tstd::array<uint8_t, NBits \/ 8> hashDataArray;\r\n\t\t::memcpy(hashDataArray.data(), hashData, hashDataArray.size());\r\n\t\t_finalized = true;\r\n\t\treturn hashDataArray;\r\n\t}\r\n\r\n\tuint64_t get64BitHash() noexcept\r\n\t{\r\n\t\tconst auto fullHash = getHash();\r\n\r\n\t\tuint64_t hash64 = 0;\r\n\t\tfor (size_t offset = 0; offset < fullHash.size(); offset += sizeof(uint64_t))\r\n\t\t{\r\n\t\t\tconst auto eightBytes = memory_cast<uint64_t>(fullHash.data() + offset);\r\n\t\t\thash64 ^= eightBytes;\r\n\t\t}\r\n\r\n\t\treturn hash64;\r\n\t}\r\n\r\nprivate:\r\n\tsha3_context _c;\r\n\tbool _finalized = false;\r\n};\r\n\r\ninline uint64_t sha3_64bit(const void * const bufIn, const size_t len) noexcept\r\n{\r\n\tSha3_Hasher<256> hasher;\r\n\thasher.update(bufIn, len);\r\n\treturn hasher.get64BitHash();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"GeomHelper.h\"\n\n#include <math.h>\n#include <iostream>\n\nusing namespace std;\n\nnamespace avg {\n\nDLineSegment::DLineSegment(const DPoint& pt0, const DPoint& pt1)\n : p0(pt0),\n p1(pt1)\n{\n}\n\nbool DLineSegment::isPointOver(const DPoint& pt)\n{\n DPoint c = pt - p0; \/\/ DPoint from a to Point\n DPoint v = (p1 - p0);\n double d = v.getNorm(); \/\/ Length of the line segment\n v \/= d; \/\/ Unit DPoint from a to b\n double t = dotProduct(v, c); \/\/ Intersection point Distance from a\n\n return (t >= 0 && t <= d);\n}\n\n\/\/ Code adapted from Antonio, Franklin, \"Faster Line Segment Intersection,\"\n\/\/ Graphics Gems III (David Kirk, ed.), Academic Press, pp. 199-202, 1992.\nbool lineSegmentsIntersect(const DLineSegment& l0, const DLineSegment& l1)\n{\n double xdiff0 = l0.p1.x-l0.p0.x;\n double xdiff1 = l1.p0.x-l1.p1.x;\n \n double x1lo, x1hi;\n\n \/* X bound box test*\/\n if (xdiff0 < 0) {\n x1lo=l0.p1.x; \n x1hi=l0.p0.x;\n } else {\n x1hi=l0.p1.x; \n x1lo=l0.p0.x;\n }\n if (xdiff1>0) {\n if (x1hi < l1.p1.x || l1.p0.x < x1lo) {\n return false;\n }\n } else {\n if (x1hi < l1.p0.x || l1.p1.x < x1lo) {\n return false;\n }\n }\n\n double ydiff0 = l0.p1.y-l0.p0.y;\n double ydiff1 = l1.p0.y-l1.p1.y;\n\n double y1lo, y1hi;\n\n \/* Y bound box test*\/\n if (ydiff0<0) {\n y1lo=l0.p1.y; \n y1hi=l0.p0.y;\n } else {\n y1hi=l0.p1.y; \n y1lo=l0.p0.y;\n }\n if (ydiff1>0) {\n if (y1hi < l1.p1.y || l1.p0.y < y1lo) {\n return false;\n }\n } else {\n if (y1hi < l1.p0.y || l1.p1.y < y1lo) {\n return false;\n }\n }\n\n double Cx = l0.p0.x-l1.p0.x;\n double Cy = l0.p0.y-l1.p0.y;\n double d = ydiff1*Cx - xdiff1*Cy; \/* alpha numerator*\/\n double f = ydiff0*xdiff1 - xdiff0*ydiff1; \/* both denominator*\/\n if (f>0) { \/* alpha tests*\/\n if (d<0 || d>f) {\n return false;\n }\n } else {\n if (d>0 || d<f) {\n return false;\n }\n }\n\n double e = xdiff0*Cy - ydiff0*Cx; \/* beta numerator*\/\n if(f>0) { \/* beta tests*\/\n if (e<0 || e>f) {\n return false;\n }\n } else {\n if (e>0 || e<f) {\n return false;\n }\n }\n\n if (f==0) {\n \/\/ Theoretically, lines could still intersect in this case, but we don't care\n \/\/ because given numerical inaccuracies, the result is random anyway :-).\n return false;\n }\n \n\/\/ \/*compute intersection coordinates*\/\n\/\/ double num = d*xdiff0; \/* numerator *\/\n\/\/ offset = SAME_SIGNS(num,f) ? f\/2 : -f\/2; \/* round direction*\/\n\/\/ *x = x1 + (num+offset) \/ f; \/* intersection x *\/\n\/\/\n\/\/ num = d*ydiff0;\n\/\/ offset = SAME_SIGNS(num,f) ? f\/2 : -f\/2;\n\/\/ *y = y1 + (num+offset) \/ f; \/* intersection y *\/\n\n return true;\n}\n\n\/\/ Standard Jordan Curve Theorem (aka ray casting, even-odd-rule, crossing number)\n\/\/ point-in-polygon test.\n\/\/ Precomputing a bounding box for the polygon would speed this up a lot,\n\/\/ but we're not using the code in a speed-critical place so far.\nbool pointInPolygon(const DPoint& pt, const vector<DPoint>& poly)\n{\n if (poly.size() < 3) {\n return false;\n }\n DPoint pointOutside(0,0);\n vector<DPoint>::const_iterator it;\n for (it=poly.begin(); it != poly.end(); ++it) {\n if (pointOutside.x > it->x) {\n pointOutside = *it;\n }\n }\n pointOutside.x -= 1;\n\n DLineSegment line0(pointOutside, pt);\n const DPoint* pLastPt = &(*--poly.end());\n bool ptInPoly = false;\n for (it=poly.begin(); it != poly.end(); ++it) {\n DLineSegment line1(*pLastPt, *it);\n if (lineSegmentsIntersect(line0, line1)) {\n ptInPoly = !ptInPoly;\n }\n pLastPt = &(*it);\n }\n return ptInPoly;\n}\n \nDPoint getLineLineIntersection(const DPoint& p1, const DPoint& v1, const DPoint& p2, \n const DPoint& v2)\n{\n double denom = v2.y*v1.x-v2.x*v1.y;\n if (fabs(denom) < 0.0000001) {\n \/\/ If the lines are parallel or coincident, we just return p2!\n return p2;\n }\n double numer = v2.x*(p1.y-p2.y) - v2.y*(p1.x-p2.x);\n double ua = numer\/denom;\n\n return p1+ua*v1;\n\n}\n\n\n}\n<commit_msg>Replaced point in polygon algorithm to fix bug (when the intersection ray passes through a vertex of the polygon, the result was random).<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"GeomHelper.h\"\n\n#include <math.h>\n#include <iostream>\n\nusing namespace std;\n\nnamespace avg {\n\nDLineSegment::DLineSegment(const DPoint& pt0, const DPoint& pt1)\n : p0(pt0),\n p1(pt1)\n{\n}\n\nbool DLineSegment::isPointOver(const DPoint& pt)\n{\n DPoint c = pt - p0; \/\/ DPoint from a to Point\n DPoint v = (p1 - p0);\n double d = v.getNorm(); \/\/ Length of the line segment\n v \/= d; \/\/ Unit DPoint from a to b\n double t = dotProduct(v, c); \/\/ Intersection point Distance from a\n\n return (t >= 0 && t <= d);\n}\n\n\/\/ Code adapted from Antonio, Franklin, \"Faster Line Segment Intersection,\"\n\/\/ Graphics Gems III (David Kirk, ed.), Academic Press, pp. 199-202, 1992.\nbool lineSegmentsIntersect(const DLineSegment& l0, const DLineSegment& l1)\n{\n double xdiff0 = l0.p1.x-l0.p0.x;\n double xdiff1 = l1.p0.x-l1.p1.x;\n \n double x1lo, x1hi;\n\n \/* X bound box test*\/\n if (xdiff0 < 0) {\n x1lo=l0.p1.x; \n x1hi=l0.p0.x;\n } else {\n x1hi=l0.p1.x; \n x1lo=l0.p0.x;\n }\n if (xdiff1>0) {\n if (x1hi < l1.p1.x || l1.p0.x < x1lo) {\n return false;\n }\n } else {\n if (x1hi < l1.p0.x || l1.p1.x < x1lo) {\n return false;\n }\n }\n\n double ydiff0 = l0.p1.y-l0.p0.y;\n double ydiff1 = l1.p0.y-l1.p1.y;\n\n double y1lo, y1hi;\n\n \/* Y bound box test*\/\n if (ydiff0<0) {\n y1lo=l0.p1.y; \n y1hi=l0.p0.y;\n } else {\n y1hi=l0.p1.y; \n y1lo=l0.p0.y;\n }\n if (ydiff1>0) {\n if (y1hi < l1.p1.y || l1.p0.y < y1lo) {\n return false;\n }\n } else {\n if (y1hi < l1.p0.y || l1.p1.y < y1lo) {\n return false;\n }\n }\n\n double Cx = l0.p0.x-l1.p0.x;\n double Cy = l0.p0.y-l1.p0.y;\n double d = ydiff1*Cx - xdiff1*Cy; \/* alpha numerator*\/\n double f = ydiff0*xdiff1 - xdiff0*ydiff1; \/* both denominator*\/\n if (f>0) { \/* alpha tests*\/\n if (d<0 || d>f) {\n return false;\n }\n } else {\n if (d>0 || d<f) {\n return false;\n }\n }\n\n double e = xdiff0*Cy - ydiff0*Cx; \/* beta numerator*\/\n if(f>0) { \/* beta tests*\/\n if (e<0 || e>f) {\n return false;\n }\n } else {\n if (e>0 || e<f) {\n return false;\n }\n }\n\n if (f==0) {\n \/\/ Theoretically, lines could still intersect in this case, but we don't care\n \/\/ because given numerical inaccuracies, the result is random anyway :-).\n return false;\n }\n \n\/\/ \/*compute intersection coordinates*\/\n\/\/ double num = d*xdiff0; \/* numerator *\/\n\/\/ offset = SAME_SIGNS(num,f) ? f\/2 : -f\/2; \/* round direction*\/\n\/\/ *x = x1 + (num+offset) \/ f; \/* intersection x *\/\n\/\/\n\/\/ num = d*ydiff0;\n\/\/ offset = SAME_SIGNS(num,f) ? f\/2 : -f\/2;\n\/\/ *y = y1 + (num+offset) \/ f; \/* intersection y *\/\n\n return true;\n}\n\n\/\/ Original code from: http:\/\/www.ecse.rpi.edu\/Homepages\/wrf\/Research\/Short_Notes\/pnpoly.html.\n\/\/ Precomputing a bounding box for the polygon would speed this up a lot,\n\/\/ but it hasn't shown up on any profiles so far.\nbool pointInPolygon(const DPoint& pt, const vector<DPoint>& poly)\n{\n if (poly.size() < 3) {\n return false;\n }\n bool bPtInPoly = false;\n for (unsigned i = 0, j = poly.size()-1; i < poly.size(); j = i++) {\n if (((poly[i].y > pt.y) != (poly[j].y > pt.y)) &&\n (pt.x < (poly[j].x-poly[i].x)*(pt.y-poly[i].y) \/ (poly[j].y-poly[i].y)\n +poly[i].x))\n {\n bPtInPoly = !bPtInPoly;\n }\n }\n return bPtInPoly;\n}\n \nDPoint getLineLineIntersection(const DPoint& p1, const DPoint& v1, const DPoint& p2, \n const DPoint& v2)\n{\n double denom = v2.y*v1.x-v2.x*v1.y;\n if (fabs(denom) < 0.0000001) {\n \/\/ If the lines are parallel or coincident, we just return p2!\n return p2;\n }\n double numer = v2.x*(p1.y-p2.y) - v2.y*(p1.x-p2.x);\n double ua = numer\/denom;\n\n return p1+ua*v1;\n\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionProjects.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/projects\/SessionProjects.hpp>\n\n#include <core\/FilePath.hpp>\n#include <core\/Settings.hpp>\n#include <core\/Exec.hpp>\n#include <core\/FileSerializer.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/r_util\/RProjectFile.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n#include <session\/SessionUserSettings.hpp>\n\n#include <r\/session\/RSessionUtils.hpp>\n\n#include \"SessionProjectsInternal.hpp\"\n\nusing namespace core;\n\nnamespace session {\nnamespace projects {\n\nnamespace {\n\nProjectContext s_projectContext;\n\n\nvoid onSuspend(Settings*)\n{\n \/\/ on suspend write out current project path as the one to use\n \/\/ on resume. we read this back in initalize (rather than in\n \/\/ the onResume handler) becuase we need it very early in the\n \/\/ processes lifetime and onResume happens too late\n s_projectContext.setNextSessionProject(\n s_projectContext.file().absolutePath());\n}\n\nvoid onResume(const Settings&) {}\n\nError createProject(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ read params\n std::string projectFile;\n Error error = json::readParam(request.params, 0, &projectFile);\n if (error)\n return error;\n FilePath projectFilePath = module_context::resolveAliasedPath(projectFile);\n\n \/\/ ensure that the parent directory exists\n error = projectFilePath.parent().ensureDirectory();\n if (error)\n return error;\n\n \/\/ create the project file\n return r_util::writeProjectFile(projectFilePath,\n ProjectContext::defaultConfig());\n}\n\njson::Object projectConfigJson(const r_util::RProjectConfig& config)\n{\n json::Object configJson;\n configJson[\"version\"] = config.version;\n configJson[\"restore_workspace\"] = config.restoreWorkspace;\n configJson[\"save_workspace\"] = config.saveWorkspace;\n configJson[\"always_save_history\"] = config.alwaysSaveHistory;\n configJson[\"enable_code_indexing\"] = config.enableCodeIndexing;\n configJson[\"use_spaces_for_tab\"] = config.useSpacesForTab;\n configJson[\"num_spaces_for_tab\"] = config.numSpacesForTab;\n configJson[\"default_encoding\"] = config.encoding;\n configJson[\"default_sweave_engine\"] = config.defaultSweaveEngine;\n configJson[\"default_latex_program\"] = config.defaultLatexProgram;\n configJson[\"root_document\"] = config.rootDocument;\n configJson[\"build_type\"] = config.buildType;\n configJson[\"package_path\"] = config.packagePath;\n configJson[\"package_install_args\"] = config.packageInstallArgs;\n configJson[\"package_build_args\"] = config.packageBuildArgs;\n configJson[\"package_check_args\"] = config.packageCheckArgs;\n configJson[\"package_roxygenize\"] = config.packageRoxygenize;\n configJson[\"makefile_path\"] = config.makefilePath;\n configJson[\"custom_script_path\"] = config.customScriptPath;\n return configJson;\n}\n\njson::Object projectBuildOptionsJson()\n{\n RProjectBuildOptions buildOptions;\n Error error = s_projectContext.readBuildOptions(&buildOptions);\n if (error)\n LOG_ERROR(error);\n json::Object buildOptionsJson;\n buildOptionsJson[\"makefile_args\"] = buildOptions.makefileArgs;\n buildOptionsJson[\"cleanup_after_check\"] = buildOptions.cleanupAfterCheck;\n\n json::Object autoRoxJson;\n autoRoxJson[\"run_on_check\"] = buildOptions.autoRoxygenizeForCheck;\n autoRoxJson[\"run_on_package_builds\"] =\n buildOptions.autoRoxygenizeForBuildPackage;\n autoRoxJson[\"run_on_build_and_reload\"] =\n buildOptions.autoRoxygenizeForBuildAndReload;\n buildOptionsJson[\"auto_roxygenize_options\"] = autoRoxJson;\n return buildOptionsJson;\n}\n\njson::Object projectVcsOptionsJson()\n{\n RProjectVcsOptions vcsOptions;\n Error error = s_projectContext.readVcsOptions(&vcsOptions);\n if (error)\n LOG_ERROR(error);\n json::Object vcsOptionsJson;\n vcsOptionsJson[\"active_vcs_override\"] = vcsOptions.vcsOverride;\n return vcsOptionsJson;\n}\n\njson::Object projectVcsContextJson()\n{\n module_context::VcsContext vcsContext = module_context::vcsContext(\n s_projectContext.directory());\n\n json::Object contextJson;\n contextJson[\"detected_vcs\"] = vcsContext.detectedVcs;\n json::Array applicableJson;\n BOOST_FOREACH(const std::string& vcs, vcsContext.applicableVcs)\n {\n applicableJson.push_back(vcs);\n }\n contextJson[\"applicable_vcs\"] = applicableJson;\n\n contextJson[\"svn_repository_root\"] = vcsContext.svnRepositoryRoot;\n contextJson[\"git_remote_origin_url\"] = vcsContext.gitRemoteOriginUrl;\n\n return contextJson;\n}\n\njson::Object projectBuildContextJson()\n{\n json::Object contextJson;\n contextJson[\"roxygen2_installed\"] =\n module_context::isPackageInstalled(\"roxygen2\");\n contextJson[\"devtools_installed\"] =\n module_context::isPackageInstalled(\"devtools\");\n return contextJson;\n}\n\nError readProjectOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get project config json\n json::Object configJson = projectConfigJson(s_projectContext.config());\n\n \/\/ create project options json\n json::Object optionsJson;\n optionsJson[\"config\"] = configJson;\n optionsJson[\"vcs_options\"] = projectVcsOptionsJson();\n optionsJson[\"vcs_context\"] = projectVcsContextJson();\n optionsJson[\"build_options\"] = projectBuildOptionsJson();\n optionsJson[\"build_context\"] = projectBuildContextJson();\n\n pResponse->setResult(optionsJson);\n return Success();\n}\n\nvoid setProjectConfig(const r_util::RProjectConfig& config)\n{\n \/\/ set it\n s_projectContext.setConfig(config);\n\n \/\/ sync underlying R setting\n module_context::syncRSaveAction();\n}\n\nError rProjectBuildOptionsFromJson(const json::Object& optionsJson,\n RProjectBuildOptions* pOptions)\n{\n json::Object autoRoxJson;\n Error error = json::readObject(\n optionsJson,\n \"makefile_args\", &(pOptions->makefileArgs),\n \"cleanup_after_check\",&(pOptions->cleanupAfterCheck),\n \"auto_roxygenize_options\", &autoRoxJson);\n if (error)\n return error;\n\n return json::readObject(\n autoRoxJson,\n \"run_on_check\", &(pOptions->autoRoxygenizeForCheck),\n \"run_on_package_builds\", &(pOptions->autoRoxygenizeForBuildPackage),\n \"run_on_build_and_reload\", &(pOptions->autoRoxygenizeForBuildAndReload));\n}\n\nError rProjectVcsOptionsFromJson(const json::Object& optionsJson,\n RProjectVcsOptions* pOptions)\n{\n return json::readObject(\n optionsJson,\n \"active_vcs_override\", &(pOptions->vcsOverride));\n}\n\nError writeProjectOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the project config, vcs options, and build options\n json::Object configJson, vcsOptionsJson, buildOptionsJson;\n Error error = json::readObjectParam(request.params, 0,\n \"config\", &configJson,\n \"vcs_options\", &vcsOptionsJson,\n \"build_options\", &buildOptionsJson);\n if (error)\n return error;\n\n \/\/ read the config\n r_util::RProjectConfig config;\n error = json::readObject(\n configJson,\n \"version\", &(config.version),\n \"restore_workspace\", &(config.restoreWorkspace),\n \"save_workspace\", &(config.saveWorkspace),\n \"always_save_history\", &(config.alwaysSaveHistory),\n \"enable_code_indexing\", &(config.enableCodeIndexing),\n \"use_spaces_for_tab\", &(config.useSpacesForTab),\n \"num_spaces_for_tab\", &(config.numSpacesForTab),\n \"default_encoding\", &(config.encoding),\n \"default_sweave_engine\", &(config.defaultSweaveEngine),\n \"default_latex_program\", &(config.defaultLatexProgram),\n \"root_document\", &(config.rootDocument));\n if (error)\n return error;\n\n error = json::readObject(\n configJson,\n \"build_type\", &(config.buildType),\n \"package_path\", &(config.packagePath),\n \"package_install_args\", &(config.packageInstallArgs),\n \"package_build_args\", &(config.packageBuildArgs),\n \"package_check_args\", &(config.packageCheckArgs),\n \"package_roxygenize\", &(config.packageRoxygenize),\n \"makefile_path\", &(config.makefilePath),\n \"custom_script_path\", &(config.customScriptPath));\n if (error)\n return error;\n\n \/\/ read the vcs options\n RProjectVcsOptions vcsOptions;\n error = rProjectVcsOptionsFromJson(vcsOptionsJson, &vcsOptions);\n if (error)\n return error;\n\n \/\/ read the buld options\n RProjectBuildOptions buildOptions;\n error = rProjectBuildOptionsFromJson(buildOptionsJson, &buildOptions);\n if (error)\n return error;\n\n \/\/ write the config\n error = r_util::writeProjectFile(s_projectContext.file(), config);\n if (error)\n return error;\n\n \/\/ set the config\n setProjectConfig(config);\n\n \/\/ write the vcs options\n error = s_projectContext.writeVcsOptions(vcsOptions);\n if (error)\n LOG_ERROR(error);\n\n \/\/ write the build options\n error = s_projectContext.writeBuildOptions(buildOptions);\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n\nError writeProjectVcsOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ read the vcs options\n json::Object vcsOptionsJson;\n Error error = json::readParam(request.params, 0, &vcsOptionsJson);\n if (error)\n return error;\n RProjectVcsOptions vcsOptions;\n error = rProjectVcsOptionsFromJson(vcsOptionsJson, &vcsOptions);\n if (error)\n return error;\n\n \/\/ write the vcs options\n error = s_projectContext.writeVcsOptions(vcsOptions);\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n\n\nvoid onShutdown(bool terminatedNormally)\n{\n if (terminatedNormally)\n s_projectContext.setLastProjectPath(s_projectContext.file());\n}\n\nvoid syncProjectFileChanges()\n{\n \/\/ read project file config\n bool providedDefaults;\n std::string userErrMsg;\n r_util::RProjectConfig config;\n Error error = r_util::readProjectFile(s_projectContext.file(),\n ProjectContext::defaultConfig(),\n &config,\n &providedDefaults,\n &userErrMsg);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ set config\n setProjectConfig(config);\n\n \/\/ fire event to client\n json::Object dataJson;\n dataJson[\"type\"] = \"project\";\n dataJson[\"prefs\"] = s_projectContext.uiPrefs();\n ClientEvent event(client_events::kUiPrefsChanged, dataJson);\n module_context::enqueClientEvent(event);\n}\n\nvoid onFilesChanged(const std::vector<core::system::FileChangeEvent>& events)\n{\n BOOST_FOREACH(const core::system::FileChangeEvent& event, events)\n {\n \/\/ if the project file changed then sync its changes\n if (event.fileInfo().absolutePath() ==\n s_projectContext.file().absolutePath())\n {\n syncProjectFileChanges();\n break;\n }\n }\n}\n\nvoid onMonitoringDisabled()\n{\n \/\/ NOTE: if monitoring is disabled then we can't sync changes to the\n \/\/ project file -- we could poll for this however since it is only\n \/\/ a conveninece to have these synced we don't do this\n}\n\n\n} \/\/ anonymous namespace\n\n\nvoid startup()\n{\n \/\/ register suspend handler\n using namespace module_context;\n addSuspendHandler(SuspendHandler(onSuspend, onResume));\n\n \/\/ determine project file path\n FilePath projectFilePath;\n\n \/\/ see if there is a project path hard-wired for the next session\n \/\/ (this would be used for a switch to project or for the resuming of\n \/\/ a suspended session)\n std::string nextSessionProject = s_projectContext.nextSessionProject();\n FilePath lastProjectPath = s_projectContext.lastProjectPath();\n\n \/\/ check for next session project path (see above for comment)\n if (!nextSessionProject.empty())\n {\n \/\/ reset next session project path so its a one shot deal\n s_projectContext.setNextSessionProject(\"\");\n\n \/\/ clear any initial context settings which may be leftover\n \/\/ by a re-instatiation of rsession by desktop\n session::options().clearInitialContextSettings();\n\n \/\/ check for special \"none\" value (used for close project)\n if (nextSessionProject == \"none\")\n {\n projectFilePath = FilePath();\n }\n else\n {\n projectFilePath = module_context::resolveAliasedPath(\n nextSessionProject);\n }\n }\n\n \/\/ check for envrionment variable (file association)\n else if (!session::options().initialProjectPath().empty())\n {\n projectFilePath = session::options().initialProjectPath();\n }\n\n \/\/ check for other working dir override (implies a launch of a file\n \/\/ but not of a project). this code path is here to prevent\n \/\/ the next code path from executing\n else if (!session::options().initialWorkingDirOverride().empty())\n {\n projectFilePath = FilePath();\n }\n\n \/\/ check for restore last project\n else if (userSettings().alwaysRestoreLastProject() &&\n !lastProjectPath.empty())\n {\n\n \/\/ get last project path\n projectFilePath = lastProjectPath;\n\n \/\/ reset it to empty so that we only attempt to load the \"lastProject\"\n \/\/ a single time (this will be reset to the path below after we\n \/\/ clear the s_projectContext.initialize)\n s_projectContext.setLastProjectPath(FilePath());\n }\n\n \/\/ else no active project for this session\n else\n {\n projectFilePath = FilePath();\n }\n\n \/\/ if we have a project file path then try to initialize the\n \/\/ project context (show a warning to the user if we can't)\n if (!projectFilePath.empty())\n {\n std::string userErrMsg;\n Error error = s_projectContext.startup(projectFilePath, &userErrMsg);\n if (error)\n {\n \/\/ log the error\n error.addProperty(\"project-file\", projectFilePath.absolutePath());\n error.addProperty(\"user-msg\", userErrMsg);\n LOG_ERROR(error);\n\n \/\/ enque the error\n json::Object openProjError;\n openProjError[\"project\"] = module_context::createAliasedPath(\n projectFilePath);\n openProjError[\"message\"] = userErrMsg;\n ClientEvent event(client_events::kOpenProjectError, openProjError);\n module_context::enqueClientEvent(event);\n }\n }\n}\n\nError initialize()\n{\n \/\/ call project-context initialize\n Error error = s_projectContext.initialize();\n if (error)\n return error;\n\n \/\/ subscribe to file_monitor for project file changes\n projects::FileMonitorCallbacks cb;\n cb.onFilesChanged = onFilesChanged;\n cb.onMonitoringDisabled = onMonitoringDisabled;\n s_projectContext.subscribeToFileMonitor(\"\", cb);\n\n \/\/ subscribe to shutdown for setting lastProjectPath\n module_context::events().onShutdown.connect(onShutdown);\n\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"create_project\", createProject))\n (bind(registerRpcMethod, \"read_project_options\", readProjectOptions))\n (bind(registerRpcMethod, \"write_project_options\", writeProjectOptions))\n (bind(registerRpcMethod, \"write_project_vcs_options\", writeProjectVcsOptions))\n ;\n return initBlock.execute();\n}\n\nProjectContext& projectContext()\n{\n return s_projectContext;\n}\n\n} \/\/ namespace projects\n} \/\/ namesapce session\n\n<commit_msg>don't create project file if it already exists (e.g. when it was retreived from version control)<commit_after>\/*\n * SessionProjects.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/projects\/SessionProjects.hpp>\n\n#include <core\/FilePath.hpp>\n#include <core\/Settings.hpp>\n#include <core\/Exec.hpp>\n#include <core\/FileSerializer.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/r_util\/RProjectFile.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n#include <session\/SessionUserSettings.hpp>\n\n#include <r\/session\/RSessionUtils.hpp>\n\n#include \"SessionProjectsInternal.hpp\"\n\nusing namespace core;\n\nnamespace session {\nnamespace projects {\n\nnamespace {\n\nProjectContext s_projectContext;\n\n\nvoid onSuspend(Settings*)\n{\n \/\/ on suspend write out current project path as the one to use\n \/\/ on resume. we read this back in initalize (rather than in\n \/\/ the onResume handler) becuase we need it very early in the\n \/\/ processes lifetime and onResume happens too late\n s_projectContext.setNextSessionProject(\n s_projectContext.file().absolutePath());\n}\n\nvoid onResume(const Settings&) {}\n\nError createProject(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ read params\n std::string projectFile;\n Error error = json::readParam(request.params, 0, &projectFile);\n if (error)\n return error;\n FilePath projectFilePath = module_context::resolveAliasedPath(projectFile);\n\n \/\/ ensure that the parent directory exists\n error = projectFilePath.parent().ensureDirectory();\n if (error)\n return error;\n\n \/\/ create the project file\n if (!projectFilePath.exists())\n {\n return r_util::writeProjectFile(projectFilePath,\n ProjectContext::defaultConfig());\n }\n else\n {\n return Success();\n }\n}\n\njson::Object projectConfigJson(const r_util::RProjectConfig& config)\n{\n json::Object configJson;\n configJson[\"version\"] = config.version;\n configJson[\"restore_workspace\"] = config.restoreWorkspace;\n configJson[\"save_workspace\"] = config.saveWorkspace;\n configJson[\"always_save_history\"] = config.alwaysSaveHistory;\n configJson[\"enable_code_indexing\"] = config.enableCodeIndexing;\n configJson[\"use_spaces_for_tab\"] = config.useSpacesForTab;\n configJson[\"num_spaces_for_tab\"] = config.numSpacesForTab;\n configJson[\"default_encoding\"] = config.encoding;\n configJson[\"default_sweave_engine\"] = config.defaultSweaveEngine;\n configJson[\"default_latex_program\"] = config.defaultLatexProgram;\n configJson[\"root_document\"] = config.rootDocument;\n configJson[\"build_type\"] = config.buildType;\n configJson[\"package_path\"] = config.packagePath;\n configJson[\"package_install_args\"] = config.packageInstallArgs;\n configJson[\"package_build_args\"] = config.packageBuildArgs;\n configJson[\"package_check_args\"] = config.packageCheckArgs;\n configJson[\"package_roxygenize\"] = config.packageRoxygenize;\n configJson[\"makefile_path\"] = config.makefilePath;\n configJson[\"custom_script_path\"] = config.customScriptPath;\n return configJson;\n}\n\njson::Object projectBuildOptionsJson()\n{\n RProjectBuildOptions buildOptions;\n Error error = s_projectContext.readBuildOptions(&buildOptions);\n if (error)\n LOG_ERROR(error);\n json::Object buildOptionsJson;\n buildOptionsJson[\"makefile_args\"] = buildOptions.makefileArgs;\n buildOptionsJson[\"cleanup_after_check\"] = buildOptions.cleanupAfterCheck;\n\n json::Object autoRoxJson;\n autoRoxJson[\"run_on_check\"] = buildOptions.autoRoxygenizeForCheck;\n autoRoxJson[\"run_on_package_builds\"] =\n buildOptions.autoRoxygenizeForBuildPackage;\n autoRoxJson[\"run_on_build_and_reload\"] =\n buildOptions.autoRoxygenizeForBuildAndReload;\n buildOptionsJson[\"auto_roxygenize_options\"] = autoRoxJson;\n return buildOptionsJson;\n}\n\njson::Object projectVcsOptionsJson()\n{\n RProjectVcsOptions vcsOptions;\n Error error = s_projectContext.readVcsOptions(&vcsOptions);\n if (error)\n LOG_ERROR(error);\n json::Object vcsOptionsJson;\n vcsOptionsJson[\"active_vcs_override\"] = vcsOptions.vcsOverride;\n return vcsOptionsJson;\n}\n\njson::Object projectVcsContextJson()\n{\n module_context::VcsContext vcsContext = module_context::vcsContext(\n s_projectContext.directory());\n\n json::Object contextJson;\n contextJson[\"detected_vcs\"] = vcsContext.detectedVcs;\n json::Array applicableJson;\n BOOST_FOREACH(const std::string& vcs, vcsContext.applicableVcs)\n {\n applicableJson.push_back(vcs);\n }\n contextJson[\"applicable_vcs\"] = applicableJson;\n\n contextJson[\"svn_repository_root\"] = vcsContext.svnRepositoryRoot;\n contextJson[\"git_remote_origin_url\"] = vcsContext.gitRemoteOriginUrl;\n\n return contextJson;\n}\n\njson::Object projectBuildContextJson()\n{\n json::Object contextJson;\n contextJson[\"roxygen2_installed\"] =\n module_context::isPackageInstalled(\"roxygen2\");\n contextJson[\"devtools_installed\"] =\n module_context::isPackageInstalled(\"devtools\");\n return contextJson;\n}\n\nError readProjectOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get project config json\n json::Object configJson = projectConfigJson(s_projectContext.config());\n\n \/\/ create project options json\n json::Object optionsJson;\n optionsJson[\"config\"] = configJson;\n optionsJson[\"vcs_options\"] = projectVcsOptionsJson();\n optionsJson[\"vcs_context\"] = projectVcsContextJson();\n optionsJson[\"build_options\"] = projectBuildOptionsJson();\n optionsJson[\"build_context\"] = projectBuildContextJson();\n\n pResponse->setResult(optionsJson);\n return Success();\n}\n\nvoid setProjectConfig(const r_util::RProjectConfig& config)\n{\n \/\/ set it\n s_projectContext.setConfig(config);\n\n \/\/ sync underlying R setting\n module_context::syncRSaveAction();\n}\n\nError rProjectBuildOptionsFromJson(const json::Object& optionsJson,\n RProjectBuildOptions* pOptions)\n{\n json::Object autoRoxJson;\n Error error = json::readObject(\n optionsJson,\n \"makefile_args\", &(pOptions->makefileArgs),\n \"cleanup_after_check\",&(pOptions->cleanupAfterCheck),\n \"auto_roxygenize_options\", &autoRoxJson);\n if (error)\n return error;\n\n return json::readObject(\n autoRoxJson,\n \"run_on_check\", &(pOptions->autoRoxygenizeForCheck),\n \"run_on_package_builds\", &(pOptions->autoRoxygenizeForBuildPackage),\n \"run_on_build_and_reload\", &(pOptions->autoRoxygenizeForBuildAndReload));\n}\n\nError rProjectVcsOptionsFromJson(const json::Object& optionsJson,\n RProjectVcsOptions* pOptions)\n{\n return json::readObject(\n optionsJson,\n \"active_vcs_override\", &(pOptions->vcsOverride));\n}\n\nError writeProjectOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the project config, vcs options, and build options\n json::Object configJson, vcsOptionsJson, buildOptionsJson;\n Error error = json::readObjectParam(request.params, 0,\n \"config\", &configJson,\n \"vcs_options\", &vcsOptionsJson,\n \"build_options\", &buildOptionsJson);\n if (error)\n return error;\n\n \/\/ read the config\n r_util::RProjectConfig config;\n error = json::readObject(\n configJson,\n \"version\", &(config.version),\n \"restore_workspace\", &(config.restoreWorkspace),\n \"save_workspace\", &(config.saveWorkspace),\n \"always_save_history\", &(config.alwaysSaveHistory),\n \"enable_code_indexing\", &(config.enableCodeIndexing),\n \"use_spaces_for_tab\", &(config.useSpacesForTab),\n \"num_spaces_for_tab\", &(config.numSpacesForTab),\n \"default_encoding\", &(config.encoding),\n \"default_sweave_engine\", &(config.defaultSweaveEngine),\n \"default_latex_program\", &(config.defaultLatexProgram),\n \"root_document\", &(config.rootDocument));\n if (error)\n return error;\n\n error = json::readObject(\n configJson,\n \"build_type\", &(config.buildType),\n \"package_path\", &(config.packagePath),\n \"package_install_args\", &(config.packageInstallArgs),\n \"package_build_args\", &(config.packageBuildArgs),\n \"package_check_args\", &(config.packageCheckArgs),\n \"package_roxygenize\", &(config.packageRoxygenize),\n \"makefile_path\", &(config.makefilePath),\n \"custom_script_path\", &(config.customScriptPath));\n if (error)\n return error;\n\n \/\/ read the vcs options\n RProjectVcsOptions vcsOptions;\n error = rProjectVcsOptionsFromJson(vcsOptionsJson, &vcsOptions);\n if (error)\n return error;\n\n \/\/ read the buld options\n RProjectBuildOptions buildOptions;\n error = rProjectBuildOptionsFromJson(buildOptionsJson, &buildOptions);\n if (error)\n return error;\n\n \/\/ write the config\n error = r_util::writeProjectFile(s_projectContext.file(), config);\n if (error)\n return error;\n\n \/\/ set the config\n setProjectConfig(config);\n\n \/\/ write the vcs options\n error = s_projectContext.writeVcsOptions(vcsOptions);\n if (error)\n LOG_ERROR(error);\n\n \/\/ write the build options\n error = s_projectContext.writeBuildOptions(buildOptions);\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n\nError writeProjectVcsOptions(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ read the vcs options\n json::Object vcsOptionsJson;\n Error error = json::readParam(request.params, 0, &vcsOptionsJson);\n if (error)\n return error;\n RProjectVcsOptions vcsOptions;\n error = rProjectVcsOptionsFromJson(vcsOptionsJson, &vcsOptions);\n if (error)\n return error;\n\n \/\/ write the vcs options\n error = s_projectContext.writeVcsOptions(vcsOptions);\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n\n\nvoid onShutdown(bool terminatedNormally)\n{\n if (terminatedNormally)\n s_projectContext.setLastProjectPath(s_projectContext.file());\n}\n\nvoid syncProjectFileChanges()\n{\n \/\/ read project file config\n bool providedDefaults;\n std::string userErrMsg;\n r_util::RProjectConfig config;\n Error error = r_util::readProjectFile(s_projectContext.file(),\n ProjectContext::defaultConfig(),\n &config,\n &providedDefaults,\n &userErrMsg);\n if (error)\n {\n LOG_ERROR(error);\n return;\n }\n\n \/\/ set config\n setProjectConfig(config);\n\n \/\/ fire event to client\n json::Object dataJson;\n dataJson[\"type\"] = \"project\";\n dataJson[\"prefs\"] = s_projectContext.uiPrefs();\n ClientEvent event(client_events::kUiPrefsChanged, dataJson);\n module_context::enqueClientEvent(event);\n}\n\nvoid onFilesChanged(const std::vector<core::system::FileChangeEvent>& events)\n{\n BOOST_FOREACH(const core::system::FileChangeEvent& event, events)\n {\n \/\/ if the project file changed then sync its changes\n if (event.fileInfo().absolutePath() ==\n s_projectContext.file().absolutePath())\n {\n syncProjectFileChanges();\n break;\n }\n }\n}\n\nvoid onMonitoringDisabled()\n{\n \/\/ NOTE: if monitoring is disabled then we can't sync changes to the\n \/\/ project file -- we could poll for this however since it is only\n \/\/ a conveninece to have these synced we don't do this\n}\n\n\n} \/\/ anonymous namespace\n\n\nvoid startup()\n{\n \/\/ register suspend handler\n using namespace module_context;\n addSuspendHandler(SuspendHandler(onSuspend, onResume));\n\n \/\/ determine project file path\n FilePath projectFilePath;\n\n \/\/ see if there is a project path hard-wired for the next session\n \/\/ (this would be used for a switch to project or for the resuming of\n \/\/ a suspended session)\n std::string nextSessionProject = s_projectContext.nextSessionProject();\n FilePath lastProjectPath = s_projectContext.lastProjectPath();\n\n \/\/ check for next session project path (see above for comment)\n if (!nextSessionProject.empty())\n {\n \/\/ reset next session project path so its a one shot deal\n s_projectContext.setNextSessionProject(\"\");\n\n \/\/ clear any initial context settings which may be leftover\n \/\/ by a re-instatiation of rsession by desktop\n session::options().clearInitialContextSettings();\n\n \/\/ check for special \"none\" value (used for close project)\n if (nextSessionProject == \"none\")\n {\n projectFilePath = FilePath();\n }\n else\n {\n projectFilePath = module_context::resolveAliasedPath(\n nextSessionProject);\n }\n }\n\n \/\/ check for envrionment variable (file association)\n else if (!session::options().initialProjectPath().empty())\n {\n projectFilePath = session::options().initialProjectPath();\n }\n\n \/\/ check for other working dir override (implies a launch of a file\n \/\/ but not of a project). this code path is here to prevent\n \/\/ the next code path from executing\n else if (!session::options().initialWorkingDirOverride().empty())\n {\n projectFilePath = FilePath();\n }\n\n \/\/ check for restore last project\n else if (userSettings().alwaysRestoreLastProject() &&\n !lastProjectPath.empty())\n {\n\n \/\/ get last project path\n projectFilePath = lastProjectPath;\n\n \/\/ reset it to empty so that we only attempt to load the \"lastProject\"\n \/\/ a single time (this will be reset to the path below after we\n \/\/ clear the s_projectContext.initialize)\n s_projectContext.setLastProjectPath(FilePath());\n }\n\n \/\/ else no active project for this session\n else\n {\n projectFilePath = FilePath();\n }\n\n \/\/ if we have a project file path then try to initialize the\n \/\/ project context (show a warning to the user if we can't)\n if (!projectFilePath.empty())\n {\n std::string userErrMsg;\n Error error = s_projectContext.startup(projectFilePath, &userErrMsg);\n if (error)\n {\n \/\/ log the error\n error.addProperty(\"project-file\", projectFilePath.absolutePath());\n error.addProperty(\"user-msg\", userErrMsg);\n LOG_ERROR(error);\n\n \/\/ enque the error\n json::Object openProjError;\n openProjError[\"project\"] = module_context::createAliasedPath(\n projectFilePath);\n openProjError[\"message\"] = userErrMsg;\n ClientEvent event(client_events::kOpenProjectError, openProjError);\n module_context::enqueClientEvent(event);\n }\n }\n}\n\nError initialize()\n{\n \/\/ call project-context initialize\n Error error = s_projectContext.initialize();\n if (error)\n return error;\n\n \/\/ subscribe to file_monitor for project file changes\n projects::FileMonitorCallbacks cb;\n cb.onFilesChanged = onFilesChanged;\n cb.onMonitoringDisabled = onMonitoringDisabled;\n s_projectContext.subscribeToFileMonitor(\"\", cb);\n\n \/\/ subscribe to shutdown for setting lastProjectPath\n module_context::events().onShutdown.connect(onShutdown);\n\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"create_project\", createProject))\n (bind(registerRpcMethod, \"read_project_options\", readProjectOptions))\n (bind(registerRpcMethod, \"write_project_options\", writeProjectOptions))\n (bind(registerRpcMethod, \"write_project_vcs_options\", writeProjectVcsOptions))\n ;\n return initBlock.execute();\n}\n\nProjectContext& projectContext()\n{\n return s_projectContext;\n}\n\n} \/\/ namespace projects\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2018 The Regents of the University of Michigan\n\/\/ This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\n\n\/\/ Maintainer: joaander\n\n\/*! \\file CellListGPU.cc\n \\brief Defines CellListGPU\n*\/\n\n#include \"CellListGPU.h\"\n#include \"CellListGPU.cuh\"\n\nnamespace py = pybind11;\n\nusing namespace std;\n\n\/*! \\param sysdef system to compute the cell list of\n*\/\nCellListGPU::CellListGPU(std::shared_ptr<SystemDefinition> sysdef)\n : CellList(sysdef)\n {\n if (!m_exec_conf->isCUDAEnabled())\n {\n m_exec_conf->msg->error() << \"Creating a CellListGPU with no GPU in the execution configuration\" << endl;\n throw std::runtime_error(\"Error initializing CellListGPU\");\n }\n\n m_tuner.reset(new Autotuner(32, 1024, 32, 5, 100000, \"cell_list\", this->m_exec_conf));\n m_tuner_combine.reset(new Autotuner(32, 1024, 32, 5, 100000, \"cell_list_combine\", this->m_exec_conf));\n\n }\n\nvoid CellListGPU::computeCellList()\n {\n if (m_prof)\n m_prof->push(m_exec_conf, \"compute\");\n\n \/\/ acquire the particle data\n ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::read);\n ArrayHandle<Scalar> d_charge(m_pdata->getCharges(), access_location::device, access_mode::read);\n ArrayHandle<Scalar> d_diameter(m_pdata->getDiameters(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> d_body(m_pdata->getBodies(), access_location::device, access_mode::read);\n\n BoxDim box = m_pdata->getBox();\n\n \/\/ access the cell list data arrays\n ArrayHandle<unsigned int> d_cell_size(m_cell_size, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_xyzf(m_xyzf, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_tdb(m_tdb, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_cell_orientation(m_orientation, access_location::device, access_mode::overwrite);\n ArrayHandle<unsigned int> d_cell_idx(m_idx, access_location::device, access_mode::overwrite);\n\n \/\/ access the per-GPU cell list arrays (only needed with ngpu>1)\n ArrayHandle<unsigned int> d_cell_size_scratch(m_cell_size_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_xyzf_scratch(m_xyzf_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_tdb_scratch(m_tdb_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_cell_orientation_scratch(m_orientation_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<unsigned int> d_cell_idx_scratch(m_idx_scratch, access_location::device, access_mode::overwrite);\n\n \/\/ error conditions\n ArrayHandle<uint3> d_conditions(m_conditions, access_location::device, access_mode::overwrite);\n\n unsigned int ngpu = m_exec_conf->getNumActiveGPUs();\n\n \/\/ reset cell list contents\n cudaMemsetAsync(d_cell_size.data, 0, sizeof(unsigned int)*m_cell_indexer.getNumElements(),0);\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n if (ngpu > 1)\n {\n \/\/ reset temporary arrays\n cudaMemsetAsync(d_cell_size_scratch.data, 0, sizeof(unsigned int)*m_cell_size_scratch.getNumElements(),0);\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n m_exec_conf->beginMultiGPU();\n\n \/\/ autotune block sizes\n m_tuner->begin();\n\n \/\/ compute cell list, and write to temporary arrays with multi-GPU\n gpu_compute_cell_list(ngpu == 1 ? d_cell_size.data : d_cell_size_scratch.data,\n ngpu == 1 ? d_xyzf.data : d_xyzf_scratch.data,\n ngpu == 1 ? d_tdb.data : d_tdb_scratch.data,\n ngpu == 1 ? d_cell_orientation.data : d_cell_orientation_scratch.data,\n ngpu == 1 ? d_cell_idx.data : d_cell_idx_scratch.data,\n d_conditions.data,\n d_pos.data,\n d_orientation.data,\n d_charge.data,\n d_diameter.data,\n d_body.data,\n m_pdata->getN(),\n m_pdata->getNGhosts(),\n m_Nmax,\n m_flag_charge,\n m_flag_type,\n box,\n m_cell_indexer,\n m_cell_list_indexer,\n getGhostWidth(),\n m_tuner->getParam(),\n m_pdata->getGPUPartition());\n if(m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n m_tuner->end();\n\n m_exec_conf->endMultiGPU();\n\n if (ngpu > 1)\n {\n \/\/ have to wait for all GPUs to sync up, to have cell sizes available\n m_exec_conf->beginMultiGPU();\n\n \/\/ autotune block sizes\n m_tuner_combine->begin();\n\n gpu_combine_cell_lists(d_cell_size_scratch.data,\n d_cell_size.data,\n d_cell_idx_scratch.data,\n d_cell_idx.data,\n d_xyzf_scratch.data,\n d_xyzf.data,\n d_tdb_scratch.data,\n d_tdb.data,\n d_cell_orientation_scratch.data,\n d_cell_orientation.data,\n m_cell_list_indexer,\n ngpu,\n m_tuner_combine->getParam(),\n m_Nmax,\n d_conditions.data,\n m_pdata->getGPUPartition());\n m_tuner_combine->end();\n\n m_exec_conf->endMultiGPU();\n }\n\n if (m_sort_cell_list)\n {\n ScopedAllocation<uint2> d_sort_idx(m_exec_conf->getCachedAllocator(), m_cell_list_indexer.getNumElements());\n ScopedAllocation<unsigned int> d_sort_permutation(m_exec_conf->getCachedAllocator(), m_cell_list_indexer.getNumElements());\n ScopedAllocation<unsigned int> d_cell_idx_new(m_exec_conf->getCachedAllocator(), m_idx.getNumElements());\n ScopedAllocation<Scalar4> d_xyzf_new(m_exec_conf->getCachedAllocator(), m_xyzf.getNumElements());\n ScopedAllocation<Scalar4> d_cell_orientation_new(m_exec_conf->getCachedAllocator(), m_orientation.getNumElements());\n ScopedAllocation<Scalar4> d_tdb_new(m_exec_conf->getCachedAllocator(), m_tdb.getNumElements());\n\n gpu_sort_cell_list(d_cell_size.data,\n d_xyzf.data,\n d_xyzf_new.data,\n d_tdb.data,\n d_tdb_new.data,\n d_cell_orientation.data,\n d_cell_orientation_new.data,\n d_cell_idx.data,\n d_cell_idx_new.data,\n d_sort_idx.data,\n d_sort_permutation.data,\n m_cell_indexer,\n m_cell_list_indexer);\n\n if(m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n if (m_prof)\n m_prof->pop(m_exec_conf);\n }\n\nvoid CellListGPU::initializeMemory()\n {\n \/\/ call base class method\n CellList::initializeMemory();\n\n \/\/ only need to keep separate cell lists with more than one GPU\n unsigned int ngpu = m_exec_conf->getNumActiveGPUs();\n if (ngpu < 2)\n return;\n\n m_exec_conf->msg->notice(10) << \"CellListGPU initialize multiGPU memory\" << endl;\n if (m_prof)\n m_prof->push(\"init\");\n\n if (m_compute_adj_list && m_exec_conf->allConcurrentManagedAccess())\n {\n cudaMemAdvise(m_cell_adj.get(), m_cell_adj.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetReadMostly, 0);\n CHECK_CUDA_ERROR();\n }\n\n \/\/ allocate memory\n GlobalArray<unsigned int> cell_size_scratch(m_cell_indexer.getNumElements()*ngpu, m_exec_conf);\n m_cell_size_scratch.swap(cell_size_scratch);\n TAG_ALLOCATION(m_cell_size_scratch);\n\n if (m_compute_xyzf)\n {\n GlobalArray<Scalar4> xyzf_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_xyzf_scratch.swap(xyzf_scratch);\n TAG_ALLOCATION(m_xyzf_scratch);\n }\n else\n {\n GlobalArray<Scalar4> xyzf_scratch;\n m_xyzf_scratch.swap(xyzf_scratch);\n }\n\n if (m_compute_tdb)\n {\n GlobalArray<Scalar4> tdb_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_tdb_scratch.swap(tdb_scratch);\n TAG_ALLOCATION(m_tdb_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<Scalar4> tdb_scratch;\n m_tdb_scratch.swap(tdb_scratch);\n }\n\n if (m_compute_orientation)\n {\n GlobalArray<Scalar4> orientation_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_orientation_scratch.swap(orientation_scratch);\n TAG_ALLOCATION(m_orientation_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<Scalar4> orientation_scratch;\n m_orientation_scratch.swap(orientation_scratch);\n }\n\n if (m_compute_idx || m_sort_cell_list)\n {\n GlobalArray<unsigned int> idx_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_idx_scratch.swap(idx_scratch);\n TAG_ALLOCATION(m_idx_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<unsigned int> idx_scratch;\n m_idx_scratch.swap(idx_scratch);\n }\n\n if (! m_exec_conf->allConcurrentManagedAccess())\n return;\n\n \/\/ map cell list arrays into memory of all active GPUs\n auto& gpu_map = m_exec_conf->getGPUIds();\n\n for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)\n {\n cudaMemAdvise(m_cell_size.get(), m_cell_size.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n\n if (! m_idx.isNull())\n cudaMemAdvise(m_idx.get(), m_idx.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n\n if (! m_xyzf.isNull())\n cudaMemAdvise(m_xyzf.get(), m_xyzf.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n\n if (! m_tdb.isNull())\n cudaMemAdvise(m_tdb.get(), m_tdb.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n\n if (! m_orientation.isNull())\n cudaMemAdvise(m_orientation.get(), m_orientation.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n }\n\n for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)\n {\n cudaMemAdvise(m_cell_size_scratch.get()+idev*m_cell_indexer.getNumElements(),\n m_cell_indexer.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_idx_scratch.isNull())\n cudaMemAdvise(m_idx_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_xyzf_scratch.isNull())\n cudaMemAdvise(m_xyzf_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_tdb_scratch.isNull())\n cudaMemAdvise(m_tdb_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_orientation.isNull())\n cudaMemAdvise(m_orientation_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n \/\/ prefetch to preferred location\n cudaMemPrefetchAsync(m_cell_size_scratch.get()+idev*m_cell_indexer.getNumElements(),\n m_cell_indexer.getNumElements()*sizeof(unsigned int), gpu_map[idev]);\n\n if (! m_idx.isNull())\n cudaMemPrefetchAsync(m_idx_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(unsigned int), gpu_map[idev]);\n\n if (! m_xyzf_scratch.isNull())\n cudaMemPrefetchAsync(m_xyzf_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n\n if (! m_tdb_scratch.isNull())\n cudaMemPrefetchAsync(m_tdb_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n\n if (! m_orientation_scratch.isNull())\n cudaMemPrefetchAsync(m_orientation_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n }\n CHECK_CUDA_ERROR();\n\n if (m_prof)\n m_prof->pop();\n }\n\nvoid export_CellListGPU(py::module& m)\n {\n py::class_<CellListGPU, std::shared_ptr<CellListGPU> >(m,\"CellListGPU\",py::base<CellList>())\n .def(py::init< std::shared_ptr<SystemDefinition> >())\n ;\n }\n<commit_msg>remove some memory hints<commit_after>\/\/ Copyright (c) 2009-2018 The Regents of the University of Michigan\n\/\/ This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\n\n\/\/ Maintainer: joaander\n\n\/*! \\file CellListGPU.cc\n \\brief Defines CellListGPU\n*\/\n\n#include \"CellListGPU.h\"\n#include \"CellListGPU.cuh\"\n\nnamespace py = pybind11;\n\nusing namespace std;\n\n\/*! \\param sysdef system to compute the cell list of\n*\/\nCellListGPU::CellListGPU(std::shared_ptr<SystemDefinition> sysdef)\n : CellList(sysdef)\n {\n if (!m_exec_conf->isCUDAEnabled())\n {\n m_exec_conf->msg->error() << \"Creating a CellListGPU with no GPU in the execution configuration\" << endl;\n throw std::runtime_error(\"Error initializing CellListGPU\");\n }\n\n m_tuner.reset(new Autotuner(32, 1024, 32, 5, 100000, \"cell_list\", this->m_exec_conf));\n m_tuner_combine.reset(new Autotuner(32, 1024, 32, 5, 100000, \"cell_list_combine\", this->m_exec_conf));\n\n }\n\nvoid CellListGPU::computeCellList()\n {\n if (m_prof)\n m_prof->push(m_exec_conf, \"compute\");\n\n \/\/ acquire the particle data\n ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);\n ArrayHandle<Scalar4> d_orientation(m_pdata->getOrientationArray(), access_location::device, access_mode::read);\n ArrayHandle<Scalar> d_charge(m_pdata->getCharges(), access_location::device, access_mode::read);\n ArrayHandle<Scalar> d_diameter(m_pdata->getDiameters(), access_location::device, access_mode::read);\n ArrayHandle<unsigned int> d_body(m_pdata->getBodies(), access_location::device, access_mode::read);\n\n BoxDim box = m_pdata->getBox();\n\n \/\/ access the cell list data arrays\n ArrayHandle<unsigned int> d_cell_size(m_cell_size, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_xyzf(m_xyzf, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_tdb(m_tdb, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_cell_orientation(m_orientation, access_location::device, access_mode::overwrite);\n ArrayHandle<unsigned int> d_cell_idx(m_idx, access_location::device, access_mode::overwrite);\n\n \/\/ access the per-GPU cell list arrays (only needed with ngpu>1)\n ArrayHandle<unsigned int> d_cell_size_scratch(m_cell_size_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_xyzf_scratch(m_xyzf_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_tdb_scratch(m_tdb_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar4> d_cell_orientation_scratch(m_orientation_scratch, access_location::device, access_mode::overwrite);\n ArrayHandle<unsigned int> d_cell_idx_scratch(m_idx_scratch, access_location::device, access_mode::overwrite);\n\n \/\/ error conditions\n ArrayHandle<uint3> d_conditions(m_conditions, access_location::device, access_mode::overwrite);\n\n unsigned int ngpu = m_exec_conf->getNumActiveGPUs();\n\n \/\/ reset cell list contents\n cudaMemsetAsync(d_cell_size.data, 0, sizeof(unsigned int)*m_cell_indexer.getNumElements(),0);\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n if (ngpu > 1)\n {\n \/\/ reset temporary arrays\n cudaMemsetAsync(d_cell_size_scratch.data, 0, sizeof(unsigned int)*m_cell_size_scratch.getNumElements(),0);\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n m_exec_conf->beginMultiGPU();\n\n \/\/ autotune block sizes\n m_tuner->begin();\n\n \/\/ compute cell list, and write to temporary arrays with multi-GPU\n gpu_compute_cell_list(ngpu == 1 ? d_cell_size.data : d_cell_size_scratch.data,\n ngpu == 1 ? d_xyzf.data : d_xyzf_scratch.data,\n ngpu == 1 ? d_tdb.data : d_tdb_scratch.data,\n ngpu == 1 ? d_cell_orientation.data : d_cell_orientation_scratch.data,\n ngpu == 1 ? d_cell_idx.data : d_cell_idx_scratch.data,\n d_conditions.data,\n d_pos.data,\n d_orientation.data,\n d_charge.data,\n d_diameter.data,\n d_body.data,\n m_pdata->getN(),\n m_pdata->getNGhosts(),\n m_Nmax,\n m_flag_charge,\n m_flag_type,\n box,\n m_cell_indexer,\n m_cell_list_indexer,\n getGhostWidth(),\n m_tuner->getParam(),\n m_pdata->getGPUPartition());\n if(m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n m_tuner->end();\n\n m_exec_conf->endMultiGPU();\n\n if (ngpu > 1)\n {\n \/\/ have to wait for all GPUs to sync up, to have cell sizes available\n m_exec_conf->beginMultiGPU();\n\n \/\/ autotune block sizes\n m_tuner_combine->begin();\n\n gpu_combine_cell_lists(d_cell_size_scratch.data,\n d_cell_size.data,\n d_cell_idx_scratch.data,\n d_cell_idx.data,\n d_xyzf_scratch.data,\n d_xyzf.data,\n d_tdb_scratch.data,\n d_tdb.data,\n d_cell_orientation_scratch.data,\n d_cell_orientation.data,\n m_cell_list_indexer,\n ngpu,\n m_tuner_combine->getParam(),\n m_Nmax,\n d_conditions.data,\n m_pdata->getGPUPartition());\n m_tuner_combine->end();\n\n m_exec_conf->endMultiGPU();\n }\n\n if (m_sort_cell_list)\n {\n ScopedAllocation<uint2> d_sort_idx(m_exec_conf->getCachedAllocator(), m_cell_list_indexer.getNumElements());\n ScopedAllocation<unsigned int> d_sort_permutation(m_exec_conf->getCachedAllocator(), m_cell_list_indexer.getNumElements());\n ScopedAllocation<unsigned int> d_cell_idx_new(m_exec_conf->getCachedAllocator(), m_idx.getNumElements());\n ScopedAllocation<Scalar4> d_xyzf_new(m_exec_conf->getCachedAllocator(), m_xyzf.getNumElements());\n ScopedAllocation<Scalar4> d_cell_orientation_new(m_exec_conf->getCachedAllocator(), m_orientation.getNumElements());\n ScopedAllocation<Scalar4> d_tdb_new(m_exec_conf->getCachedAllocator(), m_tdb.getNumElements());\n\n gpu_sort_cell_list(d_cell_size.data,\n d_xyzf.data,\n d_xyzf_new.data,\n d_tdb.data,\n d_tdb_new.data,\n d_cell_orientation.data,\n d_cell_orientation_new.data,\n d_cell_idx.data,\n d_cell_idx_new.data,\n d_sort_idx.data,\n d_sort_permutation.data,\n m_cell_indexer,\n m_cell_list_indexer);\n\n if(m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n if (m_prof)\n m_prof->pop(m_exec_conf);\n }\n\nvoid CellListGPU::initializeMemory()\n {\n \/\/ call base class method\n CellList::initializeMemory();\n\n \/\/ only need to keep separate cell lists with more than one GPU\n unsigned int ngpu = m_exec_conf->getNumActiveGPUs();\n if (ngpu < 2)\n return;\n\n m_exec_conf->msg->notice(10) << \"CellListGPU initialize multiGPU memory\" << endl;\n if (m_prof)\n m_prof->push(\"init\");\n\n if (m_compute_adj_list && m_exec_conf->allConcurrentManagedAccess())\n {\n cudaMemAdvise(m_cell_adj.get(), m_cell_adj.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetReadMostly, 0);\n CHECK_CUDA_ERROR();\n }\n\n \/\/ allocate memory\n GlobalArray<unsigned int> cell_size_scratch(m_cell_indexer.getNumElements()*ngpu, m_exec_conf);\n m_cell_size_scratch.swap(cell_size_scratch);\n TAG_ALLOCATION(m_cell_size_scratch);\n\n if (m_compute_xyzf)\n {\n GlobalArray<Scalar4> xyzf_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_xyzf_scratch.swap(xyzf_scratch);\n TAG_ALLOCATION(m_xyzf_scratch);\n }\n else\n {\n GlobalArray<Scalar4> xyzf_scratch;\n m_xyzf_scratch.swap(xyzf_scratch);\n }\n\n if (m_compute_tdb)\n {\n GlobalArray<Scalar4> tdb_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_tdb_scratch.swap(tdb_scratch);\n TAG_ALLOCATION(m_tdb_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<Scalar4> tdb_scratch;\n m_tdb_scratch.swap(tdb_scratch);\n }\n\n if (m_compute_orientation)\n {\n GlobalArray<Scalar4> orientation_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_orientation_scratch.swap(orientation_scratch);\n TAG_ALLOCATION(m_orientation_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<Scalar4> orientation_scratch;\n m_orientation_scratch.swap(orientation_scratch);\n }\n\n if (m_compute_idx || m_sort_cell_list)\n {\n GlobalArray<unsigned int> idx_scratch(m_cell_list_indexer.getNumElements()*ngpu, m_exec_conf);\n m_idx_scratch.swap(idx_scratch);\n TAG_ALLOCATION(m_idx_scratch);\n }\n else\n {\n \/\/ array is no longer needed, discard it\n GlobalArray<unsigned int> idx_scratch;\n m_idx_scratch.swap(idx_scratch);\n }\n\n if (! m_exec_conf->allConcurrentManagedAccess())\n return;\n\n \/\/ map cell list arrays into memory of all active GPUs\n auto& gpu_map = m_exec_conf->getGPUIds();\n\n for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)\n {\n cudaMemAdvise(m_cell_size.get(), m_cell_size.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetAccessedBy, gpu_map[idev]);\n }\n\n for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)\n {\n cudaMemAdvise(m_cell_size_scratch.get()+idev*m_cell_indexer.getNumElements(),\n m_cell_indexer.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_idx_scratch.isNull())\n cudaMemAdvise(m_idx_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(unsigned int), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_xyzf_scratch.isNull())\n cudaMemAdvise(m_xyzf_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_tdb_scratch.isNull())\n cudaMemAdvise(m_tdb_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n if (! m_orientation.isNull())\n cudaMemAdvise(m_orientation_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), cudaMemAdviseSetPreferredLocation, gpu_map[idev]);\n\n \/\/ prefetch to preferred location\n cudaMemPrefetchAsync(m_cell_size_scratch.get()+idev*m_cell_indexer.getNumElements(),\n m_cell_indexer.getNumElements()*sizeof(unsigned int), gpu_map[idev]);\n\n if (! m_idx.isNull())\n cudaMemPrefetchAsync(m_idx_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(unsigned int), gpu_map[idev]);\n\n if (! m_xyzf_scratch.isNull())\n cudaMemPrefetchAsync(m_xyzf_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n\n if (! m_tdb_scratch.isNull())\n cudaMemPrefetchAsync(m_tdb_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n\n if (! m_orientation_scratch.isNull())\n cudaMemPrefetchAsync(m_orientation_scratch.get()+idev*m_cell_list_indexer.getNumElements(),\n m_cell_list_indexer.getNumElements()*sizeof(Scalar4), gpu_map[idev]);\n }\n CHECK_CUDA_ERROR();\n\n if (m_prof)\n m_prof->pop();\n }\n\nvoid export_CellListGPU(py::module& m)\n {\n py::class_<CellListGPU, std::shared_ptr<CellListGPU> >(m,\"CellListGPU\",py::base<CellList>())\n .def(py::init< std::shared_ptr<SystemDefinition> >())\n ;\n }\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file lis2mdl.cpp\n *\n * Driver for the LIS2MDL magnetometer connected via I2C or SPI.\n *\n * Based on the LIS2MDL driver.\n *\/\n\n#include <px4_platform_common\/time.h>\n#include \"lis2mdl.h\"\n\nLIS2MDL::LIS2MDL(device::Device *interface, enum Rotation rotation, I2CSPIBusOption bus_option, int bus) :\n\tI2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(interface->get_device_id()), bus_option, bus),\n\t_px4_mag(interface->get_device_id(), interface->external() ? ORB_PRIO_VERY_HIGH : ORB_PRIO_DEFAULT, rotation),\n\t_interface(interface),\n\t_comms_errors(perf_alloc(PC_COUNT, MODULE_NAME\": comms_errors\")),\n\t_conf_errors(perf_alloc(PC_COUNT, MODULE_NAME\": conf_errors\")),\n\t_range_errors(perf_alloc(PC_COUNT, MODULE_NAME\": range_errors\")),\n\t_sample_perf(perf_alloc(PC_ELAPSED, MODULE_NAME\": read\")),\n\t_measure_interval(0)\n{\n\t_px4_mag.set_external(_interface->external());\n\t_px4_mag.set_scale(0.0015f); \/* 49.152f \/ (2^15) *\/\n}\n\nLIS2MDL::~LIS2MDL()\n{\n\t\/\/ free perf counters\n\tperf_free(_sample_perf);\n\tperf_free(_comms_errors);\n\tperf_free(_range_errors);\n\tperf_free(_conf_errors);\n\n\tdelete _interface;\n}\n\nint\nLIS2MDL::measure()\n{\n\tstruct {\n\t\tuint8_t status;\n\t\tuint8_t x[2];\n\t\tuint8_t y[2];\n\t\tuint8_t z[2];\n\t} lis_report;\n\n\tstruct {\n\t\tint16_t x;\n\t\tint16_t y;\n\t\tint16_t z;\n\t\tint16_t t;\n\t} report;\n\n\tuint8_t buf_rx[2] = {};\n\n\t_px4_mag.set_error_count(perf_event_count(_comms_errors));\n\n\tperf_begin(_sample_perf);\n\n\tconst hrt_abstime timestamp_sample = hrt_absolute_time();\n\tint ret = _interface->read(ADDR_STATUS_REG, (uint8_t *)&lis_report, sizeof(lis_report));\n\n\t\/**\n\t * Silicon Bug: the X axis will be read instead of the temperature registers if you do a sequential read through XYZ.\n\t * The temperature registers must be addressed directly.\n\t *\/\n\tret = _interface->read(ADDR_OUT_T_L, (uint8_t *)&buf_rx, sizeof(buf_rx));\n\n\tif (ret != OK) {\n\t\tperf_end(_sample_perf);\n\t\tperf_count(_comms_errors);\n\t\tPX4_WARN(\"Register read error.\");\n\t\treturn ret;\n\t}\n\n\tperf_end(_sample_perf);\n\n\tif ((lis_report.status & (1 << 3)) == 0) { \/\/ check data ready\n\t\treturn 0;\n\t}\n\n\treport.x = (int16_t)((lis_report.x[1] << 8) | lis_report.x[0]);\n\treport.y = (int16_t)((lis_report.y[1] << 8) | lis_report.y[0]);\n\treport.z = (int16_t)((lis_report.z[1] << 8) | lis_report.z[0]);\n\n\treport.t = (int16_t)((buf_rx[1] << 8) | buf_rx[0]);\n\n\tfloat temperature = report.t;\n\t_px4_mag.set_temperature(25.0f + (temperature \/ 8.0f));\n\n\t\/* swap x and y axis *\/\n\t_px4_mag.update(timestamp_sample, report.y, report.x, report.z);\n\n\treturn PX4_OK;\n}\n\nvoid\nLIS2MDL::RunImpl()\n{\n\t\/* _measure_interval == 0 is used as _task_should_exit *\/\n\tif (_measure_interval == 0) {\n\t\treturn;\n\t}\n\n\tif (measure() != OK) {\n\t\tPX4_DEBUG(\"measure error\");\n\t}\n\n\t\/* schedule a fresh cycle call when the measurement is done *\/\n\tScheduleDelayed(LIS2MDL_CONVERSION_INTERVAL);\n}\n\nint\nLIS2MDL::init()\n{\n\n\tint ret = write_reg(ADDR_CFG_REG_A, CFG_REG_A_ODR | CFG_REG_A_MD | CFG_REG_A_TEMP_COMP_EN);\n\tret = write_reg(ADDR_CFG_REG_B, 0);\n\tret = write_reg(ADDR_CFG_REG_C, CFG_REG_C_BDU);\n\n\t_measure_interval = LIS2MDL_CONVERSION_INTERVAL;\n\tstart();\n\n\treturn ret;\n}\n\nvoid\nLIS2MDL::print_status()\n{\n\tI2CSPIDriverBase::print_status();\n\tperf_print_counter(_sample_perf);\n\tperf_print_counter(_comms_errors);\n\tPX4_INFO(\"poll interval: %u\", _measure_interval);\n\t_px4_mag.print_status();\n}\n\nvoid\nLIS2MDL::start()\n{\n\t\/* schedule a cycle to start things *\/\n\tScheduleNow();\n}\n\nint\nLIS2MDL::read_reg(uint8_t reg, uint8_t &val)\n{\n\tuint8_t buf = val;\n\tint ret = _interface->read(reg, &buf, 1);\n\tval = buf;\n\treturn ret;\n}\n\nint\nLIS2MDL::write_reg(uint8_t reg, uint8_t val)\n{\n\tuint8_t buf = val;\n\treturn _interface->write(reg, &buf, 1);\n}\n<commit_msg>lis2mdl: remove read error message<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file lis2mdl.cpp\n *\n * Driver for the LIS2MDL magnetometer connected via I2C or SPI.\n *\n * Based on the LIS2MDL driver.\n *\/\n\n#include <px4_platform_common\/time.h>\n#include \"lis2mdl.h\"\n\nLIS2MDL::LIS2MDL(device::Device *interface, enum Rotation rotation, I2CSPIBusOption bus_option, int bus) :\n\tI2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(interface->get_device_id()), bus_option, bus),\n\t_px4_mag(interface->get_device_id(), interface->external() ? ORB_PRIO_VERY_HIGH : ORB_PRIO_DEFAULT, rotation),\n\t_interface(interface),\n\t_comms_errors(perf_alloc(PC_COUNT, MODULE_NAME\": comms_errors\")),\n\t_conf_errors(perf_alloc(PC_COUNT, MODULE_NAME\": conf_errors\")),\n\t_range_errors(perf_alloc(PC_COUNT, MODULE_NAME\": range_errors\")),\n\t_sample_perf(perf_alloc(PC_ELAPSED, MODULE_NAME\": read\")),\n\t_measure_interval(0)\n{\n\t_px4_mag.set_external(_interface->external());\n\t_px4_mag.set_scale(0.0015f); \/* 49.152f \/ (2^15) *\/\n}\n\nLIS2MDL::~LIS2MDL()\n{\n\t\/\/ free perf counters\n\tperf_free(_sample_perf);\n\tperf_free(_comms_errors);\n\tperf_free(_range_errors);\n\tperf_free(_conf_errors);\n\n\tdelete _interface;\n}\n\nint\nLIS2MDL::measure()\n{\n\tstruct {\n\t\tuint8_t status;\n\t\tuint8_t x[2];\n\t\tuint8_t y[2];\n\t\tuint8_t z[2];\n\t} lis_report;\n\n\tstruct {\n\t\tint16_t x;\n\t\tint16_t y;\n\t\tint16_t z;\n\t\tint16_t t;\n\t} report;\n\n\tuint8_t buf_rx[2] = {};\n\n\t_px4_mag.set_error_count(perf_event_count(_comms_errors));\n\n\tperf_begin(_sample_perf);\n\n\tconst hrt_abstime timestamp_sample = hrt_absolute_time();\n\tint ret = _interface->read(ADDR_STATUS_REG, (uint8_t *)&lis_report, sizeof(lis_report));\n\n\t\/**\n\t * Silicon Bug: the X axis will be read instead of the temperature registers if you do a sequential read through XYZ.\n\t * The temperature registers must be addressed directly.\n\t *\/\n\tret = _interface->read(ADDR_OUT_T_L, (uint8_t *)&buf_rx, sizeof(buf_rx));\n\n\tif (ret != OK) {\n\t\tperf_end(_sample_perf);\n\t\tperf_count(_comms_errors);\n\t\treturn ret;\n\t}\n\n\tperf_end(_sample_perf);\n\n\tif ((lis_report.status & (1 << 3)) == 0) { \/\/ check data ready\n\t\treturn 0;\n\t}\n\n\treport.x = (int16_t)((lis_report.x[1] << 8) | lis_report.x[0]);\n\treport.y = (int16_t)((lis_report.y[1] << 8) | lis_report.y[0]);\n\treport.z = (int16_t)((lis_report.z[1] << 8) | lis_report.z[0]);\n\n\treport.t = (int16_t)((buf_rx[1] << 8) | buf_rx[0]);\n\n\tfloat temperature = report.t;\n\t_px4_mag.set_temperature(25.0f + (temperature \/ 8.0f));\n\n\t\/* swap x and y axis *\/\n\t_px4_mag.update(timestamp_sample, report.y, report.x, report.z);\n\n\treturn PX4_OK;\n}\n\nvoid\nLIS2MDL::RunImpl()\n{\n\t\/* _measure_interval == 0 is used as _task_should_exit *\/\n\tif (_measure_interval == 0) {\n\t\treturn;\n\t}\n\n\tif (measure() != OK) {\n\t\tPX4_DEBUG(\"measure error\");\n\t}\n\n\t\/* schedule a fresh cycle call when the measurement is done *\/\n\tScheduleDelayed(LIS2MDL_CONVERSION_INTERVAL);\n}\n\nint\nLIS2MDL::init()\n{\n\n\tint ret = write_reg(ADDR_CFG_REG_A, CFG_REG_A_ODR | CFG_REG_A_MD | CFG_REG_A_TEMP_COMP_EN);\n\tret = write_reg(ADDR_CFG_REG_B, 0);\n\tret = write_reg(ADDR_CFG_REG_C, CFG_REG_C_BDU);\n\n\t_measure_interval = LIS2MDL_CONVERSION_INTERVAL;\n\tstart();\n\n\treturn ret;\n}\n\nvoid\nLIS2MDL::print_status()\n{\n\tI2CSPIDriverBase::print_status();\n\tperf_print_counter(_sample_perf);\n\tperf_print_counter(_comms_errors);\n\tPX4_INFO(\"poll interval: %u\", _measure_interval);\n\t_px4_mag.print_status();\n}\n\nvoid\nLIS2MDL::start()\n{\n\t\/* schedule a cycle to start things *\/\n\tScheduleNow();\n}\n\nint\nLIS2MDL::read_reg(uint8_t reg, uint8_t &val)\n{\n\tuint8_t buf = val;\n\tint ret = _interface->read(reg, &buf, 1);\n\tval = buf;\n\treturn ret;\n}\n\nint\nLIS2MDL::write_reg(uint8_t reg, uint8_t val)\n{\n\tuint8_t buf = val;\n\treturn _interface->write(reg, &buf, 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993-2011 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"GameKeeper.h\"\n\n\/* system headers *\/\n#include <vector>\n#include <string>\n\n\/* common headers *\/\n#include \"GameTime.h\"\n\nGameKeeper::Player *GameKeeper::Player::playerList[PlayerSlot] = {NULL};\nbool GameKeeper::Player::allNeedHostbanChecked = false;\n\nvoid *PackPlayerInfo(void *buf, int playerIndex, uint8_t properties )\n{\n buf = nboPackUByte(buf, playerIndex);\n buf = nboPackUByte(buf, properties);\n return buf;\n}\n\nGameKeeper::Player::Player(int _playerIndex,\n\t\t\t const struct sockaddr_in &clientAddr, int fd,\n\t\t\t tcpCallback _clientCallback):\n player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(_clientCallback),\n needThisHostbanChecked(false), idFlag(-1)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = new NetHandler(&player, clientAddr, playerIndex, fd);\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n playerHandler = NULL;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::Player(int _playerIndex,\n\t\t\t NetHandler *handler,\n\t\t\t tcpCallback _clientCallback):\n player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(_clientCallback),\n needThisHostbanChecked(false)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = handler;\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n netHandler->setPlayer((PlayerInfo*)this,_playerIndex);\n playerHandler = NULL;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::Player(int _playerIndex, bz_ServerSidePlayerHandler *handler)\n : player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(NULL),\n needThisHostbanChecked(false)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = NULL;\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n netHandler->setPlayer((PlayerInfo*)this,_playerIndex);\n playerHandler = handler;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::~Player()\n{\n flagHistory.clear();\n delete netHandler;\n playerList[playerIndex] = NULL;\n}\n\nint GameKeeper::Player::count()\n{\n Player *playerData;\n int count = 0;\n\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& playerData->player.isPlaying())\n count++;\n return count;\n}\n\nvoid GameKeeper::Player::updateLatency(float &waitTime)\n{\n Player* playerData;\n int p;\n\n for (p = 0; p < PlayerSlot; p++) {\n if ((playerData = playerList[p]) && !playerData->closed) {\n \/\/ get time for next lagping\n playerData->lagInfo.updateLatency(waitTime);\n }\n }\n}\n\nvoid GameKeeper::Player::dumpScore()\n{\n Player *playerData;\n\n std::cout << \"\\n#players\\n\";\n int p;\n for (p = 0; p < PlayerSlot; p++)\n if ((playerData = playerList[p]) && !playerData->closed\n\t&& playerData->player.isPlaying()) {\n playerData->score.dump();\n std::cout << ' ' << playerData->player.getCallSign() << std::endl;\n }\n}\n\nint GameKeeper::Player::anointRabbit(int oldRabbit)\n{\n float topRatio = -100000.0f;\n int rabbitIndex = NoPlayer;\n\n Player *playerData;\n int i;\n bool goodRabbitSelected = false;\n\n for (i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& playerData->player.canBeRabbit(true)) {\n\tbool goodRabbit = i != oldRabbit && playerData->player.isAlive();\n\tfloat ratio = playerData->score.ranking();\n\tbool select = false;\n\tif (goodRabbitSelected) {\n\t if (goodRabbit && (ratio > topRatio)) {\n\t select = true;\n\t }\n\t} else {\n\t if (goodRabbit) {\n\t select\t = true;\n\t goodRabbitSelected = true;\n\t } else {\n\t if (ratio > topRatio)\n\t select = true;\n\t }\n\t}\n\tif (select) {\n\t topRatio = ratio;\n\t rabbitIndex = i;\n\t}\n }\n return rabbitIndex;\n}\n\nvoid GameKeeper::Player::updateNextGameTime()\n{\n if (gameTimeRate < GameTime::startRate) {\n gameTimeRate = GameTime::startRate;\n } else if (gameTimeRate < GameTime::finalRate) {\n gameTimeRate = gameTimeRate * 1.25f;\n } else {\n gameTimeRate = GameTime::finalRate;\n }\n gameTimeNext = TimeKeeper::getCurrent();\n gameTimeNext += gameTimeRate;\n return;\n}\n\nvoid *GameKeeper::Player::packAdminInfo(void *buf)\n{\n buf = nboPackUByte(buf, netHandler->sizeOfIP());\n buf = nboPackUByte(buf, playerIndex);\n buf = netHandler->packAdminInfo(buf);\n return buf;\n}\n\nvoid *GameKeeper::Player::packPlayerInfo(void *buf)\n{\n buf = PackPlayerInfo(buf, playerIndex, accessInfo.getPlayerProperties());\n return buf;\n}\n\nvoid *GameKeeper::Player::packPlayerUpdate(void *buf)\n{\n buf = nboPackUByte(buf, playerIndex);\n buf = player.packUpdate(buf);\n buf = score.pack(buf);\n buf = player.packId(buf);\n return buf;\n}\n\nvoid GameKeeper::Player::setPlayerAddMessage ( PlayerAddMessage &msg )\n{\n\tmsg.playerID = playerIndex;\n\tmsg.team = player.getTeam();\n\tmsg.type = player.getType();\n\tmsg.wins = score.getWins();\n\tmsg.losses = score.getLosses();\n\tmsg.tks = score.getTKs();\n\tmsg.callsign = player.getCallSign();\n\tmsg.motto = player.getMotto();\n}\n\n\nstd::vector<int> GameKeeper::Player::allowed(PlayerAccessInfo::AccessPerm right,\n\t\t\t\t\t int targetPlayer)\n{\n std::vector<int> receivers;\n Player* playerData;\n\n if (targetPlayer != -1) {\n if ((playerData = playerList[targetPlayer]) && !playerData->closed\n\t&& playerData->accessInfo.hasPerm(right))\n receivers.push_back(targetPlayer);\n } else {\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t && playerData->accessInfo.hasPerm(right))\n\treceivers.push_back(i);\n }\n\n return receivers;\n}\n\nbool GameKeeper::Player::loadEnterData(uint16_t &rejectCode,\n\t\t\t\t char *rejectMsg)\n{\n \/\/ look if there is as name clash, we won't allow this\n for (int i = 0; i < PlayerSlot; i++) {\n Player *otherData = playerList[i];\n if (i == playerIndex || !otherData || !otherData->player.isPlaying())\n continue;\n if (otherData->closed)\n continue;\n if (!strcasecmp(otherData->player.getCallSign(), player.getCallSign())) {\n rejectCode = RejectRepeatCallsign;\n strcpy(rejectMsg, \"The callsign specified is already in use.\");\n return false;\n }\n }\n\n return true;\n}\n\nvoid GameKeeper::Player::signingOn(bool ctf)\n{\n player.resetPlayer(ctf);\n player.signingOn();\n lagInfo.reset();\n}\n\n\n\/\/ Attempt to retrive a slot number for a player specified as EITHER \"callsign\" or \"#<slot>\"\nint GameKeeper::Player::getPlayerIDByName(const std::string &name)\n{\n Player* playerData;\n int slot = -1; \/\/ invalid\n\n if (sscanf (name.c_str(), \"#%d\", &slot) == 1) {\n if ( ! GameKeeper::Player::getPlayerByIndex(slot) )\n return -1;\n return slot;\n } else {\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& (TextUtils::compare_nocase(playerData->player.getCallSign(), name) == 0))\n\treturn i;\n }\n return -1;\n}\n\n\nvoid GameKeeper::Player::reloadAccessDatabase()\n{\n Player* playerData;\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed)\n playerData->accessInfo.reloadInfo();\n}\n\nvoid GameKeeper::Player::close()\n{\n closed = true;\n}\n\nbool GameKeeper::Player::clean()\n{\n Player* playerData;\n \/\/ Trying to detect if this action cleaned the array of player\n bool empty = true;\n bool ICleaned = false;\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i])) {\n if (playerData->closed) {\n\tdelete playerData;\n\tICleaned = true;\n } else {\n\tempty = false;\n }\n }\n return empty && ICleaned;\n}\n\nint GameKeeper::Player::getFreeIndex(int min, int max)\n{\n for (int i = min; i < max; i++)\n if (!playerList[i])\n return i;\n return max;\n}\n\nvoid GameKeeper::Player::handleTcpPacket(fd_set *set)\n{\n if (netHandler->isFdSet(set)) {\n const RxStatus e = netHandler->tcpReceive();\n if (e == ReadPart)\n return;\n clientCallback(*netHandler, playerIndex, e);\n }\n}\n\nvoid GameKeeper::Player::setPlayerState(float pos[3], float azimuth)\n{\n serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds();\n memcpy(lastState.pos, pos, sizeof(float) * 3);\n lastState.azimuth = azimuth;\n \/\/ Set Speeds to 0 too\n memset(lastState.velocity, 0, sizeof(float) * 3);\n lastState.angVel = 0.0f;\n stateTimeStamp = 0.0f;\n\n \/\/ player is alive.\n player.setAlive();\n\n}\n\nint GameKeeper::Player::maxShots = 0;\nvoid GameKeeper::Player::setMaxShots(int _maxShots)\n{\n maxShots = _maxShots;\n}\n\nbool GameKeeper::Player::addShot(int id, int salt, FiringInfo &firingInfo)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id < (int)shotsInfo.size() && shotsInfo[id].present\n && now < shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] shot id %d duplicated\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n \/\/ verify shot number\n if (id > maxShots - 1) {\n logDebugMessage(2,\"Player %s [%d] shot id %d out of range %d\\n\",\n\t player.getCallSign(), playerIndex, id, maxShots);\n return false;\n }\n\n shotsInfo.resize(maxShots);\n\n float lifeTime = BZDB.eval(StateDatabase::BZDB_RELOADTIME);\n if (firingInfo.flagType == Flags::RapidFire)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_RFIREADLIFE);\n else if (firingInfo.flagType == Flags::MachineGun)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_MGUNADLIFE);\n else if (firingInfo.flagType == Flags::GuidedMissile)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_GMADLIFE) + .01f;\n else if (firingInfo.flagType == Flags::Laser)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_LASERADLIFE);\n else if (firingInfo.flagType == Flags::ShockWave)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_SHOCKADLIFE);\n else if (firingInfo.flagType == Flags::Thief)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_THIEFADLIFE);\n\n ShotInfo myShot;\n myShot.firingInfo = firingInfo;\n myShot.salt\t= salt;\n myShot.expireTime = now + lifeTime;\n myShot.present = true;\n myShot.running = true;\n\n shotsInfo[id] = myShot;\n return true;\n}\n\nbool GameKeeper::Player::removeShot(int id, int salt)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id >= (int)shotsInfo.size() || !shotsInfo[id].present\n || now >= shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] trying to stop the unexistent shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (shotsInfo[id].salt != salt) {\n logDebugMessage(2,\"Player %s [%d] trying to stop a mismatched shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (!shotsInfo[id].running)\n return false;\n shotsInfo[id].running = false;\n return true;\n}\n\nbool GameKeeper::Player::updateShot(int id, int salt)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id >= (int)shotsInfo.size() || !shotsInfo[id].present\n || now >= shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] trying to update an unexistent shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (shotsInfo[id].salt != salt) {\n logDebugMessage(2,\"Player %s [%d] trying to update a mismatched shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (!shotsInfo[id].running)\n return false;\n \/\/ only GM can be updated\n if (shotsInfo[id].firingInfo.flagType != Flags::GuidedMissile) {\n logDebugMessage(2,\"Player %s [%d] trying to update a non GM shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n return true;\n}\n\nvoid GameKeeper::Player::setPlayerState(PlayerState state, float timestamp)\n{\n lagInfo.updateLag(timestamp, state.order - lastState.order > 1);\n player.updateIdleTime();\n lastState = state;\n stateTimeStamp = timestamp;\n serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds();\n}\n\nvoid GameKeeper::Player::getPlayerState(float pos[3], float &azimuth)\n{\n memcpy(pos, lastState.pos, sizeof(float) * 3);\n azimuth = lastState.azimuth;\n}\n\nvoid GameKeeper::Player::setLastIdFlag(int _idFlag) {\n idFlag = _idFlag;\n}\n\nint GameKeeper::Player::getLastIdFlag() {\n return idFlag;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>don't set the NetHandler player when we don't have a NetHandler (server side bots)<commit_after>\/* bzflag\n * Copyright (c) 1993-2011 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"GameKeeper.h\"\n\n\/* system headers *\/\n#include <vector>\n#include <string>\n\n\/* common headers *\/\n#include \"GameTime.h\"\n\nGameKeeper::Player *GameKeeper::Player::playerList[PlayerSlot] = {NULL};\nbool GameKeeper::Player::allNeedHostbanChecked = false;\n\nvoid *PackPlayerInfo(void *buf, int playerIndex, uint8_t properties )\n{\n buf = nboPackUByte(buf, playerIndex);\n buf = nboPackUByte(buf, properties);\n return buf;\n}\n\nGameKeeper::Player::Player(int _playerIndex,\n\t\t\t const struct sockaddr_in &clientAddr, int fd,\n\t\t\t tcpCallback _clientCallback):\n player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(_clientCallback),\n needThisHostbanChecked(false), idFlag(-1)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = new NetHandler(&player, clientAddr, playerIndex, fd);\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n playerHandler = NULL;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::Player(int _playerIndex,\n\t\t\t NetHandler *handler,\n\t\t\t tcpCallback _clientCallback):\n player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(_clientCallback),\n needThisHostbanChecked(false)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = handler;\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n netHandler->setPlayer((PlayerInfo*)this,_playerIndex);\n playerHandler = NULL;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::Player(int _playerIndex, bz_ServerSidePlayerHandler *handler)\n : player(_playerIndex), lagInfo(&player),\n playerIndex(_playerIndex), closed(false), clientCallback(NULL),\n needThisHostbanChecked(false)\n{\n playerList[playerIndex] = this;\n\n lastState.order = 0;\n \/\/ Timestamp 0.0 -> not yet available\n stateTimeStamp = 0.0f;\n gameTimeRate = GameTime::startRate;\n gameTimeNext = TimeKeeper::getCurrent();\n netHandler = NULL;\n _LSAState = start;\n bzIdentifier = \"\";\n isParting = false;\n playerHandler = handler;\n score.playerID = _playerIndex;\n}\n\nGameKeeper::Player::~Player()\n{\n flagHistory.clear();\n delete netHandler;\n playerList[playerIndex] = NULL;\n}\n\nint GameKeeper::Player::count()\n{\n Player *playerData;\n int count = 0;\n\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& playerData->player.isPlaying())\n count++;\n return count;\n}\n\nvoid GameKeeper::Player::updateLatency(float &waitTime)\n{\n Player* playerData;\n int p;\n\n for (p = 0; p < PlayerSlot; p++) {\n if ((playerData = playerList[p]) && !playerData->closed) {\n \/\/ get time for next lagping\n playerData->lagInfo.updateLatency(waitTime);\n }\n }\n}\n\nvoid GameKeeper::Player::dumpScore()\n{\n Player *playerData;\n\n std::cout << \"\\n#players\\n\";\n int p;\n for (p = 0; p < PlayerSlot; p++)\n if ((playerData = playerList[p]) && !playerData->closed\n\t&& playerData->player.isPlaying()) {\n playerData->score.dump();\n std::cout << ' ' << playerData->player.getCallSign() << std::endl;\n }\n}\n\nint GameKeeper::Player::anointRabbit(int oldRabbit)\n{\n float topRatio = -100000.0f;\n int rabbitIndex = NoPlayer;\n\n Player *playerData;\n int i;\n bool goodRabbitSelected = false;\n\n for (i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& playerData->player.canBeRabbit(true)) {\n\tbool goodRabbit = i != oldRabbit && playerData->player.isAlive();\n\tfloat ratio = playerData->score.ranking();\n\tbool select = false;\n\tif (goodRabbitSelected) {\n\t if (goodRabbit && (ratio > topRatio)) {\n\t select = true;\n\t }\n\t} else {\n\t if (goodRabbit) {\n\t select\t = true;\n\t goodRabbitSelected = true;\n\t } else {\n\t if (ratio > topRatio)\n\t select = true;\n\t }\n\t}\n\tif (select) {\n\t topRatio = ratio;\n\t rabbitIndex = i;\n\t}\n }\n return rabbitIndex;\n}\n\nvoid GameKeeper::Player::updateNextGameTime()\n{\n if (gameTimeRate < GameTime::startRate) {\n gameTimeRate = GameTime::startRate;\n } else if (gameTimeRate < GameTime::finalRate) {\n gameTimeRate = gameTimeRate * 1.25f;\n } else {\n gameTimeRate = GameTime::finalRate;\n }\n gameTimeNext = TimeKeeper::getCurrent();\n gameTimeNext += gameTimeRate;\n return;\n}\n\nvoid *GameKeeper::Player::packAdminInfo(void *buf)\n{\n buf = nboPackUByte(buf, netHandler->sizeOfIP());\n buf = nboPackUByte(buf, playerIndex);\n buf = netHandler->packAdminInfo(buf);\n return buf;\n}\n\nvoid *GameKeeper::Player::packPlayerInfo(void *buf)\n{\n buf = PackPlayerInfo(buf, playerIndex, accessInfo.getPlayerProperties());\n return buf;\n}\n\nvoid *GameKeeper::Player::packPlayerUpdate(void *buf)\n{\n buf = nboPackUByte(buf, playerIndex);\n buf = player.packUpdate(buf);\n buf = score.pack(buf);\n buf = player.packId(buf);\n return buf;\n}\n\nvoid GameKeeper::Player::setPlayerAddMessage ( PlayerAddMessage &msg )\n{\n\tmsg.playerID = playerIndex;\n\tmsg.team = player.getTeam();\n\tmsg.type = player.getType();\n\tmsg.wins = score.getWins();\n\tmsg.losses = score.getLosses();\n\tmsg.tks = score.getTKs();\n\tmsg.callsign = player.getCallSign();\n\tmsg.motto = player.getMotto();\n}\n\n\nstd::vector<int> GameKeeper::Player::allowed(PlayerAccessInfo::AccessPerm right,\n\t\t\t\t\t int targetPlayer)\n{\n std::vector<int> receivers;\n Player* playerData;\n\n if (targetPlayer != -1) {\n if ((playerData = playerList[targetPlayer]) && !playerData->closed\n\t&& playerData->accessInfo.hasPerm(right))\n receivers.push_back(targetPlayer);\n } else {\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t && playerData->accessInfo.hasPerm(right))\n\treceivers.push_back(i);\n }\n\n return receivers;\n}\n\nbool GameKeeper::Player::loadEnterData(uint16_t &rejectCode,\n\t\t\t\t char *rejectMsg)\n{\n \/\/ look if there is as name clash, we won't allow this\n for (int i = 0; i < PlayerSlot; i++) {\n Player *otherData = playerList[i];\n if (i == playerIndex || !otherData || !otherData->player.isPlaying())\n continue;\n if (otherData->closed)\n continue;\n if (!strcasecmp(otherData->player.getCallSign(), player.getCallSign())) {\n rejectCode = RejectRepeatCallsign;\n strcpy(rejectMsg, \"The callsign specified is already in use.\");\n return false;\n }\n }\n\n return true;\n}\n\nvoid GameKeeper::Player::signingOn(bool ctf)\n{\n player.resetPlayer(ctf);\n player.signingOn();\n lagInfo.reset();\n}\n\n\n\/\/ Attempt to retrive a slot number for a player specified as EITHER \"callsign\" or \"#<slot>\"\nint GameKeeper::Player::getPlayerIDByName(const std::string &name)\n{\n Player* playerData;\n int slot = -1; \/\/ invalid\n\n if (sscanf (name.c_str(), \"#%d\", &slot) == 1) {\n if ( ! GameKeeper::Player::getPlayerByIndex(slot) )\n return -1;\n return slot;\n } else {\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed\n\t&& (TextUtils::compare_nocase(playerData->player.getCallSign(), name) == 0))\n\treturn i;\n }\n return -1;\n}\n\n\nvoid GameKeeper::Player::reloadAccessDatabase()\n{\n Player* playerData;\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i]) && !playerData->closed)\n playerData->accessInfo.reloadInfo();\n}\n\nvoid GameKeeper::Player::close()\n{\n closed = true;\n}\n\nbool GameKeeper::Player::clean()\n{\n Player* playerData;\n \/\/ Trying to detect if this action cleaned the array of player\n bool empty = true;\n bool ICleaned = false;\n for (int i = 0; i < PlayerSlot; i++)\n if ((playerData = playerList[i])) {\n if (playerData->closed) {\n\tdelete playerData;\n\tICleaned = true;\n } else {\n\tempty = false;\n }\n }\n return empty && ICleaned;\n}\n\nint GameKeeper::Player::getFreeIndex(int min, int max)\n{\n for (int i = min; i < max; i++)\n if (!playerList[i])\n return i;\n return max;\n}\n\nvoid GameKeeper::Player::handleTcpPacket(fd_set *set)\n{\n if (netHandler->isFdSet(set)) {\n const RxStatus e = netHandler->tcpReceive();\n if (e == ReadPart)\n return;\n clientCallback(*netHandler, playerIndex, e);\n }\n}\n\nvoid GameKeeper::Player::setPlayerState(float pos[3], float azimuth)\n{\n serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds();\n memcpy(lastState.pos, pos, sizeof(float) * 3);\n lastState.azimuth = azimuth;\n \/\/ Set Speeds to 0 too\n memset(lastState.velocity, 0, sizeof(float) * 3);\n lastState.angVel = 0.0f;\n stateTimeStamp = 0.0f;\n\n \/\/ player is alive.\n player.setAlive();\n\n}\n\nint GameKeeper::Player::maxShots = 0;\nvoid GameKeeper::Player::setMaxShots(int _maxShots)\n{\n maxShots = _maxShots;\n}\n\nbool GameKeeper::Player::addShot(int id, int salt, FiringInfo &firingInfo)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id < (int)shotsInfo.size() && shotsInfo[id].present\n && now < shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] shot id %d duplicated\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n \/\/ verify shot number\n if (id > maxShots - 1) {\n logDebugMessage(2,\"Player %s [%d] shot id %d out of range %d\\n\",\n\t player.getCallSign(), playerIndex, id, maxShots);\n return false;\n }\n\n shotsInfo.resize(maxShots);\n\n float lifeTime = BZDB.eval(StateDatabase::BZDB_RELOADTIME);\n if (firingInfo.flagType == Flags::RapidFire)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_RFIREADLIFE);\n else if (firingInfo.flagType == Flags::MachineGun)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_MGUNADLIFE);\n else if (firingInfo.flagType == Flags::GuidedMissile)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_GMADLIFE) + .01f;\n else if (firingInfo.flagType == Flags::Laser)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_LASERADLIFE);\n else if (firingInfo.flagType == Flags::ShockWave)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_SHOCKADLIFE);\n else if (firingInfo.flagType == Flags::Thief)\n lifeTime *= BZDB.eval(StateDatabase::BZDB_THIEFADLIFE);\n\n ShotInfo myShot;\n myShot.firingInfo = firingInfo;\n myShot.salt\t= salt;\n myShot.expireTime = now + lifeTime;\n myShot.present = true;\n myShot.running = true;\n\n shotsInfo[id] = myShot;\n return true;\n}\n\nbool GameKeeper::Player::removeShot(int id, int salt)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id >= (int)shotsInfo.size() || !shotsInfo[id].present\n || now >= shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] trying to stop the unexistent shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (shotsInfo[id].salt != salt) {\n logDebugMessage(2,\"Player %s [%d] trying to stop a mismatched shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (!shotsInfo[id].running)\n return false;\n shotsInfo[id].running = false;\n return true;\n}\n\nbool GameKeeper::Player::updateShot(int id, int salt)\n{\n float now = (float)TimeKeeper::getCurrent().getSeconds();\n if (id >= (int)shotsInfo.size() || !shotsInfo[id].present\n || now >= shotsInfo[id].expireTime) {\n logDebugMessage(2,\"Player %s [%d] trying to update an unexistent shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (shotsInfo[id].salt != salt) {\n logDebugMessage(2,\"Player %s [%d] trying to update a mismatched shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n if (!shotsInfo[id].running)\n return false;\n \/\/ only GM can be updated\n if (shotsInfo[id].firingInfo.flagType != Flags::GuidedMissile) {\n logDebugMessage(2,\"Player %s [%d] trying to update a non GM shot id %d\\n\",\n\t player.getCallSign(), playerIndex, id);\n return false;\n }\n return true;\n}\n\nvoid GameKeeper::Player::setPlayerState(PlayerState state, float timestamp)\n{\n lagInfo.updateLag(timestamp, state.order - lastState.order > 1);\n player.updateIdleTime();\n lastState = state;\n stateTimeStamp = timestamp;\n serverTimeStamp = (float)TimeKeeper::getCurrent().getSeconds();\n}\n\nvoid GameKeeper::Player::getPlayerState(float pos[3], float &azimuth)\n{\n memcpy(pos, lastState.pos, sizeof(float) * 3);\n azimuth = lastState.azimuth;\n}\n\nvoid GameKeeper::Player::setLastIdFlag(int _idFlag) {\n idFlag = _idFlag;\n}\n\nint GameKeeper::Player::getLastIdFlag() {\n return idFlag;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file 11cxx_async_can.cxx\n * This file implements an asynchronous CAN driver for the LPC11Cxx\n * microcontrollers, using the builtin ROM drivers.\n *\n * @author Balazs Racz\n * @date 14 Dec 2013\n *\/\n\n#ifdef TARGET_LPC11Cxx\n\n#include \"11CXX_rom_driver_CAN.h\"\n#include \"can.h\"\n\n#include \"executor\/control_flow.hxx\"\n#include \"utils\/pipe.hxx\"\n\ntypedef struct _ROM\n{\n const unsigned p_usbd;\n const unsigned p_clib;\n const CAND* pCAND;\n} ROM;\n\n\/** Pointer to the ROM call structures. *\/\nconst ROM* const* const rom = (ROM**)0x1fff1ff8;\n\nstatic const int RX_MSG_OBJ_NUM = 1;\nstatic const int TX_MSG_OBJ_NUM = 2;\n\nextern Executor g_executor;\n\nnamespace lpc11cxx\n{\n\n#define FIRST_TX_OBJ 1\n#define FIRST_RX_OBJ 16\n\nclass CanPipeMember;\nclass CanRxFlow;\n\n\/* Static instances of the CAN drivers *\/\nCanPipeMember* g_tx_instance = nullptr;\nCanRxFlow* g_rx_instance = nullptr;\nPipe* g_pipe = nullptr;\n\nclass CanPipeMember : public PipeMember, public Executable, private Lockable\n{\npublic:\n CanPipeMember()\n : freeTxBuffers_(0xFFFFFFFF), frameToWrite_(nullptr), done_(nullptr), bufferFull_(0)\n {\n lock_.TypedRelease(this);\n released_ = 1;\n allocatorAsked_ = 0;\n }\n\n virtual AllocatorBase* get_allocator()\n {\n allocatorAsked_++;\n return &lock_;\n }\n\n virtual void write(const void* buf, size_t count)\n {\n HASSERT(0);\n }\n\n virtual void async_write(const void* buf, size_t count, Notifiable* done)\n {\n released_ = 0;\n allocatorAsked_--;\n HASSERT(count == sizeof(struct can_frame));\n HASSERT(!frameToWrite_);\n done_ = done;\n LockHolder h(this);\n frameToWrite_ = static_cast<const struct can_frame*>(buf);\n g_executor.Add(this);\n }\n\n virtual void Run()\n {\n HASSERT(frameToWrite_);\n const struct can_frame* frame = nullptr;\n Notifiable* done = nullptr;\n uint8_t buf_num = FIRST_TX_OBJ;\n {\n LockHolder h(this);\n\n \/\/ Looks for a free tx buffer.\n while (buf_num < FIRST_RX_OBJ &&\n (!(freeTxBuffers_ & (1 << buf_num))))\n {\n buf_num++;\n }\n if (buf_num >= FIRST_RX_OBJ)\n {\n \/\/ Wait for ISR to wake us up.\n bufferFull_ = 1;\n return;\n }\n\n freeTxBuffers_ &= ~(1 << buf_num);\n\n \/\/ We decided to send the frame.\n frame = frameToWrite_;\n frameToWrite_ = nullptr; \/\/ no callbacks from ISR.\n done = done_;\n done_ = nullptr;\n }\n bufferFull_ = 0;\n CAN_MSG_OBJ msg_obj;\n msg_obj.msgobj = buf_num;\n msg_obj.mode_id = frame->can_id |\n (frame->can_rtr ? CAN_MSGOBJ_RTR : 0) |\n (frame->can_eff ? CAN_MSGOBJ_EXT : 0);\n msg_obj.mask = 0x0;\n msg_obj.dlc = frame->can_dlc;\n memcpy(msg_obj.data, frame->data, frame->can_dlc);\n (*rom)->pCAND->can_transmit(&msg_obj);\n\n \/\/ The incoming frame is no longer needed.\n done->Notify();\n released_ = 1;\n lock_.TypedReleaseBack(this);\n }\n\n void TxFinishedFromIsr(uint8_t buf_num)\n {\n HASSERT(!(freeTxBuffers_ & (1 << buf_num)));\n freeTxBuffers_ |= (1 << buf_num);\n if (frameToWrite_ && !g_executor.IsRunning(this))\n {\n g_executor.AddFromIsr(this);\n }\n }\n\nprivate:\n uint32_t freeTxBuffers_;\n const struct can_frame* frameToWrite_;\n Notifiable* done_;\n TypedAllocator<PipeMember> lock_;\n \/\/ 1 if a run method returned because it didn't find a free tx buffer.\n unsigned bufferFull_ : 1;\n unsigned released_ : 1;\n unsigned allocatorAsked_ : 4;\n};\n\nclass CanRxFlow : public AllocationResult\n{\npublic:\n CanRxFlow() : bufFull_(0), rxPending_(0), frameLost_(0)\n {\n \/* Configures msgobj NN to receive all extended frames. *\/\n CAN_MSG_OBJ msg_obj;\n msg_obj.msgobj = FIRST_RX_OBJ;\n msg_obj.mode_id = 0x000 | CAN_MSGOBJ_EXT;\n msg_obj.mask = 0x000;\n msg_obj.dlc = 0x000;\n (*rom)->pCAND->config_rxmsgobj(&msg_obj);\n }\n\n \/\/ Callback inside the ISR context. @param buf_num is the number of the\n \/\/ message object in the hardware.\n void isr(uint8_t buf_num)\n {\n if (rxPending_)\n {\n frameLost_ = 1;\n \/\/ Since rxPending is already 1, we'll let the executor deal with\n \/\/ copying the frame to the buffer.\n return;\n }\n else\n {\n rxPending_ = 1;\n }\n if (!bufFull_)\n {\n copy_hardware_frame(buf_num);\n g_executor.AddFromIsr(this);\n }\n }\n\n \/\/ Scheduled by the ISR when the frame has arrived.\n virtual void Run()\n {\n HASSERT(bufFull_);\n g_can_alloc.AllocateEntry(this);\n }\n\n virtual void AllocationCallback(QueueMember* entry)\n {\n HASSERT(bufFull_);\n CanPipeBuffer* buf = g_can_alloc.cast_result(entry);\n buf->Reset();\n memcpy(&buf->frame, &frame_, sizeof(frame_));\n buf->pipe_buffer.skipMember = g_tx_instance;\n g_pipe->SendBuffer(&buf->pipe_buffer);\n {\n portSET_INTERRUPT_MASK();\n bufFull_ = 0;\n if (rxPending_)\n {\n copy_hardware_frame(FIRST_RX_OBJ);\n \/\/ will crash if this is already added\n g_executor.Add(this);\n }\n portCLEAR_INTERRUPT_MASK();\n }\n }\n\nprivate:\n \/\/ Has to run either in ISR or in a critical section. Retrieves a hardware\n \/\/ buffer and copies it to the class-local can_frame.\n void copy_hardware_frame(uint8_t buf_num)\n {\n HASSERT(rxPending_);\n HASSERT(!bufFull_);\n CAN_MSG_OBJ msg_obj;\n \/* Determine which CAN message has been received *\/\n msg_obj.msgobj = buf_num;\n\n \/* Now load up the msg_obj structure with the CAN message *\/\n (*rom)->pCAND->can_receive(&msg_obj);\n\n \/\/ Here we need to be in a critical section; otherwise another CAN\n \/\/ interrupt might come in between these two calls.\n bufFull_ = 1;\n rxPending_ = 0;\n\n frame_.can_id = msg_obj.mode_id & ((1 << 30) - 1);\n HASSERT(frame_.can_id & 0xfff);\n frame_.can_rtr = (msg_obj.mode_id & CAN_MSGOBJ_RTR) ? 1 : 0;\n frame_.can_eff = (msg_obj.mode_id & CAN_MSGOBJ_EXT) ? 1 : 0;\n frame_.can_err = 0;\n frame_.can_dlc = msg_obj.dlc;\n memcpy(frame_.data, msg_obj.data, msg_obj.dlc);\n }\n\n struct can_frame frame_;\n \/\/ 1 if the struct can_frame in here is full.\n unsigned bufFull_ : 1;\n \/\/ 1 if the can buffer in the hardware object is full.\n unsigned rxPending_ : 1;\n \/\/ 1 if we have lost a frame.\n unsigned frameLost_ : 1;\n};\n\n\/** CAN receive callback. Called by the ROM can driver in an ISR context.\n @param msg_obj_num the number of CAN buffer that has the new frame.\n*\/\nvoid CAN_rx(uint8_t msg_obj_num)\n{\n HASSERT(g_rx_instance);\n g_rx_instance->isr(msg_obj_num);\n \/\/ We always assume there is someone woken up. This is not nice.\n portYIELD();\n}\n\n\/** CAN transmit callback. Called by the ROM can driver in an ISR context.\n @param msg_obj_num the number of CAN buffer that finished transmission.\n*\/\nvoid CAN_tx(uint8_t msg_obj_num)\n{\n HASSERT(g_tx_instance);\n g_tx_instance->TxFinishedFromIsr(msg_obj_num);\n \/\/ We always assume there is someone woken up. This is not nice.\n portYIELD();\n}\n\n\/** CAN error callback. Called by the ROM can driver in an ISR context.\n @param error_info defines what kind of error occured on the bus.\n*\/\nvoid CAN_error(uint32_t error_info)\n{\n return;\n}\n\n\/** Function pointer table to pass to the ROM drivers with callbacks. *\/\nstatic const CAN_CALLBACKS callbacks = {CAN_rx, CAN_tx, CAN_error, NULL,\n NULL, NULL, NULL, NULL, };\n\n\/** Clock initialization constants for 125 kbaud *\/\nconst uint32_t ClkInitTable125[2] = {0x00000000UL, \/\/ CANCLKDIV\n 0x00001C57UL \/\/ CAN_BTR\n};\n\n\/** Clock initialization constants for 250 kbaud *\/\nstatic const uint32_t ClkInitTable250[2] = {0x00000000UL, \/\/ CANCLKDIV\n 0x00001C4BUL \/\/ CAN_BTR\n};\n\nvoid CreateCanDriver(Pipe* parent)\n{\n \/* Initialize the CAN controller *\/\n (*rom)->pCAND->init_can((uint32_t*)&ClkInitTable250[0], 1);\n \/* Configure the CAN callback functions *\/\n (*rom)->pCAND->config_calb((CAN_CALLBACKS*)&callbacks);\n\n g_pipe = parent;\n g_rx_instance = new CanRxFlow();\n g_tx_instance = new CanPipeMember();\n parent->RegisterMember(g_tx_instance);\n\n \/* Enable the CAN Interrupt *\/\n NVIC_SetPriority(CAN_IRQn, 1);\n NVIC_EnableIRQ(CAN_IRQn);\n}\n\n} \/\/ namespace lpc11cxx\n\nextern \"C\" {\n\/** Overrides the system's weak interrupt handler and calls the builtin ROM\n * interrupt handler. *\/\nvoid CAN_IRQHandler(void)\n{\n (*rom)->pCAND->isr();\n}\n}\n\n#else\n#error You need to define TARGET_LPC11Cxx if you want to compiple its rom driver.\n#endif\n<commit_msg>Fixes a bug in the 11CXX asyn can driver. Removes assertion on alias being zero -- JMRI sends frames like that.<commit_after>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file 11cxx_async_can.cxx\n * This file implements an asynchronous CAN driver for the LPC11Cxx\n * microcontrollers, using the builtin ROM drivers.\n *\n * @author Balazs Racz\n * @date 14 Dec 2013\n *\/\n\n#ifdef TARGET_LPC11Cxx\n\n#include \"11CXX_rom_driver_CAN.h\"\n#include \"can.h\"\n\n#include \"executor\/control_flow.hxx\"\n#include \"utils\/pipe.hxx\"\n\ntypedef struct _ROM\n{\n const unsigned p_usbd;\n const unsigned p_clib;\n const CAND* pCAND;\n} ROM;\n\n\/** Pointer to the ROM call structures. *\/\nconst ROM* const* const rom = (ROM**)0x1fff1ff8;\n\nstatic const int RX_MSG_OBJ_NUM = 1;\nstatic const int TX_MSG_OBJ_NUM = 2;\n\nextern Executor g_executor;\n\nnamespace lpc11cxx\n{\n\n#define FIRST_TX_OBJ 1\n#define FIRST_RX_OBJ 16\n\nclass CanPipeMember;\nclass CanRxFlow;\n\n\/* Static instances of the CAN drivers *\/\nCanPipeMember* g_tx_instance = nullptr;\nCanRxFlow* g_rx_instance = nullptr;\nPipe* g_pipe = nullptr;\n\nclass CanPipeMember : public PipeMember, public Executable, private Lockable\n{\npublic:\n CanPipeMember()\n : freeTxBuffers_(0xFFFFFFFF), frameToWrite_(nullptr), done_(nullptr), bufferFull_(0)\n {\n lock_.TypedRelease(this);\n released_ = 1;\n allocatorAsked_ = 0;\n }\n\n virtual AllocatorBase* get_allocator()\n {\n allocatorAsked_++;\n return &lock_;\n }\n\n virtual void write(const void* buf, size_t count)\n {\n HASSERT(0);\n }\n\n virtual void async_write(const void* buf, size_t count, Notifiable* done)\n {\n released_ = 0;\n allocatorAsked_--;\n HASSERT(count == sizeof(struct can_frame));\n HASSERT(!frameToWrite_);\n done_ = done;\n LockHolder h(this);\n frameToWrite_ = static_cast<const struct can_frame*>(buf);\n g_executor.Add(this);\n }\n\n virtual void Run()\n {\n HASSERT(frameToWrite_);\n const struct can_frame* frame = nullptr;\n Notifiable* done = nullptr;\n uint8_t buf_num = FIRST_TX_OBJ;\n {\n LockHolder h(this);\n\n \/\/ Looks for a free tx buffer.\n while (buf_num < FIRST_RX_OBJ &&\n (!(freeTxBuffers_ & (1 << buf_num))))\n {\n buf_num++;\n }\n if (buf_num >= FIRST_RX_OBJ)\n {\n \/\/ Wait for ISR to wake us up.\n bufferFull_ = 1;\n return;\n }\n\n freeTxBuffers_ &= ~(1 << buf_num);\n\n \/\/ We decided to send the frame.\n frame = frameToWrite_;\n frameToWrite_ = nullptr; \/\/ no callbacks from ISR.\n done = done_;\n done_ = nullptr;\n }\n bufferFull_ = 0;\n CAN_MSG_OBJ msg_obj;\n msg_obj.msgobj = buf_num;\n msg_obj.mode_id = frame->can_id |\n (frame->can_rtr ? CAN_MSGOBJ_RTR : 0) |\n (frame->can_eff ? CAN_MSGOBJ_EXT : 0);\n msg_obj.mask = 0x0;\n msg_obj.dlc = frame->can_dlc;\n memcpy(msg_obj.data, frame->data, frame->can_dlc);\n (*rom)->pCAND->can_transmit(&msg_obj);\n\n \/\/ The incoming frame is no longer needed.\n done->Notify();\n released_ = 1;\n lock_.TypedReleaseBack(this);\n }\n\n void TxFinishedFromIsr(uint8_t buf_num)\n {\n HASSERT(!(freeTxBuffers_ & (1 << buf_num)));\n freeTxBuffers_ |= (1 << buf_num);\n if (frameToWrite_ && !g_executor.IsRunning(this))\n {\n g_executor.AddFromIsr(this);\n }\n }\n\nprivate:\n uint32_t freeTxBuffers_;\n const struct can_frame* frameToWrite_;\n Notifiable* done_;\n TypedAllocator<PipeMember> lock_;\n \/\/ 1 if a run method returned because it didn't find a free tx buffer.\n unsigned bufferFull_ : 1;\n unsigned released_ : 1;\n unsigned allocatorAsked_ : 4;\n};\n\nclass CanRxFlow : public AllocationResult\n{\npublic:\n CanRxFlow() : bufFull_(0), rxPending_(0), frameLost_(0)\n {\n \/* Configures msgobj NN to receive all extended frames. *\/\n CAN_MSG_OBJ msg_obj;\n msg_obj.msgobj = FIRST_RX_OBJ;\n msg_obj.mode_id = 0x000 | CAN_MSGOBJ_EXT;\n msg_obj.mask = 0x000;\n msg_obj.dlc = 0x000;\n (*rom)->pCAND->config_rxmsgobj(&msg_obj);\n }\n\n \/\/ Callback inside the ISR context. @param buf_num is the number of the\n \/\/ message object in the hardware.\n void isr(uint8_t buf_num)\n {\n if (rxPending_)\n {\n frameLost_ = 1;\n \/\/ Since rxPending is already 1, we'll let the executor deal with\n \/\/ copying the frame to the buffer.\n return;\n }\n else\n {\n rxPending_ = 1;\n }\n if (!bufFull_)\n {\n copy_hardware_frame(buf_num);\n g_executor.AddFromIsr(this);\n }\n }\n\n \/\/ Scheduled by the ISR when the frame has arrived.\n virtual void Run()\n {\n HASSERT(bufFull_);\n g_can_alloc.AllocateEntry(this);\n }\n\n virtual void AllocationCallback(QueueMember* entry)\n {\n HASSERT(bufFull_);\n CanPipeBuffer* buf = g_can_alloc.cast_result(entry);\n buf->Reset();\n memcpy(&buf->frame, &frame_, sizeof(frame_));\n buf->pipe_buffer.skipMember = g_tx_instance;\n g_pipe->SendBuffer(&buf->pipe_buffer);\n {\n portSET_INTERRUPT_MASK();\n bufFull_ = 0;\n if (rxPending_)\n {\n copy_hardware_frame(FIRST_RX_OBJ);\n \/\/ will crash if this is already added\n g_executor.Add(this);\n }\n portCLEAR_INTERRUPT_MASK();\n }\n }\n\nprivate:\n \/\/ Has to run either in ISR or in a critical section. Retrieves a hardware\n \/\/ buffer and copies it to the class-local can_frame.\n void copy_hardware_frame(uint8_t buf_num)\n {\n HASSERT(rxPending_);\n HASSERT(!bufFull_);\n CAN_MSG_OBJ msg_obj;\n \/* Determine which CAN message has been received *\/\n msg_obj.msgobj = buf_num;\n\n \/* Now load up the msg_obj structure with the CAN message *\/\n (*rom)->pCAND->can_receive(&msg_obj);\n\n \/\/ Here we need to be in a critical section; otherwise another CAN\n \/\/ interrupt might come in between these two calls.\n bufFull_ = 1;\n rxPending_ = 0;\n\n frame_.can_id = msg_obj.mode_id & ((1 << 29) - 1);\n \/\/ JMRI crashes the node here.\n \/\/ HASSERT(frame_.can_id & 0xfff);\n frame_.can_rtr = (msg_obj.mode_id & CAN_MSGOBJ_RTR) ? 1 : 0;\n frame_.can_eff = (msg_obj.mode_id & CAN_MSGOBJ_EXT) ? 1 : 0;\n frame_.can_err = 0;\n frame_.can_dlc = msg_obj.dlc;\n memcpy(frame_.data, msg_obj.data, msg_obj.dlc);\n }\n\n struct can_frame frame_;\n \/\/ 1 if the struct can_frame in here is full.\n unsigned bufFull_ : 1;\n \/\/ 1 if the can buffer in the hardware object is full.\n unsigned rxPending_ : 1;\n \/\/ 1 if we have lost a frame.\n unsigned frameLost_ : 1;\n};\n\n\/** CAN receive callback. Called by the ROM can driver in an ISR context.\n @param msg_obj_num the number of CAN buffer that has the new frame.\n*\/\nvoid CAN_rx(uint8_t msg_obj_num)\n{\n HASSERT(g_rx_instance);\n g_rx_instance->isr(msg_obj_num);\n \/\/ We always assume there is someone woken up. This is not nice.\n portYIELD();\n}\n\n\/** CAN transmit callback. Called by the ROM can driver in an ISR context.\n @param msg_obj_num the number of CAN buffer that finished transmission.\n*\/\nvoid CAN_tx(uint8_t msg_obj_num)\n{\n HASSERT(g_tx_instance);\n g_tx_instance->TxFinishedFromIsr(msg_obj_num);\n \/\/ We always assume there is someone woken up. This is not nice.\n portYIELD();\n}\n\n\/** CAN error callback. Called by the ROM can driver in an ISR context.\n @param error_info defines what kind of error occured on the bus.\n*\/\nvoid CAN_error(uint32_t error_info)\n{\n return;\n}\n\n\/** Function pointer table to pass to the ROM drivers with callbacks. *\/\nstatic const CAN_CALLBACKS callbacks = {CAN_rx, CAN_tx, CAN_error, NULL,\n NULL, NULL, NULL, NULL, };\n\n\/** Clock initialization constants for 125 kbaud *\/\nconst uint32_t ClkInitTable125[2] = {0x00000000UL, \/\/ CANCLKDIV\n 0x00001C57UL \/\/ CAN_BTR\n};\n\n\/** Clock initialization constants for 250 kbaud *\/\nstatic const uint32_t ClkInitTable250[2] = {0x00000000UL, \/\/ CANCLKDIV\n 0x00001C4BUL \/\/ CAN_BTR\n};\n\nvoid CreateCanDriver(Pipe* parent)\n{\n \/* Initialize the CAN controller *\/\n (*rom)->pCAND->init_can((uint32_t*)&ClkInitTable250[0], 1);\n \/* Configure the CAN callback functions *\/\n (*rom)->pCAND->config_calb((CAN_CALLBACKS*)&callbacks);\n\n g_pipe = parent;\n g_rx_instance = new CanRxFlow();\n g_tx_instance = new CanPipeMember();\n parent->RegisterMember(g_tx_instance);\n\n \/* Enable the CAN Interrupt *\/\n NVIC_SetPriority(CAN_IRQn, 1);\n NVIC_EnableIRQ(CAN_IRQn);\n}\n\n} \/\/ namespace lpc11cxx\n\nextern \"C\" {\n\/** Overrides the system's weak interrupt handler and calls the builtin ROM\n * interrupt handler. *\/\nvoid CAN_IRQHandler(void)\n{\n (*rom)->pCAND->isr();\n}\n}\n\n#else\n#error You need to define TARGET_LPC11Cxx if you want to compiple its rom driver.\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------- -*- Mode: C++ -*-\n\/\/ $Id$\n\/\/\n\/\/ Created 2013\/06\/08\n\/\/ Author: Mike Ovsiannikov\n\/\/\n\/\/ Copyright 2013 Quantcast Corp.\n\/\/\n\/\/ This file is part of Kosmos File System (KFS).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Kerberos 5 client side authentication implementation.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \"KrbClient.h\"\n\n\n#include <krb5\/krb5.h>\n\n#include <string.h>\n#include <string>\n#include <algorithm>\n\nnamespace KFS\n{\n\nusing std::string;\nusing std::max;\n\nclass KrbClient::Impl\n{\npublic:\n Impl()\n : mServiceHost(),\n mCtx(),\n mAuthCtx(),\n mErrCode(0),\n mOutBuf(),\n mCreds(),\n mServerPtr(0),\n mKeyBlockPtr(0),\n mInitedFlag(false),\n mServiceName(),\n mErrorMsg()\n {\n mOutBuf.data = 0;\n mOutBuf.length = 0;\n }\n ~Impl()\n {}\n const char* Init(\n const char* inServiceHostNamePtr,\n const char* inServeiceNamePtr)\n {\n CleanupSelf();\n mServiceHost = inServiceHostNamePtr ? inServiceHostNamePtr : \"\";\n mServiceName = inServeiceNamePtr ? inServeiceNamePtr : \"\";\n mErrCode = 0;\n mErrorMsg.clear();\n InitSelf();\n if (mErrCode) {\n mErrorMsg = ErrToStr(mErrCode);\n return mErrorMsg.c_str();\n }\n return 0;\n }\n const char* Cleanup()\n {\n mErrorMsg.clear();\n mErrCode = CleanupSelf();\n if (mErrCode) {\n return ErrStr();\n }\n return 0;\n }\n const char* Request(\n const char*& outDataPtr,\n int& outDataLen)\n {\n if (! mInitedFlag) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not initialized yet, invoke KrbClient::Init\";\n return mErrorMsg.c_str();\n }\n CleanupAuth();\n krb5_free_data_contents(mCtx, &mOutBuf);\n krb5_ccache theCache = 0;\n\tif ((mErrCode = krb5_cc_default(mCtx, &theCache)) != 0) {\n return ErrStr();\n }\n mCreds.server = mServerPtr;\n\tif ((mErrCode = krb5_cc_get_principal(\n mCtx, theCache, &mCreds.client)) != 0) {\n return ErrStr();\n }\n krb5_creds* theCreds = 0;\n\tif ((mErrCode = krb5_get_credentials(\n mCtx, 0, theCache, &mCreds, &theCreds)) != 0) {\n return ErrStr();\n }\n krb5_data theAppData = { 0 };\n theAppData.data = 0;\n theAppData.length = 0;\n if ((mErrCode = krb5_mk_req_extended(\n mCtx,\n &mAuthCtx,\n AP_OPTS_MUTUAL_REQUIRED,\n &theAppData,\n theCreds,\n &mOutBuf)) != 0) {\n return ErrStr();\n }\n outDataPtr = (const char*)mOutBuf.data;\n outDataLen = (int)mOutBuf.length;\n return 0;\n }\n const char* Reply(\n const char* inReplyPtr,\n int inReplyLen,\n const char*& outSessionKeyPtr,\n int& outSessionKeyLen)\n {\n if (! mInitedFlag) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not initialized yet, invoke KrbClient::Init\";\n return mErrorMsg.c_str();\n }\n if (mOutBuf.length <= 0 || ! mOutBuf.data) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not ready to process reply, invoke KrbClient::Request\";\n return mErrorMsg.c_str();\n }\n if (mKeyBlockPtr) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"possible extraneous invocation of KrbClient::Reply\";\n return mErrorMsg.c_str();\n }\n krb5_data theData = { 0 };\n theData.length = max(0, inReplyLen);\n theData.data = const_cast<char*>(inReplyPtr);\n krb5_ap_rep_enc_part* theReplPtr = 0;\n if ((mErrCode = krb5_rd_rep(\n mCtx,\n mAuthCtx,\n &theData,\n &theReplPtr))) {\n return ErrStr();\n }\n if ((mErrCode = krb5_auth_con_getkey(mCtx, mAuthCtx, &mKeyBlockPtr))) {\n return ErrStr();\n }\n krb5_free_ap_rep_enc_part(mCtx, theReplPtr);\n krb5_free_data_contents(mCtx, &mOutBuf);\n outSessionKeyPtr =\n reinterpret_cast<const char*>(mKeyBlockPtr->contents);\n outSessionKeyLen = (int)mKeyBlockPtr->length;\n return 0;\n }\n int GetErrorCode() const\n {\n return mErrCode;\n }\nprivate:\n string mServiceHost;\n krb5_context mCtx;\n krb5_auth_context mAuthCtx;\n krb5_error_code mErrCode;\n krb5_data mOutBuf;\n krb5_creds mCreds;\n krb5_principal mServerPtr;\n krb5_keyblock* mKeyBlockPtr;\n bool mInitedFlag;\n string mServiceName;\n string mErrorMsg;\n\n void InitSelf()\n {\n mErrCode = krb5_init_context(&mCtx);\n if (mErrCode) {\n return;\n }\n mInitedFlag = true;\n memset(&mCreds, 0, sizeof(mCreds));\n\tif ((mErrCode = krb5_sname_to_principal(\n mCtx,\n mServiceHost.c_str(),\n mServiceName.c_str(),\n KRB5_NT_UNKNOWN, \/\/ KRB5_NT_SRV_HST,\n &mServerPtr\n ))) {\n return;\n }\n }\n krb5_error_code CleanupSelf()\n {\n if (! mInitedFlag) {\n return 0;\n }\n krb5_error_code theErr = CleanupAuth();\n mInitedFlag = false;\n memset(&mCreds, 0, sizeof(mCreds));\n\tif (mServerPtr) {\n krb5_free_principal(mCtx, mServerPtr);\n mServerPtr = 0;\n }\n krb5_free_context(mCtx);\n return theErr;\n }\n krb5_error_code CleanupAuth()\n {\n if (! mInitedFlag) {\n return 0;\n }\n\tif (mCreds.client) {\n krb5_free_principal(mCtx, mCreds.client);\n mCreds.client = 0;\n }\n if (mKeyBlockPtr) {\n krb5_free_keyblock(mCtx, mKeyBlockPtr);\n mKeyBlockPtr = 0;\n }\n krb5_free_data_contents(mCtx, &mOutBuf);\n if (! mAuthCtx) {\n return 0;\n }\n const krb5_error_code theErr = krb5_auth_con_free(mCtx, mAuthCtx);\n memset(&mCreds, 0, sizeof(mCreds));\n mAuthCtx = 0;\n return theErr;\n }\n const char* ErrStr()\n {\n mErrorMsg = ErrToStr(mErrCode);\n return mErrorMsg.c_str();\n }\n string ErrToStr(\n krb5_error_code inErrCode) const\n {\n if (! inErrCode) {\n return string();\n }\n if ( ! mCtx) {\n return string(\"no kerberos context\");\n }\n const char* const theMsgPtr = krb5_get_error_message(mCtx, inErrCode);\n return string(theMsgPtr);\n }\n\nprivate:\n Impl(\n const Impl& inImpl);\n Impl& operator=(\n const Impl& inImpl);\n};\n\nKrbClient::KrbClient()\n : mImpl(*(new Impl()))\n{\n}\n\nKrbClient::~KrbClient()\n{\n delete &mImpl;\n}\n\n const char*\nKrbClient::Init(\n const char* inServiceHostNamePtr,\n const char* inServeiceNamePtr)\n{\n return mImpl.Init(inServiceHostNamePtr, inServeiceNamePtr);\n}\n\n const char*\nKrbClient::Cleanup()\n{\n return mImpl.Cleanup();\n}\n\n const char*\nKrbClient::Request(\n const char*& outDataPtr,\n int& outDataLen)\n{\n return mImpl.Request(outDataPtr, outDataLen);\n}\n\n const char*\nKrbClient::Reply(\n const char* inReplyPtr,\n int inReplyLen,\n const char*& outSessionKeyPtr,\n int& outSessionKeyLen)\n{\n return mImpl.Reply(\n inReplyPtr, inReplyLen, outSessionKeyPtr, outSessionKeyLen);\n}\n\n int\nKrbClient::GetErrorCode() const\n{\n return mImpl.GetErrorCode();\n}\n\n}\n<commit_msg>Qfs kerberos lib: fix memory leaks in KrbClient::Request().<commit_after>\/\/---------------------------------------------------------- -*- Mode: C++ -*-\n\/\/ $Id$\n\/\/\n\/\/ Created 2013\/06\/08\n\/\/ Author: Mike Ovsiannikov\n\/\/\n\/\/ Copyright 2013 Quantcast Corp.\n\/\/\n\/\/ This file is part of Kosmos File System (KFS).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Kerberos 5 client side authentication implementation.\n\/\/\n\/\/----------------------------------------------------------------------------\n\n#include \"KrbClient.h\"\n\n\n#include <krb5\/krb5.h>\n\n#include <string.h>\n#include <string>\n#include <algorithm>\n\nnamespace KFS\n{\n\nusing std::string;\nusing std::max;\n\nclass KrbClient::Impl\n{\npublic:\n Impl()\n : mServiceHost(),\n mCtx(),\n mAuthCtx(),\n mErrCode(0),\n mOutBuf(),\n mCreds(),\n mServerPtr(0),\n mKeyBlockPtr(0),\n mInitedFlag(false),\n mServiceName(),\n mErrorMsg()\n {\n mOutBuf.data = 0;\n mOutBuf.length = 0;\n }\n ~Impl()\n {}\n const char* Init(\n const char* inServiceHostNamePtr,\n const char* inServeiceNamePtr)\n {\n CleanupSelf();\n mServiceHost = inServiceHostNamePtr ? inServiceHostNamePtr : \"\";\n mServiceName = inServeiceNamePtr ? inServeiceNamePtr : \"\";\n mErrCode = 0;\n mErrorMsg.clear();\n InitSelf();\n if (mErrCode) {\n mErrorMsg = ErrToStr(mErrCode);\n return mErrorMsg.c_str();\n }\n return 0;\n }\n const char* Cleanup()\n {\n mErrorMsg.clear();\n mErrCode = CleanupSelf();\n if (mErrCode) {\n return ErrStr();\n }\n return 0;\n }\n const char* Request(\n const char*& outDataPtr,\n int& outDataLen)\n {\n if (! mInitedFlag) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not initialized yet, invoke KrbClient::Init\";\n return mErrorMsg.c_str();\n }\n CleanupAuth();\n krb5_free_data_contents(mCtx, &mOutBuf);\n krb5_ccache theCachePtr = 0;\n\tif ((mErrCode = krb5_cc_default(mCtx, &theCachePtr)) != 0) {\n return ErrStr();\n }\n mCreds.server = mServerPtr;\n\tif ((mErrCode = krb5_cc_get_principal(\n mCtx, theCachePtr, &mCreds.client)) != 0) {\n krb5_cc_close(mCtx, theCachePtr);\n return ErrStr();\n }\n krb5_creds* theCredsPtr = 0;\n\tif ((mErrCode = krb5_get_credentials(\n mCtx, 0, theCachePtr, &mCreds, &theCredsPtr)) != 0) {\n krb5_cc_close(mCtx, theCachePtr);\n return ErrStr();\n }\n if ((mErrCode = krb5_cc_close(mCtx, theCachePtr))) {\n krb5_free_creds(mCtx, theCredsPtr);\n return ErrStr();\n }\n krb5_data theAppData = { 0 };\n theAppData.data = 0;\n theAppData.length = 0;\n mErrCode = krb5_mk_req_extended(\n mCtx,\n &mAuthCtx,\n AP_OPTS_MUTUAL_REQUIRED,\n &theAppData,\n theCredsPtr,\n &mOutBuf\n );\n krb5_free_creds(mCtx, theCredsPtr);\n if (mErrCode != 0) {\n return ErrStr();\n }\n outDataPtr = (const char*)mOutBuf.data;\n outDataLen = (int)mOutBuf.length;\n return 0;\n }\n const char* Reply(\n const char* inReplyPtr,\n int inReplyLen,\n const char*& outSessionKeyPtr,\n int& outSessionKeyLen)\n {\n if (! mInitedFlag) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not initialized yet, invoke KrbClient::Init\";\n return mErrorMsg.c_str();\n }\n if (mOutBuf.length <= 0 || ! mOutBuf.data) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"not ready to process reply, invoke KrbClient::Request\";\n return mErrorMsg.c_str();\n }\n if (mKeyBlockPtr) {\n mErrCode = KRB5_CONFIG_BADFORMAT;\n mErrorMsg = \"possible extraneous invocation of KrbClient::Reply\";\n return mErrorMsg.c_str();\n }\n krb5_data theData = { 0 };\n theData.length = max(0, inReplyLen);\n theData.data = const_cast<char*>(inReplyPtr);\n krb5_ap_rep_enc_part* theReplPtr = 0;\n if ((mErrCode = krb5_rd_rep(\n mCtx,\n mAuthCtx,\n &theData,\n &theReplPtr))) {\n return ErrStr();\n }\n if ((mErrCode = krb5_auth_con_getkey(mCtx, mAuthCtx, &mKeyBlockPtr))) {\n return ErrStr();\n }\n krb5_free_ap_rep_enc_part(mCtx, theReplPtr);\n krb5_free_data_contents(mCtx, &mOutBuf);\n outSessionKeyPtr =\n reinterpret_cast<const char*>(mKeyBlockPtr->contents);\n outSessionKeyLen = (int)mKeyBlockPtr->length;\n return 0;\n }\n int GetErrorCode() const\n {\n return mErrCode;\n }\nprivate:\n string mServiceHost;\n krb5_context mCtx;\n krb5_auth_context mAuthCtx;\n krb5_error_code mErrCode;\n krb5_data mOutBuf;\n krb5_creds mCreds;\n krb5_principal mServerPtr;\n krb5_keyblock* mKeyBlockPtr;\n bool mInitedFlag;\n string mServiceName;\n string mErrorMsg;\n\n void InitSelf()\n {\n mErrCode = krb5_init_context(&mCtx);\n if (mErrCode) {\n return;\n }\n mInitedFlag = true;\n memset(&mCreds, 0, sizeof(mCreds));\n\tif ((mErrCode = krb5_sname_to_principal(\n mCtx,\n mServiceHost.c_str(),\n mServiceName.c_str(),\n KRB5_NT_UNKNOWN, \/\/ KRB5_NT_SRV_HST,\n &mServerPtr\n ))) {\n return;\n }\n }\n krb5_error_code CleanupSelf()\n {\n if (! mInitedFlag) {\n return 0;\n }\n krb5_error_code theErr = CleanupAuth();\n mInitedFlag = false;\n memset(&mCreds, 0, sizeof(mCreds));\n\tif (mServerPtr) {\n krb5_free_principal(mCtx, mServerPtr);\n mServerPtr = 0;\n }\n krb5_free_context(mCtx);\n return theErr;\n }\n krb5_error_code CleanupAuth()\n {\n if (! mInitedFlag) {\n return 0;\n }\n\tif (mCreds.client) {\n krb5_free_principal(mCtx, mCreds.client);\n mCreds.client = 0;\n }\n if (mKeyBlockPtr) {\n krb5_free_keyblock(mCtx, mKeyBlockPtr);\n mKeyBlockPtr = 0;\n }\n krb5_free_data_contents(mCtx, &mOutBuf);\n if (! mAuthCtx) {\n return 0;\n }\n const krb5_error_code theErr = krb5_auth_con_free(mCtx, mAuthCtx);\n memset(&mCreds, 0, sizeof(mCreds));\n mAuthCtx = 0;\n return theErr;\n }\n const char* ErrStr()\n {\n mErrorMsg = ErrToStr(mErrCode);\n return mErrorMsg.c_str();\n }\n string ErrToStr(\n krb5_error_code inErrCode) const\n {\n if (! inErrCode) {\n return string();\n }\n if ( ! mCtx) {\n return string(\"no kerberos context\");\n }\n const char* const theMsgPtr = krb5_get_error_message(mCtx, inErrCode);\n return string(theMsgPtr);\n }\n\nprivate:\n Impl(\n const Impl& inImpl);\n Impl& operator=(\n const Impl& inImpl);\n};\n\nKrbClient::KrbClient()\n : mImpl(*(new Impl()))\n{\n}\n\nKrbClient::~KrbClient()\n{\n delete &mImpl;\n}\n\n const char*\nKrbClient::Init(\n const char* inServiceHostNamePtr,\n const char* inServeiceNamePtr)\n{\n return mImpl.Init(inServiceHostNamePtr, inServeiceNamePtr);\n}\n\n const char*\nKrbClient::Cleanup()\n{\n return mImpl.Cleanup();\n}\n\n const char*\nKrbClient::Request(\n const char*& outDataPtr,\n int& outDataLen)\n{\n return mImpl.Request(outDataPtr, outDataLen);\n}\n\n const char*\nKrbClient::Reply(\n const char* inReplyPtr,\n int inReplyLen,\n const char*& outSessionKeyPtr,\n int& outSessionKeyLen)\n{\n return mImpl.Reply(\n inReplyPtr, inReplyLen, outSessionKeyPtr, outSessionKeyLen);\n}\n\n int\nKrbClient::GetErrorCode() const\n{\n return mImpl.GetErrorCode();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tokrecv.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: np $ $Date: 2002-03-08 14:45:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef DSAPI_TOKRECV_HXX\n#define DSAPI_TOKRECV_HXX\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\nnamespace csi\n{\nnamespace dsapi\n{\n\n\nclass Token;\n\/**\n@descr\n*\/\nclass Token_Receiver\n{\n public:\n virtual ~Token_Receiver() {}\n virtual void Receive(\n DYN Token & let_drToken ) = 0;\n};\n\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n#endif\n\n<commit_msg>INTEGRATION: CWS adc10 (1.1.1.1.132); FILE MERGED 2005\/01\/12 13:14:31 np 1.1.1.1.132.1: #i31025# Convenient error log file.<commit_after>\/*************************************************************************\n *\n * $RCSfile: tokrecv.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2005-01-27 11:30:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef DSAPI_TOKRECV_HXX\n#define DSAPI_TOKRECV_HXX\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n \/\/ PARAMETERS\n\nnamespace csi\n{\nnamespace dsapi\n{\n\n\nclass Token;\n\/**\n@descr\n*\/\nclass Token_Receiver\n{\n public:\n virtual ~Token_Receiver() {}\n virtual void Receive(\n DYN Token & let_drToken ) = 0;\n virtual void Increment_CurLine() = 0;\n};\n\n\n} \/\/ namespace dsapi\n} \/\/ namespace csi\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ AmstradCPC.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 30\/07\/2017.\n\/\/ Copyright © 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"AmstradCPC.hpp\"\n\n#include \"..\/..\/Processors\/Z80\/Z80.hpp\"\n#include \"..\/..\/Components\/AY38910\/AY38910.hpp\"\n#include \"..\/..\/Components\/6845\/CRTC6845.hpp\"\n\nusing namespace AmstradCPC;\n\nstruct CRTCBusHandler {\n\tpublic:\n\t\tCRTCBusHandler(uint8_t *ram) :\n\t\t\tcycles_(0),\n\t\t\twas_enabled_(false),\n\t\t\twas_sync_(false),\n\t\t\tpixel_data_(nullptr),\n\t\t\tpixel_pointer_(nullptr),\n\t\t\tram_(ram) {}\n\n\t\tinline void perform_bus_cycle(const Motorola::CRTC::BusState &state) {\n\t\t\tcycles_++;\n\n\t\t\tbool is_sync = state.hsync || state.vsync;\n\t\t\t\/\/ collect some more pixels if output is ongoing\n\t\t\tif(!is_sync && state.display_enable) {\n\t\t\t\tif(!pixel_data_) {\n\t\t\t\t\tpixel_pointer_ = pixel_data_ = crt_->allocate_write_area(320);\n\t\t\t\t}\n\t\t\t\tif(pixel_pointer_) {\n\t\t\t\t\t\/\/ the CPC shuffles output lines as:\n\t\t\t\t\t\/\/\tMA12 MA11\tRA2 RA1 RA0\t\tMA9 MA8 MA7 MA6 MA5 MA4 MA3 MA2 MA1 MA0\t\tCCLK\n\t\t\t\t\tuint16_t address =\n\t\t\t\t\t\t(uint16_t)(\n\t\t\t\t\t\t\t((state.refresh_address & 0x3FF) << 1) |\n\t\t\t\t\t\t\t((state.row_address & 7) << 11) |\n\t\t\t\t\t\t\t((state.refresh_address & 0x1800) << 3)\n\t\t\t\t\t\t);\n\n\t\t\t\t\t*pixel_pointer_++ = ram_[address];\n\n\t\t\t\t\t\/\/ flush the current buffer if full\n\t\t\t\t\tif(pixel_pointer_ == pixel_data_ + 320) {\n\t\t\t\t\t\tcrt_->output_data(320, 16);\n\t\t\t\t\t\tpixel_pointer_ = pixel_data_ = nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ if a transition between sync\/border\/pixels just occurred, announce it\n\t\t\tif(state.display_enable != was_enabled_ || is_sync != was_sync_) {\n\t\t\t\tif(was_sync_) {\n\t\t\t\t\tcrt_->output_sync((unsigned int)(cycles_ * 16));\n\t\t\t\t} else {\n\t\t\t\t\tif(was_enabled_) {\n\t\t\t\t\t\tcrt_->output_data((unsigned int)(cycles_ * 16), 16);\n\t\t\t\t\t\tpixel_pointer_ = pixel_data_ = nullptr;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tuint8_t *colour_pointer = (uint8_t *)crt_->allocate_write_area(1);\n\t\t\t\t\t\tif(colour_pointer) *colour_pointer = 0x00;\n\t\t\t\t\t\tcrt_->output_level((unsigned int)(cycles_ * 16));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcycles_ = 0;\n\t\t\t\twas_sync_ = is_sync;\n\t\t\t\twas_enabled_ = state.display_enable;\n\t\t\t}\n\t\t}\n\n\t\tvoid setup_output(float aspect_ratio) {\n\t\t\tcrt_.reset(new Outputs::CRT::CRT(1024, 16, Outputs::CRT::DisplayType::PAL50, 1));\n\t\t\tcrt_->set_rgb_sampling_function(\n\t\t\t\t\"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)\"\n\t\t\t\t\"{\"\n\t\t\t\t\t\"return vec3(float(texture(texID, coordinate).r) \/ 255.0);\"\n\t\t\t\t\"}\");\n\t\t}\n\n\t\tvoid close_output() {\n\t\t\tcrt_.reset();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::CRT::CRT> get_crt() {\n\t\t\treturn crt_;\n\t\t}\n\n\tprivate:\n\t\tint cycles_;\n\t\tbool was_enabled_, was_sync_;\n\t\tstd::shared_ptr<Outputs::CRT::CRT> crt_;\n\t\tuint8_t *pixel_data_, *pixel_pointer_;\n\n\t\tuint8_t *ram_;\n};\n\nclass ConcreteMachine:\n\tpublic CPU::Z80::Processor<ConcreteMachine>,\n\tpublic Machine {\n\tpublic:\n\t\tConcreteMachine() :\n\t\t\tcrtc_counter_(HalfCycles(4)),\t\/\/ This starts the CRTC exactly out of phase with the memory accesses\n\t\t\tcrtc_(crtc_bus_handler_),\n\t\t\tcrtc_bus_handler_(ram_) {\n\t\t\t\/\/ primary clock is 4Mhz\n\t\t\tset_clock_rate(4000000);\n\t\t}\n\n\t\tinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {\n\t\t\t\/\/ Amstrad CPC timing scheme: assert WAIT for three out of four cycles\n\t\t\tclock_offset_ = (clock_offset_ + cycle.length) & HalfCycles(7);\n\t\t\tset_wait_line(clock_offset_ >= HalfCycles(2));\n\n\t\t\t\/\/ Update the CRTC once every eight half cycles; aiming for half-cycle 4 as\n\t\t\t\/\/ per the initial seed to the crtc_counter_, but any time in the final four\n\t\t\t\/\/ will do as it's safe to conclude that nobody else has touched video RAM\n\t\t\t\/\/ during that whole window\n\t\t\tcrtc_counter_ += cycle.length;\n\t\t\tint crtc_cycles = crtc_counter_.divide(HalfCycles(8)).as_int();\n\t\t\tif(crtc_cycles) crtc_.run_for(Cycles(1));\n\n\t\t\t\/\/ Stop now if no action is strictly required.\n\t\t\tif(!cycle.is_terminal()) return HalfCycles(0);\n\n\t\t\tuint16_t address = cycle.address ? *cycle.address : 0x0000;\n\t\t\tswitch(cycle.operation) {\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::ReadOpcode:\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Read:\n\t\t\t\t\t*cycle.value = read_pointers_[address >> 14][address & 16383];\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Write:\n\t\t\t\t\twrite_pointers_[address >> 14][address & 16383] = *cycle.value;\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Output:\n\t\t\t\t\t\/\/ Check for a gate array access.\n\t\t\t\t\tif((address & 0xc000) == 0x4000) {\n\t\t\t\t\t\tswitch(*cycle.value >> 6) {\n\t\t\t\t\t\t\tcase 0: printf(\"Select pen %02x\\n\", *cycle.value & 0x1f);\t\tbreak;\n\t\t\t\t\t\t\tcase 1: printf(\"Select colour %02x\\n\", *cycle.value & 0x1f);\tbreak;\n\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\tprintf(\"Set mode %d, other flags %02x\\n\", *cycle.value & 3, (*cycle.value >> 2)&7);\n\t\t\t\t\t\t\t\tread_pointers_[0] = (*cycle.value & 4) ? &ram_[0] : os_.data();\n\t\t\t\t\t\t\t\tread_pointers_[3] = (*cycle.value & 8) ? &ram_[49152] : basic_.data();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 3: printf(\"RAM paging?\\n\"); break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a CRTC access\n\t\t\t\t\tif(!(address & 0x4000)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tcrtc_.select_register(*cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 1:\tcrtc_.set_register(*cycle.value);\t\tbreak;\n\t\t\t\t\t\t\tcase 2: case 3:\tprintf(\"Illegal CRTC write?\\n\");\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a PIO access\n\t\t\t\t\tif(!(address & 0x800)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tprintf(\"PSG data: %d\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 1:\tprintf(\"Vsync, etc: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 2:\tprintf(\"Key row, etc: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 3:\tprintf(\"PIO control: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Input:\n\t\t\t\t\t\/\/ Check for a CRTC access\n\t\t\t\t\tif(!(address & 0x4000)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tcase 1: printf(\"Illegal CRTC read?\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 2: *cycle.value = crtc_.get_status();\t\tbreak;\n\t\t\t\t\t\t\tcase 3:\t*cycle.value = crtc_.get_register();\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a PIO access\n\t\t\t\t\tif(!(address & 0x800)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tprintf(\"[In] PSG data\\n\");\t\tbreak;\n\t\t\t\t\t\t\tcase 1:\tprintf(\"[In] Vsync, etc\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 2:\tprintf(\"[In] Key row, etc\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 3:\tprintf(\"[In] PIO control\\n\");\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t*cycle.value = 0xff;\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Interrupt:\n\t\t\t\t\t*cycle.value = 0xff;\n\t\t\t\tbreak;\n\n\t\t\t\tdefault: break;\n\t\t\t}\n\n\t\t\treturn HalfCycles(0);\n\t\t}\n\n\t\tvoid flush() {}\n\n\t\tvoid setup_output(float aspect_ratio) {\n\t\t\tcrtc_bus_handler_.setup_output(aspect_ratio);\n\t\t}\n\n\t\tvoid close_output() {\n\t\t\tcrtc_bus_handler_.close_output();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::CRT::CRT> get_crt() {\n\t\t\treturn crtc_bus_handler_.get_crt();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::Speaker> get_speaker() {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tvoid run_for(const Cycles cycles) {\n\t\t\tCPU::Z80::Processor<ConcreteMachine>::run_for(cycles);\n\t\t}\n\n\t\tvoid configure_as_target(const StaticAnalyser::Target &target) {\n\t\t\t\/\/ Establish reset memory map as per machine model (or, for now, as a hard-wired 464)\n\t\t\tread_pointers_[0] = os_.data();\n\t\t\tread_pointers_[1] = &ram_[16384];\n\t\t\tread_pointers_[2] = &ram_[32768];\n\t\t\tread_pointers_[3] = basic_.data();\n\n\t\t\twrite_pointers_[0] = &ram_[0];\n\t\t\twrite_pointers_[1] = &ram_[16384];\n\t\t\twrite_pointers_[2] = &ram_[32768];\n\t\t\twrite_pointers_[3] = &ram_[49152];\n\t\t}\n\n\t\tvoid set_rom(ROMType type, std::vector<uint8_t> data) {\n\t\t\t\/\/ Keep only the two ROMs that are currently of interest.\n\t\t\tswitch(type) {\n\t\t\t\tcase ROMType::OS464:\t\tos_ = data;\t\tbreak;\n\t\t\t\tcase ROMType::BASIC464:\t\tbasic_ = data;\tbreak;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tCRTCBusHandler crtc_bus_handler_;\n\t\tMotorola::CRTC::CRTC6845<CRTCBusHandler> crtc_;\n\n\t\tHalfCycles clock_offset_;\n\t\tHalfCycles crtc_counter_;\n\n\t\tuint8_t ram_[65536];\n\t\tstd::vector<uint8_t> os_, basic_;\n\n\t\tuint8_t *read_pointers_[4];\n\t\tuint8_t *write_pointers_[4];\n};\n\nMachine *Machine::AmstradCPC() {\n\treturn new ConcreteMachine;\n}\n<commit_msg>Fixed slightly: the CPC wiki has a typo. It's 12 and 13 that move up to 14 and 15.<commit_after>\/\/\n\/\/ AmstradCPC.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 30\/07\/2017.\n\/\/ Copyright © 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"AmstradCPC.hpp\"\n\n#include \"..\/..\/Processors\/Z80\/Z80.hpp\"\n#include \"..\/..\/Components\/AY38910\/AY38910.hpp\"\n#include \"..\/..\/Components\/6845\/CRTC6845.hpp\"\n\nusing namespace AmstradCPC;\n\nstruct CRTCBusHandler {\n\tpublic:\n\t\tCRTCBusHandler(uint8_t *ram) :\n\t\t\tcycles_(0),\n\t\t\twas_enabled_(false),\n\t\t\twas_sync_(false),\n\t\t\tpixel_data_(nullptr),\n\t\t\tpixel_pointer_(nullptr),\n\t\t\tram_(ram) {}\n\n\t\tinline void perform_bus_cycle(const Motorola::CRTC::BusState &state) {\n\t\t\tcycles_++;\n\n\t\t\tbool is_sync = state.hsync || state.vsync;\n\t\t\t\/\/ collect some more pixels if output is ongoing\n\t\t\tif(!is_sync && state.display_enable) {\n\t\t\t\tif(!pixel_data_) {\n\t\t\t\t\tpixel_pointer_ = pixel_data_ = crt_->allocate_write_area(320);\n\t\t\t\t}\n\t\t\t\tif(pixel_pointer_) {\n\t\t\t\t\t\/\/ the CPC shuffles output lines as:\n\t\t\t\t\t\/\/\tMA13 MA12\tRA2 RA1 RA0\t\tMA9 MA8 MA7 MA6 MA5 MA4 MA3 MA2 MA1 MA0\t\tCCLK\n\t\t\t\t\tuint16_t address =\n\t\t\t\t\t\t(uint16_t)(\n\t\t\t\t\t\t\t((state.refresh_address & 0x3ff) << 1) |\n\t\t\t\t\t\t\t((state.row_address & 0x7) << 11) |\n\t\t\t\t\t\t\t((state.refresh_address & 0x3000) << 2)\n\t\t\t\t\t\t);\n\n\t\t\t\t\t*pixel_pointer_++ = ram_[address];\n\n\t\t\t\t\t\/\/ flush the current buffer if full\n\t\t\t\t\tif(pixel_pointer_ == pixel_data_ + 320) {\n\t\t\t\t\t\tcrt_->output_data(320, 16);\n\t\t\t\t\t\tpixel_pointer_ = pixel_data_ = nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ if a transition between sync\/border\/pixels just occurred, announce it\n\t\t\tif(state.display_enable != was_enabled_ || is_sync != was_sync_) {\n\t\t\t\tif(was_sync_) {\n\t\t\t\t\tcrt_->output_sync((unsigned int)(cycles_ * 16));\n\t\t\t\t} else {\n\t\t\t\t\tif(was_enabled_) {\n\t\t\t\t\t\tcrt_->output_data((unsigned int)(cycles_ * 16), 16);\n\t\t\t\t\t\tpixel_pointer_ = pixel_data_ = nullptr;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tuint8_t *colour_pointer = (uint8_t *)crt_->allocate_write_area(1);\n\t\t\t\t\t\tif(colour_pointer) *colour_pointer = 0x00;\n\t\t\t\t\t\tcrt_->output_level((unsigned int)(cycles_ * 16));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcycles_ = 0;\n\t\t\t\twas_sync_ = is_sync;\n\t\t\t\twas_enabled_ = state.display_enable;\n\t\t\t}\n\t\t}\n\n\t\tvoid setup_output(float aspect_ratio) {\n\t\t\tcrt_.reset(new Outputs::CRT::CRT(1024, 16, Outputs::CRT::DisplayType::PAL50, 1));\n\t\t\tcrt_->set_rgb_sampling_function(\n\t\t\t\t\"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)\"\n\t\t\t\t\"{\"\n\t\t\t\t\t\"return vec3(float(texture(texID, coordinate).r) \/ 255.0);\"\n\t\t\t\t\"}\");\n\t\t}\n\n\t\tvoid close_output() {\n\t\t\tcrt_.reset();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::CRT::CRT> get_crt() {\n\t\t\treturn crt_;\n\t\t}\n\n\tprivate:\n\t\tint cycles_;\n\t\tbool was_enabled_, was_sync_;\n\t\tstd::shared_ptr<Outputs::CRT::CRT> crt_;\n\t\tuint8_t *pixel_data_, *pixel_pointer_;\n\n\t\tuint8_t *ram_;\n};\n\nclass ConcreteMachine:\n\tpublic CPU::Z80::Processor<ConcreteMachine>,\n\tpublic Machine {\n\tpublic:\n\t\tConcreteMachine() :\n\t\t\tcrtc_counter_(HalfCycles(4)),\t\/\/ This starts the CRTC exactly out of phase with the memory accesses\n\t\t\tcrtc_(crtc_bus_handler_),\n\t\t\tcrtc_bus_handler_(ram_) {\n\t\t\t\/\/ primary clock is 4Mhz\n\t\t\tset_clock_rate(4000000);\n\t\t}\n\n\t\tinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {\n\t\t\t\/\/ Amstrad CPC timing scheme: assert WAIT for three out of four cycles\n\t\t\tclock_offset_ = (clock_offset_ + cycle.length) & HalfCycles(7);\n\t\t\tset_wait_line(clock_offset_ >= HalfCycles(2));\n\n\t\t\t\/\/ Update the CRTC once every eight half cycles; aiming for half-cycle 4 as\n\t\t\t\/\/ per the initial seed to the crtc_counter_, but any time in the final four\n\t\t\t\/\/ will do as it's safe to conclude that nobody else has touched video RAM\n\t\t\t\/\/ during that whole window\n\t\t\tcrtc_counter_ += cycle.length;\n\t\t\tint crtc_cycles = crtc_counter_.divide(HalfCycles(8)).as_int();\n\t\t\tif(crtc_cycles) crtc_.run_for(Cycles(1));\n\n\t\t\t\/\/ Stop now if no action is strictly required.\n\t\t\tif(!cycle.is_terminal()) return HalfCycles(0);\n\n\t\t\tuint16_t address = cycle.address ? *cycle.address : 0x0000;\n\t\t\tswitch(cycle.operation) {\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::ReadOpcode:\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Read:\n\t\t\t\t\t*cycle.value = read_pointers_[address >> 14][address & 16383];\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Write:\n\t\t\t\t\twrite_pointers_[address >> 14][address & 16383] = *cycle.value;\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Output:\n\t\t\t\t\t\/\/ Check for a gate array access.\n\t\t\t\t\tif((address & 0xc000) == 0x4000) {\n\t\t\t\t\t\tswitch(*cycle.value >> 6) {\n\t\t\t\t\t\t\tcase 0: printf(\"Select pen %02x\\n\", *cycle.value & 0x1f);\t\tbreak;\n\t\t\t\t\t\t\tcase 1: printf(\"Select colour %02x\\n\", *cycle.value & 0x1f);\tbreak;\n\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\tprintf(\"Set mode %d, other flags %02x\\n\", *cycle.value & 3, (*cycle.value >> 2)&7);\n\t\t\t\t\t\t\t\tread_pointers_[0] = (*cycle.value & 4) ? &ram_[0] : os_.data();\n\t\t\t\t\t\t\t\tread_pointers_[3] = (*cycle.value & 8) ? &ram_[49152] : basic_.data();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 3: printf(\"RAM paging?\\n\"); break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a CRTC access\n\t\t\t\t\tif(!(address & 0x4000)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tcrtc_.select_register(*cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 1:\tcrtc_.set_register(*cycle.value);\t\tbreak;\n\t\t\t\t\t\t\tcase 2: case 3:\tprintf(\"Illegal CRTC write?\\n\");\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a PIO access\n\t\t\t\t\tif(!(address & 0x800)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tprintf(\"PSG data: %d\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 1:\tprintf(\"Vsync, etc: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 2:\tprintf(\"Key row, etc: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t\tcase 3:\tprintf(\"PIO control: %02x\\n\", *cycle.value);\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Input:\n\t\t\t\t\t\/\/ Check for a CRTC access\n\t\t\t\t\tif(!(address & 0x4000)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tcase 1: printf(\"Illegal CRTC read?\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 2: *cycle.value = crtc_.get_status();\t\tbreak;\n\t\t\t\t\t\t\tcase 3:\t*cycle.value = crtc_.get_register();\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Check for a PIO access\n\t\t\t\t\tif(!(address & 0x800)) {\n\t\t\t\t\t\tswitch((address >> 8) & 3) {\n\t\t\t\t\t\t\tcase 0:\tprintf(\"[In] PSG data\\n\");\t\tbreak;\n\t\t\t\t\t\t\tcase 1:\tprintf(\"[In] Vsync, etc\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 2:\tprintf(\"[In] Key row, etc\\n\");\tbreak;\n\t\t\t\t\t\t\tcase 3:\tprintf(\"[In] PIO control\\n\");\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t*cycle.value = 0xff;\n\t\t\t\tbreak;\n\n\t\t\t\tcase CPU::Z80::PartialMachineCycle::Interrupt:\n\t\t\t\t\t*cycle.value = 0xff;\n\t\t\t\tbreak;\n\n\t\t\t\tdefault: break;\n\t\t\t}\n\n\t\t\treturn HalfCycles(0);\n\t\t}\n\n\t\tvoid flush() {}\n\n\t\tvoid setup_output(float aspect_ratio) {\n\t\t\tcrtc_bus_handler_.setup_output(aspect_ratio);\n\t\t}\n\n\t\tvoid close_output() {\n\t\t\tcrtc_bus_handler_.close_output();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::CRT::CRT> get_crt() {\n\t\t\treturn crtc_bus_handler_.get_crt();\n\t\t}\n\n\t\tstd::shared_ptr<Outputs::Speaker> get_speaker() {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tvoid run_for(const Cycles cycles) {\n\t\t\tCPU::Z80::Processor<ConcreteMachine>::run_for(cycles);\n\t\t}\n\n\t\tvoid configure_as_target(const StaticAnalyser::Target &target) {\n\t\t\t\/\/ Establish reset memory map as per machine model (or, for now, as a hard-wired 464)\n\t\t\tread_pointers_[0] = os_.data();\n\t\t\tread_pointers_[1] = &ram_[16384];\n\t\t\tread_pointers_[2] = &ram_[32768];\n\t\t\tread_pointers_[3] = basic_.data();\n\n\t\t\twrite_pointers_[0] = &ram_[0];\n\t\t\twrite_pointers_[1] = &ram_[16384];\n\t\t\twrite_pointers_[2] = &ram_[32768];\n\t\t\twrite_pointers_[3] = &ram_[49152];\n\t\t}\n\n\t\tvoid set_rom(ROMType type, std::vector<uint8_t> data) {\n\t\t\t\/\/ Keep only the two ROMs that are currently of interest.\n\t\t\tswitch(type) {\n\t\t\t\tcase ROMType::OS464:\t\tos_ = data;\t\tbreak;\n\t\t\t\tcase ROMType::BASIC464:\t\tbasic_ = data;\tbreak;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tCRTCBusHandler crtc_bus_handler_;\n\t\tMotorola::CRTC::CRTC6845<CRTCBusHandler> crtc_;\n\n\t\tHalfCycles clock_offset_;\n\t\tHalfCycles crtc_counter_;\n\n\t\tuint8_t ram_[65536];\n\t\tstd::vector<uint8_t> os_, basic_;\n\n\t\tuint8_t *read_pointers_[4];\n\t\tuint8_t *write_pointers_[4];\n};\n\nMachine *Machine::AmstradCPC() {\n\treturn new ConcreteMachine;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"Extractor\/ExtractorCallbacks.h\"\n#include \"Extractor\/ExtractionContainers.h\"\n#include \"Extractor\/ScriptingEnvironment.h\"\n#include \"Extractor\/PBFParser.h\"\n#include \"Extractor\/XMLParser.h\"\n#include \"Util\/GitDescription.h\"\n#include \"Util\/MachineInfo.h\"\n#include \"Util\/OpenMPWrapper.h\"\n#include \"Util\/OSRMException.h\"\n#include \"Util\/ProgramOptions.h\"\n#include \"Util\/SimpleLogger.h\"\n#include \"Util\/StringUtil.h\"\n#include \"Util\/TimingUtil.h\"\n#include \"Util\/UUID.h\"\n#include \"typedefs.h\"\n\n#include <cstdlib>\n\n#include <boost\/unordered_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\nExtractorCallbacks * extractCallBacks;\nUUID uuid;\n\nint main (int argc, char *argv[]) {\n try {\n LogPolicy::GetInstance().Unmute();\n double startup_time = get_timestamp();\n\n boost::filesystem::path config_file_path, input_path, profile_path;\n int requested_num_threads;\n\n \/\/ declare a group of options that will be allowed only on command line\n boost::program_options::options_description generic_options(\"Options\");\n generic_options.add_options()\n (\"version,v\", \"Show version\")\n (\"help,h\", \"Show this help message\")\n (\"config,c\", boost::program_options::value<boost::filesystem::path>(&config_file_path)->default_value(\"extractor.ini\"),\n \"Path to a configuration file.\");\n\n \/\/ declare a group of options that will be allowed both on command line and in config file\n boost::program_options::options_description config_options(\"Configuration\");\n config_options.add_options()\n (\"profile,p\", boost::program_options::value<boost::filesystem::path>(&profile_path)->default_value(\"profile.lua\"),\n \"Path to LUA routing profile\")\n (\"threads,t\", boost::program_options::value<int>(&requested_num_threads)->default_value(8),\n \"Number of threads to use\");\n\n \/\/ hidden options, will be allowed both on command line and in config file, but will not be shown to the user\n boost::program_options::options_description hidden_options(\"Hidden options\");\n hidden_options.add_options()\n (\"input,i\", boost::program_options::value<boost::filesystem::path>(&input_path),\n \"Input file in .osm, .osm.bz2 or .osm.pbf format\");\n\n \/\/ positional option\n boost::program_options::positional_options_description positional_options;\n positional_options.add(\"input\", 1);\n\n \/\/ combine above options for parsing\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic_options).add(config_options).add(hidden_options);\n\n boost::program_options::options_description config_file_options;\n config_file_options.add(config_options).add(hidden_options);\n\n boost::program_options::options_description visible_options(boost::filesystem::basename(argv[0]) + \" <input.osm\/.osm.bz2\/.osm.pbf> [options]\");\n visible_options.add(generic_options).add(config_options);\n\n \/\/ parse command line options\n boost::program_options::variables_map option_variables;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).\n options(cmdline_options).positional(positional_options).run(), option_variables);\n\n if(option_variables.count(\"version\")) {\n SimpleLogger().Write() << g_GIT_DESCRIPTION;\n return 0;\n }\n\n if(option_variables.count(\"help\")) {\n SimpleLogger().Write() << visible_options;\n return 0;\n }\n\n boost::program_options::notify(option_variables);\n\n \/\/ parse config file\n if(boost::filesystem::is_regular_file(config_file_path)) {\n SimpleLogger().Write() << \"Reading options from: \" << config_file_path.c_str();\n std::string config_str;\n PrepareConfigFile( config_file_path.c_str(), config_str );\n std::stringstream config_stream( config_str );\n boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables);\n boost::program_options::notify(option_variables);\n }\n\n if(!option_variables.count(\"input\")) {\n SimpleLogger().Write() << visible_options;\n return 0;\n }\n\n if(1 > requested_num_threads) {\n SimpleLogger().Write(logWARNING) << \"Number of threads must be 1 or larger\";\n return 1;\n }\n\n if(!boost::filesystem::is_regular_file(input_path)) {\n SimpleLogger().Write(logWARNING) << \"Input file \" << input_path.c_str() << \" not found!\";\n return 1;\n }\n\n if(!boost::filesystem::is_regular_file(profile_path)) {\n SimpleLogger().Write(logWARNING) << \"Profile \" << profile_path.c_str() << \" not found!\";\n return 1;\n }\n\n SimpleLogger().Write() << \"Input file: \" << input_path.filename().string();\n SimpleLogger().Write() << \"Profile: \" << profile_path.filename().string();\n SimpleLogger().Write() << \"Threads: \" << requested_num_threads;\n\n \/*** Setup Scripting Environment ***\/\n ScriptingEnvironment scriptingEnvironment(profile_path.c_str());\n\n omp_set_num_threads( std::min( omp_get_num_procs(), requested_num_threads) );\n\n bool file_has_pbf_format(false);\n std::string output_file_name(input_path.c_str());\n std::string restrictionsFileName(input_path.c_str());\n std::string::size_type pos = output_file_name.find(\".osm.bz2\");\n if(pos==std::string::npos) {\n pos = output_file_name.find(\".osm.pbf\");\n if(pos!=std::string::npos) {\n file_has_pbf_format = true;\n }\n }\n if(pos==std::string::npos) {\n pos = output_file_name.find(\".pbf\");\n if(pos!=std::string::npos) {\n file_has_pbf_format = true;\n }\n }\n if(pos!=std::string::npos) {\n output_file_name.replace(pos, 8, \".osrm\");\n restrictionsFileName.replace(pos, 8, \".osrm.restrictions\");\n } else {\n pos=output_file_name.find(\".osm\");\n if(pos!=std::string::npos) {\n output_file_name.replace(pos, 5, \".osrm\");\n restrictionsFileName.replace(pos, 5, \".osrm.restrictions\");\n } else {\n output_file_name.append(\".osrm\");\n restrictionsFileName.append(\".osrm.restrictions\");\n }\n }\n\n boost::unordered_map<std::string, NodeID> stringMap;\n ExtractionContainers externalMemory;\n\n stringMap[\"\"] = 0;\n extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);\n BaseParser* parser;\n if(file_has_pbf_format) {\n parser = new PBFParser(input_path.c_str(), extractCallBacks, scriptingEnvironment);\n } else {\n parser = new XMLParser(input_path.c_str(), extractCallBacks, scriptingEnvironment);\n }\n\n if(!parser->ReadHeader()) {\n throw OSRMException(\"Parser not initialized!\");\n }\n SimpleLogger().Write() << \"Parsing in progress..\";\n double parsing_start_time = get_timestamp();\n parser->Parse();\n SimpleLogger().Write() << \"Parsing finished after \" <<\n (get_timestamp() - parsing_start_time) <<\n \" seconds\";\n\n if( externalMemory.all_edges_list.empty() ) {\n SimpleLogger().Write(logWARNING) << \"The input data is empty, exiting.\";\n return 1;\n }\n\n externalMemory.PrepareData(output_file_name, restrictionsFileName);\n\n delete parser;\n delete extractCallBacks;\n\n SimpleLogger().Write() <<\n \"extraction finished after \" << get_timestamp() - startup_time <<\n \"s\";\n\n SimpleLogger().Write() << \"To prepare the data for routing, run: \"\n << \".\/osrm-prepare \" << output_file_name << std::endl;\n\n } catch(boost::program_options::too_many_positional_options_error& e) {\n SimpleLogger().Write(logWARNING) << \"Only one input file can be specified\";\n return 1;\n } catch(boost::program_options::error& e) {\n SimpleLogger().Write(logWARNING) << e.what();\n return 1;\n } catch(std::exception & e) {\n SimpleLogger().Write(logWARNING) << \"Exception occured: \" << e.what();\n return 1;\n }\n return 0;\n}\n<commit_msg>fix inverted logic<commit_after>\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"Extractor\/ExtractorCallbacks.h\"\n#include \"Extractor\/ExtractionContainers.h\"\n#include \"Extractor\/ScriptingEnvironment.h\"\n#include \"Extractor\/PBFParser.h\"\n#include \"Extractor\/XMLParser.h\"\n#include \"Util\/GitDescription.h\"\n#include \"Util\/MachineInfo.h\"\n#include \"Util\/OpenMPWrapper.h\"\n#include \"Util\/OSRMException.h\"\n#include \"Util\/ProgramOptions.h\"\n#include \"Util\/SimpleLogger.h\"\n#include \"Util\/StringUtil.h\"\n#include \"Util\/TimingUtil.h\"\n#include \"Util\/UUID.h\"\n#include \"typedefs.h\"\n\n#include <cstdlib>\n\n#include <boost\/unordered_map.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\nExtractorCallbacks * extractCallBacks;\nUUID uuid;\n\nint main (int argc, char *argv[]) {\n try {\n LogPolicy::GetInstance().Unmute();\n double startup_time = get_timestamp();\n\n boost::filesystem::path config_file_path, input_path, profile_path;\n int requested_num_threads;\n\n \/\/ declare a group of options that will be allowed only on command line\n boost::program_options::options_description generic_options(\"Options\");\n generic_options.add_options()\n (\"version,v\", \"Show version\")\n (\"help,h\", \"Show this help message\")\n (\"config,c\", boost::program_options::value<boost::filesystem::path>(&config_file_path)->default_value(\"extractor.ini\"),\n \"Path to a configuration file.\");\n\n \/\/ declare a group of options that will be allowed both on command line and in config file\n boost::program_options::options_description config_options(\"Configuration\");\n config_options.add_options()\n (\"profile,p\", boost::program_options::value<boost::filesystem::path>(&profile_path)->default_value(\"profile.lua\"),\n \"Path to LUA routing profile\")\n (\"threads,t\", boost::program_options::value<int>(&requested_num_threads)->default_value(8),\n \"Number of threads to use\");\n\n \/\/ hidden options, will be allowed both on command line and in config file, but will not be shown to the user\n boost::program_options::options_description hidden_options(\"Hidden options\");\n hidden_options.add_options()\n (\"input,i\", boost::program_options::value<boost::filesystem::path>(&input_path),\n \"Input file in .osm, .osm.bz2 or .osm.pbf format\");\n\n \/\/ positional option\n boost::program_options::positional_options_description positional_options;\n positional_options.add(\"input\", 1);\n\n \/\/ combine above options for parsing\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic_options).add(config_options).add(hidden_options);\n\n boost::program_options::options_description config_file_options;\n config_file_options.add(config_options).add(hidden_options);\n\n boost::program_options::options_description visible_options(boost::filesystem::basename(argv[0]) + \" <input.osm\/.osm.bz2\/.osm.pbf> [options]\");\n visible_options.add(generic_options).add(config_options);\n\n \/\/ parse command line options\n boost::program_options::variables_map option_variables;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).\n options(cmdline_options).positional(positional_options).run(), option_variables);\n\n if(option_variables.count(\"version\")) {\n SimpleLogger().Write() << g_GIT_DESCRIPTION;\n return 0;\n }\n\n if(option_variables.count(\"help\")) {\n SimpleLogger().Write() << visible_options;\n return 0;\n }\n\n boost::program_options::notify(option_variables);\n\n \/\/ parse config file\n if(boost::filesystem::is_regular_file(config_file_path)) {\n SimpleLogger().Write() << \"Reading options from: \" << config_file_path.c_str();\n std::string config_str;\n PrepareConfigFile( config_file_path.c_str(), config_str );\n std::stringstream config_stream( config_str );\n boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables);\n boost::program_options::notify(option_variables);\n }\n\n if(!option_variables.count(\"input\")) {\n SimpleLogger().Write() << visible_options;\n return 0;\n }\n\n if(1 > requested_num_threads) {\n SimpleLogger().Write(logWARNING) << \"Number of threads must be 1 or larger\";\n return 1;\n }\n\n if(!boost::filesystem::is_regular_file(input_path)) {\n SimpleLogger().Write(logWARNING) << \"Input file \" << input_path.c_str() << \" not found!\";\n return 1;\n }\n\n if(!boost::filesystem::is_regular_file(profile_path)) {\n SimpleLogger().Write(logWARNING) << \"Profile \" << profile_path.c_str() << \" not found!\";\n return 1;\n }\n\n SimpleLogger().Write() << \"Input file: \" << input_path.filename().string();\n SimpleLogger().Write() << \"Profile: \" << profile_path.filename().string();\n SimpleLogger().Write() << \"Threads: \" << requested_num_threads;\n\n \/*** Setup Scripting Environment ***\/\n ScriptingEnvironment scriptingEnvironment(profile_path.c_str());\n\n omp_set_num_threads( std::min( omp_get_num_procs(), requested_num_threads) );\n\n bool file_has_pbf_format(false);\n std::string output_file_name(input_path.c_str());\n std::string restrictionsFileName(input_path.c_str());\n std::string::size_type pos = output_file_name.find(\".osm.bz2\");\n if(pos==std::string::npos) {\n pos = output_file_name.find(\".osm.pbf\");\n if(pos!=std::string::npos) {\n file_has_pbf_format = true;\n }\n }\n if (pos==std::string::npos)\n {\n pos = output_file_name.find(\".pbf\");\n if (pos!=std::string::npos)\n {\n file_has_pbf_format = true;\n }\n }\n if (pos == std::string::npos)\n {\n pos = output_file_name.find(\".osm\");\n if (pos == std::string::npos)\n {\n output_file_name.append(\".osrm\");\n restrictionsFileName.append(\".osrm.restrictions\");\n }\n else\n {\n output_file_name.replace(pos, 5, \".osrm\");\n restrictionsFileName.replace(pos, 5, \".osrm.restrictions\");\n }\n }\n else\n {\n output_file_name.replace(pos, 8, \".osrm\");\n restrictionsFileName.replace(pos, 8, \".osrm.restrictions\");\n }\n\n boost::unordered_map<std::string, NodeID> stringMap;\n ExtractionContainers externalMemory;\n\n stringMap[\"\"] = 0;\n extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap);\n BaseParser* parser;\n if(file_has_pbf_format) {\n parser = new PBFParser(input_path.c_str(), extractCallBacks, scriptingEnvironment);\n } else {\n parser = new XMLParser(input_path.c_str(), extractCallBacks, scriptingEnvironment);\n }\n\n if(!parser->ReadHeader()) {\n throw OSRMException(\"Parser not initialized!\");\n }\n SimpleLogger().Write() << \"Parsing in progress..\";\n double parsing_start_time = get_timestamp();\n parser->Parse();\n SimpleLogger().Write() << \"Parsing finished after \" <<\n (get_timestamp() - parsing_start_time) <<\n \" seconds\";\n\n if( externalMemory.all_edges_list.empty() ) {\n SimpleLogger().Write(logWARNING) << \"The input data is empty, exiting.\";\n return 1;\n }\n\n externalMemory.PrepareData(output_file_name, restrictionsFileName);\n\n delete parser;\n delete extractCallBacks;\n\n SimpleLogger().Write() <<\n \"extraction finished after \" << get_timestamp() - startup_time <<\n \"s\";\n\n SimpleLogger().Write() << \"To prepare the data for routing, run: \"\n << \".\/osrm-prepare \" << output_file_name << std::endl;\n\n } catch(boost::program_options::too_many_positional_options_error& e) {\n SimpleLogger().Write(logWARNING) << \"Only one input file can be specified\";\n return 1;\n } catch(boost::program_options::error& e) {\n SimpleLogger().Write(logWARNING) << e.what();\n return 1;\n } catch(std::exception & e) {\n SimpleLogger().Write(logWARNING) << \"Exception occured: \" << e.what();\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_planning_system\/ProblemGeneration\/PDDLProblemGenerator.h\"\n\nnamespace KCL_rosplan {\n\n\t\/**\n\t * generates a PDDL problem file.\n\t * This file is later read by the planner.\n\t *\/\n\tvoid PDDLProblemGenerator::generatePDDLProblemFile(std::string &problemPath) {\n\n\t\tstd::stringstream ss;\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/name\";\n\t\tdomain_name_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/types\";\n\t\tdomain_type_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/predicates\";\n\t\tdomain_predicate_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/functions\";\n\t\tdomain_function_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/instances\";\n\t\tstate_instance_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/propositions\";\n\t\tstate_proposition_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/functions\";\n\t\tstate_function_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/timed_knowledge\";\n\t\tstate_timed_knowledge_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/goals\";\n\t\tstate_goal_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/metric\";\n\t\tstate_metric_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tstd::ofstream pFile;\n\t\tpFile.open((problemPath).c_str());\n\n\t\tmakeHeader(pFile);\n\t\tmakeInitialState(pFile);\n\t\tmakeGoals(pFile);\n makeMetric(pFile);\n\n \/\/ add end of problem file\n pFile << \")\" << std::endl;\n\t}\n\n\t\/*--------*\/\n\t\/* header *\/\n\t\/*--------*\/\n\n\tvoid PDDLProblemGenerator::makeHeader(std::ofstream &pFile) {\n\n\t\t\/\/ setup service calls\n\t\tros::NodeHandle nh;\n\n\n\t\tros::ServiceClient getNameClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainNameService>(domain_name_service);\n\t\tros::ServiceClient getTypesClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainTypeService>(domain_type_service);\n\t\tros::ServiceClient getInstancesClient = nh.serviceClient<rosplan_knowledge_msgs::GetInstanceService>(state_instance_service);\n\n\t\t\/\/ get domain name\n\t\trosplan_knowledge_msgs::GetDomainNameService nameSrv;\n\t\tif (!getNameClient.call(nameSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_name_service.c_str());\n\t\t}\n\n\t\tpFile << \"(define (problem task)\" << std::endl;\n\t\tpFile << \"(:domain \" << nameSrv.response.domain_name << \")\" << std::endl;\n\n\t\t\/* objects *\/\n\t\tpFile << \"(:objects\" << std::endl;\n\n\t\t\/\/ get types\n\t\trosplan_knowledge_msgs::GetDomainTypeService typeSrv;\n\t\tif (!getTypesClient.call(typeSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_type_service.c_str());\n\t\t}\n\n\t\t\/\/ get instances of each type\n\t\tfor(size_t t=0; t<typeSrv.response.types.size(); t++) {\n\n\t\t\trosplan_knowledge_msgs::GetInstanceService instanceSrv;\n\t\t\tinstanceSrv.request.type_name = typeSrv.response.types[t];\n\n\t\t\tif (!getInstancesClient.call(instanceSrv)) {\n\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_instance_service.c_str(), instanceSrv.request.type_name.c_str());\n\t\t\t} else {\n\t\t\t\tif(instanceSrv.response.instances.size() == 0) continue;\n\t\t\t\tpFile << \" \";\n\t\t\t\tfor(size_t i=0;i<instanceSrv.response.instances.size();i++) {\n\t\t\t\t\tpFile << instanceSrv.response.instances[i] << \" \";\n\t\t\t\t}\n\t\t\t\tpFile << \"- \" << typeSrv.response.types[t] << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tpFile << \")\" << std::endl;\n\t}\n\n\t\/*---------------*\/\n\t\/* initial state *\/\n\t\/*---------------*\/\n\n\tvoid PDDLProblemGenerator::makeInitialState(std::ofstream &pFile) {\n\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient getDomainPropsClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainAttributeService>(domain_predicate_service);\n\t\tros::ServiceClient getDomainFuncsClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainAttributeService>(domain_function_service);\n\t\tros::ServiceClient getPropsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_proposition_service);\n\t\tros::ServiceClient getFuncsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_function_service);\n\t\tros::ServiceClient getTILsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_timed_knowledge_service);\n\n\t\t\/\/ note the time now for TILs\n\t\tros::Time time = ros::Time::now() + ros::Duration(1);\n\n\t\tpFile << \"(:init\" << std::endl;\n\n\t\t\/\/ get propositions\n\t\trosplan_knowledge_msgs::GetDomainAttributeService domainAttrSrv;\n\t\tif (!getDomainPropsClient.call(domainAttrSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_predicate_service.c_str());\n\t\t} else {\n\n\t\t\tstd::vector<rosplan_knowledge_msgs::DomainFormula>::iterator ait = domainAttrSrv.response.items.begin();\n\t\t\tfor(; ait != domainAttrSrv.response.items.end(); ait++) {\n\n\t\t\t\trosplan_knowledge_msgs::GetAttributeService attrSrv;\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tif (!getPropsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_proposition_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (\";\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/Check if the attribute is negated\n\t\t\t\t\t\tif(attr.is_negative) pFile << \"not (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpFile << \")\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(attr.is_negative) pFile << \")\";\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tattrSrv.response.attributes.clear();\n\t\t\t\tif (!getTILsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_timed_knowledge_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (at \" << (attr.initial_time - time).toSec() << \" (\";\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/Check if the attribute is negated\n\t\t\t\t\t\tif(attr.is_negative) pFile << \"not (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpFile << \"))\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(attr.is_negative) pFile << \")\";\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ get functions\n\t\tif (!getDomainFuncsClient.call(domainAttrSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_function_service.c_str());\n\t\t} else {\n\n\t\t\tstd::vector<rosplan_knowledge_msgs::DomainFormula>::iterator ait = domainAttrSrv.response.items.begin();\n\t\t\tfor(; ait != domainAttrSrv.response.items.end(); ait++) {\n\n\t\t\t\trosplan_knowledge_msgs::GetAttributeService attrSrv;\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tif (!getFuncsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_function_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (\";\n\n\t\t\t\t\t\tif(time < attr.initial_time) {\n\t\t\t\t\t\t\tpFile << \"at \" << (attr.initial_time - time).toSec() << \" (\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << \"= (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << \") \" << attr.function_value << \")\";\n\n\t\t\t\t\t\tif(time < attr.initial_time) {\n\t\t\t\t\t\t\tpFile << \")\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tpFile << \")\" << std::endl;\n\t}\n\n\t\/*------*\/\n\t\/* goal *\/\n\t\/*------*\/\n\n\tvoid PDDLProblemGenerator::makeGoals(std::ofstream &pFile) {\n\t\t\t\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient getCurrentGoalsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_goal_service);\n\n\t\tpFile << \"(:goal (and\" << std::endl;\n\n\t\t\/\/ get current goals\n\t\trosplan_knowledge_msgs::GetAttributeService currentGoalSrv;\n\t\tif (!getCurrentGoalsClient.call(currentGoalSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", state_goal_service.c_str());\n\t\t} else {\n\n\t\t\tfor(size_t i=0;i<currentGoalSrv.response.attributes.size();i++) {\n\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = currentGoalSrv.response.attributes[i];\n\t\t\t\tif(attr.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FACT) {\n\t\t\t\t\tpFile << \" (\" + attr.attribute_name;\n\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t}\n\t\t\t\t\tpFile << \")\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpFile << \"))\" << std::endl;\n\t}\n\n\n\t\/*--------*\/\n\t\/* metric *\/\n\t\/*--------*\/\n\n\tvoid PDDLProblemGenerator::makeMetric(std::ofstream &pFile) {\n\n\t\tros::NodeHandle nh;\n\n\t\t\/\/ get current metric\n\t\tros::ServiceClient getCurrentMetricClient = nh.serviceClient<rosplan_knowledge_msgs::GetMetricService>(state_metric_service);\n\t\trosplan_knowledge_msgs::GetMetricService currentMetricSrv;\n\t\tif (!getCurrentMetricClient.call(currentMetricSrv)) {\n\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", state_metric_service.c_str());\n\n\t\t} else {\n\n\t\t\trosplan_knowledge_msgs::KnowledgeItem metric = currentMetricSrv.response.metric;\n if (metric.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::EXPRESSION) {\n\t\t\t\t\t\n\t\t\t\tpFile << \"(:metric \" << metric.optimization;\n\t\t\t\tstd::vector<int> operand_count;\n\t\t\t\tprintExpression(pFile, metric.expr);\n\n\t\t\t\tpFile << \")\" << std::endl;\n }\n }\n\t}\n\n\tvoid PDDLProblemGenerator::printExpression(std::ofstream &pFile, rosplan_knowledge_msgs::ExprComposite & e) {\n\n\t\tstd::vector<rosplan_knowledge_msgs::ExprBase> tokens = e.tokens;\n\t\tbool second_operand = false;\n\t\tint depth = 0;\n\t\tfor(int i=0; i<tokens.size(); i++) {\n\t\t\trosplan_knowledge_msgs::ExprBase token = tokens[i];\n\n\t\t\tpFile << \" \";\n\n\t\t\tswitch(token.expr_type) {\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::OPERATOR:\n\n\t\t\t\tswitch(token.op) {\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::ADD: pFile << \"(+\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::SUB: pFile << \"(-\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::MUL: pFile << \"(*\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::DIV: pFile << \"(\/\"; break;\n\t\t\t\t}\n\t\t\t\tsecond_operand = false;\n\t\t\t\tdepth++;\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::CONSTANT:\n\n\t\t\t\tpFile << token.constant;\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::FUNCTION:\n\n\t\t\t\tpFile << \"(\" << token.function.name;\n\t\t\t\tfor(size_t j=0; j<token.function.typed_parameters.size(); j++) {\n\t\t\t\t\tpFile << \" \" << token.function.typed_parameters[j].value;\n\t\t\t\t}\n\t\t\t\tpFile << \")\";\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::SPECIAL:\n\n\t\t\t\tswitch(token.special_type) {\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::HASHT:\t\tpFile << \"#t\";\t\t\tbreak;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::TOTAL_TIME:\tpFile << \"total-time\";\tbreak;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::DURATION:\tpFile << \"?duration\";\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(second_operand && token.expr_type!=rosplan_knowledge_msgs::ExprBase::OPERATOR) {\n\t\t\t\tsecond_operand = true;\n\t\t\t\tpFile << \")\";\n\t\t\t\tdepth--;\n\t\t\t}\n\n\t\t\tif(token.expr_type!=rosplan_knowledge_msgs::ExprBase::OPERATOR) {\n\t\t\t\tsecond_operand = true;\n\t\t\t}\n\t\t}\n\n\t\twhile(depth>0) {\n\t\t\tpFile << \")\";\n\t\t\tdepth--;\n\t\t}\n\t};\n} \/\/ close namespace\n<commit_msg>minor bugfix, added paranthesis in the total-time metric<commit_after>#include \"rosplan_planning_system\/ProblemGeneration\/PDDLProblemGenerator.h\"\n\nnamespace KCL_rosplan {\n\n\t\/**\n\t * generates a PDDL problem file.\n\t * This file is later read by the planner.\n\t *\/\n\tvoid PDDLProblemGenerator::generatePDDLProblemFile(std::string &problemPath) {\n\n\t\tstd::stringstream ss;\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/name\";\n\t\tdomain_name_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/types\";\n\t\tdomain_type_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/predicates\";\n\t\tdomain_predicate_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/domain\/functions\";\n\t\tdomain_function_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/instances\";\n\t\tstate_instance_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/propositions\";\n\t\tstate_proposition_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/functions\";\n\t\tstate_function_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/timed_knowledge\";\n\t\tstate_timed_knowledge_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/goals\";\n\t\tstate_goal_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tss << \"\/\" << knowledge_base << \"\/state\/metric\";\n\t\tstate_metric_service = ss.str();\n\t\tss.str(\"\");\n\n\t\tstd::ofstream pFile;\n\t\tpFile.open((problemPath).c_str());\n\n\t\tmakeHeader(pFile);\n\t\tmakeInitialState(pFile);\n\t\tmakeGoals(pFile);\n makeMetric(pFile);\n\n \/\/ add end of problem file\n pFile << \")\" << std::endl;\n\t}\n\n\t\/*--------*\/\n\t\/* header *\/\n\t\/*--------*\/\n\n\tvoid PDDLProblemGenerator::makeHeader(std::ofstream &pFile) {\n\n\t\t\/\/ setup service calls\n\t\tros::NodeHandle nh;\n\n\n\t\tros::ServiceClient getNameClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainNameService>(domain_name_service);\n\t\tros::ServiceClient getTypesClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainTypeService>(domain_type_service);\n\t\tros::ServiceClient getInstancesClient = nh.serviceClient<rosplan_knowledge_msgs::GetInstanceService>(state_instance_service);\n\n\t\t\/\/ get domain name\n\t\trosplan_knowledge_msgs::GetDomainNameService nameSrv;\n\t\tif (!getNameClient.call(nameSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_name_service.c_str());\n\t\t}\n\n\t\tpFile << \"(define (problem task)\" << std::endl;\n\t\tpFile << \"(:domain \" << nameSrv.response.domain_name << \")\" << std::endl;\n\n\t\t\/* objects *\/\n\t\tpFile << \"(:objects\" << std::endl;\n\n\t\t\/\/ get types\n\t\trosplan_knowledge_msgs::GetDomainTypeService typeSrv;\n\t\tif (!getTypesClient.call(typeSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_type_service.c_str());\n\t\t}\n\n\t\t\/\/ get instances of each type\n\t\tfor(size_t t=0; t<typeSrv.response.types.size(); t++) {\n\n\t\t\trosplan_knowledge_msgs::GetInstanceService instanceSrv;\n\t\t\tinstanceSrv.request.type_name = typeSrv.response.types[t];\n\n\t\t\tif (!getInstancesClient.call(instanceSrv)) {\n\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_instance_service.c_str(), instanceSrv.request.type_name.c_str());\n\t\t\t} else {\n\t\t\t\tif(instanceSrv.response.instances.size() == 0) continue;\n\t\t\t\tpFile << \" \";\n\t\t\t\tfor(size_t i=0;i<instanceSrv.response.instances.size();i++) {\n\t\t\t\t\tpFile << instanceSrv.response.instances[i] << \" \";\n\t\t\t\t}\n\t\t\t\tpFile << \"- \" << typeSrv.response.types[t] << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tpFile << \")\" << std::endl;\n\t}\n\n\t\/*---------------*\/\n\t\/* initial state *\/\n\t\/*---------------*\/\n\n\tvoid PDDLProblemGenerator::makeInitialState(std::ofstream &pFile) {\n\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient getDomainPropsClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainAttributeService>(domain_predicate_service);\n\t\tros::ServiceClient getDomainFuncsClient = nh.serviceClient<rosplan_knowledge_msgs::GetDomainAttributeService>(domain_function_service);\n\t\tros::ServiceClient getPropsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_proposition_service);\n\t\tros::ServiceClient getFuncsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_function_service);\n\t\tros::ServiceClient getTILsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_timed_knowledge_service);\n\n\t\t\/\/ note the time now for TILs\n\t\tros::Time time = ros::Time::now() + ros::Duration(1);\n\n\t\tpFile << \"(:init\" << std::endl;\n\n\t\t\/\/ get propositions\n\t\trosplan_knowledge_msgs::GetDomainAttributeService domainAttrSrv;\n\t\tif (!getDomainPropsClient.call(domainAttrSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_predicate_service.c_str());\n\t\t} else {\n\n\t\t\tstd::vector<rosplan_knowledge_msgs::DomainFormula>::iterator ait = domainAttrSrv.response.items.begin();\n\t\t\tfor(; ait != domainAttrSrv.response.items.end(); ait++) {\n\n\t\t\t\trosplan_knowledge_msgs::GetAttributeService attrSrv;\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tif (!getPropsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_proposition_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (\";\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/Check if the attribute is negated\n\t\t\t\t\t\tif(attr.is_negative) pFile << \"not (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpFile << \")\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(attr.is_negative) pFile << \")\";\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tattrSrv.response.attributes.clear();\n\t\t\t\tif (!getTILsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_timed_knowledge_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (at \" << (attr.initial_time - time).toSec() << \" (\";\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/Check if the attribute is negated\n\t\t\t\t\t\tif(attr.is_negative) pFile << \"not (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpFile << \"))\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(attr.is_negative) pFile << \")\";\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ get functions\n\t\tif (!getDomainFuncsClient.call(domainAttrSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", domain_function_service.c_str());\n\t\t} else {\n\n\t\t\tstd::vector<rosplan_knowledge_msgs::DomainFormula>::iterator ait = domainAttrSrv.response.items.begin();\n\t\t\tfor(; ait != domainAttrSrv.response.items.end(); ait++) {\n\n\t\t\t\trosplan_knowledge_msgs::GetAttributeService attrSrv;\n\t\t\t\tattrSrv.request.predicate_name = ait->name;\n\t\t\t\tif (!getFuncsClient.call(attrSrv)) {\n\t\t\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s: %s\", state_function_service.c_str(), attrSrv.request.predicate_name.c_str());\n\t\t\t\t} else {\n\t\t\t\t\tif(attrSrv.response.attributes.size() == 0) continue;\n\n\t\t\t\t\tfor(size_t i=0;i<attrSrv.response.attributes.size();i++) {\n\n\t\t\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = attrSrv.response.attributes[i];\n\n\t\t\t\t\t\tpFile << \" (\";\n\n\t\t\t\t\t\tif(time < attr.initial_time) {\n\t\t\t\t\t\t\tpFile << \"at \" << (attr.initial_time - time).toSec() << \" (\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << \"= (\";\n\n\t\t\t\t\t\tpFile << attr.attribute_name;\n\t\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << \") \" << attr.function_value << \")\";\n\n\t\t\t\t\t\tif(time < attr.initial_time) {\n\t\t\t\t\t\t\tpFile << \")\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpFile << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpFile << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tpFile << \")\" << std::endl;\n\t}\n\n\t\/*------*\/\n\t\/* goal *\/\n\t\/*------*\/\n\n\tvoid PDDLProblemGenerator::makeGoals(std::ofstream &pFile) {\n\t\t\t\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient getCurrentGoalsClient = nh.serviceClient<rosplan_knowledge_msgs::GetAttributeService>(state_goal_service);\n\n\t\tpFile << \"(:goal (and\" << std::endl;\n\n\t\t\/\/ get current goals\n\t\trosplan_knowledge_msgs::GetAttributeService currentGoalSrv;\n\t\tif (!getCurrentGoalsClient.call(currentGoalSrv)) {\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", state_goal_service.c_str());\n\t\t} else {\n\n\t\t\tfor(size_t i=0;i<currentGoalSrv.response.attributes.size();i++) {\n\t\t\t\trosplan_knowledge_msgs::KnowledgeItem attr = currentGoalSrv.response.attributes[i];\n\t\t\t\tif(attr.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FACT) {\n\t\t\t\t\tpFile << \" (\" + attr.attribute_name;\n\t\t\t\t\tfor(size_t j=0; j<attr.values.size(); j++) {\n\t\t\t\t\t\tpFile << \" \" << attr.values[j].value;\n\t\t\t\t\t}\n\t\t\t\t\tpFile << \")\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpFile << \"))\" << std::endl;\n\t}\n\n\n\t\/*--------*\/\n\t\/* metric *\/\n\t\/*--------*\/\n\n\tvoid PDDLProblemGenerator::makeMetric(std::ofstream &pFile) {\n\n\t\tros::NodeHandle nh;\n\n\t\t\/\/ get current metric\n\t\tros::ServiceClient getCurrentMetricClient = nh.serviceClient<rosplan_knowledge_msgs::GetMetricService>(state_metric_service);\n\t\trosplan_knowledge_msgs::GetMetricService currentMetricSrv;\n\t\tif (!getCurrentMetricClient.call(currentMetricSrv)) {\n\n\t\t\tROS_ERROR(\"KCL: (PDDLProblemGenerator) Failed to call service %s\", state_metric_service.c_str());\n\n\t\t} else {\n\n\t\t\trosplan_knowledge_msgs::KnowledgeItem metric = currentMetricSrv.response.metric;\n if (metric.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::EXPRESSION) {\n\t\t\t\t\t\n\t\t\t\tpFile << \"(:metric \" << metric.optimization;\n\t\t\t\tstd::vector<int> operand_count;\n\t\t\t\tprintExpression(pFile, metric.expr);\n\n\t\t\t\tpFile << \")\" << std::endl;\n }\n }\n\t}\n\n\tvoid PDDLProblemGenerator::printExpression(std::ofstream &pFile, rosplan_knowledge_msgs::ExprComposite & e) {\n\n\t\tstd::vector<rosplan_knowledge_msgs::ExprBase> tokens = e.tokens;\n\t\tbool second_operand = false;\n\t\tint depth = 0;\n\t\tfor(int i=0; i<tokens.size(); i++) {\n\t\t\trosplan_knowledge_msgs::ExprBase token = tokens[i];\n\n\t\t\tpFile << \" \";\n\n\t\t\tswitch(token.expr_type) {\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::OPERATOR:\n\n\t\t\t\tswitch(token.op) {\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::ADD: pFile << \"(+\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::SUB: pFile << \"(-\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::MUL: pFile << \"(*\"; break;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::DIV: pFile << \"(\/\"; break;\n\t\t\t\t}\n\t\t\t\tsecond_operand = false;\n\t\t\t\tdepth++;\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::CONSTANT:\n\n\t\t\t\tpFile << token.constant;\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::FUNCTION:\n\n\t\t\t\tpFile << \"(\" << token.function.name;\n\t\t\t\tfor(size_t j=0; j<token.function.typed_parameters.size(); j++) {\n\t\t\t\t\tpFile << \" \" << token.function.typed_parameters[j].value;\n\t\t\t\t}\n\t\t\t\tpFile << \")\";\n\t\t\t\tbreak;\n\n\t\t\tcase rosplan_knowledge_msgs::ExprBase::SPECIAL:\n\n\t\t\t\tswitch(token.special_type) {\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::HASHT:\t\tpFile << \"#t\";\t\t\tbreak;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::TOTAL_TIME:\tpFile << \"(total-time)\";\tbreak;\n\t\t\t\t\tcase rosplan_knowledge_msgs::ExprBase::DURATION:\tpFile << \"?duration\";\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(second_operand && token.expr_type!=rosplan_knowledge_msgs::ExprBase::OPERATOR) {\n\t\t\t\tsecond_operand = true;\n\t\t\t\tpFile << \")\";\n\t\t\t\tdepth--;\n\t\t\t}\n\n\t\t\tif(token.expr_type!=rosplan_knowledge_msgs::ExprBase::OPERATOR) {\n\t\t\t\tsecond_operand = true;\n\t\t\t}\n\t\t}\n\n\t\twhile(depth>0) {\n\t\t\tpFile << \")\";\n\t\t\tdepth--;\n\t\t}\n\t};\n} \/\/ close namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/fastos\/fastos.h>\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchcorespi.index.index_manager_explorer\");\n#include \"index_manager_explorer.h\"\n#include \"index_manager_stats.h\"\n\n#include <vespa\/vespalib\/data\/slime\/cursor.h>\n\nusing vespalib::slime::Cursor;\nusing vespalib::slime::Inserter;\nusing search::SearchableStats;\n\nnamespace searchcorespi {\n\nIndexManagerExplorer::IndexManagerExplorer(IIndexManager::SP mgr)\n : _mgr(std::move(mgr))\n{\n}\n\nvoid\nIndexManagerExplorer::get_state(const Inserter &inserter, bool full) const\n{\n Cursor &object = inserter.insertObject();\n object.setLong(\"lastSerialNum\", _mgr->getCurrentSerialNum());\n if (full) {\n IndexManagerStats stats(*_mgr);\n Cursor &diskIndexArrayCursor = object.setArray(\"diskIndexes\");\n for (const auto &diskIndex : stats.getDiskIndexes()) {\n Cursor &diskIndexCursor = diskIndexArrayCursor.addObject();\n const SearchableStats &sstats = diskIndex.getSearchableStats();\n diskIndexCursor.setLong(\"serialNum\", diskIndex.getSerialNum());\n diskIndexCursor.setString(\"indexDir\", diskIndex.getIndexdir());\n diskIndexCursor.setLong(\"sizeOnDisk\", sstats.sizeOnDisk());\n }\n Cursor &memoryIndexArrayCursor = object.setArray(\"memoryIndexes\");\n for (const auto &memoryIndex : stats.getMemoryIndexes()) {\n Cursor &memoryIndexCursor = memoryIndexArrayCursor.addObject();\n const SearchableStats &sstats = memoryIndex.getSearchableStats();\n memoryIndexCursor.setLong(\"serialNum\", memoryIndex.getSerialNum());\n memoryIndexCursor.setLong(\"docsInMemory\", sstats.docsInMemory());\n memoryIndexCursor.setLong(\"memoryUsage\", sstats.memoryUsage());\n }\n }\n}\n\n} \/\/ namespace searchcorespi\n<commit_msg>Factor out portions of get_state() to helper functions.<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/fastos\/fastos.h>\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchcorespi.index.index_manager_explorer\");\n#include \"index_manager_explorer.h\"\n#include \"index_manager_stats.h\"\n\n#include <vespa\/vespalib\/data\/slime\/cursor.h>\n\nusing vespalib::slime::Cursor;\nusing vespalib::slime::Inserter;\nusing search::SearchableStats;\nusing searchcorespi::index::DiskIndexStats;\nusing searchcorespi::index::MemoryIndexStats;\n\nnamespace searchcorespi {\n\nnamespace {\n\nvoid insertDiskIndex(Cursor &arrayCursor, const DiskIndexStats &diskIndex)\n{\n Cursor &diskIndexCursor = arrayCursor.addObject();\n const SearchableStats &sstats = diskIndex.getSearchableStats();\n diskIndexCursor.setLong(\"serialNum\", diskIndex.getSerialNum());\n diskIndexCursor.setString(\"indexDir\", diskIndex.getIndexdir());\n diskIndexCursor.setLong(\"sizeOnDisk\", sstats.sizeOnDisk());\n}\n\nvoid insertMemoryIndex(Cursor &arrayCursor, const MemoryIndexStats &memoryIndex)\n{\n Cursor &memoryIndexCursor = arrayCursor.addObject();\n const SearchableStats &sstats = memoryIndex.getSearchableStats();\n memoryIndexCursor.setLong(\"serialNum\", memoryIndex.getSerialNum());\n memoryIndexCursor.setLong(\"docsInMemory\", sstats.docsInMemory());\n memoryIndexCursor.setLong(\"memoryUsage\", sstats.memoryUsage());\n}\n\n}\n\n\nIndexManagerExplorer::IndexManagerExplorer(IIndexManager::SP mgr)\n : _mgr(std::move(mgr))\n{\n}\n\nvoid\nIndexManagerExplorer::get_state(const Inserter &inserter, bool full) const\n{\n Cursor &object = inserter.insertObject();\n object.setLong(\"lastSerialNum\", _mgr->getCurrentSerialNum());\n if (full) {\n IndexManagerStats stats(*_mgr);\n Cursor &diskIndexArrayCursor = object.setArray(\"diskIndexes\");\n for (const auto &diskIndex : stats.getDiskIndexes()) {\n insertDiskIndex(diskIndexArrayCursor, diskIndex);\n }\n Cursor &memoryIndexArrayCursor = object.setArray(\"memoryIndexes\");\n for (const auto &memoryIndex : stats.getMemoryIndexes()) {\n insertMemoryIndex(memoryIndexArrayCursor, memoryIndex);\n }\n }\n}\n\n} \/\/ namespace searchcorespi\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"docsumfieldwriter.h\"\n#include \"idocsumenvironment.h\"\n#include \"docsumstate.h\"\n#include <vespa\/searchlib\/common\/documentlocations.h>\n#include <vespa\/searchlib\/common\/location.h>\n#include <vespa\/searchlib\/parsequery\/stackdumpiterator.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchlib.docsummary.docsumfieldwriter\");\n\nnamespace search::docsummary {\n\nusing search::attribute::IAttributeContext;\nusing search::attribute::IAttributeVector;\nusing search::attribute::BasicType;\nusing search::common::Location;\n\n\/\/--------------------------------------------------------------------------\n\nconst vespalib::string IDocsumFieldWriter::_empty(\"\");\n\nbool\nIDocsumFieldWriter::setFieldWriterStateIndex(uint32_t)\n{\n return false; \/\/ Don't need any field writer state by default\n}\n\n\/\/--------------------------------------------------------------------------\n\nEmptyDFW::EmptyDFW() = default;\n\nEmptyDFW::~EmptyDFW() = default;\n\nvoid\nEmptyDFW::insertField(uint32_t, GetDocsumsState *, ResType, vespalib::slime::Inserter &target)\n{\n \/\/ insert explicitly-empty field?\n \/\/ target.insertNix();\n (void)target;\n}\n\n\/\/--------------------------------------------------------------------------\n\nCopyDFW::CopyDFW()\n : _inputFieldEnumValue(static_cast<uint32_t>(-1))\n{\n}\n\nCopyDFW::~CopyDFW() = default;\n\nbool\nCopyDFW::Init(const ResultConfig & config, const char *inputField)\n{\n _inputFieldEnumValue = config.GetFieldNameEnum().Lookup(inputField);\n\n if (_inputFieldEnumValue >= config.GetFieldNameEnum().GetNumEntries()) {\n LOG(warning, \"no docsum format contains field '%s'; copied fields will be empty\", inputField);\n }\n\n for (const auto & field : config) {\n const ResConfigEntry *entry = field.GetEntry(field.GetIndexFromEnumValue(_inputFieldEnumValue));\n\n if (entry != nullptr &&\n !IsRuntimeCompatible(entry->_type, RES_INT) &&\n !IsRuntimeCompatible(entry->_type, RES_DOUBLE) &&\n !IsRuntimeCompatible(entry->_type, RES_INT64) &&\n !IsRuntimeCompatible(entry->_type, RES_STRING) &&\n !IsRuntimeCompatible(entry->_type, RES_DATA)) {\n\n LOG(warning, \"cannot use docsum field '%s' as input to copy; type conflict with result class %d (%s)\",\n inputField, field.GetClassID(), field.GetClassName());\n return false;\n }\n }\n return true;\n}\n\nvoid\nCopyDFW::insertField(uint32_t \/*docid*\/, GeneralResult *gres, GetDocsumsState *, ResType type,\n vespalib::slime::Inserter &target)\n{\n int idx = gres->GetClass()->GetIndexFromEnumValue(_inputFieldEnumValue);\n ResEntry *entry = gres->GetEntry(idx);\n\n if (entry != nullptr &&\n IsRuntimeCompatible(entry->_type, type))\n {\n switch (type) {\n case RES_INT: {\n uint32_t val32 = entry->_intval;\n target.insertLong(val32);\n break; }\n\n case RES_SHORT: {\n uint16_t val16 = entry->_intval;\n target.insertLong(val16);\n break; }\n\n case RES_BYTE: {\n uint8_t val8 = entry->_intval;\n target.insertLong(val8);\n break; }\n case RES_BOOL: {\n target.insertBool(entry->_intval != 0);\n break; }\n\n case RES_FLOAT: {\n float valfloat = entry->_doubleval;\n target.insertDouble(valfloat);\n break; }\n\n case RES_DOUBLE: {\n double valdouble = entry->_doubleval;\n target.insertDouble(valdouble);\n break; }\n\n case RES_INT64: {\n uint64_t valint64 = entry->_int64val;\n target.insertLong(valint64);\n break; }\n\n case RES_JSONSTRING:\n case RES_FEATUREDATA:\n case RES_LONG_STRING:\n case RES_STRING: {\n uint32_t len;\n const char *spt;\n \/\/ resolve field\n entry->_resolve_field(&spt, &len);\n vespalib::Memory value(spt, len);\n target.insertString(value);\n break; }\n\n case RES_TENSOR:\n case RES_LONG_DATA:\n case RES_DATA: {\n uint32_t len;\n const char *dpt;\n \/\/ resolve field\n entry->_resolve_field(&dpt, &len);\n vespalib::Memory value(dpt, len);\n target.insertData(value);\n break; }\n }\n }\n}\n\n}\n<commit_msg>Handle struct field in CopyDFW.<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"docsumfieldwriter.h\"\n#include \"idocsumenvironment.h\"\n#include \"docsumstate.h\"\n#include <vespa\/searchlib\/common\/documentlocations.h>\n#include <vespa\/searchlib\/common\/location.h>\n#include <vespa\/searchlib\/parsequery\/stackdumpiterator.h>\n#include <vespa\/vespalib\/data\/slime\/slime.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchlib.docsummary.docsumfieldwriter\");\n\nnamespace search::docsummary {\n\nusing search::attribute::IAttributeContext;\nusing search::attribute::IAttributeVector;\nusing search::attribute::BasicType;\nusing search::common::Location;\n\n\/\/--------------------------------------------------------------------------\n\nconst vespalib::string IDocsumFieldWriter::_empty(\"\");\n\nbool\nIDocsumFieldWriter::setFieldWriterStateIndex(uint32_t)\n{\n return false; \/\/ Don't need any field writer state by default\n}\n\n\/\/--------------------------------------------------------------------------\n\nEmptyDFW::EmptyDFW() = default;\n\nEmptyDFW::~EmptyDFW() = default;\n\nvoid\nEmptyDFW::insertField(uint32_t, GetDocsumsState *, ResType, vespalib::slime::Inserter &target)\n{\n \/\/ insert explicitly-empty field?\n \/\/ target.insertNix();\n (void)target;\n}\n\n\/\/--------------------------------------------------------------------------\n\nCopyDFW::CopyDFW()\n : _inputFieldEnumValue(static_cast<uint32_t>(-1))\n{\n}\n\nCopyDFW::~CopyDFW() = default;\n\nbool\nCopyDFW::Init(const ResultConfig & config, const char *inputField)\n{\n _inputFieldEnumValue = config.GetFieldNameEnum().Lookup(inputField);\n\n if (_inputFieldEnumValue >= config.GetFieldNameEnum().GetNumEntries()) {\n LOG(warning, \"no docsum format contains field '%s'; copied fields will be empty\", inputField);\n }\n\n for (const auto & field : config) {\n const ResConfigEntry *entry = field.GetEntry(field.GetIndexFromEnumValue(_inputFieldEnumValue));\n\n if (entry != nullptr &&\n !IsRuntimeCompatible(entry->_type, RES_INT) &&\n !IsRuntimeCompatible(entry->_type, RES_DOUBLE) &&\n !IsRuntimeCompatible(entry->_type, RES_INT64) &&\n !IsRuntimeCompatible(entry->_type, RES_STRING) &&\n !IsRuntimeCompatible(entry->_type, RES_DATA)) {\n\n LOG(warning, \"cannot use docsum field '%s' as input to copy; type conflict with result class %d (%s)\",\n inputField, field.GetClassID(), field.GetClassName());\n return false;\n }\n }\n return true;\n}\n\nvoid\nCopyDFW::insertField(uint32_t \/*docid*\/, GeneralResult *gres, GetDocsumsState *, ResType type,\n vespalib::slime::Inserter &target)\n{\n int idx = gres->GetClass()->GetIndexFromEnumValue(_inputFieldEnumValue);\n ResEntry *entry = gres->GetEntry(idx);\n\n if (entry != nullptr &&\n IsRuntimeCompatible(entry->_type, type))\n {\n switch (type) {\n case RES_INT: {\n uint32_t val32 = entry->_intval;\n target.insertLong(val32);\n break; }\n\n case RES_SHORT: {\n uint16_t val16 = entry->_intval;\n target.insertLong(val16);\n break; }\n\n case RES_BYTE: {\n uint8_t val8 = entry->_intval;\n target.insertLong(val8);\n break; }\n case RES_BOOL: {\n target.insertBool(entry->_intval != 0);\n break; }\n\n case RES_FLOAT: {\n float valfloat = entry->_doubleval;\n target.insertDouble(valfloat);\n break; }\n\n case RES_DOUBLE: {\n double valdouble = entry->_doubleval;\n target.insertDouble(valdouble);\n break; }\n\n case RES_INT64: {\n uint64_t valint64 = entry->_int64val;\n target.insertLong(valint64);\n break; }\n\n case RES_JSONSTRING: {\n uint32_t len;\n const char *spt;\n \/\/ resolve field\n entry->_resolve_field(&spt, &len);\n if (len != 0) {\n \/\/ note: 'JSONSTRING' really means 'structured data'\n vespalib::Slime input_field_as_slime;\n size_t d = vespalib::slime::BinaryFormat::decode(vespalib::Memory(spt, len), input_field_as_slime);\n if (d != len) {\n LOG(warning, \"could not decode %u bytes: %zu bytes decoded\", len, d);\n }\n if (d != 0) {\n inject(input_field_as_slime.get(), target);\n }\n }\n break; }\n case RES_FEATUREDATA:\n case RES_LONG_STRING:\n case RES_STRING: {\n uint32_t len;\n const char *spt;\n \/\/ resolve field\n entry->_resolve_field(&spt, &len);\n vespalib::Memory value(spt, len);\n target.insertString(value);\n break; }\n\n case RES_TENSOR:\n case RES_LONG_DATA:\n case RES_DATA: {\n uint32_t len;\n const char *dpt;\n \/\/ resolve field\n entry->_resolve_field(&dpt, &len);\n vespalib::Memory value(dpt, len);\n target.insertData(value);\n break; }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\copyright (c) RDO-Team, 2003-2012\n \\file app\/rdo_studio_mfc\/src\/chart\/document.cpp\n \\author \n \\date 20.02.2003\n \\brief \n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"app\/rdo_studio_mfc\/src\/chart\/document.h\"\n#include \"app\/rdo_studio_mfc\/src\/chart\/view.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracer.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracerserie.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracervalues.h\"\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\n#include \"app\/rdo_studio_mfc\/src\/main_frm.h\"\n\/\/ --------------------------------------------------------------------------------\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioChartDocInsertTime\n\/\/ --------------------------------------------------------------------------------\nclass RDOStudioChartDocInsertTime\n{\n\tRDOStudioChartDoc* doc;\npublic:\n\tRDOStudioChartDocInsertTime( RDOStudioChartDoc* _doc ): doc( _doc ) {};\n\tvoid operator ()( RDOTracerValue* val );\n};\n\nvoid RDOStudioChartDocInsertTime::operator ()( RDOTracerValue* val )\n{\n\tif( val ) {\n\t\ttimesList::iterator it = std::find_if( doc->inserted_it, doc->docTimes.end(), std::bind2nd( std::mem_fun1( &RDOTracerTimeNow::compareTimes ), val->modeltime ) );\n\t\tif ( it == doc->docTimes.end() || (*it) != val->modeltime ) {\n\t\t\tdoc->inserted_it = doc->docTimes.insert( it, val->modeltime );\n\t\t\tdoc->ticksCount += val->modeltime->eventCount;\n\t\t\tdouble offl = 1.7E+308;\n\t\t\tdouble offr = 1.7E+308;\n\t\t\tif ( it != doc->docTimes.end() )\n\t\t\t\toffr = (*it)->time - (*doc->inserted_it)->time;\n\t\t\tif ( doc->inserted_it != doc->docTimes.begin() ) {\n\t\t\t\toffl = (*doc->inserted_it)->time;\n\t\t\t\ttimesList::iterator prev_it = doc->inserted_it;\n\t\t\t\tprev_it --;\n\t\t\t\toffl -= (*prev_it)->time;\n\t\t\t}\n\t\t\tdouble minoff = min( offl, offr );\n\t\t\tif ( minoff < doc->minTimeOffset )\n\t\t\t\tdoc->minTimeOffset = minoff;\n\t\t}\n\t}\n\t\/\/studioApp.m_pMainFrame->stepProgress();\n}\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioChartDoc\n\/\/ --------------------------------------------------------------------------------\nIMPLEMENT_DYNCREATE(RDOStudioChartDoc, CDocument)\n\nBEGIN_MESSAGE_MAP(RDOStudioChartDoc, CDocument)\nEND_MESSAGE_MAP()\n\nRDOStudioChartDoc::RDOStudioChartDoc( const rbool preview )\n\t: CDocument(),\n\tminTimeOffset( 1.7E+308 ),\n\tticksCount( 0 ),\n\tpreviewMode( preview )\n{\n\tif ( !previewMode )\n\t\ttracer->addChart( this );\n}\n\nRDOStudioChartDoc::~RDOStudioChartDoc()\n{\n\ttracer->lock();\n\n\tmutex.Lock();\n\n\tfor ( std::vector< RDOStudioDocSerie* >::iterator it = series.begin(); it != series.end(); it++ ) {\n\t\t(*it)->serie->removeFromDoc( this );\n\t\tdelete (*it);\n\t}\n\tif ( !previewMode )\n\t\ttracer->removeChart( this );\n\n\tmutex.Unlock();\n\n\ttracer->unlock();\n}\n\nint RDOStudioChartDoc::getSerieIndex( RDOStudioDocSerie* serie ) const\n{\n\tint res = -1;\n\tint index = 0;\n\tfor ( std::vector< RDOStudioDocSerie* >::const_iterator it = series.begin(); it != series.end(); it++ ) {\n\t\tif ( serie == (*it) )\n\t\t\tres = index;\n\t\tindex ++;\n\t}\n\treturn res;\n}\n\nBOOL RDOStudioChartDoc::OnNewDocument()\n{\n\tif ( !CDocument::OnNewDocument() ) return FALSE;\n\treturn TRUE;\n}\n\nvoid RDOStudioChartDoc::Serialize(CArchive& ar)\n{\n\tif ( ar.IsStoring() ) {\n\t}\n\telse {\n\t}\n}\n\nvoid RDOStudioChartDoc::incTimeEventsCount( RDOTracerTimeNow* time )\n{\n\t\/\/mutex.Lock(); Document is locked from RDOTracerBase::addTime\n\n\tif ( docTimes.back() == time ) {\n\t\tticksCount ++;\n\t\tupdateChartViews( UPDATE_TIMETICKS );\n\t}\n\n\t\/\/mutex.Unlock();\n}\n\nrbool RDOStudioChartDoc::newValueToSerieAdded( RDOTracerValue* val )\n{\n\t\/\/mutex.Lock(); Document is locked from RDOTracerSerie::addValue\n\t\n\tif ( docTimes.empty() ) {\n\t\tdocTimes.push_back( val->modeltime );\n\t\tticksCount += val->modeltime->eventCount;\n\t} else {\n\t\tRDOTracerTimeNow* last = docTimes.back();\n\t\tif ( last != val->modeltime ) {\n\t\t\tdocTimes.push_back( val->modeltime );\n\t\t\tticksCount += val->modeltime->eventCount;\n\t\t\tdouble off = val->modeltime->time - last->time;\n\t\t\tif ( off < minTimeOffset )\n\t\t\t\tminTimeOffset = off;\n\t\t}\n\t}\n\tupdateChartViews( UPDATE_NEWVALUE );\n\n\t\/\/mutex.Unlock();\n\n\treturn true;\n}\n\nint RDOStudioChartDoc::getMaxMarkerSize() const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\t\n\tint res = 0;\n\tfor ( std::vector< RDOStudioDocSerie* >::const_iterator it = series.begin(); it != series.end(); it++ ) {\n\t\tif ( (*it)->needDrawMarker && (*it)->marker_size > res ) res = (*it)->marker_size;\n\t}\n\n\tconst_cast<CMutex&>(mutex).Unlock();\n\n\treturn res;\n}\n\nvoid RDOStudioChartDoc::addToViews( const HWND handle )\n{\n\tmutex.Lock();\n\n\tviews_hwnd.push_back( handle );\n\n\tmutex.Unlock();\n}\n\nvoid RDOStudioChartDoc::removeFromViews( const HWND handle )\n{\n\tmutex.Lock();\n\n\tstd::vector< HWND >::iterator it = std::find( views_hwnd.begin(), views_hwnd.end(), handle );\n\tif ( it != views_hwnd.end() )\n\t\tviews_hwnd.erase( it );\n\n\tmutex.Unlock();\n}\n\nvoid RDOStudioChartDoc::updateChartViews( const UINT update_type ) const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\n\tfor( std::vector< HWND >::const_iterator it = views_hwnd.begin(); it != views_hwnd.end(); it++ ) {\n\t\t::SendNotifyMessage( (*it), WM_USER_UPDATE_CHART_VIEW, WPARAM( update_type ), 0 );\n\t}\n\t\n\tconst_cast<CMutex&>(mutex).Unlock();\n}\n\nvoid RDOStudioChartDoc::addSerie( RDOTracerSerie* const serie )\n{\n\tmutex.Lock();\n\t\n\tif ( serie && !serieExists( serie ) ) {\n\t\tRDOStudioDocSerie* docserie = new RDOStudioDocSerie( serie );\n\t\tdocserie->lock();\n\t\tdocserie->color = selectColor();\n\t\tdocserie->marker = selectMarker();\n\t\tseries.push_back( docserie );\n\t\tinserted_it = docTimes.begin();\n\n\t\tif ( !docTimes.empty() && !serie->empty() ) {\n\t\t\ttimesList::iterator last_doc = docTimes.end();\n\t\t\tlast_doc --;\n\t\t\tvaluesList::const_iterator first_serie = serie->begin();\n\t\t\tif ( (*first_serie)->modeltime->time >= (*last_doc)->time ) {\n\t\t\t\tinserted_it = docTimes.end();\n\t\t\t\tif ( (*first_serie)->modeltime->time == (*last_doc)->time ) {\n\t\t\t\t\tinserted_it = last_doc;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tstudioApp.BeginWaitCursor();\n\t\t\t\n\t\t\t\/\/int count;\n\t\t\t\/\/serie->getValueCount( count );\n\t\t\t\/\/studioApp.m_pMainFrame->beginProgress( 0, count );\n\n\t\t\tstd::for_each( serie->begin(), serie->end(), RDOStudioChartDocInsertTime( this ) );\n\n\t\t\t\/\/studioApp.m_pMainFrame->endProgress();\n\t\t\tstudioApp.EndWaitCursor();\n\t\t} catch( ... ) {\n\t\t\tstudioApp.EndWaitCursor();\n\t\t}\n\n\t\tserie->addToDoc( this );\n\t\tif ( series.size() == 1 ) {\n\t\t\tPOSITION pos = GetFirstViewPosition();\n\t\t\twhile (pos != NULL) {\n\t\t\t\tCView* pView = GetNextView( pos );\n\t\t\t\tif ( pView && pView->IsKindOf( RUNTIME_CLASS(RDOStudioChartView) ) )\n\t\t\t\t\tstatic_cast<RDOStudioChartView*>( pView )->yAxis = docserie;\n\t\t\t}\n\t\t}\n\t\tdocserie->unlock();\n\t\tupdateChartViews( UPDATE_NEWSERIE );\n\t}\n\n\tmutex.Unlock();\n}\n\n\/*void RDOStudioChartDoc::removeSerie( RDOTracerSerie* const serie )\n{\n\tif ( !serie ) return;\n\tvector<RDOStudioDocSerie*>::iterator it = find_if( series.begin(), series.end(), bind2nd( mem_fun1(&RDOStudioDocSerie::isTracerSerie), serie ) );\n\tif ( it != series.end() ) {\n\t\t(*it)->serie->removeFromDoc( this );\n\t\t\/\/must be recalc of minTimeOffset && tickscount\n\t\tdelete (*it);\n\t\tseries.erase( it );\n\t\tupdateChartViews();\n\t}\n}*\/\n\nCOLORREF RDOStudioChartDoc::selectColor()\n{\n\tint count = series.size();\n\tint mul = count \/ 15;\n\tint index = count - mul * 16;\n\tCOLORREF res = RGB( 0, 0, 0 );\n\tswitch ( index ) {\n\t\tcase 0 : res = RGB( 0x00, 0x80, 0x00 ); break;\n\t\tcase 1 : res = RGB( 0x00, 0x00, 0x80 ); break;\n\t\tcase 2 : res = RGB( 0x80, 0x80, 0x80 ); break;\n\t\tcase 3 : res = RGB( 0x80, 0x00, 0x80 ); break;\n\t\tcase 4 : res = RGB( 0xFF, 0x00, 0x00 ); break;\n\t\tcase 5 : res = RGB( 0x00, 0xFF, 0x00 ); break;\n\t\tcase 6 : res = RGB( 0x00, 0x00, 0x00 ); break;\n\t\tcase 7 : res = RGB( 0x80, 0x80, 0x00 ); break;\n\t\tcase 8 : res = RGB( 0xC0, 0xC0, 0xC0 ); break;\n\t\tcase 9 : res = RGB( 0x80, 0x00, 0x00 ); break;\n\t\tcase 10 : res = RGB( 0x00, 0x80, 0x80 ); break;\n\t\tcase 11 : res = RGB( 0xFF, 0xFF, 0x00 ); break;\n\t\tcase 12 : res = RGB( 0x00, 0x00, 0xFF ); break;\n\t\tcase 13 : res = RGB( 0xFF, 0x00, 0xFF ); break;\n\t\tcase 14 : res = RGB( 0x00, 0xFF, 0xFF ); break;\n\t};\n\treturn res;\n}\n\nRDOTracerSerieMarker RDOStudioChartDoc::selectMarker()\n{\n\tint count = series.size();\n\tint mul = count \/ 4;\n\tint index = count - mul * 4;\n\tRDOTracerSerieMarker res = RDOSM_CIRCLE;\n\tswitch ( index ) {\n\t\tcase 0 : res = RDOSM_CIRCLE; break;\n\t\tcase 1 : res = RDOSM_SQUARE; break;\n\t\tcase 2 : res = RDOSM_RHOMB; break;\n\t\tcase 3 : res = RDOSM_CROSS; break;\n\t};\n\treturn res;\n}\n\nrbool RDOStudioChartDoc::serieExists( const RDOTracerSerie* serie ) const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\n\trbool res = std::find_if( series.begin(), series.end(), std::bind2nd( std::mem_fun1(&RDOStudioDocSerie::isTracerSerie), serie ) ) != series.end();\n\n\tconst_cast<CMutex&>(mutex).Unlock();\n\n\treturn res;\n}\n\nvoid RDOStudioChartDoc::SetTitle( LPCTSTR lpszTitle )\n{\n\ttitle = lpszTitle;\n\tCDocument::SetTitle( rdo::format( IDS_CHART_TITLE, title.c_str() ).c_str() );\n}\n\n#ifdef _DEBUG\nvoid RDOStudioChartDoc::AssertValid() const\n{\n\tCDocument::AssertValid();\n}\n\nvoid RDOStudioChartDoc::Dump(CDumpContext& dc) const\n{\n\tCDocument::Dump(dc);\n}\n#endif \/\/_DEBUG<commit_msg> - исправлено падение при построении графика по нетрассируемой переменной<commit_after>\/*!\n \\copyright (c) RDO-Team, 2003-2012\n \\file app\/rdo_studio_mfc\/src\/chart\/document.cpp\n \\author \n \\date 20.02.2003\n \\brief \n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"app\/rdo_studio_mfc\/src\/chart\/document.h\"\n#include \"app\/rdo_studio_mfc\/src\/chart\/view.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracer.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracerserie.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracervalues.h\"\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\n#include \"app\/rdo_studio_mfc\/src\/main_frm.h\"\n\/\/ --------------------------------------------------------------------------------\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioChartDocInsertTime\n\/\/ --------------------------------------------------------------------------------\nclass RDOStudioChartDocInsertTime\n{\n\tRDOStudioChartDoc* doc;\npublic:\n\tRDOStudioChartDocInsertTime( RDOStudioChartDoc* _doc ): doc( _doc ) {};\n\tvoid operator ()( RDOTracerValue* val );\n};\n\nvoid RDOStudioChartDocInsertTime::operator ()( RDOTracerValue* val )\n{\n\tif( val ) {\n\t\ttimesList::iterator it = std::find_if( doc->inserted_it, doc->docTimes.end(), std::bind2nd( std::mem_fun1( &RDOTracerTimeNow::compareTimes ), val->modeltime ) );\n\t\tif ( it == doc->docTimes.end() || (*it) != val->modeltime ) {\n\t\t\tdoc->inserted_it = doc->docTimes.insert( it, val->modeltime );\n\t\t\tdoc->ticksCount += val->modeltime->eventCount;\n\t\t\tdouble offl = 1.7E+308;\n\t\t\tdouble offr = 1.7E+308;\n\t\t\tif ( it != doc->docTimes.end() )\n\t\t\t\toffr = (*it)->time - (*doc->inserted_it)->time;\n\t\t\tif ( doc->inserted_it != doc->docTimes.begin() ) {\n\t\t\t\toffl = (*doc->inserted_it)->time;\n\t\t\t\ttimesList::iterator prev_it = doc->inserted_it;\n\t\t\t\tprev_it --;\n\t\t\t\toffl -= (*prev_it)->time;\n\t\t\t}\n\t\t\tdouble minoff = min( offl, offr );\n\t\t\tif ( minoff < doc->minTimeOffset )\n\t\t\t\tdoc->minTimeOffset = minoff;\n\t\t}\n\t}\n\t\/\/studioApp.m_pMainFrame->stepProgress();\n}\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioChartDoc\n\/\/ --------------------------------------------------------------------------------\nIMPLEMENT_DYNCREATE(RDOStudioChartDoc, CDocument)\n\nBEGIN_MESSAGE_MAP(RDOStudioChartDoc, CDocument)\nEND_MESSAGE_MAP()\n\nRDOStudioChartDoc::RDOStudioChartDoc( const rbool preview )\n\t: CDocument(),\n\tminTimeOffset( 1.7E+308 ),\n\tticksCount( 0 ),\n\tpreviewMode( preview )\n{\n\tif ( !previewMode )\n\t\ttracer->addChart( this );\n}\n\nRDOStudioChartDoc::~RDOStudioChartDoc()\n{\n\ttracer->lock();\n\n\tmutex.Lock();\n\n\tfor ( std::vector< RDOStudioDocSerie* >::iterator it = series.begin(); it != series.end(); it++ ) {\n\t\t(*it)->serie->removeFromDoc( this );\n\t\tdelete (*it);\n\t}\n\tif ( !previewMode )\n\t\ttracer->removeChart( this );\n\n\tmutex.Unlock();\n\n\ttracer->unlock();\n}\n\nint RDOStudioChartDoc::getSerieIndex( RDOStudioDocSerie* serie ) const\n{\n\tint res = -1;\n\tint index = 0;\n\tfor ( std::vector< RDOStudioDocSerie* >::const_iterator it = series.begin(); it != series.end(); it++ ) {\n\t\tif ( serie == (*it) )\n\t\t\tres = index;\n\t\tindex ++;\n\t}\n\treturn res;\n}\n\nBOOL RDOStudioChartDoc::OnNewDocument()\n{\n\tif ( !CDocument::OnNewDocument() ) return FALSE;\n\treturn TRUE;\n}\n\nvoid RDOStudioChartDoc::Serialize(CArchive& ar)\n{\n\tif ( ar.IsStoring() ) {\n\t}\n\telse {\n\t}\n}\n\nvoid RDOStudioChartDoc::incTimeEventsCount( RDOTracerTimeNow* time )\n{\n\t\/\/mutex.Lock(); Document is locked from RDOTracerBase::addTime\n\n\tif ( !docTimes.empty() && docTimes.back() == time ) {\n\t\tticksCount ++;\n\t\tupdateChartViews( UPDATE_TIMETICKS );\n\t}\n\n\t\/\/mutex.Unlock();\n}\n\nrbool RDOStudioChartDoc::newValueToSerieAdded( RDOTracerValue* val )\n{\n\t\/\/mutex.Lock(); Document is locked from RDOTracerSerie::addValue\n\t\n\tif ( docTimes.empty() ) {\n\t\tdocTimes.push_back( val->modeltime );\n\t\tticksCount += val->modeltime->eventCount;\n\t} else {\n\t\tRDOTracerTimeNow* last = docTimes.back();\n\t\tif ( last != val->modeltime ) {\n\t\t\tdocTimes.push_back( val->modeltime );\n\t\t\tticksCount += val->modeltime->eventCount;\n\t\t\tdouble off = val->modeltime->time - last->time;\n\t\t\tif ( off < minTimeOffset )\n\t\t\t\tminTimeOffset = off;\n\t\t}\n\t}\n\tupdateChartViews( UPDATE_NEWVALUE );\n\n\t\/\/mutex.Unlock();\n\n\treturn true;\n}\n\nint RDOStudioChartDoc::getMaxMarkerSize() const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\t\n\tint res = 0;\n\tfor ( std::vector< RDOStudioDocSerie* >::const_iterator it = series.begin(); it != series.end(); it++ ) {\n\t\tif ( (*it)->needDrawMarker && (*it)->marker_size > res ) res = (*it)->marker_size;\n\t}\n\n\tconst_cast<CMutex&>(mutex).Unlock();\n\n\treturn res;\n}\n\nvoid RDOStudioChartDoc::addToViews( const HWND handle )\n{\n\tmutex.Lock();\n\n\tviews_hwnd.push_back( handle );\n\n\tmutex.Unlock();\n}\n\nvoid RDOStudioChartDoc::removeFromViews( const HWND handle )\n{\n\tmutex.Lock();\n\n\tstd::vector< HWND >::iterator it = std::find( views_hwnd.begin(), views_hwnd.end(), handle );\n\tif ( it != views_hwnd.end() )\n\t\tviews_hwnd.erase( it );\n\n\tmutex.Unlock();\n}\n\nvoid RDOStudioChartDoc::updateChartViews( const UINT update_type ) const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\n\tfor( std::vector< HWND >::const_iterator it = views_hwnd.begin(); it != views_hwnd.end(); it++ ) {\n\t\t::SendNotifyMessage( (*it), WM_USER_UPDATE_CHART_VIEW, WPARAM( update_type ), 0 );\n\t}\n\t\n\tconst_cast<CMutex&>(mutex).Unlock();\n}\n\nvoid RDOStudioChartDoc::addSerie( RDOTracerSerie* const serie )\n{\n\tmutex.Lock();\n\t\n\tif ( serie && !serieExists( serie ) ) {\n\t\tRDOStudioDocSerie* docserie = new RDOStudioDocSerie( serie );\n\t\tdocserie->lock();\n\t\tdocserie->color = selectColor();\n\t\tdocserie->marker = selectMarker();\n\t\tseries.push_back( docserie );\n\t\tinserted_it = docTimes.begin();\n\n\t\tif ( !docTimes.empty() && !serie->empty() ) {\n\t\t\ttimesList::iterator last_doc = docTimes.end();\n\t\t\tlast_doc --;\n\t\t\tvaluesList::const_iterator first_serie = serie->begin();\n\t\t\tif ( (*first_serie)->modeltime->time >= (*last_doc)->time ) {\n\t\t\t\tinserted_it = docTimes.end();\n\t\t\t\tif ( (*first_serie)->modeltime->time == (*last_doc)->time ) {\n\t\t\t\t\tinserted_it = last_doc;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tstudioApp.BeginWaitCursor();\n\t\t\t\n\t\t\t\/\/int count;\n\t\t\t\/\/serie->getValueCount( count );\n\t\t\t\/\/studioApp.m_pMainFrame->beginProgress( 0, count );\n\n\t\t\tstd::for_each( serie->begin(), serie->end(), RDOStudioChartDocInsertTime( this ) );\n\n\t\t\t\/\/studioApp.m_pMainFrame->endProgress();\n\t\t\tstudioApp.EndWaitCursor();\n\t\t} catch( ... ) {\n\t\t\tstudioApp.EndWaitCursor();\n\t\t}\n\n\t\tserie->addToDoc( this );\n\t\tif ( series.size() == 1 ) {\n\t\t\tPOSITION pos = GetFirstViewPosition();\n\t\t\twhile (pos != NULL) {\n\t\t\t\tCView* pView = GetNextView( pos );\n\t\t\t\tif ( pView && pView->IsKindOf( RUNTIME_CLASS(RDOStudioChartView) ) )\n\t\t\t\t\tstatic_cast<RDOStudioChartView*>( pView )->yAxis = docserie;\n\t\t\t}\n\t\t}\n\t\tdocserie->unlock();\n\t\tupdateChartViews( UPDATE_NEWSERIE );\n\t}\n\n\tmutex.Unlock();\n}\n\n\/*void RDOStudioChartDoc::removeSerie( RDOTracerSerie* const serie )\n{\n\tif ( !serie ) return;\n\tvector<RDOStudioDocSerie*>::iterator it = find_if( series.begin(), series.end(), bind2nd( mem_fun1(&RDOStudioDocSerie::isTracerSerie), serie ) );\n\tif ( it != series.end() ) {\n\t\t(*it)->serie->removeFromDoc( this );\n\t\t\/\/must be recalc of minTimeOffset && tickscount\n\t\tdelete (*it);\n\t\tseries.erase( it );\n\t\tupdateChartViews();\n\t}\n}*\/\n\nCOLORREF RDOStudioChartDoc::selectColor()\n{\n\tint count = series.size();\n\tint mul = count \/ 15;\n\tint index = count - mul * 16;\n\tCOLORREF res = RGB( 0, 0, 0 );\n\tswitch ( index ) {\n\t\tcase 0 : res = RGB( 0x00, 0x80, 0x00 ); break;\n\t\tcase 1 : res = RGB( 0x00, 0x00, 0x80 ); break;\n\t\tcase 2 : res = RGB( 0x80, 0x80, 0x80 ); break;\n\t\tcase 3 : res = RGB( 0x80, 0x00, 0x80 ); break;\n\t\tcase 4 : res = RGB( 0xFF, 0x00, 0x00 ); break;\n\t\tcase 5 : res = RGB( 0x00, 0xFF, 0x00 ); break;\n\t\tcase 6 : res = RGB( 0x00, 0x00, 0x00 ); break;\n\t\tcase 7 : res = RGB( 0x80, 0x80, 0x00 ); break;\n\t\tcase 8 : res = RGB( 0xC0, 0xC0, 0xC0 ); break;\n\t\tcase 9 : res = RGB( 0x80, 0x00, 0x00 ); break;\n\t\tcase 10 : res = RGB( 0x00, 0x80, 0x80 ); break;\n\t\tcase 11 : res = RGB( 0xFF, 0xFF, 0x00 ); break;\n\t\tcase 12 : res = RGB( 0x00, 0x00, 0xFF ); break;\n\t\tcase 13 : res = RGB( 0xFF, 0x00, 0xFF ); break;\n\t\tcase 14 : res = RGB( 0x00, 0xFF, 0xFF ); break;\n\t};\n\treturn res;\n}\n\nRDOTracerSerieMarker RDOStudioChartDoc::selectMarker()\n{\n\tint count = series.size();\n\tint mul = count \/ 4;\n\tint index = count - mul * 4;\n\tRDOTracerSerieMarker res = RDOSM_CIRCLE;\n\tswitch ( index ) {\n\t\tcase 0 : res = RDOSM_CIRCLE; break;\n\t\tcase 1 : res = RDOSM_SQUARE; break;\n\t\tcase 2 : res = RDOSM_RHOMB; break;\n\t\tcase 3 : res = RDOSM_CROSS; break;\n\t};\n\treturn res;\n}\n\nrbool RDOStudioChartDoc::serieExists( const RDOTracerSerie* serie ) const\n{\n\tconst_cast<CMutex&>(mutex).Lock();\n\n\trbool res = std::find_if( series.begin(), series.end(), std::bind2nd( std::mem_fun1(&RDOStudioDocSerie::isTracerSerie), serie ) ) != series.end();\n\n\tconst_cast<CMutex&>(mutex).Unlock();\n\n\treturn res;\n}\n\nvoid RDOStudioChartDoc::SetTitle( LPCTSTR lpszTitle )\n{\n\ttitle = lpszTitle;\n\tCDocument::SetTitle( rdo::format( IDS_CHART_TITLE, title.c_str() ).c_str() );\n}\n\n#ifdef _DEBUG\nvoid RDOStudioChartDoc::AssertValid() const\n{\n\tCDocument::AssertValid();\n}\n\nvoid RDOStudioChartDoc::Dump(CDumpContext& dc) const\n{\n\tCDocument::Dump(dc);\n}\n#endif \/\/_DEBUG<|endoftext|>"} {"text":"<commit_before><commit_msg>avoid use of ref. to possibly deleted object<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: notemark.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2002-04-10 10:29:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_NOTEMARK_HXX\n#define SC_NOTEMARK_HXX\n\n#ifndef _MAPMOD_HXX \/\/autogen\n#include <vcl\/mapmod.hxx>\n#endif\n#ifndef _TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\nclass SdrModel;\nclass SdrObject;\n\nclass ScNoteMarker\n{\nprivate:\n Window* pWindow;\n Window* pRightWin;\n Window* pBottomWin;\n Window* pDiagWin;\n ScDocument* pDoc;\n ScAddress aDocPos;\n String aUserText;\n Timer aTimer;\n MapMode aMapMode;\n BOOL bLeft;\n BOOL bByKeyboard;\n\n Rectangle aRect;\n SdrModel* pModel;\n SdrObject* pObject;\n BOOL bVisible;\n\n DECL_LINK( TimeHdl, Timer* );\n\npublic:\n ScNoteMarker( Window* pWin,\n Window* pRight, Window* pBottom, Window* pDiagonal,\n ScDocument* pD, ScAddress aPos,\n const String& rUser, const MapMode& rMap,\n BOOL bLeftEdge, BOOL bForce, BOOL bKeyboard );\n ~ScNoteMarker();\n\n void Draw();\n void InvalidateWin();\n\n ScAddress GetDocPos() const { return aDocPos; }\n BOOL IsByKeyboard() const { return bByKeyboard; }\n};\n\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.2.310); FILE MERGED 2003\/11\/28 19:48:00 er 1.2.310.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>\/*************************************************************************\n *\n * $RCSfile: notemark.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:36:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_NOTEMARK_HXX\n#define SC_NOTEMARK_HXX\n\n#ifndef _MAPMOD_HXX \/\/autogen\n#include <vcl\/mapmod.hxx>\n#endif\n#ifndef _TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\nclass SdrModel;\nclass SdrObject;\n\nclass ScNoteMarker\n{\nprivate:\n Window* pWindow;\n Window* pRightWin;\n Window* pBottomWin;\n Window* pDiagWin;\n ScDocument* pDoc;\n ScAddress aDocPos;\n String aUserText;\n Timer aTimer;\n MapMode aMapMode;\n BOOL bLeft;\n BOOL bByKeyboard;\n\n Rectangle aRect;\n SdrModel* pModel;\n SdrObject* pObject;\n BOOL bVisible;\n\n DECL_LINK( TimeHdl, Timer* );\n\npublic:\n ScNoteMarker( Window* pWin,\n Window* pRight, Window* pBottom, Window* pDiagonal,\n ScDocument* pD, ScAddress aPos,\n const String& rUser, const MapMode& rMap,\n BOOL bLeftEdge, BOOL bForce, BOOL bKeyboard );\n ~ScNoteMarker();\n\n void Draw();\n void InvalidateWin();\n\n ScAddress GetDocPos() const { return aDocPos; }\n BOOL IsByKeyboard() const { return bByKeyboard; }\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>send mouse events to the OpenGL window<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include <fstream>\n#include <iomanip>\n#include <list>\n#include <map>\n#include <string>\n\n#include \"base\/callback.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/debug.hh\"\n#include \"base\/hostinfo.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/str.hh\"\n#include \"base\/time.hh\"\n#include \"base\/trace.hh\"\n\nusing namespace std;\n\nnamespace Stats {\n\nstd::string Info::separatorString = \"::\";\ntypedef map<const void *, Info *> MapType;\n\n\/\/ We wrap these in a function to make sure they're built in time.\nlist<Info *> &\nstatsList()\n{\n static list<Info *> the_list;\n return the_list;\n}\n\nMapType &\nstatsMap()\n{\n static MapType the_map;\n return the_map;\n}\n\nvoid\nInfoAccess::setInfo(Info *info)\n{\n if (statsMap().find(this) != statsMap().end())\n panic(\"shouldn't register stat twice!\");\n\n statsList().push_back(info);\n\n#ifndef NDEBUG\n pair<MapType::iterator, bool> result =\n#endif\n statsMap().insert(make_pair(this, info));\n assert(result.second && \"this should never fail\");\n assert(statsMap().find(this) != statsMap().end());\n}\n\nvoid\nInfoAccess::setParams(const StorageParams *params)\n{\n info()->storageParams = params;\n}\n\nvoid\nInfoAccess::setInit()\n{\n info()->flags.set(init);\n}\n\nInfo *\nInfoAccess::info()\n{\n MapType::const_iterator i = statsMap().find(this);\n assert(i != statsMap().end());\n return (*i).second;\n}\n\nconst Info *\nInfoAccess::info() const\n{\n MapType::const_iterator i = statsMap().find(this);\n assert(i != statsMap().end());\n return (*i).second;\n}\n\nStorageParams::~StorageParams()\n{\n}\n\ntypedef map<std::string, Info *> NameMapType;\nNameMapType &\nnameMap()\n{\n static NameMapType the_map;\n return the_map;\n}\n\nint Info::id_count = 0;\n\nint debug_break_id = -1;\n\nInfo::Info()\n : flags(none), precision(-1), prereq(0), storageParams(NULL)\n{\n id = id_count++;\n if (debug_break_id >= 0 and debug_break_id == id)\n Debug::breakpoint();\n}\n\nInfo::~Info()\n{\n}\n\nvoid\nInfo::setName(const string &name)\n{\n pair<NameMapType::iterator, bool> p =\n nameMap().insert(make_pair(name, this));\n\n Info *other = p.first->second;\n bool result = p.second;\n \n if (!result) {\n \/\/ using other->name instead of just name to avoid a compiler\n \/\/ warning. They should be the same.\n panic(\"same statistic name used twice! name=%s\\n\", other->name);\n }\n\n this->name = name;\n}\n\nbool\nInfo::less(Info *stat1, Info *stat2)\n{\n const string &name1 = stat1->name;\n const string &name2 = stat2->name;\n\n vector<string> v1;\n vector<string> v2;\n\n tokenize(v1, name1, '.');\n tokenize(v2, name2, '.');\n\n size_type last = min(v1.size(), v2.size()) - 1;\n for (off_type i = 0; i < last; ++i)\n if (v1[i] != v2[i])\n return v1[i] < v2[i];\n\n \/\/ Special compare for last element.\n if (v1[last] == v2[last])\n return v1.size() < v2.size();\n else\n return v1[last] < v2[last];\n\n return false;\n}\n\nbool\nInfo::baseCheck() const\n{\n if (!(flags & Stats::init)) {\n#ifdef DEBUG\n cprintf(\"this is stat number %d\\n\", id);\n#endif\n panic(\"Not all stats have been initialized\");\n return false;\n }\n\n if ((flags & display) && name.empty()) {\n panic(\"all printable stats must be named\");\n return false;\n }\n\n return true;\n}\n\nvoid\nInfo::enable()\n{\n}\n\nvoid\nVectorInfo::enable()\n{\n size_type s = size();\n if (subnames.size() < s)\n subnames.resize(s);\n if (subdescs.size() < s)\n subdescs.resize(s);\n}\n\nvoid\nVectorDistInfo::enable()\n{\n size_type s = size();\n if (subnames.size() < s)\n subnames.resize(s);\n if (subdescs.size() < s)\n subdescs.resize(s);\n}\n\nvoid\nVector2dInfo::enable()\n{\n if (subnames.size() < x)\n subnames.resize(x);\n if (subdescs.size() < x)\n subdescs.resize(x);\n if (y_subnames.size() < y)\n y_subnames.resize(y);\n}\n\nvoid\nHistStor::grow_out()\n{\n int size = cvec.size();\n int zero = size \/ 2; \/\/ round down!\n int top_half = zero + (size - zero + 1) \/ 2; \/\/ round up!\n int bottom_half = (size - zero) \/ 2; \/\/ round down!\n\n \/\/ grow down\n int low_pair = zero - 1;\n for (int i = zero - 1; i >= bottom_half; i--) {\n cvec[i] = cvec[low_pair];\n if (low_pair - 1 >= 0)\n cvec[i] += cvec[low_pair - 1];\n low_pair -= 2;\n }\n assert(low_pair == 0 || low_pair == -1 || low_pair == -2);\n\n for (int i = bottom_half - 1; i >= 0; i--)\n cvec[i] = Counter();\n\n \/\/ grow up\n int high_pair = zero;\n for (int i = zero; i < top_half; i++) {\n cvec[i] = cvec[high_pair];\n if (high_pair + 1 < size)\n cvec[i] += cvec[high_pair + 1];\n high_pair += 2;\n }\n assert(high_pair == size || high_pair == size + 1);\n\n for (int i = top_half; i < size; i++)\n cvec[i] = Counter();\n\n max_bucket *= 2;\n min_bucket *= 2;\n bucket_size *= 2;\n}\n\nvoid\nHistStor::grow_convert()\n{\n int size = cvec.size();\n int half = (size + 1) \/ 2; \/\/ round up!\n \/\/bool even = (size & 1) == 0;\n\n int pair = size - 1;\n for (int i = size - 1; i >= half; --i) {\n cvec[i] = cvec[pair];\n if (pair - 1 >= 0)\n cvec[i] += cvec[pair - 1];\n pair -= 2;\n }\n\n for (int i = half - 1; i >= 0; i--)\n cvec[i] = Counter();\n\n min_bucket = -max_bucket;\/\/ - (even ? bucket_size : 0);\n bucket_size *= 2;\n}\n\nvoid\nHistStor::grow_up()\n{\n int size = cvec.size();\n int half = (size + 1) \/ 2; \/\/ round up!\n\n int pair = 0;\n for (int i = 0; i < half; i++) {\n cvec[i] = cvec[pair];\n if (pair + 1 < size)\n cvec[i] += cvec[pair + 1];\n pair += 2;\n }\n assert(pair == size || pair == size + 1);\n\n for (int i = half; i < size; i++)\n cvec[i] = Counter();\n\n max_bucket *= 2;\n bucket_size *= 2;\n}\n\nFormula::Formula()\n{\n}\n\nFormula::Formula(Temp r)\n{\n root = r;\n setInit();\n assert(size());\n}\n\nconst Formula &\nFormula::operator=(Temp r)\n{\n assert(!root && \"Can't change formulas\");\n root = r;\n setInit();\n assert(size());\n return *this;\n}\n\nconst Formula &\nFormula::operator+=(Temp r)\n{\n if (root)\n root = NodePtr(new BinaryNode<std::plus<Result> >(root, r));\n else {\n root = r;\n setInit();\n }\n\n assert(size());\n return *this;\n}\n\nvoid\nFormula::result(VResult &vec) const\n{\n if (root)\n vec = root->result();\n}\n\nResult\nFormula::total() const\n{\n return root ? root->total() : 0.0;\n}\n\nsize_type\nFormula::size() const\n{\n if (!root)\n return 0;\n else\n return root->size();\n}\n\nvoid\nFormula::reset()\n{\n}\n\nbool\nFormula::zero() const\n{\n VResult vec;\n result(vec);\n for (VResult::size_type i = 0; i < vec.size(); ++i)\n if (vec[i] != 0.0)\n return false;\n return true;\n}\n\nstring\nFormula::str() const\n{\n return root ? root->str() : \"\";\n}\n\nvoid\nenable()\n{\n typedef list<Info *>::iterator iter_t;\n\n iter_t i, end = statsList().end();\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n assert(info);\n if (!info->check() || !info->baseCheck())\n panic(\"stat check failed for '%s' %d\\n\", info->name, info->id);\n }\n\n off_t j = 0;\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n if (!(info->flags & display))\n info->name = \"__Stat\" + to_string(j++);\n }\n\n statsList().sort(Info::less);\n\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n info->enable();\n }\n}\n\nvoid\nprepare()\n{\n list<Info *>::iterator i = statsList().begin();\n list<Info *>::iterator end = statsList().end();\n while (i != end) {\n Info *info = *i;\n info->prepare();\n ++i;\n }\n}\n\nCallbackQueue resetQueue;\n\nvoid\nreset()\n{\n list<Info *>::iterator i = statsList().begin();\n list<Info *>::iterator end = statsList().end();\n while (i != end) {\n Info *info = *i;\n info->reset();\n ++i;\n }\n\n resetQueue.process();\n}\n\nvoid\nregisterResetCallback(Callback *cb)\n{\n resetQueue.add(cb);\n}\n\n} \/\/ namespace Stats\n<commit_msg>stats: ensure that stat names are valid<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include <fstream>\n#include <iomanip>\n#include <list>\n#include <map>\n#include <string>\n\n#include \"base\/callback.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/debug.hh\"\n#include \"base\/hostinfo.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/str.hh\"\n#include \"base\/time.hh\"\n#include \"base\/trace.hh\"\n\nusing namespace std;\n\nnamespace Stats {\n\nstd::string Info::separatorString = \"::\";\ntypedef map<const void *, Info *> MapType;\n\n\/\/ We wrap these in a function to make sure they're built in time.\nlist<Info *> &\nstatsList()\n{\n static list<Info *> the_list;\n return the_list;\n}\n\nMapType &\nstatsMap()\n{\n static MapType the_map;\n return the_map;\n}\n\nvoid\nInfoAccess::setInfo(Info *info)\n{\n if (statsMap().find(this) != statsMap().end())\n panic(\"shouldn't register stat twice!\");\n\n statsList().push_back(info);\n\n#ifndef NDEBUG\n pair<MapType::iterator, bool> result =\n#endif\n statsMap().insert(make_pair(this, info));\n assert(result.second && \"this should never fail\");\n assert(statsMap().find(this) != statsMap().end());\n}\n\nvoid\nInfoAccess::setParams(const StorageParams *params)\n{\n info()->storageParams = params;\n}\n\nvoid\nInfoAccess::setInit()\n{\n info()->flags.set(init);\n}\n\nInfo *\nInfoAccess::info()\n{\n MapType::const_iterator i = statsMap().find(this);\n assert(i != statsMap().end());\n return (*i).second;\n}\n\nconst Info *\nInfoAccess::info() const\n{\n MapType::const_iterator i = statsMap().find(this);\n assert(i != statsMap().end());\n return (*i).second;\n}\n\nStorageParams::~StorageParams()\n{\n}\n\ntypedef map<std::string, Info *> NameMapType;\nNameMapType &\nnameMap()\n{\n static NameMapType the_map;\n return the_map;\n}\n\nint Info::id_count = 0;\n\nint debug_break_id = -1;\n\nInfo::Info()\n : flags(none), precision(-1), prereq(0), storageParams(NULL)\n{\n id = id_count++;\n if (debug_break_id >= 0 and debug_break_id == id)\n Debug::breakpoint();\n}\n\nInfo::~Info()\n{\n}\n\nbool\nvalidateStatName(const string &name)\n{\n if (name.empty())\n return false;\n\n vector<string> vec;\n tokenize(vec, name, '.');\n vector<string>::const_iterator item = vec.begin();\n while (item != vec.end()) {\n if (item->empty())\n return false;\n\n string::const_iterator c = item->begin();\n\n \/\/ The first character is different\n if (!isalpha(*c) && *c != '_')\n return false;\n\n \/\/ The rest of the characters have different rules.\n while (++c != item->end()) {\n if (!isalnum(*c) && *c != '_')\n return false;\n }\n\n ++item;\n }\n\n return true;\n}\n\nvoid\nInfo::setName(const string &name)\n{\n if (!validateStatName(name))\n panic(\"invalid stat name '%s'\", name);\n\n pair<NameMapType::iterator, bool> p =\n nameMap().insert(make_pair(name, this));\n\n Info *other = p.first->second;\n bool result = p.second;\n \n if (!result) {\n \/\/ using other->name instead of just name to avoid a compiler\n \/\/ warning. They should be the same.\n panic(\"same statistic name used twice! name=%s\\n\", other->name);\n }\n\n this->name = name;\n}\n\nbool\nInfo::less(Info *stat1, Info *stat2)\n{\n const string &name1 = stat1->name;\n const string &name2 = stat2->name;\n\n vector<string> v1;\n vector<string> v2;\n\n tokenize(v1, name1, '.');\n tokenize(v2, name2, '.');\n\n size_type last = min(v1.size(), v2.size()) - 1;\n for (off_type i = 0; i < last; ++i)\n if (v1[i] != v2[i])\n return v1[i] < v2[i];\n\n \/\/ Special compare for last element.\n if (v1[last] == v2[last])\n return v1.size() < v2.size();\n else\n return v1[last] < v2[last];\n\n return false;\n}\n\nbool\nInfo::baseCheck() const\n{\n if (!(flags & Stats::init)) {\n#ifdef DEBUG\n cprintf(\"this is stat number %d\\n\", id);\n#endif\n panic(\"Not all stats have been initialized\");\n return false;\n }\n\n if ((flags & display) && name.empty()) {\n panic(\"all printable stats must be named\");\n return false;\n }\n\n return true;\n}\n\nvoid\nInfo::enable()\n{\n}\n\nvoid\nVectorInfo::enable()\n{\n size_type s = size();\n if (subnames.size() < s)\n subnames.resize(s);\n if (subdescs.size() < s)\n subdescs.resize(s);\n}\n\nvoid\nVectorDistInfo::enable()\n{\n size_type s = size();\n if (subnames.size() < s)\n subnames.resize(s);\n if (subdescs.size() < s)\n subdescs.resize(s);\n}\n\nvoid\nVector2dInfo::enable()\n{\n if (subnames.size() < x)\n subnames.resize(x);\n if (subdescs.size() < x)\n subdescs.resize(x);\n if (y_subnames.size() < y)\n y_subnames.resize(y);\n}\n\nvoid\nHistStor::grow_out()\n{\n int size = cvec.size();\n int zero = size \/ 2; \/\/ round down!\n int top_half = zero + (size - zero + 1) \/ 2; \/\/ round up!\n int bottom_half = (size - zero) \/ 2; \/\/ round down!\n\n \/\/ grow down\n int low_pair = zero - 1;\n for (int i = zero - 1; i >= bottom_half; i--) {\n cvec[i] = cvec[low_pair];\n if (low_pair - 1 >= 0)\n cvec[i] += cvec[low_pair - 1];\n low_pair -= 2;\n }\n assert(low_pair == 0 || low_pair == -1 || low_pair == -2);\n\n for (int i = bottom_half - 1; i >= 0; i--)\n cvec[i] = Counter();\n\n \/\/ grow up\n int high_pair = zero;\n for (int i = zero; i < top_half; i++) {\n cvec[i] = cvec[high_pair];\n if (high_pair + 1 < size)\n cvec[i] += cvec[high_pair + 1];\n high_pair += 2;\n }\n assert(high_pair == size || high_pair == size + 1);\n\n for (int i = top_half; i < size; i++)\n cvec[i] = Counter();\n\n max_bucket *= 2;\n min_bucket *= 2;\n bucket_size *= 2;\n}\n\nvoid\nHistStor::grow_convert()\n{\n int size = cvec.size();\n int half = (size + 1) \/ 2; \/\/ round up!\n \/\/bool even = (size & 1) == 0;\n\n int pair = size - 1;\n for (int i = size - 1; i >= half; --i) {\n cvec[i] = cvec[pair];\n if (pair - 1 >= 0)\n cvec[i] += cvec[pair - 1];\n pair -= 2;\n }\n\n for (int i = half - 1; i >= 0; i--)\n cvec[i] = Counter();\n\n min_bucket = -max_bucket;\/\/ - (even ? bucket_size : 0);\n bucket_size *= 2;\n}\n\nvoid\nHistStor::grow_up()\n{\n int size = cvec.size();\n int half = (size + 1) \/ 2; \/\/ round up!\n\n int pair = 0;\n for (int i = 0; i < half; i++) {\n cvec[i] = cvec[pair];\n if (pair + 1 < size)\n cvec[i] += cvec[pair + 1];\n pair += 2;\n }\n assert(pair == size || pair == size + 1);\n\n for (int i = half; i < size; i++)\n cvec[i] = Counter();\n\n max_bucket *= 2;\n bucket_size *= 2;\n}\n\nFormula::Formula()\n{\n}\n\nFormula::Formula(Temp r)\n{\n root = r;\n setInit();\n assert(size());\n}\n\nconst Formula &\nFormula::operator=(Temp r)\n{\n assert(!root && \"Can't change formulas\");\n root = r;\n setInit();\n assert(size());\n return *this;\n}\n\nconst Formula &\nFormula::operator+=(Temp r)\n{\n if (root)\n root = NodePtr(new BinaryNode<std::plus<Result> >(root, r));\n else {\n root = r;\n setInit();\n }\n\n assert(size());\n return *this;\n}\n\nvoid\nFormula::result(VResult &vec) const\n{\n if (root)\n vec = root->result();\n}\n\nResult\nFormula::total() const\n{\n return root ? root->total() : 0.0;\n}\n\nsize_type\nFormula::size() const\n{\n if (!root)\n return 0;\n else\n return root->size();\n}\n\nvoid\nFormula::reset()\n{\n}\n\nbool\nFormula::zero() const\n{\n VResult vec;\n result(vec);\n for (VResult::size_type i = 0; i < vec.size(); ++i)\n if (vec[i] != 0.0)\n return false;\n return true;\n}\n\nstring\nFormula::str() const\n{\n return root ? root->str() : \"\";\n}\n\nvoid\nenable()\n{\n typedef list<Info *>::iterator iter_t;\n\n iter_t i, end = statsList().end();\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n assert(info);\n if (!info->check() || !info->baseCheck())\n panic(\"stat check failed for '%s' %d\\n\", info->name, info->id);\n }\n\n off_t j = 0;\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n if (!(info->flags & display))\n info->name = \"__Stat\" + to_string(j++);\n }\n\n statsList().sort(Info::less);\n\n for (i = statsList().begin(); i != end; ++i) {\n Info *info = *i;\n info->enable();\n }\n}\n\nvoid\nprepare()\n{\n list<Info *>::iterator i = statsList().begin();\n list<Info *>::iterator end = statsList().end();\n while (i != end) {\n Info *info = *i;\n info->prepare();\n ++i;\n }\n}\n\nCallbackQueue resetQueue;\n\nvoid\nreset()\n{\n list<Info *>::iterator i = statsList().begin();\n list<Info *>::iterator end = statsList().end();\n while (i != end) {\n Info *info = *i;\n info->reset();\n ++i;\n }\n\n resetQueue.process();\n}\n\nvoid\nregisterResetCallback(Callback *cb)\n{\n resetQueue.add(cb);\n}\n\n} \/\/ namespace Stats\n<|endoftext|>"} {"text":"<commit_before>#define WIN32_LEAN_AND_MEAN\n#define STRICT_GS_ENABLED\n#define _ATL_NO_AUTOMATIC_NAMESPACE\n#define _ATL_NO_DEFAULT_LIBS\n#define _ATL_NO_WIN_SUPPORT\n#define _CRTDBG_MAP_ALLOC\n#include <atlbase.h>\n#include <windows.h>\n#include <winioctl.h>\n#include <algorithm>\n#include \"reflink.h\"\n#include <crtdbg.h>\n\nconstexpr LONG64 inline ROUNDUP(LONG64 file_size, ULONG cluster_size) noexcept\n{\n\treturn (file_size + cluster_size - 1) \/ cluster_size * cluster_size;\n}\nstatic_assert(ROUNDUP(5678, 4 * 1024) == 8 * 1024);\n_Success_(return == true)\nbool reflink(_In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath)\n{\n\tATL::CHandle source(CreateFileW(oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr));\n\tif (source == INVALID_HANDLE_VALUE)\n\t{\n\t\tsource.Detach();\n\t\treturn false;\n\t}\n\n\tULONG fs_flags;\n\tif (!GetVolumeInformationByHandleW(source, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0))\n\t{\n\t\treturn false;\n\t}\n\tif (!(fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING))\n\t{\n\t\tSetLastError(ERROR_NOT_CAPABLE);\n\t\treturn false;\n\t}\n\n\tFILE_END_OF_FILE_INFO file_size;\n\tif (!GetFileSizeEx(source, &file_size.EndOfFile))\n\t{\n\t\treturn false;\n\t}\n\tFILE_BASIC_INFO file_basic;\n\tif (!GetFileInformationByHandleEx(source, FileBasicInfo, &file_basic, sizeof file_basic))\n\t{\n\t\treturn false;\n\t}\n\tULONG junk;\n\tFSCTL_GET_INTEGRITY_INFORMATION_BUFFER get_integrity;\n\tif (!DeviceIoControl(source, FSCTL_GET_INTEGRITY_INFORMATION, nullptr, 0, &get_integrity, sizeof get_integrity, &junk, nullptr))\n\t{\n\t\treturn false;\n\t}\n\n#ifdef _DEBUG\n\tSetFileAttributesW(newpath, FILE_ATTRIBUTE_NORMAL);\n\tATL::CHandle destination(CreateFileW(newpath, GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, source));\n#else\n\tATL::CHandle destination(CreateFileW(newpath, GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source));\n#endif\n\tif (destination == INVALID_HANDLE_VALUE)\n\t{\n\t\tdestination.Detach();\n\t\treturn false;\n\t}\n\tFILE_DISPOSITION_INFO dispose = { TRUE };\n\tif (!SetFileInformationByHandle(destination, FileDispositionInfo, &dispose, sizeof dispose))\n\t{\n\t\treturn false;\n\t}\n\n\tif (file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)\n\t{\n\t\tif (!DeviceIoControl(destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &junk, nullptr))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\tFSCTL_SET_INTEGRITY_INFORMATION_BUFFER set_integrity = { get_integrity.ChecksumAlgorithm, get_integrity.Reserved, get_integrity.Flags };\n\tif (!DeviceIoControl(destination, FSCTL_SET_INTEGRITY_INFORMATION, &set_integrity, sizeof set_integrity, nullptr, 0, nullptr, nullptr))\n\t{\n\t\treturn false;\n\t}\n\tif (!SetFileInformationByHandle(destination, FileEndOfFileInfo, &file_size, sizeof file_size))\n\t{\n\t\treturn false;\n\t}\n\n\tconst LONG64 split_threshold = (1LL << 32) - get_integrity.ClusterSizeInBytes;\n\n\tDUPLICATE_EXTENTS_DATA dup_extent;\n\tdup_extent.FileHandle = source;\n\tfor (LONG64 offset = 0, remain = ROUNDUP(file_size.EndOfFile.QuadPart, get_integrity.ClusterSizeInBytes); remain > 0; offset += split_threshold, remain -= split_threshold)\n\t{\n\t\tdup_extent.SourceFileOffset.QuadPart = dup_extent.TargetFileOffset.QuadPart = offset;\n\t\tdup_extent.ByteCount.QuadPart = (std::min)(split_threshold, remain);\n\t\t_ASSERTE(dup_extent.SourceFileOffset.QuadPart % get_integrity.ClusterSizeInBytes == 0);\n\t\t_ASSERTE(dup_extent.ByteCount.QuadPart % get_integrity.ClusterSizeInBytes == 0);\n\t\t_ASSERTE(dup_extent.ByteCount.QuadPart <= UINT32_MAX);\n\t\t_RPT3(_CRT_WARN, \"Remain=%llx\\nOffset=%llx\\nLength=%llx\\n\\n\", remain, dup_extent.SourceFileOffset.QuadPart, dup_extent.ByteCount.QuadPart);\n\t\tif (!DeviceIoControl(destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &junk, nullptr))\n\t\t{\n\t\t\t_CrtDbgBreak();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfile_basic.CreationTime.QuadPart = 0;\n\tif (!SetFileInformationByHandle(destination, FileBasicInfo, &file_basic, sizeof file_basic))\n\t{\n\t\treturn false;\n\t}\n\tif (!FlushFileBuffers(destination))\n\t{\n\t\treturn false;\n\t}\n\tdispose = { FALSE };\n\treturn !!SetFileInformationByHandle(destination, FileDispositionInfo, &dispose, sizeof dispose);\n}<commit_msg>Don't grow file all at once<commit_after>#define WIN32_LEAN_AND_MEAN\n#define STRICT_GS_ENABLED\n#define _ATL_NO_AUTOMATIC_NAMESPACE\n#define _ATL_NO_DEFAULT_LIBS\n#define _ATL_NO_WIN_SUPPORT\n#define _CRTDBG_MAP_ALLOC\n#include <atlbase.h>\n#include <windows.h>\n#include <winioctl.h>\n#include <algorithm>\n#include \"reflink.h\"\n#include <crtdbg.h>\n\nconstexpr LONG64 inline ROUNDUP(LONG64 file_size, ULONG cluster_size) noexcept\n{\n\treturn (file_size + cluster_size - 1) \/ cluster_size * cluster_size;\n}\nstatic_assert(ROUNDUP(5678, 4 * 1024) == 8 * 1024);\n_Success_(return == true)\nbool reflink(_In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath)\n{\n\tATL::CHandle source(CreateFileW(oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr));\n\tif (source == INVALID_HANDLE_VALUE)\n\t{\n\t\tsource.Detach();\n\t\treturn false;\n\t}\n\n\tULONG fs_flags;\n\tif (!GetVolumeInformationByHandleW(source, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0))\n\t{\n\t\treturn false;\n\t}\n\tif (!(fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING))\n\t{\n\t\tSetLastError(ERROR_NOT_CAPABLE);\n\t\treturn false;\n\t}\n\n\tFILE_END_OF_FILE_INFO file_size;\n\tif (!GetFileSizeEx(source, &file_size.EndOfFile))\n\t{\n\t\treturn false;\n\t}\n\tFILE_BASIC_INFO file_basic;\n\tif (!GetFileInformationByHandleEx(source, FileBasicInfo, &file_basic, sizeof file_basic))\n\t{\n\t\treturn false;\n\t}\n\tULONG junk;\n\tFSCTL_GET_INTEGRITY_INFORMATION_BUFFER get_integrity;\n\tif (!DeviceIoControl(source, FSCTL_GET_INTEGRITY_INFORMATION, nullptr, 0, &get_integrity, sizeof get_integrity, &junk, nullptr))\n\t{\n\t\treturn false;\n\t}\n\n#ifdef _DEBUG\n\tSetFileAttributesW(newpath, FILE_ATTRIBUTE_NORMAL);\n\tATL::CHandle destination(CreateFileW(newpath, GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, source));\n#else\n\tATL::CHandle destination(CreateFileW(newpath, GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source));\n#endif\n\tif (destination == INVALID_HANDLE_VALUE)\n\t{\n\t\tdestination.Detach();\n\t\treturn false;\n\t}\n\tFILE_DISPOSITION_INFO dispose = { TRUE };\n\tif (!SetFileInformationByHandle(destination, FileDispositionInfo, &dispose, sizeof dispose))\n\t{\n\t\treturn false;\n\t}\n\n\tif (!DeviceIoControl(destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &junk, nullptr))\n\t{\n\t\treturn false;\n\t}\n\tFSCTL_SET_INTEGRITY_INFORMATION_BUFFER set_integrity = { get_integrity.ChecksumAlgorithm, get_integrity.Reserved, get_integrity.Flags };\n\tif (!DeviceIoControl(destination, FSCTL_SET_INTEGRITY_INFORMATION, &set_integrity, sizeof set_integrity, nullptr, 0, nullptr, nullptr))\n\t{\n\t\treturn false;\n\t}\n\tif (!SetFileInformationByHandle(destination, FileEndOfFileInfo, &file_size, sizeof file_size))\n\t{\n\t\treturn false;\n\t}\n\n\tconst LONG64 split_threshold = (1LL << 32) - get_integrity.ClusterSizeInBytes;\n\n\tDUPLICATE_EXTENTS_DATA dup_extent;\n\tdup_extent.FileHandle = source;\n\tfor (LONG64 offset = 0, remain = ROUNDUP(file_size.EndOfFile.QuadPart, get_integrity.ClusterSizeInBytes); remain > 0; offset += split_threshold, remain -= split_threshold)\n\t{\n\t\tdup_extent.SourceFileOffset.QuadPart = dup_extent.TargetFileOffset.QuadPart = offset;\n\t\tdup_extent.ByteCount.QuadPart = (std::min)(split_threshold, remain);\n\t\t_ASSERTE(dup_extent.SourceFileOffset.QuadPart % get_integrity.ClusterSizeInBytes == 0);\n\t\t_ASSERTE(dup_extent.ByteCount.QuadPart % get_integrity.ClusterSizeInBytes == 0);\n\t\t_ASSERTE(dup_extent.ByteCount.QuadPart <= UINT32_MAX);\n\t\t_RPT3(_CRT_WARN, \"Remain=%llx\\nOffset=%llx\\nLength=%llx\\n\\n\", remain, dup_extent.SourceFileOffset.QuadPart, dup_extent.ByteCount.QuadPart);\n\t\tif (!DeviceIoControl(destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &junk, nullptr))\n\t\t{\n\t\t\t_CrtDbgBreak();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif (!(file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE))\n\t{\n\t\tFILE_SET_SPARSE_BUFFER set_sparse = { FALSE };\n\t\tif (!DeviceIoControl(destination, FSCTL_SET_SPARSE, &set_sparse, sizeof set_sparse, nullptr, 0, &junk, nullptr))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfile_basic.CreationTime.QuadPart = 0;\n\tif (!SetFileInformationByHandle(destination, FileBasicInfo, &file_basic, sizeof file_basic))\n\t{\n\t\treturn false;\n\t}\n\tif (!FlushFileBuffers(destination))\n\t{\n\t\treturn false;\n\t}\n\tdispose = { FALSE };\n\treturn !!SetFileInformationByHandle(destination, FileDispositionInfo, &dispose, sizeof dispose);\n}<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/\/ \\file es\/storage.hpp\n\/\/\/ \\brief The entity\/component data store\n\/\/\n\/\/ Copyright 2013, nocte@hippie.nu Released under the MIT License.\n\/\/---------------------------------------------------------------------------\n#pragma once\n\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <unordered_map>\n\n#include \"component.hpp\"\n#include \"entity.hpp\"\n#include \"traits.hpp\"\n\nnamespace es {\n\n\/** A storage ties entities and components together.\n * Storage associates two other bits of data with every entity:\n * - A 64-bit mask that keeps track of which components are defined\n * - A vector of bytes, holding the actual data\n *\n * The vector of bytes tries to pack the component data as tightly as\n * possible. It is really fast for plain old datatypes, but it also\n * handles nontrivial types safely. It packs a virtual table and a\n * pointer to some heap space in the vector, and calls the constructor\n * and destructor as needed.\n *\/\nclass storage\n{\n \/\/ It is assumed the first few components will be accessed the\n \/\/ most often. We keep a cache of the first 12.\n static constexpr uint32_t cache_size = 12;\n static constexpr uint32_t cache_mask = (1 << cache_size) - 1;\n\n \/** This data gets associated with every entity. *\/\n struct elem\n {\n \/** Bitmask to keep track of which components are held in \\a data. *\/\n std::bitset<64> components;\n \/** Component data for this entity. *\/\n std::vector<char> data;\n };\n\n typedef component::placeholder placeholder;\n\n \/** Data types that do not have a flat memory layout are kept in the \n ** elem::data buffer in a placeholder object. *\/\n template <typename t>\n class holder : public placeholder\n {\n public:\n holder () { }\n holder (t init) : held_(std::move(init)) { }\n\n const t& held() const { return held_; }\n t& held() { return held_; }\n\n placeholder* clone() const { return new holder<t>(held_); }\n\n private:\n t held_;\n };\n\n typedef std::unordered_map<uint32_t, elem> stor_impl;\n\npublic:\n typedef uint8_t component_id;\n\n typedef stor_impl::iterator iterator;\n typedef stor_impl::const_iterator const_iterator;\n\npublic:\n \/** Variable references are used by systems to access an entity's data.\n * It keeps track of the elem::data buffer and the offset inside that\n * buffer. *\/\n template <typename type>\n class var_ref\n {\n friend class storage;\n\n type& get()\n {\n if (is_flat<type>::value)\n return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);\n\n auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));\n return ptr->held();\n }\n\n public:\n operator const type& () const\n {\n if (is_flat<type>::value)\n return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);\n\n auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));\n return ptr->held();\n }\n\n var_ref& operator= (type assign)\n {\n if (is_flat<type>::value)\n {\n new (&*e_.data.begin() + offset_) type(std::move(assign));\n }\n else\n {\n auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));\n new (ptr) holder<type>(std::move(assign));\n }\n return *this;\n }\n\n template <typename s>\n var_ref& operator+= (s val)\n { get() += val; return *this; }\n\n template <typename s>\n var_ref& operator-= (s val)\n { get() -= val; return *this; }\n\n template <typename s>\n var_ref& operator*= (s val)\n { get() *= val; return *this; }\n\n template <typename s>\n var_ref& operator\/= (s val)\n { get() \/= val; return *this; }\n\n protected:\n var_ref (size_t offset, elem& e)\n : offset_(offset), e_(e)\n { }\n\n private:\n size_t offset_;\n elem& e_;\n };\n\npublic:\n storage()\n : next_id_(0)\n {\n component_offsets_.push_back(0);\n }\n\n template <typename type>\n component_id register_component (std::string name)\n {\n size_t size;\n\n if (is_flat<type>::value)\n {\n size = sizeof(type);\n components_.emplace_back(name, size, nullptr);\n }\n else\n {\n flat_mask_.set(components_.size());\n size = sizeof(holder<type>);\n components_.emplace_back(name, size,\n std::unique_ptr<placeholder>(new holder<type>()));\n }\n\n if (components_.size() < cache_size)\n {\n size_t i (component_offsets_.size());\n component_offsets_.resize(i * 2);\n for (size_t j (i); j != i * 2; ++j)\n component_offsets_[j] = component_offsets_[j-i] + size;\n }\n\n return components_.size() - 1;\n }\n\n component_id find_component (const std::string& name) const\n {\n auto found (std::find(components_.begin(), components_.end(), name));\n if (found == components_.end())\n throw std::logic_error(\"component does not exist\");\n\n return std::distance(components_.begin(), found);\n }\n\n const component& operator[] (component_id id) const\n { return components_[id]; }\n\n const std::vector<component>& components() const\n { return components_; }\n\npublic:\n entity new_entity()\n {\n entities_[next_id_++];\n return next_id_ - 1;\n }\n\n \/** Get an entity with a given ID, or create it if it didn't exist yet. *\/\n iterator make (uint32_t id)\n {\n if (next_id_ <= id)\n next_id_ = id + 1;\n\n return entities_.insert(entities_.end(), std::make_pair(id, elem()));\n }\n\n \/** Create a whole bunch of empty entities in one go.\n * @param count The number of entities to create\n * @return The range of entities created *\/\n std::pair<entity, entity> new_entities (size_t count)\n {\n auto range_begin (next_id_);\n for (; count > 0; --count)\n entities_[next_id_++];\n\n return std::make_pair(range_begin, next_id_);\n }\n\n entity clone_entity (iterator f)\n {\n elem& e (f->second);\n entities_[next_id_++] = e;\n\n \/\/ Quick check if we need to make deep copies\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)\n {\n if (e.components[c_id])\n {\n if (!components_[c_id].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr = ptr->clone();\n }\n off += components_[c_id].size();\n }\n }\n }\n return next_id_ - 1;\n }\n\n iterator find (entity en)\n {\n auto found (entities_.find(en.id()));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n }\n\n const_iterator find (entity en) const\n {\n auto found (entities_.find(en.id()));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n }\n\n void delete_entity (entity en)\n { delete_entity(find(en)); }\n\n void delete_entity (iterator f)\n {\n elem& e (f->second);\n\n \/\/ Quick check if we'll have to call any destructors.\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int search (0); search < 64 && off < e.data.size(); ++search)\n {\n if (e.components[search])\n {\n if (!components_[search].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n off += components_[search].size();\n }\n }\n }\n\n entities_.erase(f);\n }\n\n void remove_component_from_entity (iterator en, component_id c)\n {\n auto& e (en->second);\n if (!e.components[c])\n return;\n\n size_t off (offset(e, c));\n auto& comp_info (components_[c]);\n if (!comp_info.is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n auto o (e.data.begin() + off);\n e.data.erase(o, o + comp_info.size());\n e.components.reset(c);\n }\n\n \/** Call a function for every entity that has a given component.\n * The callee can then query and change the value of the component through\n * a var_ref object, or remove the entity.\n * @param c The component to look for.\n * @param func The function to call. This function will be passed an \n * iterator to the current entity, and a var_ref corresponding\n * to the component value in this entity. *\/\n template <typename t>\n void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)\n {\n std::bitset<64> mask;\n mask.set(c);\n for (auto i (entities_.begin()); i != entities_.end(); )\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n func(i, var_ref<t>(offset(e, c), e));\n\n i = next;\n }\n }\n\n template <typename t1, typename t2>\n void for_each (component_id c1, component_id c2,\n std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)\n {\n std::bitset<64> mask;\n mask.set(c1);\n mask.set(c2);\n for (auto i (entities_.begin()); i != entities_.end(); ++i)\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n {\n func(i, var_ref<t1>(offset(e, c1), e),\n var_ref<t2>(offset(e, c2), e));\n }\n i = next;\n }\n }\n\n template <typename t1, typename t2, typename t3>\n void for_each (component_id c1, component_id c2, component_id c3,\n std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)\n {\n std::bitset<64> mask;\n mask.set(c1);\n mask.set(c2);\n mask.set(c3);\n for (auto i (entities_.begin()); i != entities_.end(); ++i)\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n {\n func(i, var_ref<t1>(offset(e, c1), e),\n var_ref<t2>(offset(e, c2), e),\n var_ref<t3>(offset(e, c3), e));\n }\n i = next;\n }\n }\n\n bool exists (entity en) const\n { return entities_.count(en.id()); }\n\n template <typename type>\n void set (entity en, component_id c_id, type val)\n { return set<type>(find(en), c_id, std::move(val)); }\n\n template <typename type>\n void set (iterator en, component_id c_id, type val)\n {\n const component& c (components_[c_id]);\n elem& e (en->second);\n size_t off (offset(e, c_id));\n\n if (!e.components[c_id])\n {\n if (e.data.size() < off)\n e.data.resize(off + c.size());\n else\n e.data.insert(e.data.begin() + off, c.size(), 0);\n\n e.components.set(c_id);\n }\n\n if (is_flat<type>::value)\n {\n assert(e.data.size() >= off + sizeof(type));\n new (&*e.data.begin() + off) type(std::move(val));\n }\n else\n {\n assert(e.data.size() >= off + sizeof(holder<type>));\n auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));\n new (ptr) holder<type>(std::move(val));\n }\n }\n\n template <typename type>\n const type& get (entity en, component_id c_id) const\n { return get<type>(find(en), c_id); }\n\n template <typename type>\n const type& get (const_iterator en, component_id c_id) const\n {\n auto& e (en->second);\n if (!e.components[c_id])\n throw std::logic_error(\"entity does not have component\");\n\n return get<type>(e, c_id);\n }\n\nprivate:\n template <typename type>\n const type& get (const elem& e, component_id c_id) const\n {\n size_t off (offset(e, c_id));\n if (is_flat<type>::value)\n return *reinterpret_cast<const type*>(&*e.data.begin() + off);\n\n auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));\n\n return ptr->held();\n }\n\n size_t offset (const elem& e, component_id c) const\n {\n assert(c < components_.size());\n assert((c & cache_mask) < component_offsets_.size());\n size_t result (component_offsets_[c & cache_mask]);\n\n for (component_id search (cache_size); search < c; ++search)\n {\n if (e.components[search])\n result += components_[search].size();\n }\n return result;\n }\n\nprivate:\n \/** Keeps track of entity IDs to give out. *\/\n uint32_t next_id_;\n \/** The list of registered components. *\/\n std::vector<component> components_;\n \/** Mapping entity IDs to their data. *\/\n std::unordered_map<uint32_t, elem> entities_;\n \/** A lookup table for the data offsets of components.\n * The index is the bitmask as used in elem::components. *\/\n std::vector<size_t> component_offsets_;\n \/** A bitmask to quickly determine whether a certain combination of\n ** components has a flat memory layout or not. *\/\n std::bitset<64> flat_mask_;\n};\n\n} \/\/ namespace es\n<commit_msg>Applied #e2928c1b32 again (?)<commit_after>\/\/---------------------------------------------------------------------------\n\/\/\/ \\file es\/storage.hpp\n\/\/\/ \\brief The entity\/component data store\n\/\/\n\/\/ Copyright 2013, nocte@hippie.nu Released under the MIT License.\n\/\/---------------------------------------------------------------------------\n#pragma once\n\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cstdint>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <unordered_map>\n\n#include \"component.hpp\"\n#include \"entity.hpp\"\n#include \"traits.hpp\"\n\nnamespace es {\n\n\/** A storage ties entities and components together.\n * Storage associates two other bits of data with every entity:\n * - A 64-bit mask that keeps track of which components are defined\n * - A vector of bytes, holding the actual data\n *\n * The vector of bytes tries to pack the component data as tightly as\n * possible. It is really fast for plain old datatypes, but it also\n * handles nontrivial types safely. It packs a virtual table and a\n * pointer to some heap space in the vector, and calls the constructor\n * and destructor as needed.\n *\/\nclass storage\n{\n \/\/ It is assumed the first few components will be accessed the\n \/\/ most often. We keep a cache of the first 12.\n static constexpr uint32_t cache_size = 12;\n static constexpr uint32_t cache_mask = (1 << cache_size) - 1;\n\n \/** This data gets associated with every entity. *\/\n struct elem\n {\n \/** Bitmask to keep track of which components are held in \\a data. *\/\n std::bitset<64> components;\n \/** Component data for this entity. *\/\n std::vector<char> data;\n };\n\n typedef component::placeholder placeholder;\n\n \/** Data types that do not have a flat memory layout are kept in the \n ** elem::data buffer in a placeholder object. *\/\n template <typename t>\n class holder : public placeholder\n {\n public:\n holder () { }\n holder (t init) : held_(std::move(init)) { }\n\n const t& held() const { return held_; }\n t& held() { return held_; }\n\n placeholder* clone() const { return new holder<t>(held_); }\n\n private:\n t held_;\n };\n\n typedef std::unordered_map<uint32_t, elem> stor_impl;\n\npublic:\n typedef uint8_t component_id;\n\n typedef stor_impl::iterator iterator;\n typedef stor_impl::const_iterator const_iterator;\n\npublic:\n \/** Variable references are used by systems to access an entity's data.\n * It keeps track of the elem::data buffer and the offset inside that\n * buffer. *\/\n template <typename type>\n class var_ref\n {\n friend class storage;\n\n type& get()\n {\n if (is_flat<type>::value)\n return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);\n\n auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));\n return ptr->held();\n }\n\n public:\n operator const type& () const\n {\n if (is_flat<type>::value)\n return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);\n\n auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));\n return ptr->held();\n }\n\n var_ref& operator= (type assign)\n {\n if (is_flat<type>::value)\n {\n new (&*e_.data.begin() + offset_) type(std::move(assign));\n }\n else\n {\n auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));\n new (ptr) holder<type>(std::move(assign));\n }\n return *this;\n }\n\n template <typename s>\n var_ref& operator+= (s val)\n { get() += val; return *this; }\n\n template <typename s>\n var_ref& operator-= (s val)\n { get() -= val; return *this; }\n\n template <typename s>\n var_ref& operator*= (s val)\n { get() *= val; return *this; }\n\n template <typename s>\n var_ref& operator\/= (s val)\n { get() \/= val; return *this; }\n\n protected:\n var_ref (size_t offset, elem& e)\n : offset_(offset), e_(e)\n { }\n\n private:\n size_t offset_;\n elem& e_;\n };\n\npublic:\n storage()\n : next_id_(0)\n {\n component_offsets_.push_back(0);\n }\n\n template <typename type>\n component_id register_component (std::string name)\n {\n size_t size;\n\n if (is_flat<type>::value)\n {\n size = sizeof(type);\n components_.emplace_back(name, size, nullptr);\n }\n else\n {\n flat_mask_.set(components_.size());\n size = sizeof(holder<type>);\n components_.emplace_back(name, size,\n std::unique_ptr<placeholder>(new holder<type>()));\n }\n\n if (components_.size() < cache_size)\n {\n size_t i (component_offsets_.size());\n component_offsets_.resize(i * 2);\n for (size_t j (i); j != i * 2; ++j)\n component_offsets_[j] = component_offsets_[j-i] + size;\n }\n\n return components_.size() - 1;\n }\n\n component_id find_component (const std::string& name) const\n {\n auto found (std::find(components_.begin(), components_.end(), name));\n if (found == components_.end())\n throw std::logic_error(\"component does not exist\");\n\n return std::distance(components_.begin(), found);\n }\n\n const component& operator[] (component_id id) const\n { return components_[id]; }\n\n const std::vector<component>& components() const\n { return components_; }\n\npublic:\n entity new_entity()\n {\n entities_[next_id_++];\n return next_id_ - 1;\n }\n\n \/** Get an entity with a given ID, or create it if it didn't exist yet. *\/\n iterator make (uint32_t id)\n {\n if (next_id_ <= id)\n next_id_ = id + 1;\n\n return entities_.insert(entities_.end(), std::make_pair(id, elem()));\n }\n\n \/** Create a whole bunch of empty entities in one go.\n * @param count The number of entities to create\n * @return The range of entities created *\/\n std::pair<entity, entity> new_entities (size_t count)\n {\n auto range_begin (next_id_);\n for (; count > 0; --count)\n entities_[next_id_++];\n\n return std::make_pair(range_begin, next_id_);\n }\n\n entity clone_entity (iterator f)\n {\n elem& e (f->second);\n entities_[next_id_++] = e;\n\n \/\/ Quick check if we need to make deep copies\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)\n {\n if (e.components[c_id])\n {\n if (!components_[c_id].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr = ptr->clone();\n }\n off += components_[c_id].size();\n }\n }\n }\n return next_id_ - 1;\n }\n\n iterator find (entity en)\n {\n auto found (entities_.find(en.id()));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n }\n\n const_iterator find (entity en) const\n {\n auto found (entities_.find(en.id()));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n }\n\n void delete_entity (entity en)\n { delete_entity(find(en)); }\n\n void delete_entity (iterator f)\n {\n elem& e (f->second);\n\n \/\/ Quick check if we'll have to call any destructors.\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int search (0); search < 64 && off < e.data.size(); ++search)\n {\n if (e.components[search])\n {\n if (!components_[search].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n off += components_[search].size();\n }\n }\n }\n\n entities_.erase(f);\n }\n\n void remove_component_from_entity (iterator en, component_id c)\n {\n auto& e (en->second);\n if (!e.components[c])\n return;\n\n size_t off (offset(e, c));\n auto& comp_info (components_[c]);\n if (!comp_info.is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n auto o (e.data.begin() + off);\n e.data.erase(o, o + comp_info.size());\n e.components.reset(c);\n }\n\n \/** Call a function for every entity that has a given component.\n * The callee can then query and change the value of the component through\n * a var_ref object, or remove the entity.\n * @param c The component to look for.\n * @param func The function to call. This function will be passed an \n * iterator to the current entity, and a var_ref corresponding\n * to the component value in this entity. *\/\n template <typename t>\n void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)\n {\n std::bitset<64> mask;\n mask.set(c);\n for (auto i (entities_.begin()); i != entities_.end(); )\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n func(i, var_ref<t>(offset(e, c), e));\n\n i = next;\n }\n }\n\n template <typename t1, typename t2>\n void for_each (component_id c1, component_id c2,\n std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)\n {\n std::bitset<64> mask;\n mask.set(c1);\n mask.set(c2);\n for (auto i (entities_.begin()); i != entities_.end(); )\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n {\n func(i, var_ref<t1>(offset(e, c1), e),\n var_ref<t2>(offset(e, c2), e));\n }\n i = next;\n }\n }\n\n template <typename t1, typename t2, typename t3>\n void for_each (component_id c1, component_id c2, component_id c3,\n std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)\n {\n std::bitset<64> mask;\n mask.set(c1);\n mask.set(c2);\n mask.set(c3);\n for (auto i (entities_.begin()); i != entities_.end(); )\n {\n auto next (std::next(i));\n elem& e (i->second);\n if ((e.components & mask) == mask)\n {\n func(i, var_ref<t1>(offset(e, c1), e),\n var_ref<t2>(offset(e, c2), e),\n var_ref<t3>(offset(e, c3), e));\n }\n i = next;\n }\n }\n\n bool exists (entity en) const\n { return entities_.count(en.id()); }\n\n template <typename type>\n void set (entity en, component_id c_id, type val)\n { return set<type>(find(en), c_id, std::move(val)); }\n\n template <typename type>\n void set (iterator en, component_id c_id, type val)\n {\n const component& c (components_[c_id]);\n elem& e (en->second);\n size_t off (offset(e, c_id));\n\n if (!e.components[c_id])\n {\n if (e.data.size() < off)\n e.data.resize(off + c.size());\n else\n e.data.insert(e.data.begin() + off, c.size(), 0);\n\n e.components.set(c_id);\n }\n\n if (is_flat<type>::value)\n {\n assert(e.data.size() >= off + sizeof(type));\n new (&*e.data.begin() + off) type(std::move(val));\n }\n else\n {\n assert(e.data.size() >= off + sizeof(holder<type>));\n auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));\n new (ptr) holder<type>(std::move(val));\n }\n }\n\n template <typename type>\n const type& get (entity en, component_id c_id) const\n { return get<type>(find(en), c_id); }\n\n template <typename type>\n const type& get (const_iterator en, component_id c_id) const\n {\n auto& e (en->second);\n if (!e.components[c_id])\n throw std::logic_error(\"entity does not have component\");\n\n return get<type>(e, c_id);\n }\n\nprivate:\n template <typename type>\n const type& get (const elem& e, component_id c_id) const\n {\n size_t off (offset(e, c_id));\n if (is_flat<type>::value)\n return *reinterpret_cast<const type*>(&*e.data.begin() + off);\n\n auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));\n\n return ptr->held();\n }\n\n size_t offset (const elem& e, component_id c) const\n {\n assert(c < components_.size());\n assert((c & cache_mask) < component_offsets_.size());\n size_t result (component_offsets_[c & cache_mask]);\n\n for (component_id search (cache_size); search < c; ++search)\n {\n if (e.components[search])\n result += components_[search].size();\n }\n return result;\n }\n\nprivate:\n \/** Keeps track of entity IDs to give out. *\/\n uint32_t next_id_;\n \/** The list of registered components. *\/\n std::vector<component> components_;\n \/** Mapping entity IDs to their data. *\/\n std::unordered_map<uint32_t, elem> entities_;\n \/** A lookup table for the data offsets of components.\n * The index is the bitmask as used in elem::components. *\/\n std::vector<size_t> component_offsets_;\n \/** A bitmask to quickly determine whether a certain combination of\n ** components has a flat memory layout or not. *\/\n std::bitset<64> flat_mask_;\n};\n\n} \/\/ namespace es\n<|endoftext|>"} {"text":"<commit_before>\/*\n * GridMapRosConverter.cpp\n *\n * Created on: Jul 14, 2014\n * Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"grid_map\/GridMapRosConverter.hpp\"\n#include \"grid_map\/GridMapMsgHelpers.hpp\"\n#include <grid_map_core\/GridMapMath.hpp>\n#include <grid_map_core\/iterators\/GridMapIterator.hpp>\n\n\/\/ ROS\n#include <sensor_msgs\/point_cloud2_iterator.h>\n#include <geometry_msgs\/Point.h>\n#include <rosbag\/bag.h>\n#include <rosbag\/view.h>\n\n\/\/ STL\n#include <limits>\n#include <algorithm>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace grid_map {\n\nGridMapRosConverter::GridMapRosConverter()\n{\n}\n\nGridMapRosConverter::~GridMapRosConverter()\n{\n}\n\nbool GridMapRosConverter::fromMessage(const grid_map_msgs::GridMap& message, grid_map::GridMap& gridMap)\n{\n gridMap.setTimestamp(message.info.header.stamp.toNSec());\n gridMap.setFrameId(message.info.header.frame_id);\n gridMap.setGeometry(Length(message.info.length_x, message.info.length_y), message.info.resolution,\n Position(message.info.pose.position.x, message.info.pose.position.y));\n\n if (message.layers.size() != message.data.size()) {\n ROS_ERROR(\"Different number of layers and data in grid map message.\");\n return false;\n }\n\n for (unsigned int i = 0; i < message.layers.size(); i++) {\n Matrix data;\n multiArrayMessageCopyToMatrixEigen(message.data[i], data); \/\/ TODO Could we use the data mapping (instead of copying) method here?\n \/\/ TODO Check if size is good. size_ << getRows(message.data[0]), getCols(message.data[0]);\n gridMap.add(message.layers[i], data);\n }\n\n gridMap.setBasicLayers(message.basic_layers);\n gridMap.setStartIndex(Index(message.outer_start_index, message.inner_start_index));\n return true;\n}\n\nvoid GridMapRosConverter::toMessage(const grid_map::GridMap& gridMap, grid_map_msgs::GridMap& message)\n{\n toMessage(gridMap, gridMap.getLayers(), message);\n}\n\nvoid GridMapRosConverter::toMessage(const grid_map::GridMap& gridMap, const std::vector<std::string>& layers,\n grid_map_msgs::GridMap& message)\n{\n message.info.header.stamp.fromNSec(gridMap.getTimestamp());\n message.info.header.frame_id = gridMap.getFrameId();\n message.info.resolution = gridMap.getResolution();\n message.info.length_x = gridMap.getLength().x();\n message.info.length_y = gridMap.getLength().y();\n message.info.pose.position.x = gridMap.getPosition().x();\n message.info.pose.position.y = gridMap.getPosition().y();\n message.info.pose.position.z = 0.0;\n message.info.pose.orientation.x = 0.0;\n message.info.pose.orientation.y = 0.0;\n message.info.pose.orientation.z = 0.0;\n message.info.pose.orientation.w = 1.0;\n\n message.layers = layers;\n message.basic_layers = gridMap.getBasicLayers();\n\n for (const auto& layer : layers) {\n std_msgs::Float32MultiArray dataArray;\n matrixEigenCopyToMultiArrayMessage(gridMap.get(layer), dataArray);\n message.data.push_back(dataArray);\n }\n\n message.outer_start_index = gridMap.getStartIndex()(0);\n message.inner_start_index = gridMap.getStartIndex()(1);\n}\n\nvoid GridMapRosConverter::toPointCloud(const grid_map::GridMap& gridMap,\n const std::string& pointLayer,\n sensor_msgs::PointCloud2& pointCloud)\n{\n toPointCloud(gridMap, gridMap.getLayers(), pointLayer, pointCloud);\n}\n\nvoid GridMapRosConverter::toPointCloud(const grid_map::GridMap& gridMap,\n const std::vector<std::string>& layers,\n const std::string& pointLayer,\n sensor_msgs::PointCloud2& pointCloud)\n{\n\/\/ Header.\n pointCloud.header.frame_id = gridMap.getFrameId();\n pointCloud.header.stamp.fromNSec(gridMap.getTimestamp());\n pointCloud.is_dense = false;\n\n\/\/ Fields.\n std::vector <std::string> fieldNames;\n\n for (const auto& layer : layers) {\n if (layer == pointLayer) {\n fieldNames.push_back(\"x\");\n fieldNames.push_back(\"y\");\n fieldNames.push_back(\"z\");\n } else if (layer == \"color\") {\n fieldNames.push_back(\"rgb\");\n } else {\n fieldNames.push_back(layer);\n }\n }\n\n pointCloud.fields.clear();\n pointCloud.fields.reserve(fieldNames.size());\n int offset = 0;\n\n for (auto& name : fieldNames) {\n sensor_msgs::PointField point_field;\n point_field.name = name;\n point_field.count = 1;\n point_field.datatype = sensor_msgs::PointField::FLOAT32;\n point_field.offset = offset;\n pointCloud.fields.push_back(point_field);\n offset = offset + point_field.count * 4; \/\/ 4 for sensor_msgs::PointField::FLOAT32\n }\n\n\/\/ Resize.\n size_t nPoints = gridMap.getSize().prod();\n pointCloud.height = 1;\n pointCloud.width = nPoints;\n pointCloud.point_step = offset;\n pointCloud.row_step = pointCloud.width * pointCloud.point_step;\n pointCloud.data.resize(pointCloud.height * pointCloud.row_step);\n\n\/\/ Points\n std::unordered_map<std::string, sensor_msgs::PointCloud2Iterator<float>> fieldIterators;\n for (auto& name : fieldNames) {\n fieldIterators.insert(\n std::pair<std::string, sensor_msgs::PointCloud2Iterator<float>>(\n name, sensor_msgs::PointCloud2Iterator<float>(pointCloud, name)));\n }\n\n GridMapIterator mapIterator(gridMap);\n\n for (size_t i = 0; i < nPoints; ++i) {\n Position3 position;\n position.setConstant(NAN);\n gridMap.getPosition3(pointLayer, *mapIterator, position);\n\n for (auto& iterator : fieldIterators) {\n if (iterator.first == \"x\") {\n *iterator.second = (float) position.x();\n } else if (iterator.first == \"y\") {\n *iterator.second = (float) position.y();\n } else if (iterator.first == \"z\") {\n *iterator.second = (float) position.z();\n } else if (iterator.first == \"rgb\") {\n *iterator.second = gridMap.at(\"color\", *mapIterator);\n ;\n } else {\n *iterator.second = gridMap.at(iterator.first, *mapIterator);\n }\n }\n\n ++mapIterator;\n for (auto& iterator : fieldIterators) {\n ++iterator.second;\n }\n }\n}\n\nvoid GridMapRosConverter::toOccupancyGrid(const grid_map::GridMap& gridMap,\n const std::string& layer, float dataMin, float dataMax,\n nav_msgs::OccupancyGrid& occupancyGrid)\n{\n occupancyGrid.header.frame_id = gridMap.getFrameId();\n occupancyGrid.header.stamp.fromNSec(gridMap.getTimestamp());\n occupancyGrid.info.map_load_time = occupancyGrid.header.stamp; \/\/ Same as header stamp as we do not load the map.\n occupancyGrid.info.resolution = gridMap.getResolution();\n occupancyGrid.info.width = gridMap.getSize()(0);\n occupancyGrid.info.height = gridMap.getSize()(1);\n Position positionOfOrigin;\n getPositionOfDataStructureOrigin(gridMap.getPosition(), gridMap.getLength(), positionOfOrigin);\n occupancyGrid.info.origin.position.x = positionOfOrigin.x();\n occupancyGrid.info.origin.position.y = positionOfOrigin.y();\n occupancyGrid.info.origin.position.z = 0.0;\n occupancyGrid.info.origin.orientation.x = 0.0;\n occupancyGrid.info.origin.orientation.y = 0.0;\n occupancyGrid.info.origin.orientation.z = 1.0; \/\/ yes, this is correct.\n occupancyGrid.info.origin.orientation.w = 0.0;\n occupancyGrid.data.resize(occupancyGrid.info.width * occupancyGrid.info.height);\n\n \/\/ Occupancy probabilities are in the range [0,100]. Unknown is -1.\n const float cellMin = 0;\n const float cellMax = 100;\n const float cellRange = cellMax - cellMin;\n\n for (GridMapIterator iterator(gridMap); !iterator.isPassedEnd(); ++iterator) {\n float value = (gridMap.at(layer, *iterator) - dataMin) \/ (dataMax - dataMin);\n if (isnan(value))\n value = -1;\n else\n value = cellMin + min(max(0.0f, value), 1.0f) * cellRange;\n \/\/ Occupancy grid claims to be row-major order, but it does not seem that way.\n \/\/ http:\/\/docs.ros.org\/api\/nav_msgs\/html\/msg\/OccupancyGrid.html.\n unsigned int index = get1dIndexFrom2dIndex(*iterator, gridMap.getSize(), false);\n occupancyGrid.data[index] = value;\n }\n}\n\nvoid GridMapRosConverter::toGridCells(const grid_map::GridMap& gridMap, const std::string& layer, float lowerThreshold,\n float upperThreshold, nav_msgs::GridCells& gridCells)\n{\n gridCells.header.frame_id = gridMap.getFrameId();\n gridCells.header.stamp.fromNSec(gridMap.getTimestamp());\n gridCells.cell_width = gridMap.getResolution();\n gridCells.cell_height = gridMap.getResolution();\n\n for (GridMapIterator iterator(gridMap); !iterator.isPassedEnd(); ++iterator) {\n if (!gridMap.isValid(*iterator, layer)) continue;\n if (gridMap.at(layer, *iterator) >= lowerThreshold\n && gridMap.at(layer, *iterator) <= upperThreshold) {\n Position position;\n gridMap.getPosition(*iterator, position);\n geometry_msgs::Point point;\n point.x = position.x();\n point.y = position.y();\n gridCells.cells.push_back(point);\n }\n }\n}\n \n\nbool GridMapRosConverter::saveToBag(const grid_map::GridMap& gridMap, const std::string& pathToBag,\n const std::string& topic)\n{\n grid_map_msgs::GridMap message;\n toMessage(gridMap, message);\n ros::Time time(gridMap.getTimestamp());\n\n if (!time.isValid()) {\n if (!ros::Time::isValid()) ros::Time::init();\n time = ros::Time::now();\n }\n\n rosbag::Bag bag;\n bag.open(pathToBag, rosbag::bagmode::Write);\n bag.write(topic, time, message);\n bag.close();\n return true;\n}\n\nbool GridMapRosConverter::loadFromBag(const std::string& pathToBag, const std::string& topic,\n grid_map::GridMap& gridMap)\n{\n rosbag::Bag bag;\n bag.open(pathToBag, rosbag::bagmode::Read);\n rosbag::View view(bag, rosbag::TopicQuery(topic));\n\n for (const auto& messageInstance : view) {\n grid_map_msgs::GridMap::ConstPtr message = messageInstance.instantiate<grid_map_msgs::GridMap>();\n if (message != NULL) {\n fromMessage(*message, gridMap);\n } else {\n bag.close();\n ROS_WARN(\"Unable to load data from ROS bag.\");\n return false;\n }\n }\n bag.close();\n return true;\n}\n\n} \/* namespace *\/\n<commit_msg>Bugfix.<commit_after>\/*\n * GridMapRosConverter.cpp\n *\n * Created on: Jul 14, 2014\n * Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"grid_map\/GridMapRosConverter.hpp\"\n#include \"grid_map\/GridMapMsgHelpers.hpp\"\n#include <grid_map_core\/GridMapMath.hpp>\n#include <grid_map_core\/iterators\/GridMapIterator.hpp>\n\n\/\/ ROS\n#include <sensor_msgs\/point_cloud2_iterator.h>\n#include <geometry_msgs\/Point.h>\n#include <rosbag\/bag.h>\n#include <rosbag\/view.h>\n\n\/\/ STL\n#include <limits>\n#include <algorithm>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace grid_map {\n\nGridMapRosConverter::GridMapRosConverter()\n{\n}\n\nGridMapRosConverter::~GridMapRosConverter()\n{\n}\n\nbool GridMapRosConverter::fromMessage(const grid_map_msgs::GridMap& message, grid_map::GridMap& gridMap)\n{\n gridMap.setTimestamp(message.info.header.stamp.toNSec());\n gridMap.setFrameId(message.info.header.frame_id);\n gridMap.setGeometry(Length(message.info.length_x, message.info.length_y), message.info.resolution,\n Position(message.info.pose.position.x, message.info.pose.position.y));\n\n if (message.layers.size() != message.data.size()) {\n ROS_ERROR(\"Different number of layers and data in grid map message.\");\n return false;\n }\n\n for (unsigned int i = 0; i < message.layers.size(); i++) {\n Matrix data;\n multiArrayMessageCopyToMatrixEigen(message.data[i], data); \/\/ TODO Could we use the data mapping (instead of copying) method here?\n \/\/ TODO Check if size is good. size_ << getRows(message.data[0]), getCols(message.data[0]);\n gridMap.add(message.layers[i], data);\n }\n\n gridMap.setBasicLayers(message.basic_layers);\n gridMap.setStartIndex(Index(message.outer_start_index, message.inner_start_index));\n return true;\n}\n\nvoid GridMapRosConverter::toMessage(const grid_map::GridMap& gridMap, grid_map_msgs::GridMap& message)\n{\n toMessage(gridMap, gridMap.getLayers(), message);\n}\n\nvoid GridMapRosConverter::toMessage(const grid_map::GridMap& gridMap, const std::vector<std::string>& layers,\n grid_map_msgs::GridMap& message)\n{\n message.info.header.stamp.fromNSec(gridMap.getTimestamp());\n message.info.header.frame_id = gridMap.getFrameId();\n message.info.resolution = gridMap.getResolution();\n message.info.length_x = gridMap.getLength().x();\n message.info.length_y = gridMap.getLength().y();\n message.info.pose.position.x = gridMap.getPosition().x();\n message.info.pose.position.y = gridMap.getPosition().y();\n message.info.pose.position.z = 0.0;\n message.info.pose.orientation.x = 0.0;\n message.info.pose.orientation.y = 0.0;\n message.info.pose.orientation.z = 0.0;\n message.info.pose.orientation.w = 1.0;\n\n message.layers = layers;\n message.basic_layers = gridMap.getBasicLayers();\n\n message.data.clear();\n for (const auto& layer : layers) {\n std_msgs::Float32MultiArray dataArray;\n matrixEigenCopyToMultiArrayMessage(gridMap.get(layer), dataArray);\n message.data.push_back(dataArray);\n }\n\n message.outer_start_index = gridMap.getStartIndex()(0);\n message.inner_start_index = gridMap.getStartIndex()(1);\n}\n\nvoid GridMapRosConverter::toPointCloud(const grid_map::GridMap& gridMap,\n const std::string& pointLayer,\n sensor_msgs::PointCloud2& pointCloud)\n{\n toPointCloud(gridMap, gridMap.getLayers(), pointLayer, pointCloud);\n}\n\nvoid GridMapRosConverter::toPointCloud(const grid_map::GridMap& gridMap,\n const std::vector<std::string>& layers,\n const std::string& pointLayer,\n sensor_msgs::PointCloud2& pointCloud)\n{\n\/\/ Header.\n pointCloud.header.frame_id = gridMap.getFrameId();\n pointCloud.header.stamp.fromNSec(gridMap.getTimestamp());\n pointCloud.is_dense = false;\n\n\/\/ Fields.\n std::vector <std::string> fieldNames;\n\n for (const auto& layer : layers) {\n if (layer == pointLayer) {\n fieldNames.push_back(\"x\");\n fieldNames.push_back(\"y\");\n fieldNames.push_back(\"z\");\n } else if (layer == \"color\") {\n fieldNames.push_back(\"rgb\");\n } else {\n fieldNames.push_back(layer);\n }\n }\n\n pointCloud.fields.clear();\n pointCloud.fields.reserve(fieldNames.size());\n int offset = 0;\n\n for (auto& name : fieldNames) {\n sensor_msgs::PointField point_field;\n point_field.name = name;\n point_field.count = 1;\n point_field.datatype = sensor_msgs::PointField::FLOAT32;\n point_field.offset = offset;\n pointCloud.fields.push_back(point_field);\n offset = offset + point_field.count * 4; \/\/ 4 for sensor_msgs::PointField::FLOAT32\n }\n\n\/\/ Resize.\n size_t nPoints = gridMap.getSize().prod();\n pointCloud.height = 1;\n pointCloud.width = nPoints;\n pointCloud.point_step = offset;\n pointCloud.row_step = pointCloud.width * pointCloud.point_step;\n pointCloud.data.resize(pointCloud.height * pointCloud.row_step);\n\n\/\/ Points\n std::unordered_map<std::string, sensor_msgs::PointCloud2Iterator<float>> fieldIterators;\n for (auto& name : fieldNames) {\n fieldIterators.insert(\n std::pair<std::string, sensor_msgs::PointCloud2Iterator<float>>(\n name, sensor_msgs::PointCloud2Iterator<float>(pointCloud, name)));\n }\n\n GridMapIterator mapIterator(gridMap);\n\n for (size_t i = 0; i < nPoints; ++i) {\n Position3 position;\n position.setConstant(NAN);\n gridMap.getPosition3(pointLayer, *mapIterator, position);\n\n for (auto& iterator : fieldIterators) {\n if (iterator.first == \"x\") {\n *iterator.second = (float) position.x();\n } else if (iterator.first == \"y\") {\n *iterator.second = (float) position.y();\n } else if (iterator.first == \"z\") {\n *iterator.second = (float) position.z();\n } else if (iterator.first == \"rgb\") {\n *iterator.second = gridMap.at(\"color\", *mapIterator);\n ;\n } else {\n *iterator.second = gridMap.at(iterator.first, *mapIterator);\n }\n }\n\n ++mapIterator;\n for (auto& iterator : fieldIterators) {\n ++iterator.second;\n }\n }\n}\n\nvoid GridMapRosConverter::toOccupancyGrid(const grid_map::GridMap& gridMap,\n const std::string& layer, float dataMin, float dataMax,\n nav_msgs::OccupancyGrid& occupancyGrid)\n{\n occupancyGrid.header.frame_id = gridMap.getFrameId();\n occupancyGrid.header.stamp.fromNSec(gridMap.getTimestamp());\n occupancyGrid.info.map_load_time = occupancyGrid.header.stamp; \/\/ Same as header stamp as we do not load the map.\n occupancyGrid.info.resolution = gridMap.getResolution();\n occupancyGrid.info.width = gridMap.getSize()(0);\n occupancyGrid.info.height = gridMap.getSize()(1);\n Position positionOfOrigin;\n getPositionOfDataStructureOrigin(gridMap.getPosition(), gridMap.getLength(), positionOfOrigin);\n occupancyGrid.info.origin.position.x = positionOfOrigin.x();\n occupancyGrid.info.origin.position.y = positionOfOrigin.y();\n occupancyGrid.info.origin.position.z = 0.0;\n occupancyGrid.info.origin.orientation.x = 0.0;\n occupancyGrid.info.origin.orientation.y = 0.0;\n occupancyGrid.info.origin.orientation.z = 1.0; \/\/ yes, this is correct.\n occupancyGrid.info.origin.orientation.w = 0.0;\n occupancyGrid.data.resize(occupancyGrid.info.width * occupancyGrid.info.height);\n\n \/\/ Occupancy probabilities are in the range [0,100]. Unknown is -1.\n const float cellMin = 0;\n const float cellMax = 100;\n const float cellRange = cellMax - cellMin;\n\n for (GridMapIterator iterator(gridMap); !iterator.isPassedEnd(); ++iterator) {\n float value = (gridMap.at(layer, *iterator) - dataMin) \/ (dataMax - dataMin);\n if (isnan(value))\n value = -1;\n else\n value = cellMin + min(max(0.0f, value), 1.0f) * cellRange;\n \/\/ Occupancy grid claims to be row-major order, but it does not seem that way.\n \/\/ http:\/\/docs.ros.org\/api\/nav_msgs\/html\/msg\/OccupancyGrid.html.\n unsigned int index = get1dIndexFrom2dIndex(*iterator, gridMap.getSize(), false);\n occupancyGrid.data[index] = value;\n }\n}\n\nvoid GridMapRosConverter::toGridCells(const grid_map::GridMap& gridMap, const std::string& layer, float lowerThreshold,\n float upperThreshold, nav_msgs::GridCells& gridCells)\n{\n gridCells.header.frame_id = gridMap.getFrameId();\n gridCells.header.stamp.fromNSec(gridMap.getTimestamp());\n gridCells.cell_width = gridMap.getResolution();\n gridCells.cell_height = gridMap.getResolution();\n\n for (GridMapIterator iterator(gridMap); !iterator.isPassedEnd(); ++iterator) {\n if (!gridMap.isValid(*iterator, layer)) continue;\n if (gridMap.at(layer, *iterator) >= lowerThreshold\n && gridMap.at(layer, *iterator) <= upperThreshold) {\n Position position;\n gridMap.getPosition(*iterator, position);\n geometry_msgs::Point point;\n point.x = position.x();\n point.y = position.y();\n gridCells.cells.push_back(point);\n }\n }\n}\n \n\nbool GridMapRosConverter::saveToBag(const grid_map::GridMap& gridMap, const std::string& pathToBag,\n const std::string& topic)\n{\n grid_map_msgs::GridMap message;\n toMessage(gridMap, message);\n ros::Time time(gridMap.getTimestamp());\n\n if (!time.isValid()) {\n if (!ros::Time::isValid()) ros::Time::init();\n time = ros::Time::now();\n }\n\n rosbag::Bag bag;\n bag.open(pathToBag, rosbag::bagmode::Write);\n bag.write(topic, time, message);\n bag.close();\n return true;\n}\n\nbool GridMapRosConverter::loadFromBag(const std::string& pathToBag, const std::string& topic,\n grid_map::GridMap& gridMap)\n{\n rosbag::Bag bag;\n bag.open(pathToBag, rosbag::bagmode::Read);\n rosbag::View view(bag, rosbag::TopicQuery(topic));\n\n for (const auto& messageInstance : view) {\n grid_map_msgs::GridMap::ConstPtr message = messageInstance.instantiate<grid_map_msgs::GridMap>();\n if (message != NULL) {\n fromMessage(*message, gridMap);\n } else {\n bag.close();\n ROS_WARN(\"Unable to load data from ROS bag.\");\n return false;\n }\n }\n bag.close();\n return true;\n}\n\n} \/* namespace *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Temporarily whitelist DirectoryLister, which is blocking the IO thread.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 2002-2004, Michael Brade <brade@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*******************************************************************\/\n\n#include <QFile>\n#include <QFont>\n#include <QPoint>\n#include <QColor>\n#include <QStringList>\n#include <QTextStream>\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kglobal.h>\n#include <kurl.h>\n#include <kstandarddirs.h>\n#include <kconfig.h>\n#include <kio\/netaccess.h>\n\n#include <unistd.h>\n\n#include \"knoteslegacy.h\"\n#include \"knoteconfig.h\"\n#include \"version.h\"\n\n#include <kcal\/calendarlocal.h>\n#include <kcal\/journal.h>\n\n#include <netwm.h>\n\nusing namespace KCal;\n\n\nvoid KNotesLegacy::cleanUp()\n{\n \/\/ remove old (KDE 1.x) local config file if it still exists\n QString configfile = KGlobal::dirs()->saveLocation( \"config\" ) + \"knotesrc\";\n if ( QFile::exists( configfile ) ) {\n KConfigGroup test(\n KSharedConfig::openConfig( configfile, KConfig::SimpleConfig ), \n \"General\" );\n double version = test.readEntry( \"version\", 1.0 );\n \n if ( version == 1.0 ) {\n if ( !( KStandardDirs::checkAccess( configfile, W_OK ) &&\n QFile::remove( configfile ) ) ) {\n kError( 5500 ) <<\"Could not delete old config file\" << configfile;\n }\n }\n }\n}\n\nbool KNotesLegacy::convert( CalendarLocal *calendar )\n{\n bool converted = false;\n \n QDir noteDir( KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" ) );\n QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );\n for ( QStringList::Iterator note = notes.begin(); note != notes.end();\n note++ ) {\n QString file = noteDir.absoluteFilePath( *note );\n KConfig *test = new KConfig( file, KConfig::SimpleConfig );\n KConfigGroup grp( test, \"General\" );\n double version = grp.readEntry( \"version\", 1.0 );\n \n if ( version < 3.0 ) {\n \n \/\/ create the new note\n Journal *journal = new Journal();\n bool success;\n \n if ( version < 2.0 ) {\n success = convertKNotes1Config( journal, noteDir, *note );\n } else {\n success = convertKNotes2Config( journal, noteDir, *note );\n }\n \n \/\/ could not convert file => do not add a new note\n if ( !success ) {\n delete journal;\n } else {\n calendar->addJournal( journal );\n converted = true;\n }\n } else if ( version < 3.2 ) { \/\/ window state changed for version 3.2\n#ifdef Q_WS_X11\n uint state = grp.readEntry( \"state\", uint( NET::SkipTaskbar ) );\n \n grp.writeEntry( \"ShowInTaskbar\",\n ( state & NET::SkipTaskbar ) ? false : true );\n grp.writeEntry( \"KeepAbove\", \n ( state & NET::KeepAbove ) ? true : false );\n#endif\n grp.deleteEntry( \"state\" );\n }\n delete test;\n }\n \n return converted;\n}\n\nbool KNotesLegacy::convertKNotes1Config( Journal *journal, QDir ¬eDir,\n const QString &file )\n{\n QFile infile( noteDir.absoluteFilePath( file ) );\n if ( !infile.open( QIODevice::ReadOnly ) ) {\n kError( 5500 ) << \"Could not open input file: \\\"\"\n << infile.fileName() << \"\\\"\";\n return false;\n }\n \n QTextStream input( &infile );\n \n \/\/ get the name\n journal->setSummary( input.readLine() );\n \n QStringList props = input.readLine().split( '+', QString::SkipEmptyParts );\n \n \/\/ robustness\n if ( props.count() != 13 ) {\n kWarning( 5500 ) <<\"The file \\\"\" << infile.fileName()\n << \"\\\" lacks version information but is not a valid\"\n << \"KNotes 1 config file either!\";\n return false;\n }\n \n \/\/ the new configfile's name\n QString configFile = noteDir.absoluteFilePath( journal->uid() );\n \n \/\/ set the defaults\n KIO::NetAccess::file_copy(\n KUrl( KGlobal::dirs()->saveLocation( \"config\" ) + \"knotesrc\" ),\n KUrl( configFile ),\n 0\n );\n \n KNoteConfig config( KSharedConfig::openConfig( configFile,\n KConfig::NoGlobals ) );\n config.readConfig();\n config.setVersion( KNOTES_VERSION );\n \n \/\/ get the geometry\n config.setWidth( props[3].toUInt() );\n config.setHeight( props[4].toUInt() );\n \n \/\/ get the background color\n uint red = input.readLine().toUInt();\n uint green = input.readLine().toUInt();\n uint blue = input.readLine().toUInt();\n config.setBgColor( QColor( Qt::red, Qt::green, Qt::blue ) );\n \n \/\/ get the foreground color\n red = input.readLine().toUInt();\n green = input.readLine().toUInt();\n blue = input.readLine().toUInt();\n config.setFgColor( QColor( Qt::red, Qt::green, Qt::blue ) );\n \n \/\/ get the font\n QString fontfamily = input.readLine();\n if ( fontfamily.isEmpty() )\n fontfamily = QString( \"Sans Serif\" );\n uint size = input.readLine().toUInt();\n size = qMax( size, ( uint ) 4 );\n uint weight = input.readLine().toUInt();\n bool italic = ( input.readLine().toUInt() == 1 );\n QFont font( fontfamily, size, weight, italic );\n \n config.setTitleFont( font );\n config.setFont( font );\n \n \/\/ 3d frame? Not supported yet!\n input.readLine();\n \n \/\/ autoindent\n config.setAutoIndent( input.readLine().toUInt() == 1 );\n \n \/\/ KNotes 1 never had rich text\n config.setRichText( false );\n \n int note_desktop = props[0].toUInt();\n \n \/\/ hidden or on all desktops?\n if ( input.readLine().toUInt() == 1 )\n note_desktop = 0;\n#ifdef Q_WS_X11\n else if ( props[11].toUInt() == 1 )\n note_desktop = NETWinInfo::OnAllDesktops;\n#endif\n \n config.setDesktop( note_desktop );\n config.setPosition( QPoint( props[1].toUInt(), props[2].toUInt() ) );\n config.setKeepAbove( props[12].toUInt() & 2048 );\n \n config.writeConfig();\n \n \/\/ get the text\n QString text;\n while ( !input.atEnd() ) {\n text.append( input.readLine() );\n if ( !input.atEnd() ) {\n text.append( '\\n' );\n }\n }\n \n journal->setDescription( text );\n \n if ( !infile.remove() )\n {\n kWarning( 5500 ) << \"Could not delete input file: \\\"\" << infile.fileName()\n << \"\\\"\";\n }\n \n return true;\n}\n\nbool KNotesLegacy::convertKNotes2Config( Journal *journal, QDir ¬eDir,\n const QString &file )\n{\n QString configFile = noteDir.absoluteFilePath( journal->uid() );\n \n \/\/ new name for config file\n if ( !noteDir.rename( file, journal->uid() ) ) {\n kError( 5500 ) << \"Could not rename input file: \\\"\"\n << noteDir.absoluteFilePath( file ) << \"\\\" to \\\"\"\n << configFile << \"\\\"!\";\n return false;\n }\n \n \/\/ update the config\n KConfig config( configFile );\n KConfigGroup grp( &config, \"Data\" );\n journal->setSummary( grp.readEntry( \"name\" ) );\n config.deleteGroup( \"Data\", KConfig::Localized );\n KConfigGroup grp2(&config, \"General\" ); \/\/ XXX right?\n grp2.writeEntry( \"version\", KNOTES_VERSION );\n KConfigGroup grp3(&config, \"WindowDisplay\" ); \/\/ XXX right?\n#ifdef Q_WS_X11\n uint state = grp3.readEntry( \"state\", uint( NET::SkipTaskbar ) );\n grp3.writeEntry( \"ShowInTaskbar\", \n ( state & NET::SkipTaskbar ) ? false : true );\n grp3.writeEntry( \"KeepAbove\", \n ( state & NET::KeepAbove ) ? true : false );\n#endif\n grp3.deleteEntry( \"state\" );\n \n \/\/ load the saved text and put it in the journal\n QFile infile( noteDir.absoluteFilePath( \".\" + file + \"_data\" ) );\n if ( infile.open( QIODevice::ReadOnly ) ) {\n QTextStream input( &infile );\n input.setCodec( \"UTF-8\" );\n journal->setDescription( input.readAll() );\n if ( !infile.remove() ) {\n kWarning( 5500 ) << \"Could not delete data file: \\\"\" << infile.fileName()\n << \"\\\"\";\n }\n }\n else\n kWarning( 5500 ) << \"Could not open data file: \\\"\" << infile.fileName()\n << \"\\\"\";\n \n return true;\n}\n<commit_msg>Const'ify<commit_after>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 2002-2004, Michael Brade <brade@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*******************************************************************\/\n\n#include <QFile>\n#include <QFont>\n#include <QPoint>\n#include <QColor>\n#include <QStringList>\n#include <QTextStream>\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kglobal.h>\n#include <kurl.h>\n#include <kstandarddirs.h>\n#include <kconfig.h>\n#include <kio\/netaccess.h>\n\n#include <unistd.h>\n\n#include \"knoteslegacy.h\"\n#include \"knoteconfig.h\"\n#include \"version.h\"\n\n#include <kcal\/calendarlocal.h>\n#include <kcal\/journal.h>\n\n#include <netwm.h>\n\nusing namespace KCal;\n\n\nvoid KNotesLegacy::cleanUp()\n{\n \/\/ remove old (KDE 1.x) local config file if it still exists\n QString configfile = KGlobal::dirs()->saveLocation( \"config\" ) + \"knotesrc\";\n if ( QFile::exists( configfile ) ) {\n KConfigGroup test(\n KSharedConfig::openConfig( configfile, KConfig::SimpleConfig ), \n \"General\" );\n double version = test.readEntry( \"version\", 1.0 );\n \n if ( version == 1.0 ) {\n if ( !( KStandardDirs::checkAccess( configfile, W_OK ) &&\n QFile::remove( configfile ) ) ) {\n kError( 5500 ) <<\"Could not delete old config file\" << configfile;\n }\n }\n }\n}\n\nbool KNotesLegacy::convert( CalendarLocal *calendar )\n{\n bool converted = false;\n \n QDir noteDir( KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" ) );\n const QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );\n for ( QStringList::ConstIterator note = notes.constBegin(); note != notes.constEnd();\n ++note ) {\n QString file = noteDir.absoluteFilePath( *note );\n KConfig *test = new KConfig( file, KConfig::SimpleConfig );\n KConfigGroup grp( test, \"General\" );\n double version = grp.readEntry( \"version\", 1.0 );\n \n if ( version < 3.0 ) {\n \n \/\/ create the new note\n Journal *journal = new Journal();\n bool success;\n \n if ( version < 2.0 ) {\n success = convertKNotes1Config( journal, noteDir, *note );\n } else {\n success = convertKNotes2Config( journal, noteDir, *note );\n }\n \n \/\/ could not convert file => do not add a new note\n if ( !success ) {\n delete journal;\n } else {\n calendar->addJournal( journal );\n converted = true;\n }\n } else if ( version < 3.2 ) { \/\/ window state changed for version 3.2\n#ifdef Q_WS_X11\n uint state = grp.readEntry( \"state\", uint( NET::SkipTaskbar ) );\n \n grp.writeEntry( \"ShowInTaskbar\",\n ( state & NET::SkipTaskbar ) ? false : true );\n grp.writeEntry( \"KeepAbove\", \n ( state & NET::KeepAbove ) ? true : false );\n#endif\n grp.deleteEntry( \"state\" );\n }\n delete test;\n }\n \n return converted;\n}\n\nbool KNotesLegacy::convertKNotes1Config( Journal *journal, QDir ¬eDir,\n const QString &file )\n{\n QFile infile( noteDir.absoluteFilePath( file ) );\n if ( !infile.open( QIODevice::ReadOnly ) ) {\n kError( 5500 ) << \"Could not open input file: \\\"\"\n << infile.fileName() << \"\\\"\";\n return false;\n }\n \n QTextStream input( &infile );\n \n \/\/ get the name\n journal->setSummary( input.readLine() );\n \n QStringList props = input.readLine().split( '+', QString::SkipEmptyParts );\n \n \/\/ robustness\n if ( props.count() != 13 ) {\n kWarning( 5500 ) <<\"The file \\\"\" << infile.fileName()\n << \"\\\" lacks version information but is not a valid\"\n << \"KNotes 1 config file either!\";\n return false;\n }\n \n \/\/ the new configfile's name\n QString configFile = noteDir.absoluteFilePath( journal->uid() );\n \n \/\/ set the defaults\n KIO::NetAccess::file_copy(\n KUrl( KGlobal::dirs()->saveLocation( \"config\" ) + \"knotesrc\" ),\n KUrl( configFile ),\n 0\n );\n \n KNoteConfig config( KSharedConfig::openConfig( configFile,\n KConfig::NoGlobals ) );\n config.readConfig();\n config.setVersion( KNOTES_VERSION );\n \n \/\/ get the geometry\n config.setWidth( props[3].toUInt() );\n config.setHeight( props[4].toUInt() );\n \n \/\/ get the background color\n uint red = input.readLine().toUInt();\n uint green = input.readLine().toUInt();\n uint blue = input.readLine().toUInt();\n config.setBgColor( QColor( Qt::red, Qt::green, Qt::blue ) );\n \n \/\/ get the foreground color\n red = input.readLine().toUInt();\n green = input.readLine().toUInt();\n blue = input.readLine().toUInt();\n config.setFgColor( QColor( Qt::red, Qt::green, Qt::blue ) );\n \n \/\/ get the font\n QString fontfamily = input.readLine();\n if ( fontfamily.isEmpty() )\n fontfamily = QString( \"Sans Serif\" );\n uint size = input.readLine().toUInt();\n size = qMax( size, ( uint ) 4 );\n uint weight = input.readLine().toUInt();\n bool italic = ( input.readLine().toUInt() == 1 );\n QFont font( fontfamily, size, weight, italic );\n \n config.setTitleFont( font );\n config.setFont( font );\n \n \/\/ 3d frame? Not supported yet!\n input.readLine();\n \n \/\/ autoindent\n config.setAutoIndent( input.readLine().toUInt() == 1 );\n \n \/\/ KNotes 1 never had rich text\n config.setRichText( false );\n \n int note_desktop = props[0].toUInt();\n \n \/\/ hidden or on all desktops?\n if ( input.readLine().toUInt() == 1 )\n note_desktop = 0;\n#ifdef Q_WS_X11\n else if ( props[11].toUInt() == 1 )\n note_desktop = NETWinInfo::OnAllDesktops;\n#endif\n \n config.setDesktop( note_desktop );\n config.setPosition( QPoint( props[1].toUInt(), props[2].toUInt() ) );\n config.setKeepAbove( props[12].toUInt() & 2048 );\n \n config.writeConfig();\n \n \/\/ get the text\n QString text;\n while ( !input.atEnd() ) {\n text.append( input.readLine() );\n if ( !input.atEnd() ) {\n text.append( '\\n' );\n }\n }\n \n journal->setDescription( text );\n \n if ( !infile.remove() )\n {\n kWarning( 5500 ) << \"Could not delete input file: \\\"\" << infile.fileName()\n << \"\\\"\";\n }\n \n return true;\n}\n\nbool KNotesLegacy::convertKNotes2Config( Journal *journal, QDir ¬eDir,\n const QString &file )\n{\n QString configFile = noteDir.absoluteFilePath( journal->uid() );\n \n \/\/ new name for config file\n if ( !noteDir.rename( file, journal->uid() ) ) {\n kError( 5500 ) << \"Could not rename input file: \\\"\"\n << noteDir.absoluteFilePath( file ) << \"\\\" to \\\"\"\n << configFile << \"\\\"!\";\n return false;\n }\n \n \/\/ update the config\n KConfig config( configFile );\n KConfigGroup grp( &config, \"Data\" );\n journal->setSummary( grp.readEntry( \"name\" ) );\n config.deleteGroup( \"Data\", KConfig::Localized );\n KConfigGroup grp2(&config, \"General\" ); \/\/ XXX right?\n grp2.writeEntry( \"version\", KNOTES_VERSION );\n KConfigGroup grp3(&config, \"WindowDisplay\" ); \/\/ XXX right?\n#ifdef Q_WS_X11\n uint state = grp3.readEntry( \"state\", uint( NET::SkipTaskbar ) );\n grp3.writeEntry( \"ShowInTaskbar\", \n ( state & NET::SkipTaskbar ) ? false : true );\n grp3.writeEntry( \"KeepAbove\", \n ( state & NET::KeepAbove ) ? true : false );\n#endif\n grp3.deleteEntry( \"state\" );\n \n \/\/ load the saved text and put it in the journal\n QFile infile( noteDir.absoluteFilePath( '.' + file + \"_data\" ) );\n if ( infile.open( QIODevice::ReadOnly ) ) {\n QTextStream input( &infile );\n input.setCodec( \"UTF-8\" );\n journal->setDescription( input.readAll() );\n if ( !infile.remove() ) {\n kWarning( 5500 ) << \"Could not delete data file: \\\"\" << infile.fileName()\n << \"\\\"\";\n }\n }\n else\n kWarning( 5500 ) << \"Could not open data file: \\\"\" << infile.fileName()\n << \"\\\"\";\n \n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/* Test program to test the timer callbacks\n*\/\n\n#include <iostream>\n#include \"SDL.hh\"\nusing namespace RAGE;\n\nint loop_number = 0;\n\nclass ObjectWithCallback\n{\n\n\n\tpublic:\n\t\t\n\tunsigned int callback1(unsigned int interval, void* args)\n\t{\n\t\tstd::cout << \"Instance Method 1 Called back ! \" << std::endl;\n\t\treturn 0;\n\t}\n\t\n\tunsigned int callback2(unsigned int interval, void* args)\n\t{\n\t\t\/\/this should be only called 3 times\n\t\tstatic int iter = 5;\n\t\tstd::cout << \"Instance Method 2 Called back ! Number: \" << iter-- << std::endl;\n\t\tif ( iter != 0 )\n\t\t\treturn interval;\n\t\treturn 0;\n\t}\n};\n\nstatic unsigned int callback(unsigned int interval, void * args)\n{\n\tstd::cout << \"Static Function called back !\" << std::endl;\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tLogger testlog(\"testTimer\");\n\n\ttestlog << \"SDL init...\" << std::endl;\n\n\tSDL::App::getInstance().initTimer();\t\n\t\t\t\n\ttestlog << \"Creating instance\"<< std::endl;\n\tObjectWithCallback obj;\n\n\ttestlog << \"Creating instance timer\" << std::endl;\n\tSDL::Timer<ObjectWithCallback> timer1;\n\tSDL::Timer<ObjectWithCallback> timer2;\n\n\ttimer1.setInterval(2000);\n\ttimer1.setCallback(&obj,&ObjectWithCallback::callback1,(void*)NULL);\n\ttimer2.setInterval(100);\n\ttimer2.setCallback(&obj,&ObjectWithCallback::callback2,(void*)NULL);\n\t\n\ttestlog << \"Starting instance timer1 ( 2 sec )\" << std::endl;\n\ttimer1.start();\n\ttestlog << \"Starting instance timer2\" << std::endl;\n\ttimer2.start();\n\ttestlog << \"Starting static SDL timer ( 4 sec )\"<< std::endl;\n\tSDL_AddTimer(4000,callback,NULL);\n\n\tSDL::Delay(6000); \/\/TODO Display time running\n\n\treturn 0;\n}\n<commit_msg>Set Interval to 0 to show the BUG that the timer is looping infinitely instead of exiting.<commit_after>\n\/* Test program to test the timer callbacks\n*\/\n\n#include <iostream>\n#include \"SDL.hh\"\nusing namespace RAGE;\n\nint loop_number = 0;\n\nclass ObjectWithCallback\n{\n\n\n\tpublic:\n\t\t\n\tunsigned int callback1(unsigned int interval, void* args)\n\t{\n\t\tstd::cout << \"Instance Method 1 Called back ! \" << std::endl;\n\t\treturn 0;\n\t}\n\t\n\tunsigned int callback2(unsigned int interval, void* args)\n\t{\n\t\t\/\/this should be only called 3 times\n\t\tstatic int iter = 5;\n\t\tstd::cout << \"Instance Method 2 Called back ! Number: \" << iter-- << std::endl;\n\t\tif ( iter != 0 )\n\t\t\treturn interval;\n\t\treturn 0;\n\t}\n};\n\nstatic unsigned int callback(unsigned int interval, void * args)\n{\n\tstd::cout << \"Static Function called back !\" << std::endl;\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tLogger testlog(\"testTimer\");\n\n\ttestlog << \"SDL init...\" << std::endl;\n\n\tSDL::App::getInstance().initTimer();\t\n\t\t\t\n\ttestlog << \"Creating instance\"<< std::endl;\n\tObjectWithCallback obj;\n\n\ttestlog << \"Creating instance timer\" << std::endl;\n\tSDL::Timer<ObjectWithCallback> timer1;\n\tSDL::Timer<ObjectWithCallback> timer2;\n\n\ttimer1.setInterval(2000);\n\ttimer1.setCallback(&obj,&ObjectWithCallback::callback1,(void*)NULL);\n\ttimer2.setInterval(0); \/\/BUG!! when Interval = 0, the timer loop infinitly instead of exit like when there is the return 0;\n\ttimer2.setCallback(&obj,&ObjectWithCallback::callback2,(void*)NULL);\n\t\n\ttestlog << \"Starting instance timer1 ( 2 sec )\" << std::endl;\n\ttimer1.start();\n\ttestlog << \"Starting instance timer2\" << std::endl;\n\ttimer2.start();\n\ttestlog << \"Starting static SDL timer ( 4 sec )\"<< std::endl;\n\tSDL_AddTimer(4000,callback,NULL);\n\n\tSDL::Delay(6000); \/\/TODO Display time running\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/* $Id$ *\/\n\/\/_________________________________________________________________________\n\/\/Basic Memory Leak utility. \n\/\/ You can use this tiny class to *see* if your program is leaking.\n\/\/ Usage:\n\/\/ AliMemoryWatcher memwatcher;\n\/\/ some program loop on events here {\n\/\/ if ( nevents % x == 0 ) \n\/\/ {\n\/\/ \/\/ take a sample every x events\n\/\/ memwatcher.Watch(nevents);\n\/\/ }\n\/\/ }\n\/\/ TFile f(\"out.root\",\"RECREATE\");\n\/\/ memwatcher.Write();\n\/\/ f.Close();\n\/\/ In the output root file you'll get 3 graphs representing\n\/\/ the evolAliPHOSon, as a function of the number of events, of :\n\/\/ - VSIZE is the virtual size (in KBytes) of your program, that is sort of\n\/\/ the total memory used\n\/\/ - RSSIZE is the resident size (in KBytes), that is, the part of your \n\/\/ program which is really in physical memory.\n\/\/ - TIME is an estimate of time per event (really it's the time elasped\n\/\/ between two calls to watch method)\n\/\/ WARNING: this is far from a bulletproof memory report (it's basically \n\/\/ using UNIX command ps -h -p [PID] -o vsize,rssize to do its job).\n\/\/ It has only been tested on Linux so far. \n\/\/ But by fitting the VSIZE by a pol1 under ROOT, you'll see right away\n\/\/ by how much your program is leaking. \n\/\/*-- Author: Laurent Aphecetche(SUBATECH)\n\/\/ --- std system ---\nclass assert ; \n#include <malloc.h>\n\/\/ --- AliRoot header files ---\n#include \"AliMemoryWatcher.h\"\n\/\/ --- ROOT system ---\n#include \"TSystem.h\"\n#include \"TGraph.h\"\n#include \"TH2.h\"\n#include \"TStopwatch.h\"\n#include \"TError.h\"\n\nClassImp(AliMemoryWatcher)\n\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::AliMemoryWatcher(UInt_t maxsize)\n{\n \/\/ctor\n fMAXSIZE=maxsize;\n fUseMallinfo = true;\n fPID = gSystem->GetPid();\n sprintf(fCmd,\"ps -h -p %d -o vsize,rssize\",fPID);\n fX = new Int_t[fMAXSIZE];\n fVSIZE = new Int_t[fMAXSIZE];\n fRSSIZE = new Int_t[fMAXSIZE];\n fTIME = new Double_t[fMAXSIZE];\n fSize=0;\n fDisabled=false;\n fTimer=0;\n}\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::AliMemoryWatcher(const AliMemoryWatcher& mw):\n TObject(mw)\n{\n \/\/copy ctor\n fMAXSIZE = mw.fMAXSIZE ;\n fUseMallinfo = mw.fUseMallinfo;\n fPID = mw.fPID ; \n strcpy(fCmd, mw.fCmd) ; \n fX = new Int_t[fMAXSIZE];\n fVSIZE = new Int_t[fMAXSIZE];\n fRSSIZE = new Int_t[fMAXSIZE];\n fTIME = new Double_t[fMAXSIZE];\n fSize=0;\n fDisabled=false;\n fTimer=0; \n}\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::~AliMemoryWatcher()\n{\n \/\/ dtor\n delete[] fVSIZE;\n delete[] fRSSIZE;\n delete[] fX;\n delete[] fTIME;\n delete fTimer;\n}\n\/\/_____________________________________________________________________________\nvoid AliMemoryWatcher::Watch(Int_t x)\n{\n \/\/ Sets the point where CPU parameters have to be monitored\n if ( !fDisabled && fSize < fMAXSIZE ) {\n if ( fSize==0 ) {\n assert(fTimer==0);\n fTimer = new TStopwatch;\n fTimer->Start(true);\n fTimer->Stop();\n }\n if ( fUseMallinfo ) {\n#ifdef __linux\n static struct mallinfo meminfo;\n meminfo = mallinfo();\n fX[fSize] = x ;\n fVSIZE[fSize] = (meminfo.hblkhd + meminfo.uordblks) \/ 1024;\n fRSSIZE[fSize] = meminfo.uordblks \/ 1024;\n fTIME[fSize] = fTimer->CpuTime();\n fSize++;\n#else\n ::Fatal(\"Watch\",\"Please SetUseMallinfo to kFALSE on this system\");\n#endif\n } else {\n static Int_t vsize, rssize;\n static FILE* pipe = 0;\n pipe = popen(fCmd,\"r\");\n if ( pipe ) {\n \n\tfscanf(pipe,\"%d %d\",&vsize,&rssize);\n \n\tfX[fSize] = x ;\n\tfVSIZE[fSize] = vsize ;\n\tfRSSIZE[fSize] = rssize ;\n\tfTIME[fSize] = fTimer->CpuTime();\n\tfSize++;\n }\n assert(pclose(pipe)!=-1);\n }\n fTimer->Start(true);\n }\n else {\n fDisabled=true;\n Error(\"watch\", \"I'm full !\" ) ;\n }\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphVSIZE(void)\n{\n \/\/ Fills the graph with the virtual memory sized used\n TGraph* g = 0;\n if ( Size() )\n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),VSIZE(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphRSSIZE(void)\n{\n \/\/ Fills the graph with the real memory sized used\n TGraph* g = 0;\n if ( Size() ) \n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),RSSIZE(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphTIME(void)\n{\n \/\/ Fills the raph with the used CPU time\n TGraph* g = 0;\n if ( Size() ) \n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),TIME(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTH2*\nAliMemoryWatcher::Frame(void) const\n{\n \/\/creates the frame histo in which the graphs will be plotted \n Double_t xmin=1E30;\n Double_t xmax=0;\n Double_t ymin=1;\n Double_t ymax=0;\n UInt_t i ; \n for (i=0; i < Size() ; i++ ) {\n if ( X(i) < xmin ) xmin = X(i);\n if ( X(i) > xmax ) xmax = X(i);\n Double_t y = VSIZE(i)+RSSIZE(i);\n if ( y > ymax ) ymax = y;\n if ( VSIZE(i) < ymin ) ymin = VSIZE(i);\n if ( RSSIZE(i) < ymin ) ymin = RSSIZE(i);\n }\n TH2F* h = new TH2F(\"frame\",\"\",10,xmin,xmax,10,ymin*0.8,ymax*1.2);\n return h;\n}\n\/\/_____________________________________________________________________________\nInt_t\nAliMemoryWatcher::Write(const char *, Int_t, Int_t)\n{\n \/\/ Stores the graphs in a file \n if ( GraphVSIZE() ) GraphVSIZE()->Write(\"VSIZE\",TObject::kOverwrite);\n if ( GraphRSSIZE() ) GraphRSSIZE() ->Write(\"RSSIZE\",TObject::kOverwrite);\n if ( GraphTIME() ) GraphTIME()->Write(\"TIME\",TObject::kOverwrite);\n return 0;\n}\n<commit_msg>malloc in stdlib.h on Mac<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/* $Id$ *\/\n\/\/_________________________________________________________________________\n\/\/Basic Memory Leak utility. \n\/\/ You can use this tiny class to *see* if your program is leaking.\n\/\/ Usage:\n\/\/ AliMemoryWatcher memwatcher;\n\/\/ some program loop on events here {\n\/\/ if ( nevents % x == 0 ) \n\/\/ {\n\/\/ \/\/ take a sample every x events\n\/\/ memwatcher.Watch(nevents);\n\/\/ }\n\/\/ }\n\/\/ TFile f(\"out.root\",\"RECREATE\");\n\/\/ memwatcher.Write();\n\/\/ f.Close();\n\/\/ In the output root file you'll get 3 graphs representing\n\/\/ the evolAliPHOSon, as a function of the number of events, of :\n\/\/ - VSIZE is the virtual size (in KBytes) of your program, that is sort of\n\/\/ the total memory used\n\/\/ - RSSIZE is the resident size (in KBytes), that is, the part of your \n\/\/ program which is really in physical memory.\n\/\/ - TIME is an estimate of time per event (really it's the time elasped\n\/\/ between two calls to watch method)\n\/\/ WARNING: this is far from a bulletproof memory report (it's basically \n\/\/ using UNIX command ps -h -p [PID] -o vsize,rssize to do its job).\n\/\/ It has only been tested on Linux so far. \n\/\/ But by fitting the VSIZE by a pol1 under ROOT, you'll see right away\n\/\/ by how much your program is leaking. \n\/\/*-- Author: Laurent Aphecetche(SUBATECH)\n\/\/ --- std system ---\nclass assert ; \n#ifdef __APPLE__\n#include <stdlib.h>\n#else\n#include <malloc.h>\n#endif\n\/\/ --- AliRoot header files ---\n#include \"AliMemoryWatcher.h\"\n\/\/ --- ROOT system ---\n#include \"TSystem.h\"\n#include \"TGraph.h\"\n#include \"TH2.h\"\n#include \"TStopwatch.h\"\n#include \"TError.h\"\n\nClassImp(AliMemoryWatcher)\n\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::AliMemoryWatcher(UInt_t maxsize)\n{\n \/\/ctor\n fMAXSIZE=maxsize;\n fUseMallinfo = true;\n fPID = gSystem->GetPid();\n sprintf(fCmd,\"ps -h -p %d -o vsize,rssize\",fPID);\n fX = new Int_t[fMAXSIZE];\n fVSIZE = new Int_t[fMAXSIZE];\n fRSSIZE = new Int_t[fMAXSIZE];\n fTIME = new Double_t[fMAXSIZE];\n fSize=0;\n fDisabled=false;\n fTimer=0;\n}\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::AliMemoryWatcher(const AliMemoryWatcher& mw):\n TObject(mw)\n{\n \/\/copy ctor\n fMAXSIZE = mw.fMAXSIZE ;\n fUseMallinfo = mw.fUseMallinfo;\n fPID = mw.fPID ; \n strcpy(fCmd, mw.fCmd) ; \n fX = new Int_t[fMAXSIZE];\n fVSIZE = new Int_t[fMAXSIZE];\n fRSSIZE = new Int_t[fMAXSIZE];\n fTIME = new Double_t[fMAXSIZE];\n fSize=0;\n fDisabled=false;\n fTimer=0; \n}\n\/\/_____________________________________________________________________________\nAliMemoryWatcher::~AliMemoryWatcher()\n{\n \/\/ dtor\n delete[] fVSIZE;\n delete[] fRSSIZE;\n delete[] fX;\n delete[] fTIME;\n delete fTimer;\n}\n\/\/_____________________________________________________________________________\nvoid AliMemoryWatcher::Watch(Int_t x)\n{\n \/\/ Sets the point where CPU parameters have to be monitored\n if ( !fDisabled && fSize < fMAXSIZE ) {\n if ( fSize==0 ) {\n assert(fTimer==0);\n fTimer = new TStopwatch;\n fTimer->Start(true);\n fTimer->Stop();\n }\n if ( fUseMallinfo ) {\n#ifdef __linux\n static struct mallinfo meminfo;\n meminfo = mallinfo();\n fX[fSize] = x ;\n fVSIZE[fSize] = (meminfo.hblkhd + meminfo.uordblks) \/ 1024;\n fRSSIZE[fSize] = meminfo.uordblks \/ 1024;\n fTIME[fSize] = fTimer->CpuTime();\n fSize++;\n#else\n ::Fatal(\"Watch\",\"Please SetUseMallinfo to kFALSE on this system\");\n#endif\n } else {\n static Int_t vsize, rssize;\n static FILE* pipe = 0;\n pipe = popen(fCmd,\"r\");\n if ( pipe ) {\n \n\tfscanf(pipe,\"%d %d\",&vsize,&rssize);\n \n\tfX[fSize] = x ;\n\tfVSIZE[fSize] = vsize ;\n\tfRSSIZE[fSize] = rssize ;\n\tfTIME[fSize] = fTimer->CpuTime();\n\tfSize++;\n }\n assert(pclose(pipe)!=-1);\n }\n fTimer->Start(true);\n }\n else {\n fDisabled=true;\n Error(\"watch\", \"I'm full !\" ) ;\n }\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphVSIZE(void)\n{\n \/\/ Fills the graph with the virtual memory sized used\n TGraph* g = 0;\n if ( Size() )\n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),VSIZE(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphRSSIZE(void)\n{\n \/\/ Fills the graph with the real memory sized used\n TGraph* g = 0;\n if ( Size() ) \n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),RSSIZE(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTGraph*\nAliMemoryWatcher::GraphTIME(void)\n{\n \/\/ Fills the raph with the used CPU time\n TGraph* g = 0;\n if ( Size() ) \n {\n g = new TGraph(Size());\n Int_t i ; \n for (i=0; i < g->GetN(); i++ ) {\n g->SetPoint(i,X(i),TIME(i));\n }\n }\n return g;\n}\n\/\/_____________________________________________________________________________\nTH2*\nAliMemoryWatcher::Frame(void) const\n{\n \/\/creates the frame histo in which the graphs will be plotted \n Double_t xmin=1E30;\n Double_t xmax=0;\n Double_t ymin=1;\n Double_t ymax=0;\n UInt_t i ; \n for (i=0; i < Size() ; i++ ) {\n if ( X(i) < xmin ) xmin = X(i);\n if ( X(i) > xmax ) xmax = X(i);\n Double_t y = VSIZE(i)+RSSIZE(i);\n if ( y > ymax ) ymax = y;\n if ( VSIZE(i) < ymin ) ymin = VSIZE(i);\n if ( RSSIZE(i) < ymin ) ymin = RSSIZE(i);\n }\n TH2F* h = new TH2F(\"frame\",\"\",10,xmin,xmax,10,ymin*0.8,ymax*1.2);\n return h;\n}\n\/\/_____________________________________________________________________________\nInt_t\nAliMemoryWatcher::Write(const char *, Int_t, Int_t)\n{\n \/\/ Stores the graphs in a file \n if ( GraphVSIZE() ) GraphVSIZE()->Write(\"VSIZE\",TObject::kOverwrite);\n if ( GraphRSSIZE() ) GraphRSSIZE() ->Write(\"RSSIZE\",TObject::kOverwrite);\n if ( GraphTIME() ) GraphTIME()->Write(\"TIME\",TObject::kOverwrite);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2020 Inria\n * Copyright (c) 2016 Georgia Institute of Technology\n * Copyright (c) 2008 Princeton University\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\n#ifndef __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n#define __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n\n#include <iostream>\n#include <vector>\n\n#include \"mem\/ruby\/common\/Consumer.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/CommonTypes.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/NetworkLink.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/OutVcState.hh\"\n\nclass CreditLink;\nclass Router;\n\nclass OutputUnit : public Consumer\n{\n public:\n OutputUnit(int id, PortDirection direction, Router *router);\n ~OutputUnit() = default;\n void set_out_link(NetworkLink *link);\n void set_credit_link(CreditLink *credit_link);\n void wakeup();\n flitBuffer* getOutQueue();\n void print(std::ostream& out) const {};\n void decrement_credit(int out_vc);\n void increment_credit(int out_vc);\n bool has_credit(int out_vc);\n bool has_free_vc(int vnet);\n int select_free_vc(int vnet);\n\n inline PortDirection get_direction() { return m_direction; }\n\n int\n get_credit_count(int vc)\n {\n return outVcState[vc].get_credit_count();\n }\n\n inline int\n get_outlink_id()\n {\n return m_out_link->get_id();\n }\n\n inline void\n set_vc_state(VC_state_type state, int vc, Cycles curTime)\n {\n outVcState[vc].setState(state, curTime);\n }\n\n inline bool\n is_vc_idle(int vc, Cycles curTime)\n {\n return (outVcState[vc].isInState(IDLE_, curTime));\n }\n\n void insert_flit(flit *t_flit);\n\n uint32_t functionalWrite(Packet *pkt);\n\n private:\n Router *m_router;\n int m_id;\n PortDirection m_direction;\n int m_vc_per_vnet;\n NetworkLink *m_out_link;\n CreditLink *m_credit_link;\n\n \/\/ This is for the network link to consume\n flitBuffer outBuffer;\n \/\/ vc state of downstream router\n std::vector<OutVcState> outVcState;\n};\n\n#endif \/\/ __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n<commit_msg>mem-ruby: Added M5_CLASS_VAR_USED to m_id in OutputUnit<commit_after>\/*\n * Copyright (c) 2020 Inria\n * Copyright (c) 2016 Georgia Institute of Technology\n * Copyright (c) 2008 Princeton University\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\n#ifndef __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n#define __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n\n#include <iostream>\n#include <vector>\n\n#include \"base\/compiler.hh\"\n#include \"mem\/ruby\/common\/Consumer.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/CommonTypes.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/NetworkLink.hh\"\n#include \"mem\/ruby\/network\/garnet2.0\/OutVcState.hh\"\n\nclass CreditLink;\nclass Router;\n\nclass OutputUnit : public Consumer\n{\n public:\n OutputUnit(int id, PortDirection direction, Router *router);\n ~OutputUnit() = default;\n void set_out_link(NetworkLink *link);\n void set_credit_link(CreditLink *credit_link);\n void wakeup();\n flitBuffer* getOutQueue();\n void print(std::ostream& out) const {};\n void decrement_credit(int out_vc);\n void increment_credit(int out_vc);\n bool has_credit(int out_vc);\n bool has_free_vc(int vnet);\n int select_free_vc(int vnet);\n\n inline PortDirection get_direction() { return m_direction; }\n\n int\n get_credit_count(int vc)\n {\n return outVcState[vc].get_credit_count();\n }\n\n inline int\n get_outlink_id()\n {\n return m_out_link->get_id();\n }\n\n inline void\n set_vc_state(VC_state_type state, int vc, Cycles curTime)\n {\n outVcState[vc].setState(state, curTime);\n }\n\n inline bool\n is_vc_idle(int vc, Cycles curTime)\n {\n return (outVcState[vc].isInState(IDLE_, curTime));\n }\n\n void insert_flit(flit *t_flit);\n\n uint32_t functionalWrite(Packet *pkt);\n\n private:\n Router *m_router;\n int M5_CLASS_VAR_USED m_id;\n PortDirection m_direction;\n int m_vc_per_vnet;\n NetworkLink *m_out_link;\n CreditLink *m_credit_link;\n\n \/\/ This is for the network link to consume\n flitBuffer outBuffer;\n \/\/ vc state of downstream router\n std::vector<OutVcState> outVcState;\n};\n\n#endif \/\/ __MEM_RUBY_NETWORK_GARNET2_0_OUTPUTUNIT_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n ASSERT_TRUE(RunExtensionTest(\"popup_api\")) << message_;\n}\n<commit_msg>Disable flaky (crashing) ExtensionApiTest.Popup<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n\/\/ This test has been disabled because it was crashing \n\/\/ browsertests. crbug.com\/26599\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n ASSERT_TRUE(RunExtensionTest(\"popup_api\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_toolbar_model.h\"\n\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nExtensionToolbarModel::ExtensionToolbarModel(ExtensionsService* service)\n : service_(service),\n prefs_(service->profile()->GetPrefs()),\n extensions_initialized_(false) {\n DCHECK(service_);\n\n registrar_.Add(this, NotificationType::EXTENSION_LOADED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSIONS_READY,\n Source<Profile>(service_->profile()));\n\n visible_icon_count_ = prefs_->GetInteger(prefs::kExtensionToolbarSize);\n}\n\nExtensionToolbarModel::~ExtensionToolbarModel() {\n}\n\nvoid ExtensionToolbarModel::DestroyingProfile() {\n registrar_.RemoveAll();\n}\n\nvoid ExtensionToolbarModel::AddObserver(Observer* observer) {\n observers_.AddObserver(observer);\n}\n\nvoid ExtensionToolbarModel::RemoveObserver(Observer* observer) {\n observers_.RemoveObserver(observer);\n}\n\nvoid ExtensionToolbarModel::MoveBrowserAction(Extension* extension,\n int index) {\n ExtensionList::iterator pos = std::find(begin(), end(), extension);\n if (pos == end()) {\n NOTREACHED();\n return;\n }\n toolitems_.erase(pos);\n\n int i = 0;\n bool inserted = false;\n for (ExtensionList::iterator iter = begin(); iter != end(); ++iter, ++i) {\n if (i == index) {\n toolitems_.insert(iter, extension);\n inserted = true;\n break;\n }\n }\n\n if (!inserted) {\n DCHECK_EQ(index, static_cast<int>(toolitems_.size()));\n index = toolitems_.size();\n\n toolitems_.push_back(extension);\n }\n\n FOR_EACH_OBSERVER(Observer, observers_, BrowserActionMoved(extension, index));\n\n UpdatePrefs();\n}\n\nvoid ExtensionToolbarModel::SetVisibleIconCount(int count) {\n visible_icon_count_ = count == static_cast<int>(size()) ? -1 : count;\n prefs_->SetInteger(prefs::kExtensionToolbarSize, visible_icon_count_);\n}\n\nvoid ExtensionToolbarModel::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::EXTENSIONS_READY) {\n InitializeExtensionList();\n return;\n }\n\n if (!service_->is_ready())\n return;\n\n Extension* extension = Details<Extension>(details).ptr();\n if (type == NotificationType::EXTENSION_LOADED) {\n AddExtension(extension);\n } else if (type == NotificationType::EXTENSION_UNLOADED ||\n type == NotificationType::EXTENSION_UNLOADED_DISABLED) {\n RemoveExtension(extension);\n } else {\n NOTREACHED() << \"Received unexpected notification\";\n }\n}\n\nvoid ExtensionToolbarModel::AddExtension(Extension* extension) {\n \/\/ We only care about extensions with browser actions.\n if (!extension->browser_action())\n return;\n\n if (extension->id() == last_extension_removed_ &&\n last_extension_removed_index_ < toolitems_.size()) {\n toolitems_.insert(begin() + last_extension_removed_index_, extension);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(extension, last_extension_removed_index_));\n } else {\n toolitems_.push_back(extension);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(extension, toolitems_.size() - 1));\n }\n\n last_extension_removed_ = \"\";\n last_extension_removed_index_ = -1;\n\n UpdatePrefs();\n}\n\nvoid ExtensionToolbarModel::RemoveExtension(Extension* extension) {\n ExtensionList::iterator pos = std::find(begin(), end(), extension);\n if (pos == end()) {\n return;\n }\n\n last_extension_removed_ = extension->id();\n last_extension_removed_index_ = pos - begin();\n\n toolitems_.erase(pos);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionRemoved(extension));\n\n UpdatePrefs();\n}\n\n\/\/ Combine the currently enabled extensions that have browser actions (which\n\/\/ we get from the ExtensionsService) with the ordering we get from the\n\/\/ pref service. For robustness we use a somewhat inefficient process:\n\/\/ 1. Create a vector of extensions sorted by their pref values. This vector may\n\/\/ have holes.\n\/\/ 2. Create a vector of extensions that did not have a pref value.\n\/\/ 3. Remove holes from the sorted vector and append the unsorted vector.\nvoid ExtensionToolbarModel::InitializeExtensionList() {\n DCHECK(service_->is_ready());\n\n std::vector<std::string> pref_order = service_->extension_prefs()->\n GetToolbarOrder();\n \/\/ Items that have a pref for their position.\n ExtensionList sorted;\n sorted.resize(pref_order.size(), NULL);\n \/\/ The items that don't have a pref for their position.\n ExtensionList unsorted;\n\n \/\/ Create the lists.\n for (size_t i = 0; i < service_->extensions()->size(); ++i) {\n Extension* extension = service_->extensions()->at(i);\n if (!extension->browser_action())\n continue;\n\n std::vector<std::string>::iterator pos =\n std::find(pref_order.begin(), pref_order.end(), extension->id());\n if (pos != pref_order.end()) {\n int index = std::distance(pref_order.begin(), pos);\n sorted[index] = extension;\n } else {\n unsorted.push_back(extension);\n }\n }\n\n \/\/ Merge the lists.\n toolitems_.reserve(sorted.size() + unsorted.size());\n for (ExtensionList::iterator iter = sorted.begin();\n iter != sorted.end(); ++iter) {\n if (*iter != NULL)\n toolitems_.push_back(*iter);\n }\n toolitems_.insert(toolitems_.end(), unsorted.begin(), unsorted.end());\n\n \/\/ Inform observers.\n for (size_t i = 0; i < toolitems_.size(); i++) {\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(toolitems_[i], i));\n }\n\n UpdatePrefs();\n\n extensions_initialized_ = true;\n FOR_EACH_OBSERVER(Observer, observers_, ModelLoaded());\n}\n\nvoid ExtensionToolbarModel::UpdatePrefs() {\n if (!service_->extension_prefs())\n return;\n\n std::vector<std::string> ids;\n ids.reserve(toolitems_.size());\n for (ExtensionList::iterator iter = begin(); iter != end(); ++iter)\n ids.push_back((*iter)->id());\n service_->extension_prefs()->SetToolbarOrder(ids);\n}\n\nExtension* ExtensionToolbarModel::GetExtensionByIndex(int index) const {\n return toolitems_.at(index);\n}\n\nint ExtensionToolbarModel::IncognitoIndexToOriginal(int incognito_index) {\n int original_index = 0, i = 0;\n for (ExtensionList::iterator iter = begin(); iter != end();\n ++iter, ++original_index) {\n if (service_->IsIncognitoEnabled(*iter)) {\n if (incognito_index == i)\n break;\n ++i;\n }\n }\n return original_index;\n}\n\nint ExtensionToolbarModel::OriginalIndexToIncognito(int original_index) {\n int incognito_index = 0, i = 0;\n for (ExtensionList::iterator iter = begin(); iter != end();\n ++iter, ++i) {\n if (original_index == i)\n break;\n if (service_->IsIncognitoEnabled(*iter))\n ++incognito_index;\n }\n return incognito_index;\n}\n<commit_msg>add a pref save when changing the visible icon count<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_toolbar_model.h\"\n\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nExtensionToolbarModel::ExtensionToolbarModel(ExtensionsService* service)\n : service_(service),\n prefs_(service->profile()->GetPrefs()),\n extensions_initialized_(false) {\n DCHECK(service_);\n\n registrar_.Add(this, NotificationType::EXTENSION_LOADED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,\n Source<Profile>(service_->profile()));\n registrar_.Add(this, NotificationType::EXTENSIONS_READY,\n Source<Profile>(service_->profile()));\n\n visible_icon_count_ = prefs_->GetInteger(prefs::kExtensionToolbarSize);\n}\n\nExtensionToolbarModel::~ExtensionToolbarModel() {\n}\n\nvoid ExtensionToolbarModel::DestroyingProfile() {\n registrar_.RemoveAll();\n}\n\nvoid ExtensionToolbarModel::AddObserver(Observer* observer) {\n observers_.AddObserver(observer);\n}\n\nvoid ExtensionToolbarModel::RemoveObserver(Observer* observer) {\n observers_.RemoveObserver(observer);\n}\n\nvoid ExtensionToolbarModel::MoveBrowserAction(Extension* extension,\n int index) {\n ExtensionList::iterator pos = std::find(begin(), end(), extension);\n if (pos == end()) {\n NOTREACHED();\n return;\n }\n toolitems_.erase(pos);\n\n int i = 0;\n bool inserted = false;\n for (ExtensionList::iterator iter = begin(); iter != end(); ++iter, ++i) {\n if (i == index) {\n toolitems_.insert(iter, extension);\n inserted = true;\n break;\n }\n }\n\n if (!inserted) {\n DCHECK_EQ(index, static_cast<int>(toolitems_.size()));\n index = toolitems_.size();\n\n toolitems_.push_back(extension);\n }\n\n FOR_EACH_OBSERVER(Observer, observers_, BrowserActionMoved(extension, index));\n\n UpdatePrefs();\n}\n\nvoid ExtensionToolbarModel::SetVisibleIconCount(int count) {\n visible_icon_count_ = count == static_cast<int>(size()) ? -1 : count;\n prefs_->SetInteger(prefs::kExtensionToolbarSize, visible_icon_count_);\n prefs_->ScheduleSavePersistentPrefs();\n}\n\nvoid ExtensionToolbarModel::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::EXTENSIONS_READY) {\n InitializeExtensionList();\n return;\n }\n\n if (!service_->is_ready())\n return;\n\n Extension* extension = Details<Extension>(details).ptr();\n if (type == NotificationType::EXTENSION_LOADED) {\n AddExtension(extension);\n } else if (type == NotificationType::EXTENSION_UNLOADED ||\n type == NotificationType::EXTENSION_UNLOADED_DISABLED) {\n RemoveExtension(extension);\n } else {\n NOTREACHED() << \"Received unexpected notification\";\n }\n}\n\nvoid ExtensionToolbarModel::AddExtension(Extension* extension) {\n \/\/ We only care about extensions with browser actions.\n if (!extension->browser_action())\n return;\n\n if (extension->id() == last_extension_removed_ &&\n last_extension_removed_index_ < toolitems_.size()) {\n toolitems_.insert(begin() + last_extension_removed_index_, extension);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(extension, last_extension_removed_index_));\n } else {\n toolitems_.push_back(extension);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(extension, toolitems_.size() - 1));\n }\n\n last_extension_removed_ = \"\";\n last_extension_removed_index_ = -1;\n\n UpdatePrefs();\n}\n\nvoid ExtensionToolbarModel::RemoveExtension(Extension* extension) {\n ExtensionList::iterator pos = std::find(begin(), end(), extension);\n if (pos == end()) {\n return;\n }\n\n last_extension_removed_ = extension->id();\n last_extension_removed_index_ = pos - begin();\n\n toolitems_.erase(pos);\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionRemoved(extension));\n\n UpdatePrefs();\n}\n\n\/\/ Combine the currently enabled extensions that have browser actions (which\n\/\/ we get from the ExtensionsService) with the ordering we get from the\n\/\/ pref service. For robustness we use a somewhat inefficient process:\n\/\/ 1. Create a vector of extensions sorted by their pref values. This vector may\n\/\/ have holes.\n\/\/ 2. Create a vector of extensions that did not have a pref value.\n\/\/ 3. Remove holes from the sorted vector and append the unsorted vector.\nvoid ExtensionToolbarModel::InitializeExtensionList() {\n DCHECK(service_->is_ready());\n\n std::vector<std::string> pref_order = service_->extension_prefs()->\n GetToolbarOrder();\n \/\/ Items that have a pref for their position.\n ExtensionList sorted;\n sorted.resize(pref_order.size(), NULL);\n \/\/ The items that don't have a pref for their position.\n ExtensionList unsorted;\n\n \/\/ Create the lists.\n for (size_t i = 0; i < service_->extensions()->size(); ++i) {\n Extension* extension = service_->extensions()->at(i);\n if (!extension->browser_action())\n continue;\n\n std::vector<std::string>::iterator pos =\n std::find(pref_order.begin(), pref_order.end(), extension->id());\n if (pos != pref_order.end()) {\n int index = std::distance(pref_order.begin(), pos);\n sorted[index] = extension;\n } else {\n unsorted.push_back(extension);\n }\n }\n\n \/\/ Merge the lists.\n toolitems_.reserve(sorted.size() + unsorted.size());\n for (ExtensionList::iterator iter = sorted.begin();\n iter != sorted.end(); ++iter) {\n if (*iter != NULL)\n toolitems_.push_back(*iter);\n }\n toolitems_.insert(toolitems_.end(), unsorted.begin(), unsorted.end());\n\n \/\/ Inform observers.\n for (size_t i = 0; i < toolitems_.size(); i++) {\n FOR_EACH_OBSERVER(Observer, observers_,\n BrowserActionAdded(toolitems_[i], i));\n }\n\n UpdatePrefs();\n\n extensions_initialized_ = true;\n FOR_EACH_OBSERVER(Observer, observers_, ModelLoaded());\n}\n\nvoid ExtensionToolbarModel::UpdatePrefs() {\n if (!service_->extension_prefs())\n return;\n\n std::vector<std::string> ids;\n ids.reserve(toolitems_.size());\n for (ExtensionList::iterator iter = begin(); iter != end(); ++iter)\n ids.push_back((*iter)->id());\n service_->extension_prefs()->SetToolbarOrder(ids);\n}\n\nExtension* ExtensionToolbarModel::GetExtensionByIndex(int index) const {\n return toolitems_.at(index);\n}\n\nint ExtensionToolbarModel::IncognitoIndexToOriginal(int incognito_index) {\n int original_index = 0, i = 0;\n for (ExtensionList::iterator iter = begin(); iter != end();\n ++iter, ++original_index) {\n if (service_->IsIncognitoEnabled(*iter)) {\n if (incognito_index == i)\n break;\n ++i;\n }\n }\n return original_index;\n}\n\nint ExtensionToolbarModel::OriginalIndexToIncognito(int original_index) {\n int incognito_index = 0, i = 0;\n for (ExtensionList::iterator iter = begin(); iter != end();\n ++iter, ++i) {\n if (original_index == i)\n break;\n if (service_->IsIncognitoEnabled(*iter))\n ++incognito_index;\n }\n return incognito_index;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/autofill\/autofill_dialog.h\"\n#include \"chrome\/browser\/autofill\/autofill_infobar_delegate.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"webkit\/glue\/form_field_values.h\"\n\nAutoFillManager::AutoFillManager(TabContents* tab_contents)\n : tab_contents_(tab_contents),\n infobar_(NULL) {\n personal_data_ = tab_contents_->profile()->GetPersonalDataManager();\n}\n\nAutoFillManager::~AutoFillManager() {\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);\n prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false);\n}\n\nvoid AutoFillManager::FormFieldValuesSubmitted(\n const webkit_glue::FormFieldValues& form) {\n \/\/ TODO(jhawkins): Remove this switch when AutoFill++ is fully implemented.\n if (!CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableNewAutoFill))\n return;\n\n \/\/ Grab a copy of the form data.\n upload_form_structure_.reset(new FormStructure(form));\n\n if (!upload_form_structure_->IsAutoFillable())\n return;\n\n \/\/ Determine the possible field types.\n DeterminePossibleFieldTypes(upload_form_structure_.get());\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n bool autofill_enabled = prefs->GetBoolean(prefs::kAutoFillEnabled);\n bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);\n if (!infobar_shown) {\n \/\/ Ask the user for permission to save form information.\n infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));\n } else if (autofill_enabled) {\n HandleSubmit();\n }\n}\n\nvoid AutoFillManager::OnAutoFillDialogApply(\n std::vector<AutoFillProfile>* profiles,\n std::vector<CreditCard>* credit_cards) {\n \/\/ Save the personal data.\n personal_data_->SetProfiles(profiles);\n personal_data_->SetCreditCards(credit_cards);\n\n HandleSubmit();\n}\n\nvoid AutoFillManager::OnPersonalDataLoaded() {\n \/\/ We might have been alerted that the PersonalDataManager has loaded, so\n \/\/ remove ourselves as observer.\n personal_data_->RemoveObserver(this);\n\n ShowAutoFillDialog(\n this, personal_data_->profiles(), personal_data_->credit_cards());\n}\n\nvoid AutoFillManager::DeterminePossibleFieldTypes(\n FormStructure* form_structure) {\n \/\/ TODO(jhawkins): Update field text.\n\n form_structure->GetHeuristicAutoFillTypes();\n\n for (size_t i = 0; i < form_structure->field_count(); i++) {\n const AutoFillField* field = form_structure->field(i);\n FieldTypeSet field_types;\n personal_data_->GetPossibleFieldTypes(field->value(), &field_types);\n form_structure->set_possible_types(i, field_types);\n }\n}\n\nvoid AutoFillManager::HandleSubmit() {\n \/\/ If there wasn't enough data to import then we don't want to send an upload\n \/\/ to the server.\n if (!personal_data_->ImportFormData(form_structures_, this))\n return;\n\n UploadFormData();\n}\n\nvoid AutoFillManager::OnInfoBarAccepted() {\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n prefs->SetBoolean(prefs::kAutoFillEnabled, true);\n\n \/\/ If the personal data manager has not loaded the data yet, set ourselves as\n \/\/ its observer so that we can listen for the OnPersonalDataLoaded signal.\n if (!personal_data_->IsDataLoaded())\n personal_data_->SetObserver(this);\n else\n OnPersonalDataLoaded();\n}\n\nvoid AutoFillManager::SaveFormData() {\n \/\/ TODO(jhawkins): Save the form data to the web database.\n}\n\nvoid AutoFillManager::UploadFormData() {\n std::string xml;\n bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);\n DCHECK(ok);\n\n \/\/ TODO(jhawkins): Initiate the upload request thread.\n}\n\nvoid AutoFillManager::Reset() {\n upload_form_structure_.reset();\n}\n<commit_msg>Remove the AutoFillManager as an observer of the PersonalDataManager in the constructor. In rare circumtances, the user can close the browser (and shutdown the AutoFillManager) after we've set ourselves as observers of the PersonalDataManager and before the PersonalDataManager has called us back.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/autofill\/autofill_dialog.h\"\n#include \"chrome\/browser\/autofill\/autofill_infobar_delegate.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"webkit\/glue\/form_field_values.h\"\n\nAutoFillManager::AutoFillManager(TabContents* tab_contents)\n : tab_contents_(tab_contents),\n infobar_(NULL) {\n personal_data_ = tab_contents_->profile()->GetPersonalDataManager();\n}\n\nAutoFillManager::~AutoFillManager() {\n personal_data_->RemoveObserver(this);\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);\n prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false);\n}\n\nvoid AutoFillManager::FormFieldValuesSubmitted(\n const webkit_glue::FormFieldValues& form) {\n \/\/ TODO(jhawkins): Remove this switch when AutoFill++ is fully implemented.\n if (!CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableNewAutoFill))\n return;\n\n \/\/ Grab a copy of the form data.\n upload_form_structure_.reset(new FormStructure(form));\n\n if (!upload_form_structure_->IsAutoFillable())\n return;\n\n \/\/ Determine the possible field types.\n DeterminePossibleFieldTypes(upload_form_structure_.get());\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n bool autofill_enabled = prefs->GetBoolean(prefs::kAutoFillEnabled);\n bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);\n if (!infobar_shown) {\n \/\/ Ask the user for permission to save form information.\n infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));\n } else if (autofill_enabled) {\n HandleSubmit();\n }\n}\n\nvoid AutoFillManager::OnAutoFillDialogApply(\n std::vector<AutoFillProfile>* profiles,\n std::vector<CreditCard>* credit_cards) {\n \/\/ Save the personal data.\n personal_data_->SetProfiles(profiles);\n personal_data_->SetCreditCards(credit_cards);\n\n HandleSubmit();\n}\n\nvoid AutoFillManager::OnPersonalDataLoaded() {\n \/\/ We might have been alerted that the PersonalDataManager has loaded, so\n \/\/ remove ourselves as observer.\n personal_data_->RemoveObserver(this);\n\n ShowAutoFillDialog(\n this, personal_data_->profiles(), personal_data_->credit_cards());\n}\n\nvoid AutoFillManager::DeterminePossibleFieldTypes(\n FormStructure* form_structure) {\n \/\/ TODO(jhawkins): Update field text.\n\n form_structure->GetHeuristicAutoFillTypes();\n\n for (size_t i = 0; i < form_structure->field_count(); i++) {\n const AutoFillField* field = form_structure->field(i);\n FieldTypeSet field_types;\n personal_data_->GetPossibleFieldTypes(field->value(), &field_types);\n form_structure->set_possible_types(i, field_types);\n }\n}\n\nvoid AutoFillManager::HandleSubmit() {\n \/\/ If there wasn't enough data to import then we don't want to send an upload\n \/\/ to the server.\n if (!personal_data_->ImportFormData(form_structures_, this))\n return;\n\n UploadFormData();\n}\n\nvoid AutoFillManager::OnInfoBarAccepted() {\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n prefs->SetBoolean(prefs::kAutoFillEnabled, true);\n\n \/\/ If the personal data manager has not loaded the data yet, set ourselves as\n \/\/ its observer so that we can listen for the OnPersonalDataLoaded signal.\n if (!personal_data_->IsDataLoaded())\n personal_data_->SetObserver(this);\n else\n OnPersonalDataLoaded();\n}\n\nvoid AutoFillManager::SaveFormData() {\n \/\/ TODO(jhawkins): Save the form data to the web database.\n}\n\nvoid AutoFillManager::UploadFormData() {\n std::string xml;\n bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);\n DCHECK(ok);\n\n \/\/ TODO(jhawkins): Initiate the upload request thread.\n}\n\nvoid AutoFillManager::Reset() {\n upload_form_structure_.reset();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_preferences_util.h\"\n\n#include \"chrome\/browser\/profile.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#endif\n\nnamespace renderer_preferences_util {\n\nvoid UpdateFromSystemSettings(RendererPreferences* prefs, Profile* profile) {\n#if defined(TOOLKIT_USES_GTK)\n gtk_util::UpdateGtkFontSettings(prefs);\n\n#if !defined(TOOLKIT_VIEWS)\n GtkThemeProvider* provider = GtkThemeProvider::GetFrom(profile);\n\n prefs->focus_ring_color = provider->get_focus_ring_color();\n prefs->thumb_active_color = provider->get_thumb_active_color();\n prefs->thumb_inactive_color = provider->get_thumb_inactive_color();\n prefs->track_color = provider->get_track_color();\n prefs->active_selection_bg_color = provider->get_active_selection_bg_color();\n prefs->active_selection_fg_color = provider->get_active_selection_fg_color();\n prefs->inactive_selection_bg_color =\n provider->get_inactive_selection_bg_color();\n prefs->inactive_selection_fg_color =\n provider->get_inactive_selection_fg_color();\n#endif \/\/ !defined(TOOLKIT_VIEWS)\n\n#if defined(OS_CHROMEOS)\n prefs->active_selection_bg_color = SkColorSetRGB(0xDC, 0xE4, 0xFA);\n prefs->active_selection_fg_color = SK_ColorBLACK;\n prefs->inactive_selection_bg_color = SkColorSetRGB(0xF7, 0xF7, 0xF7);\n prefs->inactive_selection_fg_color = SK_ColorBLACK;\n#endif \/\/ defined(OS_CHROMEOS)\n\n#endif \/\/ defined(TOOLKIT_USES_GTK)\n}\n\n} \/\/ renderer_preferences_util\n<commit_msg>Fix to show focus ring color properly. BUG=chromium-os:9019 TEST=manual Review URL: http:\/\/codereview.chromium.org\/4842002<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_preferences_util.h\"\n\n#include \"chrome\/browser\/profile.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#endif\n\nnamespace renderer_preferences_util {\n\nvoid UpdateFromSystemSettings(RendererPreferences* prefs, Profile* profile) {\n#if defined(TOOLKIT_USES_GTK)\n gtk_util::UpdateGtkFontSettings(prefs);\n\n#if !defined(TOOLKIT_VIEWS)\n GtkThemeProvider* provider = GtkThemeProvider::GetFrom(profile);\n\n prefs->focus_ring_color = provider->get_focus_ring_color();\n prefs->thumb_active_color = provider->get_thumb_active_color();\n prefs->thumb_inactive_color = provider->get_thumb_inactive_color();\n prefs->track_color = provider->get_track_color();\n prefs->active_selection_bg_color = provider->get_active_selection_bg_color();\n prefs->active_selection_fg_color = provider->get_active_selection_fg_color();\n prefs->inactive_selection_bg_color =\n provider->get_inactive_selection_bg_color();\n prefs->inactive_selection_fg_color =\n provider->get_inactive_selection_fg_color();\n#endif \/\/ !defined(TOOLKIT_VIEWS)\n\n#if defined(OS_CHROMEOS)\n prefs->focus_ring_color = SkColorSetARGB(255, 229, 151, 0);\n prefs->active_selection_bg_color = SkColorSetRGB(0xDC, 0xE4, 0xFA);\n prefs->active_selection_fg_color = SK_ColorBLACK;\n prefs->inactive_selection_bg_color = SkColorSetRGB(0xF7, 0xF7, 0xF7);\n prefs->inactive_selection_fg_color = SK_ColorBLACK;\n#endif \/\/ defined(OS_CHROMEOS)\n\n#endif \/\/ defined(TOOLKIT_USES_GTK)\n}\n\n} \/\/ renderer_preferences_util\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/test\/automation\/dom_element_proxy.h\"\n#include \"chrome\/test\/automation\/javascript_execution_controller.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nnamespace {\n\n\/\/ Tests the DOMAutomation framework for manipulating DOMElements within\n\/\/ browser tests.\nclass DOMAutomationTest : public InProcessBrowserTest {\n public:\n DOMAutomationTest() {\n EnableDOMAutomation();\n JavaScriptExecutionController::set_timeout(30000);\n }\n\n GURL GetTestURL(const char* path) {\n std::string url_path = \"files\/dom_automation\/\";\n url_path.append(path);\n return test_server()->GetURL(url_path);\n }\n};\n\ntypedef DOMElementProxy::By By;\n\n#if defined(OS_WIN)\n\/\/ See http:\/\/crbug.com\/61636\n#define MAYBE_FindByXPath DISABLED_FindByXPath\n#define MAYBE_FindBySelectors DISABLED_FindByXPath\n#define MAYBE_FindByText DISABLED_FindByText\n#else\n#define MAYBE_FindByXPath FindByXPath\n#define MAYBE_FindBySelectors FindBySelectors\n#define MAYBE_FindByText FindByText\n#endif\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByXPath) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_div = main_doc->FindElement(By::XPath(\"\/\/div\"));\n ASSERT_TRUE(first_div);\n ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/div\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\"\/\/nosuchtag\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/nosuchtag\"), &elements));\n elements.clear();\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find with invalid xpath.\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\"'invalid'\")));\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\" \/ \/ \")));\n ASSERT_FALSE(main_doc->FindElements(By::XPath(\"'invalid'\"), &elements));\n ASSERT_FALSE(main_doc->FindElements(By::XPath(\" \/ \/ \"), &elements));\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::XPath(\"\/html\/body\/span\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::XPath(\".\/span\"));\n }\n ASSERT_EQ(3, nested_count);\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_myclass =\n main_doc->FindElement(By::Selectors(\".myclass\"));\n ASSERT_TRUE(first_myclass);\n ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\".myclass\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::Selectors(\"#nosuchid\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\"#nosuchid\"), &elements));\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find with invalid selectors.\n ASSERT_FALSE(main_doc->FindElement(By::Selectors(\"1#2\")));\n ASSERT_FALSE(main_doc->FindElements(By::Selectors(\"1#2\"), &elements));\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::Selectors(\"span\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::Selectors(\"span\"));\n }\n ASSERT_EQ(3, nested_count);\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindByText) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_text = main_doc->FindElement(By::Text(\"div_text\"));\n ASSERT_TRUE(first_text);\n ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::Text(\"div_text\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::Text(\"nosuchtext\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::Text(\"nosuchtext\"), &elements));\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::Text(\"span_text\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::Text(\"span_text\"));\n }\n ASSERT_EQ(3, nested_count);\n\n \/\/ Find only visible text.\n DOMElementProxyRef shown_td = main_doc->FindElement(By::Text(\"table_text\"));\n ASSERT_TRUE(shown_td);\n ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches(\"shown\"));\n\n \/\/ Find text in inputs.\n ASSERT_TRUE(main_doc->FindElement(By::Text(\"textarea_text\")));\n ASSERT_TRUE(main_doc->FindElement(By::Text(\"input_text\")));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef div =\n main_doc->WaitFor1VisibleElement(By::Selectors(\"div\"));\n ASSERT_TRUE(div.get());\n ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches(\"div_inner\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors(\"img\")));\n std::vector<DOMElementProxyRef> img_elements;\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\"img\"), &img_elements));\n ASSERT_EQ(0u, img_elements.size());\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors(\"a\"));\n ASSERT_TRUE(anchor.get());\n ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(\n \"href\", \"http:\/\/www.google.com\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"frames\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Get both frame elements.\n std::vector<DOMElementProxyRef> frame_elements;\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/frame\"), &frame_elements));\n ASSERT_EQ(2u, frame_elements.size());\n\n \/\/ Get both frames, checking their contents are correct.\n DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();\n DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();\n ASSERT_TRUE(frame1 && frame2);\n DOMElementProxyRef frame_div =\n frame1->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"frame 1\"));\n frame_div = frame2->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"frame 2\"));\n\n \/\/ Get both inner iframes, checking their contents are correct.\n DOMElementProxyRef iframe1 =\n frame1->GetDocumentFromFrame(\"0\");\n DOMElementProxyRef iframe2 =\n frame2->GetDocumentFromFrame(\"0\");\n ASSERT_TRUE(iframe1 && iframe2);\n frame_div = iframe1->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"iframe 1\"));\n frame_div = iframe2->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"iframe 2\"));\n\n \/\/ Get nested frame.\n ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame(\"0\", \"0\").get());\n ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame(\"1\", \"0\").get());\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"events\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Click link and make sure text changes.\n DOMElementProxyRef link = main_doc->FindElement(By::Selectors(\"a\"));\n ASSERT_TRUE(link && link->Click());\n ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches(\"clicked\"));\n\n \/\/ Click input button and make sure textfield changes.\n DOMElementProxyRef button = main_doc->FindElement(By::Selectors(\"#button\"));\n DOMElementProxyRef textfield =\n main_doc->FindElement(By::Selectors(\"#textfield\"));\n ASSERT_TRUE(textfield && button && button->Click());\n ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches(\"clicked\"));\n\n \/\/ Type in the textfield.\n ASSERT_TRUE(textfield->SetText(\"test\"));\n ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches(\"test\"));\n\n \/\/ Type in the textarea.\n DOMElementProxyRef textarea =\n main_doc->FindElement(By::Selectors(\"textarea\"));\n ASSERT_TRUE(textarea && textarea->Type(\"test\"));\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(\"textareatest\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"string_escape\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef textarea =\n main_doc->FindElement(By::Selectors(\"textarea\"));\n ASSERT_TRUE(textarea);\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L\"\\u00FF\")));\n\n const wchar_t* set_and_expect_strings[] = {\n L\"\\u00FF and \\u00FF\",\n L\"\\n \\t \\\\\",\n L\"' \\\"\"\n };\n for (size_t i = 0; i < 3; i++) {\n ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(\n WideToUTF8(set_and_expect_strings[i])));\n }\n}\n\n} \/\/ namespace\n<commit_msg>Disable the FindBy tests for real this time. <commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/test\/automation\/dom_element_proxy.h\"\n#include \"chrome\/test\/automation\/javascript_execution_controller.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nnamespace {\n\n\/\/ Tests the DOMAutomation framework for manipulating DOMElements within\n\/\/ browser tests.\nclass DOMAutomationTest : public InProcessBrowserTest {\n public:\n DOMAutomationTest() {\n EnableDOMAutomation();\n JavaScriptExecutionController::set_timeout(30000);\n }\n\n GURL GetTestURL(const char* path) {\n std::string url_path = \"files\/dom_automation\/\";\n url_path.append(path);\n return test_server()->GetURL(url_path);\n }\n};\n\ntypedef DOMElementProxy::By By;\n\n#if defined(OS_WIN)\n\/\/ See http:\/\/crbug.com\/61636\n#define MAYBE_FindByXPath DISABLED_FindByXPath\n#define MAYBE_FindBySelectors DISABLED_FindBySelectors\n#define MAYBE_FindByText DISABLED_FindByText\n#else\n#define MAYBE_FindByXPath FindByXPath\n#define MAYBE_FindBySelectors FindBySelectors\n#define MAYBE_FindByText FindByText\n#endif\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByXPath) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_div = main_doc->FindElement(By::XPath(\"\/\/div\"));\n ASSERT_TRUE(first_div);\n ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/div\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\"\/\/nosuchtag\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/nosuchtag\"), &elements));\n elements.clear();\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find with invalid xpath.\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\"'invalid'\")));\n ASSERT_FALSE(main_doc->FindElement(By::XPath(\" \/ \/ \")));\n ASSERT_FALSE(main_doc->FindElements(By::XPath(\"'invalid'\"), &elements));\n ASSERT_FALSE(main_doc->FindElements(By::XPath(\" \/ \/ \"), &elements));\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::XPath(\"\/html\/body\/span\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::XPath(\".\/span\"));\n }\n ASSERT_EQ(3, nested_count);\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindBySelectors) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_myclass =\n main_doc->FindElement(By::Selectors(\".myclass\"));\n ASSERT_TRUE(first_myclass);\n ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\".myclass\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::Selectors(\"#nosuchid\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\"#nosuchid\"), &elements));\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find with invalid selectors.\n ASSERT_FALSE(main_doc->FindElement(By::Selectors(\"1#2\")));\n ASSERT_FALSE(main_doc->FindElements(By::Selectors(\"1#2\"), &elements));\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::Selectors(\"span\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::Selectors(\"span\"));\n }\n ASSERT_EQ(3, nested_count);\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"find_elements\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Find first element.\n DOMElementProxyRef first_text = main_doc->FindElement(By::Text(\"div_text\"));\n ASSERT_TRUE(first_text);\n ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches(\"0\"));\n\n \/\/ Find many elements.\n std::vector<DOMElementProxyRef> elements;\n ASSERT_TRUE(main_doc->FindElements(By::Text(\"div_text\"), &elements));\n ASSERT_EQ(2u, elements.size());\n for (size_t i = 0; i < elements.size(); i++) {\n ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(\n base::UintToString(i)));\n }\n\n \/\/ Find 0 elements.\n ASSERT_FALSE(main_doc->FindElement(By::Text(\"nosuchtext\")));\n elements.clear();\n ASSERT_TRUE(main_doc->FindElements(By::Text(\"nosuchtext\"), &elements));\n ASSERT_EQ(0u, elements.size());\n\n \/\/ Find nested elements.\n int nested_count = 0;\n std::string span_name;\n DOMElementProxyRef node = main_doc->FindElement(By::Text(\"span_text\"));\n while (node) {\n nested_count++;\n span_name.append(\"span\");\n ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));\n node = node->FindElement(By::Text(\"span_text\"));\n }\n ASSERT_EQ(3, nested_count);\n\n \/\/ Find only visible text.\n DOMElementProxyRef shown_td = main_doc->FindElement(By::Text(\"table_text\"));\n ASSERT_TRUE(shown_td);\n ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches(\"shown\"));\n\n \/\/ Find text in inputs.\n ASSERT_TRUE(main_doc->FindElement(By::Text(\"textarea_text\")));\n ASSERT_TRUE(main_doc->FindElement(By::Text(\"input_text\")));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef div =\n main_doc->WaitFor1VisibleElement(By::Selectors(\"div\"));\n ASSERT_TRUE(div.get());\n ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches(\"div_inner\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors(\"img\")));\n std::vector<DOMElementProxyRef> img_elements;\n ASSERT_TRUE(main_doc->FindElements(By::Selectors(\"img\"), &img_elements));\n ASSERT_EQ(0u, img_elements.size());\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"wait\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors(\"a\"));\n ASSERT_TRUE(anchor.get());\n ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(\n \"href\", \"http:\/\/www.google.com\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"frames\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Get both frame elements.\n std::vector<DOMElementProxyRef> frame_elements;\n ASSERT_TRUE(main_doc->FindElements(By::XPath(\"\/\/frame\"), &frame_elements));\n ASSERT_EQ(2u, frame_elements.size());\n\n \/\/ Get both frames, checking their contents are correct.\n DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();\n DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();\n ASSERT_TRUE(frame1 && frame2);\n DOMElementProxyRef frame_div =\n frame1->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"frame 1\"));\n frame_div = frame2->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"frame 2\"));\n\n \/\/ Get both inner iframes, checking their contents are correct.\n DOMElementProxyRef iframe1 =\n frame1->GetDocumentFromFrame(\"0\");\n DOMElementProxyRef iframe2 =\n frame2->GetDocumentFromFrame(\"0\");\n ASSERT_TRUE(iframe1 && iframe2);\n frame_div = iframe1->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"iframe 1\"));\n frame_div = iframe2->FindElement(By::XPath(\"\/html\/body\/div\"));\n ASSERT_TRUE(frame_div);\n ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches(\"iframe 2\"));\n\n \/\/ Get nested frame.\n ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame(\"0\", \"0\").get());\n ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame(\"1\", \"0\").get());\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(), GetTestURL(\"events\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n \/\/ Click link and make sure text changes.\n DOMElementProxyRef link = main_doc->FindElement(By::Selectors(\"a\"));\n ASSERT_TRUE(link && link->Click());\n ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches(\"clicked\"));\n\n \/\/ Click input button and make sure textfield changes.\n DOMElementProxyRef button = main_doc->FindElement(By::Selectors(\"#button\"));\n DOMElementProxyRef textfield =\n main_doc->FindElement(By::Selectors(\"#textfield\"));\n ASSERT_TRUE(textfield && button && button->Click());\n ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches(\"clicked\"));\n\n \/\/ Type in the textfield.\n ASSERT_TRUE(textfield->SetText(\"test\"));\n ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches(\"test\"));\n\n \/\/ Type in the textarea.\n DOMElementProxyRef textarea =\n main_doc->FindElement(By::Selectors(\"textarea\"));\n ASSERT_TRUE(textarea && textarea->Type(\"test\"));\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(\"textareatest\"));\n}\n\nIN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {\n ASSERT_TRUE(test_server()->Start());\n ui_test_utils::NavigateToURL(browser(),\n GetTestURL(\"string_escape\/test.html\"));\n DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());\n\n DOMElementProxyRef textarea =\n main_doc->FindElement(By::Selectors(\"textarea\"));\n ASSERT_TRUE(textarea);\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L\"\\u00FF\")));\n\n const wchar_t* set_and_expect_strings[] = {\n L\"\\u00FF and \\u00FF\",\n L\"\\n \\t \\\\\",\n L\"' \\\"\"\n };\n for (size_t i = 0; i < 3; i++) {\n ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));\n ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(\n WideToUTF8(set_and_expect_strings[i])));\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file AbstrRenderer.cpp\r\n \\author Jens Krueger\r\n SCI Institute\r\n University of Utah\r\n \\date August 2008\r\n*\/\r\n\r\n#include \"AbstrRenderer.h\"\r\n#include \"..\/Controller\/MasterController.h\"\r\n\r\nusing namespace std;\r\n\r\nAbstrRenderer::AbstrRenderer(MasterController* pMasterController) : \r\n m_pMasterController(pMasterController),\r\n m_bRedraw(true), \r\n m_bCompleteRedraw(true), \r\n m_eRenderMode(RM_1DTRANS),\r\n m_eViewMode(VM_ONEBYTREE),\r\n m_bUseLigthing(true),\r\n m_pDataset(NULL),\r\n m_p1DTrans(NULL),\r\n m_p2DTrans(NULL),\r\n m_fSampleRateModifier(1.0f),\r\n m_vTextColor(1,1,1,1),\r\n m_fIsovalue(0.5f)\r\n{\r\n m_vBackgroundColors[0] = FLOATVECTOR3(0,0,0);\r\n m_vBackgroundColors[1] = FLOATVECTOR3(0,0,0);\r\n\r\n m_eWindowMode[0] = WM_3D;\r\n m_eWindowMode[1] = WM_CORONAL;\r\n m_eWindowMode[2] = WM_AXIAL;\r\n m_eWindowMode[3] = WM_SAGITTAL;\r\n\r\n m_fSliceIndex[0] = 0.5f;\r\n m_fSliceIndex[1] = 0.5f;\r\n m_fSliceIndex[2] = 0.5f;\r\n m_fSliceIndex[3] = 0.5f;\r\n}\r\n\r\n\r\nbool AbstrRenderer::LoadDataset(const string& strFilename) {\r\n if (m_pMasterController == NULL) return false;\r\n\r\n if (m_pMasterController->IOMan() == NULL) {\r\n m_pMasterController->DebugOut()->Error(\"AbstrRenderer::LoadDataset\",\"Cannont load dataset because m_pMasterController->IOMan() == NULL\");\r\n return false;\r\n }\r\n\r\n m_pDataset = m_pMasterController->IOMan()->LoadDataset(strFilename,this);\r\n\r\n if (m_pDataset == NULL) {\r\n m_pMasterController->DebugOut()->Error(\"AbstrRenderer::LoadDataset\",\"IOMan call to load dataset failed\");\r\n return false;\r\n }\r\n\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::LoadDataset\",\"Load successful, initializing renderer!\");\r\n\r\n return true;\r\n}\r\n\r\nAbstrRenderer::~AbstrRenderer() {\r\n m_pMasterController->MemMan()->FreeDataset(m_pDataset, this);\r\n m_pMasterController->MemMan()->Free1DTrans(m_p1DTrans, this);\r\n m_pMasterController->MemMan()->Free2DTrans(m_p2DTrans, this);\r\n\r\n}\r\n\r\nvoid AbstrRenderer::SetRendermode(ERenderMode eRenderMode) \r\n{\r\n if (m_eRenderMode != eRenderMode) {\r\n m_eRenderMode = eRenderMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n } \r\n}\r\n\r\nvoid AbstrRenderer::SetViewmode(EViewMode eViewMode)\r\n{\r\n if (m_eViewMode != eViewMode) {\r\n m_eViewMode = eViewMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n } \r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetWindowmode(unsigned int iWindowIndex, EWindowMode eWindowMode)\r\n{\r\n if (m_eWindowMode[iWindowIndex] != eWindowMode) {\r\n m_eWindowMode[iWindowIndex] = eWindowMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n \/\/\/ \\todo only redraw the windows dependent on this change\r\n } \r\n}\r\n\r\nvoid AbstrRenderer::SetUseLigthing(bool bUseLigthing) {\r\n if (m_bUseLigthing != bUseLigthing) {\r\n m_bUseLigthing = bUseLigthing; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n \/\/\/ \\todo only redraw the windows dependent on this change\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::Changed1DTrans() {\r\n if (m_eRenderMode != RM_1DTRANS) {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed1DTrans\",\"not using the 1D transferfunction at the moment, ignoring message\");\r\n } else {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed1DTrans\",\"complete redraw scheduled\");\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\nvoid AbstrRenderer::Changed2DTrans() {\r\n if (m_eRenderMode != RM_2DTRANS) {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed2DTrans\",\"not using the 2D transferfunction at the moment, ignoring message\");\r\n } else {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed2DTrans\",\"complete redraw scheduled\");\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetSampleRateModifier(float fSampleRateModifier) {\r\n if(m_fSampleRateModifier != fSampleRateModifier) {\r\n m_fSampleRateModifier = fSampleRateModifier;\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetIsoValue(float fIsovalue) {\r\n if(m_fIsovalue != fIsovalue) {\r\n m_fIsovalue = fIsovalue;\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n<commit_msg><commit_after>\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file AbstrRenderer.cpp\r\n \\author Jens Krueger\r\n SCI Institute\r\n University of Utah\r\n \\date August 2008\r\n*\/\r\n\r\n#include \"AbstrRenderer.h\"\r\n#include \"..\/Controller\/MasterController.h\"\r\n\r\nusing namespace std;\r\n\r\nAbstrRenderer::AbstrRenderer(MasterController* pMasterController) : \r\n m_pMasterController(pMasterController),\r\n m_bRedraw(true), \r\n m_bCompleteRedraw(true), \r\n m_eRenderMode(RM_1DTRANS),\r\n m_eViewMode(VM_ONEBYTREE),\r\n m_bUseLigthing(true),\r\n m_pDataset(NULL),\r\n m_p1DTrans(NULL),\r\n m_p2DTrans(NULL),\r\n m_fSampleRateModifier(1.0f),\r\n m_fIsovalue(0.5f),\r\n m_vTextColor(1,1,1,1)\r\n{\r\n m_vBackgroundColors[0] = FLOATVECTOR3(0,0,0);\r\n m_vBackgroundColors[1] = FLOATVECTOR3(0,0,0);\r\n\r\n m_eWindowMode[0] = WM_3D;\r\n m_eWindowMode[1] = WM_CORONAL;\r\n m_eWindowMode[2] = WM_AXIAL;\r\n m_eWindowMode[3] = WM_SAGITTAL;\r\n\r\n m_fSliceIndex[0] = 0.5f;\r\n m_fSliceIndex[1] = 0.5f;\r\n m_fSliceIndex[2] = 0.5f;\r\n m_fSliceIndex[3] = 0.5f;\r\n}\r\n\r\n\r\nbool AbstrRenderer::LoadDataset(const string& strFilename) {\r\n if (m_pMasterController == NULL) return false;\r\n\r\n if (m_pMasterController->IOMan() == NULL) {\r\n m_pMasterController->DebugOut()->Error(\"AbstrRenderer::LoadDataset\",\"Cannont load dataset because m_pMasterController->IOMan() == NULL\");\r\n return false;\r\n }\r\n\r\n m_pDataset = m_pMasterController->IOMan()->LoadDataset(strFilename,this);\r\n\r\n if (m_pDataset == NULL) {\r\n m_pMasterController->DebugOut()->Error(\"AbstrRenderer::LoadDataset\",\"IOMan call to load dataset failed\");\r\n return false;\r\n }\r\n\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::LoadDataset\",\"Load successful, initializing renderer!\");\r\n\r\n return true;\r\n}\r\n\r\nAbstrRenderer::~AbstrRenderer() {\r\n m_pMasterController->MemMan()->FreeDataset(m_pDataset, this);\r\n m_pMasterController->MemMan()->Free1DTrans(m_p1DTrans, this);\r\n m_pMasterController->MemMan()->Free2DTrans(m_p2DTrans, this);\r\n\r\n}\r\n\r\nvoid AbstrRenderer::SetRendermode(ERenderMode eRenderMode) \r\n{\r\n if (m_eRenderMode != eRenderMode) {\r\n m_eRenderMode = eRenderMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n } \r\n}\r\n\r\nvoid AbstrRenderer::SetViewmode(EViewMode eViewMode)\r\n{\r\n if (m_eViewMode != eViewMode) {\r\n m_eViewMode = eViewMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n } \r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetWindowmode(unsigned int iWindowIndex, EWindowMode eWindowMode)\r\n{\r\n if (m_eWindowMode[iWindowIndex] != eWindowMode) {\r\n m_eWindowMode[iWindowIndex] = eWindowMode; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n \/\/\/ \\todo only redraw the windows dependent on this change\r\n } \r\n}\r\n\r\nvoid AbstrRenderer::SetUseLigthing(bool bUseLigthing) {\r\n if (m_bUseLigthing != bUseLigthing) {\r\n m_bUseLigthing = bUseLigthing; \r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n \/\/\/ \\todo only redraw the windows dependent on this change\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::Changed1DTrans() {\r\n if (m_eRenderMode != RM_1DTRANS) {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed1DTrans\",\"not using the 1D transferfunction at the moment, ignoring message\");\r\n } else {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed1DTrans\",\"complete redraw scheduled\");\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\nvoid AbstrRenderer::Changed2DTrans() {\r\n if (m_eRenderMode != RM_2DTRANS) {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed2DTrans\",\"not using the 2D transferfunction at the moment, ignoring message\");\r\n } else {\r\n m_pMasterController->DebugOut()->Message(\"AbstrRenderer::Changed2DTrans\",\"complete redraw scheduled\");\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetSampleRateModifier(float fSampleRateModifier) {\r\n if(m_fSampleRateModifier != fSampleRateModifier) {\r\n m_fSampleRateModifier = fSampleRateModifier;\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n\r\n\r\nvoid AbstrRenderer::SetIsoValue(float fIsovalue) {\r\n if(m_fIsovalue != fIsovalue) {\r\n m_fIsovalue = fIsovalue;\r\n m_bRedraw = true;\r\n m_bCompleteRedraw = true;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/centaur\/common\/include\/cen_gen_scom_addresses_fixes.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/Example: To fix an existing definiton\n\/\/CEN_FIXREG32 (CEN_MBA_1_CCS_INST_ARR0_10, RULL(0x01234567));\n\n<commit_msg>Edit ECID+Perv code to use new gen'd centaur scom headers<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/centaur\/common\/include\/cen_gen_scom_addresses_fixes.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/Example: To fix an existing definiton\n\/\/CEN_FIXREG32 (CEN_MBA_1_CCS_INST_ARR0_10, RULL(0x01234567));\n#include <p9_const_common.H>\n#include <p9_scom_template_consts.H>\n#ifndef CEN_GEN_SCOM_ADDRESSES_FIXES_H\n#define CEN_GEN_SCOM_ADDRESSES_FIXES_H\n\nREG64( CEN_WRITE_ALL_FUNC_GP3 , RULL(0x6B0F0012), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_WRITE_ALL_FUNC_GP3_AND , RULL(0x6B0F0013), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_WRITE_ALL_FUNC_GP3_OR , RULL(0x6B0F0014), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_WRITE_ALL_PCB_SLAVE_ERRREG , RULL(0x6B0F001F), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_PERV_LOCAL_FIR , RULL(0x0004000A), SH_UNT_PERV , SH_ACS_SCOM_RW );\nREG64( CEN_PERV_TP_LOCAL_FIR , RULL(0x0104000A), SH_UNT_PERV_1 , SH_ACS_SCOM_RW );\nREG64( CEN_PERV_LOCAL_FIR_AND , RULL(0x0004000B), SH_UNT_PERV , SH_ACS_SCOM1_AND );\nREG64( CEN_PERV_TP_LOCAL_FIR_AND , RULL(0x0104000B), SH_UNT_PERV_1 , SH_ACS_SCOM1_AND );\nREG64( CEN_PERV_LOCAL_FIR_OR , RULL(0x0004000C), SH_UNT_PERV , SH_ACS_SCOM2_OR );\nREG64( CEN_PERV_TP_LOCAL_FIR_OR , RULL(0x0104000C), SH_UNT_PERV_1 , SH_ACS_SCOM2_OR );\nREG64( CEN_PERV_LOCAL_FIR_MASK , RULL(0x0004000D), SH_UNT_PERV , SH_ACS_SCOM_RW );\nREG64( CEN_PERV_TP_LOCAL_FIR_MASK , RULL(0x0104000D), SH_UNT_PERV_1 , SH_ACS_SCOM_RW );\nREG64( CEN_PERV_LOCAL_FIR_MASK_AND , RULL(0x0004000E), SH_UNT_PERV , SH_ACS_SCOM1_AND );\nREG64( CEN_PERV_TP_LOCAL_FIR_MASK_AND , RULL(0x0104000E), SH_UNT_PERV_1 , SH_ACS_SCOM1_AND );\nREG64( CEN_PERV_LOCAL_FIR_MASK_OR , RULL(0x0004000F), SH_UNT_PERV , SH_ACS_SCOM2_OR );\nREG64( CEN_PERV_TP_LOCAL_FIR_MASK_OR , RULL(0x0104000F), SH_UNT_PERV_1 , SH_ACS_SCOM2_OR );\nREG64( CEN_GENERIC_GP1 , RULL(0x00000001), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_GP0_AND , RULL(0x00000004), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_GP0_OR , RULL(0x00000005), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_GP3_AND , RULL(0x000F0013), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_GP3_OR , RULL(0x000F0014), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_OPCG_CNTL0 , RULL(0x00030002), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_OPCG_CNTL2 , RULL(0x00030004), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_CLK_REGION , RULL(0x00030006), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_CLK_SCANSEL , RULL(0x00030007), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_CLK_STATUS , RULL(0x00030008), SH_UNT_PERV, SH_ACS_FSI );\nREG64( CEN_GENERIC_CLK_SCANDATA0 , RULL(0x00038000), SH_UNT_PERV, SH_ACS_FSI );\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Animated GIFs Display Code for 32x32 RGB LED Matrix\n *\n * This file contains code to decompress the LZW encoded animated GIF data\n *\n * Written by: Craig A. Lindley, Fabrice Bellard and Steven A. Bennett\n * See my book, \"Practical Image Processing in C\", John Wiley & Sons, Inc.\n *\n * Version: 1.2\n * Last Update: 07\/04\/2014\n *\n * Copyright (c) 2014 Craig A. Lindley\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"SmartMatrix.h\"\n\nextern SmartMatrix matrix;\n\nextern int lsdWidth;\nextern int lsdHeight;\nextern int lsdBackgroundIndex;\n\n\/\/ Table based image attributes\nextern int tbiImageX;\nextern int tbiImageY;\nextern int tbiWidth;\nextern int tbiHeight;\nextern boolean tbiInterlaced;\n\nextern int frameDelay;\nextern int transparentColorIndex;\nextern int disposalMethod;\n\nconst int WIDTH = 32;\nconst int HEIGHT = 32;\n\n\/\/ RGB data structure\ntypedef struct {\n byte Red;\n byte Green;\n byte Blue;\n}\nRGB;\n\nextern RGB palette[];\n\n\/\/ LZW constants\n\/\/ NOTE: LZW_MAXBITS set to 10 to save memory\n#define LZW_MAXBITS 10\n#define LZW_SIZTABLE (1 << LZW_MAXBITS)\n\n\/\/ Masks for 0 .. 16 bits\nunsigned int mask[17] = {\n 0x0000, 0x0001, 0x0003, 0x0007,\n 0x000F, 0x001F, 0x003F, 0x007F,\n 0x00FF, 0x01FF, 0x03FF, 0x07FF,\n 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF,\n 0xFFFF\n};\n\n\/\/ LZW variables\nbyte *pbuf;\nint bbits;\nint bbuf;\nint cursize; \/\/ The current code size\nint curmask;\nint codesize;\nint clear_code;\nint end_code;\nint newcodes; \/\/ First available code\nint top_slot; \/\/ Highest code for current size\nint extra_slot;\nint slot; \/\/ Last read code\nint fc, oc;\nint bs; \/\/ Current buffer size for GIF\nbyte *sp;\nbyte stack [LZW_SIZTABLE];\nbyte suffix [LZW_SIZTABLE];\nunsigned int prefix [LZW_SIZTABLE];\n\n\/\/ Buffer image data is decoded into\nbyte imageData[1024];\n\n\/\/ Backup image data buffer for saving portions of image disposal method == 3\nbyte imageDataBU[1024];\n\n\/\/ Initialize LZW decoder\n\/\/ csize initial code size in bits\n\/\/ buf input data\nvoid lzw_decode_init (int csize, byte *buf) {\n\n \/\/ Initialize read buffer variables\n pbuf = buf;\n bbuf = 0;\n bbits = 0;\n bs = 0;\n\n \/\/ Initialize decoder variables\n codesize = csize;\n cursize = codesize + 1;\n curmask = mask[cursize];\n top_slot = 1 << cursize;\n clear_code = 1 << codesize;\n end_code = clear_code + 1;\n slot = newcodes = clear_code + 2;\n oc = fc = -1;\n sp = stack;\n}\n\n\/\/ Get one code of given number of bits from stream\nint lzw_get_code() {\n\n while (bbits < cursize) {\n if (!bs) {\n bs = *pbuf++;\n }\n bbuf |= (*pbuf++) << bbits;\n bbits += 8;\n bs--;\n }\n int c = bbuf;\n bbuf >>= cursize;\n bbits -= cursize;\n return c & curmask;\n}\n\n\/\/ Decode given number of bytes\n\/\/ buf 8 bit output buffer\n\/\/ len number of pixels to decode\n\/\/ returns the number of bytes decoded\nint lzw_decode(byte *buf, int len) {\n int l, c, code;\n\n if (end_code < 0) {\n return 0;\n }\n l = len;\n\n for (;;) {\n while (sp > stack) {\n *buf++ = *(--sp);\n if ((--l) == 0) {\n goto the_end;\n }\n }\n c = lzw_get_code();\n if (c == end_code) {\n break;\n\n }\n else if (c == clear_code) {\n cursize = codesize + 1;\n curmask = mask[cursize];\n slot = newcodes;\n top_slot = 1 << cursize;\n fc= oc= -1;\n\n }\n else\t{\n\n code = c;\n if ((code == slot) && (fc >= 0)) {\n *sp++ = fc;\n code = oc;\n }\n else if (code >= slot) {\n break;\n }\n while (code >= newcodes) {\n *sp++ = suffix[code];\n code = prefix[code];\n }\n *sp++ = code;\n if ((slot < top_slot) && (oc >= 0)) {\n suffix[slot] = code;\n prefix[slot++] = oc;\n }\n fc = code;\n oc = c;\n if (slot >= top_slot) {\n if (cursize < LZW_MAXBITS) {\n top_slot <<= 1;\n curmask = mask[++cursize];\n }\n }\n }\n }\n end_code = -1;\nthe_end:\n return len - l;\n}\n\n\/\/ Decompress LZW data and display animation frame\nvoid decompressAndDisplayFrame() {\n\n \/\/ Each pixel of image is 8 bits and is an index into the palette\n\n \/\/ How the image is decoded depends upon whether it is interlaced or not\n \/\/ Decode the interlaced LZW data into the image buffer\n if (tbiInterlaced) {\n \/\/ Decode every 8th line starting at line 0\n for (int line = 0; line < tbiHeight; line += 8) {\n lzw_decode(imageData + (line * WIDTH), tbiWidth);\n }\n \/\/ Decode every 8th line starting at line 4\n for (int line = 4; line < tbiHeight; line += 8) {\n lzw_decode(imageData + (line * WIDTH), tbiWidth);\n }\n \/\/ Decode every 4th line starting at line 2\n for (int line = 2; line < tbiHeight; line += 4) {\n lzw_decode(imageData + (line * WIDTH), tbiWidth);\n }\n \/\/ Decode every 2nd line starting at line 1\n for (int line = 1; line < tbiHeight; line += 2) {\n lzw_decode(imageData + (line * WIDTH), tbiWidth);\n }\n }\n else\t{\n \/\/ Decode the non interlaced LZW data into the image data buffer\n for (int line = tbiImageY; line < tbiHeight + tbiImageY; line++) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n }\n\n \/\/ Image data is decompressed, now display portion of image affected by frame\n\n rgb24 color;\n int yOffset, pixel;\n for (int y = tbiImageY; y < tbiHeight + tbiImageY; y++) {\n yOffset = y * WIDTH;\n for (int x = tbiImageX; x < tbiWidth + tbiImageX; x++) {\n \/\/ Get the next pixel\n pixel = imageData[yOffset + x];\n\n \/\/ Check pixel transparency\n if (pixel == transparentColorIndex) {\n continue;\n }\n\n \/\/ Pixel not transparent so get color from palette\n color.red = palette[pixel].Red;\n color.green = palette[pixel].Green;\n color.blue = palette[pixel].Blue;\n\n \/\/ Draw the pixel\n matrix.drawPixel(x, y, color);\n }\n }\n \/\/ Make animation frame visible\n matrix.swapBuffers();\n}\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>Fix to allow drawing interlaced frames that are offset from (0,0)<commit_after>\/*\n * Animated GIFs Display Code for 32x32 RGB LED Matrix\n *\n * This file contains code to decompress the LZW encoded animated GIF data\n *\n * Written by: Craig A. Lindley, Fabrice Bellard and Steven A. Bennett\n * See my book, \"Practical Image Processing in C\", John Wiley & Sons, Inc.\n *\n * Version: 1.2\n * Last Update: 07\/04\/2014\n *\n * Copyright (c) 2014 Craig A. Lindley\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"SmartMatrix.h\"\n\nextern SmartMatrix matrix;\n\nextern int lsdWidth;\nextern int lsdHeight;\nextern int lsdBackgroundIndex;\n\n\/\/ Table based image attributes\nextern int tbiImageX;\nextern int tbiImageY;\nextern int tbiWidth;\nextern int tbiHeight;\nextern boolean tbiInterlaced;\n\nextern int frameDelay;\nextern int transparentColorIndex;\nextern int disposalMethod;\n\nconst int WIDTH = 32;\nconst int HEIGHT = 32;\n\n\/\/ RGB data structure\ntypedef struct {\n byte Red;\n byte Green;\n byte Blue;\n}\nRGB;\n\nextern RGB palette[];\n\n\/\/ LZW constants\n\/\/ NOTE: LZW_MAXBITS set to 10 to save memory\n#define LZW_MAXBITS 10\n#define LZW_SIZTABLE (1 << LZW_MAXBITS)\n\n\/\/ Masks for 0 .. 16 bits\nunsigned int mask[17] = {\n 0x0000, 0x0001, 0x0003, 0x0007,\n 0x000F, 0x001F, 0x003F, 0x007F,\n 0x00FF, 0x01FF, 0x03FF, 0x07FF,\n 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF,\n 0xFFFF\n};\n\n\/\/ LZW variables\nbyte *pbuf;\nint bbits;\nint bbuf;\nint cursize; \/\/ The current code size\nint curmask;\nint codesize;\nint clear_code;\nint end_code;\nint newcodes; \/\/ First available code\nint top_slot; \/\/ Highest code for current size\nint extra_slot;\nint slot; \/\/ Last read code\nint fc, oc;\nint bs; \/\/ Current buffer size for GIF\nbyte *sp;\nbyte stack [LZW_SIZTABLE];\nbyte suffix [LZW_SIZTABLE];\nunsigned int prefix [LZW_SIZTABLE];\n\n\/\/ Buffer image data is decoded into\nbyte imageData[1024];\n\n\/\/ Backup image data buffer for saving portions of image disposal method == 3\nbyte imageDataBU[1024];\n\n\/\/ Initialize LZW decoder\n\/\/ csize initial code size in bits\n\/\/ buf input data\nvoid lzw_decode_init (int csize, byte *buf) {\n\n \/\/ Initialize read buffer variables\n pbuf = buf;\n bbuf = 0;\n bbits = 0;\n bs = 0;\n\n \/\/ Initialize decoder variables\n codesize = csize;\n cursize = codesize + 1;\n curmask = mask[cursize];\n top_slot = 1 << cursize;\n clear_code = 1 << codesize;\n end_code = clear_code + 1;\n slot = newcodes = clear_code + 2;\n oc = fc = -1;\n sp = stack;\n}\n\n\/\/ Get one code of given number of bits from stream\nint lzw_get_code() {\n\n while (bbits < cursize) {\n if (!bs) {\n bs = *pbuf++;\n }\n bbuf |= (*pbuf++) << bbits;\n bbits += 8;\n bs--;\n }\n int c = bbuf;\n bbuf >>= cursize;\n bbits -= cursize;\n return c & curmask;\n}\n\n\/\/ Decode given number of bytes\n\/\/ buf 8 bit output buffer\n\/\/ len number of pixels to decode\n\/\/ returns the number of bytes decoded\nint lzw_decode(byte *buf, int len) {\n int l, c, code;\n\n if (end_code < 0) {\n return 0;\n }\n l = len;\n\n for (;;) {\n while (sp > stack) {\n *buf++ = *(--sp);\n if ((--l) == 0) {\n goto the_end;\n }\n }\n c = lzw_get_code();\n if (c == end_code) {\n break;\n\n }\n else if (c == clear_code) {\n cursize = codesize + 1;\n curmask = mask[cursize];\n slot = newcodes;\n top_slot = 1 << cursize;\n fc= oc= -1;\n\n }\n else\t{\n\n code = c;\n if ((code == slot) && (fc >= 0)) {\n *sp++ = fc;\n code = oc;\n }\n else if (code >= slot) {\n break;\n }\n while (code >= newcodes) {\n *sp++ = suffix[code];\n code = prefix[code];\n }\n *sp++ = code;\n if ((slot < top_slot) && (oc >= 0)) {\n suffix[slot] = code;\n prefix[slot++] = oc;\n }\n fc = code;\n oc = c;\n if (slot >= top_slot) {\n if (cursize < LZW_MAXBITS) {\n top_slot <<= 1;\n curmask = mask[++cursize];\n }\n }\n }\n }\n end_code = -1;\nthe_end:\n return len - l;\n}\n\n\/\/ Decompress LZW data and display animation frame\nvoid decompressAndDisplayFrame() {\n\n \/\/ Each pixel of image is 8 bits and is an index into the palette\n\n \/\/ How the image is decoded depends upon whether it is interlaced or not\n \/\/ Decode the interlaced LZW data into the image buffer\n if (tbiInterlaced) {\n \/\/ Decode every 8th line starting at line 0\n for (int line = tbiImageY + 0; line < tbiHeight + tbiImageY; line += 8) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n \/\/ Decode every 8th line starting at line 4\n for (int line = tbiImageY + 4; line < tbiHeight + tbiImageY; line += 8) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n \/\/ Decode every 4th line starting at line 2\n for (int line = tbiImageY + 2; line < tbiHeight + tbiImageY; line += 4) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n \/\/ Decode every 2nd line starting at line 1\n for (int line = tbiImageY + 1; line < tbiHeight + tbiImageY; line += 2) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n }\n else\t{\n \/\/ Decode the non interlaced LZW data into the image data buffer\n for (int line = tbiImageY; line < tbiHeight + tbiImageY; line++) {\n lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);\n }\n }\n\n \/\/ Image data is decompressed, now display portion of image affected by frame\n\n rgb24 color;\n int yOffset, pixel;\n for (int y = tbiImageY; y < tbiHeight + tbiImageY; y++) {\n yOffset = y * WIDTH;\n for (int x = tbiImageX; x < tbiWidth + tbiImageX; x++) {\n \/\/ Get the next pixel\n pixel = imageData[yOffset + x];\n\n \/\/ Check pixel transparency\n if (pixel == transparentColorIndex) {\n continue;\n }\n\n \/\/ Pixel not transparent so get color from palette\n color.red = palette[pixel].Red;\n color.green = palette[pixel].Green;\n color.blue = palette[pixel].Blue;\n\n \/\/ Draw the pixel\n matrix.drawPixel(x, y, color);\n }\n }\n \/\/ Make animation frame visible\n matrix.swapBuffers();\n}\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n#include <vector>\n#include <iomanip>\n#include <iostream>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\terror_code ec;\n\n\taddress local = guess_local_address(ios);\n\tstd::cout << \"Local address: \" << local << std::endl;\n\n\taddress def_gw = get_default_gateway(ios, ec);\n\tif (ec)\n\t{\n\t\tstd::cerr << ec.message() << std::endl;\n\t\treturn 1;\n\t}\n\tstd::cout << \"Default gateway: \" << def_gw << std::endl;\n\n\tstd::cout << \"=========== Routes ===========\\n\";\n\tstd::vector<ip_route> routes = enum_routes(ios, ec);\n\tif (ec)\n\t{\n\t\tstd::cerr << ec.message() << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << std::setiosflags(std::ios::left)\n\t\t<< std::setw(18) << \"destination\"\n\t\t<< std::setw(18) << \"netmask\"\n\t\t<< std::setw(35) << \"gateway\"\n\t\t<< \"interface name\"\n\t\t<< std::endl;\n\n\tfor (std::vector<ip_route>::const_iterator i = routes.begin()\n\t\t, end(routes.end()); i != end; ++i)\n\t{\n\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t<< std::setw(18) << i->destination\n\t\t\t<< std::setw(18) << i->netmask\n\t\t\t<< std::setw(35) << i->gateway\n\t\t\t<< i->name\n\t\t\t<< std::endl;\n\t}\n\n\tstd::cout << \"========= Interfaces =========\\n\";\n\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\tif (ec)\n\t{\n\t\tstd::cerr << ec.message() << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << std::setiosflags(std::ios::left)\n\t\t<< std::setw(35) << \"address\"\n\t\t<< std::setw(18) << \"netmask\"\n\t\t<< std::setw(18) << \"name\"\n\t\t<< \"flags\"\n\t\t<< std::endl;\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tstd::cout << std::setiosflags(std::ios::left)\n\t\t\t<< std::setw(35) << i->interface_address\n\t\t\t<< std::setw(18) << i->netmask\n\t\t\t<< std::setw(18) << i->name\n\t\t\t<< (is_multicast(i->interface_address)?\"multicast \":\"\")\n\t\t\t<< (is_local(i->interface_address)?\"local \":\"\")\n\t\t\t<< (is_loopback(i->interface_address)?\"loopback \":\"\")\n\t\t\t\n\t\t\t<< std::endl;\n\t}\n\n}\n\n<commit_msg>replaced iostream in example<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <stdio.h>\n#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\terror_code ec;\n\taddress local = guess_local_address(ios);\n\tprintf(\"Local address: %s\\n\", local.to_string(ec).c_str());\n\n\taddress def_gw = get_default_gateway(ios, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\n\tprintf(\"Default gateway: %s\\n\", def_gw.to_string(ec).c_str());\n\n\tprintf(\"=========== Routes ===========\\n\");\n\tstd::vector<ip_route> routes = enum_routes(ios, ec);\n\tif (ec)\n\t{\n\t\tprintf(\"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\n\tprintf(\"%-18s%-18s%-35sinterface name\\n\", \"destination\", \"network\", \"gateway\");\n\n\tfor (std::vector<ip_route>::const_iterator i = routes.begin()\n\t\t, end(routes.end()); i != end; ++i)\n\t{\n\t\tprintf(\"%-18s%-18s%-35s%s\\n\"\n\t\t\t, i->destination.to_string(ec).c_str()\n\t\t\t, i->netmask.to_string(ec).c_str()\n\t\t\t, i->gateway.to_string(ec).c_str()\n\t\t\t, i->name);\n\t}\n\n\tprintf(\"========= Interfaces =========\\n\");\n\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\tif (ec)\n\t{\n\t\tprintf(\"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\n\tprintf(\"%-18s%-18s%-35sflags\\n\", \"address\", \"netmask\", \"name\");\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tprintf(\"%-18s%-18s%-35s%s%s%s\\n\"\n\t\t\t, i->interface_address.to_string(ec).c_str()\n\t\t\t, i->netmask.to_string(ec).c_str()\n\t\t\t, i->name\n\t\t\t, (is_multicast(i->interface_address)?\"multicast \":\"\")\n\t\t\t, (is_local(i->interface_address)?\"local \":\"\")\n\t\t\t, (is_loopback(i->interface_address)?\"loopback \":\"\")\n\t\t\t);\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#pragma once\n\n#define GLFW_INCLUDE_GLU\n#include <GLFW\/glfw3.h>\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic Data Types \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct float3 { float x, y, z; };\nstruct float2 { float x, y; };\n\nstruct rect\n{\n float x, y;\n float w, h;\n\n \/\/ Create new rect within original boundaries with give aspect ration\n rect adjust_ratio(float2 size) const\n {\n auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x \/ size.y;\n if (W > w)\n {\n auto scale = w \/ W;\n W *= scale;\n H *= scale;\n }\n\n return{ x + (w - W) \/ 2, y + (h - H) \/ 2, W, H };\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Simple font loading code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"..\/third-party\/stb_easy_font.h\"\n\ninline void draw_text(int x, int y, const char * text)\n{\n char buffer[60000]; \/\/ ~300 chars\n glEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, 16, buffer);\n glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer)));\n glDisableClientState(GL_VERTEX_ARRAY);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Image display code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass texture\n{\npublic:\n void render(const rs2::frameset& frames, int window_width, int window_height)\n {\n std::vector<rs2::video_frame> supported_frames;\n for (auto f : frames)\n {\n if (can_render(f))\n supported_frames.push_back(f);\n }\n if (supported_frames.empty())\n return;\n\n std::sort(supported_frames.begin(), supported_frames.end(), [](rs2::frame first, rs2::frame second)\n { return first.get_profile().stream_type() < second.get_profile().stream_type(); });\n\n auto image_grid = calc_grid(float2{ (float)window_width, (float)window_height }, supported_frames);\n\n int image_index = 0;\n for (auto f : supported_frames)\n {\n upload(f);\n show(image_grid.at(image_index));\n image_index++;\n }\n }\n\n void render(const rs2::video_frame& frame, const rect& r)\n {\n upload(frame);\n show(r.adjust_ratio({ float(width), float(height) }));\n }\n\n void upload(const rs2::video_frame& frame)\n {\n if (!frame) return;\n\n if (!gl_handle)\n glGenTextures(1, &gl_handle);\n GLenum err = glGetError();\n\n auto format = frame.get_profile().format();\n width = frame.get_width();\n height = frame.get_height();\n stream = frame.get_profile().stream_type();\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_RGBA8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_Y8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n default:\n throw std::runtime_error(\"The requested format is not supported by this demo!\");\n }\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n GLuint get_gl_handle() { return gl_handle; }\n\n void show(const rect& r) const\n {\n if (!gl_handle)\n return;\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n glEnable(GL_TEXTURE_2D);\n glBegin(GL_QUAD_STRIP);\n glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h);\n glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y);\n glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h);\n glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream));\n }\n\nprivate:\n GLuint gl_handle = 0;\n int width = 0;\n int height = 0;\n rs2_stream stream = RS2_STREAM_ANY;\n\n bool can_render(const rs2::frame& f) const\n {\n auto format = f.get_profile().format();\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n case RS2_FORMAT_RGBA8:\n case RS2_FORMAT_Y8:\n return true;\n default:\n return false;\n }\n }\n\n rect calc_grid(float2 window, int streams)\n {\n float ratio = window.x \/ window.y;\n auto x = sqrt(ratio * (float)streams);\n auto y = (float)streams \/ x;\n auto w = round(x);\n auto h = round(y);\n while (w*h > streams)\n h > w ? h-- : w--;\n while (w*h < streams)\n h > w ? w++ : h++;\n auto new_w = round(window.x \/ w);\n auto new_h = round(window.y \/ h);\n return rect{ w, h, new_w, new_h}; \/\/column count, line count, cell width cell height\n }\n\n std::vector<rect> calc_grid(float2 window, std::vector<rs2::video_frame>& frames)\n {\n auto grid = calc_grid(window, frames.size());\n\n int index = 0;\n std::vector<rect> rv;\n int curr_line = -1;\n for (auto f : frames)\n {\n auto mod = index % (int)grid.x;\n auto fw = (float)frames[index].get_width();\n auto fh = (float)frames[index].get_height();\n\n float cell_x_postion = (float)(mod * grid.w);\n if (mod == 0) curr_line++;\n float cell_y_position = curr_line * grid.h;\n\n auto r = rect{ cell_x_postion, cell_y_position, grid.w, grid.h };\n rv.push_back(r.adjust_ratio(float2{ fw, fh }));\n index++;\n }\n\n return rv;\n }\n};\n\nclass window\n{\npublic:\n std::function<void(bool)> on_left_mouse = [](bool) {};\n std::function<void(double, double)> on_mouse_scroll = [](double, double) {};\n std::function<void(double, double)> on_mouse_move = [](double, double) {};\n std::function<void(int)> on_key_release = [](int) {};\n\n window(int width, int height, const char* title)\n : _width(width), _height(height)\n {\n glfwInit();\n win = glfwCreateWindow(width, height, title, nullptr, nullptr);\n if (!win)\n throw std::runtime_error(\"Could not open OpenGL window, please check your graphic drivers or use the textual SDK tools\");\n glfwMakeContextCurrent(win);\n\n glfwSetWindowUserPointer(win, this);\n glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (button == 0) s->on_left_mouse(action == GLFW_PRESS);\n });\n\n glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_scroll(xoffset, yoffset);\n });\n\n glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_move(x, y);\n });\n\n glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (0 == action) \/\/ on key release\n {\n s->on_key_release(key);\n }\n });\n }\n\n float width() const { return float(_width); }\n float height() const { return float(_height); }\n\n operator bool()\n {\n glPopMatrix();\n glfwSwapBuffers(win);\n\n auto res = !glfwWindowShouldClose(win);\n\n glfwPollEvents();\n glfwGetFramebufferSize(win, &_width, &_height);\n\n \/\/ Clear the framebuffer\n glClear(GL_COLOR_BUFFER_BIT);\n glViewport(0, 0, _width, _height);\n\n \/\/ Draw the images\n glPushMatrix();\n glfwGetWindowSize(win, &_width, &_height);\n glOrtho(0, _width, _height, 0, -1, +1);\n\n return res;\n }\n\n ~window()\n {\n glfwDestroyWindow(win);\n glfwTerminate();\n }\n\n operator GLFWwindow*() { return win; }\n\nprivate:\n GLFWwindow * win;\n int _width, _height;\n};\n\n\/\/ Struct for managing rotation of pointcloud view\nstruct glfw_state {\n glfw_state() : yaw(15.0), pitch(15.0), last_x(0.0), last_y(0.0),\n ml(false), offset_x(2.f), offset_y(2.f), tex() {}\n double yaw;\n double pitch;\n double last_x;\n double last_y;\n bool ml;\n float offset_x;\n float offset_y;\n texture tex;\n};\n\n\n\/\/ Handles all the OpenGL calls needed to display the point cloud\nvoid draw_pointcloud(float width, float height, glfw_state& app_state, rs2::points& points)\n{\n if (!points)\n return;\n\n \/\/ OpenGL commands that prep screen for the pointcloud\n glPopMatrix();\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glClearColor(153.f \/ 255, 153.f \/ 255, 153.f \/ 255, 1);\n glClear(GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n gluPerspective(60, width \/ height, 0.01f, 10.0f);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0);\n\n glTranslatef(0, 0, +0.5f + app_state.offset_y*0.05f);\n glRotated(app_state.pitch, 1, 0, 0);\n glRotated(app_state.yaw, 0, 1, 0);\n glTranslatef(0, 0, -0.5f);\n\n glPointSize(width \/ 640);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, app_state.tex.get_gl_handle());\n float tex_border_color[] = { 0.8f, 0.8f, 0.8f, 0.8f };\n glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_color);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); \/\/ GL_CLAMP_TO_EDGE\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); \/\/ GL_CLAMP_TO_EDGE\n glBegin(GL_POINTS);\n\n\n \/* this segment actually prints the pointcloud *\/\n auto vertices = points.get_vertices(); \/\/ get vertices\n auto tex_coords = points.get_texture_coordinates(); \/\/ and texture coordinates\n for (int i = 0; i < points.size(); i++)\n {\n if (vertices[i].z)\n {\n \/\/ upload the point and texture coordinates only for points we have depth data for\n glVertex3fv(vertices[i]);\n glTexCoord2fv(tex_coords[i]);\n }\n }\n\n \/\/ OpenGL cleanup\n glEnd();\n glPopMatrix();\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n glPushMatrix();\n}\n\n\/\/ Registers the state variable and callbacks to allow mouse control of the pointcloud\nvoid register_glfw_callbacks(window& app, glfw_state& app_state)\n{\n app.on_left_mouse = [&](bool pressed)\n {\n app_state.ml = pressed;\n };\n\n app.on_mouse_scroll = [&](double xoffset, double yoffset)\n {\n app_state.offset_x -= static_cast<float>(xoffset);\n app_state.offset_y -= static_cast<float>(yoffset);\n };\n\n app.on_mouse_move = [&](double x, double y)\n {\n if (app_state.ml)\n {\n app_state.yaw -= (x - app_state.last_x);\n app_state.yaw = std::max(app_state.yaw, -120.0);\n app_state.yaw = std::min(app_state.yaw, +120.0);\n app_state.pitch += (y - app_state.last_y);\n app_state.pitch = std::max(app_state.pitch, -80.0);\n app_state.pitch = std::min(app_state.pitch, +80.0);\n }\n app_state.last_x = x;\n app_state.last_y = y;\n };\n\n app.on_key_release = [&](int key)\n {\n if (key == 32) \/\/ Escape\n {\n app_state.yaw = app_state.pitch = 0; app_state.offset_x = app_state.offset_y = 0.0;\n }\n };\n}<commit_msg>resolve linux compilation issues<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#pragma once\n\n#define GLFW_INCLUDE_GLU\n#include <GLFW\/glfw3.h>\n\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Basic Data Types \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct float3 { float x, y, z; };\nstruct float2 { float x, y; };\n\nstruct rect\n{\n float x, y;\n float w, h;\n\n \/\/ Create new rect within original boundaries with give aspect ration\n rect adjust_ratio(float2 size) const\n {\n auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x \/ size.y;\n if (W > w)\n {\n auto scale = w \/ W;\n W *= scale;\n H *= scale;\n }\n\n return{ x + (w - W) \/ 2, y + (h - H) \/ 2, W, H };\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Simple font loading code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"..\/third-party\/stb_easy_font.h\"\n\ninline void draw_text(int x, int y, const char * text)\n{\n char buffer[60000]; \/\/ ~300 chars\n glEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, 16, buffer);\n glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer)));\n glDisableClientState(GL_VERTEX_ARRAY);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Image display code \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass texture\n{\npublic:\n void render(const rs2::frameset& frames, int window_width, int window_height)\n {\n std::vector<rs2::video_frame> supported_frames;\n for (auto f : frames)\n {\n if (can_render(f))\n supported_frames.push_back(f);\n }\n if (supported_frames.empty())\n return;\n\n std::sort(supported_frames.begin(), supported_frames.end(), [](rs2::frame first, rs2::frame second)\n { return first.get_profile().stream_type() < second.get_profile().stream_type(); });\n\n auto image_grid = calc_grid(float2{ (float)window_width, (float)window_height }, supported_frames);\n\n int image_index = 0;\n for (auto f : supported_frames)\n {\n upload(f);\n show(image_grid.at(image_index));\n image_index++;\n }\n }\n\n void render(const rs2::video_frame& frame, const rect& r)\n {\n upload(frame);\n show(r.adjust_ratio({ float(width), float(height) }));\n }\n\n void upload(const rs2::video_frame& frame)\n {\n if (!frame) return;\n\n if (!gl_handle)\n glGenTextures(1, &gl_handle);\n GLenum err = glGetError();\n\n auto format = frame.get_profile().format();\n width = frame.get_width();\n height = frame.get_height();\n stream = frame.get_profile().stream_type();\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_RGBA8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n case RS2_FORMAT_Y8:\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data());\n break;\n default:\n throw std::runtime_error(\"The requested format is not supported by this demo!\");\n }\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n GLuint get_gl_handle() { return gl_handle; }\n\n void show(const rect& r) const\n {\n if (!gl_handle)\n return;\n\n glBindTexture(GL_TEXTURE_2D, gl_handle);\n glEnable(GL_TEXTURE_2D);\n glBegin(GL_QUAD_STRIP);\n glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h);\n glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y);\n glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h);\n glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream));\n }\n\nprivate:\n GLuint gl_handle = 0;\n int width = 0;\n int height = 0;\n rs2_stream stream = RS2_STREAM_ANY;\n\n bool can_render(const rs2::frame& f) const\n {\n auto format = f.get_profile().format();\n switch (format)\n {\n case RS2_FORMAT_RGB8:\n case RS2_FORMAT_RGBA8:\n case RS2_FORMAT_Y8:\n return true;\n default:\n return false;\n }\n }\n\n rect calc_grid(float2 window, int streams)\n {\n float ratio = window.x \/ window.y;\n auto x = sqrt(ratio * (float)streams);\n auto y = (float)streams \/ x;\n auto w = round(x);\n auto h = round(y);\n while (w*h > streams)\n h > w ? h-- : w--;\n while (w*h < streams)\n h > w ? w++ : h++;\n auto new_w = round(window.x \/ w);\n auto new_h = round(window.y \/ h);\n return rect{ w, h, new_w, new_h}; \/\/column count, line count, cell width cell height\n }\n\n std::vector<rect> calc_grid(float2 window, std::vector<rs2::video_frame>& frames)\n {\n auto grid = calc_grid(window, frames.size());\n\n int index = 0;\n std::vector<rect> rv;\n int curr_line = -1;\n for (auto f : frames)\n {\n auto mod = index % (int)grid.x;\n auto fw = (float)frames[index].get_width();\n auto fh = (float)frames[index].get_height();\n\n float cell_x_postion = (float)(mod * grid.w);\n if (mod == 0) curr_line++;\n float cell_y_position = curr_line * grid.h;\n\n auto r = rect{ cell_x_postion, cell_y_position, grid.w, grid.h };\n rv.push_back(r.adjust_ratio(float2{ fw, fh }));\n index++;\n }\n\n return rv;\n }\n};\n\nclass window\n{\npublic:\n std::function<void(bool)> on_left_mouse = [](bool) {};\n std::function<void(double, double)> on_mouse_scroll = [](double, double) {};\n std::function<void(double, double)> on_mouse_move = [](double, double) {};\n std::function<void(int)> on_key_release = [](int) {};\n\n window(int width, int height, const char* title)\n : _width(width), _height(height)\n {\n glfwInit();\n win = glfwCreateWindow(width, height, title, nullptr, nullptr);\n if (!win)\n throw std::runtime_error(\"Could not open OpenGL window, please check your graphic drivers or use the textual SDK tools\");\n glfwMakeContextCurrent(win);\n\n glfwSetWindowUserPointer(win, this);\n glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (button == 0) s->on_left_mouse(action == GLFW_PRESS);\n });\n\n glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_scroll(xoffset, yoffset);\n });\n\n glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n s->on_mouse_move(x, y);\n });\n\n glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods)\n {\n auto s = (window*)glfwGetWindowUserPointer(win);\n if (0 == action) \/\/ on key release\n {\n s->on_key_release(key);\n }\n });\n }\n\n float width() const { return float(_width); }\n float height() const { return float(_height); }\n\n operator bool()\n {\n glPopMatrix();\n glfwSwapBuffers(win);\n\n auto res = !glfwWindowShouldClose(win);\n\n glfwPollEvents();\n glfwGetFramebufferSize(win, &_width, &_height);\n\n \/\/ Clear the framebuffer\n glClear(GL_COLOR_BUFFER_BIT);\n glViewport(0, 0, _width, _height);\n\n \/\/ Draw the images\n glPushMatrix();\n glfwGetWindowSize(win, &_width, &_height);\n glOrtho(0, _width, _height, 0, -1, +1);\n\n return res;\n }\n\n ~window()\n {\n glfwDestroyWindow(win);\n glfwTerminate();\n }\n\n operator GLFWwindow*() { return win; }\n\nprivate:\n GLFWwindow * win;\n int _width, _height;\n};\n\n\/\/ Struct for managing rotation of pointcloud view\nstruct glfw_state {\n glfw_state() : yaw(15.0), pitch(15.0), last_x(0.0), last_y(0.0),\n ml(false), offset_x(2.f), offset_y(2.f), tex() {}\n double yaw;\n double pitch;\n double last_x;\n double last_y;\n bool ml;\n float offset_x;\n float offset_y;\n texture tex;\n};\n\n\n\/\/ Handles all the OpenGL calls needed to display the point cloud\nvoid draw_pointcloud(float width, float height, glfw_state& app_state, rs2::points& points)\n{\n if (!points)\n return;\n\n \/\/ OpenGL commands that prep screen for the pointcloud\n glPopMatrix();\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glClearColor(153.f \/ 255, 153.f \/ 255, 153.f \/ 255, 1);\n glClear(GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n gluPerspective(60, width \/ height, 0.01f, 10.0f);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0);\n\n glTranslatef(0, 0, +0.5f + app_state.offset_y*0.05f);\n glRotated(app_state.pitch, 1, 0, 0);\n glRotated(app_state.yaw, 0, 1, 0);\n glTranslatef(0, 0, -0.5f);\n\n glPointSize(width \/ 640);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, app_state.tex.get_gl_handle());\n float tex_border_color[] = { 0.8f, 0.8f, 0.8f, 0.8f };\n glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_color);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); \/\/ GL_CLAMP_TO_EDGE\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); \/\/ GL_CLAMP_TO_EDGE\n glBegin(GL_POINTS);\n\n\n \/* this segment actually prints the pointcloud *\/\n auto vertices = points.get_vertices(); \/\/ get vertices\n auto tex_coords = points.get_texture_coordinates(); \/\/ and texture coordinates\n for (int i = 0; i < points.size(); i++)\n {\n if (vertices[i].z)\n {\n \/\/ upload the point and texture coordinates only for points we have depth data for\n glVertex3fv(vertices[i]);\n glTexCoord2fv(tex_coords[i]);\n }\n }\n\n \/\/ OpenGL cleanup\n glEnd();\n glPopMatrix();\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n glPushMatrix();\n}\n\n\/\/ Registers the state variable and callbacks to allow mouse control of the pointcloud\nvoid register_glfw_callbacks(window& app, glfw_state& app_state)\n{\n app.on_left_mouse = [&](bool pressed)\n {\n app_state.ml = pressed;\n };\n\n app.on_mouse_scroll = [&](double xoffset, double yoffset)\n {\n app_state.offset_x -= static_cast<float>(xoffset);\n app_state.offset_y -= static_cast<float>(yoffset);\n };\n\n app.on_mouse_move = [&](double x, double y)\n {\n if (app_state.ml)\n {\n app_state.yaw -= (x - app_state.last_x);\n app_state.yaw = std::max(app_state.yaw, -120.0);\n app_state.yaw = std::min(app_state.yaw, +120.0);\n app_state.pitch += (y - app_state.last_y);\n app_state.pitch = std::max(app_state.pitch, -80.0);\n app_state.pitch = std::min(app_state.pitch, +80.0);\n }\n app_state.last_x = x;\n app_state.last_y = y;\n };\n\n app.on_key_release = [&](int key)\n {\n if (key == 32) \/\/ Escape\n {\n app_state.yaw = app_state.pitch = 0; app_state.offset_x = app_state.offset_y = 0.0;\n }\n };\n}<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"gdbengine.h\"\n#include \"gdbmi.h\"\n#include \"abstractgdbadapter.h\"\n#include \"debuggeractions.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstringutils.h\"\n#include \"debuggertooltipmanager.h\"\n\n#include \"breakhandler.h\"\n#include \"watchhandler.h\"\n#include \"stackhandler.h\"\n\n#include <utils\/qtcassert.h>\n\n#define PRECONDITION QTC_ASSERT(hasPython(), \/**\/)\n#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)\n\n\nnamespace Debugger {\nnamespace Internal {\n\nvoid GdbEngine::updateLocalsPython(bool tryPartial, const QByteArray &varList)\n{\n PRECONDITION;\n m_processedNames.clear();\n watchHandler()->beginCycle(!tryPartial);\n \/\/m_toolTipExpression.clear();\n WatchHandler *handler = watchHandler();\n\n QByteArray expanded = \"expanded:\" + handler->expansionRequests() + ' ';\n expanded += \"typeformats:\" + handler->typeFormatRequests() + ' ';\n expanded += \"formats:\" + handler->individualFormatRequests();\n\n QByteArray watchers;\n const QString fileName = stackHandler()->currentFrame().file;\n const QString function = stackHandler()->currentFrame().function;\n if (!fileName.isEmpty()) {\n QStringList expressions =\n DebuggerToolTipManager::instance()->treeWidgetExpressions(fileName, objectName(), function);\n const QString currentExpression = tooltipExpression();\n if (!currentExpression.isEmpty() && !expressions.contains(currentExpression))\n expressions.push_back(currentExpression);\n foreach (const QString &te, expressions) {\n if (!watchers.isEmpty())\n watchers += \"##\";\n watchers += te.toLatin1();\n watchers += '#';\n watchers += tooltipIName(te);\n }\n }\n\n QHash<QByteArray, int> watcherNames = handler->watcherNames();\n QHashIterator<QByteArray, int> it(watcherNames);\n while (it.hasNext()) {\n it.next();\n if (!watchers.isEmpty())\n watchers += \"##\";\n watchers += it.key() + \"#watch.\" + QByteArray::number(it.value());\n }\n\n QByteArray options;\n if (debuggerCore()->boolSetting(UseDebuggingHelpers))\n options += \"fancy,\";\n if (debuggerCore()->boolSetting(AutoDerefPointers))\n options += \"autoderef,\";\n if (!qgetenv(\"QTC_DEBUGGER_PYTHON_VERBOSE\").isEmpty())\n options += \"pe,\";\n if (options.isEmpty())\n options += \"defaults,\";\n if (tryPartial)\n options += \"partial,\";\n options.chop(1);\n\n QByteArray resultVar;\n if (!m_resultVarName.isEmpty())\n resultVar = \"resultvarname:\" + m_resultVarName + ' ';\n\n postCommand(\"bb options:\" + options + \" vars:\" + varList + ' '\n + resultVar + expanded + \" watchers:\" + watchers.toHex(),\n WatchUpdate, CB(handleStackFramePython), QVariant(tryPartial));\n}\n\nvoid GdbEngine::handleStackListLocalsPython(const GdbResponse &response)\n{\n PRECONDITION;\n if (response.resultClass == GdbResultDone) {\n \/\/ 44^done,data={locals=[name=\"model\",name=\"backString\",...]}\n QByteArray varList = \"vars\"; \/\/ Dummy entry, will be stripped by dumper.\n foreach (const GdbMi &child, response.data.findChild(\"locals\").children()) {\n varList.append(',');\n varList.append(child.data());\n }\n updateLocalsPython(false, varList);\n }\n}\n\nvoid GdbEngine::handleStackFramePython(const GdbResponse &response)\n{\n PRECONDITION;\n if (response.resultClass == GdbResultDone) {\n const bool partial = response.cookie.toBool();\n \/\/qDebug() << \"READING \" << (partial ? \"PARTIAL\" : \"FULL\");\n QByteArray out = response.data.findChild(\"consolestreamoutput\").data();\n while (out.endsWith(' ') || out.endsWith('\\n'))\n out.chop(1);\n \/\/qDebug() << \"SECOND CHUNK: \" << out;\n int pos = out.indexOf(\"data=\");\n if (pos != 0) {\n showMessage(_(\"DISCARDING JUNK AT BEGIN OF RESPONSE: \"\n + out.left(pos)));\n out = out.mid(pos);\n }\n GdbMi all;\n all.fromStringMultiple(out);\n \/\/qDebug() << \"ALL: \" << all.toString();\n\n GdbMi data = all.findChild(\"data\");\n QList<WatchData> list;\n foreach (const GdbMi &child, data.children()) {\n WatchData dummy;\n dummy.iname = child.findChild(\"iname\").data();\n GdbMi wname = child.findChild(\"wname\");\n if (wname.isValid()) {\n \/\/ Happens (only) for watched expressions. They are encoded as.\n \/\/ base64 encoded 8 bit data, without quotes\n dummy.name = decodeData(wname.data(), 5);\n dummy.exp = dummy.name.toUtf8();\n } else {\n dummy.name = _(child.findChild(\"name\").data());\n }\n \/\/qDebug() << \"CHILD: \" << child.toString();\n parseWatchData(watchHandler()->expandedINames(), dummy, child, &list);\n }\n watchHandler()->insertBulkData(list);\n \/\/for (int i = 0; i != list.size(); ++i)\n \/\/ qDebug() << \"LOCAL: \" << list.at(i).toString();\n\n#if 0\n data = all.findChild(\"bkpts\");\n if (data.isValid()) {\n BreakHandler *handler = breakHandler();\n foreach (const GdbMi &child, data.children()) {\n int bpNumber = child.findChild(\"number\").data().toInt();\n int found = handler->findBreakpoint(bpNumber);\n if (found != -1) {\n BreakpointData *bp = handler->at(found);\n GdbMi addr = child.findChild(\"addr\");\n if (addr.isValid()) {\n bp->bpAddress = child.findChild(\"addr\").data();\n bp->pending = false;\n } else {\n bp->bpAddress = \"<PENDING>\";\n bp->pending = true;\n }\n bp->bpFuncName = child.findChild(\"func\").data();\n bp->bpLineNumber = child.findChild(\"line\").data();\n bp->bpFileName = child.findChild(\"file\").data();\n bp->markerLineNumber = bp->bpLineNumber.toInt();\n bp->markerFileName = bp->bpFileName;\n \/\/ Happens with moved\/symlinked sources.\n if (!bp->fileName.isEmpty()\n && !bp->bpFileName.isEmpty()\n && bp->fileName != bp->bpFileName)\n bp->markerFileName = bp->fileName;\n } else {\n QTC_ASSERT(false, qDebug() << child.toString() << bpNumber);\n \/\/bp->bpNumber = \"<unavailable>\";\n }\n }\n handler->updateMarkers();\n }\n#endif\n\n \/\/PENDING_DEBUG(\"AFTER handleStackFrame()\");\n \/\/ FIXME: This should only be used when updateLocals() was\n \/\/ triggered by expanding an item in the view.\n if (m_pendingWatchRequests <= 0) {\n \/\/PENDING_DEBUG(\"\\n\\n .... AND TRIGGERS MODEL UPDATE\\n\");\n rebuildWatchModel();\n }\n if (!partial)\n emit stackFrameCompleted();\n } else {\n showMessage(_(\"DUMPER FAILED: \" + response.toString()));\n }\n}\n\n\/\/ Called from CoreAdapter and AttachAdapter\nvoid GdbEngine::updateAllPython()\n{\n PRECONDITION;\n \/\/PENDING_DEBUG(\"UPDATING ALL\\n\");\n QTC_ASSERT(state() == InferiorUnrunnable || state() == InferiorStopOk, \/**\/);\n reloadModulesInternal();\n postCommand(\"-stack-list-frames\", CB(handleStackListFrames),\n QVariant::fromValue<StackCookie>(StackCookie(false, true)));\n stackHandler()->setCurrentIndex(0);\n if (m_gdbAdapter->isTrkAdapter())\n m_gdbAdapter->trkReloadThreads();\n else\n postCommand(\"-thread-list-ids\", CB(handleThreadListIds), 0);\n reloadRegisters();\n updateLocals();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<commit_msg>debugger: use the new enum<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"gdbengine.h\"\n#include \"gdbmi.h\"\n#include \"abstractgdbadapter.h\"\n#include \"debuggeractions.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstringutils.h\"\n#include \"debuggertooltipmanager.h\"\n\n#include \"breakhandler.h\"\n#include \"watchhandler.h\"\n#include \"stackhandler.h\"\n\n#include <utils\/qtcassert.h>\n\n#define PRECONDITION QTC_ASSERT(hasPython(), \/**\/)\n#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)\n\n\nnamespace Debugger {\nnamespace Internal {\n\nvoid GdbEngine::updateLocalsPython(bool tryPartial, const QByteArray &varList)\n{\n PRECONDITION;\n m_processedNames.clear();\n watchHandler()->beginCycle(!tryPartial);\n \/\/m_toolTipExpression.clear();\n WatchHandler *handler = watchHandler();\n\n QByteArray expanded = \"expanded:\" + handler->expansionRequests() + ' ';\n expanded += \"typeformats:\" + handler->typeFormatRequests() + ' ';\n expanded += \"formats:\" + handler->individualFormatRequests();\n\n QByteArray watchers;\n const QString fileName = stackHandler()->currentFrame().file;\n const QString function = stackHandler()->currentFrame().function;\n if (!fileName.isEmpty()) {\n QStringList expressions =\n DebuggerToolTipManager::instance()->treeWidgetExpressions(fileName, objectName(), function);\n const QString currentExpression = tooltipExpression();\n if (!currentExpression.isEmpty() && !expressions.contains(currentExpression))\n expressions.push_back(currentExpression);\n foreach (const QString &te, expressions) {\n if (!watchers.isEmpty())\n watchers += \"##\";\n watchers += te.toLatin1();\n watchers += '#';\n watchers += tooltipIName(te);\n }\n }\n\n QHash<QByteArray, int> watcherNames = handler->watcherNames();\n QHashIterator<QByteArray, int> it(watcherNames);\n while (it.hasNext()) {\n it.next();\n if (!watchers.isEmpty())\n watchers += \"##\";\n watchers += it.key() + \"#watch.\" + QByteArray::number(it.value());\n }\n\n QByteArray options;\n if (debuggerCore()->boolSetting(UseDebuggingHelpers))\n options += \"fancy,\";\n if (debuggerCore()->boolSetting(AutoDerefPointers))\n options += \"autoderef,\";\n if (!qgetenv(\"QTC_DEBUGGER_PYTHON_VERBOSE\").isEmpty())\n options += \"pe,\";\n if (options.isEmpty())\n options += \"defaults,\";\n if (tryPartial)\n options += \"partial,\";\n options.chop(1);\n\n QByteArray resultVar;\n if (!m_resultVarName.isEmpty())\n resultVar = \"resultvarname:\" + m_resultVarName + ' ';\n\n postCommand(\"bb options:\" + options + \" vars:\" + varList + ' '\n + resultVar + expanded + \" watchers:\" + watchers.toHex(),\n WatchUpdate, CB(handleStackFramePython), QVariant(tryPartial));\n}\n\nvoid GdbEngine::handleStackListLocalsPython(const GdbResponse &response)\n{\n PRECONDITION;\n if (response.resultClass == GdbResultDone) {\n \/\/ 44^done,data={locals=[name=\"model\",name=\"backString\",...]}\n QByteArray varList = \"vars\"; \/\/ Dummy entry, will be stripped by dumper.\n foreach (const GdbMi &child, response.data.findChild(\"locals\").children()) {\n varList.append(',');\n varList.append(child.data());\n }\n updateLocalsPython(false, varList);\n }\n}\n\nvoid GdbEngine::handleStackFramePython(const GdbResponse &response)\n{\n PRECONDITION;\n if (response.resultClass == GdbResultDone) {\n const bool partial = response.cookie.toBool();\n \/\/qDebug() << \"READING \" << (partial ? \"PARTIAL\" : \"FULL\");\n QByteArray out = response.data.findChild(\"consolestreamoutput\").data();\n while (out.endsWith(' ') || out.endsWith('\\n'))\n out.chop(1);\n \/\/qDebug() << \"SECOND CHUNK: \" << out;\n int pos = out.indexOf(\"data=\");\n if (pos != 0) {\n showMessage(_(\"DISCARDING JUNK AT BEGIN OF RESPONSE: \"\n + out.left(pos)));\n out = out.mid(pos);\n }\n GdbMi all;\n all.fromStringMultiple(out);\n \/\/qDebug() << \"ALL: \" << all.toString();\n\n GdbMi data = all.findChild(\"data\");\n QList<WatchData> list;\n foreach (const GdbMi &child, data.children()) {\n WatchData dummy;\n dummy.iname = child.findChild(\"iname\").data();\n GdbMi wname = child.findChild(\"wname\");\n if (wname.isValid()) {\n \/\/ Happens (only) for watched expressions.\n dummy.name = decodeData(wname.data(), Base64Encoded8Bit);\n dummy.exp = dummy.name.toUtf8();\n } else {\n dummy.name = _(child.findChild(\"name\").data());\n }\n \/\/qDebug() << \"CHILD: \" << child.toString();\n parseWatchData(watchHandler()->expandedINames(), dummy, child, &list);\n }\n watchHandler()->insertBulkData(list);\n \/\/for (int i = 0; i != list.size(); ++i)\n \/\/ qDebug() << \"LOCAL: \" << list.at(i).toString();\n\n#if 0\n data = all.findChild(\"bkpts\");\n if (data.isValid()) {\n BreakHandler *handler = breakHandler();\n foreach (const GdbMi &child, data.children()) {\n int bpNumber = child.findChild(\"number\").data().toInt();\n int found = handler->findBreakpoint(bpNumber);\n if (found != -1) {\n BreakpointData *bp = handler->at(found);\n GdbMi addr = child.findChild(\"addr\");\n if (addr.isValid()) {\n bp->bpAddress = child.findChild(\"addr\").data();\n bp->pending = false;\n } else {\n bp->bpAddress = \"<PENDING>\";\n bp->pending = true;\n }\n bp->bpFuncName = child.findChild(\"func\").data();\n bp->bpLineNumber = child.findChild(\"line\").data();\n bp->bpFileName = child.findChild(\"file\").data();\n bp->markerLineNumber = bp->bpLineNumber.toInt();\n bp->markerFileName = bp->bpFileName;\n \/\/ Happens with moved\/symlinked sources.\n if (!bp->fileName.isEmpty()\n && !bp->bpFileName.isEmpty()\n && bp->fileName != bp->bpFileName)\n bp->markerFileName = bp->fileName;\n } else {\n QTC_ASSERT(false, qDebug() << child.toString() << bpNumber);\n \/\/bp->bpNumber = \"<unavailable>\";\n }\n }\n handler->updateMarkers();\n }\n#endif\n\n \/\/PENDING_DEBUG(\"AFTER handleStackFrame()\");\n \/\/ FIXME: This should only be used when updateLocals() was\n \/\/ triggered by expanding an item in the view.\n if (m_pendingWatchRequests <= 0) {\n \/\/PENDING_DEBUG(\"\\n\\n .... AND TRIGGERS MODEL UPDATE\\n\");\n rebuildWatchModel();\n }\n if (!partial)\n emit stackFrameCompleted();\n } else {\n showMessage(_(\"DUMPER FAILED: \" + response.toString()));\n }\n}\n\n\/\/ Called from CoreAdapter and AttachAdapter\nvoid GdbEngine::updateAllPython()\n{\n PRECONDITION;\n \/\/PENDING_DEBUG(\"UPDATING ALL\\n\");\n QTC_ASSERT(state() == InferiorUnrunnable || state() == InferiorStopOk, \/**\/);\n reloadModulesInternal();\n postCommand(\"-stack-list-frames\", CB(handleStackListFrames),\n QVariant::fromValue<StackCookie>(StackCookie(false, true)));\n stackHandler()->setCurrentIndex(0);\n if (m_gdbAdapter->isTrkAdapter())\n m_gdbAdapter->trkReloadThreads();\n else\n postCommand(\"-thread-list-ids\", CB(handleThreadListIds), 0);\n reloadRegisters();\n updateLocals();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nCopyright The University of Auckland\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Qwt plugin\n\/\/==============================================================================\n\n#include \"qwtplugin.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Qwt {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC QwtPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to access <a href=\\\"http:\/\/qwt.sourceforge.net\/\\\">Qwt<\/a> 6.1.2+.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour accéder <a href=\\\"http:\/\/qwt.sourceforge.net\/\\\">Qwt<\/a> 6.1.2+.\"));\n\n return new PluginInfo(\"Third-party\", false, false,\n QStringList(),\n descriptions);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Qwt\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Qwt library: some work on upgrading to version 6.1.3 (#1002).<commit_after>\/*******************************************************************************\n\nCopyright The University of Auckland\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Qwt plugin\n\/\/==============================================================================\n\n#include \"qwtplugin.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Qwt {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC QwtPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to access <a href=\\\"http:\/\/qwt.sourceforge.net\/\\\">Qwt<\/a> 6.1.3.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour accéder <a href=\\\"http:\/\/qwt.sourceforge.net\/\\\">Qwt<\/a> 6.1.3.\"));\n\n return new PluginInfo(\"Third-party\", false, false,\n QStringList(),\n descriptions);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Qwt\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/profiling\/memory\/bookkeeping.h\"\n\n#include \"test\/gtest_and_gmock.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nusing ::testing::AnyOf;\nusing ::testing::Eq;\n\nstd::vector<FrameData> stack() {\n std::vector<FrameData> res;\n\n unwindstack::FrameData data{};\n data.function_name = \"fun1\";\n data.map_name = \"map1\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n data = {};\n data.function_name = \"fun2\";\n data.map_name = \"map2\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n return res;\n}\n\nstd::vector<FrameData> stack2() {\n std::vector<FrameData> res;\n unwindstack::FrameData data{};\n data.function_name = \"fun1\";\n data.map_name = \"map1\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n data = {};\n data.function_name = \"fun3\";\n data.map_name = \"map3\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n return res;\n}\n\nTEST(BookkeepingTest, Basic) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 2, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 2u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n hd.RecordFree(2, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n hd.RecordFree(1, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 0u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n}\n\nTEST(BookkeepingTest, Max) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, true);\n\n hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 2, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordFree(2, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordFree(1, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.max_timestamp(), 200u);\n ASSERT_EQ(hd.GetMaxForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetMaxForTesting(stack2()), 2u);\n}\n\nTEST(BookkeepingTest, TwoHeapTrackers) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n {\n HeapTracker hd2(&c, false);\n\n hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);\n hd2.RecordMalloc(stack(), 2, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd2.GetSizeForTesting(stack()), 2u);\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n }\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n}\n\nTEST(BookkeepingTest, ReplaceAlloc) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 1, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n EXPECT_EQ(hd.GetSizeForTesting(stack()), 0u);\n EXPECT_EQ(hd.GetSizeForTesting(stack2()), 2u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n}\n\nTEST(BookkeepingTest, OutOfOrder) {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 1, 5, 5, 2, 2);\n hd.RecordMalloc(stack2(), 1, 2, 2, 1, 1);\n EXPECT_EQ(hd.GetSizeForTesting(stack()), 5u);\n EXPECT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n}\n\nTEST(BookkeepingTest, ManyAllocations) {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n std::vector<std::pair<uint64_t, uint64_t>> batch_frees;\n\n for (uint64_t sequence_number = 1; sequence_number < 1000;) {\n if (batch_frees.size() > 10) {\n for (const auto& p : batch_frees)\n hd.RecordFree(p.first, p.second, 100 * p.second);\n batch_frees.clear();\n }\n\n uint64_t addr = sequence_number;\n hd.RecordMalloc(stack(), addr, 5, 5, sequence_number, sequence_number);\n sequence_number++;\n batch_frees.emplace_back(addr, sequence_number++);\n ASSERT_THAT(hd.GetSizeForTesting(stack()), AnyOf(Eq(0u), Eq(5u)));\n }\n}\n\nTEST(BookkeepingTest, ArbitraryOrder) {\n std::vector<FrameData> s = stack();\n std::vector<FrameData> s2 = stack2();\n\n enum OperationType { kAlloc, kFree, kDump };\n\n struct Operation {\n uint64_t sequence_number;\n OperationType type;\n uint64_t address;\n uint64_t bytes; \/\/ 0 for free\n const std::vector<FrameData>* stack; \/\/ nullptr for free\n\n \/\/ For std::next_permutation.\n bool operator<(const Operation& other) const {\n return sequence_number < other.sequence_number;\n }\n } operations[] = {\n {1, kAlloc, 1, 5, &s}, \/\/\n {2, kAlloc, 1, 10, &s2}, \/\/\n {3, kFree, 1, 0, nullptr}, \/\/\n {4, kFree, 2, 0, nullptr}, \/\/\n {5, kFree, 3, 0, nullptr}, \/\/\n {6, kAlloc, 3, 2, &s}, \/\/\n {7, kAlloc, 4, 3, &s2}, \/\/\n {0, kDump, 0, 0, nullptr}, \/\/\n };\n\n uint64_t s_size = 2;\n uint64_t s2_size = 3;\n\n do {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n for (auto it = std::begin(operations); it != std::end(operations); ++it) {\n const Operation& operation = *it;\n\n if (operation.type == OperationType::kFree) {\n hd.RecordFree(operation.address, operation.sequence_number,\n 100 * operation.sequence_number);\n } else if (operation.type == OperationType::kAlloc) {\n hd.RecordMalloc(*operation.stack, operation.address, operation.bytes,\n operation.bytes, operation.sequence_number,\n 100 * operation.sequence_number);\n } else {\n hd.GetCallstackAllocations(\n [](const HeapTracker::CallstackAllocations&) {});\n }\n }\n ASSERT_EQ(hd.GetSizeForTesting(s), s_size);\n ASSERT_EQ(hd.GetSizeForTesting(s2), s2_size);\n } while (std::next_permutation(std::begin(operations), std::end(operations)));\n}\n\n} \/\/ namespace\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n<commit_msg>Add bookkeeping test for empty callstack.<commit_after>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/profiling\/memory\/bookkeeping.h\"\n\n#include \"test\/gtest_and_gmock.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nusing ::testing::AnyOf;\nusing ::testing::Eq;\n\nstd::vector<FrameData> stack() {\n std::vector<FrameData> res;\n\n unwindstack::FrameData data{};\n data.function_name = \"fun1\";\n data.map_name = \"map1\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n data = {};\n data.function_name = \"fun2\";\n data.map_name = \"map2\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n return res;\n}\n\nstd::vector<FrameData> stack2() {\n std::vector<FrameData> res;\n unwindstack::FrameData data{};\n data.function_name = \"fun1\";\n data.map_name = \"map1\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n data = {};\n data.function_name = \"fun3\";\n data.map_name = \"map3\";\n res.emplace_back(std::move(data), \"dummy_buildid\");\n return res;\n}\n\nTEST(BookkeepingTest, EmptyStack) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc({}, 0x1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordFree(0x1, sequence_number, 100 * sequence_number);\n hd.GetCallstackAllocations([](const HeapTracker::CallstackAllocations&) {});\n}\n\nTEST(BookkeepingTest, Basic) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 0x2, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 2u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n hd.RecordFree(0x2, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n hd.RecordFree(0x1, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 0u);\n ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n}\n\nTEST(BookkeepingTest, Max) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, true);\n\n hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 0x2, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordFree(0x2, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordFree(0x1, sequence_number, 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd.max_timestamp(), 200u);\n ASSERT_EQ(hd.GetMaxForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetMaxForTesting(stack2()), 2u);\n}\n\nTEST(BookkeepingTest, TwoHeapTrackers) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n {\n HeapTracker hd2(&c, false);\n\n hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);\n hd2.RecordMalloc(stack(), 0x2, 2, 2, sequence_number,\n 100 * sequence_number);\n sequence_number++;\n ASSERT_EQ(hd2.GetSizeForTesting(stack()), 2u);\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n }\n ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);\n}\n\nTEST(BookkeepingTest, ReplaceAlloc) {\n uint64_t sequence_number = 1;\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);\n sequence_number++;\n hd.RecordMalloc(stack2(), 0x1, 2, 2, sequence_number, 100 * sequence_number);\n sequence_number++;\n EXPECT_EQ(hd.GetSizeForTesting(stack()), 0u);\n EXPECT_EQ(hd.GetSizeForTesting(stack2()), 2u);\n ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));\n}\n\nTEST(BookkeepingTest, OutOfOrder) {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n hd.RecordMalloc(stack(), 0x1, 5, 5, 2, 2);\n hd.RecordMalloc(stack2(), 0x1, 2, 2, 1, 1);\n EXPECT_EQ(hd.GetSizeForTesting(stack()), 5u);\n EXPECT_EQ(hd.GetSizeForTesting(stack2()), 0u);\n}\n\nTEST(BookkeepingTest, ManyAllocations) {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n std::vector<std::pair<uint64_t, uint64_t>> batch_frees;\n\n for (uint64_t sequence_number = 1; sequence_number < 1000;) {\n if (batch_frees.size() > 10) {\n for (const auto& p : batch_frees)\n hd.RecordFree(p.first, p.second, 100 * p.second);\n batch_frees.clear();\n }\n\n uint64_t addr = sequence_number;\n hd.RecordMalloc(stack(), addr, 5, 5, sequence_number, sequence_number);\n sequence_number++;\n batch_frees.emplace_back(addr, sequence_number++);\n ASSERT_THAT(hd.GetSizeForTesting(stack()), AnyOf(Eq(0u), Eq(5u)));\n }\n}\n\nTEST(BookkeepingTest, ArbitraryOrder) {\n std::vector<FrameData> s = stack();\n std::vector<FrameData> s2 = stack2();\n\n enum OperationType { kAlloc, kFree, kDump };\n\n struct Operation {\n uint64_t sequence_number;\n OperationType type;\n uint64_t address;\n uint64_t bytes; \/\/ 0 for free\n const std::vector<FrameData>* stack; \/\/ nullptr for free\n\n \/\/ For std::next_permutation.\n bool operator<(const Operation& other) const {\n return sequence_number < other.sequence_number;\n }\n } operations[] = {\n {1, kAlloc, 0x1, 5, &s}, \/\/\n {2, kAlloc, 0x1, 10, &s2}, \/\/\n {3, kFree, 0x01, 0, nullptr}, \/\/\n {4, kFree, 0x02, 0, nullptr}, \/\/\n {5, kFree, 0x03, 0, nullptr}, \/\/\n {6, kAlloc, 0x3, 2, &s}, \/\/\n {7, kAlloc, 0x4, 3, &s2}, \/\/\n {0, kDump, 0x00, 0, nullptr}, \/\/\n };\n\n uint64_t s_size = 2;\n uint64_t s2_size = 3;\n\n do {\n GlobalCallstackTrie c;\n HeapTracker hd(&c, false);\n\n for (auto it = std::begin(operations); it != std::end(operations); ++it) {\n const Operation& operation = *it;\n\n if (operation.type == OperationType::kFree) {\n hd.RecordFree(operation.address, operation.sequence_number,\n 100 * operation.sequence_number);\n } else if (operation.type == OperationType::kAlloc) {\n hd.RecordMalloc(*operation.stack, operation.address, operation.bytes,\n operation.bytes, operation.sequence_number,\n 100 * operation.sequence_number);\n } else {\n hd.GetCallstackAllocations(\n [](const HeapTracker::CallstackAllocations&) {});\n }\n }\n ASSERT_EQ(hd.GetSizeForTesting(s), s_size);\n ASSERT_EQ(hd.GetSizeForTesting(s2), s2_size);\n } while (std::next_permutation(std::begin(operations), std::end(operations)));\n}\n\n} \/\/ namespace\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2015 ANON authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"sproc_mgr.h\"\n#include \"log.h\"\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\nchar base_path[4096];\nchar cmd_path[4096];\n\n\/\/ hard-coded for now\nconst char* exe_name;\n\nstatic void validate_command_file()\n{\n struct stat st;\n if (stat(cmd_path, &st) != 0) {\n if (errno == ENOENT) {\n if (mkfifo(cmd_path, 0666) != 0)\n do_error(\"mkfifo(\\\"\" << &cmd_path[0] << \"\\\", 0666\");\n else\n return;\n } else\n do_error(\"stat(\\\"\" << &cmd_path[0] << \"\\\", &st)\");\n }\n \n if (S_ISFIFO(st.st_mode))\n return;\n \n if (S_ISREG(st.st_mode)) {\n if (unlink(cmd_path) != 0)\n do_error(\"unlink(\\\"\" << &cmd_path[0] << \"\\\")\");\n validate_command_file();\n } else if (S_ISDIR(st.st_mode)) {\n anon_log(\"\\\"\" << &cmd_path[0] << \"\\\" is a directory and must be manually deleted for this program to run\");\n exit(1);\n }\n \n anon_log(\"\\\"\" << &cmd_path[0] << \"\\\" is an unknown file type and must be manually deleted for this program to run\");\n exit(1);\n}\n\nstatic void write_all(int fd, const char* data)\n{\n size_t len = strlen(data);\n size_t written = 0;\n while (written < len)\n written += ::write(fd,&data[written],len-written);\n}\n\nstatic bool process_command(const std::string& cmd)\n{\n std::ostringstream reply;\n bool ret = true;\n bool show_help = false;\n \n try {\n if (cmd == \"help\") {\n \n show_help = true;\n \n } else if (cmd == \"quit\") {\n \n reply << \"\\nquitting, bye\\n\\n\";\n ret = false;\n \n } else if (cmd == \"list_exes\") {\n \n list_exes(base_path, exe_name, reply);\n \n } else if (cmd.find(\"start\") == 0) {\n \n const char* p = &cmd.c_str()[5];\n while (*p && ((*p == ' ') || (*p == '\\t')))\n ++p;\n std::string full_path = std::string(base_path) + p;\n \n \/\/ hard-coded for now...\n std::vector<std::string> args;\n args.push_back(\"-cert_verify_dir\");\n args.push_back(\"\/etc\/ssl\/certs\");\n args.push_back(\"-server_cert\");\n args.push_back(\".\/secrets\/srv_cert.pem\");\n args.push_back(\"-server_key\");\n args.push_back(\".\/secrets\/srv_key.pem\");\n\n start_server(full_path.c_str(), args);\n reply << \"\\n\" << p << \" now running in process \" << current_server_pid() << \"\\n\\n\";\n \n } else if (cmd == \"current_exe\") {\n \n if (current_server_pid())\n reply << \"\\ncurrent executable: \" << current_exe_name() << \", in process id: \" << current_server_pid() << \"\\n\\n\";\n else\n reply << \"\\nno executable currently running\\n\\n\";\n \n } else {\n \n reply << \"ignoring unknown command, you sent:\\n\" << cmd << \"\\n\\n\";\n show_help = true;\n \n }\n } catch (const std::exception& err) {\n reply << \"\\n\\nerror: \" << err.what() << \"\\n\\n\";\n } catch (...) {\n reply << \"\\n\\nunknown error\\n\\n\";\n }\n \n if (show_help) {\n reply << \"available commands:\\n\\n\";\n reply << \"help\\n\";\n reply << \" shows this menu\\n\\n\";\n reply << \"quit\\n\";\n reply << \" quits the server application and all of its child processes\\n\\n\";\n reply << \"list_exes\\n\";\n reply << \" list the set of available executable images to run, along with their\\n\";\n reply << \" sha1 checksum values\\n\\n\";\n reply << \"start <executable name>\\n\";\n reply << \" starts the specified process running. If there is already a process\\n\";\n reply << \" running it will perform a \\\"hot-swap\\\" of the process, stopping the\\n\";\n reply << \" older one and replacing it with the newer one\\n\\n\";\n reply << \"current_exe\\n\";\n reply << \" returns the file name and process id of the currently running executable\\n\";\n reply << \" if there is one, otherwise tells you that no process is currently running\\n\\n\";\n }\n\n validate_command_file();\n int fd = open(cmd_path, O_WRONLY | O_CLOEXEC);\n if (fd != -1) {\n write_all(fd, reply.str().c_str());\n close(fd);\n }\n \n return ret;\n}\n\n\nextern \"C\" int main(int argc, char** argv)\n{\n if (argc != 3) {\n fprintf(stderr,\"usage: epoxy <port> <exe_name>\\n\");\n return 1;\n }\n \n size_t sz = strlen(argv[0]);\n if (sz > sizeof(cmd_path) - 20) {\n fprintf(stderr,\"path to epoxy executable too long\\n\");\n return 1;\n }\n \n memcpy(base_path, argv[0], sz+1);\n char* p = &base_path[sz+1];\n while (p > &base_path[0] && *(p-1) != '\/')\n --p;\n *p = 0;\n \n const char* cmd_file_name = \".epoxy_cmd\";\n \n strcpy(cmd_path, base_path);\n strcat(cmd_path, cmd_file_name);\n \n int port = atoi(argv[1]);\n exe_name = argv[2];\n \n try {\n sproc_mgr_init(port);\n } catch (const std::exception& err) {\n anon_log(\"unable to initialize: \" << err.what());\n return 1;\n } catch (...) {\n anon_log(\"unable to initialize\");\n return 1;\n }\n \n anon_log(\"epoxy bound to network port \" << port);\n anon_log(\"listening for commands on file \" << &cmd_path[0]);\n \n int exitcode = 0;\n char cmd_buf[4096];\n\n validate_command_file();\n\n while (true) {\n\n int fd = open(cmd_path, O_RDONLY | O_CLOEXEC);\n if (fd < 0)\n do_error(\"open(\\\"\" << &cmd_path[0] << \"\\\", O_RDONLY | O_CLOEXEC)\");\n auto bytes = ::read(fd, &cmd_buf[0], sizeof(cmd_buf));\n close(fd);\n if (bytes == sizeof(cmd_buf)) {\n cmd_buf[20] = 0;\n anon_log(\"command too big, ignoring - starts with: \\\"\" << &cmd_buf[0] << \"...\\\"\");\n }\n else {\n while (bytes > 0 && cmd_buf[bytes-1] == '\\n')\n --bytes;\n if (bytes) {\n bool keep_going = true;\n try {\n keep_going = process_command(std::string(&cmd_buf[0], 0, bytes));\n }\n catch(...)\n {}\n if (!keep_going)\n break;\n }\n }\n \n }\n \n unlink(cmd_path);\n sproc_mgr_term();\n \n anon_log(\"epoxy process exiting\");\n return exitcode;\n\n}\n\n\n<commit_msg>minor bug fix<commit_after>\/*\n Copyright (c) 2015 ANON authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"sproc_mgr.h\"\n#include \"log.h\"\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\nchar base_path[4096];\nchar cmd_path[4096];\n\n\/\/ hard-coded for now\nconst char* exe_name;\n\nstatic void validate_command_file()\n{\n struct stat st;\n if (stat(cmd_path, &st) != 0) {\n if (errno == ENOENT) {\n if (mkfifo(cmd_path, 0666) != 0)\n do_error(\"mkfifo(\\\"\" << &cmd_path[0] << \"\\\", 0666\");\n else\n return;\n } else\n do_error(\"stat(\\\"\" << &cmd_path[0] << \"\\\", &st)\");\n }\n \n if (S_ISFIFO(st.st_mode))\n return;\n \n if (S_ISREG(st.st_mode)) {\n if (unlink(cmd_path) != 0)\n do_error(\"unlink(\\\"\" << &cmd_path[0] << \"\\\")\");\n validate_command_file();\n return;\n } else if (S_ISDIR(st.st_mode)) {\n anon_log(\"\\\"\" << &cmd_path[0] << \"\\\" is a directory and must be manually deleted for this program to run\");\n exit(1);\n }\n \n anon_log(\"\\\"\" << &cmd_path[0] << \"\\\" is an unknown file type and must be manually deleted for this program to run\");\n exit(1);\n}\n\nstatic void write_all(int fd, const char* data)\n{\n size_t len = strlen(data);\n size_t written = 0;\n while (written < len)\n written += ::write(fd,&data[written],len-written);\n}\n\nstatic bool process_command(const std::string& cmd)\n{\n std::ostringstream reply;\n bool ret = true;\n bool show_help = false;\n \n try {\n if (cmd == \"help\") {\n \n show_help = true;\n \n } else if (cmd == \"quit\") {\n \n reply << \"\\nquitting, bye\\n\\n\";\n ret = false;\n \n } else if (cmd == \"list_exes\") {\n \n list_exes(base_path, exe_name, reply);\n \n } else if (cmd.find(\"start\") == 0) {\n \n const char* p = &cmd.c_str()[5];\n while (*p && ((*p == ' ') || (*p == '\\t')))\n ++p;\n std::string full_path = std::string(base_path) + p;\n \n \/\/ hard-coded for now...\n std::vector<std::string> args;\n args.push_back(\"-cert_verify_dir\");\n args.push_back(\"\/etc\/ssl\/certs\");\n args.push_back(\"-server_cert\");\n args.push_back(\".\/secrets\/srv_cert.pem\");\n args.push_back(\"-server_key\");\n args.push_back(\".\/secrets\/srv_key.pem\");\n\n start_server(full_path.c_str(), args);\n reply << \"\\n\" << p << \" now running in process \" << current_server_pid() << \"\\n\\n\";\n \n } else if (cmd == \"current_exe\") {\n \n if (current_server_pid())\n reply << \"\\ncurrent executable: \" << current_exe_name() << \", in process id: \" << current_server_pid() << \"\\n\\n\";\n else\n reply << \"\\nno executable currently running\\n\\n\";\n \n } else {\n \n reply << \"ignoring unknown command, you sent:\\n\" << cmd << \"\\n\\n\";\n show_help = true;\n \n }\n } catch (const std::exception& err) {\n reply << \"\\n\\nerror: \" << err.what() << \"\\n\\n\";\n } catch (...) {\n reply << \"\\n\\nunknown error\\n\\n\";\n }\n \n if (show_help) {\n reply << \"available commands:\\n\\n\";\n reply << \"help\\n\";\n reply << \" shows this menu\\n\\n\";\n reply << \"quit\\n\";\n reply << \" quits the server application and all of its child processes\\n\\n\";\n reply << \"list_exes\\n\";\n reply << \" list the set of available executable images to run, along with their\\n\";\n reply << \" sha1 checksum values\\n\\n\";\n reply << \"start <executable name>\\n\";\n reply << \" starts the specified process running. If there is already a process\\n\";\n reply << \" running it will perform a \\\"hot-swap\\\" of the process, stopping the\\n\";\n reply << \" older one and replacing it with the newer one\\n\\n\";\n reply << \"current_exe\\n\";\n reply << \" returns the file name and process id of the currently running executable\\n\";\n reply << \" if there is one, otherwise tells you that no process is currently running\\n\\n\";\n }\n\n validate_command_file();\n int fd = open(cmd_path, O_WRONLY | O_CLOEXEC);\n if (fd != -1) {\n write_all(fd, reply.str().c_str());\n close(fd);\n }\n \n return ret;\n}\n\n\nextern \"C\" int main(int argc, char** argv)\n{\n if (argc != 3) {\n fprintf(stderr,\"usage: epoxy <port> <exe_name>\\n\");\n return 1;\n }\n \n size_t sz = strlen(argv[0]);\n if (sz > sizeof(cmd_path) - 20) {\n fprintf(stderr,\"path to epoxy executable too long\\n\");\n return 1;\n }\n \n memcpy(base_path, argv[0], sz+1);\n char* p = &base_path[sz+1];\n while (p > &base_path[0] && *(p-1) != '\/')\n --p;\n *p = 0;\n \n const char* cmd_file_name = \".epoxy_cmd\";\n \n strcpy(cmd_path, base_path);\n strcat(cmd_path, cmd_file_name);\n \n int port = atoi(argv[1]);\n exe_name = argv[2];\n \n try {\n sproc_mgr_init(port);\n } catch (const std::exception& err) {\n anon_log(\"unable to initialize: \" << err.what());\n return 1;\n } catch (...) {\n anon_log(\"unable to initialize\");\n return 1;\n }\n \n anon_log(\"epoxy bound to network port \" << port);\n anon_log(\"listening for commands on file \" << &cmd_path[0]);\n \n int exitcode = 0;\n char cmd_buf[4096];\n\n validate_command_file();\n\n while (true) {\n\n int fd = open(cmd_path, O_RDONLY | O_CLOEXEC);\n if (fd < 0)\n do_error(\"open(\\\"\" << &cmd_path[0] << \"\\\", O_RDONLY | O_CLOEXEC)\");\n auto bytes = ::read(fd, &cmd_buf[0], sizeof(cmd_buf));\n close(fd);\n if (bytes == sizeof(cmd_buf)) {\n cmd_buf[20] = 0;\n anon_log(\"command too big, ignoring - starts with: \\\"\" << &cmd_buf[0] << \"...\\\"\");\n }\n else {\n while (bytes > 0 && cmd_buf[bytes-1] == '\\n')\n --bytes;\n if (bytes) {\n bool keep_going = true;\n try {\n keep_going = process_command(std::string(&cmd_buf[0], 0, bytes));\n }\n catch(...)\n {}\n if (!keep_going)\n break;\n }\n }\n \n }\n \n unlink(cmd_path);\n sproc_mgr_term();\n \n anon_log(\"epoxy process exiting\");\n return exitcode;\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <cbor++\/CBORValue.h>\n\n#include <cmath>\n\n#include \"util.h\"\n\nunion uint_conv_u{\n std::uint8_t byte[8];\n std::uint8_t i8;\n std::uint16_t i16;\n std::uint32_t i32;\n std::uint64_t i64;\n} uint_conv;\n\nstd::uint64_t getInteger(const std::uint8_t * bytes, std::uint8_t count)\n{\n for(int i = 0; i < count; i++){\n \/\/printf(\"Setting byte %d to 0x%02x\\n\", i, bytes[i]);\n uint_conv.byte[i] = bytes[i];\n }\n\n switch(count){\n case 1:\n return uint_conv.i8;\n break;\n case 2:\n return uint_conv.i16;\n break;\n case 4:\n return uint_conv.i32;\n break;\n case 8:\n return uint_conv.i64;\n break;\n }\n return 0;\n}\n\n\/*************************\n *\n * Constructors\n *\n *************************\/\nCBORValue::CBORValue(const std::uint8_t * bytes)\n{\n std::uint8_t typeByte = *bytes;\n\n std::uint8_t mt = getMajorType(typeByte);\n std::uint8_t ai = getAdditionalInfo(typeByte);\n\n switch(mt) {\n case CBORType_PInt:\n type = CBORType_PInt;\n isNegative = false;\n if(ai <= 23) {\n integerValue = ai;\n } else {\n const std::uint8_t * data = bytes + sizeof(std::uint8_t);\n std::uint8_t count = pow(2,ai-24);\n integerValue = getInteger(data, count);\n }\n break;\n case CBORType_NInt:\n type = CBORType_NInt;\n isNegative = true;\n if(ai <= 23) {\n integerValue = ai;\n } else {\n const std::uint8_t * data = bytes + sizeof(std::uint8_t);\n std::uint8_t count = pow(2,ai-24);\n integerValue = getInteger(data, count);\n }\n break;\n case CBORType_BString:\n case CBORType_UString:\n case CBORType_Array:\n case CBORType_Map:\n default:\n break;\n }\n}\n\n\/*************************\n *\n * Type Checks\n *\n *************************\/\nbool CBORValue::isType(CBORType t) const\n{\n return type == t;\n}\n\nbool CBORValue::isPosInteger() const\n{\n return isType(CBORType_PInt);\n}\n\nbool CBORValue::isNegInteger() const\n{\n return isType(CBORType_NInt);\n}\n\n\/*************************\n *\n * Value Accessors\n *\n *************************\/\nstd::uint64_t CBORValue::getPosInteger() const\n{\n return integerValue;\n}\n\nstd::int64_t CBORValue::getNegInteger() const\n{\n return -1 - integerValue;\n}\n<commit_msg>Added inital byte string code<commit_after>#include <cbor++\/CBORValue.h>\n\n#include <cmath>\n\n#include \"util.h\"\n\nunion uint_conv_u{\n std::uint8_t byte[8];\n std::uint8_t i8;\n std::uint16_t i16;\n std::uint32_t i32;\n std::uint64_t i64;\n} uint_conv;\n\nstd::uint64_t getInteger(const std::uint8_t * bytes, std::uint8_t count)\n{\n for(int i = 0; i < count; i++){\n \/\/printf(\"Setting byte %d to 0x%02x\\n\", i, bytes[i]);\n uint_conv.byte[i] = bytes[i];\n }\n\n switch(count){\n case 1:\n return uint_conv.i8;\n break;\n case 2:\n return uint_conv.i16;\n break;\n case 4:\n return uint_conv.i32;\n break;\n case 8:\n return uint_conv.i64;\n break;\n }\n return 0;\n}\n\n\/*************************\n *\n * Constructors\n *\n *************************\/\nCBORValue::CBORValue(const std::uint8_t * bytes)\n{\n std::uint8_t typeByte = *bytes;\n\n std::uint8_t mt = getMajorType(typeByte);\n std::uint8_t ai = getAdditionalInfo(typeByte);\n\n switch(mt) {\n case CBORType_PInt:\n type = CBORType_PInt;\n isNegative = false;\n if(ai <= 23) {\n integerValue = ai;\n } else {\n const std::uint8_t * data = bytes + sizeof(std::uint8_t);\n std::uint8_t count = pow(2,ai-24);\n integerValue = getInteger(data, count);\n }\n break;\n case CBORType_NInt:\n type = CBORType_NInt;\n isNegative = true;\n if(ai <= 23) {\n integerValue = ai;\n } else {\n const std::uint8_t * data = bytes + sizeof(std::uint8_t);\n std::uint8_t count = pow(2,ai-24);\n integerValue = getInteger(data, count);\n }\n break;\n case CBORType_BString: {\n type = CBORType_BString;\n size_t strSize = ai;\n const std::uint8_t * data = bytes;\n if (strSize > 23 && strSize != 31) {\n data = data + sizeof(std::uint8_t);\n std::uint8_t count = pow(2,ai-24);\n strSize = getInteger(data, count);\n data = data + (sizeof(std::uint8_t)*count);\n }\n stringValue = std::string((const char *)data, strSize);\n break;\n }\n case CBORType_UString:\n case CBORType_Array:\n case CBORType_Map:\n default:\n break;\n }\n}\n\n\/*************************\n *\n * Type Checks\n *\n *************************\/\nbool CBORValue::isType(CBORType t) const\n{\n return type == t;\n}\n\nbool CBORValue::isPosInteger() const\n{\n return isType(CBORType_PInt);\n}\n\nbool CBORValue::isNegInteger() const\n{\n return isType(CBORType_NInt);\n}\n\nbool CBORValue::isByteString() const\n{\n return isType(CBORType_BString);\n}\n\n\/*************************\n *\n * Value Accessors\n *\n *************************\/\nstd::uint64_t CBORValue::getPosInteger() const\n{\n return integerValue;\n}\n\nstd::int64_t CBORValue::getNegInteger() const\n{\n return -1 - integerValue;\n}\n\nconst std::string CBORValue::getByteString() const\n{\n return stringValue;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <CReadLine.h>\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\nusing std::string;\nusing std::vector;\n\nCReadLine *CReadLine::current_ = NULL;\n\nCReadLine::\nCReadLine() :\n prompt_(\"> \"), name_(\"readline\"), eof_(false), history_(NULL)\n{\n rl_readline_name = name_.c_str();\n\n rl_catch_signals = 0;\n\n rl_bind_key('\\t' , (int (*)(int, int)) rlCompleteLine);\n rl_bind_key('\\033', (int (*)(int, int)) rlCompleteLine);\n\n rl_set_key(\"\\\\C-d\", (int (*)(int, int)) rlShowComplete, rl_get_keymap());\n\n#ifdef OS_WIN\n rl_set_key(\"\\033[0A\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[0B\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[0C\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[0D\", rl_named_function(\"backward-char\"), rl_get_keymap());\n#endif\n\n rl_set_key(\"\\033[A\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[B\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[C\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[D\", rl_named_function(\"backward-char\"), rl_get_keymap());\n\n rl_set_key(\"\\033[OA\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[OB\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[OC\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[OD\", rl_named_function(\"backward-char\"), rl_get_keymap());\n}\n\nvoid\nCReadLine::\nsetAutoHistory(bool flag)\n{\n delete history_;\n\n if (flag)\n history_ = new CHistory();\n else\n history_ = NULL;\n}\n\nvoid\nCReadLine::\nenableTimoutHook()\n{\n rl_event_hook = rlEventHook;\n}\n\nvoid\nCReadLine::\ndisableTimoutHook()\n{\n rl_event_hook = NULL;\n}\n\nstring\nCReadLine::\nreadLine()\n{\n current_ = this;\n\n char *p = ::readline((char *) prompt_.c_str());\n\n if (p == NULL) {\n eof_ = true;\n\n return \"\";\n }\n\n if (history_ != NULL)\n addHistory(p);\n\n return p;\n}\n\nvoid\nCReadLine::\nsetPrompt(const string &prompt)\n{\n prompt_ = prompt;\n}\n\nvoid\nCReadLine::\nsetName(const string &name)\n{\n name_ = name;\n\n rl_readline_name = name_.c_str();\n}\n\nbool\nCReadLine::\ngetPrevCommand(string &line)\n{\n if (history_ != NULL)\n return history_->getPrevCommand(line);\n else\n return false;\n}\n\nbool\nCReadLine::\ngetNextCommand(string &line)\n{\n if (history_ != NULL)\n return history_->getNextCommand(line);\n else\n return false;\n}\n\nint\nCReadLine::\nrlCompleteLine(int, int)\n{\n if (rl_point != rl_end)\n return 0;\n\n string line = current_->getBuffer();\n\n string line1;\n\n if (current_->completeLine(line, line1))\n current_->setBuffer(line + line1);\n\n return 0;\n}\n\nint\nCReadLine::\nrlShowComplete(int, int)\n{\n if (rl_point != rl_end) {\n rl_end = rl_point;\n\n rl_line_buffer[rl_end] = '\\0';\n }\n else {\n string line = current_->getBuffer();\n\n if (current_->showComplete(line))\n rl_forced_update_display();\n }\n\n return 0;\n}\n\nint\nCReadLine::\nrlPrevCommand(int, int)\n{\n string line;\n\n if (current_->getPrevCommand(line))\n current_->setBuffer(line);\n\n return 0;\n}\n\nint\nCReadLine::\nrlNextCommand(int, int)\n{\n string line;\n\n if (! current_->getNextCommand(line))\n line = \"\";\n\n current_->setBuffer(line);\n\n return 0;\n}\n\nint\nCReadLine::\nrlEventHook()\n{\n current_->timeout();\n\n return 1;\n}\n\nstring\nCReadLine::\ngetBuffer() const\n{\n return rl_line_buffer;\n}\n\nvoid\nCReadLine::\nsetBuffer(const string &buffer)\n{\n rl_extend_line_buffer(buffer.size() + 1);\n\n strcpy(rl_line_buffer, buffer.c_str());\n\n rl_end = buffer.size();\n\n rl_point = rl_end;\n}\n\nvoid\nCReadLine::\naddHistory(const string &line)\n{\n if (history_ == NULL)\n history_ = new CHistory;\n\n history_->addCommand(line);\n}\n\nvoid\nCReadLine::\ngetHistoryEntries(vector<CReadLineHistoryEntry> &entries)\n{\n HIST_ENTRY **hist_entries = history_list();\n\n for (int i = 0; hist_entries != NULL && hist_entries[i] != NULL; i++) {\n CReadLineHistoryEntry entry(i + history_base, hist_entries[i]->line);\n\n entries.push_back(entry);\n }\n}\n\nvoid\nCReadLine::\nbeep()\n{\n rl_ding();\n}\n\nvoid\nCReadLine::\ninterrupt()\n{\n rl_crlf();\n\n setBuffer(\"\");\n\n rl_forced_update_display();\n}\n<commit_msg>new files<commit_after>#include <CReadLine.h>\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\nCReadLine *CReadLine::current_ = NULL;\n\nCReadLine::\nCReadLine() :\n prompt_(\"> \"), name_(\"readline\"), eof_(false), history_(NULL)\n{\n rl_readline_name = name_.c_str();\n\n rl_catch_signals = 0;\n\n rl_bind_key('\\t' , (int (*)(int, int)) rlCompleteLine);\n rl_bind_key('\\033', (int (*)(int, int)) rlCompleteLine);\n\n rl_set_key(\"\\\\C-d\", (int (*)(int, int)) rlShowComplete, rl_get_keymap());\n\n#ifdef OS_WIN\n rl_set_key(\"\\033[0A\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[0B\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[0C\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[0D\", rl_named_function(\"backward-char\"), rl_get_keymap());\n#endif\n\n rl_set_key(\"\\033[A\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[B\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[C\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[D\", rl_named_function(\"backward-char\"), rl_get_keymap());\n\n rl_set_key(\"\\033[OA\", (int (*)(int, int)) rlPrevCommand , rl_get_keymap());\n rl_set_key(\"\\033[OB\", (int (*)(int, int)) rlNextCommand , rl_get_keymap());\n rl_set_key(\"\\033[OC\", rl_named_function(\"forward-char\" ), rl_get_keymap());\n rl_set_key(\"\\033[OD\", rl_named_function(\"backward-char\"), rl_get_keymap());\n}\n\nvoid\nCReadLine::\nsetAutoHistory(bool flag)\n{\n delete history_;\n\n if (flag)\n history_ = new CHistory();\n else\n history_ = NULL;\n}\n\nvoid\nCReadLine::\nenableTimoutHook()\n{\n rl_event_hook = rlEventHook;\n}\n\nvoid\nCReadLine::\ndisableTimoutHook()\n{\n rl_event_hook = NULL;\n}\n\nstd::string\nCReadLine::\nreadLine()\n{\n current_ = this;\n\n char *p = ::readline((char *) prompt_.c_str());\n\n if (p == NULL) {\n eof_ = true;\n\n return \"\";\n }\n\n if (history_ != NULL)\n addHistory(p);\n\n return p;\n}\n\nvoid\nCReadLine::\nsetPrompt(const std::string &prompt)\n{\n prompt_ = prompt;\n}\n\nvoid\nCReadLine::\nsetName(const std::string &name)\n{\n name_ = name;\n\n rl_readline_name = name_.c_str();\n}\n\nbool\nCReadLine::\ngetPrevCommand(std::string &line)\n{\n if (history_ != NULL)\n return history_->getPrevCommand(line);\n else\n return false;\n}\n\nbool\nCReadLine::\ngetNextCommand(std::string &line)\n{\n if (history_ != NULL)\n return history_->getNextCommand(line);\n else\n return false;\n}\n\nint\nCReadLine::\nrlCompleteLine(int, int)\n{\n if (rl_point != rl_end)\n return 0;\n\n std::string line = current_->getBuffer();\n\n std::string line1;\n\n if (current_->completeLine(line, line1))\n current_->setBuffer(line + line1);\n\n return 0;\n}\n\nint\nCReadLine::\nrlShowComplete(int, int)\n{\n if (rl_point != rl_end) {\n rl_end = rl_point;\n\n rl_line_buffer[rl_end] = '\\0';\n }\n else {\n std::string line = current_->getBuffer();\n\n if (current_->showComplete(line))\n rl_forced_update_display();\n }\n\n return 0;\n}\n\nint\nCReadLine::\nrlPrevCommand(int, int)\n{\n std::string line;\n\n if (current_->getPrevCommand(line))\n current_->setBuffer(line);\n\n return 0;\n}\n\nint\nCReadLine::\nrlNextCommand(int, int)\n{\n std::string line;\n\n if (! current_->getNextCommand(line))\n line = \"\";\n\n current_->setBuffer(line);\n\n return 0;\n}\n\nint\nCReadLine::\nrlEventHook()\n{\n current_->timeout();\n\n return 1;\n}\n\nstd::string\nCReadLine::\ngetBuffer() const\n{\n return rl_line_buffer;\n}\n\nvoid\nCReadLine::\nsetBuffer(const std::string &buffer)\n{\n rl_extend_line_buffer(buffer.size() + 1);\n\n strcpy(rl_line_buffer, buffer.c_str());\n\n rl_end = buffer.size();\n\n rl_point = rl_end;\n}\n\nvoid\nCReadLine::\naddHistory(const std::string &line)\n{\n if (history_ == NULL)\n history_ = new CHistory;\n\n history_->addCommand(line);\n}\n\nvoid\nCReadLine::\ngetHistoryEntries(std::vector<CReadLineHistoryEntry> &entries)\n{\n HIST_ENTRY **hist_entries = history_list();\n\n for (int i = 0; hist_entries != NULL && hist_entries[i] != NULL; i++) {\n CReadLineHistoryEntry entry(i + history_base, hist_entries[i]->line);\n\n entries.push_back(entry);\n }\n}\n\nvoid\nCReadLine::\nbeep()\n{\n rl_ding();\n}\n\nvoid\nCReadLine::\ninterrupt()\n{\n rl_crlf();\n\n setBuffer(\"\");\n\n rl_forced_update_display();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/speech\/speech_recognition_request.h\"\n\n#include <vector>\n\n#include \"base\/json\/json_reader.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\nconst char* const kDefaultSpeechRecognitionUrl =\n \"https:\/\/www.google.com\/speech-api\/v1\/recognize?xjerr=1&client=chromium&\";\nconst char* const kHypothesesString = \"hypotheses\";\nconst char* const kUtteranceString = \"utterance\";\nconst char* const kConfidenceString = \"confidence\";\n\nbool ParseServerResponse(const std::string& response_body,\n speech_input::SpeechInputResultArray* result) {\n if (response_body.empty()) {\n LOG(WARNING) << \"ParseServerResponse: Response was empty.\";\n return false;\n }\n DVLOG(1) << \"ParseServerResponse: Parsing response \" << response_body;\n\n \/\/ Parse the response, ignoring comments.\n std::string error_msg;\n scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError(\n response_body, false, NULL, &error_msg));\n if (response_value == NULL) {\n LOG(WARNING) << \"ParseServerResponse: JSONReader failed : \" << error_msg;\n return false;\n }\n\n if (!response_value->IsType(Value::TYPE_DICTIONARY)) {\n VLOG(1) << \"ParseServerResponse: Unexpected response type \"\n << response_value->GetType();\n return false;\n }\n const DictionaryValue* response_object =\n static_cast<DictionaryValue*>(response_value.get());\n\n \/\/ Get the hypotheses\n Value* hypotheses_value = NULL;\n if (!response_object->Get(kHypothesesString, &hypotheses_value)) {\n VLOG(1) << \"ParseServerResponse: Missing hypotheses attribute.\";\n return false;\n }\n DCHECK(hypotheses_value);\n if (!hypotheses_value->IsType(Value::TYPE_LIST)) {\n VLOG(1) << \"ParseServerResponse: Unexpected hypotheses type \"\n << hypotheses_value->GetType();\n return false;\n }\n const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value);\n\n size_t index = 0;\n for (; index < hypotheses_list->GetSize(); ++index) {\n Value* hypothesis = NULL;\n if (!hypotheses_list->Get(index, &hypothesis)) {\n LOG(WARNING) << \"ParseServerResponse: Unable to read hypothesis value.\";\n break;\n }\n DCHECK(hypothesis);\n if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) {\n LOG(WARNING) << \"ParseServerResponse: Unexpected value type \"\n << hypothesis->GetType();\n break;\n }\n\n const DictionaryValue* hypothesis_value =\n static_cast<DictionaryValue*>(hypothesis);\n string16 utterance;\n if (!hypothesis_value->GetString(kUtteranceString, &utterance)) {\n LOG(WARNING) << \"ParseServerResponse: Missing utterance value.\";\n break;\n }\n\n \/\/ It is not an error if the 'confidence' field is missing.\n double confidence = 0.0;\n hypothesis_value->GetDouble(kConfidenceString, &confidence);\n\n result->push_back(speech_input::SpeechInputResultItem(utterance,\n confidence));\n }\n\n if (index < hypotheses_list->GetSize()) {\n result->clear();\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nnamespace speech_input {\n\nint SpeechRecognitionRequest::url_fetcher_id_for_tests = 0;\n\nSpeechRecognitionRequest::SpeechRecognitionRequest(\n URLRequestContextGetter* context, Delegate* delegate)\n : url_context_(context),\n delegate_(delegate) {\n DCHECK(delegate);\n}\n\nSpeechRecognitionRequest::~SpeechRecognitionRequest() {}\n\nvoid SpeechRecognitionRequest::Start(const std::string& language,\n const std::string& grammar,\n const std::string& hardware_info,\n const std::string& origin_url,\n const std::string& content_type) {\n DCHECK(!url_fetcher_.get());\n\n std::vector<std::string> parts;\n\n std::string lang_param = language;\n if (lang_param.empty() && url_context_) {\n \/\/ If no language is provided then we use the first from the accepted\n \/\/ language list. If this list is empty then it defaults to \"en-US\".\n \/\/ Example of the contents of this list: \"es,en-GB;q=0.8\", \"\"\n net::URLRequestContext* request_context =\n url_context_->GetURLRequestContext();\n DCHECK(request_context);\n std::string accepted_language_list = request_context->accept_language();\n size_t separator = accepted_language_list.find_first_of(\",;\");\n lang_param = accepted_language_list.substr(0, separator);\n }\n if (lang_param.empty())\n lang_param = \"en-US\";\n parts.push_back(\"lang=\" + EscapeQueryParamValue(lang_param, true));\n\n if (!grammar.empty())\n parts.push_back(\"lm=\" + EscapeQueryParamValue(grammar, true));\n if (!hardware_info.empty())\n parts.push_back(\"xhw=\" + EscapeQueryParamValue(hardware_info, true));\n \/\/ TODO(satish): Remove this hardcoded value once the page is allowed to\n \/\/ set this via an attribute.\n parts.push_back(\"maxresults=3\");\n\n GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&'));\n\n url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests,\n url,\n URLFetcher::POST,\n this));\n url_fetcher_->set_chunked_upload(content_type);\n url_fetcher_->set_request_context(url_context_);\n url_fetcher_->set_referrer(origin_url);\n\n \/\/ The speech recognition API does not require user identification as part\n \/\/ of requests, so we don't send cookies or auth data for these requests to\n \/\/ prevent any accidental connection between users who are logged into the\n \/\/ domain for other services (e.g. bookmark sync) with the speech requests.\n url_fetcher_->set_load_flags(\n net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |\n net::LOAD_DO_NOT_SEND_AUTH_DATA);\n url_fetcher_->Start();\n}\n\nvoid SpeechRecognitionRequest::UploadAudioChunk(const std::string& audio_data,\n bool is_last_chunk) {\n DCHECK(url_fetcher_.get());\n url_fetcher_->AppendChunkToUpload(audio_data, is_last_chunk);\n}\n\nvoid SpeechRecognitionRequest::OnURLFetchComplete(\n const URLFetcher* source,\n const GURL& url,\n const net::URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n DCHECK_EQ(url_fetcher_.get(), source);\n\n bool error = !status.is_success() || response_code != 200;\n SpeechInputResultArray result;\n if (!error)\n error = !ParseServerResponse(data, &result);\n url_fetcher_.reset();\n\n DVLOG(1) << \"SpeechRecognitionRequest: Invoking delegate with result.\";\n delegate_->SetRecognitionResult(error, result);\n}\n\n} \/\/ namespace speech_input\n<commit_msg>Request for 5 speech recognition results instead of 3. This will give webapps more choice until we implement the maxresults attribute.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/speech\/speech_recognition_request.h\"\n\n#include <vector>\n\n#include \"base\/json\/json_reader.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\nconst char* const kDefaultSpeechRecognitionUrl =\n \"https:\/\/www.google.com\/speech-api\/v1\/recognize?xjerr=1&client=chromium&\";\nconst char* const kHypothesesString = \"hypotheses\";\nconst char* const kUtteranceString = \"utterance\";\nconst char* const kConfidenceString = \"confidence\";\n\n\/\/ TODO(satish): Remove this hardcoded value once the page is allowed to\n\/\/ set this via an attribute.\nconst int kMaxResults = 5;\n\nbool ParseServerResponse(const std::string& response_body,\n speech_input::SpeechInputResultArray* result) {\n if (response_body.empty()) {\n LOG(WARNING) << \"ParseServerResponse: Response was empty.\";\n return false;\n }\n DVLOG(1) << \"ParseServerResponse: Parsing response \" << response_body;\n\n \/\/ Parse the response, ignoring comments.\n std::string error_msg;\n scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError(\n response_body, false, NULL, &error_msg));\n if (response_value == NULL) {\n LOG(WARNING) << \"ParseServerResponse: JSONReader failed : \" << error_msg;\n return false;\n }\n\n if (!response_value->IsType(Value::TYPE_DICTIONARY)) {\n VLOG(1) << \"ParseServerResponse: Unexpected response type \"\n << response_value->GetType();\n return false;\n }\n const DictionaryValue* response_object =\n static_cast<DictionaryValue*>(response_value.get());\n\n \/\/ Get the hypotheses\n Value* hypotheses_value = NULL;\n if (!response_object->Get(kHypothesesString, &hypotheses_value)) {\n VLOG(1) << \"ParseServerResponse: Missing hypotheses attribute.\";\n return false;\n }\n DCHECK(hypotheses_value);\n if (!hypotheses_value->IsType(Value::TYPE_LIST)) {\n VLOG(1) << \"ParseServerResponse: Unexpected hypotheses type \"\n << hypotheses_value->GetType();\n return false;\n }\n const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value);\n\n size_t index = 0;\n for (; index < hypotheses_list->GetSize(); ++index) {\n Value* hypothesis = NULL;\n if (!hypotheses_list->Get(index, &hypothesis)) {\n LOG(WARNING) << \"ParseServerResponse: Unable to read hypothesis value.\";\n break;\n }\n DCHECK(hypothesis);\n if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) {\n LOG(WARNING) << \"ParseServerResponse: Unexpected value type \"\n << hypothesis->GetType();\n break;\n }\n\n const DictionaryValue* hypothesis_value =\n static_cast<DictionaryValue*>(hypothesis);\n string16 utterance;\n if (!hypothesis_value->GetString(kUtteranceString, &utterance)) {\n LOG(WARNING) << \"ParseServerResponse: Missing utterance value.\";\n break;\n }\n\n \/\/ It is not an error if the 'confidence' field is missing.\n double confidence = 0.0;\n hypothesis_value->GetDouble(kConfidenceString, &confidence);\n\n result->push_back(speech_input::SpeechInputResultItem(utterance,\n confidence));\n }\n\n if (index < hypotheses_list->GetSize()) {\n result->clear();\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nnamespace speech_input {\n\nint SpeechRecognitionRequest::url_fetcher_id_for_tests = 0;\n\nSpeechRecognitionRequest::SpeechRecognitionRequest(\n URLRequestContextGetter* context, Delegate* delegate)\n : url_context_(context),\n delegate_(delegate) {\n DCHECK(delegate);\n}\n\nSpeechRecognitionRequest::~SpeechRecognitionRequest() {}\n\nvoid SpeechRecognitionRequest::Start(const std::string& language,\n const std::string& grammar,\n const std::string& hardware_info,\n const std::string& origin_url,\n const std::string& content_type) {\n DCHECK(!url_fetcher_.get());\n\n std::vector<std::string> parts;\n\n std::string lang_param = language;\n if (lang_param.empty() && url_context_) {\n \/\/ If no language is provided then we use the first from the accepted\n \/\/ language list. If this list is empty then it defaults to \"en-US\".\n \/\/ Example of the contents of this list: \"es,en-GB;q=0.8\", \"\"\n net::URLRequestContext* request_context =\n url_context_->GetURLRequestContext();\n DCHECK(request_context);\n std::string accepted_language_list = request_context->accept_language();\n size_t separator = accepted_language_list.find_first_of(\",;\");\n lang_param = accepted_language_list.substr(0, separator);\n }\n if (lang_param.empty())\n lang_param = \"en-US\";\n parts.push_back(\"lang=\" + EscapeQueryParamValue(lang_param, true));\n\n if (!grammar.empty())\n parts.push_back(\"lm=\" + EscapeQueryParamValue(grammar, true));\n if (!hardware_info.empty())\n parts.push_back(\"xhw=\" + EscapeQueryParamValue(hardware_info, true));\n parts.push_back(\"maxresults=\" + base::IntToString(kMaxResults));\n\n GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&'));\n\n url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests,\n url,\n URLFetcher::POST,\n this));\n url_fetcher_->set_chunked_upload(content_type);\n url_fetcher_->set_request_context(url_context_);\n url_fetcher_->set_referrer(origin_url);\n\n \/\/ The speech recognition API does not require user identification as part\n \/\/ of requests, so we don't send cookies or auth data for these requests to\n \/\/ prevent any accidental connection between users who are logged into the\n \/\/ domain for other services (e.g. bookmark sync) with the speech requests.\n url_fetcher_->set_load_flags(\n net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |\n net::LOAD_DO_NOT_SEND_AUTH_DATA);\n url_fetcher_->Start();\n}\n\nvoid SpeechRecognitionRequest::UploadAudioChunk(const std::string& audio_data,\n bool is_last_chunk) {\n DCHECK(url_fetcher_.get());\n url_fetcher_->AppendChunkToUpload(audio_data, is_last_chunk);\n}\n\nvoid SpeechRecognitionRequest::OnURLFetchComplete(\n const URLFetcher* source,\n const GURL& url,\n const net::URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n DCHECK_EQ(url_fetcher_.get(), source);\n\n bool error = !status.is_success() || response_code != 200;\n SpeechInputResultArray result;\n if (!error)\n error = !ParseServerResponse(data, &result);\n url_fetcher_.reset();\n\n DVLOG(1) << \"SpeechRecognitionRequest: Invoking delegate with result.\";\n delegate_->SetRecognitionResult(error, result);\n}\n\n} \/\/ namespace speech_input\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2016-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/animationqt\/animationqtmodule.h>\n#include <inviwo\/core\/properties\/ordinalproperty.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/util\/raiiutils.h>\n\n#include <modules\/qtwidgets\/inviwoqtutils.h>\n\n#include <modules\/animation\/animationmodule.h>\n#include <modules\/animation\/datastructures\/animation.h>\n#include <modules\/animation\/datastructures\/buttontrack.h>\n#include <modules\/animation\/datastructures\/cameratrack.h>\n#include <modules\/animation\/datastructures\/callbacktrack.h>\n#include <modules\/animation\/datastructures\/controltrack.h>\n#include <modules\/animation\/datastructures\/keyframe.h>\n#include <modules\/animation\/datastructures\/propertytrack.h>\n#include <modules\/animation\/datastructures\/valuekeyframe.h>\n#include <modules\/animation\/datastructures\/track.h>\n#include <modules\/animation\/animationcontroller.h>\n\n#include <modules\/animationqt\/animationeditordockwidgetqt.h>\n#include <modules\/animationqt\/demo\/demonavigatordockwidgetqt.h>\n\n#include <modules\/animationqt\/widgets\/propertytrackwidgetqt.h>\n#include <modules\/animationqt\/widgets\/controltrackwidgetqt.h>\n\n#include <modules\/animationqt\/sequenceeditor\/propertysequenceeditor.h>\n#include <modules\/animationqt\/sequenceeditor\/controlsequenceeditor.h>\n\n#include <inviwo\/core\/properties\/boolproperty.h>\n#include <inviwo\/core\/properties\/buttonproperty.h>\n#include <inviwo\/core\/properties\/cameraproperty.h>\n#include <inviwo\/core\/properties\/fileproperty.h>\n#include <inviwo\/core\/properties\/minmaxproperty.h>\n#include <inviwo\/core\/properties\/optionproperty.h>\n#include <inviwo\/core\/properties\/ordinalproperty.h>\n#include <inviwo\/core\/properties\/ordinalrefproperty.h>\n#include <inviwo\/core\/properties\/stringproperty.h>\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QMenu>\n#include <QMainWindow>\n#include <QMenuBar>\n#include <QAction>\n#include <warn\/pop>\n\n#ifndef INVIWO_ALL_DYN_LINK\nstruct InitQtAnimationResources {\n \/\/ Needed for loading of resources when building statically\n \/\/ see https:\/\/wiki.qt.io\/QtResources#Q_INIT_RESOURCE\n InitQtAnimationResources() { Q_INIT_RESOURCE(animation); }\n ~InitQtAnimationResources() { Q_CLEANUP_RESOURCE(animation); }\n} initQtAnimationResources;\n#endif\n\nnamespace inviwo {\n\nnamespace {\n\ntemplate <typename PropertyType, typename Keyframe,\n typename KeyframeSequence = animation::KeyframeSequenceTyped<Keyframe>>\nvoid registerPropertyTrackHelper(animation::AnimationQtSupplier& as) {\n using namespace animation;\n\n using TrackType = PropertyTrack<PropertyType, Keyframe, KeyframeSequence>;\n\n as.registerTrackToWidgetMap(TrackType::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n as.registerTrackToSequenceEditorMap(TrackType::classIdentifier(),\n PropertySequenceEditor::classIdentifier());\n}\n\ntemplate <template <typename> class Prop>\nstruct Reghelper {\n template <typename T>\n auto operator()(animation::AnimationQtSupplier& as) {\n using namespace animation;\n registerPropertyTrackHelper<Prop<T>, ValueKeyframe<typename Prop<T>::value_type>>(as);\n }\n};\n\nstruct PropertyValueKeyframeReghelper {\n template <typename Prop>\n auto operator()(animation::AnimationQtSupplier& as) {\n using namespace animation;\n registerPropertyTrackHelper<Prop, ValueKeyframe<typename Prop::value_type>>(as);\n }\n};\n\n} \/\/ namespace\n\nAnimationQtModule::AnimationQtModule(InviwoApplication* app)\n : InviwoModule(app, \"AnimationQt\")\n , animation::AnimationQtSupplier(*this)\n , trackWidgetQtFactory_{}\n , sequenceEditorFactory_{} {\n\n using namespace animation;\n\n if (auto win = utilqt::getApplicationMainWindow()) {\n QString animationMenuName(\"Animation\");\n QMenu* menu = nullptr;\n \/\/ Find view menu\n auto menus = win->menuBar()->findChildren<QMenu*>();\n auto viewMenuIt = std::find_if(menus.begin(), menus.end(), [](auto& m) {\n return m->title().compare(QObject::tr(\"&View\"), Qt::CaseInsensitive) == 0;\n });\n\n if (viewMenuIt != menus.end()) {\n \/\/ Add to view menu if found\n menu = (*viewMenuIt);\n } else {\n \/\/ Add new menu if not found\n \/\/ To be removed when module is destroyed\n menu_ = std::make_unique<QMenu>(animationMenuName);\n win->menuBar()->addMenu(menu_.get());\n menu = menu_.get();\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(menu_.get(), &QObject::destroyed, [&](QObject*) { menu_.release(); });\n }\n\n {\n auto action = menu->addAction(\"Animation Editor\");\n action->setCheckable(true);\n QObject::connect(action, &QAction::triggered, [this, win, app, menu, action]() {\n util::OnScopeExit onexit([action]() { delete action; });\n\n auto animationModule = app->getModuleByType<AnimationModule>();\n editor_ = std::make_unique<AnimationEditorDockWidgetQt>(\n animationModule->getWorkspaceAnimations(),\n animationModule->getAnimationManager(), \"Animation Editor\",\n getTrackWidgetQtFactory(), getSequenceEditorFactory(), win);\n win->addDockWidget(Qt::BottomDockWidgetArea, editor_.get());\n editor_->hide();\n editor_->loadState();\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(editor_.get(), &QObject::destroyed,\n [this](QObject*) { editor_.release(); });\n editor_->setVisible(true);\n\n menu->insertAction(action, editor_->toggleViewAction());\n menu->removeAction(action);\n });\n }\n\n {\n auto action = menu->addAction(\"Demo Navigator\");\n action->setCheckable(true);\n QObject::connect(action, &QAction::triggered, [this, win, app, menu, action]() {\n util::OnScopeExit onexit([action]() { delete action; });\n\n auto animationModule = app->getModuleByType<AnimationModule>();\n auto& demoController = animationModule->getDemoController();\n navigator_ = std::make_unique<DemoNavigatorDockWidgetQt>(demoController,\n \"Demo Navigator\", win);\n win->addDockWidget(Qt::RightDockWidgetArea, navigator_.get());\n navigator_->hide();\n navigator_->loadState();\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(navigator_.get(), &QObject::destroyed,\n [this](QObject*) { navigator_.release(); });\n navigator_->setVisible(true);\n\n menu->insertAction(action, navigator_->toggleViewAction());\n menu->removeAction(action);\n });\n }\n }\n\n \/\/ register widgets\n registerTrackWidgetQt<PropertyTrackWidgetQt>();\n registerTrackWidgetQt<ControlTrackWidgetQt>();\n\n registerSequenceEditor<PropertySequenceEditor>();\n registerSequenceEditor<ControlSequenceEditor>();\n\n \/\/ Map Ordinal properties\n using Types = std::tuple<float, vec2, vec3, vec4, mat2, mat3, mat4, double, dvec2, dvec3, dvec4,\n dmat2, dmat3, dmat4, int, ivec2, ivec3, ivec4, unsigned int, uvec2,\n uvec3, uvec4, size_t, size2_t, size3_t, size4_t>;\n util::for_each_type<Types>{}(Reghelper<OrdinalProperty>{}, *this);\n util::for_each_type<Types>{}(Reghelper<OrdinalRefProperty>{}, *this);\n\n util::for_each_type<std::tuple<float, double, int, unsigned int, size_t>>{}(\n Reghelper<MinMaxProperty>{}, *this);\n\n util::for_each_type<std::tuple<float, double, int, unsigned int, size_t, std::string>>{}(\n Reghelper<TemplateOptionProperty>{}, *this);\n\n util::for_each_type<std::tuple<BoolProperty, FileProperty, StringProperty>>{}(\n PropertyValueKeyframeReghelper{}, *this);\n\n registerPropertyTrackHelper<CameraProperty, CameraKeyframe>(*this);\n\n registerTrackToWidgetMap(ButtonTrack::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n registerTrackToWidgetMap(CallbackTrack::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n registerTrackToWidgetMap(ControlTrack::classIdentifier(),\n ControlTrackWidgetQt::classIdentifier());\n\n registerTrackToSequenceEditorMap(ControlTrack::classIdentifier(),\n ControlSequenceEditor::classIdentifier());\n}\n\nAnimationQtModule::~AnimationQtModule() {\n \/\/ Unregister everything from the factory since this module _owns_ the factory. This is\n \/\/ neccessary even though the base class destructor, i.e. animation::AnimationQtSupplier, takes\n \/\/ care of this. Otherwise the supplier will unregister the items _after_ the factory is\n \/\/ destroyed.\n \/\/\n \/\/ Other modules do not have to do this!\n unRegisterAll();\n}\n\nanimation::TrackWidgetQtFactory& AnimationQtModule::getTrackWidgetQtFactory() {\n return trackWidgetQtFactory_;\n}\nconst animation::TrackWidgetQtFactory& AnimationQtModule::getTrackWidgetQtFactory() const {\n return trackWidgetQtFactory_;\n}\n\nanimation::SequenceEditorFactory& AnimationQtModule::getSequenceEditorFactory() {\n return sequenceEditorFactory_;\n}\nconst animation::SequenceEditorFactory& AnimationQtModule::getSequenceEditorFactory() const {\n return sequenceEditorFactory_;\n}\n\n} \/\/ namespace inviwo\n<commit_msg>AnimationQt: minor refactoring<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2016-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/animationqt\/animationqtmodule.h>\n#include <inviwo\/core\/properties\/ordinalproperty.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/util\/raiiutils.h>\n\n#include <modules\/qtwidgets\/inviwoqtutils.h>\n\n#include <modules\/animation\/animationmodule.h>\n#include <modules\/animation\/datastructures\/animation.h>\n#include <modules\/animation\/datastructures\/buttontrack.h>\n#include <modules\/animation\/datastructures\/cameratrack.h>\n#include <modules\/animation\/datastructures\/callbacktrack.h>\n#include <modules\/animation\/datastructures\/controltrack.h>\n#include <modules\/animation\/datastructures\/keyframe.h>\n#include <modules\/animation\/datastructures\/propertytrack.h>\n#include <modules\/animation\/datastructures\/valuekeyframe.h>\n#include <modules\/animation\/datastructures\/track.h>\n#include <modules\/animation\/animationcontroller.h>\n\n#include <modules\/animationqt\/animationeditordockwidgetqt.h>\n#include <modules\/animationqt\/demo\/demonavigatordockwidgetqt.h>\n\n#include <modules\/animationqt\/widgets\/propertytrackwidgetqt.h>\n#include <modules\/animationqt\/widgets\/controltrackwidgetqt.h>\n\n#include <modules\/animationqt\/sequenceeditor\/propertysequenceeditor.h>\n#include <modules\/animationqt\/sequenceeditor\/controlsequenceeditor.h>\n\n#include <inviwo\/core\/properties\/boolproperty.h>\n#include <inviwo\/core\/properties\/buttonproperty.h>\n#include <inviwo\/core\/properties\/cameraproperty.h>\n#include <inviwo\/core\/properties\/fileproperty.h>\n#include <inviwo\/core\/properties\/minmaxproperty.h>\n#include <inviwo\/core\/properties\/optionproperty.h>\n#include <inviwo\/core\/properties\/ordinalproperty.h>\n#include <inviwo\/core\/properties\/ordinalrefproperty.h>\n#include <inviwo\/core\/properties\/stringproperty.h>\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QMenu>\n#include <QMainWindow>\n#include <QMenuBar>\n#include <QAction>\n#include <warn\/pop>\n\n#ifndef INVIWO_ALL_DYN_LINK\nstruct InitQtAnimationResources {\n \/\/ Needed for loading of resources when building statically\n \/\/ see https:\/\/wiki.qt.io\/QtResources#Q_INIT_RESOURCE\n InitQtAnimationResources() { Q_INIT_RESOURCE(animation); }\n ~InitQtAnimationResources() { Q_CLEANUP_RESOURCE(animation); }\n} initQtAnimationResources;\n#endif\n\nnamespace inviwo {\n\nnamespace {\n\ntemplate <typename PropertyType, typename Keyframe,\n typename KeyframeSequence = animation::KeyframeSequenceTyped<Keyframe>>\nvoid registerPropertyTrackHelper(animation::AnimationQtSupplier& as) {\n using namespace animation;\n\n using TrackType = PropertyTrack<PropertyType, Keyframe, KeyframeSequence>;\n\n as.registerTrackToWidgetMap(TrackType::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n as.registerTrackToSequenceEditorMap(TrackType::classIdentifier(),\n PropertySequenceEditor::classIdentifier());\n}\n\ntemplate <template <typename> class Prop>\nstruct Reghelper {\n template <typename T>\n auto operator()(animation::AnimationQtSupplier& as) {\n using namespace animation;\n registerPropertyTrackHelper<Prop<T>, ValueKeyframe<typename Prop<T>::value_type>>(as);\n }\n};\n\nstruct PropertyValueKeyframeReghelper {\n template <typename Prop>\n auto operator()(animation::AnimationQtSupplier& as) {\n using namespace animation;\n registerPropertyTrackHelper<Prop, ValueKeyframe<typename Prop::value_type>>(as);\n }\n};\n\n} \/\/ namespace\n\nAnimationQtModule::AnimationQtModule(InviwoApplication* app)\n : InviwoModule(app, \"AnimationQt\")\n , animation::AnimationQtSupplier(*this)\n , trackWidgetQtFactory_{}\n , sequenceEditorFactory_{} {\n\n using namespace animation;\n\n if (auto win = utilqt::getApplicationMainWindow()) {\n QString animationMenuName(\"Animation\");\n QMenu* menu = nullptr;\n \/\/ Find view menu\n auto menus = win->menuBar()->findChildren<QMenu*>();\n auto viewMenuIt = std::find_if(menus.begin(), menus.end(), [](auto& m) {\n return m->title().compare(QObject::tr(\"&View\"), Qt::CaseInsensitive) == 0;\n });\n\n if (viewMenuIt != menus.end()) {\n \/\/ Add to view menu if found\n menu = (*viewMenuIt);\n } else {\n \/\/ Add new menu if not found\n \/\/ To be removed when module is destroyed\n menu_ = std::make_unique<QMenu>(animationMenuName);\n win->menuBar()->addMenu(menu_.get());\n menu = menu_.get();\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(menu_.get(), &QObject::destroyed, [&](QObject*) { menu_.release(); });\n }\n\n const auto addWidgetLazy = [&](QString name, Qt::DockWidgetArea area, auto factory) {\n auto* action = menu->addAction(name);\n action->setCheckable(true);\n QObject::connect(action, &QAction::triggered, [action, win, area, menu, factory]() {\n \/\/ The first time the callback is called we will create the widget. And then replace\n \/\/ this action with the toggleViewAction from the new widget.\n util::OnScopeExit onExit([action]() { delete action; });\n auto widget = factory();\n win->addDockWidget(area, widget);\n widget->hide();\n widget->loadState();\n widget->setVisible(true);\n\n menu->insertAction(action, widget->toggleViewAction());\n menu->removeAction(action);\n });\n };\n\n addWidgetLazy(\"Animation Editor\", Qt::BottomDockWidgetArea, [this, app, win]() {\n auto* animationModule = app->getModuleByType<AnimationModule>();\n editor_ = std::make_unique<AnimationEditorDockWidgetQt>(\n animationModule->getWorkspaceAnimations(), animationModule->getAnimationManager(),\n \"Animation Editor\", getTrackWidgetQtFactory(), getSequenceEditorFactory(), win);\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(editor_.get(), &QObject::destroyed,\n [this](QObject*) { editor_.release(); });\n return editor_.get();\n });\n\n addWidgetLazy(\"Demo Navigator\", Qt::RightDockWidgetArea, [this, app, win]() {\n auto* animationModule = app->getModuleByType<AnimationModule>();\n auto& demoController = animationModule->getDemoController();\n navigator_ =\n std::make_unique<DemoNavigatorDockWidgetQt>(demoController, \"Demo Navigator\", win);\n \/\/ Release pointer if destroyed by Qt before module is destroyed\n QObject::connect(navigator_.get(), &QObject::destroyed,\n [this](QObject*) { navigator_.release(); });\n return navigator_.get();\n });\n }\n\n \/\/ register widgets\n registerTrackWidgetQt<PropertyTrackWidgetQt>();\n registerTrackWidgetQt<ControlTrackWidgetQt>();\n\n registerSequenceEditor<PropertySequenceEditor>();\n registerSequenceEditor<ControlSequenceEditor>();\n\n \/\/ Map Ordinal properties\n using Types = std::tuple<float, vec2, vec3, vec4, mat2, mat3, mat4, double, dvec2, dvec3, dvec4,\n dmat2, dmat3, dmat4, int, ivec2, ivec3, ivec4, unsigned int, uvec2,\n uvec3, uvec4, size_t, size2_t, size3_t, size4_t>;\n util::for_each_type<Types>{}(Reghelper<OrdinalProperty>{}, *this);\n util::for_each_type<Types>{}(Reghelper<OrdinalRefProperty>{}, *this);\n\n util::for_each_type<std::tuple<float, double, int, unsigned int, size_t>>{}(\n Reghelper<MinMaxProperty>{}, *this);\n\n util::for_each_type<std::tuple<float, double, int, unsigned int, size_t, std::string>>{}(\n Reghelper<TemplateOptionProperty>{}, *this);\n\n util::for_each_type<std::tuple<BoolProperty, FileProperty, StringProperty>>{}(\n PropertyValueKeyframeReghelper{}, *this);\n\n registerPropertyTrackHelper<CameraProperty, CameraKeyframe>(*this);\n\n registerTrackToWidgetMap(ButtonTrack::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n registerTrackToWidgetMap(CallbackTrack::classIdentifier(),\n PropertyTrackWidgetQt::classIdentifier());\n\n registerTrackToWidgetMap(ControlTrack::classIdentifier(),\n ControlTrackWidgetQt::classIdentifier());\n\n registerTrackToSequenceEditorMap(ControlTrack::classIdentifier(),\n ControlSequenceEditor::classIdentifier());\n} \/\/ namespace inviwo\n\nAnimationQtModule::~AnimationQtModule() {\n \/\/ Unregister everything from the factory since this module _owns_ the factory. This is\n \/\/ neccessary even though the base class destructor, i.e. animation::AnimationQtSupplier, takes\n \/\/ care of this. Otherwise the supplier will unregister the items _after_ the factory is\n \/\/ destroyed.\n \/\/\n \/\/ Other modules do not have to do this!\n unRegisterAll();\n}\n\nanimation::TrackWidgetQtFactory& AnimationQtModule::getTrackWidgetQtFactory() {\n return trackWidgetQtFactory_;\n}\nconst animation::TrackWidgetQtFactory& AnimationQtModule::getTrackWidgetQtFactory() const {\n return trackWidgetQtFactory_;\n}\n\nanimation::SequenceEditorFactory& AnimationQtModule::getSequenceEditorFactory() {\n return sequenceEditorFactory_;\n}\nconst animation::SequenceEditorFactory& AnimationQtModule::getSequenceEditorFactory() const {\n return sequenceEditorFactory_;\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FakeESOut.cpp\n *****************************************************************************\n * Copyright © 2014-2015 VideoLAN and VLC Authors\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"FakeESOut.hpp\"\n#include \"FakeESOutID.hpp\"\n#include \"CommandsQueue.hpp\"\n#include <vlc_es_out.h>\n#include <vlc_block.h>\n#include <cassert>\n\nusing namespace adaptive;\n\nFakeESOut::FakeESOut( es_out_t *es, CommandsQueue *queue )\n{\n real_es_out = es;\n fakeesout = new es_out_t;\n\n fakeesout->pf_add = esOutAdd_Callback;\n fakeesout->pf_control = esOutControl_Callback;\n fakeesout->pf_del = esOutDel_Callback;\n fakeesout->pf_destroy = esOutDestroy_Callback;\n fakeesout->pf_send = esOutSend_Callback;\n fakeesout->p_sys = (es_out_sys_t*) this;\n\n commandsqueue = queue;\n\n timestamps_offset = 0;\n extrainfo = NULL;\n vlc_mutex_init(&lock);\n}\n\nes_out_t * FakeESOut::getEsOut()\n{\n return fakeesout;\n}\n\nFakeESOut::~FakeESOut()\n{\n recycleAll();\n gc();\n\n delete fakeesout;\n vlc_mutex_destroy(&lock);\n}\n\nvoid FakeESOut::setTimestampOffset(mtime_t offset)\n{\n vlc_mutex_lock(&lock);\n timestamps_offset = offset;\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::setExtraInfoProvider( ExtraFMTInfoInterface *extra )\n{\n vlc_mutex_lock(&lock);\n extrainfo = extra;\n vlc_mutex_unlock(&lock);\n}\n\nFakeESOutID * FakeESOut::createNewID( const es_format_t *p_fmt )\n{\n es_format_t fmtcopy;\n es_format_Init( &fmtcopy, 0, 0 );\n es_format_Copy( &fmtcopy, p_fmt );\n fmtcopy.i_group = 0; \/* Always ignore group for adaptive *\/\n fmtcopy.i_id = -1;\n\n vlc_mutex_lock(&lock);\n\n if( extrainfo )\n extrainfo->fillExtraFMTInfo( &fmtcopy );\n\n FakeESOutID *es_id = new (std::nothrow) FakeESOutID( this, &fmtcopy );\n if(likely(es_id))\n fakeesidlist.push_back( es_id );\n\n vlc_mutex_unlock(&lock);\n\n es_format_Clean( &fmtcopy );\n\n return es_id;\n}\n\nvoid FakeESOut::createOrRecycleRealEsID( FakeESOutID *es_id )\n{\n std::list<FakeESOutID *>::iterator it;\n es_out_id_t *realid = NULL;\n\n vlc_mutex_lock(&lock);\n\n bool b_select = false;\n for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )\n {\n FakeESOutID *cand = *it;\n if ( cand->isCompatible( es_id ) )\n {\n realid = cand->realESID();\n cand->setRealESID( NULL );\n delete *it;\n recycle_candidates.erase( it );\n break;\n }\n else if( cand->getFmt()->i_cat == es_id->getFmt()->i_cat && cand->realESID() )\n {\n \/* We need to enforce same selection when not reused\n Otherwise the es will select any other compatible track\n and will end this in a activate\/select loop when reactivating a track *\/\n es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, cand->realESID(), &b_select );\n break;\n }\n }\n\n if( !realid )\n {\n realid = es_out_Add( real_es_out, es_id->getFmt() );\n if( b_select )\n es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, realid, b_select );\n }\n\n es_id->setRealESID( realid );\n\n vlc_mutex_unlock(&lock);\n}\n\nmtime_t FakeESOut::getTimestampOffset() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n mtime_t time = timestamps_offset;\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return time;\n}\n\nsize_t FakeESOut::esCount() const\n{\n size_t i_count = 0;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n if( (*it)->realESID() )\n i_count++;\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return i_count;\n}\n\nvoid FakeESOut::schedulePCRReset()\n{\n AbstractCommand *command = commandsqueue->factory()->creatEsOutControlResetPCRCommand();\n if( likely(command) )\n commandsqueue->Schedule( command );\n}\n\nvoid FakeESOut::scheduleAllForDeletion()\n{\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(&lock);\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n {\n FakeESOutID *es_id = *it;\n if(!es_id->scheduledForDeletion())\n {\n AbstractCommand *command = commandsqueue->factory()->createEsOutDelCommand( es_id );\n if( likely(command) )\n {\n commandsqueue->Schedule( command );\n es_id->setScheduledForDeletion();\n }\n }\n }\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::recycleAll()\n{\n \/* Only used when demux is killed and commands queue is cancelled *\/\n commandsqueue->Abort( true );\n assert(commandsqueue->isEmpty());\n vlc_mutex_lock(&lock);\n recycle_candidates.splice( recycle_candidates.end(), fakeesidlist );\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::gc()\n{\n vlc_mutex_lock(&lock);\n if( recycle_candidates.empty() )\n {\n vlc_mutex_unlock(&lock);\n return;\n }\n\n std::list<FakeESOutID *>::iterator it;\n for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )\n {\n if( (*it)->realESID() )\n {\n es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, (*it)->realESID(), false );\n es_out_Del( real_es_out, (*it)->realESID() );\n }\n delete *it;\n }\n recycle_candidates.clear();\n vlc_mutex_unlock(&lock);\n}\n\nbool FakeESOut::hasSelectedEs() const\n{\n bool b_selected = false;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end() && !b_selected; ++it )\n {\n FakeESOutID *esID = *it;\n if( esID->realESID() )\n es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, esID->realESID(), &b_selected );\n }\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return b_selected;\n}\n\nbool FakeESOut::drain()\n{\n bool b_drained = true;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(&lock);\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n {\n FakeESOutID *esID = *it;\n if( esID->realESID() )\n {\n bool b_empty;\n es_out_Control( real_es_out, ES_OUT_GET_EMPTY, &b_empty );\n b_drained &= b_empty;\n }\n }\n vlc_mutex_unlock(&lock);\n return b_drained;\n}\n\nbool FakeESOut::restarting() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n bool b = !recycle_candidates.empty();\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return b;\n}\n\nvoid FakeESOut::recycle( FakeESOutID *id )\n{\n vlc_mutex_lock(&lock);\n fakeesidlist.remove( id );\n recycle_candidates.push_back( id );\n vlc_mutex_unlock(&lock);\n}\n\n\/* Static callbacks *\/\n\/* Always pass Fake ES ID to slave demuxes, it is just an opaque struct to them *\/\nes_out_id_t * FakeESOut::esOutAdd_Callback(es_out_t *fakees, const es_format_t *p_fmt)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n \/* Feed the slave demux\/stream_Demux with FakeESOutID struct,\n * we'll create real ES later on main demux on execution *\/\n FakeESOutID *es_id = me->createNewID( p_fmt );\n if( likely(es_id) )\n {\n assert(!es_id->scheduledForDeletion());\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutAddCommand( es_id );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return reinterpret_cast<es_out_id_t *>(es_id);\n }\n else\n {\n delete es_id;\n }\n }\n return NULL;\n}\n\nint FakeESOut::esOutSend_Callback(es_out_t *fakees, es_out_id_t *p_es, block_t *p_block)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );\n assert(!es_id->scheduledForDeletion());\n mtime_t offset = me->getTimestampOffset();\n if( p_block->i_dts > VLC_TS_INVALID )\n {\n p_block->i_dts += offset;\n if( p_block->i_pts > VLC_TS_INVALID )\n p_block->i_pts += offset;\n }\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutSendCommand( es_id, p_block );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return VLC_SUCCESS;\n }\n return VLC_EGENERIC;\n}\n\nvoid FakeESOut::esOutDel_Callback(es_out_t *fakees, es_out_id_t *p_es)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutDelCommand( es_id );\n if( likely(command) )\n {\n es_id->setScheduledForDeletion();\n me->commandsqueue->Schedule( command );\n }\n}\n\nint FakeESOut::esOutControl_Callback(es_out_t *fakees, int i_query, va_list args)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n\n switch( i_query )\n {\n case ES_OUT_SET_PCR:\n case ES_OUT_SET_GROUP_PCR:\n {\n int i_group;\n if( i_query == ES_OUT_SET_GROUP_PCR )\n i_group = static_cast<int>(va_arg( args, int ));\n else\n i_group = 0;\n int64_t pcr = static_cast<int64_t>(va_arg( args, int64_t ));\n pcr += me->getTimestampOffset();\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutControlPCRCommand( i_group, pcr );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return VLC_SUCCESS;\n }\n }\n break;\n\n \/* For others, we don't have the delorean, so always lie *\/\n case ES_OUT_GET_ES_STATE:\n {\n static_cast<void*>(va_arg( args, es_out_id_t * ));\n bool *pb = static_cast<bool *>(va_arg( args, bool * ));\n *pb = true;\n \/\/ ft\n }\n case ES_OUT_SET_ES:\n case ES_OUT_SET_ES_DEFAULT:\n case ES_OUT_SET_ES_STATE:\n return VLC_SUCCESS;\n\n }\n\n return VLC_EGENERIC;\n}\n\nvoid FakeESOut::esOutDestroy_Callback(es_out_t *fakees)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutDestroyCommand();\n if( likely(command) )\n me->commandsqueue->Schedule( command );\n}\n\/* !Static callbacks *\/\n<commit_msg>demux: adaptive: reject UNKNOWN_ES<commit_after>\/*\n * FakeESOut.cpp\n *****************************************************************************\n * Copyright © 2014-2015 VideoLAN and VLC Authors\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"FakeESOut.hpp\"\n#include \"FakeESOutID.hpp\"\n#include \"CommandsQueue.hpp\"\n#include <vlc_es_out.h>\n#include <vlc_block.h>\n#include <cassert>\n\nusing namespace adaptive;\n\nFakeESOut::FakeESOut( es_out_t *es, CommandsQueue *queue )\n{\n real_es_out = es;\n fakeesout = new es_out_t;\n\n fakeesout->pf_add = esOutAdd_Callback;\n fakeesout->pf_control = esOutControl_Callback;\n fakeesout->pf_del = esOutDel_Callback;\n fakeesout->pf_destroy = esOutDestroy_Callback;\n fakeesout->pf_send = esOutSend_Callback;\n fakeesout->p_sys = (es_out_sys_t*) this;\n\n commandsqueue = queue;\n\n timestamps_offset = 0;\n extrainfo = NULL;\n vlc_mutex_init(&lock);\n}\n\nes_out_t * FakeESOut::getEsOut()\n{\n return fakeesout;\n}\n\nFakeESOut::~FakeESOut()\n{\n recycleAll();\n gc();\n\n delete fakeesout;\n vlc_mutex_destroy(&lock);\n}\n\nvoid FakeESOut::setTimestampOffset(mtime_t offset)\n{\n vlc_mutex_lock(&lock);\n timestamps_offset = offset;\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::setExtraInfoProvider( ExtraFMTInfoInterface *extra )\n{\n vlc_mutex_lock(&lock);\n extrainfo = extra;\n vlc_mutex_unlock(&lock);\n}\n\nFakeESOutID * FakeESOut::createNewID( const es_format_t *p_fmt )\n{\n es_format_t fmtcopy;\n es_format_Init( &fmtcopy, 0, 0 );\n es_format_Copy( &fmtcopy, p_fmt );\n fmtcopy.i_group = 0; \/* Always ignore group for adaptive *\/\n fmtcopy.i_id = -1;\n\n vlc_mutex_lock(&lock);\n\n if( extrainfo )\n extrainfo->fillExtraFMTInfo( &fmtcopy );\n\n FakeESOutID *es_id = new (std::nothrow) FakeESOutID( this, &fmtcopy );\n if(likely(es_id))\n fakeesidlist.push_back( es_id );\n\n vlc_mutex_unlock(&lock);\n\n es_format_Clean( &fmtcopy );\n\n return es_id;\n}\n\nvoid FakeESOut::createOrRecycleRealEsID( FakeESOutID *es_id )\n{\n std::list<FakeESOutID *>::iterator it;\n es_out_id_t *realid = NULL;\n\n vlc_mutex_lock(&lock);\n\n bool b_select = false;\n for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )\n {\n FakeESOutID *cand = *it;\n if ( cand->isCompatible( es_id ) )\n {\n realid = cand->realESID();\n cand->setRealESID( NULL );\n delete *it;\n recycle_candidates.erase( it );\n break;\n }\n else if( cand->getFmt()->i_cat == es_id->getFmt()->i_cat && cand->realESID() )\n {\n \/* We need to enforce same selection when not reused\n Otherwise the es will select any other compatible track\n and will end this in a activate\/select loop when reactivating a track *\/\n es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, cand->realESID(), &b_select );\n break;\n }\n }\n\n if( !realid )\n {\n realid = es_out_Add( real_es_out, es_id->getFmt() );\n if( b_select )\n es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, realid, b_select );\n }\n\n es_id->setRealESID( realid );\n\n vlc_mutex_unlock(&lock);\n}\n\nmtime_t FakeESOut::getTimestampOffset() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n mtime_t time = timestamps_offset;\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return time;\n}\n\nsize_t FakeESOut::esCount() const\n{\n size_t i_count = 0;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n if( (*it)->realESID() )\n i_count++;\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return i_count;\n}\n\nvoid FakeESOut::schedulePCRReset()\n{\n AbstractCommand *command = commandsqueue->factory()->creatEsOutControlResetPCRCommand();\n if( likely(command) )\n commandsqueue->Schedule( command );\n}\n\nvoid FakeESOut::scheduleAllForDeletion()\n{\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(&lock);\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n {\n FakeESOutID *es_id = *it;\n if(!es_id->scheduledForDeletion())\n {\n AbstractCommand *command = commandsqueue->factory()->createEsOutDelCommand( es_id );\n if( likely(command) )\n {\n commandsqueue->Schedule( command );\n es_id->setScheduledForDeletion();\n }\n }\n }\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::recycleAll()\n{\n \/* Only used when demux is killed and commands queue is cancelled *\/\n commandsqueue->Abort( true );\n assert(commandsqueue->isEmpty());\n vlc_mutex_lock(&lock);\n recycle_candidates.splice( recycle_candidates.end(), fakeesidlist );\n vlc_mutex_unlock(&lock);\n}\n\nvoid FakeESOut::gc()\n{\n vlc_mutex_lock(&lock);\n if( recycle_candidates.empty() )\n {\n vlc_mutex_unlock(&lock);\n return;\n }\n\n std::list<FakeESOutID *>::iterator it;\n for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )\n {\n if( (*it)->realESID() )\n {\n es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, (*it)->realESID(), false );\n es_out_Del( real_es_out, (*it)->realESID() );\n }\n delete *it;\n }\n recycle_candidates.clear();\n vlc_mutex_unlock(&lock);\n}\n\nbool FakeESOut::hasSelectedEs() const\n{\n bool b_selected = false;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end() && !b_selected; ++it )\n {\n FakeESOutID *esID = *it;\n if( esID->realESID() )\n es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, esID->realESID(), &b_selected );\n }\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return b_selected;\n}\n\nbool FakeESOut::drain()\n{\n bool b_drained = true;\n std::list<FakeESOutID *>::const_iterator it;\n vlc_mutex_lock(&lock);\n for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )\n {\n FakeESOutID *esID = *it;\n if( esID->realESID() )\n {\n bool b_empty;\n es_out_Control( real_es_out, ES_OUT_GET_EMPTY, &b_empty );\n b_drained &= b_empty;\n }\n }\n vlc_mutex_unlock(&lock);\n return b_drained;\n}\n\nbool FakeESOut::restarting() const\n{\n vlc_mutex_lock(const_cast<vlc_mutex_t *>(&lock));\n bool b = !recycle_candidates.empty();\n vlc_mutex_unlock(const_cast<vlc_mutex_t *>(&lock));\n return b;\n}\n\nvoid FakeESOut::recycle( FakeESOutID *id )\n{\n vlc_mutex_lock(&lock);\n fakeesidlist.remove( id );\n recycle_candidates.push_back( id );\n vlc_mutex_unlock(&lock);\n}\n\n\/* Static callbacks *\/\n\/* Always pass Fake ES ID to slave demuxes, it is just an opaque struct to them *\/\nes_out_id_t * FakeESOut::esOutAdd_Callback(es_out_t *fakees, const es_format_t *p_fmt)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n\n if( p_fmt->i_cat != VIDEO_ES && p_fmt->i_cat != AUDIO_ES && p_fmt->i_cat != SPU_ES )\n return NULL;\n\n \/* Feed the slave demux\/stream_Demux with FakeESOutID struct,\n * we'll create real ES later on main demux on execution *\/\n FakeESOutID *es_id = me->createNewID( p_fmt );\n if( likely(es_id) )\n {\n assert(!es_id->scheduledForDeletion());\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutAddCommand( es_id );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return reinterpret_cast<es_out_id_t *>(es_id);\n }\n else\n {\n delete es_id;\n }\n }\n return NULL;\n}\n\nint FakeESOut::esOutSend_Callback(es_out_t *fakees, es_out_id_t *p_es, block_t *p_block)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );\n assert(!es_id->scheduledForDeletion());\n mtime_t offset = me->getTimestampOffset();\n if( p_block->i_dts > VLC_TS_INVALID )\n {\n p_block->i_dts += offset;\n if( p_block->i_pts > VLC_TS_INVALID )\n p_block->i_pts += offset;\n }\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutSendCommand( es_id, p_block );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return VLC_SUCCESS;\n }\n return VLC_EGENERIC;\n}\n\nvoid FakeESOut::esOutDel_Callback(es_out_t *fakees, es_out_id_t *p_es)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutDelCommand( es_id );\n if( likely(command) )\n {\n es_id->setScheduledForDeletion();\n me->commandsqueue->Schedule( command );\n }\n}\n\nint FakeESOut::esOutControl_Callback(es_out_t *fakees, int i_query, va_list args)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n\n switch( i_query )\n {\n case ES_OUT_SET_PCR:\n case ES_OUT_SET_GROUP_PCR:\n {\n int i_group;\n if( i_query == ES_OUT_SET_GROUP_PCR )\n i_group = static_cast<int>(va_arg( args, int ));\n else\n i_group = 0;\n int64_t pcr = static_cast<int64_t>(va_arg( args, int64_t ));\n pcr += me->getTimestampOffset();\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutControlPCRCommand( i_group, pcr );\n if( likely(command) )\n {\n me->commandsqueue->Schedule( command );\n return VLC_SUCCESS;\n }\n }\n break;\n\n \/* For others, we don't have the delorean, so always lie *\/\n case ES_OUT_GET_ES_STATE:\n {\n static_cast<void*>(va_arg( args, es_out_id_t * ));\n bool *pb = static_cast<bool *>(va_arg( args, bool * ));\n *pb = true;\n \/\/ ft\n }\n case ES_OUT_SET_ES:\n case ES_OUT_SET_ES_DEFAULT:\n case ES_OUT_SET_ES_STATE:\n return VLC_SUCCESS;\n\n }\n\n return VLC_EGENERIC;\n}\n\nvoid FakeESOut::esOutDestroy_Callback(es_out_t *fakees)\n{\n FakeESOut *me = (FakeESOut *) fakees->p_sys;\n AbstractCommand *command = me->commandsqueue->factory()->createEsOutDestroyCommand();\n if( likely(command) )\n me->commandsqueue->Schedule( command );\n}\n\/* !Static callbacks *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * examples\/smithvalence.C\n * Copyright (c) Linbox\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n\/**\\file examples\/smithvalence.C\n * @example examples\/smithvalence.C\n \\brief Valence of sparse matrix over Z or Zp.\n \\ingroup examples\n*\/\n#ifndef DISABLE_COMMENTATOR\n#define DISABLE_COMMENTATOR\n#endif\n\n#include <linbox\/linbox-config.h>\n\n#include <iostream>\n#include <fflas-ffpack\/paladin\/parallel.h>\n#include <linbox\/algorithms\/smith-form-valence.h>\n#include <vector>\n\nusing namespace LinBox;\n\n\nint main (int argc, char **argv)\n{\n \/\/ commentator().setMaxDetailLevel (-1);\n \/\/ commentator().setMaxDepth (-1);\n \/\/ commentator().setReportStream (std::cerr);\n\n\n\tif (argc < 2 || argc > 4) {\n\t\tstd::cerr << \"Usage: smithvalence <matrix-file-in-supported-format> [-ata|-aat|valence] [coprime]\" << std::endl;\n std::cerr << \" Optional parameters valence and coprime are integers.\" << std::endl;\n std::cerr << \" Prime factors of valence will be used for local computation.\" << std::endl;\n std::cerr << \" coprime will be used for overall rank computation.\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::ifstream input (argv[1]);\n\tif (!input) { std::cerr << \"Error opening matrix file \" << argv[1] << std::endl; return -1; }\n\n\tGivaro::ZRing<Integer> ZZ;\n\tMatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );\n\ttypedef SparseMatrix<Givaro::ZRing<Integer>> Blackbox;\n\tBlackbox A (ms);\n\tinput.close();\n\n\tstd::cout << \"A is \" << A.rowdim() << \" by \" << A.coldim() << std::endl;\n\n\tGivaro::ZRing<Integer>::Element val_A;\n\n\tLinBox::Timer chrono; chrono.start();\n\tif (argc >= 3) {\n\t\tTranspose<Blackbox> T(&A);\n\t\tif (strcmp(argv[2],\"-ata\") == 0) {\n\t\t\tCompose< Transpose<Blackbox>, Blackbox > C (&T, &A);\n\t\t\tstd::cout << \"A^T A is \" << C.rowdim() << \" by \" << C.coldim() << std::endl;\n\t\t\tvalence(val_A, C);\n\t\t}\n\t\telse if (strcmp(argv[2],\"-aat\") == 0) {\n\t\t\tCompose< Blackbox, Transpose<Blackbox> > C (&A, &T);\n\t\t\tstd::cout << \"A A^T is \" << C.rowdim() << \" by \" << C.coldim() << std::endl;\n\t\t\tvalence(val_A, C);\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"Suppose primes are contained in \" << argv[2] << std::endl;\n\t\t\tval_A = LinBox::Integer(argv[2]);\n\t\t}\n\t}\n\telse {\n\t\tif (A.rowdim() != A.coldim()) {\n\t\t\tstd::cerr << \"Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options.\" << std::endl;\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t\tvalence (val_A, A);\n\t}\n\n\tstd::cout << \"Valence is \" << val_A << std::endl;\n\n\tstd::vector<Givaro::Integer> Moduli;\n\tstd::vector<size_t> exponents;\n\tGivaro::IntFactorDom<> FTD;\n\n\tstd::vector< PairIntRk > smith;\n\n\n Givaro::Integer coprimeV=2;\n\tif (argc >= 4) {\n\t\tcoprimeV =Givaro::Integer(argv[3]);\n\t}\n\twhile ( gcd(val_A,coprimeV) > 1 ) {\n\t\tFTD.nextprimein(coprimeV);\n\t}\n\n\tif (argc >= 4) {\n\t\tstd::cout << \"Suppose \" << argv[3] << \" is coprime with Smith form\" << std::endl;\n\t}\n\nstd::cout << \"Some factors (50000 factoring loop bound): \";\n\tFTD.set(Moduli, exponents, val_A, 50000);\n\tstd::vector<size_t>::const_iterator eit=exponents.begin();\n\tfor(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();\n\t mit != Moduli.end(); ++mit,++eit)\n\t\tstd::cout << *mit << '^' << *eit << ' ';\n\tstd::cout << std::endl;\n smith.resize(Moduli.size());\n\n size_t coprimeR; \n \n\tstd::cout << \"num procs: \" << omp_get_num_procs() << std::endl;\n\tstd::cout << \"num threads: \" << NUM_THREADS << std::endl;\n\tstd::cout << \"max threads: \" << MAX_THREADS << std::endl;\n\n#pragma omp parallel \n {\n#pragma omp single\n {\n for(size_t j=0; j<Moduli.size(); ++j) {\n smith[j].first = Moduli[j];\n#pragma omp task shared(smith,argv) firstprivate(j)\n LRank(smith[j].second, argv[1], smith[j].first);\n }\n LRank(coprimeR, argv[1], coprimeV);\n }\n\t}\n\n std::vector<Givaro::Integer> SmithDiagonal(coprimeR,Givaro::Integer(1));\n \n#pragma omp parallel for shared(SmithDiagonal, smith, exponents)\n\tfor(size_t j=0; j<Moduli.size(); ++j) {\n \n if (smith[j].second != coprimeR) {\n std::vector<size_t> ranks;\n const PairIntRk& smithj(smith[j]);\n const size_t& exponentsj(exponents[j]);\n\n AllPowersRanks(ranks, smithj, exponentsj, coprimeR, argv[1]);\n\n#pragma omp critical\n {\n populateSmithForm(SmithDiagonal, ranks, smithj, coprimeR);\n }\n }\n }\n\n\n\/\/ std::vector<size_t> * AllRanks = new std::vector<size_t>[Moduli.size()];\n\n\/\/ SYNCH_GROUP(\n\/\/ for(size_t j=0; j<Moduli.size(); ++j) \n\/\/ {\n\/\/ if (smith[j].second != coprimeR) {\n\/\/ std::vector<size_t>& ranks(AllRanks[j]);\n\/\/ const PairIntRk& smithj(smith[j]);\n\/\/ const size_t& exponentsj(exponents[j]);\n\/\/ { TASK(MODE(CONSTREFERENCE(smithj, exponentsj, coprimeR) WRITE(AllRanks[j])),\n\/\/ {\n\/\/ AllPowersRanks(AllRanks[j], smithj, exponentsj, coprimeR, argv[1]);\n\/\/ })}\n \n\/\/ }\n\/\/ }\n\/\/ );\n \n\/\/ for(size_t j=0; j<Moduli.size(); ++j) {\n\/\/ if (smith[j].second != coprimeR) {\n\/\/ populateSmithForm(SmithDiagonal, AllRanks[j], smith[j], coprimeR);\n\/\/ }\n\/\/ }\n \n\n\/\/ SYNCH_GROUP(\n\/\/ FORBLOCK1D(iter, Moduli.size(), SPLITTER(),\n\/\/ TASK(MODE( \n\/\/ CONSTREFERENCE(SmithDiagonal, smith, exponents, coprimeR) ),\n\/\/ {\n\/\/ for(size_t j=iter.begin(); j != iter.end(); ++j) { \n\/\/ if (smith[j].second != coprimeR) {\n\/\/ std::vector<size_t> ranks;\n\/\/ AllPowersRanks(ranks, smith[j], exponents[j], coprimeR, argv[1]);\n \n\/\/ #pragma omp critical\n\/\/ { \n\n\/\/ populateSmithForm(SmithDiagonal, ranks, smith[j], coprimeR);\n\/\/ }\n\/\/ }\n\/\/ \t}\n\/\/ })\n\/\/ );\n\/\/ );\n \n\tchrono.stop();\n\n Givaro::Integer si=1;\n\tsize_t num=0;\n\tstd::cerr << \"Integer Smith Form :\" << std::endl;\n std::cout << '(';\n\tfor( std::vector<Givaro::Integer>::const_iterator dit=SmithDiagonal.begin();\n\t dit != SmithDiagonal.end(); ++dit) {\n\t\tif (*dit == si) ++num;\n\t\telse {\n\t\t\tstd::cerr << '[' << si << ',' << num << \"] \";\n\t\t\tnum=1;\n\t\t\tsi = *dit;\n\t\t}\n\t}\n\tstd::cerr << '[' << si << ',' << num << \"] \";\n\tnum = std::min(A.rowdim(),A.coldim()) - SmithDiagonal.size();\n\tsi = ZZ.zero;\n\tif (num > 0) std::cout << '[' << si << ',' << num << ']';\n\tstd::cout << ')' << std::endl;\n\tstd::cerr << chrono << std::endl;\n\n\n\treturn 0;\n}\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ tab-width: 4\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 4\n\/\/ End:\n\/\/ vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n<commit_msg>parblock<commit_after>\/*\n * examples\/smithvalence.C\n * Copyright (c) Linbox\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n\/**\\file examples\/smithvalence.C\n * @example examples\/smithvalence.C\n \\brief Valence of sparse matrix over Z or Zp.\n \\ingroup examples\n*\/\n#ifndef DISABLE_COMMENTATOR\n#define DISABLE_COMMENTATOR\n#endif\n\n#include <linbox\/linbox-config.h>\n\n#include <iostream>\n#include <fflas-ffpack\/paladin\/parallel.h>\n#include <linbox\/algorithms\/smith-form-valence.h>\n#include <vector>\n\nusing namespace LinBox;\n\n\nint main (int argc, char **argv)\n{\n \/\/ commentator().setMaxDetailLevel (-1);\n \/\/ commentator().setMaxDepth (-1);\n \/\/ commentator().setReportStream (std::cerr);\n\n\n\tif (argc < 2 || argc > 4) {\n\t\tstd::cerr << \"Usage: smithvalence <matrix-file-in-supported-format> [-ata|-aat|valence] [coprime]\" << std::endl;\n std::cerr << \" Optional parameters valence and coprime are integers.\" << std::endl;\n std::cerr << \" Prime factors of valence will be used for local computation.\" << std::endl;\n std::cerr << \" coprime will be used for overall rank computation.\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::ifstream input (argv[1]);\n\tif (!input) { std::cerr << \"Error opening matrix file \" << argv[1] << std::endl; return -1; }\n\n\tGivaro::ZRing<Integer> ZZ;\n\tMatrixStream< Givaro::ZRing<Integer> > ms( ZZ, input );\n\ttypedef SparseMatrix<Givaro::ZRing<Integer>> Blackbox;\n\tBlackbox A (ms);\n\tinput.close();\n\n\tstd::cout << \"A is \" << A.rowdim() << \" by \" << A.coldim() << std::endl;\n\n\tGivaro::ZRing<Integer>::Element val_A;\n\n\tLinBox::Timer chrono; chrono.start();\n\tif (argc >= 3) {\n\t\tTranspose<Blackbox> T(&A);\n\t\tif (strcmp(argv[2],\"-ata\") == 0) {\n\t\t\tCompose< Transpose<Blackbox>, Blackbox > C (&T, &A);\n\t\t\tstd::cout << \"A^T A is \" << C.rowdim() << \" by \" << C.coldim() << std::endl;\n\t\t\tvalence(val_A, C);\n\t\t}\n\t\telse if (strcmp(argv[2],\"-aat\") == 0) {\n\t\t\tCompose< Blackbox, Transpose<Blackbox> > C (&A, &T);\n\t\t\tstd::cout << \"A A^T is \" << C.rowdim() << \" by \" << C.coldim() << std::endl;\n\t\t\tvalence(val_A, C);\n\t\t}\n\t\telse {\n\t\t\tstd::cout << \"Suppose primes are contained in \" << argv[2] << std::endl;\n\t\t\tval_A = LinBox::Integer(argv[2]);\n\t\t}\n\t}\n\telse {\n\t\tif (A.rowdim() != A.coldim()) {\n\t\t\tstd::cerr << \"Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options.\" << std::endl;\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t\tvalence (val_A, A);\n\t}\n\n\tstd::cout << \"Valence is \" << val_A << std::endl;\n\n\tstd::vector<Givaro::Integer> Moduli;\n\tstd::vector<size_t> exponents;\n\tGivaro::IntFactorDom<> FTD;\n\n\tstd::vector< PairIntRk > smith;\n\n\n Givaro::Integer coprimeV=2;\n\tif (argc >= 4) {\n\t\tcoprimeV =Givaro::Integer(argv[3]);\n\t}\n\twhile ( gcd(val_A,coprimeV) > 1 ) {\n\t\tFTD.nextprimein(coprimeV);\n\t}\n\n\tif (argc >= 4) {\n\t\tstd::cout << \"Suppose \" << argv[3] << \" is coprime with Smith form\" << std::endl;\n\t}\n\nstd::cout << \"Some factors (50000 factoring loop bound): \";\n\tFTD.set(Moduli, exponents, val_A, 50000);\n\tstd::vector<size_t>::const_iterator eit=exponents.begin();\n\tfor(std::vector<Givaro::Integer>::const_iterator mit=Moduli.begin();\n\t mit != Moduli.end(); ++mit,++eit)\n\t\tstd::cout << *mit << '^' << *eit << ' ';\n\tstd::cout << std::endl;\n smith.resize(Moduli.size());\n\n size_t coprimeR; \n \n\tstd::cout << \"num procs: \" << omp_get_num_procs() << std::endl;\n\tstd::cout << \"num threads: \" << NUM_THREADS << std::endl;\n\tstd::cout << \"max threads: \" << MAX_THREADS << std::endl;\n\n#pragma omp parallel \n {\n#pragma omp single\n {\n for(size_t j=0; j<Moduli.size(); ++j) {\n smith[j].first = Moduli[j];\n#pragma omp task shared(smith,argv) firstprivate(j)\n LRank(smith[j].second, argv[1], smith[j].first);\n }\n LRank(coprimeR, argv[1], coprimeV);\n }\n\t}\n\n std::vector<Givaro::Integer> SmithDiagonal(coprimeR,Givaro::Integer(1));\n \n\/\/ #pragma omp parallel for shared(SmithDiagonal, smith, exponents)\n\/\/ \tfor(size_t j=0; j<Moduli.size(); ++j) {\n \n\/\/ if (smith[j].second != coprimeR) {\n\/\/ std::vector<size_t> ranks;\n\/\/ const PairIntRk& smithj(smith[j]);\n\/\/ const size_t& exponentsj(exponents[j]);\n\n\/\/ AllPowersRanks(ranks, smithj, exponentsj, coprimeR, argv[1]);\n\n\/\/ #pragma omp critical\n\/\/ {\n\/\/ populateSmithForm(SmithDiagonal, ranks, smithj, coprimeR);\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ std::vector<size_t> * AllRanks = new std::vector<size_t>[Moduli.size()];\n\n\/\/ #pragma omp parallel \n\/\/ {\n\/\/ for(size_t j=0; j<Moduli.size(); ++j) {\n \n\/\/ if (smith[j].second != coprimeR) {\n\/\/ \/\/ std::vector<size_t>& ranksj(AllRanks[j]);\n\/\/ const PairIntRk& smithj(smith[j]);\n\/\/ const size_t& exponentsj(exponents[j]);\n\/\/ #pragma omp task depend(out: AllRanks[j]) shared(smithj, exponentsj, coprimeR)\n\/\/ {\n\/\/ AllPowersRanks(AllRanks[j], smithj, exponentsj, coprimeR, argv[1]); \n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n \n\n\/\/ for(size_t j=0; j<Moduli.size(); ++j) {\n\/\/ if (smith[j].second != coprimeR) {\n\/\/ populateSmithForm(SmithDiagonal, AllRanks[j], smith[j], coprimeR);\n\/\/ }\n\/\/ }\n \n\n\n\n\n\n std::vector<size_t> * AllRanks = new std::vector<size_t>[Moduli.size()];\n PAR_BLOCK {\n for(size_t j=0; j<Moduli.size(); ++j) {\n if (smith[j].second != coprimeR) {\n\/\/ std::vector<size_t>& ranks(AllRanks[j]);\n const PairIntRk& smithj(smith[j]);\n const size_t& exponentsj(exponents[j]);\n { TASK(MODE(CONSTREFERENCE(smithj, exponentsj, coprimeR) WRITE(AllRanks[j])),\n {\n AllPowersRanks(AllRanks[j], smithj, exponentsj, coprimeR, argv[1]);\n })}\n }\n }\n }\n \n for(size_t j=0; j<Moduli.size(); ++j) {\n if (smith[j].second != coprimeR) {\n populateSmithForm(SmithDiagonal, AllRanks[j], smith[j], coprimeR);\n }\n }\n \n delete [] AllRanks;\n \n\/\/ SYNCH_GROUP(\n\/\/ FORBLOCK1D(iter, Moduli.size(), SPLITTER(),\n\/\/ TASK(MODE( \n\/\/ CONSTREFERENCE(SmithDiagonal, smith, exponents, coprimeR) ),\n\/\/ {\n\/\/ for(size_t j=iter.begin(); j != iter.end(); ++j) { \n\/\/ if (smith[j].second != coprimeR) {\n\/\/ std::vector<size_t> ranks;\n\/\/ AllPowersRanks(ranks, smith[j], exponents[j], coprimeR, argv[1]);\n \n\/\/ #pragma omp critical\n\/\/ { \n\n\/\/ populateSmithForm(SmithDiagonal, ranks, smith[j], coprimeR);\n\/\/ }\n\/\/ }\n\/\/ \t}\n\/\/ })\n\/\/ );\n\/\/ );\n \n\tchrono.stop();\n\n Givaro::Integer si=1;\n\tsize_t num=0;\n\tstd::cerr << \"Integer Smith Form :\" << std::endl;\n std::cout << '(';\n\tfor( std::vector<Givaro::Integer>::const_iterator dit=SmithDiagonal.begin();\n\t dit != SmithDiagonal.end(); ++dit) {\n\t\tif (*dit == si) ++num;\n\t\telse {\n\t\t\tstd::cerr << '[' << si << ',' << num << \"] \";\n\t\t\tnum=1;\n\t\t\tsi = *dit;\n\t\t}\n\t}\n\tstd::cerr << '[' << si << ',' << num << \"] \";\n\tnum = std::min(A.rowdim(),A.coldim()) - SmithDiagonal.size();\n\tsi = ZZ.zero;\n\tif (num > 0) std::cout << '[' << si << ',' << num << ']';\n\tstd::cout << ')' << std::endl;\n\tstd::cerr << chrono << std::endl;\n\n\n\treturn 0;\n}\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ tab-width: 4\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 4\n\/\/ End:\n\/\/ vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n<|endoftext|>"} {"text":"<commit_before>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/gadgetConfig.h>\n\n#include <vpr\/vpr.h>\n#include <vpr\/Sync\/Guard.h>\n#include <vpr\/Util\/Assert.h>\n\n#include <gadget\/Type\/EventWindow.h>\n\n\nnamespace gadget\n{\n\nvpr::ReturnStatus EventWindow::writeObject(vpr::ObjectWriter* writer)\n{\n writer->writeUint16(MSG_DATA_KEYBOARD); \/\/ Write out the data type so that we can assert if reading in wrong place\n writer->writeUint16(256);\n\n for ( unsigned i = 0; i < 256; ++i )\n {\n writer->writeUint16(mCurKeys[i]);\n }\n\n return vpr::ReturnStatus::Succeed;\n}\n\nvpr::ReturnStatus EventWindow::readObject(vpr::ObjectReader* reader)\n{\n \/\/vprASSERT(reader->attribExists(\"rim.timestamp.delta\"));\n \/\/vpr::Uint64 delta = reader->getAttrib<vpr::Uint64>(\"rim.timestamp.delta\");\n\n \/\/ ASSERT if this data is really not Digital Data\n vpr::Uint16 temp = reader->readUint16();\n vprASSERT(temp==MSG_DATA_KEYBOARD && \"[Remote Input Manager]Not Digital Data\");\n unsigned numVectors = reader->readUint16();\n\n for (unsigned i = 0; i < numVectors; ++i )\n {\n mCurKeys[i] = reader->readUint16();\n }\n\n return vpr::ReturnStatus::Succeed;\n}\n\n\/**\n * Checks for the given modifier key pressed only.\n * @return true if key pressed exclusively.\n *\/\n\/\/virtual bool modifierOnly(int modKey) =0;\nbool EventWindow::modifierOnly(gadget::Keys modKey)\n{\n switch (modKey)\n {\n case gadget::KEY_NONE:\n return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_SHIFT:\n return (mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_CTRL:\n return (!mCurKeys[gadget::KEY_SHIFT] && mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_ALT:\n return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && mCurKeys[gadget::KEY_ALT]);\n default:\n vprASSERT(false);\n return 0;\n }\n}\n\nstd::string EventWindow::getKeyName(gadget::Keys keyId)\n{\n switch(keyId)\n {\n case gadget::KEY_NONE: return std::string(\"VJKEY_NONE\");\n case gadget::KEY_UP: return std::string(\"VJKEY_UP\");\n case gadget::KEY_DOWN: return std::string(\"VJKEY_DOWN\");\n case gadget::KEY_LEFT: return std::string(\"VJKEY_LEFT\");\n case gadget::KEY_RIGHT: return std::string(\"VJKEY_RIGHT\");\n case gadget::KEY_SHIFT: return std::string(\"VJKEY_SHIFT\");\n case gadget::KEY_CTRL: return std::string(\"VJKEY_CTRL\");\n case gadget::KEY_ALT: return std::string(\"VJKEY_ALT\");\n case gadget::KEY_1: return std::string(\"VJKEY_1\");\n case gadget::KEY_2: return std::string(\"VJKEY_2\");\n case gadget::KEY_3: return std::string(\"VJKEY_3\");\n case gadget::KEY_4: return std::string(\"VJKEY_4\");\n case gadget::KEY_5: return std::string(\"VJKEY_5\");\n case gadget::KEY_6: return std::string(\"VJKEY_6\");\n case gadget::KEY_7: return std::string(\"VJKEY_7\");\n case gadget::KEY_8: return std::string(\"VJKEY_8\");\n case gadget::KEY_9: return std::string(\"VJKEY_9\");\n case gadget::KEY_0: return std::string(\"VJKEY_0\");\n case gadget::KEY_A: return std::string(\"VJKEY_A\");\n case gadget::KEY_B: return std::string(\"VJKEY_B\");\n case gadget::KEY_C: return std::string(\"VJKEY_C\");\n case gadget::KEY_D: return std::string(\"VJKEY_D\");\n case gadget::KEY_E: return std::string(\"VJKEY_E\");\n case gadget::KEY_F: return std::string(\"VJKEY_F\");\n case gadget::KEY_G: return std::string(\"VJKEY_G\");\n case gadget::KEY_H: return std::string(\"VJKEY_H\");\n case gadget::KEY_I: return std::string(\"VJKEY_I\");\n case gadget::KEY_J: return std::string(\"VJKEY_J\");\n case gadget::KEY_K: return std::string(\"VJKEY_K\");\n case gadget::KEY_L: return std::string(\"VJKEY_L\");\n case gadget::KEY_M: return std::string(\"VJKEY_M\");\n case gadget::KEY_N: return std::string(\"VJKEY_N\");\n case gadget::KEY_O: return std::string(\"VJKEY_O\");\n case gadget::KEY_P: return std::string(\"VJKEY_P\");\n case gadget::KEY_Q: return std::string(\"VJKEY_Q\");\n case gadget::KEY_R: return std::string(\"VJKEY_R\");\n case gadget::KEY_S: return std::string(\"VJKEY_S\");\n case gadget::KEY_T: return std::string(\"VJKEY_T\");\n case gadget::KEY_U: return std::string(\"VJKEY_U\");\n case gadget::KEY_V: return std::string(\"VJKEY_V\");\n case gadget::KEY_W: return std::string(\"VJKEY_W\");\n case gadget::KEY_X: return std::string(\"VJKEY_X\");\n case gadget::KEY_Y: return std::string(\"VJKEY_Y\");\n case gadget::KEY_Z: return std::string(\"VJKEY_Z\");\n case gadget::KEY_ESC: return std::string(\"VJKEY_ESC\");\n case gadget::MOUSE_POSX: return std::string(\"VJMOUSE_POSX\");\n case gadget::MOUSE_NEGX: return std::string(\"VJMOUSE_NEGX\");\n case gadget::MOUSE_POSY: return std::string(\"VJMOUSE_POSY\");\n case gadget::MOUSE_NEGY: return std::string(\"VJMOUSE_NEGY\");\n case gadget::MBUTTON1: return std::string(\"VJMBUTTON1\");\n case gadget::MBUTTON2: return std::string(\"VJMBUTTON2\");\n case gadget::MBUTTON3: return std::string(\"VJMBUTTON3\");\n }\n\n \/\/ If all of the above fell through ...\n return std::string(\"Unknown key\");\n}\n\nstd::queue<gadget::EventPtr> EventWindow::getEventQueue()\n{\n vpr::Guard<vpr::Mutex> guard(mCurEventQueueLock);\n return mCurEventQueue;\n}\n\nvoid EventWindow::addEvent(gadget::EventPtr e)\n{\n vpr::Guard<vpr::Mutex> guard(mWorkingEventQueueLock);\n mWorkingEventQueue.push(e);\n}\n\nvoid EventWindow::updateEventQueue()\n{\n vpr::Guard<vpr::Mutex> work_guard(mWorkingEventQueueLock);\n {\n vpr::Guard<vpr::Mutex> cur_guard(mCurEventQueueLock);\n mCurEventQueue = mWorkingEventQueue;\n }\n\n while ( ! mWorkingEventQueue.empty() )\n {\n mWorkingEventQueue.pop();\n }\n}\n\n} \/\/ End of gadget namespcae\n<commit_msg>Removed the \"VJ\" prefix from the symbolic key names returned by getKeyName(). I sincerely hope that no one was depending on these strings for anything other than debugging output.<commit_after>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/gadgetConfig.h>\n\n#include <vpr\/vpr.h>\n#include <vpr\/Sync\/Guard.h>\n#include <vpr\/Util\/Assert.h>\n\n#include <gadget\/Type\/EventWindow.h>\n\n\nnamespace gadget\n{\n\nvpr::ReturnStatus EventWindow::writeObject(vpr::ObjectWriter* writer)\n{\n writer->writeUint16(MSG_DATA_KEYBOARD); \/\/ Write out the data type so that we can assert if reading in wrong place\n writer->writeUint16(256);\n\n for ( unsigned i = 0; i < 256; ++i )\n {\n writer->writeUint16(mCurKeys[i]);\n }\n\n return vpr::ReturnStatus::Succeed;\n}\n\nvpr::ReturnStatus EventWindow::readObject(vpr::ObjectReader* reader)\n{\n \/\/vprASSERT(reader->attribExists(\"rim.timestamp.delta\"));\n \/\/vpr::Uint64 delta = reader->getAttrib<vpr::Uint64>(\"rim.timestamp.delta\");\n\n \/\/ ASSERT if this data is really not Digital Data\n vpr::Uint16 temp = reader->readUint16();\n vprASSERT(temp==MSG_DATA_KEYBOARD && \"[Remote Input Manager]Not Digital Data\");\n unsigned numVectors = reader->readUint16();\n\n for (unsigned i = 0; i < numVectors; ++i )\n {\n mCurKeys[i] = reader->readUint16();\n }\n\n return vpr::ReturnStatus::Succeed;\n}\n\n\/**\n * Checks for the given modifier key pressed only.\n * @return true if key pressed exclusively.\n *\/\n\/\/virtual bool modifierOnly(int modKey) =0;\nbool EventWindow::modifierOnly(gadget::Keys modKey)\n{\n switch (modKey)\n {\n case gadget::KEY_NONE:\n return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_SHIFT:\n return (mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_CTRL:\n return (!mCurKeys[gadget::KEY_SHIFT] && mCurKeys[gadget::KEY_CTRL] && !mCurKeys[gadget::KEY_ALT]);\n case gadget::KEY_ALT:\n return (!mCurKeys[gadget::KEY_SHIFT] && !mCurKeys[gadget::KEY_CTRL] && mCurKeys[gadget::KEY_ALT]);\n default:\n vprASSERT(false);\n return 0;\n }\n}\n\nstd::string EventWindow::getKeyName(gadget::Keys keyId)\n{\n switch(keyId)\n {\n case gadget::KEY_NONE: return std::string(\"KEY_NONE\");\n case gadget::KEY_UP: return std::string(\"KEY_UP\");\n case gadget::KEY_DOWN: return std::string(\"KEY_DOWN\");\n case gadget::KEY_LEFT: return std::string(\"KEY_LEFT\");\n case gadget::KEY_RIGHT: return std::string(\"KEY_RIGHT\");\n case gadget::KEY_SHIFT: return std::string(\"KEY_SHIFT\");\n case gadget::KEY_CTRL: return std::string(\"KEY_CTRL\");\n case gadget::KEY_ALT: return std::string(\"KEY_ALT\");\n case gadget::KEY_1: return std::string(\"KEY_1\");\n case gadget::KEY_2: return std::string(\"KEY_2\");\n case gadget::KEY_3: return std::string(\"KEY_3\");\n case gadget::KEY_4: return std::string(\"KEY_4\");\n case gadget::KEY_5: return std::string(\"KEY_5\");\n case gadget::KEY_6: return std::string(\"KEY_6\");\n case gadget::KEY_7: return std::string(\"KEY_7\");\n case gadget::KEY_8: return std::string(\"KEY_8\");\n case gadget::KEY_9: return std::string(\"KEY_9\");\n case gadget::KEY_0: return std::string(\"KEY_0\");\n case gadget::KEY_A: return std::string(\"KEY_A\");\n case gadget::KEY_B: return std::string(\"KEY_B\");\n case gadget::KEY_C: return std::string(\"KEY_C\");\n case gadget::KEY_D: return std::string(\"KEY_D\");\n case gadget::KEY_E: return std::string(\"KEY_E\");\n case gadget::KEY_F: return std::string(\"KEY_F\");\n case gadget::KEY_G: return std::string(\"KEY_G\");\n case gadget::KEY_H: return std::string(\"KEY_H\");\n case gadget::KEY_I: return std::string(\"KEY_I\");\n case gadget::KEY_J: return std::string(\"KEY_J\");\n case gadget::KEY_K: return std::string(\"KEY_K\");\n case gadget::KEY_L: return std::string(\"KEY_L\");\n case gadget::KEY_M: return std::string(\"KEY_M\");\n case gadget::KEY_N: return std::string(\"KEY_N\");\n case gadget::KEY_O: return std::string(\"KEY_O\");\n case gadget::KEY_P: return std::string(\"KEY_P\");\n case gadget::KEY_Q: return std::string(\"KEY_Q\");\n case gadget::KEY_R: return std::string(\"KEY_R\");\n case gadget::KEY_S: return std::string(\"KEY_S\");\n case gadget::KEY_T: return std::string(\"KEY_T\");\n case gadget::KEY_U: return std::string(\"KEY_U\");\n case gadget::KEY_V: return std::string(\"KEY_V\");\n case gadget::KEY_W: return std::string(\"KEY_W\");\n case gadget::KEY_X: return std::string(\"KEY_X\");\n case gadget::KEY_Y: return std::string(\"KEY_Y\");\n case gadget::KEY_Z: return std::string(\"KEY_Z\");\n case gadget::KEY_ESC: return std::string(\"KEY_ESC\");\n case gadget::MOUSE_POSX: return std::string(\"MOUSE_POSX\");\n case gadget::MOUSE_NEGX: return std::string(\"MOUSE_NEGX\");\n case gadget::MOUSE_POSY: return std::string(\"MOUSE_POSY\");\n case gadget::MOUSE_NEGY: return std::string(\"MOUSE_NEGY\");\n case gadget::MBUTTON1: return std::string(\"MBUTTON1\");\n case gadget::MBUTTON2: return std::string(\"MBUTTON2\");\n case gadget::MBUTTON3: return std::string(\"MBUTTON3\");\n }\n\n \/\/ If all of the above fell through ...\n return std::string(\"Unknown key\");\n}\n\nstd::queue<gadget::EventPtr> EventWindow::getEventQueue()\n{\n vpr::Guard<vpr::Mutex> guard(mCurEventQueueLock);\n return mCurEventQueue;\n}\n\nvoid EventWindow::addEvent(gadget::EventPtr e)\n{\n vpr::Guard<vpr::Mutex> guard(mWorkingEventQueueLock);\n mWorkingEventQueue.push(e);\n}\n\nvoid EventWindow::updateEventQueue()\n{\n vpr::Guard<vpr::Mutex> work_guard(mWorkingEventQueueLock);\n {\n vpr::Guard<vpr::Mutex> cur_guard(mCurEventQueueLock);\n mCurEventQueue = mWorkingEventQueue;\n }\n\n while ( ! mWorkingEventQueue.empty() )\n {\n mWorkingEventQueue.pop();\n }\n}\n\n} \/\/ End of gadget namespcae\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Copyright (C) 2012 Sergey Lisitsyn\n *\/\n\n#include <shogun\/transfer\/multitask\/MultitaskClusteredLogisticRegression.h>\n#include <shogun\/lib\/malsar\/malsar_clustered.h>\n#include <shogun\/lib\/malsar\/malsar_options.h>\n#include <shogun\/lib\/SGVector.h>\n\nnamespace shogun\n{\n\nCMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression() :\n\tCMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)\n{\n}\n\nCMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression(\n float64_t rho1, float64_t rho2, CDotFeatures* train_features,\n CBinaryLabels* train_labels, CTaskGroup* task_group, int32_t n_clusters) :\n\tCMultitaskLogisticRegression(0.0,train_features,train_labels,(CTaskRelation*)task_group)\n{\n\tset_rho1(rho1);\n\tset_rho2(rho2);\n\tset_num_clusters(n_clusters);\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_rho1() const\n{\n\treturn m_rho1;\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_rho2() const\n{\n\treturn m_rho2;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_rho1(float64_t rho1)\n{\n\tm_rho1 = rho1;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_rho2(float64_t rho2)\n{\n\tm_rho2 = rho2;\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_num_clusters() const\n{\n\treturn m_num_clusters;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_num_clusters(int32_t num_clusters)\n{\n\tm_num_clusters = num_clusters;\n}\n\nCMultitaskClusteredLogisticRegression::~CMultitaskClusteredLogisticRegression()\n{\n}\n\nbool CMultitaskClusteredLogisticRegression::train_locked_implementation(SGVector<index_t>* tasks)\n{\n\tSGVector<float64_t> y(m_labels->get_num_labels());\n\tfor (int32_t i=0; i<y.vlen; i++)\n\t\ty[i] = ((CBinaryLabels*)m_labels)->get_label(i);\n\n\tmalsar_options options = malsar_options::default_options();\n\toptions.termination = m_termination;\n\toptions.tolerance = m_tolerance;\n\toptions.max_iter = m_max_iter;\n\toptions.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();\n\toptions.tasks_indices = tasks;\n\toptions.n_clusters = m_num_clusters;\n\n#ifdef HAVE_EIGEN3\n#ifndef HAVE_CXX11\n\tmalsar_result_t model = malsar_clustered(\n\t\tfeatures, y.vector, m_rho1, m_rho2, options);\n\n\tm_tasks_w = model.w;\n\tm_tasks_c = model.c;\n#else\n\tSG_WARNING(\"Clustered LR is unstable with C++11\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_w.set_const(0);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n\tm_tasks_c.set_const(0);\n#endif\n#else\n\tSG_WARNING(\"Please install Eigen3 to use MultitaskClusteredLogisticRegression\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n#endif\n\treturn true;\n}\n\nbool CMultitaskClusteredLogisticRegression::train_machine(CFeatures* data)\n{\n\tif (data && (CDotFeatures*)data)\n\t\tset_features((CDotFeatures*)data);\n\n\tASSERT(features)\n\tASSERT(m_labels)\n\tASSERT(m_task_relation)\n\n\tSGVector<float64_t> y(m_labels->get_num_labels());\n\tfor (int32_t i=0; i<y.vlen; i++)\n\t\ty[i] = ((CBinaryLabels*)m_labels)->get_label(i);\n\n\tmalsar_options options = malsar_options::default_options();\n\toptions.termination = m_termination;\n\toptions.tolerance = m_tolerance;\n\toptions.max_iter = m_max_iter;\n\toptions.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();\n\toptions.tasks_indices = ((CTaskGroup*)m_task_relation)->get_tasks_indices();\n\toptions.n_clusters = m_num_clusters;\n\n#ifdef HAVE_EIGEN3\n#ifndef HAVE_CXX11\n\tmalsar_result_t model = malsar_clustered(\n\t\tfeatures, y.vector, m_rho1, m_rho2, options);\n\n\tm_tasks_w = model.w;\n\tm_tasks_c = model.c;\n#else\n\tSG_WARNING(\"Clustered LR is unstable with C++11\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n#endif\n#else\n\tSG_WARNING(\"Please install Eigen3 to use MultitaskClusteredLogisticRegression\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n#endif\n\n\tSG_FREE(options.tasks_indices);\n\n\treturn true;\n}\n\n}\n<commit_msg>Fixed MALSAR clustered LR fallback (affects #1360)<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Copyright (C) 2012 Sergey Lisitsyn\n *\/\n\n#include <shogun\/transfer\/multitask\/MultitaskClusteredLogisticRegression.h>\n#include <shogun\/lib\/malsar\/malsar_clustered.h>\n#include <shogun\/lib\/malsar\/malsar_options.h>\n#include <shogun\/lib\/SGVector.h>\n\nnamespace shogun\n{\n\nCMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression() :\n\tCMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)\n{\n}\n\nCMultitaskClusteredLogisticRegression::CMultitaskClusteredLogisticRegression(\n float64_t rho1, float64_t rho2, CDotFeatures* train_features,\n CBinaryLabels* train_labels, CTaskGroup* task_group, int32_t n_clusters) :\n\tCMultitaskLogisticRegression(0.0,train_features,train_labels,(CTaskRelation*)task_group)\n{\n\tset_rho1(rho1);\n\tset_rho2(rho2);\n\tset_num_clusters(n_clusters);\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_rho1() const\n{\n\treturn m_rho1;\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_rho2() const\n{\n\treturn m_rho2;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_rho1(float64_t rho1)\n{\n\tm_rho1 = rho1;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_rho2(float64_t rho2)\n{\n\tm_rho2 = rho2;\n}\n\nint32_t CMultitaskClusteredLogisticRegression::get_num_clusters() const\n{\n\treturn m_num_clusters;\n}\n\nvoid CMultitaskClusteredLogisticRegression::set_num_clusters(int32_t num_clusters)\n{\n\tm_num_clusters = num_clusters;\n}\n\nCMultitaskClusteredLogisticRegression::~CMultitaskClusteredLogisticRegression()\n{\n}\n\nbool CMultitaskClusteredLogisticRegression::train_locked_implementation(SGVector<index_t>* tasks)\n{\n\tSGVector<float64_t> y(m_labels->get_num_labels());\n\tfor (int32_t i=0; i<y.vlen; i++)\n\t\ty[i] = ((CBinaryLabels*)m_labels)->get_label(i);\n\n\tmalsar_options options = malsar_options::default_options();\n\toptions.termination = m_termination;\n\toptions.tolerance = m_tolerance;\n\toptions.max_iter = m_max_iter;\n\toptions.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();\n\toptions.tasks_indices = tasks;\n\toptions.n_clusters = m_num_clusters;\n\n#ifdef HAVE_EIGEN3\n#ifndef HAVE_CXX11\n\tmalsar_result_t model = malsar_clustered(\n\t\tfeatures, y.vector, m_rho1, m_rho2, options);\n\n\tm_tasks_w = model.w;\n\tm_tasks_c = model.c;\n#else\n\tSG_WARNING(\"Clustered LR is unstable with C++11\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_w.set_const(0);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n\tm_tasks_c.set_const(0);\n#endif\n#else\n\tSG_WARNING(\"Please install Eigen3 to use MultitaskClusteredLogisticRegression\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n#endif\n\treturn true;\n}\n\nbool CMultitaskClusteredLogisticRegression::train_machine(CFeatures* data)\n{\n\tif (data && (CDotFeatures*)data)\n\t\tset_features((CDotFeatures*)data);\n\n\tASSERT(features)\n\tASSERT(m_labels)\n\tASSERT(m_task_relation)\n\n\tSGVector<float64_t> y(m_labels->get_num_labels());\n\tfor (int32_t i=0; i<y.vlen; i++)\n\t\ty[i] = ((CBinaryLabels*)m_labels)->get_label(i);\n\n\tmalsar_options options = malsar_options::default_options();\n\toptions.termination = m_termination;\n\toptions.tolerance = m_tolerance;\n\toptions.max_iter = m_max_iter;\n\toptions.n_tasks = ((CTaskGroup*)m_task_relation)->get_num_tasks();\n\toptions.tasks_indices = ((CTaskGroup*)m_task_relation)->get_tasks_indices();\n\toptions.n_clusters = m_num_clusters;\n\n#ifdef HAVE_EIGEN3\n#ifndef HAVE_CXX11\n\tmalsar_result_t model = malsar_clustered(\n\t\tfeatures, y.vector, m_rho1, m_rho2, options);\n\n\tm_tasks_w = model.w;\n\tm_tasks_c = model.c;\n#else\n\tSG_WARNING(\"Clustered LR is unstable with C++11\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_w.set_const(0);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n\tm_tasks_c.set_const(0);\n#endif\n#else\n\tSG_WARNING(\"Please install Eigen3 to use MultitaskClusteredLogisticRegression\\n\")\n\tm_tasks_w = SGMatrix<float64_t>(((CDotFeatures*)features)->get_dim_feature_space(), options.n_tasks);\n\tm_tasks_c = SGVector<float64_t>(options.n_tasks);\n#endif\n\n\tSG_FREE(options.tasks_indices);\n\n\treturn true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-\n * Copyright (c) 2008 Michael Marner <michael@20papercups.net>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\n\/\/ include system headers\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n\/\/ include openGL headers\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/glut.h>\n\n#include <wcl\/video\/VideoDecoder.h>\n\nusing namespace std;\nusing namespace wcl;\n\nVideoDecoder *decoder;\n\nvoid usage()\n{\n printf(\"Usage: video filename\\n\");\n}\n\n\n\/**\n * Initialise OpenGL\n *\/\nGLvoid init()\n{\n\tunsigned char *data = new unsigned char[decoder->getWidth() * decoder->getHeight() * 3 \/* RGB *\/];\n\tglShadeModel(GL_SMOOTH);\n\tglClearColor(0,0,0,0);\n\tglEnable(GL_DEPTH_TEST);\n\tglDepthFunc(GL_LEQUAL);\n\n\t\/\/ create a texture for the image...\n\tglTexImage2D(GL_TEXTURE_2D, \/\/target\n\t\t\t\t 0, \/\/level of detail\n\t\t\t\t 3, \/\/colour components\n\t\t\t\t decoder->getWidth(), \/\/width\n\t\t\t\t decoder->getHeight(), \/\/height\n\t\t\t\t 0, \/\/border\n\t\t\t\t GL_RGB, \/\/image format\n\t\t\t\t GL_UNSIGNED_BYTE,\n\t\t\t\t data);\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);\n\n\tglEnable(GL_TEXTURE_2D);\n\n\tglMatrixMode(GL_PROJECTION);\n\tgluOrtho2D(0,1,0,1);\n\tglMatrixMode(GL_MODELVIEW);\n\tdelete data;\n}\n\n\n\/**\n * Constantly fetch a new image from the camera to display\n *\/\nGLvoid idle()\n{\n\tglutPostRedisplay();\n}\n\n\n\/**\n * Display Loop.\n *\/\nGLvoid display()\n{\n\tglClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n\n\tconst unsigned char* frame = decoder->getFrame();\n\tif( frame == NULL ){\n\t \/\/ No more frames\n\t exit(1);\n\t}\n\n\tglTexSubImage2D(GL_TEXTURE_2D,\n\t 0,\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\tdecoder->getWidth(),\n\t\t\t\t\tdecoder->getHeight(),\n\t\t\t\t\tGL_RGB,\n\t\t\t\t\tGL_UNSIGNED_BYTE,\n\t\t\t\t\tframe);\n\n\tglMatrixMode(GL_MODELVIEW);\n\n\tglLoadIdentity();\n\t\tglBegin(GL_QUADS);\n\n\t\tglTexCoord2f(0,1);\n\t\tglVertex2f(0,0);\n\n\t\tglTexCoord2f(1,1);\n\t\tglVertex2f(1,0);\n\n\t\tglTexCoord2f(1,0);\n\t\tglVertex2f(1,1);\n\n\t\tglTexCoord2f(0,0);\n\t\tglVertex2f(0,1);\n\tglEnd();\n\n\n\tglRasterPos2d( 0, 0);\n\n\tglDisable(GL_TEXTURE_2D);\n\tchar buffer[100];\n\tsprintf(buffer, \"[Video Test] Frame: %lld - %2.2f FPS\", \n\t\tdecoder->getCurrentFrame(),\n\t\tdecoder->getFPS());\n\tfor(char *c=buffer; *c != '\\0'; c++)\n\t glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,*c);\n\tglEnable(GL_TEXTURE_2D);\n\n\tglFlush();\n\tglutSwapBuffers();\n\n\t\/\/ print out any opengl errors to the console\n\tGLenum error = glGetError();\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tcout << gluErrorString(error) << endl;\n\t}\n}\n\n\n\/**\n * This doesn't do what it is supposed to do!\n *\/\nGLvoid reshape(int width, int height)\n{\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluOrtho2D(0,1,0,1);\n\tglMatrixMode(GL_MODELVIEW);\n}\n\nvoid keyboard(unsigned char key, int w, int h)\n{\n if(key==27)\n\texit(EXIT_SUCCESS);\n}\n\nint main(int argc, char** argv)\n{\n if(argc < 2 ){\n\t\tusage();\n\t\treturn 1;\n }\n\n\ttry {\n\t\tcout << \"Opening Video... \";\n\n\t\tdecoder = new VideoDecoder(argv[1]);\n\n\t\tcout << \"Done!\" << endl;\n\n\t\t\/\/ Create GLUT window\n\t\tglutInit(&argc, argv);\n\t\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n\t\tglutInitWindowSize(decoder->getWidth(), decoder->getHeight());\n\t\tglutCreateWindow(argv[0]);\n\n\t\tinit();\n\n\t\t\/\/ register callbacks\n\t\tglutDisplayFunc(display);\n\t\tglutReshapeFunc(reshape);\n\t\tglutKeyboardFunc(keyboard);\n\t\tglutIdleFunc(idle);\n\n\t\t\/\/ GO!\n\t\tglutMainLoop();\n\n\t\tdelete decoder;\n\n\t}\n\tcatch (std::string s)\n\t{\n\t\tcout << \"Exception Occured: \" << s << endl;\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>examples: Play the video at it intended speed, allow window resizing<commit_after>\/*-\n * Copyright (c) 2008 Michael Marner <michael@20papercups.net>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\n\/\/ include system headers\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n\/\/ include openGL headers\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/glut.h>\n\n#include <wcl\/video\/VideoDecoder.h>\n\nusing namespace std;\nusing namespace wcl;\n\nVideoDecoder *decoder;\n\nvoid usage()\n{\n printf(\"Usage: video filename\\n\");\n}\n\n\n\/**\n * Initialise OpenGL\n *\/\nGLvoid init()\n{\n\tunsigned char *data = new unsigned char[decoder->getWidth() * decoder->getHeight() * 3 \/* RGB *\/];\n\tglShadeModel(GL_SMOOTH);\n\tglClearColor(0,0,0,0);\n\tglEnable(GL_DEPTH_TEST);\n\tglDepthFunc(GL_LEQUAL);\n\n\t\/\/ create a texture for the image...\n\tglTexImage2D(GL_TEXTURE_2D, \/\/target\n\t\t\t\t 0, \/\/level of detail\n\t\t\t\t 3, \/\/colour components\n\t\t\t\t decoder->getWidth(), \/\/width\n\t\t\t\t decoder->getHeight(), \/\/height\n\t\t\t\t 0, \/\/border\n\t\t\t\t GL_RGB, \/\/image format\n\t\t\t\t GL_UNSIGNED_BYTE,\n\t\t\t\t data);\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);\n\n\tglEnable(GL_TEXTURE_2D);\n\n\tglMatrixMode(GL_PROJECTION);\n\tgluOrtho2D(0,1,0,1);\n\tglMatrixMode(GL_MODELVIEW);\n\tdelete data;\n}\n\n\n\/**\n * Constantly fetch a new image from the camera to display\n *\/\nGLvoid idle()\n{\n\tglutPostRedisplay();\n}\n\n\n\/**\n * Display Loop.\n *\/\nGLvoid display()\n{\n\tglClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n\n\tconst unsigned char* frame = decoder->getFrame();\n\tif( frame == NULL ){\n\t \/\/ No more frames\n\t exit(1);\n\t}\n\n\tglTexSubImage2D(GL_TEXTURE_2D,\n\t 0,\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\tdecoder->getWidth(),\n\t\t\t\t\tdecoder->getHeight(),\n\t\t\t\t\tGL_RGB,\n\t\t\t\t\tGL_UNSIGNED_BYTE,\n\t\t\t\t\tframe);\n\n\tglMatrixMode(GL_MODELVIEW);\n\n\tglLoadIdentity();\n\t\tglBegin(GL_QUADS);\n\n\t\tglTexCoord2f(0,1);\n\t\tglVertex2f(0,0);\n\n\t\tglTexCoord2f(1,1);\n\t\tglVertex2f(1,0);\n\n\t\tglTexCoord2f(1,0);\n\t\tglVertex2f(1,1);\n\n\t\tglTexCoord2f(0,0);\n\t\tglVertex2f(0,1);\n\tglEnd();\n\n\n\tglRasterPos2d( 0, 0);\n\n\tglDisable(GL_TEXTURE_2D);\n\tchar buffer[100];\n\tsprintf(buffer, \"[Video Test] Frame: %lld - %2.2f FPS\", \n\t\tdecoder->getCurrentFrame(),\n\t\tdecoder->getFPS());\n\tfor(char *c=buffer; *c != '\\0'; c++)\n\t glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,*c);\n\tglEnable(GL_TEXTURE_2D);\n\n\tglFlush();\n\tglutSwapBuffers();\n\n\t\/\/ print out any opengl errors to the console\n\tGLenum error = glGetError();\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tcout << gluErrorString(error) << endl;\n\t}\n}\n\n\n\/**\n * This doesn't do what it is supposed to do!\n *\/\nGLvoid reshape(int width, int height)\n{\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluOrtho2D(0,1,0,1);\n\tglMatrixMode(GL_MODELVIEW);\n\tglViewport(0,0, (GLsizei)width, (GLsizei)height);\n}\n\nvoid keyboard(unsigned char key, int w, int h)\n{\n if(key==27)\n\texit(EXIT_SUCCESS);\n}\n\nint main(int argc, char** argv)\n{\n if(argc < 2 ){\n\t\tusage();\n\t\treturn 1;\n }\n\n\ttry {\n\t\tcout << \"Opening Video... \";\n\n\t\tdecoder = new VideoDecoder(argv[1],true);\n\n\t\tcout << \"Done!\" << endl;\n\n\t\t\/\/ Create GLUT window\n\t\tglutInit(&argc, argv);\n\t\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n\t\tglutInitWindowSize(decoder->getWidth(), decoder->getHeight());\n\t\tglutCreateWindow(argv[0]);\n\n\t\tinit();\n\n\t\t\/\/ register callbacks\n\t\tglutDisplayFunc(display);\n\t\tglutReshapeFunc(reshape);\n\t\tglutKeyboardFunc(keyboard);\n\t\tglutIdleFunc(idle);\n\n\t\t\/\/ GO!\n\t\tglutMainLoop();\n\n\t\tdelete decoder;\n\n\t}\n\tcatch (std::string s)\n\t{\n\t\tcout << \"Exception Occured: \" << s << endl;\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* exonerate_fastparse.cpp\n * \n * Reads raw exonerate output (from STDIN)\n *\n *\/\n\n#define BUFFER_SIZE 4096\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string>\n#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <getopt.h>\nusing namespace std;\n\nstring get_sans_introns_header();\nstring get_with_introns_header();\nstring get_simple_header();\n\nstring parse_simple(string line, int stop, char delim);\nstring parse_sans_introns(string line, int stop, char delim);\nstring parse_with_introns(string line, int stop, char delim);\nstring parse_verbose(string line, int stop, char delim);\nint get_first_integer(string line);\nint get_stop_position(string line, int offset);\n\nint main(int argc, char **argv)\n{\n\n int format = 0;\n int c;\n\n while (1) {\n static struct option long_options[] =\n {\n {\"simple\", no_argument, &format, 0}, \n {\"sans-introns\", no_argument, &format, 1}, \n {\"with-introns\", no_argument, &format, 2}, \n {\"verbose\", no_argument, &format, 3},\n {\"help\", no_argument, 0, 'h'},\n {0,0,0,0}\n };\n int option_index = 0;\n c = getopt_long (argc, argv, \"h\", long_options, &option_index);\n\n \/* Detect the end of the options. *\/\n if (c == -1)\n break;\n\n switch(c) {\n case 0:\n break;\n case 'h':\n cout << \"Usage: exonerate-fastparse [options] filename\" << endl\n << \"Format options:\" << endl\n << \" --simple - writes tabular output with the following columns:\" << endl\n << \" 1. query_seqid\" << endl\n << \" 2. query_start\" << endl\n << \" 3. query_stop\" << endl\n << \" 4. query_strand\" << endl\n << \" 5. target_seqid\" << endl\n << \" 6. target_start\" << endl\n << \" 7. target_stop\" << endl\n << \" 8. target_strand\" << endl\n << \" 9. score\" << endl\n << \" --sans-introns - adds 5 columns to the simple output\" << endl\n << \" 10. first_stop\" << endl\n << \" 11. has_frameshift\" << endl\n << \" 12. split_codons\" << endl\n << \" 13. introns\" << endl\n << \" 14. max_introns\" << endl\n << \" --with-introns - adds 1 column to the sans-introns output\" << endl\n << \" 15. intron_lengths - a comma-delimited list of intron lengths\" << endl\n << \" --verbose\\tprints simple tabular output and then one line for each gff entry\" << endl;\n return 0;\n }\n }\n\n string (*parse)(string, int, char);\n\n switch(format) {\n case 0:\n cout << get_simple_header() << endl;\n parse = parse_simple;\n break;\n case 1:\n cout << get_sans_introns_header() << endl;\n parse = parse_sans_introns;\n break;\n case 2:\n cout << get_with_introns_header() << endl;\n parse = parse_with_introns;\n break;\n case 3:\n parse = parse_verbose;\n break;\n }\n\n \/\/ buffer to hold data input\n char buffer[BUFFER_SIZE];\n\n \/\/ string to hold line input\n string line;\n\n \/\/ index for ordering within a record\n int position = 0;\n\n \/\/ flag for being within the alignment region of a record\n bool between = true;\n\n \/\/ query start position for current alignment segment\n int running_position = 0;\n\n \/\/ position of first stop codon, 0 indicates none found\n int stop = 0;\n\n \/\/ temporary storage for output of get_stop_position\n int tmp_stop;\n\n while(fgets(buffer, BUFFER_SIZE, stdin)){\n\n \/\/ cast the cstring as a string object\n line = buffer;\n\n if(between){\n if(line.length() > 3 && line.substr(2,6) == \"Target\"){\n position = 1; \n between = false;\n }\n continue;\n }\n\n switch(position % 5) {\n case 2: if(line[0] == 'v'){\n cout << parse(line, stop, '\\t') << endl;\n between = true;\n stop = 0;\n } else {\n running_position = get_first_integer(line);\n }\n break;\n case 4: if(stop == 0) {\n tmp_stop = get_stop_position(line, running_position);\n if(tmp_stop != 0 && stop == 0){\n stop = tmp_stop; \n }\n }\n break;\n }\n\n position++;\n }\n}\n\nint get_stop_position(string line, int pos){\n for(unsigned int i = 0; i < line.length(); i++){\n \/\/ All capital letters signal a new amino acid\n if(line[i] >= 'A' && line[i] <= 'Z'){\n pos++; \n }\n \/\/ I am interested only in the position of the first stop,\n \/\/ so return when first '*' is encountered\n else if(line[i] == '*'){\n return(pos);\n }\n }\n \/\/ Return 0 if no stop is found\n return 0;\n}\n\nint get_first_integer(string line){\n int x;\n std::stringstream ss;\n ss << line;\n ss >> x;\n return x;\n}\n\nstring get_simple_header(){\n string header = \"query_seqid\\t\" \n \"query_start\\t\" \n \"query_stop\\t\" \n \"query_strand\\t\" \n \"target_contig\\t\" \n \"target_start\\t\" \n \"target_stop\\t\" \n \"target_strand\\t\" \n \"score\\t\";\n return header;\n}\n\nstring get_sans_introns_header(){\n string header = get_simple_header();\n header += \"first_stop\\t\" \n \"has_frameshift\\t\" \n \"split_codons\\t\" \n \"introns\\t\" \n \"max_intron\";\n return header;\n}\n\nstring get_with_introns_header(){\n string header = get_sans_introns_header();\n header += \"\\tintron_lengths\";\n return header;\n}\n\nstring parse_sans_introns(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 10 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n out << stop << delim;\n bool shifted = false;\n int nintrons = 0;\n int splits = 0;\n int longest_intron = 0;\n while(s >> word){\n switch(word[0]){\n case 'F': shifted = true;\n break;\n case 'I': { nintrons++;\n s >> word;\n s >> word;\n int len = atoi(word.c_str());\n if(len > longest_intron)\n longest_intron = len;\n }\n break;\n case 'S': splits++;\n break;\n }\n }\n out << shifted << delim\n << splits << delim\n << nintrons << delim\n << longest_intron;\n return out.str();\n}\n\nstring parse_with_introns(string line, int stop, char delim){\n stringstream out;\n stringstream s(line);\n out << parse_sans_introns(line, stop, delim) << delim;\n string word;\n bool has_intron = false;\n while(s >> word){\n if(word[0] == 'I'){\n s >> word;\n s >> word;\n if(has_intron)\n out << ',';\n out << word;\n has_intron = true; \n }\n }\n if(! has_intron)\n out << '-';\n return out.str();\n}\n\nstring parse_simple(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 9 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n s >> word;\n out << word;\n return out.str();\n}\n\nstring parse_verbose(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 10 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n out << stop << endl;\n for(int i = 0; s >> word; i++){\n if(i % 3 == 0)\n out << \"> \";\n out << word;\n out << ((i % 3 != 2) ? delim : '\\n');\n }\n return out.str();\n}\n<commit_msg>abstracted header handling<commit_after>\/* exonerate_fastparse.cpp\n * \n * Reads raw exonerate output (from STDIN)\n *\n *\/\n\n#define BUFFER_SIZE 4096\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string>\n#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <getopt.h>\nusing namespace std;\n\nstring get_sans_introns_header();\nstring get_with_introns_header();\nstring get_simple_header();\n\nstring parse_simple(string line, int stop, char delim);\nstring parse_sans_introns(string line, int stop, char delim);\nstring parse_with_introns(string line, int stop, char delim);\nstring parse_verbose(string line, int stop, char delim);\nint get_first_integer(string line);\nint get_stop_position(string line, int offset);\n\nint main(int argc, char **argv)\n{\n\n int format = 0;\n int c;\n bool header = true;\n\n while (1) {\n static struct option long_options[] =\n {\n {\"simple\", no_argument, &format, 0}, \n {\"sans-introns\", no_argument, &format, 1}, \n {\"with-introns\", no_argument, &format, 2}, \n {\"verbose\", no_argument, &format, 3},\n {\"help\", no_argument, 0, 'h'},\n {\"no-header\", no_argument, 0, 's'},\n {0,0,0,0}\n };\n int option_index = 0;\n c = getopt_long (argc, argv, \"hs\", long_options, &option_index);\n\n \/* Detect the end of the options. *\/\n if (c == -1)\n break;\n\n switch(c) {\n case 0:\n break;\n case 's':\n header = false;\n break;\n case 'h':\n cout << \"Usage: exonerate-fastparse [options] filename\" << endl\n << \"Format options:\" << endl\n << \" --simple - writes tabular output with the following columns:\" << endl\n << \" 1. query_seqid\" << endl\n << \" 2. query_start\" << endl\n << \" 3. query_stop\" << endl\n << \" 4. query_strand\" << endl\n << \" 5. target_seqid\" << endl\n << \" 6. target_start\" << endl\n << \" 7. target_stop\" << endl\n << \" 8. target_strand\" << endl\n << \" 9. score\" << endl\n << \" --sans-introns - adds 5 columns to the simple output\" << endl\n << \" 10. first_stop - first stop codon in alignment\" << endl\n << \" 11. has_frameshift - is there a frameshift? [01]\" << endl\n << \" 12. split_codons - number of codons split by introns\" << endl\n << \" 13. introns - total number of introns\" << endl\n << \" 14. max_introns - longest single intron\" << endl\n << \" --with-introns - adds 1 column to the sans-introns output\" << endl\n << \" 15. intron_lengths - a comma-delimited list of intron lengths\" << endl\n << \" --verbose - prints simple tabular output and then one line for each gff entry\" << endl;\n return 0;\n }\n }\n\n string (*parse)(string, int, char);\n string (*get_header)(void);\n\n switch(format) {\n case 0:\n get_header = get_simple_header;\n parse = parse_simple;\n break;\n case 1:\n get_header = get_sans_introns_header;\n parse = parse_sans_introns;\n break;\n case 2:\n get_header = get_with_introns_header;\n parse = parse_with_introns;\n break;\n case 3:\n header = false;\n parse = parse_verbose;\n break;\n }\n\n if(header)\n cout << get_header() << endl;\n\n \/\/ buffer to hold data input\n char buffer[BUFFER_SIZE];\n\n \/\/ string to hold line input\n string line;\n\n \/\/ index for ordering within a record\n int position = 0;\n\n \/\/ flag for being within the alignment region of a record\n bool between = true;\n\n \/\/ query start position for current alignment segment\n int running_position = 0;\n\n \/\/ position of first stop codon, 0 indicates none found\n int stop = 0;\n\n \/\/ temporary storage for output of get_stop_position\n int tmp_stop;\n\n while(fgets(buffer, BUFFER_SIZE, stdin)){\n\n \/\/ cast the cstring as a string object\n line = buffer;\n\n if(between){\n if(line.length() > 3 && line.substr(2,6) == \"Target\"){\n position = 1; \n between = false;\n }\n continue;\n }\n\n switch(position % 5) {\n case 2: if(line[0] == 'v'){\n cout << parse(line, stop, '\\t') << endl;\n between = true;\n stop = 0;\n } else {\n running_position = get_first_integer(line);\n }\n break;\n case 4: if(stop == 0) {\n tmp_stop = get_stop_position(line, running_position);\n if(tmp_stop != 0 && stop == 0){\n stop = tmp_stop; \n }\n }\n break;\n }\n\n position++;\n }\n}\n\nint get_stop_position(string line, int pos){\n for(unsigned int i = 0; i < line.length(); i++){\n \/\/ All capital letters signal a new amino acid\n if(line[i] >= 'A' && line[i] <= 'Z'){\n pos++; \n }\n \/\/ I am interested only in the position of the first stop,\n \/\/ so return when first '*' is encountered\n else if(line[i] == '*'){\n return(pos);\n }\n }\n \/\/ Return 0 if no stop is found\n return 0;\n}\n\nint get_first_integer(string line){\n int x;\n std::stringstream ss;\n ss << line;\n ss >> x;\n return x;\n}\n\nstring get_simple_header(){\n string header = \"query_seqid\\t\" \n \"query_start\\t\" \n \"query_stop\\t\" \n \"query_strand\\t\" \n \"target_contig\\t\" \n \"target_start\\t\" \n \"target_stop\\t\" \n \"target_strand\\t\" \n \"score\\t\";\n return header;\n}\n\nstring get_sans_introns_header(){\n string header = get_simple_header();\n header += \"first_stop\\t\" \n \"has_frameshift\\t\" \n \"split_codons\\t\" \n \"introns\\t\" \n \"max_intron\";\n return header;\n}\n\nstring get_with_introns_header(){\n string header = get_sans_introns_header();\n header += \"\\tintron_lengths\";\n return header;\n}\n\nstring parse_sans_introns(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 10 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n out << stop << delim;\n bool shifted = false;\n int nintrons = 0;\n int splits = 0;\n int longest_intron = 0;\n while(s >> word){\n switch(word[0]){\n case 'F': shifted = true;\n break;\n case 'I': { nintrons++;\n s >> word;\n s >> word;\n int len = atoi(word.c_str());\n if(len > longest_intron)\n longest_intron = len;\n }\n break;\n case 'S': splits++;\n break;\n }\n }\n out << shifted << delim\n << splits << delim\n << nintrons << delim\n << longest_intron;\n return out.str();\n}\n\nstring parse_with_introns(string line, int stop, char delim){\n stringstream out;\n stringstream s(line);\n out << parse_sans_introns(line, stop, delim) << delim;\n string word;\n bool has_intron = false;\n while(s >> word){\n if(word[0] == 'I'){\n s >> word;\n s >> word;\n if(has_intron)\n out << ',';\n out << word;\n has_intron = true; \n }\n }\n if(! has_intron)\n out << '-';\n return out.str();\n}\n\nstring parse_simple(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 9 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n s >> word;\n out << word;\n return out.str();\n}\n\nstring parse_verbose(string line, int stop, char delim){\n stringstream s(line);\n stringstream out;\n string word;\n for(int i = 0; i < 10 && s >> word; i++){\n if(i > 0){\n out << word << delim;\n }\n }\n out << stop << endl;\n for(int i = 0; s >> word; i++){\n if(i % 3 == 0)\n out << \"> \";\n out << word;\n out << ((i % 3 != 2) ? delim : '\\n');\n }\n return out.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/monitor\/common\/can_checker_factory.h\"\n\n#include \"modules\/monitor\/hwmonitor\/hw\/esdcan\/esdcan_checker.h\"\n\n\/**\n * @file: hw_checker_factory.cc\n *\/\n\nnamespace apollo {\nnamespace monitor {\n\nusing ::apollo::drivers::canbus::CANCardParameter;\nusing ::apollo::monitor::HwCheckerInterface;\nusing ::apollo::monitor::hw::EsdCanChecker;\n\nCanCheckerFactory::CanCheckerFactory() {}\n\nvoid CanCheckerFactory::RegisterCanCheckers() {\n Register(CANCardParameter::FAKE_CAN,\n []() -> HwCheckerInterface* { return new EsdCanChecker(); });\n}\n\nstd::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker(\n const CANCardParameter& parameter) {\n auto factory = CreateObject(parameter.brand());\n if (!factory) {\n AERROR << \"Failed to create CAN checker with parameter: \"\n << parameter.DebugString();\n }\n return factory;\n}\n\n} \/\/ namespace monitor\n} \/\/ namespace apollo\n\n<commit_msg>Monitor: fix can_checker_factory<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/monitor\/common\/can_checker_factory.h\"\n\n#include \"modules\/monitor\/hwmonitor\/hw\/esdcan\/esdcan_checker.h\"\n\n\/**\n * @file: hw_checker_factory.cc\n *\/\n\nnamespace apollo {\nnamespace monitor {\n\nusing ::apollo::drivers::canbus::CANCardParameter;\nusing ::apollo::monitor::HwCheckerInterface;\nusing ::apollo::monitor::hw::EsdCanChecker;\n\nCanCheckerFactory::CanCheckerFactory() {}\n\nvoid CanCheckerFactory::RegisterCanCheckers() {\n Register(CANCardParameter::ESD_CAN,\n []() -> HwCheckerInterface* { return new EsdCanChecker(); });\n}\n\nstd::unique_ptr<HwCheckerInterface> CanCheckerFactory::CreateCanChecker(\n const CANCardParameter& parameter) {\n auto factory = CreateObject(parameter.brand());\n if (!factory) {\n AERROR << \"Failed to create CAN checker with parameter: \"\n << parameter.DebugString();\n }\n return factory;\n}\n\n} \/\/ namespace monitor\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (c) 2014-2021 AscEmu Team <http:\/\/www.ascemu.org>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n * Copyright (C) 2005-2007 Ascent Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n\n#include <cstdint>\n#include <Network\/Network.h>\n#include <Config\/Config.h>\n\n#include \"BaseConsole.h\"\n#include \"ConsoleCommands.h\"\n#include \"Server\/World.h\"\n\n#include \"ConsoleSocket.h\"\n#include \"ConsoleAuthMgr.h\"\n\nListenSocket<ConsoleSocket>* g_pListenSocket = nullptr;\n\nvoid ConsoleAuthCallback(uint32_t request, uint32_t result)\n{\n ConsoleSocket* consoleSocket = sConsoleAuthMgr.getSocketByRequestId(request);\n if (consoleSocket == nullptr || consoleSocket->IsConnected() == false)\n {\n return;\n }\n\n if (result)\n {\n consoleSocket->getConsoleAuthResult(true);\n }\n else\n {\n consoleSocket->getConsoleAuthResult(false);\n }\n}\n\nvoid CloseConsoleListener()\n{\n if (g_pListenSocket != nullptr)\n {\n g_pListenSocket->Close();\n }\n}\n\nbool StartConsoleListener()\n{\n if (worldConfig.remoteConsole.isEnabled == false)\n {\n return false;\n }\n\n std::string consoleListenHost = worldConfig.remoteConsole.host;\n uint32_t consoleListenPort = worldConfig.remoteConsole.port;\n\n g_pListenSocket = new ListenSocket<ConsoleSocket>(consoleListenHost.c_str(), consoleListenPort);\n if (g_pListenSocket == nullptr)\n {\n return false;\n }\n\n if (g_pListenSocket->IsOpen() == false)\n {\n g_pListenSocket->Close();\n\n delete g_pListenSocket;\n g_pListenSocket = nullptr;\n\n return false;\n }\n\n sConsoleAuthMgr.initialize();\n return true;\n}\n\nThreadBase* GetConsoleListener()\n{\n \/\/\\todo Zyres: cast in redundant on MSVC but gcc needs it.\n return static_cast<ThreadBase*>(g_pListenSocket);\n}\n\nRemoteConsole::RemoteConsole(ConsoleSocket* pSocket)\n{\n m_pSocket = pSocket;\n}\n\nvoid RemoteConsole::Write(const char* Format, ...)\n{\n char obuf[65536];\n va_list ap;\n\n va_start(ap, Format);\n vsnprintf(obuf, 65536, Format, ap);\n va_end(ap);\n\n if (*obuf == '\\0')\n return;\n\n m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf));\n}\n\nstruct ConsoleCommand\n{\n bool(*CommandPointer)(BaseConsole*, int, std::string, bool);\n std::string consoleCommand;\n int argumentCount;\n std::string argumentFormat;\n std::string commandDescription;\n};\n\nstatic ConsoleCommand Commands[] =\n{\n { &handleSendChatAnnounceCommand, \"a\", 1, \"<announce>\", \"Send chat announce.\" },\n { &handleSendChatAnnounceCommand, \"announce\", 1, \"<announce>\", \"Send chat announce.\" },\n { &handleBanAccountCommand, \"ban\", 3, \"<account> <time e.g. 3d> [reason]\", \"Bans account <account> for time <time> with optional reason [reason].\" },\n { &handleBanAccountCommand, \"banaccount\", 3, \"<account> <time e.g. 3d> [reason]\", \"Bans account <account> for time <time> with optional reason [reason].\" },\n { &handleCreateAccountCommand, \"createaccount\", 2, \"<accountname> <password>\", \"Creates an account X with password y\" },\n { &handleCancelShutdownCommand, \"cancel\", 0, \"None\", \"Cancels a pending shutdown.\" },\n { &handleServerInfoCommand, \"info\", 0, \"None\", \"Return current Server information.\" },\n { &handleOnlineGmsCommand, \"gms\", 0, \"None\", \"Shows online GMs.\" },\n { &handleKickPlayerCommand, \"kick\", 2, \"<player name> [reason]\", \"Kicks player <player name> for optional reason [reason].\" },\n { &handleMotdCommand, \"getmotd\", 0, \"None\", \"View the current MOTD\" },\n { &handleMotdCommand, \"setmotd\", 1, \"<motd>\", \"Sets a new MOTD\" },\n { &handleAccountPermission, \"setaccpermission\", 2, \"<account> <permission>\", \"Aets permission y for account name x\" },\n { &handleListOnlinePlayersCommand, \"online\", 0, \"None\", \"Shows online players.\" },\n { &handlePlayerInfoCommand, \"playerinfo\", 1, \"<player name>\", \"Shows information about a player.\" },\n { &handleShutDownServerCommand, \"exit\", 0, \"[delay]\", \"Server shutdown with optional delay in seconds.\" },\n { &handleShutDownServerCommand, \"shutdown\", 0, \"[delay]\", \"Server shutdown with optional delay in seconds.\" },\n { &handleRehashConfigCommand, \"rehash\", 0, \"None\", \"Reload world-config.\" },\n { &handleUnbanAccountCommand, \"unban\", 1, \"<account>\", \"Unbans account x.\" },\n { &handleUnbanAccountCommand, \"unbanaccount\", 1, \"<account>\", \"Unbans account x.\" },\n { &handleSendWAnnounceCommand, \"w\", 1, \"<wannounce>\", \"Send announce on screen for all.\" },\n { &handleSendWAnnounceCommand, \"wannounce\", 1, \"<wannounce>\", \"Send announce on screen for all.\" },\n { &handleWhisperCommand, \"whisper\", 2, \"<player> <message>\", \"Whispers message to someone.\" },\n { &handleCreateNameHashCommand, \"getnamehash\", 1, \"<text>\", \"Returns the crc32 hash of <text>\" },\n { &handleRevivePlayerCommand, \"reviveplr\", 1, \"<player name>\", \"Revives a Player <player name>\" },\n { &handleClearConsoleCommand, \"clear\", 0, \"None\", \"Clears the console.\" },\n { &handleReloadScriptEngineCommand, \"reloadscripts\", 0, \"None\", \"Reloads all scripting engines currently loaded.\" },\n { &handlePrintTimeDateCommand, \"datetime\", 0, \"None\", \"Shows time and date according to localtime()\" },\n { &handleGetAccountsCommand, \"getaccountdata\", 0, \"None\", \"Prints out all account data\" },\n { nullptr, \"\", 0, \"\", \"\" },\n};\n\nvoid processConsoleInput(BaseConsole* baseConsole, std::string consoleInput, bool isWebClient)\n{\n ConsoleCommand commandList;\n\n std::stringstream consoleInputStream(consoleInput);\n\n std::string commandName;\n std::string commandVars;\n\n consoleInputStream >> commandName;\n std::getline(consoleInputStream, commandVars);\n\n bool commandFound = false;\n bool isHelpCommand = false;\n for (int i = 0; Commands[i].consoleCommand.empty() == false; ++i)\n {\n if (commandName.empty())\n break;\n\n if (commandName.compare(\"help\") == 0 || commandName.compare(\"?\") == 0)\n {\n isHelpCommand = true;\n break;\n }\n\n if (Commands[i].consoleCommand.compare(commandName) == 0)\n {\n commandFound = true;\n commandList = Commands[i];\n break;\n }\n }\n\n if (isHelpCommand)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Show Command list with ----- :%s\\r\\n\", commandName.c_str());\n\n baseConsole->Write(\"===============================================================================\\r\\n\");\n baseConsole->Write(\"| %15s | %57s |\\r\\n\", \"Name\", \"Arguments\");\n baseConsole->Write(\"===============================================================================\\r\\n\");\n\n for (int j = 0; Commands[j].consoleCommand.empty() == false; ++j)\n {\n baseConsole->Write(\"| %15s | %57s |\\r\\n\", Commands[j].consoleCommand.c_str(), Commands[j].argumentFormat.c_str());\n }\n\n baseConsole->Write(\"===============================================================================\\r\\n\");\n baseConsole->Write(\"| type 'quit' to terminate a Remote Console Session |\\r\\n\");\n baseConsole->Write(\"===============================================================================\\r\\n\");\n }\n }\n else\n {\n if (commandFound)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Received command: %s\\r\\n\", commandName.c_str());\n }\n\n if (commandList.argumentCount > 0 && commandVars.empty() == false)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Received vars: %s\\r\\n\", commandVars.c_str());\n }\n }\n\n if (!commandList.CommandPointer(baseConsole, commandList.argumentCount, commandVars, isWebClient))\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\\r\\n\\r\\n\",\n commandList.consoleCommand.c_str(), commandList.argumentFormat.c_str());\n }\n }\n }\n else\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\\r\\n\\r\\n\",\n commandName.c_str());\n }\n }\n }\n}\n\nvoid LocalConsole::Write(const char* Format, ...)\n{\n va_list ap;\n va_start(ap, Format);\n vprintf(Format, ap);\n va_end(ap);\n}\n<commit_msg>Update ConsoleListener.cpp<commit_after>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (c) 2014-2021 AscEmu Team <http:\/\/www.ascemu.org>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n * Copyright (C) 2005-2007 Ascent Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n\n#include <cstdint>\n#include <Network\/Network.h>\n#include <Config\/Config.h>\n\n#include \"BaseConsole.h\"\n#include \"ConsoleCommands.h\"\n#include \"Server\/World.h\"\n\n#include \"ConsoleSocket.h\"\n#include \"ConsoleAuthMgr.h\"\n\n#include \"Threading\/LegacyThreadBase.h\"\n\nListenSocket<ConsoleSocket>* g_pListenSocket = nullptr;\n\nvoid ConsoleAuthCallback(uint32_t request, uint32_t result)\n{\n ConsoleSocket* consoleSocket = sConsoleAuthMgr.getSocketByRequestId(request);\n if (consoleSocket == nullptr || consoleSocket->IsConnected() == false)\n {\n return;\n }\n\n if (result)\n {\n consoleSocket->getConsoleAuthResult(true);\n }\n else\n {\n consoleSocket->getConsoleAuthResult(false);\n }\n}\n\nvoid CloseConsoleListener()\n{\n if (g_pListenSocket != nullptr)\n {\n g_pListenSocket->Close();\n }\n}\n\nbool StartConsoleListener()\n{\n if (worldConfig.remoteConsole.isEnabled == false)\n {\n return false;\n }\n\n std::string consoleListenHost = worldConfig.remoteConsole.host;\n uint32_t consoleListenPort = worldConfig.remoteConsole.port;\n\n g_pListenSocket = new ListenSocket<ConsoleSocket>(consoleListenHost.c_str(), consoleListenPort);\n if (g_pListenSocket == nullptr)\n {\n return false;\n }\n\n if (g_pListenSocket->IsOpen() == false)\n {\n g_pListenSocket->Close();\n\n delete g_pListenSocket;\n g_pListenSocket = nullptr;\n\n return false;\n }\n\n sConsoleAuthMgr.initialize();\n return true;\n}\n\nThreadBase* GetConsoleListener()\n{\n \/\/\\todo Zyres: cast in redundant on MSVC but gcc needs it.\n return static_cast<ThreadBase*>(g_pListenSocket);\n}\n\nRemoteConsole::RemoteConsole(ConsoleSocket* pSocket)\n{\n m_pSocket = pSocket;\n}\n\nvoid RemoteConsole::Write(const char* Format, ...)\n{\n char obuf[65536];\n va_list ap;\n\n va_start(ap, Format);\n vsnprintf(obuf, 65536, Format, ap);\n va_end(ap);\n\n if (*obuf == '\\0')\n return;\n\n m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf));\n}\n\nstruct ConsoleCommand\n{\n bool(*CommandPointer)(BaseConsole*, int, std::string, bool);\n std::string consoleCommand;\n int argumentCount;\n std::string argumentFormat;\n std::string commandDescription;\n};\n\nstatic ConsoleCommand Commands[] =\n{\n { &handleSendChatAnnounceCommand, \"a\", 1, \"<announce>\", \"Send chat announce.\" },\n { &handleSendChatAnnounceCommand, \"announce\", 1, \"<announce>\", \"Send chat announce.\" },\n { &handleBanAccountCommand, \"ban\", 3, \"<account> <time e.g. 3d> [reason]\", \"Bans account <account> for time <time> with optional reason [reason].\" },\n { &handleBanAccountCommand, \"banaccount\", 3, \"<account> <time e.g. 3d> [reason]\", \"Bans account <account> for time <time> with optional reason [reason].\" },\n { &handleCreateAccountCommand, \"createaccount\", 2, \"<accountname> <password>\", \"Creates an account X with password y\" },\n { &handleCancelShutdownCommand, \"cancel\", 0, \"None\", \"Cancels a pending shutdown.\" },\n { &handleServerInfoCommand, \"info\", 0, \"None\", \"Return current Server information.\" },\n { &handleOnlineGmsCommand, \"gms\", 0, \"None\", \"Shows online GMs.\" },\n { &handleKickPlayerCommand, \"kick\", 2, \"<player name> [reason]\", \"Kicks player <player name> for optional reason [reason].\" },\n { &handleMotdCommand, \"getmotd\", 0, \"None\", \"View the current MOTD\" },\n { &handleMotdCommand, \"setmotd\", 1, \"<motd>\", \"Sets a new MOTD\" },\n { &handleAccountPermission, \"setaccpermission\", 2, \"<account> <permission>\", \"Aets permission y for account name x\" },\n { &handleListOnlinePlayersCommand, \"online\", 0, \"None\", \"Shows online players.\" },\n { &handlePlayerInfoCommand, \"playerinfo\", 1, \"<player name>\", \"Shows information about a player.\" },\n { &handleShutDownServerCommand, \"exit\", 0, \"[delay]\", \"Server shutdown with optional delay in seconds.\" },\n { &handleShutDownServerCommand, \"shutdown\", 0, \"[delay]\", \"Server shutdown with optional delay in seconds.\" },\n { &handleRehashConfigCommand, \"rehash\", 0, \"None\", \"Reload world-config.\" },\n { &handleUnbanAccountCommand, \"unban\", 1, \"<account>\", \"Unbans account x.\" },\n { &handleUnbanAccountCommand, \"unbanaccount\", 1, \"<account>\", \"Unbans account x.\" },\n { &handleSendWAnnounceCommand, \"w\", 1, \"<wannounce>\", \"Send announce on screen for all.\" },\n { &handleSendWAnnounceCommand, \"wannounce\", 1, \"<wannounce>\", \"Send announce on screen for all.\" },\n { &handleWhisperCommand, \"whisper\", 2, \"<player> <message>\", \"Whispers message to someone.\" },\n { &handleCreateNameHashCommand, \"getnamehash\", 1, \"<text>\", \"Returns the crc32 hash of <text>\" },\n { &handleRevivePlayerCommand, \"reviveplr\", 1, \"<player name>\", \"Revives a Player <player name>\" },\n { &handleClearConsoleCommand, \"clear\", 0, \"None\", \"Clears the console.\" },\n { &handleReloadScriptEngineCommand, \"reloadscripts\", 0, \"None\", \"Reloads all scripting engines currently loaded.\" },\n { &handlePrintTimeDateCommand, \"datetime\", 0, \"None\", \"Shows time and date according to localtime()\" },\n { &handleGetAccountsCommand, \"getaccountdata\", 0, \"None\", \"Prints out all account data\" },\n { nullptr, \"\", 0, \"\", \"\" },\n};\n\nvoid processConsoleInput(BaseConsole* baseConsole, std::string consoleInput, bool isWebClient)\n{\n ConsoleCommand commandList;\n\n std::stringstream consoleInputStream(consoleInput);\n\n std::string commandName;\n std::string commandVars;\n\n consoleInputStream >> commandName;\n std::getline(consoleInputStream, commandVars);\n\n bool commandFound = false;\n bool isHelpCommand = false;\n for (int i = 0; Commands[i].consoleCommand.empty() == false; ++i)\n {\n if (commandName.empty())\n break;\n\n if (commandName.compare(\"help\") == 0 || commandName.compare(\"?\") == 0)\n {\n isHelpCommand = true;\n break;\n }\n\n if (Commands[i].consoleCommand.compare(commandName) == 0)\n {\n commandFound = true;\n commandList = Commands[i];\n break;\n }\n }\n\n if (isHelpCommand)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Show Command list with ----- :%s\\r\\n\", commandName.c_str());\n\n baseConsole->Write(\"===============================================================================\\r\\n\");\n baseConsole->Write(\"| %15s | %57s |\\r\\n\", \"Name\", \"Arguments\");\n baseConsole->Write(\"===============================================================================\\r\\n\");\n\n for (int j = 0; Commands[j].consoleCommand.empty() == false; ++j)\n {\n baseConsole->Write(\"| %15s | %57s |\\r\\n\", Commands[j].consoleCommand.c_str(), Commands[j].argumentFormat.c_str());\n }\n\n baseConsole->Write(\"===============================================================================\\r\\n\");\n baseConsole->Write(\"| type 'quit' to terminate a Remote Console Session |\\r\\n\");\n baseConsole->Write(\"===============================================================================\\r\\n\");\n }\n }\n else\n {\n if (commandFound)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Received command: %s\\r\\n\", commandName.c_str());\n }\n\n if (commandList.argumentCount > 0 && commandVars.empty() == false)\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"Received vars: %s\\r\\n\", commandVars.c_str());\n }\n }\n\n if (!commandList.CommandPointer(baseConsole, commandList.argumentCount, commandVars, isWebClient))\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\\r\\n\\r\\n\",\n commandList.consoleCommand.c_str(), commandList.argumentFormat.c_str());\n }\n }\n }\n else\n {\n if (isWebClient == false)\n {\n baseConsole->Write(\"[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\\r\\n\\r\\n\",\n commandName.c_str());\n }\n }\n }\n}\n\nvoid LocalConsole::Write(const char* Format, ...)\n{\n va_list ap;\n va_start(ap, Format);\n vprintf(Format, ap);\n va_end(ap);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP\n\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/mat\/fun\/typedefs.hpp>\n#include <stan\/math\/prim\/mat\/fun\/cholesky_decompose.hpp>\n#include <stan\/math\/rev\/scal\/fun\/value_of_rec.hpp>\n#include <stan\/math\/rev\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/prim\/mat\/fun\/value_of_rec.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_pos_definite.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_square.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_symmetric.hpp>\n#include <algorithm>\n\nnamespace stan {\n namespace math {\n\n class cholesky_decompose_v_vari : public vari {\n public:\n int M_; \/\/ A.rows() = A.cols()\n int block_size_;\n typedef Eigen::Block<Eigen::MatrixXd> Block_;\n vari** variRefA_;\n vari** variRefL_;\n\n \/**\n * Constructor for cholesky function.\n *\n * Stores varis for A.\n * Instantiates and stores varis for L.\n * Instantiates and stores dummy vari for\n * upper triangular part of var result returned\n * in cholesky_decompose function call\n *\n * variRefL aren't on the chainable\n * autodiff stack, only used for storage\n * and computation. Note that varis for\n * L are constructed externally in\n * cholesky_decompose.\n *\n * block_size_ determined using the same\n * calculation Eigen\/LLT.h\n *\n * @param matrix A\n * @param matrix L, cholesky factor of A\n *\/\n cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,\n const Eigen::Matrix<double, -1, -1>& L_A)\n : vari(0.0),\n M_(A.rows()),\n variRefA_(ChainableStack::memalloc_.alloc_array<vari*>\n (A.rows() * (A.rows() + 1) \/ 2)),\n variRefL_(ChainableStack::memalloc_.alloc_array<vari*>\n (A.rows() * (A.rows() + 1) \/ 2)) {\n size_t pos = 0;\n block_size_ = M_\/8;\n block_size_ = (block_size_\/16)*16;\n block_size_ = (std::min)((std::max)(block_size_, 8), 128);\n for (size_type j = 0; j < M_; ++j) {\n for (size_type i = j; i < M_; ++i) {\n variRefA_[pos] = A.coeffRef(i, j).vi_;\n variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);\n ++pos;\n }\n }\n }\n\n inline void symbolic_rev(Block_& L,\n Block_& Lbar,\n int size) {\n using Eigen::Lower;\n using Eigen::Upper;\n using Eigen::StrictlyUpper;\n L.transposeInPlace();\n Lbar = (L * Lbar.triangularView<Lower>()).eval();\n Lbar.triangularView<StrictlyUpper>()\n = Lbar.adjoint().triangularView<StrictlyUpper>();\n L.triangularView<Upper>().solveInPlace(Lbar);\n L.triangularView<Upper>().solveInPlace(Lbar.transpose());\n }\n\n \/**\n * Reverse mode differentiation\n * algorithm refernce:\n *\n * Iain Murray: Differentiation of\n * the Cholesky decomposition, 2016.\n *\n *\/\n virtual void chain() {\n using Eigen::MatrixXd;\n using Eigen::Lower;\n using Eigen::Block;\n using Eigen::Upper;\n using Eigen::StrictlyUpper;\n MatrixXd Lbar(M_, M_);\n MatrixXd L(M_, M_);\n\n Lbar.setZero();\n L.setZero();\n size_t pos = 0;\n for (size_type j = 0; j < M_; ++j) {\n for (size_type i = j; i < M_; ++i) {\n Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;\n L.coeffRef(i, j) = variRefL_[pos]->val_;\n ++pos;\n }\n }\n\n for (int k = M_; k > 0; k -= block_size_) {\n int j = std::max(0, k - block_size_);\n Block_ R = L.block(j, 0, k - j, j);\n Block_ D = L.block(j, j, k - j, k - j);\n Block_ B = L.block(k, 0, M_ - k, j);\n Block_ C = L.block(k, j, M_ - k, k - j);\n Block_ Rbar = Lbar.block(j, 0, k - j, j);\n Block_ Dbar = Lbar.block(j, j, k - j, k - j);\n Block_ Bbar = Lbar.block(k, 0, M_ - k, j);\n Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);\n if (Cbar.size() > 0) {\n Cbar\n = D.transpose().triangularView<Upper>()\n .solve(Cbar.transpose()).transpose();\n Bbar.noalias() -= Cbar * R;\n Dbar.noalias() -= Cbar.transpose() * C;\n }\n symbolic_rev(D, Dbar, D.rows());\n Rbar.noalias() -= Cbar.transpose() * B;\n Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;\n Dbar.diagonal().array() *= 0.5;\n Dbar.triangularView<StrictlyUpper>().setZero();\n }\n pos = 0;\n for (size_type j = 0; j < M_; ++j)\n for (size_type i = j; i < M_; ++i)\n variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j);\n }\n };\n\n \/**\n * Reverse mode specialization of\n * cholesky decomposition\n *\n * Internally calls llt rather than using\n * cholesky_decompose in order\n * to use selfadjointView<Lower> optimization.\n *\n * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky\n * when possible\n *\n * Note chainable stack varis are created\n * below in Matrix<var, -1, -1>\n *\n * @param Matrix A\n * @return L cholesky factor of A\n *\/\n inline Eigen::Matrix<var, -1, -1>\n cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {\n check_square(\"cholesky_decompose\", \"A\", A);\n check_symmetric(\"cholesky_decompose\", \"A\", A);\n\n Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));\n Eigen::LLT<Eigen::MatrixXd> L_factor\n = L_A.selfadjointView<Eigen::Lower>().llt();\n check_pos_definite(\"cholesky_decompose\", \"m\", L_factor);\n L_A = L_factor.matrixL();\n\n \/\/ Memory allocated in arena.\n cholesky_decompose_v_vari *baseVari\n = new cholesky_decompose_v_vari(A, L_A);\n vari dummy(0.0, false);\n Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());\n size_t pos = 0;\n for (size_type j = 0; j < L.cols(); ++j) {\n for (size_type i = j; i < L.cols(); ++i) {\n L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];\n }\n for (size_type k = 0; k < j; ++k)\n L.coeffRef(k, j).vi_ = &dummy;\n }\n return L;\n }\n }\n}\n#endif\n<commit_msg>Fixed memory leak<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP\n\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/mat\/fun\/typedefs.hpp>\n#include <stan\/math\/prim\/mat\/fun\/cholesky_decompose.hpp>\n#include <stan\/math\/rev\/scal\/fun\/value_of_rec.hpp>\n#include <stan\/math\/rev\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/prim\/mat\/fun\/value_of_rec.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_pos_definite.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_square.hpp>\n#include <stan\/math\/prim\/mat\/err\/check_symmetric.hpp>\n#include <algorithm>\n\nnamespace stan {\n namespace math {\n\n class cholesky_decompose_v_vari : public vari {\n public:\n int M_; \/\/ A.rows() = A.cols()\n int block_size_;\n typedef Eigen::Block<Eigen::MatrixXd> Block_;\n vari** variRefA_;\n vari** variRefL_;\n\n \/**\n * Constructor for cholesky function.\n *\n * Stores varis for A.\n * Instantiates and stores varis for L.\n * Instantiates and stores dummy vari for\n * upper triangular part of var result returned\n * in cholesky_decompose function call\n *\n * variRefL aren't on the chainable\n * autodiff stack, only used for storage\n * and computation. Note that varis for\n * L are constructed externally in\n * cholesky_decompose.\n *\n * block_size_ determined using the same\n * calculation Eigen\/LLT.h\n *\n * @param matrix A\n * @param matrix L, cholesky factor of A\n *\/\n cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,\n const Eigen::Matrix<double, -1, -1>& L_A)\n : vari(0.0),\n M_(A.rows()),\n variRefA_(ChainableStack::memalloc_.alloc_array<vari*>\n (A.rows() * (A.rows() + 1) \/ 2)),\n variRefL_(ChainableStack::memalloc_.alloc_array<vari*>\n (A.rows() * (A.rows() + 1) \/ 2)) {\n size_t pos = 0;\n block_size_ = M_\/8;\n block_size_ = (block_size_\/16)*16;\n block_size_ = (std::min)((std::max)(block_size_, 8), 128);\n for (size_type j = 0; j < M_; ++j) {\n for (size_type i = j; i < M_; ++i) {\n variRefA_[pos] = A.coeffRef(i, j).vi_;\n variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);\n ++pos;\n }\n }\n }\n\n inline void symbolic_rev(Block_& L,\n Block_& Lbar,\n int size) {\n using Eigen::Lower;\n using Eigen::Upper;\n using Eigen::StrictlyUpper;\n L.transposeInPlace();\n Lbar = (L * Lbar.triangularView<Lower>()).eval();\n Lbar.triangularView<StrictlyUpper>()\n = Lbar.adjoint().triangularView<StrictlyUpper>();\n L.triangularView<Upper>().solveInPlace(Lbar);\n L.triangularView<Upper>().solveInPlace(Lbar.transpose());\n }\n\n \/**\n * Reverse mode differentiation\n * algorithm refernce:\n *\n * Iain Murray: Differentiation of\n * the Cholesky decomposition, 2016.\n *\n *\/\n virtual void chain() {\n using Eigen::MatrixXd;\n using Eigen::Lower;\n using Eigen::Block;\n using Eigen::Upper;\n using Eigen::StrictlyUpper;\n MatrixXd Lbar(M_, M_);\n MatrixXd L(M_, M_);\n\n Lbar.setZero();\n L.setZero();\n size_t pos = 0;\n for (size_type j = 0; j < M_; ++j) {\n for (size_type i = j; i < M_; ++i) {\n Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;\n L.coeffRef(i, j) = variRefL_[pos]->val_;\n ++pos;\n }\n }\n\n for (int k = M_; k > 0; k -= block_size_) {\n int j = std::max(0, k - block_size_);\n Block_ R = L.block(j, 0, k - j, j);\n Block_ D = L.block(j, j, k - j, k - j);\n Block_ B = L.block(k, 0, M_ - k, j);\n Block_ C = L.block(k, j, M_ - k, k - j);\n Block_ Rbar = Lbar.block(j, 0, k - j, j);\n Block_ Dbar = Lbar.block(j, j, k - j, k - j);\n Block_ Bbar = Lbar.block(k, 0, M_ - k, j);\n Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);\n if (Cbar.size() > 0) {\n Cbar\n = D.transpose().triangularView<Upper>()\n .solve(Cbar.transpose()).transpose();\n Bbar.noalias() -= Cbar * R;\n Dbar.noalias() -= Cbar.transpose() * C;\n }\n symbolic_rev(D, Dbar, D.rows());\n Rbar.noalias() -= Cbar.transpose() * B;\n Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;\n Dbar.diagonal().array() *= 0.5;\n Dbar.triangularView<StrictlyUpper>().setZero();\n }\n pos = 0;\n for (size_type j = 0; j < M_; ++j)\n for (size_type i = j; i < M_; ++i)\n variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j);\n }\n };\n\n \/**\n * Reverse mode specialization of\n * cholesky decomposition\n *\n * Internally calls llt rather than using\n * cholesky_decompose in order\n * to use selfadjointView<Lower> optimization.\n *\n * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky\n * when possible\n *\n * Note chainable stack varis are created\n * below in Matrix<var, -1, -1>\n *\n * @param Matrix A\n * @return L cholesky factor of A\n *\/\n inline Eigen::Matrix<var, -1, -1>\n cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {\n check_square(\"cholesky_decompose\", \"A\", A);\n check_symmetric(\"cholesky_decompose\", \"A\", A);\n\n Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));\n Eigen::LLT<Eigen::MatrixXd> L_factor\n = L_A.selfadjointView<Eigen::Lower>().llt();\n check_pos_definite(\"cholesky_decompose\", \"m\", L_factor);\n L_A = L_factor.matrixL();\n\n \/\/ Memory allocated in arena.\n cholesky_decompose_v_vari *baseVari\n = new cholesky_decompose_v_vari(A, L_A);\n vari* dummy = new vari(0.0, false);\n Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());\n size_t pos = 0;\n for (size_type j = 0; j < L.cols(); ++j) {\n for (size_type i = j; i < L.cols(); ++i) {\n L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];\n }\n for (size_type k = 0; k < j; ++k)\n L.coeffRef(k, j).vi_ = dummy;\n }\n return L;\n }\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"precompiled_svtools.hxx\"\n\n#include \"toolpaneldrawer.hxx\"\n#include \"toolpaneldrawerpeer.hxx\"\n#include \"svtools\/svtdata.hxx\"\n\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n\n#include <svl\/svtools.hrc>\n#include <vcl\/lineinfo.hxx>\n#include <vcl\/image.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/vclevent.hxx>\n\n\/\/......................................................................................................................\nnamespace svt\n{\n\/\/......................................................................................................................\n\n using ::com::sun::star::uno::Reference;\n using ::com::sun::star::awt::XWindowPeer;\n namespace AccessibleRole = ::com::sun::star::accessibility::AccessibleRole;\n\n static const int s_nIndentationWidth = 16;\n\n \/\/==================================================================================================================\n \/\/= ToolPanelDrawer\n \/\/==================================================================================================================\n \/\/------------------------------------------------------------------------------------------------------------------\n ToolPanelDrawer::ToolPanelDrawer( Window& i_rParent, const ::rtl::OUString& i_rTitle )\n :Window( &i_rParent, 0 )\n ,m_pPaintDevice( new VirtualDevice( *this ) )\n ,m_bFocused( false )\n ,m_bExpanded( false )\n {\n EnableMapMode( FALSE );\n SetBackground( Wallpaper() );\n SetPointer( POINTER_REFHAND );\n\n SetAccessibleRole( AccessibleRole::LABEL );\n\n SetText( i_rTitle );\n SetAccessibleName( i_rTitle );\n SetAccessibleDescription( i_rTitle );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n ToolPanelDrawer::~ToolPanelDrawer()\n {\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n long ToolPanelDrawer::GetPreferredHeightPixel() const\n {\n Rectangle aTitleBarBox( impl_calcTitleBarBox( impl_calcTextBoundingBox() ) );\n return aTitleBarBox.GetHeight();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::Paint( const Rectangle& i_rBoundingBox )\n {\n m_pPaintDevice->SetMapMode( GetMapMode() );\n m_pPaintDevice->SetOutputSize( GetOutputSizePixel() );\n m_pPaintDevice->SetSettings( GetSettings() );\n m_pPaintDevice->SetDrawMode( GetDrawMode() );\n\n const int nWidth( GetOutputSizePixel().Width() );\n const Rectangle aTextBox( impl_calcTextBoundingBox() );\n impl_paintBackground( impl_calcTitleBarBox( aTextBox ) );\n\n Rectangle aFocusBox( impl_paintExpansionIndicator( aTextBox ) );\n\n m_pPaintDevice->DrawText( aTextBox, GetText(), impl_getTextStyle() );\n\n aFocusBox.Union( aTextBox );\n aFocusBox.Left() += 2;\n impl_paintFocusIndicator( aFocusBox );\n\n DrawOutDev(\n Point(), GetOutputSizePixel(),\n Point(), GetOutputSizePixel(),\n *m_pPaintDevice\n );\n\n ::Window::Paint( i_rBoundingBox );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_paintExpansionIndicator( const Rectangle& i_rTextBox )\n {\n Rectangle aExpansionIndicatorArea;\n\n Image aImage( impl_getExpansionIndicator() );\n const int nHeight( aImage.GetSizePixel().Height() );\n if ( nHeight > 0 )\n {\n Point aPosition(\n 0,\n i_rTextBox.Top() + ( GetTextHeight() - nHeight ) \/ 2\n );\n m_pPaintDevice->DrawImage( aPosition, aImage );\n\n aExpansionIndicatorArea = Rectangle( aPosition, aImage.GetSizePixel() );\n }\n\n return aExpansionIndicatorArea;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Image ToolPanelDrawer::impl_getExpansionIndicator() const\n {\n const bool bHighContrastMode( GetSettings().GetStyleSettings().GetHighContrastMode() != 0 );\n USHORT nResourceId = 0;\n if ( m_bExpanded )\n if ( bHighContrastMode )\n nResourceId = IMG_TRIANGLE_DOWN_HC;\n else\n nResourceId = IMG_TRIANGLE_DOWN;\n else\n if ( bHighContrastMode )\n nResourceId = IMG_TRIANGLE_RIGHT_HC;\n else\n nResourceId = IMG_TRIANGLE_RIGHT;\n return Image( SvtResId( nResourceId ) );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n USHORT ToolPanelDrawer::impl_getTextStyle() const\n {\n const USHORT nBasicStyle = TEXT_DRAW_LEFT\n | TEXT_DRAW_TOP\n | TEXT_DRAW_WORDBREAK;\n\n if ( IsEnabled() )\n return nBasicStyle;\n\n return nBasicStyle | TEXT_DRAW_DISABLE;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::impl_paintBackground( const Rectangle& i_rTitleBarBox )\n {\n m_pPaintDevice->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );\n m_pPaintDevice->DrawRect( i_rTitleBarBox );\n\n m_pPaintDevice->SetFillColor();\n m_pPaintDevice->SetLineColor( GetSettings().GetStyleSettings().GetLightColor() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopLeft(), i_rTitleBarBox.TopRight() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopLeft(), i_rTitleBarBox.BottomLeft() );\n\n m_pPaintDevice->SetLineColor( GetSettings().GetStyleSettings().GetShadowColor() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.BottomLeft(), i_rTitleBarBox.BottomRight() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopRight(), i_rTitleBarBox.BottomRight() );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::impl_paintFocusIndicator( const Rectangle& i_rTextBox )\n {\n if ( m_bFocused )\n {\n const Rectangle aTextPixelBox( m_pPaintDevice->LogicToPixel( i_rTextBox ) );\n\n m_pPaintDevice->EnableMapMode( FALSE );\n m_pPaintDevice->SetFillColor();\n\n Rectangle aBox( i_rTextBox );\n aBox.Top() -= 1;\n aBox.Bottom() += 1;\n\n m_pPaintDevice->DrawRect( aTextPixelBox );\n\n LineInfo aDottedStyle( LINE_DASH );\n aDottedStyle.SetDashCount( 0 );\n aDottedStyle.SetDotCount( 1 );\n aDottedStyle.SetDotLen( 1 );\n aDottedStyle.SetDistance( 1 );\n\n m_pPaintDevice->SetLineColor( COL_BLACK );\n m_pPaintDevice->DrawPolyLine( Polygon( aTextPixelBox ), aDottedStyle );\n m_pPaintDevice->EnableMapMode( FALSE );\n }\n else\n HideFocus();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::GetFocus()\n {\n m_bFocused = true;\n Invalidate();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::LoseFocus()\n {\n m_bFocused = false;\n Invalidate();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::DataChanged( const DataChangedEvent& i_rEvent )\n {\n Window::DataChanged( i_rEvent );\n\n switch ( i_rEvent.GetType() )\n {\n case DATACHANGED_SETTINGS:\n if ( ( i_rEvent.GetFlags() & SETTINGS_STYLE ) == 0 )\n break;\n SetSettings( Application::GetSettings() );\n m_pPaintDevice.reset( new VirtualDevice( *this ) );\n\n \/\/ fall through.\n\n case DATACHANGED_FONTS:\n case DATACHANGED_FONTSUBSTITUTION:\n {\n const StyleSettings& rStyleSettings( GetSettings().GetStyleSettings() );\n\n \/\/ Font.\n Font aFont = rStyleSettings.GetAppFont();\n if ( IsControlFont() )\n aFont.Merge( GetControlFont() );\n SetZoomedPointFont( aFont );\n\n \/\/ Color.\n Color aColor;\n if ( IsControlForeground() )\n aColor = GetControlForeground();\n else\n aColor = rStyleSettings.GetButtonTextColor();\n SetTextColor( aColor );\n SetTextFillColor();\n\n Invalidate();\n }\n break;\n }\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Reference< XWindowPeer > ToolPanelDrawer::GetComponentInterface( BOOL i_bCreate )\n {\n Reference< XWindowPeer > xWindowPeer( Window::GetComponentInterface( FALSE ) );\n if ( !xWindowPeer.is() && i_bCreate )\n {\n xWindowPeer.set( new ToolPanelDrawerPeer() );\n SetComponentInterface( xWindowPeer );\n }\n return xWindowPeer;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_calcTextBoundingBox() const\n {\n Font aFont( GetFont() );\n if ( m_bExpanded )\n aFont.SetWeight( m_bExpanded ? WEIGHT_BOLD : WEIGHT_NORMAL );\n m_pPaintDevice->SetFont( aFont );\n\n int nAvailableWidth = m_pPaintDevice->GetTextWidth( GetText() );\n\n Rectangle aTextBox(\n Point(),\n Size(\n nAvailableWidth,\n GetSettings().GetStyleSettings().GetTitleHeight()\n )\n );\n aTextBox.Top() += ( aTextBox.GetHeight() - GetTextHeight() ) \/ 2;\n aTextBox.Left() += s_nIndentationWidth;\n aTextBox.Right() -= 1;\n\n aTextBox = m_pPaintDevice->GetTextRect( aTextBox, GetText(), impl_getTextStyle() );\n return aTextBox;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_calcTitleBarBox( const Rectangle& i_rTextBox ) const\n {\n Rectangle aTitleBarBox( i_rTextBox );\n aTitleBarBox.Bottom() += aTitleBarBox.Top();\n aTitleBarBox.Top() = 0;\n aTitleBarBox.Left() = 0;\n\n const long nWidth = GetOutputSizePixel().Width();\n if ( aTitleBarBox.GetWidth() < nWidth )\n aTitleBarBox.Right() = nWidth - 1;\n\n return aTitleBarBox;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::SetExpanded( const bool i_bExpanded )\n {\n if ( m_bExpanded != i_bExpanded )\n {\n m_bExpanded = i_bExpanded;\n CallEventListeners( m_bExpanded ? VCLEVENT_ITEM_EXPANDED : VCLEVENT_ITEM_COLLAPSED );\n Invalidate();\n }\n }\n\n\/\/......................................................................................................................\n} \/\/ namespace svt\n\/\/......................................................................................................................\n<commit_msg>slidecopy: WB_TABSTOP<commit_after>\/*************************************************************************\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"precompiled_svtools.hxx\"\n\n#include \"toolpaneldrawer.hxx\"\n#include \"toolpaneldrawerpeer.hxx\"\n#include \"svtools\/svtdata.hxx\"\n\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n\n#include <svl\/svtools.hrc>\n#include <vcl\/lineinfo.hxx>\n#include <vcl\/image.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/vclevent.hxx>\n\n\/\/......................................................................................................................\nnamespace svt\n{\n\/\/......................................................................................................................\n\n using ::com::sun::star::uno::Reference;\n using ::com::sun::star::awt::XWindowPeer;\n namespace AccessibleRole = ::com::sun::star::accessibility::AccessibleRole;\n\n static const int s_nIndentationWidth = 16;\n\n \/\/==================================================================================================================\n \/\/= ToolPanelDrawer\n \/\/==================================================================================================================\n \/\/------------------------------------------------------------------------------------------------------------------\n ToolPanelDrawer::ToolPanelDrawer( Window& i_rParent, const ::rtl::OUString& i_rTitle )\n :Window( &i_rParent, WB_TABSTOP )\n ,m_pPaintDevice( new VirtualDevice( *this ) )\n ,m_bFocused( false )\n ,m_bExpanded( false )\n {\n EnableMapMode( FALSE );\n SetBackground( Wallpaper() );\n SetPointer( POINTER_REFHAND );\n\n SetAccessibleRole( AccessibleRole::LABEL );\n\n SetText( i_rTitle );\n SetAccessibleName( i_rTitle );\n SetAccessibleDescription( i_rTitle );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n ToolPanelDrawer::~ToolPanelDrawer()\n {\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n long ToolPanelDrawer::GetPreferredHeightPixel() const\n {\n Rectangle aTitleBarBox( impl_calcTitleBarBox( impl_calcTextBoundingBox() ) );\n return aTitleBarBox.GetHeight();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::Paint( const Rectangle& i_rBoundingBox )\n {\n m_pPaintDevice->SetMapMode( GetMapMode() );\n m_pPaintDevice->SetOutputSize( GetOutputSizePixel() );\n m_pPaintDevice->SetSettings( GetSettings() );\n m_pPaintDevice->SetDrawMode( GetDrawMode() );\n\n const int nWidth( GetOutputSizePixel().Width() );\n const Rectangle aTextBox( impl_calcTextBoundingBox() );\n impl_paintBackground( impl_calcTitleBarBox( aTextBox ) );\n\n Rectangle aFocusBox( impl_paintExpansionIndicator( aTextBox ) );\n\n m_pPaintDevice->DrawText( aTextBox, GetText(), impl_getTextStyle() );\n\n aFocusBox.Union( aTextBox );\n aFocusBox.Left() += 2;\n impl_paintFocusIndicator( aFocusBox );\n\n DrawOutDev(\n Point(), GetOutputSizePixel(),\n Point(), GetOutputSizePixel(),\n *m_pPaintDevice\n );\n\n ::Window::Paint( i_rBoundingBox );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_paintExpansionIndicator( const Rectangle& i_rTextBox )\n {\n Rectangle aExpansionIndicatorArea;\n\n Image aImage( impl_getExpansionIndicator() );\n const int nHeight( aImage.GetSizePixel().Height() );\n if ( nHeight > 0 )\n {\n Point aPosition(\n 0,\n i_rTextBox.Top() + ( GetTextHeight() - nHeight ) \/ 2\n );\n m_pPaintDevice->DrawImage( aPosition, aImage );\n\n aExpansionIndicatorArea = Rectangle( aPosition, aImage.GetSizePixel() );\n }\n\n return aExpansionIndicatorArea;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Image ToolPanelDrawer::impl_getExpansionIndicator() const\n {\n const bool bHighContrastMode( GetSettings().GetStyleSettings().GetHighContrastMode() != 0 );\n USHORT nResourceId = 0;\n if ( m_bExpanded )\n if ( bHighContrastMode )\n nResourceId = IMG_TRIANGLE_DOWN_HC;\n else\n nResourceId = IMG_TRIANGLE_DOWN;\n else\n if ( bHighContrastMode )\n nResourceId = IMG_TRIANGLE_RIGHT_HC;\n else\n nResourceId = IMG_TRIANGLE_RIGHT;\n return Image( SvtResId( nResourceId ) );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n USHORT ToolPanelDrawer::impl_getTextStyle() const\n {\n const USHORT nBasicStyle = TEXT_DRAW_LEFT\n | TEXT_DRAW_TOP\n | TEXT_DRAW_WORDBREAK;\n\n if ( IsEnabled() )\n return nBasicStyle;\n\n return nBasicStyle | TEXT_DRAW_DISABLE;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::impl_paintBackground( const Rectangle& i_rTitleBarBox )\n {\n m_pPaintDevice->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );\n m_pPaintDevice->DrawRect( i_rTitleBarBox );\n\n m_pPaintDevice->SetFillColor();\n m_pPaintDevice->SetLineColor( GetSettings().GetStyleSettings().GetLightColor() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopLeft(), i_rTitleBarBox.TopRight() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopLeft(), i_rTitleBarBox.BottomLeft() );\n\n m_pPaintDevice->SetLineColor( GetSettings().GetStyleSettings().GetShadowColor() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.BottomLeft(), i_rTitleBarBox.BottomRight() );\n m_pPaintDevice->DrawLine( i_rTitleBarBox.TopRight(), i_rTitleBarBox.BottomRight() );\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::impl_paintFocusIndicator( const Rectangle& i_rTextBox )\n {\n if ( m_bFocused )\n {\n const Rectangle aTextPixelBox( m_pPaintDevice->LogicToPixel( i_rTextBox ) );\n\n m_pPaintDevice->EnableMapMode( FALSE );\n m_pPaintDevice->SetFillColor();\n\n Rectangle aBox( i_rTextBox );\n aBox.Top() -= 1;\n aBox.Bottom() += 1;\n\n m_pPaintDevice->DrawRect( aTextPixelBox );\n\n LineInfo aDottedStyle( LINE_DASH );\n aDottedStyle.SetDashCount( 0 );\n aDottedStyle.SetDotCount( 1 );\n aDottedStyle.SetDotLen( 1 );\n aDottedStyle.SetDistance( 1 );\n\n m_pPaintDevice->SetLineColor( COL_BLACK );\n m_pPaintDevice->DrawPolyLine( Polygon( aTextPixelBox ), aDottedStyle );\n m_pPaintDevice->EnableMapMode( FALSE );\n }\n else\n HideFocus();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::GetFocus()\n {\n m_bFocused = true;\n Invalidate();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::LoseFocus()\n {\n m_bFocused = false;\n Invalidate();\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::DataChanged( const DataChangedEvent& i_rEvent )\n {\n Window::DataChanged( i_rEvent );\n\n switch ( i_rEvent.GetType() )\n {\n case DATACHANGED_SETTINGS:\n if ( ( i_rEvent.GetFlags() & SETTINGS_STYLE ) == 0 )\n break;\n SetSettings( Application::GetSettings() );\n m_pPaintDevice.reset( new VirtualDevice( *this ) );\n\n \/\/ fall through.\n\n case DATACHANGED_FONTS:\n case DATACHANGED_FONTSUBSTITUTION:\n {\n const StyleSettings& rStyleSettings( GetSettings().GetStyleSettings() );\n\n \/\/ Font.\n Font aFont = rStyleSettings.GetAppFont();\n if ( IsControlFont() )\n aFont.Merge( GetControlFont() );\n SetZoomedPointFont( aFont );\n\n \/\/ Color.\n Color aColor;\n if ( IsControlForeground() )\n aColor = GetControlForeground();\n else\n aColor = rStyleSettings.GetButtonTextColor();\n SetTextColor( aColor );\n SetTextFillColor();\n\n Invalidate();\n }\n break;\n }\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Reference< XWindowPeer > ToolPanelDrawer::GetComponentInterface( BOOL i_bCreate )\n {\n Reference< XWindowPeer > xWindowPeer( Window::GetComponentInterface( FALSE ) );\n if ( !xWindowPeer.is() && i_bCreate )\n {\n xWindowPeer.set( new ToolPanelDrawerPeer() );\n SetComponentInterface( xWindowPeer );\n }\n return xWindowPeer;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_calcTextBoundingBox() const\n {\n Font aFont( GetFont() );\n if ( m_bExpanded )\n aFont.SetWeight( m_bExpanded ? WEIGHT_BOLD : WEIGHT_NORMAL );\n m_pPaintDevice->SetFont( aFont );\n\n int nAvailableWidth = m_pPaintDevice->GetTextWidth( GetText() );\n\n Rectangle aTextBox(\n Point(),\n Size(\n nAvailableWidth,\n GetSettings().GetStyleSettings().GetTitleHeight()\n )\n );\n aTextBox.Top() += ( aTextBox.GetHeight() - GetTextHeight() ) \/ 2;\n aTextBox.Left() += s_nIndentationWidth;\n aTextBox.Right() -= 1;\n\n aTextBox = m_pPaintDevice->GetTextRect( aTextBox, GetText(), impl_getTextStyle() );\n return aTextBox;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n Rectangle ToolPanelDrawer::impl_calcTitleBarBox( const Rectangle& i_rTextBox ) const\n {\n Rectangle aTitleBarBox( i_rTextBox );\n aTitleBarBox.Bottom() += aTitleBarBox.Top();\n aTitleBarBox.Top() = 0;\n aTitleBarBox.Left() = 0;\n\n const long nWidth = GetOutputSizePixel().Width();\n if ( aTitleBarBox.GetWidth() < nWidth )\n aTitleBarBox.Right() = nWidth - 1;\n\n return aTitleBarBox;\n }\n\n \/\/------------------------------------------------------------------------------------------------------------------\n void ToolPanelDrawer::SetExpanded( const bool i_bExpanded )\n {\n if ( m_bExpanded != i_bExpanded )\n {\n m_bExpanded = i_bExpanded;\n CallEventListeners( m_bExpanded ? VCLEVENT_ITEM_EXPANDED : VCLEVENT_ITEM_COLLAPSED );\n Invalidate();\n }\n }\n\n\/\/......................................................................................................................\n} \/\/ namespace svt\n\/\/......................................................................................................................\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <atlbase.h>\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nnamespace {\n\nclass AccessibilityWinBrowserTest : public InProcessBrowserTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n \/\/ Turns on the accessibility in the renderer. Off by default until\n \/\/ http:\/\/crbug.com\/25564 is fixed.\n command_line->AppendSwitch(switches::kEnableRendererAccessibility);\n }\n\n protected:\n IAccessible* GetRenderWidgetHostViewClientAccessible();\n};\n\nclass AccessibleChecker {\n public:\n AccessibleChecker(std::wstring expected_name, int32 expected_role);\n\n \/\/ Append an AccessibleChecker that verifies accessibility information for\n \/\/ a child IAccessible. Order is important.\n void AppendExpectedChild(AccessibleChecker* expected_child);\n\n \/\/ Check that the name and role of the given IAccessible instance and its\n \/\/ descendants match the expected names and roles that this object was\n \/\/ initialized with.\n void CheckAccessible(IAccessible* accessible);\n\n typedef std::vector<AccessibleChecker*> AccessibleCheckerVector;\n\n private:\n void CheckAccessibleName(IAccessible* accessible);\n void CheckAccessibleRole(IAccessible* accessible);\n void CheckAccessibleChildren(IAccessible* accessible);\n\n private:\n \/\/ Expected accessible name. Checked against IAccessible::get_accName.\n std::wstring name_;\n\n \/\/ Expected accessible role. Checked against IAccessible::get_accRole.\n int32 role_;\n\n \/\/ Expected accessible children. Checked using IAccessible::get_accChildCount\n \/\/ and ::AccessibleChildren.\n AccessibleCheckerVector children_;\n};\n\nVARIANT CreateI4Variant(LONG value) {\n VARIANT variant = {0};\n\n V_VT(&variant) = VT_I4;\n V_I4(&variant) = value;\n\n return variant;\n}\n\nIAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) {\n switch (V_VT(var)) {\n case VT_DISPATCH:\n return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach();\n break;\n\n case VT_I4: {\n CComPtr<IDispatch> dispatch;\n HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch);\n EXPECT_EQ(hr, S_OK);\n return CComQIPtr<IAccessible>(dispatch).Detach();\n break;\n }\n }\n\n return NULL;\n}\n\n\/\/ Retrieve the MSAA client accessibility object for the Render Widget Host View\n\/\/ of the selected tab.\nIAccessible*\nAccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() {\n HWND hwnd_render_widget_host_view =\n browser()->GetSelectedTabContents()->GetRenderWidgetHostView()->\n GetNativeView();\n\n IAccessible* accessible;\n HRESULT hr = AccessibleObjectFromWindow(\n hwnd_render_widget_host_view, OBJID_CLIENT,\n IID_IAccessible, reinterpret_cast<void**>(&accessible));\n EXPECT_EQ(S_OK, hr);\n EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL));\n\n return accessible;\n}\n\nAccessibleChecker::AccessibleChecker(\n std::wstring expected_name, int32 expected_role) :\n name_(expected_name),\n role_(expected_role) {\n}\n\nvoid AccessibleChecker::AppendExpectedChild(\n AccessibleChecker* expected_child) {\n children_.push_back(expected_child);\n}\n\nvoid AccessibleChecker::CheckAccessible(IAccessible* accessible) {\n CheckAccessibleName(accessible);\n CheckAccessibleRole(accessible);\n CheckAccessibleChildren(accessible);\n}\n\nvoid AccessibleChecker::CheckAccessibleName(IAccessible* accessible) {\n CComBSTR name;\n HRESULT hr =\n accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);\n\n if (name_.empty()) {\n \/\/ If the object doesn't have name S_FALSE should be returned.\n EXPECT_EQ(hr, S_FALSE);\n } else {\n \/\/ Test that the correct string was returned.\n EXPECT_EQ(hr, S_OK);\n EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name),\n name_.c_str(), name_.length()),\n CSTR_EQUAL);\n }\n}\n\nvoid AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) {\n VARIANT var_role = {0};\n HRESULT hr =\n accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role);\n EXPECT_EQ(hr, S_OK);\n EXPECT_EQ(V_VT(&var_role), VT_I4);\n EXPECT_EQ(V_I4(&var_role), role_);\n}\n\nvoid AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) {\n LONG child_count = 0;\n HRESULT hr = parent->get_accChildCount(&child_count);\n EXPECT_EQ(hr, S_OK);\n\n \/\/ TODO(dmazzoni): remove as soon as test passes on build bot\n printf(\"CheckAccessibleChildren: actual=%d expected=%d\\n\",\n static_cast<int>(child_count),\n static_cast<int>(children_.size()));\n\n ASSERT_EQ(child_count, children_.size());\n\n std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]);\n LONG obtained_count = 0;\n hr = AccessibleChildren(parent, 0, child_count,\n child_array.get(), &obtained_count);\n ASSERT_EQ(hr, S_OK);\n ASSERT_EQ(child_count, obtained_count);\n\n VARIANT* child = child_array.get();\n for (AccessibleCheckerVector::iterator child_checker = children_.begin();\n child_checker != children_.end();\n ++child_checker, ++child) {\n ScopedComPtr<IAccessible> child_accessible;\n child_accessible.Attach(GetAccessibleFromResultVariant(parent, child));\n (*child_checker)->CheckAccessible(child_accessible);\n }\n}\n\n\/\/ Flaky http:\/\/crbug.com\/44546.\nIN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest,\n FLAKY_TestRendererAccessibilityTree) {\n GURL tree_url(\n \"data:text\/html,<html><head><title>Accessibility Win Test<\/title><\/head>\"\n \"<body><input type='button' value='push' \/><input type='checkbox' \/>\"\n \"<\/body><\/html>\");\n browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED);\n ui_test_utils::WaitForNotification(\n NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED);\n\n ScopedComPtr<IAccessible> document_accessible(\n GetRenderWidgetHostViewClientAccessible());\n ASSERT_NE(document_accessible.get(), reinterpret_cast<IAccessible*>(NULL));\n\n AccessibleChecker button_checker(L\"push\", ROLE_SYSTEM_PUSHBUTTON);\n AccessibleChecker checkbox_checker(L\"\", ROLE_SYSTEM_CHECKBUTTON);\n\n AccessibleChecker grouping_checker(L\"\", ROLE_SYSTEM_GROUPING);\n grouping_checker.AppendExpectedChild(&button_checker);\n grouping_checker.AppendExpectedChild(&checkbox_checker);\n\n AccessibleChecker document_checker(L\"\", ROLE_SYSTEM_DOCUMENT);\n document_checker.AppendExpectedChild(&grouping_checker);\n\n \/\/ Check the accessible tree of the renderer.\n document_checker.CheckAccessible(document_accessible);\n\n \/\/ Check that document accessible has a parent accessible.\n ScopedComPtr<IDispatch> parent_dispatch;\n HRESULT hr = document_accessible->get_accParent(parent_dispatch.Receive());\n EXPECT_EQ(hr, S_OK);\n EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL));\n\n \/\/ Navigate to another page.\n GURL about_url(\"about:\");\n ui_test_utils::NavigateToURL(browser(), about_url);\n\n \/\/ Verify that the IAccessible reference still points to a valid object and\n \/\/ that it calls to its methods fail since the tree is no longer valid after\n \/\/ the page navagation.\n \/\/ Todo(ctguil): Currently this is giving a false positive because E_FAIL is\n \/\/ returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails\n \/\/ since the previous render view host connection is lost. Verify that\n \/\/ instances are actually marked as invalid once the browse side cache is\n \/\/ checked in.\n CComBSTR name;\n hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);\n ASSERT_EQ(E_FAIL, hr);\n}\n} \/\/ namespace.\n<commit_msg>Mark AccessibilityWinBrowserTest.TestRendererAccessibilityTree as FAILS.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <atlbase.h>\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nnamespace {\n\nclass AccessibilityWinBrowserTest : public InProcessBrowserTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n \/\/ Turns on the accessibility in the renderer. Off by default until\n \/\/ http:\/\/crbug.com\/25564 is fixed.\n command_line->AppendSwitch(switches::kEnableRendererAccessibility);\n }\n\n protected:\n IAccessible* GetRenderWidgetHostViewClientAccessible();\n};\n\nclass AccessibleChecker {\n public:\n AccessibleChecker(std::wstring expected_name, int32 expected_role);\n\n \/\/ Append an AccessibleChecker that verifies accessibility information for\n \/\/ a child IAccessible. Order is important.\n void AppendExpectedChild(AccessibleChecker* expected_child);\n\n \/\/ Check that the name and role of the given IAccessible instance and its\n \/\/ descendants match the expected names and roles that this object was\n \/\/ initialized with.\n void CheckAccessible(IAccessible* accessible);\n\n typedef std::vector<AccessibleChecker*> AccessibleCheckerVector;\n\n private:\n void CheckAccessibleName(IAccessible* accessible);\n void CheckAccessibleRole(IAccessible* accessible);\n void CheckAccessibleChildren(IAccessible* accessible);\n\n private:\n \/\/ Expected accessible name. Checked against IAccessible::get_accName.\n std::wstring name_;\n\n \/\/ Expected accessible role. Checked against IAccessible::get_accRole.\n int32 role_;\n\n \/\/ Expected accessible children. Checked using IAccessible::get_accChildCount\n \/\/ and ::AccessibleChildren.\n AccessibleCheckerVector children_;\n};\n\nVARIANT CreateI4Variant(LONG value) {\n VARIANT variant = {0};\n\n V_VT(&variant) = VT_I4;\n V_I4(&variant) = value;\n\n return variant;\n}\n\nIAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) {\n switch (V_VT(var)) {\n case VT_DISPATCH:\n return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach();\n break;\n\n case VT_I4: {\n CComPtr<IDispatch> dispatch;\n HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch);\n EXPECT_EQ(hr, S_OK);\n return CComQIPtr<IAccessible>(dispatch).Detach();\n break;\n }\n }\n\n return NULL;\n}\n\n\/\/ Retrieve the MSAA client accessibility object for the Render Widget Host View\n\/\/ of the selected tab.\nIAccessible*\nAccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() {\n HWND hwnd_render_widget_host_view =\n browser()->GetSelectedTabContents()->GetRenderWidgetHostView()->\n GetNativeView();\n\n IAccessible* accessible;\n HRESULT hr = AccessibleObjectFromWindow(\n hwnd_render_widget_host_view, OBJID_CLIENT,\n IID_IAccessible, reinterpret_cast<void**>(&accessible));\n EXPECT_EQ(S_OK, hr);\n EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL));\n\n return accessible;\n}\n\nAccessibleChecker::AccessibleChecker(\n std::wstring expected_name, int32 expected_role) :\n name_(expected_name),\n role_(expected_role) {\n}\n\nvoid AccessibleChecker::AppendExpectedChild(\n AccessibleChecker* expected_child) {\n children_.push_back(expected_child);\n}\n\nvoid AccessibleChecker::CheckAccessible(IAccessible* accessible) {\n CheckAccessibleName(accessible);\n CheckAccessibleRole(accessible);\n CheckAccessibleChildren(accessible);\n}\n\nvoid AccessibleChecker::CheckAccessibleName(IAccessible* accessible) {\n CComBSTR name;\n HRESULT hr =\n accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);\n\n if (name_.empty()) {\n \/\/ If the object doesn't have name S_FALSE should be returned.\n EXPECT_EQ(hr, S_FALSE);\n } else {\n \/\/ Test that the correct string was returned.\n EXPECT_EQ(hr, S_OK);\n EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name),\n name_.c_str(), name_.length()),\n CSTR_EQUAL);\n }\n}\n\nvoid AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) {\n VARIANT var_role = {0};\n HRESULT hr =\n accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role);\n EXPECT_EQ(hr, S_OK);\n EXPECT_EQ(V_VT(&var_role), VT_I4);\n EXPECT_EQ(V_I4(&var_role), role_);\n}\n\nvoid AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) {\n LONG child_count = 0;\n HRESULT hr = parent->get_accChildCount(&child_count);\n EXPECT_EQ(hr, S_OK);\n\n \/\/ TODO(dmazzoni): remove as soon as test passes on build bot\n printf(\"CheckAccessibleChildren: actual=%d expected=%d\\n\",\n static_cast<int>(child_count),\n static_cast<int>(children_.size()));\n\n ASSERT_EQ(child_count, children_.size());\n\n std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]);\n LONG obtained_count = 0;\n hr = AccessibleChildren(parent, 0, child_count,\n child_array.get(), &obtained_count);\n ASSERT_EQ(hr, S_OK);\n ASSERT_EQ(child_count, obtained_count);\n\n VARIANT* child = child_array.get();\n for (AccessibleCheckerVector::iterator child_checker = children_.begin();\n child_checker != children_.end();\n ++child_checker, ++child) {\n ScopedComPtr<IAccessible> child_accessible;\n child_accessible.Attach(GetAccessibleFromResultVariant(parent, child));\n (*child_checker)->CheckAccessible(child_accessible);\n }\n}\n\n\/\/ Flaky http:\/\/crbug.com\/44546.\nIN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest,\n FAILS_TestRendererAccessibilityTree) {\n GURL tree_url(\n \"data:text\/html,<html><head><title>Accessibility Win Test<\/title><\/head>\"\n \"<body><input type='button' value='push' \/><input type='checkbox' \/>\"\n \"<\/body><\/html>\");\n browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED);\n ui_test_utils::WaitForNotification(\n NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED);\n\n ScopedComPtr<IAccessible> document_accessible(\n GetRenderWidgetHostViewClientAccessible());\n ASSERT_NE(document_accessible.get(), reinterpret_cast<IAccessible*>(NULL));\n\n AccessibleChecker button_checker(L\"push\", ROLE_SYSTEM_PUSHBUTTON);\n AccessibleChecker checkbox_checker(L\"\", ROLE_SYSTEM_CHECKBUTTON);\n\n AccessibleChecker grouping_checker(L\"\", ROLE_SYSTEM_GROUPING);\n grouping_checker.AppendExpectedChild(&button_checker);\n grouping_checker.AppendExpectedChild(&checkbox_checker);\n\n AccessibleChecker document_checker(L\"\", ROLE_SYSTEM_DOCUMENT);\n document_checker.AppendExpectedChild(&grouping_checker);\n\n \/\/ Check the accessible tree of the renderer.\n document_checker.CheckAccessible(document_accessible);\n\n \/\/ Check that document accessible has a parent accessible.\n ScopedComPtr<IDispatch> parent_dispatch;\n HRESULT hr = document_accessible->get_accParent(parent_dispatch.Receive());\n EXPECT_EQ(hr, S_OK);\n EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL));\n\n \/\/ Navigate to another page.\n GURL about_url(\"about:\");\n ui_test_utils::NavigateToURL(browser(), about_url);\n\n \/\/ Verify that the IAccessible reference still points to a valid object and\n \/\/ that it calls to its methods fail since the tree is no longer valid after\n \/\/ the page navagation.\n \/\/ Todo(ctguil): Currently this is giving a false positive because E_FAIL is\n \/\/ returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails\n \/\/ since the previous render view host connection is lost. Verify that\n \/\/ instances are actually marked as invalid once the browse side cache is\n \/\/ checked in.\n CComBSTR name;\n hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name);\n ASSERT_EQ(E_FAIL, hr);\n}\n} \/\/ namespace.\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/configuration_policy_provider.h\"\n\n#include \"base\/values.h\"\n\nnamespace {\n\n\/\/ TODO(avi): Use this mapping to auto-generate MCX manifests and Windows\n\/\/ ADM\/ADMX files. http:\/\/crbug.com\/49316\n\nstruct InternalPolicyValueMapEntry {\n ConfigurationPolicyStore::PolicyType policy_type;\n Value::ValueType value_type;\n const char* name;\n};\n\nconst InternalPolicyValueMapEntry kPolicyValueMap[] = {\n { ConfigurationPolicyStore::kPolicyHomePage,\n Value::TYPE_STRING, \"HomepageLocation\" },\n { ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,\n Value::TYPE_BOOLEAN, \"HomepageIsNewTabPage\" },\n { ConfigurationPolicyStore::kPolicyProxyServerMode,\n Value::TYPE_INTEGER, \"ProxyServerMode\" },\n { ConfigurationPolicyStore::kPolicyProxyServer,\n Value::TYPE_STRING, \"ProxyServer\" },\n { ConfigurationPolicyStore::kPolicyProxyPacUrl,\n Value::TYPE_STRING, \"ProxyPacUrl\" },\n { ConfigurationPolicyStore::kPolicyProxyBypassList,\n Value::TYPE_STRING, \"ProxyBypassList\" },\n { ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,\n Value::TYPE_BOOLEAN, \"AlternateErrorPagesEnabled\" },\n { ConfigurationPolicyStore::kPolicySearchSuggestEnabled,\n Value::TYPE_BOOLEAN, \"SearchSuggestEnabled\" },\n { ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,\n Value::TYPE_BOOLEAN, \"DnsPrefetchingEnabled\" },\n { ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,\n Value::TYPE_BOOLEAN, \"SafeBrowsingEnabled\" },\n { ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,\n Value::TYPE_BOOLEAN, \"MetricsReportingEnabled\" },\n { ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,\n Value::TYPE_BOOLEAN, \"PasswordManagerEnabled\" },\n { ConfigurationPolicyStore::kPolicyDisabledPlugins,\n Value::TYPE_STRING, \"DisabledPluginsList\" },\n { ConfigurationPolicyStore::kPolicyApplicationLocale,\r\n Value::TYPE_STRING, \"ApplicationLocaleValue\" },\n { ConfigurationPolicyStore::kPolicySyncDisabled,\n Value::TYPE_BOOLEAN, \"SyncDisabled\" },\n};\n\n} \/\/ namespace\n\n\/* static *\/\nconst ConfigurationPolicyProvider::PolicyValueMap*\n ConfigurationPolicyProvider::PolicyValueMapping() {\n static PolicyValueMap* mapping;\n if (!mapping) {\n mapping = new PolicyValueMap();\n for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {\n const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];\n PolicyValueMapEntry entry;\n entry.policy_type = internal_entry.policy_type;\n entry.value_type = internal_entry.value_type;\n entry.name = std::string(internal_entry.name);\n mapping->push_back(entry);\n }\n }\n return mapping;\n}\n<commit_msg>Fix wrong line ending.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/configuration_policy_provider.h\"\n\n#include \"base\/values.h\"\n\nnamespace {\n\n\/\/ TODO(avi): Use this mapping to auto-generate MCX manifests and Windows\n\/\/ ADM\/ADMX files. http:\/\/crbug.com\/49316\n\nstruct InternalPolicyValueMapEntry {\n ConfigurationPolicyStore::PolicyType policy_type;\n Value::ValueType value_type;\n const char* name;\n};\n\nconst InternalPolicyValueMapEntry kPolicyValueMap[] = {\n { ConfigurationPolicyStore::kPolicyHomePage,\n Value::TYPE_STRING, \"HomepageLocation\" },\n { ConfigurationPolicyStore::kPolicyHomepageIsNewTabPage,\n Value::TYPE_BOOLEAN, \"HomepageIsNewTabPage\" },\n { ConfigurationPolicyStore::kPolicyProxyServerMode,\n Value::TYPE_INTEGER, \"ProxyServerMode\" },\n { ConfigurationPolicyStore::kPolicyProxyServer,\n Value::TYPE_STRING, \"ProxyServer\" },\n { ConfigurationPolicyStore::kPolicyProxyPacUrl,\n Value::TYPE_STRING, \"ProxyPacUrl\" },\n { ConfigurationPolicyStore::kPolicyProxyBypassList,\n Value::TYPE_STRING, \"ProxyBypassList\" },\n { ConfigurationPolicyStore::kPolicyAlternateErrorPagesEnabled,\n Value::TYPE_BOOLEAN, \"AlternateErrorPagesEnabled\" },\n { ConfigurationPolicyStore::kPolicySearchSuggestEnabled,\n Value::TYPE_BOOLEAN, \"SearchSuggestEnabled\" },\n { ConfigurationPolicyStore::kPolicyDnsPrefetchingEnabled,\n Value::TYPE_BOOLEAN, \"DnsPrefetchingEnabled\" },\n { ConfigurationPolicyStore::kPolicySafeBrowsingEnabled,\n Value::TYPE_BOOLEAN, \"SafeBrowsingEnabled\" },\n { ConfigurationPolicyStore::kPolicyMetricsReportingEnabled,\n Value::TYPE_BOOLEAN, \"MetricsReportingEnabled\" },\n { ConfigurationPolicyStore::kPolicyPasswordManagerEnabled,\n Value::TYPE_BOOLEAN, \"PasswordManagerEnabled\" },\n { ConfigurationPolicyStore::kPolicyDisabledPlugins,\n Value::TYPE_STRING, \"DisabledPluginsList\" },\n { ConfigurationPolicyStore::kPolicyApplicationLocale,\n Value::TYPE_STRING, \"ApplicationLocaleValue\" },\n { ConfigurationPolicyStore::kPolicySyncDisabled,\n Value::TYPE_BOOLEAN, \"SyncDisabled\" },\n};\n\n} \/\/ namespace\n\n\/* static *\/\nconst ConfigurationPolicyProvider::PolicyValueMap*\n ConfigurationPolicyProvider::PolicyValueMapping() {\n static PolicyValueMap* mapping;\n if (!mapping) {\n mapping = new PolicyValueMap();\n for (size_t i = 0; i < arraysize(kPolicyValueMap); ++i) {\n const InternalPolicyValueMapEntry& internal_entry = kPolicyValueMap[i];\n PolicyValueMapEntry entry;\n entry.policy_type = internal_entry.policy_type;\n entry.value_type = internal_entry.value_type;\n entry.name = std::string(internal_entry.name);\n mapping->push_back(entry);\n }\n }\n return mapping;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/most_visited_handler.h\"\n\n#include <set>\n\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/md5.h\"\n#include \"base\/memory\/scoped_vector.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/history\/page_usage_data.h\"\n#include \"chrome\/browser\/history\/top_sites.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prefs\/scoped_user_pref_update.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/favicon_source.h\"\n#include \"chrome\/browser\/ui\/webui\/new_tab_ui.h\"\n#include \"chrome\/browser\/ui\/webui\/thumbnail_source.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/common\/notification_source.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\n\/\/ The number of most visited pages we show.\nconst size_t kMostVisitedPages = 8;\n\n\/\/ The number of days of history we consider for most visited entries.\nconst int kMostVisitedScope = 90;\n\n} \/\/ namespace\n\n\/\/ This struct is used when getting the pre-populated pages in case the user\n\/\/ hasn't filled up his most visited pages.\nstruct MostVisitedHandler::MostVisitedPage {\n string16 title;\n GURL url;\n GURL thumbnail_url;\n GURL favicon_url;\n};\n\nMostVisitedHandler::MostVisitedHandler()\n : got_first_most_visited_request_(false) {\n}\n\nMostVisitedHandler::~MostVisitedHandler() {\n}\n\nWebUIMessageHandler* MostVisitedHandler::Attach(WebUI* web_ui) {\n Profile* profile = web_ui->GetProfile();\n \/\/ Set up our sources for thumbnail and favicon data.\n ThumbnailSource* thumbnail_src = new ThumbnailSource(profile);\n profile->GetChromeURLDataManager()->AddDataSource(thumbnail_src);\n\n profile->GetChromeURLDataManager()->AddDataSource(\n new FaviconSource(profile, FaviconSource::FAVICON));\n\n \/\/ Get notifications when history is cleared.\n registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED,\n Source<Profile>(profile));\n\n WebUIMessageHandler* result = WebUIMessageHandler::Attach(web_ui);\n\n \/\/ We pre-emptively make a fetch for the most visited pages so we have the\n \/\/ results sooner.\n StartQueryForMostVisited();\n return result;\n}\n\nvoid MostVisitedHandler::RegisterMessages() {\n \/\/ Register ourselves as the handler for the \"mostvisited\" message from\n \/\/ Javascript.\n web_ui_->RegisterMessageCallback(\"getMostVisited\",\n NewCallback(this, &MostVisitedHandler::HandleGetMostVisited));\n\n \/\/ Register ourselves for any most-visited item blacklisting.\n web_ui_->RegisterMessageCallback(\"blacklistURLFromMostVisited\",\n NewCallback(this, &MostVisitedHandler::HandleBlacklistURL));\n web_ui_->RegisterMessageCallback(\"removeURLsFromMostVisitedBlacklist\",\n NewCallback(this, &MostVisitedHandler::HandleRemoveURLsFromBlacklist));\n web_ui_->RegisterMessageCallback(\"clearMostVisitedURLsBlacklist\",\n NewCallback(this, &MostVisitedHandler::HandleClearBlacklist));\n\n \/\/ Register ourself for pinned URL messages.\n web_ui_->RegisterMessageCallback(\"addPinnedURL\",\n NewCallback(this, &MostVisitedHandler::HandleAddPinnedURL));\n web_ui_->RegisterMessageCallback(\"removePinnedURL\",\n NewCallback(this, &MostVisitedHandler::HandleRemovePinnedURL));\n}\n\nvoid MostVisitedHandler::HandleGetMostVisited(const ListValue* args) {\n if (!got_first_most_visited_request_) {\n \/\/ If our intial data is already here, return it.\n SendPagesValue();\n got_first_most_visited_request_ = true;\n } else {\n StartQueryForMostVisited();\n }\n}\n\nvoid MostVisitedHandler::SendPagesValue() {\n if (pages_value_.get()) {\n Profile* profile = web_ui_->GetProfile();\n const DictionaryValue* url_blacklist =\n profile->GetPrefs()->GetDictionary(prefs::kNTPMostVisitedURLsBlacklist);\n bool has_blacklisted_urls = !url_blacklist->empty();\n history::TopSites* ts = profile->GetTopSites();\n if (ts)\n has_blacklisted_urls = ts->HasBlacklistedItems();\n FundamentalValue first_run(IsFirstRun());\n FundamentalValue has_blacklisted_urls_value(has_blacklisted_urls);\n web_ui_->CallJavascriptFunction(\"mostVisitedPages\",\n *(pages_value_.get()),\n first_run,\n has_blacklisted_urls_value);\n pages_value_.reset();\n }\n}\n\nvoid MostVisitedHandler::StartQueryForMostVisited() {\n \/\/ Use TopSites.\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts) {\n ts->GetMostVisitedURLs(\n &topsites_consumer_,\n NewCallback(this, &MostVisitedHandler::OnMostVisitedURLsAvailable));\n }\n}\n\nvoid MostVisitedHandler::HandleBlacklistURL(const ListValue* args) {\n std::string url = UTF16ToUTF8(ExtractStringValue(args));\n BlacklistURL(GURL(url));\n}\n\nvoid MostVisitedHandler::HandleRemoveURLsFromBlacklist(const ListValue* args) {\n DCHECK(args->GetSize() != 0);\n\n for (ListValue::const_iterator iter = args->begin();\n iter != args->end(); ++iter) {\n std::string url;\n bool r = (*iter)->GetAsString(&url);\n if (!r) {\n NOTREACHED();\n return;\n }\n UserMetrics::RecordAction(UserMetricsAction(\"MostVisited_UrlRemoved\"),\n web_ui_->GetProfile());\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->RemoveBlacklistedURL(GURL(url));\n }\n}\n\nvoid MostVisitedHandler::HandleClearBlacklist(const ListValue* args) {\n UserMetrics::RecordAction(UserMetricsAction(\"MostVisited_BlacklistCleared\"),\n web_ui_->GetProfile());\n\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->ClearBlacklistedURLs();\n}\n\nvoid MostVisitedHandler::HandleAddPinnedURL(const ListValue* args) {\n DCHECK_EQ(5U, args->GetSize()) << \"Wrong number of params to addPinnedURL\";\n MostVisitedPage mvp;\n std::string tmp_string;\n string16 tmp_string16;\n int index;\n\n bool r = args->GetString(0, &tmp_string);\n DCHECK(r) << \"Missing URL in addPinnedURL from the NTP Most Visited.\";\n mvp.url = GURL(tmp_string);\n\n r = args->GetString(1, &tmp_string16);\n DCHECK(r) << \"Missing title in addPinnedURL from the NTP Most Visited.\";\n mvp.title = tmp_string16;\n\n r = args->GetString(2, &tmp_string);\n DCHECK(r) << \"Failed to read the favicon URL in addPinnedURL from the NTP \"\n << \"Most Visited.\";\n if (!tmp_string.empty())\n mvp.favicon_url = GURL(tmp_string);\n\n r = args->GetString(3, &tmp_string);\n DCHECK(r) << \"Failed to read the thumbnail URL in addPinnedURL from the NTP \"\n << \"Most Visited.\";\n if (!tmp_string.empty())\n mvp.thumbnail_url = GURL(tmp_string);\n\n r = args->GetString(4, &tmp_string);\n DCHECK(r) << \"Missing index in addPinnedURL from the NTP Most Visited.\";\n base::StringToInt(tmp_string, &index);\n\n AddPinnedURL(mvp, index);\n}\n\nvoid MostVisitedHandler::AddPinnedURL(const MostVisitedPage& page, int index) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->AddPinnedURL(page.url, index);\n}\n\nvoid MostVisitedHandler::HandleRemovePinnedURL(const ListValue* args) {\n std::string url = UTF16ToUTF8(ExtractStringValue(args));\n RemovePinnedURL(GURL(url));\n}\n\nvoid MostVisitedHandler::RemovePinnedURL(const GURL& url) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->RemovePinnedURL(url);\n}\n\nbool MostVisitedHandler::GetPinnedURLAtIndex(int index,\n MostVisitedPage* page) {\n \/\/ This iterates over all the pinned URLs. It might seem like it is worth\n \/\/ having a map from the index to the item but the number of items is limited\n \/\/ to the number of items the most visited section is showing on the NTP so\n \/\/ this will be fast enough for now.\n PrefService* prefs = web_ui_->GetProfile()->GetPrefs();\n const DictionaryValue* pinned_urls =\n prefs->GetDictionary(prefs::kNTPMostVisitedPinnedURLs);\n for (DictionaryValue::key_iterator it = pinned_urls->begin_keys();\n it != pinned_urls->end_keys(); ++it) {\n Value* value;\n if (pinned_urls->GetWithoutPathExpansion(*it, &value)) {\n if (!value->IsType(DictionaryValue::TYPE_DICTIONARY)) {\n \/\/ Moved on to TopSites and now going back.\n DictionaryPrefUpdate update(prefs, prefs::kNTPMostVisitedPinnedURLs);\n update.Get()->Clear();\n return false;\n }\n\n int dict_index;\n const DictionaryValue* dict = static_cast<DictionaryValue*>(value);\n if (dict->GetInteger(\"index\", &dict_index) && dict_index == index) {\n \/\/ The favicon and thumbnail URLs may be empty.\n std::string tmp_string;\n if (dict->GetString(\"faviconUrl\", &tmp_string))\n page->favicon_url = GURL(tmp_string);\n if (dict->GetString(\"thumbnailUrl\", &tmp_string))\n page->thumbnail_url = GURL(tmp_string);\n\n if (dict->GetString(\"url\", &tmp_string))\n page->url = GURL(tmp_string);\n else\n return false;\n\n return dict->GetString(\"title\", &page->title);\n }\n } else {\n NOTREACHED() << \"DictionaryValue iterators are filthy liars.\";\n }\n }\n\n return false;\n}\n\nvoid MostVisitedHandler::SetPagesValueFromTopSites(\n const history::MostVisitedURLList& data) {\n pages_value_.reset(new ListValue);\n for (size_t i = 0; i < data.size(); i++) {\n const history::MostVisitedURL& url = data[i];\n DictionaryValue* page_value = new DictionaryValue();\n if (url.url.is_empty()) {\n page_value->SetBoolean(\"filler\", true);\n pages_value_->Append(page_value);\n continue;\n }\n\n NewTabUI::SetURLTitleAndDirection(page_value,\n url.title,\n url.url);\n if (!url.favicon_url.is_empty())\n page_value->SetString(\"faviconUrl\", url.favicon_url.spec());\n\n \/\/ Special case for prepopulated pages: thumbnailUrl is different from url.\n if (url.url.spec() == l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)) {\n page_value->SetString(\"thumbnailUrl\",\n \"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL\");\n } else if (url.url.spec() ==\n l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)) {\n page_value->SetString(\"thumbnailUrl\",\n \"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL\");\n }\n\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts && ts->IsURLPinned(url.url))\n page_value->SetBoolean(\"pinned\", true);\n pages_value_->Append(page_value);\n }\n}\n\nvoid MostVisitedHandler::OnMostVisitedURLsAvailable(\n const history::MostVisitedURLList& data) {\n SetPagesValueFromTopSites(data);\n if (got_first_most_visited_request_) {\n SendPagesValue();\n }\n}\n\nbool MostVisitedHandler::IsFirstRun() {\n \/\/ If we found no pages we treat this as the first run.\n bool first_run = NewTabUI::NewTabHTMLSource::first_run() &&\n pages_value_->GetSize() ==\n MostVisitedHandler::GetPrePopulatedPages().size();\n \/\/ but first_run should only be true once.\n NewTabUI::NewTabHTMLSource::set_first_run(false);\n return first_run;\n}\n\n\/\/ static\nconst std::vector<MostVisitedHandler::MostVisitedPage>&\n MostVisitedHandler::GetPrePopulatedPages() {\n \/\/ TODO(arv): This needs to get the data from some configurable place.\n \/\/ http:\/\/crbug.com\/17630\n static std::vector<MostVisitedPage> pages;\n if (pages.empty()) {\n MostVisitedPage welcome_page = {\n l10n_util::GetStringUTF16(IDS_NEW_TAB_CHROME_WELCOME_PAGE_TITLE),\n GURL(l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL\"),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_FAVICON\")};\n pages.push_back(welcome_page);\n\n MostVisitedPage gallery_page = {\n l10n_util::GetStringUTF16(IDS_NEW_TAB_THEMES_GALLERY_PAGE_TITLE),\n GURL(l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL\"),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_FAVICON\")};\n pages.push_back(gallery_page);\n }\n\n return pages;\n}\n\nvoid MostVisitedHandler::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type != NotificationType::HISTORY_URLS_DELETED) {\n NOTREACHED();\n return;\n }\n\n \/\/ Some URLs were deleted from history. Reload the most visited list.\n HandleGetMostVisited(NULL);\n}\n\nvoid MostVisitedHandler::BlacklistURL(const GURL& url) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->AddBlacklistedURL(url);\n}\n\nstd::string MostVisitedHandler::GetDictionaryKeyForURL(const std::string& url) {\n return MD5String(url);\n}\n\n\/\/ static\nvoid MostVisitedHandler::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedURLsBlacklist);\n prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedPinnedURLs);\n}\n\n\/\/ static\nstd::vector<GURL> MostVisitedHandler::GetPrePopulatedUrls() {\n const std::vector<MostVisitedPage> pages =\n MostVisitedHandler::GetPrePopulatedPages();\n std::vector<GURL> page_urls;\n for (size_t i = 0; i < pages.size(); ++i)\n page_urls.push_back(pages[i].url);\n return page_urls;\n}\n<commit_msg>Remove obsolete constants from MostVisitedHandler<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/most_visited_handler.h\"\n\n#include <set>\n\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/md5.h\"\n#include \"base\/memory\/scoped_vector.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/history\/page_usage_data.h\"\n#include \"chrome\/browser\/history\/top_sites.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prefs\/scoped_user_pref_update.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/favicon_source.h\"\n#include \"chrome\/browser\/ui\/webui\/new_tab_ui.h\"\n#include \"chrome\/browser\/ui\/webui\/thumbnail_source.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/common\/notification_source.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\n\/\/ This struct is used when getting the pre-populated pages in case the user\n\/\/ hasn't filled up his most visited pages.\nstruct MostVisitedHandler::MostVisitedPage {\n string16 title;\n GURL url;\n GURL thumbnail_url;\n GURL favicon_url;\n};\n\nMostVisitedHandler::MostVisitedHandler()\n : got_first_most_visited_request_(false) {\n}\n\nMostVisitedHandler::~MostVisitedHandler() {\n}\n\nWebUIMessageHandler* MostVisitedHandler::Attach(WebUI* web_ui) {\n Profile* profile = web_ui->GetProfile();\n \/\/ Set up our sources for thumbnail and favicon data.\n ThumbnailSource* thumbnail_src = new ThumbnailSource(profile);\n profile->GetChromeURLDataManager()->AddDataSource(thumbnail_src);\n\n profile->GetChromeURLDataManager()->AddDataSource(\n new FaviconSource(profile, FaviconSource::FAVICON));\n\n \/\/ Get notifications when history is cleared.\n registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED,\n Source<Profile>(profile));\n\n WebUIMessageHandler* result = WebUIMessageHandler::Attach(web_ui);\n\n \/\/ We pre-emptively make a fetch for the most visited pages so we have the\n \/\/ results sooner.\n StartQueryForMostVisited();\n return result;\n}\n\nvoid MostVisitedHandler::RegisterMessages() {\n \/\/ Register ourselves as the handler for the \"mostvisited\" message from\n \/\/ Javascript.\n web_ui_->RegisterMessageCallback(\"getMostVisited\",\n NewCallback(this, &MostVisitedHandler::HandleGetMostVisited));\n\n \/\/ Register ourselves for any most-visited item blacklisting.\n web_ui_->RegisterMessageCallback(\"blacklistURLFromMostVisited\",\n NewCallback(this, &MostVisitedHandler::HandleBlacklistURL));\n web_ui_->RegisterMessageCallback(\"removeURLsFromMostVisitedBlacklist\",\n NewCallback(this, &MostVisitedHandler::HandleRemoveURLsFromBlacklist));\n web_ui_->RegisterMessageCallback(\"clearMostVisitedURLsBlacklist\",\n NewCallback(this, &MostVisitedHandler::HandleClearBlacklist));\n\n \/\/ Register ourself for pinned URL messages.\n web_ui_->RegisterMessageCallback(\"addPinnedURL\",\n NewCallback(this, &MostVisitedHandler::HandleAddPinnedURL));\n web_ui_->RegisterMessageCallback(\"removePinnedURL\",\n NewCallback(this, &MostVisitedHandler::HandleRemovePinnedURL));\n}\n\nvoid MostVisitedHandler::HandleGetMostVisited(const ListValue* args) {\n if (!got_first_most_visited_request_) {\n \/\/ If our intial data is already here, return it.\n SendPagesValue();\n got_first_most_visited_request_ = true;\n } else {\n StartQueryForMostVisited();\n }\n}\n\nvoid MostVisitedHandler::SendPagesValue() {\n if (pages_value_.get()) {\n Profile* profile = web_ui_->GetProfile();\n const DictionaryValue* url_blacklist =\n profile->GetPrefs()->GetDictionary(prefs::kNTPMostVisitedURLsBlacklist);\n bool has_blacklisted_urls = !url_blacklist->empty();\n history::TopSites* ts = profile->GetTopSites();\n if (ts)\n has_blacklisted_urls = ts->HasBlacklistedItems();\n FundamentalValue first_run(IsFirstRun());\n FundamentalValue has_blacklisted_urls_value(has_blacklisted_urls);\n web_ui_->CallJavascriptFunction(\"mostVisitedPages\",\n *(pages_value_.get()),\n first_run,\n has_blacklisted_urls_value);\n pages_value_.reset();\n }\n}\n\nvoid MostVisitedHandler::StartQueryForMostVisited() {\n \/\/ Use TopSites.\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts) {\n ts->GetMostVisitedURLs(\n &topsites_consumer_,\n NewCallback(this, &MostVisitedHandler::OnMostVisitedURLsAvailable));\n }\n}\n\nvoid MostVisitedHandler::HandleBlacklistURL(const ListValue* args) {\n std::string url = UTF16ToUTF8(ExtractStringValue(args));\n BlacklistURL(GURL(url));\n}\n\nvoid MostVisitedHandler::HandleRemoveURLsFromBlacklist(const ListValue* args) {\n DCHECK(args->GetSize() != 0);\n\n for (ListValue::const_iterator iter = args->begin();\n iter != args->end(); ++iter) {\n std::string url;\n bool r = (*iter)->GetAsString(&url);\n if (!r) {\n NOTREACHED();\n return;\n }\n UserMetrics::RecordAction(UserMetricsAction(\"MostVisited_UrlRemoved\"),\n web_ui_->GetProfile());\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->RemoveBlacklistedURL(GURL(url));\n }\n}\n\nvoid MostVisitedHandler::HandleClearBlacklist(const ListValue* args) {\n UserMetrics::RecordAction(UserMetricsAction(\"MostVisited_BlacklistCleared\"),\n web_ui_->GetProfile());\n\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->ClearBlacklistedURLs();\n}\n\nvoid MostVisitedHandler::HandleAddPinnedURL(const ListValue* args) {\n DCHECK_EQ(5U, args->GetSize()) << \"Wrong number of params to addPinnedURL\";\n MostVisitedPage mvp;\n std::string tmp_string;\n string16 tmp_string16;\n int index;\n\n bool r = args->GetString(0, &tmp_string);\n DCHECK(r) << \"Missing URL in addPinnedURL from the NTP Most Visited.\";\n mvp.url = GURL(tmp_string);\n\n r = args->GetString(1, &tmp_string16);\n DCHECK(r) << \"Missing title in addPinnedURL from the NTP Most Visited.\";\n mvp.title = tmp_string16;\n\n r = args->GetString(2, &tmp_string);\n DCHECK(r) << \"Failed to read the favicon URL in addPinnedURL from the NTP \"\n << \"Most Visited.\";\n if (!tmp_string.empty())\n mvp.favicon_url = GURL(tmp_string);\n\n r = args->GetString(3, &tmp_string);\n DCHECK(r) << \"Failed to read the thumbnail URL in addPinnedURL from the NTP \"\n << \"Most Visited.\";\n if (!tmp_string.empty())\n mvp.thumbnail_url = GURL(tmp_string);\n\n r = args->GetString(4, &tmp_string);\n DCHECK(r) << \"Missing index in addPinnedURL from the NTP Most Visited.\";\n base::StringToInt(tmp_string, &index);\n\n AddPinnedURL(mvp, index);\n}\n\nvoid MostVisitedHandler::AddPinnedURL(const MostVisitedPage& page, int index) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->AddPinnedURL(page.url, index);\n}\n\nvoid MostVisitedHandler::HandleRemovePinnedURL(const ListValue* args) {\n std::string url = UTF16ToUTF8(ExtractStringValue(args));\n RemovePinnedURL(GURL(url));\n}\n\nvoid MostVisitedHandler::RemovePinnedURL(const GURL& url) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->RemovePinnedURL(url);\n}\n\nbool MostVisitedHandler::GetPinnedURLAtIndex(int index,\n MostVisitedPage* page) {\n \/\/ This iterates over all the pinned URLs. It might seem like it is worth\n \/\/ having a map from the index to the item but the number of items is limited\n \/\/ to the number of items the most visited section is showing on the NTP so\n \/\/ this will be fast enough for now.\n PrefService* prefs = web_ui_->GetProfile()->GetPrefs();\n const DictionaryValue* pinned_urls =\n prefs->GetDictionary(prefs::kNTPMostVisitedPinnedURLs);\n for (DictionaryValue::key_iterator it = pinned_urls->begin_keys();\n it != pinned_urls->end_keys(); ++it) {\n Value* value;\n if (pinned_urls->GetWithoutPathExpansion(*it, &value)) {\n if (!value->IsType(DictionaryValue::TYPE_DICTIONARY)) {\n \/\/ Moved on to TopSites and now going back.\n DictionaryPrefUpdate update(prefs, prefs::kNTPMostVisitedPinnedURLs);\n update.Get()->Clear();\n return false;\n }\n\n int dict_index;\n const DictionaryValue* dict = static_cast<DictionaryValue*>(value);\n if (dict->GetInteger(\"index\", &dict_index) && dict_index == index) {\n \/\/ The favicon and thumbnail URLs may be empty.\n std::string tmp_string;\n if (dict->GetString(\"faviconUrl\", &tmp_string))\n page->favicon_url = GURL(tmp_string);\n if (dict->GetString(\"thumbnailUrl\", &tmp_string))\n page->thumbnail_url = GURL(tmp_string);\n\n if (dict->GetString(\"url\", &tmp_string))\n page->url = GURL(tmp_string);\n else\n return false;\n\n return dict->GetString(\"title\", &page->title);\n }\n } else {\n NOTREACHED() << \"DictionaryValue iterators are filthy liars.\";\n }\n }\n\n return false;\n}\n\nvoid MostVisitedHandler::SetPagesValueFromTopSites(\n const history::MostVisitedURLList& data) {\n pages_value_.reset(new ListValue);\n for (size_t i = 0; i < data.size(); i++) {\n const history::MostVisitedURL& url = data[i];\n DictionaryValue* page_value = new DictionaryValue();\n if (url.url.is_empty()) {\n page_value->SetBoolean(\"filler\", true);\n pages_value_->Append(page_value);\n continue;\n }\n\n NewTabUI::SetURLTitleAndDirection(page_value,\n url.title,\n url.url);\n if (!url.favicon_url.is_empty())\n page_value->SetString(\"faviconUrl\", url.favicon_url.spec());\n\n \/\/ Special case for prepopulated pages: thumbnailUrl is different from url.\n if (url.url.spec() == l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)) {\n page_value->SetString(\"thumbnailUrl\",\n \"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL\");\n } else if (url.url.spec() ==\n l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)) {\n page_value->SetString(\"thumbnailUrl\",\n \"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL\");\n }\n\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts && ts->IsURLPinned(url.url))\n page_value->SetBoolean(\"pinned\", true);\n pages_value_->Append(page_value);\n }\n}\n\nvoid MostVisitedHandler::OnMostVisitedURLsAvailable(\n const history::MostVisitedURLList& data) {\n SetPagesValueFromTopSites(data);\n if (got_first_most_visited_request_) {\n SendPagesValue();\n }\n}\n\nbool MostVisitedHandler::IsFirstRun() {\n \/\/ If we found no pages we treat this as the first run.\n bool first_run = NewTabUI::NewTabHTMLSource::first_run() &&\n pages_value_->GetSize() ==\n MostVisitedHandler::GetPrePopulatedPages().size();\n \/\/ but first_run should only be true once.\n NewTabUI::NewTabHTMLSource::set_first_run(false);\n return first_run;\n}\n\n\/\/ static\nconst std::vector<MostVisitedHandler::MostVisitedPage>&\n MostVisitedHandler::GetPrePopulatedPages() {\n \/\/ TODO(arv): This needs to get the data from some configurable place.\n \/\/ http:\/\/crbug.com\/17630\n static std::vector<MostVisitedPage> pages;\n if (pages.empty()) {\n MostVisitedPage welcome_page = {\n l10n_util::GetStringUTF16(IDS_NEW_TAB_CHROME_WELCOME_PAGE_TITLE),\n GURL(l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL\"),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_CHROME_WELCOME_PAGE_FAVICON\")};\n pages.push_back(welcome_page);\n\n MostVisitedPage gallery_page = {\n l10n_util::GetStringUTF16(IDS_NEW_TAB_THEMES_GALLERY_PAGE_TITLE),\n GURL(l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL\"),\n GURL(\"chrome:\/\/theme\/IDR_NEWTAB_THEMES_GALLERY_FAVICON\")};\n pages.push_back(gallery_page);\n }\n\n return pages;\n}\n\nvoid MostVisitedHandler::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type != NotificationType::HISTORY_URLS_DELETED) {\n NOTREACHED();\n return;\n }\n\n \/\/ Some URLs were deleted from history. Reload the most visited list.\n HandleGetMostVisited(NULL);\n}\n\nvoid MostVisitedHandler::BlacklistURL(const GURL& url) {\n history::TopSites* ts = web_ui_->GetProfile()->GetTopSites();\n if (ts)\n ts->AddBlacklistedURL(url);\n}\n\nstd::string MostVisitedHandler::GetDictionaryKeyForURL(const std::string& url) {\n return MD5String(url);\n}\n\n\/\/ static\nvoid MostVisitedHandler::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedURLsBlacklist);\n prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedPinnedURLs);\n}\n\n\/\/ static\nstd::vector<GURL> MostVisitedHandler::GetPrePopulatedUrls() {\n const std::vector<MostVisitedPage> pages =\n MostVisitedHandler::GetPrePopulatedPages();\n std::vector<GURL> page_urls;\n for (size_t i = 0; i < pages.size(); ++i)\n page_urls.push_back(pages[i].url);\n return page_urls;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QtTest\/QtTest>\n#include <QDebug>\n#include <random>\n#include <typeinfo>\n#include \"model.h\"\n#include \"model_io.h\"\n#include <fstream>\n\nusing namespace figures;\n\nusing std::make_shared;\nusing std::dynamic_pointer_cast;\n\nclass ModelModifier {\npublic:\n ModelModifier(Model &model, std::default_random_engine::result_type seed)\n : model(model)\n , generator(seed)\n , coordGen(MIN_COORD, MAX_COORD)\n , curveLengthGen(2, 20)\n , labelLengthGen(1, 20)\n , labelLetterGen('a', 'z')\n {}\n\n void doRandom() {\n int operation = randint(1, 4);\n if (operation == 1) {\n removeFigure();\n } else {\n addFigure();\n }\n }\n\n void addFigure() {\n int type = randint(0, 4);\n Point a = genPoint();\n Point b = genPoint();\n\n PFigure figure;\n switch (type) {\n case 0: {\n auto segment = make_shared<Segment>(a, b);\n segment->setArrowedA(randint(0, 1));\n segment->setArrowedB(randint(0, 1));\n figure = segment;\n } break;\n case 1:\n figure = make_shared<Ellipse>(BoundingBox({ a, b }));\n break;\n case 2:\n figure = make_shared<Rectangle>(BoundingBox({ a, b }));\n break;\n case 3: {\n int len = curveLengthGen(generator);\n std::vector<Point> points;\n for (int i = 0; i < len; i++) {\n points.push_back(genPoint());\n }\n figure = make_shared<Curve>(points);\n } break;\n case 4: {\n auto figA = getRandomBoundedFigure();\n auto figB = getRandomBoundedFigure();\n if (!figA || !figB) {\n return;\n }\n auto segment = make_shared<SegmentConnection>(figA, figB);\n segment->setArrowedA(randint(0, 1));\n segment->setArrowedB(randint(0, 1));\n figure = segment;\n }\n }\n if (randint(0, 1) == 0) {\n figure->setLabel(genLabel());\n }\n model.addFigure(figure);\n }\n\n void removeFigure() {\n if (model.size() == 0) {\n return;\n }\n int id = randint(0, model.size() - 1);\n for (auto it = model.begin(); it != model.end(); it++, id--) {\n if (id == 0) {\n model.removeFigure(it);\n return;\n }\n }\n }\n\nprivate:\n Model &model;\n std::default_random_engine generator;\n\n PBoundedFigure getRandomBoundedFigure() {\n size_t count = 0;\n for (auto fig : model) {\n auto result = dynamic_pointer_cast<BoundedFigure>(fig);\n if (result) { count++; }\n }\n if (!count) { return nullptr; }\n int id = randint(0, count - 1);\n for (auto fig : model) {\n auto result = dynamic_pointer_cast<BoundedFigure>(fig);\n if (result) {\n if (id == 0) {\n return result;\n } else {\n id--;\n }\n }\n }\n abort();\n }\n\n static const int MIN_COORD = -1e5;\n static const int MAX_COORD = 1e5;\n std::uniform_real_distribution<> coordGen;\n std::uniform_int_distribution<> curveLengthGen;\n std::uniform_int_distribution<> labelLengthGen, labelLetterGen;\n\n int randint(int l, int r) {\n return std::uniform_int_distribution<>(l, r)(generator);\n }\n\n Point genPoint() {\n double x = round(coordGen(generator) * 10) \/ 10;\n double y = round(coordGen(generator) * 10) \/ 10;\n return Point(x, y);\n }\n std::string genLabel() {\n int len = labelLengthGen(generator);\n std::string result = \"\";\n for (int i = 0; i < len; i++) {\n result += labelLetterGen(generator);\n }\n return result;\n }\n};\n\nclass FiguresComparator : public FigureVisitor {\npublic:\n FiguresComparator(const Figure &other, const std::map<PFigure, PFigure> &othersMapping) : other(other), othersMapping(othersMapping), _result(false) {}\n bool result() const { return _result; }\n\n virtual void accept(Segment &segm1) override {\n _result = false;\n auto &segm2 = dynamic_cast<const Segment&>(other);\n if (segm1.label() != segm2.label()) { return; }\n if (segm1.getArrowedA() != segm2.getArrowedA()) { return; }\n if (segm1.getArrowedB() != segm2.getArrowedB()) { return; }\n _result =\n segm1.getA() == segm2.getA() &&\n segm1.getB() == segm2.getB();\n }\n\n virtual void accept(SegmentConnection &segm1) override {\n _result = false;\n auto &segm2 = dynamic_cast<const SegmentConnection&>(other);\n if (segm1.label() != segm2.label()) { return; }\n if (segm1.getArrowedA() != segm2.getArrowedA()) { return; }\n if (segm1.getArrowedB() != segm2.getArrowedB()) { return; }\n _result =\n segm1.getFigureA() == othersMapping.at(segm2.getFigureA()) &&\n segm1.getFigureB() == othersMapping.at(segm2.getFigureB());\n }\n\n virtual void accept(Curve &curve1) override {\n _result = false;\n auto &curve2 = dynamic_cast<const Curve&>(other);\n if (curve1.label() != curve2.label()) { return; }\n _result = curve1.points == curve2.points;\n }\n\n virtual void accept(figures::Ellipse &fig1) override {\n _result = false;\n auto &fig2 = dynamic_cast<const Ellipse&>(other);\n if (fig1.label() != fig2.label()) { return; }\n _result = fig1.getBoundingBox() == fig2.getBoundingBox();\n }\n\n virtual void accept(figures::Rectangle &fig1) override {\n _result = false;\n auto &fig2 = dynamic_cast<const Rectangle&>(other);\n if (fig1.label() != fig2.label()) { return; }\n _result = fig1.getBoundingBox() == fig2.getBoundingBox();\n }\n\nprivate:\n const Figure &other;\n const std::map<PFigure, PFigure> &othersMapping;\n bool _result;\n};\n\nbool modelsAreEqual(const Model &a, const Model &b) {\n if (a.size() != b.size()) {\n return false;\n }\n\n std::map<PFigure, PFigure> others;\n\n auto ita = a.begin(), itb = b.begin();\n for (; ita != a.end() && itb != b.end(); ita++, itb++) {\n \/\/ one dereference from iterator, second dereference from shared_ptr\n Figure &a = **ita;\n Figure &b = **itb;\n if (typeid(a) != typeid(b)) {\n return false;\n }\n FiguresComparator cmp(b, others);\n a.visit(cmp);\n if (!cmp.result()) {\n return false;\n }\n assert(!others.count(*itb));\n others[*itb] = *ita;\n }\n assert(ita == a.end() && itb == b.end());\n return true;\n}\n\nclass Tests : public QObject {\n Q_OBJECT\nprivate slots:\n void testDistanceToSegmentBorder() {\n const double EPS = 1e-8;\n Segment s(Point(11, 1), Point(14, 4));\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(11, 1)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(11, 0)) - 1) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(10, 0)) - sqrt(2)) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(14, 4)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(15, 4)) - 1) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(15, 5)) - sqrt(2)) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(12, 2)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(14, 2)) - sqrt(2)) < EPS);\n }\n void testInsideSegment() {\n Segment s(Point(11, 4), Point(14, 1));\n QVERIFY( s.isInsideOrOnBorder(Point(11, 4)));\n QVERIFY(!s.isInsideOrOnBorder(Point(11, 4.001)));\n QVERIFY(!s.isInsideOrOnBorder(Point(10.999, 4)));\n QVERIFY( s.isInsideOrOnBorder(Point(14, 1)));\n QVERIFY(!s.isInsideOrOnBorder(Point(13.999, 1)));\n QVERIFY(!s.isInsideOrOnBorder(Point(14, 0.999)));\n QVERIFY(!s.isInsideOrOnBorder(Point(13.999, 0.999)));\n QVERIFY( s.isInsideOrOnBorder(Point(12, 3)));\n QVERIFY( s.isInsideOrOnBorder(Point(13, 2)));\n }\n void testDistanceToRectangleBorder() {\n const double EPS = 1e-8;\n Rectangle r({ Point(11, 1), Point(14, 4) });\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 1)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 2)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 4)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(13, 4)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 4)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12, 0)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12.5, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(13.5, 2)) - 0.5) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12.5, 3)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, 3)) - 1) < EPS);\n\n \/\/ Test distance to corners\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 5)) - sqrt(2)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 5)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, -1)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, 6)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 5)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 0)) - sqrt(5)) < EPS);\n }\n void testInsideEllipse() {\n Ellipse e({ Point(11, 1), Point(17, 5) });\n QVERIFY(!e.isInsideOrOnBorder(Point(11, 1)));\n QVERIFY(!e.isInsideOrOnBorder(Point(11.5, 1.5)));\n QVERIFY(!e.isInsideOrOnBorder(Point(17, 5)));\n QVERIFY(!e.isInsideOrOnBorder(Point(11, 5)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 5)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 1)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 3)));\n QVERIFY(e.isInsideOrOnBorder(Point(15, 3.2)));\n QVERIFY( e.isInsideOrOnBorder(Point(16.1, 4.4)));\n QVERIFY(!e.isInsideOrOnBorder(Point(16.2, 4.4)));\n QVERIFY(!e.isInsideOrOnBorder(Point(16.1, 4.5)));\n }\n void testDistanceToEllipseBorder() {\n const double EPS = 1e-8;\n Ellipse e({ Point(11, 1), Point(17, 5) });\n QVERIFY(e.getApproximateDistanceToBorder(Point(11, 1)) <= sqrt(9 + 4) + EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(11, 3)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(17, 3)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 1)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 5)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(10, 3)) >= 1 - EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 0)) >= 1 - EPS);\n QVERIFY(fabs(e.getApproximateDistanceToBorder(Point(14, 3)) - 2) < EPS);\n\n Ellipse e2({ Point(11, 1), Point(15, 7) });\n QVERIFY(fabs(e2.getApproximateDistanceToBorder(Point(13, 4)) - 2) < EPS);\n }\n\n void testSimpleSaveLoad() {\n int testId = 1;\n for (;; testId++) {\n char resourceName[64];\n snprintf(resourceName, sizeof resourceName, \":\/tests\/%02d.model\", testId);\n QFile file(resourceName);\n if (!file.open(QFile::ReadOnly | QFile::Text)) {\n break;\n }\n qDebug() << \"Trying\" << resourceName;\n\n QByteArray inData = file.readAll();\n std::stringstream inDataStream;\n inDataStream << inData.toStdString();\n\n Model model;\n try {\n inDataStream >> model;\n } catch (model_format_error &e) {\n qDebug() << e.what();\n throw;\n }\n\n std::stringstream outDataStream;\n outDataStream << model;\n std::string outStr = outDataStream.str();\n QByteArray outData(outStr.data(), outStr.length());\n QCOMPARE(outData, inData);\n }\n QVERIFY(testId > 1);\n }\n\n void testStressSaveLoad() {\n const int PASSES = 10;\n for (int pass = 0; pass < PASSES; pass++) {\n qDebug(\"pass %d\/%d\", pass + 1, PASSES);\n Model model;\n ModelModifier modifier(model, pass);\n for (int iteration = 0; iteration < 50; iteration++) {\n std::stringstream data;\n data << model;\n\n std::string saved1 = data.str();\n\n Model restored;\n data >> restored;\n\n std::stringstream data2;\n data2 << restored;\n\n Model restored2;\n data2 >> restored2;\n\n std::string saved2 = data.str();\n QCOMPARE(saved1, saved2);\n QVERIFY(modelsAreEqual(model, restored2));\n modifier.doRandom();\n }\n }\n }\n};\n\nQTEST_MAIN(Tests)\n#include \"tests.moc\"\n<commit_msg>tests.testStressSaveLoad: 100 iterations instead of 50<commit_after>#include <QtTest\/QtTest>\n#include <QDebug>\n#include <random>\n#include <typeinfo>\n#include \"model.h\"\n#include \"model_io.h\"\n#include <fstream>\n\nusing namespace figures;\n\nusing std::make_shared;\nusing std::dynamic_pointer_cast;\n\nclass ModelModifier {\npublic:\n ModelModifier(Model &model, std::default_random_engine::result_type seed)\n : model(model)\n , generator(seed)\n , coordGen(MIN_COORD, MAX_COORD)\n , curveLengthGen(2, 20)\n , labelLengthGen(1, 20)\n , labelLetterGen('a', 'z')\n {}\n\n void doRandom() {\n int operation = randint(1, 4);\n if (operation == 1) {\n removeFigure();\n } else {\n addFigure();\n }\n }\n\n void addFigure() {\n int type = randint(0, 4);\n Point a = genPoint();\n Point b = genPoint();\n\n PFigure figure;\n switch (type) {\n case 0: {\n auto segment = make_shared<Segment>(a, b);\n segment->setArrowedA(randint(0, 1));\n segment->setArrowedB(randint(0, 1));\n figure = segment;\n } break;\n case 1:\n figure = make_shared<Ellipse>(BoundingBox({ a, b }));\n break;\n case 2:\n figure = make_shared<Rectangle>(BoundingBox({ a, b }));\n break;\n case 3: {\n int len = curveLengthGen(generator);\n std::vector<Point> points;\n for (int i = 0; i < len; i++) {\n points.push_back(genPoint());\n }\n figure = make_shared<Curve>(points);\n } break;\n case 4: {\n auto figA = getRandomBoundedFigure();\n auto figB = getRandomBoundedFigure();\n if (!figA || !figB) {\n return;\n }\n auto segment = make_shared<SegmentConnection>(figA, figB);\n segment->setArrowedA(randint(0, 1));\n segment->setArrowedB(randint(0, 1));\n figure = segment;\n }\n }\n if (randint(0, 1) == 0) {\n figure->setLabel(genLabel());\n }\n model.addFigure(figure);\n }\n\n void removeFigure() {\n if (model.size() == 0) {\n return;\n }\n int id = randint(0, model.size() - 1);\n for (auto it = model.begin(); it != model.end(); it++, id--) {\n if (id == 0) {\n model.removeFigure(it);\n return;\n }\n }\n }\n\nprivate:\n Model &model;\n std::default_random_engine generator;\n\n PBoundedFigure getRandomBoundedFigure() {\n size_t count = 0;\n for (auto fig : model) {\n auto result = dynamic_pointer_cast<BoundedFigure>(fig);\n if (result) { count++; }\n }\n if (!count) { return nullptr; }\n int id = randint(0, count - 1);\n for (auto fig : model) {\n auto result = dynamic_pointer_cast<BoundedFigure>(fig);\n if (result) {\n if (id == 0) {\n return result;\n } else {\n id--;\n }\n }\n }\n abort();\n }\n\n static const int MIN_COORD = -1e5;\n static const int MAX_COORD = 1e5;\n std::uniform_real_distribution<> coordGen;\n std::uniform_int_distribution<> curveLengthGen;\n std::uniform_int_distribution<> labelLengthGen, labelLetterGen;\n\n int randint(int l, int r) {\n return std::uniform_int_distribution<>(l, r)(generator);\n }\n\n Point genPoint() {\n double x = round(coordGen(generator) * 10) \/ 10;\n double y = round(coordGen(generator) * 10) \/ 10;\n return Point(x, y);\n }\n std::string genLabel() {\n int len = labelLengthGen(generator);\n std::string result = \"\";\n for (int i = 0; i < len; i++) {\n result += labelLetterGen(generator);\n }\n return result;\n }\n};\n\nclass FiguresComparator : public FigureVisitor {\npublic:\n FiguresComparator(const Figure &other, const std::map<PFigure, PFigure> &othersMapping) : other(other), othersMapping(othersMapping), _result(false) {}\n bool result() const { return _result; }\n\n virtual void accept(Segment &segm1) override {\n _result = false;\n auto &segm2 = dynamic_cast<const Segment&>(other);\n if (segm1.label() != segm2.label()) { return; }\n if (segm1.getArrowedA() != segm2.getArrowedA()) { return; }\n if (segm1.getArrowedB() != segm2.getArrowedB()) { return; }\n _result =\n segm1.getA() == segm2.getA() &&\n segm1.getB() == segm2.getB();\n }\n\n virtual void accept(SegmentConnection &segm1) override {\n _result = false;\n auto &segm2 = dynamic_cast<const SegmentConnection&>(other);\n if (segm1.label() != segm2.label()) { return; }\n if (segm1.getArrowedA() != segm2.getArrowedA()) { return; }\n if (segm1.getArrowedB() != segm2.getArrowedB()) { return; }\n _result =\n segm1.getFigureA() == othersMapping.at(segm2.getFigureA()) &&\n segm1.getFigureB() == othersMapping.at(segm2.getFigureB());\n }\n\n virtual void accept(Curve &curve1) override {\n _result = false;\n auto &curve2 = dynamic_cast<const Curve&>(other);\n if (curve1.label() != curve2.label()) { return; }\n _result = curve1.points == curve2.points;\n }\n\n virtual void accept(figures::Ellipse &fig1) override {\n _result = false;\n auto &fig2 = dynamic_cast<const Ellipse&>(other);\n if (fig1.label() != fig2.label()) { return; }\n _result = fig1.getBoundingBox() == fig2.getBoundingBox();\n }\n\n virtual void accept(figures::Rectangle &fig1) override {\n _result = false;\n auto &fig2 = dynamic_cast<const Rectangle&>(other);\n if (fig1.label() != fig2.label()) { return; }\n _result = fig1.getBoundingBox() == fig2.getBoundingBox();\n }\n\nprivate:\n const Figure &other;\n const std::map<PFigure, PFigure> &othersMapping;\n bool _result;\n};\n\nbool modelsAreEqual(const Model &a, const Model &b) {\n if (a.size() != b.size()) {\n return false;\n }\n\n std::map<PFigure, PFigure> others;\n\n auto ita = a.begin(), itb = b.begin();\n for (; ita != a.end() && itb != b.end(); ita++, itb++) {\n \/\/ one dereference from iterator, second dereference from shared_ptr\n Figure &a = **ita;\n Figure &b = **itb;\n if (typeid(a) != typeid(b)) {\n return false;\n }\n FiguresComparator cmp(b, others);\n a.visit(cmp);\n if (!cmp.result()) {\n return false;\n }\n assert(!others.count(*itb));\n others[*itb] = *ita;\n }\n assert(ita == a.end() && itb == b.end());\n return true;\n}\n\nclass Tests : public QObject {\n Q_OBJECT\nprivate slots:\n void testDistanceToSegmentBorder() {\n const double EPS = 1e-8;\n Segment s(Point(11, 1), Point(14, 4));\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(11, 1)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(11, 0)) - 1) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(10, 0)) - sqrt(2)) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(14, 4)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(15, 4)) - 1) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(15, 5)) - sqrt(2)) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(12, 2)) - 0) < EPS);\n QVERIFY(fabs(s.getApproximateDistanceToBorder(Point(14, 2)) - sqrt(2)) < EPS);\n }\n void testInsideSegment() {\n Segment s(Point(11, 4), Point(14, 1));\n QVERIFY( s.isInsideOrOnBorder(Point(11, 4)));\n QVERIFY(!s.isInsideOrOnBorder(Point(11, 4.001)));\n QVERIFY(!s.isInsideOrOnBorder(Point(10.999, 4)));\n QVERIFY( s.isInsideOrOnBorder(Point(14, 1)));\n QVERIFY(!s.isInsideOrOnBorder(Point(13.999, 1)));\n QVERIFY(!s.isInsideOrOnBorder(Point(14, 0.999)));\n QVERIFY(!s.isInsideOrOnBorder(Point(13.999, 0.999)));\n QVERIFY( s.isInsideOrOnBorder(Point(12, 3)));\n QVERIFY( s.isInsideOrOnBorder(Point(13, 2)));\n }\n void testDistanceToRectangleBorder() {\n const double EPS = 1e-8;\n Rectangle r({ Point(11, 1), Point(14, 4) });\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 1)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 2)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(11, 4)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(13, 4)) - 0) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 4)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12, 0)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12.5, 2)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(13.5, 2)) - 0.5) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(12.5, 3)) - 1) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, 3)) - 1) < EPS);\n\n \/\/ Test distance to corners\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(15, 5)) - sqrt(2)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 5)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, -1)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(10, 6)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 5)) - sqrt(5)) < EPS);\n QVERIFY(fabs(r.getApproximateDistanceToBorder(Point(16, 0)) - sqrt(5)) < EPS);\n }\n void testInsideEllipse() {\n Ellipse e({ Point(11, 1), Point(17, 5) });\n QVERIFY(!e.isInsideOrOnBorder(Point(11, 1)));\n QVERIFY(!e.isInsideOrOnBorder(Point(11.5, 1.5)));\n QVERIFY(!e.isInsideOrOnBorder(Point(17, 5)));\n QVERIFY(!e.isInsideOrOnBorder(Point(11, 5)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 5)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 1)));\n QVERIFY(e.isInsideOrOnBorder(Point(14, 3)));\n QVERIFY(e.isInsideOrOnBorder(Point(15, 3.2)));\n QVERIFY( e.isInsideOrOnBorder(Point(16.1, 4.4)));\n QVERIFY(!e.isInsideOrOnBorder(Point(16.2, 4.4)));\n QVERIFY(!e.isInsideOrOnBorder(Point(16.1, 4.5)));\n }\n void testDistanceToEllipseBorder() {\n const double EPS = 1e-8;\n Ellipse e({ Point(11, 1), Point(17, 5) });\n QVERIFY(e.getApproximateDistanceToBorder(Point(11, 1)) <= sqrt(9 + 4) + EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(11, 3)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(17, 3)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 1)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 5)) <= EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(10, 3)) >= 1 - EPS);\n QVERIFY(e.getApproximateDistanceToBorder(Point(14, 0)) >= 1 - EPS);\n QVERIFY(fabs(e.getApproximateDistanceToBorder(Point(14, 3)) - 2) < EPS);\n\n Ellipse e2({ Point(11, 1), Point(15, 7) });\n QVERIFY(fabs(e2.getApproximateDistanceToBorder(Point(13, 4)) - 2) < EPS);\n }\n\n void testSimpleSaveLoad() {\n int testId = 1;\n for (;; testId++) {\n char resourceName[64];\n snprintf(resourceName, sizeof resourceName, \":\/tests\/%02d.model\", testId);\n QFile file(resourceName);\n if (!file.open(QFile::ReadOnly | QFile::Text)) {\n break;\n }\n qDebug() << \"Trying\" << resourceName;\n\n QByteArray inData = file.readAll();\n std::stringstream inDataStream;\n inDataStream << inData.toStdString();\n\n Model model;\n try {\n inDataStream >> model;\n } catch (model_format_error &e) {\n qDebug() << e.what();\n throw;\n }\n\n std::stringstream outDataStream;\n outDataStream << model;\n std::string outStr = outDataStream.str();\n QByteArray outData(outStr.data(), outStr.length());\n QCOMPARE(outData, inData);\n }\n QVERIFY(testId > 1);\n }\n\n void testStressSaveLoad() {\n const int PASSES = 10;\n for (int pass = 0; pass < PASSES; pass++) {\n qDebug(\"pass %d\/%d\", pass + 1, PASSES);\n Model model;\n ModelModifier modifier(model, pass);\n for (int iteration = 0; iteration < 100; iteration++) {\n std::stringstream data;\n data << model;\n\n std::string saved1 = data.str();\n\n Model restored;\n data >> restored;\n\n std::stringstream data2;\n data2 << restored;\n\n Model restored2;\n data2 >> restored2;\n\n std::string saved2 = data.str();\n QCOMPARE(saved1, saved2);\n QVERIFY(modelsAreEqual(model, restored2));\n modifier.doRandom();\n }\n }\n }\n};\n\nQTEST_MAIN(Tests)\n#include \"tests.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"PiecewisePolynomial.h\"\n#include <stdexcept>\n#include <cassert>\n#include <algorithm>\n#include <complex>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialMatrix> const& polynomials, std::vector<double> const& segment_times) :\n PiecewisePolynomialBase(segment_times),\n polynomials(polynomials)\n{\n assert(segment_times.size() == (polynomials.size() + 1));\n for (int i = 1; i < getNumberOfSegments(); i++) {\n if (polynomials[i].rows() != polynomials[0].rows())\n throw std::runtime_error(\"The polynomial matrix for each segment must have the same number of rows.\");\n if (polynomials[i].cols() != polynomials[0].cols())\n throw std::runtime_error(\"The polynomial matrix for each segment must have the same number of columns.\");\n }\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialType> const& polynomials, std::vector<double> const& segment_times) :\n PiecewisePolynomialBase(segment_times)\n{\n assert(segment_times.size() == (polynomials.size() + 1));\n\n for (int i = 0; i < polynomials.size(); i++) {\n PolynomialMatrix matrix(1, 1);\n matrix(0, 0) = polynomials[i];\n this->polynomials.push_back(matrix);\n }\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial() {\n \/\/ empty\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::derivative(int derivative_order) const {\n PiecewisePolynomial ret = *this;\n for (auto it = ret.polynomials.begin(); it != ret.polynomials.end(); ++it) {\n PolynomialMatrix& matrix = *it;\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n matrix(row, col) = matrix(row, col).derivative(derivative_order);\n }\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(double value_at_start_time) const {\n CoefficientMatrix matrix_value_at_start_time = CoefficientMatrix::Constant(rows(), cols(), value_at_start_time);\n return integral(matrix_value_at_start_time);\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(const Eigen::Ref<PiecewisePolynomial<CoefficientType>::CoefficientMatrix> & value_at_start_time) const {\n PiecewisePolynomial ret = *this;\n for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {\n PolynomialMatrix& matrix = ret.polynomials[segment_index];\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n if (segment_index == 0) {\n matrix(row, col) = matrix(row, col).integral(value_at_start_time(row, col));\n }\n else {\n matrix(row, col) = matrix(row, col).integral(ret.segmentValueAtGlobalAbscissa(segment_index - 1, getStartTime(segment_index), row, col));\n }\n }\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\ndouble PiecewisePolynomial<CoefficientType>::scalarValue(double t, Eigen::DenseIndex row, Eigen::DenseIndex col) {\n int segment_index = getSegmentIndex(t);\n return segmentValueAtGlobalAbscissa(segment_index, t, row, col);\n}\n\ntemplate <typename CoefficientType>\nEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> PiecewisePolynomial<CoefficientType>::value(double t) {\n int segment_index = getSegmentIndex(t);\n Eigen::Matrix<double, PolynomialMatrix::RowsAtCompileTime, PolynomialMatrix::ColsAtCompileTime> ret(rows(), cols());\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n ret(row, col) = segmentValueAtGlobalAbscissa(segment_index, t, row, col);\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\nconst Polynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::getPolynomial(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n segmentNumberRangeCheck(segment_index);\n return polynomials[segment_index](row, col);\n}\n\ntemplate <typename CoefficientType>\nint PiecewisePolynomial<CoefficientType>::getSegmentPolynomialDegree(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n segmentNumberRangeCheck(segment_index);\n return polynomials[segment_index](row, col).getDegree();\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator+=(const PiecewisePolynomial<CoefficientType>& other) {\n if (!segmentTimesEqual(other, 1e-10))\n throw runtime_error(\"Addition not yet implemented when segment times are not equal\");\n for (int i = 0; i < polynomials.size(); i++)\n polynomials[i] += other.polynomials[i];\n return *this;\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator*=(const PiecewisePolynomial<CoefficientType>& other) {\n if (!segmentTimesEqual(other, 1e-10))\n throw runtime_error(\"Multiplication not yet implemented when segment times are not equal\");\n for (int i = 0; i < polynomials.size(); i++)\n polynomials[i] *= other.polynomials[i];\n return *this;\n}\n\ntemplate <typename CoefficientType>\nconst PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator+(const PiecewisePolynomial<CoefficientType> &other) const {\n PiecewisePolynomial<CoefficientType> ret = *this;\n ret += other;\n return ret;\n}\n\ntemplate <typename CoefficientType>\nconst PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator*(const PiecewisePolynomial<CoefficientType> &other) const {\n PiecewisePolynomial<CoefficientType> ret = *this;\n ret *= other;\n return ret;\n}\n\ntemplate <typename CoefficientType>\nbool PiecewisePolynomial<CoefficientType>::isApprox(const PiecewisePolynomial<CoefficientType>& other, double tol) const {\n if (rows() != other.rows() || cols() != other.cols())\n return false;\n\n if (!segmentTimesEqual(other, tol))\n return false;\n\n for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {\n const PolynomialMatrix& matrix = polynomials[segment_index];\n const PolynomialMatrix& other_matrix = other.polynomials[segment_index];\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n if (!matrix(row, col).isApprox(other_matrix(row, col), tol))\n return false;\n }\n }\n }\n return true;\n}\n\ntemplate<typename CoefficientType>\nvoid PiecewisePolynomial<CoefficientType>::shiftRight(double offset) {\n for (auto it = segment_times.begin(); it != segment_times.end(); ++it) {\n *it += offset;\n }\n}\n\ntemplate <typename CoefficientType>\ndouble PiecewisePolynomial<CoefficientType>::segmentValueAtGlobalAbscissa(int segment_index, double t, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n return polynomials[segment_index](row, col).value(t - getStartTime(segment_index));\n}\n\ntemplate <typename CoefficientType>\nEigen::DenseIndex PiecewisePolynomial<CoefficientType>::rows() const\n{\n if (polynomials.size() > 0)\n return polynomials[0].rows();\n else\n throw std::runtime_error(\"PiecewisePolynomial has no segments. Number of rows is undefined.\");\n}\n\ntemplate <typename CoefficientType>\nEigen::DenseIndex PiecewisePolynomial<CoefficientType>::cols() const\n{\n if (polynomials.size() > 0)\n return polynomials[0].cols();\n else\n throw std::runtime_error(\"PiecewisePolynomial has no segments. Number of columns is undefined.\");\n}\n\ntemplate class DLLEXPORT PiecewisePolynomial<double>;\n\/\/template class DLLEXPORT PiecewisePolynomial<std::complex<double>>; \/\/ doesn't work yet\n<commit_msg>Bug fix: add implementation for getPolynomialMatrix.<commit_after>#include \"PiecewisePolynomial.h\"\n#include <stdexcept>\n#include <cassert>\n#include <algorithm>\n#include <complex>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialMatrix> const& polynomials, std::vector<double> const& segment_times) :\n PiecewisePolynomialBase(segment_times),\n polynomials(polynomials)\n{\n assert(segment_times.size() == (polynomials.size() + 1));\n for (int i = 1; i < getNumberOfSegments(); i++) {\n if (polynomials[i].rows() != polynomials[0].rows())\n throw std::runtime_error(\"The polynomial matrix for each segment must have the same number of rows.\");\n if (polynomials[i].cols() != polynomials[0].cols())\n throw std::runtime_error(\"The polynomial matrix for each segment must have the same number of columns.\");\n }\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialType> const& polynomials, std::vector<double> const& segment_times) :\n PiecewisePolynomialBase(segment_times)\n{\n assert(segment_times.size() == (polynomials.size() + 1));\n\n for (int i = 0; i < polynomials.size(); i++) {\n PolynomialMatrix matrix(1, 1);\n matrix(0, 0) = polynomials[i];\n this->polynomials.push_back(matrix);\n }\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>::PiecewisePolynomial() {\n \/\/ empty\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::derivative(int derivative_order) const {\n PiecewisePolynomial ret = *this;\n for (auto it = ret.polynomials.begin(); it != ret.polynomials.end(); ++it) {\n PolynomialMatrix& matrix = *it;\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n matrix(row, col) = matrix(row, col).derivative(derivative_order);\n }\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(double value_at_start_time) const {\n CoefficientMatrix matrix_value_at_start_time = CoefficientMatrix::Constant(rows(), cols(), value_at_start_time);\n return integral(matrix_value_at_start_time);\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(const Eigen::Ref<PiecewisePolynomial<CoefficientType>::CoefficientMatrix> & value_at_start_time) const {\n PiecewisePolynomial ret = *this;\n for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {\n PolynomialMatrix& matrix = ret.polynomials[segment_index];\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n if (segment_index == 0) {\n matrix(row, col) = matrix(row, col).integral(value_at_start_time(row, col));\n }\n else {\n matrix(row, col) = matrix(row, col).integral(ret.segmentValueAtGlobalAbscissa(segment_index - 1, getStartTime(segment_index), row, col));\n }\n }\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\ndouble PiecewisePolynomial<CoefficientType>::scalarValue(double t, Eigen::DenseIndex row, Eigen::DenseIndex col) {\n int segment_index = getSegmentIndex(t);\n return segmentValueAtGlobalAbscissa(segment_index, t, row, col);\n}\n\ntemplate <typename CoefficientType>\nEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> PiecewisePolynomial<CoefficientType>::value(double t) {\n int segment_index = getSegmentIndex(t);\n Eigen::Matrix<double, PolynomialMatrix::RowsAtCompileTime, PolynomialMatrix::ColsAtCompileTime> ret(rows(), cols());\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n ret(row, col) = segmentValueAtGlobalAbscissa(segment_index, t, row, col);\n }\n }\n return ret;\n}\n\ntemplate <typename CoefficientType>\nconst typename PiecewisePolynomial<CoefficientType>::PolynomialMatrix& PiecewisePolynomial<CoefficientType>::getPolynomialMatrix(int segment_index) const {\n return polynomials[segment_index];\n}\n\ntemplate <typename CoefficientType>\nconst Polynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::getPolynomial(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n segmentNumberRangeCheck(segment_index);\n return polynomials[segment_index](row, col);\n}\n\ntemplate <typename CoefficientType>\nint PiecewisePolynomial<CoefficientType>::getSegmentPolynomialDegree(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n segmentNumberRangeCheck(segment_index);\n return polynomials[segment_index](row, col).getDegree();\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator+=(const PiecewisePolynomial<CoefficientType>& other) {\n if (!segmentTimesEqual(other, 1e-10))\n throw runtime_error(\"Addition not yet implemented when segment times are not equal\");\n for (int i = 0; i < polynomials.size(); i++)\n polynomials[i] += other.polynomials[i];\n return *this;\n}\n\ntemplate <typename CoefficientType>\nPiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator*=(const PiecewisePolynomial<CoefficientType>& other) {\n if (!segmentTimesEqual(other, 1e-10))\n throw runtime_error(\"Multiplication not yet implemented when segment times are not equal\");\n for (int i = 0; i < polynomials.size(); i++)\n polynomials[i] *= other.polynomials[i];\n return *this;\n}\n\ntemplate <typename CoefficientType>\nconst PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator+(const PiecewisePolynomial<CoefficientType> &other) const {\n PiecewisePolynomial<CoefficientType> ret = *this;\n ret += other;\n return ret;\n}\n\ntemplate <typename CoefficientType>\nconst PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator*(const PiecewisePolynomial<CoefficientType> &other) const {\n PiecewisePolynomial<CoefficientType> ret = *this;\n ret *= other;\n return ret;\n}\n\ntemplate <typename CoefficientType>\nbool PiecewisePolynomial<CoefficientType>::isApprox(const PiecewisePolynomial<CoefficientType>& other, double tol) const {\n if (rows() != other.rows() || cols() != other.cols())\n return false;\n\n if (!segmentTimesEqual(other, tol))\n return false;\n\n for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {\n const PolynomialMatrix& matrix = polynomials[segment_index];\n const PolynomialMatrix& other_matrix = other.polynomials[segment_index];\n for (DenseIndex row = 0; row < rows(); row++) {\n for (DenseIndex col = 0; col < cols(); col++) {\n if (!matrix(row, col).isApprox(other_matrix(row, col), tol))\n return false;\n }\n }\n }\n return true;\n}\n\ntemplate<typename CoefficientType>\nvoid PiecewisePolynomial<CoefficientType>::shiftRight(double offset) {\n for (auto it = segment_times.begin(); it != segment_times.end(); ++it) {\n *it += offset;\n }\n}\n\ntemplate <typename CoefficientType>\ndouble PiecewisePolynomial<CoefficientType>::segmentValueAtGlobalAbscissa(int segment_index, double t, Eigen::DenseIndex row, Eigen::DenseIndex col) const {\n return polynomials[segment_index](row, col).value(t - getStartTime(segment_index));\n}\n\ntemplate <typename CoefficientType>\nEigen::DenseIndex PiecewisePolynomial<CoefficientType>::rows() const\n{\n if (polynomials.size() > 0)\n return polynomials[0].rows();\n else\n throw std::runtime_error(\"PiecewisePolynomial has no segments. Number of rows is undefined.\");\n}\n\ntemplate <typename CoefficientType>\nEigen::DenseIndex PiecewisePolynomial<CoefficientType>::cols() const\n{\n if (polynomials.size() > 0)\n return polynomials[0].cols();\n else\n throw std::runtime_error(\"PiecewisePolynomial has no segments. Number of columns is undefined.\");\n}\n\ntemplate class DLLEXPORT PiecewisePolynomial<double>;\n\/\/template class DLLEXPORT PiecewisePolynomial<std::complex<double>>; \/\/ doesn't work yet\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @author Mohammad S. Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 Mohammad S. Babaei\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * Manage website pages.\n *\/\n\n\n#include <ctime>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/format.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <pqxx\/pqxx>\n#include <Wt\/WApplication>\n#include <Wt\/WPushButton>\n#include <Wt\/WString>\n#include <Wt\/WTable>\n#include <Wt\/WTemplate>\n#include <Wt\/WText>\n#include <Wt\/WWidget>\n#include <CoreLib\/CDate.hpp>\n#include <CoreLib\/Crypto.hpp>\n#include <CoreLib\/Database.hpp>\n#include <CoreLib\/FileSystem.hpp>\n#include <CoreLib\/Log.hpp>\n#include \"CgiEnv.hpp\"\n#include \"CgiRoot.hpp\"\n#include \"CmsSubscribers.hpp\"\n#include \"Div.hpp\"\n#include \"Pool.hpp\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace pqxx;\nusing namespace Wt;\nusing namespace CoreLib;\nusing namespace Service;\n\nstruct CmsSubscribers::Impl : public Wt::WObject\n{\npublic:\n enum class Table : unsigned char {\n All,\n EnFa,\n En,\n Fa,\n Inactive\n };\n\npublic:\n WContainerWidget *SubscribersTableContainer;\n\npublic:\n Impl();\n ~Impl();\n\npublic:\n void OnAllButtonPressed();\n void OnEnFaButtonPressed();\n void OnEnButtonPressed();\n void OnFaButtonPressed();\n void OnInactiveButtonPressed();\n\nprivate:\n void GetDate(const std::string &timeSinceEpoch, Wt::WString &out_date);\n void GetSubscriptionTypeName(const std::string &type, Wt::WString &out_name);\n\n void FillDataTable(const CmsSubscribers::Impl::Table &table);\n};\n\nCmsSubscribers::CmsSubscribers()\n : Page(),\n m_pimpl(make_unique<CmsSubscribers::Impl>())\n{\n this->clear();\n this->setId(\"CmsSubscribersPage\");\n this->addWidget(this->Layout());\n}\n\nCmsSubscribers::~CmsSubscribers() = default;\n\nWWidget *CmsSubscribers::Layout()\n{\n Div *container = new Div(\"CmsSubscribers\", \"container-fluid\");\n\n try {\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n string htmlData;\n string file;\n if (cgiEnv->GetInformation().Client.Language.Code\n == CgiEnv::InformationRecord::ClientRecord::LanguageCode::Fa) {\n file = \"..\/templates\/cms-subscribers-fa.wtml\";\n } else {\n file = \"..\/templates\/cms-subscribers.wtml\";\n }\n\n if (CoreLib::FileSystem::Read(file, htmlData)) {\n \/\/\/ Fill the template\n WTemplate *tmpl = new WTemplate(container);\n tmpl->setTemplateText(WString::fromUTF8(htmlData), TextFormat::XHTMLUnsafeText);\n\n WPushButton *allSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-all\"));\n allSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *englishFarsiSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-english-farsi\"));\n englishFarsiSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *englishSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-english\"));\n englishSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *farsiSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-farsi\"));\n farsiSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *inactiveSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-inactive\"));\n inactiveSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n m_pimpl->SubscribersTableContainer = new Div(\"SubscribersTableContainer\", \"subscribers-table-container\");\n\n tmpl->bindWidget(\"subscribers-title\", new WText(tr(\"cms-subscribers-page-title\")));\n\n tmpl->bindWidget(\"subscribers-table\", m_pimpl->SubscribersTableContainer);\n\n tmpl->bindWidget(\"all-subscribers-button\", allSubscribersPushButton);\n tmpl->bindWidget(\"english-farsi-subscribers-button\", englishFarsiSubscribersPushButton);\n tmpl->bindWidget(\"english-subscribers-button\", englishSubscribersPushButton);\n tmpl->bindWidget(\"farsi-subscribers-button\", farsiSubscribersPushButton);\n tmpl->bindWidget(\"inactive-subscribers-button\", inactiveSubscribersPushButton);\n\n allSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnAllButtonPressed);\n englishFarsiSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnEnFaButtonPressed);\n englishSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnEnButtonPressed);\n farsiSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnFaButtonPressed);\n inactiveSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnInactiveButtonPressed);\n\n allSubscribersPushButton->setFocus();\n }\n }\n\n catch (const boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (const std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n\n return container;\n}\n\nCmsSubscribers::Impl::Impl()\n{\n\n}\n\nCmsSubscribers::Impl::~Impl() = default;\n\nvoid CmsSubscribers::Impl::OnAllButtonPressed()\n{\n FillDataTable(Table::All);\n}\n\nvoid CmsSubscribers::Impl::OnEnFaButtonPressed()\n{\n FillDataTable(Table::EnFa);\n}\n\nvoid CmsSubscribers::Impl::OnEnButtonPressed()\n{\n FillDataTable(Table::En);\n}\n\nvoid CmsSubscribers::Impl::OnFaButtonPressed()\n{\n FillDataTable(Table::Fa);\n}\n\nvoid CmsSubscribers::Impl::OnInactiveButtonPressed()\n{\n FillDataTable(Table::Inactive);\n}\n\nvoid CmsSubscribers::Impl::GetDate(const std::string &timeSinceEpoch, Wt::WString &out_date)\n{\n try {\n time_t tt = lexical_cast<time_t>(timeSinceEpoch);\n\n struct tm *utc_tm = gmtime(&tt);\n\n int year = utc_tm->tm_year + 1900;\n int month = utc_tm->tm_mon + 1;\n int day = utc_tm->tm_mday;\n\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n if (cgiEnv->GetInformation().Client.Language.Code\n == CgiEnv::InformationRecord::ClientRecord::LanguageCode::Fa) {\n out_date = (boost::wformat(L\"%1%\/%2%\/%3%\/\")\n % lexical_cast<wstring>(year)\n % lexical_cast<wstring>(month)\n % lexical_cast<wstring>(day)).str();\n } else {\n out_date = CDate::DateConv::FormatToPersianNums(CDate::DateConv::ToJalali(year, month, day));\n }\n } catch (...) {\n out_date = L\"-\";\n }\n}\n\nvoid CmsSubscribers::Impl::GetSubscriptionTypeName(const std::string &type, Wt::WString &out_name)\n{\n static const std::string EN_FA_TYPE(\"en_fa\");\n static const std::string EN_TYPE(\"en\");\n static const std::string FA_TYPE(\"fa\");\n static const std::string NONE_TYPE(\"none\");\n\n static const std::string EN_FA_NAME(tr(\"cms-subscribers-subscription-en-fa\").toUTF8());\n static const std::string EN_NAME(tr(\"cms-subscribers-subscription-en\").toUTF8());\n static const std::string FA_NAME(tr(\"cms-subscribers-subscription-fa\").toUTF8());\n static const std::string NONE_NAME(tr(\"cms-subscribers-subscription-none\").toUTF8());\n\n if (type == EN_FA_TYPE) {\n out_name = WString::fromUTF8(EN_FA_NAME);\n } else if (type == EN_TYPE) {\n out_name = WString::fromUTF8(EN_NAME);\n } else if (type == FA_TYPE) {\n out_name = WString::fromUTF8(FA_NAME);\n } else if (type == NONE_TYPE) {\n out_name = WString::fromUTF8(NONE_NAME);\n }\n}\n\nvoid CmsSubscribers::Impl::FillDataTable(const CmsSubscribers::Impl::Table &tableType)\n{\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n try {\n SubscribersTableContainer->clear();\n\n WTable *table = new WTable(SubscribersTableContainer);\n table->setStyleClass(\"table table-striped table-hover\");\n table->setHeaderCount(1, Orientation::Horizontal);\n\n table->elementAt(0, 0)->addWidget(new WText(tr(\"cms-subscribers-no\")));\n table->elementAt(0, 1)->addWidget(new WText(tr(\"cms-subscribers-inbox\")));\n table->elementAt(0, 2)->addWidget(new WText(tr(\"cms-subscribers-subscription\")));\n table->elementAt(0, 3)->addWidget(new WText(tr(\"cms-subscribers-pending-confirm\")));\n table->elementAt(0, 4)->addWidget(new WText(tr(\"cms-subscribers-pending-cancel\")));\n table->elementAt(0, 5)->addWidget(new WText(tr(\"cms-subscribers-join-date\")));\n table->elementAt(0, 6)->addWidget(new WText(tr(\"cms-subscribers-update-date\")));\n table->elementAt(0, 7)->addWidget(new WText(tr(\"cms-subscribers-uuid\")));\n\n string query;\n switch (tableType) {\n case Table::All:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::EnFa:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'en_fa' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::En:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'en' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::Fa:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'fa' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::Inactive:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'none' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n }\n\n LOG_INFO(\"Running query...\", query, cgiEnv->GetInformation().ToJson());\n\n auto conn = Pool::Database().Connection();\n conn->activate();\n pqxx::work txn(*conn.get());\n\n result r = txn.exec(query);\n\n int i = 0;\n for (const auto & row : r) {\n ++i;\n\n const string inbox(row[\"inbox\"].c_str());\n const string uuid(row[\"uuid\"].c_str());\n const string subscription(row[\"subscription\"].c_str());\n const string pendingConfirm(row[\"pending_confirm\"].c_str());\n const string pendingCancel(row[\"pending_cancel\"].c_str());\n const string joinDate(row[\"join_date\"].c_str());\n const string updateDate(row[\"update_date\"].c_str());\n\n WString subscriptionTypeName;\n WString pendingConfirmTypeName;\n WString pendingCancelTypeName;\n\n this->GetSubscriptionTypeName(subscription, subscriptionTypeName);\n this->GetSubscriptionTypeName(pendingConfirm, pendingConfirmTypeName);\n this->GetSubscriptionTypeName(pendingCancel, pendingCancelTypeName);\n\n WString joinDateFormatted;\n WString updateDateFormatted;\n\n this->GetDate(joinDate, joinDateFormatted);\n this->GetDate(updateDate, updateDateFormatted);\n\n table->elementAt(i, 0)->addWidget(new WText(WString::fromUTF8(lexical_cast<string>(i))));\n table->elementAt(i, 1)->addWidget(new WText(WString::fromUTF8(inbox)));\n table->elementAt(i, 2)->addWidget(new WText(subscriptionTypeName));\n table->elementAt(i, 3)->addWidget(new WText(pendingConfirmTypeName));\n table->elementAt(i, 4)->addWidget(new WText(pendingCancelTypeName));\n table->elementAt(i, 5)->addWidget(new WText(joinDateFormatted));\n table->elementAt(i, 6)->addWidget(new WText(updateDateFormatted));\n table->elementAt(i, 7)->addWidget(new WText(WString::fromUTF8(uuid)));\n }\n }\n\n catch (const pqxx::sql_error &ex) {\n LOG_ERROR(ex.what(), ex.query(), cgiEnv->GetInformation().ToJson());\n }\n\n catch (const boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());\n }\n\n catch (const std::exception &ex) {\n LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());\n }\n}\n<commit_msg>fix the wrong date format (jalali\/gregorian) on subscribers page<commit_after>\/**\n * @file\n * @author Mohammad S. Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 Mohammad S. Babaei\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * Manage website pages.\n *\/\n\n\n#include <ctime>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/format.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <pqxx\/pqxx>\n#include <Wt\/WApplication>\n#include <Wt\/WPushButton>\n#include <Wt\/WString>\n#include <Wt\/WTable>\n#include <Wt\/WTemplate>\n#include <Wt\/WText>\n#include <Wt\/WWidget>\n#include <CoreLib\/CDate.hpp>\n#include <CoreLib\/Crypto.hpp>\n#include <CoreLib\/Database.hpp>\n#include <CoreLib\/FileSystem.hpp>\n#include <CoreLib\/Log.hpp>\n#include \"CgiEnv.hpp\"\n#include \"CgiRoot.hpp\"\n#include \"CmsSubscribers.hpp\"\n#include \"Div.hpp\"\n#include \"Pool.hpp\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace pqxx;\nusing namespace Wt;\nusing namespace CoreLib;\nusing namespace Service;\n\nstruct CmsSubscribers::Impl : public Wt::WObject\n{\npublic:\n enum class Table : unsigned char {\n All,\n EnFa,\n En,\n Fa,\n Inactive\n };\n\npublic:\n WContainerWidget *SubscribersTableContainer;\n\npublic:\n Impl();\n ~Impl();\n\npublic:\n void OnAllButtonPressed();\n void OnEnFaButtonPressed();\n void OnEnButtonPressed();\n void OnFaButtonPressed();\n void OnInactiveButtonPressed();\n\nprivate:\n void GetDate(const std::string &timeSinceEpoch, Wt::WString &out_date);\n void GetSubscriptionTypeName(const std::string &type, Wt::WString &out_name);\n\n void FillDataTable(const CmsSubscribers::Impl::Table &table);\n};\n\nCmsSubscribers::CmsSubscribers()\n : Page(),\n m_pimpl(make_unique<CmsSubscribers::Impl>())\n{\n this->clear();\n this->setId(\"CmsSubscribersPage\");\n this->addWidget(this->Layout());\n}\n\nCmsSubscribers::~CmsSubscribers() = default;\n\nWWidget *CmsSubscribers::Layout()\n{\n Div *container = new Div(\"CmsSubscribers\", \"container-fluid\");\n\n try {\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n string htmlData;\n string file;\n if (cgiEnv->GetInformation().Client.Language.Code\n == CgiEnv::InformationRecord::ClientRecord::LanguageCode::Fa) {\n file = \"..\/templates\/cms-subscribers-fa.wtml\";\n } else {\n file = \"..\/templates\/cms-subscribers.wtml\";\n }\n\n if (CoreLib::FileSystem::Read(file, htmlData)) {\n \/\/\/ Fill the template\n WTemplate *tmpl = new WTemplate(container);\n tmpl->setTemplateText(WString::fromUTF8(htmlData), TextFormat::XHTMLUnsafeText);\n\n WPushButton *allSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-all\"));\n allSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *englishFarsiSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-english-farsi\"));\n englishFarsiSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *englishSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-english\"));\n englishSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *farsiSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-farsi\"));\n farsiSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n WPushButton *inactiveSubscribersPushButton = new WPushButton(tr(\"cms-subscribers-inactive\"));\n inactiveSubscribersPushButton->setStyleClass(\"btn btn-default\");\n\n m_pimpl->SubscribersTableContainer = new Div(\"SubscribersTableContainer\", \"subscribers-table-container\");\n\n tmpl->bindWidget(\"subscribers-title\", new WText(tr(\"cms-subscribers-page-title\")));\n\n tmpl->bindWidget(\"subscribers-table\", m_pimpl->SubscribersTableContainer);\n\n tmpl->bindWidget(\"all-subscribers-button\", allSubscribersPushButton);\n tmpl->bindWidget(\"english-farsi-subscribers-button\", englishFarsiSubscribersPushButton);\n tmpl->bindWidget(\"english-subscribers-button\", englishSubscribersPushButton);\n tmpl->bindWidget(\"farsi-subscribers-button\", farsiSubscribersPushButton);\n tmpl->bindWidget(\"inactive-subscribers-button\", inactiveSubscribersPushButton);\n\n allSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnAllButtonPressed);\n englishFarsiSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnEnFaButtonPressed);\n englishSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnEnButtonPressed);\n farsiSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnFaButtonPressed);\n inactiveSubscribersPushButton->clicked().connect(m_pimpl.get(), &CmsSubscribers::Impl::OnInactiveButtonPressed);\n\n allSubscribersPushButton->setFocus();\n }\n }\n\n catch (const boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (const std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n\n return container;\n}\n\nCmsSubscribers::Impl::Impl()\n{\n\n}\n\nCmsSubscribers::Impl::~Impl() = default;\n\nvoid CmsSubscribers::Impl::OnAllButtonPressed()\n{\n FillDataTable(Table::All);\n}\n\nvoid CmsSubscribers::Impl::OnEnFaButtonPressed()\n{\n FillDataTable(Table::EnFa);\n}\n\nvoid CmsSubscribers::Impl::OnEnButtonPressed()\n{\n FillDataTable(Table::En);\n}\n\nvoid CmsSubscribers::Impl::OnFaButtonPressed()\n{\n FillDataTable(Table::Fa);\n}\n\nvoid CmsSubscribers::Impl::OnInactiveButtonPressed()\n{\n FillDataTable(Table::Inactive);\n}\n\nvoid CmsSubscribers::Impl::GetDate(const std::string &timeSinceEpoch, Wt::WString &out_date)\n{\n try {\n time_t tt = lexical_cast<time_t>(timeSinceEpoch);\n\n struct tm *utc_tm = gmtime(&tt);\n\n int year = utc_tm->tm_year + 1900;\n int month = utc_tm->tm_mon + 1;\n int day = utc_tm->tm_mday;\n\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n if (cgiEnv->GetInformation().Client.Language.Code\n == CgiEnv::InformationRecord::ClientRecord::LanguageCode::En) {\n out_date = (boost::wformat(L\"%1%\/%2%\/%3%\")\n % lexical_cast<wstring>(year)\n % lexical_cast<wstring>(month)\n % lexical_cast<wstring>(day)).str();\n } else {\n out_date = CDate::DateConv::FormatToPersianNums(CDate::DateConv::ToJalali(year, month, day));\n }\n } catch (...) {\n out_date = L\"-\";\n }\n}\n\nvoid CmsSubscribers::Impl::GetSubscriptionTypeName(const std::string &type, Wt::WString &out_name)\n{\n static const std::string EN_FA_TYPE(\"en_fa\");\n static const std::string EN_TYPE(\"en\");\n static const std::string FA_TYPE(\"fa\");\n static const std::string NONE_TYPE(\"none\");\n\n static const std::string EN_FA_NAME(tr(\"cms-subscribers-subscription-en-fa\").toUTF8());\n static const std::string EN_NAME(tr(\"cms-subscribers-subscription-en\").toUTF8());\n static const std::string FA_NAME(tr(\"cms-subscribers-subscription-fa\").toUTF8());\n static const std::string NONE_NAME(tr(\"cms-subscribers-subscription-none\").toUTF8());\n\n if (type == EN_FA_TYPE) {\n out_name = WString::fromUTF8(EN_FA_NAME);\n } else if (type == EN_TYPE) {\n out_name = WString::fromUTF8(EN_NAME);\n } else if (type == FA_TYPE) {\n out_name = WString::fromUTF8(FA_NAME);\n } else if (type == NONE_TYPE) {\n out_name = WString::fromUTF8(NONE_NAME);\n }\n}\n\nvoid CmsSubscribers::Impl::FillDataTable(const CmsSubscribers::Impl::Table &tableType)\n{\n CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());\n CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();\n\n try {\n SubscribersTableContainer->clear();\n\n WTable *table = new WTable(SubscribersTableContainer);\n table->setStyleClass(\"table table-striped table-hover\");\n table->setHeaderCount(1, Orientation::Horizontal);\n\n table->elementAt(0, 0)->addWidget(new WText(tr(\"cms-subscribers-no\")));\n table->elementAt(0, 1)->addWidget(new WText(tr(\"cms-subscribers-inbox\")));\n table->elementAt(0, 2)->addWidget(new WText(tr(\"cms-subscribers-subscription\")));\n table->elementAt(0, 3)->addWidget(new WText(tr(\"cms-subscribers-pending-confirm\")));\n table->elementAt(0, 4)->addWidget(new WText(tr(\"cms-subscribers-pending-cancel\")));\n table->elementAt(0, 5)->addWidget(new WText(tr(\"cms-subscribers-join-date\")));\n table->elementAt(0, 6)->addWidget(new WText(tr(\"cms-subscribers-update-date\")));\n table->elementAt(0, 7)->addWidget(new WText(tr(\"cms-subscribers-uuid\")));\n\n string query;\n switch (tableType) {\n case Table::All:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::EnFa:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'en_fa' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::En:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'en' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::Fa:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'fa' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n case Table::Inactive:\n query.assign((format(\"SELECT inbox, uuid, subscription, pending_confirm, pending_cancel, join_date, update_date\"\n \" FROM \\\"%1%\\\" WHERE subscription = 'none' ORDER BY inbox COLLATE \\\"en_US.UTF-8\\\" ASC;\")\n % Pool::Database().GetTableName(\"SUBSCRIBERS\")).str());\n break;\n }\n\n LOG_INFO(\"Running query...\", query, cgiEnv->GetInformation().ToJson());\n\n auto conn = Pool::Database().Connection();\n conn->activate();\n pqxx::work txn(*conn.get());\n\n result r = txn.exec(query);\n\n int i = 0;\n for (const auto & row : r) {\n ++i;\n\n const string inbox(row[\"inbox\"].c_str());\n const string uuid(row[\"uuid\"].c_str());\n const string subscription(row[\"subscription\"].c_str());\n const string pendingConfirm(row[\"pending_confirm\"].c_str());\n const string pendingCancel(row[\"pending_cancel\"].c_str());\n const string joinDate(row[\"join_date\"].c_str());\n const string updateDate(row[\"update_date\"].c_str());\n\n WString subscriptionTypeName;\n WString pendingConfirmTypeName;\n WString pendingCancelTypeName;\n\n this->GetSubscriptionTypeName(subscription, subscriptionTypeName);\n this->GetSubscriptionTypeName(pendingConfirm, pendingConfirmTypeName);\n this->GetSubscriptionTypeName(pendingCancel, pendingCancelTypeName);\n\n WString joinDateFormatted;\n WString updateDateFormatted;\n\n this->GetDate(joinDate, joinDateFormatted);\n this->GetDate(updateDate, updateDateFormatted);\n\n table->elementAt(i, 0)->addWidget(new WText(WString::fromUTF8(lexical_cast<string>(i))));\n table->elementAt(i, 1)->addWidget(new WText(WString::fromUTF8(inbox)));\n table->elementAt(i, 2)->addWidget(new WText(subscriptionTypeName));\n table->elementAt(i, 3)->addWidget(new WText(pendingConfirmTypeName));\n table->elementAt(i, 4)->addWidget(new WText(pendingCancelTypeName));\n table->elementAt(i, 5)->addWidget(new WText(joinDateFormatted));\n table->elementAt(i, 6)->addWidget(new WText(updateDateFormatted));\n table->elementAt(i, 7)->addWidget(new WText(WString::fromUTF8(uuid)));\n }\n }\n\n catch (const pqxx::sql_error &ex) {\n LOG_ERROR(ex.what(), ex.query(), cgiEnv->GetInformation().ToJson());\n }\n\n catch (const boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());\n }\n\n catch (const std::exception &ex) {\n LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>menus are way too wide, wrong checkbox\/radiobutton width<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>compilation fix: disable method inside the name space<commit_after><|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include \"glproc.hpp\"\n\n\n#if !defined(_WIN32)\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE \/\/ for dladdr\n#endif\n#include <dlfcn.h>\n#endif\n\n\n\/*\n * Handle to the true OpenGL library.\n * XXX: Not really used yet.\n *\/\n#if defined(_WIN32)\nHINSTANCE __libGlHandle = NULL;\n#else\nvoid *__libGlHandle = NULL;\n#endif\n\n\n\n#if defined(_WIN32)\n\n#error Unsupported\n\n#elif defined(__APPLE__)\n\n#error Unsupported\n\n#else\n\n\/*\n * Lookup a public EGL\/GL\/GLES symbol\n *\n * The spec states that eglGetProcAddress should only be used for non-core\n * (extensions) entry-points. Core entry-points should be taken directly from\n * the API specific libraries.\n *\n * We cannot tell here which API a symbol is meant for here (as some are\n * exported by many). So this code assumes that the appropriate shared\n * libraries have been loaded previously (either dlopened with RTLD_GLOBAL, or\n * as part of the executable dependencies), and that their symbols available\n * for quering via dlsym(RTLD_NEXT, ...).\n *\/\nvoid *\n__getPublicProcAddress(const char *procName)\n{\n#if defined(ANDROID)\n \/*\n * Android does not support LD_PRELOAD. It is assumed that applications\n * are explicitely loading egltrace.so.\n *\/\n void *lib = NULL;\n if (procName[0] == 'e' && procName[1] == 'g' && procName[2] == 'l') {\n static void *libEGL = NULL;\n if (!libEGL) {\n libEGL = dlopen(\"libEGL.so\", RTLD_LOCAL | RTLD_LAZY);\n }\n lib = libEGL;\n } else if (procName[0] == 'g' && procName[1] == 'l') {\n \/* TODO: Support libGLESv1_CM.so too somehow. *\/\n static void *libGLESv2 = NULL;\n if (!libGLESv2) {\n libGLESv2 = dlopen(\"libGLESv2.so\", RTLD_LOCAL | RTLD_LAZY);\n }\n lib = libGLESv2;\n }\n if (lib) {\n return dlsym(lib, procName);\n }\n return NULL;\n#else\n return dlsym(RTLD_NEXT, procName);\n#endif\n}\n\n\/*\n * Lookup a private EGL\/GL\/GLES symbol\n *\n * Private symbols should always be available through eglGetProcAddress, and\n * they are guaranteed to work with any context bound (regardless of the API).\n *\n * However, per issue#57, eglGetProcAddress returns garbage on some\n * implementations, and the spec states that implementations may choose to also\n * export extension functions publicly, so we always attempt dlsym before\n * eglGetProcAddress to mitigate that.\n *\/\nvoid *\n__getPrivateProcAddress(const char *procName)\n{\n void *proc;\n proc = __getPublicProcAddress(procName);\n if (!proc &&\n ((procName[0] == 'e' && procName[1] == 'g' && procName[2] == 'l') ||\n (procName[0] == 'g' && procName[1] == 'l'))) {\n proc = (void *) __eglGetProcAddress(procName);\n }\n\n return proc;\n}\n\n#endif\n<commit_msg>gles: fix lookup for GLESv1 functions<commit_after>\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include \"glproc.hpp\"\n\n\n#if !defined(_WIN32)\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE \/\/ for dladdr\n#endif\n#include <dlfcn.h>\n#endif\n\n\n\/*\n * Handle to the true OpenGL library.\n * XXX: Not really used yet.\n *\/\n#if defined(_WIN32)\nHINSTANCE __libGlHandle = NULL;\n#else\nvoid *__libGlHandle = NULL;\n#endif\n\n\n\n#if defined(_WIN32)\n\n#error Unsupported\n\n#elif defined(__APPLE__)\n\n#error Unsupported\n\n#else\n\n\/*\n * Lookup a public EGL\/GL\/GLES symbol\n *\n * The spec states that eglGetProcAddress should only be used for non-core\n * (extensions) entry-points. Core entry-points should be taken directly from\n * the API specific libraries.\n *\n * We cannot tell here which API a symbol is meant for here (as some are\n * exported by many). So this code assumes that the appropriate shared\n * libraries have been loaded previously (either dlopened with RTLD_GLOBAL, or\n * as part of the executable dependencies), and that their symbols available\n * for quering via dlsym(RTLD_NEXT, ...).\n *\/\nvoid *\n__getPublicProcAddress(const char *procName)\n{\n#if defined(ANDROID)\n \/*\n * Android does not support LD_PRELOAD. It is assumed that applications\n * are explicitely loading egltrace.so.\n *\/\n\n if (procName[0] == 'e' && procName[1] == 'g' && procName[2] == 'l') {\n static void *libEGL = NULL;\n if (!libEGL) {\n libEGL = dlopen(\"libEGL.so\", RTLD_LOCAL | RTLD_LAZY);\n if (!libEGL) {\n return NULL;\n }\n }\n return dlsym(libEGL, procName);\n }\n\n if (procName[0] == 'g' && procName[1] == 'l') {\n \/* TODO: Use GLESv1\/GLESv2 on a per-context basis. *\/\n static void *sym = NULL;\n\n static void *libGLESv2 = NULL;\n if (!libGLESv2) {\n libGLESv2 = dlopen(\"libGLESv2.so\", RTLD_LOCAL | RTLD_LAZY);\n }\n if (libGLESv2) {\n sym = dlsym(libGLESv2, procName);\n }\n if (sym) {\n return sym;\n }\n\n static void *libGLESv1 = NULL;\n if (!libGLESv1) {\n libGLESv1 = dlopen(\"libGLESv1_CM.so\", RTLD_LOCAL | RTLD_LAZY);\n }\n if (libGLESv1) {\n sym = dlsym(libGLESv1, procName);\n }\n if (sym) {\n return sym;\n }\n }\n\n return NULL;\n#else\n return dlsym(RTLD_NEXT, procName);\n#endif\n}\n\n\/*\n * Lookup a private EGL\/GL\/GLES symbol\n *\n * Private symbols should always be available through eglGetProcAddress, and\n * they are guaranteed to work with any context bound (regardless of the API).\n *\n * However, per issue#57, eglGetProcAddress returns garbage on some\n * implementations, and the spec states that implementations may choose to also\n * export extension functions publicly, so we always attempt dlsym before\n * eglGetProcAddress to mitigate that.\n *\/\nvoid *\n__getPrivateProcAddress(const char *procName)\n{\n void *proc;\n proc = __getPublicProcAddress(procName);\n if (!proc &&\n ((procName[0] == 'e' && procName[1] == 'g' && procName[2] == 'l') ||\n (procName[0] == 'g' && procName[1] == 'l'))) {\n proc = (void *) __eglGetProcAddress(procName);\n }\n\n return proc;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <SDL2\/SDL.h>\n#define GL_GLEXT_PROTOTYPES\n#include <SDL2\/SDL_opengl.h>\n\/\/#include <OpenGL\/glu.h>\n#include <iostream>\n#include <array>\n#include <algorithm>\n#include <cassert>\n#include \"glm\/gtc\/constants.hpp\"\n#include \"renderer.h\"\n#include \"scene.h\"\n#include \"algorithm.h\"\n#include \"resource.h\"\n\n\nstatic const int SCREEN_WIDTH = 640;\nstatic const int SCREEN_HEIGHT = 480;\n\ntemplate <typename T, unsigned int S>\nclass DelayQueue\n{\n T arr[S];\n unsigned int current;\npublic:\n DelayQueue(const T& init_v = T())\n : current (0)\n {\n for (auto p = arr; p < arr + S; ++p) *p = init_v;\n }\n T Head() const\n {\n return arr[current];\n }\n T PushPop(const T& v)\n {\n auto r = arr[current];\n arr[current] = v;\n current = (current + 1) % S;\n return r;\n }\n};\n\nnamespace hardrock\n{\n class SpriteModel\n {\n glm::vec2 size;\n glm::vec2 anchor;\n std::uint16_t tex_id;\n std::uint16_t padding;\n public:\n SpriteModel(const glm::vec2& size, const glm::vec2& anchor, std::uint16_t tex_id)\n : size(size)\n , anchor(anchor)\n , tex_id(tex_id)\n , padding(0)\n {\n }\n void SetTileWithPosScaleDir(const glm::vec2& pos, const glm::vec2& scale, const glm::vec2& norm_dir, Tile* p_out_tile)\n {\n const glm::vec2 size = this->size * scale;\n const glm::mat2 transform(norm_dir.x * size.x, norm_dir.y * size.x, -norm_dir.y * size.y, norm_dir.x * size.y);\n p_out_tile->transform = transform;\n p_out_tile->translate = pos - transform * this->anchor;\n p_out_tile->tex_id = this->tex_id;\n p_out_tile->color = { 240, 240, 240, 255 };\n }\n void SetTileWithPos(const glm::vec2& pos, Tile* p_out_tile)\n {\n const glm::mat2 transform(this->size.x, 0, 0, this->size.y);\n p_out_tile->transform = transform;\n p_out_tile->translate = pos - transform * this->anchor;\n p_out_tile->tex_id = this->tex_id;\n p_out_tile->color = { 240, 240, 240, 255 };\n }\n };\n \n struct IControlTarget\n {\n virtual ~IControlTarget() { }\n virtual void Move(float x, float y) = 0;\n };\n \n class KeyboardControl\n {\n int left, right, up, down;\n public:\n KeyboardControl() : left(0), right(0), up(0), down(0) { }\n void KeyStatus(int scan_code, bool pressed)\n {\n int v = pressed ? 1 : 0;\n switch (scan_code)\n {\n case SDL_SCANCODE_UP:\n this->up = v;\n break;\n case SDL_SCANCODE_DOWN:\n this->down = v;\n break;\n case SDL_SCANCODE_LEFT:\n this->left = v;\n break;\n case SDL_SCANCODE_RIGHT:\n this->right = v;\n break;\n default:\n return;\n }\n }\n void Control(IControlTarget* p_target)\n {\n int x = this->right - this->left;\n int y = this->down - this->up;\n if (x && y)\n p_target->Move(x * glm::one_over_root_two<float>(), y * glm::one_over_root_two<float>());\n else\n p_target->Move(static_cast<float>(x), static_cast<float>(y));\n }\n };\n\n}\n\nint main(int argc, char* args[])\n{\n hardrock::PackResourceManager resource_manager(\"res.pack\");\n\n if (SDL_Init(SDL_INIT_VIDEO) < 0)\n {\n std::cerr << \"SDL_Init failed: \" << SDL_GetError() << std::endl;\n return -1;\n }\n\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n \n auto p_window = SDL_CreateWindow(\n \"SDL test\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\n if (p_window == nullptr)\n {\n std::cerr << \"SDL_CreateWindow failed: \" << SDL_GetError() << std::endl;\n return -2;\n }\n\n auto p_context = SDL_GL_CreateContext(p_window);\n if (p_context == nullptr)\n {\n std::cerr << \"SDL_GL_CreateContext failed: \" << SDL_GetError() << std::endl;\n return -3;\n }\n\n {\n auto up_vert_shader_data = std::move(resource_manager.LoadResource(hardrock::FnvHash(\"test.vert\")));\n assert(up_vert_shader_data);\n auto up_frag_shader_data = std::move(resource_manager.LoadResource(hardrock::FnvHash(\"test.frag\")));\n assert(up_frag_shader_data);\n auto up_render_device = hardrock::RenderDevice::Create(SCREEN_WIDTH, SCREEN_HEIGHT, &up_vert_shader_data->at(0), up_vert_shader_data->size(), &up_frag_shader_data->at(0), up_frag_shader_data->size());\n assert(up_render_device);\n std::array<std::uint32_t, 4> tex_res_id_list =\n {\n hardrock::FnvHash(\"self_l.webp\"),\n hardrock::FnvHash(\"self_m.webp\"),\n hardrock::FnvHash(\"self_r.webp\"),\n hardrock::FnvHash(\"bullet_0.webp\"),\n };\n std::sort(tex_res_id_list.begin(), tex_res_id_list.end());\n auto up_tex_res_bundle = resource_manager.LoadResourceBatch(&tex_res_id_list[0], tex_res_id_list.size());\n assert(up_tex_res_bundle);\n int r;\n hardrock::RenderDevice::AtlasIdType atlas_id;\n r = up_render_device->CreateTextureAtlas(*up_tex_res_bundle, 16, 16, 16, atlas_id);\n assert(r == 0);\n hardrock::RenderDevice::BatchIdType batch_id;\n r = up_render_device->CreateBatch(64, atlas_id, batch_id);\n assert(r == 0);\n hardrock::RenderDevice::BatchIdType player_batch_id;\n r = up_render_device->CreateBatch(64, atlas_id, player_batch_id);\n assert(r == 0);\n std::array<hardrock::RenderDevice::RenderQuest, 2> render_quest_list\n {{\n { nullptr, {}, {}, batch_id, {} },\n { nullptr, {}, {}, player_batch_id, {} },\n }};\n \n assert(r == 0);\n auto tex_self_m_find_iter = std::lower_bound(tex_res_id_list.begin(), tex_res_id_list.end(), hardrock::FnvHash(\"self_m.webp\"));\n assert(*tex_self_m_find_iter == hardrock::FnvHash(\"self_m.webp\"));\n auto const self_m_tex_id = static_cast<hardrock::TileSet::IndexType>(tex_self_m_find_iter - tex_res_id_list.begin());\n hardrock::SpriteModel sprite_model({128, 128}, {0.5, 0.5}, self_m_tex_id);\n hardrock::SpriteModel player_model({64, 64}, {0.5, 0.5}, self_m_tex_id);\n \n hardrock::TileSet tile_set(64);\n \n const float pi = glm::pi<float>();\n const float double_pi = pi * 2.0f;\n const float half_pi = glm::half_pi<float>();\n const size_t sprite_count = 16;\n struct SpriteData\n {\n glm::vec2 pos;\n float radius;\n hardrock::TileSet::IndexType tile_idx;\n hardrock::TileSet::IndexType padding;\n } sprite_data[sprite_count];\n for (int i = 0; i < sprite_count; ++i)\n {\n auto const tile_idx = tile_set.TileAdd();\n int x = i % 4;\n int y = i \/ 4;\n sprite_data[i] = { { x * 128, y * 128 }, (i % 4) * half_pi, tile_idx, 0 };\n }\n struct PlayerData\n {\n glm::vec2 pos;\n hardrock::TileSet::IndexType tile_idx;\n hardrock::TileSet::IndexType padding;\n } player_data;\n hardrock::TileSet player_tile_set(8);\n player_data.tile_idx = player_tile_set.TileAdd();\n player_model.SetTileWithPos({}, &player_tile_set.TileAt(player_data.tile_idx));\n \n class ControlTranslate : public hardrock::IControlTarget\n {\n glm::vec2* p_translate;\n float x, y;\n public:\n ControlTranslate(glm::vec2* p_translate, float x = 0, float y = 0)\n : p_translate(p_translate)\n , x(x), y(y)\n {\n }\n void Move(float x, float y) override\n {\n this->x += x;\n this->y += y;\n p_translate->x = this->x;\n p_translate->y = this->y;\n }\n };\n ControlTranslate control_translate(&player_data.pos, SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.8);\n hardrock::KeyboardControl keyboard_control;\n\n typedef decltype(SDL_GetTicks()) tick_t;\n tick_t last_fps_tick = SDL_GetTicks();\n tick_t last_fps_frame = 0;\n DelayQueue<unsigned int, 6> tick_time_queue;\n while (true)\n {\n SDL_Event e;\n bool b_quit = false;\n while (SDL_PollEvent(&e) != 0)\n {\n switch(e.type)\n {\n case SDL_QUIT:\n b_quit = true;\n break;\n case SDL_KEYDOWN:\n if (!e.key.repeat)\n {\n keyboard_control.KeyStatus(e.key.keysym.scancode, e.key.state);\n }\n break;\n case SDL_KEYUP:\n keyboard_control.KeyStatus(e.key.keysym.scancode, e.key.state);\n break;\n }\n }\n if (b_quit)\n {\n break;\n }\n\n keyboard_control.Control(&control_translate);\n\n for (int i = 0; i < sprite_count; ++i)\n {\n SpriteData& s = sprite_data[i];\n s.radius += 0.01f;\n if (s.radius > pi)\n s.radius -= double_pi;\n glm::vec2 norm;\n hardrock::FastSinCos(s.radius, &norm.y, &norm.x);\n sprite_model.SetTileWithPosScaleDir(s.pos, {1, 1}, norm, &tile_set.TileAt(s.tile_idx));\n hardrock::Tile tile0;\n sprite_model.SetTileWithPos(s.pos, &tile0);\n hardrock::Tile tile1;\n sprite_model.SetTileWithPosScaleDir(s.pos, {1, 1}, {1, 0}, &tile1);\n assert(tile0.transform == tile1.transform);\n assert(tile0.translate == tile1.translate);\n }\n\n glClearColor(0.2f, 0.0f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n {\n auto tile_seq = tile_set.GetTileSequence();\n render_quest_list[0].p_tile_seq = &tile_seq;\n auto player_tile_seq = player_tile_set.GetTileSequence();\n render_quest_list[1].p_tile_seq = &player_tile_seq;\n render_quest_list[1].translate = player_data.pos;\n up_render_device->Render(render_quest_list.begin(), render_quest_list.end());\n }\n glFlush();\n\n SDL_GL_SwapWindow(p_window);\n\n tick_t tick_5 = tick_time_queue.Head();\n tick_t len_5_x = SDL_GetTicks() - tick_5;\n if (len_5_x < 90)\n {\n SDL_Delay(100 - len_5_x);\n }\n tick_t now = SDL_GetTicks();\n tick_time_queue.PushPop(now);\n ++last_fps_frame;\n if (last_fps_frame >= 60)\n {\n std::cout << \"fps: \" << 60000.0 \/ (now - last_fps_tick) << std::endl;\n last_fps_tick = now;\n last_fps_frame = 0;\n }\n }\n }\n \n SDL_GL_DeleteContext(p_context);\n SDL_DestroyWindow(p_window);\n SDL_Quit();\n\n std::cout << \"Quit\" << std::endl;\n\n return 0;\n}<commit_msg>Player can shoot bullets.<commit_after>#include <SDL2\/SDL.h>\n#define GL_GLEXT_PROTOTYPES\n#include <SDL2\/SDL_opengl.h>\n\/\/#include <OpenGL\/glu.h>\n#include <iostream>\n#include <array>\n#include <algorithm>\n#include <cassert>\n#include \"glm\/gtc\/constants.hpp\"\n#include \"renderer.h\"\n#include \"scene.h\"\n#include \"algorithm.h\"\n#include \"resource.h\"\n\n\nstatic const int SCREEN_WIDTH = 640;\nstatic const int SCREEN_HEIGHT = 480;\n\ntemplate <typename T, unsigned int S>\nclass DelayQueue\n{\n T arr[S];\n unsigned int current;\npublic:\n DelayQueue(const T& init_v = T())\n : current (0)\n {\n for (auto p = arr; p < arr + S; ++p) *p = init_v;\n }\n T Head() const\n {\n return arr[current];\n }\n T PushPop(const T& v)\n {\n auto r = arr[current];\n arr[current] = v;\n current = (current + 1) % S;\n return r;\n }\n};\n\nnamespace hardrock\n{\n class SpriteModel\n {\n glm::vec2 size;\n glm::vec2 anchor;\n std::uint16_t tex_id;\n std::uint16_t padding;\n public:\n SpriteModel(const glm::vec2& size, const glm::vec2& anchor, std::uint16_t tex_id)\n : size(size)\n , anchor(anchor)\n , tex_id(tex_id)\n , padding(0)\n {\n }\n void SetTileWithPosScaleDir(const glm::vec2& pos, const glm::vec2& scale, const glm::vec2& norm_dir, Tile* p_out_tile)\n {\n const glm::vec2 size = this->size * scale;\n const glm::mat2 transform(norm_dir.x * size.x, norm_dir.y * size.x, -norm_dir.y * size.y, norm_dir.x * size.y);\n p_out_tile->transform = transform;\n p_out_tile->translate = pos - transform * this->anchor;\n p_out_tile->tex_id = this->tex_id;\n p_out_tile->color = { 240, 240, 240, 255 };\n }\n void SetTileWithPos(const glm::vec2& pos, Tile* p_out_tile)\n {\n const glm::mat2 transform(this->size.x, 0, 0, this->size.y);\n p_out_tile->transform = transform;\n p_out_tile->translate = pos - transform * this->anchor;\n p_out_tile->tex_id = this->tex_id;\n p_out_tile->color = { 240, 240, 240, 255 };\n }\n };\n \n class KeyboardControl\n {\n int left, right, up, down;\n std::uint32_t button_mask;\n public:\n KeyboardControl() : left(0), right(0), up(0), down(0) { }\n void KeyStatus(int scan_code, bool pressed)\n {\n int v = pressed ? 1 : 0;\n switch (scan_code)\n {\n case SDL_SCANCODE_UP:\n this->up = v;\n break;\n case SDL_SCANCODE_DOWN:\n this->down = v;\n break;\n case SDL_SCANCODE_LEFT:\n this->left = v;\n break;\n case SDL_SCANCODE_RIGHT:\n this->right = v;\n break;\n case SDL_SCANCODE_SPACE:\n if (pressed)\n this->button_mask |= 1;\n else\n this->button_mask &= ~ 1;\n break;\n default:\n return;\n }\n }\n glm::vec2 GetMoveVector() const\n {\n int x = this->right - this->left;\n int y = this->down - this->up;\n if (x && y)\n return {x * glm::one_over_root_two<float>(), y * glm::one_over_root_two<float>()};\n else\n return {static_cast<float>(x), static_cast<float>(y)};\n }\n std::uint32_t GetButtonMask() const\n {\n return this->button_mask;\n }\n };\n\n}\n\nint main(int argc, char* args[])\n{\n hardrock::PackResourceManager resource_manager(\"res.pack\");\n\n if (SDL_Init(SDL_INIT_VIDEO) < 0)\n {\n std::cerr << \"SDL_Init failed: \" << SDL_GetError() << std::endl;\n return -1;\n }\n\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n \n auto p_window = SDL_CreateWindow(\n \"SDL test\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\n if (p_window == nullptr)\n {\n std::cerr << \"SDL_CreateWindow failed: \" << SDL_GetError() << std::endl;\n return -2;\n }\n\n auto p_context = SDL_GL_CreateContext(p_window);\n if (p_context == nullptr)\n {\n std::cerr << \"SDL_GL_CreateContext failed: \" << SDL_GetError() << std::endl;\n return -3;\n }\n\n {\n auto up_vert_shader_data = std::move(resource_manager.LoadResource(hardrock::FnvHash(\"test.vert\")));\n assert(up_vert_shader_data);\n auto up_frag_shader_data = std::move(resource_manager.LoadResource(hardrock::FnvHash(\"test.frag\")));\n assert(up_frag_shader_data);\n auto up_render_device = hardrock::RenderDevice::Create(SCREEN_WIDTH, SCREEN_HEIGHT, &up_vert_shader_data->at(0), up_vert_shader_data->size(), &up_frag_shader_data->at(0), up_frag_shader_data->size());\n assert(up_render_device);\n std::array<std::uint32_t, 5> tex_res_id_list =\n {\n hardrock::FnvHash(\"self_l.webp\"),\n hardrock::FnvHash(\"self_m.webp\"),\n hardrock::FnvHash(\"self_r.webp\"),\n hardrock::FnvHash(\"bullet_0.webp\"),\n hardrock::FnvHash(\"bullet_1.webp\"),\n };\n std::sort(tex_res_id_list.begin(), tex_res_id_list.end());\n auto up_tex_res_bundle = resource_manager.LoadResourceBatch(&tex_res_id_list[0], tex_res_id_list.size());\n assert(up_tex_res_bundle);\n int r;\n hardrock::RenderDevice::AtlasIdType atlas_id;\n r = up_render_device->CreateTextureAtlas(*up_tex_res_bundle, 16, 16, 16, atlas_id);\n assert(r == 0);\n hardrock::RenderDevice::BatchIdType batch_id;\n r = up_render_device->CreateBatch(64, atlas_id, batch_id);\n assert(r == 0);\n hardrock::RenderDevice::BatchIdType sprite_batch_id;\n r = up_render_device->CreateBatch(512, atlas_id, sprite_batch_id);\n assert(r == 0);\n std::array<hardrock::RenderDevice::RenderQuest, 2> render_quest_list\n {{\n { nullptr, {}, {}, batch_id, {} },\n { nullptr, {}, {}, sprite_batch_id, {} },\n }};\n \n auto tex_self_m_find_iter = std::lower_bound(tex_res_id_list.begin(), tex_res_id_list.end(), hardrock::FnvHash(\"self_m.webp\"));\n assert(*tex_self_m_find_iter == hardrock::FnvHash(\"self_m.webp\"));\n auto const self_m_tex_id = static_cast<hardrock::TileSet::IndexType>(tex_self_m_find_iter - tex_res_id_list.begin());\n hardrock::SpriteModel sprite_model({128, 128}, {0.5, 0.5}, self_m_tex_id);\n hardrock::SpriteModel player_model({64, 64}, {0.5, 0.5}, self_m_tex_id);\n \n auto tex_bullet_1_find_iter = std::lower_bound(tex_res_id_list.begin(), tex_res_id_list.end(), hardrock::FnvHash(\"bullet_1.webp\"));\n assert(*tex_bullet_1_find_iter == hardrock::FnvHash(\"bullet_1.webp\"));\n auto const bullet_1_id = static_cast<hardrock::TileSet::IndexType>(tex_bullet_1_find_iter - tex_res_id_list.begin());\n hardrock::SpriteModel bullet_1_model({32, 32}, {0.5, 0.5}, bullet_1_id);\n \n hardrock::SpriteModel empty_model({}, {}, 0);\n \n hardrock::TileSet tile_set(64);\n \n const float pi = glm::pi<float>();\n const float double_pi = pi * 2.0f;\n const float half_pi = glm::half_pi<float>();\n const size_t sprite_count = 16;\n struct SpriteData\n {\n glm::vec2 pos;\n float radius;\n hardrock::TileSet::IndexType tile_idx;\n hardrock::TileSet::IndexType padding;\n } sprite_data[sprite_count];\n for (int i = 0; i < sprite_count; ++i)\n {\n auto const tile_idx = tile_set.TileAdd();\n int x = i % 4;\n int y = i \/ 4;\n sprite_data[i] = { { x * 128, y * 128 }, (i % 4) * half_pi, tile_idx, 0 };\n }\n hardrock::TileSet sprite_tile_set(512);\n \n struct PlayerData\n {\n glm::vec2 pos;\n hardrock::TileSet::IndexType tile_idx;\n hardrock::TileSet::IndexType padding;\n };\n PlayerData player_data =\n {\n { SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.9 },\n sprite_tile_set.TileAdd(),\n };\n player_model.SetTileWithPos(player_data.pos, &sprite_tile_set.TileAt(player_data.tile_idx));\n \n const auto player_bullet_tile_head_idx = sprite_tile_set.TileAdd();\n empty_model.SetTileWithPos({}, &sprite_tile_set.TileAt(player_bullet_tile_head_idx));\n \n struct PlayerBulletData\n {\n glm::vec2 pos;\n hardrock::TileSet::IndexType tile_idx;\n hardrock::TileSet::IndexType padding;\n };\n const std::size_t player_bullet_count = 64;\n std::array<PlayerBulletData, player_bullet_count> player_bullet_data;\n std::size_t active_player_bullet_count = 0;\n \n hardrock::KeyboardControl keyboard_control;\n\n typedef decltype(SDL_GetTicks()) tick_t;\n tick_t last_fps_tick = SDL_GetTicks();\n tick_t last_fps_frame = 0;\n DelayQueue<unsigned int, 6> tick_time_queue;\n while (true)\n {\n SDL_Event e;\n bool b_quit = false;\n while (SDL_PollEvent(&e) != 0)\n {\n switch(e.type)\n {\n case SDL_QUIT:\n b_quit = true;\n break;\n case SDL_KEYDOWN:\n if (!e.key.repeat)\n {\n keyboard_control.KeyStatus(e.key.keysym.scancode, e.key.state);\n }\n break;\n case SDL_KEYUP:\n keyboard_control.KeyStatus(e.key.keysym.scancode, e.key.state);\n break;\n }\n }\n if (b_quit)\n {\n break;\n }\n \n for (std::size_t i = 0; i < active_player_bullet_count;)\n {\n auto &bullet_data = player_bullet_data[i];\n const auto bullet_idx = bullet_data.tile_idx;\n auto &pos = bullet_data.pos;\n pos += glm::vec2(0, -16.0f);\n \n if (pos.y < 0)\n {\n sprite_tile_set.TileRemove(bullet_idx);\n player_bullet_data[i] = player_bullet_data[active_player_bullet_count - 1];\n --active_player_bullet_count;\n }\n else\n {\n bullet_1_model.SetTileWithPos(pos, &sprite_tile_set.TileAt(bullet_idx));\n ++i;\n }\n }\n \n if (keyboard_control.GetButtonMask() & 1 && active_player_bullet_count < player_bullet_count)\n {\n const auto bullet_idx = active_player_bullet_count++;\n auto &bullet_data = player_bullet_data[bullet_idx];\n bullet_data.tile_idx = sprite_tile_set.TileAdd(player_bullet_tile_head_idx);\n const auto bullet_pos = player_data.pos;\n bullet_data.pos = bullet_pos;\n bullet_1_model.SetTileWithPos(bullet_pos, &sprite_tile_set.TileAt(bullet_data.tile_idx));\n }\n\n player_data.pos += keyboard_control.GetMoveVector() * 2.0f;\n player_model.SetTileWithPos(player_data.pos, &sprite_tile_set.TileAt(player_data.tile_idx));\n\n for (int i = 0; i < sprite_count; ++i)\n {\n SpriteData& s = sprite_data[i];\n s.radius += 0.01f;\n if (s.radius > pi)\n s.radius -= double_pi;\n glm::vec2 norm;\n hardrock::FastSinCos(s.radius, &norm.y, &norm.x);\n sprite_model.SetTileWithPosScaleDir(s.pos, {1, 1}, norm, &tile_set.TileAt(s.tile_idx));\n }\n\n glClearColor(0.2f, 0.0f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n {\n auto tile_seq = tile_set.GetTileSequence();\n render_quest_list[0].p_tile_seq = &tile_seq;\n auto sprite_tile_seq = sprite_tile_set.GetTileSequence();\n render_quest_list[1].p_tile_seq = &sprite_tile_seq;\n up_render_device->Render(render_quest_list.begin(), render_quest_list.end());\n }\n glFlush();\n\n SDL_GL_SwapWindow(p_window);\n\n tick_t tick_5 = tick_time_queue.Head();\n tick_t len_5_x = SDL_GetTicks() - tick_5;\n if (len_5_x < 90)\n {\n SDL_Delay(100 - len_5_x);\n }\n tick_t now = SDL_GetTicks();\n tick_time_queue.PushPop(now);\n ++last_fps_frame;\n if (last_fps_frame >= 60)\n {\n std::cout << \"fps: \" << 60000.0 \/ (now - last_fps_tick) << std::endl;\n last_fps_tick = now;\n last_fps_frame = 0;\n }\n }\n }\n \n SDL_GL_DeleteContext(p_context);\n SDL_DestroyWindow(p_window);\n SDL_Quit();\n\n std::cout << \"Quit\" << std::endl;\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_OMP_UNLIMITED_GRID_CELL_LIST_HPP\n#define MJOLNIR_OMP_UNLIMITED_GRID_CELL_LIST_HPP\n#include <mjolnir\/omp\/OpenMPSimulatorTraits.hpp>\n#include <mjolnir\/omp\/sort.hpp>\n#include <mjolnir\/core\/UnlimitedGridCellList.hpp>\n#include <mjolnir\/core\/ParallelNeighborList.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nclass UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>\n{\n public:\n using traits_type = OpenMPSimulatorTraits<realT, boundaryT>;\n using system_type = System<traits_type>;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using exclusion_list_type = ExclusionList;\n using parameter_type = parameterT;\n using neighbor_list_type = ParallelNeighborList<parameter_type>;\n using neighbor_type = typename neighbor_list_type::neighbor_type;\n using range_type = typename neighbor_list_type::range_type;\n\n constexpr static std::size_t dim_size = dimI;\n constexpr static std::int64_t dim = static_cast<std::int64_t>(dimI);\n constexpr static std::size_t total_size = dim_size * dim_size * dim_size;\n constexpr static real_type mesh_epsilon = 1e-6;\n\n using particle_cell_idx_pair = std::pair<std::size_t, std::size_t>;\n using cell_index_container_type = std::vector<particle_cell_idx_pair>;\n using cell_index_const_iterator = typename cell_index_container_type::const_iterator;\n using adjacent_cell_idx = std::array<std::size_t, 27>;\n using cell_type = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;\n using cell_list_type = std::array<cell_type, total_size>;\n\n public:\n\n UnlimitedGridCellList()\n : margin_(0.5), current_margin_(-1.0), r_cell_size_(-1.0)\n {}\n\n ~UnlimitedGridCellList() = default;\n UnlimitedGridCellList(UnlimitedGridCellList const&) = default;\n UnlimitedGridCellList(UnlimitedGridCellList &&) = default;\n UnlimitedGridCellList& operator=(UnlimitedGridCellList const&) = default;\n UnlimitedGridCellList& operator=(UnlimitedGridCellList &&) = default;\n\n explicit UnlimitedGridCellList(const real_type margin)\n : margin_(margin), current_margin_(-1.0), r_cell_size_(-1.0)\n {}\n\n bool valid() const noexcept\n {\n return current_margin_ >= 0.;\n }\n\n \/\/XXX do NOT call this from parallel region.\n template<typename PotentialT>\n void initialize(const system_type& sys, const PotentialT& pot)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n MJOLNIR_LOG_INFO(pot.name(), \" cutoff = \", pot.max_cutoff_length());\n MJOLNIR_LOG_INFO(\"dimension = \", dim, 'x', dim, 'x', dim);\n this->set_cutoff(pot.max_cutoff_length());\n this->exclusion_.make(sys, pot);\n\n \/\/ initialize cell list\n#pragma omp parallel for\n for(int x = 0; x < dim; ++x)\n {\n for(int y = 0; y < dim; ++y)\n {\n for(int z = 0; z < dim; ++z)\n {\n auto& cell = this->cell_list_[calc_index(x, y, z)];\n\n const std::size_t x_prev = (x == 0) ? dim-1 : x-1;\n const std::size_t x_next = (x == dim-1) ? 0 : x+1;\n const std::size_t y_prev = (y == 0) ? dim-1 : y-1;\n const std::size_t y_next = (y == dim-1) ? 0 : y+1;\n const std::size_t z_prev = (z == 0) ? dim-1 : z-1;\n const std::size_t z_next = (z == dim-1) ? 0 : z+1;\n\n cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);\n cell.second[ 1] = calc_index(x, y_prev, z_prev);\n cell.second[ 2] = calc_index(x_next, y_prev, z_prev);\n cell.second[ 3] = calc_index(x_prev, y, z_prev);\n cell.second[ 4] = calc_index(x, y, z_prev);\n cell.second[ 5] = calc_index(x_next, y, z_prev);\n cell.second[ 6] = calc_index(x_prev, y_next, z_prev);\n cell.second[ 7] = calc_index(x, y_next, z_prev);\n cell.second[ 8] = calc_index(x_next, y_next, z_prev);\n\n cell.second[ 9] = calc_index(x_prev, y_prev, z);\n cell.second[10] = calc_index(x, y_prev, z);\n cell.second[11] = calc_index(x_next, y_prev, z);\n cell.second[12] = calc_index(x_prev, y, z);\n cell.second[13] = calc_index(x, y, z);\n cell.second[14] = calc_index(x_next, y, z);\n cell.second[15] = calc_index(x_prev, y_next, z);\n cell.second[16] = calc_index(x, y_next, z);\n cell.second[17] = calc_index(x_next, y_next, z);\n\n cell.second[18] = calc_index(x_prev, y_prev, z_next);\n cell.second[19] = calc_index(x, y_prev, z_next);\n cell.second[20] = calc_index(x_next, y_prev, z_next);\n cell.second[21] = calc_index(x_prev, y, z_next);\n cell.second[22] = calc_index(x, y, z_next);\n cell.second[23] = calc_index(x_next, y, z_next);\n cell.second[24] = calc_index(x_prev, y_next, z_next);\n cell.second[25] = calc_index(x, y_next, z_next);\n cell.second[26] = calc_index(x_next, y_next, z_next);\n } \/\/ for z\n } \/\/ for y\n } \/\/ for x (in parallel)\n\n this->make(sys, pot);\n return;\n }\n\n template<typename PotentialT>\n void reconstruct(const system_type& sys, const PotentialT& pot)\n {\n this->initialize(sys, pot); \/\/ do the same thing as `initialize`\n return;\n }\n\n \/\/XXX do NOT call this from parallel region\n template<typename PotentialT>\n void make (const system_type& sys, const PotentialT& pot)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n neighbors_.clear();\n if(index_by_cell_.size() != sys.size())\n {\n index_by_cell_ .resize(sys.size());\n index_by_cell_buf_.resize(sys.size());\n }\n\n#pragma omp parallel for\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n \/\/ pairof {particle-idx, cell-idx}\n index_by_cell_[i] = std::make_pair(i, calc_index(sys.position(i)));\n }\n\n omp::sort(this->index_by_cell_, this->index_by_cell_buf_,\n [](const particle_cell_idx_pair& lhs,\n const particle_cell_idx_pair& rhs) noexcept -> bool {\n return lhs.second < rhs.second;\n });\n\n \/\/ assign first and last iterator for each cells\n \/\/ Also, search the max number of particles in a cell\n std::size_t max_neighbors = 0;\n#pragma omp parallel for reduction(max:max_neighbors)\n for(std::size_t cell_idx=0; cell_idx<cell_list_.size(); ++cell_idx)\n {\n auto iter = std::find_if(index_by_cell_.cbegin(), index_by_cell_.cend(),\n [cell_idx](const particle_cell_idx_pair& item) noexcept -> bool {\n return item.second == cell_idx;\n });\n if(iter == index_by_cell_.cend())\n {\n cell_list_[cell_idx].first = make_range(iter, iter);\n continue;\n }\n const auto first = iter; \/\/ the first iter of the range\n while(iter != index_by_cell_.cend() && iter->second == cell_idx)\n {\n ++iter;\n }\n cell_list_[cell_idx].first = make_range(first, iter);\n max_neighbors = std::max(max_neighbors,\n std::size_t(std::distance(first, iter)));\n }\n\n MJOLNIR_LOG_INFO(\"max number of particles per cell is \", max_neighbors);\n\n \/\/ resize neighbor list by the max number of interacting-particles\n this->neighbors_.resize(sys.size(), max_neighbors * 27);\n\n const real_type r_c = cutoff_ * (1 + margin_);\n const real_type r_c2 = r_c * r_c;\n\n std::size_t max_neighbors_actual = 0;\n std::vector<neighbor_type> partner;\n#pragma omp parallel for private(partner) reduction(max: max_neighbors_actual)\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto& ri = sys.position(i);\n const auto& cell = cell_list_[this->calc_index(ri)];\n\n partner.clear();\n for(std::size_t cidx : cell.second) \/\/ for all adjacent cells...\n {\n for(auto pici : cell_list_[cidx].first)\n {\n const auto j = pici.first;\n if(j <= i || this->exclusion_.is_excluded(i, j))\n {\n continue;\n }\n\n const auto& rj = sys.position(j);\n if(math::length_sq(sys.adjust_direction(rj - ri)) < r_c2)\n {\n partner.emplace_back(j, pot.prepare_params(i, j));\n }\n }\n }\n \/\/ make the result consistent with NaivePairCalculation...\n std::sort(partner.begin(), partner.end());\n this->neighbors_.add_list_for(i, partner.begin(), partner.end());\n\n max_neighbors_actual = std::max(max_neighbors_actual, partner.size());\n }\n MJOLNIR_LOG_INFO(\"actual number of partners is \", max_neighbors_actual);\n\n this->current_margin_ = cutoff_ * margin_;\n return ;\n }\n\n \/\/XXX do NOT call this from `parallel` region.\n template<typename PotentialT>\n void update(const real_type dmargin, const system_type& sys,\n const PotentialT& pot)\n {\n this->current_margin_ -= dmargin;\n\n if(this->current_margin_ < 0.)\n {\n this->make(sys, pot);\n }\n return ;\n }\n\n real_type cutoff() const noexcept {return this->cutoff_;}\n real_type margin() const noexcept {return this->margin_;}\n\n range_type partners(std::size_t i) const noexcept {return neighbors_[i];}\n\n private:\n\n \/\/ calc cell index of the position\n std::size_t calc_index(const coordinate_type& pos) const noexcept\n {\n const auto x = static_cast<std::int64_t>(std::floor(math::X(pos) * r_cell_size_)) % dim;\n const auto y = static_cast<std::int64_t>(std::floor(math::Y(pos) * r_cell_size_)) % dim;\n const auto z = static_cast<std::int64_t>(std::floor(math::Z(pos) * r_cell_size_)) % dim;\n\n return this->calc_index(\n (x<0) ? x+dim : x, (y<0) ? y+dim : y, (z<0) ? z+dim : z);\n }\n\n std::size_t calc_index(const std::size_t x, const std::size_t y,\n const std::size_t z) const noexcept\n {\n return x + dim_size * y + dim_size * dim_size * z;\n }\n\n void set_cutoff(const real_type c) noexcept\n {\n this->cutoff_ = c;\n this->r_cell_size_ = 1 \/ (cutoff_ * (1 + margin_) * (1+mesh_epsilon));\n }\n void set_margin(const real_type m) noexcept\n {\n this->margin_ = m;\n this->r_cell_size_ = 1 \/ (cutoff_ * (1 + margin_) * (1+mesh_epsilon));\n }\n\n private:\n\n real_type cutoff_;\n real_type margin_;\n real_type current_margin_;\n real_type r_cell_size_;\n\n exclusion_list_type exclusion_;\n neighbor_list_type neighbors_;\n cell_list_type cell_list_;\n cell_index_container_type index_by_cell_;\n cell_index_container_type index_by_cell_buf_; \/\/ buffer for sort\n \/\/ index_by_cell_ has {particle idx, cell idx} and sorted by cell idx\n \/\/ first term of cell list contains first and last idx of index_by_cell\n};\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::size_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::dim_size;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::int64_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::dim;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::size_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::total_size;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr typename UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::real_type\n UnlimitedGridCellList<OpenMPSimulatorTraits<realT, boundaryT>,\n parameterT, dimI>::mesh_epsilon;\n\n} \/\/ mjolnir\n#endif\/* MJOLNIR_UNLIMITED_GRID_CELL_LIST *\/\n<commit_msg>perf: use normal NeighborList in CellList<commit_after>#ifndef MJOLNIR_OMP_UNLIMITED_GRID_CELL_LIST_HPP\n#define MJOLNIR_OMP_UNLIMITED_GRID_CELL_LIST_HPP\n#include <mjolnir\/omp\/OpenMPSimulatorTraits.hpp>\n#include <mjolnir\/omp\/sort.hpp>\n#include <mjolnir\/core\/UnlimitedGridCellList.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nclass UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>\n{\n public:\n using traits_type = OpenMPSimulatorTraits<realT, boundaryT>;\n using system_type = System<traits_type>;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using exclusion_list_type = ExclusionList;\n using parameter_type = parameterT;\n using neighbor_list_type = NeighborList<parameter_type>;\n using neighbor_type = typename neighbor_list_type::neighbor_type;\n using range_type = typename neighbor_list_type::range_type;\n\n constexpr static std::size_t dim_size = dimI;\n constexpr static std::int64_t dim = static_cast<std::int64_t>(dimI);\n constexpr static std::size_t total_size = dim_size * dim_size * dim_size;\n constexpr static real_type mesh_epsilon = 1e-6;\n\n using particle_cell_idx_pair = std::pair<std::size_t, std::size_t>;\n using cell_index_container_type = std::vector<particle_cell_idx_pair>;\n using cell_index_const_iterator = typename cell_index_container_type::const_iterator;\n using adjacent_cell_idx = std::array<std::size_t, 27>;\n using cell_type = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;\n using cell_list_type = std::array<cell_type, total_size>;\n\n public:\n\n UnlimitedGridCellList()\n : margin_(0.5), current_margin_(-1.0), r_cell_size_(-1.0)\n {}\n\n ~UnlimitedGridCellList() = default;\n UnlimitedGridCellList(UnlimitedGridCellList const&) = default;\n UnlimitedGridCellList(UnlimitedGridCellList &&) = default;\n UnlimitedGridCellList& operator=(UnlimitedGridCellList const&) = default;\n UnlimitedGridCellList& operator=(UnlimitedGridCellList &&) = default;\n\n explicit UnlimitedGridCellList(const real_type margin)\n : margin_(margin), current_margin_(-1.0), r_cell_size_(-1.0)\n {}\n\n bool valid() const noexcept\n {\n return current_margin_ >= 0.;\n }\n\n \/\/XXX do NOT call this from parallel region.\n template<typename PotentialT>\n void initialize(const system_type& sys, const PotentialT& pot)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n MJOLNIR_LOG_INFO(pot.name(), \" cutoff = \", pot.max_cutoff_length());\n MJOLNIR_LOG_INFO(\"dimension = \", dim, 'x', dim, 'x', dim);\n this->set_cutoff(pot.max_cutoff_length());\n this->exclusion_.make(sys, pot);\n\n \/\/ initialize cell list\n#pragma omp parallel for\n for(int x = 0; x < dim; ++x)\n {\n for(int y = 0; y < dim; ++y)\n {\n for(int z = 0; z < dim; ++z)\n {\n auto& cell = this->cell_list_[calc_index(x, y, z)];\n\n const std::size_t x_prev = (x == 0) ? dim-1 : x-1;\n const std::size_t x_next = (x == dim-1) ? 0 : x+1;\n const std::size_t y_prev = (y == 0) ? dim-1 : y-1;\n const std::size_t y_next = (y == dim-1) ? 0 : y+1;\n const std::size_t z_prev = (z == 0) ? dim-1 : z-1;\n const std::size_t z_next = (z == dim-1) ? 0 : z+1;\n\n cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);\n cell.second[ 1] = calc_index(x, y_prev, z_prev);\n cell.second[ 2] = calc_index(x_next, y_prev, z_prev);\n cell.second[ 3] = calc_index(x_prev, y, z_prev);\n cell.second[ 4] = calc_index(x, y, z_prev);\n cell.second[ 5] = calc_index(x_next, y, z_prev);\n cell.second[ 6] = calc_index(x_prev, y_next, z_prev);\n cell.second[ 7] = calc_index(x, y_next, z_prev);\n cell.second[ 8] = calc_index(x_next, y_next, z_prev);\n\n cell.second[ 9] = calc_index(x_prev, y_prev, z);\n cell.second[10] = calc_index(x, y_prev, z);\n cell.second[11] = calc_index(x_next, y_prev, z);\n cell.second[12] = calc_index(x_prev, y, z);\n cell.second[13] = calc_index(x, y, z);\n cell.second[14] = calc_index(x_next, y, z);\n cell.second[15] = calc_index(x_prev, y_next, z);\n cell.second[16] = calc_index(x, y_next, z);\n cell.second[17] = calc_index(x_next, y_next, z);\n\n cell.second[18] = calc_index(x_prev, y_prev, z_next);\n cell.second[19] = calc_index(x, y_prev, z_next);\n cell.second[20] = calc_index(x_next, y_prev, z_next);\n cell.second[21] = calc_index(x_prev, y, z_next);\n cell.second[22] = calc_index(x, y, z_next);\n cell.second[23] = calc_index(x_next, y, z_next);\n cell.second[24] = calc_index(x_prev, y_next, z_next);\n cell.second[25] = calc_index(x, y_next, z_next);\n cell.second[26] = calc_index(x_next, y_next, z_next);\n } \/\/ for z\n } \/\/ for y\n } \/\/ for x (in parallel)\n\n this->make(sys, pot);\n return;\n }\n\n template<typename PotentialT>\n void reconstruct(const system_type& sys, const PotentialT& pot)\n {\n this->initialize(sys, pot); \/\/ do the same thing as `initialize`\n return;\n }\n\n \/\/XXX do NOT call this from parallel region\n template<typename PotentialT>\n void make (const system_type& sys, const PotentialT& pot)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n neighbors_.clear();\n if(index_by_cell_.size() != sys.size())\n {\n index_by_cell_ .resize(sys.size());\n index_by_cell_buf_.resize(sys.size());\n }\n\n#pragma omp parallel for\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n \/\/ pairof {particle-idx, cell-idx}\n index_by_cell_[i] = std::make_pair(i, calc_index(sys.position(i)));\n }\n\n MJOLNIR_LOG_INFO(\"cell indices calculated\");\n\n omp::sort(this->index_by_cell_, this->index_by_cell_buf_,\n [](const particle_cell_idx_pair& lhs,\n const particle_cell_idx_pair& rhs) noexcept -> bool {\n return lhs.second < rhs.second;\n });\n\n MJOLNIR_LOG_INFO(\"particle id & cell indices are sorted\");\n\n \/\/ assign first and last iterator for each cells\n#pragma omp parallel for\n for(std::size_t cell_idx=0; cell_idx<cell_list_.size(); ++cell_idx)\n {\n auto iter = std::find_if(index_by_cell_.cbegin(), index_by_cell_.cend(),\n [cell_idx](const particle_cell_idx_pair& item) noexcept -> bool {\n return item.second == cell_idx;\n });\n if(iter == index_by_cell_.cend())\n {\n cell_list_[cell_idx].first = make_range(iter, iter);\n continue;\n }\n const auto first = iter; \/\/ the first iter of the range\n while(iter != index_by_cell_.cend() && iter->second == cell_idx)\n {\n ++iter;\n }\n cell_list_[cell_idx].first = make_range(first, iter);\n }\n\n MJOLNIR_LOG_INFO(\"ranges are determined\");\n\n const real_type r_c = cutoff_ * (1 + margin_);\n const real_type r_c2 = r_c * r_c;\n\n std::vector<neighbor_type> partner;\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto& ri = sys.position(i);\n const auto& cell = cell_list_[this->calc_index(ri)];\n\n partner.clear();\n for(std::size_t cidx : cell.second) \/\/ for all adjacent cells...\n {\n for(auto pici : cell_list_[cidx].first)\n {\n const auto j = pici.first;\n if(j <= i || this->exclusion_.is_excluded(i, j))\n {\n continue;\n }\n\n const auto& rj = sys.position(j);\n if(math::length_sq(sys.adjust_direction(rj - ri)) < r_c2)\n {\n partner.emplace_back(j, pot.prepare_params(i, j));\n }\n }\n }\n \/\/ make the result consistent with NaivePairCalculation...\n std::sort(partner.begin(), partner.end());\n\n this->neighbors_.add_list_for(i, partner.begin(), partner.end());\n }\n\n MJOLNIR_LOG_INFO(\"ranges are determined\");\n\n this->current_margin_ = cutoff_ * margin_;\n return ;\n }\n\n \/\/XXX do NOT call this from `parallel` region.\n template<typename PotentialT>\n void update(const real_type dmargin, const system_type& sys,\n const PotentialT& pot)\n {\n this->current_margin_ -= dmargin;\n\n if(this->current_margin_ < 0.)\n {\n this->make(sys, pot);\n }\n return ;\n }\n\n real_type cutoff() const noexcept {return this->cutoff_;}\n real_type margin() const noexcept {return this->margin_;}\n\n range_type partners(std::size_t i) const noexcept {return neighbors_[i];}\n\n private:\n\n \/\/ calc cell index of the position\n std::size_t calc_index(const coordinate_type& pos) const noexcept\n {\n const auto x = static_cast<std::int64_t>(std::floor(math::X(pos) * r_cell_size_)) % dim;\n const auto y = static_cast<std::int64_t>(std::floor(math::Y(pos) * r_cell_size_)) % dim;\n const auto z = static_cast<std::int64_t>(std::floor(math::Z(pos) * r_cell_size_)) % dim;\n\n return this->calc_index(\n (x<0) ? x+dim : x, (y<0) ? y+dim : y, (z<0) ? z+dim : z);\n }\n\n std::size_t calc_index(const std::size_t x, const std::size_t y,\n const std::size_t z) const noexcept\n {\n return x + dim_size * y + dim_size * dim_size * z;\n }\n\n void set_cutoff(const real_type c) noexcept\n {\n this->cutoff_ = c;\n this->r_cell_size_ = 1 \/ (cutoff_ * (1 + margin_) * (1+mesh_epsilon));\n }\n void set_margin(const real_type m) noexcept\n {\n this->margin_ = m;\n this->r_cell_size_ = 1 \/ (cutoff_ * (1 + margin_) * (1+mesh_epsilon));\n }\n\n private:\n\n real_type cutoff_;\n real_type margin_;\n real_type current_margin_;\n real_type r_cell_size_;\n\n exclusion_list_type exclusion_;\n neighbor_list_type neighbors_;\n cell_list_type cell_list_;\n cell_index_container_type index_by_cell_;\n cell_index_container_type index_by_cell_buf_; \/\/ buffer for sort\n \/\/ index_by_cell_ has {particle idx, cell idx} and sorted by cell idx\n \/\/ first term of cell list contains first and last idx of index_by_cell\n};\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::size_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::dim_size;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::int64_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::dim;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr std::size_t UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::total_size;\n\ntemplate<typename realT, template<typename, typename> class boundaryT,\n typename parameterT, std::size_t dimI>\nconstexpr typename UnlimitedGridCellList<\n OpenMPSimulatorTraits<realT, boundaryT>, parameterT, dimI>::real_type\n UnlimitedGridCellList<OpenMPSimulatorTraits<realT, boundaryT>,\n parameterT, dimI>::mesh_epsilon;\n\n} \/\/ mjolnir\n#endif\/* MJOLNIR_UNLIMITED_GRID_CELL_LIST *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"glresource.hpp\"\n#include \"glx.hpp\"\n#include \"adaptsdl.hpp\"\n#include \"systeminfo.hpp\"\n\nnamespace rs {\n\tconst std::string& IGLResource::getResourceName() const {\n\t\tstatic std::string str(\"IGLResource\");\n\t\treturn str;\n\t}\n\n\tnamespace {\n\t\ttemplate <class Tex_t, class... Ts>\n\t\tauto MakeStaticTex(Ts&&... ts) {\n\t\t\treturn [&](const spn::URI& uri){\n\t\t\t\treturn UPResource(new Tex_t(uri, std::forward<Ts>(ts)...));\n\t\t\t};\n\t\t}\n\t}\n\n\tstd::shared_ptr<FxBlock> InitFxBlock() {\n\t\treturn std::make_shared<FxBlock>();\n\t}\n\tvoid ReloadFxBlock(const spn::URI& uri) {\n\t\tmgr_block.replace(uri, GLEffect::LoadGLXStruct(uri));\n\t}\n\tconst std::string GLRes::cs_rtname[] = {\n\t\t\"texture\",\n\t\t\"effect\"\n\t};\n\tGLRes::GLRes(): ResMgrApp(cs_rtname) {\n\t\t_bInit = false;\n\t\t_bInDtor = false;\n\t\t_upFb.reset(new GLFBuffer());\n\t\t\/\/ 既にデバイスがアクティブだったらonDeviceResetを呼ぶ\n\t\t_cbInit =\n\t\t\t[&](auto h){\n\t\t\t\tif(_bInit)\n\t\t\t\t\th.ref()->onDeviceReset();\n\t\t\t};\n\n\t\t\/\/ EmptyTexture = 1x1の単色テクスチャ\n\t\tuint32_t buff1 = 0xffffffff;\n\t\t_hlEmptyTex.reset(new HLTex(createTextureInit(spn::Size(1,1), GL_RGBA, false, true, GL_UNSIGNED_BYTE, spn::AB_Byte(&buff1, 1))));\n\t}\n\tGLRes::~GLRes() {\n\t\t\/\/ 破棄フラグを立ててからOnDeviceLost関数を呼ぶ\n\t\t_bInDtor = true;\n\t\tonDeviceLost();\n\t}\n\tconst FBInfo_OP& GLRes::getDefaultDepth() const {\n\t\treturn _defaultDepth;\n\t}\n\tconst FBInfo_OP& GLRes::getDefaultColor() const {\n\t\treturn _defaultColor;\n\t}\n\tconst std::string& GLRes::getResourceName(spn::SHandle sh) const {\n\t\tif(sh) {\n\t\t\tIGLResource* gr = HRes::FromHandle(sh)->get();\n\t\t\treturn gr->getResourceName();\n\t\t}\n\t\tconst static std::string name(\"IGLResource\");\n\t\treturn name;\n\t}\n\tspn::URI GLRes::_modifyResourceName(spn::URI& key) const {\n\t\tspn::URI key_k = base_type::_modifyResourceName(key);\n\t\t\/\/ Cubeプリフィックスを持っている時は末尾に加える\n\t\tif(_chPostfix) {\n\t\t\tauto str = key_k.getLast_utf8();\n\t\t\tstr += *_chPostfix;\n\t\t\tkey_k.popBack();\n\t\t\tkey_k.pushBack(str);\n\t\t}\n\t\treturn key_k;\n\t}\n\tHLTex GLRes::loadTexture(const std::string& name, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_setResourceTypeId(ResourceType::Texture);\n\t\treturn loadTextureUri(_uriFromResourceName(name), miplevel, fmt);\n\t}\n\tHLTex GLRes::loadTextureUri(const spn::URI& uri, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_chPostfix = spn::none;\n\t\treturn Cast<UPTexture>(\n\t\t\tloadResourceApp(uri,\n\t\t\t\tMakeStaticTex<Texture_StaticURI>(miplevel, fmt),\n\t\t\t\t_cbInit)\n\t\t);\n\t}\n\tHLTex GLRes::loadCubeTexture(const std::string& name, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_setResourceTypeId(ResourceType::Texture);\n\t\t\/\/ 0を付加してリソース検索\n\t\tspn::PathBlock pb(name);\n\t\tpb.setPathNum([](auto \/*num*\/) -> spn::Int_OP{ return 0; });\n\n\t\tpb = _uriFromResourceName(pb.plain_utf8()).path();\n\t\t\/\/ 末尾の0を除く\n\t\tpb.setPathNum([](auto) ->spn::Int_OP{ return spn::none; });\n\t\treturn loadCubeTextureUri(spn::URI(\"file\", pb), miplevel, fmt);\n\t}\n\tHLTex GLRes::loadCubeTextureUri(const spn::URI& uri, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t\/\/ 連番CubeTexutreの場合はキーとなるURIの末尾に\"@\"を付加する\n\t\t_chPostfix = '@';\n\t\t\/\/ Uriの連番展開\n\t\treturn Cast<UPTexture>(\n\t\t\t\t\tloadResourceApp(uri,\n\t\t\t\t\t\tMakeStaticTex<Texture_StaticCubeURI>(miplevel, fmt),\n\t\t\t\t\t\t_cbInit)\n\t\t\t\t);\n\t}\n\t\/\/ 連番キューブ: Key=(Path+@, ext) URI=(Path, ext)\n\tHLTex GLRes::_loadCubeTexture(MipState miplevel, OPInCompressedFmt fmt, const spn::URI& uri0, const spn::URI& uri1, const spn::URI& uri2,\n\t\t\t\t\t\t\t\t const spn::URI& uri3, const spn::URI& uri4, const spn::URI& uri5)\n\t{\n\t\t_chPostfix = spn::none;\n\t\t\/\/ 個別指定CubeTextureの場合はリソース名はUriを全部つなげた文字列とする\n\t\tstd::string tmp(uri0.plainUri_utf8());\n\t\tauto fn = [&tmp](const spn::URI& u) { tmp.append(u.plainUri_utf8()); };\n\t\tfn(uri1); fn(uri2); fn(uri3); fn(uri4); fn(uri5);\n\n\t\treturn Cast<UPTexture>(\n\t\t\tloadResourceApp(spn::URI(\"file\", tmp),\n\t\t\t\t[&](const spn::URI&){ return UPResource(new Texture_StaticCubeURI(uri0,uri1,uri2,uri3,uri4,uri5,miplevel,fmt)); },\n\t\t\t\t_cbInit)\n\t\t);\n\t}\n\tHLTex GLRes::_createTexture(bool bCube, const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\tLHdl lh = base_type::acquire(UPResource(new Texture_Mem(bCube, fmt, size, bStream, bRestore)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPTexture>(std::move(lh));\n\t}\n\tHLTex GLRes::createCubeTexture(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\treturn _createTexture(true, size, fmt, bStream, bRestore);\n\t}\n\tHLTex GLRes::createTexture(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\treturn _createTexture(false, size, fmt, bStream, bRestore);\n\t}\n\tHLTex GLRes::createTextureInit(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore, GLTypeFmt srcFmt, spn::AB_Byte data) {\n\t\tauto ptr = std::make_unique<Texture_Mem>(false, fmt, size, bStream, bRestore);\n\t\tptr->writeData(data, srcFmt);\n\t\tLHdl lh = base_type::acquire(std::move(ptr));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPTexture>(std::move(lh));\n\t}\n\tHLSh GLRes::makeShader(ShType type, const std::string& src) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLShader(type, src)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPShader>(std::move(lh));\n\t}\n\tHLFx GLRes::loadEffect(const std::string& name, const CBCreateFx& cb) {\n\t\t_chPostfix = spn::none;\n\t\t_setResourceTypeId(ResourceType::Effect);\n\t\tauto ret = this->base_t::acquire(name, [&](const spn::URI& u){\n\t\t\t\treturn UPResource(cb(u.plain_utf8()));\n\t\t});\n\t\tif(ret.second)\n\t\t\t_cbInit(ret.first);\n\t\treturn Cast<UPEffect>(ret.first);\n\t}\n\tUPResource GLRes::replaceEffect(HLFx& hlFx, const CBCreateFx& cb) {\n\t\tauto& key = this->base_t::getKey(hlFx.get());\n\t\tUPResource res(cb(key.plain_utf8()));\n\t\thlFx->get()->onDeviceLost();\n\t\t\/\/ 前のエンジン変数をとっておく\n\t\tUPResource prev = std::move(hlFx.ref());\n\t\t\/\/ ハンドルの中身(UPResource)を置き換え\n\t\thlFx = Cast<UPEffect>(this->base_t::replace(key, std::move(res)));\n\t\t_cbInit(hlFx.get());\n\t\treturn prev;\n\t}\n\tHLVb GLRes::makeVBuffer(GLuint dtype) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLVBuffer(dtype)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPVBuffer>(std::move(lh));\n\t}\n\tHLIb GLRes::makeIBuffer(GLuint dtype) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLIBuffer(dtype)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPIBuffer>(std::move(lh));\n\t}\n\n\tHLProg GLRes::makeProgram(HSh vsh, HSh psh) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLProgram(vsh,psh)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPProg>(std::move(lh));\n\t}\n\tHLProg GLRes::makeProgram(HSh vsh, HSh gsh, HSh psh) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLProgram(vsh,gsh,psh)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPProg>(std::move(lh));\n\t}\n\tGLFBufferTmp& GLRes::getTmpFramebuffer() const {\n\t\treturn *_tmpFb;\n\t}\n\tHTex GLRes::getEmptyTexture() const {\n\t\treturn _hlEmptyTex->get();\n\t}\n\tbool GLRes::deviceStatus() const {\n\t\treturn _bInit;\n\t}\n\tbool GLRes::isInDtor() const {\n\t\treturn _bInDtor;\n\t}\n\tvoid GLRes::onDeviceLost() {\n\t\tif(_bInit) {\n\t\t\t_bInit = false;\n\t\t\tfor(auto& r : *this)\n\t\t\t\tr->onDeviceLost();\n\t\t\t\/\/ 一旦DeviceLostしたらフレームバッファはデフォルトに戻る(in Gameloop)\n\t\t\t_tmpFb->use_begin();\n\t\t\t_tmpFb.reset(nullptr);\n\n\t\t\t_upFb->onDeviceLost();\n\t\t\t_clearDefaultInfo();\n\t\t}\n\t}\n\tvoid GLRes::_initDefaultInfo() {\n\t\tGL.glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\t\tusing Att = GLFBufferCore::Att;\n\t\t_defaultColor = GLFBufferCore::GetCurrentInfo(Att::COLOR0);\n\t\t_defaultDepth = GLFBufferCore::GetCurrentInfo(Att::DEPTH);\n\t}\n\tvoid GLRes::_clearDefaultInfo() {\n\t\t_defaultDepth = spn::none;\n\t\t_defaultColor = spn::none;\n\t}\n\tvoid GLRes::onDeviceReset() {\n\t\tif(!_bInit) {\n\t\t\t_bInit = true;\n\t\t\t_upFb->onDeviceReset();\n\t\t\t_tmpFb.reset(new GLFBufferTmp(_upFb->getBufferID(), mgr_info.getScreenSize()));\n\t\t\t_initDefaultInfo();\n\t\t\tfor(auto& r : *this)\n\t\t\t\tr->onDeviceReset();\n\t\t}\n\t}\n\tspn::LHandle GLRes::loadResource(spn::AdaptStream& \/*ast*\/, const spn::URI& uri) {\n\t\tauto ext = uri.getExtension();\n\t\tspn::LHandle ret;\n\t\t\/\/ is it Texture?\n\t\tif(ext==\"png\" || ext==\"jpg\" || ext==\"bmp\")\n\t\t\tret = loadTextureUri(uri);\n\t\t\/\/ is it Effect(Shader)?\n\t\telse if(ext == \"glx\") {\n\t\t\tHLRW hlRW = mgr_rw.fromURI(uri, RWops::Read);\n\t\t\tret = loadEffect(uri.plain_utf8(), [](auto& name){\n\t\t\t\t\treturn new GLEffect(name); });\n\t\t}\n\t\treturn ret;\n\t}\n\tHLFb GLRes::makeFBuffer() {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLFBuffer()));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPFBuffer>(lh);\n\t}\n\tHLRb GLRes::makeRBuffer(int w, int h, GLInRenderFmt fmt) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLRBuffer(w, h, fmt)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPRBuffer>(lh);\n\t}\n\n\tnamespace draw {\n\t\tClear::Clear(const ClearParam& p):\n\t\t\t_param(p)\n\t\t{}\n\t\tvoid Clear::exec() {\n\t\t\tGLenum flag = 0;\n\t\t\tif(_param.color) {\n\t\t\t\tflag |= GL_COLOR_BUFFER_BIT;\n\t\t\t\tauto& c = *_param.color;\n\t\t\t\tGL.glClearColor(c.x, c.y, c.z, c.w);\n\t\t\t}\n\t\t\tif(_param.depth) {\n\t\t\t\tflag |= GL_DEPTH_BUFFER_BIT;\n#ifndef USE_OPENGLES2\n\t\t\t\tGL.glClearDepth\n#else\n\t\t\t\tGL.glClearDepthf\n#endif\n\t\t\t\t\t(*_param.depth);\n\t\t\t}\n\t\t\tif(_param.stencil) {\n\t\t\t\tflag |= GL_STENCIL_BUFFER_BIT;\n\t\t\t\tGL.glClearStencil(*_param.stencil);\n\t\t\t}\n\t\t\t\/\/ WindowsではDepthMaskをTrueにしないとクリアされない為、一旦値を退避\n\t\t\tGLboolean b;\n\t\t\tGL.glGetBooleanv(GL_DEPTH_TEST, &b);\n\t\t\tGL.glDepthMask(GL_TRUE);\n\t\t\tGL.glClear(flag);\n\t\t\t\/\/ DepthMask値を戻す\n\t\t\tGL.glDepthMask(b);\n\t\t}\n\t}\n}\n<commit_msg>GLRes: FBufferTmpの初期化パラメータの修正<commit_after>#include \"glresource.hpp\"\n#include \"glx.hpp\"\n#include \"adaptsdl.hpp\"\n#include \"systeminfo.hpp\"\n\nnamespace rs {\n\tconst std::string& IGLResource::getResourceName() const {\n\t\tstatic std::string str(\"IGLResource\");\n\t\treturn str;\n\t}\n\n\tnamespace {\n\t\ttemplate <class Tex_t, class... Ts>\n\t\tauto MakeStaticTex(Ts&&... ts) {\n\t\t\treturn [&](const spn::URI& uri){\n\t\t\t\treturn UPResource(new Tex_t(uri, std::forward<Ts>(ts)...));\n\t\t\t};\n\t\t}\n\t}\n\n\tstd::shared_ptr<FxBlock> InitFxBlock() {\n\t\treturn std::make_shared<FxBlock>();\n\t}\n\tvoid ReloadFxBlock(const spn::URI& uri) {\n\t\tmgr_block.replace(uri, GLEffect::LoadGLXStruct(uri));\n\t}\n\tconst std::string GLRes::cs_rtname[] = {\n\t\t\"texture\",\n\t\t\"effect\"\n\t};\n\tGLRes::GLRes(): ResMgrApp(cs_rtname) {\n\t\t_bInit = false;\n\t\t_bInDtor = false;\n\t\t_upFb.reset(new GLFBuffer());\n\t\t\/\/ 既にデバイスがアクティブだったらonDeviceResetを呼ぶ\n\t\t_cbInit =\n\t\t\t[&](auto h){\n\t\t\t\tif(_bInit)\n\t\t\t\t\th.ref()->onDeviceReset();\n\t\t\t};\n\n\t\t\/\/ EmptyTexture = 1x1の単色テクスチャ\n\t\tuint32_t buff1 = 0xffffffff;\n\t\t_hlEmptyTex.reset(new HLTex(createTextureInit(spn::Size(1,1), GL_RGBA, false, true, GL_UNSIGNED_BYTE, spn::AB_Byte(&buff1, sizeof(buff1)))));\n\t}\n\tGLRes::~GLRes() {\n\t\t\/\/ 破棄フラグを立ててからOnDeviceLost関数を呼ぶ\n\t\t_bInDtor = true;\n\t\tonDeviceLost();\n\t}\n\tconst FBInfo_OP& GLRes::getDefaultDepth() const {\n\t\treturn _defaultDepth;\n\t}\n\tconst FBInfo_OP& GLRes::getDefaultColor() const {\n\t\treturn _defaultColor;\n\t}\n\tconst std::string& GLRes::getResourceName(spn::SHandle sh) const {\n\t\tif(sh) {\n\t\t\tIGLResource* gr = HRes::FromHandle(sh)->get();\n\t\t\treturn gr->getResourceName();\n\t\t}\n\t\tconst static std::string name(\"IGLResource\");\n\t\treturn name;\n\t}\n\tspn::URI GLRes::_modifyResourceName(spn::URI& key) const {\n\t\tspn::URI key_k = base_type::_modifyResourceName(key);\n\t\t\/\/ Cubeプリフィックスを持っている時は末尾に加える\n\t\tif(_chPostfix) {\n\t\t\tauto str = key_k.getLast_utf8();\n\t\t\tstr += *_chPostfix;\n\t\t\tkey_k.popBack();\n\t\t\tkey_k.pushBack(str);\n\t\t}\n\t\treturn key_k;\n\t}\n\tHLTex GLRes::loadTexture(const std::string& name, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_setResourceTypeId(ResourceType::Texture);\n\t\treturn loadTextureUri(_uriFromResourceName(name), miplevel, fmt);\n\t}\n\tHLTex GLRes::loadTextureUri(const spn::URI& uri, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_chPostfix = spn::none;\n\t\treturn Cast<UPTexture>(\n\t\t\tloadResourceApp(uri,\n\t\t\t\tMakeStaticTex<Texture_StaticURI>(miplevel, fmt),\n\t\t\t\t_cbInit)\n\t\t);\n\t}\n\tHLTex GLRes::loadCubeTexture(const std::string& name, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t_setResourceTypeId(ResourceType::Texture);\n\t\t\/\/ 0を付加してリソース検索\n\t\tspn::PathBlock pb(name);\n\t\tpb.setPathNum([](auto \/*num*\/) -> spn::Int_OP{ return 0; });\n\n\t\tpb = _uriFromResourceName(pb.plain_utf8()).path();\n\t\t\/\/ 末尾の0を除く\n\t\tpb.setPathNum([](auto) ->spn::Int_OP{ return spn::none; });\n\t\treturn loadCubeTextureUri(spn::URI(\"file\", pb), miplevel, fmt);\n\t}\n\tHLTex GLRes::loadCubeTextureUri(const spn::URI& uri, MipState miplevel, OPInCompressedFmt fmt) {\n\t\t\/\/ 連番CubeTexutreの場合はキーとなるURIの末尾に\"@\"を付加する\n\t\t_chPostfix = '@';\n\t\t\/\/ Uriの連番展開\n\t\treturn Cast<UPTexture>(\n\t\t\t\t\tloadResourceApp(uri,\n\t\t\t\t\t\tMakeStaticTex<Texture_StaticCubeURI>(miplevel, fmt),\n\t\t\t\t\t\t_cbInit)\n\t\t\t\t);\n\t}\n\t\/\/ 連番キューブ: Key=(Path+@, ext) URI=(Path, ext)\n\tHLTex GLRes::_loadCubeTexture(MipState miplevel, OPInCompressedFmt fmt, const spn::URI& uri0, const spn::URI& uri1, const spn::URI& uri2,\n\t\t\t\t\t\t\t\t const spn::URI& uri3, const spn::URI& uri4, const spn::URI& uri5)\n\t{\n\t\t_chPostfix = spn::none;\n\t\t\/\/ 個別指定CubeTextureの場合はリソース名はUriを全部つなげた文字列とする\n\t\tstd::string tmp(uri0.plainUri_utf8());\n\t\tauto fn = [&tmp](const spn::URI& u) { tmp.append(u.plainUri_utf8()); };\n\t\tfn(uri1); fn(uri2); fn(uri3); fn(uri4); fn(uri5);\n\n\t\treturn Cast<UPTexture>(\n\t\t\tloadResourceApp(spn::URI(\"file\", tmp),\n\t\t\t\t[&](const spn::URI&){ return UPResource(new Texture_StaticCubeURI(uri0,uri1,uri2,uri3,uri4,uri5,miplevel,fmt)); },\n\t\t\t\t_cbInit)\n\t\t);\n\t}\n\tHLTex GLRes::_createTexture(bool bCube, const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\tLHdl lh = base_type::acquire(UPResource(new Texture_Mem(bCube, fmt, size, bStream, bRestore)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPTexture>(std::move(lh));\n\t}\n\tHLTex GLRes::createCubeTexture(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\treturn _createTexture(true, size, fmt, bStream, bRestore);\n\t}\n\tHLTex GLRes::createTexture(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore) {\n\t\treturn _createTexture(false, size, fmt, bStream, bRestore);\n\t}\n\tHLTex GLRes::createTextureInit(const spn::Size& size, GLInSizedFmt fmt, bool bStream, bool bRestore, GLTypeFmt srcFmt, spn::AB_Byte data) {\n\t\tauto ptr = std::make_unique<Texture_Mem>(false, fmt, size, bStream, bRestore);\n\t\tptr->writeData(data, srcFmt);\n\t\tLHdl lh = base_type::acquire(std::move(ptr));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPTexture>(std::move(lh));\n\t}\n\tHLSh GLRes::makeShader(ShType type, const std::string& src) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLShader(type, src)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPShader>(std::move(lh));\n\t}\n\tHLFx GLRes::loadEffect(const std::string& name, const CBCreateFx& cb) {\n\t\t_chPostfix = spn::none;\n\t\t_setResourceTypeId(ResourceType::Effect);\n\t\tauto ret = this->base_t::acquire(name, [&](const spn::URI& u){\n\t\t\t\treturn UPResource(cb(u.plain_utf8()));\n\t\t});\n\t\tif(ret.second)\n\t\t\t_cbInit(ret.first);\n\t\treturn Cast<UPEffect>(ret.first);\n\t}\n\tUPResource GLRes::replaceEffect(HLFx& hlFx, const CBCreateFx& cb) {\n\t\tauto& key = this->base_t::getKey(hlFx.get());\n\t\tUPResource res(cb(key.plain_utf8()));\n\t\thlFx->get()->onDeviceLost();\n\t\t\/\/ 前のエンジン変数をとっておく\n\t\tUPResource prev = std::move(hlFx.ref());\n\t\t\/\/ ハンドルの中身(UPResource)を置き換え\n\t\thlFx = Cast<UPEffect>(this->base_t::replace(key, std::move(res)));\n\t\t_cbInit(hlFx.get());\n\t\treturn prev;\n\t}\n\tHLVb GLRes::makeVBuffer(GLuint dtype) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLVBuffer(dtype)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPVBuffer>(std::move(lh));\n\t}\n\tHLIb GLRes::makeIBuffer(GLuint dtype) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLIBuffer(dtype)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPIBuffer>(std::move(lh));\n\t}\n\n\tHLProg GLRes::makeProgram(HSh vsh, HSh psh) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLProgram(vsh,psh)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPProg>(std::move(lh));\n\t}\n\tHLProg GLRes::makeProgram(HSh vsh, HSh gsh, HSh psh) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLProgram(vsh,gsh,psh)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPProg>(std::move(lh));\n\t}\n\tGLFBufferTmp& GLRes::getTmpFramebuffer() const {\n\t\treturn *_tmpFb;\n\t}\n\tHTex GLRes::getEmptyTexture() const {\n\t\treturn _hlEmptyTex->get();\n\t}\n\tbool GLRes::deviceStatus() const {\n\t\treturn _bInit;\n\t}\n\tbool GLRes::isInDtor() const {\n\t\treturn _bInDtor;\n\t}\n\tvoid GLRes::onDeviceLost() {\n\t\tif(_bInit) {\n\t\t\t_bInit = false;\n\t\t\tfor(auto& r : *this)\n\t\t\t\tr->onDeviceLost();\n\t\t\t\/\/ 一旦DeviceLostしたらフレームバッファはデフォルトに戻る(in Gameloop)\n\t\t\t_tmpFb->use_begin();\n\t\t\t_tmpFb.reset(nullptr);\n\n\t\t\t_upFb->onDeviceLost();\n\t\t\t_clearDefaultInfo();\n\t\t}\n\t}\n\tvoid GLRes::_initDefaultInfo() {\n\t\tGL.glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\t\tusing Att = GLFBufferCore::Att;\n\t\t_defaultColor = GLFBufferCore::GetCurrentInfo(Att::COLOR0);\n\t\t_defaultDepth = GLFBufferCore::GetCurrentInfo(Att::DEPTH);\n\t}\n\tvoid GLRes::_clearDefaultInfo() {\n\t\t_defaultDepth = spn::none;\n\t\t_defaultColor = spn::none;\n\t}\n\tvoid GLRes::onDeviceReset() {\n\t\tif(!_bInit) {\n\t\t\t_bInit = true;\n\t\t\t_upFb->onDeviceReset();\n\t\t\t_tmpFb.reset(new GLFBufferTmp(_upFb->getBufferID(), mgr_info.getScreenSize()));\n\t\t\t_initDefaultInfo();\n\t\t\tfor(auto& r : *this)\n\t\t\t\tr->onDeviceReset();\n\t\t}\n\t}\n\tspn::LHandle GLRes::loadResource(spn::AdaptStream& \/*ast*\/, const spn::URI& uri) {\n\t\tauto ext = uri.getExtension();\n\t\tspn::LHandle ret;\n\t\t\/\/ is it Texture?\n\t\tif(ext==\"png\" || ext==\"jpg\" || ext==\"bmp\")\n\t\t\tret = loadTextureUri(uri);\n\t\t\/\/ is it Effect(Shader)?\n\t\telse if(ext == \"glx\") {\n\t\t\tHLRW hlRW = mgr_rw.fromURI(uri, RWops::Read);\n\t\t\tret = loadEffect(uri.plain_utf8(), [](auto& name){\n\t\t\t\t\treturn new GLEffect(name); });\n\t\t}\n\t\treturn ret;\n\t}\n\tHLFb GLRes::makeFBuffer() {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLFBuffer()));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPFBuffer>(lh);\n\t}\n\tHLRb GLRes::makeRBuffer(int w, int h, GLInRenderFmt fmt) {\n\t\tLHdl lh = base_type::acquire(UPResource(new GLRBuffer(w, h, fmt)));\n\t\t_cbInit(lh);\n\t\treturn Cast<UPRBuffer>(lh);\n\t}\n\n\tnamespace draw {\n\t\tClear::Clear(const ClearParam& p):\n\t\t\t_param(p)\n\t\t{}\n\t\tvoid Clear::exec() {\n\t\t\tGLenum flag = 0;\n\t\t\tif(_param.color) {\n\t\t\t\tflag |= GL_COLOR_BUFFER_BIT;\n\t\t\t\tauto& c = *_param.color;\n\t\t\t\tGL.glClearColor(c.x, c.y, c.z, c.w);\n\t\t\t}\n\t\t\tif(_param.depth) {\n\t\t\t\tflag |= GL_DEPTH_BUFFER_BIT;\n#ifndef USE_OPENGLES2\n\t\t\t\tGL.glClearDepth\n#else\n\t\t\t\tGL.glClearDepthf\n#endif\n\t\t\t\t\t(*_param.depth);\n\t\t\t}\n\t\t\tif(_param.stencil) {\n\t\t\t\tflag |= GL_STENCIL_BUFFER_BIT;\n\t\t\t\tGL.glClearStencil(*_param.stencil);\n\t\t\t}\n\t\t\t\/\/ WindowsではDepthMaskをTrueにしないとクリアされない為、一旦値を退避\n\t\t\tGLboolean b;\n\t\t\tGL.glGetBooleanv(GL_DEPTH_TEST, &b);\n\t\t\tGL.glDepthMask(GL_TRUE);\n\t\t\tGL.glClear(flag);\n\t\t\t\/\/ DepthMask値を戻す\n\t\t\tGL.glDepthMask(b);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of gltfpack; see gltfpack.h for version\/license details\n#include \"gltfpack.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten.h>\n#endif\n\nstruct BasisSettings\n{\n\tint etc1s_l;\n\tint etc1s_q;\n\tint uastc_l;\n\tfloat uastc_q;\n};\n\nstatic const char* kMimeTypes[][2] = {\n {\"image\/jpeg\", \".jpg\"},\n {\"image\/jpeg\", \".jpeg\"},\n {\"image\/png\", \".png\"},\n};\n\nstatic const BasisSettings kBasisSettings[10] = {\n {1, 1, 0, 1.5f},\n {1, 6, 0, 1.f},\n {1, 20, 1, 1.0f},\n {1, 50, 1, 0.75f},\n {1, 90, 1, 0.5f},\n {1, 128, 1, 0.4f},\n {1, 160, 1, 0.34f},\n {1, 192, 1, 0.29f}, \/\/ default\n {1, 224, 2, 0.26f},\n {1, 255, 2, 0.f},\n};\n\nvoid analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)\n{\n\tfor (size_t i = 0; i < data->materials_count; ++i)\n\t{\n\t\tconst cgltf_material& material = data->materials[i];\n\n\t\tif (material.has_pbr_metallic_roughness)\n\t\t{\n\t\t\tconst cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;\n\n\t\t\tif (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)\n\t\t\t\timages[pbr.base_color_texture.texture->image - data->images].srgb = true;\n\t\t}\n\n\t\tif (material.has_pbr_specular_glossiness)\n\t\t{\n\t\t\tconst cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;\n\n\t\t\tif (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)\n\t\t\t\timages[pbr.diffuse_texture.texture->image - data->images].srgb = true;\n\t\t}\n\n\t\tif (material.emissive_texture.texture && material.emissive_texture.texture->image)\n\t\t\timages[material.emissive_texture.texture->image - data->images].srgb = true;\n\n\t\tif (material.normal_texture.texture && material.normal_texture.texture->image)\n\t\t\timages[material.normal_texture.texture->image - data->images].normal_map = true;\n\t}\n}\n\nconst char* inferMimeType(const char* path)\n{\n\tconst char* ext = strrchr(path, '.');\n\tif (!ext)\n\t\treturn \"\";\n\n\tstd::string extl = ext;\n\tfor (size_t i = 0; i < extl.length(); ++i)\n\t\textl[i] = char(tolower(extl[i]));\n\n\tfor (size_t i = 0; i < sizeof(kMimeTypes) \/ sizeof(kMimeTypes[0]); ++i)\n\t\tif (extl == kMimeTypes[i][1])\n\t\t\treturn kMimeTypes[i][0];\n\n\treturn \"\";\n}\n\nstatic const char* mimeExtension(const char* mime_type)\n{\n\tfor (size_t i = 0; i < sizeof(kMimeTypes) \/ sizeof(kMimeTypes[0]); ++i)\n\t\tif (strcmp(kMimeTypes[i][0], mime_type) == 0)\n\t\t\treturn kMimeTypes[i][1];\n\n\treturn \".raw\";\n}\n\n#ifdef __EMSCRIPTEN__\nEM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {\n\tvar cp = require('child_process');\n\tvar stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];\n\tvar ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });\n\treturn ret.status == null ? 256 : ret.status;\n});\n\nEM_JS(const char*, readenv, (const char* name), {\n\tvar val = process.env[UTF8ToString(name)];\n\tif (!val)\n\t\treturn 0;\n\tvar ret = _malloc(lengthBytesUTF8(val) + 1);\n\tstringToUTF8(val, ret, lengthBytesUTF8(val) + 1);\n\treturn ret;\n});\n#else\nstatic int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)\n{\n#ifdef _WIN32\n\tstd::string ignore = \"nul\";\n#else\n\tstd::string ignore = \"\/dev\/null\";\n#endif\n\n\tstd::string cmd = cmd_;\n\n\tif (ignore_stdout)\n\t\t(cmd += \" >\") += ignore;\n\tif (ignore_stderr)\n\t\t(cmd += \" 2>\") += ignore;\n\n\treturn system(cmd.c_str());\n}\n\nstatic const char* readenv(const char* name)\n{\n\treturn getenv(name);\n}\n#endif\n\nbool checkBasis(bool verbose)\n{\n\tconst char* basisu_path = readenv(\"BASISU_PATH\");\n\tstd::string cmd = basisu_path ? basisu_path : \"basisu\";\n\n\tcmd += \" -version\";\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ true);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0;\n}\n\nbool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool pow2, bool uastc, bool verbose)\n{\n\t(void)scale;\n\t(void)pow2;\n\n\tTempFile temp_input(mimeExtension(mime_type));\n\tTempFile temp_output(\".basis\");\n\n\tif (!writeFile(temp_input.path.c_str(), data))\n\t\treturn false;\n\n\tconst char* basisu_path = readenv(\"BASISU_PATH\");\n\tstd::string cmd = basisu_path ? basisu_path : \"basisu\";\n\n\tconst BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1];\n\n\tcmd += \" -mipmap\";\n\n\tif (normal_map)\n\t{\n\t\tcmd += \" -normal_map\";\n\t\t\/\/ for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness\n\t}\n\telse if (!srgb)\n\t{\n\t\tcmd += \" -linear\";\n\t}\n\n\tif (uastc)\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" -uastc_level %d -uastc_rdo_q %.2f\", bs.uastc_l, bs.uastc_q);\n\n\t\tcmd += \" -uastc\";\n\t\tcmd += settings;\n\t\tcmd += \" -uastc_rdo_d 1024\";\n\t}\n\telse\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" -comp_level %d -q %d\", bs.etc1s_l, bs.etc1s_q);\n\n\t\tcmd += settings;\n\t}\n\n\tcmd += \" -file \";\n\tcmd += temp_input.path;\n\tcmd += \" -output_file \";\n\tcmd += temp_output.path;\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ false);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0 && readFile(temp_output.path.c_str(), result);\n}\n\nbool checkKtx(bool verbose)\n{\n\tconst char* toktx_path = readenv(\"TOKTX_PATH\");\n\tstd::string cmd = toktx_path ? toktx_path : \"toktx\";\n\n\tcmd += \" --version\";\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ true);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0;\n}\n\nstatic int readInt16(const std::string& data, size_t offset)\n{\n\treturn (unsigned char)data[offset] * 256 + (unsigned char)data[offset + 1];\n}\n\nstatic bool getDimensionsPng(const std::string& data, int& width, int& height)\n{\n\tif (data.size() < 8 + 8 + 13 + 4)\n\t\treturn false;\n\n\tconst char* signature = \"\\x89\\x50\\x4e\\x47\\x0d\\x0a\\x1a\\x0a\";\n\tif (data.compare(0, 8, signature) != 0)\n\t\treturn false;\n\n\tif (data.compare(12, 4, \"IHDR\") != 0)\n\t\treturn false;\n\n\twidth = readInt16(data, 18);\n\theight = readInt16(data, 22);\n\n\treturn true;\n}\n\nstatic bool getDimensionsJpeg(const std::string& data, int& width, int& height)\n{\n\tsize_t offset = 0;\n\n\t\/\/ note, this can stop parsing before reaching the end but we stop at SOF anyway\n\twhile (offset + 4 <= data.size())\n\t{\n\t\tif (data[offset] != '\\xff')\n\t\t\treturn false;\n\n\t\tchar marker = data[offset];\n\n\t\tif (marker == '\\xff')\n\t\t{\n\t\t\toffset++;\n\t\t\tcontinue; \/\/ padding\n\t\t}\n\n\t\t\/\/ d0..d9 correspond to SOI, RSTn, EOI\n\t\tif (marker == 0 || unsigned(marker - '\\xd0') <= 9)\n\t\t{\n\t\t\toffset += 2;\n\t\t\tcontinue; \/\/ no payload\n\t\t}\n\n\t\t\/\/ c0..c1 correspond to SOF0, SOF1\n\t\tif (marker == '\\xc0' || marker == '\\xc2')\n\t\t{\n\t\t\tif (offset + 10 > data.size())\n\t\t\t\treturn false;\n\n\t\t\twidth = readInt16(data, offset + 7);\n\t\t\theight = readInt16(data, offset + 5);\n\n\t\t\treturn true;\n\t\t}\n\n\t\toffset += 2 + readInt16(data, offset + 2);\n\t}\n\n\treturn false;\n}\n\nstatic bool getDimensions(const std::string& data, const char* mime_type, int& width, int& height)\n{\n\tif (strcmp(mime_type, \"image\/png\") == 0)\n\t\treturn getDimensionsPng(data, width, height);\n\tif (strcmp(mime_type, \"image\/jpeg\") == 0)\n\t\treturn getDimensionsJpeg(data, width, height);\n\n\treturn false;\n}\n\nstatic int roundPow2(int value)\n{\n\tint result = 1;\n\n\twhile (result < value)\n\t\tresult <<= 1;\n\n\t\/\/ to prevent odd texture sizes from increasing the size too much, we round to nearest power of 2 above a certain size\n\tif (value > 128 && result * 3 \/ 4 > value)\n\t\tresult >>= 1;\n\n\treturn result;\n}\n\nstatic int roundBlock(int value)\n{\n\treturn (value == 1 || value == 2) ? value : (value + 3) & ~3;\n}\n\nbool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool pow2, bool uastc, bool verbose)\n{\n\tint width = 0, height = 0;\n\tif (!getDimensions(data, mime_type, width, height))\n\t\treturn false;\n\n\tTempFile temp_input(mimeExtension(mime_type));\n\tTempFile temp_output(\".ktx2\");\n\n\tif (!writeFile(temp_input.path.c_str(), data))\n\t\treturn false;\n\n\tconst char* toktx_path = readenv(\"TOKTX_PATH\");\n\tstd::string cmd = toktx_path ? toktx_path : \"toktx\";\n\n\tconst BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1];\n\n\tcmd += \" --t2\";\n\tcmd += \" --2d\";\n\tcmd += \" --genmipmap\";\n\tcmd += \" --nowarn\";\n\n\tint (*round)(int value) = pow2 ? roundPow2 : roundBlock;\n\tint newWidth = round(int(width * scale)), newHeight = round(int(height * scale));\n\n\tif (newWidth != width || newHeight != height)\n\t{\n\t\tchar wh[128];\n\t\tsprintf(wh, \" --resize %dx%d\", newWidth, newHeight);\n\t\tcmd += wh;\n\t}\n\n\tif (uastc)\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" %d --uastc_rdo_q %.2f\", bs.uastc_l, bs.uastc_q);\n\n\t\tcmd += \" --uastc\";\n\t\tcmd += settings;\n\t\tcmd += \" --uastc_rdo_d 1024\";\n\t\tcmd += \" --zcmp 9\";\n\t}\n\telse\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" --clevel %d --qlevel %d\", bs.etc1s_l, bs.etc1s_q);\n\n\t\tcmd += \" --bcmp\";\n\t\tcmd += settings;\n\n\t\t\/\/ for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness\n\t\tif (normal_map)\n\t\t\tcmd += \" --normal_map\";\n\t}\n\n\tif (srgb)\n\t\tcmd += \" --srgb\";\n\telse\n\t\tcmd += \" --linear\";\n\n\tcmd += \" -- \";\n\tcmd += temp_output.path;\n\tcmd += \" \";\n\tcmd += temp_input.path;\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ false, \/* ignore_stderr= *\/ false);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0 && readFile(temp_output.path.c_str(), result);\n}\n<commit_msg>gltfpack: Fix rounding logic for small textures<commit_after>\/\/ This file is part of gltfpack; see gltfpack.h for version\/license details\n#include \"gltfpack.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten.h>\n#endif\n\nstruct BasisSettings\n{\n\tint etc1s_l;\n\tint etc1s_q;\n\tint uastc_l;\n\tfloat uastc_q;\n};\n\nstatic const char* kMimeTypes[][2] = {\n {\"image\/jpeg\", \".jpg\"},\n {\"image\/jpeg\", \".jpeg\"},\n {\"image\/png\", \".png\"},\n};\n\nstatic const BasisSettings kBasisSettings[10] = {\n {1, 1, 0, 1.5f},\n {1, 6, 0, 1.f},\n {1, 20, 1, 1.0f},\n {1, 50, 1, 0.75f},\n {1, 90, 1, 0.5f},\n {1, 128, 1, 0.4f},\n {1, 160, 1, 0.34f},\n {1, 192, 1, 0.29f}, \/\/ default\n {1, 224, 2, 0.26f},\n {1, 255, 2, 0.f},\n};\n\nvoid analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)\n{\n\tfor (size_t i = 0; i < data->materials_count; ++i)\n\t{\n\t\tconst cgltf_material& material = data->materials[i];\n\n\t\tif (material.has_pbr_metallic_roughness)\n\t\t{\n\t\t\tconst cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;\n\n\t\t\tif (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)\n\t\t\t\timages[pbr.base_color_texture.texture->image - data->images].srgb = true;\n\t\t}\n\n\t\tif (material.has_pbr_specular_glossiness)\n\t\t{\n\t\t\tconst cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;\n\n\t\t\tif (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)\n\t\t\t\timages[pbr.diffuse_texture.texture->image - data->images].srgb = true;\n\t\t}\n\n\t\tif (material.emissive_texture.texture && material.emissive_texture.texture->image)\n\t\t\timages[material.emissive_texture.texture->image - data->images].srgb = true;\n\n\t\tif (material.normal_texture.texture && material.normal_texture.texture->image)\n\t\t\timages[material.normal_texture.texture->image - data->images].normal_map = true;\n\t}\n}\n\nconst char* inferMimeType(const char* path)\n{\n\tconst char* ext = strrchr(path, '.');\n\tif (!ext)\n\t\treturn \"\";\n\n\tstd::string extl = ext;\n\tfor (size_t i = 0; i < extl.length(); ++i)\n\t\textl[i] = char(tolower(extl[i]));\n\n\tfor (size_t i = 0; i < sizeof(kMimeTypes) \/ sizeof(kMimeTypes[0]); ++i)\n\t\tif (extl == kMimeTypes[i][1])\n\t\t\treturn kMimeTypes[i][0];\n\n\treturn \"\";\n}\n\nstatic const char* mimeExtension(const char* mime_type)\n{\n\tfor (size_t i = 0; i < sizeof(kMimeTypes) \/ sizeof(kMimeTypes[0]); ++i)\n\t\tif (strcmp(kMimeTypes[i][0], mime_type) == 0)\n\t\t\treturn kMimeTypes[i][1];\n\n\treturn \".raw\";\n}\n\n#ifdef __EMSCRIPTEN__\nEM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {\n\tvar cp = require('child_process');\n\tvar stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];\n\tvar ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });\n\treturn ret.status == null ? 256 : ret.status;\n});\n\nEM_JS(const char*, readenv, (const char* name), {\n\tvar val = process.env[UTF8ToString(name)];\n\tif (!val)\n\t\treturn 0;\n\tvar ret = _malloc(lengthBytesUTF8(val) + 1);\n\tstringToUTF8(val, ret, lengthBytesUTF8(val) + 1);\n\treturn ret;\n});\n#else\nstatic int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)\n{\n#ifdef _WIN32\n\tstd::string ignore = \"nul\";\n#else\n\tstd::string ignore = \"\/dev\/null\";\n#endif\n\n\tstd::string cmd = cmd_;\n\n\tif (ignore_stdout)\n\t\t(cmd += \" >\") += ignore;\n\tif (ignore_stderr)\n\t\t(cmd += \" 2>\") += ignore;\n\n\treturn system(cmd.c_str());\n}\n\nstatic const char* readenv(const char* name)\n{\n\treturn getenv(name);\n}\n#endif\n\nbool checkBasis(bool verbose)\n{\n\tconst char* basisu_path = readenv(\"BASISU_PATH\");\n\tstd::string cmd = basisu_path ? basisu_path : \"basisu\";\n\n\tcmd += \" -version\";\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ true);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0;\n}\n\nbool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool pow2, bool uastc, bool verbose)\n{\n\t(void)scale;\n\t(void)pow2;\n\n\tTempFile temp_input(mimeExtension(mime_type));\n\tTempFile temp_output(\".basis\");\n\n\tif (!writeFile(temp_input.path.c_str(), data))\n\t\treturn false;\n\n\tconst char* basisu_path = readenv(\"BASISU_PATH\");\n\tstd::string cmd = basisu_path ? basisu_path : \"basisu\";\n\n\tconst BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1];\n\n\tcmd += \" -mipmap\";\n\n\tif (normal_map)\n\t{\n\t\tcmd += \" -normal_map\";\n\t\t\/\/ for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness\n\t}\n\telse if (!srgb)\n\t{\n\t\tcmd += \" -linear\";\n\t}\n\n\tif (uastc)\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" -uastc_level %d -uastc_rdo_q %.2f\", bs.uastc_l, bs.uastc_q);\n\n\t\tcmd += \" -uastc\";\n\t\tcmd += settings;\n\t\tcmd += \" -uastc_rdo_d 1024\";\n\t}\n\telse\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" -comp_level %d -q %d\", bs.etc1s_l, bs.etc1s_q);\n\n\t\tcmd += settings;\n\t}\n\n\tcmd += \" -file \";\n\tcmd += temp_input.path;\n\tcmd += \" -output_file \";\n\tcmd += temp_output.path;\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ false);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0 && readFile(temp_output.path.c_str(), result);\n}\n\nbool checkKtx(bool verbose)\n{\n\tconst char* toktx_path = readenv(\"TOKTX_PATH\");\n\tstd::string cmd = toktx_path ? toktx_path : \"toktx\";\n\n\tcmd += \" --version\";\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ true, \/* ignore_stderr= *\/ true);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0;\n}\n\nstatic int readInt16(const std::string& data, size_t offset)\n{\n\treturn (unsigned char)data[offset] * 256 + (unsigned char)data[offset + 1];\n}\n\nstatic bool getDimensionsPng(const std::string& data, int& width, int& height)\n{\n\tif (data.size() < 8 + 8 + 13 + 4)\n\t\treturn false;\n\n\tconst char* signature = \"\\x89\\x50\\x4e\\x47\\x0d\\x0a\\x1a\\x0a\";\n\tif (data.compare(0, 8, signature) != 0)\n\t\treturn false;\n\n\tif (data.compare(12, 4, \"IHDR\") != 0)\n\t\treturn false;\n\n\twidth = readInt16(data, 18);\n\theight = readInt16(data, 22);\n\n\treturn true;\n}\n\nstatic bool getDimensionsJpeg(const std::string& data, int& width, int& height)\n{\n\tsize_t offset = 0;\n\n\t\/\/ note, this can stop parsing before reaching the end but we stop at SOF anyway\n\twhile (offset + 4 <= data.size())\n\t{\n\t\tif (data[offset] != '\\xff')\n\t\t\treturn false;\n\n\t\tchar marker = data[offset];\n\n\t\tif (marker == '\\xff')\n\t\t{\n\t\t\toffset++;\n\t\t\tcontinue; \/\/ padding\n\t\t}\n\n\t\t\/\/ d0..d9 correspond to SOI, RSTn, EOI\n\t\tif (marker == 0 || unsigned(marker - '\\xd0') <= 9)\n\t\t{\n\t\t\toffset += 2;\n\t\t\tcontinue; \/\/ no payload\n\t\t}\n\n\t\t\/\/ c0..c1 correspond to SOF0, SOF1\n\t\tif (marker == '\\xc0' || marker == '\\xc2')\n\t\t{\n\t\t\tif (offset + 10 > data.size())\n\t\t\t\treturn false;\n\n\t\t\twidth = readInt16(data, offset + 7);\n\t\t\theight = readInt16(data, offset + 5);\n\n\t\t\treturn true;\n\t\t}\n\n\t\toffset += 2 + readInt16(data, offset + 2);\n\t}\n\n\treturn false;\n}\n\nstatic bool getDimensions(const std::string& data, const char* mime_type, int& width, int& height)\n{\n\tif (strcmp(mime_type, \"image\/png\") == 0)\n\t\treturn getDimensionsPng(data, width, height);\n\tif (strcmp(mime_type, \"image\/jpeg\") == 0)\n\t\treturn getDimensionsJpeg(data, width, height);\n\n\treturn false;\n}\n\nstatic int roundPow2(int value)\n{\n\tint result = 1;\n\n\twhile (result < value)\n\t\tresult <<= 1;\n\n\t\/\/ to prevent odd texture sizes from increasing the size too much, we round to nearest power of 2 above a certain size\n\tif (value > 128 && result * 3 \/ 4 > value)\n\t\tresult >>= 1;\n\n\treturn result;\n}\n\nstatic int roundBlock(int value)\n{\n\treturn (value + 3) & ~3;\n}\n\nbool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool pow2, bool uastc, bool verbose)\n{\n\tint width = 0, height = 0;\n\tif (!getDimensions(data, mime_type, width, height))\n\t\treturn false;\n\n\tTempFile temp_input(mimeExtension(mime_type));\n\tTempFile temp_output(\".ktx2\");\n\n\tif (!writeFile(temp_input.path.c_str(), data))\n\t\treturn false;\n\n\tconst char* toktx_path = readenv(\"TOKTX_PATH\");\n\tstd::string cmd = toktx_path ? toktx_path : \"toktx\";\n\n\tconst BasisSettings& bs = kBasisSettings[quality <= 0 ? 0 : quality > 9 ? 9 : quality - 1];\n\n\tcmd += \" --t2\";\n\tcmd += \" --2d\";\n\tcmd += \" --genmipmap\";\n\tcmd += \" --nowarn\";\n\n\tint newWidth = roundBlock(int(width * scale)), newHeight = roundBlock(int(height * scale));\n\n\tif (pow2)\n\t{\n\t\tnewWidth = roundPow2(newWidth);\n\t\tnewHeight = roundPow2(newHeight);\n\t}\n\n\tif (newWidth != width || newHeight != height)\n\t{\n\t\tchar wh[128];\n\t\tsprintf(wh, \" --resize %dx%d\", newWidth, newHeight);\n\t\tcmd += wh;\n\t}\n\n\tif (uastc)\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" %d --uastc_rdo_q %.2f\", bs.uastc_l, bs.uastc_q);\n\n\t\tcmd += \" --uastc\";\n\t\tcmd += settings;\n\t\tcmd += \" --uastc_rdo_d 1024\";\n\t\tcmd += \" --zcmp 9\";\n\t}\n\telse\n\t{\n\t\tchar settings[128];\n\t\tsprintf(settings, \" --clevel %d --qlevel %d\", bs.etc1s_l, bs.etc1s_q);\n\n\t\tcmd += \" --bcmp\";\n\t\tcmd += settings;\n\n\t\t\/\/ for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness\n\t\tif (normal_map)\n\t\t\tcmd += \" --normal_map\";\n\t}\n\n\tif (srgb)\n\t\tcmd += \" --srgb\";\n\telse\n\t\tcmd += \" --linear\";\n\n\tcmd += \" -- \";\n\tcmd += temp_output.path;\n\tcmd += \" \";\n\tcmd += temp_input.path;\n\n\tint rc = execute(cmd.c_str(), \/* ignore_stdout= *\/ false, \/* ignore_stderr= *\/ false);\n\tif (verbose)\n\t\tprintf(\"%s => %d\\n\", cmd.c_str(), rc);\n\n\treturn rc == 0 && readFile(temp_output.path.c_str(), result);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Miguel Rentes on 30\/01\/2017.\n\/\/\n\n#include \"STL.h\"\n\nvoid printKMax(int arr[], int n, int k) {\n deque<int> mydeque;\n for (int i = 0; i < n; i++) {\n \/\/ clean the deque at the back if the array element is greater\n \/\/ than the ones currently on the deque\n for (; !mydeque.empty() && arr[i] > mydeque.back();)\n mydeque.pop_back();\n mydeque.push_back(arr[i]);\n if (i >= k && mydeque.front() == arr[i-k])\n mydeque.pop_front();\n \/\/ at the end of the k-elements\n if (i >= k-1)\n printf (i < n-1 ? \"%d \" : \"%d\\n\", mydeque.front());\n }\n}\n\nint main(void) {\n int t;\n cin >> t;\n while (t > 0) {\n int n, k;\n cin >> n >> k;\n int i;\n int arr[n];\n for (i = 0; i < n; i++)\n cin >> arr[i];\n printKMax(arr, n, k);\n t--;\n }\n return EXIT_SUCCESS;\n}<commit_msg>Refactors solution for the Deque-STL challenge.<commit_after>\/\/\n\/\/ Created by Miguel Rentes on 30\/01\/2017.\n\/\/\n\n#include \"STL.h\"\n\nvoid printKMax(int arr[], int n, int k) {\n deque<int> mydeque;\n for (int i = 0; i < n; i++) {\n \/\/ clean the deque at the back if the array element is greater\n \/\/ than the ones currently on the deque\n for (; !mydeque.empty() && arr[i] > mydeque.back();)\n mydeque.pop_back();\n mydeque.push_back(arr[i]);\n \/\/ at another set of k-elements\n \/\/ pop out the elements if they are the same as the ones\n \/\/ previously read\n if (i >= k && mydeque.front() == arr[i-k])\n mydeque.pop_front();\n \/\/ at the end of the k-elements\n if (i >= k-1)\n printf (i < n-1 ? \"%d \" : \"%d\\n\", mydeque.front());\n }\n}\n\nint main(void) {\n int t;\n cin >> t;\n while (t > 0) {\n int n, k;\n cin >> n >> k;\n int i;\n int arr[n];\n for (i = 0; i < n; i++)\n cin >> arr[i];\n printKMax(arr, n, k);\n t--;\n }\n return EXIT_SUCCESS;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n\n#define W 400\n#define H 400\n#define N 10\n\nconstexpr SkScalar SH = SkIntToScalar(H);\n\nstatic void rnd_quad(SkPath* p, SkPaint* paint, SkRandom& rand) {\n p->moveTo(rand.nextRangeScalar(0, W), rand.nextRangeScalar(0, H));\n for (int x = 0; x < 2; ++x) {\n auto a = rand.nextRangeScalar(W\/4, W),\n b = rand.nextRangeScalar( 0, H),\n c = rand.nextRangeScalar( 0, W),\n d = rand.nextRangeScalar(H\/4, H);\n p->quadTo(a,b,c,d);\n }\n paint->setColor(rand.nextU());\n SkScalar width = rand.nextRangeScalar(1, 5);\n width *= width;\n paint->setStrokeWidth(width);\n paint->setAlpha(0xFF);\n}\n\nstatic void rnd_cubic(SkPath* p, SkPaint* paint, SkRandom& rand) {\n auto a = rand.nextRangeScalar(0,W),\n b = rand.nextRangeScalar(0,H);\n p->moveTo(a,b);\n for (int x = 0; x < 2; ++x) {\n auto c = rand.nextRangeScalar(W\/4, W),\n d = rand.nextRangeScalar( 0, H),\n e = rand.nextRangeScalar( 0, W),\n f = rand.nextRangeScalar(H\/4, H),\n g = rand.nextRangeScalar(W\/4, W),\n h = rand.nextRangeScalar(H\/4, H);\n p->cubicTo(c,d,e,f,g,h);\n }\n paint->setColor(rand.nextU());\n SkScalar width = rand.nextRangeScalar(1, 5);\n width *= width;\n paint->setStrokeWidth(width);\n paint->setAlpha(0xFF);\n}\n\nclass BeziersGM : public skiagm::GM {\npublic:\n BeziersGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"beziers\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(W, H*2);\n }\n\n void onDraw(SkCanvas* canvas) override {\n SkPaint paint;\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(9)\/2);\n paint.setAntiAlias(true);\n\n SkRandom rand;\n for (int i = 0; i < N; i++) {\n SkPath p;\n rnd_quad(&p, &paint, rand);\n canvas->drawPath(p, paint);\n }\n canvas->translate(0, SH);\n for (int i = 0; i < N; i++) {\n SkPath p;\n rnd_cubic(&p, &paint, rand);\n canvas->drawPath(p, paint);\n }\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\nDEF_GM( return new BeziersGM; )\n<commit_msg>beziers: I missed an unsequenced moveTo() pair.<commit_after>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n\n#define W 400\n#define H 400\n#define N 10\n\nconstexpr SkScalar SH = SkIntToScalar(H);\n\nstatic void rnd_quad(SkPath* p, SkPaint* paint, SkRandom& rand) {\n auto a = rand.nextRangeScalar(0,W),\n b = rand.nextRangeScalar(0,H);\n p->moveTo(a,b);\n for (int x = 0; x < 2; ++x) {\n auto c = rand.nextRangeScalar(W\/4, W),\n d = rand.nextRangeScalar( 0, H),\n e = rand.nextRangeScalar( 0, W),\n f = rand.nextRangeScalar(H\/4, H);\n p->quadTo(c,d,e,f);\n }\n paint->setColor(rand.nextU());\n SkScalar width = rand.nextRangeScalar(1, 5);\n width *= width;\n paint->setStrokeWidth(width);\n paint->setAlpha(0xFF);\n}\n\nstatic void rnd_cubic(SkPath* p, SkPaint* paint, SkRandom& rand) {\n auto a = rand.nextRangeScalar(0,W),\n b = rand.nextRangeScalar(0,H);\n p->moveTo(a,b);\n for (int x = 0; x < 2; ++x) {\n auto c = rand.nextRangeScalar(W\/4, W),\n d = rand.nextRangeScalar( 0, H),\n e = rand.nextRangeScalar( 0, W),\n f = rand.nextRangeScalar(H\/4, H),\n g = rand.nextRangeScalar(W\/4, W),\n h = rand.nextRangeScalar(H\/4, H);\n p->cubicTo(c,d,e,f,g,h);\n }\n paint->setColor(rand.nextU());\n SkScalar width = rand.nextRangeScalar(1, 5);\n width *= width;\n paint->setStrokeWidth(width);\n paint->setAlpha(0xFF);\n}\n\nclass BeziersGM : public skiagm::GM {\npublic:\n BeziersGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"beziers\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(W, H*2);\n }\n\n void onDraw(SkCanvas* canvas) override {\n SkPaint paint;\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(9)\/2);\n paint.setAntiAlias(true);\n\n SkRandom rand;\n for (int i = 0; i < N; i++) {\n SkPath p;\n rnd_quad(&p, &paint, rand);\n canvas->drawPath(p, paint);\n }\n canvas->translate(0, SH);\n for (int i = 0; i < N; i++) {\n SkPath p;\n rnd_cubic(&p, &paint, rand);\n canvas->drawPath(p, paint);\n }\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\nDEF_GM( return new BeziersGM; )\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2005, Thorvald Natvig <thorvald@natvig.com>\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n#include <QApplication>\n#include <QHostAddress>\n#include \"ServerHandler.h\"\n#include \"MainWindow.h\"\n#include \"AudioOutput.h\"\n#include \"Global.h\"\n\nServerHandlerMessageEvent::ServerHandlerMessageEvent(QByteArray &msg, bool udp) : QEvent(static_cast<QEvent::Type>(SERVERSEND_EVENT)) {\n\tqbaMsg = msg;\n\tbUdp = udp;\n}\n\nServerHandler::ServerHandler()\n{\n\tcConnection = NULL;\n\tqusUdp = NULL;\n}\n\nServerHandler::~ServerHandler()\n{\n\twait();\n}\n\nvoid ServerHandler::customEvent(QEvent *evt) {\n\tif (evt->type() != SERVERSEND_EVENT)\n\t\treturn;\n\n\tServerHandlerMessageEvent *shme=static_cast<ServerHandlerMessageEvent *>(evt);\n\n\tif (cConnection) {\n\t\tif (shme->qbaMsg.size() > 0) {\n\t\t\tif (shme->bUdp) {\n\t\t\t\tif (! qusUdp) {\n\t\t\t\t\tqusUdp = new QUdpSocket(this);\n\t\t\t\t\tqusUdp->bind();\n\t\t\t\t\tconnect(qusUdp, SIGNAL(readyRead()), this, SLOT(udpReady()));\n\t\t\t\t\tqhaRemote = cConnection->peerAddress();\n\t\t\t\t}\n\t\t\t\tqusUdp->writeDatagram(shme->qbaMsg, qhaRemote, iPort);\n\t\t\t} else {\n\t\t\t\tcConnection->sendMessage(shme->qbaMsg);\n\t\t\t}\n\t\t} else\n\t\t\tcConnection->disconnect();\n\t}\n}\n\nvoid ServerHandler::udpReady() {\n\twhile (qusUdp->hasPendingDatagrams()) {\n\t\tQByteArray qba;\n\t\tqba.resize(qusUdp->pendingDatagramSize());\n\t\tQHostAddress senderAddr;\n\t\tquint16 senderPort;\n\t\tqusUdp->readDatagram(qba.data(), qba.size(), &senderAddr, &senderPort);\n\n\t\tif (!(senderAddr == qhaRemote) || (senderPort != iPort))\n\t\t\tcontinue;\n\n\t\tMessage *msg = Message::networkToMessage(qba);\n\n\t\tif (! msg)\n\t\t\tcontinue;\n\t\tif (msg->messageType() != Message::Speex) {\n\t\t\tdelete msg;\n\t\t\tcontinue;\n\t\t}\n message(qba);\n\t\tdelete msg;\n\t}\n}\n\nvoid ServerHandler::sendMessage(Message *mMsg)\n{\n\tQByteArray qbaBuffer;\n\tmMsg->sPlayerId = g.sId;\n\tmMsg->messageToNetwork(qbaBuffer);\n\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaBuffer, bUdp && g.sId && (mMsg->messageType() == Message::Speex));\n\tQApplication::postEvent(this, shme);\n}\n\nvoid ServerHandler::run()\n{\n\tQTcpSocket *qtsSock = new QTcpSocket(this);\n\tcConnection = new Connection(this, qtsSock);\n\tqusUdp = NULL;\n\n\tconnect(qtsSock, SIGNAL(connected()), this, SLOT(serverConnectionConnected()));\n\tconnect(cConnection, SIGNAL(connectionClosed(QString)), this, SLOT(serverConnectionClosed(QString)));\n\tconnect(cConnection, SIGNAL(message(QByteArray &)), this, SLOT(message(QByteArray &)));\n\tqtsSock->connectToHost(qsHostName, iPort);\n\texec();\n\tcConnection->disconnect();\n\tdelete cConnection;\n\tcConnection = NULL;\n\tif (qusUdp) {\n\t\tdelete qusUdp;\n\t\tqusUdp = NULL;\n\t}\n}\n\nvoid ServerHandler::message(QByteArray &qbaMsg) {\n\tMessage *mMsg = Message::networkToMessage(qbaMsg);\n\tif (! mMsg)\n\t\treturn;\n\n\tPlayer *p = Player::get(mMsg->sPlayerId);\n\n\tif (mMsg->messageType() == Message::Speex) {\n\t\tQWriteLocker alocka(&g.qrwlAudio);\n\t\tif (g.ao) {\n\t\t\tif (p) {\n\t\t\t\tMessageSpeex *msMsg=static_cast<MessageSpeex *>(mMsg);\n\t\t\t\tg.ao->addFrameToBuffer(p, msMsg->qbaSpeexPacket, msMsg->iSeq);\n\t\t\t} else {\n\t\t\t\t\/\/ Eek, we just got a late packet for a player already removed. Remove\n\t\t\t\t\/\/ the buffer and pretend this never happened.\n\t\t\t\t\/\/ If ~AudioOutputPlayer or decendants uses the Player object now,\n\t\t\t\t\/\/ Bad Things happen.\n\t\t\t\tg.ao->removeBuffer(p);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif(mMsg->messageType() == Message::ServerLeave) {\n\t\t\tQReadLocker alockb(&g.qrwlAudio);\n\t\t\tif (g.ao)\n\t\t\t\tg.ao->removeBuffer(p);\n\t\t}\n\t\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaMsg, false);\n\t\tQApplication::postEvent(g.mw, shme);\n\t}\n\n\tdelete mMsg;\n}\n\nvoid ServerHandler::disconnect() {\n\t\/\/ Actual TCP object is in a different thread, so signal it\n\tQByteArray qbaBuffer;\n\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaBuffer, false);\n\tQApplication::postEvent(this, shme);\n}\n\nvoid ServerHandler::serverConnectionClosed(QString reason) {\n\t{\n\t\tQReadLocker alock(&g.qrwlAudio);\n\t\tif (g.ao)\n\t\t\tg.ao->wipe();\n\t}\n\n\temit disconnected(reason);\n\texit(0);\n}\n\nvoid ServerHandler::serverConnectionConnected() {\n\tMessageServerAuthenticate msaMsg;\n\tmsaMsg.qsUsername = qsUserName;\n\tmsaMsg.qsPassword = qsPassword;\n\tcConnection->sendMessage(&msaMsg);\n\temit connected();\n}\n\nvoid ServerHandler::setConnectionInfo(QString host, int port, bool udp, QString username, QString pw) {\n\tqWarning(\"bUDP set to %d\", udp);\n\tqsHostName = host;\n\tiPort = port;\n\tbUdp = udp;\n\tqsUserName = username;\n\tqsPassword = pw;\n}\n<commit_msg>*** empty log message ***<commit_after>\/* Copyright (C) 2005, Thorvald Natvig <thorvald@natvig.com>\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n#include <QApplication>\n#include <QHostAddress>\n#include \"ServerHandler.h\"\n#include \"MainWindow.h\"\n#include \"AudioOutput.h\"\n#include \"Global.h\"\n\nServerHandlerMessageEvent::ServerHandlerMessageEvent(QByteArray &msg, bool udp) : QEvent(static_cast<QEvent::Type>(SERVERSEND_EVENT)) {\n\tqbaMsg = msg;\n\tbUdp = udp;\n}\n\nServerHandler::ServerHandler()\n{\n\tcConnection = NULL;\n\tqusUdp = NULL;\n}\n\nServerHandler::~ServerHandler()\n{\n\twait();\n}\n\nvoid ServerHandler::customEvent(QEvent *evt) {\n\tif (evt->type() != SERVERSEND_EVENT)\n\t\treturn;\n\n\tServerHandlerMessageEvent *shme=static_cast<ServerHandlerMessageEvent *>(evt);\n\n\tif (cConnection) {\n\t\tif (shme->qbaMsg.size() > 0) {\n\t\t\tif (shme->bUdp) {\n\t\t\t\tif (! qusUdp) {\n\t\t\t\t\tqusUdp = new QUdpSocket(this);\n\t\t\t\t\tqusUdp->bind();\n\t\t\t\t\tconnect(qusUdp, SIGNAL(readyRead()), this, SLOT(udpReady()));\n\t\t\t\t\tqhaRemote = cConnection->peerAddress();\n\t\t\t\t}\n\t\t\t\tqusUdp->writeDatagram(shme->qbaMsg, qhaRemote, iPort);\n\t\t\t} else {\n\t\t\t\tcConnection->sendMessage(shme->qbaMsg);\n\t\t\t}\n\t\t} else\n\t\t\tcConnection->disconnect();\n\t}\n}\n\nvoid ServerHandler::udpReady() {\n\twhile (qusUdp->hasPendingDatagrams()) {\n\t\tQByteArray qba;\n\t\tqba.resize(qusUdp->pendingDatagramSize());\n\t\tQHostAddress senderAddr;\n\t\tquint16 senderPort;\n\t\tqusUdp->readDatagram(qba.data(), qba.size(), &senderAddr, &senderPort);\n\n\t\tif (!(senderAddr == qhaRemote) || (senderPort != iPort))\n\t\t\tcontinue;\n\n\t\tMessage *msg = Message::networkToMessage(qba);\n\n\t\tif (! msg)\n\t\t\tcontinue;\n\t\tif (msg->messageType() != Message::Speex) {\n\t\t\tdelete msg;\n\t\t\tcontinue;\n\t\t}\n message(qba);\n\t\tdelete msg;\n\t}\n}\n\nvoid ServerHandler::sendMessage(Message *mMsg)\n{\n\tQByteArray qbaBuffer;\n\tmMsg->sPlayerId = g.sId;\n\tmMsg->messageToNetwork(qbaBuffer);\n\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaBuffer, bUdp && g.sId && (mMsg->messageType() == Message::Speex));\n\tQApplication::postEvent(this, shme);\n}\n\nvoid ServerHandler::run()\n{\n\tQTcpSocket *qtsSock = new QTcpSocket(this);\n\tcConnection = new Connection(this, qtsSock);\n\tqusUdp = NULL;\n\n\tconnect(qtsSock, SIGNAL(connected()), this, SLOT(serverConnectionConnected()));\n\tconnect(cConnection, SIGNAL(connectionClosed(QString)), this, SLOT(serverConnectionClosed(QString)));\n\tconnect(cConnection, SIGNAL(message(QByteArray &)), this, SLOT(message(QByteArray &)));\n\tqtsSock->connectToHost(qsHostName, iPort);\n\texec();\n\tcConnection->disconnect();\n\tdelete cConnection;\n\tcConnection = NULL;\n\tif (qusUdp) {\n\t\tdelete qusUdp;\n\t\tqusUdp = NULL;\n\t}\n}\n\nvoid ServerHandler::message(QByteArray &qbaMsg) {\n\tMessage *mMsg = Message::networkToMessage(qbaMsg);\n\tif (! mMsg)\n\t\treturn;\n\n\tPlayer *p = Player::get(mMsg->sPlayerId);\n\n\tif (mMsg->messageType() == Message::Speex) {\n\t\tQWriteLocker alocka(&g.qrwlAudio);\n\t\tif (g.ao) {\n\t\t\tif (p) {\n\t\t\t\tMessageSpeex *msMsg=static_cast<MessageSpeex *>(mMsg);\n\t\t\t\tg.ao->addFrameToBuffer(p, msMsg->qbaSpeexPacket, msMsg->iSeq);\n\t\t\t} else {\n\t\t\t\t\/\/ Eek, we just got a late packet for a player already removed. Remove\n\t\t\t\t\/\/ the buffer and pretend this never happened.\n\t\t\t\t\/\/ If ~AudioOutputPlayer or decendants uses the Player object now,\n\t\t\t\t\/\/ Bad Things happen.\n\t\t\t\tg.ao->removeBuffer(p);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif(mMsg->messageType() == Message::ServerLeave) {\n\t\t\tQReadLocker alockb(&g.qrwlAudio);\n\t\t\tif (g.ao)\n\t\t\t\tg.ao->removeBuffer(p);\n\t\t}\n\t\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaMsg, false);\n\t\tQApplication::postEvent(g.mw, shme);\n\t}\n\n\tdelete mMsg;\n}\n\nvoid ServerHandler::disconnect() {\n\t\/\/ Actual TCP object is in a different thread, so signal it\n\tQByteArray qbaBuffer;\n\tServerHandlerMessageEvent *shme=new ServerHandlerMessageEvent(qbaBuffer, false);\n\tQApplication::postEvent(this, shme);\n}\n\nvoid ServerHandler::serverConnectionClosed(QString reason) {\n\t{\n\t\tQReadLocker alock(&g.qrwlAudio);\n\t\tif (g.ao)\n\t\t\tg.ao->wipe();\n\t}\n\n\temit disconnected(reason);\n\texit(0);\n}\n\nvoid ServerHandler::serverConnectionConnected() {\n\tMessageServerAuthenticate msaMsg;\n\tmsaMsg.qsUsername = qsUserName;\n\tmsaMsg.qsPassword = qsPassword;\n\tcConnection->sendMessage(&msaMsg);\n\temit connected();\n}\n\nvoid ServerHandler::setConnectionInfo(QString host, int port, bool udp, QString username, QString pw) {\n\tqsHostName = host;\n\tiPort = port;\n\tbUdp = udp;\n\tqsUserName = username;\n\tqsPassword = pw;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n GURL WaitForSavePackageToFinish() {\n ui_test_utils::TestNotificationObserver observer;\n ui_test_utils::RegisterAndWait(&observer,\n NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n return *Details<GURL>(observer.details()).ptr();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveViewSourceHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL view_source_url = URLRequestMockHTTPJob::GetMockViewSourceUrl(\n FilePath(kTestDir).Append(file_name));\n GURL actual_page_url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), view_source_url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n EXPECT_EQ(actual_page_url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\n} \/\/ namespace\n<commit_msg>Mark 2 failing tests in SavePageBrowserTest as flaky TBR: joth@chromium.org<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n GURL WaitForSavePackageToFinish() {\n ui_test_utils::TestNotificationObserver observer;\n ui_test_utils::RegisterAndWait(&observer,\n NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n return *Details<GURL>(observer.details()).ptr();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveViewSourceHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL view_source_url = URLRequestMockHTTPJob::GetMockViewSourceUrl(\n FilePath(kTestDir).Append(file_name));\n GURL actual_page_url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), view_source_url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n EXPECT_EQ(actual_page_url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FLAKY_SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FLAKY_FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n EXPECT_EQ(url, WaitForSavePackageToFinish());\n\n if (browser()->SupportsWindowFeature(Browser::FEATURE_DOWNLOADSHELF))\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/process_singleton.h\"\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <signal.h>\n#include <unistd.h>\n#include <vector>\n#include <string>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/chrome_process_util.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\ntypedef UITest ProcessSingletonLinuxTest;\n\n\/\/ A helper method to call ProcessSingleton::NotifyOtherProcess().\n\/\/ |url| will be added to CommandLine for current process, so that it can be\n\/\/ sent to browser process by ProcessSingleton::NotifyOtherProcess().\nProcessSingleton::NotifyResult NotifyOtherProcess(const std::string& url,\n int timeout_ms) {\n FilePath user_data_dir;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n\n \/\/ Hack: mutate the current process's command line so we don't show a dialog.\n \/\/ Note that this only works if we have no loose values on the command line,\n \/\/ but that's fine for unit tests. In a UI test we disable error dialogs\n \/\/ when spawning Chrome, but this test hits the ProcessSingleton directly.\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n if (!cmd_line->HasSwitch(switches::kNoProcessSingletonDialog))\n cmd_line->AppendSwitch(switches::kNoProcessSingletonDialog);\n\n CommandLine new_cmd_line(*cmd_line);\n new_cmd_line.AppendLooseValue(ASCIIToWide(url));\n\n ProcessSingleton process_singleton(user_data_dir);\n\n return process_singleton.NotifyOtherProcessWithTimeout(\n new_cmd_line, timeout_ms \/ 1000);\n}\n\n} \/\/ namespace\n\n\/\/ Test if the socket file and symbol link created by ProcessSingletonLinux\n\/\/ are valid. When running this test, the ProcessSingleton object is already\n\/\/ initiated by UITest. So we just test against this existing object.\nTEST_F(ProcessSingletonLinuxTest, CheckSocketFile) {\n FilePath user_data_dir;\n FilePath socket_path;\n FilePath lock_path;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n\n socket_path = user_data_dir.Append(chrome::kSingletonSocketFilename);\n lock_path = user_data_dir.Append(chrome::kSingletonLockFilename);\n\n struct stat statbuf;\n ASSERT_EQ(0, lstat(lock_path.value().c_str(), &statbuf));\n ASSERT_TRUE(S_ISLNK(statbuf.st_mode));\n char buf[PATH_MAX + 1];\n ssize_t len = readlink(lock_path.value().c_str(), buf, PATH_MAX);\n ASSERT_GT(len, 0);\n buf[len] = '\\0';\n\n ASSERT_EQ(0, lstat(socket_path.value().c_str(), &statbuf));\n ASSERT_TRUE(S_ISSOCK(statbuf.st_mode));\n}\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ The following tests in linux\/view does not pass without a window manager,\n\/\/ which is true in build\/try bots.\n\/\/ See http:\/\/crbug.com\/30953.\n#define NotifyOtherProcessSuccess FLAKY_NotifyOtherProcessSuccess\n#define NotifyOtherProcessHostChanged FLAKY_NotifyOtherProcessHostChanged\n#endif\n\n\/\/ TODO(james.su@gmail.com): port following tests to Windows.\n\/\/ Test success case of NotifyOtherProcess().\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessSuccess) {\n std::string url(\"about:blank\");\n int original_tab_count = GetTabCount();\n\n EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,\n NotifyOtherProcess(url, action_timeout_ms()));\n EXPECT_EQ(original_tab_count + 1, GetTabCount());\n EXPECT_EQ(url, GetActiveTabURL().spec());\n}\n\n\/\/ Test failure case of NotifyOtherProcess().\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessFailure) {\n base::ProcessId pid = browser_process_id();\n\n ASSERT_GE(pid, 1);\n\n \/\/ Block the browser process, then it'll be killed by\n \/\/ ProcessSingleton::NotifyOtherProcess().\n kill(pid, SIGSTOP);\n\n \/\/ Wait to make sure the browser process is actually stopped.\n \/\/ It's necessary when running with valgrind.\n HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NONE,\n NotifyOtherProcess(url, action_timeout_ms()));\n\n \/\/ Wait for a while to make sure the browser process is actually killed.\n EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));\n}\n\n\/\/ Test that we don't kill ourselves by accident if a lockfile with the same pid\n\/\/ happens to exist.\n\/\/ TODO(mattm): This doesn't really need to be a uitest. (We don't use the\n\/\/ uitest created browser process, but we do use some uitest provided stuff like\n\/\/ the user_data_dir and the NotifyOtherProcess function in this file, which\n\/\/ would have to be duplicated or shared if this test was moved into a\n\/\/ unittest.)\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessNoSuicide) {\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n std::string symlink_content = StringPrintf(\n \"%s%c%u\",\n net::GetHostName().c_str(),\n '-',\n base::GetCurrentProcId());\n EXPECT_EQ(0, symlink(symlink_content.c_str(), lock_path.value().c_str()));\n\n base::ProcessId pid = browser_process_id();\n\n ASSERT_GE(pid, 1);\n\n \/\/ Block the browser process, so that ProcessSingleton::NotifyOtherProcess()\n \/\/ will want to kill something.\n kill(pid, SIGSTOP);\n\n \/\/ Wait to make sure the browser process is actually stopped.\n \/\/ It's necessary when running with valgrind.\n HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NONE,\n NotifyOtherProcess(url, action_timeout_ms()));\n \/\/ If we've gotten to this point without killing ourself, the test succeeded.\n\n \/\/ Unblock the browser process so the test actually finishes.\n kill(pid, SIGCONT);\n}\n\n\/\/ Test that we can still notify a process on the same host even after the\n\/\/ hostname changed.\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessHostChanged) {\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n EXPECT_EQ(0, symlink(\"FAKEFOOHOST-1234\", lock_path.value().c_str()));\n\n int original_tab_count = GetTabCount();\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,\n NotifyOtherProcess(url, action_timeout_ms()));\n EXPECT_EQ(original_tab_count + 1, GetTabCount());\n EXPECT_EQ(url, GetActiveTabURL().spec());\n}\n\n\/\/ Test that we fail when lock says process is on another host and we can't\n\/\/ notify it over the socket.\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessDifferingHost) {\n base::ProcessId pid = browser_process_id();\n\n ASSERT_GE(pid, 1);\n\n \/\/ Kill the browser process, so that it does not respond on the socket.\n kill(pid, SIGKILL);\n \/\/ Wait for a while to make sure the browser process is actually killed.\n EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));\n\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n EXPECT_EQ(0, symlink(\"FAKEFOOHOST-1234\", lock_path.value().c_str()));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,\n NotifyOtherProcess(url, action_timeout_ms()));\n}\n<commit_msg>ProcessSingletonLinux.NotifyOtherProcessNoSuicide removes socket instead of sending SIGSTOP.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/process_singleton.h\"\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <signal.h>\n#include <unistd.h>\n#include <vector>\n#include <string>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/chrome_process_util.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\ntypedef UITest ProcessSingletonLinuxTest;\n\n\/\/ A helper method to call ProcessSingleton::NotifyOtherProcess().\n\/\/ |url| will be added to CommandLine for current process, so that it can be\n\/\/ sent to browser process by ProcessSingleton::NotifyOtherProcess().\nProcessSingleton::NotifyResult NotifyOtherProcess(const std::string& url,\n int timeout_ms) {\n FilePath user_data_dir;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n\n \/\/ Hack: mutate the current process's command line so we don't show a dialog.\n \/\/ Note that this only works if we have no loose values on the command line,\n \/\/ but that's fine for unit tests. In a UI test we disable error dialogs\n \/\/ when spawning Chrome, but this test hits the ProcessSingleton directly.\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n if (!cmd_line->HasSwitch(switches::kNoProcessSingletonDialog))\n cmd_line->AppendSwitch(switches::kNoProcessSingletonDialog);\n\n CommandLine new_cmd_line(*cmd_line);\n new_cmd_line.AppendLooseValue(ASCIIToWide(url));\n\n ProcessSingleton process_singleton(user_data_dir);\n\n return process_singleton.NotifyOtherProcessWithTimeout(\n new_cmd_line, timeout_ms \/ 1000);\n}\n\n} \/\/ namespace\n\n\/\/ Test if the socket file and symbol link created by ProcessSingletonLinux\n\/\/ are valid. When running this test, the ProcessSingleton object is already\n\/\/ initiated by UITest. So we just test against this existing object.\nTEST_F(ProcessSingletonLinuxTest, CheckSocketFile) {\n FilePath user_data_dir;\n FilePath socket_path;\n FilePath lock_path;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n\n socket_path = user_data_dir.Append(chrome::kSingletonSocketFilename);\n lock_path = user_data_dir.Append(chrome::kSingletonLockFilename);\n\n struct stat statbuf;\n ASSERT_EQ(0, lstat(lock_path.value().c_str(), &statbuf));\n ASSERT_TRUE(S_ISLNK(statbuf.st_mode));\n char buf[PATH_MAX + 1];\n ssize_t len = readlink(lock_path.value().c_str(), buf, PATH_MAX);\n ASSERT_GT(len, 0);\n buf[len] = '\\0';\n\n ASSERT_EQ(0, lstat(socket_path.value().c_str(), &statbuf));\n ASSERT_TRUE(S_ISSOCK(statbuf.st_mode));\n}\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ The following tests in linux\/view does not pass without a window manager,\n\/\/ which is true in build\/try bots.\n\/\/ See http:\/\/crbug.com\/30953.\n#define NotifyOtherProcessSuccess FLAKY_NotifyOtherProcessSuccess\n#define NotifyOtherProcessHostChanged FLAKY_NotifyOtherProcessHostChanged\n#endif\n\n\/\/ TODO(james.su@gmail.com): port following tests to Windows.\n\/\/ Test success case of NotifyOtherProcess().\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessSuccess) {\n std::string url(\"about:blank\");\n int original_tab_count = GetTabCount();\n\n EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,\n NotifyOtherProcess(url, action_timeout_ms()));\n EXPECT_EQ(original_tab_count + 1, GetTabCount());\n EXPECT_EQ(url, GetActiveTabURL().spec());\n}\n\n\/\/ Test failure case of NotifyOtherProcess().\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessFailure) {\n base::ProcessId pid = browser_process_id();\n\n ASSERT_GE(pid, 1);\n\n \/\/ Block the browser process, then it'll be killed by\n \/\/ ProcessSingleton::NotifyOtherProcess().\n kill(pid, SIGSTOP);\n\n \/\/ Wait to make sure the browser process is actually stopped.\n \/\/ It's necessary when running with valgrind.\n HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NONE,\n NotifyOtherProcess(url, action_timeout_ms()));\n\n \/\/ Wait for a while to make sure the browser process is actually killed.\n EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));\n}\n\n\/\/ Test that we don't kill ourselves by accident if a lockfile with the same pid\n\/\/ happens to exist.\n\/\/ TODO(mattm): This doesn't really need to be a uitest. (We don't use the\n\/\/ uitest created browser process, but we do use some uitest provided stuff like\n\/\/ the user_data_dir and the NotifyOtherProcess function in this file, which\n\/\/ would have to be duplicated or shared if this test was moved into a\n\/\/ unittest.)\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessNoSuicide) {\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n FilePath socket_path = user_data_dir().Append(chrome::kSingletonSocketFilename);\n\n \/\/ Replace lockfile with one containing our own pid.\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n std::string symlink_content = StringPrintf(\n \"%s%c%u\",\n net::GetHostName().c_str(),\n '-',\n base::GetCurrentProcId());\n EXPECT_EQ(0, symlink(symlink_content.c_str(), lock_path.value().c_str()));\n\n \/\/ Remove socket so that we will not be able to notify the existing browser.\n EXPECT_EQ(0, unlink(socket_path.value().c_str()));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NONE,\n NotifyOtherProcess(url, action_timeout_ms()));\n \/\/ If we've gotten to this point without killing ourself, the test succeeded.\n}\n\n\/\/ Test that we can still notify a process on the same host even after the\n\/\/ hostname changed.\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessHostChanged) {\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n EXPECT_EQ(0, symlink(\"FAKEFOOHOST-1234\", lock_path.value().c_str()));\n\n int original_tab_count = GetTabCount();\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,\n NotifyOtherProcess(url, action_timeout_ms()));\n EXPECT_EQ(original_tab_count + 1, GetTabCount());\n EXPECT_EQ(url, GetActiveTabURL().spec());\n}\n\n\/\/ Test that we fail when lock says process is on another host and we can't\n\/\/ notify it over the socket.\nTEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessDifferingHost) {\n base::ProcessId pid = browser_process_id();\n\n ASSERT_GE(pid, 1);\n\n \/\/ Kill the browser process, so that it does not respond on the socket.\n kill(pid, SIGKILL);\n \/\/ Wait for a while to make sure the browser process is actually killed.\n EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));\n\n FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);\n EXPECT_EQ(0, unlink(lock_path.value().c_str()));\n EXPECT_EQ(0, symlink(\"FAKEFOOHOST-1234\", lock_path.value().c_str()));\n\n std::string url(\"about:blank\");\n EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,\n NotifyOtherProcess(url, action_timeout_ms()));\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>When a DOMUI dialog contains HTML with a select or a text-field which would have auto-fill, bringing the popup crashes the browser. This is because the WebContentView may not have a delegate.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n * \n *\/\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <set>\n#include <vector>\n#include <string>\nusing namespace std;\n\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <sys\/stat.h>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE\n#include <natus\/natus.hpp>\nusing namespace natus;\n\n#define _str(s) # s\n#define __str(s) _str(s)\n\n#define PWSIZE 1024\n#define PROMPT \">>> \"\n#define NPRMPT \"... \"\n#define HISTORYFILE \".natus_history\"\n#define error(status, num, ...) { \\\n fprintf(stderr, __VA_ARGS__); \\\n return status; \\\n}\n\nValue* glbl;\n\nstatic Value alert(Value& ths, Value& fnc, Value& args) {\n\tNATUS_CHECK_ARGUMENTS(fnc, \"s\");\n\n\tfprintf(stderr, \"%s\\n\", args[0].to<UTF8>().c_str());\n\treturn ths.newUndefined();\n}\n\nstatic Value dir(Value& ths, Value& fnc, Value& args) {\n\tValue obj = ths.getGlobal();\n\tif (args.get(\"length\").to<long>() > 0)\n\t\tobj = args[0];\n\n\tValue names = obj.enumerate();\n\tfor (long i=0 ; i < names.get(\"length\").to<long>() ; i++)\n\t\tfprintf(stderr, \"\\t%s\\n\", names[i].to<UTF8>().c_str());\n\treturn ths.newUndefined();\n}\n\nstatic bool inblock(const char *str) {\n\tchar strstart = '\\0';\n\tint cnt = 0;\n\tfor (char prv='\\0' ; *str ; prv=*str++) {\n\t\tif (strstart) {\n\t\t\tif (strstart == '\"' && *str == '\"' && prv != '\\\\')\n\t\t\t\tstrstart = '\\0';\n\t\t\telse if (strstart == '\\'' && *str == '\\'' && prv != '\\\\')\n\t\t\t\tstrstart = '\\0';\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ We are not inside a string literal\n\t\tswitch (*str) {\n\t\t\tcase '\"':\n\t\t\t\t\/\/ We're starting a double-quoted string\n\t\t\t\tstrstart = '\"';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\t\/\/ We're starting a single-quoted string\n\t\t\t\tstrstart = '\\'';\n\t\t\t\tbreak;\n\t\t\tcase '{':\n\t\t\t\t\/\/ We're starting a new block\n\t\t\t\tcnt++;\n\t\t\t\tbreak;\n\t\t\tcase '}':\n\t\t\t\t\/\/ We're ending an existing block\n\t\t\t\tcnt--;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn cnt > 0;\n}\n\nstatic vector<string> pathparser(string path) {\n\tif (path.find(':') == string::npos) {\n\t\tvector<string> tmp;\n\t\tif (path != \"\")\n\t\t\ttmp.push_back(path);\n\t\treturn tmp;\n\t}\n\n\tstring segment = path.substr(path.find_last_of(':')+1);\n\tvector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));\n\tif (segment != \"\") paths.push_back(segment);\n\treturn paths;\n}\n\nstatic char* completion_generator(const char* text, int state) {\n\tstatic set<string> names;\n\tstatic set<string>::iterator it;\n\tchar* last = (char*) strrchr(text, '.');\n\n\tif (state == 0) {\n\t\tValue obj = *glbl;\n\t\tif (last) {\n\t\t\tchar* base = new char[last-text+1];\n\t\t\tmemset(base, 0, sizeof(char) * (last-text+1));\n\t\t\tstrncpy(base, text, last-text);\n\t\t\tobj = obj.get(base);\n\t\t\tdelete[] base;\n\t\t\tif (obj.isUndefined()) return NULL;\n\t\t}\n\n\t\tValue nm = obj.enumerate();\n\t\tfor (long i=0 ; i < nm.get(\"length\").to<long>() ; i++)\n\t\t\tnames.insert(nm[i].to<UTF8>().c_str());\n\t\tit = names.begin();\n\t}\n\tif (last) last++;\n\n\tfor ( ; it != names.end() ; it++) {\n\t\tif ((last && it->find(last) == 0) || (!last && it->find(text) == 0)) {\n\t\t\tstring tmp = last ? (string(text) + (it->c_str()+strlen(last))) : *it;\n\t\t\tchar* ret = strdup(tmp.c_str());\n\t\t\tit++;\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nstatic char** completion(const char* text, int start, int end) {\n\treturn rl_completion_matches(text, completion_generator);\n}\n\nstatic Value set_path(Value& ctx, Require::HookStep step, char* name, void* misc) {\n\tif (step == Require::HookStepProcess && !strcmp(name, \"system\")) {\n\t\tValue args = ctx.get(\"args\");\n\t\tif (!args.isArray()) return NULL;\n\n\t\tconst char** argv = (const char **) misc;\n\t\tfor (int i=0 ; argv[i] ; i++)\n\t\t\targs.newArrayBuilder(argv[i]);\n\t}\n\n\treturn NULL;\n}\n\nint main(int argc, char** argv) {\n\tEngine engine;\n\tValue global;\n\tvector<string> configs;\n\tconst char *eng = NULL;\n\tconst char *eval = NULL;\n\tint c=0, exitcode=0;\n\tglbl = &global;\n\n\t\/\/ The engine argument can be embedded in a symlink\n\tif (strstr(argv[0], \"natus-\") == argv[0])\n\t\teng = strchr(argv[0], '-')+1;\n\n\t\/\/ Get the path\n\tstring path;\n\tif (getenv(\"NATUS_PATH\"))\n\t\tpath = string(getenv(\"NATUS_PATH\")) + \":\";\n\tpath += __str(MODULEDIR);\n\n\topterr = 0;\n\twhile ((c = getopt (argc, argv, \"+C:c:e:n\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 'C':\n\t\t\tconfigs.push_back(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\teval = optarg;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\teng = optarg;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tpath.clear();\n\t\t\tbreak;\n\t\tcase '?':\n\t\t\tif (optopt == 'e')\n\t\t\t\tfprintf(stderr, \"Option -%c requires an engine name.\\n\", optopt);\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"Usage: %s [-C <config>=<jsonval>|-c <javascript>|-e <engine>|-n|<scriptfile>]\\n\\n\", argv[0]);\n\t\t\t\tfprintf(stderr, \"Unknown option `-%c'.\\n\", optopt);\n\t\t\t}\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\tabort();\n\t }\n\t}\n\n\t\/\/ Initialize the engine\n\tif (!engine.initialize(eng))\n\t\terror(1, 0, \"Unable to init engine!\\n\");\n\n\t\/\/ Setup our global\n\tglobal = engine.newGlobal();\n\tif (global.isUndefined() || global.isException())\n\t\terror(2, 0, \"Unable to init global!\\n\");\n\n\t\/\/ Setup our config\n\tValue cfg = global.newObject();\n\tif (!path.empty()) {\n\t\twhile (path.find(':') != string::npos)\n\t\t\tpath = path.substr(0, path.find(':')) + \"\\\", \\\"\" + path.substr(path.find(':')+1);\n\t\tcfg.setRecursive(\"natus.require.path\", fromJSON(global, \"[\\\"\" + path + \"\\\"]\"), Value::PropAttrNone, true);\n\t}\n\tfor (vector<string>::iterator it=configs.begin() ; it != configs.end() ; it++) {\n\t\tif (access(it->c_str(), R_OK) == 0) {\n\t\t\tifstream file(it->c_str());\n\t\t\tfor (string line ; getline(file, line) ; ) {\n\t\t\t\tif (line.find('=') == string::npos) continue;\n\t\t\t\tstring key = line.substr(0, line.find('='));\n\t\t\t\tValue val = fromJSON(global, line.substr(line.find('=')+1).c_str());\n\t\t\t\tif (val.isException()) continue;\n\t\t\t\tcfg.setRecursive(key, val, Value::PropAttrNone, true);\n\t\t\t}\n\t\t\tfile.close();\n\t\t} else if (it->find(\"=\") != string::npos) {\n\t\t\tstring key = it->substr(0, it->find('='));\n\t\t\tValue val = fromJSON(global, it->substr(it->find('=')+1));\n\t\t\tif (val.isException()) continue;\n\t\t\tcfg.setRecursive(key, val, Value::PropAttrNone, true);\n\t\t}\n\t}\n\n\t\/\/ Bring up the Module Loader\n\tRequire req(global);\n\tif (!req.initialize(cfg))\n\t\terror(3, 0, \"Unable to init module loader\\n!\");\n\n\t\/\/ Export some basic functions\n\tglobal.set(\"alert\", global.newFunction(alert));\n\tglobal.set(\"dir\", global.newFunction(dir));\n\n\t\/\/ Do the evaluation\n\tif (eval) {\n\t\tValue res = global.evaluate(eval);\n\n\t\t\/\/ Print uncaught exceptions\n\t\tif (res.isException())\n\t\t\terror(8, 0, \"Uncaught Exception: %s\", res.to<UTF8>().c_str());\n\n\t\t\/\/ Let the script return exitcodes\n\t\tif (res.isNumber())\n\t\t\texitcode = (int) res.to<long>();\n\n\t\treturn exitcode;\n\t}\n\n\t\/\/ Start the shell\n\tif (optind >= argc) {\n\t\tfprintf(stderr, \"Natus v\" PACKAGE_VERSION \" - Using: %s\\n\", engine.getName());\n\t\tif (getenv(\"HOME\"))\n\t\t\tread_history((string(getenv(\"HOME\")) + \"\/\" + HISTORYFILE).c_str());\n\t\trl_readline_name = (char*) \"natus\";\n\t\trl_attempted_completion_function = completion;\n\t\tread_history(HISTORYFILE);\n\n\t\tchar* line;\n\t\tconst char* prompt = PROMPT;\n\t\tstring prev = \"\";\n\n\t\tlong lcnt = 0;\n\t\tfor (line=readline(prompt) ; line ; line=readline(prompt)) {\n\t\t\t\/\/ Strip the line\n\t\t\tstring l = line;\n\t\t\tfree(line);\n\t\t\tstring::size_type start = l.find_first_not_of(\" \\t\");\n\t\t\tl = start == string::npos ? string(\"\") : l.substr(start, l.find_last_not_of(\" \\t\")-start+1);\n\t\t\tif (l == \"\") continue;\n\n\t\t\t\/\/ Append the line to the buffer\n\t\t\tprev.append(l);\n\n\t\t\t\/\/ Continue to the next line\n\t\t if (inblock(prev.c_str())) {\n\t\t \tprompt = NPRMPT;\n\t\t \tcontinue;\n\t\t }\n\t\t prompt = PROMPT;\n\t\t\tadd_history(prev.c_str());\n\n\t\t\tValue res = global.evaluate(prev.c_str(), \"\", lcnt++);\n\t\t\tstring fmt;\n\t\t\tif (res.isException()) {\n\t\t\t\tfmt = \"Uncaught Exception: %s\\n\";\n\t\t\t\tif (prev == \"exit\" || prev == \"quit\") {\n\t\t\t\t\tres = res.newUndefined();\n\t\t\t\t\tfprintf(stderr, \"Use Ctrl-D (i.e. EOF) to exit\\n\");\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tfmt = \"%s\\n\";\n\n\t\t\tif (!res.isUndefined() && !res.isNull())\n\t\t\t\tfprintf(stderr, fmt.c_str(), res.to<UTF8>().c_str());\n\t\t\tprev = \"\";\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tif (getenv(\"HOME\"))\n\t\t\twrite_history((string(getenv(\"HOME\")) + \"\/\" + HISTORYFILE).c_str());\n\t\treturn 0;\n\t}\n\n\t\/\/ Get the script filename\n\tchar *filename = argv[optind];\n\n\t\/\/ Stat our file\n\tstruct stat st;\n\tif (stat(filename, &st))\n\t\terror(3, 0, \"Script file does not exist: %s\\n\", filename);\n\n\t\/\/ Read in our script file\n\tFILE *file = fopen(filename, \"r\");\n\tif (!file)\n\t\terror(4, 0, \"Unable to open file: %s\\n\", filename);\n\tchar *jscript = new char[st.st_size + 1];\n\tif (!jscript) {\n\t\tfclose(file);\n\t\terror(5, 0, \"Out of memory!\\n\");\n\t}\n\tif ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {\n\t\tdelete[] jscript;\n\t\tfclose(file);\n\t\terror(6, 0, \"Error reading file: %s\\n\", filename);\n\t}\n\tfclose(file);\n\tjscript[st.st_size] = '\\0';\n\n\t\/\/ Evaluate it\n\treq.addHook(\"system_args\", set_path, argv+optind);\n\tValue res = global.evaluate(jscript, filename ? filename : \"\");\n\tdelete[] jscript;\n\n\t\/\/ Print uncaught exceptions\n\tif (res.isException())\n\t\terror(8, 0, \"Uncaught Exception: %s\\n\", res.to<UTF8>().c_str());\n\n\t\/\/ Let the script return exitcodes\n\tif (res.isNumber())\n\t\texitcode = (int) res.to<long>();\n\n\treturn exitcode;\n}\n<commit_msg>add error messages; add error checking<commit_after>\/*\n * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n * \n *\/\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <set>\n#include <vector>\n#include <string>\nusing namespace std;\n\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <sys\/stat.h>\n\n#include <readline\/readline.h>\n#include <readline\/history.h>\n\n#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE\n#include <natus\/natus.hpp>\nusing namespace natus;\n\n#define _str(s) # s\n#define __str(s) _str(s)\n\n#define PWSIZE 1024\n#define PROMPT \">>> \"\n#define NPRMPT \"... \"\n#define HISTORYFILE \".natus_history\"\n#define error(status, num, ...) { \\\n fprintf(stderr, __VA_ARGS__); \\\n return status; \\\n}\n\nValue* glbl;\n\nstatic Value alert(Value& ths, Value& fnc, Value& args) {\n\tNATUS_CHECK_ARGUMENTS(fnc, \"s\");\n\n\tfprintf(stderr, \"%s\\n\", args[0].to<UTF8>().c_str());\n\treturn ths.newUndefined();\n}\n\nstatic Value dir(Value& ths, Value& fnc, Value& args) {\n\tValue obj = ths.getGlobal();\n\tif (args.get(\"length\").to<long>() > 0)\n\t\tobj = args[0];\n\n\tValue names = obj.enumerate();\n\tfor (long i=0 ; i < names.get(\"length\").to<long>() ; i++)\n\t\tfprintf(stderr, \"\\t%s\\n\", names[i].to<UTF8>().c_str());\n\treturn ths.newUndefined();\n}\n\nstatic bool inblock(const char *str) {\n\tchar strstart = '\\0';\n\tint cnt = 0;\n\tfor (char prv='\\0' ; *str ; prv=*str++) {\n\t\tif (strstart) {\n\t\t\tif (strstart == '\"' && *str == '\"' && prv != '\\\\')\n\t\t\t\tstrstart = '\\0';\n\t\t\telse if (strstart == '\\'' && *str == '\\'' && prv != '\\\\')\n\t\t\t\tstrstart = '\\0';\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ We are not inside a string literal\n\t\tswitch (*str) {\n\t\t\tcase '\"':\n\t\t\t\t\/\/ We're starting a double-quoted string\n\t\t\t\tstrstart = '\"';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\t\/\/ We're starting a single-quoted string\n\t\t\t\tstrstart = '\\'';\n\t\t\t\tbreak;\n\t\t\tcase '{':\n\t\t\t\t\/\/ We're starting a new block\n\t\t\t\tcnt++;\n\t\t\t\tbreak;\n\t\t\tcase '}':\n\t\t\t\t\/\/ We're ending an existing block\n\t\t\t\tcnt--;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn cnt > 0;\n}\n\nstatic vector<string> pathparser(string path) {\n\tif (path.find(':') == string::npos) {\n\t\tvector<string> tmp;\n\t\tif (path != \"\")\n\t\t\ttmp.push_back(path);\n\t\treturn tmp;\n\t}\n\n\tstring segment = path.substr(path.find_last_of(':')+1);\n\tvector<string> paths = pathparser(path.substr(0, path.find_last_of(':')));\n\tif (segment != \"\") paths.push_back(segment);\n\treturn paths;\n}\n\nstatic char* completion_generator(const char* text, int state) {\n\tstatic set<string> names;\n\tstatic set<string>::iterator it;\n\tchar* last = (char*) strrchr(text, '.');\n\n\tif (state == 0) {\n\t\tValue obj = *glbl;\n\t\tif (last) {\n\t\t\tchar* base = new char[last-text+1];\n\t\t\tmemset(base, 0, sizeof(char) * (last-text+1));\n\t\t\tstrncpy(base, text, last-text);\n\t\t\tobj = obj.get(base);\n\t\t\tdelete[] base;\n\t\t\tif (obj.isUndefined()) return NULL;\n\t\t}\n\n\t\tValue nm = obj.enumerate();\n\t\tfor (long i=0 ; i < nm.get(\"length\").to<long>() ; i++)\n\t\t\tnames.insert(nm[i].to<UTF8>().c_str());\n\t\tit = names.begin();\n\t}\n\tif (last) last++;\n\n\tfor ( ; it != names.end() ; it++) {\n\t\tif ((last && it->find(last) == 0) || (!last && it->find(text) == 0)) {\n\t\t\tstring tmp = last ? (string(text) + (it->c_str()+strlen(last))) : *it;\n\t\t\tchar* ret = strdup(tmp.c_str());\n\t\t\tit++;\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nstatic char** completion(const char* text, int start, int end) {\n\treturn rl_completion_matches(text, completion_generator);\n}\n\nstatic Value set_path(Value& ctx, Require::HookStep step, char* name, void* misc) {\n\tif (step == Require::HookStepProcess && !strcmp(name, \"system\")) {\n\t\tValue args = ctx.get(\"args\");\n\t\tif (!args.isArray()) return NULL;\n\n\t\tconst char** argv = (const char **) misc;\n\t\tfor (int i=0 ; argv[i] ; i++)\n\t\t\targs.newArrayBuilder(argv[i]);\n\t}\n\n\treturn NULL;\n}\n\nint main(int argc, char** argv) {\n\tEngine engine;\n\tValue global;\n\tvector<string> configs;\n\tconst char *eng = NULL;\n\tconst char *eval = NULL;\n\tint c=0, exitcode=0;\n\tglbl = &global;\n\n\t\/\/ The engine argument can be embedded in a symlink\n\tif (strstr(argv[0], \"natus-\") == argv[0])\n\t\teng = strchr(argv[0], '-')+1;\n\n\t\/\/ Get the path\n\tstring path;\n\tif (getenv(\"NATUS_PATH\"))\n\t\tpath = string(getenv(\"NATUS_PATH\")) + \":\";\n\tpath += __str(MODULEDIR);\n\n\topterr = 0;\n\twhile ((c = getopt (argc, argv, \"+C:c:e:n\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 'C':\n\t\t\tconfigs.push_back(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\teval = optarg;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\teng = optarg;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tpath.clear();\n\t\t\tbreak;\n\t\tcase '?':\n\t\t\tif (optopt == 'e')\n\t\t\t\tfprintf(stderr, \"Option -%c requires an engine name.\\n\", optopt);\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"Usage: %s [-C <config>=<jsonval>|-c <javascript>|-e <engine>|-n|<scriptfile>]\\n\\n\", argv[0]);\n\t\t\t\tfprintf(stderr, \"Unknown option `-%c'.\\n\", optopt);\n\t\t\t}\n\t\t\treturn 1;\n\t\tdefault:\n\t\t\tabort();\n\t }\n\t}\n\n\t\/\/ Initialize the engine\n\tif (!engine.initialize(eng))\n\t\terror(1, 0, \"Unable to init engine!\\n\");\n\n\t\/\/ Setup our global\n\tglobal = engine.newGlobal();\n\tif (global.isUndefined() || global.isException())\n\t\terror(2, 0, \"Unable to init global!\\n\");\n\n\t\/\/ Setup our config\n\tValue cfg = global.newObject();\n\tif (!path.empty()) {\n\t\twhile (path.find(':') != string::npos)\n\t\t\tpath = path.substr(0, path.find(':')) + \"\\\", \\\"\" + path.substr(path.find(':')+1);\n\t\tassert(!cfg.setRecursive(\"natus.require.path\", fromJSON(global, \"[\\\"\" + path + \"\\\"]\"), Value::PropAttrNone, true).isException());\n\t}\n\tfor (vector<string>::iterator it=configs.begin() ; it != configs.end() ; it++) {\n\t\tif (access(it->c_str(), R_OK) == 0) {\n\t\t\tifstream file(it->c_str());\n\t\t\tfor (string line ; getline(file, line) ; ) {\n\t\t\t\tif (line.find('=') == string::npos) continue;\n\t\t\t\tstring key = line.substr(0, line.find('='));\n\t\t\t\tValue val = fromJSON(global, line.substr(line.find('=')+1).c_str());\n\t\t\t\tif (val.isException()) {\n\t\t\t\t\tfprintf(stderr, \"An error occurred in file '%s'\\n\", it->c_str());\n\t\t\t\t\tfprintf(stderr, \"\\tline: %s\\n\", line.c_str());\n\t\t\t\t\tfprintf(stderr, \"\\t%s\\n\", val.to<UTF8>().c_str());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tassert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());\n\t\t\t}\n\t\t\tfile.close();\n\t\t} else if (it->find(\"=\") != string::npos) {\n\t\t\tstring key = it->substr(0, it->find('='));\n\t\t\tValue val = fromJSON(global, it->substr(it->find('=')+1));\n\t\t\tif (val.isException()) {\n\t\t\t\tfprintf(stderr, \"An error occurred on '%s'\\n\", it->c_str());\n\t\t\t\tfprintf(stderr, \"\\t%s\\n\", val.to<UTF8>().c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tassert(!cfg.setRecursive(key, val, Value::PropAttrNone, true).isException());\n\t\t}\n\t}\n\n\t\/\/ Bring up the Module Loader\n\tRequire req(global);\n\tif (!req.initialize(cfg))\n\t\terror(3, 0, \"Unable to init module loader\\n!\");\n\n\t\/\/ Export some basic functions\n\tglobal.set(\"alert\", global.newFunction(alert));\n\tglobal.set(\"dir\", global.newFunction(dir));\n\n\t\/\/ Do the evaluation\n\tif (eval) {\n\t\tValue res = global.evaluate(eval);\n\n\t\t\/\/ Print uncaught exceptions\n\t\tif (res.isException())\n\t\t\terror(8, 0, \"Uncaught Exception: %s\", res.to<UTF8>().c_str());\n\n\t\t\/\/ Let the script return exitcodes\n\t\tif (res.isNumber())\n\t\t\texitcode = (int) res.to<long>();\n\n\t\treturn exitcode;\n\t}\n\n\t\/\/ Start the shell\n\tif (optind >= argc) {\n\t\tfprintf(stderr, \"Natus v\" PACKAGE_VERSION \" - Using: %s\\n\", engine.getName());\n\t\tif (getenv(\"HOME\"))\n\t\t\tread_history((string(getenv(\"HOME\")) + \"\/\" + HISTORYFILE).c_str());\n\t\trl_readline_name = (char*) \"natus\";\n\t\trl_attempted_completion_function = completion;\n\t\tread_history(HISTORYFILE);\n\n\t\tchar* line;\n\t\tconst char* prompt = PROMPT;\n\t\tstring prev = \"\";\n\n\t\tlong lcnt = 0;\n\t\tfor (line=readline(prompt) ; line ; line=readline(prompt)) {\n\t\t\t\/\/ Strip the line\n\t\t\tstring l = line;\n\t\t\tfree(line);\n\t\t\tstring::size_type start = l.find_first_not_of(\" \\t\");\n\t\t\tl = start == string::npos ? string(\"\") : l.substr(start, l.find_last_not_of(\" \\t\")-start+1);\n\t\t\tif (l == \"\") continue;\n\n\t\t\t\/\/ Append the line to the buffer\n\t\t\tprev.append(l);\n\n\t\t\t\/\/ Continue to the next line\n\t\t if (inblock(prev.c_str())) {\n\t\t \tprompt = NPRMPT;\n\t\t \tcontinue;\n\t\t }\n\t\t prompt = PROMPT;\n\t\t\tadd_history(prev.c_str());\n\n\t\t\tValue res = global.evaluate(prev.c_str(), \"\", lcnt++);\n\t\t\tstring fmt;\n\t\t\tif (res.isException()) {\n\t\t\t\tfmt = \"Uncaught Exception: %s\\n\";\n\t\t\t\tif (prev == \"exit\" || prev == \"quit\") {\n\t\t\t\t\tres = res.newUndefined();\n\t\t\t\t\tfprintf(stderr, \"Use Ctrl-D (i.e. EOF) to exit\\n\");\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tfmt = \"%s\\n\";\n\n\t\t\tif (!res.isUndefined() && !res.isNull())\n\t\t\t\tfprintf(stderr, fmt.c_str(), res.to<UTF8>().c_str());\n\t\t\tprev = \"\";\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tif (getenv(\"HOME\"))\n\t\t\twrite_history((string(getenv(\"HOME\")) + \"\/\" + HISTORYFILE).c_str());\n\t\treturn 0;\n\t}\n\n\t\/\/ Get the script filename\n\tchar *filename = argv[optind];\n\n\t\/\/ Stat our file\n\tstruct stat st;\n\tif (stat(filename, &st))\n\t\terror(3, 0, \"Script file does not exist: %s\\n\", filename);\n\n\t\/\/ Read in our script file\n\tFILE *file = fopen(filename, \"r\");\n\tif (!file)\n\t\terror(4, 0, \"Unable to open file: %s\\n\", filename);\n\tchar *jscript = new char[st.st_size + 1];\n\tif (!jscript) {\n\t\tfclose(file);\n\t\terror(5, 0, \"Out of memory!\\n\");\n\t}\n\tif ((size_t) fread(jscript, 1, st.st_size, file) != (size_t) st.st_size) {\n\t\tdelete[] jscript;\n\t\tfclose(file);\n\t\terror(6, 0, \"Error reading file: %s\\n\", filename);\n\t}\n\tfclose(file);\n\tjscript[st.st_size] = '\\0';\n\n\t\/\/ Evaluate it\n\treq.addHook(\"system_args\", set_path, argv+optind);\n\tValue res = global.evaluate(jscript, filename ? filename : \"\");\n\tdelete[] jscript;\n\n\t\/\/ Print uncaught exceptions\n\tif (res.isException())\n\t\terror(8, 0, \"Uncaught Exception: %s\\n\", res.to<UTF8>().c_str());\n\n\t\/\/ Let the script return exitcodes\n\tif (res.isNumber())\n\t\texitcode = (int) res.to<long>();\n\n\treturn exitcode;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"mojo\/edk\/system\/message_in_transit.h\"\n\n#include <string.h>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"mojo\/edk\/system\/configuration.h\"\n#include \"mojo\/edk\/system\/transport_data.h\"\n\nnamespace mojo {\nnamespace system {\n\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeMessagePipeEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeMessagePipe;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeChannel;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeRawChannel;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeMessagePipeEndpointData;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelAttachAndRunEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelRemoveMessagePipeEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelRemoveMessagePipeEndpointAck;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeRawChannelPosixExtraPlatformHandles;\nSTATIC_CONST_MEMBER_DEFINITION const size_t MessageInTransit::kMessageAlignment;\n\nstruct MessageInTransit::PrivateStructForCompileAsserts {\n \/\/ The size of |Header| must be a multiple of the alignment.\n static_assert(sizeof(Header) % kMessageAlignment == 0,\n \"sizeof(MessageInTransit::Header) invalid\");\n};\n\nMessageInTransit::View::View(size_t message_size, const void* buffer)\n : buffer_(buffer) {\n size_t next_message_size = 0;\n DCHECK(MessageInTransit::GetNextMessageSize(buffer_, message_size,\n &next_message_size));\n DCHECK_EQ(message_size, next_message_size);\n \/\/ This should be equivalent.\n DCHECK_EQ(message_size, total_size());\n}\n\nbool MessageInTransit::View::IsValid(size_t serialized_platform_handle_size,\n const char** error_message) const {\n size_t max_message_num_bytes = GetConfiguration().max_message_num_bytes;\n \/\/ Avoid dangerous situations, but making sure that the size of the \"header\" +\n \/\/ the size of the data fits into a 31-bit number.\n DCHECK_LE(static_cast<uint64_t>(sizeof(Header)) + max_message_num_bytes,\n 0x7fffffffULL)\n << \"GetConfiguration().max_message_num_bytes too big\";\n\n \/\/ We assume (to avoid extra rounding code) that the maximum message (data)\n \/\/ size is a multiple of the alignment.\n DCHECK_EQ(max_message_num_bytes % kMessageAlignment, 0U)\n << \"GetConfiguration().max_message_num_bytes not a multiple of alignment\";\n\n \/\/ Note: This also implies a check on the |main_buffer_size()|, which is just\n \/\/ |RoundUpMessageAlignment(sizeof(Header) + num_bytes())|.\n if (num_bytes() > max_message_num_bytes) {\n *error_message = \"Message data payload too large\";\n return false;\n }\n\n if (transport_data_buffer_size() > 0) {\n const char* e = TransportData::ValidateBuffer(\n serialized_platform_handle_size, transport_data_buffer(),\n transport_data_buffer_size());\n if (e) {\n *error_message = e;\n return false;\n }\n }\n\n return true;\n}\n\nMessageInTransit::MessageInTransit(Type type,\n Subtype subtype,\n uint32_t num_bytes,\n const void* bytes)\n : main_buffer_size_(RoundUpMessageAlignment(sizeof(Header) + num_bytes)),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n ConstructorHelper(type, subtype, num_bytes);\n if (bytes) {\n memcpy(MessageInTransit::bytes(), bytes, num_bytes);\n memset(static_cast<char*>(MessageInTransit::bytes()) + num_bytes, 0,\n main_buffer_size_ - sizeof(Header) - num_bytes);\n } else {\n memset(MessageInTransit::bytes(), 0, main_buffer_size_ - sizeof(Header));\n }\n}\n\nMessageInTransit::MessageInTransit(Type type,\n Subtype subtype,\n uint32_t num_bytes,\n UserPointer<const void> bytes)\n : main_buffer_size_(RoundUpMessageAlignment(sizeof(Header) + num_bytes)),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n ConstructorHelper(type, subtype, num_bytes);\n bytes.GetArray(MessageInTransit::bytes(), num_bytes);\n}\n\nMessageInTransit::MessageInTransit(const View& message_view)\n : main_buffer_size_(message_view.main_buffer_size()),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n DCHECK_GE(main_buffer_size_, sizeof(Header));\n DCHECK_EQ(main_buffer_size_ % kMessageAlignment, 0u);\n\n memcpy(main_buffer_.get(), message_view.main_buffer(), main_buffer_size_);\n DCHECK_EQ(main_buffer_size_,\n RoundUpMessageAlignment(sizeof(Header) + num_bytes()));\n}\n\nMessageInTransit::~MessageInTransit() {\n if (dispatchers_) {\n for (size_t i = 0; i < dispatchers_->size(); i++) {\n if (!(*dispatchers_)[i].get())\n continue;\n\n DCHECK((*dispatchers_)[i]->HasOneRef());\n (*dispatchers_)[i]->Close();\n }\n }\n}\n\n\/\/ static\nbool MessageInTransit::GetNextMessageSize(const void* buffer,\n size_t buffer_size,\n size_t* next_message_size) {\n DCHECK(next_message_size);\n if (!buffer_size)\n return false;\n DCHECK(buffer);\n DCHECK_EQ(\n reinterpret_cast<uintptr_t>(buffer) % MessageInTransit::kMessageAlignment,\n 0u);\n\n if (buffer_size < sizeof(Header))\n return false;\n\n const Header* header = static_cast<const Header*>(buffer);\n *next_message_size = header->total_size;\n DCHECK_EQ(*next_message_size % kMessageAlignment, 0u);\n return true;\n}\n\nvoid MessageInTransit::SetDispatchers(\n scoped_ptr<DispatcherVector> dispatchers) {\n DCHECK(dispatchers);\n DCHECK(!dispatchers_);\n DCHECK(!transport_data_);\n\n dispatchers_ = dispatchers.Pass();\n#ifndef NDEBUG\n for (size_t i = 0; i < dispatchers_->size(); i++)\n DCHECK(!(*dispatchers_)[i].get() || (*dispatchers_)[i]->HasOneRef());\n#endif\n}\n\nvoid MessageInTransit::SetTransportData(\n scoped_ptr<TransportData> transport_data) {\n DCHECK(transport_data);\n DCHECK(!transport_data_);\n DCHECK(!dispatchers_);\n\n transport_data_ = transport_data.Pass();\n}\n\nvoid MessageInTransit::SerializeAndCloseDispatchers(Channel* channel) {\n DCHECK(channel);\n DCHECK(!transport_data_);\n\n if (!dispatchers_ || !dispatchers_->size())\n return;\n\n transport_data_.reset(new TransportData(dispatchers_.Pass(), channel));\n\n \/\/ Update the sizes in the message header.\n UpdateTotalSize();\n}\n\nvoid MessageInTransit::ConstructorHelper(Type type,\n Subtype subtype,\n uint32_t num_bytes) {\n DCHECK_LE(num_bytes, GetConfiguration().max_message_num_bytes);\n\n \/\/ |total_size| is updated below, from the other values.\n header()->type = type;\n header()->subtype = subtype;\n header()->source_id = ChannelEndpointId();\n header()->destination_id = ChannelEndpointId();\n header()->num_bytes = num_bytes;\n header()->unused = 0;\n \/\/ Note: If dispatchers are subsequently attached, then |total_size| will have\n \/\/ to be adjusted.\n UpdateTotalSize();\n}\n\nvoid MessageInTransit::UpdateTotalSize() {\n DCHECK_EQ(main_buffer_size_ % kMessageAlignment, 0u);\n header()->total_size = static_cast<uint32_t>(main_buffer_size_);\n if (transport_data_) {\n header()->total_size +=\n static_cast<uint32_t>(transport_data_->buffer_size());\n }\n}\n\n} \/\/ namespace system\n} \/\/ namespace mojo\n<commit_msg>Revert \"Revert \"MessageInTransit: Fill padding bytes with zero.\"\"<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"mojo\/edk\/system\/message_in_transit.h\"\n\n#include <string.h>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"mojo\/edk\/system\/configuration.h\"\n#include \"mojo\/edk\/system\/transport_data.h\"\n\nnamespace mojo {\nnamespace system {\n\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeMessagePipeEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeMessagePipe;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeChannel;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Type\n MessageInTransit::kTypeRawChannel;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeMessagePipeEndpointData;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelAttachAndRunEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelRemoveMessagePipeEndpoint;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeChannelRemoveMessagePipeEndpointAck;\nSTATIC_CONST_MEMBER_DEFINITION const MessageInTransit::Subtype\n MessageInTransit::kSubtypeRawChannelPosixExtraPlatformHandles;\nSTATIC_CONST_MEMBER_DEFINITION const size_t MessageInTransit::kMessageAlignment;\n\nstruct MessageInTransit::PrivateStructForCompileAsserts {\n \/\/ The size of |Header| must be a multiple of the alignment.\n static_assert(sizeof(Header) % kMessageAlignment == 0,\n \"sizeof(MessageInTransit::Header) invalid\");\n};\n\nMessageInTransit::View::View(size_t message_size, const void* buffer)\n : buffer_(buffer) {\n size_t next_message_size = 0;\n DCHECK(MessageInTransit::GetNextMessageSize(buffer_, message_size,\n &next_message_size));\n DCHECK_EQ(message_size, next_message_size);\n \/\/ This should be equivalent.\n DCHECK_EQ(message_size, total_size());\n}\n\nbool MessageInTransit::View::IsValid(size_t serialized_platform_handle_size,\n const char** error_message) const {\n size_t max_message_num_bytes = GetConfiguration().max_message_num_bytes;\n \/\/ Avoid dangerous situations, but making sure that the size of the \"header\" +\n \/\/ the size of the data fits into a 31-bit number.\n DCHECK_LE(static_cast<uint64_t>(sizeof(Header)) + max_message_num_bytes,\n 0x7fffffffULL)\n << \"GetConfiguration().max_message_num_bytes too big\";\n\n \/\/ We assume (to avoid extra rounding code) that the maximum message (data)\n \/\/ size is a multiple of the alignment.\n DCHECK_EQ(max_message_num_bytes % kMessageAlignment, 0U)\n << \"GetConfiguration().max_message_num_bytes not a multiple of alignment\";\n\n \/\/ Note: This also implies a check on the |main_buffer_size()|, which is just\n \/\/ |RoundUpMessageAlignment(sizeof(Header) + num_bytes())|.\n if (num_bytes() > max_message_num_bytes) {\n *error_message = \"Message data payload too large\";\n return false;\n }\n\n if (transport_data_buffer_size() > 0) {\n const char* e = TransportData::ValidateBuffer(\n serialized_platform_handle_size, transport_data_buffer(),\n transport_data_buffer_size());\n if (e) {\n *error_message = e;\n return false;\n }\n }\n\n return true;\n}\n\nMessageInTransit::MessageInTransit(Type type,\n Subtype subtype,\n uint32_t num_bytes,\n const void* bytes)\n : main_buffer_size_(RoundUpMessageAlignment(sizeof(Header) + num_bytes)),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n ConstructorHelper(type, subtype, num_bytes);\n if (bytes) {\n memcpy(MessageInTransit::bytes(), bytes, num_bytes);\n memset(static_cast<char*>(MessageInTransit::bytes()) + num_bytes, 0,\n main_buffer_size_ - sizeof(Header) - num_bytes);\n } else {\n memset(MessageInTransit::bytes(), 0, main_buffer_size_ - sizeof(Header));\n }\n}\n\nMessageInTransit::MessageInTransit(Type type,\n Subtype subtype,\n uint32_t num_bytes,\n UserPointer<const void> bytes)\n : main_buffer_size_(RoundUpMessageAlignment(sizeof(Header) + num_bytes)),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n ConstructorHelper(type, subtype, num_bytes);\n bytes.GetArray(MessageInTransit::bytes(), num_bytes);\n memset(static_cast<char*>(MessageInTransit::bytes()) + num_bytes, 0,\n main_buffer_size_ - sizeof(Header) - num_bytes);\n}\n\nMessageInTransit::MessageInTransit(const View& message_view)\n : main_buffer_size_(message_view.main_buffer_size()),\n main_buffer_(static_cast<char*>(\n base::AlignedAlloc(main_buffer_size_, kMessageAlignment))) {\n DCHECK_GE(main_buffer_size_, sizeof(Header));\n DCHECK_EQ(main_buffer_size_ % kMessageAlignment, 0u);\n\n memcpy(main_buffer_.get(), message_view.main_buffer(), main_buffer_size_);\n DCHECK_EQ(main_buffer_size_,\n RoundUpMessageAlignment(sizeof(Header) + num_bytes()));\n}\n\nMessageInTransit::~MessageInTransit() {\n if (dispatchers_) {\n for (size_t i = 0; i < dispatchers_->size(); i++) {\n if (!(*dispatchers_)[i].get())\n continue;\n\n DCHECK((*dispatchers_)[i]->HasOneRef());\n (*dispatchers_)[i]->Close();\n }\n }\n}\n\n\/\/ static\nbool MessageInTransit::GetNextMessageSize(const void* buffer,\n size_t buffer_size,\n size_t* next_message_size) {\n DCHECK(next_message_size);\n if (!buffer_size)\n return false;\n DCHECK(buffer);\n DCHECK_EQ(\n reinterpret_cast<uintptr_t>(buffer) % MessageInTransit::kMessageAlignment,\n 0u);\n\n if (buffer_size < sizeof(Header))\n return false;\n\n const Header* header = static_cast<const Header*>(buffer);\n *next_message_size = header->total_size;\n DCHECK_EQ(*next_message_size % kMessageAlignment, 0u);\n return true;\n}\n\nvoid MessageInTransit::SetDispatchers(\n scoped_ptr<DispatcherVector> dispatchers) {\n DCHECK(dispatchers);\n DCHECK(!dispatchers_);\n DCHECK(!transport_data_);\n\n dispatchers_ = dispatchers.Pass();\n#ifndef NDEBUG\n for (size_t i = 0; i < dispatchers_->size(); i++)\n DCHECK(!(*dispatchers_)[i].get() || (*dispatchers_)[i]->HasOneRef());\n#endif\n}\n\nvoid MessageInTransit::SetTransportData(\n scoped_ptr<TransportData> transport_data) {\n DCHECK(transport_data);\n DCHECK(!transport_data_);\n DCHECK(!dispatchers_);\n\n transport_data_ = transport_data.Pass();\n}\n\nvoid MessageInTransit::SerializeAndCloseDispatchers(Channel* channel) {\n DCHECK(channel);\n DCHECK(!transport_data_);\n\n if (!dispatchers_ || !dispatchers_->size())\n return;\n\n transport_data_.reset(new TransportData(dispatchers_.Pass(), channel));\n\n \/\/ Update the sizes in the message header.\n UpdateTotalSize();\n}\n\nvoid MessageInTransit::ConstructorHelper(Type type,\n Subtype subtype,\n uint32_t num_bytes) {\n DCHECK_LE(num_bytes, GetConfiguration().max_message_num_bytes);\n\n \/\/ |total_size| is updated below, from the other values.\n header()->type = type;\n header()->subtype = subtype;\n header()->source_id = ChannelEndpointId();\n header()->destination_id = ChannelEndpointId();\n header()->num_bytes = num_bytes;\n header()->unused = 0;\n \/\/ Note: If dispatchers are subsequently attached, then |total_size| will have\n \/\/ to be adjusted.\n UpdateTotalSize();\n}\n\nvoid MessageInTransit::UpdateTotalSize() {\n DCHECK_EQ(main_buffer_size_ % kMessageAlignment, 0u);\n header()->total_size = static_cast<uint32_t>(main_buffer_size_);\n if (transport_data_) {\n header()->total_size +=\n static_cast<uint32_t>(transport_data_->buffer_size());\n }\n}\n\n} \/\/ namespace system\n} \/\/ namespace mojo\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <string>\n#include <cctype>\n\n#include \"..\/interp.hxx\"\n#include \"..\/command.hxx\"\n#include \"..\/argument.hxx\"\n#include \"basic_parsers.hxx\"\n\nusing namespace std;\n\nnamespace tglng {\n \/* Magic case conversion is performed as a two-pass process.\n *\n * The first pass examines the input string and determines hinting properties\n * from it (ie, what cases or separators are present).\n *\n * The second transforms the string by repeadedly executing a function for\n * each character, given the hint. This function may also alter what function\n * is executed for the next character.\n *\/\n\n \/* Indicates that one or more lowercase characters are present in the input\n * string.\n *\/\n#define HINT_LC (1<<0)\n \/* Indicates that one or more uppercase characters are present in the input\n * string.\n *\/\n#define HINT_UC (1<<1)\n \/* Indicates that both upper and lowercase characters are present in the\n * input string. This is automatically set if both LC and UC are set.\n *\/\n#define HINT_MC (1<<2)\n \/* Indicates that space-like delimiters (space characters, hyphens, or\n * underscores) are present in the input string.\n *\/\n#define HINT_SEP (1<<4)\n\n \/* Wrapper struct since it is otherwise impossible to define a function which\n * takes itself as a parm.\n *\/\n struct Converter {\n \/**\n * Performs conversion of a single character.\n *\n * @param ch The single-character string to convert.\n * @param hint A bitwise OR of any number of the HINT constants.\n * @param next The next function to use, by default the one being called.\n * @return The transformed character.\n *\/\n typedef void (*f_t)(wstring& ch, unsigned hint, Converter& next);\n f_t f;\n };\n\n typedef wint_t (*case_t)(wint_t);\n\n static int isseparator(wint_t ch) {\n return iswspace(ch) || ch == L'_' || ch == L'-';\n }\n\n \/* Basic to-uppercase or to-lower converter. *\/\n namespace { \/* Since templates can't take functions with static linkage (?) *\/\n template<case_t F>\n void simpleConverter(wstring& ch, unsigned, Converter&) {\n ch[0] = F(ch[0]);\n }\n }\n\n \/* Common functions for converting to delimited-word and mixed-case formats.\n *\n * If separators exist in the input string, they define the word boundaries\n * and may be replaced by the expected delimiter (see ReplaceSeparators);\n * other word characters are normalised according to WordInit and WordRest.\n *\n * If no separators exist, an uppercase character following a lowercase\n * character is considered a word boundary, and will cause a delimiter to be\n * inserted between the two.\n *\n * Digits after any character will start a word, and any alpha after a digit\n * will as well.\n *\n * A Delimiter of NUL means nothing.\n *\/\n template<wchar_t Delimiter, bool ReplaceSeparators,\n case_t TokenInit, case_t WordInit, case_t WordRest>\n class delimitedConverter {\n template<bool StartToken, bool StartWord,\n bool PUChar, bool PLChar, bool PDigit>\n static void main(wstring& ch, unsigned hint, Converter& next) {\n bool wasU = iswupper(ch[0]),\n wasD = iswdigit(ch[0]);\n if (wasD || iswalpha(ch[0])) {\n if (StartToken) {\n ch[0] = TokenInit(ch[0]);\n } else if ((PLChar && (wasU || wasD) && !(hint & HINT_SEP)) ||\n (PDigit && !wasD && !(hint & HINT_SEP)) ||\n StartWord) {\n \/\/New word\n ch[0] = WordInit(ch[0]);\n if (Delimiter && !StartWord)\n \/\/Insert our own word start\n ch.insert(0, 1, Delimiter);\n } else {\n \/\/Other word char\n ch[0] = WordRest(ch[0]);\n }\n\n if (wasU)\n next.f = main<false,false,true,false,false>;\n else if (wasD)\n next.f = main<false,false,false,true,false>;\n else\n \/\/If there are any letters which are neither upper nor lower,\n \/\/consider them lower.\n next.f = main<false,false,false,true,false>;\n } else if (isseparator(ch[0])) {\n if (ReplaceSeparators) {\n if (Delimiter && !StartToken && !StartWord)\n ch[0] = Delimiter;\n else if (Delimiter == 0)\n \/\/NUL delimiter, remove the separator\n ch.clear();\n\n \/\/Next char is word start unless this was a token start\n next.f = main<StartToken,!StartToken,false,false,false>;\n }\n } else {\n \/\/Non-word non-separator\n \/\/Next one is the start of a new token\n next.f = main<true,false,false,false,false>;\n }\n }\n\n public:\n static void f(wstring& ch, unsigned hint, Converter& next) {\n main<true,false,false,false,false>(ch, hint, next);\n }\n };\n\n template<Converter::f_t InitF>\n class MagicCaseConverter: public UnaryCommand {\n public:\n MagicCaseConverter(Command* left, auto_ptr<Command> sub)\n : UnaryCommand(left, sub) {}\n\n virtual bool exec(wstring& dst, Interpreter& interp) {\n wstring in;\n if (!interp.exec(in, sub.get())) return false;\n\n \/\/Determine hints\n unsigned hint = 0;\n for (unsigned i = 0; i < in.size(); ++i) {\n if (iswlower(in[i])) hint |= HINT_LC;\n if (iswupper(in[i])) hint |= HINT_UC;\n if (isseparator(in[i])) hint |= HINT_SEP;\n }\n if ((hint & (HINT_LC|HINT_UC)) == (HINT_LC|HINT_UC))\n hint |= HINT_MC;\n\n \/\/Convert\n dst.clear();\n Converter conv;\n conv.f = InitF;\n wstring ch;\n for (unsigned i = 0; i < in.size(); ++i) {\n ch.assign(1, in[i]);\n conv.f(ch, hint, conv);\n dst += ch;\n }\n\n \/\/OK\n return true;\n }\n };\n\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n simpleConverter<\n towlower> > > > _strtolower(L\"str-tolower\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n simpleConverter<\n towupper> > > > _strtoupper(L\"str-toupper\");\n\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L' ', false,\n towupper, towupper, towlower>::f> > >\n _strtotitle(L\"str-totitle\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L' ', false,\n towupper, towlower, towlower>::f> > >\n _strtosent(L\"str-tosent\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<0, true,\n towlower, towupper, towlower>::f> > >\n _strtocamel(L\"str-tocamel\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<0, true,\n towupper, towupper, towlower>::f> > >\n _strtopascal(L\"str-topascal\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towupper, towupper, towupper>::f> > >\n _strtoscream(L\"str-toscream\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towlower, towlower, towlower>::f> > >\n _strtocstyle(L\"str-tocstyle\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towupper, towupper, towlower>::f> > >\n _strtocaspal(L\"str-tocaspal\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'-', true,\n towlower, towlower, towlower>::f> > >\n _strtolisp(L\"str-tolisp\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'-', true,\n towupper, towupper, towupper>::f> > >\n _strtocobol(L\"str-tocobol\");\n}\n<commit_msg>Fix issue regarding word breaks and digits in magic case conversion.<commit_after>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <string>\n#include <cctype>\n\n#include \"..\/interp.hxx\"\n#include \"..\/command.hxx\"\n#include \"..\/argument.hxx\"\n#include \"basic_parsers.hxx\"\n\nusing namespace std;\n\nnamespace tglng {\n \/* Magic case conversion is performed as a two-pass process.\n *\n * The first pass examines the input string and determines hinting properties\n * from it (ie, what cases or separators are present).\n *\n * The second transforms the string by repeadedly executing a function for\n * each character, given the hint. This function may also alter what function\n * is executed for the next character.\n *\/\n\n \/* Indicates that one or more lowercase characters are present in the input\n * string.\n *\/\n#define HINT_LC (1<<0)\n \/* Indicates that one or more uppercase characters are present in the input\n * string.\n *\/\n#define HINT_UC (1<<1)\n \/* Indicates that both upper and lowercase characters are present in the\n * input string. This is automatically set if both LC and UC are set.\n *\/\n#define HINT_MC (1<<2)\n \/* Indicates that space-like delimiters (space characters, hyphens, or\n * underscores) are present in the input string.\n *\/\n#define HINT_SEP (1<<4)\n\n \/* Wrapper struct since it is otherwise impossible to define a function which\n * takes itself as a parm.\n *\/\n struct Converter {\n \/**\n * Performs conversion of a single character.\n *\n * @param ch The single-character string to convert.\n * @param hint A bitwise OR of any number of the HINT constants.\n * @param next The next function to use, by default the one being called.\n * @return The transformed character.\n *\/\n typedef void (*f_t)(wstring& ch, unsigned hint, Converter& next);\n f_t f;\n };\n\n typedef wint_t (*case_t)(wint_t);\n\n static int isseparator(wint_t ch) {\n return iswspace(ch) || ch == L'_' || ch == L'-';\n }\n\n \/* Basic to-uppercase or to-lower converter. *\/\n namespace { \/* Since templates can't take functions with static linkage (?) *\/\n template<case_t F>\n void simpleConverter(wstring& ch, unsigned, Converter&) {\n ch[0] = F(ch[0]);\n }\n }\n\n \/* Common functions for converting to delimited-word and mixed-case formats.\n *\n * If separators exist in the input string, they define the word boundaries\n * and may be replaced by the expected delimiter (see ReplaceSeparators);\n * other word characters are normalised according to WordInit and WordRest.\n *\n * If no separators exist, an uppercase character following a lowercase\n * character is considered a word boundary, and will cause a delimiter to be\n * inserted between the two.\n *\n * Digits after any character will start a word, and any alpha after a digit\n * will as well.\n *\n * A Delimiter of NUL means nothing.\n *\/\n template<wchar_t Delimiter, bool ReplaceSeparators,\n case_t TokenInit, case_t WordInit, case_t WordRest>\n class delimitedConverter {\n template<bool StartToken, bool StartWord,\n bool PUChar, bool PLChar, bool PDigit>\n static void main(wstring& ch, unsigned hint, Converter& next) {\n bool wasU = iswupper(ch[0]),\n wasD = iswdigit(ch[0]);\n if (wasD || iswalpha(ch[0])) {\n if (StartToken) {\n ch[0] = TokenInit(ch[0]);\n } else if ((PLChar && (wasU || wasD) && !(hint & HINT_SEP)) ||\n (PDigit && !wasD && !(hint & HINT_SEP)) ||\n StartWord) {\n \/\/New word\n ch[0] = WordInit(ch[0]);\n if (Delimiter && !StartWord)\n \/\/Insert our own word start\n ch.insert(0, 1, Delimiter);\n } else {\n \/\/Other word char\n ch[0] = WordRest(ch[0]);\n }\n\n if (wasU)\n next.f = main<false,false,true,false,false>;\n else if (wasD)\n next.f = main<false,false,false,false,true>;\n else\n \/\/If there are any letters which are neither upper nor lower,\n \/\/consider them lower.\n next.f = main<false,false,false,true,false>;\n } else if (isseparator(ch[0])) {\n if (ReplaceSeparators) {\n if (Delimiter && !StartToken && !StartWord)\n ch[0] = Delimiter;\n else if (Delimiter == 0)\n \/\/NUL delimiter, remove the separator\n ch.clear();\n\n \/\/Next char is word start unless this was a token start\n next.f = main<StartToken,!StartToken,false,false,false>;\n }\n } else {\n \/\/Non-word non-separator\n \/\/Next one is the start of a new token\n next.f = main<true,false,false,false,false>;\n }\n }\n\n public:\n static void f(wstring& ch, unsigned hint, Converter& next) {\n main<true,false,false,false,false>(ch, hint, next);\n }\n };\n\n template<Converter::f_t InitF>\n class MagicCaseConverter: public UnaryCommand {\n public:\n MagicCaseConverter(Command* left, auto_ptr<Command> sub)\n : UnaryCommand(left, sub) {}\n\n virtual bool exec(wstring& dst, Interpreter& interp) {\n wstring in;\n if (!interp.exec(in, sub.get())) return false;\n\n \/\/Determine hints\n unsigned hint = 0;\n for (unsigned i = 0; i < in.size(); ++i) {\n if (iswlower(in[i])) hint |= HINT_LC;\n if (iswupper(in[i])) hint |= HINT_UC;\n if (isseparator(in[i])) hint |= HINT_SEP;\n }\n if ((hint & (HINT_LC|HINT_UC)) == (HINT_LC|HINT_UC))\n hint |= HINT_MC;\n\n \/\/Convert\n dst.clear();\n Converter conv;\n conv.f = InitF;\n wstring ch;\n for (unsigned i = 0; i < in.size(); ++i) {\n ch.assign(1, in[i]);\n conv.f(ch, hint, conv);\n dst += ch;\n }\n\n \/\/OK\n return true;\n }\n };\n\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n simpleConverter<\n towlower> > > > _strtolower(L\"str-tolower\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n simpleConverter<\n towupper> > > > _strtoupper(L\"str-toupper\");\n\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L' ', false,\n towupper, towupper, towlower>::f> > >\n _strtotitle(L\"str-totitle\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L' ', false,\n towupper, towlower, towlower>::f> > >\n _strtosent(L\"str-tosent\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<0, true,\n towlower, towupper, towlower>::f> > >\n _strtocamel(L\"str-tocamel\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<0, true,\n towupper, towupper, towlower>::f> > >\n _strtopascal(L\"str-topascal\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towupper, towupper, towupper>::f> > >\n _strtoscream(L\"str-toscream\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towlower, towlower, towlower>::f> > >\n _strtocstyle(L\"str-tocstyle\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'_', true,\n towupper, towupper, towlower>::f> > >\n _strtocaspal(L\"str-tocaspal\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'-', true,\n towlower, towlower, towlower>::f> > >\n _strtolisp(L\"str-tolisp\");\n static GlobalBinding<\n UnaryCommandParser<\n MagicCaseConverter<\n delimitedConverter<L'-', true,\n towupper, towupper, towupper>::f> > >\n _strtocobol(L\"str-tocobol\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TorrentFileParser.h\"\n#include <iostream>\n#include <filesystem>\n#include \"SHA.h\"\n\n#define TPARSER_LOG(x) WRITE_LOG(LogTypeFileParser, x)\n\nusing namespace mtt;\n\nbool generateInfoHash(BencodeParser& parsed, TorrentFileInfo&);\nvoid loadTorrentFileInfo(BencodeParser& parsed, TorrentFileInfo&);\nTorrentInfo parseTorrentInfo(const BencodeParser::Object* info);\n\nTorrentFileInfo TorrentFileParser::parse(const uint8_t* data, size_t length)\n{\n\tTorrentFileInfo out;\n\tBencodeParser parser;\n\n\tif (!parser.parse(data, length))\n\t\treturn out;\n\t\n\tloadTorrentFileInfo(parser, out);\n\tgenerateInfoHash(parser, out);\n\n\treturn out;\n}\n\nTorrentFileInfo TorrentFileParser::parseFile(const char* filename)\n{\n\tTorrentFileInfo out;\n\n\tsize_t maxSize = 10 * 1024 * 1024;\n\tstd::filesystem::path dir(filename);\n\n\tif (!std::filesystem::exists(dir) || std::filesystem::file_size(dir) > maxSize)\n\t{\n\t\tTPARSER_LOG(\"Invalid torrent file \" << filename);\n\t\treturn out;\n\t}\n\n\tstd::ifstream file(filename, std::ios_base::binary);\n\n\tif (!file.good())\n\t{\n\t\tTPARSER_LOG(\"Failed to open torrent file \" << filename);\n\t\treturn out;\n\t}\n\n\tDataBuffer buffer((\n\t\tstd::istreambuf_iterator<char>(file)),\n\t\t(std::istreambuf_iterator<char>()));\n\n\treturn parse(buffer.data(), buffer.size());\n}\n\nstatic uint32_t getPieceIndex(size_t pos, size_t pieceSize)\n{\n\tsize_t p = 0;\n\n\twhile (pieceSize + p*pieceSize < pos)\n\t{\n\t\tp++;\n\t}\n\n\treturn static_cast<uint32_t>(p);\n}\n\nvoid loadTorrentFileInfo(BencodeParser& parser, TorrentFileInfo& fileInfo)\n{\n\tauto root = parser.getRoot();\n\n\tif (root && root->isMap())\n\t{\n\t\tif (auto announce = root->getTxtItem(\"announce\"))\n\t\t\tfileInfo.announce = std::string(announce->data, announce->size);\n\n\t\tif (auto list = root->getListItem(\"announce-list\"))\n\t\t{\n\t\t\tauto announce = list->getFirstItem();\n\n\t\t\twhile (announce)\n\t\t\t{\n\t\t\t\tif (announce->isList())\n\t\t\t\t{\n\t\t\t\t\tauto a = announce->getFirstItem();\n\n\t\t\t\t\twhile (a)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (a->isText())\n\t\t\t\t\t\t\tfileInfo.announceList.push_back(std::string(a->info.data, a->info.size));\n\n\t\t\t\t\t\ta = a->getNextSibling();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tannounce = announce->getNextSibling();\n\t\t\t}\n\t\t}\n\t\telse if (!fileInfo.announce.empty())\n\t\t\tfileInfo.announceList.push_back(fileInfo.announce);\n\n\t\tif (auto info = root->getDictItem(\"info\"))\n\t\t{\n\t\t\tfileInfo.info = parseTorrentInfo(info);\n\t\t}\t\t\n\t}\n}\n\nbool generateInfoHash(BencodeParser& parser, TorrentFileInfo& fileInfo)\n{\n\tconst char* infoStart = nullptr;\n\tconst char* infoEnd = nullptr;\n\tauto dict = parser.getRoot();\n\n\tif (dict)\n\t{\n\t\tauto it = dict->getFirstItem();\n\n\t\twhile (it)\n\t\t{\n\t\t\tif (it->isText(\"info\", 4))\n\t\t\t{\n\t\t\t\tinfoStart = it->info.data + 4;\n\n\t\t\t\tauto infod = it->getNextSibling();\n\n\t\t\t\tif (infod->isMap())\n\t\t\t\t{\n\t\t\t\t\tauto pieces = infod->getTxtItem(\"pieces\");\n\n\t\t\t\t\tif (pieces)\n\t\t\t\t\t\tinfoEnd = pieces->data + pieces->size + 1; \n\t\t\t\t}\n\n\t\t\t\tit = nullptr;\n\t\t\t}\n\t\t\telse\n\t\t\t\tit = it->getNextSibling();\n\t\t}\n\t}\n\n\tif (infoStart && infoEnd)\n\t{\n\t\tSHA1((const unsigned char*)infoStart, infoEnd - infoStart, (unsigned char*)&fileInfo.info.hash[0]);\n\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\nmtt::TorrentInfo mtt::TorrentFileParser::parseTorrentInfo(const uint8_t* data, size_t length)\n{\n\tBencodeParser parser;\n\n\tif (parser.parse(data, length))\n\t{\n\t\tauto info = ::parseTorrentInfo(parser.getRoot());\n\n\t\tauto infoStart = (const char*)data;\n\t\tauto infoEnd = (const char*)data + length;\n\n\t\tSHA1((const unsigned char*)infoStart, infoEnd - infoStart, (unsigned char*)&info.hash[0]);\n\n\t\treturn info;\n\t}\n\telse\n\t\treturn mtt::TorrentInfo();\n}\n\nmtt::TorrentInfo parseTorrentInfo(const BencodeParser::Object* infoDictionary)\n{\n\tmtt::TorrentInfo info;\n\n\tinfo.pieceSize = infoDictionary->getInt(\"piece length\");\n\n\tauto piecesHash = infoDictionary->getTxtItem(\"pieces\");\n\n\tif (piecesHash && piecesHash->size % 20 == 0)\n\t{\n\t\tPieceInfo temp;\n\t\tauto end = piecesHash->data + piecesHash->size;\n\n\t\tfor (auto it = piecesHash->data; it != end; it += 20)\n\t\t{\n\t\t\tmemcpy(temp.hash, it, 20);\n\t\t\tinfo.pieces.push_back(temp);\n\t\t}\n\t}\n\n\tif (auto files = infoDictionary->getListItem(\"files\"))\n\t{\n\t\tinfo.name = infoDictionary->getTxt(\"name\");\n\n\t\tsize_t sizeSum = 0;\n\t\t\n\t\tauto file = files->getFirstItem();\n\t\twhile(file)\n\t\t{\n\t\t\tstd::vector<std::string> path;\n\t\t\tpath.push_back(info.name);\n\n\t\t\tauto pathList = file->getListItem(\"path\");\n\t\t\tauto pathItem = pathList->getFirstItem();\n\t\t\twhile (pathItem)\n\t\t\t{\n\t\t\t\tpath.push_back(pathItem->getTxt());\n\t\t\t\tpathItem = pathItem->getNextSibling();\n\t\t\t}\n\n\t\t\tsize_t size = file->getBigInt(\"length\");\n\t\t\tauto startId = getPieceIndex(sizeSum, info.pieceSize);\n\t\t\tauto startPos = sizeSum % info.pieceSize;\n\t\t\tsizeSum += size;\n\t\t\tauto endId = getPieceIndex(sizeSum, info.pieceSize);\n\t\t\tauto endPos = sizeSum % info.pieceSize;\n\n\t\t\tinfo.files.push_back({ path, size, startId, (uint32_t)startPos, endId, (uint32_t)endPos });\n\t\t\tfile = file->getNextSibling();\n\t\t}\n\n\t\tinfo.fullSize = sizeSum;\n\t}\n\telse\n\t{\n\t\tsize_t size = infoDictionary->getBigInt(\"length\");\n\t\tauto endPos = size % info.pieceSize;\n\t\tinfo.name = infoDictionary->getTxt(\"name\");\n\t\tinfo.files.push_back({ { info.name }, size, 0, 0, static_cast<uint32_t>(info.pieces.size() - 1), (uint32_t)endPos });\n\n\t\tinfo.fullSize = size;\n\t}\n\n\tif (!info.files.empty())\n\t{\n\t\tinfo.lastPieceIndex = info.files.back().endPieceIndex;\n\t\tinfo.lastPieceSize = info.files.back().endPiecePos;\n\t\tinfo.lastPieceLastBlockIndex = (info.lastPieceSize - 1) \/ BlockRequestMaxSize;\n\t\tinfo.lastPieceLastBlockSize = info.lastPieceSize - (info.lastPieceLastBlockIndex * BlockRequestMaxSize);\n\t}\n\n\tauto piecesCount = info.pieces.size();\n\tauto addExpected = piecesCount % 8 > 0 ? 1 : 0; \/\/8 pieces in byte\n\tinfo.expectedBitfieldSize = piecesCount \/ 8 + addExpected;\n\n\treturn info;\n}\n<commit_msg>fix files ending with aligned piece size<commit_after>#include \"TorrentFileParser.h\"\n#include <iostream>\n#include <filesystem>\n#include \"SHA.h\"\n\n#define TPARSER_LOG(x) WRITE_LOG(LogTypeFileParser, x)\n\nusing namespace mtt;\n\nbool generateInfoHash(BencodeParser& parsed, TorrentFileInfo&);\nvoid loadTorrentFileInfo(BencodeParser& parsed, TorrentFileInfo&);\nTorrentInfo parseTorrentInfo(const BencodeParser::Object* info);\n\nTorrentFileInfo TorrentFileParser::parse(const uint8_t* data, size_t length)\n{\n\tTorrentFileInfo out;\n\tBencodeParser parser;\n\n\tif (!parser.parse(data, length))\n\t\treturn out;\n\t\n\tloadTorrentFileInfo(parser, out);\n\tgenerateInfoHash(parser, out);\n\n\treturn out;\n}\n\nTorrentFileInfo TorrentFileParser::parseFile(const char* filename)\n{\n\tTorrentFileInfo out;\n\n\tsize_t maxSize = 10 * 1024 * 1024;\n\tstd::filesystem::path dir(filename);\n\n\tif (!std::filesystem::exists(dir) || std::filesystem::file_size(dir) > maxSize)\n\t{\n\t\tTPARSER_LOG(\"Invalid torrent file \" << filename);\n\t\treturn out;\n\t}\n\n\tstd::ifstream file(filename, std::ios_base::binary);\n\n\tif (!file.good())\n\t{\n\t\tTPARSER_LOG(\"Failed to open torrent file \" << filename);\n\t\treturn out;\n\t}\n\n\tDataBuffer buffer((\n\t\tstd::istreambuf_iterator<char>(file)),\n\t\t(std::istreambuf_iterator<char>()));\n\n\treturn parse(buffer.data(), buffer.size());\n}\n\nstatic uint32_t getPieceIndex(size_t pos, size_t pieceSize)\n{\n\tsize_t p = 0;\n\n\twhile (pieceSize + p*pieceSize < pos)\n\t{\n\t\tp++;\n\t}\n\n\treturn static_cast<uint32_t>(p);\n}\n\nvoid loadTorrentFileInfo(BencodeParser& parser, TorrentFileInfo& fileInfo)\n{\n\tauto root = parser.getRoot();\n\n\tif (root && root->isMap())\n\t{\n\t\tif (auto announce = root->getTxtItem(\"announce\"))\n\t\t\tfileInfo.announce = std::string(announce->data, announce->size);\n\n\t\tif (auto list = root->getListItem(\"announce-list\"))\n\t\t{\n\t\t\tauto announce = list->getFirstItem();\n\n\t\t\twhile (announce)\n\t\t\t{\n\t\t\t\tif (announce->isList())\n\t\t\t\t{\n\t\t\t\t\tauto a = announce->getFirstItem();\n\n\t\t\t\t\twhile (a)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (a->isText())\n\t\t\t\t\t\t\tfileInfo.announceList.push_back(std::string(a->info.data, a->info.size));\n\n\t\t\t\t\t\ta = a->getNextSibling();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tannounce = announce->getNextSibling();\n\t\t\t}\n\t\t}\n\t\telse if (!fileInfo.announce.empty())\n\t\t\tfileInfo.announceList.push_back(fileInfo.announce);\n\n\t\tif (auto info = root->getDictItem(\"info\"))\n\t\t{\n\t\t\tfileInfo.info = parseTorrentInfo(info);\n\t\t}\t\t\n\t}\n}\n\nbool generateInfoHash(BencodeParser& parser, TorrentFileInfo& fileInfo)\n{\n\tconst char* infoStart = nullptr;\n\tconst char* infoEnd = nullptr;\n\tauto dict = parser.getRoot();\n\n\tif (dict)\n\t{\n\t\tauto it = dict->getFirstItem();\n\n\t\twhile (it)\n\t\t{\n\t\t\tif (it->isText(\"info\", 4))\n\t\t\t{\n\t\t\t\tinfoStart = it->info.data + 4;\n\n\t\t\t\tauto infod = it->getNextSibling();\n\n\t\t\t\tif (infod->isMap())\n\t\t\t\t{\n\t\t\t\t\tauto pieces = infod->getTxtItem(\"pieces\");\n\n\t\t\t\t\tif (pieces)\n\t\t\t\t\t\tinfoEnd = pieces->data + pieces->size + 1; \n\t\t\t\t}\n\n\t\t\t\tit = nullptr;\n\t\t\t}\n\t\t\telse\n\t\t\t\tit = it->getNextSibling();\n\t\t}\n\t}\n\n\tif (infoStart && infoEnd)\n\t{\n\t\tSHA1((const unsigned char*)infoStart, infoEnd - infoStart, (unsigned char*)&fileInfo.info.hash[0]);\n\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\nmtt::TorrentInfo mtt::TorrentFileParser::parseTorrentInfo(const uint8_t* data, size_t length)\n{\n\tBencodeParser parser;\n\n\tif (parser.parse(data, length))\n\t{\n\t\tauto info = ::parseTorrentInfo(parser.getRoot());\n\n\t\tauto infoStart = (const char*)data;\n\t\tauto infoEnd = (const char*)data + length;\n\n\t\tSHA1((const unsigned char*)infoStart, infoEnd - infoStart, (unsigned char*)&info.hash[0]);\n\n\t\treturn info;\n\t}\n\telse\n\t\treturn mtt::TorrentInfo();\n}\n\nmtt::TorrentInfo parseTorrentInfo(const BencodeParser::Object* infoDictionary)\n{\n\tmtt::TorrentInfo info;\n\n\tinfo.pieceSize = infoDictionary->getInt(\"piece length\");\n\n\tauto piecesHash = infoDictionary->getTxtItem(\"pieces\");\n\n\tif (piecesHash && piecesHash->size % 20 == 0)\n\t{\n\t\tPieceInfo temp;\n\t\tauto end = piecesHash->data + piecesHash->size;\n\n\t\tfor (auto it = piecesHash->data; it != end; it += 20)\n\t\t{\n\t\t\tmemcpy(temp.hash, it, 20);\n\t\t\tinfo.pieces.push_back(temp);\n\t\t}\n\t}\n\n\tif (auto files = infoDictionary->getListItem(\"files\"))\n\t{\n\t\tinfo.name = infoDictionary->getTxt(\"name\");\n\n\t\tsize_t sizeSum = 0;\n\t\t\n\t\tauto file = files->getFirstItem();\n\t\twhile(file)\n\t\t{\n\t\t\tstd::vector<std::string> path;\n\t\t\tpath.push_back(info.name);\n\n\t\t\tauto pathList = file->getListItem(\"path\");\n\t\t\tauto pathItem = pathList->getFirstItem();\n\t\t\twhile (pathItem)\n\t\t\t{\n\t\t\t\tpath.push_back(pathItem->getTxt());\n\t\t\t\tpathItem = pathItem->getNextSibling();\n\t\t\t}\n\n\t\t\tsize_t size = file->getBigInt(\"length\");\n\t\t\tauto startId = getPieceIndex(sizeSum, info.pieceSize);\n\t\t\tauto startPos = sizeSum % info.pieceSize;\n\t\t\tsizeSum += size;\n\t\t\tauto endId = getPieceIndex(sizeSum, info.pieceSize);\n\t\t\tauto endPos = sizeSum % info.pieceSize;\n\n\t\t\tinfo.files.push_back({ path, size, startId, (uint32_t)startPos, endId, (uint32_t)endPos });\n\t\t\tfile = file->getNextSibling();\n\t\t}\n\n\t\tinfo.fullSize = sizeSum;\n\t}\n\telse\n\t{\n\t\tsize_t size = infoDictionary->getBigInt(\"length\");\n\t\tauto endPos = size % info.pieceSize;\n\t\tinfo.name = infoDictionary->getTxt(\"name\");\n\t\tinfo.files.push_back({ { info.name }, size, 0, 0, static_cast<uint32_t>(info.pieces.size() - 1), (uint32_t)(endPos ? endPos : info.pieceSize) });\n\n\t\tinfo.fullSize = size;\n\t}\n\n\tif (!info.files.empty())\n\t{\n\t\tinfo.lastPieceIndex = info.files.back().endPieceIndex;\n\t\tinfo.lastPieceSize = info.files.back().endPiecePos;\n\t\tinfo.lastPieceLastBlockIndex = (info.lastPieceSize - 1) \/ BlockRequestMaxSize;\n\t\tinfo.lastPieceLastBlockSize = info.lastPieceSize - (info.lastPieceLastBlockIndex * BlockRequestMaxSize);\n\t}\n\n\tauto piecesCount = info.pieces.size();\n\tauto addExpected = piecesCount % 8 > 0 ? 1 : 0; \/\/8 pieces in byte\n\tinfo.expectedBitfieldSize = piecesCount \/ 8 + addExpected;\n\n\treturn info;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include \"config.h\"\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n\/\/#define DODS_DEBUG 1\n\n#include \"D4Group.h\"\n\n#include \"Byte.h\"\n#include \"Int64.h\"\n\n#include \"XMLWriter.h\"\n#include \"debug.h\"\n\n#include \"testFile.h\"\n#include \"test_config.h\"\n\nusing namespace CppUnit;\nusing namespace std;\nusing namespace libdap;\n\nclass D4GroupTest: public TestFixture {\nprivate:\n XMLWriter *xml;\n D4Group *root, *named;\n\npublic:\n D4GroupTest() {\n }\n\n ~D4GroupTest() {\n }\n\n void setUp() {\n root = new D4Group(\"\");\n named = new D4Group(\"test\");\n xml = new XMLWriter;\n }\n\n void tearDown() {\n delete xml;\n delete root;\n delete named;\n }\n\n void load_group_with_scalars(D4Group *g) {\n g->add_var_nocopy(new Byte(\"b\"));\n g->add_var_nocopy(new Int64(\"i64\"));\n }\n\n void load_group_with_stuff(D4Group *g) {\n g->dims()->add_dim_nocopy(new D4Dimension(\"lat\", 1024));\n g->dims()->add_dim_nocopy(new D4Dimension(\"lon\", 1024));\n g->dims()->add_dim_nocopy(new D4Dimension(\"time\"));\n\n D4EnumDef *color_values = new D4EnumDef(\"colors\", dods_byte_c);\n color_values->add_value(\"red\", 1);\n color_values->add_value(\"green\", 2);\n color_values->add_value(\"blue\", 3);\n g->enum_defs()->add_enum_nocopy(color_values);\n\n g->get_attr_table().append_attr(\"test\", \"Int16\", \"1\");\n }\n\n \/\/ An empty D4Group object prints nothing; the XMLWriter class adds\n \/\/ a xml doc preface.\n void test_print_empty() {\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_empty.xml\");\n DBG(cerr << \"test_print_empty: doc: \" << doc << endl);\n DBG(cerr << \"test_print_empty: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_empty() {\n named->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_empty.xml\");\n DBG(cerr << \"test_print_named_empty: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_empty: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_with_vars() {\n load_group_with_scalars(root);\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_with_scalars.xml\");\n DBG(cerr << \"test_print_with_vars: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_with_vars() {\n load_group_with_scalars(named);\n\n named->print_dap4(*xml);\n\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_with_scalars.xml\");\n DBG(cerr << \"test_print_named_with_vars: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_with_vars: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_with_vars_and_stuff() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_with_scalars_and_stuff.xml\");\n DBG(cerr << \"test_print_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_with_vars_and_stuff() {\n load_group_with_scalars(named);\n load_group_with_stuff(named);\n\n named->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_with_scalars_and_stuff.xml\");\n DBG(cerr << \"test_print_named_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_everything() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group(child);\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_copy_ctor() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group(child);\n\n D4Group lhs(*root);\n\n lhs.print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_copy_ctor: doc: \" << doc << endl);\n DBG(cerr << \"test_print_copy_ctor: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_assignment() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group(child);\n\n D4Group lhs = *root;\n\n lhs.print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_assignment: doc: \" << doc << endl);\n DBG(cerr << \"test_print_assignment: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n CPPUNIT_TEST_SUITE( D4GroupTest );\n\n CPPUNIT_TEST(test_print_empty);\n CPPUNIT_TEST(test_print_named_empty);\n CPPUNIT_TEST(test_print_with_vars);\n CPPUNIT_TEST(test_print_named_with_vars);\n\n CPPUNIT_TEST(test_print_with_vars_and_stuff);\n\n CPPUNIT_TEST(test_print_named_with_vars_and_stuff);\n CPPUNIT_TEST(test_print_everything);\n\n CPPUNIT_TEST(test_print_copy_ctor);\n CPPUNIT_TEST(test_print_assignment);\n\n CPPUNIT_TEST_SUITE_END();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(D4GroupTest);\n\nint main(int, char**) {\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = runner.run(\"\", false);\n\n return wasSuccessful ? 0 : 1;\n}\n\n<commit_msg>Fixed memory leaks in the D4Group unit tests<commit_after>\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include \"config.h\"\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n\/\/#define DODS_DEBUG 1\n\n#include \"D4Group.h\"\n\n#include \"Byte.h\"\n#include \"Int64.h\"\n\n#include \"XMLWriter.h\"\n#include \"debug.h\"\n\n#include \"testFile.h\"\n#include \"test_config.h\"\n\nusing namespace CppUnit;\nusing namespace std;\nusing namespace libdap;\n\nclass D4GroupTest: public TestFixture {\nprivate:\n XMLWriter *xml;\n D4Group *root, *named;\n\npublic:\n D4GroupTest() {\n }\n\n ~D4GroupTest() {\n }\n\n void setUp() {\n root = new D4Group(\"\");\n named = new D4Group(\"test\");\n xml = new XMLWriter;\n }\n\n void tearDown() {\n delete xml;\n delete root;\n delete named;\n }\n\n void load_group_with_scalars(D4Group *g) {\n g->add_var_nocopy(new Byte(\"b\"));\n g->add_var_nocopy(new Int64(\"i64\"));\n }\n\n void load_group_with_stuff(D4Group *g) {\n g->dims()->add_dim_nocopy(new D4Dimension(\"lat\", 1024));\n g->dims()->add_dim_nocopy(new D4Dimension(\"lon\", 1024));\n g->dims()->add_dim_nocopy(new D4Dimension(\"time\"));\n\n D4EnumDef *color_values = new D4EnumDef(\"colors\", dods_byte_c);\n color_values->add_value(\"red\", 1);\n color_values->add_value(\"green\", 2);\n color_values->add_value(\"blue\", 3);\n g->enum_defs()->add_enum_nocopy(color_values);\n\n g->get_attr_table().append_attr(\"test\", \"Int16\", \"1\");\n }\n\n \/\/ An empty D4Group object prints nothing; the XMLWriter class adds\n \/\/ a xml doc preface.\n void test_print_empty() {\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_empty.xml\");\n DBG(cerr << \"test_print_empty: doc: \" << doc << endl);\n DBG(cerr << \"test_print_empty: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_empty() {\n named->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_empty.xml\");\n DBG(cerr << \"test_print_named_empty: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_empty: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_with_vars() {\n load_group_with_scalars(root);\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_with_scalars.xml\");\n DBG(cerr << \"test_print_with_vars: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_with_vars() {\n load_group_with_scalars(named);\n\n named->print_dap4(*xml);\n\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_with_scalars.xml\");\n DBG(cerr << \"test_print_named_with_vars: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_with_vars: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_with_vars_and_stuff() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_with_scalars_and_stuff.xml\");\n DBG(cerr << \"test_print_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_named_with_vars_and_stuff() {\n load_group_with_scalars(named);\n load_group_with_stuff(named);\n\n named->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_named_with_scalars_and_stuff.xml\");\n DBG(cerr << \"test_print_named_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_named_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_everything() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group(child);\n\n \/\/ Used add_group() and not add_group_nocopy()\n delete child;\n\n root->print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_with_vars_and_stuff: doc: \" << doc << endl);\n DBG(cerr << \"test_print_with_vars_and_stuff: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_copy_ctor() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group_nocopy(child); \/\/ add it using ...nocopy() this time\n\n D4Group lhs(*root);\n\n lhs.print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_copy_ctor: doc: \" << doc << endl);\n DBG(cerr << \"test_print_copy_ctor: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n void test_print_assignment() {\n load_group_with_scalars(root);\n load_group_with_stuff(root);\n\n D4Group *child = new D4Group(\"child\");\n load_group_with_scalars(child);\n load_group_with_stuff(child);\n root->add_group_nocopy(child);\n\n D4Group lhs = *root;\n\n lhs.print_dap4(*xml);\n string doc = xml->get_doc();\n string baseline = readTestBaseline(string(TEST_SRC_DIR) + \"\/D4-xml\/D4Group_everything.xml\");\n DBG(cerr << \"test_print_assignment: doc: \" << doc << endl);\n DBG(cerr << \"test_print_assignment: baseline: \" << baseline << endl);\n CPPUNIT_ASSERT(doc == baseline);\n }\n\n CPPUNIT_TEST_SUITE( D4GroupTest );\n\n CPPUNIT_TEST(test_print_empty);\n\n CPPUNIT_TEST(test_print_named_empty);\n CPPUNIT_TEST(test_print_with_vars);\n CPPUNIT_TEST(test_print_named_with_vars);\n\n CPPUNIT_TEST(test_print_with_vars_and_stuff);\n\n CPPUNIT_TEST(test_print_named_with_vars_and_stuff);\n CPPUNIT_TEST(test_print_everything);\n\n CPPUNIT_TEST(test_print_copy_ctor);\n CPPUNIT_TEST(test_print_assignment);\n\n CPPUNIT_TEST_SUITE_END();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(D4GroupTest);\n\nint main(int, char**) {\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = runner.run(\"\", false);\n\n return wasSuccessful ? 0 : 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"OutputGeometry.h\"\n#include \"OutputGeometryPart.h\"\n#include \"OutputObject.h\"\n#include \"util.h\"\n#include \"AssetNode.h\"\n\nOutputGeometry::OutputGeometry(HAPI_NodeId nodeId) :\n myNodeId(nodeId),\n myLastCookCount(0)\n{\n update();\n}\n\nOutputGeometry::~OutputGeometry()\n{\n for(int i = myParts.size(); i-- > 0;)\n {\n delete myParts.back();\n myParts.pop_back();\n }\n}\n\nvoid\nOutputGeometry::update()\n{\n HAPI_Result hapiResult;\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n myNodeId, &myNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetGeoInfo(\n Util::theHAPISession.get(),\n myNodeId,\n &myGeoInfo);\n if(HAPI_FAIL(hapiResult))\n {\n \/\/ Make sre myGeoInfo is properly initialized.\n HAPI_GeoInfo_Init(&myGeoInfo);\n\n \/\/ Even when HAPI_GetGeoInfo() failed, there's always at least one\n \/\/ part. So we want the below code to initialize myParts.\n }\n\n if(myGeoInfo.type == HAPI_GEOTYPE_DEFAULT\n || myGeoInfo.type == HAPI_GEOTYPE_INTERMEDIATE\n || myGeoInfo.type == HAPI_GEOTYPE_CURVE)\n {\n \/\/ Create any new OutputGeometryPart\n myParts.reserve(myGeoInfo.partCount);\n for(int i = myParts.size(); i < myGeoInfo.partCount; i++)\n {\n OutputGeometryPart* outputGeometryPart = new OutputGeometryPart(\n myNodeId,\n i\n );\n myParts.push_back(outputGeometryPart);\n }\n\n \/\/ Destroy the extra OutputGeometryPart\n for(int i = myParts.size(); i-- > myGeoInfo.partCount;)\n {\n delete myParts.back();\n myParts.pop_back();\n }\n }\n}\n\nMStatus\nOutputGeometry::compute(\n const MTime &time,\n const MPlug &geoPlug,\n MDataBlock &data,\n MDataHandle &geoHandle,\n AssetNodeOptions::AccessorDataBlock &options,\n bool &needToSyncOutputs\n )\n{\n MStatus stat;\n\n data.setClean(geoPlug);\n\n update();\n\n MDataHandle geoNameHandle = geoHandle.child(AssetNode::outputGeoName);\n MString geoName;\n if(myGeoInfo.nameSH != 0)\n {\n geoName = Util::HAPIString(myGeoInfo.nameSH);\n }\n geoNameHandle.setString(geoName);\n\n MDataHandle isTemplatedHandle = geoHandle.child(AssetNode::outputGeoIsTemplated);\n isTemplatedHandle.setBool(myGeoInfo.isTemplated);\n\n MDataHandle isDisplayGeoHandle = geoHandle.child(AssetNode::outputGeoIsDisplayGeo);\n isDisplayGeoHandle.setBool(myGeoInfo.isDisplayGeo);\n\n MPlug partsPlug = geoPlug.child(AssetNode::outputParts);\n MDataHandle partsHandle = geoHandle.child(AssetNode::outputParts);\n MArrayDataHandle partsArrayHandle(partsHandle);\n\n bool partCountChanged = partsArrayHandle.elementCount() != (unsigned int)myGeoInfo.partCount;\n if(partCountChanged)\n {\n Util::resizeArrayDataHandle(partsArrayHandle, myGeoInfo.partCount);\n needToSyncOutputs = true;\n }\n\n bool forceCompute = false;\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n forceCompute |= myParts[i]->needCompute(options);\n }\n\n if(myGeoInfo.type == HAPI_GEOTYPE_DEFAULT ||\n myGeoInfo.type == HAPI_GEOTYPE_INTERMEDIATE ||\n myGeoInfo.type == HAPI_GEOTYPE_CURVE)\n {\n if(myNodeInfo.totalCookCount > myLastCookCount\n || partCountChanged || forceCompute)\n {\n \/\/ Compute the OutputGeometryPart\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n MPlug partPlug = partsPlug.elementByLogicalIndex(i);\n\n CHECK_MSTATUS(partsArrayHandle.jumpToArrayElement(i));\n MDataHandle partHandle = partsArrayHandle.outputValue();\n\n stat = myParts[i]->compute(\n time,\n partPlug,\n data,\n partHandle,\n options,\n needToSyncOutputs\n );\n CHECK_MSTATUS_AND_RETURN(stat, MS::kFailure);\n }\n }\n else\n {\n \/\/ even if nothing changed, clean the plugs\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n MPlug partPlug = partsPlug.elementByLogicalIndex(i);\n\n MPlugArray childPlugs;\n Util::getChildPlugs(childPlugs, partPlug);\n for(unsigned int j = 0; j < childPlugs.length(); j++)\n {\n data.setClean(childPlugs[j]);\n }\n }\n }\n }\n\n myLastCookCount = myNodeInfo.totalCookCount;\n\n return MS::kSuccess;\n}\n<commit_msg>fix for plugin crash when asset has an output null that HAPI has, for whatever reason, identified as an input.<commit_after>#include \"OutputGeometry.h\"\n#include \"OutputGeometryPart.h\"\n#include \"OutputObject.h\"\n#include \"util.h\"\n#include \"AssetNode.h\"\n\nOutputGeometry::OutputGeometry(HAPI_NodeId nodeId) :\n myNodeId(nodeId),\n myLastCookCount(0)\n{\n update();\n}\n\nOutputGeometry::~OutputGeometry()\n{\n for(int i = myParts.size(); i-- > 0;)\n {\n delete myParts.back();\n myParts.pop_back();\n }\n}\n\nvoid\nOutputGeometry::update()\n{\n HAPI_Result hapiResult;\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n myNodeId, &myNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetGeoInfo(\n Util::theHAPISession.get(),\n myNodeId,\n &myGeoInfo);\n if(HAPI_FAIL(hapiResult))\n {\n \/\/ Make sre myGeoInfo is properly initialized.\n HAPI_GeoInfo_Init(&myGeoInfo);\n\n \/\/ Even when HAPI_GetGeoInfo() failed, there's always at least one\n \/\/ part. So we want the below code to initialize myParts.\n }\n\n if(myGeoInfo.type == HAPI_GEOTYPE_DEFAULT\n || myGeoInfo.type == HAPI_GEOTYPE_INTERMEDIATE\n || myGeoInfo.type == HAPI_GEOTYPE_INPUT\n || myGeoInfo.type == HAPI_GEOTYPE_CURVE)\n {\n \/\/ Create any new OutputGeometryPart\n myParts.reserve(myGeoInfo.partCount);\n for(int i = myParts.size(); i < myGeoInfo.partCount; i++)\n {\n OutputGeometryPart* outputGeometryPart = new OutputGeometryPart(\n myNodeId,\n i\n );\n myParts.push_back(outputGeometryPart);\n }\n\n \/\/ Destroy the extra OutputGeometryPart\n for(int i = myParts.size(); i-- > myGeoInfo.partCount;)\n {\n delete myParts.back();\n myParts.pop_back();\n }\n }\n}\n\nMStatus\nOutputGeometry::compute(\n const MTime &time,\n const MPlug &geoPlug,\n MDataBlock &data,\n MDataHandle &geoHandle,\n AssetNodeOptions::AccessorDataBlock &options,\n bool &needToSyncOutputs\n )\n{\n MStatus stat;\n\n data.setClean(geoPlug);\n\n update();\n\n MDataHandle geoNameHandle = geoHandle.child(AssetNode::outputGeoName);\n MString geoName;\n if(myGeoInfo.nameSH != 0)\n {\n geoName = Util::HAPIString(myGeoInfo.nameSH);\n }\n geoNameHandle.setString(geoName);\n\n MDataHandle isTemplatedHandle = geoHandle.child(AssetNode::outputGeoIsTemplated);\n isTemplatedHandle.setBool(myGeoInfo.isTemplated);\n\n MDataHandle isDisplayGeoHandle = geoHandle.child(AssetNode::outputGeoIsDisplayGeo);\n isDisplayGeoHandle.setBool(myGeoInfo.isDisplayGeo);\n\n MPlug partsPlug = geoPlug.child(AssetNode::outputParts);\n MDataHandle partsHandle = geoHandle.child(AssetNode::outputParts);\n MArrayDataHandle partsArrayHandle(partsHandle);\n\n bool partCountChanged = partsArrayHandle.elementCount() != (unsigned int)myGeoInfo.partCount;\n if(partCountChanged)\n {\n Util::resizeArrayDataHandle(partsArrayHandle, myGeoInfo.partCount);\n needToSyncOutputs = true;\n }\n\n bool forceCompute = false;\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n forceCompute |= myParts[i]->needCompute(options);\n }\n\n \/\/ if we got here it's an output, even if HAPI thinks it's an input too\n if(myGeoInfo.type == HAPI_GEOTYPE_DEFAULT ||\n myGeoInfo.type == HAPI_GEOTYPE_INTERMEDIATE ||\n myGeoInfo.type == HAPI_GEOTYPE_INPUT ||\n myGeoInfo.type == HAPI_GEOTYPE_CURVE)\n {\n if(myNodeInfo.totalCookCount > myLastCookCount\n || partCountChanged || forceCompute)\n {\n \/\/ Compute the OutputGeometryPart\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n MPlug partPlug = partsPlug.elementByLogicalIndex(i);\n\n CHECK_MSTATUS(partsArrayHandle.jumpToArrayElement(i));\n MDataHandle partHandle = partsArrayHandle.outputValue();\n\n stat = myParts[i]->compute(\n time,\n partPlug,\n data,\n partHandle,\n options,\n needToSyncOutputs\n );\n CHECK_MSTATUS_AND_RETURN(stat, MS::kFailure);\n }\n }\n else\n {\n \/\/ even if nothing changed, clean the plugs\n for(int i = 0; i < myGeoInfo.partCount; i++)\n {\n MPlug partPlug = partsPlug.elementByLogicalIndex(i);\n\n MPlugArray childPlugs;\n Util::getChildPlugs(childPlugs, partPlug);\n for(unsigned int j = 0; j < childPlugs.length(); j++)\n {\n data.setClean(childPlugs[j]);\n }\n }\n }\n }\n\n myLastCookCount = myNodeInfo.totalCookCount;\n\n return MS::kSuccess;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest.h\"\n#include \"proposer.h\"\n\nclass ProposerTest : public testing::Test {\nprotected:\n\n\tint id;\n\tint instances;\n\tstruct proposer* p;\n\n\tvirtual void SetUp() {\n\t\tid = 2;\n\t\tinstances = 100;\n\t\tp = proposer_new(id, instances);\n\t}\n\t\n\tvirtual void TearDown() { }\n};\n\nTEST_F(ProposerTest, Prepare) {\n\tint count = 10;\n\tprepare_req pr;\n\tfor (int i = 0; i < count; ++i) {\n\t\tpr = proposer_prepare(p);\n\t\tASSERT_EQ(pr.iid, i+1);\n\t\tASSERT_EQ(pr.ballot, id + MAX_N_OF_PROPOSERS);\n\t}\n\tASSERT_EQ(count, proposer_prepared_count(p));\n}\n\nTEST_F(ProposerTest, PrepareAndAccept) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\taccept_req* ar;\n\taccept_ack aa;\n\t\n\tpr = proposer_prepare(p);\n\n\t\/\/ aid, iid, bal, val_bal, val_size\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};\t\n\tproposer_receive_prepare_ack(p, &pa);\n\tpa = (prepare_ack) {2, pr.iid, pr.ballot, 0, 0};\n\tproposer_receive_prepare_ack(p, &pa);\n\t\n\t\/\/ we have no value to propose!\n\tASSERT_EQ(proposer_accept(p), (void*)NULL);\n\t\n\tproposer_propose(p, (char*)\"value\", 6);\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (accept_req*)NULL);\n\tASSERT_EQ(ar->iid, pr.iid);\n\tASSERT_EQ(ar->ballot, pr.ballot);\n\tASSERT_EQ(ar->value_size, 6);\n\tASSERT_STREQ(ar->value, \"value\");\n\t\n\t\/\/ aid, iid, bal, val_bal, final, size\n\tprepare_req* req;\n\taa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n\taa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n}\n\nTEST_F(ProposerTest, PreparePreempted) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\tprepare_req* pr_preempt;\n\taccept_req* ar;\n\tchar value[] = \"some value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tpr = proposer_prepare(p);\n\tproposer_propose(p, value, value_size);\n\t\n\t\/\/ preempt! proposer receives a different ballot...\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot+1, 0, 0};\n\tpr_preempt = proposer_receive_prepare_ack(p, &pa);\n\tASSERT_NE((void*)NULL, pr_preempt);\n\tASSERT_EQ(pr_preempt->iid, pr.iid);\n\tASSERT_GT(pr_preempt->ballot, pr.ballot);\n\t\n\tpa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\tASSERT_EQ(ar->iid, pr_preempt->iid);\n\tASSERT_EQ(ar->ballot, pr_preempt->ballot);\n\tASSERT_EQ(ar->value_size, value_size);\n\tASSERT_STREQ(ar->value, value);\n\t\n\tfree(ar);\n\tfree(pr_preempt);\n}\n\nTEST_F(ProposerTest, AcceptPreempted) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\tprepare_req* pr_preempt;\n\taccept_req* ar;\n\taccept_ack aa;\n\tchar value[] = \"some value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tpr = proposer_prepare(p);\n\tproposer_propose(p, value, value_size);\n\t\n\tpa = (prepare_ack) {0, pr.iid, pr.ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\t\n\t\/\/ preempt! proposer receives accept nack\n\taa = (accept_ack) {0, ar->iid, ar->ballot+1, 0, 0, 0};\n\tpr_preempt = proposer_receive_accept_ack(p, &aa);\t\n\tASSERT_NE((void*)NULL, pr_preempt);\n\tASSERT_EQ(pr_preempt->iid, pr.iid);\n\tASSERT_GT(pr_preempt->ballot, ar->ballot);\n\tfree(ar);\n\t\n\t\/\/ finally acquire the instance\n\tpa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\t\/\/ accept again\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\tASSERT_EQ(pr_preempt->iid, ar->iid);\n\tASSERT_EQ(pr_preempt->ballot, ar->ballot);\n\tASSERT_EQ(value_size, ar->value_size);\n\tASSERT_STREQ(value, ar->value);\n\t\n\taa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, value_size};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n\taa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, value_size};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\t\n\t\n\tfree(ar);\n\tfree(pr_preempt);\n}\n\nTEST_F(ProposerTest, PreparedCount) {\n\tint count = 10;\n\tprepare_req pr;\n\tprepare_ack pa;\n\taccept_req* ar;\n\tchar value[] = \"a value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tpr = proposer_prepare(p);\n\t\tproposer_propose(p, value, value_size);\n\t\tASSERT_EQ(i + 1, proposer_prepared_count(p));\n\t}\n\t\n\tfor (size_t i = 0; i < count; ++i)\n\t\tproposer_accept(p);\n\tASSERT_EQ(count, proposer_prepared_count(p));\n\t\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tpa = (prepare_ack) {0, i+1, pr.ballot, 0, 0};\n\t\tproposer_receive_prepare_ack(p, &pa);\n\t\tpa = (prepare_ack) {1, i+1, pr.ballot, 0, 0};\n\t\tproposer_receive_prepare_ack(p, &pa);\n\t\tar = proposer_accept(p);\n\t\tfree(ar);\n\t\tASSERT_EQ(count-(i+1), proposer_prepared_count(p));\n\t}\n}\n<commit_msg>Improves AcceptPreemptedTest.<commit_after>#include \"gtest.h\"\n#include \"proposer.h\"\n\nclass ProposerTest : public testing::Test {\nprotected:\n\n\tint id;\n\tint instances;\n\tstruct proposer* p;\n\n\tvirtual void SetUp() {\n\t\tid = 2;\n\t\tinstances = 100;\n\t\tp = proposer_new(id, instances);\n\t}\n\t\n\tvirtual void TearDown() { }\n};\n\nTEST_F(ProposerTest, Prepare) {\n\tint count = 10;\n\tprepare_req pr;\n\tfor (int i = 0; i < count; ++i) {\n\t\tpr = proposer_prepare(p);\n\t\tASSERT_EQ(pr.iid, i+1);\n\t\tASSERT_EQ(pr.ballot, id + MAX_N_OF_PROPOSERS);\n\t}\n\tASSERT_EQ(count, proposer_prepared_count(p));\n}\n\nTEST_F(ProposerTest, PrepareAndAccept) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\taccept_req* ar;\n\taccept_ack aa;\n\t\n\tpr = proposer_prepare(p);\n\n\t\/\/ aid, iid, bal, val_bal, val_size\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};\t\n\tproposer_receive_prepare_ack(p, &pa);\n\tpa = (prepare_ack) {2, pr.iid, pr.ballot, 0, 0};\n\tproposer_receive_prepare_ack(p, &pa);\n\t\n\t\/\/ we have no value to propose!\n\tASSERT_EQ(proposer_accept(p), (void*)NULL);\n\t\n\tproposer_propose(p, (char*)\"value\", 6);\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (accept_req*)NULL);\n\tASSERT_EQ(ar->iid, pr.iid);\n\tASSERT_EQ(ar->ballot, pr.ballot);\n\tASSERT_EQ(ar->value_size, 6);\n\tASSERT_STREQ(ar->value, \"value\");\n\t\n\t\/\/ aid, iid, bal, val_bal, final, size\n\tprepare_req* req;\n\taa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n\taa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n}\n\nTEST_F(ProposerTest, PreparePreempted) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\tprepare_req* pr_preempt;\n\taccept_req* ar;\n\tchar value[] = \"some value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tpr = proposer_prepare(p);\n\tproposer_propose(p, value, value_size);\n\t\n\t\/\/ preempt! proposer receives a different ballot...\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot+1, 0, 0};\n\tpr_preempt = proposer_receive_prepare_ack(p, &pa);\n\tASSERT_NE((void*)NULL, pr_preempt);\n\tASSERT_EQ(pr_preempt->iid, pr.iid);\n\tASSERT_GT(pr_preempt->ballot, pr.ballot);\n\t\n\tpa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\tASSERT_EQ(ar->iid, pr_preempt->iid);\n\tASSERT_EQ(ar->ballot, pr_preempt->ballot);\n\tASSERT_EQ(ar->value_size, value_size);\n\tASSERT_STREQ(ar->value, value);\n\t\n\tfree(ar);\n\tfree(pr_preempt);\n}\n\nTEST_F(ProposerTest, AcceptPreempted) {\n\tprepare_req pr;\n\tprepare_ack pa;\n\tprepare_req* pr_preempt;\n\taccept_req* ar;\n\taccept_ack aa;\n\tchar value[] = \"some value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tpr = proposer_prepare(p);\n\tproposer_propose(p, value, value_size);\n\t\n\tpa = (prepare_ack) {0, pr.iid, pr.ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr.iid, pr.ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\t\n\t\/\/ preempt! proposer receives accept nack\n\taa = (accept_ack) {0, ar->iid, ar->ballot+1, 0, 0, 0};\n\tpr_preempt = proposer_receive_accept_ack(p, &aa);\t\n\tASSERT_NE((void*)NULL, pr_preempt);\n\tASSERT_EQ(pr_preempt->iid, pr.iid);\n\tASSERT_GT(pr_preempt->ballot, ar->ballot);\n\tfree(ar);\n\t\n\t\/\/ check that proposer pushed the instance back \n\t\/\/ to the prepare phase\n\tASSERT_EQ(proposer_prepared_count(p), 1);\n\t\n\t\/\/ finally acquire the instance\n\tpa = (prepare_ack) {0, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\tpa = (prepare_ack) {1, pr_preempt->iid, pr_preempt->ballot, 0, 0};\n\tASSERT_EQ(proposer_receive_prepare_ack(p, &pa), (void*)NULL);\n\t\n\t\/\/ accept again\n\tar = proposer_accept(p);\n\tASSERT_NE(ar, (void*)NULL);\n\tASSERT_EQ(pr_preempt->iid, ar->iid);\n\tASSERT_EQ(pr_preempt->ballot, ar->ballot);\n\tASSERT_EQ(value_size, ar->value_size);\n\tASSERT_STREQ(value, ar->value);\n\t\n\taa = (accept_ack) {0, ar->iid, ar->ballot, ar->ballot, 0, value_size};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\n\taa = (accept_ack) {1, ar->iid, ar->ballot, ar->ballot, 0, value_size};\n\tASSERT_EQ(proposer_receive_accept_ack(p, &aa), (void*)NULL);\t\n\t\n\tfree(ar);\n\tfree(pr_preempt);\n}\n\nTEST_F(ProposerTest, PreparedCount) {\n\tint count = 10;\n\tprepare_req pr;\n\tprepare_ack pa;\n\taccept_req* ar;\n\tchar value[] = \"a value\";\n\tint value_size = strlen(value) + 1;\n\t\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tpr = proposer_prepare(p);\n\t\tproposer_propose(p, value, value_size);\n\t\tASSERT_EQ(i + 1, proposer_prepared_count(p));\n\t}\n\t\n\tfor (size_t i = 0; i < count; ++i)\n\t\tproposer_accept(p);\n\tASSERT_EQ(count, proposer_prepared_count(p));\n\t\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tpa = (prepare_ack) {0, i+1, pr.ballot, 0, 0};\n\t\tproposer_receive_prepare_ack(p, &pa);\n\t\tpa = (prepare_ack) {1, i+1, pr.ballot, 0, 0};\n\t\tproposer_receive_prepare_ack(p, &pa);\n\t\tar = proposer_accept(p);\n\t\tfree(ar);\n\t\tASSERT_EQ(count-(i+1), proposer_prepared_count(p));\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixes bug in views on gtk where we wouldn't necessarily paint correctly on an expose. This happened if between the time we told Gtk we needed to paint and the time we got the expose event more paints were scheduled. In this case, because we were double buffered, GTK would clip to the original region we scheduled the paint for. The fix is to turn off double buffering as we're double buffering ourself.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"node.hh\"\n\n\nnamespace doanimate {\n\tnamespace nodes {\n\t\tvoid default_node::update() {\n\t\t\toutputs = implementation(inputs);\n\t\t}\n\n\n\t\tstd::vector<types::value>& default_node::get_inputs() {\n\t\t\treturn inputs;\n\t\t}\n\n\t\t \n\t\tconst std::vector<types::value>& default_node::get_outputs() {\n\t\t\treturn outputs;\n\t\t}\n\n\n\t\tconst std::vector<types::type_info>& default_node::get_input_type_infos() {\n\t\t\treturn input_type_infos;\n\t\t}\n\n\n\t\tconst std::vector<types::type_info>& default_node::get_output_type_infos() {\n\t\t\treturn output_type_infos;\n\t\t}\n\t}\n}\n<commit_msg>Changed type names to lowercase in node.cc<commit_after>#include \"node.hh\"\n\n\nnamespace doanimate {\n\tnamespace nodes {\n\t\tvoid DefaultNode::update() {\n\t\t\toutputs = implementation(inputs);\n\t\t}\n\n\n\t\tstd::vector<types::Value>& DefaultNode::get_inputs() {\n\t\t\treturn inputs;\n\t\t}\n\n\t\t \n\t\tconst std::vector<types::Value>& DefaultNode::get_outputs() {\n\t\t\treturn outputs;\n\t\t}\n\n\n\t\tconst std::vector<types::TypeInfo>& DefaultNode::get_input_type_infos() {\n\t\t\treturn input_type_infos;\n\t\t}\n\n\n\t\tconst std::vector<types::TypeInfo>& DefaultNode::get_output_type_infos() {\n\t\t\treturn output_type_infos;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ SimClientTest.cpp : Defines the entry point for the console application.\n\/\/\n#include <string>\n#include <atlbase.h>\n#include <iostream>\n\n#include \"SimIntefaceHelper.h\"\n#include \"CwSidetoneNotifyImpl.h\"\n\nnamespace {\n void DoWithCOM();\n int DemoSidetone(IKnowDispatchIsManagerPtr pMgr);\n void DemoCwQso(IKnowDispatchIsManagerPtr pMgr);\n void DemoRtty(IKnowDispatchIsManagerPtr pMgr);\n}\n\nint main(int argc, char* argv[])\n{\n ::CoInitialize(0);\n DoWithCOM(); \/\/ COM objects must be released BEFORE CoUninitialize\n ::CoUninitialize();\n\treturn 0;\n}\n\nnamespace\n{\n void DoWithCOM()\n {\n try\n {\n\n \/\/ For the interfaces named:\n \/\/ IKnowDispatchIsManager\n \/\/ IKnowDispatchIsCwSimulator\n \/\/ IKnowDispatchIsRadioSimulator\n \/\/ If we used an admin install of the interfaces, we could make\n \/\/ Windows \"marshall\" the above interfaces..\n \/\/ \n \/\/ But they are just IDispatch which has a built-in marshaller. Sowe just use \n \/\/ some goop in SimInterfaceHelper.h to convince the Microsoft C++ compiler to \n \/\/ attach its IDispatch helpers to an unaddorned IDispatch interface.\n\n \/\/ The simulator manager registers itself in the ROT when the user runs it.\n IKnowDispatchIsManagerPtr pMgr;\n pMgr.GetActiveObject(__uuidof(ContestSuperSimDispLib::SuperSimManager));\n\n char c; \/\/ place to read for cin to block for user input\n if (!pMgr)\n {\n std::cout << \"SuperSimManager not active\" << std::endl;\n std::cin.read(&c, 1);\n return;\n }\n\n \/\/ The manager object provides access to the virtual radio objects.\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(\n 0 \/* zero-based index of radio number *\/\n );\n\n \/\/ The simulator puts its virtual radios on frequencies of its own choosing. See what that is:\n std::cout << \"Got radio of frequency: \" << pRadio->CenterFrequency << \" KHz. ENTER to continue\" << std::endl;\n std::cin.read(&c, 1);\n\n int yesno = DemoSidetone(pMgr);\n if (yesno == IDNO)\n {\n pMgr->GetCwSidetoneGenerator(0); \/\/ make simulator let go of our notifier\n return;\n }\n\n DemoCwQso(pMgr);\n\n yesno = ::MessageBox(0, \"Try RTTY?\", \"SimClientTest\", MB_YESNO);\n\n if (yesno == IDYES)\n {\n DemoRtty(pMgr);\n }\n\n }\n catch (const std::exception &e)\n {\n std::cerr << \"Caught exception \" << e.what() << std::endl;\n }\n catch (const _com_error &e)\n {\n std::cerr << \"Caught COM exception \" << e.ErrorMessage() << std::endl;\n }\n }\n\n int DemoSidetone(IKnowDispatchIsManagerPtr pMgr)\n {\n \/\/ Nothing here but sidetone generation\n \/\/ Client of simulator can call its winkey emulation or call on\n \/\/ its ICwSimulator, but its redundant to do both.\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n CComPtr<MyNotifier>pNotify = new MyNotifier();\n\n IKnowDispatchIsCwSimulatorPtr pCwSidetone =\n pMgr->GetCwSidetoneGenerator(pNotify);\n\n if (!pCwSidetone)\n {\n std::cout << \"GetCwSidetoneGenerate returned empty!\" << std::endl;\n return IDNO;\n }\n\n pCwSidetone->PutWPM(25);\n pCwSidetone->QueueToTransmitText(\"test de w5xd\");\n pCwSidetone->QueueWpmChange(35);\n pCwSidetone->QueueToTransmitText(\"test test w5xd\");\n int yesno = ::MessageBox(0, \"Yes to continue, No to Exit\", \"SimClientTest\", MB_YESNO);\n pCwSidetone->AbortTransmission(); \/\/ if you OK fast enough, the transmission in progress will be aborted\n return yesno;\n }\n\n void DemoCwQso(IKnowDispatchIsManagerPtr pMgr)\n {\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n\n \/\/ see if we can get the simulator to answer us\n _bstr_t msg(\"CQ TEST DE W5XD\");\n\n \/\/ Demonstrate the timing sequence.\n CComPtr<MyNotifier>pNotify = new MyNotifier(\n \/\/ this callback happens when the CQ finishes..\n \/\/ Will ALSO get call backs for WinKey-initiated message finished...\n \/\/ should not support both.\n [pRadio, msg]() {\n pRadio->MessageCompletedNow(\"CW\", msg); \/\/ tell the simulator our CQ is over\n });\n\n IKnowDispatchIsCwSimulatorPtr pCwSidetone = pMgr->GetCwSidetoneGenerator(pNotify);\n pCwSidetone->PutWPM(25); \/\/ Lets do a typical contest CQ speed\n\n for (;;)\n {\n pRadio->MessageStartedNow();\n pCwSidetone->QueueToTransmitText(msg);\n int yesno = ::MessageBox(0, \"CQ again? No to Exit\", \"SimClientTest\", MB_YESNO);\n if (yesno == IDNO)\n break;\n }\n }\n\n void DemoRtty(IKnowDispatchIsManagerPtr pMgr)\n {\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n\n \/\/ tune the virtual radio to RTTY\n \/\/ This demo would work on the simulator's default frequency, but\n \/\/ this one is a more conventional RTTY frequency.\n pRadio->SetListenFrequency(7080, \"RY\");\n\n \/\/ see if we can get the simulator to answer us\n _bstr_t msg(\"CQ TEST DE W5XD\");\n\n for (;;)\n {\n pRadio->MessageStartedNow();\n bool stop = ::MessageBox(0, \"Simulator thinks are sending RTTY now.\\r\\n OK to end the CQ (or cancel)\", \"SimClientTest\", MB_YESNOCANCEL) != IDYES;\n if (stop)\n break;\n pRadio->MessageCompletedNow(\"RY\", msg); \/\/ we call CQ in RTTY mode...the simulator may answer\n stop = ::MessageBox(0, \"Again?\", \"SimClientTest\", MB_YESNO) != IDYES;\n\n }\n\n }\n\n}<commit_msg>more commentary<commit_after>\/\/ SimClientTest.cpp : Defines the entry point for the console application.\n\/\/\n#include <string>\n#include <atlbase.h>\n#include <iostream>\n\n#include \"SimIntefaceHelper.h\"\n#include \"CwSidetoneNotifyImpl.h\"\n\nnamespace {\n void DoWithCOM();\n int DemoSidetone(IKnowDispatchIsManagerPtr pMgr);\n void DemoCwQso(IKnowDispatchIsManagerPtr pMgr);\n void DemoRtty(IKnowDispatchIsManagerPtr pMgr);\n}\n\nint main(int argc, char* argv[])\n{\n ::CoInitialize(0);\n DoWithCOM(); \/\/ COM objects must be released BEFORE CoUninitialize\n ::CoUninitialize();\n\treturn 0;\n}\n\nnamespace\n{\n void DoWithCOM()\n {\n try\n {\n\n \/\/ For the interfaces named:\n \/\/ IKnowDispatchIsManager\n \/\/ IKnowDispatchIsCwSimulator\n \/\/ IKnowDispatchIsRadioSimulator\n \/\/ If we used an admin install of the interfaces, we could make\n \/\/ Windows \"marshall\" the above interfaces..\n \/\/ \n \/\/ But they are just IDispatch which has a built-in marshaller. Sowe just use \n \/\/ some goop in SimInterfaceHelper.h to convince the Microsoft C++ compiler to \n \/\/ attach its IDispatch helpers to an unaddorned IDispatch interface.\n\n \/\/ The simulator manager registers itself in the ROT when the user runs it.\n IKnowDispatchIsManagerPtr pMgr;\n pMgr.GetActiveObject(__uuidof(ContestSuperSimDispLib::SuperSimManager));\n\n char c; \/\/ place to read for cin to block for user input\n if (!pMgr)\n {\n std::cout << \"SuperSimManager not active\" << std::endl;\n std::cin.read(&c, 1);\n return;\n }\n\n \/\/ The manager object provides access to the virtual radio objects.\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(\n 0 \/* zero-based index of radio number *\/\n );\n\n \/\/ The simulator puts its virtual radios on frequencies of its own choosing. See what that is:\n std::cout << \"Got radio of frequency: \" << pRadio->CenterFrequency << \" KHz. ENTER to continue\" << std::endl;\n std::cin.read(&c, 1);\n\n int yesno = DemoSidetone(pMgr);\n if (yesno == IDNO)\n {\n pMgr->GetCwSidetoneGenerator(0); \/\/ make simulator let go of our notifier\n return;\n }\n\n DemoCwQso(pMgr);\n\n \/\/ Why does this demo switch back and forth between using cout\/cin and \n \/\/ MessageBox?\n \/\/ The distinction is important because we called CoInitialize(0); (way\n \/\/ back in the first line in main).\n \/\/ We won't get any COM callbacks while stuck reading cin. But we\n \/\/ will if we're in MessageBox. \n \/\/ That difference is important to the simulator for only one scenario:\n \/\/ when you pass a non-null argument to GetCwSidetoneGenerator()\n \/\/ The object you pass will only get called through a Windows message\n yesno = ::MessageBox(0, \"Try RTTY?\", \"SimClientTest\", MB_YESNO);\n\n if (yesno == IDYES)\n DemoRtty(pMgr);\n\n }\n catch (const std::exception &e)\n {\n std::cerr << \"Caught exception \" << e.what() << std::endl;\n }\n catch (const _com_error &e)\n {\n std::cerr << \"Caught COM exception \" << e.ErrorMessage() << std::endl;\n }\n }\n\n int DemoSidetone(IKnowDispatchIsManagerPtr pMgr)\n {\n \/\/ Nothing here but sidetone generation\n \/\/ Client of simulator can call its winkey emulation or call on\n \/\/ its ICwSimulator, but its redundant to do both.\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n CComPtr<MyNotifier>pNotify = new MyNotifier();\n\n IKnowDispatchIsCwSimulatorPtr pCwSidetone =\n pMgr->GetCwSidetoneGenerator(pNotify);\n\n if (!pCwSidetone)\n {\n std::cout << \"GetCwSidetoneGenerate returned empty!\" << std::endl;\n return IDNO;\n }\n\n pCwSidetone->PutWPM(25);\n pCwSidetone->QueueToTransmitText(\"test de w5xd\");\n pCwSidetone->QueueWpmChange(35);\n pCwSidetone->QueueToTransmitText(\"test test w5xd\");\n int yesno = ::MessageBox(0, \"Yes to continue, No to Exit\", \"SimClientTest\", MB_YESNO);\n pCwSidetone->AbortTransmission(); \/\/ if you OK fast enough, the transmission in progress will be aborted\n return yesno;\n }\n\n void DemoCwQso(IKnowDispatchIsManagerPtr pMgr)\n {\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n\n \/\/ see if we can get the simulator to answer us\n _bstr_t msg(\"CQ TEST DE W5XD\");\n\n \/\/ Demonstrate the timing sequence.\n CComPtr<MyNotifier>pNotify = new MyNotifier(\n \/\/ this callback happens when the CQ finishes..\n \/\/ Will ALSO get call backs for WinKey-initiated message finished...\n \/\/ should not support both.\n [pRadio, msg]() {\n pRadio->MessageCompletedNow(\"CW\", msg); \/\/ tell the simulator our CQ is over\n });\n\n IKnowDispatchIsCwSimulatorPtr pCwSidetone = pMgr->GetCwSidetoneGenerator(pNotify);\n pCwSidetone->PutWPM(25); \/\/ Lets do a typical contest CQ speed\n\n for (;;)\n {\n pRadio->MessageStartedNow();\n pCwSidetone->QueueToTransmitText(msg);\n int yesno = ::MessageBox(0, \"CQ again? No to Exit\", \"SimClientTest\", MB_YESNO);\n if (yesno == IDNO)\n break;\n }\n }\n\n void DemoRtty(IKnowDispatchIsManagerPtr pMgr)\n {\n IKnowDispatchIsRadioSimulatorPtr pRadio = pMgr->GetSimulatorForRadio(0);\n\n \/\/ tune the virtual radio to RTTY\n \/\/ This demo would work on the simulator's default frequency, but\n \/\/ this one is a more conventional RTTY frequency.\n pRadio->SetListenFrequency(7080, \"RY\");\n\n \/\/ see if we can get the simulator to answer us\n _bstr_t msg(\"CQ TEST DE W5XD\");\n\n for (;;)\n {\n pRadio->MessageStartedNow();\n bool stop = ::MessageBox(0, \"Simulator thinks are sending RTTY now.\\r\\n OK to end the CQ (or cancel)\", \"SimClientTest\", MB_YESNOCANCEL) != IDYES;\n if (stop)\n break;\n pRadio->MessageCompletedNow(\"RY\", msg); \/\/ we call CQ in RTTY mode...the simulator may answer\n stop = ::MessageBox(0, \"Again?\", \"SimClientTest\", MB_YESNO) != IDYES;\n\n }\n\n }\n\n}<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#include <mapnik\/version.hpp>\n#include <mapnik\/debug.hpp>\n#include <mapnik\/marker.hpp>\n#include <mapnik\/marker_cache.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/svg\/svg_renderer_agg.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/program_options.hpp>\n#pragma GCC diagnostic pop\n\n#include \"agg_rasterizer_scanline_aa.h\"\n#include \"agg_basics.h\"\n#include \"agg_rendering_buffer.h\"\n#include \"agg_renderer_base.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_scanline_u.h\"\n\n#include <libxml\/parser.h> \/\/ for xmlInitParser(), xmlCleanupParser()\n\nstruct main_marker_visitor\n{\n main_marker_visitor(std::string const& svg_name,\n bool verbose,\n bool auto_open)\n : svg_name_(svg_name),\n verbose_(verbose),\n auto_open_(auto_open) {}\n\n int operator() (mapnik::marker_svg const& marker)\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::rasterizer_scanline_aa<> ras_ptr;\n agg::scanline_u8 sl;\n\n double opacity = 1;\n int w = marker.width();\n int h = marker.height();\n if (verbose_)\n {\n std::clog << \"found width of '\" << w << \"' and height of '\" << h << \"'\\n\";\n }\n \/\/ 10 pixel buffer to avoid edge clipping of 100% svg's\n mapnik::image_rgba8 im(w+0,h+0);\n agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box();\n mapnik::coord<double,2> c = bbox.center();\n \/\/ center the svg marker on '0,0'\n agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);\n \/\/ render the marker at the center of the marker box\n mtx.translate(0.5 * im.width(), 0.5 * im.height());\n\n mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source());\n mapnik::svg::svg_path_adapter svg_path(stl_storage);\n mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter,\n agg::pod_bvector<mapnik::svg::path_attributes>,\n renderer_solid,\n agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path,\n marker.get_data()->attributes());\n\n svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);\n\n std::string png_name(svg_name_);\n boost::algorithm::ireplace_last(png_name,\".svg\",\".png\");\n demultiply_alpha(im);\n mapnik::save_to_file<mapnik::image_rgba8>(im,png_name,\"png\");\n int status = 0;\n if (auto_open_)\n {\n std::ostringstream s;\n#ifdef DARWIN\n s << \"open \" << png_name;\n#else\n s << \"xdg-open \" << png_name;\n#endif\n int ret = system(s.str().c_str());\n if (ret != 0)\n status = ret;\n }\n std::clog << \"rendered to: \" << png_name << \"\\n\";\n return status;\n }\n\n \/\/ default\n template <typename T>\n int operator() (T const&)\n {\n std::clog << \"svg2png error: '\" << svg_name_ << \"' is not a valid vector!\\n\";\n return -1;\n }\n\n private:\n std::string const& svg_name_;\n bool verbose_;\n bool auto_open_;\n};\n\nint main (int argc,char** argv)\n{\n namespace po = boost::program_options;\n\n bool verbose = false;\n bool auto_open = false;\n int status = 0;\n std::vector<std::string> svg_files;\n mapnik::logger::instance().set_severity(mapnik::logger::error);\n\n try\n {\n po::options_description desc(\"svg2png utility\");\n desc.add_options()\n (\"help,h\", \"produce usage message\")\n (\"version,V\",\"print version string\")\n (\"verbose,v\",\"verbose output\")\n (\"open\",\"automatically open the file after rendering (os x only)\")\n (\"svg\",po::value<std::vector<std::string> >(),\"svg file to read\")\n ;\n\n po::positional_options_description p;\n p.add(\"svg\",-1);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n po::notify(vm);\n\n if (vm.count(\"version\"))\n {\n std::clog <<\"version \" << MAPNIK_VERSION_STRING << std::endl;\n return 1;\n }\n\n if (vm.count(\"help\"))\n {\n std::clog << desc << std::endl;\n return 1;\n }\n\n if (vm.count(\"verbose\"))\n {\n verbose = true;\n }\n\n if (vm.count(\"open\"))\n {\n auto_open = true;\n }\n\n if (vm.count(\"svg\"))\n {\n svg_files=vm[\"svg\"].as< std::vector<std::string> >();\n }\n else\n {\n std::clog << \"please provide an svg file!\" << std::endl;\n return -1;\n }\n\n std::vector<std::string>::const_iterator itr = svg_files.begin();\n if (itr == svg_files.end())\n {\n std::clog << \"no svg files to render\" << std::endl;\n return 0;\n }\n\n xmlInitParser();\n\n while (itr != svg_files.end())\n {\n std::string svg_name (*itr++);\n if (verbose)\n {\n std::clog << \"found: \" << svg_name << \"\\n\";\n }\n\n std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false);\n main_marker_visitor visitor(svg_name, verbose, auto_open);\n status = mapnik::util::apply_visitor(visitor, *marker);\n }\n }\n catch (...)\n {\n std::clog << \"Exception of unknown type!\" << std::endl;\n xmlCleanupParser();\n return -1;\n }\n\n \/\/ only call this once, on exit\n \/\/ to make sure valgrind output is clean\n \/\/ http:\/\/xmlsoft.org\/xmlmem.html\n xmlCleanupParser();\n return status;\n}\n<commit_msg>catch std::exception to get better stderr<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#include <mapnik\/version.hpp>\n#include <mapnik\/debug.hpp>\n#include <mapnik\/marker.hpp>\n#include <mapnik\/marker_cache.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/svg\/svg_renderer_agg.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/program_options.hpp>\n#pragma GCC diagnostic pop\n\n#include \"agg_rasterizer_scanline_aa.h\"\n#include \"agg_basics.h\"\n#include \"agg_rendering_buffer.h\"\n#include \"agg_renderer_base.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_scanline_u.h\"\n\n#include <libxml\/parser.h> \/\/ for xmlInitParser(), xmlCleanupParser()\n\nstruct main_marker_visitor\n{\n main_marker_visitor(std::string const& svg_name,\n bool verbose,\n bool auto_open)\n : svg_name_(svg_name),\n verbose_(verbose),\n auto_open_(auto_open) {}\n\n int operator() (mapnik::marker_svg const& marker)\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::rasterizer_scanline_aa<> ras_ptr;\n agg::scanline_u8 sl;\n\n double opacity = 1;\n int w = marker.width();\n int h = marker.height();\n if (verbose_)\n {\n std::clog << \"found width of '\" << w << \"' and height of '\" << h << \"'\\n\";\n }\n \/\/ 10 pixel buffer to avoid edge clipping of 100% svg's\n mapnik::image_rgba8 im(w+0,h+0);\n agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box();\n mapnik::coord<double,2> c = bbox.center();\n \/\/ center the svg marker on '0,0'\n agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);\n \/\/ render the marker at the center of the marker box\n mtx.translate(0.5 * im.width(), 0.5 * im.height());\n\n mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source());\n mapnik::svg::svg_path_adapter svg_path(stl_storage);\n mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter,\n agg::pod_bvector<mapnik::svg::path_attributes>,\n renderer_solid,\n agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path,\n marker.get_data()->attributes());\n\n svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);\n\n std::string png_name(svg_name_);\n boost::algorithm::ireplace_last(png_name,\".svg\",\".png\");\n demultiply_alpha(im);\n mapnik::save_to_file<mapnik::image_rgba8>(im,png_name,\"png\");\n int status = 0;\n if (auto_open_)\n {\n std::ostringstream s;\n#ifdef DARWIN\n s << \"open \" << png_name;\n#else\n s << \"xdg-open \" << png_name;\n#endif\n int ret = system(s.str().c_str());\n if (ret != 0)\n status = ret;\n }\n std::clog << \"rendered to: \" << png_name << \"\\n\";\n return status;\n }\n\n \/\/ default\n template <typename T>\n int operator() (T const&)\n {\n std::clog << \"svg2png error: '\" << svg_name_ << \"' is not a valid vector!\\n\";\n return -1;\n }\n\n private:\n std::string const& svg_name_;\n bool verbose_;\n bool auto_open_;\n};\n\nint main (int argc,char** argv)\n{\n namespace po = boost::program_options;\n\n bool verbose = false;\n bool auto_open = false;\n int status = 0;\n std::vector<std::string> svg_files;\n mapnik::logger::instance().set_severity(mapnik::logger::error);\n\n try\n {\n po::options_description desc(\"svg2png utility\");\n desc.add_options()\n (\"help,h\", \"produce usage message\")\n (\"version,V\",\"print version string\")\n (\"verbose,v\",\"verbose output\")\n (\"open\",\"automatically open the file after rendering (os x only)\")\n (\"svg\",po::value<std::vector<std::string> >(),\"svg file to read\")\n ;\n\n po::positional_options_description p;\n p.add(\"svg\",-1);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n po::notify(vm);\n\n if (vm.count(\"version\"))\n {\n std::clog <<\"version \" << MAPNIK_VERSION_STRING << std::endl;\n return 1;\n }\n\n if (vm.count(\"help\"))\n {\n std::clog << desc << std::endl;\n return 1;\n }\n\n if (vm.count(\"verbose\"))\n {\n verbose = true;\n }\n\n if (vm.count(\"open\"))\n {\n auto_open = true;\n }\n\n if (vm.count(\"svg\"))\n {\n svg_files=vm[\"svg\"].as< std::vector<std::string> >();\n }\n else\n {\n std::clog << \"please provide an svg file!\" << std::endl;\n return -1;\n }\n\n std::vector<std::string>::const_iterator itr = svg_files.begin();\n if (itr == svg_files.end())\n {\n std::clog << \"no svg files to render\" << std::endl;\n return 0;\n }\n\n xmlInitParser();\n\n while (itr != svg_files.end())\n {\n std::string svg_name (*itr++);\n if (verbose)\n {\n std::clog << \"found: \" << svg_name << \"\\n\";\n }\n\n std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false);\n main_marker_visitor visitor(svg_name, verbose, auto_open);\n status = mapnik::util::apply_visitor(visitor, *marker);\n }\n }\n catch (std::exception const& ex)\n {\n std::clog << \"Exception caught:\" << ex.what() << std::endl;\n xmlCleanupParser();\n return -1;\n }\n catch (...)\n {\n std::clog << \"Exception of unknown type!\" << std::endl;\n xmlCleanupParser();\n return -1;\n }\n\n \/\/ only call this once, on exit\n \/\/ to make sure valgrind output is clean\n \/\/ http:\/\/xmlsoft.org\/xmlmem.html\n xmlCleanupParser();\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DateConversion.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 00:58:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATECONVERSION_HXX_\n#define _CONNECTIVITY_DATECONVERSION_HXX_\n\n#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_\n#include <com\/sun\/star\/util\/Date.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_TIME_HPP_\n#include <com\/sun\/star\/util\/Time.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_\n#include <com\/sun\/star\/util\/DateTime.hpp>\n#endif\n\nnamespace connectivity\n{\n class DateConversion\n {\n public:\n static sal_Int32 toINT32(const ::com::sun::star::util::Date&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int32 toINT32(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int64 toINT64(const ::com::sun::star::util::DateTime&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int32 getMsFromTime(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::Date&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::DateTime&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static ::com::sun::star::util::Date toDate(double,const ::com::sun::star::util::Date& =::com::sun::star::util::Date(01,01,1900))\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::Date();\n }\n static ::com::sun::star::util::Time toTime(double)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::Time();\n }\n static ::com::sun::star::util::DateTime toDateTime(double,const ::com::sun::star::util::Date& =::com::sun::star::util::Date(01,01,1900))\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::DateTime();\n }\n };\n}\n#endif \/\/ _CONNECTIVITY_DATECONVERSION_HXX_\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.276); FILE MERGED 2008\/04\/01 10:52:40 thb 1.4.276.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:14 rt 1.4.276.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DateConversion.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATECONVERSION_HXX_\n#define _CONNECTIVITY_DATECONVERSION_HXX_\n\n#include <com\/sun\/star\/util\/Date.hpp>\n#include <com\/sun\/star\/util\/Time.hpp>\n#include <com\/sun\/star\/util\/DateTime.hpp>\n\nnamespace connectivity\n{\n class DateConversion\n {\n public:\n static sal_Int32 toINT32(const ::com::sun::star::util::Date&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int32 toINT32(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int64 toINT64(const ::com::sun::star::util::DateTime&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static sal_Int32 getMsFromTime(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::Date&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::Time&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static double toDouble(const ::com::sun::star::util::DateTime&)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return 0;\n }\n static ::com::sun::star::util::Date toDate(double,const ::com::sun::star::util::Date& =::com::sun::star::util::Date(01,01,1900))\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::Date();\n }\n static ::com::sun::star::util::Time toTime(double)\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::Time();\n }\n static ::com::sun::star::util::DateTime toDateTime(double,const ::com::sun::star::util::Date& =::com::sun::star::util::Date(01,01,1900))\n {\n OSL_ENSURE(0,\"Please use DBConversion instead!\");\n return ::com::sun::star::util::DateTime();\n }\n };\n}\n#endif \/\/ _CONNECTIVITY_DATECONVERSION_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"savefmtdialog.h\"\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QApplication>\n#include <QStyle>\n\nusing namespace Vipster;\n\nMainWindow::MainWindow(QString path, QWidget *parent):\n QMainWindow{parent},\n ui{new Ui::MainWindow},\n path{path}\n{\n ui->setupUi(this);\n connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);\n connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);\n setupUI();\n newMol();\n}\n\nMainWindow::MainWindow(QString path, std::vector<IO::Data> &&d, QWidget *parent):\n QMainWindow{parent},\n ui{new Ui::MainWindow},\n path{path}\n{\n ui->setupUi(this);\n setupUI();\n connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);\n connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);\n for(auto&& mol: d){\n newData(std::move(mol));\n }\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::setupUI()\n{\n ui->firstStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));\n ui->preStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n ui->nextStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekForward));\n ui->lastStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));\n \/\/ setup left dock-area\n baseWidgets = {\n ui->paramDock,\n ui->configDock,\n ui->settingsDock,\n ui->mpseDock,\n ui->pseDock,\n ui->dataDock,\n };\n for(auto& w: baseWidgets){\n tabifyDockWidget(ui->molDock, w);\n }\n ui->molDock->raise();\n \/\/ setup right dock-area\n toolWidgets = {\n ui->scriptDock,\n ui->pickDock,\n ui->cellModDock,\n ui->millerDock,\n };\n for(auto& w: toolWidgets){\n auto action = ui->toolBar->addAction(w->windowTitle());\n action->setCheckable(true);\n connect(action, &QAction::toggled, w, &QWidget::setVisible);\n w->hide();\n }\n#ifdef Q_OS_MACOS\n setDockOptions(dockOptions()^VerticalTabs);\n#endif\n \/\/ fill in global PSE\n ui->pseWidget->setPSE(&Vipster::pse);\n \/\/ fill in menu-options\n for(const auto& pair:IOPlugins){\n const auto& param_map = Vipster::params[pair.first];\n if(!param_map.empty()){\n auto* param_menu = ui->menuLoad_Parameter_set->addMenu(\n QString::fromStdString(pair.second->name));\n for(const auto& p: param_map){\n param_menu->addAction(QString::fromStdString(p.first),\n this, &MainWindow::loadParam);\n }\n }\n const auto& conf_map = Vipster::configs[pair.first];\n if(!conf_map.empty()){\n auto* conf_menu = ui->menuLoad_IO_Config->addMenu(\n QString::fromStdString(pair.second->name));\n for(const auto& p: conf_map){\n conf_menu->addAction(QString::fromStdString(p.first),\n this, &MainWindow::loadConfig);\n }\n }\n }\n}\n\nvoid MainWindow::updateWidgets(uint8_t change)\n{\n ui->openGLWidget->updateWidget(change);\n ui->molWidget->updateWidget(change);\n for(auto& w: baseWidgets){\n static_cast<BaseWidget*>(w->widget())->updateWidget(change);\n }\n for(auto& w: toolWidgets){\n static_cast<BaseWidget*>(w->widget())->updateWidget(change);\n }\n}\n\nvoid MainWindow::setFmt(int i, bool apply, bool scale)\n{\n fmt = static_cast<AtomFmt>(i);\n if(apply){\n curStep->setFmt(fmt, scale);\n if(curSel){\n curSel->setFmt(fmt);\n }\n updateWidgets(guiStepChanged);\n }else{\n updateWidgets(GuiChange::fmt);\n }\n}\n\nAtomFmt MainWindow::getFmt()\n{\n return fmt;\n}\n\nvoid MainWindow::setMol(int i)\n{\n curMol = &*std::next(molecules.begin(), i);\n int nstep = static_cast<int>(curMol->getNstep());\n if(moldata[curMol].curStep < 0){\n moldata[curMol].curStep = nstep;\n }\n \/\/Step-control\n ui->stepLabel->setText(QString::number(nstep));\n QSignalBlocker boxBlocker(ui->stepEdit);\n QSignalBlocker slideBlocker(ui->stepSlider);\n ui->stepEdit->setMaximum(nstep);\n ui->stepSlider->setMaximum(nstep);\n if(nstep == 1){\n ui->stepEdit->setDisabled(true);\n ui->stepSlider->setDisabled(true);\n }else{\n ui->stepEdit->setEnabled(true);\n ui->stepSlider->setEnabled(true);\n }\n setStep(moldata[curMol].curStep);\n updateWidgets(guiMolChanged);\n}\n\nvoid MainWindow::setStep(int i)\n{\n moldata[curMol].curStep = i;\n curStep = &curMol->getStep(static_cast<size_t>(i-1));\n fmt = curStep->getFmt();\n \/\/ if no previous selection exists, create one, afterwards assign it\n auto& tmpSel = stepdata[curStep].sel;\n if(!tmpSel && curStep){\n tmpSel = std::make_unique<StepSelection>(*curStep);\n }\n curSel = tmpSel.get();\n \/\/Handle control-elements\n if(playTimer.isActive() && (i == static_cast<int>(curMol->getNstep()))){\n playTimer.stop();\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n }\n QSignalBlocker boxBlocker(ui->stepEdit);\n QSignalBlocker slideBlocker(ui->stepSlider);\n ui->stepEdit->setValue(i);\n ui->stepSlider->setValue(i);\n if(i == 1){\n ui->preStepButton->setDisabled(true);\n ui->firstStepButton->setDisabled(true);\n }else{\n ui->preStepButton->setEnabled(true);\n ui->firstStepButton->setEnabled(true);\n }\n if(i == static_cast<int>(curMol->getNstep())){\n ui->nextStepButton->setDisabled(true);\n ui->lastStepButton->setDisabled(true);\n }else{\n ui->nextStepButton->setEnabled(true);\n ui->lastStepButton->setEnabled(true);\n }\n \/\/Update child widgets\n updateWidgets(guiStepChanged);\n}\n\nvoid MainWindow::stepBut(QAbstractButton* but)\n{\n if(but == ui->firstStepButton){\n setStep(1);\n }else if(but == ui->lastStepButton){\n setStep(static_cast<int>(curMol->getNstep()));\n }else if(but == ui->playButton){\n if(playTimer.isActive()){\n playTimer.stop();\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n }else{\n playTimer.start(1000);\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));\n }\n }\n}\n\nvoid MainWindow::editAtoms(QAction* sender)\n{\n if ( sender == ui->actionNew_Atom){\n curStep->newAtom();\n }else if ( sender == ui->actionDelete_Atom_s){\n curSel->delAtoms();\n }else if ( sender == ui->actionHide_Atom_s){\n for(auto& at: *curSel){\n at.properties->flags[AtomFlag::Hidden] = 1;\n }\n }else if ( sender == ui->actionShow_Atom_s){\n for(auto& at: *curSel){\n at.properties->flags[AtomFlag::Hidden] = 0;\n }\n }\n updateWidgets(GuiChange::atoms);\n}\n\nvoid MainWindow::newMol()\n{\n molecules.emplace_back();\n ui->molWidget->registerMol(molecules.back().getName());\n}\n\nvoid MainWindow::newData(IO::Data &&d)\n{\n molecules.push_back(std::move(d.mol));\n ui->molWidget->registerMol(molecules.back().getName());\n if(d.param){\n ui->paramWidget->registerParam(d.fmt, std::move(d.param));\n }\n for(auto& dat: d.data){\n data.push_back(std::move(dat));\n ui->dataWidget->registerData(data.back()->name);\n }\n}\n\nvoid MainWindow::loadMol()\n{\n \/\/ File dialog\n QStringList files;\n QFileDialog fileDiag{this};\n fileDiag.setDirectory(path);\n fileDiag.setFileMode(QFileDialog::ExistingFiles);\n \/\/ Format dialog\n QStringList formats{};\n for(auto &iop: IOPlugins){\n formats << QString::fromStdString(iop.second->name);\n }\n QString fmt_s;\n IOFmt fmt;\n bool got_fmt{false};\n if(fileDiag.exec() != 0){\n files = fileDiag.selectedFiles();\n path = fileDiag.directory();\n if(files.count() != 0){\n fmt_s = QInputDialog::getItem(this, \"Select format\", \"Format:\",\n formats, 0, false, &got_fmt);\n if(got_fmt){\n fmt = static_cast<IOFmt>(formats.indexOf(fmt_s));\n for(auto &file: files){\n newData(readFile(file.toStdString(), fmt));\n }\n }\n }\n }\n}\n\nvoid MainWindow::saveMol()\n{\n QFileDialog fileDiag{this};\n fileDiag.setDirectory(path);\n fileDiag.setAcceptMode(QFileDialog::AcceptSave);\n if(fileDiag.exec() == QDialog::Accepted){\n auto target = fileDiag.selectedFiles()[0].toStdString();\n path = fileDiag.directory();\n SaveFmtDialog sfd{this};\n if(sfd.exec() == QDialog::Accepted){\n writeFile(target, sfd.fmt, *curMol,\n sfd.getParam(), sfd.getConfig(),\n IO::State{static_cast<size_t>(ui->stepSlider->value()-1),\n this->fmt,\n ui->molWidget->getCellFmt()});\n }\n }\n}\n\n\nconst decltype (ParamWidget::params)& MainWindow::getParams() const noexcept\n{\n return ui->paramWidget->params;\n}\n\nconst decltype (ConfigWidget::configs)& MainWindow::getConfigs() const noexcept\n{\n return ui->configWidget->configs;\n}\n\nvoid MainWindow::addExtraData(GUI::Data* dat)\n{\n ui->openGLWidget->addExtraData(dat);\n updateWidgets(GuiChange::extra);\n}\n\nvoid MainWindow::delExtraData(GUI::Data* dat)\n{\n ui->openGLWidget->delExtraData(dat);\n updateWidgets(GuiChange::extra);\n}\n\nconst GUI::GlobalData& MainWindow::getGLGlobals()\n{\n return ui->openGLWidget->globals;\n}\n\nvoid MainWindow::loadParam()\n{\n auto* s = static_cast<QAction*>(sender());\n auto* p = static_cast<QMenu*>(s->parent());\n IOFmt fmt = [](QString name){\n for(const auto& pair:IOPlugins){\n if(name == pair.second->name.c_str()){\n return pair.first;\n }\n }\n throw Error(\"Invalid parameter set\");\n }(p->title());\n auto pos = Vipster::params[fmt].find(s->text().toStdString());\n if(pos != Vipster::params[fmt].end()){\n ui->paramWidget->registerParam(fmt, pos->second->copy());\n }else{\n throw Error(\"Invalid parameter set\");\n }\n}\n\nvoid MainWindow::loadConfig()\n{\n auto* s = static_cast<QAction*>(sender());\n auto* p = static_cast<QMenu*>(s->parent());\n IOFmt fmt = [](QString name){\n for(const auto& pair:IOPlugins){\n if(name == pair.second->name.c_str()){\n return pair.first;\n }\n }\n throw Error(\"Invalid IO-config\");\n }(p->title());\n auto pos = Vipster::configs[fmt].find(s->text().toStdString());\n if(pos != Vipster::configs[fmt].end()){\n ui->configWidget->registerConfig(fmt, pos->second->copy());\n }else{\n throw Error(\"Invalid IO-config\");\n }\n}\n\nvoid MainWindow::saveParam()\n{\n if(!ui->paramWidget->curParam){\n return;\n }\n bool ok;\n auto name = QInputDialog::getText(this, \"Save parameter set\", \"Name of preset\",\n QLineEdit::Normal, QString(), &ok);\n if(ok){\n Vipster::params[ui->paramWidget->curFmt][name.toStdString()] =\n ui->paramWidget->curParam->copy();\n }\n}\n\nvoid MainWindow::saveConfig()\n{\n if(!ui->configWidget->curConfig){\n return;\n }\n bool ok;\n auto name = QInputDialog::getText(this, \"Save IO-Config\", \"Name of preset\",\n QLineEdit::Normal, QString(), &ok);\n if(ok){\n Vipster::configs[ui->configWidget->curFmt][name.toStdString()] =\n ui->configWidget->curConfig->copy();\n }\n}\n\nvoid MainWindow::about()\n{\n QMessageBox::about(this,QString(\"About Vipster\"),\n QString(\"<h2>Vipster<\/h2>\"\n \"<p>\"\n \"©Sebastian Gsänger, 2018\"\n \"<br>\"\n \"<a href='https:\/\/sgsaenger.github.io\/vipster'>Homepage<\/a>\"\n \"<br>\"\n \"<a href='https:\/\/github.com\/sgsaenger\/vipster'>Source<\/a>\"\n \"<\/p>\"\n \"<p>\"\n \"This program is provided under the GPLv3.\"\n \"<br>\"\n \"It uses\"\n \"<a href='https:\/\/github.com\/nlohmann\/json'>JSON for Modern C++<\/a>, \"\n \"<a href='https:\/\/github.com\/CLIUtils\/CLI11'>CLI11<\/a>,\"\n \"<a href='https:\/\/github.com\/catchorg\/catch2'>Catch2<\/a> and \"\n \"<a href='https:\/\/github.com\/pybind\/pybind11'>pybind11<\/a>.\"\n \"<\/p>\"));\n}\n\nvoid MainWindow::saveScreenshot()\n{\n QFileDialog diag{this};\n diag.setDirectory(path);\n diag.setAcceptMode(QFileDialog::AcceptSave);\n diag.setMimeTypeFilters({\"image\/png\"});\n if(diag.exec() == QDialog::Accepted){\n auto target = diag.selectedFiles()[0];\n if(!target.endsWith(\".png\", Qt::CaseInsensitive)){\n target += \".png\";\n }\n path = diag.directory();\n\n auto aa = settings.antialias.val;\n settings.antialias.val = false;\n auto img = ui->openGLWidget->grabFramebuffer();\n img.save(target);\n settings.antialias.val = aa;\n updateWidgets(0);\n }\n}\n<commit_msg>set names when saving param\/config<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"savefmtdialog.h\"\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QApplication>\n#include <QStyle>\n\nusing namespace Vipster;\n\nMainWindow::MainWindow(QString path, QWidget *parent):\n QMainWindow{parent},\n ui{new Ui::MainWindow},\n path{path}\n{\n ui->setupUi(this);\n connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);\n connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);\n setupUI();\n newMol();\n}\n\nMainWindow::MainWindow(QString path, std::vector<IO::Data> &&d, QWidget *parent):\n QMainWindow{parent},\n ui{new Ui::MainWindow},\n path{path}\n{\n ui->setupUi(this);\n setupUI();\n connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt);\n connect(&playTimer, &QTimer::timeout, ui->stepEdit, &QSpinBox::stepUp);\n for(auto&& mol: d){\n newData(std::move(mol));\n }\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::setupUI()\n{\n ui->firstStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));\n ui->preStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n ui->nextStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekForward));\n ui->lastStepButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));\n \/\/ setup left dock-area\n baseWidgets = {\n ui->paramDock,\n ui->configDock,\n ui->settingsDock,\n ui->mpseDock,\n ui->pseDock,\n ui->dataDock,\n };\n for(auto& w: baseWidgets){\n tabifyDockWidget(ui->molDock, w);\n }\n ui->molDock->raise();\n \/\/ setup right dock-area\n toolWidgets = {\n ui->scriptDock,\n ui->pickDock,\n ui->cellModDock,\n ui->millerDock,\n };\n for(auto& w: toolWidgets){\n auto action = ui->toolBar->addAction(w->windowTitle());\n action->setCheckable(true);\n connect(action, &QAction::toggled, w, &QWidget::setVisible);\n w->hide();\n }\n#ifdef Q_OS_MACOS\n setDockOptions(dockOptions()^VerticalTabs);\n#endif\n \/\/ fill in global PSE\n ui->pseWidget->setPSE(&Vipster::pse);\n \/\/ fill in menu-options\n for(const auto& pair:IOPlugins){\n const auto& param_map = Vipster::params[pair.first];\n if(!param_map.empty()){\n auto* param_menu = ui->menuLoad_Parameter_set->addMenu(\n QString::fromStdString(pair.second->name));\n for(const auto& p: param_map){\n param_menu->addAction(QString::fromStdString(p.first),\n this, &MainWindow::loadParam);\n }\n }\n const auto& conf_map = Vipster::configs[pair.first];\n if(!conf_map.empty()){\n auto* conf_menu = ui->menuLoad_IO_Config->addMenu(\n QString::fromStdString(pair.second->name));\n for(const auto& p: conf_map){\n conf_menu->addAction(QString::fromStdString(p.first),\n this, &MainWindow::loadConfig);\n }\n }\n }\n}\n\nvoid MainWindow::updateWidgets(uint8_t change)\n{\n ui->openGLWidget->updateWidget(change);\n ui->molWidget->updateWidget(change);\n for(auto& w: baseWidgets){\n static_cast<BaseWidget*>(w->widget())->updateWidget(change);\n }\n for(auto& w: toolWidgets){\n static_cast<BaseWidget*>(w->widget())->updateWidget(change);\n }\n}\n\nvoid MainWindow::setFmt(int i, bool apply, bool scale)\n{\n fmt = static_cast<AtomFmt>(i);\n if(apply){\n curStep->setFmt(fmt, scale);\n if(curSel){\n curSel->setFmt(fmt);\n }\n updateWidgets(guiStepChanged);\n }else{\n updateWidgets(GuiChange::fmt);\n }\n}\n\nAtomFmt MainWindow::getFmt()\n{\n return fmt;\n}\n\nvoid MainWindow::setMol(int i)\n{\n curMol = &*std::next(molecules.begin(), i);\n int nstep = static_cast<int>(curMol->getNstep());\n if(moldata[curMol].curStep < 0){\n moldata[curMol].curStep = nstep;\n }\n \/\/Step-control\n ui->stepLabel->setText(QString::number(nstep));\n QSignalBlocker boxBlocker(ui->stepEdit);\n QSignalBlocker slideBlocker(ui->stepSlider);\n ui->stepEdit->setMaximum(nstep);\n ui->stepSlider->setMaximum(nstep);\n if(nstep == 1){\n ui->stepEdit->setDisabled(true);\n ui->stepSlider->setDisabled(true);\n }else{\n ui->stepEdit->setEnabled(true);\n ui->stepSlider->setEnabled(true);\n }\n setStep(moldata[curMol].curStep);\n updateWidgets(guiMolChanged);\n}\n\nvoid MainWindow::setStep(int i)\n{\n moldata[curMol].curStep = i;\n curStep = &curMol->getStep(static_cast<size_t>(i-1));\n fmt = curStep->getFmt();\n \/\/ if no previous selection exists, create one, afterwards assign it\n auto& tmpSel = stepdata[curStep].sel;\n if(!tmpSel && curStep){\n tmpSel = std::make_unique<StepSelection>(*curStep);\n }\n curSel = tmpSel.get();\n \/\/Handle control-elements\n if(playTimer.isActive() && (i == static_cast<int>(curMol->getNstep()))){\n playTimer.stop();\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n }\n QSignalBlocker boxBlocker(ui->stepEdit);\n QSignalBlocker slideBlocker(ui->stepSlider);\n ui->stepEdit->setValue(i);\n ui->stepSlider->setValue(i);\n if(i == 1){\n ui->preStepButton->setDisabled(true);\n ui->firstStepButton->setDisabled(true);\n }else{\n ui->preStepButton->setEnabled(true);\n ui->firstStepButton->setEnabled(true);\n }\n if(i == static_cast<int>(curMol->getNstep())){\n ui->nextStepButton->setDisabled(true);\n ui->lastStepButton->setDisabled(true);\n }else{\n ui->nextStepButton->setEnabled(true);\n ui->lastStepButton->setEnabled(true);\n }\n \/\/Update child widgets\n updateWidgets(guiStepChanged);\n}\n\nvoid MainWindow::stepBut(QAbstractButton* but)\n{\n if(but == ui->firstStepButton){\n setStep(1);\n }else if(but == ui->lastStepButton){\n setStep(static_cast<int>(curMol->getNstep()));\n }else if(but == ui->playButton){\n if(playTimer.isActive()){\n playTimer.stop();\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));\n }else{\n playTimer.start(1000);\n ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));\n }\n }\n}\n\nvoid MainWindow::editAtoms(QAction* sender)\n{\n if ( sender == ui->actionNew_Atom){\n curStep->newAtom();\n }else if ( sender == ui->actionDelete_Atom_s){\n curSel->delAtoms();\n }else if ( sender == ui->actionHide_Atom_s){\n for(auto& at: *curSel){\n at.properties->flags[AtomFlag::Hidden] = 1;\n }\n }else if ( sender == ui->actionShow_Atom_s){\n for(auto& at: *curSel){\n at.properties->flags[AtomFlag::Hidden] = 0;\n }\n }\n updateWidgets(GuiChange::atoms);\n}\n\nvoid MainWindow::newMol()\n{\n molecules.emplace_back();\n ui->molWidget->registerMol(molecules.back().getName());\n}\n\nvoid MainWindow::newData(IO::Data &&d)\n{\n molecules.push_back(std::move(d.mol));\n ui->molWidget->registerMol(molecules.back().getName());\n if(d.param){\n ui->paramWidget->registerParam(d.fmt, std::move(d.param));\n }\n for(auto& dat: d.data){\n data.push_back(std::move(dat));\n ui->dataWidget->registerData(data.back()->name);\n }\n}\n\nvoid MainWindow::loadMol()\n{\n \/\/ File dialog\n QStringList files;\n QFileDialog fileDiag{this};\n fileDiag.setDirectory(path);\n fileDiag.setFileMode(QFileDialog::ExistingFiles);\n \/\/ Format dialog\n QStringList formats{};\n for(auto &iop: IOPlugins){\n formats << QString::fromStdString(iop.second->name);\n }\n QString fmt_s;\n IOFmt fmt;\n bool got_fmt{false};\n if(fileDiag.exec() != 0){\n files = fileDiag.selectedFiles();\n path = fileDiag.directory();\n if(files.count() != 0){\n fmt_s = QInputDialog::getItem(this, \"Select format\", \"Format:\",\n formats, 0, false, &got_fmt);\n if(got_fmt){\n fmt = static_cast<IOFmt>(formats.indexOf(fmt_s));\n for(auto &file: files){\n newData(readFile(file.toStdString(), fmt));\n }\n }\n }\n }\n}\n\nvoid MainWindow::saveMol()\n{\n QFileDialog fileDiag{this};\n fileDiag.setDirectory(path);\n fileDiag.setAcceptMode(QFileDialog::AcceptSave);\n if(fileDiag.exec() == QDialog::Accepted){\n auto target = fileDiag.selectedFiles()[0].toStdString();\n path = fileDiag.directory();\n SaveFmtDialog sfd{this};\n if(sfd.exec() == QDialog::Accepted){\n writeFile(target, sfd.fmt, *curMol,\n sfd.getParam(), sfd.getConfig(),\n IO::State{static_cast<size_t>(ui->stepSlider->value()-1),\n this->fmt,\n ui->molWidget->getCellFmt()});\n }\n }\n}\n\n\nconst decltype (ParamWidget::params)& MainWindow::getParams() const noexcept\n{\n return ui->paramWidget->params;\n}\n\nconst decltype (ConfigWidget::configs)& MainWindow::getConfigs() const noexcept\n{\n return ui->configWidget->configs;\n}\n\nvoid MainWindow::addExtraData(GUI::Data* dat)\n{\n ui->openGLWidget->addExtraData(dat);\n updateWidgets(GuiChange::extra);\n}\n\nvoid MainWindow::delExtraData(GUI::Data* dat)\n{\n ui->openGLWidget->delExtraData(dat);\n updateWidgets(GuiChange::extra);\n}\n\nconst GUI::GlobalData& MainWindow::getGLGlobals()\n{\n return ui->openGLWidget->globals;\n}\n\nvoid MainWindow::loadParam()\n{\n auto* s = static_cast<QAction*>(sender());\n auto* p = static_cast<QMenu*>(s->parent());\n IOFmt fmt = [](QString name){\n for(const auto& pair:IOPlugins){\n if(name == pair.second->name.c_str()){\n return pair.first;\n }\n }\n throw Error(\"Invalid parameter set\");\n }(p->title());\n auto pos = Vipster::params[fmt].find(s->text().toStdString());\n if(pos != Vipster::params[fmt].end()){\n ui->paramWidget->registerParam(fmt, pos->second->copy());\n }else{\n throw Error(\"Invalid parameter set\");\n }\n}\n\nvoid MainWindow::loadConfig()\n{\n auto* s = static_cast<QAction*>(sender());\n auto* p = static_cast<QMenu*>(s->parent());\n IOFmt fmt = [](QString name){\n for(const auto& pair:IOPlugins){\n if(name == pair.second->name.c_str()){\n return pair.first;\n }\n }\n throw Error(\"Invalid IO-config\");\n }(p->title());\n auto pos = Vipster::configs[fmt].find(s->text().toStdString());\n if(pos != Vipster::configs[fmt].end()){\n ui->configWidget->registerConfig(fmt, pos->second->copy());\n }else{\n throw Error(\"Invalid IO-config\");\n }\n}\n\nvoid MainWindow::saveParam()\n{\n if(!ui->paramWidget->curParam){\n return;\n }\n bool ok;\n auto name = QInputDialog::getText(this, \"Save parameter set\", \"Name of preset\",\n QLineEdit::Normal, QString(), &ok).toStdString();\n if(ok){\n Vipster::params[ui->paramWidget->curFmt][name] =\n ui->paramWidget->curParam->copy();\n Vipster::params[ui->paramWidget->curFmt][name]->name = name;\n }\n}\n\nvoid MainWindow::saveConfig()\n{\n if(!ui->configWidget->curConfig){\n return;\n }\n bool ok;\n auto name = QInputDialog::getText(this, \"Save IO-Config\", \"Name of preset\",\n QLineEdit::Normal, QString(), &ok).toStdString();\n if(ok){\n Vipster::configs[ui->configWidget->curFmt][name] =\n ui->configWidget->curConfig->copy();\n Vipster::configs[ui->configWidget->curFmt][name]->name = name;\n }\n}\n\nvoid MainWindow::about()\n{\n QMessageBox::about(this,QString(\"About Vipster\"),\n QString(\"<h2>Vipster<\/h2>\"\n \"<p>\"\n \"©Sebastian Gsänger, 2018\"\n \"<br>\"\n \"<a href='https:\/\/sgsaenger.github.io\/vipster'>Homepage<\/a>\"\n \"<br>\"\n \"<a href='https:\/\/github.com\/sgsaenger\/vipster'>Source<\/a>\"\n \"<\/p>\"\n \"<p>\"\n \"This program is provided under the GPLv3.\"\n \"<br>\"\n \"It uses\"\n \"<a href='https:\/\/github.com\/nlohmann\/json'>JSON for Modern C++<\/a>, \"\n \"<a href='https:\/\/github.com\/CLIUtils\/CLI11'>CLI11<\/a>,\"\n \"<a href='https:\/\/github.com\/catchorg\/catch2'>Catch2<\/a> and \"\n \"<a href='https:\/\/github.com\/pybind\/pybind11'>pybind11<\/a>.\"\n \"<\/p>\"));\n}\n\nvoid MainWindow::saveScreenshot()\n{\n QFileDialog diag{this};\n diag.setDirectory(path);\n diag.setAcceptMode(QFileDialog::AcceptSave);\n diag.setMimeTypeFilters({\"image\/png\"});\n if(diag.exec() == QDialog::Accepted){\n auto target = diag.selectedFiles()[0];\n if(!target.endsWith(\".png\", Qt::CaseInsensitive)){\n target += \".png\";\n }\n path = diag.directory();\n\n auto aa = settings.antialias.val;\n settings.antialias.val = false;\n auto img = ui->openGLWidget->grabFramebuffer();\n img.save(target);\n settings.antialias.val = aa;\n updateWidgets(0);\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>:sparkles: feat(echo-server-stackful): add an example of echo-serevr using boost.asio with stackful corotine<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"polygon_triangulation.hpp\"\n#include \"cpp\/ylikuutio\/common\/globals.hpp\"\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n\nnamespace geometry\n{\n bool triangulate_simple_polygon(\n TriangulatePolygonsStruct triangulate_polygons_struct,\n std::vector<glm::vec3> &out_vertices,\n std::vector<glm::vec2> &out_UVs,\n std::vector<glm::vec3> &out_normals)\n {\n \/\/ TODO: implement this function!\n }\n\n bool triangulate_polygons(\n TriangulatePolygonsStruct triangulate_polygons_struct,\n std::vector<glm::vec3> &out_vertices,\n std::vector<glm::vec2> &out_UVs,\n std::vector<glm::vec3> &out_normals)\n {\n \/\/ TODO: implement this function!\n\n \/\/ Find hidden vertices using `get_intersection_point(geometry::LineSegment2D* line_segment1, geometry::LineSegment2D* line_segment2)`.\n std::vector<std::vector<glm::vec2>>* vertex_data = triangulate_polygons_struct.input_vertices;\n\n \/\/ Each edge may have intersections with any other intersections\n \/\/ except immediately previous and immediately next intersections.\n \/\/ TODO: write the code!\n\n for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)\n {\n }\n\n \/\/ All vertices (3D, explicitly defined and hidden) should be known now.\n\n \/\/ Divide complex polygons into simple polygons. Each vertex belongs to 1 or more simple polygons.\n \/\/ TODO: write the code!\n std::vector<std::vector<glm::vec3>> simple_polygons;\n\n for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)\n {\n }\n\n \/\/ Loop through simple polygons and triangulate them.\n \/\/ TODO: write the code!\n\n return false;\n }\n}\n<commit_msg>Bugfix: Added `return false` to `bool triangulate_simple_polygon`.<commit_after>#include \"polygon_triangulation.hpp\"\n#include \"cpp\/ylikuutio\/common\/globals.hpp\"\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n\nnamespace geometry\n{\n bool triangulate_simple_polygon(\n TriangulatePolygonsStruct triangulate_polygons_struct,\n std::vector<glm::vec3> &out_vertices,\n std::vector<glm::vec2> &out_UVs,\n std::vector<glm::vec3> &out_normals)\n {\n \/\/ TODO: implement this function!\n return false;\n }\n\n bool triangulate_polygons(\n TriangulatePolygonsStruct triangulate_polygons_struct,\n std::vector<glm::vec3> &out_vertices,\n std::vector<glm::vec2> &out_UVs,\n std::vector<glm::vec3> &out_normals)\n {\n \/\/ TODO: implement this function!\n\n \/\/ Find hidden vertices using `get_intersection_point(geometry::LineSegment2D* line_segment1, geometry::LineSegment2D* line_segment2)`.\n std::vector<std::vector<glm::vec2>>* vertex_data = triangulate_polygons_struct.input_vertices;\n\n \/\/ Each edge may have intersections with any other intersections\n \/\/ except immediately previous and immediately next intersections.\n \/\/ TODO: write the code!\n\n for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)\n {\n }\n\n \/\/ All vertices (3D, explicitly defined and hidden) should be known now.\n\n \/\/ Divide complex polygons into simple polygons. Each vertex belongs to 1 or more simple polygons.\n \/\/ TODO: write the code!\n std::vector<std::vector<glm::vec3>> simple_polygons;\n\n for (uint32_t vertex_i = 0; vertex_i < vertex_data->size(); vertex_i++)\n {\n }\n\n \/\/ Loop through simple polygons and triangulate them.\n \/\/ TODO: write the code!\n\n return false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cyber\/scheduler\/policy\/scheduler_choreography.h\"\n\n#include <memory>\n\n#include \"cyber\/scheduler\/processor.h\"\n#include \"cyber\/scheduler\/policy\/choreography.h\"\n#include \"cyber\/scheduler\/policy\/classic.h\"\n\nnamespace apollo {\nnamespace cyber {\nnamespace scheduler {\n\nusing apollo::cyber::common::GlobalData;\n\nSchedulerChoreography::SchedulerChoreography() {\n sched_policy_ = SchedPolicy::CHOREO;\n\n auto gconf = GlobalData::Instance()->Config();\n for (auto& conf : gconf.scheduler_conf().confs()) {\n sched_confs_[conf.name()] = conf;\n }\n\n auto desc = SchedName_descriptor()->\n FindValueByName(GlobalData::Instance()->SchedName());\n int sname;\n if (desc) {\n sname = desc->number();\n\n SchedConf sconf;\n auto itr = sched_confs_.find(sname);\n if (itr != sched_confs_.end()) {\n proc_num_ = itr->second.proc_num();\n task_pool_size_ = itr->second.task_pool_size();\n cpu_binding_start_index_ = itr->second.cpu_binding_start_index();\n }\n }\n\n for (auto& conf : gconf.choreo_conf()) {\n if (conf.sched_name() == sname) {\n for (auto& choreo : conf.choreos()) {\n cr_confs_[choreo.name()] = choreo;\n }\n }\n }\n\n \/\/ default val for case w\/o config:\n if (proc_num_ == 0) {\n proc_num_ = std::thread::hardware_concurrency() \/ 4 * 3;\n \/\/ FIXME: other vals ... ?\n }\n \/\/ Currently for compatible with task\/task_manager.cc,\n \/\/ will be deleted at last:\n \/\/ auto pool_size = scheduler::Scheduler::Instance()->TaskPoolSize();\n task_pool_size_ = std::thread::hardware_concurrency() \/ 4;\n\n CreateProcessor();\n}\n\nvoid SchedulerChoreography::CreateProcessor() {\n for (uint32_t i = 0; i < proc_num_; i++) {\n auto proc = std::make_shared<Processor>();\n auto ctx = std::make_shared<ChoreoGraphyContext>();\n\n proc->BindContext(ctx);\n proc->SetBindCpuIndex(cpu_binding_start_index_ + i);\n ctx->BindProc(proc);\n proc_ctxs_.emplace_back(ctx);\n\n proc->Start();\n }\n\n \/\/ For choreography policy: put tasks w\/o processor assigned\n \/\/ to a classic pool.\n for (uint32_t i = 0; i < task_pool_size_; i++) {\n auto proc = std::make_shared<Processor>();\n auto ctx = std::make_shared<ClassicContext>();\n\n proc->BindContext(ctx);\n proc->SetBindCpuIndex(cpu_binding_start_index_ + proc_num_ + i);\n ctx->BindProc(proc);\n proc_ctxs_.emplace_back(ctx);\n\n classic_4_choreo_ = ctx.get();\n\n proc->Start();\n }\n}\n\n} \/\/ namespace scheduler\n} \/\/ namespace cyber\n} \/\/ namespace apollo\n\n<commit_msg>framework: make task_pool_size configurable again<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cyber\/scheduler\/policy\/scheduler_choreography.h\"\n\n#include <memory>\n\n#include \"cyber\/scheduler\/processor.h\"\n#include \"cyber\/scheduler\/policy\/choreography.h\"\n#include \"cyber\/scheduler\/policy\/classic.h\"\n\nnamespace apollo {\nnamespace cyber {\nnamespace scheduler {\n\nusing apollo::cyber::common::GlobalData;\n\nSchedulerChoreography::SchedulerChoreography() {\n sched_policy_ = SchedPolicy::CHOREO;\n\n auto gconf = GlobalData::Instance()->Config();\n for (auto& conf : gconf.scheduler_conf().confs()) {\n sched_confs_[conf.name()] = conf;\n }\n\n auto desc = SchedName_descriptor()->\n FindValueByName(GlobalData::Instance()->SchedName());\n int sname;\n if (desc) {\n sname = desc->number();\n\n SchedConf sconf;\n auto itr = sched_confs_.find(sname);\n if (itr != sched_confs_.end()) {\n proc_num_ = itr->second.proc_num();\n task_pool_size_ = itr->second.task_pool_size();\n cpu_binding_start_index_ = itr->second.cpu_binding_start_index();\n }\n }\n\n for (auto& conf : gconf.choreo_conf()) {\n if (conf.sched_name() == sname) {\n for (auto& choreo : conf.choreos()) {\n cr_confs_[choreo.name()] = choreo;\n }\n }\n }\n\n \/\/ default val for case w\/o config:\n if (proc_num_ == 0) {\n proc_num_ = std::thread::hardware_concurrency() \/ 4 * 3;\n \/\/ FIXME: other vals ... ?\n }\n \/\/ Currently for compatible with task\/task_manager.cc,\n \/\/ will be deleted at last:\n \/\/ auto pool_size = scheduler::Scheduler::Instance()->TaskPoolSize();\n \/\/ task_pool_size_ = std::thread::hardware_concurrency() \/ 4;\n\n CreateProcessor();\n}\n\nvoid SchedulerChoreography::CreateProcessor() {\n for (uint32_t i = 0; i < proc_num_; i++) {\n auto proc = std::make_shared<Processor>();\n auto ctx = std::make_shared<ChoreoGraphyContext>();\n\n proc->BindContext(ctx);\n proc->SetBindCpuIndex(cpu_binding_start_index_ + i);\n ctx->BindProc(proc);\n proc_ctxs_.emplace_back(ctx);\n\n proc->Start();\n }\n\n \/\/ For choreography policy: put tasks w\/o processor assigned\n \/\/ to a classic pool.\n for (uint32_t i = 0; i < task_pool_size_; i++) {\n auto proc = std::make_shared<Processor>();\n auto ctx = std::make_shared<ClassicContext>();\n\n proc->BindContext(ctx);\n proc->SetBindCpuIndex(cpu_binding_start_index_ + proc_num_ + i);\n ctx->BindProc(proc);\n proc_ctxs_.emplace_back(ctx);\n\n classic_4_choreo_ = ctx.get();\n\n proc->Start();\n }\n}\n\n} \/\/ namespace scheduler\n} \/\/ namespace cyber\n} \/\/ namespace apollo\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Configuration\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Configuration\/Enumeration.h\"\n#include \"Stroika\/Foundation\/Configuration\/Version.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\n\n\n\n\nnamespace {\n void Test1_Version_ ()\n {\n const Configuration::Version kTestVersion_ =\n Configuration::Version (1, 0, Configuration::VersionStage::Alpha, 1, false\n )\n ;\n VerifyTestResult (kTestVersion_.AsPrettyVersionString () == L\"1.0a1x\");\n }\n}\n\n\n\nnamespace {\n void Test2_EnumNames_ ()\n {\n using namespace Configuration;\n enum class fooEnum {\n eOne,\n eTwo,\n };\n const EnumNames<fooEnum> Stroika_Enum_Names(fooEnum) = {\n { fooEnum::eOne, L\"eOne\" },\n { fooEnum::eTwo, L\"eTwo\" },\n };\n Verify (wstring (L\"eOne\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));\n Verify (wstring (L\"eTwo\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));\n }\n}\n\n\n\nnamespace {\n void DoRegressionTests_ ()\n {\n Test1_Version_ ();\n Test2_EnumNames_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\n<commit_msg>enhance Stroika_Enum_Names() regtest<commit_after>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Configuration\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Configuration\/Enumeration.h\"\n#include \"Stroika\/Foundation\/Configuration\/Version.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\n\n\n\n\nnamespace {\n void Test1_Version_ ()\n {\n const Configuration::Version kTestVersion_ =\n Configuration::Version (1, 0, Configuration::VersionStage::Alpha, 1, false\n )\n ;\n VerifyTestResult (kTestVersion_.AsPrettyVersionString () == L\"1.0a1x\");\n }\n}\n\n\n\nnamespace {\n void Test2_EnumNames_ ()\n {\n using namespace Configuration;\n enum class fooEnum {\n eOne,\n eTwo,\n };\n {\n const EnumNames<fooEnum> Stroika_Enum_Names(fooEnum) = {\n { fooEnum::eOne, L\"eOne\" },\n { fooEnum::eTwo, L\"eTwo\" },\n };\n Verify (wstring (L\"eOne\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));\n Verify (wstring (L\"eTwo\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));\n }\n {\n static const EnumNames<fooEnum> Stroika_Enum_Names(fooEnum) = {\n { fooEnum::eOne, L\"eOne\" },\n { fooEnum::eTwo, L\"eTwo\" },\n };\n Verify (wstring (L\"eOne\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eOne));\n Verify (wstring (L\"eTwo\") == Stroika_Enum_Names(fooEnum).GetName (fooEnum::eTwo));\n }\n }\n}\n\n\n\nnamespace {\n void DoRegressionTests_ ()\n {\n Test1_Version_ ();\n Test2_EnumNames_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Containers::Mapping\n\/\/ STATUS Alpha-Late\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include <iostream>\n#include <sstream>\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_Array.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_LinkedList.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_stdmap.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/SortedMapping_stdmap.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"..\/TestCommon\/CommonTests_Mapping.h\"\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\n\nusing Concrete::Mapping_Array;\nusing Concrete::Mapping_LinkedList;\nusing Concrete::Mapping_stdmap;\n\n\nnamespace {\n template <typename CONCRETE_CONTAINER>\n void DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_ ()\n {\n auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {\n \/\/ only work todo on sorted mappings\n };\n CommonTests::MappingTests::SimpleMappingTest_AllTestsWhichDontRequireComparer_For_Type_<CONCRETE_CONTAINER> (extraChecksFunction);\n }\n template <typename CONCRETE_CONTAINER>\n void DoTestForConcreteContainer_ ()\n {\n auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {\n \/\/ only work todo on sorted mappings\n };\n CommonTests::MappingTests::SimpleMappingTest_All_For_Type<CONCRETE_CONTAINER> (extraChecksFunction);\n }\n}\n\n\nnamespace {\n void Test2_SimpleBaseClassConversionTraitsConfusion_ ()\n {\n SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> ();\n Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> ();\n }\n}\n\n\nnamespace {\n template <typename CONTAINER, typename COMPARER>\n void doIt_t3_()\n {\n CommonTests::MappingTests::SimpleMappingTest_WhichRequiresExplcitValueComparer<CONTAINER, COMPARER> ([] (const CONTAINER & c) {});\n }\n void Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ()\n {\n doIt_t3_<Mapping_LinkedList<size_t, size_t>, Common::ComparerWithEquals<size_t>> ();\n }\n}\n\n\n\nnamespace {\n namespace Test4_MappingCTOROverloads_ {\n namespace xPrivate_ {\n struct A;\n struct B;\n struct A {\n A() {}\n A(const A&) {}\n A(const B&) {}\n };\n struct B {\n B() {}\n B(const A&) {}\n B(const B&) {}\n };\n\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;\n\n struct aaaaaa {\n\/\/ template <typename X>\n using X = T;\n static auto check(const X& x) ->\n std::conditional <\n Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and\n std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,\n Configuration::substitution_succeeded <T>,\n Configuration::substitution_failure\n >::type\n ;\n\/\/ static Configuration::substitution_failure check (...);\n using type = decltype(check(declval<T>()));\n };\n\n }\n void DoIt ()\n {\n using namespace xPrivate_;\n Mapping<int, A> from;\n\n\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n bool n1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n \/\/bool n2 = Configuration::IsIterableOfT2<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n\n using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;\n using ttt =\n std::conditional <\n Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and\n std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,\n Configuration::substitution_succeeded <T>,\n Configuration::substitution_failure\n >::type;\n const bool n3 = is_same<ttt, Configuration::substitution_failure>::value;\n\n using aaaa3 = Configuration::Private_::IsIterableOfT_Impl2_<CONTAINER_OF_PAIR_KEY_T, T>::type;\n const bool n4 = is_same<aaaa3, Configuration::substitution_failure>::value;\n\n const bool n5 = is_same<aaaaaa::type, Configuration::substitution_failure>::value;\n\n\n#if 0\n bool xxx1 = std::is_convertible<const Mapping<int, A>*, const Mapping<int, B>*>::value;\n bool xxx2 = Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, B>>::value;\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n bool xxxxx1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n bool xxxxx2 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;\n \/\/bool xxxxx3 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value);\n \/\/bool xxxxx = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value or Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;\n#endif\n Mapping<int, B> to1;\n for (auto i : from) {\n to1.Add (i);\n }\n Mapping<int, B> to2 = from;\n }\n }\n}\n\n\n\n\nnamespace {\n void DoRegressionTests_ ()\n {\n struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {\n using ElementType = SimpleClassWithoutComparisonOperators;\n static bool Equals (ElementType v1, ElementType v2)\n {\n return v1.GetValue () == v2.GetValue ();\n }\n };\n using SimpleClassWithoutComparisonOperators_MappingTRAITS = DefaultTraits::Mapping <\n SimpleClassWithoutComparisonOperators,\n SimpleClassWithoutComparisonOperators,\n MySimpleClassWithoutComparisonOperators_ComparerWithEquals_\n > ;\n\n DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();\n {\n struct MySimpleClassWithoutComparisonOperators_ComparerWithCompare_ : MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {\n using ElementType = SimpleClassWithoutComparisonOperators;\n static int Compare (ElementType v1, ElementType v2)\n {\n return Common::CompareNormalizer (v1.GetValue (), v2.GetValue ());\n }\n };\n using SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS =\n Concrete::Mapping_stdmap_DefaultTraits <\n SimpleClassWithoutComparisonOperators,\n SimpleClassWithoutComparisonOperators,\n MySimpleClassWithoutComparisonOperators_ComparerWithEquals_,\n MySimpleClassWithoutComparisonOperators_ComparerWithCompare_\n >;\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS>> ();\n }\n\n Test2_SimpleBaseClassConversionTraitsConfusion_ ();\n\n Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();\n\n Test4_MappingCTOROverloads_::DoIt ();\n }\n}\n\n\nint main (int argc, const char* argv[])\n{\n\tstruct foo {\n\t const Mapping<int,int> cx;\n\t};\n\tfoo bar;\n\tfoo ddd = bar;\n\tif (auto i = ddd.cx.Lookup (1)) {\n\t\tint j = *i;\n\t}\n\t\n\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n<commit_msg>undid accidental 'foo' checkin<commit_after>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved\n *\/\n\/\/ TEST Foundation::Containers::Mapping\n\/\/ STATUS Alpha-Late\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include <iostream>\n#include <sstream>\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_Array.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_LinkedList.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Mapping_stdmap.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/SortedMapping_stdmap.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"..\/TestCommon\/CommonTests_Mapping.h\"\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\n\nusing Concrete::Mapping_Array;\nusing Concrete::Mapping_LinkedList;\nusing Concrete::Mapping_stdmap;\n\n\nnamespace {\n template <typename CONCRETE_CONTAINER>\n void DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_ ()\n {\n auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {\n \/\/ only work todo on sorted mappings\n };\n CommonTests::MappingTests::SimpleMappingTest_AllTestsWhichDontRequireComparer_For_Type_<CONCRETE_CONTAINER> (extraChecksFunction);\n }\n template <typename CONCRETE_CONTAINER>\n void DoTestForConcreteContainer_ ()\n {\n auto extraChecksFunction = [](const typename CONCRETE_CONTAINER::ArchetypeContainerType & m) {\n \/\/ only work todo on sorted mappings\n };\n CommonTests::MappingTests::SimpleMappingTest_All_For_Type<CONCRETE_CONTAINER> (extraChecksFunction);\n }\n}\n\n\nnamespace {\n void Test2_SimpleBaseClassConversionTraitsConfusion_ ()\n {\n SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> ();\n Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> ();\n }\n}\n\n\nnamespace {\n template <typename CONTAINER, typename COMPARER>\n void doIt_t3_()\n {\n CommonTests::MappingTests::SimpleMappingTest_WhichRequiresExplcitValueComparer<CONTAINER, COMPARER> ([] (const CONTAINER & c) {});\n }\n void Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ()\n {\n doIt_t3_<Mapping_LinkedList<size_t, size_t>, Common::ComparerWithEquals<size_t>> ();\n }\n}\n\n\n\nnamespace {\n namespace Test4_MappingCTOROverloads_ {\n namespace xPrivate_ {\n struct A;\n struct B;\n struct A {\n A() {}\n A(const A&) {}\n A(const B&) {}\n };\n struct B {\n B() {}\n B(const A&) {}\n B(const B&) {}\n };\n\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;\n\n struct aaaaaa {\n\/\/ template <typename X>\n using X = T;\n static auto check(const X& x) ->\n std::conditional <\n Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and\n std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,\n Configuration::substitution_succeeded <T>,\n Configuration::substitution_failure\n >::type\n ;\n\/\/ static Configuration::substitution_failure check (...);\n using type = decltype(check(declval<T>()));\n };\n\n }\n void DoIt ()\n {\n using namespace xPrivate_;\n Mapping<int, A> from;\n\n\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n bool n1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n \/\/bool n2 = Configuration::IsIterableOfT2<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n\n using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>;\n using ttt =\n std::conditional <\n Configuration::has_beginend<CONTAINER_OF_PAIR_KEY_T>::value and\n std::is_convertible<typename std::iterator_traits<Configuration::begin_result<CONTAINER_OF_PAIR_KEY_T>>::value_type, T>::value,\n Configuration::substitution_succeeded <T>,\n Configuration::substitution_failure\n >::type;\n const bool n3 = is_same<ttt, Configuration::substitution_failure>::value;\n\n using aaaa3 = Configuration::Private_::IsIterableOfT_Impl2_<CONTAINER_OF_PAIR_KEY_T, T>::type;\n const bool n4 = is_same<aaaa3, Configuration::substitution_failure>::value;\n\n const bool n5 = is_same<aaaaaa::type, Configuration::substitution_failure>::value;\n\n\n#if 0\n bool xxx1 = std::is_convertible<const Mapping<int, A>*, const Mapping<int, B>*>::value;\n bool xxx2 = Configuration::IsIterableOfT<Mapping<int, A>, KeyValuePair<int, B>>::value;\n using Common::KeyValuePair;\n using KEY_TYPE = int;\n using VALUE_TYPE = B;\n using TRAITS = DefaultTraits::Mapping<KEY_TYPE, VALUE_TYPE>;\n using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>;\n bool xxxxx1 = Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value;\n bool xxxxx2 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;\n \/\/bool xxxxx3 = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value);\n \/\/bool xxxxx = (Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, KeyValuePair<KEY_TYPE, VALUE_TYPE>>::value or Configuration::IsIterableOfT<CONTAINER_OF_PAIR_KEY_T, pair<KEY_TYPE, VALUE_TYPE>>::value) and not std::is_convertible<const CONTAINER_OF_PAIR_KEY_T*, const Mapping<KEY_TYPE, VALUE_TYPE, TRAITS>*>::value;\n#endif\n Mapping<int, B> to1;\n for (auto i : from) {\n to1.Add (i);\n }\n Mapping<int, B> to2 = from;\n }\n }\n}\n\n\n\n\nnamespace {\n void DoRegressionTests_ ()\n {\n struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {\n using ElementType = SimpleClassWithoutComparisonOperators;\n static bool Equals (ElementType v1, ElementType v2)\n {\n return v1.GetValue () == v2.GetValue ();\n }\n };\n using SimpleClassWithoutComparisonOperators_MappingTRAITS = DefaultTraits::Mapping <\n SimpleClassWithoutComparisonOperators,\n SimpleClassWithoutComparisonOperators,\n MySimpleClassWithoutComparisonOperators_ComparerWithEquals_\n > ;\n\n DoTestForConcreteContainer_<Mapping<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> ();\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> ();\n\n DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> ();\n DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> ();\n {\n struct MySimpleClassWithoutComparisonOperators_ComparerWithCompare_ : MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ {\n using ElementType = SimpleClassWithoutComparisonOperators;\n static int Compare (ElementType v1, ElementType v2)\n {\n return Common::CompareNormalizer (v1.GetValue (), v2.GetValue ());\n }\n };\n using SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS =\n Concrete::Mapping_stdmap_DefaultTraits <\n SimpleClassWithoutComparisonOperators,\n SimpleClassWithoutComparisonOperators,\n MySimpleClassWithoutComparisonOperators_ComparerWithEquals_,\n MySimpleClassWithoutComparisonOperators_ComparerWithCompare_\n >;\n DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_Mapping_stdmap_TRAITS>> ();\n }\n\n Test2_SimpleBaseClassConversionTraitsConfusion_ ();\n\n Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer ();\n\n Test4_MappingCTOROverloads_::DoIt ();\n }\n}\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n\/\/ TEST Foundation::Execution::Signals\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Sanitizer.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n#include \"Stroika\/Foundation\/Execution\/SignalHandlers.h\"\n#include \"Stroika\/Foundation\/Execution\/Sleep.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\nusing Containers::Set;\n\nnamespace {\n void Test1_Basic_ ()\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n bool called = false;\n Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); \/\/ helgrind doesnt know signal handler must have returend by end of sleep.\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n}\n\nnamespace {\n Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE (\"thread\") void Test2_Direct_ ()\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n bool called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));\n Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); \/\/ helgrind doesnt know signal handler must have returend by end of sleep.\n ::raise (SIGINT);\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n}\n\nnamespace {\n void Test3_Safe_ ()\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n bool called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));\n Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); \/\/ helgrind doesnt know signal handler must have returend by end of sleep.\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n}\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Basic_ ();\n Test2_Direct_ ();\n Test3_Safe_ ();\n }\n}\n\nint main (int argc, const char* argv[])\n{\n SignalHandlerRegistry::SafeSignalsManager safeSignals;\n Stroika::TestHarness::Setup ();\n return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n}\n<commit_msg>Enhanced Test1_Basic_ regtest to hopfully workaround\/fix TSAN reported error about race writing to variable<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n\/\/ TEST Foundation::Execution::Signals\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Sanitizer.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n#include \"Stroika\/Foundation\/Execution\/SignalHandlers.h\"\n#include \"Stroika\/Foundation\/Execution\/Sleep.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\nusing Containers::Set;\n\nnamespace {\n void Test1_Basic_ ()\n {\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n \/\/ atomic CAN be used with SAFE signal handlers\n atomic<bool> called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eSafe));\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n \/\/ atomic CAN be used with direct signal handlers\n atomic<bool> called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eDirect));\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n \/\/ Synchronized CAN be used with SAFE signal handlers\n Synchronized<bool> called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::eSafe));\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n }\n}\n\nnamespace {\n Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE (\"thread\") void Test2_Direct_ ()\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n bool called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));\n Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); \/\/ helgrind doesnt know signal handler must have returend by end of sleep.\n ::raise (SIGINT);\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n}\n\nnamespace {\n void Test3_Safe_ ()\n {\n Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);\n {\n bool called = false;\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));\n Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); \/\/ helgrind doesnt know signal handler must have returend by end of sleep.\n ::raise (SIGINT);\n Execution::Sleep (0.5); \/\/ delivery could be delayed because signal is pushed to another thread\n VerifyTestResult (called);\n }\n SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);\n }\n}\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Basic_ ();\n Test2_Direct_ ();\n Test3_Safe_ ();\n }\n}\n\nint main (int argc, const char* argv[])\n{\n SignalHandlerRegistry::SafeSignalsManager safeSignals;\n Stroika::TestHarness::Setup ();\n return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ SSSSCpp.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"GF256.h\"\r\n#include \"SSSSCpp.h\"\r\n#include <vector>\r\n#include <stdio.h>\r\n#include <iostream>\r\n\r\n#include <assert.h>\r\n#define UINT unsigned int\r\n\r\nusing std::vector; using std::pair;\r\nusing std::make_pair;\r\n\r\nint _tmain(int argc, _TCHAR* argv[])\r\n{\r\n\tGF256init();\r\n\tPGF256 hi = generateRandomPolynomial(5, 0x08);\r\n\tvector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);\r\n\tvector<pair<UINT, UINT>> lol2;\r\n\tlol2.push_back(make_pair(225, 113));\r\n\tlol2.push_back(make_pair(32, 247));\r\n\tlol2.push_back(make_pair(249, 248));\r\n\tUINT result = decodeByte(lol2);\r\n\treturn 0;\r\n}\r\n\r\n<commit_msg>added trivial test case.<commit_after>\/\/ SSSSCpp.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"GF256.h\"\r\n#include \"SSSSCpp.h\"\r\n#include <vector>\r\n#include <stdio.h>\r\n#include <iostream>\r\n\r\n#include <assert.h>\r\n#define UINT unsigned int\r\n\r\nusing std::vector; using std::pair;\r\nusing std::make_pair;\r\n\r\nint _tmain(int argc, _TCHAR* argv[])\r\n{\r\n\tGF256init();\r\n\tPGF256 hi = generateRandomPolynomial(5, 0x08);\r\n\tvector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);\r\n\tvector<pair<UINT, UINT>> lol2;\r\n\tlol2.push_back(make_pair(1, 17));\r\n\tlol2.push_back(make_pair(2, 34));\r\n\tlol2.push_back(make_pair(3, 61));\r\n\t\/\/lol2.push_back(make_pair(225, 113));\r\n\t\/\/lol2.push_back(make_pair(32, 247));\r\n\t\/\/lol2.push_back(make_pair(249, 248));\r\n\tUINT result = decodeByte(lol2);\r\n\treturn 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"Interpret\\SmartView\\SmartView.h\"\n#include \"Interpret\\SmartView\\SmartViewParser.h\"\n#include \"MFCMAPI.h\"\n#include \"resource.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace SmartViewTest\n{\n\tTEST_CLASS(SmartViewTest)\n\t{\n\tprivate:\n\t\tstruct SmartViewTestResource {\n\t\t\t__ParsingTypeEnum structType;\n\t\t\tbool parseAll;\n\t\t\tDWORD hex;\n\t\t\tDWORD expected;\n\t\t};\n\n\t\tstruct SmartViewTestData {\n\t\t\t__ParsingTypeEnum structType;\n\t\t\tbool parseAll;\n\t\t\twstring testName;\n\t\t\twstring hex;\n\t\t\twstring expected;\n\t\t};\n\n\t\tconst bool parseAll = false;\n\t\twstring ParseString(wstring hexString, __ParsingTypeEnum iStructType)\n\t\t{\n\t\t\tauto bin = HexStringToBin(hexString);\n\t\t\treturn InterpretBinaryAsString({ bin.size(), bin.data() }, iStructType, nullptr);\n\t\t}\n\n\t\tvoid test(vector<SmartViewTestData> testData)\n\t\t{\n\t\t\tfor (auto data : testData)\n\t\t\t{\n\t\t\t\tAreEqualEx(data.expected, ParseString(data.hex, data.structType), data.testName.c_str());\n\n\t\t\t\tif (data.parseAll) {\n\t\t\t\t\tfor (ULONG i = IDS_STNOPARSING; i < IDS_STEND; i++) {\n\t\t\t\t\t\t\/\/Logger::WriteMessage(format(L\"Testing %ws\\n\", AddInStructTypeToString(static_cast<__ParsingTypeEnum>(i)).c_str()).c_str());\n\t\t\t\t\t\tAssert::IsTrue(ParseString(data.hex, data.structType).length() != 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Resource files saved in unicode have a byte order mark of 0xfeff\n\t\t\/\/ We load these in and strip the BOM.\n\t\t\/\/ Otherwise we load as ansi and convert to unicode\n\t\twstring loadfile(HMODULE handle, int name)\n\t\t{\n\t\t\tauto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE));\n\t\t\tauto rcData = ::LoadResource(handle, rc);\n\t\t\tauto cb = ::SizeofResource(handle, rc);\n\t\t\tauto bytes = ::LockResource(rcData);\n\t\t\tauto data = static_cast<const BYTE*>(bytes);\n\t\t\tif (cb >= 2 && data[0] == 0xfe && data[1] == 0xff)\n\t\t\t{\n\t\t\t\t\/\/ Skip the byte order mark\n\t\t\t\tauto wstr = static_cast<const wchar_t*>(bytes);\n\t\t\t\tauto cch = cb \/ sizeof(wchar_t);\n\t\t\t\treturn std::wstring(wstr + 1, cch - 1);\n\t\t\t}\n\n\t\t\tauto str = std::string(static_cast<const char*>(bytes), cb);\n\t\t\treturn stringTowstring(str);\n\t\t}\n\n\t\tvector<SmartViewTestData> loadTestData(HMODULE handle, std::initializer_list<SmartViewTestResource> resources)\n\t\t{\n\t\t\tvector<SmartViewTestData> testData;\n\t\t\tfor (auto resource : resources)\n\t\t\t{\n\t\t\t\ttestData.push_back(SmartViewTestData\n\t\t\t\t\t{\n\t\t\t\t\t\tresource.structType, resource.parseAll,\n\t\t\t\t\t\tformat(L\"%d\/%d\", resource.hex, resource.expected),\n\t\t\t\t\t\tloadfile(handle, resource.hex),\n\t\t\t\t\t\tloadfile(handle, resource.expected)\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn testData;\n\t\t}\n\n\tpublic:\n\t\tTEST_CLASS_INITIALIZE(Initialize_smartview)\n\t\t{\n\t\t\t\/\/ Set up our property arrays or nothing works\n\t\t\tMergeAddInArrays();\n\n\t\t\tRegKeys[regkeyDO_SMART_VIEW].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyUSE_GETPROPLIST].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyPARSED_NAMED_PROPS].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyCACHE_NAME_DPROPS].ulCurDWORD = 1;\n\n\t\t\tsetTestInstance(::GetModuleHandleW(L\"UnitTest.dll\"));\n\t\t}\n\n\t\tTEST_METHOD(Test_STADDITIONALRENENTRYIDSEX)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STAPPOINTMENTRECURRENCEPATTERN)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STCONVERSATIONINDEX)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STENTRYID)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }\n\t\t\t\t}));\n\t\t}\n\t};\n}<commit_msg>Do HexStringToBin on load<commit_after>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"Interpret\\SmartView\\SmartView.h\"\n#include \"Interpret\\SmartView\\SmartViewParser.h\"\n#include \"MFCMAPI.h\"\n#include \"resource.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace SmartViewTest\n{\n\tTEST_CLASS(SmartViewTest)\n\t{\n\tprivate:\n\t\tstruct SmartViewTestResource {\n\t\t\t__ParsingTypeEnum structType;\n\t\t\tbool parseAll;\n\t\t\tDWORD hex;\n\t\t\tDWORD expected;\n\t\t};\n\n\t\tstruct SmartViewTestData {\n\t\t\t__ParsingTypeEnum structType;\n\t\t\tbool parseAll;\n\t\t\twstring testName;\n\t\t\tvector<BYTE> hex;\n\t\t\twstring expected;\n\t\t};\n\n\t\tconst bool parseAll = false;\n\t\twstring ParseString(vector<BYTE> hex, __ParsingTypeEnum iStructType)\n\t\t{\n\t\t\treturn InterpretBinaryAsString({ hex.size(), hex.data() }, iStructType, nullptr);\n\t\t}\n\n\t\tvoid test(vector<SmartViewTestData> testData)\n\t\t{\n\t\t\tfor (auto data : testData)\n\t\t\t{\n\t\t\t\tAreEqualEx(data.expected, ParseString(data.hex, data.structType), data.testName.c_str());\n\n\t\t\t\tif (data.parseAll) {\n\t\t\t\t\tfor (ULONG i = IDS_STNOPARSING; i < IDS_STEND; i++) {\n\t\t\t\t\t\t\/\/Logger::WriteMessage(format(L\"Testing %ws\\n\", AddInStructTypeToString(static_cast<__ParsingTypeEnum>(i)).c_str()).c_str());\n\t\t\t\t\t\tAssert::IsTrue(ParseString(data.hex, data.structType).length() != 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Resource files saved in unicode have a byte order mark of 0xfeff\n\t\t\/\/ We load these in and strip the BOM.\n\t\t\/\/ Otherwise we load as ansi and convert to unicode\n\t\twstring loadfile(HMODULE handle, int name)\n\t\t{\n\t\t\tauto rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(TEXTFILE));\n\t\t\tauto rcData = ::LoadResource(handle, rc);\n\t\t\tauto cb = ::SizeofResource(handle, rc);\n\t\t\tauto bytes = ::LockResource(rcData);\n\t\t\tauto data = static_cast<const BYTE*>(bytes);\n\t\t\tif (cb >= 2 && data[0] == 0xfe && data[1] == 0xff)\n\t\t\t{\n\t\t\t\t\/\/ Skip the byte order mark\n\t\t\t\tauto wstr = static_cast<const wchar_t*>(bytes);\n\t\t\t\tauto cch = cb \/ sizeof(wchar_t);\n\t\t\t\treturn std::wstring(wstr + 1, cch - 1);\n\t\t\t}\n\n\t\t\tauto str = std::string(static_cast<const char*>(bytes), cb);\n\t\t\treturn stringTowstring(str);\n\t\t}\n\n\t\tvector<SmartViewTestData> loadTestData(HMODULE handle, std::initializer_list<SmartViewTestResource> resources)\n\t\t{\n\t\t\tvector<SmartViewTestData> testData;\n\t\t\tfor (auto resource : resources)\n\t\t\t{\n\t\t\t\ttestData.push_back(SmartViewTestData\n\t\t\t\t\t{\n\t\t\t\t\t\tresource.structType, resource.parseAll,\n\t\t\t\t\t\tformat(L\"%d\/%d\", resource.hex, resource.expected),\n\t\t\t\t\t\tHexStringToBin(loadfile(handle, resource.hex)),\n\t\t\t\t\t\tloadfile(handle, resource.expected)\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn testData;\n\t\t}\n\n\tpublic:\n\t\tTEST_CLASS_INITIALIZE(Initialize_smartview)\n\t\t{\n\t\t\t\/\/ Set up our property arrays or nothing works\n\t\t\tMergeAddInArrays();\n\n\t\t\tRegKeys[regkeyDO_SMART_VIEW].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyUSE_GETPROPLIST].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyPARSED_NAMED_PROPS].ulCurDWORD = 1;\n\t\t\tRegKeys[regkeyCACHE_NAME_DPROPS].ulCurDWORD = 1;\n\n\t\t\tsetTestInstance(::GetModuleHandleW(L\"UnitTest.dll\"));\n\t\t}\n\n\t\tTEST_METHOD(Test_STADDITIONALRENENTRYIDSEX)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI1IN, IDR_SV1AEI1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STADDITIONALRENENTRYIDSEX, parseAll, IDR_SV1AEI2IN, IDR_SV1AEI2OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STAPPOINTMENTRECURRENCEPATTERN)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP1IN, IDR_SV2ARP1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP2IN, IDR_SV2ARP2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP3IN, IDR_SV2ARP3OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STAPPOINTMENTRECURRENCEPATTERN, parseAll, IDR_SV2ARP4IN, IDR_SV2ARP4OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STCONVERSATIONINDEX)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI1IN, IDR_SV3CI1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI2IN, IDR_SV3CI2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STCONVERSATIONINDEX, parseAll, IDR_SV3CI3IN, IDR_SV3CI3OUT },\n\t\t\t\t}));\n\t\t}\n\n\t\tTEST_METHOD(Test_STENTRYID)\n\t\t{\n\t\t\ttest(loadTestData(::GetModuleHandleW(L\"UnitTest.dll\"),\n\t\t\t\t{\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID1IN, IDR_SV4EID1OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID2IN, IDR_SV4EID2OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID3IN, IDR_SV4EID3OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID4IN, IDR_SV4EID4OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID5IN, IDR_SV4EID5OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID6IN, IDR_SV4EID6OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID7IN, IDR_SV4EID7OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID8IN, IDR_SV4EID8OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID9IN, IDR_SV4EID9OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID10IN, IDR_SV4EID10OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID11IN, IDR_SV4EID11OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID12IN, IDR_SV4EID12OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID13IN, IDR_SV4EID13OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID14IN, IDR_SV4EID14OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID15IN, IDR_SV4EID15OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID16IN, IDR_SV4EID16OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID17IN, IDR_SV4EID17OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID18IN, IDR_SV4EID18OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID19IN, IDR_SV4EID19OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID20IN, IDR_SV4EID20OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID21IN, IDR_SV4EID21OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID22IN, IDR_SV4EID22OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID23IN, IDR_SV4EID23OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID24IN, IDR_SV4EID24OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID25IN, IDR_SV4EID25OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID26IN, IDR_SV4EID26OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID27IN, IDR_SV4EID27OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID28IN, IDR_SV4EID28OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID29IN, IDR_SV4EID29OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID30IN, IDR_SV4EID30OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID31IN, IDR_SV4EID31OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID32IN, IDR_SV4EID32OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID33IN, IDR_SV4EID33OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID34IN, IDR_SV4EID34OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID35IN, IDR_SV4EID35OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID36IN, IDR_SV4EID36OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID37IN, IDR_SV4EID37OUT },\n\t\t\t\t\tSmartViewTestResource{ IDS_STENTRYID, parseAll, IDR_SV4EID38IN, IDR_SV4EID38OUT }\n\t\t\t\t}));\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * =====================================================================================\n *\n * Filename: WebSocketConn.cpp\n *\n * Description: \n *\n * Version: 1.0\n * Created: 06\/23\/16 09:59:19\n * Revision: none\n * Compiler: gcc\n *\n * Author: YOUR NAME (), \n * Organization: \n *\n * =====================================================================================\n *\/\n#include <WebSocketConn.h>\n\nvoid WebSocketConn::OnRead()\n{\n for (;;)\n {\n uint32_t free_buf_len = m_in_buf.GetAllocSize() - m_in_buf.GetWriteOffset();\n if (free_buf_len < READ_BUF_SIZE)\n m_in_buf.Extend(READ_BUF_SIZE);\n int ret = netlib_recv(m_handle, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);\n if (ret <= 0)\n break;\n m_recv_bytes += ret;\n m_in_buf.IncWriteOffset(ret);\n m_last_recv_tick = get_tick_count();\n }\n\/*\n if(m_websocket == NULL)\n {\n m_websocket = new WebSocket;\n }\n*\/\n \n WebSocket websocket;\n if(m_websocket_inited)\n {\n CImPdu *pPdu = NULL;\n\n int data_size = m_in_buf.GetWriteOffset();\n unsigned char *dataBuffer = (unsigned char*)malloc(data_size);\n try{\n int data_length = 0;\n int use_length = 0;\n int read_count = 0;\n WebSocketFrameType frameType = websocket.getFrame(m_in_buf.GetBuffer() ,m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);\n \/\/log(\"len:%d use:%d\",m_in_buf.GetWriteOffset(),use_length);\n while(frameType == BINARY_FRAME || frameType == TEXT_FRAME)\n {\n read_count = read_count + use_length;\n while((pPdu = CImPdu::ReadPdu((uchar_t*)dataBuffer,data_length)))\n {\n uint32_t pdu_len = pPdu->GetLength();\n HandlePdu(pPdu);\n delete pPdu;\n pPdu = NULL;\n break;\n }\n m_in_buf.Read(NULL, use_length);\n if(read_count >= data_size) {\n break;\n }\n data_length = 0;\n use_length = 0;\n frameType = websocket.getFrame(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);\n }\n\n \/\/m_in_buf.~CSimpleBuffer();\n }catch(CPduException& ex)\n {\n\n }\n free(dataBuffer);\n\n }else \n {\n WebSocketFrameType type = websocket.parseHandshake(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset()); \n if(type == OPENING_FRAME) {\n string answer = websocket.answerHandshake();\n CMsgConn::Send((void *)answer.c_str(), answer.size());\n m_in_buf.Read(NULL, m_in_buf.GetWriteOffset());\n \/\/ m_in_buf.~CSimpleBuffer();\n m_websocket_inited = true; \n }else {\n \/\/OnClose();\n } \n }\n}\n\n\n\nint WebSocketConn::Send(void *data, int len)\n{\n WebSocket websocket;\n unsigned char* outData = (unsigned char*)malloc(len + 14);\n int out_len = websocket.makeFrame(BINARY_FRAME, (unsigned char*)data,len,outData ,len + 14);\n int result = CMsgConn::Send(outData ,out_len);\n free(outData);\n return result;\n}\n<commit_msg>update code<commit_after>\/*\n * =====================================================================================\n *\n * Filename: WebSocketConn.cpp\n *\n * Description: \n *\n * Version: 1.0\n * Created: 06\/23\/16 09:59:19\n * Revision: none\n * Compiler: gcc\n *\n * Author: YOUR NAME (), \n * Organization: \n *\n * =====================================================================================\n *\/\n#include <WebSocketConn.h>\n\nvoid WebSocketConn::OnRead()\n{\n for (;;)\n {\n uint32_t free_buf_len = m_in_buf.GetAllocSize() - m_in_buf.GetWriteOffset();\n if (free_buf_len < READ_BUF_SIZE)\n m_in_buf.Extend(READ_BUF_SIZE);\n int ret = 0;\n if(m_socket) {\n ret = netlib_socket_recv(m_socket, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);\n }else {\n ret = netlib_recv(m_handle, m_in_buf.GetBuffer() + m_in_buf.GetWriteOffset(), READ_BUF_SIZE);\n }\n if (ret <= 0)\n break;\n m_recv_bytes += ret;\n m_in_buf.IncWriteOffset(ret);\n m_last_recv_tick = get_tick_count();\n }\n\/*\n if(m_websocket == NULL)\n {\n m_websocket = new WebSocket;\n }\n*\/\n \n WebSocket websocket;\n if(m_websocket_inited)\n {\n CImPdu *pPdu = NULL;\n\n int data_size = m_in_buf.GetWriteOffset();\n unsigned char *dataBuffer = (unsigned char*)malloc(data_size);\n try{\n int data_length = 0;\n int use_length = 0;\n int read_count = 0;\n WebSocketFrameType frameType = websocket.getFrame(m_in_buf.GetBuffer() ,m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);\n \/\/log(\"len:%d use:%d\",m_in_buf.GetWriteOffset(),use_length);\n while(frameType == BINARY_FRAME || frameType == TEXT_FRAME)\n {\n read_count = read_count + use_length;\n while((pPdu = CImPdu::ReadPdu((uchar_t*)dataBuffer,data_length)))\n {\n uint32_t pdu_len = pPdu->GetLength();\n HandlePdu(pPdu);\n delete pPdu;\n pPdu = NULL;\n break;\n }\n m_in_buf.Read(NULL, use_length);\n if(read_count >= data_size) {\n break;\n }\n data_length = 0;\n use_length = 0;\n frameType = websocket.getFrame(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset() ,dataBuffer ,data_size, data_length,use_length);\n }\n\n \/\/m_in_buf.~CSimpleBuffer();\n }catch(CPduException& ex)\n {\n\n }\n free(dataBuffer);\n\n }else \n {\n WebSocketFrameType type = websocket.parseHandshake(m_in_buf.GetBuffer(),m_in_buf.GetWriteOffset()); \n if(type == OPENING_FRAME) {\n string answer = websocket.answerHandshake();\n CMsgConn::Send((void *)answer.c_str(), answer.size());\n m_in_buf.Read(NULL, m_in_buf.GetWriteOffset());\n \/\/ m_in_buf.~CSimpleBuffer();\n m_websocket_inited = true; \n }else {\n \/\/OnClose();\n } \n }\n}\n\n\n\nint WebSocketConn::Send(void *data, int len)\n{\n WebSocket websocket;\n unsigned char* outData = (unsigned char*)malloc(len + 14);\n int out_len = websocket.makeFrame(BINARY_FRAME, (unsigned char*)data,len,outData ,len + 14);\n int result = CMsgConn::Send(outData ,out_len);\n free(outData);\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>getClosestBall fix<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"src\/graphics.h\"\n#include \"src\/math.h\"\n\n#include <sys\/timeb.h>\n\n\/\/ Bresenham line drawing test\nvoid testBresenham(int ox, int oy, int r)\n{\n float l;\n unsigned int elapsed, numLines = 0;\n struct timeb startTime, endTime;\n printf(\"Bresenham drawing:\");\n\n ftime(&startTime);\n for(l = 0.0f; l < 2.0f*M_PI; l += 0.001f, numLines++)\n {\n int color = (int)((l * 10.f) + 1) % 256;\n drawLine(ox, oy, ox + r * cos(l), oy + r * sin(l), color);\n }\n ftime(&endTime);\n\n elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;\n printf(\" %u lines in %ums\", numLines, elapsed);\n}\n<commit_msg>Minor test update<commit_after>#include \"src\/graphics.h\"\n#include \"src\/math.h\"\n\n#include <sys\/timeb.h>\n\n\/\/ Bresenham line drawing test\nvoid testBresenham(int ox, int oy, int r)\n{\n float l;\n unsigned int elapsed, numLines = 0;\n struct timeb startTime, endTime;\n\n printf(\"Bresenham drawing: please wait...\\r\");\n\n ftime(&startTime);\n for(l = 0.0f; l < 2.0f*M_PI; l += 0.001f, numLines++)\n {\n int color = (int)((l * 10.f) + 1) % 256;\n drawLine(ox, oy, ox + r * cos(l), oy + r * sin(l), color);\n }\n ftime(&endTime);\n\n elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;\n printf(\"Bresenham drawing: %ums (%u lines)\", elapsed, numLines);\n}\n<|endoftext|>"} {"text":"<commit_before>{\n TProof::Open(\"pod:\/\/\");\n if (!gProof) return;\n\n TDSet *manual_dset = new TDSet(\"TTree\", \"deuterons\");\n TString user[3] = {\"m\/mpuccio\",\"m\/masera\",\"s\/sbufalin\"};\n for (int i = 0; i < 3; ++i)\n {\n TString ddset = Form(\"Find;BasePath=\/alice\/cern.ch\/user\/%s\/NucleiPbPb2011test\/output;FileName=*\/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=\/deuterons;Mode=local\",user[i].Data());\n\n TFileCollection *fc = gProof->GetDataSet(ddset.Data());\n\n \/\/ Create TDSet manually (terrible hack): apparently PROOF is stupid\n \/\/ and cannot create it correctly\n TFileInfo *fi;\n TIter next( fc->GetList() );\n while (( fi = (TFileInfo *)next() )) {\n const char *fn = fi->GetCurrentUrl()->GetUrl();\n Printf(\"adding: %s\", fn);\n manual_dset->Add( fn );\n }\n }\n\n const double kCent[4] = {0.,10.,30.,50.};\n const double kBins[29] = {\n 0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f,\n 1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f,\n 3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f\n };\n TH2F *hBins = new TH2F(\"hBins\",\"hBins\",3,kCent,28,kBins);\n TH1D *hCuts = new TH1D(\"hCuts\",\"hCuts\",10,0,10);\n TNamed *taskTitle = new TNamed(\"taskName\",\"deuteron3cent\");\n enum cutsName {kEtaMin=1,kEtaMax,kYMin,kYMax,kTPCsig,kTPCchi2,kSPDrec,kDCAxy,kDCAz,kRecreate};\n double cutsA[10] = {-0.8,0.8,-0.5,0.5,70,4.,1,0.5,1,1};\n for (int i = 1; i < 11; ++i) {\n hCuts->SetBinContent(i,cutsA[i - 1]);\n }\n gProof->AddInput(hBins);\n gProof->AddInput(hCuts);\n gProof->AddInput(taskTitle);\n \n \/\/ Process the TDset\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n \n \/\/ Other cuts\n hCuts->SetBinContent(10,0.);\n hCuts->SetBinContent(5,60);\n taskTitle.SetTitle(\"deuteron3cent_chi0\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n\n\n}\n<commit_msg>Complete cut variation in the steering macro (first attempt)<commit_after>{\n TProof::Open(\"pod:\/\/\");\n if (!gProof) return;\n\n TDSet *manual_dset = new TDSet(\"TTree\", \"deuterons\");\n TString user[3] = {\"m\/mpuccio\",\"m\/masera\",\"s\/sbufalin\"};\n for (int i = 0; i < 3; ++i)\n {\n TString ddset = Form(\"Find;BasePath=\/alice\/cern.ch\/user\/%s\/NucleiPbPb2011test\/output;FileName=*\/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=\/deuterons;Mode=local\",user[i].Data());\n\n TFileCollection *fc = gProof->GetDataSet(ddset.Data());\n\n \/\/ Create TDSet manually (terrible hack): apparently PROOF is stupid\n \/\/ and cannot create it correctly\n TFileInfo *fi;\n TIter next( fc->GetList() );\n while (( fi = (TFileInfo *)next() )) {\n const char *fn = fi->GetCurrentUrl()->GetUrl();\n Printf(\"adding: %s\", fn);\n manual_dset->Add( fn );\n }\n }\n\n const double kCent[4] = {0.,10.,30.,50.};\n const double kBins[29] = {\n 0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f,\n 1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f,\n 3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f\n };\n TH2F *hBins = new TH2F(\"hBins\",\"hBins\",3,kCent,28,kBins);\n TH1D *hCuts = new TH1D(\"hCuts\",\"hCuts\",10,0,10);\n TNamed *taskTitle = new TNamed(\"taskName\",\"deuteron3cent\");\n enum cutsName {kEtaMin=1,kEtaMax,kYMin,kYMax,kTPCsig,kTPCchi2,kSPDrec,kDCAxy,kDCAz,kRecreate};\n double cutsA[10] = {-0.8,0.8,-0.5,0.5,70,4.,1,0.5,1,1};\n for (int i = 1; i < 11; ++i) {\n hCuts->SetBinContent(i,cutsA[i - 1]);\n }\n gProof->AddInput(hBins);\n gProof->AddInput(hCuts);\n gProof->AddInput(taskTitle);\n \n \/\/ Process the TDset\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n \n \/\/ Other cuts\n hCuts->SetBinContent(10,0.);\n \/\/ chi2\n hCuts->SetBinContent(5,3.5);\n taskTitle->SetTitle(\"deuteron3cent_chi0\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(5,4.5);\n taskTitle->SetTitle(\"deuteron3cent_chi1\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(5,5);\n taskTitle->SetTitle(\"deuteron3cent_chi2\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(5,5.5);\n taskTitle->SetTitle(\"deuteron3cent_chi3\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(5,6.);\n taskTitle->SetTitle(\"deuteron3cent_chi4\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(5,4.);\n \/\/ dca_z\n hCuts->SetBinContent(9,0.5);\n taskTitle->SetTitle(\"deuteron3cent_dcaz0\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(9,0.75);\n taskTitle->SetTitle(\"deuteron3cent_dcaz1\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(9,1.5);\n taskTitle->SetTitle(\"deuteron3cent_dcaz2\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(9,2.);\n taskTitle->SetTitle(\"deuteron3cent_dcaz3\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(9,1.);\n \/\/ tpc\n hCuts->SetBinContent(4,60);\n taskTitle->SetTitle(\"deuteron3cent_tpc0\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(4,65);\n taskTitle->SetTitle(\"deuteron3cent_tpc1\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(4,75);\n taskTitle->SetTitle(\"deuteron3cent_tpc2\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n hCuts->SetBinContent(4,80);\n taskTitle->SetTitle(\"deuteron3cent_tpc3\");\n gProof->Process(manual_dset, \"AODSelector.cxx+g\");\n\n\n\n\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n1. Treat each edge id as a cluster, unordered map from edgeId to a set\n2. also store size of each cluster which will 0 in the begining\n\/\/ $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp\n\/\/ $ .\/calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv\n*\/\n#include <math.h> \n#include <ctime>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\n \n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 6){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.jaccs sortedjaccs.csv \"\n << \" Nthresholds threshDensity.csv\" << endl;\n exit(1);\n }\n \/\/ Nthresholds is the total thresholds user wants us to try\n int nThresh = atoi(argv[4]);\n cout << \"nThresh = \" << nThresh << endl;\n int gapBetweenthresh = 0;\n float threshold = 0;\n float D = 0.0;\n int mc, nc;\n int M = 0, Mns = 0;\n double wSum = 0.0;\n float highestD=0.0;\n float highestDThr = 0.0;\n \/\/************* got the args\n clock_t begin = clock(); \n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ store edge ids in a map\n \/\/ each edge id will be a cluster of it's own in the begining\n \/\/ each cluster will be og size 1\n map< int, pair<int,int> > idEdgePairMap;\n map< int, set<int > > index2cluster; \/\/ O(log n) access too slow?\n map< int, map< int, set<int > >::iterator > edge2iter;\n int ni, nj, edgeId, index = 0;\n while (inFile >> ni >> nj >> edgeId){ \n idEdgePairMap[ edgeId ] = make_pair(ni,nj);\n index2cluster[ index ].insert(edgeId); \/\/ build cluster index to set of edge-pairs map\n edge2iter[edgeId] = index2cluster.find(index); \n index++;\n }\n inFile.close(); inFile.clear();\n cout << \"There were \" << index2cluster.size() << \" edges. \";\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n \/\/\/ end reading edge ids ----- \n \n \/\/----- ----- ----- ----- \n ifstream sortedjaccFile; \n sortedjaccFile.open( argv[3] );\n if (!sortedjaccFile) {\n cout << \"ERROR: unable to open sortedjaccFile file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int totalThresh = 0;\n int edgeId1,edgeId2;\n double jacc; \n \/\/ Count totalines in the file, we are setting \n while ( sortedjaccFile >> jacc ) {\n if(jacc>0 && jacc<=1.0)\n totalThresh++;\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n cout << \"Done counting totalines in the file, \\nTotal unique Jaccs = \" << totalThresh;\n cout << \". Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n if(totalThresh==0){\n cout << \"ERROR: there are 0 Jaccs!!!\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ now we want gap between two consecutive thresholds\n \/\/ we want to consider\n gapBetweenthresh = totalThresh\/nThresh;\n if(totalThresh < nThresh)\n gapBetweenthresh = totalThresh;\n set<float> thresholdSet;\n set<float> ::reverse_iterator thIt;\n cout << \"thresholds\" << endl;\n \/\/ ----------------------------\n totalThresh = -1;\n sortedjaccFile.open( argv[3] );\n while ( sortedjaccFile >> jacc ){\n totalThresh++;\n if(totalThresh%gapBetweenthresh!=0){\n continue;\n }\n cout << jacc << endl;\n thresholdSet.insert(jacc);\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n thresholdSet.insert(1.1);\n cout << \"Done with thresholdSet creation.\";\n cout << \" Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n \/\/ ---------------------------\n\n ifstream jaccFile; \n jaccFile.open(argv[2]);\n \/\/ read first line\n jaccFile >> edgeId1 >> edgeId2 >> jacc ;\n \/\/ open the outputfile\n map< int, set< int> >::iterator iter_i,iter_j;\n set<int>::iterator iterS;\n FILE * threshDensityFile = fopen( argv[5], \"w\" ); \n fclose(threshDensityFile);\n fprintf( threshDensityFile, \"thresh D\\n\" );\n long long done = 0;\n float percDone = 0.01;\n clock_t lastBegin = clock(); \n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n threshold = *thIt;\n if (threshold < 0.0 || threshold > 1.11){\n cout << \"ERROR: specified threshold not in [0,1]: \" << threshold << endl;\n exit(1);\n }\n cout << \" Starting new clustering...... \" ;\n do{\n if( jacc < threshold ) \n break; \n iter_i = edge2iter[ edgeId1 ];\n iter_j = edge2iter[ edgeId2 ];\n if ( iter_i != iter_j ) {\n \/\/cout << edgeId1 << \" \" << edgeId2 << \" \" << jacc << endl;\n \/\/ always merge smaller cluster into bigger:\n if ( (*iter_j).second.size() > (*iter_i).second.size() ){ \/\/ !!!!!!\n swap(iter_i, iter_j);\n } \n \/\/ merge cluster j into i and update index for all elements in j:\n \/\/cout << \"merging cluster \" << endl;\n for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){\n iter_i->second.insert( *iterS );\n edge2iter[ *iterS ] = iter_i;\n } \n \n \/\/ delete cluster j:\n cout << \"Deleting cluster \" << endl;\n index2cluster.erase(iter_j);\n cout << \"Done deleteing \" << endl;\n }\n }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );\n cout << \" Done!\" << endl; \n \/\/ all done clustering, write to file (and calculated partition density):\n M = 0, Mns = 0;\n wSum = 0.0;\n set< int >::iterator S;\n set<int> clusterNodes;\n map< int, set< int > >::iterator it;\n for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {\n clusterNodes.clear();\n for (S = it->second.begin(); S != it->second.end(); S++ ){\n \/\/fprintf( clustersFile, \"%i \", *S ); \/\/ this leaves a trailing space...!\n clusterNodes.insert(idEdgePairMap[*S].first);\n clusterNodes.insert(idEdgePairMap[*S].second);\n }\n mc = it->second.size();\n nc = clusterNodes.size();\n M += mc;\n if (nc > 2) {\n Mns += mc;\n wSum += mc * (mc - (nc-1.0)) \/ ((nc-2.0)*(nc-1.0));\n }\n } \n threshDensityFile = fopen( argv[5], \"a\" ); \n D = 2.0 * wSum \/ M;\n if (isinf(D)){\n fprintf( threshDensityFile, \"\\nERROR: D == -inf \\n\\n\"); \n fclose(threshDensityFile);\n exit(1);\n }\n \/\/*************\n fprintf( threshDensityFile, \"%.6f %.6f \\n\", threshold, D);\n fclose(threshDensityFile);\n if(D > highestD){\n highestD = D;\n highestDThr = threshold;\n } \n done++;\n if((float)done\/(float)thresholdSet.size() >= percDone){\n cout << percDone*100 << \" pc done.\\n\" << endl;\n percDone += 0.01;\n }\n cout << \"Time taken = \" << double(clock() - lastBegin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n lastBegin = clock();\n }\n jaccFile.close(); jaccFile.clear();\n fprintf( threshDensityFile, \"\\n highest D=%.6f at thresh:%.6f.\\n\", highestD, highestDThr);\n fclose(threshDensityFile);\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<commit_msg>Update calcDensityForDiffThresh.cpp<commit_after>\/*\n1. Treat each edge id as a cluster, unordered map from edgeId to a set\n2. also store size of each cluster which will 0 in the begining\n\/\/ $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp\n\/\/ $ .\/calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv\n*\/\n#include <math.h> \n#include <ctime>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\n \n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 6){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.jaccs sortedjaccs.csv \"\n << \" Nthresholds threshDensity.csv\" << endl;\n exit(1);\n }\n \/\/ Nthresholds is the total thresholds user wants us to try\n int nThresh = atoi(argv[4]);\n cout << \"nThresh = \" << nThresh << endl;\n int gapBetweenthresh = 0;\n float threshold = 0;\n float D = 0.0;\n int mc, nc;\n int M = 0, Mns = 0;\n double wSum = 0.0;\n float highestD=0.0;\n float highestDThr = 0.0;\n \/\/************* got the args\n clock_t begin = clock(); \n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ store edge ids in a map\n \/\/ each edge id will be a cluster of it's own in the begining\n \/\/ each cluster will be og size 1\n map< int, pair<int,int> > idEdgePairMap;\n map< int, set<int > > index2cluster; \/\/ O(log n) access too slow?\n map< int, map< int, set<int > >::iterator > edge2iter;\n int ni, nj, edgeId, index = 0;\n while (inFile >> ni >> nj >> edgeId){ \n idEdgePairMap[ edgeId ] = make_pair(ni,nj);\n index2cluster[ index ].insert(edgeId); \/\/ build cluster index to set of edge-pairs map\n edge2iter[edgeId] = index2cluster.find(index); \n index++;\n }\n inFile.close(); inFile.clear();\n cout << \"There were \" << index2cluster.size() << \" edges. \";\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n \/\/\/ end reading edge ids ----- \n \n \/\/----- ----- ----- ----- \n ifstream sortedjaccFile; \n sortedjaccFile.open( argv[3] );\n if (!sortedjaccFile) {\n cout << \"ERROR: unable to open sortedjaccFile file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int totalThresh = 0;\n int edgeId1,edgeId2;\n double jacc; \n \/\/ Count totalines in the file, we are setting \n while ( sortedjaccFile >> jacc ) {\n if(jacc>0 && jacc<=1.0)\n totalThresh++;\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n cout << \"Done counting totalines in the file, \\nTotal unique Jaccs = \" << totalThresh;\n cout << \". Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n if(totalThresh==0){\n cout << \"ERROR: there are 0 Jaccs!!!\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ now we want gap between two consecutive thresholds\n \/\/ we want to consider\n gapBetweenthresh = totalThresh\/nThresh;\n if(totalThresh < nThresh)\n gapBetweenthresh = totalThresh;\n set<float> thresholdSet;\n set<float> ::reverse_iterator thIt;\n cout << \"thresholds\" << endl;\n \/\/ ----------------------------\n totalThresh = -1;\n sortedjaccFile.open( argv[3] );\n while ( sortedjaccFile >> jacc ){\n totalThresh++;\n if(totalThresh%gapBetweenthresh!=0){\n continue;\n }\n cout << jacc << endl;\n thresholdSet.insert(jacc);\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n thresholdSet.insert(1.1);\n cout << \"Done with thresholdSet creation.\";\n cout << \" Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n \/\/ ---------------------------\n\n ifstream jaccFile; \n jaccFile.open(argv[2]);\n \/\/ read first line\n jaccFile >> edgeId1 >> edgeId2 >> jacc ;\n \/\/ open the outputfile\n map< int, set< int> >::iterator iter_i,iter_j;\n set<int>::iterator iterS;\n FILE * threshDensityFile = fopen( argv[5], \"w\" ); \n fclose(threshDensityFile);\n fprintf( threshDensityFile, \"thresh D\\n\" );\n long long done = 0;\n float percDone = 0.01;\n clock_t lastBegin = clock(); \n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n threshold = *thIt;\n if (threshold < 0.0 || threshold > 1.11){\n cout << \"ERROR: specified threshold not in [0,1]: \" << threshold << endl;\n exit(1);\n }\n cout << \" Starting new clustering...... \" ;\n do{\n if( jacc < threshold ) \n break; \n iter_i = edge2iter[ edgeId1 ];\n iter_j = edge2iter[ edgeId2 ];\n if ( iter_i != iter_j ) {\n \/\/cout << edgeId1 << \" \" << edgeId2 << \" \" << jacc << endl;\n \/\/ always merge smaller cluster into bigger:\n if ( (*iter_j).second.size() > (*iter_i).second.size() ){ \/\/ !!!!!!\n swap(iter_i, iter_j);\n } \n \/\/ merge cluster j into i and update index for all elements in j:\n \/\/cout << \"merging cluster \" << endl;\n for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){\n iter_i->second.insert( *iterS );\n edge2iter[ *iterS ] = iter_i;\n } \n \n \/\/ delete cluster j:\n \/\/cout << \"Deleting cluster \" << endl;\n index2cluster.erase(iter_j);\n \/\/cout << \"Done deleteing \" << endl;\n }\n }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );\n cout << \" Done!\" << endl; \n \/\/ all done clustering, write to file (and calculated partition density):\n M = 0, Mns = 0;\n wSum = 0.0;\n set< int >::iterator S;\n set<int> clusterNodes;\n map< int, set< int > >::iterator it;\n for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {\n clusterNodes.clear();\n for (S = it->second.begin(); S != it->second.end(); S++ ){\n \/\/fprintf( clustersFile, \"%i \", *S ); \/\/ this leaves a trailing space...!\n clusterNodes.insert(idEdgePairMap[*S].first);\n clusterNodes.insert(idEdgePairMap[*S].second);\n }\n mc = it->second.size();\n nc = clusterNodes.size();\n M += mc;\n if (nc > 2) {\n Mns += mc;\n wSum += mc * (mc - (nc-1.0)) \/ ((nc-2.0)*(nc-1.0));\n }\n } \n threshDensityFile = fopen( argv[5], \"a\" ); \n D = 2.0 * wSum \/ M;\n if (isinf(D)){\n fprintf( threshDensityFile, \"\\nERROR: D == -inf \\n\\n\"); \n fclose(threshDensityFile);\n exit(1);\n }\n \/\/*************\n fprintf( threshDensityFile, \"%.6f %.6f \\n\", threshold, D);\n fclose(threshDensityFile);\n if(D > highestD){\n highestD = D;\n highestDThr = threshold;\n } \n done++;\n if((float)done\/(float)thresholdSet.size() >= percDone){\n cout << percDone*100 << \" pc done.\\n\" << endl;\n percDone += 0.01;\n }\n cout << \"Time taken = \" << double(clock() - lastBegin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n lastBegin = clock();\n }\n jaccFile.close(); jaccFile.clear();\n fprintf( threshDensityFile, \"\\n highest D=%.6f at thresh:%.6f.\\n\", highestD, highestDThr);\n fclose(threshDensityFile);\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n1. Treat each edge id as a cluster, unordered map from edgeId to a set\n2. also store size of each cluster which will 0 in the begining\n\/\/ $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp\n\/\/ $ .\/calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv\n*\/\n#include <math.h> \n#include <ctime>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\n \n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 4){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.jaccs sortedjaccs.csv \"\n << \" Nthresholds threshDensity.csv\" << endl;\n exit(1);\n }\n \/\/ Nthresholds is the total thresholds user wants us to try\n int nThresh = atoi(argv[4]);\n int gapBetweenthresh = 0;\n float threshold = 0;\n float D = 0.0;\n int mc, nc;\n int M = 0, Mns = 0;\n double wSum = 0.0;\n float highestD=0.0;\n float highestDThr = 0.0;\n \/\/************* got the args\n clock_t begin = clock(); \n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ store edge ids in a map\n \/\/ each edge id will be a cluster of it's own in the begining\n \/\/ each cluster will be og size 1\n unordered_map< int, pair<int,int> > idEdgePairMap;\n unordered_map< int, set<int > > index2cluster; \/\/ O(log n) access too slow?\n unordered_map< int, unordered_map< int, set<int > >::iterator > edge2iter;\n int ni, nj, edgeId, index = 0;\n while (inFile >> ni >> nj >> edgeId){ \n idEdgePairMap[ edgeId ] = make_pair(ni,nj);\n index2cluster[ index ].insert(edgeId); \/\/ build cluster index to set of edge-pairs map\n edge2iter[edgeId] = index2cluster.find(index); \n index++;\n }\n inFile.close(); inFile.clear();\n cout << \"There were \" << index2cluster.size() << \" edges.\" << endl;\n \/\/\/ end reading edge ids ----- \n \n \/\/----- ----- ----- ----- \n ifstream sortedjaccFile; \n sortedjaccFile.open( argv[3] );\n if (!sortedjaccFile) {\n cout << \"ERROR: unable to open sortedjaccFile file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int totalThresh = 0;\n int edgeId1,edgeId2;\n float jacc; \n \/\/ Count totalines in the file, we are setting \n while ( sortedjaccFile >> jacc ) {\n if(jacc>0 && jacc<=1.0)\n totalThresh++;\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n cout << \"Done counting totalines in the file, \\nTotal unique Jaccs = \" << totalThresh << endl;\n if(totalThresh==0){\n cout << \"ERROR: there are 0 Jaccs!!!\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ now we want gap between two consecutive thresholds\n \/\/ we want to consider\n gapBetweenthresh = totalThresh\/nThresh;\n if(totalThresh < nThresh)\n gapBetweenthresh = totalThresh;\n set<float> thresholdSet;\n set<float> ::reverse_iterator thIt;\n \/\/ ----------------------------\n totalThresh = -1;\n sortedjaccFile.open( argv[3] );\n while ( sortedjaccFile >> jacc ){\n totalThresh++;\n if(totalThresh%gapBetweenthresh!=0){\n continue;\n }\n thresholdSet.insert(jacc);\n }\n thresholdSet.insert(1.1);\n cout << \"Done with thresholdSet creation.\" << endl;\n \/\/ ---------------------------\n\n ifstream jaccFile; \n jaccFile.open(argv[2]);\n \/\/ read first line\n jaccFile >> edgeId1 >> edgeId2 >> jacc ;\n \/\/ open the outputfile\n unordered_map< int, set< int> >::iterator iter_i,iter_j;\n set<int>::iterator iterS;\n FILE * threshDensityFile = fopen( argv[3], \"w\" ); \n fclose(threshDensityFile);\n fprintf( threshDensityFile, \"thresh D\\n\" );\n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n threshold = *thIt;\n if (threshold < 0.0 || threshold > 1.0){\n cout << \"ERROR: specified threshold not in [0,1]\" << endl;\n exit(1);\n }\n do{\n if( jacc < threshold ) \n break; \n iter_i = edge2iter[ edgeId1 ];\n iter_j = edge2iter[ edgeId2 ];\n if ( iter_i != iter_j ) {\n \/\/ always merge smaller cluster into bigger:\n if ( (*iter_j).second.size() > (*iter_i).second.size() ){ \/\/ !!!!!!\n swap(iter_i, iter_j);\n } \n \/\/ merge cluster j into i and update index for all elements in j:\n for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){\n iter_i->second.insert( *iterS );\n edge2iter[ *iterS ] = iter_i;\n } \n \/\/ delete cluster j:\n index2cluster.erase(iter_j);\n }\n }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );\n \n \/\/ all done clustering, write to file (and calculated partition density):\n M = 0, Mns = 0;\n wSum = 0.0;\n set< int >::iterator S;\n set<int> clusterNodes;\n unordered_map< int, set< int > >::iterator it;\n for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {\n clusterNodes.clear();\n for (S = it->second.begin(); S != it->second.end(); S++ ){\n \/\/fprintf( clustersFile, \"%i \", *S ); \/\/ this leaves a trailing space...!\n clusterNodes.insert(idEdgePairMap[*S].first);\n clusterNodes.insert(idEdgePairMap[*S].second);\n }\n mc = it->second.size();\n nc = clusterNodes.size();\n M += mc;\n if (nc > 2) {\n Mns += mc;\n wSum += mc * (mc - (nc-1.0)) \/ ((nc-2.0)*(nc-1.0));\n }\n } \n threshDensityFile = fopen( argv[3], \"a\" ); \n D = 2.0 * wSum \/ M;\n if (isinf(D)){\n fprintf( threshDensityFile, \"\\nERROR: D == -inf \\n\\n\"); \n fclose(threshDensityFile);\n exit(1);\n }\n \/\/*************\n fprintf( threshDensityFile, \"%.6f %.6f \", threshold, D);\n fclose(threshDensityFile);\n if(D > highestD){\n highestD = D;\n highestDThr = threshold;\n } \n }\n jaccFile.close(); jaccFile.clear();\n fprintf( threshDensityFile, \"\\n highest D=%.6f at thresh:%.6f.\\n\", highestD, highestDThr);\n fclose(threshDensityFile);\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<commit_msg>Update calcDensityForDiffThresh.cpp<commit_after>\/*\n1. Treat each edge id as a cluster, unordered map from edgeId to a set\n2. also store size of each cluster which will 0 in the begining\n\/\/ $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp\n\/\/ $ .\/calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv\n*\/\n#include <math.h> \n#include <ctime>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n#include <set>\n#include <map>\n#include <utility> \/\/ for pairs\n#include <algorithm> \/\/ for swap\nusing namespace std;\n\n \n\nint main (int argc, char const *argv[]){\n \/\/************* make sure args are present:\n if (argc != 4){\n cout << \"ERROR: something wrong with the inputs\" << endl;\n cout << \"usage:\\n \" << argv[0] << \" networkEdgeIdMap.csv network.jaccs sortedjaccs.csv \"\n << \" Nthresholds threshDensity.csv\" << endl;\n exit(1);\n }\n \/\/ Nthresholds is the total thresholds user wants us to try\n int nThresh = atoi(argv[4]);\n int gapBetweenthresh = 0;\n float threshold = 0;\n float D = 0.0;\n int mc, nc;\n int M = 0, Mns = 0;\n double wSum = 0.0;\n float highestD=0.0;\n float highestDThr = 0.0;\n \/\/************* got the args\n clock_t begin = clock(); \n \n \/\/************* start load edgelist\n ifstream inFile;\n inFile.open( argv[1] );\n if (!inFile) {\n cout << \"ERROR: unable to open input file\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ store edge ids in a map\n \/\/ each edge id will be a cluster of it's own in the begining\n \/\/ each cluster will be og size 1\n unordered_map< int, pair<int,int> > idEdgePairMap;\n unordered_map< int, set<int > > index2cluster; \/\/ O(log n) access too slow?\n unordered_map< int, unordered_map< int, set<int > >::iterator > edge2iter;\n int ni, nj, edgeId, index = 0;\n while (inFile >> ni >> nj >> edgeId){ \n idEdgePairMap[ edgeId ] = make_pair(ni,nj);\n index2cluster[ index ].insert(edgeId); \/\/ build cluster index to set of edge-pairs map\n edge2iter[edgeId] = index2cluster.find(index); \n index++;\n }\n inFile.close(); inFile.clear();\n cout << \"There were \" << index2cluster.size() << \" edges.\" << endl;\n \/\/\/ end reading edge ids ----- \n \n \/\/----- ----- ----- ----- \n ifstream sortedjaccFile; \n sortedjaccFile.open( argv[3] );\n if (!sortedjaccFile) {\n cout << \"ERROR: unable to open sortedjaccFile file\" << endl;\n exit(1); \/\/ terminate with error\n }\n int totalThresh = 0;\n int edgeId1,edgeId2;\n float jacc; \n \/\/ Count totalines in the file, we are setting \n while ( sortedjaccFile >> jacc ) {\n if(jacc>0 && jacc<=1.0)\n totalThresh++;\n }\n sortedjaccFile.close(); sortedjaccFile.clear();\n cout << \"Done counting totalines in the file, \\nTotal unique Jaccs = \" << totalThresh << endl;\n if(totalThresh==0){\n cout << \"ERROR: there are 0 Jaccs!!!\" << endl;\n exit(1); \/\/ terminate with error\n }\n \/\/ now we want gap between two consecutive thresholds\n \/\/ we want to consider\n gapBetweenthresh = totalThresh\/nThresh;\n if(totalThresh < nThresh)\n gapBetweenthresh = totalThresh;\n set<float> thresholdSet;\n set<float> ::reverse_iterator thIt;\n \/\/ ----------------------------\n totalThresh = -1;\n sortedjaccFile.open( argv[3] );\n while ( sortedjaccFile >> jacc ){\n totalThresh++;\n if(totalThresh%gapBetweenthresh!=0){\n continue;\n }\n thresholdSet.insert(jacc);\n }\n thresholdSet.insert(1.1);\n cout << \"Done with thresholdSet creation.\" << endl;\n \/\/ ---------------------------\n\n ifstream jaccFile; \n jaccFile.open(argv[2]);\n \/\/ read first line\n jaccFile >> edgeId1 >> edgeId2 >> jacc ;\n \/\/ open the outputfile\n unordered_map< int, set< int> >::iterator iter_i,iter_j;\n set<int>::iterator iterS;\n FILE * threshDensityFile = fopen( argv[3], \"w\" ); \n fclose(threshDensityFile);\n fprintf( threshDensityFile, \"thresh D\\n\" );\n long long done = 0;\n float percDone = 0.01;\n clock_t lastBegin = clock(); \n for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){\n threshold = *thIt;\n if (threshold < 0.0 || threshold > 1.0){\n cout << \"ERROR: specified threshold not in [0,1]\" << endl;\n exit(1);\n }\n do{\n if( jacc < threshold ) \n break; \n iter_i = edge2iter[ edgeId1 ];\n iter_j = edge2iter[ edgeId2 ];\n if ( iter_i != iter_j ) {\n \/\/ always merge smaller cluster into bigger:\n if ( (*iter_j).second.size() > (*iter_i).second.size() ){ \/\/ !!!!!!\n swap(iter_i, iter_j);\n } \n \/\/ merge cluster j into i and update index for all elements in j:\n for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){\n iter_i->second.insert( *iterS );\n edge2iter[ *iterS ] = iter_i;\n } \n \/\/ delete cluster j:\n index2cluster.erase(iter_j);\n }\n }while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ); \n \/\/ all done clustering, write to file (and calculated partition density):\n M = 0, Mns = 0;\n wSum = 0.0;\n set< int >::iterator S;\n set<int> clusterNodes;\n unordered_map< int, set< int > >::iterator it;\n for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {\n clusterNodes.clear();\n for (S = it->second.begin(); S != it->second.end(); S++ ){\n \/\/fprintf( clustersFile, \"%i \", *S ); \/\/ this leaves a trailing space...!\n clusterNodes.insert(idEdgePairMap[*S].first);\n clusterNodes.insert(idEdgePairMap[*S].second);\n }\n mc = it->second.size();\n nc = clusterNodes.size();\n M += mc;\n if (nc > 2) {\n Mns += mc;\n wSum += mc * (mc - (nc-1.0)) \/ ((nc-2.0)*(nc-1.0));\n }\n } \n threshDensityFile = fopen( argv[3], \"a\" ); \n D = 2.0 * wSum \/ M;\n if (isinf(D)){\n fprintf( threshDensityFile, \"\\nERROR: D == -inf \\n\\n\"); \n fclose(threshDensityFile);\n exit(1);\n }\n \/\/*************\n fprintf( threshDensityFile, \"%.6f %.6f \\n\", threshold, D);\n fclose(threshDensityFile);\n if(D > highestD){\n highestD = D;\n highestDThr = threshold;\n } \n done++;\n if((float)done\/(float)thresholdSet.size() >= percDone){\n cout << percDone*100 << \" pc done.\\n\" << endl;\n percDone += 0.01;\n }\n cout << \"Time taken = \" << double(clock() - lastBegin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n lastBegin = clock();\n }\n jaccFile.close(); jaccFile.clear();\n fprintf( threshDensityFile, \"\\n highest D=%.6f at thresh:%.6f.\\n\", highestD, highestDThr);\n fclose(threshDensityFile);\n cout << \"Time taken = \" << double(clock() - begin)\/ CLOCKS_PER_SEC << \" seconds. \"<< endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ TreeView.cpp\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"App.h\"\n#include \"TreeView.h\"\n#include \"MenuEnum.h\"\t\/\/ for LayerTree_Ctrl\n#include \"Frame.h\"\n#include \"BuilderView.h\"\n\nDECLARE_APP(MyApp)\n\n\/\/ Under Windows, the icons are in the .rc file; on Unix, they are included\n\/\/ from .xpm files.\n#ifndef __WXMSW__\n#include \"building.xpm\"\n#include \"file1.xpm\"\n#include \"file2.xpm\"\n#include \"folder1.xpm\"\n#include \"folder2.xpm\"\n#include \"folder3.xpm\"\n\n#include \"grid.xpm\"\n#include \"image.xpm\"\n#include \"raw.xpm\"\n#include \"road.xpm\"\n#include \"veg1.xpm\"\n#include \"water.xpm\"\n#include \"util.xpm\"\n#include \"transit.xpm\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ MyTreeCtrl implementation\nIMPLEMENT_DYNAMIC_CLASS(MyTreeCtrl, wxTreeCtrl)\n\nMyTreeCtrl::MyTreeCtrl(wxWindow *parent, const wxWindowID id,\n\tconst wxPoint& pos, const wxSize& size,\n\tlong style)\n: wxTreeCtrl(parent, id, pos, size, style)\n{\n\tm_reverseSort = false;\n\tm_imageListNormal = NULL;\n\tm_bShowPaths = true;\n\n\tCreateImageList(16);\n\n\t\/\/ Add some items to the tree\n\tRefreshTreeItems(NULL);\n}\n\nvoid MyTreeCtrl::CreateImageList(int size)\n{\n\tdelete m_imageListNormal;\n\n\tif ( size == -1 )\n\t{\n\t\tm_imageListNormal = NULL;\n\t\treturn;\n\t}\n\n\t\/\/ Make an image list containing small icons\n\tm_imageListNormal = new wxImageList(size, size, TRUE);\n\n\t\/\/ should correspond to TreeCtrlIcon_xxx enum\n\twxIcon icons[14];\n\ticons[0] = wxICON(file1);\n\ticons[1] = wxICON(file2);\n\ticons[2] = wxICON(folder1);\n\ticons[3] = wxICON(folder2);\n\ticons[4] = wxICON(folder3);\n\ticons[5] = wxICON(building);\n\ticons[6] = wxICON(road);\n\ticons[7] = wxICON(grid);\n\ticons[8] = wxICON(image);\n\ticons[9] = wxICON(veg1);\n\ticons[10] = wxICON(water);\n\ticons[11] = wxICON(transit);\n\ticons[12] = wxICON(util);\n\ticons[13] = wxICON(raw);\n\n\tint sizeOrig = icons[0].GetWidth();\n\tfor ( size_t i = 0; i < WXSIZEOF(icons); i++ )\n\t{\n\t\tif ( size == sizeOrig )\n\t\t\tm_imageListNormal->Add(icons[i]);\n\t\telse\n\t\t\tm_imageListNormal->Add(wxImage(icons[i]).Rescale(size, size).\n\t\t\t\tConvertToBitmap());\n\t}\n\n\tSetImageList(m_imageListNormal);\n}\n\nMyTreeCtrl::~MyTreeCtrl()\n{\n\tdelete m_imageListNormal;\n}\n\nint MyTreeCtrl::OnCompareItems(const wxTreeItemId& item1,\n\tconst wxTreeItemId& item2)\n{\n\tif ( m_reverseSort )\n\t{\n\t\t\/\/ just exchange 1st and 2nd items\n\t\treturn wxTreeCtrl::OnCompareItems(item2, item1);\n\t}\n\telse\n\t{\n\t\treturn wxTreeCtrl::OnCompareItems(item1, item2);\n\t}\n}\n\nwxTreeItemId rootId;\n\nwxTreeItemId MyTreeCtrl::AddRootItem(int image, const char *text)\n{\n\twxTreeItemId id = AppendItem(rootId, text, image);\n\tSetItemBold(id);\n\treturn id;\n}\n\nwxString MyTreeCtrl::MakeItemName(vtLayerPtr lp)\n{\n\twxString str;\n\tif (lp->GetModified())\n\t\tstr += \"(*) \";\n\twxString fullpath = lp->GetFilename();\n\tif (!m_bShowPaths)\n\t{\n\t\tif (fullpath.Find('\/') != -1)\n\t\t\tfullpath = fullpath.AfterLast('\/');\n\t\tif (fullpath.Find('\\\\') != -1)\n\t\t\tfullpath = fullpath.AfterLast('\\\\');\n\t\tif (fullpath.Find(':') != -1)\n\t\t\tfullpath = fullpath.AfterLast(':');\n\t}\n\tstr += fullpath;\n\treturn str;\n}\n\nvoid MyTreeCtrl::RefreshTreeItems(MainFrame *pFrame)\n{\n\tDeleteAllItems();\n\n\trootId = AddRoot(\"Layers\");\n\tSetItemBold(rootId);\n\n\tint\timage, imageSel;\n\n\twxTreeItemId elevId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Grid, \"Elevation\");\n#ifndef ELEVATION_ONLY\n\twxTreeItemId imageId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Image, \"Images\");\n\twxTreeItemId buildId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Building, \"Structures\");\n\twxTreeItemId roadId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Road, \"Roads\");\n\twxTreeItemId vegId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Veg1, \"Vegetation\");\n\twxTreeItemId waterId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Water, \"Water\");\n#if SUPPORT_TRANSIT\n\twxTreeItemId transId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Transit, \"Transit\");\n#endif\n\twxTreeItemId utilityId = AddRootItem(MyTreeCtrl::TreeCtrlIcon_Utility, \"Utilities\");\n#endif\n\twxTreeItemId rawId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Raw, \"Raw\");\n\n\timage = TreeCtrlIcon_File;\n\timageSel = TreeCtrlIcon_FileSelected;\n\tvtLayerPtr lp;\n\tint iLayers = 0;\n\tif (pFrame) iLayers = pFrame->m_Layers.GetSize();\n\tfor (int i = 0; i < iLayers; i++)\n\t{\n\t\tlp = pFrame->m_Layers.GetAt(i);\n\n\t\twxString str = MakeItemName(lp);\n\n\t\twxTreeItemId hItem = -1;\n\t\tswitch (lp->GetType())\n\t\t{\n\t\t\tcase LT_ELEVATION:\n\t\t\t\thItem = AppendItem(elevId, str, image, imageSel);\n\t\t\t\tbreak;\n#ifndef ELEVATION_ONLY\n\t\t\tcase LT_IMAGE:\n\t\t\t\thItem = AppendItem(imageId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_ROAD:\n\t\t\t\thItem = AppendItem(roadId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_STRUCTURE:\n\t\t\t\thItem = AppendItem(buildId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_VEG:\n\t\t\t\thItem = AppendItem(vegId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_WATER:\n\t\t\t\thItem = AppendItem(waterId, str, image, imageSel);\n\t\t\t\tbreak;\n#if SUPPORT_TRANSIT\n\t\t\tcase LT_TRANSIT:\n\t\t\t\thItem = AppendItem(transId, str, image, imageSel);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase LT_UTILITY:\n\t\t\t\thItem = AppendItem(utilityId, str, image, imageSel);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase LT_RAW:\n\t\t\t\thItem = AppendItem(rawId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t}\n\t\tif (hItem != -1)\n\t\t{\n\t\t\tSetItemData(hItem, new MyTreeItemData(lp));\n\n\t\t\tif (lp == pFrame->GetActiveLayer())\n\t\t\t\tSelectItem(hItem);\n\t\t}\n\t}\n\n\tExpand(rootId);\n\tExpand(elevId);\n#ifndef ELEVATION_ONLY\n\tExpand(imageId);\n\tExpand(roadId);\n\tExpand(buildId);\n\tExpand(vegId);\n\tExpand(waterId);\n#if SUPPORT_TRANSIT\n\tExpand(transId);\n#endif\n\tExpand(utilityId);\n#endif\n\tExpand(rawId);\n}\n\nvoid MyTreeCtrl::RefreshTreeStatus(MainFrame *pFrame)\n{\n\twxTreeItemId root = GetRootItem();\n\twxTreeItemId parent, item;\n\tlong cookie = 0, cookie2 = 1;\n\n\tfor (parent = GetFirstChild(root, cookie); parent; parent = GetNextChild(root, cookie))\n\t{\n\/\/\t\twxString str = GetItemText(parent);\n\t\tfor (item = GetFirstChild(parent, cookie2); item; item = GetNextChild(parent, cookie2))\n\t\t{\n\t\t\tMyTreeItemData *data = (MyTreeItemData *)GetItemData(item);\n\/\/\t\t\twxString str2 = GetItemText(item);\n\t\t\tif (data)\n\t\t\t{\n\t\t\t\tSetItemText(item, MakeItemName(data->m_pLayer));\n\t\t\t\tif (data->m_pLayer == pFrame->GetActiveLayer())\n\t\t\t\t\tSelectItem(item);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/\/ avoid repetition\n#define TREE_EVENT_HANDLER(name)\t\t\t\\\nvoid MyTreeCtrl::name(wxTreeEvent& event)\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\\\n\tevent.Skip();\t\t\t\t\t\t\t\\\n}\n\nTREE_EVENT_HANDLER(OnBeginRDrag)\n\tTREE_EVENT_HANDLER(OnDeleteItem)\n\tTREE_EVENT_HANDLER(OnGetInfo)\n\tTREE_EVENT_HANDLER(OnSetInfo)\n\tTREE_EVENT_HANDLER(OnItemExpanded)\n\tTREE_EVENT_HANDLER(OnItemExpanding)\n\tTREE_EVENT_HANDLER(OnItemCollapsed)\n\tTREE_EVENT_HANDLER(OnSelChanging)\n\tTREE_EVENT_HANDLER(OnTreeKeyDown)\n\n#undef TREE_EVENT_HANDLER\n\n\tvoid MyTreeCtrl::OnSelChanged(wxTreeEvent& event)\n{\n\twxTreeItemId item = event.GetItem();\n\tMyTreeItemData *data = (MyTreeItemData *)GetItemData(item);\n\tvtLayerPtr lp = NULL;\n\tif (data)\n\t\tlp = data->m_pLayer;\n\n\tvtLayerPtr last = GetMainFrame()->GetActiveLayer();\n\tif (lp != last)\n\t\tGetMainFrame()->GetView()->SetActiveLayer(lp);\n\n\tLayerType last_ltype = last ? last->GetType() : LT_UNKNOWN;\n\tif (lp && lp->GetType() != last_ltype)\n\t\tGetMainFrame()->RefreshToolbar();\n}\n\nvoid MyTreeCtrl::OnBeginDrag(wxTreeEvent& event)\n{\n}\n\nvoid MyTreeCtrl::OnEndDrag(wxTreeEvent& event)\n{\n}\n\nvoid MyTreeCtrl::OnBeginLabelEdit(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnBeginLabelEdit\");\n\n\t\/\/ for testing, prevent this items label editing\n\twxTreeItemId itemId = event.GetItem();\n\tif ( IsTestItem(itemId) )\n\t{\n\t\twxMessageBox(\"You can't edit this item.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnEndLabelEdit(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnEndLabelEdit\");\n\n\t\/\/ don't allow anything except letters in the labels\n\tif ( !event.GetLabel().IsWord() )\n\t{\n\t\twxMessageBox(\"The label should contain only letters.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnItemCollapsing(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnItemCollapsing\");\n\n\t\/\/ for testing, prevent the user from collapsing the first child folder\n\twxTreeItemId itemId = event.GetItem();\n\tif ( IsTestItem(itemId) )\n\t{\n\t\twxMessageBox(\"You can't collapse this item.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnItemActivated(wxTreeEvent& event)\n{\n#if 0\n\t\/\/ show some info about this item\n\twxTreeItemId itemId = event.GetItem();\n\tMyTreeItemData *item = (MyTreeItemData *)GetItemData(itemId);\n\n\tif ( item != NULL )\n\t{\n\t\titem->ShowInfo(this);\n\t}\n\twxLogMessage(\"OnItemActivated\");\n#endif\n}\n\nvoid MyTreeCtrl::OnRMouseDClick(wxMouseEvent& event)\n{\n#if 0\n\twxTreeItemId id = HitTest(event.GetPosition());\n\tif ( !id )\n\t\twxLogMessage(\"No item under mouse\");\n\telse\n\t{\n\t\tMyTreeItemData *item = (MyTreeItemData *)GetItemData(id);\n\t\tif ( item )\n\t\t\twxLogMessage(\"Item '%s' under mouse\", item->GetDesc());\n\t}\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBEGIN_EVENT_TABLE(MyTreeCtrl, wxTreeCtrl)\nEVT_TREE_BEGIN_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginDrag)\nEVT_TREE_BEGIN_RDRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginRDrag)\nEVT_TREE_END_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnEndDrag)\nEVT_TREE_BEGIN_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnBeginLabelEdit)\nEVT_TREE_END_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnEndLabelEdit)\nEVT_TREE_DELETE_ITEM(LayerTree_Ctrl, MyTreeCtrl::OnDeleteItem)\nEVT_TREE_SET_INFO(LayerTree_Ctrl, MyTreeCtrl::OnSetInfo)\nEVT_TREE_ITEM_EXPANDED(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanded)\nEVT_TREE_ITEM_EXPANDING(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanding)\nEVT_TREE_ITEM_COLLAPSED(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsed)\nEVT_TREE_ITEM_COLLAPSING(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsing)\nEVT_TREE_SEL_CHANGED(LayerTree_Ctrl, MyTreeCtrl::OnSelChanged)\nEVT_TREE_SEL_CHANGING(LayerTree_Ctrl, MyTreeCtrl::OnSelChanging)\nEVT_TREE_KEY_DOWN(LayerTree_Ctrl, MyTreeCtrl::OnTreeKeyDown)\nEVT_TREE_ITEM_ACTIVATED(LayerTree_Ctrl, MyTreeCtrl::OnItemActivated)\nEVT_RIGHT_DCLICK(MyTreeCtrl::OnRMouseDClick)\nEND_EVENT_TABLE()\n<commit_msg>tweak<commit_after>\/\/\n\/\/ TreeView.cpp\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"App.h\"\n#include \"TreeView.h\"\n#include \"MenuEnum.h\"\t\/\/ for LayerTree_Ctrl\n#include \"Frame.h\"\n#include \"BuilderView.h\"\n\nDECLARE_APP(MyApp)\n\n\/\/ Under Windows, the icons are in the .rc file; on Unix, they are included\n\/\/ from .xpm files.\n#ifndef __WXMSW__\n#include \"building.xpm\"\n#include \"file1.xpm\"\n#include \"file2.xpm\"\n#include \"folder1.xpm\"\n#include \"folder2.xpm\"\n#include \"folder3.xpm\"\n\n#include \"grid.xpm\"\n#include \"image.xpm\"\n#include \"raw.xpm\"\n#include \"road.xpm\"\n#include \"veg1.xpm\"\n#include \"water.xpm\"\n#include \"util.xpm\"\n#include \"transit.xpm\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ MyTreeCtrl implementation\nIMPLEMENT_DYNAMIC_CLASS(MyTreeCtrl, wxTreeCtrl)\n\nMyTreeCtrl::MyTreeCtrl(wxWindow *parent, const wxWindowID id,\n\tconst wxPoint& pos, const wxSize& size,\n\tlong style)\n: wxTreeCtrl(parent, id, pos, size, style)\n{\n\tm_reverseSort = false;\n\tm_imageListNormal = NULL;\n\tm_bShowPaths = true;\n\n\tCreateImageList(16);\n\n\t\/\/ Add some items to the tree\n\tRefreshTreeItems(NULL);\n}\n\nvoid MyTreeCtrl::CreateImageList(int size)\n{\n\tdelete m_imageListNormal;\n\n\tif ( size == -1 )\n\t{\n\t\tm_imageListNormal = NULL;\n\t\treturn;\n\t}\n\n\t\/\/ Make an image list containing small icons\n\tm_imageListNormal = new wxImageList(size, size, TRUE);\n\n\t\/\/ should correspond to TreeCtrlIcon_xxx enum\n\twxIcon icons[14];\n\ticons[0] = wxICON(file1);\n\ticons[1] = wxICON(file2);\n\ticons[2] = wxICON(folder1);\n\ticons[3] = wxICON(folder2);\n\ticons[4] = wxICON(folder3);\n\ticons[5] = wxICON(building);\n\ticons[6] = wxICON(road);\n\ticons[7] = wxICON(grid);\n\ticons[8] = wxICON(image);\n\ticons[9] = wxICON(veg1);\n\ticons[10] = wxICON(water);\n\ticons[11] = wxICON(transit);\n\ticons[12] = wxICON(util);\n\ticons[13] = wxICON(raw);\n\n\tint sizeOrig = icons[0].GetWidth();\n\tfor ( size_t i = 0; i < WXSIZEOF(icons); i++ )\n\t{\n\t\tif ( size == sizeOrig )\n\t\t\tm_imageListNormal->Add(icons[i]);\n\t\telse\n\t\t\tm_imageListNormal->Add(wxImage(icons[i]).Rescale(size, size).\n\t\t\t\tConvertToBitmap());\n\t}\n\n\tSetImageList(m_imageListNormal);\n}\n\nMyTreeCtrl::~MyTreeCtrl()\n{\n\tdelete m_imageListNormal;\n}\n\nint MyTreeCtrl::OnCompareItems(const wxTreeItemId& item1,\n\tconst wxTreeItemId& item2)\n{\n\tif ( m_reverseSort )\n\t{\n\t\t\/\/ just exchange 1st and 2nd items\n\t\treturn wxTreeCtrl::OnCompareItems(item2, item1);\n\t}\n\telse\n\t{\n\t\treturn wxTreeCtrl::OnCompareItems(item1, item2);\n\t}\n}\n\nwxTreeItemId rootId;\n\nwxTreeItemId MyTreeCtrl::AddRootItem(int image, const char *text)\n{\n\twxTreeItemId id = AppendItem(rootId, text, image);\n\tSetItemBold(id);\n\treturn id;\n}\n\nwxString MyTreeCtrl::MakeItemName(vtLayerPtr lp)\n{\n\twxString str;\n\tif (lp->GetModified())\n\t\tstr += \"(*) \";\n\twxString fullpath = lp->GetFilename();\n\tif (!m_bShowPaths)\n\t{\n\t\tif (fullpath.Find('\/') != -1)\n\t\t\tfullpath = fullpath.AfterLast('\/');\n\t\tif (fullpath.Find('\\\\') != -1)\n\t\t\tfullpath = fullpath.AfterLast('\\\\');\n\t\tif (fullpath.Find(':') != -1)\n\t\t\tfullpath = fullpath.AfterLast(':');\n\t}\n\tstr += fullpath;\n\treturn str;\n}\n\nvoid MyTreeCtrl::RefreshTreeItems(MainFrame *pFrame)\n{\n\tDeleteAllItems();\n\n\trootId = AddRoot(\"Layers\");\n\tSetItemBold(rootId);\n\n\tint\timage, imageSel;\n\n\twxTreeItemId elevId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Grid, \"Elevation\");\n#ifndef ELEVATION_ONLY\n\twxTreeItemId imageId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Image, \"Images\");\n\twxTreeItemId buildId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Building, \"Structures\");\n\twxTreeItemId roadId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Road, \"Roads\");\n\twxTreeItemId vegId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Veg1, \"Vegetation\");\n\twxTreeItemId waterId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Water, \"Water\");\n#if SUPPORT_TRANSIT\n\twxTreeItemId transId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Transit, \"Transit\");\n#endif\n\twxTreeItemId utilityId = AddRootItem(MyTreeCtrl::TreeCtrlIcon_Utility, \"Utilities\");\n#endif\n\twxTreeItemId rawId =\tAddRootItem(MyTreeCtrl::TreeCtrlIcon_Raw, \"Raw\");\n\n\timage = TreeCtrlIcon_File;\n\timageSel = TreeCtrlIcon_FileSelected;\n\tvtLayerPtr lp;\n\tint iLayers = 0;\n\tif (pFrame) iLayers = pFrame->m_Layers.GetSize();\n\tfor (int i = 0; i < iLayers; i++)\n\t{\n\t\tlp = pFrame->m_Layers.GetAt(i);\n\n\t\twxString str = MakeItemName(lp);\n\n\t\twxTreeItemId hItem = -1;\n\t\tswitch (lp->GetType())\n\t\t{\n\t\t\tcase LT_ELEVATION:\n\t\t\t\thItem = AppendItem(elevId, str, image, imageSel);\n\t\t\t\tbreak;\n#ifndef ELEVATION_ONLY\n\t\t\tcase LT_IMAGE:\n\t\t\t\thItem = AppendItem(imageId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_ROAD:\n\t\t\t\thItem = AppendItem(roadId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_STRUCTURE:\n\t\t\t\thItem = AppendItem(buildId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_VEG:\n\t\t\t\thItem = AppendItem(vegId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t\tcase LT_WATER:\n\t\t\t\thItem = AppendItem(waterId, str, image, imageSel);\n\t\t\t\tbreak;\n#if SUPPORT_TRANSIT\n\t\t\tcase LT_TRANSIT:\n\t\t\t\thItem = AppendItem(transId, str, image, imageSel);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase LT_UTILITY:\n\t\t\t\thItem = AppendItem(utilityId, str, image, imageSel);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase LT_RAW:\n\t\t\t\thItem = AppendItem(rawId, str, image, imageSel);\n\t\t\t\tbreak;\n\t\t}\n\t\tif (hItem != -1)\n\t\t{\n\t\t\tSetItemData(hItem, new MyTreeItemData(lp));\n\n\t\t\tif (lp == pFrame->GetActiveLayer())\n\t\t\t\tSelectItem(hItem);\n\t\t}\n\t}\n\n\tExpand(rootId);\n\tExpand(elevId);\n#ifndef ELEVATION_ONLY\n\tExpand(imageId);\n\tExpand(roadId);\n\tExpand(buildId);\n\tExpand(vegId);\n\tExpand(waterId);\n#if SUPPORT_TRANSIT\n\tExpand(transId);\n#endif\n\tExpand(utilityId);\n#endif\n\tExpand(rawId);\n}\n\nvoid MyTreeCtrl::RefreshTreeStatus(MainFrame *pFrame)\n{\n\twxTreeItemId root = GetRootItem();\n\twxTreeItemId parent, item;\n\tlong cookie = 0, cookie2 = 1;\n\n\tfor (parent = GetFirstChild(root, cookie); parent; parent = GetNextChild(root, cookie))\n\t{\n\t\tfor (item = GetFirstChild(parent, cookie2); item; item = GetNextChild(parent, cookie2))\n\t\t{\n\t\t\tMyTreeItemData *data = (MyTreeItemData *)GetItemData(item);\n\t\t\tif (data)\n\t\t\t{\n\t\t\t\tSetItemText(item, MakeItemName(data->m_pLayer));\n\t\t\t\tif (data->m_pLayer == pFrame->GetActiveLayer())\n\t\t\t\t\tSelectItem(item);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/\/ avoid repetition\n#define TREE_EVENT_HANDLER(name)\t\t\t\\\nvoid MyTreeCtrl::name(wxTreeEvent& event)\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\\\n\tevent.Skip();\t\t\t\t\t\t\t\\\n}\n\nTREE_EVENT_HANDLER(OnBeginRDrag)\n\tTREE_EVENT_HANDLER(OnDeleteItem)\n\tTREE_EVENT_HANDLER(OnGetInfo)\n\tTREE_EVENT_HANDLER(OnSetInfo)\n\tTREE_EVENT_HANDLER(OnItemExpanded)\n\tTREE_EVENT_HANDLER(OnItemExpanding)\n\tTREE_EVENT_HANDLER(OnItemCollapsed)\n\tTREE_EVENT_HANDLER(OnSelChanging)\n\tTREE_EVENT_HANDLER(OnTreeKeyDown)\n\n#undef TREE_EVENT_HANDLER\n\nvoid MyTreeCtrl::OnSelChanged(wxTreeEvent& event)\n{\n\twxTreeItemId item = event.GetItem();\n\tMyTreeItemData *data = (MyTreeItemData *)GetItemData(item);\n\tvtLayerPtr lp = NULL;\n\tif (data)\n\t\tlp = data->m_pLayer;\n\n\tvtLayerPtr last = GetMainFrame()->GetActiveLayer();\n\tif (lp != last)\n\t\tGetMainFrame()->GetView()->SetActiveLayer(lp);\n\n\tLayerType last_ltype = last ? last->GetType() : LT_UNKNOWN;\n\tif (lp && lp->GetType() != last_ltype)\n\t\tGetMainFrame()->RefreshToolbar();\n}\n\nvoid MyTreeCtrl::OnBeginDrag(wxTreeEvent& event)\n{\n}\n\nvoid MyTreeCtrl::OnEndDrag(wxTreeEvent& event)\n{\n}\n\nvoid MyTreeCtrl::OnBeginLabelEdit(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnBeginLabelEdit\");\n\n\t\/\/ for testing, prevent this items label editing\n\twxTreeItemId itemId = event.GetItem();\n\tif ( IsTestItem(itemId) )\n\t{\n\t\twxMessageBox(\"You can't edit this item.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnEndLabelEdit(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnEndLabelEdit\");\n\n\t\/\/ don't allow anything except letters in the labels\n\tif ( !event.GetLabel().IsWord() )\n\t{\n\t\twxMessageBox(\"The label should contain only letters.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnItemCollapsing(wxTreeEvent& event)\n{\n#if 0\n\twxLogMessage(\"OnItemCollapsing\");\n\n\t\/\/ for testing, prevent the user from collapsing the first child folder\n\twxTreeItemId itemId = event.GetItem();\n\tif ( IsTestItem(itemId) )\n\t{\n\t\twxMessageBox(\"You can't collapse this item.\");\n\n\t\tevent.Veto();\n\t}\n#endif\n}\n\nvoid MyTreeCtrl::OnItemActivated(wxTreeEvent& event)\n{\n#if 0\n\t\/\/ show some info about this item\n\twxTreeItemId itemId = event.GetItem();\n\tMyTreeItemData *item = (MyTreeItemData *)GetItemData(itemId);\n\n\tif ( item != NULL )\n\t{\n\t\titem->ShowInfo(this);\n\t}\n\twxLogMessage(\"OnItemActivated\");\n#endif\n}\n\nvoid MyTreeCtrl::OnRMouseDClick(wxMouseEvent& event)\n{\n#if 0\n\twxTreeItemId id = HitTest(event.GetPosition());\n\tif ( !id )\n\t\twxLogMessage(\"No item under mouse\");\n\telse\n\t{\n\t\tMyTreeItemData *item = (MyTreeItemData *)GetItemData(id);\n\t\tif ( item )\n\t\t\twxLogMessage(\"Item '%s' under mouse\", item->GetDesc());\n\t}\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBEGIN_EVENT_TABLE(MyTreeCtrl, wxTreeCtrl)\nEVT_TREE_BEGIN_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginDrag)\nEVT_TREE_BEGIN_RDRAG(LayerTree_Ctrl, MyTreeCtrl::OnBeginRDrag)\nEVT_TREE_END_DRAG(LayerTree_Ctrl, MyTreeCtrl::OnEndDrag)\nEVT_TREE_BEGIN_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnBeginLabelEdit)\nEVT_TREE_END_LABEL_EDIT(LayerTree_Ctrl, MyTreeCtrl::OnEndLabelEdit)\nEVT_TREE_DELETE_ITEM(LayerTree_Ctrl, MyTreeCtrl::OnDeleteItem)\nEVT_TREE_SET_INFO(LayerTree_Ctrl, MyTreeCtrl::OnSetInfo)\nEVT_TREE_ITEM_EXPANDED(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanded)\nEVT_TREE_ITEM_EXPANDING(LayerTree_Ctrl, MyTreeCtrl::OnItemExpanding)\nEVT_TREE_ITEM_COLLAPSED(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsed)\nEVT_TREE_ITEM_COLLAPSING(LayerTree_Ctrl, MyTreeCtrl::OnItemCollapsing)\nEVT_TREE_SEL_CHANGED(LayerTree_Ctrl, MyTreeCtrl::OnSelChanged)\nEVT_TREE_SEL_CHANGING(LayerTree_Ctrl, MyTreeCtrl::OnSelChanging)\nEVT_TREE_KEY_DOWN(LayerTree_Ctrl, MyTreeCtrl::OnTreeKeyDown)\nEVT_TREE_ITEM_ACTIVATED(LayerTree_Ctrl, MyTreeCtrl::OnItemActivated)\nEVT_RIGHT_DCLICK(MyTreeCtrl::OnRMouseDClick)\nEND_EVENT_TABLE()\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2010 University of Szeged.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"TestController.h\"\n\n#include <QApplication>\n#include <QObject>\n#include <QTimer>\n\nclass Launcher : public QObject {\n Q_OBJECT\n\npublic:\n Launcher(int argc, char** argv)\n : m_argc(argc)\n , m_argv(argv)\n {\n }\n\n ~Launcher()\n {\n delete m_controller;\n }\n\npublic slots:\n void launch()\n {\n m_controller = new WTR::TestController(m_argc, const_cast<const char**>(m_argv));\n QApplication::exit();\n }\n\nprivate:\n WTR::TestController* m_controller;\n int m_argc;\n char** m_argv;\n};\n\nvoid messageHandler(QtMsgType type, const char* message)\n{\n if (type == QtCriticalMsg) {\n fprintf(stderr, \"%s\\n\", message);\n return;\n }\n\n \/\/ Do nothing\n}\n\nint main(int argc, char** argv)\n{\n \/\/ Suppress debug output from Qt if not started with --verbose\n bool suppressQtDebugOutput = true;\n for (int i = 1; i < argc; ++i) {\n if (!qstrcmp(argv[i], \"--verbose\")) {\n suppressQtDebugOutput = false;\n break;\n }\n }\n\n \/\/ Has to be done before QApplication is constructed in case\n \/\/ QApplication itself produces debug output.\n if (suppressQtDebugOutput) {\n qInstallMsgHandler(messageHandler);\n if (qgetenv(\"QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT\").isEmpty())\n qputenv(\"QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT\", \"1\");\n }\n\n QApplication app(argc, argv);\n Launcher launcher(argc, argv);\n QTimer::singleShot(0, &launcher, SLOT(launch()));\n return app.exec();;\n}\n\n#include \"main.moc\"\n<commit_msg>[Qt] Prospective build fix for WebKit2 on Linux<commit_after>\/*\n * Copyright (C) 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2010 University of Szeged.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"TestController.h\"\n\n#include <stdio.h>\n\n#include <QApplication>\n#include <QObject>\n#include <QTimer>\n\nclass Launcher : public QObject {\n Q_OBJECT\n\npublic:\n Launcher(int argc, char** argv)\n : m_argc(argc)\n , m_argv(argv)\n {\n }\n\n ~Launcher()\n {\n delete m_controller;\n }\n\npublic slots:\n void launch()\n {\n m_controller = new WTR::TestController(m_argc, const_cast<const char**>(m_argv));\n QApplication::exit();\n }\n\nprivate:\n WTR::TestController* m_controller;\n int m_argc;\n char** m_argv;\n};\n\nvoid messageHandler(QtMsgType type, const char* message)\n{\n if (type == QtCriticalMsg) {\n fprintf(stderr, \"%s\\n\", message);\n return;\n }\n\n \/\/ Do nothing\n}\n\nint main(int argc, char** argv)\n{\n \/\/ Suppress debug output from Qt if not started with --verbose\n bool suppressQtDebugOutput = true;\n for (int i = 1; i < argc; ++i) {\n if (!qstrcmp(argv[i], \"--verbose\")) {\n suppressQtDebugOutput = false;\n break;\n }\n }\n\n \/\/ Has to be done before QApplication is constructed in case\n \/\/ QApplication itself produces debug output.\n if (suppressQtDebugOutput) {\n qInstallMsgHandler(messageHandler);\n if (qgetenv(\"QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT\").isEmpty())\n qputenv(\"QT_WEBKIT_SUPPRESS_WEB_PROCESS_OUTPUT\", \"1\");\n }\n\n QApplication app(argc, argv);\n Launcher launcher(argc, argv);\n QTimer::singleShot(0, &launcher, SLOT(launch()));\n return app.exec();;\n}\n\n#include \"main.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of the Util library.\n\tCopyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>\n\tCopyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>\n\tCopyright (C) 2007-2012 Ralf Petring <ralf@petring.net>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)\n\n#include \"WindowEGL.h\"\n#include \"WindowX11Data.h\"\n#include \"..\/StringUtils.h\"\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n#include <EGL\/egl.h>\n#include <memory>\n#include <stdexcept>\n\nnamespace Util {\nnamespace UI {\n\nextern Key keySymToKey(KeySym sym);\n\nstruct WindowEGL::WindowEGLData {\n\t\tEGLDisplay display;\n\t\tEGLContext context;\n\t\tEGLSurface surface;\n\n\t\tWindowEGLData() :\n\t\t\tdisplay(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {\n\t\t}\n\n\t\t~WindowEGLData() {\n\t\t\tif (display != EGL_NO_DISPLAY) {\n\t\t\t\teglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);\n\t\t\t\tif (surface != EGL_NO_SURFACE) {\n\t\t\t\t\teglDestroySurface(display, surface);\n\t\t\t\t}\n\t\t\t\tif (context != EGL_NO_CONTEXT) {\n\t\t\t\t\teglDestroyContext(display, context);\n\t\t\t\t}\n\t\t\t\teglTerminate(display);\n\t\t\t}\n\t\t}\n};\n\nstatic std::string eglErrorToString(const EGLint errorCode) {\n\tconst std::string strErrorCode = StringUtils::toString(errorCode);\n\tswitch(errorCode) {\n\t\tcase EGL_SUCCESS:\n\t\t\treturn \"EGL_SUCCESS\/\" + strErrorCode + \": The last function succeeded without error.\";\n\t\tcase EGL_NOT_INITIALIZED:\n\t\t\treturn \"EGL_NOT_INITIALIZED\/\" + strErrorCode + \": EGL is not initialized, or could not be initialized, for the specified EGL display connection.\";\n\t\tcase EGL_BAD_ACCESS:\n\t\t\treturn \"EGL_BAD_ACCESS\/\" + strErrorCode + \": EGL cannot access a requested resource (for example a context is bound in another thread).\";\n\t\tcase EGL_BAD_ALLOC:\n\t\t\treturn \"EGL_BAD_ALLOC\/\" + strErrorCode + \": EGL failed to allocate resources for the requested operation.\";\n\t\tcase EGL_BAD_ATTRIBUTE:\n\t\t\treturn \"EGL_BAD_ATTRIBUTE\/\" + strErrorCode + \": An unrecognized attribute or attribute value was passed in the attribute list.\";\n\t\tcase EGL_BAD_CONTEXT:\n\t\t\treturn \"EGL_BAD_CONTEXT\/\" + strErrorCode + \": An EGLContext argument does not name a valid EGL rendering context.\";\n\t\tcase EGL_BAD_CONFIG:\n\t\t\treturn \"EGL_BAD_CONFIG\/\" + strErrorCode + \": An EGLConfig argument does not name a valid EGL frame buffer configuration.\";\n\t\tcase EGL_BAD_CURRENT_SURFACE:\n\t\t\treturn \"EGL_BAD_CURRENT_SURFACE\/\" + strErrorCode + \": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.\";\n\t\tcase EGL_BAD_DISPLAY:\n\t\t\treturn \"EGL_BAD_DISPLAY\/\" + strErrorCode + \": An EGLDisplay argument does not name a valid EGL display connection.\";\n\t\tcase EGL_BAD_SURFACE:\n\t\t\treturn \"EGL_BAD_SURFACE\/\" + strErrorCode + \": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.\";\n\t\tcase EGL_BAD_MATCH:\n\t\t\treturn \"EGL_BAD_MATCH\/\" + strErrorCode + \": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).\";\n\t\tcase EGL_BAD_PARAMETER:\n\t\t\treturn \"EGL_BAD_PARAMETER\/\" + strErrorCode + \": One or more argument values are invalid.\";\n\t\tcase EGL_BAD_NATIVE_PIXMAP:\n\t\t\treturn \"EGL_BAD_NATIVE_PIXMAP\/\" + strErrorCode + \": A NativePixmapType argument does not refer to a valid native pixmap.\";\n\t\tcase EGL_BAD_NATIVE_WINDOW:\n\t\t\treturn \"EGL_BAD_NATIVE_WINDOW\/\" + strErrorCode + \": A NativeWindowType argument does not refer to a valid native window.\";\n\t\tcase EGL_CONTEXT_LOST:\n\t\t\treturn \"EGL_CONTEXT_LOST\/\" + strErrorCode + \": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nWindowEGL::WindowEGL(const Window::Properties & properties) :\n\t\tWindowX11(properties), eglData(new WindowEGLData) {\n\n\teglData->display = eglGetDisplay(x11Data->display);\n\tif (eglData->display == EGL_NO_DISPLAY) {\n\t\tthrow std::runtime_error(\"Failed to open display.\");\n\t}\n\n\tEGLint versionMajor;\n\tEGLint versionMinor;\n\tif (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {\n\t\tthrow std::runtime_error(\"Failed to initialize display.\");\n\t}\n\n\t\/\/ EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION\n\tif ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {\n\t\tthrow std::runtime_error(\"EGL version less than 1.3 detected.\");\n\t}\n\n\tif (EGL_TRUE != eglBindAPI(EGL_OPENGL_ES_API)) {\n\t\tthrow std::runtime_error(\"Cannot bind API.\");\n\t}\n\n\t\/\/ Define attributes of desired framebuffer configurations\n\tEGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,\n\t\t\t\t\t\t\tEGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };\n\t\/\/ Request a single framebuffer configuration\n\tEGLConfig fbConfig;\n\tEGLint fbCount;\n\tif (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {\n\t\tthrow std::runtime_error(\"Failed to retrieve a matching framebuffer configuration.\");\n\t}\n\n\tif (fbCount == 0) {\n\t\t\/\/ FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.\n\t\tEGLConfig fbConfigs[200];\n\t\teglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);\n\t\tfor (EGLint i = 0; i < fbCount; ++i) {\n\t\t\tEGLint value;\n\t\t\t\/\/ We want to render into a window\n\t\t\teglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);\n\t\t\tif (!(value & EGL_WINDOW_BIT)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\/\/ We want a configuration with a depth buffer\n\t\t\teglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);\n\t\t\tif (value == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfbConfig = fbConfigs[i];\n\t\t}\n\t}\n\n\tif (fbCount == 0) {\n\t\tthrow std::runtime_error(\"No matching framebuffer configurations found.\");\n\t}\n\n\tEGLint visualID;\n\teglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);\n\n\tconst EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };\n\teglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);\n\tif (eglData->context == EGL_NO_CONTEXT) {\n\t\tthrow std::runtime_error(\"Failed to create OpenGL ES 2.x context. \" + \n\t\t\t\t\t\t\t\t eglErrorToString(eglGetError()));\n\t}\n\n\t\/\/ Create X11 window\n\tXVisualInfo templateInfo;\n\ttemplateInfo.visualid = visualID;\n\tint visualCount;\n\tXVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);\n\tif (visualsInfo == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to find a matching visual.\");\n\t} else if (visualCount != 1) {\n\t\tXFree(visualsInfo);\n\t\tthrow std::runtime_error(\"More than one visual found.\");\n\t}\n\n\tx11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);\n\tx11Data->freeColorMap = true;\n\n\tXSetWindowAttributes windowAttribs;\n\twindowAttribs.colormap = x11Data->colorMap;\n\twindowAttribs.background_pixmap = None;\n\twindowAttribs.border_pixel = 0;\n\twindowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;\n\n\tx11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), \n\t\t\t\t\t\t\t\t 0, 0, properties.clientAreaWidth, properties.clientAreaHeight, \n\t\t\t\t\t\t\t\t 0, visualsInfo[0].depth,\n\t\t\t\t\t\t\t\t InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);\n\n\tXFree(visualsInfo);\n\n\tif (!x11Data->window) {\n\t\tthrow std::runtime_error(\"Failed to create window.\");\n\t} else {\n\t\tx11Data->freeWindow = true;\n\t}\n\n\tif (properties.borderless) {\n\t\tx11Data->removeWindowBorder();\n\t}\n\tif (!properties.resizable) {\n\t\tx11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth), \n\t\t\t\t\t\t\t static_cast<int>(properties.clientAreaHeight));\n\t}\n\n\tx11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);\n\tif (x11Data->inputMethod == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to create input method.\");\n\t}\n\n\tx11Data->inputContext = XCreateIC(x11Data->inputMethod,\n\t\t\t\t\t\t\t\t XNInputStyle, XIMPreeditNone | XIMStatusNone,\n\t\t\t\t\t\t\t\t XNClientWindow, x11Data->window,\n\t\t\t\t\t\t\t\t XNFocusWindow, x11Data->window,\n\t\t\t\t\t\t\t\t nullptr);\n\tif (x11Data->inputContext == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to create input context.\");\n\t}\n\n\tXStoreName(x11Data->display, x11Data->window, properties.title.c_str());\n\n\tXMapWindow(x11Data->display, x11Data->window);\n\tif (properties.positioned) {\n\t\tXMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);\n\t}\n\n\teglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);\n\tif (eglData->surface == EGL_NO_SURFACE) {\n\t\tthrow std::runtime_error(\"Failed to create window surface.\");\n\t}\n\n\teglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);\n}\n\nWindowEGL::~WindowEGL() = default;\n\nvoid WindowEGL::swapBuffers() {\n\teglSwapBuffers(eglData->display, eglData->surface);\n}\n\n}\n}\n\n#endif \/* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) *\/\n<commit_msg>Select rendering API based on parameter<commit_after>\/*\n\tThis file is part of the Util library.\n\tCopyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org>\n\tCopyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de>\n\tCopyright (C) 2007-2012 Ralf Petring <ralf@petring.net>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#if defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL)\n\n#include \"WindowEGL.h\"\n#include \"WindowX11Data.h\"\n#include \"..\/StringUtils.h\"\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n#include <EGL\/egl.h>\n#include <memory>\n#include <stdexcept>\n\nnamespace Util {\nnamespace UI {\n\nextern Key keySymToKey(KeySym sym);\n\nstruct WindowEGL::WindowEGLData {\n\t\tEGLDisplay display;\n\t\tEGLContext context;\n\t\tEGLSurface surface;\n\n\t\tWindowEGLData() :\n\t\t\tdisplay(EGL_NO_DISPLAY), context(EGL_NO_CONTEXT), surface(EGL_NO_SURFACE) {\n\t\t}\n\n\t\t~WindowEGLData() {\n\t\t\tif (display != EGL_NO_DISPLAY) {\n\t\t\t\teglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);\n\t\t\t\tif (surface != EGL_NO_SURFACE) {\n\t\t\t\t\teglDestroySurface(display, surface);\n\t\t\t\t}\n\t\t\t\tif (context != EGL_NO_CONTEXT) {\n\t\t\t\t\teglDestroyContext(display, context);\n\t\t\t\t}\n\t\t\t\teglTerminate(display);\n\t\t\t}\n\t\t}\n};\n\nstatic std::string eglErrorToString(const EGLint errorCode) {\n\tconst std::string strErrorCode = StringUtils::toString(errorCode);\n\tswitch(errorCode) {\n\t\tcase EGL_SUCCESS:\n\t\t\treturn \"EGL_SUCCESS\/\" + strErrorCode + \": The last function succeeded without error.\";\n\t\tcase EGL_NOT_INITIALIZED:\n\t\t\treturn \"EGL_NOT_INITIALIZED\/\" + strErrorCode + \": EGL is not initialized, or could not be initialized, for the specified EGL display connection.\";\n\t\tcase EGL_BAD_ACCESS:\n\t\t\treturn \"EGL_BAD_ACCESS\/\" + strErrorCode + \": EGL cannot access a requested resource (for example a context is bound in another thread).\";\n\t\tcase EGL_BAD_ALLOC:\n\t\t\treturn \"EGL_BAD_ALLOC\/\" + strErrorCode + \": EGL failed to allocate resources for the requested operation.\";\n\t\tcase EGL_BAD_ATTRIBUTE:\n\t\t\treturn \"EGL_BAD_ATTRIBUTE\/\" + strErrorCode + \": An unrecognized attribute or attribute value was passed in the attribute list.\";\n\t\tcase EGL_BAD_CONTEXT:\n\t\t\treturn \"EGL_BAD_CONTEXT\/\" + strErrorCode + \": An EGLContext argument does not name a valid EGL rendering context.\";\n\t\tcase EGL_BAD_CONFIG:\n\t\t\treturn \"EGL_BAD_CONFIG\/\" + strErrorCode + \": An EGLConfig argument does not name a valid EGL frame buffer configuration.\";\n\t\tcase EGL_BAD_CURRENT_SURFACE:\n\t\t\treturn \"EGL_BAD_CURRENT_SURFACE\/\" + strErrorCode + \": The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.\";\n\t\tcase EGL_BAD_DISPLAY:\n\t\t\treturn \"EGL_BAD_DISPLAY\/\" + strErrorCode + \": An EGLDisplay argument does not name a valid EGL display connection.\";\n\t\tcase EGL_BAD_SURFACE:\n\t\t\treturn \"EGL_BAD_SURFACE\/\" + strErrorCode + \": An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.\";\n\t\tcase EGL_BAD_MATCH:\n\t\t\treturn \"EGL_BAD_MATCH\/\" + strErrorCode + \": Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).\";\n\t\tcase EGL_BAD_PARAMETER:\n\t\t\treturn \"EGL_BAD_PARAMETER\/\" + strErrorCode + \": One or more argument values are invalid.\";\n\t\tcase EGL_BAD_NATIVE_PIXMAP:\n\t\t\treturn \"EGL_BAD_NATIVE_PIXMAP\/\" + strErrorCode + \": A NativePixmapType argument does not refer to a valid native pixmap.\";\n\t\tcase EGL_BAD_NATIVE_WINDOW:\n\t\t\treturn \"EGL_BAD_NATIVE_WINDOW\/\" + strErrorCode + \": A NativeWindowType argument does not refer to a valid native window.\";\n\t\tcase EGL_CONTEXT_LOST:\n\t\t\treturn \"EGL_CONTEXT_LOST\/\" + strErrorCode + \": A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nWindowEGL::WindowEGL(const Window::Properties & properties) :\n\t\tWindowX11(properties), eglData(new WindowEGLData) {\n\n\teglData->display = eglGetDisplay(x11Data->display);\n\tif (eglData->display == EGL_NO_DISPLAY) {\n\t\tthrow std::runtime_error(\"Failed to open display.\");\n\t}\n\n\tEGLint versionMajor;\n\tEGLint versionMinor;\n\tif (eglInitialize(eglData->display, &versionMajor, &versionMinor) == EGL_FALSE) {\n\t\tthrow std::runtime_error(\"Failed to initialize display.\");\n\t}\n\n\t\/\/ EGL version 1.3 is needed for EGL_CONTEXT_CLIENT_VERSION\n\tif ((versionMajor < 1) || ((versionMajor == 1) && (versionMinor < 3))) {\n\t\tthrow std::runtime_error(\"EGL version less than 1.3 detected.\");\n\t}\n\n\tEGLenum api;\n\tEGLint glesVersion = 0;\n\tswitch(properties.renderingAPI) {\n\t\tcase Properties::RenderingAPI::GL_ES_1:\n\t\t\tapi = EGL_OPENGL_ES_API;\n\t\t\tglesVersion = 1;\n\t\t\tbreak;\n\t\tcase Properties::RenderingAPI::GL_ES_2:\n\t\t\tapi = EGL_OPENGL_ES_API;\n\t\t\tglesVersion = 2;\n\t\t\tbreak;\n\t\tcase Properties::RenderingAPI::GL_ES_3:\n\t\t\tapi = EGL_OPENGL_ES_API;\n\t\t\tglesVersion = 3;\n\t\t\tbreak;\n\t\tcase Properties::RenderingAPI::GL:\n\t\t\tapi = EGL_OPENGL_API;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"Unsupported rendering API.\");\n\t}\n\tif (EGL_TRUE != eglBindAPI(api)) {\n\t\tthrow std::runtime_error(\"Cannot bind API.\");\n\t}\n\n\t\/\/ Define attributes of desired framebuffer configurations\n\tEGLint fbAttribs[] = { EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_BUFFER_SIZE, 24, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8,\n\t\t\t\t\t\t\tEGL_NATIVE_RENDERABLE, EGL_TRUE, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };\n\t\/\/ Request a single framebuffer configuration\n\tEGLConfig fbConfig;\n\tEGLint fbCount;\n\tif (eglChooseConfig(eglData->display, fbAttribs, &fbConfig, 1, &fbCount) == EGL_FALSE) {\n\t\tthrow std::runtime_error(\"Failed to retrieve a matching framebuffer configuration.\");\n\t}\n\n\tif (fbCount == 0) {\n\t\t\/\/ FIXME: Workaround: Use eglGetConfigs instead of eglChooseConfig, because sometimes eglChooseConfig does not find matching configurations.\n\t\tEGLConfig fbConfigs[200];\n\t\teglGetConfigs(eglData->display, fbConfigs, 200, &fbCount);\n\t\tfor (EGLint i = 0; i < fbCount; ++i) {\n\t\t\tEGLint value;\n\t\t\t\/\/ We want to render into a window\n\t\t\teglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_SURFACE_TYPE, &value);\n\t\t\tif (!(value & EGL_WINDOW_BIT)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\/\/ We want a configuration with a depth buffer\n\t\t\teglGetConfigAttrib(eglData->display, fbConfigs[i], EGL_DEPTH_SIZE, &value);\n\t\t\tif (value == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfbConfig = fbConfigs[i];\n\t\t}\n\t}\n\n\tif (fbCount == 0) {\n\t\tthrow std::runtime_error(\"No matching framebuffer configurations found.\");\n\t}\n\n\tEGLint visualID;\n\teglGetConfigAttrib(eglData->display, fbConfig, EGL_NATIVE_VISUAL_ID, &visualID);\n\n\tEGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, glesVersion, EGL_NONE };\n\tif (0 == glesVersion) {\n\t\tcontextAttribs[0] = EGL_NONE;\n\t\tcontextAttribs[1] = EGL_NONE;\n\t}\n\teglData->context = eglCreateContext(eglData->display, fbConfig, EGL_NO_CONTEXT, contextAttribs);\n\tif (eglData->context == EGL_NO_CONTEXT) {\n\t\tthrow std::runtime_error(\"Failed to create context: \" +\n\t\t\t\t\t\t\t\t eglErrorToString(eglGetError()));\n\t}\n\n\t\/\/ Create X11 window\n\tXVisualInfo templateInfo;\n\ttemplateInfo.visualid = visualID;\n\tint visualCount;\n\tXVisualInfo * visualsInfo = XGetVisualInfo(x11Data->display, VisualIDMask, &templateInfo, &visualCount);\n\tif (visualsInfo == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to find a matching visual.\");\n\t} else if (visualCount != 1) {\n\t\tXFree(visualsInfo);\n\t\tthrow std::runtime_error(\"More than one visual found.\");\n\t}\n\n\tx11Data->colorMap = XCreateColormap(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), visualsInfo[0].visual, AllocNone);\n\tx11Data->freeColorMap = true;\n\n\tXSetWindowAttributes windowAttribs;\n\twindowAttribs.colormap = x11Data->colorMap;\n\twindowAttribs.background_pixmap = None;\n\twindowAttribs.border_pixel = 0;\n\twindowAttribs.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;\n\n\tx11Data->window = XCreateWindow(x11Data->display, RootWindow(x11Data->display, visualsInfo[0].screen), \n\t\t\t\t\t\t\t\t 0, 0, properties.clientAreaWidth, properties.clientAreaHeight, \n\t\t\t\t\t\t\t\t 0, visualsInfo[0].depth,\n\t\t\t\t\t\t\t\t InputOutput, visualsInfo[0].visual, CWBorderPixel | CWColormap | CWEventMask, &windowAttribs);\n\n\tXFree(visualsInfo);\n\n\tif (!x11Data->window) {\n\t\tthrow std::runtime_error(\"Failed to create window.\");\n\t} else {\n\t\tx11Data->freeWindow = true;\n\t}\n\n\tif (properties.borderless) {\n\t\tx11Data->removeWindowBorder();\n\t}\n\tif (!properties.resizable) {\n\t\tx11Data->fixWindowSize(static_cast<int>(properties.clientAreaWidth), \n\t\t\t\t\t\t\t static_cast<int>(properties.clientAreaHeight));\n\t}\n\n\tx11Data->inputMethod = XOpenIM(x11Data->display, nullptr, nullptr, nullptr);\n\tif (x11Data->inputMethod == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to create input method.\");\n\t}\n\n\tx11Data->inputContext = XCreateIC(x11Data->inputMethod,\n\t\t\t\t\t\t\t\t XNInputStyle, XIMPreeditNone | XIMStatusNone,\n\t\t\t\t\t\t\t\t XNClientWindow, x11Data->window,\n\t\t\t\t\t\t\t\t XNFocusWindow, x11Data->window,\n\t\t\t\t\t\t\t\t nullptr);\n\tif (x11Data->inputContext == nullptr) {\n\t\tthrow std::runtime_error(\"Failed to create input context.\");\n\t}\n\n\tXStoreName(x11Data->display, x11Data->window, properties.title.c_str());\n\n\tXMapWindow(x11Data->display, x11Data->window);\n\tif (properties.positioned) {\n\t\tXMoveWindow(x11Data->display, x11Data->window, properties.posX, properties.posY);\n\t}\n\n\teglData->surface = eglCreateWindowSurface(eglData->display, fbConfig, x11Data->window, nullptr);\n\tif (eglData->surface == EGL_NO_SURFACE) {\n\t\tthrow std::runtime_error(\"Failed to create window surface.\");\n\t}\n\n\teglMakeCurrent(eglData->display, eglData->surface, eglData->surface, eglData->context);\n}\n\nWindowEGL::~WindowEGL() = default;\n\nvoid WindowEGL::swapBuffers() {\n\teglSwapBuffers(eglData->display, eglData->surface);\n}\n\n}\n}\n\n#endif \/* defined(UTIL_HAVE_LIB_X11) and defined(UTIL_HAVE_LIB_EGL) *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"VBase.h\"\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <ctype.h>\n#include <cstdio>\n#include <cstring>\n\n#if defined(_WIN32)\n#include <windows.h>\n#endif\n\n#if defined(__linux__)\n#include <unistd.h>\n#include <term.h>\n#endif\n\n#ifdef _DEBUG\nint VBase::DebugObjectCount = 0;\n#endif\n\nvoid VBase::VLog(const char* format, ...)\n{\n\tchar buf[4096], *p = buf;\n\tva_list args;\n\tint n;\n\n\tva_start(args, format);\n\tn = vsnprintf(p, sizeof buf - 3, format, args); \/\/ buf-3 is room for CR\/LF\/NUL\n\n\tint len = strlen(buf);\n\tchar* con = new char[len + 2];\n\n\tstrcpy(con, buf);\n\tcon[len] = '\\n';\n\tcon[len + 1] = '\\0';\n\n\tprintf(con, args);\n\tva_end(args);\n\n\tp += (n < 0) ? sizeof buf - 3 : n;\n\n\twhile (p > buf && isspace(p[-1]))\n\t\t*--p = '\\0';\n\n\t*p++ = '\\r';\n\t*p++ = '\\n';\n\t*p = '\\0';\n\n\twchar_t output[4096];\n\tstd::mbstowcs(output, buf, strlen(buf) + 1);\n\n#ifdef _MSC_VER\n\tOutputDebugString(output);\n#endif\n\n\tdelete[] con;\n}\n\nvoid VBase::VClearLog()\n{\n#if defined(_WIN32)\n\tHANDLE hStdOut;\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\tDWORD count;\n\tDWORD cellCount;\n\tCOORD homeCoords = { 0, 0 };\n\n\thStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n\tif (hStdOut == INVALID_HANDLE_VALUE) return;\n\n\t\/* Get the number of cells in the current buffer *\/\n\tif (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;\n\tcellCount = csbi.dwSize.X *csbi.dwSize.Y;\n\n\t\/* Fill the entire buffer with spaces *\/\n\tif (!FillConsoleOutputCharacter(\n\t\thStdOut,\n\t\t(TCHAR) ' ',\n\t\tcellCount,\n\t\thomeCoords,\n\t\t&count\n\t)) return;\n\n\t\/* Fill the entire buffer with the current colors and attributes *\/\n\tif (!FillConsoleOutputAttribute(\n\t\thStdOut,\n\t\tcsbi.wAttributes,\n\t\tcellCount,\n\t\thomeCoords,\n\t\t&count\n\t)) return;\n\n\t\/* Move the cursor home *\/\n\tSetConsoleCursorPosition(hStdOut, homeCoords);\n#endif\n\n#ifdef __linux__\n\tif (!cur_term)\n\t{\n\t\tint result;\n\t\tsetupterm(NULL, STDOUT_FILENO, &result);\n\t\tif (result <= 0) return;\n\t}\n\n\tputp(tigetstr(\"clear\"));\n#endif\n}<commit_msg>Add source for clearing logs.<commit_after>#include \"VBase.h\"\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <ctype.h>\n#include <cstdio>\n#include <cstring>\n\n#if defined(_WIN32)\n#include <windows.h>\n#endif\n\n#if defined(__linux__)\n#include <unistd.h>\n#include <term.h>\n#endif\n\n#ifdef _DEBUG\nint VBase::DebugObjectCount = 0;\n#endif\n\nvoid VBase::VLog(const char* format, ...)\n{\n\tchar buf[4096], *p = buf;\n\tva_list args;\n\tint n;\n\n\tva_start(args, format);\n\tn = vsnprintf(p, sizeof buf - 3, format, args); \/\/ buf-3 is room for CR\/LF\/NUL\n\n\tint len = strlen(buf);\n\tchar* con = new char[len + 2];\n\n\tstrcpy(con, buf);\n\tcon[len] = '\\n';\n\tcon[len + 1] = '\\0';\n\n\tprintf(con, args);\n\tva_end(args);\n\n\tp += (n < 0) ? sizeof buf - 3 : n;\n\n\twhile (p > buf && isspace(p[-1]))\n\t\t*--p = '\\0';\n\n\t*p++ = '\\r';\n\t*p++ = '\\n';\n\t*p = '\\0';\n\n\twchar_t output[4096];\n\tstd::mbstowcs(output, buf, strlen(buf) + 1);\n\n#ifdef _MSC_VER\n\tOutputDebugString(output);\n#endif\n\n\tdelete[] con;\n}\n\n\/\/Source http:\/\/www.cplusplus.com\/articles\/4z18T05o\/\nvoid VBase::VClearLog()\n{\n#if defined(_WIN32)\n\tHANDLE hStdOut;\n\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\tDWORD count;\n\tDWORD cellCount;\n\tCOORD homeCoords = { 0, 0 };\n\n\thStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n\tif (hStdOut == INVALID_HANDLE_VALUE) return;\n\n\t\/* Get the number of cells in the current buffer *\/\n\tif (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;\n\tcellCount = csbi.dwSize.X *csbi.dwSize.Y;\n\n\t\/* Fill the entire buffer with spaces *\/\n\tif (!FillConsoleOutputCharacter(\n\t\thStdOut,\n\t\t(TCHAR) ' ',\n\t\tcellCount,\n\t\thomeCoords,\n\t\t&count\n\t)) return;\n\n\t\/* Fill the entire buffer with the current colors and attributes *\/\n\tif (!FillConsoleOutputAttribute(\n\t\thStdOut,\n\t\tcsbi.wAttributes,\n\t\tcellCount,\n\t\thomeCoords,\n\t\t&count\n\t)) return;\n\n\t\/* Move the cursor home *\/\n\tSetConsoleCursorPosition(hStdOut, homeCoords);\n#endif\n\n#ifdef __linux__\n\tif (!cur_term)\n\t{\n\t\tint result;\n\t\tsetupterm(NULL, STDOUT_FILENO, &result);\n\t\tif (result <= 0) return;\n\t}\n\n\tputp(tigetstr(\"clear\"));\n#endif\n}<|endoftext|>"} {"text":"<commit_before>\/* we will try to recreate the mem layout from the execution traces *\/\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include \"utility\/fileparser.h\"\n#include \"utility\/defines.h\"\n#include \"meminfo.h\"\n#include \"utilities.h\"\n#include \"memory\/meminstrace.h\"\n\nusing namespace std;\n\nvoid create_mem_layout(std::ifstream &in, vector<mem_info_t *> &mem_info, uint32_t version){\n\n\tuint32_t count = 0;\n\n\tin.clear();\n\tin.seekg(0, in.beg);\n\n\tDEBUG_PRINT((\"create_mem_layout(mem_info)...\\n\"), 2);\n\n\twhile (!in.eof()){\n\t\tcinstr_t * instr = get_next_from_ascii_file(in, version);\n\t\tmem_input_t * input = new mem_input_t;\n\n\t\tif (instr != NULL){\n\n\t\t\tfor (int i = 0; i < instr->num_srcs; i++){\n\t\t\t\tif (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){\n\t\t\t\t\tinput->mem_addr = instr->srcs[i].value;\n\t\t\t\t\tinput->stride = instr->srcs[i].width;\n\t\t\t\t\tinput->write = false;\n\t\t\t\t\tinput->type = instr->srcs[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < instr->num_dsts; i++){\n\t\t\t\tif (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){\n\t\t\t\t\tinput->mem_addr = instr->dsts[i].value;\n\t\t\t\t\tinput->stride = instr->dsts[i].width;\n\t\t\t\t\tinput->write = true;\n\t\t\t\t\tinput->type = instr->dsts[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tprint_progress(&count, 10000);\n\n\t\tdelete instr;\n\t\tdelete input;\n\t}\n\n\tpostprocess_mem_regions(mem_info);\n\n\tDEBUG_PRINT((\"create_mem_layout(mem_info) - done\\n\"), 2);\n\n\n}\n\n\/* only app_pc based pc_mem_region recording is done here - if needed implement the module based recording *\/\nvoid create_mem_layout(std::ifstream &in, vector<pc_mem_region_t *> &mem_info, uint32_t version){\n\n\tuint32_t count = 0;\n\n\tin.clear();\n\tin.seekg(0, in.beg);\n\n\tDEBUG_PRINT((\"create_mem_layout(pc_mem_regions)...\\n\"), 2);\n\n\twhile (!in.eof()){\n\t\tcinstr_t * instr = get_next_from_ascii_file(in, version);\n\t\tmem_input_t * input = new mem_input_t;\n\n\t\tif (instr != NULL){\n\n\t\t\tfor (int i = 0; i < instr->num_srcs; i++){\n\t\t\t\tif (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){\n\t\t\t\t\tinput->pc = instr->pc;\n\t\t\t\t\tinput->mem_addr = instr->srcs[i].value;\n\t\t\t\t\tinput->stride = instr->srcs[i].width;\n\t\t\t\t\tinput->write = false;\n\t\t\t\t\tinput->type = instr->srcs[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < instr->num_dsts; i++){\n\t\t\t\tif (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){\n\t\t\t\t\tinput->pc = instr->pc;\n\t\t\t\t\tinput->mem_addr = instr->dsts[i].value;\n\t\t\t\t\tinput->stride = instr->dsts[i].width;\n\t\t\t\t\tinput->write = true;\n\t\t\t\t\tinput->type = instr->dsts[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tprint_progress(&count, 10000);\n\n\t\tdelete instr;\n\t\tdelete input;\n\t}\n\n\tpostprocess_mem_regions(mem_info);\n\n\tDEBUG_PRINT((\"create_mem_layout(pc_mem_regions) - done\\n\"), 2);\n\n}\n\nvoid create_mem_layout(vector<cinstr_t * > &instrs, vector<mem_info_t *> &mem_info){\n\n}\n\nvoid create_mem_layout(vector<cinstr_t * > &instrs, vector<pc_mem_region_t *> &pc_mems){\n\n}\n\n<commit_msg>stack locations excluded<commit_after>\/* we will try to recreate the mem layout from the execution traces *\/\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include \"utility\/fileparser.h\"\n#include \"utility\/defines.h\"\n#include \"meminfo.h\"\n#include \"utilities.h\"\n#include \"memory\/meminstrace.h\"\n\nusing namespace std;\n\nvoid create_mem_layout(std::ifstream &in, vector<mem_info_t *> &mem_info, uint32_t version){\n\n\tuint32_t count = 0;\n\n\tin.clear();\n\tin.seekg(0, in.beg);\n\n\tDEBUG_PRINT((\"create_mem_layout(mem_info)...\\n\"), 2);\n\n\twhile (!in.eof()){\n\t\tcinstr_t * instr = get_next_from_ascii_file(in, version);\n\t\tmem_input_t * input = new mem_input_t;\n\n\t\tif (instr != NULL){\n\n\t\t\tfor (int i = 0; i < instr->num_srcs; i++){\n\t\t\t\tif (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\n\t\t\t\t\tbool skip = true;\n\t\t\t\t\tif (instr->srcs[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\toperand_t opnd = instr->srcs[i];\n\t\t\t\t\t\tfor (int addr = 0; addr < 2; addr++){\n\t\t\t\t\t\t\tuint32_t reg = opnd.addr[addr].value;\n\t\t\t\t\t\t\tif (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tskip = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (skip) continue;\n\n\t\t\t\t\tinput->mem_addr = instr->srcs[i].value;\n\t\t\t\t\tinput->stride = instr->srcs[i].width;\n\t\t\t\t\tinput->write = false;\n\t\t\t\t\tinput->type = instr->srcs[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < instr->num_dsts; i++){\n\t\t\t\tif (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\n\t\t\t\t\tbool skip = true;\n\t\t\t\t\tif (instr->dsts[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\toperand_t opnd = instr->dsts[i];\n\t\t\t\t\t\tfor (int addr = 0; addr < 2; addr++){\n\t\t\t\t\t\t\tuint32_t reg = opnd.addr[addr].value;\n\t\t\t\t\t\t\tif (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tskip = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (skip) continue;\n\n\n\t\t\t\t\tinput->mem_addr = instr->dsts[i].value;\n\t\t\t\t\tinput->stride = instr->dsts[i].width;\n\t\t\t\t\tinput->write = true;\n\t\t\t\t\tinput->type = instr->dsts[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tprint_progress(&count, 10000);\n\n\t\tdelete instr;\n\t\tdelete input;\n\t}\n\n\tpostprocess_mem_regions(mem_info);\n\n\tDEBUG_PRINT((\"create_mem_layout(mem_info) - done\\n\"), 2);\n\n\n}\n\n\/* only app_pc based pc_mem_region recording is done here - if needed implement the module based recording *\/\nvoid create_mem_layout(std::ifstream &in, vector<pc_mem_region_t *> &mem_info, uint32_t version){\n\n\tuint32_t count = 0;\n\n\tin.clear();\n\tin.seekg(0, in.beg);\n\n\tDEBUG_PRINT((\"create_mem_layout(pc_mem_regions)...\\n\"), 2);\n\n\twhile (!in.eof()){\n\t\tcinstr_t * instr = get_next_from_ascii_file(in, version);\n\t\tmem_input_t * input = new mem_input_t;\n\n\t\tif (instr != NULL){\n\n\t\t\tfor (int i = 0; i < instr->num_srcs; i++){\n\t\t\t\tif (instr->srcs[i].type == MEM_HEAP_TYPE || instr->srcs[i].type == MEM_STACK_TYPE){\n\n\t\t\t\t\tbool skip = true;\n\t\t\t\t\tif (instr->srcs[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\toperand_t opnd = instr->srcs[i];\n\t\t\t\t\t\tfor (int addr = 0; addr < 2; addr++){\n\t\t\t\t\t\t\tuint32_t reg = opnd.addr[addr].value;\n\t\t\t\t\t\t\tif (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tskip = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (skip) continue;\n\n\t\t\t\t\tinput->pc = instr->pc;\n\t\t\t\t\tinput->mem_addr = instr->srcs[i].value;\n\t\t\t\t\tinput->stride = instr->srcs[i].width;\n\t\t\t\t\tinput->write = false;\n\t\t\t\t\tinput->type = instr->srcs[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < instr->num_dsts; i++){\n\t\t\t\tif (instr->dsts[i].type == MEM_HEAP_TYPE || instr->dsts[i].type == MEM_STACK_TYPE){\n\n\t\t\t\t\tbool skip = true;\n\t\t\t\t\tif (instr->dsts[i].type == MEM_STACK_TYPE){\n\t\t\t\t\t\toperand_t opnd = instr->dsts[i];\n\t\t\t\t\t\tfor (int addr = 0; addr < 2; addr++){\n\t\t\t\t\t\t\tuint32_t reg = opnd.addr[addr].value;\n\t\t\t\t\t\t\tif (reg != 0 && reg != DR_REG_EBP && reg != DR_REG_ESP) skip = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tskip = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (skip) continue;\n\n\n\t\t\t\t\tinput->pc = instr->pc;\n\t\t\t\t\tinput->mem_addr = instr->dsts[i].value;\n\t\t\t\t\tinput->stride = instr->dsts[i].width;\n\t\t\t\t\tinput->write = true;\n\t\t\t\t\tinput->type = instr->dsts[i].type;\n\t\t\t\t\tif (input->stride != 0){\n\t\t\t\t\t\tupdate_mem_regions(mem_info, input);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tprint_progress(&count, 10000);\n\n\t\tdelete instr;\n\t\tdelete input;\n\t}\n\n\tpostprocess_mem_regions(mem_info);\n\n\tDEBUG_PRINT((\"create_mem_layout(pc_mem_regions) - done\\n\"), 2);\n\n}\n\nvoid create_mem_layout(vector<cinstr_t * > &instrs, vector<mem_info_t *> &mem_info){\n\n}\n\nvoid create_mem_layout(vector<cinstr_t * > &instrs, vector<pc_mem_region_t *> &pc_mems){\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"test\/test_syscoin_services.h\"\n#include \"data\/utxo.json.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include <boost\/test\/unit_test.hpp>\n#include <univalue.h>\n\nextern UniValue read_json(const std::string& jsondata);\nBOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)\nstruct PaymentAmount\n{\n\tstd::string address;\n\tstd::string amount;\n};\nvoid VerifySnapShot()\n{\n}\nvoid GenerateSnapShot()\n{\n}\nvoid GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)\n{\n UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 2) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n\t\tPaymentAmount payment;\n payment.address = test[0].get_str();\n payment.amount = ValueFromAmount(test[1].get_int64()).write());\n\t\tpaymentAmounts.push_back(payment);\n }\n}\nbool IsMainNetAlreadyCreated()\n{\n\tint height;\n\tUniValue r;\n\tBOOST_CHECK_NO_THROW(r = CallRPC(node, \"getinfo\"));\n\theight = find_value(r.get_obj(), \"blocks\").get_int();\n\treturn height > 0;\n}\nBOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)\n{\n\tstd::vector<PaymentAmount> paymentAmounts;\n\tGetUTXOs(paymentAmounts);\n\tif(IsMainNetAlreadyCreated())\n\t{\n\t\tVerifySnapShot();\n\t}\n\telse\n\t{\n\t\tGenerateSnapShot();\n\t\tVerifySnapShot();\n\t}\n}\nBOOST_AUTO_TEST_SUITE_END ()<commit_msg>typos<commit_after>#include \"test\/test_syscoin_services.h\"\n#include \"data\/utxo.json.h\"\n#include \"utiltime.h\"\n#include \"rpcserver.h\"\n#include <boost\/test\/unit_test.hpp>\n#include <univalue.h>\n\nextern UniValue read_json(const std::string& jsondata);\nBOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)\nstruct PaymentAmount\n{\n\tstd::string address;\n\tstd::string amount;\n};\nvoid VerifySnapShot()\n{\n}\nvoid GenerateSnapShot()\n{\n}\nvoid GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)\n{\n UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 2) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n\t\tPaymentAmount payment;\n payment.address = test[0].get_str();\n payment.amount = ValueFromAmount(test[1].get_int64()).write();\n\t\tpaymentAmounts.push_back(payment);\n }\n}\nbool IsMainNetAlreadyCreated()\n{\n\tint height;\n\tUniValue r;\n\tBOOST_CHECK_NO_THROW(r = CallRPC(\"mainnet1\", \"getinfo\"));\n\theight = find_value(r.get_obj(), \"blocks\").get_int();\n\treturn height > 0;\n}\nBOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)\n{\n\tstd::vector<PaymentAmount> paymentAmounts;\n\tGetUTXOs(paymentAmounts);\n\tif(IsMainNetAlreadyCreated())\n\t{\n\t\tVerifySnapShot();\n\t}\n\telse\n\t{\n\t\tGenerateSnapShot();\n\t\tVerifySnapShot();\n\t}\n}\nBOOST_AUTO_TEST_SUITE_END ()<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2011 New Dream Network\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"common\/errno.h\"\n#include \"include\/atomic.h\"\n#include \"systest_runnable.h\"\n#include \"systest_settings.h\"\n\n#include <errno.h>\n#include <pthread.h>\n#include <sstream>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <string>\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <vector>\n\nusing std::ostringstream;\nusing std::string;\n\nstatic pid_t do_gettid(void)\n{\n return static_cast < pid_t >(syscall(SYS_gettid));\n}\n\nceph::atomic_t m_highest_id(0);\n\nSysTestRunnable::\nSysTestRunnable(int argc, const char **argv)\n : m_argc(0),\n m_argv(NULL),\n m_argv_orig(NULL)\n{\n m_started = false;\n m_id = m_highest_id.inc();\n memset(&m_pthread, 0, sizeof(m_pthread));\n m_pid = 0;\n update_id_str(false);\n set_argv(argc, argv);\n}\n\nSysTestRunnable::\n~SysTestRunnable()\n{\n set_argv(0, NULL);\n}\n\nconst char* SysTestRunnable::\nget_id_str(void) const\n{\n return m_id_str;\n}\n\nint SysTestRunnable::\nstart()\n{\n if (m_started) {\n return -EDOM;\n }\n bool use_threads = SysTestSettings::inst().use_threads();\n if (use_threads) {\n int ret = pthread_create(&m_pthread, NULL, systest_runnable_pthread_helper,\n\t\t\t static_cast<void*>(this));\n if (ret)\n return ret;\n m_started = true;\n return 0;\n }\n else {\n pid_t pid = fork();\n if (pid == -1) {\n int err = errno;\n return -err;\n }\n else if (pid == 0) {\n m_started = true;\n m_pid = getpid();\n void *retptr = systest_runnable_pthread_helper(static_cast<void*>(this));\n exit((int)(uintptr_t)retptr);\n }\n else {\n m_started = true;\n m_pid = pid;\n return 0;\n }\n }\n}\n\nstd::string SysTestRunnable::\njoin()\n{\n if (!m_started) {\n return \"SysTestRunnable was never started.\";\n }\n bool use_threads = SysTestSettings::inst().use_threads();\n if (use_threads) {\n void *ptrretval;\n int ret = pthread_join(m_pthread, &ptrretval);\n if (ret) {\n ostringstream oss;\n oss << \"pthread_join failed with error \" << ret;\n return oss.str();\n }\n int retval = (int)(uintptr_t)ptrretval;\n if (retval != 0) {\n ostringstream oss;\n oss << \"ERROR \" << retval;\n return oss.str();\n }\n return \"\";\n }\n else {\n int status;\n printf(\"waitpid(%d)\\n\", m_pid);\n pid_t pid = waitpid(m_pid, &status, 0);\n if (pid == -1) {\n int err = errno;\n ostringstream oss;\n oss << get_id_str() << \" waitpid error: \" << cpp_strerror(err);\n return oss.str();\n }\n else if (WIFSIGNALED(status)) {\n ostringstream oss;\n oss << get_id_str() << \" exited with a signal\";\n return oss.str();\n }\n else if (!WIFEXITED(status)) {\n ostringstream oss;\n oss << get_id_str() << \" did not exit normally\";\n return oss.str();\n }\n else {\n int exit_status = WEXITSTATUS(status);\n if (exit_status != 0) {\n\tostringstream oss;\n\toss << get_id_str() << \" returned exit_status \" << exit_status;\n\treturn oss.str();\n }\n return \"\";\n }\n }\n}\n\nstd::string SysTestRunnable::\nrun_until_finished(std::vector < SysTestRunnable * > &runnables)\n{\n int ret, index = 0;\n for (std::vector < SysTestRunnable * >::const_iterator r = runnables.begin();\n r != runnables.end(); ++r) {\n ret = (*r)->start();\n if (ret) {\n ostringstream oss;\n oss << \"run_until_finished: got error \" << ret\n\t << \" when starting runnable \" << index;\n return oss.str();\n }\n ++index;\n }\n\n for (std::vector < SysTestRunnable * >::const_iterator r = runnables.begin();\n r != runnables.end(); ++r) {\n std::string rstr = (*r)->join();\n if (!rstr.empty()) {\n ostringstream oss;\n oss << \"run_until_finished: runnable \" << (*r)->get_id_str() \n\t << \": got error: \" << rstr;\n return oss.str();\n }\n }\n return \"\";\n}\n\nvoid *systest_runnable_pthread_helper(void *arg)\n{\n SysTestRunnable *st = static_cast < SysTestRunnable * >(arg);\n st->update_id_str(true);\n int ret = st->run();\n return (void*)(uintptr_t)ret;\n}\n\nvoid SysTestRunnable::\nupdate_id_str(bool started)\n{\n bool use_threads = SysTestSettings::inst().use_threads();\n char extra[128];\n extra[0] = '\\0';\n\n if (started) {\n if (use_threads)\n snprintf(extra, sizeof(extra), \"_[%d]\", do_gettid());\n else\n snprintf(extra, sizeof(extra), \"_[%d]\", getpid());\n }\n if (use_threads)\n snprintf(m_id_str, SysTestRunnable::ID_STR_SZ, \"thread_%d%s\", m_id, extra);\n else\n snprintf(m_id_str, SysTestRunnable::ID_STR_SZ, \"process_%d%s\", m_id, extra);\n}\n\n\/\/ Copy argv so that if some fiend decides to modify it, it's ok.\nvoid SysTestRunnable::\nset_argv(int argc, const char **argv)\n{\n if (m_argv_orig != NULL) {\n for (int i = 0; i < m_argc; ++i)\n free((void*)(m_argv_orig[i]));\n delete m_argv_orig;\n m_argv_orig = NULL;\n delete m_argv;\n m_argv = NULL;\n m_argc = 0;\n }\n if (argv == NULL)\n return;\n m_argc = argc;\n m_argv_orig = new const char*[m_argc+1];\n for (int i = 0; i < m_argc; ++i)\n m_argv_orig[i] = strdup(argv[i]);\n m_argv_orig[argc] = NULL;\n m_argv = new const char*[m_argc+1];\n for (int i = 0; i <= m_argc; ++i)\n m_argv[i] = m_argv_orig[i];\n}\n<commit_msg>systest_runnable: print line when joining runnables<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2011 New Dream Network\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"common\/errno.h\"\n#include \"include\/atomic.h\"\n#include \"systest_runnable.h\"\n#include \"systest_settings.h\"\n\n#include <errno.h>\n#include <pthread.h>\n#include <sstream>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <string>\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <vector>\n\nusing std::ostringstream;\nusing std::string;\n\nstatic pid_t do_gettid(void)\n{\n return static_cast < pid_t >(syscall(SYS_gettid));\n}\n\nceph::atomic_t m_highest_id(0);\n\nSysTestRunnable::\nSysTestRunnable(int argc, const char **argv)\n : m_argc(0),\n m_argv(NULL),\n m_argv_orig(NULL)\n{\n m_started = false;\n m_id = m_highest_id.inc();\n memset(&m_pthread, 0, sizeof(m_pthread));\n m_pid = 0;\n update_id_str(false);\n set_argv(argc, argv);\n}\n\nSysTestRunnable::\n~SysTestRunnable()\n{\n set_argv(0, NULL);\n}\n\nconst char* SysTestRunnable::\nget_id_str(void) const\n{\n return m_id_str;\n}\n\nint SysTestRunnable::\nstart()\n{\n if (m_started) {\n return -EDOM;\n }\n bool use_threads = SysTestSettings::inst().use_threads();\n if (use_threads) {\n int ret = pthread_create(&m_pthread, NULL, systest_runnable_pthread_helper,\n\t\t\t static_cast<void*>(this));\n if (ret)\n return ret;\n m_started = true;\n return 0;\n }\n else {\n pid_t pid = fork();\n if (pid == -1) {\n int err = errno;\n return -err;\n }\n else if (pid == 0) {\n m_started = true;\n m_pid = getpid();\n void *retptr = systest_runnable_pthread_helper(static_cast<void*>(this));\n exit((int)(uintptr_t)retptr);\n }\n else {\n m_started = true;\n m_pid = pid;\n return 0;\n }\n }\n}\n\nstd::string SysTestRunnable::\njoin()\n{\n if (!m_started) {\n return \"SysTestRunnable was never started.\";\n }\n bool use_threads = SysTestSettings::inst().use_threads();\n if (use_threads) {\n void *ptrretval;\n int ret = pthread_join(m_pthread, &ptrretval);\n if (ret) {\n ostringstream oss;\n oss << \"pthread_join failed with error \" << ret;\n return oss.str();\n }\n int retval = (int)(uintptr_t)ptrretval;\n if (retval != 0) {\n ostringstream oss;\n oss << \"ERROR \" << retval;\n return oss.str();\n }\n return \"\";\n }\n else {\n int status;\n printf(\"waitpid(%d)\\n\", m_pid);\n pid_t pid = waitpid(m_pid, &status, 0);\n if (pid == -1) {\n int err = errno;\n ostringstream oss;\n oss << get_id_str() << \" waitpid error: \" << cpp_strerror(err);\n return oss.str();\n }\n else if (WIFSIGNALED(status)) {\n ostringstream oss;\n oss << get_id_str() << \" exited with a signal\";\n return oss.str();\n }\n else if (!WIFEXITED(status)) {\n ostringstream oss;\n oss << get_id_str() << \" did not exit normally\";\n return oss.str();\n }\n else {\n int exit_status = WEXITSTATUS(status);\n if (exit_status != 0) {\n\tostringstream oss;\n\toss << get_id_str() << \" returned exit_status \" << exit_status;\n\treturn oss.str();\n }\n return \"\";\n }\n }\n}\n\nstd::string SysTestRunnable::\nrun_until_finished(std::vector < SysTestRunnable * > &runnables)\n{\n int ret, index = 0;\n for (std::vector < SysTestRunnable * >::const_iterator r = runnables.begin();\n r != runnables.end(); ++r) {\n ret = (*r)->start();\n if (ret) {\n ostringstream oss;\n oss << \"run_until_finished: got error \" << ret\n\t << \" when starting runnable \" << index;\n return oss.str();\n }\n ++index;\n }\n\n for (std::vector < SysTestRunnable * >::const_iterator r = runnables.begin();\n r != runnables.end(); ++r) {\n std::string rstr = (*r)->join();\n if (!rstr.empty()) {\n ostringstream oss;\n oss << \"run_until_finished: runnable \" << (*r)->get_id_str() \n\t << \": got error: \" << rstr;\n return oss.str();\n }\n }\n printf(\"*******************************\\n\");\n return \"\";\n}\n\nvoid *systest_runnable_pthread_helper(void *arg)\n{\n SysTestRunnable *st = static_cast < SysTestRunnable * >(arg);\n st->update_id_str(true);\n int ret = st->run();\n return (void*)(uintptr_t)ret;\n}\n\nvoid SysTestRunnable::\nupdate_id_str(bool started)\n{\n bool use_threads = SysTestSettings::inst().use_threads();\n char extra[128];\n extra[0] = '\\0';\n\n if (started) {\n if (use_threads)\n snprintf(extra, sizeof(extra), \"_[%d]\", do_gettid());\n else\n snprintf(extra, sizeof(extra), \"_[%d]\", getpid());\n }\n if (use_threads)\n snprintf(m_id_str, SysTestRunnable::ID_STR_SZ, \"thread_%d%s\", m_id, extra);\n else\n snprintf(m_id_str, SysTestRunnable::ID_STR_SZ, \"process_%d%s\", m_id, extra);\n}\n\n\/\/ Copy argv so that if some fiend decides to modify it, it's ok.\nvoid SysTestRunnable::\nset_argv(int argc, const char **argv)\n{\n if (m_argv_orig != NULL) {\n for (int i = 0; i < m_argc; ++i)\n free((void*)(m_argv_orig[i]));\n delete m_argv_orig;\n m_argv_orig = NULL;\n delete m_argv;\n m_argv = NULL;\n m_argc = 0;\n }\n if (argv == NULL)\n return;\n m_argc = argc;\n m_argv_orig = new const char*[m_argc+1];\n for (int i = 0; i < m_argc; ++i)\n m_argv_orig[i] = strdup(argv[i]);\n m_argv_orig[argc] = NULL;\n m_argv = new const char*[m_argc+1];\n for (int i = 0; i <= m_argc; ++i)\n m_argv[i] = m_argv_orig[i];\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"include\/engine\/SoundEngine.h\"\r\n\r\nSoundEngine::SoundEngine(int soundEffectsVolume, int musicVolume, QObject *parent) :\r\n QObject(parent), satCounter(0)\r\n{\r\n Phonon::AudioOutput *shootOutput = new Phonon::AudioOutput(Phonon::GameCategory, this);\r\n shootOutput->setVolume(soundEffectsVolume \/ 100.0);\r\n Phonon::AudioOutput *satOutput = new Phonon::AudioOutput(Phonon::GameCategory, this);\r\n satOutput->setVolume(soundEffectsVolume \/ 100.0);\r\n\r\n Phonon::AudioOutput *musicOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);\r\n musicOutput->setVolume(musicVolume \/ 100.0);\r\n\r\n shootMediaObject = new Phonon::MediaObject(this);\r\n shootMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/laser\"));\r\n Phonon::createPath(shootMediaObject, shootOutput);\r\n\r\n satMediaObject = new Phonon::MediaObject(this);\r\n satMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/sat\"));\r\n Phonon::createPath(satMediaObject, satOutput);\r\n\r\n musicMediaObject = new Phonon::MediaObject(this);\r\n musicMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/bgmusic\"));\r\n Phonon::createPath(musicMediaObject, musicOutput);\r\n connect(musicMediaObject, SIGNAL(aboutToFinish()), this, SLOT(musicFinished()));\r\n musicMediaObject->play();\r\n}\r\n\r\nvoid SoundEngine::playSound(Sounds toPlay)\r\n{\r\n if(toPlay == SatelliteSound)\r\n {\r\n if(++satCounter <= 1)\r\n {\r\n playSat();\r\n QTimer::singleShot(SAT_INTERVAL, this, SLOT(playSat()));\r\n }\r\n }\r\n else if(toPlay == ShootSound)\r\n {\r\n shootMediaObject->seek(0);\r\n shootMediaObject->play();\r\n }\r\n}\r\n\r\nvoid SoundEngine::stopSound(Sounds toStop)\r\n{\r\n if(toStop == SatelliteSound)\r\n --satCounter;\r\n}\r\n\r\nvoid SoundEngine::playSat()\r\n{\r\n if(satCounter > 0)\r\n {\r\n qDebug() << \"Counter : \" << satCounter;\r\n\r\n satMediaObject->seek(0);\r\n satMediaObject->play();\r\n\r\n QTimer::singleShot(SAT_INTERVAL, this, SLOT(playSat()));\r\n }\r\n}\r\n\r\nvoid SoundEngine::musicFinished()\r\n{\r\n musicMediaObject->enqueue(Phonon::MediaSource(\":\/sounds\/bgmusic\"));\r\n}\r\n<commit_msg>Remove annoying qDebug()<commit_after>#include \"include\/engine\/SoundEngine.h\"\r\n\r\nSoundEngine::SoundEngine(int soundEffectsVolume, int musicVolume, QObject *parent) :\r\n QObject(parent), satCounter(0)\r\n{\r\n Phonon::AudioOutput *shootOutput = new Phonon::AudioOutput(Phonon::GameCategory, this);\r\n shootOutput->setVolume(soundEffectsVolume \/ 100.0);\r\n Phonon::AudioOutput *satOutput = new Phonon::AudioOutput(Phonon::GameCategory, this);\r\n satOutput->setVolume(soundEffectsVolume \/ 100.0);\r\n\r\n Phonon::AudioOutput *musicOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);\r\n musicOutput->setVolume(musicVolume \/ 100.0);\r\n\r\n shootMediaObject = new Phonon::MediaObject(this);\r\n shootMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/laser\"));\r\n Phonon::createPath(shootMediaObject, shootOutput);\r\n\r\n satMediaObject = new Phonon::MediaObject(this);\r\n satMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/sat\"));\r\n Phonon::createPath(satMediaObject, satOutput);\r\n\r\n musicMediaObject = new Phonon::MediaObject(this);\r\n musicMediaObject->setCurrentSource(Phonon::MediaSource(\":\/sounds\/bgmusic\"));\r\n Phonon::createPath(musicMediaObject, musicOutput);\r\n connect(musicMediaObject, SIGNAL(aboutToFinish()), this, SLOT(musicFinished()));\r\n musicMediaObject->play();\r\n}\r\n\r\nvoid SoundEngine::playSound(Sounds toPlay)\r\n{\r\n if(toPlay == SatelliteSound)\r\n {\r\n if(++satCounter <= 1)\r\n {\r\n playSat();\r\n QTimer::singleShot(SAT_INTERVAL, this, SLOT(playSat()));\r\n }\r\n }\r\n else if(toPlay == ShootSound)\r\n {\r\n shootMediaObject->seek(0);\r\n shootMediaObject->play();\r\n }\r\n}\r\n\r\nvoid SoundEngine::stopSound(Sounds toStop)\r\n{\r\n if(toStop == SatelliteSound)\r\n --satCounter;\r\n}\r\n\r\nvoid SoundEngine::playSat()\r\n{\r\n if(satCounter > 0)\r\n {\r\n satMediaObject->seek(0);\r\n satMediaObject->play();\r\n\r\n QTimer::singleShot(SAT_INTERVAL, this, SLOT(playSat()));\r\n }\r\n}\r\n\r\nvoid SoundEngine::musicFinished()\r\n{\r\n musicMediaObject->enqueue(Phonon::MediaSource(\":\/sounds\/bgmusic\"));\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"nano.h\"\n#include \"class.h\"\n#include \"measure.h\"\n#include \"text\/table.h\"\n#include \"accumulator.h\"\n#include \"text\/cmdline.h\"\n#include \"math\/random.h\"\n#include \"tensor\/numeric.h\"\n#include \"measure_and_log.h\"\n#include \"layers\/make_layers.h\"\n#include \"tasks\/task_charset.h\"\n#include \"text\/table_row_mark.h\"\n#include <iostream>\n\nint main(int argc, const char *argv[])\n{\n using namespace nano;\n\n \/\/ parse the command line\n cmdline_t cmdline(\"benchmark models\");\n cmdline.add(\"s\", \"samples\", \"number of samples to use [100, 10000]\", \"1000\");\n cmdline.add(\"c\", \"conn\", \"plane connectivity for convolution networks [1, 16]\", \"8\");\n cmdline.add(\"\", \"mlps\", \"benchmark MLP models\");\n cmdline.add(\"\", \"convnets\", \"benchmark convolution networks\");\n cmdline.add(\"\", \"forward\", \"evaluate the \\'forward\\' pass (output)\");\n cmdline.add(\"\", \"backward\", \"evaluate the \\'backward' pass (gradient)\");\n cmdline.add(\"\", \"activation\", \"activation layer\", \"act-snorm\");\n cmdline.add(\"\", \"detailed\", \"print detailed measurements (e.g. per-layer)\");\n\n cmdline.process(argc, argv);\n\n \/\/ check arguments and options\n const auto cmd_samples = clamp(cmdline.get<size_t>(\"samples\"), 100, 100 * 1000);\n const auto conn = clamp(cmdline.get<int>(\"conn\"), 1, 16);\n const auto cmd_forward = cmdline.has(\"forward\");\n const auto cmd_backward = cmdline.has(\"backward\");\n const auto cmd_mlps = cmdline.has(\"mlps\");\n const auto cmd_convnets = cmdline.has(\"convnets\");\n const auto activation = cmdline.get(\"activation\");\n const auto cmd_detailed = cmdline.has(\"detailed\");\n\n if (!cmd_forward && !cmd_backward)\n {\n cmdline.usage();\n }\n\n if (!cmd_mlps && !cmd_convnets)\n {\n cmdline.usage();\n }\n\n const auto cmd_rows = 28;\n const auto cmd_cols = 28;\n const auto cmd_color = color_mode::luma;\n\n const size_t cmd_min_nthreads = 1;\n const size_t cmd_max_nthreads = logical_cpus();\n\n \/\/ generate synthetic task\n charset_task_t task(to_params(\n \"type\", charset_mode::digit, \"color\", cmd_color, \"irows\", cmd_rows, \"icols\", cmd_cols, \"count\", cmd_samples));\n task.load();\n\n \/\/ construct models\n const string_t mlp0;\n const string_t mlp1 = mlp0 + make_affine_layer(128, activation);\n const string_t mlp2 = mlp1 + make_affine_layer(512, activation);\n const string_t mlp3 = mlp2 + make_affine_layer(128, activation);\n const string_t mlp4 = mlp3 + make_affine_layer(512, activation);\n const string_t mlp5 = mlp4 + make_affine_layer(128, activation);\n const string_t mlp6 = mlp5 + make_affine_layer(512, activation);\n const string_t mlp7 = mlp6 + make_affine_layer(128, activation);\n\n const string_t convnet0;\n const string_t convnet1 = convnet0 + make_conv_layer(128, 7, 7, 1, activation);\n const string_t convnet2 = convnet1 + make_conv_layer(128, 7, 7, conn, activation);\n const string_t convnet3 = convnet2 + make_conv_layer(128, 5, 5, conn, activation);\n const string_t convnet4 = convnet3 + make_conv_layer(128, 5, 5, conn, activation);\n const string_t convnet5 = convnet4 + make_conv_layer(128, 3, 3, conn, activation);\n const string_t convnet6 = convnet5 + make_conv_layer(128, 3, 3, conn, activation);\n const string_t convnet7 = convnet6 + make_conv_layer(128, 3, 3, conn, activation);\n\n const string_t outlayer = make_output_layer(task.odims());\n\n std::vector<std::pair<string_t, string_t>> networks;\n #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))\n if (cmd_mlps)\n {\n DEFINE(mlp0);\n DEFINE(mlp1);\n DEFINE(mlp2);\n DEFINE(mlp3);\n DEFINE(mlp4);\n DEFINE(mlp5);\n DEFINE(mlp6);\n DEFINE(mlp7);\n }\n if (cmd_convnets)\n {\n DEFINE(convnet1);\n DEFINE(convnet2);\n DEFINE(convnet3);\n DEFINE(convnet4);\n DEFINE(convnet5);\n DEFINE(convnet6);\n DEFINE(convnet7);\n }\n #undef DEFINE\n\n const auto loss = get_losses().get(\"logistic\");\n const auto criterion = get_criteria().get(\"avg\");\n\n \/\/ construct tables to compare models\n table_t ftable; ftable.header() << \"model-forward [us] \/ sample\";\n table_t btable; btable.header() << \"model-backward [us] \/ sample\";\n\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n ftable.header() << (to_string(nthreads) + \"xCPU\");\n btable.header() << (to_string(nthreads) + \"xCPU\");\n }\n\n \/\/ evaluate models\n for (const auto& config : networks)\n {\n const string_t cmd_network = config.first;\n const string_t cmd_name = config.second;\n\n \/\/ create feed-forward network\n const auto model = get_models().get(\"forward-network\", cmd_network);\n model->configure(task);\n model->random();\n model->describe();\n\n auto& frow = ftable.append() << (cmd_name + \" (\" + to_string(model->psize()) + \")\");\n auto& brow = btable.append() << (cmd_name + \" (\" + to_string(model->psize()) + \")\");\n\n const auto fold = fold_t{0, protocol::train};\n\n std::vector<timings_t> ftimings(cmd_max_nthreads + 1);\n std::vector<timings_t> btimings(cmd_max_nthreads + 1);\n\n \/\/ process the samples\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n accumulator_t acc(*model, *loss, *criterion);\n acc.lambda(scalar_t(0.1));\n acc.threads(nthreads);\n\n if (cmd_forward)\n {\n const auto duration = measure_robustly_usec([&] ()\n {\n acc.mode(criterion_t::type::value);\n acc.update(task, fold);\n }, 1);\n\n log_info() << \"<<< processed [\" << acc.count()\n << \"] forward samples in \" << duration.count() << \" us.\";\n\n frow << idiv(static_cast<size_t>(duration.count()), acc.count());\n\n ftimings[nthreads] = acc.timings();\n }\n\n if (cmd_backward)\n {\n const auto duration = measure_robustly_usec([&] ()\n {\n acc.mode(criterion_t::type::vgrad);\n acc.update(task, fold);\n }, 1);\n\n log_info() << \"<<< processed [\" << acc.count()\n << \"] backward samples in \" << duration.count() << \" us.\";\n\n brow << idiv(static_cast<size_t>(duration.count()), acc.count());\n\n btimings[nthreads] = acc.timings();\n }\n }\n\n \/\/ detailed per-component (e.g. per-layer) timing information\n const auto print_timings = [&] (table_t& table, const string_t& basename,\n const std::vector<timings_t>& timings)\n {\n for (const auto& timing0 : timings[cmd_min_nthreads])\n {\n auto& row = table.append();\n row << (basename + timing0.first);\n\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n const auto& timingT = timings[nthreads];\n assert(timingT.find(timing0.first) != timingT.end());\n row << timingT.find(timing0.first)->second.avg();\n }\n }\n };\n\n if (cmd_forward && cmd_detailed)\n {\n print_timings(ftable, \">\", ftimings);\n }\n\n if (cmd_backward && cmd_detailed)\n {\n print_timings(btable, \">\", btimings);\n }\n }\n\n \/\/ print results\n if (cmd_forward)\n {\n ftable.mark(make_table_mark_minimum_percentage_cols<size_t>(5));\n std::cout << ftable;\n }\n if (cmd_backward)\n {\n btable.mark(make_table_mark_minimum_percentage_cols<size_t>(5));\n std::cout << btable;\n }\n\n \/\/ OK\n return EXIT_SUCCESS;\n}\n<commit_msg>more compact benchmark table<commit_after>#include \"nano.h\"\n#include \"class.h\"\n#include \"measure.h\"\n#include \"text\/table.h\"\n#include \"accumulator.h\"\n#include \"text\/cmdline.h\"\n#include \"math\/random.h\"\n#include \"tensor\/numeric.h\"\n#include \"measure_and_log.h\"\n#include \"layers\/make_layers.h\"\n#include \"tasks\/task_charset.h\"\n#include \"text\/table_row_mark.h\"\n#include <iostream>\n\nint main(int argc, const char *argv[])\n{\n using namespace nano;\n\n \/\/ parse the command line\n cmdline_t cmdline(\"benchmark models\");\n cmdline.add(\"s\", \"samples\", \"number of samples to use [100, 10000]\", \"1000\");\n cmdline.add(\"c\", \"conn\", \"plane connectivity for convolution networks [1, 16]\", \"8\");\n cmdline.add(\"\", \"mlps\", \"benchmark MLP models\");\n cmdline.add(\"\", \"convnets\", \"benchmark convolution networks\");\n cmdline.add(\"\", \"forward\", \"evaluate the \\'forward\\' pass (output)\");\n cmdline.add(\"\", \"backward\", \"evaluate the \\'backward' pass (gradient)\");\n cmdline.add(\"\", \"activation\", \"activation layer\", \"act-snorm\");\n cmdline.add(\"\", \"detailed\", \"print detailed measurements (e.g. per-layer)\");\n\n cmdline.process(argc, argv);\n\n \/\/ check arguments and options\n const auto cmd_samples = clamp(cmdline.get<size_t>(\"samples\"), 100, 100 * 1000);\n const auto conn = clamp(cmdline.get<int>(\"conn\"), 1, 16);\n const auto cmd_forward = cmdline.has(\"forward\");\n const auto cmd_backward = cmdline.has(\"backward\");\n const auto cmd_mlps = cmdline.has(\"mlps\");\n const auto cmd_convnets = cmdline.has(\"convnets\");\n const auto activation = cmdline.get(\"activation\");\n const auto cmd_detailed = cmdline.has(\"detailed\");\n\n if (!cmd_forward && !cmd_backward)\n {\n cmdline.usage();\n }\n\n if (!cmd_mlps && !cmd_convnets)\n {\n cmdline.usage();\n }\n\n const auto cmd_rows = 28;\n const auto cmd_cols = 28;\n const auto cmd_color = color_mode::luma;\n\n const size_t cmd_min_nthreads = 1;\n const size_t cmd_max_nthreads = logical_cpus();\n\n \/\/ generate synthetic task\n charset_task_t task(to_params(\n \"type\", charset_mode::digit, \"color\", cmd_color, \"irows\", cmd_rows, \"icols\", cmd_cols, \"count\", cmd_samples));\n task.load();\n\n \/\/ construct models\n const string_t mlp0;\n const string_t mlp1 = mlp0 + make_affine_layer(128, activation);\n const string_t mlp2 = mlp1 + make_affine_layer(512, activation);\n const string_t mlp3 = mlp2 + make_affine_layer(128, activation);\n const string_t mlp4 = mlp3 + make_affine_layer(512, activation);\n const string_t mlp5 = mlp4 + make_affine_layer(128, activation);\n const string_t mlp6 = mlp5 + make_affine_layer(512, activation);\n const string_t mlp7 = mlp6 + make_affine_layer(128, activation);\n\n const string_t convnet0;\n const string_t convnet1 = convnet0 + make_conv_layer(128, 7, 7, 1, activation);\n const string_t convnet2 = convnet1 + make_conv_layer(128, 7, 7, conn, activation);\n const string_t convnet3 = convnet2 + make_conv_layer(128, 5, 5, conn, activation);\n const string_t convnet4 = convnet3 + make_conv_layer(128, 5, 5, conn, activation);\n const string_t convnet5 = convnet4 + make_conv_layer(128, 3, 3, conn, activation);\n const string_t convnet6 = convnet5 + make_conv_layer(128, 3, 3, conn, activation);\n const string_t convnet7 = convnet6 + make_conv_layer(128, 3, 3, conn, activation);\n\n const string_t outlayer = make_output_layer(task.odims());\n\n std::vector<std::pair<string_t, string_t>> networks;\n #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))\n if (cmd_mlps)\n {\n DEFINE(mlp0);\n DEFINE(mlp1);\n DEFINE(mlp2);\n DEFINE(mlp3);\n DEFINE(mlp4);\n DEFINE(mlp5);\n DEFINE(mlp6);\n DEFINE(mlp7);\n }\n if (cmd_convnets)\n {\n DEFINE(convnet1);\n DEFINE(convnet2);\n DEFINE(convnet3);\n DEFINE(convnet4);\n DEFINE(convnet5);\n DEFINE(convnet6);\n DEFINE(convnet7);\n }\n #undef DEFINE\n\n const auto loss = get_losses().get(\"logistic\");\n const auto criterion = get_criteria().get(\"avg\");\n\n \/\/ construct tables to compare models\n table_t ftable; ftable.header() << \"forward [us\/sample]\";\n table_t btable; btable.header() << \"backward [us\/sample]\";\n\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n ftable.header() << (to_string(nthreads) + \"xCPU\");\n btable.header() << (to_string(nthreads) + \"xCPU\");\n }\n\n \/\/ evaluate models\n for (const auto& config : networks)\n {\n const string_t cmd_network = config.first;\n const string_t cmd_name = config.second;\n\n \/\/ create feed-forward network\n const auto model = get_models().get(\"forward-network\", cmd_network);\n model->configure(task);\n model->random();\n model->describe();\n\n auto& frow = ftable.append() << (cmd_name + \" (\" + to_string(model->psize()) + \")\");\n auto& brow = btable.append() << (cmd_name + \" (\" + to_string(model->psize()) + \")\");\n\n const auto fold = fold_t{0, protocol::train};\n\n std::vector<timings_t> ftimings(cmd_max_nthreads + 1);\n std::vector<timings_t> btimings(cmd_max_nthreads + 1);\n\n \/\/ process the samples\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n accumulator_t acc(*model, *loss, *criterion);\n acc.lambda(scalar_t(0.1));\n acc.threads(nthreads);\n\n if (cmd_forward)\n {\n const auto duration = measure_robustly_usec([&] ()\n {\n acc.mode(criterion_t::type::value);\n acc.update(task, fold);\n }, 1);\n\n log_info() << \"<<< processed [\" << acc.count()\n << \"] forward samples in \" << duration.count() << \" us.\";\n\n frow << idiv(static_cast<size_t>(duration.count()), acc.count());\n\n ftimings[nthreads] = acc.timings();\n }\n\n if (cmd_backward)\n {\n const auto duration = measure_robustly_usec([&] ()\n {\n acc.mode(criterion_t::type::vgrad);\n acc.update(task, fold);\n }, 1);\n\n log_info() << \"<<< processed [\" << acc.count()\n << \"] backward samples in \" << duration.count() << \" us.\";\n\n brow << idiv(static_cast<size_t>(duration.count()), acc.count());\n\n btimings[nthreads] = acc.timings();\n }\n }\n\n \/\/ detailed per-component (e.g. per-layer) timing information\n const auto print_timings = [&] (table_t& table, const string_t& basename,\n const std::vector<timings_t>& timings)\n {\n for (const auto& timing0 : timings[cmd_min_nthreads])\n {\n auto& row = table.append();\n row << (basename + timing0.first);\n\n for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)\n {\n const auto& timingT = timings[nthreads];\n assert(timingT.find(timing0.first) != timingT.end());\n row << timingT.find(timing0.first)->second.avg();\n }\n }\n };\n\n if (cmd_forward && cmd_detailed)\n {\n print_timings(ftable, \">\", ftimings);\n }\n\n if (cmd_backward && cmd_detailed)\n {\n print_timings(btable, \">\", btimings);\n }\n }\n\n \/\/ print results\n if (cmd_forward)\n {\n ftable.mark(make_table_mark_minimum_percentage_cols<size_t>(5));\n std::cout << ftable;\n }\n if (cmd_backward)\n {\n btable.mark(make_table_mark_minimum_percentage_cols<size_t>(5));\n std::cout << btable;\n }\n\n \/\/ OK\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * LinearTransferFunction.cpp\r\n *\r\n * Copyright (C) 2008 by Universitaet Stuttgart (VIS). \r\n * Alle Rechte vorbehalten.\r\n *\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"vislib\/graphics\/gl\/IncludeAllGL.h\"\r\n#include \"mmcore\/view\/LinearTransferFunction.h\"\r\n#ifdef _WIN32\r\n#include <windows.h>\r\n#endif\r\n#include \"mmcore\/param\/BoolParam.h\"\r\n#include \"mmcore\/param\/FloatParam.h\"\r\n#include \"mmcore\/param\/IntParam.h\"\r\n#include \"mmcore\/param\/StringParam.h\"\r\n#include \"mmcore\/param\/FilePathParam.h\"\r\n#include \"mmcore\/param\/ButtonParam.h\"\r\n#include \"mmcore\/utility\/ColourParser.h\"\r\n#include \"vislib\/Array.h\"\r\n#include \"vislib\/assert.h\"\r\n#include \"vislib\/math\/Vector.h\"\r\n#include \"vislib\/sys\/sysfunctions.h\"\r\n#include \"vislib\/sys\/Log.h\"\r\n\r\n\r\nnamespace megamol {\r\nnamespace core {\r\nnamespace view {\r\n\r\n static int InterColourComparer(const vislib::math::Vector<float, 5>& lhs, \r\n const vislib::math::Vector<float, 5>& rhs) {\r\n if (lhs[4] >= rhs[4]) {\r\n if (rhs[4] + vislib::math::FLOAT_EPSILON >= lhs[4]) {\r\n return 0;\r\n } else {\r\n return 1;\r\n }\r\n } else {\r\n if (lhs[4] + vislib::math::FLOAT_EPSILON >= rhs[4]) {\r\n return 0;\r\n } else {\r\n return -1;\r\n }\r\n }\r\n }\r\n\r\n} \/* end namespace view *\/\r\n} \/* end namespace core *\/\r\n} \/* end namespace megamol *\/\r\n\r\n\r\nusing namespace megamol::core;\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::LinearTransferFunction\r\n *\/\r\nview::LinearTransferFunction::LinearTransferFunction(void) : Module(),\r\n getTFSlot(\"gettransferfunction\", \"Provides the transfer function\"),\r\n minColSlot(\"mincolour\", \"The colour for the minimum value\"),\r\n maxColSlot(\"maxcolour\", \"The colour for the maximum value\"),\r\n texSizeSlot(\"texsize\", \"The size of the texture to generate\"),\r\n pathSlot(\"filepath\", \"path for serializing the TF\"),\r\n loadTFSlot(\"loadTF\", \"trigger loading from file\"),\r\n storeTFSlot(\"storeTF\", \"trigger saving to file\"),\r\n texID(0), texSize(1),\r\n texFormat(CallGetTransferFunction::TEXTURE_FORMAT_RGB),\r\n firstRequest(true) {\r\n\r\n view::CallGetTransferFunctionDescription cgtfd;\r\n this->getTFSlot.SetCallback(cgtfd.ClassName(), cgtfd.FunctionName(0),\r\n &LinearTransferFunction::requestTF);\r\n this->MakeSlotAvailable(&this->getTFSlot);\r\n\r\n this->minColSlot << new param::StringParam(\"blue\");\r\n this->MakeSlotAvailable(&this->minColSlot);\r\n\r\n vislib::StringA t1, t2;\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n t1.Format(\"enable%.2d\", i + 1);\r\n t2.Format(\"Enables the intermediate colour %d\", i + 1);\r\n this->interCols[i].enableSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].enableSlot->SetParameter(new param::BoolParam(false));\r\n this->MakeSlotAvailable(this->interCols[i].enableSlot);\r\n\r\n t1.Format(\"colour%.2d\", i + 1);\r\n t2.Format(\"The colour for the intermediate value no. %d\", i + 1);\r\n this->interCols[i].colSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].colSlot->SetParameter(new param::StringParam(\"Gray\"));\r\n this->MakeSlotAvailable(this->interCols[i].colSlot);\r\n\r\n t1.Format(\"value%.2d\", i + 1);\r\n t2.Format(\"The intermediate value no. %d\", i + 1);\r\n this->interCols[i].valSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].valSlot->SetParameter(new param::FloatParam(\r\n static_cast<float>(i + 1) \/ static_cast<float>(INTER_COLOUR_COUNT + 1),\r\n 0.0f, 1.0f));\r\n this->MakeSlotAvailable(this->interCols[i].valSlot);\r\n }\r\n\r\n this->maxColSlot << new param::StringParam(\"red\");\r\n this->MakeSlotAvailable(&this->maxColSlot);\r\n this->maxColSlot.ForceSetDirty();\r\n\r\n this->texSizeSlot << new param::IntParam(128, 2, 1024);\r\n this->MakeSlotAvailable(&this->texSizeSlot);\r\n\r\n this->pathSlot << new param::FilePathParam(\"\");\r\n this->MakeSlotAvailable(&this->pathSlot);\r\n\r\n this->loadTFSlot << new param::ButtonParam();\r\n this->loadTFSlot.SetUpdateCallback(&LinearTransferFunction::loadTFPressed);\r\n this->MakeSlotAvailable(&this->loadTFSlot);\r\n\r\n this->storeTFSlot << new param::ButtonParam();\r\n this->storeTFSlot.SetUpdateCallback(&LinearTransferFunction::storeTFPressed);\r\n this->MakeSlotAvailable(&this->storeTFSlot);\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::~LinearTransferFunction\r\n *\/\r\nview::LinearTransferFunction::~LinearTransferFunction(void) {\r\n this->Release();\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::create\r\n *\/\r\nbool view::LinearTransferFunction::create(void) {\r\n firstRequest = true;\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::release\r\n *\/\r\nvoid view::LinearTransferFunction::release(void) {\r\n ::glDeleteTextures(1, &this->texID);\r\n this->texID = 0;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::loadTFPressed\r\n *\/\r\nbool view::LinearTransferFunction::loadTFPressed(param::ParamSlot& param) {\r\n try {\r\n vislib::sys::BufferedFile inFile;\r\n if (!inFile.Open(pathSlot.Param<param::FilePathParam>()->Value(),\r\n vislib::sys::File::AccessMode::READ_ONLY,\r\n vislib::sys::File::ShareMode::SHARE_READ,\r\n vislib::sys::File::CreationMode::OPEN_ONLY)) {\r\n vislib::sys::Log::DefaultLog.WriteMsg(\r\n vislib::sys::Log::LEVEL_WARN,\r\n \"Unable to open TF file.\");\r\n \/\/ failed, but does not matter here\r\n return true;\r\n }\r\n\r\n while (!inFile.IsEOF()) {\r\n vislib::StringA line = vislib::sys::ReadLineFromFileA(inFile);\r\n line.TrimSpaces();\r\n if (line.IsEmpty()) continue;\r\n if (line[0] == '#') continue;\r\n vislib::StringA::Size pos = line.Find('=');\r\n vislib::StringA name = line.Substring(0, pos);\r\n vislib::StringA value = line.Substring(pos + 1);\r\n Module::child_list_type::iterator ano_end = this->ChildList_End();\r\n for (Module::child_list_type::iterator ano_i = this->ChildList_Begin(); ano_i != ano_end; ++ano_i) {\r\n std::shared_ptr<param::ParamSlot> p = std::dynamic_pointer_cast<param::ParamSlot>(*ano_i);\r\n if (p && p->Name().Equals(name)) {\r\n p->Parameter()->ParseValue(value);\r\n }\r\n }\r\n }\r\n inFile.Close();\r\n } catch (...) {\r\n\r\n }\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::requestTF\r\n *\/\r\nbool view::LinearTransferFunction::requestTF(Call& call) {\r\n view::CallGetTransferFunction *cgtf = dynamic_cast<view::CallGetTransferFunction*>(&call);\r\n if (cgtf == NULL) return false;\r\n\r\n if (firstRequest) {\r\n loadTFPressed(loadTFSlot);\r\n }\r\n\r\n bool dirty = this->minColSlot.IsDirty() || this->maxColSlot.IsDirty() || this->texSizeSlot.IsDirty();\r\n for (SIZE_T i = 0; !dirty && (i < INTER_COLOUR_COUNT); i++) {\r\n dirty = this->interCols[i].enableSlot->IsDirty()\r\n || this->interCols[i].colSlot->IsDirty()\r\n || this->interCols[i].valSlot->IsDirty();\r\n }\r\n if ((this->texID == 0) || dirty) {\r\n this->minColSlot.ResetDirty();\r\n this->maxColSlot.ResetDirty();\r\n this->texSizeSlot.ResetDirty();\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n this->interCols[i].enableSlot->ResetDirty();\r\n this->interCols[i].colSlot->ResetDirty();\r\n this->interCols[i].valSlot->ResetDirty();\r\n }\r\n\r\n bool t1de = (glIsEnabled(GL_TEXTURE_1D) == GL_TRUE);\r\n if (!t1de) glEnable(GL_TEXTURE_1D);\r\n if (this->texID == 0) glGenTextures(1, &this->texID);\r\n\r\n vislib::Array<vislib::math::Vector<float, 5> > cols;\r\n vislib::math::Vector<float, 5> cx1, cx2;\r\n bool validAlpha = false;\r\n if (utility::ColourParser::FromString(\r\n this->minColSlot.Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = 0.0f;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = 0.0f;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n if (utility::ColourParser::FromString(\r\n this->maxColSlot.Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = 1.0f;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = 1.0f;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n if (this->interCols[i].enableSlot->Param<param::BoolParam>()->Value()) {\r\n float val = this->interCols[i].valSlot->Param<param::FloatParam>()->Value();\r\n if (utility::ColourParser::FromString(\r\n this->interCols[i].colSlot->Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = val;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = val;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n }\r\n }\r\n\r\n cols.Sort(&InterColourComparer);\r\n\r\n this->texSize = this->texSizeSlot.Param<param::IntParam>()->Value();\r\n float *tex = new float[4 * this->texSize];\r\n int p1, p2;\r\n\r\n cx2 = cols[0];\r\n p2 = 0;\r\n for (SIZE_T i = 1; i < cols.Count(); i++) {\r\n cx1 = cx2;\r\n p1 = p2;\r\n cx2 = cols[i];\r\n ASSERT(cx2[4] <= 1.0f + vislib::math::FLOAT_EPSILON);\r\n p2 = static_cast<int>(cx2[4] * static_cast<float>(this->texSize - 1));\r\n ASSERT(p2 < static_cast<int>(this->texSize));\r\n ASSERT(p2 >= p1);\r\n\r\n for (int p = p1; p <= p2; p++) {\r\n float al = static_cast<float>(p - p1) \/ static_cast<float>(p2 - p1);\r\n float be = 1.0f - al;\r\n\r\n tex[p * 4] = cx1[0] * be + cx2[0] * al;\r\n tex[p * 4 + 1] = cx1[1] * be + cx2[1] * al;\r\n tex[p * 4 + 2] = cx1[2] * be + cx2[2] * al;\r\n tex[p * 4 + 3] = cx1[3] * be + cx2[3] * al;\r\n }\r\n }\r\n\r\n GLint otid = 0;\r\n glGetIntegerv(GL_TEXTURE_BINDING_1D, &otid);\r\n glBindTexture(GL_TEXTURE_1D, this->texID);\r\n\r\n glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, this->texSize, 0, GL_RGBA, GL_FLOAT, tex);\r\n\r\n delete[] tex;\r\n\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);\r\n\r\n glBindTexture(GL_TEXTURE_1D, otid);\r\n\r\n if (!t1de) glDisable(GL_TEXTURE_1D);\r\n\r\n this->texFormat = validAlpha\r\n ? CallGetTransferFunction::TEXTURE_FORMAT_RGBA\r\n : CallGetTransferFunction::TEXTURE_FORMAT_RGB;\r\n\r\n }\r\n\r\n cgtf->SetTexture(this->texID, this->texSize, this->texFormat);\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n* view::LinearTransferFunction::storeTFPressed\r\n*\/\r\nbool view::LinearTransferFunction::storeTFPressed(param::ParamSlot& param) {\r\n\r\n try {\r\n vislib::sys::BufferedFile outFile;\r\n if (!outFile.Open(pathSlot.Param<param::FilePathParam>()->Value(),\r\n vislib::sys::File::AccessMode::WRITE_ONLY,\r\n vislib::sys::File::ShareMode::SHARE_EXCLUSIVE,\r\n vislib::sys::File::CreationMode::CREATE_OVERWRITE)) {\r\n vislib::sys::Log::DefaultLog.WriteMsg(\r\n vislib::sys::Log::LEVEL_WARN,\r\n \"Unable to create TF file.\");\r\n }\r\n\r\n Module::child_list_type::iterator ano_end = this->ChildList_End();\r\n for (Module::child_list_type::iterator ano_i = this->ChildList_Begin(); ano_i != ano_end; ++ano_i) {\r\n std::shared_ptr<param::ParamSlot> p = std::dynamic_pointer_cast<param::ParamSlot>(*ano_i);\r\n if (p && !p->Name().Equals(\"filepath\")) {\r\n writeParameterFileParameter(*p, outFile);\r\n }\r\n }\r\n outFile.Close();\r\n } catch (...) {\r\n\r\n }\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n* view::LinearTransferFunction::writeParameterFileParameter\r\n*\/\r\nvoid view::LinearTransferFunction::writeParameterFileParameter(\r\n param::ParamSlot& param,\r\n vislib::sys::BufferedFile &outFile) {\r\n\r\n unsigned int len = 0;\r\n vislib::RawStorage store;\r\n param.Parameter()->Definition(store);\r\n\r\n if (::memcmp(store, \"MMBUTN\", 6) == 0) {\r\n outFile.Write(\"# \", 2);\r\n }\r\n\r\n vislib::sys::WriteFormattedLineToFile(outFile,\r\n \"%s=%s\\n\", param.Name().PeekBuffer(), vislib::StringA(param.Parameter()->ValueString()).PeekBuffer());\r\n}\r\n<commit_msg>Arg. Forgot to reset a flag<commit_after>\/*\r\n * LinearTransferFunction.cpp\r\n *\r\n * Copyright (C) 2008 by Universitaet Stuttgart (VIS). \r\n * Alle Rechte vorbehalten.\r\n *\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"vislib\/graphics\/gl\/IncludeAllGL.h\"\r\n#include \"mmcore\/view\/LinearTransferFunction.h\"\r\n#ifdef _WIN32\r\n#include <windows.h>\r\n#endif\r\n#include \"mmcore\/param\/BoolParam.h\"\r\n#include \"mmcore\/param\/FloatParam.h\"\r\n#include \"mmcore\/param\/IntParam.h\"\r\n#include \"mmcore\/param\/StringParam.h\"\r\n#include \"mmcore\/param\/FilePathParam.h\"\r\n#include \"mmcore\/param\/ButtonParam.h\"\r\n#include \"mmcore\/utility\/ColourParser.h\"\r\n#include \"vislib\/Array.h\"\r\n#include \"vislib\/assert.h\"\r\n#include \"vislib\/math\/Vector.h\"\r\n#include \"vislib\/sys\/sysfunctions.h\"\r\n#include \"vislib\/sys\/Log.h\"\r\n\r\n\r\nnamespace megamol {\r\nnamespace core {\r\nnamespace view {\r\n\r\n static int InterColourComparer(const vislib::math::Vector<float, 5>& lhs, \r\n const vislib::math::Vector<float, 5>& rhs) {\r\n if (lhs[4] >= rhs[4]) {\r\n if (rhs[4] + vislib::math::FLOAT_EPSILON >= lhs[4]) {\r\n return 0;\r\n } else {\r\n return 1;\r\n }\r\n } else {\r\n if (lhs[4] + vislib::math::FLOAT_EPSILON >= rhs[4]) {\r\n return 0;\r\n } else {\r\n return -1;\r\n }\r\n }\r\n }\r\n\r\n} \/* end namespace view *\/\r\n} \/* end namespace core *\/\r\n} \/* end namespace megamol *\/\r\n\r\n\r\nusing namespace megamol::core;\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::LinearTransferFunction\r\n *\/\r\nview::LinearTransferFunction::LinearTransferFunction(void) : Module(),\r\n getTFSlot(\"gettransferfunction\", \"Provides the transfer function\"),\r\n minColSlot(\"mincolour\", \"The colour for the minimum value\"),\r\n maxColSlot(\"maxcolour\", \"The colour for the maximum value\"),\r\n texSizeSlot(\"texsize\", \"The size of the texture to generate\"),\r\n pathSlot(\"filepath\", \"path for serializing the TF\"),\r\n loadTFSlot(\"loadTF\", \"trigger loading from file\"),\r\n storeTFSlot(\"storeTF\", \"trigger saving to file\"),\r\n texID(0), texSize(1),\r\n texFormat(CallGetTransferFunction::TEXTURE_FORMAT_RGB),\r\n firstRequest(true) {\r\n\r\n view::CallGetTransferFunctionDescription cgtfd;\r\n this->getTFSlot.SetCallback(cgtfd.ClassName(), cgtfd.FunctionName(0),\r\n &LinearTransferFunction::requestTF);\r\n this->MakeSlotAvailable(&this->getTFSlot);\r\n\r\n this->minColSlot << new param::StringParam(\"blue\");\r\n this->MakeSlotAvailable(&this->minColSlot);\r\n\r\n vislib::StringA t1, t2;\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n t1.Format(\"enable%.2d\", i + 1);\r\n t2.Format(\"Enables the intermediate colour %d\", i + 1);\r\n this->interCols[i].enableSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].enableSlot->SetParameter(new param::BoolParam(false));\r\n this->MakeSlotAvailable(this->interCols[i].enableSlot);\r\n\r\n t1.Format(\"colour%.2d\", i + 1);\r\n t2.Format(\"The colour for the intermediate value no. %d\", i + 1);\r\n this->interCols[i].colSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].colSlot->SetParameter(new param::StringParam(\"Gray\"));\r\n this->MakeSlotAvailable(this->interCols[i].colSlot);\r\n\r\n t1.Format(\"value%.2d\", i + 1);\r\n t2.Format(\"The intermediate value no. %d\", i + 1);\r\n this->interCols[i].valSlot = new param::ParamSlot(t1, t2);\r\n this->interCols[i].valSlot->SetParameter(new param::FloatParam(\r\n static_cast<float>(i + 1) \/ static_cast<float>(INTER_COLOUR_COUNT + 1),\r\n 0.0f, 1.0f));\r\n this->MakeSlotAvailable(this->interCols[i].valSlot);\r\n }\r\n\r\n this->maxColSlot << new param::StringParam(\"red\");\r\n this->MakeSlotAvailable(&this->maxColSlot);\r\n this->maxColSlot.ForceSetDirty();\r\n\r\n this->texSizeSlot << new param::IntParam(128, 2, 1024);\r\n this->MakeSlotAvailable(&this->texSizeSlot);\r\n\r\n this->pathSlot << new param::FilePathParam(\"\");\r\n this->MakeSlotAvailable(&this->pathSlot);\r\n\r\n this->loadTFSlot << new param::ButtonParam();\r\n this->loadTFSlot.SetUpdateCallback(&LinearTransferFunction::loadTFPressed);\r\n this->MakeSlotAvailable(&this->loadTFSlot);\r\n\r\n this->storeTFSlot << new param::ButtonParam();\r\n this->storeTFSlot.SetUpdateCallback(&LinearTransferFunction::storeTFPressed);\r\n this->MakeSlotAvailable(&this->storeTFSlot);\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::~LinearTransferFunction\r\n *\/\r\nview::LinearTransferFunction::~LinearTransferFunction(void) {\r\n this->Release();\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::create\r\n *\/\r\nbool view::LinearTransferFunction::create(void) {\r\n firstRequest = true;\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::release\r\n *\/\r\nvoid view::LinearTransferFunction::release(void) {\r\n ::glDeleteTextures(1, &this->texID);\r\n this->texID = 0;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::loadTFPressed\r\n *\/\r\nbool view::LinearTransferFunction::loadTFPressed(param::ParamSlot& param) {\r\n try {\r\n vislib::sys::BufferedFile inFile;\r\n if (!inFile.Open(pathSlot.Param<param::FilePathParam>()->Value(),\r\n vislib::sys::File::AccessMode::READ_ONLY,\r\n vislib::sys::File::ShareMode::SHARE_READ,\r\n vislib::sys::File::CreationMode::OPEN_ONLY)) {\r\n vislib::sys::Log::DefaultLog.WriteMsg(\r\n vislib::sys::Log::LEVEL_WARN,\r\n \"Unable to open TF file.\");\r\n \/\/ failed, but does not matter here\r\n return true;\r\n }\r\n\r\n while (!inFile.IsEOF()) {\r\n vislib::StringA line = vislib::sys::ReadLineFromFileA(inFile);\r\n line.TrimSpaces();\r\n if (line.IsEmpty()) continue;\r\n if (line[0] == '#') continue;\r\n vislib::StringA::Size pos = line.Find('=');\r\n vislib::StringA name = line.Substring(0, pos);\r\n vislib::StringA value = line.Substring(pos + 1);\r\n Module::child_list_type::iterator ano_end = this->ChildList_End();\r\n for (Module::child_list_type::iterator ano_i = this->ChildList_Begin(); ano_i != ano_end; ++ano_i) {\r\n std::shared_ptr<param::ParamSlot> p = std::dynamic_pointer_cast<param::ParamSlot>(*ano_i);\r\n if (p && p->Name().Equals(name)) {\r\n p->Parameter()->ParseValue(value);\r\n }\r\n }\r\n }\r\n inFile.Close();\r\n } catch (...) {\r\n\r\n }\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n * view::LinearTransferFunction::requestTF\r\n *\/\r\nbool view::LinearTransferFunction::requestTF(Call& call) {\r\n view::CallGetTransferFunction *cgtf = dynamic_cast<view::CallGetTransferFunction*>(&call);\r\n if (cgtf == NULL) return false;\r\n\r\n if (firstRequest) {\r\n loadTFPressed(loadTFSlot);\r\n firstRequest = false;\r\n }\r\n\r\n bool dirty = this->minColSlot.IsDirty() || this->maxColSlot.IsDirty() || this->texSizeSlot.IsDirty();\r\n for (SIZE_T i = 0; !dirty && (i < INTER_COLOUR_COUNT); i++) {\r\n dirty = this->interCols[i].enableSlot->IsDirty()\r\n || this->interCols[i].colSlot->IsDirty()\r\n || this->interCols[i].valSlot->IsDirty();\r\n }\r\n if ((this->texID == 0) || dirty) {\r\n this->minColSlot.ResetDirty();\r\n this->maxColSlot.ResetDirty();\r\n this->texSizeSlot.ResetDirty();\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n this->interCols[i].enableSlot->ResetDirty();\r\n this->interCols[i].colSlot->ResetDirty();\r\n this->interCols[i].valSlot->ResetDirty();\r\n }\r\n\r\n bool t1de = (glIsEnabled(GL_TEXTURE_1D) == GL_TRUE);\r\n if (!t1de) glEnable(GL_TEXTURE_1D);\r\n if (this->texID == 0) glGenTextures(1, &this->texID);\r\n\r\n vislib::Array<vislib::math::Vector<float, 5> > cols;\r\n vislib::math::Vector<float, 5> cx1, cx2;\r\n bool validAlpha = false;\r\n if (utility::ColourParser::FromString(\r\n this->minColSlot.Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = 0.0f;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = 0.0f;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n if (utility::ColourParser::FromString(\r\n this->maxColSlot.Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = 1.0f;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = 1.0f;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n for (SIZE_T i = 0; i < INTER_COLOUR_COUNT; i++) {\r\n if (this->interCols[i].enableSlot->Param<param::BoolParam>()->Value()) {\r\n float val = this->interCols[i].valSlot->Param<param::FloatParam>()->Value();\r\n if (utility::ColourParser::FromString(\r\n this->interCols[i].colSlot->Param<param::StringParam>()->Value(),\r\n cx1[0], cx1[1], cx1[2], cx1[3])) {\r\n cx1[4] = val;\r\n } else {\r\n cx1[0] = cx1[1] = cx1[2] = cx1[3] = 0.0f;\r\n cx1[4] = val;\r\n }\r\n if (cx1[3] < 0.99f) validAlpha = true;\r\n cols.Add(cx1);\r\n }\r\n }\r\n\r\n cols.Sort(&InterColourComparer);\r\n\r\n this->texSize = this->texSizeSlot.Param<param::IntParam>()->Value();\r\n float *tex = new float[4 * this->texSize];\r\n int p1, p2;\r\n\r\n cx2 = cols[0];\r\n p2 = 0;\r\n for (SIZE_T i = 1; i < cols.Count(); i++) {\r\n cx1 = cx2;\r\n p1 = p2;\r\n cx2 = cols[i];\r\n ASSERT(cx2[4] <= 1.0f + vislib::math::FLOAT_EPSILON);\r\n p2 = static_cast<int>(cx2[4] * static_cast<float>(this->texSize - 1));\r\n ASSERT(p2 < static_cast<int>(this->texSize));\r\n ASSERT(p2 >= p1);\r\n\r\n for (int p = p1; p <= p2; p++) {\r\n float al = static_cast<float>(p - p1) \/ static_cast<float>(p2 - p1);\r\n float be = 1.0f - al;\r\n\r\n tex[p * 4] = cx1[0] * be + cx2[0] * al;\r\n tex[p * 4 + 1] = cx1[1] * be + cx2[1] * al;\r\n tex[p * 4 + 2] = cx1[2] * be + cx2[2] * al;\r\n tex[p * 4 + 3] = cx1[3] * be + cx2[3] * al;\r\n }\r\n }\r\n\r\n GLint otid = 0;\r\n glGetIntegerv(GL_TEXTURE_BINDING_1D, &otid);\r\n glBindTexture(GL_TEXTURE_1D, this->texID);\r\n\r\n glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, this->texSize, 0, GL_RGBA, GL_FLOAT, tex);\r\n\r\n delete[] tex;\r\n\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);\r\n\r\n glBindTexture(GL_TEXTURE_1D, otid);\r\n\r\n if (!t1de) glDisable(GL_TEXTURE_1D);\r\n\r\n this->texFormat = validAlpha\r\n ? CallGetTransferFunction::TEXTURE_FORMAT_RGBA\r\n : CallGetTransferFunction::TEXTURE_FORMAT_RGB;\r\n\r\n }\r\n\r\n cgtf->SetTexture(this->texID, this->texSize, this->texFormat);\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n* view::LinearTransferFunction::storeTFPressed\r\n*\/\r\nbool view::LinearTransferFunction::storeTFPressed(param::ParamSlot& param) {\r\n\r\n try {\r\n vislib::sys::BufferedFile outFile;\r\n if (!outFile.Open(pathSlot.Param<param::FilePathParam>()->Value(),\r\n vislib::sys::File::AccessMode::WRITE_ONLY,\r\n vislib::sys::File::ShareMode::SHARE_EXCLUSIVE,\r\n vislib::sys::File::CreationMode::CREATE_OVERWRITE)) {\r\n vislib::sys::Log::DefaultLog.WriteMsg(\r\n vislib::sys::Log::LEVEL_WARN,\r\n \"Unable to create TF file.\");\r\n }\r\n\r\n Module::child_list_type::iterator ano_end = this->ChildList_End();\r\n for (Module::child_list_type::iterator ano_i = this->ChildList_Begin(); ano_i != ano_end; ++ano_i) {\r\n std::shared_ptr<param::ParamSlot> p = std::dynamic_pointer_cast<param::ParamSlot>(*ano_i);\r\n if (p && !p->Name().Equals(\"filepath\")) {\r\n writeParameterFileParameter(*p, outFile);\r\n }\r\n }\r\n outFile.Close();\r\n } catch (...) {\r\n\r\n }\r\n\r\n return true;\r\n}\r\n\r\n\r\n\/*\r\n* view::LinearTransferFunction::writeParameterFileParameter\r\n*\/\r\nvoid view::LinearTransferFunction::writeParameterFileParameter(\r\n param::ParamSlot& param,\r\n vislib::sys::BufferedFile &outFile) {\r\n\r\n unsigned int len = 0;\r\n vislib::RawStorage store;\r\n param.Parameter()->Definition(store);\r\n\r\n if (::memcmp(store, \"MMBUTN\", 6) == 0) {\r\n outFile.Write(\"# \", 2);\r\n }\r\n\r\n vislib::sys::WriteFormattedLineToFile(outFile,\r\n \"%s=%s\\n\", param.Name().PeekBuffer(), vislib::StringA(param.Parameter()->ValueString()).PeekBuffer());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2008 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"colcopy.h\"\n\n#include \"akonadiconnection.h\"\n#include \"handlerhelper.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/transaction.h\"\n#include \"storage\/itemretriever.h\"\n#include \"imapstreamparser.h\"\n\nusing namespace Akonadi;\n\nbool ColCopy::copyCollection(const Collection & source, const Collection & target)\n{\n \/\/ copy the source collection\n Collection col = source;\n col.setParentId( target.id() );\n col.setResourceId( target.resourceId() );\n \/\/ clear remote id and revision on inter-resource copies\n if ( source.resourceId() != target.resourceId() ) {\n col.setRemoteId( QString() );\n col.setRemoteRevision( QString() );\n }\n\n DataStore *db = connection()->storageBackend();\n if ( !db->appendCollection( col ) )\n return false;\n\n foreach ( const MimeType &mt, source.mimeTypes() ) {\n if ( !col.addMimeType( mt ) )\n return false;\n }\n\n foreach ( const CollectionAttribute &attr, source.attributes() ) {\n CollectionAttribute newAttr = attr;\n newAttr.setId( -1 );\n newAttr.setCollectionId( col.id() );\n if ( !newAttr.insert() )\n return false;\n }\n\n \/\/ copy sub-collections\n foreach ( const Collection &child, source.children() ) {\n if ( !copyCollection( child, col ) )\n return false;\n }\n\n \/\/ copy items\n foreach ( const PimItem &item, source.items() ) {\n if ( !copyItem( item, col ) )\n return false;\n }\n\n return true;\n}\n\nbool ColCopy::parseStream()\n{\n QByteArray tmp = m_streamParser->readString();\n const Collection source = HandlerHelper::collectionFromIdOrName( tmp );\n if ( !source.isValid() )\n return failureResponse( \"No valid source specified\" );\n\n tmp = m_streamParser->readString();\n const Collection target = HandlerHelper::collectionFromIdOrName( tmp );\n if ( !target.isValid() )\n return failureResponse( \"No valid target specified\" );\n\n \/\/ retrieve all not yet cached items of the source\n ItemRetriever retriever( connection() );\n retriever.setCollection( source, true );\n retriever.setRetrieveFullPayload( true );\n retriever.exec();\n\n DataStore *store = connection()->storageBackend();\n Transaction transaction( store );\n\n if ( !copyCollection( source, target ) )\n return failureResponse( \"Failed to copy collection\" );\n\n if ( !transaction.commit() )\n return failureResponse( \"Cannot commit transaction.\" );\n\n return successResponse( \"COLCOPY complete\" );\n}\n\n\n#include \"colcopy.moc\"\n<commit_msg>Don't crash when copying a folder into itself.<commit_after>\/*\n Copyright (c) 2008 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"colcopy.h\"\n\n#include \"akonadiconnection.h\"\n#include \"handlerhelper.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/transaction.h\"\n#include \"storage\/itemretriever.h\"\n#include \"storage\/collectionqueryhelper.h\"\n#include \"imapstreamparser.h\"\n\nusing namespace Akonadi;\n\nbool ColCopy::copyCollection(const Collection & source, const Collection & target)\n{\n if ( !CollectionQueryHelper::canBeMovedTo( source, target ) ) {\n \/\/ We don't accept source==target, or source being an ancestor of target.\n return false;\n }\n\n \/\/ copy the source collection\n Collection col = source;\n col.setParentId( target.id() );\n col.setResourceId( target.resourceId() );\n \/\/ clear remote id and revision on inter-resource copies\n if ( source.resourceId() != target.resourceId() ) {\n col.setRemoteId( QString() );\n col.setRemoteRevision( QString() );\n }\n\n DataStore *db = connection()->storageBackend();\n if ( !db->appendCollection( col ) )\n return false;\n\n foreach ( const MimeType &mt, source.mimeTypes() ) {\n if ( !col.addMimeType( mt ) )\n return false;\n }\n\n foreach ( const CollectionAttribute &attr, source.attributes() ) {\n CollectionAttribute newAttr = attr;\n newAttr.setId( -1 );\n newAttr.setCollectionId( col.id() );\n if ( !newAttr.insert() )\n return false;\n }\n\n \/\/ copy sub-collections\n foreach ( const Collection &child, source.children() ) {\n if ( !copyCollection( child, col ) )\n return false;\n }\n\n \/\/ copy items\n foreach ( const PimItem &item, source.items() ) {\n if ( !copyItem( item, col ) )\n return false;\n }\n\n return true;\n}\n\nbool ColCopy::parseStream()\n{\n QByteArray tmp = m_streamParser->readString();\n const Collection source = HandlerHelper::collectionFromIdOrName( tmp );\n if ( !source.isValid() )\n return failureResponse( \"No valid source specified\" );\n\n tmp = m_streamParser->readString();\n const Collection target = HandlerHelper::collectionFromIdOrName( tmp );\n if ( !target.isValid() )\n return failureResponse( \"No valid target specified\" );\n\n \/\/ retrieve all not yet cached items of the source\n ItemRetriever retriever( connection() );\n retriever.setCollection( source, true );\n retriever.setRetrieveFullPayload( true );\n retriever.exec();\n\n DataStore *store = connection()->storageBackend();\n Transaction transaction( store );\n\n if ( !copyCollection( source, target ) )\n return failureResponse( \"Failed to copy collection\" );\n\n if ( !transaction.commit() )\n return failureResponse( \"Cannot commit transaction.\" );\n\n return successResponse( \"COLCOPY complete\" );\n}\n\n\n#include \"colcopy.moc\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add solution of prob 1<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\n#define EMPTY 0\n#define BLOCK 1\n#define VISITED 2\n\nstruct board\n{\n int size;\n int x, y;\n int **board;\n};\n\nstruct board game;\nint x, y;\n\nvoid make_board(const char *filename)\n{\n FILE *fp = fopen(filename, \"r\");\n fscanf(fp, \"%d %d %d %d %d\", &game.size, &x, &y, &game.x, &game.y);\n game.board = (int **)malloc(sizeof(int *) * game.size);\n\n for(int row = 0; row < game.size; row++)\n {\n game.board[row] = (int *)malloc(sizeof(int) * game.size);\n for(int col = 0; col < game.size; col++)\n {\n int in;\n fscanf(fp, \"%d\", &in);\n game.board[row][col] = ((in == 0) ? EMPTY : BLOCK);\n }\n }\n}\n\nvoid free_board(void)\n{\n for(int row = 0; row < game.size; row++)\n free(game.board[row]);\n free(game.board);\n}\n\nbool is_empty(const int x, const int y, const bool flag = false)\n{\n if(x < 0 || x >= game.size || y < 0 || y >= game.size) return false;\n if(game.board[x][y] == EMPTY || flag && game.board[x][y] == VISITED) return true;\n return false;\n}\n\nbool is_horse_able_to_move(const int x, const int y)\n{\n \/* base case *\/\n if(x == game.x && y == game.y) return true;\n if(! is_empty(x, y)) return false;\n\n \/* recursive case *\/\n game.board[x][y] = VISITED;\n if(is_empty(x - 1, y , true) && (is_horse_able_to_move(x - 2, y - 1) || is_horse_able_to_move(x - 2, y + 1))) return true;\n if(is_empty(x , y + 1, true) && (is_horse_able_to_move(x - 1, y + 2) || is_horse_able_to_move(x + 1, y + 2))) return true;\n if(is_empty(x + 1, y , true) && (is_horse_able_to_move(x + 2, y + 1) || is_horse_able_to_move(x + 2, y - 1))) return true;\n if(is_empty(x , y - 1, true) && (is_horse_able_to_move(x + 1, y - 2) || is_horse_able_to_move(x - 1, y - 2))) return true;\n\n return false;\n}\n\nint main(void)\n{\n make_board(\"resources\/01input.txt\");\n printf(\"%d\\n\", is_horse_able_to_move(0, 0));\n free_board();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\n#define DIR_SE 3\n#define DIR_S 4\n#define DIR_SW 5\n\nbool is_able_to_set(const int x, const int y, const int dir = -1);\nint count_n_queens(const int x, const int y);\n\nint n;\nint *board;\n\nint main(void)\n{\n for(n = 1; n <= 15; n++)\n {\n board = (int *)malloc(sizeof(int) * n);\n memset(board, 0, sizeof(int) * n);\n\n printf(\"N(%d) Result=%d\\n\", n, count_n_queens(n, n));\n free(board);\n }\n\n return 0;\n}\n\nbool is_able_to_set(const int x, const int y, const int dir)\n{\n \/* base case *\/\n if(x < 1 || x > n || y < 1 || y > n) return true;\n if(board[x - 1] == y) return false; \/* queen is exist *\/\n\n \/* recursive case *\/\n switch(dir)\n {\n case DIR_SE: return is_able_to_set(x + 1, y + 1, DIR_SE);\n case DIR_S : return is_able_to_set(x + 1, y , DIR_S );\n case DIR_SW: return is_able_to_set(x + 1, y - 1, DIR_SW);\n default: \/* re-call with a direction *\/\n if(\n is_able_to_set(x, y, DIR_SE) &&\n is_able_to_set(x, y, DIR_S ) &&\n is_able_to_set(x, y, DIR_SW)\n ) return true;\n return false;\n }\n}\n\nint b_add(const int x, const int y)\n{\n board[x - 1] = y; \/* 0 MEANS EMPTY *\/\n return 0;\n}\n\nint b_rm(const int x)\n{\n board[x - 1] = 0; \/* 0 MEANS EMPTY *\/\n return 0;\n}\n\nint count_n_queens(const int x, const int y)\n{\n \/* base case *\/\n if(y < 1) return 0;\n\n \/* recursive case *\/\n if(is_able_to_set(x, y))\n {\n if(x - 1 >= 1) return count_n_queens(x, y - 1) + b_add(x, y) + count_n_queens(x - 1, ::n) + b_rm(x);\n if(is_able_to_set(x - 1, ::n)) return count_n_queens(x, y - 1) + 1;\n }\n return count_n_queens(x, y - 1);\n}\n<commit_msg>Add some comments<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\n#define DIR_SE 3\n#define DIR_S 4\n#define DIR_SW 5\n\nbool is_able_to_set(const int x, const int y, const int dir = -1);\nint count_n_queens(const int x, const int y);\n\nint n;\nint *board; \/* 0 MEANS EMPTY *\/\n\nint main(void)\n{\n for(n = 1; n <= 15; n++)\n {\n board = (int *)malloc(sizeof(int) * n);\n memset(board, 0, sizeof(int) * n); \/* 0 MEANS EMPTY *\/\n\n printf(\"N(%d) Result=%d\\n\", n, count_n_queens(n, n));\n free(board);\n }\n\n return 0;\n}\n\nbool is_able_to_set(const int x, const int y, const int dir)\n{\n \/* base case *\/\n if(x < 1 || x > n || y < 1 || y > n) return true;\n if(board[x - 1] == y) return false; \/* queen is exist *\/\n\n \/* recursive case *\/\n switch(dir)\n {\n case DIR_SE: return is_able_to_set(x + 1, y + 1, DIR_SE);\n case DIR_S : return is_able_to_set(x + 1, y , DIR_S );\n case DIR_SW: return is_able_to_set(x + 1, y - 1, DIR_SW);\n default: \/* re-call with a direction *\/\n if(\n is_able_to_set(x, y, DIR_SE) &&\n is_able_to_set(x, y, DIR_S ) &&\n is_able_to_set(x, y, DIR_SW)\n ) return true;\n return false;\n }\n}\n\nint b_add(const int x, const int y)\n{\n board[x - 1] = y; \/* 0 MEANS EMPTY *\/\n return 0;\n}\n\nint b_rm(const int x)\n{\n board[x - 1] = 0; \/* 0 MEANS EMPTY *\/\n return 0;\n}\n\nint count_n_queens(const int x, const int y)\n{\n \/* base case *\/\n if(y < 1) return 0;\n\n \/* recursive case *\/\n if(is_able_to_set(x, y))\n {\n if(x - 1 >= 1) return count_n_queens(x, y - 1) + b_add(x, y) + count_n_queens(x - 1, ::n) + b_rm(x);\n if(is_able_to_set(x - 1, ::n)) return count_n_queens(x, y - 1) + 1;\n }\n return count_n_queens(x, y - 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"MediaSinkImpl.hpp\"\n#include \"MediaSourceImpl.hpp\"\n\n#define GST_CAT_DEFAULT kurento_media_sink_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaSinkImpl\"\n\nnamespace kurento\n{\n\nMediaSinkImpl::MediaSinkImpl (std::shared_ptr< MediaType > mediaType,\n const std::string &mediaDescription,\n std::shared_ptr< MediaObjectImpl > parent) :\n MediaPadImpl (mediaType, mediaDescription, parent)\n{\n}\n\nMediaSinkImpl::~MediaSinkImpl()\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if (connectedSrcLocked != NULL) {\n disconnect (connectedSrcLocked);\n }\n}\n\nvoid\nMediaSinkImpl::disconnect (std::shared_ptr<MediaSource> mediaSource)\n{\n std::shared_ptr<MediaSourceImpl> mediaSourceImpl;\n\n mediaSourceImpl = std::dynamic_pointer_cast<MediaSourceImpl> (mediaSource);\n\n mediaSourceImpl->disconnect (this);\n}\n\nstd::string\nMediaSinkImpl::getPadName ()\n{\n if (getMediaType()->getValue() == MediaType::AUDIO) {\n return \"audio_sink\";\n } else {\n return \"video_sink\";\n }\n}\n\nstatic void\nremove_from_parent (GstElement *element)\n{\n GstBin *parent = GST_BIN (GST_OBJECT_PARENT (element) );\n\n if (parent == NULL) {\n return;\n }\n\n gst_object_ref (element);\n gst_bin_remove (parent, element);\n gst_element_set_state (element, GST_STATE_NULL);\n\n gst_object_unref (element);\n}\n\nstatic void\nsink_unlinked (GstPad *pad, GstPad *peer, GstElement *filter)\n{\n GstPad *src;\n GstPad *src_peer;\n\n src = gst_element_get_static_pad (filter, \"src\");\n src_peer = gst_pad_get_peer (src);\n\n if (src_peer != NULL) {\n gst_pad_unlink (src, src_peer);\n gst_object_unref (src_peer);\n } else {\n remove_from_parent (filter);\n }\n\n gst_object_unref (src);\n}\n\nstatic void\nsrc_unlinked (GstPad *pad, GstPad *peer, GstElement *filter)\n{\n GstPad *sink;\n GstPad *sink_peer;\n\n sink = gst_element_get_static_pad (filter, \"sink\");\n sink_peer = gst_pad_get_peer (sink);\n\n if (sink_peer != NULL) {\n gst_pad_unlink (sink_peer, sink);\n gst_object_unref (sink_peer);\n } else {\n remove_from_parent (filter);\n }\n\n gst_object_unref (sink);\n}\n\nbool\nMediaSinkImpl::linkPad (std::shared_ptr<MediaSourceImpl> mediaSrc, GstPad *src)\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n GstPad *sink;\n bool ret = false;\n\n mutex.lock();\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if ( (sink = gst_element_get_static_pad (getGstreamerElement(),\n getPadName().c_str() ) ) == NULL) {\n sink = gst_element_get_request_pad (getGstreamerElement(),\n getPadName().c_str() );\n }\n\n if (gst_pad_is_linked (sink) ) {\n unlink (connectedSrcLocked, sink);\n }\n\n if (std::dynamic_pointer_cast<MediaObjectImpl> (mediaSrc)->getParent() ==\n getParent() ) {\n GstBin *container;\n GstElement *filter, *parent;\n GstPad *aux_sink, *aux_src;\n\n GST_DEBUG (\"Connecting loopback, adding a capsfilter to allow connection\");\n parent = GST_ELEMENT (GST_OBJECT_PARENT (sink) );\n\n if (parent == NULL) {\n goto end;\n }\n\n container = GST_BIN (GST_OBJECT_PARENT (parent) );\n\n if (container == NULL) {\n goto end;\n }\n\n filter = gst_element_factory_make (\"capsfilter\", NULL);\n\n aux_sink = gst_element_get_static_pad (filter, \"sink\");\n aux_src = gst_element_get_static_pad (filter, \"src\");\n\n g_signal_connect (G_OBJECT (aux_sink), \"unlinked\", G_CALLBACK (sink_unlinked),\n filter );\n g_signal_connect (G_OBJECT (aux_src), \"unlinked\", G_CALLBACK (src_unlinked),\n filter );\n\n gst_bin_add (container, filter);\n gst_element_sync_state_with_parent (filter);\n\n if (gst_pad_link (aux_src, sink) == GST_PAD_LINK_OK) {\n if (gst_pad_link (src, aux_sink) == GST_PAD_LINK_OK) {\n ret = true;\n } else {\n gst_pad_unlink (aux_src, sink);\n }\n\n }\n\n g_object_unref (aux_sink);\n g_object_unref (aux_src);\n\n gst_debug_bin_to_dot_file_with_ts (GST_BIN (container),\n GST_DEBUG_GRAPH_SHOW_ALL, \"loopback\");\n\n } else {\n if (gst_pad_link (src, sink) == GST_PAD_LINK_OK) {\n ret = true;\n }\n }\n\n if (ret == true) {\n connectedSrc = std::weak_ptr<MediaSourceImpl> (mediaSrc);\n } else {\n gst_element_release_request_pad (getGstreamerElement(), sink);\n }\n\nend:\n\n g_object_unref (sink);\n\n mutex.unlock();\n\n return ret;\n}\n\nvoid\nMediaSinkImpl::unlink (std::shared_ptr<MediaSourceImpl> mediaSrc, GstPad *sink)\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n mutex.lock();\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if (connectedSrcLocked != NULL && mediaSrc == connectedSrcLocked) {\n unlinkUnchecked (sink);\n connectedSrcLocked->removeSink (this);\n }\n\n mutex.unlock();\n}\n\nvoid\nMediaSinkImpl::unlinkUnchecked (GstPad *sink)\n{\n GstPad *peer;\n GstPad *sinkPad;\n\n if (sink == NULL) {\n sinkPad = gst_element_get_static_pad (getGstreamerElement(),\n getPadName().c_str() );\n } else {\n sinkPad = sink;\n }\n\n if (sinkPad == NULL) {\n return;\n }\n\n peer = gst_pad_get_peer (sinkPad);\n\n if (peer != NULL) {\n gst_pad_unlink (peer, sinkPad);\n\n g_object_unref (peer);\n }\n\n if (sink == NULL) {\n GstElement *elem;\n\n elem = gst_pad_get_parent_element (sinkPad);\n gst_element_release_request_pad (elem, sinkPad);\n g_object_unref (elem);\n g_object_unref (sinkPad);\n }\n}\n\nstd::shared_ptr<MediaSource>\nMediaSinkImpl::getConnectedSrc ()\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n return std::dynamic_pointer_cast<MediaSource> (connectedSrcLocked);\n}\n\nMediaSinkImpl::StaticConstructor MediaSinkImpl::staticConstructor;\n\nMediaSinkImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n\n<commit_msg>MediaSinkImpl: block peer pad before unlinking<commit_after>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"MediaSinkImpl.hpp\"\n#include \"MediaSourceImpl.hpp\"\n\n#define GST_CAT_DEFAULT kurento_media_sink_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaSinkImpl\"\n\nnamespace kurento\n{\n\nMediaSinkImpl::MediaSinkImpl (std::shared_ptr< MediaType > mediaType,\n const std::string &mediaDescription,\n std::shared_ptr< MediaObjectImpl > parent) :\n MediaPadImpl (mediaType, mediaDescription, parent)\n{\n}\n\nMediaSinkImpl::~MediaSinkImpl()\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if (connectedSrcLocked != NULL) {\n disconnect (connectedSrcLocked);\n }\n}\n\nvoid\nMediaSinkImpl::disconnect (std::shared_ptr<MediaSource> mediaSource)\n{\n std::shared_ptr<MediaSourceImpl> mediaSourceImpl;\n\n mediaSourceImpl = std::dynamic_pointer_cast<MediaSourceImpl> (mediaSource);\n\n mediaSourceImpl->disconnect (this);\n}\n\nstd::string\nMediaSinkImpl::getPadName ()\n{\n if (getMediaType()->getValue() == MediaType::AUDIO) {\n return \"audio_sink\";\n } else {\n return \"video_sink\";\n }\n}\n\nstatic void\nremove_from_parent (GstElement *element)\n{\n GstBin *parent = GST_BIN (GST_OBJECT_PARENT (element) );\n\n if (parent == NULL) {\n return;\n }\n\n gst_object_ref (element);\n gst_bin_remove (parent, element);\n gst_element_set_state (element, GST_STATE_NULL);\n\n gst_object_unref (element);\n}\n\nstatic void\nsink_unlinked (GstPad *pad, GstPad *peer, GstElement *filter)\n{\n GstPad *src;\n GstPad *src_peer;\n\n src = gst_element_get_static_pad (filter, \"src\");\n src_peer = gst_pad_get_peer (src);\n\n if (src_peer != NULL) {\n gst_pad_unlink (src, src_peer);\n gst_object_unref (src_peer);\n } else {\n remove_from_parent (filter);\n }\n\n gst_object_unref (src);\n}\n\nstatic void\nsrc_unlinked (GstPad *pad, GstPad *peer, GstElement *filter)\n{\n GstPad *sink;\n GstPad *sink_peer;\n\n sink = gst_element_get_static_pad (filter, \"sink\");\n sink_peer = gst_pad_get_peer (sink);\n\n if (sink_peer != NULL) {\n gst_pad_unlink (sink_peer, sink);\n gst_object_unref (sink_peer);\n } else {\n remove_from_parent (filter);\n }\n\n gst_object_unref (sink);\n}\n\nbool\nMediaSinkImpl::linkPad (std::shared_ptr<MediaSourceImpl> mediaSrc, GstPad *src)\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n GstPad *sink;\n bool ret = false;\n\n mutex.lock();\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if ( (sink = gst_element_get_static_pad (getGstreamerElement(),\n getPadName().c_str() ) ) == NULL) {\n sink = gst_element_get_request_pad (getGstreamerElement(),\n getPadName().c_str() );\n }\n\n if (gst_pad_is_linked (sink) ) {\n unlink (connectedSrcLocked, sink);\n }\n\n if (std::dynamic_pointer_cast<MediaObjectImpl> (mediaSrc)->getParent() ==\n getParent() ) {\n GstBin *container;\n GstElement *filter, *parent;\n GstPad *aux_sink, *aux_src;\n\n GST_DEBUG (\"Connecting loopback, adding a capsfilter to allow connection\");\n parent = GST_ELEMENT (GST_OBJECT_PARENT (sink) );\n\n if (parent == NULL) {\n goto end;\n }\n\n container = GST_BIN (GST_OBJECT_PARENT (parent) );\n\n if (container == NULL) {\n goto end;\n }\n\n filter = gst_element_factory_make (\"capsfilter\", NULL);\n\n aux_sink = gst_element_get_static_pad (filter, \"sink\");\n aux_src = gst_element_get_static_pad (filter, \"src\");\n\n g_signal_connect (G_OBJECT (aux_sink), \"unlinked\", G_CALLBACK (sink_unlinked),\n filter );\n g_signal_connect (G_OBJECT (aux_src), \"unlinked\", G_CALLBACK (src_unlinked),\n filter );\n\n gst_bin_add (container, filter);\n gst_element_sync_state_with_parent (filter);\n\n if (gst_pad_link (aux_src, sink) == GST_PAD_LINK_OK) {\n if (gst_pad_link (src, aux_sink) == GST_PAD_LINK_OK) {\n ret = true;\n } else {\n gst_pad_unlink (aux_src, sink);\n }\n\n }\n\n g_object_unref (aux_sink);\n g_object_unref (aux_src);\n\n gst_debug_bin_to_dot_file_with_ts (GST_BIN (container),\n GST_DEBUG_GRAPH_SHOW_ALL, \"loopback\");\n\n } else {\n if (gst_pad_link (src, sink) == GST_PAD_LINK_OK) {\n ret = true;\n }\n }\n\n if (ret == true) {\n connectedSrc = std::weak_ptr<MediaSourceImpl> (mediaSrc);\n } else {\n gst_element_release_request_pad (getGstreamerElement(), sink);\n }\n\nend:\n\n g_object_unref (sink);\n\n mutex.unlock();\n\n return ret;\n}\n\nvoid\nMediaSinkImpl::unlink (std::shared_ptr<MediaSourceImpl> mediaSrc, GstPad *sink)\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n mutex.lock();\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n if (connectedSrcLocked != NULL && mediaSrc == connectedSrcLocked) {\n unlinkUnchecked (sink);\n connectedSrcLocked->removeSink (this);\n }\n\n mutex.unlock();\n}\n\nstatic GstPadProbeReturn\npad_blocked_adaptor (GstPad *pad, GstPadProbeInfo *info, gpointer data)\n{\n auto handler =\n reinterpret_cast < std::function < void (GstPad * pad,\n GstPadProbeInfo * info) > * > (data);\n\n (*handler) (pad, info);\n\n \/* Drop everithing so as to avoid broken pipe errors on an unlinked pad *\/\n return GST_PAD_PROBE_DROP;\n}\n\nvoid\nMediaSinkImpl::unlinkUnchecked (GstPad *sink)\n{\n GstPad *peer;\n GstPad *sinkPad;\n\n if (sink == NULL) {\n sinkPad = gst_element_get_static_pad (getGstreamerElement(),\n getPadName().c_str() );\n } else {\n sinkPad = sink;\n }\n\n if (sinkPad == NULL) {\n return;\n }\n\n peer = gst_pad_get_peer (sinkPad);\n\n if (peer != NULL) {\n Glib::Cond cond;\n Glib::Mutex cmutex;\n bool blocked = FALSE;\n std::function <void (GstPad *pad, GstPadProbeInfo *info) >\n blockedLambda = [&] (GstPad * pad, GstPadProbeInfo * info) {\n GST_DEBUG (\"Peer pad blocked %\" GST_PTR_FORMAT, pad);\n\n cmutex.lock ();\n\n if (!blocked) {\n gst_pad_unlink (pad, sinkPad);\n }\n\n blocked = TRUE;\n cond.signal();\n cmutex.unlock ();\n };\n\n gst_pad_add_probe (peer, (GstPadProbeType) (GST_PAD_PROBE_TYPE_IDLE |\n GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM), pad_blocked_adaptor, &blockedLambda,\n NULL);\n\n cmutex.lock ();\n\n while (!blocked) {\n cond.wait (cmutex);\n }\n\n cmutex.unlock ();\n\n g_object_unref (peer);\n }\n\n if (sink == NULL) {\n GstElement *elem;\n\n elem = gst_pad_get_parent_element (sinkPad);\n gst_element_release_request_pad (elem, sinkPad);\n g_object_unref (elem);\n g_object_unref (sinkPad);\n }\n}\n\nstd::shared_ptr<MediaSource>\nMediaSinkImpl::getConnectedSrc ()\n{\n std::shared_ptr<MediaSourceImpl> connectedSrcLocked;\n\n try {\n connectedSrcLocked = connectedSrc.lock();\n } catch (const std::bad_weak_ptr &e) {\n }\n\n return std::dynamic_pointer_cast<MediaSource> (connectedSrcLocked);\n}\n\nMediaSinkImpl::StaticConstructor MediaSinkImpl::staticConstructor;\n\nMediaSinkImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributemap.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-11-02 14:02:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/canvastools.hxx>\n\n#include \"attributemap.hxx\"\n#include \"tools.hxx\"\n\n\nnamespace presentation\n{\n namespace internal\n {\n typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;\n\n AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )\n {\n \/** Maps attribute name to AttributeType enum.\n\n String entries are all case-insensitive and MUST\n BE STORED lowercase.\n\n String entries MUST BE SORTED in ascending order!\n *\/\n static AnimateAttributeMap::MapEntry lcl_attributeMap[] =\n {\n { \"charcolor\", ATTRIBUTE_CHAR_COLOR },\n\n { \"charfontname\", ATTRIBUTE_CHAR_FONT_NAME },\n\n { \"charheight\", ATTRIBUTE_CHAR_HEIGHT },\n\n { \"charposture\", ATTRIBUTE_CHAR_POSTURE },\n\n \/\/ TODO(Q1): This should prolly be changed in PPT import\n \/\/ { \"charrotation\", ATTRIBUTE_CHAR_ROTATION },\n { \"charrotation\", ATTRIBUTE_ROTATE },\n\n { \"charunderline\", ATTRIBUTE_CHAR_UNDERLINE },\n\n { \"charweight\", ATTRIBUTE_CHAR_WEIGHT },\n\n { \"color\", ATTRIBUTE_COLOR },\n\n { \"dimcolor\", ATTRIBUTE_DIMCOLOR },\n\n { \"fillcolor\", ATTRIBUTE_FILL_COLOR },\n\n { \"fillstyle\", ATTRIBUTE_FILL_STYLE },\n\n { \"height\", ATTRIBUTE_HEIGHT },\n\n { \"linecolor\", ATTRIBUTE_LINE_COLOR },\n\n { \"linestyle\", ATTRIBUTE_LINE_STYLE },\n\n { \"opacity\", ATTRIBUTE_OPACITY },\n\n { \"rotate\", ATTRIBUTE_ROTATE },\n\n { \"skewx\", ATTRIBUTE_SKEW_X },\n\n { \"skewy\", ATTRIBUTE_SKEW_Y },\n\n { \"visibility\", ATTRIBUTE_VISIBILITY },\n\n { \"width\", ATTRIBUTE_WIDTH },\n\n { \"x\", ATTRIBUTE_POS_X },\n\n { \"y\", ATTRIBUTE_POS_Y }\n };\n\n static AnimateAttributeMap aMap( lcl_attributeMap,\n sizeof(lcl_attributeMap)\/sizeof(AnimateAttributeMap::MapEntry),\n false );\n\n AttributeType eAttributeType;\n\n \/\/ determine the type from the attribute name\n if( !aMap.lookup( rAttrName,\n eAttributeType ) )\n {\n OSL_TRACE( \"mapAttributeName(): attribute name %s not found in map.\",\n ::rtl::OUStringToOString( rAttrName,\n RTL_TEXTENCODING_ASCII_US ).getStr() );\n return ATTRIBUTE_INVALID;\n }\n\n return eAttributeType;\n }\n\n }\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.4.42); FILE MERGED 2006\/09\/01 17:39:28 kaib 1.4.42.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: attributemap.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 08:23:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/canvastools.hxx>\n\n#include \"attributemap.hxx\"\n#include \"tools.hxx\"\n\n\nnamespace presentation\n{\n namespace internal\n {\n typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;\n\n AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )\n {\n \/** Maps attribute name to AttributeType enum.\n\n String entries are all case-insensitive and MUST\n BE STORED lowercase.\n\n String entries MUST BE SORTED in ascending order!\n *\/\n static AnimateAttributeMap::MapEntry lcl_attributeMap[] =\n {\n { \"charcolor\", ATTRIBUTE_CHAR_COLOR },\n\n { \"charfontname\", ATTRIBUTE_CHAR_FONT_NAME },\n\n { \"charheight\", ATTRIBUTE_CHAR_HEIGHT },\n\n { \"charposture\", ATTRIBUTE_CHAR_POSTURE },\n\n \/\/ TODO(Q1): This should prolly be changed in PPT import\n \/\/ { \"charrotation\", ATTRIBUTE_CHAR_ROTATION },\n { \"charrotation\", ATTRIBUTE_ROTATE },\n\n { \"charunderline\", ATTRIBUTE_CHAR_UNDERLINE },\n\n { \"charweight\", ATTRIBUTE_CHAR_WEIGHT },\n\n { \"color\", ATTRIBUTE_COLOR },\n\n { \"dimcolor\", ATTRIBUTE_DIMCOLOR },\n\n { \"fillcolor\", ATTRIBUTE_FILL_COLOR },\n\n { \"fillstyle\", ATTRIBUTE_FILL_STYLE },\n\n { \"height\", ATTRIBUTE_HEIGHT },\n\n { \"linecolor\", ATTRIBUTE_LINE_COLOR },\n\n { \"linestyle\", ATTRIBUTE_LINE_STYLE },\n\n { \"opacity\", ATTRIBUTE_OPACITY },\n\n { \"rotate\", ATTRIBUTE_ROTATE },\n\n { \"skewx\", ATTRIBUTE_SKEW_X },\n\n { \"skewy\", ATTRIBUTE_SKEW_Y },\n\n { \"visibility\", ATTRIBUTE_VISIBILITY },\n\n { \"width\", ATTRIBUTE_WIDTH },\n\n { \"x\", ATTRIBUTE_POS_X },\n\n { \"y\", ATTRIBUTE_POS_Y }\n };\n\n static AnimateAttributeMap aMap( lcl_attributeMap,\n sizeof(lcl_attributeMap)\/sizeof(AnimateAttributeMap::MapEntry),\n false );\n\n AttributeType eAttributeType;\n\n \/\/ determine the type from the attribute name\n if( !aMap.lookup( rAttrName,\n eAttributeType ) )\n {\n OSL_TRACE( \"mapAttributeName(): attribute name %s not found in map.\",\n ::rtl::OUStringToOString( rAttrName,\n RTL_TEXTENCODING_ASCII_US ).getStr() );\n return ATTRIBUTE_INVALID;\n }\n\n return eAttributeType;\n }\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/find_bar_win.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n fprintf(stderr, \"Starting FindMovesOnTabClose_Issue1343052\\n\");\n TestServer server(L\"chrome\/test\/data\");\n\n fprintf(stderr, \"TestServerPageW\\n\");\n GURL url = server.TestServerPageW(kFramePage);\n fprintf(stderr, \"GetActiveTab A\\n\");\n scoped_ptr<TabProxy> tabA(GetActiveTab());\n fprintf(stderr, \"Navigate A\\n\");\n ASSERT_TRUE(tabA->NavigateToURL(url));\n fprintf(stderr, \"WaitUntilTabCount(1) for A\\n\");\n WaitUntilTabCount(1);\n\n fprintf(stderr, \"GetBrowserWindow(0)\\n\");\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n fprintf(stderr, \"ApplyAccelerator bookmark bar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkVisibility\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n fprintf(stderr, \"OpenFindInPage in A\\n\");\n EXPECT_TRUE(tabA->OpenFindInPage());\n fprintf(stderr, \"WaitForWindowFullyVisible in A\\n\");\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n fprintf(stderr, \"AppendTab B\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab B\\n\");\n scoped_ptr<TabProxy> tabB(GetActiveTab());\n\n \/\/ Close tab B.\n fprintf(stderr, \"Tab Close B\\n\");\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n fprintf(stderr, \"ApplyAccelerator BookmarksBar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkBarVisibilityChange\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n fprintf(stderr, \"GetFindWindowLocation again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n fprintf(stderr, \"Append tab C\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab C\\n\");\n scoped_ptr<TabProxy> tabC(GetActiveTab());\n\n \/\/ Close it.\n fprintf(stderr, \"Close tab C\\n\");\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n fprintf(stderr, \"GetFindWindowLocation yet again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n fprintf(stderr, \"Done!\\n\");\n}\n<commit_msg>Fix include path from last checkin. Review URL: http:\/\/codereview.chromium.org\/7815<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/views\/find_bar_win.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n fprintf(stderr, \"Starting FindMovesOnTabClose_Issue1343052\\n\");\n TestServer server(L\"chrome\/test\/data\");\n\n fprintf(stderr, \"TestServerPageW\\n\");\n GURL url = server.TestServerPageW(kFramePage);\n fprintf(stderr, \"GetActiveTab A\\n\");\n scoped_ptr<TabProxy> tabA(GetActiveTab());\n fprintf(stderr, \"Navigate A\\n\");\n ASSERT_TRUE(tabA->NavigateToURL(url));\n fprintf(stderr, \"WaitUntilTabCount(1) for A\\n\");\n WaitUntilTabCount(1);\n\n fprintf(stderr, \"GetBrowserWindow(0)\\n\");\n scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n fprintf(stderr, \"ApplyAccelerator bookmark bar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkVisibility\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n fprintf(stderr, \"OpenFindInPage in A\\n\");\n EXPECT_TRUE(tabA->OpenFindInPage());\n fprintf(stderr, \"WaitForWindowFullyVisible in A\\n\");\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n fprintf(stderr, \"AppendTab B\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab B\\n\");\n scoped_ptr<TabProxy> tabB(GetActiveTab());\n\n \/\/ Close tab B.\n fprintf(stderr, \"Tab Close B\\n\");\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n fprintf(stderr, \"ApplyAccelerator BookmarksBar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkBarVisibilityChange\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n fprintf(stderr, \"GetFindWindowLocation again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n fprintf(stderr, \"Append tab C\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab C\\n\");\n scoped_ptr<TabProxy> tabC(GetActiveTab());\n\n \/\/ Close it.\n fprintf(stderr, \"Close tab C\\n\");\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n fprintf(stderr, \"GetFindWindowLocation yet again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n fprintf(stderr, \"Done!\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\toscarclientstream.cpp - Kopete Oscar Protocol\n\t\n\tCopyright (c) 2004 Matt Rogers <mattr@kde.org>\n\t\n\tBased on code Copyright (c) 2004 SuSE Linux AG <http:\/\/www.suse.com>\n\tBased on Iris, Copyright (C) 2003 Justin Karneges\n\t\n\tKopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>\n\t\n\t*************************************************************************\n\t* *\n\t* This library is free software; you can redistribute it and\/or *\n\t* modify it under the terms of the GNU Lesser General Public *\n\t* License as published by the Free Software Foundation; either *\n\t* version 2 of the License, or (at your option) any later version. *\n\t* *\n\t*************************************************************************\n*\/\n\n#include \"oscarclientstream.h\"\n\n#include <qguardedptr.h> \n#include <qobject.h>\n#include <qptrqueue.h>\n#include <qtimer.h>\n\n#include <kdebug.h>\n\n#include \"bytestream.h\"\n#include \"connection.h\"\n#include \"connector.h\"\n#include \"coreprotocol.h\"\n#include \"rateclassmanager.h\"\n#include \"transfer.h\"\n\n#define LIBOSCAR_DEBUG 0\n\nvoid cs_dump( const QByteArray &bytes );\n\nenum {\n\tIdle,\n\tConnecting,\n\tActive,\n\tClosing\n};\n\nenum {\n\tClientMode,\n\tServerMode\n};\n\nclass ClientStream::Private\n{\npublic:\n\tPrivate()\n\t{\n\t\tconn = 0;\n\t\tbs = 0;\n\t\tconnection = 0;\n\t\t\n\t\tusername = QString::null;\n\t\tpassword = QString::null;\n\t\tserver = QString::null;\n\t\thaveLocalAddr = false;\n\t\tdoBinding = true;\n\n\t\treset();\n\t}\n\tvoid reset()\n\t{\n\t\tstate = Idle;\n\t\tnotify = 0;\n\t\tnewTransfers = false;\n\t}\n\t\n\tQString username;\n\tQString password;\n\tQString server;\n\tbool doAuth; \/\/send the initial login sequences to get the cookie\n\tbool haveLocalAddr;\n\tQHostAddress localAddr;\n\tQ_UINT16 localPort;\n\tbool doBinding;\n\n\tConnector *conn;\n\tByteStream *bs;\n\tCoreProtocol client;\n\tConnection* connection;\n\n\tQString defRealm;\n\n\tint mode;\n\tint state;\n\tint notify;\n\tbool newTransfers;\n\t\n\tint errCond;\n\tQString errText;\n\n\tQPtrQueue<Transfer> in;\n\n\tQTimer noopTimer; \/\/ used to send icq keepalive\n\tint noop_time;\n};\n\nClientStream::ClientStream(Connector *conn, QObject *parent)\n:Stream(parent)\n{\n\t\/\/qDebug(\"CLIENTSTREAM::ClientStream\");\n\n\td = new Private;\n\td->mode = ClientMode;\n\td->conn = conn;\n\tconnect( d->conn, SIGNAL(connected()), SLOT(cr_connected()) );\n\tconnect( d->conn, SIGNAL(error()), SLOT(cr_error()) );\n\tconnect( &d->client, SIGNAL( outgoingData( const QByteArray& ) ), SLOT ( cp_outgoingData( const QByteArray & ) ) );\n\tconnect( &d->client, SIGNAL( incomingData() ), SLOT ( cp_incomingData() ) );\n\n\td->noop_time = 0;\n\tconnect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop()));\n}\n\nClientStream::~ClientStream()\n{\n\treset();\n\tdelete d;\n}\n\nvoid ClientStream::reset(bool all)\n{\n\td->reset();\n\td->noopTimer.stop();\n\n\t\/\/ client\n\tif(d->mode == ClientMode)\n\t{\n\t\t\/\/ reset connector\n\t\tif ( d->bs )\n\t\t{\n\t\t\td->bs->close();\n\t\t\td->bs = 0;\n\t\t}\n\t\tif ( d->conn )\n\t\t\td->conn->done();\n\n\t\t\/\/ reset state machine\n\t\td->client.reset();\n\t}\n\tif(all)\n\t\td->in.clear();\n}\n\nvoid ClientStream::connectToServer(const QString& server, bool auth)\n{\n\treset(true);\n\td->state = Connecting;\n\td->doAuth = auth;\n\td->server = server;\n\n\td->conn->connectToServer( d->server );\n}\n\nvoid ClientStream::continueAfterWarning()\n{\n\/* unneeded?\n\tif(d->state == WaitVersion) {\n\t\td->state = Connecting;\n\t\tprocessNext();\n\t}\n\telse if(d->state == WaitTLS) {\n\t\td->state = Connecting;\n\t\tprocessNext();\n\t}\n*\/\n}\n\nvoid ClientStream::accept()\n{\n\n}\n\nbool ClientStream::isActive() const\n{\n\treturn (d->state != Idle);\n}\n\nbool ClientStream::isAuthenticated() const\n{\n\treturn (d->state == Active);\n}\n\nvoid ClientStream::setNoopTime(int mills)\n{\n\td->noop_time = mills;\n\n\tif(d->noop_time == 0) {\n\t\td->noopTimer.stop();\n\t\treturn;\n\t}\n\t\n\tif( d->state != Active )\n\t\treturn;\n\t\n\td->noopTimer.start( d->noop_time );\n}\n\nvoid ClientStream::setLocalAddr(const QHostAddress &addr, Q_UINT16 port)\n{\n\td->haveLocalAddr = true;\n\td->localAddr = addr;\n\td->localPort = port;\n}\n\nint ClientStream::errorCondition() const\n{\n\treturn d->errCond;\n}\n\nQString ClientStream::errorText() const\n{\n\treturn d->errText;\n}\n\nvoid ClientStream::close()\n{\n\tif(d->state == Active) {\n\t\td->state = Closing;\n\/\/\t\td->client.shutdown();\n\t\tprocessNext();\n\t}\n\telse if(d->state != Idle && d->state != Closing) {\n\t\treset();\n\t}\n}\n\nvoid ClientStream::setConnection( Connection *c )\n{\n\td->connection = c;\n}\n\nConnection* ClientStream::connection() const\n{\n\treturn d->connection;\n}\n\n\nbool ClientStream::transfersAvailable() const\n{\n\treturn ( !d->in.isEmpty() );\n}\n\nTransfer* ClientStream::read()\n{\n\tif(d->in.isEmpty())\n\t\treturn 0; \/\/first from queue...\n\telse \n\t\treturn d->in.dequeue();\n}\n\nvoid ClientStream::write( Transfer *request )\n{\n\td->client.outgoingTransfer( request );\n}\n\t\nvoid cs_dump( const QByteArray &bytes )\n{\n#if 0\n\tqDebug( \"contains: %i bytes \", bytes.count() );\n\tuint count = 0;\n\twhile ( count < bytes.count() )\n\t{\n\t\tint dword = 0;\n\t\tfor ( int i = 0; i < 8; ++i )\n\t\t{\n\t\t\tif ( count + i < bytes.count() )\n\t\t\t\tprintf( \"%02x \", bytes[ count + i ] );\n\t\t\telse\n\t\t\t\tprintf( \" \" );\n\t\t\tif ( i == 3 )\n\t\t\t\tprintf( \" \" );\n\t\t}\n\t\tprintf(\" | \");\n\t\tdword = 0;\n\t\tfor ( int i = 0; i < 8; ++i )\n\t\t{\n\t\t\tif ( count + i < bytes.count() )\n\t\t\t{\n\t\t\t\tint j = bytes [ count + i ];\n\t\t\t\tif ( j >= 0x20 && j <= 0x7e ) \n\t\t\t\t\tprintf( \"%2c \", j );\n\t\t\t\telse\n\t\t\t\t\tprintf( \"%2c \", '.' );\n\t\t\t}\n\t\t\telse\n\t\t\t\tprintf( \" \" );\n\t\t\tif ( i == 3 )\n\t\t\t\tprintf( \" \" );\n\t\t}\n\t\tprintf( \"\\n\" );\n\t\tcount += 8;\n\t}\n\tprintf( \"\\n\" );\n#endif\n\tQ_UNUSED( bytes );\n}\n\nvoid ClientStream::cp_outgoingData( const QByteArray& outgoingBytes )\n{\n\t\/\/ take formatted bytes from CoreProtocol and put them on the wire\n\td->bs->write( outgoingBytes );\n}\n\nvoid ClientStream::cp_incomingData()\n{\n\tTransfer * incoming = d->client.incomingTransfer();\n\tif ( incoming )\n\t{\n\t\td->in.enqueue( incoming );\n\t\td->newTransfers = true;\n\t\tdoReadyRead();\n\t}\n\telse\n\t\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << \n\t\t\t\"client signalled incomingData but none was available, state is: \" <<\n\t\t\td->client.state() << endl;\n}\n\nvoid ClientStream::cr_connected()\n{\n\td->bs = d->conn->stream();\n\tconnect(d->bs, SIGNAL(connectionClosed()), SLOT(bs_connectionClosed()));\n\tconnect(d->bs, SIGNAL(delayedCloseFinished()), SLOT(bs_delayedCloseFinished()));\n\tconnect(d->bs, SIGNAL(readyRead()), SLOT(bs_readyRead()));\n\tconnect(d->bs, SIGNAL(bytesWritten(int)), SLOT(bs_bytesWritten(int)));\n\tconnect(d->bs, SIGNAL(error(int)), SLOT(bs_error(int)));\n\n\td->state = Active;\n\tif ( d->noop_time )\n\t\td->noopTimer.start( d->noop_time );\n\n\tQByteArray spare = d->bs->read();\n\n\tQGuardedPtr<QObject> self = this;\n\temit connected();\n\tif(!self)\n\t\treturn;\n}\n\nvoid ClientStream::cr_error()\n{\n\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << endl;\n\treset();\n\temit error(ErrConnection);\n}\n\nvoid ClientStream::bs_connectionClosed()\t\n{\n\treset();\n\temit connectionClosed();\n}\n\nvoid ClientStream::bs_delayedCloseFinished()\n{\n\t\/\/ we don't care about this (we track all important data ourself)\n}\n\nvoid ClientStream::bs_error(int)\n{\n\t\/\/ TODO\n}\n\nvoid ClientStream::bs_readyRead()\n{\n\tQByteArray a;\n\t\/\/qDebug( \"size of storage for incoming data is %i bytes.\", a.size() );\n\ta = d->bs->read();\n\n#ifdef LIBOSCAR_DEBUG\n\tQCString cs(a.data(), a.size()+1);\n\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << \"recv: \" << a.size() << \"bytes\" << endl;\n\tcs_dump( a );\n#endif\n\n\td->client.addIncomingData(a);\n}\n\nvoid ClientStream::bs_bytesWritten(int bytes)\n{\n#ifdef LIBOSCAR_DEBUG\n \tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << bytes << \" bytes written\" << endl;\n\tQ_UNUSED( bytes );\n#else\n\tQ_UNUSED( bytes );\n#endif\n}\n\nvoid ClientStream::srvProcessNext()\n{\n}\n\nvoid ClientStream::doReadyRead()\n{\n\temit readyRead();\n}\n\nvoid ClientStream::processNext()\n{\n\tif( !d->in.isEmpty() ) \n\t{\n\t\tQTimer::singleShot(0, this, SLOT(doReadyRead()));\n\t}\n}\n\nbool ClientStream::handleNeed()\n{\n\treturn false;\n}\n\nvoid ClientStream::doNoop()\n{\n\tif ( d->state != Active )\n\t\treturn;\n\t\n\tFLAP f = { 0x05, d->connection->flapSequence(), 0 };\n\tBuffer* b = new Buffer(); \/\/deleted in Transfer destructor\n\tTransfer* t = new FlapTransfer( f, b ); \/\/deleted after being sent\n\twrite( t );\n}\n\nvoid ClientStream::handleError()\n{\n}\n\n#include \"oscarclientstream.moc\"\n\n\/\/kate: tab-width 4; indent-mode csands;\n<commit_msg>less debug.<commit_after>\/*\n\toscarclientstream.cpp - Kopete Oscar Protocol\n\t\n\tCopyright (c) 2004 Matt Rogers <mattr@kde.org>\n\t\n\tBased on code Copyright (c) 2004 SuSE Linux AG <http:\/\/www.suse.com>\n\tBased on Iris, Copyright (C) 2003 Justin Karneges\n\t\n\tKopete (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>\n\t\n\t*************************************************************************\n\t* *\n\t* This library is free software; you can redistribute it and\/or *\n\t* modify it under the terms of the GNU Lesser General Public *\n\t* License as published by the Free Software Foundation; either *\n\t* version 2 of the License, or (at your option) any later version. *\n\t* *\n\t*************************************************************************\n*\/\n\n#include \"oscarclientstream.h\"\n\n#include <qguardedptr.h> \n#include <qobject.h>\n#include <qptrqueue.h>\n#include <qtimer.h>\n\n#include <kdebug.h>\n\n#include \"bytestream.h\"\n#include \"connection.h\"\n#include \"connector.h\"\n#include \"coreprotocol.h\"\n#include \"rateclassmanager.h\"\n#include \"transfer.h\"\n\n#define LIBOSCAR_DEBUG 0\n\nvoid cs_dump( const QByteArray &bytes );\n\nenum {\n\tIdle,\n\tConnecting,\n\tActive,\n\tClosing\n};\n\nenum {\n\tClientMode,\n\tServerMode\n};\n\nclass ClientStream::Private\n{\npublic:\n\tPrivate()\n\t{\n\t\tconn = 0;\n\t\tbs = 0;\n\t\tconnection = 0;\n\t\t\n\t\tusername = QString::null;\n\t\tpassword = QString::null;\n\t\tserver = QString::null;\n\t\thaveLocalAddr = false;\n\t\tdoBinding = true;\n\n\t\treset();\n\t}\n\tvoid reset()\n\t{\n\t\tstate = Idle;\n\t\tnotify = 0;\n\t\tnewTransfers = false;\n\t}\n\t\n\tQString username;\n\tQString password;\n\tQString server;\n\tbool doAuth; \/\/send the initial login sequences to get the cookie\n\tbool haveLocalAddr;\n\tQHostAddress localAddr;\n\tQ_UINT16 localPort;\n\tbool doBinding;\n\n\tConnector *conn;\n\tByteStream *bs;\n\tCoreProtocol client;\n\tConnection* connection;\n\n\tQString defRealm;\n\n\tint mode;\n\tint state;\n\tint notify;\n\tbool newTransfers;\n\t\n\tint errCond;\n\tQString errText;\n\n\tQPtrQueue<Transfer> in;\n\n\tQTimer noopTimer; \/\/ used to send icq keepalive\n\tint noop_time;\n};\n\nClientStream::ClientStream(Connector *conn, QObject *parent)\n:Stream(parent)\n{\n\t\/\/qDebug(\"CLIENTSTREAM::ClientStream\");\n\n\td = new Private;\n\td->mode = ClientMode;\n\td->conn = conn;\n\tconnect( d->conn, SIGNAL(connected()), SLOT(cr_connected()) );\n\tconnect( d->conn, SIGNAL(error()), SLOT(cr_error()) );\n\tconnect( &d->client, SIGNAL( outgoingData( const QByteArray& ) ), SLOT ( cp_outgoingData( const QByteArray & ) ) );\n\tconnect( &d->client, SIGNAL( incomingData() ), SLOT ( cp_incomingData() ) );\n\n\td->noop_time = 0;\n\tconnect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop()));\n}\n\nClientStream::~ClientStream()\n{\n\treset();\n\tdelete d;\n}\n\nvoid ClientStream::reset(bool all)\n{\n\td->reset();\n\td->noopTimer.stop();\n\n\t\/\/ client\n\tif(d->mode == ClientMode)\n\t{\n\t\t\/\/ reset connector\n\t\tif ( d->bs )\n\t\t{\n\t\t\td->bs->close();\n\t\t\td->bs = 0;\n\t\t}\n\t\tif ( d->conn )\n\t\t\td->conn->done();\n\n\t\t\/\/ reset state machine\n\t\td->client.reset();\n\t}\n\tif(all)\n\t\td->in.clear();\n}\n\nvoid ClientStream::connectToServer(const QString& server, bool auth)\n{\n\treset(true);\n\td->state = Connecting;\n\td->doAuth = auth;\n\td->server = server;\n\n\td->conn->connectToServer( d->server );\n}\n\nvoid ClientStream::continueAfterWarning()\n{\n\/* unneeded?\n\tif(d->state == WaitVersion) {\n\t\td->state = Connecting;\n\t\tprocessNext();\n\t}\n\telse if(d->state == WaitTLS) {\n\t\td->state = Connecting;\n\t\tprocessNext();\n\t}\n*\/\n}\n\nvoid ClientStream::accept()\n{\n\n}\n\nbool ClientStream::isActive() const\n{\n\treturn (d->state != Idle);\n}\n\nbool ClientStream::isAuthenticated() const\n{\n\treturn (d->state == Active);\n}\n\nvoid ClientStream::setNoopTime(int mills)\n{\n\td->noop_time = mills;\n\n\tif(d->noop_time == 0) {\n\t\td->noopTimer.stop();\n\t\treturn;\n\t}\n\t\n\tif( d->state != Active )\n\t\treturn;\n\t\n\td->noopTimer.start( d->noop_time );\n}\n\nvoid ClientStream::setLocalAddr(const QHostAddress &addr, Q_UINT16 port)\n{\n\td->haveLocalAddr = true;\n\td->localAddr = addr;\n\td->localPort = port;\n}\n\nint ClientStream::errorCondition() const\n{\n\treturn d->errCond;\n}\n\nQString ClientStream::errorText() const\n{\n\treturn d->errText;\n}\n\nvoid ClientStream::close()\n{\n\tif(d->state == Active) {\n\t\td->state = Closing;\n\/\/\t\td->client.shutdown();\n\t\tprocessNext();\n\t}\n\telse if(d->state != Idle && d->state != Closing) {\n\t\treset();\n\t}\n}\n\nvoid ClientStream::setConnection( Connection *c )\n{\n\td->connection = c;\n}\n\nConnection* ClientStream::connection() const\n{\n\treturn d->connection;\n}\n\n\nbool ClientStream::transfersAvailable() const\n{\n\treturn ( !d->in.isEmpty() );\n}\n\nTransfer* ClientStream::read()\n{\n\tif(d->in.isEmpty())\n\t\treturn 0; \/\/first from queue...\n\telse \n\t\treturn d->in.dequeue();\n}\n\nvoid ClientStream::write( Transfer *request )\n{\n\td->client.outgoingTransfer( request );\n}\n\t\nvoid cs_dump( const QByteArray &bytes )\n{\n#if 0\n\tqDebug( \"contains: %i bytes \", bytes.count() );\n\tuint count = 0;\n\twhile ( count < bytes.count() )\n\t{\n\t\tint dword = 0;\n\t\tfor ( int i = 0; i < 8; ++i )\n\t\t{\n\t\t\tif ( count + i < bytes.count() )\n\t\t\t\tprintf( \"%02x \", bytes[ count + i ] );\n\t\t\telse\n\t\t\t\tprintf( \" \" );\n\t\t\tif ( i == 3 )\n\t\t\t\tprintf( \" \" );\n\t\t}\n\t\tprintf(\" | \");\n\t\tdword = 0;\n\t\tfor ( int i = 0; i < 8; ++i )\n\t\t{\n\t\t\tif ( count + i < bytes.count() )\n\t\t\t{\n\t\t\t\tint j = bytes [ count + i ];\n\t\t\t\tif ( j >= 0x20 && j <= 0x7e ) \n\t\t\t\t\tprintf( \"%2c \", j );\n\t\t\t\telse\n\t\t\t\t\tprintf( \"%2c \", '.' );\n\t\t\t}\n\t\t\telse\n\t\t\t\tprintf( \" \" );\n\t\t\tif ( i == 3 )\n\t\t\t\tprintf( \" \" );\n\t\t}\n\t\tprintf( \"\\n\" );\n\t\tcount += 8;\n\t}\n\tprintf( \"\\n\" );\n#endif\n\tQ_UNUSED( bytes );\n}\n\nvoid ClientStream::cp_outgoingData( const QByteArray& outgoingBytes )\n{\n\t\/\/ take formatted bytes from CoreProtocol and put them on the wire\n\td->bs->write( outgoingBytes );\n}\n\nvoid ClientStream::cp_incomingData()\n{\n\tTransfer * incoming = d->client.incomingTransfer();\n\tif ( incoming )\n\t{\n\t\td->in.enqueue( incoming );\n\t\td->newTransfers = true;\n\t\tdoReadyRead();\n\t}\n\telse\n\t\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << \n\t\t\t\"client signalled incomingData but none was available, state is: \" <<\n\t\t\td->client.state() << endl;\n}\n\nvoid ClientStream::cr_connected()\n{\n\td->bs = d->conn->stream();\n\tconnect(d->bs, SIGNAL(connectionClosed()), SLOT(bs_connectionClosed()));\n\tconnect(d->bs, SIGNAL(delayedCloseFinished()), SLOT(bs_delayedCloseFinished()));\n\tconnect(d->bs, SIGNAL(readyRead()), SLOT(bs_readyRead()));\n\tconnect(d->bs, SIGNAL(bytesWritten(int)), SLOT(bs_bytesWritten(int)));\n\tconnect(d->bs, SIGNAL(error(int)), SLOT(bs_error(int)));\n\n\td->state = Active;\n\tif ( d->noop_time )\n\t\td->noopTimer.start( d->noop_time );\n\n\tQByteArray spare = d->bs->read();\n\n\tQGuardedPtr<QObject> self = this;\n\temit connected();\n\tif(!self)\n\t\treturn;\n}\n\nvoid ClientStream::cr_error()\n{\n\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << endl;\n\treset();\n\temit error(ErrConnection);\n}\n\nvoid ClientStream::bs_connectionClosed()\t\n{\n\treset();\n\temit connectionClosed();\n}\n\nvoid ClientStream::bs_delayedCloseFinished()\n{\n\t\/\/ we don't care about this (we track all important data ourself)\n}\n\nvoid ClientStream::bs_error(int)\n{\n\t\/\/ TODO\n}\n\nvoid ClientStream::bs_readyRead()\n{\n\tQByteArray a;\n\t\/\/qDebug( \"size of storage for incoming data is %i bytes.\", a.size() );\n\ta = d->bs->read();\n\n#if LIBOSCAR_DEBUG\n\tQCString cs(a.data(), a.size()+1);\n\tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << \"recv: \" << a.size() << \"bytes\" << endl;\n\tcs_dump( a );\n#endif\n\n\td->client.addIncomingData(a);\n}\n\nvoid ClientStream::bs_bytesWritten(int bytes)\n{\n#if LIBOSCAR_DEBUG\n \tkdDebug(OSCAR_RAW_DEBUG) << k_funcinfo << bytes << \" bytes written\" << endl;\n\tQ_UNUSED( bytes );\n#else\n\tQ_UNUSED( bytes );\n#endif\n}\n\nvoid ClientStream::srvProcessNext()\n{\n}\n\nvoid ClientStream::doReadyRead()\n{\n\temit readyRead();\n}\n\nvoid ClientStream::processNext()\n{\n\tif( !d->in.isEmpty() ) \n\t{\n\t\tQTimer::singleShot(0, this, SLOT(doReadyRead()));\n\t}\n}\n\nbool ClientStream::handleNeed()\n{\n\treturn false;\n}\n\nvoid ClientStream::doNoop()\n{\n\tif ( d->state != Active )\n\t\treturn;\n\t\n\tFLAP f = { 0x05, d->connection->flapSequence(), 0 };\n\tBuffer* b = new Buffer(); \/\/deleted in Transfer destructor\n\tTransfer* t = new FlapTransfer( f, b ); \/\/deleted after being sent\n\twrite( t );\n}\n\nvoid ClientStream::handleError()\n{\n}\n\n#include \"oscarclientstream.moc\"\n\n\/\/kate: tab-width 4; indent-mode csands;\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"chrome\/renderer\/media\/simple_data_source.h\"\n#include \"chrome\/renderer\/render_thread.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"webkit\/glue\/webappcachecontext.h\"\n\nSimpleDataSource::SimpleDataSource(int32 routing_id)\n : routing_id_(routing_id),\n render_loop_(RenderThread::current()->message_loop()),\n size_(0),\n position_(0) {\n}\n\nSimpleDataSource::~SimpleDataSource() {}\n\nvoid SimpleDataSource::Stop() {}\n\nbool SimpleDataSource::Initialize(const std::string& url) {\n SetURL(GURL(url));\n\n \/\/ Validate the URL.\n if (!url_.is_valid()) {\n return false;\n }\n\n \/\/ Create our bridge and post a task to start loading the resource.\n bridge_.reset(RenderThread::current()->resource_dispatcher()->CreateBridge(\n \"GET\",\n url_,\n url_,\n GURL::EmptyGURL(), \/\/ TODO(scherkus): provide referer here.\n \"null\", \/\/ TODO(abarth): provide frame_origin\n \"null\", \/\/ TODO(abarth): provide main_frame_origin\n \"\",\n net::LOAD_BYPASS_CACHE,\n base::GetCurrentProcId(),\n ResourceType::MEDIA,\n 0,\n \/\/ TODO(michaeln): delegate->mediaplayer->frame->\n \/\/ app_cache_context()->context_id()\n \/\/ For now don't service media resource requests from the appcache.\n WebAppCacheContext::kNoAppCacheContextId,\n routing_id_));\n render_loop_->PostTask(FROM_HERE,\n NewRunnableMethod(this, &SimpleDataSource::StartTask));\n return true;\n}\n\nconst media::MediaFormat& SimpleDataSource::media_format() {\n return media_format_;\n}\n\nsize_t SimpleDataSource::Read(uint8* data, size_t size) {\n size_t copied = std::min(size, static_cast<size_t>(size_ - position_));\n memcpy(data, data_.c_str() + position_, copied);\n position_ += copied;\n return copied;\n}\n\nbool SimpleDataSource::GetPosition(int64* position_out) {\n *position_out = position_;\n return true;\n}\n\nbool SimpleDataSource::SetPosition(int64 position) {\n if (position < 0 || position > size_)\n return false;\n position_ = position;\n return true;\n}\n\nbool SimpleDataSource::GetSize(int64* size_out) {\n *size_out = size_;\n return true;\n}\n\nbool SimpleDataSource::IsSeekable() {\n return true;\n}\n\nvoid SimpleDataSource::OnDownloadProgress(uint64 position, uint64 size) {}\n\nvoid SimpleDataSource::OnUploadProgress(uint64 position, uint64 size) {}\n\nvoid SimpleDataSource::OnReceivedRedirect(const GURL& new_url) {\n SetURL(new_url);\n}\n\nvoid SimpleDataSource::OnReceivedResponse(\n const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,\n bool content_filtered) {\n \/\/ This is a simple data source, so we assume 200 responses with the content\n \/\/ length provided.\n DCHECK(url_.SchemeIsFile() || info.headers->response_code() == 200);\n DCHECK(info.content_length != -1);\n size_ = info.content_length;\n}\n\nvoid SimpleDataSource::OnReceivedData(const char* data, int len) {\n data_.append(data, len);\n}\n\nvoid SimpleDataSource::OnCompletedRequest(const URLRequestStatus& status,\n const std::string& security_info) {\n DCHECK(size_ == data_.length());\n position_ = 0;\n bridge_.reset();\n host_->SetTotalBytes(size_);\n host_->SetBufferedBytes(size_);\n host_->InitializationComplete();\n}\n\nstd::string SimpleDataSource::GetURLForDebugging() {\n return url_.spec();\n}\n\nvoid SimpleDataSource::SetURL(const GURL& url) {\n url_ = url;\n media_format_.Clear();\n media_format_.SetAsString(media::MediaFormat::kMimeType,\n media::mime_type::kApplicationOctetStream);\n media_format_.SetAsString(media::MediaFormat::kURL, url.spec());\n}\n\nvoid SimpleDataSource::StartTask() {\n DCHECK(MessageLoop::current() == render_loop_);\n bridge_->Start(this);\n}\n<commit_msg>Shouldn't assume response code of 200 in SimpleDataSource SimpleDataSource assumes the scheme is file or http and the response code is 200. We should just check if the response is successful using response.is_success() and verify the content_length, which will be -1 in case of unspecified length.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n#include \"chrome\/renderer\/media\/simple_data_source.h\"\n#include \"chrome\/renderer\/render_thread.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"webkit\/glue\/webappcachecontext.h\"\n\nSimpleDataSource::SimpleDataSource(int32 routing_id)\n : routing_id_(routing_id),\n render_loop_(RenderThread::current()->message_loop()),\n size_(-1),\n position_(0) {\n}\n\nSimpleDataSource::~SimpleDataSource() {}\n\nvoid SimpleDataSource::Stop() {}\n\nbool SimpleDataSource::Initialize(const std::string& url) {\n SetURL(GURL(url));\n\n \/\/ Validate the URL.\n if (!url_.is_valid()) {\n return false;\n }\n\n \/\/ Create our bridge and post a task to start loading the resource.\n bridge_.reset(RenderThread::current()->resource_dispatcher()->CreateBridge(\n \"GET\",\n url_,\n url_,\n GURL::EmptyGURL(), \/\/ TODO(scherkus): provide referer here.\n \"null\", \/\/ TODO(abarth): provide frame_origin\n \"null\", \/\/ TODO(abarth): provide main_frame_origin\n \"\",\n net::LOAD_BYPASS_CACHE,\n base::GetCurrentProcId(),\n ResourceType::MEDIA,\n 0,\n \/\/ TODO(michaeln): delegate->mediaplayer->frame->\n \/\/ app_cache_context()->context_id()\n \/\/ For now don't service media resource requests from the appcache.\n WebAppCacheContext::kNoAppCacheContextId,\n routing_id_));\n render_loop_->PostTask(FROM_HERE,\n NewRunnableMethod(this, &SimpleDataSource::StartTask));\n return true;\n}\n\nconst media::MediaFormat& SimpleDataSource::media_format() {\n return media_format_;\n}\n\nsize_t SimpleDataSource::Read(uint8* data, size_t size) {\n DCHECK_GE(size_, 0);\n size_t copied = std::min(size, static_cast<size_t>(size_ - position_));\n memcpy(data, data_.c_str() + position_, copied);\n position_ += copied;\n return copied;\n}\n\nbool SimpleDataSource::GetPosition(int64* position_out) {\n *position_out = position_;\n return true;\n}\n\nbool SimpleDataSource::SetPosition(int64 position) {\n if (position < 0 || position > size_)\n return false;\n position_ = position;\n return true;\n}\n\nbool SimpleDataSource::GetSize(int64* size_out) {\n *size_out = size_;\n return true;\n}\n\nbool SimpleDataSource::IsSeekable() {\n return true;\n}\n\nvoid SimpleDataSource::OnDownloadProgress(uint64 position, uint64 size) {}\n\nvoid SimpleDataSource::OnUploadProgress(uint64 position, uint64 size) {}\n\nvoid SimpleDataSource::OnReceivedRedirect(const GURL& new_url) {\n SetURL(new_url);\n}\n\nvoid SimpleDataSource::OnReceivedResponse(\n const webkit_glue::ResourceLoaderBridge::ResponseInfo& info,\n bool content_filtered) {\n size_ = info.content_length;\n}\n\nvoid SimpleDataSource::OnReceivedData(const char* data, int len) {\n data_.append(data, len);\n}\n\nvoid SimpleDataSource::OnCompletedRequest(const URLRequestStatus& status,\n const std::string& security_info) {\n bridge_.reset();\n \/\/ If we don't get a content length or the request has failed, report it\n \/\/ as a network error.\n DCHECK(size_ == -1 || size_ == data_.length());\n if (size_ == -1)\n size_ = data_.length();\n if (!status.is_success()) {\n host_->Error(media::PIPELINE_ERROR_NETWORK);\n } else {\n host_->InitializationComplete();\n }\n host_->SetTotalBytes(size_);\n host_->SetBufferedBytes(size_);\n host_->InitializationComplete();\n}\n\nstd::string SimpleDataSource::GetURLForDebugging() {\n return url_.spec();\n}\n\nvoid SimpleDataSource::SetURL(const GURL& url) {\n url_ = url;\n media_format_.Clear();\n media_format_.SetAsString(media::MediaFormat::kMimeType,\n media::mime_type::kApplicationOctetStream);\n media_format_.SetAsString(media::MediaFormat::kURL, url.spec());\n}\n\nvoid SimpleDataSource::StartTask() {\n DCHECK(MessageLoop::current() == render_loop_);\n bridge_->Start(this);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/media\/rtc_video_capture_delegate.h\"\n\n#include \"base\/bind.h\"\n\nnamespace content {\n\nRtcVideoCaptureDelegate::RtcVideoCaptureDelegate(\n const media::VideoCaptureSessionId id,\n VideoCaptureImplManager* vc_manager)\n : session_id_(id),\n vc_manager_(vc_manager),\n capture_engine_(NULL),\n got_first_frame_(false),\n error_occured_(false) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::ctor\";\n capture_engine_ = vc_manager_->AddDevice(session_id_, this);\n}\n\nRtcVideoCaptureDelegate::~RtcVideoCaptureDelegate() {\n DVLOG(3) << \" RtcVideoCaptureDelegate::dtor\";\n vc_manager_->RemoveDevice(session_id_, this);\n}\n\nvoid RtcVideoCaptureDelegate::StartCapture(\n const media::VideoCaptureCapability& capability,\n const FrameCapturedCallback& captured_callback,\n const StateChangeCallback& state_callback) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::StartCapture \";\n message_loop_proxy_ = base::MessageLoopProxy::current();\n captured_callback_ = captured_callback;\n state_callback_ = state_callback;\n got_first_frame_ = false;\n error_occured_ = false;\n\n \/\/ Increase the reference count to ensure we are not deleted until\n \/\/ The we are unregistered in RtcVideoCaptureDelegate::OnRemoved.\n AddRef();\n capture_engine_->StartCapture(this, capability);\n}\n\nvoid RtcVideoCaptureDelegate::StopCapture() {\n \/\/ Immediately make sure we don't provide more frames.\n captured_callback_.Reset();\n state_callback_.Reset();\n capture_engine_->StopCapture(this);\n}\n\nvoid RtcVideoCaptureDelegate::OnStarted(media::VideoCapture* capture) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnStarted\";\n}\n\nvoid RtcVideoCaptureDelegate::OnStopped(media::VideoCapture* capture) {\n}\n\nvoid RtcVideoCaptureDelegate::OnPaused(media::VideoCapture* capture) {\n NOTIMPLEMENTED();\n}\n\nvoid RtcVideoCaptureDelegate::OnError(media::VideoCapture* capture,\n int error_code) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnError\";\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnErrorOnCaptureThread,\n this, capture));\n}\n\nvoid RtcVideoCaptureDelegate::OnRemoved(media::VideoCapture* capture) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnRemoved\";\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnRemovedOnCaptureThread,\n this, capture));\n\n \/\/ Balance the AddRef in StartCapture.\n \/\/ This means we are no longer registered as an event handler and can safely\n \/\/ be deleted.\n Release();\n}\n\nvoid RtcVideoCaptureDelegate::OnBufferReady(\n media::VideoCapture* capture,\n scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) {\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnBufferReadyOnCaptureThread,\n this, capture, buf));\n}\n\nvoid RtcVideoCaptureDelegate::OnDeviceInfoReceived(\n media::VideoCapture* capture,\n const media::VideoCaptureParams& device_info) {\n NOTIMPLEMENTED();\n}\n\nvoid RtcVideoCaptureDelegate::OnDeviceInfoChanged(\n media::VideoCapture* capture,\n const media::VideoCaptureParams& device_info) {\n NOTIMPLEMENTED();\n}\n\nvoid RtcVideoCaptureDelegate::OnBufferReadyOnCaptureThread(\n media::VideoCapture* capture,\n scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) {\n if (!captured_callback_.is_null()) {\n if (!got_first_frame_) {\n got_first_frame_ = true;\n if (!state_callback_.is_null())\n state_callback_.Run(CAPTURE_RUNNING);\n }\n\n captured_callback_.Run(*buf.get());\n }\n capture->FeedBuffer(buf);\n}\n\nvoid RtcVideoCaptureDelegate::OnErrorOnCaptureThread(\n media::VideoCapture* capture) {\n error_occured_ = true;\n if (!state_callback_.is_null())\n state_callback_.Run(CAPTURE_FAILED);\n}\n\n\nvoid RtcVideoCaptureDelegate::OnRemovedOnCaptureThread(\n media::VideoCapture* capture) {\n if (!error_occured_ && !state_callback_.is_null())\n state_callback_.Run(CAPTURE_STOPPED);\n}\n\n} \/\/ namespace content\n<commit_msg>Remove NOTIMPLEMENTED()s from RtcVideoCaptureDelegate.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/media\/rtc_video_capture_delegate.h\"\n\n#include \"base\/bind.h\"\n\nnamespace content {\n\nRtcVideoCaptureDelegate::RtcVideoCaptureDelegate(\n const media::VideoCaptureSessionId id,\n VideoCaptureImplManager* vc_manager)\n : session_id_(id),\n vc_manager_(vc_manager),\n capture_engine_(NULL),\n got_first_frame_(false),\n error_occured_(false) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::ctor\";\n capture_engine_ = vc_manager_->AddDevice(session_id_, this);\n}\n\nRtcVideoCaptureDelegate::~RtcVideoCaptureDelegate() {\n DVLOG(3) << \" RtcVideoCaptureDelegate::dtor\";\n vc_manager_->RemoveDevice(session_id_, this);\n}\n\nvoid RtcVideoCaptureDelegate::StartCapture(\n const media::VideoCaptureCapability& capability,\n const FrameCapturedCallback& captured_callback,\n const StateChangeCallback& state_callback) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::StartCapture \";\n message_loop_proxy_ = base::MessageLoopProxy::current();\n captured_callback_ = captured_callback;\n state_callback_ = state_callback;\n got_first_frame_ = false;\n error_occured_ = false;\n\n \/\/ Increase the reference count to ensure we are not deleted until\n \/\/ The we are unregistered in RtcVideoCaptureDelegate::OnRemoved.\n AddRef();\n capture_engine_->StartCapture(this, capability);\n}\n\nvoid RtcVideoCaptureDelegate::StopCapture() {\n \/\/ Immediately make sure we don't provide more frames.\n captured_callback_.Reset();\n state_callback_.Reset();\n capture_engine_->StopCapture(this);\n}\n\nvoid RtcVideoCaptureDelegate::OnStarted(media::VideoCapture* capture) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnStarted\";\n}\n\nvoid RtcVideoCaptureDelegate::OnStopped(media::VideoCapture* capture) {\n}\n\nvoid RtcVideoCaptureDelegate::OnPaused(media::VideoCapture* capture) {\n}\n\nvoid RtcVideoCaptureDelegate::OnError(media::VideoCapture* capture,\n int error_code) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnError\";\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnErrorOnCaptureThread,\n this, capture));\n}\n\nvoid RtcVideoCaptureDelegate::OnRemoved(media::VideoCapture* capture) {\n DVLOG(3) << \" RtcVideoCaptureDelegate::OnRemoved\";\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnRemovedOnCaptureThread,\n this, capture));\n\n \/\/ Balance the AddRef in StartCapture.\n \/\/ This means we are no longer registered as an event handler and can safely\n \/\/ be deleted.\n Release();\n}\n\nvoid RtcVideoCaptureDelegate::OnBufferReady(\n media::VideoCapture* capture,\n scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) {\n message_loop_proxy_->PostTask(\n FROM_HERE,\n base::Bind(&RtcVideoCaptureDelegate::OnBufferReadyOnCaptureThread,\n this, capture, buf));\n}\n\nvoid RtcVideoCaptureDelegate::OnDeviceInfoReceived(\n media::VideoCapture* capture,\n const media::VideoCaptureParams& device_info) {\n}\n\nvoid RtcVideoCaptureDelegate::OnDeviceInfoChanged(\n media::VideoCapture* capture,\n const media::VideoCaptureParams& device_info) {\n}\n\nvoid RtcVideoCaptureDelegate::OnBufferReadyOnCaptureThread(\n media::VideoCapture* capture,\n scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) {\n if (!captured_callback_.is_null()) {\n if (!got_first_frame_) {\n got_first_frame_ = true;\n if (!state_callback_.is_null())\n state_callback_.Run(CAPTURE_RUNNING);\n }\n\n captured_callback_.Run(*buf.get());\n }\n capture->FeedBuffer(buf);\n}\n\nvoid RtcVideoCaptureDelegate::OnErrorOnCaptureThread(\n media::VideoCapture* capture) {\n error_occured_ = true;\n if (!state_callback_.is_null())\n state_callback_.Run(CAPTURE_FAILED);\n}\n\n\nvoid RtcVideoCaptureDelegate::OnRemovedOnCaptureThread(\n media::VideoCapture* capture) {\n if (!error_occured_ && !state_callback_.is_null())\n state_callback_.Run(CAPTURE_STOPPED);\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/*\n * LexicalReordering.cpp\n *\n * Created on: 15 Dec 2015\n * Author: hieu\n *\/\n\n#include \"LexicalReordering.h\"\n#include \"..\/System.h\"\n#include \"..\/Search\/Manager.h\"\n#include \"..\/legacy\/InputFileStream.h\"\n\nusing namespace std;\n\nnamespace Moses2 {\n\nstruct LexicalReorderingState : public FFState\n{\n const Range *range;\n\n LexicalReorderingState()\n {\n\t \/\/ uninitialised\n }\n\n\n size_t hash() const {\n\t\/\/ compare range address. All ranges are created in InputPath\n return (size_t) range;\n }\n virtual bool operator==(const FFState& other) const {\n\t\/\/ compare range address. All ranges are created in InputPath\n const LexicalReorderingState &stateCast = static_cast<const LexicalReorderingState&>(other);\n return range == stateCast.range;\n }\n\n virtual std::string ToString() const\n {\n\t return \"\";\n }\n\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLexicalReordering::LexicalReordering(size_t startInd, const std::string &line)\n:StatefulFeatureFunction(startInd, line)\n{\n\tReadParameters();\n}\n\nLexicalReordering::~LexicalReordering()\n{\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid LexicalReordering::Load(System &system)\n{\n InputFileStream file(m_path);\n string line;\n size_t lineNum = 0;\n\n while(getline(file, line)) {\n\tif (++lineNum % 1000000 == 0) {\n\t\tcerr << lineNum << \" \";\n\t}\n\n\tstd::vector<std::string> toks = TokenizeMultiCharSeparator(line, \"|||\");\n\tassert(toks.size() == 3);\n\tPhraseImpl *source = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[0]);\n\tPhraseImpl *target = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[1]);\n\tstd::vector<SCORE> scores = Tokenize<SCORE>(toks[2]);\n std::transform(scores.begin(), scores.end(), scores.begin(), TransformScore);\n\n\tKey key(source, target);\n\tm_coll[key] = scores;\n }\n}\n\nvoid LexicalReordering::SetParameter(const std::string& key, const std::string& value)\n{\n if (key == \"path\") {\n\t m_path = value;\n }\n else if (key == \"type\") {\n\n }\n else if (key == \"input-factor\") {\n\n }\n else if (key == \"output-factor\") {\n\n }\n\n else {\n\t StatefulFeatureFunction::SetParameter(key, value);\n }\n}\n\nFFState* LexicalReordering::BlankState(const Manager &mgr, const InputType &input) const\n{\n MemPool &pool = mgr.GetPool();\n return new (pool.Allocate<LexicalReorderingState>()) LexicalReorderingState();\n}\n\nvoid LexicalReordering::EmptyHypothesisState(FFState &state,\n\t\tconst Manager &mgr,\n\t\tconst InputType &input,\n\t\tconst Hypothesis &hypo) const\n{\n\tLexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state);\n\tstateCast.range = &hypo.GetInputPath().range;\n}\n\nvoid LexicalReordering::EvaluateWhenApplied(const Manager &mgr,\n const Hypothesis &hypo,\n const FFState &prevState,\n Scores &scores,\n FFState &state) const\n{\n const LexicalReorderingState &prevStateCast = static_cast<const LexicalReorderingState&>(prevState);\n LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state);\n\n const Range &currRange = hypo.GetInputPath().range;\n stateCast.range = &currRange;\n\n const Phrase &source = hypo.GetInputPath().subPhrase;\n const Phrase &target = hypo.GetTargetPhrase();\n\n const LexicalReordering::Values *values = GetValues(source, target);\n\n if (values) {\n\t size_t orientation;\n\t vector<SCORE> scoreVec(6, 0);\n\n\n\t const Range *prevRange = prevStateCast.range;\n\t assert(prevRange);\n\n\t if (prevRange->GetStartPos() == NOT_FOUND) {\n\t\t orientation = GetOrientation(currRange);\n\t\t scoreVec[orientation] = (*values)[orientation];\n\t }\n\t else {\n\t\t orientation = GetOrientation(*prevRange, currRange);\n\t\t scoreVec[orientation] = (*values)[orientation];\n\t\t scoreVec[3 + orientation] = (*values)[3 + orientation];\n\t }\n\n\t scores.PlusEquals(mgr.system, *this, scoreVec);\n }\n}\n\nconst LexicalReordering::Values *LexicalReordering::GetValues(const Phrase &source, const Phrase &target) const\n{\n\tKey key(&source, &target);\n\tColl::const_iterator iter;\n\titer = m_coll.find(key);\n\tif (iter == m_coll.end()) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\treturn &iter->second;\n\t}\n}\n\nsize_t LexicalReordering::GetOrientation(Range const& cur) const\n{\n return (cur.GetStartPos() == 0) ? 0 : 1;\n}\n\nsize_t LexicalReordering::GetOrientation(Range const& prev, Range const& cur) const\n{\n if (cur.GetStartPos() == prev.GetEndPos() + 1) {\n\t \/\/ monotone\n\t return 0;\n }\n else if (prev.GetStartPos() == cur.GetEndPos() + 1) {\n\t \/\/ swap\n\t return 1;\n }\n else {\n\t \/\/ discontinuous\n\t return 2;\n }\n}\n\n} \/* namespace Moses2 *\/\n<commit_msg>replicate moses1 scoring<commit_after>\/*\n * LexicalReordering.cpp\n *\n * Created on: 15 Dec 2015\n * Author: hieu\n *\/\n\n#include \"LexicalReordering.h\"\n#include \"..\/System.h\"\n#include \"..\/Search\/Manager.h\"\n#include \"..\/legacy\/InputFileStream.h\"\n\nusing namespace std;\n\nnamespace Moses2 {\n\nstruct LexicalReorderingState : public FFState\n{\n const InputPath *path;\n const TargetPhrase *targetPhrase;\n\n LexicalReorderingState()\n {\n\t \/\/ uninitialised\n }\n\n\n size_t hash() const {\n\t\/\/ compare range address. All ranges are created in InputPath\n return (size_t) &path->range;\n }\n virtual bool operator==(const FFState& other) const {\n\t\/\/ compare range address. All ranges are created in InputPath\n const LexicalReorderingState &stateCast = static_cast<const LexicalReorderingState&>(other);\n return &path->range == &stateCast.path->range;\n }\n\n virtual std::string ToString() const\n {\n\t return \"\";\n }\n\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLexicalReordering::LexicalReordering(size_t startInd, const std::string &line)\n:StatefulFeatureFunction(startInd, line)\n{\n\tReadParameters();\n}\n\nLexicalReordering::~LexicalReordering()\n{\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid LexicalReordering::Load(System &system)\n{\n InputFileStream file(m_path);\n string line;\n size_t lineNum = 0;\n\n while(getline(file, line)) {\n\tif (++lineNum % 1000000 == 0) {\n\t\tcerr << lineNum << \" \";\n\t}\n\n\tstd::vector<std::string> toks = TokenizeMultiCharSeparator(line, \"|||\");\n\tassert(toks.size() == 3);\n\tPhraseImpl *source = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[0]);\n\tPhraseImpl *target = PhraseImpl::CreateFromString(system.systemPool, system.GetVocab(), system, toks[1]);\n\tstd::vector<SCORE> scores = Tokenize<SCORE>(toks[2]);\n std::transform(scores.begin(), scores.end(), scores.begin(), TransformScore);\n\n\tKey key(source, target);\n\tm_coll[key] = scores;\n }\n}\n\nvoid LexicalReordering::SetParameter(const std::string& key, const std::string& value)\n{\n if (key == \"path\") {\n\t m_path = value;\n }\n else if (key == \"type\") {\n\n }\n else if (key == \"input-factor\") {\n\n }\n else if (key == \"output-factor\") {\n\n }\n\n else {\n\t StatefulFeatureFunction::SetParameter(key, value);\n }\n}\n\nFFState* LexicalReordering::BlankState(const Manager &mgr, const InputType &input) const\n{\n MemPool &pool = mgr.GetPool();\n return new (pool.Allocate<LexicalReorderingState>()) LexicalReorderingState();\n}\n\nvoid LexicalReordering::EmptyHypothesisState(FFState &state,\n\t\tconst Manager &mgr,\n\t\tconst InputType &input,\n\t\tconst Hypothesis &hypo) const\n{\n\tLexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state);\n\tstateCast.path = &hypo.GetInputPath();\n\tstateCast.targetPhrase = &hypo.GetTargetPhrase();\n}\n\nvoid LexicalReordering::EvaluateWhenApplied(const Manager &mgr,\n const Hypothesis &hypo,\n const FFState &prevState,\n Scores &scores,\n FFState &state) const\n{\n const LexicalReorderingState &prevStateCast = static_cast<const LexicalReorderingState&>(prevState);\n LexicalReorderingState &stateCast = static_cast<LexicalReorderingState&>(state);\n\n const Range &currRange = hypo.GetInputPath().range;\n stateCast.path = &hypo.GetInputPath();\n stateCast.targetPhrase = &hypo.GetTargetPhrase();\n\n vector<SCORE> scoreVec(6, 0);\n\n \/\/ calc orientation\n size_t orientation;\n const Range *prevRange = &prevStateCast.path->range;\n assert(prevRange);\n if (prevRange->GetStartPos() == NOT_FOUND) {\n\t orientation = GetOrientation(currRange);\n }\n else {\n\t orientation = GetOrientation(*prevRange, currRange);\n }\n\n \/\/ backwards\n const Phrase &source = hypo.GetInputPath().subPhrase;\n const Phrase &target = hypo.GetTargetPhrase();\n\n const LexicalReordering::Values *values = GetValues(source, target);\n if (values) {\n\t scoreVec[orientation] = (*values)[orientation];\n }\n\n \/\/ forwards\n if (prevRange->GetStartPos() != NOT_FOUND) {\n\t const Phrase &source = prevStateCast.path->subPhrase;\n\t const Phrase &target = *prevStateCast.targetPhrase;\n\n\t const LexicalReordering::Values *values = GetValues(source, target);\n\t if (values) {\n\t\t scoreVec[orientation + 3] = (*values)[orientation + 3];\n\t }\n }\n\n scores.PlusEquals(mgr.system, *this, scoreVec);\n\n}\n\nconst LexicalReordering::Values *LexicalReordering::GetValues(const Phrase &source, const Phrase &target) const\n{\n\tKey key(&source, &target);\n\tColl::const_iterator iter;\n\titer = m_coll.find(key);\n\tif (iter == m_coll.end()) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\treturn &iter->second;\n\t}\n}\n\nsize_t LexicalReordering::GetOrientation(Range const& cur) const\n{\n return (cur.GetStartPos() == 0) ? 0 : 1;\n}\n\nsize_t LexicalReordering::GetOrientation(Range const& prev, Range const& cur) const\n{\n if (cur.GetStartPos() == prev.GetEndPos() + 1) {\n\t \/\/ monotone\n\t return 0;\n }\n else if (prev.GetStartPos() == cur.GetEndPos() + 1) {\n\t \/\/ swap\n\t return 1;\n }\n else {\n\t \/\/ discontinuous\n\t return 2;\n }\n}\n\n} \/* namespace Moses2 *\/\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <boost\/version.hpp>\n\n#include <fstream> \n#include <stdint.h>\n#include \"task_manager_lib\/TaskServerInterface.h\"\n#include <ros\/ros.h>\n#include <ros\/package.h>\n\nusing namespace boost::posix_time;\nusing namespace std;\nusing namespace task_manager_lib;\n\n\nstd::string TaskServerInterface::package_name = \"task_manager_turtlesim\";\n\n\nTaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)\n{\n\tsaveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService(\"save_basic_mission\", &TaskServerInterface::saveBasicMission,this);\n\tsaveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService(\"save_complex_mission\", &TaskServerInterface::saveComplexMission,this);\n\texecuteComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService(\"execute_complex_mission\", &TaskServerInterface::executeComplexMission,this);\n\tstopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService(\"abord_complex_mission\", &TaskServerInterface::stopComplexMission,this);\n\tlistMissionsSrv=ts_ref.getNodeHandle().advertiseService(\"list_mission\", &TaskServerInterface::listMissions,this);\n}\n\n\/\/callback\n\nbool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request &req, task_manager_lib::SaveBasicMission::Response &res )\n{\n\tcreateBasicMissionFile(req.basic_mission,res.filename);\n\treturn true;\n}\n\nbool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request &req, task_manager_lib::SaveComplexMission::Response &res )\n{\n\tcreateComplexMissionFile(req.complex_mission,res.filename);\n\treturn true;\n}\n\nbool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request &req, task_manager_lib::ExeComplexMission::Response &res )\n{\n\tlaunchComplexMission(req.mission_name, res.pid);\n\treturn true;\n}\n\nbool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request &req, task_manager_lib::StopComplexMission::Response &res )\n{\n\tabordComplexMission(req.pid);\n\treturn true;\n}\n\n\nbool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request &req, task_manager_lib::ListMissions::Response &res )\n{\n\tparseMissionDirectory(res.basic_missions,res.complex_missions);\n\treturn true;\n}\n\nvoid TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const\n{\n\tstd::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;\n\t\n\ttry\n\t{\n\t\tstringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\t\tstringstream msg;\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\ttime_facet *facet = new time_facet(\"%d-%b-%Y-%H_%M_%S\");\n\t\t\t\t\n\t\t\t\tstringstream pathName;\n\t\t\t\tpathName.imbue(locale(pathName.getloc(), facet));\n\t\t\t\tpathName<<mission_path.string()<<\"\/mission_\"<<second_clock::local_time() << \".mission\";\n\t\t\t\t\n\t\t\t\tboost::filesystem::path output_boost_path(pathName.str());\n\t\t\t\t\n\n\t\t\t\tofstream outputFile (pathName.str().c_str()) ;\n\t\t\t\t\/\/write mission file\n\t\t\t\t\/\/Mission task\n\t\t\t\tfor (unsigned int i = 0;i<tasklist.size();i++) \n\t\t\t\t{\n\t\t\t\t\toutputFile<<\"---\"<<\"\\n\";\n\t\t\t\t\toutputFile<<tasklist[i].name<<\"\\n\";\n\n\t\t\t\t\tif (tasklist[i].parameters.size()==0)\n\t\t\t\t\t{\n\t\t\t\t\t\toutputFile<<\"empty\"<<\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int j = 0;j<tasklist[i].parameters.size();j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toutputFile<<tasklist[i].parameters[j].name;\n\t\t\t\t\t\t\toutputFile<<\";\";\n\t\t\t\t\t\t\toutputFile<<tasklist[i].parameters[j].value;\n\t\t\t\t\t\t\toutputFile<<\"|\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutputFile<<\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\toutputFile.close();\n\t\t\t\t\t\n\t\t\t\t}\n#if (BOOST_VERSION > 104200)\n filename=output_boost_path.filename().string();\n#else\n filename=output_boost_path.filename();\n#endif\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.c_str());\n\t\t\t}\n\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPRINTF(1,\"%s does not exist\\n\",path.str().c_str());\n\t\t}\n\t\t\n\t}\n\tcatch (char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t\tfilename=\"Error creating Basic Mission file\";\n\t}\n}\n\nvoid TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename) \n{\n\tstd::string tasklist=complex_mission;\n\tstringstream msg;\n\ttry\n\t{\n\t\tstd::stringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\ttime_facet *facet = new time_facet(\"%d-%b-%Y-%H_%M_%S\");\n\t\t\t\t\n\t\t\t\tstd::stringstream pathName;\n\t\t\t\tpathName.imbue(locale(pathName.getloc(), facet));\n\t\t\t\tpathName<<mission_path.string()<<\"\/mission_\"<<second_clock::local_time() << \".py\";\n\t\t\t\t\n\t\t\t\tboost::filesystem::path output_boost_path(pathName.str());\n\t\t\t\t\n\t\t\t\tif (boost::filesystem::exists(output_boost_path))\n\t\t\t\t{\n\t\t\t\t\t\/\/replace\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/write mission file\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tofstream outputFile (pathName.str().c_str()) ;\n\t\t\t\t\t\toutputFile<<tasklist<<endl;\n\t\t\t\t\t\toutputFile.close();\n\t\t\t\t\t\tstd::stringstream command_line;\n\t\t\t\t\t\tcommand_line<<\"chmod 775 \"<<pathName.str();\n\t\t\t\t\t\tint result=system(command_line.str().c_str());\n\t\t\t\t\t\tif (result!=0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPRINTF(1,\"Error %d setting execution permission to %s\",result,command_line.str().c_str());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch(char * str)\n\t\t\t\t\t{\n\t\t\t\t\t\tPRINTF(1,\"%s\",str);\n\t\t\t\t\t}\n\t\t\t\t}\n#if BOOST_VERSION > 104200\n\t\t\t\tfilename=output_boost_path.filename().string();\n#else\n\t\t\t\tfilename=output_boost_path.filename();\n#endif\n\t\t\t\t\/\/update list of complex filename\n\t\t\t\ttask_manager_msgs::ComplexMission current_mission;\n\t\t\t\tcurrent_mission.name=filename;\n\t\t\t\tcurrent_mission.complex_mission=tasklist;\n\t\t\t\tComplexMissions.push_back(current_mission);\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.c_str());\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPRINTF(1,\" %s does not exist\\n\",path.str().c_str());\n\t\t}\n\t\t\n\t}\n\tcatch (char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t\tfilename=\"error creating file\";\n\t}\n\t\n}\n\n\nvoid TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions) \n{\n\tif (boost::filesystem::exists(mission_file_path))\n\t{\n\t\tstringstream pathName(mission_file_path.string());\n\t\tifstream MisssionFile(pathName.str().c_str());\n\t\tstd::string line;\n\t\t\n\t\ttask_manager_msgs::BasicMission mission_elem;\n\t\tstd::vector<task_manager_msgs::TaskDescriptionLight> tasks;\n\t\t\n\t\tif (MisssionFile.is_open())\n\t\t{\n\t\t\ttask_manager_msgs::TaskDescriptionLight current_task;\n\t\t\tstd::vector<task_manager_msgs::TaskParameter> parameters;\n\t\t\t\n\t\t\tunsigned int current_line(0), task_line(0);\n\t\t\twhile ( getline(MisssionFile,line))\n\t\t\t{\n\t\t\t\tcurrent_line ++;\n\t\t\t\tif (line==\"---\")\n\t\t\t\t{\n\t\t\t\t\ttask_line=current_line;\n\t\t\t\t\tcurrent_task=task_manager_msgs::TaskDescriptionLight();\n\t\t\t\t\tparameters.clear();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (current_line>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (current_line==task_line+1)\/\/name\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrent_task.name=line;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (current_line==task_line+2)\/\/params\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (line!=\"empty\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::vector<std::string> params;\n\t\t\t\t\t\t\t\tsplit(line,'|',params);\n\t\t\t\t\t\t\t\tfor (unsigned int j=0;j<params.size();j++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstd::vector<std::string> name_value;\n\t\t\t\t\t\t\t\t\tsplit(params[j],';',name_value);\n\t\t\t\t\t\t\t\t\ttask_manager_msgs::TaskParameter current_param;\n\t\t\t\t\t\t\t\t\tcurrent_param.name=name_value[0];\n\t\t\t\t\t\t\t\t\tcurrent_param.value=name_value[1];\n\t\t\t\t\t\t\t\t\tparameters.push_back(current_param);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrent_task.parameters=parameters;\n\t\t\t\t\t\t\t\ttasks.push_back(current_task);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/error\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n#if BOOST_VERSION > 104200\n\t\tmission_elem.name=mission_file_path.filename().string();\n#else\n\t\tmission_elem.name=mission_file_path.filename();\n#endif\n\t\tmission_elem.basic_mission=tasks;\n\t\t\/\/store in taskserverinterface BasicMissions\n\t\tBasicMissions.push_back(mission_elem);\n\t\t\/\/response\n\t\tbasic_missions.push_back(mission_elem);\n\t}\n}\n\nvoid TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions) \n{\n\tif (boost::filesystem::exists(mission_file_path))\n\t{\n\t\tstringstream pathName(mission_file_path.string());\n\t\tifstream MisssionFile(pathName.str().c_str());\n\t\tstd::string line;\n\t\ttask_manager_msgs::ComplexMission mission_elem;\n\t\tstringstream current_complex_mission;\n\t\t\n\t\tif (MisssionFile.is_open())\n\t\t{\n\t\t\twhile ( getline(MisssionFile,line))\n\t\t\t{\n\t\t\t\tcurrent_complex_mission<<line<<endl;\n\t\t\t}\n\t\t}\n#if BOOST_VERSION > 104200\n\t\tmission_elem.name=mission_file_path.filename().string();\n#else\n\t\tmission_elem.name=mission_file_path.filename();\n#endif\n\t\tmission_elem.complex_mission= current_complex_mission.str();\n\t\t\/\/store\n\t\tComplexMissions.push_back(mission_elem);\n\t\t\/\/in response\n\t\tcomplex_missions.push_back(mission_elem);\n\t\t\n\t}\n}\n\nvoid TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions ) \n{\n\ttry\n\t{\n\t\/\/todo for all package\n\tstd::stringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\tboost::filesystem::directory_iterator end;\n\t\t\t\t\n\t\t\t\tfor( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ ) \n\t\t\t\t{\n\t\t\t\t\tif ( !boost::filesystem::is_directory( *iter ) )\n\t\t\t\t\t{\n#if BOOST_VERSION > 104200\n\t\t\t\t\t\tboost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));\n#else\n\t\t\t\t\t\t\t\/\/char * cwd = get_current_dir_name();\n\t\t\t\t\t\t\t\/\/boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());\n\t\t\t\t\t\t\t\/\/free(cwd);\n\t\t\t\t\t\t\tboost::filesystem::path current_path(iter-> path().string());\n#endif\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (current_path.extension() ==\".py\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparseComplexMissionFile(current_path,complex_missions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (current_path.extension() ==\".mission\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparseBasicMissionFile(current_path,basic_missions);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPRINTF(1,\"Can't find missions directory in %s \\n\",path.str().c_str());\n\t\t\t}\n\t\t}\n\t}\n\tcatch(char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t}\n}\n\nvoid TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const\n{\n\t\n\tint id(-1);\n\tfor (unsigned int i=0;i<ComplexMissions.size();i++)\n\t{\n\t\tif (ComplexMissions[i].name==mission_name)\n\t\t{\n\t\t\tid=i;\n\t\t}\n\t}\n\t\n\tstd::string full_name=saveBasicMissionSrv.getService();\n\tsize_t pos=full_name.find(\"save_basic_mission\");\n\tstd::string node_name=full_name.substr(0,pos-1);\n\t\n\tstringstream parameter;\n\tparameter<<\" _server:=\"<<node_name;\n\t\n\tstringstream rosrun_path;\n\trosrun_path<<getenv(\"ROS_ROOT\")<<\"\/bin\/rosrun\";\n\t\n\t\/\/WARNING adding fork in service \n\tstringstream msg;\n\tif (id>-1)\n\t{\n\t\tint current_pid = fork();\n\n\t\tif (current_pid ==-1)\n\t\t{\n\t\t\tPRINTF(1,\"Fork failed\");\n\t\t}\n\t\telse if (current_pid ==0)\/\/in child\n\t\t{\n\t\t\texecl (rosrun_path.str().c_str(),\"rosrun\", package_name.c_str(), mission_name.c_str(),parameter.str().c_str(),(char *) 0);\n\t\t\t\/\/msg<<\"Error running the following command :\"<<\"rosrun \"<<package_name.c_str()<<\" \"<<mission_name.c_str()<<\" \"<<parameter.str().c_str()<<\"\\n\";\n\t\t\tPRINTF(1,\"Error running the following command : 'rosrun %s %s %s' \\n\",package_name.c_str(),mission_name.c_str(),parameter.str().c_str());\n\t\t}\n\t\telse \/\/in parent\n\t\t{\n\t\t\tpid=current_pid;\n\t\t}\n\t}\n\telse\n\t{\n\t\tPRINTF(1,\"Complex Mission %s not found\\n\",mission_name.c_str());\n\t}\n}\n\nvoid TaskServerInterface::abordComplexMission(int &pid)\n{\n\tkill( pid, SIGKILL );\n}\n\n\n\nvoid TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n}\n\n\n<commit_msg>*.c_str() changed for ubuntu 10.04<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <boost\/version.hpp>\n\n#include <fstream> \n#include <stdint.h>\n#include \"task_manager_lib\/TaskServerInterface.h\"\n#include <ros\/ros.h>\n#include <ros\/package.h>\n\nusing namespace boost::posix_time;\nusing namespace std;\nusing namespace task_manager_lib;\n\n\nstd::string TaskServerInterface::package_name = \"task_manager_turtlesim\";\n\n\nTaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)\n{\n\tsaveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService(\"save_basic_mission\", &TaskServerInterface::saveBasicMission,this);\n\tsaveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService(\"save_complex_mission\", &TaskServerInterface::saveComplexMission,this);\n\texecuteComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService(\"execute_complex_mission\", &TaskServerInterface::executeComplexMission,this);\n\tstopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService(\"abord_complex_mission\", &TaskServerInterface::stopComplexMission,this);\n\tlistMissionsSrv=ts_ref.getNodeHandle().advertiseService(\"list_mission\", &TaskServerInterface::listMissions,this);\n}\n\n\/\/callback\n\nbool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request &req, task_manager_lib::SaveBasicMission::Response &res )\n{\n\tcreateBasicMissionFile(req.basic_mission,res.filename);\n\treturn true;\n}\n\nbool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request &req, task_manager_lib::SaveComplexMission::Response &res )\n{\n\tcreateComplexMissionFile(req.complex_mission,res.filename);\n\treturn true;\n}\n\nbool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request &req, task_manager_lib::ExeComplexMission::Response &res )\n{\n\tlaunchComplexMission(req.mission_name, res.pid);\n\treturn true;\n}\n\nbool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request &req, task_manager_lib::StopComplexMission::Response &res )\n{\n\tabordComplexMission(req.pid);\n\treturn true;\n}\n\n\nbool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request &req, task_manager_lib::ListMissions::Response &res )\n{\n\tparseMissionDirectory(res.basic_missions,res.complex_missions);\n\treturn true;\n}\n\nvoid TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const\n{\n\tstd::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;\n\t\n\ttry\n\t{\n\t\tstringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\t\tstringstream msg;\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\ttime_facet *facet = new time_facet(\"%d-%b-%Y-%H_%M_%S\");\n\t\t\t\t\n\t\t\t\tstringstream pathName;\n\t\t\t\tpathName.imbue(locale(pathName.getloc(), facet));\n\t\t\t\tpathName<<mission_path.string()<<\"\/mission_\"<<second_clock::local_time() << \".mission\";\n\t\t\t\t\n\t\t\t\tboost::filesystem::path output_boost_path(pathName.str());\n\t\t\t\t\n\n\t\t\t\tofstream outputFile (pathName.str().c_str()) ;\n\t\t\t\t\/\/write mission file\n\t\t\t\t\/\/Mission task\n\t\t\t\tfor (unsigned int i = 0;i<tasklist.size();i++) \n\t\t\t\t{\n\t\t\t\t\toutputFile<<\"---\"<<\"\\n\";\n\t\t\t\t\toutputFile<<tasklist[i].name<<\"\\n\";\n\n\t\t\t\t\tif (tasklist[i].parameters.size()==0)\n\t\t\t\t\t{\n\t\t\t\t\t\toutputFile<<\"empty\"<<\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int j = 0;j<tasklist[i].parameters.size();j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toutputFile<<tasklist[i].parameters[j].name;\n\t\t\t\t\t\t\toutputFile<<\";\";\n\t\t\t\t\t\t\toutputFile<<tasklist[i].parameters[j].value;\n\t\t\t\t\t\t\toutputFile<<\"|\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutputFile<<\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\toutputFile.close();\n\t\t\t\t\t\n\t\t\t\t}\n#if (BOOST_VERSION > 104200)\n filename=output_boost_path.filename().string();\n#else\n filename=output_boost_path.filename();\n#endif\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t#if (BOOST_VERSION > 104200)\n\t\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.c_str());\n\t\t\t\t#else\n\t\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.string().c_str());\n\t\t\t\t#endif\n\t\t\t}\n\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPRINTF(1,\"%s does not exist\\n\",path.str().c_str());\n\t\t}\n\t\t\n\t}\n\tcatch (char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t\tfilename=\"Error creating Basic Mission file\";\n\t}\n}\n\nvoid TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename) \n{\n\tstd::string tasklist=complex_mission;\n\tstringstream msg;\n\ttry\n\t{\n\t\tstd::stringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\ttime_facet *facet = new time_facet(\"%d-%b-%Y-%H_%M_%S\");\n\t\t\t\t\n\t\t\t\tstd::stringstream pathName;\n\t\t\t\tpathName.imbue(locale(pathName.getloc(), facet));\n\t\t\t\tpathName<<mission_path.string()<<\"\/mission_\"<<second_clock::local_time() << \".py\";\n\t\t\t\t\n\t\t\t\tboost::filesystem::path output_boost_path(pathName.str());\n\t\t\t\t\n\t\t\t\tif (boost::filesystem::exists(output_boost_path))\n\t\t\t\t{\n\t\t\t\t\t\/\/replace\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/write mission file\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tofstream outputFile (pathName.str().c_str()) ;\n\t\t\t\t\t\toutputFile<<tasklist<<endl;\n\t\t\t\t\t\toutputFile.close();\n\t\t\t\t\t\tstd::stringstream command_line;\n\t\t\t\t\t\tcommand_line<<\"chmod 775 \"<<pathName.str();\n\t\t\t\t\t\tint result=system(command_line.str().c_str());\n\t\t\t\t\t\tif (result!=0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPRINTF(1,\"Error %d setting execution permission to %s\",result,command_line.str().c_str());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch(char * str)\n\t\t\t\t\t{\n\t\t\t\t\t\tPRINTF(1,\"%s\",str);\n\t\t\t\t\t}\n\t\t\t\t}\n#if BOOST_VERSION > 104200\n\t\t\t\tfilename=output_boost_path.filename().string();\n#else\n\t\t\t\tfilename=output_boost_path.filename();\n#endif\n\t\t\t\t\/\/update list of complex filename\n\t\t\t\ttask_manager_msgs::ComplexMission current_mission;\n\t\t\t\tcurrent_mission.name=filename;\n\t\t\t\tcurrent_mission.complex_mission=tasklist;\n\t\t\t\tComplexMissions.push_back(current_mission);\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t#if (BOOST_VERSION > 104200)\n\t\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.c_str());\n\t\t\t\t#else\n\t\t\t\t\tPRINTF(1,\"%s does not exist\\n\",mission_path.string().c_str());\n\t\t\t\t#endif\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPRINTF(1,\" %s does not exist\\n\",path.str().c_str());\n\t\t}\n\t\t\n\t}\n\tcatch (char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t\tfilename=\"error creating file\";\n\t}\n\t\n}\n\n\nvoid TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions) \n{\n\tif (boost::filesystem::exists(mission_file_path))\n\t{\n\t\tstringstream pathName(mission_file_path.string());\n\t\tifstream MisssionFile(pathName.str().c_str());\n\t\tstd::string line;\n\t\t\n\t\ttask_manager_msgs::BasicMission mission_elem;\n\t\tstd::vector<task_manager_msgs::TaskDescriptionLight> tasks;\n\t\t\n\t\tif (MisssionFile.is_open())\n\t\t{\n\t\t\ttask_manager_msgs::TaskDescriptionLight current_task;\n\t\t\tstd::vector<task_manager_msgs::TaskParameter> parameters;\n\t\t\t\n\t\t\tunsigned int current_line(0), task_line(0);\n\t\t\twhile ( getline(MisssionFile,line))\n\t\t\t{\n\t\t\t\tcurrent_line ++;\n\t\t\t\tif (line==\"---\")\n\t\t\t\t{\n\t\t\t\t\ttask_line=current_line;\n\t\t\t\t\tcurrent_task=task_manager_msgs::TaskDescriptionLight();\n\t\t\t\t\tparameters.clear();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (current_line>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (current_line==task_line+1)\/\/name\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrent_task.name=line;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (current_line==task_line+2)\/\/params\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (line!=\"empty\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::vector<std::string> params;\n\t\t\t\t\t\t\t\tsplit(line,'|',params);\n\t\t\t\t\t\t\t\tfor (unsigned int j=0;j<params.size();j++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstd::vector<std::string> name_value;\n\t\t\t\t\t\t\t\t\tsplit(params[j],';',name_value);\n\t\t\t\t\t\t\t\t\ttask_manager_msgs::TaskParameter current_param;\n\t\t\t\t\t\t\t\t\tcurrent_param.name=name_value[0];\n\t\t\t\t\t\t\t\t\tcurrent_param.value=name_value[1];\n\t\t\t\t\t\t\t\t\tparameters.push_back(current_param);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcurrent_task.parameters=parameters;\n\t\t\t\t\t\t\t\ttasks.push_back(current_task);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/error\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n#if BOOST_VERSION > 104200\n\t\tmission_elem.name=mission_file_path.filename().string();\n#else\n\t\tmission_elem.name=mission_file_path.filename();\n#endif\n\t\tmission_elem.basic_mission=tasks;\n\t\t\/\/store in taskserverinterface BasicMissions\n\t\tBasicMissions.push_back(mission_elem);\n\t\t\/\/response\n\t\tbasic_missions.push_back(mission_elem);\n\t}\n}\n\nvoid TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions) \n{\n\tif (boost::filesystem::exists(mission_file_path))\n\t{\n\t\tstringstream pathName(mission_file_path.string());\n\t\tifstream MisssionFile(pathName.str().c_str());\n\t\tstd::string line;\n\t\ttask_manager_msgs::ComplexMission mission_elem;\n\t\tstringstream current_complex_mission;\n\t\t\n\t\tif (MisssionFile.is_open())\n\t\t{\n\t\t\twhile ( getline(MisssionFile,line))\n\t\t\t{\n\t\t\t\tcurrent_complex_mission<<line<<endl;\n\t\t\t}\n\t\t}\n#if BOOST_VERSION > 104200\n\t\tmission_elem.name=mission_file_path.filename().string();\n#else\n\t\tmission_elem.name=mission_file_path.filename();\n#endif\n\t\tmission_elem.complex_mission= current_complex_mission.str();\n\t\t\/\/store\n\t\tComplexMissions.push_back(mission_elem);\n\t\t\/\/in response\n\t\tcomplex_missions.push_back(mission_elem);\n\t\t\n\t}\n}\n\nvoid TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions ) \n{\n\ttry\n\t{\n\t\/\/todo for all package\n\tstd::stringstream path(ros::package::getPath(TaskServerInterface::package_name));\n\n\t\tif (path.str().length() >0)\n\t\t{\n\t\t\tboost::filesystem::path mission_path(path.str()+\"\/missions\");\n\t\t\tif (boost::filesystem::exists(mission_path))\n\t\t\t{\n\t\t\t\tboost::filesystem::directory_iterator end;\n\t\t\t\t\n\t\t\t\tfor( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ ) \n\t\t\t\t{\n\t\t\t\t\tif ( !boost::filesystem::is_directory( *iter ) )\n\t\t\t\t\t{\n#if BOOST_VERSION > 104200\n\t\t\t\t\t\tboost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));\n#else\n\t\t\t\t\t\t\t\/\/char * cwd = get_current_dir_name();\n\t\t\t\t\t\t\t\/\/boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());\n\t\t\t\t\t\t\t\/\/free(cwd);\n\t\t\t\t\t\t\tboost::filesystem::path current_path(iter-> path().string());\n#endif\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (current_path.extension() ==\".py\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparseComplexMissionFile(current_path,complex_missions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (current_path.extension() ==\".mission\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparseBasicMissionFile(current_path,basic_missions);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPRINTF(1,\"Can't find missions directory in %s \\n\",path.str().c_str());\n\t\t\t}\n\t\t}\n\t}\n\tcatch(char * str)\n\t{\n\t\tPRINTF(1,\"%s\",str);\n\t}\n}\n\nvoid TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const\n{\n\t\n\tint id(-1);\n\tfor (unsigned int i=0;i<ComplexMissions.size();i++)\n\t{\n\t\tif (ComplexMissions[i].name==mission_name)\n\t\t{\n\t\t\tid=i;\n\t\t}\n\t}\n\t\n\tstd::string full_name=saveBasicMissionSrv.getService();\n\tsize_t pos=full_name.find(\"save_basic_mission\");\n\tstd::string node_name=full_name.substr(0,pos-1);\n\t\n\tstringstream parameter;\n\tparameter<<\" _server:=\"<<node_name;\n\t\n\tstringstream rosrun_path;\n\trosrun_path<<getenv(\"ROS_ROOT\")<<\"\/bin\/rosrun\";\n\t\n\t\/\/WARNING adding fork in service \n\tstringstream msg;\n\tif (id>-1)\n\t{\n\t\tint current_pid = fork();\n\n\t\tif (current_pid ==-1)\n\t\t{\n\t\t\tPRINTF(1,\"Fork failed\");\n\t\t}\n\t\telse if (current_pid ==0)\/\/in child\n\t\t{\n\t\t\texecl (rosrun_path.str().c_str(),\"rosrun\", package_name.c_str(), mission_name.c_str(),parameter.str().c_str(),(char *) 0);\n\t\t\t\/\/msg<<\"Error running the following command :\"<<\"rosrun \"<<package_name.c_str()<<\" \"<<mission_name.c_str()<<\" \"<<parameter.str().c_str()<<\"\\n\";\n\t\t\tPRINTF(1,\"Error running the following command : 'rosrun %s %s %s' \\n\",package_name.c_str(),mission_name.c_str(),parameter.str().c_str());\n\t\t}\n\t\telse \/\/in parent\n\t\t{\n\t\t\tpid=current_pid;\n\t\t}\n\t}\n\telse\n\t{\n\t\tPRINTF(1,\"Complex Mission %s not found\\n\",mission_name.c_str());\n\t}\n}\n\nvoid TaskServerInterface::abordComplexMission(int &pid)\n{\n\tkill( pid, SIGKILL );\n}\n\n\n\nvoid TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"filedecompressor.h\"\n#include <QMap>\n#include <QBuffer>\n\nFileDecompressor::FileDecompressor()\n{\n\n}\n\nFileDecompressor::~FileDecompressor()\n{\n\n}\n\nvoid FileDecompressor::decompress()\n{\n \/\/Opens HZIP file\n qDebug() << endl << endl;\n QString filePath;\n QFileDialog dialog;\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setNameFilter(\"HuffmanZip (*.hzip)\");\n int result = dialog.exec();\n if (result)\n filePath = dialog.selectedFiles().first();\n else\n filePath = \"\";\n \/\/Now we need to separate HEADER from DATA\n\n QFile inputFile(filePath);\n inputFile.open(QIODevice::ReadOnly | QIODevice::Text);\n\n \/* Check it opened OK *\/\n if(!inputFile.isOpen()){\n qDebug() << \"- Error, unable to open\" << filePath << \"for input\";\n }\n\n \/* Point a QTextStream object at the file *\/\n QTextStream inStream(&inputFile);\n\n \/* Write the line to the file *\/\n qDebug() << \"????????????????????????????????\";\n QString text = inStream.readAll();\n\n \/* Close the file *\/\n inputFile.close();\n\n QStringList list = text.split(\" \",QString::SkipEmptyParts);\n this->width = list.at(0).toInt();\n this->height = list.at(1).toInt();\n<<<<<<< HEAD\n this->imagedata;\n this->header = list.at(2).split(\"#\", QString::SkipEmptyParts);\n this->headerInterpreter();\n \/\/Tendria que quedar asi los bits que me da decodificar\n \/\/QString bits = decodificate();\n QString bits = \"1010111000010110101101011101010010101010010011110\";\n this->generateFile(bits);\n=======\n this->imagedata = list.at(3);\n QStringList codelist = list.at(2).split(\"#\");\n this->header = codelist;\n\n decodificate();\n>>>>>>> origin\/master\n}\n\nQString FileDecompressor::decodificate()\n{\n QString file = this->imagedata;\n std::string filestring = file.toStdString();\n char temp = filestring.at(0);\n qDebug() << \"EL PRIMER CHAR SIN DECODIFICAR ES\" <<temp;\n QChar temp2 = filestring.at(0);\n qDebug() << \"EL PRIMER QCHAR SIN CODIFICAR ES\" <<temp2;\n qDebug() << \"EL UNICODE: \" << temp2.unicode();\n QChar temp3 = filestring.at(1);\n qDebug() << \"EL PRIMER QCHAR SIN CODIFICAR ES\" <<temp3;\n qDebug() << \"EL UNICODE: \" << temp3.unicode();\n\n QString image;\n\n\n for (int i = 0; i < file.size(); i++) {\n char mander = filestring.at(i);\n for (int e = 0; e < 16; e++) {\n int value = (e >> mander) & 1;\n qDebug() << value;\n image.append(value);\n }\n }\n qDebug() << image.at(0) << image.at(1);\n\n\n}\n\nvoid FileDecompressor::headerInterpreter()\n{\n QStringList::iterator it;\n for(it=this->header.begin(); it!=this->header.end(); it++)\n {\n this->codes.insert(it->mid(6), it->mid(0,6).prepend(\"#\"));\n }\n}\n\nvoid FileDecompressor::generateFile(QString bits)\n{\n QString aux;\n QVector<QColor> colors;\n QString::iterator it;\n for(it=bits.begin(); it!=bits.end(); it++)\n {\n aux += *it;\n if(this->codes.contains(aux))\n {\n colors.push_back(QColor(this->codes.find(aux).value()));\n aux.clear();\n }\n }\n qDebug() << colors;\n QImage img;\n QByteArray ba;\n QBuffer buffer(&ba);\n \/\/Esto va a tardar por la resolucion de la imagen, no es que se colgo el programa\n for(int i=0; i<this->height; i++)\n {\n for(int j=0; j<this->width; j++)\n {\n img.setPixel(i,j,colors.first().rgb());\n }\n\n }\n \/\/Tengo que ver como guardar la imagen\n img.save(&buffer, \"PNG\");\n}\n\n<commit_msg>Modified method implementation<commit_after>#include \"filedecompressor.h\"\n#include <QMap>\n#include <QBuffer>\n\nFileDecompressor::FileDecompressor()\n{\n\n}\n\nFileDecompressor::~FileDecompressor()\n{\n\n}\n\nvoid FileDecompressor::decompress()\n{\n \/\/Opens HZIP file\n qDebug() << endl << endl;\n QString filePath;\n QFileDialog dialog;\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setNameFilter(\"HuffmanZip (*.hzip)\");\n int result = dialog.exec();\n if (result)\n filePath = dialog.selectedFiles().first();\n else\n filePath = \"\";\n \/\/Now we need to separate HEADER from DATA\n\n QFile inputFile(filePath);\n inputFile.open(QIODevice::ReadOnly | QIODevice::Text);\n\n \/* Check it opened OK *\/\n if(!inputFile.isOpen()){\n qDebug() << \"- Error, unable to open\" << filePath << \"for input\";\n }\n\n \/* Point a QTextStream object at the file *\/\n QTextStream inStream(&inputFile);\n\n \/* Write the line to the file *\/\n qDebug() << \"????????????????????????????????\";\n QString text = inStream.readAll();\n\n \/* Close the file *\/\n inputFile.close();\n\n QStringList list = text.split(\" \",QString::SkipEmptyParts);\n this->width = list.at(0).toInt();\n this->height = list.at(1).toInt();\n this->header = list.at(2).split(\"#\", QString::SkipEmptyParts);\n this->imagedata = list.at(3);\n this->headerInterpreter();\n \/\/Tendria que quedar asi los bits que me da decodificar\n \/\/QString bits = decodificate();\n QString bits = \"1010111000010110101101011101010010101010010011110\";\n this->generateFile(bits);\n}\n\nQString FileDecompressor::decodificate()\n{\n QString file = this->imagedata;\n std::string filestring = file.toStdString();\n char temp = filestring.at(0);\n qDebug() << \"EL PRIMER CHAR SIN DECODIFICAR ES\" <<temp;\n QChar temp2 = filestring.at(0);\n qDebug() << \"EL PRIMER QCHAR SIN CODIFICAR ES\" <<temp2;\n qDebug() << \"EL UNICODE: \" << temp2.unicode();\n QChar temp3 = filestring.at(1);\n qDebug() << \"EL PRIMER QCHAR SIN CODIFICAR ES\" <<temp3;\n qDebug() << \"EL UNICODE: \" << temp3.unicode();\n\n QString image;\n\n\n for (int i = 0; i < file.size(); i++) {\n char mander = filestring.at(i);\n for (int e = 0; e < 16; e++) {\n int value = (e >> mander) & 1;\n qDebug() << value;\n image.append(value);\n }\n }\n qDebug() << image.at(0) << image.at(1);\n\n\n}\n\nvoid FileDecompressor::headerInterpreter()\n{\n QStringList::iterator it;\n for(it=this->header.begin(); it!=this->header.end(); it++)\n {\n this->codes.insert(it->mid(6), it->mid(0,6).prepend(\"#\"));\n }\n}\n\nvoid FileDecompressor::generateFile(QString bits)\n{\n QString aux;\n QVector<QColor> colors;\n QString::iterator it;\n for(it=bits.begin(); it!=bits.end(); it++)\n {\n aux += *it;\n if(this->codes.contains(aux))\n {\n colors.push_back(QColor(this->codes.find(aux).value()));\n aux.clear();\n }\n }\n qDebug() << colors;\n QImage img;\n QByteArray ba;\n QBuffer buffer(&ba);\n \/\/Esto va a tardar por la resolucion de la imagen, no es que se colgo el programa\n for(int i=0; i<this->height; i++)\n {\n for(int j=0; j<this->width; j++)\n {\n img.setPixel(i,j,colors.first().rgb());\n }\n\n }\n \/\/Tengo que ver como guardar la imagen\n img.save(&buffer, \"PNG\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <stdlib.h>\n#include <set>\n#include <string>\n#include <stdio.h>\n\n#include <libcassandra\/connection_manager.h>\n#include <libcassandra\/cassandra.h>\n\nusing namespace std;\nusing namespace org::apache::cassandra;\nusing namespace libcassandra;\n\nstatic string host(\"172.16.0.163\");\nstatic int port= 9160;\nstatic size_t pool_size = 16;\nint main()\n{\n try\n {\n static const string ks_name(\"drizzle\");\n static const string key(\"sarah\");\n static const string col_value(\"this is data being inserted!\");\n static const string col_family(\"Data\");\n static const string sup_col_name(\"Test\");\n static const string col_name(\"third\");\n\n CassandraConnectionManager::instance()->init(host,port,pool_size);\n boost::shared_ptr<Cassandra> client(new Cassandra());\n\n string clus_name= client->getClusterName();\n cout << \"cluster name: \" << clus_name << endl;\n\n ColumnParent col_parent;\n col_parent.__set_column_family(col_family);\n col_parent.__set_super_column(sup_col_name);\n SlicePredicate pred;\n\n \/* create keyspace *\/\n cout << \"Create keyspace: \" << ks_name << endl;\n KsDef ks_def;\n ks_def.__set_name(ks_name);\n client->createKeyspace(ks_def);\n client->setKeyspace(ks_name);\n\n client->reloadKeyspaces();\n cout << \"Current keyspaces are:\" << endl;\n {\n const vector<KsDef>& key_out= client->getKeyspaces();\n for (vector<KsDef>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n {\n cout << it->name << endl;\n }\n }\n cout << endl;\n\n \/* create standard column family *\/\n CfDef cf_def;\n cf_def.__set_name(col_family);\n cf_def.__set_column_type(\"Super\");\n cf_def.__set_keyspace(ks_def.name);\n cf_def.__set_id(1000);\n std::map<std::string, std::string> compress_options;\n compress_options[\"sstable_compression\"] = \"SnappyCompressor\";\n compress_options[\"chunk_length_kb\"] = \"64\";\n cf_def.__set_compression_options(compress_options);\n client->createColumnFamily(cf_def);\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n\n \/* insert data *\/\n cout << \"Value will be inserted is: \" << col_value << endl;\n client->insertColumn(col_value, key, col_family, sup_col_name, col_name);\n cout << endl << \"Inserting....\" << endl;\n\n \/* retrieve that data *\/\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n string res;\n client->getColumnValue(res, key, col_family, sup_col_name, col_name);\n cout << \"Value in column retrieved is: \" << res << endl;\n\n \/* delete data *\/\n cout << endl << \"Deleting....\" << endl;\n client->removeColumn(key, col_family, sup_col_name, col_name);\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n }\n catch (const org::apache::cassandra::InvalidRequestException &ire)\n {\n cerr << \"Invalid request: \" << ire.why << endl;\n return 1;\n }\n catch (const ::apache::thrift::TException &ex)\n {\n cerr << \"Other error: \" << ex.what() << endl;\n return 2;\n }\n\n return 0;\n}\n<commit_msg>tiny fix<commit_after>#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <stdlib.h>\n#include <set>\n#include <string>\n#include <stdio.h>\n\n#include <libcassandra\/connection_manager.h>\n#include <libcassandra\/cassandra.h>\n\nusing namespace std;\nusing namespace org::apache::cassandra;\nusing namespace libcassandra;\n\nstatic string host(\"172.16.0.163\");\nstatic int port= 9160;\nstatic size_t pool_size = 16;\nint main()\n{\n try\n {\n static const string ks_name(\"drizzle\");\n static const string key(\"sarah\");\n static const string col_value(\"this is data being inserted!\");\n static const string col_family(\"Data\");\n static const string sup_col_name(\"Test\");\n static const string col_name(\"third\");\n\n CassandraConnectionManager::instance()->init(host,port,pool_size);\n boost::shared_ptr<Cassandra> client(new Cassandra());\n\n string clus_name= client->getClusterName();\n cout << \"cluster name: \" << clus_name << endl;\n\n ColumnParent col_parent;\n col_parent.__set_column_family(col_family);\n col_parent.__set_super_column(sup_col_name);\n SlicePredicate pred;\n\n \/* create keyspace *\/\n cout << \"Create keyspace: \" << ks_name << endl;\n KsDef ks_def;\n ks_def.__set_name(ks_name);\n ks_def.__set_strategy_class(\"SimpleStrategy\");\n map<string, string> strategy_options;\n strategy_options[\"replication_factor\"] = \"1\";\n ks_def.__set_strategy_options(strategy_options);\n client->createKeyspace(ks_def);\n client->setKeyspace(ks_name);\n\n client->reloadKeyspaces();\n cout << \"Current keyspaces are:\" << endl;\n {\n const vector<KsDef>& key_out= client->getKeyspaces();\n for (vector<KsDef>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n {\n cout << it->name << endl;\n }\n }\n cout << endl;\n\n \/* create standard column family *\/\n CfDef cf_def;\n cf_def.__set_name(col_family);\n cf_def.__set_column_type(\"Super\");\n cf_def.__set_keyspace(ks_def.name);\n std::map<std::string, std::string> compress_options;\n compress_options[\"sstable_compression\"] = \"SnappyCompressor\";\n compress_options[\"chunk_length_kb\"] = \"64\";\n cf_def.__set_compression_options(compress_options);\n client->createColumnFamily(cf_def);\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n\n \/* insert data *\/\n cout << \"Value will be inserted is: \" << col_value << endl;\n client->insertColumn(col_value, key, col_family, sup_col_name, col_name);\n cout << endl << \"Inserting....\" << endl;\n\n \/* retrieve that data *\/\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n string res;\n client->getColumnValue(res, key, col_family, sup_col_name, col_name);\n cout << \"Value in column retrieved is: \" << res << endl;\n\n \/* delete data *\/\n cout << endl << \"Deleting....\" << endl;\n client->removeColumn(key, col_family, sup_col_name, col_name);\n cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n }\n catch (const org::apache::cassandra::InvalidRequestException &ire)\n {\n cerr << \"Invalid request: \" << ire.why << endl;\n return 1;\n }\n catch (const ::apache::thrift::TException &ex)\n {\n cerr << \"Other error: \" << ex.what() << endl;\n return 2;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -emit-llvm -fno-standalone-debug -g -o - %s | FileCheck %s\n\/\/ RUN: %clang_cc1 -emit-llvm -fno-standalone-debug -g -o - -load %llvmshlibdir\/PrintFunctionNames%pluginext %s 2>&1 | FileCheck %s\n\nnamespace PR16214_1 {\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n int i;\n};\n\ntypedef foo bar;\n\nbar *a;\nbar b;\n}\n\nnamespace PR14467 {\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nfoo *bar(foo *a) {\n foo *b = new foo(*a);\n return b;\n}\n}\n\nnamespace test1 {\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nextern int bar(foo *a);\nint baz(foo *a) {\n return bar(a);\n}\n}\n\nnamespace test2 {\n\/\/ FIXME: if we were a bit fancier, we could realize that the 'foo' type is only\n\/\/ required because of the 'bar' type which is not required at all (or might\n\/\/ only be required to be declared)\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nstruct bar {\n foo f;\n};\n\nvoid func() {\n foo *f;\n}\n}\n<commit_msg>DebugInfo: Ensure the ASTConsumer \"HandleTagDeclRequireDefinition\" callback path is tested.<commit_after>\/\/ RUN: %clang_cc1 -emit-llvm -fno-standalone-debug -g -o - %s | FileCheck %s\n\/\/ RUN: %clang_cc1 -emit-llvm -fno-standalone-debug -g -o - -load %llvmshlibdir\/PrintFunctionNames%pluginext %s 2>&1 | FileCheck %s\n\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [PR16214] [line [[@LINE+1]], {{.*}} [def]\nstruct PR16214 {\n int i;\n};\n\ntypedef PR16214 bar;\n\nbar *a;\nbar b;\n\nnamespace PR14467 {\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nfoo *bar(foo *a) {\n foo *b = new foo(*a);\n return b;\n}\n}\n\nnamespace test1 {\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nextern int bar(foo *a);\nint baz(foo *a) {\n return bar(a);\n}\n}\n\nnamespace test2 {\n\/\/ FIXME: if we were a bit fancier, we could realize that the 'foo' type is only\n\/\/ required because of the 'bar' type which is not required at all (or might\n\/\/ only be required to be declared)\n\/\/ CHECK-DAG: [ DW_TAG_structure_type ] [foo] [line [[@LINE+1]], {{.*}} [def]\nstruct foo {\n};\n\nstruct bar {\n foo f;\n};\n\nvoid func() {\n foo *f;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <iostream>\n#include <Common\/Colorful.hh>\n#include <Lex\/Lexer.hh>\n#include <Object\/StringObject.hh>\n#include <Core\/TadpoleVM.hh>\n#include <Compiler\/Parser.hh>\n\nnamespace Tadpole::Compiler {\n\nGlobalParser::GlobalParser(Core::TadpoleVM& vm, Lex::Lexer& lex) noexcept\n : vm_(vm), lex_(lex) {\n}\n\nvoid GlobalParser::iter_objects(Object::ObjectVisitor&& visitor) {\n \/\/ TODO:\n}\n\nObject::FunctionObject* GlobalParser::compile() {\n \/\/ TODO:\n return nullptr;\n}\n\nconst ParseRule& GlobalParser::get_rule(Lex::TokenKind kind) const noexcept {\n static const ParseRule _rules[] = {\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LPAREN, \"(\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RPAREN, \")\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LBRACE, \"{\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RBRACE, \"}\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(COMMA, \",\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(MINUS, \"-\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(PLUS, \"+\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SEMI, \";\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SLASH, \"\/\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(STAR, \"*\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(EQ, \"=\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(IDENTIFIER, \"Identifier\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(NUMERIC, \"Numeric\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(STRING, \"String\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FALSE, \"false\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FN, \"fn\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(NIL, \"nil\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(TRUE, \"true\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(VAR, \"var\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(EOF, \"Eof\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(ERR, \"Error\")\n };\n\n return _rules[Common::as_type<int>(kind)];\n}\n\nvoid GlobalParser::error_at(const Lex::Token& tok, const str_t& msg) noexcept {\n if (panic_mode_)\n return;\n panic_mode_ = true;\n\n std::cerr\n << Common::Colorful::fg::red\n << \"SyntaxError:\" << std::endl\n << \" [LINE: \" << tok.lineno() << \"] ERROR \";\n if (tok.kind() == Lex::TokenKind::TK_EOF)\n std::cerr << \"at end \";\n else if (tok.kind() == Lex::TokenKind::TK_ERR)\n TADPOLE_UNUSED(0);\n else\n std::cerr << \"at `\" << tok.literal() << \"` \";\n std::cerr << \": \" << msg << Common::Colorful::reset << std::endl;\n}\n\nvoid GlobalParser::advance() {\n prev_ = curr_;\n\n for (;;) {\n curr_ = lex_.next_token();\n if (!check(Lex::TokenKind::TK_ERR))\n break;\n\n error_at_current(curr_.as_string());\n }\n}\n\nvoid GlobalParser::consume(Lex::TokenKind kind, const str_t& msg) {\n if (check(kind))\n advance();\n else\n error_at_current(msg);\n}\n\nbool GlobalParser::match(Lex::TokenKind kind) {\n if (check(kind)) {\n advance();\n return true;\n }\n return false;\n}\n\nvoid GlobalParser::init_compiler(FunctionCompiler* compiler, int scope_depth, FunctionType fn_type) {\n Object::StringObject* fn_name{};\n if (fn_type == FunctionType::FUNCTION)\n fn_name = Object::StringObject::create(prev_.as_string());\n\n compiler->set_compiler(\n curr_compiler_,\n Object::FunctionObject::create(fn_name),\n fn_type,\n scope_depth);\n curr_compiler_ = compiler;\n\n curr_compiler_->append_local({Lex::Token::make(\"\"), curr_compiler_->scope_depth(), false});\n}\n\nObject::FunctionObject* GlobalParser::finish_compiler() {\n emit_return();\n\n Object::FunctionObject* fn = curr_compiler_->fn();\n#if defined(_TADPOLE_DEBUG_VM)\n if (!had_error_)\n curr_chunk()->dis(fn->name_asstr());\n#endif\n\n curr_compiler_ = curr_compiler_->enclosing();\n return fn;\n}\n\nvoid GlobalParser::enter_scope() {\n curr_compiler_->enter_scope();\n}\n\nvoid GlobalParser::leave_scope() {\n}\n\n}\n<commit_msg>:construction: chore(parser): add leave scope implementation of parser<commit_after>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <iostream>\n#include <Common\/Colorful.hh>\n#include <Lex\/Lexer.hh>\n#include <Object\/StringObject.hh>\n#include <Core\/TadpoleVM.hh>\n#include <Compiler\/Parser.hh>\n\nnamespace Tadpole::Compiler {\n\nGlobalParser::GlobalParser(Core::TadpoleVM& vm, Lex::Lexer& lex) noexcept\n : vm_(vm), lex_(lex) {\n}\n\nvoid GlobalParser::iter_objects(Object::ObjectVisitor&& visitor) {\n \/\/ TODO:\n}\n\nObject::FunctionObject* GlobalParser::compile() {\n \/\/ TODO:\n return nullptr;\n}\n\nconst ParseRule& GlobalParser::get_rule(Lex::TokenKind kind) const noexcept {\n static const ParseRule _rules[] = {\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LPAREN, \"(\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RPAREN, \")\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LBRACE, \"{\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RBRACE, \"}\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(COMMA, \",\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(MINUS, \"-\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(PLUS, \"+\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SEMI, \";\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SLASH, \"\/\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(STAR, \"*\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(EQ, \"=\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(IDENTIFIER, \"Identifier\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(NUMERIC, \"Numeric\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(STRING, \"String\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FALSE, \"false\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FN, \"fn\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(NIL, \"nil\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(TRUE, \"true\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(VAR, \"var\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(EOF, \"Eof\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(ERR, \"Error\")\n };\n\n return _rules[Common::as_type<int>(kind)];\n}\n\nvoid GlobalParser::error_at(const Lex::Token& tok, const str_t& msg) noexcept {\n if (panic_mode_)\n return;\n panic_mode_ = true;\n\n std::cerr\n << Common::Colorful::fg::red\n << \"SyntaxError:\" << std::endl\n << \" [LINE: \" << tok.lineno() << \"] ERROR \";\n if (tok.kind() == Lex::TokenKind::TK_EOF)\n std::cerr << \"at end \";\n else if (tok.kind() == Lex::TokenKind::TK_ERR)\n TADPOLE_UNUSED(0);\n else\n std::cerr << \"at `\" << tok.literal() << \"` \";\n std::cerr << \": \" << msg << Common::Colorful::reset << std::endl;\n}\n\nvoid GlobalParser::advance() {\n prev_ = curr_;\n\n for (;;) {\n curr_ = lex_.next_token();\n if (!check(Lex::TokenKind::TK_ERR))\n break;\n\n error_at_current(curr_.as_string());\n }\n}\n\nvoid GlobalParser::consume(Lex::TokenKind kind, const str_t& msg) {\n if (check(kind))\n advance();\n else\n error_at_current(msg);\n}\n\nbool GlobalParser::match(Lex::TokenKind kind) {\n if (check(kind)) {\n advance();\n return true;\n }\n return false;\n}\n\nvoid GlobalParser::init_compiler(FunctionCompiler* compiler, int scope_depth, FunctionType fn_type) {\n Object::StringObject* fn_name{};\n if (fn_type == FunctionType::FUNCTION)\n fn_name = Object::StringObject::create(prev_.as_string());\n\n compiler->set_compiler(\n curr_compiler_,\n Object::FunctionObject::create(fn_name),\n fn_type,\n scope_depth);\n curr_compiler_ = compiler;\n\n curr_compiler_->append_local({Lex::Token::make(\"\"), curr_compiler_->scope_depth(), false});\n}\n\nObject::FunctionObject* GlobalParser::finish_compiler() {\n emit_return();\n\n Object::FunctionObject* fn = curr_compiler_->fn();\n#if defined(_TADPOLE_DEBUG_VM)\n if (!had_error_)\n curr_chunk()->dis(fn->name_asstr());\n#endif\n\n curr_compiler_ = curr_compiler_->enclosing();\n return fn;\n}\n\nvoid GlobalParser::enter_scope() {\n curr_compiler_->enter_scope();\n}\n\nvoid GlobalParser::leave_scope() {\n curr_compiler_->leave_scope([this](const LocalVar& var) {\n emit_byte(var.is_upvalue ? Core::Code::CLOSE_UPVALUE : Core::Code::POP);\n });\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- LoopVR.cpp - Value Range analysis driven by loop information -------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ FIXME: What does this do?\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loopvr\"\n#include \"llvm\/Analysis\/LoopVR.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/ScalarEvolutionExpressions.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nchar LoopVR::ID = 0;\nstatic RegisterPass<LoopVR> X(\"loopvr\", \"Loop Value Ranges\", false, true);\n\n\/\/\/ getRange - determine the range for a particular SCEV within a given Loop\nConstantRange LoopVR::getRange(SCEVHandle S, Loop *L, ScalarEvolution &SE) {\n SCEVHandle T = SE.getBackedgeTakenCount(L);\n if (isa<SCEVCouldNotCompute>(T))\n return ConstantRange(cast<IntegerType>(S->getType())->getBitWidth(), true);\n\n T = SE.getTruncateOrZeroExtend(T, S->getType());\n return getRange(S, T, SE);\n}\n\n\/\/\/ getRange - determine the range for a particular SCEV with a given trip count\nConstantRange LoopVR::getRange(SCEVHandle S, SCEVHandle T, ScalarEvolution &SE){\n\n if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))\n return ConstantRange(C->getValue()->getValue());\n\n ConstantRange FullSet(cast<IntegerType>(S->getType())->getBitWidth(), true);\n\n \/\/ {x,+,y,+,...z}. We detect overflow by checking the size of the set after\n \/\/ summing the upper and lower.\n if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n ConstantRange X = getRange(Add->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(Add->getOperand(i), T, SE);\n if (Y.isFullSet()) return FullSet;\n\n APInt Spread_X = X.getSetSize(), Spread_Y = Y.getSetSize();\n APInt NewLower = X.getLower() + Y.getLower();\n APInt NewUpper = X.getUpper() + Y.getUpper() - 1;\n if (NewLower == NewUpper)\n return FullSet;\n\n X = ConstantRange(NewLower, NewUpper);\n if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))\n return FullSet; \/\/ we've wrapped, therefore, full set.\n }\n return X;\n }\n\n \/\/ {x,*,y,*,...,z}. In order to detect overflow, we use k*bitwidth where\n \/\/ k is the number of terms being multiplied.\n if (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {\n ConstantRange X = getRange(Mul->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n const IntegerType *Ty = IntegerType::get(X.getBitWidth());\n const IntegerType *ExTy = IntegerType::get(X.getBitWidth() *\n Mul->getNumOperands());\n ConstantRange XExt = X.zeroExtend(ExTy->getBitWidth());\n\n for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(Mul->getOperand(i), T, SE);\n if (Y.isFullSet()) return FullSet;\n\n ConstantRange YExt = Y.zeroExtend(ExTy->getBitWidth());\n XExt = ConstantRange(XExt.getLower() * YExt.getLower(),\n ((XExt.getUpper()-1) * (YExt.getUpper()-1)) + 1);\n }\n return XExt.truncate(Ty->getBitWidth());\n }\n\n \/\/ X smax Y smax ... Z is: range(smax(X_smin, Y_smin, ..., Z_smin),\n \/\/ smax(X_smax, Y_smax, ..., Z_smax))\n \/\/ It doesn't matter if one of the SCEVs has FullSet because we're taking\n \/\/ a maximum of the minimums across all of them.\n if (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {\n ConstantRange X = getRange(SMax->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n APInt smin = X.getSignedMin(), smax = X.getSignedMax();\n for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(SMax->getOperand(i), T, SE);\n smin = APIntOps::smax(smin, Y.getSignedMin());\n smax = APIntOps::smax(smax, Y.getSignedMax());\n }\n if (smax + 1 == smin) return FullSet;\n return ConstantRange(smin, smax + 1);\n }\n\n \/\/ X umax Y umax ... Z is: range(umax(X_umin, Y_umin, ..., Z_umin),\n \/\/ umax(X_umax, Y_umax, ..., Z_umax))\n \/\/ It doesn't matter if one of the SCEVs has FullSet because we're taking\n \/\/ a maximum of the minimums across all of them.\n if (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {\n ConstantRange X = getRange(UMax->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n APInt umin = X.getUnsignedMin(), umax = X.getUnsignedMax();\n for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(UMax->getOperand(i), T, SE);\n umin = APIntOps::umax(umin, Y.getUnsignedMin());\n umax = APIntOps::umax(umax, Y.getUnsignedMax());\n }\n if (umax + 1 == umin) return FullSet;\n return ConstantRange(umin, umax + 1);\n }\n\n \/\/ L udiv R. Luckily, there's only ever 2 sides to a udiv.\n if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {\n ConstantRange L = getRange(UDiv->getLHS(), T, SE);\n ConstantRange R = getRange(UDiv->getRHS(), T, SE);\n if (L.isFullSet() && R.isFullSet()) return FullSet;\n\n if (R.getUnsignedMax() == 0) {\n \/\/ RHS must be single-element zero. Return an empty set.\n return ConstantRange(R.getBitWidth(), false);\n }\n\n APInt Lower = L.getUnsignedMin().udiv(R.getUnsignedMax());\n\n APInt Upper;\n\n if (R.getUnsignedMin() == 0) {\n \/\/ Just because it contains zero, doesn't mean it will also contain one.\n \/\/ Use maximalIntersectWith to get the right behaviour.\n ConstantRange NotZero(APInt(L.getBitWidth(), 1),\n APInt::getNullValue(L.getBitWidth()));\n R = R.maximalIntersectWith(NotZero);\n }\n \n \/\/ But, the maximal intersection might still include zero. If it does, then\n \/\/ we know it also included one.\n if (R.contains(APInt::getNullValue(L.getBitWidth())))\n Upper = L.getUnsignedMax();\n else\n Upper = L.getUnsignedMax().udiv(R.getUnsignedMin());\n\n return ConstantRange(Lower, Upper);\n }\n\n \/\/ ConstantRange already implements the cast operators.\n\n if (SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, ZExt->getOperand()->getType());\n ConstantRange X = getRange(ZExt->getOperand(), T, SE);\n return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());\n }\n\n if (SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, SExt->getOperand()->getType());\n ConstantRange X = getRange(SExt->getOperand(), T, SE);\n return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());\n }\n\n if (SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, Trunc->getOperand()->getType());\n ConstantRange X = getRange(Trunc->getOperand(), T, SE);\n if (X.isFullSet()) return FullSet;\n return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());\n }\n\n if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {\n SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);\n if (!Trip) return FullSet;\n\n if (AddRec->isAffine()) {\n SCEVHandle StartHandle = AddRec->getStart();\n SCEVHandle StepHandle = AddRec->getOperand(1);\n\n SCEVConstant *Step = dyn_cast<SCEVConstant>(StepHandle);\n if (!Step) return FullSet;\n\n uint32_t ExWidth = 2 * Trip->getValue()->getBitWidth();\n APInt TripExt = Trip->getValue()->getValue(); TripExt.zext(ExWidth);\n APInt StepExt = Step->getValue()->getValue(); StepExt.zext(ExWidth);\n if ((TripExt * StepExt).ugt(APInt::getLowBitsSet(ExWidth, ExWidth >> 1)))\n return FullSet;\n\n SCEVHandle EndHandle = SE.getAddExpr(StartHandle,\n SE.getMulExpr(T, StepHandle));\n SCEVConstant *Start = dyn_cast<SCEVConstant>(StartHandle);\n SCEVConstant *End = dyn_cast<SCEVConstant>(EndHandle);\n if (!Start || !End) return FullSet;\n\n const APInt &StartInt = Start->getValue()->getValue();\n const APInt &EndInt = End->getValue()->getValue();\n const APInt &StepInt = Step->getValue()->getValue();\n\n if (StepInt.isNegative()) {\n if (EndInt == StartInt + 1) return FullSet;\n return ConstantRange(EndInt, StartInt + 1);\n } else {\n if (StartInt == EndInt + 1) return FullSet;\n return ConstantRange(StartInt, EndInt + 1);\n }\n }\n }\n\n \/\/ TODO: non-affine addrec, udiv, SCEVUnknown (narrowed from elsewhere)?\n\n return FullSet;\n}\n\nbool LoopVR::runOnFunction(Function &F) { Map.clear(); return false; }\n\nvoid LoopVR::print(std::ostream &os, const Module *) const {\n raw_os_ostream OS(os);\n for (std::map<Value *, ConstantRange *>::const_iterator I = Map.begin(),\n E = Map.end(); I != E; ++I) {\n OS << *I->first << \": \" << *I->second << '\\n';\n }\n}\n\nvoid LoopVR::releaseMemory() {\n for (std::map<Value *, ConstantRange *>::iterator I = Map.begin(),\n E = Map.end(); I != E; ++I) {\n delete I->second;\n }\n\n Map.clear(); \n}\n\nConstantRange LoopVR::compute(Value *V) {\n if (ConstantInt *CI = dyn_cast<ConstantInt>(V))\n return ConstantRange(CI->getValue());\n\n Instruction *I = dyn_cast<Instruction>(V);\n if (!I)\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n LoopInfo &LI = getAnalysis<LoopInfo>();\n\n Loop *L = LI.getLoopFor(I->getParent());\n if (!L || L->isLoopInvariant(I))\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n ScalarEvolution &SE = getAnalysis<ScalarEvolution>();\n\n SCEVHandle S = SE.getSCEV(I);\n if (isa<SCEVUnknown>(S) || isa<SCEVCouldNotCompute>(S))\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n return ConstantRange(getRange(S, L, SE));\n}\n\nConstantRange LoopVR::get(Value *V) {\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I == Map.end()) {\n ConstantRange *CR = new ConstantRange(compute(V));\n Map[V] = CR;\n return *CR;\n }\n\n return *I->second;\n}\n\nvoid LoopVR::remove(Value *V) {\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I != Map.end()) {\n delete I->second;\n Map.erase(I);\n }\n}\n\nvoid LoopVR::narrow(Value *V, const ConstantRange &CR) {\n if (CR.isFullSet()) return;\n\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I == Map.end())\n Map[V] = new ConstantRange(CR);\n else\n Map[V] = new ConstantRange(Map[V]->maximalIntersectWith(CR));\n}\n<commit_msg>More const qualifiers.<commit_after>\/\/===- LoopVR.cpp - Value Range analysis driven by loop information -------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ FIXME: What does this do?\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loopvr\"\n#include \"llvm\/Analysis\/LoopVR.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/ScalarEvolutionExpressions.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\nchar LoopVR::ID = 0;\nstatic RegisterPass<LoopVR> X(\"loopvr\", \"Loop Value Ranges\", false, true);\n\n\/\/\/ getRange - determine the range for a particular SCEV within a given Loop\nConstantRange LoopVR::getRange(SCEVHandle S, Loop *L, ScalarEvolution &SE) {\n SCEVHandle T = SE.getBackedgeTakenCount(L);\n if (isa<SCEVCouldNotCompute>(T))\n return ConstantRange(cast<IntegerType>(S->getType())->getBitWidth(), true);\n\n T = SE.getTruncateOrZeroExtend(T, S->getType());\n return getRange(S, T, SE);\n}\n\n\/\/\/ getRange - determine the range for a particular SCEV with a given trip count\nConstantRange LoopVR::getRange(SCEVHandle S, SCEVHandle T, ScalarEvolution &SE){\n\n if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))\n return ConstantRange(C->getValue()->getValue());\n\n ConstantRange FullSet(cast<IntegerType>(S->getType())->getBitWidth(), true);\n\n \/\/ {x,+,y,+,...z}. We detect overflow by checking the size of the set after\n \/\/ summing the upper and lower.\n if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n ConstantRange X = getRange(Add->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(Add->getOperand(i), T, SE);\n if (Y.isFullSet()) return FullSet;\n\n APInt Spread_X = X.getSetSize(), Spread_Y = Y.getSetSize();\n APInt NewLower = X.getLower() + Y.getLower();\n APInt NewUpper = X.getUpper() + Y.getUpper() - 1;\n if (NewLower == NewUpper)\n return FullSet;\n\n X = ConstantRange(NewLower, NewUpper);\n if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))\n return FullSet; \/\/ we've wrapped, therefore, full set.\n }\n return X;\n }\n\n \/\/ {x,*,y,*,...,z}. In order to detect overflow, we use k*bitwidth where\n \/\/ k is the number of terms being multiplied.\n if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {\n ConstantRange X = getRange(Mul->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n const IntegerType *Ty = IntegerType::get(X.getBitWidth());\n const IntegerType *ExTy = IntegerType::get(X.getBitWidth() *\n Mul->getNumOperands());\n ConstantRange XExt = X.zeroExtend(ExTy->getBitWidth());\n\n for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(Mul->getOperand(i), T, SE);\n if (Y.isFullSet()) return FullSet;\n\n ConstantRange YExt = Y.zeroExtend(ExTy->getBitWidth());\n XExt = ConstantRange(XExt.getLower() * YExt.getLower(),\n ((XExt.getUpper()-1) * (YExt.getUpper()-1)) + 1);\n }\n return XExt.truncate(Ty->getBitWidth());\n }\n\n \/\/ X smax Y smax ... Z is: range(smax(X_smin, Y_smin, ..., Z_smin),\n \/\/ smax(X_smax, Y_smax, ..., Z_smax))\n \/\/ It doesn't matter if one of the SCEVs has FullSet because we're taking\n \/\/ a maximum of the minimums across all of them.\n if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {\n ConstantRange X = getRange(SMax->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n APInt smin = X.getSignedMin(), smax = X.getSignedMax();\n for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(SMax->getOperand(i), T, SE);\n smin = APIntOps::smax(smin, Y.getSignedMin());\n smax = APIntOps::smax(smax, Y.getSignedMax());\n }\n if (smax + 1 == smin) return FullSet;\n return ConstantRange(smin, smax + 1);\n }\n\n \/\/ X umax Y umax ... Z is: range(umax(X_umin, Y_umin, ..., Z_umin),\n \/\/ umax(X_umax, Y_umax, ..., Z_umax))\n \/\/ It doesn't matter if one of the SCEVs has FullSet because we're taking\n \/\/ a maximum of the minimums across all of them.\n if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {\n ConstantRange X = getRange(UMax->getOperand(0), T, SE);\n if (X.isFullSet()) return FullSet;\n\n APInt umin = X.getUnsignedMin(), umax = X.getUnsignedMax();\n for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) {\n ConstantRange Y = getRange(UMax->getOperand(i), T, SE);\n umin = APIntOps::umax(umin, Y.getUnsignedMin());\n umax = APIntOps::umax(umax, Y.getUnsignedMax());\n }\n if (umax + 1 == umin) return FullSet;\n return ConstantRange(umin, umax + 1);\n }\n\n \/\/ L udiv R. Luckily, there's only ever 2 sides to a udiv.\n if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {\n ConstantRange L = getRange(UDiv->getLHS(), T, SE);\n ConstantRange R = getRange(UDiv->getRHS(), T, SE);\n if (L.isFullSet() && R.isFullSet()) return FullSet;\n\n if (R.getUnsignedMax() == 0) {\n \/\/ RHS must be single-element zero. Return an empty set.\n return ConstantRange(R.getBitWidth(), false);\n }\n\n APInt Lower = L.getUnsignedMin().udiv(R.getUnsignedMax());\n\n APInt Upper;\n\n if (R.getUnsignedMin() == 0) {\n \/\/ Just because it contains zero, doesn't mean it will also contain one.\n \/\/ Use maximalIntersectWith to get the right behaviour.\n ConstantRange NotZero(APInt(L.getBitWidth(), 1),\n APInt::getNullValue(L.getBitWidth()));\n R = R.maximalIntersectWith(NotZero);\n }\n \n \/\/ But, the maximal intersection might still include zero. If it does, then\n \/\/ we know it also included one.\n if (R.contains(APInt::getNullValue(L.getBitWidth())))\n Upper = L.getUnsignedMax();\n else\n Upper = L.getUnsignedMax().udiv(R.getUnsignedMin());\n\n return ConstantRange(Lower, Upper);\n }\n\n \/\/ ConstantRange already implements the cast operators.\n\n if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, ZExt->getOperand()->getType());\n ConstantRange X = getRange(ZExt->getOperand(), T, SE);\n return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());\n }\n\n if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, SExt->getOperand()->getType());\n ConstantRange X = getRange(SExt->getOperand(), T, SE);\n return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());\n }\n\n if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {\n T = SE.getTruncateOrZeroExtend(T, Trunc->getOperand()->getType());\n ConstantRange X = getRange(Trunc->getOperand(), T, SE);\n if (X.isFullSet()) return FullSet;\n return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());\n }\n\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {\n const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);\n if (!Trip) return FullSet;\n\n if (AddRec->isAffine()) {\n SCEVHandle StartHandle = AddRec->getStart();\n SCEVHandle StepHandle = AddRec->getOperand(1);\n\n const SCEVConstant *Step = dyn_cast<SCEVConstant>(StepHandle);\n if (!Step) return FullSet;\n\n uint32_t ExWidth = 2 * Trip->getValue()->getBitWidth();\n APInt TripExt = Trip->getValue()->getValue(); TripExt.zext(ExWidth);\n APInt StepExt = Step->getValue()->getValue(); StepExt.zext(ExWidth);\n if ((TripExt * StepExt).ugt(APInt::getLowBitsSet(ExWidth, ExWidth >> 1)))\n return FullSet;\n\n SCEVHandle EndHandle = SE.getAddExpr(StartHandle,\n SE.getMulExpr(T, StepHandle));\n const SCEVConstant *Start = dyn_cast<SCEVConstant>(StartHandle);\n const SCEVConstant *End = dyn_cast<SCEVConstant>(EndHandle);\n if (!Start || !End) return FullSet;\n\n const APInt &StartInt = Start->getValue()->getValue();\n const APInt &EndInt = End->getValue()->getValue();\n const APInt &StepInt = Step->getValue()->getValue();\n\n if (StepInt.isNegative()) {\n if (EndInt == StartInt + 1) return FullSet;\n return ConstantRange(EndInt, StartInt + 1);\n } else {\n if (StartInt == EndInt + 1) return FullSet;\n return ConstantRange(StartInt, EndInt + 1);\n }\n }\n }\n\n \/\/ TODO: non-affine addrec, udiv, SCEVUnknown (narrowed from elsewhere)?\n\n return FullSet;\n}\n\nbool LoopVR::runOnFunction(Function &F) { Map.clear(); return false; }\n\nvoid LoopVR::print(std::ostream &os, const Module *) const {\n raw_os_ostream OS(os);\n for (std::map<Value *, ConstantRange *>::const_iterator I = Map.begin(),\n E = Map.end(); I != E; ++I) {\n OS << *I->first << \": \" << *I->second << '\\n';\n }\n}\n\nvoid LoopVR::releaseMemory() {\n for (std::map<Value *, ConstantRange *>::iterator I = Map.begin(),\n E = Map.end(); I != E; ++I) {\n delete I->second;\n }\n\n Map.clear(); \n}\n\nConstantRange LoopVR::compute(Value *V) {\n if (ConstantInt *CI = dyn_cast<ConstantInt>(V))\n return ConstantRange(CI->getValue());\n\n Instruction *I = dyn_cast<Instruction>(V);\n if (!I)\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n LoopInfo &LI = getAnalysis<LoopInfo>();\n\n Loop *L = LI.getLoopFor(I->getParent());\n if (!L || L->isLoopInvariant(I))\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n ScalarEvolution &SE = getAnalysis<ScalarEvolution>();\n\n SCEVHandle S = SE.getSCEV(I);\n if (isa<SCEVUnknown>(S) || isa<SCEVCouldNotCompute>(S))\n return ConstantRange(cast<IntegerType>(V->getType())->getBitWidth(), false);\n\n return ConstantRange(getRange(S, L, SE));\n}\n\nConstantRange LoopVR::get(Value *V) {\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I == Map.end()) {\n ConstantRange *CR = new ConstantRange(compute(V));\n Map[V] = CR;\n return *CR;\n }\n\n return *I->second;\n}\n\nvoid LoopVR::remove(Value *V) {\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I != Map.end()) {\n delete I->second;\n Map.erase(I);\n }\n}\n\nvoid LoopVR::narrow(Value *V, const ConstantRange &CR) {\n if (CR.isFullSet()) return;\n\n std::map<Value *, ConstantRange *>::iterator I = Map.find(V);\n if (I == Map.end())\n Map[V] = new ConstantRange(CR);\n else\n Map[V] = new ConstantRange(Map[V]->maximalIntersectWith(CR));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual \n\/\/ Properties, Inc., University of Heidelberg, and The University \n\/\/ of Manchester. \n\/\/ All rights reserved. \n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual \n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg, \n\/\/ and The University of Manchester. \n\/\/ All rights reserved. \n\n\/\/ Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual \n\/\/ Properties, Inc. and EML Research, gGmbH. \n\/\/ All rights reserved. \n\n\/\/*** In this file I have put \"\/\/+++\" in all places where something has to be added\n\/\/*** if a new scan item is introduced.\n\n#include <QtGui\/QLabel>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QLayout>\n#include <QtGui\/QToolTip>\n#include <QtGui\/QWhatsThis>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QGridLayout>\n#include <QtGui\/QHBoxLayout>\n\n#include <QtGui\/QInputDialog>\n\n#include \"copasi.h\"\n\n#include \"ScanWidget.h\"\n#include \"scan\/CScanTask.h\"\n#include \"scan\/CScanProblem.h\"\n#include \"scan\/CScanMethod.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"CQSimpleSelectionTree.h\"\n#include \"CCopasiSelectionDialog.h\"\n\n#include \"report\/CKeyFactory.h\"\n#include \"qtUtilities.h\"\n#include \"CScanContainerWidget.h\"\n#include \"utilities\/CopasiTime.h\"\n\n\/\/+++\n\/\/#include \"CScanWidgetBreak.h\"\n#include \"CScanWidgetRandom.h\"\n#include \"CScanWidgetRepeat.h\"\n#include \"CScanWidgetScan.h\"\n#include \"CScanWidgetTask.h\"\n\nScanWidget::ScanWidget(QWidget* parent, const char* name, Qt::WFlags f)\n : TaskWidget(parent, name, f)\n{\n if (!name)\n setObjectName(\"ScanWidget\");\n\n setWindowTitle(trUtf8(\"ScanWidget\"));\n ScanWidgetLayout = new QGridLayout(this);\n ScanWidgetLayout->setMargin(11);\n ScanWidgetLayout->setSpacing(6);\n ScanWidgetLayout->setObjectName(\"ScanWidgetLayout\");\n\n mpHeaderWidget->setTaskName(\"Parameter Scan\");\n\n ScanWidgetLayout->addWidget(mpHeaderWidget, 0, 0);\n\n mpBtnWidget->verticalLayout->removeItem(mpBtnWidget->verticalSpacer);\n ScanWidgetLayout->addWidget(mpBtnWidget, 3, 0);\n\n \/\/*****************\n\n QHBoxLayout* tmpLayout = new QHBoxLayout();\n\n QSpacerItem* tmpSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);\n tmpLayout->addItem(tmpSpacer);\n\n QLabel* tmpLabel = new QLabel(this);\n tmpLabel->setText(\"New scan item: \");\n tmpLayout->addWidget(tmpLabel);\n\n comboType = new QComboBox(this);\n \/\/+++\n comboType->insertItem(0, \"Scan\");\n comboType->insertItem(0, \"Repeat\");\n comboType->insertItem(0, \"Random distribution\");\n tmpLayout->addWidget(comboType);\n\n QSpacerItem *mpSpacer = new QSpacerItem(20, 20, QSizePolicy::Maximum, QSizePolicy::Minimum);\n tmpLayout->addItem(mpSpacer);\n\n buttonNewItem = new QPushButton(this);\n buttonNewItem->setObjectName(\"buttonNewItem\");\n buttonNewItem->setText(\"Create\");\n \/\/ScanWidgetLayout->addWidget(buttonNewItem, 1, 2);\n tmpLayout->addWidget(buttonNewItem);\n\n ScanWidgetLayout->addLayout(tmpLayout, 1, 0);\n\n \/\/*****************************\n\n scrollview = new CScanContainerWidget(this);\n ScanWidgetLayout->addWidget(scrollview, 2, 0);\n\n \/\/ tab order\n \/*setTabOrder(taskName, sExecutable);\n setTabOrder(sExecutable, steadyState);*\/\n\n connect(buttonNewItem, SIGNAL(clicked()), this, SLOT(slotAddItem()));\n}\n\nScanWidget::~ScanWidget()\n{}\n\nbool ScanWidget::runTask()\n{\n if (!commonBeforeRunTask()) return false;\n\n bool success = true;\n\n if (!commonRunTask()) success = false;\n\n return success;\n}\n\nbool ScanWidget::loadTask()\n{\n loadCommon();\n\n CScanTask* scanTask =\n dynamic_cast< CScanTask * >(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (!scanTask) return false;\n\n CScanProblem *scanProblem = dynamic_cast<CScanProblem *>(scanTask->getProblem());\n\n if (!scanProblem) return false;\n\n scrollview->clearWidgetList();\n\n \/\/std::vector<QWidget*> & widgetList = scrollview->getWidgetList();\n\n \/\/+++\n CScanWidgetScan* tmp1;\n CScanWidgetRepeat* tmp2;\n CScanWidgetRandom* tmp3;\n \/\/CScanWidgetBreak* tmp4;\n\n \/\/ the scan items\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n \/\/CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];\n \/\/assert(pDataModel != NULL);\n size_t i, imax = scanProblem->getNumberOfScanItems();\n\n for (i = 0; i < imax; ++i)\n {\n void * pTmp;\n\n if (!(pTmp = scanProblem->getScanItem(i)->getValue(\"Type\").pVOID)) return false;\n\n CScanProblem::Type type = *(CScanProblem::Type*)pTmp;\n\n switch (type)\n {\n \/\/+++\n case CScanProblem::SCAN_LINEAR:\n tmp1 = new CScanWidgetScan(scrollview);\n tmp1->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp1);\n break;\n\n case CScanProblem::SCAN_REPEAT:\n tmp2 = new CScanWidgetRepeat(scrollview);\n tmp2->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp2);\n break;\n\n case CScanProblem::SCAN_RANDOM:\n tmp3 = new CScanWidgetRandom(scrollview);\n tmp3->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp3);\n break;\n\n default:\n break;\n }\n }\n\n \/\/ the widget for the subtask\n CScanWidgetTask* tmpT = new CScanWidgetTask(scrollview);\n tmpT->load(scanProblem);\n scrollview->addWidget(tmpT, false); \/\/false: no control buttons (up\/down\/del)\n\n mChanged = false;\n\n return true;\n}\n\nbool ScanWidget::slotAddItem()\n{\n int totalRows = -1;\n \/\/+++\n CScanWidgetScan* tmp1;\n CScanWidgetRepeat* tmp2;\n CScanWidgetRandom* tmp3;\n \/\/CScanWidgetBreak* tmp4;\n\n int intType = comboType->currentIndex();\n CScanProblem::Type type;\n\n switch (intType)\n {\n case 0:\n type = CScanProblem::SCAN_LINEAR;\n break;\n\n case 1:\n type = CScanProblem::SCAN_REPEAT;\n break;\n\n case 2:\n type = CScanProblem::SCAN_RANDOM;\n break;\n\n default:\n type = CScanProblem::SCAN_LINEAR;\n break;\n }\n\n switch (type)\n {\n case CScanProblem::SCAN_REPEAT:\n {\n tmp2 = new CScanWidgetRepeat(scrollview);\n\n \/\/create item to get the default values\n CCopasiParameterGroup* pItem = CScanProblem::createScanItem(type, 10);\n tmp2->load(pItem);\n pdelete(pItem);\n\n scrollview->insertWidget(tmp2);\n totalRows = scrollview->rowCount();\n tmp2->lineEditNumber->setFocus();\n }\n break;\n\n case CScanProblem::SCAN_LINEAR:\n {\n CQSimpleSelectionTree::ObjectClasses Classes = CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters;\n\n std::vector< const CCopasiObject * > Selection = CCopasiSelectionDialog::getObjectVector(this, Classes);\n\n \/\/ create scan widgets as many as the number of selected objects\n std::vector< const CCopasiObject * >::iterator it = Selection.begin();\n std::vector< const CCopasiObject * >::iterator end = Selection.end();\n\n for (; it != end; ++it)\n {\n tmp1 = new CScanWidgetScan(scrollview);\n tmp1->initFromObject(*it);\n scrollview->insertWidget(tmp1);\n totalRows = scrollview->rowCount();\n tmp1->lineEditMin->setFocus();\n }\n\n break;\n }\n\n case CScanProblem::SCAN_RANDOM:\n {\n CQSimpleSelectionTree::ObjectClasses Classes = CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters;\n\n std::vector< const CCopasiObject * > Selection = CCopasiSelectionDialog::getObjectVector(this, Classes);\n\n \/\/ create scan widgets as many as the number of selected objects\n std::vector< const CCopasiObject * >::iterator it = Selection.begin();\n std::vector< const CCopasiObject * >::iterator end = Selection.end();\n\n for (; it != end; ++it)\n {\n tmp3 = new CScanWidgetRandom(scrollview);\n tmp3->initFromObject(*it);\n scrollview->insertWidget(tmp3);\n totalRows = scrollview->rowCount();\n tmp3->lineEditMin->setFocus();\n }\n\n break;\n }\n\n default:\n break;\n }\n\n return true;\n}\n\nbool ScanWidget::saveTask()\n{\n saveCommon();\n\n CScanTask* scanTask =\n dynamic_cast< CScanTask * >(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (!scanTask) return false;\n\n CScanProblem *scanProblem = dynamic_cast<CScanProblem *>(scanTask->getProblem());\n\n if (!scanProblem) return false;\n\n const std::vector< QWidget * > & widgetList = scrollview->getWidgetList();\n\n size_t newSize = widgetList.size() - 1; \/\/ The last widget is reserved for the subtask.\n size_t oldSize = scanProblem->getNumberOfScanItems();\n\n size_t i, imax = std::min(newSize, oldSize);\n\n mChanged = false;\n\n for (i = 0; i < imax; ++i)\n {\n QWidget * pWidget = widgetList[i];\n\n if (pWidget->objectName() == \"CScanWidgetScan\")\n {\n mChanged |= static_cast< CScanWidgetScan * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n else if (pWidget->objectName() == \"CScanWidgetRandom\")\n {\n mChanged |= static_cast< CScanWidgetRandom * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n else if (pWidget->objectName() == \"CScanWidgetRepeat\")\n {\n mChanged |= static_cast< CScanWidgetRepeat * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n }\n\n for (; i < newSize; ++i)\n {\n mChanged = true;\n QWidget * pWidget = widgetList[i];\n CCopasiParameterGroup * pItem = scanProblem->addScanItem(CScanProblem::SCAN_LINEAR);\n\n if (pWidget->objectName() == \"CScanWidgetScan\")\n {\n static_cast< CScanWidgetScan * >(pWidget)->save(pItem);\n }\n else if (pWidget->objectName() == \"CScanWidgetRandom\")\n {\n static_cast< CScanWidgetRandom * >(pWidget)->save(pItem);\n }\n else if (pWidget->objectName() == \"CScanWidgetRepeat\")\n {\n static_cast< CScanWidgetRepeat * >(pWidget)->save(pItem);\n }\n }\n\n for (; i < oldSize; ++i)\n {\n mChanged = true;\n scanProblem->removeScanItem(newSize);\n }\n\n \/\/ the subtask\n const CScanWidgetTask * tmpT = dynamic_cast<CScanWidgetTask*>(widgetList[newSize]);\n\n if (tmpT != NULL)\n {\n mChanged |= tmpT->save(scanProblem);\n }\n\n \/\/ :TODO Bug 322: This should only be called when actual changes have been saved.\n \/\/ However we do not check whether the scan item are mChanged we delete all\n \/\/ and create them new.\n if (mChanged)\n {\n if (mpDataModel != NULL)\n {\n mpDataModel->changed();\n }\n\n mChanged = false;\n }\n\n return true;\n}\n<commit_msg>Bug 2000. The combo box items were inserted into the front instead of appended to the list creating an incorrect order.<commit_after>\/\/ Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n\/\/*** In this file I have put \"\/\/+++\" in all places where something has to be added\n\/\/*** if a new scan item is introduced.\n\n#include <QtGui\/QLabel>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QLayout>\n#include <QtGui\/QToolTip>\n#include <QtGui\/QWhatsThis>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QGridLayout>\n#include <QtGui\/QHBoxLayout>\n\n#include <QtGui\/QInputDialog>\n\n#include \"copasi.h\"\n\n#include \"ScanWidget.h\"\n#include \"scan\/CScanTask.h\"\n#include \"scan\/CScanProblem.h\"\n#include \"scan\/CScanMethod.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"CQSimpleSelectionTree.h\"\n#include \"CCopasiSelectionDialog.h\"\n\n#include \"report\/CKeyFactory.h\"\n#include \"qtUtilities.h\"\n#include \"CScanContainerWidget.h\"\n#include \"utilities\/CopasiTime.h\"\n\n\/\/+++\n\/\/#include \"CScanWidgetBreak.h\"\n#include \"CScanWidgetRandom.h\"\n#include \"CScanWidgetRepeat.h\"\n#include \"CScanWidgetScan.h\"\n#include \"CScanWidgetTask.h\"\n\nScanWidget::ScanWidget(QWidget* parent, const char* name, Qt::WFlags f)\n : TaskWidget(parent, name, f)\n{\n if (!name)\n setObjectName(\"ScanWidget\");\n\n setWindowTitle(trUtf8(\"ScanWidget\"));\n ScanWidgetLayout = new QGridLayout(this);\n ScanWidgetLayout->setMargin(11);\n ScanWidgetLayout->setSpacing(6);\n ScanWidgetLayout->setObjectName(\"ScanWidgetLayout\");\n\n mpHeaderWidget->setTaskName(\"Parameter Scan\");\n\n ScanWidgetLayout->addWidget(mpHeaderWidget, 0, 0);\n\n mpBtnWidget->verticalLayout->removeItem(mpBtnWidget->verticalSpacer);\n ScanWidgetLayout->addWidget(mpBtnWidget, 3, 0);\n\n \/\/*****************\n\n QHBoxLayout* tmpLayout = new QHBoxLayout();\n\n QSpacerItem* tmpSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);\n tmpLayout->addItem(tmpSpacer);\n\n QLabel* tmpLabel = new QLabel(this);\n tmpLabel->setText(\"New scan item: \");\n tmpLayout->addWidget(tmpLabel);\n\n comboType = new QComboBox(this);\n \/\/+++\n comboType->addItem(\"Scan\");\n comboType->addItem(\"Repeat\");\n comboType->addItem(\"Random distribution\");\n tmpLayout->addWidget(comboType);\n\n QSpacerItem *mpSpacer = new QSpacerItem(20, 20, QSizePolicy::Maximum, QSizePolicy::Minimum);\n tmpLayout->addItem(mpSpacer);\n\n buttonNewItem = new QPushButton(this);\n buttonNewItem->setObjectName(\"buttonNewItem\");\n buttonNewItem->setText(\"Create\");\n \/\/ScanWidgetLayout->addWidget(buttonNewItem, 1, 2);\n tmpLayout->addWidget(buttonNewItem);\n\n ScanWidgetLayout->addLayout(tmpLayout, 1, 0);\n\n \/\/*****************************\n\n scrollview = new CScanContainerWidget(this);\n ScanWidgetLayout->addWidget(scrollview, 2, 0);\n\n \/\/ tab order\n \/*setTabOrder(taskName, sExecutable);\n setTabOrder(sExecutable, steadyState);*\/\n\n connect(buttonNewItem, SIGNAL(clicked()), this, SLOT(slotAddItem()));\n}\n\nScanWidget::~ScanWidget()\n{}\n\nbool ScanWidget::runTask()\n{\n if (!commonBeforeRunTask()) return false;\n\n bool success = true;\n\n if (!commonRunTask()) success = false;\n\n return success;\n}\n\nbool ScanWidget::loadTask()\n{\n loadCommon();\n\n CScanTask* scanTask =\n dynamic_cast< CScanTask * >(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (!scanTask) return false;\n\n CScanProblem *scanProblem = dynamic_cast<CScanProblem *>(scanTask->getProblem());\n\n if (!scanProblem) return false;\n\n scrollview->clearWidgetList();\n\n \/\/std::vector<QWidget*> & widgetList = scrollview->getWidgetList();\n\n \/\/+++\n CScanWidgetScan* tmp1;\n CScanWidgetRepeat* tmp2;\n CScanWidgetRandom* tmp3;\n \/\/CScanWidgetBreak* tmp4;\n\n \/\/ the scan items\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n \/\/CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];\n \/\/assert(pDataModel != NULL);\n size_t i, imax = scanProblem->getNumberOfScanItems();\n\n for (i = 0; i < imax; ++i)\n {\n void * pTmp;\n\n if (!(pTmp = scanProblem->getScanItem(i)->getValue(\"Type\").pVOID)) return false;\n\n CScanProblem::Type type = *(CScanProblem::Type*)pTmp;\n\n switch (type)\n {\n \/\/+++\n case CScanProblem::SCAN_LINEAR:\n tmp1 = new CScanWidgetScan(scrollview);\n tmp1->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp1);\n break;\n\n case CScanProblem::SCAN_REPEAT:\n tmp2 = new CScanWidgetRepeat(scrollview);\n tmp2->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp2);\n break;\n\n case CScanProblem::SCAN_RANDOM:\n tmp3 = new CScanWidgetRandom(scrollview);\n tmp3->load(scanProblem->getScanItem(i));\n scrollview->addWidget(tmp3);\n break;\n\n default:\n break;\n }\n }\n\n \/\/ the widget for the subtask\n CScanWidgetTask* tmpT = new CScanWidgetTask(scrollview);\n tmpT->load(scanProblem);\n scrollview->addWidget(tmpT, false); \/\/false: no control buttons (up\/down\/del)\n\n mChanged = false;\n\n return true;\n}\n\nbool ScanWidget::slotAddItem()\n{\n int totalRows = -1;\n \/\/+++\n CScanWidgetScan* tmp1;\n CScanWidgetRepeat* tmp2;\n CScanWidgetRandom* tmp3;\n \/\/CScanWidgetBreak* tmp4;\n\n int intType = comboType->currentIndex();\n CScanProblem::Type type;\n\n switch (intType)\n {\n case 0:\n type = CScanProblem::SCAN_LINEAR;\n break;\n\n case 1:\n type = CScanProblem::SCAN_REPEAT;\n break;\n\n case 2:\n type = CScanProblem::SCAN_RANDOM;\n break;\n\n default:\n type = CScanProblem::SCAN_LINEAR;\n break;\n }\n\n switch (type)\n {\n case CScanProblem::SCAN_REPEAT:\n {\n tmp2 = new CScanWidgetRepeat(scrollview);\n\n \/\/create item to get the default values\n CCopasiParameterGroup* pItem = CScanProblem::createScanItem(type, 10);\n tmp2->load(pItem);\n pdelete(pItem);\n\n scrollview->insertWidget(tmp2);\n totalRows = scrollview->rowCount();\n tmp2->lineEditNumber->setFocus();\n }\n break;\n\n case CScanProblem::SCAN_LINEAR:\n {\n CQSimpleSelectionTree::ObjectClasses Classes = CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters;\n\n std::vector< const CCopasiObject * > Selection = CCopasiSelectionDialog::getObjectVector(this, Classes);\n\n \/\/ create scan widgets as many as the number of selected objects\n std::vector< const CCopasiObject * >::iterator it = Selection.begin();\n std::vector< const CCopasiObject * >::iterator end = Selection.end();\n\n for (; it != end; ++it)\n {\n tmp1 = new CScanWidgetScan(scrollview);\n tmp1->initFromObject(*it);\n scrollview->insertWidget(tmp1);\n totalRows = scrollview->rowCount();\n tmp1->lineEditMin->setFocus();\n }\n\n break;\n }\n\n case CScanProblem::SCAN_RANDOM:\n {\n CQSimpleSelectionTree::ObjectClasses Classes = CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters;\n\n std::vector< const CCopasiObject * > Selection = CCopasiSelectionDialog::getObjectVector(this, Classes);\n\n \/\/ create scan widgets as many as the number of selected objects\n std::vector< const CCopasiObject * >::iterator it = Selection.begin();\n std::vector< const CCopasiObject * >::iterator end = Selection.end();\n\n for (; it != end; ++it)\n {\n tmp3 = new CScanWidgetRandom(scrollview);\n tmp3->initFromObject(*it);\n scrollview->insertWidget(tmp3);\n totalRows = scrollview->rowCount();\n tmp3->lineEditMin->setFocus();\n }\n\n break;\n }\n\n default:\n break;\n }\n\n return true;\n}\n\nbool ScanWidget::saveTask()\n{\n saveCommon();\n\n CScanTask* scanTask =\n dynamic_cast< CScanTask * >(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (!scanTask) return false;\n\n CScanProblem *scanProblem = dynamic_cast<CScanProblem *>(scanTask->getProblem());\n\n if (!scanProblem) return false;\n\n const std::vector< QWidget * > & widgetList = scrollview->getWidgetList();\n\n size_t newSize = widgetList.size() - 1; \/\/ The last widget is reserved for the subtask.\n size_t oldSize = scanProblem->getNumberOfScanItems();\n\n size_t i, imax = std::min(newSize, oldSize);\n\n mChanged = false;\n\n for (i = 0; i < imax; ++i)\n {\n QWidget * pWidget = widgetList[i];\n\n if (pWidget->objectName() == \"CScanWidgetScan\")\n {\n mChanged |= static_cast< CScanWidgetScan * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n else if (pWidget->objectName() == \"CScanWidgetRandom\")\n {\n mChanged |= static_cast< CScanWidgetRandom * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n else if (pWidget->objectName() == \"CScanWidgetRepeat\")\n {\n mChanged |= static_cast< CScanWidgetRepeat * >(pWidget)->save(scanProblem->getScanItem(i));\n }\n }\n\n for (; i < newSize; ++i)\n {\n mChanged = true;\n QWidget * pWidget = widgetList[i];\n CCopasiParameterGroup * pItem = scanProblem->addScanItem(CScanProblem::SCAN_LINEAR);\n\n if (pWidget->objectName() == \"CScanWidgetScan\")\n {\n static_cast< CScanWidgetScan * >(pWidget)->save(pItem);\n }\n else if (pWidget->objectName() == \"CScanWidgetRandom\")\n {\n static_cast< CScanWidgetRandom * >(pWidget)->save(pItem);\n }\n else if (pWidget->objectName() == \"CScanWidgetRepeat\")\n {\n static_cast< CScanWidgetRepeat * >(pWidget)->save(pItem);\n }\n }\n\n for (; i < oldSize; ++i)\n {\n mChanged = true;\n scanProblem->removeScanItem(newSize);\n }\n\n \/\/ the subtask\n const CScanWidgetTask * tmpT = dynamic_cast<CScanWidgetTask*>(widgetList[newSize]);\n\n if (tmpT != NULL)\n {\n mChanged |= tmpT->save(scanProblem);\n }\n\n \/\/ :TODO Bug 322: This should only be called when actual changes have been saved.\n \/\/ However we do not check whether the scan item are mChanged we delete all\n \/\/ and create them new.\n if (mChanged)\n {\n if (mpDataModel != NULL)\n {\n mpDataModel->changed();\n }\n\n mChanged = false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- SourceLoc.cpp - SourceLoc and SourceRange implementations --------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/SourceLoc.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace swift;\n\nvoid SourceManager::verifyAllBuffers() const {\n llvm::PrettyStackTraceString backtrace{\n \"Checking that all source buffers are still valid\"\n };\n\n \/\/ FIXME: This depends on the buffer IDs chosen by llvm::SourceMgr.\n LLVM_ATTRIBUTE_USED static char arbitraryTotal = 0;\n for (unsigned i = 1, e = LLVMSourceMgr.getNumBuffers(); i <= e; ++i) {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(i);\n if (buffer->getBufferSize() == 0)\n continue;\n arbitraryTotal += buffer->getBufferStart()[0];\n arbitraryTotal += buffer->getBufferEnd()[-1];\n }\n}\n\nSourceLoc SourceManager::getCodeCompletionLoc() const {\n if (CodeCompletionBufferID == 0U)\n return SourceLoc();\n\n return getLocForBufferStart(CodeCompletionBufferID)\n .getAdvancedLoc(CodeCompletionOffset);\n}\n\nStringRef SourceManager::getDisplayNameForLoc(SourceLoc Loc) const {\n \/\/ Respect #line first\n if (auto VFile = getVirtualFile(Loc))\n return VFile->Name;\n\n \/\/ Next, try the stat cache\n auto Ident = getIdentifierForBuffer(findBufferContainingLoc(Loc));\n auto found = StatusCache.find(Ident);\n if (found != StatusCache.end()) {\n return found->second.getName();\n }\n\n \/\/ Populate the cache with a (virtual) stat.\n if (auto Status = FileSystem->status(Ident)) {\n return (StatusCache[Ident] = Status.get()).getName();\n }\n\n \/\/ Finally, fall back to the buffer identifier.\n return Ident;\n}\n\nunsigned\nSourceManager::addNewSourceBuffer(std::unique_ptr<llvm::MemoryBuffer> Buffer) {\n assert(Buffer);\n StringRef BufIdentifier = Buffer->getBufferIdentifier();\n auto ID = LLVMSourceMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());\n BufIdentIDMap[BufIdentifier] = ID;\n return ID;\n}\n\nunsigned SourceManager::addMemBufferCopy(llvm::MemoryBuffer *Buffer) {\n return addMemBufferCopy(Buffer->getBuffer(), Buffer->getBufferIdentifier());\n}\n\nunsigned SourceManager::addMemBufferCopy(StringRef InputData,\n StringRef BufIdentifier) {\n auto Buffer = std::unique_ptr<llvm::MemoryBuffer>(\n llvm::MemoryBuffer::getMemBufferCopy(InputData, BufIdentifier));\n return addNewSourceBuffer(std::move(Buffer));\n}\n\nbool SourceManager::openVirtualFile(SourceLoc loc, StringRef name,\n int lineOffset) {\n CharSourceRange fullRange = getRangeForBuffer(findBufferContainingLoc(loc));\n SourceLoc end;\n\n auto nextRangeIter = VirtualFiles.upper_bound(loc.Value.getPointer());\n if (nextRangeIter != VirtualFiles.end() &&\n fullRange.contains(nextRangeIter->second.Range.getStart())) {\n const VirtualFile &existingFile = nextRangeIter->second;\n if (existingFile.Range.getStart() == loc) {\n assert(existingFile.Name == name);\n assert(existingFile.LineOffset == lineOffset);\n return false;\n }\n assert(!existingFile.Range.contains(loc) &&\n \"must close current open file first\");\n end = nextRangeIter->second.Range.getStart();\n } else {\n end = fullRange.getEnd();\n }\n\n CharSourceRange range = CharSourceRange(*this, loc, end);\n VirtualFiles[end.Value.getPointer()] = {range, name.str(), lineOffset};\n CachedVFile = {nullptr, nullptr};\n return true;\n}\n\nvoid SourceManager::closeVirtualFile(SourceLoc end) {\n auto *virtualFile = const_cast<VirtualFile *>(getVirtualFile(end));\n if (!virtualFile) {\n#ifndef NDEBUG\n unsigned bufferID = findBufferContainingLoc(end);\n CharSourceRange fullRange = getRangeForBuffer(bufferID);\n assert((fullRange.getByteLength() == 0 ||\n getVirtualFile(end.getAdvancedLoc(-1))) &&\n \"no open virtual file for this location\");\n assert(fullRange.getEnd() == end);\n#endif\n return;\n }\n CachedVFile = {nullptr, nullptr};\n\n CharSourceRange oldRange = virtualFile->Range;\n virtualFile->Range = CharSourceRange(*this, virtualFile->Range.getStart(),\n end);\n VirtualFiles[end.Value.getPointer()] = std::move(*virtualFile);\n\n bool existed = VirtualFiles.erase(oldRange.getEnd().Value.getPointer());\n assert(existed);\n (void)existed;\n}\n\nconst SourceManager::VirtualFile *\nSourceManager::getVirtualFile(SourceLoc Loc) const {\n const char *p = Loc.Value.getPointer();\n\n if (CachedVFile.first == p)\n return CachedVFile.second;\n\n \/\/ Returns the first element that is >p.\n auto VFileIt = VirtualFiles.upper_bound(p);\n if (VFileIt != VirtualFiles.end() && VFileIt->second.Range.contains(Loc)) {\n CachedVFile = { p, &VFileIt->second };\n return CachedVFile.second;\n }\n\n return nullptr;\n}\n\nOptional<unsigned>\nSourceManager::getIDForBufferIdentifier(StringRef BufIdentifier) const {\n auto It = BufIdentIDMap.find(BufIdentifier);\n if (It == BufIdentIDMap.end())\n return None;\n return It->second;\n}\n\nStringRef SourceManager::getIdentifierForBuffer(unsigned bufferID) const {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);\n assert(buffer && \"invalid buffer ID\");\n return buffer->getBufferIdentifier();\n}\n\nCharSourceRange SourceManager::getRangeForBuffer(unsigned bufferID) const {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);\n SourceLoc start{llvm::SMLoc::getFromPointer(buffer->getBufferStart())};\n return CharSourceRange(start, buffer->getBufferSize());\n}\n\nunsigned SourceManager::getLocOffsetInBuffer(SourceLoc Loc,\n unsigned BufferID) const {\n assert(Loc.isValid() && \"location should be valid\");\n auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);\n assert(Loc.Value.getPointer() >= Buffer->getBuffer().begin() &&\n Loc.Value.getPointer() <= Buffer->getBuffer().end() &&\n \"Location is not from the specified buffer\");\n return Loc.Value.getPointer() - Buffer->getBuffer().begin();\n}\n\nunsigned SourceManager::getByteDistance(SourceLoc Start, SourceLoc End) const {\n assert(Start.isValid() && \"start location should be valid\");\n assert(End.isValid() && \"end location should be valid\");\n#ifndef NDEBUG\n unsigned BufferID = findBufferContainingLoc(Start);\n auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);\n assert(End.Value.getPointer() >= Buffer->getBuffer().begin() &&\n End.Value.getPointer() <= Buffer->getBuffer().end() &&\n \"End location is not from the same buffer\");\n#endif\n \/\/ When we have a rope buffer, could be implemented in terms of\n \/\/ getLocOffsetInBuffer().\n return End.Value.getPointer() - Start.Value.getPointer();\n}\n\nStringRef SourceManager::getEntireTextForBuffer(unsigned BufferID) const {\n return LLVMSourceMgr.getMemoryBuffer(BufferID)->getBuffer();\n}\n\nStringRef SourceManager::extractText(CharSourceRange Range,\n Optional<unsigned> BufferID) const {\n assert(Range.isValid() && \"range should be valid\");\n\n if (!BufferID)\n BufferID = findBufferContainingLoc(Range.getStart());\n StringRef Buffer = LLVMSourceMgr.getMemoryBuffer(*BufferID)->getBuffer();\n return Buffer.substr(getLocOffsetInBuffer(Range.getStart(), *BufferID),\n Range.getByteLength());\n}\n\nOptional<unsigned>\nSourceManager::findBufferContainingLocInternal(SourceLoc Loc) const {\n assert(Loc.isValid());\n \/\/ Search the buffers back-to front, so later alias buffers are\n \/\/ visited first.\n auto less_equal = std::less_equal<const char *>();\n for (unsigned i = LLVMSourceMgr.getNumBuffers(), e = 1; i >= e; --i) {\n auto Buf = LLVMSourceMgr.getMemoryBuffer(i);\n if (less_equal(Buf->getBufferStart(), Loc.Value.getPointer()) &&\n \/\/ Use <= here so that a pointer to the null at the end of the buffer\n \/\/ is included as part of the buffer.\n less_equal(Loc.Value.getPointer(), Buf->getBufferEnd()))\n return i;\n }\n return None;\n}\n\nunsigned SourceManager::findBufferContainingLoc(SourceLoc Loc) const {\n auto Id = findBufferContainingLocInternal(Loc);\n if (Id.hasValue())\n return *Id;\n llvm_unreachable(\"no buffer containing location found\");\n}\n\nbool SourceManager::isOwning(SourceLoc Loc) const {\n return findBufferContainingLocInternal(Loc).hasValue();\n}\n\nvoid SourceRange::widen(SourceRange Other) {\n if (Other.Start.Value.getPointer() < Start.Value.getPointer())\n Start = Other.Start;\n if (Other.End.Value.getPointer() > End.Value.getPointer())\n End = Other.End;\n}\n\nvoid SourceLoc::printLineAndColumn(raw_ostream &OS, const SourceManager &SM,\n unsigned BufferID) const {\n if (isInvalid()) {\n OS << \"<invalid loc>\";\n return;\n }\n\n auto LineAndCol = SM.getPresumedLineAndColumnForLoc(*this, BufferID);\n OS << \"line:\" << LineAndCol.first << ':' << LineAndCol.second;\n}\n\nvoid SourceLoc::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID) const {\n if (isInvalid()) {\n OS << \"<invalid loc>\";\n return;\n }\n\n unsigned BufferID = SM.findBufferContainingLoc(*this);\n if (BufferID != LastBufferID) {\n OS << SM.getIdentifierForBuffer(BufferID);\n LastBufferID = BufferID;\n } else {\n OS << \"line\";\n }\n\n auto LineAndCol = SM.getPresumedLineAndColumnForLoc(*this, BufferID);\n OS << ':' << LineAndCol.first << ':' << LineAndCol.second;\n}\n\nvoid SourceLoc::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nvoid SourceRange::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID, bool PrintText) const {\n \/\/ FIXME: CharSourceRange is a half-open character-based range, while\n \/\/ SourceRange is a closed token-based range, so this conversion omits the\n \/\/ last token in the range. Unfortunately, we can't actually get to the end\n \/\/ of the token without using the Lex library, which would be a layering\n \/\/ violation. This is still better than nothing.\n CharSourceRange(SM, Start, End).print(OS, SM, LastBufferID, PrintText);\n}\n\nvoid SourceRange::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nCharSourceRange::CharSourceRange(const SourceManager &SM, SourceLoc Start,\n SourceLoc End)\n : Start(Start) {\n assert(Start.isValid() == End.isValid() &&\n \"Start and end should either both be valid or both be invalid!\");\n if (Start.isValid())\n ByteLength = SM.getByteDistance(Start, End);\n}\n\nvoid CharSourceRange::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID, bool PrintText) const {\n OS << '[';\n Start.print(OS, SM, LastBufferID);\n OS << \" - \";\n getEnd().print(OS, SM, LastBufferID);\n OS << ']';\n\n if (Start.isInvalid() || getEnd().isInvalid())\n return;\n\n if (PrintText) {\n OS << \" RangeText=\\\"\" << SM.extractText(*this) << '\"';\n }\n}\n\nvoid CharSourceRange::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nllvm::Optional<unsigned>\nSourceManager::resolveOffsetForEndOfLine(unsigned BufferId,\n unsigned Line) const {\n return resolveFromLineCol(BufferId, Line, ~0u);\n}\n\nllvm::Optional<unsigned>\nSourceManager::getLineLength(unsigned BufferId, unsigned Line) const {\n auto BegOffset = resolveFromLineCol(BufferId, Line, 0);\n auto EndOffset = resolveFromLineCol(BufferId, Line, ~0u);\n if (BegOffset && EndOffset) {\n return EndOffset.getValue() - BegOffset.getValue();\n }\n return None;\n}\n\nllvm::Optional<unsigned> SourceManager::resolveFromLineCol(unsigned BufferId,\n unsigned Line,\n unsigned Col) const {\n if (Line == 0) {\n return None;\n }\n const bool LineEnd = Col == ~0u;\n auto InputBuf = getLLVMSourceMgr().getMemoryBuffer(BufferId);\n const char *Ptr = InputBuf->getBufferStart();\n const char *End = InputBuf->getBufferEnd();\n const char *LineStart = Ptr;\n --Line;\n for (; Line && (Ptr < End); ++Ptr) {\n if (*Ptr == '\\n') {\n --Line;\n LineStart = Ptr+1;\n }\n }\n if (Line != 0) {\n return None;\n }\n Ptr = LineStart;\n if (Col == 0) {\n return Ptr - InputBuf->getBufferStart();\n }\n \/\/ The <= here is to allow for non-inclusive range end positions at EOF\n for (; ; ++Ptr) {\n --Col;\n if (Col == 0)\n return Ptr - InputBuf->getBufferStart();\n if (*Ptr == '\\n' || Ptr == End) {\n if (LineEnd) {\n return Ptr - InputBuf->getBufferStart();\n } else {\n break;\n }\n }\n }\n return None;\n}\n\nunsigned SourceManager::getExternalSourceBufferId(StringRef Path) {\n auto It = BufIdentIDMap.find(Path);\n if (It != BufIdentIDMap.end()) {\n return It->getSecond();\n }\n unsigned Id = 0u;\n auto InputFileOrErr = swift::vfs::getFileOrSTDIN(*getFileSystem(), Path);\n if (InputFileOrErr) {\n \/\/ This assertion ensures we can look up from the map in the future when\n \/\/ using the same Path.\n assert(InputFileOrErr.get()->getBufferIdentifier() == Path);\n Id = addNewSourceBuffer(std::move(InputFileOrErr.get()));\n }\n return Id;\n}\n\nSourceLoc\nSourceManager::getLocFromExternalSource(StringRef Path, unsigned Line,\n unsigned Col) {\n auto BufferId = getExternalSourceBufferId(Path);\n if (BufferId == 0u)\n return SourceLoc();\n auto Offset = resolveFromLineCol(BufferId, Line, Col);\n if (!Offset.hasValue())\n return SourceLoc();\n return getLocForOffset(BufferId, *Offset);\n}\n<commit_msg>[SourceManager] Use llvm::SourceMgr::FindLocForLineAndColumn()<commit_after>\/\/===--- SourceLoc.cpp - SourceLoc and SourceRange implementations --------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/SourceLoc.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace swift;\n\nvoid SourceManager::verifyAllBuffers() const {\n llvm::PrettyStackTraceString backtrace{\n \"Checking that all source buffers are still valid\"\n };\n\n \/\/ FIXME: This depends on the buffer IDs chosen by llvm::SourceMgr.\n LLVM_ATTRIBUTE_USED static char arbitraryTotal = 0;\n for (unsigned i = 1, e = LLVMSourceMgr.getNumBuffers(); i <= e; ++i) {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(i);\n if (buffer->getBufferSize() == 0)\n continue;\n arbitraryTotal += buffer->getBufferStart()[0];\n arbitraryTotal += buffer->getBufferEnd()[-1];\n }\n}\n\nSourceLoc SourceManager::getCodeCompletionLoc() const {\n if (CodeCompletionBufferID == 0U)\n return SourceLoc();\n\n return getLocForBufferStart(CodeCompletionBufferID)\n .getAdvancedLoc(CodeCompletionOffset);\n}\n\nStringRef SourceManager::getDisplayNameForLoc(SourceLoc Loc) const {\n \/\/ Respect #line first\n if (auto VFile = getVirtualFile(Loc))\n return VFile->Name;\n\n \/\/ Next, try the stat cache\n auto Ident = getIdentifierForBuffer(findBufferContainingLoc(Loc));\n auto found = StatusCache.find(Ident);\n if (found != StatusCache.end()) {\n return found->second.getName();\n }\n\n \/\/ Populate the cache with a (virtual) stat.\n if (auto Status = FileSystem->status(Ident)) {\n return (StatusCache[Ident] = Status.get()).getName();\n }\n\n \/\/ Finally, fall back to the buffer identifier.\n return Ident;\n}\n\nunsigned\nSourceManager::addNewSourceBuffer(std::unique_ptr<llvm::MemoryBuffer> Buffer) {\n assert(Buffer);\n StringRef BufIdentifier = Buffer->getBufferIdentifier();\n auto ID = LLVMSourceMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());\n BufIdentIDMap[BufIdentifier] = ID;\n return ID;\n}\n\nunsigned SourceManager::addMemBufferCopy(llvm::MemoryBuffer *Buffer) {\n return addMemBufferCopy(Buffer->getBuffer(), Buffer->getBufferIdentifier());\n}\n\nunsigned SourceManager::addMemBufferCopy(StringRef InputData,\n StringRef BufIdentifier) {\n auto Buffer = std::unique_ptr<llvm::MemoryBuffer>(\n llvm::MemoryBuffer::getMemBufferCopy(InputData, BufIdentifier));\n return addNewSourceBuffer(std::move(Buffer));\n}\n\nbool SourceManager::openVirtualFile(SourceLoc loc, StringRef name,\n int lineOffset) {\n CharSourceRange fullRange = getRangeForBuffer(findBufferContainingLoc(loc));\n SourceLoc end;\n\n auto nextRangeIter = VirtualFiles.upper_bound(loc.Value.getPointer());\n if (nextRangeIter != VirtualFiles.end() &&\n fullRange.contains(nextRangeIter->second.Range.getStart())) {\n const VirtualFile &existingFile = nextRangeIter->second;\n if (existingFile.Range.getStart() == loc) {\n assert(existingFile.Name == name);\n assert(existingFile.LineOffset == lineOffset);\n return false;\n }\n assert(!existingFile.Range.contains(loc) &&\n \"must close current open file first\");\n end = nextRangeIter->second.Range.getStart();\n } else {\n end = fullRange.getEnd();\n }\n\n CharSourceRange range = CharSourceRange(*this, loc, end);\n VirtualFiles[end.Value.getPointer()] = {range, name.str(), lineOffset};\n CachedVFile = {nullptr, nullptr};\n return true;\n}\n\nvoid SourceManager::closeVirtualFile(SourceLoc end) {\n auto *virtualFile = const_cast<VirtualFile *>(getVirtualFile(end));\n if (!virtualFile) {\n#ifndef NDEBUG\n unsigned bufferID = findBufferContainingLoc(end);\n CharSourceRange fullRange = getRangeForBuffer(bufferID);\n assert((fullRange.getByteLength() == 0 ||\n getVirtualFile(end.getAdvancedLoc(-1))) &&\n \"no open virtual file for this location\");\n assert(fullRange.getEnd() == end);\n#endif\n return;\n }\n CachedVFile = {nullptr, nullptr};\n\n CharSourceRange oldRange = virtualFile->Range;\n virtualFile->Range = CharSourceRange(*this, virtualFile->Range.getStart(),\n end);\n VirtualFiles[end.Value.getPointer()] = std::move(*virtualFile);\n\n bool existed = VirtualFiles.erase(oldRange.getEnd().Value.getPointer());\n assert(existed);\n (void)existed;\n}\n\nconst SourceManager::VirtualFile *\nSourceManager::getVirtualFile(SourceLoc Loc) const {\n const char *p = Loc.Value.getPointer();\n\n if (CachedVFile.first == p)\n return CachedVFile.second;\n\n \/\/ Returns the first element that is >p.\n auto VFileIt = VirtualFiles.upper_bound(p);\n if (VFileIt != VirtualFiles.end() && VFileIt->second.Range.contains(Loc)) {\n CachedVFile = { p, &VFileIt->second };\n return CachedVFile.second;\n }\n\n return nullptr;\n}\n\nOptional<unsigned>\nSourceManager::getIDForBufferIdentifier(StringRef BufIdentifier) const {\n auto It = BufIdentIDMap.find(BufIdentifier);\n if (It == BufIdentIDMap.end())\n return None;\n return It->second;\n}\n\nStringRef SourceManager::getIdentifierForBuffer(unsigned bufferID) const {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);\n assert(buffer && \"invalid buffer ID\");\n return buffer->getBufferIdentifier();\n}\n\nCharSourceRange SourceManager::getRangeForBuffer(unsigned bufferID) const {\n auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);\n SourceLoc start{llvm::SMLoc::getFromPointer(buffer->getBufferStart())};\n return CharSourceRange(start, buffer->getBufferSize());\n}\n\nunsigned SourceManager::getLocOffsetInBuffer(SourceLoc Loc,\n unsigned BufferID) const {\n assert(Loc.isValid() && \"location should be valid\");\n auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);\n assert(Loc.Value.getPointer() >= Buffer->getBuffer().begin() &&\n Loc.Value.getPointer() <= Buffer->getBuffer().end() &&\n \"Location is not from the specified buffer\");\n return Loc.Value.getPointer() - Buffer->getBuffer().begin();\n}\n\nunsigned SourceManager::getByteDistance(SourceLoc Start, SourceLoc End) const {\n assert(Start.isValid() && \"start location should be valid\");\n assert(End.isValid() && \"end location should be valid\");\n#ifndef NDEBUG\n unsigned BufferID = findBufferContainingLoc(Start);\n auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);\n assert(End.Value.getPointer() >= Buffer->getBuffer().begin() &&\n End.Value.getPointer() <= Buffer->getBuffer().end() &&\n \"End location is not from the same buffer\");\n#endif\n \/\/ When we have a rope buffer, could be implemented in terms of\n \/\/ getLocOffsetInBuffer().\n return End.Value.getPointer() - Start.Value.getPointer();\n}\n\nStringRef SourceManager::getEntireTextForBuffer(unsigned BufferID) const {\n return LLVMSourceMgr.getMemoryBuffer(BufferID)->getBuffer();\n}\n\nStringRef SourceManager::extractText(CharSourceRange Range,\n Optional<unsigned> BufferID) const {\n assert(Range.isValid() && \"range should be valid\");\n\n if (!BufferID)\n BufferID = findBufferContainingLoc(Range.getStart());\n StringRef Buffer = LLVMSourceMgr.getMemoryBuffer(*BufferID)->getBuffer();\n return Buffer.substr(getLocOffsetInBuffer(Range.getStart(), *BufferID),\n Range.getByteLength());\n}\n\nOptional<unsigned>\nSourceManager::findBufferContainingLocInternal(SourceLoc Loc) const {\n assert(Loc.isValid());\n \/\/ Search the buffers back-to front, so later alias buffers are\n \/\/ visited first.\n auto less_equal = std::less_equal<const char *>();\n for (unsigned i = LLVMSourceMgr.getNumBuffers(), e = 1; i >= e; --i) {\n auto Buf = LLVMSourceMgr.getMemoryBuffer(i);\n if (less_equal(Buf->getBufferStart(), Loc.Value.getPointer()) &&\n \/\/ Use <= here so that a pointer to the null at the end of the buffer\n \/\/ is included as part of the buffer.\n less_equal(Loc.Value.getPointer(), Buf->getBufferEnd()))\n return i;\n }\n return None;\n}\n\nunsigned SourceManager::findBufferContainingLoc(SourceLoc Loc) const {\n auto Id = findBufferContainingLocInternal(Loc);\n if (Id.hasValue())\n return *Id;\n llvm_unreachable(\"no buffer containing location found\");\n}\n\nbool SourceManager::isOwning(SourceLoc Loc) const {\n return findBufferContainingLocInternal(Loc).hasValue();\n}\n\nvoid SourceRange::widen(SourceRange Other) {\n if (Other.Start.Value.getPointer() < Start.Value.getPointer())\n Start = Other.Start;\n if (Other.End.Value.getPointer() > End.Value.getPointer())\n End = Other.End;\n}\n\nvoid SourceLoc::printLineAndColumn(raw_ostream &OS, const SourceManager &SM,\n unsigned BufferID) const {\n if (isInvalid()) {\n OS << \"<invalid loc>\";\n return;\n }\n\n auto LineAndCol = SM.getPresumedLineAndColumnForLoc(*this, BufferID);\n OS << \"line:\" << LineAndCol.first << ':' << LineAndCol.second;\n}\n\nvoid SourceLoc::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID) const {\n if (isInvalid()) {\n OS << \"<invalid loc>\";\n return;\n }\n\n unsigned BufferID = SM.findBufferContainingLoc(*this);\n if (BufferID != LastBufferID) {\n OS << SM.getIdentifierForBuffer(BufferID);\n LastBufferID = BufferID;\n } else {\n OS << \"line\";\n }\n\n auto LineAndCol = SM.getPresumedLineAndColumnForLoc(*this, BufferID);\n OS << ':' << LineAndCol.first << ':' << LineAndCol.second;\n}\n\nvoid SourceLoc::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nvoid SourceRange::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID, bool PrintText) const {\n \/\/ FIXME: CharSourceRange is a half-open character-based range, while\n \/\/ SourceRange is a closed token-based range, so this conversion omits the\n \/\/ last token in the range. Unfortunately, we can't actually get to the end\n \/\/ of the token without using the Lex library, which would be a layering\n \/\/ violation. This is still better than nothing.\n CharSourceRange(SM, Start, End).print(OS, SM, LastBufferID, PrintText);\n}\n\nvoid SourceRange::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nCharSourceRange::CharSourceRange(const SourceManager &SM, SourceLoc Start,\n SourceLoc End)\n : Start(Start) {\n assert(Start.isValid() == End.isValid() &&\n \"Start and end should either both be valid or both be invalid!\");\n if (Start.isValid())\n ByteLength = SM.getByteDistance(Start, End);\n}\n\nvoid CharSourceRange::print(raw_ostream &OS, const SourceManager &SM,\n unsigned &LastBufferID, bool PrintText) const {\n OS << '[';\n Start.print(OS, SM, LastBufferID);\n OS << \" - \";\n getEnd().print(OS, SM, LastBufferID);\n OS << ']';\n\n if (Start.isInvalid() || getEnd().isInvalid())\n return;\n\n if (PrintText) {\n OS << \" RangeText=\\\"\" << SM.extractText(*this) << '\"';\n }\n}\n\nvoid CharSourceRange::dump(const SourceManager &SM) const {\n print(llvm::errs(), SM);\n}\n\nllvm::Optional<unsigned>\nSourceManager::resolveOffsetForEndOfLine(unsigned BufferId,\n unsigned Line) const {\n return resolveFromLineCol(BufferId, Line, ~0u);\n}\n\nllvm::Optional<unsigned>\nSourceManager::getLineLength(unsigned BufferId, unsigned Line) const {\n auto BegOffset = resolveFromLineCol(BufferId, Line, 0);\n auto EndOffset = resolveFromLineCol(BufferId, Line, ~0u);\n if (BegOffset && EndOffset) {\n return EndOffset.getValue() - BegOffset.getValue();\n }\n return None;\n}\n\nllvm::Optional<unsigned> SourceManager::resolveFromLineCol(unsigned BufferId,\n unsigned Line,\n unsigned Col) const {\n if (Line == 0) {\n return None;\n }\n const bool LineEnd = (Col == ~0u);\n if (LineEnd)\n Col = 0;\n\n auto loc = const_cast<SourceManager *>(this)\n ->getLLVMSourceMgr()\n .FindLocForLineAndColumn(BufferId, Line, Col);\n if (!loc.isValid())\n return None;\n\n auto InputBuf = getLLVMSourceMgr().getMemoryBuffer(BufferId);\n const char *Ptr = loc.getPointer();\n if (LineEnd) {\n const char *End = InputBuf->getBufferEnd();\n for (;; ++Ptr) {\n if (Ptr == End || *Ptr == '\\n')\n break;\n }\n }\n return Ptr - InputBuf->getBufferStart();\n}\n\nunsigned SourceManager::getExternalSourceBufferId(StringRef Path) {\n auto It = BufIdentIDMap.find(Path);\n if (It != BufIdentIDMap.end()) {\n return It->getSecond();\n }\n unsigned Id = 0u;\n auto InputFileOrErr = swift::vfs::getFileOrSTDIN(*getFileSystem(), Path);\n if (InputFileOrErr) {\n \/\/ This assertion ensures we can look up from the map in the future when\n \/\/ using the same Path.\n assert(InputFileOrErr.get()->getBufferIdentifier() == Path);\n Id = addNewSourceBuffer(std::move(InputFileOrErr.get()));\n }\n return Id;\n}\n\nSourceLoc\nSourceManager::getLocFromExternalSource(StringRef Path, unsigned Line,\n unsigned Col) {\n auto BufferId = getExternalSourceBufferId(Path);\n if (BufferId == 0u)\n return SourceLoc();\n auto Offset = resolveFromLineCol(BufferId, Line, Col);\n if (!Offset.hasValue())\n return SourceLoc();\n return getLocForOffset(BufferId, *Offset);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include <boost\/bimap.hpp>\n#include <boost\/bimap\/list_of.hpp>\n#include <boost\/bimap\/multiset_of.hpp>\n#include <boost\/range\/adaptor\/reversed.hpp>\n#include <iostream>\n#include <vcf2multialign\/check_overlapping_non_nested_variants.hh>\n\n\nnamespace v2m = vcf2multialign;\n\n\ntypedef boost::bimap <\n\tboost::bimaps::multiset_of <size_t>,\n\tboost::bimaps::multiset_of <size_t>\n> overlap_map;\n\n\ntypedef boost::bimap <\n\tboost::bimaps::set_of <size_t>,\n\tboost::bimaps::list_of <size_t>\n> conflict_count_map;\n\n\nnamespace {\n\t\n\ttemplate <typename t_map>\n\tvoid check_overlap(\n\t\tt_map &bad_overlap_side,\n\t\tconflict_count_map &conflict_counts,\n\t\tv2m::variant_set &skipped_variants,\n\t\tsize_t const var_lineno,\n\t\tv2m::error_logger &error_logger\n\t)\n\t{\n\t\tauto const range(bad_overlap_side.equal_range(var_lineno));\n\t\tif (! (bad_overlap_side.end() == range.first || range.first == range.second))\n\t\t{\n\t\t\tif (error_logger.is_logging_errors())\n\t\t\t{\n\t\t\t\tfor (auto it(range.first); it != range.second; ++it)\n\t\t\t\t\terror_logger.log_conflicting_variants(var_lineno, it->second);\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Update conflict counts.\n\t\t\tfor (auto it(range.first); it != range.second; ++it)\n\t\t\t{\n\t\t\t\tauto c_it(conflict_counts.left.find(it->second));\n\t\t\t\tif (conflict_counts.left.end() == c_it)\n\t\t\t\t\tthrow std::runtime_error(\"Unable to find conflict count for variant\");\n\t\t\t\t\n\t\t\t\tauto &val(c_it->second);\n\t\t\t\t--val;\n\t\t\t\t\n\t\t\t\tif (0 == val)\n\t\t\t\t\tconflict_counts.left.erase(c_it);\n\t\t\t\t\n\t\t\t\t\/\/ In case 0 == val, bad_overlaps need not be updated b.c. the entries have\n\t\t\t\t\/\/ already been erased as part of handling previous overlapping variants.\n\t\t\t}\n\t\t\t\n\t\t\tskipped_variants.insert(var_lineno); \/\/ May be done without checking b.c. skipped_variants is a set.\n\t\t\tbad_overlap_side.erase(range.first, range.second);\n\t\t}\n\t}\n}\n\n\nnamespace vcf2multialign {\n\t\n\tsize_t check_overlapping_non_nested_variants(\n\t\tvcf_reader &reader,\n\t\tvariant_set \/* out *\/ &skipped_variants,\n\t\tvariant_set \/* out *\/ &non_nested_variants,\n\t\terror_logger &error_logger\n\t)\n\t{\n\t\ttypedef boost::bimap <\n\t\t\tboost::bimaps::multiset_of <size_t>,\n\t\t\tboost::bimaps::multiset_of <size_t>\n\t\t> overlap_map;\n\t\t\n\t\tsize_t last_position(0);\n\t\tstd::map <size_t, size_t> end_positions;\n\t\tstd::map <size_t, size_t, std::greater <size_t>> current_end_positions; \/\/ End positions for variants that have the same POS.\n\t\tconflict_count_map conflict_counts;\n\t\toverlap_map bad_overlaps;\n\t\tsize_t i(0);\n\t\tsize_t conflict_count(0);\n\t\t\n\t\treader.reset();\n\t\treader.set_parsed_fields(vcf_field::REF);\n\t\tvariant var(reader.sample_count());\n\t\twhile (reader.get_next_variant(var))\n\t\t{\n\t\t\t\/\/ Verify that the positions are in increasing order.\n\t\t\tauto const pos(var.zero_based_pos());\n\n\t\t\tif (! (last_position <= pos))\n\t\t\t\tthrow std::runtime_error(\"Positions not in increasing order\");\n\n\t\t\tauto const end(pos + var.ref().size());\n\t\t\tauto const var_lineno(var.lineno());\n\n\t\t\tif (last_position != pos)\n\t\t\t\tcurrent_end_positions.clear();\n\n\t\t\t\/\/ Check end position order.\n\t\t\tif (last_position == pos)\n\t\t\t{\n\t\t\t\tauto const it(current_end_positions.upper_bound(end));\n\t\t\t\tif (current_end_positions.cend() != it)\n\t\t\t\t{\n\t\t\t\t\tnon_nested_variants.emplace(var_lineno);\n\t\t\t\t\tnon_nested_variants.emplace(it->second);\n\t\t\t\t}\n\t\t\t\tcurrent_end_positions.emplace(end, var_lineno);\n\t\t\t}\n\n\t\t\t\/\/ Try to find an end position that is greater than var's position.\n\t\t\tauto it(end_positions.upper_bound(pos));\n\t\t\tauto const end_it(end_positions.cend());\n\n\t\t\tif (end_it == it)\n\t\t\t{\n\t\t\t\tend_positions.emplace(end, var_lineno);\n\t\t\t\tgoto loop_end;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Check that the found position is not within var's range.\n\t\t\t\/\/ If it is, continue checking succeeding positions.\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ Proper nesting.\n\t\t\t\tif (end <= it->first)\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\t++conflict_count;\n\t\t\t\tstd::cerr << \"Variant on line \" << var_lineno << \" conflicts with line \" << it->second << \".\" << std::endl;\n\t\t\t\t\n\t\t\t\tauto const res(bad_overlaps.insert(overlap_map::value_type(it->second, var_lineno)));\n\t\t\t\tif (false == res.second)\n\t\t\t\t\tthrow std::runtime_error(\"Unable to insert\");\n\n\t\t\t\t++conflict_counts.left[it->second];\n\t\t\t\t++conflict_counts.left[var_lineno];\n\t\t\t\t++it;\n\t\t\t} while (end_it != it);\n\t\t\t\n\t\t\t\/\/ Add the end position.\n\t\t\tend_positions.emplace(end, var_lineno);\n\n\t\tloop_end:\n\t\t\tlast_position = pos;\n\t\t\t\n\t\t\t++i;\n\t\t\tif (0 == i % 100000)\n\t\t\t\tstd::cerr << \"Handled \" << i << \" variants…\" << std::endl;\n\t\t}\n\t\t\n\t\t\/\/ Remove conflicting variants starting from the one with the highest score.\n\t\twhile (!conflict_counts.empty())\n\t\t{\n\t\t\tconflict_counts.right.sort();\n\n\t\t\tauto const it(conflict_counts.right.rbegin());\n\t\t\tauto const count(it->first);\n\t\t\tauto const var_lineno(it->second);\n\t\t\t\n\t\t\t\/\/ Check if the candidate variant is still listed.\n\t\t\tcheck_overlap(bad_overlaps.left, conflict_counts, skipped_variants, var_lineno, error_logger);\n\t\t\tcheck_overlap(bad_overlaps.right, conflict_counts, skipped_variants, var_lineno, error_logger);\n\t\t\tconflict_counts.left.erase(var_lineno);\n\t\t}\n\t\t\n\t\tif (bad_overlaps.size() != 0)\n\t\t\tthrow std::runtime_error(\"Unable to remove all conflicting variants\");\n\t\t\n\t\treturn conflict_count;\n\t}\n}\n<commit_msg>Multiple variants may have the same ending positions<commit_after>\/*\n * Copyright (c) 2017 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include <boost\/bimap.hpp>\n#include <boost\/bimap\/list_of.hpp>\n#include <boost\/bimap\/multiset_of.hpp>\n#include <boost\/range\/adaptor\/reversed.hpp>\n#include <iostream>\n#include <vcf2multialign\/check_overlapping_non_nested_variants.hh>\n\n\nnamespace v2m = vcf2multialign;\n\n\ntypedef boost::bimap <\n\tboost::bimaps::multiset_of <size_t>,\n\tboost::bimaps::multiset_of <size_t>\n> overlap_map;\n\n\ntypedef boost::bimap <\n\tboost::bimaps::set_of <size_t>,\n\tboost::bimaps::list_of <size_t>\n> conflict_count_map;\n\n\nnamespace {\n\t\n\ttemplate <typename t_map>\n\tvoid check_overlap(\n\t\tt_map &bad_overlap_side,\n\t\tconflict_count_map &conflict_counts,\n\t\tv2m::variant_set &skipped_variants,\n\t\tsize_t const var_lineno,\n\t\tv2m::error_logger &error_logger\n\t)\n\t{\n\t\tauto const range(bad_overlap_side.equal_range(var_lineno));\n\t\tif (! (bad_overlap_side.end() == range.first || range.first == range.second))\n\t\t{\n\t\t\tif (error_logger.is_logging_errors())\n\t\t\t{\n\t\t\t\tfor (auto it(range.first); it != range.second; ++it)\n\t\t\t\t\terror_logger.log_conflicting_variants(var_lineno, it->second);\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Update conflict counts.\n\t\t\tfor (auto it(range.first); it != range.second; ++it)\n\t\t\t{\n\t\t\t\tauto c_it(conflict_counts.left.find(it->second));\n\t\t\t\tif (conflict_counts.left.end() == c_it)\n\t\t\t\t\tthrow std::runtime_error(\"Unable to find conflict count for variant\");\n\t\t\t\t\n\t\t\t\tauto &val(c_it->second);\n\t\t\t\t--val;\n\t\t\t\t\n\t\t\t\tif (0 == val)\n\t\t\t\t\tconflict_counts.left.erase(c_it);\n\t\t\t\t\n\t\t\t\t\/\/ In case 0 == val, bad_overlaps need not be updated b.c. the entries have\n\t\t\t\t\/\/ already been erased as part of handling previous overlapping variants.\n\t\t\t}\n\t\t\t\n\t\t\tskipped_variants.insert(var_lineno); \/\/ May be done without checking b.c. skipped_variants is a set.\n\t\t\tbad_overlap_side.erase(range.first, range.second);\n\t\t}\n\t}\n}\n\n\nnamespace vcf2multialign {\n\t\n\tsize_t check_overlapping_non_nested_variants(\n\t\tvcf_reader &reader,\n\t\tvariant_set \/* out *\/ &skipped_variants,\n\t\tvariant_set \/* out *\/ &non_nested_variants,\n\t\terror_logger &error_logger\n\t)\n\t{\n\t\ttypedef boost::bimap <\n\t\t\tboost::bimaps::multiset_of <size_t>,\n\t\t\tboost::bimaps::multiset_of <size_t>\n\t\t> overlap_map;\n\t\t\n\t\tsize_t last_position(0);\n\t\tstd::multimap <size_t, size_t> end_positions;\n\t\tstd::multimap <size_t, size_t, std::greater <size_t>> current_end_positions; \/\/ End positions for variants that have the same POS.\n\t\tconflict_count_map conflict_counts;\n\t\toverlap_map bad_overlaps;\n\t\tsize_t i(0);\n\t\tsize_t conflict_count(0);\n\t\t\n\t\treader.reset();\n\t\treader.set_parsed_fields(vcf_field::REF);\n\t\tvariant var(reader.sample_count());\n\t\twhile (reader.get_next_variant(var))\n\t\t{\n\t\t\t\/\/ Verify that the positions are in increasing order.\n\t\t\tauto const pos(var.zero_based_pos());\n\n\t\t\tif (! (last_position <= pos))\n\t\t\t\tthrow std::runtime_error(\"Positions not in increasing order\");\n\n\t\t\tauto const end(pos + var.ref().size());\n\t\t\tauto const var_lineno(var.lineno());\n\n\t\t\tif (last_position != pos)\n\t\t\t\tcurrent_end_positions.clear();\n\n\t\t\t\/\/ Check end position order.\n\t\t\tif (last_position == pos)\n\t\t\t{\n\t\t\t\tauto const it(current_end_positions.upper_bound(end));\n\t\t\t\tif (current_end_positions.cend() != it)\n\t\t\t\t{\n\t\t\t\t\tnon_nested_variants.emplace(var_lineno);\n\t\t\t\t\tnon_nested_variants.emplace(it->second);\n\t\t\t\t}\n\t\t\t\tcurrent_end_positions.emplace(end, var_lineno);\n\t\t\t}\n\n\t\t\t\/\/ Try to find an end position that is greater than var's position.\n\t\t\tauto it(end_positions.upper_bound(pos));\n\t\t\tauto const end_it(end_positions.cend());\n\n\t\t\tif (end_it == it)\n\t\t\t{\n\t\t\t\tend_positions.emplace(end, var_lineno);\n\t\t\t\tgoto loop_end;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Check that the found position is not within var's range.\n\t\t\t\/\/ If it is, continue checking succeeding positions.\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ Proper nesting.\n\t\t\t\tif (end <= it->first)\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\t++conflict_count;\n\t\t\t\tstd::cerr << \"Variant on line \" << var_lineno << \" conflicts with line \" << it->second << \".\" << std::endl;\n\t\t\t\t\n\t\t\t\tauto const res(bad_overlaps.insert(overlap_map::value_type(it->second, var_lineno)));\n\t\t\t\tif (false == res.second)\n\t\t\t\t\tthrow std::runtime_error(\"Unable to insert\");\n\n\t\t\t\t++conflict_counts.left[it->second];\n\t\t\t\t++conflict_counts.left[var_lineno];\n\t\t\t\t++it;\n\t\t\t} while (end_it != it);\n\t\t\t\n\t\t\t\/\/ Add the end position.\n\t\t\tend_positions.emplace(end, var_lineno);\n\n\t\tloop_end:\n\t\t\tlast_position = pos;\n\t\t\t\n\t\t\t++i;\n\t\t\tif (0 == i % 100000)\n\t\t\t\tstd::cerr << \"Handled \" << i << \" variants…\" << std::endl;\n\t\t}\n\t\t\n\t\t\/\/ Remove conflicting variants starting from the one with the highest score.\n\t\twhile (!conflict_counts.empty())\n\t\t{\n\t\t\tconflict_counts.right.sort();\n\n\t\t\tauto const it(conflict_counts.right.rbegin());\n\t\t\tauto const count(it->first);\n\t\t\tauto const var_lineno(it->second);\n\t\t\t\n\t\t\t\/\/ Check if the candidate variant is still listed.\n\t\t\tcheck_overlap(bad_overlaps.left, conflict_counts, skipped_variants, var_lineno, error_logger);\n\t\t\tcheck_overlap(bad_overlaps.right, conflict_counts, skipped_variants, var_lineno, error_logger);\n\t\t\tconflict_counts.left.erase(var_lineno);\n\t\t}\n\t\t\n\t\tif (bad_overlaps.size() != 0)\n\t\t\tthrow std::runtime_error(\"Unable to remove all conflicting variants\");\n\t\t\n\t\treturn conflict_count;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/javascript_test_util.h\"\n#include \"chrome\/test\/ui\/ui_perf_test.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nclass FrameRateTest : public UIPerfTest {\n public:\n FrameRateTest() {\n show_window_ = true;\n dom_automation_enabled_ = true;\n }\n\n virtual FilePath GetDataPath(const std::string& name) {\n \/\/ Make sure the test data is checked out.\n FilePath test_path;\n PathService::Get(chrome::DIR_TEST_DATA, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"perf\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"frame_rate\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"content\"));\n test_path = test_path.AppendASCII(name);\n return test_path;\n }\n\n void RunTest(const std::string& name, const std::string& suffix) {\n FilePath test_path = GetDataPath(name);\n ASSERT_TRUE(file_util::DirectoryExists(test_path))\n << \"Missing test directory: \" << test_path.value();\n\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test.html\"));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n tab->NavigateToURL(net::FilePathToFileURL(test_path)));\n\n \/\/ Start the tests.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"javascript:__start_all();\")));\n\n \/\/ Block until the tests completes.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(\n tab, L\"\", L\"window.domAutomationController.send(!__running_all);\",\n TestTimeouts::huge_test_timeout_ms()));\n\n \/\/ Read out the results.\n std::wstring json;\n ASSERT_TRUE(tab->ExecuteAndExtractString(\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"JSON.stringify(__calc_results_total()));\",\n &json));\n\n std::map<std::string, std::string> results;\n ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));\n\n ASSERT_TRUE(results.find(\"mean\") != results.end());\n ASSERT_TRUE(results.find(\"sigma\") != results.end());\n ASSERT_TRUE(results.find(\"gestures\") != results.end());\n ASSERT_TRUE(results.find(\"means\") != results.end());\n ASSERT_TRUE(results.find(\"sigmas\") != results.end());\n\n std::cout << \"Gestures: \" + results[\"gestures\"] + \"\\n\";\n std::cout << \"Means: \" + results[\"means\"] + \"\\n\";\n std::cout << \"Sigmas: \" + results[\"sigmas\"] + \"\\n\";\n PrintResultList(\"fps\", suffix, \"\", results[\"means\"],\n \"frames-per-second\", true);\n\n std::string mean_and_error = results[\"mean\"] + \",\" + results[\"sigma\"];\n PrintResultMeanAndError(\"fps\", suffix, \"\", mean_and_error,\n \"frames-per-second\", true);\n }\n};\n\nclass FrameRateTest_Reference : public FrameRateTest {\n public:\n void SetUp() {\n UseReferenceBuild();\n FrameRateTest::SetUp();\n }\n};\n\n#define FRAME_RATE_TEST(content) \\\nTEST_F(FrameRateTest, content) { \\\n RunTest(#content, \"\"); \\\n} \\\nTEST_F(FrameRateTest_Reference, content) { \\\n RunTest(#content, \"_ref\"); \\\n}\nFRAME_RATE_TEST(blank);\nFRAME_RATE_TEST(googleblog);\n\n} \/\/ namespace\n<commit_msg>Fixed frame rate test output for performance dashboard.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/javascript_test_util.h\"\n#include \"chrome\/test\/ui\/ui_perf_test.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nclass FrameRateTest : public UIPerfTest {\n public:\n FrameRateTest() {\n show_window_ = true;\n dom_automation_enabled_ = true;\n }\n\n virtual FilePath GetDataPath(const std::string& name) {\n \/\/ Make sure the test data is checked out.\n FilePath test_path;\n PathService::Get(chrome::DIR_TEST_DATA, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"perf\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"frame_rate\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"content\"));\n test_path = test_path.AppendASCII(name);\n return test_path;\n }\n\n void RunTest(const std::string& name, const std::string& suffix) {\n FilePath test_path = GetDataPath(name);\n ASSERT_TRUE(file_util::DirectoryExists(test_path))\n << \"Missing test directory: \" << test_path.value();\n\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test.html\"));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n tab->NavigateToURL(net::FilePathToFileURL(test_path)));\n\n \/\/ Start the tests.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"javascript:__start_all();\")));\n\n \/\/ Block until the tests completes.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(\n tab, L\"\", L\"window.domAutomationController.send(!__running_all);\",\n TestTimeouts::huge_test_timeout_ms()));\n\n \/\/ Read out the results.\n std::wstring json;\n ASSERT_TRUE(tab->ExecuteAndExtractString(\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"JSON.stringify(__calc_results_total()));\",\n &json));\n\n std::map<std::string, std::string> results;\n ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));\n\n ASSERT_TRUE(results.find(\"mean\") != results.end());\n ASSERT_TRUE(results.find(\"sigma\") != results.end());\n ASSERT_TRUE(results.find(\"gestures\") != results.end());\n ASSERT_TRUE(results.find(\"means\") != results.end());\n ASSERT_TRUE(results.find(\"sigmas\") != results.end());\n\n std::string trace_name = \"fps\" + suffix;\n printf(\"GESTURES %s: %s= [%s] [%s] [%s]\\n\", name.c_str(),\n trace_name.c_str(),\n results[\"gestures\"].c_str(),\n results[\"means\"].c_str(),\n results[\"sigmas\"].c_str());\n\n std::string mean_and_error = results[\"mean\"] + \",\" + results[\"sigma\"];\n PrintResultMeanAndError(name, \"\", trace_name, mean_and_error,\n \"frames-per-second\", true);\n }\n};\n\nclass FrameRateTest_Reference : public FrameRateTest {\n public:\n void SetUp() {\n UseReferenceBuild();\n FrameRateTest::SetUp();\n }\n};\n\n#define FRAME_RATE_TEST(content) \\\nTEST_F(FrameRateTest, content) { \\\n RunTest(#content, \"\"); \\\n} \\\nTEST_F(FrameRateTest_Reference, content) { \\\n RunTest(#content, \"_ref\"); \\\n}\nFRAME_RATE_TEST(blank);\nFRAME_RATE_TEST(googleblog);\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/util\/util.hpp>\n#include <nix\/DataArray.hpp>\n\nusing namespace nix;\n\n\nvoid DataArray::getData(DataType dtype,\n void *data,\n const NDSize &count,\n const NDSize &offset) const {\n backend()->read(dtype, data, count, offset);\n}\n\nvoid DataArray::setData(DataType dtype,\n const void *data,\n const NDSize &count,\n const NDSize &offset)\n{\n backend()->write(dtype, data, count, offset);\n}\n\ndouble DataArray::applyPolynomial(std::vector<double> &coefficients, double origin, double input) const{\n double value = 0.0;\n double term = 1.0;\n for (size_t i = 0; i < coefficients.size(); i++) {\n value += coefficients[i] * term;\n term *= input - origin;\n }\n return value;\n}\n\n\nvoid DataArray::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not SI or composite of SI units.\", \"DataArray::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nstd::vector<Dimension> DataArray::dimensions(const util::Filter<Dimension>::type &filter) const {\n auto f = [this] (size_t i) { return getDimension(i+1); }; \/\/ +1 since index starts at 1\n return getEntities<Dimension>(f,\n dimensionCount(),\n filter);\n}\n\n\nstd::ostream& nix::operator<<(std::ostream &out, const DataArray &ent) {\n out << \"DataArray: {name = \" << ent.name();\n out << \", type = \" << ent.type();\n out << \", id = \" << ent.id() << \"}\";\n return out;\n}\n\n<commit_msg>DataArray::getData: support polynom while reading<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/util\/util.hpp>\n#include <nix\/DataArray.hpp>\n#include <nix\/hdf5\/DataTypeHDF5.hpp>\n\nusing namespace nix;\n\nstatic void convertData(DataType source, DataType destination, void *data, size_t nelms)\n{\n H5::DataType h5_src = hdf5::data_type_to_h5_memtype(source);\n H5::DataType h5_dst = hdf5::data_type_to_h5_memtype(destination);\n\n h5_src.convert(h5_dst, nelms, data, nullptr);\n}\n\nvoid DataArray::getData(DataType dtype,\n void *data,\n const NDSize &count,\n const NDSize &offset) const {\n\n std::vector<double> poly = polynomCoefficients();\n\n if (poly.size()) {\n size_t data_esize = data_type_to_size(dtype);\n size_t nelms = count.nelms();\n std::vector<double> tmp;\n double *read_buffer;\n\n if (data_esize < sizeof(double)) {\n \/\/need temporary buffer\n tmp.resize(nelms);\n read_buffer = tmp.data();\n } else {\n read_buffer = reinterpret_cast<double *>(data);\n }\n\n backend()->read(DataType::Double, read_buffer, count, offset);\n std::transform(read_buffer, read_buffer + nelms, read_buffer, [this, &poly](double x) -> double {\n return applyPolynomial(poly, 0.0, x);\n });\n\n convertData(DataType::Double, dtype, read_buffer, nelms);\n\n if (tmp.size()) {\n memcpy(data, read_buffer, nelms * data_esize);\n }\n\n } else {\n backend()->read(dtype, data, count, offset);\n }\n}\n\nvoid DataArray::setData(DataType dtype,\n const void *data,\n const NDSize &count,\n const NDSize &offset)\n{\n backend()->write(dtype, data, count, offset);\n}\n\ndouble DataArray::applyPolynomial(std::vector<double> &coefficients, double origin, double input) const{\n double value = 0.0;\n double term = 1.0;\n for (size_t i = 0; i < coefficients.size(); i++) {\n value += coefficients[i] * term;\n term *= input - origin;\n }\n return value;\n}\n\n\nvoid DataArray::unit(const std::string &unit) {\n if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {\n throw InvalidUnit(\"Unit is not SI or composite of SI units.\", \"DataArray::unit(const string &unit)\");\n }\n backend()->unit(unit);\n}\n\n\nstd::vector<Dimension> DataArray::dimensions(const util::Filter<Dimension>::type &filter) const {\n auto f = [this] (size_t i) { return getDimension(i+1); }; \/\/ +1 since index starts at 1\n return getEntities<Dimension>(f,\n dimensionCount(),\n filter);\n}\n\n\nstd::ostream& nix::operator<<(std::ostream &out, const DataArray &ent) {\n out << \"DataArray: {name = \" << ent.name();\n out << \", type = \" << ent.type();\n out << \", id = \" << ent.id() << \"}\";\n return out;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * $Id$\n *\n * Project: libLAS - http:\/\/liblas.org - A BSD library for LAS format data.\n * Purpose: LAS Dimension implementation for C++ libLAS\n * Author: Howard Butler, hobu.inc@gmail.com\n *\n ******************************************************************************\n * Copyright (c) 2010, Howard Butler\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following\n * conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Martin Isenburg or Iowa Department\n * of Natural Resources nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n ****************************************************************************\/\n\n#include <pdal\/Dimension.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <boost\/uuid\/random_generator.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <map>\n\n#include <time.h>\n#include <cstdlib>\n\nnamespace pdal\n{\n\n\n\nDimension::Dimension(std::string const& name,\n dimension::Interpretation interpretation,\n dimension::size_type sizeInBytes,\n std::string description)\n : m_name(name)\n , m_flags(0)\n , m_endian(pdal::Endian_Little)\n , m_byteSize(sizeInBytes)\n , m_description(description)\n , m_min(0.0)\n , m_max(0.0)\n , m_numericScale(1.0)\n , m_numericOffset(0.0)\n , m_byteOffset(0)\n , m_position(-1)\n , m_interpretation(interpretation)\n , m_uuid(boost::uuids::nil_uuid())\n , m_namespace(std::string(\"\"))\n , m_parentDimensionID(boost::uuids::nil_uuid())\n\n{\n\n if (!m_name.size())\n {\n \/\/ Generate a random name from the time\n ::time_t seconds;\n ::time(&seconds);\n\n std::ostringstream oss;\n srand(static_cast<unsigned int>(seconds));\n oss << \"unnamed\" << rand();\n m_name = oss.str();\n\n }\n\n}\n\n\/\/\/ copy constructor\nDimension::Dimension(Dimension const& other)\n : m_name(other.m_name)\n , m_flags(other.m_flags)\n , m_endian(other.m_endian)\n , m_byteSize(other.m_byteSize)\n , m_description(other.m_description)\n , m_min(other.m_min)\n , m_max(other.m_max)\n , m_numericScale(other.m_numericScale)\n , m_numericOffset(other.m_numericOffset)\n , m_byteOffset(other.m_byteOffset)\n , m_position(other.m_position)\n , m_interpretation(other.m_interpretation)\n , m_uuid(other.m_uuid)\n , m_namespace(other.m_namespace)\n , m_parentDimensionID(other.m_parentDimensionID)\n{\n return;\n}\n\n\/\/\/ assignment operator\nDimension& Dimension::operator=(Dimension const& rhs)\n{\n if (&rhs != this)\n {\n m_name = rhs.m_name;\n m_flags = rhs.m_flags;\n m_endian = rhs.m_endian;\n m_byteSize = rhs.m_byteSize;\n m_description = rhs.m_description;\n m_min = rhs.m_min;\n m_max = rhs.m_max;\n m_numericScale = rhs.m_numericScale;\n m_numericOffset = rhs.m_numericOffset;\n m_byteOffset = rhs.m_byteOffset;\n m_position = rhs.m_position;\n m_interpretation = rhs.m_interpretation;\n m_uuid = rhs.m_uuid;\n m_namespace = rhs.m_namespace;\n m_parentDimensionID = rhs.m_parentDimensionID;\n }\n\n return *this;\n}\n\n\nbool Dimension::operator==(const Dimension& other) const\n{\n if (boost::iequals(m_name, other.m_name) &&\n m_flags == other.m_flags &&\n m_endian == other.m_endian &&\n m_byteSize == other.m_byteSize &&\n boost::iequals(m_description, other.m_description) &&\n Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&\n m_byteOffset == other.m_byteOffset &&\n m_position == other.m_position &&\n m_interpretation == other.m_interpretation &&\n m_uuid == other.m_uuid &&\n m_parentDimensionID == other.m_parentDimensionID\n )\n {\n return true;\n }\n\n return false;\n}\n\n\nbool Dimension::operator!=(const Dimension& other) const\n{\n return !(*this==other);\n}\n\nboost::property_tree::ptree Dimension::toPTree() const\n{\n using boost::property_tree::ptree;\n ptree dim;\n dim.put(\"name\", getName());\n dim.put(\"namespace\", getNamespace());\n dim.put(\"parent\", getParent());\n dim.put(\"description\", getDescription());\n dim.put(\"bytesize\", getByteSize());\n\n std::string e(\"little\");\n if (getEndianness() == Endian_Big)\n e = std::string(\"big\");\n dim.put(\"endianness\", e);\n\n dim.put(\"minimum\", getMinimum());\n dim.put(\"maximum\", getMaximum());\n dim.put(\"scale\", getNumericScale());\n dim.put(\"offset\", getNumericOffset());\n\n dim.put(\"scale\", getNumericScale());\n\n dim.put(\"isValid\", isValid());\n dim.put(\"isIgnored\", isIgnored());\n\n std::stringstream oss;\n\n dimension::id t = getUUID();\n oss << t;\n\n dim.put(\"uuid\", oss.str());\n return dim;\n}\n\nvoid Dimension::setUUID(std::string const& id)\n{\n boost::uuids::string_generator gen;\n m_uuid = gen(id);\n}\n\nvoid Dimension::createUUID()\n{\n boost::uuids::basic_random_generator<boost::mt19937> gen(pdal::Environment::get()->getRNG());\n m_uuid = gen();\n}\nvoid Dimension::dump() const\n{\n std::cout << *this;\n}\n\nstd::string Dimension::getInterpretationName() const\n{\n std::ostringstream type;\n dimension::Interpretation t = getInterpretation();\n boost::uint32_t bytesize = getByteSize();\n\n switch (t)\n {\n case dimension::SignedByte:\n if (bytesize == 1)\n type << \"int8_t\";\n break;\n case dimension::UnsignedByte:\n if (bytesize == 1)\n type << \"uint8_t\";\n break;\n\n\n case dimension::SignedInteger:\n if (bytesize == 1)\n type << \"int8_t\";\n else if (bytesize == 2)\n type << \"int16_t\";\n else if (bytesize == 4)\n type << \"int32_t\";\n else if (bytesize == 8)\n type << \"int64_t\";\n else\n type << \"unknown\";\n break;\n case dimension::UnsignedInteger:\n if (bytesize == 1)\n type << \"uint8_t\";\n else if (bytesize == 2)\n type << \"uint16_t\";\n else if (bytesize == 4)\n type << \"uint32_t\";\n else if (bytesize == 8)\n type << \"uint64_t\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Float:\n if (bytesize == 4)\n type << \"float\";\n else if (bytesize == 8)\n type << \"double\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Pointer:\n type << \"pointer\";\n break;\n case dimension::Undefined:\n type << \"unknown\";\n break;\n }\n\n return type.str();\n}\n\nstd::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)\n{\n using boost::property_tree::ptree;\n ptree tree = d.toPTree();\n\n std::string const name = tree.get<std::string>(\"name\");\n std::string const ns = tree.get<std::string>(\"namespace\");\n\n std::ostringstream quoted_name;\n if (ns.size())\n quoted_name << \"'\" << ns << \".\" << name << \"'\";\n else\n quoted_name << \"'\" << name << \"'\";\n std::ostringstream pad;\n std::string const& cur = quoted_name.str();\n std::string::size_type size = cur.size();\n std::string::size_type buffer(24);\n std::string::size_type pad_size = buffer - size;\n if (size > buffer) \n pad_size = 4;\n for (std::string::size_type i=0; i != pad_size; i++)\n {\n pad << \" \";\n }\n os << quoted_name.str() << pad.str() <<\" -- \"<< \" size: \" << tree.get<boost::uint32_t>(\"bytesize\");\n\n double scale = tree.get<double>(\"scale\");\n boost::uint32_t precision = Utils::getStreamPrecision(scale);\n os.setf(std::ios_base::fixed, std::ios_base::floatfield);\n os.precision(precision);\n os << \" scale: \" << scale;\n\n double offset = tree.get<double>(\"offset\");\n os << \" offset: \" << offset;\n \n os << \" ignored: \" << tree.get<bool>(\"isIgnored\");\n os << std::endl;\n\n return os;\n}\n\n\n} \/\/ namespace pdal\n<commit_msg>put position and byteoffset in the ptree output<commit_after>\/******************************************************************************\n * $Id$\n *\n * Project: libLAS - http:\/\/liblas.org - A BSD library for LAS format data.\n * Purpose: LAS Dimension implementation for C++ libLAS\n * Author: Howard Butler, hobu.inc@gmail.com\n *\n ******************************************************************************\n * Copyright (c) 2010, Howard Butler\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following\n * conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Martin Isenburg or Iowa Department\n * of Natural Resources nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n ****************************************************************************\/\n\n#include <pdal\/Dimension.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <boost\/uuid\/random_generator.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <map>\n\n#include <time.h>\n#include <cstdlib>\n\nnamespace pdal\n{\n\n\n\nDimension::Dimension(std::string const& name,\n dimension::Interpretation interpretation,\n dimension::size_type sizeInBytes,\n std::string description)\n : m_name(name)\n , m_flags(0)\n , m_endian(pdal::Endian_Little)\n , m_byteSize(sizeInBytes)\n , m_description(description)\n , m_min(0.0)\n , m_max(0.0)\n , m_numericScale(1.0)\n , m_numericOffset(0.0)\n , m_byteOffset(0)\n , m_position(-1)\n , m_interpretation(interpretation)\n , m_uuid(boost::uuids::nil_uuid())\n , m_namespace(std::string(\"\"))\n , m_parentDimensionID(boost::uuids::nil_uuid())\n\n{\n\n if (!m_name.size())\n {\n \/\/ Generate a random name from the time\n ::time_t seconds;\n ::time(&seconds);\n\n std::ostringstream oss;\n srand(static_cast<unsigned int>(seconds));\n oss << \"unnamed\" << rand();\n m_name = oss.str();\n\n }\n\n}\n\n\/\/\/ copy constructor\nDimension::Dimension(Dimension const& other)\n : m_name(other.m_name)\n , m_flags(other.m_flags)\n , m_endian(other.m_endian)\n , m_byteSize(other.m_byteSize)\n , m_description(other.m_description)\n , m_min(other.m_min)\n , m_max(other.m_max)\n , m_numericScale(other.m_numericScale)\n , m_numericOffset(other.m_numericOffset)\n , m_byteOffset(other.m_byteOffset)\n , m_position(other.m_position)\n , m_interpretation(other.m_interpretation)\n , m_uuid(other.m_uuid)\n , m_namespace(other.m_namespace)\n , m_parentDimensionID(other.m_parentDimensionID)\n{\n return;\n}\n\n\/\/\/ assignment operator\nDimension& Dimension::operator=(Dimension const& rhs)\n{\n if (&rhs != this)\n {\n m_name = rhs.m_name;\n m_flags = rhs.m_flags;\n m_endian = rhs.m_endian;\n m_byteSize = rhs.m_byteSize;\n m_description = rhs.m_description;\n m_min = rhs.m_min;\n m_max = rhs.m_max;\n m_numericScale = rhs.m_numericScale;\n m_numericOffset = rhs.m_numericOffset;\n m_byteOffset = rhs.m_byteOffset;\n m_position = rhs.m_position;\n m_interpretation = rhs.m_interpretation;\n m_uuid = rhs.m_uuid;\n m_namespace = rhs.m_namespace;\n m_parentDimensionID = rhs.m_parentDimensionID;\n }\n\n return *this;\n}\n\n\nbool Dimension::operator==(const Dimension& other) const\n{\n if (boost::iequals(m_name, other.m_name) &&\n m_flags == other.m_flags &&\n m_endian == other.m_endian &&\n m_byteSize == other.m_byteSize &&\n boost::iequals(m_description, other.m_description) &&\n Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&\n m_byteOffset == other.m_byteOffset &&\n m_position == other.m_position &&\n m_interpretation == other.m_interpretation &&\n m_uuid == other.m_uuid &&\n m_parentDimensionID == other.m_parentDimensionID\n )\n {\n return true;\n }\n\n return false;\n}\n\n\nbool Dimension::operator!=(const Dimension& other) const\n{\n return !(*this==other);\n}\n\nboost::property_tree::ptree Dimension::toPTree() const\n{\n using boost::property_tree::ptree;\n ptree dim;\n dim.put(\"name\", getName());\n dim.put(\"namespace\", getNamespace());\n dim.put(\"parent\", getParent());\n dim.put(\"description\", getDescription());\n dim.put(\"bytesize\", getByteSize());\n\n std::string e(\"little\");\n if (getEndianness() == Endian_Big)\n e = std::string(\"big\");\n dim.put(\"endianness\", e);\n\n dim.put(\"minimum\", getMinimum());\n dim.put(\"maximum\", getMaximum());\n dim.put(\"scale\", getNumericScale());\n dim.put(\"offset\", getNumericOffset());\n\n dim.put(\"scale\", getNumericScale());\n\n dim.put(\"position\", getPosition());\n dim.put(\"byteoffset\", getByteOffset());\n dim.put(\"isIgnored\", isIgnored());\n\n std::stringstream oss;\n\n dimension::id t = getUUID();\n oss << t;\n\n dim.put(\"uuid\", oss.str());\n return dim;\n}\n\nvoid Dimension::setUUID(std::string const& id)\n{\n boost::uuids::string_generator gen;\n m_uuid = gen(id);\n}\n\nvoid Dimension::createUUID()\n{\n boost::uuids::basic_random_generator<boost::mt19937> gen(pdal::Environment::get()->getRNG());\n m_uuid = gen();\n}\nvoid Dimension::dump() const\n{\n std::cout << *this;\n}\n\nstd::string Dimension::getInterpretationName() const\n{\n std::ostringstream type;\n dimension::Interpretation t = getInterpretation();\n boost::uint32_t bytesize = getByteSize();\n\n switch (t)\n {\n case dimension::SignedByte:\n if (bytesize == 1)\n type << \"int8_t\";\n break;\n case dimension::UnsignedByte:\n if (bytesize == 1)\n type << \"uint8_t\";\n break;\n\n\n case dimension::SignedInteger:\n if (bytesize == 1)\n type << \"int8_t\";\n else if (bytesize == 2)\n type << \"int16_t\";\n else if (bytesize == 4)\n type << \"int32_t\";\n else if (bytesize == 8)\n type << \"int64_t\";\n else\n type << \"unknown\";\n break;\n case dimension::UnsignedInteger:\n if (bytesize == 1)\n type << \"uint8_t\";\n else if (bytesize == 2)\n type << \"uint16_t\";\n else if (bytesize == 4)\n type << \"uint32_t\";\n else if (bytesize == 8)\n type << \"uint64_t\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Float:\n if (bytesize == 4)\n type << \"float\";\n else if (bytesize == 8)\n type << \"double\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Pointer:\n type << \"pointer\";\n break;\n case dimension::Undefined:\n type << \"unknown\";\n break;\n }\n\n return type.str();\n}\n\nstd::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)\n{\n using boost::property_tree::ptree;\n ptree tree = d.toPTree();\n\n std::string const name = tree.get<std::string>(\"name\");\n std::string const ns = tree.get<std::string>(\"namespace\");\n\n std::ostringstream quoted_name;\n if (ns.size())\n quoted_name << \"'\" << ns << \".\" << name << \"'\";\n else\n quoted_name << \"'\" << name << \"'\";\n std::ostringstream pad;\n std::string const& cur = quoted_name.str();\n std::string::size_type size = cur.size();\n std::string::size_type buffer(24);\n std::string::size_type pad_size = buffer - size;\n if (size > buffer) \n pad_size = 4;\n for (std::string::size_type i=0; i != pad_size; i++)\n {\n pad << \" \";\n }\n os << quoted_name.str() << pad.str() <<\" -- \"<< \" size: \" << tree.get<boost::uint32_t>(\"bytesize\");\n\n double scale = tree.get<double>(\"scale\");\n boost::uint32_t precision = Utils::getStreamPrecision(scale);\n os.setf(std::ios_base::fixed, std::ios_base::floatfield);\n os.precision(precision);\n os << \" scale: \" << scale;\n\n double offset = tree.get<double>(\"offset\");\n os << \" offset: \" << offset;\n \n os << \" ignored: \" << tree.get<bool>(\"isIgnored\");\n os << std::endl;\n\n return os;\n}\n\n\n} \/\/ namespace pdal\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ START SNIPPET: demo\n\n#include <activemq\/concurrent\/Thread.h>\n#include <activemq\/concurrent\/Runnable.h>\n#include <activemq\/core\/ActiveMQConnectionFactory.h>\n#include <activemq\/util\/Integer.h>\n#include <cms\/Connection.h>\n#include <cms\/Session.h>\n#include <cms\/TextMessage.h>\n#include <cms\/ExceptionListener.h>\n#include <cms\/MessageListener.h>\n#include <stdlib.h>\n#include <iostream>\n\nusing namespace activemq::core;\nusing namespace activemq::util;\nusing namespace activemq::concurrent;\nusing namespace cms;\nusing namespace std;\n\nclass HelloWorldProducer : public Runnable {\nprivate:\n\t\n\tConnection* connection;\n\tSession* session;\n\tDestination* destination;\n\tMessageProducer* producer;\n\tint numMessages;\n bool useTopic;\n\npublic:\n\t\n\tHelloWorldProducer( int numMessages, bool useTopic = false ){\n\t\tconnection = NULL;\n \tsession = NULL;\n \tdestination = NULL;\n \tproducer = NULL;\n \tthis->numMessages = numMessages;\n this->useTopic = useTopic;\n\t}\n\t\n\tvirtual ~HelloWorldProducer(){\n\t\tcleanup();\n\t}\n\t\n virtual void run() {\n try {\n \/\/ Create a ConnectionFactory\n ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory(\"tcp:\/\/127.0.0.1:61613\");\n\n \/\/ Create a Connection\n connection = connectionFactory->createConnection();\n connection->start();\n\n \/\/ Create a Session\n session = connection->createSession( Session::AUTO_ACKNOWLEDGE );\n\n \/\/ Create the destination (Topic or Queue)\n if( useTopic ) {\n destination = session->createTopic( \"TEST.FOO\" );\n } else {\n destination = session->createQueue( \"TEST.FOO\" );\n }\n\n \/\/ Create a MessageProducer from the Session to the Topic or Queue\n producer = session->createProducer( destination );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTANT );\n \n \/\/ Create the Thread Id String\n string threadIdStr = Integer::toString( Thread::getId() );\n \n \/\/ Create a messages\n string text = (string)\"Hello world! from thread \" + threadIdStr;\n \n for( int ix=0; ix<numMessages; ++ix ){\n\t TextMessage* message = session->createTextMessage( text );\n\n \t \/\/ Tell the producer to send the message\n \t printf( \"Sent message from thread %s\\n\", threadIdStr.c_str() );\n \tproducer->send( message );\n \t\n \tdelete message;\n }\n\t\t\t\n }catch ( CMSException& e ) {\n e.printStackTrace();\n }\n }\n \nprivate:\n\n void cleanup(){\n \t\t\t\t\n\t\t\t\/\/ Destroy resources.\n\t\t\ttry{ \n \tif( destination != NULL ) delete destination;\n\t\t\t}catch ( CMSException& e ) {}\n\t\t\tdestination = NULL;\n\t\t\t\n\t\t\ttry{\n\t if( producer != NULL ) delete producer;\n\t\t\t}catch ( CMSException& e ) {}\n\t\t\tproducer = NULL;\n\t\t\t\n \t\t\/\/ Close open resources.\n \t\ttry{\n \t\t\tif( session != NULL ) session->close();\n \t\t\tif( connection != NULL ) connection->close();\n\t\t\t}catch ( CMSException& e ) {}\n\n\t\t\ttry{\n \tif( session != NULL ) delete session;\n\t\t\t}catch ( CMSException& e ) {}\n\t\t\tsession = NULL;\n\t\t\t\n try{\n \tif( connection != NULL ) delete connection;\n\t\t\t}catch ( CMSException& e ) {}\n \t\tconnection = NULL;\n }\n};\n\nclass HelloWorldConsumer : public ExceptionListener, \n public MessageListener,\n public Runnable {\n\t\nprivate:\n\t\n\tConnection* connection;\n\tSession* session;\n\tDestination* destination;\n\tMessageConsumer* consumer;\n\tlong waitMillis;\n bool useTopic;\n\t\t\npublic: \n\n\tHelloWorldConsumer( long waitMillis, bool useTopic = false ){\n\t\tconnection = NULL;\n \tsession = NULL;\n \tdestination = NULL;\n \tconsumer = NULL;\n \tthis->waitMillis = waitMillis;\n this->useTopic = useTopic;\n\t}\n virtual ~HelloWorldConsumer(){ \t\n \tcleanup();\n }\n \n virtual void run() {\n \t \t\n try {\n\n \/\/ Create a ConnectionFactory\n ActiveMQConnectionFactory* connectionFactory = \n new ActiveMQConnectionFactory( \"tcp:\/\/127.0.0.1:61613\" );\n\n \/\/ Create a Connection\n connection = connectionFactory->createConnection();\n delete connectionFactory;\n connection->start();\n \n connection->setExceptionListener(this);\n\n \/\/ Create a Session\n session = connection->createSession( Session::AUTO_ACKNOWLEDGE );\n\n \/\/ Create the destination (Topic or Queue)\n if( useTopic ) {\n destination = session->createTopic( \"TEST.FOO\" );\n } else {\n destination = session->createQueue( \"TEST.FOO\" );\n }\n\n \/\/ Create a MessageConsumer from the Session to the Topic or Queue\n consumer = session->createConsumer( destination );\n \n consumer->setMessageListener( this );\n \n \/\/ Sleep while asynchronous messages come in.\n Thread::sleep( waitMillis );\t\t\n \n } catch (CMSException& e) {\n e.printStackTrace();\n }\n }\n \n \/\/ Called from the consumer since this class is a registered MessageListener.\n virtual void onMessage( const Message* message ){\n \t\n static int count = 0;\n \n try\n {\n count++;\n \t const TextMessage* textMessage = \n dynamic_cast< const TextMessage* >( message );\n string text = textMessage->getText();\n printf( \"Message #%d Received: %s\\n\", count, text.c_str() );\n } catch (CMSException& e) {\n e.printStackTrace();\n }\n }\n\n \/\/ If something bad happens you see it here as this class is also been\n \/\/ registered as an ExceptionListener with the connection.\n virtual void onException( const CMSException& ex ) {\n printf(\"JMS Exception occured. Shutting down client.\\n\");\n }\n \nprivate:\n\n void cleanup(){\n \t\n \/\/*************************************************\n \/\/ Always close destination, consumers and producers before\n \/\/ you destroy their sessions and connection.\n \/\/*************************************************\n \n\t\t\/\/ Destroy resources.\n\t\ttry{ \n \tif( destination != NULL ) delete destination;\n\t\t}catch (CMSException& e) {}\n\t\tdestination = NULL;\n\t\t\n\t\ttry{\n if( consumer != NULL ) delete consumer;\n\t\t}catch (CMSException& e) {}\n\t\tconsumer = NULL;\n\t\t\n\t\t\/\/ Close open resources.\n\t\ttry{\n\t\t\tif( session != NULL ) session->close();\n\t\t\tif( connection != NULL ) connection->close();\n\t\t}catch (CMSException& e) {}\n\t\t\n \/\/ Now Destroy them\n try{\n \tif( session != NULL ) delete session;\n\t\t}catch (CMSException& e) {}\n\t\tsession = NULL;\n\t\t\n\t\ttry{\n \tif( connection != NULL ) delete connection;\n\t\t}catch (CMSException& e) {}\n\t\tconnection = NULL;\n }\n};\n \nint main(int argc, char* argv[]) {\n\n std::cout << \"=====================================================\\n\"; \n std::cout << \"Starting the example:\" << std::endl;\n std::cout << \"-----------------------------------------------------\\n\";\n\n \/\/============================================================\n \/\/ set to true to use topics instead of queues\n \/\/ Note in the code above that this causes createTopic or\n \/\/ createQueue to be used in both consumer an producer.\n \/\/============================================================ \n bool useTopics = false; \n\n HelloWorldProducer producer( 1000, useTopics );\n\tHelloWorldConsumer consumer( 8000, useTopics );\n\t\n\t\/\/ Start the consumer thread.\n\tThread consumerThread( &consumer );\n\tconsumerThread.start();\n\t\n\t\/\/ Start the producer thread.\n\tThread producerThread( &producer );\n\tproducerThread.start();\n\n\t\/\/ Wait for the threads to complete.\n\tproducerThread.join();\n\tconsumerThread.join();\n\n std::cout << \"-----------------------------------------------------\\n\"; \n std::cout << \"Finished with the example, ignore errors from this\" \n << std::endl\n << \"point on as the sockets breaks when we shutdown.\"\n << std::endl;\n std::cout << \"=====================================================\\n\"; \n}\n \n\/\/ END SNIPPET: demo\n<commit_msg>cleaning up the spaces\/tabs in the example ActiveMQ CPP main.cpp<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ START SNIPPET: demo\n\n#include <activemq\/concurrent\/Thread.h>\n#include <activemq\/concurrent\/Runnable.h>\n#include <activemq\/core\/ActiveMQConnectionFactory.h>\n#include <activemq\/util\/Integer.h>\n#include <cms\/Connection.h>\n#include <cms\/Session.h>\n#include <cms\/TextMessage.h>\n#include <cms\/ExceptionListener.h>\n#include <cms\/MessageListener.h>\n#include <stdlib.h>\n#include <iostream>\n\nusing namespace activemq::core;\nusing namespace activemq::util;\nusing namespace activemq::concurrent;\nusing namespace cms;\nusing namespace std;\n\nclass HelloWorldProducer : public Runnable {\nprivate:\n \n Connection* connection;\n Session* session;\n Destination* destination;\n MessageProducer* producer;\n int numMessages;\n bool useTopic;\n\npublic:\n \n HelloWorldProducer( int numMessages, bool useTopic = false ){\n connection = NULL;\n session = NULL;\n destination = NULL;\n producer = NULL;\n this->numMessages = numMessages;\n this->useTopic = useTopic;\n }\n \n virtual ~HelloWorldProducer(){\n cleanup();\n }\n \n virtual void run() {\n try {\n \/\/ Create a ConnectionFactory\n ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory(\"tcp:\/\/127.0.0.1:61613\");\n\n \/\/ Create a Connection\n connection = connectionFactory->createConnection();\n connection->start();\n\n \/\/ Create a Session\n session = connection->createSession( Session::AUTO_ACKNOWLEDGE );\n\n \/\/ Create the destination (Topic or Queue)\n if( useTopic ) {\n destination = session->createTopic( \"TEST.FOO\" );\n } else {\n destination = session->createQueue( \"TEST.FOO\" );\n }\n\n \/\/ Create a MessageProducer from the Session to the Topic or Queue\n producer = session->createProducer( destination );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTANT );\n \n \/\/ Create the Thread Id String\n string threadIdStr = Integer::toString( Thread::getId() );\n \n \/\/ Create a messages\n string text = (string)\"Hello world! from thread \" + threadIdStr;\n \n for( int ix=0; ix<numMessages; ++ix ){\n TextMessage* message = session->createTextMessage( text );\n\n \/\/ Tell the producer to send the message\n printf( \"Sent message from thread %s\\n\", threadIdStr.c_str() );\n producer->send( message );\n \n delete message;\n }\n \n }catch ( CMSException& e ) {\n e.printStackTrace();\n }\n }\n \nprivate:\n\n void cleanup(){\n \n \/\/ Destroy resources.\n try{ \n if( destination != NULL ) delete destination;\n }catch ( CMSException& e ) {}\n destination = NULL;\n \n try{\n if( producer != NULL ) delete producer;\n }catch ( CMSException& e ) {}\n producer = NULL;\n \n \/\/ Close open resources.\n try{\n if( session != NULL ) session->close();\n if( connection != NULL ) connection->close();\n }catch ( CMSException& e ) {}\n\n try{\n if( session != NULL ) delete session;\n }catch ( CMSException& e ) {}\n session = NULL;\n \n try{\n if( connection != NULL ) delete connection;\n }catch ( CMSException& e ) {}\n connection = NULL;\n }\n};\n\nclass HelloWorldConsumer : public ExceptionListener, \n public MessageListener,\n public Runnable {\n \nprivate:\n \n Connection* connection;\n Session* session;\n Destination* destination;\n MessageConsumer* consumer;\n long waitMillis;\n bool useTopic;\n \npublic: \n\n HelloWorldConsumer( long waitMillis, bool useTopic = false ){\n connection = NULL;\n session = NULL;\n destination = NULL;\n consumer = NULL;\n this->waitMillis = waitMillis;\n this->useTopic = useTopic;\n }\n virtual ~HelloWorldConsumer(){ \n cleanup();\n }\n \n virtual void run() {\n \n try {\n\n \/\/ Create a ConnectionFactory\n ActiveMQConnectionFactory* connectionFactory = \n new ActiveMQConnectionFactory( \"tcp:\/\/127.0.0.1:61613\" );\n\n \/\/ Create a Connection\n connection = connectionFactory->createConnection();\n delete connectionFactory;\n connection->start();\n \n connection->setExceptionListener(this);\n\n \/\/ Create a Session\n session = connection->createSession( Session::AUTO_ACKNOWLEDGE );\n\n \/\/ Create the destination (Topic or Queue)\n if( useTopic ) {\n destination = session->createTopic( \"TEST.FOO\" );\n } else {\n destination = session->createQueue( \"TEST.FOO\" );\n }\n\n \/\/ Create a MessageConsumer from the Session to the Topic or Queue\n consumer = session->createConsumer( destination );\n \n consumer->setMessageListener( this );\n \n \/\/ Sleep while asynchronous messages come in.\n Thread::sleep( waitMillis ); \n \n } catch (CMSException& e) {\n e.printStackTrace();\n }\n }\n \n \/\/ Called from the consumer since this class is a registered MessageListener.\n virtual void onMessage( const Message* message ){\n \n static int count = 0;\n \n try\n {\n count++;\n const TextMessage* textMessage = \n dynamic_cast< const TextMessage* >( message );\n string text = textMessage->getText();\n printf( \"Message #%d Received: %s\\n\", count, text.c_str() );\n } catch (CMSException& e) {\n e.printStackTrace();\n }\n }\n\n \/\/ If something bad happens you see it here as this class is also been\n \/\/ registered as an ExceptionListener with the connection.\n virtual void onException( const CMSException& ex ) {\n printf(\"JMS Exception occured. Shutting down client.\\n\");\n }\n \nprivate:\n\n void cleanup(){\n \n \/\/*************************************************\n \/\/ Always close destination, consumers and producers before\n \/\/ you destroy their sessions and connection.\n \/\/*************************************************\n \n \/\/ Destroy resources.\n try{ \n if( destination != NULL ) delete destination;\n }catch (CMSException& e) {}\n destination = NULL;\n \n try{\n if( consumer != NULL ) delete consumer;\n }catch (CMSException& e) {}\n consumer = NULL;\n \n \/\/ Close open resources.\n try{\n if( session != NULL ) session->close();\n if( connection != NULL ) connection->close();\n }catch (CMSException& e) {}\n \n \/\/ Now Destroy them\n try{\n if( session != NULL ) delete session;\n }catch (CMSException& e) {}\n session = NULL;\n \n try{\n if( connection != NULL ) delete connection;\n }catch (CMSException& e) {}\n connection = NULL;\n }\n};\n \nint main(int argc, char* argv[]) {\n\n std::cout << \"=====================================================\\n\"; \n std::cout << \"Starting the example:\" << std::endl;\n std::cout << \"-----------------------------------------------------\\n\";\n\n \/\/============================================================\n \/\/ set to true to use topics instead of queues\n \/\/ Note in the code above that this causes createTopic or\n \/\/ createQueue to be used in both consumer an producer.\n \/\/============================================================ \n bool useTopics = false; \n\n HelloWorldProducer producer( 1000, useTopics );\n HelloWorldConsumer consumer( 8000, useTopics );\n \n \/\/ Start the consumer thread.\n Thread consumerThread( &consumer );\n consumerThread.start();\n \n \/\/ Start the producer thread.\n Thread producerThread( &producer );\n producerThread.start();\n\n \/\/ Wait for the threads to complete.\n producerThread.join();\n consumerThread.join();\n\n std::cout << \"-----------------------------------------------------\\n\"; \n std::cout << \"Finished with the example, ignore errors from this\" \n << std::endl\n << \"point on as the sockets breaks when we shutdown.\"\n << std::endl;\n std::cout << \"=====================================================\\n\"; \n}\n \n\/\/ END SNIPPET: demo\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2011-2012 Merethis\n**\n** This file is part of Centreon Clib.\n**\n** Centreon Clib is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Affero General Public License as\n** published by the Free Software Foundation, either version 3 of the\n** License, or (at your option) any later version.\n**\n** Centreon Clib is distributed in the hope that it will be useful, but\n** WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** Affero General Public License for more details.\n**\n** You should have received a copy of the GNU Affero General Public\n** License along with Centreon Clib. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef CC_UNIQUE_ARRAY_PTR_HH\n# define CC_UNIQUE_ARRAY_PTR_HH\n\n# include <cstddef>\n# include \"com\/centreon\/namespace.hh\"\n\nCC_BEGIN()\n\n\/**\n * @class unique_array_ptr unique_array_ptr.hh\n * @brief Similar to unique_ptr for arrays.\n *\n * Provide similar feature as unique_ptr but for array pointers.\n *\/\ntemplate <typename T>\nclass unique_array_ptr {\n private:\n T* _ptr;\n\n public:\n \/**\n * Constructor.\n *\n * @param[in] t Array pointer.\n *\/\n unique_array_ptr(T* t) : _ptr(t) {}\n\n \/**\n * Copy constructor.\n *\n * @param[in] uap Object to copy.\n *\/\n unique_array_ptr(unique_array_ptr& uap) : _ptr(uap._ptr) {\n uap._ptr = NULL;\n }\n\n \/**\n * Destructor.\n *\/\n ~unique_array_ptr() {\n delete [] _ptr;\n }\n\n \/**\n * Assignment operator.\n *\n * @param[in] uap Object to copy.\n *\n * @return This object.\n *\/\n unique_array_ptr& operator=(unique_array_ptr& uap) {\n if (&uap != this) {\n _ptr = uap._ptr;\n uap._ptr = NULL;\n }\n return (*this);\n }\n\n \/**\n * Dereferencing pointer.\n *\n * @return Dereferenced pointer.\n *\/\n T& operator*() {\n return (*_ptr);\n }\n\n \/**\n * Array access operator.\n *\n * @param[in] idx Index in array.\n *\n * @return Element at position idx.\n *\/\n T& operator[](unsigned int idx) {\n return (_ptr[idx]);\n }\n\n \/**\n * Get the pointer associated with this object.\n *\n * @return Pointer associated with this object.\n *\/\n T* get() const {\n return (_ptr);\n }\n\n \/**\n * Release the associated pointer and release it.\n *\n * @return Pointer associated with this object.\n *\/\n T* release() {\n T* tmp(_ptr);\n _ptr = NULL;\n return (tmp);\n }\n};\n\nCC_END()\n\n#endif \/\/ !CC_UNIQUE_ARRAY_PTR_HH\n<commit_msg>Added default argument to unique_array_ptr's constructor.<commit_after>\/*\n** Copyright 2011-2012 Merethis\n**\n** This file is part of Centreon Clib.\n**\n** Centreon Clib is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Affero General Public License as\n** published by the Free Software Foundation, either version 3 of the\n** License, or (at your option) any later version.\n**\n** Centreon Clib is distributed in the hope that it will be useful, but\n** WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** Affero General Public License for more details.\n**\n** You should have received a copy of the GNU Affero General Public\n** License along with Centreon Clib. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef CC_UNIQUE_ARRAY_PTR_HH\n# define CC_UNIQUE_ARRAY_PTR_HH\n\n# include <cstddef>\n# include \"com\/centreon\/namespace.hh\"\n\nCC_BEGIN()\n\n\/**\n * @class unique_array_ptr unique_array_ptr.hh\n * @brief Similar to unique_ptr for arrays.\n *\n * Provide similar feature as unique_ptr but for array pointers.\n *\/\ntemplate <typename T>\nclass unique_array_ptr {\n private:\n T* _ptr;\n\n public:\n \/**\n * Constructor.\n *\n * @param[in] t Array pointer.\n *\/\n unique_array_ptr(T* t = NULL) : _ptr(t) {}\n\n \/**\n * Copy constructor.\n *\n * @param[in] uap Object to copy.\n *\/\n unique_array_ptr(unique_array_ptr& uap) : _ptr(uap._ptr) {\n uap._ptr = NULL;\n }\n\n \/**\n * Destructor.\n *\/\n ~unique_array_ptr() {\n delete [] _ptr;\n }\n\n \/**\n * Assignment operator.\n *\n * @param[in] uap Object to copy.\n *\n * @return This object.\n *\/\n unique_array_ptr& operator=(unique_array_ptr& uap) {\n if (&uap != this) {\n _ptr = uap._ptr;\n uap._ptr = NULL;\n }\n return (*this);\n }\n\n \/**\n * Dereferencing pointer.\n *\n * @return Dereferenced pointer.\n *\/\n T& operator*() {\n return (*_ptr);\n }\n\n \/**\n * Array access operator.\n *\n * @param[in] idx Index in array.\n *\n * @return Element at position idx.\n *\/\n T& operator[](unsigned int idx) {\n return (_ptr[idx]);\n }\n\n \/**\n * Get the pointer associated with this object.\n *\n * @return Pointer associated with this object.\n *\/\n T* get() const {\n return (_ptr);\n }\n\n \/**\n * Release the associated pointer and release it.\n *\n * @return Pointer associated with this object.\n *\/\n T* release() {\n T* tmp(_ptr);\n _ptr = NULL;\n return (tmp);\n }\n};\n\nCC_END()\n\n#endif \/\/ !CC_UNIQUE_ARRAY_PTR_HH\n<|endoftext|>"} {"text":"<commit_before>#include \"RSolid.h\"\n\n#include <iostream>\n\n#include \"..\/Maths\/Matrix_Maths.h\"\n\n#include \"..\/Camera.h\"\n\n#include \"..\/World\/Chunk\/CSection.h\"\n\nnamespace Renderer\n{\n void RChunk::draw(const Chunk::Section& section)\n {\n m_chunks.push_back(§ion);\n }\n\n void RChunk::update(const Camera& camera)\n {\n \/\/glEnable (GL_CULL_FACE);\n\n m_shader.bind();\n\n m_shader.setProjMatrix(camera.getProjectionMatrix());\n m_shader.setViewMatrix(camera.getViewMatrix());\n\n for (const auto* section : m_chunks)\n {\n prepare(*section);\n\n glDrawElements(GL_TRIANGLES,\n section->getMeshes().solidMesh.getModel().getIndicesCount(),\n GL_UNSIGNED_INT,\n nullptr);\n\n }\n m_chunks.clear();\n }\n\n void RChunk::prepare(const Chunk::Section& section)\n {\n section.getMeshes().solidMesh.getModel().bind();\n }\n}\n<commit_msg>readd face cull<commit_after>#include \"RSolid.h\"\n\n#include <iostream>\n\n#include \"..\/Maths\/Matrix_Maths.h\"\n\n#include \"..\/Camera.h\"\n\n#include \"..\/World\/Chunk\/CSection.h\"\n\nnamespace Renderer\n{\n void RChunk::draw(const Chunk::Section& section)\n {\n m_chunks.push_back(§ion);\n }\n\n void RChunk::update(const Camera& camera)\n {\n glEnable (GL_CULL_FACE);\n\n m_shader.bind();\n\n m_shader.setProjMatrix(camera.getProjectionMatrix());\n m_shader.setViewMatrix(camera.getViewMatrix());\n\n for (const auto* section : m_chunks)\n {\n prepare(*section);\n\n glDrawElements(GL_TRIANGLES,\n section->getMeshes().solidMesh.getModel().getIndicesCount(),\n GL_UNSIGNED_INT,\n nullptr);\n\n }\n m_chunks.clear();\n }\n\n void RChunk::prepare(const Chunk::Section& section)\n {\n section.getMeshes().solidMesh.getModel().bind();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2794\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1720329 by chui@ocl-promo-incrementor on 2018\/12\/14 03:00:54<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2795\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of asciival, software which can return an ASCII\n\/\/ representation of the data read from a DAP server.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ asciival is free software; you can redistribute it and\/or modify it under\n\/\/ the terms of the GNU General Public License as published by the Free\n\/\/ Software Foundation; either version 2, or (at your option) any later\n\/\/ version.\n\/\/ \n\/\/ asciival is distributed in the hope that it will be useful, but WITHOUT\n\/\/ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n\/\/ more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License along\n\/\/ with GCC; see the file COPYING. If not, write to the Free Software\n\/\/ Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/ \n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n \n\/\/ (c) COPYRIGHT URI\/MIT 1998,2000\n\/\/ Please read the full copyright statement in the file COPYRIGHT_URI.\n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher <jgallagher@gso.uri.edu>\n\n\/\/ Implementation for the class AsciiStructure. See AsciiByte.cc\n\/\/\n\/\/ 3\/12\/98 jhrg\n\n#include \"config.h\"\n\n#include <iostream>\n#include <string>\n\n#include \"InternalErr.h\"\n#include \"AsciiSequence.h\"\n#include \"AsciiStructure.h\"\n\/\/#include \"name_map.h\"\n#include \"get_ascii.h\"\n#include \"debug.h\"\n\nusing std::endl ;\nusing namespace dap_asciival;\n\nBaseType *\nAsciiSequence::ptr_duplicate()\n{\n return new AsciiSequence(*this);\n}\n\nAsciiSequence::AsciiSequence(const string &n) : Sequence(n)\n{\n}\n\nAsciiSequence::AsciiSequence(Sequence * bt):AsciiOutput(bt)\n{\n \/\/ Let's make the alternative structure of Ascii types now so that we\n \/\/ don't have to do it on the fly.\n Vars_iter p = bt->var_begin();\n while (p != bt->var_end()) {\n if ((*p)->send_p()) {\n BaseType *new_bt = basetype_to_asciitype(*p);\n add_var(new_bt);\n delete new_bt;\n }\n p++;\n }\n set_name(bt->name());\n}\n\nAsciiSequence::~AsciiSequence()\n{\n}\n\nint\nAsciiSequence::length()\n{\n return -1;\n}\n\nint\nAsciiSequence::element_count(bool leaves)\n{\n if (!leaves)\n return _vars.size();\n else {\n int i = 0;\n for (Vars_iter iter = _vars.begin(); iter != _vars.end(); iter++) {\n if ((*iter)->send_p())\n i += (*iter)->element_count(true);\n }\n return i;\n }\n}\n\n\/\/ case 1: Simple, Seq - handled\n\/\/ Case 2: Seq, Simple\nvoid\n AsciiSequence::print_ascii_row(FILE * os, int row, BaseTypeRow outer_vars)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n \/\/ Print the values from this sequence.\n \/\/ AsciiSequence::element_count() returns only vars with send_p() set.\n int elements = element_count() - 1;\n int j = 0;\n bool done = false;\n do {\n BaseType *bt_ptr = seq->var_value(row, j);\n if (bt_ptr) { \/\/ Check for data.\n BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);\n if (bt_ptr->type() == dods_sequence_c) {\n dynamic_cast <\n AsciiSequence * >(abt_ptr)->print_ascii_rows(os,\n outer_vars);\n } else {\n \/\/ push the real base type pointer instead of the ascii one.\n \/\/ We can cast it again later from the outer_vars vector.\n outer_vars.push_back(bt_ptr);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,\n false);\n }\n ++j;\n \/\/ we only need the ascii type here, so delete it\n delete abt_ptr;\n }\n \n \/\/ ++j;\n \/\/ When we're finally done, set the flag and omit the comma.\n if (j > elements)\n done = true;\n else if (bt_ptr)\n fprintf(os, \", \");\n \n } while (!done);\n}\n\nvoid\n AsciiSequence::print_leading_vars(FILE * os, BaseTypeRow & outer_vars)\n{\n BaseTypeRow::iterator BTR_iter = outer_vars.begin();\n for (BTR_iter = outer_vars.begin(); BTR_iter != outer_vars.end();\n BTR_iter++) {\n BaseType *abt_ptr = basetype_to_asciitype(*BTR_iter);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os, false);\n fprintf(os, \", \");\n \/\/ we only need the ascii base type locally, so delete it\n delete abt_ptr;\n }\n}\n\nvoid\n AsciiSequence::print_ascii_rows(FILE * os, BaseTypeRow outer_vars)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n int rows = seq->number_of_rows() - 1;\n int i = 0;\n bool done = false;\n do {\n if (i > 0 && !outer_vars.empty())\n print_leading_vars(os, outer_vars);\n\n print_ascii_row(os, i++, outer_vars);\n\n if (i > rows)\n done = true;\n else\n fprintf(os, \"\\n\");\n } while (!done);\n}\n\n\/\/ Assume that this mfunc is called only for simple sequences. Do not print\n\/\/ table style headers for complex sequences. \n\nvoid\n AsciiSequence::print_header(FILE * os)\n{\n Vars_iter p = var_begin();\n while (p != var_end()) {\n if ((*p)->is_simple_type())\n fprintf(os, \"%s\",\n dynamic_cast <\n AsciiOutput * >(*p)->get_full_name().c_str());\n else if ((*p)->type() == dods_sequence_c)\n dynamic_cast < AsciiSequence * >((*p))->print_header(os);\n else if ((*p)->type() == dods_structure_c)\n dynamic_cast < AsciiStructure * >((*p))->print_header(os);\n else\n throw InternalErr(__FILE__, __LINE__,\n \"This method should only be called by instances for which `is_simple_sequence' returns true.\");\n if (++p != var_end())\n fprintf(os, \", \");\n }\n}\n\nvoid\n AsciiSequence::print_ascii(FILE * os, bool print_name) throw(InternalErr)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n if (seq->is_linear()) {\n if (print_name) {\n print_header(os);\n fprintf(os, \"\\n\");\n }\n\n BaseTypeRow outer_vars(0);\n print_ascii_rows(os, outer_vars);\n } else {\n int rows = seq->number_of_rows() - 1;\n int elements = seq->element_count() - 1;\n\n \/\/ For each row of the Sequence...\n bool rows_done = false;\n int i = 0;\n do {\n \/\/ For each variable of the row...\n bool vars_done = false;\n int j = 0;\n do {\n BaseType *bt_ptr = seq->var_value(i, j++);\n BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,\n true);\n \/\/ abt_ptr is not stored for future use, so delete it\n delete abt_ptr;\n\n if (j > elements)\n vars_done = true;\n else\n fprintf(os, \"\\n\");\n } while (!vars_done);\n\n i++;\n if (i > rows)\n rows_done = true;\n else\n fprintf(os, \"\\n\");\n } while (!rows_done);\n }\n}\n\n\n<commit_msg>AsciiSequence.cc: Added a comment about a specialization of element_count().<commit_after>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of asciival, software which can return an ASCII\n\/\/ representation of the data read from a DAP server.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ asciival is free software; you can redistribute it and\/or modify it under\n\/\/ the terms of the GNU General Public License as published by the Free\n\/\/ Software Foundation; either version 2, or (at your option) any later\n\/\/ version.\n\/\/ \n\/\/ asciival is distributed in the hope that it will be useful, but WITHOUT\n\/\/ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n\/\/ more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License along\n\/\/ with GCC; see the file COPYING. If not, write to the Free Software\n\/\/ Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/ \n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n \n\/\/ (c) COPYRIGHT URI\/MIT 1998,2000\n\/\/ Please read the full copyright statement in the file COPYRIGHT_URI.\n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher <jgallagher@gso.uri.edu>\n\n\/\/ Implementation for the class AsciiStructure. See AsciiByte.cc\n\/\/\n\/\/ 3\/12\/98 jhrg\n\n#include \"config.h\"\n\n#include <iostream>\n#include <string>\n\n#include \"InternalErr.h\"\n#include \"AsciiSequence.h\"\n#include \"AsciiStructure.h\"\n\/\/#include \"name_map.h\"\n#include \"get_ascii.h\"\n#include \"debug.h\"\n\nusing std::endl ;\nusing namespace dap_asciival;\n\nBaseType *\nAsciiSequence::ptr_duplicate()\n{\n return new AsciiSequence(*this);\n}\n\nAsciiSequence::AsciiSequence(const string &n) : Sequence(n)\n{\n}\n\nAsciiSequence::AsciiSequence(Sequence * bt):AsciiOutput(bt)\n{\n \/\/ Let's make the alternative structure of Ascii types now so that we\n \/\/ don't have to do it on the fly.\n Vars_iter p = bt->var_begin();\n while (p != bt->var_end()) {\n if ((*p)->send_p()) {\n BaseType *new_bt = basetype_to_asciitype(*p);\n add_var(new_bt);\n delete new_bt;\n }\n p++;\n }\n set_name(bt->name());\n}\n\nAsciiSequence::~AsciiSequence()\n{\n}\n\nint\nAsciiSequence::length()\n{\n return -1;\n}\n\n\/\/ This specialization is different from the Sequence version only in that \n\/\/ it tests '*iter)->send_p()' before incrementing 'i' by \n\/\/ '(*iter)->element_count(true)'.\nint\nAsciiSequence::element_count(bool leaves)\n{\n if (!leaves)\n return _vars.size();\n else {\n int i = 0;\n for (Vars_iter iter = _vars.begin(); iter != _vars.end(); iter++) {\n if ((*iter)->send_p())\n i += (*iter)->element_count(true);\n }\n return i;\n }\n}\n\n\/\/ case 1: Simple, Seq - handled\n\/\/ Case 2: Seq, Simple\nvoid\nAsciiSequence::print_ascii_row(FILE * os, int row, BaseTypeRow outer_vars)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n \/\/ Print the values from this sequence.\n \/\/ AsciiSequence::element_count() returns only vars with send_p() set.\n int elements = element_count() - 1;\n int j = 0;\n bool done = false;\n do {\n BaseType *bt_ptr = seq->var_value(row, j);\n if (bt_ptr) { \/\/ Check for data.\n BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);\n if (bt_ptr->type() == dods_sequence_c) {\n dynamic_cast <\n AsciiSequence * >(abt_ptr)->print_ascii_rows(os,\n outer_vars);\n } else {\n \/\/ push the real base type pointer instead of the ascii one.\n \/\/ We can cast it again later from the outer_vars vector.\n outer_vars.push_back(bt_ptr);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,\n false);\n }\n ++j;\n \/\/ we only need the ascii type here, so delete it\n delete abt_ptr;\n }\n \n \/\/ ++j;\n \/\/ When we're finally done, set the flag and omit the comma.\n if (j > elements)\n done = true;\n else if (bt_ptr)\n fprintf(os, \", \");\n \n } while (!done);\n}\n\nvoid\n AsciiSequence::print_leading_vars(FILE * os, BaseTypeRow & outer_vars)\n{\n BaseTypeRow::iterator BTR_iter = outer_vars.begin();\n for (BTR_iter = outer_vars.begin(); BTR_iter != outer_vars.end();\n BTR_iter++) {\n BaseType *abt_ptr = basetype_to_asciitype(*BTR_iter);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os, false);\n fprintf(os, \", \");\n \/\/ we only need the ascii base type locally, so delete it\n delete abt_ptr;\n }\n}\n\nvoid\n AsciiSequence::print_ascii_rows(FILE * os, BaseTypeRow outer_vars)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n int rows = seq->number_of_rows() - 1;\n int i = 0;\n bool done = false;\n do {\n if (i > 0 && !outer_vars.empty())\n print_leading_vars(os, outer_vars);\n\n print_ascii_row(os, i++, outer_vars);\n\n if (i > rows)\n done = true;\n else\n fprintf(os, \"\\n\");\n } while (!done);\n}\n\n\/\/ Assume that this mfunc is called only for simple sequences. Do not print\n\/\/ table style headers for complex sequences. \n\nvoid\n AsciiSequence::print_header(FILE * os)\n{\n Vars_iter p = var_begin();\n while (p != var_end()) {\n if ((*p)->is_simple_type())\n fprintf(os, \"%s\",\n dynamic_cast <\n AsciiOutput * >(*p)->get_full_name().c_str());\n else if ((*p)->type() == dods_sequence_c)\n dynamic_cast < AsciiSequence * >((*p))->print_header(os);\n else if ((*p)->type() == dods_structure_c)\n dynamic_cast < AsciiStructure * >((*p))->print_header(os);\n else\n throw InternalErr(__FILE__, __LINE__,\n \"This method should only be called by instances for which `is_simple_sequence' returns true.\");\n if (++p != var_end())\n fprintf(os, \", \");\n }\n}\n\nvoid\n AsciiSequence::print_ascii(FILE * os, bool print_name) throw(InternalErr)\n{\n Sequence *seq = dynamic_cast < Sequence * >(_redirect);\n if (!seq)\n seq = this;\n\n if (seq->is_linear()) {\n if (print_name) {\n print_header(os);\n fprintf(os, \"\\n\");\n }\n\n BaseTypeRow outer_vars(0);\n print_ascii_rows(os, outer_vars);\n } else {\n int rows = seq->number_of_rows() - 1;\n int elements = seq->element_count() - 1;\n\n \/\/ For each row of the Sequence...\n bool rows_done = false;\n int i = 0;\n do {\n \/\/ For each variable of the row...\n bool vars_done = false;\n int j = 0;\n do {\n BaseType *bt_ptr = seq->var_value(i, j++);\n BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);\n dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,\n true);\n \/\/ abt_ptr is not stored for future use, so delete it\n delete abt_ptr;\n\n if (j > elements)\n vars_done = true;\n else\n fprintf(os, \"\\n\");\n } while (!vars_done);\n\n i++;\n if (i > rows)\n rows_done = true;\n else\n fprintf(os, \"\\n\");\n } while (!rows_done);\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/cli_progress_bar.h\"\n\n#include \"core\/cli_position.h\"\n#include \"core\/range.h\"\n\n#include <iostream>\n#include <string>\n#include <string_view>\n#include <array>\n\nnamespace euphoria::core\n{\n CliProgressBar::CliProgressBar()\n : position(GetConsolePosition().value_or(vec2i::Zero()))\n , last(Now())\n {\n }\n\n CliProgressBar::~CliProgressBar()\n {\n Update(1.0f, true);\n }\n\n void\n CliProgressBar::Update(float apercent, bool force)\n {\n constexpr float min_interval_seconds = 0.1f;\n constexpr int total_number_of_characters = 30;\n constexpr std::array animation_chars\n {\n std::string_view{\"|\"},\n std::string_view{\"\/\"},\n std::string_view{\"-\"},\n std::string_view{\"\\\\\"}\n };\n constexpr std::string_view filled_char = \"#\";\n constexpr std::string_view empty_char = \"-\";\n constexpr std::string_view start_char = \"[\";\n constexpr std::string_view end_char = \"]\";\n\n const auto percent = KeepWithin(R01(), apercent);\n\n const auto number_of_characters = static_cast<int>(percent * total_number_of_characters);\n\n const auto now = Now();\n if (!force && SecondsBetween(last, now) < min_interval_seconds)\n {\n return;\n }\n last = now;\n\n SetConsolePosition(position);\n std::cout << start_char;\n for (int i = 0; i < number_of_characters; i += 1)\n {\n std::cout << filled_char;\n }\n for (int i = number_of_characters; i < total_number_of_characters; i += 1)\n {\n std::cout << empty_char;\n }\n std::cout << end_char;\n\n std::cout << \"\\n\";\n }\n\n void\n CliProgressBarInfinite::Step(int each)\n {\n index += 1;\n if (index < each)\n {\n return;\n }\n index -= each;\n\n percent += 0.01f;\n if (percent > 1)\n {\n percent -= 1;\n }\n progress.Update(percent);\n }\n} \/\/ namespace euphoria::core\n<commit_msg>better format<commit_after>#include \"core\/cli_progress_bar.h\"\n\n#include \"core\/cli_position.h\"\n#include \"core\/range.h\"\n\n#include <iostream>\n#include <string>\n#include <string_view>\n#include <array>\n\nnamespace euphoria::core\n{\n CliProgressBar::CliProgressBar()\n : position(GetConsolePosition().value_or(vec2i::Zero()))\n , last(Now())\n {\n }\n\n CliProgressBar::~CliProgressBar()\n {\n Update(1.0f, true);\n }\n\n void\n CliProgressBar::Update(float apercent, bool force)\n {\n constexpr float min_interval_seconds = 0.1f;\n constexpr int total_number_of_characters = 30;\n constexpr std::array animation_chars\n {\n std::string_view{\"|\"},\n std::string_view{\"\/\"},\n std::string_view{\"-\"},\n std::string_view{\"\\\\\"}\n };\n constexpr std::string_view filled_char = \"#\";\n constexpr std::string_view empty_char = \"-\";\n constexpr std::string_view start_char = \"[\";\n constexpr std::string_view end_char = \"]\";\n\n const auto percent = KeepWithin(R01(), apercent);\n\n const auto number_of_characters = static_cast<int>\n (\n percent * total_number_of_characters\n );\n\n const auto now = Now();\n if (!force && SecondsBetween(last, now) < min_interval_seconds)\n {\n return;\n }\n last = now;\n\n SetConsolePosition(position);\n std::cout << start_char;\n for (int i = 0; i < number_of_characters; i += 1)\n {\n std::cout << filled_char;\n }\n for\n (\n int i = number_of_characters;\n i < total_number_of_characters;\n i += 1\n )\n {\n std::cout << empty_char;\n }\n std::cout << end_char;\n\n std::cout << \"\\n\";\n }\n\n void\n CliProgressBarInfinite::Step(int each)\n {\n index += 1;\n if(index < each) { return; }\n\n index -= each;\n\n percent += 0.01f;\n if(percent > 1) { percent -= 1; }\n\n progress.Update(percent);\n }\n} \/\/ namespace euphoria::core\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1580\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1052481 by johtaylo@johtaylo-JTBUILDER03-increment on 2014\/07\/06 03:00:12<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1581\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file varying_list.hpp\n * \\brief file varying_list.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/util\/string_array.hpp>\n\nnamespace fastuidraw\n{\n namespace glsl\n {\n\/*!\\addtogroup GLSL\n * @{\n *\/\n \/*!\n * \\brief\n * A varying_list lists all the in's of a frag shader (and\n * their names) which is the same as the out's of the vertex\n * shader which which it is paired.\n *\n * A varying is ALWAYS a SCALAR. The varyings of shaders should\n * -never- be declared in the shader code. Instead, each varying\n * should be declared in the \\ref varying_list object passed to\n * the shader object's ctor. The \\ref GLSL module will share the\n * varyings across different shaders within the uber-shader.\n * Indeed, the number of varying the uber-shader has is not the\n * sum of the varyings across all the shaders, but rather is the\n * maximum number of varyings across the shaders present in the\n * uber-shader.\n *\/\n class varying_list\n {\n public:\n \/*!\n * \\brief\n * Enumeration to define the interpolator type of a varying\n *\/\n enum interpolator_type_t\n {\n interpolator_smooth, \/*!< corresponds to \"smooth\" of type float in GLSL *\/\n interpolator_noperspective, \/*!< corresponds to \"noperspective\" of type float in GLSL *\/\n interpolator_flat, \/*!< corresponds to \"flat\" of type float in GLSL *\/\n interpolator_uint, \/*!< corresponds to \"flat\" of type uint in GLSL *\/\n interpolator_int, \/*!< corresponds to \"flat\" of type int in GLSL *\/\n\n interpolator_number_types,\n };\n\n \/*!\n * Ctor.\n *\/\n varying_list(void);\n\n \/*!\n * Copy ctor.\n * \\param rhs value from which to copy\n *\/\n varying_list(const varying_list &rhs);\n\n ~varying_list();\n\n \/*!\n * Assignment operator.\n * \\param rhs value from which to copy\n *\/\n varying_list&\n operator=(const varying_list &rhs);\n\n \/*!\n * Swap operation\n * \\param obj object with which to swap\n *\/\n void\n swap(varying_list &obj);\n\n \/*!\n * Returns the names of the varyings of the\n * specified interpolator type.\n * \\param q interpolator type\n *\/\n c_array<const c_string>\n varyings(enum interpolator_type_t q) const;\n\n \/*!\n * Returns the alias names of the aliases, i.e.\n * the values of the first argument of calls\n * to \\ref add_varying_alias().\n *\/\n c_array<const c_string>\n alias_varying_names(void) const;\n\n \/*!\n * Returns the source names of the aliases, i.e.\n * the values of the second argument of calls to\n * \\ref add_varying_alias().\n *\/\n c_array<const c_string>\n alias_varying_source_names(void) const;\n\n \/*!\n * Add a varying\n * \\param pname name by which to reference the varying\n * \\param q interpolator type of the varying\n *\/\n varying_list&\n add_varying(c_string pname, enum interpolator_type_t q);\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_uint);\n * \\endcode\n *\/\n varying_list&\n add_uint(c_string pname)\n {\n return add_varying(pname, interpolator_uint);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_int);\n * \\endcode\n *\/\n varying_list&\n add_int(c_string pname)\n {\n return add_varying(pname, interpolator_int);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_smooth);\n * \\endcode\n *\/\n varying_list&\n add_float(c_string pname)\n {\n return add_varying(pname, interpolator_smooth);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_flat);\n * \\endcode\n *\/\n varying_list&\n add_float_flat(c_string pname)\n {\n return add_varying(pname, interpolator_flat);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_noperspective);\n * \\endcode\n *\/\n varying_list&\n add_float_noperspective(c_string pname)\n {\n return add_varying(pname, interpolator_noperspective);\n }\n\n \/*!\n * Add an alias to a varying. The use case being if a fixed\n * varying is used in two different roles and aliasing the\n * name makes the GLSL shader code more readable.\n * \\param name the new identifier to reference an existing alias\n * \\param src_name the varying referenced by name, which should\n * be a string value that has been passed as\n * the first argument to \\ref add_varying() or\n * \\ref add_varying_alias().\n *\/\n varying_list&\n add_varying_alias(c_string name, c_string src_name);\n\n private:\n void *m_d;\n };\n\/*! @} *\/\n\n }\n}\n<commit_msg>fastuidraw\/glsl\/varying_list: doxytag fix<commit_after>\/*!\n * \\file varying_list.hpp\n * \\brief file varying_list.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/util\/string_array.hpp>\n\nnamespace fastuidraw\n{\n namespace glsl\n {\n\/*!\\addtogroup GLSL\n * @{\n *\/\n \/*!\n * \\brief\n * A varying_list lists all the in's of a frag shader (and\n * their names) which is the same as the out's of the vertex\n * shader which which it is paired.\n *\n * A varying is ALWAYS a SCALAR. The varyings of shaders should\n * -never- be declared in the shader code. Instead, each varying\n * should be declared in the \\ref varying_list object passed to\n * the shader object's ctor. The \\ref GLSL module will share the\n * varyings across different shaders within the uber-shader.\n * Indeed, the number of varying the uber-shader has is not the\n * sum of the varyings across all the shaders, but rather is the\n * maximum number of varyings across the shaders present in the\n * uber-shader.\n *\/\n class varying_list\n {\n public:\n \/*!\n * \\brief\n * Enumeration to define the interpolator type of a varying\n *\/\n enum interpolator_type_t\n {\n interpolator_smooth, \/*!< corresponds to \"smooth\" of type float in GLSL *\/\n interpolator_noperspective, \/*!< corresponds to \"noperspective\" of type float in GLSL *\/\n interpolator_flat, \/*!< corresponds to \"flat\" of type float in GLSL *\/\n interpolator_uint, \/*!< corresponds to \"flat\" of type uint in GLSL *\/\n interpolator_int, \/*!< corresponds to \"flat\" of type int in GLSL *\/\n\n interpolator_number_types,\n };\n\n \/*!\n * Ctor.\n *\/\n varying_list(void);\n\n \/*!\n * Copy ctor.\n * \\param rhs value from which to copy\n *\/\n varying_list(const varying_list &rhs);\n\n ~varying_list();\n\n \/*!\n * Assignment operator.\n * \\param rhs value from which to copy\n *\/\n varying_list&\n operator=(const varying_list &rhs);\n\n \/*!\n * Swap operation\n * \\param obj object with which to swap\n *\/\n void\n swap(varying_list &obj);\n\n \/*!\n * Returns the names of the varyings of the\n * specified interpolator type.\n * \\param q interpolator type\n *\/\n c_array<const c_string>\n varyings(enum interpolator_type_t q) const;\n\n \/*!\n * Returns the alias names of the aliases, i.e.\n * the values of the first argument of calls\n * to \\ref add_varying_alias().\n *\/\n c_array<const c_string>\n alias_varying_names(void) const;\n\n \/*!\n * Returns the source names of the aliases, i.e.\n * the values of the second argument of calls to\n * \\ref add_varying_alias().\n *\/\n c_array<const c_string>\n alias_varying_source_names(void) const;\n\n \/*!\n * Add a varying\n * \\param pname name by which to reference the varying\n * \\param q interpolator type of the varying\n *\/\n varying_list&\n add_varying(c_string pname, enum interpolator_type_t q);\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_uint);\n * \\endcode\n *\/\n varying_list&\n add_uint(c_string pname)\n {\n return add_varying(pname, interpolator_uint);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_int);\n * \\endcode\n *\/\n varying_list&\n add_int(c_string pname)\n {\n return add_varying(pname, interpolator_int);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_smooth);\n * \\endcode\n *\/\n varying_list&\n add_float(c_string pname)\n {\n return add_varying(pname, interpolator_smooth);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_flat);\n * \\endcode\n *\/\n varying_list&\n add_float_flat(c_string pname)\n {\n return add_varying(pname, interpolator_flat);\n }\n\n \/*!\n * Add an uint varying, equivalent to\n * \\code\n * add_varying(pname, interpolator_noperspective);\n * \\endcode\n *\/\n varying_list&\n add_float_noperspective(c_string pname)\n {\n return add_varying(pname, interpolator_noperspective);\n }\n\n \/*!\n * Add an alias to a varying. The use case being if a fixed\n * varying is used in two different roles and aliasing the\n * name makes the GLSL shader code more readable.\n * \\param name the new identifier to reference an existing varying\n * \\param src_name the varying referenced by name, which should\n * be a string value that has been passed as\n * the first argument to \\ref add_varying() or\n * \\ref add_varying_alias().\n *\/\n varying_list&\n add_varying_alias(c_string name, c_string src_name);\n\n private:\n void *m_d;\n };\n\/*! @} *\/\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2095\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1258794 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/04\/16 03:00:10<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2096\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2410\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1403666 by johtaylo@johtaylo-jtincrementor-increment on 2017\/04\/28 03:00:06<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2411\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2671\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1566979 by johtaylo@johtaylo-jtincrementor2-increment on 2018\/06\/12 03:00:06<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2672\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2550\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1490975 by johtaylo@johtaylo-jtincrementor2-increment on 2017\/12\/06 03:00:04<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2551\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/notifier\/base\/async_network_alive.h\"\n\n#include <sys\/socket.h>\n#include <asm\/types.h>\n#include <linux\/netlink.h>\n#include <linux\/rtnetlink.h>\n\n#include \"base\/logging.h\"\n#include \"talk\/base\/physicalsocketserver.h\"\n\nnamespace notifier {\n\nclass AsyncNetworkAliveLinux : public AsyncNetworkAlive {\n public:\n AsyncNetworkAliveLinux() {\n if (pipe(exit_pipe_) == -1) {\n PLOG(ERROR) << \"Could not create pipe for exit signal.\";\n exit_pipe_[0] = 0;\n exit_pipe_[1] = 0;\n }\n }\n\n virtual ~AsyncNetworkAliveLinux() {\n if (exit_pipe_[1]) {\n close(exit_pipe_[1]);\n }\n }\n\n protected:\n \/\/ SignalThread Interface\n virtual void DoWork() {\n if (!exit_pipe_[0]) {\n \/\/ If we don't have an exit flag to listen for, set the error flag and\n \/\/ abort.\n error_ = true;\n return;\n }\n\n \/\/ This function listens for changes to network interfaces, and link state.\n \/\/ It's copied from syncapi.cc.\n struct sockaddr_nl socket_address;\n\n memset(&socket_address, 0, sizeof(socket_address));\n socket_address.nl_family = AF_NETLINK;\n socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;\n\n \/\/ NETLINK_ROUTE is the protocol used to update the kernel routing table.\n int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);\n bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address));\n\n fd_set rdfs;\n FD_ZERO(&rdfs);\n FD_SET(fd, &rdfs);\n FD_SET(exit_pipe_[0], &rdfs);\n\n int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0];\n\n int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL);\n\n if (result <= 0) {\n error_ = true;\n PLOG(ERROR) << \"select() returned unexpected result \" << result;\n close(fd);\n close(exit_pipe_[0]);\n return;\n }\n\n \/\/ Since we received a change from the socket, read the change in.\n if (FD_ISSET(fd, &rdfs)) {\n char buf[4096];\n struct iovec iov = { buf, sizeof(buf) };\n struct sockaddr_nl sa;\n\n struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };\n recvmsg(fd, &msg, 0);\n }\n\n close(fd);\n\n \/\/ If exit_pipe was written to, we must be shutting down.\n if (FD_ISSET(exit_pipe_[0], &rdfs)) {\n alive_ = false;\n error_ = true;\n close(exit_pipe_[0]);\n return;\n }\n\n \/\/ If there is an active connection, check that talk.google.com:5222\n \/\/ is reachable.\n talk_base::PhysicalSocketServer physical;\n scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM));\n if (socket->Connect(talk_base::SocketAddress(\"talk.google.com\", 5222))) {\n alive_ = false;\n } else {\n alive_ = true;\n }\n }\n\n virtual void OnWorkStop() {\n if (exit_pipe_[1]) {\n char data = 0;\n \/\/ We can't ignore the return value on write(), since that generates a\n \/\/ compile warning. However, since we're exiting, there's nothing we can\n \/\/ do if this fails except to log it.\n if (write(exit_pipe_[1], &data, 1) == -1) {\n PLOG(WARNING) << \"Error sending error signal to AsyncNetworkAliveLinux\";\n }\n }\n }\n\n private:\n int exit_pipe_[2];\n DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux);\n};\n\nAsyncNetworkAlive* AsyncNetworkAlive::Create() {\n return new AsyncNetworkAliveLinux();\n}\n\n} \/\/ namespace notifier\n<commit_msg>Clean up read FDs in async network alive. This prevents chrome from eating all FDs.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/notifier\/base\/async_network_alive.h\"\n\n#include <sys\/socket.h>\n#include <asm\/types.h>\n#include <linux\/netlink.h>\n#include <linux\/rtnetlink.h>\n\n#include \"base\/logging.h\"\n#include \"talk\/base\/physicalsocketserver.h\"\n\nnamespace notifier {\n\nclass AsyncNetworkAliveLinux : public AsyncNetworkAlive {\n public:\n AsyncNetworkAliveLinux() {\n if (pipe(exit_pipe_) == -1) {\n PLOG(ERROR) << \"Could not create pipe for exit signal.\";\n exit_pipe_[0] = 0;\n exit_pipe_[1] = 0;\n }\n }\n\n virtual ~AsyncNetworkAliveLinux() {\n if (exit_pipe_[1]) {\n \/\/ Ensure that we've signalled the thread to quit.\n char data = 0;\n if (write(exit_pipe_[1], &data, 1) == -1) {\n PLOG(WARNING) << \"Error sending error signal to AsyncNetworkAliveLinux\";\n }\n close(exit_pipe_[1]);\n exit_pipe_[1] = 0;\n }\n if (exit_pipe_[0]) {\n close(exit_pipe_[0]);\n exit_pipe_[0] = 0;\n }\n }\n\n protected:\n \/\/ SignalThread Interface\n virtual void DoWork() {\n if (!exit_pipe_[0]) {\n PLOG(ERROR) << \"No exit flag to listen for.\";\n \/\/ If we don't have an exit flag to listen for, set the error flag and\n \/\/ abort.\n error_ = true;\n return;\n }\n\n \/\/ This function listens for changes to network interfaces, and link state.\n \/\/ It's copied from syncapi.cc.\n struct sockaddr_nl socket_address;\n\n memset(&socket_address, 0, sizeof(socket_address));\n socket_address.nl_family = AF_NETLINK;\n socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;\n\n \/\/ NETLINK_ROUTE is the protocol used to update the kernel routing table.\n int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);\n bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address));\n\n fd_set rdfs;\n FD_ZERO(&rdfs);\n FD_SET(fd, &rdfs);\n FD_SET(exit_pipe_[0], &rdfs);\n\n int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0];\n\n int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL);\n\n if (result <= 0) {\n error_ = true;\n PLOG(ERROR) << \"select() returned unexpected result \" << result;\n close(fd);\n close(exit_pipe_[0]);\n exit_pipe_[0] = 0;\n return;\n }\n\n \/\/ Since we received a change from the socket, read the change in.\n if (FD_ISSET(fd, &rdfs)) {\n char buf[4096];\n struct iovec iov = { buf, sizeof(buf) };\n struct sockaddr_nl sa;\n\n struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };\n recvmsg(fd, &msg, 0);\n }\n\n close(fd);\n\n \/\/ If exit_pipe was written to, we must be shutting down.\n if (exit_pipe_[0] == 0 || FD_ISSET(exit_pipe_[0], &rdfs)) {\n alive_ = false;\n error_ = true;\n close(exit_pipe_[0]);\n exit_pipe_[0] = 0;\n return;\n }\n\n \/\/ If there is an active connection, check that talk.google.com:5222\n \/\/ is reachable.\n talk_base::PhysicalSocketServer physical;\n scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM));\n if (socket->Connect(talk_base::SocketAddress(\"talk.google.com\", 5222))) {\n alive_ = false;\n } else {\n alive_ = true;\n }\n\n close(exit_pipe_[0]);\n exit_pipe_[0] = 0;\n }\n\n virtual void OnWorkStop() {\n if (exit_pipe_[1]) {\n char data = 0;\n \/\/ We can't ignore the return value on write(), since that generates a\n \/\/ compile warning. However, since we're exiting, there's nothing we can\n \/\/ do if this fails except to log it.\n if (write(exit_pipe_[1], &data, 1) == -1) {\n PLOG(WARNING) << \"Error sending error signal to AsyncNetworkAliveLinux\";\n }\n }\n }\n\n private:\n int exit_pipe_[2];\n DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux);\n};\n\nAsyncNetworkAlive* AsyncNetworkAlive::Create() {\n return new AsyncNetworkAliveLinux();\n}\n\n} \/\/ namespace notifier\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/chrome_web_contents_view_win_delegate.h\"\n\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"chrome\/browser\/tab_contents\/web_drag_bookmark_handler_win.h\"\n#include \"chrome\/browser\/ui\/constrained_window_tab_helper.h\"\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/views\/constrained_window_views.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/render_view_context_menu_views.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/render_widget_host_view.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/view_storage.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nChromeWebContentsViewWinDelegate::ChromeWebContentsViewWinDelegate(\n content::WebContents* web_contents)\n : web_contents_(web_contents) {\n last_focused_view_storage_id_ =\n views::ViewStorage::GetInstance()->CreateStorageID();\n}\n\nChromeWebContentsViewWinDelegate::~ChromeWebContentsViewWinDelegate() {\n \/\/ Makes sure to remove any stored view we may still have in the ViewStorage.\n \/\/\n \/\/ It is possible the view went away before us, so we only do this if the\n \/\/ view is registered.\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n}\n\ncontent::WebDragDestDelegate*\n ChromeWebContentsViewWinDelegate::GetDragDestDelegate() {\n \/\/ We install a chrome specific handler to intercept bookmark drags for the\n \/\/ bookmark manager\/extension API.\n bookmark_handler_.reset(new WebDragBookmarkHandlerWin);\n return bookmark_handler_.get();\n}\n\nbool ChromeWebContentsViewWinDelegate::Focus() {\n TabContentsWrapper* wrapper =\n TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);\n if (wrapper) {\n views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();\n if (sad_tab) {\n sad_tab->GetContentsView()->RequestFocus();\n return true;\n }\n\n \/\/ TODO(erg): TabContents used to own constrained windows, which is why\n \/\/ this is here. Eventually this should be ported to a containing view\n \/\/ specializing in constrained window management.\n ConstrainedWindowTabHelper* helper =\n wrapper->constrained_window_tab_helper();\n if (helper->constrained_window_count() > 0) {\n ConstrainedWindow* window = *helper->constrained_window_begin();\n DCHECK(window);\n window->FocusConstrainedWindow();\n return true;\n }\n }\n return false;\n}\n\nvoid ChromeWebContentsViewWinDelegate::TakeFocus(bool reverse) {\n GetFocusManager()->AdvanceFocus(reverse);\n}\n\nvoid ChromeWebContentsViewWinDelegate::StoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (focused_view)\n view_storage->StoreView(last_focused_view_storage_id_, focused_view);\n}\n\nvoid ChromeWebContentsViewWinDelegate::RestoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n views::View* last_focused_view =\n view_storage->RetrieveView(last_focused_view_storage_id_);\n\n if (!last_focused_view) {\n SetInitialFocus();\n } else {\n if (last_focused_view->IsFocusable() &&\n GetFocusManager()->ContainsView(last_focused_view)) {\n last_focused_view->RequestFocus();\n } else {\n \/\/ The focused view may not belong to the same window hierarchy (e.g.\n \/\/ if the location bar was focused and the tab is dragged out), or it may\n \/\/ no longer be focusable (e.g. if the location bar was focused and then\n \/\/ we switched to fullscreen mode). In that case we default to the\n \/\/ default focus.\n SetInitialFocus();\n }\n view_storage->RemoveView(last_focused_view_storage_id_);\n }\n}\n\nvoid ChromeWebContentsViewWinDelegate::ShowContextMenu(\n const content::ContextMenuParams& params) {\n context_menu_.reset(new RenderViewContextMenuViews(web_contents_, params));\n context_menu_->Init();\n\n \/\/ Don't show empty menus.\n if (context_menu_->menu_model().GetItemCount() == 0)\n return;\n\n gfx::Point screen_point(params.x, params.y);\n\n POINT temp = screen_point.ToPOINT();\n ClientToScreen(web_contents_->GetView()->GetNativeView(), &temp);\n screen_point = temp;\n\n \/\/ Enable recursive tasks on the message loop so we can get updates while\n \/\/ the context menu is being displayed.\n MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());\n context_menu_->RunMenuAt(\n GetTopLevelWidget(), screen_point.x(), screen_point.y());\n}\n\nvoid ChromeWebContentsViewWinDelegate::SizeChanged(const gfx::Size& size) {\n TabContentsWrapper* wrapper =\n TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);\n if (!wrapper)\n return;\n views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();\n if (sad_tab)\n sad_tab->SetBounds(gfx::Rect(size));\n}\n\nviews::Widget* ChromeWebContentsViewWinDelegate::GetTopLevelWidget() {\n HWND top_level_window = web_contents_->GetView()->GetTopLevelNativeWindow();\n if (!top_level_window)\n return NULL;\n return views::Widget::GetWidgetForNativeWindow(top_level_window);\n}\n\nviews::FocusManager*\n ChromeWebContentsViewWinDelegate::GetFocusManager() {\n views::Widget* toplevel_widget = GetTopLevelWidget();\n return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;\n}\n\nvoid ChromeWebContentsViewWinDelegate::SetInitialFocus() {\n if (web_contents_->FocusLocationBarByDefault()) {\n web_contents_->SetFocusToLocationBar(false);\n } else {\n web_contents_->GetView()->Focus();\n }\n}\n<commit_msg>Fix Win builder dbg, RenderViewContextMenuViews::RunMenuAt now has only two parameters.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/chrome_web_contents_view_win_delegate.h\"\n\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"chrome\/browser\/tab_contents\/web_drag_bookmark_handler_win.h\"\n#include \"chrome\/browser\/ui\/constrained_window_tab_helper.h\"\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/views\/constrained_window_views.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/render_view_context_menu_views.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/render_widget_host_view.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/view_storage.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nChromeWebContentsViewWinDelegate::ChromeWebContentsViewWinDelegate(\n content::WebContents* web_contents)\n : web_contents_(web_contents) {\n last_focused_view_storage_id_ =\n views::ViewStorage::GetInstance()->CreateStorageID();\n}\n\nChromeWebContentsViewWinDelegate::~ChromeWebContentsViewWinDelegate() {\n \/\/ Makes sure to remove any stored view we may still have in the ViewStorage.\n \/\/\n \/\/ It is possible the view went away before us, so we only do this if the\n \/\/ view is registered.\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n}\n\ncontent::WebDragDestDelegate*\n ChromeWebContentsViewWinDelegate::GetDragDestDelegate() {\n \/\/ We install a chrome specific handler to intercept bookmark drags for the\n \/\/ bookmark manager\/extension API.\n bookmark_handler_.reset(new WebDragBookmarkHandlerWin);\n return bookmark_handler_.get();\n}\n\nbool ChromeWebContentsViewWinDelegate::Focus() {\n TabContentsWrapper* wrapper =\n TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);\n if (wrapper) {\n views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();\n if (sad_tab) {\n sad_tab->GetContentsView()->RequestFocus();\n return true;\n }\n\n \/\/ TODO(erg): TabContents used to own constrained windows, which is why\n \/\/ this is here. Eventually this should be ported to a containing view\n \/\/ specializing in constrained window management.\n ConstrainedWindowTabHelper* helper =\n wrapper->constrained_window_tab_helper();\n if (helper->constrained_window_count() > 0) {\n ConstrainedWindow* window = *helper->constrained_window_begin();\n DCHECK(window);\n window->FocusConstrainedWindow();\n return true;\n }\n }\n return false;\n}\n\nvoid ChromeWebContentsViewWinDelegate::TakeFocus(bool reverse) {\n GetFocusManager()->AdvanceFocus(reverse);\n}\n\nvoid ChromeWebContentsViewWinDelegate::StoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n\n if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)\n view_storage->RemoveView(last_focused_view_storage_id_);\n\n views::View* focused_view = GetFocusManager()->GetFocusedView();\n if (focused_view)\n view_storage->StoreView(last_focused_view_storage_id_, focused_view);\n}\n\nvoid ChromeWebContentsViewWinDelegate::RestoreFocus() {\n views::ViewStorage* view_storage = views::ViewStorage::GetInstance();\n views::View* last_focused_view =\n view_storage->RetrieveView(last_focused_view_storage_id_);\n\n if (!last_focused_view) {\n SetInitialFocus();\n } else {\n if (last_focused_view->IsFocusable() &&\n GetFocusManager()->ContainsView(last_focused_view)) {\n last_focused_view->RequestFocus();\n } else {\n \/\/ The focused view may not belong to the same window hierarchy (e.g.\n \/\/ if the location bar was focused and the tab is dragged out), or it may\n \/\/ no longer be focusable (e.g. if the location bar was focused and then\n \/\/ we switched to fullscreen mode). In that case we default to the\n \/\/ default focus.\n SetInitialFocus();\n }\n view_storage->RemoveView(last_focused_view_storage_id_);\n }\n}\n\nvoid ChromeWebContentsViewWinDelegate::ShowContextMenu(\n const content::ContextMenuParams& params) {\n context_menu_.reset(new RenderViewContextMenuViews(web_contents_, params));\n context_menu_->Init();\n\n \/\/ Don't show empty menus.\n if (context_menu_->menu_model().GetItemCount() == 0)\n return;\n\n gfx::Point screen_point(params.x, params.y);\n\n POINT temp = screen_point.ToPOINT();\n ClientToScreen(web_contents_->GetView()->GetNativeView(), &temp);\n screen_point = temp;\n\n \/\/ Enable recursive tasks on the message loop so we can get updates while\n \/\/ the context menu is being displayed.\n MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());\n context_menu_->RunMenuAt(GetTopLevelWidget(), screen_point);\n}\n\nvoid ChromeWebContentsViewWinDelegate::SizeChanged(const gfx::Size& size) {\n TabContentsWrapper* wrapper =\n TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);\n if (!wrapper)\n return;\n views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();\n if (sad_tab)\n sad_tab->SetBounds(gfx::Rect(size));\n}\n\nviews::Widget* ChromeWebContentsViewWinDelegate::GetTopLevelWidget() {\n HWND top_level_window = web_contents_->GetView()->GetTopLevelNativeWindow();\n if (!top_level_window)\n return NULL;\n return views::Widget::GetWidgetForNativeWindow(top_level_window);\n}\n\nviews::FocusManager*\n ChromeWebContentsViewWinDelegate::GetFocusManager() {\n views::Widget* toplevel_widget = GetTopLevelWidget();\n return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;\n}\n\nvoid ChromeWebContentsViewWinDelegate::SetInitialFocus() {\n if (web_contents_->FocusLocationBarByDefault()) {\n web_contents_->SetFocusToLocationBar(false);\n } else {\n web_contents_->GetView()->Focus();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_view_win.h\"\n\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"chrome\/browser\/tab_contents\/web_drop_target_win.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_drag_win.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_view_delegate.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/tab_contents_view.h\"\n\nnamespace {\n\n\/\/ Tabs must be created as child widgets, otherwise they will be given\n\/\/ a FocusManager which will conflict with the FocusManager of the\n\/\/ window they eventually end up attached to.\n\/\/\n\/\/ A tab will not have a parent HWND whenever it is not active in its\n\/\/ host window - for example at creation time and when it's in the\n\/\/ background, so we provide a default widget to host them.\n\/\/\n\/\/ It may be tempting to use GetDesktopWindow() instead, but this is\n\/\/ problematic as the shell sends messages to children of the desktop\n\/\/ window that interact poorly with us.\n\/\/\n\/\/ See: http:\/\/crbug.com\/16476\nHWND GetHiddenTabHostWindow() {\n static views::Widget* widget = NULL;\n\n if (!widget) {\n widget = new views::Widget;\n \/\/ We don't want this widget to be closed automatically, this causes\n \/\/ problems in tests that close the last non-secondary window.\n widget->set_is_secondary_widget(false);\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);\n widget->Init(params);\n \/\/ If a background window requests focus, the hidden tab host will\n \/\/ be activated to focus the tab. Use WS_DISABLED to prevent\n \/\/ this.\n EnableWindow(widget->GetNativeView(), FALSE);\n }\n\n return widget->GetNativeView();\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, public:\n\nNativeTabContentsViewWin::NativeTabContentsViewWin(\n internal::NativeTabContentsViewDelegate* delegate)\n : views::NativeWidgetWin(delegate->AsNativeWidgetDelegate()),\n delegate_(delegate) {\n}\n\nNativeTabContentsViewWin::~NativeTabContentsViewWin() {\n CloseNow();\n}\n\nTabContents* NativeTabContentsViewWin::GetTabContents() const {\n return delegate_->GetTabContents();\n}\n\nvoid NativeTabContentsViewWin::EndDragging() {\n delegate_->OnNativeTabContentsViewDraggingEnded();\n drag_handler_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, NativeTabContentsView implementation:\n\nvoid NativeTabContentsViewWin::InitNativeTabContentsView() {\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.native_widget = this;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.parent = GetHiddenTabHostWindow();\n GetWidget()->Init(params);\n\n \/\/ Remove the root view drop target so we can register our own.\n RevokeDragDrop(GetNativeView());\n drop_target_ = new WebDropTarget(GetNativeView(),\n delegate_->GetTabContents());\n}\n\nvoid NativeTabContentsViewWin::Unparent() {\n \/\/ Note that we do not DCHECK on focus_manager_ as it may be NULL when used\n \/\/ with an external tab container.\n views::Widget::ReparentNativeView(GetNativeView(), GetHiddenTabHostWindow());\n}\n\nRenderWidgetHostView* NativeTabContentsViewWin::CreateRenderWidgetHostView(\n RenderWidgetHost* render_widget_host) {\n RenderWidgetHostViewWin* view =\n new RenderWidgetHostViewWin(render_widget_host);\n view->CreateWnd(GetNativeView());\n view->ShowWindow(SW_SHOW);\n return view;\n}\n\ngfx::NativeWindow NativeTabContentsViewWin::GetTopLevelNativeWindow() const {\n return ::GetAncestor(GetNativeView(), GA_ROOT);\n}\n\nvoid NativeTabContentsViewWin::SetPageTitle(const std::wstring& title) {\n \/\/ It's possible to get this after the hwnd has been destroyed.\n if (GetNativeView())\n ::SetWindowText(GetNativeView(), title.c_str());\n}\n\nvoid NativeTabContentsViewWin::StartDragging(const WebDropData& drop_data,\n WebKit::WebDragOperationsMask ops,\n const SkBitmap& image,\n const gfx::Point& image_offset) {\n drag_handler_ = new TabContentsDragWin(this);\n drag_handler_->StartDragging(drop_data, ops, image, image_offset);\n}\n\nvoid NativeTabContentsViewWin::CancelDrag() {\n drag_handler_->CancelDrag();\n}\n\nbool NativeTabContentsViewWin::IsDoingDrag() const {\n return drag_handler_.get() != NULL;\n}\n\nvoid NativeTabContentsViewWin::SetDragCursor(\n WebKit::WebDragOperation operation) {\n drop_target_->set_drag_cursor(operation);\n}\n\nviews::NativeWidget* NativeTabContentsViewWin::AsNativeWidget() {\n return this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, views::NativeWidgetWin overrides:\n\nvoid NativeTabContentsViewWin::OnDestroy() {\n if (drop_target_.get()) {\n RevokeDragDrop(GetNativeView());\n drop_target_ = NULL;\n }\n\n NativeWidgetWin::OnDestroy();\n}\n\nvoid NativeTabContentsViewWin::OnHScroll(int scroll_type,\n short position,\n HWND scrollbar) {\n ScrollCommon(WM_HSCROLL, scroll_type, position, scrollbar);\n}\n\nLRESULT NativeTabContentsViewWin::OnMouseRange(UINT msg,\n WPARAM w_param,\n LPARAM l_param) {\n if (delegate_->IsShowingSadTab())\n return NativeWidgetWin::OnMouseRange(msg, w_param, l_param);\n\n switch (msg) {\n case WM_LBUTTONDOWN:\n case WM_MBUTTONDOWN:\n case WM_RBUTTONDOWN: {\n delegate_->OnNativeTabContentsViewMouseDown();\n break;\n }\n case WM_MOUSEMOVE:\n delegate_->OnNativeTabContentsViewMouseMove(true);\n break;\n default:\n break;\n }\n return 0;\n}\n\n\/\/ A message is reflected here from view().\n\/\/ Return non-zero to indicate that it is handled here.\n\/\/ Return 0 to allow view() to further process it.\nLRESULT NativeTabContentsViewWin::OnReflectedMessage(UINT msg,\n WPARAM w_param,\n LPARAM l_param) {\n MSG* message = reinterpret_cast<MSG*>(l_param);\n switch (message->message) {\n case WM_MOUSEWHEEL:\n \/\/ This message is reflected from the view() to this window.\n if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {\n delegate_->OnNativeTabContentsViewWheelZoom(\n GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);\n return 1;\n }\n break;\n case WM_HSCROLL:\n case WM_VSCROLL:\n if (ScrollZoom(LOWORD(message->wParam)))\n return 1;\n default:\n break;\n }\n\n return 0;\n}\n\nvoid NativeTabContentsViewWin::OnVScroll(int scroll_type,\n short position,\n HWND scrollbar) {\n ScrollCommon(WM_VSCROLL, scroll_type, position, scrollbar);\n}\n\nvoid NativeTabContentsViewWin::OnWindowPosChanged(WINDOWPOS* window_pos) {\n if (window_pos->flags & SWP_HIDEWINDOW) {\n delegate_->OnNativeTabContentsViewHidden();\n } else {\n \/\/ The TabContents was shown by a means other than the user selecting a\n \/\/ Tab, e.g. the window was minimized then restored.\n if (window_pos->flags & SWP_SHOWWINDOW)\n delegate_->OnNativeTabContentsViewShown();\n\n \/\/ Unless we were specifically told not to size, cause the renderer to be\n \/\/ sized to the new bounds, which forces a repaint. Not required for the\n \/\/ simple minimize-restore case described above, for example, since the\n \/\/ size hasn't changed.\n if (!(window_pos->flags & SWP_NOSIZE)) {\n delegate_->OnNativeTabContentsViewSized(\n gfx::Size(window_pos->cx, window_pos->cy));\n }\n }\n NativeWidgetWin::OnWindowPosChanged(window_pos);\n}\n\nvoid NativeTabContentsViewWin::OnSize(UINT param, const CSize& size) {\n \/\/ NOTE: Because TabContentsViewViews handles OnWindowPosChanged without\n \/\/ calling DefWindowProc, OnSize is NOT called on window resize. This handler\n \/\/ is called only once when the window is created.\n\n \/\/ Don't call base class OnSize to avoid useless layout for 0x0 size.\n \/\/ We will get OnWindowPosChanged later and layout root view in WasSized.\n\n \/\/ Hack for ThinkPad touch-pad driver.\n \/\/ Set fake scrollbars so that we can get scroll messages,\n SCROLLINFO si = {0};\n si.cbSize = sizeof(si);\n si.fMask = SIF_ALL;\n\n si.nMin = 1;\n si.nMax = 100;\n si.nPage = 10;\n si.nPos = 50;\n\n ::SetScrollInfo(GetNativeView(), SB_HORZ, &si, FALSE);\n ::SetScrollInfo(GetNativeView(), SB_VERT, &si, FALSE);\n}\n\nLRESULT NativeTabContentsViewWin::OnNCCalcSize(BOOL w_param, LPARAM l_param) {\n \/\/ Hack for ThinkPad mouse wheel driver. We have set the fake scroll bars\n \/\/ to receive scroll messages from ThinkPad touch-pad driver. Suppress\n \/\/ painting of scrollbars by returning 0 size for them.\n return 0;\n}\n\nvoid NativeTabContentsViewWin::OnNCPaint(HRGN rgn) {\n \/\/ Suppress default WM_NCPAINT handling. We don't need to do anything\n \/\/ here since the view will draw everything correctly.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, private:\n\nvoid NativeTabContentsViewWin::ScrollCommon(UINT message, int scroll_type,\n short position, HWND scrollbar) {\n \/\/ This window can receive scroll events as a result of the ThinkPad's\n \/\/ touch-pad scroll wheel emulation.\n if (!ScrollZoom(scroll_type)) {\n \/\/ Reflect scroll message to the view() to give it a chance\n \/\/ to process scrolling.\n SendMessage(delegate_->GetTabContents()->view()->GetContentNativeView(),\n message, MAKELONG(scroll_type, position),\n reinterpret_cast<LPARAM>(scrollbar));\n }\n}\n\nbool NativeTabContentsViewWin::ScrollZoom(int scroll_type) {\n \/\/ If ctrl is held, zoom the UI. There are three issues with this:\n \/\/ 1) Should the event be eaten or forwarded to content? We eat the event,\n \/\/ which is like Firefox and unlike IE.\n \/\/ 2) Should wheel up zoom in or out? We zoom in (increase font size), which\n \/\/ is like IE and Google maps, but unlike Firefox.\n \/\/ 3) Should the mouse have to be over the content area? We zoom as long as\n \/\/ content has focus, although FF and IE require that the mouse is over\n \/\/ content. This is because all events get forwarded when content has\n \/\/ focus.\n if (GetAsyncKeyState(VK_CONTROL) & 0x8000) {\n int distance = 0;\n switch (scroll_type) {\n case SB_LINEUP:\n distance = WHEEL_DELTA;\n break;\n case SB_LINEDOWN:\n distance = -WHEEL_DELTA;\n break;\n \/\/ TODO(joshia): Handle SB_PAGEUP, SB_PAGEDOWN, SB_THUMBPOSITION,\n \/\/ and SB_THUMBTRACK for completeness\n default:\n break;\n }\n\n delegate_->OnNativeTabContentsViewWheelZoom(distance > 0);\n return true;\n }\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsView, public:\n\n\/\/ static\nNativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(\n internal::NativeTabContentsViewDelegate* delegate) {\n return new NativeTabContentsViewWin(delegate);\n}\n<commit_msg>Use a Window instead of a Widget for the hidden tab host window.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_view_win.h\"\n\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_win.h\"\n#include \"chrome\/browser\/tab_contents\/web_drop_target_win.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_view_delegate.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_drag_win.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Tabs must be created as child widgets, otherwise they will be given\n\/\/ a FocusManager which will conflict with the FocusManager of the\n\/\/ window they eventually end up attached to.\n\/\/\n\/\/ A tab will not have a parent HWND whenever it is not active in its\n\/\/ host window - for example at creation time and when it's in the\n\/\/ background, so we provide a default widget to host them.\n\/\/\n\/\/ It may be tempting to use GetDesktopWindow() instead, but this is\n\/\/ problematic as the shell sends messages to children of the desktop\n\/\/ window that interact poorly with us.\n\/\/\n\/\/ See: http:\/\/crbug.com\/16476\nclass HiddenTabHostWindow : public views::Widget {\n public:\n static HWND Instance();\n\n private:\n HiddenTabHostWindow() {}\n\n ~HiddenTabHostWindow() {\n instance_ = NULL;\n }\n\n \/\/ Do nothing when asked to close. External applications (notably\n \/\/ installers) try to close Chrome by sending WM_CLOSE to Chrome's\n \/\/ top level windows. We don't want the tab host to close due to\n \/\/ those messages. Instead the browser will close when the browser\n \/\/ window receives a WM_CLOSE.\n virtual void Close() OVERRIDE {}\n\n static HiddenTabHostWindow* instance_;\n\n DISALLOW_COPY_AND_ASSIGN(HiddenTabHostWindow);\n};\n\nHiddenTabHostWindow* HiddenTabHostWindow::instance_ = NULL;\n\nHWND HiddenTabHostWindow::Instance() {\n if (instance_ == NULL) {\n instance_ = new HiddenTabHostWindow;\n \/\/ We don't want this widget to be closed automatically, this causes\n \/\/ problems in tests that close the last non-secondary window.\n instance_->set_is_secondary_widget(false);\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);\n instance_->Init(params);\n \/\/ If a background window requests focus, the hidden tab host will\n \/\/ be activated to focus the tab. Disable the window to prevent\n \/\/ this.\n EnableWindow(instance_->GetNativeView(), FALSE);\n }\n\n return instance_->GetNativeView();\n}\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, public:\n\nNativeTabContentsViewWin::NativeTabContentsViewWin(\n internal::NativeTabContentsViewDelegate* delegate)\n : views::NativeWidgetWin(delegate->AsNativeWidgetDelegate()),\n delegate_(delegate) {\n}\n\nNativeTabContentsViewWin::~NativeTabContentsViewWin() {\n CloseNow();\n}\n\nTabContents* NativeTabContentsViewWin::GetTabContents() const {\n return delegate_->GetTabContents();\n}\n\nvoid NativeTabContentsViewWin::EndDragging() {\n delegate_->OnNativeTabContentsViewDraggingEnded();\n drag_handler_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, NativeTabContentsView implementation:\n\nvoid NativeTabContentsViewWin::InitNativeTabContentsView() {\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.native_widget = this;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.parent = HiddenTabHostWindow::Instance();\n GetWidget()->Init(params);\n\n \/\/ Remove the root view drop target so we can register our own.\n RevokeDragDrop(GetNativeView());\n drop_target_ = new WebDropTarget(GetNativeView(),\n delegate_->GetTabContents());\n}\n\nvoid NativeTabContentsViewWin::Unparent() {\n \/\/ Note that we do not DCHECK on focus_manager_ as it may be NULL when used\n \/\/ with an external tab container.\n views::Widget::ReparentNativeView(GetNativeView(),\n HiddenTabHostWindow::Instance());\n}\n\nRenderWidgetHostView* NativeTabContentsViewWin::CreateRenderWidgetHostView(\n RenderWidgetHost* render_widget_host) {\n RenderWidgetHostViewWin* view =\n new RenderWidgetHostViewWin(render_widget_host);\n view->CreateWnd(GetNativeView());\n view->ShowWindow(SW_SHOW);\n return view;\n}\n\ngfx::NativeWindow NativeTabContentsViewWin::GetTopLevelNativeWindow() const {\n return ::GetAncestor(GetNativeView(), GA_ROOT);\n}\n\nvoid NativeTabContentsViewWin::SetPageTitle(const std::wstring& title) {\n \/\/ It's possible to get this after the hwnd has been destroyed.\n if (GetNativeView())\n ::SetWindowText(GetNativeView(), title.c_str());\n}\n\nvoid NativeTabContentsViewWin::StartDragging(const WebDropData& drop_data,\n WebKit::WebDragOperationsMask ops,\n const SkBitmap& image,\n const gfx::Point& image_offset) {\n drag_handler_ = new TabContentsDragWin(this);\n drag_handler_->StartDragging(drop_data, ops, image, image_offset);\n}\n\nvoid NativeTabContentsViewWin::CancelDrag() {\n drag_handler_->CancelDrag();\n}\n\nbool NativeTabContentsViewWin::IsDoingDrag() const {\n return drag_handler_.get() != NULL;\n}\n\nvoid NativeTabContentsViewWin::SetDragCursor(\n WebKit::WebDragOperation operation) {\n drop_target_->set_drag_cursor(operation);\n}\n\nviews::NativeWidget* NativeTabContentsViewWin::AsNativeWidget() {\n return this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, views::NativeWidgetWin overrides:\n\nvoid NativeTabContentsViewWin::OnDestroy() {\n if (drop_target_.get()) {\n RevokeDragDrop(GetNativeView());\n drop_target_ = NULL;\n }\n\n NativeWidgetWin::OnDestroy();\n}\n\nvoid NativeTabContentsViewWin::OnHScroll(int scroll_type,\n short position,\n HWND scrollbar) {\n ScrollCommon(WM_HSCROLL, scroll_type, position, scrollbar);\n}\n\nLRESULT NativeTabContentsViewWin::OnMouseRange(UINT msg,\n WPARAM w_param,\n LPARAM l_param) {\n if (delegate_->IsShowingSadTab())\n return NativeWidgetWin::OnMouseRange(msg, w_param, l_param);\n\n switch (msg) {\n case WM_LBUTTONDOWN:\n case WM_MBUTTONDOWN:\n case WM_RBUTTONDOWN: {\n delegate_->OnNativeTabContentsViewMouseDown();\n break;\n }\n case WM_MOUSEMOVE:\n delegate_->OnNativeTabContentsViewMouseMove(true);\n break;\n default:\n break;\n }\n return 0;\n}\n\n\/\/ A message is reflected here from view().\n\/\/ Return non-zero to indicate that it is handled here.\n\/\/ Return 0 to allow view() to further process it.\nLRESULT NativeTabContentsViewWin::OnReflectedMessage(UINT msg,\n WPARAM w_param,\n LPARAM l_param) {\n MSG* message = reinterpret_cast<MSG*>(l_param);\n switch (message->message) {\n case WM_MOUSEWHEEL:\n \/\/ This message is reflected from the view() to this window.\n if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {\n delegate_->OnNativeTabContentsViewWheelZoom(\n GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);\n return 1;\n }\n break;\n case WM_HSCROLL:\n case WM_VSCROLL:\n if (ScrollZoom(LOWORD(message->wParam)))\n return 1;\n default:\n break;\n }\n\n return 0;\n}\n\nvoid NativeTabContentsViewWin::OnVScroll(int scroll_type,\n short position,\n HWND scrollbar) {\n ScrollCommon(WM_VSCROLL, scroll_type, position, scrollbar);\n}\n\nvoid NativeTabContentsViewWin::OnWindowPosChanged(WINDOWPOS* window_pos) {\n if (window_pos->flags & SWP_HIDEWINDOW) {\n delegate_->OnNativeTabContentsViewHidden();\n } else {\n \/\/ The TabContents was shown by a means other than the user selecting a\n \/\/ Tab, e.g. the window was minimized then restored.\n if (window_pos->flags & SWP_SHOWWINDOW)\n delegate_->OnNativeTabContentsViewShown();\n\n \/\/ Unless we were specifically told not to size, cause the renderer to be\n \/\/ sized to the new bounds, which forces a repaint. Not required for the\n \/\/ simple minimize-restore case described above, for example, since the\n \/\/ size hasn't changed.\n if (!(window_pos->flags & SWP_NOSIZE)) {\n delegate_->OnNativeTabContentsViewSized(\n gfx::Size(window_pos->cx, window_pos->cy));\n }\n }\n NativeWidgetWin::OnWindowPosChanged(window_pos);\n}\n\nvoid NativeTabContentsViewWin::OnSize(UINT param, const CSize& size) {\n \/\/ NOTE: Because TabContentsViewViews handles OnWindowPosChanged without\n \/\/ calling DefWindowProc, OnSize is NOT called on window resize. This handler\n \/\/ is called only once when the window is created.\n\n \/\/ Don't call base class OnSize to avoid useless layout for 0x0 size.\n \/\/ We will get OnWindowPosChanged later and layout root view in WasSized.\n\n \/\/ Hack for ThinkPad touch-pad driver.\n \/\/ Set fake scrollbars so that we can get scroll messages,\n SCROLLINFO si = {0};\n si.cbSize = sizeof(si);\n si.fMask = SIF_ALL;\n\n si.nMin = 1;\n si.nMax = 100;\n si.nPage = 10;\n si.nPos = 50;\n\n ::SetScrollInfo(GetNativeView(), SB_HORZ, &si, FALSE);\n ::SetScrollInfo(GetNativeView(), SB_VERT, &si, FALSE);\n}\n\nLRESULT NativeTabContentsViewWin::OnNCCalcSize(BOOL w_param, LPARAM l_param) {\n \/\/ Hack for ThinkPad mouse wheel driver. We have set the fake scroll bars\n \/\/ to receive scroll messages from ThinkPad touch-pad driver. Suppress\n \/\/ painting of scrollbars by returning 0 size for them.\n return 0;\n}\n\nvoid NativeTabContentsViewWin::OnNCPaint(HRGN rgn) {\n \/\/ Suppress default WM_NCPAINT handling. We don't need to do anything\n \/\/ here since the view will draw everything correctly.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsViewWin, private:\n\nvoid NativeTabContentsViewWin::ScrollCommon(UINT message, int scroll_type,\n short position, HWND scrollbar) {\n \/\/ This window can receive scroll events as a result of the ThinkPad's\n \/\/ touch-pad scroll wheel emulation.\n if (!ScrollZoom(scroll_type)) {\n \/\/ Reflect scroll message to the view() to give it a chance\n \/\/ to process scrolling.\n SendMessage(delegate_->GetTabContents()->view()->GetContentNativeView(),\n message, MAKELONG(scroll_type, position),\n reinterpret_cast<LPARAM>(scrollbar));\n }\n}\n\nbool NativeTabContentsViewWin::ScrollZoom(int scroll_type) {\n \/\/ If ctrl is held, zoom the UI. There are three issues with this:\n \/\/ 1) Should the event be eaten or forwarded to content? We eat the event,\n \/\/ which is like Firefox and unlike IE.\n \/\/ 2) Should wheel up zoom in or out? We zoom in (increase font size), which\n \/\/ is like IE and Google maps, but unlike Firefox.\n \/\/ 3) Should the mouse have to be over the content area? We zoom as long as\n \/\/ content has focus, although FF and IE require that the mouse is over\n \/\/ content. This is because all events get forwarded when content has\n \/\/ focus.\n if (GetAsyncKeyState(VK_CONTROL) & 0x8000) {\n int distance = 0;\n switch (scroll_type) {\n case SB_LINEUP:\n distance = WHEEL_DELTA;\n break;\n case SB_LINEDOWN:\n distance = -WHEEL_DELTA;\n break;\n \/\/ TODO(joshia): Handle SB_PAGEUP, SB_PAGEDOWN, SB_THUMBPOSITION,\n \/\/ and SB_THUMBTRACK for completeness\n default:\n break;\n }\n\n delegate_->OnNativeTabContentsViewWheelZoom(distance > 0);\n return true;\n }\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsView, public:\n\n\/\/ static\nNativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(\n internal::NativeTabContentsViewDelegate* delegate) {\n return new NativeTabContentsViewWin(delegate);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/website_settings\/permission_selector_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/website_settings\/website_settings_ui.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/models\/simple_menu_model.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/views\/controls\/button\/menu_button.h\"\n#include \"ui\/views\/controls\/image_view.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/controls\/menu\/menu_model_adapter.h\"\n#include \"ui\/views\/controls\/menu\/menu_runner.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Left icon margin.\nconst int kPermissionIconMarginLeft = 6;\n\/\/ The width of the column that contains the permissions icons.\nconst int kPermissionIconColumnWidth = 20;\n\n\/\/ An array with |ContentSetting|s ordered by CommandID. The array is used to\n\/\/ lookup a content setting for a given command id.\nconst ContentSetting kSettingsForCommandIDs[] = {\n CONTENT_SETTING_DEFAULT, \/\/ COMMAND_SET_TO_DEFAULT\n CONTENT_SETTING_ALLOW, \/\/ COMMAND_SET_TO_ALLOW\n CONTENT_SETTING_BLOCK, \/\/ COMMAND_SET_TO_BLOCK\n};\n\n} \/\/ namespace\n\nnamespace internal {\n\nclass PermissionMenuModel : public ui::SimpleMenuModel,\n public ui::SimpleMenuModel::Delegate {\n public:\n PermissionMenuModel(ContentSettingsType site_permission,\n ContentSetting default_setting,\n ContentSetting current_setting,\n PermissionSelectorView* selector);\n\n ContentSettingsType site_permission() const { return site_permission_; }\n ContentSetting default_setting() const { return default_setting_; }\n ContentSetting current_setting() const { return current_setting_; }\n\n \/\/ Overridden from ui::SimpleMenuModel::Delegate:\n virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;\n virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;\n virtual bool GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) OVERRIDE;\n virtual void ExecuteCommand(int command_id) OVERRIDE;\n\n private:\n enum CommandID {\n COMMAND_SET_TO_DEFAULT,\n COMMAND_SET_TO_ALLOW,\n COMMAND_SET_TO_BLOCK,\n };\n\n \/\/ The site permission (the |ContentSettingsType|) for which the menu model\n \/\/ provides settings.\n ContentSettingsType site_permission_;\n\n \/\/ The global default setting for the |site_permission_|.\n ContentSetting default_setting_;\n\n \/\/ The currently active setting for the |site_permission|.\n ContentSetting current_setting_;\n\n \/\/ The |permission_selector_|s SelectionChanged method is called whenever the\n \/\/ |current_setting_| is changed.\n PermissionSelectorView* permission_selector_; \/\/ Owned by views hierarchy.\n\n DISALLOW_COPY_AND_ASSIGN(PermissionMenuModel);\n};\n\n\/\/ The |PermissionMenuButton| provides a menu for selecting a setting a\n\/\/ permissions type.\nclass PermissionMenuButton : public views::MenuButton,\n public views::MenuButtonListener {\n public:\n \/\/ Creates a new |PermissionMenuButton| with the passed |text|. The ownership\n \/\/ of the |model| remains with the caller and is not transfered to the\n \/\/ |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a\n \/\/ small icon is be displayed next to the button |text|, indicating that the\n \/\/ button opens a drop down menu.\n PermissionMenuButton(const string16& text,\n PermissionMenuModel* model,\n bool show_menu_marker);\n virtual ~PermissionMenuButton();\n\n \/\/ Overridden from views::MenuButton.\n virtual gfx::Size GetPreferredSize() OVERRIDE;\n\n \/\/ Overridden from views::TextButton.\n virtual void SetText(const string16& text) OVERRIDE;\n\n private:\n \/\/ Overridden from views::MenuButtonListener.\n virtual void OnMenuButtonClicked(View* source,\n const gfx::Point& point) OVERRIDE;\n\n PermissionMenuModel* menu_model_; \/\/ Owned by |PermissionSelectorView|.\n scoped_ptr<views::MenuRunner> menu_runner_;\n\n DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionMenuModel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionMenuModel::PermissionMenuModel(\n ContentSettingsType site_permission,\n ContentSetting default_setting,\n ContentSetting current_setting,\n PermissionSelectorView* parent)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n site_permission_(site_permission),\n default_setting_(default_setting),\n current_setting_(current_setting),\n permission_selector_(parent) {\n string16 label;\n switch (default_setting_) {\n case CONTENT_SETTING_ALLOW:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);\n break;\n case CONTENT_SETTING_BLOCK:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);\n break;\n case CONTENT_SETTING_ASK:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);\n break;\n default:\n break;\n }\n AddCheckItem(COMMAND_SET_TO_DEFAULT, label);\n\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);\n AddCheckItem(COMMAND_SET_TO_ALLOW, label);\n\n if (site_permission != CONTENT_SETTINGS_TYPE_FULLSCREEN) {\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);\n AddCheckItem(COMMAND_SET_TO_BLOCK, label);\n }\n}\n\nbool PermissionMenuModel::IsCommandIdChecked(int command_id) const {\n return current_setting_ == kSettingsForCommandIDs[command_id];\n}\n\nbool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {\n return true;\n}\n\nbool PermissionMenuModel::GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) {\n \/\/ Accelerators are not supported.\n return false;\n}\n\nvoid PermissionMenuModel::ExecuteCommand(int command_id) {\n current_setting_ = kSettingsForCommandIDs[command_id];\n permission_selector_->SelectionChanged();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionMenuButton\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionMenuButton::PermissionMenuButton(const string16& text,\n PermissionMenuModel* model,\n bool show_menu_marker)\n : ALLOW_THIS_IN_INITIALIZER_LIST(MenuButton(NULL, text, this,\n show_menu_marker)),\n menu_model_(model) {\n SetEnabledColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelEnabledColor));\n SetHoverColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelEnabledColor));\n SetDisabledColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelDisabledColor));\n}\n\nPermissionMenuButton::~PermissionMenuButton() {\n}\n\ngfx::Size PermissionMenuButton::GetPreferredSize() {\n gfx::Insets insets = GetInsets();\n \/\/ Scale the button to the current text size.\n gfx::Size prefsize(text_size_.width() + insets.width(),\n text_size_.height() + insets.height());\n if (max_width_ > 0)\n prefsize.set_width(std::min(max_width_, prefsize.width()));\n if (show_menu_marker()) {\n prefsize.Enlarge(menu_marker()->width() +\n views::MenuButton::kMenuMarkerPaddingLeft +\n views::MenuButton::kMenuMarkerPaddingRight,\n 0);\n }\n return prefsize;\n}\n\nvoid PermissionMenuButton::SetText(const string16& text) {\n MenuButton::SetText(text);\n SizeToPreferredSize();\n}\n\nvoid PermissionMenuButton::OnMenuButtonClicked(View* source,\n const gfx::Point& point) {\n views::MenuModelAdapter menu_model_adapter(menu_model_);\n menu_runner_.reset(new views::MenuRunner(menu_model_adapter.CreateMenu()));\n\n gfx::Point p(point);\n p.Offset(-source->width(), 0);\n if (menu_runner_->RunMenuAt(\n source->GetWidget()->GetTopLevelWidget(),\n this,\n gfx::Rect(p, gfx::Size()),\n views::MenuItemView::TOPLEFT,\n views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED)\n return;\n}\n\n} \/\/ namespace internal\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionSelectorView\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionSelectorView::PermissionSelectorView(\n ContentSettingsType type,\n ContentSetting default_setting,\n ContentSetting current_setting,\n content_settings::SettingSource source)\n : icon_(NULL),\n menu_button_(NULL) {\n views::GridLayout* layout = new views::GridLayout(this);\n SetLayoutManager(layout);\n const int column_set_id = 0;\n views::ColumnSet* column_set = layout->AddColumnSet(column_set_id);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::FIXED,\n kPermissionIconColumnWidth,\n 0);\n column_set->AddPaddingColumn(0, kPermissionIconMarginLeft);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::USE_PREF,\n 0,\n 0);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::USE_PREF,\n 0,\n 0);\n\n layout->StartRow(1, column_set_id);\n \/\/ Create the permission icon.\n icon_ = new views::ImageView();\n ContentSetting setting = current_setting;\n if (setting == CONTENT_SETTING_DEFAULT)\n setting = default_setting;\n const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(type, setting);\n icon_->SetImage(image.ToImageSkia());\n layout->AddView(icon_,\n 1,\n 1,\n views::GridLayout::CENTER,\n views::GridLayout::CENTER);\n \/\/ Create the label that displays the permission type.\n views::Label* label = new views::Label(\n l10n_util::GetStringFUTF16(\n IDS_WEBSITE_SETTINGS_PERMISSION_TYPE,\n WebsiteSettingsUI::PermissionTypeToUIString(type)));\n layout->AddView(label,\n 1,\n 1,\n views::GridLayout::LEADING,\n views::GridLayout::CENTER);\n \/\/ Create the permission menu button.\n menu_button_model_.reset(new internal::PermissionMenuModel(\n type, default_setting, current_setting, this));\n bool button_enabled = source == content_settings::SETTING_SOURCE_USER;\n menu_button_ = new internal::PermissionMenuButton(\n WebsiteSettingsUI::PermissionActionToUIString(current_setting,\n default_setting,\n source),\n menu_button_model_.get(),\n button_enabled);\n menu_button_->SetEnabled(button_enabled);\n layout->AddView(menu_button_);\n}\n\nvoid PermissionSelectorView::AddObserver(\n PermissionSelectorViewObserver* observer) {\n observer_list_.AddObserver(observer);\n}\n\nvoid PermissionSelectorView::SelectionChanged() {\n \/\/ Update the icon to reflect the new setting.\n ContentSetting effective_setting = menu_button_model_->current_setting();\n if (effective_setting == CONTENT_SETTING_DEFAULT)\n effective_setting = menu_button_model_->default_setting();\n const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(\n menu_button_model_->site_permission(), effective_setting);\n icon_->SetImage(image.ToImageSkia());\n\n \/\/ Update the menu button text to reflect the new setting.\n menu_button_->SetText(WebsiteSettingsUI::PermissionActionToUIString(\n menu_button_model_->current_setting(),\n menu_button_model_->default_setting(),\n content_settings::SETTING_SOURCE_USER));\n\n FOR_EACH_OBSERVER(PermissionSelectorViewObserver,\n observer_list_,\n OnPermissionChanged(this));\n}\n\nContentSetting PermissionSelectorView::GetSelectedSetting() const {\n return menu_button_model_->current_setting();\n}\n\nContentSettingsType PermissionSelectorView::GetPermissionType() const {\n return menu_button_model_->site_permission();\n}\n\nvoid PermissionSelectorView::ChildPreferredSizeChanged(View* child) {\n SizeToPreferredSize();\n \/\/ FIXME: The parent is only a plain |View| that is used as a\n \/\/ container\/box\/panel. The SizeToPreferredSize method of the parent is\n \/\/ called here directly in order not to implement a custom |View| class with\n \/\/ its own implementation of the ChildPreferredSizeChanged method.\n parent()->SizeToPreferredSize();\n}\n\nPermissionSelectorView::~PermissionSelectorView() {\n}\n<commit_msg>[Views] Make the permissions menus on the Website Settings UI focusable by the TAB key and provuide accasability information.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/website_settings\/permission_selector_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/website_settings\/website_settings_ui.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/models\/simple_menu_model.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/views\/controls\/button\/menu_button.h\"\n#include \"ui\/views\/controls\/image_view.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/controls\/menu\/menu_model_adapter.h\"\n#include \"ui\/views\/controls\/menu\/menu_runner.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Left icon margin.\nconst int kPermissionIconMarginLeft = 6;\n\/\/ The width of the column that contains the permissions icons.\nconst int kPermissionIconColumnWidth = 20;\n\n\/\/ An array with |ContentSetting|s ordered by CommandID. The array is used to\n\/\/ lookup a content setting for a given command id.\nconst ContentSetting kSettingsForCommandIDs[] = {\n CONTENT_SETTING_DEFAULT, \/\/ COMMAND_SET_TO_DEFAULT\n CONTENT_SETTING_ALLOW, \/\/ COMMAND_SET_TO_ALLOW\n CONTENT_SETTING_BLOCK, \/\/ COMMAND_SET_TO_BLOCK\n};\n\n} \/\/ namespace\n\nnamespace internal {\n\nclass PermissionMenuModel : public ui::SimpleMenuModel,\n public ui::SimpleMenuModel::Delegate {\n public:\n PermissionMenuModel(ContentSettingsType site_permission,\n ContentSetting default_setting,\n ContentSetting current_setting,\n PermissionSelectorView* selector);\n\n ContentSettingsType site_permission() const { return site_permission_; }\n ContentSetting default_setting() const { return default_setting_; }\n ContentSetting current_setting() const { return current_setting_; }\n\n \/\/ Overridden from ui::SimpleMenuModel::Delegate:\n virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;\n virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;\n virtual bool GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) OVERRIDE;\n virtual void ExecuteCommand(int command_id) OVERRIDE;\n\n private:\n enum CommandID {\n COMMAND_SET_TO_DEFAULT,\n COMMAND_SET_TO_ALLOW,\n COMMAND_SET_TO_BLOCK,\n };\n\n \/\/ The site permission (the |ContentSettingsType|) for which the menu model\n \/\/ provides settings.\n ContentSettingsType site_permission_;\n\n \/\/ The global default setting for the |site_permission_|.\n ContentSetting default_setting_;\n\n \/\/ The currently active setting for the |site_permission|.\n ContentSetting current_setting_;\n\n \/\/ The |permission_selector_|s SelectionChanged method is called whenever the\n \/\/ |current_setting_| is changed.\n PermissionSelectorView* permission_selector_; \/\/ Owned by views hierarchy.\n\n DISALLOW_COPY_AND_ASSIGN(PermissionMenuModel);\n};\n\n\/\/ The |PermissionMenuButton| provides a menu for selecting a setting a\n\/\/ permissions type.\nclass PermissionMenuButton : public views::MenuButton,\n public views::MenuButtonListener {\n public:\n \/\/ Creates a new |PermissionMenuButton| with the passed |text|. The ownership\n \/\/ of the |model| remains with the caller and is not transfered to the\n \/\/ |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a\n \/\/ small icon is be displayed next to the button |text|, indicating that the\n \/\/ button opens a drop down menu.\n PermissionMenuButton(const string16& text,\n PermissionMenuModel* model,\n bool show_menu_marker);\n virtual ~PermissionMenuButton();\n\n \/\/ Overridden from views::MenuButton.\n virtual gfx::Size GetPreferredSize() OVERRIDE;\n\n \/\/ Overridden from views::TextButton.\n virtual void SetText(const string16& text) OVERRIDE;\n\n \/\/ Overridden from views::View.\n virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;\n\n private:\n \/\/ Overridden from views::MenuButtonListener.\n virtual void OnMenuButtonClicked(View* source,\n const gfx::Point& point) OVERRIDE;\n\n PermissionMenuModel* menu_model_; \/\/ Owned by |PermissionSelectorView|.\n scoped_ptr<views::MenuRunner> menu_runner_;\n\n DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionMenuModel\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionMenuModel::PermissionMenuModel(\n ContentSettingsType site_permission,\n ContentSetting default_setting,\n ContentSetting current_setting,\n PermissionSelectorView* parent)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n site_permission_(site_permission),\n default_setting_(default_setting),\n current_setting_(current_setting),\n permission_selector_(parent) {\n string16 label;\n switch (default_setting_) {\n case CONTENT_SETTING_ALLOW:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);\n break;\n case CONTENT_SETTING_BLOCK:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);\n break;\n case CONTENT_SETTING_ASK:\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);\n break;\n default:\n break;\n }\n AddCheckItem(COMMAND_SET_TO_DEFAULT, label);\n\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);\n AddCheckItem(COMMAND_SET_TO_ALLOW, label);\n\n if (site_permission != CONTENT_SETTINGS_TYPE_FULLSCREEN) {\n label = l10n_util::GetStringUTF16(\n IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);\n AddCheckItem(COMMAND_SET_TO_BLOCK, label);\n }\n}\n\nbool PermissionMenuModel::IsCommandIdChecked(int command_id) const {\n return current_setting_ == kSettingsForCommandIDs[command_id];\n}\n\nbool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {\n return true;\n}\n\nbool PermissionMenuModel::GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) {\n \/\/ Accelerators are not supported.\n return false;\n}\n\nvoid PermissionMenuModel::ExecuteCommand(int command_id) {\n current_setting_ = kSettingsForCommandIDs[command_id];\n permission_selector_->SelectionChanged();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionMenuButton\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionMenuButton::PermissionMenuButton(const string16& text,\n PermissionMenuModel* model,\n bool show_menu_marker)\n : ALLOW_THIS_IN_INITIALIZER_LIST(MenuButton(NULL, text, this,\n show_menu_marker)),\n menu_model_(model) {\n SetEnabledColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelEnabledColor));\n SetHoverColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelEnabledColor));\n SetDisabledColor(ui::NativeTheme::instance()->GetSystemColor(\n ui::NativeTheme::kColorId_LabelDisabledColor));\n}\n\nPermissionMenuButton::~PermissionMenuButton() {\n}\n\ngfx::Size PermissionMenuButton::GetPreferredSize() {\n gfx::Insets insets = GetInsets();\n \/\/ Scale the button to the current text size.\n gfx::Size prefsize(text_size_.width() + insets.width(),\n text_size_.height() + insets.height());\n if (max_width_ > 0)\n prefsize.set_width(std::min(max_width_, prefsize.width()));\n if (show_menu_marker()) {\n prefsize.Enlarge(menu_marker()->width() +\n views::MenuButton::kMenuMarkerPaddingLeft +\n views::MenuButton::kMenuMarkerPaddingRight,\n 0);\n }\n return prefsize;\n}\n\nvoid PermissionMenuButton::SetText(const string16& text) {\n MenuButton::SetText(text);\n SizeToPreferredSize();\n}\n\nvoid PermissionMenuButton::GetAccessibleState(ui::AccessibleViewState* state) {\n MenuButton::GetAccessibleState(state);\n state->value = text();\n}\n\nvoid PermissionMenuButton::OnMenuButtonClicked(View* source,\n const gfx::Point& point) {\n views::MenuModelAdapter menu_model_adapter(menu_model_);\n menu_runner_.reset(new views::MenuRunner(menu_model_adapter.CreateMenu()));\n\n gfx::Point p(point);\n p.Offset(-source->width(), 0);\n if (menu_runner_->RunMenuAt(\n source->GetWidget()->GetTopLevelWidget(),\n this,\n gfx::Rect(p, gfx::Size()),\n views::MenuItemView::TOPLEFT,\n views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED)\n return;\n}\n\n} \/\/ namespace internal\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PermissionSelectorView\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPermissionSelectorView::PermissionSelectorView(\n ContentSettingsType type,\n ContentSetting default_setting,\n ContentSetting current_setting,\n content_settings::SettingSource source)\n : icon_(NULL),\n menu_button_(NULL) {\n views::GridLayout* layout = new views::GridLayout(this);\n SetLayoutManager(layout);\n const int column_set_id = 0;\n views::ColumnSet* column_set = layout->AddColumnSet(column_set_id);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::FIXED,\n kPermissionIconColumnWidth,\n 0);\n column_set->AddPaddingColumn(0, kPermissionIconMarginLeft);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::USE_PREF,\n 0,\n 0);\n column_set->AddColumn(views::GridLayout::FILL,\n views::GridLayout::FILL,\n 1,\n views::GridLayout::USE_PREF,\n 0,\n 0);\n\n layout->StartRow(1, column_set_id);\n \/\/ Create the permission icon.\n icon_ = new views::ImageView();\n ContentSetting setting = current_setting;\n if (setting == CONTENT_SETTING_DEFAULT)\n setting = default_setting;\n const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(type, setting);\n icon_->SetImage(image.ToImageSkia());\n layout->AddView(icon_,\n 1,\n 1,\n views::GridLayout::CENTER,\n views::GridLayout::CENTER);\n \/\/ Create the label that displays the permission type.\n views::Label* label = new views::Label(\n l10n_util::GetStringFUTF16(\n IDS_WEBSITE_SETTINGS_PERMISSION_TYPE,\n WebsiteSettingsUI::PermissionTypeToUIString(type)));\n layout->AddView(label,\n 1,\n 1,\n views::GridLayout::LEADING,\n views::GridLayout::CENTER);\n \/\/ Create the permission menu button.\n menu_button_model_.reset(new internal::PermissionMenuModel(\n type, default_setting, current_setting, this));\n bool button_enabled = source == content_settings::SETTING_SOURCE_USER;\n menu_button_ = new internal::PermissionMenuButton(\n WebsiteSettingsUI::PermissionActionToUIString(current_setting,\n default_setting,\n source),\n menu_button_model_.get(),\n button_enabled);\n menu_button_->SetEnabled(button_enabled);\n menu_button_->set_focusable(button_enabled);\n menu_button_->SetAccessibleName(\n WebsiteSettingsUI::PermissionTypeToUIString(type));\n layout->AddView(menu_button_);\n}\n\nvoid PermissionSelectorView::AddObserver(\n PermissionSelectorViewObserver* observer) {\n observer_list_.AddObserver(observer);\n}\n\nvoid PermissionSelectorView::SelectionChanged() {\n \/\/ Update the icon to reflect the new setting.\n ContentSetting effective_setting = menu_button_model_->current_setting();\n if (effective_setting == CONTENT_SETTING_DEFAULT)\n effective_setting = menu_button_model_->default_setting();\n const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(\n menu_button_model_->site_permission(), effective_setting);\n icon_->SetImage(image.ToImageSkia());\n\n \/\/ Update the menu button text to reflect the new setting.\n menu_button_->SetText(WebsiteSettingsUI::PermissionActionToUIString(\n menu_button_model_->current_setting(),\n menu_button_model_->default_setting(),\n content_settings::SETTING_SOURCE_USER));\n\n FOR_EACH_OBSERVER(PermissionSelectorViewObserver,\n observer_list_,\n OnPermissionChanged(this));\n}\n\nContentSetting PermissionSelectorView::GetSelectedSetting() const {\n return menu_button_model_->current_setting();\n}\n\nContentSettingsType PermissionSelectorView::GetPermissionType() const {\n return menu_button_model_->site_permission();\n}\n\nvoid PermissionSelectorView::ChildPreferredSizeChanged(View* child) {\n SizeToPreferredSize();\n \/\/ FIXME: The parent is only a plain |View| that is used as a\n \/\/ container\/box\/panel. The SizeToPreferredSize method of the parent is\n \/\/ called here directly in order not to implement a custom |View| class with\n \/\/ its own implementation of the ChildPreferredSizeChanged method.\n parent()->SizeToPreferredSize();\n}\n\nPermissionSelectorView::~PermissionSelectorView() {\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2016 Michal Kosciesza <michal@mkiol.net>\n\n This file is part of Zimpedia application.\n\n This Source Code Form is subject to the terms of\n the Mozilla Public License, v.2.0. If a copy of\n the MPL was not distributed with this file, You can\n obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\n#include <QDir>\n#include <QFileInfoList>\n#include <QFile>\n#include <QStandardPaths>\n\n#include \"filemodel.h\"\n\nFileFinder::FileFinder(QObject *parent) : QThread(parent)\n{\n}\n\nvoid FileFinder::run()\n{\n \/\/ Start search for ZIM files\n const QStringList homeLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);\n QString homePath = homeLocation.isEmpty() ? \"\/home\/nemo\" : homeLocation.first();\n findFiles(homePath);\n}\n\nvoid FileFinder::findFiles(const QString &dirName)\n{\n QDir dir(dirName);\n\n \/\/qDebug() << \"dirName\" << dirName;\n\n if (dir.exists(dirName)) {\n QFileInfoList infoList = dir.entryInfoList(QStringList(\"*.zim\"),QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst);\n\n Q_FOREACH(QFileInfo info, infoList) {\n if (info.isDir())\n findFiles(info.absoluteFilePath());\n else\n emit fileFound(info);\n }\n }\n}\n\nFileModel::FileModel(QObject *parent) :\n ListModel(new FileItem, parent), finder(parent)\n{\n connect(&finder, SIGNAL(fileFound(QFileInfo)), this, SLOT(fileFoundHandler(QFileInfo)));\n connect(&finder, SIGNAL(finished()), this, SLOT(finderStatusHandler()));\n connect(&finder, SIGNAL(started()), this, SLOT(finderStatusHandler()));\n finder.start(QThread::IdlePriority);\n}\n\nbool FileModel::getSearching()\n{\n return finder.isRunning();\n}\n\nvoid FileModel::fileFoundHandler(const QFileInfo &fileInfo)\n{\n appendRow(new FileItem(fileInfo.absoluteFilePath(), fileInfo.fileName(), fileInfo.filePath()));\n}\n\nvoid FileModel::finderStatusHandler()\n{\n emit searchingChanged();\n}\n\nvoid FileModel::clear()\n{\n if(rowCount()>0) removeRows(0,rowCount());\n}\n\nFileItem::FileItem(const QString &id,\n const QString &name,\n const QString &dir,\n QObject *parent) :\n ListItem(parent),\n m_id(id),\n m_name(name),\n m_dir(dir)\n{}\n\nQHash<int, QByteArray> FileItem::roleNames() const\n{\n QHash<int, QByteArray> names;\n names[IdRole] = \"id\";\n names[NameRole] = \"name\";\n names[DirRole] = \"dir\";\n return names;\n}\n\nQVariant FileItem::data(int role) const\n{\n switch(role) {\n case IdRole:\n return id();\n case NameRole:\n return name();\n case DirRole:\n return dir();\n default:\n return QVariant();\n }\n}\n\n<commit_msg>SD card dir as possible ZIM files location<commit_after>\/*\n Copyright (C) 2016 Michal Kosciesza <michal@mkiol.net>\n\n This file is part of Zimpedia application.\n\n This Source Code Form is subject to the terms of\n the Mozilla Public License, v.2.0. If a copy of\n the MPL was not distributed with this file, You can\n obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\n#include <QDir>\n#include <QFileInfoList>\n#include <QFile>\n#include <QStandardPaths>\n\n#include \"filemodel.h\"\n\nFileFinder::FileFinder(QObject *parent) : QThread(parent)\n{\n}\n\nvoid FileFinder::run()\n{\n \/\/ Start search for ZIM files\n\n \/\/ All dirs under home directory\n const QStringList homeLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);\n findFiles(homeLocation.isEmpty() ? \"\/home\/nemo\" : homeLocation.first());\n\n \/\/ All dirs on SD card\n findFiles(\"\/media\/sdcard\");\n}\n\nvoid FileFinder::findFiles(const QString &dirName)\n{\n QDir dir(dirName);\n\n \/\/qDebug() << \"dirName\" << dirName;\n\n if (dir.exists(dirName)) {\n QFileInfoList infoList = dir.entryInfoList(QStringList(\"*.zim\"),QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst);\n\n Q_FOREACH(QFileInfo info, infoList) {\n if (info.isDir())\n findFiles(info.absoluteFilePath());\n else\n emit fileFound(info);\n }\n }\n}\n\nFileModel::FileModel(QObject *parent) :\n ListModel(new FileItem, parent), finder(parent)\n{\n connect(&finder, SIGNAL(fileFound(QFileInfo)), this, SLOT(fileFoundHandler(QFileInfo)));\n connect(&finder, SIGNAL(finished()), this, SLOT(finderStatusHandler()));\n connect(&finder, SIGNAL(started()), this, SLOT(finderStatusHandler()));\n finder.start(QThread::IdlePriority);\n}\n\nbool FileModel::getSearching()\n{\n return finder.isRunning();\n}\n\nvoid FileModel::fileFoundHandler(const QFileInfo &fileInfo)\n{\n appendRow(new FileItem(fileInfo.absoluteFilePath(), fileInfo.fileName(), fileInfo.filePath()));\n}\n\nvoid FileModel::finderStatusHandler()\n{\n emit searchingChanged();\n}\n\nvoid FileModel::clear()\n{\n if(rowCount()>0) removeRows(0,rowCount());\n}\n\nFileItem::FileItem(const QString &id,\n const QString &name,\n const QString &dir,\n QObject *parent) :\n ListItem(parent),\n m_id(id),\n m_name(name),\n m_dir(dir)\n{}\n\nQHash<int, QByteArray> FileItem::roleNames() const\n{\n QHash<int, QByteArray> names;\n names[IdRole] = \"id\";\n names[NameRole] = \"name\";\n names[DirRole] = \"dir\";\n return names;\n}\n\nQVariant FileItem::data(int role) const\n{\n switch(role) {\n case IdRole:\n return id();\n case NameRole:\n return name();\n case DirRole:\n return dir();\n default:\n return QVariant();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n\n#include <rtl\/process.h>\n#include <rtl\/bootstrap.hxx>\n#include <rtl\/string.hxx>\n#include <rtl\/byteseq.hxx>\n\n#include <osl\/process.h>\n\nusing namespace ::rtl;\n\n\nint main( int argc, char *argv[] )\n{\n sal_Int32 nCount = rtl_getAppCommandArgCount();\n\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stdout, \"rtl-commandargs (%d) real args:%i \", nCount, argc);\n for( sal_Int32 i = 0 ; i < nCount ; i ++ )\n {\n OUString data;\n rtl_getAppCommandArg( i , &(data.pData) );\n OString o = OUStringToOString( data, RTL_TEXTENCODING_ASCII_US );\n fprintf( stdout, \" %s\", o.getStr() );\n }\n fprintf( stdout, \"\\n\" );\n#endif\n\n if( nCount == 0 )\n {\n printf( \"usage : testbootstrap <checkedValueOfMyBootstrapValue>\\n\" );\n exit( 1 );\n }\n\n\n OUString iniName;\n Bootstrap::get(OUString(RTL_CONSTASCII_USTRINGPARAM(\"iniName\")), iniName, OUString());\n\n#if OSL_DEBUG_LEVEL > 1\n if(iniName.getLength())\n {\n OString tmp_iniName = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"using ini: %s\\n\", tmp_iniName.getStr());\n }\n#endif\n\n Bootstrap bootstrap(iniName);\n\n\n OUString name( RTL_CONSTASCII_USTRINGPARAM( \"MYBOOTSTRAPTESTVALUE\" ));\n OUString myDefault( RTL_CONSTASCII_USTRINGPARAM(\"$Default\"));\n\n OUString value;\n sal_Bool useDefault;\n\n OUString aDummy;\n useDefault = bootstrap.getFrom(OUString(RTL_CONSTASCII_USTRINGPARAM(\"USEDEFAULT\")), aDummy);\n\n sal_Bool result = sal_False;\n sal_Bool found = sal_True;\n\n if(useDefault)\n bootstrap.getFrom(name, value, myDefault);\n\n else\n found = bootstrap.getFrom(name, value);\n\n if(found)\n {\n OUString para(OUString::createFromAscii( argv[1] ));\n\n result = para == value;\n\n if(!result)\n {\n OString para_tmp = OUStringToOString(para, RTL_TEXTENCODING_ASCII_US);\n OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);\n\n fprintf(stderr, \"para(%s) != value(%s)\\n\", para_tmp.getStr(), value_tmp.getStr());\n }\n }\n else\n fprintf(stderr, \"bootstrap parameter couldn't be found\\n\");\n\n \/\/ test the default case\n name = OUString( RTL_CONSTASCII_USTRINGPARAM( \"no_one_has_set_this_name\" ) );\n OSL_ASSERT( ! bootstrap.getFrom( name, value ) );\n result = result && !bootstrap.getFrom( name, value );\n\n myDefault = OUString( RTL_CONSTASCII_USTRINGPARAM( \"1\" ) );\n OUString myDefault2 = OUString( RTL_CONSTASCII_USTRINGPARAM( \"2\" ) );\n\n bootstrap.getFrom( name, value, myDefault );\n OSL_ASSERT( value == myDefault );\n result = result && (value == myDefault);\n\n bootstrap.getFrom( name, value, myDefault2 );\n OSL_ASSERT( value == myDefault2 );\n result = result && (value == myDefault2);\n\n return result;\n}\n<commit_msg>INTEGRATION: CWS valgrind02 (1.8.234); FILE MERGED 2004\/10\/18 17:30:52 mhu 1.8.234.1: #i35209# Added call to 'osl_setCommandArgs()'.<commit_after>#include <stdio.h>\n\n#include <rtl\/process.h>\n#include <rtl\/bootstrap.hxx>\n#include <rtl\/string.hxx>\n#include <rtl\/byteseq.hxx>\n\n#include <osl\/process.h>\n\nusing namespace ::rtl;\n\n\nint main( int argc, char *argv[] )\n{\n osl_setCommandArgs (argc, argv);\n\n sal_Int32 nCount = rtl_getAppCommandArgCount();\n\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stdout, \"rtl-commandargs (%d) real args:%i \", nCount, argc);\n for( sal_Int32 i = 0 ; i < nCount ; i ++ )\n {\n OUString data;\n rtl_getAppCommandArg( i , &(data.pData) );\n OString o = OUStringToOString( data, RTL_TEXTENCODING_ASCII_US );\n fprintf( stdout, \" %s\", o.getStr() );\n }\n fprintf( stdout, \"\\n\" );\n#endif\n\n if( nCount == 0 )\n {\n printf( \"usage : testbootstrap <checkedValueOfMyBootstrapValue>\\n\" );\n exit( 1 );\n }\n\n\n OUString iniName;\n Bootstrap::get(OUString(RTL_CONSTASCII_USTRINGPARAM(\"iniName\")), iniName, OUString());\n\n#if OSL_DEBUG_LEVEL > 1\n if(iniName.getLength())\n {\n OString tmp_iniName = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"using ini: %s\\n\", tmp_iniName.getStr());\n }\n#endif\n\n Bootstrap bootstrap(iniName);\n\n\n OUString name( RTL_CONSTASCII_USTRINGPARAM( \"MYBOOTSTRAPTESTVALUE\" ));\n OUString myDefault( RTL_CONSTASCII_USTRINGPARAM(\"$Default\"));\n\n OUString value;\n sal_Bool useDefault;\n\n OUString aDummy;\n useDefault = bootstrap.getFrom(OUString(RTL_CONSTASCII_USTRINGPARAM(\"USEDEFAULT\")), aDummy);\n\n sal_Bool result = sal_False;\n sal_Bool found = sal_True;\n\n if(useDefault)\n bootstrap.getFrom(name, value, myDefault);\n\n else\n found = bootstrap.getFrom(name, value);\n\n if(found)\n {\n OUString para(OUString::createFromAscii( argv[1] ));\n\n result = para == value;\n\n if(!result)\n {\n OString para_tmp = OUStringToOString(para, RTL_TEXTENCODING_ASCII_US);\n OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);\n\n fprintf(stderr, \"para(%s) != value(%s)\\n\", para_tmp.getStr(), value_tmp.getStr());\n }\n }\n else\n fprintf(stderr, \"bootstrap parameter couldn't be found\\n\");\n\n \/\/ test the default case\n name = OUString( RTL_CONSTASCII_USTRINGPARAM( \"no_one_has_set_this_name\" ) );\n OSL_ASSERT( ! bootstrap.getFrom( name, value ) );\n result = result && !bootstrap.getFrom( name, value );\n\n myDefault = OUString( RTL_CONSTASCII_USTRINGPARAM( \"1\" ) );\n OUString myDefault2 = OUString( RTL_CONSTASCII_USTRINGPARAM( \"2\" ) );\n\n bootstrap.getFrom( name, value, myDefault );\n OSL_ASSERT( value == myDefault );\n result = result && (value == myDefault);\n\n bootstrap.getFrom( name, value, myDefault2 );\n OSL_ASSERT( value == myDefault2 );\n result = result && (value == myDefault2);\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Includes the Model and IModelObserver class declarations.\n\n The Model has the items necessary to construct a modified OptiX image.\n\n In normal use, one or more IModelObserver objects are registered\n to the model. Specific observers or viewers may inherit from \n IModelObservers.\n\n A controller updates the model and calls the model notifyObservers\n function which calls the modelUpdated function of each of the\n observers registered to the model.\n\n*\/\n\n#pragma once\n\n#include <set>\n#include <vector>\n#include <ostream>\n\nnamespace grt {\n\n\tclass Position\n\t{\n\t\tpublic:\n\t\t\tfloat x;\n\t\t\tfloat y;\n\t\t\tfloat z;\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Position & pos)\n\t\t\t{\n\t\t\t\t_out << \"position: x= \" << pos.x << \", y= \" << pos.y << \", z= \" << pos.z;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Color\n\t{\n\t\tpublic:\n\t\t\tfloat r;\n\t\t\tfloat g;\n\t\t\tfloat b;\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Color & c)\n\t\t\t{\n\t\t\t\t_out << \"color: r=\" << c.r << \", g=\" << c.g << \", b= \" << c.b;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Light\n\t{\n\t\tpublic:\n\t\t\tPosition position; \/\/ x, y, z position\n\t\t\tColor color; \/\/ R G B color\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Light & light)\n\t\t\t{\n\t\t\t\t_out << \"Light: \" << light.position << \" \" << light.color;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Camera\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat fieldOfView;\n\t};\n\n\t\/\/ May become a shape\n\tclass Box\n\t{\n\t\tpublic:\n\t\t\tPosition minPosition;\n\t\t\tPosition maxPosition;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Box & box)\n\t\t\t{\n\t\t\t\t_out << \"minPosition= \" << box.minPosition << \", maxPosition= \"<<box.maxPosition << \", material= \" << box.material;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Sphere\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat radius;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Sphere & sphere)\n\t\t\t{\n\t\t\t\t_out << \"position= \" << sphere.position << \", radius= \" << sphere.radius << \", material= \" << sphere.material << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Chull\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat radius;\n\t\t\tfloat min;\n\t\t\tfloat max;\n\t\t\tint nsides;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Chull & chull)\n\t\t\t{\n\t\t\t\t_out << \"position= \" << chull.position << \", radius= \" << chull.radius << \", material= \" << chull.material << \", min = \" << chull.min << \",max = \" << chull.max << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Parallelogram\n\t{\n\t\tpublic:\n\t\t\t\/\/ how specify? vec1, vec2, anchor, Material?\n\t};\n\n\tclass Model;\n\n\tclass IModelObserver {\n\t\tpublic:\n\t\t\tvirtual void modelUpdated(const Model &) = 0;\n\t};\n\n\tclass Model {\n\t\tstd::set<IModelObserver*> observers;\n\n\t\tpublic:\n\t\t\tstd::string imageTitle;\n\n\t\t\tfloat totalBrightness;\n\n\t\t\t\/\/ Lights\n\t\t\tstd::vector< Light > lights;\n\n\t\t\t\/\/ Boxes\n\t\t\tstd::vector< Box > boxes;\n\n\t\t\t\/\/ Spheres\n\t\t\tstd::vector< Sphere > spheres;\n\n\t\t\t\/\/ Chulls\n\t\t\tstd::vector< Chull > chulls;\n\n\t\t\t\/* Rest is not yet ready\n\t\t\t\/\/ Camera information\n\t\t\tCamera camera;\n\n\t\t\t\/\/ Parallelogram shapes (includes floor)\n\t\t\tstd::vector< Parallelogram > parallelogram;\n\t\t\t*\/\n\n\t\t\t\/\/ Constructor\n\t\t\tModel()\n\t\t\t\t: imageTitle(\"GPURayTracer\")\n\t\t\t{ }\n\n\t\t\tvoid registerObserver(IModelObserver * _obs) {\n\t\t\t\tobservers.insert(_obs);\n\t\t\t}\n\n\t\t\tvoid unregisterObserver(IModelObserver * _obs) {\n\t\t\t\tobservers.erase(_obs);\n\t\t\t}\n\n\t\t\tvoid notifyObservers() {\n\t\t\t\tfor (std::set<IModelObserver*>::iterator ob_it = observers.begin(); ob_it != observers.end(); ++ob_it) {\n\t\t\t\t\t(*ob_it)->modelUpdated(*this);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Model & model)\n\t\t\t{\n\t\t\t\t_out << \"imageTitle = \" << model.imageTitle << std::endl;\n\t\t\t\t_out << \"totalBrightness = \" << model.totalBrightness << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.lights.size(); ++i)\n\t\t\t\t\t_out << \"Light: \" << (i+1) << \" - \" << model.lights[i] << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.boxes.size(); ++i)\n\t\t\t\t\t_out << \"Box: \" << (i+1) << \" - \" << model.boxes[i] << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.spheres.size(); ++i)\n\t\t\t\t\t_out << \"Sphere:\" << (i+1) << \" - \" << model.spheres[i] << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n}; \/\/ grt\n\n<commit_msg>Added missing chull print<commit_after>\/*\n Includes the Model and IModelObserver class declarations.\n\n The Model has the items necessary to construct a modified OptiX image.\n\n In normal use, one or more IModelObserver objects are registered\n to the model. Specific observers or viewers may inherit from \n IModelObservers.\n\n A controller updates the model and calls the model notifyObservers\n function which calls the modelUpdated function of each of the\n observers registered to the model.\n\n*\/\n\n#pragma once\n\n#include <set>\n#include <vector>\n#include <ostream>\n\nnamespace grt {\n\n\tclass Position\n\t{\n\t\tpublic:\n\t\t\tfloat x;\n\t\t\tfloat y;\n\t\t\tfloat z;\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Position & pos)\n\t\t\t{\n\t\t\t\t_out << \"position: x= \" << pos.x << \", y= \" << pos.y << \", z= \" << pos.z;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Color\n\t{\n\t\tpublic:\n\t\t\tfloat r;\n\t\t\tfloat g;\n\t\t\tfloat b;\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Color & c)\n\t\t\t{\n\t\t\t\t_out << \"color: r=\" << c.r << \", g=\" << c.g << \", b= \" << c.b;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Light\n\t{\n\t\tpublic:\n\t\t\tPosition position; \/\/ x, y, z position\n\t\t\tColor color; \/\/ R G B color\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Light & light)\n\t\t\t{\n\t\t\t\t_out << \"Light: \" << light.position << \" \" << light.color;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\tclass Camera\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat fieldOfView;\n\t};\n\n\t\/\/ May become a shape\n\tclass Box\n\t{\n\t\tpublic:\n\t\t\tPosition minPosition;\n\t\t\tPosition maxPosition;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Box & box)\n\t\t\t{\n\t\t\t\t_out << \"minPosition= \" << box.minPosition << \", maxPosition= \"<<box.maxPosition << \", material= \" << box.material;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Sphere\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat radius;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Sphere & sphere)\n\t\t\t{\n\t\t\t\t_out << \"position= \" << sphere.position << \", radius= \" << sphere.radius << \", material= \" << sphere.material << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Chull\n\t{\n\t\tpublic:\n\t\t\tPosition position;\n\t\t\tfloat radius;\n\t\t\tfloat min;\n\t\t\tfloat max;\n\t\t\tint nsides;\n\t\t\tstd::string material;\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Chull & chull)\n\t\t\t{\n\t\t\t\t_out << \"position= \" << chull.position << \", radius= \" << chull.radius << \", material= \" << chull.material << \", min = \" << chull.min << \",max = \" << chull.max << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n\t\/\/ May become a shape\n\tclass Parallelogram\n\t{\n\t\tpublic:\n\t\t\t\/\/ how specify? vec1, vec2, anchor, Material?\n\t};\n\n\tclass Model;\n\n\tclass IModelObserver {\n\t\tpublic:\n\t\t\tvirtual void modelUpdated(const Model &) = 0;\n\t};\n\n\tclass Model {\n\t\tstd::set<IModelObserver*> observers;\n\n\t\tpublic:\n\t\t\tstd::string imageTitle;\n\n\t\t\tfloat totalBrightness;\n\n\t\t\t\/\/ Lights\n\t\t\tstd::vector< Light > lights;\n\n\t\t\t\/\/ Boxes\n\t\t\tstd::vector< Box > boxes;\n\n\t\t\t\/\/ Spheres\n\t\t\tstd::vector< Sphere > spheres;\n\n\t\t\t\/\/ Chulls\n\t\t\tstd::vector< Chull > chulls;\n\n\t\t\t\/* Rest is not yet ready\n\t\t\t\/\/ Camera information\n\t\t\tCamera camera;\n\n\t\t\t\/\/ Parallelogram shapes (includes floor)\n\t\t\tstd::vector< Parallelogram > parallelogram;\n\t\t\t*\/\n\n\t\t\t\/\/ Constructor\n\t\t\tModel()\n\t\t\t\t: imageTitle(\"GPURayTracer\")\n\t\t\t{ }\n\n\t\t\tvoid registerObserver(IModelObserver * _obs) {\n\t\t\t\tobservers.insert(_obs);\n\t\t\t}\n\n\t\t\tvoid unregisterObserver(IModelObserver * _obs) {\n\t\t\t\tobservers.erase(_obs);\n\t\t\t}\n\n\t\t\tvoid notifyObservers() {\n\t\t\t\tfor (std::set<IModelObserver*>::iterator ob_it = observers.begin(); ob_it != observers.end(); ++ob_it) {\n\t\t\t\t\t(*ob_it)->modelUpdated(*this);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfriend std::ostream & operator<<(std::ostream & _out, const Model & model)\n\t\t\t{\n\t\t\t\t_out << \"imageTitle = \" << model.imageTitle << std::endl;\n\t\t\t\t_out << \"totalBrightness = \" << model.totalBrightness << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.lights.size(); ++i)\n\t\t\t\t\t_out << \"Light: \" << (i+1) << \" - \" << model.lights[i] << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.boxes.size(); ++i)\n\t\t\t\t\t_out << \"Box: \" << (i+1) << \" - \" << model.boxes[i] << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.spheres.size(); ++i)\n\t\t\t\t\t_out << \"Sphere:\" << (i+1) << \" - \" << model.spheres[i] << std::endl;\n\t\t\t\tfor (int i=0; i<(int)model.chulls.size(); ++i)\n\t\t\t\t\t_out << \"Chull:\" << (i+1) << \" - \" << model.chulls[i] << std::endl;\n\t\t\t\treturn _out;\n\t\t\t}\n\t};\n\n}; \/\/ grt\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/raster_cache.h\"\n\n#include <vector>\n\n#include \"flutter\/common\/threads.h\"\n#include \"flutter\/flow\/paint_utils.h\"\n#include \"flutter\/glue\/trace_event.h\"\n#include \"lib\/ftl\/logging.h\"\n#include \"third_party\/skia\/include\/core\/SkCanvas.h\"\n#include \"third_party\/skia\/include\/core\/SkImage.h\"\n#include \"third_party\/skia\/include\/core\/SkPicture.h\"\n#include \"third_party\/skia\/include\/core\/SkSurface.h\"\n\nnamespace flow {\n\nRasterCache::RasterCache(size_t threshold)\n : threshold_(threshold), checkerboard_images_(false), weak_factory_(this) {}\n\nRasterCache::~RasterCache() = default;\n\nstatic bool CanRasterizePicture(SkPicture* picture) {\n if (picture == nullptr) {\n return false;\n }\n\n const SkRect cull_rect = picture->cullRect();\n\n if (cull_rect.isEmpty()) {\n \/\/ No point in ever rasterizing an empty picture.\n return false;\n }\n\n if (!cull_rect.isFinite()) {\n \/\/ Cannot attempt to rasterize into an infinitely large surface.\n return false;\n }\n\n return true;\n}\n\nstatic bool IsPictureWorthRasterizing(SkPicture* picture,\n bool will_change,\n bool is_complex) {\n if (will_change) {\n \/\/ If the picture is going to change in the future, there is no point in\n \/\/ doing to extra work to rasterize.\n return false;\n }\n\n if (!CanRasterizePicture(picture)) {\n \/\/ No point in deciding whether the picture is worth rasterizing if it\n \/\/ cannot be rasterized at all.\n return false;\n }\n\n if (is_complex) {\n \/\/ The caller seems to have extra information about the picture and thinks\n \/\/ the picture is always worth rasterizing.\n return true;\n }\n\n \/\/ TODO(abarth): We should find a better heuristic here that lets us avoid\n \/\/ wasting memory on trivial layers that are easy to re-rasterize every frame.\n return picture->approximateOpCount() > 10;\n}\n\nRasterCacheResult RasterizePicture(SkPicture* picture,\n GrContext* context,\n const MatrixDecomposition& matrix,\n bool checkerboard) {\n TRACE_EVENT0(\"flutter\", \"RasterCachePopulate\");\n\n const SkVector3& scale = matrix.scale();\n\n const SkRect logical_rect = picture->cullRect();\n const SkRect physical_rect =\n SkRect::MakeWH(std::ceil(std::labs(logical_rect.width() * scale.x())),\n std::ceil(std::labs(logical_rect.height() * scale.y())));\n\n const SkImageInfo image_info =\n SkImageInfo::MakeN32Premul(physical_rect.width(), \/\/ physical width\n physical_rect.height(), \/\/ physical height\n nullptr \/\/ colorspace\n );\n\n sk_sp<SkSurface> surface =\n context\n ? SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, image_info)\n : SkSurface::MakeRaster(image_info);\n\n if (!surface) {\n FTL_DCHECK(false);\n return {};\n }\n\n SkCanvas* canvas = surface->getCanvas();\n\n canvas->clear(SK_ColorTRANSPARENT);\n canvas->scale(std::abs(scale.x()), std::abs(scale.y()));\n canvas->translate(-logical_rect.left(), -logical_rect.top());\n canvas->drawPicture(picture);\n\n if (checkerboard) {\n DrawCheckerboard(canvas, logical_rect);\n }\n\n return {\n surface->makeImageSnapshot(), \/\/ image\n physical_rect, \/\/ source rect\n logical_rect \/\/ destination rect\n };\n}\n\nstatic inline size_t ClampSize(size_t value, size_t min, size_t max) {\n if (value > max) {\n return max;\n }\n\n if (value < min) {\n return min;\n }\n\n return value;\n}\n\nRasterCacheResult RasterCache::GetPrerolledImage(\n GrContext* context,\n SkPicture* picture,\n const SkMatrix& transformation_matrix,\n bool is_complex,\n bool will_change) {\n if (!IsPictureWorthRasterizing(picture, will_change, is_complex)) {\n \/\/ We only deal with pictures that are worthy of rasterization.\n return {};\n }\n\n \/\/ Decompose the matrix (once) for all subsequent operations. We want to make\n \/\/ sure to avoid volumetric distortions while accounting for scaling.\n const MatrixDecomposition matrix(transformation_matrix);\n\n if (!matrix.IsValid()) {\n \/\/ The matrix was singular. No point in going further.\n return {};\n }\n\n RasterCacheKey cache_key(*picture, matrix);\n\n Entry& entry = cache_[cache_key];\n entry.access_count = ClampSize(entry.access_count + 1, 0, threshold_);\n entry.used_this_frame = true;\n\n if (entry.access_count < threshold_ || threshold_ == 0) {\n \/\/ Frame threshold has not yet been reached.\n return {};\n }\n\n if (!entry.image.is_valid()) {\n entry.image =\n RasterizePicture(picture, context, matrix, checkerboard_images_);\n }\n\n \/\/ We are not considering unrasterizable images. So if we don't have an image\n \/\/ by now, we know that rasterization itself failed.\n FTL_DCHECK(entry.image.is_valid());\n\n return entry.image;\n}\n\nvoid RasterCache::SweepAfterFrame() {\n std::vector<RasterCacheKey::Map<Entry>::iterator> dead;\n\n for (auto it = cache_.begin(); it != cache_.end(); ++it) {\n Entry& entry = it->second;\n if (!entry.used_this_frame) {\n dead.push_back(it);\n }\n entry.used_this_frame = false;\n }\n\n for (auto it : dead) {\n cache_.erase(it);\n }\n}\n\nvoid RasterCache::Clear() {\n cache_.clear();\n}\n\nvoid RasterCache::SetCheckboardCacheImages(bool checkerboard) {\n if (checkerboard_images_ == checkerboard) {\n return;\n }\n\n checkerboard_images_ = checkerboard;\n\n \/\/ Clear all existing entries so previously rasterized items (with or without\n \/\/ a checkerboard) will be refreshed in subsequent passes.\n Clear();\n}\n\n} \/\/ namespace flow\n<commit_msg>Fix usage of std::labs (#3891)<commit_after>\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/raster_cache.h\"\n\n#include <vector>\n\n#include \"flutter\/common\/threads.h\"\n#include \"flutter\/flow\/paint_utils.h\"\n#include \"flutter\/glue\/trace_event.h\"\n#include \"lib\/ftl\/logging.h\"\n#include \"third_party\/skia\/include\/core\/SkCanvas.h\"\n#include \"third_party\/skia\/include\/core\/SkImage.h\"\n#include \"third_party\/skia\/include\/core\/SkPicture.h\"\n#include \"third_party\/skia\/include\/core\/SkSurface.h\"\n\nnamespace flow {\n\nRasterCache::RasterCache(size_t threshold)\n : threshold_(threshold), checkerboard_images_(false), weak_factory_(this) {}\n\nRasterCache::~RasterCache() = default;\n\nstatic bool CanRasterizePicture(SkPicture* picture) {\n if (picture == nullptr) {\n return false;\n }\n\n const SkRect cull_rect = picture->cullRect();\n\n if (cull_rect.isEmpty()) {\n \/\/ No point in ever rasterizing an empty picture.\n return false;\n }\n\n if (!cull_rect.isFinite()) {\n \/\/ Cannot attempt to rasterize into an infinitely large surface.\n return false;\n }\n\n return true;\n}\n\nstatic bool IsPictureWorthRasterizing(SkPicture* picture,\n bool will_change,\n bool is_complex) {\n if (will_change) {\n \/\/ If the picture is going to change in the future, there is no point in\n \/\/ doing to extra work to rasterize.\n return false;\n }\n\n if (!CanRasterizePicture(picture)) {\n \/\/ No point in deciding whether the picture is worth rasterizing if it\n \/\/ cannot be rasterized at all.\n return false;\n }\n\n if (is_complex) {\n \/\/ The caller seems to have extra information about the picture and thinks\n \/\/ the picture is always worth rasterizing.\n return true;\n }\n\n \/\/ TODO(abarth): We should find a better heuristic here that lets us avoid\n \/\/ wasting memory on trivial layers that are easy to re-rasterize every frame.\n return picture->approximateOpCount() > 10;\n}\n\nRasterCacheResult RasterizePicture(SkPicture* picture,\n GrContext* context,\n const MatrixDecomposition& matrix,\n bool checkerboard) {\n TRACE_EVENT0(\"flutter\", \"RasterCachePopulate\");\n\n const SkVector3& scale = matrix.scale();\n\n const SkRect logical_rect = picture->cullRect();\n const SkRect physical_rect =\n SkRect::MakeWH(std::ceil(std::fabs(logical_rect.width() * scale.x())),\n std::ceil(std::fabs(logical_rect.height() * scale.y())));\n\n const SkImageInfo image_info =\n SkImageInfo::MakeN32Premul(physical_rect.width(), \/\/ physical width\n physical_rect.height(), \/\/ physical height\n nullptr \/\/ colorspace\n );\n\n sk_sp<SkSurface> surface =\n context\n ? SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, image_info)\n : SkSurface::MakeRaster(image_info);\n\n if (!surface) {\n FTL_DCHECK(false);\n return {};\n }\n\n SkCanvas* canvas = surface->getCanvas();\n\n canvas->clear(SK_ColorTRANSPARENT);\n canvas->scale(std::abs(scale.x()), std::abs(scale.y()));\n canvas->translate(-logical_rect.left(), -logical_rect.top());\n canvas->drawPicture(picture);\n\n if (checkerboard) {\n DrawCheckerboard(canvas, logical_rect);\n }\n\n return {\n surface->makeImageSnapshot(), \/\/ image\n physical_rect, \/\/ source rect\n logical_rect \/\/ destination rect\n };\n}\n\nstatic inline size_t ClampSize(size_t value, size_t min, size_t max) {\n if (value > max) {\n return max;\n }\n\n if (value < min) {\n return min;\n }\n\n return value;\n}\n\nRasterCacheResult RasterCache::GetPrerolledImage(\n GrContext* context,\n SkPicture* picture,\n const SkMatrix& transformation_matrix,\n bool is_complex,\n bool will_change) {\n if (!IsPictureWorthRasterizing(picture, will_change, is_complex)) {\n \/\/ We only deal with pictures that are worthy of rasterization.\n return {};\n }\n\n \/\/ Decompose the matrix (once) for all subsequent operations. We want to make\n \/\/ sure to avoid volumetric distortions while accounting for scaling.\n const MatrixDecomposition matrix(transformation_matrix);\n\n if (!matrix.IsValid()) {\n \/\/ The matrix was singular. No point in going further.\n return {};\n }\n\n RasterCacheKey cache_key(*picture, matrix);\n\n Entry& entry = cache_[cache_key];\n entry.access_count = ClampSize(entry.access_count + 1, 0, threshold_);\n entry.used_this_frame = true;\n\n if (entry.access_count < threshold_ || threshold_ == 0) {\n \/\/ Frame threshold has not yet been reached.\n return {};\n }\n\n if (!entry.image.is_valid()) {\n entry.image =\n RasterizePicture(picture, context, matrix, checkerboard_images_);\n }\n\n \/\/ We are not considering unrasterizable images. So if we don't have an image\n \/\/ by now, we know that rasterization itself failed.\n FTL_DCHECK(entry.image.is_valid());\n\n return entry.image;\n}\n\nvoid RasterCache::SweepAfterFrame() {\n std::vector<RasterCacheKey::Map<Entry>::iterator> dead;\n\n for (auto it = cache_.begin(); it != cache_.end(); ++it) {\n Entry& entry = it->second;\n if (!entry.used_this_frame) {\n dead.push_back(it);\n }\n entry.used_this_frame = false;\n }\n\n for (auto it : dead) {\n cache_.erase(it);\n }\n}\n\nvoid RasterCache::Clear() {\n cache_.clear();\n}\n\nvoid RasterCache::SetCheckboardCacheImages(bool checkerboard) {\n if (checkerboard_images_ == checkerboard) {\n return;\n }\n\n checkerboard_images_ = checkerboard;\n\n \/\/ Clear all existing entries so previously rasterized items (with or without\n \/\/ a checkerboard) will be refreshed in subsequent passes.\n Clear();\n}\n\n} \/\/ namespace flow\n<|endoftext|>"} {"text":"<commit_before><commit_msg>sd\/source\/ui\/dlg\/dlgolbul.cxx comment translation and cleanup<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"SDL2\/Sdl2Window.h\"\n\n#include <iostream>\n#include <string>\n\n#include <SDL2\/SDL.h>\n#include <GL\/glew.h>\n\n#include \"GUI\/AllWidgets.h\"\n#include \"SDL2\/SdlMouse.h\"\n\nusing namespace std;\n\nnamespace Core\n{\n\nbool Sdl2Window::mGlewInit = false;\n\nSdl2Window::Sdl2Window(const string& title, uint width, uint height)\n : mTitle(title),\n mVisible(false),\n mWindow(nullptr)\n{\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n\n mWindow = SDL_CreateWindow\n (\n title.c_str(),\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n width, height,\n SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE\n );\n\n mContext = SDL_GL_CreateContext(mWindow);\n\n GUInterface::RootWidget* root = new GUInterface::RootWidget(0,0,0,0);\/\/GetWidth(),GetHeight());\n mEnv = new GUInterface::Environment(root);\n mMouse = new SdlMouse();\n\n const char* version = (const char*)glGetString(GL_VERSION);\n\/\/ std::cout << version << std::endl;\n delete[] version;\n\n version = (const char*)glGetString(GL_RENDERER);\n\/\/ std::cout << version << std::endl;\n delete[] version;\n}\n\nSdl2Window::~Sdl2Window()\n{\n SDL_GL_DeleteContext(mContext);\n SDL_DestroyWindow(mWindow);\n mWindow = NULL;\n}\n\nvoid Sdl2Window::SetTitle(const std::string& title)\n{\n \/\/ TODO\n}\n\nvoid Sdl2Window::SetSize(uint width, uint height)\n{\n \/\/ TODO\n}\n\nvoid Sdl2Window::PollEvents()\n{\n\tSDL_Event e;\n\n\tmMouse->SetClicks(0,0,0);\n\tmMouse->SetRelativePosition(0,0);\n\n while (SDL_PollEvent(&e))\n {\n if (e.type == SDL_QUIT)\n {\n SetVisible(false);\n }\n else if(e.type == SDL_MOUSEBUTTONUP)\n {\n \tstd::cout << \"\\n*********Click*********\\n\";\n \tint32 button = (int)e.button.button;\n \tint32 x = e.button.x;\n \tint32 y = GetHeight() - e.button.y - 1;\n \tint32 clicks = (int)e.button.clicks;\n\n \t\/\/std::cout << \"X: \" << x << \", Y: \" << y << std::endl;\n \tmMouse->SetPosition(x,y);\n\n \tif(button == 1) mMouse->SetLeftClicks(clicks);\n \telse if(button == 2) mMouse->SetMiddleClicks(clicks);\n \telse mMouse->SetRightClicks(clicks);\n\n \tmEnv->OnMouseButton(x,y,button,true);\n }\n else if(e.type == SDL_MOUSEMOTION)\n {\n \tint32 x = e.motion.x;\n \tint32 y = GetHeight() - e.motion.y - 1;\n \tint32 xRel = e.motion.xrel;\n \tint32 yRel = e.motion.yrel;\n\n \tmMouse->SetPosition(x,y);\n \tmMouse->SetRelativePosition(xRel,yRel);\n }\n }\n\n}\n\nvoid Sdl2Window::SwapBuffers()\n{\n SDL_GL_SwapWindow(mWindow);\n int width, height;\n SDL_GetWindowSize(mWindow, &width, &height);\n glViewport(0, 0, width, height);\n\n}\n\nvoid Sdl2Window::SetVisible(bool visible)\n{\n if (mVisible == visible) return;\n\n mVisible = visible;\n if (mVisible)\n {\n SDL_ShowWindow(mWindow);\n InitGlew();\n }\n else\n {\n SDL_HideWindow(mWindow);\n }\n}\n\nvoid Sdl2Window::InitGlew()\n{\n if (mGlewInit) return;\n\n mGlewInit = true;\n\n glewExperimental = GL_TRUE;\n glewInit();\n}\n\nSdlMouse* Sdl2Window::GetMouse()\n{\n\treturn mMouse;\n}\n\nGUInterface::Environment* Sdl2Window::GetEnvironment()\n{\n\treturn mEnv;\n}\n\n}\n<commit_msg>Remove invalid delete[]s<commit_after>#include \"SDL2\/Sdl2Window.h\"\n\n#include <iostream>\n#include <string>\n\n#include <SDL2\/SDL.h>\n#include <GL\/glew.h>\n\n#include \"GUI\/AllWidgets.h\"\n#include \"SDL2\/SdlMouse.h\"\n\nusing namespace std;\n\nnamespace Core\n{\n\nbool Sdl2Window::mGlewInit = false;\n\nSdl2Window::Sdl2Window(const string& title, uint width, uint height)\n : mTitle(title),\n mVisible(false),\n mWindow(nullptr)\n{\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n\n mWindow = SDL_CreateWindow\n (\n title.c_str(),\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n width, height,\n SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE\n );\n\n mContext = SDL_GL_CreateContext(mWindow);\n\n GUInterface::RootWidget* root = new GUInterface::RootWidget(0,0,0,0);\/\/GetWidth(),GetHeight());\n mEnv = new GUInterface::Environment(root);\n mMouse = new SdlMouse();\n\n const char* version = (const char*)glGetString(GL_VERSION);\n\/\/ std::cout << version << std::endl;\n\/\/ delete[] version;\n\n version = (const char*)glGetString(GL_RENDERER);\n\/\/ std::cout << version << std::endl;\n\/\/ delete[] version;\n}\n\nSdl2Window::~Sdl2Window()\n{\n SDL_GL_DeleteContext(mContext);\n SDL_DestroyWindow(mWindow);\n mWindow = NULL;\n}\n\nvoid Sdl2Window::SetTitle(const std::string& title)\n{\n \/\/ TODO\n}\n\nvoid Sdl2Window::SetSize(uint width, uint height)\n{\n \/\/ TODO\n}\n\nvoid Sdl2Window::PollEvents()\n{\n\tSDL_Event e;\n\n\tmMouse->SetClicks(0,0,0);\n\tmMouse->SetRelativePosition(0,0);\n\n while (SDL_PollEvent(&e))\n {\n if (e.type == SDL_QUIT)\n {\n SetVisible(false);\n }\n else if(e.type == SDL_MOUSEBUTTONUP)\n {\n \tstd::cout << \"\\n*********Click*********\\n\";\n \tint32 button = (int)e.button.button;\n \tint32 x = e.button.x;\n \tint32 y = GetHeight() - e.button.y - 1;\n \tint32 clicks = (int)e.button.clicks;\n\n \t\/\/std::cout << \"X: \" << x << \", Y: \" << y << std::endl;\n \tmMouse->SetPosition(x,y);\n\n \tif(button == 1) mMouse->SetLeftClicks(clicks);\n \telse if(button == 2) mMouse->SetMiddleClicks(clicks);\n \telse mMouse->SetRightClicks(clicks);\n\n \tmEnv->OnMouseButton(x,y,button,true);\n }\n else if(e.type == SDL_MOUSEMOTION)\n {\n \tint32 x = e.motion.x;\n \tint32 y = GetHeight() - e.motion.y - 1;\n \tint32 xRel = e.motion.xrel;\n \tint32 yRel = e.motion.yrel;\n\n \tmMouse->SetPosition(x,y);\n \tmMouse->SetRelativePosition(xRel,yRel);\n }\n }\n\n}\n\nvoid Sdl2Window::SwapBuffers()\n{\n SDL_GL_SwapWindow(mWindow);\n int width, height;\n SDL_GetWindowSize(mWindow, &width, &height);\n glViewport(0, 0, width, height);\n\n}\n\nvoid Sdl2Window::SetVisible(bool visible)\n{\n if (mVisible == visible) return;\n\n mVisible = visible;\n if (mVisible)\n {\n SDL_ShowWindow(mWindow);\n InitGlew();\n }\n else\n {\n SDL_HideWindow(mWindow);\n }\n}\n\nvoid Sdl2Window::InitGlew()\n{\n if (mGlewInit) return;\n\n mGlewInit = true;\n\n glewExperimental = GL_TRUE;\n glewInit();\n}\n\nSdlMouse* Sdl2Window::GetMouse()\n{\n\treturn mMouse;\n}\n\nGUInterface::Environment* Sdl2Window::GetEnvironment()\n{\n\treturn mEnv;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>use snap rectangle instead of logic rectangle<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/..\/Characters\/FloatConversion.h\"\n#include \"..\/..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/..\/Streams\/TextWriter.h\"\n\n#include \"Writer.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Streams;\n\nusing Characters::Character;\nusing Characters::String_Constant;\nusing Memory::Byte;\n\n\/*\n * TODO:\n * No known issues\n *\/\n\nnamespace {\n \/\/ Just like Writer::Options but without opionals... fill those in\n struct Options_ {\n Options_ (const Variant::JSON::Writer::Options& o)\n : fFloatOptions{o.fFloatOptions.Value ()}\n , fJSONPrettyPrint (o.fJSONPrettyPrint.Value (true))\n , fSpacesPerIndent{o.fSpacesPerIndent.Value (4)}\n , fAllowNANInf{o.fAllowNANInf.Value (true)}\n {\n if (not fJSONPrettyPrint) {\n fSpacesPerIndent = 0;\n }\n if (fSpacesPerIndent != 0) {\n fIndentSpace = String_Constant{L\" \"}.Repeat (fSpacesPerIndent);\n }\n }\n Characters::Float2StringOptions fFloatOptions;\n bool fJSONPrettyPrint;\n unsigned int fSpacesPerIndent;\n String fIndentSpace;\n bool fAllowNANInf;\n };\n}\n\n\/*\n ********************************************************************************\n ********************* DataExchange::JSON::PrettyPrint **************************\n ********************************************************************************\n *\/\nnamespace {\n void Indent_ (const Options_& options, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n \/\/ if test not needed, but speed tweak (especially since incorporates options.fJSONPrettyPrint check\n if (options.fSpacesPerIndent != 0) {\n out.Write (options.fIndentSpace.Repeat (indentLevel));\n }\n }\n}\nnamespace {\n void PrettyPrint_ (const Options_& options, const VariantValue& v, const OutputStream<Character>::Ptr& out, int indentLevel);\n void PrettyPrint_Null_ (const Options_& options, const OutputStream<Character>::Ptr& out)\n {\n out.Write (L\"null\");\n }\n void PrettyPrint_ (const Options_& options, bool v, const OutputStream<Character>::Ptr& out)\n {\n if (v) {\n out.Write (L\"true\");\n }\n else {\n out.Write (L\"false\");\n }\n }\n void PrettyPrint_ (const Options_& options, long long int v, const OutputStream<Character>::Ptr& out)\n {\n wchar_t buf[1024];\n (void)::swprintf (buf, NEltsOf (buf), L\"%lld\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (const Options_& options, unsigned long long int v, const OutputStream<Character>::Ptr& out)\n {\n wchar_t buf[1024];\n (void)::swprintf (buf, NEltsOf (buf), L\"%llu\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (const Options_& options, const String& v, const OutputStream<Character>::Ptr& out);\n void PrettyPrint_ (const Options_& options, long double v, const OutputStream<Character>::Ptr& out)\n {\n String tmp{Characters::Float2String (v, options.fFloatOptions)};\n if (isnan (v) or isinf (v)) {\n Require (options.fAllowNANInf);\n PrettyPrint_ (options, tmp, out);\n }\n else {\n out.Write (tmp);\n }\n }\n template <typename CHARITERATOR>\n void PrettyPrint_ (const Options_& options, CHARITERATOR start, CHARITERATOR end, const OutputStream<Character>::Ptr& out)\n {\n \/\/ A backslash can be followed by \"\\\/bfnrtu (@ see http:\/\/www.ecma-international.org\/publications\/files\/ECMA-ST\/ECMA-404.pdf)\n Characters::StringBuilder sb;\n sb.Append (L\"\\\"\");\n for (auto i = start; i != end; ++i) {\n switch (*i) {\n case '\\\"':\n sb.Append (L\"\\\\\\\"\");\n break;\n case '\\b':\n sb.Append (L\"\\\\b\");\n break;\n case '\\f':\n sb.Append (L\"\\\\f\");\n break;\n case '\\n':\n sb.Append (L\"\\\\n\");\n break;\n case '\\r':\n sb.Append (L\"\\\\r\");\n break;\n case '\\t':\n sb.Append (L\"\\\\t\");\n break;\n case '\\\\':\n sb.Append (L\"\\\\\\\\\");\n break;\n default:\n \/\/ JSON rule is Any code point except \" or \\ or control character. So OK to emit most large unicode chars - just not control chars\n wchar_t c = *i;\n if (std::iswcntrl (c)) {\n wchar_t buf[10];\n (void)::swprintf (buf, NEltsOf (buf), L\"\\\\u%04x\", static_cast<char16_t> (c));\n sb.Append (buf);\n }\n else {\n sb.Append (&c, &c + 1);\n }\n break;\n }\n }\n sb.Append (L\"\\\"\");\n out.Write (sb.begin (), sb.end ());\n }\n void PrettyPrint_ (const Options_& options, const wstring& v, const OutputStream<Character>::Ptr& out)\n {\n PrettyPrint_ (options, v.begin (), v.end (), out);\n }\n void PrettyPrint_ (const Options_& options, const String& v, const OutputStream<Character>::Ptr& out)\n {\n pair<const wchar_t*, const wchar_t*> p = v.GetData<wchar_t> ();\n static_assert (sizeof (Character) == sizeof (wchar_t), \"sizeof(Character) == sizeof(wchar_t)\");\n PrettyPrint_ (options, p.first, p.second, out);\n }\n void PrettyPrint_ (const Options_& options, const vector<VariantValue>& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n out.Write (options.fJSONPrettyPrint ? L\"[\\n\" : L\"[\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n Indent_ (options, out, indentLevel + 1);\n PrettyPrint_ (options, *i, out, indentLevel + 1);\n if (i + 1 != v.end ()) {\n out.Write (L\",\");\n }\n if (options.fJSONPrettyPrint) {\n out.Write (L\"\\n\");\n }\n }\n Indent_ (options, out, indentLevel);\n out.Write (L\"]\");\n }\n void PrettyPrint_ (const Options_& options, const Mapping<String, VariantValue>& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n out.Write (options.fJSONPrettyPrint ? L\"{\\n\" : L\"{\");\n for (auto i = v.begin (); i != v.end ();) {\n Indent_ (options, out, indentLevel + 1);\n PrettyPrint_ (options, i->fKey, out, indentLevel + 1);\n out.Write (L\" : \");\n PrettyPrint_ (options, i->fValue, out, indentLevel + 1);\n ++i;\n if (i != v.end ()) {\n out.Write (L\",\");\n }\n if (options.fJSONPrettyPrint) {\n out.Write (L\"\\n\");\n }\n }\n Indent_ (options, out, indentLevel);\n out.Write (L\"}\");\n }\n void PrettyPrint_ (const Options_& options, const VariantValue& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n switch (v.GetType ()) {\n case VariantValue::eNull:\n PrettyPrint_Null_ (options, out);\n break;\n case VariantValue::eBoolean:\n PrettyPrint_ (options, v.As<bool> (), out);\n break;\n case VariantValue::eBLOB:\n PrettyPrint_ (options, v.As<String> (), out);\n break;\n case VariantValue::eDate:\n PrettyPrint_ (options, v.As<wstring> (), out);\n break;\n case VariantValue::eDateTime:\n PrettyPrint_ (options, v.As<wstring> (), out);\n break;\n case VariantValue::eInteger:\n PrettyPrint_ (options, v.As<long long int> (), out);\n break;\n case VariantValue::eUnsignedInteger:\n PrettyPrint_ (options, v.As<unsigned long long int> (), out);\n break;\n case VariantValue::eFloat:\n PrettyPrint_ (options, v.As<long double> (), out);\n break;\n case VariantValue::eString:\n PrettyPrint_ (options, v.As<wstring> (), out);\n break;\n case VariantValue::eMap:\n PrettyPrint_ (options, v.As<Mapping<String, VariantValue>> (), out, indentLevel);\n break;\n case VariantValue::eArray:\n PrettyPrint_ (options, v.As<vector<VariantValue>> (), out, indentLevel);\n break;\n default:\n RequireNotReached (); \/\/ only certain types allowed\n }\n }\n}\n\n\/*\n ********************************************************************************\n ************************** DataExchange::JSON::Writer **************************\n ********************************************************************************\n *\/\nclass Variant::JSON::Writer::Rep_ : public Variant::Writer::_IRep {\npublic:\n Options_ fOptions_;\n Rep_ (const Options& options)\n : fOptions_ (options)\n {\n }\n Rep_ (const Options_& options)\n : fOptions_ (options)\n {\n }\n virtual _SharedPtrIRep Clone () const override\n {\n return make_shared<Rep_> (fOptions_); \/\/ no instance data\n }\n virtual String GetDefaultFileSuffix () const override\n {\n return String_Constant (L\".json\");\n }\n virtual void Write (const VariantValue& v, const Streams::OutputStream<Byte>::Ptr& out) override\n {\n TextWriter::Ptr textOut = TextWriter::New (out, TextWriter::Format::eUTF8WithoutBOM);\n PrettyPrint_ (fOptions_, v, textOut, 0);\n if (fOptions_.fJSONPrettyPrint) {\n textOut.Write (L\"\\n\"); \/\/ a single elt not LF terminated, but the entire doc should be.\n }\n }\n virtual void Write (const VariantValue& v, const Streams::OutputStream<Character>::Ptr& out) override\n {\n PrettyPrint_ (fOptions_, v, out, 0);\n }\n};\n\nVariant::JSON::Writer::Writer (const Options& options)\n : inherited (make_shared<Rep_> (options))\n{\n}\n<commit_msg>JSONWriter - refactor a bunch of cases that write string to go through same case<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/..\/Characters\/FloatConversion.h\"\n#include \"..\/..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/..\/Streams\/TextWriter.h\"\n\n#include \"Writer.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Streams;\n\nusing Characters::Character;\nusing Characters::String_Constant;\nusing Memory::Byte;\n\n\/*\n * TODO:\n * No known issues\n *\/\n\nnamespace {\n \/\/ Just like Writer::Options but without opionals... fill those in\n struct Options_ {\n Options_ (const Variant::JSON::Writer::Options& o)\n : fFloatOptions{o.fFloatOptions.Value ()}\n , fJSONPrettyPrint (o.fJSONPrettyPrint.Value (true))\n , fSpacesPerIndent{o.fSpacesPerIndent.Value (4)}\n , fAllowNANInf{o.fAllowNANInf.Value (true)}\n {\n if (not fJSONPrettyPrint) {\n fSpacesPerIndent = 0;\n }\n if (fSpacesPerIndent != 0) {\n fIndentSpace = String_Constant{L\" \"}.Repeat (fSpacesPerIndent);\n }\n }\n Characters::Float2StringOptions fFloatOptions;\n bool fJSONPrettyPrint;\n unsigned int fSpacesPerIndent;\n String fIndentSpace;\n bool fAllowNANInf;\n };\n}\n\n\/*\n ********************************************************************************\n ********************* DataExchange::JSON::PrettyPrint **************************\n ********************************************************************************\n *\/\nnamespace {\n void Indent_ (const Options_& options, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n \/\/ if test not needed, but speed tweak (especially since incorporates options.fJSONPrettyPrint check\n if (options.fSpacesPerIndent != 0) {\n out.Write (options.fIndentSpace.Repeat (indentLevel));\n }\n }\n}\nnamespace {\n void PrettyPrint_ (const Options_& options, const VariantValue& v, const OutputStream<Character>::Ptr& out, int indentLevel);\n void PrettyPrint_Null_ (const Options_& options, const OutputStream<Character>::Ptr& out)\n {\n out.Write (L\"null\");\n }\n void PrettyPrint_ (const Options_& options, bool v, const OutputStream<Character>::Ptr& out)\n {\n if (v) {\n out.Write (L\"true\");\n }\n else {\n out.Write (L\"false\");\n }\n }\n void PrettyPrint_ (const Options_& options, long long int v, const OutputStream<Character>::Ptr& out)\n {\n wchar_t buf[1024];\n (void)::swprintf (buf, NEltsOf (buf), L\"%lld\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (const Options_& options, unsigned long long int v, const OutputStream<Character>::Ptr& out)\n {\n wchar_t buf[1024];\n (void)::swprintf (buf, NEltsOf (buf), L\"%llu\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (const Options_& options, const String& v, const OutputStream<Character>::Ptr& out);\n void PrettyPrint_ (const Options_& options, long double v, const OutputStream<Character>::Ptr& out)\n {\n String tmp{Characters::Float2String (v, options.fFloatOptions)};\n if (isnan (v) or isinf (v)) {\n Require (options.fAllowNANInf);\n PrettyPrint_ (options, tmp, out);\n }\n else {\n out.Write (tmp);\n }\n }\n template <typename CHARITERATOR>\n void PrettyPrint_ (const Options_& options, CHARITERATOR start, CHARITERATOR end, const OutputStream<Character>::Ptr& out)\n {\n \/\/ A backslash can be followed by \"\\\/bfnrtu (@ see http:\/\/www.ecma-international.org\/publications\/files\/ECMA-ST\/ECMA-404.pdf)\n Characters::StringBuilder sb;\n sb.Append (L\"\\\"\");\n for (auto i = start; i != end; ++i) {\n switch (*i) {\n case '\\\"':\n sb.Append (L\"\\\\\\\"\");\n break;\n case '\\b':\n sb.Append (L\"\\\\b\");\n break;\n case '\\f':\n sb.Append (L\"\\\\f\");\n break;\n case '\\n':\n sb.Append (L\"\\\\n\");\n break;\n case '\\r':\n sb.Append (L\"\\\\r\");\n break;\n case '\\t':\n sb.Append (L\"\\\\t\");\n break;\n case '\\\\':\n sb.Append (L\"\\\\\\\\\");\n break;\n default:\n \/\/ JSON rule is Any code point except \" or \\ or control character. So OK to emit most large unicode chars - just not control chars\n wchar_t c = *i;\n if (std::iswcntrl (c)) {\n wchar_t buf[10];\n (void)::swprintf (buf, NEltsOf (buf), L\"\\\\u%04x\", static_cast<char16_t> (c));\n sb.Append (buf);\n }\n else {\n sb.Append (&c, &c + 1);\n }\n break;\n }\n }\n sb.Append (L\"\\\"\");\n out.Write (sb.begin (), sb.end ());\n }\n void PrettyPrint_ (const Options_& options, const wstring& v, const OutputStream<Character>::Ptr& out)\n {\n PrettyPrint_ (options, v.begin (), v.end (), out);\n }\n void PrettyPrint_ (const Options_& options, const String& v, const OutputStream<Character>::Ptr& out)\n {\n pair<const wchar_t*, const wchar_t*> p = v.GetData<wchar_t> ();\n static_assert (sizeof (Character) == sizeof (wchar_t), \"sizeof(Character) == sizeof(wchar_t)\");\n PrettyPrint_ (options, p.first, p.second, out);\n }\n void PrettyPrint_ (const Options_& options, const vector<VariantValue>& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n out.Write (options.fJSONPrettyPrint ? L\"[\\n\" : L\"[\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n Indent_ (options, out, indentLevel + 1);\n PrettyPrint_ (options, *i, out, indentLevel + 1);\n if (i + 1 != v.end ()) {\n out.Write (L\",\");\n }\n if (options.fJSONPrettyPrint) {\n out.Write (L\"\\n\");\n }\n }\n Indent_ (options, out, indentLevel);\n out.Write (L\"]\");\n }\n void PrettyPrint_ (const Options_& options, const Mapping<String, VariantValue>& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n out.Write (options.fJSONPrettyPrint ? L\"{\\n\" : L\"{\");\n for (auto i = v.begin (); i != v.end ();) {\n Indent_ (options, out, indentLevel + 1);\n PrettyPrint_ (options, i->fKey, out, indentLevel + 1);\n out.Write (L\" : \");\n PrettyPrint_ (options, i->fValue, out, indentLevel + 1);\n ++i;\n if (i != v.end ()) {\n out.Write (L\",\");\n }\n if (options.fJSONPrettyPrint) {\n out.Write (L\"\\n\");\n }\n }\n Indent_ (options, out, indentLevel);\n out.Write (L\"}\");\n }\n void PrettyPrint_ (const Options_& options, const VariantValue& v, const OutputStream<Character>::Ptr& out, int indentLevel)\n {\n switch (v.GetType ()) {\n case VariantValue::eNull:\n PrettyPrint_Null_ (options, out);\n break;\n case VariantValue::eBoolean:\n PrettyPrint_ (options, v.As<bool> (), out);\n break;\n case VariantValue::eInteger:\n PrettyPrint_ (options, v.As<long long int> (), out);\n break;\n case VariantValue::eUnsignedInteger:\n PrettyPrint_ (options, v.As<unsigned long long int> (), out);\n break;\n case VariantValue::eFloat:\n PrettyPrint_ (options, v.As<long double> (), out);\n break;\n case VariantValue::eMap:\n PrettyPrint_ (options, v.As<Mapping<String, VariantValue>> (), out, indentLevel);\n break;\n case VariantValue::eArray:\n PrettyPrint_ (options, v.As<vector<VariantValue>> (), out, indentLevel);\n break;\n default:\n PrettyPrint_ (options, v.As<String> (), out);\n }\n }\n}\n\n\/*\n ********************************************************************************\n ************************** DataExchange::JSON::Writer **************************\n ********************************************************************************\n *\/\nclass Variant::JSON::Writer::Rep_ : public Variant::Writer::_IRep {\npublic:\n Options_ fOptions_;\n Rep_ (const Options& options)\n : fOptions_ (options)\n {\n }\n Rep_ (const Options_& options)\n : fOptions_ (options)\n {\n }\n virtual _SharedPtrIRep Clone () const override\n {\n return make_shared<Rep_> (fOptions_); \/\/ no instance data\n }\n virtual String GetDefaultFileSuffix () const override\n {\n return String_Constant (L\".json\");\n }\n virtual void Write (const VariantValue& v, const Streams::OutputStream<Byte>::Ptr& out) override\n {\n TextWriter::Ptr textOut = TextWriter::New (out, TextWriter::Format::eUTF8WithoutBOM);\n PrettyPrint_ (fOptions_, v, textOut, 0);\n if (fOptions_.fJSONPrettyPrint) {\n textOut.Write (L\"\\n\"); \/\/ a single elt not LF terminated, but the entire doc should be.\n }\n }\n virtual void Write (const VariantValue& v, const Streams::OutputStream<Character>::Ptr& out) override\n {\n PrettyPrint_ (fOptions_, v, out, 0);\n }\n};\n\nVariant::JSON::Writer::Writer (const Options& options)\n : inherited (make_shared<Rep_> (options))\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2018 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file\n * \\brief memory_slice_view expression implementation\n *\/\n\n#pragma once\n\nnamespace etl {\n\n\/*!\n * \\brief View that shows a slice of an expression\n * \\tparam T The type of expression on which the view is made\n *\/\ntemplate <typename T, bool Aligned>\nstruct memory_slice_view {\n using sub_type = T; \/\/\/< The sub type\n using value_type = value_t<sub_type>; \/\/\/< The value contained in the expression\n using memory_type = value_type*; \/\/\/< The memory acess type\n using const_memory_type = const value_type*; \/\/\/< The const memory access type\n using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; \/\/\/< The type returned by the view\n using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; \/\/\/< The const type return by the view\n\nprivate:\n T sub; \/\/\/< The Sub expression\n const size_t first; \/\/\/< The index\n const size_t last; \/\/\/< The last index\n\n friend struct etl_traits<memory_slice_view>;\n\npublic:\n\n \/*!\n * \\brief The vectorization type for V\n *\/\n template<typename V = default_vec>\n using vec_type = typename V::template vec_type<value_type>;\n\n \/*!\n * \\brief Construct a new memory_slice_view over the given sub expression\n * \\param sub The sub expression\n * \\param first The first index\n * \\param last The last index\n *\/\n memory_slice_view(sub_type sub, size_t first, size_t last)\n : sub(sub), first(first), last(last) {}\n\n \/*!\n * \\brief Returns the element at the given index\n * \\param j The index\n * \\return a reference to the element at the given index.\n *\/\n const_return_type operator[](size_t j) const {\n return sub[first + j];\n }\n\n \/*!\n * \\brief Returns the element at the given index\n * \\param j The index\n * \\return a reference to the element at the given index.\n *\/\n return_type operator[](size_t j) {\n return sub[first + j];\n }\n\n \/*!\n * \\brief Returns the value at the given index\n * This function never has side effects.\n * \\param j The index\n * \\return the value at the given index.\n *\/\n value_type read_flat(size_t j) const noexcept {\n return sub[first + j];\n }\n\n \/\/Note(CPP17): Use if constexpr for alignment\n\n \/*!\n * \\brief Load several elements of the expression at once\n * \\param x The position at which to start.\n * \\tparam V The vectorization mode to use\n * \\return a vector containing several elements of the expression\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_enable_iff(A)>\n auto load(size_t x) const noexcept {\n return sub.template load<V>(x + first );\n }\n\n \/*!\n * \\brief Load several elements of the expression at once\n * \\param x The position at which to start.\n * \\tparam V The vectorization mode to use\n * \\return a vector containing several elements of the expression\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_disable_iff(A)>\n auto load(size_t x) const noexcept {\n return sub.template loadu<V>(x + first );\n }\n\n \/*!\n * \\brief Load several elements of the expression at once\n * \\param x The position at which to start.\n * \\tparam V The vectorization mode to use\n * \\return a vector containing several elements of the expression\n *\/\n template <typename V = default_vec>\n auto loadu(size_t x) const noexcept {\n return sub.template loadu<V>(x + first );\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_enable_iff(A)>\n void store(vec_type<V> in, size_t i) noexcept {\n sub.template store<V>(in, first + i);\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_disable_iff(A)>\n void store(vec_type<V> in, size_t i) noexcept {\n sub.template storeu<V>(in, first + i);\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec>\n void storeu(vec_type<V> in, size_t i) noexcept {\n sub.template storeu<V>(in, first + i);\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once, using non-temporal store\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_enable_iff(A)>\n void stream(vec_type<V> in, size_t i) noexcept {\n sub.template stream<V>(in, first + i);\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once, using non-temporal store\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec, bool A = Aligned, cpp_disable_iff(A)>\n void stream(vec_type<V> in, size_t i) noexcept {\n sub.template storeu<V>(in, first + i);\n }\n\n \/*!\n * \\brief Test if this expression aliases with the given expression\n * \\param rhs The other expression to test\n * \\return true if the two expressions aliases, false otherwise\n *\/\n template <typename E>\n bool alias(const E& rhs) const noexcept {\n return sub.alias(rhs);\n }\n\n \/*!\n * \\brief Returns a pointer to the first element in memory.\n * \\return a pointer tot the first element in memory.\n *\/\n memory_type memory_start() noexcept {\n return sub.memory_start() + first ;\n }\n\n \/*!\n * \\brief Returns a pointer to the first element in memory.\n * \\return a pointer tot the first element in memory.\n *\/\n const_memory_type memory_start() const noexcept {\n return sub.memory_start() + first ;\n }\n\n \/*!\n * \\brief Returns a pointer to the past-the-end element in memory.\n * \\return a pointer tot the past-the-end element in memory.\n *\/\n memory_type memory_end() noexcept {\n return sub.memory_start() + last ;\n }\n\n \/*!\n * \\brief Returns a pointer to the past-the-end element in memory.\n * \\return a pointer tot the past-the-end element in memory.\n *\/\n const_memory_type memory_end() const noexcept {\n return sub.memory_start() + last;\n }\n\n \/\/ Assignment functions\n\n \/*!\n * \\brief Assign to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_to(L&& lhs) const {\n std_assign_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Add to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_add_to(L&& lhs) const {\n std_add_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Sub from the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_sub_to(L&& lhs) const {\n std_sub_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Multiply the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mul_to(L&& lhs) const {\n std_mul_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Divide the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_div_to(L&& lhs) const {\n std_div_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Modulo the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mod_to(L&& lhs) const {\n std_mod_evaluate(*this, lhs);\n }\n\n \/\/ Internals\n\n \/*!\n * \\brief Apply the given visitor to this expression and its descendants.\n * \\param visitor The visitor to apply\n *\/\n void visit(detail::evaluator_visitor& visitor) const {\n sub.visit(visitor);\n }\n\n \/*!\n * \\brief Ensures that the GPU memory is allocated and that the GPU memory\n * is up to date (to undefined value).\n *\/\n void ensure_cpu_up_to_date() const {\n \/\/ The sub value must be ensured\n sub.ensure_cpu_up_to_date();\n }\n\n \/*!\n * \\brief Copy back from the GPU to the expression memory if\n * necessary.\n *\/\n void ensure_gpu_up_to_date() const {\n \/\/ The sub value must be ensured\n sub.ensure_gpu_up_to_date();\n }\n};\n\n\/*!\n * \\brief Specialization for memory_slice_view\n *\/\ntemplate <typename T, bool Aligned>\nstruct etl_traits<etl::memory_slice_view<T, Aligned>> {\n using expr_t = etl::memory_slice_view<T, Aligned>; \/\/\/< The expression type\n using sub_expr_t = std::decay_t<T>; \/\/\/< The sub expression type\n using value_type = typename etl_traits<sub_expr_t>::value_type; \/\/\/< The value type\n\n static constexpr bool is_etl = true; \/\/\/< Indicates if the type is an ETL expression\n static constexpr bool is_transformer = false; \/\/\/< Indicates if the type is a transformer\n static constexpr bool is_view = true; \/\/\/< Indicates if the type is a view\n static constexpr bool is_magic_view = false; \/\/\/< Indicates if the type is a magic view\n static constexpr bool is_fast = false; \/\/\/< Indicates if the expression is fast\n static constexpr bool is_linear = etl_traits<sub_expr_t>::is_linear; \/\/\/< Indicates if the expression is linear\n static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; \/\/\/< Indicates if the expression is thread safe\n static constexpr bool is_value = false; \/\/\/< Indicates if the expression is of value type\n static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct; \/\/\/< Indicates if the expression has direct memory access\n static constexpr bool is_generator = false; \/\/\/< Indicates if the expression is a generator\n static constexpr bool is_padded = false; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_aligned = Aligned; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_temporary = etl_traits<sub_expr_t>::is_temporary; \/\/\/< Indicates if the exxpression needs a evaluator visitor\n static constexpr bool gpu_computable = false; \/\/\/< Indicates if the expression can be computed on GPU\n static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; \/\/\/< The expression's storage order\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template <vector_mode_t V>\n static constexpr bool vectorizable = etl_traits<sub_expr_t>::template vectorizable<V>;\n\n \/*!\n * \\brief Returns the size of the given expression\n * \\param v The expression to get the size for\n * \\returns the size of the given expression\n *\/\n static size_t size(const expr_t& v) {\n return v.last - v.first;\n }\n\n \/*!\n * \\brief Returns the dth dimension of the given expression\n * \\param v The expression\n * \\param d The dimension to get\n * \\return The dth dimension of the given expression\n *\/\n static size_t dim(const expr_t& v, size_t d) {\n cpp_unused(d);\n return v.last - v.first;\n }\n\n \/*!\n * \\brief Returns the number of expressions for this type\n * \\return the number of dimensions of this type\n *\/\n static constexpr size_t dimensions() {\n return 1;\n }\n};\n\n\/*!\n * \\brief Returns view representing a memory slice view of the given expression.\n * \\param value The ETL expression\n * \\param first The first index\n * \\param last The last index\n * \\return a view expression representing a sub dimensional view of the given expression\n *\/\ntemplate <bool Aligned = false, typename E>\nauto memory_slice(E&& value, size_t first, size_t last) -> detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>> {\n static_assert(is_etl_expr<E>, \"etl::memory_slice can only be used on ETL expressions\");\n return detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>>{{value, first, last}};\n}\n\n} \/\/end of namespace etl\n<commit_msg>C++17: Use if constexpr<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2018 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file\n * \\brief memory_slice_view expression implementation\n *\/\n\n#pragma once\n\nnamespace etl {\n\n\/*!\n * \\brief View that shows a slice of an expression\n * \\tparam T The type of expression on which the view is made\n *\/\ntemplate <typename T, bool Aligned>\nstruct memory_slice_view {\n using sub_type = T; \/\/\/< The sub type\n using value_type = value_t<sub_type>; \/\/\/< The value contained in the expression\n using memory_type = value_type*; \/\/\/< The memory acess type\n using const_memory_type = const value_type*; \/\/\/< The const memory access type\n using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; \/\/\/< The type returned by the view\n using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; \/\/\/< The const type return by the view\n\nprivate:\n T sub; \/\/\/< The Sub expression\n const size_t first; \/\/\/< The index\n const size_t last; \/\/\/< The last index\n\n friend struct etl_traits<memory_slice_view>;\n\npublic:\n\n \/*!\n * \\brief The vectorization type for V\n *\/\n template<typename V = default_vec>\n using vec_type = typename V::template vec_type<value_type>;\n\n \/*!\n * \\brief Construct a new memory_slice_view over the given sub expression\n * \\param sub The sub expression\n * \\param first The first index\n * \\param last The last index\n *\/\n memory_slice_view(sub_type sub, size_t first, size_t last)\n : sub(sub), first(first), last(last) {}\n\n \/*!\n * \\brief Returns the element at the given index\n * \\param j The index\n * \\return a reference to the element at the given index.\n *\/\n const_return_type operator[](size_t j) const {\n return sub[first + j];\n }\n\n \/*!\n * \\brief Returns the element at the given index\n * \\param j The index\n * \\return a reference to the element at the given index.\n *\/\n return_type operator[](size_t j) {\n return sub[first + j];\n }\n\n \/*!\n * \\brief Returns the value at the given index\n * This function never has side effects.\n * \\param j The index\n * \\return the value at the given index.\n *\/\n value_type read_flat(size_t j) const noexcept {\n return sub[first + j];\n }\n\n \/*!\n * \\brief Load several elements of the expression at once\n * \\param x The position at which to start.\n * \\tparam V The vectorization mode to use\n * \\return a vector containing several elements of the expression\n *\/\n template <typename V = default_vec>\n auto load(size_t x) const noexcept {\n if constexpr (Aligned) {\n return sub.template load<V>(x + first);\n } else {\n return sub.template loadu<V>(x + first);\n }\n }\n\n \/*!\n * \\brief Load several elements of the expression at once\n * \\param x The position at which to start.\n * \\tparam V The vectorization mode to use\n * \\return a vector containing several elements of the expression\n *\/\n template <typename V = default_vec>\n auto loadu(size_t x) const noexcept {\n return sub.template loadu<V>(x + first );\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec>\n void store(vec_type<V> in, size_t i) noexcept {\n if constexpr (Aligned) {\n sub.template store<V>(in, first + i);\n } else {\n sub.template storeu<V>(in, first + i);\n }\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec>\n void storeu(vec_type<V> in, size_t i) noexcept {\n sub.template storeu<V>(in, first + i);\n }\n\n \/*!\n * \\brief Store several elements in the matrix at once, using non-temporal store\n * \\param in The several elements to store\n * \\param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).\n * \\tparam V The vectorization mode to use\n *\/\n template <typename V = default_vec>\n void stream(vec_type<V> in, size_t i) noexcept {\n if constexpr (Aligned) {\n sub.template stream<V>(in, first + i);\n } else {\n sub.template storeu<V>(in, first + i);\n }\n }\n\n \/*!\n * \\brief Test if this expression aliases with the given expression\n * \\param rhs The other expression to test\n * \\return true if the two expressions aliases, false otherwise\n *\/\n template <typename E>\n bool alias(const E& rhs) const noexcept {\n return sub.alias(rhs);\n }\n\n \/*!\n * \\brief Returns a pointer to the first element in memory.\n * \\return a pointer tot the first element in memory.\n *\/\n memory_type memory_start() noexcept {\n return sub.memory_start() + first ;\n }\n\n \/*!\n * \\brief Returns a pointer to the first element in memory.\n * \\return a pointer tot the first element in memory.\n *\/\n const_memory_type memory_start() const noexcept {\n return sub.memory_start() + first ;\n }\n\n \/*!\n * \\brief Returns a pointer to the past-the-end element in memory.\n * \\return a pointer tot the past-the-end element in memory.\n *\/\n memory_type memory_end() noexcept {\n return sub.memory_start() + last ;\n }\n\n \/*!\n * \\brief Returns a pointer to the past-the-end element in memory.\n * \\return a pointer tot the past-the-end element in memory.\n *\/\n const_memory_type memory_end() const noexcept {\n return sub.memory_start() + last;\n }\n\n \/\/ Assignment functions\n\n \/*!\n * \\brief Assign to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_to(L&& lhs) const {\n std_assign_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Add to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_add_to(L&& lhs) const {\n std_add_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Sub from the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_sub_to(L&& lhs) const {\n std_sub_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Multiply the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mul_to(L&& lhs) const {\n std_mul_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Divide the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_div_to(L&& lhs) const {\n std_div_evaluate(*this, lhs);\n }\n\n \/*!\n * \\brief Modulo the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mod_to(L&& lhs) const {\n std_mod_evaluate(*this, lhs);\n }\n\n \/\/ Internals\n\n \/*!\n * \\brief Apply the given visitor to this expression and its descendants.\n * \\param visitor The visitor to apply\n *\/\n void visit(detail::evaluator_visitor& visitor) const {\n sub.visit(visitor);\n }\n\n \/*!\n * \\brief Ensures that the GPU memory is allocated and that the GPU memory\n * is up to date (to undefined value).\n *\/\n void ensure_cpu_up_to_date() const {\n \/\/ The sub value must be ensured\n sub.ensure_cpu_up_to_date();\n }\n\n \/*!\n * \\brief Copy back from the GPU to the expression memory if\n * necessary.\n *\/\n void ensure_gpu_up_to_date() const {\n \/\/ The sub value must be ensured\n sub.ensure_gpu_up_to_date();\n }\n};\n\n\/*!\n * \\brief Specialization for memory_slice_view\n *\/\ntemplate <typename T, bool Aligned>\nstruct etl_traits<etl::memory_slice_view<T, Aligned>> {\n using expr_t = etl::memory_slice_view<T, Aligned>; \/\/\/< The expression type\n using sub_expr_t = std::decay_t<T>; \/\/\/< The sub expression type\n using value_type = typename etl_traits<sub_expr_t>::value_type; \/\/\/< The value type\n\n static constexpr bool is_etl = true; \/\/\/< Indicates if the type is an ETL expression\n static constexpr bool is_transformer = false; \/\/\/< Indicates if the type is a transformer\n static constexpr bool is_view = true; \/\/\/< Indicates if the type is a view\n static constexpr bool is_magic_view = false; \/\/\/< Indicates if the type is a magic view\n static constexpr bool is_fast = false; \/\/\/< Indicates if the expression is fast\n static constexpr bool is_linear = etl_traits<sub_expr_t>::is_linear; \/\/\/< Indicates if the expression is linear\n static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; \/\/\/< Indicates if the expression is thread safe\n static constexpr bool is_value = false; \/\/\/< Indicates if the expression is of value type\n static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct; \/\/\/< Indicates if the expression has direct memory access\n static constexpr bool is_generator = false; \/\/\/< Indicates if the expression is a generator\n static constexpr bool is_padded = false; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_aligned = Aligned; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_temporary = etl_traits<sub_expr_t>::is_temporary; \/\/\/< Indicates if the exxpression needs a evaluator visitor\n static constexpr bool gpu_computable = false; \/\/\/< Indicates if the expression can be computed on GPU\n static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; \/\/\/< The expression's storage order\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template <vector_mode_t V>\n static constexpr bool vectorizable = etl_traits<sub_expr_t>::template vectorizable<V>;\n\n \/*!\n * \\brief Returns the size of the given expression\n * \\param v The expression to get the size for\n * \\returns the size of the given expression\n *\/\n static size_t size(const expr_t& v) {\n return v.last - v.first;\n }\n\n \/*!\n * \\brief Returns the dth dimension of the given expression\n * \\param v The expression\n * \\param d The dimension to get\n * \\return The dth dimension of the given expression\n *\/\n static size_t dim(const expr_t& v, size_t d) {\n cpp_unused(d);\n return v.last - v.first;\n }\n\n \/*!\n * \\brief Returns the number of expressions for this type\n * \\return the number of dimensions of this type\n *\/\n static constexpr size_t dimensions() {\n return 1;\n }\n};\n\n\/*!\n * \\brief Returns view representing a memory slice view of the given expression.\n * \\param value The ETL expression\n * \\param first The first index\n * \\param last The last index\n * \\return a view expression representing a sub dimensional view of the given expression\n *\/\ntemplate <bool Aligned = false, typename E>\nauto memory_slice(E&& value, size_t first, size_t last) -> detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>> {\n static_assert(is_etl_expr<E>, \"etl::memory_slice can only be used on ETL expressions\");\n return detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>>{{value, first, last}};\n}\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ client.hpp\n\/\/ fibio\n\/\/\n\/\/ Created by Chen Xu on 14-3-11.\n\/\/ Copyright (c) 2014 0d0a.com. All rights reserved.\n\/\/\n\n#ifndef fiberized_io_http_client_client_hpp\n#define fiberized_io_http_client_client_hpp\n\n#include <string>\n#include <functional>\n#include <fibio\/stream\/iostream.hpp>\n#include <fibio\/http\/client\/request.hpp>\n#include <fibio\/http\/client\/response.hpp>\n\nnamespace fibio { namespace http { namespace client {\n struct client {\n typedef fibio::http::client::request request;\n typedef fibio::http::client::response response;\n \n client()=default;\n client(const std::string &server, const std::string &port);\n client(const std::string &server, int port);\n \n std::error_code connect(const std::string &server, const std::string &port);\n std::error_code connect(const std::string &server, int port);\n void disconnect();\n \n void set_auto_decompress(bool c);\n bool get_auto_decompress() const;\n \n bool send_request(request &req, response &resp);\n \n std::string server_;\n std::string port_;\n stream::tcp_stream stream_;\n bool auto_decompress_;\n };\n}}} \/\/ End of namespace fibio::http::client\n\nnamespace fibio { namespace http {\n typedef client::client http_client;\n}} \/\/ End of namespace fibio::http\n\n#endif\n<commit_msg>disable auto decompress by default as it costs<commit_after>\/\/\n\/\/ client.hpp\n\/\/ fibio\n\/\/\n\/\/ Created by Chen Xu on 14-3-11.\n\/\/ Copyright (c) 2014 0d0a.com. All rights reserved.\n\/\/\n\n#ifndef fiberized_io_http_client_client_hpp\n#define fiberized_io_http_client_client_hpp\n\n#include <string>\n#include <functional>\n#include <fibio\/stream\/iostream.hpp>\n#include <fibio\/http\/client\/request.hpp>\n#include <fibio\/http\/client\/response.hpp>\n\nnamespace fibio { namespace http { namespace client {\n struct client {\n typedef fibio::http::client::request request;\n typedef fibio::http::client::response response;\n \n client()=default;\n client(const std::string &server, const std::string &port);\n client(const std::string &server, int port);\n \n std::error_code connect(const std::string &server, const std::string &port);\n std::error_code connect(const std::string &server, int port);\n void disconnect();\n \n void set_auto_decompress(bool c);\n bool get_auto_decompress() const;\n \n bool send_request(request &req, response &resp);\n \n std::string server_;\n std::string port_;\n stream::tcp_stream stream_;\n bool auto_decompress_=false;\n };\n}}} \/\/ End of namespace fibio::http::client\n\nnamespace fibio { namespace http {\n typedef client::client http_client;\n}} \/\/ End of namespace fibio::http\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\/*=========================================================================\n *\n * Portions of this file are subject to the VTK Toolkit Version 3 copyright.\n *\n * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n *\n * For complete copyright, license and disclaimer of warranty information\n * please refer to the NOTICE file at the top of the ITK source tree.\n *\n *=========================================================================*\/\n#ifndef itkInterpolateImagePointsFilter_hxx\n#define itkInterpolateImagePointsFilter_hxx\n\n#include \"itkInterpolateImagePointsFilter.h\"\n#include \"itkProgressReporter.h\"\n\nnamespace itk\n{\n\/**\n * Constructor\n *\/\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::InterpolateImagePointsFilter()\n{\n m_Interpolator = InterpolatorType::New();\n m_DefaultPixelValue = 0;\n\n this->SetNumberOfRequiredInputs(ImageDimension+1);\n}\n\n\/**\n * Standard \"PrintSelf\" method\n *\/\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::PrintSelf(\n std::ostream & os,\n Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n os << indent << \"Default (background) pixel level: \" << m_DefaultPixelValue << std::endl;\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::SetInputImage(const TInputImage *inputImage)\n{\n this->SetInput(0, inputImage); \/\/ This is a data filter input\n \/\/ ***TODO: Where should this be done? During the filter update?\n \/\/ should be converted to a filter.\n m_Interpolator->SetInputImage(inputImage);\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::SetInterpolationCoordinate(const CoordImageType *coordinate, unsigned int setDimension)\n{\n \/\/ Set each coordinate as an input. Note that Input '0' is for the image.\n this->SetInput(setDimension + 1, coordinate); \/\/ This is a data filter input\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::BeforeThreadedGenerateData()\n{\n itkDebugMacro(<< \"Actually Executing\");\n\n \/\/ ***TODO: What needs to be done here? Should we set the input image at this\n \/\/ time?\n \/\/ ** Also, where is the output allocated?\n\n \/\/ OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );\n \/\/ outputPtr->Allocate();\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,\n ThreadIdType threadId)\n{\n itkDebugMacro(<< \"Actually Executing\");\n\n OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ There is a direct mapping between the desired outputRegion and the\n \/\/ CoordRegion\n \/\/ coordRegion is set to outputRegionForThread.\n RegionCopierType regionCopier;\n CoordImageRegionType coordRegion;\n regionCopier(coordRegion, outputRegionForThread);\n\n \/\/ Setup iterator for the output\n OutputImageIterator outIter(outputPtr, outputRegionForThread);\n \/\/outIter.GoToBegin(); \/\/Not sure if this is needed or inappropriate for\n \/\/ threading.\n\n \/\/ Setup an interator for each of the coordinate inputs.\n CoordImageIterator coordIter[ImageDimension];\n for ( unsigned int j = 0; j < ImageDimension; j++ )\n {\n CoordImageIterator temp(this->GetInput(j + 1), coordRegion);\n\/\/ temp.GoToBegin(); \/\/Not sure if this is needed or inappropriate for\n\/\/ threading.\n coordIter[j] = temp;\n }\n\n \/\/ Support for progress methods\/callbacks\n ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );\n\n \/\/ Loop through each pixel and calculate interpolated value.\n ContinuousIndexType index;\n while ( !outIter.IsAtEnd() )\n {\n for ( unsigned int j = 0; j < ImageDimension; j++ )\n {\n index[j] = ( coordIter[j] ).Value();\n ++( coordIter[j] );\n }\n if ( m_Interpolator->IsInsideBuffer(index) )\n {\n outIter.Set( m_Interpolator->EvaluateAtContinuousIndex(index) );\n \/\/ TODO: How can we modify the code so that it could also interpolate\n \/\/ from a set of point coordinates instead of Continuous Index\n \/\/ coordinates?\n \/\/ If this line is used instead of the above line then this will\n \/\/ calculate from points. ( PointType point must replace index throughout\n \/\/ this\n \/\/ function.)\n \/\/ outIter.Set( m_Interpolator->Evaluate( point );\n }\n else\n {\n outIter.Set(m_DefaultPixelValue);\n }\n ++outIter;\n progress.CompletedPixel();\n }\n}\n\n\/**\n *\n *\/\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::GenerateInputRequestedRegion()\n{\n \/\/ call the superclass' implementation of this method\n Superclass::GenerateInputRequestedRegion();\n\n if ( !this->GetInput(0) )\n {\n return;\n }\n\n \/\/ The coordinates may have arbitrary ordering so the entire image must be\n \/\/ available\n \/\/ for the filter. The coordinates on the other hand have the default\n \/\/ requested\n \/\/ region size.\n InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput(0) );\n inputPtr->SetRequestedRegionToLargestPossibleRegion();\n}\n\n\/**\n *\n *\/\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::GenerateOutputInformation()\n{\n \/\/ call the superclass' implementation of this method\n Superclass::GenerateOutputInformation();\n\n \/\/ This sets the largestPossibleRegion to ensure it is the same as\n \/\/ the coordinates. While this should be the default behavor, given the\n \/\/ multiple inputs it may incorrectly default to the image\n \/\/ largestPossibleRegion\n \/\/ thus this method was explicitly written.\n CoordImageTypePointer xCoordPtr = const_cast< TInputImage * >( this->GetInput(1) );\n OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ we need to compute the output spacing, the output image size, and the\n \/\/ output image start index. This is all determined by the coordinate data\n\n const typename TOutputImage::SpacingType &\n outputSpacing = xCoordPtr->GetSpacing();\n const typename TOutputImage::SizeType & outputSize =\n xCoordPtr->GetLargestPossibleRegion().GetSize();\n const typename TOutputImage::IndexType & outputStartIndex =\n xCoordPtr->GetLargestPossibleRegion().GetIndex();\n\n outputPtr->SetSpacing(outputSpacing);\n\n typename TOutputImage::RegionType outputLargestPossibleRegion;\n outputLargestPossibleRegion.SetSize(outputSize);\n outputLargestPossibleRegion.SetIndex(outputStartIndex);\n\n outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion);\n}\n} \/\/ namespace itk\n\n#endif\n<commit_msg>STYLE: Improve the class implementation file style.<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\/*=========================================================================\n *\n * Portions of this file are subject to the VTK Toolkit Version 3 copyright.\n *\n * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n *\n * For complete copyright, license and disclaimer of warranty information\n * please refer to the NOTICE file at the top of the ITK source tree.\n *\n *=========================================================================*\/\n#ifndef itkInterpolateImagePointsFilter_hxx\n#define itkInterpolateImagePointsFilter_hxx\n\n#include \"itkInterpolateImagePointsFilter.h\"\n#include \"itkProgressReporter.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::InterpolateImagePointsFilter()\n{\n m_Interpolator = InterpolatorType::New();\n m_DefaultPixelValue = 0;\n\n this->SetNumberOfRequiredInputs(ImageDimension+1);\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::SetInputImage(const TInputImage *inputImage)\n{\n this->SetInput(0, inputImage); \/\/ This is a data filter input\n \/\/ ***TODO: Where should this be done? During the filter update?\n \/\/ should be converted to a filter.\n m_Interpolator->SetInputImage(inputImage);\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::SetInterpolationCoordinate(const CoordImageType *coordinate, unsigned int setDimension)\n{\n \/\/ Set each coordinate as an input. Note that Input '0' is for the image.\n this->SetInput(setDimension + 1, coordinate); \/\/ This is a data filter input\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::BeforeThreadedGenerateData()\n{\n itkDebugMacro(<< \"Actually Executing\");\n\n \/\/ ***TODO: What needs to be done here? Should we set the input image at this\n \/\/ time?\n \/\/ ** Also, where is the output allocated?\n\n \/\/ OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() );\n \/\/ outputPtr->Allocate();\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,\n ThreadIdType threadId)\n{\n itkDebugMacro(<< \"Actually Executing\");\n\n OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ There is a direct mapping between the desired outputRegion and the\n \/\/ CoordRegion\n \/\/ coordRegion is set to outputRegionForThread.\n RegionCopierType regionCopier;\n CoordImageRegionType coordRegion;\n regionCopier(coordRegion, outputRegionForThread);\n\n \/\/ Setup iterator for the output\n OutputImageIterator outIter(outputPtr, outputRegionForThread);\n \/\/outIter.GoToBegin(); \/\/Not sure if this is needed or inappropriate for\n \/\/ threading.\n\n \/\/ Setup an interator for each of the coordinate inputs.\n CoordImageIterator coordIter[ImageDimension];\n for ( unsigned int j = 0; j < ImageDimension; j++ )\n {\n CoordImageIterator temp(this->GetInput(j + 1), coordRegion);\n\/\/ temp.GoToBegin(); \/\/Not sure if this is needed or inappropriate for threading.\n coordIter[j] = temp;\n }\n\n \/\/ Support for progress methods\/callbacks\n ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );\n\n \/\/ Loop through each pixel and calculate interpolated value.\n ContinuousIndexType index;\n while ( !outIter.IsAtEnd() )\n {\n for ( unsigned int j = 0; j < ImageDimension; j++ )\n {\n index[j] = ( coordIter[j] ).Value();\n ++( coordIter[j] );\n }\n if ( m_Interpolator->IsInsideBuffer(index) )\n {\n outIter.Set( m_Interpolator->EvaluateAtContinuousIndex(index) );\n \/\/ TODO: How can we modify the code so that it could also interpolate\n \/\/ from a set of point coordinates instead of Continuous Index\n \/\/ coordinates?\n \/\/ If this line is used instead of the above line then this will\n \/\/ calculate from points. ( PointType point must replace index throughout\n \/\/ this function.)\n \/\/ outIter.Set( m_Interpolator->Evaluate( point );\n }\n else\n {\n outIter.Set(m_DefaultPixelValue);\n }\n ++outIter;\n progress.CompletedPixel();\n }\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::GenerateInputRequestedRegion()\n{\n \/\/ Call the superclass' implementation of this method\n Superclass::GenerateInputRequestedRegion();\n\n if ( !this->GetInput(0) )\n {\n return;\n }\n\n \/\/ The coordinates may have arbitrary ordering so the entire image must be\n \/\/ available for the filter. The coordinates on the other hand have the default\n \/\/ requested region size.\n InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput(0) );\n inputPtr->SetRequestedRegionToLargestPossibleRegion();\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::GenerateOutputInformation()\n{\n \/\/ Call the superclass' implementation of this method\n Superclass::GenerateOutputInformation();\n\n \/\/ This sets the largestPossibleRegion to ensure it is the same as\n \/\/ the coordinates. While this should be the default behavor, given the\n \/\/ multiple inputs it may incorrectly default to the image\n \/\/ largestPossibleRegion.\n \/\/ Thus this method was explicitly written.\n \/\/\n CoordImageTypePointer xCoordPtr = const_cast< TInputImage * >( this->GetInput(1) );\n OutputImagePointer outputPtr = this->GetOutput();\n\n \/\/ We need to compute the output spacing, the output image size, and the\n \/\/ output image start index. This is all determined by the coordinate data\n\n const typename TOutputImage::SpacingType &\n outputSpacing = xCoordPtr->GetSpacing();\n const typename TOutputImage::SizeType & outputSize =\n xCoordPtr->GetLargestPossibleRegion().GetSize();\n const typename TOutputImage::IndexType & outputStartIndex =\n xCoordPtr->GetLargestPossibleRegion().GetIndex();\n\n outputPtr->SetSpacing(outputSpacing);\n\n typename TOutputImage::RegionType outputLargestPossibleRegion;\n outputLargestPossibleRegion.SetSize(outputSize);\n outputLargestPossibleRegion.SetIndex(outputStartIndex);\n\n outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion);\n}\n\ntemplate< typename TInputImage, typename TOutputImage, typename TCoordType, typename InterpolatorType >\nvoid\nInterpolateImagePointsFilter< TInputImage, TOutputImage, TCoordType, InterpolatorType >\n::PrintSelf( std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf( os, indent );\n\n os << indent << \"Default (background) pixel level: \" << m_DefaultPixelValue << std::endl;\n}\n} \/\/ namespace itk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageLiveWireContourModelFilter.h\"\n\n#include <itkShortestPathCostFunctionLiveWire.h>\n#include <itkImageRegionIterator.h>\n#include <itkShortestPathImageFilter.h>\n\n\nmitk::ImageLiveWireContourModelFilter::ImageLiveWireContourModelFilter()\n{\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNumberOfRequiredInputs(1);\n this->SetNumberOfOutputs( 1 );\n this->SetNthOutput(0, output.GetPointer());\n\n}\nmitk::ImageLiveWireContourModelFilter::~ImageLiveWireContourModelFilter()\n{\n\n}\n\n\nmitk::ImageLiveWireContourModelFilter::OutputType* mitk::ImageLiveWireContourModelFilter::GetOutput()\n{\n return Superclass::GetOutput();\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n this->SetInput( 0, input );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( unsigned int idx, const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n if ( idx + 1 > this->GetNumberOfInputs() )\n {\n this->SetNumberOfRequiredInputs(idx + 1);\n }\n if ( input != static_cast<InputType*> ( this->ProcessObject::GetInput ( idx ) ) )\n {\n this->ProcessObject::SetNthInput ( idx, const_cast<InputType*> ( input ) );\n this->Modified();\n }\n}\n\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( void )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(0));\n}\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( unsigned int idx )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(idx));\n}\n\n\nvoid mitk::ImageLiveWireContourModelFilter::GenerateData()\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n if(!input)\n {\n MITK_ERROR << \"No input available.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: No input available. Please set the input!\");\n return;\n }\n\n if( input->GetDimension() != 2 )\n {\n MITK_ERROR << \"Filter is only working on 2D images.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: Filter is only working on 2D images.. Please make sure that the input is 2D!\");\n return;\n }\n\n\n input->GetGeometry()->WorldToIndex(m_StartPoint, m_StartPointInIndex);\n input->GetGeometry()->WorldToIndex(m_EndPoint, m_EndPointInIndex);\n\n\n AccessFixedDimensionByItk(input, ItkProcessImage, 2);\n}\n\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::ItkProcessImage (itk::Image<TPixel, VImageDimension>* inputImage)\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef itk::Image< float, 2 > FloatImageType;\n\n typedef typename itk::ShortestPathImageFilter< InputImageType, InputImageType > ShortestPathImageFilterType;\n typedef typename itk::ShortestPathCostFunctionLiveWire< InputImageType > CostFunctionType;\n\n typedef InputImageType::IndexType IndexType;\n\n\n \/* compute the requested region for itk filters *\/\n\n typename IndexType startPoint, endPoint;\n \n startPoint[0] = m_StartPointInIndex[0];\n startPoint[1] = m_StartPointInIndex[1];\n\n endPoint[0] = m_EndPointInIndex[0];\n endPoint[1] = m_EndPointInIndex[1];\n\n \/\/minimum value in each direction for startRegion\n typename IndexType startRegion;\n startRegion[0] = startPoint[0] < endPoint[0] ? startPoint[0] : endPoint[0];\n startRegion[1] = startPoint[1] < endPoint[1] ? startPoint[1] : endPoint[1];\n\n \/\/maximum value in each direction for size\n typename InputImageType::SizeType size;\n size[0] = startPoint[0] > endPoint[0] ? startPoint[0] : endPoint[0];\n size[1] = startPoint[1] > endPoint[1] ? startPoint[1] : endPoint[1];\n\n\n typename InputImageType::RegionType region;\n region.SetSize( size );\n region.SetIndex( startRegion );\n \/*---------------------------------------------*\/\n\n\n \/* extracts features from image and calculates costs *\/\n typename CostFunctionType::Pointer costFunction = CostFunctionType::New();\n costFunction->SetImage(inputImage);\n costFunction->SetStartIndex(startPoint);\n costFunction->SetEndIndex(endPoint);\n \/\/costFunction->SetRequestedRegion(region);\n \/*---------------------------------------------*\/\n\n\n \/* calculate shortest path between start and end point *\/\n ShortestPathImageFilterType::Pointer shortestPathFilter = ShortestPathImageFilterType::New();\n shortestPathFilter->SetFullNeighborsMode(true);\n shortestPathFilter->SetInput(inputImage);\n shortestPathFilter->SetMakeOutputImage(false); \n\n \/\/shortestPathFilter->SetCalcAllDistances(true);\n shortestPathFilter->SetStartIndex(startPoint);\n shortestPathFilter->SetEndIndex(endPoint);\n\n shortestPathFilter->SetCostFunction(costFunction);\n\n shortestPathFilter->Update();\n\n \/*---------------------------------------------*\/\n\n\n \/* construct contour from path image *\/\n \/\/get the shortest path as vector\n typename std::vector< ShortestPathImageFilterType::IndexType> shortestPath = shortestPathFilter->GetVectorPath();\n\n \/\/fill the output contour with controll points from the path\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNthOutput(0, output.GetPointer());\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n typename std::vector< ShortestPathImageFilterType::IndexType>::iterator pathIterator = shortestPath.begin();\n\n while(pathIterator != shortestPath.end())\n {\n mitk::Point2D currentPoint;\n currentPoint[0] = (*pathIterator)[0];\n currentPoint[1] = (*pathIterator)[1];\n \n mitk::Point3D currentPoint3D;\n\n m_Geo2D->IndexToWorld(currentPoint, currentPoint);\n m_Geo2D->Map(currentPoint, currentPoint3D);\n output->AddVertex(currentPoint3D);\n \n pathIterator++;\n }\n \/*---------------------------------------------*\/\n\n}<commit_msg>cost function typedefinition<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageLiveWireContourModelFilter.h\"\n\n#include <itkShortestPathCostFunctionLiveWire.h>\n#include <itkImageRegionIterator.h>\n#include <itkShortestPathImageFilter.h>\n\n\nmitk::ImageLiveWireContourModelFilter::ImageLiveWireContourModelFilter()\n{\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNumberOfRequiredInputs(1);\n this->SetNumberOfOutputs( 1 );\n this->SetNthOutput(0, output.GetPointer());\n\n}\nmitk::ImageLiveWireContourModelFilter::~ImageLiveWireContourModelFilter()\n{\n\n}\n\n\nmitk::ImageLiveWireContourModelFilter::OutputType* mitk::ImageLiveWireContourModelFilter::GetOutput()\n{\n return Superclass::GetOutput();\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n this->SetInput( 0, input );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( unsigned int idx, const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n if ( idx + 1 > this->GetNumberOfInputs() )\n {\n this->SetNumberOfRequiredInputs(idx + 1);\n }\n if ( input != static_cast<InputType*> ( this->ProcessObject::GetInput ( idx ) ) )\n {\n this->ProcessObject::SetNthInput ( idx, const_cast<InputType*> ( input ) );\n this->Modified();\n }\n}\n\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( void )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(0));\n}\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( unsigned int idx )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(idx));\n}\n\n\nvoid mitk::ImageLiveWireContourModelFilter::GenerateData()\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n if(!input)\n {\n MITK_ERROR << \"No input available.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: No input available. Please set the input!\");\n return;\n }\n\n if( input->GetDimension() != 2 )\n {\n MITK_ERROR << \"Filter is only working on 2D images.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: Filter is only working on 2D images.. Please make sure that the input is 2D!\");\n return;\n }\n\n\n input->GetGeometry()->WorldToIndex(m_StartPoint, m_StartPointInIndex);\n input->GetGeometry()->WorldToIndex(m_EndPoint, m_EndPointInIndex);\n\n\n AccessFixedDimensionByItk(input, ItkProcessImage, 2);\n}\n\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::ItkProcessImage (itk::Image<TPixel, VImageDimension>* inputImage)\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef itk::Image< float, 2 > FloatImageType;\n\n typedef itk::ShortestPathImageFilter< typename InputImageType, typename InputImageType > ShortestPathImageFilterType;\n typedef itk::ShortestPathCostFunctionLiveWire< itk::Image< TPixel, VImageDimension > > CostFunctionType;\n\n typedef InputImageType::IndexType IndexType;\n\n\n \/* compute the requested region for itk filters *\/\n\n typename IndexType startPoint, endPoint;\n \n startPoint[0] = m_StartPointInIndex[0];\n startPoint[1] = m_StartPointInIndex[1];\n\n endPoint[0] = m_EndPointInIndex[0];\n endPoint[1] = m_EndPointInIndex[1];\n\n \/\/minimum value in each direction for startRegion\n typename IndexType startRegion;\n startRegion[0] = startPoint[0] < endPoint[0] ? startPoint[0] : endPoint[0];\n startRegion[1] = startPoint[1] < endPoint[1] ? startPoint[1] : endPoint[1];\n\n \/\/maximum value in each direction for size\n typename InputImageType::SizeType size;\n size[0] = startPoint[0] > endPoint[0] ? startPoint[0] : endPoint[0];\n size[1] = startPoint[1] > endPoint[1] ? startPoint[1] : endPoint[1];\n\n\n typename CostFunctionType::RegionType region;\n region.SetSize( size );\n region.SetIndex( startRegion );\n \/*---------------------------------------------*\/\n\n\n \/* extracts features from image and calculates costs *\/\n typename CostFunctionType::Pointer costFunction = CostFunctionType::New();\n costFunction->SetImage(inputImage);\n costFunction->SetStartIndex(startPoint);\n costFunction->SetEndIndex(endPoint);\n costFunction->SetRequestedRegion(region);\n \/*---------------------------------------------*\/\n\n\n \/* calculate shortest path between start and end point *\/\n ShortestPathImageFilterType::Pointer shortestPathFilter = ShortestPathImageFilterType::New();\n shortestPathFilter->SetFullNeighborsMode(true);\n shortestPathFilter->SetInput(inputImage);\n shortestPathFilter->SetMakeOutputImage(false); \n\n \/\/shortestPathFilter->SetCalcAllDistances(true);\n shortestPathFilter->SetStartIndex(startPoint);\n shortestPathFilter->SetEndIndex(endPoint);\n\n shortestPathFilter->SetCostFunction(costFunction);\n\n shortestPathFilter->Update();\n\n \/*---------------------------------------------*\/\n\n\n \/* construct contour from path image *\/\n \/\/get the shortest path as vector\n typename std::vector< ShortestPathImageFilterType::IndexType> shortestPath = shortestPathFilter->GetVectorPath();\n\n \/\/fill the output contour with controll points from the path\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNthOutput(0, output.GetPointer());\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n typename std::vector< ShortestPathImageFilterType::IndexType>::iterator pathIterator = shortestPath.begin();\n\n while(pathIterator != shortestPath.end())\n {\n mitk::Point2D currentPoint;\n currentPoint[0] = (*pathIterator)[0];\n currentPoint[1] = (*pathIterator)[1];\n \n mitk::Point3D currentPoint3D;\n\n m_Geo2D->IndexToWorld(currentPoint, currentPoint);\n m_Geo2D->Map(currentPoint, currentPoint3D);\n output->AddVertex(currentPoint3D);\n \n pathIterator++;\n }\n \/*---------------------------------------------*\/\n\n}<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file spsc_ring_buffer.inl\n \\brief Single producer \/ single consumer wait-free ring buffer inline implementation\n \\author Ivan Shynkarenka\n \\date 16.01.2016\n \\copyright MIT License\n*\/\n\n#include <windows.h>\n#include <debugapi.h>\n#include <string>\n\nnamespace CppCommon {\n\ninline SPSCRingBuffer::SPSCRingBuffer(size_t capacity) : _capacity(capacity), _mask(capacity - 1), _buffer(new uint8_t[capacity]), _head(0), _tail(0)\n{\n assert((capacity > 1) && \"Ring buffer capacity must be greater than one!\");\n assert(((capacity & (capacity - 1)) == 0) && \"Ring buffer capacity must be a power of two!\");\n}\n\ninline size_t SPSCRingBuffer::size() const noexcept\n{\n const size_t head = _head.load(std::memory_order_acquire);\n const size_t tail = _tail.load(std::memory_order_acquire);\n\n return head - tail;\n}\n\ninline bool SPSCRingBuffer::Enqueue(const void* chunk, size_t size)\n{\n assert((chunk != nullptr) && \"Pointer to the chunk should not be equal to 'nullptr'!\");\n assert((size > 0) && \"Chunk size should be greater than zero!\");\n assert((size <= _capacity) && \"Chunk size should not be greater than ring buffer capacity!\");\n\n if ((chunk == nullptr) || (size == 0) || (size > _capacity))\n return false;\n\n const size_t head = _head.load(std::memory_order_relaxed);\n const size_t tail = _tail.load(std::memory_order_acquire);\n\n \/\/ Check if there is required free space in the ring buffer\n if ((size + head - tail) > _capacity)\n return false;\n\n \/\/ Copy chunk of bytes into the ring buffer\n size_t head_index = head & _mask;\n size_t tail_index = tail & _mask;\n size_t remain = (tail_index > head_index) ? (tail_index - head_index) : (_capacity - head_index);\n size_t first = (size > remain) ? remain : size;\n size_t last = (size > remain) ? size - remain : 0;\n memcpy(&_buffer[head_index], (uint8_t*)chunk, first);\n memcpy(_buffer, (uint8_t*)chunk + first, last);\n\n \/\/ Increase the head cursor\n _head.store(head + size, std::memory_order_release);\n\n return true;\n}\n\ninline bool SPSCRingBuffer::Dequeue(void* chunk, size_t& size)\n{\n assert((chunk != nullptr) && \"Pointer to the chunk should not be equal to 'nullptr'!\");\n assert((size > 0) && \"Chunk size should be greater than zero!\");\n\n if ((chunk == nullptr) || (size == 0))\n return false;\n\n const size_t tail = _tail.load(std::memory_order_relaxed);\n const size_t head = _head.load(std::memory_order_acquire);\n\n \/\/ Get the ring buffer size\n size_t available = head - tail;\n if (size > available)\n size = available;\n\n \/\/ Check if the ring buffer is empty\n if (size == 0)\n return false;\n\n \/\/ Copy chunk of bytes from the ring buffer\n size_t head_index = head & _mask;\n size_t tail_index = tail & _mask;\n size_t remain = (head_index > tail_index) ? (head_index - tail_index) : (_capacity - tail_index);\n size_t first = (size > remain) ? remain : size;\n size_t last = (size > remain) ? size - remain : 0;\n memcpy((uint8_t*)chunk, &_buffer[tail_index], first);\n memcpy((uint8_t*)chunk + first, _buffer, last);\n\n \/\/ Increase the tail cursor\n _tail.store(tail + size, std::memory_order_release);\n\n return true;\n}\n\n} \/\/ namespace CppCommon\n<commit_msg>Bugfixing<commit_after>\/*!\n \\file spsc_ring_buffer.inl\n \\brief Single producer \/ single consumer wait-free ring buffer inline implementation\n \\author Ivan Shynkarenka\n \\date 16.01.2016\n \\copyright MIT License\n*\/\n\nnamespace CppCommon {\n\ninline SPSCRingBuffer::SPSCRingBuffer(size_t capacity) : _capacity(capacity), _mask(capacity - 1), _buffer(new uint8_t[capacity]), _head(0), _tail(0)\n{\n assert((capacity > 1) && \"Ring buffer capacity must be greater than one!\");\n assert(((capacity & (capacity - 1)) == 0) && \"Ring buffer capacity must be a power of two!\");\n}\n\ninline size_t SPSCRingBuffer::size() const noexcept\n{\n const size_t head = _head.load(std::memory_order_acquire);\n const size_t tail = _tail.load(std::memory_order_acquire);\n\n return head - tail;\n}\n\ninline bool SPSCRingBuffer::Enqueue(const void* chunk, size_t size)\n{\n assert((chunk != nullptr) && \"Pointer to the chunk should not be equal to 'nullptr'!\");\n assert((size > 0) && \"Chunk size should be greater than zero!\");\n assert((size <= _capacity) && \"Chunk size should not be greater than ring buffer capacity!\");\n\n if ((chunk == nullptr) || (size == 0) || (size > _capacity))\n return false;\n\n const size_t head = _head.load(std::memory_order_relaxed);\n const size_t tail = _tail.load(std::memory_order_acquire);\n\n \/\/ Check if there is required free space in the ring buffer\n if ((size + head - tail) > _capacity)\n return false;\n\n \/\/ Copy chunk of bytes into the ring buffer\n size_t head_index = head & _mask;\n size_t tail_index = tail & _mask;\n size_t remain = (tail_index > head_index) ? (tail_index - head_index) : (_capacity - head_index);\n size_t first = (size > remain) ? remain : size;\n size_t last = (size > remain) ? size - remain : 0;\n memcpy(&_buffer[head_index], (uint8_t*)chunk, first);\n memcpy(_buffer, (uint8_t*)chunk + first, last);\n\n \/\/ Increase the head cursor\n _head.store(head + size, std::memory_order_release);\n\n return true;\n}\n\ninline bool SPSCRingBuffer::Dequeue(void* chunk, size_t& size)\n{\n assert((chunk != nullptr) && \"Pointer to the chunk should not be equal to 'nullptr'!\");\n assert((size > 0) && \"Chunk size should be greater than zero!\");\n\n if ((chunk == nullptr) || (size == 0))\n return false;\n\n const size_t tail = _tail.load(std::memory_order_relaxed);\n const size_t head = _head.load(std::memory_order_acquire);\n\n \/\/ Get the ring buffer size\n size_t available = head - tail;\n if (size > available)\n size = available;\n\n \/\/ Check if the ring buffer is empty\n if (size == 0)\n return false;\n\n \/\/ Copy chunk of bytes from the ring buffer\n size_t head_index = head & _mask;\n size_t tail_index = tail & _mask;\n size_t remain = (head_index > tail_index) ? (head_index - tail_index) : (_capacity - tail_index);\n size_t first = (size > remain) ? remain : size;\n size_t last = (size > remain) ? size - remain : 0;\n memcpy((uint8_t*)chunk, &_buffer[tail_index], first);\n memcpy((uint8_t*)chunk + first, _buffer, last);\n\n \/\/ Increase the tail cursor\n _tail.store(tail + size, std::memory_order_release);\n\n return true;\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"zmsg_types.hpp\"\n#include \"zmsg_record_offset.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::shrinkage_test_start> {\npublic:\n\tfs_pattern_t FSPattern;\n\tUINT32 FibreType;\n\tUINT32 FibreAlignment;\n\tBOOL XImageFocus;\n\tBOOL YImageFocus;\n\tBOOL FibreShift;\n\tBOOL DischargeStrengthAdjustment;\n\tBOOL TensionSet;\n\tFLOAT CutAngleLimit;\n\tFLOAT LossLimit;\n\tFLOAT FibreAngleLimit;\n\tULONG CleanDischargeTime;\n\tULONG FibreIntervalSetup;\n\tLONG FSPosSetup;\n\tDOUBLE FibrePreFSStrength;\n\tULONG FibrePreFSTime;\n\tULONG FibreOverlapSetup;\n\tDOUBLE Discharge1Strength;\n\tULONG Discharge1Time;\n\tDOUBLE Discharge2Strength;\n\tULONG Discharge2LastTime;\n\tULONG Discharge2StartTime;\n\tULONG Discharge2StopTime;\n\tULONG ExtraManualDischargeTime;\n\n\tBOOL ConeFS;\n\tULONG ConeFSWaitTime;\n\tDOUBLE ConeFSSpeed;\n\tULONG ConeFSStretchLength;\n\tloss_estimate_mode_t LossEstimationMode;\n\tFLOAT LeftFibreMFD;\n\tFLOAT RightFibreMFD;\n\tFLOAT LeastLoss;\n\tFLOAT RateOfSyntropyBending;\n\tFLOAT RateOfReverseBending;\n\tFLOAT RateOfMFDDeviation;\n\n\tBOOL AutoStart;\n\tBOOL Stop1;\n\tBOOL Stop2;\n\t\/*data dispaly*\/\n\tBOOL CutAngle;\n\tBOOL OffsetData;\n\t\/*omitted choice*\/\n\tBOOL Cut;\n\tBOOL Loss;\n\tBOOL FibreCoreAngle;\n\tBOOL Bubble;\n\tBOOL Thick;\n\tBOOL Thin;\n\t\/*dischargesupplement*\/\n\tBOOL AirPressure;\n\tBOOL Temperature;\n\t\/*fiber_image_display*\/\n\tUINT32 ImgGap;\n\tUINT32 ImgStop1;\n\tUINT32 ImgAlign;\n\tUINT32 ImgStop2;\n\tUINT32 ImgDischarge;\n\tUINT32 ImgLossEstimation;\n\t\/*else*\/\n\tBOOL FibreAutoFeed;\n\tBOOL BadCutSurface;\n\tBOOL AutoAlignAfterStop;\n\tULONG ManualDischargeTimes;\npublic:\n\tZMSG_PU(\n\t\tFSPattern,\n\t\tFibreType,\n\t\tFibreAlignment,\n\t\tXImageFocus,\n\t\tYImageFocus,\n\t\tFibreShift,\n\t\tDischargeStrengthAdjustment,\n\t\tTensionSet,\n\t\tCutAngleLimit,\n\t\tLossLimit,\n\t\tFibreAngleLimit,\n\t\tCleanDischargeTime,\n\t\tFibreIntervalSetup,\n\t\tFSPosSetup,\n\t\tFibrePreFSStrength,\n\t\tFibrePreFSTime,\n\t\tFibreOverlapSetup,\n\t\tDischarge1Strength,\n\t\tDischarge1Time,\n\t\tDischarge2Strength,\n\t\tDischarge2LastTime,\n\t\tDischarge2StartTime,\n\t\tDischarge2StopTime,\n\t\tExtraManualDischargeTime,\n\n\t\tConeFS,\n\t\tConeFSWaitTime,\n\t\tConeFSSpeed,\n\t\tConeFSStretchLength,\n\t\tLossEstimationMode,\n\t\tLeftFibreMFD,\n\t\tRightFibreMFD,\n\t\tLeastLoss,\n\t\tRateOfSyntropyBending,\n\t\tRateOfReverseBending,\n\t\tRateOfMFDDeviation,\n\n\t\tAutoStart,\n\t\tStop1,\n\t\tStop2,\n\t\tCutAngle,\n\t\tOffsetData,\n\t\tCut,\n\t\tLoss,\n\t\tFibreCoreAngle,\n\t\tBubble,\n\t\tThick,\n\t\tThin,\n\t\tAirPressure,\n\t\tTemperature,\n\t\tImgGap,\n\t\tImgStop1,\n\t\tImgAlign,\n\t\tImgStop2,\n\t\tImgDischarge,\n\t\tImgLossEstimation,\n\t\tFibreAutoFeed,\n\t\tBadCutSurface,\n\t\tAutoAlignAfterStop,\n\t\tManualDischargeTimes)\n};\n\ntemplate<>\nstruct zmsg<mid_t::shrinkage_test_result> {\n\tfs_err_t code;\n\n\tzmsg<mid_t::shrinkage_test_start> z_cfg;\n\n\tfiber_rec_info_t rec_info;\n\n\timg_defects_t defect_data;\n\n\tzmsg<mid_t::record_off_set> z_record_offset;\n\n\tdouble shrinkage;\t\t\/\/\/ unit: um\npublic:\n\tZMSG_PU(code, z_cfg, rec_info, defect_data, z_record_offset, shrinkage)\n};\n\n}\n\n<commit_msg>zmsg: shrink_test_result: add real_gap<commit_after>#pragma once\n\n#include \"zmsg_types.hpp\"\n#include \"zmsg_record_offset.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::shrinkage_test_start> {\npublic:\n\tfs_pattern_t FSPattern;\n\tUINT32 FibreType;\n\tUINT32 FibreAlignment;\n\tBOOL XImageFocus;\n\tBOOL YImageFocus;\n\tBOOL FibreShift;\n\tBOOL DischargeStrengthAdjustment;\n\tBOOL TensionSet;\n\tFLOAT CutAngleLimit;\n\tFLOAT LossLimit;\n\tFLOAT FibreAngleLimit;\n\tULONG CleanDischargeTime;\n\tULONG FibreIntervalSetup;\n\tLONG FSPosSetup;\n\tDOUBLE FibrePreFSStrength;\n\tULONG FibrePreFSTime;\n\tULONG FibreOverlapSetup;\n\tDOUBLE Discharge1Strength;\n\tULONG Discharge1Time;\n\tDOUBLE Discharge2Strength;\n\tULONG Discharge2LastTime;\n\tULONG Discharge2StartTime;\n\tULONG Discharge2StopTime;\n\tULONG ExtraManualDischargeTime;\n\n\tBOOL ConeFS;\n\tULONG ConeFSWaitTime;\n\tDOUBLE ConeFSSpeed;\n\tULONG ConeFSStretchLength;\n\tloss_estimate_mode_t LossEstimationMode;\n\tFLOAT LeftFibreMFD;\n\tFLOAT RightFibreMFD;\n\tFLOAT LeastLoss;\n\tFLOAT RateOfSyntropyBending;\n\tFLOAT RateOfReverseBending;\n\tFLOAT RateOfMFDDeviation;\n\n\tBOOL AutoStart;\n\tBOOL Stop1;\n\tBOOL Stop2;\n\t\/*data dispaly*\/\n\tBOOL CutAngle;\n\tBOOL OffsetData;\n\t\/*omitted choice*\/\n\tBOOL Cut;\n\tBOOL Loss;\n\tBOOL FibreCoreAngle;\n\tBOOL Bubble;\n\tBOOL Thick;\n\tBOOL Thin;\n\t\/*dischargesupplement*\/\n\tBOOL AirPressure;\n\tBOOL Temperature;\n\t\/*fiber_image_display*\/\n\tUINT32 ImgGap;\n\tUINT32 ImgStop1;\n\tUINT32 ImgAlign;\n\tUINT32 ImgStop2;\n\tUINT32 ImgDischarge;\n\tUINT32 ImgLossEstimation;\n\t\/*else*\/\n\tBOOL FibreAutoFeed;\n\tBOOL BadCutSurface;\n\tBOOL AutoAlignAfterStop;\n\tULONG ManualDischargeTimes;\npublic:\n\tZMSG_PU(\n\t\tFSPattern,\n\t\tFibreType,\n\t\tFibreAlignment,\n\t\tXImageFocus,\n\t\tYImageFocus,\n\t\tFibreShift,\n\t\tDischargeStrengthAdjustment,\n\t\tTensionSet,\n\t\tCutAngleLimit,\n\t\tLossLimit,\n\t\tFibreAngleLimit,\n\t\tCleanDischargeTime,\n\t\tFibreIntervalSetup,\n\t\tFSPosSetup,\n\t\tFibrePreFSStrength,\n\t\tFibrePreFSTime,\n\t\tFibreOverlapSetup,\n\t\tDischarge1Strength,\n\t\tDischarge1Time,\n\t\tDischarge2Strength,\n\t\tDischarge2LastTime,\n\t\tDischarge2StartTime,\n\t\tDischarge2StopTime,\n\t\tExtraManualDischargeTime,\n\n\t\tConeFS,\n\t\tConeFSWaitTime,\n\t\tConeFSSpeed,\n\t\tConeFSStretchLength,\n\t\tLossEstimationMode,\n\t\tLeftFibreMFD,\n\t\tRightFibreMFD,\n\t\tLeastLoss,\n\t\tRateOfSyntropyBending,\n\t\tRateOfReverseBending,\n\t\tRateOfMFDDeviation,\n\n\t\tAutoStart,\n\t\tStop1,\n\t\tStop2,\n\t\tCutAngle,\n\t\tOffsetData,\n\t\tCut,\n\t\tLoss,\n\t\tFibreCoreAngle,\n\t\tBubble,\n\t\tThick,\n\t\tThin,\n\t\tAirPressure,\n\t\tTemperature,\n\t\tImgGap,\n\t\tImgStop1,\n\t\tImgAlign,\n\t\tImgStop2,\n\t\tImgDischarge,\n\t\tImgLossEstimation,\n\t\tFibreAutoFeed,\n\t\tBadCutSurface,\n\t\tAutoAlignAfterStop,\n\t\tManualDischargeTimes)\n};\n\ntemplate<>\nstruct zmsg<mid_t::shrinkage_test_result> {\n\tfs_err_t code;\n\n\tzmsg<mid_t::shrinkage_test_start> z_cfg;\n\n\tfiber_rec_info_t rec_info;\n\n\timg_defects_t defect_data;\n\n\tzmsg<mid_t::record_off_set> z_record_offset;\n\n\tdouble real_gap;\t\t\/\/\/ unit: um\n\tdouble shrinkage;\t\t\/\/\/ unit: um\npublic:\n\tZMSG_PU(code, z_cfg, rec_info, defect_data, z_record_offset, real_gap, shrinkage)\n};\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file llurlmatch_test.cpp\n * @author Martin Reddy\n * @brief Unit tests for LLUrlMatch\n *\n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * \n * Copyright (c) 2009, Linden Research, Inc.\n * \n * The following source code is PROPRIETARY AND CONFIDENTIAL. Use of\n * this source code is governed by the Linden Lab Source Code Disclosure\n * Agreement (\"Agreement\") previously entered between you and Linden\n * Lab. By accessing, using, copying, modifying or distributing this\n * software, you acknowledge that you have been informed of your\n * obligations under the Agreement and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"..\/llurlmatch.h\"\n#include \"lltut.h\"\n\n\/\/ link seams\n\nLLUIColor::LLUIColor()\n\t: mColorPtr(NULL)\n{}\n\nLLStyle::Params::Params()\n{\n}\n\nnamespace LLInitParam\n{\n\tBaseBlock::BaseBlock() {}\n\tBaseBlock::~BaseBlock() {}\n\n\tvoid BaseBlock::setLastChangedParam(const Param& last_param, bool user_provided) {}\n\n\tvoid BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptor& in_param, const char* char_name){}\n\tparam_handle_t BaseBlock::getHandleFromParam(const Param* param) const {return 0;}\n\t\n\tvoid BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size)\n\t{\n\t\tmBlockDescriptor = &descriptor;\n\t\tdescriptor.mCurrentBlockPtr = this;\n\t}\n\n\tParam::Param(BaseBlock* enclosing_block)\n\t:\tmIsProvided(false)\n\t{\n\t\tconst U8* my_addr = reinterpret_cast<const U8*>(this);\n\t\tconst U8* block_addr = reinterpret_cast<const U8*>(enclosing_block);\n\t\tmEnclosingBlockOffset = (U16)(my_addr - block_addr);\n\t}\n\n\tbool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack){ return true; }\n\tbool BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t name_stack, const LLInitParam::BaseBlock* diff_block) const { return true; }\n\tbool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack) const { return true; }\n\tbool BaseBlock::merge(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) { return true; }\n\tbool BaseBlock::validateBlock(bool emit_errors) const { return true; }\n\n\tTypedParam<LLUIColor >::TypedParam(BlockDescriptor& descriptor, const char* name, const LLUIColor& value, ParamDescriptor::validation_func_t func, S32 min_count, S32 max_count)\n\t:\tsuper_t(descriptor, name, value, func, min_count, max_count)\n\t{}\n\n\tvoid TypedParam<LLUIColor>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<LLUIColor>::setBlockFromValue()\n\t{}\n\n\tvoid TypeValues<LLUIColor>::declareValues()\n\t{}\n\n\tbool ParamCompare<const LLFontGL*, false>::equals(const LLFontGL* a, const LLFontGL* b)\n\t{\n\t\treturn false;\n\t}\n\n\tTypedParam<const LLFontGL*>::TypedParam(BlockDescriptor& descriptor, const char* _name, const LLFontGL*const value, ParamDescriptor::validation_func_t func, S32 min_count, S32 max_count)\n\t:\tsuper_t(descriptor, _name, value, func, min_count, max_count)\n\t{}\n\n\tvoid TypedParam<const LLFontGL*>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<const LLFontGL*>::setBlockFromValue()\n\t{}\n\n\tvoid TypeValues<LLFontGL::HAlign>::declareValues()\n\t{}\n\n\tvoid TypeValues<LLFontGL::VAlign>::declareValues()\n\t{}\n\n\tvoid TypeValues<LLFontGL::ShadowType>::declareValues()\n\t{}\n\n\tvoid TypedParam<LLUIImage*>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<LLUIImage*>::setBlockFromValue()\n\t{}\n\n\t\n\tbool ParamCompare<LLUIImage*, false>::equals(\n\t\tLLUIImage* const &a,\n\t\tLLUIImage* const &b)\n\t{\n\t\treturn false;\n\t}\n\n\tbool ParamCompare<LLUIColor, false>::equals(const LLUIColor &a, const LLUIColor &b)\n\t{\n\t\treturn false;\n\t}\n\n}\n\n\/\/static\nLLFontGL* LLFontGL::getFontDefault()\n{\n\treturn NULL; \n}\n\n\nnamespace tut\n{\n\tstruct LLUrlMatchData\n\t{\n\t};\n\n\ttypedef test_group<LLUrlMatchData> factory;\n\ttypedef factory::object object;\n}\n\nnamespace\n{\n\ttut::factory tf(\"LLUrlMatch\");\n}\n\nnamespace tut\n{\n\ttemplate<> template<>\n\tvoid object::test<1>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the empty() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"empty()\", match.empty());\n\n\t\tmatch.setValues(0, 1, \"http:\/\/secondlife.com\", \"Second Life\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"! empty()\", ! match.empty());\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<2>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getStart() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getStart() == 0\", match.getStart(), 0);\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getStart() == 10\", match.getStart(), 10);\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<3>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getEnd() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getEnd() == 0\", match.getEnd(), 0);\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getEnd() == 20\", match.getEnd(), 20);\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<4>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getUrl() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getUrl() == ''\", match.getUrl(), \"\");\n\n\t\tmatch.setValues(10, 20, \"http:\/\/slurl.com\/\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getUrl() == 'http:\/\/slurl.com\/'\", match.getUrl(), \"http:\/\/slurl.com\/\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getUrl() == '' (2)\", match.getUrl(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<5>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getLabel() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getLabel() == ''\", match.getLabel(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"Label\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getLabel() == 'Label'\", match.getLabel(), \"Label\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getLabel() == '' (2)\", match.getLabel(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<6>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getTooltip() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getTooltip() == ''\", match.getTooltip(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"Info\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getTooltip() == 'Info'\", match.getTooltip(), \"Info\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getTooltip() == '' (2)\", match.getTooltip(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<7>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getIcon() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getIcon() == ''\", match.getIcon(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getIcon() == 'Icon'\", match.getIcon(), \"Icon\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getIcon() == '' (2)\", match.getIcon(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<8>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getMenuName() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"getMenuName() empty\", match.getMenuName().empty());\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"xui_file.xml\", \"\", false);\n\t\tensure_equals(\"getMenuName() == \\\"xui_file.xml\\\"\", match.getMenuName(), \"xui_file.xml\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"getMenuName() empty (2)\", match.getMenuName().empty());\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<9>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getLocation() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"getLocation() empty\", match.getLocation().empty());\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"xui_file.xml\", \"Paris\", false);\n\t\tensure_equals(\"getLocation() == \\\"Paris\\\"\", match.getLocation(), \"Paris\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"getLocation() empty (2)\", match.getLocation().empty());\n\t}\n}\n<commit_msg>Fix broken Mac build on llurlmatch_test.cpp<commit_after>\/**\n * @file llurlmatch_test.cpp\n * @author Martin Reddy\n * @brief Unit tests for LLUrlMatch\n *\n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * \n * Copyright (c) 2009, Linden Research, Inc.\n * \n * The following source code is PROPRIETARY AND CONFIDENTIAL. Use of\n * this source code is governed by the Linden Lab Source Code Disclosure\n * Agreement (\"Agreement\") previously entered between you and Linden\n * Lab. By accessing, using, copying, modifying or distributing this\n * software, you acknowledge that you have been informed of your\n * obligations under the Agreement and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"..\/llurlmatch.h\"\n\/\/#include \"..\/lluiimage.h\"\n#include \"lltut.h\"\n\n\/\/ link seams\n\nLLUIColor::LLUIColor()\n\t: mColorPtr(NULL)\n{}\n\nLLStyle::Params::Params()\n{\n}\n\nLLUIImage::LLUIImage(const std::string& name, LLPointer<LLTexture> image)\n{\n}\n\nLLUIImage::~LLUIImage()\n{\n}\n\n\/\/virtual\nS32 LLUIImage::getWidth() const\n{\n\treturn 0;\n}\n\n\/\/virtual\nS32 LLUIImage::getHeight() const\n{\n\treturn 0;\n}\n\nnamespace LLInitParam\n{\n\tBaseBlock::BaseBlock() {}\n\tBaseBlock::~BaseBlock() {}\n\n\tvoid BaseBlock::setLastChangedParam(const Param& last_param, bool user_provided) {}\n\n\tvoid BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptor& in_param, const char* char_name){}\n\tparam_handle_t BaseBlock::getHandleFromParam(const Param* param) const {return 0;}\n\t\n\tvoid BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size)\n\t{\n\t\tmBlockDescriptor = &descriptor;\n\t\tdescriptor.mCurrentBlockPtr = this;\n\t}\n\n\tParam::Param(BaseBlock* enclosing_block)\n\t:\tmIsProvided(false)\n\t{\n\t\tconst U8* my_addr = reinterpret_cast<const U8*>(this);\n\t\tconst U8* block_addr = reinterpret_cast<const U8*>(enclosing_block);\n\t\tmEnclosingBlockOffset = (U16)(my_addr - block_addr);\n\t}\n\n\tbool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack){ return true; }\n\tbool BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t name_stack, const LLInitParam::BaseBlock* diff_block) const { return true; }\n\tbool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack) const { return true; }\n\tbool BaseBlock::merge(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) { return true; }\n\tbool BaseBlock::validateBlock(bool emit_errors) const { return true; }\n\n\tTypedParam<LLUIColor >::TypedParam(BlockDescriptor& descriptor, const char* name, const LLUIColor& value, ParamDescriptor::validation_func_t func, S32 min_count, S32 max_count)\n\t:\tsuper_t(descriptor, name, value, func, min_count, max_count)\n\t{}\n\n\tvoid TypedParam<LLUIColor>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<LLUIColor>::setBlockFromValue()\n\t{}\n\n\tvoid TypeValues<LLUIColor>::declareValues()\n\t{}\n\n\tbool ParamCompare<const LLFontGL*, false>::equals(const LLFontGL* a, const LLFontGL* b)\n\t{\n\t\treturn false;\n\t}\n\n\tTypedParam<const LLFontGL*>::TypedParam(BlockDescriptor& descriptor, const char* _name, const LLFontGL*const value, ParamDescriptor::validation_func_t func, S32 min_count, S32 max_count)\n\t:\tsuper_t(descriptor, _name, value, func, min_count, max_count)\n\t{}\n\n\tvoid TypedParam<const LLFontGL*>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<const LLFontGL*>::setBlockFromValue()\n\t{}\n\n\tvoid TypeValues<LLFontGL::HAlign>::declareValues()\n\t{}\n\n\tvoid TypeValues<LLFontGL::VAlign>::declareValues()\n\t{}\n\n\tvoid TypeValues<LLFontGL::ShadowType>::declareValues()\n\t{}\n\n\tvoid TypedParam<LLUIImage*>::setValueFromBlock() const\n\t{}\n\t\n\tvoid TypedParam<LLUIImage*>::setBlockFromValue()\n\t{}\n\t\n\tbool ParamCompare<LLUIImage*, false>::equals(\n\t\tLLUIImage* const &a,\n\t\tLLUIImage* const &b)\n\t{\n\t\treturn false;\n\t}\n\n\tbool ParamCompare<LLUIColor, false>::equals(const LLUIColor &a, const LLUIColor &b)\n\t{\n\t\treturn false;\n\t}\n\n}\n\n\/\/static\nLLFontGL* LLFontGL::getFontDefault()\n{\n\treturn NULL; \n}\n\n\nnamespace tut\n{\n\tstruct LLUrlMatchData\n\t{\n\t};\n\n\ttypedef test_group<LLUrlMatchData> factory;\n\ttypedef factory::object object;\n}\n\nnamespace\n{\n\ttut::factory tf(\"LLUrlMatch\");\n}\n\nnamespace tut\n{\n\ttemplate<> template<>\n\tvoid object::test<1>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the empty() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"empty()\", match.empty());\n\n\t\tmatch.setValues(0, 1, \"http:\/\/secondlife.com\", \"Second Life\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"! empty()\", ! match.empty());\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<2>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getStart() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getStart() == 0\", match.getStart(), 0);\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getStart() == 10\", match.getStart(), 10);\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<3>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getEnd() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getEnd() == 0\", match.getEnd(), 0);\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getEnd() == 20\", match.getEnd(), 20);\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<4>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getUrl() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getUrl() == ''\", match.getUrl(), \"\");\n\n\t\tmatch.setValues(10, 20, \"http:\/\/slurl.com\/\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getUrl() == 'http:\/\/slurl.com\/'\", match.getUrl(), \"http:\/\/slurl.com\/\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getUrl() == '' (2)\", match.getUrl(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<5>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getLabel() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getLabel() == ''\", match.getLabel(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"Label\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getLabel() == 'Label'\", match.getLabel(), \"Label\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getLabel() == '' (2)\", match.getLabel(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<6>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getTooltip() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getTooltip() == ''\", match.getTooltip(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"Info\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getTooltip() == 'Info'\", match.getTooltip(), \"Info\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getTooltip() == '' (2)\", match.getTooltip(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<7>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getIcon() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure_equals(\"getIcon() == ''\", match.getIcon(), \"\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getIcon() == 'Icon'\", match.getIcon(), \"Icon\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure_equals(\"getIcon() == '' (2)\", match.getIcon(), \"\");\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<8>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getMenuName() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"getMenuName() empty\", match.getMenuName().empty());\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"xui_file.xml\", \"\", false);\n\t\tensure_equals(\"getMenuName() == \\\"xui_file.xml\\\"\", match.getMenuName(), \"xui_file.xml\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"getMenuName() empty (2)\", match.getMenuName().empty());\n\t}\n\n\ttemplate<> template<>\n\tvoid object::test<9>()\n\t{\n\t\t\/\/\n\t\t\/\/ test the getLocation() method\n\t\t\/\/\n\t\tLLUrlMatch match;\n\t\tensure(\"getLocation() empty\", match.getLocation().empty());\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"Icon\", LLStyle::Params(), \"xui_file.xml\", \"Paris\", false);\n\t\tensure_equals(\"getLocation() == \\\"Paris\\\"\", match.getLocation(), \"Paris\");\n\n\t\tmatch.setValues(10, 20, \"\", \"\", \"\", \"\", LLStyle::Params(), \"\", \"\", false);\n\t\tensure(\"getLocation() empty (2)\", match.getLocation().empty());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fixed bug EXT-1768\t Unable to store landmark attached to notecard into Landmarks<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkCannySegmentationLevelSetImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkCannySegmentationLevelSetImageFilter.h\"\n\/\/#include \"itkImageFileWriter.h\"\n\/\/#include \"itkRawImageIO.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkCommand.h\"\n#include \"itkEventObject.h\"\n\n\nnamespace CSIFTN {\n\ntypedef itk::Image<float, 3> ImageType;\ntypedef itk::Image<char, 3> SeedImageType;\n\nconst int V_WIDTH = 64;\nconst int V_HEIGHT = 64;\nconst int V_DEPTH = 64;\n\nfloat sphere(float x, float y, float z)\n{\n float dis;\n dis = (x - (float)V_WIDTH\/2.0)*(x - (float)V_WIDTH\/2.0)\n \/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) + \n (y - (float)V_HEIGHT\/2.0)*(y - (float)V_HEIGHT\/2.0)\n \/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) + \n (z - (float)V_DEPTH\/2.0)*(z - (float)V_DEPTH\/2.0)\n \/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));\n return(1.0f-dis);\n}\n\nfloat sphere2(float x, float y, float z)\n{\n float dis;\n dis = (x - (float)V_WIDTH\/2.1)*(x - (float)V_WIDTH\/2.1)\n \/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) + \n (y - (float)V_HEIGHT\/2.0)*(y - (float)V_HEIGHT\/2.0)\n \/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) + \n (z - (float)V_DEPTH\/2.0)*(z - (float)V_DEPTH\/2.0)\n \/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));\n return(1.0f-dis);\n}\n\n\n \nvoid evaluate_float_function(itk::Image<float, 3> *im,\n float (*f)(float, float, float) )\n{\n itk::Image<float, 3>::IndexType idx;\n\n for(int z = 0; z < V_DEPTH; ++z)\n {\n idx[2] = z;\n for (int y = 0; y < V_HEIGHT; ++y)\n {\n idx[1] = y;\n for (int x = 0; x < V_WIDTH; ++x)\n {\n idx[0] = x;\n float val = f((float)x,(float)y,(float)z);\n \/\/im->SetPixel(idx, -1.0 * f((float)x,(float)y,(float)z));\n if ( val >= 0.0 )\n { im->SetPixel(idx, (64 - val)); }\n else\n { im->SetPixel(idx, 64 + val ); }\n }\n }\n }\n}\n\nvoid evaluate_function(itk::Image<char, 3> *im,\n float (*f)(float, float, float) )\n{\n itk::Image<char, 3>::IndexType idx;\n\n for(int z = 0; z < V_DEPTH; ++z)\n {\n idx[2] = z;\n for (int y = 0; y < V_HEIGHT; ++y)\n {\n idx[1] = y;\n for (int x = 0; x < V_WIDTH; ++x)\n {\n idx[0] = x;\n if ( f((float)x,(float)y,(float)z) >= 0.0 )\n { im->SetPixel(idx, 1 ); }\n else\n { im->SetPixel(idx, 0 ); }\n }\n }\n }\n}\n\n} \/\/ end namespace\n\n\nnamespace itk {\n\nclass RMSCommand : public Command\n{\npublic:\n \/** Smart pointer declaration methods *\/\n typedef RMSCommand Self;\n typedef Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkTypeMacro( RMSCommand, Command );\n itkNewMacro(Self);\n\n \/** Standard Command virtual methods *\/\n void Execute(Object *caller, const EventObject &)\n {\n std::cout <<\n (dynamic_cast<SparseFieldLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType> *>(caller))->GetRMSChange()\n << std::endl;\n std::cout <<\n (dynamic_cast<SegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType> *>(caller))->GetSegmentationFunction()->GetPropagationWeight()\n << std::endl;\n \n }\n void Execute(const Object *, const EventObject &)\n {\n std::cout << \"ack\" << std::endl;\n\n }\n\nprotected:\n RMSCommand() {}\n virtual ~RMSCommand() {}\n};\n\n}\n\n\nint itkCannySegmentationLevelSetImageFilterTest(int, char * [] )\n{\n std::cout << \"Last modified 11\/08\/02\" << std::endl;\n\n CSIFTN::ImageType::RegionType reg;\n CSIFTN::ImageType::RegionType::SizeType sz;\n CSIFTN::ImageType::RegionType::IndexType idx;\n idx[0] = idx[1] = idx[2] = 0;\n sz[0] = sz[1] = sz[2] = 64;\n reg.SetSize(sz);\n reg.SetIndex(idx);\n\n CSIFTN::ImageType::Pointer inputImage = CSIFTN::ImageType::New();\n CSIFTN::SeedImageType::Pointer seedImage = CSIFTN::SeedImageType::New();\n inputImage->SetRegions(reg);\n seedImage->SetRegions(reg);\n inputImage->Allocate();\n seedImage->Allocate();\n\n \/\/ Starting surface is a sphere in the center of the image.\n CSIFTN::evaluate_function(seedImage, CSIFTN::sphere);\n\n \/\/ Target surface is a sphere VERY NEAR to the starting surface.\n CSIFTN::evaluate_float_function(inputImage, CSIFTN::sphere2);\n \n itk::CannySegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType>::Pointer\n filter = itk::CannySegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType>::New();\n filter->SetInput(seedImage);\n filter->SetFeatureImage(inputImage);\n\n filter->SetMaximumRMSError(0.009);\n filter->SetMaximumIterations(10);\n \/\/ filter->SetUseNegativeFeaturesOn(); \/\/ Change the default behavior of the speed\n \/\/ function so that negative values result in\n \/\/ surface growth.\n \n itk::RMSCommand::Pointer c = itk::RMSCommand::New();\n filter->AddObserver(itk::IterationEvent(), c); \n filter->SetIsoSurfaceValue(0.5); \/\/<--- IMPORTANT! Default is zero.\n filter->SetPropagationScaling(0.5);\n filter->SetCurvatureScaling(1.0);\n filter->SetAdvectionScaling(1.0);\n filter->SetThreshold(10);\n filter->SetVariance(1.0);\n \n try {\n filter->Update();\n std::cout << \"Done first trial\" << std::endl;\n \/\/ Repeat to make sure that the filter is reinitialized properly\n filter->SetMaximumIterations(5);\n filter->Update();\n std::cout << \"Done second trial\" << std::endl;\n \n \/\/ Write the output for debugging purposes\n \/\/ itk::ImageFileWriter<CSIFTN::ImageType>::Pointer writer\n \/\/ = itk::ImageFileWriter<CSIFTN::ImageType>::New();\n \/\/ itk::RawImageIO<float, 3>::Pointer io = itk::RawImageIO<float, 3>::New();\n \/\/ io->SetFileTypeToBinary();\n \/\/ io->SetFileDimensionality(3);\n \/\/ io->SetByteOrderToLittleEndian();\n \/\/ writer->SetImageIO(io);\n \n \/\/ itk::CastImageFilter<CSIFTN::SeedImageType, CSIFTN::ImageType>::Pointer\n \/\/ caster = itk::CastImageFilter<CSIFTN::SeedImageType, CSIFTN::ImageType>::New();\n \/\/ caster->SetInput(seedImage);\n \/\/ caster->Update();\n \n \/\/ writer->SetInput(caster->GetOutput());\n \/\/ writer->SetInput(filter->GetSpeedImage());\n \/\/ writer->SetInput(filter->GetFeatureImage());\n \/\/ writer->SetInput(inputImage);\n \/\/ writer->SetInput(filter->GetOutput());\n \/\/ writer->SetFileName(\"featureimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(caster->GetOutput());\n \/\/ writer->SetFileName(\"seedimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(filter->GetOutput());\n \/\/ writer->SetFileName(\"outputimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(filter->GetSpeedImage());\n \/\/ writer->SetFileName(\"speedimage.raw\");\n \/\/ writer->Write();\n \n \n }\n catch (itk::ExceptionObject &e)\n {\n std::cerr << e << std::endl;\n }\n \n return 0;\n}\n<commit_msg>BUG: Fixed threshold parameter. Submitted by Bill Lorensen.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkCannySegmentationLevelSetImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkCannySegmentationLevelSetImageFilter.h\"\n\/\/#include \"itkImageFileWriter.h\"\n\/\/#include \"itkRawImageIO.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkCommand.h\"\n#include \"itkEventObject.h\"\n\n\nnamespace CSIFTN {\n\ntypedef itk::Image<float, 3> ImageType;\ntypedef itk::Image<char, 3> SeedImageType;\n\nconst int V_WIDTH = 64;\nconst int V_HEIGHT = 64;\nconst int V_DEPTH = 64;\n\nfloat sphere(float x, float y, float z)\n{\n float dis;\n dis = (x - (float)V_WIDTH\/2.0)*(x - (float)V_WIDTH\/2.0)\n \/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) + \n (y - (float)V_HEIGHT\/2.0)*(y - (float)V_HEIGHT\/2.0)\n \/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) + \n (z - (float)V_DEPTH\/2.0)*(z - (float)V_DEPTH\/2.0)\n \/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));\n return(1.0f-dis);\n}\n\nfloat sphere2(float x, float y, float z)\n{\n float dis;\n dis = (x - (float)V_WIDTH\/2.1)*(x - (float)V_WIDTH\/2.1)\n \/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) + \n (y - (float)V_HEIGHT\/2.0)*(y - (float)V_HEIGHT\/2.0)\n \/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) + \n (z - (float)V_DEPTH\/2.0)*(z - (float)V_DEPTH\/2.0)\n \/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));\n return(1.0f-dis);\n}\n\n\n \nvoid evaluate_float_function(itk::Image<float, 3> *im,\n float (*f)(float, float, float) )\n{\n itk::Image<float, 3>::IndexType idx;\n\n for(int z = 0; z < V_DEPTH; ++z)\n {\n idx[2] = z;\n for (int y = 0; y < V_HEIGHT; ++y)\n {\n idx[1] = y;\n for (int x = 0; x < V_WIDTH; ++x)\n {\n idx[0] = x;\n float val = f((float)x,(float)y,(float)z);\n \/\/im->SetPixel(idx, -1.0 * f((float)x,(float)y,(float)z));\n if ( val >= 0.0 )\n { im->SetPixel(idx, (64 - val)); }\n else\n { im->SetPixel(idx, 64 + val ); }\n }\n }\n }\n}\n\nvoid evaluate_function(itk::Image<char, 3> *im,\n float (*f)(float, float, float) )\n{\n itk::Image<char, 3>::IndexType idx;\n\n for(int z = 0; z < V_DEPTH; ++z)\n {\n idx[2] = z;\n for (int y = 0; y < V_HEIGHT; ++y)\n {\n idx[1] = y;\n for (int x = 0; x < V_WIDTH; ++x)\n {\n idx[0] = x;\n if ( f((float)x,(float)y,(float)z) >= 0.0 )\n { im->SetPixel(idx, 1 ); }\n else\n { im->SetPixel(idx, 0 ); }\n }\n }\n }\n}\n\n} \/\/ end namespace\n\n\nnamespace itk {\n\nclass RMSCommand : public Command\n{\npublic:\n \/** Smart pointer declaration methods *\/\n typedef RMSCommand Self;\n typedef Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkTypeMacro( RMSCommand, Command );\n itkNewMacro(Self);\n\n \/** Standard Command virtual methods *\/\n void Execute(Object *caller, const EventObject &)\n {\n std::cout <<\n (dynamic_cast<SparseFieldLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType> *>(caller))->GetRMSChange()\n << std::endl;\n std::cout <<\n (dynamic_cast<SegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType> *>(caller))->GetSegmentationFunction()->GetPropagationWeight()\n << std::endl;\n \n }\n void Execute(const Object *, const EventObject &)\n {\n std::cout << \"ack\" << std::endl;\n\n }\n\nprotected:\n RMSCommand() {}\n virtual ~RMSCommand() {}\n};\n\n}\n\n\nint itkCannySegmentationLevelSetImageFilterTest(int, char * [] )\n{\n std::cout << \"Last modified 11\/08\/02\" << std::endl;\n\n CSIFTN::ImageType::RegionType reg;\n CSIFTN::ImageType::RegionType::SizeType sz;\n CSIFTN::ImageType::RegionType::IndexType idx;\n idx[0] = idx[1] = idx[2] = 0;\n sz[0] = sz[1] = sz[2] = 64;\n reg.SetSize(sz);\n reg.SetIndex(idx);\n\n CSIFTN::ImageType::Pointer inputImage = CSIFTN::ImageType::New();\n CSIFTN::SeedImageType::Pointer seedImage = CSIFTN::SeedImageType::New();\n inputImage->SetRegions(reg);\n seedImage->SetRegions(reg);\n inputImage->Allocate();\n seedImage->Allocate();\n\n \/\/ Starting surface is a sphere in the center of the image.\n CSIFTN::evaluate_function(seedImage, CSIFTN::sphere);\n\n \/\/ Target surface is a sphere VERY NEAR to the starting surface.\n CSIFTN::evaluate_float_function(inputImage, CSIFTN::sphere2);\n \n itk::CannySegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType>::Pointer\n filter = itk::CannySegmentationLevelSetImageFilter< ::CSIFTN::SeedImageType, ::CSIFTN::ImageType>::New();\n filter->SetInput(seedImage);\n filter->SetFeatureImage(inputImage);\n\n filter->SetMaximumRMSError(0.009);\n filter->SetMaximumIterations(10);\n \/\/ filter->SetUseNegativeFeaturesOn(); \/\/ Change the default behavior of the speed\n \/\/ function so that negative values result in\n \/\/ surface growth.\n \n itk::RMSCommand::Pointer c = itk::RMSCommand::New();\n filter->AddObserver(itk::IterationEvent(), c); \n filter->SetIsoSurfaceValue(0.5); \/\/<--- IMPORTANT! Default is zero.\n filter->SetPropagationScaling(0.5);\n filter->SetCurvatureScaling(1.0);\n filter->SetAdvectionScaling(1.0);\n filter->SetThreshold(.4);\n filter->SetVariance(1.0);\n \n try {\n filter->Update();\n std::cout << \"Done first trial\" << std::endl;\n \/\/ Repeat to make sure that the filter is reinitialized properly\n filter->SetMaximumIterations(5);\n filter->Update();\n std::cout << \"Done second trial\" << std::endl;\n \n \/\/ Write the output for debugging purposes\n \/\/ itk::ImageFileWriter<CSIFTN::ImageType>::Pointer writer\n \/\/ = itk::ImageFileWriter<CSIFTN::ImageType>::New();\n \/\/ itk::RawImageIO<float, 3>::Pointer io = itk::RawImageIO<float, 3>::New();\n \/\/ io->SetFileTypeToBinary();\n \/\/ io->SetFileDimensionality(3);\n \/\/ io->SetByteOrderToLittleEndian();\n \/\/ writer->SetImageIO(io);\n \n \/\/ itk::CastImageFilter<CSIFTN::SeedImageType, CSIFTN::ImageType>::Pointer\n \/\/ caster = itk::CastImageFilter<CSIFTN::SeedImageType, CSIFTN::ImageType>::New();\n \/\/ caster->SetInput(seedImage);\n \/\/ caster->Update();\n \n \/\/ writer->SetInput(caster->GetOutput());\n \/\/ writer->SetInput(filter->GetSpeedImage());\n \/\/ writer->SetInput(filter->GetFeatureImage());\n \/\/ writer->SetInput(inputImage);\n \/\/ writer->SetInput(filter->GetOutput());\n \/\/ writer->SetFileName(\"featureimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(caster->GetOutput());\n \/\/ writer->SetFileName(\"seedimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(filter->GetOutput());\n \/\/ writer->SetFileName(\"outputimage.raw\");\n \/\/ writer->Write();\n\n \/\/ writer->SetInput(filter->GetSpeedImage());\n \/\/ writer->SetFileName(\"speedimage.raw\");\n \/\/ writer->Write();\n \n \n }\n catch (itk::ExceptionObject &e)\n {\n std::cerr << e << std::endl;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>shader_material_tiles_scene.cpp : correct issue in shader code<commit_after><|endoftext|>"} {"text":"<commit_before>\n#include <iostream>\n#include \"window.h\"\n#include \"application.h\"\n#include \"style.h\"\n#include <platform\/window.h>\n\nnamespace gui\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nwindow::window( const std::shared_ptr<platform::window> &w )\n\t: _window( w )\n{\n\tprecondition( bool(_window), \"null window\" );\n\t_window->exposed.callback( [=] { this->paint(); } );\n\t_window->resized.callback( [=]( double w, double h ) { this->resize( w, h ); } );\n\t_window->mouse_pressed.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p, int b ) { this->mouse_press( p, b ); } );\n\t_window->mouse_released.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p, int b ) { this->mouse_release( p, b ); } );\n\t_window->mouse_moved.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p ) { this->mouse_moved( p ); } );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nwindow::~window( void )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::set_title( const std::string &t )\n{\n\t_window->set_title( t );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::show( void )\n{\n\t_window->show();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::set_widget( const std::shared_ptr<widget> &w )\n{\n\t_widget = w;\n\t_widget->set_horizontal( 0.0, _window->width() - 1.0 );\n\t_widget->set_vertical( 0.0, _window->height() - 1.0 );\n\t_widget->set_minimum( _window->width(), _window->height() );\n\t_widget->set_delegate( this );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::invalidate( const draw::rect &r )\n{\n\t_window->invalidate( r );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::paint( void )\n{\n\tauto canvas = _window->canvas();\n\tauto style = application::current()->get_style();\n\tif ( style )\n\t\tstyle->background( canvas );\n\tif ( _widget )\n\t\t_widget->paint( canvas );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::resize( double w, double h )\n{\n\tif ( _widget )\n\t{\n\t\t_widget->set_horizontal( 0.0, w - 1.0 );\n\t\t_widget->set_vertical( 0.0, h - 1.0 );\n\t\t_widget->compute_layout();\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_press( const draw::point &p, int b )\n{\n\tif ( _widget )\n\t\t_widget->mouse_press( p, b );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_release( const draw::point &p, int b )\n{\n\tif ( _widget )\n\t\t_widget->mouse_release( p, b );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_moved( const draw::point &p )\n{\n\tif ( _widget )\n\t\t_widget->mouse_move( p );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n\n<commit_msg>Fixed bug with window never calling compute_minimum.<commit_after>\n#include <iostream>\n#include \"window.h\"\n#include \"application.h\"\n#include \"style.h\"\n#include <platform\/window.h>\n\nnamespace gui\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nwindow::window( const std::shared_ptr<platform::window> &w )\n\t: _window( w )\n{\n\tprecondition( bool(_window), \"null window\" );\n\t_window->exposed.callback( [=] { this->paint(); } );\n\t_window->resized.callback( [=]( double w, double h ) { this->resize( w, h ); } );\n\t_window->mouse_pressed.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p, int b ) { this->mouse_press( p, b ); } );\n\t_window->mouse_released.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p, int b ) { this->mouse_release( p, b ); } );\n\t_window->mouse_moved.callback( [=]( const std::shared_ptr<platform::mouse> &, const draw::point &p ) { this->mouse_moved( p ); } );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nwindow::~window( void )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::set_title( const std::string &t )\n{\n\t_window->set_title( t );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::show( void )\n{\n\t_window->show();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::set_widget( const std::shared_ptr<widget> &w )\n{\n\t_widget = w;\n\t_widget->set_horizontal( 0.0, _window->width() - 1.0 );\n\t_widget->set_vertical( 0.0, _window->height() - 1.0 );\n\t_widget->compute_minimum();\n\t_widget->set_delegate( this );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::invalidate( const draw::rect &r )\n{\n\t_window->invalidate( r );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::paint( void )\n{\n\tauto canvas = _window->canvas();\n\tauto style = application::current()->get_style();\n\tif ( style )\n\t\tstyle->background( canvas );\n\tif ( _widget )\n\t\t_widget->paint( canvas );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::resize( double w, double h )\n{\n\tif ( _widget )\n\t{\n\t\t_widget->set_horizontal( 0.0, w - 1.0 );\n\t\t_widget->set_vertical( 0.0, h - 1.0 );\n\t\t_widget->compute_layout();\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_press( const draw::point &p, int b )\n{\n\tif ( _widget )\n\t\t_widget->mouse_press( p, b );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_release( const draw::point &p, int b )\n{\n\tif ( _widget )\n\t\t_widget->mouse_release( p, b );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid window::mouse_moved( const draw::point &p )\n{\n\tif ( _widget )\n\t\t_widget->mouse_move( p );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===--------------------- Instruction.cpp ----------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines abstractions used by the Pipeline to model register reads,\n\/\/ register writes and instructions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MCA\/Instruction.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nnamespace llvm {\nnamespace mca {\n\nvoid ReadState::writeStartEvent(unsigned Cycles) {\n assert(DependentWrites);\n assert(CyclesLeft == UNKNOWN_CYCLES);\n\n \/\/ This read may be dependent on more than one write. This typically occurs\n \/\/ when a definition is the result of multiple writes where at least one\n \/\/ write does a partial register update.\n \/\/ The HW is forced to do some extra bookkeeping to track of all the\n \/\/ dependent writes, and implement a merging scheme for the partial writes.\n --DependentWrites;\n TotalCycles = std::max(TotalCycles, Cycles);\n\n if (!DependentWrites) {\n CyclesLeft = TotalCycles;\n IsReady = !CyclesLeft;\n }\n}\n\nvoid WriteState::onInstructionIssued() {\n assert(CyclesLeft == UNKNOWN_CYCLES);\n \/\/ Update the number of cycles left based on the WriteDescriptor info.\n CyclesLeft = getLatency();\n\n \/\/ Now that the time left before write-back is known, notify\n \/\/ all the users.\n for (const std::pair<ReadState *, int> &User : Users) {\n ReadState *RS = User.first;\n unsigned ReadCycles = std::max(0, CyclesLeft - User.second);\n RS->writeStartEvent(ReadCycles);\n }\n\n \/\/ Notify any writes that are in a false dependency with this write.\n if (PartialWrite)\n PartialWrite->writeStartEvent(CyclesLeft);\n}\n\nvoid WriteState::addUser(ReadState *User, int ReadAdvance) {\n \/\/ If CyclesLeft is different than -1, then we don't need to\n \/\/ update the list of users. We can just notify the user with\n \/\/ the actual number of cycles left (which may be zero).\n if (CyclesLeft != UNKNOWN_CYCLES) {\n unsigned ReadCycles = std::max(0, CyclesLeft - ReadAdvance);\n User->writeStartEvent(ReadCycles);\n return;\n }\n\n if (llvm::find_if(Users, [&User](const std::pair<ReadState *, int> &Use) {\n return Use.first == User;\n }) == Users.end()) {\n Users.emplace_back(User, ReadAdvance);\n }\n}\n\nvoid WriteState::addUser(WriteState *User) {\n if (CyclesLeft != UNKNOWN_CYCLES) {\n User->writeStartEvent(std::max(0, CyclesLeft));\n return;\n }\n\n assert(!PartialWrite && \"PartialWrite already set!\");\n PartialWrite = User;\n User->setDependentWrite(this);\n}\n\nvoid WriteState::cycleEvent() {\n \/\/ Note: CyclesLeft can be a negative number. It is an error to\n \/\/ make it an unsigned quantity because users of this write may\n \/\/ specify a negative ReadAdvance.\n if (CyclesLeft != UNKNOWN_CYCLES)\n CyclesLeft--;\n\n if (DependentWriteCyclesLeft)\n DependentWriteCyclesLeft--;\n}\n\nvoid ReadState::cycleEvent() {\n \/\/ Update the total number of cycles.\n if (DependentWrites && TotalCycles) {\n --TotalCycles;\n return;\n }\n\n \/\/ Bail out immediately if we don't know how many cycles are left.\n if (CyclesLeft == UNKNOWN_CYCLES)\n return;\n\n if (CyclesLeft) {\n --CyclesLeft;\n IsReady = !CyclesLeft;\n }\n}\n\n#ifndef NDEBUG\nvoid WriteState::dump() const {\n dbgs() << \"{ OpIdx=\" << WD->OpIndex << \", Lat=\" << getLatency() << \", RegID \"\n << getRegisterID() << \", Cycles Left=\" << getCyclesLeft() << \" }\";\n}\n\nvoid WriteRef::dump() const {\n dbgs() << \"IID=\" << getSourceIndex() << ' ';\n if (isValid())\n getWriteState()->dump();\n else\n dbgs() << \"(null)\";\n}\n#endif\n\nvoid Instruction::dispatch(unsigned RCUToken) {\n assert(Stage == IS_INVALID);\n Stage = IS_AVAILABLE;\n RCUTokenID = RCUToken;\n\n \/\/ Check if input operands are already available.\n update();\n}\n\nvoid Instruction::execute() {\n assert(Stage == IS_READY);\n Stage = IS_EXECUTING;\n\n \/\/ Set the cycles left before the write-back stage.\n CyclesLeft = getLatency();\n\n for (WriteState &WS : getDefs())\n WS.onInstructionIssued();\n\n \/\/ Transition to the \"executed\" stage if this is a zero-latency instruction.\n if (!CyclesLeft)\n Stage = IS_EXECUTED;\n}\n\nvoid Instruction::forceExecuted() {\n assert(Stage == IS_READY && \"Invalid internal state!\");\n CyclesLeft = 0;\n Stage = IS_EXECUTED;\n}\n\nvoid Instruction::update() {\n assert(isDispatched() && \"Unexpected instruction stage found!\");\n\n if (!all_of(getUses(), [](const ReadState &Use) { return Use.isReady(); }))\n return;\n\n \/\/ A partial register write cannot complete before a dependent write.\n auto IsDefReady = [&](const WriteState &Def) {\n if (!Def.getDependentWrite()) {\n unsigned CyclesLeft = Def.getDependentWriteCyclesLeft();\n return !CyclesLeft || CyclesLeft < getLatency();\n }\n return false;\n };\n\n if (all_of(getDefs(), IsDefReady))\n Stage = IS_READY;\n}\n\nvoid Instruction::cycleEvent() {\n if (isReady())\n return;\n\n if (isDispatched()) {\n for (ReadState &Use : getUses())\n Use.cycleEvent();\n\n for (WriteState &Def : getDefs())\n Def.cycleEvent();\n\n update();\n return;\n }\n\n assert(isExecuting() && \"Instruction not in-flight?\");\n assert(CyclesLeft && \"Instruction already executed?\");\n for (WriteState &Def : getDefs())\n Def.cycleEvent();\n CyclesLeft--;\n if (!CyclesLeft)\n Stage = IS_EXECUTED;\n}\n\nconst unsigned WriteRef::INVALID_IID = std::numeric_limits<unsigned>::max();\n\n} \/\/ namespace mca\n} \/\/ namespace llvm\n<commit_msg>[MCA] Simplify the logic in method WriteState::addUser. NFCI<commit_after>\/\/===--------------------- Instruction.cpp ----------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines abstractions used by the Pipeline to model register reads,\n\/\/ register writes and instructions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MCA\/Instruction.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nnamespace llvm {\nnamespace mca {\n\nvoid ReadState::writeStartEvent(unsigned Cycles) {\n assert(DependentWrites);\n assert(CyclesLeft == UNKNOWN_CYCLES);\n\n \/\/ This read may be dependent on more than one write. This typically occurs\n \/\/ when a definition is the result of multiple writes where at least one\n \/\/ write does a partial register update.\n \/\/ The HW is forced to do some extra bookkeeping to track of all the\n \/\/ dependent writes, and implement a merging scheme for the partial writes.\n --DependentWrites;\n TotalCycles = std::max(TotalCycles, Cycles);\n\n if (!DependentWrites) {\n CyclesLeft = TotalCycles;\n IsReady = !CyclesLeft;\n }\n}\n\nvoid WriteState::onInstructionIssued() {\n assert(CyclesLeft == UNKNOWN_CYCLES);\n \/\/ Update the number of cycles left based on the WriteDescriptor info.\n CyclesLeft = getLatency();\n\n \/\/ Now that the time left before write-back is known, notify\n \/\/ all the users.\n for (const std::pair<ReadState *, int> &User : Users) {\n ReadState *RS = User.first;\n unsigned ReadCycles = std::max(0, CyclesLeft - User.second);\n RS->writeStartEvent(ReadCycles);\n }\n\n \/\/ Notify any writes that are in a false dependency with this write.\n if (PartialWrite)\n PartialWrite->writeStartEvent(CyclesLeft);\n}\n\nvoid WriteState::addUser(ReadState *User, int ReadAdvance) {\n \/\/ If CyclesLeft is different than -1, then we don't need to\n \/\/ update the list of users. We can just notify the user with\n \/\/ the actual number of cycles left (which may be zero).\n if (CyclesLeft != UNKNOWN_CYCLES) {\n unsigned ReadCycles = std::max(0, CyclesLeft - ReadAdvance);\n User->writeStartEvent(ReadCycles);\n return;\n }\n\n Users.emplace_back(User, ReadAdvance);\n}\n\nvoid WriteState::addUser(WriteState *User) {\n if (CyclesLeft != UNKNOWN_CYCLES) {\n User->writeStartEvent(std::max(0, CyclesLeft));\n return;\n }\n\n assert(!PartialWrite && \"PartialWrite already set!\");\n PartialWrite = User;\n User->setDependentWrite(this);\n}\n\nvoid WriteState::cycleEvent() {\n \/\/ Note: CyclesLeft can be a negative number. It is an error to\n \/\/ make it an unsigned quantity because users of this write may\n \/\/ specify a negative ReadAdvance.\n if (CyclesLeft != UNKNOWN_CYCLES)\n CyclesLeft--;\n\n if (DependentWriteCyclesLeft)\n DependentWriteCyclesLeft--;\n}\n\nvoid ReadState::cycleEvent() {\n \/\/ Update the total number of cycles.\n if (DependentWrites && TotalCycles) {\n --TotalCycles;\n return;\n }\n\n \/\/ Bail out immediately if we don't know how many cycles are left.\n if (CyclesLeft == UNKNOWN_CYCLES)\n return;\n\n if (CyclesLeft) {\n --CyclesLeft;\n IsReady = !CyclesLeft;\n }\n}\n\n#ifndef NDEBUG\nvoid WriteState::dump() const {\n dbgs() << \"{ OpIdx=\" << WD->OpIndex << \", Lat=\" << getLatency() << \", RegID \"\n << getRegisterID() << \", Cycles Left=\" << getCyclesLeft() << \" }\";\n}\n\nvoid WriteRef::dump() const {\n dbgs() << \"IID=\" << getSourceIndex() << ' ';\n if (isValid())\n getWriteState()->dump();\n else\n dbgs() << \"(null)\";\n}\n#endif\n\nvoid Instruction::dispatch(unsigned RCUToken) {\n assert(Stage == IS_INVALID);\n Stage = IS_AVAILABLE;\n RCUTokenID = RCUToken;\n\n \/\/ Check if input operands are already available.\n update();\n}\n\nvoid Instruction::execute() {\n assert(Stage == IS_READY);\n Stage = IS_EXECUTING;\n\n \/\/ Set the cycles left before the write-back stage.\n CyclesLeft = getLatency();\n\n for (WriteState &WS : getDefs())\n WS.onInstructionIssued();\n\n \/\/ Transition to the \"executed\" stage if this is a zero-latency instruction.\n if (!CyclesLeft)\n Stage = IS_EXECUTED;\n}\n\nvoid Instruction::forceExecuted() {\n assert(Stage == IS_READY && \"Invalid internal state!\");\n CyclesLeft = 0;\n Stage = IS_EXECUTED;\n}\n\nvoid Instruction::update() {\n assert(isDispatched() && \"Unexpected instruction stage found!\");\n\n if (!all_of(getUses(), [](const ReadState &Use) { return Use.isReady(); }))\n return;\n\n \/\/ A partial register write cannot complete before a dependent write.\n auto IsDefReady = [&](const WriteState &Def) {\n if (!Def.getDependentWrite()) {\n unsigned CyclesLeft = Def.getDependentWriteCyclesLeft();\n return !CyclesLeft || CyclesLeft < getLatency();\n }\n return false;\n };\n\n if (all_of(getDefs(), IsDefReady))\n Stage = IS_READY;\n}\n\nvoid Instruction::cycleEvent() {\n if (isReady())\n return;\n\n if (isDispatched()) {\n for (ReadState &Use : getUses())\n Use.cycleEvent();\n\n for (WriteState &Def : getDefs())\n Def.cycleEvent();\n\n update();\n return;\n }\n\n assert(isExecuting() && \"Instruction not in-flight?\");\n assert(CyclesLeft && \"Instruction already executed?\");\n for (WriteState &Def : getDefs())\n Def.cycleEvent();\n CyclesLeft--;\n if (!CyclesLeft)\n Stage = IS_EXECUTED;\n}\n\nconst unsigned WriteRef::INVALID_IID = std::numeric_limits<unsigned>::max();\n\n} \/\/ namespace mca\n} \/\/ namespace llvm\n<|endoftext|>"} {"text":"<commit_before>#include \"io_utar.h\"\n#include \"logger.h\"\n#include <fstream>\n#include <cmath>\n#include <cstdint>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/iostreams\/filter\/bzip2.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/array.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nnamespace ncv\n{\n \/\/ http:\/\/techoverflow.net\/blog\/2013\/03\/29\/reading-tar-files-in-c\/\n\n namespace\n {\n using std::int64_t;\n using std::uint64_t;\n\n \/\/\/\n \/\/\/ \\brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit)\n \/\/\/\n uint64_t ascii_to_number(unsigned char num)\n {\n return ((num) - 48);\n }\n\n \/\/\/\n \/\/\/ \\brief decode a TAR octal number. ignores everything after the first NUL or space character.\n \/\/\/\n uint64_t decode_tar_octal(const char* data, size_t size = 12)\n {\n const unsigned char* currentPtr = (const unsigned char*)data + size;\n\n const unsigned char* checkPtr = currentPtr;\n for (; checkPtr >= (const unsigned char*) data; checkPtr --)\n {\n if ((*checkPtr) == 0 || (*checkPtr) == ' ')\n {\n currentPtr = checkPtr - 1;\n }\n }\n\n uint64_t sum = 0;\n uint64_t currentMultiplier = 1;\n for (; currentPtr >= (const unsigned char*)data; currentPtr --)\n {\n sum += ascii_to_number(*currentPtr) * currentMultiplier;\n currentMultiplier *= 8;\n }\n\n return sum;\n }\n\n struct TARFileHeader\n {\n char filename[100];\n char mode[8];\n char uid[8];\n char gid[8];\n char fileSize[12];\n char lastModification[12];\n char checksum[8];\n char typeFlag;\n char linkedFileName[100];\n char ustarIndicator[6];\n char ustarVersion[2];\n char ownerUserName[32];\n char ownerGroupName[32];\n char deviceMajorNumber[8];\n char deviceMinorNumber[8];\n char filenamePrefix[155];\n char padding[12];\n\n size_t filesize() const\n {\n return decode_tar_octal(fileSize);\n }\n };\n }\n\n namespace\n {\n bool io_untar(\n boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n char zeroBlock[512];\n memset(zeroBlock, 0, 512);\n\n bool nextEntryHasLongName = false;\n while (in)\n {\n TARFileHeader header;\n in.read((char*)&header, 512);\n if (memcmp(&header, zeroBlock, 512) == 0)\n {\n log_info() << info_header << \"found TAR end.\";\n break;\n }\n\n \/\/ compose the filename\n std::string filename(header.filename, std::min((size_t)100, strlen(header.filename)));\n const size_t prefixLength = strlen(header.filenamePrefix);\n if (prefixLength > 0)\n {\n filename =\n std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) +\n \"\/\" +\n filename;\n }\n\n if (header.typeFlag == '0' || header.typeFlag == 0)\n {\n \/\/ handle GNU TAR long filenames\n if (nextEntryHasLongName)\n {\n filename = std::string(header.filename);\n in.read((char*) &header, 512);\n nextEntryHasLongName = false;\n }\n\n const size_t size = header.filesize();\n log_info() << info_header << \"found file <\" << filename << \"> (\" << size << \" bytes).\";\n\n \/\/Read the file into memory\n \/\/ This won't work for very large files -- use streaming methods there!\n {\n std::vector<unsigned char> filedata(size);\n\n char* const pdata = reinterpret_cast<char*>(filedata.data());\n in.read(pdata, size);\n\n \/\/ decode archive type\n if (boost::algorithm::iends_with(filename, \".gz\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::gzip_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".bz2\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::bzip2_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar\"))\n {\n \/\/ no decompression filter needed\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else\n {\n callback(filename, filedata);\n }\n }\n\n \/\/ ignore padding\n const size_t paddingBytes = (512 - (size % 512)) % 512;\n in.ignore(paddingBytes);\n }\n\n else if (header.typeFlag == '5')\n {\n log_info() << info_header << \"found directory <\" << filename << \">.\";\n }\n\n else if(header.typeFlag == 'L')\n {\n nextEntryHasLongName = true;\n }\n\n else\n {\n log_info() << info_header << \"found unhandled TAR entry type <\" << header.typeFlag << \">.\";\n }\n }\n\n \/\/ OK\n return true;\n }\n }\n\n bool io::untar(\n const std::string& path, const untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary);\n if (!fin.is_open())\n {\n log_error() << error_header << \"failed to open file <\" << path << \">!\";\n return false;\n }\n\n boost::iostreams::filtering_istream in;\n\n \/\/ decode archive type\n if (boost::algorithm::iends_with(path, \".gz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".bz2\"))\n {\n in.push(boost::iostreams::bzip2_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar\"))\n {\n \/\/ no decompression filter needed\n }\n else\n {\n log_error() << error_header << \"unknown file suffix <\" << path << \">!\";\n return false;\n }\n\n in.push(fin);\n\n return io_untar(in, callback, info_header, error_header);\n }\n}\n<commit_msg>handle .gz differently from .tar<commit_after>#include \"io_utar.h\"\n#include \"logger.h\"\n#include <fstream>\n#include <cmath>\n#include <cstdint>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/iostreams\/filter\/bzip2.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/array.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nnamespace ncv\n{\n \/\/ http:\/\/techoverflow.net\/blog\/2013\/03\/29\/reading-tar-files-in-c\/\n\n namespace\n {\n using std::int64_t;\n using std::uint64_t;\n\n \/\/\/\n \/\/\/ \\brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit)\n \/\/\/\n uint64_t ascii_to_number(unsigned char num)\n {\n return ((num) - 48);\n }\n\n \/\/\/\n \/\/\/ \\brief decode a TAR octal number. ignores everything after the first NUL or space character.\n \/\/\/\n uint64_t decode_tar_octal(const char* data, size_t size = 12)\n {\n const unsigned char* currentPtr = (const unsigned char*)data + size;\n\n const unsigned char* checkPtr = currentPtr;\n for (; checkPtr >= (const unsigned char*) data; checkPtr --)\n {\n if ((*checkPtr) == 0 || (*checkPtr) == ' ')\n {\n currentPtr = checkPtr - 1;\n }\n }\n\n uint64_t sum = 0;\n uint64_t currentMultiplier = 1;\n for (; currentPtr >= (const unsigned char*)data; currentPtr --)\n {\n sum += ascii_to_number(*currentPtr) * currentMultiplier;\n currentMultiplier *= 8;\n }\n\n return sum;\n }\n\n struct TARFileHeader\n {\n char filename[100];\n char mode[8];\n char uid[8];\n char gid[8];\n char fileSize[12];\n char lastModification[12];\n char checksum[8];\n char typeFlag;\n char linkedFileName[100];\n char ustarIndicator[6];\n char ustarVersion[2];\n char ownerUserName[32];\n char ownerGroupName[32];\n char deviceMajorNumber[8];\n char deviceMinorNumber[8];\n char filenamePrefix[155];\n char padding[12];\n\n size_t filesize() const\n {\n return decode_tar_octal(fileSize);\n }\n };\n }\n\n namespace\n {\n bool io_untar(\n boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n char zeroBlock[512];\n memset(zeroBlock, 0, 512);\n\n bool nextEntryHasLongName = false;\n while (in)\n {\n TARFileHeader header;\n in.read((char*)&header, 512);\n if (memcmp(&header, zeroBlock, 512) == 0)\n {\n log_info() << info_header << \"found TAR end.\";\n break;\n }\n\n \/\/ compose the filename\n std::string filename(header.filename, std::min((size_t)100, strlen(header.filename)));\n const size_t prefixLength = strlen(header.filenamePrefix);\n if (prefixLength > 0)\n {\n filename =\n std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) +\n \"\/\" +\n filename;\n }\n\n if (header.typeFlag == '0' || header.typeFlag == 0)\n {\n \/\/ handle GNU TAR long filenames\n if (nextEntryHasLongName)\n {\n filename = std::string(header.filename);\n in.read((char*) &header, 512);\n nextEntryHasLongName = false;\n }\n\n const size_t size = header.filesize();\n log_info() << info_header << \"found file <\" << filename << \"> (\" << size << \" bytes).\";\n\n \/\/Read the file into memory\n \/\/ This won't work for very large files -- use streaming methods there!\n {\n std::vector<unsigned char> filedata(size);\n\n char* const pdata = reinterpret_cast<char*>(filedata.data());\n in.read(pdata, size);\n\n \/\/ decode archive type\n if (boost::algorithm::iends_with(filename, \".gz\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::gzip_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".bz2\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::bzip2_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar\"))\n {\n \/\/ no decompression filter needed\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else\n {\n callback(filename, filedata);\n }\n }\n\n \/\/ ignore padding\n const size_t paddingBytes = (512 - (size % 512)) % 512;\n in.ignore(paddingBytes);\n }\n\n else if (header.typeFlag == '5')\n {\n log_info() << info_header << \"found directory <\" << filename << \">.\";\n }\n\n else if(header.typeFlag == 'L')\n {\n nextEntryHasLongName = true;\n }\n\n else\n {\n log_info() << info_header << \"found unhandled TAR entry type <\" << header.typeFlag << \">.\";\n }\n }\n\n \/\/ OK\n return true;\n }\n }\n\n bool io::untar(\n const std::string& path, const untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary);\n if (!fin.is_open())\n {\n log_error() << error_header << \"failed to open file <\" << path << \">!\";\n return false;\n }\n\n boost::iostreams::filtering_istream in;\n\n \/\/ decode archive type\n if (boost::algorithm::iends_with(path, \".tar.gz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar.bz2\"))\n {\n in.push(boost::iostreams::bzip2_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar\"))\n {\n \/\/ no decompression filter needed\n }\n else if (boost::algorithm::iends_with(path, \".gz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n in.push(fin);\n\n std::vector<unsigned char> filedata;\n\n const size_t chunk = 4096;\n char data[chunk];\n\n std::streamsize read_size;\n while ((read_size = boost::iostreams::read(in, data, chunk)) > 0)\n {\n filedata.insert(filedata.end(),\n reinterpret_cast<const unsigned char*>(data),\n reinterpret_cast<const unsigned char*>(data) + read_size);\n }\n\n callback(path, filedata);\n return true;\n }\n else\n {\n log_error() << error_header << \"unknown file suffix <\" << path << \">!\";\n return false;\n }\n\n in.push(fin);\n\n return io_untar(in, callback, info_header, error_header);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DataBaseWriter.h\"\n#include \"sqlite3.h\"\n#include \"DBWrapper.h\"\n\nvoid CreateTables(DBWrapper &db)\n{\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_FUNCTION_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_MAP_INFO_TABLE_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_MAP_INFO_TABLE_SRCBLOCK_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_FILE_INFO_TABLE_STATEMENT);\n}\n\nint DatabaseWriterWrapper(DBWrapper *db,BYTE Type,PBYTE Data,DWORD Length)\n{\n\tstatic int FileID=0;\n\tbool Status=FALSE;\n\tstatic DWORD CurrentAddress=0L;\n\n\tswitch(Type)\n\t{\n\t\tcase ONE_LOCATION_INFO:\n\t\t\tif(sizeof(OneLocationInfo)<=Length)\n\t\t\t{\n\t\t\t\tPOneLocationInfo pOneLocationInfo=(POneLocationInfo)Data;\n\t\t\t\tchar *FingerprintHexStringBuffer=NULL;\n\t\t\t\tif(pOneLocationInfo->FingerprintLen>0)\n\t\t\t\t{\n\t\t\t\t\tFingerprintHexStringBuffer=(char *)malloc(pOneLocationInfo->FingerprintLen*2+10);\n\t\t\t\t\tif(FingerprintHexStringBuffer)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemset(FingerprintHexStringBuffer,0,pOneLocationInfo->FingerprintLen*2+10);\n\t\t\t\t\t\tchar tmp_buffer[10];\n\t\t\t\t\t\tfor(DWORD i=0;i<pOneLocationInfo->FingerprintLen;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_snprintf(tmp_buffer,sizeof(tmp_buffer)-1,\"%.2x\",pOneLocationInfo->Data[pOneLocationInfo->NameLen+pOneLocationInfo->DisasmLinesLen+i]&0xff);\n\t\t\t\t\t\t\ttmp_buffer[sizeof(tmp_buffer)-1]=NULL;\n\t\t\t\t\t\t\tstrncat(FingerprintHexStringBuffer,tmp_buffer,sizeof(tmp_buffer));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tCurrentAddress=pOneLocationInfo->StartAddress;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_ONE_LOCATION_INFO_TABLE_STATEMENT,\n\t\t\t\t\tFileID,\n\t\t\t\t\tpOneLocationInfo->StartAddress,\n\t\t\t\t\tpOneLocationInfo->EndAddress,\n\t\t\t\t\tpOneLocationInfo->Flag,\n\t\t\t\t\tpOneLocationInfo->FunctionAddress,\n\t\t\t\t\tpOneLocationInfo->BlockType,\n\t\t\t\t\tpOneLocationInfo->Data,\n\t\t\t\t\tpOneLocationInfo->Data+pOneLocationInfo->NameLen,\n\t\t\t\t\tFingerprintHexStringBuffer?FingerprintHexStringBuffer:\"\"\n\t\t\t\t\t);\n\t\t\t\tif(FingerprintHexStringBuffer)\n\t\t\t\t\tfree(FingerprintHexStringBuffer);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase MAP_INFO:\n\t\t\tif(sizeof(MapInfo)<=Length)\n\t\t\t{\n\t\t\t\tPMapInfo pMapInfo=(PMapInfo)Data;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_MAP_INFO_TABLE_STATEMENT,\n\t\t\t\t\tFileID,\n\t\t\t\t\tpMapInfo->Type,\n\t\t\t\t\tpMapInfo->SrcBlock,\n\t\t\t\t\tpMapInfo->SrcBlockEnd,\n\t\t\t\t\tpMapInfo->Dst\n\t\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase FILE_INFO:\n\t\t\tif(sizeof(FileInfo)<=Length)\n\t\t\t{\n\t\t\t\tPFileInfo pFileInfo=(PFileInfo)Data;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_FILE_INFO_TABLE_STATEMENT,\n\t\t\t\t\tpFileInfo->OriginalFilePath,\n\t\t\t\t\tpFileInfo->ComputerName,\n\t\t\t\t\tpFileInfo->UserName,\n\t\t\t\t\tpFileInfo->CompanyName,\n\t\t\t\t\tpFileInfo->FileVersion,\n\t\t\t\t\tpFileInfo->FileDescription,\n\t\t\t\t\tpFileInfo->InternalName,\n\t\t\t\t\tpFileInfo->ProductName,\n\t\t\t\t\tpFileInfo->ModifiedTime,\n\t\t\t\t\tpFileInfo->MD5Sum\n\t\t\t\t\t);\n\t\t\t\tFileID=db->GetLastInsertRowID();\n\t\t\t}\n\t\t\tbreak;\n\t}\n\tStatus=TRUE;\n\treturn FileID;\n}\n\n<commit_msg>Put new lines in code for readability<commit_after>#include \"DataBaseWriter.h\"\n#include \"sqlite3.h\"\n#include \"DBWrapper.h\"\n\nvoid CreateTables(DBWrapper &db)\n{\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_FUNCTION_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_MAP_INFO_TABLE_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_MAP_INFO_TABLE_SRCBLOCK_INDEX_STATEMENT);\n\tdb.ExecuteStatement(NULL, NULL, CREATE_FILE_INFO_TABLE_STATEMENT);\n}\n\nint DatabaseWriterWrapper(DBWrapper *db,BYTE Type,PBYTE Data,DWORD Length)\n{\n\tstatic int FileID=0;\n\tbool Status=FALSE;\n\tstatic DWORD CurrentAddress=0L;\n\n\tswitch(Type)\n\t{\n\t\tcase ONE_LOCATION_INFO:\n\t\t\tif(sizeof(OneLocationInfo)<=Length)\n\t\t\t{\n\t\t\t\tPOneLocationInfo pOneLocationInfo=(POneLocationInfo)Data;\n\t\t\t\tchar *FingerprintHexStringBuffer=NULL;\n\t\t\t\tif(pOneLocationInfo->FingerprintLen>0)\n\t\t\t\t{\n\t\t\t\t\tFingerprintHexStringBuffer=(char *)malloc(pOneLocationInfo->FingerprintLen*2+10);\n\t\t\t\t\tif(FingerprintHexStringBuffer)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemset(FingerprintHexStringBuffer,0,pOneLocationInfo->FingerprintLen*2+10);\n\t\t\t\t\t\tchar tmp_buffer[10];\n\t\t\t\t\t\tfor(DWORD i=0;i<pOneLocationInfo->FingerprintLen;i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_snprintf(tmp_buffer,sizeof(tmp_buffer)-1,\"%.2x\",pOneLocationInfo->Data[pOneLocationInfo->NameLen+pOneLocationInfo->DisasmLinesLen+i]&0xff);\n\t\t\t\t\t\t\ttmp_buffer[sizeof(tmp_buffer)-1]=NULL;\n\t\t\t\t\t\t\tstrncat(FingerprintHexStringBuffer,tmp_buffer,sizeof(tmp_buffer));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tCurrentAddress=pOneLocationInfo->StartAddress;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_ONE_LOCATION_INFO_TABLE_STATEMENT,\n\t\t\t\t\tFileID,\n\t\t\t\t\tpOneLocationInfo->StartAddress,\n\t\t\t\t\tpOneLocationInfo->EndAddress,\n\t\t\t\t\tpOneLocationInfo->Flag,\n\t\t\t\t\tpOneLocationInfo->FunctionAddress,\n\t\t\t\t\tpOneLocationInfo->BlockType,\n\t\t\t\t\tpOneLocationInfo->Data,\n\t\t\t\t\tpOneLocationInfo->Data+pOneLocationInfo->NameLen,\n\t\t\t\t\tFingerprintHexStringBuffer?FingerprintHexStringBuffer:\"\"\n\t\t\t\t\t);\n\n\t\t\t\tif(FingerprintHexStringBuffer)\n\t\t\t\t\tfree(FingerprintHexStringBuffer);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MAP_INFO:\n\t\t\tif(sizeof(MapInfo)<=Length)\n\t\t\t{\n\t\t\t\tPMapInfo pMapInfo=(PMapInfo)Data;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_MAP_INFO_TABLE_STATEMENT,\n\t\t\t\t\tFileID,\n\t\t\t\t\tpMapInfo->Type,\n\t\t\t\t\tpMapInfo->SrcBlock,\n\t\t\t\t\tpMapInfo->SrcBlockEnd,\n\t\t\t\t\tpMapInfo->Dst\n\t\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FILE_INFO:\n\t\t\tif(sizeof(FileInfo)<=Length)\n\t\t\t{\n\t\t\t\tPFileInfo pFileInfo=(PFileInfo)Data;\n\t\t\t\tStatus=db->ExecuteStatement(NULL,NULL,INSERT_FILE_INFO_TABLE_STATEMENT,\n\t\t\t\t\tpFileInfo->OriginalFilePath,\n\t\t\t\t\tpFileInfo->ComputerName,\n\t\t\t\t\tpFileInfo->UserName,\n\t\t\t\t\tpFileInfo->CompanyName,\n\t\t\t\t\tpFileInfo->FileVersion,\n\t\t\t\t\tpFileInfo->FileDescription,\n\t\t\t\t\tpFileInfo->InternalName,\n\t\t\t\t\tpFileInfo->ProductName,\n\t\t\t\t\tpFileInfo->ModifiedTime,\n\t\t\t\t\tpFileInfo->MD5Sum\n\t\t\t\t\t);\n\t\t\t\tFileID=db->GetLastInsertRowID();\n\t\t\t}\n\t\t\tbreak;\n\n\t}\n\tStatus=TRUE;\n\treturn FileID;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: smplmailsuppl.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:10:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SMPLMAILSUPPL_HXX_\n#define _SMPLMAILSUPPL_HXX_\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_SYS_SHELL_XSYSTEMSHELLEXECUTE_HPP_\n#include <com\/sun\/star\/system\/XSimpleMailClientSupplier.hpp>\n#endif\n\n#ifndef _SIMPLEMAPI_HXX_\n#include \"simplemapi.hxx\"\n#endif\n\n\nclass CSmplMailSupplBase\n{\nprotected:\n osl::Mutex m_aMutex;\n};\n\nclass CSmplMailSuppl :\n public CSmplMailSupplBase,\n public cppu::WeakComponentImplHelper2<\n com::sun::star::system::XSimpleMailClientSupplier,\n com::sun::star::lang::XServiceInfo >\n{\npublic:\n CSmplMailSuppl( );\n ~CSmplMailSuppl( );\n\n \/\/ XSimpleMailClientSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::system::XSimpleMailClient > SAL_CALL querySimpleMailClient( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw(::com::sun::star::uno::RuntimeException);\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.216); FILE MERGED 2008\/04\/01 15:40:28 thb 1.3.216.3: #i85898# Stripping all external header guards 2008\/04\/01 12:41:17 thb 1.3.216.2: #i85898# Stripping all external header guards 2008\/03\/31 13:17:15 rt 1.3.216.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: smplmailsuppl.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SMPLMAILSUPPL_HXX_\n#define _SMPLMAILSUPPL_HXX_\n\n#include <cppuhelper\/compbase2.hxx>\n#include <osl\/mutex.hxx>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n\n#ifndef _COM_SUN_STAR_SYS_SHELL_XSYSTEMSHELLEXECUTE_HPP_\n#include <com\/sun\/star\/system\/XSimpleMailClientSupplier.hpp>\n#endif\n\n#ifndef _SIMPLEMAPI_HXX_\n#include \"simplemapi.hxx\"\n#endif\n\n\nclass CSmplMailSupplBase\n{\nprotected:\n osl::Mutex m_aMutex;\n};\n\nclass CSmplMailSuppl :\n public CSmplMailSupplBase,\n public cppu::WeakComponentImplHelper2<\n com::sun::star::system::XSimpleMailClientSupplier,\n com::sun::star::lang::XServiceInfo >\n{\npublic:\n CSmplMailSuppl( );\n ~CSmplMailSuppl( );\n\n \/\/ XSimpleMailClientSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::system::XSimpleMailClient > SAL_CALL querySimpleMailClient( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw(::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )\n throw(::com::sun::star::uno::RuntimeException);\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef JARNGREIPR_CLEMENTI_GO\n#define JARNGREIPR_CLEMENTI_GO\n#include <jarngreipr\/forcefield\/ForceFieldGenerator.hpp>\n#include <jarngreipr\/geometry\/distance.hpp>\n#include <jarngreipr\/geometry\/angle.hpp>\n#include <jarngreipr\/geometry\/dihedral.hpp>\n#include <iterator>\n#include <iostream>\n#include <vector>\n\nnamespace jarngreipr\n{\n\ntemplate<typename realT>\nclass ClementiGo final : public IntraChainForceFieldGenerator<realT>\n{\n public:\n typedef IntraChainForceFieldGenerator<realT> base_type;\n typedef typename base_type::real_type real_type;\n typedef typename base_type::bead_type bead_type;\n\n public:\n\n ClementiGo()\n : contact_threshold_(6.5), k_bond_length_(100.0), k_bond_angle_(20.0),\n k_dihedral_angle_1_(1.0), k_dihedral_angle_3_(0.5), k_intra_go_(0.3)\n {}\n ~ClementiGo() override = default;\n\n explicit ClementiGo(const real_type th)\n : contact_threshold_(th), k_bond_length_(100.0), k_bond_angle_(20.0),\n k_dihedral_angle_1_(1.0), k_dihedral_angle_3_(0.5), k_intra_go_(0.3)\n {}\n\n ClementiGo(const real_type threshold,\n const real_type k_bl, const real_type k_ba,\n const real_type k_dih1, const real_type k_dih3, const real_type k_igo)\n : contact_threshold_(threshold), k_bond_length_(k_bl), k_bond_angle_(k_ba),\n k_dihedral_angle_1_(k_dih1), k_dihedral_angle_3_(k_dih3),\n k_intra_go_(k_igo)\n {}\n\n \/\/ generate parameters and write out to `ostrm`.\n void generate(toml::Table& out,\n const std::vector<std::unique_ptr<bead_type>>& chain) const override;\n\n bool check_beads_kind(\n const std::vector<std::unique_ptr<bead_type>>& chain) const override;\n\n real_type& contact_threshold() noexcept {return contact_threshold_;}\n real_type contact_threshold() const noexcept {return contact_threshold_;}\n\n private:\n\n real_type min_distance_sq(\n const typename bead_type::container_type& lhs,\n const typename bead_type::container_type& rhs) const\n {\n real_type dist2 = std::numeric_limits<real_type>::max();\n for(const auto& l : lhs)\n {\n if(l.element == \" H\")\n {\n std::cerr << \"ignore atom: \" << l << std::endl;\n continue;\n }\n for(const auto& r : rhs)\n {\n if(r.element == \" H\")\n {\n std::cerr << \"ignore atom: \" << r << std::endl;\n continue;\n }\n const auto d2 = distance(l.position, r.position);\n dist2 = std::min(dist2, d2);\n }\n }\n return dist2;\n }\n\n private:\n real_type contact_threshold_;\n real_type k_bond_length_;\n real_type k_bond_angle_;\n real_type k_dihedral_angle_1_;\n real_type k_dihedral_angle_3_;\n real_type k_intra_go_;\n};\n\ntemplate<typename realT>\nvoid ClementiGo<realT>::generate(toml::Table& ff,\n const std::vector<std::unique_ptr<bead_type>>& chain) const\n{\n if(!this->check_beads_kind(chain))\n {\n std::cerr << \"ClementiGo: stop generating forcefield...\" << std::endl;\n return ;\n }\n\n if(ff.count(\"local\") == 0)\n {\n ff[\"local\"] = toml::Array();\n }\n\n \/* bond-length *\/ {\n toml::Table bond_length;\n bond_length[\"interaction\"] = toml::String(\"BondLength\");\n bond_length[\"potential\"] = toml::String(\"Harmonic\");\n bond_length[\"topology\"] = toml::String(\"bond\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 1; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2};\n para[\"native\"] = distance(bead1->position(), bead2->position());\n para[\"k\"] = this->k_bond_length_;\n params.push_back(std::move(para));\n }\n bond_length[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(bond_length));\n }\n \/* bond-angle *\/{\n toml::Table bond_angle;\n bond_angle[\"interaction\"] = toml::String(\"BondAngle\");\n bond_angle[\"potential\"] = toml::String(\"Harmonic\");\n bond_angle[\"topology\"] = toml::String(\"none\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 2; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const auto& bead3 = chain.at(i+2);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n const std::size_t i3 = bead3->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2, i3};\n para[\"native\"] = angle(bead1->position(), bead2->position(),\n bead3->position());\n para[\"k\"] = this->k_bond_angle_;\n params.push_back(std::move(para));\n }\n bond_angle[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(bond_angle));\n }\n \/* dihedral-angle *\/{\n toml::Table dihd_angle;\n dihd_angle[\"interaction\"] = toml::String(\"DihedralAngle\");\n dihd_angle[\"potential\"] = toml::String(\"ClementiDihedral\");\n dihd_angle[\"topology\"] = toml::String(\"none\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 3; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const auto& bead3 = chain.at(i+2);\n const auto& bead4 = chain.at(i+3);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n const std::size_t i3 = bead3->index();\n const std::size_t i4 = bead4->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2, i3, i4};\n para[\"native\"] = dihedral_angle(bead1->position(),\n bead2->position(), bead3->position(), bead4->position());\n para[\"k1\"] = this->k_dihedral_angle_1_;\n para[\"k3\"] = this->k_dihedral_angle_3_;\n params.push_back(std::move(para));\n }\n dihd_angle[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(dihd_angle));\n }\n\n const real_type th2 = this->contact_threshold_ * this->contact_threshold_;\n \/* intra-chain-go-contacts *\/{\n toml::Table go_contact;\n go_contact[\"interaction\"] = toml::String(\"BondLength\");\n go_contact[\"potential\"] = toml::String(\"Go1012Contact\");\n go_contact[\"topology\"] = toml::String(\"contact\");\n\n toml::Array params;\n for(std::size_t i=0, sz_i = chain.size()-4; i<sz_i; ++i)\n {\n const auto& group1 = chain.at(i)->atoms();\n for(std::size_t j=i+4, sz_j = chain.size(); j<sz_j; ++j)\n {\n const auto& group2 = chain.at(j)->atoms();\n if(this->min_distance_sq(group1, group2))\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(j);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2};\n para[\"native\"] = distance(bead1->position(), bead2->position());\n para[\"k\"] = this->k_intra_go_;\n params.push_back(std::move(para));\n }\n }\n }\n go_contact[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(go_contact));\n }\n return;\n}\n\ntemplate<typename realT>\nbool ClementiGo<realT>::check_beads_kind(\n const std::vector<std::unique_ptr<bead_type>>& chain) const\n{\n for(const auto& bead : chain)\n {\n if(bead->kind() != \"CarbonAlpha\")\n {\n std::cerr << \"ClementiGo: invalid coarse-grained bead kind: \"\n << bead->kind() << '\\n';\n std::cerr << \"it allows only CarbonAlpha beads.\\n\";\n return false;\n }\n }\n return true;\n}\n\n}\/\/jarngreipr\n#endif \/* JARNGREIPR_CLEMENTI_GO *\/\n<commit_msg>fix min_dist_sq in ClementiGo<commit_after>#ifndef JARNGREIPR_CLEMENTI_GO\n#define JARNGREIPR_CLEMENTI_GO\n#include <jarngreipr\/forcefield\/ForceFieldGenerator.hpp>\n#include <jarngreipr\/geometry\/distance.hpp>\n#include <jarngreipr\/geometry\/angle.hpp>\n#include <jarngreipr\/geometry\/dihedral.hpp>\n#include <iterator>\n#include <iostream>\n#include <vector>\n\nnamespace jarngreipr\n{\n\ntemplate<typename realT>\nclass ClementiGo final : public IntraChainForceFieldGenerator<realT>\n{\n public:\n typedef IntraChainForceFieldGenerator<realT> base_type;\n typedef typename base_type::real_type real_type;\n typedef typename base_type::bead_type bead_type;\n\n public:\n\n ClementiGo()\n : contact_threshold_(6.5), k_bond_length_(100.0), k_bond_angle_(20.0),\n k_dihedral_angle_1_(1.0), k_dihedral_angle_3_(0.5), k_intra_go_(0.3)\n {}\n ~ClementiGo() override = default;\n\n explicit ClementiGo(const real_type th)\n : contact_threshold_(th), k_bond_length_(100.0), k_bond_angle_(20.0),\n k_dihedral_angle_1_(1.0), k_dihedral_angle_3_(0.5), k_intra_go_(0.3)\n {}\n\n ClementiGo(const real_type threshold,\n const real_type k_bl, const real_type k_ba,\n const real_type k_dih1, const real_type k_dih3, const real_type k_igo)\n : contact_threshold_(threshold), k_bond_length_(k_bl), k_bond_angle_(k_ba),\n k_dihedral_angle_1_(k_dih1), k_dihedral_angle_3_(k_dih3),\n k_intra_go_(k_igo)\n {}\n\n \/\/ generate parameters and write out to `ostrm`.\n void generate(toml::Table& out,\n const std::vector<std::unique_ptr<bead_type>>& chain) const override;\n\n bool check_beads_kind(\n const std::vector<std::unique_ptr<bead_type>>& chain) const override;\n\n real_type& contact_threshold() noexcept {return contact_threshold_;}\n real_type contact_threshold() const noexcept {return contact_threshold_;}\n\n private:\n\n real_type min_distance_sq(\n const typename bead_type::container_type& lhs,\n const typename bead_type::container_type& rhs) const\n {\n real_type dist2 = std::numeric_limits<real_type>::max();\n for(const auto& l : lhs)\n {\n if(l.element == \" H\")\n {\n continue;\n }\n for(const auto& r : rhs)\n {\n if(r.element == \" H\")\n {\n continue;\n }\n const auto d2 = distance_sq(l.position, r.position);\n dist2 = std::min(dist2, d2);\n }\n }\n return dist2;\n }\n\n private:\n real_type contact_threshold_;\n real_type k_bond_length_;\n real_type k_bond_angle_;\n real_type k_dihedral_angle_1_;\n real_type k_dihedral_angle_3_;\n real_type k_intra_go_;\n};\n\ntemplate<typename realT>\nvoid ClementiGo<realT>::generate(toml::Table& ff,\n const std::vector<std::unique_ptr<bead_type>>& chain) const\n{\n if(!this->check_beads_kind(chain))\n {\n std::cerr << \"ClementiGo: stop generating forcefield...\" << std::endl;\n return ;\n }\n\n if(ff.count(\"local\") == 0)\n {\n ff[\"local\"] = toml::Array();\n }\n\n \/* bond-length *\/ {\n toml::Table bond_length;\n bond_length[\"interaction\"] = toml::String(\"BondLength\");\n bond_length[\"potential\"] = toml::String(\"Harmonic\");\n bond_length[\"topology\"] = toml::String(\"bond\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 1; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2};\n para[\"native\"] = distance(bead1->position(), bead2->position());\n para[\"k\"] = this->k_bond_length_;\n params.push_back(std::move(para));\n }\n bond_length[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(bond_length));\n }\n \/* bond-angle *\/{\n toml::Table bond_angle;\n bond_angle[\"interaction\"] = toml::String(\"BondAngle\");\n bond_angle[\"potential\"] = toml::String(\"Harmonic\");\n bond_angle[\"topology\"] = toml::String(\"none\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 2; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const auto& bead3 = chain.at(i+2);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n const std::size_t i3 = bead3->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2, i3};\n para[\"native\"] = angle(bead1->position(), bead2->position(),\n bead3->position());\n para[\"k\"] = this->k_bond_angle_;\n params.push_back(std::move(para));\n }\n bond_angle[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(bond_angle));\n }\n \/* dihedral-angle *\/{\n toml::Table dihd_angle;\n dihd_angle[\"interaction\"] = toml::String(\"DihedralAngle\");\n dihd_angle[\"potential\"] = toml::String(\"ClementiDihedral\");\n dihd_angle[\"topology\"] = toml::String(\"none\");\n\n toml::Array params;\n for(std::size_t i=0, sz = chain.size() - 3; i<sz; ++i)\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(i+1);\n const auto& bead3 = chain.at(i+2);\n const auto& bead4 = chain.at(i+3);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n const std::size_t i3 = bead3->index();\n const std::size_t i4 = bead4->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2, i3, i4};\n para[\"native\"] = dihedral_angle(bead1->position(),\n bead2->position(), bead3->position(), bead4->position());\n para[\"k1\"] = this->k_dihedral_angle_1_;\n para[\"k3\"] = this->k_dihedral_angle_3_;\n params.push_back(std::move(para));\n }\n dihd_angle[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(dihd_angle));\n }\n\n const real_type th2 = this->contact_threshold_ * this->contact_threshold_;\n \/* intra-chain-go-contacts *\/{\n toml::Table go_contact;\n go_contact[\"interaction\"] = toml::String(\"BondLength\");\n go_contact[\"potential\"] = toml::String(\"Go1012Contact\");\n go_contact[\"topology\"] = toml::String(\"contact\");\n\n toml::Array params;\n for(std::size_t i=0, sz_i = chain.size()-4; i<sz_i; ++i)\n {\n const auto& group1 = chain.at(i)->atoms();\n for(std::size_t j=i+4, sz_j = chain.size(); j<sz_j; ++j)\n {\n const auto& group2 = chain.at(j)->atoms();\n if(this->min_distance_sq(group1, group2))\n {\n const auto& bead1 = chain.at(i);\n const auto& bead2 = chain.at(j);\n const std::size_t i1 = bead1->index();\n const std::size_t i2 = bead2->index();\n\n toml::Table para;\n para[\"indices\"] = toml::value{i1, i2};\n para[\"native\"] = distance(bead1->position(), bead2->position());\n para[\"k\"] = this->k_intra_go_;\n params.push_back(std::move(para));\n }\n }\n }\n go_contact[\"parameters\"] = std::move(params);\n ff[\"local\"].cast<toml::value_t::Array>().push_back(std::move(go_contact));\n }\n return;\n}\n\ntemplate<typename realT>\nbool ClementiGo<realT>::check_beads_kind(\n const std::vector<std::unique_ptr<bead_type>>& chain) const\n{\n for(const auto& bead : chain)\n {\n if(bead->kind() != \"CarbonAlpha\")\n {\n std::cerr << \"ClementiGo: invalid coarse-grained bead kind: \"\n << bead->kind() << '\\n';\n std::cerr << \"it allows only CarbonAlpha beads.\\n\";\n return false;\n }\n }\n return true;\n}\n\n}\/\/jarngreipr\n#endif \/* JARNGREIPR_CLEMENTI_GO *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2008, 2010, Oracle and\/or its affiliates. All rights reserved.\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA *\/\n\n\/**\n @file storage\/perfschema\/ha_perfschema.cc\n Performance schema storage engine (implementation).\n*\/\n\n#include \"my_global.h\"\n#include \"my_pthread.h\"\n#include \"sql_plugin.h\"\n#include \"mysql\/plugin.h\"\n#include \"ha_perfschema.h\"\n#include \"pfs_engine_table.h\"\n#include \"pfs_column_values.h\"\n#include \"pfs_instr_class.h\"\n#include \"pfs_instr.h\"\n\nhandlerton *pfs_hton= NULL;\n\nstatic handler* pfs_create_handler(handlerton *hton,\n TABLE_SHARE *table,\n MEM_ROOT *mem_root)\n{\n return new (mem_root) ha_perfschema(hton, table);\n}\n\nstatic int compare_database_names(const char *name1, const char *name2)\n{\n if (lower_case_table_names)\n return strcasecmp(name1, name2);\n return strcmp(name1, name2);\n}\n\nstatic const PFS_engine_table_share*\nfind_table_share(const char *db, const char *name)\n{\n DBUG_ENTER(\"find_table_share\");\n\n if (compare_database_names(db, PERFORMANCE_SCHEMA_str.str) != 0)\n DBUG_RETURN(NULL);\n\n const PFS_engine_table_share* result;\n result= PFS_engine_table::find_engine_table_share(name);\n DBUG_RETURN(result);\n}\n\nstatic int pfs_init_func(void *p)\n{\n DBUG_ENTER(\"pfs_init_func\");\n\n pfs_hton= reinterpret_cast<handlerton *> (p);\n\n pfs_hton->state= SHOW_OPTION_YES;\n pfs_hton->create= pfs_create_handler;\n pfs_hton->show_status= pfs_show_status;\n pfs_hton->flags= HTON_ALTER_NOT_SUPPORTED |\n HTON_TEMPORARY_NOT_SUPPORTED |\n HTON_NO_PARTITION;\n\n \/*\n As long as the server implementation keeps using legacy_db_type,\n as for example in mysql_truncate(),\n we can not rely on the fact that different mysqld process will assign\n consistently the same legacy_db_type for a given storage engine name.\n In particular, using different --loose-skip-xxx options between\n .\/mysqld --bootstrap\n .\/mysqld\n creates bogus .frm forms when bootstrapping the performance schema,\n if we rely on ha_initialize_handlerton to assign a really dynamic value.\n To fix this, a dedicated DB_TYPE is officially assigned to\n the performance schema. See Bug#43039.\n *\/\n pfs_hton->db_type= DB_TYPE_PERFORMANCE_SCHEMA;\n\n PFS_engine_table_share::init_all_locks();\n\n DBUG_RETURN(0);\n}\n\nstatic int pfs_done_func(void *p)\n{\n DBUG_ENTER(\"pfs_done_func\");\n\n pfs_hton= NULL;\n\n PFS_engine_table_share::delete_all_locks();\n\n DBUG_RETURN(0);\n}\n\nstatic struct st_mysql_show_var pfs_status_vars[]=\n{\n {\"Performance_schema_mutex_classes_lost\",\n (char*) &mutex_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_rwlock_classes_lost\",\n (char*) &rwlock_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_cond_classes_lost\",\n (char*) &cond_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_thread_classes_lost\",\n (char*) &thread_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_file_classes_lost\",\n (char*) &file_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_mutex_instances_lost\",\n (char*) &mutex_lost, SHOW_LONG},\n {\"Performance_schema_rwlock_instances_lost\",\n (char*) &rwlock_lost, SHOW_LONG},\n {\"Performance_schema_cond_instances_lost\",\n (char*) &cond_lost, SHOW_LONG},\n {\"Performance_schema_thread_instances_lost\",\n (char*) &thread_lost, SHOW_LONG},\n {\"Performance_schema_file_instances_lost\",\n (char*) &file_lost, SHOW_LONG},\n {\"Performance_schema_file_handles_lost\",\n (char*) &file_handle_lost, SHOW_LONG},\n {\"Performance_schema_locker_lost\",\n (char*) &locker_lost, SHOW_LONG},\n \/* table shares, can be flushed *\/\n {\"Performance_schema_table_instances_lost\",\n (char*) &table_share_lost, SHOW_LONG},\n \/* table handles, can be flushed *\/\n {\"Performance_schema_table_handles_lost\",\n (char*) &table_lost, SHOW_LONG},\n {NullS, NullS, SHOW_LONG}\n};\n\nstruct st_mysql_storage_engine pfs_storage_engine=\n{ MYSQL_HANDLERTON_INTERFACE_VERSION };\n\nconst char* pfs_engine_name= \"PERFORMANCE_SCHEMA\";\n\nmysql_declare_plugin(perfschema)\n{\n MYSQL_STORAGE_ENGINE_PLUGIN,\n &pfs_storage_engine,\n pfs_engine_name,\n \"Marc Alff, Oracle\", \/* Formerly Sun Microsystems, formerly MySQL *\/\n \"Performance Schema\",\n PLUGIN_LICENSE_GPL,\n pfs_init_func, \/* Plugin Init *\/\n pfs_done_func, \/* Plugin Deinit *\/\n 0x0001 \/* 0.1 *\/,\n pfs_status_vars, \/* status variables *\/\n NULL, \/* system variables *\/\n NULL \/* config options *\/\n}\nmysql_declare_plugin_end;\n\nha_perfschema::ha_perfschema(handlerton *hton, TABLE_SHARE *share)\n : handler(hton, share), m_table_share(NULL), m_table(NULL)\n{}\n\nha_perfschema::~ha_perfschema()\n{}\n\nstatic const char *ha_pfs_exts[]= {\n NullS\n};\n\nconst char **ha_perfschema::bas_ext() const\n{\n return ha_pfs_exts;\n}\n\nint ha_perfschema::open(const char *name, int mode, uint test_if_locked)\n{\n DBUG_ENTER(\"ha_perfschema::open\");\n\n m_table_share= find_table_share(table_share->db.str,\n table_share->table_name.str);\n if (! m_table_share)\n DBUG_RETURN(HA_ERR_NO_SUCH_TABLE);\n\n thr_lock_data_init(m_table_share->m_thr_lock_ptr, &m_thr_lock, NULL);\n ref_length= m_table_share->m_ref_length;\n\n psi_open();\n\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::close(void)\n{\n DBUG_ENTER(\"ha_perfschema::close\");\n m_table_share= NULL;\n delete m_table;\n m_table= NULL;\n\n psi_close();\n\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::write_row(uchar *buf)\n{\n int result;\n\n DBUG_ENTER(\"ha_perfschema::write_row\");\n\n ha_statistic_increment(&SSV::ha_write_count);\n DBUG_ASSERT(m_table_share);\n\n if (m_table_share->m_write_row)\n result= m_table_share->m_write_row(table, buf, table->field);\n else\n {\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n result= HA_ERR_WRONG_COMMAND;\n }\n\n DBUG_RETURN(result);\n}\n\nvoid ha_perfschema::use_hidden_primary_key(void)\n{\n \/*\n This is also called in case of row based replication,\n see TABLE::mark_columns_needed_for_update().\n Add all columns to the read set, but do not touch the write set,\n as some columns in the SETUP_ tables are not writable.\n *\/\n table->column_bitmaps_set_no_signal(&table->s->all_set, table->write_set);\n}\n\nint ha_perfschema::update_row(const uchar *old_data, uchar *new_data)\n{\n DBUG_ENTER(\"ha_perfschema::update_row\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->update_row(table, old_data, new_data, table->field);\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::rnd_init(bool scan)\n{\n int result;\n DBUG_ENTER(\"ha_perfschema::rnd_init\");\n\n DBUG_ASSERT(m_table_share);\n DBUG_ASSERT(m_table_share->m_open_table != NULL);\n\n stats.records= 0;\n if (m_table == NULL)\n m_table= m_table_share->m_open_table();\n else\n m_table->reset_position();\n\n result= m_table ? 0 : HA_ERR_OUT_OF_MEM;\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::rnd_end(void)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_end\");\n DBUG_ASSERT(m_table);\n delete m_table;\n m_table= NULL;\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::rnd_next(uchar *buf)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_next\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->rnd_next();\n if (result == 0)\n {\n result= m_table->read_row(table, buf, table->field);\n if (result == 0)\n stats.records++;\n }\n DBUG_RETURN(result);\n}\n\nvoid ha_perfschema::position(const uchar *record)\n{\n DBUG_ENTER(\"ha_perfschema::position\");\n\n DBUG_ASSERT(m_table);\n m_table->get_position(ref);\n DBUG_VOID_RETURN;\n}\n\nint ha_perfschema::rnd_pos(uchar *buf, uchar *pos)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_pos\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->rnd_pos(pos);\n if (result == 0)\n result= m_table->read_row(table, buf, table->field);\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::info(uint flag)\n{\n DBUG_ENTER(\"ha_perfschema::info\");\n DBUG_ASSERT(m_table_share);\n if (flag & HA_STATUS_VARIABLE)\n stats.records= m_table_share->m_records;\n if (flag & HA_STATUS_CONST)\n ref_length= m_table_share->m_ref_length;\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::delete_all_rows(void)\n{\n int result;\n\n DBUG_ENTER(\"ha_perfschema::delete_all_rows\");\n\n DBUG_ASSERT(m_table_share);\n if (m_table_share->m_delete_all_rows)\n result= m_table_share->m_delete_all_rows();\n else\n {\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n result= HA_ERR_WRONG_COMMAND;\n }\n DBUG_RETURN(result);\n}\n\nTHR_LOCK_DATA **ha_perfschema::store_lock(THD *thd,\n THR_LOCK_DATA **to,\n enum thr_lock_type lock_type)\n{\n if (lock_type != TL_IGNORE && m_thr_lock.type == TL_UNLOCK)\n m_thr_lock.type= lock_type;\n *to++= &m_thr_lock;\n m_thr_lock.m_psi= m_psi;\n return to;\n}\n\nint ha_perfschema::delete_table(const char *name)\n{\n DBUG_ENTER(\"ha_perfschema::delete_table\");\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::rename_table(const char * from, const char * to)\n{\n DBUG_ENTER(\"ha_perfschema::rename_table \");\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n DBUG_RETURN(HA_ERR_WRONG_COMMAND);\n}\n\nint ha_perfschema::create(const char *name, TABLE *table_arg,\n HA_CREATE_INFO *create_info)\n{\n DBUG_ENTER(\"ha_perfschema::create\");\n DBUG_ASSERT(table_arg);\n DBUG_ASSERT(table_arg->s);\n if (find_table_share(table_arg->s->db.str,\n table_arg->s->table_name.str))\n {\n \/*\n Attempting to create a known performance schema table.\n Allowing the create, to create .FRM files,\n for the initial database install, and mysql_upgrade.\n This should fail once .FRM are removed.\n *\/\n DBUG_RETURN(0);\n }\n \/*\n This is not a general purpose engine.\n Failure to CREATE TABLE is the expected result.\n *\/\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n DBUG_RETURN(HA_ERR_WRONG_COMMAND);\n}\n\n<commit_msg>Bug#56521 Assertion failed: (m_state == 2), function allocated_to_free, pfs_lock.h (138)<commit_after>\/* Copyright (c) 2008, 2010, Oracle and\/or its affiliates. All rights reserved.\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA *\/\n\n\/**\n @file storage\/perfschema\/ha_perfschema.cc\n Performance schema storage engine (implementation).\n*\/\n\n#include \"my_global.h\"\n#include \"my_atomic.h\"\n#include \"my_pthread.h\"\n#include \"sql_plugin.h\"\n#include \"mysql\/plugin.h\"\n#include \"ha_perfschema.h\"\n#include \"pfs_engine_table.h\"\n#include \"pfs_column_values.h\"\n#include \"pfs_instr_class.h\"\n#include \"pfs_instr.h\"\n\n#ifdef MY_ATOMIC_MODE_DUMMY\n\/*\n The performance schema can can not function with MY_ATOMIC_MODE_DUMMY,\n a fully functional implementation of MY_ATOMIC should be used instead.\n If the build fails with this error message:\n - either use a different .\/configure --with-atomic-ops option\n - or do not build with the performance schema.\n*\/\n#error \"The performance schema needs a functional MY_ATOMIC implementation.\"\n#endif\n\nhandlerton *pfs_hton= NULL;\n\nstatic handler* pfs_create_handler(handlerton *hton,\n TABLE_SHARE *table,\n MEM_ROOT *mem_root)\n{\n return new (mem_root) ha_perfschema(hton, table);\n}\n\nstatic int compare_database_names(const char *name1, const char *name2)\n{\n if (lower_case_table_names)\n return strcasecmp(name1, name2);\n return strcmp(name1, name2);\n}\n\nstatic const PFS_engine_table_share*\nfind_table_share(const char *db, const char *name)\n{\n DBUG_ENTER(\"find_table_share\");\n\n if (compare_database_names(db, PERFORMANCE_SCHEMA_str.str) != 0)\n DBUG_RETURN(NULL);\n\n const PFS_engine_table_share* result;\n result= PFS_engine_table::find_engine_table_share(name);\n DBUG_RETURN(result);\n}\n\nstatic int pfs_init_func(void *p)\n{\n DBUG_ENTER(\"pfs_init_func\");\n\n pfs_hton= reinterpret_cast<handlerton *> (p);\n\n pfs_hton->state= SHOW_OPTION_YES;\n pfs_hton->create= pfs_create_handler;\n pfs_hton->show_status= pfs_show_status;\n pfs_hton->flags= HTON_ALTER_NOT_SUPPORTED |\n HTON_TEMPORARY_NOT_SUPPORTED |\n HTON_NO_PARTITION;\n\n \/*\n As long as the server implementation keeps using legacy_db_type,\n as for example in mysql_truncate(),\n we can not rely on the fact that different mysqld process will assign\n consistently the same legacy_db_type for a given storage engine name.\n In particular, using different --loose-skip-xxx options between\n .\/mysqld --bootstrap\n .\/mysqld\n creates bogus .frm forms when bootstrapping the performance schema,\n if we rely on ha_initialize_handlerton to assign a really dynamic value.\n To fix this, a dedicated DB_TYPE is officially assigned to\n the performance schema. See Bug#43039.\n *\/\n pfs_hton->db_type= DB_TYPE_PERFORMANCE_SCHEMA;\n\n PFS_engine_table_share::init_all_locks();\n\n DBUG_RETURN(0);\n}\n\nstatic int pfs_done_func(void *p)\n{\n DBUG_ENTER(\"pfs_done_func\");\n\n pfs_hton= NULL;\n\n PFS_engine_table_share::delete_all_locks();\n\n DBUG_RETURN(0);\n}\n\nstatic struct st_mysql_show_var pfs_status_vars[]=\n{\n {\"Performance_schema_mutex_classes_lost\",\n (char*) &mutex_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_rwlock_classes_lost\",\n (char*) &rwlock_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_cond_classes_lost\",\n (char*) &cond_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_thread_classes_lost\",\n (char*) &thread_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_file_classes_lost\",\n (char*) &file_class_lost, SHOW_LONG_NOFLUSH},\n {\"Performance_schema_mutex_instances_lost\",\n (char*) &mutex_lost, SHOW_LONG},\n {\"Performance_schema_rwlock_instances_lost\",\n (char*) &rwlock_lost, SHOW_LONG},\n {\"Performance_schema_cond_instances_lost\",\n (char*) &cond_lost, SHOW_LONG},\n {\"Performance_schema_thread_instances_lost\",\n (char*) &thread_lost, SHOW_LONG},\n {\"Performance_schema_file_instances_lost\",\n (char*) &file_lost, SHOW_LONG},\n {\"Performance_schema_file_handles_lost\",\n (char*) &file_handle_lost, SHOW_LONG},\n {\"Performance_schema_locker_lost\",\n (char*) &locker_lost, SHOW_LONG},\n \/* table shares, can be flushed *\/\n {\"Performance_schema_table_instances_lost\",\n (char*) &table_share_lost, SHOW_LONG},\n \/* table handles, can be flushed *\/\n {\"Performance_schema_table_handles_lost\",\n (char*) &table_lost, SHOW_LONG},\n {NullS, NullS, SHOW_LONG}\n};\n\nstruct st_mysql_storage_engine pfs_storage_engine=\n{ MYSQL_HANDLERTON_INTERFACE_VERSION };\n\nconst char* pfs_engine_name= \"PERFORMANCE_SCHEMA\";\n\nmysql_declare_plugin(perfschema)\n{\n MYSQL_STORAGE_ENGINE_PLUGIN,\n &pfs_storage_engine,\n pfs_engine_name,\n \"Marc Alff, Oracle\", \/* Formerly Sun Microsystems, formerly MySQL *\/\n \"Performance Schema\",\n PLUGIN_LICENSE_GPL,\n pfs_init_func, \/* Plugin Init *\/\n pfs_done_func, \/* Plugin Deinit *\/\n 0x0001 \/* 0.1 *\/,\n pfs_status_vars, \/* status variables *\/\n NULL, \/* system variables *\/\n NULL \/* config options *\/\n}\nmysql_declare_plugin_end;\n\nha_perfschema::ha_perfschema(handlerton *hton, TABLE_SHARE *share)\n : handler(hton, share), m_table_share(NULL), m_table(NULL)\n{}\n\nha_perfschema::~ha_perfschema()\n{}\n\nstatic const char *ha_pfs_exts[]= {\n NullS\n};\n\nconst char **ha_perfschema::bas_ext() const\n{\n return ha_pfs_exts;\n}\n\nint ha_perfschema::open(const char *name, int mode, uint test_if_locked)\n{\n DBUG_ENTER(\"ha_perfschema::open\");\n\n m_table_share= find_table_share(table_share->db.str,\n table_share->table_name.str);\n if (! m_table_share)\n DBUG_RETURN(HA_ERR_NO_SUCH_TABLE);\n\n thr_lock_data_init(m_table_share->m_thr_lock_ptr, &m_thr_lock, NULL);\n ref_length= m_table_share->m_ref_length;\n\n psi_open();\n\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::close(void)\n{\n DBUG_ENTER(\"ha_perfschema::close\");\n m_table_share= NULL;\n delete m_table;\n m_table= NULL;\n\n psi_close();\n\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::write_row(uchar *buf)\n{\n int result;\n\n DBUG_ENTER(\"ha_perfschema::write_row\");\n\n ha_statistic_increment(&SSV::ha_write_count);\n DBUG_ASSERT(m_table_share);\n\n if (m_table_share->m_write_row)\n result= m_table_share->m_write_row(table, buf, table->field);\n else\n {\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n result= HA_ERR_WRONG_COMMAND;\n }\n\n DBUG_RETURN(result);\n}\n\nvoid ha_perfschema::use_hidden_primary_key(void)\n{\n \/*\n This is also called in case of row based replication,\n see TABLE::mark_columns_needed_for_update().\n Add all columns to the read set, but do not touch the write set,\n as some columns in the SETUP_ tables are not writable.\n *\/\n table->column_bitmaps_set_no_signal(&table->s->all_set, table->write_set);\n}\n\nint ha_perfschema::update_row(const uchar *old_data, uchar *new_data)\n{\n DBUG_ENTER(\"ha_perfschema::update_row\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->update_row(table, old_data, new_data, table->field);\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::rnd_init(bool scan)\n{\n int result;\n DBUG_ENTER(\"ha_perfschema::rnd_init\");\n\n DBUG_ASSERT(m_table_share);\n DBUG_ASSERT(m_table_share->m_open_table != NULL);\n\n stats.records= 0;\n if (m_table == NULL)\n m_table= m_table_share->m_open_table();\n else\n m_table->reset_position();\n\n result= m_table ? 0 : HA_ERR_OUT_OF_MEM;\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::rnd_end(void)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_end\");\n DBUG_ASSERT(m_table);\n delete m_table;\n m_table= NULL;\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::rnd_next(uchar *buf)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_next\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->rnd_next();\n if (result == 0)\n {\n result= m_table->read_row(table, buf, table->field);\n if (result == 0)\n stats.records++;\n }\n DBUG_RETURN(result);\n}\n\nvoid ha_perfschema::position(const uchar *record)\n{\n DBUG_ENTER(\"ha_perfschema::position\");\n\n DBUG_ASSERT(m_table);\n m_table->get_position(ref);\n DBUG_VOID_RETURN;\n}\n\nint ha_perfschema::rnd_pos(uchar *buf, uchar *pos)\n{\n DBUG_ENTER(\"ha_perfschema::rnd_pos\");\n\n DBUG_ASSERT(m_table);\n int result= m_table->rnd_pos(pos);\n if (result == 0)\n result= m_table->read_row(table, buf, table->field);\n DBUG_RETURN(result);\n}\n\nint ha_perfschema::info(uint flag)\n{\n DBUG_ENTER(\"ha_perfschema::info\");\n DBUG_ASSERT(m_table_share);\n if (flag & HA_STATUS_VARIABLE)\n stats.records= m_table_share->m_records;\n if (flag & HA_STATUS_CONST)\n ref_length= m_table_share->m_ref_length;\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::delete_all_rows(void)\n{\n int result;\n\n DBUG_ENTER(\"ha_perfschema::delete_all_rows\");\n\n DBUG_ASSERT(m_table_share);\n if (m_table_share->m_delete_all_rows)\n result= m_table_share->m_delete_all_rows();\n else\n {\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n result= HA_ERR_WRONG_COMMAND;\n }\n DBUG_RETURN(result);\n}\n\nTHR_LOCK_DATA **ha_perfschema::store_lock(THD *thd,\n THR_LOCK_DATA **to,\n enum thr_lock_type lock_type)\n{\n if (lock_type != TL_IGNORE && m_thr_lock.type == TL_UNLOCK)\n m_thr_lock.type= lock_type;\n *to++= &m_thr_lock;\n m_thr_lock.m_psi= m_psi;\n return to;\n}\n\nint ha_perfschema::delete_table(const char *name)\n{\n DBUG_ENTER(\"ha_perfschema::delete_table\");\n DBUG_RETURN(0);\n}\n\nint ha_perfschema::rename_table(const char * from, const char * to)\n{\n DBUG_ENTER(\"ha_perfschema::rename_table \");\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n DBUG_RETURN(HA_ERR_WRONG_COMMAND);\n}\n\nint ha_perfschema::create(const char *name, TABLE *table_arg,\n HA_CREATE_INFO *create_info)\n{\n DBUG_ENTER(\"ha_perfschema::create\");\n DBUG_ASSERT(table_arg);\n DBUG_ASSERT(table_arg->s);\n if (find_table_share(table_arg->s->db.str,\n table_arg->s->table_name.str))\n {\n \/*\n Attempting to create a known performance schema table.\n Allowing the create, to create .FRM files,\n for the initial database install, and mysql_upgrade.\n This should fail once .FRM are removed.\n *\/\n DBUG_RETURN(0);\n }\n \/*\n This is not a general purpose engine.\n Failure to CREATE TABLE is the expected result.\n *\/\n my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));\n DBUG_RETURN(HA_ERR_WRONG_COMMAND);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ \n\/\/ Copyright (C) 2007 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ Copyright (C) 2007 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <sipxunit\/TestUtilities.h>\n\n#include <mp\/MpOutputDeviceManager.h>\n#include <mp\/MpAudioBuf.h>\n#include <mp\/MpSineWaveGeneratorDeviceDriver.h>\n#include <os\/OsTask.h>\n#include <os\/OsEvent.h>\n\n#define TEST_SAMPLES_PER_FRAME_SIZE 80\n#define BUFFER_NUM 500\n#define TEST_SAMPLES_PER_SECOND 8000\n#define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1)\n#define TEST_SAMPLE_DATA_MAGNITUDE 32000\n#define TEST_SAMPLE_DATA_PERIOD (1000000\/60) \/\/in microseconds 60 Hz\n\n#define CREATE_TEST_RUNS_NUMBER 3\n#define ENABLE_DISABLE_TEST_RUNS_NUMBER 5\n#define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10\n#define DIRECT_WRITE_TEST_RUNS_NUMBER 3\n#define TICKER_TEST_WRITE_RUNS_NUMBER 3\n\n#undef USE_TEST_DRIVER\n\n#ifdef USE_TEST_DRIVER \/\/ USE_TEST_DRIVER [\n#include <mp\/MpodBufferRecorder.h>\n#define OUTPUT_DRIVER MpodBufferRecorder\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"default\", TEST_SAMPLE_DATA_SIZE*1000\/TEST_SAMPLES_PER_SECOND\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#include <mp\/MpodWinMM.h>\n#define OUTPUT_DRIVER MpodWinMM\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName()\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include <mp\/MpodOSS.h>\n#define OUTPUT_DRIVER MpodOSS\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"\/dev\/dsp\"\n\n#else \/\/ __pingtel_on_posix__ ]\n#error Unknown platform!\n#endif\n\n\/\/static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE];\n\/\/static UtlBoolean sampleDataInitialized=FALSE;\n\nstatic void calculateSampleData(int frequency, \n MpAudioSample sampleData[], \n int samplesPerFrame,\n int samplesPerSecond)\n{\n for (int i=0; i<TEST_SAMPLE_DATA_SIZE; i++)\n {\n sampleData[i] = \n MpSineWaveGeneratorDeviceDriver::calculateSample(0,\n TEST_SAMPLE_DATA_MAGNITUDE,\n 1000000 \/ frequency,\n i,\n samplesPerFrame,\n samplesPerSecond);\n }\n}\n\n\/**\n * Unittest for MpOutputDeviceDriver\n *\/\nclass MpOutputDeviceDriverTest : public CppUnit::TestCase\n{\n CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest);\n CPPUNIT_TEST(testCreate);\n CPPUNIT_TEST(testEnableDisable);\n CPPUNIT_TEST(testEnableDisableFast);\n CPPUNIT_TEST(testDirectWrite);\n CPPUNIT_TEST(testTickerNotification);\n CPPUNIT_TEST_SUITE_END();\n\n\npublic:\n\n void setUp()\n {\n \/\/ Create pool for data buffers\n mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample)\n + MpArrayBuf::getHeaderSize(), BUFFER_NUM);\n CPPUNIT_ASSERT(mpPool != NULL);\n\n \/\/ Create pool for buffer headers\n mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM);\n CPPUNIT_ASSERT(mpHeadersPool != NULL);\n\n \/\/ Set mpHeadersPool as default pool for audio and data pools.\n MpAudioBuf::smpDefaultPool = mpHeadersPool;\n MpDataBuf::smpDefaultPool = mpHeadersPool;\n }\n\n void tearDown()\n {\n if (mpPool != NULL)\n {\n delete mpPool;\n }\n if (mpHeadersPool != NULL)\n {\n delete mpHeadersPool;\n }\n }\n\n void testCreate()\n {\n for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++)\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testEnableDisable()\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++)\n {\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n OsTask::delay(50);\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testEnableDisableFast()\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++)\n {\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testDirectWrite()\n {\n MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE];\n calculateSampleData(440, sampleData, 80, 8000);\n\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++)\n {\n MpFrameTime frameTime=0;\n\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n \/\/ Write some data to device.\n for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE\/TEST_SAMPLES_PER_FRAME_SIZE; frame++)\n {\n OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE\/TEST_SAMPLES_PER_SECOND);\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE,\n sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame,\n frameTime));\n\n frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000\/TEST_SAMPLES_PER_SECOND;\n }\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testTickerNotification()\n {\n OsEvent notificationEvent;\n int sampleRates[]={8000, 16000, 32000, 48000};\n int numRates = 4;\n MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE];\n int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000};\n int numFreqs = 6;\n\n int rateIndex = 0;\n\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<numFreqs; i++)\n {\n printf(\"Frequency: %d (Hz) Sample rate: %d\/sec.\\n\", \n frequencies[i], sampleRates[rateIndex]);\n calculateSampleData(frequencies[i], sampleData, sampleRates[rateIndex]\/100, sampleRates[rateIndex]);\n MpFrameTime frameTime=0;\n\n driver.enableDevice(sampleRates[rateIndex]\/100, sampleRates[rateIndex], 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(¬ificationEvent));\n\n \/\/ Write some data to device.\n for (int frame=0; frame<100; frame++)\n {\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000)));\n notificationEvent.reset();\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n driver.pushFrame(sampleRates[rateIndex]\/100,\n sampleData + sampleRates[rateIndex]\/100*frame,\n frameTime));\n\n frameTime += sampleRates[rateIndex]\/100*1000\/sampleRates[rateIndex];\n }\n\n CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS);\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\nprotected:\n MpBufPool *mpPool; \/\/\/< Pool for data buffers\n MpBufPool *mpHeadersPool; \/\/\/< Pool for buffers headers\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest);\n<commit_msg>Bug fix: sampleData buffer size now adjusted properly for rate given.<commit_after>\/\/ \n\/\/ Copyright (C) 2007 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ Copyright (C) 2007 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <sipxunit\/TestUtilities.h>\n\n#include <mp\/MpOutputDeviceManager.h>\n#include <mp\/MpAudioBuf.h>\n#include <mp\/MpSineWaveGeneratorDeviceDriver.h>\n#include <os\/OsTask.h>\n#include <os\/OsEvent.h>\n\n#define TEST_SAMPLES_PER_FRAME_SIZE 80\n#define BUFFER_NUM 500\n#define TEST_SAMPLES_PER_SECOND 8000\n#define TEST_SAMPLE_DATA_SIZE (TEST_SAMPLES_PER_SECOND*1)\n#define TEST_SAMPLE_DATA_MAGNITUDE 32000\n#define TEST_SAMPLE_DATA_PERIOD (1000000\/60) \/\/in microseconds 60 Hz\n\n#define CREATE_TEST_RUNS_NUMBER 3\n#define ENABLE_DISABLE_TEST_RUNS_NUMBER 5\n#define ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER 10\n#define DIRECT_WRITE_TEST_RUNS_NUMBER 3\n#define TICKER_TEST_WRITE_RUNS_NUMBER 3\n\n#undef USE_TEST_DRIVER\n\n#ifdef USE_TEST_DRIVER \/\/ USE_TEST_DRIVER [\n#include <mp\/MpodBufferRecorder.h>\n#define OUTPUT_DRIVER MpodBufferRecorder\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"default\", TEST_SAMPLE_DATA_SIZE*1000\/TEST_SAMPLES_PER_SECOND\n\n#elif defined(WIN32) \/\/ USE_TEST_DRIVER ][ WIN32\n#include <mp\/MpodWinMM.h>\n#define OUTPUT_DRIVER MpodWinMM\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS MpodWinMM::getDefaultDeviceName()\n\n#elif defined(__pingtel_on_posix__) \/\/ WIN32 ][ __pingtel_on_posix__\n#include <mp\/MpodOSS.h>\n#define OUTPUT_DRIVER MpodOSS\n#define OUTPUT_DRIVER_CONSTRUCTOR_PARAMS \"\/dev\/dsp\"\n\n#else \/\/ __pingtel_on_posix__ ]\n#error Unknown platform!\n#endif\n\n\/\/static MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE];\n\/\/static UtlBoolean sampleDataInitialized=FALSE;\n\nstatic void calculateSampleData(int frequency, \n MpAudioSample sampleData[], \n int samplesPerFrame,\n int samplesPerSecond)\n{\n for (int i=0; i<TEST_SAMPLE_DATA_SIZE; i++)\n {\n sampleData[i] = \n MpSineWaveGeneratorDeviceDriver::calculateSample(0,\n TEST_SAMPLE_DATA_MAGNITUDE,\n 1000000 \/ frequency,\n i,\n samplesPerFrame,\n samplesPerSecond);\n }\n}\n\n\/**\n * Unittest for MpOutputDeviceDriver\n *\/\nclass MpOutputDeviceDriverTest : public CppUnit::TestCase\n{\n CPPUNIT_TEST_SUITE(MpOutputDeviceDriverTest);\n CPPUNIT_TEST(testCreate);\n CPPUNIT_TEST(testEnableDisable);\n CPPUNIT_TEST(testEnableDisableFast);\n CPPUNIT_TEST(testDirectWrite);\n CPPUNIT_TEST(testTickerNotification);\n CPPUNIT_TEST_SUITE_END();\n\n\npublic:\n\n void setUp()\n {\n \/\/ Create pool for data buffers\n mpPool = new MpBufPool(TEST_SAMPLES_PER_FRAME_SIZE * sizeof(MpAudioSample)\n + MpArrayBuf::getHeaderSize(), BUFFER_NUM);\n CPPUNIT_ASSERT(mpPool != NULL);\n\n \/\/ Create pool for buffer headers\n mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), BUFFER_NUM);\n CPPUNIT_ASSERT(mpHeadersPool != NULL);\n\n \/\/ Set mpHeadersPool as default pool for audio and data pools.\n MpAudioBuf::smpDefaultPool = mpHeadersPool;\n MpDataBuf::smpDefaultPool = mpHeadersPool;\n }\n\n void tearDown()\n {\n if (mpPool != NULL)\n {\n delete mpPool;\n }\n if (mpHeadersPool != NULL)\n {\n delete mpHeadersPool;\n }\n }\n\n void testCreate()\n {\n for (int i=0; i<CREATE_TEST_RUNS_NUMBER; i++)\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testEnableDisable()\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<ENABLE_DISABLE_TEST_RUNS_NUMBER; i++)\n {\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n OsTask::delay(50);\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testEnableDisableFast()\n {\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<ENABLE_DISABLE_FAST_TEST_RUNS_NUMBER; i++)\n {\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testDirectWrite()\n {\n MpAudioSample sampleData[TEST_SAMPLE_DATA_SIZE];\n calculateSampleData(440, sampleData, 80, 8000);\n\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<DIRECT_WRITE_TEST_RUNS_NUMBER; i++)\n {\n MpFrameTime frameTime=0;\n\n driver.enableDevice(TEST_SAMPLES_PER_FRAME_SIZE, TEST_SAMPLES_PER_SECOND, 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n \/\/ Write some data to device.\n for (int frame=0; frame<TEST_SAMPLE_DATA_SIZE\/TEST_SAMPLES_PER_FRAME_SIZE; frame++)\n {\n OsTask::delay(1000*TEST_SAMPLES_PER_FRAME_SIZE\/TEST_SAMPLES_PER_SECOND);\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n driver.pushFrame(TEST_SAMPLES_PER_FRAME_SIZE,\n sampleData + TEST_SAMPLES_PER_FRAME_SIZE*frame,\n frameTime));\n\n frameTime += TEST_SAMPLES_PER_FRAME_SIZE*1000\/TEST_SAMPLES_PER_SECOND;\n }\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n }\n\n void testTickerNotification()\n {\n OsEvent notificationEvent;\n int sampleRates[]={8000, 16000, 32000, 48000};\n int numRates = 4;\n int frequencies[] = {1000, 2000, 4000, 8000, 16000, 20000};\n int numFreqs = 6;\n\n int rateIndex = 0;\n MpAudioSample* sampleData = new MpAudioSample[sampleRates[rateIndex]];\n\n OUTPUT_DRIVER driver(OUTPUT_DRIVER_CONSTRUCTOR_PARAMS);\n CPPUNIT_ASSERT(!driver.isEnabled());\n\n for (int i=0; i<numFreqs; i++)\n {\n printf(\"Frequency: %d (Hz) Sample rate: %d\/sec.\\n\", \n frequencies[i], sampleRates[rateIndex]);\n calculateSampleData(frequencies[i], sampleData, sampleRates[rateIndex]\/100, sampleRates[rateIndex]);\n MpFrameTime frameTime=0;\n\n driver.enableDevice(sampleRates[rateIndex]\/100, sampleRates[rateIndex], 0);\n CPPUNIT_ASSERT(driver.isEnabled());\n\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, driver.setTickerNotification(¬ificationEvent));\n\n \/\/ Write some data to device.\n for (int frame=0; frame<100; frame++)\n {\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, notificationEvent.wait(OsTime(1000)));\n notificationEvent.reset();\n CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,\n driver.pushFrame(sampleRates[rateIndex]\/100,\n sampleData + sampleRates[rateIndex]\/100*frame,\n frameTime));\n\n frameTime += sampleRates[rateIndex]\/100*1000\/sampleRates[rateIndex];\n }\n\n CPPUNIT_ASSERT(driver.setTickerNotification(NULL) == OS_SUCCESS);\n\n driver.disableDevice();\n CPPUNIT_ASSERT(!driver.isEnabled());\n }\n delete[] sampleData;\n }\n\nprotected:\n MpBufPool *mpPool; \/\/\/< Pool for data buffers\n MpBufPool *mpHeadersPool; \/\/\/< Pool for buffers headers\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(MpOutputDeviceDriverTest);\n<|endoftext|>"} {"text":"<commit_before>#include \"datalayer.h\"\n#include \"persons.h\"\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nDataLayer::DataLayer()\n{\n loadFromFile();\n}\nvector<Persons> DataLayer::getVector()\n{\n vector<Persons> myV;\n\n for(int i = 0; i < people.size();i++)\n {\n \/\/ vector<Persons> myV = people;\n myV.push_back(people[i]);\n\n }\n return myV;\n}\n\nvoid DataLayer::loadFromFile()\n{\n\n Persons p;\n ifstream inStream;\n\n\n inStream.open(\"textFile.txt\");\n\n\n\n while(inStream >> p)\n {\n\n people.push_back(p);\n cout << p;\n\n addPerson(p);\n\n }\n inStream.close();\n\n }\n\nvoid DataLayer::saveToFile()\n{\n fstream out;\n\n out.open(\"textFile.txt\");\n\n for (size_t i = 0; i < people.size(); i++)\n {\n out << people[i] << endl;\n }\n\n out.close();\n}\n\nvoid DataLayer::addPerson(const Persons& p) {\n people.push_back(p);\n}\n\nvoid DataLayer::listPersons()\n{\n\n}\n\nvoid DataLayer::sortByName()\n{\n\n}\n\nvoid DataLayer::sortByBirthYear()\n{\n int i = 0, j = people.size();\n Persons tmp;\n int pivot = people[people.size() \/ 2].getBirthYear();\n\n while (i <= j)\n {\n while (people[i].getBirthYear() < pivot)\n {\n i++;\n }\n while (people[j].getBirthYear() > pivot)\n {\n j--;\n }\n if (i <= j)\n {\n tmp = people[i];\n people[i] = people[j];\n people[j] = tmp;\n i++;\n j--;\n }\n }\n}\n\nvoid DataLayer::sortByDeathYear()\n{\n int i = 0, j = people.size();\n Persons tmp;\n int pivot = people[people.size() \/ 2].getDeathYear();\n\n while (i <= j)\n {\n while (people[i].getDeathYear() < pivot)\n {\n i++;\n }\n while (people[j].getDeathYear() > pivot)\n {\n j--;\n }\n if (i <= j)\n {\n tmp = people[i];\n people[i] = people[j];\n people[j] = tmp;\n i++;\n j--;\n }\n }\n}\n\nvoid DataLayer::sortByGender()\n{\n\n}\n<commit_msg>breytti int í size_t<commit_after>#include \"datalayer.h\"\n#include \"persons.h\"\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nDataLayer::DataLayer()\n{\n loadFromFile();\n}\nvector<Persons> DataLayer::getVector()\n{\n vector<Persons> myV;\n\n for(size_t i = 0; i < people.size();i++)\n {\n \/\/ vector<Persons> myV = people;\n myV.push_back(people[i]);\n\n }\n return myV;\n}\n\nvoid DataLayer::loadFromFile()\n{\n\n Persons p;\n ifstream inStream;\n\n inStream.open(\"textFile.txt\");\n\n while(inStream >> p)\n {\n\n people.push_back(p);\n cout << p;\n\n addPerson(p);\n\n }\n inStream.close();\n\n }\n\nvoid DataLayer::saveToFile()\n{\n fstream out;\n\n out.open(\"textFile.txt\");\n\n for (size_t i = 0; i < people.size(); i++)\n {\n out << people[i] << endl;\n }\n\n out.close();\n}\n\nvoid DataLayer::addPerson(const Persons& p) {\n people.push_back(p);\n}\n\nvoid DataLayer::listPersons()\n{\n\n}\n\nvoid DataLayer::sortByName()\n{\n\n}\n\nvoid DataLayer::sortByBirthYear()\n{\n int i = 0, j = people.size();\n Persons tmp;\n int pivot = people[people.size() \/ 2].getBirthYear();\n\n while (i <= j)\n {\n while (people[i].getBirthYear() < pivot)\n {\n i++;\n }\n while (people[j].getBirthYear() > pivot)\n {\n j--;\n }\n if (i <= j)\n {\n tmp = people[i];\n people[i] = people[j];\n people[j] = tmp;\n i++;\n j--;\n }\n }\n}\n\nvoid DataLayer::sortByDeathYear()\n{\n int i = 0, j = people.size();\n Persons tmp;\n int pivot = people[people.size() \/ 2].getDeathYear();\n\n while (i <= j)\n {\n while (people[i].getDeathYear() < pivot)\n {\n i++;\n }\n while (people[j].getDeathYear() > pivot)\n {\n j--;\n }\n if (i <= j)\n {\n tmp = people[i];\n people[i] = people[j];\n people[j] = tmp;\n i++;\n j--;\n }\n }\n}\n\nvoid DataLayer::sortByGender()\n{\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, others 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#include <cassert>\n#include <climits>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <libxml\/xmlreader.h>\n\n#include <google\/sparse_hash_map>\n\n#include <stxxl\/mng>\n#include <stxxl\/ksort>\n#include <stxxl\/sort>\n#include <stxxl\/vector>\n#include <stxxl\/bits\/io\/syscall_file.h>\n\n#include \"typedefs.h\"\n#include \"DataStructures\/extractorStructs.h\"\n\nusing namespace std;\ntypedef google::dense_hash_map<NodeID, _Node> NodeMap;\n\n_Stats stats;\nSettings settings;\nvector<NodeID> SignalNodes;\n\nNodeMap * nodeMap = new NodeMap();\n\nint main (int argc, char *argv[])\n{\n\tif(argc <= 1)\n\t{\n\t\tcerr << \"usage: \" << endl << argv[0] << \" <file.osm>\" << endl;\n\t\texit(-1);\n\t}\n\tcout << \"reading input file. This may take some time ...\" << flush;\n\t\/*\n Default Speed Profile:\n motorway 120\n motorway_link 80\n trunk 100\n trunk_link 80\n secondary 100\n secondary_link 50\n primary 100\n primary_link 50\n tertiary 100\n unclassified 50\n residential 50\n living_street 30\n service 20\n\t *\/\n\tdouble time = get_timestamp();\n\tstring names[13] = { \"motorway\", \"motorway_link\", \"trunk\", \"trunk_link\", \"secondary\", \"secondary_link\", \"primary\", \"primary_link\", \"tertiary\", \"unclassified\", \"residential\", \"living_street\", \"service\" };\n\tdouble speeds[13] = { 120, 80, 100, 80, 100, 50, 100, 50, 100, 50, 50 , 30, 20};\n\tsettings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+13);\n\tsettings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+13);\n\n\txmlTextReaderPtr inputReader = xmlNewTextReaderFilename( argv[1] );\n\tofstream allNodeFile(\"_allnodes\", ios::binary);\n\tofstream usedNodesFile(\"_usednodes\", ios::binary);\n\tofstream wayFile(\"_ways\", ios::binary);\n\tnodeMap->set_empty_key(UINT_MAX);\n\ttry {\n\t\twhile ( xmlTextReaderRead( inputReader ) == 1 ) {\n\t\t\tconst int type = xmlTextReaderNodeType( inputReader );\n\n\t\t\t\/\/1 is Element\n\t\t\tif ( type != 1 )\n\t\t\t\tcontinue;\n\n\t\t\txmlChar* currentName = xmlTextReaderName( inputReader );\n\t\t\tif ( currentName == NULL )\n\t\t\t\tcontinue;\n\n\t\t\tif ( xmlStrEqual( currentName, ( const xmlChar* ) \"node\" ) == 1 ) {\n\t\t\t\tstats.numberOfNodes++;\n\t\t\t\t_Node node = _ReadXMLNode( inputReader );\n\t\t\t\tallNodeFile.write((char *)&node, sizeof(node));\/\/ << node.id << node.lat << node.lon << node.trafficSignal << endl;\n\n\t\t\t\tif ( node.trafficSignal )\n\t\t\t\t\tSignalNodes.push_back( node.id );\n\n\t\t\t}\n\t\t\telse if ( xmlStrEqual( currentName, ( const xmlChar* ) \"way\" ) == 1 ) {\n\t\t\t\tstats.numberOfWays++;\n\t\t\t\t_Way way = _ReadXMLWay( inputReader, settings, stats );\n\n\t\t\t\tif ( way.usefull && way.access && way.path.size() ) {\n\t\t\t\t\tfor ( unsigned i = 0; i < way.path.size(); ++i ) {\n\t\t\t\t\t\tusedNodesFile.write((char *)&way.path[i], sizeof(NodeID));\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( way.direction == _Way::opposite )\n\t\t\t\t\t\tstd::reverse( way.path.begin(), way.path.end() );\n\n\t\t\t\t\tstats.numberOfEdges += ( int ) way.path.size() - 1;\n\t\t\t\t\t{\n\t\t\t\t\t\tvector< NodeID > & path = way.path;\n\t\t\t\t\t\tdouble speed = way.maximumSpeed;\n\t\t\t\t\t\tassert(way.type > -1 || way.maximumSpeed != -1);\n\t\t\t\t\t\tassert(path.size()>0);\n\n\t\t\t\t\t\tfor(vector< NodeID >::size_type n = 0; n < path.size()-1; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/serialize edge (path[n], path[n+1])\n\t\t\t\t\t\t\twayFile.write((char*)&way.path[n], sizeof(NodeID));\n\t\t\t\t\t\t\twayFile.write((char*)&way.path[n+1], sizeof(NodeID));\n\t\t\t\t\t\t\twayFile.write((char*)&way.type, sizeof(short));\n\t\t\t\t\t\t\twayFile.write((char*)&way.direction, sizeof(short));\n\t\t\t\t\t\t\twayFile.write((char*)&way.maximumSpeed, sizeof(double));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\txmlFree( currentName );\n\t\t}\n\t\tallNodeFile.close();\n\t\tusedNodesFile.close();\n\t\twayFile.close();\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t\tunsigned memory_to_use = 1024 * 1024 * 1024;\n\n\t\tstxxl::syscall_file f(\"_usednodes\", stxxl::file::DIRECT | stxxl::file::RDWR);\n\t\ttypedef stxxl::vector<NodeID> usedNodesVectorType;\n\n\t\tusedNodesVectorType usedNodes( &f);\n\t\tcout << \"Sorting used nodes ...\" << flush;\n\t\tstxxl::sort(usedNodes.begin(), usedNodes.end(), Cmp(), memory_to_use);\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t\tcout << \"Erasing duplicate entries ...\" << flush;\n\t\tstxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodes.begin(),usedNodes.end() ) ;\n\t\tusedNodes.resize ( NewEnd - usedNodes.begin() );\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tstxxl::syscall_file fallnodes(\"_allnodes\", stxxl::file::DIRECT | stxxl::file::RDWR);\n\t\ttypedef stxxl::vector< _Node > second_vector_type;\n\n\t\tsecond_vector_type van(&fallnodes);\n\t\tcout << \"Sorting all nodes ...\" << flush;\n\t\tstxxl::ksort(van.begin(), van.end(), memory_to_use);\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tcout << endl << \"Statistics: \" << endl;\n\t\tcout << \"All Nodes: \" << stats.numberOfNodes << endl;\n\t\tcout << \"Used Nodes: \" << nodeMap->size() << endl;\n\t\tcout << \"Number of Ways: \" << stats.numberOfWays << endl;\n\t\tcout << \"Edges in graph: \" << stats.numberOfEdges << endl;\n\t\tcout << \"Number of ways with maxspeed information: \" << stats.numberOfMaxspeed << endl;\n\t\tcout << \"Number of nodes with traffic lights: \" << SignalNodes.size() << endl;\n\t\tcout << \"finished loading data\" << endl;\n\t\tcout << \"calculated edge weights and writing to disk ...\" << flush;\n\t\tstring name(argv[1]);\n\t\tint pos=name.find(\".osm\"); \/\/ pos=9\n\t\tif(pos!=string::npos)\n\t\t{\n\t\t\tname.replace(pos, 5, \".osrm\");\n\t\t} else {\n\t\t\tname.append(\".osrm\");\n\t\t}\n\n\t\tofstream fout;\n\t\tfout.open(name.c_str());\n\t\tifstream inall(\"_allnodes\", ios::binary);\n\t\tifstream inuse(\"_usednodes\", ios::binary);\n\t\tifstream inway(\"_ways\", ios::binary);\n\n\t\tcout << \"Writing used nodes ...\" << flush;\n\t\tfout << usedNodes.size() << endl;\n\t\tNodeID counter = 0;\n\t\tfor(usedNodesVectorType::iterator it = usedNodes.begin(); it!=usedNodes.end(); it++)\n\t\t{\n\t\t\tNodeID currentNodeID = *it;\n\t\t\t_Node current_Node;\n\t\t\tinall.read((char *)¤t_Node, sizeof(_Node));\n\t\t\twhile(currentNodeID!=current_Node.id)\n\t\t\t{\n\t\t\t\tinall.read((char *)¤t_Node, sizeof(_Node));\n\t\t\t}\n\t\t\tfout << current_Node.id<< \" \" << current_Node.lon << \" \" << current_Node.lat << \"\\n\";\n\t\t\tnodeMap->insert(std::make_pair(current_Node.id, current_Node));\n\t\t\tcounter++;\n\t\t}\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tcout << \"writing used ways ...\" << endl;\n\t\tNodeID start, target;\n\t\tshort type, direction;\n\t\tdouble maximumSpeed;\n\t\tfout << stats.numberOfEdges << \"\\n\";\n\t\twhile(!inway.eof())\n\t\t{\n\n\t\t\tinway.read((char*)&start, sizeof(NodeID));\n\t\t\tinway.read((char*)&target, sizeof(NodeID));\n\t\t\tinway.read((char*)&type, sizeof(short));\n\t\t\tinway.read((char*)&direction, sizeof(short));\n\t\t\tinway.read((char*)&maximumSpeed, sizeof(double));\n\t\t\tassert(type > -1 || maximumSpeed != -1);\n\n\t\t\tNodeMap::iterator startit = nodeMap->find(start);\n\t\t\tif(startit == nodeMap->end())\n\t\t\t{\n\t\t\t\tcerr << \"Node \" << start << \" missing albeit referenced in way. Edge skipped\" << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tNodeMap::iterator targetit = nodeMap->find(target);\n\n\t\t\tif(targetit == nodeMap->end())\n\t\t\t{\n\t\t\t\tcerr << \"Node << \" << target << \"missing albeit reference in a way. Edge skipped\" << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble distance = ApproximateDistance(startit->second.lat, startit->second.lon, targetit->second.lat, targetit->second.lon);\n\t\t\tif(maximumSpeed == -1)\n\t\t\t\tmaximumSpeed = settings.speedProfile.speed[type];\n\t\t\tdouble weight = ( distance * 10. ) \/ (maximumSpeed \/ 3.6);\n\t\t\tdouble intWeight = max(1, (int) weight);\n\t\t\tswitch(direction)\n\t\t\t{\n\t\t\tcase _Way::notSure:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 0 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::oneway:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 1 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::bidirectional:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 0 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::opposite:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 1 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tinway.close();\n\t\tfout.close();\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t} catch ( const std::exception& e ) {\n\t\tcerr << \"Caught Execption:\" << e.what() << endl;\n\t\treturn false;\n\t}\n\tSignalNodes.clear();\n\txmlFreeTextReader(inputReader);\n\n\tremove(\"_allnodes\");\n\tremove(\"_usednodes\");\n\tremove(\"_ways\");\n\treturn true;\n}\n\n<commit_msg>Replacing many includes by a single one<commit_after>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, others 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#include <cassert>\n#include <climits>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <libxml\/xmlreader.h>\n\n#include <google\/sparse_hash_map>\n\n#include <stxxl.h>\n\n#include \"typedefs.h\"\n#include \"DataStructures\/extractorStructs.h\"\n\nusing namespace std;\ntypedef google::dense_hash_map<NodeID, _Node> NodeMap;\n\n_Stats stats;\nSettings settings;\nvector<NodeID> SignalNodes;\n\nNodeMap * nodeMap = new NodeMap();\n\nint main (int argc, char *argv[])\n{\n\tif(argc <= 1)\n\t{\n\t\tcerr << \"usage: \" << endl << argv[0] << \" <file.osm>\" << endl;\n\t\texit(-1);\n\t}\n\tcout << \"reading input file. This may take some time ...\" << flush;\n\t\/*\n Default Speed Profile:\n motorway 120\n motorway_link 80\n trunk 100\n trunk_link 80\n secondary 100\n secondary_link 50\n primary 100\n primary_link 50\n tertiary 100\n unclassified 50\n residential 50\n living_street 30\n service 20\n\t *\/\n\tdouble time = get_timestamp();\n\tstring names[13] = { \"motorway\", \"motorway_link\", \"trunk\", \"trunk_link\", \"secondary\", \"secondary_link\", \"primary\", \"primary_link\", \"tertiary\", \"unclassified\", \"residential\", \"living_street\", \"service\" };\n\tdouble speeds[13] = { 120, 80, 100, 80, 100, 50, 100, 50, 100, 50, 50 , 30, 20};\n\tsettings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+13);\n\tsettings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+13);\n\n\txmlTextReaderPtr inputReader = xmlNewTextReaderFilename( argv[1] );\n\tofstream allNodeFile(\"_allnodes\", ios::binary);\n\tofstream usedNodesFile(\"_usednodes\", ios::binary);\n\tofstream wayFile(\"_ways\", ios::binary);\n\tnodeMap->set_empty_key(UINT_MAX);\n\ttry {\n\t\twhile ( xmlTextReaderRead( inputReader ) == 1 ) {\n\t\t\tconst int type = xmlTextReaderNodeType( inputReader );\n\n\t\t\t\/\/1 is Element\n\t\t\tif ( type != 1 )\n\t\t\t\tcontinue;\n\n\t\t\txmlChar* currentName = xmlTextReaderName( inputReader );\n\t\t\tif ( currentName == NULL )\n\t\t\t\tcontinue;\n\n\t\t\tif ( xmlStrEqual( currentName, ( const xmlChar* ) \"node\" ) == 1 ) {\n\t\t\t\tstats.numberOfNodes++;\n\t\t\t\t_Node node = _ReadXMLNode( inputReader );\n\t\t\t\tallNodeFile.write((char *)&node, sizeof(node));\/\/ << node.id << node.lat << node.lon << node.trafficSignal << endl;\n\n\t\t\t\tif ( node.trafficSignal )\n\t\t\t\t\tSignalNodes.push_back( node.id );\n\n\t\t\t}\n\t\t\telse if ( xmlStrEqual( currentName, ( const xmlChar* ) \"way\" ) == 1 ) {\n\t\t\t\tstats.numberOfWays++;\n\t\t\t\t_Way way = _ReadXMLWay( inputReader, settings, stats );\n\n\t\t\t\tif ( way.usefull && way.access && way.path.size() ) {\n\t\t\t\t\tfor ( unsigned i = 0; i < way.path.size(); ++i ) {\n\t\t\t\t\t\tusedNodesFile.write((char *)&way.path[i], sizeof(NodeID));\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( way.direction == _Way::opposite )\n\t\t\t\t\t\tstd::reverse( way.path.begin(), way.path.end() );\n\n\t\t\t\t\tstats.numberOfEdges += ( int ) way.path.size() - 1;\n\t\t\t\t\t{\n\t\t\t\t\t\tvector< NodeID > & path = way.path;\n\t\t\t\t\t\tdouble speed = way.maximumSpeed;\n\t\t\t\t\t\tassert(way.type > -1 || way.maximumSpeed != -1);\n\t\t\t\t\t\tassert(path.size()>0);\n\n\t\t\t\t\t\tfor(vector< NodeID >::size_type n = 0; n < path.size()-1; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/serialize edge (path[n], path[n+1])\n\t\t\t\t\t\t\twayFile.write((char*)&way.path[n], sizeof(NodeID));\n\t\t\t\t\t\t\twayFile.write((char*)&way.path[n+1], sizeof(NodeID));\n\t\t\t\t\t\t\twayFile.write((char*)&way.type, sizeof(short));\n\t\t\t\t\t\t\twayFile.write((char*)&way.direction, sizeof(short));\n\t\t\t\t\t\t\twayFile.write((char*)&way.maximumSpeed, sizeof(double));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\txmlFree( currentName );\n\t\t}\n\t\tallNodeFile.close();\n\t\tusedNodesFile.close();\n\t\twayFile.close();\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t\tunsigned memory_to_use = 1024 * 1024 * 1024;\n\n\t\tstxxl::syscall_file f(\"_usednodes\", stxxl::file::DIRECT | stxxl::file::RDWR);\n\t\ttypedef stxxl::vector<NodeID> usedNodesVectorType;\n\n\t\tusedNodesVectorType usedNodes( &f);\n\t\tcout << \"Sorting used nodes ...\" << flush;\n\t\tstxxl::sort(usedNodes.begin(), usedNodes.end(), Cmp(), memory_to_use);\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t\tcout << \"Erasing duplicate entries ...\" << flush;\n\t\tstxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodes.begin(),usedNodes.end() ) ;\n\t\tusedNodes.resize ( NewEnd - usedNodes.begin() );\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tstxxl::syscall_file fallnodes(\"_allnodes\", stxxl::file::DIRECT | stxxl::file::RDWR);\n\t\ttypedef stxxl::vector< _Node > second_vector_type;\n\n\t\tsecond_vector_type van(&fallnodes);\n\t\tcout << \"Sorting all nodes ...\" << flush;\n\t\tstxxl::ksort(van.begin(), van.end(), memory_to_use);\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tcout << endl << \"Statistics: \" << endl;\n\t\tcout << \"All Nodes: \" << stats.numberOfNodes << endl;\n\t\tcout << \"Used Nodes: \" << nodeMap->size() << endl;\n\t\tcout << \"Number of Ways: \" << stats.numberOfWays << endl;\n\t\tcout << \"Edges in graph: \" << stats.numberOfEdges << endl;\n\t\tcout << \"Number of ways with maxspeed information: \" << stats.numberOfMaxspeed << endl;\n\t\tcout << \"Number of nodes with traffic lights: \" << SignalNodes.size() << endl;\n\t\tcout << \"finished loading data\" << endl;\n\t\tcout << \"calculated edge weights and writing to disk ...\" << flush;\n\t\tstring name(argv[1]);\n\t\tint pos=name.find(\".osm\"); \/\/ pos=9\n\t\tif(pos!=string::npos)\n\t\t{\n\t\t\tname.replace(pos, 5, \".osrm\");\n\t\t} else {\n\t\t\tname.append(\".osrm\");\n\t\t}\n\n\t\tofstream fout;\n\t\tfout.open(name.c_str());\n\t\tifstream inall(\"_allnodes\", ios::binary);\n\t\tifstream inuse(\"_usednodes\", ios::binary);\n\t\tifstream inway(\"_ways\", ios::binary);\n\n\t\tcout << \"Writing used nodes ...\" << flush;\n\t\tfout << usedNodes.size() << endl;\n\t\tNodeID counter = 0;\n\t\tfor(usedNodesVectorType::iterator it = usedNodes.begin(); it!=usedNodes.end(); it++)\n\t\t{\n\t\t\tNodeID currentNodeID = *it;\n\t\t\t_Node current_Node;\n\t\t\tinall.read((char *)¤t_Node, sizeof(_Node));\n\t\t\twhile(currentNodeID!=current_Node.id)\n\t\t\t{\n\t\t\t\tinall.read((char *)¤t_Node, sizeof(_Node));\n\t\t\t}\n\t\t\tfout << current_Node.id<< \" \" << current_Node.lon << \" \" << current_Node.lat << \"\\n\";\n\t\t\tnodeMap->insert(std::make_pair(current_Node.id, current_Node));\n\t\t\tcounter++;\n\t\t}\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\n\t\tcout << \"writing used ways ...\" << endl;\n\t\tNodeID start, target;\n\t\tshort type, direction;\n\t\tdouble maximumSpeed;\n\t\tfout << stats.numberOfEdges << \"\\n\";\n\t\twhile(!inway.eof())\n\t\t{\n\n\t\t\tinway.read((char*)&start, sizeof(NodeID));\n\t\t\tinway.read((char*)&target, sizeof(NodeID));\n\t\t\tinway.read((char*)&type, sizeof(short));\n\t\t\tinway.read((char*)&direction, sizeof(short));\n\t\t\tinway.read((char*)&maximumSpeed, sizeof(double));\n\t\t\tassert(type > -1 || maximumSpeed != -1);\n\n\t\t\tNodeMap::iterator startit = nodeMap->find(start);\n\t\t\tif(startit == nodeMap->end())\n\t\t\t{\n\t\t\t\tcerr << \"Node \" << start << \" missing albeit referenced in way. Edge skipped\" << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tNodeMap::iterator targetit = nodeMap->find(target);\n\n\t\t\tif(targetit == nodeMap->end())\n\t\t\t{\n\t\t\t\tcerr << \"Node << \" << target << \"missing albeit reference in a way. Edge skipped\" << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble distance = ApproximateDistance(startit->second.lat, startit->second.lon, targetit->second.lat, targetit->second.lon);\n\t\t\tif(maximumSpeed == -1)\n\t\t\t\tmaximumSpeed = settings.speedProfile.speed[type];\n\t\t\tdouble weight = ( distance * 10. ) \/ (maximumSpeed \/ 3.6);\n\t\t\tdouble intWeight = max(1, (int) weight);\n\t\t\tswitch(direction)\n\t\t\t{\n\t\t\tcase _Way::notSure:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 0 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::oneway:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 1 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::bidirectional:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 0 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tcase _Way::opposite:\n\t\t\t\tfout << startit->first << \" \" << targetit->first << \" \" << max(1, (int)distance) << \" \" << 1 << \" \" << intWeight << \"\\n\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tinway.close();\n\t\tfout.close();\n\t\tcout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n\t\ttime = get_timestamp();\n\t} catch ( const std::exception& e ) {\n\t\tcerr << \"Caught Execption:\" << e.what() << endl;\n\t\treturn false;\n\t}\n\tSignalNodes.clear();\n\txmlFreeTextReader(inputReader);\n\n\tremove(\"_allnodes\");\n\tremove(\"_usednodes\");\n\tremove(\"_ways\");\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation, either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"NetIO\/Lobby.h\"\n#include \"NetIO\/CryptIO.h\"\n#include \"GateKeeper\/GateServ.h\"\n#include \"FileServ\/FileServer.h\"\n#include \"AuthServ\/AuthServer.h\"\n#include \"GameServ\/GameServer.h\"\n#include \"SDL\/DescriptorDb.h\"\n#include \"strings.h\"\n#include \"errors.h\"\n#include \"settings.h\"\n#include \"encodings.h\"\n#include <readline.h>\n#include <history.h>\n#include <signal.h>\n#include <execinfo.h>\n#include <cstdio>\n\n#ifdef DEBUG\nextern bool s_commdebug;\n#endif\n\nstatic char** dup_strlist(const char* text, const char** strlist, size_t count)\n{\n char** dupe;\n if (count == 1) {\n dupe = reinterpret_cast<char**>(malloc(sizeof(char*) * 2));\n dupe[0] = strdup(strlist[0]);\n dupe[1] = 0;\n } else {\n dupe = reinterpret_cast<char**>(malloc(sizeof(char*) * (count + 2)));\n dupe[0] = strdup(text);\n for (size_t i=0; i<count; ++i)\n dupe[i+1] = strdup(strlist[i]);\n dupe[count+1] = 0;\n }\n return dupe;\n}\n\nstatic char** console_completer(const char* text, int start, int end)\n{\n static const char* completions[] = {\n \/* Commands *\/\n \"clients\", \"commdebug\", \"help\", \"keygen\", \"quit\", \"restart\",\n \/* Services *\/\n \"auth\", \"lobby\",\n };\n\n rl_attempted_completion_over = true;\n if (strlen(text) == 0)\n return dup_strlist(text, completions, sizeof(completions) \/ sizeof(completions[0]));\n\n std::vector<const char*> matches;\n for (size_t i=0; i<sizeof(completions) \/ sizeof(completions[0]); ++i) {\n if (strncmp(text, completions[i], strlen(text)) == 0)\n matches.push_back(completions[i]);\n }\n if (matches.size() == 0)\n return 0;\n return dup_strlist(text, matches.data(), matches.size());\n}\n\nstatic void print_trace(const char* text)\n{\n const size_t max_depth = 100;\n size_t stack_depth;\n void* stack_addrs[max_depth];\n char** stack_strings;\n\n stack_depth = backtrace(stack_addrs, max_depth);\n stack_strings = backtrace_symbols(stack_addrs, stack_depth);\n\n fprintf(stderr, \"%s at %s\\n\", text, stack_strings[0]);\n for (size_t i=1; i<stack_depth; ++i)\n fprintf(stderr, \" from %s\\n\", stack_strings[i]);\n free(stack_strings);\n}\n\nstatic void sigh_segv(int)\n{\n print_trace(\"Segfault\");\n abort();\n}\n\nstatic void exception_filter()\n{\n print_trace(\"Unhandled exception\");\n abort();\n}\n\nint main(int argc, char* argv[])\n{\n if (argc == 1) {\n fprintf(stderr, \"Warning: No config file specified. Using defaults...\\n\");\n DS::Settings::UseDefaults();\n } else if (!DS::Settings::LoadFrom(argv[1])) {\n return 1;\n }\n\n \/\/ Show a stackdump in case we crash\n std::set_terminate(&exception_filter);\n signal(SIGSEGV, &sigh_segv);\n\n \/\/ Ignore sigpipe and force send() to return EPIPE\n signal(SIGPIPE, SIG_IGN);\n\n SDL::DescriptorDb::LoadDescriptors(DS::Settings::SdlPath());\n DS::FileServer_Init();\n DS::AuthServer_Init();\n DS::GameServer_Init();\n DS::GateKeeper_Init();\n DS::StartLobby();\n\n char* cmdbuf = 0;\n rl_attempted_completion_function = &console_completer;\n for ( ;; ) {\n cmdbuf = readline(\"\");\n if (!cmdbuf)\n break;\n\n std::vector<DS::String> args = DS::String(cmdbuf).strip('#').split();\n if (args.size() == 0) {\n free(cmdbuf);\n continue;\n }\n add_history(cmdbuf);\n free(cmdbuf);\n\n if (args[0] == \"quit\") {\n break;\n } else if (args[0] == \"restart\") {\n if (args.size() < 2) {\n fprintf(stderr, \"Error: No services specified\\n\");\n continue;\n }\n for (std::vector<DS::String>::iterator svc = args.begin() + 1;\n svc != args.end(); ++svc) {\n if (*svc == \"lobby\") {\n DS::StopLobby();\n DS::StartLobby();\n } else if (*svc == \"auth\") {\n DS::AuthServer_Shutdown();\n DS::AuthServer_Init();\n printf(\"Auth server restarted\\n\");\n } else {\n fprintf(stderr, \"Error: Service %s cannot be restarted\\n\", svc->c_str());\n }\n }\n } else if (args[0] == \"keygen\") {\n uint8_t xbuffer[64];\n if (args.size() != 2) {\n fprintf(stderr, \"Please specify new, ue or pc\\n\");\n } else if (args[1] == \"new\") {\n uint8_t nbuffer[3][64], kbuffer[3][64];\n printf(\"Generating new server keys... This will take a while.\");\n fflush(stdout);\n for (size_t i=0; i<3; ++i)\n DS::GenPrimeKeys(nbuffer[i], kbuffer[i]);\n\n printf(\"\\n--------------------\\n\");\n printf(\"Server keys:\\n\");\n printf(\"Key.Auth.N = %s\\n\", DS::Base64Encode(nbuffer[0], 64).c_str());\n printf(\"Key.Auth.K = %s\\n\", DS::Base64Encode(kbuffer[0], 64).c_str());\n printf(\"Key.Game.N = %s\\n\", DS::Base64Encode(nbuffer[1], 64).c_str());\n printf(\"Key.Game.K = %s\\n\", DS::Base64Encode(kbuffer[1], 64).c_str());\n printf(\"Key.Gate.N = %s\\n\", DS::Base64Encode(nbuffer[2], 64).c_str());\n printf(\"Key.Gate.K = %s\\n\", DS::Base64Encode(kbuffer[2], 64).c_str());\n\n printf(\"--------------------\\n\");\n printf(\"UruExplorer:\\n\");\n printf(\"Auth client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[0], kbuffer[0], CRYPT_BASE_AUTH);\n DS::PrintClientKeys(xbuffer, nbuffer[0]);\n\n printf(\"Game client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[1], kbuffer[1], CRYPT_BASE_GAME);\n DS::PrintClientKeys(xbuffer, nbuffer[1]);\n\n printf(\"GateKeeper client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[2], kbuffer[2], CRYPT_BASE_GATE);\n DS::PrintClientKeys(xbuffer, nbuffer[2]);\n\n printf(\"--------------------\\n\");\n printf(\"PlasmaClient:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[0], kbuffer[0], CRYPT_BASE_AUTH);\n printf(\"Server.Auth.N %s\\n\", DS::Base64Encode(nbuffer[0], 64).c_str());\n printf(\"Server.Auth.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, nbuffer[1], kbuffer[1], CRYPT_BASE_GAME);\n printf(\"Server.Game.N %s\\n\", DS::Base64Encode(nbuffer[1], 64).c_str());\n printf(\"Server.Game.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, nbuffer[2], kbuffer[2], CRYPT_BASE_GATE);\n printf(\"Server.Gate.N %s\\n\", DS::Base64Encode(nbuffer[2], 64).c_str());\n printf(\"Server.Gate.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n printf(\"--------------------\\n\");\n } else if (args[1] == \"ue\") {\n uint8_t xbuffer[64];\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N),\n DS::Settings::CryptKey(DS::e_KeyAuth_K), CRYPT_BASE_AUTH);\n printf(\"Auth client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N));\n\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), CRYPT_BASE_GAME);\n printf(\"Game client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N));\n\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N),\n DS::Settings::CryptKey(DS::e_KeyGate_K), CRYPT_BASE_GATE);\n printf(\"GateKeeper client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N));\n } else if (args[1] == \"pc\") {\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N),\n DS::Settings::CryptKey(DS::e_KeyAuth_K), CRYPT_BASE_AUTH);\n printf(\"Server.Auth.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyAuth_N), 64).c_str());\n printf(\"Server.Auth.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), CRYPT_BASE_GAME);\n printf(\"Server.Game.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyGame_N), 64).c_str());\n printf(\"Server.Game.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N),\n DS::Settings::CryptKey(DS::e_KeyGate_K), CRYPT_BASE_GATE);\n printf(\"Server.Gate.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyGate_N), 64).c_str());\n printf(\"Server.Gate.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n } else {\n fprintf(stderr, \"Error: %s is not a valid keygen target\\n\", args[1].c_str());\n continue;\n }\n } else if (args[0] == \"clients\") {\n DS::GateKeeper_DisplayClients();\n DS::FileServer_DisplayClients();\n DS::AuthServer_DisplayClients();\n DS::GameServer_DisplayClients();\n } else if (args[0] == \"commdebug\") {\n#ifdef DEBUG\n if (args.size() == 1)\n printf(\"Comm debugging is currently %s\\n\", s_commdebug ? \"on\" : \"off\");\n else if (args[1] == \"on\")\n s_commdebug = true;\n else if (args[1] == \"off\")\n s_commdebug = false;\n else\n fprintf(stderr, \"Error: must specify on or off\\n\");\n#else\n fprintf(stderr, \"Error: COMM debugging is only enabled in debug builds\\n\");\n#endif\n } else if (args[0] == \"help\") {\n printf(\"DirtSand v1.0 Console supported commands:\\n\"\n \" clients\\n\"\n \" commdebug <on|off>\\n\"\n \" help\\n\"\n \" keygen <new|ue|pc>\\n\"\n \" quit\\n\"\n \" restart <auth|lobby>\\n\"\n );\n } else {\n fprintf(stderr, \"Error: Unrecognized command: %s\\n\", args[0].c_str());\n }\n }\n\n DS::StopLobby();\n DS::GateKeeper_Shutdown();\n DS::GameServer_Shutdown();\n DS::AuthServer_Shutdown();\n DS::FileServer_Shutdown();\n return 0;\n}\n<commit_msg>Change key output to the correct console command<commit_after>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation, either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"NetIO\/Lobby.h\"\n#include \"NetIO\/CryptIO.h\"\n#include \"GateKeeper\/GateServ.h\"\n#include \"FileServ\/FileServer.h\"\n#include \"AuthServ\/AuthServer.h\"\n#include \"GameServ\/GameServer.h\"\n#include \"SDL\/DescriptorDb.h\"\n#include \"strings.h\"\n#include \"errors.h\"\n#include \"settings.h\"\n#include \"encodings.h\"\n#include <readline.h>\n#include <history.h>\n#include <signal.h>\n#include <execinfo.h>\n#include <cstdio>\n\n#ifdef DEBUG\nextern bool s_commdebug;\n#endif\n\nstatic char** dup_strlist(const char* text, const char** strlist, size_t count)\n{\n char** dupe;\n if (count == 1) {\n dupe = reinterpret_cast<char**>(malloc(sizeof(char*) * 2));\n dupe[0] = strdup(strlist[0]);\n dupe[1] = 0;\n } else {\n dupe = reinterpret_cast<char**>(malloc(sizeof(char*) * (count + 2)));\n dupe[0] = strdup(text);\n for (size_t i=0; i<count; ++i)\n dupe[i+1] = strdup(strlist[i]);\n dupe[count+1] = 0;\n }\n return dupe;\n}\n\nstatic char** console_completer(const char* text, int start, int end)\n{\n static const char* completions[] = {\n \/* Commands *\/\n \"clients\", \"commdebug\", \"help\", \"keygen\", \"quit\", \"restart\",\n \/* Services *\/\n \"auth\", \"lobby\",\n };\n\n rl_attempted_completion_over = true;\n if (strlen(text) == 0)\n return dup_strlist(text, completions, sizeof(completions) \/ sizeof(completions[0]));\n\n std::vector<const char*> matches;\n for (size_t i=0; i<sizeof(completions) \/ sizeof(completions[0]); ++i) {\n if (strncmp(text, completions[i], strlen(text)) == 0)\n matches.push_back(completions[i]);\n }\n if (matches.size() == 0)\n return 0;\n return dup_strlist(text, matches.data(), matches.size());\n}\n\nstatic void print_trace(const char* text)\n{\n const size_t max_depth = 100;\n size_t stack_depth;\n void* stack_addrs[max_depth];\n char** stack_strings;\n\n stack_depth = backtrace(stack_addrs, max_depth);\n stack_strings = backtrace_symbols(stack_addrs, stack_depth);\n\n fprintf(stderr, \"%s at %s\\n\", text, stack_strings[0]);\n for (size_t i=1; i<stack_depth; ++i)\n fprintf(stderr, \" from %s\\n\", stack_strings[i]);\n free(stack_strings);\n}\n\nstatic void sigh_segv(int)\n{\n print_trace(\"Segfault\");\n abort();\n}\n\nstatic void exception_filter()\n{\n print_trace(\"Unhandled exception\");\n abort();\n}\n\nint main(int argc, char* argv[])\n{\n if (argc == 1) {\n fprintf(stderr, \"Warning: No config file specified. Using defaults...\\n\");\n DS::Settings::UseDefaults();\n } else if (!DS::Settings::LoadFrom(argv[1])) {\n return 1;\n }\n\n \/\/ Show a stackdump in case we crash\n std::set_terminate(&exception_filter);\n signal(SIGSEGV, &sigh_segv);\n\n \/\/ Ignore sigpipe and force send() to return EPIPE\n signal(SIGPIPE, SIG_IGN);\n\n SDL::DescriptorDb::LoadDescriptors(DS::Settings::SdlPath());\n DS::FileServer_Init();\n DS::AuthServer_Init();\n DS::GameServer_Init();\n DS::GateKeeper_Init();\n DS::StartLobby();\n\n char* cmdbuf = 0;\n rl_attempted_completion_function = &console_completer;\n for ( ;; ) {\n cmdbuf = readline(\"\");\n if (!cmdbuf)\n break;\n\n std::vector<DS::String> args = DS::String(cmdbuf).strip('#').split();\n if (args.size() == 0) {\n free(cmdbuf);\n continue;\n }\n add_history(cmdbuf);\n free(cmdbuf);\n\n if (args[0] == \"quit\") {\n break;\n } else if (args[0] == \"restart\") {\n if (args.size() < 2) {\n fprintf(stderr, \"Error: No services specified\\n\");\n continue;\n }\n for (std::vector<DS::String>::iterator svc = args.begin() + 1;\n svc != args.end(); ++svc) {\n if (*svc == \"lobby\") {\n DS::StopLobby();\n DS::StartLobby();\n } else if (*svc == \"auth\") {\n DS::AuthServer_Shutdown();\n DS::AuthServer_Init();\n printf(\"Auth server restarted\\n\");\n } else {\n fprintf(stderr, \"Error: Service %s cannot be restarted\\n\", svc->c_str());\n }\n }\n } else if (args[0] == \"keygen\") {\n uint8_t xbuffer[64];\n if (args.size() != 2) {\n fprintf(stderr, \"Please specify new, ue or pc\\n\");\n } else if (args[1] == \"new\") {\n uint8_t nbuffer[3][64], kbuffer[3][64];\n printf(\"Generating new server keys... This will take a while.\");\n fflush(stdout);\n for (size_t i=0; i<3; ++i)\n DS::GenPrimeKeys(nbuffer[i], kbuffer[i]);\n\n printf(\"\\n--------------------\\n\");\n printf(\"Server keys:\\n\");\n printf(\"Server.Auth.N = %s\\n\", DS::Base64Encode(nbuffer[0], 64).c_str());\n printf(\"Server.Auth.K = %s\\n\", DS::Base64Encode(kbuffer[0], 64).c_str());\n printf(\"Server.Game.N = %s\\n\", DS::Base64Encode(nbuffer[1], 64).c_str());\n printf(\"Server.Game.K = %s\\n\", DS::Base64Encode(kbuffer[1], 64).c_str());\n printf(\"Server.Gate.N = %s\\n\", DS::Base64Encode(nbuffer[2], 64).c_str());\n printf(\"Server.Gate.K = %s\\n\", DS::Base64Encode(kbuffer[2], 64).c_str());\n\n printf(\"--------------------\\n\");\n printf(\"UruExplorer:\\n\");\n printf(\"Auth client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[0], kbuffer[0], CRYPT_BASE_AUTH);\n DS::PrintClientKeys(xbuffer, nbuffer[0]);\n\n printf(\"Game client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[1], kbuffer[1], CRYPT_BASE_GAME);\n DS::PrintClientKeys(xbuffer, nbuffer[1]);\n\n printf(\"GateKeeper client keys:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[2], kbuffer[2], CRYPT_BASE_GATE);\n DS::PrintClientKeys(xbuffer, nbuffer[2]);\n\n printf(\"--------------------\\n\");\n printf(\"PlasmaClient:\\n\");\n DS::CryptCalcX(xbuffer, nbuffer[0], kbuffer[0], CRYPT_BASE_AUTH);\n printf(\"Server.Auth.N %s\\n\", DS::Base64Encode(nbuffer[0], 64).c_str());\n printf(\"Server.Auth.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, nbuffer[1], kbuffer[1], CRYPT_BASE_GAME);\n printf(\"Server.Game.N %s\\n\", DS::Base64Encode(nbuffer[1], 64).c_str());\n printf(\"Server.Game.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, nbuffer[2], kbuffer[2], CRYPT_BASE_GATE);\n printf(\"Server.Gate.N %s\\n\", DS::Base64Encode(nbuffer[2], 64).c_str());\n printf(\"Server.Gate.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n printf(\"--------------------\\n\");\n } else if (args[1] == \"ue\") {\n uint8_t xbuffer[64];\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N),\n DS::Settings::CryptKey(DS::e_KeyAuth_K), CRYPT_BASE_AUTH);\n printf(\"Auth client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N));\n\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), CRYPT_BASE_GAME);\n printf(\"Game client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N));\n\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N),\n DS::Settings::CryptKey(DS::e_KeyGate_K), CRYPT_BASE_GATE);\n printf(\"GateKeeper client keys:\\n\");\n DS::PrintClientKeys(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N));\n } else if (args[1] == \"pc\") {\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyAuth_N),\n DS::Settings::CryptKey(DS::e_KeyAuth_K), CRYPT_BASE_AUTH);\n printf(\"Server.Auth.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyAuth_N), 64).c_str());\n printf(\"Server.Auth.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), CRYPT_BASE_GAME);\n printf(\"Server.Game.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyGame_N), 64).c_str());\n printf(\"Server.Game.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n DS::CryptCalcX(xbuffer, DS::Settings::CryptKey(DS::e_KeyGate_N),\n DS::Settings::CryptKey(DS::e_KeyGate_K), CRYPT_BASE_GATE);\n printf(\"Server.Gate.N %s\\n\", DS::Base64Encode(DS::Settings::CryptKey(DS::e_KeyGate_N), 64).c_str());\n printf(\"Server.Gate.X %s\\n\", DS::Base64Encode(xbuffer, 64).c_str());\n } else {\n fprintf(stderr, \"Error: %s is not a valid keygen target\\n\", args[1].c_str());\n continue;\n }\n } else if (args[0] == \"clients\") {\n DS::GateKeeper_DisplayClients();\n DS::FileServer_DisplayClients();\n DS::AuthServer_DisplayClients();\n DS::GameServer_DisplayClients();\n } else if (args[0] == \"commdebug\") {\n#ifdef DEBUG\n if (args.size() == 1)\n printf(\"Comm debugging is currently %s\\n\", s_commdebug ? \"on\" : \"off\");\n else if (args[1] == \"on\")\n s_commdebug = true;\n else if (args[1] == \"off\")\n s_commdebug = false;\n else\n fprintf(stderr, \"Error: must specify on or off\\n\");\n#else\n fprintf(stderr, \"Error: COMM debugging is only enabled in debug builds\\n\");\n#endif\n } else if (args[0] == \"help\") {\n printf(\"DirtSand v1.0 Console supported commands:\\n\"\n \" clients\\n\"\n \" commdebug <on|off>\\n\"\n \" help\\n\"\n \" keygen <new|ue|pc>\\n\"\n \" quit\\n\"\n \" restart <auth|lobby>\\n\"\n );\n } else {\n fprintf(stderr, \"Error: Unrecognized command: %s\\n\", args[0].c_str());\n }\n }\n\n DS::StopLobby();\n DS::GateKeeper_Shutdown();\n DS::GameServer_Shutdown();\n DS::AuthServer_Shutdown();\n DS::FileServer_Shutdown();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"macros.hpp\"\n#include \"ConfigParser.hpp\"\n#include \"FileUtils.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/parsers.hpp>\n\nnamespace po = boost::program_options;\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nCOLD ConfigParser::ConfigParser(int argc, char** argv) {\n \/\/ Declare the supported options.\n po::options_description desc(\"Options\");\n string configFileName;\n repEndpoints = {\"tcp:\/\/localhost:7100\",\"ipc:\/\/\/tmp\/yakserver-rep\"};\n pullEndpoints = {\"tcp:\/\/localhost:7101\",\"ipc:\/\/\/tmp\/yakserver-pull\"};\n subEndpoints = {\"tcp:\/\/localhost:7102\",\"ipc:\/\/\/tmp\/yakserver-sub\"};\n desc.add_options()\n (\"help\", \"Print help message\")\n (\"l,logfile\", po::value<string>(&logFile)->default_value(\"\"), \"The file the log will be written to\")\n (\"c,config\",\n po::value<string>(&configFileName)->default_value(\"yak.cfg\"),\n \"The configuration file to use\")\n (\"req-endpoint\", \n po::value<vector<string> >(&repEndpoints),\n \"The endpoints the REP backend will bind to.\\nDefaults to tcp:\/\/localhost:7100, ipc:\/\/\/tmp\/yakserver-rep\")\n (\"pull-endpoint\", po::value<vector<string> >(&pullEndpoints),\n \"The endpoints the PULL backend will bind to.\\nDefaults to tcp:\/\/localhost:7101, ipc:\/\/\/tmp\/yakserver-pull\")\n (\"sub-endpoint\", po::value<vector<string> >(&pullEndpoints),\n \"The endpoints the SUB backend will bind to.\\nDefaults to tcp:\/\/localhost:7102, ipc:\/\/\/tmp\/yakserver-sub\")\n ;\n \n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n \/\/Parse the config file\n if(fexists(configFileName)) {\n po::store(po::parse_config_file<char>(configFileName.c_str(), desc, true), vm);\n }\n po::notify(vm);\n \n if (vm.count(\"help\")) {\n cout << desc << endl;\n exit(1);\n }\n}\n\nconst std::string& ConfigParser::getLogFile() {\n return logFile;\n}\n\nconst std::vector<std::string>& ConfigParser::getREPEndpoints() {\n return repEndpoints;\n}\n\nconst std::vector<std::string>& ConfigParser::getPullEndpoints() {\n return pullEndpoints;\n}\n\nconst std::vector<std::string>& ConfigParser::getSubEndpoints() {\n return subEndpoints;\n}<commit_msg>Started to add more config stuff<commit_after>#include \"macros.hpp\"\n#include \"ConfigParser.hpp\"\n#include \"FileUtils.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/parsers.hpp>\n\nnamespace po = boost::program_options;\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nCOLD ConfigParser::ConfigParser(int argc, char** argv) {\n \/\/ Declare the supported options.\n po::options_description desc(\"Options\");\n string configFileName;\n repEndpoints = {\"tcp:\/\/localhost:7100\",\"ipc:\/\/\/tmp\/yakserver-rep\"};\n pullEndpoints = {\"tcp:\/\/localhost:7101\",\"ipc:\/\/\/tmp\/yakserver-pull\"};\n subEndpoints = {\"tcp:\/\/localhost:7102\",\"ipc:\/\/\/tmp\/yakserver-sub\"};\n desc.add_options()\n (\"help\", \"Print help message\")\n (\"logfile,l\", po::value<string>(&logFile)->default_value(\"\"), \"The file the log will be written to\")\n (\"config,c\",\n po::value<string>(&configFileName)->default_value(\"yak.cfg\"),\n \"The configuration file to use\")\n (\"req-endpoint\", \n po::value<vector<string> >(&repEndpoints),\n \"The endpoints the REP backend will bind to.\\nDefaults to tcp:\/\/localhost:7100, ipc:\/\/\/tmp\/yakserver-rep\")\n (\"pull-endpoint\", po::value<vector<string> >(&pullEndpoints),\n \"The endpoints the PULL backend will bind to.\\nDefaults to tcp:\/\/localhost:7101, ipc:\/\/\/tmp\/yakserver-pull\")\n (\"sub-endpoint\", po::value<vector<string> >(&pullEndpoints),\n \"The endpoints the SUB backend will bind to.\\nDefaults to tcp:\/\/localhost:7102, ipc:\/\/\/tmp\/yakserver-sub\")\n ;\n \n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n \/\/Parse the config file\n if(fexists(configFileName)) {\n po::store(po::parse_config_file<char>(configFileName.c_str(), desc, true), vm);\n }\n po::notify(vm);\n \n if (vm.count(\"help\")) {\n cout << desc << endl;\n exit(1);\n }\n}\n\nconst std::string& ConfigParser::getLogFile() {\n return logFile;\n}\n\nconst std::vector<std::string>& ConfigParser::getREPEndpoints() {\n return repEndpoints;\n}\n\nconst std::vector<std::string>& ConfigParser::getPullEndpoints() {\n return pullEndpoints;\n}\n\nconst std::vector<std::string>& ConfigParser::getSubEndpoints() {\n return subEndpoints;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <vector>\n#include \"inventory.h\"\n#include \"db.h\"\n#include \"book.h\"\nusing namespace std;\n\n#define DEFAULT_INV_FILE \"tools\/books.db\"\n\nInventory::Inventory() { m_db = NULL; }\nInventory::Inventory(DB::Database* db) { m_db = db; }\n\nInventory::~Inventory() {\n if(m_db != NULL) delete m_db;\n}\n\nvoid Inventory::setDatabase(DB::Database* db) {\n try {\n if(db == NULL) throw domain_error(\"Argument is NULL\");\n m_db = db;\n return;\n } catch(exception& e) {\n cerr << \"Inventory::setDatabase: \" << e.what() << endl;\n return;\n }\n}\n\nvoid Inventory::setDatabaseFile(string filename = DEFAULT_INV_FILE) {\n try {\n if(filename == \"\") throw domain_error(\"Argument is empty\");\n m_dbFileName = filename;\n return;\n } catch(exception& e) {\n cerr << \"Inventory::setDatabaseFile: \" << e.what() << endl;\n return;\n }\n}\n\n\/\/ Mutators\nbool Inventory::addBook(Book* book) {\n try {\n if(book == NULL) throw domain_error(\"Domain Error: Argument is NULL\");\n\n \/\/ TODO: Issue #26: Should change quantity if book exists\n \/\/ Add book to list, for writing to file later\n m_addList.push_back(book);\n } catch(exception& e) {\n cerr << \"Inventory::addBook: \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::updBook(Book* book) {\n try {\n vector<unsigned>::iterator first = m_deltaList.begin();\n vector<unsigned>::iterator last = m_deltaList.end();\n\n \/\/ if file index does not exist in delta list\n if(find(first, last, book->getFileIndex()) == last) {\n \/\/ Push index to delta list\n m_deltaList.push_back(book->getFileIndex());\n }\n } catch(exception& e) {\n cerr << \"Inventory::updBook(): \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::delBook(Book* book) {\n try {\n vector<unsigned>::iterator first = m_deleteList.begin();\n vector<unsigned>::iterator last = m_deleteList.end();\n\n \/\/ if file index does not exist in delete list\n if(find(first, last, book->getFileIndex()) == last) {\n \/\/ Push index to delta list\n m_deleteList.push_back(book->getFileIndex());\n return true;\n } else {\n return false;\n }\n } catch(exception& e) {\n cerr << \"Inventory::delBook(): \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::sync() {\n try {\n \/\/ Open database\n m_db->open(DEFAULT_INV_FILE);\n\n \/\/ for elements in delta list\n for(unsigned i = 0; i < m_deltaList.size(); i++) {\n \/\/ Find book by index\n Book* temp = getBook(m_deltaList[i]);\n \/\/ Write book to record\n \/\/if(!m_db->change(temp)) throw runtime_error(\"Could not modify database\");\n }\n\n\n \/\/ Sort delete list in reverse... order matters when deleting from arrays!\n sort(m_deleteList.begin(), m_deleteList.end());\n reverse(m_deleteList.begin(), m_deleteList.end()); \/\/ TODO: Inefficient...?\n \/\/for(unsigned i = m_deleteList.size(); i >= 0; i--) {\n \/\/Book* temp = getBook(m_deleteList[i]);\n \/\/\/\/if(!m_db->remove(temp)) throw runtime_error(\"Could not remove from database\");\n \/\/delete temp; \/\/ Deallocate\n \/\/m_deleteList.erase(m_deleteList.begin() + i); \/\/ Erase from vector\n \/\/}\n\n\n \/\/ for elements in add list\n for(unsigned i = 0; i < m_addList.size(); i++) {\n \/\/ Push element to book list\n m_bookList.push_back(m_addList[i]);\n \/\/ Write book to database\n \/\/if(!m_db->add(m_addList[i])) throw runtime_error(\"Could not add to database\");\n }\n\n m_db->close();\n reset();\n return true;\n } catch(exception& e) {\n cerr << \"Inventory::sync: \" << e.what() << endl;\n return false;\n }\n}\n\nbool Inventory::reset() {\n try {\n \/\/ Clear delta list, add list, and delete list\n m_deltaList.clear(); m_addList.clear(); m_deleteList.clear();\n clearBookList(); \/\/ Clear book list\n\n \/\/ Open database\n m_db->open(DEFAULT_INV_FILE);\n m_db->start(); \/\/ Start reading from beginning\n\n while(!m_db->eof()) {\n Book buffer; \/\/ Create temporary book (on stack)\n if(m_db->read(&buffer)) {\n \/\/ Read record into book, and if succeeds...?\n Book* book = new Book; \/\/ Create new book (on heap)\n *book = buffer; \/\/ Copy buffer book to new\n m_bookList.push_back(book); \/\/ Push to book list\n } else {\n throw runtime_error(\"Unable to read record\");\n }\n }\n\n m_db->close(); \/\/ Close database\n return true;\n } catch(exception& e) {\n cerr << \"Inventory::reset(): \" << e.what() << endl;\n return false;\n }\n}\n\nunsigned Inventory::getSize() {\n \/\/ Return number of books in inventory\n return m_bookList.size();\n}\n\nvector<Book*> Inventory::getRange(int first, int last) {\n \/\/ Create empty book list\n vector<Book*> retval;\n\n try {\n if(first >= last) throw domain_error(\"Domain Error: first >= last\");\n\n \/\/ check if first\/last are within book list bounds\n \/\/ Auto throws out of range exception\n m_bookList.at(first);\n m_bookList.at(last);\n\n \/\/ Assign empty vector with bounds from book list\n vector<Book*> sub(m_bookList.begin() + first, m_bookList.begin() + last);\n retval = sub;\n\n } catch(exception &e) {\n cerr << \"Inventory::getRange: \" << e.what() << endl;\n }\n return retval;\n}\n\nvector<Book*> Inventory::findBook(Book::field field, void* search) {\n \/\/ Create temp book list\n vector<Book*> retval;\n\n \/\/ for all books in book list\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n Book* book = m_bookList[i];\n switch(field) {\n case Book::ISBN:\n if(book->getISBN() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::TITLE:\n if(book->getTitle() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::AUTHOR:\n if(book->getAuthor() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::QUANTITY:\n if(book->getQuantity() == *((int*) search))\n retval.push_back(book);\n break;\n case Book::WHOLECOST:\n if(book->getWholeCost() == *((double*) search))\n retval.push_back(book);\n break;\n case Book::RETAILPRICE:\n if(book->getRetailPrice() == *((double*) search))\n retval.push_back(book);\n break;\n case Book::DATEADDED:\n if(book->getDateAdded() == *((date*) search))\n retval.push_back(book);\n break;\n default:\n break;\n }\n }\n return retval;\n}\n\n\n\n\n\n\/\/ Private methods\nBook* Inventory::getBook(unsigned index) {\n try {\n if(index >= m_bookList.size()) throw out_of_range(\"Out of Range\");\n\n \/\/ For all items in book list\n \/\/ TODO: critical: book file indices must start at 0, not 1\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n if(m_bookList[i]->getFileIndex() == index)\n return m_bookList[i];\n }\n\n return NULL;\n } catch(exception& e) {\n cerr << \"Inventory::getBook: \" << e.what() << endl;\n return NULL;\n }\n}\n\nvoid Inventory::clearBookList() {\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n delete m_bookList[i];\n }\n}\n<commit_msg>#31: Inventory adds to quantity<commit_after>#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <vector>\n#include \"inventory.h\"\n#include \"db.h\"\n#include \"book.h\"\nusing namespace std;\n\n#define DEFAULT_INV_FILE \"tools\/books.db\"\n\nInventory::Inventory() { m_db = NULL; }\nInventory::Inventory(DB::Database* db) { m_db = db; }\n\nInventory::~Inventory() {\n if(m_db != NULL) delete m_db;\n}\n\nvoid Inventory::setDatabase(DB::Database* db) {\n try {\n if(db == NULL) throw domain_error(\"Argument is NULL\");\n m_db = db;\n return;\n } catch(exception& e) {\n cerr << \"Inventory::setDatabase: \" << e.what() << endl;\n return;\n }\n}\n\nvoid Inventory::setDatabaseFile(string filename = DEFAULT_INV_FILE) {\n try {\n if(filename == \"\") throw domain_error(\"Argument is empty\");\n m_dbFileName = filename;\n return;\n } catch(exception& e) {\n cerr << \"Inventory::setDatabaseFile: \" << e.what() << endl;\n return;\n }\n}\n\n\/\/ Mutators\nbool Inventory::addBook(Book* book) {\n try {\n if(book == NULL) throw domain_error(\"Domain Error: Argument is NULL\");\n\n \/\/ ISBN numbers are unique: search if exists\n \/\/ Only add to FIRST book found\n vector<Book*> search = findBook(Book::ISBN, &(book->getISBN()));\n if(search.empty()) {\n \/\/ Add book to list, for writing to file later\n m_addList.push_back(book);\n } else {\n \/\/ Change quantity of found book\n search[0]->setQuantity( search[0]->getQuantity() + 1);\n \/\/ Mark book for update\n updBook(search[0]);\n }\n } catch(exception& e) {\n cerr << \"Inventory::addBook: \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::updBook(Book* book) {\n try {\n vector<unsigned>::iterator first = m_deltaList.begin();\n vector<unsigned>::iterator last = m_deltaList.end();\n\n \/\/ if file index does not exist in delta list\n if(find(first, last, book->getFileIndex()) == last) {\n \/\/ Push index to delta list\n m_deltaList.push_back(book->getFileIndex());\n }\n } catch(exception& e) {\n cerr << \"Inventory::updBook(): \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::delBook(Book* book) {\n try {\n vector<unsigned>::iterator first = m_deleteList.begin();\n vector<unsigned>::iterator last = m_deleteList.end();\n\n \/\/ if file index does not exist in delete list\n if(find(first, last, book->getFileIndex()) == last) {\n \/\/ Push index to delta list\n m_deleteList.push_back(book->getFileIndex());\n return true;\n } else {\n return false;\n }\n } catch(exception& e) {\n cerr << \"Inventory::delBook(): \" << e.what() << endl;\n }\n return 0;\n}\n\nbool Inventory::sync() {\n try {\n \/\/ Open database\n m_db->open(DEFAULT_INV_FILE);\n\n \/\/ for elements in delta list\n for(unsigned i = 0; i < m_deltaList.size(); i++) {\n \/\/ Find book by index\n Book* temp = getBook(m_deltaList[i]);\n \/\/ Write book to record\n \/\/if(!m_db->change(temp)) throw runtime_error(\"Could not modify database\");\n }\n\n\n \/\/ Sort delete list in reverse... order matters when deleting from arrays!\n sort(m_deleteList.begin(), m_deleteList.end());\n reverse(m_deleteList.begin(), m_deleteList.end()); \/\/ TODO: Inefficient...?\n \/\/for(unsigned i = m_deleteList.size(); i >= 0; i--) {\n \/\/Book* temp = getBook(m_deleteList[i]);\n \/\/\/\/if(!m_db->remove(temp)) throw runtime_error(\"Could not remove from database\");\n \/\/delete temp; \/\/ Deallocate\n \/\/m_deleteList.erase(m_deleteList.begin() + i); \/\/ Erase from vector\n \/\/}\n\n\n \/\/ for elements in add list\n for(unsigned i = 0; i < m_addList.size(); i++) {\n \/\/ Push element to book list\n m_bookList.push_back(m_addList[i]);\n \/\/ Write book to database\n \/\/if(!m_db->add(m_addList[i])) throw runtime_error(\"Could not add to database\");\n }\n\n m_db->close();\n reset();\n return true;\n } catch(exception& e) {\n cerr << \"Inventory::sync: \" << e.what() << endl;\n return false;\n }\n}\n\nbool Inventory::reset() {\n try {\n \/\/ Clear delta list, add list, and delete list\n m_deltaList.clear(); m_addList.clear(); m_deleteList.clear();\n clearBookList(); \/\/ Clear book list\n\n \/\/ Open database\n m_db->open(DEFAULT_INV_FILE);\n m_db->start(); \/\/ Start reading from beginning\n\n while(!m_db->eof()) {\n Book buffer; \/\/ Create temporary book (on stack)\n if(m_db->read(&buffer)) {\n \/\/ Read record into book, and if succeeds...?\n Book* book = new Book; \/\/ Create new book (on heap)\n *book = buffer; \/\/ Copy buffer book to new\n m_bookList.push_back(book); \/\/ Push to book list\n } else {\n throw runtime_error(\"Unable to read record\");\n }\n }\n\n m_db->close(); \/\/ Close database\n return true;\n } catch(exception& e) {\n cerr << \"Inventory::reset(): \" << e.what() << endl;\n return false;\n }\n}\n\nunsigned Inventory::getSize() {\n \/\/ Return number of books in inventory\n return m_bookList.size();\n}\n\nvector<Book*> Inventory::getRange(int first, int last) {\n \/\/ Create empty book list\n vector<Book*> retval;\n\n try {\n if(first >= last) throw domain_error(\"Domain Error: first >= last\");\n\n \/\/ check if first\/last are within book list bounds\n \/\/ Auto throws out of range exception\n m_bookList.at(first);\n m_bookList.at(last);\n\n \/\/ Assign empty vector with bounds from book list\n vector<Book*> sub(m_bookList.begin() + first, m_bookList.begin() + last);\n retval = sub;\n\n } catch(exception &e) {\n cerr << \"Inventory::getRange: \" << e.what() << endl;\n }\n return retval;\n}\n\nvector<Book*> Inventory::findBook(Book::field field, void* search) {\n \/\/ Create temp book list\n vector<Book*> retval;\n\n \/\/ for all books in book list\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n Book* book = m_bookList[i];\n switch(field) {\n case Book::ISBN:\n if(book->getISBN() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::TITLE:\n if(book->getTitle() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::AUTHOR:\n if(book->getAuthor() == *((string*) search))\n retval.push_back(book);\n break;\n case Book::QUANTITY:\n if(book->getQuantity() == *((int*) search))\n retval.push_back(book);\n break;\n case Book::WHOLECOST:\n if(book->getWholeCost() == *((double*) search))\n retval.push_back(book);\n break;\n case Book::RETAILPRICE:\n if(book->getRetailPrice() == *((double*) search))\n retval.push_back(book);\n break;\n case Book::DATEADDED:\n if(book->getDateAdded() == *((date*) search))\n retval.push_back(book);\n break;\n default:\n break;\n }\n }\n return retval;\n}\n\n\n\n\n\n\/\/ Private methods\nBook* Inventory::getBook(unsigned index) {\n try {\n if(index >= m_bookList.size()) throw out_of_range(\"Out of Range\");\n\n \/\/ For all items in book list\n \/\/ TODO: critical: book file indices must start at 0, not 1\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n if(m_bookList[i]->getFileIndex() == index)\n return m_bookList[i];\n }\n\n return NULL;\n } catch(exception& e) {\n cerr << \"Inventory::getBook: \" << e.what() << endl;\n return NULL;\n }\n}\n\nvoid Inventory::clearBookList() {\n for(unsigned i = 0; i < m_bookList.size(); i++) {\n delete m_bookList[i];\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Extractor.h\"\n\nnamespace BibOcr {\n Extractor::Extractor(const std::string filename) : filename_(filename) {\n image_ = cv::imread(filename);\n\n filter();\n }\n\n Extractor::~Extractor() {\n }\n\n std::vector<cv::Mat> Extractor::extract() {\n std::vector<cv::Mat> objects;\n\n\n return objects;\n }\n\n void Extractor::filter() {\n cv::blur(image_, image_, cv::Size(3, 3));\n save(\"blur\", image_);\n cv::Canny(image_, image_, 120, 200);\n save(\"canny\", image_);\n\n }\n\n void Extractor::save(const std::string category, const cv::Mat data) {\n std::string filename(filename_);\n\n filename.replace(filename.find(\"input\/\"), 6, \"output\/\");\n filename.replace(filename.find(\".jpg\"), 4, \".\" + category + \".jpg\");\n\n cv::imwrite(filename, data);\n }\n}\n<commit_msg>canny's builtin blur<commit_after>#include \"Extractor.h\"\n\nnamespace BibOcr {\n Extractor::Extractor(const std::string filename) : filename_(filename) {\n image_ = cv::imread(filename);\n\n filter();\n }\n\n Extractor::~Extractor() {\n }\n\n std::vector<cv::Mat> Extractor::extract() {\n std::vector<cv::Mat> objects;\n\n\n return objects;\n }\n\n void Extractor::filter() {\n cv::Canny(image_, image_, 120, 200, 3);\n save(\"canny\", image_);\n\n }\n\n void Extractor::save(const std::string category, const cv::Mat data) {\n std::string filename(filename_);\n\n filename.replace(filename.find(\"input\/\"), 6, \"output\/\");\n filename.replace(filename.find(\".jpg\"), 4, \".\" + category + \".jpg\");\n\n cv::imwrite(filename, data);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* cbr\n * FairQueue.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of cbr nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _FAIR_MESSAGE_QUEUE_HPP_\n#define _FAIR_MESSAGE_QUEUE_HPP_\n\n#include \"Time.hpp\"\n#include \"Queue.hpp\"\n\nnamespace CBR {\n\n\/** Predicate for FairQueue which never rejects the item being considered. *\/\nstruct AlwaysUsePredicate {\n template<typename Key, typename Message>\n bool operator()(const Key& key, const Message* msg) const {\n return true;\n }\n};\n\n\/** Fair Queue with one input queue of Messages per Key, backed by a TQueue. Each\n * input queue can be assigned a weight and selection happens according to FairQueuing,\n * with the additional constraint that each potential front element will be checked\n * against a Predicate to give the user a chance to block certain queues from being used\n * (for instance, if the downstream queue couldn't handle it).\n *\/\ntemplate <class Message,class Key,class TQueue,class Predicate=AlwaysUsePredicate> class FairQueue {\npublic:\n struct ServerQueueInfo {\n private:\n ServerQueueInfo():nextFinishTime(0) {\n messageQueue=NULL;\n weight=1.0;\n }\n public:\n ServerQueueInfo(Key serverName, TQueue* queue, float w)\n : messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {}\n\n TQueue* messageQueue;\n float weight;\n Time nextFinishTime;\n Key mKey;\n\n struct FinishTimeOrder {\n bool operator()(const ServerQueueInfo* lhs, const ServerQueueInfo* rhs) {\n return (lhs->nextFinishTime < rhs->nextFinishTime);\n }\n };\n };\n\n\n typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap;\n typedef TQueue MessageQueue;\n\n FairQueue(const Predicate pred = Predicate())\n :mCurrentVirtualTime(0),\n mServerQueues(),\n mPredicate(pred)\n {\n }\n\n ~FairQueue() {\n typename ServerQueueInfoMap::iterator it = mServerQueues.begin();\n for(; it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n delete queue_info->messageQueue;\n }\n }\n\n void addQueue(MessageQueue *mq, Key server, float weight) {\n \/\/assert(mq->empty());\n\n ServerQueueInfo queue_info (server, mq, weight);\n\n mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info));\n }\n void setQueueWeight(Key server, float weight) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (where != mServerQueues.end()) {\n where->second.weight = weight;\n }\n }\n float getQueueWeight(Key server) const {\n typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server);\n\n if (where != mServerQueues.end()) {\n return where->second.weight;\n }\n\n return 0;\n }\n\n\n\n bool deprioritize(Key server,float factor, float affine, float minval,float maxval) {\n return changepriority(server,factor,affine,minval,maxval,true);\n }\n bool reprioritize(Key server,float factor, float affine, float minval,float maxval) {\n return changepriority(server,factor,affine,minval,maxval,false);\n }\n bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n if ( where == mServerQueues.end() )\n return false;\n float oldweight=where->second.weight;\n oldweight*=factor;\n oldweight+=affine;\n if (oldweight<minval){\n oldweight=minval;\n }\n this->setQueueWeight(server,oldweight);\n return true;\n }\n bool removeQueue(Key server) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (retval) {\n delete where->second.messageQueue;\n mServerQueues.erase(where);\n }\n return retval;\n }\n bool hasQueue(Key server) const{\n return ( mServerQueues.find(server) != mServerQueues.end() );\n }\n unsigned int numQueues() const {\n return (unsigned int)mServerQueues.size();\n }\n QueueEnum::PushResult push(Key dest_server, Message *msg){\n typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);\n\n assert( qi_it != mServerQueues.end() );\n\n ServerQueueInfo* queue_info = &qi_it->second;\n\n \/\/ If the queue was empty then the new packet is first and its finish time needs to be computed.\n if (queue_info->messageQueue->empty())\n queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);\n return queue_info->messageQueue->push(msg);\n }\n\n \/\/ Returns the next message to deliver, given the number of bytes available for transmission\n \/\/ \\param bytes number of bytes available; updated appropriately for intermediate null messages when returns\n \/\/ \\returns the next message, or NULL if the queue is empty or the next message cannot be handled\n \/\/ given the number of bytes allocated\n Message* front(uint64* bytes, Key*keyAtFront) {\n Message* result = NULL;\n Time vftime(0);\n ServerQueueInfo* min_queue_info = NULL;\n\n nextMessage(bytes, &result, &vftime, &min_queue_info);\n if (result != NULL) {\n assert( *bytes >= result->size() );\n *keyAtFront=min_queue_info->mKey;\n return result;\n }\n\n return NULL;\n }\n\n \/\/ Returns the next message to deliver, given the number of bytes available for transmission\n \/\/ \\param bytes number of bytes available; updated appropriately when returns\n \/\/ \\returns the next message, or NULL if the queue is empty or the next message cannot be handled\n \/\/ given the number of bytes allotted\n Message* pop(uint64* bytes) {\n Message* result = NULL;\n Time vftime(0);\n ServerQueueInfo* min_queue_info = NULL;\n\n nextMessage(bytes, &result, &vftime, &min_queue_info);\n if (result != NULL) {\n mCurrentVirtualTime = vftime;\n\n assert(min_queue_info != NULL);\n\n assert( *bytes >= result->size() );\n *bytes -= result->size();\n\n min_queue_info->messageQueue->pop();\n\n \/\/ update the next finish time if there's anything in the queue\n if (!min_queue_info->messageQueue->empty())\n min_queue_info->nextFinishTime = finishTime(min_queue_info->messageQueue->front()->size(), min_queue_info->weight);\n }\n\n return result;\n }\n\n bool empty() const {\n \/\/ FIXME we could track a count ourselves instead of checking all these queues\n for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n const ServerQueueInfo* queue_info = &it->second;\n if (!queue_info->messageQueue->empty())\n return false;\n }\n return true;\n }\n\n \/\/ Returns the total amount of space that can be allocated for the destination\n uint32 maxSize(Key dest) const {\n typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);\n if (it == mServerQueues.end()) return 0;\n return it->second.messageQueue->maxSize();\n }\n\n \/\/ Returns the total amount of space currently used for the destination\n uint32 size(Key dest) const {\n typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);\n if (it == mServerQueues.end()) return 0;\n return it->second.messageQueue->size();\n }\n\nprotected:\n\n \/\/ Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available\n \/\/ for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for\n \/\/ the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty.\n void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) {\n \/\/ Create a list of queues, sorted by nextFinishTime. FIXME we should probably track this instead of regenerating it every time\n std::vector<ServerQueueInfo*> queues_by_finish_time;\n queues_by_finish_time.reserve(mServerQueues.size());\n for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n if (queue_info->messageQueue->empty()) continue;\n queues_by_finish_time.push_back(queue_info);\n }\n\n \/\/ If this list ends up empty then there are no enqueued messages\n if (queues_by_finish_time.empty()) {\n *result_out = NULL;\n return;\n }\n\n std::sort(queues_by_finish_time.begin(), queues_by_finish_time.end(), typename ServerQueueInfo::FinishTimeOrder());\n\n \/\/ Loop through until we find one that has data and can be handled.\n for(uint32 i = 0; i < queues_by_finish_time.size(); i++) {\n ServerQueueInfo* min_queue_info = queues_by_finish_time[i];\n\n \/\/ Check that we have enough bytes to deliver. If not stop the search and return since doing otherwise\n \/\/ would violate the ordering.\n if (*bytes < min_queue_info->messageQueue->front()->size()) {\n *result_out = NULL;\n return;\n }\n\n \/\/ Now give the user a chance to veto this packet. If they can use it, set output and return.\n \/\/ Otherwise just continue trying the rest of the options.\n if (mPredicate(min_queue_info->mKey, min_queue_info->messageQueue->front())) {\n *min_queue_info_out = min_queue_info;\n *vftime_out = min_queue_info->nextFinishTime;\n *result_out = min_queue_info->messageQueue->front();\n return;\n }\n }\n\n \/\/ If we get here then we've tried everything and nothing has satisfied our constraints. Give up.\n *result_out = NULL;\n return;\n }\n\n Time finishTime(uint32 size, float weight) const{\n float queue_frac = weight;\n Duration transmitTime = Duration::seconds( size \/ queue_frac );\n if (transmitTime == Duration(0)) transmitTime = Duration(1); \/\/ just make sure we take *some* time\n\n return mCurrentVirtualTime + transmitTime;\n }\n\nprotected:\n uint32 mRate;\n Time mCurrentVirtualTime;\n ServerQueueInfoMap mServerQueues;\n Predicate mPredicate;\n}; \/\/ class FairQueue\n\n} \/\/ namespace CBR\n\n#endif \/\/_FAIR_MESSAGE_QUEUE_HPP_\n<commit_msg>Calculate nextFinishTime properly depending on whether the packet was added when there were others in the queue or not. Handle updating of current virtual time properly so that it is guaranteed to increase monotonically.<commit_after>\/* cbr\n * FairQueue.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of cbr nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _FAIR_MESSAGE_QUEUE_HPP_\n#define _FAIR_MESSAGE_QUEUE_HPP_\n\n#include \"Time.hpp\"\n#include \"Queue.hpp\"\n\nnamespace CBR {\n\n\/** Predicate for FairQueue which never rejects the item being considered. *\/\nstruct AlwaysUsePredicate {\n template<typename Key, typename Message>\n bool operator()(const Key& key, const Message* msg) const {\n return true;\n }\n};\n\n\/** Fair Queue with one input queue of Messages per Key, backed by a TQueue. Each\n * input queue can be assigned a weight and selection happens according to FairQueuing,\n * with the additional constraint that each potential front element will be checked\n * against a Predicate to give the user a chance to block certain queues from being used\n * (for instance, if the downstream queue couldn't handle it).\n *\/\ntemplate <class Message,class Key,class TQueue,class Predicate=AlwaysUsePredicate> class FairQueue {\npublic:\n struct ServerQueueInfo {\n private:\n ServerQueueInfo():nextFinishTime(0) {\n messageQueue=NULL;\n weight=1.0;\n }\n public:\n ServerQueueInfo(Key serverName, TQueue* queue, float w)\n : messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {}\n\n TQueue* messageQueue;\n float weight;\n Time nextFinishTime;\n Key mKey;\n\n struct FinishTimeOrder {\n bool operator()(const ServerQueueInfo* lhs, const ServerQueueInfo* rhs) {\n return (lhs->nextFinishTime < rhs->nextFinishTime);\n }\n };\n };\n\n\n typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap;\n typedef TQueue MessageQueue;\n\n FairQueue(const Predicate pred = Predicate())\n :mCurrentVirtualTime(0),\n mServerQueues(),\n mPredicate(pred)\n {\n }\n\n ~FairQueue() {\n typename ServerQueueInfoMap::iterator it = mServerQueues.begin();\n for(; it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n delete queue_info->messageQueue;\n }\n }\n\n void addQueue(MessageQueue *mq, Key server, float weight) {\n \/\/assert(mq->empty());\n\n ServerQueueInfo queue_info (server, mq, weight);\n\n mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info));\n }\n void setQueueWeight(Key server, float weight) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (where != mServerQueues.end()) {\n where->second.weight = weight;\n }\n }\n float getQueueWeight(Key server) const {\n typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server);\n\n if (where != mServerQueues.end()) {\n return where->second.weight;\n }\n\n return 0;\n }\n\n\n\n bool deprioritize(Key server,float factor, float affine, float minval,float maxval) {\n return changepriority(server,factor,affine,minval,maxval,true);\n }\n bool reprioritize(Key server,float factor, float affine, float minval,float maxval) {\n return changepriority(server,factor,affine,minval,maxval,false);\n }\n bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n if ( where == mServerQueues.end() )\n return false;\n float oldweight=where->second.weight;\n oldweight*=factor;\n oldweight+=affine;\n if (oldweight<minval){\n oldweight=minval;\n }\n this->setQueueWeight(server,oldweight);\n return true;\n }\n bool removeQueue(Key server) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (retval) {\n delete where->second.messageQueue;\n mServerQueues.erase(where);\n }\n return retval;\n }\n bool hasQueue(Key server) const{\n return ( mServerQueues.find(server) != mServerQueues.end() );\n }\n unsigned int numQueues() const {\n return (unsigned int)mServerQueues.size();\n }\n QueueEnum::PushResult push(Key dest_server, Message *msg){\n typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);\n\n assert( qi_it != mServerQueues.end() );\n\n ServerQueueInfo* queue_info = &qi_it->second;\n\n \/\/ If the queue was empty then the new packet is first and its finish time needs to be computed.\n if (queue_info->messageQueue->empty())\n queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);\n return queue_info->messageQueue->push(msg);\n }\n\n \/\/ Returns the next message to deliver, given the number of bytes available for transmission\n \/\/ \\param bytes number of bytes available; updated appropriately for intermediate null messages when returns\n \/\/ \\returns the next message, or NULL if the queue is empty or the next message cannot be handled\n \/\/ given the number of bytes allocated\n Message* front(uint64* bytes, Key*keyAtFront) {\n Message* result = NULL;\n Time vftime(0);\n ServerQueueInfo* min_queue_info = NULL;\n\n nextMessage(bytes, &result, &vftime, &min_queue_info);\n if (result != NULL) {\n assert( *bytes >= result->size() );\n *keyAtFront=min_queue_info->mKey;\n return result;\n }\n\n return NULL;\n }\n\n \/\/ Returns the next message to deliver, given the number of bytes available for transmission\n \/\/ \\param bytes number of bytes available; updated appropriately when returns\n \/\/ \\returns the next message, or NULL if the queue is empty or the next message cannot be handled\n \/\/ given the number of bytes allotted\n Message* pop(uint64* bytes) {\n Message* result = NULL;\n Time vftime(0);\n ServerQueueInfo* min_queue_info = NULL;\n\n nextMessage(bytes, &result, &vftime, &min_queue_info);\n if (result != NULL) {\n \/\/ Note: we may have skipped a msg using the predicate, so we use max here to make sure\n \/\/ the virtual time increases monotonically.\n mCurrentVirtualTime = std::max(vftime, mCurrentVirtualTime);\n\n assert(min_queue_info != NULL);\n\n assert( *bytes >= result->size() );\n *bytes -= result->size();\n\n min_queue_info->messageQueue->pop();\n\n \/\/ update the next finish time if there's anything in the queue\n if (!min_queue_info->messageQueue->empty())\n min_queue_info->nextFinishTime = finishTime(min_queue_info->messageQueue->front()->size(), min_queue_info->weight, min_queue_info->nextFinishTime);\n }\n\n return result;\n }\n\n bool empty() const {\n \/\/ FIXME we could track a count ourselves instead of checking all these queues\n for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n const ServerQueueInfo* queue_info = &it->second;\n if (!queue_info->messageQueue->empty())\n return false;\n }\n return true;\n }\n\n \/\/ Returns the total amount of space that can be allocated for the destination\n uint32 maxSize(Key dest) const {\n typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);\n if (it == mServerQueues.end()) return 0;\n return it->second.messageQueue->maxSize();\n }\n\n \/\/ Returns the total amount of space currently used for the destination\n uint32 size(Key dest) const {\n typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);\n if (it == mServerQueues.end()) return 0;\n return it->second.messageQueue->size();\n }\n\nprotected:\n\n \/\/ Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available\n \/\/ for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for\n \/\/ the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty.\n void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) {\n \/\/ Create a list of queues, sorted by nextFinishTime. FIXME we should probably track this instead of regenerating it every time\n std::vector<ServerQueueInfo*> queues_by_finish_time;\n queues_by_finish_time.reserve(mServerQueues.size());\n for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n if (queue_info->messageQueue->empty()) continue;\n queues_by_finish_time.push_back(queue_info);\n }\n\n \/\/ If this list ends up empty then there are no enqueued messages\n if (queues_by_finish_time.empty()) {\n *result_out = NULL;\n return;\n }\n\n std::sort(queues_by_finish_time.begin(), queues_by_finish_time.end(), typename ServerQueueInfo::FinishTimeOrder());\n\n \/\/ Loop through until we find one that has data and can be handled.\n for(uint32 i = 0; i < queues_by_finish_time.size(); i++) {\n ServerQueueInfo* min_queue_info = queues_by_finish_time[i];\n\n \/\/ Check that we have enough bytes to deliver. If not stop the search and return since doing otherwise\n \/\/ would violate the ordering.\n if (*bytes < min_queue_info->messageQueue->front()->size()) {\n *result_out = NULL;\n return;\n }\n\n \/\/ Now give the user a chance to veto this packet. If they can use it, set output and return.\n \/\/ Otherwise just continue trying the rest of the options.\n if (mPredicate(min_queue_info->mKey, min_queue_info->messageQueue->front())) {\n *min_queue_info_out = min_queue_info;\n *vftime_out = min_queue_info->nextFinishTime;\n *result_out = min_queue_info->messageQueue->front();\n return;\n }\n }\n\n \/\/ If we get here then we've tried everything and nothing has satisfied our constraints. Give up.\n *result_out = NULL;\n return;\n }\n\n \/** Finish time for a packet that was inserted into a non-empty queue, i.e. based on the previous packet's\n * finish time. *\/\n Time finishTime(uint32 size, float weight, const Time& last_finish_time) const {\n float queue_frac = weight;\n Duration transmitTime = Duration::seconds( size \/ queue_frac );\n if (transmitTime == Duration(0)) transmitTime = Duration(1); \/\/ just make sure we take *some* time\n\n return last_finish_time + transmitTime;\n }\n\n \/** Finish time for a packet inserted into an empty queue, i.e. based on the most recent virtual time. *\/\n Time finishTime(uint32 size, float weight) const {\n float queue_frac = weight;\n Duration transmitTime = Duration::seconds( size \/ queue_frac );\n if (transmitTime == Duration(0)) transmitTime = Duration(1); \/\/ just make sure we take *some* time\n\n return mCurrentVirtualTime + transmitTime;\n }\n\nprotected:\n uint32 mRate;\n Time mCurrentVirtualTime;\n ServerQueueInfoMap mServerQueues;\n Predicate mPredicate;\n}; \/\/ class FairQueue\n\n} \/\/ namespace CBR\n\n#endif \/\/_FAIR_MESSAGE_QUEUE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/ FbCommands.hh for Fluxbox\n\/\/ Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: FbCommands.hh,v 1.20 2004\/10\/06 11:40:28 akir Exp $\n\n\/\/ \\file contains basic commands to restart, reconfigure, execute command and exit fluxbox\n\n#ifndef FBCOMMANDS_HH\n#define FBCOMMANDS_HH\n\n#include \"Command.hh\"\n\n#include <string>\n\nnamespace FbCommands {\n\n\/\/\/ executes a system command\nclass ExecuteCmd: public FbTk::Command {\npublic:\n ExecuteCmd(const std::string &cmd, int screen_num = -1);\n void execute();\nprivate:\n std::string m_cmd;\n const int m_screen_num;\n};\n\n\/\/\/ sets environment\nclass ExportCmd : public FbTk::Command {\npublic:\n ExportCmd(const std::string& name, const std::string& value);\n void execute();\nprivate:\n std::string m_name;\n std::string m_value;\n};\n\n\/\/\/ exit fluxbox\nclass ExitFluxboxCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\n\/\/\/ saves resources\nclass SaveResources: public FbTk::Command {\npublic:\n void execute();\n};\n\n\/\/\/ restarts fluxbox\nclass RestartFluxboxCmd: public FbTk::Command {\npublic:\n RestartFluxboxCmd(const std::string &cmd);\n void execute();\nprivate:\n std::string m_cmd;\n};\n\n\/\/\/ reconfigures fluxbox\nclass ReconfigureFluxboxCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass ReloadStyleCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass SetStyleCmd: public FbTk::Command {\npublic:\n explicit SetStyleCmd(const std::string &filename);\n void execute();\nprivate:\n std::string m_filename;\n};\n\nclass ShowRootMenuCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass ShowWorkspaceMenuCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass SetWorkspaceNameCmd: public FbTk::Command {\npublic:\n SetWorkspaceNameCmd(const std::string &name, int spaceid = -1);\n void execute();\nprivate:\n std::string m_name;\n int m_workspace;\n};\n\nclass WorkspaceNameDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass CommandDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\n} \/\/ end namespace FbCommands\n\nclass SetResourceValueCmd: public FbTk::Command {\npublic:\n SetResourceValueCmd(const std::string &resourcename, const std::string &value);\n void execute();\nprivate:\n const std::string m_resname;\n const std::string m_value;\n};\n\nclass SetResourceValueDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass BindKeyCmd: public FbTk::Command {\npublic:\n BindKeyCmd(const std::string &keybind);\n void execute();\nprivate:\n const std::string m_keybind;\n};\n\n\/\/\/ deiconifies iconified windows\nclass DeiconifyCmd: public FbTk::Command {\npublic:\n enum Mode { \n LAST,\n LASTWORKSPACE,\n ALL,\n ALLWORKSPACE\n };\n\n enum Destination {\n CURRENT, \/\/\/ deiconification on current workspace\n ORIGIN, \/\/\/ deiconification on origin workspace, change to that ws\n ORIGINQUIET \/\/\/ deiconification on origin workspace, dont change ws\n };\n \n DeiconifyCmd(const Mode mode= LASTWORKSPACE,\n const Destination dest= CURRENT);\n void execute();\nprivate:\n Mode m_mode;\n Destination m_dest;\n};\n\n#endif \/\/ FBCOMMANDS_HH\n<commit_msg>fix for wrong placed end of namespace }; (thanx mipspro :))<commit_after>\/\/ FbCommands.hh for Fluxbox\n\/\/ Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: FbCommands.hh,v 1.21 2004\/10\/21 10:23:58 akir Exp $\n\n\/\/ \\file contains basic commands to restart, reconfigure, execute command and exit fluxbox\n\n#ifndef FBCOMMANDS_HH\n#define FBCOMMANDS_HH\n\n#include \"Command.hh\"\n\n#include <string>\n\nnamespace FbCommands {\n\n\/\/\/ executes a system command\nclass ExecuteCmd: public FbTk::Command {\npublic:\n ExecuteCmd(const std::string &cmd, int screen_num = -1);\n void execute();\nprivate:\n std::string m_cmd;\n const int m_screen_num;\n};\n\n\/\/\/ sets environment\nclass ExportCmd : public FbTk::Command {\npublic:\n ExportCmd(const std::string& name, const std::string& value);\n void execute();\nprivate:\n std::string m_name;\n std::string m_value;\n};\n\n\/\/\/ exit fluxbox\nclass ExitFluxboxCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\n\/\/\/ saves resources\nclass SaveResources: public FbTk::Command {\npublic:\n void execute();\n};\n\n\/\/\/ restarts fluxbox\nclass RestartFluxboxCmd: public FbTk::Command {\npublic:\n RestartFluxboxCmd(const std::string &cmd);\n void execute();\nprivate:\n std::string m_cmd;\n};\n\n\/\/\/ reconfigures fluxbox\nclass ReconfigureFluxboxCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass ReloadStyleCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass SetStyleCmd: public FbTk::Command {\npublic:\n explicit SetStyleCmd(const std::string &filename);\n void execute();\nprivate:\n std::string m_filename;\n};\n\nclass ShowRootMenuCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass ShowWorkspaceMenuCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass SetWorkspaceNameCmd: public FbTk::Command {\npublic:\n SetWorkspaceNameCmd(const std::string &name, int spaceid = -1);\n void execute();\nprivate:\n std::string m_name;\n int m_workspace;\n};\n\nclass WorkspaceNameDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass CommandDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\n\nclass SetResourceValueCmd: public FbTk::Command {\npublic:\n SetResourceValueCmd(const std::string &resourcename, const std::string &value);\n void execute();\nprivate:\n const std::string m_resname;\n const std::string m_value;\n};\n\nclass SetResourceValueDialogCmd: public FbTk::Command {\npublic:\n void execute();\n};\n\nclass BindKeyCmd: public FbTk::Command {\npublic:\n BindKeyCmd(const std::string &keybind);\n void execute();\nprivate:\n const std::string m_keybind;\n};\n\n\/\/\/ deiconifies iconified windows\nclass DeiconifyCmd: public FbTk::Command {\npublic:\n enum Mode { \n LAST,\n LASTWORKSPACE,\n ALL,\n ALLWORKSPACE\n };\n\n enum Destination {\n CURRENT, \/\/\/ deiconification on current workspace\n ORIGIN, \/\/\/ deiconification on origin workspace, change to that ws\n ORIGINQUIET \/\/\/ deiconification on origin workspace, dont change ws\n };\n \n DeiconifyCmd(const Mode mode= LASTWORKSPACE,\n const Destination dest= CURRENT);\n void execute();\nprivate:\n Mode m_mode;\n Destination m_dest;\n};\n\n} \/\/ end namespace FbCommands\n\n#endif \/\/ FBCOMMANDS_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <ks\/KsLog.hpp>\n\n#ifdef KS_ENV_ANDROID\n#include <android\/log.hpp>\n#endif\n\nnamespace ks\n{\n namespace Log\n {\n #ifdef KS_ENV_ANDROID\n void SinkToLogCat::log(std::string const &line)\n {\n m_mutex.lock();\n __android_log_print(ANDROID_LOG_VERBOSE,\"ks\",line.c_str());\n m_mutex.unlock();\n }\n #endif\n\n \/\/ ============================================================= \/\/\n\n FBRunTimeMs::FBRunTimeMs() :\n m_time_str(\"00:00:00.000\"),\n m_start(std::chrono::system_clock::now()),\n m_list_num_chars({{'0','1','2','3','4','5','6','7','8','9'}})\n {\n \/\/ empty\n }\n\n FBRunTimeMs::~FBRunTimeMs()\n {\n \/\/ empty\n }\n\n std::string FBRunTimeMs::Get()\n {\n \/\/ TODO: should we use steady_clock, not system clock?\n auto now = std::chrono::system_clock::now();\n std::chrono::system_clock::duration elapsed = now-m_start;\n\n std::chrono::hours hours =\n std::chrono::duration_cast<std::chrono::hours>(\n elapsed);\n elapsed -= hours;\n\n std::chrono::minutes mins =\n std::chrono::duration_cast<std::chrono::minutes>(\n elapsed);\n elapsed -= mins;\n\n std::chrono::seconds secs =\n std::chrono::duration_cast<std::chrono::seconds>(\n elapsed);\n elapsed -= secs;\n\n std::chrono::milliseconds ms =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n elapsed);\n\n uint_fast8_t const hours_count = hours.count();\n uint_fast8_t const mins_count = mins.count();\n uint_fast8_t const secs_count = secs.count();\n uint_fast16_t const ms_count = ms.count();\n\n m_time_str[0] = m_list_num_chars[hours_count\/10];\n m_time_str[1] = m_list_num_chars[hours_count%10];\n\n m_time_str[3] = m_list_num_chars[mins_count\/10];\n m_time_str[4] = m_list_num_chars[mins_count%10];\n\n m_time_str[6] = m_list_num_chars[secs_count\/10];\n m_time_str[7] = m_list_num_chars[secs_count%10];\n\n m_time_str[9] = m_list_num_chars[ms_count\/100];\n m_time_str[10] = m_list_num_chars[(ms_count%100)\/10];\n m_time_str[11] = m_list_num_chars[(ms_count%100)%10];\n\n return m_time_str;\n }\n\n FBCustomStr::FBCustomStr(std::string const &s) : m_s(s)\n {\n \/\/ empty\n }\n\n FBCustomStr::~FBCustomStr()\n {\n \/\/ empty\n }\n\n std::string FBCustomStr::Get()\n {\n return m_s;\n }\n\n \/\/ ============================================================= \/\/\n\n Logger::Logger()\n {\n m_mutex = make_unique<MutexSTL>();\n\n \/\/ default filter is all on\n m_filter.set(static_cast<size_t>(Level::TRACE));\n m_filter.set(static_cast<size_t>(Level::DEBUG));\n m_filter.set(static_cast<size_t>(Level::INFO));\n m_filter.set(static_cast<size_t>(Level::WARN));\n m_filter.set(static_cast<size_t>(Level::ERROR));\n m_filter.set(static_cast<size_t>(Level::FATAL));\n }\n\n Logger::Logger(bool thread_safe,\n shared_ptr<Sink> const &sink,\n std::array<std::vector<FormatBlock*>,6> && list_fbs)\n {\n if(thread_safe) {\n m_mutex = make_unique<MutexSTL>();\n }\n else {\n m_mutex = make_unique<MutexDummy>();\n }\n\n \/\/ save sink\n m_list_sinks.push_back(sink);\n\n \/\/ save format blocks\n for(uint level=0; level < 6; level++) {\n for(uint fb_idx=0; fb_idx < list_fbs[level].size(); fb_idx++) {\n m_list_fb[level].push_back(\n std::move(unique_ptr<FormatBlock>(\n list_fbs[level][fb_idx])));\n }\n }\n\n \/\/ default filter is all on\n m_filter.set(static_cast<size_t>(Level::TRACE));\n m_filter.set(static_cast<size_t>(Level::DEBUG));\n m_filter.set(static_cast<size_t>(Level::INFO));\n m_filter.set(static_cast<size_t>(Level::WARN));\n m_filter.set(static_cast<size_t>(Level::ERROR));\n m_filter.set(static_cast<size_t>(Level::FATAL));\n }\n\n bool Logger::AddSink(shared_ptr<Sink> const &new_sink)\n {\n m_mutex->lock();\n\n for(size_t i=0; i < m_list_sinks.size(); i++) {\n shared_ptr<Sink> const &sink =\n m_list_sinks[i];\n\n if(sink == new_sink) {\n m_mutex->unlock();\n return false;\n }\n }\n\n m_list_sinks.push_back(new_sink);\n\n m_mutex->unlock();\n return true;\n }\n\n bool Logger::RemoveSink(shared_ptr<Sink> const &sink)\n {\n m_mutex->lock();\n\n for(auto sink_it = m_list_sinks.begin();\n sink_it != m_list_sinks.end();\n ++sink_it)\n {\n if((*sink_it) == sink) {\n m_list_sinks.erase(sink_it);\n m_mutex->unlock();\n return true;\n }\n }\n m_mutex->unlock();\n return false;\n }\n\n void Logger::SetLevel(Level level)\n {\n m_mutex->lock();\n m_filter.set(static_cast<size_t>(level));\n m_mutex->unlock();\n }\n\n void Logger::UnsetLevel(Level level)\n {\n m_mutex->lock();\n m_filter.reset(static_cast<size_t>(level));\n m_mutex->unlock();\n }\n\n void Logger::AddFormatBlock(unique_ptr<FormatBlock> fb,\n Level level)\n {\n m_mutex->lock();\n m_list_fb[static_cast<size_t>(level)].push_back(\n std::move(fb));\n m_mutex->unlock();\n }\n\n \/\/ logging methods\n Logger::Line Logger::Custom(Level level)\n {\n m_mutex->lock();\n\n size_t const level_int = static_cast<size_t>(level);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level_int]),\n m_mutex.get(),\n m_filter[level_int]);\n }\n\n\n Logger::Line Logger::Trace()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::TRACE);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Debug()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::DEBUG);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Info()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::INFO);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Warn()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::WARN);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Error()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::ERROR);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Fatal()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::FATAL);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n \/\/ ============================================================= \/\/\n\n } \/\/ Log\n\n Log::Logger LOG(\n true, \/\/ thread-safe\n#ifdef KS_ENV_ANDROID\n make_shared<Log::SinkToLogCat>(),\n#else\n make_shared<Log::SinkToStdOut>(), \/\/ log to stdout by default\n#endif\n\/\/ {{ \/\/ array init-list\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": TRACE: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": DEBUG: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": INFO: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": WARN: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": ERROR: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": FATAL: KS: \") }\n\/\/ }});\n\n {{ \/\/ array init-list\n { new Log::FBCustomStr(\"TRACE: KS: \") },\n { new Log::FBCustomStr(\"DEBUG: KS: \") },\n { new Log::FBCustomStr(\"INFO: KS: \") },\n { new Log::FBCustomStr(\"WARN: KS: \") },\n { new Log::FBCustomStr(\"ERROR: KS: \") },\n { new Log::FBCustomStr(\"FATAL: KS: \") }\n }});\n\n} \/\/ ks\n<commit_msg>Log: fixed include header typo for android log<commit_after>\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <ks\/KsLog.hpp>\n\n#ifdef KS_ENV_ANDROID\n#include <android\/log.h>\n#endif\n\nnamespace ks\n{\n namespace Log\n {\n #ifdef KS_ENV_ANDROID\n void SinkToLogCat::log(std::string const &line)\n {\n m_mutex.lock();\n __android_log_print(ANDROID_LOG_VERBOSE,\"ks\",line.c_str());\n m_mutex.unlock();\n }\n #endif\n\n \/\/ ============================================================= \/\/\n\n FBRunTimeMs::FBRunTimeMs() :\n m_time_str(\"00:00:00.000\"),\n m_start(std::chrono::system_clock::now()),\n m_list_num_chars({{'0','1','2','3','4','5','6','7','8','9'}})\n {\n \/\/ empty\n }\n\n FBRunTimeMs::~FBRunTimeMs()\n {\n \/\/ empty\n }\n\n std::string FBRunTimeMs::Get()\n {\n \/\/ TODO: should we use steady_clock, not system clock?\n auto now = std::chrono::system_clock::now();\n std::chrono::system_clock::duration elapsed = now-m_start;\n\n std::chrono::hours hours =\n std::chrono::duration_cast<std::chrono::hours>(\n elapsed);\n elapsed -= hours;\n\n std::chrono::minutes mins =\n std::chrono::duration_cast<std::chrono::minutes>(\n elapsed);\n elapsed -= mins;\n\n std::chrono::seconds secs =\n std::chrono::duration_cast<std::chrono::seconds>(\n elapsed);\n elapsed -= secs;\n\n std::chrono::milliseconds ms =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n elapsed);\n\n uint_fast8_t const hours_count = hours.count();\n uint_fast8_t const mins_count = mins.count();\n uint_fast8_t const secs_count = secs.count();\n uint_fast16_t const ms_count = ms.count();\n\n m_time_str[0] = m_list_num_chars[hours_count\/10];\n m_time_str[1] = m_list_num_chars[hours_count%10];\n\n m_time_str[3] = m_list_num_chars[mins_count\/10];\n m_time_str[4] = m_list_num_chars[mins_count%10];\n\n m_time_str[6] = m_list_num_chars[secs_count\/10];\n m_time_str[7] = m_list_num_chars[secs_count%10];\n\n m_time_str[9] = m_list_num_chars[ms_count\/100];\n m_time_str[10] = m_list_num_chars[(ms_count%100)\/10];\n m_time_str[11] = m_list_num_chars[(ms_count%100)%10];\n\n return m_time_str;\n }\n\n FBCustomStr::FBCustomStr(std::string const &s) : m_s(s)\n {\n \/\/ empty\n }\n\n FBCustomStr::~FBCustomStr()\n {\n \/\/ empty\n }\n\n std::string FBCustomStr::Get()\n {\n return m_s;\n }\n\n \/\/ ============================================================= \/\/\n\n Logger::Logger()\n {\n m_mutex = make_unique<MutexSTL>();\n\n \/\/ default filter is all on\n m_filter.set(static_cast<size_t>(Level::TRACE));\n m_filter.set(static_cast<size_t>(Level::DEBUG));\n m_filter.set(static_cast<size_t>(Level::INFO));\n m_filter.set(static_cast<size_t>(Level::WARN));\n m_filter.set(static_cast<size_t>(Level::ERROR));\n m_filter.set(static_cast<size_t>(Level::FATAL));\n }\n\n Logger::Logger(bool thread_safe,\n shared_ptr<Sink> const &sink,\n std::array<std::vector<FormatBlock*>,6> && list_fbs)\n {\n if(thread_safe) {\n m_mutex = make_unique<MutexSTL>();\n }\n else {\n m_mutex = make_unique<MutexDummy>();\n }\n\n \/\/ save sink\n m_list_sinks.push_back(sink);\n\n \/\/ save format blocks\n for(uint level=0; level < 6; level++) {\n for(uint fb_idx=0; fb_idx < list_fbs[level].size(); fb_idx++) {\n m_list_fb[level].push_back(\n std::move(unique_ptr<FormatBlock>(\n list_fbs[level][fb_idx])));\n }\n }\n\n \/\/ default filter is all on\n m_filter.set(static_cast<size_t>(Level::TRACE));\n m_filter.set(static_cast<size_t>(Level::DEBUG));\n m_filter.set(static_cast<size_t>(Level::INFO));\n m_filter.set(static_cast<size_t>(Level::WARN));\n m_filter.set(static_cast<size_t>(Level::ERROR));\n m_filter.set(static_cast<size_t>(Level::FATAL));\n }\n\n bool Logger::AddSink(shared_ptr<Sink> const &new_sink)\n {\n m_mutex->lock();\n\n for(size_t i=0; i < m_list_sinks.size(); i++) {\n shared_ptr<Sink> const &sink =\n m_list_sinks[i];\n\n if(sink == new_sink) {\n m_mutex->unlock();\n return false;\n }\n }\n\n m_list_sinks.push_back(new_sink);\n\n m_mutex->unlock();\n return true;\n }\n\n bool Logger::RemoveSink(shared_ptr<Sink> const &sink)\n {\n m_mutex->lock();\n\n for(auto sink_it = m_list_sinks.begin();\n sink_it != m_list_sinks.end();\n ++sink_it)\n {\n if((*sink_it) == sink) {\n m_list_sinks.erase(sink_it);\n m_mutex->unlock();\n return true;\n }\n }\n m_mutex->unlock();\n return false;\n }\n\n void Logger::SetLevel(Level level)\n {\n m_mutex->lock();\n m_filter.set(static_cast<size_t>(level));\n m_mutex->unlock();\n }\n\n void Logger::UnsetLevel(Level level)\n {\n m_mutex->lock();\n m_filter.reset(static_cast<size_t>(level));\n m_mutex->unlock();\n }\n\n void Logger::AddFormatBlock(unique_ptr<FormatBlock> fb,\n Level level)\n {\n m_mutex->lock();\n m_list_fb[static_cast<size_t>(level)].push_back(\n std::move(fb));\n m_mutex->unlock();\n }\n\n \/\/ logging methods\n Logger::Line Logger::Custom(Level level)\n {\n m_mutex->lock();\n\n size_t const level_int = static_cast<size_t>(level);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level_int]),\n m_mutex.get(),\n m_filter[level_int]);\n }\n\n\n Logger::Line Logger::Trace()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::TRACE);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Debug()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::DEBUG);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Info()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::INFO);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Warn()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::WARN);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Error()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::ERROR);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n Logger::Line Logger::Fatal()\n {\n m_mutex->lock();\n\n size_t const level = static_cast<size_t>(Level::FATAL);\n\n return Line(&m_list_sinks,\n &(m_list_fb[level]),\n m_mutex.get(),\n m_filter[level]);\n }\n\n \/\/ ============================================================= \/\/\n\n } \/\/ Log\n\n Log::Logger LOG(\n true, \/\/ thread-safe\n#ifdef KS_ENV_ANDROID\n make_shared<Log::SinkToLogCat>(),\n#else\n make_shared<Log::SinkToStdOut>(), \/\/ log to stdout by default\n#endif\n\/\/ {{ \/\/ array init-list\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": TRACE: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": DEBUG: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": INFO: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": WARN: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": ERROR: KS: \") },\n\/\/ { new Log::FBRunTimeMs(), new Log::FBCustomStr(\": FATAL: KS: \") }\n\/\/ }});\n\n {{ \/\/ array init-list\n { new Log::FBCustomStr(\"TRACE: KS: \") },\n { new Log::FBCustomStr(\"DEBUG: KS: \") },\n { new Log::FBCustomStr(\"INFO: KS: \") },\n { new Log::FBCustomStr(\"WARN: KS: \") },\n { new Log::FBCustomStr(\"ERROR: KS: \") },\n { new Log::FBCustomStr(\"FATAL: KS: \") }\n }});\n\n} \/\/ ks\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <DO\/Sara\/Core\/EigenExtension.hpp>\n\n\nnamespace DO { namespace Sara {\n\n struct EightPointAlgorithm\n {\n template <typename Sample>\n Matrix3d operator()(const Sample&)\n {\n return Matrix3d{};\n }\n };\n\n\n} \/* namespace Sara *\/\n} \/* namespace DO *\/\n<commit_msg>WIP: save work.<commit_after>#pragma once\n\n#include <DO\/Sara\/Core\/EigenExtension.hpp>\n\n\nnamespace DO { namespace Sara {\n\n inline void eight_point_alg_fundamental(const MatrixXd& x, const MatrixXd& y,\n Matrix3d& F)\n {\n Matrix<double, 8, 9> A(8, 9);\n\n for (int i = 0; i < 8; ++i)\n A.row(i) << \/\/\n x(i, 0) * y.col(i).transpose(), \/\/\n x(i, 1) * y.col(0).transpose(), \/\/\n y.col(i).transpose();\n\n Eigen::JacobiSVD<MatrixXd> svd(A);\n Matrix<double, 9, 1> S = svd.singularValues();\n Matrix<double, 9, 1> f = svd.matrixV().col(8);\n\n F.col(0) = f.block(0, 0, 1, 3);\n F.col(1) = f.block(3, 0, 1, 3);\n F.col(2) = f.block(6, 0, 1, 3);\n }\n\n inline void eight_point_alg_homography(const MatrixXd& x, const MatrixXd& y,\n Matrix3d& H)\n {\n const Vector2d p1 = x.col(0);\n const Vector2d p2 = x.col(1);\n const Vector2d p3 = x.col(2);\n const Vector2d p4 = x.col(3);\n\n const Vector2d q1 = y.col(0);\n const Vector2d q2 = y.col(1);\n const Vector2d q3 = y.col(2);\n const Vector2d q4 = y.col(3);\n\n using T = double;\n\n Matrix<double, 8, 8> M;\n M <<\n p1.x(), p1.y(), T(1), T(0), T(0), T(0), -p1.x()*q1.x(), -p1.y()*q1.x(),\n T(0), T(0), T(0), p1.x(), p1.y(), T(1), -p1.x()*q1.y(), -p1.y()*q1.y(),\n p2.x(), p2.y(), T(1), T(0), T(0), T(0), -p2.x()*q2.x(), -p2.y()*q2.x(),\n T(0), T(0), T(0), p2.x(), p2.y(), T(1), -p2.x()*q2.y(), -p2.y()*q2.y(),\n p3.x(), p3.y(), T(1), T(0), T(0), T(0), -p3.x()*q3.x(), -p3.y()*q3.x(),\n T(0), T(0), T(0), p3.x(), p3.y(), T(1), -p3.x()*q3.y(), -p3.y()*q3.y(),\n p4.x(), p4.y(), T(1), T(0), T(0), T(0), -p4.x()*q4.x(), -p4.y()*q4.x(),\n T(0), T(0), T(0), p4.x(), p4.y(), T(1), -p4.x()*q4.y(), -p4.y()*q4.y();\n\n Matrix<double, 8, 1> b;\n b << q1.x(), q1.y(), q2.x(), q2.y(), q3.x(), q3.y(), q4.x(), q4.y();\n\n Matrix<T, 8, 1> h(M.colPivHouseholderQr().solve(b));\n\n H << h[0], h[1], h[2],\n h[3], h[4], h[5],\n h[6], h[7], 1.0;\n }\n\n} \/* namespace Sara *\/\n} \/* namespace DO *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n ePaper.cpp\n 2013 Copyright (c) Seeed Technology Inc. All right reserved.\n\n Modified by Loovee\n www.seeedstudio.com\n 2013-7-2\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"GT20L16_drive.h\"\n#include \"ePaper.h\"\n\n\nstatic void spi_on()\n{\n SPI.begin();\n \/\/SPI.setClockDivider(SPI_CLOCK_DIV2);\n \/\/SPI_put(0x00);\n \/\/SPI_put(0x00);\n}\n\n\/*********************************************************************************************************\n* \\brief According to EPD size and temperature to get stage_time\n* \\note Refer to COG document Section 5.3 for more details\n*\n* \\param EPD_type_index The defined EPD size\n**********************************************************************************************************\/\nvoid ePaper::begin(EPD_size sz)\n{\n size = sz;\n direction = DIRNORMAL;\n \n switch(size)\n {\n case EPD_1_44: \/\/ 128*96\n SIZE_LEN = 128;\n SIZE_WIDTH = 96;\n break;\n \n case EPD_2_0: \/\/ 200*96\n SIZE_LEN = 200;\n SIZE_WIDTH = 96;\n break;\n \n case EPD_2_7: \/\/ 264*176\n SIZE_LEN = 264;\n SIZE_WIDTH = 176;\n break;\n \n default:\n println_ep(\"wrong size\");\n while(1); \/\/ die here\n }\n \n EPD.begin(size);\n init_io();\n}\n\nvoid ePaper::spi_detach()\n{\n}\n\/*********************************************************************************************************\n** Function name: begin\n** Descriptions: begin\n*********************************************************************************************************\/\nvoid ePaper::setDirection(EPD_DIR dir)\n{\n direction = dir;\n \n if((direction == DIRLEFT) || (direction == DIRRIGHT))\n {\n DISP_LEN = SIZE_WIDTH;\n DISP_WIDTH = SIZE_LEN;\n }\n \n eSD.setDirection(direction);\n}\n\/*********************************************************************************************************\n** Function name: start\n** Descriptions: start\n*********************************************************************************************************\/\nvoid ePaper::start()\n{\n EPD.start(); \/\/ power up the EPD panel\n \n int tmp = getTemperature();\n Serial.print(\"temperature: \");\n EPD.setFactor(getTemperature()); \/\/ adjust for current temperature\n}\n\n\/*********************************************************************************************************\n** Function name: end\n** Descriptions: end\n*********************************************************************************************************\/\nvoid ePaper::end()\n{\n EPD.end();\n}\n\n\/*********************************************************************************************************\n** Function name: init_io\n** Descriptions: init IO\n*********************************************************************************************************\/\nvoid ePaper::init_io()\n{\n \/\/ init IO\n pinMode(Pin_BUSY, INPUT);\n pinMode(Pin_RESET, OUTPUT);\n pinMode(Pin_PANEL_ON, OUTPUT);\n pinMode(Pin_DISCHARGE, OUTPUT);\n pinMode(Pin_BORDER, OUTPUT);\n pinMode(Pin_EPD_CS, OUTPUT);\n pinMode(Pin_SD_CS, OUTPUT);\n \n pinMode(9, OUTPUT);\n digitalWrite(9, HIGH);\n\n digitalWrite(Pin_RESET, LOW);\n digitalWrite(Pin_PANEL_ON, LOW);\n digitalWrite(Pin_DISCHARGE, LOW);\n digitalWrite(Pin_BORDER, LOW);\n digitalWrite(Pin_EPD_CS, HIGH);\n digitalWrite(Pin_SD_CS, HIGH);\n \n \/\/ init SPI\n SPI.begin();\n SPI.setBitOrder(MSBFIRST);\n SPI.setDataMode(SPI_MODE0);\n \/\/SPI.setClockDivider(SPI_CLOCK_DIV2);\n}\n\n\/*********************************************************************************************************\n** Function name: getTemperature\n** Descriptions: get temperature of sensor\n*********************************************************************************************************\/\nint ePaper::getTemperature()\n{\n int sum = 0;\n for(int i=0; i<32; i++)\n {\n sum += analogRead(Pin_TEMPERATURE);\n }\n sum = sum >> 5;\n\n float temp = 209.56-121.7*(float(sum)\/1023.0*5.0);\n\n return (int)temp;\n}\n\n\/*********************************************************************************************************\n** Function name: drawUnicode\n** Descriptions: draw a unicode\n*********************************************************************************************************\/\nint ePaper::drawUnicode(unsigned int uniCode, int x, int y)\n{\n \n \/\/ if(((x+16)>= DISP_LEN) || ((y+16) >= DISP_WIDTH) || x<0 || y<0) return 0;\n \n\n int dtaLen = GT20L16.getMatrixUnicode(uniCode, tMatrix);\n\n\n int pX = 0;\n int pY = 0;\n int color = 0;\n \/\/spi_on();\n for(int k = 0; k<2; k++)\n {\n for(int i=0; i<8; i++)\n {\n for(int j=0; j<(dtaLen\/2); j++)\n {\n\n if(tMatrix[j+(dtaLen\/2)*k] & (0x01<<(7-i)))\n { \n color = 1;\n }\n else\n {\n color = 0;\n }\n \n pX = x + j;\n pY = y + k*8+i;\n \n \n drawPixel(pX, pY, color);\n }\n }\n }\n\n return dtaLen\/2; \/\/ x +\n}\n\nint ePaper::drawUnicode(unsigned char *matrix, int x, int y)\n{\n \n \/\/ if(((x+16)>= DISP_LEN) || ((y+16) >= DISP_WIDTH) || x<0 || y<0) return 0;\n \n\n int dtaLen = 32;\n int pX = 0;\n int pY = 0;\n int color = 0;\n \/\/spi_on();\n for(int k = 0; k<2; k++)\n {\n for(int i=0; i<8; i++)\n {\n for(int j=0; j<(dtaLen\/2); j++)\n {\n\n if(matrix[j+(dtaLen\/2)*k] & (0x01<<(7-i)))\n { \n color = 1;\n }\n else\n {\n color = 0;\n }\n \n pX = x + j;\n pY = y + k*8+i;\n \n drawPixel(pX, pY, color);\n }\n }\n }\n\n return dtaLen\/2; \/\/ x +\n}\n\n\/*********************************************************************************************************\n** Function name: drawUnicodeString\n** Descriptions: draw string\n*********************************************************************************************************\/\nint ePaper::drawUnicodeString(unsigned int *uniCode, int len, int x, int y)\n{\n int xPlus = 0;\n int xSum = 0;\n \n for(int i=0; i<len; i++)\n {\n xPlus = drawUnicode(uniCode[i], x, y);\n x += xPlus;\n xSum += xPlus;\n }\n return xSum;\n}\n\n\/*********************************************************************************************************\n** Function name: drawChar\n** Descriptions: draw char\n*********************************************************************************************************\/\nint ePaper::drawChar(char c, int x, int y)\n{\n return drawUnicode(c, x, y);\n}\n\n\/*********************************************************************************************************\n** Function name: drawString\n** Descriptions: draw string\n*********************************************************************************************************\/\nint ePaper::drawString(char *string, int poX, int poY)\n{\n int sumX = 0;\n\n while(*string)\n {\n \n int xPlus = drawChar(*string, poX, poY);\n sumX += xPlus;\n *string++;\n \n if(poX < 200)\n {\n poX += xPlus; \/* Move cursor right *\/\n }\n }\n \n return sumX;\n}\n\n\/*********************************************************************************************************\n** Function name: drawNumber\n** Descriptions: drawNumber\n*********************************************************************************************************\/\nint ePaper::drawNumber(long long_num,int poX, int poY)\n{\n char tmp[10];\n sprintf(tmp, \"%d\", long_num);\n return drawString(tmp, poX, poY);\n\n}\n\n\/*********************************************************************************************************\n** Function name: drawFloat\n** Descriptions: drawFloat\n*********************************************************************************************************\/\nint ePaper::drawFloat(float floatNumber, int decimal, int poX, int poY)\n{\n unsigned long temp=0;\n float decy=0.0;\n float rounding = 0.5;\n unsigned char f=0;\n \n float eep = 0.000001;\n \n int sumX = 0;\n int xPlus = 0;\n \n if(floatNumber-0.0 < eep) \/\/ floatNumber < 0\n {\n xPlus = drawChar('-',poX, poY);\n floatNumber = -floatNumber;\n\n poX += xPlus; \n sumX += xPlus;\n }\n \n for (unsigned char i=0; i<decimal; ++i)\n {\n rounding \/= 10.0;\n }\n \n floatNumber += rounding;\n\n temp = (long)floatNumber;\n \n \n xPlus = drawNumber(temp,poX, poY);\n\n poX += xPlus; \n sumX += xPlus;\n\n if(decimal>0)\n {\n xPlus = drawChar('.',poX, poY);\n poX += xPlus; \/* Move cursor right *\/\n sumX += xPlus;\n }\n else\n {\n return sumX;\n }\n \n decy = floatNumber - temp;\n for(unsigned char i=0; i<decimal; i++) \n {\n decy *= 10; \/* for the next decimal *\/\n temp = decy; \/* get the decimal *\/\n xPlus = drawNumber(temp,poX, poY);\n \n poX += xPlus; \/* Move cursor right *\/\n sumX += xPlus;\n decy -= temp;\n }\n return sumX;\n}\n\n\/*********************************************************************************************************\n** Function name: drawLine\n** Descriptions: drawLine\n*********************************************************************************************************\/\nvoid ePaper::drawLine(int x0, int y0, int x1, int y1)\n{\n\n init_io();\n \n int x = x1-x0;\n int y = y1-y0;\n int dx = abs(x), sx = x0<x1 ? 1 : -1;\n int dy = -abs(y), sy = y0<y1 ? 1 : -1;\n int err = dx+dy, e2; \n for (;;)\n { \n drawPixel(x0,y0,1);\n e2 = 2*err;\n if (e2 >= dy) \n { \n if (x0 == x1) break;\n err += dy; x0 += sx;\n }\n if (e2 <= dx) \n { \n if (y0 == y1) break;\n err += dx; y0 += sy;\n }\n }\n}\n\n\n\/*********************************************************************************************************\n** Function name: clear_sd\n** Descriptions: clear sd card\n*********************************************************************************************************\/\nvoid ePaper::clear_sd()\n{\n \n init_io();\n \n for(int i=0; i<DISP_WIDTH; i++)\n {\n for(int j=0; j<DISP_LEN; j++)\n {\n drawPixel(j, i, 0);\n \n }\n }\n}\n\n\/*********************************************************************************************************\n** Function name: drawCircle\n** Descriptions: drawCircle\n*********************************************************************************************************\/\nvoid ePaper::drawCircle(int poX, int poY, int r)\n{\n\n init_io();\n int x = -r, y = 0, err = 2-2*r, e2;\n do {\n drawPixel(poX-x, poY+y, 1);\n drawPixel(poX+x, poY+y, 1);\n drawPixel(poX+x, poY-y, 1);\n drawPixel(poX-x, poY-y, 1);\n e2 = err;\n if (e2 <= y) {\n err += ++y*2+1;\n if (-x == y && e2 <= x) e2 = 0;\n }\n if (e2 > x) err += ++x*2+1;\n } while (x <= 0);\n}\n\n\/*********************************************************************************************************\n** Function name: drawHorizontalLine\n** Descriptions: drawHorizontalLine\n*********************************************************************************************************\/\nvoid ePaper::drawHorizontalLine( int poX, int poY, int len)\n{\n drawLine(poX, poY, poX+len, poY);\n}\n\n\/*********************************************************************************************************\n** Function name: drawVerticalLine\n** Descriptions: drawVerticalLine\n*********************************************************************************************************\/\nvoid ePaper::drawVerticalLine( int poX, int poY, int len)\n{\n drawLine(poX, poY, poX, poY+len);\n}\n\n\/*********************************************************************************************************\n** Function name: drawRectangle\n** Descriptions: drawRectangle\n*********************************************************************************************************\/\nvoid ePaper::drawRectangle(int poX, int poY, int len, int width)\n{\n drawHorizontalLine(poX, poY, len);\n drawHorizontalLine(poX, poY+width, len);\n drawVerticalLine(poX, poY, width);\n drawVerticalLine(poX + len, poY, width);\n}\n\n\/*********************************************************************************************************\n** Function name: fillCircle\n** Descriptions: fillCircle\n*********************************************************************************************************\/\nvoid ePaper::fillCircle(int poX, int poY, int r)\n{\n int x = -r, y = 0, err = 2-2*r, e2;\n \n do {\n\n drawVerticalLine(poX-x, poY-y, 2*y);\n drawVerticalLine(poX+x, poY-y, 2*y);\n\n e2 = err;\n if (e2 <= y) {\n err += ++y*2+1;\n if (-x == y && e2 <= x) e2 = 0;\n }\n if (e2 > x) err += ++x*2+1;\n } while (x <= 0);\n\n}\n\n\/*********************************************************************************************************\n** Function name: drawTraingle\n** Descriptions: drawTraingle\n*********************************************************************************************************\/\nvoid ePaper::drawTraingle( int poX1, int poY1, int poX2, int poY2, int poX3, int poY3)\n{\n drawLine(poX1, poY1, poX2, poY2);\n drawLine(poX1, poY1, poX3, poY3);\n drawLine(poX2, poY2, poX3, poY3);\n}\n\n\/*********************************************************************************************************\n** Function name: drawTraingle\n** Descriptions: drawTraingle\n*********************************************************************************************************\/\nvoid ePaper::fillRectangle(int poX, int poY, int len, int width)\n{\n for(int i=0; i<width; i++)\n {\n drawHorizontalLine(poX, poY+i, len);\n }\n}\n\n\/*********************************************************************************************************\n** Function name: display\n** Descriptions: you should use this function once after finish drawing\n*********************************************************************************************************\/\nunsigned char ePaper::display()\n{\n start();\n#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega328P__)\n EPD.image_sd();\n#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)\n EPD.image_sram(eSD.sram_image);\n#endif\n end();\n}\n\nePaper EPAPER;\n\/*********************************************************************************************************\n END FILE\n*********************************************************************************************************\/\n<commit_msg>Fixed additional problems<commit_after>\/*\n ePaper.cpp\n 2013 Copyright (c) Seeed Technology Inc. All right reserved.\n\n Modified by Loovee\n www.seeedstudio.com\n 2013-7-2\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include <Arduino.h>\n#include <SPI.h>\n#include \"GT20L16_drive.h\"\n#include \"ePaper.h\"\n\n\nstatic void spi_on()\n{\n SPI.begin();\n \/\/SPI.setClockDivider(SPI_CLOCK_DIV2);\n \/\/SPI_put(0x00);\n \/\/SPI_put(0x00);\n}\n\n\/*********************************************************************************************************\n* \\brief According to EPD size and temperature to get stage_time\n* \\note Refer to COG document Section 5.3 for more details\n*\n* \\param EPD_type_index The defined EPD size\n**********************************************************************************************************\/\nvoid ePaper::begin(EPD_size sz)\n{\n size = sz;\n direction = DIRNORMAL;\n \n switch(size)\n {\n case EPD_1_44: \/\/ 128*96\n SIZE_LEN = 128;\n SIZE_WIDTH = 96;\n break;\n \n case EPD_2_0: \/\/ 200*96\n SIZE_LEN = 200;\n SIZE_WIDTH = 96;\n break;\n \n case EPD_2_7: \/\/ 264*176\n SIZE_LEN = 264;\n SIZE_WIDTH = 176;\n break;\n \n default:\n println_ep(\"wrong size\");\n while(1); \/\/ die here\n }\n \n DISP_LEN = SIZE_LEN;\n DISP_WIDTH = SIZE_WIDTH;\n \n EPD.begin(size);\n init_io();\n}\n\nvoid ePaper::spi_detach()\n{\n}\n\/*********************************************************************************************************\n** Function name: begin\n** Descriptions: begin\n*********************************************************************************************************\/\nvoid ePaper::setDirection(EPD_DIR dir)\n{\n direction = dir;\n \n if((direction == DIRLEFT) || (direction == DIRRIGHT))\n {\n DISP_LEN = SIZE_WIDTH;\n DISP_WIDTH = SIZE_LEN;\n }\n \n eSD.setDirection(direction);\n}\n\/*********************************************************************************************************\n** Function name: start\n** Descriptions: start\n*********************************************************************************************************\/\nvoid ePaper::start()\n{\n EPD.start(); \/\/ power up the EPD panel\n \n int tmp = getTemperature();\n Serial.print(\"temperature: \");\n EPD.setFactor(getTemperature()); \/\/ adjust for current temperature\n}\n\n\/*********************************************************************************************************\n** Function name: end\n** Descriptions: end\n*********************************************************************************************************\/\nvoid ePaper::end()\n{\n EPD.end();\n}\n\n\/*********************************************************************************************************\n** Function name: init_io\n** Descriptions: init IO\n*********************************************************************************************************\/\nvoid ePaper::init_io()\n{\n \/\/ init IO\n pinMode(Pin_BUSY, INPUT);\n pinMode(Pin_RESET, OUTPUT);\n pinMode(Pin_PANEL_ON, OUTPUT);\n pinMode(Pin_DISCHARGE, OUTPUT);\n pinMode(Pin_BORDER, OUTPUT);\n pinMode(Pin_EPD_CS, OUTPUT);\n pinMode(Pin_SD_CS, OUTPUT);\n \n pinMode(9, OUTPUT);\n digitalWrite(9, HIGH);\n\n digitalWrite(Pin_RESET, LOW);\n digitalWrite(Pin_PANEL_ON, LOW);\n digitalWrite(Pin_DISCHARGE, LOW);\n digitalWrite(Pin_BORDER, LOW);\n digitalWrite(Pin_EPD_CS, HIGH);\n digitalWrite(Pin_SD_CS, HIGH);\n \n \/\/ init SPI\n SPI.begin();\n SPI.setBitOrder(MSBFIRST);\n SPI.setDataMode(SPI_MODE0);\n \/\/SPI.setClockDivider(SPI_CLOCK_DIV2);\n}\n\n\/*********************************************************************************************************\n** Function name: getTemperature\n** Descriptions: get temperature of sensor\n*********************************************************************************************************\/\nint ePaper::getTemperature()\n{\n int sum = 0;\n for(int i=0; i<32; i++)\n {\n sum += analogRead(Pin_TEMPERATURE);\n }\n sum = sum >> 5;\n\n float temp = 209.56-121.7*(float(sum)\/1023.0*5.0);\n\n return (int)temp;\n}\n\n\/*********************************************************************************************************\n** Function name: drawUnicode\n** Descriptions: draw a unicode\n*********************************************************************************************************\/\nint ePaper::drawUnicode(unsigned int uniCode, int x, int y)\n{\n \n \/\/ if(((x+16)>= DISP_LEN) || ((y+16) >= DISP_WIDTH) || x<0 || y<0) return 0;\n \n\n int dtaLen = GT20L16.getMatrixUnicode(uniCode, tMatrix);\n\n\n int pX = 0;\n int pY = 0;\n int color = 0;\n \/\/spi_on();\n for(int k = 0; k<2; k++)\n {\n for(int i=0; i<8; i++)\n {\n for(int j=0; j<(dtaLen\/2); j++)\n {\n\n if(tMatrix[j+(dtaLen\/2)*k] & (0x01<<(7-i)))\n { \n color = 1;\n }\n else\n {\n color = 0;\n }\n \n pX = x + j;\n pY = y + k*8+i;\n \n \n drawPixel(pX, pY, color);\n }\n }\n }\n\n return dtaLen\/2; \/\/ x +\n}\n\nint ePaper::drawUnicode(unsigned char *matrix, int x, int y)\n{\n \n \/\/ if(((x+16)>= DISP_LEN) || ((y+16) >= DISP_WIDTH) || x<0 || y<0) return 0;\n \n\n int dtaLen = 32;\n int pX = 0;\n int pY = 0;\n int color = 0;\n \/\/spi_on();\n for(int k = 0; k<2; k++)\n {\n for(int i=0; i<8; i++)\n {\n for(int j=0; j<(dtaLen\/2); j++)\n {\n\n if(matrix[j+(dtaLen\/2)*k] & (0x01<<(7-i)))\n { \n color = 1;\n }\n else\n {\n color = 0;\n }\n \n pX = x + j;\n pY = y + k*8+i;\n \n drawPixel(pX, pY, color);\n }\n }\n }\n\n return dtaLen\/2; \/\/ x +\n}\n\n\/*********************************************************************************************************\n** Function name: drawUnicodeString\n** Descriptions: draw string\n*********************************************************************************************************\/\nint ePaper::drawUnicodeString(unsigned int *uniCode, int len, int x, int y)\n{\n int xPlus = 0;\n int xSum = 0;\n \n for(int i=0; i<len; i++)\n {\n xPlus = drawUnicode(uniCode[i], x, y);\n x += xPlus;\n xSum += xPlus;\n }\n return xSum;\n}\n\n\/*********************************************************************************************************\n** Function name: drawChar\n** Descriptions: draw char\n*********************************************************************************************************\/\nint ePaper::drawChar(char c, int x, int y)\n{\n return drawUnicode(c, x, y);\n}\n\n\/*********************************************************************************************************\n** Function name: drawString\n** Descriptions: draw string\n*********************************************************************************************************\/\nint ePaper::drawString(char *string, int poX, int poY)\n{\n int sumX = 0;\n\n while(*string)\n {\n \n int xPlus = drawChar(*string, poX, poY);\n sumX += xPlus;\n *string++;\n \n if(poX < 200)\n {\n poX += xPlus; \/* Move cursor right *\/\n }\n }\n \n return sumX;\n}\n\n\/*********************************************************************************************************\n** Function name: drawNumber\n** Descriptions: drawNumber\n*********************************************************************************************************\/\nint ePaper::drawNumber(long long_num,int poX, int poY)\n{\n char tmp[10];\n sprintf(tmp, \"%d\", long_num);\n return drawString(tmp, poX, poY);\n\n}\n\n\/*********************************************************************************************************\n** Function name: drawFloat\n** Descriptions: drawFloat\n*********************************************************************************************************\/\nint ePaper::drawFloat(float floatNumber, int decimal, int poX, int poY)\n{\n unsigned long temp=0;\n float decy=0.0;\n float rounding = 0.5;\n unsigned char f=0;\n \n float eep = 0.000001;\n \n int sumX = 0;\n int xPlus = 0;\n \n if(floatNumber-0.0 < eep) \/\/ floatNumber < 0\n {\n xPlus = drawChar('-',poX, poY);\n floatNumber = -floatNumber;\n\n poX += xPlus; \n sumX += xPlus;\n }\n \n for (unsigned char i=0; i<decimal; ++i)\n {\n rounding \/= 10.0;\n }\n \n floatNumber += rounding;\n\n temp = (long)floatNumber;\n \n \n xPlus = drawNumber(temp,poX, poY);\n\n poX += xPlus; \n sumX += xPlus;\n\n if(decimal>0)\n {\n xPlus = drawChar('.',poX, poY);\n poX += xPlus; \/* Move cursor right *\/\n sumX += xPlus;\n }\n else\n {\n return sumX;\n }\n \n decy = floatNumber - temp;\n for(unsigned char i=0; i<decimal; i++) \n {\n decy *= 10; \/* for the next decimal *\/\n temp = decy; \/* get the decimal *\/\n xPlus = drawNumber(temp,poX, poY);\n \n poX += xPlus; \/* Move cursor right *\/\n sumX += xPlus;\n decy -= temp;\n }\n return sumX;\n}\n\n\/*********************************************************************************************************\n** Function name: drawLine\n** Descriptions: drawLine\n*********************************************************************************************************\/\nvoid ePaper::drawLine(int x0, int y0, int x1, int y1)\n{\n\n init_io();\n \n int x = x1-x0;\n int y = y1-y0;\n int dx = abs(x), sx = x0<x1 ? 1 : -1;\n int dy = -abs(y), sy = y0<y1 ? 1 : -1;\n int err = dx+dy, e2; \n for (;;)\n { \n drawPixel(x0,y0,1);\n e2 = 2*err;\n if (e2 >= dy) \n { \n if (x0 == x1) break;\n err += dy; x0 += sx;\n }\n if (e2 <= dx) \n { \n if (y0 == y1) break;\n err += dx; y0 += sy;\n }\n }\n}\n\n\n\/*********************************************************************************************************\n** Function name: clear_sd\n** Descriptions: clear sd card\n*********************************************************************************************************\/\nvoid ePaper::clear_sd()\n{\n \n init_io();\n \n for(int i=0; i<DISP_WIDTH; i++)\n {\n for(int j=0; j<DISP_LEN; j++)\n {\n drawPixel(j, i, 0);\n \n }\n }\n}\n\n\/*********************************************************************************************************\n** Function name: drawCircle\n** Descriptions: drawCircle\n*********************************************************************************************************\/\nvoid ePaper::drawCircle(int poX, int poY, int r)\n{\n\n init_io();\n int x = -r, y = 0, err = 2-2*r, e2;\n do {\n drawPixel(poX-x, poY+y, 1);\n drawPixel(poX+x, poY+y, 1);\n drawPixel(poX+x, poY-y, 1);\n drawPixel(poX-x, poY-y, 1);\n e2 = err;\n if (e2 <= y) {\n err += ++y*2+1;\n if (-x == y && e2 <= x) e2 = 0;\n }\n if (e2 > x) err += ++x*2+1;\n } while (x <= 0);\n}\n\n\/*********************************************************************************************************\n** Function name: drawHorizontalLine\n** Descriptions: drawHorizontalLine\n*********************************************************************************************************\/\nvoid ePaper::drawHorizontalLine( int poX, int poY, int len)\n{\n drawLine(poX, poY, poX+len, poY);\n}\n\n\/*********************************************************************************************************\n** Function name: drawVerticalLine\n** Descriptions: drawVerticalLine\n*********************************************************************************************************\/\nvoid ePaper::drawVerticalLine( int poX, int poY, int len)\n{\n drawLine(poX, poY, poX, poY+len);\n}\n\n\/*********************************************************************************************************\n** Function name: drawRectangle\n** Descriptions: drawRectangle\n*********************************************************************************************************\/\nvoid ePaper::drawRectangle(int poX, int poY, int len, int width)\n{\n drawHorizontalLine(poX, poY, len);\n drawHorizontalLine(poX, poY+width, len);\n drawVerticalLine(poX, poY, width);\n drawVerticalLine(poX + len, poY, width);\n}\n\n\/*********************************************************************************************************\n** Function name: fillCircle\n** Descriptions: fillCircle\n*********************************************************************************************************\/\nvoid ePaper::fillCircle(int poX, int poY, int r)\n{\n int x = -r, y = 0, err = 2-2*r, e2;\n \n do {\n\n drawVerticalLine(poX-x, poY-y, 2*y);\n drawVerticalLine(poX+x, poY-y, 2*y);\n\n e2 = err;\n if (e2 <= y) {\n err += ++y*2+1;\n if (-x == y && e2 <= x) e2 = 0;\n }\n if (e2 > x) err += ++x*2+1;\n } while (x <= 0);\n\n}\n\n\/*********************************************************************************************************\n** Function name: drawTraingle\n** Descriptions: drawTraingle\n*********************************************************************************************************\/\nvoid ePaper::drawTraingle( int poX1, int poY1, int poX2, int poY2, int poX3, int poY3)\n{\n drawLine(poX1, poY1, poX2, poY2);\n drawLine(poX1, poY1, poX3, poY3);\n drawLine(poX2, poY2, poX3, poY3);\n}\n\n\/*********************************************************************************************************\n** Function name: drawTraingle\n** Descriptions: drawTraingle\n*********************************************************************************************************\/\nvoid ePaper::fillRectangle(int poX, int poY, int len, int width)\n{\n for(int i=0; i<width; i++)\n {\n drawHorizontalLine(poX, poY+i, len);\n }\n}\n\n\/*********************************************************************************************************\n** Function name: display\n** Descriptions: you should use this function once after finish drawing\n*********************************************************************************************************\/\nunsigned char ePaper::display()\n{\n start();\n#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega328P__)\n EPD.image_sd();\n#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)\n EPD.image_sram(eSD.sram_image);\n#endif\n end();\n}\n\nePaper EPAPER;\n\/*********************************************************************************************************\n END FILE\n*********************************************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include \"gibbs_sampler.hpp\"\n#include \"distribution.hpp\"\n#include <vector>\n#include <deque>\n\nnamespace mcmc_utilities\n{\n \n template <typename T_p,typename T_stat,typename T_obs,typename T_t>\n class pf_model\n {\n private:\n pf_model(const pf_model&);\n public:\n typedef typename element_type_trait<T_stat>::element_type stat_element_type;\n typedef typename element_type_trait<T_obs>::element_type obs_element_type;\n public:\n pf_model(){}\n virtual ~pf_model(){}\n T_p evol_log_prob(const T_stat& x,const T_t& t,const std::deque<T_stat>& prev_stat,const std::deque<T_t>& prev_t)const\n {\n return do_evol_log_prob(x,t,prev_stat,prev_t);\n\t}\n\n T_p obs_log_prob(const T_obs& y,const T_stat& x,const T_t& t)const\n {\n return do_obs_log_prob(y,x,t);\n }\n\n void stat_var_range(T_stat& x1,T_stat& x2)const\n {\n return do_stat_var_range(x1,x2);\n }\n\n public:\n void update(const T_obs& y,const T_t& t,std::deque<T_stat>& prev_stat,std::deque<T_t>& prev_t)const\n {\n class cprob\n\t:public probability_density_md<T_p,T_stat>\n {\n private:\n\tconst pf_model* ptr_pf_model;\n\tconst T_obs* ptr_obs_vec;\n\tconst std::deque<T_stat>* ptr_prev_stat;\n\tconst std::deque<T_t>* ptr_prev_t;\n\tconst T_t* ptr_t;\n\tfriend class pf_model;\n public:\n\tT_p do_eval_log(const T_stat& x)const\n\t{\n\t return ptr_pf_model->evol_log_prob(x,*ptr_t,*ptr_prev_stat,*ptr_prev_t)+\n\t ptr_pf_model->obs_log_prob(*ptr_obs_vec,x,*ptr_t);\n\t}\n\tcprob* do_clone()const\n\t{\n\t return new cprob(*this);\n\t}\n\t\n\tvoid do_var_range(T_stat& x1,T_stat& x2)const\n\t{\n\t ptr_pf_model->stat_var_range(x1,x2);\n\t}\n }prob;\n prob.ptr_pf_model=this;\n prob.ptr_obs_vec=&y;\n prob.ptr_prev_stat=&prev_stat;\n prob.ptr_prev_t=&prev_t;\n prob.ptr_t=&t;\n T_stat new_pred(prev_stat.back());\n gibbs_sample(prob,new_pred);\n prev_stat.push_back(new_pred);\n prev_t.push_back(t);\n }\n \n private:\n virtual T_p do_evol_log_prob(const T_stat& x,const T_t& t,const std::deque<T_stat>& prev_stat,const std::deque<T_t>& prev_t)const=0;\n virtual T_p do_obs_log_prob(const T_obs& y,const T_stat& x,const T_t& t)const=0;\n virtual void do_stat_var_range(T_stat& x1,T_stat& x2)const=0;\n };\n};\n<commit_msg>\t修改: core\/particle_filter.hpp<commit_after>#include \"gibbs_sampler.hpp\"\n#include \"distribution.hpp\"\n#include <vector>\n#include <deque>\nnamespace mcmc_utilities\n{\n \n template <typename T_p,typename T_stat,typename T_obs,typename T_t>\n class pf_model\n {\n private:\n pf_model(const pf_model&);\n public:\n typedef typename element_type_trait<T_stat>::element_type stat_element_type;\n typedef typename element_type_trait<T_obs>::element_type obs_element_type;\n public:\n pf_model(){}\n virtual ~pf_model(){}\n T_p evol_log_prob(const T_stat& x,const T_t& t,const std::deque<T_stat>& prev_stat,const std::deque<T_t>& prev_t)const\n {\n return do_evol_log_prob(x,t,prev_stat,prev_t);\n\t}\n\n T_p obs_log_prob(const T_obs& y,const T_stat& x,const T_t& t)const\n {\n return do_obs_log_prob(y,x,t);\n }\n\n void stat_var_range(T_stat& x1,T_stat& x2)const\n {\n return do_stat_var_range(x1,x2);\n }\n\n public:\n void update(const T_obs& y,const T_t& t,std::deque<T_stat>& prev_stat,std::deque<T_t>& prev_t)const\n {\n class cprob\n\t:public probability_density_md<T_p,T_stat>\n {\n private:\n\tconst pf_model* ptr_pf_model;\n\tconst T_obs* ptr_obs_vec;\n\tconst std::deque<T_stat>* ptr_prev_stat;\n\tconst std::deque<T_t>* ptr_prev_t;\n\tconst T_t* ptr_t;\n\tfriend class pf_model;\n public:\n\tT_p do_eval_log(const T_stat& x)const\n\t{\n\t return ptr_pf_model->evol_log_prob(x,*ptr_t,*ptr_prev_stat,*ptr_prev_t)\n\t +ptr_pf_model->obs_log_prob(*ptr_obs_vec,x,*ptr_t);\n\t}\n\tcprob* do_clone()const\n\t{\n\t return new cprob(*this);\n\t}\n\t\n\tvoid do_var_range(T_stat& x1,T_stat& x2)const\n\t{\n\t ptr_pf_model->stat_var_range(x1,x2);\n\t}\n }prob;\n prob.ptr_pf_model=this;\n prob.ptr_obs_vec=&y;\n prob.ptr_prev_stat=&prev_stat;\n prob.ptr_prev_t=&prev_t;\n prob.ptr_t=&t;\n T_stat new_pred(prev_stat.back());\n gibbs_sample(prob,new_pred);\n prev_stat.push_back(new_pred);\n prev_t.push_back(t);\n }\n \n private:\n virtual T_p do_evol_log_prob(const T_stat& x,const T_t& t,const std::deque<T_stat>& prev_stat,const std::deque<T_t>& prev_t)const=0;\n virtual T_p do_obs_log_prob(const T_obs& y,const T_stat& x,const T_t& t)const=0;\n virtual void do_stat_var_range(T_stat& x1,T_stat& x2)const=0;\n };\n};\n<|endoftext|>"} {"text":"<commit_before>\/**\n@file VarTemplate.hpp\n@brief Var validation.\n\n@author Tim Howard\n@copyright 2010-2013 Tim Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n\/\/ TODO: infinitism\n\n#ifndef DUCT_VARTEMPLATE_HPP_\n#define DUCT_VARTEMPLATE_HPP_\n\n#include \".\/config.hpp\"\n#include \".\/aux.hpp\"\n#include \".\/string.hpp\"\n#include \".\/StateStore.hpp\"\n#include \".\/VarType.hpp\"\n#include \".\/Var.hpp\"\n\n#include <utility>\n\nnamespace duct {\n\n\/**\n\t@addtogroup var\n\t@{\n*\/\n\n\/**\n\tVar validator.\n*\/\nclass VarTemplate {\npublic:\n\/** @name Types *\/ \/\/\/ @{\n\t\/**\n\t\tLayout field.\n\t*\/\n\tstruct Field {\n\t\/** @name Types *\/ \/\/\/ @{\n\t\t\/**\n\t\t\tField flags.\n\n\t\t\t@note See VarTemplate::validate_layout() for usage notes.\n\t\t*\/\n\t\tenum class Flags : unsigned {\n\t\t\t\/** No flags. *\/\n\t\t\tnone = 0,\n\n\t\t\t\/** Optional field. *\/\n\t\t\toptional = 1 << 0,\n\t\t};\n\t\/\/\/ @}\n\n\t\/** @name Properties *\/ \/\/\/ @{\n\t\t\/** Type mask. *\/\n\t\tVarMask mask;\n\n\t\t\/** Flags. *\/\n\t\tStateStore<Flags> flags;\n\n\t\t\/**\n\t\t\tCheck if Flags::optional is enabled.\n\t\t*\/\n\t\tbool\n\t\toptional() const noexcept {\n\t\t\treturn flags.test(Flags::optional);\n\t\t}\n\t\/\/\/ @}\n\n\t\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\t\/** Destructor. *\/\n\t\t~Field() = default;\n\t\t\/** Copy constructor. *\/\n\t\tField(Field const&) = default;\n\t\t\/** Move constructor. *\/\n\t\tField(Field&&) = default;\n\n\t\t\/**\n\t\t\tConstruct with flags.\n\n\t\t\t@note Mask is VarMask::none.\n\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(VarMask::none)\n\t\t\t, flags(flags)\n\t\t{}\n\n\t\t\/**\n\t\t\tConstruct with type and flags.\n\n\t\t\t@param type Single-type mask.\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tVarType const type,\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(var_mask(type))\n\t\t\t, flags(flags)\n\t\t{}\n\n\t\t\/**\n\t\t\tConstruct with mask and flags.\n\n\t\t\t@param mask Mask.\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tVarMask const mask,\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(mask)\n\t\t\t, flags(flags)\n\t\t{}\n\t\/\/\/ @}\n\n\t\/** @name Operators *\/ \/\/\/ @{\n\t\t\/** Copy assignment operator. *\/\n\t\tField& operator=(Field const&) = default;\n\t\t\/** Move assignment operator. *\/\n\t\tField& operator=(Field&&) = default;\n\t\/\/\/ @}\n\t};\n\n\t\/** Identity vector type. *\/\n\tusing identity_vector_type = duct::aux::vector<u8string>;\n\t\/** Layout vector type. *\/\n\tusing layout_vector_type = duct::aux::vector<Field>;\n\/\/\/ @}\n\nprotected:\n\t\/**\n\t\t%Flags.\n\t*\/\n\tenum class Flags {\n\t\t\/**\n\t\t\tWhether to permit empty collections in layout validation.\n\n\t\t\t@note This is enabled by default.\n\t\t*\/\n\t\tpermit_empty = 1 << 0\n\t};\n\n\t\/** %Flags. *\/\n\tStateStore<Flags> m_flags{Flags::permit_empty};\n\t\/** Type mask. *\/\n\tVarMask m_type_mask{VarMask::none};\n\t\/** Identity. *\/\n\tidentity_vector_type m_identity{};\n\t\/** Layout. *\/\n\tlayout_vector_type m_layout{};\n\npublic:\n\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\/**\n\t\tConstruct with @c VarMask::none type mask, empty identity,\n\t\tand empty layout.\n\t*\/\n\tVarTemplate() = default;\n\n\t\/**\n\t\tConstruct with type mask, empty identity, and empty layout.\n\n\t\t@param type_mask Type mask.\n\t*\/\n\texplicit\n\tVarTemplate(\n\t\tVarMask const type_mask\n\t)\n\t\t: m_type_mask(type_mask)\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, identity, and empty layout.\n\n\t\t@param type_mask Type mask.\n\t\t@param identity Identity.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tidentity_vector_type identity\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_identity(std::move(identity))\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, layout, and empty identity.\n\n\t\t@param type_mask Type mask.\n\t\t@param layout Layout.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tlayout_vector_type layout\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_layout(std::move(layout))\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, identity, and layout.\n\n\t\t@param type_mask Type mask.\n\t\t@param identity Identity.\n\t\t@param layout Layout.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tidentity_vector_type identity,\n\t\tlayout_vector_type layout\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_identity(std::move(identity))\n\t\t, m_layout(std::move(layout))\n\t{}\n\n\t\/** Copy constructor (deleted). *\/\n\tVarTemplate(VarTemplate const&) = delete;\n\t\/** Move constructor. *\/\n\tVarTemplate(VarTemplate&&) = default;\n\t\/** Destructor. *\/\n\tvirtual ~VarTemplate() = default;\n\/\/\/ @}\n\n\/** @name Operators *\/ \/\/\/ @{\n\t\/** Copy assignment operator (deleted). *\/\n\tVarTemplate& operator=(VarTemplate const&) = delete;\n\t\/** Move assignment operator. *\/\n\tVarTemplate& operator=(VarTemplate&&) = default;\n\/\/\/ @}\n\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tEnable or disable flags.\n\n\t\t@param flags %Flags.\n\t\t@param enable Whether to enable or disable the flags.\n\t*\/\n\tvoid\n\tset_flags(\n\t\tFlags const flags,\n\t\tbool const enable\n\t) noexcept {\n\t\tm_flags.set(flags, enable);\n\t}\n\n\t\/**\n\t\tCheck if Flags::permit_empty is enabled.\n\t*\/\n\tbool\n\tpermit_empty() const noexcept {\n\t\treturn m_flags.test(Flags::permit_empty);\n\t}\n\n\t\/**\n\t\tSet type mask.\n\n\t\t@param type_mask New type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tvoid\n\tset_type_mask(\n\t\tVarMask const type_mask\n\t) noexcept {\n\t\tm_type_mask = type_mask;\n\t}\n\n\t\/**\n\t\tSet type mask (single type).\n\n\t\t@param type New type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tvoid\n\tset_type_mask(\n\t\tVarType const type\n\t) noexcept {\n\t\tm_type_mask = var_mask(type);\n\t}\n\n\t\/**\n\t\tGet type mask.\n\n\t\t@returns The current type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tVarMask\n\tget_type_mask() const noexcept {\n\t\treturn m_type_mask;\n\t}\n\n\t\/**\n\t\tSet identity.\n\n\t\t@param identity New identity.\n\t\t@sa validate_identity(Var const&) const\n\t*\/\n\tvoid\n\tset_identity(\n\t\tidentity_vector_type identity\n\t) {\n\t\tm_identity = std::move(identity);\n\t}\n\n\t\/**\n\t\tGet identity.\n\n\t\t@returns The current identity.\n\t\t@sa validate_identity(Var const&) const\n\t*\/\n\tidentity_vector_type&\n\tget_identity() noexcept {\n\t\treturn m_identity;\n\t}\n\n\t\/** @copydoc get_identity() *\/\n\tidentity_vector_type const&\n\tget_identity() const noexcept {\n\t\treturn m_identity;\n\t}\n\n\t\/**\n\t\tSet layout.\n\n\t\t@param layout New layout.\n\t\t@sa validate_layout(Var const&) const\n\t*\/\n\tvoid\n\tset_layout(\n\t\tlayout_vector_type layout\n\t) {\n\t\tm_layout = std::move(layout);\n\t}\n\n\t\/**\n\t\tGet layout.\n\n\t\t@returns The current layout.\n\t\t@sa validate_layout(Var const&) const\n\t*\/\n\tlayout_vector_type&\n\tget_layout() noexcept {\n\t\treturn m_layout;\n\t}\n\n\t\/** @copydoc get_layout() *\/\n\tlayout_vector_type const&\n\tget_layout() const noexcept {\n\t\treturn m_layout;\n\t}\n\n\/\/\/ @}\n\n\/** @name Validation *\/ \/\/\/ @{\n\t\/**\n\t\tValidate a variable.\n\n\t\t@note If @c validate_type(var) is @c true, layout validation\n\t\tis only done if @a var is a collection.\n\n\t\t@returns @c true iff @a var matches template in type, identity,\n\t\tand layout.\n\t\t@param var Variable to validate.\n\t\t@sa validate_type(Var const&) const,\n\t\t\tvalidate_identity(Var const&) const,\n\t\t\tvalidate_layout(Var const&) const\n\t*\/\n\tbool\n\tvalidate(\n\t\tVar const& var\n\t) const noexcept {\n\t\treturn\n\t\t\tvalidate_type(var) &&\n\t\t\tvalidate_identity(var) &&\n\t\t\t(!var.is_type_of(VarMask::collection) || validate_layout(var))\n\t\t;\n\t}\n\n\t\/**\n\t\tValidate a variable by type.\n\n\t\t@returns @c true iff bitwise-and of @a var type and template\n\t\ttype mask is non-zero.\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_type(\n\t\tVar const& var\n\t) const noexcept {\n\t\treturn var_type_is_of(var.get_type(), m_type_mask);\n\t}\n\n\t\/**\n\t\tValidate a variable by identity.\n\n\t\t@returns @c true iff:\n\t\t-# identity is empty (permits any name),\n\t\t-# variable name matches any name from identity\n\t\t (including empty name).\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_identity(\n\t\tVar const& var\n\t) const noexcept {\n\t\tif (m_identity.empty()) {\n\t\t\t\/\/ Any name is permitted with empty identity\n\t\t\treturn true;\n\t\t} else {\n\t\t\tfor (auto const& iname : get_identity()) {\n\t\t\t\tif (var.get_name() == iname) {\n\t\t\t\t\t\/\/ Variable name matches a name from identity\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Variable name does not match a name from identity\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/**\n\t\tValidate a variable by layout.\n\n\t\t@note The @c Field::Flags::optional flag will cause all succeeding\n\t\tfields to be considered optional.\n\t\t@note The @c Field::Flags::empty flag is only considered when layout\n\t\tcontains a single field.\n\n\t\t@returns\n\t\t- @c false iff:\n\t\t\t-# variable is not a @c VarMask::collection,\n\t\t\t-# variable has more children than layout;\n\t\t- @c true iff:\n\t\t\t-# layout is empty (permits any collection),\n\t\t\t-# layout contains a single field with flag\n\t\t\t @c Field::Flags::empty and variable has no children,\n\t\t\t-# children sequentially match layout fields exactly,\n\t\t\t-# children sequentially match [0..var.size()] layout fields\n\t\t\t if a field from [0..var.size()+1] is optional\n\t\t\t (thus making all subsequent fields optional).\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_layout(\n\t\tVar const& var\n\t) const noexcept {\n\t\tif (var.is_type_of(VarMask::collection)) {\n\t\t\tif (m_layout.empty()) {\n\t\t\t\t\/\/ Any collection is permitted with empty layout\n\t\t\t\treturn permit_empty();\n\t\t\t} else if (var.size() > get_layout().size()) {\n\t\t\t\t\/\/ Collection cannot be larger than layout\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tauto vc_iter = var.cbegin();\n\t\t\t\tauto lo_iter = get_layout().cbegin();\n\t\t\t\tbool optional_met = false;\n\t\t\t\tfor (; var.cend() != vc_iter; ++vc_iter, ++lo_iter) {\n\t\t\t\t\tif (!vc_iter->is_type_of(lo_iter->mask)) {\n\t\t\t\t\t\t\/\/ Child type does not match field\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t} else if (!optional_met) {\n\t\t\t\t\t\toptional_met = lo_iter->optional();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (optional_met || get_layout().cend() == lo_iter) {\n\t\t\t\t\t\/\/ Collection sequentially matches layout fields\n\t\t\t\t\t\/\/ exactly or any trailing fields are optional\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ No optional field has been met, and there are\n\t\t\t\t\t\/\/ unchecked trailing field(s)\n\t\t\t\t\tif (lo_iter->optional()) {\n\t\t\t\t\t\t\/\/ First trailing field is optional (therefore\n\t\t\t\t\t\t\/\/ all following fields are optional)\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ First trailing field is not optional\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Variable is not a collection\n\t\t\treturn false;\n\t\t}\n\t}\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group var\n\n} \/\/ namespace duct\n\n#endif \/\/ DUCT_VARTEMPLATE_HPP_\n<commit_msg>VarTemplate: defaulted cctor and copy operator=().¹<commit_after>\/**\n@file VarTemplate.hpp\n@brief Var validation.\n\n@author Tim Howard\n@copyright 2010-2013 Tim Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n\/\/ TODO: infinitism\n\n#ifndef DUCT_VARTEMPLATE_HPP_\n#define DUCT_VARTEMPLATE_HPP_\n\n#include \".\/config.hpp\"\n#include \".\/aux.hpp\"\n#include \".\/string.hpp\"\n#include \".\/StateStore.hpp\"\n#include \".\/VarType.hpp\"\n#include \".\/Var.hpp\"\n\n#include <utility>\n\nnamespace duct {\n\n\/**\n\t@addtogroup var\n\t@{\n*\/\n\n\/**\n\tVar validator.\n*\/\nclass VarTemplate {\npublic:\n\/** @name Types *\/ \/\/\/ @{\n\t\/**\n\t\tLayout field.\n\t*\/\n\tstruct Field {\n\t\/** @name Types *\/ \/\/\/ @{\n\t\t\/**\n\t\t\tField flags.\n\n\t\t\t@note See VarTemplate::validate_layout() for usage notes.\n\t\t*\/\n\t\tenum class Flags : unsigned {\n\t\t\t\/** No flags. *\/\n\t\t\tnone = 0,\n\n\t\t\t\/** Optional field. *\/\n\t\t\toptional = 1 << 0,\n\t\t};\n\t\/\/\/ @}\n\n\t\/** @name Properties *\/ \/\/\/ @{\n\t\t\/** Type mask. *\/\n\t\tVarMask mask;\n\n\t\t\/** Flags. *\/\n\t\tStateStore<Flags> flags;\n\n\t\t\/**\n\t\t\tCheck if Flags::optional is enabled.\n\t\t*\/\n\t\tbool\n\t\toptional() const noexcept {\n\t\t\treturn flags.test(Flags::optional);\n\t\t}\n\t\/\/\/ @}\n\n\t\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\t\/** Destructor. *\/\n\t\t~Field() = default;\n\t\t\/** Copy constructor. *\/\n\t\tField(Field const&) = default;\n\t\t\/** Move constructor. *\/\n\t\tField(Field&&) = default;\n\n\t\t\/**\n\t\t\tConstruct with flags.\n\n\t\t\t@note Mask is VarMask::none.\n\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(VarMask::none)\n\t\t\t, flags(flags)\n\t\t{}\n\n\t\t\/**\n\t\t\tConstruct with type and flags.\n\n\t\t\t@param type Single-type mask.\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tVarType const type,\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(var_mask(type))\n\t\t\t, flags(flags)\n\t\t{}\n\n\t\t\/**\n\t\t\tConstruct with mask and flags.\n\n\t\t\t@param mask Mask.\n\t\t\t@param flags %Flags.\n\t\t*\/\n\t\tField(\n\t\t\tVarMask const mask,\n\t\t\tFlags const flags = Flags::none\n\t\t) noexcept\n\t\t\t: mask(mask)\n\t\t\t, flags(flags)\n\t\t{}\n\t\/\/\/ @}\n\n\t\/** @name Operators *\/ \/\/\/ @{\n\t\t\/** Copy assignment operator. *\/\n\t\tField& operator=(Field const&) = default;\n\t\t\/** Move assignment operator. *\/\n\t\tField& operator=(Field&&) = default;\n\t\/\/\/ @}\n\t};\n\n\t\/** Identity vector type. *\/\n\tusing identity_vector_type = duct::aux::vector<u8string>;\n\t\/** Layout vector type. *\/\n\tusing layout_vector_type = duct::aux::vector<Field>;\n\/\/\/ @}\n\nprotected:\n\t\/**\n\t\t%Flags.\n\t*\/\n\tenum class Flags {\n\t\t\/**\n\t\t\tWhether to permit empty collections in layout validation.\n\n\t\t\t@note This is enabled by default.\n\t\t*\/\n\t\tpermit_empty = 1 << 0\n\t};\n\n\t\/** %Flags. *\/\n\tStateStore<Flags> m_flags{Flags::permit_empty};\n\t\/** Type mask. *\/\n\tVarMask m_type_mask{VarMask::none};\n\t\/** Identity. *\/\n\tidentity_vector_type m_identity{};\n\t\/** Layout. *\/\n\tlayout_vector_type m_layout{};\n\npublic:\n\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\/**\n\t\tConstruct with @c VarMask::none type mask, empty identity,\n\t\tand empty layout.\n\t*\/\n\tVarTemplate() = default;\n\n\t\/**\n\t\tConstruct with type mask, empty identity, and empty layout.\n\n\t\t@param type_mask Type mask.\n\t*\/\n\texplicit\n\tVarTemplate(\n\t\tVarMask const type_mask\n\t)\n\t\t: m_type_mask(type_mask)\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, identity, and empty layout.\n\n\t\t@param type_mask Type mask.\n\t\t@param identity Identity.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tidentity_vector_type identity\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_identity(std::move(identity))\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, layout, and empty identity.\n\n\t\t@param type_mask Type mask.\n\t\t@param layout Layout.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tlayout_vector_type layout\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_layout(std::move(layout))\n\t{}\n\n\t\/**\n\t\tConstruct with type mask, identity, and layout.\n\n\t\t@param type_mask Type mask.\n\t\t@param identity Identity.\n\t\t@param layout Layout.\n\t*\/\n\tVarTemplate(\n\t\tVarMask const type_mask,\n\t\tidentity_vector_type identity,\n\t\tlayout_vector_type layout\n\t)\n\t\t: m_type_mask(type_mask)\n\t\t, m_identity(std::move(identity))\n\t\t, m_layout(std::move(layout))\n\t{}\n\n\t\/** Copy constructor. *\/\n\tVarTemplate(VarTemplate const&) = default;\n\t\/** Move constructor. *\/\n\tVarTemplate(VarTemplate&&) = default;\n\t\/** Destructor. *\/\n\tvirtual ~VarTemplate() = default;\n\/\/\/ @}\n\n\/** @name Operators *\/ \/\/\/ @{\n\t\/** Copy assignment operator. *\/\n\tVarTemplate& operator=(VarTemplate const&) = default;\n\t\/** Move assignment operator. *\/\n\tVarTemplate& operator=(VarTemplate&&) = default;\n\/\/\/ @}\n\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tEnable or disable flags.\n\n\t\t@param flags %Flags.\n\t\t@param enable Whether to enable or disable the flags.\n\t*\/\n\tvoid\n\tset_flags(\n\t\tFlags const flags,\n\t\tbool const enable\n\t) noexcept {\n\t\tm_flags.set(flags, enable);\n\t}\n\n\t\/**\n\t\tCheck if Flags::permit_empty is enabled.\n\t*\/\n\tbool\n\tpermit_empty() const noexcept {\n\t\treturn m_flags.test(Flags::permit_empty);\n\t}\n\n\t\/**\n\t\tSet type mask.\n\n\t\t@param type_mask New type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tvoid\n\tset_type_mask(\n\t\tVarMask const type_mask\n\t) noexcept {\n\t\tm_type_mask = type_mask;\n\t}\n\n\t\/**\n\t\tSet type mask (single type).\n\n\t\t@param type New type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tvoid\n\tset_type_mask(\n\t\tVarType const type\n\t) noexcept {\n\t\tm_type_mask = var_mask(type);\n\t}\n\n\t\/**\n\t\tGet type mask.\n\n\t\t@returns The current type mask.\n\t\t@sa validate_type(Var const&) const\n\t*\/\n\tVarMask\n\tget_type_mask() const noexcept {\n\t\treturn m_type_mask;\n\t}\n\n\t\/**\n\t\tSet identity.\n\n\t\t@param identity New identity.\n\t\t@sa validate_identity(Var const&) const\n\t*\/\n\tvoid\n\tset_identity(\n\t\tidentity_vector_type identity\n\t) {\n\t\tm_identity = std::move(identity);\n\t}\n\n\t\/**\n\t\tGet identity.\n\n\t\t@returns The current identity.\n\t\t@sa validate_identity(Var const&) const\n\t*\/\n\tidentity_vector_type&\n\tget_identity() noexcept {\n\t\treturn m_identity;\n\t}\n\n\t\/** @copydoc get_identity() *\/\n\tidentity_vector_type const&\n\tget_identity() const noexcept {\n\t\treturn m_identity;\n\t}\n\n\t\/**\n\t\tSet layout.\n\n\t\t@param layout New layout.\n\t\t@sa validate_layout(Var const&) const\n\t*\/\n\tvoid\n\tset_layout(\n\t\tlayout_vector_type layout\n\t) {\n\t\tm_layout = std::move(layout);\n\t}\n\n\t\/**\n\t\tGet layout.\n\n\t\t@returns The current layout.\n\t\t@sa validate_layout(Var const&) const\n\t*\/\n\tlayout_vector_type&\n\tget_layout() noexcept {\n\t\treturn m_layout;\n\t}\n\n\t\/** @copydoc get_layout() *\/\n\tlayout_vector_type const&\n\tget_layout() const noexcept {\n\t\treturn m_layout;\n\t}\n\n\/\/\/ @}\n\n\/** @name Validation *\/ \/\/\/ @{\n\t\/**\n\t\tValidate a variable.\n\n\t\t@note If @c validate_type(var) is @c true, layout validation\n\t\tis only done if @a var is a collection.\n\n\t\t@returns @c true iff @a var matches template in type, identity,\n\t\tand layout.\n\t\t@param var Variable to validate.\n\t\t@sa validate_type(Var const&) const,\n\t\t\tvalidate_identity(Var const&) const,\n\t\t\tvalidate_layout(Var const&) const\n\t*\/\n\tbool\n\tvalidate(\n\t\tVar const& var\n\t) const noexcept {\n\t\treturn\n\t\t\tvalidate_type(var) &&\n\t\t\tvalidate_identity(var) &&\n\t\t\t(!var.is_type_of(VarMask::collection) || validate_layout(var))\n\t\t;\n\t}\n\n\t\/**\n\t\tValidate a variable by type.\n\n\t\t@returns @c true iff bitwise-and of @a var type and template\n\t\ttype mask is non-zero.\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_type(\n\t\tVar const& var\n\t) const noexcept {\n\t\treturn var_type_is_of(var.get_type(), m_type_mask);\n\t}\n\n\t\/**\n\t\tValidate a variable by identity.\n\n\t\t@returns @c true iff:\n\t\t-# identity is empty (permits any name),\n\t\t-# variable name matches any name from identity\n\t\t (including empty name).\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_identity(\n\t\tVar const& var\n\t) const noexcept {\n\t\tif (m_identity.empty()) {\n\t\t\t\/\/ Any name is permitted with empty identity\n\t\t\treturn true;\n\t\t} else {\n\t\t\tfor (auto const& iname : get_identity()) {\n\t\t\t\tif (var.get_name() == iname) {\n\t\t\t\t\t\/\/ Variable name matches a name from identity\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Variable name does not match a name from identity\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/**\n\t\tValidate a variable by layout.\n\n\t\t@note The @c Field::Flags::optional flag will cause all succeeding\n\t\tfields to be considered optional.\n\t\t@note The @c Field::Flags::empty flag is only considered when layout\n\t\tcontains a single field.\n\n\t\t@returns\n\t\t- @c false iff:\n\t\t\t-# variable is not a @c VarMask::collection,\n\t\t\t-# variable has more children than layout;\n\t\t- @c true iff:\n\t\t\t-# layout is empty (permits any collection),\n\t\t\t-# layout contains a single field with flag\n\t\t\t @c Field::Flags::empty and variable has no children,\n\t\t\t-# children sequentially match layout fields exactly,\n\t\t\t-# children sequentially match [0..var.size()] layout fields\n\t\t\t if a field from [0..var.size()+1] is optional\n\t\t\t (thus making all subsequent fields optional).\n\t\t@param var Variable to validate.\n\t*\/\n\tvirtual bool\n\tvalidate_layout(\n\t\tVar const& var\n\t) const noexcept {\n\t\tif (var.is_type_of(VarMask::collection)) {\n\t\t\tif (m_layout.empty()) {\n\t\t\t\t\/\/ Any collection is permitted with empty layout\n\t\t\t\treturn permit_empty();\n\t\t\t} else if (var.size() > get_layout().size()) {\n\t\t\t\t\/\/ Collection cannot be larger than layout\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tauto vc_iter = var.cbegin();\n\t\t\t\tauto lo_iter = get_layout().cbegin();\n\t\t\t\tbool optional_met = false;\n\t\t\t\tfor (; var.cend() != vc_iter; ++vc_iter, ++lo_iter) {\n\t\t\t\t\tif (!vc_iter->is_type_of(lo_iter->mask)) {\n\t\t\t\t\t\t\/\/ Child type does not match field\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t} else if (!optional_met) {\n\t\t\t\t\t\toptional_met = lo_iter->optional();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (optional_met || get_layout().cend() == lo_iter) {\n\t\t\t\t\t\/\/ Collection sequentially matches layout fields\n\t\t\t\t\t\/\/ exactly or any trailing fields are optional\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ No optional field has been met, and there are\n\t\t\t\t\t\/\/ unchecked trailing field(s)\n\t\t\t\t\tif (lo_iter->optional()) {\n\t\t\t\t\t\t\/\/ First trailing field is optional (therefore\n\t\t\t\t\t\t\/\/ all following fields are optional)\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ First trailing field is not optional\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Variable is not a collection\n\t\t\treturn false;\n\t\t}\n\t}\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group var\n\n} \/\/ namespace duct\n\n#endif \/\/ DUCT_VARTEMPLATE_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"SuiteExternalRelations.h\"\n#include \"SuiteCommon.h\"\n#include <string>\n#include <windows.h>\n#include <initguid.h>\n#include <mstask.h>\n#include <taskschd.h>\n#include <lmcons.h>\n#include \"taskschd_hs.h\"\n\n#ifdef DEBUG\n#include <iostream>\n#endif\n\nnamespace SuiteExtRel {\n\tint Schedule10(bool &na);\n\tint Schedule20(bool &na, bool current_user);\n}\n\nint SuiteExtRel::Schedule(bool current_user)\n{\n\tint ret;\n\tbool na;\n\t\n\tret=Schedule20(na, current_user);\n\tif (na) {\n\t\tif (!current_user) {\n\t\t\t\/\/In Task Scheduler 1.0 you can't run task for any logged on user by using BUILTIN\\Users group as user like in 2.0\n\t\t\tErrorMessage(L\"Task Scheduler 1.0 doesn't support scheduling GUI apps for all users!\");\n\t\t\treturn ERR_SUITEEXTREL+3;\n\t\t} else if ((ret=Schedule10(na), na)) {\n\t\t\tErrorMessage(L\"Task Scheduler 1.0 not available!\");\n\t\t\treturn ERR_SUITEEXTREL+4;\n\t\t}\n\t}\n\tif (ret) ErrorMessage(L\"Error scheduling SnK HotkeySuite!\");\n\t\n\treturn ret;\n}\n\nint SuiteExtRel::Schedule10(bool &na)\n{\n\tint ret=ERR_SUITEEXTREL+1;\n\tna=false;\n\t\n\tCoInitialize(NULL);\n\t\n\twchar_t uname[UNLEN+1];\n\tDWORD uname_len=UNLEN+1;\n\tGetUserName(uname, &uname_len);\n\tstd::wstring tname(L\"SnK HotkeySuite [\");\n\ttname.append(uname);\n\ttname.append({L']'});\n\t\n\tITaskScheduler *pITS;\n\tif (SUCCEEDED(CoCreateInstance(CLSID_CTaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, (void**)&pITS))) {\n#ifdef DEBUG\n\t\tstd::wcerr<<L\"SCHEDULE: Task Scheduler 1.0 available\"<<std::endl;\n#endif\n\t\tITask *pITask;\n\t\tif (SUCCEEDED(pITS->NewWorkItem(tname.c_str(), CLSID_CTask, IID_ITask, (IUnknown**)&pITask))) {\n\t\t\tITaskTrigger *pITaskTrigger;\n\t\t\tWORD piNewTrigger;\n\t\t\tif (SUCCEEDED(pITask->SetApplicationName(GetExecutableFileName().c_str()))&&\n\t\t\t\tSUCCEEDED(pITask->SetWorkingDirectory(GetExecutableFileName(L\"\").c_str()))&&\n\t\t\t\tSUCCEEDED(pITask->SetMaxRunTime(INFINITE))&&\n\t\t\t\tSUCCEEDED(pITask->SetFlags(TASK_FLAG_RUN_ONLY_IF_LOGGED_ON))&&\t\t\/\/TASK_FLAG_RUN_ONLY_IF_LOGGED_ON required if pwszPassword in SetAccountInformation is NULL\n\t\t\t\tSUCCEEDED(pITask->SetAccountInformation(uname, NULL))&&\t\t\t\t\/\/Required\n\t\t\t\tSUCCEEDED(pITask->CreateTrigger(&piNewTrigger, &pITaskTrigger))) {\n\t\t\t\tTASK_TRIGGER trigger={};\n\t\t\t\ttrigger.wBeginDay=1;\t\t\/\/Required\n\t\t\t\ttrigger.wBeginMonth=1;\t\t\/\/Required\n\t\t\t\ttrigger.wBeginYear=1970;\t\/\/Required\n\t\t\t\ttrigger.cbTriggerSize=sizeof(TASK_TRIGGER);\n\t\t\t\ttrigger.TriggerType=TASK_EVENT_TRIGGER_AT_LOGON;\n\t\t\t\t\n\t\t\t\tif (SUCCEEDED(pITaskTrigger->SetTrigger(&trigger))) {\n\t\t\t\t\tIPersistFile *pIPersistFile;\n\t\t\t\t\tif (SUCCEEDED(pITask->QueryInterface(IID_PPV_ARGS(&pIPersistFile)))) {\n\t\t\t\t\t\tif (SUCCEEDED(pIPersistFile->Save(NULL, TRUE))) ret=0;\n\t\t\t\t\t\tpIPersistFile->Release();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpITaskTrigger->Release();\n\t\t\t}\n\t\t\tpITask->Release();\n\t\t}\n\t\tpITS->Release();\n\t} else {\n\t\tna=true;\n\t\tret=0;\n\t}\n\t\n\tCoUninitialize();\n\t\n\treturn ret;\n}\n\nint SuiteExtRel::Schedule20(bool &na, bool current_user)\n{\n\tint ret=ERR_SUITEEXTREL+2;\n\tna=false;\n\t\n\tCoInitialize(NULL);\t\/\/Same as CoInitializeEx(NULL, COINIT_APARTMENTTHREADED), whatever, we don't need COINIT_MULTITHREADED\n\t\/\/CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,0,NULL);\n\t\n\tstd::wstring tname(L\"SnK HotkeySuite\");\n\tBSTR uname_bstr=NULL;\t\n\tif (current_user) {\n\t\twchar_t uname[UNLEN+1];\n\t\tDWORD uname_len=UNLEN+1;\n\t\tGetUserName(uname, &uname_len);\n\t\ttname.append({L' ', L'['});\n\t\ttname.append(uname);\n\t\ttname.append({L']'});\n\t} else {\n\t\tuname_bstr=SysAllocString(L\"Users\");\n\t}\n\t\n\tITaskService *pService;\n\tif (SUCCEEDED(CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService))) {\n#ifdef DEBUG\n\t\tstd::wcerr<<L\"SCHEDULE: Task Scheduler 2.0 available\"<<std::endl;\n#endif\n\t\tITaskDefinition *pTask;\n\t\tVARIANT empty_var={VT_EMPTY};\n\t\tif (SUCCEEDED(pService->Connect(empty_var, empty_var, empty_var, empty_var))&&\n\t\t\tSUCCEEDED(pService->NewTask(0, &pTask))) {\n\t\t\tIPrincipal *pPrincipal;\n\t\t\tif (SUCCEEDED(pTask->get_Principal(&pPrincipal))) {\n\t\t\t\tITaskSettings *pTaskSettings;\n\t\t\t\tif (SUCCEEDED(pPrincipal->put_RunLevel(TASK_RUNLEVEL_HIGHEST))&&\n\t\t\t\t\t(current_user?true:(uname_bstr&&SUCCEEDED(pPrincipal->put_GroupId(uname_bstr))))&&\n\t\t\t\t\tSUCCEEDED(pTask->get_Settings(&pTaskSettings))) {\n\t\t\t\t\tif (BSTR infinite_bstr=SysAllocString(L\"PT0S\")) {\n\t\t\t\t\t\tITriggerCollection *pTriggerCollection;\n\t\t\t\t\t\tif (SUCCEEDED(pTaskSettings->put_ExecutionTimeLimit(infinite_bstr))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTaskSettings->put_StopIfGoingOnBatteries(VARIANT_FALSE))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTaskSettings->put_DisallowStartIfOnBatteries(VARIANT_FALSE))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTask->get_Triggers(&pTriggerCollection))) {\n\t\t\t\t\t\t\tITrigger *pTrigger;\n\t\t\t\t\t\t\tif (SUCCEEDED(pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger))) {\n\t\t\t\t\t\t\t\tIActionCollection *pActionCollection;\n\t\t\t\t\t\t\t\tif (SUCCEEDED(pTask->get_Actions(&pActionCollection))) {\n\t\t\t\t\t\t\t\t\tIAction *pAction;\n\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pActionCollection->Create(TASK_ACTION_EXEC, &pAction))) {\n\t\t\t\t\t\t\t\t\t\tIExecAction *pExecAction;\n\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction))) {\n\t\t\t\t\t\t\t\t\t\t\tif (BSTR hspath_bstr=SysAllocString(GetExecutableFileName().c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (BSTR hsdir_bstr=SysAllocString(GetExecutableFileName(L\"\").c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tBSTR root_bstr;\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pExecAction->put_Path(hspath_bstr))&&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSUCCEEDED(pExecAction->put_WorkingDirectory(hsdir_bstr))&&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(root_bstr=SysAllocString(L\"\\\\\"))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tITaskFolder *pRootFolder;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pService->GetFolder(root_bstr, &pRootFolder))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (BSTR tname_bstr=SysAllocString(tname.c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIRegisteredTask *pRegisteredTask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pRootFolder->RegisterTaskDefinition(tname_bstr, pTask, TASK_CREATE_OR_UPDATE, empty_var, empty_var, TASK_LOGON_INTERACTIVE_TOKEN, empty_var, &pRegisteredTask))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tret=0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpRegisteredTask->Release();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(tname_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpRootFolder->Release();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(root_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(hsdir_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(hspath_bstr);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tpExecAction->Release();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tpAction->Release();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tpActionCollection->Release();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpTrigger->Release();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpTriggerCollection->Release();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSysFreeString(infinite_bstr);\n\t\t\t\t\t}\n\t\t\t\t\tpTaskSettings->Release();\n\t\t\t\t}\n\t\t\t\tpPrincipal->Release();\n\t\t\t}\n\t\t\tpTask->Release();\n\t\t}\n\t\tpService->Release();\n\t} else {\n\t\tna=true;\n\t\tret=0;\n\t}\n\t\n\tif (uname_bstr)\n\t\tSysFreeString(uname_bstr);\n\t\n\tCoUninitialize();\n\t\n\treturn ret;\n}<commit_msg>Scheduled tasks should be silently recreated if exist<commit_after>#include \"SuiteExternalRelations.h\"\n#include \"SuiteCommon.h\"\n#include <string>\n#include <windows.h>\n#include <initguid.h>\n#include <mstask.h>\n#include <taskschd.h>\n#include <lmcons.h>\n#include \"taskschd_hs.h\"\n\n#ifdef DEBUG\n#include <iostream>\n#endif\n\nnamespace SuiteExtRel {\n\tint Schedule10(bool &na);\n\tint Schedule20(bool &na, bool current_user);\n}\n\nint SuiteExtRel::Schedule(bool current_user)\n{\n\tint ret;\n\tbool na;\n\t\n\tret=Schedule20(na, current_user);\n\tif (na) {\n\t\tif (!current_user) {\n\t\t\t\/\/In Task Scheduler 1.0 you can't run task for any logged on user by using BUILTIN\\Users group as user like in 2.0\n\t\t\tErrorMessage(L\"Task Scheduler 1.0 doesn't support scheduling GUI apps for all users!\");\n\t\t\treturn ERR_SUITEEXTREL+3;\n\t\t} else if ((ret=Schedule10(na), na)) {\n\t\t\tErrorMessage(L\"Task Scheduler 1.0 not available!\");\n\t\t\treturn ERR_SUITEEXTREL+4;\n\t\t}\n\t}\n\tif (ret) ErrorMessage(L\"Error scheduling SnK HotkeySuite! Make sure that you have Admin rights before scheduling a task.\");\n\t\n\treturn ret;\n}\n\nint SuiteExtRel::Schedule10(bool &na)\n{\n\tint ret=ERR_SUITEEXTREL+1;\n\tna=false;\n\t\n\tCoInitialize(NULL);\n\t\n\twchar_t uname[UNLEN+1];\n\tDWORD uname_len=UNLEN+1;\n\tGetUserName(uname, &uname_len);\n\tstd::wstring tname(L\"SnK HotkeySuite [\");\n\ttname.append(uname);\n\ttname.append({L']'});\n\t\n\tITaskScheduler *pITS;\n\tif (SUCCEEDED(CoCreateInstance(CLSID_CTaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, (void**)&pITS))) {\n#ifdef DEBUG\n\t\tstd::wcerr<<L\"SCHEDULE: Task Scheduler 1.0 available\"<<std::endl;\n#endif\n\t\tITask *pITask;\n\t\t\/\/ITask->Delete w\/ ITask->NewWorkItem: if task exists - we are silently recreating it\n\t\tpITS->Delete(tname.c_str());\n\t\tif (SUCCEEDED(pITS->NewWorkItem(tname.c_str(), CLSID_CTask, IID_ITask, (IUnknown**)&pITask))) {\n\t\t\tITaskTrigger *pITaskTrigger;\n\t\t\tWORD piNewTrigger;\n\t\t\tif (SUCCEEDED(pITask->SetApplicationName(GetExecutableFileName().c_str()))&&\n\t\t\t\tSUCCEEDED(pITask->SetWorkingDirectory(GetExecutableFileName(L\"\").c_str()))&&\n\t\t\t\tSUCCEEDED(pITask->SetMaxRunTime(INFINITE))&&\n\t\t\t\tSUCCEEDED(pITask->SetFlags(TASK_FLAG_RUN_ONLY_IF_LOGGED_ON))&&\t\t\/\/TASK_FLAG_RUN_ONLY_IF_LOGGED_ON required if pwszPassword in SetAccountInformation is NULL\n\t\t\t\tSUCCEEDED(pITask->SetAccountInformation(uname, NULL))&&\t\t\t\t\/\/Required\n\t\t\t\tSUCCEEDED(pITask->CreateTrigger(&piNewTrigger, &pITaskTrigger))) {\n\t\t\t\tTASK_TRIGGER trigger={};\n\t\t\t\ttrigger.wBeginDay=1;\t\t\/\/Required\n\t\t\t\ttrigger.wBeginMonth=1;\t\t\/\/Required\n\t\t\t\ttrigger.wBeginYear=1970;\t\/\/Required\n\t\t\t\ttrigger.cbTriggerSize=sizeof(TASK_TRIGGER);\n\t\t\t\ttrigger.TriggerType=TASK_EVENT_TRIGGER_AT_LOGON;\n\t\t\t\t\n\t\t\t\tif (SUCCEEDED(pITaskTrigger->SetTrigger(&trigger))) {\n\t\t\t\t\tIPersistFile *pIPersistFile;\n\t\t\t\t\tif (SUCCEEDED(pITask->QueryInterface(IID_PPV_ARGS(&pIPersistFile)))) {\n\t\t\t\t\t\tif (SUCCEEDED(pIPersistFile->Save(NULL, TRUE))) ret=0;\n\t\t\t\t\t\tpIPersistFile->Release();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpITaskTrigger->Release();\n\t\t\t}\n\t\t\tpITask->Release();\n\t\t}\n\t\tpITS->Release();\n\t} else {\n\t\tna=true;\n\t\tret=0;\n\t}\n\t\n\tCoUninitialize();\n\t\n\treturn ret;\n}\n\nint SuiteExtRel::Schedule20(bool &na, bool current_user)\n{\n\tint ret=ERR_SUITEEXTREL+2;\n\tna=false;\n\t\n\tCoInitialize(NULL);\t\/\/Same as CoInitializeEx(NULL, COINIT_APARTMENTTHREADED), whatever, we don't need COINIT_MULTITHREADED\n\t\n\tstd::wstring tname(L\"SnK HotkeySuite\");\n\tBSTR uname_bstr=NULL;\t\n\tif (current_user) {\n\t\twchar_t uname[UNLEN+1];\n\t\tDWORD uname_len=UNLEN+1;\n\t\tGetUserName(uname, &uname_len);\n\t\ttname.append({L' ', L'['});\n\t\ttname.append(uname);\n\t\ttname.append({L']'});\n\t} else {\n\t\tuname_bstr=SysAllocString(L\"Users\");\n\t}\n\t\n\tITaskService *pService;\n\tif (SUCCEEDED(CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService))) {\n#ifdef DEBUG\n\t\tstd::wcerr<<L\"SCHEDULE: Task Scheduler 2.0 available\"<<std::endl;\n#endif\n\t\tITaskDefinition *pTask;\n\t\tVARIANT empty_var={VT_EMPTY};\n\t\tif (SUCCEEDED(pService->Connect(empty_var, empty_var, empty_var, empty_var))&&\n\t\t\tSUCCEEDED(pService->NewTask(0, &pTask))) {\n\t\t\tIPrincipal *pPrincipal;\n\t\t\tif (SUCCEEDED(pTask->get_Principal(&pPrincipal))) {\n\t\t\t\tITaskSettings *pTaskSettings;\n\t\t\t\tif (SUCCEEDED(pPrincipal->put_RunLevel(TASK_RUNLEVEL_HIGHEST))&&\n\t\t\t\t\t(current_user?true:(uname_bstr&&SUCCEEDED(pPrincipal->put_GroupId(uname_bstr))))&&\n\t\t\t\t\tSUCCEEDED(pTask->get_Settings(&pTaskSettings))) {\n\t\t\t\t\tif (BSTR infinite_bstr=SysAllocString(L\"PT0S\")) {\n\t\t\t\t\t\tITriggerCollection *pTriggerCollection;\n\t\t\t\t\t\tif (SUCCEEDED(pTaskSettings->put_ExecutionTimeLimit(infinite_bstr))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTaskSettings->put_StopIfGoingOnBatteries(VARIANT_FALSE))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTaskSettings->put_DisallowStartIfOnBatteries(VARIANT_FALSE))&&\n\t\t\t\t\t\t\tSUCCEEDED(pTask->get_Triggers(&pTriggerCollection))) {\n\t\t\t\t\t\t\tITrigger *pTrigger;\n\t\t\t\t\t\t\tif (SUCCEEDED(pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger))) {\n\t\t\t\t\t\t\t\tIActionCollection *pActionCollection;\n\t\t\t\t\t\t\t\tif (SUCCEEDED(pTask->get_Actions(&pActionCollection))) {\n\t\t\t\t\t\t\t\t\tIAction *pAction;\n\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pActionCollection->Create(TASK_ACTION_EXEC, &pAction))) {\n\t\t\t\t\t\t\t\t\t\tIExecAction *pExecAction;\n\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction))) {\n\t\t\t\t\t\t\t\t\t\t\tif (BSTR hspath_bstr=SysAllocString(GetExecutableFileName().c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (BSTR hsdir_bstr=SysAllocString(GetExecutableFileName(L\"\").c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tBSTR root_bstr;\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pExecAction->put_Path(hspath_bstr))&&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSUCCEEDED(pExecAction->put_WorkingDirectory(hsdir_bstr))&&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(root_bstr=SysAllocString(L\"\\\\\"))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tITaskFolder *pRootFolder;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pService->GetFolder(root_bstr, &pRootFolder))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (BSTR tname_bstr=SysAllocString(tname.c_str())) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIRegisteredTask *pRegisteredTask;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/ITaskService->NewTask w\/ TASK_CREATE_OR_UPDATE: if task exists - we are silently recreating it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (SUCCEEDED(pRootFolder->RegisterTaskDefinition(tname_bstr, pTask, TASK_CREATE_OR_UPDATE, empty_var, empty_var, TASK_LOGON_INTERACTIVE_TOKEN, empty_var, &pRegisteredTask))) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tret=0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpRegisteredTask->Release();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(tname_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpRootFolder->Release();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(root_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(hsdir_bstr);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tSysFreeString(hspath_bstr);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tpExecAction->Release();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tpAction->Release();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tpActionCollection->Release();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpTrigger->Release();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpTriggerCollection->Release();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSysFreeString(infinite_bstr);\n\t\t\t\t\t}\n\t\t\t\t\tpTaskSettings->Release();\n\t\t\t\t}\n\t\t\t\tpPrincipal->Release();\n\t\t\t}\n\t\t\tpTask->Release();\n\t\t}\n\t\tpService->Release();\n\t} else {\n\t\tna=true;\n\t\tret=0;\n\t}\n\t\n\tif (uname_bstr)\n\t\tSysFreeString(uname_bstr);\n\t\n\tCoUninitialize();\n\t\n\treturn ret;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class wrap target description classes used by the various code\n\/\/ generation TableGen backends. This makes it easier to access the data and\n\/\/ provides a single place that needs to check it for validity. All of these\n\/\/ classes throw exceptions on error conditions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include <set>\n#include <algorithm>\nusing namespace llvm;\n\nstatic cl::opt<unsigned>\nAsmWriterNum(\"asmwriternum\", cl::init(0),\n cl::desc(\"Make -gen-asm-writer emit assembly writer #N\"));\n\n\/\/\/ getValueType - Return the MCV::ValueType that the specified TableGen record\n\/\/\/ corresponds to.\nMVT::ValueType llvm::getValueType(Record *Rec) {\n return (MVT::ValueType)Rec->getValueAsInt(\"Value\");\n}\n\nstd::string llvm::getName(MVT::ValueType T) {\n switch (T) {\n case MVT::Other: return \"UNKNOWN\";\n case MVT::i1: return \"i1\";\n case MVT::i8: return \"i8\";\n case MVT::i16: return \"i16\";\n case MVT::i32: return \"i32\";\n case MVT::i64: return \"i64\";\n case MVT::i128: return \"i128\";\n case MVT::f32: return \"f32\";\n case MVT::f64: return \"f64\";\n case MVT::f80: return \"f80\";\n case MVT::f128: return \"f128\";\n case MVT::Flag: return \"Flag\";\n case MVT::isVoid:return \"void\";\n case MVT::v8i8: return \"v8i8\";\n case MVT::v4i16: return \"v4i16\";\n case MVT::v2i32: return \"v2i32\";\n case MVT::v16i8: return \"v16i8\";\n case MVT::v8i16: return \"v8i16\";\n case MVT::v4i32: return \"v4i32\";\n case MVT::v2i64: return \"v2i64\";\n case MVT::v2f32: return \"v2f32\";\n case MVT::v4f32: return \"v4f32\";\n case MVT::v2f64: return \"v2f64\";\n default: assert(0 && \"ILLEGAL VALUE TYPE!\"); return \"\";\n }\n}\n\nstd::string llvm::getEnumName(MVT::ValueType T) {\n switch (T) {\n case MVT::Other: return \"Other\";\n case MVT::i1: return \"i1\";\n case MVT::i8: return \"i8\";\n case MVT::i16: return \"i16\";\n case MVT::i32: return \"i32\";\n case MVT::i64: return \"i64\";\n case MVT::i128: return \"i128\";\n case MVT::f32: return \"f32\";\n case MVT::f64: return \"f64\";\n case MVT::f80: return \"f80\";\n case MVT::f128: return \"f128\";\n case MVT::Flag: return \"Flag\";\n case MVT::isVoid:return \"isVoid\";\n case MVT::v16i8: return \"v16i8\";\n case MVT::v8i16: return \"v8i16\";\n case MVT::v4i32: return \"v4i32\";\n case MVT::v2i64: return \"v2i64\";\n case MVT::v2f32: return \"v2f32\";\n case MVT::v4f32: return \"v4f32\";\n case MVT::v2f64: return \"v2f64\";\n default: assert(0 && \"ILLEGAL VALUE TYPE!\"); return \"\";\n }\n}\n\n\nstd::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {\n return OS << getName(T);\n}\n\n\n\/\/\/ getTarget - Return the current instance of the Target class.\n\/\/\/\nCodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {\n std::vector<Record*> Targets = Records.getAllDerivedDefinitions(\"Target\");\n if (Targets.size() == 0)\n throw std::string(\"ERROR: No 'Target' subclasses defined!\");\n if (Targets.size() != 1)\n throw std::string(\"ERROR: Multiple subclasses of Target defined!\");\n TargetRec = Targets[0];\n\n \/\/ Read in all of the CalleeSavedRegisters.\n CalleeSavedRegisters =TargetRec->getValueAsListOfDefs(\"CalleeSavedRegisters\");\n PointerType = getValueType(TargetRec->getValueAsDef(\"PointerType\"));\n}\n\n\nconst std::string &CodeGenTarget::getName() const {\n return TargetRec->getName();\n}\n\nRecord *CodeGenTarget::getInstructionSet() const {\n return TargetRec->getValueAsDef(\"InstructionSet\");\n}\n\n\/\/\/ getAsmWriter - Return the AssemblyWriter definition for this target.\n\/\/\/\nRecord *CodeGenTarget::getAsmWriter() const {\n std::vector<Record*> LI = TargetRec->getValueAsListOfDefs(\"AssemblyWriters\");\n if (AsmWriterNum >= LI.size())\n throw \"Target does not have an AsmWriter #\" + utostr(AsmWriterNum) + \"!\";\n return LI[AsmWriterNum];\n}\n\nvoid CodeGenTarget::ReadRegisters() const {\n std::vector<Record*> Regs = Records.getAllDerivedDefinitions(\"Register\");\n if (Regs.empty())\n throw std::string(\"No 'Register' subclasses defined!\");\n\n Registers.reserve(Regs.size());\n Registers.assign(Regs.begin(), Regs.end());\n}\n\nCodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {\n DeclaredSpillSize = R->getValueAsInt(\"SpillSize\");\n DeclaredSpillAlignment = R->getValueAsInt(\"SpillAlignment\");\n}\n\nconst std::string &CodeGenRegister::getName() const {\n return TheDef->getName();\n}\n\nvoid CodeGenTarget::ReadRegisterClasses() const {\n std::vector<Record*> RegClasses =\n Records.getAllDerivedDefinitions(\"RegisterClass\");\n if (RegClasses.empty())\n throw std::string(\"No 'RegisterClass' subclasses defined!\");\n\n RegisterClasses.reserve(RegClasses.size());\n RegisterClasses.assign(RegClasses.begin(), RegClasses.end());\n}\n\nCodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {\n \/\/ Rename anonymous register classes.\n if (R->getName().size() > 9 && R->getName()[9] == '.') {\n static unsigned AnonCounter = 0;\n R->setName(\"AnonRegClass_\"+utostr(AnonCounter++));\n } \n \n std::vector<Record*> TypeList = R->getValueAsListOfDefs(\"RegTypes\");\n for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {\n Record *Type = TypeList[i];\n if (!Type->isSubClassOf(\"ValueType\"))\n throw \"RegTypes list member '\" + Type->getName() +\n \"' does not derive from the ValueType class!\";\n VTs.push_back(getValueType(Type));\n }\n assert(!VTs.empty() && \"RegisterClass must contain at least one ValueType!\");\n \n std::vector<Record*> RegList = R->getValueAsListOfDefs(\"MemberList\");\n for (unsigned i = 0, e = RegList.size(); i != e; ++i) {\n Record *Reg = RegList[i];\n if (!Reg->isSubClassOf(\"Register\"))\n throw \"Register Class member '\" + Reg->getName() +\n \"' does not derive from the Register class!\";\n Elements.push_back(Reg);\n }\n \n \/\/ Allow targets to override the size in bits of the RegisterClass.\n unsigned Size = R->getValueAsInt(\"Size\");\n\n Namespace = R->getValueAsString(\"Namespace\");\n SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);\n SpillAlignment = R->getValueAsInt(\"Alignment\");\n MethodBodies = R->getValueAsCode(\"MethodBodies\");\n MethodProtos = R->getValueAsCode(\"MethodProtos\");\n}\n\nconst std::string &CodeGenRegisterClass::getName() const {\n return TheDef->getName();\n}\n\nvoid CodeGenTarget::ReadLegalValueTypes() const {\n const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();\n for (unsigned i = 0, e = RCs.size(); i != e; ++i)\n for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)\n LegalValueTypes.push_back(RCs[i].VTs[ri]);\n \n \/\/ Remove duplicates.\n std::sort(LegalValueTypes.begin(), LegalValueTypes.end());\n LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),\n LegalValueTypes.end()),\n LegalValueTypes.end());\n}\n\n\nvoid CodeGenTarget::ReadInstructions() const {\n std::vector<Record*> Insts = Records.getAllDerivedDefinitions(\"Instruction\");\n if (Insts.size() <= 2)\n throw std::string(\"No 'Instruction' subclasses defined!\");\n\n \/\/ Parse the instructions defined in the .td file.\n std::string InstFormatName =\n getAsmWriter()->getValueAsString(\"InstFormatName\");\n\n for (unsigned i = 0, e = Insts.size(); i != e; ++i) {\n std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);\n Instructions.insert(std::make_pair(Insts[i]->getName(),\n CodeGenInstruction(Insts[i], AsmStr)));\n }\n}\n\n\/\/\/ getInstructionsByEnumValue - Return all of the instructions defined by the\n\/\/\/ target, ordered by their enum value.\nvoid CodeGenTarget::\ngetInstructionsByEnumValue(std::vector<const CodeGenInstruction*>\n &NumberedInstructions) {\n std::map<std::string, CodeGenInstruction>::const_iterator I;\n I = getInstructions().find(\"PHI\");\n if (I == Instructions.end()) throw \"Could not find 'PHI' instruction!\";\n const CodeGenInstruction *PHI = &I->second;\n \n I = getInstructions().find(\"INLINEASM\");\n if (I == Instructions.end()) throw \"Could not find 'INLINEASM' instruction!\";\n const CodeGenInstruction *INLINEASM = &I->second;\n \n \/\/ Print out the rest of the instructions now.\n NumberedInstructions.push_back(PHI);\n NumberedInstructions.push_back(INLINEASM);\n for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)\n if (&II->second != PHI &&&II->second != INLINEASM)\n NumberedInstructions.push_back(&II->second);\n}\n\n\n\/\/\/ isLittleEndianEncoding - Return whether this target encodes its instruction\n\/\/\/ in little-endian format, i.e. bits laid out in the order [0..n]\n\/\/\/\nbool CodeGenTarget::isLittleEndianEncoding() const {\n return getInstructionSet()->getValueAsBit(\"isLittleEndianEncoding\");\n}\n\nCodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)\n : TheDef(R), AsmString(AsmStr) {\n Name = R->getValueAsString(\"Name\");\n Namespace = R->getValueAsString(\"Namespace\");\n\n isReturn = R->getValueAsBit(\"isReturn\");\n isBranch = R->getValueAsBit(\"isBranch\");\n isBarrier = R->getValueAsBit(\"isBarrier\");\n isCall = R->getValueAsBit(\"isCall\");\n isLoad = R->getValueAsBit(\"isLoad\");\n isStore = R->getValueAsBit(\"isStore\");\n isTwoAddress = R->getValueAsBit(\"isTwoAddress\");\n isConvertibleToThreeAddress = R->getValueAsBit(\"isConvertibleToThreeAddress\");\n isCommutable = R->getValueAsBit(\"isCommutable\");\n isTerminator = R->getValueAsBit(\"isTerminator\");\n hasDelaySlot = R->getValueAsBit(\"hasDelaySlot\");\n usesCustomDAGSchedInserter = R->getValueAsBit(\"usesCustomDAGSchedInserter\");\n hasCtrlDep = R->getValueAsBit(\"hasCtrlDep\");\n noResults = R->getValueAsBit(\"noResults\");\n hasVariableNumberOfOperands = false;\n \n DagInit *DI;\n try {\n DI = R->getValueAsDag(\"OperandList\");\n } catch (...) {\n \/\/ Error getting operand list, just ignore it (sparcv9).\n AsmString.clear();\n OperandList.clear();\n return;\n }\n\n unsigned MIOperandNo = 0;\n std::set<std::string> OperandNames;\n for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {\n DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));\n if (!Arg)\n throw \"Illegal operand for the '\" + R->getName() + \"' instruction!\";\n\n Record *Rec = Arg->getDef();\n std::string PrintMethod = \"printOperand\";\n unsigned NumOps = 1;\n DagInit *MIOpInfo = 0;\n if (Rec->isSubClassOf(\"Operand\")) {\n PrintMethod = Rec->getValueAsString(\"PrintMethod\");\n NumOps = Rec->getValueAsInt(\"NumMIOperands\");\n MIOpInfo = Rec->getValueAsDag(\"MIOperandInfo\");\n } else if (Rec->getName() == \"variable_ops\") {\n hasVariableNumberOfOperands = true;\n continue;\n } else if (!Rec->isSubClassOf(\"RegisterClass\"))\n throw \"Unknown operand class '\" + Rec->getName() +\n \"' in instruction '\" + R->getName() + \"' instruction!\";\n\n \/\/ Check that the operand has a name and that it's unique.\n if (DI->getArgName(i).empty())\n throw \"In instruction '\" + R->getName() + \"', operand #\" + utostr(i) +\n \" has no name!\";\n if (!OperandNames.insert(DI->getArgName(i)).second)\n throw \"In instruction '\" + R->getName() + \"', operand #\" + utostr(i) +\n \" has the same name as a previous operand!\";\n \n OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, \n MIOperandNo, NumOps, MIOpInfo));\n MIOperandNo += NumOps;\n }\n}\n\n\n\n\/\/\/ getOperandNamed - Return the index of the operand with the specified\n\/\/\/ non-empty name. If the instruction does not have an operand with the\n\/\/\/ specified name, throw an exception.\n\/\/\/\nunsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {\n assert(!Name.empty() && \"Cannot search for operand with no name!\");\n for (unsigned i = 0, e = OperandList.size(); i != e; ++i)\n if (OperandList[i].Name == Name) return i;\n throw \"Instruction '\" + TheDef->getName() +\n \"' does not have an operand named '$\" + Name + \"'!\";\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ComplexPattern implementation\n\/\/\nComplexPattern::ComplexPattern(Record *R) {\n Ty = ::getValueType(R->getValueAsDef(\"Ty\"));\n NumOperands = R->getValueAsInt(\"NumOperands\");\n SelectFunc = R->getValueAsString(\"SelectFunc\");\n RootNodes = R->getValueAsListOfDefs(\"RootNodes\");\n}\n\n<commit_msg>getEnumName() missed v8i8, v4i16, and v2i32 types<commit_after>\/\/===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class wrap target description classes used by the various code\n\/\/ generation TableGen backends. This makes it easier to access the data and\n\/\/ provides a single place that needs to check it for validity. All of these\n\/\/ classes throw exceptions on error conditions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include <set>\n#include <algorithm>\nusing namespace llvm;\n\nstatic cl::opt<unsigned>\nAsmWriterNum(\"asmwriternum\", cl::init(0),\n cl::desc(\"Make -gen-asm-writer emit assembly writer #N\"));\n\n\/\/\/ getValueType - Return the MCV::ValueType that the specified TableGen record\n\/\/\/ corresponds to.\nMVT::ValueType llvm::getValueType(Record *Rec) {\n return (MVT::ValueType)Rec->getValueAsInt(\"Value\");\n}\n\nstd::string llvm::getName(MVT::ValueType T) {\n switch (T) {\n case MVT::Other: return \"UNKNOWN\";\n case MVT::i1: return \"i1\";\n case MVT::i8: return \"i8\";\n case MVT::i16: return \"i16\";\n case MVT::i32: return \"i32\";\n case MVT::i64: return \"i64\";\n case MVT::i128: return \"i128\";\n case MVT::f32: return \"f32\";\n case MVT::f64: return \"f64\";\n case MVT::f80: return \"f80\";\n case MVT::f128: return \"f128\";\n case MVT::Flag: return \"Flag\";\n case MVT::isVoid:return \"void\";\n case MVT::v8i8: return \"v8i8\";\n case MVT::v4i16: return \"v4i16\";\n case MVT::v2i32: return \"v2i32\";\n case MVT::v16i8: return \"v16i8\";\n case MVT::v8i16: return \"v8i16\";\n case MVT::v4i32: return \"v4i32\";\n case MVT::v2i64: return \"v2i64\";\n case MVT::v2f32: return \"v2f32\";\n case MVT::v4f32: return \"v4f32\";\n case MVT::v2f64: return \"v2f64\";\n default: assert(0 && \"ILLEGAL VALUE TYPE!\"); return \"\";\n }\n}\n\nstd::string llvm::getEnumName(MVT::ValueType T) {\n switch (T) {\n case MVT::Other: return \"Other\";\n case MVT::i1: return \"i1\";\n case MVT::i8: return \"i8\";\n case MVT::i16: return \"i16\";\n case MVT::i32: return \"i32\";\n case MVT::i64: return \"i64\";\n case MVT::i128: return \"i128\";\n case MVT::f32: return \"f32\";\n case MVT::f64: return \"f64\";\n case MVT::f80: return \"f80\";\n case MVT::f128: return \"f128\";\n case MVT::Flag: return \"Flag\";\n case MVT::isVoid:return \"isVoid\";\n case MVT::v8i8: return \"v8i8\";\n case MVT::v4i16: return \"v4i16\";\n case MVT::v2i32: return \"v2i32\";\n case MVT::v16i8: return \"v16i8\";\n case MVT::v8i16: return \"v8i16\";\n case MVT::v4i32: return \"v4i32\";\n case MVT::v2i64: return \"v2i64\";\n case MVT::v2f32: return \"v2f32\";\n case MVT::v4f32: return \"v4f32\";\n case MVT::v2f64: return \"v2f64\";\n default: assert(0 && \"ILLEGAL VALUE TYPE!\"); return \"\";\n }\n}\n\n\nstd::ostream &llvm::operator<<(std::ostream &OS, MVT::ValueType T) {\n return OS << getName(T);\n}\n\n\n\/\/\/ getTarget - Return the current instance of the Target class.\n\/\/\/\nCodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {\n std::vector<Record*> Targets = Records.getAllDerivedDefinitions(\"Target\");\n if (Targets.size() == 0)\n throw std::string(\"ERROR: No 'Target' subclasses defined!\");\n if (Targets.size() != 1)\n throw std::string(\"ERROR: Multiple subclasses of Target defined!\");\n TargetRec = Targets[0];\n\n \/\/ Read in all of the CalleeSavedRegisters.\n CalleeSavedRegisters =TargetRec->getValueAsListOfDefs(\"CalleeSavedRegisters\");\n PointerType = getValueType(TargetRec->getValueAsDef(\"PointerType\"));\n}\n\n\nconst std::string &CodeGenTarget::getName() const {\n return TargetRec->getName();\n}\n\nRecord *CodeGenTarget::getInstructionSet() const {\n return TargetRec->getValueAsDef(\"InstructionSet\");\n}\n\n\/\/\/ getAsmWriter - Return the AssemblyWriter definition for this target.\n\/\/\/\nRecord *CodeGenTarget::getAsmWriter() const {\n std::vector<Record*> LI = TargetRec->getValueAsListOfDefs(\"AssemblyWriters\");\n if (AsmWriterNum >= LI.size())\n throw \"Target does not have an AsmWriter #\" + utostr(AsmWriterNum) + \"!\";\n return LI[AsmWriterNum];\n}\n\nvoid CodeGenTarget::ReadRegisters() const {\n std::vector<Record*> Regs = Records.getAllDerivedDefinitions(\"Register\");\n if (Regs.empty())\n throw std::string(\"No 'Register' subclasses defined!\");\n\n Registers.reserve(Regs.size());\n Registers.assign(Regs.begin(), Regs.end());\n}\n\nCodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {\n DeclaredSpillSize = R->getValueAsInt(\"SpillSize\");\n DeclaredSpillAlignment = R->getValueAsInt(\"SpillAlignment\");\n}\n\nconst std::string &CodeGenRegister::getName() const {\n return TheDef->getName();\n}\n\nvoid CodeGenTarget::ReadRegisterClasses() const {\n std::vector<Record*> RegClasses =\n Records.getAllDerivedDefinitions(\"RegisterClass\");\n if (RegClasses.empty())\n throw std::string(\"No 'RegisterClass' subclasses defined!\");\n\n RegisterClasses.reserve(RegClasses.size());\n RegisterClasses.assign(RegClasses.begin(), RegClasses.end());\n}\n\nCodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {\n \/\/ Rename anonymous register classes.\n if (R->getName().size() > 9 && R->getName()[9] == '.') {\n static unsigned AnonCounter = 0;\n R->setName(\"AnonRegClass_\"+utostr(AnonCounter++));\n } \n \n std::vector<Record*> TypeList = R->getValueAsListOfDefs(\"RegTypes\");\n for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {\n Record *Type = TypeList[i];\n if (!Type->isSubClassOf(\"ValueType\"))\n throw \"RegTypes list member '\" + Type->getName() +\n \"' does not derive from the ValueType class!\";\n VTs.push_back(getValueType(Type));\n }\n assert(!VTs.empty() && \"RegisterClass must contain at least one ValueType!\");\n \n std::vector<Record*> RegList = R->getValueAsListOfDefs(\"MemberList\");\n for (unsigned i = 0, e = RegList.size(); i != e; ++i) {\n Record *Reg = RegList[i];\n if (!Reg->isSubClassOf(\"Register\"))\n throw \"Register Class member '\" + Reg->getName() +\n \"' does not derive from the Register class!\";\n Elements.push_back(Reg);\n }\n \n \/\/ Allow targets to override the size in bits of the RegisterClass.\n unsigned Size = R->getValueAsInt(\"Size\");\n\n Namespace = R->getValueAsString(\"Namespace\");\n SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);\n SpillAlignment = R->getValueAsInt(\"Alignment\");\n MethodBodies = R->getValueAsCode(\"MethodBodies\");\n MethodProtos = R->getValueAsCode(\"MethodProtos\");\n}\n\nconst std::string &CodeGenRegisterClass::getName() const {\n return TheDef->getName();\n}\n\nvoid CodeGenTarget::ReadLegalValueTypes() const {\n const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();\n for (unsigned i = 0, e = RCs.size(); i != e; ++i)\n for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)\n LegalValueTypes.push_back(RCs[i].VTs[ri]);\n \n \/\/ Remove duplicates.\n std::sort(LegalValueTypes.begin(), LegalValueTypes.end());\n LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),\n LegalValueTypes.end()),\n LegalValueTypes.end());\n}\n\n\nvoid CodeGenTarget::ReadInstructions() const {\n std::vector<Record*> Insts = Records.getAllDerivedDefinitions(\"Instruction\");\n if (Insts.size() <= 2)\n throw std::string(\"No 'Instruction' subclasses defined!\");\n\n \/\/ Parse the instructions defined in the .td file.\n std::string InstFormatName =\n getAsmWriter()->getValueAsString(\"InstFormatName\");\n\n for (unsigned i = 0, e = Insts.size(); i != e; ++i) {\n std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);\n Instructions.insert(std::make_pair(Insts[i]->getName(),\n CodeGenInstruction(Insts[i], AsmStr)));\n }\n}\n\n\/\/\/ getInstructionsByEnumValue - Return all of the instructions defined by the\n\/\/\/ target, ordered by their enum value.\nvoid CodeGenTarget::\ngetInstructionsByEnumValue(std::vector<const CodeGenInstruction*>\n &NumberedInstructions) {\n std::map<std::string, CodeGenInstruction>::const_iterator I;\n I = getInstructions().find(\"PHI\");\n if (I == Instructions.end()) throw \"Could not find 'PHI' instruction!\";\n const CodeGenInstruction *PHI = &I->second;\n \n I = getInstructions().find(\"INLINEASM\");\n if (I == Instructions.end()) throw \"Could not find 'INLINEASM' instruction!\";\n const CodeGenInstruction *INLINEASM = &I->second;\n \n \/\/ Print out the rest of the instructions now.\n NumberedInstructions.push_back(PHI);\n NumberedInstructions.push_back(INLINEASM);\n for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)\n if (&II->second != PHI &&&II->second != INLINEASM)\n NumberedInstructions.push_back(&II->second);\n}\n\n\n\/\/\/ isLittleEndianEncoding - Return whether this target encodes its instruction\n\/\/\/ in little-endian format, i.e. bits laid out in the order [0..n]\n\/\/\/\nbool CodeGenTarget::isLittleEndianEncoding() const {\n return getInstructionSet()->getValueAsBit(\"isLittleEndianEncoding\");\n}\n\nCodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)\n : TheDef(R), AsmString(AsmStr) {\n Name = R->getValueAsString(\"Name\");\n Namespace = R->getValueAsString(\"Namespace\");\n\n isReturn = R->getValueAsBit(\"isReturn\");\n isBranch = R->getValueAsBit(\"isBranch\");\n isBarrier = R->getValueAsBit(\"isBarrier\");\n isCall = R->getValueAsBit(\"isCall\");\n isLoad = R->getValueAsBit(\"isLoad\");\n isStore = R->getValueAsBit(\"isStore\");\n isTwoAddress = R->getValueAsBit(\"isTwoAddress\");\n isConvertibleToThreeAddress = R->getValueAsBit(\"isConvertibleToThreeAddress\");\n isCommutable = R->getValueAsBit(\"isCommutable\");\n isTerminator = R->getValueAsBit(\"isTerminator\");\n hasDelaySlot = R->getValueAsBit(\"hasDelaySlot\");\n usesCustomDAGSchedInserter = R->getValueAsBit(\"usesCustomDAGSchedInserter\");\n hasCtrlDep = R->getValueAsBit(\"hasCtrlDep\");\n noResults = R->getValueAsBit(\"noResults\");\n hasVariableNumberOfOperands = false;\n \n DagInit *DI;\n try {\n DI = R->getValueAsDag(\"OperandList\");\n } catch (...) {\n \/\/ Error getting operand list, just ignore it (sparcv9).\n AsmString.clear();\n OperandList.clear();\n return;\n }\n\n unsigned MIOperandNo = 0;\n std::set<std::string> OperandNames;\n for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {\n DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));\n if (!Arg)\n throw \"Illegal operand for the '\" + R->getName() + \"' instruction!\";\n\n Record *Rec = Arg->getDef();\n std::string PrintMethod = \"printOperand\";\n unsigned NumOps = 1;\n DagInit *MIOpInfo = 0;\n if (Rec->isSubClassOf(\"Operand\")) {\n PrintMethod = Rec->getValueAsString(\"PrintMethod\");\n NumOps = Rec->getValueAsInt(\"NumMIOperands\");\n MIOpInfo = Rec->getValueAsDag(\"MIOperandInfo\");\n } else if (Rec->getName() == \"variable_ops\") {\n hasVariableNumberOfOperands = true;\n continue;\n } else if (!Rec->isSubClassOf(\"RegisterClass\"))\n throw \"Unknown operand class '\" + Rec->getName() +\n \"' in instruction '\" + R->getName() + \"' instruction!\";\n\n \/\/ Check that the operand has a name and that it's unique.\n if (DI->getArgName(i).empty())\n throw \"In instruction '\" + R->getName() + \"', operand #\" + utostr(i) +\n \" has no name!\";\n if (!OperandNames.insert(DI->getArgName(i)).second)\n throw \"In instruction '\" + R->getName() + \"', operand #\" + utostr(i) +\n \" has the same name as a previous operand!\";\n \n OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, \n MIOperandNo, NumOps, MIOpInfo));\n MIOperandNo += NumOps;\n }\n}\n\n\n\n\/\/\/ getOperandNamed - Return the index of the operand with the specified\n\/\/\/ non-empty name. If the instruction does not have an operand with the\n\/\/\/ specified name, throw an exception.\n\/\/\/\nunsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {\n assert(!Name.empty() && \"Cannot search for operand with no name!\");\n for (unsigned i = 0, e = OperandList.size(); i != e; ++i)\n if (OperandList[i].Name == Name) return i;\n throw \"Instruction '\" + TheDef->getName() +\n \"' does not have an operand named '$\" + Name + \"'!\";\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ComplexPattern implementation\n\/\/\nComplexPattern::ComplexPattern(Record *R) {\n Ty = ::getValueType(R->getValueAsDef(\"Ty\"));\n NumOperands = R->getValueAsInt(\"NumOperands\");\n SelectFunc = R->getValueAsString(\"SelectFunc\");\n RootNodes = R->getValueAsListOfDefs(\"RootNodes\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CdsdkSourceInfoImpl.hpp CDSDK - SourceInfo impl\n\/\/\n#pragma once\n\n\/\/ includes\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"CdsdkCommon.hpp\"\n#include \"CdsdkSourceDeviceImpl.hpp\"\n\nnamespace CDSDK\n{\n\n\/\/\/ source info impl for CDSDK\nclass SourceInfoImpl: public SourceInfo\n{\npublic:\n \/\/\/ ctor\n SourceInfoImpl(RefSp spRef)\n :m_spRef(spRef)\n {\n ZeroMemory(&m_sourceInfo, sizeof(m_sourceInfo));\n }\n\n \/\/\/ dtor\n virtual ~SourceInfoImpl() throw() {}\n\n virtual CString Name() const override\n {\n return m_sourceInfo.Name;\n }\n\n virtual std::shared_ptr<SourceDevice> Open() override\n {\n cdHSource hSource = 0;\n\n LOG_TRACE(_T(\"about to call CDOpenSource...\\n\"));\n\n \/\/ may return cdINVALID_PARAMETER, cdMEM_ALLOC_FAILED, cdDEVICE_NOT_FOUND, cdDEVICE_NOT_INSTALLED\n cdError err = CDOpenSource(&m_sourceInfo, &hSource);\n LOG_TRACE(_T(\"CDOpenSource(&si = \\\"%hs\\\") returned %08x\\n\"), m_sourceInfo.Name, err);\n CheckError(_T(\"CDOpenSource\"), err, __FILE__, __LINE__);\n\n return std::shared_ptr<SourceDevice>(new SourceDeviceImpl(m_spRef, hSource));\n }\n\n \/\/\/ returns source info\n cdSourceInfo& GetSourceInfo() throw() { return m_sourceInfo; }\n\nprivate:\n \/\/\/ source info\n cdSourceInfo m_sourceInfo;\n\n \/\/\/ SDK ref\n RefSp m_spRef;\n};\n\n} \/\/ namespace EDSDK\n<commit_msg>added more logging infos for CDOpenSource<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CdsdkSourceInfoImpl.hpp CDSDK - SourceInfo impl\n\/\/\n#pragma once\n\n\/\/ includes\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"CdsdkCommon.hpp\"\n#include \"CdsdkSourceDeviceImpl.hpp\"\n\nnamespace CDSDK\n{\n\n\/\/\/ source info impl for CDSDK\nclass SourceInfoImpl: public SourceInfo\n{\npublic:\n \/\/\/ ctor\n SourceInfoImpl(RefSp spRef)\n :m_spRef(spRef)\n {\n ZeroMemory(&m_sourceInfo, sizeof(m_sourceInfo));\n }\n\n \/\/\/ dtor\n virtual ~SourceInfoImpl() throw() {}\n\n virtual CString Name() const override\n {\n return m_sourceInfo.Name;\n }\n\n virtual std::shared_ptr<SourceDevice> Open() override\n {\n cdHSource hSource = 0;\n\n LOG_TRACE(_T(\"about to call CDOpenSource...\\n\"));\n\n \/\/ may return cdINVALID_PARAMETER, cdMEM_ALLOC_FAILED, cdDEVICE_NOT_FOUND, cdDEVICE_NOT_INSTALLED\n cdError err = CDOpenSource(&m_sourceInfo, &hSource);\n LOG_TRACE(_T(\"CDOpenSource(&si = \\\"%hs\\\", hSource=%08x) returned %08x\\n\"),\n m_sourceInfo.Name, hSource, err);\n CheckError(_T(\"CDOpenSource\"), err, __FILE__, __LINE__);\n\n return std::shared_ptr<SourceDevice>(new SourceDeviceImpl(m_spRef, hSource));\n }\n\n \/\/\/ returns source info\n cdSourceInfo& GetSourceInfo() throw() { return m_sourceInfo; }\n\nprivate:\n \/\/\/ source info\n cdSourceInfo m_sourceInfo;\n\n \/\/\/ SDK ref\n RefSp m_spRef;\n};\n\n} \/\/ namespace EDSDK\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <sstream>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n freopen (\"input.txt\",\"r\",stdin);\n freopen (\"output.txt\",\"w\",stdout);\n int n;\n cin >> n;\n getchar();\n while(n--) {\n vector<int> v;\n string line;\n getline(cin, line);\n stringstream ss(line);\n int tmp;\n while(ss >> tmp) {\n \/\/int tmp; ss >> tmp;\n v.push_back(tmp);\n }\n \/\/v.pop_back();\n sort(v.begin(),v.end());\n for(int i = 0; i < v.size(); ++i) cout << v[i] << ' ';\n cout << endl;\n }\n fclose (stdout);\n fclose (stdin);\n return 0;\n}\n<commit_msg>All C vi<commit_after>#include <cstdio>\n#include <cstring>\n#include <algorithm>\nusing namespace std;\n\nint main()\n{\n FILE * oFile, * iFile;\n iFile = fopen (\"input.txt\",\"r\");\n oFile = fopen (\"output.txt\",\"w\");\n int n;\n char enter;\n fscanf(iFile, \"%d\", &n);\n fscanf(iFile, \"%c\", &enter);\n while(n--) {\n int v[100010];\n char line[100000];\n int o = 0;\n for(o = 0;; ++o) {\n fscanf(iFile, \"%c\", line+o);\n if(line[o] == '\\n') break;\n }\n int tmp = 0;\n int ord = 0;\n for(int i = 0; i < o; ++i) {\n if(line[i] >= '0' && line[i] <= '9') {\n tmp *= 10;\n tmp += line[i] - '0';\n continue;\n } else {\n if(tmp) v[ord++] = tmp;\n tmp = 0;\n }\n }\n if(tmp) v[ord++] = tmp;\n sort(v,v+ord);\n for(int i = 0; i < ord; ++i) fprintf(oFile, \"%d \", v[i]);\n fprintf(oFile,\"\\n\");\n }\n fclose (iFile);\n fclose (oFile);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#define MAIN\n\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbForwardFourierMellinTransformImageFilter.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n\nint otbForwardFourierMellinTransformImageFilterNew(int argc, char* argv[])\n{\n\n typedef double PixelType;\n const unsigned int \t Dimension = 2;\n\n typedef otb::Image< PixelType, Dimension > InputImageType;\n typedef otb::Image< PixelType, Dimension > OutputImageType;\n \n typedef itk::LinearInterpolateImageFunction< InputImageType, double >\t\tInterpolatorType;\n typedef otb::ForwardFourierMellinTransformImageFilter<PixelType,\n \t\t\t\tInterpolatorType,Dimension> \t\t\tFourierMellinTransformType;\n try \n { \n FourierMellinTransformType::Pointer fourierMellinTransform = FourierMellinTransformType::New();\n } \n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"itk::Exception detected: \" << err.GetDescription();\n return EXIT_FAILURE;\n } \n catch( ... ) \n { \n std::cout << \"unknown exception detected !\" << std::endl; \n return EXIT_FAILURE;\n } \n \n return EXIT_SUCCESS;\n}\n<commit_msg>otbForwardFourierMellinTransformImageFilter : implémentation de la classe + tests<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef SILICIUM_THREAD_HPP\n#define SILICIUM_THREAD_HPP\n\n#include <silicium\/config.hpp>\n#include <functional>\n\nnamespace Si\n{\n\ttemplate <class SuccessElement, class ThreadingAPI>\n\tstruct thread_observable\n\t{\n\t\ttypedef typename ThreadingAPI::template future<SuccessElement>::type element_type;\n\n\t\tthread_observable()\n\t\t : m_has_finished(false)\n\t\t{\n\t\t}\n\n\t\texplicit thread_observable(std::function<SuccessElement ()> action)\n\t\t\t: m_action(std::move(action))\n\t\t\t, m_has_finished(false)\n\t\t{\n\t\t}\n\n\t\ttemplate <class Observer>\n\t\tvoid async_get_one(Observer &&observer)\n\t\t{\n\t\t\tif (m_has_finished)\n\t\t\t{\n\t\t\t\treturn std::forward<Observer>(observer).ended();\n\t\t\t}\n\t\t\tassert(m_action);\n\t\t\tauto action = std::move(m_action);\n\t\t\tm_worker = ThreadingAPI::launch_async([\n\t\t\t\tthis,\n\t\t\t\tobserver\n#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE\n\t\t\t\t\t= std::forward<Observer>(observer)\n#endif\n\t\t\t\t,\n\t\t\t\taction\n#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE\n\t\t\t\t\t= std::move(action)\n#endif\n\t\t\t\t]() mutable\n\t\t\t{\n\t\t\t\tm_has_finished = true;\n\t\t\t\ttypename ThreadingAPI::template packaged_task<SuccessElement>::type task(action);\n\t\t\t\tauto result = task.get_future();\n\t\t\t\ttask();\n\t\t\t\tauto observer_ = std::forward<Observer>(observer);\n\t\t\t\tstd::forward<Observer>(observer_).got_element(std::move(result));\n\t\t\t});\n\t\t}\n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n\t\tthread_observable(thread_observable &&) = default;\n\t\tthread_observable &operator = (thread_observable &&) = default;\n#else\n\t\tthread_observable(thread_observable &&other)\n\t\t\t: m_action(std::move(other.m_action))\n\t\t\t, m_worker(std::move(other.m_worker))\n\t\t\t, m_has_finished(std::move(other.m_has_finished))\n\t\t{\n\t\t}\n\n\t\tthread_observable &operator = (thread_observable &&other)\n\t\t{\n\t\t\tm_action = std::move(other.m_action);\n\t\t\tm_worker = std::move(other.m_worker);\n\t\t\tm_has_finished = std::move(other.m_has_finished);\n\t\t\treturn *this;\n\t\t}\n#endif\n\n\tprivate:\n\n\t\ttypedef typename ThreadingAPI::template future<void>::type worker_type;\n\n\t\tstd::function<SuccessElement ()> m_action;\n\t\tworker_type m_worker;\n\t\tbool m_has_finished;\n\n\t\tSILICIUM_DELETED_FUNCTION(thread_observable(thread_observable const &))\n\t\tSILICIUM_DELETED_FUNCTION(thread_observable &operator = (thread_observable const &))\n\t};\n\n\ttemplate <class ThreadingAPI, class Action>\n\tauto make_thread_observable(Action &&action)\n#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE\n\t\t-> thread_observable<decltype(action()), ThreadingAPI>\n#endif\n\t{\n\t\treturn thread_observable<decltype(action()), ThreadingAPI>(std::forward<Action>(action));\n\t}\n}\n\n#endif\n<commit_msg>thread_observable does not keep resources unnecessarily long alive (solves a deadlock on VC++)<commit_after>#ifndef SILICIUM_THREAD_HPP\n#define SILICIUM_THREAD_HPP\n\n#include <silicium\/config.hpp>\n#include <functional>\n\nnamespace Si\n{\n\ttemplate <class SuccessElement, class ThreadingAPI>\n\tstruct thread_observable\n\t{\n\t\ttypedef typename ThreadingAPI::template future<SuccessElement>::type element_type;\n\n\t\tthread_observable()\n\t\t : m_has_finished(false)\n\t\t{\n\t\t}\n\n\t\texplicit thread_observable(std::function<SuccessElement ()> action)\n\t\t\t: m_action(std::move(action))\n\t\t\t, m_has_finished(false)\n\t\t{\n\t\t}\n\n\t\ttemplate <class Observer>\n\t\tvoid async_get_one(Observer &&observer)\n\t\t{\n\t\t\tif (m_has_finished)\n\t\t\t{\n\t\t\t\treturn std::forward<Observer>(observer).ended();\n\t\t\t}\n\t\t\tassert(m_action);\n\t\t\tauto action = std::move(m_action);\n\t\t\toptional<typename std::decay<Observer>::type> maybe_observer{std::forward<Observer>(observer)};\n\t\t\tm_worker = ThreadingAPI::launch_async([\n\t\t\t\tthis,\n\t\t\t\t\tmaybe_observer\n#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE\n\t\t\t\t\t= std::forward<Observer>(maybe_observer)\n#endif\n\t\t\t\t,\n\t\t\t\taction\n#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE\n\t\t\t\t\t= std::move(action)\n#endif\n\t\t\t\t]() mutable\n\t\t\t{\n\t\t\t\tm_has_finished = true;\n\t\t\t\ttypename ThreadingAPI::template packaged_task<SuccessElement>::type task(action);\n\t\t\t\tauto result = task.get_future();\n\t\t\t\ttask();\n\t\t\t\tassert(maybe_observer);\n\t\t\t\tauto observer_ = std::forward<Observer>(*maybe_observer);\n\t\t\t\tstd::forward<Observer>(observer_).got_element(std::move(result));\n\t\t\t\t\/\/kill the observer with fire so that it cannot keep any shared state alive\n\t\t\t\tmaybe_observer = none;\n\t\t\t});\n\t\t}\n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n\t\tthread_observable(thread_observable &&) = default;\n\t\tthread_observable &operator = (thread_observable &&) = default;\n#else\n\t\tthread_observable(thread_observable &&other)\n\t\t\t: m_action(std::move(other.m_action))\n\t\t\t, m_worker(std::move(other.m_worker))\n\t\t\t, m_has_finished(std::move(other.m_has_finished))\n\t\t{\n\t\t}\n\n\t\tthread_observable &operator = (thread_observable &&other)\n\t\t{\n\t\t\tm_action = std::move(other.m_action);\n\t\t\tm_worker = std::move(other.m_worker);\n\t\t\tm_has_finished = std::move(other.m_has_finished);\n\t\t\treturn *this;\n\t\t}\n#endif\n\n\tprivate:\n\n\t\ttypedef typename ThreadingAPI::template future<void>::type worker_type;\n\n\t\tstd::function<SuccessElement ()> m_action;\n\t\tworker_type m_worker;\n\t\tbool m_has_finished;\n\n\t\tSILICIUM_DELETED_FUNCTION(thread_observable(thread_observable const &))\n\t\tSILICIUM_DELETED_FUNCTION(thread_observable &operator = (thread_observable const &))\n\t};\n\n\ttemplate <class ThreadingAPI, class Action>\n\tauto make_thread_observable(Action &&action)\n#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE\n\t\t-> thread_observable<decltype(action()), ThreadingAPI>\n#endif\n\t{\n\t\treturn thread_observable<decltype(action()), ThreadingAPI>(std::forward<Action>(action));\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/client.h\"\n#include \"google\/cloud\/storage\/testing\/storage_integration_test.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include \"google\/cloud\/internal\/random.h\"\n#include \"google\/cloud\/log.h\"\n#include \"google\/cloud\/testing_util\/status_matchers.h\"\n#include \"absl\/strings\/str_split.h\"\n#include <gmock\/gmock.h>\n#include <future>\n#include <thread>\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace {\nusing ObjectNameList = std::vector<std::string>;\n\n\/\/ This is basically a smoke test, if the test does not crash it was\n\/\/ successful. Its main value is when running with the *Sanitizers.\n\/\/ Synchronization and memory management problems are often revealed by this\n\/\/ type of test.\nclass ThreadIntegrationTest\n : public google::cloud::storage::testing::StorageIntegrationTest {\n public:\n static void CreateObjects(std::string const& bucket_name,\n ObjectNameList const& group,\n std::string const& contents) {\n \/\/ Create our own client so no state is shared with the other threads.\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n for (auto const& object_name : group) {\n (void)client->InsertObject(bucket_name, object_name, contents,\n IfGenerationMatch(0));\n }\n }\n\n static void DeleteObjects(std::string const& bucket_name,\n ObjectNameList const& group) {\n \/\/ Create our own client so no state is shared with the other threads.\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n for (auto const& object_name : group) {\n (void)client->DeleteObject(bucket_name, object_name);\n }\n }\n\n protected:\n void SetUp() override {\n project_id_ =\n google::cloud::internal::GetEnv(\"GOOGLE_CLOUD_PROJECT\").value_or(\"\");\n ASSERT_FALSE(project_id_.empty());\n region_id_ = google::cloud::internal::GetEnv(\n \"GOOGLE_CLOUD_CPP_STORAGE_TEST_REGION_ID\")\n .value_or(\"\");\n ASSERT_FALSE(region_id_.empty());\n }\n\n std::string project_id_;\n std::string region_id_;\n};\n\n\/**\n * Divides @p source in to @p count groups of approximately equal size.\n *\/\nstd::vector<ObjectNameList> DivideIntoEqualSizedGroups(\n ObjectNameList const& source, unsigned int count) {\n std::vector<ObjectNameList> groups(count);\n std::size_t index = 0;\n for (auto const& name : source) {\n auto group_id = index % count;\n groups[group_id].push_back(name);\n }\n return groups;\n}\n\n} \/\/ anonymous namespace\n\nTEST_F(ThreadIntegrationTest, Unshared) {\n std::string bucket_name = MakeRandomBucketName();\n auto bucket_client = MakeBucketIntegrationTestClient();\n ASSERT_STATUS_OK(bucket_client);\n\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n\n StatusOr<BucketMetadata> meta = bucket_client->CreateBucketForProject(\n bucket_name, project_id_,\n BucketMetadata()\n .set_storage_class(storage_class::Standard())\n .set_location(region_id_)\n .disable_versioning(),\n PredefinedAcl(\"private\"), PredefinedDefaultObjectAcl(\"projectPrivate\"),\n Projection(\"full\"));\n ASSERT_STATUS_OK(meta);\n EXPECT_EQ(bucket_name, meta->name());\n\n auto const thread_count = (std::max)(std::thread::hardware_concurrency(), 8U);\n auto const object_count = 100 * thread_count;\n std::vector<std::string> objects(object_count);\n std::generate(objects.begin(), objects.end(),\n [this] { return MakeRandomObjectName(); });\n\n auto const groups = DivideIntoEqualSizedGroups(objects, thread_count);\n std::vector<std::future<void>> tasks(groups.size());\n std::transform(groups.begin(), groups.end(), tasks.begin(),\n [&](ObjectNameList const& g) {\n return std::async(std::launch::async,\n &ThreadIntegrationTest::CreateObjects,\n bucket_name, g, LoremIpsum());\n });\n for (auto& t : tasks) t.get();\n \/\/ Verify at least 1\/2 of the objects were successfully created, note that\n \/\/ with the default policies an object may be successfully created, but\n \/\/ `InsertObject()` returns an error due to retries.\n std::size_t found = 0;\n for (auto& o : client->ListObjects(bucket_name)) {\n if (!o.ok()) break;\n ++found;\n }\n EXPECT_GE(found, object_count \/ 2);\n std::transform(groups.begin(), groups.end(), tasks.begin(),\n [&](ObjectNameList const& g) {\n return std::async(std::launch::async,\n &ThreadIntegrationTest::DeleteObjects,\n bucket_name, g);\n });\n for (auto& t : tasks) t.get();\n\n auto delete_status = bucket_client->DeleteBucket(bucket_name);\n ASSERT_STATUS_OK(delete_status);\n}\n\nclass CaptureSendHeaderBackend : public LogBackend {\n public:\n std::vector<std::string> log_lines;\n\n void Process(LogRecord const& lr) override {\n \/\/ Break the records in lines, because we will analyze the output per line.\n std::vector<std::string> lines = absl::StrSplit(lr.message, '\\n');\n log_lines.insert(log_lines.end(), lines.begin(), lines.end());\n }\n\n void ProcessWithOwnership(LogRecord lr) override { Process(lr); }\n};\n\nTEST_F(ThreadIntegrationTest, ReuseConnections) {\n auto log_backend = std::make_shared<CaptureSendHeaderBackend>();\n\n Client client(Options{}.set<TracingComponentsOption>({\"raw-client\", \"http\"}));\n\n std::string bucket_name = MakeRandomBucketName();\n\n auto id = LogSink::Instance().AddBackend(log_backend);\n StatusOr<BucketMetadata> meta = client.CreateBucketForProject(\n bucket_name, project_id_,\n BucketMetadata()\n .set_storage_class(storage_class::Standard())\n .set_location(region_id_)\n .disable_versioning(),\n PredefinedAcl(\"private\"), PredefinedDefaultObjectAcl(\"projectPrivate\"),\n Projection(\"full\"));\n ASSERT_STATUS_OK(meta);\n EXPECT_EQ(bucket_name, meta->name());\n\n constexpr int kObjectCount = 100;\n std::vector<std::string> objects;\n objects.reserve(kObjectCount);\n std::generate_n(std::back_inserter(objects), kObjectCount,\n [this] { return MakeRandomObjectName(); });\n\n std::vector<std::chrono::steady_clock::duration> create_elapsed;\n std::vector<std::chrono::steady_clock::duration> delete_elapsed;\n for (auto const& name : objects) {\n auto start = std::chrono::steady_clock::now();\n StatusOr<ObjectMetadata> insert = client.InsertObject(\n bucket_name, name, LoremIpsum(), IfGenerationMatch(0));\n ASSERT_STATUS_OK(insert);\n create_elapsed.emplace_back(std::chrono::steady_clock::now() - start);\n }\n for (auto const& name : objects) {\n auto start = std::chrono::steady_clock::now();\n (void)client.DeleteObject(bucket_name, name);\n delete_elapsed.emplace_back(std::chrono::steady_clock::now() - start);\n }\n LogSink::Instance().RemoveBackend(id);\n auto delete_status = client.DeleteBucket(bucket_name);\n ASSERT_STATUS_OK(delete_status);\n\n std::set<std::string> connected;\n std::copy_if(\n log_backend->log_lines.begin(), log_backend->log_lines.end(),\n std::inserter(connected, connected.end()), [](std::string const& line) {\n \/\/ libcurl prints established connections using this format:\n \/\/ Connected to <hostname> (<ipaddress>) port <num> (#<connection>)\n \/\/ We capturing the different lines in that form tells us how many\n \/\/ different connections were used.\n return line.find(\"== curl(Info): Connected to \") != std::string::npos;\n });\n \/\/ We expect that at most 5% of the requests required a new connection,\n \/\/ ideally it should be 1 connection, but anything small is acceptable. Recall\n \/\/ that we make two requests per connection, so:\n std::size_t max_expected_connections = kObjectCount * 2 * 5 \/ 100;\n EXPECT_GE(max_expected_connections, connected.size()) << [&log_backend] {\n return std::accumulate(log_backend->log_lines.begin(),\n log_backend->log_lines.end(), std::string{},\n [](std::string const& x, std::string const& y) {\n return x + \"\\n\" + y;\n });\n }();\n \/\/ Zero connections indicates a bug in the test, the client should have\n \/\/ connected at least once.\n EXPECT_LT(0U, connected.size());\n}\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace storage\n} \/\/ namespace cloud\n} \/\/ namespace google\n<commit_msg>test(storage): speed up thread_integration_test (#7576)<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/client.h\"\n#include \"google\/cloud\/storage\/testing\/storage_integration_test.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include \"google\/cloud\/internal\/random.h\"\n#include \"google\/cloud\/log.h\"\n#include \"google\/cloud\/testing_util\/status_matchers.h\"\n#include \"absl\/strings\/str_split.h\"\n#include <gmock\/gmock.h>\n#include <algorithm>\n#include <future>\n#include <thread>\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace {\nusing ObjectNameList = std::vector<std::string>;\n\n\/\/ This is basically a smoke test, if the test does not crash it was\n\/\/ successful. Its main value is when running with the *Sanitizers.\n\/\/ Synchronization and memory management problems are often revealed by this\n\/\/ type of test.\nclass ThreadIntegrationTest\n : public google::cloud::storage::testing::StorageIntegrationTest {\n public:\n static void CreateObjects(std::string const& bucket_name,\n ObjectNameList const& group,\n std::string const& contents) {\n \/\/ Create our own client so no state is shared with the other threads.\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n for (auto const& object_name : group) {\n (void)client->InsertObject(bucket_name, object_name, contents,\n IfGenerationMatch(0));\n }\n }\n\n static void DeleteObjects(std::string const& bucket_name,\n ObjectNameList const& group) {\n \/\/ Create our own client so no state is shared with the other threads.\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n for (auto const& object_name : group) {\n (void)client->DeleteObject(bucket_name, object_name);\n }\n }\n\n protected:\n void SetUp() override {\n project_id_ =\n google::cloud::internal::GetEnv(\"GOOGLE_CLOUD_PROJECT\").value_or(\"\");\n ASSERT_FALSE(project_id_.empty());\n region_id_ = google::cloud::internal::GetEnv(\n \"GOOGLE_CLOUD_CPP_STORAGE_TEST_REGION_ID\")\n .value_or(\"\");\n ASSERT_FALSE(region_id_.empty());\n }\n\n std::string project_id_;\n std::string region_id_;\n};\n\n\/**\n * Divides @p source in to @p count groups of approximately equal size.\n *\/\nstd::vector<ObjectNameList> DivideIntoEqualSizedGroups(\n ObjectNameList const& source, unsigned int count) {\n std::vector<ObjectNameList> groups(count);\n std::size_t index = 0;\n for (auto const& name : source) {\n auto group_id = index % count;\n groups[group_id].push_back(name);\n }\n return groups;\n}\n\n} \/\/ anonymous namespace\n\nTEST_F(ThreadIntegrationTest, Unshared) {\n std::string bucket_name = MakeRandomBucketName();\n auto bucket_client = MakeBucketIntegrationTestClient();\n ASSERT_STATUS_OK(bucket_client);\n\n StatusOr<Client> client = MakeIntegrationTestClient();\n ASSERT_STATUS_OK(client);\n\n StatusOr<BucketMetadata> meta = bucket_client->CreateBucketForProject(\n bucket_name, project_id_,\n BucketMetadata()\n .set_storage_class(storage_class::Standard())\n .set_location(region_id_)\n .disable_versioning(),\n PredefinedAcl(\"private\"), PredefinedDefaultObjectAcl(\"projectPrivate\"),\n Projection(\"full\"));\n ASSERT_STATUS_OK(meta);\n EXPECT_EQ(bucket_name, meta->name());\n\n \/\/ Clamp the thread count to the [8, 32] range. Sadly, `std::clamp` is a C++17\n \/\/ feature.\n auto const thread_count =\n (std::min)(32U, (std::max)(8U, std::thread::hardware_concurrency()));\n auto const object_count = 100 * thread_count;\n std::vector<std::string> objects(object_count);\n std::generate(objects.begin(), objects.end(),\n [this] { return MakeRandomObjectName(); });\n\n auto const groups = DivideIntoEqualSizedGroups(objects, thread_count);\n std::vector<std::future<void>> tasks(groups.size());\n std::transform(groups.begin(), groups.end(), tasks.begin(),\n [&](ObjectNameList const& g) {\n return std::async(std::launch::async,\n &ThreadIntegrationTest::CreateObjects,\n bucket_name, g, LoremIpsum());\n });\n for (auto& t : tasks) t.get();\n \/\/ Verify at least 1\/2 of the objects were successfully created, note that\n \/\/ with the default policies an object may be successfully created, but\n \/\/ `InsertObject()` returns an error due to retries.\n std::size_t found = 0;\n for (auto& o : client->ListObjects(bucket_name)) {\n if (!o.ok()) break;\n ++found;\n }\n EXPECT_GE(found, object_count \/ 2);\n std::transform(groups.begin(), groups.end(), tasks.begin(),\n [&](ObjectNameList const& g) {\n return std::async(std::launch::async,\n &ThreadIntegrationTest::DeleteObjects,\n bucket_name, g);\n });\n for (auto& t : tasks) t.get();\n\n auto delete_status = bucket_client->DeleteBucket(bucket_name);\n ASSERT_STATUS_OK(delete_status);\n}\n\nclass CaptureSendHeaderBackend : public LogBackend {\n public:\n std::vector<std::string> log_lines;\n\n void Process(LogRecord const& lr) override {\n \/\/ Break the records in lines, because we will analyze the output per line.\n std::vector<std::string> lines = absl::StrSplit(lr.message, '\\n');\n log_lines.insert(log_lines.end(), lines.begin(), lines.end());\n }\n\n void ProcessWithOwnership(LogRecord lr) override { Process(lr); }\n};\n\nTEST_F(ThreadIntegrationTest, ReuseConnections) {\n auto log_backend = std::make_shared<CaptureSendHeaderBackend>();\n\n Client client(Options{}.set<TracingComponentsOption>({\"raw-client\", \"http\"}));\n\n std::string bucket_name = MakeRandomBucketName();\n\n auto id = LogSink::Instance().AddBackend(log_backend);\n StatusOr<BucketMetadata> meta = client.CreateBucketForProject(\n bucket_name, project_id_,\n BucketMetadata()\n .set_storage_class(storage_class::Standard())\n .set_location(region_id_)\n .disable_versioning(),\n PredefinedAcl(\"private\"), PredefinedDefaultObjectAcl(\"projectPrivate\"),\n Projection(\"full\"));\n ASSERT_STATUS_OK(meta);\n EXPECT_EQ(bucket_name, meta->name());\n\n constexpr int kObjectCount = 100;\n std::vector<std::string> objects;\n objects.reserve(kObjectCount);\n std::generate_n(std::back_inserter(objects), kObjectCount,\n [this] { return MakeRandomObjectName(); });\n\n std::vector<std::chrono::steady_clock::duration> create_elapsed;\n std::vector<std::chrono::steady_clock::duration> delete_elapsed;\n for (auto const& name : objects) {\n auto start = std::chrono::steady_clock::now();\n StatusOr<ObjectMetadata> insert = client.InsertObject(\n bucket_name, name, LoremIpsum(), IfGenerationMatch(0));\n ASSERT_STATUS_OK(insert);\n create_elapsed.emplace_back(std::chrono::steady_clock::now() - start);\n }\n for (auto const& name : objects) {\n auto start = std::chrono::steady_clock::now();\n (void)client.DeleteObject(bucket_name, name);\n delete_elapsed.emplace_back(std::chrono::steady_clock::now() - start);\n }\n LogSink::Instance().RemoveBackend(id);\n auto delete_status = client.DeleteBucket(bucket_name);\n ASSERT_STATUS_OK(delete_status);\n\n std::set<std::string> connected;\n std::copy_if(\n log_backend->log_lines.begin(), log_backend->log_lines.end(),\n std::inserter(connected, connected.end()), [](std::string const& line) {\n \/\/ libcurl prints established connections using this format:\n \/\/ Connected to <hostname> (<ipaddress>) port <num> (#<connection>)\n \/\/ We capturing the different lines in that form tells us how many\n \/\/ different connections were used.\n return line.find(\"== curl(Info): Connected to \") != std::string::npos;\n });\n \/\/ We expect that at most 5% of the requests required a new connection,\n \/\/ ideally it should be 1 connection, but anything small is acceptable. Recall\n \/\/ that we make two requests per connection, so:\n std::size_t max_expected_connections = kObjectCount * 2 * 5 \/ 100;\n EXPECT_GE(max_expected_connections, connected.size()) << [&log_backend] {\n return std::accumulate(log_backend->log_lines.begin(),\n log_backend->log_lines.end(), std::string{},\n [](std::string const& x, std::string const& y) {\n return x + \"\\n\" + y;\n });\n }();\n \/\/ Zero connections indicates a bug in the test, the client should have\n \/\/ connected at least once.\n EXPECT_LT(0U, connected.size());\n}\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace storage\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 William Jagels\n#pragma once\n\n#include <memory>\n#include <stdexcept>\n#include <type_traits>\n#include <variant>\n\nnamespace wijagels {\nstruct BadFunctionCall : std::runtime_error {\n using std::runtime_error::runtime_error;\n};\n\nnamespace detail {\ntemplate <typename ResultType, typename... ArgumentTypes>\nstruct function_storage {\n function_storage() = default;\n function_storage(const function_storage &) = default;\n function_storage(function_storage &&) noexcept = default;\n virtual ~function_storage() = default;\n function_storage &operator=(const function_storage &) = default;\n function_storage &operator=(function_storage &&) noexcept = default;\n\n virtual std::unique_ptr<function_storage> clone() const = 0;\n virtual void clone_into(function_storage *) const = 0;\n virtual void move_into(function_storage *) noexcept = 0;\n virtual ResultType invoke(ArgumentTypes &&... args) = 0;\n};\n\ntemplate <typename FunctionType, typename ResultType, typename... ArgumentTypes>\nstruct function_storage_impl : function_storage<ResultType, ArgumentTypes...> {\n function_storage_impl(FunctionType fn) : m_fn{fn} {}\n\n std::unique_ptr<function_storage<ResultType, ArgumentTypes...>> clone()\n const override {\n return std::make_unique<function_storage_impl>(m_fn);\n }\n\n void clone_into(\n function_storage<ResultType, ArgumentTypes...> *ptr) const override {\n new (ptr) function_storage_impl(*this);\n }\n\n void move_into(\n function_storage<ResultType, ArgumentTypes...> *ptr) noexcept override {\n new (ptr) function_storage_impl(std::move(*this));\n }\n\n ResultType invoke(ArgumentTypes &&... args) override {\n return m_fn(std::forward<ArgumentTypes>(args)...);\n }\n\n FunctionType m_fn;\n};\n} \/\/ namespace detail\n\ntemplate <typename>\nclass Function;\n\ntemplate <typename ResultType, typename... ArgumentTypes>\nclass Function<ResultType(ArgumentTypes...)> {\n static constexpr std::size_t MAX_SIZE = 24;\n static constexpr std::size_t ALIGNMENT = 8;\n\n using ptr_t = typename std::unique_ptr<\n detail::function_storage<ResultType, ArgumentTypes...>>;\n using inline_storage = std::aligned_storage_t<MAX_SIZE, ALIGNMENT>;\n using base_fn_storage =\n detail::function_storage<ResultType, ArgumentTypes...>;\n\n std::variant<std::monostate, inline_storage, ptr_t> m_storage;\n\n public:\n constexpr Function() = default;\n ~Function() {\n if (auto *ptr = std::get_if<inline_storage>(&m_storage))\n std::destroy_at(reinterpret_cast<base_fn_storage *>(ptr));\n }\n\n template <typename FunctionType,\n typename = std::enable_if_t<std::is_invocable_r_v<\n ResultType, FunctionType, ArgumentTypes...>>>\n Function(FunctionType f) {\n if constexpr (sizeof(detail::function_storage_impl<FunctionType, ResultType,\n ArgumentTypes...>) <=\n MAX_SIZE &&\n alignof(\n detail::function_storage_impl<FunctionType, ResultType,\n ArgumentTypes...>) <=\n ALIGNMENT) {\n m_storage.template emplace<inline_storage>();\n auto *ptr = std::get_if<inline_storage>(&m_storage);\n new (ptr) detail::function_storage_impl<FunctionType, ResultType,\n ArgumentTypes...>{std::move(f)};\n } else {\n m_storage.template emplace<ptr_t>(\n std::make_unique<detail::function_storage_impl<\n FunctionType, ResultType, ArgumentTypes...>>(std::move(f)));\n }\n }\n\n Function(const Function &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = (*ptr)->clone();\n else if (auto inline_ptr = std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<const base_fn_storage *>(inline_ptr)\n ->clone_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n\n Function(Function &&other) noexcept {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = std::move(*ptr);\n else if (auto inline_ptr = std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->move_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n\n Function &operator=(const Function &other) {\n if (this != &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = (*ptr)->clone();\n else if (auto inline_ptr =\n std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<const base_fn_storage *>(inline_ptr)\n ->clone_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n return *this;\n }\n\n Function &operator=(Function &&other) noexcept {\n if (this != &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = std::move(*ptr);\n else if (auto inline_ptr =\n std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->move_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n return *this;\n }\n\n ResultType operator()(ArgumentTypes &&... args) {\n if (auto ptr = std::get_if<ptr_t>(&m_storage))\n return (*ptr)->invoke(std::forward<ArgumentTypes>(args)...);\n else if (auto inline_ptr = std::get_if<inline_storage>(&m_storage))\n return reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->invoke(std::forward<ArgumentTypes>(args)...);\n else\n throw BadFunctionCall{\"No function stored\"};\n }\n\n constexpr explicit operator bool() const { return m_storage.index() != 0; }\n\n constexpr friend bool operator==(\n const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {\n return !bool{f};\n }\n constexpr friend bool operator==(\n std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {\n return !bool{f};\n }\n constexpr friend bool operator!=(\n const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {\n return bool{f};\n }\n constexpr friend bool operator!=(\n std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {\n return bool{f};\n }\n};\n\n} \/\/ namespace wijagels\n<commit_msg>Cleanup function<commit_after>\/\/ Copyright 2018 William Jagels\n#pragma once\n\n#include <memory>\n#include <stdexcept>\n#include <type_traits>\n#include <variant>\n\nnamespace wijagels {\nstruct BadFunctionCall : std::runtime_error {\n using std::runtime_error::runtime_error;\n};\n\nnamespace detail {\ntemplate <typename ResultType, typename... ArgumentTypes>\nstruct function_storage {\n function_storage() = default;\n function_storage(const function_storage &) = default;\n function_storage(function_storage &&) noexcept = default;\n virtual ~function_storage() = default;\n function_storage &operator=(const function_storage &) = default;\n function_storage &operator=(function_storage &&) noexcept = default;\n\n virtual std::unique_ptr<function_storage> clone() const = 0;\n virtual void clone_into(function_storage *) const = 0;\n virtual void move_into(function_storage *) noexcept = 0;\n virtual ResultType invoke(ArgumentTypes &&... args) = 0;\n};\n\ntemplate <typename FunctionType, typename ResultType, typename... ArgumentTypes>\nstruct function_storage_impl final\n : function_storage<ResultType, ArgumentTypes...> {\n function_storage_impl(FunctionType fn) : m_fn{fn} {}\n\n std::unique_ptr<function_storage<ResultType, ArgumentTypes...>> clone()\n const override {\n return std::make_unique<function_storage_impl>(m_fn);\n }\n\n void clone_into(\n function_storage<ResultType, ArgumentTypes...> *ptr) const override {\n new (ptr) function_storage_impl(*this);\n }\n\n void move_into(\n function_storage<ResultType, ArgumentTypes...> *ptr) noexcept override {\n new (ptr) function_storage_impl(std::move(*this));\n }\n\n ResultType invoke(ArgumentTypes &&... args) override {\n return m_fn(std::forward<ArgumentTypes>(args)...);\n }\n\n FunctionType m_fn;\n};\n} \/\/ namespace detail\n\ntemplate <typename>\nclass Function;\n\ntemplate <typename ResultType, typename... ArgumentTypes>\nclass Function<ResultType(ArgumentTypes...)> {\n static constexpr std::size_t MAX_SIZE = 24;\n static constexpr std::size_t ALIGNMENT = 8;\n\n using ptr_t = typename std::unique_ptr<\n detail::function_storage<ResultType, ArgumentTypes...>>;\n using inline_storage = std::aligned_storage_t<MAX_SIZE, ALIGNMENT>;\n using base_fn_storage =\n detail::function_storage<ResultType, ArgumentTypes...>;\n\n std::variant<std::monostate, inline_storage, ptr_t> m_storage;\n\n public:\n constexpr Function() = default;\n ~Function() {\n if (auto *ptr = std::get_if<inline_storage>(&m_storage))\n std::destroy_at(reinterpret_cast<base_fn_storage *>(ptr));\n }\n\n template <typename FunctionType,\n typename = std::enable_if_t<std::is_invocable_r_v<\n ResultType, FunctionType, ArgumentTypes...>>>\n Function(FunctionType f) {\n using fn_storage_t = detail::function_storage_impl<FunctionType, ResultType,\n ArgumentTypes...>;\n if constexpr (sizeof(fn_storage_t) <= MAX_SIZE &&\n alignof(fn_storage_t) <= ALIGNMENT) {\n m_storage.template emplace<inline_storage>();\n auto *ptr = std::get_if<inline_storage>(&m_storage);\n new (ptr) fn_storage_t{std::move(f)};\n } else {\n m_storage.template emplace<ptr_t>(\n std::make_unique<fn_storage_t>(std::move(f)));\n }\n }\n\n Function(const Function &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = (*ptr)->clone();\n else if (auto inline_ptr = std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<const base_fn_storage *>(inline_ptr)\n ->clone_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n\n Function(Function &&other) noexcept {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = std::move(*ptr);\n else if (auto inline_ptr = std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->move_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n\n Function &operator=(const Function &other) {\n if (this != &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = (*ptr)->clone();\n else if (auto inline_ptr =\n std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<const base_fn_storage *>(inline_ptr)\n ->clone_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n return *this;\n }\n\n Function &operator=(Function &&other) noexcept {\n if (this != &other) {\n if (auto ptr = std::get_if<ptr_t>(&other.m_storage))\n m_storage = std::move(*ptr);\n else if (auto inline_ptr =\n std::get_if<inline_storage>(&other.m_storage)) {\n m_storage.template emplace<inline_storage>();\n reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->move_into(reinterpret_cast<base_fn_storage *>(\n std::get_if<inline_storage>(&m_storage)));\n }\n }\n return *this;\n }\n\n ResultType operator()(ArgumentTypes &&... args) {\n if (auto ptr = std::get_if<ptr_t>(&m_storage))\n return (*ptr)->invoke(std::forward<ArgumentTypes>(args)...);\n else if (auto inline_ptr = std::get_if<inline_storage>(&m_storage))\n return reinterpret_cast<base_fn_storage *>(inline_ptr)\n ->invoke(std::forward<ArgumentTypes>(args)...);\n else\n throw BadFunctionCall{\"No function stored\"};\n }\n\n constexpr explicit operator bool() const { return m_storage.index() != 0; }\n\n constexpr friend bool operator==(\n const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {\n return !bool{f};\n }\n constexpr friend bool operator==(\n std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {\n return !bool{f};\n }\n constexpr friend bool operator!=(\n const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {\n return bool{f};\n }\n constexpr friend bool operator!=(\n std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {\n return bool{f};\n }\n};\n\n} \/\/ namespace wijagels\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <fstream>\n#include <vector>\n#include <set>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <exception>\n#ifdef HAVE_HDF5\n#include <H5Cpp.h>\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n#include <dada_hdu.h>\n#include <ascii_header.h>\n#endif \/\/ HAVE_PSRDADA\n\n#include <utils.hpp>\n#include \"Observation.hpp\"\n#include \"Platform.hpp\"\n\n\n#pragma once\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDADA ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n explicit RingBufferError(std::string message);\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\nprivate:\n std::string message;\n};\n\n\/\/ Zapped channels (excluded from computation)\nvoid readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector<unsigned int> & zappedChannels);\n\/\/ Integration steps\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps);\n\/\/ SIGPROC data\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch = 0);\n#ifdef HAVE_HDF5\n\/\/ LOFAR data\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches = 0, unsigned int firstBatch = 0);\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n\/\/ PSRDADA buffer\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n#endif \/\/ HAVE_PSRDADA\n\n\/\/ Implementations\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch) {\n std::ifstream inputFile;\n const unsigned int BUFFER_DIM = sizeof(T);\n char * buffer = new char [BUFFER_DIM];\n\n inputFile.open(inputFilename.c_str(), std::ios::binary);\n if ( ! inputFile ) {\n delete [] buffer;\n throw FileError(\"Impossible to open \" + inputFilename);\n }\n inputFile.sync_with_stdio(false);\n inputFile.seekg(bytesToSkip, std::ios::beg);\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n if ( inputBits >= 8 ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(batch)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n uint64_t bytesToRead = static_cast< uint64_t >(observation.getNrSamplesPerBatch() * (observation.getNrChannels() \/ (8.0 \/ inputBits)));\n\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T)));\n for ( uint64_t byte = 0; byte < bytesToRead; byte++ ) {\n unsigned int channel = (observation.getNrChannels() - 1) - ((byte * (8 \/ inputBits)) % observation.getNrChannels());\n unsigned int sample = (byte * (8 \/ inputBits)) \/ observation.getNrChannels();\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < 8 \/ inputBits; item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( item > channel ) {\n \/\/ All channels read, the remaining elements are from the next sample\n unsigned int channelOffset = 0;\n channel = (observation.getNrChannels() - 1);\n sample += 1;\n sampleByte = sample \/ (8 \/ inputBits);\n sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n while ( item < (8 \/ inputBits) ) {\n channelFirstBit = item * inputBits;\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n item++;\n channelOffset++;\n }\n\n break;\n }\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n }\n }\n }\n }\n inputFile.close();\n\n delete [] buffer;\n}\n\n#ifdef HAVE_HDF5\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches, unsigned int firstBatch) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n \/\/ Read the HDF5 file with the metadata\n H5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n H5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n double valueDouble = 0.0;\n H5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n unsigned int valueUInt = 0;\n\n H5::Group currentNode = headerFile.openGroup(\"\/\");\n currentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n double totalIntegrationTime = valueDouble;\n currentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrBeams(valueUInt);\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n unsigned int totalSamples = valueUInt;\n currentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrStations(valueUInt);\n currentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrChannels = valueUInt;\n currentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n H5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n currentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrSubbands = valueUInt;\n headerFile.close();\n\n observation.setNrSamplesPerBatch(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n if ( nrBatches == 0 ) {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime));\n } else {\n if ( static_cast< unsigned int >(totalIntegrationTime) >= (firstBatch + nrBatches) ) {\n observation.setNrBatches(nrBatches);\n } else {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime) - firstBatch);\n }\n }\n observation.setFrequencyRange(1, nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n \/\/ Read the raw file with the actual data\n std::ifstream rawFile;\n rawFile.open(rawFilename.c_str(), std::ios::binary);\n if ( !rawFile ) {\n throw FileError(\"Impossible to open \" + rawFilename);\n }\n rawFile.sync_with_stdio(false);\n if ( firstBatch > 0 ) {\n rawFile.seekg(firstBatch * observation.getNrSamplesPerBatch() * nrSubbands * nrChannels, std::ios::beg);\n }\n data.resize(observation.getNrBatches());\n\n char * word = new char [4];\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n for ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n rawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(batch)->at((globalChannel * observation.getNrSamplesPerBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(word));\n }\n }\n }\n }\n rawFile.close();\n delete [] word;\n}\n#endif \/\/ HAVE_HDF5\n\n#ifdef HAVE_PSRDADA\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n char * buffer = 0;\n uint64_t bufferBytes = 0;\n\n buffer = ipcbuf_get_next_read(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block), &bufferBytes);\n if ( (buffer == 0) || (bufferBytes == 0) ) {\n throw RingBufferError(\"Impossible to read the PSRDADA buffer.\");\n }\n std::memcpy(reinterpret_cast< void * >(data->data()), reinterpret_cast< const void * >(buffer), data->size() * sizeof(T));\n if ( ipcbuf_mark_cleared(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block)) < 0 ) {\n throw RingBufferError(\"Impossible to mark the PSRDADA buffer as cleared.\");\n }\n}\n#endif \/\/ HAVE_PSRDADA\n\n} \/\/ AstroData\n\n<commit_msg>Wrong use of Observation interface.<commit_after>\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <fstream>\n#include <vector>\n#include <set>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <exception>\n#ifdef HAVE_HDF5\n#include <H5Cpp.h>\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n#include <dada_hdu.h>\n#include <ascii_header.h>\n#endif \/\/ HAVE_PSRDADA\n\n#include <utils.hpp>\n#include \"Observation.hpp\"\n#include \"Platform.hpp\"\n\n\n#pragma once\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDADA ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n explicit RingBufferError(std::string message);\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\nprivate:\n std::string message;\n};\n\n\/\/ Zapped channels (excluded from computation)\nvoid readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector<unsigned int> & zappedChannels);\n\/\/ Integration steps\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps);\n\/\/ SIGPROC data\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch = 0);\n#ifdef HAVE_HDF5\n\/\/ LOFAR data\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches = 0, unsigned int firstBatch = 0);\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n\/\/ PSRDADA buffer\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n#endif \/\/ HAVE_PSRDADA\n\n\/\/ Implementations\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch) {\n std::ifstream inputFile;\n const unsigned int BUFFER_DIM = sizeof(T);\n char * buffer = new char [BUFFER_DIM];\n\n inputFile.open(inputFilename.c_str(), std::ios::binary);\n if ( ! inputFile ) {\n delete [] buffer;\n throw FileError(\"Impossible to open \" + inputFilename);\n }\n inputFile.sync_with_stdio(false);\n inputFile.seekg(bytesToSkip, std::ios::beg);\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n if ( inputBits >= 8 ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerBatch(false, padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(batch)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerBatch(false, padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n uint64_t bytesToRead = static_cast< uint64_t >(observation.getNrSamplesPerBatch() * (observation.getNrChannels() \/ (8.0 \/ inputBits)));\n\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T)));\n for ( uint64_t byte = 0; byte < bytesToRead; byte++ ) {\n unsigned int channel = (observation.getNrChannels() - 1) - ((byte * (8 \/ inputBits)) % observation.getNrChannels());\n unsigned int sample = (byte * (8 \/ inputBits)) \/ observation.getNrChannels();\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < 8 \/ inputBits; item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( item > channel ) {\n \/\/ All channels read, the remaining elements are from the next sample\n unsigned int channelOffset = 0;\n channel = (observation.getNrChannels() - 1);\n sample += 1;\n sampleByte = sample \/ (8 \/ inputBits);\n sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n while ( item < (8 \/ inputBits) ) {\n channelFirstBit = item * inputBits;\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n item++;\n channelOffset++;\n }\n\n break;\n }\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n }\n }\n }\n }\n inputFile.close();\n\n delete [] buffer;\n}\n\n#ifdef HAVE_HDF5\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches, unsigned int firstBatch) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n \/\/ Read the HDF5 file with the metadata\n H5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n H5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n double valueDouble = 0.0;\n H5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n unsigned int valueUInt = 0;\n\n H5::Group currentNode = headerFile.openGroup(\"\/\");\n currentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n double totalIntegrationTime = valueDouble;\n currentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrBeams(valueUInt);\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n unsigned int totalSamples = valueUInt;\n currentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrStations(valueUInt);\n currentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrChannels = valueUInt;\n currentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n H5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n currentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrSubbands = valueUInt;\n headerFile.close();\n\n observation.setNrSamplesPerBatch(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n if ( nrBatches == 0 ) {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime));\n } else {\n if ( static_cast< unsigned int >(totalIntegrationTime) >= (firstBatch + nrBatches) ) {\n observation.setNrBatches(nrBatches);\n } else {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime) - firstBatch);\n }\n }\n observation.setFrequencyRange(1, nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n \/\/ Read the raw file with the actual data\n std::ifstream rawFile;\n rawFile.open(rawFilename.c_str(), std::ios::binary);\n if ( !rawFile ) {\n throw FileError(\"Impossible to open \" + rawFilename);\n }\n rawFile.sync_with_stdio(false);\n if ( firstBatch > 0 ) {\n rawFile.seekg(firstBatch * observation.getNrSamplesPerBatch() * nrSubbands * nrChannels, std::ios::beg);\n }\n data.resize(observation.getNrBatches());\n\n char * word = new char [4];\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerBatch(false, padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n for ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n rawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(batch)->at((globalChannel * observation.getNrSamplesPerBatch(false, padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(word));\n }\n }\n }\n }\n rawFile.close();\n delete [] word;\n}\n#endif \/\/ HAVE_HDF5\n\n#ifdef HAVE_PSRDADA\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n char * buffer = 0;\n uint64_t bufferBytes = 0;\n\n buffer = ipcbuf_get_next_read(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block), &bufferBytes);\n if ( (buffer == 0) || (bufferBytes == 0) ) {\n throw RingBufferError(\"Impossible to read the PSRDADA buffer.\");\n }\n std::memcpy(reinterpret_cast< void * >(data->data()), reinterpret_cast< const void * >(buffer), data->size() * sizeof(T));\n if ( ipcbuf_mark_cleared(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block)) < 0 ) {\n throw RingBufferError(\"Impossible to mark the PSRDADA buffer as cleared.\");\n }\n}\n#endif \/\/ HAVE_PSRDADA\n\n} \/\/ AstroData\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <exception>\n#include <H5Cpp.h>\n#include <dada_hdu.h>\n#include <ascii_header.h>\n\n#include <Observation.hpp>\n#include <utils.hpp>\n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDada ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n RingBufferError();\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\n};\n\ntemplate< typename T > void readSIGPROC(Observation & observation, const unsigned int bytestoSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation & observation, unsigned int bytesToSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = sizeof(T);\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n data.at(second)->at((static_cast< long long unsigned int >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)->at((globalChannel * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError();\n }\n\n ascii_header_get(header, \"SAMPLES_PER_SECOND\", \"%d\", &uintValue);\n observation.setNrSamplesPerSecond(uintValue);\n ascii_header_get(header, \"CHANNELS\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(uintValue, floatValue[0], floatValue[1]);\n ipcbuf_mark_cleared(ringBuffer.header_block);\n\n delete header;\n}\n\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n if ( (ipcio_read(ringBuffer.data_block, reinterpret_cast< char * >(data->data()), observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * sizeof(T))) < 0 ) {\n throw RingBufferError();\n }\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<commit_msg>With readSIGPROC it is now possible to read input files where samples are less than 8 bits.<commit_after>\/\/ Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <exception>\n#include <H5Cpp.h>\n#include <dada_hdu.h>\n#include <ascii_header.h>\n\n#include <Observation.hpp>\n#include <utils.hpp>\n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDada ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n RingBufferError();\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\n};\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = sizeof(T);\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n if ( inputBits >= 8 ) {\n data.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(second)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n data.at(second) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding()));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond() \/ (8 \/ inputBits); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(second)->at((static_cast< uint64_t >(channel - 1) * (observation.getNrSamplesPerSecond() \/ (8 \/ inputBits))) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n }\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)->at((globalChannel * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError();\n }\n\n ascii_header_get(header, \"SAMPLES_PER_SECOND\", \"%d\", &uintValue);\n observation.setNrSamplesPerSecond(uintValue);\n ascii_header_get(header, \"CHANNELS\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(uintValue, floatValue[0], floatValue[1]);\n ipcbuf_mark_cleared(ringBuffer.header_block);\n\n delete header;\n}\n\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n if ( (ipcio_read(ringBuffer.data_block, reinterpret_cast< char * >(data->data()), observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * sizeof(T))) < 0 ) {\n throw RingBufferError();\n }\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_planning_system\/PlanDispatcher.h\"\n#include <map>\n\nnamespace KCL_rosplan {\n\n\tint PlanDispatcher::getCurrentAction() {\n\t\treturn current_action;\n\t}\n\n\tvoid PlanDispatcher::reset() {\n\t\tdispatch_paused = false;\n\t\tcurrent_action = 0;\n\t\taction_received.clear();\n\t\taction_completed.clear();\n\t\treplan_requested = false;\n\t}\n\n\t\/*-----------------*\/\n\t\/* action dispatch *\/\n\t\/*-----------------*\/\n\n\t\/*\n\t * Loop through and publish planned actions\n\t *\/\n\tbool PlanDispatcher::dispatchPlan(const std::vector<rosplan_dispatch_msgs::ActionDispatch> &actionList, double missionStart, double planStart) {\n\n\t\tros::NodeHandle nh(\"~\");\n\t\tros::Rate loop_rate(10);\n\n\t\tROS_INFO(\"KCL: (PS) Dispatching plan\");\n\t\treplan_requested = false;\n\t\tbool repeatAction = false;\n\t\twhile (ros::ok() && actionList.size() > current_action) {\n\n\t\t\t\/\/ get next action\n\t\t\trosplan_dispatch_msgs::ActionDispatch currentMessage = actionList[current_action];\n\t\t\tif((unsigned int)currentMessage.action_id != current_action)\n\t\t\t\tROS_ERROR(\"KCL: (PS) Message action_id [%d] does not meet expected [%zu]\", currentMessage.action_id, current_action);\n\n\t\t\t\/\/ loop while waiting for dispatch time\n\t\t\tif(!dispatch_on_completion) {\n\t\t\t\tdouble wait_period = 10.0;\n\t\t\t\tint wait_print = (int)(currentMessage.dispatch_time + planStart - ros::WallTime::now().toSec()) \/ wait_period;\n\t\t\t\twhile (ros::ok() && ros::WallTime::now().toSec() < currentMessage.dispatch_time + planStart) {\n\t\t\t\t\tros::spinOnce();\n\t\t\t\t\tloop_rate.sleep();\n\t\t\t\t\tdouble remaining = planStart + currentMessage.dispatch_time - ros::WallTime::now().toSec();\n\t\t\t\t\tif(wait_print > (int)remaining \/ wait_period) {\n\t\t\t\t\t\tROS_INFO(\"KCL: (PS) Waiting %f before dispatching action: [%i, %s, %f, %f]\",\n\t\t\t\t\t\t\t\tremaining,currentMessage.action_id, currentMessage.name.c_str(),\n\t\t\t\t\t\t\t\t (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration);\n\t\t\t\t\t\twait_print--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!checkPreconditions(currentMessage)) {\n\t\t\t\tROS_INFO(\"KCL: (PS) Preconditions not achieved [%i, %s]\", currentMessage.action_id, currentMessage.name.c_str());\n\t\t\t}\n\n\t\t\t\/\/ dispatch action\n\t\t\tROS_INFO(\"KCL: (PS) Dispatching action [%i, %s, %f, %f]\", currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration);\n\t\t\taction_publisher.publish(currentMessage);\n\t\t\tdouble late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time + planStart));\n\t\t\tif(late_print>0.1) ROS_INFO(\"KCL: (PS) Action [%i] is %f second(s) late\", currentMessage.action_id, late_print);\n\n\t\t\t\/\/ wait for action to complete\n\t\t\tif(dispatch_concurrent) {\n\t\t\t\tint counter = 0;\n\t\t\t\twhile (ros::ok() && !action_completed[current_action]) {\n\t\t\t\t\tros::spinOnce();\n\t\t\t\t\tloop_rate.sleep();\n\t\t\t\t\tcounter++;\n\t\t\t\t\tif (counter == 2000) {\n\t\t\t\t\t\tROS_INFO(\"KCL: (PS) Action %i timed out now. Cancelling...\", currentMessage.action_id);\n\t\t\t\t\t\trosplan_dispatch_msgs::ActionDispatch cancelMessage;\n\t\t\t\t\t\tcancelMessage.action_id = currentMessage.action_id;\n\t\t\t\t\t\tcancelMessage.name = \"cancel_action\";\n\t\t\t\t\t\taction_publisher.publish(cancelMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ get ready for next action\n\t\t\tif(!repeatAction) current_action++;\n\t\t\trepeatAction = false;\n\t\t\taction_received[current_action] = false;\n\t\t\taction_completed[current_action] = false;\n\n\t\t\t\/\/ finish dispatch and replan\n\t\t\tif(replan_requested) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) {\n\n\t\t\/\/ setup service call\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient queryKnowledgeClient = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(\"\/kcl_rosplan\/query_knowledge_base\");\n\t\trosplan_knowledge_msgs::KnowledgeQueryService querySrv;\n\n\t\tstd::map<std::string, std::vector<std::vector<std::string> > >::iterator oit;\n\t\toit = environment.domain_operator_precondition_map.find(msg.name);\n\t\tif(oit==environment.domain_operator_precondition_map.end()) return false;\n\n\t\t\/\/ iterate through conditions\n\t\tstd::vector<std::vector<std::string> >::iterator cit = oit->second.begin();\n\t\tfor(; cit!=oit->second.end(); cit++) {\n\t\t\t\n\t\t\trosplan_knowledge_msgs::KnowledgeItem condition;\n\t\t\t\n\t\t\t\/\/ set fact or function\n\t\t\tstd::map<std::string,std::vector<std::string> >::iterator dit = environment.domain_predicates.find((*cit)[0]);\n\t\t\tif(dit!=environment.domain_predicates.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;\n\n\t\t\tdit = environment.domain_functions.find((*cit)[0]);\n\t\t\tif(dit!=environment.domain_functions.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION;\n\n\t\t\t\/\/ populate parameters\n\t\t\tcondition.attribute_name = (*cit)[0];\n\t\t\tstd::vector<diagnostic_msgs::KeyValue>::iterator pit;\n\t\t\tfor(pit = msg.parameters.begin(); pit!=msg.parameters.end(); pit++)\n\t\t\t\tcondition.values.push_back(*pit);\n\n\t\t\tquerySrv.request.knowledge.push_back(condition);\n\t\t}\n\n\t\t\/\/ check conditions in knowledge base\n\t\tif (queryKnowledgeClient.call(querySrv)) {\n\t\t\t\n\t\t\treturn querySrv.response.all_true;\n\n\t\t} else {\n\t\t\tROS_ERROR(\"KCL: (PS) Failed to call service \/kcl_rosplan\/query_knowledge_base\");\n\t\t}\n\t}\n\n\t\/*------------------*\/\n\t\/* general feedback *\/\n\t\/*------------------*\/\n\n\t\/**\n\t * listen to and process actionFeedback topic.\n\t *\/\n\tvoid PlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {\n\n\t\t\/\/ create error if the action is unrecognised\n\t\tROS_INFO(\"KCL: (PS) Feedback received [%i,%s]\", msg->action_id, msg->status.c_str());\n\t\tif(current_action != (unsigned int)msg->action_id)\n\t\t\tROS_ERROR(\"KCL: (PS) Unexpected action ID: %d; current action: %zu\", msg->action_id, current_action);\n\n\t\t\/\/ action enabled\n\t\tif(!action_received[msg->action_id] && (0 == msg->status.compare(\"action enabled\")))\n\t\t\taction_received[msg->action_id] = true;\n\t\t\n\t\t\/\/ more specific feedback\n\t\tactionFeedback(msg);\n\n\t\t\/\/ action completed (successfuly)\n\t\tif(!action_completed[msg->action_id] && 0 == msg->status.compare(\"action achieved\"))\n\t\t\taction_completed[msg->action_id] = true;\n\n\t\t\/\/ action completed (failed)\n\t\tif(!action_completed[msg->action_id] && 0 == msg->status.compare(\"action failed\")) {\n\t\t\treplan_requested = true;\n\t\t\taction_completed[msg->action_id] = true;\n\t\t}\n\t}\n\n\t\/*---------------------------*\/\n\t\/* Specific action responses *\/\n\t\/*---------------------------*\/\n\n\t\/**\n\t * processes single action feedback message.\n\t * This method serves as the hook for defining more interesting behaviour on action feedback.\n\t *\/\n\tvoid PlanDispatcher::actionFeedback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {\n\t\t\/\/ nothing yet...\n\t}\n} \/\/ close namespace\n<commit_msg>Correct flag as online<commit_after>#include \"rosplan_planning_system\/PlanDispatcher.h\"\n#include <map>\n\nnamespace KCL_rosplan {\n\n\tint PlanDispatcher::getCurrentAction() {\n\t\treturn current_action;\n\t}\n\n\tvoid PlanDispatcher::reset() {\n\t\tdispatch_paused = false;\n\t\tcurrent_action = 0;\n\t\taction_received.clear();\n\t\taction_completed.clear();\n\t\treplan_requested = false;\n\t}\n\n\t\/*-----------------*\/\n\t\/* action dispatch *\/\n\t\/*-----------------*\/\n\n\t\/*\n\t * Loop through and publish planned actions\n\t *\/\n\tbool PlanDispatcher::dispatchPlan(const std::vector<rosplan_dispatch_msgs::ActionDispatch> &actionList, double missionStart, double planStart) {\n\n\t\tros::NodeHandle nh(\"~\");\n\t\tros::Rate loop_rate(10);\n\n\t\tROS_INFO(\"KCL: (PS) Dispatching plan\");\n\t\treplan_requested = false;\n\t\tbool repeatAction = false;\n\t\twhile (ros::ok() && actionList.size() > current_action) {\n\n\t\t\t\/\/ get next action\n\t\t\trosplan_dispatch_msgs::ActionDispatch currentMessage = actionList[current_action];\n\t\t\tif((unsigned int)currentMessage.action_id != current_action)\n\t\t\t\tROS_ERROR(\"KCL: (PS) Message action_id [%d] does not meet expected [%zu]\", currentMessage.action_id, current_action);\n\n\t\t\t\/\/ loop while waiting for dispatch time\n\t\t\tif(!dispatch_on_completion) {\n\t\t\t\tdouble wait_period = 10.0;\n\t\t\t\tint wait_print = (int)(currentMessage.dispatch_time + planStart - ros::WallTime::now().toSec()) \/ wait_period;\n\t\t\t\twhile (ros::ok() && ros::WallTime::now().toSec() < currentMessage.dispatch_time + planStart) {\n\t\t\t\t\tros::spinOnce();\n\t\t\t\t\tloop_rate.sleep();\n\t\t\t\t\tdouble remaining = planStart + currentMessage.dispatch_time - ros::WallTime::now().toSec();\n\t\t\t\t\tif(wait_print > (int)remaining \/ wait_period) {\n\t\t\t\t\t\tROS_INFO(\"KCL: (PS) Waiting %f before dispatching action: [%i, %s, %f, %f]\",\n\t\t\t\t\t\t\t\tremaining,currentMessage.action_id, currentMessage.name.c_str(),\n\t\t\t\t\t\t\t\t (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration);\n\t\t\t\t\t\twait_print--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!checkPreconditions(currentMessage)) {\n\t\t\t\tROS_INFO(\"KCL: (PS) Preconditions not achieved [%i, %s]\", currentMessage.action_id, currentMessage.name.c_str());\n\t\t\t}\n\n\t\t\t\/\/ dispatch action\n\t\t\tROS_INFO(\"KCL: (PS) Dispatching action [%i, %s, %f, %f]\", currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration);\n\t\t\taction_publisher.publish(currentMessage);\n\t\t\tdouble late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time + planStart));\n\t\t\tif(late_print>0.1) ROS_INFO(\"KCL: (PS) Action [%i] is %f second(s) late\", currentMessage.action_id, late_print);\n\n\t\t\t\/\/ wait for action to complete\n\t\t\tif(!dispatch_concurrent) {\n\t\t\t\tint counter = 0;\n\t\t\t\twhile (ros::ok() && !action_completed[current_action]) {\n\t\t\t\t\tros::spinOnce();\n\t\t\t\t\tloop_rate.sleep();\n\t\t\t\t\tcounter++;\n\t\t\t\t\tif (counter == 2000) {\n\t\t\t\t\t\tROS_INFO(\"KCL: (PS) Action %i timed out now. Cancelling...\", currentMessage.action_id);\n\t\t\t\t\t\trosplan_dispatch_msgs::ActionDispatch cancelMessage;\n\t\t\t\t\t\tcancelMessage.action_id = currentMessage.action_id;\n\t\t\t\t\t\tcancelMessage.name = \"cancel_action\";\n\t\t\t\t\t\taction_publisher.publish(cancelMessage);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ get ready for next action\n\t\t\tif(!repeatAction) current_action++;\n\t\t\trepeatAction = false;\n\t\t\taction_received[current_action] = false;\n\t\t\taction_completed[current_action] = false;\n\n\t\t\t\/\/ finish dispatch and replan\n\t\t\tif(replan_requested) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) {\n\n\t\t\/\/ setup service call\n\t\tros::NodeHandle nh;\n\t\tros::ServiceClient queryKnowledgeClient = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(\"\/kcl_rosplan\/query_knowledge_base\");\n\t\trosplan_knowledge_msgs::KnowledgeQueryService querySrv;\n\n\t\tstd::map<std::string, std::vector<std::vector<std::string> > >::iterator oit;\n\t\toit = environment.domain_operator_precondition_map.find(msg.name);\n\t\tif(oit==environment.domain_operator_precondition_map.end()) return false;\n\n\t\t\/\/ iterate through conditions\n\t\tstd::vector<std::vector<std::string> >::iterator cit = oit->second.begin();\n\t\tfor(; cit!=oit->second.end(); cit++) {\n\t\t\t\n\t\t\trosplan_knowledge_msgs::KnowledgeItem condition;\n\t\t\t\n\t\t\t\/\/ set fact or function\n\t\t\tstd::map<std::string,std::vector<std::string> >::iterator dit = environment.domain_predicates.find((*cit)[0]);\n\t\t\tif(dit!=environment.domain_predicates.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;\n\n\t\t\tdit = environment.domain_functions.find((*cit)[0]);\n\t\t\tif(dit!=environment.domain_functions.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION;\n\n\t\t\t\/\/ populate parameters\n\t\t\tcondition.attribute_name = (*cit)[0];\n\t\t\tstd::vector<diagnostic_msgs::KeyValue>::iterator pit;\n\t\t\tfor(pit = msg.parameters.begin(); pit!=msg.parameters.end(); pit++) {\n\t\t\t\tcondition.values.push_back(*pit);\n\t\t\t}\n\n\n\t\t\tquerySrv.request.knowledge.push_back(condition);\n\t\t}\n\n\t\t\/\/ check conditions in knowledge base\n\t\tif (queryKnowledgeClient.call(querySrv)) {\n\t\t\t\n\t\t\treturn querySrv.response.all_true;\n\n\t\t} else {\n\t\t\tROS_ERROR(\"KCL: (PS) Failed to call service \/kcl_rosplan\/query_knowledge_base\");\n\t\t}\n\t}\n\n\t\/*------------------*\/\n\t\/* general feedback *\/\n\t\/*------------------*\/\n\n\t\/**\n\t * listen to and process actionFeedback topic.\n\t *\/\n\tvoid PlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {\n\n\t\t\/\/ create error if the action is unrecognised\n\t\tROS_INFO(\"KCL: (PS) Feedback received [%i,%s]\", msg->action_id, msg->status.c_str());\n\t\tif(current_action != (unsigned int)msg->action_id)\n\t\t\tROS_ERROR(\"KCL: (PS) Unexpected action ID: %d; current action: %zu\", msg->action_id, current_action);\n\n\t\t\/\/ action enabled\n\t\tif(!action_received[msg->action_id] && (0 == msg->status.compare(\"action enabled\")))\n\t\t\taction_received[msg->action_id] = true;\n\t\t\n\t\t\/\/ more specific feedback\n\t\tactionFeedback(msg);\n\n\t\t\/\/ action completed (successfuly)\n\t\tif(!action_completed[msg->action_id] && 0 == msg->status.compare(\"action achieved\"))\n\t\t\taction_completed[msg->action_id] = true;\n\n\t\t\/\/ action completed (failed)\n\t\tif(!action_completed[msg->action_id] && 0 == msg->status.compare(\"action failed\")) {\n\t\t\treplan_requested = true;\n\t\t\taction_completed[msg->action_id] = true;\n\t\t}\n\t}\n\n\t\/*---------------------------*\/\n\t\/* Specific action responses *\/\n\t\/*---------------------------*\/\n\n\t\/**\n\t * processes single action feedback message.\n\t * This method serves as the hook for defining more interesting behaviour on action feedback.\n\t *\/\n\tvoid PlanDispatcher::actionFeedback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {\n\t\t\/\/ nothing yet...\n\t}\n} \/\/ close namespace\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: atrflyin.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 09:23:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#include \"hintids.hxx\"\n#include \"cntfrm.hxx\" \/\/ _GetFly\n#include \"doc.hxx\"\n#include \"pam.hxx\" \/\/ fuer SwTxtFlyCnt\n#include \"flyfrm.hxx\" \/\/ fuer SwTxtFlyCnt\n#include \"ndtxt.hxx\" \/\/ SwFlyFrmFmt\n#include \"frmfmt.hxx\" \/\/ SwFlyFrmFmt\n\n#ifndef _FMTFLCNT_HXX \/\/autogen\n#include <fmtflcnt.hxx>\n#endif\n#ifndef _TXTFLCNT_HXX \/\/autogen\n#include <txtflcnt.hxx>\n#endif\n#ifndef _FMTANCHR_HXX \/\/autogen\n#include <fmtanchr.hxx>\n#endif\n#include \"swfont.hxx\"\n#include \"txtfrm.hxx\"\n#include \"flyfrms.hxx\"\n\/\/ --> OD 2004-11-09 #i26945#\n#ifndef _OBJECTFORMATTER_HXX\n#include <objectformatter.hxx>\n#endif\n\/\/ <--\n\nSwFmtFlyCnt::SwFmtFlyCnt( SwFrmFmt *pFrmFmt )\n : SfxPoolItem( RES_TXTATR_FLYCNT ),\n pTxtAttr( 0 ),\n pFmt( pFrmFmt )\n{\n}\n\nint __EXPORT SwFmtFlyCnt::operator==( const SfxPoolItem& rAttr ) const\n{\n ASSERT( SfxPoolItem::operator==( rAttr ), \"keine gleichen Attribute\" );\n return( pTxtAttr && ((SwFmtFlyCnt&)rAttr).pTxtAttr &&\n *pTxtAttr->GetStart() == *((SwFmtFlyCnt&)rAttr).pTxtAttr->GetStart() &&\n pFmt == ((SwFmtFlyCnt&)rAttr).GetFrmFmt() );\n}\n\nSfxPoolItem* __EXPORT SwFmtFlyCnt::Clone( SfxItemPool* ) const\n{\n return new SwFmtFlyCnt( pFmt );\n}\n\nSwTxtFlyCnt::SwTxtFlyCnt( const SwFmtFlyCnt& rAttr, xub_StrLen nStartPos )\n : SwTxtAttr( rAttr, nStartPos )\n{\n ((SwFmtFlyCnt&)rAttr).pTxtAttr = this;\n}\n\n\n\n\/*************************************************************************\n * SwTxtFlyCnt::MakeTxtHint()\n *\n * An dieser Stelle soll einmal der Gesamtzusammenhang bei der Erzeugung\n * eines neuen SwTxtFlyCnt erlaeutert werden.\n * Das MakeTxtHint() wird z.B. im SwTxtNode::Copy() gerufen.\n * Fuer die komplette Verdopplung sind folgende Schritte notwendig:\n * 1) Duplizieren des pFmt incl. Inhalt, Attributen etc.\n * 2) Setzen des Ankers\n * 3) Benachrichtigung\n * Da fuer die Bewaeltigung der Aufgaben nicht immer alle Informationen\n * bereitstehen und darueber hinaus bestimmte Methoden erst zu einem\n * spaeteren Zeitpunkt gerufen werden duerfen (weil nocht nicht alle\n * Nodeinformationen vorliegen), verteilt sich der Ablauf.\n * ad 1) MakeTxtHint() wird durch den Aufruf von SwDoc::CopyLayout()\n * der das neue FlyFrmFmt erzeugt und mit dem duplizierten Inhalt des\n * FlyFrm verbunden.\n * ad 2) SetAnchor() wird von SwTxtNode::Insert() gerufen und sorgt fuer das\n * setzen des Ankers (die SwPosition des Dummy-Zeichens wird dem FlyFrmFmt\n * per SetAttr bekannt gegeben). Dies kann nicht im MakeTxtHint erledigt\n * werden, da der Zielnode unbestimmt ist.\n * ad 3) _GetFlyFrm() wird im Formatierungsprozess vom LineIter gerufen\n * und sucht den FlyFrm zum Dummyzeichen des aktuellen CntntFrm. Wird keiner\n * gefunden, so wird ein neuer FlyFrm angelegt.\n * Kritisch an diesem Vorgehen ist, dass das pCntnt->AppendFly() eine\n * sofortige Neuformatierung von pCntnt anstoesst. Die Rekursion kommt\n * allerdings durch den Lockmechanismus in SwTxtFrm::Format() nicht\n * zu stande.\n * Attraktiv ist der Umstand, dass niemand ueber die vom Node abhaengigen\n * CntntFrms iterieren braucht, um die FlyInCntFrm anzulegen. Dies geschieht\n * bei der Arbeit.\n *************************************************************************\/\n\nvoid SwTxtFlyCnt::CopyFlyFmt( SwDoc* pDoc )\n{\n SwFrmFmt* pFmt = GetFlyCnt().GetFrmFmt();\n ASSERT( pFmt, \"von welchem Format soll ich eine Kopie erzeugen?\" )\n \/\/ Das FlyFrmFmt muss dupliziert werden.\n \/\/ In CopyLayoutFmt (siehe doclay.cxx) wird das FlyFrmFmt erzeugt\n \/\/ und der Inhalt dupliziert.\n\n \/\/ fuers kopieren vom Attribut das Undo immer abschalten\n BOOL bUndo = pDoc->DoesUndo();\n pDoc->DoUndo( FALSE );\n SwFmtAnchor aAnchor( pFmt->GetAnchor() );\n if( FLY_PAGE != aAnchor.GetAnchorId() &&\n pDoc != pFmt->GetDoc() ) \/\/ Unterschiedliche Docs?\n {\n \/\/ JP 03.06.96: dann sorge dafuer, das der koperierte Anker auf\n \/\/ gueltigen Content zeigt! Die Umsetzung auf die\n \/\/ richtige Position erfolgt spaeter.\n SwNodeIndex aIdx( pDoc->GetNodes().GetEndOfExtras(), +2 );\n SwCntntNode* pCNd = aIdx.GetNode().GetCntntNode();\n if( !pCNd )\n pCNd = pDoc->GetNodes().GoNext( &aIdx );\n\n SwPosition* pPos = (SwPosition*)aAnchor.GetCntntAnchor();\n pPos->nNode = aIdx;\n if( FLY_IN_CNTNT == aAnchor.GetAnchorId() )\n pPos->nContent.Assign( pCNd, 0 );\n else\n {\n pPos->nContent.Assign( 0, 0 );\n ASSERT( !this, \"CopyFlyFmt: Was fuer ein Anker?\" );\n }\n }\n\n SwFrmFmt* pNew = pDoc->CopyLayoutFmt( *pFmt, aAnchor, false, false );\n pDoc->DoUndo( bUndo );\n ((SwFmtFlyCnt&)GetFlyCnt()).SetFlyFmt( pNew );\n}\n\n\/*************************************************************************\n * SwTxtFlyCnt::SetAnchor()\n *\n * SetAnchor() wird von SwTxtNode::Insert() gerufen und sorgt fuer das\n * setzen des Ankers (die SwPosition des Dummy-Zeichens wird dem FlyFrmFmt\n * per SetAttr bekannt gegeben). Dies kann nicht im MakeTxtHint erledigt\n * werden, da der Zielnode unbestimmt ist.\n * (siehe Kommentar in SwTxtFlyCnt::MakeTxtHint)\n *************************************************************************\/\n\nvoid SwTxtFlyCnt::SetAnchor( const SwTxtNode *pNode )\n{\n \/\/ fuers Undo muss der neue Anker schon bekannt sein !\n\n \/\/ Wir ermitteln den Index im Nodesarray zum Node\n\n SwDoc* pDoc = (SwDoc*)pNode->GetDoc();\n\n SwIndex aIdx( (SwTxtNode*)pNode, *GetStart() );\n SwPosition aPos( *pNode->StartOfSectionNode(), aIdx );\n SwFrmFmt* pFmt = GetFlyCnt().GetFrmFmt();\n SwFmtAnchor aAnchor( pFmt->GetAnchor() );\n\n if( !aAnchor.GetCntntAnchor() ||\n !aAnchor.GetCntntAnchor()->nNode.GetNode().GetNodes().IsDocNodes() ||\n &aAnchor.GetCntntAnchor()->nNode.GetNode() != (SwNode*)pNode )\n aPos.nNode = *pNode;\n else\n aPos.nNode = aAnchor.GetCntntAnchor()->nNode;\n\n aAnchor.SetType( FLY_IN_CNTNT ); \/\/ defaulten !!\n aAnchor.SetAnchor( &aPos );\n\n \/\/ beim Ankerwechsel werden immer alle FlyFrms vom Attribut geloescht\n \/\/ JP 25.04.95: wird innerhalb des SplitNodes die Frames verschoben\n \/\/ koennen die Frames erhalten bleiben.\n if( ( !pNode->GetpSwpHints() || !pNode->GetpSwpHints()->IsInSplitNode() )\n && RES_DRAWFRMFMT != pFmt->Which() )\n pFmt->DelFrms();\n\n \/\/ stehen wir noch im falschen Dokument ?\n if( pDoc != pFmt->GetDoc() )\n {\n \/\/ fuers kopieren vom Attribut das Undo immer abschalten\n BOOL bUndo = pDoc->DoesUndo();\n pDoc->DoUndo( FALSE );\n SwFrmFmt* pNew = pDoc->CopyLayoutFmt( *pFmt, aAnchor, false, false );\n pDoc->DoUndo( bUndo );\n\n bUndo = pFmt->GetDoc()->DoesUndo();\n pFmt->GetDoc()->DoUndo( FALSE );\n pFmt->GetDoc()->DelLayoutFmt( pFmt );\n pFmt->GetDoc()->DoUndo( bUndo );\n ((SwFmtFlyCnt&)GetFlyCnt()).SetFlyFmt( pNew );\n }\n else if( pNode->GetpSwpHints() &&\n pNode->GetpSwpHints()->IsInSplitNode() &&\n RES_DRAWFRMFMT != pFmt->Which() )\n {\n pFmt->LockModify();\n pFmt->SetAttr( aAnchor ); \/\/ nur den Anker neu setzen\n pFmt->UnlockModify();\n }\n else\n pFmt->SetAttr( aAnchor ); \/\/ nur den Anker neu setzen\n\n \/\/ Am Node haengen u.a. abhaengige CntFrms.\n \/\/ Fuer jeden CntFrm wird ein SwFlyInCntFrm angelegt.\n}\n\n\/*************************************************************************\n * SwTxtFlyCnt::_GetFlyFrm()\n *\n * _GetFlyFrm() wird im Formatierungsprozess vom LineIter gerufen\n * und sucht den FlyFrm zum Dummyzeichen des aktuellen CntntFrm. Wird keiner\n * gefunden, so wird ein neuer FlyFrm angelegt.\n * (siehe Kommentar ind SwTxtFlyCnt::MakeTxtHint)\n *************************************************************************\/\n\nSwFlyInCntFrm *SwTxtFlyCnt::_GetFlyFrm( const SwFrm *pCurrFrm )\n{\n SwFrmFmt* pFrmFmt = GetFlyCnt().GetFrmFmt();\n if( RES_DRAWFRMFMT == pFrmFmt->Which() )\n {\n ASSERT( !this, \"SwTxtFlyCnt::_GetFlyFrm: DrawInCnt-Baustelle!\" );\n return NULL;\n }\n\n SwClientIter aIter( *GetFlyCnt().pFmt );\n ASSERT( pCurrFrm->IsTxtFrm(), \"SwTxtFlyCnt::_GetFlyFrm for TxtFrms only.\" );\n\n if( aIter.GoStart() )\n {\n SwTxtFrm *pFirst = (SwTxtFrm*)pCurrFrm;\n while ( pFirst->IsFollow() )\n pFirst = pFirst->FindMaster();\n do\n { SwFrm * pFrm = PTR_CAST( SwFrm, aIter() );\n if ( pFrm )\n {\n SwTxtFrm *pTmp = pFirst;\n do\n { if( ( (SwFlyFrm*)pFrm )->GetAnchorFrm() == (SwFrm*) pTmp )\n {\n if ( pTmp != pCurrFrm )\n {\n pTmp->RemoveFly( (SwFlyFrm*)pFrm );\n ((SwTxtFrm*)pCurrFrm)->AppendFly( (SwFlyFrm*)pFrm );\n }\n return (SwFlyInCntFrm*)pFrm;\n }\n pTmp = pTmp->GetFollow();\n } while ( pTmp );\n }\n } while( aIter++ );\n }\n\n \/\/ Wir haben keinen passenden FlyFrm gefunden, deswegen wird ein\n \/\/ neuer angelegt.\n \/\/ Dabei wird eine sofortige Neuformatierung von pCurrFrm angestossen.\n \/\/ Die Rekursion wird durch den Lockmechanismus in SwTxtFrm::Format()\n \/\/ abgewuergt.\n SwFlyInCntFrm *pFly = new SwFlyInCntFrm( (SwFlyFrmFmt*)pFrmFmt, (SwFrm*)pCurrFrm );\n ((SwFrm*)pCurrFrm)->AppendFly( pFly );\n pFly->RegistFlys();\n\n \/\/ 7922: Wir muessen dafuer sorgen, dass der Inhalt des FlyInCnt\n \/\/ nach seiner Konstruktion stramm durchformatiert wird.\n \/\/ --> OD 2004-11-09 #i26945# - Use new object formatter to format Writer\n \/\/ fly frame and its content.\n SwObjectFormatter::FormatObj( *pFly, const_cast<SwFrm*>(pCurrFrm),\n pCurrFrm->FindPageFrm() );\n \/\/ <--\n\n return pFly;\n}\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.8.242); FILE MERGED 2008\/04\/01 12:54:27 thb 1.8.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:54:58 rt 1.8.242.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: atrflyin.cxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#include \"hintids.hxx\"\n#include \"cntfrm.hxx\" \/\/ _GetFly\n#include \"doc.hxx\"\n#include \"pam.hxx\" \/\/ fuer SwTxtFlyCnt\n#include \"flyfrm.hxx\" \/\/ fuer SwTxtFlyCnt\n#include \"ndtxt.hxx\" \/\/ SwFlyFrmFmt\n#include \"frmfmt.hxx\" \/\/ SwFlyFrmFmt\n#include <fmtflcnt.hxx>\n#include <txtflcnt.hxx>\n#include <fmtanchr.hxx>\n#include \"swfont.hxx\"\n#include \"txtfrm.hxx\"\n#include \"flyfrms.hxx\"\n\/\/ --> OD 2004-11-09 #i26945#\n#include <objectformatter.hxx>\n\/\/ <--\n\nSwFmtFlyCnt::SwFmtFlyCnt( SwFrmFmt *pFrmFmt )\n : SfxPoolItem( RES_TXTATR_FLYCNT ),\n pTxtAttr( 0 ),\n pFmt( pFrmFmt )\n{\n}\n\nint __EXPORT SwFmtFlyCnt::operator==( const SfxPoolItem& rAttr ) const\n{\n ASSERT( SfxPoolItem::operator==( rAttr ), \"keine gleichen Attribute\" );\n return( pTxtAttr && ((SwFmtFlyCnt&)rAttr).pTxtAttr &&\n *pTxtAttr->GetStart() == *((SwFmtFlyCnt&)rAttr).pTxtAttr->GetStart() &&\n pFmt == ((SwFmtFlyCnt&)rAttr).GetFrmFmt() );\n}\n\nSfxPoolItem* __EXPORT SwFmtFlyCnt::Clone( SfxItemPool* ) const\n{\n return new SwFmtFlyCnt( pFmt );\n}\n\nSwTxtFlyCnt::SwTxtFlyCnt( const SwFmtFlyCnt& rAttr, xub_StrLen nStartPos )\n : SwTxtAttr( rAttr, nStartPos )\n{\n ((SwFmtFlyCnt&)rAttr).pTxtAttr = this;\n}\n\n\n\n\/*************************************************************************\n * SwTxtFlyCnt::MakeTxtHint()\n *\n * An dieser Stelle soll einmal der Gesamtzusammenhang bei der Erzeugung\n * eines neuen SwTxtFlyCnt erlaeutert werden.\n * Das MakeTxtHint() wird z.B. im SwTxtNode::Copy() gerufen.\n * Fuer die komplette Verdopplung sind folgende Schritte notwendig:\n * 1) Duplizieren des pFmt incl. Inhalt, Attributen etc.\n * 2) Setzen des Ankers\n * 3) Benachrichtigung\n * Da fuer die Bewaeltigung der Aufgaben nicht immer alle Informationen\n * bereitstehen und darueber hinaus bestimmte Methoden erst zu einem\n * spaeteren Zeitpunkt gerufen werden duerfen (weil nocht nicht alle\n * Nodeinformationen vorliegen), verteilt sich der Ablauf.\n * ad 1) MakeTxtHint() wird durch den Aufruf von SwDoc::CopyLayout()\n * der das neue FlyFrmFmt erzeugt und mit dem duplizierten Inhalt des\n * FlyFrm verbunden.\n * ad 2) SetAnchor() wird von SwTxtNode::Insert() gerufen und sorgt fuer das\n * setzen des Ankers (die SwPosition des Dummy-Zeichens wird dem FlyFrmFmt\n * per SetAttr bekannt gegeben). Dies kann nicht im MakeTxtHint erledigt\n * werden, da der Zielnode unbestimmt ist.\n * ad 3) _GetFlyFrm() wird im Formatierungsprozess vom LineIter gerufen\n * und sucht den FlyFrm zum Dummyzeichen des aktuellen CntntFrm. Wird keiner\n * gefunden, so wird ein neuer FlyFrm angelegt.\n * Kritisch an diesem Vorgehen ist, dass das pCntnt->AppendFly() eine\n * sofortige Neuformatierung von pCntnt anstoesst. Die Rekursion kommt\n * allerdings durch den Lockmechanismus in SwTxtFrm::Format() nicht\n * zu stande.\n * Attraktiv ist der Umstand, dass niemand ueber die vom Node abhaengigen\n * CntntFrms iterieren braucht, um die FlyInCntFrm anzulegen. Dies geschieht\n * bei der Arbeit.\n *************************************************************************\/\n\nvoid SwTxtFlyCnt::CopyFlyFmt( SwDoc* pDoc )\n{\n SwFrmFmt* pFmt = GetFlyCnt().GetFrmFmt();\n ASSERT( pFmt, \"von welchem Format soll ich eine Kopie erzeugen?\" )\n \/\/ Das FlyFrmFmt muss dupliziert werden.\n \/\/ In CopyLayoutFmt (siehe doclay.cxx) wird das FlyFrmFmt erzeugt\n \/\/ und der Inhalt dupliziert.\n\n \/\/ fuers kopieren vom Attribut das Undo immer abschalten\n BOOL bUndo = pDoc->DoesUndo();\n pDoc->DoUndo( FALSE );\n SwFmtAnchor aAnchor( pFmt->GetAnchor() );\n if( FLY_PAGE != aAnchor.GetAnchorId() &&\n pDoc != pFmt->GetDoc() ) \/\/ Unterschiedliche Docs?\n {\n \/\/ JP 03.06.96: dann sorge dafuer, das der koperierte Anker auf\n \/\/ gueltigen Content zeigt! Die Umsetzung auf die\n \/\/ richtige Position erfolgt spaeter.\n SwNodeIndex aIdx( pDoc->GetNodes().GetEndOfExtras(), +2 );\n SwCntntNode* pCNd = aIdx.GetNode().GetCntntNode();\n if( !pCNd )\n pCNd = pDoc->GetNodes().GoNext( &aIdx );\n\n SwPosition* pPos = (SwPosition*)aAnchor.GetCntntAnchor();\n pPos->nNode = aIdx;\n if( FLY_IN_CNTNT == aAnchor.GetAnchorId() )\n pPos->nContent.Assign( pCNd, 0 );\n else\n {\n pPos->nContent.Assign( 0, 0 );\n ASSERT( !this, \"CopyFlyFmt: Was fuer ein Anker?\" );\n }\n }\n\n SwFrmFmt* pNew = pDoc->CopyLayoutFmt( *pFmt, aAnchor, false, false );\n pDoc->DoUndo( bUndo );\n ((SwFmtFlyCnt&)GetFlyCnt()).SetFlyFmt( pNew );\n}\n\n\/*************************************************************************\n * SwTxtFlyCnt::SetAnchor()\n *\n * SetAnchor() wird von SwTxtNode::Insert() gerufen und sorgt fuer das\n * setzen des Ankers (die SwPosition des Dummy-Zeichens wird dem FlyFrmFmt\n * per SetAttr bekannt gegeben). Dies kann nicht im MakeTxtHint erledigt\n * werden, da der Zielnode unbestimmt ist.\n * (siehe Kommentar in SwTxtFlyCnt::MakeTxtHint)\n *************************************************************************\/\n\nvoid SwTxtFlyCnt::SetAnchor( const SwTxtNode *pNode )\n{\n \/\/ fuers Undo muss der neue Anker schon bekannt sein !\n\n \/\/ Wir ermitteln den Index im Nodesarray zum Node\n\n SwDoc* pDoc = (SwDoc*)pNode->GetDoc();\n\n SwIndex aIdx( (SwTxtNode*)pNode, *GetStart() );\n SwPosition aPos( *pNode->StartOfSectionNode(), aIdx );\n SwFrmFmt* pFmt = GetFlyCnt().GetFrmFmt();\n SwFmtAnchor aAnchor( pFmt->GetAnchor() );\n\n if( !aAnchor.GetCntntAnchor() ||\n !aAnchor.GetCntntAnchor()->nNode.GetNode().GetNodes().IsDocNodes() ||\n &aAnchor.GetCntntAnchor()->nNode.GetNode() != (SwNode*)pNode )\n aPos.nNode = *pNode;\n else\n aPos.nNode = aAnchor.GetCntntAnchor()->nNode;\n\n aAnchor.SetType( FLY_IN_CNTNT ); \/\/ defaulten !!\n aAnchor.SetAnchor( &aPos );\n\n \/\/ beim Ankerwechsel werden immer alle FlyFrms vom Attribut geloescht\n \/\/ JP 25.04.95: wird innerhalb des SplitNodes die Frames verschoben\n \/\/ koennen die Frames erhalten bleiben.\n if( ( !pNode->GetpSwpHints() || !pNode->GetpSwpHints()->IsInSplitNode() )\n && RES_DRAWFRMFMT != pFmt->Which() )\n pFmt->DelFrms();\n\n \/\/ stehen wir noch im falschen Dokument ?\n if( pDoc != pFmt->GetDoc() )\n {\n \/\/ fuers kopieren vom Attribut das Undo immer abschalten\n BOOL bUndo = pDoc->DoesUndo();\n pDoc->DoUndo( FALSE );\n SwFrmFmt* pNew = pDoc->CopyLayoutFmt( *pFmt, aAnchor, false, false );\n pDoc->DoUndo( bUndo );\n\n bUndo = pFmt->GetDoc()->DoesUndo();\n pFmt->GetDoc()->DoUndo( FALSE );\n pFmt->GetDoc()->DelLayoutFmt( pFmt );\n pFmt->GetDoc()->DoUndo( bUndo );\n ((SwFmtFlyCnt&)GetFlyCnt()).SetFlyFmt( pNew );\n }\n else if( pNode->GetpSwpHints() &&\n pNode->GetpSwpHints()->IsInSplitNode() &&\n RES_DRAWFRMFMT != pFmt->Which() )\n {\n pFmt->LockModify();\n pFmt->SetAttr( aAnchor ); \/\/ nur den Anker neu setzen\n pFmt->UnlockModify();\n }\n else\n pFmt->SetAttr( aAnchor ); \/\/ nur den Anker neu setzen\n\n \/\/ Am Node haengen u.a. abhaengige CntFrms.\n \/\/ Fuer jeden CntFrm wird ein SwFlyInCntFrm angelegt.\n}\n\n\/*************************************************************************\n * SwTxtFlyCnt::_GetFlyFrm()\n *\n * _GetFlyFrm() wird im Formatierungsprozess vom LineIter gerufen\n * und sucht den FlyFrm zum Dummyzeichen des aktuellen CntntFrm. Wird keiner\n * gefunden, so wird ein neuer FlyFrm angelegt.\n * (siehe Kommentar ind SwTxtFlyCnt::MakeTxtHint)\n *************************************************************************\/\n\nSwFlyInCntFrm *SwTxtFlyCnt::_GetFlyFrm( const SwFrm *pCurrFrm )\n{\n SwFrmFmt* pFrmFmt = GetFlyCnt().GetFrmFmt();\n if( RES_DRAWFRMFMT == pFrmFmt->Which() )\n {\n ASSERT( !this, \"SwTxtFlyCnt::_GetFlyFrm: DrawInCnt-Baustelle!\" );\n return NULL;\n }\n\n SwClientIter aIter( *GetFlyCnt().pFmt );\n ASSERT( pCurrFrm->IsTxtFrm(), \"SwTxtFlyCnt::_GetFlyFrm for TxtFrms only.\" );\n\n if( aIter.GoStart() )\n {\n SwTxtFrm *pFirst = (SwTxtFrm*)pCurrFrm;\n while ( pFirst->IsFollow() )\n pFirst = pFirst->FindMaster();\n do\n { SwFrm * pFrm = PTR_CAST( SwFrm, aIter() );\n if ( pFrm )\n {\n SwTxtFrm *pTmp = pFirst;\n do\n { if( ( (SwFlyFrm*)pFrm )->GetAnchorFrm() == (SwFrm*) pTmp )\n {\n if ( pTmp != pCurrFrm )\n {\n pTmp->RemoveFly( (SwFlyFrm*)pFrm );\n ((SwTxtFrm*)pCurrFrm)->AppendFly( (SwFlyFrm*)pFrm );\n }\n return (SwFlyInCntFrm*)pFrm;\n }\n pTmp = pTmp->GetFollow();\n } while ( pTmp );\n }\n } while( aIter++ );\n }\n\n \/\/ Wir haben keinen passenden FlyFrm gefunden, deswegen wird ein\n \/\/ neuer angelegt.\n \/\/ Dabei wird eine sofortige Neuformatierung von pCurrFrm angestossen.\n \/\/ Die Rekursion wird durch den Lockmechanismus in SwTxtFrm::Format()\n \/\/ abgewuergt.\n SwFlyInCntFrm *pFly = new SwFlyInCntFrm( (SwFlyFrmFmt*)pFrmFmt, (SwFrm*)pCurrFrm );\n ((SwFrm*)pCurrFrm)->AppendFly( pFly );\n pFly->RegistFlys();\n\n \/\/ 7922: Wir muessen dafuer sorgen, dass der Inhalt des FlyInCnt\n \/\/ nach seiner Konstruktion stramm durchformatiert wird.\n \/\/ --> OD 2004-11-09 #i26945# - Use new object formatter to format Writer\n \/\/ fly frame and its content.\n SwObjectFormatter::FormatObj( *pFly, const_cast<SwFrm*>(pCurrFrm),\n pCurrFrm->FindPageFrm() );\n \/\/ <--\n\n return pFly;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $\n\n#ifndef GRAPHICS_HPP\n#define GRAPHICS_HPP\n\n#include <cmath>\n#include <string>\n#include <cassert>\n#include \"color.hpp\"\n#include \"gamma.hpp\"\n#include \"image_data.hpp\"\n#include \"envelope.hpp\"\n\nnamespace mapnik\n{\n class MAPNIK_DECL Image32\n {\n private:\n\tunsigned width_;\n\tunsigned height_;\n\tColor background_;\n\tImageData32 data_;\n public:\n\tImage32(int width,int height);\n\tImage32(const Image32& rhs);\n\t~Image32();\n\tvoid setBackground(const Color& background);\n\tconst Color& getBackground() const; \n\tconst ImageData32& data() const;\n\tinline ImageData32& data() {\n\t return data_;\n\t}\n\tinline const unsigned char* raw_data() const\n\t{\n\t return data_.getBytes();\n\t}\n\t\n\tinline unsigned char* raw_data()\n\t{\n\t return data_.getBytes();\n\t}\n\t\n\tvoid saveToFile(const std::string& file,const std::string& format=\"auto\"); \n private:\n\n\tinline bool checkBounds(unsigned x, unsigned y) const\n\t{\n\t return (x < width_ && y < height_);\n\t}\n\n public:\n\tinline void setPixel(int x,int y,unsigned int rgba)\n\t{\n\t if (checkBounds(x,y))\n\t {\n\t\tdata_(x,y)=rgba;\n\t }\n\t}\n\tinline void blendPixel(int x,int y,unsigned int rgba1,int t)\n\t{\n\t if (checkBounds(x,y))\n\t {\n\t\tunsigned rgba0 = data_(x,y);\t\n\t\tunsigned a1 = t;\/\/(rgba1 >> 24) & 0xff;\n\t\tif (a1 == 0) return;\n\t\tunsigned r1 = rgba1 & 0xff;\n\t\tunsigned g1 = (rgba1 >> 8 ) & 0xff;\n\t\tunsigned b1 = (rgba1 >> 16) & 0xff;\n\t\t\n\t\tunsigned a0 = (rgba0 >> 24) & 0xff;\n\t\tunsigned r0 = (rgba0 & 0xff) * a0;\n\t\tunsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;\n\t\tunsigned b0 = ((rgba0 >> 16) & 0xff) * a0;\n\t\t\n\t\t\n\t\ta0 = ((a1 + a0) << 8) - a0*a1;\n\t\t\n\t\tr0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) \/ a0);\n\t\tg0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) \/ a0);\n\t\tb0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) \/ a0);\n\t\ta0 = a0 >> 8;\n\t\tdata_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;\n\t }\n\t}\n\n\tinline unsigned width() const\n\t{\n\t return width_;\n\t}\n\t\n\tinline unsigned height() const\n\t{\n\t return height_;\n\t}\n\n\tinline void set_rectangle(int x0,int y0,ImageData32 const& data)\n\t{\n\t Envelope<int> ext0(0,0,width_,height_); \n\t Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());\n\t \n\t if (ext0.intersects(ext1))\n\t {\t\n\t\tEnvelope<int> box = ext0.intersect(ext1);\n\t\tfor (int y = box.miny(); y < box.maxy(); ++y)\n\t\t{\n\t\t for (int x = box.minx(); x < box.maxx(); ++x)\n\t\t {\n\t\t\tif ((data(x-x0,y-y0) & 0xff000000)) \n\t\t\t{\n\t\t\t data_(x,y)=data(x-x0,y-y0);\n\t\t\t}\n\t\t }\n\t\t} \n\t }\n\t}\n\t\n\tinline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)\n\t{\n\t Envelope<int> ext0(0,0,width_,height_); \n\t Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());\n\t \n\t if (ext0.intersects(ext1))\n\t {\t \t\t\n\t\tEnvelope<int> box = ext0.intersect(ext1);\t\t\n\t\tfor (int y = box.miny(); y < box.maxy(); ++y)\n\t\t{\n\t\t for (int x = box.minx(); x < box.maxx(); ++x)\n\t\t {\n\t\t\tunsigned rgba0 = data_(x,y);\n\t\t\tunsigned rgba1 = data(x-x0,y-y0);\n\t\t \n\t\t\tunsigned a1 = (rgba1 >> 24) & 0xff;\n\t\t\tif (a1 == 0) continue;\n\t\t\tunsigned r1 = rgba1 & 0xff;\n\t\t\tunsigned g1 = (rgba1 >> 8 ) & 0xff;\n\t\t\tunsigned b1 = (rgba1 >> 16) & 0xff;\n\t\t \n\t\t\tunsigned a0 = (rgba0 >> 24) & 0xff;\n\t\t\tunsigned r0 = (rgba0 & 0xff) * a0;\n\t\t\tunsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;\n\t\t\tunsigned b0 = ((rgba0 >> 16) & 0xff) * a0;\n\t\t \n\t\t \n\t\t\ta0 = ((a1 + a0) << 8) - a0*a1;\n\t\t \n\t\t\tr0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) \/ a0);\n\t\t\tg0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) \/ a0);\n\t\t\tb0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) \/ a0);\n\t\t\ta0 = a0 >> 8;\n\t\t\tdata_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;\n\t\t }\n\t\t}\n\t }\n\t}\n };\n}\n#endif \/\/GRAPHICS_HPP\n<commit_msg>replaced tabs with spaces<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $\n\n#ifndef GRAPHICS_HPP\n#define GRAPHICS_HPP\n\n#include <cmath>\n#include <string>\n#include <cassert>\n#include \"color.hpp\"\n#include \"gamma.hpp\"\n#include \"image_data.hpp\"\n#include \"envelope.hpp\"\n\nnamespace mapnik\n{\n class MAPNIK_DECL Image32\n {\n private:\n unsigned width_;\n unsigned height_;\n Color background_;\n ImageData32 data_;\n public:\n Image32(int width,int height);\n Image32(const Image32& rhs);\n ~Image32();\n void setBackground(const Color& background);\n const Color& getBackground() const; \n const ImageData32& data() const;\n inline ImageData32& data() {\n return data_;\n }\n inline const unsigned char* raw_data() const\n {\n return data_.getBytes();\n }\n\t\n inline unsigned char* raw_data()\n {\n return data_.getBytes();\n }\n\t\n void saveToFile(const std::string& file,const std::string& format=\"auto\"); \n private:\n\n inline bool checkBounds(unsigned x, unsigned y) const\n {\n return (x < width_ && y < height_);\n }\n\n public:\n inline void setPixel(int x,int y,unsigned int rgba)\n {\n if (checkBounds(x,y))\n {\n data_(x,y)=rgba;\n }\n }\n inline void blendPixel(int x,int y,unsigned int rgba1,int t)\n {\n if (checkBounds(x,y))\n {\n unsigned rgba0 = data_(x,y);\t\n unsigned a1 = t;\/\/(rgba1 >> 24) & 0xff;\n if (a1 == 0) return;\n unsigned r1 = rgba1 & 0xff;\n unsigned g1 = (rgba1 >> 8 ) & 0xff;\n unsigned b1 = (rgba1 >> 16) & 0xff;\n\t\t\n unsigned a0 = (rgba0 >> 24) & 0xff;\n unsigned r0 = (rgba0 & 0xff) * a0;\n unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;\n unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;\n\t\t\n\t\t\n a0 = ((a1 + a0) << 8) - a0*a1;\n\t\t\n r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) \/ a0);\n g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) \/ a0);\n b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) \/ a0);\n a0 = a0 >> 8;\n data_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;\n }\n }\n\n inline unsigned width() const\n {\n return width_;\n }\n\t\n inline unsigned height() const\n {\n return height_;\n }\n\n inline void set_rectangle(int x0,int y0,ImageData32 const& data)\n {\n Envelope<int> ext0(0,0,width_,height_); \n Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());\n\t \n if (ext0.intersects(ext1))\n {\t\n Envelope<int> box = ext0.intersect(ext1);\n for (int y = box.miny(); y < box.maxy(); ++y)\n {\n for (int x = box.minx(); x < box.maxx(); ++x)\n {\n if ((data(x-x0,y-y0) & 0xff000000)) \n {\n data_(x,y)=data(x-x0,y-y0);\n }\n }\n } \n }\n }\n\t\n inline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)\n {\n Envelope<int> ext0(0,0,width_,height_); \n Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());\n\t \n if (ext0.intersects(ext1))\n {\t \t\t\n Envelope<int> box = ext0.intersect(ext1);\t\t\n for (int y = box.miny(); y < box.maxy(); ++y)\n {\n for (int x = box.minx(); x < box.maxx(); ++x)\n {\n unsigned rgba0 = data_(x,y);\n unsigned rgba1 = data(x-x0,y-y0);\n\t\t \n unsigned a1 = (rgba1 >> 24) & 0xff;\n if (a1 == 0) continue;\n unsigned r1 = rgba1 & 0xff;\n unsigned g1 = (rgba1 >> 8 ) & 0xff;\n unsigned b1 = (rgba1 >> 16) & 0xff;\n\t\t \n unsigned a0 = (rgba0 >> 24) & 0xff;\n unsigned r0 = (rgba0 & 0xff) * a0;\n unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;\n unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;\n\t\t \n\t\t \n a0 = ((a1 + a0) << 8) - a0*a1;\n\t\t \n r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) \/ a0);\n g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) \/ a0);\n b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) \/ a0);\n a0 = a0 >> 8;\n data_(x,y)= (a0 << 24)| (b0 << 16) | (g0 << 8) | (r0) ;\n }\n }\n }\n }\n };\n}\n#endif \/\/GRAPHICS_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \".\/headers\/Book.h\"\n\n\/*!\n \\fn Book::Book()\n \\brief Constructor sets book position to 0,0,0\n Constructor which initialises all the required data members for the class\n*\/\nBook::Book(){\n this->x = 0;\n this->y = 0;\n this->z = 0;\n this->width = BOOK_WIDTH;\n this->height = BOOK_HEIGHT;\n this->noOfPages = 0;\n this->pages = new Page*[MAX_NO_PAGES];\n this->currentPageIndex = 0;\n}\n\n\/*!\n \\fn Book::renderBook()\n \\brief Render the book.\n Render the Book with the margin and border on the screen.\n*\/\nvoid Book::renderBook(){\n int i=0;\n glColor3f(0.0,0.0,0.0);\n setBorder();\n}\n\n\/*!\n \\fn Book::setBorder()\n \\brief Set Page Border\n Set the page border based on the size mentioned in the config\/constants file.\n Render a 3d image for the book.\n*\/\nvoid Book::setBorder(){\n glColor3f(0,0,0);\n GLfloat xLimit = x + width;\n GLfloat yLimit = y + height;\n GLfloat zLimit = z - BOOK_THICKNESS;\n cubeConstruction(x, y, z, xLimit, yLimit, zLimit);\n glColor3f(1,1,1);\n fillFaces(xLimit, yLimit, zLimit);\n}\n\n\/*!\n \\fn Book::addPage(GLint type, char s[])\n \\brief Add a new Page\n Add a text page to the book by creating a new page from Page class and storing that as \n a page in the created Book object.\n type -> Page type\n s -> String to be rendered onto the page\n*\/\nvoid Book::addPage(GLint type, char s[]){\n pages[noOfPages] = new Page(type, (x + BOOK_BORDER_SIZE), y + BOOK_BORDER_SIZE, -(noOfPages * (PAGE_THICKNESS + PAGE_GAP)), s);\n noOfPages++;\n}\n\n\/*!\n \\fn Book::addPage(GLint type, void (*pageContent)(GLfloat, GLfloat, GLfloat, GLfloat, GLfloat))\n \\brief Add a new Page\n Add a drawing page to the book by creating a new page from Page class and storing that as \n a page in the created Book object.\n type -> Page type\n pageContent -> function pointer which renders the drawing inside the Page. \n*\/\nvoid Book::addPage(GLint type, void (*pageContent)(GLfloat, GLfloat, GLfloat, GLfloat, GLfloat)){\n pages[noOfPages] = new Page(type, (x + BOOK_BORDER_SIZE), y + BOOK_BORDER_SIZE, -(noOfPages * (PAGE_THICKNESS + PAGE_GAP)), pageContent);\n noOfPages++;\n}\n\n\/*!\n \\fn Book::renderPage()\n \\brief Render the Page constructed\n Render the Page pointed by the currentPageIndex.\n*\/\nvoid Book::renderPage(){\n pages[currentPageIndex]->renderPage();\n}\n\n\/*!\n \\fn Book::renderPage(GLint pageIndex)\n \\brief Render the Page constructed\n Render the specified page in the book.\n*\/\nvoid Book::renderPage(GLint pageIndex){\n if(pageIndex<noOfPages){\n pages[pageIndex]->renderPage();\n currentPageIndex = pageIndex;\n }\n}\n\n\/*!\n \\fn constructPolygon()\n \\brief Construct a Polygon for the given vertices\n*\/\nvoid constructPolygon(GLfloat vertices[][3]){\n glBegin(GL_POLYGON);\n for(int i=0;i<4;i++){\n glVertex3f(vertices[i][0],vertices[i][1],vertices[i][2]);\n glNormal3f(vertices[i][0],vertices[i][1],vertices[i][2]);\n }\n glEnd();\n}\n\n\/*!\n \\fn fillFaces()\n \\brief Select each face and construct a Polygon\n*\/\nvoid Book::fillFaces(GLfloat xLimit, GLfloat yLimit, GLfloat zLimit){\n GLfloat backFace[][3]={\n {x, y, zLimit}, {xLimit, y, zLimit}, {xLimit, yLimit, zLimit}, {x, yLimit, zLimit}\n };\n constructPolygon(backFace);\n GLfloat bottomFace[][3]={\n {x,y,z},{xLimit,y,z},{xLimit,y,zLimit},{x,y,zLimit}\n };\n constructPolygon(bottomFace);\n GLfloat topFace[][3]={\n {x,yLimit,z},{xLimit,yLimit,z},{xLimit,yLimit,zLimit},{x,yLimit,zLimit}\n };\n constructPolygon(topFace);\n GLfloat leftFace[][3]={\n {x,y,z},{x,yLimit,z},{x,yLimit,zLimit},{x,y,zLimit}\n };\n constructPolygon(leftFace);\n GLfloat rightFace[][3]={\n {xLimit,y,zLimit},{xLimit,yLimit,zLimit},{xLimit,yLimit,z},{xLimit,yLimit,z}\n };\n constructPolygon(rightFace);\n}<commit_msg>Colouring the Book edges for 360 deg viewing<commit_after>#include \".\/headers\/Book.h\"\n\n\/*!\n \\fn Book::Book()\n \\brief Constructor sets book position to 0,0,0\n Constructor which initialises all the required data members for the class\n*\/\nBook::Book(){\n this->x = 0;\n this->y = 0;\n this->z = 0;\n this->width = BOOK_WIDTH;\n this->height = BOOK_HEIGHT;\n this->noOfPages = 0;\n this->pages = new Page*[MAX_NO_PAGES];\n this->currentPageIndex = 0;\n}\n\n\/*!\n \\fn Book::renderBook()\n \\brief Render the book.\n Render the Book with the margin and border on the screen.\n*\/\nvoid Book::renderBook(){\n int i=0;\n glColor3f(0.0,0.0,0.0);\n setBorder();\n}\n\n\/*!\n \\fn Book::setBorder()\n \\brief Set Page Border\n Set the page border based on the size mentioned in the config\/constants file.\n Render a 3d image for the book.\n*\/\nvoid Book::setBorder(){\n glColor3f(0,0,0);\n GLfloat xLimit = x + width;\n GLfloat yLimit = y + height;\n GLfloat zLimit = z - BOOK_THICKNESS;\n cubeConstruction(x, y, z, xLimit, yLimit, zLimit);\n glColor3f(1,1,1);\n fillFaces(xLimit, yLimit, zLimit);\n}\n\n\/*!\n \\fn Book::addPage(GLint type, char s[])\n \\brief Add a new Page\n Add a text page to the book by creating a new page from Page class and storing that as \n a page in the created Book object.\n type -> Page type\n s -> String to be rendered onto the page\n*\/\nvoid Book::addPage(GLint type, char s[]){\n pages[noOfPages] = new Page(type, (x + BOOK_BORDER_SIZE), y + BOOK_BORDER_SIZE, -(noOfPages * (PAGE_THICKNESS + PAGE_GAP)), s);\n noOfPages++;\n}\n\n\/*!\n \\fn Book::addPage(GLint type, void (*pageContent)(GLfloat, GLfloat, GLfloat, GLfloat, GLfloat))\n \\brief Add a new Page\n Add a drawing page to the book by creating a new page from Page class and storing that as \n a page in the created Book object.\n type -> Page type\n pageContent -> function pointer which renders the drawing inside the Page. \n*\/\nvoid Book::addPage(GLint type, void (*pageContent)(GLfloat, GLfloat, GLfloat, GLfloat, GLfloat)){\n pages[noOfPages] = new Page(type, (x + BOOK_BORDER_SIZE), y + BOOK_BORDER_SIZE, -(noOfPages * (PAGE_THICKNESS + PAGE_GAP)), pageContent);\n noOfPages++;\n}\n\n\/*!\n \\fn Book::renderPage()\n \\brief Render the Page constructed\n Render the Page pointed by the currentPageIndex.\n*\/\nvoid Book::renderPage(){\n pages[currentPageIndex]->renderPage();\n}\n\n\/*!\n \\fn Book::renderPage(GLint pageIndex)\n \\brief Render the Page constructed\n Render the specified page in the book.\n*\/\nvoid Book::renderPage(GLint pageIndex){\n if(pageIndex<noOfPages){\n pages[pageIndex]->renderPage();\n currentPageIndex = pageIndex;\n }\n}\n\n\/*!\n \\fn constructPolygon()\n \\brief Construct a Polygon for the given vertices\n*\/\nvoid constructPolygon(GLfloat vertices[][3]){\n glBegin(GL_POLYGON);\n for(int i=0;i<4;i++){\n glVertex3f(vertices[i][0],vertices[i][1],vertices[i][2]);\n glNormal3f(vertices[i][0],vertices[i][1],vertices[i][2]);\n }\n glEnd();\n}\n\n\/*!\n \\fn fillFaces()\n \\brief Select each face and construct a Polygon\n*\/\nvoid Book::fillFaces(GLfloat xLimit, GLfloat yLimit, GLfloat zLimit){\n glColor3f(0.5,0,0.5);\n GLfloat backFace[][3]={\n {x, y, zLimit}, {xLimit, y, zLimit}, {xLimit, yLimit, zLimit}, {x, yLimit, zLimit}\n };\n constructPolygon(backFace);\n GLfloat bottomFace[][3]={\n {x,y,z},{xLimit,y,z},{xLimit,y,zLimit},{x,y,zLimit}\n };\n constructPolygon(bottomFace);\n GLfloat topFace[][3]={\n {x,yLimit,z},{xLimit,yLimit,z},{xLimit,yLimit,zLimit},{x,yLimit,zLimit}\n };\n constructPolygon(topFace);\n GLfloat leftFace[][3]={\n {x,y,z},{x,yLimit,z},{x,yLimit,zLimit},{x,y,zLimit}\n };\n constructPolygon(leftFace);\n GLfloat rightFace[][3]={\n {xLimit,y,zLimit},{xLimit,yLimit,zLimit},{xLimit,yLimit,z},{xLimit,yLimit,z}\n };\n constructPolygon(rightFace);\n glColor3f(1,1,1);\n}<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n printf(\"hello world!\\n\");\n printf(\"show me the code\\n\");\n printf(\"Talk is cheap\\n\");\n sleep(100); \n \/\/ this is first branch.\n return 0;\n}\n\n<commit_msg>second line<commit_after>#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n printf(\"hello world!\\n\");\n printf(\"show me the code\\n\");\n printf(\"Talk is cheap\\n\");\n sleep(100); \n \/\/ this is first branch.\n\n \/\/ this is the second line.\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"city.h\"\n#include \"..\/..\/framework\/data.h\"\n\n#include <iostream>\n\nstd::unique_ptr<City> City::city;\n\nCity::City(std::string mapName)\n\t: sizeX(100), sizeY(100), sizeZ(100)\n{\n\tauto file = DATA->load_file(\"ufodata\/\" + mapName, \"r\");\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Failed to open city map:\" << mapName << \"\\n\";\n\t\treturn;\n\t}\n\n\ttiles.resize(sizeZ);\n\n\tfor (int z = 0; z < sizeZ; z++)\n\t{\n\t\ttiles[z].resize(sizeY);\n\t\tfor (int y = 0; y < sizeY; y++)\n\t\t{\n\t\t\ttiles[z][y].resize(sizeX);\n\t\t\tfor (int x = 0; x < sizeX; x++)\n\t\t\t{\n\t\t\t\tint16_t tileID = al_fread16le(file);\n\t\t\t\ttiles[z][y][x] = CityTile(tileID);\n\t\t\t}\n\t\t}\n\t}\n\n\tal_fclose(file);\n}\n\nCity::~City()\n{\n\n}\n\nCityTile::CityTile(int id)\n\t: id(id)\n{\n}\n<commit_msg>Citymap is 10 high, not 100<commit_after>#include \"city.h\"\n#include \"..\/..\/framework\/data.h\"\n\n#include <iostream>\n\nstd::unique_ptr<City> City::city;\n\nCity::City(std::string mapName)\n\t: sizeX(100), sizeY(100), sizeZ(10)\n{\n\tauto file = DATA->load_file(\"ufodata\/\" + mapName, \"r\");\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Failed to open city map:\" << mapName << \"\\n\";\n\t\treturn;\n\t}\n\n\ttiles.resize(sizeZ);\n\n\tfor (int z = 0; z < sizeZ; z++)\n\t{\n\t\ttiles[z].resize(sizeY);\n\t\tfor (int y = 0; y < sizeY; y++)\n\t\t{\n\t\t\ttiles[z][y].resize(sizeX);\n\t\t\tfor (int x = 0; x < sizeX; x++)\n\t\t\t{\n\t\t\t\tint16_t tileID = al_fread16le(file);\n\t\t\t\tif (tileID == -1 &&\n\t\t\t\t al_feof(file))\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Unexpected EOF reading citymap at x=\"\n\t\t\t\t\t\t<< x << \" y = \" << y << \" z = \" << z << \"\\n\";\n\t\t\t\t\tal_fclose(file);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttiles[z][y][x] = CityTile(tileID);\n\t\t\t}\n\t\t}\n\t}\n\n\tal_fclose(file);\n}\n\nCity::~City()\n{\n\n}\n\nCityTile::CityTile(int id)\n\t: id(id)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <cstdarg>\n#include <algorithm>\n#include <iostream>\n#include \"chunk.hh\"\n#include \"compiler.hh\"\n#include \"vm.hh\"\n\nnamespace tadpole {\n\nclass CallFrame final : public Copyable {\n ClosureObject* closure_{};\n const u8_t* ip_{};\n sz_t stack_begpos_{};\npublic:\n CallFrame() noexcept {}\n CallFrame(ClosureObject* c, const u8_t* i, sz_t begpos = 0) noexcept\n : closure_(c), ip_(i), stack_begpos_(begpos) {\n }\n\n inline ClosureObject* closure() const noexcept { return closure_; }\n inline FunctionObject* frame_fn() const noexcept { return closure_->fn(); }\n inline Chunk* frame_chunk() const noexcept { return frame_fn()->chunk(); }\n inline const u8_t* ip() const noexcept { return ip_; }\n inline u8_t get_ip(sz_t i) const noexcept { return ip_[i]; }\n inline u8_t inc_ip() noexcept { return *ip_++; }\n inline u8_t dec_ip() noexcept { return *ip_--; }\n inline sz_t stack_begpos() const noexcept { return stack_begpos_; }\n};\n\nVM::VM() noexcept {\n gcompiler_ = new GlobalCompiler();\n stack_.reserve(kDefaultCap);\n\n \/\/ TODO: register built-in functions\n}\n\nVM::~VM() {\n delete gcompiler_;\n\n globals_.clear();\n interned_strings_.clear();\n\n while (!objects_.empty()) {\n auto* o = objects_.back();\n objects_.pop_back();\n\n reclaim_object(o);\n }\n}\n\nvoid VM::define_native(const str_t& name, NativeFn&& fn) {\n globals_[name] = NativeObject::create(*this, std::move(fn));\n}\n\nvoid VM::append_object(BaseObject* o) {\n if (objects_.size() >= kGCThreshold)\n collect();\n\n objects_.push_back(o);\n}\n\nvoid VM::mark_object(BaseObject* o) {\n if (o == nullptr || o->is_marked())\n return;\n\n#if defined(_TADPOLE_DEBUG_GC)\n std::cout << \"[\" << o << \"] mark object: `\" << o->stringify() << \"`\" << std::endl;\n#endif\n\n o->set_marked(true);\n worklist_.push_back(o);\n}\n\nvoid VM::mark_value(const Value& v) {\n if (v.is_object())\n mark_object(v.as_object());\n}\n\nInterpretRet VM::interpret(const str_t& source_bytes) {\n FunctionObject* fn = gcompiler_->compile(*this, source_bytes);\n if (fn == nullptr)\n return InterpretRet::ECOMPILE;\n\n push(fn);\n ClosureObject* closure = ClosureObject::create(*this, fn);\n pop();\n call(closure, 0);\n\n return run();\n}\n\nvoid VM::collect() {\n \/\/ mark root objects\n gcompiler_->mark_compiler();\n for (auto& v : stack_)\n mark_value(v);\n for (auto& f : frames_)\n mark_object(f.closure());\n for (auto& g : globals_)\n mark_value(g.second);\n for (auto* u = open_upvalues_; u != nullptr; u = u->next())\n mark_object(u);\n\n \/\/ mark reference objects\n while (!worklist_.empty()) {\n auto* o = worklist_.back();\n worklist_.pop_back();\n o->gc_blacken(*this);\n }\n\n \/\/ delete unmarked interned string objects\n for (auto it = interned_strings_.begin(); it != interned_strings_.end();) {\n if (!it->second->is_marked())\n interned_strings_.erase(it++);\n else\n ++it;\n }\n\n \/\/ sweep and reclaim unmarked objects\n for (auto it = objects_.begin(); it != objects_.end();) {\n if (!(*it)->is_marked()) {\n reclaim_object(*it);\n objects_.erase(it++);\n }\n else {\n (*it)->set_marked(false);\n ++it;\n }\n }\n\n gc_threshold_ = std::max(kGCThreshold, objects_.size() * kGCFactor);\n}\n\nvoid VM::reclaim_object(BaseObject* o) {\n#if defined(_TADPOLE_DEBUG_GC)\n std::cout << \"[\" << o << \"] reclaim object: `\" << o->stringify() << \"`\" << std::endl;\n#endif\n\n delete o;\n}\n\nvoid VM::reset() {\n stack_.clear();\n frames_.clear();\n open_upvalues_ = nullptr;\n}\n\nvoid VM::runtime_error(const char* format, ...) {\n std::cerr << \"Traceback (most recent call last):\" << std::endl;\n for (auto it = frames_.rbegin(); it != frames_.rend(); ++it) {\n auto& frame = *it;\n\n sz_t i = frame.frame_chunk()->offset(frame.ip()) - 1;\n std::cerr\n << \" [LINE: \" << frame.frame_chunk()->get_line(i) << \"] in \"\n << \"`\" << frame.frame_fn()->name_asstr() << \"()`\"\n << std::endl;\n }\n\n va_list ap;\n va_start(ap, format);\n std::vfprintf(stderr, format, ap);\n va_end(ap);\n std::fprintf(stderr, \"\\n\");\n\n reset();\n}\n\nvoid VM::push(Value value) noexcept {\n stack_.push_back(value);\n}\n\nValue VM::pop() noexcept {\n Value value = stack_.back();\n stack_.pop_back();\n return value;\n}\n\nconst Value& VM::peek(sz_t distance) const noexcept {\n return stack_[stack_.size() - 1 - distance];\n}\n\nbool VM::call(ClosureObject* closure, sz_t argc) {\n FunctionObject* fn = closure->fn();\n if (fn->arity() != argc) {\n runtime_error(\"%s() takes exactly %ud arguments (%ud given)\",\n fn->name_asstr(), fn->arity(), argc);\n return false;\n }\n\n frames_.push_back(CallFrame(closure, fn->chunk()->codes(), stack_.size() - argc - 1));\n return true;\n}\n\nbool VM::call(const Value& callee, sz_t argc) {\n if (callee.is_object()) {\n switch (callee.objtype()) {\n case ObjType::NATIVE:\n {\n Value* args = nullptr;\n if (argc > 0 && stack_.size() > argc)\n args = &stack_[stack_.size() - argc];\n\n Value result = callee.as_native()->fn()(argc, args);\n stack_.resize(stack_.size() - argc - 1);\n push(result);\n\n return true;\n }\n case ObjType::CLOSURE: return call(callee.as_closure(), argc);\n }\n }\n\n runtime_error(\"can only call function\");\n return false;\n}\n\nUpvalueObject* VM::capture_upvalue(Value* local) {\n if (open_upvalues_ == nullptr) {\n open_upvalues_ = UpvalueObject::create(*this, local);\n return open_upvalues_;\n }\n\n UpvalueObject* upvalue = open_upvalues_;\n UpvalueObject* prev_upvalue = nullptr;\n while (upvalue != nullptr && upvalue->value() > local) {\n prev_upvalue = upvalue;\n upvalue = upvalue->next();\n }\n if (upvalue != nullptr && upvalue->value() == local)\n return upvalue;\n\n UpvalueObject* new_upvalue = UpvalueObject::create(*this, local, upvalue);\n if (prev_upvalue == nullptr)\n open_upvalues_ = new_upvalue;\n else\n prev_upvalue->set_next(new_upvalue);\n return new_upvalue;\n}\n\nvoid VM::close_upvalues(Value* last) {\n while (open_upvalues_ != nullptr && open_upvalues_->value() >= last) {\n UpvalueObject* upvalue = open_upvalues_;\n upvalue->set_closed(upvalue->value_asref());\n upvalue->set_value(upvalue->closed_asptr());\n\n open_upvalues_ = upvalue->next();\n }\n}\n\nInterpretRet VM::run() {\n CallFrame* frame = &frames_.back();\n\n#define _RDBYTE() frame->inc_ip()\n#define _RDCONST() frame->frame_chunk()->get_constant(_RDBYTE())\n#define _RDSTR() _RDCONST().as_string()\n#define _RDCSTR() _RDCONST().as_cstring()\n#define _BINOP(op) do {\\\n if (!peek(0).is_numeric() || !peek(1).is_numeric()) {\\\n runtime_error(\"operands must be two numerics\");\\\n return InterpretRet::ERUNTIME;\\\n }\\\n double b = pop().as_numeric();\\\n double a = pop().as_numeric();\\\n push(a op b);\\\n } while (false)\n\n for (;;) {\n#if defined(_TADPOLE_DEBUG_VM)\n auto* frame_chunk = frame->frame_chunk();\n std::cout << \" \";\n for (auto& v : stack_)\n std::cout << \"[\" << v << \"]\";\n std::cout << std::endl;\n frame_chunk->dis_code(frame_chunk->offset(frame->ip()));\n#endif\n\n switch (Code c = as_type<Code>(_RDBYTE())) {\n case Code::CONSTANT: push(_RDCONST()); break;\n case Code::NIL: push(nullptr); break;\n case Code::FALSE: push(false); break;\n case Code::TRUE: push(true); break;\n case Code::POP: pop(); break;\n case Code::DEF_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n runtime_error(\"name `%s` is redefined\", name);\n return InterpretRet::ERUNTIME;\n }\n else {\n globals_[name] = pop();\n }\n } break;\n case Code::GET_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n push(it->second);\n }\n else {\n runtime_error(\"name `%s` is not defined\", name);\n return InterpretRet::ERUNTIME;\n }\n } break;\n case Code::SET_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n it->second = peek();\n }\n else {\n runtime_error(\"name `%s` is not defined\", name);\n return InterpretRet::ERUNTIME;\n }\n } break;\n case Code::GET_LOCAL: push(stack_[frame->stack_begpos() + _RDBYTE()]); break;\n case Code::SET_LOCAL: stack_[frame->stack_begpos() + _RDBYTE()] = peek(); break;\n case Code::GET_UPVALUE:\n {\n u8_t slot = _RDBYTE();\n push(frame->closure()->get_upvalue(slot)->value_asref());\n } break;\n case Code::SET_UPVALUE:\n {\n u8_t slot = _RDBYTE();\n frame->closure()->get_upvalue(slot)->set_value(peek());\n } break;\n }\n }\n\n#undef _BINOP\n#undef _RDCSTR\n#undef _RDSTR\n#undef _RDCONST\n#undef _RDBYTE\n\n return InterpretRet::OK;\n}\n\n}\n<commit_msg>:constuction: chore(vm): updated the vm code implementation about calc<commit_after>\/\/ Copyright (c) 2020 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <cstdarg>\n#include <algorithm>\n#include <iostream>\n#include \"chunk.hh\"\n#include \"compiler.hh\"\n#include \"vm.hh\"\n\nnamespace tadpole {\n\nclass CallFrame final : public Copyable {\n ClosureObject* closure_{};\n const u8_t* ip_{};\n sz_t stack_begpos_{};\npublic:\n CallFrame() noexcept {}\n CallFrame(ClosureObject* c, const u8_t* i, sz_t begpos = 0) noexcept\n : closure_(c), ip_(i), stack_begpos_(begpos) {\n }\n\n inline ClosureObject* closure() const noexcept { return closure_; }\n inline FunctionObject* frame_fn() const noexcept { return closure_->fn(); }\n inline Chunk* frame_chunk() const noexcept { return frame_fn()->chunk(); }\n inline const u8_t* ip() const noexcept { return ip_; }\n inline u8_t get_ip(sz_t i) const noexcept { return ip_[i]; }\n inline u8_t inc_ip() noexcept { return *ip_++; }\n inline u8_t dec_ip() noexcept { return *ip_--; }\n inline sz_t stack_begpos() const noexcept { return stack_begpos_; }\n};\n\nVM::VM() noexcept {\n gcompiler_ = new GlobalCompiler();\n stack_.reserve(kDefaultCap);\n\n \/\/ TODO: register built-in functions\n}\n\nVM::~VM() {\n delete gcompiler_;\n\n globals_.clear();\n interned_strings_.clear();\n\n while (!objects_.empty()) {\n auto* o = objects_.back();\n objects_.pop_back();\n\n reclaim_object(o);\n }\n}\n\nvoid VM::define_native(const str_t& name, NativeFn&& fn) {\n globals_[name] = NativeObject::create(*this, std::move(fn));\n}\n\nvoid VM::append_object(BaseObject* o) {\n if (objects_.size() >= kGCThreshold)\n collect();\n\n objects_.push_back(o);\n}\n\nvoid VM::mark_object(BaseObject* o) {\n if (o == nullptr || o->is_marked())\n return;\n\n#if defined(_TADPOLE_DEBUG_GC)\n std::cout << \"[\" << o << \"] mark object: `\" << o->stringify() << \"`\" << std::endl;\n#endif\n\n o->set_marked(true);\n worklist_.push_back(o);\n}\n\nvoid VM::mark_value(const Value& v) {\n if (v.is_object())\n mark_object(v.as_object());\n}\n\nInterpretRet VM::interpret(const str_t& source_bytes) {\n FunctionObject* fn = gcompiler_->compile(*this, source_bytes);\n if (fn == nullptr)\n return InterpretRet::ECOMPILE;\n\n push(fn);\n ClosureObject* closure = ClosureObject::create(*this, fn);\n pop();\n call(closure, 0);\n\n return run();\n}\n\nvoid VM::collect() {\n \/\/ mark root objects\n gcompiler_->mark_compiler();\n for (auto& v : stack_)\n mark_value(v);\n for (auto& f : frames_)\n mark_object(f.closure());\n for (auto& g : globals_)\n mark_value(g.second);\n for (auto* u = open_upvalues_; u != nullptr; u = u->next())\n mark_object(u);\n\n \/\/ mark reference objects\n while (!worklist_.empty()) {\n auto* o = worklist_.back();\n worklist_.pop_back();\n o->gc_blacken(*this);\n }\n\n \/\/ delete unmarked interned string objects\n for (auto it = interned_strings_.begin(); it != interned_strings_.end();) {\n if (!it->second->is_marked())\n interned_strings_.erase(it++);\n else\n ++it;\n }\n\n \/\/ sweep and reclaim unmarked objects\n for (auto it = objects_.begin(); it != objects_.end();) {\n if (!(*it)->is_marked()) {\n reclaim_object(*it);\n objects_.erase(it++);\n }\n else {\n (*it)->set_marked(false);\n ++it;\n }\n }\n\n gc_threshold_ = std::max(kGCThreshold, objects_.size() * kGCFactor);\n}\n\nvoid VM::reclaim_object(BaseObject* o) {\n#if defined(_TADPOLE_DEBUG_GC)\n std::cout << \"[\" << o << \"] reclaim object: `\" << o->stringify() << \"`\" << std::endl;\n#endif\n\n delete o;\n}\n\nvoid VM::reset() {\n stack_.clear();\n frames_.clear();\n open_upvalues_ = nullptr;\n}\n\nvoid VM::runtime_error(const char* format, ...) {\n std::cerr << \"Traceback (most recent call last):\" << std::endl;\n for (auto it = frames_.rbegin(); it != frames_.rend(); ++it) {\n auto& frame = *it;\n\n sz_t i = frame.frame_chunk()->offset(frame.ip()) - 1;\n std::cerr\n << \" [LINE: \" << frame.frame_chunk()->get_line(i) << \"] in \"\n << \"`\" << frame.frame_fn()->name_asstr() << \"()`\"\n << std::endl;\n }\n\n va_list ap;\n va_start(ap, format);\n std::vfprintf(stderr, format, ap);\n va_end(ap);\n std::fprintf(stderr, \"\\n\");\n\n reset();\n}\n\nvoid VM::push(Value value) noexcept {\n stack_.push_back(value);\n}\n\nValue VM::pop() noexcept {\n Value value = stack_.back();\n stack_.pop_back();\n return value;\n}\n\nconst Value& VM::peek(sz_t distance) const noexcept {\n return stack_[stack_.size() - 1 - distance];\n}\n\nbool VM::call(ClosureObject* closure, sz_t argc) {\n FunctionObject* fn = closure->fn();\n if (fn->arity() != argc) {\n runtime_error(\"%s() takes exactly %ud arguments (%ud given)\",\n fn->name_asstr(), fn->arity(), argc);\n return false;\n }\n\n frames_.push_back(CallFrame(closure, fn->chunk()->codes(), stack_.size() - argc - 1));\n return true;\n}\n\nbool VM::call(const Value& callee, sz_t argc) {\n if (callee.is_object()) {\n switch (callee.objtype()) {\n case ObjType::NATIVE:\n {\n Value* args = nullptr;\n if (argc > 0 && stack_.size() > argc)\n args = &stack_[stack_.size() - argc];\n\n Value result = callee.as_native()->fn()(argc, args);\n stack_.resize(stack_.size() - argc - 1);\n push(result);\n\n return true;\n }\n case ObjType::CLOSURE: return call(callee.as_closure(), argc);\n }\n }\n\n runtime_error(\"can only call function\");\n return false;\n}\n\nUpvalueObject* VM::capture_upvalue(Value* local) {\n if (open_upvalues_ == nullptr) {\n open_upvalues_ = UpvalueObject::create(*this, local);\n return open_upvalues_;\n }\n\n UpvalueObject* upvalue = open_upvalues_;\n UpvalueObject* prev_upvalue = nullptr;\n while (upvalue != nullptr && upvalue->value() > local) {\n prev_upvalue = upvalue;\n upvalue = upvalue->next();\n }\n if (upvalue != nullptr && upvalue->value() == local)\n return upvalue;\n\n UpvalueObject* new_upvalue = UpvalueObject::create(*this, local, upvalue);\n if (prev_upvalue == nullptr)\n open_upvalues_ = new_upvalue;\n else\n prev_upvalue->set_next(new_upvalue);\n return new_upvalue;\n}\n\nvoid VM::close_upvalues(Value* last) {\n while (open_upvalues_ != nullptr && open_upvalues_->value() >= last) {\n UpvalueObject* upvalue = open_upvalues_;\n upvalue->set_closed(upvalue->value_asref());\n upvalue->set_value(upvalue->closed_asptr());\n\n open_upvalues_ = upvalue->next();\n }\n}\n\nInterpretRet VM::run() {\n CallFrame* frame = &frames_.back();\n\n#define _RDBYTE() frame->inc_ip()\n#define _RDCONST() frame->frame_chunk()->get_constant(_RDBYTE())\n#define _RDSTR() _RDCONST().as_string()\n#define _RDCSTR() _RDCONST().as_cstring()\n#define _BINOP(op) do {\\\n if (!peek(0).is_numeric() || !peek(1).is_numeric()) {\\\n runtime_error(\"operands must be two numerics\");\\\n return InterpretRet::ERUNTIME;\\\n }\\\n double b = pop().as_numeric();\\\n double a = pop().as_numeric();\\\n push(a op b);\\\n } while (false)\n\n for (;;) {\n#if defined(_TADPOLE_DEBUG_VM)\n auto* frame_chunk = frame->frame_chunk();\n std::cout << \" \";\n for (auto& v : stack_)\n std::cout << \"[\" << v << \"]\";\n std::cout << std::endl;\n frame_chunk->dis_code(frame_chunk->offset(frame->ip()));\n#endif\n\n switch (Code c = as_type<Code>(_RDBYTE())) {\n case Code::CONSTANT: push(_RDCONST()); break;\n case Code::NIL: push(nullptr); break;\n case Code::FALSE: push(false); break;\n case Code::TRUE: push(true); break;\n case Code::POP: pop(); break;\n case Code::DEF_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n runtime_error(\"name `%s` is redefined\", name);\n return InterpretRet::ERUNTIME;\n }\n else {\n globals_[name] = pop();\n }\n } break;\n case Code::GET_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n push(it->second);\n }\n else {\n runtime_error(\"name `%s` is not defined\", name);\n return InterpretRet::ERUNTIME;\n }\n } break;\n case Code::SET_GLOBAL:\n {\n const char* name = _RDCSTR();\n if (auto it = globals_.find(name); it != globals_.end()) {\n it->second = peek();\n }\n else {\n runtime_error(\"name `%s` is not defined\", name);\n return InterpretRet::ERUNTIME;\n }\n } break;\n case Code::GET_LOCAL: push(stack_[frame->stack_begpos() + _RDBYTE()]); break;\n case Code::SET_LOCAL: stack_[frame->stack_begpos() + _RDBYTE()] = peek(); break;\n case Code::GET_UPVALUE:\n {\n u8_t slot = _RDBYTE();\n push(frame->closure()->get_upvalue(slot)->value_asref());\n } break;\n case Code::SET_UPVALUE:\n {\n u8_t slot = _RDBYTE();\n frame->closure()->get_upvalue(slot)->set_value(peek());\n } break;\n case Code::ADD:\n {\n if (peek(0).is_string() && peek(1).is_string()) {\n StringObject* b = peek(0).as_string();\n StringObject* a = peek(1).as_string();\n StringObject* s = StringObject::concat(*this, a, b);\n pop();\n pop();\n push(s);\n }\n else if (peek(0).is_numeric() && peek(1).is_numeric()) {\n double b = pop().as_numeric();\n double a = pop().as_numeric();\n push(a + b);\n }\n else {\n runtime_error(\"operands must be two strings or two numerics\");\n return InterpretRet::ERUNTIME;\n }\n } break;\n case Code::SUB: _BINOP(-); break;\n case Code::MUL: _BINOP(*); break;\n case Code::DIV: _BINOP(\/); break;\n }\n }\n\n#undef _BINOP\n#undef _RDCSTR\n#undef _RDSTR\n#undef _RDCONST\n#undef _RDBYTE\n\n return InterpretRet::OK;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_CONSTANT_MACROS\n\n#include <cstdlib>\n#include <cstdio>\n\n#include \"monarch\/app\/App.h\"\n#include \"monarch\/app\/AppPluginFactory.h\"\n#include \"monarch\/app\/ConfigPlugin.h\"\n#include \"monarch\/app\/LoggingPlugin.h\"\n#include \"monarch\/app\/MonarchPlugin.h\"\n#include \"monarch\/app\/KernelPlugin.h\"\n#include \"monarch\/data\/json\/JsonWriter.h\"\n#include \"monarch\/event\/EventWaiter.h\"\n#include \"monarch\/logging\/Logging.h\"\n\n#include \"monarch\/app\/KernelPlugin.h\"\n\nusing namespace std;\nusing namespace monarch::app;\nusing namespace monarch::config;\nusing namespace monarch::data::json;\nusing namespace monarch::event;\nusing namespace monarch::fiber;\nusing namespace monarch::io;\nusing namespace monarch::kernel;\nusing namespace monarch::logging;\nusing namespace monarch::modest;\nusing namespace monarch::net;\nusing namespace monarch::rt;\n\n#define PLUGIN_NAME \"monarch.app.Kernel\"\n#define PLUGIN_CL_CFG_ID PLUGIN_NAME \".commandLine\"\n\n\nKernelPlugin::KernelPlugin() :\n mState(Stopped),\n mKernel(NULL)\n{\n}\n\nKernelPlugin::~KernelPlugin()\n{\n}\n\nbool KernelPlugin::initMetaConfig(Config& meta)\n{\n bool rval = monarch::app::AppPlugin::initMetaConfig(meta);\n\n \/\/ defaults\n if(rval)\n {\n Config& c =\n App::makeMetaConfig(meta, PLUGIN_NAME \".defaults\", \"defaults\")\n [ConfigManager::MERGE][PLUGIN_NAME];\n \/\/ modulePath is a map of arrays\n \/\/ Keys are unique per module path source to allow for configured other\n \/\/ lists of paths. Values are arrays of files or dirs to load.\n c[\"modulePath\"]->setType(Map);\n c[\"env\"] = true;\n c[\"printModuleVersions\"] = false;\n c[\"maxThreadCount\"] = UINT32_C(100);\n c[\"maxConnectionCount\"] = UINT32_C(100);\n \/\/ waitEvents is a map of arrays of event ids. The map keys should be\n \/\/ unique such as plugin ids. The kernel will wait for all these events\n \/\/ to occur before exiting. (Some special kernel events also can cause\n \/\/ a quicker exit.)\n c[\"waitEvents\"]->setType(Map);\n }\n\n \/\/ command line options\n if(rval)\n {\n Config& c = App::makeMetaConfig(\n meta, PLUGIN_CL_CFG_ID, \"command line\", \"options\")\n [ConfigManager::MERGE][PLUGIN_NAME];\n c[\"modulePath\"][PLUGIN_CL_CFG_ID]->setType(Array);\n }\n\n return rval;\n}\n\nDynamicObject KernelPlugin::getCommandLineSpecs()\n{\n DynamicObject spec;\n spec[\"help\"] =\n\"Module options:\\n\"\n\" -m, --module-path PATH\\n\"\n\" A colon separated list of module files, directories of\\n\"\n\" modules, y list where extension modules\\n\"\n\" are stored. May be specified multiple times.\\n\"\n\" Loaded after modules in MONARCH_MODULE_PATH.\\n\"\n\" --no-module-path-env\\n\"\n\" Disable MONARCH_MODULE_PATH.\\n\"\n\" --module-versions\\n\"\n\" Prints the module versions.\\n\"\n\"\\n\";\n\n DynamicObject opt;\n Config& options = getApp()->getMetaConfig()\n [\"options\"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE];\n Config& configOptions = options[PLUGIN_NAME];\n\n opt = spec[\"options\"]->append();\n opt[\"short\"] = \"-m\";\n opt[\"long\"] = \"--module-path\";\n opt[\"append\"] = configOptions[\"modulePath\"][PLUGIN_CL_CFG_ID];\n opt[\"argError\"] = \"No path specified.\";\n\n opt = spec[\"options\"]->append();\n opt[\"long\"] = \"--no-module-path-env\";\n opt[\"setFalse\"][\"root\"] = configOptions;\n opt[\"setFalse\"][\"path\"] = \"env\";\n\n opt = spec[\"options\"]->append();\n opt[\"long\"] = \"--module-versions\";\n opt[\"setTrue\"][\"root\"] = configOptions;\n opt[\"setTrue\"][\"path\"] = \"printModuleVersions\";\n\n DynamicObject specs = AppPlugin::getCommandLineSpecs();\n specs->append(spec);\n return specs;\n}\n\nbool KernelPlugin::didParseCommandLine()\n{\n bool rval = AppPlugin::didParseCommandLine();\n\n \/\/ process flags\n \/\/ only done after bootstrap mode so that all modules info is available\n if(rval && getApp()->getMode() != App::BOOTSTRAP)\n {\n Config& cfg = getApp()->getMetaConfig()\n [\"options\"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE][PLUGIN_NAME];\n\n if(cfg[\"printModuleVersions\"]->getBoolean())\n {\n \/\/ FIXME: print out module info\n \/*\n printf(\"%s v%s\\n\", ...);\n \/\/ Raise known exit exception.\n ExceptionRef e = new Exception(\n \"Module versions printed.\",\n \"monarch.app.Exit\", EXIT_SUCCESS);\n Exception::set(e);\n rval = false;\n *\/\n ExceptionRef e = new Exception(\n \"Not implemented.\",\n \"monarch.app.NotImplemented\", EXIT_FAILURE);\n Exception::set(e);\n rval = false;\n }\n }\n\n return rval;\n}\n\nbool KernelPlugin::runApp()\n{\n bool rval = true;\n\n mState = Starting;\n while(mState == Starting || mState == Restarting)\n {\n \/\/ [re]start the node\n MO_CAT_INFO(MO_KERNEL_CAT,\n (mState == Restarting) ?\n \"Restarting kernel...\" : \"Starting kernel...\");\n\n \/\/ get kernel config\n Config cfg = getApp()->getConfig()[PLUGIN_NAME];\n App* app = new App;\n\n \/\/ create and start kernel\n mKernel = new MicroKernel();\n mKernel->setConfigManager(app->getConfigManager(), false);\n mKernel->setFiberScheduler(new FiberScheduler(), true);\n mKernel->setFiberMessageCenter(new FiberMessageCenter(), true);\n mKernel->setEventController(new EventController(), true);\n mKernel->setEventDaemon(new EventDaemon(), true);\n mKernel->setServer(new Server(), true);\n\n \/\/ set thread and connection limits\n mKernel->setMaxAuxiliaryThreads(cfg[\"maxThreadCount\"]->getUInt32());\n mKernel->setMaxServerConnections(cfg[\"maxConnectionCount\"]->getUInt32());\n\n rval = mKernel->start();\n if(rval)\n {\n rval =\n mKernel->loadModule(\n createMonarchPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createConfigPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createLoggingPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createKernelPluginFactory, freeAppPluginFactory);\n\n \/\/ FIXME: in did load configs should add env paths to config\n\n \/\/ Collect all module paths so they can be loaded in bulk.\n \/\/ This helps to avoid issues with needing to specify load order\n \/\/ explicitly.\n FileList modulePaths;\n ConfigIterator mpMods = cfg[\"modulePath\"].getIterator();\n while(rval && mpMods->hasNext())\n {\n ConfigIterator mpPaths = mpMods->next().getIterator();\n while(rval && mpPaths->hasNext())\n {\n const char* path = mpPaths->next()->getString();\n FileList pathList = File::parsePath(path);\n modulePaths->concat(*pathList);\n }\n }\n \/\/ load all module paths at once\n rval = mKernel->loadModules(modulePaths);\n\n if(!rval)\n {\n MO_CAT_INFO(MO_KERNEL_CAT, \"Stopping kernel due to exception.\");\n mKernel->stop();\n }\n }\n mState = Running;\n\n if(rval)\n {\n MO_CAT_INFO(MO_KERNEL_CAT, \"Kernel started.\");\n\n \/\/ send ready event\n {\n Event e;\n e[\"type\"] = \"monarch.kernel.Kernel.ready\";\n mKernel->getEventController()->schedule(e);\n }\n\n if(rval)\n {\n {\n \/\/ create AppPlugins from all loaded AppPluginFactories\n MicroKernel::ModuleApiList factories;\n mKernel->getModuleApisByType(\n \"monarch.app.AppPluginFactory\", factories);\n for(MicroKernel::ModuleApiList::iterator i = factories.begin();\n rval && i != factories.end(); i++)\n {\n ModuleId id = dynamic_cast<Module*>(*i)->getId();\n AppPluginFactory* f = dynamic_cast<AppPluginFactory*>(*i);\n AppPluginRef p = f->createAppPlugin();\n MO_CAT_OBJECT_INFO(\n MO_KERNEL_CAT, app,\n \"Adding AppPlugin to App: %s v%s.\", id.name, id.version);\n rval = app->addPlugin(p);\n }\n }\n\n \/\/ waiter for kernel and plugin events\n \/\/ used to wait for plugins to complete or for kernel control events\n EventWaiter waiter(mKernel->getEventController());\n \/\/ wait for generic kernel events\n waiter.start(\"monarch.kernel.Kernel.shutdown\");\n waiter.start(\"monarch.kernel.Kernel.restart\");\n\n \/\/ collect event counts and start waiting for them\n \/\/ make a map of event ids to a counter\n DynamicObject waitEvents;\n waitEvents->setType(Map);\n \/\/ get the event config\n {\n \/\/ map of arrays of event ids\n Config cfgWaitEvents =\n getApp()->getConfig()[PLUGIN_NAME][\"waitEvents\"];\n DynamicObjectIterator i = cfgWaitEvents.getIterator();\n while(i->hasNext())\n {\n DynamicObjectIterator ii = i->next().getIterator();\n while(ii->hasNext())\n {\n const char* type = i->next()->getString();\n uint32_t count = 1;\n if(waitEvents->hasMember(type))\n {\n count += waitEvents[type]->getUInt32();\n }\n waitEvents[type] = count;\n \/\/ first time seeing event, start waiting for it\n if(count == 1)\n {\n waiter.start(type);\n }\n }\n }\n }\n\n int status;\n if(rval)\n {\n \/\/ run sub app\n status = app->start(getApp()->getCommandLine());\n rval = (status == EXIT_SUCCESS);\n }\n\n \/\/ wait for events if app started successfully\n \/\/ checking for exception in case of success with an exit exception\n if(rval && !Exception::isSet())\n {\n while(mState == Running && waitEvents->length() != 0)\n {\n waiter.waitForEvent();\n Event e = waiter.popEvent();\n const char* type = e[\"type\"]->getString();\n MO_CAT_INFO(MO_KERNEL_CAT,\n \"EventWaiter got event: %s\", type);\n if(strcmp(\"monarch.kernel.Kernel.shutdown\", type) == 0)\n {\n mState = Stopping;\n }\n else if(strcmp(\"monarch.kernel.Kernel.restart\", type) == 0)\n {\n mState = Restarting;\n }\n else\n {\n if(waitEvents->hasMember(type))\n {\n uint32_t count = waitEvents[type]->getUInt32();\n count--;\n if(count == 0)\n {\n waitEvents->removeMember(type);\n }\n else\n {\n waitEvents[type] = count;\n }\n }\n }\n }\n mState = Stopping;\n }\n\n if(!rval)\n {\n getApp()->setExitStatus(app->getExitStatus());\n }\n }\n\n delete app;\n app = NULL;\n\n \/\/ FIXME: actually stopping microkernel, not just node\n \/\/ stop node\n MO_CAT_INFO(MO_KERNEL_CAT,\n (mState == Restarting) ?\n \"Stopping kernel for restart...\" :\n \"Stopping kernel...\");\n mKernel->stop();\n MO_CAT_INFO(MO_KERNEL_CAT, \"Kernel stopped.\");\n \/\/ set to stopped unless restarting\n mState = (mState == Stopping) ? Stopped : mState;\n }\n else\n {\n MO_CAT_ERROR(MO_KERNEL_CAT, \"Kernel start failed: %s\",\n JsonWriter::writeToString(Exception::getAsDynamicObject()).c_str());\n }\n\n if(app != NULL)\n {\n delete app;\n app = NULL;\n }\n\n \/\/ clean up kernel\n delete mKernel;\n mKernel = NULL;\n }\n\n return rval;\n}\n\nbool KernelPlugin::run()\n{\n bool rval = AppPlugin::run();\n if(rval && getApp()->getMode() == App::BOOTSTRAP)\n {\n rval = runApp();\n }\n return rval;\n}\n\nclass KernelPluginFactory :\n public AppPluginFactory\n{\npublic:\n KernelPluginFactory() :\n AppPluginFactory(PLUGIN_NAME, \"1.0\")\n {\n addDependency(\"monarch.app.Config\", \"1.0\");\n addDependency(\"monarch.app.Logging\", \"1.0\");\n }\n\n virtual ~KernelPluginFactory() {}\n\n virtual AppPluginRef createAppPlugin()\n {\n return new KernelPlugin();\n }\n};\n\nModule* monarch::app::createKernelPluginFactory()\n{\n return new KernelPluginFactory();\n}\n<commit_msg>Fix typos and text of command line option help.<commit_after>\/*\n * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_CONSTANT_MACROS\n\n#include <cstdlib>\n#include <cstdio>\n\n#include \"monarch\/app\/App.h\"\n#include \"monarch\/app\/AppPluginFactory.h\"\n#include \"monarch\/app\/ConfigPlugin.h\"\n#include \"monarch\/app\/LoggingPlugin.h\"\n#include \"monarch\/app\/MonarchPlugin.h\"\n#include \"monarch\/app\/KernelPlugin.h\"\n#include \"monarch\/data\/json\/JsonWriter.h\"\n#include \"monarch\/event\/EventWaiter.h\"\n#include \"monarch\/logging\/Logging.h\"\n\n#include \"monarch\/app\/KernelPlugin.h\"\n\nusing namespace std;\nusing namespace monarch::app;\nusing namespace monarch::config;\nusing namespace monarch::data::json;\nusing namespace monarch::event;\nusing namespace monarch::fiber;\nusing namespace monarch::io;\nusing namespace monarch::kernel;\nusing namespace monarch::logging;\nusing namespace monarch::modest;\nusing namespace monarch::net;\nusing namespace monarch::rt;\n\n#define PLUGIN_NAME \"monarch.app.Kernel\"\n#define PLUGIN_CL_CFG_ID PLUGIN_NAME \".commandLine\"\n\n\nKernelPlugin::KernelPlugin() :\n mState(Stopped),\n mKernel(NULL)\n{\n}\n\nKernelPlugin::~KernelPlugin()\n{\n}\n\nbool KernelPlugin::initMetaConfig(Config& meta)\n{\n bool rval = monarch::app::AppPlugin::initMetaConfig(meta);\n\n \/\/ defaults\n if(rval)\n {\n Config& c =\n App::makeMetaConfig(meta, PLUGIN_NAME \".defaults\", \"defaults\")\n [ConfigManager::MERGE][PLUGIN_NAME];\n \/\/ modulePath is a map of arrays\n \/\/ Keys are unique per module path source to allow for configured other\n \/\/ lists of paths. Values are arrays of files or dirs to load.\n c[\"modulePath\"]->setType(Map);\n c[\"env\"] = true;\n c[\"printModuleVersions\"] = false;\n c[\"maxThreadCount\"] = UINT32_C(100);\n c[\"maxConnectionCount\"] = UINT32_C(100);\n \/\/ waitEvents is a map of arrays of event ids. The map keys should be\n \/\/ unique such as plugin ids. The kernel will wait for all these events\n \/\/ to occur before exiting. (Some special kernel events also can cause\n \/\/ a quicker exit.)\n c[\"waitEvents\"]->setType(Map);\n }\n\n \/\/ command line options\n if(rval)\n {\n Config& c = App::makeMetaConfig(\n meta, PLUGIN_CL_CFG_ID, \"command line\", \"options\")\n [ConfigManager::MERGE][PLUGIN_NAME];\n c[\"modulePath\"][PLUGIN_CL_CFG_ID]->setType(Array);\n }\n\n return rval;\n}\n\nDynamicObject KernelPlugin::getCommandLineSpecs()\n{\n DynamicObject spec;\n spec[\"help\"] =\n\"Module options:\\n\"\n\" -m, --module-path PATH\\n\"\n\" A colon separated list of modules or directories where\\n\"\n\" modules are stored. May be specified multiple times.\\n\"\n\" Loaded after modules in MONARCH_MODULE_PATH.\\n\"\n\" --no-module-path-env\\n\"\n\" Disable MONARCH_MODULE_PATH.\\n\"\n\" --module-versions\\n\"\n\" Prints the module versions.\\n\"\n\"\\n\";\n\n DynamicObject opt;\n Config& options = getApp()->getMetaConfig()\n [\"options\"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE];\n Config& configOptions = options[PLUGIN_NAME];\n\n opt = spec[\"options\"]->append();\n opt[\"short\"] = \"-m\";\n opt[\"long\"] = \"--module-path\";\n opt[\"append\"] = configOptions[\"modulePath\"][PLUGIN_CL_CFG_ID];\n opt[\"argError\"] = \"No path specified.\";\n\n opt = spec[\"options\"]->append();\n opt[\"long\"] = \"--no-module-path-env\";\n opt[\"setFalse\"][\"root\"] = configOptions;\n opt[\"setFalse\"][\"path\"] = \"env\";\n\n opt = spec[\"options\"]->append();\n opt[\"long\"] = \"--module-versions\";\n opt[\"setTrue\"][\"root\"] = configOptions;\n opt[\"setTrue\"][\"path\"] = \"printModuleVersions\";\n\n DynamicObject specs = AppPlugin::getCommandLineSpecs();\n specs->append(spec);\n return specs;\n}\n\nbool KernelPlugin::didParseCommandLine()\n{\n bool rval = AppPlugin::didParseCommandLine();\n\n \/\/ process flags\n \/\/ only done after bootstrap mode so that all modules info is available\n if(rval && getApp()->getMode() != App::BOOTSTRAP)\n {\n Config& cfg = getApp()->getMetaConfig()\n [\"options\"][PLUGIN_CL_CFG_ID][ConfigManager::MERGE][PLUGIN_NAME];\n\n if(cfg[\"printModuleVersions\"]->getBoolean())\n {\n \/\/ FIXME: print out module info\n \/*\n printf(\"%s v%s\\n\", ...);\n \/\/ Raise known exit exception.\n ExceptionRef e = new Exception(\n \"Module versions printed.\",\n \"monarch.app.Exit\", EXIT_SUCCESS);\n Exception::set(e);\n rval = false;\n *\/\n ExceptionRef e = new Exception(\n \"Not implemented.\",\n \"monarch.app.NotImplemented\", EXIT_FAILURE);\n Exception::set(e);\n rval = false;\n }\n }\n\n return rval;\n}\n\nbool KernelPlugin::runApp()\n{\n bool rval = true;\n\n mState = Starting;\n while(mState == Starting || mState == Restarting)\n {\n \/\/ [re]start the node\n MO_CAT_INFO(MO_KERNEL_CAT,\n (mState == Restarting) ?\n \"Restarting kernel...\" : \"Starting kernel...\");\n\n \/\/ get kernel config\n Config cfg = getApp()->getConfig()[PLUGIN_NAME];\n App* app = new App;\n\n \/\/ create and start kernel\n mKernel = new MicroKernel();\n mKernel->setConfigManager(app->getConfigManager(), false);\n mKernel->setFiberScheduler(new FiberScheduler(), true);\n mKernel->setFiberMessageCenter(new FiberMessageCenter(), true);\n mKernel->setEventController(new EventController(), true);\n mKernel->setEventDaemon(new EventDaemon(), true);\n mKernel->setServer(new Server(), true);\n\n \/\/ set thread and connection limits\n mKernel->setMaxAuxiliaryThreads(cfg[\"maxThreadCount\"]->getUInt32());\n mKernel->setMaxServerConnections(cfg[\"maxConnectionCount\"]->getUInt32());\n\n rval = mKernel->start();\n if(rval)\n {\n rval =\n mKernel->loadModule(\n createMonarchPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createConfigPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createLoggingPluginFactory, freeAppPluginFactory) &&\n mKernel->loadModule(\n createKernelPluginFactory, freeAppPluginFactory);\n\n \/\/ FIXME: in did load configs should add env paths to config\n\n \/\/ Collect all module paths so they can be loaded in bulk.\n \/\/ This helps to avoid issues with needing to specify load order\n \/\/ explicitly.\n FileList modulePaths;\n ConfigIterator mpMods = cfg[\"modulePath\"].getIterator();\n while(rval && mpMods->hasNext())\n {\n ConfigIterator mpPaths = mpMods->next().getIterator();\n while(rval && mpPaths->hasNext())\n {\n const char* path = mpPaths->next()->getString();\n FileList pathList = File::parsePath(path);\n modulePaths->concat(*pathList);\n }\n }\n \/\/ load all module paths at once\n rval = mKernel->loadModules(modulePaths);\n\n if(!rval)\n {\n MO_CAT_INFO(MO_KERNEL_CAT, \"Stopping kernel due to exception.\");\n mKernel->stop();\n }\n }\n mState = Running;\n\n if(rval)\n {\n MO_CAT_INFO(MO_KERNEL_CAT, \"Kernel started.\");\n\n \/\/ send ready event\n {\n Event e;\n e[\"type\"] = \"monarch.kernel.Kernel.ready\";\n mKernel->getEventController()->schedule(e);\n }\n\n if(rval)\n {\n {\n \/\/ create AppPlugins from all loaded AppPluginFactories\n MicroKernel::ModuleApiList factories;\n mKernel->getModuleApisByType(\n \"monarch.app.AppPluginFactory\", factories);\n for(MicroKernel::ModuleApiList::iterator i = factories.begin();\n rval && i != factories.end(); i++)\n {\n ModuleId id = dynamic_cast<Module*>(*i)->getId();\n AppPluginFactory* f = dynamic_cast<AppPluginFactory*>(*i);\n AppPluginRef p = f->createAppPlugin();\n MO_CAT_OBJECT_INFO(\n MO_KERNEL_CAT, app,\n \"Adding AppPlugin to App: %s v%s.\", id.name, id.version);\n rval = app->addPlugin(p);\n }\n }\n\n \/\/ waiter for kernel and plugin events\n \/\/ used to wait for plugins to complete or for kernel control events\n EventWaiter waiter(mKernel->getEventController());\n \/\/ wait for generic kernel events\n waiter.start(\"monarch.kernel.Kernel.shutdown\");\n waiter.start(\"monarch.kernel.Kernel.restart\");\n\n \/\/ collect event counts and start waiting for them\n \/\/ make a map of event ids to a counter\n DynamicObject waitEvents;\n waitEvents->setType(Map);\n \/\/ get the event config\n {\n \/\/ map of arrays of event ids\n Config cfgWaitEvents =\n getApp()->getConfig()[PLUGIN_NAME][\"waitEvents\"];\n DynamicObjectIterator i = cfgWaitEvents.getIterator();\n while(i->hasNext())\n {\n DynamicObjectIterator ii = i->next().getIterator();\n while(ii->hasNext())\n {\n const char* type = i->next()->getString();\n uint32_t count = 1;\n if(waitEvents->hasMember(type))\n {\n count += waitEvents[type]->getUInt32();\n }\n waitEvents[type] = count;\n \/\/ first time seeing event, start waiting for it\n if(count == 1)\n {\n waiter.start(type);\n }\n }\n }\n }\n\n int status;\n if(rval)\n {\n \/\/ run sub app\n status = app->start(getApp()->getCommandLine());\n rval = (status == EXIT_SUCCESS);\n }\n\n \/\/ wait for events if app started successfully\n \/\/ checking for exception in case of success with an exit exception\n if(rval && !Exception::isSet())\n {\n while(mState == Running && waitEvents->length() != 0)\n {\n waiter.waitForEvent();\n Event e = waiter.popEvent();\n const char* type = e[\"type\"]->getString();\n MO_CAT_INFO(MO_KERNEL_CAT,\n \"EventWaiter got event: %s\", type);\n if(strcmp(\"monarch.kernel.Kernel.shutdown\", type) == 0)\n {\n mState = Stopping;\n }\n else if(strcmp(\"monarch.kernel.Kernel.restart\", type) == 0)\n {\n mState = Restarting;\n }\n else\n {\n if(waitEvents->hasMember(type))\n {\n uint32_t count = waitEvents[type]->getUInt32();\n count--;\n if(count == 0)\n {\n waitEvents->removeMember(type);\n }\n else\n {\n waitEvents[type] = count;\n }\n }\n }\n }\n mState = Stopping;\n }\n\n if(!rval)\n {\n getApp()->setExitStatus(app->getExitStatus());\n }\n }\n\n delete app;\n app = NULL;\n\n \/\/ FIXME: actually stopping microkernel, not just node\n \/\/ stop node\n MO_CAT_INFO(MO_KERNEL_CAT,\n (mState == Restarting) ?\n \"Stopping kernel for restart...\" :\n \"Stopping kernel...\");\n mKernel->stop();\n MO_CAT_INFO(MO_KERNEL_CAT, \"Kernel stopped.\");\n \/\/ set to stopped unless restarting\n mState = (mState == Stopping) ? Stopped : mState;\n }\n else\n {\n MO_CAT_ERROR(MO_KERNEL_CAT, \"Kernel start failed: %s\",\n JsonWriter::writeToString(Exception::getAsDynamicObject()).c_str());\n }\n\n if(app != NULL)\n {\n delete app;\n app = NULL;\n }\n\n \/\/ clean up kernel\n delete mKernel;\n mKernel = NULL;\n }\n\n return rval;\n}\n\nbool KernelPlugin::run()\n{\n bool rval = AppPlugin::run();\n if(rval && getApp()->getMode() == App::BOOTSTRAP)\n {\n rval = runApp();\n }\n return rval;\n}\n\nclass KernelPluginFactory :\n public AppPluginFactory\n{\npublic:\n KernelPluginFactory() :\n AppPluginFactory(PLUGIN_NAME, \"1.0\")\n {\n addDependency(\"monarch.app.Config\", \"1.0\");\n addDependency(\"monarch.app.Logging\", \"1.0\");\n }\n\n virtual ~KernelPluginFactory() {}\n\n virtual AppPluginRef createAppPlugin()\n {\n return new KernelPlugin();\n }\n};\n\nModule* monarch::app::createKernelPluginFactory()\n{\n return new KernelPluginFactory();\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file Subfields.cc\n * \\brief Implementation of the Subfields class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2014 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"Subfields.h\"\n#include <stdexcept>\n#include \"Compiler.h\"\n#include \"util.h\"\n\n\nSubfields::Subfields(const std::string &field_data) {\n if (field_data.size() < 3) {\n indicator1_ = indicator2_ = '\\0';\n return;\n }\n\n std::string::const_iterator ch(field_data.begin());\n indicator1_ = *ch++;\n indicator2_ = *ch++;\n\n while (ch != field_data.end()) {\n if (*ch != '\\x1F')\n std::runtime_error(\n \"in Subfields::Subfields(const std::string &): expected subfield code delimiter not found! \"\n \"Found \" + std::string(1, *ch) + \" in \" + field_data + \" indicators: \"\n + std::string(1, indicator1_) + \", \" + std::string(1, indicator2_) + \"! \" + field_data);\n\n ++ch;\n if (ch == field_data.end())\n std::runtime_error(\n \"in Subfields::Subfields(const std::string &): unexpected subfield data end while expecting \"\n \"a subfield code! \" + field_data);\n const char subfield_code = *ch++;\n\n std::string subfield_data;\n while (ch != field_data.end() and *ch != '\\x1F')\n subfield_data += *ch++;\n if (not subfield_data.empty())\n subfields_.emplace_back(subfield_code, subfield_data);\n }\n\n std::sort(begin(), end(), SubfieldCodeLessThan());\n}\n\n\nbool Subfields::hasSubfieldWithValue(const char subfield_code, const std::string &value) const {\n auto code_and_value(std::find_if(begin(), end(), CompareSubfieldCode(subfield_code)));\n for (\/* empty *\/; code_and_value != end() && code_and_value->code_ == subfield_code; ++code_and_value) {\n if (code_and_value->value_ == value)\n return true;\n }\n return false;\n}\n\n\nstd::string Subfields::getFirstSubfieldValue(const char subfield_code) const {\n const auto begin_end(getIterators(subfield_code));\n if (begin_end.first == begin_end.second)\n return \"\";\n return begin_end.first->value_;\n}\n\n\nvoid Subfields::addSubfield(const char subfield_code, const std::string &subfield_data) {\n auto insert(begin());\n for (\/* empty *\/; insert != end() && insert->code_ <= subfield_code; ++insert);\n subfields_.emplace(insert, subfield_code, subfield_data);\n}\n\n\nvoid Subfields::replace(const char subfield_code, const std::string &old_value, const std::string &new_value) {\n bool found(false);\n\n const auto begin_end(getIterators(subfield_code));\n for (auto code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value) {\n if (code_and_value->value_ == old_value) {\n found = true;\n code_and_value->value_ = new_value;\n }\n }\n\n if (not found)\n throw std::runtime_error(\n \"Subfields::replace: tried to replace \\\"\" + old_value + \"\\\" with \\\"\" + new_value + \"\\\" in subfield '\"\n + subfield_code + \"' but did not find the original value!\");\n}\n\n\nvoid Subfields::erase(const char subfield_code) {\n const auto begin_end(getIterators(subfield_code));\n subfields_.erase(begin_end.first, begin_end.second);\n}\n\n\nvoid Subfields::erase(const char subfield_code, const std::string &value) {\n auto code_and_value(std::find_if(begin(), end(), CompareSubfieldCode(subfield_code)));\n while (code_and_value != end() and code_and_value->code_ == subfield_code) {\n if (code_and_value->value_ == value)\n code_and_value = subfields_.erase(code_and_value);\n else\n ++code_and_value;\n }\n}\n\n\nvoid Subfields::moveSubfield(const char from_subfield_code, const char to_subfield_code) {\n erase(to_subfield_code);\n std::vector <std::string> values;\n extractSubfields(from_subfield_code, &values);\n for (auto value : values)\n subfields_.emplace_back(to_subfield_code, value);\n erase(from_subfield_code);\n std::sort(begin(), end(), SubfieldCodeLessThan());\n}\n\n\nsize_t Subfields::extractSubfields(const std::string &subfield_codes,\n std::vector <std::string> *const subfield_values) const {\n for (char subfield_code : subfield_codes) {\n extractSubfields(subfield_code, subfield_values);\n }\n return subfield_values->size();\n}\n\nvoid Subfields::extractSubfields(const char subfield_code, std::vector <std::string> *const subfield_values) const {\n const auto begin_end(getIterators(subfield_code));\n for (auto code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value)\n subfield_values->emplace_back(code_and_value->value_);\n}\n\n\nstd::string Subfields::toString() const {\n std::string as_string;\n\n as_string += indicator1_;\n as_string += indicator2_;\n\n for (const_iterator code_and_value(cbegin()); code_and_value != cend(); ++code_and_value) {\n as_string += '\\x1F';\n as_string += code_and_value->code_;\n as_string += code_and_value->value_;\n }\n\n return as_string;\n}\n<commit_msg>Cosmetic.<commit_after>\/** \\file Subfields.cc\n * \\brief Implementation of the Subfields class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2014,2016 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"Subfields.h\"\n#include <stdexcept>\n#include \"Compiler.h\"\n#include \"util.h\"\n\n\nSubfields::Subfields(const std::string &field_data) {\n if (field_data.size() < 3) {\n indicator1_ = indicator2_ = '\\0';\n return;\n }\n\n std::string::const_iterator ch(field_data.begin());\n indicator1_ = *ch++;\n indicator2_ = *ch++;\n\n while (ch != field_data.end()) {\n if (*ch != '\\x1F')\n std::runtime_error(\n \"in Subfields::Subfields(const std::string &): expected subfield code delimiter not found! \"\n \"Found \" + std::string(1, *ch) + \" in \" + field_data + \" indicators: \"\n + std::string(1, indicator1_) + \", \" + std::string(1, indicator2_) + \"! \" + field_data);\n\n ++ch;\n if (ch == field_data.end())\n std::runtime_error(\n \"in Subfields::Subfields(const std::string &): unexpected subfield data end while expecting \"\n \"a subfield code! \" + field_data);\n const char subfield_code(*ch++);\n\n std::string subfield_data;\n while (ch != field_data.end() and *ch != '\\x1F')\n subfield_data += *ch++;\n if (not subfield_data.empty())\n subfields_.emplace_back(subfield_code, subfield_data);\n }\n\n std::sort(begin(), end(), SubfieldCodeLessThan());\n}\n\n\nbool Subfields::hasSubfieldWithValue(const char subfield_code, const std::string &value) const {\n auto code_and_value(std::find_if(begin(), end(), CompareSubfieldCode(subfield_code)));\n for (\/* empty *\/; code_and_value != end() && code_and_value->code_ == subfield_code; ++code_and_value) {\n if (code_and_value->value_ == value)\n return true;\n }\n return false;\n}\n\n\nstd::string Subfields::getFirstSubfieldValue(const char subfield_code) const {\n const auto begin_end(getIterators(subfield_code));\n if (begin_end.first == begin_end.second)\n return \"\";\n return begin_end.first->value_;\n}\n\n\nvoid Subfields::addSubfield(const char subfield_code, const std::string &subfield_data) {\n auto insert(begin());\n for (\/* empty *\/; insert != end() && insert->code_ <= subfield_code; ++insert);\n subfields_.emplace(insert, subfield_code, subfield_data);\n}\n\n\nvoid Subfields::replace(const char subfield_code, const std::string &old_value, const std::string &new_value) {\n bool found(false);\n\n const auto begin_end(getIterators(subfield_code));\n for (auto code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value) {\n if (code_and_value->value_ == old_value) {\n found = true;\n code_and_value->value_ = new_value;\n }\n }\n\n if (not found)\n throw std::runtime_error(\n \"Subfields::replace: tried to replace \\\"\" + old_value + \"\\\" with \\\"\" + new_value + \"\\\" in subfield '\"\n + subfield_code + \"' but did not find the original value!\");\n}\n\n\nvoid Subfields::erase(const char subfield_code) {\n const auto begin_end(getIterators(subfield_code));\n subfields_.erase(begin_end.first, begin_end.second);\n}\n\n\nvoid Subfields::erase(const char subfield_code, const std::string &value) {\n auto code_and_value(std::find_if(begin(), end(), CompareSubfieldCode(subfield_code)));\n while (code_and_value != end() and code_and_value->code_ == subfield_code) {\n if (code_and_value->value_ == value)\n code_and_value = subfields_.erase(code_and_value);\n else\n ++code_and_value;\n }\n}\n\n\nvoid Subfields::moveSubfield(const char from_subfield_code, const char to_subfield_code) {\n erase(to_subfield_code);\n std::vector <std::string> values;\n extractSubfields(from_subfield_code, &values);\n for (auto value : values)\n subfields_.emplace_back(to_subfield_code, value);\n erase(from_subfield_code);\n std::sort(begin(), end(), SubfieldCodeLessThan());\n}\n\n\nsize_t Subfields::extractSubfields(const std::string &subfield_codes,\n std::vector <std::string> *const subfield_values) const {\n for (char subfield_code : subfield_codes) {\n extractSubfields(subfield_code, subfield_values);\n }\n return subfield_values->size();\n}\n\nvoid Subfields::extractSubfields(const char subfield_code, std::vector <std::string> *const subfield_values) const {\n const auto begin_end(getIterators(subfield_code));\n for (auto code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value)\n subfield_values->emplace_back(code_and_value->value_);\n}\n\n\nstd::string Subfields::toString() const {\n std::string as_string;\n\n as_string += indicator1_;\n as_string += indicator2_;\n\n for (const_iterator code_and_value(cbegin()); code_and_value != cend(); ++code_and_value) {\n as_string += '\\x1F';\n as_string += code_and_value->code_;\n as_string += code_and_value->value_;\n }\n\n return as_string;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"game\/gamestate.h\"\n#include \"game\/city\/city.h\"\n\n#include \"framework\/includes.h\"\n#include \"framework\/framework.h\"\n\nnamespace OpenApoc {\n\nGameState::GameState(Framework &fw, Rules &rules)\n{\n\tfor (auto &orgdef : rules.getOrganisationDefs())\n\t{\n\t\tthis->organisations.emplace_back(orgdef);\n\t}\n\n\tthis->city.reset(new City(fw));\n\t\/\/Place some random testing vehicles\n\tstd::default_random_engine generator;\n\t\/\/FIXME: Read size from city? (Only 'temporary' code anyway)\n\tstd::uniform_int_distribution<int> xydistribution(0,99);\n\t\/\/ Spawn vehicles at the top to avoid creating them in small\n\t\/\/ inescapeable gaps in buildings\n\tstd::uniform_int_distribution<int> zdistribution(8,9);\n\n\tfor (int i = 0; i < 50; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while(!this->city->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tauto vehicleDefIt = fw.rules->getVehicleDefs().find(\"POLICE_HOVERCAR\");\n\t\tif (vehicleDefIt == fw.rules->getVehicleDefs().end())\n\t\t{\n\t\t\tLogError(\"No POLICE_HOVERCAR vehicle def found?\");\n\t\t\treturn;\n\t\t}\n\t\t\/\/Organisations[3] == megapol\n\t\tauto testVehicle = std::make_shared<Vehicle>(vehicleDefIt->second, this->organisations[3]);\n\t\tthis->city->vehicles.push_back(testVehicle);\n\t\ttestVehicle->launch(*this->city, Vec3<float>{x,y,z});\n\t}\n\tfor (int i = 0; i < 50; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while(!this->city->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tauto vehicleDefIt = fw.rules->getVehicleDefs().find(\"PHOENIX_HOVERCAR\");\n\t\tif (vehicleDefIt == fw.rules->getVehicleDefs().end())\n\t\t{\n\t\t\tLogError(\"No PHOENIX_HOVERCAR vehicle def found?\");\n\t\t\treturn;\n\t\t}\n\t\t\/\/Organisations[3] == X-Com\n\t\tauto testVehicle = std::make_shared<Vehicle>(vehicleDefIt->second, this->organisations[0]);\n\t\tthis->city->vehicles.push_back(testVehicle);\n\t\ttestVehicle->launch(*this->city, Vec3<float>{x,y,z});\n\t}\n}\n\n\n}; \/\/namespace OpenApoc\n<commit_msg>Build fix - #include <random><commit_after>#include \"game\/gamestate.h\"\n#include \"game\/city\/city.h\"\n\n#include \"framework\/includes.h\"\n#include \"framework\/framework.h\"\n\n#include <random>\n\nnamespace OpenApoc {\n\nGameState::GameState(Framework &fw, Rules &rules)\n{\n\tfor (auto &orgdef : rules.getOrganisationDefs())\n\t{\n\t\tthis->organisations.emplace_back(orgdef);\n\t}\n\n\tthis->city.reset(new City(fw));\n\t\/\/Place some random testing vehicles\n\tstd::default_random_engine generator;\n\t\/\/FIXME: Read size from city? (Only 'temporary' code anyway)\n\tstd::uniform_int_distribution<int> xydistribution(0,99);\n\t\/\/ Spawn vehicles at the top to avoid creating them in small\n\t\/\/ inescapeable gaps in buildings\n\tstd::uniform_int_distribution<int> zdistribution(8,9);\n\n\tfor (int i = 0; i < 50; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while(!this->city->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tauto vehicleDefIt = fw.rules->getVehicleDefs().find(\"POLICE_HOVERCAR\");\n\t\tif (vehicleDefIt == fw.rules->getVehicleDefs().end())\n\t\t{\n\t\t\tLogError(\"No POLICE_HOVERCAR vehicle def found?\");\n\t\t\treturn;\n\t\t}\n\t\t\/\/Organisations[3] == megapol\n\t\tauto testVehicle = std::make_shared<Vehicle>(vehicleDefIt->second, this->organisations[3]);\n\t\tthis->city->vehicles.push_back(testVehicle);\n\t\ttestVehicle->launch(*this->city, Vec3<float>{x,y,z});\n\t}\n\tfor (int i = 0; i < 50; i++)\n\t{\n\t\tint x = 0;\n\t\tint y = 0;\n\t\tint z = 0;\n\t\tdo {\n\t\t\tx = xydistribution(generator);\n\t\t\ty = xydistribution(generator);\n\t\t\tz = zdistribution(generator);\n\t\t} while(!this->city->getTile(x,y,z)->ownedObjects.empty());\n\n\t\tauto vehicleDefIt = fw.rules->getVehicleDefs().find(\"PHOENIX_HOVERCAR\");\n\t\tif (vehicleDefIt == fw.rules->getVehicleDefs().end())\n\t\t{\n\t\t\tLogError(\"No PHOENIX_HOVERCAR vehicle def found?\");\n\t\t\treturn;\n\t\t}\n\t\t\/\/Organisations[3] == X-Com\n\t\tauto testVehicle = std::make_shared<Vehicle>(vehicleDefIt->second, this->organisations[0]);\n\t\tthis->city->vehicles.push_back(testVehicle);\n\t\ttestVehicle->launch(*this->city, Vec3<float>{x,y,z});\n\t}\n}\n\n\n}; \/\/namespace OpenApoc\n<|endoftext|>"} {"text":"<commit_before>#ifndef MESSAGES_HPP_\n#define MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n static const int ID = 0xFE; \/\/ TODO: Probably make this 0x00\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstd::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<commit_msg>Use enum for message ID to avoid linking errors.<commit_after>#ifndef MESSAGES_HPP_\n#define MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0xFE };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstd::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>#include <SFML\/Graphics.hpp>\n#include <iostream>\n#include \"sfJoystick.h\"\n#include \"sfMouse.h\"\n#include \"sfKeyboard.h\"\n#include \"sfSpriteSheet.h\"\n#include \"GameComponent.h\"\n#include \"Stage.h\"\n#include \"Skin.h\"\n\n#ifdef WIN32\n#include <boost\\asio.hpp>\n#include <Windows.h>\n#endif\n\nextern\tstd::vector<skin>\tskinArray;\nextern\tsfWindow\tsfmlWin;\n\nint main()\n{\n\tfillArray();\n\tISpriteSheet\t*test = new sfSpriteSheet(skinArray[0].filePath, skinArray[0].anim, skinArray[0].frame);\n\tISpriteSheet\t*test2 = new sfSpriteSheet(skinArray[8].filePath, skinArray[8].anim, skinArray[8].frame);\n\tISpriteSheet\t*ships = new sfSpriteSheet(\"..\/Resources\/Sprite\/ennemy_bullet1.gif\", 1, 8);\n\tISpriteSheet\t*boom = new sfSpriteSheet(skinArray[7].filePath, skinArray[7].anim, skinArray[7].frame);\n\tISpriteSheet\t*boom2 = new sfSpriteSheet(\"..\/Resources\/Sprite\/big_death.gif\", 1, 8);\n\tISpriteSheet\t*bing = new sfSpriteSheet(skinArray[9].filePath, skinArray[9].anim, skinArray[9].frame);\n\tISpriteSheet\t*ennemy = new sfSpriteSheet(\"..\/Resources\/Sprite\/ennemy1.gif\", 1, 8);\n\t\n<<<<<<< HEAD\n\t\/\/IInput\t*input3 = new sfKeyboard();\n=======\n\n\tIInput\t*input3 = new sfKeyboard();\n>>>>>>> 317e185242f0b1773191a19a6c54679e66905c46\n\t\/\/IInput\t*input2 = new sfJoystick();\n\tIInput\t*input = new sfMouse();\n\n\t\/*\n\tinput3->autoBind(UpKey, sf::Keyboard::W);\n\tinput3->autoBind(DownKey, sf::Keyboard::S);\n\tinput3->autoBind(LeftKey, sf::Keyboard::A);\n\tinput3->autoBind(RightKey, sf::Keyboard::D);\n\tinput3->autoBind(FireKey, sf::Keyboard::Space);\n\t*\/\n\t\t\n\tGameComponent\t*vaisseau = new GameComponent(test, boom);\n\tGameComponent\t*vaisseau2 = new GameComponent(test2, boom2);\n\tStage st;\n\tst.add(vaisseau);\n\tst.add(vaisseau2);\n\n\tint\ti = 0, o = 1;\n\tvaisseau2->move(5, 0); \n\t\/\/balise copiage de code\n\tsf::Event ev;\n\twhile (sfmlWin.isOpen())\n\t{\n\t\tsfmlWin.pollEvent(ev);\n\t\tif (ev.type == sf::Event::Closed)\n\t\t\tsfmlWin.getWindow().close();\n\t\tSleep(10); \/\/TODO replace par truc utiles genre les packets udp lol\n\t\tint x = 0, y = 0;\n\t\tvaisseau->move(input->getLastInput(UpKey), input->getLastInput(LeftKey));\n\t\t\/\/vaisseau->move(input2->getLastInput(UpKey), input2->getLastInput(LeftKey));\n\t\t\/*if (input3->getLastInput(UpKey))\n\t\t\ty = -4;\n\t\telse if (input3->getLastInput(DownKey))\n\t\t\ty = 4;\n\t\tif (input3->getLastInput(LeftKey))\n\t\t\tx = -4;\n\t\telse if (input3->getLastInput(RightKey))\n\t\t\tx = 4;\n\t\tvaisseau->move(x, y);\n\t\tif (input3->isPressed(FireKey))\n\t\t\tvaisseau->death();\n\t\t*\/\n\t\tst.update();\n\t\tsfmlWin.clear();\n\t\tst.draw();\n\t\tsfmlWin.display();\n\t}\n\t\/\/balise fin copiage de code\n\treturn 0;\n}\n\/*\n#include\t<iostream>\n#include\t\"NetworkManager.hpp\"\n\nint\t\tmain(int ac, char **av)\n{\n if (ac == 3)\n {\n INetworkManager*\tNM = new NetworkManager(av);\n NM->run();\n }\n else\n std::cout << \"Usage : .\/ClientRtype [ip] [port]\" << std::endl;\n}\n*\/<commit_msg>[Clean] Bug merge corrected<commit_after>#include <SFML\/Graphics.hpp>\n#include <iostream>\n#include \"sfJoystick.h\"\n#include \"sfMouse.h\"\n#include \"sfKeyboard.h\"\n#include \"sfSpriteSheet.h\"\n#include \"GameComponent.h\"\n#include \"Stage.h\"\n#include \"Skin.h\"\n\n#ifdef WIN32\n#include <boost\\asio.hpp>\n#include <Windows.h>\n#endif\n\nextern\tstd::vector<skin>\tskinArray;\nextern\tsfWindow\tsfmlWin;\n\nint main()\n{\n\tfillArray();\n\tISpriteSheet\t*test = new sfSpriteSheet(skinArray[0].filePath, skinArray[0].anim, skinArray[0].frame);\n\tISpriteSheet\t*test2 = new sfSpriteSheet(skinArray[8].filePath, skinArray[8].anim, skinArray[8].frame);\n\tISpriteSheet\t*ships = new sfSpriteSheet(\"..\/Resources\/Sprite\/ennemy_bullet1.gif\", 1, 8);\n\tISpriteSheet\t*boom = new sfSpriteSheet(skinArray[7].filePath, skinArray[7].anim, skinArray[7].frame);\n\tISpriteSheet\t*boom2 = new sfSpriteSheet(\"..\/Resources\/Sprite\/big_death.gif\", 1, 8);\n\tISpriteSheet\t*bing = new sfSpriteSheet(skinArray[9].filePath, skinArray[9].anim, skinArray[9].frame);\n\tISpriteSheet\t*ennemy = new sfSpriteSheet(\"..\/Resources\/Sprite\/ennemy1.gif\", 1, 8);\n\t\n\t\/\/IInput\t*input3 = new sfKeyboard();\n\t\/\/IInput\t*input2 = new sfJoystick();\n\tIInput\t*input = new sfMouse();\n\n\t\/*\n\tinput3->autoBind(UpKey, sf::Keyboard::W);\n\tinput3->autoBind(DownKey, sf::Keyboard::S);\n\tinput3->autoBind(LeftKey, sf::Keyboard::A);\n\tinput3->autoBind(RightKey, sf::Keyboard::D);\n\tinput3->autoBind(FireKey, sf::Keyboard::Space);\n\t*\/\n\t\t\n\tGameComponent\t*vaisseau = new GameComponent(test, boom);\n\tGameComponent\t*vaisseau2 = new GameComponent(test2, boom2);\n\tStage st;\n\tst.add(vaisseau);\n\tst.add(vaisseau2);\n\n\tint\ti = 0, o = 1;\n\tvaisseau2->move(5, 0); \n\t\/\/balise copiage de code\n\tsf::Event ev;\n\twhile (sfmlWin.isOpen())\n\t{\n\t\tsfmlWin.pollEvent(ev);\n\t\tif (ev.type == sf::Event::Closed)\n\t\t\tsfmlWin.getWindow().close();\n\t\tSleep(10); \/\/TODO replace par truc utiles genre les packets udp lol\n\t\tint x = 0, y = 0;\n\t\tvaisseau->move(input->getLastInput(UpKey), input->getLastInput(LeftKey));\n\t\t\/\/vaisseau->move(input2->getLastInput(UpKey), input2->getLastInput(LeftKey));\n\t\t\/*if (input3->getLastInput(UpKey))\n\t\t\ty = -4;\n\t\telse if (input3->getLastInput(DownKey))\n\t\t\ty = 4;\n\t\tif (input3->getLastInput(LeftKey))\n\t\t\tx = -4;\n\t\telse if (input3->getLastInput(RightKey))\n\t\t\tx = 4;\n\t\tvaisseau->move(x, y);\n\t\tif (input3->isPressed(FireKey))\n\t\t\tvaisseau->death();\n\t\t*\/\n\t\tst.update();\n\t\tsfmlWin.clear();\n\t\tst.draw();\n\t\tsfmlWin.display();\n\t}\n\t\/\/balise fin copiage de code\n\treturn 0;\n}\n\/*\n#include\t<iostream>\n#include\t\"NetworkManager.hpp\"\n\nint\t\tmain(int ac, char **av)\n{\n if (ac == 3)\n {\n INetworkManager*\tNM = new NetworkManager(av);\n NM->run();\n }\n else\n std::cout << \"Usage : .\/ClientRtype [ip] [port]\" << std::endl;\n}\n*\/<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ macros.hpp\n\/\/\n\/\/ Created By Davis Blalock on 3\/15\/16.\n\/\/ Copyright (c) 2016 Davis Blalock. All rights reserved.\n\/\/\n\n#ifndef __MACROS_HPP\n#define __MACROS_HPP\n\n\/\/ ------------------------ restrict keyword\n\/\/ adapted from http:\/\/stackoverflow.com\/a\/5948101\/1153180\n\n#if defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))\n\t#define RESTRICT __restrict__\n\n\t#define LIKELY(x) __builtin_expect (!!(x), 1)\n\t#define UNLIKELY(x) __builtin_expect (!!(x), 0)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n#elif defined(__clang__)\n\t#define RESTRICT __restrict__\n\n\t#define LIKELY(x) __builtin_expect (!!(x), 1)\n\t#define UNLIKELY(x) __builtin_expect (!!(x), 0)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n#else\n\t#if defined(_MSC_VER) && _MSC_VER >= 1400\n\t\t#define RESTRICT\n\t#else\n\t\t#define RESTRICT __restrict\n\t#endif\n\n\t#define LIKELY(x) (x)\n\t#define UNLIKELY(x) (x)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n\n#endif\n\n\/\/ count the number of arguments in a varargs list\n#define VA_NUM_ARGS(...) _VA_NUM_ARGS_IMPL(__VA_ARGS__, \\\n\t16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)\n#define _VA_NUM_ARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, \\\n\t _13, _14, _15, _16, N, ...) N\n\n#ifdef __cplusplus\n\/\/ ------------------------ type traits macros\n\t#include <type_traits>\n\n\t\/\/ #define SELF_TYPE \\\n\t\/\/ \ttypename std::remove_reference<decltype(*this)>::type\n\n\t\/\/ put these in function bodies to statically assert that appropriate types\n\t\/\/ have been passed in as template params; prefer using the below type\n\t\/\/ constraint macros, however\n\t#define ASSERT_TRAIT(TRAIT, T, MSG) static_assert(std::TRAIT<T>::value, MSG)\n\t#define ASSERT_INTEGRAL(T) ASSERT_TRAIT(is_integral, T, \"Type not integral!\")\n\n\t\/\/ put these as extra template params to enforce constraints\n\t\/\/ on previous template params; e.g.:\n\t\/\/\n\t\/\/ template<class T, REQUIRE_INT(T)> T foo(T arg) { return arg + 1; }\n\t\/\/\n\n\t\/\/ ------------------------ require that some constexpr be true\n\n\t#define REQ(EXPR) \\\n\t\ttypename = typename std::enable_if<EXPR, void>::type\n\n\t\/\/ have to wrap EXPR in a local template param for enable_if to work on\n\t\/\/ a class method where EXPR is a class template param\n\t#define _METHOD_REQ(EXPR, NAME) \\\n\t\tbool NAME = EXPR, typename = typename std::enable_if<NAME, void>::type\n\n\t#define METHOD_REQ0(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr0__)\n\n\t#define METHOD_REQ1(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr1__)\n\n\t#define METHOD_REQ2(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr2__)\n\n\t#define METHOD_REQ3(EXPR) \\\n\t\t_METHOD_REQ3(EXPR, __expr3__)\n\n\t#define METHOD_REQ4(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr4__)\n\n\t#define METHOD_REQ5(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr5__)\n\n\t#define METHOD_REQ6(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr6__)\n\n\t#define METHOD_REQ(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr__)\n\n\t\t\/\/ bool __expr__ = EXPR, typename = typename std::enable_if<__expr__, void>::type\n\n\t\t\/\/ typename = typename std::enable_if<EXPR, T>::type\n\t#define REQUIRE_TRAIT(TRAIT, T) \\\n\t\ttypename = typename std::enable_if<std::TRAIT<T>::value, T>::type\n\n\t#define REQUIRE_NOT_TRAIT(TRAIT, T) \\\n\t\ttypename = typename std::enable_if<!std::TRAIT<T>::value, T>::type\n\n\t#define REQUIRE_IS_A(BASE, T) \\\n\t\ttypename = typename std::enable_if<std::is_base_of<BASE, T>::value, T>::type\n\n\t#define REQUIRE_IS_NOT_A(BASE, T) \\\n\t\ttypename = typename std::enable_if<!std::is_base_of<BASE, T>::value, T>::type\n\n\t\t\/\/ REQ(!std::is_base_of<BASE, T>::value)\n\n\t#define REQUIRE_INT(T) REQUIRE_TRAIT(is_integral, T)\n\t#define REQUIRE_NUM(T) REQUIRE_TRAIT(is_arithmetic, T)\n\t#define REQUIRE_FLOAT(T) REQUIRE_TRAIT(is_floating_point, T)\n\t#define REQUIRE_PRIMITIVE(T) REQUIRE_TRAIT(is_arithmetic, T)\n\t#define REQUIRE_NOT_PTR(T) REQUIRE_NOT_TRAIT(is_pointer, T)\n\n\t#define REQ_HAS_ATTR(T, METHOD_INVOCATION) \\\n\t\ttypename=decltype(std::declval<T>() . METHOD_INVOCATION)\n\n\t\/\/ ------------------------ is_valid; requires C++14\n\t\/\/ inspired by https:\/\/gist.github.com\/Jiwan\/7a586c739a30dd90d259\n\n\ttemplate <typename T> struct _valid_helper {\n\tprivate:\n\t template <typename Param> constexpr auto _is_valid(int _)\n\t\t \/\/ type returned by decltype is last type in the list (here,\n\t\t\t\/\/ std::true_type), but previous types must be valid\n\t \t-> decltype(std::declval<T>()(std::declval<Param>()),\n\t \t\tstd::true_type())\n\t {\n\t return std::true_type();\n\t }\n\n\t template <typename Param> constexpr std::false_type _is_valid(...) {\n\t return std::false_type();\n\t }\n\n\tpublic:\n\t template <typename Param> constexpr auto operator()(const Param& p) {\n\t return _is_valid<Param>(int(0));\n\t }\n\t};\n\n\ttemplate <typename T> constexpr auto is_valid(const T& t) {\n\t return _valid_helper<T>();\n\t}\n\n\t#define CREATE_TEST(OBJNAME, EXPR) \\\n\t\tis_valid([](auto&& OBJNAME) -> decltype(EXPR) { })\n\n\t#define CREATE_TEST_X(EXPR) \\\n\t\tis_valid([](auto&& x) -> decltype(EXPR) { })\n\n\t#define TEST_FOR_METHOD(INVOCATION) \\\n\t\tis_valid([](auto&& x) -> decltype(x. INVOCATION) { })\n\n\t#define PASSES_TEST(OBJ, TEST) \\\n\t\tdecltype(TEST(OBJ))::value\n\n\t#define TYPE_PASSES_TEST(T, TEST) \\\n\t\tPASSES_TEST(std::declval<T>(), TEST)\n\n\t#define REQ_TYPE_PASSES(T, TEST) \\\n\t\tREQ(TYPE_PASSES_TEST(T, TEST))\n\n\t#define ENABLE_IF(EXPR, T) \\\n\t\ttypename std::enable_if<EXPR, T>::type\n\n\n\/\/ ------------------------ TYPES(...) convenience macro for template args\n#define TYPES_1(A) template<typename A>\n#define TYPES_2(A, B) \\\n\ttemplate<typename A, typename B>\n#define TYPES_3(A, B, C) \\\n\ttemplate<typename A, typename B, typename C>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_4(A, B, C, D) \\\n\ttemplate<typename A, typename B, typename C, typename D>\n\t\t\/\/ TYPES_10(A, B, C, D, E=int, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_5(A, B, C, D, E) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_6(A, B, C, D, E, F) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G=int, H=int, I=int, J=int)\n#define TYPES_7(A, B, C, D, E, F, G) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H=int, I=int, J=int)\n#define TYPES_8(A, B, C, D, E, F, G, H) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H, I=int, J=int)\n#define TYPES_9(A, B, C, D, E, F, G, H, I) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H, typename I>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H, I, J=int)\n#define TYPES_10(A, B, C, D, E, F, G, H, I, J) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H, typename I, typename J\n\n\/\/ define a top level TYPES macro that automatically calls the macro with\n\/\/ the proper number of arguments\n\/\/ #define _TYPES_IMPL2(count, ...) TYPES_ ## count (__VA_ARGS__)\n\/\/ #define _TYPES_IMPL(count, ...) _TYPES_IMPL2(count, __VA_ARGS__)\n\/\/ #define TYPES(...) _TYPES_IMPL(VA_NUM_ARGS(__VA_ARGS__), __VA_ARGS__)\n\n\/\/ TODO if this works, get rid of above 3 loc and move outside of cpp block\n#define _WRAP_VARIADIC_IMPL2(name, count, ...) \\\n\t\tname ## count (__VA_ARGS__)\n#define _WRAP_VARIADIC_IMPL(name, count, ...) \\\n\t\t_WRAP_VARIADIC_IMPL2(name, count, __VA_ARGS__)\n#define WRAP_VARIADIC(name, ...) \\\n\t\t_WRAP_VARIADIC_IMPL(name, VA_NUM_ARGS(__VA_ARGS__), __VA_ARGS__)\n\n#define TYPES(...) WRAP_VARIADIC(TYPES, __VA_ARGS__)\n\n\/\/ #undef _TYPES_IMPL\n\/\/ #undef _TYPES_IMPL2\n#undef _WRAP_VARIADIC_IMPL\n#undef _WRAP_VARIADIC_IMPL2\n#undef VA_NUM_ARGS\n#undef _VA_NUM_ARGS_IMPL\n\n\/\/ ------------------------ static size assertions from Eigen\n\n#define _PREDICATE_SAME_MATRIX_SIZE(TYPE0,TYPE1) \\\n ( \\\n (int(TYPE0::SizeAtCompileTime)==0 && int(TYPE1::SizeAtCompileTime)==0) \\\n || (\\\n (int(TYPE0::RowsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE1::RowsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE0::RowsAtCompileTime)==int(TYPE1::RowsAtCompileTime)) \\\n && (int(TYPE0::ColsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE1::ColsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE0::ColsAtCompileTime)==int(TYPE1::ColsAtCompileTime))\\\n ) \\\n )\n\n#define STATIC_ASSERT_SAME_SHAPE(TYPE0,TYPE1) \\\n\tstatic_assert(_PREDICATE_SAME_MATRIX_SIZE(TYPE0,TYPE1), \\\n\t\tYOU_MIXED_MATRICES_OF_DIFFERENT_SIZES)\n\n#undef _PREDICATE_SAME_MATRIX_SIZE\n\n\n#define PRINT_STATIC_TYPE(X) \\\n\tstatic_assert(decltype(X)::__debug__, #X);\n\n#endif \/\/ __cplusplus\n\n\n\n\n#endif \/\/ __MACROS_HPP\n<commit_msg>add optional<> to macros file + fix type in prefetch_rw macro<commit_after>\/\/\n\/\/ macros.hpp\n\/\/\n\/\/ Created By Davis Blalock on 3\/15\/16.\n\/\/ Copyright (c) 2016 Davis Blalock. All rights reserved.\n\/\/\n\n#ifndef __MACROS_HPP\n#define __MACROS_HPP\n\n\/\/ ------------------------ restrict keyword\n\/\/ adapted from http:\/\/stackoverflow.com\/a\/5948101\/1153180\n\n#if defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))\n\t#define RESTRICT __restrict__\n\n\t#define LIKELY(x) __builtin_expect (!!(x), 1)\n\t#define UNLIKELY(x) __builtin_expect (!!(x), 0)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n#elif defined(__clang__)\n\t#define RESTRICT __restrict__\n\n\t#define LIKELY(x) __builtin_expect (!!(x), 1)\n\t#define UNLIKELY(x) __builtin_expect (!!(x), 0)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 0, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT) \\\n\t\t__builtin_prefetch(ADDR, 1, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n#else\n\t#if defined(_MSC_VER) && _MSC_VER >= 1400\n\t\t#define RESTRICT\n\t#else\n\t\t#define RESTRICT __restrict\n\t#endif\n\n\t#define LIKELY(x) (x)\n\t#define UNLIKELY(x) (x)\n\n\t#define PREFETCH_WITH_STICKINESS(ADDR, INT)\n\t#define PREFETCH_RW_WITH_STICKINESS(ADDR, INT)\n\t#define PREFETCH_TRANSIENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_PERSISTENT(ADDR) PREFETCH_WITH_STICKINESS(ADDR, 3)\n\t#define PREFETCH_RW_TRANSIENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 0)\n\t#define PREFETCH_RW_PERSISTENT(ADDR) PREFETCH_RW_WITH_STICKINESS(ADDR, 3)\n\n#endif\n\n\/\/ count the number of arguments in a varargs list\n#define VA_NUM_ARGS(...) _VA_NUM_ARGS_IMPL(__VA_ARGS__, \\\n\t16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)\n#define _VA_NUM_ARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, \\\n\t _13, _14, _15, _16, N, ...) N\n\n#ifdef __cplusplus\n\/\/ ------------------------ type aliases \/\/ TODO macros file not ideal place\n\t#include <experimental\/optional>\n\t\/\/ will be std::optional in c++17\n\ttemplate<class T> using optional = std::experimental::optional<T>;\n\tstatic constexpr auto nullopt = std::experimental::nullopt;\n\n\/\/ ------------------------ type traits macros\n\t#include <type_traits>\n\n\t\/\/ #define SELF_TYPE \\\n\t\/\/ \ttypename std::remove_reference<decltype(*this)>::type\n\n\t\/\/ put these in function bodies to statically assert that appropriate types\n\t\/\/ have been passed in as template params; prefer using the below type\n\t\/\/ constraint macros, however\n\t#define ASSERT_TRAIT(TRAIT, T, MSG) static_assert(std::TRAIT<T>::value, MSG)\n\t#define ASSERT_INTEGRAL(T) ASSERT_TRAIT(is_integral, T, \"Type not integral!\")\n\n\t\/\/ put these as extra template params to enforce constraints\n\t\/\/ on previous template params; e.g.:\n\t\/\/\n\t\/\/ template<class T, REQUIRE_INT(T)> T foo(T arg) { return arg + 1; }\n\t\/\/\n\n\t\/\/ ------------------------ require that some constexpr be true\n\n\t#define REQ(EXPR) \\\n\t\ttypename = typename std::enable_if<EXPR, void>::type\n\n\t\/\/ have to wrap EXPR in a local template param for enable_if to work on\n\t\/\/ a class method where EXPR is a class template param\n\t#define _METHOD_REQ(EXPR, NAME) \\\n\t\tbool NAME = EXPR, typename = typename std::enable_if<NAME, void>::type\n\n\t#define METHOD_REQ0(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr0__)\n\n\t#define METHOD_REQ1(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr1__)\n\n\t#define METHOD_REQ2(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr2__)\n\n\t#define METHOD_REQ3(EXPR) \\\n\t\t_METHOD_REQ3(EXPR, __expr3__)\n\n\t#define METHOD_REQ4(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr4__)\n\n\t#define METHOD_REQ5(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr5__)\n\n\t#define METHOD_REQ6(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr6__)\n\n\t#define METHOD_REQ(EXPR) \\\n\t\t_METHOD_REQ(EXPR, __expr__)\n\n\t\t\/\/ bool __expr__ = EXPR, typename = typename std::enable_if<__expr__, void>::type\n\n\t\t\/\/ typename = typename std::enable_if<EXPR, T>::type\n\t#define REQUIRE_TRAIT(TRAIT, T) \\\n\t\ttypename = typename std::enable_if<std::TRAIT<T>::value, T>::type\n\n\t#define REQUIRE_NOT_TRAIT(TRAIT, T) \\\n\t\ttypename = typename std::enable_if<!std::TRAIT<T>::value, T>::type\n\n\t#define REQUIRE_IS_A(BASE, T) \\\n\t\ttypename = typename std::enable_if<std::is_base_of<BASE, T>::value, T>::type\n\n\t#define REQUIRE_IS_NOT_A(BASE, T) \\\n\t\ttypename = typename std::enable_if<!std::is_base_of<BASE, T>::value, T>::type\n\n\t\t\/\/ REQ(!std::is_base_of<BASE, T>::value)\n\n\t#define REQUIRE_INT(T) REQUIRE_TRAIT(is_integral, T)\n\t#define REQUIRE_NUM(T) REQUIRE_TRAIT(is_arithmetic, T)\n\t#define REQUIRE_FLOAT(T) REQUIRE_TRAIT(is_floating_point, T)\n\t#define REQUIRE_PRIMITIVE(T) REQUIRE_TRAIT(is_arithmetic, T)\n\t#define REQUIRE_NOT_PTR(T) REQUIRE_NOT_TRAIT(is_pointer, T)\n\n\t#define REQ_HAS_ATTR(T, METHOD_INVOCATION) \\\n\t\ttypename=decltype(std::declval<T>() . METHOD_INVOCATION)\n\n\t\/\/ ------------------------ is_valid; requires C++14\n\t\/\/ inspired by https:\/\/gist.github.com\/Jiwan\/7a586c739a30dd90d259\n\n\ttemplate <typename T> struct _valid_helper {\n\tprivate:\n\t template <typename Param> constexpr auto _is_valid(int _)\n\t\t \/\/ type returned by decltype is last type in the list (here,\n\t\t\t\/\/ std::true_type), but previous types must be valid\n\t \t-> decltype(std::declval<T>()(std::declval<Param>()),\n\t \t\tstd::true_type())\n\t {\n\t return std::true_type();\n\t }\n\n\t template <typename Param> constexpr std::false_type _is_valid(...) {\n\t return std::false_type();\n\t }\n\n\tpublic:\n\t template <typename Param> constexpr auto operator()(const Param& p) {\n\t return _is_valid<Param>(int(0));\n\t }\n\t};\n\n\ttemplate <typename T> constexpr auto is_valid(const T& t) {\n\t return _valid_helper<T>();\n\t}\n\n\t#define CREATE_TEST(OBJNAME, EXPR) \\\n\t\tis_valid([](auto&& OBJNAME) -> decltype(EXPR) { })\n\n\t#define CREATE_TEST_X(EXPR) \\\n\t\tis_valid([](auto&& x) -> decltype(EXPR) { })\n\n\t#define TEST_FOR_METHOD(INVOCATION) \\\n\t\tis_valid([](auto&& x) -> decltype(x. INVOCATION) { })\n\n\t#define PASSES_TEST(OBJ, TEST) \\\n\t\tdecltype(TEST(OBJ))::value\n\n\t#define TYPE_PASSES_TEST(T, TEST) \\\n\t\tPASSES_TEST(std::declval<T>(), TEST)\n\n\t#define REQ_TYPE_PASSES(T, TEST) \\\n\t\tREQ(TYPE_PASSES_TEST(T, TEST))\n\n\t#define ENABLE_IF(EXPR, T) \\\n\t\ttypename std::enable_if<EXPR, T>::type\n\n\n\/\/ ------------------------ TYPES(...) convenience macro for template args\n#define TYPES_1(A) template<typename A>\n#define TYPES_2(A, B) \\\n\ttemplate<typename A, typename B>\n#define TYPES_3(A, B, C) \\\n\ttemplate<typename A, typename B, typename C>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_4(A, B, C, D) \\\n\ttemplate<typename A, typename B, typename C, typename D>\n\t\t\/\/ TYPES_10(A, B, C, D, E=int, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_5(A, B, C, D, E) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F=int, G=int, H=int, I=int, J=int)\n#define TYPES_6(A, B, C, D, E, F) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G=int, H=int, I=int, J=int)\n#define TYPES_7(A, B, C, D, E, F, G) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H=int, I=int, J=int)\n#define TYPES_8(A, B, C, D, E, F, G, H) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H, I=int, J=int)\n#define TYPES_9(A, B, C, D, E, F, G, H, I) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H, typename I>\n\t\t\/\/ TYPES_10(A, B, C, D, E, F, G, H, I, J=int)\n#define TYPES_10(A, B, C, D, E, F, G, H, I, J) \\\n\ttemplate<typename A, typename B, typename C, typename D, typename E, \\\n\t\ttypename F, typename G, typename H, typename I, typename J\n\n\/\/ define a top level TYPES macro that automatically calls the macro with\n\/\/ the proper number of arguments\n\/\/ #define _TYPES_IMPL2(count, ...) TYPES_ ## count (__VA_ARGS__)\n\/\/ #define _TYPES_IMPL(count, ...) _TYPES_IMPL2(count, __VA_ARGS__)\n\/\/ #define TYPES(...) _TYPES_IMPL(VA_NUM_ARGS(__VA_ARGS__), __VA_ARGS__)\n\n\/\/ TODO if this works, get rid of above 3 loc and move outside of cpp block\n#define _WRAP_VARIADIC_IMPL2(name, count, ...) \\\n\t\tname ## count (__VA_ARGS__)\n#define _WRAP_VARIADIC_IMPL(name, count, ...) \\\n\t\t_WRAP_VARIADIC_IMPL2(name, count, __VA_ARGS__)\n#define WRAP_VARIADIC(name, ...) \\\n\t\t_WRAP_VARIADIC_IMPL(name, VA_NUM_ARGS(__VA_ARGS__), __VA_ARGS__)\n\n#define TYPES(...) WRAP_VARIADIC(TYPES, __VA_ARGS__)\n\n\/\/ #undef _TYPES_IMPL\n\/\/ #undef _TYPES_IMPL2\n#undef _WRAP_VARIADIC_IMPL\n#undef _WRAP_VARIADIC_IMPL2\n#undef VA_NUM_ARGS\n#undef _VA_NUM_ARGS_IMPL\n\n\/\/ ------------------------ static size assertions from Eigen\n\n#define _PREDICATE_SAME_MATRIX_SIZE(TYPE0,TYPE1) \\\n ( \\\n (int(TYPE0::SizeAtCompileTime)==0 && int(TYPE1::SizeAtCompileTime)==0) \\\n || (\\\n (int(TYPE0::RowsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE1::RowsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE0::RowsAtCompileTime)==int(TYPE1::RowsAtCompileTime)) \\\n && (int(TYPE0::ColsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE1::ColsAtCompileTime)==Eigen::Dynamic \\\n || int(TYPE0::ColsAtCompileTime)==int(TYPE1::ColsAtCompileTime))\\\n ) \\\n )\n\n#define STATIC_ASSERT_SAME_SHAPE(TYPE0,TYPE1) \\\n\tstatic_assert(_PREDICATE_SAME_MATRIX_SIZE(TYPE0,TYPE1), \\\n\t\tYOU_MIXED_MATRICES_OF_DIFFERENT_SIZES)\n\n#undef _PREDICATE_SAME_MATRIX_SIZE\n\n\n#define PRINT_STATIC_TYPE(X) \\\n\tstatic_assert(decltype(X)::__debug__, #X);\n\n#endif \/\/ __cplusplus\n\n\n\n\n#endif \/\/ __MACROS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdlib.h>\n#include \"Transcoder.hpp\"\n\nXERCES_CPP_NAMESPACE_USE\n\nstatic bool DEBUG_IN = false;\nstatic bool DEBUG_OUT = false;\n\nTranscoder* Transcoder::_instance = NULL;\n\nTranscoder*\nTranscoder::getInstance() {\n \/\/ fprintf(stderr, \"getInstance: finding instance\\n\");\n if (_instance == NULL) {\n \/\/ fprintf(stderr, \"getInstance: making new transcoder\\n\");\n _instance = new Transcoder();\n }\n return _instance;\n}\n\nTranscoder::~Transcoder() {\n \/\/ fprintf(stderr, \"Deleting transcoder\\n\");\n}\n\nTranscoder::Transcoder() {\n XMLTransService::Codes failReason;\n\n \/\/ we assume that the Xerces-C transcoding service is already initialized\n \/\/ via XMLPlatformUtils::Initialize()\n UTF8_TRANSCODER = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\n\t\t\t\t\t\tXMLUni::fgUTF8EncodingString,\n\t\t\t\t\t\tfailReason,\n\t\t\t\t\t\t1024);\n\n if (UTF8_TRANSCODER == NULL) {\n croak(\"ERROR: Transcoder Could not create UTF-8 transcoder\");\n } else if (failReason == XMLTransService::UnsupportedEncoding) {\n croak(\"ERROR: Transcoder: unsupported encoding\");\n } else if (failReason == XMLTransService::InternalFailure) {\n croak(\"ERROR: Transcoder: internal failure\");\n } else if (failReason == XMLTransService::SupportFilesNotFound) {\n croak(\"ERROR: Transcoder: support files not found\");\n } else if (failReason == XMLTransService::Ok) {\n \/\/ fprintf(stderr, \"Created transcoder ok\\n\");\n }\n}\n\nSV*\nTranscoder::XMLString2Local(const XMLCh* input) {\n if (input == NULL) {\n return &PL_sv_undef;\n }\n\n SV *output;\n unsigned int charsEaten = 0;\n int length = XMLString::stringLen(input); \/\/ string length\n \/\/ use +1 to make room for the '\\0' at the end of the string\n \/\/ in the pathological case when each character of the string \n \/\/ is UTF8_MAXLEN bytes long\n XMLByte* res = new XMLByte[(length * UTF8_MAXLEN) + 1]; \/\/ output string\n\n unsigned int total_chars =\n UTF8_TRANSCODER->transcodeTo((const XMLCh*) input, \n\t\t\t\t (unsigned int) length,\n\t\t\t\t (XMLByte*) res,\n\t\t\t\t (unsigned int) (length*UTF8_MAXLEN),\n\t\t\t\t charsEaten,\n\t\t\t\t XMLTranscoder::UnRep_Throw\n\t\t\t\t );\n res[total_chars] = '\\0';\n\n#if (0) \n if (DEBUG_OUT) {\n printf(\"Xerces out length = %d: \",total_chars);\n for (int i=0;i<length;i++){\n\t printf(\"<0x%.4X>\",res[i]);\n }\n printf(\"\\n\");\n }\n#endif\n\n output = sv_newmortal();\n sv_setpv((SV*)output, (char *)res );\n SvUTF8_on((SV*)output);\n delete[] res;\n return output;\n}\n\nXMLCh* \nTranscoder::Local2XMLString(SV* input){\n\n if (input == &PL_sv_undef) {\n return NULL;\n }\n\n XMLCh* output;\n\n STRLEN length;\n char *ptr = (char *)SvPVutf8(input,length);\n\n#if (0) \n if (DEBUG_IN) {\n\tprintf(\"Perl in length = %d: \",length);\n\tfor (unsigned int i=0;i<length;i++){\n\t printf(\"<0x%.4X>\",ptr[i]);\n\t}\n\tprintf(\"\\n\");\n }\n#endif\n\n if (SvUTF8(input)) {\n\tunsigned int charsEaten = 0;\n unsigned char* sizes = new unsigned char[length+1];\n output = new XMLCh[length+1];\n\tunsigned int chars_stored = \n\t UTF8_TRANSCODER->transcodeFrom((const XMLByte*) ptr,\n\t\t\t\t\t (unsigned int) length,\n\t\t\t\t\t (XMLCh*) output, \n\t\t\t\t\t (unsigned int) length,\n\t\t\t\t\t charsEaten,\n\t\t\t\t\t (unsigned char*)sizes\n\t\t\t\t\t );\n\tdelete [] sizes;\n\n#if (0) \n\tif (DEBUG_IN) {\n\t printf(\"Xerces in length = %d: \",chars_stored);\n\t for (unsigned int i=0;i<chars_stored;i++){\n\t\tprintf(\"<0x%.4X>\",output[i]);\n\t }\n\t printf(\"\\n\");\n\t}\n#endif\n\n\t\/\/ indicate the end of the string\n\toutput[chars_stored] = '\\0';\n } else {\n\toutput = XMLString::transcode(ptr);\n\n#if (0) \n\tif (DEBUG_IN) {\n\t printf(\"Xerces: \");\n\t for (int i=0;output[i];i++){\n\t\tprintf(\"<0x%.4X>\",output[i]);\n\t }\n\t printf(\"\\n\");\n\t}\n#endif\n\n }\n return(output);\n}\n\n<commit_msg>64 bit compile issues: unsigned int -> XMLSize_t<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdlib.h>\n#include \"Transcoder.hpp\"\n\nXERCES_CPP_NAMESPACE_USE\n\nstatic bool DEBUG_IN = false;\nstatic bool DEBUG_OUT = false;\n\nTranscoder* Transcoder::_instance = NULL;\n\nTranscoder*\nTranscoder::getInstance() {\n \/\/ fprintf(stderr, \"getInstance: finding instance\\n\");\n if (_instance == NULL) {\n \/\/ fprintf(stderr, \"getInstance: making new transcoder\\n\");\n _instance = new Transcoder();\n }\n return _instance;\n}\n\nTranscoder::~Transcoder() {\n \/\/ fprintf(stderr, \"Deleting transcoder\\n\");\n}\n\nTranscoder::Transcoder() {\n XMLTransService::Codes failReason;\n\n \/\/ we assume that the Xerces-C transcoding service is already initialized\n \/\/ via XMLPlatformUtils::Initialize()\n UTF8_TRANSCODER = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\n\t\t\t\t\t\tXMLUni::fgUTF8EncodingString,\n\t\t\t\t\t\tfailReason,\n\t\t\t\t\t\t1024);\n\n if (UTF8_TRANSCODER == NULL) {\n croak(\"ERROR: Transcoder Could not create UTF-8 transcoder\");\n } else if (failReason == XMLTransService::UnsupportedEncoding) {\n croak(\"ERROR: Transcoder: unsupported encoding\");\n } else if (failReason == XMLTransService::InternalFailure) {\n croak(\"ERROR: Transcoder: internal failure\");\n } else if (failReason == XMLTransService::SupportFilesNotFound) {\n croak(\"ERROR: Transcoder: support files not found\");\n } else if (failReason == XMLTransService::Ok) {\n \/\/ fprintf(stderr, \"Created transcoder ok\\n\");\n }\n}\n\nSV*\nTranscoder::XMLString2Local(const XMLCh* input) {\n if (input == NULL) {\n return &PL_sv_undef;\n }\n\n SV *output;\n XMLSize_t charsEaten = 0;\n int length = XMLString::stringLen(input); \/\/ string length\n \/\/ use +1 to make room for the '\\0' at the end of the string\n \/\/ in the pathological case when each character of the string \n \/\/ is UTF8_MAXLEN bytes long\n XMLByte* res = new XMLByte[(length * UTF8_MAXLEN) + 1]; \/\/ output string\n\n XMLSize_t total_chars =\n UTF8_TRANSCODER->transcodeTo((const XMLCh*) input, \n\t\t\t\t (XMLSize_t) length,\n\t\t\t\t (XMLByte*) res,\n\t\t\t\t (XMLSize_t) (length*UTF8_MAXLEN),\n\t\t\t\t charsEaten,\n\t\t\t\t XMLTranscoder::UnRep_Throw\n\t\t\t\t );\n res[total_chars] = '\\0';\n\n#if (0) \n if (DEBUG_OUT) {\n printf(\"Xerces out length = %d: \",total_chars);\n for (int i=0;i<length;i++){\n\t printf(\"<0x%.4X>\",res[i]);\n }\n printf(\"\\n\");\n }\n#endif\n\n output = sv_newmortal();\n sv_setpv((SV*)output, (char *)res );\n SvUTF8_on((SV*)output);\n delete[] res;\n return output;\n}\n\nXMLCh* \nTranscoder::Local2XMLString(SV* input){\n\n if (input == &PL_sv_undef) {\n return NULL;\n }\n\n XMLCh* output;\n\n STRLEN length;\n char *ptr = (char *)SvPVutf8(input,length);\n\n#if (0) \n if (DEBUG_IN) {\n\tprintf(\"Perl in length = %d: \",length);\n\tfor (unsigned int i=0;i<length;i++){\n\t printf(\"<0x%.4X>\",ptr[i]);\n\t}\n\tprintf(\"\\n\");\n }\n#endif\n\n if (SvUTF8(input)) {\n\tXMLSize_t charsEaten = 0;\n unsigned char* sizes = new unsigned char[length+1];\n output = new XMLCh[length+1];\n\tXMLSize_t chars_stored = \n\t UTF8_TRANSCODER->transcodeFrom((const XMLByte*) ptr,\n\t\t\t\t\t (XMLSize_t) length,\n\t\t\t\t\t (XMLCh*) output, \n\t\t\t\t\t (XMLSize_t) length,\n\t\t\t\t\t charsEaten,\n\t\t\t\t\t (unsigned char*)sizes\n\t\t\t\t\t );\n\tdelete [] sizes;\n\n#if (0) \n\tif (DEBUG_IN) {\n\t printf(\"Xerces in length = %d: \",chars_stored);\n\t for (unsigned int i=0;i<chars_stored;i++){\n\t\tprintf(\"<0x%.4X>\",output[i]);\n\t }\n\t printf(\"\\n\");\n\t}\n#endif\n\n\t\/\/ indicate the end of the string\n\toutput[chars_stored] = '\\0';\n } else {\n\toutput = XMLString::transcode(ptr);\n\n#if (0) \n\tif (DEBUG_IN) {\n\t printf(\"Xerces: \");\n\t for (int i=0;output[i];i++){\n\t\tprintf(\"<0x%.4X>\",output[i]);\n\t }\n\t printf(\"\\n\");\n\t}\n#endif\n\n }\n return(output);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================\n\/\/\n\/\/ OpenMesh\n\/\/ Copyright (C) 2001-2003 by Computer Graphics Group, RWTH Aachen\n\/\/ www.openmesh.org\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ License\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation, version 2.1.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ $Revision$\n\/\/ $Date$\n\/\/\n\/\/=============================================================================\n\n\/\/=============================================================================\n\/\/\n\/\/ CLASS StripifierT - IMPLEMENTATION\n\/\/\n\/\/=============================================================================\n\n#define OPENMESH_STRIPIFIERT_C\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Tools\/Utils\/StripifierT.hh>\n#include <list>\n\n\n\/\/== NAMESPACES ===============================================================\n\nnamespace OpenMesh {\n\n\n \/\/== IMPLEMENTATION ==========================================================\n\ntemplate <class Mesh>\nStripifierT<Mesh>::\nStripifierT(Mesh& _mesh) :\n mesh_(_mesh)\n{\n \/\/ preprocess: add new properties\n mesh_.add_property( processed_ );\n mesh_.add_property( used_ );\n mesh_.request_face_status();\n}\n\ntemplate <class Mesh>\nStripifierT<Mesh>::\n~StripifierT() {\n \/\/ postprocess: remove properties\n mesh_.remove_property(processed_);\n mesh_.remove_property(used_);\n mesh_.release_face_status();\n}\n\ntemplate <class Mesh>\nunsigned int\nStripifierT<Mesh>::\nstripify()\n{\n \/\/ build strips\n clear();\n build_strips();\n\n return n_strips();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Mesh>\nvoid\nStripifierT<Mesh>::\nbuild_strips()\n{\n Strip experiments[3];\n typename Mesh::HalfedgeHandle h[3];\n unsigned int best_idx, best_length, length;\n FaceHandles faces[3];\n typename FaceHandles::iterator fh_it, fh_end;\n typename Mesh::FaceIter f_it, f_end=mesh_.faces_end();\n\n\n\n \/\/ init faces to be un-processed and un-used\n \/\/ deleted or hidden faces are marked processed\n if (mesh_.has_face_status())\n {\n for (f_it=mesh_.faces_begin(); f_it!=f_end; ++f_it)\n if (mesh_.status(f_it).hidden() || mesh_.status(f_it).deleted())\n processed(f_it) = used(f_it) = true;\n else\n processed(f_it) = used(f_it) = false;\n }\n else\n {\n for (f_it=mesh_.faces_begin(); f_it!=f_end; ++f_it)\n processed(f_it) = used(f_it) = false;\n }\n\n\n\n for (f_it=mesh_.faces_begin(); true; )\n {\n \/\/ find start face\n for (; f_it!=f_end; ++f_it)\n if (!processed(f_it))\n break;\n if (f_it==f_end) break; \/\/ stop if all have been processed\n\n\n \/\/ collect starting halfedges\n h[0] = mesh_.halfedge_handle(f_it.handle());\n h[1] = mesh_.next_halfedge_handle(h[0]);\n h[2] = mesh_.next_halfedge_handle(h[1]);\n\n\n \/\/ build 3 strips, take best one\n best_length = best_idx = 0;\n for (unsigned int i=0; i<3; ++i)\n {\n build_strip(h[i], experiments[i], faces[i]);\n if ((length = experiments[i].size()) > best_length)\n {\n best_length = length;\n best_idx = i;\n }\n\n for (fh_it=faces[i].begin(), fh_end=faces[i].end();\n fh_it!=fh_end; ++fh_it)\n used(*fh_it) = false;\n }\n\n\n \/\/ update processed status\n fh_it = faces[best_idx].begin();\n fh_end = faces[best_idx].end();\n for (; fh_it!=fh_end; ++fh_it)\n processed(*fh_it) = true;\n\n\n\n \/\/ add best strip to strip-list\n strips_.push_back(experiments[best_idx]);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Mesh>\nvoid\nStripifierT<Mesh>::\nbuild_strip(typename Mesh::HalfedgeHandle _start_hh,\n Strip& _strip,\n FaceHandles& _faces)\n{\n std::list<unsigned int> strip;\n typename Mesh::HalfedgeHandle hh;\n typename Mesh::FaceHandle fh;\n\n\n \/\/ reset face list\n _faces.clear();\n\n\n \/\/ init strip\n strip.push_back(mesh_.from_vertex_handle(_start_hh).idx());\n strip.push_back(mesh_.to_vertex_handle(_start_hh).idx());\n\n\n \/\/ walk along the strip: 1st direction\n hh = mesh_.prev_halfedge_handle(mesh_.opposite_halfedge_handle(_start_hh));\n while (1)\n {\n \/\/ go right\n hh = mesh_.next_halfedge_handle(hh);\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_back(mesh_.to_vertex_handle(hh).idx());\n\n \/\/ go left\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_back(mesh_.to_vertex_handle(hh).idx());\n }\n\n\n \/\/ walk along the strip: 2nd direction\n bool flip(false);\n hh = mesh_.prev_halfedge_handle(_start_hh);\n while (1)\n {\n \/\/ go right\n hh = mesh_.next_halfedge_handle(hh);\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_front(mesh_.to_vertex_handle(hh).idx());\n flip = true;\n\n \/\/ go left\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_front(mesh_.to_vertex_handle(hh).idx());\n flip = false;\n }\n\n if (flip) strip.push_front(strip.front());\n\n\n\n \/\/ copy final strip to _strip\n _strip.clear();\n _strip.reserve(strip.size());\n std::copy(strip.begin(), strip.end(), std::back_inserter(_strip));\n}\n\n\n\/\/=============================================================================\n} \/\/ namespace OpenMesh\n \/\/=============================================================================\n<commit_msg>Revert last patch<commit_after>\/\/=============================================================================\n\/\/\n\/\/ OpenMesh\n\/\/ Copyright (C) 2001-2003 by Computer Graphics Group, RWTH Aachen\n\/\/ www.openmesh.org\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ License\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation, version 2.1.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ $Revision$\n\/\/ $Date$\n\/\/\n\/\/=============================================================================\n\n\/\/=============================================================================\n\/\/\n\/\/ CLASS StripifierT - IMPLEMENTATION\n\/\/\n\/\/=============================================================================\n\n#define OPENMESH_STRIPIFIERT_C\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Tools\/Utils\/StripifierT.hh>\n#include <list>\n\n\n\/\/== NAMESPACES ===============================================================\n\nnamespace OpenMesh {\n\n\n \/\/== IMPLEMENTATION ==========================================================\n\ntemplate <class Mesh>\nStripifierT<Mesh>::\nStripifierT(Mesh& _mesh) :\n mesh_(_mesh)\n{\n\n}\n\ntemplate <class Mesh>\nStripifierT<Mesh>::\n~StripifierT() {\n\n}\n\ntemplate <class Mesh>\nunsigned int\nStripifierT<Mesh>::\nstripify()\n{\n \/\/ preprocess: add new properties\n mesh_.add_property( processed_ );\n mesh_.add_property( used_ );\n mesh_.request_face_status();\n\n \/\/ build strips\n clear();\n build_strips();\n\n \/\/ postprocess: remove properties\n mesh_.remove_property(processed_);\n mesh_.remove_property(used_);\n mesh_.release_face_status();\n\n return n_strips();\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Mesh>\nvoid\nStripifierT<Mesh>::\nbuild_strips()\n{\n Strip experiments[3];\n typename Mesh::HalfedgeHandle h[3];\n unsigned int best_idx, best_length, length;\n FaceHandles faces[3];\n typename FaceHandles::iterator fh_it, fh_end;\n typename Mesh::FaceIter f_it, f_end=mesh_.faces_end();\n\n\n\n \/\/ init faces to be un-processed and un-used\n \/\/ deleted or hidden faces are marked processed\n if (mesh_.has_face_status())\n {\n for (f_it=mesh_.faces_begin(); f_it!=f_end; ++f_it)\n if (mesh_.status(f_it).hidden() || mesh_.status(f_it).deleted())\n processed(f_it) = used(f_it) = true;\n else\n processed(f_it) = used(f_it) = false;\n }\n else\n {\n for (f_it=mesh_.faces_begin(); f_it!=f_end; ++f_it)\n processed(f_it) = used(f_it) = false;\n }\n\n\n\n for (f_it=mesh_.faces_begin(); true; )\n {\n \/\/ find start face\n for (; f_it!=f_end; ++f_it)\n if (!processed(f_it))\n break;\n if (f_it==f_end) break; \/\/ stop if all have been processed\n\n\n \/\/ collect starting halfedges\n h[0] = mesh_.halfedge_handle(f_it.handle());\n h[1] = mesh_.next_halfedge_handle(h[0]);\n h[2] = mesh_.next_halfedge_handle(h[1]);\n\n\n \/\/ build 3 strips, take best one\n best_length = best_idx = 0;\n for (unsigned int i=0; i<3; ++i)\n {\n build_strip(h[i], experiments[i], faces[i]);\n if ((length = experiments[i].size()) > best_length)\n {\n best_length = length;\n best_idx = i;\n }\n\n for (fh_it=faces[i].begin(), fh_end=faces[i].end();\n fh_it!=fh_end; ++fh_it)\n used(*fh_it) = false;\n }\n\n\n \/\/ update processed status\n fh_it = faces[best_idx].begin();\n fh_end = faces[best_idx].end();\n for (; fh_it!=fh_end; ++fh_it)\n processed(*fh_it) = true;\n\n\n\n \/\/ add best strip to strip-list\n strips_.push_back(experiments[best_idx]);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Mesh>\nvoid\nStripifierT<Mesh>::\nbuild_strip(typename Mesh::HalfedgeHandle _start_hh,\n Strip& _strip,\n FaceHandles& _faces)\n{\n std::list<unsigned int> strip;\n typename Mesh::HalfedgeHandle hh;\n typename Mesh::FaceHandle fh;\n\n\n \/\/ reset face list\n _faces.clear();\n\n\n \/\/ init strip\n strip.push_back(mesh_.from_vertex_handle(_start_hh).idx());\n strip.push_back(mesh_.to_vertex_handle(_start_hh).idx());\n\n\n \/\/ walk along the strip: 1st direction\n hh = mesh_.prev_halfedge_handle(mesh_.opposite_halfedge_handle(_start_hh));\n while (1)\n {\n \/\/ go right\n hh = mesh_.next_halfedge_handle(hh);\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_back(mesh_.to_vertex_handle(hh).idx());\n\n \/\/ go left\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_back(mesh_.to_vertex_handle(hh).idx());\n }\n\n\n \/\/ walk along the strip: 2nd direction\n bool flip(false);\n hh = mesh_.prev_halfedge_handle(_start_hh);\n while (1)\n {\n \/\/ go right\n hh = mesh_.next_halfedge_handle(hh);\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_front(mesh_.to_vertex_handle(hh).idx());\n flip = true;\n\n \/\/ go left\n hh = mesh_.opposite_halfedge_handle(hh);\n hh = mesh_.next_halfedge_handle(hh);\n if (mesh_.is_boundary(hh)) break;\n fh = mesh_.face_handle(hh);\n if (processed(fh) || used(fh)) break;\n _faces.push_back(fh);\n used(fh) = true;\n strip.push_front(mesh_.to_vertex_handle(hh).idx());\n flip = false;\n }\n\n if (flip) strip.push_front(strip.front());\n\n\n\n \/\/ copy final strip to _strip\n _strip.clear();\n _strip.reserve(strip.size());\n std::copy(strip.begin(), strip.end(), std::back_inserter(_strip));\n}\n\n\n\/\/=============================================================================\n} \/\/ namespace OpenMesh\n \/\/=============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prim.hxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 13:15:15 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef PRIM_HXX\n#define PRIM_HXX\n\n#ifndef _TYPELIB_TYPEDESCRIPTION_H_\n#include \"typelib\/typedescription.h\"\n#endif\n#ifndef _typelib_TypeClass_H_\n#include \"typelib\/typeclass.h\"\n#endif\n#ifndef _UNO_SEQUENCE2_H_\n#include \"uno\/sequence2.h\"\n#endif\n#ifndef _UNO_ANY2_H_\n#include \"uno\/any2.h\"\n#endif\n#ifndef _UNO_DATA_H_\n#include \"uno\/data.h\"\n#endif\n#ifndef _UNO_MAPPING_H_\n#include \"uno\/mapping.h\"\n#endif\n#ifndef _UNO_DISPATCHER_H_\n#include \"uno\/dispatcher.h\"\n#endif\n\n#ifndef _OSL_INTERLCK_H\n#include \"osl\/interlck.h\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include \"osl\/diagnose.h\"\n#endif\n#ifndef _RTL_USTRING_HXX\n#include \"rtl\/ustring.hxx\"\n#endif\n#ifndef _RTL_ALLOC_H_\n#include \"rtl\/alloc.h\"\n#endif\n\n#if OSL_DEBUG_LEVEL > 1\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/string.hxx\"\n#endif\n\n\nnamespace cppu\n{\n\nextern uno_Sequence g_emptySeq;\nextern typelib_TypeDescriptionReference * g_pVoidType;\n\n\/\/--------------------------------------------------------------------------------------------------\ninline void * _map(\n void * p,\n typelib_TypeDescriptionReference * pType, typelib_TypeDescription * pTypeDescr,\n uno_Mapping * mapping )\n SAL_THROW( () )\n{\n void * pRet = 0;\n if (p)\n {\n if (pTypeDescr)\n {\n (*mapping->mapInterface)(\n mapping, &pRet, p, (typelib_InterfaceTypeDescription *)pTypeDescr );\n }\n else\n {\n TYPELIB_DANGER_GET( &pTypeDescr, pType );\n (*mapping->mapInterface)(\n mapping, &pRet, p, (typelib_InterfaceTypeDescription *)pTypeDescr );\n TYPELIB_DANGER_RELEASE( pTypeDescr );\n }\n }\n return pRet;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline void _acquire( void * p, uno_AcquireFunc acquire ) SAL_THROW( () )\n{\n if (p)\n {\n if (acquire)\n {\n (*acquire)( p );\n }\n else\n {\n (*((uno_Interface *)p)->acquire)( (uno_Interface *)p );\n }\n }\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline void _release( void * p, uno_ReleaseFunc release ) SAL_THROW( () )\n{\n if (p)\n {\n if (release)\n {\n (*release)( p );\n }\n else\n {\n (*((uno_Interface *)p)->release)( (uno_Interface *)p );\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\ninline sal_uInt32 calcSeqMemSize(\n sal_Int32 nElementSize, sal_Int32 nElements )\n{\n sal_uInt64 nSize =\n (sal_uInt64) SAL_SEQUENCE_HEADER_SIZE +\n ((sal_uInt64) nElementSize * (sal_uInt64) nElements);\n if (nSize > 0xffffffffU)\n return 0;\n else\n return (sal_uInt32) nSize;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\ninline uno_Sequence * createEmptySequence() SAL_THROW( () )\n{\n ::osl_incrementInterlockedCount( &g_emptySeq.nRefCount );\n return &g_emptySeq;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline typelib_TypeDescriptionReference * _getVoidType()\n SAL_THROW( () )\n{\n if (! g_pVoidType)\n {\n g_pVoidType = * ::typelib_static_type_getByTypeClass( typelib_TypeClass_VOID );\n }\n ::typelib_typedescriptionreference_acquire( g_pVoidType );\n return g_pVoidType;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n#if OSL_DEBUG_LEVEL > 0\n#define CONSTRUCT_EMPTY_ANY( pAny ) \\\n(pAny)->pType = _getVoidType(); \\\n(pAny)->pData = (void *)0xdeadbeef;\n#else\n#define CONSTRUCT_EMPTY_ANY( pAny ) \\\n(pAny)->pType = _getVoidType(); \\\n(pAny)->pData = (pAny);\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n#define TYPE_ACQUIRE( pType ) \\\n ::osl_incrementInterlockedCount( &(pType)->nRefCount );\n\n\/\/--------------------------------------------------------------------------------------------------\nextern \"C\" void * binuno_queryInterface(\n void * pUnoI, typelib_TypeDescriptionReference * pDestType );\n\n\/\/--------------------------------------------------------------------------------------------------\ninline typelib_TypeDescriptionReference * _unionGetSetType(\n void * pUnion, typelib_TypeDescription * pTD )\n SAL_THROW( () )\n{\n typelib_TypeDescriptionReference * pRet = 0;\n sal_Int32 nPos;\n\n sal_Int64 * pDiscr = ((typelib_UnionTypeDescription *)pTD)->pDiscriminants;\n sal_Int64 nDiscr = *(sal_Int64 *)pUnion;\n for ( nPos = ((typelib_UnionTypeDescription *)pTD)->nMembers; nPos--; )\n {\n if (pDiscr[nPos] == nDiscr)\n {\n pRet = ((typelib_UnionTypeDescription *)pTD)->ppTypeRefs[nPos];\n break;\n }\n }\n if (nPos >= 0)\n {\n \/\/ default\n pRet = ((typelib_UnionTypeDescription *)pTD)->pDefaultTypeRef;\n }\n typelib_typedescriptionreference_acquire( pRet );\n return pRet;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline sal_Bool _type_equals(\n typelib_TypeDescriptionReference * pType1, typelib_TypeDescriptionReference * pType2 )\n SAL_THROW( () )\n{\n return (pType1 == pType2 ||\n (pType1->eTypeClass == pType2->eTypeClass &&\n pType1->pTypeName->length == pType2->pTypeName->length &&\n ::rtl_ustr_compare( pType1->pTypeName->buffer, pType2->pTypeName->buffer ) == 0));\n}\n\n}\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.17.84); FILE MERGED 2008\/04\/01 15:10:35 thb 1.17.84.3: #i85898# Stripping all external header guards 2008\/04\/01 12:28:03 thb 1.17.84.2: #i85898# Stripping all external header guards 2008\/03\/31 07:23:22 rt 1.17.84.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prim.hxx,v $\n * $Revision: 1.18 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef PRIM_HXX\n#define PRIM_HXX\n\n#include \"typelib\/typedescription.h\"\n#ifndef _typelib_TypeClass_H_\n#include \"typelib\/typeclass.h\"\n#endif\n#include \"uno\/sequence2.h\"\n#include \"uno\/any2.h\"\n#include \"uno\/data.h\"\n#include \"uno\/mapping.h\"\n#include \"uno\/dispatcher.h\"\n\n#ifndef _OSL_INTERLCK_H\n#include \"osl\/interlck.h\"\n#endif\n#include \"osl\/diagnose.h\"\n#ifndef _RTL_USTRING_HXX\n#include \"rtl\/ustring.hxx\"\n#endif\n#include \"rtl\/alloc.h\"\n\n#if OSL_DEBUG_LEVEL > 1\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/string.hxx\"\n#endif\n\n\nnamespace cppu\n{\n\nextern uno_Sequence g_emptySeq;\nextern typelib_TypeDescriptionReference * g_pVoidType;\n\n\/\/--------------------------------------------------------------------------------------------------\ninline void * _map(\n void * p,\n typelib_TypeDescriptionReference * pType, typelib_TypeDescription * pTypeDescr,\n uno_Mapping * mapping )\n SAL_THROW( () )\n{\n void * pRet = 0;\n if (p)\n {\n if (pTypeDescr)\n {\n (*mapping->mapInterface)(\n mapping, &pRet, p, (typelib_InterfaceTypeDescription *)pTypeDescr );\n }\n else\n {\n TYPELIB_DANGER_GET( &pTypeDescr, pType );\n (*mapping->mapInterface)(\n mapping, &pRet, p, (typelib_InterfaceTypeDescription *)pTypeDescr );\n TYPELIB_DANGER_RELEASE( pTypeDescr );\n }\n }\n return pRet;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline void _acquire( void * p, uno_AcquireFunc acquire ) SAL_THROW( () )\n{\n if (p)\n {\n if (acquire)\n {\n (*acquire)( p );\n }\n else\n {\n (*((uno_Interface *)p)->acquire)( (uno_Interface *)p );\n }\n }\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline void _release( void * p, uno_ReleaseFunc release ) SAL_THROW( () )\n{\n if (p)\n {\n if (release)\n {\n (*release)( p );\n }\n else\n {\n (*((uno_Interface *)p)->release)( (uno_Interface *)p );\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\ninline sal_uInt32 calcSeqMemSize(\n sal_Int32 nElementSize, sal_Int32 nElements )\n{\n sal_uInt64 nSize =\n (sal_uInt64) SAL_SEQUENCE_HEADER_SIZE +\n ((sal_uInt64) nElementSize * (sal_uInt64) nElements);\n if (nSize > 0xffffffffU)\n return 0;\n else\n return (sal_uInt32) nSize;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\ninline uno_Sequence * createEmptySequence() SAL_THROW( () )\n{\n ::osl_incrementInterlockedCount( &g_emptySeq.nRefCount );\n return &g_emptySeq;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline typelib_TypeDescriptionReference * _getVoidType()\n SAL_THROW( () )\n{\n if (! g_pVoidType)\n {\n g_pVoidType = * ::typelib_static_type_getByTypeClass( typelib_TypeClass_VOID );\n }\n ::typelib_typedescriptionreference_acquire( g_pVoidType );\n return g_pVoidType;\n}\n\n\/\/--------------------------------------------------------------------------------------------------\n#if OSL_DEBUG_LEVEL > 0\n#define CONSTRUCT_EMPTY_ANY( pAny ) \\\n(pAny)->pType = _getVoidType(); \\\n(pAny)->pData = (void *)0xdeadbeef;\n#else\n#define CONSTRUCT_EMPTY_ANY( pAny ) \\\n(pAny)->pType = _getVoidType(); \\\n(pAny)->pData = (pAny);\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n#define TYPE_ACQUIRE( pType ) \\\n ::osl_incrementInterlockedCount( &(pType)->nRefCount );\n\n\/\/--------------------------------------------------------------------------------------------------\nextern \"C\" void * binuno_queryInterface(\n void * pUnoI, typelib_TypeDescriptionReference * pDestType );\n\n\/\/--------------------------------------------------------------------------------------------------\ninline typelib_TypeDescriptionReference * _unionGetSetType(\n void * pUnion, typelib_TypeDescription * pTD )\n SAL_THROW( () )\n{\n typelib_TypeDescriptionReference * pRet = 0;\n sal_Int32 nPos;\n\n sal_Int64 * pDiscr = ((typelib_UnionTypeDescription *)pTD)->pDiscriminants;\n sal_Int64 nDiscr = *(sal_Int64 *)pUnion;\n for ( nPos = ((typelib_UnionTypeDescription *)pTD)->nMembers; nPos--; )\n {\n if (pDiscr[nPos] == nDiscr)\n {\n pRet = ((typelib_UnionTypeDescription *)pTD)->ppTypeRefs[nPos];\n break;\n }\n }\n if (nPos >= 0)\n {\n \/\/ default\n pRet = ((typelib_UnionTypeDescription *)pTD)->pDefaultTypeRef;\n }\n typelib_typedescriptionreference_acquire( pRet );\n return pRet;\n}\n\/\/--------------------------------------------------------------------------------------------------\ninline sal_Bool _type_equals(\n typelib_TypeDescriptionReference * pType1, typelib_TypeDescriptionReference * pType2 )\n SAL_THROW( () )\n{\n return (pType1 == pType2 ||\n (pType1->eTypeClass == pType2->eTypeClass &&\n pType1->pTypeName->length == pType2->pTypeName->length &&\n ::rtl_ustr_compare( pType1->pTypeName->buffer, pType2->pTypeName->buffer ) == 0));\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef __TASK_DISTRIBUTION__RUNNABLE_HPP__\n#define __TASK_DISTRIBUTION__RUNNABLE_HPP__\n\n#include <boost\/program_options.hpp>\n\n#include \"object_archive.hpp\"\n#include \"task_manager.hpp\"\n\nnamespace po = boost::program_options;\n\nnamespace TaskDistribution {\n class Runnable {\n public:\n Runnable(int argc, char* argv[], ObjectArchive<Key>& archive,\n TaskManager& task_manager);\n\n virtual void create_tasks() = 0;\n virtual void process_results() { }\n\n int process();\n void print_status();\n\n void check();\n void clean();\n void invalidate(std::string const& unit_name);\n void run();\n\n void update_unit_map();\n\n protected:\n void task_creation_handler(std::string const& name, Key const& key);\n void task_begin_handler(Key const& key);\n void task_end_handler(Key const& key);\n\n void clean_tasks();\n void invalidate_unit(std::string const& unit_name);\n void remove_result(Key const& task_key);\n size_t remove_task(Key const& task_key, KeySet& possible_removals);\n void clean_possible_removals(KeySet& possible_removals,\n KeySet const& created_tasks);\n void relocate_keys();\n void replace_key(Key const& task_key, Key const& current_key,\n Key const& new_key);\n\n struct UnitEntry {\n UnitEntry(): waiting(0), running(0), finished(0) { }\n\n KeySet keys;\n size_t waiting, running, finished;\n };\n\n std::map<std::string, UnitEntry> map_units_to_tasks_;\n\n ObjectArchive<Key>& archive_;\n TaskManager& task_manager_;\n\n po::variables_map vm;\n\n po::options_description cmd_args;\n po::options_description help_args;\n po::options_description invalidate_args;\n };\n};\n\n#endif\n<commit_msg>Added documentation to runnable.hpp.<commit_after>\/\/ For better interface with the user and control of the tasks, a standard\n\/\/ command line interface is defines in this file.\n\/\/\n\/\/ A Runnable allows 4 kinds of commands:\n\/\/ 1) check the list of tasks created;\n\/\/ 2) clean the archive;\n\/\/ 3) invalidate a given task set;\n\/\/ 4) run the tasks.\n\/\/\n\/\/ The \"check\" command only prints the status of each task type, with the number\n\/\/ of tasks waiting execution and number of tasks finished.\n\/\/\n\/\/ The \"clean\" command deletes everything from the archive that isn't used by\n\/\/ the tasks provided. For instance, if some task isn't performed anymore, it\n\/\/ may leave some debree inside the archive which occupies space, slows start-up\n\/\/ and isn't useful. The command deletes these entries and re-arranges the keys\n\/\/ to be occupy new free slots.\n\/\/\n\/\/ The \"invalidate\" command MUST be used with an option \"-i\" to avoid mistakenly\n\/\/ invalidating a task set. This command deletes every result of the set and\n\/\/ every other task that depends on the original set. This should be used when\n\/\/ the implementation of a task has changed.\n\/\/\n\/\/ The \"run\" command just performs the computations, which can happen either\n\/\/ with or without MPI.\n\/\/\n\/\/ The current status of tasks is shown by commands \"check\", \"clean\" and\n\/\/ \"invalidate\". The command \"run\" re-prints the table as each task is\n\/\/ performed, allowing the user to keep track. The name used to print the table\n\/\/ is the name associated with the computing unit.\n\/\/\n\/\/ The user must inherit the class described here and provide:\n\/\/ 1) the method \"create_tasks()\", which just creates all tasks to be computed;\n\/\/ 2) the method \"process_results()\" is optional, and is called after all tasks\n\/\/ are computed and every time the class is run.\n\/\/\n\/\/ For an example on how to use it, check the file example\/example.cpp.\n\n#ifndef __TASK_DISTRIBUTION__RUNNABLE_HPP__\n#define __TASK_DISTRIBUTION__RUNNABLE_HPP__\n\n#include <boost\/program_options.hpp>\n\n#include \"object_archive.hpp\"\n#include \"task_manager.hpp\"\n\nnamespace po = boost::program_options;\n\nnamespace TaskDistribution {\n class Runnable {\n public:\n Runnable(int argc, char* argv[], ObjectArchive<Key>& archive,\n TaskManager& task_manager);\n\n \/\/ Creates the tasks that must be computed.\n virtual void create_tasks() = 0;\n\n \/\/ Process the results of the tasks.\n virtual void process_results() { }\n\n \/\/ Interprets the command line arguments and returns 0 if everything was\n \/\/ OK.\n int process();\n\n \/\/ Creates the metadata displayed on the tasks table. This should be\n \/\/ called after create_tasks().\n void create_unit_map();\n\n \/\/ Prints the tasks status. This should be called after create_unit_map().\n void print_status();\n\n \/\/ Performs the check command.\n void check();\n\n \/\/ Performs the clean command.\n void clean();\n\n \/\/ Performs the invalidate command for a given unit name.\n void invalidate(std::string const& unit_name);\n\n \/\/ Performs the run command.\n void run();\n\n protected:\n \/\/ Handlers given to TaskManager to get feedback about what is happening\n \/\/ with the tasks.\n void task_creation_handler(std::string const& name, Key const& key);\n void task_begin_handler(Key const& key);\n void task_end_handler(Key const& key);\n\n \/\/ Removes everything from the archive that isn't used by the current\n \/\/ known tasks.\n void clean_tasks();\n\n \/\/ Invalidate all tasks of the given unit name.\n void invalidate_unit(std::string const& unit_name);\n\n \/\/ Removes the result associated with the given task and all its children.\n void remove_result(Key const& task_key);\n\n \/\/ Removes everything possible from a task and adds the rest to the set of\n \/\/ possible removals, as some data may be shared by multiple tasks.\n size_t remove_task(Key const& task_key, KeySet& possible_removals);\n\n \/\/ Remove everything from the set of possible removals that are used by\n \/\/ the known tasks.\n void clean_possible_removals(KeySet& possible_removals,\n KeySet const& created_tasks);\n\n \/\/ Changes keys to reduce sparsity.\n void relocate_keys();\n\n \/\/ Replaces a given key by another key in a task entry, described by the\n \/\/ task key.\n void replace_key(Key const& task_key, Key const& current_key,\n Key const& new_key);\n\n \/\/ Structure to hold every information required about a given unit.\n struct UnitEntry {\n UnitEntry(): waiting(0), running(0), finished(0) { }\n\n KeySet keys;\n \/\/ Number of tasks in each state.\n size_t waiting, running, finished;\n };\n\n \/\/ Map between unit names and their entries.\n std::map<std::string, UnitEntry> map_units_to_tasks_;\n\n ObjectArchive<Key>& archive_;\n TaskManager& task_manager_;\n\n \/\/ Command line interpretation variables.\n po::variables_map vm_;\n po::options_description cmd_args_;\n po::options_description help_args_;\n po::options_description invalidate_args_;\n };\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\n#include <dirent.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include \"au\/file.h\"\n#include \"au\/string.h\"\n#include \"au\/utils.h\"\n\n#include \"au\/console\/ConsoleAutoComplete.h\" \/\/ Own interface\n\n\nnamespace au {\nchar get_last_char(std::string txt) {\n if (txt.length() == 0) {\n return 0;\n } else {\n return txt[ txt.length() - 1 ];\n }\n}\n\nConsoleAutoComplete::ConsoleAutoComplete(std::string command) {\n current_command = command;\n\n \/\/ Get all the words so far and the last word\n au::split(command, ' ', previous_words);\n if (command.length() > 0) {\n if (command[command.length() - 1] != ' ') {\n last_word = previous_words.back();\n previous_words.pop_back();\n }\n }\n add_space_if_unique_alternative = true;\n}\n\nint ConsoleAutoComplete::completingWord() {\n return previous_words.size();\n}\n\nstd::string ConsoleAutoComplete::firstWord() {\n if (previous_words.size() < 1) {\n return \"\";\n }\n return previous_words[0];\n}\n\nstd::string ConsoleAutoComplete::lastCompletedWord() {\n if (previous_words.size() > 0) {\n return previous_words[ previous_words.size() - 1 ];\n }\n return \"\";\n}\n\nstd::string ConsoleAutoComplete::secondWord() {\n if (previous_words.size() < 2) {\n return \"\";\n }\n return previous_words[1];\n}\n\nbool ConsoleAutoComplete::completingSecondWord(std::string first_word) {\n if (previous_words.size() == 1) {\n if (previous_words[0] == first_word) {\n return true;\n }\n }\n return false;\n}\n\nbool ConsoleAutoComplete::completingFirstWord() {\n return (previous_words.size() == 0);\n}\n\nbool ConsoleAutoComplete::completingSecondWord() {\n return (previous_words.size() == 1);\n}\n\nbool ConsoleAutoComplete::completingThirdWord() {\n return (previous_words.size() == 2);\n}\n\nbool ConsoleAutoComplete::completingThirdWord(std::string first_word, std::string second_word) {\n if (previous_words.size() != 2) {\n return false;\n }\n\n if (( first_word != \"*\" ) && ( previous_words[0] != first_word )) {\n return false;\n }\n if (( second_word != \"*\" ) && ( previous_words[1] != second_word )) {\n return false;\n }\n\n return true;\n}\n\nstd::string ConsoleAutoComplete::getCurrentCommand() {\n return current_command;\n}\n\nvoid ConsoleAutoComplete::add(const std::string& command) {\n add(ConsoleAutoCompleteAlternative(command));\n}\n\nvoid ConsoleAutoComplete::add(std::vector<std::string> commands) {\n for (size_t i = 0; i < commands.size(); i++) {\n add(commands[i]);\n }\n}\n\nvoid ConsoleAutoComplete::add(const std::string& label, const std::string& command, bool add_space) {\n add(ConsoleAutoCompleteAlternative(label, command, add_space));\n}\n\nvoid ConsoleAutoComplete::add(ConsoleAutoCompleteAlternative alternative) {\n if (alternative.command.length() < last_word.length()) {\n return; \/\/ Not valid candidate\n }\n \/\/ Check if it was previously included...\n for (size_t i = 0; i < last_word_alternatives.size(); i++) {\n if (last_word_alternatives[i].command == alternative.command) {\n return;\n }\n }\n\n if (strings_begin_equal(alternative.command, last_word)) {\n last_word_alternatives.push_back(alternative);\n }\n}\n\nvoid ConsoleAutoComplete::auto_complete_files(std::string file_selector) {\n std::string directory = get_directory_from_path(last_word); \/\/ By default, take the last work as the directory to go\n std::string base = path_remove_last_component(last_word);\n\n if (( base.length() > 0 ) && ( base != \"\/\" )) {\n base.append(\"\/\"); \/\/ printf(\"Last word '%s' dir='%s' base='%s'\\n\", last_word.c_str() , directory.c_str() , base.c_str() );\n }\n \/\/ Try to open directory\n DIR *dp;\n struct dirent *dirp;\n if ((dp = opendir(directory.c_str())) == NULL) {\n return; \/\/ Nothing else to do...\n }\n while ((dirp = readdir(dp)) != NULL) {\n std::string fileName = dirp->d_name;\n\n \/\/ Skip \".files\"\n if (fileName.length() > 0) {\n if (fileName[0] == '.') {\n continue; \/\/ Full path of the file\n }\n }\n std::string path = path_from_directory(directory, dirp->d_name);\n\n struct ::stat info;\n stat(path.c_str(), &info);\n\n if (S_ISREG(info.st_mode)) {\n if (string_ends(path, file_selector)) {\n \/\/ Final string to show\n size_t size = info.st_size;\n\n\n add(\n au::str(\"%s (%s)\", fileName.c_str(), au::str(size, \"B\").c_str())\n , base + fileName\n , true\n );\n }\n } else if (S_ISDIR(info.st_mode)) {\n add(fileName + \"\/\", base + fileName + \"\/\", false);\n }\n }\n\n closedir(dp);\n}\n\nvoid ConsoleAutoComplete::setHelpMessage(std::string _help_message) {\n help_message = _help_message;\n}\n\nint ConsoleAutoComplete::common_chars_in_last_word_alternative() {\n if (last_word_alternatives.size() == 0) {\n return 0;\n }\n\n int common_chars = last_word_alternatives[0].command.length();\n for (size_t i = 1; i < last_word_alternatives.size(); i++) {\n int n = getCommonChars(last_word_alternatives[i].command, last_word_alternatives[i - 1].command);\n if (n < common_chars) {\n common_chars = n;\n }\n }\n\n return common_chars;\n}\n\nstd::string ConsoleAutoComplete::stringToAppend() {\n \/\/ If no options, return the previous one...\n if (last_word_alternatives.size() == 0) {\n return \"\";\n }\n\n int last_word_length = last_word.length();\n int common_chars = common_chars_in_last_word_alternative();\n\n std::string complete_text = last_word_alternatives[0].command.substr(last_word_length,\n common_chars - last_word_length);\n\n \/\/ printf(\"Complete %s\", complete_text.c_str());\n if (last_word_alternatives.size() == 1) {\n if (last_word_alternatives[0].add_space_if_unique) {\n return complete_text + \" \";\n } else {\n return complete_text;\n }\n } else {\n return complete_text;\n }\n}\n\nstd::string ConsoleAutoComplete::getHelpMessage() {\n return help_message;\n}\n\nbool ConsoleAutoComplete::necessary_print_last_words_alternatives() {\n if (last_word_alternatives.size() == 0) {\n return false;\n }\n\n if (last_word_alternatives.size() == 1) {\n return false;\n }\n\n int last_word_length = last_word.length();\n int common_chars = common_chars_in_last_word_alternative();\n\n return (last_word_length == common_chars);\n}\n\nvoid ConsoleAutoComplete::print_last_words_alternatives() {\n if (!necessary_print_last_words_alternatives()) {\n return;\n }\n\n int columns = getTerminalColumns();\n int max_length = 0;\n for (size_t i = 0; i < last_word_alternatives.size(); i++) {\n int n = last_word_alternatives[i].label.length();\n if (n > max_length) {\n max_length = n;\n }\n }\n\n int num_words_per_row = columns \/ ( max_length + 1 );\n if (num_words_per_row == 0) {\n num_words_per_row = 1;\n }\n for (size_t i = 0; i < last_word_alternatives.size(); i++)\n {\n \n std::ostringstream output;\n \n output << last_word_alternatives[i].bold_label( last_word );\n for ( int j = 0 ; j < ( max_length - last_word_alternatives[i].label.length() ) ; j++ )\n output << \" \";\n output << \" \";\n \n \/\/ Print command and help\n printf(\"%s\",output.str().c_str());\n \n if ((i % num_words_per_row) == (size_t)(num_words_per_row - 1)) {\n printf(\"\\n\");\n }\n }\n\n if (((last_word_alternatives.size() - 1) % num_words_per_row) != (size_t)(num_words_per_row - 1)) {\n printf(\"\\n\");\n }\n}\n}\n<commit_msg>Fix minor error for compilation in al linux platforms<commit_after>\n\n#include <dirent.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include \"au\/file.h\"\n#include \"au\/string.h\"\n#include \"au\/utils.h\"\n\n#include \"au\/console\/ConsoleAutoComplete.h\" \/\/ Own interface\n\n\nnamespace au {\nchar get_last_char(std::string txt) {\n if (txt.length() == 0) {\n return 0;\n } else {\n return txt[ txt.length() - 1 ];\n }\n}\n\nConsoleAutoComplete::ConsoleAutoComplete(std::string command) {\n current_command = command;\n\n \/\/ Get all the words so far and the last word\n au::split(command, ' ', previous_words);\n if (command.length() > 0) {\n if (command[command.length() - 1] != ' ') {\n last_word = previous_words.back();\n previous_words.pop_back();\n }\n }\n add_space_if_unique_alternative = true;\n}\n\nint ConsoleAutoComplete::completingWord() {\n return previous_words.size();\n}\n\nstd::string ConsoleAutoComplete::firstWord() {\n if (previous_words.size() < 1) {\n return \"\";\n }\n return previous_words[0];\n}\n\nstd::string ConsoleAutoComplete::lastCompletedWord() {\n if (previous_words.size() > 0) {\n return previous_words[ previous_words.size() - 1 ];\n }\n return \"\";\n}\n\nstd::string ConsoleAutoComplete::secondWord() {\n if (previous_words.size() < 2) {\n return \"\";\n }\n return previous_words[1];\n}\n\nbool ConsoleAutoComplete::completingSecondWord(std::string first_word) {\n if (previous_words.size() == 1) {\n if (previous_words[0] == first_word) {\n return true;\n }\n }\n return false;\n}\n\nbool ConsoleAutoComplete::completingFirstWord() {\n return (previous_words.size() == 0);\n}\n\nbool ConsoleAutoComplete::completingSecondWord() {\n return (previous_words.size() == 1);\n}\n\nbool ConsoleAutoComplete::completingThirdWord() {\n return (previous_words.size() == 2);\n}\n\nbool ConsoleAutoComplete::completingThirdWord(std::string first_word, std::string second_word) {\n if (previous_words.size() != 2) {\n return false;\n }\n\n if (( first_word != \"*\" ) && ( previous_words[0] != first_word )) {\n return false;\n }\n if (( second_word != \"*\" ) && ( previous_words[1] != second_word )) {\n return false;\n }\n\n return true;\n}\n\nstd::string ConsoleAutoComplete::getCurrentCommand() {\n return current_command;\n}\n\nvoid ConsoleAutoComplete::add(const std::string& command) {\n add(ConsoleAutoCompleteAlternative(command));\n}\n\nvoid ConsoleAutoComplete::add(std::vector<std::string> commands) {\n for (size_t i = 0; i < commands.size(); i++) {\n add(commands[i]);\n }\n}\n\nvoid ConsoleAutoComplete::add(const std::string& label, const std::string& command, bool add_space) {\n add(ConsoleAutoCompleteAlternative(label, command, add_space));\n}\n\nvoid ConsoleAutoComplete::add(ConsoleAutoCompleteAlternative alternative) {\n if (alternative.command.length() < last_word.length()) {\n return; \/\/ Not valid candidate\n }\n \/\/ Check if it was previously included...\n for (size_t i = 0; i < last_word_alternatives.size(); i++) {\n if (last_word_alternatives[i].command == alternative.command) {\n return;\n }\n }\n\n if (strings_begin_equal(alternative.command, last_word)) {\n last_word_alternatives.push_back(alternative);\n }\n}\n\nvoid ConsoleAutoComplete::auto_complete_files(std::string file_selector) {\n std::string directory = get_directory_from_path(last_word); \/\/ By default, take the last work as the directory to go\n std::string base = path_remove_last_component(last_word);\n\n if (( base.length() > 0 ) && ( base != \"\/\" )) {\n base.append(\"\/\"); \/\/ printf(\"Last word '%s' dir='%s' base='%s'\\n\", last_word.c_str() , directory.c_str() , base.c_str() );\n }\n \/\/ Try to open directory\n DIR *dp;\n struct dirent *dirp;\n if ((dp = opendir(directory.c_str())) == NULL) {\n return; \/\/ Nothing else to do...\n }\n while ((dirp = readdir(dp)) != NULL) {\n std::string fileName = dirp->d_name;\n\n \/\/ Skip \".files\"\n if (fileName.length() > 0) {\n if (fileName[0] == '.') {\n continue; \/\/ Full path of the file\n }\n }\n std::string path = path_from_directory(directory, dirp->d_name);\n\n struct ::stat info;\n stat(path.c_str(), &info);\n\n if (S_ISREG(info.st_mode)) {\n if (string_ends(path, file_selector)) {\n \/\/ Final string to show\n size_t size = info.st_size;\n\n\n add(\n au::str(\"%s (%s)\", fileName.c_str(), au::str(size, \"B\").c_str())\n , base + fileName\n , true\n );\n }\n } else if (S_ISDIR(info.st_mode)) {\n add(fileName + \"\/\", base + fileName + \"\/\", false);\n }\n }\n\n closedir(dp);\n}\n\nvoid ConsoleAutoComplete::setHelpMessage(std::string _help_message) {\n help_message = _help_message;\n}\n\nint ConsoleAutoComplete::common_chars_in_last_word_alternative() {\n if (last_word_alternatives.size() == 0) {\n return 0;\n }\n\n int common_chars = last_word_alternatives[0].command.length();\n for (size_t i = 1; i < last_word_alternatives.size(); i++) {\n int n = getCommonChars(last_word_alternatives[i].command, last_word_alternatives[i - 1].command);\n if (n < common_chars) {\n common_chars = n;\n }\n }\n\n return common_chars;\n}\n\nstd::string ConsoleAutoComplete::stringToAppend() {\n \/\/ If no options, return the previous one...\n if (last_word_alternatives.size() == 0) {\n return \"\";\n }\n\n int last_word_length = last_word.length();\n int common_chars = common_chars_in_last_word_alternative();\n\n std::string complete_text = last_word_alternatives[0].command.substr(last_word_length,\n common_chars - last_word_length);\n\n \/\/ printf(\"Complete %s\", complete_text.c_str());\n if (last_word_alternatives.size() == 1) {\n if (last_word_alternatives[0].add_space_if_unique) {\n return complete_text + \" \";\n } else {\n return complete_text;\n }\n } else {\n return complete_text;\n }\n}\n\nstd::string ConsoleAutoComplete::getHelpMessage() {\n return help_message;\n}\n\nbool ConsoleAutoComplete::necessary_print_last_words_alternatives() {\n if (last_word_alternatives.size() == 0) {\n return false;\n }\n\n if (last_word_alternatives.size() == 1) {\n return false;\n }\n\n int last_word_length = last_word.length();\n int common_chars = common_chars_in_last_word_alternative();\n\n return (last_word_length == common_chars);\n}\n\nvoid ConsoleAutoComplete::print_last_words_alternatives() {\n if (!necessary_print_last_words_alternatives()) {\n return;\n }\n\n int columns = getTerminalColumns();\n int max_length = 0;\n for (size_t i = 0; i < last_word_alternatives.size(); i++) {\n int n = last_word_alternatives[i].label.length();\n if (n > max_length) {\n max_length = n;\n }\n }\n\n int num_words_per_row = columns \/ ( max_length + 1 );\n if (num_words_per_row == 0) {\n num_words_per_row = 1;\n }\n for (size_t i = 0; i < last_word_alternatives.size(); i++)\n {\n \n std::ostringstream output;\n \n output << last_word_alternatives[i].bold_label( last_word );\n for ( int j = 0 ; j < (int)( max_length - last_word_alternatives[i].label.length() ) ; j++ )\n output << \" \";\n output << \" \";\n \n \/\/ Print command and help\n printf(\"%s\",output.str().c_str());\n \n if ((i % num_words_per_row) == (size_t)(num_words_per_row - 1)) {\n printf(\"\\n\");\n }\n }\n\n if (((last_word_alternatives.size() - 1) % num_words_per_row) != (size_t)(num_words_per_row - 1)) {\n printf(\"\\n\");\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstdint>\n\nnamespace stx {\n\nnamespace hash_type {\n\nstruct fnv_1a_64bit {\n\tusing value_type = uint64_t;\n\tusing state_type = uint64_t;\n\n\tconstexpr static uint64_t FnvPrime = 1099511628211UL;\n\tconstexpr static uint64_t OffsetBasis = 14695981039346656037UL;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn OffsetBasis;\n\t}\n\n\tconstexpr static inline\n\tstate_type increment_hash(state_type state, const char* data, std::size_t len) noexcept {\n\t\tfor (std::size_t i = 0; i < len; i++) {\n\t\t\tstate ^= data[i];\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n\n\ttemplate<std::size_t len> constexpr static inline\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tstate_type state = create_state();\n\t\tfor(char c : strn) {\n\t\t\tstate ^= c;\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n};\n\nstruct fnv_1a_32bit {\n\tusing value_type = uint32_t;\n\tusing state_type = uint32_t;\n\n\tconstexpr static uint32_t FnvPrime = 16777619U;\n\tconstexpr static uint32_t OffsetBasis = 2166136261U;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn OffsetBasis;\n\t}\n\n\tconstexpr static\n\tstate_type increment_hash(state_type state, const char* data, std::size_t len) noexcept {\n\t\tfor (std::size_t i = 0; i < len; i++) {\n\t\t\tstate ^= data[i];\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n\n\ttemplate<std::size_t len> constexpr static\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tstate_type state = create_state();\n\t\tfor(char c : strn) {\n\t\t\tstate ^= c;\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n};\n\nstruct fnv_1a_32bit_xor_folded {\n\tusing value_type = uint16_t;\n\tusing state_type = typename fnv_1a_32bit::state_type;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn fnv_1a_32bit::create_state();\n\t}\n\n\tconstexpr static inline\n\tstate_type increment_hash(const state_type& state, const char* data, std::size_t len) noexcept {\n\t\treturn fnv_1a_32bit::increment_hash(state, data, len);\n\t}\n\n\tconstexpr static inline\n\tvalue_type collapse_hash(const state_type& state) noexcept {\n\t\treturn ((state << 16) ^ state);\n\t}\n\n\ttemplate<std::size_t len> constexpr static inline\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tvalue_type val = fnv_1a_32bit::constexpr_hash_strn(strn);\n\t\treturn ((val << 16) ^ val);\n\t}\n};\n\nusing fast64 = fnv_1a_64bit;\nusing fast32 = fnv_1a_32bit;\nusing fast = fnv_1a_64bit;\n\nusing default_hash = fast64;\n\n} \/\/ namespace hash_type\n\n\n\ntemplate<typename hashtype = hash_type::default_hash>\nstruct basic_hash {\n\tusing value_type = typename hashtype::value_type;\n\tusing state_type = typename hashtype::state_type;\n\n\tvalue_type value;\n\n\tinline\n\toperator value_type() const noexcept { return value; }\n};\n\ntemplate<typename hashtype = hash_type::default_hash>\nstruct basic_symbol {\n\tconst typename hashtype::value_type hash;\n\tconst char* value;\n\tconst std::size_t length;\n\n\ttemplate<std::size_t len> constexpr \/\/ implicit\n\tbasic_symbol(const char (&strn)[len]) :\n\t\thash(hashtype::constexpr_hash_strn(strn)),\n\t\tvalue(strn),\n\t\tlength(len)\n\t{}\n};\n\nusing hash = basic_hash<>;\nusing symbol = basic_symbol<>;\n\nusing hash16 = basic_hash<hash_type::fnv_1a_32bit_xor_folded>;\nusing symbol16 = basic_symbol<hash_type::fnv_1a_32bit_xor_folded>;\n\nusing hash32 = basic_hash<hash_type::fnv_1a_32bit>;\nusing symbol32 = basic_symbol<hash_type::fnv_1a_32bit>;\n\nusing hash64 = basic_hash<hash_type::fnv_1a_64bit>;\nusing symbol64 = basic_symbol<hash_type::fnv_1a_64bit>;\n\n} \/\/ namespace stx\n\nnamespace std {\n\ntemplate<typename T>\nstruct hash;\n\ntemplate<typename H>\nstruct hash<::stx::basic_symbol<H>> {\n\tsize_t operator()(const ::stx::basic_symbol<H>& sym) const noexcept {\n\t\treturn sym.hash;\n\t}\n};\n\ntemplate<typename H>\nstruct hash<stx::basic_hash<H>> {\n\tsize_t operator()(const stx::basic_hash<H>& h) const noexcept {\n\t\treturn h.value;\n\t}\n};\n\n} \/\/ namespace std\n<commit_msg>Further implemented hash.hpp (e.g. added finalize_hash everywhere)<commit_after>#pragma once\n\n#include <cstdint>\n\nnamespace stx {\n\nnamespace hash_type {\n\nstruct fnv_1a_64bit {\n\tusing value_type = uint64_t;\n\tusing state_type = uint64_t;\n\n\tconstexpr static uint64_t FnvPrime = 1099511628211UL;\n\tconstexpr static uint64_t OffsetBasis = 14695981039346656037UL;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn OffsetBasis;\n\t}\n\n\tconstexpr static inline\n\tstate_type increment_hash(state_type state, const char* data, std::size_t len) noexcept {\n\t\tfor (std::size_t i = 0; i < len; i++) {\n\t\t\tstate ^= data[i];\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n\n\tconstexpr static inline\n\tvalue_type finalize_hash(const state_type& state) noexcept {\n\t\treturn state;\n\t}\n\n\ttemplate<std::size_t len> constexpr static inline\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tstate_type state = create_state();\n\t\tfor(char c : strn) {\n\t\t\tstate ^= c;\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n};\n\nstruct fnv_1a_32bit {\n\tusing value_type = uint32_t;\n\tusing state_type = uint32_t;\n\n\tconstexpr static uint32_t FnvPrime = 16777619U;\n\tconstexpr static uint32_t OffsetBasis = 2166136261U;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn OffsetBasis;\n\t}\n\n\tconstexpr static\n\tstate_type increment_hash(state_type state, const char* data, std::size_t len) noexcept {\n\t\tfor (std::size_t i = 0; i < len; i++) {\n\t\t\tstate ^= data[i];\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n\n\tconstexpr static inline\n\tvalue_type finalize_hash(const state_type& state) noexcept {\n\t\treturn state;\n\t}\n\n\ttemplate<std::size_t len> constexpr static\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tstate_type state = create_state();\n\t\tfor(char c : strn) {\n\t\t\tstate ^= c;\n\t\t\tstate *= FnvPrime;\n\t\t}\n\t\treturn state;\n\t}\n};\n\nstruct fnv_1a_32bit_xor_folded {\n\tusing value_type = uint16_t;\n\tusing state_type = typename fnv_1a_32bit::state_type;\n\n\tconstexpr static inline\n\tstate_type create_state() noexcept {\n\t\treturn fnv_1a_32bit::create_state();\n\t}\n\n\tconstexpr static inline\n\tstate_type increment_hash(const state_type& state, const char* data, std::size_t len) noexcept {\n\t\treturn fnv_1a_32bit::increment_hash(state, data, len);\n\t}\n\n\tconstexpr static inline\n\tvalue_type finalize_hash(const state_type& state) noexcept {\n\t\treturn ((state << 16) ^ state);\n\t}\n\n\ttemplate<std::size_t len> constexpr static inline\n\tvalue_type constexpr_hash_strn(const char (&strn)[len]) noexcept {\n\t\tvalue_type val = fnv_1a_32bit::constexpr_hash_strn(strn);\n\t\treturn ((val << 16) ^ val);\n\t}\n};\n\nusing fast64 = fnv_1a_64bit;\nusing fast32 = fnv_1a_32bit;\nusing fast = fnv_1a_64bit;\n\nusing default_hash = fast64;\n\n} \/\/ namespace hash_type\n\n\n\ntemplate<typename hashtype = hash_type::default_hash>\nstruct basic_hash {\n\tusing value_type = typename hashtype::value_type;\n\tusing state_type = typename hashtype::state_type;\n\n\tvalue_type value;\n\n\tinline\n\toperator value_type() const noexcept { return value; }\n};\n\ntemplate<typename hashtype = hash_type::default_hash>\nclass basic_symbol {\n\tusing Tself = basic_symbol<hashtype>;\n\tusing hash_value = typename hashtype::value_type;\n\n\tconstexpr inline\n\tbasic_symbol(const char* v, std::size_t len, hash_value h) :\n\t\thash(h),\n\t\tvalue(v),\n\t\tlength(len)\n\t{}\npublic:\n\tconst hash_value hash;\n\tconst char* value;\n\tconst std::size_t length;\n\n\ttemplate<std::size_t len> constexpr \/\/ implicit\n\tbasic_symbol(const char (&strn)[len]) :\n\t\thash(hashtype::constexpr_hash_strn(strn)),\n\t\tvalue(strn),\n\t\tlength(len)\n\t{}\n\n\tconstexpr inline\n\tstatic Tself unsafe_construct(const char* data, std::size_t len) {\n\t\tauto hash = hashtype::finalize_hash(\n\t\t\thashtype::increment_hash(\n\t\t\t\thashtype::create_state(),\n\t\t\t\tdata, len\n\t\t\t)\n\t\t);\n\t\treturn Tself(data, len, hash);\n\t}\n\n\tconstexpr inline\n\toperator const char*() const noexcept {\n\t\treturn value;\n\t}\n\n\tconstexpr inline\n\toperator hash_value() const noexcept {\n\t\treturn hash;\n\t}\n};\n\nusing hash = basic_hash<>;\nusing symbol = basic_symbol<>;\n\nusing hash16 = basic_hash<hash_type::fnv_1a_32bit_xor_folded>;\nusing symbol16 = basic_symbol<hash_type::fnv_1a_32bit_xor_folded>;\n\nusing hash32 = basic_hash<hash_type::fnv_1a_32bit>;\nusing symbol32 = basic_symbol<hash_type::fnv_1a_32bit>;\n\nusing hash64 = basic_hash<hash_type::fnv_1a_64bit>;\nusing symbol64 = basic_symbol<hash_type::fnv_1a_64bit>;\n\nconstexpr inline\nsymbol operator \"\" _sym(const char* strn, std::size_t len) {\n\treturn symbol::unsafe_construct(strn, len);\n}\n\n} \/\/ namespace stx\n\nnamespace std {\n\ntemplate<typename T>\nstruct hash;\n\ntemplate<typename H>\nstruct hash<::stx::basic_symbol<H>> {\n\tsize_t operator()(const ::stx::basic_symbol<H>& sym) const noexcept {\n\t\treturn sym.hash;\n\t}\n};\n\ntemplate<typename H>\nstruct hash<stx::basic_hash<H>> {\n\tsize_t operator()(const stx::basic_hash<H>& h) const noexcept {\n\t\treturn h.value;\n\t}\n};\n\n} \/\/ namespace std\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by david on 2018-10-30.\n\/\/\n\n#include \"arpack_solver.h\"\n#include \"matrix_product_dense.h\"\n#include \"matrix_product_hamiltonian.h\"\n#include \"matrix_product_sparse.h\"\n#include <general\/nmspc_sfinae.h>\n\n#if defined(_MKL_LAPACK_H_)\n #error MKL_LAPACK IS NOT SUPPOSED TO BE DEFINED HERE\n#endif\n\n#if defined(LAPACK_H)\n #error LAPACK IS NOT SUPPOSED TO BE DEFINED HERE\n#endif\n\n#if defined(__clang__)\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Woverloaded-virtual\"\n#elif defined(__GNUC__) || defined(__GNUG__)\n#endif\n\n#if __has_include(<arpackpp\/arcomp.h>)\n #include <arpackpp\/arcomp.h>\n #include <arpackpp\/ardnsmat.h>\n #include <arpackpp\/ardscomp.h>\n #include <arpackpp\/arsnsym.h>\n #include <arpackpp\/arssym.h>\n#elif __has_include(<arpack++\/arcomp.h>)\n #include <arpack++\/ardnsmat.h>\n #include <arpack++\/ardscomp.h>\n #include <arpack++\/arsnsym.h>\n #include <arpack++\/arssym.h>\n#else\n #error Could not include arpack headers correctly\n#endif\n\n#if defined(__clang__)\n \/\/ turn the warnings back on\n #pragma clang diagnostic pop\n#elif defined(__GNUC__) || defined(__GNUG__)\n#endif\n\nnamespace tc = sfinae;\nusing namespace eig;\n\ntemplate<typename MatrixType>\neig::arpack_solver<MatrixType>::arpack_solver(MatrixType &matrix_, eig::settings &config_, eig::solution &result_, Scalar *residual_)\n : matrix(matrix_), config(config_), result(result_), residual(residual_) {\n t_sol.set_properties(profile_arpack, 10, \"Time iterating \");\n t_get.set_properties(profile_arpack, 10, \"Time getting result\");\n t_sub.set_properties(profile_arpack, 10, \"Time subtracting\");\n t_all.set_properties(profile_arpack, 10, \"Time doing all \");\n nev_internal = std::min(matrix.rows() \/ 2, static_cast<int>(config.eigMaxNev.value()));\n ncv_internal = static_cast<int>(std::max(config.eigMaxNcv.value(), 2 + config.eigMaxNev.value()));\n ncv_internal = std::min(ncv_internal, matrix.rows());\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs() {\n auto loglevel = tools::Logger::getLogLevel(eig::log);\n eig::log = tools::Logger::setLogger(\"eigs\", loglevel);\n\n result.reset();\n nev_internal = std::min(matrix.rows() \/ 2, static_cast<int>(config.eigMaxNev.value()));\n ncv_internal = static_cast<int>(std::max(config.eigMaxNcv.value(), 2 + config.eigMaxNev.value()));\n ncv_internal = std::min(ncv_internal, matrix.rows());\n assert(nev_internal >= 1 and nev_internal <= matrix.rows() \/ 2);\n\n config.checkRitz();\n matrix.set_mode(config.form.value());\n matrix.set_side(config.side.value());\n\n \/\/ Dispatch to symmetric or nonsymmetric. If complex, there's only a nonsymmetric option available.\n if constexpr(std::is_same<Scalar, std::complex<double>>::value) {\n eigs_comp();\n } else {\n if(config.form == Form::SYMM)\n eigs_sym();\n else\n eigs_nsym();\n }\n eig::log = tools::Logger::setLogger(\"eigs\", loglevel);\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_sym() {\n if constexpr(std::is_same<Scalar, double>::value) {\n assert(config.form == Form::SYMM and \"ERROR: config not SYMMETRIC\");\n assert(matrix.get_form() == Form::SYMM and \"ERROR: matrix not SYMMETRIC\");\n ARSymStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), static_cast<int>(config.eigMaxIter.value()), residual);\n\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n\n } else {\n eig::log->critical(\"Called eigs_sym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n throw std::runtime_error(\"Called eigs_sym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_nsym() {\n if constexpr(std::is_same<Scalar, double>::value) {\n assert(config.form == Form::NSYM and \"ERROR: config not NSYM\");\n assert(matrix.get_form() == Form::NSYM and \"ERROR: matrix not NSYM\");\n if(nev_internal == 1) { nev_internal++; }\n\n ARNonSymStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), config.eigMaxIter.value(), residual);\n\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n } else {\n throw std::runtime_error(\"Called eigs_nsym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_comp() {\n if constexpr(std::is_same<Scalar, std::complex<double>>::value) {\n ARCompStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), config.eigMaxIter.value(), residual);\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n } else {\n throw std::runtime_error(\"Called eigs_nsym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\n\/\/\n\/\/\ntemplate<typename MatrixType>\ntemplate<typename Derived>\nvoid eig::arpack_solver<MatrixType>::find_solution(Derived &solver, eig::size_type nev) {\n if(config.compute_eigvecs) {\n eig::log->trace(\"Finding eigenvectors\");\n solver.FindEigenvectors();\n if(config.side == eig::Side::L)\n result.meta.eigvecsL_found = solver.EigenvectorsFound();\n else\n result.meta.eigvecsR_found = solver.EigenvectorsFound(); \/\/ BOOL!\n\n result.meta.eigvals_found = solver.EigenvaluesFound(); \/\/ BOOL!\n result.meta.iter = solver.GetIter();\n result.meta.n = solver.GetN();\n result.meta.nev = std::min(nev, static_cast<eig::size_type>(solver.GetNev()));\n result.meta.nev_converged = solver.ConvergedEigenvalues();\n result.meta.ncv_used = solver.GetNcv();\n result.meta.rows = solver.GetN();\n result.meta.cols = result.meta.nev;\n result.meta.counter = matrix.counter;\n result.meta.form = config.form.value();\n result.meta.type = config.type.value();\n \/* clang-format off *\/\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvals_found\", result.meta.eigvals_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsR_found\", result.meta.eigvecsR_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsL_found\", result.meta.eigvecsL_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"iter\", result.meta.iter);\n eig::log->trace(\"- {:<30} = {}\" ,\"n\", result.meta.n);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev\", result.meta.nev);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev_converged\", result.meta.nev_converged);\n eig::log->trace(\"- {:<30} = {}\" ,\"ncv_used\", result.meta.ncv_used);\n eig::log->trace(\"- {:<30} = {}\" ,\"rows\", result.meta.rows);\n eig::log->trace(\"- {:<30} = {}\" ,\"cols\", result.meta.cols);\n eig::log->trace(\"- {:<30} = {}\" ,\"counter\", result.meta.counter);\n \/* clang-format on *\/\n assert(result.meta.nev_converged >= result.meta.nev and \"Not enough eigenvalues converged\");\n assert(result.meta.eigvals_found and \"Eigenvalues were not found\");\n assert(solver.EigenvectorsFound() and \"Eigenvectors were not found\");\n\n } else {\n eig::log->trace(\"Finding eigenvalues\");\n solver.FindEigenvalues();\n result.meta.eigvals_found = solver.EigenvaluesFound();\n result.meta.iter = solver.GetIter();\n result.meta.n = solver.GetN();\n result.meta.nev = std::min(nev, static_cast<eig::size_type>(solver.GetNev()));\n result.meta.nev_converged = solver.ConvergedEigenvalues();\n result.meta.ncv_used = solver.GetNcv();\n result.meta.rows = solver.GetN();\n result.meta.cols = result.meta.nev;\n result.meta.counter = matrix.counter;\n result.meta.form = config.form.value();\n result.meta.type = config.type.value();\n \/* clang-format off *\/\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvals_found\", result.meta.eigvals_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsR_found\", result.meta.eigvecsR_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsL_found\", result.meta.eigvecsL_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"iter\", result.meta.iter);\n eig::log->trace(\"- {:<30} = {}\" ,\"n\", result.meta.n);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev\", result.meta.nev);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev_converged\", result.meta.nev_converged);\n eig::log->trace(\"- {:<30} = {}\" ,\"ncv_used\", result.meta.ncv_used);\n eig::log->trace(\"- {:<30} = {}\" ,\"rows\", result.meta.rows);\n eig::log->trace(\"- {:<30} = {}\" ,\"cols\", result.meta.cols);\n eig::log->trace(\"- {:<30} = {}\" ,\"counter\", result.meta.counter);\n \/* clang-format on *\/\n\n assert(result.meta.nev_converged >= result.meta.nev and \"Not enough eigenvalues converged\");\n assert(result.meta.eigvals_found and \"Eigenvalues were not found\");\n }\n}\n\ntemplate class eig::arpack_solver<MatrixProductDense<real>>;\ntemplate class eig::arpack_solver<MatrixProductDense<cplx>>;\ntemplate class eig::arpack_solver<MatrixProductSparse<real>>;\ntemplate class eig::arpack_solver<MatrixProductSparse<cplx>>;\ntemplate class eig::arpack_solver<MatrixProductHamiltonian<real>>;\ntemplate class eig::arpack_solver<MatrixProductHamiltonian<cplx>>;\n<commit_msg>Warn instead of assert when eigenvalue solver fails<commit_after>\/\/\n\/\/ Created by david on 2018-10-30.\n\/\/\n\n#include \"arpack_solver.h\"\n#include \"matrix_product_dense.h\"\n#include \"matrix_product_hamiltonian.h\"\n#include \"matrix_product_sparse.h\"\n#include <general\/nmspc_sfinae.h>\n\n#if defined(_MKL_LAPACK_H_)\n #error MKL_LAPACK IS NOT SUPPOSED TO BE DEFINED HERE\n#endif\n\n#if defined(LAPACK_H)\n #error LAPACK IS NOT SUPPOSED TO BE DEFINED HERE\n#endif\n\n#if defined(__clang__)\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Woverloaded-virtual\"\n#elif defined(__GNUC__) || defined(__GNUG__)\n#endif\n\n#if __has_include(<arpackpp\/arcomp.h>)\n #include <arpackpp\/arcomp.h>\n #include <arpackpp\/ardnsmat.h>\n #include <arpackpp\/ardscomp.h>\n #include <arpackpp\/arsnsym.h>\n #include <arpackpp\/arssym.h>\n#elif __has_include(<arpack++\/arcomp.h>)\n #include <arpack++\/ardnsmat.h>\n #include <arpack++\/ardscomp.h>\n #include <arpack++\/arsnsym.h>\n #include <arpack++\/arssym.h>\n#else\n #error Could not include arpack headers correctly\n#endif\n\n#if defined(__clang__)\n \/\/ turn the warnings back on\n #pragma clang diagnostic pop\n#elif defined(__GNUC__) || defined(__GNUG__)\n#endif\n\nnamespace tc = sfinae;\nusing namespace eig;\n\ntemplate<typename MatrixType>\neig::arpack_solver<MatrixType>::arpack_solver(MatrixType &matrix_, eig::settings &config_, eig::solution &result_, Scalar *residual_)\n : matrix(matrix_), config(config_), result(result_), residual(residual_) {\n t_sol.set_properties(profile_arpack, 10, \"Time iterating \");\n t_get.set_properties(profile_arpack, 10, \"Time getting result\");\n t_sub.set_properties(profile_arpack, 10, \"Time subtracting\");\n t_all.set_properties(profile_arpack, 10, \"Time doing all \");\n nev_internal = std::min(matrix.rows() \/ 2, static_cast<int>(config.eigMaxNev.value()));\n ncv_internal = static_cast<int>(std::max(config.eigMaxNcv.value(), 2 + config.eigMaxNev.value()));\n ncv_internal = std::min(ncv_internal, matrix.rows());\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs() {\n auto loglevel = tools::Logger::getLogLevel(eig::log);\n eig::log = tools::Logger::setLogger(\"eigs\", loglevel);\n\n result.reset();\n nev_internal = std::min(matrix.rows() \/ 2, static_cast<int>(config.eigMaxNev.value()));\n ncv_internal = static_cast<int>(std::max(config.eigMaxNcv.value(), 2 + config.eigMaxNev.value()));\n ncv_internal = std::min(ncv_internal, matrix.rows());\n assert(nev_internal >= 1 and nev_internal <= matrix.rows() \/ 2);\n\n config.checkRitz();\n matrix.set_mode(config.form.value());\n matrix.set_side(config.side.value());\n\n \/\/ Dispatch to symmetric or nonsymmetric. If complex, there's only a nonsymmetric option available.\n if constexpr(std::is_same<Scalar, std::complex<double>>::value) {\n eigs_comp();\n } else {\n if(config.form == Form::SYMM)\n eigs_sym();\n else\n eigs_nsym();\n }\n eig::log = tools::Logger::setLogger(\"eigs\", loglevel);\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_sym() {\n if constexpr(std::is_same<Scalar, double>::value) {\n assert(config.form == Form::SYMM and \"ERROR: config not SYMMETRIC\");\n assert(matrix.get_form() == Form::SYMM and \"ERROR: matrix not SYMMETRIC\");\n ARSymStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), static_cast<int>(config.eigMaxIter.value()), residual);\n\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n\n } else {\n eig::log->critical(\"Called eigs_sym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n throw std::runtime_error(\"Called eigs_sym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_nsym() {\n if constexpr(std::is_same<Scalar, double>::value) {\n assert(config.form == Form::NSYM and \"ERROR: config not NSYM\");\n assert(matrix.get_form() == Form::NSYM and \"ERROR: matrix not NSYM\");\n if(nev_internal == 1) { nev_internal++; }\n\n ARNonSymStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), config.eigMaxIter.value(), residual);\n\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n } else {\n throw std::runtime_error(\"Called eigs_nsym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\ntemplate<typename MatrixType>\nvoid eig::arpack_solver<MatrixType>::eigs_comp() {\n if constexpr(std::is_same<Scalar, std::complex<double>>::value) {\n ARCompStdEig<double, MatrixType> solver(matrix.rows(), nev_internal, &matrix, &MatrixType::MultAx, config.get_ritz_string().data(), ncv_internal,\n config.eigThreshold.value(), config.eigMaxIter.value(), residual);\n if(config.sigma) {\n if(config.shift_invert == Shinv::ON) {\n if constexpr(MatrixType::can_shift_invert) {\n eig::log->trace(\"Enabling shift-invert mode with sigma = {}\", std::real(config.sigma.value()));\n \/\/ Calculate shift-inverse mat-vec mult operator by LU decomposition\n matrix.set_shift(config.sigma.value());\n matrix.FactorOP();\n if constexpr(std::is_same_v<Scalar, cplx>) solver.SetShiftInvertMode(config.sigma.value(), &matrix, &MatrixType::MultOPv);\n if constexpr(std::is_same_v<Scalar, real>) solver.SetShiftInvertMode(std::real(config.sigma.value()), &matrix, &MatrixType::MultOPv);\n } else\n throw std::runtime_error(\"Tried to shift-invert an incompatible matrix\");\n } else {\n if constexpr(MatrixType::can_shift) {\n eig::log->trace(\"Setting shift with sigma = {}\", std::real(config.sigma.value()));\n matrix.set_shift(config.sigma.value());\n } else\n throw std::runtime_error(\"Tried to apply shift on an incompatible matrix\");\n }\n }\n find_solution(solver, config.eigMaxNev.value());\n copy_solution(solver);\n } else {\n throw std::runtime_error(\"Called eigs_nsym() with wrong type: \" + std::string(tc::type_name<MatrixType>()));\n }\n}\n\n\/\/\n\/\/\ntemplate<typename MatrixType>\ntemplate<typename Derived>\nvoid eig::arpack_solver<MatrixType>::find_solution(Derived &solver, eig::size_type nev) {\n if(config.compute_eigvecs) {\n eig::log->trace(\"Finding eigenvectors\");\n solver.FindEigenvectors();\n if(config.side == eig::Side::L)\n result.meta.eigvecsL_found = solver.EigenvectorsFound();\n else\n result.meta.eigvecsR_found = solver.EigenvectorsFound(); \/\/ BOOL!\n\n result.meta.eigvals_found = solver.EigenvaluesFound(); \/\/ BOOL!\n result.meta.iter = solver.GetIter();\n result.meta.n = solver.GetN();\n result.meta.nev = std::min(nev, static_cast<eig::size_type>(solver.GetNev()));\n result.meta.nev_converged = solver.ConvergedEigenvalues();\n result.meta.ncv_used = solver.GetNcv();\n result.meta.rows = solver.GetN();\n result.meta.cols = result.meta.nev;\n result.meta.counter = matrix.counter;\n result.meta.form = config.form.value();\n result.meta.type = config.type.value();\n \/* clang-format off *\/\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvals_found\", result.meta.eigvals_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsR_found\", result.meta.eigvecsR_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsL_found\", result.meta.eigvecsL_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"iter\", result.meta.iter);\n eig::log->trace(\"- {:<30} = {}\" ,\"n\", result.meta.n);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev\", result.meta.nev);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev_converged\", result.meta.nev_converged);\n eig::log->trace(\"- {:<30} = {}\" ,\"ncv_used\", result.meta.ncv_used);\n eig::log->trace(\"- {:<30} = {}\" ,\"rows\", result.meta.rows);\n eig::log->trace(\"- {:<30} = {}\" ,\"cols\", result.meta.cols);\n eig::log->trace(\"- {:<30} = {}\" ,\"counter\", result.meta.counter);\n \/* clang-format on *\/\n\/\/ assert(result.meta.nev_converged >= result.meta.nev and \"Not enough eigenvalues converged\");\n\/\/ assert(result.meta.eigvals_found and \"Eigenvalues were not found\");\n if(result.meta.nev_converged < result.meta.nev) eig::log->warn(\"Not enough eigenvalues converged\");\n if(not result.meta.eigvals_found) eig::log->warn(\"Eigenvalues were not found\");\n if(not solver.EigenvectorsFound()) eig::log->warn(\"Eigenvectors were not found\");\n } else {\n eig::log->trace(\"Finding eigenvalues\");\n solver.FindEigenvalues();\n result.meta.eigvals_found = solver.EigenvaluesFound();\n result.meta.iter = solver.GetIter();\n result.meta.n = solver.GetN();\n result.meta.nev = std::min(nev, static_cast<eig::size_type>(solver.GetNev()));\n result.meta.nev_converged = solver.ConvergedEigenvalues();\n result.meta.ncv_used = solver.GetNcv();\n result.meta.rows = solver.GetN();\n result.meta.cols = result.meta.nev;\n result.meta.counter = matrix.counter;\n result.meta.form = config.form.value();\n result.meta.type = config.type.value();\n \/* clang-format off *\/\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvals_found\", result.meta.eigvals_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsR_found\", result.meta.eigvecsR_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"eigvecsL_found\", result.meta.eigvecsL_found);\n eig::log->trace(\"- {:<30} = {}\" ,\"iter\", result.meta.iter);\n eig::log->trace(\"- {:<30} = {}\" ,\"n\", result.meta.n);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev\", result.meta.nev);\n eig::log->trace(\"- {:<30} = {}\" ,\"nev_converged\", result.meta.nev_converged);\n eig::log->trace(\"- {:<30} = {}\" ,\"ncv_used\", result.meta.ncv_used);\n eig::log->trace(\"- {:<30} = {}\" ,\"rows\", result.meta.rows);\n eig::log->trace(\"- {:<30} = {}\" ,\"cols\", result.meta.cols);\n eig::log->trace(\"- {:<30} = {}\" ,\"counter\", result.meta.counter);\n \/* clang-format on *\/\n\n\/\/ assert(result.meta.nev_converged >= result.meta.nev and \"Not enough eigenvalues converged\");\n\/\/ assert(result.meta.eigvals_found and \"Eigenvalues were not found\");\n if(result.meta.nev_converged < result.meta.nev) eig::log->warn(\"Not enough eigenvalues converged\");\n if(not result.meta.eigvals_found) eig::log->warn(\"Eigenvalues were not found\");\n }\n}\n\ntemplate class eig::arpack_solver<MatrixProductDense<real>>;\ntemplate class eig::arpack_solver<MatrixProductDense<cplx>>;\ntemplate class eig::arpack_solver<MatrixProductSparse<real>>;\ntemplate class eig::arpack_solver<MatrixProductSparse<cplx>>;\ntemplate class eig::arpack_solver<MatrixProductHamiltonian<real>>;\ntemplate class eig::arpack_solver<MatrixProductHamiltonian<cplx>>;\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"debugutil_p.h\"\n\n#include <QEventLoop>\n#include <QTimer>\n\nbool QQmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {\n QEventLoop loop;\n QTimer timer;\n timer.setSingleShot(true);\n QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));\n QObject::connect(receiver, member, &loop, SLOT(quit()));\n timer.start(timeout);\n loop.exec();\n return timer.isActive();\n}\n\nQQmlDebugTestClient::QQmlDebugTestClient(const QString &s, QQmlDebugConnection *c)\n : QQmlDebugClient(s, c)\n{\n}\n\nQByteArray QQmlDebugTestClient::waitForResponse()\n{\n lastMsg.clear();\n QQmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));\n if (lastMsg.isEmpty()) {\n qWarning() << \"tst_QQmlDebugTestClient: no response from server!\";\n return QByteArray();\n }\n return lastMsg;\n}\n\nvoid QQmlDebugTestClient::stateChanged(State stat)\n{\n QCOMPARE(stat, state());\n emit stateHasChanged();\n}\n\nvoid QQmlDebugTestClient::messageReceived(const QByteArray &ba)\n{\n lastMsg = ba;\n emit serverMessage(ba);\n}\n\nQQmlDebugProcess::QQmlDebugProcess(const QString &executable)\n : m_executable(executable)\n , m_started(false)\n{\n m_process.setProcessChannelMode(QProcess::MergedChannels);\n m_timer.setSingleShot(true);\n m_timer.setInterval(5000);\n connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(processAppOutput()));\n connect(&m_timer, SIGNAL(timeout()), &m_eventLoop, SLOT(quit()));\n}\n\nQQmlDebugProcess::~QQmlDebugProcess()\n{\n stop();\n}\n\nvoid QQmlDebugProcess::start(const QStringList &arguments)\n{\n m_mutex.lock();\n m_process.setEnvironment(m_environment);\n m_process.start(m_executable, arguments);\n m_process.waitForStarted();\n m_timer.start();\n m_mutex.unlock();\n}\n\nvoid QQmlDebugProcess::stop()\n{\n if (m_process.state() != QProcess::NotRunning) {\n m_process.kill();\n m_process.waitForFinished(5000);\n }\n}\n\nbool QQmlDebugProcess::waitForSessionStart()\n{\n if (m_process.state() != QProcess::Running) {\n qWarning() << \"Could not start up \" << m_executable;\n return false;\n }\n m_eventLoop.exec();\n\n return m_started;\n}\n\nvoid QQmlDebugProcess::setEnvironment(const QStringList &environment)\n{\n m_environment = environment;\n}\n\nQString QQmlDebugProcess::output() const\n{\n return m_output;\n}\n\nvoid QQmlDebugProcess::processAppOutput()\n{\n m_mutex.lock();\n\n QString newOutput = m_process.readAll();\n m_output.append(newOutput);\n m_outputBuffer.append(newOutput);\n\n while (true) {\n const int nlIndex = m_outputBuffer.indexOf(QLatin1Char('\\n'));\n if (nlIndex < 0) \/\/ no further complete lines\n break;\n const QString line = m_outputBuffer.left(nlIndex);\n m_outputBuffer = m_outputBuffer.right(m_outputBuffer.size() - nlIndex - 1);\n\n if (line.startsWith(\"QML debugging is enabled\")) \/\/ ignore\n continue;\n if (line.startsWith(\"QML Debugger:\")) {\n if (line.contains(\"Waiting for connection \")) {\n m_started = true;\n m_eventLoop.quit();\n continue;\n }\n if (line.contains(\"Connection established.\")) {\n continue;\n }\n }\n }\n m_mutex.unlock();\n}\n<commit_msg>irrelevant qDebug removed<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"debugutil_p.h\"\n\n#include <QEventLoop>\n#include <QTimer>\n\nbool QQmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {\n QEventLoop loop;\n QTimer timer;\n timer.setSingleShot(true);\n QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));\n QObject::connect(receiver, member, &loop, SLOT(quit()));\n timer.start(timeout);\n loop.exec();\n return timer.isActive();\n}\n\nQQmlDebugTestClient::QQmlDebugTestClient(const QString &s, QQmlDebugConnection *c)\n : QQmlDebugClient(s, c)\n{\n}\n\nQByteArray QQmlDebugTestClient::waitForResponse()\n{\n lastMsg.clear();\n QQmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));\n if (lastMsg.isEmpty()) {\n qWarning() << \"tst_QQmlDebugTestClient: no response from server!\";\n return QByteArray();\n }\n return lastMsg;\n}\n\nvoid QQmlDebugTestClient::stateChanged(State stat)\n{\n QCOMPARE(stat, state());\n emit stateHasChanged();\n}\n\nvoid QQmlDebugTestClient::messageReceived(const QByteArray &ba)\n{\n lastMsg = ba;\n emit serverMessage(ba);\n}\n\nQQmlDebugProcess::QQmlDebugProcess(const QString &executable)\n : m_executable(executable)\n , m_started(false)\n{\n m_process.setProcessChannelMode(QProcess::MergedChannels);\n m_timer.setSingleShot(true);\n m_timer.setInterval(5000);\n connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(processAppOutput()));\n connect(&m_timer, SIGNAL(timeout()), &m_eventLoop, SLOT(quit()));\n}\n\nQQmlDebugProcess::~QQmlDebugProcess()\n{\n stop();\n}\n\nvoid QQmlDebugProcess::start(const QStringList &arguments)\n{\n m_mutex.lock();\n m_process.setEnvironment(m_environment);\n m_process.start(m_executable, arguments);\n m_process.waitForStarted();\n m_timer.start();\n m_mutex.unlock();\n}\n\nvoid QQmlDebugProcess::stop()\n{\n if (m_process.state() != QProcess::NotRunning) {\n m_process.kill();\n m_process.waitForFinished(5000);\n }\n}\n\nbool QQmlDebugProcess::waitForSessionStart()\n{\n if (m_process.state() != QProcess::Running) {\n qWarning() << \"Could not start up \" << m_executable;\n return false;\n }\n m_eventLoop.exec();\n\n return m_started;\n}\n\nvoid QQmlDebugProcess::setEnvironment(const QStringList &environment)\n{\n m_environment = environment;\n}\n\nQString QQmlDebugProcess::output() const\n{\n return m_output;\n}\n\nvoid QQmlDebugProcess::processAppOutput()\n{\n m_mutex.lock();\n\n QString newOutput = m_process.readAll();\n m_output.append(newOutput);\n m_outputBuffer.append(newOutput);\n\n while (true) {\n const int nlIndex = m_outputBuffer.indexOf(QLatin1Char('\\n'));\n if (nlIndex < 0) \/\/ no further complete lines\n break;\n const QString line = m_outputBuffer.left(nlIndex);\n m_outputBuffer = m_outputBuffer.right(m_outputBuffer.size() - nlIndex - 1);\n\n if (line.startsWith(\"QML debugging is enabled\")) \/\/ ignore\n continue;\n if (line.startsWith(\"QML Debugger:\")) {\n if (line.contains(\"Waiting for connection \")) {\n m_started = true;\n m_eventLoop.quit();\n continue;\n }\n }\n }\n m_mutex.unlock();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update Ring For Android<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"CompressIndices.h\"\n\n#include <cstring>\n#include <algorithm>\n#include <Corrade\/Containers\/Array.h>\n\n#include \"Magnum\/Math\/Functions.h\"\n\nnamespace Magnum { namespace MeshTools {\n\nnamespace {\n\ntemplate<class T> inline Containers::Array<char> compress(const std::vector<UnsignedInt>& indices) {\n Containers::Array<char> buffer(indices.size()*sizeof(T));\n for(std::size_t i = 0; i != indices.size(); ++i) {\n T index = static_cast<T>(indices[i]);\n std::memcpy(buffer.begin()+i*sizeof(T), &index, sizeof(T));\n }\n\n return buffer;\n}\n\n}\n\nstd::tuple<Containers::Array<char>, Mesh::IndexType, UnsignedInt, UnsignedInt> compressIndices(const std::vector<UnsignedInt>& indices) {\n \/** @todo Performance hint when range can be represented by smaller value? *\/\n auto minmax = std::minmax_element(indices.begin(), indices.end());\n Containers::Array<char> data;\n Mesh::IndexType type;\n switch(Math::log(256, *minmax.second)) {\n case 0:\n data = compress<UnsignedByte>(indices);\n type = Mesh::IndexType::UnsignedByte;\n break;\n case 1:\n data = compress<UnsignedShort>(indices);\n type = Mesh::IndexType::UnsignedShort;\n break;\n case 2:\n case 3:\n data = compress<UnsignedInt>(indices);\n type = Mesh::IndexType::UnsignedInt;\n break;\n\n default:\n CORRADE_ASSERT(false, \"MeshTools::compressIndices(): no type able to index\" << *minmax.second << \"elements.\", {});\n }\n\n return std::make_tuple(std::move(data), type, *minmax.first, *minmax.second);\n}\n\n}}\n<commit_msg>MeshTools: const++.<commit_after>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"CompressIndices.h\"\n\n#include <cstring>\n#include <algorithm>\n#include <Corrade\/Containers\/Array.h>\n\n#include \"Magnum\/Math\/Functions.h\"\n\nnamespace Magnum { namespace MeshTools {\n\nnamespace {\n\ntemplate<class T> inline Containers::Array<char> compress(const std::vector<UnsignedInt>& indices) {\n Containers::Array<char> buffer(indices.size()*sizeof(T));\n for(std::size_t i = 0; i != indices.size(); ++i) {\n T index = static_cast<T>(indices[i]);\n std::memcpy(buffer.begin()+i*sizeof(T), &index, sizeof(T));\n }\n\n return buffer;\n}\n\n}\n\nstd::tuple<Containers::Array<char>, Mesh::IndexType, UnsignedInt, UnsignedInt> compressIndices(const std::vector<UnsignedInt>& indices) {\n \/** @todo Performance hint when range can be represented by smaller value? *\/\n const auto minmax = std::minmax_element(indices.begin(), indices.end());\n Containers::Array<char> data;\n Mesh::IndexType type;\n switch(Math::log(256, *minmax.second)) {\n case 0:\n data = compress<UnsignedByte>(indices);\n type = Mesh::IndexType::UnsignedByte;\n break;\n case 1:\n data = compress<UnsignedShort>(indices);\n type = Mesh::IndexType::UnsignedShort;\n break;\n case 2:\n case 3:\n data = compress<UnsignedInt>(indices);\n type = Mesh::IndexType::UnsignedInt;\n break;\n\n default:\n CORRADE_ASSERT(false, \"MeshTools::compressIndices(): no type able to index\" << *minmax.second << \"elements.\", {});\n }\n\n return std::make_tuple(std::move(data), type, *minmax.first, *minmax.second);\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __HIERARCHY_TEMPLATES_HPP_INCLUDED\n#define __HIERARCHY_TEMPLATES_HPP_INCLUDED\n\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy.hpp\"\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n\nnamespace hierarchy\n{\n void set_child_pointer(uint32_t childID, void* child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);\n uint32_t get_childID(std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);\n\n template<class T1>\n void bind_child_to_parent(T1 child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue)\n {\n \/\/ get childID from the parent, because every child deserves a unique ID!\n child_pointer->childID = get_childID(child_pointer_vector, free_childID_queue);\n \/\/ set pointer to the child in parent's child pointer vector so that parent knows about children's whereabouts!\n set_child_pointer(child_pointer->childID, child_pointer, child_pointer_vector, free_childID_queue);\n }\n\n template <class T1, class T2>\n void bind_child_to_new_parent(\n T1 child_pointer,\n T2 new_parent_pointer,\n std::vector<void*> &old_child_pointer_vector,\n std::queue<uint32_t> &old_free_childID_queue)\n {\n \/\/ set pointer to this child to nullptr in the old parent.\n set_child_pointer(child_pointer->childID, nullptr, old_child_pointer_vector, old_free_childID_queue);\n \/\/ set the new parent pointer.\n child_pointer->parent_pointer = new_parent_pointer;\n \/\/ bind to the new parent.\n child_pointer->bind_to_parent();\n }\n\n template<class T1>\n void delete_children(std::vector<void*> &child_pointer_vector)\n {\n for (uint32_t child_i = 0; child_i < child_pointer_vector.size(); child_i++)\n {\n delete static_cast<T1>(child_pointer_vector[child_i]);\n }\n }\n}\n\n#endif\n<commit_msg>Edited comments.<commit_after>#ifndef __HIERARCHY_TEMPLATES_HPP_INCLUDED\n#define __HIERARCHY_TEMPLATES_HPP_INCLUDED\n\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy.hpp\"\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n\nnamespace hierarchy\n{\n void set_child_pointer(uint32_t childID, void* child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);\n uint32_t get_childID(std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);\n\n template<class T1>\n void bind_child_to_parent(T1 child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue)\n {\n \/\/ If a class' instances have parents, this function must be\n \/\/ called in the constructor. The call must be done only once\n \/\/ in each constructor, usually after setting\n \/\/ `this->parent_pointer`. So, get `childID` from the parent,\n \/\/ because every child deserves a unique ID!\n child_pointer->childID = get_childID(child_pointer_vector, free_childID_queue);\n \/\/ set pointer to the child in parent's child pointer vector so that parent knows about children's whereabouts!\n set_child_pointer(child_pointer->childID, child_pointer, child_pointer_vector, free_childID_queue);\n }\n\n template <class T1, class T2>\n void bind_child_to_new_parent(\n T1 child_pointer,\n T2 new_parent_pointer,\n std::vector<void*> &old_child_pointer_vector,\n std::queue<uint32_t> &old_free_childID_queue)\n {\n \/\/ set pointer to this child to nullptr in the old parent.\n set_child_pointer(child_pointer->childID, nullptr, old_child_pointer_vector, old_free_childID_queue);\n \/\/ set the new parent pointer.\n child_pointer->parent_pointer = new_parent_pointer;\n \/\/ bind to the new parent.\n child_pointer->bind_to_parent();\n }\n\n template<class T1>\n void delete_children(std::vector<void*> &child_pointer_vector)\n {\n for (uint32_t child_i = 0; child_i < child_pointer_vector.size(); child_i++)\n {\n delete static_cast<T1>(child_pointer_vector[child_i]);\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"IRPrinter.h\"\n#include \"IROperator.h\"\n#include \"IR.h\"\n\n#include <iostream>\n#include <sstream>\n\nnamespace Halide {\n\nusing std::ostream;\nusing std::endl;\nusing std::vector;\nusing std::string;\nusing std::ostringstream;\n\nostream &operator<<(ostream &out, Type type) {\n switch (type.t) {\n case Type::Int:\n out << \"int\";\n break;\n case Type::UInt:\n out << \"uint\";\n break;\n case Type::Float:\n out << \"float\";\n break;\n default:\n assert(false && \"Malformed type\");\n }\n out << type.bits;\n if (type.width > 1) out << 'x' << type.width;\n return out;\n}\n\nostream &operator<<(ostream &stream, Expr ir) {\n if (!ir.defined()) {\n stream << \"(undefined)\";\n } else {\n Internal::IRPrinter p(stream);\n p.print(ir);\n }\n return stream;\n}\n\nnamespace Internal {\n\nvoid IRPrinter::test() {\n Type i32 = Int(32);\n Type f32 = Float(32);\n Expr x = Variable::make(Int(32), \"x\");\n Expr y = Variable::make(Int(32), \"y\");\n ostringstream expr_source;\n expr_source << (x + 3) * (y \/ 2 + 17);\n assert(expr_source.str() == \"((x + 3)*((y\/2) + 17))\");\n\n Stmt store = Store::make(\"buf\", (x * 17) \/ (x - 3), y - 1);\n Stmt for_loop = For::make(\"x\", -2, y + 2, For::Parallel, store);\n vector<Expr> args(1); args[0] = x % 3;\n Expr call = Call::make(i32, \"buf\", args, Call::Extern);\n Stmt store2 = Store::make(\"out\", call + 1, x);\n Stmt for_loop2 = For::make(\"x\", 0, y, For::Vectorized , store2);\n Stmt pipeline = Pipeline::make(\"buf\", for_loop, Stmt(), for_loop2);\n Stmt assertion = AssertStmt::make(y > 3, \"y is greater than 3\");\n Stmt block = Block::make(assertion, pipeline);\n Stmt let_stmt = LetStmt::make(\"y\", 17, block);\n Stmt allocate = Allocate::make(\"buf\", f32, 1023, let_stmt);\n\n ostringstream source;\n source << allocate;\n std::string correct_source = \\\n \"allocate buf[float32 * 1023]\\n\"\n \"let y = 17\\n\"\n \"assert((y > 3), \\\"y is greater than 3\\\")\\n\"\n \"produce buf {\\n\"\n \" parallel (x, -2, (y + 2)) {\\n\"\n \" buf[(y - 1)] = ((x*17)\/(x - 3))\\n\"\n \" }\\n\"\n \"}\\n\"\n \"vectorized (x, 0, y) {\\n\"\n \" out[x] = (buf((x % 3)) + 1)\\n\"\n \"}\\n\";\n\n if (source.str() != correct_source) {\n std::cout << \"Correct output:\" << std::endl << correct_source;\n std::cout << \"Actual output:\" << std::endl << source.str();\n assert(false);\n }\n std::cout << \"IRPrinter test passed\" << std::endl;\n}\n\nostream &operator<<(ostream &out, const For::ForType &type) {\n switch (type) {\n case For::Serial:\n out << \"for\";\n break;\n case For::Parallel:\n out << \"parallel\";\n break;\n case For::Unrolled:\n out << \"unrolled\";\n break;\n case For::Vectorized:\n out << \"vectorized\";\n break;\n default:\n assert(false && \"Malformed for type\");\n }\n return out;\n}\n\nostream &operator<<(ostream &stream, Stmt ir) {\n if (!ir.defined()) {\n stream << \"(undefined)\" << std::endl;\n } else {\n Internal::IRPrinter p(stream);\n p.print(ir);\n }\n return stream;\n}\n\nIRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {\n s.setf(std::ios::fixed, std::ios::floatfield);\n}\n\nvoid IRPrinter::print(Expr ir) {\n ir.accept(this);\n}\n\nvoid IRPrinter::print(Stmt ir) {\n ir.accept(this);\n}\n\n\nvoid IRPrinter::do_indent() {\n for (int i = 0; i < indent; i++) stream << ' ';\n}\n\nvoid IRPrinter::visit(const IntImm *op) {\n stream << op->value;\n}\n\nvoid IRPrinter::visit(const FloatImm *op) {\n stream << op->value << 'f';\n}\n\nvoid IRPrinter::visit(const Cast *op) {\n stream << op->type << '(';\n print(op->value);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Variable *op) {\n \/\/ omit the type\n \/\/ stream << op->name << \".\" << op->type;\n stream << op->name;\n}\n\nvoid IRPrinter::visit(const Add *op) {\n stream << '(';\n print(op->a);\n stream << \" + \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Sub *op) {\n stream << '(';\n print(op->a);\n stream << \" - \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Mul *op) {\n stream << '(';\n print(op->a);\n stream << \"*\";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Div *op) {\n stream << '(';\n print(op->a);\n stream << \"\/\";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Mod *op) {\n stream << '(';\n print(op->a);\n stream << \" % \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Min *op) {\n stream << \"min(\";\n print(op->a);\n stream << \", \";\n print(op->b);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Max *op) {\n stream << \"max(\";\n print(op->a);\n stream << \", \";\n print(op->b);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const EQ *op) {\n stream << '(';\n print(op->a);\n stream << \" == \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const NE *op) {\n stream << '(';\n print(op->a);\n stream << \" != \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const LT *op) {\n stream << '(';\n print(op->a);\n stream << \" < \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const LE *op) {\n stream << '(';\n print(op->a);\n stream << \" <= \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const GT *op) {\n stream << '(';\n print(op->a);\n stream << \" > \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const GE *op) {\n stream << '(';\n print(op->a);\n stream << \" >= \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const And *op) {\n stream << '(';\n print(op->a);\n stream << \" && \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Or *op) {\n stream << '(';\n print(op->a);\n stream << \" || \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Not *op) {\n stream << '!';\n print(op->a);\n}\n\nvoid IRPrinter::visit(const Select *op) {\n stream << \"select(\";\n print(op->condition);\n stream << \", \";\n print(op->true_value);\n stream << \", \";\n print(op->false_value);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Load *op) {\n stream << op->name << \"[\";\n print(op->index);\n stream << \"]\";\n}\n\nvoid IRPrinter::visit(const Ramp *op) {\n stream << \"ramp(\";\n print(op->base);\n stream << \", \";\n print(op->stride);\n stream << \", \" << op->width << \")\";\n}\n\nvoid IRPrinter::visit(const Broadcast *op) {\n stream << \"x\" << op->width << \"(\";\n print(op->value);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Call *op) {\n stream << op->name << \"(\";\n for (size_t i = 0; i < op->args.size(); i++) {\n print(op->args[i]);\n if (i < op->args.size() - 1) {\n stream << \", \";\n }\n }\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Let *op) {\n stream << \"(let \" << op->name << \" = \";\n print(op->value);\n stream << \" in \";\n print(op->body);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const LetStmt *op) {\n do_indent();\n stream << \"let \" << op->name << \" = \";\n print(op->value);\n stream << endl;\n\n print(op->body);\n}\n\nvoid IRPrinter::visit(const PrintStmt *op) {\n do_indent();\n stream << \"print(\" << op->prefix;\n for (size_t i = 0; i < op->args.size(); i++) {\n stream << \", \";\n print(op->args[i]);\n }\n stream << \")\" << endl;\n}\n\nvoid IRPrinter::visit(const AssertStmt *op) {\n do_indent();\n stream << \"assert(\";\n print(op->condition);\n stream << \", \\\"\" << op->message << \"\\\")\" << endl;\n}\n\nvoid IRPrinter::visit(const Pipeline *op) {\n\n do_indent();\n stream << \"produce \" << op->name << \" {\" << endl;\n indent += 2;\n print(op->produce);\n indent -= 2;\n\n if (op->update.defined()) {\n do_indent();\n stream << \"} update \" << op->name << \" {\" << endl;\n indent += 2;\n print(op->update);\n indent -= 2;\n }\n\n do_indent();\n stream << \"}\\n\";\n\n print(op->consume);\n\n}\n\nvoid IRPrinter::visit(const For *op) {\n\n do_indent();\n stream << op->for_type << \" (\" << op->name << \", \";\n print(op->min);\n stream << \", \";\n print(op->extent);\n stream << \") {\" << endl;\n\n indent += 2;\n print(op->body);\n indent -= 2;\n\n do_indent();\n stream << \"}\" << endl;\n}\n\nvoid IRPrinter::visit(const Store *op) {\n do_indent();\n stream << op->name << \"[\";\n print(op->index);\n stream << \"] = \";\n print(op->value);\n stream << endl;\n}\n\nvoid IRPrinter::visit(const Provide *op) {\n do_indent();\n stream << op->name << \"(\";\n for (size_t i = 0; i < op->args.size(); i++) {\n print(op->args[i]);\n if (i < op->args.size() - 1) stream << \", \";\n }\n stream << \") = \";\n print(op->value);\n stream << endl;\n}\n\nvoid IRPrinter::visit(const Allocate *op) {\n do_indent();\n stream << \"allocate \" << op->name << \"[\" << op->type << \" * \";\n print(op->size);\n stream << \"]\" << endl;\n print(op->body);\n}\n\nvoid IRPrinter::visit(const Free *op) {\n do_indent();\n stream << \"free \" << op->name << endl;\n}\n\nvoid IRPrinter::visit(const Realize *op) {\n do_indent();\n stream << \"realize \" << op->name << \"(\";\n for (size_t i = 0; i < op->bounds.size(); i++) {\n stream << \"[\";\n print(op->bounds[i].min);\n stream << \", \";\n print(op->bounds[i].extent);\n stream << \"]\";\n if (i < op->bounds.size() - 1) stream << \", \";\n }\n stream << \") {\" << endl;\n\n indent += 2;\n print(op->body);\n indent -= 2;\n\n do_indent();\n stream << \"}\" << endl;\n}\n\nvoid IRPrinter::visit(const Block *op) {\n print(op->first);\n if (op->rest.defined()) print(op->rest);\n}\n\n\n}}\n<commit_msg>Remove default cases from switch statements.<commit_after>#include \"IRPrinter.h\"\n#include \"IROperator.h\"\n#include \"IR.h\"\n\n#include <iostream>\n#include <sstream>\n\nnamespace Halide {\n\nusing std::ostream;\nusing std::endl;\nusing std::vector;\nusing std::string;\nusing std::ostringstream;\n\nostream &operator<<(ostream &out, Type type) {\n switch (type.t) {\n case Type::Int:\n out << \"int\";\n break;\n case Type::UInt:\n out << \"uint\";\n break;\n case Type::Float:\n out << \"float\";\n break;\n }\n out << type.bits;\n if (type.width > 1) out << 'x' << type.width;\n return out;\n}\n\nostream &operator<<(ostream &stream, Expr ir) {\n if (!ir.defined()) {\n stream << \"(undefined)\";\n } else {\n Internal::IRPrinter p(stream);\n p.print(ir);\n }\n return stream;\n}\n\nnamespace Internal {\n\nvoid IRPrinter::test() {\n Type i32 = Int(32);\n Type f32 = Float(32);\n Expr x = Variable::make(Int(32), \"x\");\n Expr y = Variable::make(Int(32), \"y\");\n ostringstream expr_source;\n expr_source << (x + 3) * (y \/ 2 + 17);\n assert(expr_source.str() == \"((x + 3)*((y\/2) + 17))\");\n\n Stmt store = Store::make(\"buf\", (x * 17) \/ (x - 3), y - 1);\n Stmt for_loop = For::make(\"x\", -2, y + 2, For::Parallel, store);\n vector<Expr> args(1); args[0] = x % 3;\n Expr call = Call::make(i32, \"buf\", args, Call::Extern);\n Stmt store2 = Store::make(\"out\", call + 1, x);\n Stmt for_loop2 = For::make(\"x\", 0, y, For::Vectorized , store2);\n Stmt pipeline = Pipeline::make(\"buf\", for_loop, Stmt(), for_loop2);\n Stmt assertion = AssertStmt::make(y > 3, \"y is greater than 3\");\n Stmt block = Block::make(assertion, pipeline);\n Stmt let_stmt = LetStmt::make(\"y\", 17, block);\n Stmt allocate = Allocate::make(\"buf\", f32, 1023, let_stmt);\n\n ostringstream source;\n source << allocate;\n std::string correct_source = \\\n \"allocate buf[float32 * 1023]\\n\"\n \"let y = 17\\n\"\n \"assert((y > 3), \\\"y is greater than 3\\\")\\n\"\n \"produce buf {\\n\"\n \" parallel (x, -2, (y + 2)) {\\n\"\n \" buf[(y - 1)] = ((x*17)\/(x - 3))\\n\"\n \" }\\n\"\n \"}\\n\"\n \"vectorized (x, 0, y) {\\n\"\n \" out[x] = (buf((x % 3)) + 1)\\n\"\n \"}\\n\";\n\n if (source.str() != correct_source) {\n std::cout << \"Correct output:\" << std::endl << correct_source;\n std::cout << \"Actual output:\" << std::endl << source.str();\n assert(false);\n }\n std::cout << \"IRPrinter test passed\" << std::endl;\n}\n\nostream &operator<<(ostream &out, const For::ForType &type) {\n switch (type) {\n case For::Serial:\n out << \"for\";\n break;\n case For::Parallel:\n out << \"parallel\";\n break;\n case For::Unrolled:\n out << \"unrolled\";\n break;\n case For::Vectorized:\n out << \"vectorized\";\n break;\n }\n return out;\n}\n\nostream &operator<<(ostream &stream, Stmt ir) {\n if (!ir.defined()) {\n stream << \"(undefined)\" << std::endl;\n } else {\n Internal::IRPrinter p(stream);\n p.print(ir);\n }\n return stream;\n}\n\nIRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {\n s.setf(std::ios::fixed, std::ios::floatfield);\n}\n\nvoid IRPrinter::print(Expr ir) {\n ir.accept(this);\n}\n\nvoid IRPrinter::print(Stmt ir) {\n ir.accept(this);\n}\n\n\nvoid IRPrinter::do_indent() {\n for (int i = 0; i < indent; i++) stream << ' ';\n}\n\nvoid IRPrinter::visit(const IntImm *op) {\n stream << op->value;\n}\n\nvoid IRPrinter::visit(const FloatImm *op) {\n stream << op->value << 'f';\n}\n\nvoid IRPrinter::visit(const Cast *op) {\n stream << op->type << '(';\n print(op->value);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Variable *op) {\n \/\/ omit the type\n \/\/ stream << op->name << \".\" << op->type;\n stream << op->name;\n}\n\nvoid IRPrinter::visit(const Add *op) {\n stream << '(';\n print(op->a);\n stream << \" + \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Sub *op) {\n stream << '(';\n print(op->a);\n stream << \" - \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Mul *op) {\n stream << '(';\n print(op->a);\n stream << \"*\";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Div *op) {\n stream << '(';\n print(op->a);\n stream << \"\/\";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Mod *op) {\n stream << '(';\n print(op->a);\n stream << \" % \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Min *op) {\n stream << \"min(\";\n print(op->a);\n stream << \", \";\n print(op->b);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Max *op) {\n stream << \"max(\";\n print(op->a);\n stream << \", \";\n print(op->b);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const EQ *op) {\n stream << '(';\n print(op->a);\n stream << \" == \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const NE *op) {\n stream << '(';\n print(op->a);\n stream << \" != \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const LT *op) {\n stream << '(';\n print(op->a);\n stream << \" < \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const LE *op) {\n stream << '(';\n print(op->a);\n stream << \" <= \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const GT *op) {\n stream << '(';\n print(op->a);\n stream << \" > \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const GE *op) {\n stream << '(';\n print(op->a);\n stream << \" >= \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const And *op) {\n stream << '(';\n print(op->a);\n stream << \" && \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Or *op) {\n stream << '(';\n print(op->a);\n stream << \" || \";\n print(op->b);\n stream << ')';\n}\n\nvoid IRPrinter::visit(const Not *op) {\n stream << '!';\n print(op->a);\n}\n\nvoid IRPrinter::visit(const Select *op) {\n stream << \"select(\";\n print(op->condition);\n stream << \", \";\n print(op->true_value);\n stream << \", \";\n print(op->false_value);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Load *op) {\n stream << op->name << \"[\";\n print(op->index);\n stream << \"]\";\n}\n\nvoid IRPrinter::visit(const Ramp *op) {\n stream << \"ramp(\";\n print(op->base);\n stream << \", \";\n print(op->stride);\n stream << \", \" << op->width << \")\";\n}\n\nvoid IRPrinter::visit(const Broadcast *op) {\n stream << \"x\" << op->width << \"(\";\n print(op->value);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Call *op) {\n stream << op->name << \"(\";\n for (size_t i = 0; i < op->args.size(); i++) {\n print(op->args[i]);\n if (i < op->args.size() - 1) {\n stream << \", \";\n }\n }\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const Let *op) {\n stream << \"(let \" << op->name << \" = \";\n print(op->value);\n stream << \" in \";\n print(op->body);\n stream << \")\";\n}\n\nvoid IRPrinter::visit(const LetStmt *op) {\n do_indent();\n stream << \"let \" << op->name << \" = \";\n print(op->value);\n stream << endl;\n\n print(op->body);\n}\n\nvoid IRPrinter::visit(const PrintStmt *op) {\n do_indent();\n stream << \"print(\" << op->prefix;\n for (size_t i = 0; i < op->args.size(); i++) {\n stream << \", \";\n print(op->args[i]);\n }\n stream << \")\" << endl;\n}\n\nvoid IRPrinter::visit(const AssertStmt *op) {\n do_indent();\n stream << \"assert(\";\n print(op->condition);\n stream << \", \\\"\" << op->message << \"\\\")\" << endl;\n}\n\nvoid IRPrinter::visit(const Pipeline *op) {\n\n do_indent();\n stream << \"produce \" << op->name << \" {\" << endl;\n indent += 2;\n print(op->produce);\n indent -= 2;\n\n if (op->update.defined()) {\n do_indent();\n stream << \"} update \" << op->name << \" {\" << endl;\n indent += 2;\n print(op->update);\n indent -= 2;\n }\n\n do_indent();\n stream << \"}\\n\";\n\n print(op->consume);\n\n}\n\nvoid IRPrinter::visit(const For *op) {\n\n do_indent();\n stream << op->for_type << \" (\" << op->name << \", \";\n print(op->min);\n stream << \", \";\n print(op->extent);\n stream << \") {\" << endl;\n\n indent += 2;\n print(op->body);\n indent -= 2;\n\n do_indent();\n stream << \"}\" << endl;\n}\n\nvoid IRPrinter::visit(const Store *op) {\n do_indent();\n stream << op->name << \"[\";\n print(op->index);\n stream << \"] = \";\n print(op->value);\n stream << endl;\n}\n\nvoid IRPrinter::visit(const Provide *op) {\n do_indent();\n stream << op->name << \"(\";\n for (size_t i = 0; i < op->args.size(); i++) {\n print(op->args[i]);\n if (i < op->args.size() - 1) stream << \", \";\n }\n stream << \") = \";\n print(op->value);\n stream << endl;\n}\n\nvoid IRPrinter::visit(const Allocate *op) {\n do_indent();\n stream << \"allocate \" << op->name << \"[\" << op->type << \" * \";\n print(op->size);\n stream << \"]\" << endl;\n print(op->body);\n}\n\nvoid IRPrinter::visit(const Free *op) {\n do_indent();\n stream << \"free \" << op->name << endl;\n}\n\nvoid IRPrinter::visit(const Realize *op) {\n do_indent();\n stream << \"realize \" << op->name << \"(\";\n for (size_t i = 0; i < op->bounds.size(); i++) {\n stream << \"[\";\n print(op->bounds[i].min);\n stream << \", \";\n print(op->bounds[i].extent);\n stream << \"]\";\n if (i < op->bounds.size() - 1) stream << \", \";\n }\n stream << \") {\" << endl;\n\n indent += 2;\n print(op->body);\n indent -= 2;\n\n do_indent();\n stream << \"}\" << endl;\n}\n\nvoid IRPrinter::visit(const Block *op) {\n print(op->first);\n if (op->rest.defined()) print(op->rest);\n}\n\n\n}}\n<|endoftext|>"} {"text":"<commit_before>void MakeVZERORecoParam(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult) {\n\/\/========================================================================\n\/\/\n\/\/ Steering macro for VZERO reconstruction parameters\n\/\/\n\/\/ Author: Brigitte Cheynis\n\/\/\n\/\/========================================================================\n\n const char* macroname = \"MakeVZERORecoParam.C\";\n\n \/\/ Activate CDB storage and load geometry from CDB\n AliCDBManager* cdb = AliCDBManager::Instance();\n if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage(\"local:\/\/OCDB\");\n \n TObjArray *recoParamArray = new TObjArray();\n\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kCosmic);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kLowMult);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n vzeroRecoParam->SetNPreClocks(6);\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kHighMult);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n\n \/\/ Set the default\n Bool_t defaultIsSet = kFALSE;\n for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {\n AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);\n if (!param) continue;\n if (default & param->GetEventSpecie()) {\n param->SetAsDefault();\n defaultIsSet = kTRUE;\n }\n }\n\n if (!defaultIsSet) {\n Error(macroname,\"The default reconstruction parameters are not set! Exiting...\");\n return;\n }\n\n \/\/ save in CDB storage\n AliCDBMetaData *md= new AliCDBMetaData();\n md->SetResponsible(\"Brigitte Cheynis\");\n md->SetComment(\"Reconstruction parameters for VZERO\");\n md->SetAliRootVersion(gSystem->Getenv(\"ARVERSION\"));\n md->SetBeamPeriod(0);\n AliCDBId id(\"VZERO\/Calib\/RecoParam\",0,AliCDBRunRange::Infinity());\n cdb->GetDefaultStorage()->Put(recoParamArray,id, md);\n\n return;\n}\n<commit_msg>Reducing the search window used to find the max in the ADC samples. Needed because of the dense filling scheme in 2011<commit_after>void MakeVZERORecoParam(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult) {\n\/\/========================================================================\n\/\/\n\/\/ Steering macro for VZERO reconstruction parameters\n\/\/\n\/\/ Author: Brigitte Cheynis\n\/\/\n\/\/========================================================================\n\n const char* macroname = \"MakeVZERORecoParam.C\";\n\n \/\/ Activate CDB storage and load geometry from CDB\n AliCDBManager* cdb = AliCDBManager::Instance();\n if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage(\"local:\/\/OCDB\");\n \n TObjArray *recoParamArray = new TObjArray();\n\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kCosmic);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n \/\/ the following two settings are needed to high lumi runs in 2011\n vzeroRecoParam->SetStartClock(9);\n vzeroRecoParam->SetEndClock(11);\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kLowMult);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n {\n AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;\n vzeroRecoParam->SetNPreClocks(6);\n vzeroRecoParam->SetEventSpecie(AliRecoParam::kHighMult);\n recoParamArray->AddLast(vzeroRecoParam);\n }\n\n \/\/ Set the default\n Bool_t defaultIsSet = kFALSE;\n for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {\n AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);\n if (!param) continue;\n if (default & param->GetEventSpecie()) {\n param->SetAsDefault();\n defaultIsSet = kTRUE;\n }\n }\n\n if (!defaultIsSet) {\n Error(macroname,\"The default reconstruction parameters are not set! Exiting...\");\n return;\n }\n\n \/\/ save in CDB storage\n AliCDBMetaData *md= new AliCDBMetaData();\n md->SetResponsible(\"Brigitte Cheynis\");\n md->SetComment(\"Reconstruction parameters for VZERO\");\n md->SetAliRootVersion(gSystem->Getenv(\"ARVERSION\"));\n md->SetBeamPeriod(0);\n AliCDBId id(\"VZERO\/Calib\/RecoParam\",0,AliCDBRunRange::Infinity());\n cdb->GetDefaultStorage()->Put(recoParamArray,id, md);\n\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/version.hpp>\n\n#include <mapnik\/layer.hpp>\n#include <mapnik\/feature_type_style.hpp>\n#include <mapnik\/debug.hpp>\n#include <mapnik\/ctrans.hpp>\n#include <mapnik\/vertex_converters.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n\n#if BOOST_VERSION >= 104700\n#include <mapnik\/util\/geometry_to_wkb.hpp>\n#include <mapnik\/util\/geometry_to_wkt.hpp>\n#include <mapnik\/util\/geometry_to_svg.hpp>\n#endif\n\n#include <boost\/detail\/lightweight_test.hpp>\n#include <iostream>\n\nstruct output_geometry_backend\n{\n output_geometry_backend(boost::ptr_vector<mapnik::geometry_type> & paths, mapnik::eGeomType type)\n : paths_(paths),\n type_(type) {}\n\n template <typename T>\n void add_path(T & path)\n {\n mapnik::vertex2d vtx(mapnik::vertex2d::no_init);\n path.rewind(0);\n std::auto_ptr<mapnik::geometry_type> geom_ptr(new mapnik::geometry_type(type_));\n\n while ((vtx.cmd = path.vertex(&vtx.x, &vtx.y)) != mapnik::SEG_END)\n {\n \/\/std::cerr << vtx.x << \",\" << vtx.y << \" cmd=\" << vtx.cmd << std::endl;\n geom_ptr->push_vertex(vtx.x, vtx.y, (mapnik::CommandType)vtx.cmd);\n }\n paths_.push_back(geom_ptr);\n }\n boost::ptr_vector<mapnik::geometry_type> & paths_;\n mapnik::eGeomType type_;\n};\n\nboost::optional<std::string> linestring_bbox_clipping(mapnik::box2d<double> bbox,\n std::string wkt_in)\n{\n using namespace mapnik;\n agg::trans_affine tr;\n projection src;\n projection dst;\n proj_transform prj_trans(src,dst);\n line_symbolizer sym;\n CoordTransform t(bbox.width(),bbox.height(), bbox);\n boost::ptr_vector<mapnik::geometry_type> output_paths;\n output_geometry_backend backend(output_paths, mapnik::LineString);\n\n typedef boost::mpl::vector<clip_line_tag> conv_types;\n vertex_converter<box2d<double>, output_geometry_backend, line_symbolizer,\n CoordTransform, proj_transform, agg::trans_affine, conv_types>\n converter(bbox, backend, sym, t, prj_trans, tr, 1.0);\n\n converter.template set<clip_line_tag>();\n\n boost::ptr_vector<geometry_type> p;\n if (!mapnik::from_wkt(wkt_in , p))\n {\n throw std::runtime_error(\"Failed to parse WKT\");\n }\n\n BOOST_FOREACH( geometry_type & geom, p)\n {\n converter.apply(geom);\n }\n\n std::string wkt_out;\n if (mapnik::util::to_wkt(wkt_out, output_paths))\n {\n return boost::optional<std::string>(wkt_out);\n }\n\n return boost::optional<std::string>();\n}\n\nboost::optional<std::string> polygon_bbox_clipping(mapnik::box2d<double> bbox,\n std::string wkt_in)\n{\n using namespace mapnik;\n agg::trans_affine tr;\n projection src;\n projection dst;\n proj_transform prj_trans(src,dst);\n polygon_symbolizer sym;\n CoordTransform t(bbox.width(),bbox.height(), bbox);\n boost::ptr_vector<mapnik::geometry_type> output_paths;\n output_geometry_backend backend(output_paths, mapnik::Polygon);\n\n typedef boost::mpl::vector<clip_poly_tag> conv_types;\n vertex_converter<box2d<double>, output_geometry_backend, polygon_symbolizer,\n CoordTransform, proj_transform, agg::trans_affine, conv_types>\n converter(bbox, backend, sym, t, prj_trans, tr, 1.0);\n\n converter.template set<clip_poly_tag>();\n\n boost::ptr_vector<geometry_type> p;\n if (!mapnik::from_wkt(wkt_in , p))\n {\n throw std::runtime_error(\"Failed to parse WKT\");\n }\n\n BOOST_FOREACH( geometry_type & geom, p)\n {\n converter.apply(geom);\n }\n\n std::string wkt_out;\n if (mapnik::util::to_wkt(wkt_out, output_paths))\n {\n return boost::optional<std::string>(wkt_out);\n }\n\n return boost::optional<std::string>();\n}\n\nint main( int, char*[] )\n{\n \/\/ LineString\/bbox clipping\n {\n std::string wkt_in(\"LineString(0 0,200 200)\");\n boost::optional<std::string> result = linestring_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"LineString(50 50,150 150)\"));\n }\n \/\/ Polygon\/bbox clipping\n#if 0\n \/\/ these tests will fail\n {\n std::string wkt_in(\"Polygon((50 50,150 50,150 150,50 150,50 50))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((50 50,150 50,150 150,50 150,50 50))\"));\n }\n\n {\n std::string wkt_in(\"Polygon((60 60,140 60,140 160,60 140,60 60))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((60 60,140 60,140 160,60 140,60 60))\"));\n }\n\n {\n std::string wkt_in(\"Polygon((0 0,10 0,10 10,0 10,0 0))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result, std::string(\"GeometryCollection EMPTY\"));\n }\n#endif\n {\n std::string wkt_in(\"Polygon((0 0,100 200,200 0,0 0 ))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((50 50,50 100,75 150,125 150,150 100,150 50,50 50))\"));\n }\n\n\n if (!::boost::detail::test_errors())\n {\n std::clog << \"C++ geometry conversions: \\x1b[1;32m✓ \\x1b[0m\\n\";\n#if BOOST_VERSION >= 104600\n ::boost::detail::report_errors_remind().called_report_errors_function = true;\n#endif\n }\n else\n {\n return ::boost::report_errors();\n }\n}\n<commit_msg>+ fix #1700<commit_after>#include <boost\/version.hpp>\n\n#include <mapnik\/layer.hpp>\n#include <mapnik\/feature_type_style.hpp>\n#include <mapnik\/debug.hpp>\n#include <mapnik\/ctrans.hpp>\n#include <mapnik\/vertex_converters.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n\n#if BOOST_VERSION >= 104700\n#include <mapnik\/util\/geometry_to_wkb.hpp>\n#include <mapnik\/util\/geometry_to_wkt.hpp>\n#include <mapnik\/util\/geometry_to_svg.hpp>\n#endif\n\n#include <boost\/detail\/lightweight_test.hpp>\n#include <iostream>\n\nstruct output_geometry_backend\n{\n output_geometry_backend(boost::ptr_vector<mapnik::geometry_type> & paths, mapnik::eGeomType type)\n : paths_(paths),\n type_(type) {}\n\n template <typename T>\n void add_path(T & path)\n {\n mapnik::vertex2d vtx(mapnik::vertex2d::no_init);\n path.rewind(0);\n std::auto_ptr<mapnik::geometry_type> geom_ptr(new mapnik::geometry_type(type_));\n\n while ((vtx.cmd = path.vertex(&vtx.x, &vtx.y)) != mapnik::SEG_END)\n {\n \/\/std::cerr << vtx.x << \",\" << vtx.y << \" cmd=\" << vtx.cmd << std::endl;\n geom_ptr->push_vertex(vtx.x, vtx.y, (mapnik::CommandType)vtx.cmd);\n }\n paths_.push_back(geom_ptr);\n }\n boost::ptr_vector<mapnik::geometry_type> & paths_;\n mapnik::eGeomType type_;\n};\n\nboost::optional<std::string> linestring_bbox_clipping(mapnik::box2d<double> bbox,\n std::string wkt_in)\n{\n using namespace mapnik;\n agg::trans_affine tr;\n projection src;\n projection dst;\n proj_transform prj_trans(src,dst);\n line_symbolizer sym;\n CoordTransform t(bbox.width(),bbox.height(), bbox);\n boost::ptr_vector<mapnik::geometry_type> output_paths;\n output_geometry_backend backend(output_paths, mapnik::LineString);\n\n typedef boost::mpl::vector<clip_line_tag> conv_types;\n vertex_converter<box2d<double>, output_geometry_backend, line_symbolizer,\n CoordTransform, proj_transform, agg::trans_affine, conv_types>\n converter(bbox, backend, sym, t, prj_trans, tr, 1.0);\n\n converter.set<clip_line_tag>();\n\n boost::ptr_vector<geometry_type> p;\n if (!mapnik::from_wkt(wkt_in , p))\n {\n throw std::runtime_error(\"Failed to parse WKT\");\n }\n\n BOOST_FOREACH( geometry_type & geom, p)\n {\n converter.apply(geom);\n }\n\n std::string wkt_out;\n if (mapnik::util::to_wkt(wkt_out, output_paths))\n {\n return boost::optional<std::string>(wkt_out);\n }\n\n return boost::optional<std::string>();\n}\n\nboost::optional<std::string> polygon_bbox_clipping(mapnik::box2d<double> bbox,\n std::string wkt_in)\n{\n using namespace mapnik;\n agg::trans_affine tr;\n projection src;\n projection dst;\n proj_transform prj_trans(src,dst);\n polygon_symbolizer sym;\n CoordTransform t(bbox.width(),bbox.height(), bbox);\n boost::ptr_vector<mapnik::geometry_type> output_paths;\n output_geometry_backend backend(output_paths, mapnik::Polygon);\n\n typedef boost::mpl::vector<clip_poly_tag> conv_types;\n vertex_converter<box2d<double>, output_geometry_backend, polygon_symbolizer,\n CoordTransform, proj_transform, agg::trans_affine, conv_types>\n converter(bbox, backend, sym, t, prj_trans, tr, 1.0);\n\n converter.set<clip_poly_tag>();\n\n boost::ptr_vector<geometry_type> p;\n if (!mapnik::from_wkt(wkt_in , p))\n {\n throw std::runtime_error(\"Failed to parse WKT\");\n }\n\n BOOST_FOREACH( geometry_type & geom, p)\n {\n converter.apply(geom);\n }\n\n std::string wkt_out;\n if (mapnik::util::to_wkt(wkt_out, output_paths))\n {\n return boost::optional<std::string>(wkt_out);\n }\n\n return boost::optional<std::string>();\n}\n\nint main( int, char*[] )\n{\n \/\/ LineString\/bbox clipping\n {\n std::string wkt_in(\"LineString(0 0,200 200)\");\n boost::optional<std::string> result = linestring_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"LineString(50 50,150 150)\"));\n }\n \/\/ Polygon\/bbox clipping\n#if 0\n \/\/ these tests will fail\n {\n std::string wkt_in(\"Polygon((50 50,150 50,150 150,50 150,50 50))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((50 50,150 50,150 150,50 150,50 50))\"));\n }\n\n {\n std::string wkt_in(\"Polygon((60 60,140 60,140 160,60 140,60 60))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((60 60,140 60,140 160,60 140,60 60))\"));\n }\n\n {\n std::string wkt_in(\"Polygon((0 0,10 0,10 10,0 10,0 0))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result, std::string(\"GeometryCollection EMPTY\"));\n }\n#endif\n {\n std::string wkt_in(\"Polygon((0 0,100 200,200 0,0 0 ))\");\n boost::optional<std::string> result = polygon_bbox_clipping(mapnik::box2d<double>(50,50,150,150),wkt_in);\n BOOST_TEST(result);\n BOOST_TEST_EQ(*result,std::string(\"Polygon((50 50,50 100,75 150,125 150,150 100,150 50,50 50))\"));\n }\n\n if (!::boost::detail::test_errors())\n {\n std::clog << \"C++ geometry conversions: \\x1b[1;32m✓ \\x1b[0m\\n\";\n#if BOOST_VERSION >= 104600\n ::boost::detail::report_errors_remind().called_report_errors_function = true;\n#endif\n }\n else\n {\n return ::boost::report_errors();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file BlynkDebug.cpp\n * @author Volodymyr Shymanskyy\n * @license This project is released under the MIT License (MIT)\n * @copyright Copyright (c) 2015 Volodymyr Shymanskyy\n * @date Jan 2015\n * @brief Debug utilities for Arduino\n *\/\n#include \"BlynkDebug.h\"\n\nsize_t BlynkFreeRam()\n{\n return 0;\n}\n\nvoid BlynkReset()\n{\n System.reset();\n for(;;);\n}\n\nvoid BlynkFatal()\n{\n BlynkReset();\n for(;;);\n}\n<commit_msg>Update BlynkDebug.cpp<commit_after>\/**\n * @file BlynkDebug.cpp\n * @author Volodymyr Shymanskyy\n * @license This project is released under the MIT License (MIT)\n * @copyright Copyright (c) 2015 Volodymyr Shymanskyy\n * @date Jan 2015\n * @brief Debug utilities for Arduino\n *\/\n#include \"BlynkDebug.h\"\n#include \"application.h\"\n\nsize_t BlynkFreeRam()\n{\n return 0;\n}\n\nvoid BlynkReset()\n{\n System.reset();\n for(;;);\n}\n\nvoid BlynkFatal()\n{\n BlynkReset();\n for(;;);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Precompiled.h\"\n#include \"VulkanDevice.h\"\n#include <cassert>\n#include \"VLog.h\"\n\nusing namespace vulkan;\n\nclass VulkanDevice::impl\n{\npublic:\n\timpl(std::shared_ptr<VulkanPhysicalDevice> device) : PhysicalDevice(device)\n\t{\n\t\tauto queue_props = PhysicalDevice->getQueueFamilyProperties();\n\n\t\tauto found = false;\n\t\tfor (unsigned int i = 0; i < queue_props.size(); i++)\n\t\t{\n\t\t\tif (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)\n\t\t\t{\n\t\t\t\tqueue_info.queueFamilyIndex = i;\n\t\t\t\tfound = true;\n\t\t\t\tlog() << \"Found gpu \" << i << \" with queue with VK_QUEUE_GRAPHICS_BIT\\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(found);\n\n\t\tfloat queue_priorities[1] = { 0.0 };\n\t\tqueue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;\n\t\tqueue_info.pNext = nullptr;\n\t\tqueue_info.queueCount = 1;\n\t\tqueue_info.pQueuePriorities = queue_priorities;\n\n\t\tdevice_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;\n\t\tdevice_info.pNext = nullptr;\n\t\tdevice_info.queueCreateInfoCount = 1;\n\t\tdevice_info.pQueueCreateInfos = &queue_info;\n\t\tdevice_info.enabledExtensionCount = 0;\n\t\tdevice_info.ppEnabledExtensionNames = nullptr;\n\t\tdevice_info.enabledLayerCount = 0;\n\t\tdevice_info.ppEnabledLayerNames = nullptr;\n\t\tdevice_info.pEnabledFeatures = nullptr;\n\n\t\tauto res = vkCreateDevice(PhysicalDevice->getPhysicalDevice(), &device_info, NULL, &LogicalDevice);\n\t\tassert(res == VK_SUCCESS);\n\n\t\tlog() << \"Created a logical device\\n\";\n\t}\n\n\t~impl()\n\t{\n\t\tvkDestroyDevice(LogicalDevice, nullptr);\n\t}\n\n\tVkDevice LogicalDevice;\n\tstd::shared_ptr<VulkanPhysicalDevice> PhysicalDevice;\n\n\tVkDeviceQueueCreateInfo queue_info = {};\n\tVkDeviceCreateInfo device_info = {};\n};\n\nVulkanDevice::VulkanDevice(std::shared_ptr<VulkanPhysicalDevice> device)\n{\n\tpimpl = std::make_unique<impl>(device);\n}\n\nVulkanDevice::~VulkanDevice()\n{\n\t\/\/ empty\n}\n<commit_msg>minor clean up<commit_after>#include \"Precompiled.h\"\n#include \"VulkanDevice.h\"\n#include <cassert>\n#include \"VLog.h\"\n\nusing namespace vulkan;\n\nclass VulkanDevice::impl\n{\npublic:\n\texplicit impl(std::shared_ptr<VulkanPhysicalDevice> device) : PhysicalDevice(device)\n\t{\n\t\tauto queue_props = PhysicalDevice->getQueueFamilyProperties();\n\n\t\tauto found = false;\n\t\tfor (unsigned int i = 0; i < queue_props.size(); i++)\n\t\t{\n\t\t\tif (queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)\n\t\t\t{\n\t\t\t\tqueue_info.queueFamilyIndex = i;\n\t\t\t\tfound = true;\n\t\t\t\tlog() << \"Found gpu \" << i << \" with queue with VK_QUEUE_GRAPHICS_BIT\\n\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(found);\n\n\t\tfloat queue_priorities[1] = { 0.0 };\n\t\tqueue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;\n\t\tqueue_info.pNext = nullptr;\n\t\tqueue_info.queueCount = 1;\n\t\tqueue_info.pQueuePriorities = queue_priorities;\n\n\t\tdevice_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;\n\t\tdevice_info.pNext = nullptr;\n\t\tdevice_info.queueCreateInfoCount = 1;\n\t\tdevice_info.pQueueCreateInfos = &queue_info;\n\t\tdevice_info.enabledExtensionCount = 0;\n\t\tdevice_info.ppEnabledExtensionNames = nullptr;\n\t\tdevice_info.enabledLayerCount = 0;\n\t\tdevice_info.ppEnabledLayerNames = nullptr;\n\t\tdevice_info.pEnabledFeatures = nullptr;\n\n\t\tauto res = vkCreateDevice(PhysicalDevice->getPhysicalDevice(), &device_info, nullptr, &LogicalDevice);\n\t\tassert(res == VK_SUCCESS);\n\n\t\tlog() << \"Created a logical device\\n\";\n\t}\n\n\t~impl()\n\t{\n\t\tvkDestroyDevice(LogicalDevice, nullptr);\n\t}\n\n\tVkDevice LogicalDevice;\n\tstd::shared_ptr<VulkanPhysicalDevice> PhysicalDevice;\n\n\tVkDeviceQueueCreateInfo queue_info = {};\n\tVkDeviceCreateInfo device_info = {};\n};\n\nVulkanDevice::VulkanDevice(std::shared_ptr<VulkanPhysicalDevice> device)\n{\n\tpimpl = std::make_unique<impl>(device);\n}\n\nVulkanDevice::~VulkanDevice()\n{\n\t\/\/ empty\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file Indicator.cxx\n ** Defines the style of indicators which are text decorations such as underlining.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <vector>\n#include <map>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"XPM.h\"\n#include \"Indicator.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic PRectangle PixelGridAlign(const PRectangle &rc) {\n\t\/\/ Move left and right side to nearest pixel to avoid blurry visuals\n\treturn PRectangle(int(rc.left + 0.5), rc.top, int(rc.right + 0.5), rc.bottom);\n}\n\nvoid Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine) {\n\tsurface->PenColour(fore);\n\tint ymid = (rc.bottom + rc.top) \/ 2;\n\tif (style == INDIC_SQUIGGLE) {\n\t\tsurface->MoveTo(rc.left, rc.top);\n\t\tint x = rc.left + 2;\n\t\tint y = 2;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->LineTo(x, rc.top + y);\n\t\t\tx += 2;\n\t\t\ty = 2 - y;\n\t\t}\n\t\tsurface->LineTo(rc.right, rc.top + y);\t\/\/ Finish the line\n\t} else if (style == INDIC_SQUIGGLEPIXMAP) {\n\t\tPRectangle rcSquiggle = PixelGridAlign(rc);\n\n\t\tint width = Platform::Minimum(4000, rcSquiggle.Width());\n\t\tRGBAImage image(width, 3, 1.0, 0);\n\t\tenum { alphaFull = 0xff, alphaSide = 0x2f, alphaSide2=0x5f };\n\t\tfor (int x = 0; x < width; x++) {\n\t\t\tif (x%2) {\n\t\t\t\t\/\/ Two halfway columns have a full pixel in middle flanked by light pixels\n\t\t\t\timage.SetPixel(x, 0, fore, alphaSide);\n\t\t\t\timage.SetPixel(x, 1, fore, alphaFull);\n\t\t\t\timage.SetPixel(x, 2, fore, alphaSide);\n\t\t\t} else {\n\t\t\t\t\/\/ Extreme columns have a full pixel at bottom or top and a mid-tone pixel in centre\n\t\t\t\timage.SetPixel(x, (x%4) ? 0 : 2, fore, alphaFull);\n\t\t\t\timage.SetPixel(x, 1, fore, alphaSide2);\n\t\t\t}\n\t\t}\n\t\tsurface->DrawRGBAImage(rcSquiggle, image.GetWidth(), image.GetHeight(), image.Pixels());\n\t} else if (style == INDIC_SQUIGGLELOW) {\n\t\tsurface->MoveTo(rc.left, rc.top);\n\t\tint x = rc.left + 3;\n\t\tint y = 0;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->LineTo(x-1, rc.top + y);\n\t\t\ty = 1 - y;\n \tsurface->LineTo(x, rc.top + y);\n\t\t\tx += 3;\n\t\t}\n\t\tsurface->LineTo(rc.right, rc.top + y);\t\/\/ Finish the line\n\t} else if (style == INDIC_TT) {\n\t\tsurface->MoveTo(rc.left, ymid);\n\t\tint x = rc.left + 5;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->LineTo(x, ymid);\n\t\t\tsurface->MoveTo(x-3, ymid);\n\t\t\tsurface->LineTo(x-3, ymid+2);\n\t\t\tx++;\n\t\t\tsurface->MoveTo(x, ymid);\n\t\t\tx += 5;\n\t\t}\n\t\tsurface->LineTo(rc.right, ymid);\t\/\/ Finish the line\n\t\tif (x - 3 <= rc.right) {\n\t\t\tsurface->MoveTo(x-3, ymid);\n\t\t\tsurface->LineTo(x-3, ymid+2);\n\t\t}\n\t} else if (style == INDIC_DIAGONAL) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->MoveTo(x, rc.top+2);\n\t\t\tint endX = x+3;\n\t\t\tint endY = rc.top - 1;\n\t\t\tif (endX > rc.right) {\n\t\t\t\tendY += endX - rc.right;\n\t\t\t\tendX = rc.right;\n\t\t\t}\n\t\t\tsurface->LineTo(endX, endY);\n\t\t\tx += 4;\n\t\t}\n\t} else if (style == INDIC_STRIKE) {\n\t\tsurface->MoveTo(rc.left, rc.top - 4);\n\t\tsurface->LineTo(rc.right, rc.top - 4);\n\t} else if (style == INDIC_HIDDEN) {\n\t\t\/\/ Draw nothing\n\t} else if (style == INDIC_BOX) {\n\t\tsurface->MoveTo(rc.left, ymid+1);\n\t\tsurface->LineTo(rc.right, ymid+1);\n\t\tsurface->LineTo(rc.right, rcLine.top+1);\n\t\tsurface->LineTo(rc.left, rcLine.top+1);\n\t\tsurface->LineTo(rc.left, ymid+1);\n\t} else if (style == INDIC_ROUNDBOX || style == INDIC_STRAIGHTBOX) {\n\t\tPRectangle rcBox = rcLine;\n\t\trcBox.top = rcLine.top + 1;\n\t\trcBox.left = rc.left;\n\t\trcBox.right = rc.right;\n\t\tsurface->AlphaRectangle(rcBox, (style == INDIC_ROUNDBOX) ? 1 : 0, fore, fillAlpha, fore, outlineAlpha, 0);\n\t} else if (style == INDIC_DOTBOX) {\n\t\tPRectangle rcBox = PixelGridAlign(rc);\n\t\trcBox.top = rcLine.top + 1;\n\t\trcBox.bottom = rcLine.bottom;\n\t\t\/\/ Cap width at 4000 to avoid large allocations when mistakes made\n\t\tint width = Platform::Minimum(rcBox.Width(), 4000);\n\t\tRGBAImage image(width, rcBox.Height(), 1.0, 0);\n\t\t\/\/ Draw horizontal lines top and bottom\n\t\tfor (int x=0; x<width; x++) {\n\t\t\tfor (int y=0; y<rcBox.Height(); y += rcBox.Height()-1) {\n\t\t\t\timage.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);\n\t\t\t}\n\t\t}\n\t\t\/\/ Draw vertical lines left and right\n\t\tfor (int y=1; y<rcBox.Height(); y++) {\n\t\t\tfor (int x=0; x<width; x += width-1) {\n\t\t\t\timage.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);\n\t\t\t}\n\t\t}\n\t\tsurface->DrawRGBAImage(rcBox, image.GetWidth(), image.GetHeight(), image.Pixels());\n\t} else if (style == INDIC_DASH) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->MoveTo(x, ymid);\n\t\t\tsurface->LineTo(Platform::Minimum(x + 4, rc.right), ymid);\n\t\t\tx += 7;\n\t\t}\n\t} else if (style == INDIC_DOTS) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tPRectangle rcDot(x, ymid, x+1, ymid+1);\n\t\t\tsurface->FillRectangle(rcDot, fore);\n\t\t\tx += 2;\n\t\t}\n\t} else {\t\/\/ Either INDIC_PLAIN or unknown\n\t\tsurface->MoveTo(rc.left, ymid);\n\t\tsurface->LineTo(rc.right, ymid);\n\t}\n}\n\n<commit_msg>Avoid poor drawing at right of INDIC_SQUIGGLE.<commit_after>\/\/ Scintilla source code edit control\n\/** @file Indicator.cxx\n ** Defines the style of indicators which are text decorations such as underlining.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <vector>\n#include <map>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"XPM.h\"\n#include \"Indicator.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic PRectangle PixelGridAlign(const PRectangle &rc) {\n\t\/\/ Move left and right side to nearest pixel to avoid blurry visuals\n\treturn PRectangle(int(rc.left + 0.5), rc.top, int(rc.right + 0.5), rc.bottom);\n}\n\nvoid Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine) {\n\tsurface->PenColour(fore);\n\tint ymid = (rc.bottom + rc.top) \/ 2;\n\tif (style == INDIC_SQUIGGLE) {\n\t\tint x = int(rc.left+0.5);\n\t\tint xLast = int(rc.right+0.5);\n\t\tint y = 0;\n\t\tsurface->MoveTo(x, rc.top + y);\n\t\twhile (x < xLast) {\n\t\t\tif ((x + 2) > xLast) {\n\t\t\t\tif (xLast > x)\n\t\t\t\t\ty = 1;\n\t\t\t\tx = xLast;\n\t\t\t} else {\n\t\t\t\tx += 2;\n\t\t\t\ty = 2 - y;\n\t\t\t}\n\t\t\tsurface->LineTo(x, rc.top + y);\n\t\t}\n\t} else if (style == INDIC_SQUIGGLEPIXMAP) {\n\t\tPRectangle rcSquiggle = PixelGridAlign(rc);\n\n\t\tint width = Platform::Minimum(4000, rcSquiggle.Width());\n\t\tRGBAImage image(width, 3, 1.0, 0);\n\t\tenum { alphaFull = 0xff, alphaSide = 0x2f, alphaSide2=0x5f };\n\t\tfor (int x = 0; x < width; x++) {\n\t\t\tif (x%2) {\n\t\t\t\t\/\/ Two halfway columns have a full pixel in middle flanked by light pixels\n\t\t\t\timage.SetPixel(x, 0, fore, alphaSide);\n\t\t\t\timage.SetPixel(x, 1, fore, alphaFull);\n\t\t\t\timage.SetPixel(x, 2, fore, alphaSide);\n\t\t\t} else {\n\t\t\t\t\/\/ Extreme columns have a full pixel at bottom or top and a mid-tone pixel in centre\n\t\t\t\timage.SetPixel(x, (x%4) ? 0 : 2, fore, alphaFull);\n\t\t\t\timage.SetPixel(x, 1, fore, alphaSide2);\n\t\t\t}\n\t\t}\n\t\tsurface->DrawRGBAImage(rcSquiggle, image.GetWidth(), image.GetHeight(), image.Pixels());\n\t} else if (style == INDIC_SQUIGGLELOW) {\n\t\tsurface->MoveTo(rc.left, rc.top);\n\t\tint x = rc.left + 3;\n\t\tint y = 0;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->LineTo(x-1, rc.top + y);\n\t\t\ty = 1 - y;\n \tsurface->LineTo(x, rc.top + y);\n\t\t\tx += 3;\n\t\t}\n\t\tsurface->LineTo(rc.right, rc.top + y);\t\/\/ Finish the line\n\t} else if (style == INDIC_TT) {\n\t\tsurface->MoveTo(rc.left, ymid);\n\t\tint x = rc.left + 5;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->LineTo(x, ymid);\n\t\t\tsurface->MoveTo(x-3, ymid);\n\t\t\tsurface->LineTo(x-3, ymid+2);\n\t\t\tx++;\n\t\t\tsurface->MoveTo(x, ymid);\n\t\t\tx += 5;\n\t\t}\n\t\tsurface->LineTo(rc.right, ymid);\t\/\/ Finish the line\n\t\tif (x - 3 <= rc.right) {\n\t\t\tsurface->MoveTo(x-3, ymid);\n\t\t\tsurface->LineTo(x-3, ymid+2);\n\t\t}\n\t} else if (style == INDIC_DIAGONAL) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->MoveTo(x, rc.top+2);\n\t\t\tint endX = x+3;\n\t\t\tint endY = rc.top - 1;\n\t\t\tif (endX > rc.right) {\n\t\t\t\tendY += endX - rc.right;\n\t\t\t\tendX = rc.right;\n\t\t\t}\n\t\t\tsurface->LineTo(endX, endY);\n\t\t\tx += 4;\n\t\t}\n\t} else if (style == INDIC_STRIKE) {\n\t\tsurface->MoveTo(rc.left, rc.top - 4);\n\t\tsurface->LineTo(rc.right, rc.top - 4);\n\t} else if (style == INDIC_HIDDEN) {\n\t\t\/\/ Draw nothing\n\t} else if (style == INDIC_BOX) {\n\t\tsurface->MoveTo(rc.left, ymid+1);\n\t\tsurface->LineTo(rc.right, ymid+1);\n\t\tsurface->LineTo(rc.right, rcLine.top+1);\n\t\tsurface->LineTo(rc.left, rcLine.top+1);\n\t\tsurface->LineTo(rc.left, ymid+1);\n\t} else if (style == INDIC_ROUNDBOX || style == INDIC_STRAIGHTBOX) {\n\t\tPRectangle rcBox = rcLine;\n\t\trcBox.top = rcLine.top + 1;\n\t\trcBox.left = rc.left;\n\t\trcBox.right = rc.right;\n\t\tsurface->AlphaRectangle(rcBox, (style == INDIC_ROUNDBOX) ? 1 : 0, fore, fillAlpha, fore, outlineAlpha, 0);\n\t} else if (style == INDIC_DOTBOX) {\n\t\tPRectangle rcBox = PixelGridAlign(rc);\n\t\trcBox.top = rcLine.top + 1;\n\t\trcBox.bottom = rcLine.bottom;\n\t\t\/\/ Cap width at 4000 to avoid large allocations when mistakes made\n\t\tint width = Platform::Minimum(rcBox.Width(), 4000);\n\t\tRGBAImage image(width, rcBox.Height(), 1.0, 0);\n\t\t\/\/ Draw horizontal lines top and bottom\n\t\tfor (int x=0; x<width; x++) {\n\t\t\tfor (int y=0; y<rcBox.Height(); y += rcBox.Height()-1) {\n\t\t\t\timage.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);\n\t\t\t}\n\t\t}\n\t\t\/\/ Draw vertical lines left and right\n\t\tfor (int y=1; y<rcBox.Height(); y++) {\n\t\t\tfor (int x=0; x<width; x += width-1) {\n\t\t\t\timage.SetPixel(x, y, fore, ((x + y) % 2) ? outlineAlpha : fillAlpha);\n\t\t\t}\n\t\t}\n\t\tsurface->DrawRGBAImage(rcBox, image.GetWidth(), image.GetHeight(), image.Pixels());\n\t} else if (style == INDIC_DASH) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tsurface->MoveTo(x, ymid);\n\t\t\tsurface->LineTo(Platform::Minimum(x + 4, rc.right), ymid);\n\t\t\tx += 7;\n\t\t}\n\t} else if (style == INDIC_DOTS) {\n\t\tint x = rc.left;\n\t\twhile (x < rc.right) {\n\t\t\tPRectangle rcDot(x, ymid, x+1, ymid+1);\n\t\t\tsurface->FillRectangle(rcDot, fore);\n\t\t\tx += 2;\n\t\t}\n\t} else {\t\/\/ Either INDIC_PLAIN or unknown\n\t\tsurface->MoveTo(rc.left, ymid);\n\t\tsurface->LineTo(rc.right, ymid);\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef PANGOLINDISPLAY_HPP\n#define PANGOLINDISPLAY_HPP\n\n#include <imp\/core\/size.hpp>\n#include <imp\/core\/image.hpp>\n#include <pangolin\/display.h>\n\n#include <imp\/cu_core\/cu_image_gpu.cuh>\n\nnamespace imp\n{\n\n\/\/------------------------------------------------------------------------------\ninline pangolin::View& setupPangolinView(\n const imp::Size2u& sz,\n const std::string& title = \"-\")\n{\n \/\/ Create OpenGL window in single line\n pangolin::CreateWindowAndBind(\"Lena\", sz.width(), sz.height());\n\n if (glewInit() != GLEW_OK )\n {\n LOG(ERROR) << \"Unable to initialize GLEW.\" << std::endl;\n }\n\n glEnable(GL_DEPTH_TEST); \/\/ 3D Mouse handler requires depth testing to be enabled\n \/\/! @todo (MWE) set OpenGL parameters... which glHint \/ glEnable options do we need?\n\n pangolin::View& container = pangolin::CreateDisplay()\n .SetBounds(0, 1.0f, 0, 1.0f);\n\n return container;\n}\n\n\/\/------------------------------------------------------------------------------\ninline void setupPangolinViewLayout(\n pangolin::View& container,\n int num_tiles=1, std::vector<float> aspect={})\n{\n container.SetLayout(pangolin::LayoutEqual);\n for (int i=0; i<num_tiles; ++i)\n {\n pangolin::View& v = pangolin::CreateDisplay();\n if(static_cast<int>(aspect.size())>i)\n {\n v.SetAspect(aspect.at(i));\n }\n container.AddDisplay(v);\n }\n\n \/\/! @todo (MWE) register keypresses, etc.\n}\n\n\/\/------------------------------------------------------------------------------\ninline void imshow(const imp::Image8uC1& im, const std::string& title=\"-\")\n{\n pangolin::View& container = imp::setupPangolinView(im.size(), title);\n imp::setupPangolinViewLayout(container, 1, {(float)im.width()\/im.height()});\n pangolin::GlTexture tex8(im.width(), im.height(), GL_LUMINANCE8);\n\n while(!pangolin::ShouldQuit())\n {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glColor3f(1,1,1);\n\n if (container[0].IsShown())\n {\n container[0].Activate();\n tex8.Upload(im.data(), GL_LUMINANCE, GL_UNSIGNED_BYTE);\n tex8.RenderToViewportFlipY();\n }\n pangolin::FinishFrame();\n }\n}\n\n\/\/------------------------------------------------------------------------------\ninline void imshow(const imp::cu::Image8uC1& im, const std::string& title=\"-\")\n{\n pangolin::View& container = imp::setupPangolinView(im.size(), title);\n imp::setupPangolinViewLayout(container, 1, {(float)im.width()\/im.height()});\n\n container[0].SetDrawFunction\n\n\n pangolin::GlTexture tex8(im.width(), im.height(), GL_LUMINANCE8);\n\n while(!pangolin::ShouldQuit())\n {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glColor3f(1,1,1);\n\n if (container[0].IsShown())\n {\n container[0].Activate();\n tex8.Upload(im.data(), GL_LUMINANCE, GL_UNSIGNED_BYTE);\n tex8.RenderToViewportFlipY();\n }\n pangolin::FinishFrame();\n }\n}\n\n\n\/\/\/\/==============================================================================\n\/\/class PangolinDisplay\n\/\/{\n\/\/public:\n\/\/ PangolinDisplay();\n\/\/ ~PangolinDisplay();\n\/\/};\n\n} \/\/ namespace imp\n\n#endif \/\/ PANGOLINDISPLAY_HPP\n<commit_msg>cuda image display still a todo<commit_after>#ifndef PANGOLINDISPLAY_HPP\n#define PANGOLINDISPLAY_HPP\n\n#include <imp\/core\/size.hpp>\n#include <imp\/core\/image.hpp>\n#include <pangolin\/display.h>\n\n#include <imp\/cu_core\/cu_image_gpu.cuh>\n\nnamespace imp\n{\n\n\/\/------------------------------------------------------------------------------\ninline pangolin::View& setupPangolinCudaView(\n const imp::Size2u& sz,\n const std::string& title = \"-\")\n{\n pangolin::View& container = pangolin::setupPangolinView(sz, title);\n .SetBounds(0, 1.0f, 0, 1.0f);\n\n \/\/ TODO\n\n return container;\n}\n\n\/\/------------------------------------------------------------------------------\ninline pangolin::View& setupPangolinView(\n const imp::Size2u& sz,\n const std::string& title = \"-\")\n{\n \/\/ Create OpenGL window in single line\n pangolin::CreateWindowAndBind(title, sz.width(), sz.height());\n\n if (glewInit() != GLEW_OK )\n {\n LOG(ERROR) << \"Unable to initialize GLEW.\" << std::endl;\n }\n\n glEnable(GL_DEPTH_TEST); \/\/ 3D Mouse handler requires depth testing to be enabled\n \/\/! @todo (MWE) set OpenGL parameters... which glHint \/ glEnable options do we need?\n\n pangolin::View& container = pangolin::CreateDisplay()\n .SetBounds(0, 1.0f, 0, 1.0f);\n\n return container;\n}\n\n\/\/------------------------------------------------------------------------------\ninline void setupPangolinViewLayout(\n pangolin::View& container,\n int num_tiles=1, std::vector<float> aspect={})\n{\n container.SetLayout(pangolin::LayoutEqual);\n for (int i=0; i<num_tiles; ++i)\n {\n pangolin::View& v = pangolin::CreateDisplay();\n if(static_cast<int>(aspect.size())>i)\n {\n v.SetAspect(aspect.at(i));\n }\n container.AddDisplay(v);\n }\n\n \/\/! @todo (MWE) register keypresses, etc.\n}\n\n\/\/------------------------------------------------------------------------------\ninline void imshow(const imp::Image8uC1& im, const std::string& title=\"-\")\n{\n pangolin::View& container = imp::setupPangolinView(im.size(), title);\n imp::setupPangolinViewLayout(container, 1, {(float)im.width()\/im.height()});\n pangolin::GlTexture tex8(im.width(), im.height(), GL_LUMINANCE8);\n\n while(!pangolin::ShouldQuit())\n {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glColor3f(1,1,1);\n\n if (container[0].IsShown())\n {\n container[0].Activate();\n tex8.Upload(im.data(), GL_LUMINANCE, GL_UNSIGNED_BYTE);\n tex8.RenderToViewportFlipY();\n }\n pangolin::FinishFrame();\n }\n}\n\n\/\/\/\/------------------------------------------------------------------------------\n\/\/inline void imshow(const imp::cu::ImageGpu8uC1& im, const std::string& title=\"-\")\n\/\/{\n\/\/ pangolin::View& container = imp::setupPangolinView(im.size(), title);\n\/\/ imp::setupPangolinViewLayout(container, 1, {(float)im.width()\/im.height()});\n\n\/\/ container[0].SetDrawFunction\n\n\n\/\/}\n\n\n\/\/\/\/==============================================================================\n\/\/class PangolinDisplay\n\/\/{\n\/\/public:\n\/\/ PangolinDisplay();\n\/\/ ~PangolinDisplay();\n\/\/};\n\n} \/\/ namespace imp\n\n#endif \/\/ PANGOLINDISPLAY_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <algorithm>\n#include <limits>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"build\/build_config.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if defined(OS_POSIX)\n#include <sys\/mman.h>\n#include <unistd.h>\n#endif\n\nusing std::nothrow;\nusing std::numeric_limits;\n\nnamespace {\n\n\/\/ This function acts as a compiler optimization barrier. We use it to\n\/\/ prevent the compiler from making an expression a compile-time constant.\n\/\/ We also use it so that the compiler doesn't discard certain return values\n\/\/ as something we don't need (see the comment with calloc below).\ntemplate <typename Type>\nType HideValueFromCompiler(volatile Type value) {\n return value;\n}\n\n\/\/ Check that we can not allocate a memory range that cannot be indexed\n\/\/ via an int. This is used to mitigate vulnerabilities in libraries that use\n\/\/ int instead of size_t.\n\/\/ See crbug.com\/169327.\n\n\/\/ - NO_TCMALLOC because we only patched tcmalloc\n\/\/ - ADDRESS_SANITIZER because it has its own memory allocator\n\/\/ - IOS does not seem to honor nothrow in new properly\n\/\/ - OS_MACOSX does not use tcmalloc\n#if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \\\n !defined(OS_IOS) && !defined(OS_MACOSX)\n #define ALLOC_TEST(function) function\n#else\n #define ALLOC_TEST(function) DISABLED_##function\n#endif\n\n\/\/ TODO(jln): switch to std::numeric_limits<int>::max() when we switch to\n\/\/ C++11.\nconst size_t kTooBigAllocSize = INT_MAX;\n\n\/\/ Detect runtime TCMalloc bypasses.\nbool IsTcMallocBypassed() {\n#if defined(OS_LINUX) || defined(OS_CHROMEOS)\n \/\/ This should detect a TCMalloc bypass from Valgrind.\n char* g_slice = getenv(\"G_SLICE\");\n if (g_slice && !strcmp(g_slice, \"always-malloc\"))\n return true;\n#endif\n return false;\n}\n\n\/\/ Fake test that allow to know the state of TCMalloc by looking at bots.\nTEST(SecurityTest, ALLOC_TEST(IsTCMallocDynamicallyBypassed)) {\n printf(\"Malloc is dynamically bypassed: %s\\n\",\n IsTcMallocBypassed() ? \"yes.\" : \"no.\");\n}\n\nTEST(SecurityTest, ALLOC_TEST(MemoryAllocationRestrictionsMalloc)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(malloc(kTooBigAllocSize))));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, ALLOC_TEST(MemoryAllocationRestrictionsCalloc)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, ALLOC_TEST(MemoryAllocationRestrictionsRealloc)) {\n if (!IsTcMallocBypassed()) {\n char* orig_ptr = static_cast<char*>(malloc(1));\n ASSERT_TRUE(orig_ptr);\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));\n ASSERT_TRUE(!ptr);\n \/\/ If realloc() did not succeed, we need to free orig_ptr.\n free(orig_ptr);\n }\n}\n\ntypedef struct {\n char large_array[kTooBigAllocSize];\n} VeryLargeStruct;\n\nTEST(SecurityTest, ALLOC_TEST(MemoryAllocationRestrictionsNew)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<VeryLargeStruct> ptr(\n HideValueFromCompiler(new (nothrow) VeryLargeStruct));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, ALLOC_TEST(MemoryAllocationRestrictionsNewArray)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char[]> ptr(\n HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));\n ASSERT_TRUE(!ptr);\n }\n}\n\n\/\/ The tests bellow check for overflows in new[] and calloc().\n\n#if defined(OS_IOS) || defined(OS_WIN)\n #define DISABLE_ON_IOS_AND_WIN(function) DISABLED_##function\n#else\n #define DISABLE_ON_IOS_AND_WIN(function) function\n#endif\n\n#if defined(ADDRESS_SANITIZER)\n #define DISABLE_ON_ASAN(function) DISABLED_##function\n#else\n #define DISABLE_ON_ASAN(function) function\n#endif\n\n\/\/ There are platforms where these tests are known to fail. We would like to\n\/\/ be able to easily check the status on the bots, but marking tests as\n\/\/ FAILS_ is too clunky.\nvoid OverflowTestsSoftExpectTrue(bool overflow_detected) {\n if (!overflow_detected) {\n#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)\n \/\/ Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't\n \/\/ fail the test, but report.\n printf(\"Platform has overflow: %s\\n\",\n !overflow_detected ? \"yes.\" : \"no.\");\n#else\n \/\/ Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT\n \/\/ aren't).\n EXPECT_TRUE(overflow_detected);\n#endif\n }\n}\n\n\/\/ TODO(jln): crbug.com\/174947 This can't even compile on Win64.\n#if !(defined(OS_WIN) && defined(ARCH_CPU_X86_64))\n\n\/\/ Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.\n\/\/ IOS doesn't honor nothrow, so disable the test there.\n\/\/ Disable on Windows, we suspect some are failing because of it.\nTEST(SecurityTest, DISABLE_ON_IOS_AND_WIN(NewOverflow)) {\n const size_t kArraySize = 4096;\n \/\/ We want something \"dynamic\" here, so that the compiler doesn't\n \/\/ immediately reject crazy arrays.\n const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);\n \/\/ numeric_limits are still not constexpr until we switch to C++11, so we\n \/\/ use an ugly cast.\n const size_t kMaxSizeT = ~static_cast<size_t>(0);\n ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);\n const size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);\n {\n scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)\n char[kDynamicArraySize2][kArraySize]);\n OverflowTestsSoftExpectTrue(!array_pointer);\n }\n {\n scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)\n char[kDynamicArraySize][kArraySize2]);\n OverflowTestsSoftExpectTrue(!array_pointer);\n }\n}\n#endif\n\n\/\/ Test if calloc() can overflow. Disable on ASAN for now since the\n\/\/ overflow seems present there.\nTEST(SecurityTest, DISABLE_ON_ASAN(CallocOverflow)) {\n const size_t kArraySize = 4096;\n const size_t kMaxSizeT = numeric_limits<size_t>::max();\n const size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n {\n scoped_ptr<char> array_pointer(\n static_cast<char*>(calloc(kArraySize, kArraySize2)));\n \/\/ We need the call to HideValueFromCompiler(): we have seen LLVM\n \/\/ optimize away the call to calloc() entirely and assume\n \/\/ the pointer to not be NULL.\n EXPECT_TRUE(HideValueFromCompiler(array_pointer.get()) == NULL);\n }\n {\n scoped_ptr<char> array_pointer(\n static_cast<char*>(calloc(kArraySize2, kArraySize)));\n \/\/ We need the call to HideValueFromCompiler(): we have seen LLVM\n \/\/ optimize away the call to calloc() entirely and assume\n \/\/ the pointer to not be NULL.\n EXPECT_TRUE(HideValueFromCompiler(array_pointer.get()) == NULL);\n }\n}\n\n#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)\n\/\/ Useful for debugging.\nvoid PrintProcSelfMaps() {\n int fd = open(\"\/proc\/self\/maps\", O_RDONLY);\n file_util::ScopedFD fd_closer(&fd);\n ASSERT_GE(fd, 0);\n char buffer[1<<13];\n int ret;\n ret = read(fd, buffer, sizeof(buffer) - 1);\n ASSERT_GT(ret, 0);\n buffer[ret - 1] = 0;\n fprintf(stdout, \"%s\\n\", buffer);\n}\n\n\/\/ Check if ptr1 and ptr2 are separated by less than size chars.\nbool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {\n ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -\n reinterpret_cast<char*>(std::min(ptr1, ptr2));\n return static_cast<size_t>(ptr_diff) <= size;\n}\n\n\/\/ Check if TCMalloc uses an underlying random memory allocator.\nTEST(SecurityTest, ALLOC_TEST(RandomMemoryAllocations)) {\n if (IsTcMallocBypassed())\n return;\n size_t kPageSize = 4096; \/\/ We support x86_64 only.\n \/\/ Check that malloc() returns an address that is neither the kernel's\n \/\/ un-hinted mmap area, nor the current brk() area. The first malloc() may\n \/\/ not be at a random address because TCMalloc will first exhaust any memory\n \/\/ that it has allocated early on, before starting the sophisticated\n \/\/ allocators.\n void* default_mmap_heap_address =\n mmap(0, kPageSize, PROT_READ|PROT_WRITE,\n MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);\n ASSERT_NE(default_mmap_heap_address,\n static_cast<void*>(MAP_FAILED));\n ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);\n void* brk_heap_address = sbrk(0);\n ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));\n ASSERT_TRUE(brk_heap_address != NULL);\n \/\/ 1 MB should get us past what TCMalloc pre-allocated before initializing\n \/\/ the sophisticated allocators.\n size_t kAllocSize = 1<<20;\n scoped_ptr<char, base::FreeDeleter> ptr(\n static_cast<char*>(malloc(kAllocSize)));\n ASSERT_TRUE(ptr != NULL);\n \/\/ If two pointers are separated by less than 512MB, they are considered\n \/\/ to be in the same area.\n \/\/ Our random pointer could be anywhere within 0x3fffffffffff (46bits),\n \/\/ and we are checking that it's not withing 1GB (30 bits) from two\n \/\/ addresses (brk and mmap heap). We have roughly one chance out of\n \/\/ 2^15 to flake.\n const size_t kAreaRadius = 1<<29;\n bool in_default_mmap_heap = ArePointersToSameArea(\n ptr.get(), default_mmap_heap_address, kAreaRadius);\n EXPECT_FALSE(in_default_mmap_heap);\n\n bool in_default_brk_heap = ArePointersToSameArea(\n ptr.get(), brk_heap_address, kAreaRadius);\n EXPECT_FALSE(in_default_brk_heap);\n\n \/\/ In the implementation, we always mask our random addresses with\n \/\/ kRandomMask, so we use it as an additional detection mechanism.\n const uintptr_t kRandomMask = 0x3fffffffffffULL;\n bool impossible_random_address =\n reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;\n EXPECT_FALSE(impossible_random_address);\n}\n\n#endif \/\/ (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)\n\n} \/\/ namespace\n<commit_msg>Base: account for calloc aborting in security unittests<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <algorithm>\n#include <limits>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"build\/build_config.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if defined(OS_POSIX)\n#include <sys\/mman.h>\n#include <unistd.h>\n#endif\n\nusing std::nothrow;\nusing std::numeric_limits;\n\nnamespace {\n\n\/\/ This function acts as a compiler optimization barrier. We use it to\n\/\/ prevent the compiler from making an expression a compile-time constant.\n\/\/ We also use it so that the compiler doesn't discard certain return values\n\/\/ as something we don't need (see the comment with calloc below).\ntemplate <typename Type>\nType HideValueFromCompiler(volatile Type value) {\n return value;\n}\n\n\/\/ - NO_TCMALLOC (should be defined if we compile with linux_use_tcmalloc=0)\n\/\/ - ADDRESS_SANITIZER because it has its own memory allocator\n\/\/ - IOS does not use tcmalloc\n\/\/ - OS_MACOSX does not use tcmalloc\n#if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \\\n !defined(OS_IOS) && !defined(OS_MACOSX)\n #define TCMALLOC_TEST(function) function\n#else\n #define TCMALLOC_TEST(function) DISABLED_##function\n#endif\n\n\/\/ TODO(jln): switch to std::numeric_limits<int>::max() when we switch to\n\/\/ C++11.\nconst size_t kTooBigAllocSize = INT_MAX;\n\n\/\/ Detect runtime TCMalloc bypasses.\nbool IsTcMallocBypassed() {\n#if defined(OS_LINUX) || defined(OS_CHROMEOS)\n \/\/ This should detect a TCMalloc bypass from Valgrind.\n char* g_slice = getenv(\"G_SLICE\");\n if (g_slice && !strcmp(g_slice, \"always-malloc\"))\n return true;\n#endif\n return false;\n}\n\nbool CallocDiesOnOOM() {\n\/\/ The wrapper function in base\/process_util_linux.cc that is used when we\n\/\/ compile without TCMalloc will just die on OOM instead of returning NULL.\n#if defined(OS_LINUX) && defined(NO_TCMALLOC)\n return true;\n#else\n return false;\n#endif\n}\n\n\/\/ Fake test that allow to know the state of TCMalloc by looking at bots.\nTEST(SecurityTest, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed)) {\n printf(\"Malloc is dynamically bypassed: %s\\n\",\n IsTcMallocBypassed() ? \"yes.\" : \"no.\");\n}\n\n\/\/ The MemoryAllocationRestrictions* tests test that we can not allocate a\n\/\/ memory range that cannot be indexed via an int. This is used to mitigate\n\/\/ vulnerabilities in libraries that use int instead of size_t. See\n\/\/ crbug.com\/169327.\n\nTEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(malloc(kTooBigAllocSize))));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc)) {\n if (!IsTcMallocBypassed()) {\n char* orig_ptr = static_cast<char*>(malloc(1));\n ASSERT_TRUE(orig_ptr);\n scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(\n HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));\n ASSERT_TRUE(!ptr);\n \/\/ If realloc() did not succeed, we need to free orig_ptr.\n free(orig_ptr);\n }\n}\n\ntypedef struct {\n char large_array[kTooBigAllocSize];\n} VeryLargeStruct;\n\nTEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNew)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<VeryLargeStruct> ptr(\n HideValueFromCompiler(new (nothrow) VeryLargeStruct));\n ASSERT_TRUE(!ptr);\n }\n}\n\nTEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray)) {\n if (!IsTcMallocBypassed()) {\n scoped_ptr<char[]> ptr(\n HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));\n ASSERT_TRUE(!ptr);\n }\n}\n\n\/\/ The tests bellow check for overflows in new[] and calloc().\n\n#if defined(OS_IOS) || defined(OS_WIN)\n #define DISABLE_ON_IOS_AND_WIN(function) DISABLED_##function\n#else\n #define DISABLE_ON_IOS_AND_WIN(function) function\n#endif\n\n#if defined(ADDRESS_SANITIZER)\n #define DISABLE_ON_ASAN(function) DISABLED_##function\n#else\n #define DISABLE_ON_ASAN(function) function\n#endif\n\n\/\/ There are platforms where these tests are known to fail. We would like to\n\/\/ be able to easily check the status on the bots, but marking tests as\n\/\/ FAILS_ is too clunky.\nvoid OverflowTestsSoftExpectTrue(bool overflow_detected) {\n if (!overflow_detected) {\n#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)\n \/\/ Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't\n \/\/ fail the test, but report.\n printf(\"Platform has overflow: %s\\n\",\n !overflow_detected ? \"yes.\" : \"no.\");\n#else\n \/\/ Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT\n \/\/ aren't).\n EXPECT_TRUE(overflow_detected);\n#endif\n }\n}\n\n\/\/ TODO(jln): crbug.com\/174947 This can't even compile on Win64.\n#if !(defined(OS_WIN) && defined(ARCH_CPU_X86_64))\n\n\/\/ Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.\n\/\/ IOS doesn't honor nothrow, so disable the test there.\n\/\/ Disable on Windows, we suspect some are failing because of it.\nTEST(SecurityTest, DISABLE_ON_IOS_AND_WIN(NewOverflow)) {\n const size_t kArraySize = 4096;\n \/\/ We want something \"dynamic\" here, so that the compiler doesn't\n \/\/ immediately reject crazy arrays.\n const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);\n \/\/ numeric_limits are still not constexpr until we switch to C++11, so we\n \/\/ use an ugly cast.\n const size_t kMaxSizeT = ~static_cast<size_t>(0);\n ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);\n const size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);\n {\n scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)\n char[kDynamicArraySize2][kArraySize]);\n OverflowTestsSoftExpectTrue(!array_pointer);\n }\n {\n scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)\n char[kDynamicArraySize][kArraySize2]);\n OverflowTestsSoftExpectTrue(!array_pointer);\n }\n}\n#endif\n\n\/\/ Call calloc(), eventually free the memory and return whether or not\n\/\/ calloc() did succeed.\nbool CallocReturnsNull(size_t nmemb, size_t size) {\n scoped_ptr<char, base::FreeDeleter> array_pointer(\n static_cast<char*>(calloc(nmemb, size)));\n \/\/ We need the call to HideValueFromCompiler(): we have seen LLVM\n \/\/ optimize away the call to calloc() entirely and assume\n \/\/ the pointer to not be NULL.\n return HideValueFromCompiler(array_pointer.get()) == NULL;\n}\n\n\/\/ Test if calloc() can overflow. Disable on ASAN for now since the\n\/\/ overflow seems present there (crbug.com\/175554).\nTEST(SecurityTest, DISABLE_ON_ASAN(CallocOverflow)) {\n const size_t kArraySize = 4096;\n const size_t kMaxSizeT = numeric_limits<size_t>::max();\n const size_t kArraySize2 = kMaxSizeT \/ kArraySize + 10;\n if (!CallocDiesOnOOM()) {\n EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2));\n EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize));\n } else {\n \/\/ It's also ok for calloc to just terminate the process.\n#if defined(GTEST_HAS_DEATH_TEST)\n EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), \"\");\n EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), \"\");\n#endif \/\/ GTEST_HAS_DEATH_TEST\n }\n}\n\n#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)\n\/\/ Useful for debugging.\nvoid PrintProcSelfMaps() {\n int fd = open(\"\/proc\/self\/maps\", O_RDONLY);\n file_util::ScopedFD fd_closer(&fd);\n ASSERT_GE(fd, 0);\n char buffer[1<<13];\n int ret;\n ret = read(fd, buffer, sizeof(buffer) - 1);\n ASSERT_GT(ret, 0);\n buffer[ret - 1] = 0;\n fprintf(stdout, \"%s\\n\", buffer);\n}\n\n\/\/ Check if ptr1 and ptr2 are separated by less than size chars.\nbool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {\n ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -\n reinterpret_cast<char*>(std::min(ptr1, ptr2));\n return static_cast<size_t>(ptr_diff) <= size;\n}\n\n\/\/ Check if TCMalloc uses an underlying random memory allocator.\nTEST(SecurityTest, TCMALLOC_TEST(RandomMemoryAllocations)) {\n if (IsTcMallocBypassed())\n return;\n size_t kPageSize = 4096; \/\/ We support x86_64 only.\n \/\/ Check that malloc() returns an address that is neither the kernel's\n \/\/ un-hinted mmap area, nor the current brk() area. The first malloc() may\n \/\/ not be at a random address because TCMalloc will first exhaust any memory\n \/\/ that it has allocated early on, before starting the sophisticated\n \/\/ allocators.\n void* default_mmap_heap_address =\n mmap(0, kPageSize, PROT_READ|PROT_WRITE,\n MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);\n ASSERT_NE(default_mmap_heap_address,\n static_cast<void*>(MAP_FAILED));\n ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);\n void* brk_heap_address = sbrk(0);\n ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));\n ASSERT_TRUE(brk_heap_address != NULL);\n \/\/ 1 MB should get us past what TCMalloc pre-allocated before initializing\n \/\/ the sophisticated allocators.\n size_t kAllocSize = 1<<20;\n scoped_ptr<char, base::FreeDeleter> ptr(\n static_cast<char*>(malloc(kAllocSize)));\n ASSERT_TRUE(ptr != NULL);\n \/\/ If two pointers are separated by less than 512MB, they are considered\n \/\/ to be in the same area.\n \/\/ Our random pointer could be anywhere within 0x3fffffffffff (46bits),\n \/\/ and we are checking that it's not withing 1GB (30 bits) from two\n \/\/ addresses (brk and mmap heap). We have roughly one chance out of\n \/\/ 2^15 to flake.\n const size_t kAreaRadius = 1<<29;\n bool in_default_mmap_heap = ArePointersToSameArea(\n ptr.get(), default_mmap_heap_address, kAreaRadius);\n EXPECT_FALSE(in_default_mmap_heap);\n\n bool in_default_brk_heap = ArePointersToSameArea(\n ptr.get(), brk_heap_address, kAreaRadius);\n EXPECT_FALSE(in_default_brk_heap);\n\n \/\/ In the implementation, we always mask our random addresses with\n \/\/ kRandomMask, so we use it as an additional detection mechanism.\n const uintptr_t kRandomMask = 0x3fffffffffffULL;\n bool impossible_random_address =\n reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;\n EXPECT_FALSE(impossible_random_address);\n}\n\n#endif \/\/ (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017-2019 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"DebugMessageView.h\"\n#include <QAction>\n#include <QMenu>\n#include \"Code\/QRDUtils.h\"\n#include \"ui_DebugMessageView.h\"\n\nstatic const int EIDRole = Qt::UserRole + 1;\nstatic const int SortDataRole = Qt::UserRole + 2;\n\nclass DebugMessageItemModel : public QAbstractItemModel\n{\npublic:\n DebugMessageItemModel(ICaptureContext &ctx, QObject *parent)\n : QAbstractItemModel(parent), m_Ctx(ctx)\n {\n }\n\n void refresh()\n {\n emit beginResetModel();\n emit endResetModel();\n }\n\n QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override\n {\n if(row < 0 || row >= rowCount())\n return QModelIndex();\n\n return createIndex(row, column);\n }\n\n QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); }\n int rowCount(const QModelIndex &parent = QModelIndex()) const override\n {\n return m_Ctx.DebugMessages().count();\n }\n int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 6; }\n Qt::ItemFlags flags(const QModelIndex &index) const override\n {\n if(!index.isValid())\n return 0;\n\n return QAbstractItemModel::flags(index);\n }\n\n QVariant headerData(int section, Qt::Orientation orientation, int role) const override\n {\n if(orientation == Qt::Horizontal && role == Qt::DisplayRole)\n {\n switch(section)\n {\n case 0: return lit(\"EID\");\n case 1: return lit(\"Source\");\n case 2: return lit(\"Severity\");\n case 3: return lit(\"Category\");\n case 4: return lit(\"ID\");\n case 5: return lit(\"Description\");\n default: break;\n }\n }\n\n return QVariant();\n }\n\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override\n {\n if(index.isValid() && (role == Qt::DisplayRole || role == SortDataRole))\n {\n bool sort = (role == SortDataRole);\n\n int row = index.row();\n int col = index.column();\n\n if(col >= 0 && col < columnCount() && row < rowCount())\n {\n const DebugMessage &msg = m_Ctx.DebugMessages()[row];\n\n switch(col)\n {\n case 0: return msg.eventId;\n case 1: return ToQStr(msg.source);\n case 2: return sort ? QVariant((uint32_t)msg.severity) : QVariant(ToQStr(msg.severity));\n case 3: return ToQStr(msg.category);\n case 4: return msg.messageID;\n case 5:\n {\n QVariant desc = msg.description;\n RichResourceTextInitialise(desc);\n return desc;\n }\n default: break;\n }\n }\n }\n\n if(index.isValid() && role == EIDRole && index.row() >= 0 &&\n index.row() < m_Ctx.DebugMessages().count())\n return m_Ctx.DebugMessages()[index.row()].eventId;\n\n return QVariant();\n }\n\nprivate:\n ICaptureContext &m_Ctx;\n};\n\nclass DebugMessageFilterModel : public QSortFilterProxyModel\n{\npublic:\n DebugMessageFilterModel(ICaptureContext &ctx, QObject *parent)\n : QSortFilterProxyModel(parent), m_Ctx(ctx)\n {\n }\n\n typedef QPair<QPair<MessageSource, MessageCategory>, uint32_t> MessageType;\n static MessageType makeType(const DebugMessage &msg)\n {\n return qMakePair(qMakePair(msg.source, msg.category), msg.messageID);\n }\n\n QList<MessageSource> m_HiddenSources;\n QList<MessageCategory> m_HiddenCategories;\n QList<MessageSeverity> m_HiddenSeverities;\n QList<MessageType> m_HiddenTypes;\n\n bool showHidden = false;\n\n void refresh() { invalidateFilter(); }\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override\n {\n if(role == Qt::FontRole && !isVisibleRow(mapToSource(index).row()))\n {\n QFont font;\n font.setItalic(true);\n return font;\n }\n\n return QSortFilterProxyModel::data(index, role);\n }\n\nprotected:\n bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override\n {\n if(showHidden)\n return true;\n\n return isVisibleRow(sourceRow);\n }\n\n bool isVisibleRow(int sourceRow) const\n {\n const DebugMessage &msg = m_Ctx.DebugMessages()[sourceRow];\n\n if(m_HiddenSources.contains(msg.source))\n return false;\n\n if(m_HiddenCategories.contains(msg.category))\n return false;\n\n if(m_HiddenSeverities.contains(msg.severity))\n return false;\n\n if(m_HiddenTypes.contains(makeType(msg)))\n return false;\n\n return true;\n }\n\n bool lessThan(const QModelIndex &left, const QModelIndex &right) const override\n {\n return sourceModel()->data(left, SortDataRole) < sourceModel()->data(right, SortDataRole);\n }\n\nprivate:\n ICaptureContext &m_Ctx;\n};\n\nDebugMessageView::DebugMessageView(ICaptureContext &ctx, QWidget *parent)\n : QFrame(parent), ui(new Ui::DebugMessageView), m_Ctx(ctx)\n{\n ui->setupUi(this);\n\n m_ItemModel = new DebugMessageItemModel(m_Ctx, this);\n m_FilterModel = new DebugMessageFilterModel(m_Ctx, this);\n\n m_FilterModel->setSourceModel(m_ItemModel);\n ui->messages->setModel(m_FilterModel);\n\n ui->messages->setSortingEnabled(true);\n ui->messages->sortByColumn(0, Qt::AscendingOrder);\n\n ui->messages->setMouseTracking(true);\n ui->messages->setAutoScroll(false);\n\n ui->messages->horizontalHeader()->setStretchLastSection(false);\n\n ui->messages->setContextMenuPolicy(Qt::CustomContextMenu);\n QObject::connect(ui->messages, &QWidget::customContextMenuRequested, this,\n &DebugMessageView::messages_contextMenu);\n\n ui->messages->setFont(Formatter::PreferredFont());\n\n m_ContextMenu = new QMenu(this);\n\n m_ShowHidden = new QAction(tr(\"Show hidden rows\"), this);\n m_ToggleSource = new QAction(QString(), this);\n m_ToggleSeverity = new QAction(QString(), this);\n m_ToggleCategory = new QAction(QString(), this);\n m_ToggleMessageType = new QAction(QString(), this);\n\n m_ShowHidden->setCheckable(true);\n\n m_ContextMenu->addAction(m_ShowHidden);\n m_ContextMenu->addSeparator();\n m_ContextMenu->addAction(m_ToggleSource);\n m_ContextMenu->addAction(m_ToggleSeverity);\n m_ContextMenu->addAction(m_ToggleCategory);\n m_ContextMenu->addAction(m_ToggleMessageType);\n\n QObject::connect(m_ShowHidden, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleSource, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleSeverity, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleCategory, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleMessageType, &QAction::triggered, this,\n &DebugMessageView::messages_toggled);\n\n RefreshMessageList();\n\n m_Ctx.AddCaptureViewer(this);\n}\n\nDebugMessageView::~DebugMessageView()\n{\n m_Ctx.BuiltinWindowClosed(this);\n\n m_Ctx.RemoveCaptureViewer(this);\n delete ui;\n}\n\nvoid DebugMessageView::OnCaptureClosed()\n{\n m_FilterModel->showHidden = false;\n RefreshMessageList();\n}\n\nvoid DebugMessageView::OnCaptureLoaded()\n{\n m_FilterModel->showHidden = false;\n RefreshMessageList();\n}\n\nvoid DebugMessageView::RefreshMessageList()\n{\n m_ItemModel->refresh();\n\n ui->messages->resizeColumnsToContents();\n\n if(m_Ctx.UnreadMessageCount() > 0)\n setWindowTitle(tr(\"(%1) Errors and Warnings\").arg(m_Ctx.UnreadMessageCount()));\n else\n setWindowTitle(tr(\"Errors and Warnings\"));\n}\n\nvoid DebugMessageView::on_messages_doubleClicked(const QModelIndex &index)\n{\n QVariant var = m_FilterModel->data(index, EIDRole);\n\n if(var.isValid())\n {\n uint32_t eid = var.toUInt();\n m_Ctx.SetEventID({}, eid, eid);\n }\n}\n\nvoid DebugMessageView::messages_toggled()\n{\n QAction *action = qobject_cast<QAction *>(QObject::sender());\n\n if(action == m_ShowHidden)\n {\n m_FilterModel->showHidden = !m_FilterModel->showHidden;\n m_ShowHidden->setChecked(m_FilterModel->showHidden);\n }\n else if(action == m_ToggleSource)\n {\n if(m_FilterModel->m_HiddenSources.contains(m_ContextMessage.source))\n m_FilterModel->m_HiddenSources.removeOne(m_ContextMessage.source);\n else\n m_FilterModel->m_HiddenSources.push_back(m_ContextMessage.source);\n }\n else if(action == m_ToggleSeverity)\n {\n if(m_FilterModel->m_HiddenSeverities.contains(m_ContextMessage.severity))\n m_FilterModel->m_HiddenSeverities.removeOne(m_ContextMessage.severity);\n else\n m_FilterModel->m_HiddenSeverities.push_back(m_ContextMessage.severity);\n }\n else if(action == m_ToggleCategory)\n {\n if(m_FilterModel->m_HiddenCategories.contains(m_ContextMessage.category))\n m_FilterModel->m_HiddenCategories.removeOne(m_ContextMessage.category);\n else\n m_FilterModel->m_HiddenCategories.push_back(m_ContextMessage.category);\n }\n else if(action == m_ToggleMessageType)\n {\n auto type = DebugMessageFilterModel::makeType(m_ContextMessage);\n if(m_FilterModel->m_HiddenTypes.contains(type))\n m_FilterModel->m_HiddenTypes.removeOne(type);\n else\n m_FilterModel->m_HiddenTypes.push_back(type);\n }\n\n m_FilterModel->refresh();\n}\n\nvoid DebugMessageView::messages_contextMenu(const QPoint &pos)\n{\n if(!m_Ctx.IsCaptureLoaded())\n return;\n\n QModelIndex index = ui->messages->indexAt(pos);\n\n if(index.isValid())\n {\n index = m_FilterModel->mapToSource(index);\n\n m_ToggleSource->setVisible(true);\n m_ToggleSeverity->setVisible(true);\n m_ToggleCategory->setVisible(true);\n m_ToggleMessageType->setVisible(true);\n\n const DebugMessage &msg = m_Ctx.DebugMessages()[index.row()];\n\n QString hide = tr(\"Hide\");\n QString show = tr(\"Show\");\n\n bool hidden = m_FilterModel->m_HiddenSources.contains(msg.source);\n m_ToggleSource->setText(tr(\"%1 Source: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.source)));\n\n hidden = m_FilterModel->m_HiddenSeverities.contains(msg.severity);\n m_ToggleSeverity->setText(\n tr(\"%1 Severity: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.severity)));\n\n hidden = m_FilterModel->m_HiddenCategories.contains(msg.category);\n m_ToggleCategory->setText(\n tr(\"%1 Category: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.category)));\n\n hidden = m_FilterModel->m_HiddenTypes.contains(DebugMessageFilterModel::makeType(msg));\n m_ToggleMessageType->setText(tr(\"%1 Message Type\").arg(hidden ? show : hide));\n\n m_ContextMessage = msg;\n }\n else\n {\n m_ToggleSource->setVisible(false);\n m_ToggleSeverity->setVisible(false);\n m_ToggleCategory->setVisible(false);\n m_ToggleMessageType->setVisible(false);\n }\n\n QString showHidden = tr(\"Show hidden rows\");\n QString hideHidden = tr(\"Stop showing hidden rows\");\n\n m_ShowHidden->setText(m_FilterModel->showHidden ? hideHidden : showHidden);\n\n RDDialog::show(m_ContextMenu, ui->messages->viewport()->mapToGlobal(pos));\n}\n\nvoid DebugMessageView::paintEvent(QPaintEvent *e)\n{\n if(m_Ctx.UnreadMessageCount() > 0)\n {\n m_Ctx.MarkMessagesRead();\n RefreshMessageList();\n }\n\n QFrame::paintEvent(e);\n}\n<commit_msg>Keep \"Show hidden rows\" text constant now that checkbox appears<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2017-2019 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"DebugMessageView.h\"\n#include <QAction>\n#include <QMenu>\n#include \"Code\/QRDUtils.h\"\n#include \"ui_DebugMessageView.h\"\n\nstatic const int EIDRole = Qt::UserRole + 1;\nstatic const int SortDataRole = Qt::UserRole + 2;\n\nclass DebugMessageItemModel : public QAbstractItemModel\n{\npublic:\n DebugMessageItemModel(ICaptureContext &ctx, QObject *parent)\n : QAbstractItemModel(parent), m_Ctx(ctx)\n {\n }\n\n void refresh()\n {\n emit beginResetModel();\n emit endResetModel();\n }\n\n QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override\n {\n if(row < 0 || row >= rowCount())\n return QModelIndex();\n\n return createIndex(row, column);\n }\n\n QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); }\n int rowCount(const QModelIndex &parent = QModelIndex()) const override\n {\n return m_Ctx.DebugMessages().count();\n }\n int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 6; }\n Qt::ItemFlags flags(const QModelIndex &index) const override\n {\n if(!index.isValid())\n return 0;\n\n return QAbstractItemModel::flags(index);\n }\n\n QVariant headerData(int section, Qt::Orientation orientation, int role) const override\n {\n if(orientation == Qt::Horizontal && role == Qt::DisplayRole)\n {\n switch(section)\n {\n case 0: return lit(\"EID\");\n case 1: return lit(\"Source\");\n case 2: return lit(\"Severity\");\n case 3: return lit(\"Category\");\n case 4: return lit(\"ID\");\n case 5: return lit(\"Description\");\n default: break;\n }\n }\n\n return QVariant();\n }\n\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override\n {\n if(index.isValid() && (role == Qt::DisplayRole || role == SortDataRole))\n {\n bool sort = (role == SortDataRole);\n\n int row = index.row();\n int col = index.column();\n\n if(col >= 0 && col < columnCount() && row < rowCount())\n {\n const DebugMessage &msg = m_Ctx.DebugMessages()[row];\n\n switch(col)\n {\n case 0: return msg.eventId;\n case 1: return ToQStr(msg.source);\n case 2: return sort ? QVariant((uint32_t)msg.severity) : QVariant(ToQStr(msg.severity));\n case 3: return ToQStr(msg.category);\n case 4: return msg.messageID;\n case 5:\n {\n QVariant desc = msg.description;\n RichResourceTextInitialise(desc);\n return desc;\n }\n default: break;\n }\n }\n }\n\n if(index.isValid() && role == EIDRole && index.row() >= 0 &&\n index.row() < m_Ctx.DebugMessages().count())\n return m_Ctx.DebugMessages()[index.row()].eventId;\n\n return QVariant();\n }\n\nprivate:\n ICaptureContext &m_Ctx;\n};\n\nclass DebugMessageFilterModel : public QSortFilterProxyModel\n{\npublic:\n DebugMessageFilterModel(ICaptureContext &ctx, QObject *parent)\n : QSortFilterProxyModel(parent), m_Ctx(ctx)\n {\n }\n\n typedef QPair<QPair<MessageSource, MessageCategory>, uint32_t> MessageType;\n static MessageType makeType(const DebugMessage &msg)\n {\n return qMakePair(qMakePair(msg.source, msg.category), msg.messageID);\n }\n\n QList<MessageSource> m_HiddenSources;\n QList<MessageCategory> m_HiddenCategories;\n QList<MessageSeverity> m_HiddenSeverities;\n QList<MessageType> m_HiddenTypes;\n\n bool showHidden = false;\n\n void refresh() { invalidateFilter(); }\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override\n {\n if(role == Qt::FontRole && !isVisibleRow(mapToSource(index).row()))\n {\n QFont font;\n font.setItalic(true);\n return font;\n }\n\n return QSortFilterProxyModel::data(index, role);\n }\n\nprotected:\n bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override\n {\n if(showHidden)\n return true;\n\n return isVisibleRow(sourceRow);\n }\n\n bool isVisibleRow(int sourceRow) const\n {\n const DebugMessage &msg = m_Ctx.DebugMessages()[sourceRow];\n\n if(m_HiddenSources.contains(msg.source))\n return false;\n\n if(m_HiddenCategories.contains(msg.category))\n return false;\n\n if(m_HiddenSeverities.contains(msg.severity))\n return false;\n\n if(m_HiddenTypes.contains(makeType(msg)))\n return false;\n\n return true;\n }\n\n bool lessThan(const QModelIndex &left, const QModelIndex &right) const override\n {\n return sourceModel()->data(left, SortDataRole) < sourceModel()->data(right, SortDataRole);\n }\n\nprivate:\n ICaptureContext &m_Ctx;\n};\n\nDebugMessageView::DebugMessageView(ICaptureContext &ctx, QWidget *parent)\n : QFrame(parent), ui(new Ui::DebugMessageView), m_Ctx(ctx)\n{\n ui->setupUi(this);\n\n m_ItemModel = new DebugMessageItemModel(m_Ctx, this);\n m_FilterModel = new DebugMessageFilterModel(m_Ctx, this);\n\n m_FilterModel->setSourceModel(m_ItemModel);\n ui->messages->setModel(m_FilterModel);\n\n ui->messages->setSortingEnabled(true);\n ui->messages->sortByColumn(0, Qt::AscendingOrder);\n\n ui->messages->setMouseTracking(true);\n ui->messages->setAutoScroll(false);\n\n ui->messages->horizontalHeader()->setStretchLastSection(false);\n\n ui->messages->setContextMenuPolicy(Qt::CustomContextMenu);\n QObject::connect(ui->messages, &QWidget::customContextMenuRequested, this,\n &DebugMessageView::messages_contextMenu);\n\n ui->messages->setFont(Formatter::PreferredFont());\n\n m_ContextMenu = new QMenu(this);\n\n m_ShowHidden = new QAction(tr(\"Show hidden rows\"), this);\n m_ToggleSource = new QAction(QString(), this);\n m_ToggleSeverity = new QAction(QString(), this);\n m_ToggleCategory = new QAction(QString(), this);\n m_ToggleMessageType = new QAction(QString(), this);\n\n m_ShowHidden->setCheckable(true);\n\n m_ContextMenu->addAction(m_ShowHidden);\n m_ContextMenu->addSeparator();\n m_ContextMenu->addAction(m_ToggleSource);\n m_ContextMenu->addAction(m_ToggleSeverity);\n m_ContextMenu->addAction(m_ToggleCategory);\n m_ContextMenu->addAction(m_ToggleMessageType);\n\n QObject::connect(m_ShowHidden, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleSource, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleSeverity, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleCategory, &QAction::triggered, this, &DebugMessageView::messages_toggled);\n QObject::connect(m_ToggleMessageType, &QAction::triggered, this,\n &DebugMessageView::messages_toggled);\n\n RefreshMessageList();\n\n m_Ctx.AddCaptureViewer(this);\n}\n\nDebugMessageView::~DebugMessageView()\n{\n m_Ctx.BuiltinWindowClosed(this);\n\n m_Ctx.RemoveCaptureViewer(this);\n delete ui;\n}\n\nvoid DebugMessageView::OnCaptureClosed()\n{\n m_FilterModel->showHidden = false;\n RefreshMessageList();\n}\n\nvoid DebugMessageView::OnCaptureLoaded()\n{\n m_FilterModel->showHidden = false;\n RefreshMessageList();\n}\n\nvoid DebugMessageView::RefreshMessageList()\n{\n m_ItemModel->refresh();\n\n ui->messages->resizeColumnsToContents();\n\n if(m_Ctx.UnreadMessageCount() > 0)\n setWindowTitle(tr(\"(%1) Errors and Warnings\").arg(m_Ctx.UnreadMessageCount()));\n else\n setWindowTitle(tr(\"Errors and Warnings\"));\n}\n\nvoid DebugMessageView::on_messages_doubleClicked(const QModelIndex &index)\n{\n QVariant var = m_FilterModel->data(index, EIDRole);\n\n if(var.isValid())\n {\n uint32_t eid = var.toUInt();\n m_Ctx.SetEventID({}, eid, eid);\n }\n}\n\nvoid DebugMessageView::messages_toggled()\n{\n QAction *action = qobject_cast<QAction *>(QObject::sender());\n\n if(action == m_ShowHidden)\n {\n m_FilterModel->showHidden = !m_FilterModel->showHidden;\n m_ShowHidden->setChecked(m_FilterModel->showHidden);\n }\n else if(action == m_ToggleSource)\n {\n if(m_FilterModel->m_HiddenSources.contains(m_ContextMessage.source))\n m_FilterModel->m_HiddenSources.removeOne(m_ContextMessage.source);\n else\n m_FilterModel->m_HiddenSources.push_back(m_ContextMessage.source);\n }\n else if(action == m_ToggleSeverity)\n {\n if(m_FilterModel->m_HiddenSeverities.contains(m_ContextMessage.severity))\n m_FilterModel->m_HiddenSeverities.removeOne(m_ContextMessage.severity);\n else\n m_FilterModel->m_HiddenSeverities.push_back(m_ContextMessage.severity);\n }\n else if(action == m_ToggleCategory)\n {\n if(m_FilterModel->m_HiddenCategories.contains(m_ContextMessage.category))\n m_FilterModel->m_HiddenCategories.removeOne(m_ContextMessage.category);\n else\n m_FilterModel->m_HiddenCategories.push_back(m_ContextMessage.category);\n }\n else if(action == m_ToggleMessageType)\n {\n auto type = DebugMessageFilterModel::makeType(m_ContextMessage);\n if(m_FilterModel->m_HiddenTypes.contains(type))\n m_FilterModel->m_HiddenTypes.removeOne(type);\n else\n m_FilterModel->m_HiddenTypes.push_back(type);\n }\n\n m_FilterModel->refresh();\n}\n\nvoid DebugMessageView::messages_contextMenu(const QPoint &pos)\n{\n if(!m_Ctx.IsCaptureLoaded())\n return;\n\n QModelIndex index = ui->messages->indexAt(pos);\n\n if(index.isValid())\n {\n index = m_FilterModel->mapToSource(index);\n\n m_ToggleSource->setVisible(true);\n m_ToggleSeverity->setVisible(true);\n m_ToggleCategory->setVisible(true);\n m_ToggleMessageType->setVisible(true);\n\n const DebugMessage &msg = m_Ctx.DebugMessages()[index.row()];\n\n QString hide = tr(\"Hide\");\n QString show = tr(\"Show\");\n\n bool hidden = m_FilterModel->m_HiddenSources.contains(msg.source);\n m_ToggleSource->setText(tr(\"%1 Source: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.source)));\n\n hidden = m_FilterModel->m_HiddenSeverities.contains(msg.severity);\n m_ToggleSeverity->setText(\n tr(\"%1 Severity: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.severity)));\n\n hidden = m_FilterModel->m_HiddenCategories.contains(msg.category);\n m_ToggleCategory->setText(\n tr(\"%1 Category: %2\").arg(hidden ? show : hide).arg(ToQStr(msg.category)));\n\n hidden = m_FilterModel->m_HiddenTypes.contains(DebugMessageFilterModel::makeType(msg));\n m_ToggleMessageType->setText(tr(\"%1 Message Type\").arg(hidden ? show : hide));\n\n m_ContextMessage = msg;\n }\n else\n {\n m_ToggleSource->setVisible(false);\n m_ToggleSeverity->setVisible(false);\n m_ToggleCategory->setVisible(false);\n m_ToggleMessageType->setVisible(false);\n }\n\n RDDialog::show(m_ContextMenu, ui->messages->viewport()->mapToGlobal(pos));\n}\n\nvoid DebugMessageView::paintEvent(QPaintEvent *e)\n{\n if(m_Ctx.UnreadMessageCount() > 0)\n {\n m_Ctx.MarkMessagesRead();\n RefreshMessageList();\n }\n\n QFrame::paintEvent(e);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <memory>\n\n#include <syslog.h>\n\n#include <zmq.hpp>\n\n#include <google\/protobuf\/io\/coded_stream.h>\n#include <google\/protobuf\/io\/zero_copy_stream_impl_lite.h>\n\n#include <magic.h>\n\n#include <Magick++.h>\n\n#include \"io.hpp\"\n#include \"thumq.pb.h\"\n\nnamespace protobuf = google::protobuf;\n\nusing namespace thumq;\n\nnamespace {\n\nstatic magic_t magic_cookie;\n\nstatic bool decode_request(zmq::message_t &message, Request &request)\n{\n\tprotobuf::io::ArrayInputStream array(message.data(), message.size());\n\tprotobuf::io::CodedInputStream coded(&array);\n\n\treturn request.MergePartialFromCodedStream(&coded);\n}\n\nstatic void encode_response(const Response &response, zmq::message_t &message)\n{\n\tmessage.rebuild(response.ByteSize());\n\n\tprotobuf::io::ArrayOutputStream array(message.data(), message.size());\n\tprotobuf::io::CodedOutputStream coded(&array);\n\n\tresponse.SerializeWithCachedSizes(&coded);\n}\n\nstatic void convert_image(Magick::Image &image, int scale, Request::Crop crop)\n{\n\tswitch (atoi(image.attribute(\"EXIF:Orientation\").c_str())) {\n\tcase Magick::TopLeftOrientation:\n\t\tbreak;\n\n\tcase Magick::TopRightOrientation:\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::BottomRightOrientation:\n\t\timage.rotate(180);\n\t\tbreak;\n\n\tcase Magick::BottomLeftOrientation:\n\t\timage.flip();\n\t\tbreak;\n\n\tcase Magick::LeftTopOrientation:\n\t\timage.rotate(90);\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::RightTopOrientation:\n\t\timage.rotate(90);\n\t\tbreak;\n\n\tcase Magick::RightBottomOrientation:\n\t\timage.rotate(270);\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::LeftBottomOrientation:\n\t\timage.rotate(270);\n\t\tbreak;\n\t}\n\n\tMagick::Geometry size = image.size();\n\tint width = size.width();\n\tint height = size.height();\n\n\tswitch (crop) {\n\tcase Request::NO_CROP:\n\t\tbreak;\n\n\tcase Request::TOP_SQUARE:\n\t\tif (width < height) {\n\t\t\timage.crop(Magick::Geometry(width, width));\n\t\t\theight = width;\n\t\t} else {\n\t\t\timage.crop(Magick::Geometry(height, height, (width - height) \/ 2, 0));\n\t\t\twidth = height;\n\t\t}\n\t\tbreak;\n\t}\n\n\tif (width > scale || height > scale)\n\t\timage.scale(Magick::Geometry(scale, scale));\n\n\timage.strip();\n}\n\nstatic void free_blob_data(void *, void *hint)\n{\n\tMagick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint);\n\tdelete blob;\n\n}\n\nstatic void write_jpeg(Magick::Image &image, zmq::message_t &data)\n{\n\tstd::unique_ptr<Magick::Blob> blob(new Magick::Blob);\n\timage.write(blob.get(), \"JPEG\");\n\tdata.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get());\n\tblob.release();\n}\n\n} \/\/ namespace\n\nint main(int argc, char **argv)\n{\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"Usage: %s ADDRESS...\\n\", argv[0]);\n\t\treturn 2;\n\t}\n\n\tconst char *progname = strrchr(argv[0], '\/');\n\tif (progname)\n\t\tprogname++;\n\telse\n\t\tprogname = argv[0];\n\n\topenlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER);\n\n\tmagic_cookie = magic_open(MAGIC_MIME_TYPE);\n\tif (magic_load(magic_cookie, nullptr) < 0) {\n\t\tsyslog(LOG_CRIT, \"magic: %s\", strerror(errno));\n\t\treturn 1;\n\t}\n\n\tMagick::InitializeMagick(argv[0]);\n\n\tzmq::context_t context(1);\n\tzmq::socket_t socket(context, ZMQ_REP);\n\n\ttry {\n\t\tfor (int i = 1; i < argc; i++)\n\t\t\tsocket.bind(argv[i]);\n\n\t\twhile (true) {\n\t\t\tIO io(socket);\n\n\t\t\tif (!io.receive()) {\n\t\t\t\tsyslog(LOG_ERR, \"request message was too short\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tRequest request;\n\t\t\tResponse response;\n\n\t\t\tif (!decode_request(io.request.first, request)) {\n\t\t\t\tsyslog(LOG_ERR, \"could not decode request header\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst char *mimetype = magic_buffer(magic_cookie, io.request.second.data(), io.request.second.size());\n\n\t\t\tresponse.set_source_type(mimetype);\n\n\t\t\tif (mimetype && (strcmp(mimetype, \"image\/bmp\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/gif\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/jpeg\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/png\") == 0)) {\n\t\t\t\ttry {\n\t\t\t\t\tMagick::Blob blob(io.request.second.data(), io.request.second.size());\n\t\t\t\t\tMagick::Image image(blob);\n\n\t\t\t\t\tconvert_image(image, request.scale(), request.crop());\n\t\t\t\t\tresponse.set_nail_width(image.size().width());\n\t\t\t\t\tresponse.set_nail_height(image.size().height());\n\t\t\t\t\twrite_jpeg(image, io.response.second);\n\t\t\t\t} catch (const Magick::Exception &e) {\n\t\t\t\t\tsyslog(LOG_ERR, \"magick: %s\", e.what());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tencode_response(response, io.response.first);\n\t\t\tio.handled = true;\n\t\t}\n\t} catch (const zmq::error_t &e) {\n\t\tsyslog(LOG_CRIT, \"zmq: %s\", e.what());\n\t}\n\n\treturn 1;\n}\n<commit_msg>silence protobuf enum switch warning<commit_after>#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <memory>\n\n#include <syslog.h>\n\n#include <zmq.hpp>\n\n#include <google\/protobuf\/io\/coded_stream.h>\n#include <google\/protobuf\/io\/zero_copy_stream_impl_lite.h>\n\n#include <magic.h>\n\n#include <Magick++.h>\n\n#include \"io.hpp\"\n#include \"thumq.pb.h\"\n\nnamespace protobuf = google::protobuf;\n\nusing namespace thumq;\n\nnamespace {\n\nstatic magic_t magic_cookie;\n\nstatic bool decode_request(zmq::message_t &message, Request &request)\n{\n\tprotobuf::io::ArrayInputStream array(message.data(), message.size());\n\tprotobuf::io::CodedInputStream coded(&array);\n\n\treturn request.MergePartialFromCodedStream(&coded);\n}\n\nstatic void encode_response(const Response &response, zmq::message_t &message)\n{\n\tmessage.rebuild(response.ByteSize());\n\n\tprotobuf::io::ArrayOutputStream array(message.data(), message.size());\n\tprotobuf::io::CodedOutputStream coded(&array);\n\n\tresponse.SerializeWithCachedSizes(&coded);\n}\n\nstatic void convert_image(Magick::Image &image, int scale, Request::Crop crop)\n{\n\tswitch (atoi(image.attribute(\"EXIF:Orientation\").c_str())) {\n\tcase Magick::TopLeftOrientation:\n\t\tbreak;\n\n\tcase Magick::TopRightOrientation:\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::BottomRightOrientation:\n\t\timage.rotate(180);\n\t\tbreak;\n\n\tcase Magick::BottomLeftOrientation:\n\t\timage.flip();\n\t\tbreak;\n\n\tcase Magick::LeftTopOrientation:\n\t\timage.rotate(90);\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::RightTopOrientation:\n\t\timage.rotate(90);\n\t\tbreak;\n\n\tcase Magick::RightBottomOrientation:\n\t\timage.rotate(270);\n\t\timage.flop();\n\t\tbreak;\n\n\tcase Magick::LeftBottomOrientation:\n\t\timage.rotate(270);\n\t\tbreak;\n\t}\n\n\tMagick::Geometry size = image.size();\n\tint width = size.width();\n\tint height = size.height();\n\n\tswitch (crop) {\n\tcase Request::NO_CROP:\n\t\tbreak;\n\n\tcase Request::TOP_SQUARE:\n\t\tif (width < height) {\n\t\t\timage.crop(Magick::Geometry(width, width));\n\t\t\theight = width;\n\t\t} else {\n\t\t\timage.crop(Magick::Geometry(height, height, (width - height) \/ 2, 0));\n\t\t\twidth = height;\n\t\t}\n\t\tbreak;\n\n\tdefault: \/\/ Avoid warning caused by generated protobuf code.\n\t\tbreak;\n\t}\n\n\tif (width > scale || height > scale)\n\t\timage.scale(Magick::Geometry(scale, scale));\n\n\timage.strip();\n}\n\nstatic void free_blob_data(void *, void *hint)\n{\n\tMagick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint);\n\tdelete blob;\n\n}\n\nstatic void write_jpeg(Magick::Image &image, zmq::message_t &data)\n{\n\tstd::unique_ptr<Magick::Blob> blob(new Magick::Blob);\n\timage.write(blob.get(), \"JPEG\");\n\tdata.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get());\n\tblob.release();\n}\n\n} \/\/ namespace\n\nint main(int argc, char **argv)\n{\n\tif (argc < 2) {\n\t\tfprintf(stderr, \"Usage: %s ADDRESS...\\n\", argv[0]);\n\t\treturn 2;\n\t}\n\n\tconst char *progname = strrchr(argv[0], '\/');\n\tif (progname)\n\t\tprogname++;\n\telse\n\t\tprogname = argv[0];\n\n\topenlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER);\n\n\tmagic_cookie = magic_open(MAGIC_MIME_TYPE);\n\tif (magic_load(magic_cookie, nullptr) < 0) {\n\t\tsyslog(LOG_CRIT, \"magic: %s\", strerror(errno));\n\t\treturn 1;\n\t}\n\n\tMagick::InitializeMagick(argv[0]);\n\n\tzmq::context_t context(1);\n\tzmq::socket_t socket(context, ZMQ_REP);\n\n\ttry {\n\t\tfor (int i = 1; i < argc; i++)\n\t\t\tsocket.bind(argv[i]);\n\n\t\twhile (true) {\n\t\t\tIO io(socket);\n\n\t\t\tif (!io.receive()) {\n\t\t\t\tsyslog(LOG_ERR, \"request message was too short\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tRequest request;\n\t\t\tResponse response;\n\n\t\t\tif (!decode_request(io.request.first, request)) {\n\t\t\t\tsyslog(LOG_ERR, \"could not decode request header\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst char *mimetype = magic_buffer(magic_cookie, io.request.second.data(), io.request.second.size());\n\n\t\t\tresponse.set_source_type(mimetype);\n\n\t\t\tif (mimetype && (strcmp(mimetype, \"image\/bmp\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/gif\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/jpeg\") == 0 ||\n\t\t\t strcmp(mimetype, \"image\/png\") == 0)) {\n\t\t\t\ttry {\n\t\t\t\t\tMagick::Blob blob(io.request.second.data(), io.request.second.size());\n\t\t\t\t\tMagick::Image image(blob);\n\n\t\t\t\t\tconvert_image(image, request.scale(), request.crop());\n\t\t\t\t\tresponse.set_nail_width(image.size().width());\n\t\t\t\t\tresponse.set_nail_height(image.size().height());\n\t\t\t\t\twrite_jpeg(image, io.response.second);\n\t\t\t\t} catch (const Magick::Exception &e) {\n\t\t\t\t\tsyslog(LOG_ERR, \"magick: %s\", e.what());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tencode_response(response, io.response.first);\n\t\t\tio.handled = true;\n\t\t}\n\t} catch (const zmq::error_t &e) {\n\t\tsyslog(LOG_CRIT, \"zmq: %s\", e.what());\n\t}\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#include <grpc++\/grpc++.h>\n#include <unistd.h>\n\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n#include \"parse_arguments.h\"\n#include \"google\/cloud\/speech\/v1\/cloud_speech.grpc.pb.h\"\n#include \"google\/longrunning\/operations.grpc.pb.h\"\n\nusing google::cloud::speech::v1::RecognitionConfig;\nusing google::cloud::speech::v1::Speech;\nusing google::cloud::speech::v1::LongRunningRecognizeRequest;\nusing google::cloud::speech::v1::LongRunningRecognizeResponse;\n\nstatic const char usage[] =\n \"Usage:\\n\"\n \" async_transcribe [--bitrate N] gs:\/\/bucket\/audio.(raw|ulaw|flac|amr|awb)\\n\";\n\nint main(int argc, char** argv) {\n \/\/ [START speech_async_recognize]\n \/\/ Create a Speech stub connected to the speech service.\n auto creds = grpc::GoogleDefaultCredentials();\n auto channel = grpc::CreateChannel(\"speech.googleapis.com\", creds);\n std::unique_ptr<Speech::Stub> speech(Speech::NewStub(channel));\n \/\/ Create a long operations stub so we can check the progress of the async\n \/\/ request.\n std::unique_ptr<google::longrunning::Operations::Stub> long_operations(\n google::longrunning::Operations::NewStub(channel));\n \/\/ Parse command line arguments.\n LongRunningRecognizeRequest request;\n char* file_path =\n ParseArguments(argc, argv, request.mutable_config());\n if (nullptr == file_path) {\n std::cerr << usage;\n return -1;\n }\n \/\/ Pass the Google Cloud Storage URI to the request.\n request.mutable_audio()->set_uri(file_path);\n \/\/ Call LongRunningRecognize().\n grpc::ClientContext context;\n google::longrunning::Operation op;\n grpc::Status rpc_status = speech->\n LongRunningRecognize(&context, request, &op);\n if (!rpc_status.ok()) {\n \/\/ Report the RPC failure.\n std::cerr << rpc_status.error_message() << std::endl;\n return -1;\n }\n \/\/ Wait for the operation to complete. Check the status once per second.\n std::cout << \"Waiting for operation \" << op.name() << \" to complete.\";\n google::longrunning::GetOperationRequest get_op_request;\n get_op_request.set_name(op.name());\n while (!op.done()) {\n std::cout << \".\" << std::flush;\n sleep(1);\n grpc::ClientContext op_context;\n rpc_status = long_operations->\n GetOperation(&op_context, get_op_request, &op);\n if (!rpc_status.ok()) {\n \/\/ Report the RPC failure.\n std::cerr << rpc_status.error_message() << std::endl;\n return -1;\n }\n }\n std::cout << std::endl;\n \/\/ Unpack the response.\n if (!op.response().Is<LongRunningRecognizeResponse>()) {\n std::cerr << \"The operation completed, but did not contain a \"\n << \"LongRunningRecognizeResponse.\";\n return -1;\n }\n LongRunningRecognizeResponse response;\n op.response().UnpackTo(&response);\n \/\/ Dump the transcript of all the results.\n for (int r = 0; r < response.results_size(); ++r) {\n auto result = response.results(r);\n for (int a = 0; a < result.alternatives_size(); ++a) {\n auto alternative = result.alternatives(a);\n std::cout << alternative.confidence() << \"\\t\"\n << alternative.transcript() << std::endl;\n }\n }\n \/\/ [END speech_async_recognize]\n return 0;\n}\n<commit_msg>speech_async_recognize -> speech_async_recognize_gcs<commit_after>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#include <grpc++\/grpc++.h>\n#include <unistd.h>\n\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n#include \"parse_arguments.h\"\n#include \"google\/cloud\/speech\/v1\/cloud_speech.grpc.pb.h\"\n#include \"google\/longrunning\/operations.grpc.pb.h\"\n\nusing google::cloud::speech::v1::RecognitionConfig;\nusing google::cloud::speech::v1::Speech;\nusing google::cloud::speech::v1::LongRunningRecognizeRequest;\nusing google::cloud::speech::v1::LongRunningRecognizeResponse;\n\nstatic const char usage[] =\n \"Usage:\\n\"\n \" async_transcribe [--bitrate N] gs:\/\/bucket\/audio.(raw|ulaw|flac|amr|awb)\\n\";\n\nint main(int argc, char** argv) {\n \/\/ [START speech_async_recognize_gcs]\n \/\/ Create a Speech stub connected to the speech service.\n auto creds = grpc::GoogleDefaultCredentials();\n auto channel = grpc::CreateChannel(\"speech.googleapis.com\", creds);\n std::unique_ptr<Speech::Stub> speech(Speech::NewStub(channel));\n \/\/ Create a long operations stub so we can check the progress of the async\n \/\/ request.\n std::unique_ptr<google::longrunning::Operations::Stub> long_operations(\n google::longrunning::Operations::NewStub(channel));\n \/\/ Parse command line arguments.\n LongRunningRecognizeRequest request;\n char* file_path =\n ParseArguments(argc, argv, request.mutable_config());\n if (nullptr == file_path) {\n std::cerr << usage;\n return -1;\n }\n \/\/ Pass the Google Cloud Storage URI to the request.\n request.mutable_audio()->set_uri(file_path);\n \/\/ Call LongRunningRecognize().\n grpc::ClientContext context;\n google::longrunning::Operation op;\n grpc::Status rpc_status = speech->\n LongRunningRecognize(&context, request, &op);\n if (!rpc_status.ok()) {\n \/\/ Report the RPC failure.\n std::cerr << rpc_status.error_message() << std::endl;\n return -1;\n }\n \/\/ Wait for the operation to complete. Check the status once per second.\n std::cout << \"Waiting for operation \" << op.name() << \" to complete.\";\n google::longrunning::GetOperationRequest get_op_request;\n get_op_request.set_name(op.name());\n while (!op.done()) {\n std::cout << \".\" << std::flush;\n sleep(1);\n grpc::ClientContext op_context;\n rpc_status = long_operations->\n GetOperation(&op_context, get_op_request, &op);\n if (!rpc_status.ok()) {\n \/\/ Report the RPC failure.\n std::cerr << rpc_status.error_message() << std::endl;\n return -1;\n }\n }\n std::cout << std::endl;\n \/\/ Unpack the response.\n if (!op.response().Is<LongRunningRecognizeResponse>()) {\n std::cerr << \"The operation completed, but did not contain a \"\n << \"LongRunningRecognizeResponse.\";\n return -1;\n }\n LongRunningRecognizeResponse response;\n op.response().UnpackTo(&response);\n \/\/ Dump the transcript of all the results.\n for (int r = 0; r < response.results_size(); ++r) {\n auto result = response.results(r);\n for (int a = 0; a < result.alternatives_size(); ++a) {\n auto alternative = result.alternatives(a);\n std::cout << alternative.confidence() << \"\\t\"\n << alternative.transcript() << std::endl;\n }\n }\n \/\/ [END speech_async_recognize_gcs]\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <avr\/interrupt.h>\n#include \"UART.h\"\n#include \"UARTsettings.h\"\n\nstatic volatile uint8_t tx_buffer[SERIAL_BUFFER_SIZE];\nstatic volatile uint8_t rx_buffer[SERIAL_BUFFER_SIZE];\n\nstatic volatile uint8_t rx_buffer_head = 0;\nstatic volatile uint8_t rx_buffer_tail = 0;\n\nstatic volatile uint8_t tx_buffer_head = 0;\nstatic volatile uint8_t tx_buffer_tail = 0;\n\nbool rxEnabled,\n txEnabled;\n\n\/\/isr functions\n\nISR(USART1_RX_vect) {\n\n uint8_t data, bufferIndex;\n\n data = UDR1;\n bufferIndex = rx_buffer_head + 1;\n\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n\n if (bufferIndex != rx_buffer_tail) {\n\n rx_buffer[bufferIndex] = data;\n rx_buffer_head = bufferIndex;\n\n }\n\n}\n\nISR(USART1_UDRE_vect) {\n\n uint8_t bufferIndex;\n\n if (tx_buffer_head == tx_buffer_tail) {\n\n \/\/ buffer is empty, disable transmit interrupt\n if (!rxEnabled)\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1);\n else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);\n\n } else {\n\n bufferIndex = tx_buffer_tail + 1;\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n UDR1 = tx_buffer[bufferIndex];\n tx_buffer_tail = bufferIndex;\n\n }\n\n}\n\n\nUART::UART() {\n\n \/\/default constructor\n\n}\n\n\nint8_t UART::read(void) {\n\n uint8_t data, bufferIndex;\n\n if (rx_buffer_head == rx_buffer_tail) return -1;\n bufferIndex = rx_buffer_tail + 1;\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n data = rx_buffer[bufferIndex];\n rx_buffer_tail = bufferIndex;\n return data;\n\n}\n\nvoid UART::write(uint8_t data) {\n\n if (!txEnabled) return;\n\n uint8_t bufferIndex;\n\n if (!(UCSR1B & (1<<TXEN1))) return;\n\n bufferIndex = tx_buffer_head + 1;\n\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n\n while (tx_buffer_tail == bufferIndex); \/\/ wait until space in buffer\n\n tx_buffer[bufferIndex] = data;\n\n tx_buffer_head = bufferIndex;\n\n if (!rxEnabled)\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1) | (1<<UDRIE1);\n else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1) | (1<<UDRIE1);\n\n}\n\nvoid UART::begin(uint32_t baudRate, bool enableRX, bool enableTX) {\n\n rxEnabled = enableRX;\n txEnabled = enableTX;\n\n int16_t baud_count = ((F_CPU \/ 8) + (baudRate \/ 2)) \/ baudRate;\n\n if ((baud_count & 1) && baud_count <= 4096) {\n\n UCSR1A = (1<<U2X1); \/\/double speed uart\n UBRR1 = baud_count - 1;\n\n } else {\n\n UCSR1A = 0;\n UBRR1 = (baud_count >> 1) - 1;\n\n }\n\n if (!(UCSR1B & (1<<TXEN1))) {\n\n rx_buffer_head = 0;\n rx_buffer_tail = 0;\n tx_buffer_head = 0;\n tx_buffer_tail = 0;\n\n UCSR1C = (1<<UCSZ11) | (1<<UCSZ10); \/\/8 bit, no parity, 1 stop bit\n\n if (enableRX && enableTX) \/\/enable both rx and tx\n UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);\n else if (enableRX && !enableTX) \/\/enable only receive\n UCSR1B = (1<<RXEN1) | (1<<RXCIE1);\n else if (enableTX & !enableRX) \/\/enable only transmit\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1);\n\n }\n\n}\n\nuint8_t UART::available() {\n\n \/\/return available number of bytes in incoming buffer\n\n uint8_t head, tail;\n\n head = rx_buffer_head;\n tail = rx_buffer_tail;\n\n if (head >= tail) return head - tail;\n return SERIAL_BUFFER_SIZE + head - tail;\n\n}\n\nUART uart;<commit_msg>define USART1_TX_vect interrupt<commit_after>#include <avr\/interrupt.h>\n#include \"UART.h\"\n#include \"UARTsettings.h\"\n\nstatic volatile uint8_t tx_buffer[SERIAL_BUFFER_SIZE];\nstatic volatile uint8_t rx_buffer[SERIAL_BUFFER_SIZE];\n\nstatic volatile uint8_t rx_buffer_head = 0;\nstatic volatile uint8_t rx_buffer_tail = 0;\n\nstatic volatile uint8_t tx_buffer_head = 0;\nstatic volatile uint8_t tx_buffer_tail = 0;\n\nbool rxEnabled,\n txEnabled;\n\n\/\/isr functions\n\nISR(USART1_RX_vect) {\n\n uint8_t data, bufferIndex;\n\n data = UDR1;\n bufferIndex = rx_buffer_head + 1;\n\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n\n if (bufferIndex != rx_buffer_tail) {\n\n rx_buffer[bufferIndex] = data;\n rx_buffer_head = bufferIndex;\n\n }\n\n}\n\nISR(USART1_UDRE_vect) {\n\n uint8_t bufferIndex;\n\n if (tx_buffer_head == tx_buffer_tail) {\n\n \/\/ buffer is empty, disable transmit interrupt\n if (!rxEnabled)\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1);\n else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);\n\n } else {\n\n bufferIndex = tx_buffer_tail + 1;\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n UDR1 = tx_buffer[bufferIndex];\n tx_buffer_tail = bufferIndex;\n\n }\n\n}\n\nISR(USART1_TX_vect) {}\n\nUART::UART() {\n\n \/\/default constructor\n\n}\n\n\nint8_t UART::read(void) {\n\n uint8_t data, bufferIndex;\n\n if (rx_buffer_head == rx_buffer_tail) return -1;\n bufferIndex = rx_buffer_tail + 1;\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n data = rx_buffer[bufferIndex];\n rx_buffer_tail = bufferIndex;\n return data;\n\n}\n\nvoid UART::write(uint8_t data) {\n\n if (!txEnabled) return;\n\n uint8_t bufferIndex;\n\n if (!(UCSR1B & (1<<TXEN1))) return;\n\n bufferIndex = tx_buffer_head + 1;\n\n if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;\n\n while (tx_buffer_tail == bufferIndex); \/\/ wait until space in buffer\n\n tx_buffer[bufferIndex] = data;\n\n tx_buffer_head = bufferIndex;\n\n if (!rxEnabled)\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1) | (1<<UDRIE1);\n else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1) | (1<<UDRIE1);\n\n}\n\nvoid UART::begin(uint32_t baudRate, bool enableRX, bool enableTX) {\n\n rxEnabled = enableRX;\n txEnabled = enableTX;\n\n int16_t baud_count = ((F_CPU \/ 8) + (baudRate \/ 2)) \/ baudRate;\n\n if ((baud_count & 1) && baud_count <= 4096) {\n\n UCSR1A = (1<<U2X1); \/\/double speed uart\n UBRR1 = baud_count - 1;\n\n } else {\n\n UCSR1A = 0;\n UBRR1 = (baud_count >> 1) - 1;\n\n }\n\n if (!(UCSR1B & (1<<TXEN1))) {\n\n rx_buffer_head = 0;\n rx_buffer_tail = 0;\n tx_buffer_head = 0;\n tx_buffer_tail = 0;\n\n UCSR1C = (1<<UCSZ11) | (1<<UCSZ10); \/\/8 bit, no parity, 1 stop bit\n\n if (enableRX && enableTX) \/\/enable both rx and tx\n UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);\n else if (enableRX && !enableTX) \/\/enable only receive\n UCSR1B = (1<<RXEN1) | (1<<RXCIE1);\n else if (enableTX & !enableRX) \/\/enable only transmit\n UCSR1B = (1<<TXCIE1) | (1<<TXEN1);\n\n }\n\n}\n\nuint8_t UART::available() {\n\n \/\/return available number of bytes in incoming buffer\n\n uint8_t head, tail;\n\n head = rx_buffer_head;\n tail = rx_buffer_tail;\n\n if (head >= tail) return head - tail;\n return SERIAL_BUFFER_SIZE + head - tail;\n\n}\n\nUART uart;<|endoftext|>"} {"text":"<commit_before>\/*\n\tDashel\n\tA cross-platform DAta Stream Helper Encapsulation Library\n\tCopyright (C) 2007 -- 2009:\n\t\t\n\t\tStephane Magnenat <stephane at magnenat dot net>\n\t\t\t(http:\/\/stephane.magnenat.net)\n\t\tMobots group - Laboratory of Robotics Systems, EPFL, Lausanne\n\t\t\t(http:\/\/mobots.epfl.ch)\n\t\t\n\t\tSebastian Gerlach\n\t\tKenzan Technologies\n\t\t\t(http:\/\/www.kenzantech.com)\n\t\n\tAll rights reserved.\n\t\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\t\t* Redistributions of source code must retain the above copyright\n\t\t notice, this list of conditions and the following disclaimer.\n\t\t* Redistributions in binary form must reproduce the above copyright\n\t\t notice, this list of conditions and the following disclaimer in the\n\t\t documentation and\/or other materials provided with the distribution.\n\t\t* Neither the names of \"Mobots\", \"Laboratory of Robotics Systems\", \"EPFL\",\n\t\t \"Kenzan Technologies\" nor the names of the contributors may be used to\n\t\t endorse or promote products derived from this software without specific\n\t\t prior written permission.\n\t\n\tTHIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``AS IS'' AND ANY\n\tEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\tWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\tDISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\tDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\t(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\tLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\tON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\tSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"dashel.h\"\n#include \"dashel-private.h\"\n#include <algorithm>\n\n#include <ostream>\n#include <sstream>\n#ifndef WIN32\n\t#include <netdb.h>\n\t#include <sys\/socket.h>\n\t#include <arpa\/inet.h>\n#else\n\t#include <winsock2.h>\n#endif\n\n\/*!\t\\file dashel-commong.cpp\n\t\\brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library\n*\/\n\nnamespace Dashel\n{\n\tusing namespace std;\n\t\n\t\/\/ frome dashe-private.h\n\tExpandableBuffer::ExpandableBuffer(size_t size) :\n\t\t_data((unsigned char*)malloc(size)),\n\t\t_size(size),\n\t\t_pos(0)\n\t{\n\t}\n\t\n\tExpandableBuffer::~ExpandableBuffer()\n\t{\n\t\tfree(_data);\n\t}\n\t\n\tvoid ExpandableBuffer::clear()\n\t{\n\t\t_pos = 0;\n\t}\n\t\n\tvoid ExpandableBuffer::add(const void* data, const size_t size)\n\t{\n\t\tif (_pos + size > _size)\n\t\t{\n\t\t\t_size = max(_size * 2, _size + size);\n\t\t\t_data = (unsigned char*)realloc(_data, _size);\n\t\t}\n\t\tmemcpy(_data + _pos, (unsigned char *)data, size);\n\t\t_pos += size;\n\t}\n\t\n\t\/\/ frome dashel.h\n\tDashelException::DashelException(Source s, int se, const char *reason, Stream* stream) :\n\t\tstd::runtime_error(reason),\n\t\tsource(s),\n\t\tsysError(se),\n\t\tstream(stream)\n\t{\n\t\n\t}\n\t\n\tIPV4Address::IPV4Address(unsigned addr, unsigned short prt)\n\t{\n\t\taddress = addr;\n\t\tport = prt;\n\t}\n\t\n\tIPV4Address::IPV4Address(const std::string& name, unsigned short port) :\n\t\tport(port)\n\t{\n\t\thostent *he = gethostbyname(name.c_str());\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\t#ifndef WIN32\n\t\t\tstruct in_addr addr;\n\t\t\tif (inet_aton(name.c_str(), &addr))\n\t\t\t{\n\t\t\t\taddress = ntohl(addr.s_addr);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taddress = INADDR_ANY;\n\t\t\t}\n\t\t\t#else \/\/ WIN32\n\t\t\tunsigned long addr = inet_addr(name.c_str());\n\t\t\tif(addr != INADDR_NONE)\n\t\t\t\taddress = addr;\n\t\t\telse\n\t\t\t\taddress = INADDR_ANY;\n\t\t\t#endif \/\/ WIN32\n\t\t}\n\t\telse\n\t\t{\n\t\t\t#ifndef WIN32\n\t\t\taddress = ntohl(*((unsigned *)he->h_addr));\n\t\t\t#else\n\t\t\taddress = ntohl(*((unsigned *)he->h_addr));\n\t\t\t#endif\n\t\t}\n\t}\n\t\n\tbool IPV4Address::operator==(const IPV4Address& o) const\n\t{\n\t\treturn address==o.address && port==o.port;\n\t}\n\t\n\tbool IPV4Address::operator<(const IPV4Address& o) const\n\t{\n\t\treturn address<o.address || (address==o.address && port<o.port);\n\t}\n\t\n\tstd::string IPV4Address::hostname() const\n\t{\n\t\tunsigned a2 = htonl(address);\n\t\tstruct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\tstruct in_addr addr;\n\t\t\taddr.s_addr = a2;\n\t\t\treturn std::string(inet_ntoa(addr));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn std::string(he->h_name);\n\t\t}\n\t}\n\t\n\tstd::string IPV4Address::format() const\n\t{\n\t\tstd::ostringstream buf;\n\t\tunsigned a2 = htonl(address);\n\t\tstruct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\tstruct in_addr addr;\n\t\t\taddr.s_addr = a2;\n\t\t\tbuf << \"tcp:host=\" << inet_ntoa(addr) << \";port=\" << port;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbuf << \"tcp:host=\" << he->h_name << \";port=\" << port;\n\t\t}\n\t\t\n\t\treturn buf.str();\n\t}\n\t\n\tvoid ParameterSet::add(const char *line)\n\t{\n\t\tchar *lc = strdup(line);\n\t\tint spc = 0;\n\t\tchar *param;\n\t\tbool storeParams = (params.size() == 0);\n\t\tchar *protocolName = strtok(lc, \":\");\n\t\t\n\t\t\/\/ Do nothing with this.\n\t\tassert(protocolName);\n\t\t\n\t\twhile((param = strtok(NULL, \";\")) != NULL)\n\t\t{\n\t\t\tchar *sep = strchr(param, '=');\n\t\t\tif(sep)\n\t\t\t{\n\t\t\t\t*sep++ = 0;\n\t\t\t\tvalues[param] = sep;\n\t\t\t\tif (storeParams)\n\t\t\t\t\tparams.push_back(param);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (storeParams)\n\t\t\t\t\tparams.push_back(param);\n\t\t\t\tvalues[params[spc]] = param;\n\t\t\t}\n\t\t\t++spc;\n\t\t}\n\t\t\n\t\tfree(lc);\n\t}\n\t\n\tvoid ParameterSet::addParam(const char *param, const char *value, bool atStart)\n\t{\n\t\tif (atStart)\n\t\t\tparams.insert(params.begin(), 1, param);\n\t\telse\n\t\t\tparams.push_back(param);\n\t\t\n\t\tif (value)\n\t\t\tvalues[param] = value;\n\t}\n\t\n\tbool ParameterSet::isSet(const char *key) const\n\t{\n\t\treturn (values.find(key) != values.end());\n\t}\n\n\tconst std::string& ParameterSet::get(const char *key) const\n\t{\n\t\tstd::map<std::string, std::string>::const_iterator it = values.find(key);\n\t\tif(it == values.end())\n\t\t{\n\t\t\tstd::string r = std::string(\"Parameter missing: \").append(key);\n\t\t\tthrow DashelException(DashelException::InvalidTarget, 0, r.c_str());\n\t\t}\n\t\treturn it->second;\n\t}\n\t\n\tstd::string ParameterSet::getString() const\n\t{\n\t\tstd::ostringstream oss;\n\t\tstd::vector<std::string>::const_iterator i = params.begin();\n\t\twhile (true)\n\t\t{\n\t\t\toss << *i << \"=\" << values.find(*i)->second;\n\t\t\tif (++i == params.end())\n\t\t\t\tbreak;\n\t\t\toss << \";\";\n\t\t}\n\t\treturn oss.str();\n\t}\n\t\n\tvoid ParameterSet::erase(const char *key)\n\t{\n\t\tstd::vector<std::string>::iterator i = std::find(params.begin(), params.end(), key);\n\t\tif (i != params.end())\n\t\t\tparams.erase(i);\n\t\t\n\t\tstd::map<std::string, std::string>::iterator j = values.find(key);\n\t\tif (j != values.end())\n\t\t\tvalues.erase(j);\n\t}\n\t\n\t\n\tvoid MemoryPacketStream::write(const void *data, const size_t size)\n\t{\n\t\tsendBuffer.add(data, size);\n\t}\n\t\n\tvoid MemoryPacketStream::read(void *data, size_t size)\n\t{\n\t\tif (size > receptionBuffer.size())\n\t\t\tfail(DashelException::IOError, 0, \"Attempt to read past available data\");\n\t\t\n\t\tunsigned char* ptr = (unsigned char*)data;\n\t\tstd::copy(receptionBuffer.begin(), receptionBuffer.begin() + size, ptr);\n\t\treceptionBuffer.erase(receptionBuffer.begin(), receptionBuffer.begin() + size);\n\t}\n\t\n\tvoid Hub::closeStream(Stream* stream)\n\t{\n\t\tstreams.erase(stream);\n\t\tdataStreams.erase(stream);\n\t\tdelete stream;\n\t}\n}\n\n<commit_msg>Fixed trash when target has no arguments<commit_after>\/*\n\tDashel\n\tA cross-platform DAta Stream Helper Encapsulation Library\n\tCopyright (C) 2007 -- 2009:\n\t\t\n\t\tStephane Magnenat <stephane at magnenat dot net>\n\t\t\t(http:\/\/stephane.magnenat.net)\n\t\tMobots group - Laboratory of Robotics Systems, EPFL, Lausanne\n\t\t\t(http:\/\/mobots.epfl.ch)\n\t\t\n\t\tSebastian Gerlach\n\t\tKenzan Technologies\n\t\t\t(http:\/\/www.kenzantech.com)\n\t\n\tAll rights reserved.\n\t\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\t\t* Redistributions of source code must retain the above copyright\n\t\t notice, this list of conditions and the following disclaimer.\n\t\t* Redistributions in binary form must reproduce the above copyright\n\t\t notice, this list of conditions and the following disclaimer in the\n\t\t documentation and\/or other materials provided with the distribution.\n\t\t* Neither the names of \"Mobots\", \"Laboratory of Robotics Systems\", \"EPFL\",\n\t\t \"Kenzan Technologies\" nor the names of the contributors may be used to\n\t\t endorse or promote products derived from this software without specific\n\t\t prior written permission.\n\t\n\tTHIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``AS IS'' AND ANY\n\tEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\tWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\tDISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\tDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\t(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\tLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\tON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\tSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"dashel.h\"\n#include \"dashel-private.h\"\n#include <algorithm>\n\n#include <ostream>\n#include <sstream>\n#ifndef WIN32\n\t#include <netdb.h>\n\t#include <sys\/socket.h>\n\t#include <arpa\/inet.h>\n#else\n\t#include <winsock2.h>\n#endif\n\n\/*!\t\\file dashel-commong.cpp\n\t\\brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library\n*\/\n\nnamespace Dashel\n{\n\tusing namespace std;\n\t\n\t\/\/ frome dashe-private.h\n\tExpandableBuffer::ExpandableBuffer(size_t size) :\n\t\t_data((unsigned char*)malloc(size)),\n\t\t_size(size),\n\t\t_pos(0)\n\t{\n\t}\n\t\n\tExpandableBuffer::~ExpandableBuffer()\n\t{\n\t\tfree(_data);\n\t}\n\t\n\tvoid ExpandableBuffer::clear()\n\t{\n\t\t_pos = 0;\n\t}\n\t\n\tvoid ExpandableBuffer::add(const void* data, const size_t size)\n\t{\n\t\tif (_pos + size > _size)\n\t\t{\n\t\t\t_size = max(_size * 2, _size + size);\n\t\t\t_data = (unsigned char*)realloc(_data, _size);\n\t\t}\n\t\tmemcpy(_data + _pos, (unsigned char *)data, size);\n\t\t_pos += size;\n\t}\n\t\n\t\/\/ frome dashel.h\n\tDashelException::DashelException(Source s, int se, const char *reason, Stream* stream) :\n\t\tstd::runtime_error(reason),\n\t\tsource(s),\n\t\tsysError(se),\n\t\tstream(stream)\n\t{\n\t\n\t}\n\t\n\tIPV4Address::IPV4Address(unsigned addr, unsigned short prt)\n\t{\n\t\taddress = addr;\n\t\tport = prt;\n\t}\n\t\n\tIPV4Address::IPV4Address(const std::string& name, unsigned short port) :\n\t\tport(port)\n\t{\n\t\thostent *he = gethostbyname(name.c_str());\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\t#ifndef WIN32\n\t\t\tstruct in_addr addr;\n\t\t\tif (inet_aton(name.c_str(), &addr))\n\t\t\t{\n\t\t\t\taddress = ntohl(addr.s_addr);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taddress = INADDR_ANY;\n\t\t\t}\n\t\t\t#else \/\/ WIN32\n\t\t\tunsigned long addr = inet_addr(name.c_str());\n\t\t\tif(addr != INADDR_NONE)\n\t\t\t\taddress = addr;\n\t\t\telse\n\t\t\t\taddress = INADDR_ANY;\n\t\t\t#endif \/\/ WIN32\n\t\t}\n\t\telse\n\t\t{\n\t\t\t#ifndef WIN32\n\t\t\taddress = ntohl(*((unsigned *)he->h_addr));\n\t\t\t#else\n\t\t\taddress = ntohl(*((unsigned *)he->h_addr));\n\t\t\t#endif\n\t\t}\n\t}\n\t\n\tbool IPV4Address::operator==(const IPV4Address& o) const\n\t{\n\t\treturn address==o.address && port==o.port;\n\t}\n\t\n\tbool IPV4Address::operator<(const IPV4Address& o) const\n\t{\n\t\treturn address<o.address || (address==o.address && port<o.port);\n\t}\n\t\n\tstd::string IPV4Address::hostname() const\n\t{\n\t\tunsigned a2 = htonl(address);\n\t\tstruct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\tstruct in_addr addr;\n\t\t\taddr.s_addr = a2;\n\t\t\treturn std::string(inet_ntoa(addr));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn std::string(he->h_name);\n\t\t}\n\t}\n\t\n\tstd::string IPV4Address::format() const\n\t{\n\t\tstd::ostringstream buf;\n\t\tunsigned a2 = htonl(address);\n\t\tstruct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);\n\t\t\n\t\tif (he == NULL)\n\t\t{\n\t\t\tstruct in_addr addr;\n\t\t\taddr.s_addr = a2;\n\t\t\tbuf << \"tcp:host=\" << inet_ntoa(addr) << \";port=\" << port;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbuf << \"tcp:host=\" << he->h_name << \";port=\" << port;\n\t\t}\n\t\t\n\t\treturn buf.str();\n\t}\n\t\n\tvoid ParameterSet::add(const char *line)\n\t{\n\t\tchar *lc = strdup(line);\n\t\tint spc = 0;\n\t\tchar *param;\n\t\tbool storeParams = (params.size() == 0);\n\t\tchar *protocolName = strtok(lc, \":\");\n\t\t\n\t\t\/\/ Do nothing with this.\n\t\tassert(protocolName);\n\t\t\n\t\twhile((param = strtok(NULL, \";\")) != NULL)\n\t\t{\n\t\t\tchar *sep = strchr(param, '=');\n\t\t\tif(sep)\n\t\t\t{\n\t\t\t\t*sep++ = 0;\n\t\t\t\tvalues[param] = sep;\n\t\t\t\tif (storeParams)\n\t\t\t\t\tparams.push_back(param);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (storeParams)\n\t\t\t\t\tparams.push_back(param);\n\t\t\t\tvalues[params[spc]] = param;\n\t\t\t}\n\t\t\t++spc;\n\t\t}\n\t\t\n\t\tfree(lc);\n\t}\n\t\n\tvoid ParameterSet::addParam(const char *param, const char *value, bool atStart)\n\t{\n\t\tif (atStart)\n\t\t\tparams.insert(params.begin(), 1, param);\n\t\telse\n\t\t\tparams.push_back(param);\n\t\t\n\t\tif (value)\n\t\t\tvalues[param] = value;\n\t}\n\t\n\tbool ParameterSet::isSet(const char *key) const\n\t{\n\t\treturn (values.find(key) != values.end());\n\t}\n\n\tconst std::string& ParameterSet::get(const char *key) const\n\t{\n\t\tstd::map<std::string, std::string>::const_iterator it = values.find(key);\n\t\tif(it == values.end())\n\t\t{\n\t\t\tstd::string r = std::string(\"Parameter missing: \").append(key);\n\t\t\tthrow DashelException(DashelException::InvalidTarget, 0, r.c_str());\n\t\t}\n\t\treturn it->second;\n\t}\n\t\n\tstd::string ParameterSet::getString() const\n\t{\n\t\tstd::ostringstream oss;\n\t\tstd::vector<std::string>::const_iterator i = params.begin();\n\t\twhile (i != params.end())\n\t\t{\n\t\t\toss << *i << \"=\" << values.find(*i)->second;\n\t\t\tif (++i == params.end())\n\t\t\t\tbreak;\n\t\t\toss << \";\";\n\t\t}\n\t\treturn oss.str();\n\t}\n\t\n\tvoid ParameterSet::erase(const char *key)\n\t{\n\t\tstd::vector<std::string>::iterator i = std::find(params.begin(), params.end(), key);\n\t\tif (i != params.end())\n\t\t\tparams.erase(i);\n\t\t\n\t\tstd::map<std::string, std::string>::iterator j = values.find(key);\n\t\tif (j != values.end())\n\t\t\tvalues.erase(j);\n\t}\n\t\n\t\n\tvoid MemoryPacketStream::write(const void *data, const size_t size)\n\t{\n\t\tsendBuffer.add(data, size);\n\t}\n\t\n\tvoid MemoryPacketStream::read(void *data, size_t size)\n\t{\n\t\tif (size > receptionBuffer.size())\n\t\t\tfail(DashelException::IOError, 0, \"Attempt to read past available data\");\n\t\t\n\t\tunsigned char* ptr = (unsigned char*)data;\n\t\tstd::copy(receptionBuffer.begin(), receptionBuffer.begin() + size, ptr);\n\t\treceptionBuffer.erase(receptionBuffer.begin(), receptionBuffer.begin() + size);\n\t}\n\t\n\tvoid Hub::closeStream(Stream* stream)\n\t{\n\t\tstreams.erase(stream);\n\t\tdataStreams.erase(stream);\n\t\tdelete stream;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ MemoryMapWindow.cc\n\/\/------------------------------------------------------------------------------\n#include \"MemoryMapWindow.h\"\n#include \"IMUI\/IMUI.h\"\n#include \"Core\/String\/StringBuilder.h\"\n\nOryolClassImpl(MemoryMapWindow);\n\nusing namespace Oryol;\nusing namespace yakc;\n\n\/\/------------------------------------------------------------------------------\nvoid\nMemoryMapWindow::Setup(kc85& kc) {\n this->setName(\"Memory Map\");\n}\n\n\/\/------------------------------------------------------------------------------\nMemoryMapWindow::pageInfo\nMemoryMapWindow::getPageInfo(kc85& kc, int layer_index, int page_index) const {\n pageInfo info;\n unsigned int addr = page_index * memory::page::size;\n if (0 == layer_index) {\n if (kc.model() == kc85_model::kc85_3) {\n if (addr < 0x4000) {\n info.name = \"RAM0\";\n info.addr = 0x0000;\n info.size = 0x4000;\n }\n else if ((addr >= 0x8000) && (addr < 0xC000)) {\n info.name = \"IRM\";\n info.addr = 0x8000;\n info.size = 0x4000;\n }\n else if ((addr >= 0xC000) && (addr < 0xE000)) {\n info.name = \"BASIC ROM\";\n info.addr = 0xC000;\n info.size = 0x2000;\n }\n else if ((addr >= 0xE000) && (addr < 0x10000)){\n info.name = \"CAOS ROM\";\n info.addr = 0xE000;\n info.size = 0x2000;\n }\n }\n else if (kc.model() == kc85_model::kc85_4) {\n if (addr < 0x4000) {\n info.name = \"RAM0\";\n info.addr = 0x0000;\n info.size = 0x4000;\n }\n else if ((addr >= 0x4000) && (addr < 0x8000)) {\n info.name = \"RAM4\";\n info.addr = 0x4000;\n info.size = 0x4000;\n }\n else if ((addr >= 0xE000) && (addr < 0x10000)){\n info.name = \"CAOS ROM E\";\n info.addr = 0xE000;\n info.size = 0x2000;\n }\n }\n }\n else if (1 == layer_index) {\n \/\/ base device module slot 08\n if (kc.exp.slot_occupied(0x08)) {\n const auto& slot = kc.exp.slot_by_addr(0x08);\n if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {\n info.name = slot.mod.name;\n info.addr = slot.addr;\n info.size = slot.mod.mem_size;\n }\n }\n }\n else if (2 == layer_index) {\n \/\/ base device module slot 0C\n if (kc.exp.slot_occupied(0x0C)) {\n const auto& slot = kc.exp.slot_by_addr(0x0C);\n if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {\n info.name = slot.mod.name;\n info.addr = slot.addr;\n info.size = slot.mod.mem_size;\n }\n }\n }\n return info;\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nMemoryMapWindow::Draw(kc85& kc) {\n StringBuilder strBuilder;\n static const ImVec4 grey(0.25f, 0.25f, 0.25f, 1.0f);\n static const ImVec4 light_green(0.0f, 1.0f, 0.0f, 1.0f);\n static const ImVec4 dark_green(0.0f, 0.5f, 0.0f, 1.0f);\n static const ImVec2 page_size(12, 0);\n ImGui::SetNextWindowSize(ImVec2(512, 100), ImGuiSetCond_Once);\n if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_NoResize)) {\n static const int num_layers = 3;\n static const char* layer_name[num_layers] = { \"BUILT-IN\", \"SLOT 08\", \"SLOT 0C\" };\n for (int layer=0; layer<num_layers; layer++) {\n ImGui::Text(layer_name[layer]);\n for (int page=0; page<memory::num_pages; page++) {\n ImGui::SameLine(72 + page*(page_size.x));\n bool is_mapped = false;\n if (kc.cpu.mem.layers[layer][page].ptr) {\n is_mapped = true;\n if (kc.cpu.mem.get_mapped_layer_index(page) == layer) {\n ImGui::PushStyleColor(ImGuiCol_Button, light_green);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, light_green);\n }\n else {\n ImGui::PushStyleColor(ImGuiCol_Button, dark_green);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, dark_green);\n }\n }\n else {\n ImGui::PushStyleColor(ImGuiCol_Button, grey);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, grey);\n }\n ImGui::Button(\"\",page_size);\n if (ImGui::IsItemHovered()) {\n pageInfo info = this->getPageInfo(kc, layer, page);\n if (info.name) {\n strBuilder.Format(48, \"%s\\n(%04X-%04X)\", info.name, info.addr, (info.addr + info.size) - 1);\n ImGui::SetTooltip(strBuilder.AsCStr());\n }\n }\n ImGui::PopStyleColor();\n ImGui::PopStyleColor();\n }\n }\n }\n ImGui::End();\n return this->Visible;\n}\n<commit_msg>Reminder to fix memory map window for 85\/2 and 85\/4<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ MemoryMapWindow.cc\n\/\/------------------------------------------------------------------------------\n#include \"MemoryMapWindow.h\"\n#include \"IMUI\/IMUI.h\"\n#include \"Core\/String\/StringBuilder.h\"\n\nOryolClassImpl(MemoryMapWindow);\n\nusing namespace Oryol;\nusing namespace yakc;\n\n\/\/------------------------------------------------------------------------------\nvoid\nMemoryMapWindow::Setup(kc85& kc) {\n this->setName(\"Memory Map (FIXME!)\");\n}\n\n\/\/------------------------------------------------------------------------------\nMemoryMapWindow::pageInfo\nMemoryMapWindow::getPageInfo(kc85& kc, int layer_index, int page_index) const {\n pageInfo info;\n unsigned int addr = page_index * memory::page::size;\n if (0 == layer_index) {\n if (kc.model() == kc85_model::kc85_3) {\n if (addr < 0x4000) {\n info.name = \"RAM0\";\n info.addr = 0x0000;\n info.size = 0x4000;\n }\n else if ((addr >= 0x8000) && (addr < 0xC000)) {\n info.name = \"IRM\";\n info.addr = 0x8000;\n info.size = 0x4000;\n }\n else if ((addr >= 0xC000) && (addr < 0xE000)) {\n info.name = \"BASIC ROM\";\n info.addr = 0xC000;\n info.size = 0x2000;\n }\n else if ((addr >= 0xE000) && (addr < 0x10000)){\n info.name = \"CAOS ROM\";\n info.addr = 0xE000;\n info.size = 0x2000;\n }\n }\n else if (kc.model() == kc85_model::kc85_4) {\n if (addr < 0x4000) {\n info.name = \"RAM0\";\n info.addr = 0x0000;\n info.size = 0x4000;\n }\n else if ((addr >= 0x4000) && (addr < 0x8000)) {\n info.name = \"RAM4\";\n info.addr = 0x4000;\n info.size = 0x4000;\n }\n else if ((addr >= 0xE000) && (addr < 0x10000)){\n info.name = \"CAOS ROM E\";\n info.addr = 0xE000;\n info.size = 0x2000;\n }\n }\n }\n else if (1 == layer_index) {\n \/\/ base device module slot 08\n if (kc.exp.slot_occupied(0x08)) {\n const auto& slot = kc.exp.slot_by_addr(0x08);\n if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {\n info.name = slot.mod.name;\n info.addr = slot.addr;\n info.size = slot.mod.mem_size;\n }\n }\n }\n else if (2 == layer_index) {\n \/\/ base device module slot 0C\n if (kc.exp.slot_occupied(0x0C)) {\n const auto& slot = kc.exp.slot_by_addr(0x0C);\n if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {\n info.name = slot.mod.name;\n info.addr = slot.addr;\n info.size = slot.mod.mem_size;\n }\n }\n }\n return info;\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nMemoryMapWindow::Draw(kc85& kc) {\n StringBuilder strBuilder;\n static const ImVec4 grey(0.25f, 0.25f, 0.25f, 1.0f);\n static const ImVec4 light_green(0.0f, 1.0f, 0.0f, 1.0f);\n static const ImVec4 dark_green(0.0f, 0.5f, 0.0f, 1.0f);\n static const ImVec2 page_size(12, 0);\n ImGui::SetNextWindowSize(ImVec2(512, 100), ImGuiSetCond_Once);\n if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_NoResize)) {\n static const int num_layers = 3;\n static const char* layer_name[num_layers] = { \"BUILT-IN\", \"SLOT 08\", \"SLOT 0C\" };\n for (int layer=0; layer<num_layers; layer++) {\n ImGui::Text(layer_name[layer]);\n for (int page=0; page<memory::num_pages; page++) {\n ImGui::SameLine(72 + page*(page_size.x));\n bool is_mapped = false;\n if (kc.cpu.mem.layers[layer][page].ptr) {\n is_mapped = true;\n if (kc.cpu.mem.get_mapped_layer_index(page) == layer) {\n ImGui::PushStyleColor(ImGuiCol_Button, light_green);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, light_green);\n }\n else {\n ImGui::PushStyleColor(ImGuiCol_Button, dark_green);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, dark_green);\n }\n }\n else {\n ImGui::PushStyleColor(ImGuiCol_Button, grey);\n ImGui::PushStyleColor(ImGuiCol_ButtonHovered, grey);\n }\n ImGui::Button(\"\",page_size);\n if (ImGui::IsItemHovered()) {\n pageInfo info = this->getPageInfo(kc, layer, page);\n if (info.name) {\n strBuilder.Format(48, \"%s\\n(%04X-%04X)\", info.name, info.addr, (info.addr + info.size) - 1);\n ImGui::SetTooltip(strBuilder.AsCStr());\n }\n }\n ImGui::PopStyleColor();\n ImGui::PopStyleColor();\n }\n }\n }\n ImGui::End();\n return this->Visible;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx\n#define itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageRegionIterator.h\"\n\nnamespace itk\n{\nnamespace BlockMatching\n{\n\ntemplate< typename TMultiResolutionMethod >\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::MultiResolutionSearchRegionWriterCommand()\n{\n m_SearchRegionImageComponent = SearchRegionImageComponentType::New();\n m_SearchRegionComponentWriter = SearchRegionComponentWriterType::New();\n m_SearchRegionComponentWriter->SetInput( m_SearchRegionImageComponent );\n}\n\n\ntemplate< typename TMultiResolutionMethod >\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::~MultiResolutionSearchRegionWriterCommand()\n{\n}\n\n\ntemplate< typename TMultiResolutionMethod >\nvoid\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::Execute( const itk::Object * object , const itk::EventObject & event )\n{\n Superclass::Execute( object, event );\n\n const unsigned long level = this->m_MultiResolutionMethod->GetCurrentLevel();\n\n this->m_SearchRegionImageSource->UpdateLargestPossibleRegion();\n typename SearchRegionImageType::ConstPointer searchRegionImage = this->m_SearchRegionImageSource->GetOutput();\n m_SearchRegionImageComponent->CopyInformation( searchRegionImage );\n m_SearchRegionImageComponent->SetRegions( searchRegionImage->GetBufferedRegion() );\n m_SearchRegionImageComponent->Allocate();\n\n std::cout << \"Writing SearchRegionImage images...\" << std::endl;\n\n\n if( m_OutputFilePrefix.size() == 0 )\n {\n itkExceptionMacro( << \"OutputFilePrefix is not set.\" );\n }\n\n std::ostringstream ostr;\n itk::ImageRegionConstIterator< SearchRegionImageType > regionIt( searchRegionImage,\n searchRegionImage->GetBufferedRegion() );\n itk::ImageRegionIterator< SearchRegionImageComponentType > compIt( m_SearchRegionImageComponent,\n m_SearchRegionImageComponent->GetBufferedRegion() );\n for( unsigned int dim = 0; dim < 2; ++dim )\n {\n for( regionIt.GoToBegin(), compIt.GoToBegin();\n !regionIt.IsAtEnd();\n ++regionIt, ++compIt )\n {\n compIt.Set( regionIt.Get().GetSize()[dim] );\n }\n\n ostr.str( \"\" );\n ostr << m_OutputFilePrefix << \"_Level_\" << level << \"_SearchRegionImageComponent\" << dim << \".mha\";\n m_SearchRegionComponentWriter->SetFileName( ostr.str() );\n m_SearchRegionComponentWriter->Update();\n }\n}\n\n\n}\n}\n\n#endif\n<commit_msg>COMP: Add missing itkBlockMatchingMultiResolutionSearchRegionWriterCommand.h include<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx\n#define itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx\n\n#include \"itkBlockMatchingMultiResolutionSearchRegionWriterCommand.h\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageRegionIterator.h\"\n\nnamespace itk\n{\nnamespace BlockMatching\n{\n\ntemplate< typename TMultiResolutionMethod >\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::MultiResolutionSearchRegionWriterCommand()\n{\n m_SearchRegionImageComponent = SearchRegionImageComponentType::New();\n m_SearchRegionComponentWriter = SearchRegionComponentWriterType::New();\n m_SearchRegionComponentWriter->SetInput( m_SearchRegionImageComponent );\n}\n\n\ntemplate< typename TMultiResolutionMethod >\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::~MultiResolutionSearchRegionWriterCommand()\n{\n}\n\n\ntemplate< typename TMultiResolutionMethod >\nvoid\nMultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >\n::Execute( const itk::Object * object , const itk::EventObject & event )\n{\n Superclass::Execute( object, event );\n\n const unsigned long level = this->m_MultiResolutionMethod->GetCurrentLevel();\n\n this->m_SearchRegionImageSource->UpdateLargestPossibleRegion();\n typename SearchRegionImageType::ConstPointer searchRegionImage = this->m_SearchRegionImageSource->GetOutput();\n m_SearchRegionImageComponent->CopyInformation( searchRegionImage );\n m_SearchRegionImageComponent->SetRegions( searchRegionImage->GetBufferedRegion() );\n m_SearchRegionImageComponent->Allocate();\n\n std::cout << \"Writing SearchRegionImage images...\" << std::endl;\n\n\n if( m_OutputFilePrefix.size() == 0 )\n {\n itkExceptionMacro( << \"OutputFilePrefix is not set.\" );\n }\n\n std::ostringstream ostr;\n itk::ImageRegionConstIterator< SearchRegionImageType > regionIt( searchRegionImage,\n searchRegionImage->GetBufferedRegion() );\n itk::ImageRegionIterator< SearchRegionImageComponentType > compIt( m_SearchRegionImageComponent,\n m_SearchRegionImageComponent->GetBufferedRegion() );\n for( unsigned int dim = 0; dim < 2; ++dim )\n {\n for( regionIt.GoToBegin(), compIt.GoToBegin();\n !regionIt.IsAtEnd();\n ++regionIt, ++compIt )\n {\n compIt.Set( regionIt.Get().GetSize()[dim] );\n }\n\n ostr.str( \"\" );\n ostr << m_OutputFilePrefix << \"_Level_\" << level << \"_SearchRegionImageComponent\" << dim << \".mha\";\n m_SearchRegionComponentWriter->SetFileName( ostr.str() );\n m_SearchRegionComponentWriter->Update();\n }\n}\n\n} \/\/ end namespace BlockMatching\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: storagehelper.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _COMPHELPER_STORAGEHELPER_HXX\n#define _COMPHELPER_STORAGEHELPER_HXX\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#include <com\/sun\/star\/io\/XInputStream.hpp>\n#include <com\/sun\/star\/io\/XOutputStream.hpp>\n#include <com\/sun\/star\/io\/XStream.hpp>\n#include \"comphelper\/comphelperdllapi.h\"\n\n\n#define PACKAGE_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"PackageFormat\" ) )\n#define ZIP_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"ZipFormat\" ) )\n#define OFOPXML_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"OFOPXMLFormat\" ) )\n\nnamespace comphelper {\n\nclass COMPHELPER_DLLPUBLIC OStorageHelper\n{\npublic:\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >\n GetStorageFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetTemporaryStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromURL(\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromInputStream(\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromStream(\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,\n sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static void CopyInputToOutput(\n const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput,\n const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >\n GetInputStreamFromURL(\n const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static void SetCommonStoragePassword(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,\n const ::rtl::OUString& aPass )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/ the following method supports only storages of OOo formats\n static sal_Int32 GetXStorageFormat(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/ The followin methods are related to creation of a storage of specified format\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetTemporaryStorageOfFormat(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromURL(\n const ::rtl::OUString& aFormat,\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromInputStream(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromStream(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,\n sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n};\n\n}\n\n#endif\n\n<commit_msg>INTEGRATION: CWS odfmetadata (1.7.34); FILE MERGED 2008\/06\/11 16:26:59 mst 1.7.34.1: - comphelper\/inc\/comphelper\/storagehelper.hxx, comphelper\/source\/misc\/storagehelper.cxx: + new static methods GetFileSystemStorageFactory, GetStorageFromURL2<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: storagehelper.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _COMPHELPER_STORAGEHELPER_HXX\n#define _COMPHELPER_STORAGEHELPER_HXX\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#include <com\/sun\/star\/io\/XInputStream.hpp>\n#include <com\/sun\/star\/io\/XOutputStream.hpp>\n#include <com\/sun\/star\/io\/XStream.hpp>\n#include \"comphelper\/comphelperdllapi.h\"\n\n\n#define PACKAGE_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"PackageFormat\" ) )\n#define ZIP_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"ZipFormat\" ) )\n#define OFOPXML_STORAGE_FORMAT_STRING ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"OFOPXMLFormat\" ) )\n\nnamespace comphelper {\n\nclass COMPHELPER_DLLPUBLIC OStorageHelper\n{\npublic:\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >\n GetStorageFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >\n GetFileSystemStorageFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetTemporaryStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/\/ this one will only return Storage\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromURL(\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/\/ this one will return either Storage or FileSystemStorage\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromURL2(\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromInputStream(\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageFromStream(\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,\n sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static void CopyInputToOutput(\n const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput,\n const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >\n GetInputStreamFromURL(\n const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static void SetCommonStoragePassword(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,\n const ::rtl::OUString& aPass )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/ the following method supports only storages of OOo formats\n static sal_Int32 GetXStorageFormat(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage )\n throw ( ::com::sun::star::uno::Exception );\n\n \/\/ The followin methods are related to creation of a storage of specified format\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetTemporaryStorageOfFormat(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromURL(\n const ::rtl::OUString& aFormat,\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromInputStream(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >\n GetStorageOfFormatFromStream(\n const ::rtl::OUString& aFormat,\n const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,\n sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory\n = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )\n throw ( ::com::sun::star::uno::Exception );\n\n};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: RTableConnectionData.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef DBAUI_RTABLECONNECTIONDATA_HXX\n#define DBAUI_RTABLECONNECTIONDATA_HXX\n\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n\nnamespace dbaui\n{\n const UINT16 CARDINAL_UNDEFINED = 0x0000;\n const UINT16 CARDINAL_ONE_MANY = 0x0001;\n const UINT16 CARDINAL_MANY_ONE = 0x0002;\n const UINT16 CARDINAL_ONE_ONE = 0x0004;\n\n class OConnectionLineData;\n \/\/==================================================================\n class ORelationTableConnectionData : public OTableConnectionData\n {\n friend bool operator==(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs);\n friend bool operator!=(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs) { return !(lhs == rhs); }\n\n ::osl::Mutex m_aMutex;\n ::rtl::OUString m_sDatabaseName;\n\n \/\/ @see com.sun.star.sdbc.KeyRule\n sal_Int32 m_nUpdateRules;\n sal_Int32 m_nDeleteRules;\n sal_Int32 m_nCardinality;\n\n BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xTable,EConnectionSide _eEConnectionSide) const;\n BOOL IsSourcePrimKey() const { return checkPrimaryKey(getReferencingTable()->getTable(),JTCS_FROM); }\n BOOL IsDestPrimKey() const { return checkPrimaryKey(getReferencedTable()->getTable(),JTCS_TO); }\n\n protected:\n virtual OConnectionLineDataRef CreateLineDataObj();\n virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );\n\n ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );\n public:\n ORelationTableConnectionData();\n ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );\n ORelationTableConnectionData( const TTableWindowData::value_type& _pReferencingTable,\n const TTableWindowData::value_type& _pReferencedTable,\n const ::rtl::OUString& rConnName = ::rtl::OUString() );\n virtual ~ORelationTableConnectionData();\n\n virtual void CopyFrom(const OTableConnectionData& rSource);\n virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }\n\n inline ::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }\n\n \/** Update create a new relation\n\n @return true if successful\n *\/\n virtual BOOL Update();\n\n\n void SetCardinality();\n inline void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }\n inline void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }\n\n inline sal_Int32 GetUpdateRules() const { return m_nUpdateRules; }\n inline sal_Int32 GetDeleteRules() const { return m_nDeleteRules; }\n inline sal_Int32 GetCardinality() const { return m_nCardinality; }\n\n BOOL IsConnectionPossible();\n void ChangeOrientation();\n BOOL DropRelation();\n };\n}\n\n#endif \/\/ DBAUI_RTABLECONNECTIONDATA_HXX\n\n\n\n<commit_msg>INTEGRATION: CWS dba30c (1.8.8); FILE MERGED 2008\/05\/05 11:13:36 oj 1.8.8.1: #i87131# collect keys only once, getKeys always refetch keys<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: RTableConnectionData.hxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef DBAUI_RTABLECONNECTIONDATA_HXX\n#define DBAUI_RTABLECONNECTIONDATA_HXX\n\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n\nnamespace dbaui\n{\n const UINT16 CARDINAL_UNDEFINED = 0x0000;\n const UINT16 CARDINAL_ONE_MANY = 0x0001;\n const UINT16 CARDINAL_MANY_ONE = 0x0002;\n const UINT16 CARDINAL_ONE_ONE = 0x0004;\n\n class OConnectionLineData;\n \/\/==================================================================\n class ORelationTableConnectionData : public OTableConnectionData\n {\n friend bool operator==(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs);\n friend bool operator!=(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs) { return !(lhs == rhs); }\n\n ::osl::Mutex m_aMutex;\n ::rtl::OUString m_sDatabaseName;\n\n \/\/ @see com.sun.star.sdbc.KeyRule\n sal_Int32 m_nUpdateRules;\n sal_Int32 m_nDeleteRules;\n sal_Int32 m_nCardinality;\n\n BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xKeys,EConnectionSide _eEConnectionSide) const;\n BOOL IsSourcePrimKey() const { return checkPrimaryKey(getReferencingTable()->getKeys(),JTCS_FROM); }\n BOOL IsDestPrimKey() const { return checkPrimaryKey(getReferencedTable()->getKeys(),JTCS_TO); }\n\n protected:\n virtual OConnectionLineDataRef CreateLineDataObj();\n virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );\n\n ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );\n public:\n ORelationTableConnectionData();\n ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );\n ORelationTableConnectionData( const TTableWindowData::value_type& _pReferencingTable,\n const TTableWindowData::value_type& _pReferencedTable,\n const ::rtl::OUString& rConnName = ::rtl::OUString() );\n virtual ~ORelationTableConnectionData();\n\n virtual void CopyFrom(const OTableConnectionData& rSource);\n virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }\n\n inline ::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }\n\n \/** Update create a new relation\n\n @return true if successful\n *\/\n virtual BOOL Update();\n\n\n void SetCardinality();\n inline void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }\n inline void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }\n\n inline sal_Int32 GetUpdateRules() const { return m_nUpdateRules; }\n inline sal_Int32 GetDeleteRules() const { return m_nDeleteRules; }\n inline sal_Int32 GetCardinality() const { return m_nCardinality; }\n\n BOOL IsConnectionPossible();\n void ChangeOrientation();\n BOOL DropRelation();\n };\n}\n\n#endif \/\/ DBAUI_RTABLECONNECTIONDATA_HXX\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/button-grid-22641306\n#if 0\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nconst char kIndex[] = \"index\";\nstruct Display : QLabel {\n Q_SLOT void onClicked() {\n setText(sender()->property(kIndex).toString());\n }\n Q_OBJECT\n};\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n Display display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto index = QString{\"(%1,%2)\"}.arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(index);\n button.setProperty(kIndex, index);\n layout.addWidget(&button, i, j);\n display.connect(&button, SIGNAL(clicked()), SLOT(onClicked()));\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n#include \"main.moc\"\n\n#endif\n\n#if 0\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QSignalMapper mapper;\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n QLabel display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto text = QString{\"(%1,%2)\"}.arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(text);\n layout.addWidget(&button, i, j);\n mapper.connect(&button, SIGNAL(clicked()), SLOT(map()));\n mapper.setMapping(&button, text);\n }\n display.connect(&mapper, SIGNAL(mapped(QString)), SLOT(setText(QString)));\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n\n#endif\n\n#if 0\n\n#include <QtWidgets>\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n QLabel display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto text = QStringLiteral(\"(%1,%2)\").arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(text);\n layout.addWidget(&button, i, j);\n QObject::connect(&button, &QPushButton::clicked, [&display, text] {\n display.setText(text);\n });\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n\n#endif\n\n#if 1\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nstruct Display : QLabel {\n Q_SLOT void onClicked() {\n setText(sender()->objectName());\n }\n Q_OBJECT\n};\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n Display display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto & button = buttons[i*columns+j];\n button.setText(QString{\"(%1,%2)\"}.arg(i).arg(j));\n button.setObjectName(QString{\"buton_%1_%2\"}.arg(i).arg(j));\n layout.addWidget(&button, i, j);\n display.connect(&button, SIGNAL(clicked()), SLOT(onClicked()));\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n#include \"main.moc\"\n\n#endif\n<commit_msg>Unify functionality of all implementations.<commit_after>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/button-grid-22641306\n#define VARIANT 3\n\n#if VARIANT==1\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nconst char kIndex[] = \"index\";\nstruct Display : QLabel {\n Q_SLOT void onClicked() {\n setText(sender()->property(kIndex).toString());\n }\n Q_OBJECT\n};\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n Display display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto index = QString{\"(%1,%2)\"}.arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(index);\n button.setProperty(kIndex, index);\n layout.addWidget(&button, i, j);\n display.connect(&button, SIGNAL(clicked()), SLOT(onClicked()));\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n#include \"main.moc\"\n\n#elif VARIANT==2\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QSignalMapper mapper;\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n QLabel display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto text = QString{\"(%1,%2)\"}.arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(text);\n layout.addWidget(&button, i, j);\n mapper.connect(&button, SIGNAL(clicked()), SLOT(map()));\n mapper.setMapping(&button, text);\n }\n display.connect(&mapper, SIGNAL(mapped(QString)), SLOT(setText(QString)));\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n\n#elif VARIANT==3\n\n#include <QtWidgets>\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n QLabel display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto text = QStringLiteral(\"(%1,%2)\").arg(i).arg(j);\n auto & button = buttons[i*columns+j];\n button.setText(text);\n layout.addWidget(&button, i, j);\n QObject::connect(&button, &QPushButton::clicked, [&display, text] {\n display.setText(text);\n });\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n\n#elif VARIANT==4\n\n#include <QtGui>\n#if QT_VERSION_MAJOR >= 5\n#include <QtWidgets>\n#endif\n\nstruct Display : QLabel {\n Q_SLOT void onClicked() {\n auto const elements = sender()->objectName().split('_');\n auto const i = elements.at(1).toInt();\n auto const j = elements.at(2).toInt();\n setText(QString{\"(%1,%2)\"}.arg(i).arg(j));\n }\n Q_OBJECT\n};\n\nint main(int argc, char *argv[])\n{\n QApplication a{argc, argv};\n QWidget window;\n QGridLayout layout{&window};\n QVarLengthArray<QPushButton, 12> buttons(12);\n Display display;\n\n const int rows = 4, columns = 3;\n for (int i = 0; i < rows; ++ i)\n for (int j = 0; j < columns; ++j) {\n auto & button = buttons[i*columns+j];\n button.setText(QString{\"(%1,%2)\"}.arg(i).arg(j));\n button.setObjectName(QString{\"button_%1_%2\"}.arg(i).arg(j));\n layout.addWidget(&button, i, j);\n display.connect(&button, SIGNAL(clicked()), SLOT(onClicked()));\n }\n layout.addWidget(&display, rows, 0, 1, columns);\n\n window.show();\n return a.exec();\n}\n#include \"main.moc\"\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: querycontainerwindow.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:00:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#define DBAUI_QUERYCONTAINERWINDOW_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include <vcl\/window.hxx>\n#endif\n#ifndef _SV_SPLIT_HXX\n#include <vcl\/split.hxx>\n#endif\n#ifndef DBAUI_DATAVIEW_HXX\n#include \"dataview.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n#ifndef DBAUI_QUERYVIEWSWITCH_HXX\n#include \"QueryViewSwitch.hxx\"\n#endif\n#ifndef _SV_DOCKWIN_HXX\n#include <vcl\/dockwin.hxx>\n#endif\n\nclass FixedLine;\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OBeamer\n \/\/=====================================================================\n \/\/ tempoaray class until the beamer is implemented\n class OBeamer : public DockingWindow\n {\n public:\n OBeamer(Window* _pParent) : DockingWindow(_pParent,0){}\n };\n\n \/\/=====================================================================\n \/\/= OQueryContainerWindow\n \/\/=====================================================================\n class OQueryContainerWindow : public ODataView\n {\n OQueryViewSwitch* m_pViewSwitch;\n OBeamer* m_pBeamer;\n Splitter* m_pSplitter;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xBeamer;\n\n DECL_LINK( SplitHdl, void* );\n public:\n OQueryContainerWindow(Window* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);\n ~OQueryContainerWindow();\n\n virtual void Construct();\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n \/\/ show the beamer\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _xFrame);\n \/\/ called when the beamer has been disposed\n void disposingPreview();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >\n getPreviewFrame() const { return m_xBeamer; }\n\n void initialize(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _xFrame);\n\n OQueryDesignView* getDesignView() { return m_pViewSwitch->getDesignView(); }\n\n sal_Bool isCutAllowed() { return m_pViewSwitch->isCutAllowed(); }\n sal_Bool isPasteAllowed() { return m_pViewSwitch->isPasteAllowed(); }\n sal_Bool isCopyAllowed() { return m_pViewSwitch->isCopyAllowed(); }\n void copy() { m_pViewSwitch->copy(); }\n void cut() { m_pViewSwitch->cut(); }\n void paste() { m_pViewSwitch->paste(); }\n\n void clear() { m_pViewSwitch->clear(); }\n sal_Bool isSlotEnabled( sal_Int32 _nSlotId ) { return m_pViewSwitch->isSlotEnabled( _nSlotId ); }\n void setSlotEnabled( sal_Int32 _nSlotId, sal_Bool _bEnable ) { m_pViewSwitch->setSlotEnabled( _nSlotId, _bEnable ); }\n void setNoneVisbleRow(sal_Int32 _nRows) { m_pViewSwitch->setNoneVisbleRow( _nRows); }\n\n void setReadOnly( sal_Bool _bReadOnly ) { m_pViewSwitch->setReadOnly( _bReadOnly ); }\n\n sal_Bool checkStatement() { return m_pViewSwitch->checkStatement( ); }\n ::rtl::OUString getStatement() { return m_pViewSwitch->getStatement( ); }\n void setStatement( const ::rtl::OUString& _rsStatement ) { m_pViewSwitch->setStatement( _rsStatement ); }\n\n void initialize() { m_pViewSwitch->initialize(); }\n void SaveUIConfig() { m_pViewSwitch->SaveUIConfig(); }\n void reset() { m_pViewSwitch->reset(); }\n\n sal_Bool switchView();\n virtual void GetFocus();\n\n protected:\n \/\/ re-arrange the controls belonging to the document itself\n virtual void resizeAll( const Rectangle& _rPlayground );\n\n \/\/ arrange dericed classes controls in the rectangle given\n virtual void resizeDocumentView(Rectangle& _rPlayground);\n };\n \/\/ end of temp classes\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ DBAUI_QUERYCONTAINERWINDOW_HXX\n\n<commit_msg>INTEGRATION: CWS dba23a (1.7.254); FILE MERGED 2007\/02\/26 11:48:16 fs 1.7.254.1: remove unused code Issue number: #i74804# Submitted by: jnavrati@openoffice.org Reviewed by: frank.schoenheit@sun.com<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: querycontainerwindow.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 10:33:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#define DBAUI_QUERYCONTAINERWINDOW_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include <vcl\/window.hxx>\n#endif\n#ifndef _SV_SPLIT_HXX\n#include <vcl\/split.hxx>\n#endif\n#ifndef DBAUI_DATAVIEW_HXX\n#include \"dataview.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n#ifndef DBAUI_QUERYVIEWSWITCH_HXX\n#include \"QueryViewSwitch.hxx\"\n#endif\n#ifndef _SV_DOCKWIN_HXX\n#include <vcl\/dockwin.hxx>\n#endif\n\nclass FixedLine;\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OBeamer\n \/\/=====================================================================\n \/\/ tempoaray class until the beamer is implemented\n class OBeamer : public DockingWindow\n {\n public:\n OBeamer(Window* _pParent) : DockingWindow(_pParent,0){}\n };\n\n \/\/=====================================================================\n \/\/= OQueryContainerWindow\n \/\/=====================================================================\n class OQueryContainerWindow : public ODataView\n {\n OQueryViewSwitch* m_pViewSwitch;\n OBeamer* m_pBeamer;\n Splitter* m_pSplitter;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xBeamer;\n\n DECL_LINK( SplitHdl, void* );\n public:\n OQueryContainerWindow(Window* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);\n ~OQueryContainerWindow();\n\n virtual void Construct();\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n \/\/ show the beamer\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _xFrame);\n \/\/ called when the beamer has been disposed\n void disposingPreview();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >\n getPreviewFrame() const { return m_xBeamer; }\n\n OQueryDesignView* getDesignView() { return m_pViewSwitch->getDesignView(); }\n\n sal_Bool isCutAllowed() { return m_pViewSwitch->isCutAllowed(); }\n sal_Bool isPasteAllowed() { return m_pViewSwitch->isPasteAllowed(); }\n sal_Bool isCopyAllowed() { return m_pViewSwitch->isCopyAllowed(); }\n void copy() { m_pViewSwitch->copy(); }\n void cut() { m_pViewSwitch->cut(); }\n void paste() { m_pViewSwitch->paste(); }\n\n void clear() { m_pViewSwitch->clear(); }\n sal_Bool isSlotEnabled( sal_Int32 _nSlotId ) { return m_pViewSwitch->isSlotEnabled( _nSlotId ); }\n void setSlotEnabled( sal_Int32 _nSlotId, sal_Bool _bEnable ) { m_pViewSwitch->setSlotEnabled( _nSlotId, _bEnable ); }\n void setNoneVisbleRow(sal_Int32 _nRows) { m_pViewSwitch->setNoneVisbleRow( _nRows); }\n\n void setReadOnly( sal_Bool _bReadOnly ) { m_pViewSwitch->setReadOnly( _bReadOnly ); }\n\n sal_Bool checkStatement() { return m_pViewSwitch->checkStatement( ); }\n ::rtl::OUString getStatement() { return m_pViewSwitch->getStatement( ); }\n void setStatement( const ::rtl::OUString& _rsStatement ) { m_pViewSwitch->setStatement( _rsStatement ); }\n\n void initialize() { m_pViewSwitch->initialize(); }\n void SaveUIConfig() { m_pViewSwitch->SaveUIConfig(); }\n void reset() { m_pViewSwitch->reset(); }\n\n sal_Bool switchView();\n virtual void GetFocus();\n\n protected:\n \/\/ re-arrange the controls belonging to the document itself\n virtual void resizeAll( const Rectangle& _rPlayground );\n\n \/\/ arrange dericed classes controls in the rectangle given\n virtual void resizeDocumentView(Rectangle& _rPlayground);\n };\n \/\/ end of temp classes\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ DBAUI_QUERYCONTAINERWINDOW_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"exegesis\/x86\/cleanup_instruction_set_alternatives.h\"\n\n#include <cstdint>\n#include <unordered_map>\n#include <vector>\n#include \"strings\/string.h\"\n\n#include \"exegesis\/base\/cleanup_instruction_set.h\"\n#include \"exegesis\/proto\/instructions.pb.h\"\n#include \"glog\/logging.h\"\n#include \"strings\/str_cat.h\"\n#include \"util\/gtl\/map_util.h\"\n#include \"util\/task\/canonical_errors.h\"\n#include \"util\/task\/status.h\"\n\nnamespace exegesis {\nnamespace x86 {\nnamespace {\n\nusing ::exegesis::util::InvalidArgumentError;\nusing ::exegesis::util::OkStatus;\nusing ::exegesis::util::Status;\n\n\/\/ Information about an operand that need to be modified when adding an\n\/\/ alternative. There is one instance of this struct for each alternative.\nstruct OperandAlternative {\n \/\/ The new name of the operand.\n const char* operand_name;\n\n \/\/ The new addressing mode of the operand.\n InstructionOperand::AddressingMode addressing_mode;\n\n \/\/ The new value of the operand.\n uint32_t value_size;\n};\nusing OperandAlternativeMap =\n std::unordered_map<string, std::vector<OperandAlternative>>;\n\n\/\/ Returns the list of operand alternatives indexed by the name of the operand.\n\/\/ TODO(ondrasej): Re-enable broadcasted arguments when we have a way to\n\/\/ represent them in the proto.\nconst OperandAlternativeMap& GetOperandAlternativesByName() {\n static const OperandAlternativeMap* const kAlternatives = []() {\n constexpr InstructionOperand::AddressingMode DIRECT_ADDRESSING =\n InstructionOperand::DIRECT_ADDRESSING;\n constexpr InstructionOperand::AddressingMode INDIRECT_ADDRESSING =\n InstructionOperand::INDIRECT_ADDRESSING;\n return new OperandAlternativeMap({\n {\"mm\/m32\",\n {{\"mm1\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"mm\/m64\",\n {{\"mm1\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"mm2\/m64\",\n {{\"mm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"r\/m8\",\n {{\"r8\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"r\/m16\",\n {{\"r16\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"r\/m32\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"r\/m64\",\n {{\"r64\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"r32\/m8\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"r32\/m16\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"r64\/m16\",\n {{\"r64\", DIRECT_ADDRESSING, 64}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"reg\/m8\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"reg\/m16\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"reg\/m32\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm2\/m8\",\n {{\"xmm2\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"xmm2\/m16\",\n {{\"xmm2\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 8}}},\n {\"xmm\/m32\",\n {{\"xmm2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm1\/m32\",\n {{\"xmm1\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm2\/m32\",\n {{\"xmm2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm3\/m32\",\n {{\"xmm3\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm\/m64\",\n {{\"xmm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm1\/m64\",\n {{\"xmm1\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm1\/m128\",\n {{\"xmm1\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m64\",\n {{\"xmm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm3\/m64\",\n {{\"xmm3\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm\/m128\",\n {{\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m128\",\n {{\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm3\/m128\",\n {{\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m256\",\n {{\"xmm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"xmm3\/m256\",\n {{\"xmm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"ymm2\/m256\",\n {{\"ymm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"ymm3\/m256\",\n {{\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"xmm2\/m128\/m32bcst\",\n {\n {\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"xmm3\/m128\/m32bcst\",\n {\n {\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"xmm3\/m128\/m64bcst\",\n {\n {\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"ymm2\/m256\/m32bcst\",\n {\n {\"ymm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm3\/m256\/m32bcst\",\n {\n {\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm3\/m256\/m64bcst\",\n {\n {\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"zmm2\/m512\/m32bcst\",\n {\n {\"zmm2\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm2\/m512\/m64bcst\",\n {\n {\"zmm2\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm3\/m512\/m32bcst\",\n {\n {\"zmm3\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm3\/m512\/m64bcst\",\n {\n {\"zmm3\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m642bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"bnd1\/m128\",\n {{\"bnd1\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"bnd2\/m128\",\n {{\"bnd2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"k2\/m8\",\n {{\"k2\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"k2\/m16\",\n {{\"k2\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"k2\/m32\",\n {{\"k2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"k2\/m64\",\n {{\"k2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n });\n }();\n return *kAlternatives;\n}\n\n} \/\/ namespace\n\nStatus AddAlternatives(InstructionSetProto* instruction_set) {\n CHECK(instruction_set != nullptr);\n Status status = OkStatus();\n const OperandAlternativeMap& alternatives_by_name =\n GetOperandAlternativesByName();\n std::vector<InstructionProto> new_instructions;\n for (InstructionProto& instruction :\n *instruction_set->mutable_instructions()) {\n InstructionFormat* const vendor_syntax =\n instruction.mutable_vendor_syntax();\n for (int operand_index = 0; operand_index < vendor_syntax->operands_size();\n ++operand_index) {\n InstructionOperand* const operand =\n vendor_syntax->mutable_operands(operand_index);\n const std::vector<OperandAlternative>* const alternatives =\n FindOrNull(alternatives_by_name, operand->name());\n if (alternatives == nullptr) continue;\n\n \/\/ The only encoding that allows alternatives is modrm.rm. An operand with\n \/\/ alternatives anywhere else means that there is an error in the data.\n if (operand->encoding() != InstructionOperand::MODRM_RM_ENCODING) {\n return InvalidArgumentError(\n StrCat(\"Instruction does not use modrm.rm encoding:\\n\",\n instruction.DebugString()));\n }\n \/\/ The altenatives are always \"register\" vs \"memory\", because that is the\n \/\/ only kind of alternatives that can be expressed through operand\n \/\/ encoding.\n if (operand->addressing_mode() !=\n InstructionOperand::ANY_ADDRESSING_WITH_FLEXIBLE_REGISTERS) {\n return InvalidArgumentError(StrCat(\n \"The addressing mode does not allow splitting: \",\n InstructionOperand::AddressingMode_Name(operand->addressing_mode()),\n \"\\n\", instruction.DebugString()));\n }\n \/\/ Note that we start iterating at 1, and that we will be reusing\n \/\/ the existing instruction for the first alternative.\n for (int i = 1; i < alternatives->size(); ++i) {\n const OperandAlternative& alternative = (*alternatives)[i];\n new_instructions.push_back(instruction);\n InstructionOperand* const new_instruction_operand =\n new_instructions.back().mutable_vendor_syntax()->mutable_operands(\n operand_index);\n new_instruction_operand->set_name(alternative.operand_name);\n new_instruction_operand->set_addressing_mode(\n alternative.addressing_mode);\n new_instruction_operand->set_value_size_bits(alternative.value_size);\n }\n \/\/ Now overwrite the current instruction's operand.\n const OperandAlternative& first_alternative = alternatives->front();\n operand->set_name(first_alternative.operand_name);\n operand->set_addressing_mode(first_alternative.addressing_mode);\n operand->set_value_size_bits(first_alternative.value_size);\n }\n }\n for (InstructionProto& new_instruction : new_instructions) {\n instruction_set->add_instructions()->Swap(&new_instruction);\n }\n return status;\n}\nREGISTER_INSTRUCTION_SET_TRANSFORM(AddAlternatives, 6000);\n\n} \/\/ namespace x86\n} \/\/ namespace exegesis\n<commit_msg>Added missing operand alternatives.<commit_after>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"exegesis\/x86\/cleanup_instruction_set_alternatives.h\"\n\n#include <cstdint>\n#include <unordered_map>\n#include <vector>\n#include \"strings\/string.h\"\n\n#include \"exegesis\/base\/cleanup_instruction_set.h\"\n#include \"exegesis\/proto\/instructions.pb.h\"\n#include \"glog\/logging.h\"\n#include \"strings\/str_cat.h\"\n#include \"util\/gtl\/map_util.h\"\n#include \"util\/task\/canonical_errors.h\"\n#include \"util\/task\/status.h\"\n\nnamespace exegesis {\nnamespace x86 {\nnamespace {\n\nusing ::exegesis::util::InvalidArgumentError;\nusing ::exegesis::util::OkStatus;\nusing ::exegesis::util::Status;\n\n\/\/ Information about an operand that need to be modified when adding an\n\/\/ alternative. There is one instance of this struct for each alternative.\nstruct OperandAlternative {\n \/\/ The new name of the operand.\n const char* operand_name;\n\n \/\/ The new addressing mode of the operand.\n InstructionOperand::AddressingMode addressing_mode;\n\n \/\/ The new value of the operand.\n uint32_t value_size;\n};\nusing OperandAlternativeMap =\n std::unordered_map<string, std::vector<OperandAlternative>>;\n\n\/\/ Returns the list of operand alternatives indexed by the name of the operand.\n\/\/ TODO(ondrasej): Re-enable broadcasted arguments when we have a way to\n\/\/ represent them in the proto.\nconst OperandAlternativeMap& GetOperandAlternativesByName() {\n static const OperandAlternativeMap* const kAlternatives = []() {\n constexpr InstructionOperand::AddressingMode DIRECT_ADDRESSING =\n InstructionOperand::DIRECT_ADDRESSING;\n constexpr InstructionOperand::AddressingMode INDIRECT_ADDRESSING =\n InstructionOperand::INDIRECT_ADDRESSING;\n return new OperandAlternativeMap({\n {\"mm\/m32\",\n {{\"mm1\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"mm\/m64\",\n {{\"mm1\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"mm2\/m64\",\n {{\"mm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"r\/m8\",\n {{\"r8\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"r\/m16\",\n {{\"r16\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"r\/m32\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"r\/m64\",\n {{\"r64\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"r32\/m8\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"r32\/m16\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"r64\/m16\",\n {{\"r64\", DIRECT_ADDRESSING, 64}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"reg\/m8\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"reg\/m16\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"reg\/m32\",\n {{\"r32\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm2\/m8\",\n {{\"xmm2\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"xmm2\/m16\",\n {{\"xmm2\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"xmm\/m32\",\n {{\"xmm2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm1\/m32\",\n {{\"xmm1\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm2\/m32\",\n {{\"xmm2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm3\/m32\",\n {{\"xmm3\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"xmm\/m64\",\n {{\"xmm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm1\/m16\",\n {{\"xmm1\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"xmm1\/m64\",\n {{\"xmm1\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm1\/m128\",\n {{\"xmm1\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m64\",\n {{\"xmm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm2\/m64\/m32bcst\",\n {\n {\"xmm2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 32},\n }},\n {\"xmm2\/m128\/m64bcst\",\n {\n {\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"xmm3\/m64\",\n {{\"xmm3\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n {\"xmm\/m128\",\n {{\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m128\",\n {{\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm3\/m128\",\n {{\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"xmm2\/m256\",\n {{\"xmm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"xmm3\/m256\",\n {{\"xmm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"ymm2\/m256\",\n {{\"ymm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"ymm3\/m256\",\n {{\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256}}},\n {\"xmm2\/m128\/m32bcst\",\n {\n {\"xmm2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"xmm3\/m128\/m32bcst\",\n {\n {\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"xmm3\/m128\/m64bcst\",\n {\n {\"xmm3\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 128},\n }},\n {\"ymm1\/m256\",\n {\n {\"ymm1\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm2\/m256\/m64bcst\",\n {\n {\"ymm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm2\/m256\/m32bcst\",\n {\n {\"ymm2\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm3\/m256\/m32bcst\",\n {\n {\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"ymm3\/m256\/m64bcst\",\n {\n {\"ymm3\", DIRECT_ADDRESSING, 256},\n {\"m256\", INDIRECT_ADDRESSING, 256},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 256},\n }},\n {\"zmm1\/m512\",\n {\n {\"zmm1\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm2\/m512\",\n {\n {\"zmm2\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm3\/m512\",\n {\n {\"zmm3\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm2\/m512\/m32bcst\",\n {\n {\"zmm2\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm2\/m512\/m64bcst\",\n {\n {\"zmm2\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m64bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm3\/m512\/m32bcst\",\n {\n {\"zmm3\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m32bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"zmm3\/m512\/m64bcst\",\n {\n {\"zmm3\", DIRECT_ADDRESSING, 512},\n {\"m512\", INDIRECT_ADDRESSING, 512},\n \/\/ {\"m642bcst\", INDIRECT_ADDRESSING, 512},\n }},\n {\"bnd1\/m128\",\n {{\"bnd1\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"bnd2\/m128\",\n {{\"bnd2\", DIRECT_ADDRESSING, 128},\n {\"m128\", INDIRECT_ADDRESSING, 128}}},\n {\"k2\/m8\",\n {{\"k2\", DIRECT_ADDRESSING, 8}, {\"m8\", INDIRECT_ADDRESSING, 8}}},\n {\"k2\/m16\",\n {{\"k2\", DIRECT_ADDRESSING, 16}, {\"m16\", INDIRECT_ADDRESSING, 16}}},\n {\"k2\/m32\",\n {{\"k2\", DIRECT_ADDRESSING, 32}, {\"m32\", INDIRECT_ADDRESSING, 32}}},\n {\"k2\/m64\",\n {{\"k2\", DIRECT_ADDRESSING, 64}, {\"m64\", INDIRECT_ADDRESSING, 64}}},\n });\n }();\n return *kAlternatives;\n}\n\n} \/\/ namespace\n\nStatus AddAlternatives(InstructionSetProto* instruction_set) {\n CHECK(instruction_set != nullptr);\n Status status = OkStatus();\n const OperandAlternativeMap& alternatives_by_name =\n GetOperandAlternativesByName();\n std::vector<InstructionProto> new_instructions;\n for (InstructionProto& instruction :\n *instruction_set->mutable_instructions()) {\n InstructionFormat* const vendor_syntax =\n instruction.mutable_vendor_syntax();\n for (int operand_index = 0; operand_index < vendor_syntax->operands_size();\n ++operand_index) {\n InstructionOperand* const operand =\n vendor_syntax->mutable_operands(operand_index);\n const std::vector<OperandAlternative>* const alternatives =\n FindOrNull(alternatives_by_name, operand->name());\n if (alternatives == nullptr) continue;\n\n \/\/ The only encoding that allows alternatives is modrm.rm. An operand with\n \/\/ alternatives anywhere else means that there is an error in the data.\n if (operand->encoding() != InstructionOperand::MODRM_RM_ENCODING) {\n return InvalidArgumentError(\n StrCat(\"Instruction does not use modrm.rm encoding:\\n\",\n instruction.DebugString()));\n }\n \/\/ The altenatives are always \"register\" vs \"memory\", because that is the\n \/\/ only kind of alternatives that can be expressed through operand\n \/\/ encoding.\n if (operand->addressing_mode() !=\n InstructionOperand::ANY_ADDRESSING_WITH_FLEXIBLE_REGISTERS) {\n return InvalidArgumentError(StrCat(\n \"The addressing mode does not allow splitting: \",\n InstructionOperand::AddressingMode_Name(operand->addressing_mode()),\n \"\\n\", instruction.DebugString()));\n }\n \/\/ Note that we start iterating at 1, and that we will be reusing\n \/\/ the existing instruction for the first alternative.\n for (int i = 1; i < alternatives->size(); ++i) {\n const OperandAlternative& alternative = (*alternatives)[i];\n new_instructions.push_back(instruction);\n InstructionOperand* const new_instruction_operand =\n new_instructions.back().mutable_vendor_syntax()->mutable_operands(\n operand_index);\n new_instruction_operand->set_name(alternative.operand_name);\n new_instruction_operand->set_addressing_mode(\n alternative.addressing_mode);\n new_instruction_operand->set_value_size_bits(alternative.value_size);\n }\n \/\/ Now overwrite the current instruction's operand.\n const OperandAlternative& first_alternative = alternatives->front();\n operand->set_name(first_alternative.operand_name);\n operand->set_addressing_mode(first_alternative.addressing_mode);\n operand->set_value_size_bits(first_alternative.value_size);\n }\n }\n for (InstructionProto& new_instruction : new_instructions) {\n instruction_set->add_instructions()->Swap(&new_instruction);\n }\n return status;\n}\nREGISTER_INSTRUCTION_SET_TRANSFORM(AddAlternatives, 6000);\n\n} \/\/ namespace x86\n} \/\/ namespace exegesis\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2014, Peter G. Baum\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gpio.h\"\n#include <unistd.h>\n#include <fcntl.h>\n#include <string>\n#include <stdexcept>\n#include <map>\n#include <cstring>\n\nnamespace\n{\n const char *basePath = \"\/sys\/class\/gpio\/\";\n struct Comp\n {\n bool operator()( const char *a, const char *b ) const\n {\n return strcmp( a, b ) < 0;\n }\n };\n\n const std::map<const char *,int, Comp> nameMap =\n {\n { \"P8.3\", 32 + 6 },\n { \"P8.4\", 32 + 7 },\n { \"P8.5\", 32 + 2 },\n { \"P8.6\", 32 + 3 },\n { \"P8.7\", 64 + 2 },\n { \"P8.8\", 64 + 3 },\n { \"P8.9\", 64 + 5 },\n { \"P8.10\", 64 + 4 },\n { \"P8.11\", 32 + 13 },\n { \"P8.12\", 32 + 12 },\n { \"P8.13\", 0 + 23 },\n { \"P8.14\", 0 + 26 },\n { \"P8.15\", 32 + 15 },\n { \"P8.16\", 32 + 14 },\n { \"P8.17\", 0 + 27 },\n { \"P8.18\", 64 + 1 },\n { \"P8.19\", 0 + 22 },\n { \"P8.20\", 32 + 31 },\n { \"P8.21\", 32 + 30 },\n { \"P8.22\", 32 + 5 },\n { \"P8.23\", 32 + 4 },\n { \"P8.24\", 32 + 1 },\n { \"P8.25\", 32 + 0 },\n { \"P8.26\", 32 + 29 },\n { \"P8.27\", 64 + 22 },\n { \"P8.28\", 64 + 24 },\n { \"P8.29\", 64 + 23 },\n { \"P8.30\", 64 + 25 },\n { \"P8.31\", 0 + 10 },\n { \"P8.32\", 0 + 11 },\n { \"P8.33\", 0 + 9 },\n { \"P8.34\", 64 + 17 },\n { \"P8.35\", 0 + 8 },\n { \"P8.36\", 64 + 16 },\n { \"P8.37\", 64 + 14 },\n { \"P8.38\", 64 + 15 },\n { \"P8.39\", 64 + 12 },\n { \"P8.40\", 64 + 13 },\n { \"P8.41\", 64 + 10 },\n { \"P8.42\", 64 + 11 },\n { \"P8.43\", 64 + 8 },\n { \"P8.44\", 64 + 9 },\n { \"P8.45\", 64 + 6 },\n { \"P8.46\", 64 + 7 },\n { \"P9.11\", 0 + 30 },\n { \"P9.12\", 32 + 28 },\n { \"P9.13\", 0 + 31 },\n { \"P9.14\", 32 + 18 },\n { \"P9.15\", 32 + 16 },\n { \"P9.16\", 32 + 19 },\n { \"P9.17\", 0 + 5 },\n { \"P9.18\", 0 + 4 },\n { \"P9.19\", 0 + 13 },\n { \"P9.20\", 0 + 12 },\n { \"P9.21\", 0 + 3 },\n { \"P9.22\", 0 + 2 },\n { \"P9.23\", 32 + 17 },\n { \"P9.24\", 0 + 15 },\n { \"P9.25\", 96 + 21 },\n { \"P9.26\", 0 + 14 },\n { \"P9.27\", 96 + 19 },\n { \"P9.28\", 96 + 17 },\n { \"P9.29\", 96 + 15 },\n { \"P9.30\", 96 + 16 },\n { \"P9.31\", 96 + 14 },\n \/\/ LEDs\n { \"USR0\", 32 + 21 },\n { \"USR1\", 32 + 22 },\n { \"USR2\", 32 + 23 },\n { \"USR3\", 32 + 24 },\n };\n\n int getNumberFromName( const char *name )\n {\n if( strncmp( name, \"GPIO\", 4 ) == 0 )\n {\n const int bank = atoi( name + 4 );\n const char *p = strchr( name, '_' );\n if( p == nullptr )\n throw std::invalid_argument( \"Invalid GPIO name\" );\n const int num = atoi( p + 1 );\n return bank * 32 + num;\n }\n auto p( nameMap.find( name ) );\n if( p == nameMap.end() )\n throw std::invalid_argument( \"Invalid header name\" );\n return p->second;\n }\n}\n\n\nGPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )\n{\n const std::string path( basePath );\n int fd = open( ( path + \"export\" ).c_str(), O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n\n fd = open( (path + \"gpio\" + std::to_string( gpio ) + \"\/direction\").c_str(),\n O_WRONLY );\n if( fd < 0 )\n {\n close();\n throw std::invalid_argument( strerror( errno ) );\n }\n if( direction == IN )\n write( fd, \"in\", 3 );\n else\n write( fd, \"out\", 4 );\n ::close( fd );\n}\n\nvoid GPIO::close( )\n{\n const std::string path( basePath );\n int fd = open( (path + \"unexport\" ).c_str(), O_WRONLY );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n}\n\nGPIO::~GPIO( )\n{\n try\n {\n close();\n }\n catch( ... )\n {\n }\n}\n\nGPO::GPO( int gpio_ ) : gpio( gpio_, GPIO::OUT )\n{\n const std::string path( basePath );\n fd = open( (path + \"gpio\" + std::to_string( gpio_ ) + \"\/value\").c_str(),\n O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPO::GPO( const char *name ) : GPO( getNumberFromName( name ) )\n{\n}\n\nGPO::~GPO( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPO::set( bool val )\n{\n write( fd, val ? \"1\": \"0\", 2 );\n}\n\nvoid GPO::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n<commit_msg>gpio: use #define to reduce std::string overhead<commit_after>\/*\nCopyright (c) 2014, Peter G. Baum\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gpio.h\"\n#include <unistd.h>\n#include <fcntl.h>\n#include <string>\n#include <stdexcept>\n#include <map>\n#include <cstring>\n\n#define SYSFS_GPIO_DIR \"\/sys\/class\/gpio\/\"\n\nnamespace\n{\n struct Comp\n {\n bool operator()( const char *a, const char *b ) const\n {\n return strcmp( a, b ) < 0;\n }\n };\n\n const std::map<const char *,int, Comp> nameMap =\n {\n { \"P8.3\", 32 + 6 },\n { \"P8.4\", 32 + 7 },\n { \"P8.5\", 32 + 2 },\n { \"P8.6\", 32 + 3 },\n { \"P8.7\", 64 + 2 },\n { \"P8.8\", 64 + 3 },\n { \"P8.9\", 64 + 5 },\n { \"P8.10\", 64 + 4 },\n { \"P8.11\", 32 + 13 },\n { \"P8.12\", 32 + 12 },\n { \"P8.13\", 0 + 23 },\n { \"P8.14\", 0 + 26 },\n { \"P8.15\", 32 + 15 },\n { \"P8.16\", 32 + 14 },\n { \"P8.17\", 0 + 27 },\n { \"P8.18\", 64 + 1 },\n { \"P8.19\", 0 + 22 },\n { \"P8.20\", 32 + 31 },\n { \"P8.21\", 32 + 30 },\n { \"P8.22\", 32 + 5 },\n { \"P8.23\", 32 + 4 },\n { \"P8.24\", 32 + 1 },\n { \"P8.25\", 32 + 0 },\n { \"P8.26\", 32 + 29 },\n { \"P8.27\", 64 + 22 },\n { \"P8.28\", 64 + 24 },\n { \"P8.29\", 64 + 23 },\n { \"P8.30\", 64 + 25 },\n { \"P8.31\", 0 + 10 },\n { \"P8.32\", 0 + 11 },\n { \"P8.33\", 0 + 9 },\n { \"P8.34\", 64 + 17 },\n { \"P8.35\", 0 + 8 },\n { \"P8.36\", 64 + 16 },\n { \"P8.37\", 64 + 14 },\n { \"P8.38\", 64 + 15 },\n { \"P8.39\", 64 + 12 },\n { \"P8.40\", 64 + 13 },\n { \"P8.41\", 64 + 10 },\n { \"P8.42\", 64 + 11 },\n { \"P8.43\", 64 + 8 },\n { \"P8.44\", 64 + 9 },\n { \"P8.45\", 64 + 6 },\n { \"P8.46\", 64 + 7 },\n { \"P9.11\", 0 + 30 },\n { \"P9.12\", 32 + 28 },\n { \"P9.13\", 0 + 31 },\n { \"P9.14\", 32 + 18 },\n { \"P9.15\", 32 + 16 },\n { \"P9.16\", 32 + 19 },\n { \"P9.17\", 0 + 5 },\n { \"P9.18\", 0 + 4 },\n { \"P9.19\", 0 + 13 },\n { \"P9.20\", 0 + 12 },\n { \"P9.21\", 0 + 3 },\n { \"P9.22\", 0 + 2 },\n { \"P9.23\", 32 + 17 },\n { \"P9.24\", 0 + 15 },\n { \"P9.25\", 96 + 21 },\n { \"P9.26\", 0 + 14 },\n { \"P9.27\", 96 + 19 },\n { \"P9.28\", 96 + 17 },\n { \"P9.29\", 96 + 15 },\n { \"P9.30\", 96 + 16 },\n { \"P9.31\", 96 + 14 },\n \/\/ LEDs\n { \"USR0\", 32 + 21 },\n { \"USR1\", 32 + 22 },\n { \"USR2\", 32 + 23 },\n { \"USR3\", 32 + 24 },\n };\n\n int getNumberFromName( const char *name )\n {\n if( strncmp( name, \"GPIO\", 4 ) == 0 )\n {\n const int bank = atoi( name + 4 );\n const char *p = strchr( name, '_' );\n if( p == nullptr )\n throw std::invalid_argument( \"Invalid GPIO name\" );\n const int num = atoi( p + 1 );\n return bank * 32 + num;\n }\n auto p( nameMap.find( name ) );\n if( p == nameMap.end() )\n throw std::invalid_argument( \"Invalid header name\" );\n return p->second;\n }\n}\n\n\nGPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )\n{\n int fd = open( SYSFS_GPIO_DIR \"export\", O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n\n fd = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio ) + \"\/direction\").c_str(), O_WRONLY );\n if( fd < 0 )\n {\n close();\n throw std::invalid_argument( strerror( errno ) );\n }\n if( direction == IN )\n write( fd, \"in\", 3 );\n else\n write( fd, \"out\", 4 );\n ::close( fd );\n}\n\nvoid GPIO::close( )\n{\n int fd = open( SYSFS_GPIO_DIR \"unexport\", O_WRONLY );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n}\n\nGPIO::~GPIO( )\n{\n try\n {\n close();\n }\n catch( ... )\n {\n }\n}\n\nGPO::GPO( int gpio_ ) : gpio( gpio_, GPIO::OUT )\n{\n const std::string path( SYSFS_GPIO_DIR \"gpio\" );\n fd = open( (path + std::to_string( gpio_ ) + \"\/value\").c_str(),\n O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPO::GPO( const char *name ) : GPO( getNumberFromName( name ) )\n{\n}\n\nGPO::~GPO( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPO::set( bool val )\n{\n write( fd, val ? \"1\": \"0\", 2 );\n}\n\nvoid GPO::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SalomeApp_SelectionMgr.h\"\n\n#include \"SalomeApp_Study.h\"\n#include \"SalomeApp_DataOwner.h\"\n#include \"SalomeApp_DataSubOwner.h\"\n#include \"SalomeApp_Application.h\"\n\n#include <SUIT_Session.h>\n\n#include <SALOME_ListIO.hxx>\n#include <SALOME_ListIteratorOfListIO.hxx>\n\n\/\/ Open CASCADE Include\n#include <TColStd_MapOfInteger.hxx>\n#include <TColStd_MapIteratorOfMapOfInteger.hxx>\n#include <TColStd_IndexedMapOfInteger.hxx>\n\n#include \"SALOMEDSClient.hxx\"\n\nSalomeApp_SelectionMgr::SalomeApp_SelectionMgr( SalomeApp_Application* app, const bool fb )\n: SUIT_SelectionMgr( fb ),\nmyApp( app )\n{\n}\n\nSalomeApp_SelectionMgr::~SalomeApp_SelectionMgr()\n{\n}\n\nSalomeApp_Application* SalomeApp_SelectionMgr::application() const\n{\n return myApp;\n}\n\n\/*\n get all selected objects from selection manager\n\n*\/\nvoid SalomeApp_SelectionMgr::selectedObjects( SALOME_ListIO& lst ) const\n{\n lst.Clear();\n\n if ( !application() )\n return;\n\n SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( application()->activeStudy() );\n if ( !appStudy )\n return;\n\n _PTR(Study) aStudy ( appStudy->studyDS() );\n if ( !aStudy )\n return;\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataOwner* owner = dynamic_cast<const SalomeApp_DataOwner*>( (*itr).operator->() );\n if( owner )\n lst.Append( owner->IO() );\n\/*\n\n if ( owner && dynamic_cast<const SalomeApp_DataSubOwner*>( owner ) ) \n { \/\/get only subowners, insert into lst unique subowners (subowners with different entries)\n if ( !anEntryList.contains( owner->entry() ) )\n {\t\n\tanEntryList.append( owner->entry() );\n\n\t\/\/construct SALOME_InteractiveObject with predefined entry\n\t_PTR(SObject) anObj ( aStudy->FindObjectID( owner->entry().latin1() ) );\n\tif ( anObj )\n\t{\n\t _PTR(SComponent) aFC (anObj->GetFatherComponent());\n\t if ( aFC )\n\t {\n\t anIO = new SALOME_InteractiveObject( anObj->GetID().c_str(), aFC->ComponentDataType().c_str(), anObj->GetName().c_str() );\n\t if ( anIO ) lst.Append( anIO );\n\t }\n\t}\n }\n }\n else if ( owner )\n { \/\/get not subowners data owners\n _PTR(SObject) anObj ( aStudy->FindObjectID( owner->entry().latin1() ) );\n if ( anObj )\n {\n _PTR(SComponent) aFC (anObj->GetFatherComponent());\n if ( aFC )\n {\n anIO = new SALOME_InteractiveObject( anObj->GetID().c_str(), aFC->ComponentDataType().c_str(), anObj->GetName().c_str() );\n\t if ( anIO ) lst.Append( anIO );\n }\n }\n }\n*\/\n }\n}\n\nvoid SalomeApp_SelectionMgr::setSelectedObjects( const SALOME_ListIO& lst, const bool append )\n{\n if ( !application() )\n return;\n\n SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( application()->activeStudy() );\n if ( !appStudy )\n return;\n\n _PTR(Study) aStudy ( appStudy->studyDS() );\n if ( !aStudy )\n return;\n\n SUIT_DataOwnerPtrList owners;\n for ( SALOME_ListIteratorOfListIO it( lst ); it.More(); it.Next() )\n {\n if ( it.Value()->hasEntry() )\n owners.append( new SalomeApp_DataOwner( it.Value()->getEntry() ) );\n }\n setSelected( owners, append );\n}\n\nvoid SalomeApp_SelectionMgr::selectionChanged( SUIT_Selector* theSel )\n{\n SUIT_SelectionMgr::selectionChanged( theSel );\n\n emit currentSelectionChanged();\n}\n\n\/*\n get map of indexes for the given SALOME_InteractiveObject\n\n*\/\nvoid SalomeApp_SelectionMgr::GetIndexes( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t TColStd_IndexedMapOfInteger& theIndex)\n{\n theIndex.Clear();\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner )\n if ( subOwner->entry() == QString(IObject->getEntry()) )\n\ttheIndex.Add( subOwner->index() );\n }\n \n}\n\n\/*\n get map of indexes for the given entry of SALOME_InteractiveObject\n\n*\/\nvoid SalomeApp_SelectionMgr::GetIndexes( const QString& theEntry, TColStd_IndexedMapOfInteger& theIndex )\n{\n theIndex.Clear();\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner )\n if ( subOwner->entry() == theEntry )\n\ttheIndex.Add( subOwner->index() );\n }\n\n}\n\nbool SalomeApp_SelectionMgr::AddOrRemoveIndex( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t const TColStd_MapOfInteger& theIndexes, \n\t\t\t\t\t bool modeShift)\n{\n SUIT_DataOwnerPtrList remainsOwners;\n \n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n if ( !modeShift ) {\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataOwner* owner = dynamic_cast<const SalomeApp_DataOwner*>( (*itr).operator->() );\n if ( owner ) \n {\n\tif ( owner->entry() != QString(IObject->getEntry()) ) \n\t{\t \n\t const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( owner );\n\t if ( subOwner )\n\t remainsOwners.append( new SalomeApp_DataSubOwner( subOwner->entry(), subOwner->index() ) );\n\t else\n\t remainsOwners.append( new SalomeApp_DataOwner( owner->entry() ) );\n\t}\n }\n }\n }\n else\n remainsOwners = aList;\n\n TColStd_MapIteratorOfMapOfInteger It;\n It.Initialize(theIndexes);\n for(;It.More();It.Next())\n remainsOwners.append( new SalomeApp_DataSubOwner( QString(IObject->getEntry()), It.Key() ) );\n \n bool append = false;\n setSelected( remainsOwners, append );\n\n emit currentSelectionChanged();\n\n TColStd_IndexedMapOfInteger anIndexes;\n GetIndexes( IObject, anIndexes );\n return !anIndexes.IsEmpty();\n\n}\n\n\/*\n select 'subobjects' with given indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectObjects( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t TColStd_IndexedMapOfInteger theIndex, bool append )\n{\n SUIT_DataOwnerPtrList aList;\n\n if ( theIndex.IsEmpty() )\n aList.append( new SalomeApp_DataOwner( QString(IObject->getEntry()) ) );\n else\n {\n int i;\n for ( i = 1; i <= theIndex.Extent(); i++ )\n\taList.append( new SalomeApp_DataSubOwner( QString(IObject->getEntry()), theIndex( i ) ) );\n }\n\n setSelected( aList, append );\n\n}\n\n\/*\n select 'subobjects' with given indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectObjects( MapIOOfMapOfInteger theMapIO, bool append )\n{\n SUIT_DataOwnerPtrList aList;\n\n MapIOOfMapOfInteger::Iterator it;\n for ( it = theMapIO.begin(); it != theMapIO.end(); ++it ) \n {\n if ( it.data().IsEmpty() )\n\taList.append( new SalomeApp_DataOwner( QString(it.key()->getEntry()) ) );\n else\n\t{\n\t int i;\n\t for ( i = 1; i <= it.data().Extent(); i++ )\n\t aList.append( new SalomeApp_DataSubOwner( QString(it.key()->getEntry()), it.data()( i ) ) );\n\t}\n }\n \n setSelected( aList, append );\n\n}\n\n\/*\n get map of selected subowners : object's entry <-> map of indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectedSubOwners( MapEntryOfMapOfInteger& theMap )\n{\n theMap.clear();\n\n TColStd_IndexedMapOfInteger anIndexes;\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner ) \n {\n if ( !theMap.contains( subOwner->entry() ) )\n {\n\tanIndexes.Clear();\n\tGetIndexes( subOwner->entry(), anIndexes );\n\ttheMap.insert( subOwner->entry(), anIndexes );\n }\n }\n }\n}\n<commit_msg>To adjust to new SalomeApp_DataOwner, which now holds SALOME_InteractiveObject<commit_after>#include \"SalomeApp_SelectionMgr.h\"\n\n#include \"SalomeApp_Study.h\"\n#include \"SalomeApp_DataOwner.h\"\n#include \"SalomeApp_DataSubOwner.h\"\n#include \"SalomeApp_Application.h\"\n\n#include <SUIT_Session.h>\n\n#include <SALOME_ListIO.hxx>\n#include <SALOME_ListIteratorOfListIO.hxx>\n\n\/\/ Open CASCADE Include\n#include <TColStd_MapOfInteger.hxx>\n#include <TColStd_MapIteratorOfMapOfInteger.hxx>\n#include <TColStd_IndexedMapOfInteger.hxx>\n\n#include \"SALOMEDSClient.hxx\"\n\nSalomeApp_SelectionMgr::SalomeApp_SelectionMgr( SalomeApp_Application* app, const bool fb )\n: SUIT_SelectionMgr( fb ),\nmyApp( app )\n{\n}\n\nSalomeApp_SelectionMgr::~SalomeApp_SelectionMgr()\n{\n}\n\nSalomeApp_Application* SalomeApp_SelectionMgr::application() const\n{\n return myApp;\n}\n\n\/*\n get all selected objects from selection manager\n\n*\/\nvoid SalomeApp_SelectionMgr::selectedObjects( SALOME_ListIO& lst ) const\n{\n lst.Clear();\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataOwner* owner = dynamic_cast<const SalomeApp_DataOwner*>( (*itr).operator->() );\n if( owner )\n lst.Append( owner->IO() );\n }\n}\n\nvoid SalomeApp_SelectionMgr::setSelectedObjects( const SALOME_ListIO& lst, const bool append )\n{\n SUIT_DataOwnerPtrList owners;\n for ( SALOME_ListIteratorOfListIO it( lst ); it.More(); it.Next() )\n {\n if ( it.Value()->hasEntry() )\n owners.append( new SalomeApp_DataOwner( it.Value() ) );\n }\n\n setSelected( owners, append );\n}\n\nvoid SalomeApp_SelectionMgr::selectionChanged( SUIT_Selector* theSel )\n{\n SUIT_SelectionMgr::selectionChanged( theSel );\n\n emit currentSelectionChanged();\n}\n\n\/*\n get map of indexes for the given SALOME_InteractiveObject\n\n*\/\nvoid SalomeApp_SelectionMgr::GetIndexes( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t TColStd_IndexedMapOfInteger& theIndex)\n{\n theIndex.Clear();\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner )\n if ( subOwner->entry() == QString(IObject->getEntry()) )\n\ttheIndex.Add( subOwner->index() );\n }\n \n}\n\n\/*\n get map of indexes for the given entry of SALOME_InteractiveObject\n\n*\/\nvoid SalomeApp_SelectionMgr::GetIndexes( const QString& theEntry, TColStd_IndexedMapOfInteger& theIndex )\n{\n theIndex.Clear();\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner )\n if ( subOwner->entry() == theEntry )\n\ttheIndex.Add( subOwner->index() );\n }\n\n}\n\nbool SalomeApp_SelectionMgr::AddOrRemoveIndex( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t const TColStd_MapOfInteger& theIndexes, \n\t\t\t\t\t bool modeShift)\n{\n SUIT_DataOwnerPtrList remainsOwners;\n \n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n if ( !modeShift ) {\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataOwner* owner = dynamic_cast<const SalomeApp_DataOwner*>( (*itr).operator->() );\n if ( owner ) \n {\n\tif ( owner->entry() != QString(IObject->getEntry()) ) \n\t{\t \n\t const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( owner );\n\t if ( subOwner )\n\t remainsOwners.append( new SalomeApp_DataSubOwner( subOwner->entry(), subOwner->index() ) );\n\t else\n\t remainsOwners.append( new SalomeApp_DataOwner( owner->entry() ) );\n\t}\n }\n }\n }\n else\n remainsOwners = aList;\n\n TColStd_MapIteratorOfMapOfInteger It;\n It.Initialize(theIndexes);\n for(;It.More();It.Next())\n remainsOwners.append( new SalomeApp_DataSubOwner( QString(IObject->getEntry()), It.Key() ) );\n \n bool append = false;\n setSelected( remainsOwners, append );\n\n emit currentSelectionChanged();\n\n TColStd_IndexedMapOfInteger anIndexes;\n GetIndexes( IObject, anIndexes );\n return !anIndexes.IsEmpty();\n\n}\n\n\/*\n select 'subobjects' with given indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectObjects( const Handle(SALOME_InteractiveObject)& IObject, \n\t\t\t\t\t TColStd_IndexedMapOfInteger theIndex, bool append )\n{\n SUIT_DataOwnerPtrList aList;\n\n if ( theIndex.IsEmpty() )\n aList.append( new SalomeApp_DataOwner( QString(IObject->getEntry()) ) );\n else\n {\n int i;\n for ( i = 1; i <= theIndex.Extent(); i++ )\n\taList.append( new SalomeApp_DataSubOwner( QString(IObject->getEntry()), theIndex( i ) ) );\n }\n\n setSelected( aList, append );\n\n}\n\n\/*\n select 'subobjects' with given indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectObjects( MapIOOfMapOfInteger theMapIO, bool append )\n{\n SUIT_DataOwnerPtrList aList;\n\n MapIOOfMapOfInteger::Iterator it;\n for ( it = theMapIO.begin(); it != theMapIO.end(); ++it ) \n {\n if ( it.data().IsEmpty() )\n\taList.append( new SalomeApp_DataOwner( QString(it.key()->getEntry()) ) );\n else\n\t{\n\t int i;\n\t for ( i = 1; i <= it.data().Extent(); i++ )\n\t aList.append( new SalomeApp_DataSubOwner( QString(it.key()->getEntry()), it.data()( i ) ) );\n\t}\n }\n \n setSelected( aList, append );\n\n}\n\n\/*\n get map of selected subowners : object's entry <-> map of indexes\n\n*\/\nvoid SalomeApp_SelectionMgr::selectedSubOwners( MapEntryOfMapOfInteger& theMap )\n{\n theMap.clear();\n\n TColStd_IndexedMapOfInteger anIndexes;\n\n SUIT_DataOwnerPtrList aList;\n selected( aList );\n\n for ( SUIT_DataOwnerPtrList::const_iterator itr = aList.begin(); itr != aList.end(); ++itr )\n {\n const SalomeApp_DataSubOwner* subOwner = dynamic_cast<const SalomeApp_DataSubOwner*>( (*itr).operator->() );\n if ( subOwner ) \n {\n if ( !theMap.contains( subOwner->entry() ) )\n {\n\tanIndexes.Clear();\n\tGetIndexes( subOwner->entry(), anIndexes );\n\ttheMap.insert( subOwner->entry(), anIndexes );\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fltlst.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2003-04-04 16:07:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_FLTLST_HXX\n#define _SFX_FLTLST_HXX\n\n\/\/*****************************************************************************************************************\n\/\/ includes\n\/\/*****************************************************************************************************************\n#ifndef _SFX_FCONTNR_HXX\n#include <fcontnr.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XFLUSHABLE_HPP_\n#include <com\/sun\/star\/util\/XFlushable.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XFLUSHLISTENER_HPP_\n#include <com\/sun\/star\/util\/XFlushListener.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/document\/XEventListener.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_\n#include <com\/sun\/star\/lang\/EventObject.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n\n\/\/*****************************************************************************************************************\n\/\/ declarations\n\/\/*****************************************************************************************************************\nclass SfxFilterListener : public ::cppu::WeakImplHelper1< ::com::sun::star::util::XFlushListener >\n{\n \/\/ member\n private:\n ::osl::Mutex m_aMutex ;\n ::rtl::OUString m_sFactory ;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XFlushable > m_xTypeCache ;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XFlushable > m_xFilterCache;\n SfxFilterContainer* m_pContainer ;\n\n \/\/ c++ interface\n public:\n SfxFilterListener( const ::rtl::OUString& sFactory ,\n SfxFilterContainer* pContainer );\n ~SfxFilterListener( );\n\n \/\/ uno interface\n public:\n \/\/ XFlushListener\n virtual void SAL_CALL flushed( const ::com::sun::star::lang::EventObject& aSource ) throw( ::com::sun::star::uno::RuntimeException );\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aSource ) throw( ::com::sun::star::uno::RuntimeException );\n\n}; \/\/ SfxFilterListener\n\n#endif \/\/ _SFX_FLTLST_HXX\n<commit_msg>INTEGRATION: CWS fwkq1 (1.4.66); FILE MERGED 2003\/07\/14 18:00:09 mba 1.4.66.1: #110843#: get rid of factories<commit_after>\/*************************************************************************\n *\n * $RCSfile: fltlst.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 07:58:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_FLTLST_HXX\n#define _SFX_FLTLST_HXX\n\n\/\/*****************************************************************************************************************\n\/\/ includes\n\/\/*****************************************************************************************************************\n#ifndef _SFX_FCONTNR_HXX\n#include <fcontnr.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XFLUSHABLE_HPP_\n#include <com\/sun\/star\/util\/XFlushable.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XFLUSHLISTENER_HPP_\n#include <com\/sun\/star\/util\/XFlushListener.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/document\/XEventListener.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_\n#include <com\/sun\/star\/lang\/EventObject.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n\n\/\/*****************************************************************************************************************\n\/\/ declarations\n\/\/*****************************************************************************************************************\nclass SfxFilterListener : public ::cppu::WeakImplHelper1< ::com::sun::star::util::XFlushListener >\n{\n \/\/ member\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XFlushable > m_xTypeCache ;\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XFlushable > m_xFilterCache;\n\n \/\/ c++ interface\n public:\n SfxFilterListener();\n ~SfxFilterListener();\n\n \/\/ uno interface\n public:\n \/\/ XFlushListener\n virtual void SAL_CALL flushed( const ::com::sun::star::lang::EventObject& aSource ) throw( ::com::sun::star::uno::RuntimeException );\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aSource ) throw( ::com::sun::star::uno::RuntimeException );\n\n}; \/\/ SfxFilterListener\n\n#endif \/\/ _SFX_FLTLST_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"sixtracklib\/cuda\/argument.h\"\n\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <sstream>\n\n#include <gtest\/gtest.h>\n\n#include \"sixtracklib\/testlib.h\"\n\n#include \"sixtracklib\/common\/definitions.h\"\n#include \"sixtracklib\/common\/generated\/path.h\"\n#include \"sixtracklib\/common\/buffer.h\"\n#include \"sixtracklib\/common\/particles.h\"\n#include \"sixtracklib\/common\/context\/definitions.h\"\n#include \"sixtracklib\/cuda\/context.h\"\n\nTEST( C99_CudaArgumentTests, ArgumentCObjectBufferTest )\n{\n using argument_t = ::NS(CudaArgument);\n using context_t = ::NS(CudaContext);\n using particles_t = ::NS(Particles);\n using buffer_t = ::NS(Buffer);\n using buf_size_t = ::NS(buffer_size_t);\n using ctx_size_t = ::NS(context_size_t);\n\n buf_size_t const NUM_PARTICLES = 100;\n buffer_t* pb = ::NS(Buffer_new)( 0u );\n\n particles_t* particles = ::NS(Particles_new)( pb, NUM_PARTICLES );\n SIXTRL_ASSERT( particles != nullptr );\n\n context_t* context = ::NS(CudaContext_create)();\n ASSERT_TRUE( context != nullptr );\n\n argument_t* particles_arg = ::NS(CudaArgument_new)( context );\n ASSERT_TRUE( particles_arg != nullptr );\n\n bool success = ::NS(CudaArgument_send_buffer)( particles_arg, pb );\n ASSERT_TRUE( success );\n\n ::NS(CudaArgument_delete)( particles_arg );\n ::NS(CudaContext_delete)( context );\n ::NS(Buffer_delete)( pb );\n\n context = nullptr;\n particles_arg = nullptr;\n particles = nullptr;\n pb = nullptr;\n}\n\n\/* end: tests\/sixtracklib\/cuda\/test_context_cxx.cpp *\/\n<commit_msg>tests\/sixtracklib: expand the NS(CudaArgument_*) related C99 unit-test<commit_after>#include \"sixtracklib\/cuda\/argument.h\"\n\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <sstream>\n\n#include <gtest\/gtest.h>\n\n#include \"sixtracklib\/testlib.h\"\n\n#include \"sixtracklib\/common\/definitions.h\"\n#include \"sixtracklib\/common\/generated\/path.h\"\n#include \"sixtracklib\/common\/buffer.h\"\n#include \"sixtracklib\/common\/particles.h\"\n#include \"sixtracklib\/common\/context\/definitions.h\"\n#include \"sixtracklib\/cuda\/context.h\"\n\nTEST( C99_CudaArgumentTests, ArgumentCObjectBufferTest )\n{\n using argument_t = ::NS(CudaArgument);\n using context_t = ::NS(CudaContext);\n using particles_t = ::NS(Particles);\n using buffer_t = ::NS(Buffer);\n using buf_size_t = ::NS(buffer_size_t);\n using ctx_size_t = ::NS(context_size_t);\n\n buf_size_t const NUM_PARTICLES = 1000;\n buffer_t* pb = ::NS(Buffer_new)( 0u );\n\n buffer_t* cmp_pb = ::NS(Buffer_new)( 0u );\n\n particles_t* particles = ::NS(Particles_new)( pb, NUM_PARTICLES );\n SIXTRL_ASSERT( particles != nullptr );\n\n ::NS(Particles_realistic_init)( particles );\n\n particles_t* cmp_particles = ::NS(Particles_add_copy)( cmp_pb, particles );\n SIXTRL_ASSERT( cmp_particles != nullptr );\n SIXTRL_ASSERT( ::NS(Particles_compare_values)(\n particles, cmp_particles ) == 0 );\n\n context_t* context = ::NS(CudaContext_create)();\n ASSERT_TRUE( context != nullptr );\n\n argument_t* particles_arg = ::NS(CudaArgument_new)( context );\n ASSERT_TRUE( particles_arg != nullptr );\n\n bool success = ::NS(CudaArgument_send_buffer)( particles_arg, pb );\n ASSERT_TRUE( success );\n\n success = ::NS(CudaArgument_receive_buffer)( particles_arg, pb );\n ASSERT_TRUE( success );\n\n particles = ::NS(Particles_buffer_get_particles)( pb, 00 );\n ASSERT_TRUE( particles != nullptr );\n\n ASSERT_TRUE( ::NS(Particles_compare_values)(\n particles, cmp_particles ) == 0 );\n\n ::NS(CudaArgument_delete)( particles_arg );\n ::NS(CudaContext_delete)( context );\n ::NS(Buffer_delete)( pb );\n ::NS(Buffer_delete)( cmp_pb );\n\n cmp_particles = nullptr;\n particles = nullptr;\n\n context = nullptr;\n particles_arg = nullptr;\n cmp_pb = nullptr;\n pb = nullptr;\n}\n\n\/* end: tests\/sixtracklib\/cuda\/test_context_cxx.cpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appbaslib.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2007-03-15 17:03:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef APPBASLIB_HXX\n#define APPBASLIB_HXX\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SCRIPT_XSTORAGEBASEDLIBRARYCONTAINER_HPP_\n#include <com\/sun\/star\/script\/XStorageBasedLibraryContainer.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n\nclass BasicManager;\n\n\/** helper class which holds and manipulates a BasicManager\n*\/\nclass SfxBasicManagerHolder\n{\nprivate:\n BasicManager* mpBasicManager;\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >\n mxBasicContainer;\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >\n mxDialogContainer;\n\npublic:\n SfxBasicManagerHolder();\n\n enum ContainerType\n {\n SCRIPTS, DIALOGS\n };\n\n \/** returns <TRUE\/> if and only if the instance is currently bound to a non-<NULL\/>\n BasicManager.\n *\/\n bool isValid() const { return mpBasicManager != NULL; }\n\n \/** returns the BasicManager which this instance is currently bound to\n *\/\n BasicManager*\n get() const { return mpBasicManager; }\n\n \/** binds the instance to the given BasicManager\n *\/\n void reset( BasicManager* _pBasicManager );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >\n getLibraryContainer( ContainerType _eType );\n\n \/** determines whether any of our library containers is modified, i.e. returns <TRUE\/>\n in its isContainerModified call.\n *\/\n bool isAnyContainerModified() const;\n\n \/** calls the storeLibraries at both our script and basic library container\n *\/\n void storeAllLibraries();\n\n \/** calls the setStorage at all our XStorageBasedLibraryContainer.\n *\/\n void setStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage\n );\n\n \/** calls the storeLibrariesToStorage at all our XStorageBasedLibraryContainer.\n *\/\n void storeLibrariesToStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage\n );\n\n\n \/** checks if any modules in the SfxLibraryContainer exceed the binary\n limits.\n *\/\n sal_Bool LegacyPsswdBinaryLimitExceeded( ::com::sun::star::uno::Sequence< rtl::OUString >& sModules );\n\n\nprivate:\n void impl_releaseContainers();\n\n bool impl_getContainer(\n ContainerType _eType,\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >& _out_rxContainer );\n};\n\nclass SfxApplicationScriptLibraryContainer\n{\npublic:\n \/\/ Service\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();\n static ::rtl::OUString impl_getStaticImplementationName();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )\n throw( ::com::sun::star::uno::Exception );\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n\n};\n\nclass SfxApplicationDialogLibraryContainer\n{\npublic:\n \/\/ Service\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();\n static ::rtl::OUString impl_getStaticImplementationName();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )\n throw( ::com::sun::star::uno::Exception );\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n\n};\n\n#endif \/\/ APPBASLIB_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.288); FILE MERGED 2008\/04\/01 15:39:24 thb 1.4.288.3: #i85898# Stripping all external header guards 2008\/04\/01 12:40:50 thb 1.4.288.2: #i85898# Stripping all external header guards 2008\/03\/31 13:38:34 rt 1.4.288.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appbaslib.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef APPBASLIB_HXX\n#define APPBASLIB_HXX\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/script\/XStorageBasedLibraryContainer.hpp>\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n\nclass BasicManager;\n\n\/** helper class which holds and manipulates a BasicManager\n*\/\nclass SfxBasicManagerHolder\n{\nprivate:\n BasicManager* mpBasicManager;\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >\n mxBasicContainer;\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >\n mxDialogContainer;\n\npublic:\n SfxBasicManagerHolder();\n\n enum ContainerType\n {\n SCRIPTS, DIALOGS\n };\n\n \/** returns <TRUE\/> if and only if the instance is currently bound to a non-<NULL\/>\n BasicManager.\n *\/\n bool isValid() const { return mpBasicManager != NULL; }\n\n \/** returns the BasicManager which this instance is currently bound to\n *\/\n BasicManager*\n get() const { return mpBasicManager; }\n\n \/** binds the instance to the given BasicManager\n *\/\n void reset( BasicManager* _pBasicManager );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >\n getLibraryContainer( ContainerType _eType );\n\n \/** determines whether any of our library containers is modified, i.e. returns <TRUE\/>\n in its isContainerModified call.\n *\/\n bool isAnyContainerModified() const;\n\n \/** calls the storeLibraries at both our script and basic library container\n *\/\n void storeAllLibraries();\n\n \/** calls the setStorage at all our XStorageBasedLibraryContainer.\n *\/\n void setStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage\n );\n\n \/** calls the storeLibrariesToStorage at all our XStorageBasedLibraryContainer.\n *\/\n void storeLibrariesToStorage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage\n );\n\n\n \/** checks if any modules in the SfxLibraryContainer exceed the binary\n limits.\n *\/\n sal_Bool LegacyPsswdBinaryLimitExceeded( ::com::sun::star::uno::Sequence< rtl::OUString >& sModules );\n\n\nprivate:\n void impl_releaseContainers();\n\n bool impl_getContainer(\n ContainerType _eType,\n ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >& _out_rxContainer );\n};\n\nclass SfxApplicationScriptLibraryContainer\n{\npublic:\n \/\/ Service\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();\n static ::rtl::OUString impl_getStaticImplementationName();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )\n throw( ::com::sun::star::uno::Exception );\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n\n};\n\nclass SfxApplicationDialogLibraryContainer\n{\npublic:\n \/\/ Service\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();\n static ::rtl::OUString impl_getStaticImplementationName();\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )\n throw( ::com::sun::star::uno::Exception );\n static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory\n ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n\n};\n\n#endif \/\/ APPBASLIB_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <stdlib.h>\n#include <string.h>\n#include <zlib.h>\n\n#ifdef WIN32\n#include \"awdw32.h\"\n#else\n#include <unistd.h>\n#endif\n\n#include \"awd.h\"\n#include \"util.h\"\n#include \"awdlzma.h\"\n#include \"awdzlib.h\"\n\n#include \"Types.h\"\n#include \"LzmaEnc.h\"\n\n\nAWD::AWD(AWD_compression compression, awd_uint16 flags)\n{\n this->major_version = AWD_MAJOR_VERSION;\n this->minor_version = AWD_MINOR_VERSION;\n this->compression = compression;\n this->flags = flags;\n this->texture_blocks = new AWDBlockList();\n this->material_blocks = new AWDBlockList();\n this->mesh_data_blocks = new AWDBlockList();\n this->skeleton_blocks = new AWDBlockList();\n this->skelanim_blocks = new AWDBlockList();\n this->skelpose_blocks = new AWDBlockList();\n this->uvanim_blocks = new AWDBlockList();\n this->scene_blocks = new AWDBlockList();\n\n this->last_used_nsid = 0;\n this->last_used_baddr = 0;\n this->header_written = AWD_FALSE;\n}\n\n\nAWD::~AWD()\n{\n delete this->texture_blocks;\n delete this->material_blocks;\n delete this->mesh_data_blocks;\n delete this->skeleton_blocks;\n delete this->skelanim_blocks;\n delete this->skelpose_blocks;\n delete this->uvanim_blocks;\n delete this->scene_blocks;\n}\n\n\n\nvoid\nAWD::add_material(AWDSimpleMaterial *block)\n{\n this->material_blocks->append(block);\n}\n\n\nvoid\nAWD::add_namespace(AWDNamespace *block)\n{\n if (this->namespace_blocks->append(block)) {\n this->last_used_nsid++;\n block->set_handle(this->last_used_nsid);\n }\n}\n\n\nvoid\nAWD::add_texture(AWDTexture *block)\n{\n this->texture_blocks->append(block);\n}\n\n\nvoid\nAWD::add_mesh_data(AWDMeshData *block)\n{\n this->mesh_data_blocks->append(block);\n}\n\n\nvoid\nAWD::add_scene_block(AWDSceneBlock *block)\n{\n this->scene_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton(AWDSkeleton *block)\n{\n this->skeleton_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton_pose(AWDSkeletonPose *block)\n{\n this->skelpose_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton_anim(AWDSkeletonAnimation *block)\n{\n this->skelanim_blocks->append(block);\n}\n\n\nvoid\nAWD::add_uv_anim(AWDUVAnimation *block)\n{\n this->uvanim_blocks->append(block);\n}\n\n\n\nvoid\nAWD::write_header(int fd, awd_uint32 body_length)\n{\n awd_uint16 flags_be;\n\n \/\/ Convert to big-endian if necessary\n flags_be = UI16(this->flags);\n body_length = UI32(body_length);\n\n write(fd, \"AWD\", 3);\n write(fd, &this->major_version, sizeof(awd_uint8));\n write(fd, &this->minor_version, sizeof(awd_uint8));\n write(fd, &flags_be, sizeof(awd_uint16));\n write(fd, (awd_uint8*)&this->compression, sizeof(awd_uint8));\n write(fd, &body_length, sizeof(awd_uint32));\n}\n\nsize_t\nAWD::write_blocks(AWDBlockList *blocks, int fd)\n{\n size_t len;\n AWDBlock *block;\n AWDBlockIterator it(blocks);\n\n len = 0;\n while ((block = it.next()) != NULL) {\n \/\/block->add_dependencies(this);\n \/\/TODO: Check flags for wide boolean (hard-coded as false now)\n len += block->write_block(fd, AWD_FALSE, AWD_FALSE, ++this->last_used_baddr);\n }\n\n return len;\n}\n\n\nvoid\nAWD::flatten_scene(AWDSceneBlock *cur, AWDBlockList *flat_list)\n{\n AWDBlock *child;\n AWDBlockIterator *children;\n\n flat_list->append(cur);\n\n children = cur->child_iter();\n while ((child = children->next()) != NULL) {\n this->flatten_scene((AWDSceneBlock*)child, flat_list);\n }\n}\n\nsize_t\nAWD::write_scene(AWDBlockList *blocks, int fd)\n{\n AWDBlock *block;\n AWDBlockList *ordered;\n AWDBlockIterator it(blocks);\n\n ordered = new AWDBlockList();\n\n while ((block = it.next()) != NULL) {\n this->flatten_scene((AWDSceneBlock*)block, ordered);\n }\n\n return this->write_blocks(ordered, fd);\n}\n\n\nawd_uint32\nAWD::flush(int out_fd)\n{\n int tmp_fd;\n char *tmp_path;\n\n off_t tmp_len;\n awd_uint8 *tmp_buf;\n\n awd_uint8 *body_buf;\n awd_uint32 body_len;\n\n tmp_len = 0;\n tmp_fd = awdutil_mktmp(&tmp_path);\n if (tmp_fd < 0) {\n extern int errno;\n printf(\"Could not open temporary file necessary for writing, errno=%d\\n\", errno);\n return AWD_FALSE;\n }\n\n tmp_len += this->write_blocks(this->skeleton_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->skelpose_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->skelanim_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->texture_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->material_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->mesh_data_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->uvanim_blocks, tmp_fd);\n tmp_len += this->write_scene(this->scene_blocks, tmp_fd);\n\n tmp_buf = (awd_uint8 *) malloc(tmp_len);\n\tlseek(tmp_fd, 0, SEEK_SET);\n read(tmp_fd, tmp_buf, tmp_len);\n\n \/\/ Temp file no longer needed\n close(tmp_fd);\n unlink((const char *)tmp_path);\n\n\n if (this->compression == UNCOMPRESSED) {\n \/\/ Uncompressed, so output should be the exact\n \/\/ same data that was in the temporary file\n body_len = tmp_len;\n body_buf = tmp_buf;\n }\n else if (this->compression == DEFLATE) {\n int stat;\n z_streamp zstrm;\n int zlib_len;\n awd_uint8 *zlib_buf;\n bool done;\n\n zlib_len = tmp_len;\n zlib_buf = (awd_uint8*)malloc(zlib_len);\n\n zstrm = (z_streamp)malloc(sizeof(z_stream_s));\n zstrm->zalloc = awd_zalloc;\n zstrm->zfree = awd_zfree;\n zstrm->opaque = NULL;\n zstrm->next_in = tmp_buf;\n zstrm->avail_in = tmp_len;\n zstrm->next_out = zlib_buf;\n zstrm->avail_out = zlib_len;\n\n stat = deflateInit(zstrm, 9);\n\n done = false;\n while (!done) {\n stat = deflate(zstrm, Z_NO_FLUSH);\n\n switch (stat) {\n case Z_STREAM_END:\n case Z_BUF_ERROR:\n done = true;\n break;\n }\n }\n\n deflate(zstrm, Z_FINISH);\n deflateEnd(zstrm);\n\n body_len = zstrm->total_out;\n body_buf = (awd_uint8*)malloc(sizeof(body_len));\n memcpy(body_buf, zlib_buf, body_len);\n\n free(zlib_buf);\n }\n else if (this->compression == LZMA) {\n Byte *lzma_buf;\n SizeT lzma_len, props_len;\n CLzmaEncProps props;\n ISzAlloc alloc;\n Byte *props_buf;\n long tmp_len_bo;\n\n \/\/ Create allocation structure. LZMA library uses\n \/\/ these functions for memory management. They are\n \/\/ defined in awdlzma.c as simple wrappers for \n \/\/ malloc() and free().\n alloc.Alloc = &awd_SzAlloc;\n alloc.Free = &awd_SzFree;\n\n lzma_len = tmp_len;\n lzma_buf = (Byte *)malloc(tmp_len);\n props_len = sizeof(CLzmaEncProps);\n props_buf = (Byte *)malloc(props_len);\n\n LzmaEncProps_Init(&props);\n props.algo = 1;\n props.level = 9;\n\n LzmaEncode(lzma_buf, &lzma_len, tmp_buf, tmp_len,\n &props, props_buf, &props_len, 0, NULL, &alloc, &alloc);\n\n \/\/ Body length is the length of the actual\n \/\/ compressed body + size of props and an integer\n \/\/ definining the uncompressed length (see below)\n body_len = (awd_uint32)lzma_len + (awd_uint32)props_len + sizeof(awd_uint32);\n\n \/\/ Create new buffer containing LZMA props, length\n \/\/ of uncompressed body and the actual body data\n \/\/ concatenated together.\n tmp_len_bo = UI32(tmp_len);\n body_buf = (awd_uint8*)malloc(body_len);\n memcpy(body_buf, props_buf, props_len);\n memcpy(body_buf+props_len, &tmp_len_bo, sizeof(awd_uint32));\n memcpy(body_buf+props_len+sizeof(awd_uint32), lzma_buf, lzma_len);\n }\n\n\n \/\/ Write header and then body from possibly\n \/\/ compressed buffer\n if (this->header_written == AWD_FALSE) {\n this->header_written = AWD_TRUE;\n this->write_header(out_fd, body_len);\n }\n\n write(out_fd, body_buf, body_len);\n\n return AWD_TRUE;\n}\n\n\n<commit_msg>Fixed libawd DEFLATE memory bug (incorrect size in malloc()).<commit_after>#include <cstdio>\n#include <stdlib.h>\n#include <string.h>\n#include <zlib.h>\n\n#ifdef WIN32\n#include \"awdw32.h\"\n#else\n#include <unistd.h>\n#endif\n\n#include \"awd.h\"\n#include \"util.h\"\n#include \"awdlzma.h\"\n#include \"awdzlib.h\"\n\n#include \"Types.h\"\n#include \"LzmaEnc.h\"\n\n\nAWD::AWD(AWD_compression compression, awd_uint16 flags)\n{\n this->major_version = AWD_MAJOR_VERSION;\n this->minor_version = AWD_MINOR_VERSION;\n this->compression = compression;\n this->flags = flags;\n this->texture_blocks = new AWDBlockList();\n this->material_blocks = new AWDBlockList();\n this->mesh_data_blocks = new AWDBlockList();\n this->skeleton_blocks = new AWDBlockList();\n this->skelanim_blocks = new AWDBlockList();\n this->skelpose_blocks = new AWDBlockList();\n this->uvanim_blocks = new AWDBlockList();\n this->scene_blocks = new AWDBlockList();\n\n this->last_used_nsid = 0;\n this->last_used_baddr = 0;\n this->header_written = AWD_FALSE;\n}\n\n\nAWD::~AWD()\n{\n delete this->texture_blocks;\n delete this->material_blocks;\n delete this->mesh_data_blocks;\n delete this->skeleton_blocks;\n delete this->skelanim_blocks;\n delete this->skelpose_blocks;\n delete this->uvanim_blocks;\n delete this->scene_blocks;\n}\n\n\n\nvoid\nAWD::add_material(AWDSimpleMaterial *block)\n{\n this->material_blocks->append(block);\n}\n\n\nvoid\nAWD::add_namespace(AWDNamespace *block)\n{\n if (this->namespace_blocks->append(block)) {\n this->last_used_nsid++;\n block->set_handle(this->last_used_nsid);\n }\n}\n\n\nvoid\nAWD::add_texture(AWDTexture *block)\n{\n this->texture_blocks->append(block);\n}\n\n\nvoid\nAWD::add_mesh_data(AWDMeshData *block)\n{\n this->mesh_data_blocks->append(block);\n}\n\n\nvoid\nAWD::add_scene_block(AWDSceneBlock *block)\n{\n this->scene_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton(AWDSkeleton *block)\n{\n this->skeleton_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton_pose(AWDSkeletonPose *block)\n{\n this->skelpose_blocks->append(block);\n}\n\n\nvoid\nAWD::add_skeleton_anim(AWDSkeletonAnimation *block)\n{\n this->skelanim_blocks->append(block);\n}\n\n\nvoid\nAWD::add_uv_anim(AWDUVAnimation *block)\n{\n this->uvanim_blocks->append(block);\n}\n\n\n\nvoid\nAWD::write_header(int fd, awd_uint32 body_length)\n{\n awd_uint16 flags_be;\n\n \/\/ Convert to big-endian if necessary\n flags_be = UI16(this->flags);\n body_length = UI32(body_length);\n\n write(fd, \"AWD\", 3);\n write(fd, &this->major_version, sizeof(awd_uint8));\n write(fd, &this->minor_version, sizeof(awd_uint8));\n write(fd, &flags_be, sizeof(awd_uint16));\n write(fd, (awd_uint8*)&this->compression, sizeof(awd_uint8));\n write(fd, &body_length, sizeof(awd_uint32));\n}\n\nsize_t\nAWD::write_blocks(AWDBlockList *blocks, int fd)\n{\n size_t len;\n AWDBlock *block;\n AWDBlockIterator it(blocks);\n\n len = 0;\n while ((block = it.next()) != NULL) {\n \/\/block->add_dependencies(this);\n \/\/TODO: Check flags for wide boolean (hard-coded as false now)\n len += block->write_block(fd, AWD_FALSE, AWD_FALSE, ++this->last_used_baddr);\n }\n\n return len;\n}\n\n\nvoid\nAWD::flatten_scene(AWDSceneBlock *cur, AWDBlockList *flat_list)\n{\n AWDBlock *child;\n AWDBlockIterator *children;\n\n flat_list->append(cur);\n\n children = cur->child_iter();\n while ((child = children->next()) != NULL) {\n this->flatten_scene((AWDSceneBlock*)child, flat_list);\n }\n}\n\nsize_t\nAWD::write_scene(AWDBlockList *blocks, int fd)\n{\n AWDBlock *block;\n AWDBlockList *ordered;\n AWDBlockIterator it(blocks);\n\n ordered = new AWDBlockList();\n\n while ((block = it.next()) != NULL) {\n this->flatten_scene((AWDSceneBlock*)block, ordered);\n }\n\n return this->write_blocks(ordered, fd);\n}\n\n\nawd_uint32\nAWD::flush(int out_fd)\n{\n int tmp_fd;\n char *tmp_path;\n\n off_t tmp_len;\n awd_uint8 *tmp_buf;\n\n awd_uint8 *body_buf;\n awd_uint32 body_len;\n\n tmp_len = 0;\n tmp_fd = awdutil_mktmp(&tmp_path);\n if (tmp_fd < 0) {\n extern int errno;\n printf(\"Could not open temporary file necessary for writing, errno=%d\\n\", errno);\n return AWD_FALSE;\n }\n\n tmp_len += this->write_blocks(this->skeleton_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->skelpose_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->skelanim_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->texture_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->material_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->mesh_data_blocks, tmp_fd);\n tmp_len += this->write_blocks(this->uvanim_blocks, tmp_fd);\n tmp_len += this->write_scene(this->scene_blocks, tmp_fd);\n\n tmp_buf = (awd_uint8 *) malloc(tmp_len);\n\tlseek(tmp_fd, 0, SEEK_SET);\n read(tmp_fd, tmp_buf, tmp_len);\n\n \/\/ Temp file no longer needed\n close(tmp_fd);\n unlink((const char *)tmp_path);\n\n\n if (this->compression == UNCOMPRESSED) {\n \/\/ Uncompressed, so output should be the exact\n \/\/ same data that was in the temporary file\n body_len = tmp_len;\n body_buf = tmp_buf;\n }\n else if (this->compression == DEFLATE) {\n int stat;\n z_streamp zstrm;\n int zlib_len;\n awd_uint8 *zlib_buf;\n bool done;\n\n zlib_len = tmp_len;\n zlib_buf = (awd_uint8*)malloc(zlib_len);\n\n zstrm = (z_streamp)malloc(sizeof(z_stream_s));\n zstrm->zalloc = awd_zalloc;\n zstrm->zfree = awd_zfree;\n zstrm->opaque = NULL;\n zstrm->next_in = tmp_buf;\n zstrm->avail_in = tmp_len;\n zstrm->next_out = zlib_buf;\n zstrm->avail_out = zlib_len;\n\n stat = deflateInit(zstrm, 9);\n\n done = false;\n while (!done) {\n stat = deflate(zstrm, Z_NO_FLUSH);\n\n switch (stat) {\n case Z_STREAM_END:\n case Z_BUF_ERROR:\n done = true;\n break;\n }\n }\n\n deflate(zstrm, Z_FINISH);\n deflateEnd(zstrm);\n\n body_len = zstrm->total_out;\n body_buf = (awd_uint8*)malloc(body_len);\n memcpy(body_buf, zlib_buf, body_len);\n\n free(zlib_buf);\n free(zstrm);\n }\n else if (this->compression == LZMA) {\n Byte *lzma_buf;\n SizeT lzma_len, props_len;\n CLzmaEncProps props;\n ISzAlloc alloc;\n Byte *props_buf;\n long tmp_len_bo;\n\n \/\/ Create allocation structure. LZMA library uses\n \/\/ these functions for memory management. They are\n \/\/ defined in awdlzma.c as simple wrappers for \n \/\/ malloc() and free().\n alloc.Alloc = &awd_SzAlloc;\n alloc.Free = &awd_SzFree;\n\n lzma_len = tmp_len;\n lzma_buf = (Byte *)malloc(tmp_len);\n props_len = sizeof(CLzmaEncProps);\n props_buf = (Byte *)malloc(props_len);\n\n LzmaEncProps_Init(&props);\n props.algo = 1;\n props.level = 9;\n\n LzmaEncode(lzma_buf, &lzma_len, tmp_buf, tmp_len,\n &props, props_buf, &props_len, 0, NULL, &alloc, &alloc);\n\n \/\/ Body length is the length of the actual\n \/\/ compressed body + size of props and an integer\n \/\/ definining the uncompressed length (see below)\n body_len = (awd_uint32)lzma_len + (awd_uint32)props_len + sizeof(awd_uint32);\n\n \/\/ Create new buffer containing LZMA props, length\n \/\/ of uncompressed body and the actual body data\n \/\/ concatenated together.\n tmp_len_bo = UI32(tmp_len);\n body_buf = (awd_uint8*)malloc(body_len);\n memcpy(body_buf, props_buf, props_len);\n memcpy(body_buf+props_len, &tmp_len_bo, sizeof(awd_uint32));\n memcpy(body_buf+props_len+sizeof(awd_uint32), lzma_buf, lzma_len);\n }\n\n\n \/\/ Write header and then body from possibly\n \/\/ compressed buffer\n if (this->header_written == AWD_FALSE) {\n this->header_written = AWD_TRUE;\n this->write_header(out_fd, body_len);\n }\n\n write(out_fd, body_buf, body_len);\n\n return AWD_TRUE;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ProgramProfile.h\"\n\nuint8_t ProgramProfile::programShouldAdvance() {\n return !programIsDone &&\n (PHASE_SOAK == programStepPhase && \n (millis() - stepStartTs) \/ 60000 > program[currentStep].minutesAtTarget);\n}\n\nvoid ProgramProfile::stepInit(uint16_t currTemp) {\n stepStartTemperature = currTemp;\n programStepPhase = PHASE_RAMP;\n stepStartTs = millis();\n}\n\nuint8_t ProgramProfile::isMoreStepsLeft() {\n return currentStep + 1 < programStepsTotal;\n}\n\nuint8_t ProgramProfile::isTimeToRamp() {\n return PHASE_RAMP == programStepPhase && \n millis() - lastProgramInvocationTs > PROGRAM_IMVOCATION_INTERVAL;\n}\n\nuint16_t ProgramProfile::computeSetpoint() {\n return stepStartTemperature + (millis() - stepStartTs) \/ 60000 * program[currentStep].rampDegreesPerMinute;\n}\n\nuint8_t ProgramProfile::isTargetSetpointReached(uint16_t currTemp) {\n return currTemp >= program[currentStep].targetTemp;\n}\n\nvoid ProgramProfile::start(uint16_t currTemp) {\n currentStep = 0;\n stepInit(currTemp);\n}\n\nvoid ProgramProfile::compute(uint16_t currTemp) {\n if(programShouldAdvance()) {\n if(isMoreStepsLeft()) {\n currentStep = currentStep + 1;\n stepInit(currTemp);\n } else {\n programIsDone = 1;\n programDoneCallback();\n }\n } else if(isTimeToRamp()){\n if(isTargetSetpointReached(currTemp)) {\n programStepPhase = PHASE_SOAK;\n stepStartTs = millis();\n } else {\n uint16_t newSetpoint = computeSetpoint();\n setpointCallback(newSetpoint);\n }\n } \n lastProgramInvocationTs = millis();\n}\n\n\/**\n5°\/h iki 120 \nprie 120 30min\nišjungti\n**\/\n<commit_msg>Fix perefix<commit_after>#include \"ProgramProfile.h\"\n\nuint8_t ProgramProfile::programShouldAdvance() {\n return !programIsDone &&\n (PHASE_SOAK == programStepPhase && \n (millis() - stepStartTs) \/ 60000 > program[currentStep].minutesAtTarget);\n}\n\nvoid ProgramProfile::stepInit(uint16_t currTemp) {\n stepStartTemperature = currTemp;\n programStepPhase = PHASE_RAMP;\n stepStartTs = millis();\n lastProgramInvocationTs = millis();\n}\n\nuint8_t ProgramProfile::isMoreStepsLeft() {\n return currentStep + 1 < programStepsTotal;\n}\n\nuint8_t ProgramProfile::isTimeToRamp() {\n return PHASE_RAMP == programStepPhase && \n millis() - lastProgramInvocationTs > PROGRAM_IMVOCATION_INTERVAL;\n}\n\nuint16_t ProgramProfile::computeSetpoint() {\n return stepStartTemperature + (millis() - stepStartTs) \/ 60000 * program[currentStep].rampDegreesPerMinute;\n}\n\nuint8_t ProgramProfile::isTargetSetpointReached(uint16_t currTemp) {\n return currTemp >= program[currentStep].targetTemp;\n}\n\nvoid ProgramProfile::start(uint16_t currTemp) {\n currentStep = 0;\n programIsDone = 0;\n stepInit(currTemp);\n}\n\nvoid ProgramProfile::compute(uint16_t currTemp) {\n if(programShouldAdvance()) {\n if(isMoreStepsLeft()) {\n currentStep = currentStep + 1;\n stepInit(currTemp);\n } else {\n programIsDone = 1;\n programDoneCallback();\n }\n } else if(isTimeToRamp()){\n if(isTargetSetpointReached(currTemp)) {\n programStepPhase = PHASE_SOAK;\n stepStartTs = millis();\n } else {\n uint16_t newSetpoint = computeSetpoint();\n setpointCallback(newSetpoint);\n lastProgramInvocationTs = millis();\n }\n } \n}\n\n\/**\n5°\/h iki 120 \nprie 120 30min\nišjungti\n**\/\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <stdexcept>\n#include <string>\n#include <string_view>\n#include <vector>\n#include <optional>\n\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/fmt.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n namespace argv\n {\n inline namespace v2\n {\n class argv;\n using str = std::string_view;\n using str_array = std::vector<std::string_view>;\n\n struct desc : public std::string_view { using std::string_view::string_view; };\n struct arg_name : public std::string_view { using std::string_view::string_view; };\n enum mandatory { mandatory };\n template <typename T> struct dflt { dflt(T&& val) : value{std::move(val)} {} T value; explicit operator T() const { return value; } };\n dflt(const char*) -> dflt<str>;\n\n namespace detail\n {\n using cmd_line_iter = std::vector<const char*>::const_iterator;\n\n constexpr bool false_ = false;\n\n class option_base\n {\n public:\n option_base(argv& parent);\n virtual ~option_base() = default;\n\n virtual void add(cmd_line_iter& arg, cmd_line_iter last) = 0;\n virtual void add(std::string_view arg) = 0;\n std::string names() const noexcept;\n constexpr bool has_name() const noexcept { return short_name_ || !long_name_.empty(); }\n constexpr std::string_view description() const noexcept { return description_; }\n virtual std::string get_default() const noexcept = 0;\n virtual bool has_arg() const noexcept { return true; }\n virtual bool has_value() const noexcept = 0;\n virtual bool multiple_values() const noexcept = 0;\n virtual bool is_bool() const noexcept = 0;\n constexpr bool mandatory() const noexcept { return mandatory_; }\n\n constexpr char short_name() const noexcept { return short_name_; }\n constexpr std::string_view long_name() const noexcept { return long_name_; }\n constexpr std::string_view arg_name() const noexcept { return arg_name_; }\n\n protected:\n constexpr void use_arg(char short_name) noexcept { short_name_ = short_name; }\n constexpr void use_arg(const char* long_name) noexcept { long_name_ = long_name; }\n constexpr void use_arg(desc&& description) noexcept { description_ = std::move(description); }\n constexpr void use_arg(struct arg_name&& an) noexcept { arg_name_ = std::move(an); }\n constexpr void use_arg(enum mandatory&&) noexcept { mandatory_ = true; }\n\n private:\n char short_name_ = 0;\n std::string_view long_name_;\n std::string_view description_;\n std::string_view arg_name_{\"ARG\"};\n bool mandatory_ = false;\n\n }; \/\/ class option_base\n\n template <typename T> T to_value(std::string_view source) { return source; }\n \/\/ template <> inline const char* to_value<const char*>(std::string_view source) { return source; }\n \/\/ template <> inline string to_value<string>(std::string_view source) { return source; }\n template <> inline int to_value<int>(std::string_view source) { return std::stoi(std::string(source)); }\n template <> inline long to_value<long>(std::string_view source) { return std::stol(std::string(source)); }\n template <> inline unsigned long to_value<unsigned long>(std::string_view source) { return std::stoul(std::string(source)); }\n template <> inline double to_value<double>(std::string_view source) { return std::stod(std::string(source)); }\n template <> inline bool to_value<bool>(std::string_view source) { return std::stoi(std::string(source)); }\n\n template <typename T> std::string to_string(const T& source) noexcept { return std::to_string(source); }\n \/\/ template <> std::string to_string(const std::string& source) { return '\"' + source + '\"'; }\n template <> std::string to_string(const str& source) noexcept { return '\"' + std::string(source) + '\"'; }\n template <> std::string to_string(const str_array& source) noexcept { return '\"' + string::join(\"\\\" \\\"\", source) + '\"'; }\n\n class invalid_option_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n\n } \/\/ namespace detail\n\n \/\/ ----------------------------------------------------------------------\n\n template <typename T> class option : public detail::option_base\n {\n public:\n template <typename... Args> option(argv& parent, Args&&... args) : option_base(parent) { use_args(std::forward<Args>(args)...); }\n\n constexpr operator const T&() const { if (value_.has_value()) return *value_; else return default_; }\n constexpr const T& get() const { return static_cast<const T&>(*this); }\n constexpr const T* operator->() const { return &static_cast<const T&>(*this); }\n constexpr const T& operator*() const { return static_cast<const T&>(*this); }\n template <typename R> constexpr bool operator == (const R& rhs) const { return static_cast<const T&>(*this) == rhs; }\n template <typename R> constexpr bool operator != (const R& rhs) const { return !operator==(rhs); }\n std::string get_default() const noexcept override { return detail::to_string(default_); }\n bool has_arg() const noexcept override { return true; }\n bool has_value() const noexcept override { return value_.has_value(); }\n bool multiple_values() const noexcept override { return false; }\n\n bool is_bool() const noexcept override { if constexpr (std::is_same_v<T, bool>) return true; else return false; }\n\n void add(detail::cmd_line_iter& arg, detail::cmd_line_iter last) override\n {\n ++arg;\n if (arg == last)\n throw detail::invalid_option_value{\"requires argument\"};\n add(*arg);\n }\n\n void add(std::string_view arg) override { value_ = detail::to_value<T>(arg); }\n\n template <typename Z = T, typename = std::enable_if_t<!std::is_same_v<Z, bool>>> explicit operator bool() const\n {\n if constexpr (std::is_same_v<T, str>)\n return has_value() && !get().empty();\n else if constexpr (std::is_same_v<T, double>)\n return has_value();\n else\n static_assert(std::is_same_v<T, void>, \"operator bool not defined for this option type\");\n }\n\n protected:\n using detail::option_base::use_arg;\n constexpr void use_arg(dflt<T>&& def) { default_ = static_cast<T>(def); }\n\n private:\n std::optional<T> value_;\n T default_;\n\n template <typename Arg, typename... Args> void use_args(Arg&& arg, Args&&... args)\n {\n use_arg(std::forward<Arg>(arg));\n if constexpr (sizeof...(args) > 0)\n use_args(std::forward<Args>(args)...);\n }\n }; \/\/ class option<T>\n\n template <typename T> inline std::ostream& operator << (std::ostream& out, const option<T>& opt) { return out << opt.get(); }\n\n template <> void option<bool>::add(detail::cmd_line_iter& \/*arg*\/, detail::cmd_line_iter \/*last*\/) { value_ = true; }\n template <> bool option<bool>::has_arg() const noexcept { return false; }\n template <> constexpr option<bool>::operator const bool&() const { if (value_.has_value()) return *value_; return detail::false_; }\n template <> inline std::ostream& operator << (std::ostream& out, const option<bool>& opt) { return out << std::boolalpha << static_cast<const bool&>(opt); }\n\n template <> void option<str_array>::add(std::string_view arg) { if (!value_) value_ = str_array{arg}; else value_->push_back(arg); }\n template <> bool option<str_array>::multiple_values() const noexcept { return true; }\n\n template <typename T> using argument = option<T>;\n\n \/\/ ----------------------------------------------------------------------\n\n class show_help : public std::exception {};\n class errors : public std::exception {};\n\n class argv\n {\n public:\n using errors_t = std::vector<std::string>;\n enum class on_error { exit, raise, return_false };\n \/\/ returns true on success\n bool parse(int argc, const char* const argv[], on_error on_err = on_error::exit);\n\n constexpr auto argv0() const { return argv0_; }\n constexpr auto program_name() const { return prog_name_; }\n constexpr const errors_t& errors() const { return errors_; }\n void show_help(std::ostream& out) const;\n\n virtual ~argv() = default;\n\n protected:\n argv() = default;\n\n private:\n std::string_view argv0_;\n std::string_view prog_name_;\n std::vector<detail::option_base*> options_;\n std::vector<std::string_view> args_;\n errors_t errors_;\n\n option<bool> show_help_{*this, 'h', \"help\", desc{\"show this help screen\"}};\n\n void use(detail::cmd_line_iter& arg, detail::cmd_line_iter last);\n detail::option_base* find(char short_name);\n detail::option_base* find(std::string_view long_name);\n\n void register_option(detail::option_base* opt);\n friend class detail::option_base;\n friend std::ostream& operator<<(std::ostream& out, const argv& args);\n\n }; \/\/ class argv\n\n \/\/ ----------------------------------------------------------------------\n\n inline detail::option_base::option_base(argv& parent) { parent.register_option(this); }\n\n \/\/ ----------------------------------------------------------------------\n\n\n } \/\/ namespace v2\n } \/\/ namespace argv\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate <typename T> struct fmt::formatter<acmacs::argv::option<T>> : fmt::formatter<T> {\n template <typename FormatCtx> auto format(const acmacs::argv::option<T>& opt, FormatCtx& ctx) { return fmt::formatter<T>::format(*opt, ctx); }\n};\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>argv improvement<commit_after>#pragma once\n\n#include <stdexcept>\n#include <string>\n#include <string_view>\n#include <vector>\n#include <optional>\n\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/fmt.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n namespace argv\n {\n inline namespace v2\n {\n class argv;\n using str = std::string_view;\n using str_array = std::vector<std::string_view>;\n\n struct desc : public std::string_view { using std::string_view::string_view; };\n struct arg_name : public std::string_view { using std::string_view::string_view; };\n enum mandatory { mandatory };\n template <typename T> struct dflt { dflt(T&& val) : value{std::move(val)} {} T value; explicit operator T() const { return value; } };\n dflt(const char*) -> dflt<str>;\n\n namespace detail\n {\n using cmd_line_iter = std::vector<const char*>::const_iterator;\n\n constexpr bool false_ = false;\n\n class option_base\n {\n public:\n option_base(argv& parent);\n virtual ~option_base() = default;\n\n virtual void add(cmd_line_iter& arg, cmd_line_iter last) = 0;\n virtual void add(std::string_view arg) = 0;\n std::string names() const noexcept;\n constexpr bool has_name() const noexcept { return short_name_ || !long_name_.empty(); }\n constexpr std::string_view description() const noexcept { return description_; }\n virtual std::string get_default() const noexcept = 0;\n virtual bool has_arg() const noexcept { return true; }\n virtual bool has_value() const noexcept = 0;\n virtual bool multiple_values() const noexcept = 0;\n virtual bool is_bool() const noexcept = 0;\n constexpr bool mandatory() const noexcept { return mandatory_; }\n\n constexpr char short_name() const noexcept { return short_name_; }\n constexpr std::string_view long_name() const noexcept { return long_name_; }\n constexpr std::string_view arg_name() const noexcept { return arg_name_; }\n\n protected:\n constexpr void use_arg(char short_name) noexcept { short_name_ = short_name; }\n constexpr void use_arg(const char* long_name) noexcept { long_name_ = long_name; }\n constexpr void use_arg(desc&& description) noexcept { description_ = std::move(description); }\n constexpr void use_arg(struct arg_name&& an) noexcept { arg_name_ = std::move(an); }\n constexpr void use_arg(enum mandatory&&) noexcept { mandatory_ = true; }\n\n private:\n char short_name_ = 0;\n std::string_view long_name_;\n std::string_view description_;\n std::string_view arg_name_{\"ARG\"};\n bool mandatory_ = false;\n\n }; \/\/ class option_base\n\n template <typename T> T to_value(std::string_view source)\n {\n if constexpr (std::is_same_v<T, bool>)\n return std::stoi(std::string(source));\n else if constexpr (std::is_arithmetic_v<T>)\n return ::string::from_chars<T>(source);\n else\n return source;\n }\n\n template <typename T> std::string to_string(const T& source) noexcept { return std::to_string(source); }\n \/\/ template <> std::string to_string(const std::string& source) { return '\"' + source + '\"'; }\n template <> std::string to_string(const str& source) noexcept { return fmt::format(\"\\\"{}\\\"\", source); }\n template <> std::string to_string(const str_array& source) noexcept { return fmt::format(\"\\\"{}\\\"\", string::join(\"\\\" \\\"\", source)); }\n\n class invalid_option_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n\n } \/\/ namespace detail\n\n \/\/ ----------------------------------------------------------------------\n\n template <typename T> class option : public detail::option_base\n {\n public:\n template <typename... Args> option(argv& parent, Args&&... args) : option_base(parent) { use_args(std::forward<Args>(args)...); }\n\n constexpr operator const T&() const { if (value_.has_value()) return *value_; else return default_; }\n constexpr const T& get() const { return static_cast<const T&>(*this); }\n constexpr const T* operator->() const { return &static_cast<const T&>(*this); }\n constexpr const T& operator*() const { return static_cast<const T&>(*this); }\n template <typename R> constexpr bool operator == (const R& rhs) const { return static_cast<const T&>(*this) == rhs; }\n template <typename R> constexpr bool operator != (const R& rhs) const { return !operator==(rhs); }\n std::string get_default() const noexcept override { return detail::to_string(default_); }\n bool has_arg() const noexcept override { return true; }\n bool has_value() const noexcept override { return value_.has_value(); }\n bool multiple_values() const noexcept override { return false; }\n\n bool is_bool() const noexcept override { if constexpr (std::is_same_v<T, bool>) return true; else return false; }\n\n void add(detail::cmd_line_iter& arg, detail::cmd_line_iter last) override\n {\n ++arg;\n if (arg == last)\n throw detail::invalid_option_value{\"requires argument\"};\n add(*arg);\n }\n\n void add(std::string_view arg) override { value_ = detail::to_value<T>(arg); }\n\n template <typename Z = T, typename = std::enable_if_t<!std::is_same_v<Z, bool>>> explicit operator bool() const\n {\n if constexpr (std::is_same_v<T, str>)\n return has_value() && !get().empty();\n else if constexpr (std::is_same_v<T, double>)\n return has_value();\n else\n static_assert(std::is_same_v<T, void>, \"operator bool not defined for this option type\");\n }\n\n protected:\n using detail::option_base::use_arg;\n constexpr void use_arg(dflt<T>&& def) { default_ = static_cast<T>(def); }\n\n private:\n std::optional<T> value_;\n T default_;\n\n template <typename Arg, typename... Args> void use_args(Arg&& arg, Args&&... args)\n {\n use_arg(std::forward<Arg>(arg));\n if constexpr (sizeof...(args) > 0)\n use_args(std::forward<Args>(args)...);\n }\n }; \/\/ class option<T>\n\n template <typename T> inline std::ostream& operator << (std::ostream& out, const option<T>& opt) { return out << opt.get(); }\n\n template <> void option<bool>::add(detail::cmd_line_iter& \/*arg*\/, detail::cmd_line_iter \/*last*\/) { value_ = true; }\n template <> bool option<bool>::has_arg() const noexcept { return false; }\n template <> constexpr option<bool>::operator const bool&() const { if (value_.has_value()) return *value_; return detail::false_; }\n template <> inline std::ostream& operator << (std::ostream& out, const option<bool>& opt) { return out << std::boolalpha << static_cast<const bool&>(opt); }\n\n template <> void option<str_array>::add(std::string_view arg) { if (!value_) value_ = str_array{arg}; else value_->push_back(arg); }\n template <> bool option<str_array>::multiple_values() const noexcept { return true; }\n\n template <typename T> using argument = option<T>;\n\n \/\/ ----------------------------------------------------------------------\n\n class show_help : public std::exception {};\n class errors : public std::exception {};\n\n class argv\n {\n public:\n using errors_t = std::vector<std::string>;\n enum class on_error { exit, raise, return_false };\n \/\/ returns true on success\n bool parse(int argc, const char* const argv[], on_error on_err = on_error::exit);\n\n constexpr auto argv0() const { return argv0_; }\n constexpr auto program_name() const { return prog_name_; }\n constexpr const errors_t& errors() const { return errors_; }\n void show_help(std::ostream& out) const;\n\n virtual ~argv() = default;\n\n protected:\n argv() = default;\n\n private:\n std::string_view argv0_;\n std::string_view prog_name_;\n std::vector<detail::option_base*> options_;\n std::vector<std::string_view> args_;\n errors_t errors_;\n\n option<bool> show_help_{*this, 'h', \"help\", desc{\"show this help screen\"}};\n\n void use(detail::cmd_line_iter& arg, detail::cmd_line_iter last);\n detail::option_base* find(char short_name);\n detail::option_base* find(std::string_view long_name);\n\n void register_option(detail::option_base* opt);\n friend class detail::option_base;\n friend std::ostream& operator<<(std::ostream& out, const argv& args);\n\n }; \/\/ class argv\n\n \/\/ ----------------------------------------------------------------------\n\n inline detail::option_base::option_base(argv& parent) { parent.register_option(this); }\n\n \/\/ ----------------------------------------------------------------------\n\n\n } \/\/ namespace v2\n } \/\/ namespace argv\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate <typename T> struct fmt::formatter<acmacs::argv::option<T>> : fmt::formatter<T> {\n template <typename FormatCtx> auto format(const acmacs::argv::option<T>& opt, FormatCtx& ctx) { return fmt::formatter<T>::format(*opt, ctx); }\n};\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/*\n dirservconfigpage.cpp\n\n This file is part of kleopatra\n Copyright (c) 2004 Klar�vdalens Datakonsult AB\n\n Libkleopatra is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License,\n version 2, as published by the Free Software Foundation.\n\n Libkleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"dirservconfigpage.h\"\n#include \"directoryserviceswidget.h\"\n\n#include <kleo\/cryptobackendfactory.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <knuminput.h>\n#include <kdialog.h>\n#include <kcomponentdata.h> \n\n#include <khbox.h>\n#include <QLabel>\n#include <qdatetimeedit.h>\n#include <QCheckBox>\n#include <QLayout>\n\/\/Added by qt3to4:\n#include <QVBoxLayout>\n\n#include <kdemacros.h>\n\n#if 0 \/\/ disabled, since it is apparently confusing\n\/\/ For sync'ing kabldaprc\nclass KABSynchronizer\n{\npublic:\n KABSynchronizer()\n : mConfig( \"kabldaprc\" ) {\n mConfig.setGroup( \"LDAP\" );\n }\n\n KUrl::List readCurrentList() const {\n\n KUrl::List lst;\n \/\/ stolen from kabc\/ldapclient.cpp\n const uint numHosts = mConfig.readEntry( \"NumSelectedHosts\" );\n for ( uint j = 0; j < numHosts; j++ ) {\n const QString num = QString::number( j );\n\n KUrl url;\n url.setProtocol( \"ldap\" );\n url.setPath( \"\/\" ); \/\/ workaround KUrl parsing bug\n const QString host = mConfig.readEntry( QString( \"SelectedHost\" ) + num ).trimmed();\n url.setHost( host );\n\n const int port = mConfig.readEntry( QString( \"SelectedPort\" ) + num );\n if ( port != 0 )\n url.setPort( port );\n\n const QString base = mConfig.readEntry( QString( \"SelectedBase\" ) + num ).trimmed();\n url.setQuery( base );\n\n const QString bindDN = mConfig.readEntry( QString( \"SelectedBind\" ) + num ).trimmed();\n url.setUser( bindDN );\n\n const QString pwdBindDN = mConfig.readEntry( QString( \"SelectedPwdBind\" ) + num ).trimmed();\n url.setPass( pwdBindDN );\n lst.append( url );\n }\n return lst;\n }\n\n void writeList( const KUrl::List& lst ) {\n\n mConfig.writeEntry( \"NumSelectedHosts\", lst.count() );\n\n KUrl::List::const_iterator it = lst.begin();\n KUrl::List::const_iterator end = lst.end();\n unsigned j = 0;\n for( ; it != end; ++it, ++j ) {\n const QString num = QString::number( j );\n KUrl url = *it;\n\n Q_ASSERT( url.protocol() == \"ldap\" );\n mConfig.writeEntry( QString( \"SelectedHost\" ) + num, url.host() );\n mConfig.writeEntry( QString( \"SelectedPort\" ) + num, url.port() );\n\n \/\/ KUrl automatically encoded the query (e.g. for spaces inside it),\n \/\/ so decode it before writing it out\n const QString base = KUrl::decode_string( url.query().mid(1) );\n mConfig.writeEntry( QString( \"SelectedBase\" ) + num, base );\n mConfig.writeEntry( QString( \"SelectedBind\" ) + num, url.user() );\n mConfig.writeEntry( QString( \"SelectedPwdBind\" ) + num, url.pass() );\n }\n mConfig.sync();\n }\n\nprivate:\n KConfig mConfig;\n};\n\n#endif\n\nstatic const char s_dirserv_componentName[] = \"dirmngr\";\nstatic const char s_dirserv_groupName[] = \"LDAP\";\nstatic const char s_dirserv_entryName[] = \"LDAP Server\";\n\nstatic const char s_timeout_componentName[] = \"dirmngr\";\nstatic const char s_timeout_groupName[] = \"LDAP\";\nstatic const char s_timeout_entryName[] = \"ldaptimeout\";\n\nstatic const char s_maxitems_componentName[] = \"dirmngr\";\nstatic const char s_maxitems_groupName[] = \"LDAP\";\nstatic const char s_maxitems_entryName[] = \"max-replies\";\n\nstatic const char s_addnewservers_componentName[] = \"dirmngr\";\nstatic const char s_addnewservers_groupName[] = \"LDAP\";\nstatic const char s_addnewservers_entryName[] = \"add-servers\";\n\nDirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QStringList &args )\n : KCModule( instance, parent, args )\n{\n mConfig = Kleo::CryptoBackendFactory::instance()->config();\n QVBoxLayout* lay = new QVBoxLayout( this );\n lay->setSpacing( KDialog::spacingHint() );\n lay->setMargin( 0 );\n Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,\n Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );\n mWidget = new Kleo::DirectoryServicesWidget( entry, this );\n lay->addWidget( mWidget );\n connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) );\n\n \/\/ LDAP timeout\n KHBox* box = new KHBox( this );\n box->setSpacing( KDialog::spacingHint() );\n lay->addWidget( box );\n QLabel* label = new QLabel( i18n( \"LDAP &timeout (minutes:seconds):\" ), box );\n mTimeout = new QTimeEdit( box );\n mTimeout->setDisplayFormat( \"mm:ss\" );\n connect( mTimeout, SIGNAL( valueChanged( const QTime& ) ), this, SLOT( slotChanged() ) );\n label->setBuddy( mTimeout );\n QWidget* stretch = new QWidget( box );\n box->setStretchFactor( stretch, 2 );\n\n \/\/ Max number of items returned by queries\n box = new KHBox( this );\n box->setSpacing( KDialog::spacingHint() );\n lay->addWidget( box );\n mMaxItems = new KIntNumInput( box );\n mMaxItems->setLabel( i18n( \"&Maximum number of items returned by query:\" ), Qt::AlignLeft | Qt::AlignVCenter );\n mMaxItems->setMinimum( 0 );\n connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );\n stretch = new QWidget( box );\n box->setStretchFactor( stretch, 2 );\n\n#ifdef NOT_USEFUL_CURRENTLY\n mAddNewServersCB = new QCheckBox( i18n( \"Automatically add &new servers discovered in CRL distribution points\" ), this );\n connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) );\n lay->addWidget( mAddNewServersCB );\n#endif\n\n#ifndef HAVE_UNBROKEN_KCMULTIDIALOG\n load();\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::load()\n{\n mWidget->load();\n\n mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );\n if ( mTimeoutConfigEntry ) {\n QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );\n \/\/kDebug() << \"timeout:\" << mTimeoutConfigEntry->uintValue() << \" -> \" << time << endl;\n mTimeout->setTime( time );\n }\n\n mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );\n if ( mMaxItemsConfigEntry ) {\n mMaxItems->blockSignals( true ); \/\/ KNumInput emits valueChanged from setValue!\n mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );\n mMaxItems->blockSignals( false );\n }\n\n#ifdef NOT_USEFUL_CURRENTLY\n mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );\n if ( mAddNewServersConfigEntry ) {\n mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );\n }\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::save()\n{\n mWidget->save();\n\n QTime time( mTimeout->time() );\n unsigned int timeout = time.minute() * 60 + time.second();\n if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )\n mTimeoutConfigEntry->setUIntValue( timeout );\n if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )\n mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );\n#ifdef NOT_USEFUL_CURRENTLY\n if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )\n mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );\n#endif\n\n mConfig->sync( true );\n\n#if 0\n \/\/ Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook\n KABSynchronizer sync;\n const KUrl::List toAdd = mWidget->urlList();\n KUrl::List currentList = sync.readCurrentList();\n\n KUrl::List::const_iterator it = toAdd.begin();\n KUrl::List::const_iterator end = toAdd.end();\n for( ; it != end; ++it ) {\n \/\/ check if the URL is already in currentList\n if ( currentList.find( *it ) == currentList.end() )\n \/\/ if not, add it\n currentList.append( *it );\n }\n sync.writeList( currentList );\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::defaults()\n{\n mWidget->defaults();\n if ( mTimeoutConfigEntry )\n mTimeoutConfigEntry->resetToDefault();\n if ( mMaxItemsConfigEntry )\n mMaxItemsConfigEntry->resetToDefault();\n#ifdef NOT_USEFUL_CURRENTLY\n if ( mAddNewServersConfigEntry )\n mAddNewServersConfigEntry->resetToDefault();\n#endif\n load();\n}\n\nextern \"C\"\n{\n KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QStringList &args=QStringList() )\n {\n DirectoryServicesConfigurationPage *page =\n new DirectoryServicesConfigurationPage( KComponentData( \"kleopatra\" ), parent, args );\n page->setObjectName( \"kleopatra_config_dirserv\" );\n return page;\n }\n}\n\n\/\/ kdelibs-3.2 didn't have the changed signal in KCModule...\nvoid DirectoryServicesConfigurationPage::slotChanged()\n{\n emit changed(true);\n}\n\n\n\/\/ Find config entry for ldap servers. Implements runtime checks on the configuration option.\nKleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,\n const char* groupName,\n const char* entryName,\n Kleo::CryptoConfigEntry::ArgType argType,\n bool isList )\n{\n Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );\n if ( !entry ) {\n KMessageBox::error( this, i18n( \"Backend error: gpgconf does not seem to know the entry for %1\/%2\/%3\", componentName, groupName, entryName ) );\n return 0;\n }\n if( entry->argType() != argType || entry->isList() != isList ) {\n KMessageBox::error( this, i18n( \"Backend error: gpgconf has wrong type for %1\/%2\/%3: %4 %5\", componentName, groupName, entryName, entry->argType(), entry->isList() ) );\n return 0;\n }\n return entry;\n}\n\n#include \"dirservconfigpage.moc\"\n<commit_msg>Fix signal\/slot<commit_after>\/*\n dirservconfigpage.cpp\n\n This file is part of kleopatra\n Copyright (c) 2004 Klar�vdalens Datakonsult AB\n\n Libkleopatra is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License,\n version 2, as published by the Free Software Foundation.\n\n Libkleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"dirservconfigpage.h\"\n#include \"directoryserviceswidget.h\"\n\n#include <kleo\/cryptobackendfactory.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <knuminput.h>\n#include <kdialog.h>\n#include <kcomponentdata.h> \n\n#include <khbox.h>\n#include <QLabel>\n#include <qdatetimeedit.h>\n#include <QCheckBox>\n#include <QLayout>\n\/\/Added by qt3to4:\n#include <QVBoxLayout>\n\n#include <kdemacros.h>\n\n#if 0 \/\/ disabled, since it is apparently confusing\n\/\/ For sync'ing kabldaprc\nclass KABSynchronizer\n{\npublic:\n KABSynchronizer()\n : mConfig( \"kabldaprc\" ) {\n mConfig.setGroup( \"LDAP\" );\n }\n\n KUrl::List readCurrentList() const {\n\n KUrl::List lst;\n \/\/ stolen from kabc\/ldapclient.cpp\n const uint numHosts = mConfig.readEntry( \"NumSelectedHosts\" );\n for ( uint j = 0; j < numHosts; j++ ) {\n const QString num = QString::number( j );\n\n KUrl url;\n url.setProtocol( \"ldap\" );\n url.setPath( \"\/\" ); \/\/ workaround KUrl parsing bug\n const QString host = mConfig.readEntry( QString( \"SelectedHost\" ) + num ).trimmed();\n url.setHost( host );\n\n const int port = mConfig.readEntry( QString( \"SelectedPort\" ) + num );\n if ( port != 0 )\n url.setPort( port );\n\n const QString base = mConfig.readEntry( QString( \"SelectedBase\" ) + num ).trimmed();\n url.setQuery( base );\n\n const QString bindDN = mConfig.readEntry( QString( \"SelectedBind\" ) + num ).trimmed();\n url.setUser( bindDN );\n\n const QString pwdBindDN = mConfig.readEntry( QString( \"SelectedPwdBind\" ) + num ).trimmed();\n url.setPass( pwdBindDN );\n lst.append( url );\n }\n return lst;\n }\n\n void writeList( const KUrl::List& lst ) {\n\n mConfig.writeEntry( \"NumSelectedHosts\", lst.count() );\n\n KUrl::List::const_iterator it = lst.begin();\n KUrl::List::const_iterator end = lst.end();\n unsigned j = 0;\n for( ; it != end; ++it, ++j ) {\n const QString num = QString::number( j );\n KUrl url = *it;\n\n Q_ASSERT( url.protocol() == \"ldap\" );\n mConfig.writeEntry( QString( \"SelectedHost\" ) + num, url.host() );\n mConfig.writeEntry( QString( \"SelectedPort\" ) + num, url.port() );\n\n \/\/ KUrl automatically encoded the query (e.g. for spaces inside it),\n \/\/ so decode it before writing it out\n const QString base = KUrl::decode_string( url.query().mid(1) );\n mConfig.writeEntry( QString( \"SelectedBase\" ) + num, base );\n mConfig.writeEntry( QString( \"SelectedBind\" ) + num, url.user() );\n mConfig.writeEntry( QString( \"SelectedPwdBind\" ) + num, url.pass() );\n }\n mConfig.sync();\n }\n\nprivate:\n KConfig mConfig;\n};\n\n#endif\n\nstatic const char s_dirserv_componentName[] = \"dirmngr\";\nstatic const char s_dirserv_groupName[] = \"LDAP\";\nstatic const char s_dirserv_entryName[] = \"LDAP Server\";\n\nstatic const char s_timeout_componentName[] = \"dirmngr\";\nstatic const char s_timeout_groupName[] = \"LDAP\";\nstatic const char s_timeout_entryName[] = \"ldaptimeout\";\n\nstatic const char s_maxitems_componentName[] = \"dirmngr\";\nstatic const char s_maxitems_groupName[] = \"LDAP\";\nstatic const char s_maxitems_entryName[] = \"max-replies\";\n\nstatic const char s_addnewservers_componentName[] = \"dirmngr\";\nstatic const char s_addnewservers_groupName[] = \"LDAP\";\nstatic const char s_addnewservers_entryName[] = \"add-servers\";\n\nDirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QStringList &args )\n : KCModule( instance, parent, args )\n{\n mConfig = Kleo::CryptoBackendFactory::instance()->config();\n QVBoxLayout* lay = new QVBoxLayout( this );\n lay->setSpacing( KDialog::spacingHint() );\n lay->setMargin( 0 );\n Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,\n Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );\n mWidget = new Kleo::DirectoryServicesWidget( entry, this );\n lay->addWidget( mWidget );\n connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) );\n\n \/\/ LDAP timeout\n KHBox* box = new KHBox( this );\n box->setSpacing( KDialog::spacingHint() );\n lay->addWidget( box );\n QLabel* label = new QLabel( i18n( \"LDAP &timeout (minutes:seconds):\" ), box );\n mTimeout = new QTimeEdit( box );\n mTimeout->setDisplayFormat( \"mm:ss\" );\n connect( mTimeout, SIGNAL(timeChanged(const QTime&)), this, SLOT(slotChanged()) );\n label->setBuddy( mTimeout );\n QWidget* stretch = new QWidget( box );\n box->setStretchFactor( stretch, 2 );\n\n \/\/ Max number of items returned by queries\n box = new KHBox( this );\n box->setSpacing( KDialog::spacingHint() );\n lay->addWidget( box );\n mMaxItems = new KIntNumInput( box );\n mMaxItems->setLabel( i18n( \"&Maximum number of items returned by query:\" ), Qt::AlignLeft | Qt::AlignVCenter );\n mMaxItems->setMinimum( 0 );\n connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );\n stretch = new QWidget( box );\n box->setStretchFactor( stretch, 2 );\n\n#ifdef NOT_USEFUL_CURRENTLY\n mAddNewServersCB = new QCheckBox( i18n( \"Automatically add &new servers discovered in CRL distribution points\" ), this );\n connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) );\n lay->addWidget( mAddNewServersCB );\n#endif\n\n#ifndef HAVE_UNBROKEN_KCMULTIDIALOG\n load();\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::load()\n{\n mWidget->load();\n\n mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );\n if ( mTimeoutConfigEntry ) {\n QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );\n \/\/kDebug() << \"timeout:\" << mTimeoutConfigEntry->uintValue() << \" -> \" << time << endl;\n mTimeout->setTime( time );\n }\n\n mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );\n if ( mMaxItemsConfigEntry ) {\n mMaxItems->blockSignals( true ); \/\/ KNumInput emits valueChanged from setValue!\n mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );\n mMaxItems->blockSignals( false );\n }\n\n#ifdef NOT_USEFUL_CURRENTLY\n mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );\n if ( mAddNewServersConfigEntry ) {\n mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );\n }\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::save()\n{\n mWidget->save();\n\n QTime time( mTimeout->time() );\n unsigned int timeout = time.minute() * 60 + time.second();\n if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )\n mTimeoutConfigEntry->setUIntValue( timeout );\n if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )\n mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );\n#ifdef NOT_USEFUL_CURRENTLY\n if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )\n mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );\n#endif\n\n mConfig->sync( true );\n\n#if 0\n \/\/ Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook\n KABSynchronizer sync;\n const KUrl::List toAdd = mWidget->urlList();\n KUrl::List currentList = sync.readCurrentList();\n\n KUrl::List::const_iterator it = toAdd.begin();\n KUrl::List::const_iterator end = toAdd.end();\n for( ; it != end; ++it ) {\n \/\/ check if the URL is already in currentList\n if ( currentList.find( *it ) == currentList.end() )\n \/\/ if not, add it\n currentList.append( *it );\n }\n sync.writeList( currentList );\n#endif\n}\n\nvoid DirectoryServicesConfigurationPage::defaults()\n{\n mWidget->defaults();\n if ( mTimeoutConfigEntry )\n mTimeoutConfigEntry->resetToDefault();\n if ( mMaxItemsConfigEntry )\n mMaxItemsConfigEntry->resetToDefault();\n#ifdef NOT_USEFUL_CURRENTLY\n if ( mAddNewServersConfigEntry )\n mAddNewServersConfigEntry->resetToDefault();\n#endif\n load();\n}\n\nextern \"C\"\n{\n KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QStringList &args=QStringList() )\n {\n DirectoryServicesConfigurationPage *page =\n new DirectoryServicesConfigurationPage( KComponentData( \"kleopatra\" ), parent, args );\n page->setObjectName( \"kleopatra_config_dirserv\" );\n return page;\n }\n}\n\n\/\/ kdelibs-3.2 didn't have the changed signal in KCModule...\nvoid DirectoryServicesConfigurationPage::slotChanged()\n{\n emit changed(true);\n}\n\n\n\/\/ Find config entry for ldap servers. Implements runtime checks on the configuration option.\nKleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,\n const char* groupName,\n const char* entryName,\n Kleo::CryptoConfigEntry::ArgType argType,\n bool isList )\n{\n Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );\n if ( !entry ) {\n KMessageBox::error( this, i18n( \"Backend error: gpgconf does not seem to know the entry for %1\/%2\/%3\", componentName, groupName, entryName ) );\n return 0;\n }\n if( entry->argType() != argType || entry->isList() != isList ) {\n KMessageBox::error( this, i18n( \"Backend error: gpgconf has wrong type for %1\/%2\/%3: %4 %5\", componentName, groupName, entryName, entry->argType(), entry->isList() ) );\n return 0;\n }\n return entry;\n}\n\n#include \"dirservconfigpage.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <vector>\n\nclass PostingList {\npublic:\n PostingList(const std::vector<int>& v);\n void init() {\n i_ = v_.begin();\n }\n int next() {\n if (i_ == v_.end()) return -1;\n int ret = *i_;\n ++i_;\n return ret;\n }\n int next(int id) {\n while (i_ != v_.end()) {\n if (*i_ < id) {\n\t++i_;\n } else {\n\tint ret = *i_;\n\t++i_;\n\treturn ret;\n }\n }\n return -1;\n }\nprivate:\n std::vector<int> v_;\n std::vector<int>::const_iterator i_;\n};\n\nPostingList::PostingList(const std::vector<int>& v): v_(v), i_(v_.begin()) {}\n\n\nbool taat(std::vector<PostingList> &posting_lists,\n\t std::vector<std::pair<int, int>>& result) {\n result.clear();\n std::map<int, int> accumulator;\n for (auto posting_list = posting_lists.begin();\n posting_list != posting_lists.end();\n ++posting_list) {\n posting_list->init();\n while (true) {\n int tmp_docid = posting_list->next();\n if (tmp_docid == -1) break;\n accumulator[tmp_docid]++;\n }\n }\n std::vector<std::pair<int, int>> tmp_v;\n\n for (auto i = accumulator.begin();\n i != accumulator.end();\n ++i) {\n tmp_v.push_back(std::make_pair(i->first, i->second));\n }\n std::sort(tmp_v.begin(),\n\t tmp_v.end(),\n\t [](const std::pair<int, int>& a, const std::pair<int, int>& b) -> bool{\n\t if (a.second != b.second) return b.second - a.second < 0;\n\t return b.first - a.first > 0;\n\t });\n\n for (auto i = tmp_v.begin();\n i != tmp_v.end();\n ++i) {\n result.push_back(std::make_pair(i->first, i->second));\n }\n return true;\n}\n\nint main() {\n std::vector<PostingList> ps;\n ps.push_back(PostingList({1, 2, 3, 4, 5}));\n ps.push_back(PostingList({1, 3, 5}));\n\n std::vector<std::pair<int, int>> result;\n taat(ps, result);\n\n for (auto i = result.begin(); i != result.end(); ++i) {\n std::cout << i->first << \" \" << i->second << std::endl;\n }\n return 0;\n}\n<commit_msg>improve taat<commit_after>#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <vector>\n\nclass PostingList {\npublic:\n PostingList(const std::vector<int>& v);\n void init() {\n i_ = v_.begin();\n }\n int next() {\n if (i_ == v_.end()) return -1;\n int ret = *i_;\n ++i_;\n return ret;\n }\n int next(int id) {\n while (i_ != v_.end()) {\n if (*i_ < id) {\n\t++i_;\n } else {\n\tint ret = *i_;\n\t++i_;\n\treturn ret;\n }\n }\n return -1;\n }\nprivate:\n std::vector<int> v_;\n std::vector<int>::const_iterator i_;\n};\n\nPostingList::PostingList(const std::vector<int>& v): v_(v), i_(v_.begin()) {}\n\nvoid taat_intersect(PostingList& in,\n\t\t const std::vector<std::pair<int, int>>& accumlator,\n\t\t std::vector<std::pair<int, int>>& next_accumlator) {\n in.init();\n auto i = in.next();\n auto j = accumlator.begin();\n while (i != -1 && j != accumlator.end()) {\n if (i < j->first) {\n next_accumlator.push_back(std::make_pair(i, 1));\n i = in.next();\n } else if(i == j->first) {\n next_accumlator.push_back(std::make_pair(j->first, j->second + 1));\n i = in.next();\n ++j;\n } else {\n next_accumlator.push_back(*j);\n ++j;\n }\n }\n while (i != -1) {\n next_accumlator.push_back(std::make_pair(i, 1));\n i = in.next();\n }\n while (j != accumlator.end()) {\n next_accumlator.push_back(*j);\n ++j;\n }\n}\n\nbool taat(std::vector<PostingList> &posting_lists,\n\t const int top_k,\n\t std::vector<std::pair<int, int>>& result) {\n result.clear();\n\n for (auto posting_list = posting_lists.begin();\n posting_list != posting_lists.end();\n ++posting_list) {\n posting_list->init();\n std::vector<std::pair<int, int>> next_accumlator;\n\n taat_intersect(*posting_list, result, next_accumlator);\n next_accumlator.swap(result);\n }\n\n std::partial_sort(result.begin(),\n\t\t result.begin() + top_k,\n\t\t result.end(),\n\t\t [](const std::pair<int, int>& a, const std::pair<int, int>& b) -> bool{\n\t\t if (a.second != b.second) return b.second - a.second < 0;\n\t\t return b.first - a.first > 0;\n\t\t });\n return true;\n}\n\nint main() {\n std::vector<PostingList> ps;\n ps.push_back(PostingList({1, 2, 3, 4, 5}));\n ps.push_back(PostingList({1, 3, 5}));\n\n std::vector<std::pair<int, int>> result;\n taat(ps, 5, result);\n\n for (auto i = result.begin(); i != result.end(); ++i) {\n std::cout << i->first << \" \" << i->second << std::endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s\n\nnamespace std { class type_info; };\n\nnamespace ExplicitCapture {\n int GlobalVar; \/\/ expected-note {{declared here}}\n\n namespace N {\n int AmbiguousVar; \/\/ expected-note {{candidate}}\n }\n int AmbiguousVar; \/\/ expected-note {{candidate}}\n using namespace N;\n\n class C {\n int Member;\n\n static void Overload(int);\n void Overload();\n virtual C& Overload(float);\n\n void ExplicitCapture() {\n int foo;\n\n [foo, foo] () {}; \/\/ expected-error {{'foo' can appear only once}} expected-error {{not supported yet}}\n [this, this] () {}; \/\/ expected-error {{'this' can appear only once}} expected-error {{not supported yet}}\n [=, foo] () {}; \/\/ expected-error {{'&' must precede a capture when}} expected-error {{not supported yet}}\n [=, &foo] () {}; \/\/ expected-error {{not supported yet}}\n [=, this] () {}; \/\/ expected-error {{'this' cannot appear}} expected-error {{not supported yet}}\n [&, foo] () {}; \/\/ expected-error {{not supported yet}}\n [&, &foo] () {}; \/\/ expected-error {{'&' cannot precede a capture when}} expected-error {{not supported yet}}\n [&, this] () {}; \/\/ expected-error {{not supported yet}}\n [&Overload] () {}; \/\/ expected-error {{does not name a variable}} expected-error {{not supported yet}}\n [&GlobalVar] () {}; \/\/ expected-error {{does not have automatic storage duration}} expected-error {{not supported yet}}\n [&AmbiguousVar] () {} \/\/ expected-error {{reference to 'AmbiguousVar' is ambiguous}} expected-error {{not supported yet}}\n [&Globalvar] () {}; \/\/ expected-error {{use of undeclared identifier 'Globalvar'; did you mean 'GlobalVar}}\n }\n\n void ImplicitThisCapture() {\n [](){(void)Member;}; \/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n [&](){(void)Member;}; \/\/ expected-error {{not supported yet}}\n [this](){(void)Member;}; \/\/ expected-error {{not supported yet}}\n [this]{[this]{};};\/\/ expected-error 2 {{not supported yet}}\n []{[this]{};};\/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error 2 {{not supported yet}}\n []{Overload(3);}; \/\/ expected-error {{not supported yet}}\n []{Overload();}; \/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n []{(void)typeid(Overload());};\/\/ expected-error {{not supported yet}}\n []{(void)typeid(Overload(.5f));};\/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n }\n };\n\n void f() {\n [this] () {}; \/\/ expected-error {{invalid use of 'this'}} expected-error {{not supported yet}}\n }\n}\n\nnamespace ReturnDeduction {\n void test() {\n [](){ return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return ({return 1; 1;}); }; \/\/ expected-error {{not supported yet}}\n [](){ return ({return 'c'; 1;}); }; \/\/ expected-error {{not supported yet}} expected-error {{must match previous return type}}\n []()->int{ return 'c'; return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return 'c'; return 1; }; \/\/ expected-error {{not supported yet}} expected-error {{must match previous return type}}\n \/\/ FIXME: Need to check structure of lambda body \n [](){ return 1; return 1; }; \/\/ expected-error {{not supported yet}}\n }\n}\n<commit_msg>Add an additional testcase for a lambda with implicit void return type.<commit_after>\/\/ RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s\n\nnamespace std { class type_info; };\n\nnamespace ExplicitCapture {\n int GlobalVar; \/\/ expected-note {{declared here}}\n\n namespace N {\n int AmbiguousVar; \/\/ expected-note {{candidate}}\n }\n int AmbiguousVar; \/\/ expected-note {{candidate}}\n using namespace N;\n\n class C {\n int Member;\n\n static void Overload(int);\n void Overload();\n virtual C& Overload(float);\n\n void ExplicitCapture() {\n int foo;\n\n [foo, foo] () {}; \/\/ expected-error {{'foo' can appear only once}} expected-error {{not supported yet}}\n [this, this] () {}; \/\/ expected-error {{'this' can appear only once}} expected-error {{not supported yet}}\n [=, foo] () {}; \/\/ expected-error {{'&' must precede a capture when}} expected-error {{not supported yet}}\n [=, &foo] () {}; \/\/ expected-error {{not supported yet}}\n [=, this] () {}; \/\/ expected-error {{'this' cannot appear}} expected-error {{not supported yet}}\n [&, foo] () {}; \/\/ expected-error {{not supported yet}}\n [&, &foo] () {}; \/\/ expected-error {{'&' cannot precede a capture when}} expected-error {{not supported yet}}\n [&, this] () {}; \/\/ expected-error {{not supported yet}}\n [&Overload] () {}; \/\/ expected-error {{does not name a variable}} expected-error {{not supported yet}}\n [&GlobalVar] () {}; \/\/ expected-error {{does not have automatic storage duration}} expected-error {{not supported yet}}\n [&AmbiguousVar] () {} \/\/ expected-error {{reference to 'AmbiguousVar' is ambiguous}} expected-error {{not supported yet}}\n [&Globalvar] () {}; \/\/ expected-error {{use of undeclared identifier 'Globalvar'; did you mean 'GlobalVar}}\n }\n\n void ImplicitThisCapture() {\n [](){(void)Member;}; \/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n [&](){(void)Member;}; \/\/ expected-error {{not supported yet}}\n [this](){(void)Member;}; \/\/ expected-error {{not supported yet}}\n [this]{[this]{};};\/\/ expected-error 2 {{not supported yet}}\n []{[this]{};};\/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error 2 {{not supported yet}}\n []{Overload(3);}; \/\/ expected-error {{not supported yet}}\n []{Overload();}; \/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n []{(void)typeid(Overload());};\/\/ expected-error {{not supported yet}}\n []{(void)typeid(Overload(.5f));};\/\/ expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}\n }\n };\n\n void f() {\n [this] () {}; \/\/ expected-error {{invalid use of 'this'}} expected-error {{not supported yet}}\n }\n}\n\nnamespace ReturnDeduction {\n void test() {\n [](){ return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return ({return 1; 1;}); }; \/\/ expected-error {{not supported yet}}\n [](){ return ({return 'c'; 1;}); }; \/\/ expected-error {{not supported yet}} expected-error {{must match previous return type}}\n []()->int{ return 'c'; return 1; }; \/\/ expected-error {{not supported yet}}\n [](){ return 'c'; return 1; }; \/\/ expected-error {{not supported yet}} expected-error {{must match previous return type}}\n []() { return; return (void)0; }; \/\/ expected-error {{not supported yet}}\n \/\/ FIXME: Need to check structure of lambda body \n [](){ return 1; return 1; }; \/\/ expected-error {{not supported yet}}\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ft2232spi.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n\r\n\/* Standard C libraries *\/\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n#include<string.h>\r\n\/* OS specific libraries *\/\r\n#ifdef _WIN32\r\n#include<windows.h>\r\n#endif\r\n\r\n\/* Include D2XX header*\/\r\n#include \"ftd2xx.h\"\r\n\r\n#pragma comment(lib, \"FTD2XX.lib\")\r\n#pragma comment(lib, \"libMPSSE.lib\")\r\n\r\n\/* Include libMPSSE header *\/\r\n#include \"libMPSSE_spi.h\"\r\n\r\n\/* Helper macros *\/\r\n\r\n#define APP_CHECK_STATUS(exp) {if(exp!=FT_OK){printf(\"%s:%d:%s(): status(0x%x) \\\r\n!= FT_OK\\n\",__FILE__, __LINE__, __FUNCTION__,exp);exit(1);}else{;}};\r\n#define CHECK_NULL(exp){if(exp==NULL){printf(\"%s:%d:%s(): NULL expression \\\r\nencountered \\n\",__FILE__, __LINE__, __FUNCTION__);exit(1);}else{;}};\r\n\r\n\/* Definitions *\/\r\n#define SPI_DEVICE_BUFFER_SIZE\t\t256\r\n#define CHANNEL_TO_OPEN\t\t\t0\t\/*0 for first available channel, 1 for next... *\/\r\n#define SPI_WRITE_COMPLETION_RETRY 100\r\n#define SPI_OPTS SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE\r\n\r\n\/* Globals *\/\r\nstatic FT_STATUS ftStatus;\r\nstatic FT_HANDLE ftHandle;\r\nstatic uint8 wBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};\r\nstatic uint8 rBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};\r\n\r\n\r\nint _tmain(int argc, _TCHAR* argv[]) {\r\n\tFT_STATUS status = FT_OK;\r\n\tFT_DEVICE_LIST_INFO_NODE devList = {0};\r\n\tChannelConfig channelConf = {0};\r\n\tuint8 address = 0;\r\n\tuint32 channels = 0;\r\n\tuint16 data = 0;\r\n\tuint8 i = 0;\r\n\t\r\n\tchannelConf.ClockRate = 400000;\r\n\tchannelConf.LatencyTimer = 255;\r\n\tchannelConf.configOptions = SPI_CONFIG_OPTION_MODE0 | SPI_CONFIG_OPTION_CS_DBUS4 | SPI_CONFIG_OPTION_CS_ACTIVELOW;\r\n\tchannelConf.Pin = 0xFFff0000;\/*FinalVal-FinalDir-InitVal-InitDir (for dir 0=in, 1=out)*\/\r\n\tchannelConf.reserved = 0;\r\n\r\n\t\/* init library *\/\r\n#ifdef _MSC_VER\r\n\tInit_libMPSSE();\r\n#endif\r\n\tstatus = SPI_GetNumChannels(&channels);\r\n\tAPP_CHECK_STATUS(status);\r\n\tprintf(\"Number of available SPI channels = %d\\n\",(int)channels);\r\n\r\n\tif(channels>0)\r\n\t{\r\n#if 0\r\n\t\tfor(i=0;i<channels;i++)\r\n\t\t{\r\n\t\t\tstatus = SPI_GetChannelInfo(i,&devList);\r\n\t\t\tAPP_CHECK_STATUS(status);\r\n\t\t\tprintf(\"Information on channel number %d:\\n\",i);\r\n\t\t\t\/* print the dev info *\/\r\n\t\t\tprintf(\"\t\tFlags=0x%x\\n\",devList.Flags);\r\n\t\t\tprintf(\"\t\tType=0x%x\\n\",devList.Type);\r\n\t\t\tprintf(\"\t\tID=0x%x\\n\",devList.ID);\r\n\t\t\tprintf(\"\t\tLocId=0x%x\\n\",devList.LocId);\r\n\t\t\tprintf(\"\t\tSerialNumber=%s\\n\",devList.SerialNumber);\r\n\t\t\tprintf(\"\t\tDescription=%s\\n\",devList.Description);\r\n\t\t\tprintf(\"\t\tftHandle=0x%x\\n\",(unsigned int)devList.ftHandle);\/*is 0 unless open*\/\r\n\t\t}\r\n#endif\r\n\r\n\t\t\/* Open the first available channel *\/\r\n\t\tstatus = SPI_OpenChannel(CHANNEL_TO_OPEN,&ftHandle);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\t\tprintf(\"\\nhandle=0x%x status=0x%x\\n\",(unsigned int)ftHandle,status);\r\n\t\tstatus = SPI_InitChannel(ftHandle,&channelConf);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\r\n\t\t\/\/ Write some data for the lattice iCE40Ultra EVK demo\r\n\t\tuint32 sizeTransferred;\r\n\t\t\r\n\t\t\/\/ Make sure we are out of programming mode\r\n\t\tstatus = SPI_Read(ftHandle, rBuffer, 50, &sizeTransferred, SPI_OPTS);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\r\n\t\twBuffer[0] = 0x19;\r\n\t\twBuffer[1] = 0x67; \/\/ Color 6 (cyan), brightness 7 (50%)\r\n\t\twBuffer[2] = 0x20; \/\/ Ramp 2, blink rate 0\r\n\t\tstatus = SPI_ReadWrite(ftHandle, rBuffer, wBuffer, 3, &sizeTransferred, SPI_OPTS);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\t\tprintf(\"Wrote\/Read %d bytes\\r\\n\", sizeTransferred);\r\n\t\tunsigned long retry = 0;\r\n\t\tbool state=FALSE;\r\n\t\tSPI_IsBusy(ftHandle,&state);\r\n\t\twhile((FALSE==state) && (retry<SPI_WRITE_COMPLETION_RETRY))\r\n\t\t{\r\n\t\t\tprintf(\"SPI device is busy(%u)\\n\",(unsigned)retry);\r\n\t\t\tSPI_IsBusy(ftHandle,&state);\r\n\t\t\tretry++;\r\n\t\t}\r\n\t\tprintf(\"Read %02x %02x %02x\\r\\n\", rBuffer[0], rBuffer[1], rBuffer[2]);\r\n\r\n\t\tstatus = SPI_CloseChannel(ftHandle);\r\n\t}\r\n\r\n#ifdef _MSC_VER\r\n\tCleanup_libMPSSE();\r\n#endif\r\n\r\n#ifndef __linux__\r\n\tsystem(\"pause\");\r\n#endif\r\n\treturn 0;\r\n}\r\n\r\n<commit_msg>Checkpoint.<commit_after>\/\/ ft2232spi.cpp : Defines the entry point for the console application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n\r\n\/* Standard C libraries *\/\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n#include<string.h>\r\n\/* OS specific libraries *\/\r\n#ifdef _WIN32\r\n#include<windows.h>\r\n#endif\r\n\r\n\/* Include D2XX header*\/\r\n#include \"ftd2xx.h\"\r\n\r\n#pragma comment(lib, \"FTD2XX.lib\")\r\n#pragma comment(lib, \"libMPSSE.lib\")\r\n\r\n\/* Include libMPSSE header *\/\r\n#include \"libMPSSE_spi.h\"\r\n\r\n\/* Helper macros *\/\r\n\r\n#define APP_CHECK_STATUS(exp) {if(exp!=FT_OK){printf(\"%s:%d:%s(): status(0x%x) \\\r\n!= FT_OK\\n\",__FILE__, __LINE__, __FUNCTION__,exp);exit(1);}else{;}};\r\n#define CHECK_NULL(exp){if(exp==NULL){printf(\"%s:%d:%s(): NULL expression \\\r\nencountered \\n\",__FILE__, __LINE__, __FUNCTION__);exit(1);}else{;}};\r\n\r\n\/* Definitions *\/\r\n#define SPI_DEVICE_BUFFER_SIZE\t\t256\r\n#define CHANNEL_TO_OPEN\t\t\t0\t\/*0 for first available channel, 1 for next... *\/\r\n#define SPI_WRITE_COMPLETION_RETRY 100\r\n#define SPI_OPTS SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_DISABLE\r\n\r\n\/* Globals *\/\r\nstatic FT_STATUS ftStatus;\r\nstatic FT_HANDLE ftHandle;\r\nstatic uint8 wBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};\r\nstatic uint8 rBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};\r\n\r\n\r\nint _tmain(int argc, _TCHAR* argv[]) {\r\n\tFT_STATUS status = FT_OK;\r\n\tFT_DEVICE_LIST_INFO_NODE devList = {0};\r\n\tChannelConfig channelConf = {0};\r\n\tuint8 address = 0;\r\n\tuint32 channels = 0;\r\n\tuint16 data = 0;\r\n\tuint8 i = 0;\r\n\t\r\n\tchannelConf.ClockRate = 400000;\r\n\tchannelConf.LatencyTimer = 255;\r\n\tchannelConf.configOptions = SPI_CONFIG_OPTION_MODE0 | SPI_CONFIG_OPTION_CS_DBUS4 | SPI_CONFIG_OPTION_CS_ACTIVELOW;\r\n\tchannelConf.Pin = 0xFFff0000;\/*FinalVal-FinalDir-InitVal-InitDir (for dir 0=in, 1=out)*\/\r\n\tchannelConf.reserved = 0;\r\n\r\n\t\/* init library *\/\r\n#ifdef _MSC_VER\r\n\tInit_libMPSSE();\r\n#endif\r\n\tstatus = SPI_GetNumChannels(&channels);\r\n\tAPP_CHECK_STATUS(status);\r\n\tprintf(\"Number of available SPI channels = %d\\n\",(int)channels);\r\n\r\n\tif(channels>0)\r\n\t{\r\n#if 0\r\n\t\tfor(i=0;i<channels;i++)\r\n\t\t{\r\n\t\t\tstatus = SPI_GetChannelInfo(i,&devList);\r\n\t\t\tAPP_CHECK_STATUS(status);\r\n\t\t\tprintf(\"Information on channel number %d:\\n\",i);\r\n\t\t\t\/* print the dev info *\/\r\n\t\t\tprintf(\"\t\tFlags=0x%x\\n\",devList.Flags);\r\n\t\t\tprintf(\"\t\tType=0x%x\\n\",devList.Type);\r\n\t\t\tprintf(\"\t\tID=0x%x\\n\",devList.ID);\r\n\t\t\tprintf(\"\t\tLocId=0x%x\\n\",devList.LocId);\r\n\t\t\tprintf(\"\t\tSerialNumber=%s\\n\",devList.SerialNumber);\r\n\t\t\tprintf(\"\t\tDescription=%s\\n\",devList.Description);\r\n\t\t\tprintf(\"\t\tftHandle=0x%x\\n\",(unsigned int)devList.ftHandle);\/*is 0 unless open*\/\r\n\t\t}\r\n#endif\r\n\r\n\t\t\/* Open the first available channel *\/\r\n\t\tstatus = SPI_OpenChannel(CHANNEL_TO_OPEN,&ftHandle);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\t\tprintf(\"\\nhandle=0x%x status=0x%x\\n\",(unsigned int)ftHandle,status);\r\n\t\tstatus = SPI_InitChannel(ftHandle,&channelConf);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\r\n\t\t\/\/ Write some data for the lattice iCE40Ultra EVK demo\r\n\t\tuint32 sizeTransferred;\r\n\r\n\t\twBuffer[0] = 0x7e; \/\/ Programming sync pattern\r\n\t\twBuffer[1] = 0xaa;\r\n\t\twBuffer[2] = 0x99;\r\n\t\twBuffer[3] = 0x7e;\r\n\t\tstatus = SPI_ReadWrite(ftHandle, rBuffer, wBuffer, 4, &sizeTransferred, SPI_OPTS);\r\n\t\tAPP_CHECK_STATUS(status);\r\n\t\tprintf(\"Wrote\/Read %d bytes\\r\\n\", sizeTransferred);\r\n\t\tunsigned long retry = 0;\r\n\t\tbool state=FALSE;\r\n\t\tSPI_IsBusy(ftHandle,&state);\r\n\t\twhile((FALSE==state) && (retry<SPI_WRITE_COMPLETION_RETRY))\r\n\t\t{\r\n\t\t\tprintf(\"SPI device is busy(%u)\\n\",(unsigned)retry);\r\n\t\t\tSPI_IsBusy(ftHandle,&state);\r\n\t\t\tretry++;\r\n\t\t}\r\n\t\tprintf(\"Read %02x %02x %02x\\r\\n\", rBuffer[0], rBuffer[1], rBuffer[2]);\r\n\r\n\t\tstatus = SPI_CloseChannel(ftHandle);\r\n\t}\r\n\r\n#ifdef _MSC_VER\r\n\tCleanup_libMPSSE();\r\n#endif\r\n\r\n#ifndef __linux__\r\n\tsystem(\"pause\");\r\n#endif\r\n\treturn 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/end2end\/end2end_tests.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"src\/core\/lib\/surface\/channel.h\"\n\n#include <grpc\/byte_buffer.h>\n#include <grpc\/grpc.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/time.h>\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nstatic grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,\n const char* test_name,\n grpc_channel_args* client_args,\n grpc_channel_args* server_args) {\n grpc_end2end_test_fixture f;\n gpr_log(GPR_INFO, \"Running test: %s\/%s\", test_name, config.name);\n f = config.create_fixture(client_args, server_args);\n config.init_server(&f, server_args);\n config.init_client(&f, client_args);\n return f;\n}\n\nstatic gpr_timespec n_seconds_from_now(int n) {\n return grpc_timeout_seconds_to_deadline(n);\n}\n\nstatic gpr_timespec five_seconds_from_now(void) {\n return n_seconds_from_now(5);\n}\n\nstatic void drain_cq(grpc_completion_queue* cq) {\n grpc_event ev;\n do {\n ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);\n } while (ev.type != GRPC_QUEUE_SHUTDOWN);\n}\n\nstatic void shutdown_server(grpc_end2end_test_fixture* f) {\n if (!f->server) return;\n grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));\n GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),\n grpc_timeout_seconds_to_deadline(5),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_server_destroy(f->server);\n f->server = nullptr;\n}\n\nstatic void shutdown_client(grpc_end2end_test_fixture* f) {\n if (!f->client) return;\n grpc_channel_destroy(f->client);\n f->client = nullptr;\n}\n\nstatic void end_test(grpc_end2end_test_fixture* f) {\n shutdown_server(f);\n shutdown_client(f);\n\n grpc_completion_queue_shutdown(f->cq);\n drain_cq(f->cq);\n grpc_completion_queue_destroy(f->cq);\n grpc_completion_queue_destroy(f->shutdown_cq);\n}\n\nstatic void run_one_request(grpc_end2end_test_config config,\n grpc_end2end_test_fixture f,\n bool request_is_success) {\n grpc_call* c;\n grpc_call* s;\n cq_verifier* cqv = cq_verifier_create(f.cq);\n grpc_op ops[6];\n grpc_op* op;\n grpc_metadata_array initial_metadata_recv;\n grpc_metadata_array trailing_metadata_recv;\n grpc_metadata_array request_metadata_recv;\n grpc_call_details call_details;\n grpc_status_code status;\n grpc_call_error error;\n grpc_slice details;\n int was_cancelled = 2;\n\n gpr_timespec deadline = five_seconds_from_now();\n c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,\n grpc_slice_from_static_string(\"\/foo\"), nullptr,\n deadline, nullptr);\n GPR_ASSERT(c);\n\n grpc_metadata_array_init(&initial_metadata_recv);\n grpc_metadata_array_init(&trailing_metadata_recv);\n grpc_metadata_array_init(&request_metadata_recv);\n grpc_call_details_init(&call_details);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_INITIAL_METADATA;\n op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;\n op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;\n op->data.recv_status_on_client.status = &status;\n op->data.recv_status_on_client.status_details = &details;\n op->data.recv_status_on_client.error_string = nullptr;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n error =\n grpc_server_request_call(f.server, &s, &call_details,\n &request_metadata_recv, f.cq, f.cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;\n op->data.send_status_from_server.trailing_metadata_count = 0;\n op->data.send_status_from_server.status =\n request_is_success ? GRPC_STATUS_OK : GRPC_STATUS_UNIMPLEMENTED;\n grpc_slice status_details = grpc_slice_from_static_string(\"xyz\");\n op->data.send_status_from_server.status_details = &status_details;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;\n op->data.recv_close_on_server.cancelled = &was_cancelled;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n CQ_EXPECT_COMPLETION(cqv, tag(102), 1);\n CQ_EXPECT_COMPLETION(cqv, tag(1), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(0 == grpc_slice_str_cmp(details, \"xyz\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\"));\n GPR_ASSERT(0 == call_details.flags);\n\n grpc_slice_unref(details);\n grpc_metadata_array_destroy(&initial_metadata_recv);\n grpc_metadata_array_destroy(&trailing_metadata_recv);\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n\n grpc_call_unref(c);\n grpc_call_unref(s);\n\n cq_verifier_destroy(cqv);\n}\n\nstatic void test_channelz(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n f = begin_test(config, \"test_channelz\", nullptr, nullptr);\n grpc_core::channelz::Channel* channelz_channel =\n grpc_channel_get_channelz_node(f.client);\n\n char* json = channelz_channel->RenderJSON();\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"0\\\"\"));\n gpr_free(json);\n\n \/\/ one successful request\n run_one_request(config, f, true);\n\n json = channelz_channel->RenderJSON();\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"1\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"1\\\"\"));\n gpr_free(json);\n\n \/\/ one failed request\n run_one_request(config, f, false);\n\n json = channelz_channel->RenderJSON();\n gpr_log(GPR_INFO, \"%s\", json);\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"2\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"1\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"1\\\"\"));\n gpr_free(json);\n\n end_test(&f);\n config.tear_down_data(&f);\n}\n\nstatic void test_channelz_with_channel_trace(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n grpc_arg client_a;\n client_a.type = GRPC_ARG_INTEGER;\n client_a.key = const_cast<char*>(GRPC_ARG_MAX_CHANNEL_TRACE_EVENTS_PER_NODE);\n client_a.value.integer = 5;\n grpc_channel_args client_args = {1, &client_a};\n\n f = begin_test(config, \"test_channelz_with_channel_trace\", &client_args,\n nullptr);\n grpc_core::channelz::Channel* channelz_channel =\n grpc_channel_get_channelz_node(f.client);\n\n char* json = channelz_channel->RenderJSON();\n gpr_log(GPR_INFO, \"%s\", json);\n GPR_ASSERT(nullptr != strstr(json, \"\\\"trace\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"description\\\":\\\"Channel created\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"severity\\\":\\\"CT_INFO\\\"\"));\n gpr_free(json);\n\n end_test(&f);\n config.tear_down_data(&f);\n}\nvoid channelz(grpc_end2end_test_config config) {\n test_channelz(config);\n test_channelz_with_channel_trace(config);\n}\n\nvoid channelz_pre_init(void) {}\n<commit_msg>fixup! Rename channelz Channel to ChannelNode<commit_after>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/end2end\/end2end_tests.h\"\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"src\/core\/lib\/surface\/channel.h\"\n\n#include <grpc\/byte_buffer.h>\n#include <grpc\/grpc.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/time.h>\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nstatic grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,\n const char* test_name,\n grpc_channel_args* client_args,\n grpc_channel_args* server_args) {\n grpc_end2end_test_fixture f;\n gpr_log(GPR_INFO, \"Running test: %s\/%s\", test_name, config.name);\n f = config.create_fixture(client_args, server_args);\n config.init_server(&f, server_args);\n config.init_client(&f, client_args);\n return f;\n}\n\nstatic gpr_timespec n_seconds_from_now(int n) {\n return grpc_timeout_seconds_to_deadline(n);\n}\n\nstatic gpr_timespec five_seconds_from_now(void) {\n return n_seconds_from_now(5);\n}\n\nstatic void drain_cq(grpc_completion_queue* cq) {\n grpc_event ev;\n do {\n ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);\n } while (ev.type != GRPC_QUEUE_SHUTDOWN);\n}\n\nstatic void shutdown_server(grpc_end2end_test_fixture* f) {\n if (!f->server) return;\n grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));\n GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),\n grpc_timeout_seconds_to_deadline(5),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_server_destroy(f->server);\n f->server = nullptr;\n}\n\nstatic void shutdown_client(grpc_end2end_test_fixture* f) {\n if (!f->client) return;\n grpc_channel_destroy(f->client);\n f->client = nullptr;\n}\n\nstatic void end_test(grpc_end2end_test_fixture* f) {\n shutdown_server(f);\n shutdown_client(f);\n\n grpc_completion_queue_shutdown(f->cq);\n drain_cq(f->cq);\n grpc_completion_queue_destroy(f->cq);\n grpc_completion_queue_destroy(f->shutdown_cq);\n}\n\nstatic void run_one_request(grpc_end2end_test_config config,\n grpc_end2end_test_fixture f,\n bool request_is_success) {\n grpc_call* c;\n grpc_call* s;\n cq_verifier* cqv = cq_verifier_create(f.cq);\n grpc_op ops[6];\n grpc_op* op;\n grpc_metadata_array initial_metadata_recv;\n grpc_metadata_array trailing_metadata_recv;\n grpc_metadata_array request_metadata_recv;\n grpc_call_details call_details;\n grpc_status_code status;\n grpc_call_error error;\n grpc_slice details;\n int was_cancelled = 2;\n\n gpr_timespec deadline = five_seconds_from_now();\n c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,\n grpc_slice_from_static_string(\"\/foo\"), nullptr,\n deadline, nullptr);\n GPR_ASSERT(c);\n\n grpc_metadata_array_init(&initial_metadata_recv);\n grpc_metadata_array_init(&trailing_metadata_recv);\n grpc_metadata_array_init(&request_metadata_recv);\n grpc_call_details_init(&call_details);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_INITIAL_METADATA;\n op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;\n op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;\n op->data.recv_status_on_client.status = &status;\n op->data.recv_status_on_client.status_details = &details;\n op->data.recv_status_on_client.error_string = nullptr;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n error =\n grpc_server_request_call(f.server, &s, &call_details,\n &request_metadata_recv, f.cq, f.cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;\n op->data.send_status_from_server.trailing_metadata_count = 0;\n op->data.send_status_from_server.status =\n request_is_success ? GRPC_STATUS_OK : GRPC_STATUS_UNIMPLEMENTED;\n grpc_slice status_details = grpc_slice_from_static_string(\"xyz\");\n op->data.send_status_from_server.status_details = &status_details;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;\n op->data.recv_close_on_server.cancelled = &was_cancelled;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n CQ_EXPECT_COMPLETION(cqv, tag(102), 1);\n CQ_EXPECT_COMPLETION(cqv, tag(1), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(0 == grpc_slice_str_cmp(details, \"xyz\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\"));\n GPR_ASSERT(0 == call_details.flags);\n\n grpc_slice_unref(details);\n grpc_metadata_array_destroy(&initial_metadata_recv);\n grpc_metadata_array_destroy(&trailing_metadata_recv);\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n\n grpc_call_unref(c);\n grpc_call_unref(s);\n\n cq_verifier_destroy(cqv);\n}\n\nstatic void test_channelz(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n f = begin_test(config, \"test_channelz\", nullptr, nullptr);\n grpc_core::channelz::ChannelNode* channelz_channel =\n grpc_channel_get_channelz_node(f.client);\n\n char* json = channelz_channel->RenderJSON();\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"0\\\"\"));\n gpr_free(json);\n\n \/\/ one successful request\n run_one_request(config, f, true);\n\n json = channelz_channel->RenderJSON();\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"1\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"0\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"1\\\"\"));\n gpr_free(json);\n\n \/\/ one failed request\n run_one_request(config, f, false);\n\n json = channelz_channel->RenderJSON();\n gpr_log(GPR_INFO, \"%s\", json);\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsStarted\\\":\\\"2\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsFailed\\\":\\\"1\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"callsSucceeded\\\":\\\"1\\\"\"));\n gpr_free(json);\n\n end_test(&f);\n config.tear_down_data(&f);\n}\n\nstatic void test_channelz_with_channel_trace(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n grpc_arg client_a;\n client_a.type = GRPC_ARG_INTEGER;\n client_a.key = const_cast<char*>(GRPC_ARG_MAX_CHANNEL_TRACE_EVENTS_PER_NODE);\n client_a.value.integer = 5;\n grpc_channel_args client_args = {1, &client_a};\n\n f = begin_test(config, \"test_channelz_with_channel_trace\", &client_args,\n nullptr);\n grpc_core::channelz::ChannelNode* channelz_channel =\n grpc_channel_get_channelz_node(f.client);\n\n char* json = channelz_channel->RenderJSON();\n gpr_log(GPR_INFO, \"%s\", json);\n GPR_ASSERT(nullptr != strstr(json, \"\\\"trace\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"description\\\":\\\"Channel created\\\"\"));\n GPR_ASSERT(nullptr != strstr(json, \"\\\"severity\\\":\\\"CT_INFO\\\"\"));\n gpr_free(json);\n\n end_test(&f);\n config.tear_down_data(&f);\n}\nvoid channelz(grpc_end2end_test_config config) {\n test_channelz(config);\n test_channelz_with_channel_trace(config);\n}\n\nvoid channelz_pre_init(void) {}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * numerical_comparisons.hpp\n *\n * Created on: Aug 13, 2013\n * Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#ifndef SM_NUMERICALCOMPARISON_HPP_\n#define SM_NUMERICALCOMPARISON_HPP_\n\n#include <algorithm> \/\/ std::max\n#include <limits> \/\/ std::numeric_limits\n#include <cmath> \/\/ std::abs\n#include <stdexcept> \/\/ std::invalid_argument\n#include \"assert_macros.hpp\"\n\nnamespace sm {\n\n\/*\n * Functions to compare floating point numbers with a relative error (epsilon).\n *\n * As the precision of floating point numbers are limited and depending on the\n * magnitude, we compare two numbers a and b by comparing their difference |a - b|\n * to the magnitude of the the bigger number max(|a|, |b|) multiplied with the\n * relative error epsilon. Therefore, a and b are approximately equal if it holds\n * |a - b| <= max(|a|, |b|) * epsilon. This can be applied analogously to greater\n * and less than comparisons.\n *\n * More information on compare floating point numbers is given in\n * - http:\/\/randomascii.wordpress.com\/2012\/02\/25\/comparing-floating-point-numbers-2012-edition\/\n * - The art of computer programming, Volume 2 \/ Seminumerical Algorithms, Donald E. Knuth (page 218)\n *\/\n\nnamespace internal {\n\n\/*!\n * Takes max(|a|, |b|) and multiplies it with epsilon.\n * @param a the first number.\n * @param b the second number.\n * @param epsilon the precision (epsilon > 0).\n * @return the result of max(|a|, |b|) * epsilon.\n *\/\ntemplate<typename ValueType_>\nstatic inline ValueType_ maxTimesEpsilon(const ValueType_ a, const ValueType_ b, const ValueType_ epsilon)\n{\n SM_ASSERT_GT_DBG(std::invalid_argument, epsilon, 0.0, \"This method is only valid for an epsilon greater than 0.\");\n return std::max(std::abs(a), std::abs(b)) * epsilon;\n}\n\n} \/* namespace internal *\/\n\n\/*!\n * Checks if two numbers a and b are equal within a relative error.\n * @param[in] a the first number to compare.\n * @param[in] b the second number to compare.\n * @param[in] epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a and b are approximately equal, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool approximatelyEqual(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n return std::abs(a - b) <= internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n\/*!\n * Checks if a is greater than b (a > b) within a relative error.\n * @param a the first number to compare.\n * @param b the second number to compare.\n * @param epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a definitely greater than b, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool definitelyGreaterThan(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n return (a - b) > internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n\/*!\n * Checks if a is less than b (a < b) within a relative error.\n * @param a the first number to compare.\n * @param b the second number to compare.\n * @param epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a definitely less than b, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool definitelyLessThan(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n return (b - a) > internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n} \/* namespace sm *\/\n#endif \/* SM_NUMERICALCOMPARISON_HPP_ *\/\n<commit_msg>Fixed numerical comparison unit-tests<commit_after>\/*\n * numerical_comparisons.hpp\n *\n * Created on: Aug 13, 2013\n * Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#ifndef SM_NUMERICALCOMPARISON_HPP_\n#define SM_NUMERICALCOMPARISON_HPP_\n\n#include <algorithm> \/\/ std::max\n#include <limits> \/\/ std::numeric_limits\n#include <cmath> \/\/ std::abs\n#include <stdexcept> \/\/ std::invalid_argument\n#include \"assert_macros.hpp\"\n\nnamespace sm {\n\n\/*\n * Functions to compare floating point numbers with a relative error (epsilon).\n *\n * As the precision of floating point numbers are limited and depending on the\n * magnitude, we compare two numbers a and b by comparing their difference |a - b|\n * to the magnitude of the the bigger number max(|a|, |b|) multiplied with the\n * relative error epsilon. Therefore, a and b are approximately equal if it holds\n * |a - b| <= max(|a|, |b|) * epsilon. This can be applied analogously to greater\n * and less than comparisons.\n *\n * More information on compare floating point numbers is given in\n * - http:\/\/randomascii.wordpress.com\/2012\/02\/25\/comparing-floating-point-numbers-2012-edition\/\n * - The art of computer programming, Volume 2 \/ Seminumerical Algorithms, Donald E. Knuth (page 218)\n *\/\n\nnamespace internal {\n\n\/*!\n * Takes max(|a|, |b|) and multiplies it with epsilon.\n * @param a the first number.\n * @param b the second number.\n * @param epsilon the precision (epsilon > 0).\n * @return the result of max(|a|, |b|) * epsilon.\n *\/\ntemplate<typename ValueType_>\nstatic inline ValueType_ maxTimesEpsilon(const ValueType_ a, const ValueType_ b, const ValueType_ epsilon)\n{\n SM_ASSERT_GT_DBG(std::invalid_argument, epsilon, 0.0, \"This method is only valid for an epsilon greater than 0.\");\n return std::max(std::abs(a), std::abs(b)) * epsilon;\n}\n\n} \/* namespace internal *\/\n\n\/*!\n * Checks if two numbers a and b are equal within a relative error.\n * @param[in] a the first number to compare.\n * @param[in] b the second number to compare.\n * @param[in] epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a and b are approximately equal, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool approximatelyEqual(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n SM_ASSERT_GT(std::invalid_argument, epsilon, 0.0, \"This method is only valid for an epsilon greater than 0.\");\n return std::abs(a - b) <= internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n\/*!\n * Checks if a is greater than b (a > b) within a relative error.\n * @param a the first number to compare.\n * @param b the second number to compare.\n * @param epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a definitely greater than b, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool definitelyGreaterThan(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n SM_ASSERT_GT(std::invalid_argument, epsilon, 0.0, \"This method is only valid for an epsilon greater than 0.\");\n return (a - b) > internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n\/*!\n * Checks if a is less than b (a < b) within a relative error.\n * @param a the first number to compare.\n * @param b the second number to compare.\n * @param epsilon the relative error (optional, if not declared the precision of the datatype).\n * @return true if a definitely less than b, false otherwise.\n *\/\ntemplate<typename ValueType_>\nstatic bool definitelyLessThan(const ValueType_ a, const ValueType_ b, ValueType_ epsilon = std::numeric_limits<ValueType_>::epsilon())\n{\n SM_ASSERT_GT(std::invalid_argument, epsilon, 0.0, \"This method is only valid for an epsilon greater than 0.\");\n return (b - a) > internal::maxTimesEpsilon(a, b, epsilon);\n}\n\n} \/* namespace sm *\/\n#endif \/* SM_NUMERICALCOMPARISON_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"SimulatorWindow.hpp\"\n#include \"rendering\/SimRenderView.hpp\"\n#include \"Physics\/Environment.hpp\"\n\n#include <QAbstractTableModel>\n\nstatic const QString columnNames[] = {\n\t\"Visibility\",\n\t\"Ball Sensor\",\n\t\"Charger\"\n};\n\nclass RobotTableModel: public QAbstractTableModel\n{\npublic:\n\tRobotTableModel(Environment *env)\n\t: _env(env)\n\t{\n\t\tlayoutChanged();\n\t}\n\t\n\tRobot *robotForRow(int row) const\n\t{\n\t\tconst Environment::RobotMap *map;\n\t\tif (row < _env->yellow().size())\n\t\t{\n\t\t\tmap = &_env->yellow();\n\t\t} else {\n\t\t\trow -= _env->yellow().size();\n\t\t\tmap = &_env->blue();\n\t\t}\n\t\tEnvironment::RobotMap::const_iterator i = map->begin();\n\t\ti += row;\n\t\treturn *i;\n\t}\n\t\n\tvirtual int columnCount(const QModelIndex &parent) const\n\t{\n\t\treturn sizeof(columnNames) \/ sizeof(columnNames[0]);\n\t}\n\t\n\tvirtual int rowCount(const QModelIndex &parent) const\n\t{\n\t\tif (_env)\n\t\t{\n\t\t\treturn _env->blue().size() + _env->yellow().size();\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tvirtual Qt::ItemFlags flags(const QModelIndex &index) const\n\t{\n\t\tQt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\t\tif (index.column() == 0)\n\t\t{\n\t\t\tflags |= Qt::ItemIsEditable;\n\t\t} else {\n\t\t\tflags |= Qt::ItemIsUserCheckable;\n\t\t}\n\t\t\n\t\treturn flags;\n\t}\n\t\n\tvirtual QVariant data(const QModelIndex &index, int role) const\n\t{\n\t\tif (_env)\n\t\t{\n\t\t\tRobot *robot = robotForRow(index.row());\n\t\t\t\n\t\t\tif (index.column() == 0 && (role == Qt::DisplayRole || role == Qt::EditRole))\n\t\t\t{\n\t\t\t\treturn QVariant(robot->visibility);\n\t\t\t} else if (index.column() == 1 && role == Qt::CheckStateRole)\n\t\t\t{\n\t\t\t\treturn robot->ballSensorWorks ? Qt::Checked : Qt::Unchecked;\n\t\t\t} else if (index.column() == 2 && role == Qt::CheckStateRole)\n\t\t\t{\n\t\t\t\treturn robot->chargerWorks ? Qt::Checked : Qt::Unchecked;\n\t\t\t} else if (role == Qt::BackgroundRole)\n\t\t\t{\n\t\t\t\tif (index.row() < _env->yellow().size())\n\t\t\t\t{\n\t\t\t\t\treturn QVariant(QColor(255, 255, 128));\n\t\t\t\t} else {\n\t\t\t\t\treturn QVariant(QColor(128, 128, 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn QVariant();\n\t}\n\t\n\tvirtual bool setData(const QModelIndex &index, const QVariant &value, int role)\n\t{\n\t\tRobot *robot = robotForRow(index.row());\n\t\tswitch (index.column())\n\t\t{\n\t\t\tcase 0:\n\t\t\t\trobot->visibility = value.toInt();\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tcase 1:\n\t\t\t\trobot->ballSensorWorks = value.toBool();\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tcase 2:\n\t\t\t\trobot->chargerWorks = value.toBool();\n\t\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tvirtual QVariant headerData(int section, Qt::Orientation orientation, int role) const\n\t{\n\t\tif (role == Qt::DisplayRole)\n\t\t{\n\t\t\tif (orientation == Qt::Horizontal)\n\t\t\t{\n\t\t\t\treturn columnNames[section];\n\t\t\t} else if (_env)\n\t\t\t{\n\t\t\t\treturn QVariant(robotForRow(section)->shell);\n\t\t\t}\n\t\t}\n\t\treturn QVariant();\n\t}\n\nprivate:\n\tEnvironment *_env;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimulatorWindow class\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSimulatorWindow::SimulatorWindow(Environment *env, QWidget* parent):\n\tQMainWindow(parent), _env(env)\n{\n\t_ui.setupUi(this);\n\n\t\/\/ renderer setup\n\t_render = _ui.renderViewWidget;\n\n\t\/\/ connect renderer to simulator\n\tconnect(_env, SIGNAL(addNewRobot(bool,int)), _render, SLOT(addRobot(bool,int)));\n\tconnect(_env, SIGNAL(removeExistingRobot(bool,int)), _render, SLOT(removeRobot(bool,int)));\n\tconnect(_env, SIGNAL(setRobotPose(bool,int,QVector3D,qreal,QVector3D)),\n\t\t\t _render, SLOT(setRobotPose(bool,int,QVector3D,qreal,QVector3D)));\n\n\t\/\/ set up table\n\t_model = new RobotTableModel(_env);\n\t_ui.robotTable->setModel(_model);\n\t_ui.robotTable->resizeColumnsToContents();\n\n\t\/\/ start up environment\n\t_env->init();\n}\n\nvoid SimulatorWindow::on_dropFrame_clicked()\n{\n\tif (_env)\n\t{\n\t\t_env->dropFrame();\n\t}\n}\n\nvoid SimulatorWindow::on_ballVisibility_valueChanged(int value)\n{\n\tif (_env)\n\t{\n\t\t_env->ballVisibility = value;\n\t}\n}\n<commit_msg>fixed problem causing config window to not show up<commit_after>#include \"SimulatorWindow.hpp\"\n#include \"rendering\/SimRenderView.hpp\"\n#include \"Physics\/Environment.hpp\"\n\n#include <QAbstractTableModel>\n\nstatic const QString columnNames[] = {\n\t\"Visibility\",\n\t\"Ball Sensor\",\n\t\"Charger\"\n};\n\nclass RobotTableModel: public QAbstractTableModel\n{\npublic:\n\tRobotTableModel(Environment *env)\n\t: _env(env)\n\t{\n\t\tlayoutChanged();\n\t}\n\t\n\tRobot *robotForRow(int row) const\n\t{\n\t\tconst Environment::RobotMap *map;\n\t\tif (row < _env->yellow().size())\n\t\t{\n\t\t\tmap = &_env->yellow();\n\t\t} else {\n\t\t\trow -= _env->yellow().size();\n\t\t\tmap = &_env->blue();\n\t\t}\n\t\tEnvironment::RobotMap::const_iterator i = map->begin();\n\t\ti += row;\n\t\treturn *i;\n\t}\n\t\n\tvirtual int columnCount(const QModelIndex &parent) const\n\t{\n\t\treturn sizeof(columnNames) \/ sizeof(columnNames[0]);\n\t}\n\t\n\tvirtual int rowCount(const QModelIndex &parent) const\n\t{\n\t\tif (_env)\n\t\t{\n\t\t\treturn _env->blue().size() + _env->yellow().size();\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tvirtual Qt::ItemFlags flags(const QModelIndex &index) const\n\t{\n\t\tQt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\t\tif (index.column() == 0)\n\t\t{\n\t\t\tflags |= Qt::ItemIsEditable;\n\t\t} else {\n\t\t\tflags |= Qt::ItemIsUserCheckable;\n\t\t}\n\t\t\n\t\treturn flags;\n\t}\n\t\n\tvirtual QVariant data(const QModelIndex &index, int role) const\n\t{\n\t\tif (_env)\n\t\t{\n\t\t\tRobot *robot = robotForRow(index.row());\n\t\t\t\n\t\t\tif (index.column() == 0 && (role == Qt::DisplayRole || role == Qt::EditRole))\n\t\t\t{\n\t\t\t\treturn QVariant(robot->visibility);\n\t\t\t} else if (index.column() == 1 && role == Qt::CheckStateRole)\n\t\t\t{\n\t\t\t\treturn robot->ballSensorWorks ? Qt::Checked : Qt::Unchecked;\n\t\t\t} else if (index.column() == 2 && role == Qt::CheckStateRole)\n\t\t\t{\n\t\t\t\treturn robot->chargerWorks ? Qt::Checked : Qt::Unchecked;\n\t\t\t} else if (role == Qt::BackgroundRole)\n\t\t\t{\n\t\t\t\tif (index.row() < _env->yellow().size())\n\t\t\t\t{\n\t\t\t\t\treturn QVariant(QColor(255, 255, 128));\n\t\t\t\t} else {\n\t\t\t\t\treturn QVariant(QColor(128, 128, 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn QVariant();\n\t}\n\t\n\tvirtual bool setData(const QModelIndex &index, const QVariant &value, int role)\n\t{\n\t\tRobot *robot = robotForRow(index.row());\n\t\tswitch (index.column())\n\t\t{\n\t\t\tcase 0:\n\t\t\t\trobot->visibility = value.toInt();\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tcase 1:\n\t\t\t\trobot->ballSensorWorks = value.toBool();\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tcase 2:\n\t\t\t\trobot->chargerWorks = value.toBool();\n\t\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tvirtual QVariant headerData(int section, Qt::Orientation orientation, int role) const\n\t{\n\t\tif (role == Qt::DisplayRole)\n\t\t{\n\t\t\tif (orientation == Qt::Horizontal)\n\t\t\t{\n\t\t\t\treturn columnNames[section];\n\t\t\t} else if (_env)\n\t\t\t{\n\t\t\t\treturn QVariant(robotForRow(section)->shell);\n\t\t\t}\n\t\t}\n\t\treturn QVariant();\n\t}\n\nprivate:\n\tEnvironment *_env;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimulatorWindow class\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSimulatorWindow::SimulatorWindow(Environment *env, QWidget* parent):\n\tQMainWindow(parent), _env(env)\n{\n\t_ui.setupUi(this);\n\n\t\/\/ renderer setup\n\t_render = _ui.renderViewWidget;\n\n\t\/\/ connect renderer to simulator\n\tconnect(_env, SIGNAL(addNewRobot(bool,int)), _render, SLOT(addRobot(bool,int)));\n\tconnect(_env, SIGNAL(removeExistingRobot(bool,int)), _render, SLOT(removeRobot(bool,int)));\n\tconnect(_env, SIGNAL(setRobotPose(bool,int,QVector3D,qreal,QVector3D)),\n\t\t\t _render, SLOT(setRobotPose(bool,int,QVector3D,qreal,QVector3D)));\n\n\t\/\/ start up environment\n\t_env->init();\n\n\t\/\/ set up table\n\t_model = new RobotTableModel(_env);\n\t_ui.robotTable->setModel(_model);\n\t_ui.robotTable->resizeColumnsToContents();\n}\n\nvoid SimulatorWindow::on_dropFrame_clicked()\n{\n\tif (_env)\n\t{\n\t\t_env->dropFrame();\n\t}\n}\n\nvoid SimulatorWindow::on_ballVisibility_valueChanged(int value)\n{\n\tif (_env)\n\t{\n\t\t_env->ballVisibility = value;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"playing_screen.h\"\n\n#include \"game_manager.h\"\n#include \"..\/hmi\/hmi_manager.h\"\n\nvoid PlayingScreen::init() {\n\tball.init();\n\tball.set_queue(true);\n\tpad1.init();\n\tpad1.reverse(true);\n\tpad2.init();\n\n\tif (game.data.last_winner == PLAYER1) {\n\t\tball_position = HMI_WIDTH;\n\t\tball_direction = -1;\n\t} else {\n\t\tball_position = -HMI_WIDTH;\n\t\tball_direction = 1;\n\t}\n\n\tball_speed.init();\n\tball_speed.set_duration(60000);\n\tball_speed.start();\n\n\thmi.log(\"C'est (re)parti !\\n\");\n}\n\nvoid PlayingScreen::animate() {\n\thmi.leds.clear();\n\tball_speed.animate();\n\n\t\/\/ Compute ball speed and new position\n\tfloat real_speed = HMI_DTMS \/ (500.0 + (1 - ball_speed) * 1000.0 - ball_local_speed) * HMI_WIDTH * 2;\n\tball_position += real_speed * ball_direction;\n\tball.set_shiny(HMI_WIDTH - 20 < ball_position || 20 - HMI_WIDTH > ball_position);\n\tball.set_position(ball_position);\n\n\t\/\/ Check for win\n\tif (ball_position < -HMI_WIDTH) {\n\t\tgame.data.last_winner = PLAYER2;\n\t\tgame.data.p2score += 1;\n\t\tgame.show_scores();\n\t}\n\tif (ball_position > HMI_WIDTH) {\n\t\tgame.data.last_winner = PLAYER1;\n\t\tgame.data.p1score += 1;\n\t\tgame.show_scores();\n\t}\n\n\t\/\/ Play pads\n\tif (hmi.btn1.clicked() && pad1.can_fire()) {\n\t\tif (20 - HMI_WIDTH > ball_position) {\n\t\t\tpad1.fire(HMI_WIDTH + ball_position);\n\t\t\tball_direction = 1;\n\t\t\tball_local_speed = 15 * (20 - HMI_WIDTH - ball_position);\n\t\t} else {\n\t\t\tpad1.fire(20);\n\t\t}\n\t}\n\tif (hmi.btn2.clicked() && pad2.can_fire()) {\n\t\tif (HMI_WIDTH - 20 < ball_position) {\n\t\t\tpad2.fire(HMI_WIDTH - ball_position);\n\t\t\tball_direction = -1;\n\t\t\tball_local_speed = 15 * (20 - HMI_WIDTH + ball_position);\n\t\t} else {\n\t\t\tpad2.fire(20);\n\t\t}\n\t}\n\n\t\/\/ Update all\n\tpad1.animate();\n\tpad2.animate();\n\tball.animate();\n}\n<commit_msg>Change some speed constants<commit_after>#include \"playing_screen.h\"\n\n#include \"game_manager.h\"\n#include \"..\/hmi\/hmi_manager.h\"\n\nvoid PlayingScreen::init() {\n\tball.init();\n\tball.set_queue(true);\n\tpad1.init();\n\tpad1.reverse(true);\n\tpad2.init();\n\n\tif (game.data.last_winner == PLAYER1) {\n\t\tball_position = HMI_WIDTH;\n\t\tball_direction = -1;\n\t} else {\n\t\tball_position = -HMI_WIDTH;\n\t\tball_direction = 1;\n\t}\n\n\tball_speed.init();\n\tball_speed.set_duration(60000);\n\tball_speed.start();\n\n\thmi.log(\"C'est (re)parti !\\n\");\n}\n\nvoid PlayingScreen::animate() {\n\thmi.leds.clear();\n\tball_speed.animate();\n\n\t\/\/ Compute ball speed and new position\n\tfloat real_speed = HMI_DTMS \/ (600.0 + (1 - ball_speed) * 1000.0 - ball_local_speed) * HMI_WIDTH * 2;\n\tif (real_speed > HMI_DTMS \/ 500.0 * HMI_WIDTH * 2)\n\t\treal_speed = HMI_DTMS \/ 500.0 * HMI_WIDTH * 2;\n\tball_position += real_speed * ball_direction;\n\tball.set_shiny(\n\t\t(HMI_WIDTH - 20 < ball_position && ball_direction > 0) ||\n\t\t(20 - HMI_WIDTH > ball_position && ball_direction < 0)\n\t);\n\tball.set_position(ball_position);\n\n\t\/\/ Check for win\n\tif (ball_position < -HMI_WIDTH) {\n\t\tgame.data.last_winner = PLAYER2;\n\t\tgame.data.p2score += 1;\n\t\tgame.show_scores();\n\t}\n\tif (ball_position > HMI_WIDTH) {\n\t\tgame.data.last_winner = PLAYER1;\n\t\tgame.data.p1score += 1;\n\t\tgame.show_scores();\n\t}\n\n\t\/\/ Play pads\n\tif (hmi.btn1.clicked() && pad1.can_fire()) {\n\t\tif (20 - HMI_WIDTH > ball_position) {\n\t\t\tpad1.fire(HMI_WIDTH + ball_position);\n\t\t\tball_direction = 1;\n\t\t\tball_local_speed = 50 * (20 - HMI_WIDTH - ball_position);\n\t\t} else {\n\t\t\tpad1.fire(20);\n\t\t}\n\t}\n\tif (hmi.btn2.clicked() && pad2.can_fire()) {\n\t\tif (HMI_WIDTH - 20 < ball_position) {\n\t\t\tpad2.fire(HMI_WIDTH - ball_position);\n\t\t\tball_direction = -1;\n\t\t\tball_local_speed = 50 * (20 - HMI_WIDTH + ball_position);\n\t\t} else {\n\t\t\tpad2.fire(20);\n\t\t}\n\t}\n\n\t\/\/ Update all\n\tpad1.animate();\n\tpad2.animate();\n\tball.animate();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"MediaSet.hpp\"\n\n#include \"utils\/utils.hpp\"\n#include <gst\/gst.h>\n#include <KurentoException.hpp>\n\n\/* This is included to avoid problems with slots and lamdas *\/\n#include <type_traits>\n#include <sigc++\/sigc++.h>\nnamespace sigc\n{\ntemplate <typename Functor>\nstruct functor_trait<Functor, false> {\n typedef decltype (::sigc::mem_fun (std::declval<Functor &> (),\n &Functor::operator() ) ) _intermediate;\n\n typedef typename _intermediate::result_type result_type;\n typedef Functor functor_type;\n};\n}\n\n#define GST_CAT_DEFAULT kurento_media_set\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaSet\"\n\n#define COLLECTOR_INTERVAL 240000\n\nnamespace kurento\n{\n\nMediaSet &\nMediaSet::getMediaSet()\n{\n static MediaSet mediaSet;\n\n return mediaSet;\n}\n\nMediaSet::MediaSet()\n{\n Glib::RefPtr<Glib::TimeoutSource> timeout;\n\n context = Glib::MainContext::create();\n loop = Glib::MainLoop::create (context, true);\n\n thread = Glib::Thread::create ([&] () {\n context->acquire();\n loop->run();\n GST_DEBUG (\"Main loop thread stopped\");\n });\n\n timeout = Glib::TimeoutSource::create (COLLECTOR_INTERVAL);\n timeout->connect ( [&] () -> bool {\n Glib::Threads::RecMutex::Lock lock (mutex);\n auto sessions = sessionInUse;\n\n lock.release();\n\n GST_DEBUG (\"Running garbage collector\");\n\n for (auto it : sessions) {\n if (it.second) {\n lock.acquire();\n sessionInUse[it.first] = false;\n lock.release();\n } else {\n GST_WARNING (\"Session timeout: %s\", it.first.c_str() );\n unrefSession (it.first);\n }\n }\n return true;\n });\n timeout->attach (context);\n}\n\nMediaSet::~MediaSet ()\n{\n Monitor monitor (mutex);\n\n terminated = true;\n\n if (!objectsMap.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (objectsMap.size() ) +\n \" object\/s alive\" << std::endl;\n }\n\n if (!sessionMap.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (sessionMap.size() ) +\n \" session\/s alive\" << std::endl;\n }\n\n if (!sessionInUse.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (sessionInUse.size() ) +\n \" session\/s with timeout\" << std::endl;\n }\n\n childrenMap.clear();\n sessionMap.clear();\n\n if (Glib::Thread::self() != thread) {\n Glib::RefPtr<Glib::IdleSource> source = Glib::IdleSource::create ();\n source->connect (sigc::mem_fun (*this, &MediaSet::finishLoop) );\n source->attach (context);\n\n thread->join();\n } else {\n finishLoop();\n }\n\n threadPool.shutdown (true);\n}\n\nvoid\nMediaSet::executeOnMainLoop (std::function<void () > func, bool force)\n{\n if (terminated || !loop->is_running() ) {\n if (force) {\n func ();\n }\n\n return;\n }\n\n if (Glib::Thread::self() == thread) {\n func ();\n } else {\n Glib::Threads::Cond cond;\n Glib::Threads::Mutex mutex;\n Glib::Threads::Mutex::Lock lock (mutex);\n bool done = false;\n Glib::RefPtr<Glib::IdleSource> source = Glib::IdleSource::create ();\n\n\n source->connect ([&] ()->bool {\n Glib::Threads::Mutex::Lock lock (mutex);\n\n try {\n func ();\n } catch (...) {\n }\n\n done = true;\n cond.signal();\n\n return false;\n });\n\n source->attach (context);\n\n while (!done) {\n cond.wait (mutex);\n }\n }\n}\n\nbool\nMediaSet::finishLoop ()\n{\n loop->quit();\n\n return false;\n}\n\nstd::shared_ptr<MediaObjectImpl>\nMediaSet::ref (MediaObjectImpl *mediaObjectPtr)\n{\n Monitor monitor (mutex);\n\n std::shared_ptr<MediaObjectImpl> mediaObject;\n\n if (mediaObjectPtr == NULL) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Invalid object\");\n }\n\n try {\n mediaObject = std::dynamic_pointer_cast<MediaObjectImpl>\n (mediaObjectPtr->shared_from_this() );\n } catch (std::bad_weak_ptr e) {\n mediaObject = std::shared_ptr<MediaObjectImpl> (mediaObjectPtr, [] (\n MediaObjectImpl * obj) {\n if (!MediaSet::getMediaSet().terminated) {\n MediaSet::getMediaSet().releasePointer (obj);\n } else {\n delete obj;\n }\n });\n }\n\n objectsMap[mediaObject->getId()] = std::weak_ptr<MediaObjectImpl> (mediaObject);\n\n if (mediaObject->getParent() ) {\n std::shared_ptr<MediaObjectImpl> parent = std::dynamic_pointer_cast\n <MediaObjectImpl> (mediaObject->getParent() );\n\n ref (parent.get() );\n childrenMap[parent->getId()][mediaObject->getId()] = mediaObject;\n }\n\n return mediaObject;\n}\n\nvoid\nMediaSet::ref (const std::string &sessionId,\n std::shared_ptr<MediaObjectImpl> mediaObject)\n{\n Monitor monitor (mutex);\n\n keepAliveSession (sessionId, true);\n\n if (mediaObject->getParent() ) {\n ref (sessionId,\n std::dynamic_pointer_cast<MediaObjectImpl> (mediaObject->getParent() ) );\n }\n\n sessionMap[sessionId][mediaObject->getId()] = mediaObject;\n reverseSessionMap[mediaObject->getId()].insert (sessionId);\n ref (mediaObject.get() );\n}\n\nvoid\nMediaSet::keepAliveSession (const std::string &sessionId)\n{\n keepAliveSession (sessionId, false);\n}\n\nvoid\nMediaSet::keepAliveSession (const std::string &sessionId, bool create)\n{\n Monitor monitor (mutex);;\n\n auto it = sessionInUse.find (sessionId);\n\n if (it == sessionInUse.end() ) {\n if (create) {\n sessionInUse[sessionId] = true;\n } else {\n throw KurentoException (INVALID_SESSION, \"Invalid session\");\n }\n } else {\n it->second = true;\n }\n}\n\nvoid\nMediaSet::releaseSession (const std::string &sessionId)\n{\n Monitor monitor (mutex);\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto objects = it->second;\n\n for (auto it2 : objects) {\n release (it2.second);\n }\n }\n\n sessionMap.erase (sessionId);\n sessionInUse.erase (sessionId);\n}\n\nvoid\nMediaSet::unrefSession (const std::string &sessionId)\n{\n Monitor monitor (mutex);\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto objects = it->second;\n\n for (auto it2 : objects) {\n unref (sessionId, it2.second);\n }\n }\n\n sessionMap.erase (sessionId);\n sessionInUse.erase (sessionId);\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId,\n std::shared_ptr< MediaObjectImpl > mediaObject)\n{\n Monitor monitor (mutex);\n\n if (!mediaObject) {\n return;\n }\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto it2 = it->second.find (mediaObject->getId() );\n\n if (it2 == it->second.end() ) {\n return;\n }\n\n it->second.erase (it2);\n\n if (it->second.size() == 0) {\n unrefSession (sessionId);\n }\n }\n\n auto it3 = reverseSessionMap.find (mediaObject->getId() );\n\n if (it3 != reverseSessionMap.end() ) {\n it3->second.erase (sessionId);\n\n if (it3->second.empty() ) {\n std::shared_ptr<MediaObjectImpl> parent;\n\n \/\/ Object has been removed from all the sessions, remove it from childrenMap\n childrenMap.erase (mediaObject->getId() );\n\n parent = std::dynamic_pointer_cast<MediaObjectImpl> (mediaObject->getParent() );\n\n if (parent) {\n childrenMap[parent->getId()].erase (mediaObject->getId() );\n }\n\n auto childrenIt = childrenMap.find (mediaObject->getId() );\n\n if (childrenIt != childrenMap.end() ) {\n auto childMap = childrenIt->second;\n\n for (auto child : childMap) {\n unref (sessionId, child.second);\n }\n }\n }\n }\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId,\n const std::string &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> object;\n\n try {\n object = getMediaObject (mediaObjectRef);\n } catch (KurentoException e) {\n return;\n }\n\n unref (sessionId, object);\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId, const uint64_t &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> object;\n\n try {\n object = getMediaObject (mediaObjectRef);\n } catch (KurentoException e) {\n return;\n }\n\n unref (sessionId, object);\n}\n\nvoid MediaSet::releasePointer (MediaObjectImpl *mediaObject)\n{\n Monitor monitor (mutex);\n\n objectsMap.erase (mediaObject->getId() );\n\n if (!terminated) {\n threadPool.push ( [mediaObject] () {\n GST_DEBUG (\"Destroying %s\", mediaObject->getIdStr().c_str() );\n delete mediaObject;\n });\n } else {\n GST_DEBUG (\"Thread pool finished, destroying on the same thread %s\",\n mediaObject->getIdStr().c_str() );\n delete mediaObject;\n }\n}\n\nvoid MediaSet::release (std::shared_ptr< MediaObjectImpl > mediaObject)\n{\n Monitor monitor (mutex);\n\n auto it = reverseSessionMap.find (mediaObject->getId() );\n\n if (it == reverseSessionMap.end() ) {\n \/* Already released *\/\n return;\n }\n\n auto sessions = it->second;\n\n for (auto it2 : sessions) {\n unref (it2, mediaObject);\n }\n\n objectsMap.erase (mediaObject->getId() );\n}\n\nvoid MediaSet::release (const std::string &mediaObjectRef)\n{\n try {\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n release (obj);\n } catch (...) {\n \/* Do not raise exception if it is already released*\/\n }\n}\n\nvoid MediaSet::release (const uint64_t &mediaObjectRef)\n{\n try {\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n release (obj);\n } catch (...) {\n \/* Do not raise exception if it is already released*\/\n }\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &mediaObjectRef)\n{\n uint64_t objectRef;\n\n try {\n#if __WORDSIZE == 64\n objectRef = std::stoul (mediaObjectRef);\n#else\n objectRef = std::stoull (mediaObjectRef);\n#endif\n } catch (...) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND,\n \"Invalid object reference\");\n }\n\n return getMediaObject (objectRef);\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const uint64_t &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> objectLocked;\n Monitor monitor (mutex);\n\n auto it = objectsMap.find (mediaObjectRef);\n\n if (it == objectsMap.end() ) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n try {\n objectLocked = it->second.lock();\n } catch (...) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n if (!objectLocked) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n return objectLocked;\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &sessionId,\n const std::string &mediaObjectRef)\n{\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n ref (sessionId, obj);\n return obj;\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &sessionId,\n const uint64_t &mediaObjectRef)\n{\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n ref (sessionId, obj);\n return obj;\n}\n\nMediaSet::Monitor::Monitor (Glib::Threads::RecMutex &mutex) : mutex (mutex)\n{\n mutex.lock();\n}\n\nMediaSet::Monitor::~Monitor()\n{\n mutex.unlock();\n}\n\nvoid MediaSet::deleter (MediaObjectImpl *mo)\n{\n GST_ERROR (\"Deleting\");\n}\n\nMediaSet::StaticConstructor MediaSet::staticConstructor;\n\nMediaSet::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/\/ kurento\n<commit_msg>MediaSet: Do not erase element from children map before unref its children<commit_after>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"MediaSet.hpp\"\n\n#include \"utils\/utils.hpp\"\n#include <gst\/gst.h>\n#include <KurentoException.hpp>\n\n\/* This is included to avoid problems with slots and lamdas *\/\n#include <type_traits>\n#include <sigc++\/sigc++.h>\nnamespace sigc\n{\ntemplate <typename Functor>\nstruct functor_trait<Functor, false> {\n typedef decltype (::sigc::mem_fun (std::declval<Functor &> (),\n &Functor::operator() ) ) _intermediate;\n\n typedef typename _intermediate::result_type result_type;\n typedef Functor functor_type;\n};\n}\n\n#define GST_CAT_DEFAULT kurento_media_set\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaSet\"\n\n#define COLLECTOR_INTERVAL 240000\n\nnamespace kurento\n{\n\nMediaSet &\nMediaSet::getMediaSet()\n{\n static MediaSet mediaSet;\n\n return mediaSet;\n}\n\nMediaSet::MediaSet()\n{\n Glib::RefPtr<Glib::TimeoutSource> timeout;\n\n context = Glib::MainContext::create();\n loop = Glib::MainLoop::create (context, true);\n\n thread = Glib::Thread::create ([&] () {\n context->acquire();\n loop->run();\n GST_DEBUG (\"Main loop thread stopped\");\n });\n\n timeout = Glib::TimeoutSource::create (COLLECTOR_INTERVAL);\n timeout->connect ( [&] () -> bool {\n Glib::Threads::RecMutex::Lock lock (mutex);\n auto sessions = sessionInUse;\n\n lock.release();\n\n GST_DEBUG (\"Running garbage collector\");\n\n for (auto it : sessions) {\n if (it.second) {\n lock.acquire();\n sessionInUse[it.first] = false;\n lock.release();\n } else {\n GST_WARNING (\"Session timeout: %s\", it.first.c_str() );\n unrefSession (it.first);\n }\n }\n return true;\n });\n timeout->attach (context);\n}\n\nMediaSet::~MediaSet ()\n{\n Monitor monitor (mutex);\n\n terminated = true;\n\n if (!objectsMap.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (objectsMap.size() ) +\n \" object\/s alive\" << std::endl;\n }\n\n if (!sessionMap.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (sessionMap.size() ) +\n \" session\/s alive\" << std::endl;\n }\n\n if (!sessionInUse.empty() ) {\n std::cerr << \"Warning: Still \" + std::to_string (sessionInUse.size() ) +\n \" session\/s with timeout\" << std::endl;\n }\n\n childrenMap.clear();\n sessionMap.clear();\n\n if (Glib::Thread::self() != thread) {\n Glib::RefPtr<Glib::IdleSource> source = Glib::IdleSource::create ();\n source->connect (sigc::mem_fun (*this, &MediaSet::finishLoop) );\n source->attach (context);\n\n thread->join();\n } else {\n finishLoop();\n }\n\n threadPool.shutdown (true);\n}\n\nvoid\nMediaSet::executeOnMainLoop (std::function<void () > func, bool force)\n{\n if (terminated || !loop->is_running() ) {\n if (force) {\n func ();\n }\n\n return;\n }\n\n if (Glib::Thread::self() == thread) {\n func ();\n } else {\n Glib::Threads::Cond cond;\n Glib::Threads::Mutex mutex;\n Glib::Threads::Mutex::Lock lock (mutex);\n bool done = false;\n Glib::RefPtr<Glib::IdleSource> source = Glib::IdleSource::create ();\n\n\n source->connect ([&] ()->bool {\n Glib::Threads::Mutex::Lock lock (mutex);\n\n try {\n func ();\n } catch (...) {\n }\n\n done = true;\n cond.signal();\n\n return false;\n });\n\n source->attach (context);\n\n while (!done) {\n cond.wait (mutex);\n }\n }\n}\n\nbool\nMediaSet::finishLoop ()\n{\n loop->quit();\n\n return false;\n}\n\nstd::shared_ptr<MediaObjectImpl>\nMediaSet::ref (MediaObjectImpl *mediaObjectPtr)\n{\n Monitor monitor (mutex);\n\n std::shared_ptr<MediaObjectImpl> mediaObject;\n\n if (mediaObjectPtr == NULL) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Invalid object\");\n }\n\n try {\n mediaObject = std::dynamic_pointer_cast<MediaObjectImpl>\n (mediaObjectPtr->shared_from_this() );\n } catch (std::bad_weak_ptr e) {\n mediaObject = std::shared_ptr<MediaObjectImpl> (mediaObjectPtr, [] (\n MediaObjectImpl * obj) {\n if (!MediaSet::getMediaSet().terminated) {\n MediaSet::getMediaSet().releasePointer (obj);\n } else {\n delete obj;\n }\n });\n }\n\n objectsMap[mediaObject->getId()] = std::weak_ptr<MediaObjectImpl> (mediaObject);\n\n if (mediaObject->getParent() ) {\n std::shared_ptr<MediaObjectImpl> parent = std::dynamic_pointer_cast\n <MediaObjectImpl> (mediaObject->getParent() );\n\n ref (parent.get() );\n childrenMap[parent->getId()][mediaObject->getId()] = mediaObject;\n }\n\n return mediaObject;\n}\n\nvoid\nMediaSet::ref (const std::string &sessionId,\n std::shared_ptr<MediaObjectImpl> mediaObject)\n{\n Monitor monitor (mutex);\n\n keepAliveSession (sessionId, true);\n\n if (mediaObject->getParent() ) {\n ref (sessionId,\n std::dynamic_pointer_cast<MediaObjectImpl> (mediaObject->getParent() ) );\n }\n\n sessionMap[sessionId][mediaObject->getId()] = mediaObject;\n reverseSessionMap[mediaObject->getId()].insert (sessionId);\n ref (mediaObject.get() );\n}\n\nvoid\nMediaSet::keepAliveSession (const std::string &sessionId)\n{\n keepAliveSession (sessionId, false);\n}\n\nvoid\nMediaSet::keepAliveSession (const std::string &sessionId, bool create)\n{\n Monitor monitor (mutex);;\n\n auto it = sessionInUse.find (sessionId);\n\n if (it == sessionInUse.end() ) {\n if (create) {\n sessionInUse[sessionId] = true;\n } else {\n throw KurentoException (INVALID_SESSION, \"Invalid session\");\n }\n } else {\n it->second = true;\n }\n}\n\nvoid\nMediaSet::releaseSession (const std::string &sessionId)\n{\n Monitor monitor (mutex);\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto objects = it->second;\n\n for (auto it2 : objects) {\n release (it2.second);\n }\n }\n\n sessionMap.erase (sessionId);\n sessionInUse.erase (sessionId);\n}\n\nvoid\nMediaSet::unrefSession (const std::string &sessionId)\n{\n Monitor monitor (mutex);\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto objects = it->second;\n\n for (auto it2 : objects) {\n unref (sessionId, it2.second);\n }\n }\n\n sessionMap.erase (sessionId);\n sessionInUse.erase (sessionId);\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId,\n std::shared_ptr< MediaObjectImpl > mediaObject)\n{\n Monitor monitor (mutex);\n\n if (!mediaObject) {\n return;\n }\n\n auto it = sessionMap.find (sessionId);\n\n if (it != sessionMap.end() ) {\n auto it2 = it->second.find (mediaObject->getId() );\n\n if (it2 == it->second.end() ) {\n return;\n }\n\n it->second.erase (it2);\n\n if (it->second.size() == 0) {\n unrefSession (sessionId);\n }\n }\n\n auto it3 = reverseSessionMap.find (mediaObject->getId() );\n\n if (it3 != reverseSessionMap.end() ) {\n it3->second.erase (sessionId);\n\n if (it3->second.empty() ) {\n std::shared_ptr<MediaObjectImpl> parent;\n\n parent = std::dynamic_pointer_cast<MediaObjectImpl> (mediaObject->getParent() );\n\n if (parent) {\n childrenMap[parent->getId()].erase (mediaObject->getId() );\n }\n\n auto childrenIt = childrenMap.find (mediaObject->getId() );\n\n if (childrenIt != childrenMap.end() ) {\n auto childMap = childrenIt->second;\n\n for (auto child : childMap) {\n unref (sessionId, child.second);\n }\n }\n\n childrenMap.erase (mediaObject->getId() );\n }\n }\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId,\n const std::string &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> object;\n\n try {\n object = getMediaObject (mediaObjectRef);\n } catch (KurentoException e) {\n return;\n }\n\n unref (sessionId, object);\n}\n\nvoid\nMediaSet::unref (const std::string &sessionId, const uint64_t &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> object;\n\n try {\n object = getMediaObject (mediaObjectRef);\n } catch (KurentoException e) {\n return;\n }\n\n unref (sessionId, object);\n}\n\nvoid MediaSet::releasePointer (MediaObjectImpl *mediaObject)\n{\n Monitor monitor (mutex);\n\n objectsMap.erase (mediaObject->getId() );\n\n if (!terminated) {\n threadPool.push ( [mediaObject] () {\n GST_DEBUG (\"Destroying %s\", mediaObject->getIdStr().c_str() );\n delete mediaObject;\n });\n } else {\n GST_DEBUG (\"Thread pool finished, destroying on the same thread %s\",\n mediaObject->getIdStr().c_str() );\n delete mediaObject;\n }\n}\n\nvoid MediaSet::release (std::shared_ptr< MediaObjectImpl > mediaObject)\n{\n Monitor monitor (mutex);\n\n auto it = reverseSessionMap.find (mediaObject->getId() );\n\n if (it == reverseSessionMap.end() ) {\n \/* Already released *\/\n return;\n }\n\n auto sessions = it->second;\n\n for (auto it2 : sessions) {\n unref (it2, mediaObject);\n }\n\n objectsMap.erase (mediaObject->getId() );\n}\n\nvoid MediaSet::release (const std::string &mediaObjectRef)\n{\n try {\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n release (obj);\n } catch (...) {\n \/* Do not raise exception if it is already released*\/\n }\n}\n\nvoid MediaSet::release (const uint64_t &mediaObjectRef)\n{\n try {\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n release (obj);\n } catch (...) {\n \/* Do not raise exception if it is already released*\/\n }\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &mediaObjectRef)\n{\n uint64_t objectRef;\n\n try {\n#if __WORDSIZE == 64\n objectRef = std::stoul (mediaObjectRef);\n#else\n objectRef = std::stoull (mediaObjectRef);\n#endif\n } catch (...) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND,\n \"Invalid object reference\");\n }\n\n return getMediaObject (objectRef);\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const uint64_t &mediaObjectRef)\n{\n std::shared_ptr <MediaObjectImpl> objectLocked;\n Monitor monitor (mutex);\n\n auto it = objectsMap.find (mediaObjectRef);\n\n if (it == objectsMap.end() ) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n try {\n objectLocked = it->second.lock();\n } catch (...) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n if (!objectLocked) {\n throw KurentoException (MEDIA_OBJECT_NOT_FOUND, \"Object not found\");\n }\n\n return objectLocked;\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &sessionId,\n const std::string &mediaObjectRef)\n{\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n ref (sessionId, obj);\n return obj;\n}\n\nstd::shared_ptr< MediaObjectImpl >\nMediaSet::getMediaObject (const std::string &sessionId,\n const uint64_t &mediaObjectRef)\n{\n std::shared_ptr< MediaObjectImpl > obj = getMediaObject (mediaObjectRef);\n\n ref (sessionId, obj);\n return obj;\n}\n\nMediaSet::Monitor::Monitor (Glib::Threads::RecMutex &mutex) : mutex (mutex)\n{\n mutex.lock();\n}\n\nMediaSet::Monitor::~Monitor()\n{\n mutex.unlock();\n}\n\nvoid MediaSet::deleter (MediaObjectImpl *mo)\n{\n GST_ERROR (\"Deleting\");\n}\n\nMediaSet::StaticConstructor MediaSet::staticConstructor;\n\nMediaSet::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/\/ kurento\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) Lewis Baker\n\/\/ Licenced under MIT license. See LICENSE.txt for details.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cppcoro\/file.hpp>\n#include <cppcoro\/io_service.hpp>\n\n#include <system_error>\n#include <cassert>\n\n#if CPPCORO_OS_WINNT\n# define WIN32_LEAN_AND_MEAN\n# include <Windows.h>\n#endif\n\ncppcoro::file::~file()\n{}\n\nstd::uint64_t cppcoro::file::size() const\n{\n#if CPPCORO_OS_WINNT\n\tLARGE_INTEGER size;\n\tBOOL ok = ::GetFileSizeEx(m_fileHandle.handle(), &size);\n\tif (!ok)\n\t{\n\t\tDWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error getting file size: GetFileSizeEx\"\n\t\t};\n\t}\n\n\treturn size.QuadPart;\n#endif\n}\n\ncppcoro::file::file(detail::win32::safe_handle&& fileHandle) noexcept\n\t: m_fileHandle(std::move(fileHandle))\n{\n}\n\ncppcoro::detail::win32::safe_handle cppcoro::file::open(\n\tdetail::win32::dword_t fileAccess,\n\tio_context& ioContext,\n\tconst std::experimental::filesystem::path& path,\n\tfile_open_mode openMode,\n\tfile_share_mode shareMode,\n\tfile_buffering_mode bufferingMode)\n{\n\tDWORD flags = FILE_FLAG_OVERLAPPED;\n\tif ((bufferingMode & file_buffering_mode::random_access) == file_buffering_mode::random_access)\n\t{\n\t\tflags |= FILE_FLAG_RANDOM_ACCESS;\n\t}\n\tif ((bufferingMode & file_buffering_mode::sequential) == file_buffering_mode::sequential)\n\t{\n\t\tflags |= FILE_FLAG_SEQUENTIAL_SCAN;\n\t}\n\tif ((bufferingMode & file_buffering_mode::write_through) == file_buffering_mode::write_through)\n\t{\n\t\tflags |= FILE_FLAG_WRITE_THROUGH;\n\t}\n\tif ((bufferingMode & file_buffering_mode::temporary) == file_buffering_mode::temporary)\n\t{\n\t\tflags |= FILE_ATTRIBUTE_TEMPORARY;\n\t}\n\tif ((bufferingMode & file_buffering_mode::unbuffered) == file_buffering_mode::unbuffered)\n\t{\n\t\tflags |= FILE_FLAG_NO_BUFFERING;\n\t}\n\n\tDWORD shareFlags = 0;\n\tif ((shareMode & file_share_mode::read) == file_share_mode::read)\n\t{\n\t\tshareFlags |= FILE_SHARE_READ;\n\t}\n\tif ((shareMode & file_share_mode::write) == file_share_mode::write)\n\t{\n\t\tshareFlags |= FILE_SHARE_WRITE;\n\t}\n\tif ((shareMode & file_share_mode::delete_) == file_share_mode::delete_)\n\t{\n\t\tshareFlags |= FILE_SHARE_DELETE;\n\t}\n\n\tDWORD creationDisposition = 0;\n\tswitch (openMode)\n\t{\n\tcase file_open_mode::create_or_open:\n\t\tcreationDisposition = OPEN_ALWAYS;\n\t\tbreak;\n\tcase file_open_mode::create_always:\n\t\tcreationDisposition = CREATE_ALWAYS;\n\t\tbreak;\n\tcase file_open_mode::create_new:\n\t\tcreationDisposition = CREATE_NEW;\n\t\tbreak;\n\tcase file_open_mode::open_existing:\n\t\tcreationDisposition = OPEN_EXISTING;\n\t\tbreak;\n\tcase file_open_mode::truncate_existing:\n\t\tcreationDisposition = TRUNCATE_EXISTING;\n\t\tbreak;\n\t}\n\n\t\/\/ Open the file\n\tdetail::win32::safe_handle fileHandle(\n\t\t::CreateFileW(\n\t\t\tpath.c_str(),\n\t\t\tfileAccess,\n\t\t\tshareFlags,\n\t\t\tnullptr,\n\t\t\tcreationDisposition,\n\t\t\tflags,\n\t\t\tnullptr));\n\tif (fileHandle.handle() == INVALID_HANDLE_VALUE)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: CreateFileW\"\n\t\t};\n\t}\n\n\t\/\/ Associate with the I\/O service's completion port.\n\tconst HANDLE result = ::CreateIoCompletionPort(\n\t\tfileHandle.handle(),\n\t\tioContext.native_iocp_handle(),\n\t\t0,\n\t\t0);\n\tif (result == nullptr)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: CreateIoCompletionPort\"\n\t\t};\n\t}\n\n\t\/\/ Configure I\/O operations to avoid dispatching a completion event\n\t\/\/ to the I\/O service if the operation completes synchronously.\n\t\/\/ This avoids unnecessary suspension\/resuption of the awaiting coroutine.\n\tconst BOOL ok = ::SetFileCompletionNotificationModes(\n\t\tfileHandle.handle(),\n\t\tFILE_SKIP_COMPLETION_PORT_ON_SUCCESS |\n\t\tFILE_SKIP_SET_EVENT_ON_HANDLE);\n\tif (!ok)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: SetFileCompletionNotificationModes\"\n\t\t};\n\t}\n\n\treturn std::move(fileHandle);\n}\n<commit_msg>Fix usage of filesystem::path under libc++.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) Lewis Baker\n\/\/ Licenced under MIT license. See LICENSE.txt for details.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cppcoro\/file.hpp>\n#include <cppcoro\/io_service.hpp>\n\n#include <system_error>\n#include <cassert>\n\n#if CPPCORO_OS_WINNT\n# define WIN32_LEAN_AND_MEAN\n# include <Windows.h>\n#endif\n\ncppcoro::file::~file()\n{}\n\nstd::uint64_t cppcoro::file::size() const\n{\n#if CPPCORO_OS_WINNT\n\tLARGE_INTEGER size;\n\tBOOL ok = ::GetFileSizeEx(m_fileHandle.handle(), &size);\n\tif (!ok)\n\t{\n\t\tDWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error getting file size: GetFileSizeEx\"\n\t\t};\n\t}\n\n\treturn size.QuadPart;\n#endif\n}\n\ncppcoro::file::file(detail::win32::safe_handle&& fileHandle) noexcept\n\t: m_fileHandle(std::move(fileHandle))\n{\n}\n\ncppcoro::detail::win32::safe_handle cppcoro::file::open(\n\tdetail::win32::dword_t fileAccess,\n\tio_context& ioContext,\n\tconst std::experimental::filesystem::path& path,\n\tfile_open_mode openMode,\n\tfile_share_mode shareMode,\n\tfile_buffering_mode bufferingMode)\n{\n\tDWORD flags = FILE_FLAG_OVERLAPPED;\n\tif ((bufferingMode & file_buffering_mode::random_access) == file_buffering_mode::random_access)\n\t{\n\t\tflags |= FILE_FLAG_RANDOM_ACCESS;\n\t}\n\tif ((bufferingMode & file_buffering_mode::sequential) == file_buffering_mode::sequential)\n\t{\n\t\tflags |= FILE_FLAG_SEQUENTIAL_SCAN;\n\t}\n\tif ((bufferingMode & file_buffering_mode::write_through) == file_buffering_mode::write_through)\n\t{\n\t\tflags |= FILE_FLAG_WRITE_THROUGH;\n\t}\n\tif ((bufferingMode & file_buffering_mode::temporary) == file_buffering_mode::temporary)\n\t{\n\t\tflags |= FILE_ATTRIBUTE_TEMPORARY;\n\t}\n\tif ((bufferingMode & file_buffering_mode::unbuffered) == file_buffering_mode::unbuffered)\n\t{\n\t\tflags |= FILE_FLAG_NO_BUFFERING;\n\t}\n\n\tDWORD shareFlags = 0;\n\tif ((shareMode & file_share_mode::read) == file_share_mode::read)\n\t{\n\t\tshareFlags |= FILE_SHARE_READ;\n\t}\n\tif ((shareMode & file_share_mode::write) == file_share_mode::write)\n\t{\n\t\tshareFlags |= FILE_SHARE_WRITE;\n\t}\n\tif ((shareMode & file_share_mode::delete_) == file_share_mode::delete_)\n\t{\n\t\tshareFlags |= FILE_SHARE_DELETE;\n\t}\n\n\tDWORD creationDisposition = 0;\n\tswitch (openMode)\n\t{\n\tcase file_open_mode::create_or_open:\n\t\tcreationDisposition = OPEN_ALWAYS;\n\t\tbreak;\n\tcase file_open_mode::create_always:\n\t\tcreationDisposition = CREATE_ALWAYS;\n\t\tbreak;\n\tcase file_open_mode::create_new:\n\t\tcreationDisposition = CREATE_NEW;\n\t\tbreak;\n\tcase file_open_mode::open_existing:\n\t\tcreationDisposition = OPEN_EXISTING;\n\t\tbreak;\n\tcase file_open_mode::truncate_existing:\n\t\tcreationDisposition = TRUNCATE_EXISTING;\n\t\tbreak;\n\t}\n\n\t\/\/ Open the file\n\tdetail::win32::safe_handle fileHandle(\n\t\t::CreateFileW(\n\t\t\tpath.wstring().c_str(),\n\t\t\tfileAccess,\n\t\t\tshareFlags,\n\t\t\tnullptr,\n\t\t\tcreationDisposition,\n\t\t\tflags,\n\t\t\tnullptr));\n\tif (fileHandle.handle() == INVALID_HANDLE_VALUE)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: CreateFileW\"\n\t\t};\n\t}\n\n\t\/\/ Associate with the I\/O service's completion port.\n\tconst HANDLE result = ::CreateIoCompletionPort(\n\t\tfileHandle.handle(),\n\t\tioContext.native_iocp_handle(),\n\t\t0,\n\t\t0);\n\tif (result == nullptr)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: CreateIoCompletionPort\"\n\t\t};\n\t}\n\n\t\/\/ Configure I\/O operations to avoid dispatching a completion event\n\t\/\/ to the I\/O service if the operation completes synchronously.\n\t\/\/ This avoids unnecessary suspension\/resuption of the awaiting coroutine.\n\tconst BOOL ok = ::SetFileCompletionNotificationModes(\n\t\tfileHandle.handle(),\n\t\tFILE_SKIP_COMPLETION_PORT_ON_SUCCESS |\n\t\tFILE_SKIP_SET_EVENT_ON_HANDLE);\n\tif (!ok)\n\t{\n\t\tconst DWORD errorCode = ::GetLastError();\n\t\tthrow std::system_error\n\t\t{\n\t\t\tstatic_cast<int>(errorCode),\n\t\t\tstd::system_category(),\n\t\t\t\"error opening file: SetFileCompletionNotificationModes\"\n\t\t};\n\t}\n\n\treturn std::move(fileHandle);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n#include <string.h>\n#include <iostream>\n#include <CGAL\/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL\/Point_3.h>\n#include <CGAL\/Delaunay_triangulation_3.h>\n#include \"rply\/rply.h\"\n\n\nusing namespace std;\nusing namespace CGAL;\n\n\ntypedef Exact_predicates_inexact_constructions_kernel K;\ntypedef Point_3<K> Point;\ntypedef Delaunay_triangulation_3<K> Delaunay;\n\n\/\/ PLC:\nmap <unsigned, Point> plcVertices; \/\/ mapping between vertex coordinates and corresponding unique id\n\nclass TriangleFace\n{\n\tpublic:\n\t\tunsigned int vertexIds[3];\n}tempFace;\n\n\nclass TetrahedronCell\n{\n\tpublic:\n\t\tunsigned int vertexIds[4];\n}tempTet;\n\nlist <TriangleFace> plcFaces; \/\/ contains ids of vertices\/points making the triangle\n\n\/\/ Delaunay tetrahedralization:\nDelaunay DT;\n\n\/\/ CDT: \nmap <unsigned, Point> cdtVertices;\nlist <TriangleFace> cdtTets; \/\/ contains ids of vertices making tetrahedron\n\nstatic unsigned tempPoint[3];\nunsigned int dimensionId = 0;\nstatic unsigned pointId = 0;\n\nstatic int vertex_cb(p_ply_argument argument) \n{\t\n\tlong eol;\n\tply_get_argument_user_data(argument, NULL, &eol);\n\ttempPoint[dimensionId++] = ply_get_argument_value(argument);\n\t\n\t\/\/ insert the vertex into plcVertex\n\tif (eol)\n\t{\n\t\tplcVertices[pointId++] = Point(tempPoint[0],tempPoint[1],tempPoint[2]);\n\t\tdimensionId = 0;\n\t}\n}\n\nstatic int face_cb(p_ply_argument argument) \n{\n\tlong length, value_index;\n\n\tply_get_argument_property(argument, NULL, &length, &value_index);\n\n switch (value_index) \n\t{\n \tcase 0:\n\t case 1: \n \t\ttempFace.vertexIds[pointId++] = ply_get_argument_value(argument);\n\t break;\n \tcase 2:\t\n\t\t\ttempFace.vertexIds[pointId] = ply_get_argument_value(argument);\n\t\t\tpointId = 0;\t\t\t\t\n\t\t\tplcFaces.push_front(tempFace);\n\t break;\n \tdefault: \n \tcout << \"Invalid number of points in a face specified :(\";\n\t\t\tbreak;\n } \n \n}\n\n\/\/ reads input PLC\nvoid readPLCInput()\n{\n\t\/\/ read PLY file(assumed to contain the PLC)\n\tstring fileName;\n\n\tcout << \"\\nPlease enter input filename:\\t\";\n\tcin >> fileName;\n\t\n\tp_ply inputPLY = ply_open(fileName.c_str(), NULL, 0, NULL);\n \t\n\tif (!inputPLY) exit(0);\n\n if (!ply_read_header(inputPLY)) exit(0);\n\t\n\tif (!ply_read(inputPLY))\n\t{\n\t\tcout << \"Cannot read the PLY file :(\";\n\t\texit(0);\n\t}\n\n\t\/\/ Initialize plcVertex and plcFaces\n \tply_set_read_cb(inputPLY, \"vertex\", \"x\", vertex_cb, NULL, 0);\t\n\tply_set_read_cb(inputPLY, \"vertex\", \"y\", vertex_cb, NULL, 0);\n\tply_set_read_cb(inputPLY, \"vertex\", \"z\", vertex_cb, NULL, 1);\n\n\tply_set_read_cb(inputPLY, \"face\", \"vertex_indices\", face_cb, NULL, 0); \n\n\tply_close(inputPLY);\n\t\n}\n\n\/\/ computes the initial delaunay tetrahedralization\nvoid computeInitialDelaunayTetrahedralization()\n{\t\n\t\n\tlist <Point> tempPointList;\n\tunsigned int i = 0;\n\n\tfor (map<unsigned, Point>::iterator pit = plcVertices.begin(); pit != plcVertices.end(); pit++, i++)\n\t\ttempPointList.push_front(plcVertices.find(i)->second);\n\n \tDT.insert(tempPointList.begin(), tempPointList.end());\n\n\tcout << \"\\nInitial Delaunay tetrahedralization computed!!\";\n}\n*\/\n\nclass DegenerateVertexSetCandidate\n{\n\tVertex_handle degenSetVertex[5];\t\n};\n\n\n\/\/ returns true if given vertices are co-spherical\nbool areCospherical()\n{\n\n}\n\n\/\/ removes duplicate vertex sets from global degeneracyQueue\nvoid removeDuplicateDegenracies()\n{\n\n}\n\n\n\/\/ finds all local degeneracies in DT and adds them to a global queue\nvoid addLocalDegeneraciesToQueue(queue<DegenerateVertexSetCandidate> degeneracyQueue)\n{\n\t\n\tDegenerateVertexSetCandidate degenerateSet;\n\t\n\tfor (delaunay::Finite_cell_iterator cellIter = DT.finite_cells_begin(); cellIter != DT.finite_cells_end(); cellIter++)\n\t{\n\t\tfor (unsigned int n = 0; n < 4; n++)\n\t\t\tdegenerateSet.degenSetVertex[n] = cellIter->vertex(n);\n\n\t\tfor (unsigned int j = 0; j < 4; j++)\n\t\t\tfor (unsigned int k = 0; k < 4; k++)\n\t\t\t\t{\n\t\t\t\t\tif ((cellId->neighbor(j))->neighbor(k) == cellId)\n\t\t\t\t\t\tdegenerateSet.degenSetVertex[4] = (cellIter->neighbor)->vertex(k);\t\t\n\t\t\t\t\t\t\n\t\t\t\t\tif (areCospherical(degenerateSet))\n\t\t\t\t\t\tdegeneracyQueue.push_front(degenerateSet);\t\n\t\t\t\t}\n\t}\n\n\tremoveDuplicateDegeneracies(); \n}\n\n\n\n\/\/ removes local degeneracies from Delaunay tetrahedralization\nvoid removeLocalDegeneracies()\n{\n\t\n\tcout << \"\\nStarting local degeneracy removal...\";\n\n\t\/\/ compute all local degeneracies in DT and add them to Q\n\tqueue<DegenerateVertexSetCandidate> degeneracyQueue;\n\taddLocalDegeneraciesToQueue(degeneracyQueue);\n\n\t\/\/ repeat while Q != NULL\t\n\twhile (degenercyQueue.size() != 0)\n\t\tfor (queue<>::iterator qIter = degeneracyQueue.begin(); qIter != degeneracyQueue.end(); qIter++)\n\t\t\t{\n\t\t\t\tif (isDegeneracyRemovable(qIter))\n\t\t\t\t\tperturbRemove(qIter, degeneracyQueue); \n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tVertex vb;\t\n\t\t\t\t\tcomputeBreakPoint(vb, qIter, degeneracyQueue);\n\t\t\t\t\tif (isEncroachingPLC(vb))\n\t\t\t\t\t\tboundaryProtection(vb);\n\t\t\t\t\telse\n\t\t\t\t\t\tinputPLCVertices.push(vb);\t\t\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t}\n\n\tcout << \"Local degeneracy removal completed\";\n}\n\n\n\/*\n\/\/ recovers the constraint faces\nvoid recoverConstraintFaces()\n{\n\t\n}\n\n\/\/ main procedure\nint main()\n{\n\treadPLCInput();\n\tcomputeInitialDelaunayTetrahedralization();\n\tremoveLocalDegeneracies();\n\trecoverConstraintFaces();\n return 0;\n}\n*\/\n<commit_msg>added function to perform co-spherical test<commit_after>\/*\n#include <string.h>\n#include <iostream>\n#include <CGAL\/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL\/Point_3.h>\n#include <CGAL\/Delaunay_triangulation_3.h>\n#include \"rply\/rply.h\"\n\n\nusing namespace std;\nusing namespace CGAL;\n\n\ntypedef Exact_predicates_inexact_constructions_kernel K;\ntypedef Point_3<K> Point;\ntypedef Delaunay_triangulation_3<K> Delaunay;\n\n\/\/ PLC:\nmap <unsigned, Point> plcVertices; \/\/ mapping between vertex coordinates and corresponding unique id\n\nclass TriangleFace\n{\n\tpublic:\n\t\tunsigned int vertexIds[3];\n}tempFace;\n\n\nclass TetrahedronCell\n{\n\tpublic:\n\t\tunsigned int vertexIds[4];\n}tempTet;\n\nlist <TriangleFace> plcFaces; \/\/ contains ids of vertices\/points making the triangle\n\n\/\/ Delaunay tetrahedralization:\nDelaunay DT;\n\n\/\/ CDT: \nmap <unsigned, Point> cdtVertices;\nlist <TriangleFace> cdtTets; \/\/ contains ids of vertices making tetrahedron\n\nstatic unsigned tempPoint[3];\nunsigned int dimensionId = 0;\nstatic unsigned pointId = 0;\n\nstatic int vertex_cb(p_ply_argument argument) \n{\t\n\tlong eol;\n\tply_get_argument_user_data(argument, NULL, &eol);\n\ttempPoint[dimensionId++] = ply_get_argument_value(argument);\n\t\n\t\/\/ insert the vertex into plcVertex\n\tif (eol)\n\t{\n\t\tplcVertices[pointId++] = Point(tempPoint[0],tempPoint[1],tempPoint[2]);\n\t\tdimensionId = 0;\n\t}\n}\n\nstatic int face_cb(p_ply_argument argument) \n{\n\tlong length, value_index;\n\n\tply_get_argument_property(argument, NULL, &length, &value_index);\n\n switch (value_index) \n\t{\n \tcase 0:\n\t case 1: \n \t\ttempFace.vertexIds[pointId++] = ply_get_argument_value(argument);\n\t break;\n \tcase 2:\t\n\t\t\ttempFace.vertexIds[pointId] = ply_get_argument_value(argument);\n\t\t\tpointId = 0;\t\t\t\t\n\t\t\tplcFaces.push_front(tempFace);\n\t break;\n \tdefault: \n \tcout << \"Invalid number of points in a face specified :(\";\n\t\t\tbreak;\n } \n \n}\n\n\/\/ reads input PLC\nvoid readPLCInput()\n{\n\t\/\/ read PLY file(assumed to contain the PLC)\n\tstring fileName;\n\n\tcout << \"\\nPlease enter input filename:\\t\";\n\tcin >> fileName;\n\t\n\tp_ply inputPLY = ply_open(fileName.c_str(), NULL, 0, NULL);\n \t\n\tif (!inputPLY) exit(0);\n\n if (!ply_read_header(inputPLY)) exit(0);\n\t\n\tif (!ply_read(inputPLY))\n\t{\n\t\tcout << \"Cannot read the PLY file :(\";\n\t\texit(0);\n\t}\n\n\t\/\/ Initialize plcVertex and plcFaces\n \tply_set_read_cb(inputPLY, \"vertex\", \"x\", vertex_cb, NULL, 0);\t\n\tply_set_read_cb(inputPLY, \"vertex\", \"y\", vertex_cb, NULL, 0);\n\tply_set_read_cb(inputPLY, \"vertex\", \"z\", vertex_cb, NULL, 1);\n\n\tply_set_read_cb(inputPLY, \"face\", \"vertex_indices\", face_cb, NULL, 0); \n\n\tply_close(inputPLY);\n\t\n}\n\n\/\/ computes the initial delaunay tetrahedralization\nvoid computeInitialDelaunayTetrahedralization()\n{\t\n\t\n\tlist <Point> tempPointList;\n\tunsigned int i = 0;\n\n\tfor (map<unsigned, Point>::iterator pit = plcVertices.begin(); pit != plcVertices.end(); pit++, i++)\n\t\ttempPointList.push_front(plcVertices.find(i)->second);\n\n \tDT.insert(tempPointList.begin(), tempPointList.end());\n\n\tcout << \"\\nInitial Delaunay tetrahedralization computed!!\";\n}\n*\/\n\nclass DegenerateVertexSetCandidate\n{\n\tVertex_handle degenSetVertex[5];\t\n};\n\n\n\/\/ returns true if given vertices are co-spherical\nbool areCospherical(DegenerateVertexSetCandidate degenSet)\n{\n\t\n\tPoint_3 p[5];\n\t\n\tfor (unsigned int i = 0; i < 5; i++)\t\n\t\tp[i] = (degenSet.degenSetVertex[i])->point();\n\n\tif (CGAL::side_of_bounded_sphere(p[0],p[1],p[2],p[3],p[4]) == CGAL::ON_BOUNDARY)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\n\/\/ removes duplicate vertex sets from global degeneracyQueue\nvoid removeDuplicateDegenracies()\n{\n\n}\n\n\n\/\/ finds all local degeneracies in DT and adds them to a global queue\nvoid addLocalDegeneraciesToQueue(queue<DegenerateVertexSetCandidate> degeneracyQueue)\n{\n\t\n\tDegenerateVertexSetCandidate degenerateSet;\n\t\n\tfor (delaunay::Finite_cell_iterator cellIter = DT.finite_cells_begin(); cellIter != DT.finite_cells_end(); cellIter++)\n\t{\n\t\tfor (unsigned int n = 0; n < 4; n++)\n\t\t\tdegenerateSet.degenSetVertex[n] = cellIter->vertex(n);\n\n\t\tfor (unsigned int j = 0; j < 4; j++)\n\t\t\tfor (unsigned int k = 0; k < 4; k++)\n\t\t\t\t{\n\t\t\t\t\tif ((cellId->neighbor(j))->neighbor(k) == cellId)\n\t\t\t\t\t\tdegenerateSet.degenSetVertex[4] = (cellIter->neighbor)->vertex(k);\t\t\n\t\t\t\t\t\t\n\t\t\t\t\tif (areCospherical(degenerateSet))\n\t\t\t\t\t\tdegeneracyQueue.push_front(degenerateSet);\t\n\t\t\t\t}\n\t}\n\n\tremoveDuplicateDegeneracies(); \n}\n\n\n\n\/\/ removes local degeneracies from Delaunay tetrahedralization\nvoid removeLocalDegeneracies()\n{\n\t\n\tcout << \"\\nStarting local degeneracy removal...\";\n\n\t\/\/ compute all local degeneracies in DT and add them to Q\n\tqueue<DegenerateVertexSetCandidate> degeneracyQueue;\n\taddLocalDegeneraciesToQueue(degeneracyQueue);\n\n\t\/\/ repeat while Q != NULL\t\n\twhile (degenercyQueue.size() != 0)\n\t\tfor (queue<>::iterator qIter = degeneracyQueue.begin(); qIter != degeneracyQueue.end(); qIter++)\n\t\t\t{\n\t\t\t\tif (isDegeneracyRemovable(qIter))\n\t\t\t\t\tperturbRemove(qIter, degeneracyQueue); \n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tVertex vb;\t\n\t\t\t\t\tcomputeBreakPoint(vb, qIter, degeneracyQueue);\n\t\t\t\t\tif (isEncroachingPLC(vb))\n\t\t\t\t\t\tboundaryProtection(vb);\n\t\t\t\t\telse\n\t\t\t\t\t\tinputPLCVertices.push(vb);\t\t\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t}\n\n\tcout << \"Local degeneracy removal completed\";\n}\n\n\n\/*\n\/\/ recovers the constraint faces\nvoid recoverConstraintFaces()\n{\n\t\n}\n\n\/\/ main procedure\nint main()\n{\n\treadPLCInput();\n\tcomputeInitialDelaunayTetrahedralization();\n\tremoveLocalDegeneracies();\n\trecoverConstraintFaces();\n return 0;\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Master header of the `d2` library.\n *\/\n\n#ifndef D2_HPP\n#define D2_HPP\n\n#include <d2\/analysis.hpp>\n#include <d2\/concepts.hpp>\n#include <d2\/event_repository.hpp>\n#include <d2\/event_traits.hpp>\n#include <d2\/events.hpp>\n#include <d2\/filesystem_dispatcher.hpp>\n#include <d2\/lock_graph.hpp>\n#include <d2\/logging.hpp>\n#include <d2\/repository.hpp>\n#include <d2\/segment.hpp>\n#include <d2\/segmentation_graph.hpp>\n#include <d2\/sync_object.hpp>\n#include <d2\/thread.hpp>\n\n#endif \/\/ !D2_HPP\n<commit_msg>Remove the d2 master header, which is quite useless.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <nan.h>\n#include <rpcsvc\/ypclnt.h>\n\nusing namespace v8;\n\nextern \"C\" {\n int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data);\n}\n\nNAN_METHOD(Match) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value inkey(args[1]->ToString());\n char *outval;\n int outvallen;\n\n error = yp_match(*domain, *mapname, *inkey, inkey.length(), &outval, &outvallen);\n if (YPERR_KEY == error) {\n return scope.Close(Undefined());\n } else if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(String::New(outval, outvallen));\n}\n\nNAN_METHOD(Next) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value inkey(args[1]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outkey, *outval;\n int outkeylen, outvallen;\n\n error = yp_next(*domain, *mapname, *inkey, inkey.length(), &outkey, &outkeylen, &outval, &outvallen);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n Local<Object> obj = Object::New();\n obj->Set(String::New(\"key\"), String::New(outkey, outkeylen));\n obj->Set(String::New(\"value\"), String::New(outval, outvallen));\n return scope.Close(obj);\n}\n\nNAN_METHOD(First) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outkey, *outval;\n int outkeylen, outvallen;\n\n error = yp_first(*domain, *mapname, &outkey, &outkeylen, &outval, &outvallen);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n Local<Object> obj = Object::New();\n obj->Set(String::New(\"key\"), String::New(outkey, outkeylen));\n obj->Set(String::New(\"value\"), String::New(outval, outvallen));\n return scope.Close(obj);\n}\n\nNAN_METHOD(Master) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outname;\n\n error = yp_master(*domain, *mapname, &outname);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(String::New(outname));\n}\n\nNAN_METHOD(Order) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n int outorder;\n\n error = yp_order(*domain, *mapname, &outorder);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(Integer::New(outorder));\n}\n\nNAN_METHOD(All) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[1]->IsFunction()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be function\")));\n return scope.Close(Undefined());\n }\n Local<Function> user_cb = Local<Function>::Cast(args[1]);\n struct ypall_callback cb;\n cb.foreach = foreach_all;\n cb.data = (char *) &user_cb;\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n\n error = yp_all(*domain, *mapname, &cb);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(Undefined());\n}\n\nextern \"C\"\nint foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data) {\n Local<Function> *cb = static_cast<Local<Function> *>(data);\n const int argc = 3;\n Local<Value> argv[argc] = {\n Local<Value>::New(Integer::NewFromUnsigned(instatus)),\n Local<Value>::New(String::New(inkey, inkeylen)),\n Local<Value>::New(String::New(inval, invallen))\n };\n Local<Value> ret = (*cb)->Call(Context::GetCurrent()->Global(), argc, argv);\n return ret->Int32Value();\n}\n\nNAN_METHOD(CreateObject) {\n HandleScope scope;\n char* domp;\n int error;\n\n Local<Object> obj = Object::New();\n error = yp_get_default_domain(&domp);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n obj->Set(NanSymbol(\"domain_name\"), String::New(domp));\n obj->Set(NanSymbol(\"all\"), FunctionTemplate::New(All)->GetFunction());\n obj->Set(NanSymbol(\"order\"), FunctionTemplate::New(Order)->GetFunction());\n obj->Set(NanSymbol(\"master\"), FunctionTemplate::New(Master)->GetFunction());\n obj->Set(NanSymbol(\"first\"), FunctionTemplate::New(First)->GetFunction());\n obj->Set(NanSymbol(\"next\"), FunctionTemplate::New(Next)->GetFunction());\n obj->Set(NanSymbol(\"match\"), FunctionTemplate::New(Match)->GetFunction());\n return scope.Close(obj);\n}\n\nvoid Initialize(Handle<Object> exports, Handle<Object> module) {\n module->Set(\n NanSymbol(\"exports\"),\n FunctionTemplate::New(CreateObject)->GetFunction()\n );\n}\n\nNODE_MODULE(nis, Initialize);\n<commit_msg>Return undefined if no more records in database<commit_after>#include <node.h>\n#include <nan.h>\n#include <rpcsvc\/ypclnt.h>\n\nusing namespace v8;\n\nextern \"C\" {\n int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data);\n}\n\nNAN_METHOD(Match) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value inkey(args[1]->ToString());\n char *outval;\n int outvallen;\n\n error = yp_match(*domain, *mapname, *inkey, inkey.length(), &outval, &outvallen);\n if (YPERR_KEY == error) {\n return scope.Close(Undefined());\n } else if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(String::New(outval, outvallen));\n}\n\nNAN_METHOD(Next) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value inkey(args[1]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outkey, *outval;\n int outkeylen, outvallen;\n\n error = yp_next(*domain, *mapname, *inkey, inkey.length(), &outkey, &outkeylen, &outval, &outvallen);\n if (YPERR_NOMORE == error) {\n return scope.Close(Undefined());\n } else if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n Local<Object> obj = Object::New();\n obj->Set(String::New(\"key\"), String::New(outkey, outkeylen));\n obj->Set(String::New(\"value\"), String::New(outval, outvallen));\n return scope.Close(obj);\n}\n\nNAN_METHOD(First) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outkey, *outval;\n int outkeylen, outvallen;\n\n error = yp_first(*domain, *mapname, &outkey, &outkeylen, &outval, &outvallen);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n Local<Object> obj = Object::New();\n obj->Set(String::New(\"key\"), String::New(outkey, outkeylen));\n obj->Set(String::New(\"value\"), String::New(outval, outvallen));\n return scope.Close(obj);\n}\n\nNAN_METHOD(Master) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n char *outname;\n\n error = yp_master(*domain, *mapname, &outname);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(String::New(outname));\n}\n\nNAN_METHOD(Order) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n int outorder;\n\n error = yp_order(*domain, *mapname, &outorder);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(Integer::New(outorder));\n}\n\nNAN_METHOD(All) {\n HandleScope scope;\n int error;\n\n if (args.Length() < 2) {\n ThrowException(Exception::TypeError(String::New(\"Not enough arguments\")));\n return scope.Close(Undefined());\n }\n if (!args[0]->IsString()) {\n ThrowException(Exception::TypeError(String::New(\"First argument must be string\")));\n return scope.Close(Undefined());\n }\n if (!args[1]->IsFunction()) {\n ThrowException(Exception::TypeError(String::New(\"Second argument must be function\")));\n return scope.Close(Undefined());\n }\n Local<Function> user_cb = Local<Function>::Cast(args[1]);\n struct ypall_callback cb;\n cb.foreach = foreach_all;\n cb.data = (char *) &user_cb;\n\n String::Utf8Value mapname(args[0]->ToString());\n String::Utf8Value domain(args.Holder()->Get(NanSymbol(\"domain_name\")));\n\n error = yp_all(*domain, *mapname, &cb);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n\n return scope.Close(Undefined());\n}\n\nextern \"C\"\nint foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data) {\n Local<Function> *cb = static_cast<Local<Function> *>(data);\n const int argc = 3;\n Local<Value> argv[argc] = {\n Local<Value>::New(Integer::NewFromUnsigned(instatus)),\n Local<Value>::New(String::New(inkey, inkeylen)),\n Local<Value>::New(String::New(inval, invallen))\n };\n Local<Value> ret = (*cb)->Call(Context::GetCurrent()->Global(), argc, argv);\n return ret->Int32Value();\n}\n\nNAN_METHOD(CreateObject) {\n HandleScope scope;\n char* domp;\n int error;\n\n Local<Object> obj = Object::New();\n error = yp_get_default_domain(&domp);\n if (error) {\n Local<String> errorMessage = String::New(yperr_string(error));\n ThrowException(Exception::Error(errorMessage));\n }\n obj->Set(NanSymbol(\"domain_name\"), String::New(domp));\n obj->Set(NanSymbol(\"all\"), FunctionTemplate::New(All)->GetFunction());\n obj->Set(NanSymbol(\"order\"), FunctionTemplate::New(Order)->GetFunction());\n obj->Set(NanSymbol(\"master\"), FunctionTemplate::New(Master)->GetFunction());\n obj->Set(NanSymbol(\"first\"), FunctionTemplate::New(First)->GetFunction());\n obj->Set(NanSymbol(\"next\"), FunctionTemplate::New(Next)->GetFunction());\n obj->Set(NanSymbol(\"match\"), FunctionTemplate::New(Match)->GetFunction());\n return scope.Close(obj);\n}\n\nvoid Initialize(Handle<Object> exports, Handle<Object> module) {\n module->Set(\n NanSymbol(\"exports\"),\n FunctionTemplate::New(CreateObject)->GetFunction()\n );\n}\n\nNODE_MODULE(nis, Initialize);\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2004 Till Adam <adam@kde.org>\n Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n#include \"kotodoviewquicksearch.h\"\n\n#include \"kotodoviewitem.h\"\n#include \"kotodoview.h\"\n\n#include <libkcal\/calendar.h>\n#include <libkcal\/calfilter.h>\n#include <libkdepim\/categoryhierarchyreader.h>\n\n#include <korganizer\/mainwindow.h>\n\n#include \"koprefs.h\"\n\n#include <kaction.h>\n#include <klistviewsearchline.h>\n#include <ktoolbar.h>\n\n#include <qlayout.h>\n#include <qlabel.h>\n#include <qcombobox.h>\n#include <qapplication.h>\n#include <qregexp.h>\n#include <qsizepolicy.h>\n#include <qtimer.h>\n\nusing namespace KPIM;\nusing namespace KCal;\n\nKAction *KOTodoListViewQuickSearch::action = 0;\n\nKOTodoListViewQuickSearch::KOTodoListViewQuickSearch( QWidget *parent,\n QList<KListView*> listViews,\n KActionCollection *actionCollection,\n Calendar *calendar,\n const char *name )\n : KToolBar( parent, name ), mCategoryCombo( 0 ), mCalendar( calendar ),\n mQuickSearchLine( 0 )\n{\n if ( !action ) {\n action = new KAction( i18n( \"Reset To-do Quick Search\" ),\n QApplication::isRightToLeft() ? \"clear_left\" :\n \"locationbar_erase\", 0, this, SLOT( reset() ),\n actionCollection, \"reset_quicksearch\" );\n action->setWhatsThis( i18n( \"Reset Quick Search\\n\"\n \"Resets the quick search so that \"\n \"all to-dos are shown again.\" ) );\n }\n\n action->plug( this );\n\n boxLayout()->setSpacing( KDialog::spacingHint() );\n\n mSearchLabel = new QLabel( i18n(\"Sea&rch:\"), this,\n \"kde toolbar widget\" );\n\n mQuickSearchLine = new KOTodoListViewQuickSearchLine( this, listViews );\n setStretchableWidget( mQuickSearchLine );\n\n mSearchLabel->setBuddy( mQuickSearchLine );\n\n mCategoryLabel = new QLabel( i18n(\"&Category:\"), this, \"kde toolbar widget\" );\n\n mCategoryCombo = new QComboBox( this, \"quick search category combo box\" );\n fillCategories();\n\n mCategoryCombo->setCurrentItem( 0 );\n connect( mCategoryCombo, SIGNAL ( activated( int ) ),\n this, SLOT( slotCategoryChanged( int ) ) );\n\n mCategoryLabel->setBuddy( mCategoryCombo );\n}\n\nKOTodoListViewQuickSearch::~KOTodoListViewQuickSearch()\n{\n}\n\nbool KOTodoListViewQuickSearchLine::itemMatches(const Q3ListViewItem *item,\n const QString &s)\nconst\n{\n while ( item ) {\n const Todo *todo = static_cast<const KOTodoViewItem *>( item )->todo();\n if ( ( mCategory.isNull() ||\n !todo->categories().grep( QRegExp( QString( \"^\" ) +\n QRegExp::escape( mCategory ) ) ).isEmpty() ) &&\n KListViewSearchLine::itemMatches(item, s) )\n return true;\n else\n item = item->parent(); \/\/ children of passed items also pass\n }\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KOTodoListViewQuickSearch::reset()\n{\n mQuickSearchLine->clear();\n mCategoryCombo->setCurrentItem( 0 );\n slotCategoryChanged( 0 );\n}\n\nvoid KOTodoListViewQuickSearch::slotCategoryChanged( int index )\n{\n if ( index == 0 )\n mQuickSearchLine->setCategory( QString() );\n else\n mQuickSearchLine->setCategory( categoryList[index - 1] );\n mQuickSearchLine->updateSearch();\n}\n\nvoid KOTodoListViewQuickSearch::fillCategories()\n{\n QString current = mCategoryCombo->currentItem() > 0 ?\n categoryList[mCategoryCombo->currentItem() - 1] : QString();\n QStringList categories;\n\n CalFilter *filter = mCalendar->filter();\n if ( filter && ( filter->criteria() & CalFilter::ShowCategories ) ) {\n categories = filter->categoryList();\n categories.sort();\n } else {\n categories = KOPrefs::instance()->mCustomCategories;\n QStringList filterCategories = filter->categoryList();\n categories.sort();\n filterCategories.sort();\n\n QStringList::Iterator it = categories.begin();\n QStringList::Iterator jt = filterCategories.begin();\n while ( it != categories.end() && jt != filterCategories.end() )\n if ( *it == *jt ) {\n QStringList::Iterator next = it;\n next++;\n categories.remove( it );\n jt++;\n it = next;\n } else if ( *it < *jt )\n it++;\n else if ( *it > *jt )\n jt++;\n }\n\n CategoryHierarchyReaderQComboBox( mCategoryCombo ).read( categories );\n mCategoryCombo->insertItem( i18n( \"Any category\" ), 0 );\n\n categoryList.resize( categories.count() );\n qCopy( categories.begin(), categories.end(), categoryList.begin() );\n\n if ( current.isNull() ) {\n mCategoryCombo->setCurrentItem( 0 );\n } else {\n for ( int i = 0; i < categoryList.count(); ++i )\n if ( categoryList[i] == current ) {\n mCategoryCombo->setCurrentItem( i + 1 );\n break;\n }\n }\n\n}\n\nvoid KOTodoListViewQuickSearch::setCalendar( Calendar *calendar )\n{\n mCalendar = calendar;\n mQuickSearchLine->updateSearch();\n}\n\nvoid KOTodoListViewQuickSearch::resizeEvent( QResizeEvent *e )\n{\n int w = width() - mCategoryCombo->sizeHint().width()\n - mCategoryLabel->sizeHint().width()\n - mSearchLabel->sizeHint().width();\n int halfw = width() \/ 2;\n\n if ( w < halfw ) {\n w += mCategoryLabel->sizeHint().width();\n mCategoryLabel->hide();\n } else\n mCategoryLabel->show();\n if ( w < halfw ) {\n w += mSearchLabel->sizeHint().width();\n mSearchLabel->hide();\n } else\n mSearchLabel->show();\n if ( w < halfw ) {\n slotCategoryChanged( 0 );\n mCategoryCombo->hide();\n } else {\n slotCategoryChanged( mCategoryCombo->currentItem() );\n mCategoryCombo->show();\n }\n\n KToolBar::resizeEvent( e );\n}\n\nvoid KOTodoListViewQuickSearch::showEvent( QShowEvent *e )\n{\n connect( action, SIGNAL( activated() ), this, SLOT( reset() ) );\n\n KToolBar::showEvent( e );\n}\n\nvoid KOTodoListViewQuickSearch::hideEvent( QHideEvent *e )\n{\n disconnect( action, SIGNAL( activated() ), this, SLOT( reset() ) );\n\n KToolBar::hideEvent( e );\n}\n\nKOTodoListViewQuickSearchContainer::KOTodoListViewQuickSearchContainer(\n QWidget *parent,\n QList<KListView*> listViews,\n KActionCollection *actionCollection,\n Calendar *calendar)\n : QWidget( parent ), mQuickSearch( new KOTodoListViewQuickSearch(\n this, listViews, actionCollection, calendar, \"search toolbar\" ) )\n{\n setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );\n}\n\nKOTodoListViewQuickSearchContainer::~KOTodoListViewQuickSearchContainer()\n{\n}\n\nQSize KOTodoListViewQuickSearchContainer::sizeHint() const\n{\n int width = KDialog::spacingHint();\n QList<QObject*> list = mQuickSearch->children();\n for ( QList<QObject*>::Iterator it = list.begin(); it != list.end(); ++it ) {\n QWidget *child = dynamic_cast<QWidget *>( *it );\n if ( child ) {\n width += child->sizeHint().width() + KDialog::spacingHint();\n }\n }\n\n return QSize( width, mQuickSearch->sizeHint().height() );\n}\n\nQSize KOTodoListViewQuickSearchContainer::minimumSizeHint() const\n{\n return QSize( mQuickSearch->iconSize() +\n mQuickSearch->mQuickSearchLine->minimumSizeHint().width() +\n 3 * KDialog::spacingHint(),\n mQuickSearch->minimumSizeHint().height() );\n}\n\nKOTodoListViewQuickSearch *KOTodoListViewQuickSearchContainer::quickSearch()\n const\n{\n return mQuickSearch;\n}\n\nvoid KOTodoListViewQuickSearchContainer::resizeEvent ( QResizeEvent *\/*e*\/ )\n{\n mQuickSearch->setGeometry( QRect( QPoint( 0, 0 ), size() ) );\n}\n\n\n#include \"kotodoviewquicksearch.moc\"\n<commit_msg>for now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long stringfor now, it's unbearable with such a long string<commit_after>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2004 Till Adam <adam@kde.org>\n Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\n#include \"kotodoviewquicksearch.h\"\n\n#include \"kotodoviewitem.h\"\n#include \"kotodoview.h\"\n\n#include <libkcal\/calendar.h>\n#include <libkcal\/calfilter.h>\n#include <libkdepim\/categoryhierarchyreader.h>\n\n#include <korganizer\/mainwindow.h>\n\n#include \"koprefs.h\"\n\n#include <kaction.h>\n#include <klistviewsearchline.h>\n#include <ktoolbar.h>\n\n#include <qlayout.h>\n#include <qlabel.h>\n#include <qcombobox.h>\n#include <qapplication.h>\n#include <qregexp.h>\n#include <qsizepolicy.h>\n#include <qtimer.h>\n\nusing namespace KPIM;\nusing namespace KCal;\n\nKAction *KOTodoListViewQuickSearch::action = 0;\n\nKOTodoListViewQuickSearch::KOTodoListViewQuickSearch( QWidget *parent,\n QList<KListView*> listViews,\n KActionCollection *actionCollection,\n Calendar *calendar,\n const char *name )\n : KToolBar( parent, name ), mCategoryCombo( 0 ), mCalendar( calendar ),\n mQuickSearchLine( 0 )\n{\n if ( !action ) {\n action = new KAction( i18n( \"Reset\" ),\n QApplication::isRightToLeft() ? \"clear_left\" :\n \"locationbar_erase\", 0, this, SLOT( reset() ),\n actionCollection, \"reset_quicksearch\" );\n action->setWhatsThis( i18n( \"Reset Quick Search\\n\"\n \"Resets the quick search so that \"\n \"all to-dos are shown again.\" ) );\n }\n\n action->plug( this );\n\n boxLayout()->setSpacing( KDialog::spacingHint() );\n\n mSearchLabel = new QLabel( i18n(\"Sea&rch:\"), this,\n \"kde toolbar widget\" );\n\n mQuickSearchLine = new KOTodoListViewQuickSearchLine( this, listViews );\n setStretchableWidget( mQuickSearchLine );\n\n mSearchLabel->setBuddy( mQuickSearchLine );\n\n mCategoryLabel = new QLabel( i18n(\"&Category:\"), this, \"kde toolbar widget\" );\n\n mCategoryCombo = new QComboBox( this, \"quick search category combo box\" );\n fillCategories();\n\n mCategoryCombo->setCurrentItem( 0 );\n connect( mCategoryCombo, SIGNAL ( activated( int ) ),\n this, SLOT( slotCategoryChanged( int ) ) );\n\n mCategoryLabel->setBuddy( mCategoryCombo );\n}\n\nKOTodoListViewQuickSearch::~KOTodoListViewQuickSearch()\n{\n}\n\nbool KOTodoListViewQuickSearchLine::itemMatches(const Q3ListViewItem *item,\n const QString &s)\nconst\n{\n while ( item ) {\n const Todo *todo = static_cast<const KOTodoViewItem *>( item )->todo();\n if ( ( mCategory.isNull() ||\n !todo->categories().grep( QRegExp( QString( \"^\" ) +\n QRegExp::escape( mCategory ) ) ).isEmpty() ) &&\n KListViewSearchLine::itemMatches(item, s) )\n return true;\n else\n item = item->parent(); \/\/ children of passed items also pass\n }\n return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KOTodoListViewQuickSearch::reset()\n{\n mQuickSearchLine->clear();\n mCategoryCombo->setCurrentItem( 0 );\n slotCategoryChanged( 0 );\n}\n\nvoid KOTodoListViewQuickSearch::slotCategoryChanged( int index )\n{\n if ( index == 0 )\n mQuickSearchLine->setCategory( QString() );\n else\n mQuickSearchLine->setCategory( categoryList[index - 1] );\n mQuickSearchLine->updateSearch();\n}\n\nvoid KOTodoListViewQuickSearch::fillCategories()\n{\n QString current = mCategoryCombo->currentItem() > 0 ?\n categoryList[mCategoryCombo->currentItem() - 1] : QString();\n QStringList categories;\n\n CalFilter *filter = mCalendar->filter();\n if ( filter && ( filter->criteria() & CalFilter::ShowCategories ) ) {\n categories = filter->categoryList();\n categories.sort();\n } else {\n categories = KOPrefs::instance()->mCustomCategories;\n QStringList filterCategories = filter->categoryList();\n categories.sort();\n filterCategories.sort();\n\n QStringList::Iterator it = categories.begin();\n QStringList::Iterator jt = filterCategories.begin();\n while ( it != categories.end() && jt != filterCategories.end() )\n if ( *it == *jt ) {\n QStringList::Iterator next = it;\n next++;\n categories.remove( it );\n jt++;\n it = next;\n } else if ( *it < *jt )\n it++;\n else if ( *it > *jt )\n jt++;\n }\n\n CategoryHierarchyReaderQComboBox( mCategoryCombo ).read( categories );\n mCategoryCombo->insertItem( i18n( \"Any category\" ), 0 );\n\n categoryList.resize( categories.count() );\n qCopy( categories.begin(), categories.end(), categoryList.begin() );\n\n if ( current.isNull() ) {\n mCategoryCombo->setCurrentItem( 0 );\n } else {\n for ( int i = 0; i < categoryList.count(); ++i )\n if ( categoryList[i] == current ) {\n mCategoryCombo->setCurrentItem( i + 1 );\n break;\n }\n }\n\n}\n\nvoid KOTodoListViewQuickSearch::setCalendar( Calendar *calendar )\n{\n mCalendar = calendar;\n mQuickSearchLine->updateSearch();\n}\n\nvoid KOTodoListViewQuickSearch::resizeEvent( QResizeEvent *e )\n{\n int w = width() - mCategoryCombo->sizeHint().width()\n - mCategoryLabel->sizeHint().width()\n - mSearchLabel->sizeHint().width();\n int halfw = width() \/ 2;\n\n if ( w < halfw ) {\n w += mCategoryLabel->sizeHint().width();\n mCategoryLabel->hide();\n } else\n mCategoryLabel->show();\n if ( w < halfw ) {\n w += mSearchLabel->sizeHint().width();\n mSearchLabel->hide();\n } else\n mSearchLabel->show();\n if ( w < halfw ) {\n slotCategoryChanged( 0 );\n mCategoryCombo->hide();\n } else {\n slotCategoryChanged( mCategoryCombo->currentItem() );\n mCategoryCombo->show();\n }\n\n KToolBar::resizeEvent( e );\n}\n\nvoid KOTodoListViewQuickSearch::showEvent( QShowEvent *e )\n{\n connect( action, SIGNAL( activated() ), this, SLOT( reset() ) );\n\n KToolBar::showEvent( e );\n}\n\nvoid KOTodoListViewQuickSearch::hideEvent( QHideEvent *e )\n{\n disconnect( action, SIGNAL( activated() ), this, SLOT( reset() ) );\n\n KToolBar::hideEvent( e );\n}\n\nKOTodoListViewQuickSearchContainer::KOTodoListViewQuickSearchContainer(\n QWidget *parent,\n QList<KListView*> listViews,\n KActionCollection *actionCollection,\n Calendar *calendar)\n : QWidget( parent ), mQuickSearch( new KOTodoListViewQuickSearch(\n this, listViews, actionCollection, calendar, \"search toolbar\" ) )\n{\n setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );\n}\n\nKOTodoListViewQuickSearchContainer::~KOTodoListViewQuickSearchContainer()\n{\n}\n\nQSize KOTodoListViewQuickSearchContainer::sizeHint() const\n{\n int width = KDialog::spacingHint();\n QList<QObject*> list = mQuickSearch->children();\n for ( QList<QObject*>::Iterator it = list.begin(); it != list.end(); ++it ) {\n QWidget *child = dynamic_cast<QWidget *>( *it );\n if ( child ) {\n width += child->sizeHint().width() + KDialog::spacingHint();\n }\n }\n\n return QSize( width, mQuickSearch->sizeHint().height() );\n}\n\nQSize KOTodoListViewQuickSearchContainer::minimumSizeHint() const\n{\n return QSize( mQuickSearch->iconSize() +\n mQuickSearch->mQuickSearchLine->minimumSizeHint().width() +\n 3 * KDialog::spacingHint(),\n mQuickSearch->minimumSizeHint().height() );\n}\n\nKOTodoListViewQuickSearch *KOTodoListViewQuickSearchContainer::quickSearch()\n const\n{\n return mQuickSearch;\n}\n\nvoid KOTodoListViewQuickSearchContainer::resizeEvent ( QResizeEvent *\/*e*\/ )\n{\n mQuickSearch->setGeometry( QRect( QPoint( 0, 0 ), size() ) );\n}\n\n\n#include \"kotodoviewquicksearch.moc\"\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstdint>\n\nnamespace cu\n{\n\ntemplate <typename T>\nstruct IntTraits;\n\nnamespace detail\n{\n template <std::size_t nBits_,\n bool isSigned_>\n struct IntTraitsImpl\n {\n static constexpr std::size_t nBits = nBits_;\n static constexpr bool isSigned = isSigned_;\n };\n}\n\ntemplate <> struct IntTraits<std:: int8_t> : detail::IntTraitsImpl< 8, true> {};\ntemplate <> struct IntTraits<std:: int16_t> : detail::IntTraitsImpl<16, true> {};\ntemplate <> struct IntTraits<std:: int32_t> : detail::IntTraitsImpl<32, true> {};\ntemplate <> struct IntTraits<std:: int64_t> : detail::IntTraitsImpl<64, true> {};\ntemplate <> struct IntTraits<std:: uint8_t> : detail::IntTraitsImpl< 8,false> {};\ntemplate <> struct IntTraits<std::uint16_t> : detail::IntTraitsImpl<16,false> {};\ntemplate <> struct IntTraits<std::uint32_t> : detail::IntTraitsImpl<32,false> {};\ntemplate <> struct IntTraits<std::uint64_t> : detail::IntTraitsImpl<64,false> {};\n\nnamespace detail\n{\n template <std::size_t nBits,\n bool isSigned>\n struct BuildInIntImpl;\n\n template <typename T>\n struct TypeTrait { using type = T; };\n\n template <> struct BuildInIntImpl< 8, true> : TypeTrait<std:: int8_t> {};\n template <> struct BuildInIntImpl<16, true> : TypeTrait<std:: int16_t> {};\n template <> struct BuildInIntImpl<32, true> : TypeTrait<std:: int32_t> {};\n template <> struct BuildInIntImpl<64, true> : TypeTrait<std:: int64_t> {};\n template <> struct BuildInIntImpl< 8,false> : TypeTrait<std:: uint8_t> {};\n template <> struct BuildInIntImpl<16,false> : TypeTrait<std::uint16_t> {};\n template <> struct BuildInIntImpl<32,false> : TypeTrait<std::uint32_t> {};\n template <> struct BuildInIntImpl<64,false> : TypeTrait<std::uint64_t> {};\n}\n\ntemplate <std::size_t nBits,\n bool isSigned = true>\nusing BuildInInt = typename detail::BuildInIntImpl<nBits,isSigned>::type;\n\ntemplate <typename IntT>\nusing DoubleSizeInt = BuildInInt<IntTraits<IntT>::nBits*2,IntTraits<IntT>::isSigned>;\n\n} \/\/ namespace cu\n<commit_msg>Fix: Included missing header.<commit_after>#pragma once\n\n#include <cstddef>\n#include <cstdint>\n\nnamespace cu\n{\n\ntemplate <typename T>\nstruct IntTraits;\n\nnamespace detail\n{\n template <std::size_t nBits_,\n bool isSigned_>\n struct IntTraitsImpl\n {\n static constexpr std::size_t nBits = nBits_;\n static constexpr bool isSigned = isSigned_;\n };\n}\n\ntemplate <> struct IntTraits<std:: int8_t> : detail::IntTraitsImpl< 8, true> {};\ntemplate <> struct IntTraits<std:: int16_t> : detail::IntTraitsImpl<16, true> {};\ntemplate <> struct IntTraits<std:: int32_t> : detail::IntTraitsImpl<32, true> {};\ntemplate <> struct IntTraits<std:: int64_t> : detail::IntTraitsImpl<64, true> {};\ntemplate <> struct IntTraits<std:: uint8_t> : detail::IntTraitsImpl< 8,false> {};\ntemplate <> struct IntTraits<std::uint16_t> : detail::IntTraitsImpl<16,false> {};\ntemplate <> struct IntTraits<std::uint32_t> : detail::IntTraitsImpl<32,false> {};\ntemplate <> struct IntTraits<std::uint64_t> : detail::IntTraitsImpl<64,false> {};\n\nnamespace detail\n{\n template <std::size_t nBits,\n bool isSigned>\n struct BuildInIntImpl;\n\n template <typename T>\n struct TypeTrait { using type = T; };\n\n template <> struct BuildInIntImpl< 8, true> : TypeTrait<std:: int8_t> {};\n template <> struct BuildInIntImpl<16, true> : TypeTrait<std:: int16_t> {};\n template <> struct BuildInIntImpl<32, true> : TypeTrait<std:: int32_t> {};\n template <> struct BuildInIntImpl<64, true> : TypeTrait<std:: int64_t> {};\n template <> struct BuildInIntImpl< 8,false> : TypeTrait<std:: uint8_t> {};\n template <> struct BuildInIntImpl<16,false> : TypeTrait<std::uint16_t> {};\n template <> struct BuildInIntImpl<32,false> : TypeTrait<std::uint32_t> {};\n template <> struct BuildInIntImpl<64,false> : TypeTrait<std::uint64_t> {};\n}\n\ntemplate <std::size_t nBits,\n bool isSigned = true>\nusing BuildInInt = typename detail::BuildInIntImpl<nBits,isSigned>::type;\n\ntemplate <typename IntT>\nusing DoubleSizeInt = BuildInInt<IntTraits<IntT>::nBits*2,IntTraits<IntT>::isSigned>;\n\n} \/\/ namespace cu\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Metadata.cpp - Implement Metadata classes -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Metadata classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LLVMContextImpl.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"SymbolTableListTraitsImpl.h\"\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MetadataBase implementation\n\/\/\n\n\/\/\/ resizeOperands - Metadata keeps track of other metadata uses using \n\/\/\/ OperandList. Resize this list to hold anticipated number of metadata\n\/\/\/ operands.\nvoid MetadataBase::resizeOperands(unsigned NumOps) {\n unsigned e = getNumOperands();\n if (NumOps == 0) {\n NumOps = e*2;\n if (NumOps < 2) NumOps = 2; \n } else if (NumOps > NumOperands) {\n \/\/ No resize needed.\n if (ReservedSpace >= NumOps) return;\n } else if (NumOps == NumOperands) {\n if (ReservedSpace == NumOps) return;\n } else {\n return;\n }\n\n ReservedSpace = NumOps;\n Use *OldOps = OperandList;\n Use *NewOps = allocHungoffUses(NumOps);\n std::copy(OldOps, OldOps + e, NewOps);\n OperandList = NewOps;\n if (OldOps) Use::zap(OldOps, OldOps + e, true);\n}\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MDString implementation\n\/\/\nMDString *MDString::get(LLVMContext &Context, const StringRef &Str) {\n LLVMContextImpl *pImpl = Context.pImpl;\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n StringMapEntry<MDString *> &Entry = \n pImpl->MDStringCache.GetOrCreateValue(Str);\n MDString *&S = Entry.getValue();\n if (!S) S = new MDString(Context, Entry.getKeyData(),\n Entry.getKeyLength());\n\n return S;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MDNode implementation\n\/\/\nMDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals)\n : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {\n NumOperands = 0;\n resizeOperands(NumVals);\n for (unsigned i = 0; i != NumVals; ++i) {\n \/\/ Only record metadata uses.\n if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))\n OperandList[NumOperands++] = MB;\n else if(Vals[i] && \n Vals[i]->getType()->getTypeID() == Type::MetadataTyID)\n OperandList[NumOperands++] = Vals[i];\n Node.push_back(ElementVH(Vals[i], this));\n }\n}\n\nvoid MDNode::Profile(FoldingSetNodeID &ID) const {\n for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)\n ID.AddPointer(*I);\n}\n\nMDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {\n LLVMContextImpl *pImpl = Context.pImpl;\n FoldingSetNodeID ID;\n for (unsigned i = 0; i != NumVals; ++i)\n ID.AddPointer(Vals[i]);\n\n \/\/ FIXME: MDNode uniquing disabled temporarily.\n#ifndef ENABLE_MDNODE_UNIQUING\n return new MDNode(Context, Vals, NumVals);\n#endif\n\n pImpl->ConstantsLock.reader_acquire();\n void *InsertPoint;\n MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n pImpl->ConstantsLock.reader_release();\n\n if (!N) {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n if (!N) {\n \/\/ InsertPoint will have been set by the FindNodeOrInsertPos call.\n N = new MDNode(Context, Vals, NumVals);\n pImpl->MDNodeSet.InsertNode(N, InsertPoint);\n }\n }\n\n return N;\n}\n\n\/\/\/ dropAllReferences - Remove all uses and clear node vector.\nvoid MDNode::dropAllReferences() {\n User::dropAllReferences();\n Node.clear();\n}\n\nMDNode::~MDNode() {\n \/\/ FIXME: MDNode uniquing disabled temporarily.\n#ifdef ENABLE_MDNODE_UNIQUING\n getType()->getContext().pImpl->MDNodeSet.RemoveNode(this);\n#endif\n dropAllReferences();\n}\n\n\/\/ Replace value from this node's element list.\nvoid MDNode::replaceElement(Value *From, Value *To) {\n \/\/ FIXME: MDNode uniquing disabled temporarily.\n#ifndef ENABLE_MDNODE_UNIQUING\n if (From == To || !getType())\n return;\n\n for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),\n E = Node.end(); I != E; ++I)\n if (*I && *I == From)\n *I = ElementVH(To, this);\n return;\n#endif\n\n if (From == To || !getType())\n return;\n LLVMContext &Context = getType()->getContext();\n LLVMContextImpl *pImpl = Context.pImpl;\n\n \/\/ Find value. This is a linear search, do something if it consumes \n \/\/ lot of time. It is possible that to have multiple instances of\n \/\/ From in this MDNode's element list.\n SmallVector<unsigned, 4> Indexes;\n unsigned Index = 0;\n for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),\n E = Node.end(); I != E; ++I, ++Index) {\n Value *V = *I;\n if (V && V == From) \n Indexes.push_back(Index);\n }\n\n if (Indexes.empty())\n return;\n\n \/\/ Remove \"this\" from the context map. \n {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n pImpl->MDNodeSet.RemoveNode(this);\n }\n\n \/\/ MDNode only lists metadata elements in operand list, because MDNode\n \/\/ used by MDNode is considered a valid use. However on the side, MDNode\n \/\/ using a non-metadata value is not considered a \"use\" of non-metadata\n \/\/ value.\n SmallVector<unsigned, 4> OpIndexes;\n unsigned OpIndex = 0;\n for (User::op_iterator OI = op_begin(), OE = op_end();\n OI != OE; ++OI, OpIndex++) {\n if (*OI == From)\n OpIndexes.push_back(OpIndex);\n }\n if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {\n for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),\n OE = OpIndexes.end(); OI != OE; ++OI)\n setOperand(*OI, MDTo);\n } else {\n for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),\n OE = OpIndexes.end(); OI != OE; ++OI)\n setOperand(*OI, 0);\n }\n\n \/\/ Replace From element(s) in place.\n for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); \n I != E; ++I) {\n unsigned Index = *I;\n Node[Index] = ElementVH(To, this);\n }\n\n \/\/ Insert updated \"this\" into the context's folding node set.\n \/\/ If a node with same element list already exist then before inserting \n \/\/ updated \"this\" into the folding node set, replace all uses of existing \n \/\/ node with updated \"this\" node.\n FoldingSetNodeID ID;\n Profile(ID);\n pImpl->ConstantsLock.reader_acquire();\n void *InsertPoint;\n MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n pImpl->ConstantsLock.reader_release();\n\n if (N) {\n N->replaceAllUsesWith(this);\n delete N;\n N = 0;\n }\n\n {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n if (!N) {\n \/\/ InsertPoint will have been set by the FindNodeOrInsertPos call.\n N = this;\n pImpl->MDNodeSet.InsertNode(N, InsertPoint);\n }\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/NamedMDNode implementation\n\/\/\nNamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,\n MetadataBase*const* MDs, \n unsigned NumMDs, Module *ParentModule)\n : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {\n setName(N);\n NumOperands = 0;\n resizeOperands(NumMDs);\n\n for (unsigned i = 0; i != NumMDs; ++i) {\n if (MDs[i])\n OperandList[NumOperands++] = MDs[i];\n Node.push_back(WeakMetadataVH(MDs[i]));\n }\n if (ParentModule)\n ParentModule->getNamedMDList().push_back(this);\n}\n\nNamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {\n assert (NMD && \"Invalid source NamedMDNode!\");\n SmallVector<MetadataBase *, 4> Elems;\n for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)\n Elems.push_back(NMD->getElement(i));\n return new NamedMDNode(NMD->getContext(), NMD->getName().data(),\n Elems.data(), Elems.size(), M);\n}\n\n\/\/\/ eraseFromParent - Drop all references and remove the node from parent\n\/\/\/ module.\nvoid NamedMDNode::eraseFromParent() {\n getParent()->getNamedMDList().erase(this);\n}\n\n\/\/\/ dropAllReferences - Remove all uses and clear node vector.\nvoid NamedMDNode::dropAllReferences() {\n User::dropAllReferences();\n Node.clear();\n}\n\nNamedMDNode::~NamedMDNode() {\n dropAllReferences();\n}\n<commit_msg>Enable MDNode uniquing.<commit_after>\/\/===-- Metadata.cpp - Implement Metadata classes -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Metadata classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LLVMContextImpl.h\"\n#include \"llvm\/Metadata.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"SymbolTableListTraitsImpl.h\"\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MetadataBase implementation\n\/\/\n\n\/\/\/ resizeOperands - Metadata keeps track of other metadata uses using \n\/\/\/ OperandList. Resize this list to hold anticipated number of metadata\n\/\/\/ operands.\nvoid MetadataBase::resizeOperands(unsigned NumOps) {\n unsigned e = getNumOperands();\n if (NumOps == 0) {\n NumOps = e*2;\n if (NumOps < 2) NumOps = 2; \n } else if (NumOps > NumOperands) {\n \/\/ No resize needed.\n if (ReservedSpace >= NumOps) return;\n } else if (NumOps == NumOperands) {\n if (ReservedSpace == NumOps) return;\n } else {\n return;\n }\n\n ReservedSpace = NumOps;\n Use *OldOps = OperandList;\n Use *NewOps = allocHungoffUses(NumOps);\n std::copy(OldOps, OldOps + e, NewOps);\n OperandList = NewOps;\n if (OldOps) Use::zap(OldOps, OldOps + e, true);\n}\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MDString implementation\n\/\/\nMDString *MDString::get(LLVMContext &Context, const StringRef &Str) {\n LLVMContextImpl *pImpl = Context.pImpl;\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n StringMapEntry<MDString *> &Entry = \n pImpl->MDStringCache.GetOrCreateValue(Str);\n MDString *&S = Entry.getValue();\n if (!S) S = new MDString(Context, Entry.getKeyData(),\n Entry.getKeyLength());\n\n return S;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/MDNode implementation\n\/\/\nMDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals)\n : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {\n NumOperands = 0;\n resizeOperands(NumVals);\n for (unsigned i = 0; i != NumVals; ++i) {\n \/\/ Only record metadata uses.\n if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))\n OperandList[NumOperands++] = MB;\n else if(Vals[i] && \n Vals[i]->getType()->getTypeID() == Type::MetadataTyID)\n OperandList[NumOperands++] = Vals[i];\n Node.push_back(ElementVH(Vals[i], this));\n }\n}\n\nvoid MDNode::Profile(FoldingSetNodeID &ID) const {\n for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)\n ID.AddPointer(*I);\n}\n\nMDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {\n LLVMContextImpl *pImpl = Context.pImpl;\n FoldingSetNodeID ID;\n for (unsigned i = 0; i != NumVals; ++i)\n ID.AddPointer(Vals[i]);\n\n pImpl->ConstantsLock.reader_acquire();\n void *InsertPoint;\n MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n pImpl->ConstantsLock.reader_release();\n \n if (!N) {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n if (!N) {\n \/\/ InsertPoint will have been set by the FindNodeOrInsertPos call.\n N = new MDNode(Context, Vals, NumVals);\n pImpl->MDNodeSet.InsertNode(N, InsertPoint);\n }\n }\n\n return N;\n}\n\n\/\/\/ dropAllReferences - Remove all uses and clear node vector.\nvoid MDNode::dropAllReferences() {\n User::dropAllReferences();\n Node.clear();\n}\n\nMDNode::~MDNode() {\n getType()->getContext().pImpl->MDNodeSet.RemoveNode(this);\n dropAllReferences();\n}\n\n\/\/ Replace value from this node's element list.\nvoid MDNode::replaceElement(Value *From, Value *To) {\n if (From == To || !getType())\n return;\n LLVMContext &Context = getType()->getContext();\n LLVMContextImpl *pImpl = Context.pImpl;\n\n \/\/ Find value. This is a linear search, do something if it consumes \n \/\/ lot of time. It is possible that to have multiple instances of\n \/\/ From in this MDNode's element list.\n SmallVector<unsigned, 4> Indexes;\n unsigned Index = 0;\n for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),\n E = Node.end(); I != E; ++I, ++Index) {\n Value *V = *I;\n if (V && V == From) \n Indexes.push_back(Index);\n }\n\n if (Indexes.empty())\n return;\n\n \/\/ Remove \"this\" from the context map. \n {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n pImpl->MDNodeSet.RemoveNode(this);\n }\n\n \/\/ MDNode only lists metadata elements in operand list, because MDNode\n \/\/ used by MDNode is considered a valid use. However on the side, MDNode\n \/\/ using a non-metadata value is not considered a \"use\" of non-metadata\n \/\/ value.\n SmallVector<unsigned, 4> OpIndexes;\n unsigned OpIndex = 0;\n for (User::op_iterator OI = op_begin(), OE = op_end();\n OI != OE; ++OI, OpIndex++) {\n if (*OI == From)\n OpIndexes.push_back(OpIndex);\n }\n if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {\n for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),\n OE = OpIndexes.end(); OI != OE; ++OI)\n setOperand(*OI, MDTo);\n } else {\n for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),\n OE = OpIndexes.end(); OI != OE; ++OI)\n setOperand(*OI, 0);\n }\n\n \/\/ Replace From element(s) in place.\n for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); \n I != E; ++I) {\n unsigned Index = *I;\n Node[Index] = ElementVH(To, this);\n }\n\n \/\/ Insert updated \"this\" into the context's folding node set.\n \/\/ If a node with same element list already exist then before inserting \n \/\/ updated \"this\" into the folding node set, replace all uses of existing \n \/\/ node with updated \"this\" node.\n FoldingSetNodeID ID;\n Profile(ID);\n pImpl->ConstantsLock.reader_acquire();\n void *InsertPoint;\n MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n pImpl->ConstantsLock.reader_release();\n\n if (N) {\n N->replaceAllUsesWith(this);\n delete N;\n N = 0;\n }\n\n {\n sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);\n N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);\n if (!N) {\n \/\/ InsertPoint will have been set by the FindNodeOrInsertPos call.\n N = this;\n pImpl->MDNodeSet.InsertNode(N, InsertPoint);\n }\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/NamedMDNode implementation\n\/\/\nNamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,\n MetadataBase*const* MDs, \n unsigned NumMDs, Module *ParentModule)\n : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {\n setName(N);\n NumOperands = 0;\n resizeOperands(NumMDs);\n\n for (unsigned i = 0; i != NumMDs; ++i) {\n if (MDs[i])\n OperandList[NumOperands++] = MDs[i];\n Node.push_back(WeakMetadataVH(MDs[i]));\n }\n if (ParentModule)\n ParentModule->getNamedMDList().push_back(this);\n}\n\nNamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {\n assert (NMD && \"Invalid source NamedMDNode!\");\n SmallVector<MetadataBase *, 4> Elems;\n for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)\n Elems.push_back(NMD->getElement(i));\n return new NamedMDNode(NMD->getContext(), NMD->getName().data(),\n Elems.data(), Elems.size(), M);\n}\n\n\/\/\/ eraseFromParent - Drop all references and remove the node from parent\n\/\/\/ module.\nvoid NamedMDNode::eraseFromParent() {\n getParent()->getNamedMDList().erase(this);\n}\n\n\/\/\/ dropAllReferences - Remove all uses and clear node vector.\nvoid NamedMDNode::dropAllReferences() {\n User::dropAllReferences();\n Node.clear();\n}\n\nNamedMDNode::~NamedMDNode() {\n dropAllReferences();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2017 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"cpp_utils\/assert.hpp\"\n#include \"cpp_utils\/string.hpp\"\n\n#include \"writer.hpp\"\n#include \"console.hpp\"\n\nbudget::console_writer::console_writer(std::ostream& os) : os(os) {}\n\nbudget::writer& budget::console_writer::operator<<(const std::string& value){\n os << format(value);\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const double& value){\n os << value;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::money& m) {\n os << m;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::month& m) {\n os << m.as_short_string();\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::year& y) {\n os << y.value;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::end_of_line_t&) {\n os << std::endl;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::p_begin_t&) {\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::p_end_t&) {\n os << std::endl;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::title_begin_t&) {\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::title_end_t&) {\n os << std::endl << std::endl;\n\n return *this;\n}\n\nvoid budget::console_writer::display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups, std::vector<size_t> lines, size_t left){\n cpp_assert(groups > 0, \"There must be at least 1 group\");\n\n for(auto& row : contents){\n for(auto& cell : row){\n cpp::trim(cell);\n }\n }\n\n std::vector<size_t> widths;\n std::vector<size_t> header_widths;\n\n if(!contents.size()){\n for(auto& column : columns){\n widths.push_back(rsize(column));\n }\n } else {\n auto& first = contents[0];\n\n widths.assign(first.size(), 0);\n\n for(auto& row : contents){\n for(size_t i = 0; i < row.size(); ++i){\n widths[i] = std::max(widths[i], rsize(row[i]) + 1);\n }\n }\n }\n\n cpp_assert(widths.size() == groups * columns.size(), \"Widths incorrectly computed\");\n\n \/\/ Display the header\n\n if (left) {\n os << std::string(left, ' ');\n }\n\n for(size_t i = 0; i < columns.size(); ++i){\n auto& column = columns[i];\n\n size_t width = 0;\n for(size_t j = i * groups; j < (i + 1) * groups; ++j){\n width += widths[j];\n }\n\n width = std::max(width, rsize(column));\n header_widths.push_back(width + (i < columns.size() - 1 && rsize(column) >= width ? 1 : 0));\n\n \/\/The last space is not underlined\n --width;\n\n os << format_code(4, 0, 7) << column << (width > rsize(column) ? std::string(width - rsize(column), ' ') : \"\") << format_code(0, 0, 7);\n\n \/\/The very last column has no trailing space\n\n if(i < columns.size() - 1){\n os << \" \";\n }\n }\n\n os << std::endl;\n\n \/\/ Display the contents\n\n for(size_t i = 0; i < contents.size(); ++i){\n if(left){\n os << std::string(left, ' ');\n }\n\n auto& row = contents[i];\n\n bool underline = std::find(lines.begin(), lines.end(), i) != lines.end();\n\n for(size_t j = 0; j < row.size(); j += groups){\n size_t acc_width = 0;\n\n \/\/First columns of the group\n for(size_t k = 0; k < groups - 1; ++k){\n auto column = j + k;\n\n std::string value = format(row[column]);\n\n acc_width += widths[column];\n\n if (underline) {\n os << format_code(4, 0, 7);\n os << value;\n os << std::string(widths[column] - rsize(value) - 1, ' ');\n os << format_code(0, 0, 7);\n } else {\n os << value;\n os << std::string(widths[column] - rsize(value) - 1, ' ');\n }\n\n os << ' ';\n }\n\n \/\/The last column of the group\n\n auto last_column = j + (groups - 1);\n auto width = widths[last_column];\n acc_width += width;\n\n \/\/Pad with spaces to fit the header column width\n\n if(header_widths[j \/ groups] > acc_width){\n width += header_widths[j \/ groups] - acc_width;\n } else if(last_column == row.size() - 1){\n --width;\n }\n\n auto value = format(row[last_column]);\n\n auto missing = width - rsize(row[last_column]);\n\n std::string fill_string;\n if (missing > 1){\n fill_string = std::string(missing - 1, ' ');\n }\n\n if (underline) {\n os << format_code(4, 0, 7);\n os << value;\n os << fill_string;\n os << format_code(0, 0, 7);\n } else {\n os << value;\n os << fill_string;\n }\n\n if (missing > 0) {\n if (j == row.size() - 1 && underline) {\n os << format_code(4, 0, 7);\n os << ' ';\n os << format_code(0, 0, 7);\n } else {\n os << ' ';\n }\n }\n }\n\n os << format_code(0, 0, 7) << std::endl;\n }\n}\n<commit_msg>Fix support for vertical table<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2017 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"cpp_utils\/assert.hpp\"\n#include \"cpp_utils\/string.hpp\"\n\n#include \"writer.hpp\"\n#include \"console.hpp\"\n\nbudget::console_writer::console_writer(std::ostream& os) : os(os) {}\n\nbudget::writer& budget::console_writer::operator<<(const std::string& value){\n os << format(value);\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const double& value){\n os << value;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::money& m) {\n os << m;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::month& m) {\n os << m.as_short_string();\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::year& y) {\n os << y.value;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::end_of_line_t&) {\n os << std::endl;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::p_begin_t&) {\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::p_end_t&) {\n os << std::endl;\n\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::title_begin_t&) {\n return *this;\n}\n\nbudget::writer& budget::console_writer::operator<<(const budget::title_end_t&) {\n os << std::endl << std::endl;\n\n return *this;\n}\n\nvoid budget::console_writer::display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups, std::vector<size_t> lines, size_t left){\n cpp_assert(groups > 0, \"There must be at least 1 group\");\n cpp_assert(contents.size() || columns.size(), \"There must be at least some columns or contents\");\n\n for(auto& row : contents){\n for(auto& cell : row){\n cpp::trim(cell);\n }\n }\n\n std::vector<size_t> widths;\n std::vector<size_t> header_widths;\n\n if(!contents.size()){\n for(auto& column : columns){\n widths.push_back(rsize(column));\n }\n } else {\n auto& first = contents[0];\n\n widths.assign(first.size(), 0);\n\n for(auto& row : contents){\n for(size_t i = 0; i < row.size(); ++i){\n widths[i] = std::max(widths[i], rsize(row[i]) + 1);\n }\n }\n }\n\n cpp_assert(widths.size() == groups * columns.size(), \"Widths incorrectly computed\");\n\n \/\/ Display the header\n\n if (left) {\n os << std::string(left, ' ');\n }\n\n if (columns.empty()) {\n const size_t C = contents.front().size();\n for (size_t i = 0; i < C; ++i) {\n size_t width = 0;\n for (size_t j = i * groups; j < (i + 1) * groups; ++j) {\n width += widths[j];\n }\n\n header_widths.push_back(width + (i < C - 1 ? 1 : 0));\n }\n } else {\n for (size_t i = 0; i < columns.size(); ++i) {\n auto& column = columns[i];\n\n size_t width = 0;\n for (size_t j = i * groups; j < (i + 1) * groups; ++j) {\n width += widths[j];\n }\n\n width = std::max(width, rsize(column));\n header_widths.push_back(width + (i < columns.size() - 1 && rsize(column) >= width ? 1 : 0));\n\n \/\/The last space is not underlined\n --width;\n\n os << format_code(4, 0, 7) << column << (width > rsize(column) ? std::string(width - rsize(column), ' ') : \"\") << format_code(0, 0, 7);\n\n \/\/The very last column has no trailing space\n\n if (i < columns.size() - 1) {\n os << \" \";\n }\n }\n }\n\n os << std::endl;\n\n \/\/ Display the contents\n\n for(size_t i = 0; i < contents.size(); ++i){\n if(left){\n os << std::string(left, ' ');\n }\n\n auto& row = contents[i];\n\n bool underline = std::find(lines.begin(), lines.end(), i) != lines.end();\n\n for(size_t j = 0; j < row.size(); j += groups){\n size_t acc_width = 0;\n\n \/\/First columns of the group\n for(size_t k = 0; k < groups - 1; ++k){\n auto column = j + k;\n\n std::string value = format(row[column]);\n\n acc_width += widths[column];\n\n if (underline) {\n os << format_code(4, 0, 7);\n os << value;\n os << std::string(widths[column] - rsize(value) - 1, ' ');\n os << format_code(0, 0, 7);\n } else {\n os << value;\n os << std::string(widths[column] - rsize(value) - 1, ' ');\n }\n\n os << ' ';\n }\n\n \/\/The last column of the group\n\n auto last_column = j + (groups - 1);\n auto width = widths[last_column];\n acc_width += width;\n\n \/\/Pad with spaces to fit the header column width\n\n if(header_widths[j \/ groups] > acc_width){\n width += header_widths[j \/ groups] - acc_width;\n } else if(last_column == row.size() - 1){\n --width;\n }\n\n auto value = format(row[last_column]);\n\n auto missing = width - rsize(row[last_column]);\n\n std::string fill_string;\n if (missing > 1){\n fill_string = std::string(missing - 1, ' ');\n }\n\n if (underline) {\n os << format_code(4, 0, 7);\n os << value;\n os << fill_string;\n os << format_code(0, 0, 7);\n } else {\n os << value;\n os << fill_string;\n }\n\n if (missing > 0) {\n if (j == row.size() - 1 && underline) {\n os << format_code(4, 0, 7);\n os << ' ';\n os << format_code(0, 0, 7);\n } else {\n os << ' ';\n }\n }\n }\n\n os << format_code(0, 0, 7) << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n***************************************\r\n* Asylum3D @ 2014-12-17\r\n***************************************\r\n*\/\r\n\r\n#ifndef __ASYLUM3D_HPP__\r\n#define __ASYLUM3D_HPP__\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/***********\/\r\n\/* VertexN *\/\r\n\/***********\/\r\nstruct vertex_n\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n};\r\n\r\n\/************\/\r\n\/* VertexT2 *\/\r\n\/************\/\r\nstruct vertex_t2\r\n{\r\n vec3d_t pos;\r\n vec2d_t tex;\r\n};\r\n\r\n\/************\/\r\n\/* VertexT3 *\/\r\n\/************\/\r\nstruct vertex_t3\r\n{\r\n vec3d_t pos;\r\n vec3d_t tex;\r\n};\r\n\r\n\/*************\/\r\n\/* VertexNT2 *\/\r\n\/*************\/\r\nstruct vertex_nt2\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n vec2d_t tex;\r\n};\r\n\r\n\/*************\/\r\n\/* VertexNT3 *\/\r\n\/*************\/\r\nstruct vertex_nt3\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n vec3d_t tex;\r\n};\r\n\r\n} \/* namespace *\/\r\n\r\n#endif \/* __ASYLUM3D_HPP__ *\/\r\n<commit_msg>Asylum: 增加效果和材质接口<commit_after>\/*\r\n***************************************\r\n* Asylum3D @ 2014-12-17\r\n***************************************\r\n*\/\r\n\r\n#ifndef __ASYLUM3D_HPP__\r\n#define __ASYLUM3D_HPP__\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/***********\/\r\n\/* VertexN *\/\r\n\/***********\/\r\nstruct vertex_n\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n};\r\n\r\n\/************\/\r\n\/* VertexT2 *\/\r\n\/************\/\r\nstruct vertex_t2\r\n{\r\n vec3d_t pos;\r\n vec2d_t tex;\r\n};\r\n\r\n\/************\/\r\n\/* VertexT3 *\/\r\n\/************\/\r\nstruct vertex_t3\r\n{\r\n vec3d_t pos;\r\n vec3d_t tex;\r\n};\r\n\r\n\/*************\/\r\n\/* VertexNT2 *\/\r\n\/*************\/\r\nstruct vertex_nt2\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n vec2d_t tex;\r\n};\r\n\r\n\/*************\/\r\n\/* VertexNT3 *\/\r\n\/*************\/\r\nstruct vertex_nt3\r\n{\r\n vec3d_t pos;\r\n vec3d_t nrm;\r\n vec3d_t tex;\r\n};\r\n\r\n\/***************\/\r\n\/* Effect Port *\/\r\n\/***************\/\r\nclass effect_i : public asylum\r\n{\r\npublic:\r\n \/* ================= *\/\r\n virtual ~effect_i () {}\r\n\r\npublic:\r\n \/* ==================== *\/\r\n virtual void enter () = 0;\r\n\r\n \/* ==================== *\/\r\n virtual void leave () = 0;\r\n};\r\n\r\n\/*****************\/\r\n\/* Material Port *\/\r\n\/*****************\/\r\nclass material_i : public asylum\r\n{\r\npublic:\r\n \/* =================== *\/\r\n virtual ~material_i () {}\r\n\r\npublic:\r\n \/* ===================== *\/\r\n virtual void commit () = 0;\r\n};\r\n\r\n} \/* namespace *\/\r\n\r\n#endif \/* __ASYLUM3D_HPP__ *\/\r\n<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n#include <gflags\/gflags.h>\n#include <iostream>\n#include <stdio.h>\n\n#include \"lang\/interpreter\/language_evaluation.h\"\n#include \"lang\/interpreter\/source_util.h\"\n#include \"lang\/interpreter\/steinlang_parser.h\"\n#include \"util\/file_io.h\"\n#include \"util\/optional.h\"\n\nDEFINE_bool(debug_print_parse_trees, false, \"\");\nDEFINE_bool(debug_print_syntax_tree, false, \"\");\nDEFINE_bool(debug_print_steps, false,\n \"If true, print verbose evaluation state after each step. This \"\n \"slows down execution significantly.\");\nDEFINE_bool(debug_print_timing, false, \"\");\n\nnamespace {\n\nstd::string ReadStdIn() {\n std::stringstream ss;\n ss << std::cin.rdbuf();\n return ss.str();\n}\n\ntemplate <typename Lexer, typename Parser>\nutil::Optional<typename Parser::ParseTreeNode> LexAndParse(\n const std::string& text, const Lexer& lexer, const Parser& parser) {\n const std::vector<typename Lexer::Token> tokens = lexer(text);\n auto parse_result = parser.Parse(tokens.begin(), tokens.end());\n\n if (FLAGS_debug_print_parse_trees) {\n std::cout << parse_result.DebugString(tokens.end()) << \"\\n\";\n }\n\n const std::vector<typename Lexer::Token> unparsed_tokens(parse_result.pos,\n tokens.end());\n if (!unparsed_tokens.empty()) {\n std::cout << \"unparsed tokens:\";\n for (const auto& token : unparsed_tokens) {\n std::cout << \" \" << token.value;\n }\n std::cout << \"\\n\";\n }\n\n if (!parse_result.success) {\n std::cout << \"parse failed.\\n\";\n return util::EmptyOptional();\n }\n return std::move(parse_result.node);\n}\n\n} \/\/ namespace\n\nnamespace steinlang {\n\nvoid DebugPrint(const EvalContext& ctx) {\n printf(\"================\\n\");\n printf(\"results: .\");\n for (const Result& r : ctx.cur_ctx().result()) {\n printf(\" <~ %s\", r.ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n printf(\"env:\\n\");\n for (const auto& kv : ctx.cur_ctx().env()) {\n printf(\" env[%s] = %s\\n\", kv.first.c_str(),\n ctx.store(kv.second).ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n printf(\"comps: .\");\n for (const Computation c : ctx.cur_ctx().comp()) {\n printf(\" <~ %s\", c.ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n}\n\nint evaluate(std::unique_ptr<Evaluator> evaluator) {\n int steps = 0;\n int num_output_printed = 0;\n while (evaluator->HasComputation()) {\n evaluator->Step();\n for (const std::string& output : evaluator->consume_output()) {\n printf(\"output: %s\\n\", output.c_str());\n }\n ++steps;\n if (FLAGS_debug_print_steps) {\n DebugPrint(evaluator->ctx());\n }\n }\n return steps;\n}\n\nvoid InitCtx(const Program& pgm, EvalContext* ctx) {\n *ctx->mutable_pgm() = pgm;\n AnnotateSource(ctx->mutable_pgm());\n for (int i = pgm.stmt_size(); i-- > 0;) {\n *ctx->mutable_cur_ctx()->add_comp()->mutable_stmt() = pgm.stmt(i);\n }\n}\n\nbool Evaluate(const std::string& input, EvalContext* ctx, PoolingArenaAllocator* allocator) {\n const util::Optional<steinlang::Parser::ParseTreeNode> parse_result =\n LexAndParse(input, steinlang::Tokenizer(), steinlang::Parser());\n if (!parse_result.is_present()) {\n std::cout << \"failed to parse input.\\n\";\n return false;\n }\n\n steinlang::Program pgm = steinlang::ToProgram(parse_result.value());\n if (FLAGS_debug_print_syntax_tree) {\n std::cout << pgm.DebugString() << \"\\n\";\n }\n\n steinlang::InitCtx(pgm, ctx);\n auto evaluator = std::make_unique<steinlang::Evaluator>(ctx, allocator);\n auto start = std::chrono::high_resolution_clock::now();\n int num_steps = evaluate(std::move(evaluator));\n auto elapsed = std::chrono::high_resolution_clock::now() - start;\n long long microseconds =\n std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();\n if (FLAGS_debug_print_timing) {\n printf(\"total num steps evaluated: %d\\n\", num_steps);\n printf(\"total time: %lld us\\n\", microseconds);\n printf(\"avg: %f us \/ step\\n\", static_cast<float>(microseconds) \/ num_steps);\n }\n return true;\n}\n\n} \/\/ namespace steinlang\n\nint main(int argc, char** argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n steinlang::PoolingArenaAllocator allocator;\n steinlang::EvalContext* ctx = allocator.AllocateEvalContext();\n for (std::string line; std::getline(std::cin, line) && Evaluate(line, ctx, &allocator);) {}\n\n return 0;\n}\n<commit_msg>undo make interpreter_main interpret line-by-line, now that there are multistatement blocks<commit_after>#include <chrono>\n#include <gflags\/gflags.h>\n#include <iostream>\n#include <stdio.h>\n\n#include \"lang\/interpreter\/language_evaluation.h\"\n#include \"lang\/interpreter\/source_util.h\"\n#include \"lang\/interpreter\/steinlang_parser.h\"\n#include \"util\/file_io.h\"\n#include \"util\/optional.h\"\n\nDEFINE_bool(debug_print_parse_trees, false, \"\");\nDEFINE_bool(debug_print_syntax_tree, false, \"\");\nDEFINE_bool(debug_print_steps, false,\n \"If true, print verbose evaluation state after each step. This \"\n \"slows down execution significantly.\");\nDEFINE_bool(debug_print_timing, false, \"\");\n\nnamespace {\n\nstd::string ReadStdIn() {\n std::stringstream ss;\n ss << std::cin.rdbuf();\n return ss.str();\n}\n\ntemplate <typename Lexer, typename Parser>\nutil::Optional<typename Parser::ParseTreeNode> LexAndParse(\n const std::string& text, const Lexer& lexer, const Parser& parser) {\n const std::vector<typename Lexer::Token> tokens = lexer(text);\n auto parse_result = parser.Parse(tokens.begin(), tokens.end());\n\n if (FLAGS_debug_print_parse_trees) {\n std::cout << parse_result.DebugString(tokens.end()) << \"\\n\";\n }\n\n const std::vector<typename Lexer::Token> unparsed_tokens(parse_result.pos,\n tokens.end());\n if (!unparsed_tokens.empty()) {\n std::cout << \"unparsed tokens:\";\n for (const auto& token : unparsed_tokens) {\n std::cout << \" \" << token.value;\n }\n std::cout << \"\\n\";\n }\n\n if (!parse_result.success) {\n std::cout << \"parse failed.\\n\";\n return util::EmptyOptional();\n }\n return std::move(parse_result.node);\n}\n\n} \/\/ namespace\n\nnamespace steinlang {\n\nvoid DebugPrint(const EvalContext& ctx) {\n printf(\"================\\n\");\n printf(\"results: .\");\n for (const Result& r : ctx.cur_ctx().result()) {\n printf(\" <~ %s\", r.ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n printf(\"env:\\n\");\n for (const auto& kv : ctx.cur_ctx().env()) {\n printf(\" env[%s] = %s\\n\", kv.first.c_str(),\n ctx.store(kv.second).ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n printf(\"comps: .\");\n for (const Computation c : ctx.cur_ctx().comp()) {\n printf(\" <~ %s\", c.ShortDebugString().c_str());\n }\n printf(\"\\n--------\\n\");\n}\n\nint evaluate(std::unique_ptr<Evaluator> evaluator) {\n int steps = 0;\n int num_output_printed = 0;\n while (evaluator->HasComputation()) {\n evaluator->Step();\n for (const std::string& output : evaluator->consume_output()) {\n printf(\"output: %s\\n\", output.c_str());\n }\n ++steps;\n if (FLAGS_debug_print_steps) {\n DebugPrint(evaluator->ctx());\n }\n }\n return steps;\n}\n\nvoid InitCtx(const Program& pgm, EvalContext* ctx) {\n *ctx->mutable_pgm() = pgm;\n AnnotateSource(ctx->mutable_pgm());\n for (int i = pgm.stmt_size(); i-- > 0;) {\n *ctx->mutable_cur_ctx()->add_comp()->mutable_stmt() = pgm.stmt(i);\n }\n}\n\nbool Evaluate(const std::string& input, EvalContext* ctx, PoolingArenaAllocator* allocator) {\n const util::Optional<steinlang::Parser::ParseTreeNode> parse_result =\n LexAndParse(input, steinlang::Tokenizer(), steinlang::Parser());\n if (!parse_result.is_present()) {\n std::cout << \"failed to parse input.\\n\";\n return false;\n }\n\n steinlang::Program pgm = steinlang::ToProgram(parse_result.value());\n if (FLAGS_debug_print_syntax_tree) {\n std::cout << pgm.DebugString() << \"\\n\";\n }\n\n steinlang::InitCtx(pgm, ctx);\n auto evaluator = std::make_unique<steinlang::Evaluator>(ctx, allocator);\n auto start = std::chrono::high_resolution_clock::now();\n int num_steps = evaluate(std::move(evaluator));\n auto elapsed = std::chrono::high_resolution_clock::now() - start;\n long long microseconds =\n std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();\n if (FLAGS_debug_print_timing) {\n printf(\"total num steps evaluated: %d\\n\", num_steps);\n printf(\"total time: %lld us\\n\", microseconds);\n printf(\"avg: %f us \/ step\\n\", static_cast<float>(microseconds) \/ num_steps);\n }\n return true;\n}\n\n} \/\/ namespace steinlang\n\nint main(int argc, char** argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n steinlang::PoolingArenaAllocator allocator;\n steinlang::EvalContext* ctx = allocator.AllocateEvalContext();\n Evaluate(ReadStdIn(), ctx, &allocator);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** File: OGRE3DRenderable.cpp\r\n Created on: 13-Feb-09\r\n Author: Robin Southern \"betajaen\"\r\n \r\n\r\n Copyright (c) 2008-2009 Robin Southern\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included in\r\n all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n THE SOFTWARE.\r\n\r\n*\/\r\n\r\n \r\n\r\n#include \"OGRE3DRenderable.h\"\r\n#include \"OGRE3DRenderSystem.h\"\r\n#include \"Ogre.h\"\r\n\r\n \r\n\r\n\/\/ operation, normals, colour, indexes, texture-coords, 16bit indexes.\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_VISUALDEBUGGER =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_LINE_LIST, false, true, false, false, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_PHYSXMESH =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_TRIANGLE_LIST, true, false, true, true, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_PARTICLEPOINTS =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_POINT_LIST, false, false, false, false, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_SOFTBODY =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_TRIANGLE_LIST, false, false, true, false, false);\r\n\r\n \r\n\r\nOGRE3DRenderable::RenderProfile::RenderProfile()\r\n: mRenderOperation(Ogre::RenderOperation::OT_POINT_LIST),\r\n usesNormals(false),\r\n usesColourVertices(false),\r\n usesIndexes(false),\r\n uses16BitIndexes(false),\r\n usesTextureCoordinates(false)\r\n{\r\n}\r\n\r\nOGRE3DRenderable::RenderProfile::RenderProfile(Ogre::RenderOperation::OperationType op, bool n, bool c, bool i, bool t, bool _16)\r\n: mRenderOperation(op),\r\n usesNormals(n),\r\n usesColourVertices(c),\r\n usesIndexes(i),\r\n uses16BitIndexes(_16),\r\n usesTextureCoordinates(t)\r\n{\r\n}\r\n\r\nOGRE3DRenderable::OGRE3DRenderable(NxOgre::Enums::RenderableType type)\r\n: NxOgre::Renderable(type)\r\n{\r\n _createProfile(mType);\r\n _initialise();\r\n}\r\n\r\nOGRE3DRenderable::~OGRE3DRenderable()\r\n{\r\n NxOgre_Delete(mRenderOp.vertexData);\r\n NxOgre_Delete(mRenderOp.indexData);\r\n}\r\n\r\nvoid OGRE3DRenderable::drawSoftBodySimple(NxOgre::PhysXMeshData* data, const NxOgre::Bounds3& bounds)\r\n{\r\n \/\/ Early escape.\r\n if (data->getNbVertices() < 3)\r\n {\r\n mBox.setExtents(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);\r\n return;\r\n }\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n \r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(Ogre::Real), data->getVertices() );\r\n \r\n \/\/ Write the indices.\r\n mRenderOp.indexData->indexBuffer->writeData(0, data->getNbIndices() * sizeof(unsigned int), data->getIndices() );\r\n \r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\n\r\nvoid OGRE3DRenderable::drawCloth(NxOgre::PhysXMeshData* data, NxOgre::Buffer<float>& textureCoords, const NxOgre::Bounds3& bounds)\r\n{\r\n \/\/ Early escape.\r\n if (data->getNbVertices() < 3)\r\n {\r\n mBox.setExtents(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);\r\n return;\r\n }\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n \r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(Ogre::Real), data->getVertices() );\r\n \r\n \/\/ Write the normals.\r\n mNormalBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(Ogre::Real), data->getNormals() );\r\n\r\n \/\/ Write the texture coords.\r\n mTextureCoordsBuffer->writeData(0, textureCoords.size() * sizeof(float), textureCoords.first() );\r\n\r\n \/\/ Write the indices.\r\n mRenderOp.indexData->indexBuffer->writeData(0, data->getNbIndices() * sizeof(unsigned int), data->getIndices() );\r\n \r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\n\r\nvoid OGRE3DRenderable::drawClothFast(NxOgre::PhysXMeshData* data, const NxOgre::Bounds3& bounds)\r\n{\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n\r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(Ogre::Real), data->getVertices() );\r\n \r\n \/\/ Write the normals.\r\n mNormalBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(Ogre::Real), data->getNormals() );\r\n\r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\nvoid OGRE3DRenderable::drawVisualDebugger(NxOgre::VisualDebuggerMeshData* data)\r\n{\r\n _resize(data->getNbLines(), 0);\r\n\r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbLines() * sizeof(Ogre::Real), data->getLines() );\r\n \r\n mVertexColourBuffer->writeData(0, data->getNbLines() * sizeof(unsigned int), data->getColours() );\r\n\r\n mBox.setInfinite();\r\n \r\n}\r\n\r\nvoid OGRE3DRenderable::_createProfile(NxOgre::Enums::RenderableType type)\r\n{\r\n switch(type)\r\n {\r\n case NxOgre::Enums::RenderableType_VisualDebugger:\r\n mProfile = OGRE3DRenderable::NXOGRE_VISUALDEBUGGER;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_PhysXMesh:\r\n mProfile = OGRE3DRenderable::NXOGRE_PHYSXMESH;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_ParticlePoints:\r\n mProfile = OGRE3DRenderable::NXOGRE_PARTICLEPOINTS;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_SoftBody:\r\n mProfile = OGRE3DRenderable::NXOGRE_SOFTBODY;\r\n break;\r\n \r\n }\r\n}\r\n\r\nvoid OGRE3DRenderable::_initialise()\r\n{\r\n \/\/ Op.\r\n mRenderOp.operationType = mProfile.mRenderOperation;\r\n\r\n \/\/ Vertices and other vertex bits.\r\n mRenderOp.vertexData = new Ogre::VertexData;\r\n\r\n \/\/ Main vertex declartion. It is assumed that a Renderable has vertices.\r\n Ogre::VertexDeclaration* vDecl = mRenderOp.vertexData->vertexDeclaration;\r\n vDecl->addElement(VertexDeclaration_Position, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);\r\n \r\n \/\/ Normals.\r\n if (mProfile.usesNormals)\r\n vDecl->addElement(VertexDeclaration_Normal, 0, Ogre::VET_FLOAT3, Ogre::VES_NORMAL);\r\n \r\n \/\/ Vertex Colours.\r\n if (mProfile.usesColourVertices)\r\n vDecl->addElement(VertexDeclaration_Colour, 0, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE);\r\n \r\n if (mProfile.usesTextureCoordinates)\r\n vDecl->addElement(VertexDeclaration_TextureCoordinates, 0, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);\r\n\r\n \/\/ Vertex buffer capacity is zero.\r\n mVertexBufferCapacity = 0;\r\n\r\n\r\n \/\/ Do the indexes. If it has one.\r\n if (mRenderOp.useIndexes = mProfile.usesIndexes)\r\n mRenderOp.indexData = new Ogre::IndexData;\r\n\r\n\r\n mIndexBufferCapacity = 0;\r\n}\r\n\r\nvoid OGRE3DRenderable::_resize(size_t vertexCount, size_t indexCount)\r\n{\r\n \/\/ Prepare vertex buffer\r\n size_t newVertCapacity = mVertexBufferCapacity;\r\n if ((vertexCount > mVertexBufferCapacity) ||\r\n (!mVertexBufferCapacity))\r\n {\r\n \/\/ vertexCount exceeds current capacity!\r\n \/\/ It is necessary to reallocate the buffer.\r\n\r\n \/\/ Check if this is the first call\r\n if (!newVertCapacity)\r\n newVertCapacity = 1;\r\n\r\n \/\/ Make capacity the next power of two\r\n while (newVertCapacity < vertexCount)\r\n newVertCapacity <<= 1;\r\n }\r\n else if (vertexCount < mVertexBufferCapacity>>1) {\r\n \/\/ Make capacity the previous power of two\r\n while (vertexCount < newVertCapacity>>1)\r\n newVertCapacity >>= 1;\r\n }\r\n \r\n if (newVertCapacity != mVertexBufferCapacity) \r\n {\r\n mVertexBufferCapacity = newVertCapacity;\r\n \r\n \/\/ Create new vertex buffer\r\n mVertexBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Position),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Position, mVertexBuffer);\r\n \r\n \/\/ Colour vertices.\r\n if (this->mProfile.usesColourVertices)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mVertexColourBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Colour),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Colour, mVertexColourBuffer);\r\n }\r\n\r\n \/\/ Normals.\r\n if (this->mProfile.usesNormals)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mNormalBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Normal),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Normal, mNormalBuffer);\r\n }\r\n\r\n \/\/ Texture coords.\r\n if (this->mProfile.usesTextureCoordinates)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mTextureCoordsBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_TextureCoordinates),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_TextureCoordinates, mTextureCoordsBuffer);\r\n }\r\n\r\n }\r\n \/\/ Update vertex count in the render operation\r\n mRenderOp.vertexData->vertexCount = vertexCount;\r\n\r\n if (mProfile.usesIndexes)\r\n {\r\n OgreAssert(indexCount <= std::numeric_limits<unsigned short>::max(), \"indexCount exceeds 16 bit\");\r\n\r\n size_t newIndexCapacity = mIndexBufferCapacity;\r\n \/\/ Prepare index buffer\r\n if ((indexCount > newIndexCapacity) || (!newIndexCapacity))\r\n {\r\n \/\/ indexCount exceeds current capacity!\r\n \/\/ It is necessary to reallocate the buffer.\r\n \/\/ Check if this is the first call\r\n if (!newIndexCapacity)\r\n newIndexCapacity = 1;\r\n \/\/ Make capacity the next power of two\r\n while (newIndexCapacity < indexCount)\r\n newIndexCapacity <<= 1;\r\n }\r\n else if (indexCount < newIndexCapacity>>1) \r\n {\r\n \/\/ Make capacity the previous power of two\r\n while (indexCount < newIndexCapacity>>1)\r\n newIndexCapacity >>= 1;\r\n }\r\n \r\n if (newIndexCapacity != mIndexBufferCapacity)\r\n {\r\n mIndexBufferCapacity = newIndexCapacity;\r\n \/\/ Create new index buffer\r\n mIndexBuffer = mRenderOp.indexData->indexBuffer =\r\n Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(\r\n Ogre::HardwareIndexBuffer::IndexType(!mProfile.uses16BitIndexes),\r\n mIndexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n }\r\n \r\n \/\/ Update index count in the render operation\r\n mRenderOp.indexData->indexCount = indexCount;\r\n }\r\n}\r\n\r\nOgre::Real OGRE3DRenderable::getBoundingRadius(void) const\r\n{\r\n return Ogre::Math::Sqrt(std::max(mBox.getMaximum().squaredLength(), mBox.getMinimum().squaredLength()));\r\n}\r\n\r\nOgre::Real OGRE3DRenderable::getSquaredViewDepth(const Ogre::Camera* cam) const\r\n{\r\n Ogre::Vector3 vMin, vMax, vMid, vDist;\r\n vMin = mBox.getMinimum();\r\n vMax = mBox.getMaximum();\r\n vMid = ((vMax - vMin) * 0.5) + vMin;\r\n vDist = cam->getDerivedPosition() - vMid;\r\n return vDist.squaredLength();\r\n}\r\n<commit_msg>Ogre::Real to float Fix<commit_after>\/** File: OGRE3DRenderable.cpp\r\n Created on: 13-Feb-09\r\n Author: Robin Southern \"betajaen\"\r\n \r\n\r\n Copyright (c) 2008-2009 Robin Southern\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included in\r\n all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n THE SOFTWARE.\r\n\r\n*\/\r\n\r\n \r\n\r\n#include \"OGRE3DRenderable.h\"\r\n#include \"OGRE3DRenderSystem.h\"\r\n#include \"Ogre.h\"\r\n\r\n \r\n\r\n\/\/ operation, normals, colour, indexes, texture-coords, 16bit indexes.\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_VISUALDEBUGGER =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_LINE_LIST, false, true, false, false, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_PHYSXMESH =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_TRIANGLE_LIST, true, false, true, true, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_PARTICLEPOINTS =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_POINT_LIST, false, false, false, false, false);\r\n\r\nOGRE3DRenderable::RenderProfile OGRE3DRenderable::NXOGRE_SOFTBODY =\r\n OGRE3DRenderable::RenderProfile (Ogre::RenderOperation::OT_TRIANGLE_LIST, false, false, true, false, false);\r\n\r\n \r\n\r\nOGRE3DRenderable::RenderProfile::RenderProfile()\r\n: mRenderOperation(Ogre::RenderOperation::OT_POINT_LIST),\r\n usesNormals(false),\r\n usesColourVertices(false),\r\n usesIndexes(false),\r\n uses16BitIndexes(false),\r\n usesTextureCoordinates(false)\r\n{\r\n}\r\n\r\nOGRE3DRenderable::RenderProfile::RenderProfile(Ogre::RenderOperation::OperationType op, bool n, bool c, bool i, bool t, bool _16)\r\n: mRenderOperation(op),\r\n usesNormals(n),\r\n usesColourVertices(c),\r\n usesIndexes(i),\r\n uses16BitIndexes(_16),\r\n usesTextureCoordinates(t)\r\n{\r\n}\r\n\r\nOGRE3DRenderable::OGRE3DRenderable(NxOgre::Enums::RenderableType type)\r\n: NxOgre::Renderable(type)\r\n{\r\n _createProfile(mType);\r\n _initialise();\r\n}\r\n\r\nOGRE3DRenderable::~OGRE3DRenderable()\r\n{\r\n NxOgre_Delete(mRenderOp.vertexData);\r\n NxOgre_Delete(mRenderOp.indexData);\r\n}\r\n\r\nvoid OGRE3DRenderable::drawSoftBodySimple(NxOgre::PhysXMeshData* data, const NxOgre::Bounds3& bounds)\r\n{\r\n \/\/ Early escape.\r\n if (data->getNbVertices() < 3)\r\n {\r\n mBox.setExtents(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);\r\n return;\r\n }\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n \r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(float), data->getVertices() );\r\n \r\n \/\/ Write the indices.\r\n mRenderOp.indexData->indexBuffer->writeData(0, data->getNbIndices() * sizeof(unsigned int), data->getIndices() );\r\n \r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\n\r\nvoid OGRE3DRenderable::drawCloth(NxOgre::PhysXMeshData* data, NxOgre::Buffer<float>& textureCoords, const NxOgre::Bounds3& bounds)\r\n{\r\n \/\/ Early escape.\r\n if (data->getNbVertices() < 3)\r\n {\r\n mBox.setExtents(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);\r\n return;\r\n }\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n \r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(float), data->getVertices() );\r\n \r\n \/\/ Write the normals.\r\n mNormalBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(float), data->getNormals() );\r\n\r\n \/\/ Write the texture coords.\r\n mTextureCoordsBuffer->writeData(0, textureCoords.size() * sizeof(float), textureCoords.first() );\r\n\r\n \/\/ Write the indices.\r\n mRenderOp.indexData->indexBuffer->writeData(0, data->getNbIndices() * sizeof(unsigned int), data->getIndices() );\r\n \r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\n\r\nvoid OGRE3DRenderable::drawClothFast(NxOgre::PhysXMeshData* data, const NxOgre::Bounds3& bounds)\r\n{\r\n \r\n \/\/ Resize buffers if necessary.\r\n _resize(data->getNbVertices(), data->getNbIndices());\r\n\r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(float), data->getVertices() );\r\n \r\n \/\/ Write the normals.\r\n mNormalBuffer->writeData(0, 3 * data->getNbVertices() * sizeof(float), data->getNormals() );\r\n\r\n \/\/ Set the extents.\r\n mBox.setExtents(bounds.min.as<Ogre::Vector3>(), bounds.max.as<Ogre::Vector3>());\r\n \r\n \/\/ Done.\r\n}\r\nvoid OGRE3DRenderable::drawVisualDebugger(NxOgre::VisualDebuggerMeshData* data)\r\n{\r\n _resize(data->getNbLines(), 0);\r\n\r\n \/\/ Write the vertices.\r\n mVertexBuffer->writeData(0, 3 * data->getNbLines() * sizeof(float), data->getLines() );\r\n\r\n mVertexColourBuffer->writeData(0, data->getNbLines() * sizeof(unsigned int), data->getColours() );\r\n\r\n mBox.setInfinite();\r\n \r\n}\r\n\r\nvoid OGRE3DRenderable::_createProfile(NxOgre::Enums::RenderableType type)\r\n{\r\n switch(type)\r\n {\r\n case NxOgre::Enums::RenderableType_VisualDebugger:\r\n mProfile = OGRE3DRenderable::NXOGRE_VISUALDEBUGGER;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_PhysXMesh:\r\n mProfile = OGRE3DRenderable::NXOGRE_PHYSXMESH;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_ParticlePoints:\r\n mProfile = OGRE3DRenderable::NXOGRE_PARTICLEPOINTS;\r\n break;\r\n \r\n case NxOgre::Enums::RenderableType_SoftBody:\r\n mProfile = OGRE3DRenderable::NXOGRE_SOFTBODY;\r\n break;\r\n \r\n }\r\n}\r\n\r\nvoid OGRE3DRenderable::_initialise()\r\n{\r\n \/\/ Op.\r\n mRenderOp.operationType = mProfile.mRenderOperation;\r\n\r\n \/\/ Vertices and other vertex bits.\r\n mRenderOp.vertexData = new Ogre::VertexData;\r\n\r\n \/\/ Main vertex declartion. It is assumed that a Renderable has vertices.\r\n Ogre::VertexDeclaration* vDecl = mRenderOp.vertexData->vertexDeclaration;\r\n vDecl->addElement(VertexDeclaration_Position, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);\r\n \r\n \/\/ Normals.\r\n if (mProfile.usesNormals)\r\n vDecl->addElement(VertexDeclaration_Normal, 0, Ogre::VET_FLOAT3, Ogre::VES_NORMAL);\r\n \r\n \/\/ Vertex Colours.\r\n if (mProfile.usesColourVertices)\r\n vDecl->addElement(VertexDeclaration_Colour, 0, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE);\r\n \r\n if (mProfile.usesTextureCoordinates)\r\n vDecl->addElement(VertexDeclaration_TextureCoordinates, 0, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);\r\n\r\n \/\/ Vertex buffer capacity is zero.\r\n mVertexBufferCapacity = 0;\r\n\r\n\r\n \/\/ Do the indexes. If it has one.\r\n if (mRenderOp.useIndexes = mProfile.usesIndexes)\r\n mRenderOp.indexData = new Ogre::IndexData;\r\n\r\n\r\n mIndexBufferCapacity = 0;\r\n}\r\n\r\nvoid OGRE3DRenderable::_resize(size_t vertexCount, size_t indexCount)\r\n{\r\n \/\/ Prepare vertex buffer\r\n size_t newVertCapacity = mVertexBufferCapacity;\r\n if ((vertexCount > mVertexBufferCapacity) ||\r\n (!mVertexBufferCapacity))\r\n {\r\n \/\/ vertexCount exceeds current capacity!\r\n \/\/ It is necessary to reallocate the buffer.\r\n\r\n \/\/ Check if this is the first call\r\n if (!newVertCapacity)\r\n newVertCapacity = 1;\r\n\r\n \/\/ Make capacity the next power of two\r\n while (newVertCapacity < vertexCount)\r\n newVertCapacity <<= 1;\r\n }\r\n else if (vertexCount < mVertexBufferCapacity>>1) {\r\n \/\/ Make capacity the previous power of two\r\n while (vertexCount < newVertCapacity>>1)\r\n newVertCapacity >>= 1;\r\n }\r\n \r\n if (newVertCapacity != mVertexBufferCapacity) \r\n {\r\n mVertexBufferCapacity = newVertCapacity;\r\n \r\n \/\/ Create new vertex buffer\r\n mVertexBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Position),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Position, mVertexBuffer);\r\n \r\n \/\/ Colour vertices.\r\n if (this->mProfile.usesColourVertices)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mVertexColourBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Colour),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Colour, mVertexColourBuffer);\r\n }\r\n\r\n \/\/ Normals.\r\n if (this->mProfile.usesNormals)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mNormalBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_Normal),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_Normal, mNormalBuffer);\r\n }\r\n\r\n \/\/ Texture coords.\r\n if (this->mProfile.usesTextureCoordinates)\r\n {\r\n \/\/ Create new vertexColour buffer\r\n mTextureCoordsBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(\r\n mRenderOp.vertexData->vertexDeclaration->getVertexSize(VertexDeclaration_TextureCoordinates),\r\n mVertexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n \r\n \/\/ Bind buffer\r\n mRenderOp.vertexData->vertexBufferBinding->setBinding(VertexDeclaration_TextureCoordinates, mTextureCoordsBuffer);\r\n }\r\n\r\n }\r\n \/\/ Update vertex count in the render operation\r\n mRenderOp.vertexData->vertexCount = vertexCount;\r\n\r\n if (mProfile.usesIndexes)\r\n {\r\n OgreAssert(indexCount <= std::numeric_limits<unsigned short>::max(), \"indexCount exceeds 16 bit\");\r\n\r\n size_t newIndexCapacity = mIndexBufferCapacity;\r\n \/\/ Prepare index buffer\r\n if ((indexCount > newIndexCapacity) || (!newIndexCapacity))\r\n {\r\n \/\/ indexCount exceeds current capacity!\r\n \/\/ It is necessary to reallocate the buffer.\r\n \/\/ Check if this is the first call\r\n if (!newIndexCapacity)\r\n newIndexCapacity = 1;\r\n \/\/ Make capacity the next power of two\r\n while (newIndexCapacity < indexCount)\r\n newIndexCapacity <<= 1;\r\n }\r\n else if (indexCount < newIndexCapacity>>1) \r\n {\r\n \/\/ Make capacity the previous power of two\r\n while (indexCount < newIndexCapacity>>1)\r\n newIndexCapacity >>= 1;\r\n }\r\n \r\n if (newIndexCapacity != mIndexBufferCapacity)\r\n {\r\n mIndexBufferCapacity = newIndexCapacity;\r\n \/\/ Create new index buffer\r\n mIndexBuffer = mRenderOp.indexData->indexBuffer =\r\n Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(\r\n Ogre::HardwareIndexBuffer::IndexType(!mProfile.uses16BitIndexes),\r\n mIndexBufferCapacity,\r\n Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); \/\/ TODO: Custom HBU_?\r\n }\r\n \r\n \/\/ Update index count in the render operation\r\n mRenderOp.indexData->indexCount = indexCount;\r\n }\r\n}\r\n\r\nfloat OGRE3DRenderable::getBoundingRadius(void) const\r\n{\r\n return Ogre::Math::Sqrt(std::max(mBox.getMaximum().squaredLength(), mBox.getMinimum().squaredLength()));\r\n}\r\n\r\nfloat OGRE3DRenderable::getSquaredViewDepth(const Ogre::Camera* cam) const\r\n{\r\n Ogre::Vector3 vMin, vMax, vMid, vDist;\r\n vMin = mBox.getMinimum();\r\n vMax = mBox.getMaximum();\r\n vMid = ((vMax - vMin) * 0.5) + vMin;\r\n vDist = cam->getDerivedPosition() - vMid;\r\n return vDist.squaredLength();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"TMVA\/RModelParser_ONNX.hxx\"\n#include \"onnx_proto3.pb.h\"\n\n#include <string>\n#include <memory>\n\nnamespace TMVA{\nnamespace Experimental{\nnamespace SOFIE{\n\nnamespace INTERNAL{\n\nstd::unique_ptr<ROperator> make_ROperator(size_t idx, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n const auto& nodeproto = graphproto.node(idx);\n auto find = mapOptypeOperator.find(nodeproto.op_type());\n if (find == mapOptypeOperator.end()){\n throw std::runtime_error(\"TMVA::SOFIE - Operator type \" + nodeproto.op_type() + \" is not yet supported\");\n }else{\n return (find->second)(nodeproto, graphproto, tensor_type);\n }\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Transpose(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser tranpose op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n std::vector<int_t> attr_perm;\n\n if (nodeproto.attribute_size() == 1){\n attr_perm.assign(nodeproto.attribute(0).ints().begin(), nodeproto.attribute(0).ints().end());\n }\n\n switch(input_type){\n case ETensorType::FLOAT:\n if (!attr_perm.empty()){\n op.reset(new ROperator_Transpose<float>(attr_perm, nodeproto.input(0), nodeproto.output(0)));\n }else{\n op.reset(new ROperator_Transpose<float> (nodeproto.input(0), nodeproto.output(0)));\n }\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Transpose does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n\n return std::move(op);\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Relu(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser relu op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n\n\n switch(input_type){\n case ETensorType::FLOAT:\n op.reset(new ROperator_Relu<float>(nodeproto.input(0), nodeproto.output(0)));\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Relu does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n return std::move(op);\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Gemm(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser gemm op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n\n float attr_alpha =1.0;\n float attr_beta =1.0;\n int_t attr_transA =0;\n int_t attr_transB =0;\n\n for (int i = 0; i < nodeproto.attribute_size(); i++){\n std::string attribute_name = nodeproto.attribute(i).name();\n if (attribute_name == \"alpha\"){\n attr_alpha = nodeproto.attribute(i).f();\n }else if(attribute_name == \"beta\"){\n attr_beta = nodeproto.attribute(i).f();\n }else if(attribute_name == \"transA\"){\n attr_transA = nodeproto.attribute(i).i();\n if (attr_transA != 0 && attr_transA != 1) throw std::runtime_error(\"TMVA::SOFIE Error - Model Loading - attribute transA in Operator Gemm not 0\/1\");\n }else if(attribute_name == \"transB\"){\n attr_transB = nodeproto.attribute(i).i();\n if (attr_transB != 0 && attr_transB != 1) throw std::runtime_error(\"TMVA::SOFIE Error - Model Loading - attribute transB in Operator Gemm not 0\/1\");\n }else{\n std::cout << \"TMVA::SOFIE Warning - Model Loading - Attribute \" << attribute_name << \" in OperatorNode \" << nodeproto.name() << \" is not defined in ONNX IR and not applied!\\n\";\n }\n }\n\n\n switch(input_type){\n case ETensorType::FLOAT:\n if (nodeproto.input_size() == 2){\n op.reset(new ROperator_Gemm<float>(attr_alpha, attr_beta, attr_transA, attr_transB, nodeproto.input(0), nodeproto.input(1), nodeproto.output(0)));\n }else{\n op.reset(new ROperator_Gemm<float>(attr_alpha, attr_beta, attr_transA, attr_transB, nodeproto.input(0), nodeproto.input(1), nodeproto.input(2), nodeproto.output(0)));\n }\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Relu does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type, input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n\n return std::move(op);\n}\n\n} \/\/INTERNAL\n\n\n\nRModel RModelParser_ONNX::Parse(std::string filename){\n char sep = '\/';\n #ifdef _WIN32\n sep = '\\\\';\n #endif\n size_t i = filename.rfind(sep, filename.length());\n std::string modelname;\n if (i != std::string::npos){\n filename = (filename.substr(i+1, filename.length() - i));\n }\n\n\n\n std::time_t ttime = std::time(0);\n std::tm* gmt_time = std::gmtime(&ttime);\n std::string parsetime (std::asctime(gmt_time));\n\n\n\n\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n \/\/model I\/O\n onnx::ModelProto model;\n RModel rmodel(filename, parsetime);\n\n std::unordered_map<std::string, ETensorType> tensor_type;\n\n std::fstream input(filename, std::ios::in | std::ios::binary);\n if (!model.ParseFromIstream(&input)){\n throw std::runtime_error(\"TMVA::SOFIE - Failed to parse onnx file\");\n }\n\n const onnx::GraphProto& graph = model.graph(); \/\/not a memory leak. model freed automatically at the end.\n google::protobuf::ShutdownProtobufLibrary();\n\n std::unordered_set<std::string> initializer_names;\n for (int i=0; i < graph.initializer_size(); i++){\n initializer_names.insert(graph.initializer(i).name());\n }\n\n\n for (int i=0; i < graph.input_size(); i++){\n\n tensor_type[graph.input(i).name()] = static_cast<ETensorType>(graph.input(i).type().tensor_type().elem_type());\n\n if (initializer_names.find(graph.input(i).name()) != initializer_names.end()) continue;\n\n \/\/input datanode is not a weight node (has no initializer)\n const onnx::ValueInfoProto& valueinfoproto = graph.input(i);\n std::string input_name = valueinfoproto.name();\n ETensorType type = static_cast<ETensorType>(valueinfoproto.type().tensor_type().elem_type());\n if (type != ETensorType::FLOAT){\n throw std::runtime_error(\"TMVA::SOFIE Data type in input tensor \" + input_name + \" not supported!\\n\");\n }\n\n std::vector<Dim> fShape;\n bool existParam = false;\n if (!valueinfoproto.type().tensor_type().has_shape()) throw std::runtime_error(\"TMVA::SOFIE datanode with no shape restrictions is not supported yet\");\n for (int i = 0; i < valueinfoproto.type().tensor_type().shape().dim_size(); i++){\n Dim dim;\n if (valueinfoproto.type().tensor_type().shape().dim(i).value_case() == onnx::TensorShapeProto_Dimension::ValueCase::kDimValue){\n dim.dim = valueinfoproto.type().tensor_type().shape().dim(i).dim_value();\n }else if (valueinfoproto.type().tensor_type().shape().dim(i).value_case() == onnx::TensorShapeProto_Dimension::ValueCase::kDimParam){\n dim.isParam = true;\n existParam = true;\n dim.param = valueinfoproto.type().tensor_type().shape().dim(i).dim_param();\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX file error: Valueinfoproto \" + input_name + \" has neither dim_value nor dim_param! \\n\");\n }\n fShape.push_back(dim);\n }\n if (valueinfoproto.type().tensor_type().shape().dim_size() == 0){\n Dim dim;\n dim.dim = 1;\n fShape.push_back(dim);\n } \/\/in case this TensorShapeProto has no dimension message: ONNX IR defines this to be a scalar\n\n if (!existParam){\n std::vector<size_t> fShape_sizet;\n for (auto& i: fShape){\n fShape_sizet.push_back(i.dim);\n }\n\n rmodel.AddInputTensorInfo(input_name, type, fShape_sizet);\n }else{\n rmodel.AddInputTensorInfo(input_name, type, fShape);\n }\n\n }\n\n for (int i=0; i < graph.initializer_size(); i++){\n onnx::TensorProto* tensorproto = const_cast<onnx::TensorProto*>(&graph.initializer(i));\n std::vector<std::size_t> fShape;\n std::size_t fLength = 1;\n for (int i = 0; i < tensorproto->dims_size(); i++){\n fShape.push_back(tensorproto->dims(i));\n fLength *= tensorproto->dims(i);\n }\n\n std::string input_name = graph.initializer(i).name();\n\n switch(static_cast<ETensorType>(graph.initializer(i).data_type())){\n case ETensorType::FLOAT : {\n \/\/void* data = malloc (fLength * sizeof(float));\n std::shared_ptr<void> data(malloc(fLength * sizeof(float)), free);\n\n if (tensorproto->raw_data().empty() == false){\n auto raw_data_ptr = reinterpret_cast<float*>(const_cast<char*>(tensorproto->raw_data().c_str()));\n std::memcpy(data.get(), raw_data_ptr, fLength * sizeof(float));\n }else{\n tensorproto->mutable_float_data()->ExtractSubrange(0, tensorproto->float_data_size(), static_cast<float*>(data.get()));\n }\n\n rmodel.AddInitializedTensor(input_name, ETensorType::FLOAT, fShape, data);\n break;\n }\n default: throw std::runtime_error(\"Data type in weight tensor \" + graph.initializer(i).name() + \" not supported!\\n\");\n }\n }\n\n\n\n for (int i=0; i < graph.node_size(); i++){\n rmodel.AddOperator(std::move(INTERNAL::make_ROperator(i, graph, tensor_type)));\n }\n\n std::vector<std::string> outputnames;\n for (int i=0; i < graph.output_size(); i++){\n outputnames.push_back(graph.output(i).name());\n }\n rmodel.AddOutputTensorNameList(outputnames);\n\n return rmodel;\n\n}\n\n\n\n}\/\/SOFIE\n}\/\/Experimental\n}\/\/TMVA\n<commit_msg>Keeping the filename variable intact in Parse() so that models can be read not only from the current dir (#8725)<commit_after>#include \"TMVA\/RModelParser_ONNX.hxx\"\n#include \"onnx_proto3.pb.h\"\n\n#include <string>\n#include <memory>\n\nnamespace TMVA{\nnamespace Experimental{\nnamespace SOFIE{\n\nnamespace INTERNAL{\n\nstd::unique_ptr<ROperator> make_ROperator(size_t idx, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n const auto& nodeproto = graphproto.node(idx);\n auto find = mapOptypeOperator.find(nodeproto.op_type());\n if (find == mapOptypeOperator.end()){\n throw std::runtime_error(\"TMVA::SOFIE - Operator type \" + nodeproto.op_type() + \" is not yet supported\");\n }else{\n return (find->second)(nodeproto, graphproto, tensor_type);\n }\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Transpose(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser tranpose op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n std::vector<int_t> attr_perm;\n\n if (nodeproto.attribute_size() == 1){\n attr_perm.assign(nodeproto.attribute(0).ints().begin(), nodeproto.attribute(0).ints().end());\n }\n\n switch(input_type){\n case ETensorType::FLOAT:\n if (!attr_perm.empty()){\n op.reset(new ROperator_Transpose<float>(attr_perm, nodeproto.input(0), nodeproto.output(0)));\n }else{\n op.reset(new ROperator_Transpose<float> (nodeproto.input(0), nodeproto.output(0)));\n }\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Transpose does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n\n return std::move(op);\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Relu(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser relu op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n\n\n switch(input_type){\n case ETensorType::FLOAT:\n op.reset(new ROperator_Relu<float>(nodeproto.input(0), nodeproto.output(0)));\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Relu does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n return std::move(op);\n}\n\nstd::unique_ptr<ROperator> make_ROperator_Gemm(const onnx::NodeProto& nodeproto, const onnx::GraphProto& graphproto, std::unordered_map<std::string, ETensorType>& tensor_type){\n\n ETensorType input_type;\n\n auto input_name = nodeproto.input(0);\n auto it = tensor_type.find(input_name);\n if (it != tensor_type.end()){\n input_type = it->second;\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX Parser gemm op has input tensor\" + input_name + \" but its type is not yet registered\");\n }\n\n std::unique_ptr<ROperator> op;\n\n float attr_alpha =1.0;\n float attr_beta =1.0;\n int_t attr_transA =0;\n int_t attr_transB =0;\n\n for (int i = 0; i < nodeproto.attribute_size(); i++){\n std::string attribute_name = nodeproto.attribute(i).name();\n if (attribute_name == \"alpha\"){\n attr_alpha = nodeproto.attribute(i).f();\n }else if(attribute_name == \"beta\"){\n attr_beta = nodeproto.attribute(i).f();\n }else if(attribute_name == \"transA\"){\n attr_transA = nodeproto.attribute(i).i();\n if (attr_transA != 0 && attr_transA != 1) throw std::runtime_error(\"TMVA::SOFIE Error - Model Loading - attribute transA in Operator Gemm not 0\/1\");\n }else if(attribute_name == \"transB\"){\n attr_transB = nodeproto.attribute(i).i();\n if (attr_transB != 0 && attr_transB != 1) throw std::runtime_error(\"TMVA::SOFIE Error - Model Loading - attribute transB in Operator Gemm not 0\/1\");\n }else{\n std::cout << \"TMVA::SOFIE Warning - Model Loading - Attribute \" << attribute_name << \" in OperatorNode \" << nodeproto.name() << \" is not defined in ONNX IR and not applied!\\n\";\n }\n }\n\n\n switch(input_type){\n case ETensorType::FLOAT:\n if (nodeproto.input_size() == 2){\n op.reset(new ROperator_Gemm<float>(attr_alpha, attr_beta, attr_transA, attr_transB, nodeproto.input(0), nodeproto.input(1), nodeproto.output(0)));\n }else{\n op.reset(new ROperator_Gemm<float>(attr_alpha, attr_beta, attr_transA, attr_transB, nodeproto.input(0), nodeproto.input(1), nodeproto.input(2), nodeproto.output(0)));\n }\n break;\n default:\n throw std::runtime_error(\"TMVA::SOFIE - Unsupported - Operator Relu does not yet support input type \" + std::to_string(static_cast<int>(input_type)));\n }\n\n ETensorType output_type = (op->TypeInference({input_type, input_type}))[0];\n auto it2 = tensor_type.find(nodeproto.output(0));\n if (it2 == tensor_type.end()){\n tensor_type[nodeproto.output(0)] = output_type;\n }\n\n\n return std::move(op);\n}\n\n} \/\/INTERNAL\n\n\n\nRModel RModelParser_ONNX::Parse(std::string filename){\n char sep = '\/';\n #ifdef _WIN32\n sep = '\\\\';\n #endif\n size_t i = filename.rfind(sep, filename.length());\n std::string filename_nodir = filename;\n if (i != std::string::npos){\n filename_nodir = (filename.substr(i+1, filename.length() - i));\n }\n\n\n\n std::time_t ttime = std::time(0);\n std::tm* gmt_time = std::gmtime(&ttime);\n std::string parsetime (std::asctime(gmt_time));\n\n\n\n\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n \/\/model I\/O\n onnx::ModelProto model;\n RModel rmodel(filename_nodir, parsetime);\n\n std::unordered_map<std::string, ETensorType> tensor_type;\n\n std::fstream input(filename, std::ios::in | std::ios::binary);\n if (!model.ParseFromIstream(&input)){\n throw std::runtime_error(\"TMVA::SOFIE - Failed to parse onnx file\");\n }\n\n const onnx::GraphProto& graph = model.graph(); \/\/not a memory leak. model freed automatically at the end.\n google::protobuf::ShutdownProtobufLibrary();\n\n std::unordered_set<std::string> initializer_names;\n for (int i=0; i < graph.initializer_size(); i++){\n initializer_names.insert(graph.initializer(i).name());\n }\n\n\n for (int i=0; i < graph.input_size(); i++){\n\n tensor_type[graph.input(i).name()] = static_cast<ETensorType>(graph.input(i).type().tensor_type().elem_type());\n\n if (initializer_names.find(graph.input(i).name()) != initializer_names.end()) continue;\n\n \/\/input datanode is not a weight node (has no initializer)\n const onnx::ValueInfoProto& valueinfoproto = graph.input(i);\n std::string input_name = valueinfoproto.name();\n ETensorType type = static_cast<ETensorType>(valueinfoproto.type().tensor_type().elem_type());\n if (type != ETensorType::FLOAT){\n throw std::runtime_error(\"TMVA::SOFIE Data type in input tensor \" + input_name + \" not supported!\\n\");\n }\n\n std::vector<Dim> fShape;\n bool existParam = false;\n if (!valueinfoproto.type().tensor_type().has_shape()) throw std::runtime_error(\"TMVA::SOFIE datanode with no shape restrictions is not supported yet\");\n for (int i = 0; i < valueinfoproto.type().tensor_type().shape().dim_size(); i++){\n Dim dim;\n if (valueinfoproto.type().tensor_type().shape().dim(i).value_case() == onnx::TensorShapeProto_Dimension::ValueCase::kDimValue){\n dim.dim = valueinfoproto.type().tensor_type().shape().dim(i).dim_value();\n }else if (valueinfoproto.type().tensor_type().shape().dim(i).value_case() == onnx::TensorShapeProto_Dimension::ValueCase::kDimParam){\n dim.isParam = true;\n existParam = true;\n dim.param = valueinfoproto.type().tensor_type().shape().dim(i).dim_param();\n }else{\n throw std::runtime_error(\"TMVA::SOFIE ONNX file error: Valueinfoproto \" + input_name + \" has neither dim_value nor dim_param! \\n\");\n }\n fShape.push_back(dim);\n }\n if (valueinfoproto.type().tensor_type().shape().dim_size() == 0){\n Dim dim;\n dim.dim = 1;\n fShape.push_back(dim);\n } \/\/in case this TensorShapeProto has no dimension message: ONNX IR defines this to be a scalar\n\n if (!existParam){\n std::vector<size_t> fShape_sizet;\n for (auto& i: fShape){\n fShape_sizet.push_back(i.dim);\n }\n\n rmodel.AddInputTensorInfo(input_name, type, fShape_sizet);\n }else{\n rmodel.AddInputTensorInfo(input_name, type, fShape);\n }\n\n }\n\n for (int i=0; i < graph.initializer_size(); i++){\n onnx::TensorProto* tensorproto = const_cast<onnx::TensorProto*>(&graph.initializer(i));\n std::vector<std::size_t> fShape;\n std::size_t fLength = 1;\n for (int i = 0; i < tensorproto->dims_size(); i++){\n fShape.push_back(tensorproto->dims(i));\n fLength *= tensorproto->dims(i);\n }\n\n std::string input_name = graph.initializer(i).name();\n\n switch(static_cast<ETensorType>(graph.initializer(i).data_type())){\n case ETensorType::FLOAT : {\n \/\/void* data = malloc (fLength * sizeof(float));\n std::shared_ptr<void> data(malloc(fLength * sizeof(float)), free);\n\n if (tensorproto->raw_data().empty() == false){\n auto raw_data_ptr = reinterpret_cast<float*>(const_cast<char*>(tensorproto->raw_data().c_str()));\n std::memcpy(data.get(), raw_data_ptr, fLength * sizeof(float));\n }else{\n tensorproto->mutable_float_data()->ExtractSubrange(0, tensorproto->float_data_size(), static_cast<float*>(data.get()));\n }\n\n rmodel.AddInitializedTensor(input_name, ETensorType::FLOAT, fShape, data);\n break;\n }\n default: throw std::runtime_error(\"Data type in weight tensor \" + graph.initializer(i).name() + \" not supported!\\n\");\n }\n }\n\n\n\n for (int i=0; i < graph.node_size(); i++){\n rmodel.AddOperator(std::move(INTERNAL::make_ROperator(i, graph, tensor_type)));\n }\n\n std::vector<std::string> outputnames;\n for (int i=0; i < graph.output_size(); i++){\n outputnames.push_back(graph.output(i).name());\n }\n rmodel.AddOutputTensorNameList(outputnames);\n\n return rmodel;\n\n}\n\n\n\n}\/\/SOFIE\n}\/\/Experimental\n}\/\/TMVA\n<|endoftext|>"} {"text":"<commit_before><commit_msg>planning: refactored end condition sampler<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: xmlfiltersettingsdialog.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2003-10-06 14:18:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _XMLFILTERSETTINGSDIALOG_HXX_\n#define _XMLFILTERSETTINGSDIALOG_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAME_HPP_\n#include <com\/sun\/star\/container\/XHierarchicalName.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n\n#ifndef _SVTABBX_HXX\n#include <svtools\/svtabbx.hxx>\n#endif\n\n#ifndef _SFXPOOLITEM_HXX\n#include <svtools\/poolitem.hxx>\n#endif\n\n#include \"xmlfiltercommon.hxx\"\n\n\/\/ --------------------------------------------------------------------\n\nclass SvxPathControl_Impl : public Control\n{\nprivate:\n Control* m_pFocusCtrl;\n\npublic:\n SvxPathControl_Impl( Window* pParent, const ResId& rId ) :\n Control( pParent, rId ), m_pFocusCtrl( NULL ) {}\n\n void SetFocusControl( Control* pCtrl ) { m_pFocusCtrl = pCtrl; }\n\n virtual long Notify( NotifyEvent& rNEvt );\n};\n\n\/\/ --------------------------------------------------------------------\n\nclass HeaderBar;\n\nclass XMLFilterListBox : public SvTabListBox\n{\nprivate:\n bool mbFirstPaint;\n HeaderBar* mpHeaderBar;\n\n DECL_LINK( TabBoxScrollHdl_Impl, SvTabListBox* );\n DECL_LINK( HeaderSelect_Impl, HeaderBar* );\n DECL_LINK( HeaderEndDrag_Impl, HeaderBar* );\n\n String getEntryString( const filter_info_impl* pInfo ) const;\n\npublic:\n XMLFilterListBox( SvxPathControl_Impl* pParent );\n ~XMLFilterListBox();\n\n void Reset();\n\n \/** adds a new filter info entry to the ui filter list *\/\n void addFilterEntry( const filter_info_impl* pInfo );\n\n void changeEntry( const filter_info_impl* pInfo );\n\n virtual void Paint( const Rectangle& rRect );\n};\n\n\/\/ --------------------------------------------------------------------\n\nclass XMLFilterTestDialog;\n\nclass XMLFilterSettingsDialog : public WorkWindow\n{\npublic:\n XMLFilterSettingsDialog( Window* pParent, ResMgr& rResMgr, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxMSF );\n virtual ~XMLFilterSettingsDialog();\n\n DECL_LINK(ClickHdl_Impl, PushButton * );\n DECL_LINK(SelectionChangedHdl_Impl, void * );\n DECL_LINK(DoubleClickHdl_Impl, void * );\n\n void Show();\n\n void onNew();\n void onEdit();\n void onTest();\n void onDelete();\n void onSave();\n void onOpen();\n void onClose();\n\n void updateStates();\n\n virtual long Notify( NotifyEvent& rNEvt );\n\n bool isClosable();\n\n static ResMgr* mpResMgr;\n\nprivate:\n void initFilterList();\n void disposeFilterList();\n\n bool insertOrEdit( filter_info_impl* pNewInfo, const filter_info_impl* pOldInfo = NULL );\n\n rtl::OUString createUniqueFilterName( const rtl::OUString& rUIName );\n rtl::OUString createUniqueTypeName( const rtl::OUString& rTypeName );\n rtl::OUString createUniqueInterfaceName( const rtl::OUString& rInterfaceName );\n\nprivate:\n bool mbIsClosable;\n\n com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxFilterContainer;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxTypeDetection;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxExtendedTypeDetection;\n\n std::vector< filter_info_impl* > maFilterVector;\n\n XMLFilterListBox* mpFilterListBox;\n SvxPathControl_Impl maCtrlFilterList;\n PushButton maPBNew;\n PushButton maPBEdit;\n PushButton maPBTest;\n PushButton maPBDelete;\n PushButton maPBSave;\n PushButton maPBOpen;\n HelpButton maPBHelp;\n PushButton maPBClose;\n\n ::rtl::OUString sTemplatePath;\n ::rtl::OUString sDocTypePrefix;\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS os12 (1.3.50); FILE MERGED 2004\/04\/07 11:05:12 os 1.3.50.1: #115816# incorporate interface changes from #103299#<commit_after>\/*************************************************************************\n *\n * $RCSfile: xmlfiltersettingsdialog.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-04-29 16:13:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _XMLFILTERSETTINGSDIALOG_HXX_\n#define _XMLFILTERSETTINGSDIALOG_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAME_HPP_\n#include <com\/sun\/star\/container\/XHierarchicalName.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n\n#ifndef _SVTABBX_HXX\n#include <svtools\/svtabbx.hxx>\n#endif\n\n#ifndef _SFXPOOLITEM_HXX\n#include <svtools\/poolitem.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX\n#include <svtools\/moduleoptions.hxx>\n#endif\n\n#include \"xmlfiltercommon.hxx\"\n\n\/\/ --------------------------------------------------------------------\n\nclass SvxPathControl_Impl : public Control\n{\nprivate:\n Control* m_pFocusCtrl;\n\npublic:\n SvxPathControl_Impl( Window* pParent, const ResId& rId ) :\n Control( pParent, rId ), m_pFocusCtrl( NULL ) {}\n\n void SetFocusControl( Control* pCtrl ) { m_pFocusCtrl = pCtrl; }\n\n virtual long Notify( NotifyEvent& rNEvt );\n};\n\n\/\/ --------------------------------------------------------------------\n\nclass HeaderBar;\n\nclass XMLFilterListBox : public SvTabListBox\n{\nprivate:\n bool mbFirstPaint;\n HeaderBar* mpHeaderBar;\n\n DECL_LINK( TabBoxScrollHdl_Impl, SvTabListBox* );\n DECL_LINK( HeaderSelect_Impl, HeaderBar* );\n DECL_LINK( HeaderEndDrag_Impl, HeaderBar* );\n\n String getEntryString( const filter_info_impl* pInfo ) const;\n\npublic:\n XMLFilterListBox( SvxPathControl_Impl* pParent );\n ~XMLFilterListBox();\n\n void Reset();\n\n \/** adds a new filter info entry to the ui filter list *\/\n void addFilterEntry( const filter_info_impl* pInfo );\n\n void changeEntry( const filter_info_impl* pInfo );\n\n virtual void Paint( const Rectangle& rRect );\n};\n\n\/\/ --------------------------------------------------------------------\n\nclass XMLFilterTestDialog;\n\nclass XMLFilterSettingsDialog : public WorkWindow\n{\npublic:\n XMLFilterSettingsDialog( Window* pParent, ResMgr& rResMgr, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxMSF );\n virtual ~XMLFilterSettingsDialog();\n\n DECL_LINK(ClickHdl_Impl, PushButton * );\n DECL_LINK(SelectionChangedHdl_Impl, void * );\n DECL_LINK(DoubleClickHdl_Impl, void * );\n\n void Show();\n\n void onNew();\n void onEdit();\n void onTest();\n void onDelete();\n void onSave();\n void onOpen();\n void onClose();\n\n void updateStates();\n\n virtual long Notify( NotifyEvent& rNEvt );\n\n bool isClosable();\n\n static ResMgr* mpResMgr;\n\nprivate:\n void initFilterList();\n void disposeFilterList();\n\n bool insertOrEdit( filter_info_impl* pNewInfo, const filter_info_impl* pOldInfo = NULL );\n\n rtl::OUString createUniqueFilterName( const rtl::OUString& rUIName );\n rtl::OUString createUniqueTypeName( const rtl::OUString& rTypeName );\n rtl::OUString createUniqueInterfaceName( const rtl::OUString& rInterfaceName );\n\nprivate:\n bool mbIsClosable;\n\n com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxFilterContainer;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxTypeDetection;\n com::sun::star::uno::Reference< com::sun::star::container::XNameContainer > mxExtendedTypeDetection;\n\n std::vector< filter_info_impl* > maFilterVector;\n\n XMLFilterListBox* mpFilterListBox;\n SvxPathControl_Impl maCtrlFilterList;\n PushButton maPBNew;\n PushButton maPBEdit;\n PushButton maPBTest;\n PushButton maPBDelete;\n PushButton maPBSave;\n PushButton maPBOpen;\n HelpButton maPBHelp;\n PushButton maPBClose;\n\n ::rtl::OUString sTemplatePath;\n ::rtl::OUString sDocTypePrefix;\n\n SvtModuleOptions maModuleOpt;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rootactiontriggercontainer.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 00:08:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n#define __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n\n#include <helper\/propertysetcontainer.hxx>\n\n#ifndef _SV_MENU_HXX\n#include <vcl\/menu.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include <com\/sun\/star\/lang\/XUnoTunnel.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include <com\/sun\/star\/lang\/XTypeProvider.hpp>\n#endif\n\n#define IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER \"com.sun.star.comp.ui.RootActionTriggerContainer\"\n\n\nnamespace framework\n{\n\nclass RootActionTriggerContainer : public PropertySetContainer,\n public com::sun::star::lang::XMultiServiceFactory,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::lang::XUnoTunnel,\n public com::sun::star::lang::XTypeProvider\n{\n public:\n RootActionTriggerContainer( const Menu* pMenu, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager );\n virtual ~RootActionTriggerContainer();\n\n const Menu* GetMenu();\n\n ::com::sun::star::uno::Sequence< sal_Int8 > GetUnoTunnelId() const;\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire() throw ();\n virtual void SAL_CALL release() throw ();\n\n \/\/ XMultiServiceFactory\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( const ::rtl::OUString& aServiceSpecifier )\n throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments )\n throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexContainer\n virtual void SAL_CALL insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeByIndex( sal_Int32 Index )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexReplace\n virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexAccess\n virtual sal_Int32 SAL_CALL getCount()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasElements()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n void FillContainer();\n\n sal_Bool m_bContainerCreated;\n sal_Bool m_bContainerChanged;\n sal_Bool m_bInContainerCreation;\n const Menu* m_pMenu;\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.458); FILE MERGED 2008\/04\/01 15:18:15 thb 1.2.458.3: #i85898# Stripping all external header guards 2008\/04\/01 10:57:44 thb 1.2.458.2: #i85898# Stripping all external header guards 2008\/03\/28 15:34:34 rt 1.2.458.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rootactiontriggercontainer.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n#define __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n\n#include <helper\/propertysetcontainer.hxx>\n#include <vcl\/menu.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XUnoTunnel.hpp>\n#include <com\/sun\/star\/lang\/XTypeProvider.hpp>\n\n#define IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER \"com.sun.star.comp.ui.RootActionTriggerContainer\"\n\n\nnamespace framework\n{\n\nclass RootActionTriggerContainer : public PropertySetContainer,\n public com::sun::star::lang::XMultiServiceFactory,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::lang::XUnoTunnel,\n public com::sun::star::lang::XTypeProvider\n{\n public:\n RootActionTriggerContainer( const Menu* pMenu, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager );\n virtual ~RootActionTriggerContainer();\n\n const Menu* GetMenu();\n\n ::com::sun::star::uno::Sequence< sal_Int8 > GetUnoTunnelId() const;\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire() throw ();\n virtual void SAL_CALL release() throw ();\n\n \/\/ XMultiServiceFactory\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( const ::rtl::OUString& aServiceSpecifier )\n throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments )\n throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexContainer\n virtual void SAL_CALL insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeByIndex( sal_Int32 Index )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexReplace\n virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XIndexAccess\n virtual sal_Int32 SAL_CALL getCount()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XElementAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType()\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL hasElements()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n void FillContainer();\n\n sal_Bool m_bContainerCreated;\n sal_Bool m_bContainerChanged;\n sal_Bool m_bInContainerCreation;\n const Menu* m_pMenu;\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_CLASSES_ROOTACTIONTRIGGERCONTAINER_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- PrologEpilogInserter.cpp - Insert Prolog\/Epilog code in function --===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass is responsible for finalizing the functions frame layout, saving\n\/\/ callee saved registers, and for emitting prolog & epilog code for the\n\/\/ function.\n\/\/\n\/\/ This pass must be run after register allocation. After this pass is\n\/\/ executed, it is illegal to construct MO_FrameIndex operands.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\nnamespace {\n struct PEI : public MachineFunctionPass {\n const char *getPassName() const {\n return \"Prolog\/Epilog Insertion & Frame Finalization\";\n }\n\n \/\/\/ runOnMachineFunction - Insert prolog\/epilog code and replace abstract\n \/\/\/ frame indexes with appropriate references.\n \/\/\/\n bool runOnMachineFunction(MachineFunction &Fn) {\n \/\/ Scan the function for modified caller saved registers and insert spill\n \/\/ code for any caller saved registers that are modified. Also calculate\n \/\/ the MaxCallFrameSize and HasCalls variables for the function's frame\n \/\/ information and eliminates call frame pseudo instructions.\n calculateCallerSavedRegisters(Fn);\n\n \/\/ Add the code to save and restore the caller saved registers\n saveCallerSavedRegisters(Fn);\n\n \/\/ Allow the target machine to make final modifications to the function\n \/\/ before the frame layout is finalized.\n Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);\n\n \/\/ Calculate actual frame offsets for all of the abstract stack objects...\n calculateFrameObjectOffsets(Fn);\n\n \/\/ Add prolog and epilog code to the function. This function is required\n \/\/ to align the stack frame as necessary for any stack variables or\n \/\/ called functions. Because of this, calculateCallerSavedRegisters\n \/\/ must be called before this function in order to set the HasCalls\n \/\/ and MaxCallFrameSize variables.\n insertPrologEpilogCode(Fn);\n\n \/\/ Replace all MO_FrameIndex operands with physical register references\n \/\/ and actual offsets.\n \/\/\n replaceFrameIndices(Fn);\n\n RegsToSave.clear();\n StackSlots.clear();\n return true;\n }\n\n private:\n std::vector<unsigned> RegsToSave;\n std::vector<int> StackSlots;\n\n void calculateCallerSavedRegisters(MachineFunction &Fn);\n void saveCallerSavedRegisters(MachineFunction &Fn);\n void calculateFrameObjectOffsets(MachineFunction &Fn);\n void replaceFrameIndices(MachineFunction &Fn);\n void insertPrologEpilogCode(MachineFunction &Fn);\n };\n}\n\n\n\/\/\/ createPrologEpilogCodeInserter - This function returns a pass that inserts\n\/\/\/ prolog and epilog code, and eliminates abstract frame references.\n\/\/\/\nFunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }\n\n\n\/\/\/ calculateCallerSavedRegisters - Scan the function for modified caller saved\n\/\/\/ registers. Also calculate the MaxCallFrameSize and HasCalls variables for\n\/\/\/ the function's frame information and eliminates call frame pseudo\n\/\/\/ instructions.\n\/\/\/\nvoid PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {\n const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();\n const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();\n\n \/\/ Get the callee saved register list...\n const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();\n\n \/\/ Get the function call frame set-up and tear-down instruction opcode\n int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();\n int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();\n\n \/\/ Early exit for targets which have no callee saved registers and no call\n \/\/ frame setup\/destroy pseudo instructions.\n if ((CSRegs == 0 || CSRegs[0] == 0) &&\n FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)\n return;\n\n \/\/ This bitset contains an entry for each physical register for the target...\n std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());\n unsigned MaxCallFrameSize = 0;\n bool HasCalls = false;\n\n for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)\n for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )\n if (I->getOpcode() == FrameSetupOpcode ||\n I->getOpcode() == FrameDestroyOpcode) {\n assert(I->getNumOperands() == 1 && \"Call Frame Setup\/Destroy Pseudo\"\n \" instructions should have a single immediate argument!\");\n unsigned Size = I->getOperand(0).getImmedValue();\n if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;\n HasCalls = true;\n RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);\n } else {\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {\n MachineOperand &MO = I->getOperand(i);\n if (MO.isRegister() && MO.isDef()) {\n assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&\n \"Register allocation must be performed!\");\n ModifiedRegs[MO.getReg()] = true; \/\/ Register is modified\n }\n }\n ++I;\n }\n\n MachineFrameInfo *FFI = Fn.getFrameInfo();\n FFI->setHasCalls(HasCalls);\n FFI->setMaxCallFrameSize(MaxCallFrameSize);\n\n \/\/ Now figure out which *callee saved* registers are modified by the current\n \/\/ function, thus needing to be saved and restored in the prolog\/epilog.\n \/\/\n for (unsigned i = 0; CSRegs[i]; ++i) {\n unsigned Reg = CSRegs[i];\n if (ModifiedRegs[Reg]) {\n RegsToSave.push_back(Reg); \/\/ If modified register...\n } else {\n for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);\n *AliasSet; ++AliasSet) { \/\/ Check alias registers too...\n if (ModifiedRegs[*AliasSet]) {\n RegsToSave.push_back(Reg);\n break;\n }\n }\n }\n }\n\n if (RegsToSave.empty())\n return; \/\/ Early exit if no caller saved registers are modified!\n\n unsigned NumFixedSpillSlots;\n const std::pair<unsigned,int> *FixedSpillSlots =\n TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);\n\n \/\/ Now that we know which registers need to be saved and restored, allocate\n \/\/ stack slots for them.\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n unsigned Reg = RegsToSave[i];\n\n \/\/ Check to see if this physreg must be spilled to a particular stack slot\n \/\/ on this target.\n const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;\n while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&\n FixedSlot->first != Reg)\n ++FixedSlot;\n\n int FrameIdx;\n if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {\n \/\/ Nope, just spill it anywhere convenient.\n FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg),\n RegInfo->getSpillAlignment(Reg));\n } else {\n \/\/ Spill it to the stack where we must.\n FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg),\n FixedSlot->second);\n }\n StackSlots.push_back(FrameIdx);\n }\n}\n\n\/\/\/ saveCallerSavedRegisters - Insert spill code for any caller saved registers\n\/\/\/ that are modified in the function.\n\/\/\/\nvoid PEI::saveCallerSavedRegisters(MachineFunction &Fn) {\n \/\/ Early exit if no caller saved registers are modified!\n if (RegsToSave.empty())\n return; \n\n const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();\n\n \/\/ Now that we have a stack slot for each register to be saved, insert spill\n \/\/ code into the entry block...\n MachineBasicBlock *MBB = Fn.begin();\n MachineBasicBlock::iterator I = MBB->begin();\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n \/\/ Insert the spill to the stack frame.\n RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);\n }\n\n \/\/ Add code to restore the callee-save registers in each exiting block.\n const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();\n for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {\n \/\/ If last instruction is a return instruction, add an epilogue\n if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {\n MBB = FI;\n I = MBB->end(); --I;\n\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i]);\n --I; \/\/ Insert in reverse order\n }\n }\n }\n}\n\n\n\/\/\/ calculateFrameObjectOffsets - Calculate actual frame offsets for all of the\n\/\/\/ abstract stack objects...\n\/\/\/\nvoid PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {\n const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();\n \n bool StackGrowsDown =\n TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;\n \n \/\/ Loop over all of the stack objects, assigning sequential addresses...\n MachineFrameInfo *FFI = Fn.getFrameInfo();\n\n unsigned StackAlignment = TFI.getStackAlignment();\n\n \/\/ Start at the beginning of the local area.\n \/\/ The Offset is the distance from the stack top in the direction\n \/\/ of stack growth -- so it's always positive.\n int Offset = TFI.getOffsetOfLocalArea();\n if (StackGrowsDown)\n Offset = -Offset;\n assert(Offset >= 0 \n && \"Local area offset should be in direction of stack growth\");\n\n \/\/ If there are fixed sized objects that are preallocated in the local area,\n \/\/ non-fixed objects can't be allocated right at the start of local area.\n \/\/ We currently don't support filling in holes in between fixed sized objects, \n \/\/ so we adjust 'Offset' to point to the end of last fixed sized\n \/\/ preallocated object.\n for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {\n int FixedOff;\n if (StackGrowsDown) {\n \/\/ The maximum distance from the stack pointer is at lower address of\n \/\/ the object -- which is given by offset. For down growing stack\n \/\/ the offset is negative, so we negate the offset to get the distance.\n FixedOff = -FFI->getObjectOffset(i);\n } else {\n \/\/ The maximum distance from the start pointer is at the upper \n \/\/ address of the object.\n FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);\n } \n if (FixedOff > Offset) Offset = FixedOff; \n }\n\n for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {\n \/\/ If stack grows down, we need to add size of find the lowest\n \/\/ address of the object.\n if (StackGrowsDown)\n Offset += FFI->getObjectSize(i);\n\n unsigned Align = FFI->getObjectAlignment(i);\n assert(Align <= StackAlignment && \"Cannot align stack object to higher \"\n \"alignment boundary than the stack itself!\");\n Offset = (Offset+Align-1)\/Align*Align; \/\/ Adjust to Alignment boundary...\n \n if (StackGrowsDown) {\n FFI->setObjectOffset(i, -Offset); \/\/ Set the computed offset\n } else {\n FFI->setObjectOffset(i, Offset); \n Offset += FFI->getObjectSize(i);\n }\n }\n\n \/\/ Align the final stack pointer offset, but only if there are calls in the\n \/\/ function. This ensures that any calls to subroutines have their stack\n \/\/ frames suitable aligned.\n if (FFI->hasCalls())\n Offset = (Offset+StackAlignment-1)\/StackAlignment*StackAlignment;\n\n \/\/ Set the final value of the stack pointer...\n FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());\n}\n\n\n\/\/\/ insertPrologEpilogCode - Scan the function for modified caller saved\n\/\/\/ registers, insert spill code for these caller saved registers, then add\n\/\/\/ prolog and epilog code to the function.\n\/\/\/\nvoid PEI::insertPrologEpilogCode(MachineFunction &Fn) {\n \/\/ Add prologue to the function...\n Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);\n\n \/\/ Add epilogue to restore the callee-save registers in each exiting block\n const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();\n for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {\n \/\/ If last instruction is a return instruction, add an epilogue\n if (!I->empty() && TII.isReturn(I->back().getOpcode()))\n Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);\n }\n}\n\n\n\/\/\/ replaceFrameIndices - Replace all MO_FrameIndex operands with physical\n\/\/\/ register references and actual offsets.\n\/\/\/\nvoid PEI::replaceFrameIndices(MachineFunction &Fn) {\n if (!Fn.getFrameInfo()->hasStackObjects()) return; \/\/ Nothing to do?\n\n const TargetMachine &TM = Fn.getTarget();\n assert(TM.getRegisterInfo() && \"TM::getRegisterInfo() must be implemented!\");\n const MRegisterInfo &MRI = *TM.getRegisterInfo();\n\n for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)\n for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)\n if (I->getOperand(i).isFrameIndex()) {\n \/\/ If this instruction has a FrameIndex operand, we need to use that\n \/\/ target machine register info object to eliminate it.\n MRI.eliminateFrameIndex(I);\n break;\n }\n}\n<commit_msg>Register info alignment is in bits, frame object alignment is (currently) in bytes.<commit_after>\/\/===-- PrologEpilogInserter.cpp - Insert Prolog\/Epilog code in function --===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass is responsible for finalizing the functions frame layout, saving\n\/\/ callee saved registers, and for emitting prolog & epilog code for the\n\/\/ function.\n\/\/\n\/\/ This pass must be run after register allocation. After this pass is\n\/\/ executed, it is illegal to construct MO_FrameIndex operands.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MRegisterInfo.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\nnamespace {\n struct PEI : public MachineFunctionPass {\n const char *getPassName() const {\n return \"Prolog\/Epilog Insertion & Frame Finalization\";\n }\n\n \/\/\/ runOnMachineFunction - Insert prolog\/epilog code and replace abstract\n \/\/\/ frame indexes with appropriate references.\n \/\/\/\n bool runOnMachineFunction(MachineFunction &Fn) {\n \/\/ Scan the function for modified caller saved registers and insert spill\n \/\/ code for any caller saved registers that are modified. Also calculate\n \/\/ the MaxCallFrameSize and HasCalls variables for the function's frame\n \/\/ information and eliminates call frame pseudo instructions.\n calculateCallerSavedRegisters(Fn);\n\n \/\/ Add the code to save and restore the caller saved registers\n saveCallerSavedRegisters(Fn);\n\n \/\/ Allow the target machine to make final modifications to the function\n \/\/ before the frame layout is finalized.\n Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);\n\n \/\/ Calculate actual frame offsets for all of the abstract stack objects...\n calculateFrameObjectOffsets(Fn);\n\n \/\/ Add prolog and epilog code to the function. This function is required\n \/\/ to align the stack frame as necessary for any stack variables or\n \/\/ called functions. Because of this, calculateCallerSavedRegisters\n \/\/ must be called before this function in order to set the HasCalls\n \/\/ and MaxCallFrameSize variables.\n insertPrologEpilogCode(Fn);\n\n \/\/ Replace all MO_FrameIndex operands with physical register references\n \/\/ and actual offsets.\n \/\/\n replaceFrameIndices(Fn);\n\n RegsToSave.clear();\n StackSlots.clear();\n return true;\n }\n\n private:\n std::vector<unsigned> RegsToSave;\n std::vector<int> StackSlots;\n\n void calculateCallerSavedRegisters(MachineFunction &Fn);\n void saveCallerSavedRegisters(MachineFunction &Fn);\n void calculateFrameObjectOffsets(MachineFunction &Fn);\n void replaceFrameIndices(MachineFunction &Fn);\n void insertPrologEpilogCode(MachineFunction &Fn);\n };\n}\n\n\n\/\/\/ createPrologEpilogCodeInserter - This function returns a pass that inserts\n\/\/\/ prolog and epilog code, and eliminates abstract frame references.\n\/\/\/\nFunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }\n\n\n\/\/\/ calculateCallerSavedRegisters - Scan the function for modified caller saved\n\/\/\/ registers. Also calculate the MaxCallFrameSize and HasCalls variables for\n\/\/\/ the function's frame information and eliminates call frame pseudo\n\/\/\/ instructions.\n\/\/\/\nvoid PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {\n const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();\n const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();\n\n \/\/ Get the callee saved register list...\n const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();\n\n \/\/ Get the function call frame set-up and tear-down instruction opcode\n int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();\n int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();\n\n \/\/ Early exit for targets which have no callee saved registers and no call\n \/\/ frame setup\/destroy pseudo instructions.\n if ((CSRegs == 0 || CSRegs[0] == 0) &&\n FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)\n return;\n\n \/\/ This bitset contains an entry for each physical register for the target...\n std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());\n unsigned MaxCallFrameSize = 0;\n bool HasCalls = false;\n\n for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)\n for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )\n if (I->getOpcode() == FrameSetupOpcode ||\n I->getOpcode() == FrameDestroyOpcode) {\n assert(I->getNumOperands() == 1 && \"Call Frame Setup\/Destroy Pseudo\"\n \" instructions should have a single immediate argument!\");\n unsigned Size = I->getOperand(0).getImmedValue();\n if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;\n HasCalls = true;\n RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);\n } else {\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {\n MachineOperand &MO = I->getOperand(i);\n if (MO.isRegister() && MO.isDef()) {\n assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&\n \"Register allocation must be performed!\");\n ModifiedRegs[MO.getReg()] = true; \/\/ Register is modified\n }\n }\n ++I;\n }\n\n MachineFrameInfo *FFI = Fn.getFrameInfo();\n FFI->setHasCalls(HasCalls);\n FFI->setMaxCallFrameSize(MaxCallFrameSize);\n\n \/\/ Now figure out which *callee saved* registers are modified by the current\n \/\/ function, thus needing to be saved and restored in the prolog\/epilog.\n \/\/\n for (unsigned i = 0; CSRegs[i]; ++i) {\n unsigned Reg = CSRegs[i];\n if (ModifiedRegs[Reg]) {\n RegsToSave.push_back(Reg); \/\/ If modified register...\n } else {\n for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);\n *AliasSet; ++AliasSet) { \/\/ Check alias registers too...\n if (ModifiedRegs[*AliasSet]) {\n RegsToSave.push_back(Reg);\n break;\n }\n }\n }\n }\n\n if (RegsToSave.empty())\n return; \/\/ Early exit if no caller saved registers are modified!\n\n unsigned NumFixedSpillSlots;\n const std::pair<unsigned,int> *FixedSpillSlots =\n TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);\n\n \/\/ Now that we know which registers need to be saved and restored, allocate\n \/\/ stack slots for them.\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n unsigned Reg = RegsToSave[i];\n\n \/\/ Check to see if this physreg must be spilled to a particular stack slot\n \/\/ on this target.\n const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;\n while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&\n FixedSlot->first != Reg)\n ++FixedSlot;\n\n int FrameIdx;\n if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {\n \/\/ Nope, just spill it anywhere convenient.\n FrameIdx = FFI->CreateStackObject(RegInfo->getSpillSize(Reg),\n RegInfo->getSpillAlignment(Reg)\/8);\n } else {\n \/\/ Spill it to the stack where we must.\n FrameIdx = FFI->CreateFixedObject(RegInfo->getSpillSize(Reg),\n FixedSlot->second);\n }\n StackSlots.push_back(FrameIdx);\n }\n}\n\n\/\/\/ saveCallerSavedRegisters - Insert spill code for any caller saved registers\n\/\/\/ that are modified in the function.\n\/\/\/\nvoid PEI::saveCallerSavedRegisters(MachineFunction &Fn) {\n \/\/ Early exit if no caller saved registers are modified!\n if (RegsToSave.empty())\n return; \n\n const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();\n\n \/\/ Now that we have a stack slot for each register to be saved, insert spill\n \/\/ code into the entry block...\n MachineBasicBlock *MBB = Fn.begin();\n MachineBasicBlock::iterator I = MBB->begin();\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n \/\/ Insert the spill to the stack frame.\n RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);\n }\n\n \/\/ Add code to restore the callee-save registers in each exiting block.\n const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();\n for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {\n \/\/ If last instruction is a return instruction, add an epilogue\n if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {\n MBB = FI;\n I = MBB->end(); --I;\n\n for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {\n RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i]);\n --I; \/\/ Insert in reverse order\n }\n }\n }\n}\n\n\n\/\/\/ calculateFrameObjectOffsets - Calculate actual frame offsets for all of the\n\/\/\/ abstract stack objects...\n\/\/\/\nvoid PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {\n const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();\n \n bool StackGrowsDown =\n TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;\n \n \/\/ Loop over all of the stack objects, assigning sequential addresses...\n MachineFrameInfo *FFI = Fn.getFrameInfo();\n\n unsigned StackAlignment = TFI.getStackAlignment();\n\n \/\/ Start at the beginning of the local area.\n \/\/ The Offset is the distance from the stack top in the direction\n \/\/ of stack growth -- so it's always positive.\n int Offset = TFI.getOffsetOfLocalArea();\n if (StackGrowsDown)\n Offset = -Offset;\n assert(Offset >= 0 \n && \"Local area offset should be in direction of stack growth\");\n\n \/\/ If there are fixed sized objects that are preallocated in the local area,\n \/\/ non-fixed objects can't be allocated right at the start of local area.\n \/\/ We currently don't support filling in holes in between fixed sized objects, \n \/\/ so we adjust 'Offset' to point to the end of last fixed sized\n \/\/ preallocated object.\n for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {\n int FixedOff;\n if (StackGrowsDown) {\n \/\/ The maximum distance from the stack pointer is at lower address of\n \/\/ the object -- which is given by offset. For down growing stack\n \/\/ the offset is negative, so we negate the offset to get the distance.\n FixedOff = -FFI->getObjectOffset(i);\n } else {\n \/\/ The maximum distance from the start pointer is at the upper \n \/\/ address of the object.\n FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);\n } \n if (FixedOff > Offset) Offset = FixedOff; \n }\n\n for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {\n \/\/ If stack grows down, we need to add size of find the lowest\n \/\/ address of the object.\n if (StackGrowsDown)\n Offset += FFI->getObjectSize(i);\n\n unsigned Align = FFI->getObjectAlignment(i);\n assert(Align <= StackAlignment && \"Cannot align stack object to higher \"\n \"alignment boundary than the stack itself!\");\n Offset = (Offset+Align-1)\/Align*Align; \/\/ Adjust to Alignment boundary...\n \n if (StackGrowsDown) {\n FFI->setObjectOffset(i, -Offset); \/\/ Set the computed offset\n } else {\n FFI->setObjectOffset(i, Offset); \n Offset += FFI->getObjectSize(i);\n }\n }\n\n \/\/ Align the final stack pointer offset, but only if there are calls in the\n \/\/ function. This ensures that any calls to subroutines have their stack\n \/\/ frames suitable aligned.\n if (FFI->hasCalls())\n Offset = (Offset+StackAlignment-1)\/StackAlignment*StackAlignment;\n\n \/\/ Set the final value of the stack pointer...\n FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());\n}\n\n\n\/\/\/ insertPrologEpilogCode - Scan the function for modified caller saved\n\/\/\/ registers, insert spill code for these caller saved registers, then add\n\/\/\/ prolog and epilog code to the function.\n\/\/\/\nvoid PEI::insertPrologEpilogCode(MachineFunction &Fn) {\n \/\/ Add prologue to the function...\n Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);\n\n \/\/ Add epilogue to restore the callee-save registers in each exiting block\n const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();\n for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {\n \/\/ If last instruction is a return instruction, add an epilogue\n if (!I->empty() && TII.isReturn(I->back().getOpcode()))\n Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);\n }\n}\n\n\n\/\/\/ replaceFrameIndices - Replace all MO_FrameIndex operands with physical\n\/\/\/ register references and actual offsets.\n\/\/\/\nvoid PEI::replaceFrameIndices(MachineFunction &Fn) {\n if (!Fn.getFrameInfo()->hasStackObjects()) return; \/\/ Nothing to do?\n\n const TargetMachine &TM = Fn.getTarget();\n assert(TM.getRegisterInfo() && \"TM::getRegisterInfo() must be implemented!\");\n const MRegisterInfo &MRI = *TM.getRegisterInfo();\n\n for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)\n for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)\n if (I->getOperand(i).isFrameIndex()) {\n \/\/ If this instruction has a FrameIndex operand, we need to use that\n \/\/ target machine register info object to eliminate it.\n MRI.eliminateFrameIndex(I);\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_\n#define RADIUMENGINE_COLOR_PRESET_HPP_\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n\nnamespace Ra{\n namespace Core{\n\n \/\/\/ Colors are defined as vector4, i.e. 4 floats in RGBA order.\n \/\/\/ displayable colors should have all their coordinates between 0 and 1.\n namespace Colors\n {\n \/\/ Primary and secondary colors.\n \/\/ TODO (Val) : check if we can make these constexpr\n inline Color Alpha() { return Color( 0.0, 0.0, 0.0, 0.0 ); }\n inline Color Black() { return Color(0,0,0,1); }\n\n inline Color Red() { return Color(1,0,0,1); }\n inline Color Green() { return Color(0,1,0,1); }\n inline Color Blue() { return Color(0,0,1,1); }\n\n inline Color Yellow() { return Color(1,1,0,1); }\n inline Color Magenta() { return Color(1,0,1,1); }\n inline Color Cyan() { return Color(0,1,1,1); }\n\n inline Color White() { return Color(1,1,1,1); }\n\n inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}\n\n \/\/ Convert to\/from various int formats\n inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)\n {\n return Color(Scalar(r)\/255.0f, Scalar(g)\/255.0f, Scalar(b)\/255.0f, Scalar(a)\/255.0f );\n }\n\n inline Color FromRGBA32(uint32_t rgba)\n {\n uchar r = uchar((rgba >> 24) & 0xff);\n uchar g = uchar((rgba >> 16) & 0xff);\n uchar b = uchar((rgba >> 8) & 0xff);\n uchar a = uchar((rgba >> 0) & 0xff);\n return FromChars(r,g,b,a);\n }\n\n inline uint32_t ToRGBA32(const Color& color)\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<8) |(uint32_t(scaled[3])<<0);\n }\n }\n }\n}\n\n\n#endif \/\/RADIUMENGINE_COLOR_PRESET_HPP_\n<commit_msg>added toARGB32 function to colors<commit_after>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_\n#define RADIUMENGINE_COLOR_PRESET_HPP_\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n\nnamespace Ra{\n namespace Core{\n\n \/\/\/ Colors are defined as vector4, i.e. 4 floats in RGBA order.\n \/\/\/ displayable colors should have all their coordinates between 0 and 1.\n namespace Colors\n {\n \/\/ Primary and secondary colors.\n \/\/ TODO (Val) : check if we can make these constexpr\n inline Color Alpha() { return Color( 0.0, 0.0, 0.0, 0.0 ); }\n inline Color Black() { return Color(0,0,0,1); }\n\n inline Color Red() { return Color(1,0,0,1); }\n inline Color Green() { return Color(0,1,0,1); }\n inline Color Blue() { return Color(0,0,1,1); }\n\n inline Color Yellow() { return Color(1,1,0,1); }\n inline Color Magenta() { return Color(1,0,1,1); }\n inline Color Cyan() { return Color(0,1,1,1); }\n\n inline Color White() { return Color(1,1,1,1); }\n\n inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}\n\n \/\/ Convert to\/from various int formats\n inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)\n {\n return Color(Scalar(r)\/255.0f, Scalar(g)\/255.0f, Scalar(b)\/255.0f, Scalar(a)\/255.0f );\n }\n\n inline Color FromRGBA32(uint32_t rgba)\n {\n uchar r = uchar((rgba >> 24) & 0xff);\n uchar g = uchar((rgba >> 16) & 0xff);\n uchar b = uchar((rgba >> 8) & 0xff);\n uchar a = uchar((rgba >> 0) & 0xff);\n return FromChars(r,g,b,a);\n }\n\n inline uint32_t ToRGBA32(const Color& color)\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<8) |(uint32_t(scaled[3])<<0);\n }\n\n inline uint32_t ToARGB32( const Color& color )\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[3])<<24) | (uint32_t(scaled[0])<<16) |(uint32_t(scaled[1])<<8) |(uint32_t(scaled[2])<<0);\n\n }\n\n }\n }\n}\n\n\n#endif \/\/RADIUMENGINE_COLOR_PRESET_HPP_\n<|endoftext|>"} {"text":"<commit_before>\n#include \"ATEasySMS.h\"\n\nuint8_t ATEasySMS::initializeSMS()\n{\n \/\/\/\/\n \/\/ set text mode\n strncpy_P(m_cmdBuffer, ATDEV_CMD_CMGF, ATDEV_BUFF_CMD_SIZE);\n\n if (this->sendATCmd() != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/\/\/\n \/\/ Set message storage\n strncpy_P(m_cmdBuffer, ATDEV_CMD_CPMS, ATDEV_BUFF_CMD_SIZE);\n\n if (this->sendATCmd() != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ Ende\n return this->waitDevice(ATDEV_OK);\n}\n\nuint8_t ATEasySMS::sendSMS()\n{\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGS, m_smsData.m_number);\n\n \/\/ Prepare answer\n m_endBuffer[0] = ATDEV_CH_AN; \n m_endBuffer[1] = 0x00; \n\n \/\/ Send command\n if (this->sendATCmd(true) == ATDEV_OK) {\n\n \/\/ Send SMS Data\n m_hwSerial->print(m_smsData.m_message);\n\n \/\/ generate SMS end\n m_cmdBuffer[0] = ATDEV_CH_END;\n\n \/\/ End of SMS\n m_timeOut = ATDEV_SMS_TIMEOUT_SEND;\n return this->sendATCmd();\n }\n\n return ATDEV_ERR_UNEXPECTED_RESULT;\n}\n\nuint8_t ATEasySMS::receiveSMS(uint16_t idx)\n{\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGR, idx);\n\n \/\/ Prepare answer end\n memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);\n strncpy_P(m_endBuffer, ATDEV_STR_CMGR, ATDEV_BUFF_END_SIZE);\n\n \/\/ Cleanup SMS buffers\n m_smsData.cleanUp();\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_READ;\n\n \/\/ Send command\n if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {\n\n \/\/ header to smal \/ receive a error\n if (this->isCMSError() || this->parseInternalData() == 0) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_READ;\n \n \/\/ read sms text\n if (this->sendATCmd(false, m_smsData.m_message, ATDEV_SMS_TXT_SIZE) != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ copy number to buffer\n strncpy(m_smsData.m_number, this->getParseElement(2), ATDEV_SMS_NUM_SIZE);\n\n \/\/ set stop\n m_smsData.m_message[m_readPtr-5] = 0x00;\n\n return ATDEV_OK;\n }\n\n return ATDEV_ERR_UNEXPECTED_RESULT;\n}\n\nvoid ATEasySMS::setCMGLEndBuffer()\n{\n \/\/ Prepare answer end\n memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);\n strncpy_P(m_endBuffer, ATDEV_STR_CMGL, ATDEV_BUFF_END_SIZE);\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_LIST;\n}\n\nuint16_t ATEasySMS::readNextIdxSMS(uint16_t lastIdx)\n{\n uint16_t nextIdx = ATDEV_SMS_NO_MSG;\n\n \/\/ AT cmd\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGL, ATDEV_OPT_CMGL_ALL);\n\n do {\n \/\/ Set +CMGL: as end\n this->setCMGLEndBuffer();\n\n \/\/ check answer \/ +CMGL: \n if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {\n\n \/\/ is state not REC UNREAD or REC READ\n if (strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_READ) == NULL &&\n strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_UNREAD) == NULL) {\n continue;\n }\n\n \/\/ parse\n if (this->parseInternalData() >= 0) {\n nextIdx = atoi(this->getParseElement(0));\n }\n else {\n nextIdx = ATDEV_SMS_NO_MSG;\n break;\n }\n }\n \/\/ error\n else {\n nextIdx = ATDEV_SMS_NO_MSG;\n break;\n }\n\n } while ((nextIdx < lastIdx && !(nextIdx == 0 && lastIdx == 0)) || nextId == ATDEV_SMS_NO_MSG);\n\n \/\/ flush other\n this->flushInput();\n\n return nextIdx;\n}\n\nuint8_t ATEasySMS::doDeleteSMS(uint16_t idx, uint8_t flag)\n{\n char numIdx[5];\n\n \/\/ clean buffer\n memset(numIdx, 0x00, 5);\n\n \/\/ if IDX a number in store?\n if (flag == ATDEV_OPT_CMGD_DEL_IDX) {\n snprintf_P(numIdx, 4, ATDEV_INT_CHAR, idx);\n m_timeOut = ATDEV_SMS_TIMEOUT_DEL;\n }\n \/\/ Delete all\n else {\n m_timeOut = ATDEV_SMS_TIMEOUT_DELALL;\n }\n\n \/\/ prepare AT+CMGD=%d,%d\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGD, numIdx, flag);\n return this->sendATCmd();\n}\n\n\n\/\/ vim: set sts=4 sw=4 ts=4 et:\n<commit_msg>ATEasy SMS is stable and run very quickly<commit_after>\n#include \"ATEasySMS.h\"\n\nuint8_t ATEasySMS::initializeSMS()\n{\n \/\/\/\/\n \/\/ set text mode\n strncpy_P(m_cmdBuffer, ATDEV_CMD_CMGF, ATDEV_BUFF_CMD_SIZE);\n\n if (this->sendATCmd() != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/\/\/\n \/\/ Set message storage\n strncpy_P(m_cmdBuffer, ATDEV_CMD_CPMS, ATDEV_BUFF_CMD_SIZE);\n\n if (this->sendATCmd() != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ Ende\n return this->waitDevice(ATDEV_OK);\n}\n\nuint8_t ATEasySMS::sendSMS()\n{\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGS, m_smsData.m_number);\n\n \/\/ Prepare answer\n m_endBuffer[0] = ATDEV_CH_AN; \n m_endBuffer[1] = 0x00; \n\n \/\/ Send command\n if (this->sendATCmd(true) == ATDEV_OK) {\n\n \/\/ Send SMS Data\n m_hwSerial->print(m_smsData.m_message);\n\n \/\/ generate SMS end\n m_cmdBuffer[0] = ATDEV_CH_END;\n\n \/\/ End of SMS\n m_timeOut = ATDEV_SMS_TIMEOUT_SEND;\n return this->sendATCmd();\n }\n\n return ATDEV_ERR_UNEXPECTED_RESULT;\n}\n\nuint8_t ATEasySMS::receiveSMS(uint16_t idx)\n{\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGR, idx);\n\n \/\/ Prepare answer end\n memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);\n strncpy_P(m_endBuffer, ATDEV_STR_CMGR, ATDEV_BUFF_END_SIZE);\n\n \/\/ Cleanup SMS buffers\n m_smsData.cleanUp();\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_READ;\n\n \/\/ Send command\n if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {\n\n \/\/ header to smal \/ receive a error\n if (this->isCMSError() || this->parseInternalData() == 0) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_READ;\n \n \/\/ read sms text\n if (this->sendATCmd(false, m_smsData.m_message, ATDEV_SMS_TXT_SIZE) != ATDEV_OK) {\n return ATDEV_ERR_UNEXPECTED_RESULT;\n }\n\n \/\/ copy number to buffer\n strncpy(m_smsData.m_number, this->getParseElement(1), ATDEV_SMS_NUM_SIZE);\n\n \/\/ set stop\n m_smsData.m_message[m_readPtr-5] = 0x00;\n\n return ATDEV_OK;\n }\n\n return ATDEV_ERR_UNEXPECTED_RESULT;\n}\n\nvoid ATEasySMS::setCMGLEndBuffer()\n{\n \/\/ Prepare answer end\n memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);\n strncpy_P(m_endBuffer, ATDEV_STR_CMGL, ATDEV_BUFF_END_SIZE);\n\n \/\/ Timeout\n m_timeOut = ATDEV_SMS_TIMEOUT_LIST;\n}\n\nuint16_t ATEasySMS::readNextIdxSMS(uint16_t lastIdx)\n{\n uint16_t nextIdx = ATDEV_SMS_NO_MSG;\n\n \/\/ AT cmd\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGL, ATDEV_OPT_CMGL_ALL);\n\n do {\n \/\/ Set +CMGL: as end\n this->setCMGLEndBuffer();\n\n \/\/ check answer \/ +CMGL: \n if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {\n\n \/\/ is state not REC UNREAD or REC READ\n if (strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_READ) == NULL &&\n strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_UNREAD) == NULL) {\n continue;\n }\n\n \/\/ parse\n if (this->parseInternalData() >= 0) {\n nextIdx = atoi(this->getParseElement(0));\n }\n else {\n nextIdx = ATDEV_SMS_NO_MSG;\n break;\n }\n }\n \/\/ error\n else {\n nextIdx = ATDEV_SMS_NO_MSG;\n break;\n }\n\n } while ((nextIdx < lastIdx && !(nextIdx == 0 && lastIdx == 0)) || nextIdx == ATDEV_SMS_NO_MSG);\n\n \/\/ flush other\n this->flushInput();\n\n return nextIdx;\n}\n\nuint8_t ATEasySMS::doDeleteSMS(uint16_t idx, uint8_t flag)\n{\n char numIdx[5];\n\n \/\/ clean buffer\n memset(numIdx, 0x00, 5);\n\n \/\/ if IDX a number in store?\n if (flag == ATDEV_OPT_CMGD_DEL_IDX) {\n snprintf_P(numIdx, 4, ATDEV_INT_CHAR, idx);\n m_timeOut = ATDEV_SMS_TIMEOUT_DEL;\n }\n \/\/ Delete all\n else {\n m_timeOut = ATDEV_SMS_TIMEOUT_DELALL;\n }\n\n \/\/ prepare AT+CMGD=%d,%d\n snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGD, numIdx, flag);\n return this->sendATCmd();\n}\n\n\n\/\/ vim: set sts=4 sw=4 ts=4 et:\n<|endoftext|>"} {"text":"<commit_before>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_\n#define RADIUMENGINE_COLOR_PRESET_HPP_\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n\nnamespace Ra{\n namespace Core{\n\n \/\/\/ Colors are defined as vector4, i.e. 4 floats in RGBA order.\n \/\/\/ displayable colors should have all their coordinates between 0 and 1.\n namespace Colors\n {\n \/\/ Primary and secondary colors.\n \/\/ TODO (Val) : check if we can make these constexpr\n inline Color Alpha() { return Color( 0.0, 0.0, 0.0, 0.0 ); }\n inline Color Black() { return Color(0,0,0,1); }\n\n inline Color Red() { return Color(1,0,0,1); }\n inline Color Green() { return Color(0,1,0,1); }\n inline Color Blue() { return Color(0,0,1,1); }\n\n inline Color Yellow() { return Color(1,1,0,1); }\n inline Color Magenta() { return Color(1,0,1,1); }\n inline Color Cyan() { return Color(0,1,1,1); }\n\n inline Color White() { return Color(1,1,1,1); }\n\n inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}\n\n \/\/ Convert to\/from various int formats\n inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)\n {\n return Color(Scalar(r)\/255.0f, Scalar(g)\/255.0f, Scalar(b)\/255.0f, Scalar(a)\/255.0f );\n }\n\n inline Color FromRGBA32(uint32_t rgba)\n {\n uchar r = uchar((rgba >> 24) & 0xff);\n uchar g = uchar((rgba >> 16) & 0xff);\n uchar b = uchar((rgba >> 8) & 0xff);\n uchar a = uchar((rgba >> 0) & 0xff);\n return FromChars(r,g,b,a);\n }\n\n inline uint32_t ToRGBA32(const Color& color)\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<8) |(uint32_t(scaled[3])<<0);\n }\n\n inline uint32_t ToARGB32( const Color& color )\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[3])<<24) | (uint32_t(scaled[0])<<16) |(uint32_t(scaled[1])<<8) |(uint32_t(scaled[2])<<0);\n\n }\n\n }\n }\n}\n\n\n#endif \/\/RADIUMENGINE_COLOR_PRESET_HPP_\n<commit_msg>Added a fromHSV color function. Needs to be tested<commit_after>#ifndef RADIUMENGINE_COLOR_PRESET_HPP_\n#define RADIUMENGINE_COLOR_PRESET_HPP_\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n\nnamespace Ra{\n namespace Core{\n\n \/\/\/ Colors are defined as vector4, i.e. 4 floats in RGBA order.\n \/\/\/ displayable colors should have all their coordinates between 0 and 1.\n namespace Colors\n {\n \/\/ Primary and secondary colors.\n \/\/ TODO (Val) : check if we can make these constexpr\n inline Color Alpha() { return Color( 0.0, 0.0, 0.0, 0.0 ); }\n inline Color Black() { return Color(0,0,0,1); }\n\n inline Color Red() { return Color(1,0,0,1); }\n inline Color Green() { return Color(0,1,0,1); }\n inline Color Blue() { return Color(0,0,1,1); }\n\n inline Color Yellow() { return Color(1,1,0,1); }\n inline Color Magenta() { return Color(1,0,1,1); }\n inline Color Cyan() { return Color(0,1,1,1); }\n\n inline Color White() { return Color(1,1,1,1); }\n\n inline Color Grey( Scalar f = 0.5f) { return Color(f,f,f,1);}\n\n \/\/ Convert to\/from various int formats\n inline Color FromChars(uchar r, uchar g, uchar b, uchar a = 0xff)\n {\n return Color(Scalar(r)\/255.0f, Scalar(g)\/255.0f, Scalar(b)\/255.0f, Scalar(a)\/255.0f );\n }\n\n inline Color FromRGBA32(uint32_t rgba)\n {\n uchar r = uchar((rgba >> 24) & 0xff);\n uchar g = uchar((rgba >> 16) & 0xff);\n uchar b = uchar((rgba >> 8) & 0xff);\n uchar a = uchar((rgba >> 0) & 0xff);\n return FromChars(r,g,b,a);\n }\n\n inline Color fromHSV( const Scalar hue,\n const Scalar saturation = 1.0,\n const Scalar value = 1.0,\n const Scalar alpha = 1.0 ) {\n Color c;\n if( saturation == 0.0f ) {\n c[0] = c[1] = c[2] = value;\n c[3] = alpha;\n return c;\n }\n Scalar h = ( ( hue == 1.0f ) ? 0.0f : hue ) * 6.0f;\n int i = std::floor( h );\n Scalar v1 = value * ( 1.0f - saturation );\n Scalar v2 = value * ( 1.0f - ( saturation * ( h - i ) ) );\n Scalar v3 = value * ( 1.0f - ( saturation * ( 1.0f - h - i ) ) );\n switch( i ) {\n case 0: {\n c[0] = value; c[1] = v3; c[2] = v1;\n } break;\n case 1: {\n c[0] = v2; c[1] = value; c[2] = v1;\n } break;\n case 2: {\n c[0] = v1; c[1] = value; c[2] = v3;\n } break;\n case 3: {\n c[0] = v1; c[1] = v2; c[2] = value;\n } break;\n case 4: {\n c[0] = v3; c[1] = v1; c[2] = value;\n } break;\n default: {\n c[0] = value; c[1] = v1; c[2] = v2;\n } break;\n }\n c[3] = alpha;\n return c;\n }\n\n inline uint32_t ToRGBA32(const Color& color)\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[0])<<24) | (uint32_t(scaled[1])<<16) |(uint32_t(scaled[2])<<8) |(uint32_t(scaled[3])<<0);\n }\n\n inline uint32_t ToARGB32( const Color& color )\n {\n Vector4i scaled = (color * 255).cast<int>();\n return (uint32_t(scaled[3])<<24) | (uint32_t(scaled[0])<<16) |(uint32_t(scaled[1])<<8) |(uint32_t(scaled[2])<<0);\n\n }\n\n }\n }\n}\n\n\n#endif \/\/RADIUMENGINE_COLOR_PRESET_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"PathUtils.h\"\r\n\r\nusing namespace Framework;\r\n\r\n#ifdef _WIN32\r\n\r\n#if WINAPI_FAMILY_PARTITION(WINAPI_FAMILY_APP)\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\tauto localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;\r\n\treturn boost::filesystem::path(localFolder->Path->Data());\r\n}\r\n\r\n#else\t\/\/ !WINAPI_PARTITION_APP\r\n\r\n#include <shlobj.h>\r\n\r\nboost::filesystem::path PathUtils::GetPathFromCsidl(int csidl)\r\n{\r\n\twchar_t userPathString[MAX_PATH];\r\n\tif(FAILED(SHGetFolderPathW(NULL, csidl, NULL, 0, userPathString)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't get path from csidl.\");\r\n\t}\r\n\treturn boost::filesystem::wpath(userPathString, boost::filesystem::native);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\treturn GetPathFromCsidl(CSIDL_APPDATA);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn GetPathFromCsidl(CSIDL_PERSONAL);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\treturn boost::filesystem::path(\".\");\r\n}\r\n\r\n#endif\t\/\/ !WINAPI_PARTITION_APP\r\n\r\n#endif\t\/\/ _WIN32\r\n\r\n#if defined(_POSIX_VERSION)\r\n\r\n#if defined(__APPLE__)\r\n\r\n#include <CoreFoundation\/CoreFoundation.h>\r\n#include <Foundation\/Foundation.h>\r\n\r\nboost::filesystem::path PathUtils::GetSettingsPath()\r\n{\r\n\tNSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);\r\n\tstd::string directory = [[paths objectAtIndex: 0] UTF8String];\r\n\treturn boost::filesystem::path(directory);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\tNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\r\n\tstd::string directory = [[paths objectAtIndex: 0] UTF8String];\r\n\treturn boost::filesystem::path(directory);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\tNSBundle* bundle = [NSBundle mainBundle];\r\n\tNSString* bundlePath = [bundle resourcePath];\r\n\treturn boost::filesystem::path([bundlePath UTF8String]);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn GetRoamingDataPath();\r\n}\r\n\r\n#elif defined(__ANDROID__)\r\n\r\nstatic boost::filesystem::path s_filesDirPath;\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\t\/\/This won't work for Android\r\n\treturn boost::filesystem::path();\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\treturn s_filesDirPath;\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn s_filesDirPath;\r\n}\r\n\r\nvoid PathUtils::SetFilesDirPath(const char* filesDirPath)\r\n{\r\n\ts_filesDirPath = filesDirPath;\r\n}\r\n\r\n#else\t\/\/ !DEFINED(__ANDROID__) || !DEFINED(__APPLE__)\r\n\r\n#include <pwd.h>\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\tpasswd* userInfo = getpwuid(getuid());\r\n\treturn boost::filesystem::path(userInfo->pw_dir);\r\n}\r\n\r\n#endif\t\/\/ !DEFINED(__APPLE__)\r\n\r\n#endif\t\/\/ !DEFINED(_POSIX_VERSION)\r\n\r\nvoid PathUtils::EnsurePathExists(const boost::filesystem::path& path)\r\n{\r\n\ttypedef boost::filesystem::path PathType;\r\n\tPathType buildPath;\r\n\tfor(PathType::iterator pathIterator(path.begin());\r\n\t\tpathIterator != path.end(); pathIterator++)\r\n\t{\r\n\t\tbuildPath \/= (*pathIterator);\r\n\t\tboost::system::error_code existsErrorCode;\r\n\t\tbool exists = boost::filesystem::exists(buildPath, existsErrorCode);\r\n\t\tif(existsErrorCode)\r\n\t\t{\r\n#ifdef WIN32\r\n\t\t\tif(existsErrorCode.value() == ERROR_ACCESS_DENIED)\r\n\t\t\t{\r\n\t\t\t\t\/\/No problem, it exists, but we just don't have access\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\telse if(existsErrorCode.value() == ERROR_FILE_NOT_FOUND)\r\n\t\t\t{\r\n\t\t\t\texists = false;\r\n\t\t\t}\r\n#else\r\n\t\t\tif(existsErrorCode.value() == ENOENT)\r\n\t\t\t{\r\n\t\t\t\texists = false;\r\n\t\t\t}\r\n#endif\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthrow std::runtime_error(\"Couldn't ensure that path exists.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!exists)\r\n\t\t{\r\n\t\t\tboost::filesystem::create_directory(buildPath);\r\n\t\t}\r\n\t}\r\n}\r\n<commit_msg>Force CSIDL path to be created when getting a special path.<commit_after>#include \"PathUtils.h\"\r\n\r\nusing namespace Framework;\r\n\r\n#ifdef _WIN32\r\n\r\n#if WINAPI_FAMILY_PARTITION(WINAPI_FAMILY_APP)\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\tauto localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;\r\n\treturn boost::filesystem::path(localFolder->Path->Data());\r\n}\r\n\r\n#else\t\/\/ !WINAPI_PARTITION_APP\r\n\r\n#include <shlobj.h>\r\n\r\nboost::filesystem::path PathUtils::GetPathFromCsidl(int csidl)\r\n{\r\n\twchar_t userPathString[MAX_PATH];\r\n\tif(FAILED(SHGetFolderPathW(NULL, csidl | CSIDL_FLAG_CREATE, NULL, 0, userPathString)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't get path from csidl.\");\r\n\t}\r\n\treturn boost::filesystem::wpath(userPathString, boost::filesystem::native);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\treturn GetPathFromCsidl(CSIDL_APPDATA);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn GetPathFromCsidl(CSIDL_PERSONAL);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\treturn boost::filesystem::path(\".\");\r\n}\r\n\r\n#endif\t\/\/ !WINAPI_PARTITION_APP\r\n\r\n#endif\t\/\/ _WIN32\r\n\r\n#if defined(_POSIX_VERSION)\r\n\r\n#if defined(__APPLE__)\r\n\r\n#include <CoreFoundation\/CoreFoundation.h>\r\n#include <Foundation\/Foundation.h>\r\n\r\nboost::filesystem::path PathUtils::GetSettingsPath()\r\n{\r\n\tNSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);\r\n\tstd::string directory = [[paths objectAtIndex: 0] UTF8String];\r\n\treturn boost::filesystem::path(directory);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\tNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\r\n\tstd::string directory = [[paths objectAtIndex: 0] UTF8String];\r\n\treturn boost::filesystem::path(directory);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\tNSBundle* bundle = [NSBundle mainBundle];\r\n\tNSString* bundlePath = [bundle resourcePath];\r\n\treturn boost::filesystem::path([bundlePath UTF8String]);\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn GetRoamingDataPath();\r\n}\r\n\r\n#elif defined(__ANDROID__)\r\n\r\nstatic boost::filesystem::path s_filesDirPath;\r\n\r\nboost::filesystem::path PathUtils::GetAppResourcesPath()\r\n{\r\n\t\/\/This won't work for Android\r\n\treturn boost::filesystem::path();\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetRoamingDataPath()\r\n{\r\n\treturn s_filesDirPath;\r\n}\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\treturn s_filesDirPath;\r\n}\r\n\r\nvoid PathUtils::SetFilesDirPath(const char* filesDirPath)\r\n{\r\n\ts_filesDirPath = filesDirPath;\r\n}\r\n\r\n#else\t\/\/ !DEFINED(__ANDROID__) || !DEFINED(__APPLE__)\r\n\r\n#include <pwd.h>\r\n\r\nboost::filesystem::path PathUtils::GetPersonalDataPath()\r\n{\r\n\tpasswd* userInfo = getpwuid(getuid());\r\n\treturn boost::filesystem::path(userInfo->pw_dir);\r\n}\r\n\r\n#endif\t\/\/ !DEFINED(__APPLE__)\r\n\r\n#endif\t\/\/ !DEFINED(_POSIX_VERSION)\r\n\r\nvoid PathUtils::EnsurePathExists(const boost::filesystem::path& path)\r\n{\r\n\ttypedef boost::filesystem::path PathType;\r\n\tPathType buildPath;\r\n\tfor(PathType::iterator pathIterator(path.begin());\r\n\t\tpathIterator != path.end(); pathIterator++)\r\n\t{\r\n\t\tbuildPath \/= (*pathIterator);\r\n\t\tboost::system::error_code existsErrorCode;\r\n\t\tbool exists = boost::filesystem::exists(buildPath, existsErrorCode);\r\n\t\tif(existsErrorCode)\r\n\t\t{\r\n#ifdef WIN32\r\n\t\t\tif(existsErrorCode.value() == ERROR_ACCESS_DENIED)\r\n\t\t\t{\r\n\t\t\t\t\/\/No problem, it exists, but we just don't have access\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\telse if(existsErrorCode.value() == ERROR_FILE_NOT_FOUND)\r\n\t\t\t{\r\n\t\t\t\texists = false;\r\n\t\t\t}\r\n#else\r\n\t\t\tif(existsErrorCode.value() == ENOENT)\r\n\t\t\t{\r\n\t\t\t\texists = false;\r\n\t\t\t}\r\n#endif\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthrow std::runtime_error(\"Couldn't ensure that path exists.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!exists)\r\n\t\t{\r\n\t\t\tboost::filesystem::create_directory(buildPath);\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This diagnostic client prints out their diagnostic messages.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/TextDiagnosticPrinter.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/SmallString.h\"\nusing namespace clang;\n\nvoid TextDiagnosticPrinter::\nPrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {\n if (Loc.isInvalid()) return;\n\n PresumedLoc PLoc = SM.getPresumedLoc(Loc);\n\n \/\/ Print out the other include frames first.\n PrintIncludeStack(PLoc.getIncludeLoc(), SM);\n \n OS << \"In file included from \" << PLoc.getFilename()\n << ':' << PLoc.getLine() << \":\\n\";\n}\n\n\/\/\/ HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)\n\/\/\/ any characters in LineNo that intersect the SourceRange.\nvoid TextDiagnosticPrinter::HighlightRange(const SourceRange &R,\n const SourceManager &SM,\n unsigned LineNo, FileID FID,\n std::string &CaretLine,\n const std::string &SourceLine) {\n assert(CaretLine.size() == SourceLine.size() &&\n \"Expect a correspondence between source and caret line!\");\n if (!R.isValid()) return;\n\n SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());\n SourceLocation End = SM.getInstantiationLoc(R.getEnd());\n \n unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);\n if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)\n return; \/\/ No intersection.\n \n unsigned EndLineNo = SM.getInstantiationLineNumber(End);\n if (EndLineNo < LineNo || SM.getFileID(End) != FID)\n return; \/\/ No intersection.\n \n \/\/ Compute the column number of the start.\n unsigned StartColNo = 0;\n if (StartLineNo == LineNo) {\n StartColNo = SM.getInstantiationColumnNumber(Begin);\n if (StartColNo) --StartColNo; \/\/ Zero base the col #.\n }\n\n \/\/ Pick the first non-whitespace column.\n while (StartColNo < SourceLine.size() &&\n (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\\t'))\n ++StartColNo;\n \n \/\/ Compute the column number of the end.\n unsigned EndColNo = CaretLine.size();\n if (EndLineNo == LineNo) {\n EndColNo = SM.getInstantiationColumnNumber(End);\n if (EndColNo) {\n --EndColNo; \/\/ Zero base the col #.\n \n \/\/ Add in the length of the token, so that we cover multi-char tokens.\n EndColNo += Lexer::MeasureTokenLength(End, SM);\n } else {\n EndColNo = CaretLine.size();\n }\n }\n \n \/\/ Pick the last non-whitespace column.\n if (EndColNo <= SourceLine.size())\n while (EndColNo-1 &&\n (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\\t'))\n --EndColNo;\n else\n EndColNo = SourceLine.size();\n \n \/\/ Fill the range with ~'s.\n assert(StartColNo <= EndColNo && \"Invalid range!\");\n for (unsigned i = StartColNo; i < EndColNo; ++i)\n CaretLine[i] = '~';\n}\n\nvoid TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, \n const DiagnosticInfo &Info) {\n unsigned ColNo = 0;\n \n \/\/ If the location is specified, print out a file\/line\/col and include trace\n \/\/ if enabled.\n if (Info.getLocation().isValid()) {\n const SourceManager &SM = Info.getLocation().getManager();\n PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());\n unsigned LineNo = PLoc.getLine();\n \n \/\/ First, if this diagnostic is not in the main file, print out the\n \/\/ \"included from\" lines.\n if (LastWarningLoc != PLoc.getIncludeLoc()) {\n LastWarningLoc = PLoc.getIncludeLoc();\n PrintIncludeStack(LastWarningLoc, SM);\n }\n \n \/\/ Compute the column number.\n ColNo = PLoc.getColumn();\n if (ShowLocation) {\n OS << PLoc.getFilename() << ':' << LineNo << ':';\n if (ColNo && ShowColumn) \n OS << ColNo << ':';\n OS << ' ';\n }\n }\n \n switch (Level) {\n case Diagnostic::Ignored: assert(0 && \"Invalid diagnostic type\");\n case Diagnostic::Note: OS << \"note: \"; break;\n case Diagnostic::Warning: OS << \"warning: \"; break;\n case Diagnostic::Error: OS << \"error: \"; break;\n case Diagnostic::Fatal: OS << \"fatal error: \"; break;\n }\n \n llvm::SmallString<100> OutStr;\n Info.FormatDiagnostic(OutStr);\n OS.write(OutStr.begin(), OutStr.size());\n OS << '\\n';\n \n \/\/ If caret diagnostics are enabled and we have location, we want to emit the\n \/\/ caret. However, we only do this if the location moved from the last\n \/\/ diagnostic, or if the diagnostic has ranges. We don't want to emit the\n \/\/ same caret multiple times if one loc has multiple diagnostics.\n if (CaretDiagnostics && Info.getLocation().isValid() &&\n ((LastLoc != Info.getLocation()) || Info.getNumRanges())) {\n \/\/ Cache the LastLoc, it allows us to omit duplicate source\/caret spewage.\n LastLoc = Info.getLocation();\n\n \/\/ Inspect the actual instantiation point of the diagnostic, we don't care\n \/\/ about presumed locations anymore.\n FullSourceLoc ILoc = Info.getLocation().getInstantiationLoc();\n\n \/\/ Rewind from the current position to the start of the line.\n const char *TokInstantiationPtr = ILoc.getCharacterData();\n const char *LineStart = TokInstantiationPtr-ColNo+1; \/\/ Column # is 1-based.\n \n \/\/ Compute the line end. Scan forward from the error position to the end of\n \/\/ the line.\n const char *BufEnd = ILoc.getBufferData().second;\n const char *LineEnd = TokInstantiationPtr;\n while (LineEnd != BufEnd && \n *LineEnd != '\\n' && *LineEnd != '\\r')\n ++LineEnd;\n \n \/\/ Copy the line of code into an std::string for ease of manipulation.\n std::string SourceLine(LineStart, LineEnd);\n \n \/\/ Create a line for the caret that is filled with spaces that is the same\n \/\/ length as the line of source code.\n std::string CaretLine(LineEnd-LineStart, ' ');\n\n \/\/ Highlight all of the characters covered by Ranges with ~ characters.\n for (unsigned i = 0; i != Info.getNumRanges(); ++i)\n HighlightRange(Info.getRange(i), ILoc.getManager(),\n ILoc.getInstantiationLineNumber(),\n ILoc.getFileID(), CaretLine, SourceLine);\n \n \/\/ Next, insert the caret itself.\n if (ColNo-1 < CaretLine.size())\n CaretLine[ColNo-1] = '^';\n else\n CaretLine.push_back('^');\n \n \/\/ Scan the source line, looking for tabs. If we find any, manually expand\n \/\/ them to 8 characters and update the CaretLine to match.\n for (unsigned i = 0; i != SourceLine.size(); ++i) {\n if (SourceLine[i] != '\\t') continue;\n \n \/\/ Replace this tab with at least one space.\n SourceLine[i] = ' ';\n \n \/\/ Compute the number of spaces we need to insert.\n unsigned NumSpaces = ((i+8)&~7) - (i+1);\n assert(NumSpaces < 8 && \"Invalid computation of space amt\");\n \n \/\/ Insert spaces into the SourceLine.\n SourceLine.insert(i+1, NumSpaces, ' ');\n \n \/\/ Insert spaces or ~'s into CaretLine.\n CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');\n }\n \n \/\/ Finally, remove any blank spaces from the end of CaretLine.\n while (CaretLine[CaretLine.size()-1] == ' ')\n CaretLine.erase(CaretLine.end()-1);\n \n \/\/ Emit what we have computed.\n OS << SourceLine << '\\n';\n OS << CaretLine << '\\n';\n }\n \n OS.flush();\n}\n<commit_msg>If a source range comes through a function-like macro expansion, highlight the arguments to the macro as well as the identifier.<commit_after>\/\/===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This diagnostic client prints out their diagnostic messages.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/TextDiagnosticPrinter.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/SmallString.h\"\nusing namespace clang;\n\nvoid TextDiagnosticPrinter::\nPrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {\n if (Loc.isInvalid()) return;\n\n PresumedLoc PLoc = SM.getPresumedLoc(Loc);\n\n \/\/ Print out the other include frames first.\n PrintIncludeStack(PLoc.getIncludeLoc(), SM);\n \n OS << \"In file included from \" << PLoc.getFilename()\n << ':' << PLoc.getLine() << \":\\n\";\n}\n\n\/\/\/ HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)\n\/\/\/ any characters in LineNo that intersect the SourceRange.\nvoid TextDiagnosticPrinter::HighlightRange(const SourceRange &R,\n const SourceManager &SM,\n unsigned LineNo, FileID FID,\n std::string &CaretLine,\n const std::string &SourceLine) {\n assert(CaretLine.size() == SourceLine.size() &&\n \"Expect a correspondence between source and caret line!\");\n if (!R.isValid()) return;\n\n SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());\n SourceLocation End = SM.getInstantiationLoc(R.getEnd());\n \n \/\/ If the End location and the start location are the same and are a macro\n \/\/ location, then the range was something that came from a macro expansion\n \/\/ or _Pragma. If this is an object-like macro, the best we can do is to\n \/\/ highlight the range. If this is a function-like macro, we'd also like to\n \/\/ highlight the arguments.\n if (Begin == End && R.getEnd().isMacroID())\n End = SM.getInstantiationRange(R.getEnd()).second;\n \n unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);\n if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)\n return; \/\/ No intersection.\n \n unsigned EndLineNo = SM.getInstantiationLineNumber(End);\n if (EndLineNo < LineNo || SM.getFileID(End) != FID)\n return; \/\/ No intersection.\n \n \/\/ Compute the column number of the start.\n unsigned StartColNo = 0;\n if (StartLineNo == LineNo) {\n StartColNo = SM.getInstantiationColumnNumber(Begin);\n if (StartColNo) --StartColNo; \/\/ Zero base the col #.\n }\n\n \/\/ Pick the first non-whitespace column.\n while (StartColNo < SourceLine.size() &&\n (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\\t'))\n ++StartColNo;\n \n \/\/ Compute the column number of the end.\n unsigned EndColNo = CaretLine.size();\n if (EndLineNo == LineNo) {\n EndColNo = SM.getInstantiationColumnNumber(End);\n if (EndColNo) {\n --EndColNo; \/\/ Zero base the col #.\n \n \/\/ Add in the length of the token, so that we cover multi-char tokens.\n EndColNo += Lexer::MeasureTokenLength(End, SM);\n } else {\n EndColNo = CaretLine.size();\n }\n }\n \n \/\/ Pick the last non-whitespace column.\n if (EndColNo <= SourceLine.size())\n while (EndColNo-1 &&\n (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\\t'))\n --EndColNo;\n else\n EndColNo = SourceLine.size();\n \n \/\/ Fill the range with ~'s.\n assert(StartColNo <= EndColNo && \"Invalid range!\");\n for (unsigned i = StartColNo; i < EndColNo; ++i)\n CaretLine[i] = '~';\n}\n\nvoid TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, \n const DiagnosticInfo &Info) {\n unsigned ColNo = 0;\n \n \/\/ If the location is specified, print out a file\/line\/col and include trace\n \/\/ if enabled.\n if (Info.getLocation().isValid()) {\n const SourceManager &SM = Info.getLocation().getManager();\n PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());\n unsigned LineNo = PLoc.getLine();\n \n \/\/ First, if this diagnostic is not in the main file, print out the\n \/\/ \"included from\" lines.\n if (LastWarningLoc != PLoc.getIncludeLoc()) {\n LastWarningLoc = PLoc.getIncludeLoc();\n PrintIncludeStack(LastWarningLoc, SM);\n }\n \n \/\/ Compute the column number.\n ColNo = PLoc.getColumn();\n if (ShowLocation) {\n OS << PLoc.getFilename() << ':' << LineNo << ':';\n if (ColNo && ShowColumn) \n OS << ColNo << ':';\n OS << ' ';\n }\n }\n \n switch (Level) {\n case Diagnostic::Ignored: assert(0 && \"Invalid diagnostic type\");\n case Diagnostic::Note: OS << \"note: \"; break;\n case Diagnostic::Warning: OS << \"warning: \"; break;\n case Diagnostic::Error: OS << \"error: \"; break;\n case Diagnostic::Fatal: OS << \"fatal error: \"; break;\n }\n \n llvm::SmallString<100> OutStr;\n Info.FormatDiagnostic(OutStr);\n OS.write(OutStr.begin(), OutStr.size());\n OS << '\\n';\n \n \/\/ If caret diagnostics are enabled and we have location, we want to emit the\n \/\/ caret. However, we only do this if the location moved from the last\n \/\/ diagnostic, or if the diagnostic has ranges. We don't want to emit the\n \/\/ same caret multiple times if one loc has multiple diagnostics.\n if (CaretDiagnostics && Info.getLocation().isValid() &&\n ((LastLoc != Info.getLocation()) || Info.getNumRanges())) {\n \/\/ Cache the LastLoc, it allows us to omit duplicate source\/caret spewage.\n LastLoc = Info.getLocation();\n\n \/\/ Inspect the actual instantiation point of the diagnostic, we don't care\n \/\/ about presumed locations anymore.\n FullSourceLoc ILoc = Info.getLocation().getInstantiationLoc();\n\n \/\/ Rewind from the current position to the start of the line.\n const char *TokInstantiationPtr = ILoc.getCharacterData();\n const char *LineStart = TokInstantiationPtr-ColNo+1; \/\/ Column # is 1-based.\n \n \/\/ Compute the line end. Scan forward from the error position to the end of\n \/\/ the line.\n const char *BufEnd = ILoc.getBufferData().second;\n const char *LineEnd = TokInstantiationPtr;\n while (LineEnd != BufEnd && \n *LineEnd != '\\n' && *LineEnd != '\\r')\n ++LineEnd;\n \n \/\/ Copy the line of code into an std::string for ease of manipulation.\n std::string SourceLine(LineStart, LineEnd);\n \n \/\/ Create a line for the caret that is filled with spaces that is the same\n \/\/ length as the line of source code.\n std::string CaretLine(LineEnd-LineStart, ' ');\n\n \/\/ Highlight all of the characters covered by Ranges with ~ characters.\n for (unsigned i = 0; i != Info.getNumRanges(); ++i)\n HighlightRange(Info.getRange(i), ILoc.getManager(),\n ILoc.getInstantiationLineNumber(),\n ILoc.getFileID(), CaretLine, SourceLine);\n \n \/\/ Next, insert the caret itself.\n if (ColNo-1 < CaretLine.size())\n CaretLine[ColNo-1] = '^';\n else\n CaretLine.push_back('^');\n \n \/\/ Scan the source line, looking for tabs. If we find any, manually expand\n \/\/ them to 8 characters and update the CaretLine to match.\n for (unsigned i = 0; i != SourceLine.size(); ++i) {\n if (SourceLine[i] != '\\t') continue;\n \n \/\/ Replace this tab with at least one space.\n SourceLine[i] = ' ';\n \n \/\/ Compute the number of spaces we need to insert.\n unsigned NumSpaces = ((i+8)&~7) - (i+1);\n assert(NumSpaces < 8 && \"Invalid computation of space amt\");\n \n \/\/ Insert spaces into the SourceLine.\n SourceLine.insert(i+1, NumSpaces, ' ');\n \n \/\/ Insert spaces or ~'s into CaretLine.\n CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');\n }\n \n \/\/ Finally, remove any blank spaces from the end of CaretLine.\n while (CaretLine[CaretLine.size()-1] == ' ')\n CaretLine.erase(CaretLine.end()-1);\n \n \/\/ Emit what we have computed.\n OS << SourceLine << '\\n';\n OS << CaretLine << '\\n';\n }\n \n OS.flush();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <algorithm>\nusing namespace std;\n\n#include \"Processes.h\"\n#include \"Base.h\"\n#include \"Command.h\"\n#include \"Andand.h\"\n#include \"Oror.h\"\n#include \"Test.h\"\n\n\/\/Simple constructor\nProcesses::Processes()\n{\n currCmds.resize(0);\n}\n\/\/Simple destructor\nProcesses::~Processes()\n{\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n delete currCmds.at(i);\n }\n}\n\/\/This executes all objects within the object's currCmds vector\nint Processes::execute()\n{\n int temp = 0;\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n temp = currCmds.at(i)->execute();\n }\n return temp;\n}\n\/\/Processes parses the code to split it into separate command lines\n\/\/should there be any semicolons present.\nvoid Processes::parse(string input)\n{\n vector<string> currCs;\n istringstream inSS(input);\n string currString;\n \/\/Main loop for parsing input that contains semicolons\n if(count(input.begin(), input.end(), ';') >= 1)\n {\n while(input.find(\";\") != string::npos)\n {\n if(count(input.begin(), input.end(), ';') == 1 \n && input.find(\";\") != input.size() - 1 \n && (input.at(input.find(\";\") + 1)) == '\"')\n {\n break;\n }\n if(count(input.begin(), input.end(), ';') == 1 && input.find(\";\") == input.size() - 1)\n {\n break;\n }\n bool hashtag = false;\n bool semicolon = false;\n bool first = false;\n currCs.resize(0);\n while(!semicolon)\n {\n inSS >> currString;\n input.erase(0, currString.size() + 1);\n \/\/Tests for hashtag\/semicolon presence\n if(currString.find(\"#\") != string::npos)\n {\n hashtag = true;\n if(currString.find(\"#\") != 0 && (!first))\n {\n currCs.push_back(currString);\n first = true;\n }\n }\n if(currString.find(\";\") != string::npos)\n {\n semicolon = true;\n }\n string temp = \"\";\n for(unsigned g = 0; g < currString.size(); ++g)\n {\n if(currString.at(g) == '\"')\n {\n if(g > 0 && currString.at(g - 1) == '\\\\')\n {\n temp += currString.at(g);\n }\n }\n else if(currString.at(g) != '\\\\')\n {\n temp += currString.at(g);\n }\n }\n currString = temp;\n if(!hashtag)\n {\n if(!semicolon)\n {\n currCs.push_back(currString);\n }\n else\n {\n currString.erase(currString.size() - 1, 1);\n currCs.push_back(currString);\n }\n }\n }\n \/\/Here, we detect the presence of connectors.\n bool detected = false;\n for(unsigned j = 0; j < currCs.size(); ++j)\n {\n if(currCs.at(j) == \"||\" || currCs.at(j) == \"&&\")\n {\n detected = true;\n break;\n }\n }\n \/\/If it detects one, it sends the vector to a loop\n \/\/that runs until the end of the current command string.\n \/\/It stops at the next connector, looks at the previous connector,\n \/\/and creates objects and links them correspondingly.\n if(detected)\n {\n string prevConnector;\n string nextConnector;\n vector<string> firstCommand;\n unsigned i = 0;\n while(currCs.at(i) != \"&&\" && currCs.at(i) != \"||\")\n {\n firstCommand.push_back(currCs.at(i));\n ++i;\n }\n prevConnector = currCs.at(i);\n Base * temp3;\n if(firstCommand.at(0) == \"test\")\n {\n temp3 = new Test(firstCommand);\n }\n else\n {\n temp3 = new Command(firstCommand);\n }\n currCmds.push_back(temp3);\n ++i;\n vector<string> currCommand;\n for(;i < currCs.size(); ++i)\n {\n currCommand.push_back(currCs.at(i));\n if(currCs.at(i) == \"&&\" || currCs.at(i) == \"||\")\n {\n currCommand.pop_back();\n if(currCommand.at(0) == \"test\")\n {\n Base *temp = new Test(currCommand);\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n }\n else {\n Base *temp = new Command(currCommand);\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n } \n }\n }\n }\n \/\/This runs if there no connectors left after semicolon detecting.\n else {\n vector<string> currCommand;\n for(unsigned k = 0; k < currCs.size(); ++k)\n {\n currCommand.push_back(currCs.at(k));\n }\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n currCmds.push_back(temp);\n }\n }\n }\n \/\/Second loop that parses the remaining part of the input\n \/\/Also, if the input never contained any semicolons,\n \/\/the parse will go straight to this part of the code.\n currCs.resize(0);\n while(inSS >> currString)\n {\n if(currString.at(currString.size() - 1) == ';')\n {\n currString.erase(currString.size() - 1, 1);\n }\n string temp = \"\";\n for(unsigned g = 0; g < currString.size(); ++g)\n {\n if(currString.at(g) == '\"')\n {\n if(g > 0 && currString.at(g - 1) == '\\\\')\n {\n temp += currString.at(g);\n }\n }\n else if(currString.at(g) != '\\\\')\n {\n temp += currString.at(g);\n }\n }\n currString = temp;\n if(currString.find(\"#\") != string::npos)\n {\n if(currString.find(\"#\") != 0)\n {\n currCs.push_back(currString);\n }\n break;\n }\n currCs.push_back(currString);\n }\n \/\/Again, detects whether the string has connectors.\n bool detected = false;\n for(unsigned j = 0; j < currCs.size(); ++j)\n {\n if(currCs.at(j) == \"&&\" || currCs.at(j) == \"||\")\n {\n detected = true;\n break;\n }\n }\n \/\/If it detects them, it sends them to be parsed,\n \/\/where connector objects are created after the first command is created\n \/\/and subsequently linked until the end of parsing.\n if(detected)\n {\n string prevConnector;\n string nextConnector;\n vector<string> firstCommand;\n unsigned i = 0;\n while(currCs.at(i) != \"&&\" && currCs.at(i) != \"||\")\n {\n firstCommand.push_back(currCs.at(i));\n ++i;\n }\n prevConnector = currCs.at(i);\n Base *temp3;\n if(firstCommand.at(0) == \"test\")\n {\n temp3 = new Test(firstCommand);\n }\n else {\n temp3 = new Command(firstCommand);\n }\n currCmds.push_back(temp3);\n ++i;\n vector<string> currCommand;\n for(; i < currCs.size(); ++i)\n {\n currCommand.push_back(currCs.at(i));\n if(currCs.at(i) == \"&&\" || currCs.at(i) == \"||\")\n {\n currCommand.pop_back();\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n prevConnector = nextConnector;\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n prevConnector = nextConnector;\n currCommand.resize(0);\n }\n }\n }\n Base * temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n }\n }\n else {\n vector<string> currCommand;\n for(unsigned k = 0; k < currCs.size(); ++k)\n {\n currCommand.push_back(currCs.at(k));\n }\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n currCmds.push_back(temp);\n }\n}\n\/\/This is used to clean up the Processes vector in order to gather further\n\/\/input from the user.\nvoid Processes::reset()\n{\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n delete currCmds.at(i);\n }\n this->currCmds.resize(0);\n\n}<commit_msg>building precedence<commit_after>#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <algorithm>\nusing namespace std;\n\n#include \"Processes.h\"\n#include \"Base.h\"\n#include \"Command.h\"\n#include \"Andand.h\"\n#include \"Oror.h\"\n#include \"Test.h\"\n\n\/\/Simple constructor\nProcesses::Processes()\n{\n currCmds.resize(0);\n}\n\/\/Simple destructor\nProcesses::~Processes()\n{\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n delete currCmds.at(i);\n }\n}\n\/\/This executes all objects within the object's currCmds vector\nint Processes::execute()\n{\n int temp = 0;\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n temp = currCmds.at(i)->execute();\n }\n return temp;\n}\n\/\/Processes parses the code to split it into separate command lines\n\/\/should there be any semicolons present.\nvoid Processes::parse(string input)\n{\n vector<string> currCs;\n istringstream inSS(input);\n string currString;\n \/\/Main loop for parsing input that contains semicolons\n if(count(input.begin(), input.end(), ';') >= 1)\n {\n while(input.find(\";\") != string::npos)\n {\n if(count(input.begin(), input.end(), ';') == 1 \n && input.find(\";\") != input.size() - 1 \n && (input.at(input.find(\";\") + 1)) == '\"')\n {\n break;\n }\n if(count(input.begin(), input.end(), ';') == 1 && input.find(\";\") == input.size() - 1)\n {\n break;\n }\n bool hashtag = false;\n bool semicolon = false;\n bool first = false;\n currCs.resize(0);\n while(!semicolon)\n {\n inSS >> currString;\n input.erase(0, currString.size() + 1);\n \/\/Tests for hashtag\/semicolon presence\n if(currString.find(\"#\") != string::npos)\n {\n hashtag = true;\n if(currString.find(\"#\") != 0 && (!first))\n {\n currCs.push_back(currString);\n first = true;\n }\n }\n if(currString.find(\";\") != string::npos)\n {\n semicolon = true;\n }\n string temp = \"\";\n for(unsigned g = 0; g < currString.size(); ++g)\n {\n if(currString.at(g) == '\"')\n {\n if(g > 0 && currString.at(g - 1) == '\\\\')\n {\n temp += currString.at(g);\n }\n }\n else if(currString.at(g) != '\\\\')\n {\n temp += currString.at(g);\n }\n }\n currString = temp;\n if(!hashtag)\n {\n if(!semicolon)\n {\n currCs.push_back(currString);\n }\n else\n {\n currString.erase(currString.size() - 1, 1);\n currCs.push_back(currString);\n }\n }\n }\n \/\/Here, we detect the presence of connectors.\n bool detected = false;\n bool parenthesis = true;\n for(unsigned j = 0; j < currCs.size(); ++j)\n {\n if(currCs.at(j) == \"||\" || currCs.at(j) == \"&&\")\n {\n detected = true;\n break;\n }\n if(currCs.at(j).find(\"(\") != string::npos)\n {\n parenthesis = true;\n }\n }\n \/\/If it detects one, it sends the vector to a loop\n \/\/that runs until the end of the current command string.\n \/\/It stops at the next connector, looks at the previous connector,\n \/\/and creates objects and links them correspondingly.\n if(detected && !parenthsis)\n {\n string prevConnector;\n string nextConnector;\n vector<string> firstCommand;\n unsigned i = 0;\n while(currCs.at(i) != \"&&\" && currCs.at(i) != \"||\")\n {\n firstCommand.push_back(currCs.at(i));\n ++i;\n }\n prevConnector = currCs.at(i);\n Base * temp3;\n if(firstCommand.at(0) == \"test\")\n {\n temp3 = new Test(firstCommand);\n }\n else\n {\n temp3 = new Command(firstCommand);\n }\n currCmds.push_back(temp3);\n ++i;\n vector<string> currCommand;\n for(;i < currCs.size(); ++i)\n {\n currCommand.push_back(currCs.at(i));\n if(currCs.at(i) == \"&&\" || currCs.at(i) == \"||\")\n {\n currCommand.pop_back();\n if(currCommand.at(0) == \"test\")\n {\n Base *temp = new Test(currCommand);\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n }\n else {\n Base *temp = new Command(currCommand);\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(\n currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n } \n }\n }\n }\n else if(detected && parenthesis)\n {\n \n }\n \/\/This runs if there no connectors left after semicolon detecting.\n else {\n vector<string> currCommand;\n for(unsigned k = 0; k < currCs.size(); ++k)\n {\n currCommand.push_back(currCs.at(k));\n }\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n currCmds.push_back(temp);\n }\n }\n }\n \/\/Second loop that parses the remaining part of the input\n \/\/Also, if the input never contained any semicolons,\n \/\/the parse will go straight to this part of the code.\n currCs.resize(0);\n while(inSS >> currString)\n {\n if(currString.at(currString.size() - 1) == ';')\n {\n currString.erase(currString.size() - 1, 1);\n }\n string temp = \"\";\n for(unsigned g = 0; g < currString.size(); ++g)\n {\n if(currString.at(g) == '\"')\n {\n if(g > 0 && currString.at(g - 1) == '\\\\')\n {\n temp += currString.at(g);\n }\n }\n else if(currString.at(g) != '\\\\')\n {\n temp += currString.at(g);\n }\n }\n currString = temp;\n if(currString.find(\"#\") != string::npos)\n {\n if(currString.find(\"#\") != 0)\n {\n currCs.push_back(currString);\n }\n break;\n }\n currCs.push_back(currString);\n }\n \/\/Again, detects whether the string has connectors.\n bool detected = false;\n bool parenthesis = false;\n for(unsigned j = 0; j < currCs.size(); ++j)\n {\n if(currCs.at(j) == \"&&\" || currCs.at(j) == \"||\")\n {\n detected = true;\n break;\n }\n }\n \/\/If it detects them, it sends them to be parsed,\n \/\/where connector objects are created after the first command is created\n \/\/and subsequently linked until the end of parsing.\n if(detected && !parenthesis)\n {\n string prevConnector;\n string nextConnector;\n vector<string> firstCommand;\n unsigned i = 0;\n while(currCs.at(i) != \"&&\" && currCs.at(i) != \"||\")\n {\n firstCommand.push_back(currCs.at(i));\n ++i;\n }\n prevConnector = currCs.at(i);\n Base *temp3;\n if(firstCommand.at(0) == \"test\")\n {\n temp3 = new Test(firstCommand);\n }\n else {\n temp3 = new Command(firstCommand);\n }\n currCmds.push_back(temp3);\n ++i;\n vector<string> currCommand;\n for(; i < currCs.size(); ++i)\n {\n currCommand.push_back(currCs.at(i));\n if(currCs.at(i) == \"&&\" || currCs.at(i) == \"||\")\n {\n currCommand.pop_back();\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n nextConnector = currCs.at(i);\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n prevConnector = nextConnector;\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n prevConnector = nextConnector;\n currCommand.resize(0);\n }\n }\n }\n Base * temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n if(prevConnector == \"&&\")\n {\n Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), \n temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n currCommand.resize(0);\n }\n else\n {\n Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);\n currCmds.pop_back();\n currCmds.push_back(temp2);\n }\n }\n else if(detected && parenthesis)\n {\n \n }\n else {\n vector<string> currCommand;\n for(unsigned k = 0; k < currCs.size(); ++k)\n {\n currCommand.push_back(currCs.at(k));\n }\n Base *temp;\n if(currCommand.at(0) == \"test\")\n {\n temp = new Test(currCommand);\n }\n else {\n temp = new Command(currCommand);\n }\n currCmds.push_back(temp);\n }\n}\n\/\/This is used to clean up the Processes vector in order to gather further\n\/\/input from the user.\nvoid Processes::reset()\n{\n for(unsigned i = 0; i < currCmds.size(); ++i)\n {\n delete currCmds.at(i);\n }\n this->currCmds.resize(0);\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"RayTracer.hpp\"\n#include <ctime>\n\n\/\/temporary variables\nVec3Df testRayOrigin;\nVec3Df testRayDestination;\nstring input;\nextern unsigned int textures[2];\n\n\/\/use this function for any preprocessing of the mesh.\nvoid init(int argc, char **argv){\n \/\/load the mesh file\n \/\/feel free to replace cube by a path to another model\n \/\/please realize that not all OBJ files will successfully load.\n \/\/Nonetheless, if they come from Blender, they should.\n \/\/there is a difference between windows written objs and Linux written objs.\n \/\/hence, some models might not yet work well.\n\n RayTracingResolutionX = 1000; \/\/ These resolutions should be the same as the window,\n RayTracingResolutionY = 1000; \/\/ otherwise unexpected behaviour occurs.\n\n if(argc == 2){\n input = argv[1];\n }else{\n cout\n << \"Mesh file name: (0: monkey, 1: cube, 2: dodgeColorTest, 3: simple_monkey)\"\n << endl << \"You can omit the mesh\/ path and the .obj extension.\"\n << endl;\n cin >> input;\n }\n\n if(input == \"0\")\n input = \"cube\";\n else if(input == \"1\")\n input = \"simple_monkey\";\n else if(input == \"2\")\n input = \"monkey\";\n else if(input == \"3\")\n input = \"dodgeColorTest\";\n\n input = string(\"mesh\/\").append(input).append(\".obj\");\n MyMesh.loadMesh(input.c_str(), true);\n\n MyMesh.computeVertexNormals();\n\n \/\/one first move: initialize the first light source\n \/\/at least ONE light source has to be in the scene!!!\n \/\/here, we set it to the current location of the camera\n MyLightPositions.push_back(MyCameraPosition);\n}\n\n\n\/\/transformer le x, y en position 3D\nvoid produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest){\n int viewport[4];\n double modelview[16];\n double projection[16];\n \/\/point sur near plane\n \/\/double positionN[3];\n \/\/point sur far plane\n \/\/double positionF[3];\n glGetDoublev(GL_MODELVIEW_MATRIX, modelview); \/\/recuperer matrices\n glGetDoublev(GL_PROJECTION_MATRIX, projection); \/\/recuperer matrices\n glGetIntegerv(GL_VIEWPORT, viewport); \/\/viewport\n int y_new = viewport[3] - y_I;\n\n double x, y, z;\n\n gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z);\n origin->p[0] = float(x);\n origin->p[1] = float(y);\n origin->p[2] = float(z);\n gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z);\n dest->p[0] = float(x);\n dest->p[1] = float(y);\n dest->p[2] = float(z);\n}\n\nvoid produceRay(int x_I, int y_I, Vec3Df & origin, Vec3Df & dest){\n produceRay(x_I, y_I, &origin, &dest);\n}\n\n\nvoid startRayTracing(int texIndex, bool verbose){\n \/\/C'est nouveau!!!\n \/\/commencez ici et lancez vos propres fonctions par rayon.\n\n\tif (verbose) cout << \"Raytracing\" << endl;\n\tImage result(RayTracingResolutionX, RayTracingResolutionY);\n\n Vec3Df origin00, dest00;\n Vec3Df origin01, dest01;\n Vec3Df origin10, dest10;\n Vec3Df origin11, dest11;\n Vec3Df origin, dest;\n\n produceRay(0, 0, &origin00, &dest00);\n produceRay(0, RayTracingResolutionY - 1, &origin01, &dest01);\n produceRay(RayTracingResolutionX - 1, 0, &origin10, &dest10);\n produceRay(RayTracingResolutionX - 1, RayTracingResolutionY - 1, &origin11,\n &dest11);\n\n \/\/ Perform timing\n time_t start, end, ticks;\n start = clock();\n\n\tint stepsize = 8;\n\tif (verbose) stepsize = 1;\n\n for(float y = 0;y < RayTracingResolutionY; y += stepsize){\n for(float x = 0;x < RayTracingResolutionX; x += stepsize){\n \/\/svp, decidez vous memes quels parametres vous allez passer à la fonction\n \/\/e.g., maillage, triangles, sphères etc.\n const float xscale = 1.0f - x \/ (RayTracingResolutionX - 1);\n#ifdef WIN32\n const float yscale = float(y) \/ (RayTracingResolutionY - 1);\n#else\n const float yscale = 1.0f - y \/ (RayTracingResolutionY - 1);\n#endif\n origin = yscale * (xscale * origin00 + (1 - xscale) * origin10)\n + (1 - yscale)\n * (xscale * origin01 + (1 - xscale) * origin11);\n dest = yscale * (xscale * dest00 + (1 - xscale) * dest10)\n + (1 - yscale) * (xscale * dest01 + (1 - xscale) * dest11);\n\n\t\t\tVec3Df color = performRayTracing(origin, dest);\n\t\t\tfor (int xx = 0; xx < stepsize; xx++)\n\t\t\tfor (int yy = 0; yy < stepsize; yy++)\n\t\t\t\tresult.setPixel(x+xx, y+yy, color);\n }\n }\n\n \/\/ calculate elapsed time\n end = clock();\n ticks = end - start;\n\tstart = end;\n int millis = ticks * 1000 \/ CLOCKS_PER_SEC;\n\n if (verbose) printf(\"Rendering took %d ms\\n\", millis);\n\n \/\/ write to texture\n\tglBindTexture(GL_TEXTURE_2D, textures[texIndex]);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, RayTracingResolutionX,\n\t\tRayTracingResolutionY, 0, GL_RGB, GL_FLOAT, &result._image[0]);\n\n\t\/\/ calculate elapsed time\n\tend = clock();\n\tticks = end - start;\n\tmillis = ticks * 1000 \/ CLOCKS_PER_SEC;\n\n\tif (verbose) printf(\"Uploading to GPU took %d ms\\n\", millis);\n\n if (verbose) result.writeImage(\"result\");\n}\n\n#define rayOrig ray.orig\n#define rayDir ray.dir\n#define VEWY_HIGH 10e6f\n\nVec3Df black(0, 0, 0);\n\n\/\/return the color of your pixel.\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest){\n\tRay ray = Ray(black, origin, dest);\n\n\t\/\/ calculate nearest triangle\n\tint idx = -1; \/* the triangle that was hit *\/\n\tfloat hit = VEWY_HIGH; \/* distance to hit triangle *\/\n\tunsigned int numTriangles = MyMesh.triangles.size();\n\tfor (unsigned int i = 0; i < numTriangles; i++){\n\t\tfloat ins = ray.intersect(MyMesh.triangles[i]);\n\t\tif (ins < VEWY_HIGH && ins < hit && ins > 0) {\n\t\t\thit = ins;\n\t\t\tidx = i;\n\t\t}\n\t}\n\n\n\t\/\/ using black\n\tif (idx == -1)\n\t\treturn black;\n\n\tVec3Df& normal = MyMesh.triangles[idx].normal;\n\tfloat angle = -dot(normal, origin) * 0.5;\n\n\treturn Vec3Df(angle, angle, angle);\n}\n\nvoid yourDebugDraw(){\n \/\/draw open gl debug stuff\n \/\/this function is called every frame\n\n \/\/as an example:\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glDisable(GL_LIGHTING);\n glColor3f(1, 0, 1);\n glBegin(GL_LINES);\n glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);\n glVertex3f(testRayDestination[0], testRayDestination[1],\n testRayDestination[2]);\n glEnd();\n glPointSize(10);\n glBegin(GL_POINTS);\n glVertex3fv(MyLightPositions[0].pointer());\n glEnd();\n glPopAttrib();\n\n}\n\nvoid yourKeyboardFunc(char t, int x, int y){\n \/\/ do what you want with the keyboard input t.\n \/\/ x, y are the screen position\n\n \/\/here I use it to get the coordinates of a ray, which I then draw in the debug function.\n produceRay(x, y, testRayOrigin, testRayDestination);\n\n std::cout << t << \" pressed! The mouse was in location \" << x << \",\" << y\n << \"!\" << std::endl;\n}\n<commit_msg>Added FPS counter, saves to local variable.<commit_after>#include \"RayTracer.hpp\"\n#include <ctime>\n\n\/\/temporary variables\nVec3Df testRayOrigin;\nVec3Df testRayDestination;\nstring input;\nextern unsigned int textures[2];\nclock_t lastFrameTime;\nfloat fps;\n\n\/\/use this function for any preprocessing of the mesh.\nvoid init(int argc, char **argv){\n \/\/load the mesh file\n \/\/feel free to replace cube by a path to another model\n \/\/please realize that not all OBJ files will successfully load.\n \/\/Nonetheless, if they come from Blender, they should.\n \/\/there is a difference between windows written objs and Linux written objs.\n \/\/hence, some models might not yet work well.\n\n\tlastFrameTime = clock();\n\n RayTracingResolutionX = 1000; \/\/ These resolutions should be the same as the window,\n RayTracingResolutionY = 1000; \/\/ otherwise unexpected behaviour occurs.\n\n if(argc == 2){\n input = argv[1];\n }else{\n cout\n << \"Mesh file name: (0: monkey, 1: cube, 2: dodgeColorTest, 3: simple_monkey)\"\n << endl << \"You can omit the mesh\/ path and the .obj extension.\"\n << endl;\n cin >> input;\n }\n\n if(input == \"0\")\n input = \"cube\";\n else if(input == \"1\")\n input = \"simple_monkey\";\n else if(input == \"2\")\n input = \"monkey\";\n else if(input == \"3\")\n input = \"dodgeColorTest\";\n\n input = string(\"mesh\/\").append(input).append(\".obj\");\n MyMesh.loadMesh(input.c_str(), true);\n\n MyMesh.computeVertexNormals();\n\n \/\/one first move: initialize the first light source\n \/\/at least ONE light source has to be in the scene!!!\n \/\/here, we set it to the current location of the camera\n MyLightPositions.push_back(MyCameraPosition);\n}\n\n\n\/\/transformer le x, y en position 3D\nvoid produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest){\n int viewport[4];\n double modelview[16];\n double projection[16];\n \/\/point sur near plane\n \/\/double positionN[3];\n \/\/point sur far plane\n \/\/double positionF[3];\n glGetDoublev(GL_MODELVIEW_MATRIX, modelview); \/\/recuperer matrices\n glGetDoublev(GL_PROJECTION_MATRIX, projection); \/\/recuperer matrices\n glGetIntegerv(GL_VIEWPORT, viewport); \/\/viewport\n int y_new = viewport[3] - y_I;\n\n double x, y, z;\n\n gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z);\n origin->p[0] = float(x);\n origin->p[1] = float(y);\n origin->p[2] = float(z);\n gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z);\n dest->p[0] = float(x);\n dest->p[1] = float(y);\n dest->p[2] = float(z);\n}\n\nvoid produceRay(int x_I, int y_I, Vec3Df & origin, Vec3Df & dest){\n produceRay(x_I, y_I, &origin, &dest);\n}\n\n\nvoid startRayTracing(int texIndex, bool verbose){\n \/\/C'est nouveau!!!\n \/\/commencez ici et lancez vos propres fonctions par rayon.\n\n\tif (verbose) cout << \"Raytracing\" << endl;\n\tImage result(RayTracingResolutionX, RayTracingResolutionY);\n\n Vec3Df origin00, dest00;\n Vec3Df origin01, dest01;\n Vec3Df origin10, dest10;\n Vec3Df origin11, dest11;\n Vec3Df origin, dest;\n\n produceRay(0, 0, &origin00, &dest00);\n produceRay(0, RayTracingResolutionY - 1, &origin01, &dest01);\n produceRay(RayTracingResolutionX - 1, 0, &origin10, &dest10);\n produceRay(RayTracingResolutionX - 1, RayTracingResolutionY - 1, &origin11,\n &dest11);\n\n \/\/ Perform timing\n time_t start, end, ticks;\n start = clock();\n\n\tint stepsize = 8;\n\tif (verbose) stepsize = 1;\n\n for(float y = 0;y < RayTracingResolutionY; y += stepsize){\n for(float x = 0;x < RayTracingResolutionX; x += stepsize){\n \/\/svp, decidez vous memes quels parametres vous allez passer à la fonction\n \/\/e.g., maillage, triangles, sphères etc.\n const float xscale = 1.0f - x \/ (RayTracingResolutionX - 1);\n#ifdef WIN32\n const float yscale = float(y) \/ (RayTracingResolutionY - 1);\n#else\n const float yscale = 1.0f - y \/ (RayTracingResolutionY - 1);\n#endif\n origin = yscale * (xscale * origin00 + (1 - xscale) * origin10)\n + (1 - yscale)\n * (xscale * origin01 + (1 - xscale) * origin11);\n dest = yscale * (xscale * dest00 + (1 - xscale) * dest10)\n + (1 - yscale) * (xscale * dest01 + (1 - xscale) * dest11);\n\n\t\t\tVec3Df color = performRayTracing(origin, dest);\n\t\t\tfor (int xx = 0; xx < stepsize; xx++)\n\t\t\tfor (int yy = 0; yy < stepsize; yy++)\n\t\t\t\tresult.setPixel(x+xx, y+yy, color);\n }\n }\n\n \/\/ calculate elapsed time\n end = clock();\n ticks = end - start;\n\tstart = end;\n int millis = ticks * 1000 \/ CLOCKS_PER_SEC;\n\n if (verbose) printf(\"Rendering took %d ms\\n\", millis);\n\n \/\/ write to texture\n\tglBindTexture(GL_TEXTURE_2D, textures[texIndex]);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, RayTracingResolutionX,\n\t\tRayTracingResolutionY, 0, GL_RGB, GL_FLOAT, &result._image[0]);\n\n\t\/\/ calculate elapsed time\n\tend = clock();\n\tticks = end - start;\n\tmillis = ticks * 1000 \/ CLOCKS_PER_SEC;\n\n\tif (verbose) printf(\"Uploading to GPU took %d ms\\n\", millis);\n\n if (verbose) result.writeImage(\"result\");\n}\n\n#define rayOrig ray.orig\n#define rayDir ray.dir\n#define VEWY_HIGH 10e6f\n\nVec3Df black(0, 0, 0);\n\n\/\/return the color of your pixel.\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest){\n\tRay ray = Ray(black, origin, dest);\n\n\t\/\/ calculate nearest triangle\n\tint idx = -1; \/* the triangle that was hit *\/\n\tfloat hit = VEWY_HIGH; \/* distance to hit triangle *\/\n\tunsigned int numTriangles = MyMesh.triangles.size();\n\tfor (unsigned int i = 0; i < numTriangles; i++){\n\t\tfloat ins = ray.intersect(MyMesh.triangles[i]);\n\t\tif (ins < VEWY_HIGH && ins < hit && ins > 0) {\n\t\t\thit = ins;\n\t\t\tidx = i;\n\t\t}\n\t}\n\n\n\t\/\/ using black\n\tif (idx == -1)\n\t\treturn black;\n\n\tVec3Df& normal = MyMesh.triangles[idx].normal;\n\tfloat angle = -dot(normal, origin) * 0.5;\n\n\treturn Vec3Df(angle, angle, angle);\n}\n\nvoid yourDebugDraw(){\n \/\/draw open gl debug stuff\n \/\/this function is called every frame\n\n\tclock_t diff = clock() - lastFrameTime;\n\tlastFrameTime = clock();\n\tfps = 1 \/ ((float)diff \/ (float)CLOCKS_PER_SEC);\n\tcout << fps << endl;\n\n \/\/as an example:\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glDisable(GL_LIGHTING);\n glColor3f(1, 0, 1);\n glBegin(GL_LINES);\n glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);\n glVertex3f(testRayDestination[0], testRayDestination[1],\n testRayDestination[2]);\n glEnd();\n glPointSize(10);\n glBegin(GL_POINTS);\n glVertex3fv(MyLightPositions[0].pointer());\n glEnd();\n glPopAttrib();\n\n}\n\nvoid yourKeyboardFunc(char t, int x, int y){\n \/\/ do what you want with the keyboard input t.\n \/\/ x, y are the screen position\n\n \/\/here I use it to get the coordinates of a ray, which I then draw in the debug function.\n produceRay(x, y, testRayOrigin, testRayDestination);\n\n std::cout << t << \" pressed! The mouse was in location \" << x << \",\" << y\n << \"!\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <Reduction.hpp>\n\nnamespace TuneBench {\n\nreductionConf::reductionConf() : isa::OpenCL::KernelConf(), nrItemsPerBlock(1) {}\n\nstd::string reductionConf::print() const {\n return isa::utils::toString(nrItemsPerBlock) + \" \" + isa::OpenCL::KernelConf::print();\n}\n\nstd::string * getReductionOpenCL(const reductionConf & conf, const std::string & inputDataName, const std::string & outputDataName, const unsigned int inputSize) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void reduction(__global const \" + inputDataName + \" * const restrict input, __global \" + outputDataName + \" * const restrict output) {\\n\"\n \"const unsigned int firstItem = (get_group_id(0) * \" + isa::utils::toString(conf.getNrItemsPerBlock()) + \") + get_local_id(0);\\n\"\n \"__local \" + inputDataName + \" buffer[\" + isa::utils::toString(conf.getNrThreadsD0()) + \"];\\n\"\n \"<%DEF%>\"\n \"\\n\"\n \"\/\/ First compute phase\\n\"\n \"for ( unsigned int item = firstItem; (item < firstItem + \" + isa::utils::toString(conf.getNrItemsPerBlock()) + \") && (item + \" + isa::utils::toString((conf.getNrItemsD0() - 1) * conf.getNrThreadsD0()) + \" < \" + isa::utils::toString(inputSize) + \"); item += \" + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + \" ) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"\/\/ In-thread reduce phase\\n\"\n \"<%REDUCE%>\"\n \"buffer[get_local_id(0)] = accumulator0;\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"\/\/ Parallel reduce phase\\n\"\n \"unsigned int threshold = \" + isa::utils::toString(conf.getNrThreadsD0() \/ 2) + \";\\n\"\n \"for ( unsigned int item = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n \"if ( item < threshold ) {\\n\"\n \"accumulator0 += buffer[item + threshold];\\n\"\n \"buffer[item] = accumulator0;\\n\"\n \"}\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"}\\n\"\n \"\/\/ Store\\n\"\n \"if ( get_local_id(0) == 0 ) {\\n\"\n \"output[get_group_id(0)] = accumulator0;\\n\"\n \"}\\n\"\n \"}\\n\";\n std::string def_sTemplate = outputDataName + \" accumulator<%NUM%> = 0;\\n\";\n std::string compute_sTemplate = \"accumulator<%NUM%> += input[item + <%OFFSET%>];\\n\";\n std::string reduce_sTemplate = \"accumulator0 += accumulator<%NUM%>;\\n\";\n \/\/ End kernel's template\n\n std::string * def_s = new std::string();\n std::string * compute_s = new std::string();\n std::string * reduce_s = new std::string();\n\n for ( unsigned int item = 0; item < conf.getNrItemsD0(); item++ ) {\n std::string item_s = isa::utils::toString(item);\n std::string offset_s = isa::utils::toString(item * conf.getNrThreadsD0());\n std::string * temp = 0;\n\n temp = isa::utils::replace(&def_sTemplate, \"<%NUM%>\", item_s);\n def_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&compute_sTemplate, \"<%NUM%>\", item_s);\n if ( item == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n compute_s->append(*temp);\n delete temp;\n if ( item > 0 ) {\n temp = isa::utils::replace(&reduce_sTemplate, \"<%NUM%>\", item_s);\n reduce_s->append(*temp);\n delete temp;\n }\n }\n code = isa::utils::replace(code, \"<%DEF%>\", *def_s, true);\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n code = isa::utils::replace(code, \"<%REDUCE%>\", *reduce_s, true);\n delete def_s;\n delete compute_s;\n delete reduce_s;\n\n return code;\n}\n\n} \/\/ TuneBench\n\n<commit_msg>Simplifying the constraint on the first compute phase.<commit_after>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <Reduction.hpp>\n\nnamespace TuneBench {\n\nreductionConf::reductionConf() : isa::OpenCL::KernelConf(), nrItemsPerBlock(1) {}\n\nstd::string reductionConf::print() const {\n return isa::utils::toString(nrItemsPerBlock) + \" \" + isa::OpenCL::KernelConf::print();\n}\n\nstd::string * getReductionOpenCL(const reductionConf & conf, const std::string & inputDataName, const std::string & outputDataName, const unsigned int inputSize) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void reduction(__global const \" + inputDataName + \" * const restrict input, __global \" + outputDataName + \" * const restrict output) {\\n\"\n \"const unsigned int firstItem = (get_group_id(0) * \" + isa::utils::toString(conf.getNrItemsPerBlock()) + \") + get_local_id(0);\\n\"\n \"__local \" + inputDataName + \" buffer[\" + isa::utils::toString(conf.getNrThreadsD0()) + \"];\\n\"\n \"<%DEF%>\"\n \"\\n\"\n \"\/\/ First compute phase\\n\"\n \"for ( unsigned int item = firstItem; (item + \" + isa::utils::toString((conf.getNrItemsD0() - 1) * conf.getNrThreadsD0()) + \") < firstItem + \" + isa::utils::toString(conf.getNrItemsPerBlock()) + \"; item += \" + isa::utils::toString(conf.getNrThreadsD0() * conf.getNrItemsD0()) + \" ) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"\/\/ In-thread reduce phase\\n\"\n \"<%REDUCE%>\"\n \"buffer[get_local_id(0)] = accumulator0;\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"\/\/ Parallel reduce phase\\n\"\n \"unsigned int threshold = \" + isa::utils::toString(conf.getNrThreadsD0() \/ 2) + \";\\n\"\n \"for ( unsigned int item = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n \"if ( item < threshold ) {\\n\"\n \"accumulator0 += buffer[item + threshold];\\n\"\n \"buffer[item] = accumulator0;\\n\"\n \"}\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"}\\n\"\n \"\/\/ Store\\n\"\n \"if ( get_local_id(0) == 0 ) {\\n\"\n \"output[get_group_id(0)] = accumulator0;\\n\"\n \"}\\n\"\n \"}\\n\";\n std::string def_sTemplate = outputDataName + \" accumulator<%NUM%> = 0;\\n\";\n std::string compute_sTemplate = \"accumulator<%NUM%> += input[item + <%OFFSET%>];\\n\";\n std::string reduce_sTemplate = \"accumulator0 += accumulator<%NUM%>;\\n\";\n \/\/ End kernel's template\n\n std::string * def_s = new std::string();\n std::string * compute_s = new std::string();\n std::string * reduce_s = new std::string();\n\n for ( unsigned int item = 0; item < conf.getNrItemsD0(); item++ ) {\n std::string item_s = isa::utils::toString(item);\n std::string offset_s = isa::utils::toString(item * conf.getNrThreadsD0());\n std::string * temp = 0;\n\n temp = isa::utils::replace(&def_sTemplate, \"<%NUM%>\", item_s);\n def_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&compute_sTemplate, \"<%NUM%>\", item_s);\n if ( item == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n compute_s->append(*temp);\n delete temp;\n if ( item > 0 ) {\n temp = isa::utils::replace(&reduce_sTemplate, \"<%NUM%>\", item_s);\n reduce_s->append(*temp);\n delete temp;\n }\n }\n code = isa::utils::replace(code, \"<%DEF%>\", *def_s, true);\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n code = isa::utils::replace(code, \"<%REDUCE%>\", *reduce_s, true);\n delete def_s;\n delete compute_s;\n delete reduce_s;\n\n return code;\n}\n\n} \/\/ TuneBench\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/**\n * @author Marek Kotewicz <marek@ethdev.com>\n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include <libsolidity\/CompilerStack.h>\n#include <jsonrpc\/json\/json.h>\n#include <boost\/test\/unit_test.hpp>\n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass InterfaceChecker {\npublic:\n\tbool checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)\n\t{\n\t\tm_compilerStack.compile(_code);\n\t\tstd::string generatedInterfaceString = m_compilerStack.getInterface();\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\treturn expectedInterface == generatedInterface;\n\t}\n\t\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityCompilerJSONInterfaceOutput, InterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = \"[]\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\t\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\t\t\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\t\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\n<commit_msg>solidity json interface tests fixes<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/**\n * @author Marek Kotewicz <marek@ethdev.com>\n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libsolidity\/CompilerStack.h>\n#include <jsonrpc\/json\/json.h>\n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass InterfaceChecker\n{\npublic:\n\tbool checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)\n\t{\n\t\tm_compilerStack.parse(_code);\n\t\tstd::string generatedInterfaceString = m_compilerStack.getInterface();\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\treturn expectedInterface == generatedInterface;\n\t}\n\t\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityCompilerJSONInterfaceOutput, InterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = \"[]\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\t\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\t\t\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\t\n\tBOOST_CHECK(checkInterface(sourceCode, interface));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011-2012, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n#include \"boost\/algorithm\/string\/replace.hpp\"\n#include \"boost\/\/format.hpp\"\n\n#include \"IECorePython\/IECoreBinding.h\"\n#include \"IECorePython\/RunTimeTypedBinding.h\"\n#include \"IECorePython\/ScopedGILRelease.h\"\n\n#include \"Gaffer\/CompoundNumericPlug.h\"\n\n#include \"GafferBindings\/ValuePlugBinding.h\"\n\n#include \"CompoundNumericPlugBinding.h\"\n\nusing namespace boost::python;\nusing namespace GafferBindings;\nusing namespace Gaffer;\n\nnamespace\n{\n\ntemplate<typename T>\nstd::string maskedCompoundNumericPlugRepr( const T *plug, unsigned flagsMask, const Serialisation *serialisation = nullptr )\n{\n\tstd::string extraArgs = \"\";\n\n\tconst IECore::GeometricData::Interpretation interpretation = plug->interpretation();\n\n\tif( interpretation != IECore::GeometricData::None )\n\t{\n\t\tboost::python::object interpretationAsPythonObject( interpretation );\n\t\tboost::python::object interpretationRepr = interpretationAsPythonObject.attr( \"__repr__\" )();\n\t\textraArgs = \"interpretation = \" + std::string( boost::python::extract<std::string>( interpretationRepr ) );\n\t\tboost::replace_first( extraArgs, \"_IECore\", \"GeometricData\" );\n\t}\n\n\treturn ValuePlugSerialiser::repr( plug, flagsMask, extraArgs, serialisation );\n}\n\ntemplate<typename T>\nstd::string compoundNumericPlugRepr( const T *plug )\n{\n\treturn maskedCompoundNumericPlugRepr( plug, Plug::All );\n}\n\ntemplate<typename T>\nclass CompoundNumericPlugSerialiser : public ValuePlugSerialiser\n{\n public:\n\n\tstd::string constructor( const Gaffer::GraphComponent *graphComponent, const Serialisation &serialisation ) const override\n\t{\n\t\treturn maskedCompoundNumericPlugRepr( static_cast<const T *>( graphComponent ), Plug::All & ~Plug::ReadOnly, &serialisation );\n\t}\n\n\tprotected :\n\n\t\t\/\/ Ideally we'll serialise the value as a single getValue() call for this plug,\n\t\t\/\/ but we can't do that if any of the children have input connections.\n\t\tbool valueNeedsSerialisation( const Gaffer::ValuePlug *plug, const Serialisation &serialisation ) const override\n\t\t{\n\t\t\tif( !ValuePlugSerialiser::valueNeedsSerialisation( plug, serialisation ) )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor( PlugIterator it( plug ); !it.done(); ++it )\n\t\t\t{\n\t\t\t\tif( (*it)->getInput() )\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n};\n\ntemplate<typename T>\nvoid setValue( T *plug, const typename T::ValueType value )\n{\n\t\/\/ we use a GIL release here to prevent a lock in the case where this triggers a graph\n\t\/\/ evaluation which decides to go back into python on another thread:\n\tIECorePython::ScopedGILRelease r;\n\tplug->setValue( value );\n}\n\ntemplate<typename T>\ntypename T::ValueType getValue( const T *plug )\n{\n\t\/\/ Must release GIL in case computation spawns threads which need\n\t\/\/ to reenter Python.\n\tIECorePython::ScopedGILRelease r;\n\treturn plug->getValue();\n}\n\ntemplate<typename T>\nvoid gang( T *plug )\n{\n\t\/\/ Must release GIL in case this triggers a graph evaluation\n\t\/\/ which wants to enter Python on another thread.\n\tIECorePython::ScopedGILRelease r;\n\tplug->gang();\n}\n\ntemplate<typename T>\nvoid ungang( T *plug )\n{\n\t\/\/ Must release GIL in case this triggers a graph evaluation\n\t\/\/ which wants to enter Python on another thread.\n\tIECorePython::ScopedGILRelease r;\n\tplug->ungang();\n}\n\ntemplate<typename T>\nvoid bind()\n{\n\ttypedef typename T::ValueType V;\n\n\tPlugClass<T>()\n\t\t.def( init<const char *, Plug::Direction, V, V, V, unsigned, IECore::GeometricData::Interpretation>(\n\t\t\t\t(\n\t\t\t\t\tboost::python::arg_( \"name\" )=GraphComponent::defaultName<T>(),\n\t\t\t\t\tboost::python::arg_( \"direction\" )=Plug::In,\n\t\t\t\t\tboost::python::arg_( \"defaultValue\" )=V( 0 ),\n\t\t\t\t\tboost::python::arg_( \"minValue\" )=V(Imath::limits<typename V::BaseType>::min()),\n\t\t\t\t\tboost::python::arg_( \"maxValue\" )=V(Imath::limits<typename V::BaseType>::max()),\n\t\t\t\t\tboost::python::arg_( \"flags\" )=Plug::Default,\n\t\t\t\t\tboost::python::arg_( \"interpretation\" )=IECore::GeometricData::None\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\t.def( \"defaultValue\", &T::defaultValue )\n\t\t.def( \"hasMinValue\", &T::hasMinValue )\n\t\t.def( \"hasMaxValue\", &T::hasMaxValue )\n\t\t.def( \"minValue\", &T::minValue )\n\t\t.def( \"maxValue\", &T::maxValue )\n\t\t.def( \"setValue\", &setValue<T> )\n\t\t.def( \"getValue\", &getValue<T> )\n\t\t.def( \"interpretation\", &T::interpretation )\n\t\t.def( \"canGang\", &T::canGang )\n\t\t.def( \"gang\", &gang<T> )\n\t\t.def( \"isGanged\", &T::isGanged )\n\t\t.def( \"ungang\", &ungang<T> )\n\t\t.def( \"__repr__\", &compoundNumericPlugRepr<T> )\n\t;\n\n\tSerialisation::registerSerialiser( T::staticTypeId(), new CompoundNumericPlugSerialiser<T>() );\n\n}\n\n} \/\/ namespace\n\nvoid GafferModule::bindCompoundNumericPlug()\n{\n\tbind<V2fPlug>();\n\tbind<V3fPlug>();\n\tbind<V2iPlug>();\n\tbind<V3iPlug>();\n\tbind<Color3fPlug>();\n\tbind<Color4fPlug>();\n}\n<commit_msg>CompoundNumericPlugBinding : Fix indentation<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011-2012, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n#include \"boost\/algorithm\/string\/replace.hpp\"\n#include \"boost\/\/format.hpp\"\n\n#include \"IECorePython\/IECoreBinding.h\"\n#include \"IECorePython\/RunTimeTypedBinding.h\"\n#include \"IECorePython\/ScopedGILRelease.h\"\n\n#include \"Gaffer\/CompoundNumericPlug.h\"\n\n#include \"GafferBindings\/ValuePlugBinding.h\"\n\n#include \"CompoundNumericPlugBinding.h\"\n\nusing namespace boost::python;\nusing namespace GafferBindings;\nusing namespace Gaffer;\n\nnamespace\n{\n\ntemplate<typename T>\nstd::string maskedCompoundNumericPlugRepr( const T *plug, unsigned flagsMask, const Serialisation *serialisation = nullptr )\n{\n\tstd::string extraArgs = \"\";\n\n\tconst IECore::GeometricData::Interpretation interpretation = plug->interpretation();\n\n\tif( interpretation != IECore::GeometricData::None )\n\t{\n\t\tboost::python::object interpretationAsPythonObject( interpretation );\n\t\tboost::python::object interpretationRepr = interpretationAsPythonObject.attr( \"__repr__\" )();\n\t\textraArgs = \"interpretation = \" + std::string( boost::python::extract<std::string>( interpretationRepr ) );\n\t\tboost::replace_first( extraArgs, \"_IECore\", \"GeometricData\" );\n\t}\n\n\treturn ValuePlugSerialiser::repr( plug, flagsMask, extraArgs, serialisation );\n}\n\ntemplate<typename T>\nstd::string compoundNumericPlugRepr( const T *plug )\n{\n\treturn maskedCompoundNumericPlugRepr( plug, Plug::All );\n}\n\ntemplate<typename T>\nclass CompoundNumericPlugSerialiser : public ValuePlugSerialiser\n{\n\n\tpublic :\n\n\t\tstd::string constructor( const Gaffer::GraphComponent *graphComponent, const Serialisation &serialisation ) const override\n\t\t{\n\t\t\treturn maskedCompoundNumericPlugRepr( static_cast<const T *>( graphComponent ), Plug::All & ~Plug::ReadOnly, &serialisation );\n\t\t}\n\n\tprotected :\n\n\t\t\/\/ Ideally we'll serialise the value as a single getValue() call for this plug,\n\t\t\/\/ but we can't do that if any of the children have input connections.\n\t\tbool valueNeedsSerialisation( const Gaffer::ValuePlug *plug, const Serialisation &serialisation ) const override\n\t\t{\n\t\t\tif( !ValuePlugSerialiser::valueNeedsSerialisation( plug, serialisation ) )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor( PlugIterator it( plug ); !it.done(); ++it )\n\t\t\t{\n\t\t\t\tif( (*it)->getInput() )\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n};\n\ntemplate<typename T>\nvoid setValue( T *plug, const typename T::ValueType value )\n{\n\t\/\/ we use a GIL release here to prevent a lock in the case where this triggers a graph\n\t\/\/ evaluation which decides to go back into python on another thread:\n\tIECorePython::ScopedGILRelease r;\n\tplug->setValue( value );\n}\n\ntemplate<typename T>\ntypename T::ValueType getValue( const T *plug )\n{\n\t\/\/ Must release GIL in case computation spawns threads which need\n\t\/\/ to reenter Python.\n\tIECorePython::ScopedGILRelease r;\n\treturn plug->getValue();\n}\n\ntemplate<typename T>\nvoid gang( T *plug )\n{\n\t\/\/ Must release GIL in case this triggers a graph evaluation\n\t\/\/ which wants to enter Python on another thread.\n\tIECorePython::ScopedGILRelease r;\n\tplug->gang();\n}\n\ntemplate<typename T>\nvoid ungang( T *plug )\n{\n\t\/\/ Must release GIL in case this triggers a graph evaluation\n\t\/\/ which wants to enter Python on another thread.\n\tIECorePython::ScopedGILRelease r;\n\tplug->ungang();\n}\n\ntemplate<typename T>\nvoid bind()\n{\n\ttypedef typename T::ValueType V;\n\n\tPlugClass<T>()\n\t\t.def( init<const char *, Plug::Direction, V, V, V, unsigned, IECore::GeometricData::Interpretation>(\n\t\t\t\t(\n\t\t\t\t\tboost::python::arg_( \"name\" )=GraphComponent::defaultName<T>(),\n\t\t\t\t\tboost::python::arg_( \"direction\" )=Plug::In,\n\t\t\t\t\tboost::python::arg_( \"defaultValue\" )=V( 0 ),\n\t\t\t\t\tboost::python::arg_( \"minValue\" )=V(Imath::limits<typename V::BaseType>::min()),\n\t\t\t\t\tboost::python::arg_( \"maxValue\" )=V(Imath::limits<typename V::BaseType>::max()),\n\t\t\t\t\tboost::python::arg_( \"flags\" )=Plug::Default,\n\t\t\t\t\tboost::python::arg_( \"interpretation\" )=IECore::GeometricData::None\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\t\t.def( \"defaultValue\", &T::defaultValue )\n\t\t.def( \"hasMinValue\", &T::hasMinValue )\n\t\t.def( \"hasMaxValue\", &T::hasMaxValue )\n\t\t.def( \"minValue\", &T::minValue )\n\t\t.def( \"maxValue\", &T::maxValue )\n\t\t.def( \"setValue\", &setValue<T> )\n\t\t.def( \"getValue\", &getValue<T> )\n\t\t.def( \"interpretation\", &T::interpretation )\n\t\t.def( \"canGang\", &T::canGang )\n\t\t.def( \"gang\", &gang<T> )\n\t\t.def( \"isGanged\", &T::isGanged )\n\t\t.def( \"ungang\", &ungang<T> )\n\t\t.def( \"__repr__\", &compoundNumericPlugRepr<T> )\n\t;\n\n\tSerialisation::registerSerialiser( T::staticTypeId(), new CompoundNumericPlugSerialiser<T>() );\n\n}\n\n} \/\/ namespace\n\nvoid GafferModule::bindCompoundNumericPlug()\n{\n\tbind<V2fPlug>();\n\tbind<V3fPlug>();\n\tbind<V2iPlug>();\n\tbind<V3iPlug>();\n\tbind<Color3fPlug>();\n\tbind<Color4fPlug>();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/util\/fs.hpp>\n#include <cstdlib>\n#include <fstream>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/algorithm\/string.hpp>\n#pragma GCC diagnostic pop\n\nnamespace {\n\nstd::size_t count_shapefile_features(std::string const& filename)\n{\n mapnik::parameters params;\n params[\"type\"] = \"shape\";\n params[\"file\"] = filename;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(ds != nullptr);\n CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n\n std::size_t feature_count = 0;\n auto feature = features->next();\n while (feature)\n {\n ++feature_count;\n feature = features->next();\n }\n\n return feature_count;\n}\n\nint create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)\n{\n std::string cmd;\n if (std::getenv(\"DYLD_LIBRARY_PATH\") != nullptr)\n {\n cmd += std::string(\"DYLD_LIBRARY_PATH=\") + std::getenv(\"DYLD_LIBRARY_PATH\") + \" \";\n }\n\n cmd += \"shapeindex \";\n if (index_parts) cmd+= \"--index-parts \";\n cmd += filename;\n if (silent)\n {\n#ifndef _WINDOWS\n cmd += \" 2>\/dev\/null\";\n#else\n cmd += \" 2> nul\";\n#endif\n }\n return std::system(cmd.c_str());\n}\n\n}\n\nTEST_CASE(\"invalid shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Invalid index\")\n {\n std::string path = \"test\/data\/shp\/boundaries.shp\";\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n\n std::size_t feature_count = count_shapefile_features(path);\n\n \/\/ create invalid index\n std::ofstream index(index_path.c_str(), std::ios::binary);\n std::string buf(\"mapnik-invalid-index.................\");\n index.write(buf.c_str(), buf.size());\n index.close();\n\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n}\n\nTEST_CASE(\"shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Index\")\n {\n for (auto const& path : mapnik::util::list_directory(\"test\/data\/shp\/\"))\n {\n if (boost::iends_with(path,\".shp\"))\n {\n for (bool index_parts : {false, true} )\n {\n CAPTURE(path);\n CAPTURE(index_parts);\n\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n std::size_t feature_count = count_shapefile_features(path);\n \/\/ create *.index\n REQUIRE(create_shapefile_index(path, index_parts) == 0);\n if (feature_count == 0)\n {\n REQUIRE(!mapnik::util::exists(index_path)); \/\/ index won't be created if there's no features\n }\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n }\n }\n }\n}\n<commit_msg>clear mapped_memory_cache to ensure new '*.index` are used (MAPNIK_MEMORY_MAPPED_FILE) (ref #3306)<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/mapped_memory_cache.hpp>\n#include <mapnik\/util\/fs.hpp>\n#include <cstdlib>\n#include <fstream>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/algorithm\/string.hpp>\n#pragma GCC diagnostic pop\n\nnamespace {\n\nstd::size_t count_shapefile_features(std::string const& filename)\n{\n#if defined(MAPNIK_MEMORY_MAPPED_FILE)\n mapnik::mapped_memory_cache::instance().clear();\n#endif\n mapnik::parameters params;\n params[\"type\"] = \"shape\";\n params[\"file\"] = filename;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(ds != nullptr);\n CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n\n std::size_t feature_count = 0;\n auto feature = features->next();\n while (feature)\n {\n ++feature_count;\n feature = features->next();\n }\n\n return feature_count;\n}\n\nint create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)\n{\n std::string cmd;\n if (std::getenv(\"DYLD_LIBRARY_PATH\") != nullptr)\n {\n cmd += std::string(\"DYLD_LIBRARY_PATH=\") + std::getenv(\"DYLD_LIBRARY_PATH\") + \" \";\n }\n\n cmd += \"shapeindex \";\n if (index_parts) cmd+= \"--index-parts \";\n cmd += filename;\n if (silent)\n {\n#ifndef _WINDOWS\n cmd += \" 2>\/dev\/null\";\n#else\n cmd += \" 2> nul\";\n#endif\n }\n return std::system(cmd.c_str());\n}\n\n}\n\nTEST_CASE(\"invalid shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Invalid index\")\n {\n std::string path = \"test\/data\/shp\/boundaries.shp\";\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n\n std::size_t feature_count = count_shapefile_features(path);\n\n \/\/ create invalid index\n std::ofstream index(index_path.c_str(), std::ios::binary);\n std::string buf(\"mapnik-invalid-index.................\");\n index.write(buf.c_str(), buf.size());\n index.close();\n\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n}\n\nTEST_CASE(\"shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Index\")\n {\n for (auto const& path : mapnik::util::list_directory(\"test\/data\/shp\/\"))\n {\n if (boost::iends_with(path,\".shp\"))\n {\n for (bool index_parts : {false, true} )\n {\n CAPTURE(path);\n CAPTURE(index_parts);\n\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n std::size_t feature_count = count_shapefile_features(path);\n \/\/ create *.index\n REQUIRE(create_shapefile_index(path, index_parts) == 0);\n if (feature_count == 0)\n {\n REQUIRE(!mapnik::util::exists(index_path)); \/\/ index won't be created if there's no features\n }\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file Scripting.cpp\n @author Philip Abbet\n\n Implementation of the scripting-related functions of the Athena-Entities module\n*\/\n\n#include <Athena-Entities\/Scripting.h>\n#include <Athena-Entities\/Transforms.h>\n#include <Athena-Entities\/ComponentsList.h>\n#include <Athena-Scripting\/ScriptingManager.h>\n#include <Athena-Scripting\/Utils.h>\n#include <string>\n\nusing namespace Athena::Entities;\nusing namespace Athena::Scripting;\nusing namespace v8;\n\n\nnamespace Athena {\nnamespace Entities {\n\n\n\/\/-----------------------------------------------------------------------\n\nAnimation* fromJSAnimation(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Animation* pAnimation = 0;\n GetObjectPtr(value, &pAnimation);\n return pAnimation;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSAnimation()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Animation\");\n\n Handle<Object> jsAnimation = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsAnimation);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(Animation* pAnimation)\n{\n HandleScope handle_scope;\n\n if (!pAnimation)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Animation\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pAnimation);\n\n Handle<Object> jsAnimation = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsAnimation);\n}\n\n\/\/-----------------------------------------------------------------------\n\nAnimationsMixer* fromJSAnimationsMixer(Handle<Value> value)\n{\n if (value->IsObject())\n {\n AnimationsMixer* pMixer = 0;\n GetObjectPtr(value, &pMixer);\n return pMixer;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSAnimationsMixer()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.AnimationsMixer\");\n\n Handle<Object> jsAnimationsMixer = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsAnimationsMixer);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(AnimationsMixer* pMixer)\n{\n HandleScope handle_scope;\n\n if (!pMixer)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.AnimationsMixer\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pMixer);\n\n Handle<Object> jsAnimationsMixer = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsAnimationsMixer);\n}\n\n\/\/-----------------------------------------------------------------------\n\nComponentAnimation* fromJSComponentAnimation(Handle<Value> value)\n{\n if (value->IsObject())\n {\n ComponentAnimation* pComponentAnimation = 0;\n GetObjectPtr(value, &pComponentAnimation);\n return pComponentAnimation;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSComponentAnimation()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.ComponentAnimation\");\n\n Handle<Object> jsComponentAnimation = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsComponentAnimation);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(ComponentAnimation* pComponentAnimation)\n{\n HandleScope handle_scope;\n\n if (!pComponentAnimation)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.ComponentAnimation\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pComponentAnimation);\n\n Handle<Object> jsComponentAnimation = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsComponentAnimation);\n}\n\n\/\/-----------------------------------------------------------------------\n\ntComponentID fromJSComponentID(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Handle<Object> object = value->ToObject();\n Handle<Function> prototype = Handle<Function>::Cast(object->GetPrototype());\n\n if (std::string(\"Athena.Entities.ComponentID\") == *String::AsciiValue(prototype->Get(String::New(\"__classname__\"))))\n {\n return tComponentID((tComponentType) object->Get(String::New(\"type\"))->ToNumber()->NumberValue(),\n *String::AsciiValue(object->Get(String::New(\"entity\"))),\n *String::AsciiValue(object->Get(String::New(\"component\"))));\n }\n }\n\n return tComponentID(COMP_NONE);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(const tComponentID& value)\n{\n Local<Object> object = ScriptingManager::getSingletonPtr()->execute(\"new Athena.Entities.ComponentID('\" + value.toString() + \"');\")->ToObject();\n\n \/\/ Handle<Value> constructor = Context::GetCurrent()->Global()->Get(String::New(\"Athena.Entities.ComponentID\"));\n \/\/ if (!constructor->IsUndefined())\n \/\/ return ThrowException(String::New(\"BLAAAAAhD\"));\n \/\/ if (!constructor->IsFunction())\n \/\/ return ThrowException(String::New(\"Can't find the constructor function of Athena.Entities.ComponentID\"));\n\n \/\/ Local<Object> object = Handle<Function>::Cast(constructor)->NewInstance();\n\n \/\/ object->Set(String::New(\"type\"), Number::New(value.type));\n \/\/ object->Set(String::New(\"entity\"), String::New(value.strEntity.c_str()));\n \/\/ object->Set(String::New(\"component\"), String::New(value.strName.c_str()));\n\n return object;\n}\n\n\/\/-----------------------------------------------------------------------\n\nComponentsList* fromJSComponentsList(Handle<Value> value)\n{\n if (value->IsObject())\n {\n ComponentsList* pList = 0;\n GetObjectPtr(value, &pList);\n return pList;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSComponentsList()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.ComponentsList\");\n\n Handle<Object> jsList = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsList);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(ComponentsList* pList)\n{\n HandleScope handle_scope;\n\n if (!pList)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.ComponentsList\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pList);\n\n Handle<Object> jsList = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsList);\n}\n\n\/\/-----------------------------------------------------------------------\n\nComponent* fromJSComponent(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Component* pComponent = 0;\n GetObjectPtr(value, &pComponent);\n return pComponent;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSComponent()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Component\");\n\n Handle<Object> jsComponent = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsComponent);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(Component* pComponent)\n{\n HandleScope handle_scope;\n\n if (!pComponent)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Component\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pComponent);\n\n Handle<Object> jsComponent = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsComponent);\n}\n\n\/\/-----------------------------------------------------------------------\n\nEntity* fromJSEntity(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Entity* pEntity = 0;\n GetObjectPtr(value, &pEntity);\n return pEntity;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSEntity()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Entity\");\n\n Handle<Object> jsEntity = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsEntity);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(Entity* pEntity)\n{\n HandleScope handle_scope;\n\n if (!pEntity)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Entity\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pEntity);\n\n Handle<Object> jsEntity = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsEntity);\n}\n\n\/\/-----------------------------------------------------------------------\n\nScene* fromJSScene(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Scene* pScene = 0;\n GetObjectPtr(value, &pScene);\n return pScene;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSScene()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Scene\");\n\n Handle<Object> jsScene = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsScene);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(Scene* pScene)\n{\n HandleScope handle_scope;\n\n if (!pScene)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Scene\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pScene);\n\n Handle<Object> jsScene = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsScene);\n}\n\n\/\/-----------------------------------------------------------------------\n\nTransforms* fromJSTransforms(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Transforms* pTransforms = 0;\n GetObjectPtr(value, &pTransforms);\n return pTransforms;\n }\n\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Object> createJSTransforms()\n{\n HandleScope handle_scope;\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Transforms\");\n\n Handle<Object> jsTransforms = func->GetFunction()->NewInstance();\n\n return handle_scope.Close(jsTransforms);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(Transforms* pTransforms)\n{\n HandleScope handle_scope;\n\n if (!pTransforms)\n return Handle<Value>();\n\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate(\n \"Athena.Entities.Transforms\");\n\n Handle<Value> argv[1];\n argv[0] = External::Wrap(pTransforms);\n\n Handle<Object> jsTransforms = func->GetFunction()->NewInstance(1, argv);\n\n return handle_scope.Close(jsTransforms);\n}\n\n}\n}\n<commit_msg>[Scripting] Uses macros to implement the C++\/JavaScript conversion functions<commit_after>\/** @file Scripting.cpp\n @author Philip Abbet\n\n Implementation of the scripting-related functions of the Athena-Entities module\n*\/\n\n#include <Athena-Entities\/Scripting.h>\n#include <Athena-Entities\/Transforms.h>\n#include <Athena-Entities\/ComponentsList.h>\n#include <Athena-Scripting\/ScriptingManager.h>\n#include <Athena-Scripting\/Utils.h>\n#include <string>\n\nusing namespace Athena::Entities;\nusing namespace Athena::Scripting;\nusing namespace v8;\n\n\n#define FROM_JS(CLASS_NAME) \\\nCLASS_NAME* fromJS##CLASS_NAME(Handle<Value> value) \\\n{ \\\n if (value->IsObject()) \\\n { \\\n CLASS_NAME* pObject = 0; \\\n GetObjectPtr(value, &pObject); \\\n return pObject; \\\n } \\\n \\\n return 0; \\\n}\n\n\n#define CREATE_JS(CLASS_NAME) \\\nHandle<Object> createJS##CLASS_NAME() \\\n{ \\\n HandleScope handle_scope; \\\n \\\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( \\\n \"Athena.Entities.\" #CLASS_NAME); \\\n \\\n Handle<Object> jsObject = func->GetFunction()->NewInstance(); \\\n \\\n return handle_scope.Close(jsObject); \\\n}\n\n\n#define TO_JS(CLASS_NAME) \\\nHandle<Value> toJavaScript(CLASS_NAME* pObject) \\\n{ \\\n HandleScope handle_scope; \\\n \\\n if (!pObject) \\\n return Handle<Value>(); \\\n \\\n Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( \\\n \"Athena.Entities.\" #CLASS_NAME); \\\n \\\n Handle<Value> argv[1]; \\\n argv[0] = External::Wrap(pObject); \\\n \\\n Handle<Object> jsObject = func->GetFunction()->NewInstance(1, argv); \\\n \\\n return handle_scope.Close(jsObject); \\\n}\n\n\n#define IMPLEMENT_CONVERSIONS(CLASS_NAME) \\\n FROM_JS(CLASS_NAME); \\\n CREATE_JS(CLASS_NAME); \\\n TO_JS(CLASS_NAME);\n\n\n\nnamespace Athena {\nnamespace Entities {\n\n\nIMPLEMENT_CONVERSIONS(Animation)\nIMPLEMENT_CONVERSIONS(AnimationsMixer)\nIMPLEMENT_CONVERSIONS(ComponentAnimation)\nIMPLEMENT_CONVERSIONS(ComponentsList)\nIMPLEMENT_CONVERSIONS(Component)\nIMPLEMENT_CONVERSIONS(Entity)\nIMPLEMENT_CONVERSIONS(Scene)\nIMPLEMENT_CONVERSIONS(Transforms)\n\n\/\/-----------------------------------------------------------------------\n\ntComponentID fromJSComponentID(Handle<Value> value)\n{\n if (value->IsObject())\n {\n Handle<Object> object = value->ToObject();\n Handle<Function> prototype = Handle<Function>::Cast(object->GetPrototype());\n\n if (std::string(\"Athena.Entities.ComponentID\") == *String::AsciiValue(prototype->Get(String::New(\"__classname__\"))))\n {\n return tComponentID((tComponentType) object->Get(String::New(\"type\"))->ToNumber()->NumberValue(),\n *String::AsciiValue(object->Get(String::New(\"entity\"))),\n *String::AsciiValue(object->Get(String::New(\"component\"))));\n }\n }\n\n return tComponentID(COMP_NONE);\n}\n\n\/\/-----------------------------------------------------------------------\n\nHandle<Value> toJavaScript(const tComponentID& value)\n{\n HandleScope handle_scope;\n\n Local<Object> object = ScriptingManager::getSingletonPtr()->execute(\"new Athena.Entities.ComponentID('\" + value.toString() + \"');\")->ToObject();\n\n return handle_scope.Close(object);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ GrowthRegion.cpp\n\/\/ Implements the GrowthRegion class\n\n#include \"GrowthRegion.h\"\n\n#include \"QueryEngine.h\"\n#include \"SymbolicFunctionFactories.h\"\n#include \"InstModel.h\"\n#include \"Prototype.h\"\n#include \"CycException.h\"\n\n#include <vector>\n\nusing namespace std;\nusing namespace SupplyDemand;\nusing namespace ActionBuilding;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::GrowthRegion() {}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::~GrowthRegion() {}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initModuleMembers(QueryEngine* qe) {\n LOG(LEV_DEBUG2, \"greg\") << \"A Growth Region is being initialized\";\n \n string query = \"commodity\";\n\n int nCommodities = qe->nElementsMatchingQuery(query);\n\n \/\/ populate supply demand manager info for each commodity\n for (int i=0; i<nCommodities; i++) {\n addCommodityDemand(qe->queryElement(query,i));\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::addCommodityDemand(QueryEngine* qe) \n{\n \/\/ instantiate product\n string name = qe->getElementContent(\"name\");\n Commodity commodity(name);\n registerCommodity(commodity);\n\n \/\/ instantiate demand\n QueryEngine* demand = qe->queryElement(\"demand\");\n string type = demand->getElementContent(\"type\");\n string params = demand->getElementContent(\"parameters\");\n BasicFunctionFactory bff;\n FunctionPtr demand_function = bff.getFunctionPtr(type,params);\n\n \/\/ register the commodity and demand\n sdmanager_.registerCommodity(commodity,demand_function);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::enterSimulationAsModule() \n{\n for (int i = 0; i != nChildren(); i++) \n {\n Model* child = children(i); \n registerCommodityProducerManager(child);\n registerBuilder(child);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::handleTick(int time) \n{\n set<Commodity>::iterator it;\n for (it = commodities_.begin(); it != commodities_.end(); it++)\n {\n Commodity commodity = *it;\n double demand = sdmanager_.demand(commodity,time);\n double supply = sdmanager_.supply(commodity);\n double unmet_demand = demand - supply;\n\n LOG(LEV_INFO3,\"greg\") << \"GrowthRegion: \" << name() \n << \" at time: \" << time \n << \" has the following values regaring \"\n << \" commodity: \" << commodity.name();\n LOG(LEV_INFO3,\"greg\") << \" * demand = \" << demand;\n LOG(LEV_INFO3,\"greg\") << \" * supply = \" << supply;\n LOG(LEV_INFO3,\"greg\") << \" * unmet demand = \" << unmet_demand;\n \n if (unmet_demand > 0)\n {\n orderBuilds(commodity,unmet_demand);\n }\n }\n RegionModel::handleTick(time);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerCommodity(Commodity& commodity) \n{\n if (commodities_.find(commodity) != commodities_.end())\n {\n throw CycDoubleRegistrationException(\"A GrowthRegion (\"\n + name() + \" is trying to register a commodity twice.\");\n }\n else\n {\n commodities_.insert(commodity);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerCommodityProducerManager(Model* child)\n{\n CommodityProducerManager* cast = dynamic_cast<CommodityProducerManager*>(child);\n if (cast)\n {\n sdmanager_.registerProducerManager(cast);\n }\n} \n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerBuilder(Model* child)\n{\n Builder* cast = dynamic_cast<Builder*>(child);\n if (cast)\n {\n buildmanager_.registerBuilder(cast);\n }\n} \n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GrowthRegion::orderBuilds(Commodity& commodity, double unmet_demand)\n{\n vector<BuildOrder> orders = buildmanager_.makeBuildDecision(commodity,unmet_demand);\n \n LOG(LEV_INFO3,\"greg\") << \"The build orders have been determined. \" \n << orders.size() \n << \" different type(s) of prototypes will be built.\";\n\n for (int i = 0; i < orders.size(); i++)\n {\n BuildOrder order = orders.at(i);\n InstModel* instcast = dynamic_cast<InstModel*>(order.builder);\n Prototype* protocast = dynamic_cast<Prototype*>(order.producer);\n if(instcast && protocast)\n {\n LOG(LEV_INFO3,\"greg\") << \"A build order for \" << order.number\n << \" prototype(s) of type \" \n << dynamic_cast<Model*>(protocast)->name()\n << \" from builder \" << instcast->name()\n << \" is being placed.\";\n\n for (int j = 0; j < order.number; j++)\n {\n LOG(LEV_DEBUG3,\"greg\") << \"Ordering build number: \" << j+1; \n instcast->build(protocast);\n }\n }\n else\n {\n throw CycOverrideException(\"GrowthRegion has tried to incorrectly cast an already known entity.\");\n }\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nextern \"C\" Model* constructGrowthRegion() \n{\n return new GrowthRegion();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nextern \"C\" void destructGrowthRegion(Model* model) \n{\n delete model;\n}\n\n<commit_msg>more clarity in growth region logs<commit_after>\/\/ GrowthRegion.cpp\n\/\/ Implements the GrowthRegion class\n\n#include \"GrowthRegion.h\"\n\n#include \"QueryEngine.h\"\n#include \"SymbolicFunctionFactories.h\"\n#include \"InstModel.h\"\n#include \"Prototype.h\"\n#include \"CycException.h\"\n\n#include <vector>\n\nusing namespace std;\nusing namespace SupplyDemand;\nusing namespace ActionBuilding;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::GrowthRegion() {}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::~GrowthRegion() {}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initModuleMembers(QueryEngine* qe) {\n LOG(LEV_DEBUG2, \"greg\") << \"A Growth Region is being initialized\";\n \n string query = \"commodity\";\n\n int nCommodities = qe->nElementsMatchingQuery(query);\n\n \/\/ populate supply demand manager info for each commodity\n for (int i=0; i<nCommodities; i++) {\n addCommodityDemand(qe->queryElement(query,i));\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::addCommodityDemand(QueryEngine* qe) \n{\n \/\/ instantiate product\n string name = qe->getElementContent(\"name\");\n Commodity commodity(name);\n registerCommodity(commodity);\n\n \/\/ instantiate demand\n QueryEngine* demand = qe->queryElement(\"demand\");\n string type = demand->getElementContent(\"type\");\n string params = demand->getElementContent(\"parameters\");\n BasicFunctionFactory bff;\n FunctionPtr demand_function = bff.getFunctionPtr(type,params);\n\n \/\/ register the commodity and demand\n sdmanager_.registerCommodity(commodity,demand_function);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::enterSimulationAsModule() \n{\n for (int i = 0; i != nChildren(); i++) \n {\n Model* child = children(i); \n registerCommodityProducerManager(child);\n registerBuilder(child);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::handleTick(int time) \n{\n set<Commodity>::iterator it;\n for (it = commodities_.begin(); it != commodities_.end(); it++)\n {\n Commodity commodity = *it;\n double demand = sdmanager_.demand(commodity,time);\n double supply = sdmanager_.supply(commodity);\n double unmet_demand = demand - supply;\n\n LOG(LEV_INFO3,\"greg\") << \"GrowthRegion: \" << name() \n << \" at time: \" << time \n << \" has the following values regaring \"\n << \" commodity: \" << commodity.name();\n LOG(LEV_INFO3,\"greg\") << \" * demand = \" << demand;\n LOG(LEV_INFO3,\"greg\") << \" * supply = \" << supply;\n LOG(LEV_INFO3,\"greg\") << \" * unmet demand = \" << unmet_demand;\n \n if (unmet_demand > 0)\n {\n orderBuilds(commodity,unmet_demand);\n }\n }\n RegionModel::handleTick(time);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerCommodity(Commodity& commodity) \n{\n if (commodities_.find(commodity) != commodities_.end())\n {\n throw CycDoubleRegistrationException(\"A GrowthRegion (\"\n + name() + \" is trying to register a commodity twice.\");\n }\n else\n {\n commodities_.insert(commodity);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerCommodityProducerManager(Model* child)\n{\n CommodityProducerManager* cast = dynamic_cast<CommodityProducerManager*>(child);\n if (cast)\n {\n sdmanager_.registerProducerManager(cast);\n }\n} \n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::registerBuilder(Model* child)\n{\n Builder* cast = dynamic_cast<Builder*>(child);\n if (cast)\n {\n buildmanager_.registerBuilder(cast);\n }\n} \n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GrowthRegion::orderBuilds(Commodity& commodity, double unmet_demand)\n{\n vector<BuildOrder> orders = buildmanager_.makeBuildDecision(commodity,unmet_demand);\n \n LOG(LEV_INFO3,\"greg\") << \"The build orders have been determined. \" \n << orders.size() \n << \" different type(s) of prototypes will be built.\";\n\n for (int i = 0; i < orders.size(); i++)\n {\n BuildOrder order = orders.at(i);\n InstModel* instcast = dynamic_cast<InstModel*>(order.builder);\n Prototype* protocast = dynamic_cast<Prototype*>(order.producer);\n if(instcast && protocast)\n {\n LOG(LEV_INFO3,\"greg\") << \"A build order for \" << order.number\n << \" prototype(s) of type \" \n << dynamic_cast<Model*>(protocast)->name()\n << \" from builder \" << instcast->name()\n << \" is being placed.\";\n\n for (int j = 0; j < order.number; j++)\n {\n LOG(LEV_DEBUG2,\"greg\") << \"Ordering build number: \" << j+1; \n instcast->build(protocast);\n }\n }\n else\n {\n throw CycOverrideException(\"GrowthRegion has tried to incorrectly cast an already known entity.\");\n }\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nextern \"C\" Model* constructGrowthRegion() \n{\n return new GrowthRegion();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nextern \"C\" void destructGrowthRegion(Model* model) \n{\n delete model;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a simple interprocedural pass which walks the\n\/\/ call-graph, looking for functions which do not access or only read\n\/\/ non-local memory, and marking them readnone\/readonly. In addition,\n\/\/ it marks function arguments (of pointer type) 'nocapture' if a call\n\/\/ to the function does not create any copies of the pointer value that\n\/\/ outlive the call. This more or less means that the pointer is only\n\/\/ dereferenced, and not returned from the function or stored in a global.\n\/\/ This pass is implemented as a bottom-up traversal of the call-graph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"functionattrs\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/UniqueVector.h\"\n#include \"llvm\/Support\/InstIterator.h\"\nusing namespace llvm;\n\nSTATISTIC(NumReadNone, \"Number of functions marked readnone\");\nSTATISTIC(NumReadOnly, \"Number of functions marked readonly\");\nSTATISTIC(NumNoCapture, \"Number of arguments marked nocapture\");\nSTATISTIC(NumNoAlias, \"Number of function returns marked noalias\");\n\nnamespace {\n struct FunctionAttrs : public CallGraphSCCPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {\n initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());\n }\n\n \/\/ runOnSCC - Analyze the SCC, performing the transformation if possible.\n bool runOnSCC(CallGraphSCC &SCC);\n\n \/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\n bool AddReadAttrs(const CallGraphSCC &SCC);\n\n \/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\n bool AddNoCaptureAttrs(const CallGraphSCC &SCC);\n\n \/\/ IsFunctionMallocLike - Does this function allocate new memory?\n bool IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &) const;\n\n \/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\n bool AddNoAliasAttrs(const CallGraphSCC &SCC);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<AliasAnalysis>();\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n private:\n AliasAnalysis *AA;\n };\n}\n\nchar FunctionAttrs::ID = 0;\nINITIALIZE_PASS_BEGIN(FunctionAttrs, \"functionattrs\",\n \"Deduce function attributes\", false, false)\nINITIALIZE_AG_DEPENDENCY(CallGraph)\nINITIALIZE_PASS_END(FunctionAttrs, \"functionattrs\",\n \"Deduce function attributes\", false, false)\n\nPass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }\n\n\n\/\/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\nbool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n SCCNodes.insert((*I)->getFunction());\n\n \/\/ Check if any of the functions in the SCC read or write memory. If they\n \/\/ write memory then they can't be marked readnone or readonly.\n bool ReadsMemory = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - may write memory. Just give up.\n return false;\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden()) {\n if (!F->onlyReadsMemory())\n \/\/ May write memory. Just give up.\n return false;\n\n ReadsMemory = true;\n continue;\n }\n\n \/\/ Scan the function body for instructions that may read or write memory.\n for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {\n Instruction *I = &*II;\n\n \/\/ Some instructions can be ignored even if they read or write memory.\n \/\/ Detect these now, skipping to the next instruction if one is found.\n CallSite CS(cast<Value>(I));\n if (CS) {\n \/\/ Ignore calls to functions in the same SCC.\n if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))\n continue;\n switch (AA->getModRefBehavior(CS)) {\n case AliasAnalysis::DoesNotAccessMemory:\n \/\/ Ignore calls that don't access memory.\n continue;\n case AliasAnalysis::OnlyReadsMemory:\n \/\/ Handle calls that only read from memory.\n ReadsMemory = true;\n continue;\n case AliasAnalysis::AccessesArguments:\n \/\/ Check whether all pointer arguments point to local memory, and\n \/\/ ignore calls that only access local memory.\n for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();\n CI != CE; ++CI) {\n Value *Arg = *CI;\n if (Arg->getType()->isPointerTy()) {\n AliasAnalysis::Location Loc(Arg,\n AliasAnalysis::UnknownSize,\n I->getMetadata(LLVMContext::MD_tbaa));\n if (!AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n \/\/ Writes memory. Just give up.\n return false;\n }\n }\n \/\/ Only reads and writes local memory.\n continue;\n case AliasAnalysis::AccessesArgumentsReadonly:\n \/\/ Check whether all pointer arguments point to local memory, and\n \/\/ ignore calls that only access local memory.\n for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();\n CI != CE; ++CI) {\n Value *Arg = *CI;\n if (Arg->getType()->isPointerTy()) {\n AliasAnalysis::Location Loc(Arg,\n AliasAnalysis::UnknownSize,\n I->getMetadata(LLVMContext::MD_tbaa));\n if (!AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true)) {\n \/\/ Reads non-local memory.\n ReadsMemory = true;\n break;\n }\n }\n }\n \/\/ Only reads memory.\n continue;\n default:\n \/\/ Otherwise, be conservative.\n break;\n }\n } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {\n \/\/ Ignore non-volatile loads from local memory.\n if (!LI->isVolatile()) {\n AliasAnalysis::Location Loc(LI->getPointerOperand(),\n AA->getTypeStoreSize(LI->getType()),\n LI->getMetadata(LLVMContext::MD_tbaa));\n if (AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n continue;\n }\n } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {\n \/\/ Ignore non-volatile stores to local memory.\n if (!SI->isVolatile()) {\n const Type *StoredType = SI->getValueOperand()->getType();\n AliasAnalysis::Location Loc(SI->getPointerOperand(),\n AA->getTypeStoreSize(StoredType),\n SI->getMetadata(LLVMContext::MD_tbaa));\n if (AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n continue;\n }\n }\n\n \/\/ Any remaining instructions need to be taken seriously! Check if they\n \/\/ read or write memory.\n if (I->mayWriteToMemory())\n \/\/ Writes memory. Just give up.\n return false;\n\n \/\/ If this instruction may read memory, remember that.\n ReadsMemory |= I->mayReadFromMemory();\n }\n }\n\n \/\/ Success! Functions in this SCC do not access memory, or only read memory.\n \/\/ Give them the appropriate attribute.\n bool MadeChange = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n if (F->onlyReadsMemory() && ReadsMemory)\n \/\/ No change.\n continue;\n\n MadeChange = true;\n\n \/\/ Clear out any existing attributes.\n F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);\n\n \/\/ Add in the new attribute.\n F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);\n\n if (ReadsMemory)\n ++NumReadOnly;\n else\n ++NumReadNone;\n }\n\n return MadeChange;\n}\n\n\/\/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\nbool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {\n bool Changed = false;\n\n \/\/ Check each function in turn, determining which pointer arguments are not\n \/\/ captured.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n continue;\n\n for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)\n if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&\n !PointerMayBeCaptured(A, true, \/*StoreCaptures=*\/false)) {\n A->addAttr(Attribute::NoCapture);\n ++NumNoCapture;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\n\/\/\/ IsFunctionMallocLike - A function is malloc-like if it returns either null\n\/\/\/ or a pointer that doesn't alias any other pointer visible to the caller.\nbool FunctionAttrs::IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &SCCNodes) const {\n UniqueVector<Value *> FlowsToReturn;\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)\n if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))\n FlowsToReturn.insert(Ret->getReturnValue());\n\n for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {\n Value *RetVal = FlowsToReturn[i+1]; \/\/ UniqueVector[0] is reserved.\n\n if (Constant *C = dyn_cast<Constant>(RetVal)) {\n if (!C->isNullValue() && !isa<UndefValue>(C))\n return false;\n\n continue;\n }\n\n if (isa<Argument>(RetVal))\n return false;\n\n if (Instruction *RVI = dyn_cast<Instruction>(RetVal))\n switch (RVI->getOpcode()) {\n \/\/ Extend the analysis by looking upwards.\n case Instruction::BitCast:\n case Instruction::GetElementPtr:\n FlowsToReturn.insert(RVI->getOperand(0));\n continue;\n case Instruction::Select: {\n SelectInst *SI = cast<SelectInst>(RVI);\n FlowsToReturn.insert(SI->getTrueValue());\n FlowsToReturn.insert(SI->getFalseValue());\n continue;\n }\n case Instruction::PHI: {\n PHINode *PN = cast<PHINode>(RVI);\n for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n FlowsToReturn.insert(PN->getIncomingValue(i));\n continue;\n }\n\n \/\/ Check whether the pointer came from an allocation.\n case Instruction::Alloca:\n break;\n case Instruction::Call:\n case Instruction::Invoke: {\n CallSite CS(RVI);\n if (CS.paramHasAttr(0, Attribute::NoAlias))\n break;\n if (CS.getCalledFunction() &&\n SCCNodes.count(CS.getCalledFunction()))\n break;\n } \/\/ fall-through\n default:\n return false; \/\/ Did not come from an allocation.\n }\n\n if (PointerMayBeCaptured(RetVal, false, \/*StoreCaptures=*\/false))\n return false;\n }\n\n return true;\n}\n\n\/\/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\nbool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n SCCNodes.insert((*I)->getFunction());\n\n \/\/ Check each function in turn, determining which functions return noalias\n \/\/ pointers.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n return false;\n\n \/\/ Already noalias.\n if (F->doesNotAlias(0))\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime, so\n \/\/ treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n return false;\n\n \/\/ We annotate noalias return values, which are only applicable to \n \/\/ pointer types.\n if (!F->getReturnType()->isPointerTy())\n continue;\n\n if (!IsFunctionMallocLike(F, SCCNodes))\n return false;\n }\n\n bool MadeChange = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())\n continue;\n\n F->setDoesNotAlias(0);\n ++NumNoAlias;\n MadeChange = true;\n }\n\n return MadeChange;\n}\n\nbool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {\n AA = &getAnalysis<AliasAnalysis>();\n\n bool Changed = AddReadAttrs(SCC);\n Changed |= AddNoCaptureAttrs(SCC);\n Changed |= AddNoAliasAttrs(SCC);\n return Changed;\n}\n<commit_msg>Use the AliasAnalysis interface to determine how a Function accesses memory. This isn't a real improvement with present day AliasAnalysis implementations; it's mainly for consistency.<commit_after>\/\/===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a simple interprocedural pass which walks the\n\/\/ call-graph, looking for functions which do not access or only read\n\/\/ non-local memory, and marking them readnone\/readonly. In addition,\n\/\/ it marks function arguments (of pointer type) 'nocapture' if a call\n\/\/ to the function does not create any copies of the pointer value that\n\/\/ outlive the call. This more or less means that the pointer is only\n\/\/ dereferenced, and not returned from the function or stored in a global.\n\/\/ This pass is implemented as a bottom-up traversal of the call-graph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"functionattrs\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/UniqueVector.h\"\n#include \"llvm\/Support\/InstIterator.h\"\nusing namespace llvm;\n\nSTATISTIC(NumReadNone, \"Number of functions marked readnone\");\nSTATISTIC(NumReadOnly, \"Number of functions marked readonly\");\nSTATISTIC(NumNoCapture, \"Number of arguments marked nocapture\");\nSTATISTIC(NumNoAlias, \"Number of function returns marked noalias\");\n\nnamespace {\n struct FunctionAttrs : public CallGraphSCCPass {\n static char ID; \/\/ Pass identification, replacement for typeid\n FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {\n initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());\n }\n\n \/\/ runOnSCC - Analyze the SCC, performing the transformation if possible.\n bool runOnSCC(CallGraphSCC &SCC);\n\n \/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\n bool AddReadAttrs(const CallGraphSCC &SCC);\n\n \/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\n bool AddNoCaptureAttrs(const CallGraphSCC &SCC);\n\n \/\/ IsFunctionMallocLike - Does this function allocate new memory?\n bool IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &) const;\n\n \/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\n bool AddNoAliasAttrs(const CallGraphSCC &SCC);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<AliasAnalysis>();\n CallGraphSCCPass::getAnalysisUsage(AU);\n }\n\n private:\n AliasAnalysis *AA;\n };\n}\n\nchar FunctionAttrs::ID = 0;\nINITIALIZE_PASS_BEGIN(FunctionAttrs, \"functionattrs\",\n \"Deduce function attributes\", false, false)\nINITIALIZE_AG_DEPENDENCY(CallGraph)\nINITIALIZE_PASS_END(FunctionAttrs, \"functionattrs\",\n \"Deduce function attributes\", false, false)\n\nPass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }\n\n\n\/\/\/ AddReadAttrs - Deduce readonly\/readnone attributes for the SCC.\nbool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n SCCNodes.insert((*I)->getFunction());\n\n \/\/ Check if any of the functions in the SCC read or write memory. If they\n \/\/ write memory then they can't be marked readnone or readonly.\n bool ReadsMemory = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - may write memory. Just give up.\n return false;\n\n AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);\n if (MRB == AliasAnalysis::DoesNotAccessMemory)\n \/\/ Already perfect!\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden()) {\n if (!AliasAnalysis::onlyReadsMemory(MRB))\n \/\/ May write memory. Just give up.\n return false;\n\n ReadsMemory = true;\n continue;\n }\n\n \/\/ Scan the function body for instructions that may read or write memory.\n for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {\n Instruction *I = &*II;\n\n \/\/ Some instructions can be ignored even if they read or write memory.\n \/\/ Detect these now, skipping to the next instruction if one is found.\n CallSite CS(cast<Value>(I));\n if (CS) {\n \/\/ Ignore calls to functions in the same SCC.\n if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))\n continue;\n switch (AA->getModRefBehavior(CS)) {\n case AliasAnalysis::DoesNotAccessMemory:\n \/\/ Ignore calls that don't access memory.\n continue;\n case AliasAnalysis::OnlyReadsMemory:\n \/\/ Handle calls that only read from memory.\n ReadsMemory = true;\n continue;\n case AliasAnalysis::AccessesArguments:\n \/\/ Check whether all pointer arguments point to local memory, and\n \/\/ ignore calls that only access local memory.\n for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();\n CI != CE; ++CI) {\n Value *Arg = *CI;\n if (Arg->getType()->isPointerTy()) {\n AliasAnalysis::Location Loc(Arg,\n AliasAnalysis::UnknownSize,\n I->getMetadata(LLVMContext::MD_tbaa));\n if (!AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n \/\/ Writes memory. Just give up.\n return false;\n }\n }\n \/\/ Only reads and writes local memory.\n continue;\n case AliasAnalysis::AccessesArgumentsReadonly:\n \/\/ Check whether all pointer arguments point to local memory, and\n \/\/ ignore calls that only access local memory.\n for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();\n CI != CE; ++CI) {\n Value *Arg = *CI;\n if (Arg->getType()->isPointerTy()) {\n AliasAnalysis::Location Loc(Arg,\n AliasAnalysis::UnknownSize,\n I->getMetadata(LLVMContext::MD_tbaa));\n if (!AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true)) {\n \/\/ Reads non-local memory.\n ReadsMemory = true;\n break;\n }\n }\n }\n \/\/ Only reads memory.\n continue;\n default:\n \/\/ Otherwise, be conservative.\n break;\n }\n } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {\n \/\/ Ignore non-volatile loads from local memory.\n if (!LI->isVolatile()) {\n AliasAnalysis::Location Loc(LI->getPointerOperand(),\n AA->getTypeStoreSize(LI->getType()),\n LI->getMetadata(LLVMContext::MD_tbaa));\n if (AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n continue;\n }\n } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {\n \/\/ Ignore non-volatile stores to local memory.\n if (!SI->isVolatile()) {\n const Type *StoredType = SI->getValueOperand()->getType();\n AliasAnalysis::Location Loc(SI->getPointerOperand(),\n AA->getTypeStoreSize(StoredType),\n SI->getMetadata(LLVMContext::MD_tbaa));\n if (AA->pointsToConstantMemory(Loc, \/*OrLocal=*\/true))\n continue;\n }\n }\n\n \/\/ Any remaining instructions need to be taken seriously! Check if they\n \/\/ read or write memory.\n if (I->mayWriteToMemory())\n \/\/ Writes memory. Just give up.\n return false;\n\n \/\/ If this instruction may read memory, remember that.\n ReadsMemory |= I->mayReadFromMemory();\n }\n }\n\n \/\/ Success! Functions in this SCC do not access memory, or only read memory.\n \/\/ Give them the appropriate attribute.\n bool MadeChange = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F->doesNotAccessMemory())\n \/\/ Already perfect!\n continue;\n\n if (F->onlyReadsMemory() && ReadsMemory)\n \/\/ No change.\n continue;\n\n MadeChange = true;\n\n \/\/ Clear out any existing attributes.\n F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);\n\n \/\/ Add in the new attribute.\n F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);\n\n if (ReadsMemory)\n ++NumReadOnly;\n else\n ++NumReadNone;\n }\n\n return MadeChange;\n}\n\n\/\/\/ AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.\nbool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {\n bool Changed = false;\n\n \/\/ Check each function in turn, determining which pointer arguments are not\n \/\/ captured.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime with\n \/\/ something that writes memory, so treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n continue;\n\n for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)\n if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&\n !PointerMayBeCaptured(A, true, \/*StoreCaptures=*\/false)) {\n A->addAttr(Attribute::NoCapture);\n ++NumNoCapture;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\n\/\/\/ IsFunctionMallocLike - A function is malloc-like if it returns either null\n\/\/\/ or a pointer that doesn't alias any other pointer visible to the caller.\nbool FunctionAttrs::IsFunctionMallocLike(Function *F,\n SmallPtrSet<Function*, 8> &SCCNodes) const {\n UniqueVector<Value *> FlowsToReturn;\n for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)\n if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))\n FlowsToReturn.insert(Ret->getReturnValue());\n\n for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {\n Value *RetVal = FlowsToReturn[i+1]; \/\/ UniqueVector[0] is reserved.\n\n if (Constant *C = dyn_cast<Constant>(RetVal)) {\n if (!C->isNullValue() && !isa<UndefValue>(C))\n return false;\n\n continue;\n }\n\n if (isa<Argument>(RetVal))\n return false;\n\n if (Instruction *RVI = dyn_cast<Instruction>(RetVal))\n switch (RVI->getOpcode()) {\n \/\/ Extend the analysis by looking upwards.\n case Instruction::BitCast:\n case Instruction::GetElementPtr:\n FlowsToReturn.insert(RVI->getOperand(0));\n continue;\n case Instruction::Select: {\n SelectInst *SI = cast<SelectInst>(RVI);\n FlowsToReturn.insert(SI->getTrueValue());\n FlowsToReturn.insert(SI->getFalseValue());\n continue;\n }\n case Instruction::PHI: {\n PHINode *PN = cast<PHINode>(RVI);\n for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n FlowsToReturn.insert(PN->getIncomingValue(i));\n continue;\n }\n\n \/\/ Check whether the pointer came from an allocation.\n case Instruction::Alloca:\n break;\n case Instruction::Call:\n case Instruction::Invoke: {\n CallSite CS(RVI);\n if (CS.paramHasAttr(0, Attribute::NoAlias))\n break;\n if (CS.getCalledFunction() &&\n SCCNodes.count(CS.getCalledFunction()))\n break;\n } \/\/ fall-through\n default:\n return false; \/\/ Did not come from an allocation.\n }\n\n if (PointerMayBeCaptured(RetVal, false, \/*StoreCaptures=*\/false))\n return false;\n }\n\n return true;\n}\n\n\/\/\/ AddNoAliasAttrs - Deduce noalias attributes for the SCC.\nbool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {\n SmallPtrSet<Function*, 8> SCCNodes;\n\n \/\/ Fill SCCNodes with the elements of the SCC. Used for quickly\n \/\/ looking up whether a given CallGraphNode is in this SCC.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)\n SCCNodes.insert((*I)->getFunction());\n\n \/\/ Check each function in turn, determining which functions return noalias\n \/\/ pointers.\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n\n if (F == 0)\n \/\/ External node - skip it;\n return false;\n\n \/\/ Already noalias.\n if (F->doesNotAlias(0))\n continue;\n\n \/\/ Definitions with weak linkage may be overridden at linktime, so\n \/\/ treat them like declarations.\n if (F->isDeclaration() || F->mayBeOverridden())\n return false;\n\n \/\/ We annotate noalias return values, which are only applicable to \n \/\/ pointer types.\n if (!F->getReturnType()->isPointerTy())\n continue;\n\n if (!IsFunctionMallocLike(F, SCCNodes))\n return false;\n }\n\n bool MadeChange = false;\n for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {\n Function *F = (*I)->getFunction();\n if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())\n continue;\n\n F->setDoesNotAlias(0);\n ++NumNoAlias;\n MadeChange = true;\n }\n\n return MadeChange;\n}\n\nbool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {\n AA = &getAnalysis<AliasAnalysis>();\n\n bool Changed = AddReadAttrs(SCC);\n Changed |= AddNoCaptureAttrs(SCC);\n Changed |= AddNoAliasAttrs(SCC);\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <cassert>\n\n#include \"SearchCmd.h\"\n#include \"StringUtils.h\"\n\n#include \"MeshPart.h\"\n#include \"AnnLocator.h\"\n\n#include \"Reader.h\"\n#include \"Timer.h\"\n\n#include \"Writer.h\"\n#include \"HdfWriter.h\"\n\n\nusing namespace std;\nusing namespace cigma;\n\n\/\/ ---------------------------------------------------------------------------\n\nSearchCmd::SearchCmd()\n{\n name = \"search\";\n\n points = 0;\n meshPart = 0;\n coordsField = 0;\n}\n\nSearchCmd::~SearchCmd()\n{\n \/\/ XXX\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid SearchCmd::setupOptions(AnyOption *opt)\n{\n\n assert(opt != 0);\n\n \/* setup usage *\/\n opt->addUsage(\"Usage:\");\n opt->addUsage(\" cigma search [options]\");\n opt->addUsage(\" --points Path to search points\");\n opt->addUsage(\" --mesh Path to mesh\");\n opt->addUsage(\" --output Path to output dataset\");\n\n \/* setup flags and options *\/\n opt->setFlag(\"help\", 'h');\n opt->setFlag(\"debug\");\n\n \/\/ options for mesh\n opt->setOption(\"mesh\");\n opt->setOption(\"mesh-coordinates\");\n opt->setOption(\"mesh-connectivity\");\n\n \/\/ options for points\n opt->setOption(\"points\");\n\n \/\/ options for output\n opt->setOption(\"output\",'o');\n\n \/\/ other options\n opt->setFlag(\"verbose\",'v');\n}\n\n\nvoid SearchCmd::configure(AnyOption *opt)\n{\n string inputstr;\n char *in;\n\n \/* Check if --verbose was enabled *\/\n\n verbose = opt->getFlag(\"verbose\");\n\n \/* Determine the output option *\/\n in = opt->getValue(\"output\");\n if (in != 0)\n {\n inputstr = in;\n }\n string outputLoc, outputExt;\n parse_dataset_path(inputstr, outputLoc, outputFile, outputExt);\n writer = NewWriter(outputExt.c_str());\n if (writer->getType() != Writer::HDF_WRITER)\n {\n cerr << \"search: Please specify a target HDF5 file in --output option\" << endl;\n exit(1);\n }\n\n\n \/* Gather up the expected command line arguments *\/\n\n meshPartReader.load_args(opt, \"mesh\");\n pointsReader.load_args(opt, \"points\");\n\n meshPartReader.validate_args(\"search\");\n pointsReader.validate_args(\"search\");\n\n \/* load mesh into memory *\/\n meshPartReader.load_mesh();\n pointsReader.load_points();\n\n points = pointsReader.points;\n meshPart = meshPartReader.meshPart;\n\n if (meshPart == 0)\n {\n cerr << \"search: Could not load mesh!\" << endl;\n exit(1);\n }\n\n if (points == 0)\n {\n cerr << \"search: Could not load points!\" << endl;\n exit(1);\n }\n\n coordsField = new FE_Field();\n coordsField->dim = meshPart->nsd;\n coordsField->rank = meshPart->nsd;\n coordsField->meshPart = meshPart;\n coordsField->meshPart->set_cell();\n\n if ((coordsField->meshPart->nsd == 3) && (coordsField->meshPart->nno > 1000))\n {\n AnnLocator *locator = new AnnLocator();\n locator->nnk = 10;\n coordsField->meshPart->set_locator(locator);\n }\n\n return;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nint SearchCmd::run()\n{\n\n assert(points != 0);\n assert(meshPart != 0);\n\n\n int i,j;\n int e;\n const int nsd = meshPart->nsd;\n const int nel = meshPart->nel;\n const int npts = points->n_points();\n\n int *cellPointCount = new int[nel]; \/\/ how many points fall on given cell?\n int *pointCellCount = new int[npts]; \/\/ how many cells were searched for a given point?\n\n for (e = 0; e < nel; e++)\n {\n cellPointCount[e] = 0;\n }\n\n for (i = 0; i < npts; i++)\n {\n pointCellCount[i] = 0;\n }\n\n\n time_t t0,t1;\n time(&t0);\n\n int hitCount = 0;\n\n if (meshPart->locator != 0)\n {\n for (i = 0; i < points->n_points(); i++)\n {\n \/\/double *pt = (*points)[i];\n double pt[3] = {0,0,0};\n for (j = 0; j < points->n_dim(); j++)\n {\n pt[j] = (*points)(i,j);\n }\n\n \/\/bool found = meshPart->find_cell(pt, &parentCell);\n\n bool found = false;\n\n meshPart->locator->search(pt);\n for (j = 0; j < meshPart->locator->n_idx(); j++)\n {\n e = meshPart->locator->idx(j);\n if (e < 0)\n {\n continue;\n }\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = j+1;\n break;\n }\n }\n \/\/*\n if (!found)\n {\n hitCount++;\n \/\/cout << i << endl;\n for (e = 0; e < nel; e++)\n {\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = e+1;\n break;\n }\n }\n assert(found);\n } \/\/ *\/\n }\n cout << \"Locator missed \" << hitCount << \" points \"\n << \"(\" << ((100.0*hitCount)\/npts) << \"%)\"\n << endl;\n }\n else\n {\n for (i = 0; i < points->n_points(); i++)\n {\n double *pt = (*points)[i];\n bool found = false;\n for (e = 0; e < nel; e++)\n {\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = e+1;\n break;\n }\n }\n }\n }\n\n time(&t1);\n double total_time = t1 - t0;\n cout << \"Total time = \" << total_time << endl;\n\n\n int ierr;\n\n HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer);\n\n ierr = hdfWriter->open(outputFile.c_str());\n if (ierr < 0)\n {\n cerr << \"search: Could not open output file \" << outputFile << endl;\n exit(1);\n }\n\n string loc;\n\n loc = \"\/CellPointCount\";\n ierr = hdfWriter->write_int_dataset(loc.c_str(), cellPointCount, nel, 1);\n if (ierr < 0)\n {\n cerr << \"search: Could not write dataset \" << loc << endl;\n exit(1);\n }\n\n loc = \"\/PointCellCount\";\n ierr = hdfWriter->write_int_dataset(loc.c_str(), pointCellCount, npts, 1);\n if (ierr < 0)\n {\n cerr << \"search: Could not write dataset \" << loc << endl;\n exit(1);\n }\n\n ierr = hdfWriter->close();\n\n\n delete [] cellPointCount;\n delete [] pointCellCount;\n\n\n return 0;\n}\n\n\/\/ ---------------------------------------------------------------------------\n<commit_msg>Use Locator::search_point() in SearchCmd<commit_after>#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include <cassert>\n\n#include \"SearchCmd.h\"\n#include \"StringUtils.h\"\n\n#include \"MeshPart.h\"\n#include \"AnnLocator.h\"\n\n#include \"Reader.h\"\n#include \"Timer.h\"\n\n#include \"Writer.h\"\n#include \"HdfWriter.h\"\n\n\nusing namespace std;\nusing namespace cigma;\n\n\/\/ ---------------------------------------------------------------------------\n\nSearchCmd::SearchCmd()\n{\n name = \"search\";\n\n points = 0;\n meshPart = 0;\n coordsField = 0;\n}\n\nSearchCmd::~SearchCmd()\n{\n \/\/ XXX\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid SearchCmd::setupOptions(AnyOption *opt)\n{\n\n assert(opt != 0);\n\n \/* setup usage *\/\n opt->addUsage(\"Usage:\");\n opt->addUsage(\" cigma search [options]\");\n opt->addUsage(\" --points Path to search points\");\n opt->addUsage(\" --mesh Path to mesh\");\n opt->addUsage(\" --output Path to output dataset\");\n\n \/* setup flags and options *\/\n opt->setFlag(\"help\", 'h');\n opt->setFlag(\"debug\");\n\n \/\/ options for mesh\n opt->setOption(\"mesh\");\n opt->setOption(\"mesh-coordinates\");\n opt->setOption(\"mesh-connectivity\");\n\n \/\/ options for points\n opt->setOption(\"points\");\n\n \/\/ options for output\n opt->setOption(\"output\",'o');\n\n \/\/ other options\n opt->setFlag(\"verbose\",'v');\n}\n\n\nvoid SearchCmd::configure(AnyOption *opt)\n{\n string inputstr;\n char *in;\n\n \/* Check if --verbose was enabled *\/\n\n verbose = opt->getFlag(\"verbose\");\n\n \/* Determine the output option *\/\n in = opt->getValue(\"output\");\n if (in != 0)\n {\n inputstr = in;\n }\n string outputLoc, outputExt;\n parse_dataset_path(inputstr, outputLoc, outputFile, outputExt);\n writer = NewWriter(outputExt.c_str());\n if (writer->getType() != Writer::HDF_WRITER)\n {\n cerr << \"search: Please specify a target HDF5 file in --output option\" << endl;\n exit(1);\n }\n\n\n \/* Gather up the expected command line arguments *\/\n\n meshPartReader.load_args(opt, \"mesh\");\n pointsReader.load_args(opt, \"points\");\n\n meshPartReader.validate_args(\"search\");\n pointsReader.validate_args(\"search\");\n\n \/* load mesh into memory *\/\n meshPartReader.load_mesh();\n pointsReader.load_points();\n\n points = pointsReader.points;\n meshPart = meshPartReader.meshPart;\n\n if (meshPart == 0)\n {\n cerr << \"search: Could not load mesh!\" << endl;\n exit(1);\n }\n\n if (points == 0)\n {\n cerr << \"search: Could not load points!\" << endl;\n exit(1);\n }\n\n coordsField = new FE_Field();\n coordsField->dim = meshPart->nsd;\n coordsField->rank = meshPart->nsd;\n coordsField->meshPart = meshPart;\n coordsField->meshPart->set_cell();\n\n if ((coordsField->meshPart->nsd == 3) && (coordsField->meshPart->nno > 1000))\n {\n AnnLocator *locator = new AnnLocator();\n locator->nnk = 10;\n coordsField->meshPart->set_locator(locator);\n }\n\n return;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nint SearchCmd::run()\n{\n\n assert(points != 0);\n assert(meshPart != 0);\n\n\n int i,j;\n int e;\n const int nsd = meshPart->nsd;\n const int nel = meshPart->nel;\n const int npts = points->n_points();\n\n int *cellPointCount = new int[nel]; \/\/ how many points fall on given cell?\n int *pointCellCount = new int[npts]; \/\/ how many cells were searched for a given point?\n\n for (e = 0; e < nel; e++)\n {\n cellPointCount[e] = 0;\n }\n\n for (i = 0; i < npts; i++)\n {\n pointCellCount[i] = 0;\n }\n\n\n time_t t0,t1;\n time(&t0);\n\n int hitCount = 0;\n\n if (meshPart->locator != 0)\n {\n for (i = 0; i < points->n_points(); i++)\n {\n \/\/double *pt = (*points)[i];\n double pt[3] = {0,0,0};\n for (j = 0; j < points->n_dim(); j++)\n {\n pt[j] = (*points)(i,j);\n }\n\n \/\/bool found = meshPart->find_cell(pt, &parentCell);\n\n bool found = false;\n\n meshPart->locator->search_point(pt);\n for (j = 0; j < meshPart->locator->n_idx(); j++)\n {\n e = meshPart->locator->idx(j);\n if (e < 0)\n {\n continue;\n }\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = j+1;\n break;\n }\n }\n \/\/*\n if (!found)\n {\n hitCount++;\n \/\/cout << i << endl;\n for (e = 0; e < nel; e++)\n {\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = e+1;\n break;\n }\n }\n assert(found);\n } \/\/ *\/\n }\n cout << \"Locator missed \" << hitCount << \" points \"\n << \"(\" << ((100.0*hitCount)\/npts) << \"%)\"\n << endl;\n }\n else\n {\n for (i = 0; i < points->n_points(); i++)\n {\n double *pt = (*points)[i];\n bool found = false;\n for (e = 0; e < nel; e++)\n {\n meshPart->select_cell(e);\n if (meshPart->cell->global_interior(pt))\n {\n found = true;\n cellPointCount[e]++;\n pointCellCount[i] = e+1;\n break;\n }\n }\n }\n }\n\n time(&t1);\n double total_time = t1 - t0;\n cout << \"Total time = \" << total_time << endl;\n\n\n int ierr;\n\n HdfWriter *hdfWriter = static_cast<HdfWriter*>(writer);\n\n ierr = hdfWriter->open(outputFile.c_str());\n if (ierr < 0)\n {\n cerr << \"search: Could not open output file \" << outputFile << endl;\n exit(1);\n }\n\n string loc;\n\n loc = \"\/CellPointCount\";\n ierr = hdfWriter->write_int_dataset(loc.c_str(), cellPointCount, nel, 1);\n if (ierr < 0)\n {\n cerr << \"search: Could not write dataset \" << loc << endl;\n exit(1);\n }\n\n loc = \"\/PointCellCount\";\n ierr = hdfWriter->write_int_dataset(loc.c_str(), pointCellCount, npts, 1);\n if (ierr < 0)\n {\n cerr << \"search: Could not write dataset \" << loc << endl;\n exit(1);\n }\n\n ierr = hdfWriter->close();\n\n\n delete [] cellPointCount;\n delete [] pointCellCount;\n\n\n return 0;\n}\n\n\/\/ ---------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <visionaray\/math\/math.h>\n\n#include <gtest\/gtest.h>\n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test routines for simd::gather()\n\/\/\n\/\/ Those tests should also be performed in AVX compilation mode (not AVX2)!\n\/\/ simd::gather() can make use of dedicated AVX2 intrinsics in certain cases.\n\/\/\n\/\/\n\/\/-------------------------------------------------------------------------------------------------\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Template to test gather with unorm<N> array\n\/\/\n\ntemplate <unsigned Bits>\nstatic void test_gather_unorm()\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) unorm<Bits> arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = i;\n }\n\n\n \/\/ test float4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::float4 res4 = gather(arr, index4);\n\n EXPECT_TRUE( simd::get<0>(res4) == static_cast<float>(unorm<Bits>( 0)) );\n EXPECT_TRUE( simd::get<1>(res4) == static_cast<float>(unorm<Bits>( 2)) );\n EXPECT_TRUE( simd::get<2>(res4) == static_cast<float>(unorm<Bits>( 4)) );\n EXPECT_TRUE( simd::get<3>(res4) == static_cast<float>(unorm<Bits>( 6)) );\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test float8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::float8 res8 = gather(arr, index8);\n\n EXPECT_TRUE( simd::get<0>(res8) == static_cast<float>(unorm<Bits>( 0)) );\n EXPECT_TRUE( simd::get<1>(res8) == static_cast<float>(unorm<Bits>( 2)) );\n EXPECT_TRUE( simd::get<2>(res8) == static_cast<float>(unorm<Bits>( 4)) );\n EXPECT_TRUE( simd::get<3>(res8) == static_cast<float>(unorm<Bits>( 6)) );\n EXPECT_TRUE( simd::get<4>(res8) == static_cast<float>(unorm<Bits>( 8)) );\n EXPECT_TRUE( simd::get<5>(res8) == static_cast<float>(unorm<Bits>(10)) );\n EXPECT_TRUE( simd::get<6>(res8) == static_cast<float>(unorm<Bits>(12)) );\n EXPECT_TRUE( simd::get<7>(res8) == static_cast<float>(unorm<Bits>(14)) );\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with 8-bit, 16-bit, and 32-bit unorms\n\/\/\n\nTEST(SIMD, GatherUnorm)\n{\n test_gather_unorm< 8>();\n test_gather_unorm<16>();\n test_gather_unorm<32>();\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with floats\n\/\/\n\nTEST(SIMD, GatherFloat)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) float arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = static_cast<float>(i);\n }\n\n\n \/\/ test float4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::float4 res4 = gather(arr, index4);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res4), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4), 4.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4), 6.0f);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test float8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::float8 res8 = gather(arr, index8);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res8), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8), 4.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8), 6.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8), 12.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8), 14.0f);\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with integers\n\/\/\n\nTEST(SIMD, GatherInt)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) int arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = i;\n }\n\n\n \/\/ test int4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::int4 res4 = gather(arr, index4);\n\n EXPECT_TRUE(simd::get<0>(res4) == 0);\n EXPECT_TRUE(simd::get<1>(res4) == 2);\n EXPECT_TRUE(simd::get<2>(res4) == 4);\n EXPECT_TRUE(simd::get<3>(res4) == 6);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test int8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::int8 res8 = gather(arr, index8);\n\n EXPECT_TRUE(simd::get<0>(res8) == 0);\n EXPECT_TRUE(simd::get<1>(res8) == 2);\n EXPECT_TRUE(simd::get<2>(res8) == 4);\n EXPECT_TRUE(simd::get<3>(res8) == 6);\n EXPECT_TRUE(simd::get<4>(res8) == 8);\n EXPECT_TRUE(simd::get<5>(res8) == 10);\n EXPECT_TRUE(simd::get<6>(res8) == 12);\n EXPECT_TRUE(simd::get<7>(res8) == 14);\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with vec4's\n\/\/\n\nTEST(SIMD, GatherVec4)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) vec4 arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = vec4(\n static_cast<float>(i * 4),\n static_cast<float>(i * 4 + 1),\n static_cast<float>(i * 4 + 2),\n static_cast<float>(i * 4 + 3)\n );\n\n }\n\n\n \/\/ test vector<4, float4>\n\n simd::int4 index4(0, 2, 4, 6);\n vector<4, simd::float4> res4 = gather(arr, index4);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res4.x), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.y), 1.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.z), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.w), 3.0f);\n\n EXPECT_FLOAT_EQ(simd::get<1>(res4.x), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.y), 9.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.z), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.w), 11.0f);\n\n EXPECT_FLOAT_EQ(simd::get<2>(res4.x), 16.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.y), 17.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.z), 18.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.w), 19.0f);\n\n EXPECT_FLOAT_EQ(simd::get<3>(res4.x), 24.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.y), 25.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.z), 26.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.w), 27.0f);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test vector<4, float8>\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n vector<4, simd::float8> res8 = gather(arr, index8);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res8.x), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.y), 1.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.z), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.w), 3.0f);\n\n EXPECT_FLOAT_EQ(simd::get<1>(res8.x), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.y), 9.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.z), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.w), 11.0f);\n\n EXPECT_FLOAT_EQ(simd::get<2>(res8.x), 16.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.y), 17.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.z), 18.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.w), 19.0f);\n\n EXPECT_FLOAT_EQ(simd::get<3>(res8.x), 24.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.y), 25.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.z), 26.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.w), 27.0f);\n\n EXPECT_FLOAT_EQ(simd::get<4>(res8.x), 32.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.y), 33.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.z), 34.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.w), 35.0f);\n\n EXPECT_FLOAT_EQ(simd::get<5>(res8.x), 40.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.y), 41.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.z), 42.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.w), 43.0f);\n\n EXPECT_FLOAT_EQ(simd::get<6>(res8.x), 48.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.y), 49.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.z), 50.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.w), 51.0f);\n\n EXPECT_FLOAT_EQ(simd::get<7>(res8.x), 56.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.y), 57.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.z), 58.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.w), 59.0f);\n\n#endif\n\n}\n<commit_msg>More unit tests for simd::gather()<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <visionaray\/math\/math.h>\n\n#include <gtest\/gtest.h>\n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test routines for simd::gather()\n\/\/\n\/\/ Those tests should also be performed in AVX compilation mode (not AVX2)!\n\/\/ simd::gather() can make use of dedicated AVX2 intrinsics in certain cases.\n\/\/\n\/\/\n\/\/-------------------------------------------------------------------------------------------------\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Template to test gather with unorm<N> array\n\/\/\n\ntemplate <unsigned Bits>\nstatic void test_gather_unorm()\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) unorm<Bits> arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = i;\n }\n\n\n \/\/ test float4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::float4 res4 = gather(arr, index4);\n\n EXPECT_TRUE( simd::get<0>(res4) == static_cast<float>(unorm<Bits>( 0)) );\n EXPECT_TRUE( simd::get<1>(res4) == static_cast<float>(unorm<Bits>( 2)) );\n EXPECT_TRUE( simd::get<2>(res4) == static_cast<float>(unorm<Bits>( 4)) );\n EXPECT_TRUE( simd::get<3>(res4) == static_cast<float>(unorm<Bits>( 6)) );\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test float8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::float8 res8 = gather(arr, index8);\n\n EXPECT_TRUE( simd::get<0>(res8) == static_cast<float>(unorm<Bits>( 0)) );\n EXPECT_TRUE( simd::get<1>(res8) == static_cast<float>(unorm<Bits>( 2)) );\n EXPECT_TRUE( simd::get<2>(res8) == static_cast<float>(unorm<Bits>( 4)) );\n EXPECT_TRUE( simd::get<3>(res8) == static_cast<float>(unorm<Bits>( 6)) );\n EXPECT_TRUE( simd::get<4>(res8) == static_cast<float>(unorm<Bits>( 8)) );\n EXPECT_TRUE( simd::get<5>(res8) == static_cast<float>(unorm<Bits>(10)) );\n EXPECT_TRUE( simd::get<6>(res8) == static_cast<float>(unorm<Bits>(12)) );\n EXPECT_TRUE( simd::get<7>(res8) == static_cast<float>(unorm<Bits>(14)) );\n\n#endif\n\n}\n\n\ntemplate <size_t Dim, unsigned Bits>\nstatic void test_gather_vector_unorm()\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) vector<Dim, unorm<Bits>> arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n for (size_t d = 0; d < Dim; ++d)\n {\n arr[i][d] = (i * Dim + d) \/ static_cast<float>(Dim * 16);\n }\n }\n\n\n \/\/ test vector<Dim, float4>\n\n simd::int4 index4(0, 2, 4, 6);\n vector<Dim, simd::float4> res4 = gather(arr, index4);\n\n for (size_t d = 0; d < Dim; ++d)\n {\n simd::float4 f = res4[d];\n\n unorm<Bits> u0( ( 0 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u1( ( 2 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u2( ( 4 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u3( ( 6 * Dim + d) \/ static_cast<float>(Dim * 16) );\n\n EXPECT_FLOAT_EQ( simd::get<0>(f), static_cast<float>(u0) );\n EXPECT_FLOAT_EQ( simd::get<1>(f), static_cast<float>(u1) );\n EXPECT_FLOAT_EQ( simd::get<2>(f), static_cast<float>(u2) );\n EXPECT_FLOAT_EQ( simd::get<3>(f), static_cast<float>(u3) );\n }\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test vector<Dim, float8>\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n vector<Dim, simd::float8> res8 = gather(arr, index8);\n\n for (size_t d = 0; d < Dim; ++d)\n {\n simd::float8 f = res8[d];\n\n unorm<Bits> u0( ( 0 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u1( ( 2 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u2( ( 4 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u3( ( 6 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u4( ( 8 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u5( (10 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u6( (12 * Dim + d) \/ static_cast<float>(Dim * 16) );\n unorm<Bits> u7( (14 * Dim + d) \/ static_cast<float>(Dim * 16) );\n\n EXPECT_FLOAT_EQ( simd::get<0>(f), static_cast<float>(u0) );\n EXPECT_FLOAT_EQ( simd::get<1>(f), static_cast<float>(u1) );\n EXPECT_FLOAT_EQ( simd::get<2>(f), static_cast<float>(u2) );\n EXPECT_FLOAT_EQ( simd::get<3>(f), static_cast<float>(u3) );\n EXPECT_FLOAT_EQ( simd::get<4>(f), static_cast<float>(u4) );\n EXPECT_FLOAT_EQ( simd::get<5>(f), static_cast<float>(u5) );\n EXPECT_FLOAT_EQ( simd::get<6>(f), static_cast<float>(u6) );\n EXPECT_FLOAT_EQ( simd::get<7>(f), static_cast<float>(u7) );\n }\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with 8-bit, 16-bit, and 32-bit unorms\n\/\/\n\nTEST(SIMD, GatherUnorm)\n{\n test_gather_unorm< 8>();\n test_gather_unorm<16>();\n test_gather_unorm<32>();\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with floats\n\/\/\n\nTEST(SIMD, GatherFloat)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) float arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = static_cast<float>(i);\n }\n\n\n \/\/ test float4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::float4 res4 = gather(arr, index4);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res4), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4), 4.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4), 6.0f);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test float8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::float8 res8 = gather(arr, index8);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res8), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8), 4.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8), 6.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8), 12.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8), 14.0f);\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with integers\n\/\/\n\nTEST(SIMD, GatherInt)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) int arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = i;\n }\n\n\n \/\/ test int4\n\n simd::int4 index4(0, 2, 4, 6);\n simd::int4 res4 = gather(arr, index4);\n\n EXPECT_TRUE(simd::get<0>(res4) == 0);\n EXPECT_TRUE(simd::get<1>(res4) == 2);\n EXPECT_TRUE(simd::get<2>(res4) == 4);\n EXPECT_TRUE(simd::get<3>(res4) == 6);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test int8\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n simd::int8 res8 = gather(arr, index8);\n\n EXPECT_TRUE(simd::get<0>(res8) == 0);\n EXPECT_TRUE(simd::get<1>(res8) == 2);\n EXPECT_TRUE(simd::get<2>(res8) == 4);\n EXPECT_TRUE(simd::get<3>(res8) == 6);\n EXPECT_TRUE(simd::get<4>(res8) == 8);\n EXPECT_TRUE(simd::get<5>(res8) == 10);\n EXPECT_TRUE(simd::get<6>(res8) == 12);\n EXPECT_TRUE(simd::get<7>(res8) == 14);\n\n#endif\n\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with unorm vectors\n\/\/\n\nTEST(SIMD, GatherVecNUnorm)\n{\n test_gather_vector_unorm<2, 8>();\n test_gather_vector_unorm<3, 8>();\n test_gather_vector_unorm<4, 8>();\n\n test_gather_vector_unorm<2, 16>();\n test_gather_vector_unorm<3, 16>();\n test_gather_vector_unorm<4, 16>();\n\n test_gather_vector_unorm<2, 32>();\n test_gather_vector_unorm<3, 32>();\n test_gather_vector_unorm<4, 32>();\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test gather() with vec4's\n\/\/\n\nTEST(SIMD, GatherVec4)\n{\n\n \/\/ init memory\n\n VSNRAY_ALIGN(32) vec4 arr[16];\n\n for (int i = 0; i < 16; ++i)\n {\n arr[i] = vec4(\n static_cast<float>(i * 4),\n static_cast<float>(i * 4 + 1),\n static_cast<float>(i * 4 + 2),\n static_cast<float>(i * 4 + 3)\n );\n\n }\n\n\n \/\/ test vector<4, float4>\n\n simd::int4 index4(0, 2, 4, 6);\n vector<4, simd::float4> res4 = gather(arr, index4);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res4.x), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.y), 1.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.z), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res4.w), 3.0f);\n\n EXPECT_FLOAT_EQ(simd::get<1>(res4.x), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.y), 9.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.z), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res4.w), 11.0f);\n\n EXPECT_FLOAT_EQ(simd::get<2>(res4.x), 16.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.y), 17.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.z), 18.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res4.w), 19.0f);\n\n EXPECT_FLOAT_EQ(simd::get<3>(res4.x), 24.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.y), 25.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.z), 26.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res4.w), 27.0f);\n\n#if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX\n\n \/\/ test vector<4, float8>\n\n simd::int8 index8(0, 2, 4, 6, 8, 10, 12, 14);\n vector<4, simd::float8> res8 = gather(arr, index8);\n\n EXPECT_FLOAT_EQ(simd::get<0>(res8.x), 0.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.y), 1.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.z), 2.0f);\n EXPECT_FLOAT_EQ(simd::get<0>(res8.w), 3.0f);\n\n EXPECT_FLOAT_EQ(simd::get<1>(res8.x), 8.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.y), 9.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.z), 10.0f);\n EXPECT_FLOAT_EQ(simd::get<1>(res8.w), 11.0f);\n\n EXPECT_FLOAT_EQ(simd::get<2>(res8.x), 16.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.y), 17.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.z), 18.0f);\n EXPECT_FLOAT_EQ(simd::get<2>(res8.w), 19.0f);\n\n EXPECT_FLOAT_EQ(simd::get<3>(res8.x), 24.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.y), 25.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.z), 26.0f);\n EXPECT_FLOAT_EQ(simd::get<3>(res8.w), 27.0f);\n\n EXPECT_FLOAT_EQ(simd::get<4>(res8.x), 32.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.y), 33.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.z), 34.0f);\n EXPECT_FLOAT_EQ(simd::get<4>(res8.w), 35.0f);\n\n EXPECT_FLOAT_EQ(simd::get<5>(res8.x), 40.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.y), 41.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.z), 42.0f);\n EXPECT_FLOAT_EQ(simd::get<5>(res8.w), 43.0f);\n\n EXPECT_FLOAT_EQ(simd::get<6>(res8.x), 48.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.y), 49.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.z), 50.0f);\n EXPECT_FLOAT_EQ(simd::get<6>(res8.w), 51.0f);\n\n EXPECT_FLOAT_EQ(simd::get<7>(res8.x), 56.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.y), 57.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.z), 58.0f);\n EXPECT_FLOAT_EQ(simd::get<7>(res8.w), 59.0f);\n\n#endif\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Matthew Harvey. All rights reserved.\n\n#ifndef GUARD_debug_log_hpp\n#define GUARD_debug_log_hpp\n\n\/** @file debug_log.hpp\n *\n * @brief Provides macro for printing to std::clog in debug builds.\n *\n * From someone called \"snstrnd\" on Stack Overflow.\n *\/\n\n#include <iostream>\n\n\n\/**Macros to print to std::clog iff DEBUG is defined.\n *\n * If DEBUG is defined, JEWEL_DEBUG_LOG acts like std::clog\n * (but prints \" LOG: \" before the rest of the output),\n * but if DEBUG is not defined, JEWEL_DEBUG_LOG, and the rest\n * of the line, is effectively compiled away to nothing.\n *\n * If DEBUG is defined JEWEL_DEBUG_LOG_LOCATION prints the\n * file and line number to std::clog; otherwise, it is\n * effectively compiled away to nothing.\n *\n * Note a semicolon must still be included by client code\n * at the end of a statement using either of these macros.\n *\n * No particular exception safety guarantee is offered by\n * these macros. They are not intended for use in release builds.\n * But note that all it does is write to std::clog; so unless\n * exceptions have been enabled on std::clog, the only part of this\n * function that could throw is in initialization of the string being\n * written to std::clog. This might throw under conditions of\n * memory shortage; but it is extremely unlikely.\n *\/ \n\n#ifdef DEBUG\n\t#define JEWEL_DEBUG_LOG std::clog << \" LOG: \"\n\t#define JEWEL_DEBUG_LOG_LOCATION std::clog << __FILE__ << \": \" << __LINE__ << std::endl;\n#else\n\t#define JEWEL_DEBUG_LOG 0 && std::clog\n\t#define JEWEL_DEBUG_LOG_LOCATION 0\n#endif\n\n\n\n\n\n#endif \/\/ GUARD_debug_log_hpp\n<commit_msg>Created JEWEL_DEBUG_LOG_VALUE(x) macro to facilitate logging an expression, and its value, to std::clog when debugging.<commit_after>\/\/ Copyright (c) 2013, Matthew Harvey. All rights reserved.\n\n#ifndef GUARD_debug_log_hpp\n#define GUARD_debug_log_hpp\n\n\/** @file debug_log.hpp\n *\n * @brief Provides macro for printing to std::clog in debug builds.\n *\n * From someone called \"snstrnd\" on Stack Overflow.\n *\/\n\n#include <iostream>\n\n\n\/**Macros to print to std::clog if DEBUG is defined, or else to compile\n * away to nothing if DEBUG is not defined.\n *\n * If DEBUG is defined, JEWEL_DEBUG_LOG acts like std::clog\n * (but prints \"LOG: \" before the rest of the output),\n * but if DEBUG is not defined, JEWEL_DEBUG_LOG, and the rest\n * of the line, is effectively compiled away to nothing.\n *\n * If DEBUG is defined JEWEL_DEBUG_LOG_LOCATION prints the\n * file and line number to std::clog; otherwise, it is\n * effectively compiled away to nothing.\n *\n * If DEBUG is defined JEWEL_DEBUG_LOG_VALUE(x) prints a string\n * of the form \"LOG: x: [value of x]\". E.g. if x == 3, then\n * JEWEL_DEBUG_LOG_VALUE(x) will print \"LOG: x: 3\".\n *\n * Note a semicolon must still be included by client code\n * at the end of a statement using either of these macros.\n *\n * No particular exception safety guarantee is offered by\n * these macros. They are not intended for use in release builds.\n * But note that all it does is write to std::clog; so unless\n * exceptions have been enabled on std::clog, the only part of this\n * function that could throw is in initialization of the string being\n * written to std::clog. This might throw under conditions of\n * memory shortage; but it is extremely unlikely.\n *\/ \n\n#ifdef DEBUG\n\t#define JEWEL_DEBUG_LOG std::clog << \"LOG: \"\n\t#define JEWEL_DEBUG_LOG_LOCATION std::clog << __FILE__ << \": \" << __LINE__ << std::endl;\n\t#define JEWEL_DEBUG_LOG_VALUE(x) std::clog << \"LOG: \" #x \": \" << x << std::endl;\n#else\n\t#define JEWEL_DEBUG_LOG 0 && std::clog\n\t#define JEWEL_DEBUG_LOG_LOCATION 0\n\t#define JEWEL_DEBUG_LOG_VALUE(X) 0\n#endif\n\n\n\n\n\n#endif \/\/ GUARD_debug_log_hpp\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2006 - 2013, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n\n#ifdef HAVE_LIBGNUTLS\n\n#include <iostream>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <TLSClient.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <sys\/errno.h>\n#include <sys\/types.h>\n#include <netdb.h>\n#include <i18n.h>\n\n#define MAX_BUF 16384\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void gnutls_log_function (int level, const char* message)\n{\n std::cout << \"c: \" << level << \" \" << message;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTLSClient::TLSClient ()\n: _ca (\"\")\n, _socket (0)\n, _limit (0)\n, _debug (false)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTLSClient::~TLSClient ()\n{\n gnutls_deinit (_session);\n gnutls_certificate_free_credentials (_credentials);\n gnutls_global_deinit ();\n\n if (_socket)\n {\n shutdown (_socket, SHUT_RDWR);\n close (_socket);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::limit (int max)\n{\n _limit = max;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Calling this method results in all subsequent socket traffic being sent to\n\/\/ std::cout, labelled with 'c: ...'.\nvoid TLSClient::debug (int level)\n{\n if (level)\n _debug = true;\n\n gnutls_global_set_log_function (gnutls_log_function);\n gnutls_global_set_log_level (level);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::init (const std::string& ca)\n{\n _ca = ca;\n\n gnutls_global_init ();\n gnutls_certificate_allocate_credentials (&_credentials);\n gnutls_certificate_set_x509_trust_file (_credentials, _ca.c_str (), GNUTLS_X509_FMT_PEM);\n gnutls_init (&_session, GNUTLS_CLIENT);\n\n \/\/ Use default priorities.\n const char *err;\n int ret = gnutls_priority_set_direct (_session, \"NORMAL\", &err);\n if (ret < 0)\n {\n if (_debug && ret == GNUTLS_E_INVALID_REQUEST)\n std::cout << \"c: ERROR Priority error at: \" << err << \"\\n\";\n\n throw std::string (STRING_TLS_INIT_FAIL);\n }\n\n \/\/ Apply the x509 credentials to the current session.\n gnutls_credentials_set (_session, GNUTLS_CRD_CERTIFICATE, _credentials);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::connect (const std::string& host, const std::string& port)\n{\n \/\/ use IPv4 or IPv6, does not matter.\n struct addrinfo hints = {0};\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE; \/\/ use my IP\n\n struct addrinfo* res;\n if (::getaddrinfo (host.c_str (), port.c_str (), &hints, &res) != 0)\n throw \"ERROR: \" + std::string (::gai_strerror (errno));\n\n \/\/ Try them all, stop on success.\n struct addrinfo* p;\n for (p = res; p != NULL; p = p->ai_next)\n {\n if ((_socket = ::socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)\n continue;\n\n \/\/ When a socket is closed, it remains unavailable for a while (netstat -an).\n \/\/ Setting SO_REUSEADDR allows this program to assume control of a closed,\n \/\/ but unavailable socket.\n int on = 1;\n if (::setsockopt (_socket,\n SOL_SOCKET,\n SO_REUSEADDR,\n (const void*) &on,\n sizeof (on)) == -1)\n throw \"ERROR: \" + std::string (::strerror (errno));\n\n if (::connect (_socket, p->ai_addr, p->ai_addrlen) == -1)\n continue;\n\n break;\n }\n\n free (res);\n\n if (p == NULL)\n throw \"ERROR: Could not connect to \" + host + \" \" + port;\n\n gnutls_transport_set_ptr (_session, (gnutls_transport_ptr_t) (long) _socket);\n\n \/\/ Perform the TLS handshake\n int ret = gnutls_handshake (_session);\n if (ret < 0)\n {\n if (_debug)\n std::cout << \"c: ERROR Handshake failed\\n\";\n gnutls_perror (ret);\n }\n else\n {\n if (_debug)\n std::cout << \"c: INFO Handshake was completed\\n\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::bye ()\n{\n gnutls_bye (_session, GNUTLS_SHUT_RDWR);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::send (const std::string& data)\n{\n std::string packet = \"XXXX\" + data;\n\n \/\/ Encode the length.\n unsigned long l = packet.length ();\n packet[0] = l >>24;\n packet[1] = l >>16;\n packet[2] = l >>8;\n packet[3] = l;\n\n int total = 0;\n int remaining = packet.length ();\n\n while (total < packet.length ())\n {\n int status;\n do\n {\n status = gnutls_record_send (_session, packet.c_str () + total, remaining);\n }\n while (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN);\n\n if (status == -1)\n break;\n\n total += status;\n remaining -= status;\n }\n\n if (_debug)\n std::cout << \"c: INFO Sending 'XXXX\"\n << data.c_str ()\n << \"' (\" << total << \" bytes)\"\n << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::recv (std::string& data)\n{\n data = \"\"; \/\/ No appending of data.\n int received = 0;\n\n \/\/ Get the encoded length.\n unsigned char header[4] = {0};\n do\n {\n received = gnutls_record_recv (_session, header, 4);\n }\n while (received > 0 &&\n (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN));\n\n int total = received;\n\n \/\/ Decode the length.\n unsigned long expected = (header[0]<<24) |\n (header[1]<<16) |\n (header[2]<<8) |\n header[3];\n if (_debug)\n std::cout << \"c: INFO expecting \" << expected << \" bytes.\\n\";\n\n \/\/ TODO This would be a good place to assert 'expected < _limit'.\n\n \/\/ Arbitrary buffer size.\n char buffer[MAX_BUF];\n\n \/\/ Keep reading until no more data. Concatenate chunks of data if a) the\n \/\/ read was interrupted by a signal, and b) if there is more data than\n \/\/ fits in the buffer.\n do\n {\n do\n {\n received = gnutls_record_recv (_session, buffer, MAX_BUF - 1);\n }\n while (received > 0 &&\n (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN));\n\n \/\/ Other end closed the connection.\n if (received == 0)\n {\n if (_debug)\n std::cout << \"c: INFO Peer has closed the TLS connection\\n\";\n break;\n }\n\n \/\/ Something happened.\n if (received < 0)\n throw \"ERROR: \" + std::string (gnutls_strerror (received));\n\n buffer [received] = '\\0';\n data += buffer;\n total += received;\n\n \/\/ Stop at defined limit.\n if (_limit && total > _limit)\n break;\n }\n while (received > 0 && total < (int) expected);\n\n if (_debug)\n std::cout << \"c: INFO Receiving 'XXXX\"\n << data.c_str ()\n << \"' (\" << total << \" bytes)\"\n << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif\n<commit_msg>Build<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2006 - 2013, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n\n#ifdef HAVE_LIBGNUTLS\n\n#include <iostream>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <TLSClient.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <sys\/errno.h>\n#include <sys\/types.h>\n#include <netdb.h>\n#include <i18n.h>\n\n#define MAX_BUF 16384\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void gnutls_log_function (int level, const char* message)\n{\n std::cout << \"c: \" << level << \" \" << message;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTLSClient::TLSClient ()\n: _ca (\"\")\n, _socket (0)\n, _limit (0)\n, _debug (false)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTLSClient::~TLSClient ()\n{\n gnutls_deinit (_session);\n gnutls_certificate_free_credentials (_credentials);\n gnutls_global_deinit ();\n\n if (_socket)\n {\n shutdown (_socket, SHUT_RDWR);\n close (_socket);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::limit (int max)\n{\n _limit = max;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Calling this method results in all subsequent socket traffic being sent to\n\/\/ std::cout, labelled with 'c: ...'.\nvoid TLSClient::debug (int level)\n{\n if (level)\n _debug = true;\n\n gnutls_global_set_log_function (gnutls_log_function);\n gnutls_global_set_log_level (level);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::init (const std::string& ca)\n{\n _ca = ca;\n\n gnutls_global_init ();\n gnutls_certificate_allocate_credentials (&_credentials);\n gnutls_certificate_set_x509_trust_file (_credentials, _ca.c_str (), GNUTLS_X509_FMT_PEM);\n gnutls_init (&_session, GNUTLS_CLIENT);\n\n \/\/ Use default priorities.\n const char *err;\n int ret = gnutls_priority_set_direct (_session, \"NORMAL\", &err);\n if (ret < 0)\n {\n if (_debug && ret == GNUTLS_E_INVALID_REQUEST)\n std::cout << \"c: ERROR Priority error at: \" << err << \"\\n\";\n\n throw std::string (STRING_TLS_INIT_FAIL);\n }\n\n \/\/ Apply the x509 credentials to the current session.\n gnutls_credentials_set (_session, GNUTLS_CRD_CERTIFICATE, _credentials);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::connect (const std::string& host, const std::string& port)\n{\n \/\/ use IPv4 or IPv6, does not matter.\n struct addrinfo hints = {0};\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE; \/\/ use my IP\n\n struct addrinfo* res;\n if (::getaddrinfo (host.c_str (), port.c_str (), &hints, &res) != 0)\n throw \"ERROR: \" + std::string (::gai_strerror (errno));\n\n \/\/ Try them all, stop on success.\n struct addrinfo* p;\n for (p = res; p != NULL; p = p->ai_next)\n {\n if ((_socket = ::socket (p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)\n continue;\n\n \/\/ When a socket is closed, it remains unavailable for a while (netstat -an).\n \/\/ Setting SO_REUSEADDR allows this program to assume control of a closed,\n \/\/ but unavailable socket.\n int on = 1;\n if (::setsockopt (_socket,\n SOL_SOCKET,\n SO_REUSEADDR,\n (const void*) &on,\n sizeof (on)) == -1)\n throw \"ERROR: \" + std::string (::strerror (errno));\n\n if (::connect (_socket, p->ai_addr, p->ai_addrlen) == -1)\n continue;\n\n break;\n }\n\n free (res);\n\n if (p == NULL)\n throw \"ERROR: Could not connect to \" + host + \" \" + port;\n\n gnutls_transport_set_ptr (_session, (gnutls_transport_ptr_t) (long) _socket);\n\n \/\/ Perform the TLS handshake\n int ret = gnutls_handshake (_session);\n if (ret < 0)\n {\n if (_debug)\n std::cout << \"c: ERROR Handshake failed\\n\";\n gnutls_perror (ret);\n }\n else\n {\n if (_debug)\n std::cout << \"c: INFO Handshake was completed\\n\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::bye ()\n{\n gnutls_bye (_session, GNUTLS_SHUT_RDWR);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::send (const std::string& data)\n{\n std::string packet = \"XXXX\" + data;\n\n \/\/ Encode the length.\n unsigned long l = packet.length ();\n packet[0] = l >>24;\n packet[1] = l >>16;\n packet[2] = l >>8;\n packet[3] = l;\n\n unsigned int total = 0;\n unsigned int remaining = packet.length ();\n\n while (total < packet.length ())\n {\n int status;\n do\n {\n status = gnutls_record_send (_session, packet.c_str () + total, remaining);\n }\n while (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN);\n\n if (status == -1)\n break;\n\n total += (unsigned int) status;\n remaining -= (unsigned int) status;\n }\n\n if (_debug)\n std::cout << \"c: INFO Sending 'XXXX\"\n << data.c_str ()\n << \"' (\" << total << \" bytes)\"\n << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TLSClient::recv (std::string& data)\n{\n data = \"\"; \/\/ No appending of data.\n int received = 0;\n\n \/\/ Get the encoded length.\n unsigned char header[4] = {0};\n do\n {\n received = gnutls_record_recv (_session, header, 4);\n }\n while (received > 0 &&\n (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN));\n\n int total = received;\n\n \/\/ Decode the length.\n unsigned long expected = (header[0]<<24) |\n (header[1]<<16) |\n (header[2]<<8) |\n header[3];\n if (_debug)\n std::cout << \"c: INFO expecting \" << expected << \" bytes.\\n\";\n\n \/\/ TODO This would be a good place to assert 'expected < _limit'.\n\n \/\/ Arbitrary buffer size.\n char buffer[MAX_BUF];\n\n \/\/ Keep reading until no more data. Concatenate chunks of data if a) the\n \/\/ read was interrupted by a signal, and b) if there is more data than\n \/\/ fits in the buffer.\n do\n {\n do\n {\n received = gnutls_record_recv (_session, buffer, MAX_BUF - 1);\n }\n while (received > 0 &&\n (errno == GNUTLS_E_INTERRUPTED ||\n errno == GNUTLS_E_AGAIN));\n\n \/\/ Other end closed the connection.\n if (received == 0)\n {\n if (_debug)\n std::cout << \"c: INFO Peer has closed the TLS connection\\n\";\n break;\n }\n\n \/\/ Something happened.\n if (received < 0)\n throw \"ERROR: \" + std::string (gnutls_strerror (received));\n\n buffer [received] = '\\0';\n data += buffer;\n total += received;\n\n \/\/ Stop at defined limit.\n if (_limit && total > _limit)\n break;\n }\n while (received > 0 && total < (int) expected);\n\n if (_debug)\n std::cout << \"c: INFO Receiving 'XXXX\"\n << data.c_str ()\n << \"' (\" << total << \" bytes)\"\n << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ ------------------------------------------------------------------------\n\/\/ Pion is a development platform for building Reactors that process Events\n\/\/ ------------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Pion is free software: you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Affero General Public License as published by the Free\n\/\/ Software Foundation, either version 3 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ Pion is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pion. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <pion\/platform\/ConfigManager.hpp>\n#include <pion\/platform\/DatabaseManager.hpp>\n#include \"SQLiteDatabase.hpp\"\n\nusing namespace pion::platform;\n\n\nnamespace pion {\t\t\/\/ begin namespace pion\nnamespace plugins {\t\t\/\/ begin namespace plugins\n\n\n\/\/ static members of SQLiteDatabase\n\nconst std::string\t\t\tSQLiteDatabase::BACKUP_FILE_EXTENSION = \".bak\";\nconst std::string\t\t\tSQLiteDatabase::FILENAME_ELEMENT_NAME = \"Filename\";\n\n\n\/\/ SQLiteDatabase member functions\n\nvoid SQLiteDatabase::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)\n{\n\tDatabase::setConfig(v, config_ptr);\n\n\treadConfig(config_ptr, \"SQLite\");\n\n\t\/\/ get the Filename of the database\n\tif (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, m_database_name, config_ptr))\n\t\tthrow EmptyFilenameException(getId());\n\n\t\/\/ resolve paths relative to the platform DataDirectory\n\tboost::filesystem::path path_to_file(boost::filesystem::system_complete(getDatabaseManager().getDataDirectory()));\n\tpath_to_file \/= m_database_name;\n\tpath_to_file.normalize();\n\tm_database_name = path_to_file.file_string();\n}\n\nDatabasePtr SQLiteDatabase::clone(void) const\n{\n\tSQLiteDatabase *db_ptr(new SQLiteDatabase());\n\tdb_ptr->copyDatabase(*this);\n\tdb_ptr->m_database_name = m_database_name;\n\treturn DatabasePtr(db_ptr);\n}\n\nvoid SQLiteDatabase::open(unsigned partition)\n{\n\t\/\/ create a backup copy of the database before opening it\n\tconst bool is_new_database = ! boost::filesystem::exists(m_database_name);\n\/* \"no backups no more\" since it's not supported by Enterprise database either...\n\tif (! is_new_database && create_backup) {\n\t\tconst std::string backup_filename(m_database_name + BACKUP_FILE_EXTENSION);\n\t\tif (boost::filesystem::exists(backup_filename))\n\t\t\tboost::filesystem::remove(backup_filename);\n\t\tboost::filesystem::copy_file(m_database_name, backup_filename);\n\t}\n*\/\n\t\/\/ If Partitioning: Change \"name.db\" into \"name_001.db\" or, \"name\" into \"name_001.db\"\n\tif (partition) {\n\t\tchar buff[10];\n\t\tsprintf(buff, \"_%03u.db\", partition);\n\t\tstd::string::size_type i = 0;\n\t\tif ((i = m_database_name.find(\".db\", i)) != std::string::npos)\n\t\t\tm_database_name.replace(i, strlen(\".db\"), buff);\n\t\telse\n\t\t\tm_database_name += buff;\n\t}\n\n\t\/\/ open up the database\n\/\/\tif (sqlite3_open_v2(m_database_name.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {\n\tif (sqlite3_open_v2(m_database_name.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {\n\t\t\/\/ prevent memory leak (sqlite3 assigns handle even if error)\n\t\tif (m_sqlite_db != NULL) {\n\t\t\tsqlite3_close(m_sqlite_db);\n\t\t\tm_sqlite_db = NULL;\n\t\t}\n\t\tthrow OpenDatabaseException(m_database_name);\n\t}\n\n\t\/\/ set a 10s busy timeout to deal with db locking\n\tsqlite3_busy_timeout(m_sqlite_db, 10000);\n\n\t\/\/ execute all PreSQL (if any)\n\tfor (unsigned i = 0; i < m_pre_sql.size(); i++)\n\t\tif (sqlite3_exec(m_sqlite_db, m_pre_sql[i].c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\t\tthrow SQLiteAPIException(getSQLiteError());\n}\n\nvoid SQLiteDatabase::close(void)\n{\n\tif (m_sqlite_db != NULL)\n\t\tsqlite3_close(m_sqlite_db);\n\tm_sqlite_db = NULL;\n}\n\nvoid SQLiteDatabase::runQuery(const std::string& sql_query)\n{\n\t\/\/ sanity checks\n\tPION_ASSERT(is_open());\n\tPION_ASSERT(! sql_query.empty());\n\n\t\/\/ execute the query\n\tif (sqlite3_exec(m_sqlite_db, sql_query.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\tthrow SQLiteAPIException(getSQLiteError());\n}\n\nQueryPtr SQLiteDatabase::addQuery(QueryID query_id,\n\t\t\t\t\t\t\t\t const std::string& sql_query)\n{\n\t\/\/ sanity checks\n\tPION_ASSERT(is_open());\n\tPION_ASSERT(! query_id.empty());\n\tPION_ASSERT(! sql_query.empty());\n\n\t\/\/ generate a new database query object\n\tQueryPtr query_ptr(new SQLiteQuery(sql_query, m_sqlite_db));\n\n\t\/\/ add the query to our query map\n\tm_query_map.insert(std::make_pair(query_id, query_ptr));\n\n\t\/\/ return the new database query object\n\treturn query_ptr;\n}\n\nvoid SQLiteDatabase::createTable(const Query::FieldMap& field_map,\n\t\t\t\t\t\t\t\tstd::string& table_name,\n\t\t\t\t\t\t\t\tconst Query::IndexMap& index_map,\n\t\t\t\t\t\t\t\tunsigned partition)\n{\n\tPION_ASSERT(is_open());\n\n\t\/\/ If partition is defined, change table_name\n\tif (partition) {\n\t\tchar buff[10];\n\t\tsprintf(buff, \"_%03u\", partition);\n\t\ttable_name += buff;\n\t}\n\n\t\/\/ build a SQL query to create the output table if it doesn't yet exist\n\tstd::string create_table_sql = m_create_log;\n\tstringSubstitutes(create_table_sql, field_map, table_name);\n\n\t\/\/ run the SQL query to create the table\n\trunQuery(create_table_sql);\n\n\t\/\/ CREATE [UNIQUE] INDEX [IF NOT EXISTS] [dbname.] indexname ON tablename ( indexcolumn [, indexcolumn] )\n\t\/\/\t\tindexcolumn: indexcolumn [COLLATE collatename] [ ASC | DESC]\n\t\/\/ DROP INDEX [IF EXISTS] [dbname.] indexname\n\tfor (unsigned i = 0; i < index_map.size(); i++) {\n\t\tstd::string Sql;\n\t\tconst std::string idxname = table_name + \"_\" + field_map[i].first + \"_idx\";\n\t\tif (index_map[i] == \"false\" || index_map[i].empty())\n\t\t\tSql = \"DROP INDEX IF EXISTS \" + idxname;\n\t\telse if (index_map[i] == \"true\")\n\t\t\tSql = \"CREATE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + field_map[i].first + \" )\";\n\t\telse if (index_map[i] == \"unique\")\n\t\t\tSql = \"CREATE UNIQUE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + field_map[i].first + \" )\";\n\t\telse\n\t\t\tSql = \"CREATE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + index_map[i] + \" )\";\n\n\t\tif (sqlite3_exec(m_sqlite_db, Sql.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\t\tthrow SQLiteAPIException(getSQLiteError());\n\t}\n}\n\nvoid SQLiteDatabase::dropTable(std::string& table_name, unsigned partition)\n{\n\tif (m_sqlite_db) {\n\/\/\t\tthrow DBStillOpen(m_database_name);\n\t\tclose();\n\t\tunlink(m_database_name.c_str());\n\t\topen();\t\t\t\/\/ NOTE: don't id partition, it doubles up...\n\t} else {\n\t\tif (partition) {\n\t\t\tchar buff[10];\n\t\t\tsprintf(buff, \"_%03u.db\", partition);\n\t\t\tstd::string::size_type i = 0;\n\t\t\tif ((i = table_name.find(\".db\", i)) != std::string::npos)\n\t\t\t\ttable_name.replace(i, strlen(\".db\"), buff);\n\t\t\telse\n\t\t\t\ttable_name += buff;\n\t\t}\n\t\tunlink(table_name.c_str());\n\t}\n}\n\nQueryPtr SQLiteDatabase::prepareInsertQuery(const Query::FieldMap& field_map,\n\t\t\t\t\t\t\t\t\t\t\tconst std::string& table_name)\n{\n\tPION_ASSERT(is_open());\n\n\t\/\/ exit early if it already exists\n\tQueryMap::const_iterator query_it = m_query_map.find(INSERT_QUERY_ID);\n\tif (query_it != m_query_map.end())\n\t\treturn query_it->second;\n\n\t\/\/ build a SQL query that can be used to insert a new record\n\tstd::string insert_sql = m_insert_log;\n\tstringSubstitutes(insert_sql, field_map, table_name);\n\n\t\/\/ compile the SQL query into a prepared statement\n\treturn addQuery(Database::INSERT_QUERY_ID, insert_sql);\n}\n\nQueryPtr SQLiteDatabase::getBeginTransactionQuery(void)\n{\n\tPION_ASSERT(is_open());\n\tQueryMap::const_iterator i = m_query_map.find(BEGIN_QUERY_ID);\n\tif (i == m_query_map.end())\n\t\treturn addQuery(BEGIN_QUERY_ID, m_begin_insert);\n\treturn i->second;\n}\n\nQueryPtr SQLiteDatabase::getCommitTransactionQuery(void)\n{\n\tPION_ASSERT(is_open());\n\tQueryMap::const_iterator i = m_query_map.find(COMMIT_QUERY_ID);\n\tif (i == m_query_map.end())\n\t\treturn addQuery(COMMIT_QUERY_ID, m_commit_insert);\n\treturn i->second;\n}\n\nQueryPtr SQLiteDatabase::prepareFullQuery(const std::string& query)\n{\n\tPION_ASSERT(is_open());\n\n\tQueryPtr query_ptr(new SQLiteQuery(query, m_sqlite_db));\n\treturn query_ptr;\n}\n\nbool SQLiteDatabase::SQLiteQuery::runFullQuery(const pion::platform::Query::FieldMap& ins, const pion::platform::EventPtr& src,\n\tconst pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit)\n{\n\tbool changes = false;\n\tsqlite3_reset(m_sqlite_stmt);\n\tbindEvent(ins, *src);\n\twhile (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) {\n\t\tfetchEvent(outs, dest);\n\t\tchanges = true;\n\t\tif (!--limit) return changes;\n\t}\n\treturn changes;\n}\n\nbool SQLiteDatabase::SQLiteQuery::runFullGetMore(const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest,\n\tunsigned int limit)\n{\n\tbool changes = false;\n\twhile (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) {\n\t\tfetchEvent(outs, dest);\n\t\tchanges = true;\n\t\tif (!--limit) return changes;\n\t}\n\treturn changes;\n}\n\n\n\/\/ SQLiteDatabase::SQLiteQuery member functions\n\n\nSQLiteDatabase::SQLiteQuery::SQLiteQuery(const std::string& sql_query, sqlite3 *db_ptr)\n\t: Query(sql_query), m_sqlite_db(db_ptr), m_sqlite_stmt(NULL)\n{\n\tPION_ASSERT(db_ptr != NULL);\n\tif (sqlite3_prepare_v2(m_sqlite_db, sql_query.c_str(), sql_query.size(),\n\t\t\t\t\t\t&m_sqlite_stmt, NULL) != SQLITE_OK)\n\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\tPION_ASSERT(m_sqlite_stmt != NULL);\n}\n\nbool SQLiteDatabase::SQLiteQuery::run(void)\n{\n\t\/\/ step forward to the next row in the query (if there are any)\n\tbool row_available = false;\n\tswitch (sqlite3_step(m_sqlite_stmt)) {\n\t\tcase SQLITE_BUSY:\n\t\t\tthrow SQLiteDatabase::DatabaseBusyException();\n\t\t\tbreak;\n\t\tcase SQLITE_ROW:\n\t\t\t\/\/ a new result row is available\n\t\t\trow_available = true;\n\t\t\tbreak;\n\t\tcase SQLITE_DONE:\n\t\t\t\/\/ query is finished; no more rows to return\n\t\t\trow_available = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\t\t\tbreak;\n\t}\n\treturn row_available;\n}\n\n\nbool SQLiteDatabase::SQLiteQuery::fetchRow(const FieldMap& field_map, EventPtr e)\n{\n\tbool row_available = false;\n\tswitch (sqlite3_step(m_sqlite_stmt)) {\n\t\tcase SQLITE_BUSY:\n\t\t\tthrow SQLiteDatabase::DatabaseBusyException();\n\t\t\tbreak;\n\t\tcase SQLITE_ROW:\n\t\t\t\/\/ a new result row is available\n\t\t\tfetchEvent(field_map, e);\n\t\t\trow_available = true;\n\t\t\tbreak;\n\t\tcase SQLITE_DONE:\n\t\t\t\/\/ query is finished; no more rows to return\n\/\/\t\t\trow_available = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\t\t\tbreak;\n\t}\n\treturn row_available;\n}\n\n\n}\t\/\/ end namespace plugins\n}\t\/\/ end namespace pion\n\n\n\/\/\/ creates new SQLiteDatabase objects\nextern \"C\" PION_PLUGIN_API pion::platform::Database *pion_create_SQLiteDatabase(void) {\n\treturn new pion::plugins::SQLiteDatabase();\n}\n\n\/\/\/ destroys SQLiteDatabase objects\nextern \"C\" PION_PLUGIN_API void pion_destroy_SQLiteDatabase(pion::plugins::SQLiteDatabase *database_ptr) {\n\tdelete database_ptr;\n}\n<commit_msg>SQLite<commit_after>\/\/ ------------------------------------------------------------------------\n\/\/ Pion is a development platform for building Reactors that process Events\n\/\/ ------------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Pion is free software: you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Affero General Public License as published by the Free\n\/\/ Software Foundation, either version 3 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ Pion is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pion. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <boost\/filesystem\/operations.hpp>\n#include <pion\/platform\/ConfigManager.hpp>\n#include <pion\/platform\/DatabaseManager.hpp>\n#include \"SQLiteDatabase.hpp\"\n\nusing namespace pion::platform;\n\n\nnamespace pion {\t\t\/\/ begin namespace pion\nnamespace plugins {\t\t\/\/ begin namespace plugins\n\n\n\/\/ static members of SQLiteDatabase\n\nconst std::string\t\t\tSQLiteDatabase::BACKUP_FILE_EXTENSION = \".bak\";\nconst std::string\t\t\tSQLiteDatabase::FILENAME_ELEMENT_NAME = \"Filename\";\n\n\n\/\/ SQLiteDatabase member functions\n\nvoid SQLiteDatabase::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)\n{\n\tDatabase::setConfig(v, config_ptr);\n\n\treadConfig(config_ptr, \"SQLite\");\n\n\t\/\/ get the Filename of the database\n\tif (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, m_database_name, config_ptr))\n\t\tthrow EmptyFilenameException(getId());\n\n\t\/\/ resolve paths relative to the platform DataDirectory\n\tboost::filesystem::path path_to_file(boost::filesystem::system_complete(getDatabaseManager().getDataDirectory()));\n\tpath_to_file \/= m_database_name;\n\tpath_to_file.normalize();\n\tm_database_name = path_to_file.file_string();\n}\n\nDatabasePtr SQLiteDatabase::clone(void) const\n{\n\tSQLiteDatabase *db_ptr(new SQLiteDatabase());\n\tdb_ptr->copyDatabase(*this);\n\tdb_ptr->m_database_name = m_database_name;\n\treturn DatabasePtr(db_ptr);\n}\n\nstd::string dbPartition(std::string name, unsigned partition)\n{\n\tif (partition) {\n\t\tchar buff[10];\n\t\tsprintf(buff, \"_%03u.db\", partition);\n\t\tstd::string::size_type i = 0;\n\t\tif ((i = name.find(\".db\", i)) != std::string::npos)\n\t\t\tname.replace(i, strlen(\".db\"), buff);\n\t\telse\n\t\t\tname += buff;\n\t}\n\treturn name;\n}\n\nvoid SQLiteDatabase::open(unsigned partition)\n{\n\t\/\/ create a backup copy of the database before opening it\n\tconst bool is_new_database = ! boost::filesystem::exists(m_database_name);\n\/* \"no backups no more\" since it's not supported by Enterprise database either...\n\tif (! is_new_database && create_backup) {\n\t\tconst std::string backup_filename(m_database_name + BACKUP_FILE_EXTENSION);\n\t\tif (boost::filesystem::exists(backup_filename))\n\t\t\tboost::filesystem::remove(backup_filename);\n\t\tboost::filesystem::copy_file(m_database_name, backup_filename);\n\t}\n*\/\n\t\/\/ If Partitioning: Change \"name.db\" into \"name_001.db\" or, \"name\" into \"name_001.db\"\n\tstd::string dbname = dbPartition(m_database_name, partition);\n\n\t\/\/ open up the database\n\/\/\tif (sqlite3_open_v2(m_database_name.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {\n\tif (sqlite3_open_v2(dbname.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {\n\t\t\/\/ prevent memory leak (sqlite3 assigns handle even if error)\n\t\tif (m_sqlite_db != NULL) {\n\t\t\tsqlite3_close(m_sqlite_db);\n\t\t\tm_sqlite_db = NULL;\n\t\t}\n\t\tthrow OpenDatabaseException(dbname);\n\t}\n\n\t\/\/ set a 10s busy timeout to deal with db locking\n\tsqlite3_busy_timeout(m_sqlite_db, 10000);\n\n\t\/\/ execute all PreSQL (if any)\n\tfor (unsigned i = 0; i < m_pre_sql.size(); i++)\n\t\tif (sqlite3_exec(m_sqlite_db, m_pre_sql[i].c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\t\tthrow SQLiteAPIException(getSQLiteError());\n}\n\nvoid SQLiteDatabase::close(void)\n{\n\tif (m_sqlite_db != NULL)\n\t\tsqlite3_close(m_sqlite_db);\n\tm_sqlite_db = NULL;\n}\n\nvoid SQLiteDatabase::runQuery(const std::string& sql_query)\n{\n\t\/\/ sanity checks\n\tPION_ASSERT(is_open());\n\tPION_ASSERT(! sql_query.empty());\n\n\t\/\/ execute the query\n\tif (sqlite3_exec(m_sqlite_db, sql_query.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\tthrow SQLiteAPIException(getSQLiteError());\n}\n\nQueryPtr SQLiteDatabase::addQuery(QueryID query_id,\n\t\t\t\t\t\t\t\t const std::string& sql_query)\n{\n\t\/\/ sanity checks\n\tPION_ASSERT(is_open());\n\tPION_ASSERT(! query_id.empty());\n\tPION_ASSERT(! sql_query.empty());\n\n\t\/\/ generate a new database query object\n\tQueryPtr query_ptr(new SQLiteQuery(sql_query, m_sqlite_db));\n\n\t\/\/ add the query to our query map\n\tm_query_map.insert(std::make_pair(query_id, query_ptr));\n\n\t\/\/ return the new database query object\n\treturn query_ptr;\n}\n\nvoid SQLiteDatabase::createTable(const Query::FieldMap& field_map,\n\t\t\t\t\t\t\t\tstd::string& table_name,\n\t\t\t\t\t\t\t\tconst Query::IndexMap& index_map,\n\t\t\t\t\t\t\t\tunsigned partition)\n{\n\tPION_ASSERT(is_open());\n\n\t\/\/ If partition is defined, change table_name\n\tif (partition) {\n\t\tchar buff[10];\n\t\tsprintf(buff, \"_%03u\", partition);\n\t\ttable_name += buff;\n\t}\n\n\t\/\/ build a SQL query to create the output table if it doesn't yet exist\n\tstd::string create_table_sql = m_create_log;\n\tstringSubstitutes(create_table_sql, field_map, table_name);\n\n\t\/\/ run the SQL query to create the table\n\trunQuery(create_table_sql);\n\n\t\/\/ CREATE [UNIQUE] INDEX [IF NOT EXISTS] [dbname.] indexname ON tablename ( indexcolumn [, indexcolumn] )\n\t\/\/\t\tindexcolumn: indexcolumn [COLLATE collatename] [ ASC | DESC]\n\t\/\/ DROP INDEX [IF EXISTS] [dbname.] indexname\n\tfor (unsigned i = 0; i < index_map.size(); i++) {\n\t\tstd::string Sql;\n\t\tconst std::string idxname = table_name + \"_\" + field_map[i].first + \"_idx\";\n\t\tif (index_map[i] == \"false\" || index_map[i].empty())\n\t\t\tSql = \"DROP INDEX IF EXISTS \" + idxname;\n\t\telse if (index_map[i] == \"true\")\n\t\t\tSql = \"CREATE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + field_map[i].first + \" )\";\n\t\telse if (index_map[i] == \"unique\")\n\t\t\tSql = \"CREATE UNIQUE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + field_map[i].first + \" )\";\n\t\telse\n\t\t\tSql = \"CREATE INDEX IF NOT EXISTS \" + idxname + \" ON \" + table_name + \" ( \" + index_map[i] + \" )\";\n\n\t\tif (sqlite3_exec(m_sqlite_db, Sql.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK)\n\t\t\tthrow SQLiteAPIException(getSQLiteError());\n\t}\n}\n\nvoid SQLiteDatabase::dropTable(std::string& table_name, unsigned partition)\n{\n\tif (m_sqlite_db) {\n\t\tclose();\n\t\tunlink(dbPartition(table_name).c_str());\n\t\topen(partition);\n\t} else {\n\t\tunlink(dbPartition(table_name).c_str());\n\t}\n}\n\nQueryPtr SQLiteDatabase::prepareInsertQuery(const Query::FieldMap& field_map,\n\t\t\t\t\t\t\t\t\t\t\tconst std::string& table_name)\n{\n\tPION_ASSERT(is_open());\n\n\t\/\/ exit early if it already exists\n\tQueryMap::const_iterator query_it = m_query_map.find(INSERT_QUERY_ID);\n\tif (query_it != m_query_map.end())\n\t\treturn query_it->second;\n\n\t\/\/ build a SQL query that can be used to insert a new record\n\tstd::string insert_sql = m_insert_log;\n\tstringSubstitutes(insert_sql, field_map, table_name);\n\n\t\/\/ compile the SQL query into a prepared statement\n\treturn addQuery(Database::INSERT_QUERY_ID, insert_sql);\n}\n\nQueryPtr SQLiteDatabase::getBeginTransactionQuery(void)\n{\n\tPION_ASSERT(is_open());\n\tQueryMap::const_iterator i = m_query_map.find(BEGIN_QUERY_ID);\n\tif (i == m_query_map.end())\n\t\treturn addQuery(BEGIN_QUERY_ID, m_begin_insert);\n\treturn i->second;\n}\n\nQueryPtr SQLiteDatabase::getCommitTransactionQuery(void)\n{\n\tPION_ASSERT(is_open());\n\tQueryMap::const_iterator i = m_query_map.find(COMMIT_QUERY_ID);\n\tif (i == m_query_map.end())\n\t\treturn addQuery(COMMIT_QUERY_ID, m_commit_insert);\n\treturn i->second;\n}\n\nQueryPtr SQLiteDatabase::prepareFullQuery(const std::string& query)\n{\n\tPION_ASSERT(is_open());\n\n\tQueryPtr query_ptr(new SQLiteQuery(query, m_sqlite_db));\n\treturn query_ptr;\n}\n\nbool SQLiteDatabase::SQLiteQuery::runFullQuery(const pion::platform::Query::FieldMap& ins, const pion::platform::EventPtr& src,\n\tconst pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit)\n{\n\tbool changes = false;\n\tsqlite3_reset(m_sqlite_stmt);\n\tbindEvent(ins, *src);\n\twhile (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) {\n\t\tfetchEvent(outs, dest);\n\t\tchanges = true;\n\t\tif (!--limit) return changes;\n\t}\n\treturn changes;\n}\n\nbool SQLiteDatabase::SQLiteQuery::runFullGetMore(const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest,\n\tunsigned int limit)\n{\n\tbool changes = false;\n\twhile (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) {\n\t\tfetchEvent(outs, dest);\n\t\tchanges = true;\n\t\tif (!--limit) return changes;\n\t}\n\treturn changes;\n}\n\n\n\/\/ SQLiteDatabase::SQLiteQuery member functions\n\n\nSQLiteDatabase::SQLiteQuery::SQLiteQuery(const std::string& sql_query, sqlite3 *db_ptr)\n\t: Query(sql_query), m_sqlite_db(db_ptr), m_sqlite_stmt(NULL)\n{\n\tPION_ASSERT(db_ptr != NULL);\n\tif (sqlite3_prepare_v2(m_sqlite_db, sql_query.c_str(), sql_query.size(),\n\t\t\t\t\t\t&m_sqlite_stmt, NULL) != SQLITE_OK)\n\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\tPION_ASSERT(m_sqlite_stmt != NULL);\n}\n\nbool SQLiteDatabase::SQLiteQuery::run(void)\n{\n\t\/\/ step forward to the next row in the query (if there are any)\n\tbool row_available = false;\n\tswitch (sqlite3_step(m_sqlite_stmt)) {\n\t\tcase SQLITE_BUSY:\n\t\t\tthrow SQLiteDatabase::DatabaseBusyException();\n\t\t\tbreak;\n\t\tcase SQLITE_ROW:\n\t\t\t\/\/ a new result row is available\n\t\t\trow_available = true;\n\t\t\tbreak;\n\t\tcase SQLITE_DONE:\n\t\t\t\/\/ query is finished; no more rows to return\n\t\t\trow_available = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\t\t\tbreak;\n\t}\n\treturn row_available;\n}\n\n\nbool SQLiteDatabase::SQLiteQuery::fetchRow(const FieldMap& field_map, EventPtr e)\n{\n\tbool row_available = false;\n\tswitch (sqlite3_step(m_sqlite_stmt)) {\n\t\tcase SQLITE_BUSY:\n\t\t\tthrow SQLiteDatabase::DatabaseBusyException();\n\t\t\tbreak;\n\t\tcase SQLITE_ROW:\n\t\t\t\/\/ a new result row is available\n\t\t\tfetchEvent(field_map, e);\n\t\t\trow_available = true;\n\t\t\tbreak;\n\t\tcase SQLITE_DONE:\n\t\t\t\/\/ query is finished; no more rows to return\n\/\/\t\t\trow_available = false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSQLiteDatabase::throwAPIException(m_sqlite_db);\n\t\t\tbreak;\n\t}\n\treturn row_available;\n}\n\n\n}\t\/\/ end namespace plugins\n}\t\/\/ end namespace pion\n\n\n\/\/\/ creates new SQLiteDatabase objects\nextern \"C\" PION_PLUGIN_API pion::platform::Database *pion_create_SQLiteDatabase(void) {\n\treturn new pion::plugins::SQLiteDatabase();\n}\n\n\/\/\/ destroys SQLiteDatabase objects\nextern \"C\" PION_PLUGIN_API void pion_destroy_SQLiteDatabase(pion::plugins::SQLiteDatabase *database_ptr) {\n\tdelete database_ptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef GDT_COLLISION_DETECTION_HPP\n#define GDT_COLLISION_DETECTION_HPP\n\nnamespace GDT\n{\n \/\/\/ Returns true if the point (x,y) is within a convex polygon.\n \/**\n The shape of the polygon defined by arrayOfPairs must be convex.\n Otherwise, behavior is undefined.\n arrayOfPairs must be an array of at least size 3 of an array size 2.\n size must be the number of size-2-arrays within arrayOfPairs.\n Thus if arrayOfPairs is defined as \\code{.cpp} float arrayOfPairs[4][2]\n \\endcode , then size must be 4.\n *\/\n bool isWithinPolygon(float (*arrayOfPairs)[2], unsigned int size, float x, float y);\n\n \/\/\/ Returns true if the point (x,y) is within a convex polygon.\n \/**\n The shape of the polygon defined by arrayOfPairs must be convex.\n Otherwise, behavior is undefined.\n arrayOfPairs must be an array of at least size 6 and even.\n arraySize must be the size of arrayOfPairs.\n Thus if arrayOfPairs is defined as float arrayOfPairs[8], then\n arraySize must be 8.\n If the size of arrayOfPairs is not even, then behavior is undefined.\n *\/\n bool isWithinPolygon(float* arrayOfPairs, unsigned int arraySize, float x, float y);\n}\n\n#endif\n\n<commit_msg>Fixed documentation of CollisionDetection.hpp<commit_after>\n#ifndef GDT_COLLISION_DETECTION_HPP\n#define GDT_COLLISION_DETECTION_HPP\n\nnamespace GDT\n{\n \/\/\/ Returns true if the point (x,y) is within a convex polygon.\n \/**\n The shape of the polygon defined by arrayOfPairs must be convex.\n Otherwise, behavior is undefined.\n arrayOfPairs must be an array of at least size 3 of an array size 2.\n size must be the number of size-2-arrays within arrayOfPairs.\n Thus if arrayOfPairs is defined as float arrayOfPairs[4][2], then size\n must be 4.\n *\/\n bool isWithinPolygon(float (*arrayOfPairs)[2], unsigned int size, float x, float y);\n\n \/\/\/ Returns true if the point (x,y) is within a convex polygon.\n \/**\n The shape of the polygon defined by arrayOfPairs must be convex.\n Otherwise, behavior is undefined.\n arrayOfPairs must be an array of at least size 6 and even.\n arraySize must be the size of arrayOfPairs.\n Thus if arrayOfPairs is defined as float arrayOfPairs[8], then\n arraySize must be 8.\n If the size of arrayOfPairs is not even, then behavior is undefined.\n *\/\n bool isWithinPolygon(float* arrayOfPairs, unsigned int arraySize, float x, float y);\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"VerticalImageList.h\"\n#include \"ListItem.h\"\n\n#include \"dataset\/Bitmap.h\"\n#include \"widgets\/DragTargetNull.h\"\n\nnamespace d2d\n{\n\nVerticalImageList::VerticalImageList(wxWindow* parent, const wxString& name\/* = wxEmptyString*\/,\n\t\t\t\t\t\t\t\t\t bool draggable \/*= true*\/)\n\t: wxVListBox(parent)\n\t, m_name(name)\n{\n\tSetBackgroundColour(wxColour(229, 229, 229));\n\n\tConnect(GetId(), wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler(VerticalImageList::onListSelected));\n\tConnect(GetId(), wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(VerticalImageList::onListDoubleClicked));\n\n\tif (draggable)\n\t{\n\t\tSetDropTarget(new DragTargetNull);\n\t\tConnect(GetId(), wxEVT_MOTION, wxMouseEventHandler(VerticalImageList::onDragInit));\n\t}\n}\n\nVerticalImageList::~VerticalImageList()\n{\n\tclear();\n}\n\nvoid VerticalImageList::traverse(IVisitor& visitor) const\n{\n\tstd::vector<ListItem*>::const_iterator itr = m_items.begin();\n\tfor ( ; itr != m_items.end(); ++itr)\n\t{\n\t\tbool hasNext;\n\t\tvisitor.visit(*itr, hasNext);\n\t\tif (!hasNext) break;\n\t}\n}\n\nvoid VerticalImageList::clear()\n{\n\tfor (int i = 0, n = m_items.size(); i < n; ++i) {\n\t\tm_items[i]->release();\n\t}\n\tm_items.clear();\n\tSetItemCount(0);\n\tRefresh();\n}\n\nvoid VerticalImageList::insert(ListItem* item)\n{\n\titem->retain();\n\tm_items.push_back(item);\n\tSetItemCount(m_items.size());\n\tSetSelection(m_items.size() - 1);\n\tRefresh();\n}\n\nvoid VerticalImageList::insertFront(ListItem* item)\n{\n\titem->retain();\n\tm_items.insert(m_items.begin(), item);\n\tSetItemCount(m_items.size());\n\tSetSelection(0);\n\tRefresh();\n}\n\nvoid VerticalImageList::remove()\n{\n\tremove(GetSelection());\n}\n\nvoid VerticalImageList::remove(int index)\n{\n\tif (index < 0 || index >= m_items.size())\n\t\treturn;\n\n\tm_items[index]->release();\n\tm_items.erase(m_items.begin() + index);\n \tSetItemCount(m_items.size());\n\tRefresh();\n}\n\nvoid VerticalImageList::swap(int i0, int i1)\n{\n\tif (i0 < 0 || i0 >= m_items.size() ||\n\t\ti1 < 0 || i1 >= m_items.size())\n\t\treturn;\n\n\tListItem* tmp = m_items[i0];\n\tm_items[i0] = m_items[i1];\n\tm_items[i1] = tmp;\n\n\tRefresh();\n}\n\nvoid VerticalImageList::OnDrawItem(wxDC& dc, const wxRect& rect, size_t n) const\n{\n\tint y = rect.y + SPACE_UP;\n\n\tconst Bitmap* bmp = m_items[n]->getBitmap();\n\tif (bmp)\n\t{\n\t\t\/\/ bmp\n\t\tconst wxBitmap* wxBmp = bmp->getBitmap();\n\t\tint x = wxBmp->GetWidth() > rect.width ? 0 : (rect.width - wxBmp->GetWidth()) * 0.5f;\n\t\tdc.DrawBitmap(*wxBmp, x, y);\n\n\t\t\/\/ info\n\t\twxString info = m_items[n]->getInfo();\n\t\tdc.SetFont(wxFont(18, wxDEFAULT, wxNORMAL, wxNORMAL));\n\t\t\/\/dc.SetTextForeground(wxColour(0xFF, 0x20, 0xFF));\n\t\twxSize size = dc.GetTextExtent(info);\n\t\t\/\/dc.DrawText(info, rect.x\/* + rect.width * 0.5f - size.GetWidth() * 0.5f*\/, y);\n\t\tdc.DrawText(info, rect.x + SPACE_UP, y);\n\n\t\ty += wxBmp->GetHeight();\n\t}\n\n\t\/\/ name\n\twxString name = m_items[n]->getName();\n\tdc.SetFont(wxFont(10, wxDEFAULT, wxNORMAL, wxNORMAL));\n\twxSize size = dc.GetTextExtent(name);\n\tdc.DrawText(name, rect.x + rect.width * 0.5f - size.GetWidth() * 0.5f, y + SPACE_UP);\n}\n\n\/\/ void VerticalImageList::OnDrawBackground(wxDC& dc, const wxRect& rect, size_t n) const\n\/\/ {\n\/\/ \tdc.SetPen(*wxRED_PEN);\n\/\/ \tdc.DrawRectangle(rect);\n\/\/ }\n\nvoid VerticalImageList::OnDrawSeparator(wxDC& dc, wxRect& rect, size_t n) const\n{\n\tdc.SetPen(wxPen(wxColour(0, 0, 0), 3));\n\tdc.DrawLine(rect.GetLeftBottom(), rect.GetRightBottom());\n}\n\nwxCoord VerticalImageList::OnMeasureItem(size_t n) const\n{\n\tconst Bitmap* bmp = m_items[n]->getBitmap();\n\tif (bmp) \n\t\treturn bmp->getBitmap()->GetHeight() + SPACE_UP + SPACE_DOWN;\n\telse \n\t\treturn SPACE_UP + SPACE_DOWN;\n}\n\nvoid VerticalImageList::onDragInit(wxMouseEvent& event)\n{\n\tif (event.Dragging())\n\t{\n\t\twxTextDataObject tdo(m_name + \",\" + wxString::FromDouble(GetSelection()));\n\t\twxDropSource ds(tdo);\n\t\tds.DoDragDrop(wxDrag_CopyOnly);\n\t}\n}\n} \/\/ d2d<commit_msg>[FIXED] 缩略图某些机器加载bmp会失败<commit_after>#include \"VerticalImageList.h\"\n#include \"ListItem.h\"\n\n#include \"dataset\/Bitmap.h\"\n#include \"widgets\/DragTargetNull.h\"\n\nnamespace d2d\n{\n\nVerticalImageList::VerticalImageList(wxWindow* parent, const wxString& name\/* = wxEmptyString*\/,\n\t\t\t\t\t\t\t\t\t bool draggable \/*= true*\/)\n\t: wxVListBox(parent)\n\t, m_name(name)\n{\n\tSetBackgroundColour(wxColour(229, 229, 229));\n\n\tConnect(GetId(), wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler(VerticalImageList::onListSelected));\n\tConnect(GetId(), wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(VerticalImageList::onListDoubleClicked));\n\n\tif (draggable)\n\t{\n\t\tSetDropTarget(new DragTargetNull);\n\t\tConnect(GetId(), wxEVT_MOTION, wxMouseEventHandler(VerticalImageList::onDragInit));\n\t}\n}\n\nVerticalImageList::~VerticalImageList()\n{\n\tclear();\n}\n\nvoid VerticalImageList::traverse(IVisitor& visitor) const\n{\n\tstd::vector<ListItem*>::const_iterator itr = m_items.begin();\n\tfor ( ; itr != m_items.end(); ++itr)\n\t{\n\t\tbool hasNext;\n\t\tvisitor.visit(*itr, hasNext);\n\t\tif (!hasNext) break;\n\t}\n}\n\nvoid VerticalImageList::clear()\n{\n\tfor (int i = 0, n = m_items.size(); i < n; ++i) {\n\t\tm_items[i]->release();\n\t}\n\tm_items.clear();\n\tSetItemCount(0);\n\tRefresh();\n}\n\nvoid VerticalImageList::insert(ListItem* item)\n{\n\titem->retain();\n\tm_items.push_back(item);\n\tSetItemCount(m_items.size());\n\tSetSelection(m_items.size() - 1);\n\tRefresh();\n}\n\nvoid VerticalImageList::insertFront(ListItem* item)\n{\n\titem->retain();\n\tm_items.insert(m_items.begin(), item);\n\tSetItemCount(m_items.size());\n\tSetSelection(0);\n\tRefresh();\n}\n\nvoid VerticalImageList::remove()\n{\n\tremove(GetSelection());\n}\n\nvoid VerticalImageList::remove(int index)\n{\n\tif (index < 0 || index >= m_items.size())\n\t\treturn;\n\n\tm_items[index]->release();\n\tm_items.erase(m_items.begin() + index);\n \tSetItemCount(m_items.size());\n\tRefresh();\n}\n\nvoid VerticalImageList::swap(int i0, int i1)\n{\n\tif (i0 < 0 || i0 >= m_items.size() ||\n\t\ti1 < 0 || i1 >= m_items.size())\n\t\treturn;\n\n\tListItem* tmp = m_items[i0];\n\tm_items[i0] = m_items[i1];\n\tm_items[i1] = tmp;\n\n\tRefresh();\n}\n\nvoid VerticalImageList::OnDrawItem(wxDC& dc, const wxRect& rect, size_t n) const\n{\n\tint y = rect.y + SPACE_UP;\n\n\tconst Bitmap* bmp = m_items[n]->getBitmap();\n\tif (bmp)\n\t{\n\t\tconst wxBitmap* wxBmp = bmp->getBitmap();\n\t\tif (wxBmp) \n\t\t{\n\t\t\t\/\/ bmp\n\t\t\tint x = wxBmp->GetWidth() > rect.width ? 0 : (rect.width - wxBmp->GetWidth()) * 0.5f;\n\t\t\tdc.DrawBitmap(*wxBmp, x, y);\n\n\t\t\t\/\/ info\n\t\t\twxString info = m_items[n]->getInfo();\n\t\t\tdc.SetFont(wxFont(18, wxDEFAULT, wxNORMAL, wxNORMAL));\n\t\t\t\/\/dc.SetTextForeground(wxColour(0xFF, 0x20, 0xFF));\n\t\t\twxSize size = dc.GetTextExtent(info);\n\t\t\t\/\/dc.DrawText(info, rect.x\/* + rect.width * 0.5f - size.GetWidth() * 0.5f*\/, y);\n\t\t\tdc.DrawText(info, rect.x + SPACE_UP, y);\n\n\t\t\ty += wxBmp->GetHeight();\n\t\t}\n\t}\n\n\t\/\/ name\n\twxString name = m_items[n]->getName();\n\tdc.SetFont(wxFont(10, wxDEFAULT, wxNORMAL, wxNORMAL));\n\twxSize size = dc.GetTextExtent(name);\n\tdc.DrawText(name, rect.x + rect.width * 0.5f - size.GetWidth() * 0.5f, y + SPACE_UP);\n}\n\n\/\/ void VerticalImageList::OnDrawBackground(wxDC& dc, const wxRect& rect, size_t n) const\n\/\/ {\n\/\/ \tdc.SetPen(*wxRED_PEN);\n\/\/ \tdc.DrawRectangle(rect);\n\/\/ }\n\nvoid VerticalImageList::OnDrawSeparator(wxDC& dc, wxRect& rect, size_t n) const\n{\n\tdc.SetPen(wxPen(wxColour(0, 0, 0), 3));\n\tdc.DrawLine(rect.GetLeftBottom(), rect.GetRightBottom());\n}\n\nwxCoord VerticalImageList::OnMeasureItem(size_t n) const\n{\n\tint size = SPACE_UP + SPACE_DOWN;\n\tconst Bitmap* bmp = m_items[n]->getBitmap();\n\tif (bmp) {\n\t\tconst wxBitmap* wxBmp = bmp->getBitmap();\n\t\tif (wxBmp) {\n\t\t\tsize = wxBmp->GetHeight() + SPACE_UP + SPACE_DOWN;\n\t\t}\n\t}\n\treturn size;\n}\n\nvoid VerticalImageList::onDragInit(wxMouseEvent& event)\n{\n\tif (event.Dragging())\n\t{\n\t\twxTextDataObject tdo(m_name + \",\" + wxString::FromDouble(GetSelection()));\n\t\twxDropSource ds(tdo);\n\t\tds.DoDragDrop(wxDrag_CopyOnly);\n\t}\n}\n} \/\/ d2d<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include \"Font.h\"\n\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <hb-ft.h>\n\n#include \"Extensions.h\"\n#include \"Image.h\"\n#include \"TextureTools\/Atlas.h\"\n\nnamespace Magnum { namespace Text {\n\nFont::Font(FontRenderer& renderer, const std::string& fontFile, GLfloat size): _size(size) {\n #ifndef MAGNUM_TARGET_GLES\n MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_rg);\n #else\n MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::EXT::texture_rg);\n #endif\n\n \/* Create FreeType font *\/\n CORRADE_INTERNAL_ASSERT(FT_New_Face(renderer.library(), fontFile.c_str(), 0, &_ftFont) == 0);\n CORRADE_INTERNAL_ASSERT(FT_Set_Char_Size(_ftFont, 0, _size*64, 100, 100) == 0);\n\n \/* Create Harfbuzz font *\/\n _hbFont = hb_ft_font_create(_ftFont, nullptr);\n\n \/* Set up the texture *\/\n _texture.setWrapping(Texture2D::Wrapping::ClampToEdge)\n ->setMinificationFilter(Texture2D::Filter::LinearInterpolation)\n ->setMagnificationFilter(Texture2D::Filter::LinearInterpolation);\n}\n\nvoid Font::prerender(const std::string& characters, const Vector2i& atlasSize) {\n glyphs.clear();\n\n \/** @bug Crash when atlas is too small *\/\n \/** @todo Get rid of duplicate characters *\/\n\n \/* Get character codes from string *\/\n \/** @todo proper UTF-8 decoding *\/\n std::vector<std::uint32_t> charCodes(characters.begin(), characters.end());\n\n \/* Get character indices *\/\n std::vector<FT_UInt> charIndices;\n charIndices.push_back(0);\n for(std::uint32_t charCode: charCodes)\n charIndices.push_back(FT_Get_Char_Index(_ftFont, charCode));\n\n \/* Sizes of all characters *\/\n std::vector<Vector2i> charSizes;\n charSizes.reserve(charIndices.size());\n for(FT_UInt c: charIndices) {\n CORRADE_INTERNAL_ASSERT(FT_Load_Glyph(_ftFont, c, FT_LOAD_DEFAULT) == 0);\n charSizes.push_back((Vector2i(_ftFont->glyph->metrics.width, _ftFont->glyph->metrics.height))\/64);\n }\n\n \/* Create texture atlas *\/\n std::vector<Rectanglei> charPositions = TextureTools::atlas(atlasSize, charSizes);\n\n \/* Render all characters to the atlas and create character map *\/\n glyphs.reserve(charPositions.size());\n unsigned char* pixmap = new unsigned char[atlasSize.product()]();\n Image2D image(atlasSize, Image2D::Format::Red, Image2D::Type::UnsignedByte, pixmap);\n for(std::size_t i = 0; i != charPositions.size(); ++i) {\n \/* Load and render glyph *\/\n \/** @todo B&W only *\/\n FT_GlyphSlot glyph = _ftFont->glyph;\n CORRADE_INTERNAL_ASSERT(FT_Load_Glyph(_ftFont, charIndices[i], FT_LOAD_DEFAULT) == 0);\n CORRADE_INTERNAL_ASSERT(FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL) == 0);\n\n \/* Copy rendered bitmap to texture image *\/\n const FT_Bitmap& bitmap = glyph->bitmap;\n CORRADE_INTERNAL_ASSERT(std::abs(bitmap.width-charPositions[i].width()) <= 2);\n CORRADE_INTERNAL_ASSERT(std::abs(bitmap.rows-charPositions[i].height()) <= 2);\n for(std::int32_t yin = 0, yout = charPositions[i].bottom(), ymax = bitmap.rows; yin != ymax; ++yin, ++yout)\n for(std::int32_t xin = 0, xout = charPositions[i].left(), xmax = bitmap.width; xin != xmax; ++xin, ++xout)\n pixmap[yout*atlasSize.x() + xout] = bitmap.buffer[(bitmap.rows-yin-1)*bitmap.width + xin];\n\n \/* Save character texture position and texture coordinates for given character index *\/\n glyphs.insert({charIndices[i], std::make_tuple(\n Rectangle::fromSize(Vector2(glyph->bitmap_left, glyph->bitmap_top-charPositions[i].height())\/_size,\n Vector2(charPositions[i].size())\/_size),\n Rectangle(Vector2(charPositions[i].bottomLeft())\/atlasSize,\n Vector2(charPositions[i].topRight())\/atlasSize)\n )});\n }\n\n \/* Set texture data *\/\n #ifndef MAGNUM_TARGET_GLES\n _texture.setImage(0, Texture2D::InternalFormat::R8, &image);\n #else\n _texture.setImage(0, Texture2D::InternalFormat::Red, &image);\n #endif\n}\n\nvoid Font::destroy() {\n if(!_ftFont) return;\n\n hb_font_destroy(_hbFont);\n FT_Done_Face(_ftFont);\n}\n\nvoid Font::move() {\n _hbFont = nullptr;\n _ftFont = nullptr;\n}\n\nFont::~Font() { destroy(); }\n\nFont::Font(Font&& other): glyphs(std::move(other.glyphs)), _texture(std::move(other._texture)), _ftFont(other._ftFont), _hbFont(other._hbFont), _size(other._size) {\n other.move();\n}\n\nFont& Font::operator=(Font&& other) {\n destroy();\n\n glyphs = std::move(other.glyphs);\n _texture = std::move(other._texture);\n _ftFont = other._ftFont;\n _hbFont = other._hbFont;\n _size = other._size;\n\n other.move();\n return *this;\n}\n\nconst std::tuple<Rectangle, Rectangle>& Font::operator[](std::uint32_t character) const {\n auto it = glyphs.find(character);\n\n if(it == glyphs.end())\n return glyphs.at(0);\n return it->second;\n}\n\n}}\n<commit_msg>Text: removing duplicate glyphs in Font::prerender().<commit_after>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include \"Font.h\"\n\n#include <algorithm>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include <hb-ft.h>\n\n#include \"Extensions.h\"\n#include \"Image.h\"\n#include \"TextureTools\/Atlas.h\"\n\nnamespace Magnum { namespace Text {\n\nFont::Font(FontRenderer& renderer, const std::string& fontFile, GLfloat size): _size(size) {\n #ifndef MAGNUM_TARGET_GLES\n MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::ARB::texture_rg);\n #else\n MAGNUM_ASSERT_EXTENSION_SUPPORTED(Extensions::GL::EXT::texture_rg);\n #endif\n\n \/* Create FreeType font *\/\n CORRADE_INTERNAL_ASSERT(FT_New_Face(renderer.library(), fontFile.c_str(), 0, &_ftFont) == 0);\n CORRADE_INTERNAL_ASSERT(FT_Set_Char_Size(_ftFont, 0, _size*64, 100, 100) == 0);\n\n \/* Create Harfbuzz font *\/\n _hbFont = hb_ft_font_create(_ftFont, nullptr);\n\n \/* Set up the texture *\/\n _texture.setWrapping(Texture2D::Wrapping::ClampToEdge)\n ->setMinificationFilter(Texture2D::Filter::LinearInterpolation)\n ->setMagnificationFilter(Texture2D::Filter::LinearInterpolation);\n}\n\nvoid Font::prerender(const std::string& characters, const Vector2i& atlasSize) {\n glyphs.clear();\n\n \/** @bug Crash when atlas is too small *\/\n\n \/* Get character codes from string *\/\n \/** @todo proper UTF-8 decoding *\/\n std::vector<std::uint32_t> charCodes(characters.begin(), characters.end());\n\n \/* Get character indices *\/\n std::vector<FT_UInt> charIndices;\n charIndices.push_back(0);\n for(std::uint32_t charCode: charCodes)\n charIndices.push_back(FT_Get_Char_Index(_ftFont, charCode));\n\n \/* Remove duplicates (e.g. uppercase and lowercase mapped to same glyph) *\/\n std::sort(charIndices.begin(), charIndices.end());\n charIndices.erase(std::unique(charIndices.begin(), charIndices.end()), charIndices.end());\n\n \/* Sizes of all characters *\/\n std::vector<Vector2i> charSizes;\n charSizes.reserve(charIndices.size());\n for(FT_UInt c: charIndices) {\n CORRADE_INTERNAL_ASSERT(FT_Load_Glyph(_ftFont, c, FT_LOAD_DEFAULT) == 0);\n charSizes.push_back((Vector2i(_ftFont->glyph->metrics.width, _ftFont->glyph->metrics.height))\/64);\n }\n\n \/* Create texture atlas *\/\n std::vector<Rectanglei> charPositions = TextureTools::atlas(atlasSize, charSizes);\n\n \/* Render all characters to the atlas and create character map *\/\n glyphs.reserve(charPositions.size());\n unsigned char* pixmap = new unsigned char[atlasSize.product()]();\n Image2D image(atlasSize, Image2D::Format::Red, Image2D::Type::UnsignedByte, pixmap);\n for(std::size_t i = 0; i != charPositions.size(); ++i) {\n \/* Load and render glyph *\/\n \/** @todo B&W only *\/\n FT_GlyphSlot glyph = _ftFont->glyph;\n CORRADE_INTERNAL_ASSERT(FT_Load_Glyph(_ftFont, charIndices[i], FT_LOAD_DEFAULT) == 0);\n CORRADE_INTERNAL_ASSERT(FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL) == 0);\n\n \/* Copy rendered bitmap to texture image *\/\n const FT_Bitmap& bitmap = glyph->bitmap;\n CORRADE_INTERNAL_ASSERT(std::abs(bitmap.width-charPositions[i].width()) <= 2);\n CORRADE_INTERNAL_ASSERT(std::abs(bitmap.rows-charPositions[i].height()) <= 2);\n for(std::int32_t yin = 0, yout = charPositions[i].bottom(), ymax = bitmap.rows; yin != ymax; ++yin, ++yout)\n for(std::int32_t xin = 0, xout = charPositions[i].left(), xmax = bitmap.width; xin != xmax; ++xin, ++xout)\n pixmap[yout*atlasSize.x() + xout] = bitmap.buffer[(bitmap.rows-yin-1)*bitmap.width + xin];\n\n \/* Save character texture position and texture coordinates for given character index *\/\n glyphs.insert({charIndices[i], std::make_tuple(\n Rectangle::fromSize(Vector2(glyph->bitmap_left, glyph->bitmap_top-charPositions[i].height())\/_size,\n Vector2(charPositions[i].size())\/_size),\n Rectangle(Vector2(charPositions[i].bottomLeft())\/atlasSize,\n Vector2(charPositions[i].topRight())\/atlasSize)\n )});\n }\n\n \/* Set texture data *\/\n #ifndef MAGNUM_TARGET_GLES\n _texture.setImage(0, Texture2D::InternalFormat::R8, &image);\n #else\n _texture.setImage(0, Texture2D::InternalFormat::Red, &image);\n #endif\n}\n\nvoid Font::destroy() {\n if(!_ftFont) return;\n\n hb_font_destroy(_hbFont);\n FT_Done_Face(_ftFont);\n}\n\nvoid Font::move() {\n _hbFont = nullptr;\n _ftFont = nullptr;\n}\n\nFont::~Font() { destroy(); }\n\nFont::Font(Font&& other): glyphs(std::move(other.glyphs)), _texture(std::move(other._texture)), _ftFont(other._ftFont), _hbFont(other._hbFont), _size(other._size) {\n other.move();\n}\n\nFont& Font::operator=(Font&& other) {\n destroy();\n\n glyphs = std::move(other.glyphs);\n _texture = std::move(other._texture);\n _ftFont = other._ftFont;\n _hbFont = other._hbFont;\n _size = other._size;\n\n other.move();\n return *this;\n}\n\nconst std::tuple<Rectangle, Rectangle>& Font::operator[](std::uint32_t character) const {\n auto it = glyphs.find(character);\n\n if(it == glyphs.end())\n return glyphs.at(0);\n return it->second;\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2014 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef FAINT_MEASURE_HH\n#define FAINT_MEASURE_HH\n#include <vector>\n#include \"geo\/geo-fwd.hh\"\n#include \"geo\/primitive.hh\"\n\nnamespace faint{\n\n\/\/ Returns the angle of the line in the interval [0, 2pi],\n\/\/ with angles increasing counter-clockwise.\n\/\/ <..\/doc\/angle360_ccw.png>\nAngle angle360_ccw(const LineSegment&);\n\n\/\/ Note: returns an 1x1 rectangle with TopLeft IntPoint,\n\/\/ This is required by the variadic bounding_rect implementation.\nIntRect bounding_rect(const IntPoint&);\n\nIntRect bounding_rect(const IntPoint&, const IntPoint&);\nIntRect bounding_rect(const IntLineSegment&);\nIntRect bounding_rect(const IntRect&, const IntRect&);\n\n\/\/ Note: Returns a 1x1 rectangle situated at Point.\n\/\/ This is required by the variadic bounding_rect implementation.\nRect bounding_rect(const Point&);\n\nRect bounding_rect(const Point&, const Point&);\nRect bounding_rect(const Rect&);\nRect bounding_rect(const Rect&, const Rect&);\nRect bounding_rect(const LineSegment&);\n\n\ntemplate<class A, class ...B>\nauto bounding_rect(const A& head, const B&... tail)\n -> decltype(bounding_rect(head))\n{\n return bounding_rect(bounding_rect(head), bounding_rect(tail...));\n}\n\n\/\/ Returns the positive distance between the points. Insensitive to\n\/\/ ordering.\ncoord distance(const IntPoint&, const IntPoint&);\ncoord distance(const Point&, const Point&);\n\n\/\/ Approximates the length of the Bezier curve from start, using the\n\/\/ line distance for the specified number of subdivisions. A higher\n\/\/ number of subdivisions gives a better approximation, but is more\n\/\/ time consuming.\ncoord distance(const Point& start, const CubicBezier&, int subdivisions);\n\n\/\/ a and b are diameters\ncoord ellipse_perimeter(coord a, coord b);\ncoord ellipse_perimeter(const Radii&);\n\n\/\/ Returns the angle between the positive x-axis and the line in the\n\/\/ interval (-pi, pi], with positive angles on the lower semi-circle\n\/\/ (Pretty much the same as atan2!)\n\/\/ <..\/doc\/line_angle_cw.png>\nAngle line_angle_cw(const LineSegment&);\n\nPoint mid_point(const LineSegment&);\nPoint mid_point(const Point&, const Point&);\n\n\/\/ Returns the mid_point between all points in the vector. The\n\/\/ returned vector will contain one point less than source vector,\n\/\/ or no points if the source was empty.\nstd::vector<Point> mid_points(const std::vector<Point>&);\n\n\/\/ Returns the points with the mid-points between adjacent points\n\/\/ interspersed.\n\/\/ For {p1, p2, p3}, returns {p1, m(p1, p2), p2, m(p2, p3), p3}\nstd::vector<Point> with_mid_points(const std::vector<Point>&);\n\n\/\/ Returns the points with the mid-points between adjacent points\n\/\/ interspersed, including the mid-point between the last and first\n\/\/ points (as implied by cyclic).\n\/\/ For {p1, p2, p3}, returns {m(p3, p1), p1, m(p2, p1), p2, m(p2, p3), p3}\nstd::vector<Point> with_mid_points_cyclic(const std::vector<Point>&);\n\ncoord perimeter(const std::vector<PathPt>&);\n\n} \/\/ namespace\n\n#endif\n<commit_msg>Whitespace.<commit_after>\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2014 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef FAINT_MEASURE_HH\n#define FAINT_MEASURE_HH\n#include <vector>\n#include \"geo\/geo-fwd.hh\"\n#include \"geo\/primitive.hh\"\n\nnamespace faint{\n\n\/\/ Returns the angle of the line in the interval [0, 2pi],\n\/\/ with angles increasing counter-clockwise.\n\/\/ <..\/doc\/angle360_ccw.png>\nAngle angle360_ccw(const LineSegment&);\n\n\/\/ Note: returns an 1x1 rectangle with TopLeft IntPoint,\n\/\/ This is required by the variadic bounding_rect implementation.\nIntRect bounding_rect(const IntPoint&);\n\nIntRect bounding_rect(const IntPoint&, const IntPoint&);\nIntRect bounding_rect(const IntLineSegment&);\nIntRect bounding_rect(const IntRect&, const IntRect&);\n\n\/\/ Note: Returns a 1x1 rectangle situated at Point.\n\/\/ This is required by the variadic bounding_rect implementation.\nRect bounding_rect(const Point&);\n\nRect bounding_rect(const Point&, const Point&);\nRect bounding_rect(const Rect&);\nRect bounding_rect(const Rect&, const Rect&);\nRect bounding_rect(const LineSegment&);\n\ntemplate<class A, class ...B>\nauto bounding_rect(const A& head, const B&... tail)\n -> decltype(bounding_rect(head))\n{\n return bounding_rect(bounding_rect(head), bounding_rect(tail...));\n}\n\n\/\/ Returns the positive distance between the points. Insensitive to\n\/\/ ordering.\ncoord distance(const IntPoint&, const IntPoint&);\ncoord distance(const Point&, const Point&);\n\n\/\/ Approximates the length of the Bezier curve from start, using the\n\/\/ line distance for the specified number of subdivisions. A higher\n\/\/ number of subdivisions gives a better approximation, but is more\n\/\/ time consuming.\ncoord distance(const Point& start, const CubicBezier&, int subdivisions);\n\n\/\/ a and b are diameters\ncoord ellipse_perimeter(coord a, coord b);\ncoord ellipse_perimeter(const Radii&);\n\n\/\/ Returns the angle between the positive x-axis and the line in the\n\/\/ interval (-pi, pi], with positive angles on the lower semi-circle\n\/\/ (Pretty much the same as atan2!)\n\/\/ <..\/doc\/line_angle_cw.png>\nAngle line_angle_cw(const LineSegment&);\n\nPoint mid_point(const LineSegment&);\nPoint mid_point(const Point&, const Point&);\n\n\/\/ Returns the mid_point between all points in the vector. The\n\/\/ returned vector will contain one point less than source vector,\n\/\/ or no points if the source was empty.\nstd::vector<Point> mid_points(const std::vector<Point>&);\n\n\/\/ Returns the points with the mid-points between adjacent points\n\/\/ interspersed.\n\/\/ For {p1, p2, p3}, returns {p1, m(p1, p2), p2, m(p2, p3), p3}\nstd::vector<Point> with_mid_points(const std::vector<Point>&);\n\n\/\/ Returns the points with the mid-points between adjacent points\n\/\/ interspersed, including the mid-point between the last and first\n\/\/ points (as implied by cyclic).\n\/\/ For {p1, p2, p3}, returns {m(p3, p1), p1, m(p2, p1), p2, m(p2, p3), p3}\nstd::vector<Point> with_mid_points_cyclic(const std::vector<Point>&);\n\ncoord perimeter(const std::vector<PathPt>&);\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"drake\/systems\/plants\/RigidBodySystem.h\"\n#include \"drake\/util\/testUtil.h\"\n\nusing namespace std;\nusing namespace Drake;\nusing namespace Eigen;\n\n\nVector3d getAccelerometerOutput(shared_ptr<RigidBodySystem> const& sys, Vector3d const& rpy, Vector4d const& u) {\n VectorXd x0 = VectorXd::Zero(sys->getNumStates());\n auto const & tree = sys->getRigidBodyTree();\n x0.head(tree->num_positions) = tree->getZeroConfiguration();\n x0.segment(3, 4) = rpy2quat(rpy);\n auto const& output = sys->output(0, x0, u).tail<3>();\n return output;\n}\n\n\nint main(int argc, char* argv[]) { \n\n DrakeJoint::FloatingBaseType floating_base_type = DrakeJoint::QUATERNION;\n auto rigid_body_sys = make_shared<RigidBodySystem>();\n rigid_body_sys->addRobotFromFile(getDrakePath()+\"\/examples\/Quadrotor\/quadrotor.urdf\", floating_base_type);\n auto const & tree = rigid_body_sys->getRigidBodyTree();\n auto sensor_frame = tree->frames[0]; \/\/this is a propellor frame. probably want a body frame for this\n auto accelerometer = make_shared<RigidBodyAccelerometer>(*rigid_body_sys, \"accelerometer\", sensor_frame);\n rigid_body_sys->addSensor(accelerometer);\n const double g = 9.81;\n const double tol = 1e-6;\n const Vector4d hoverThrust = 1.226250 * Vector4d::Ones();\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d::Zero(), Vector4d::Zero()),\n Vector3d(0, 0, -g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI, 0, 0), Vector4d::Zero()), \/\/inverted\n Vector3d(0, 0, g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d::Zero(), hoverThrust),\n Vector3d(0, 0, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI, 0, 0), hoverThrust), \/\/inverted with thrust\n Vector3d(0, 0, 2*g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI\/2, 0, 0), Vector4d::Zero()),\n Vector3d(0, -g, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(-M_PI\/2, 0, 0), Vector4d::Zero()),\n Vector3d(0, g, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(0, M_PI\/2, 0), Vector4d::Zero()),\n Vector3d(g, 0, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(0, -M_PI\/2, 0), Vector4d::Zero()),\n Vector3d(-g, 0, 0),\n tol);\n\n}\n<commit_msg>fixed Eigen invalid memory read issue<commit_after>#include \"drake\/systems\/plants\/RigidBodySystem.h\"\n#include \"drake\/util\/testUtil.h\"\n\nusing namespace std;\nusing namespace Drake;\nusing namespace Eigen;\n\n\nVector3d getAccelerometerOutput(shared_ptr<RigidBodySystem> const& sys, Vector3d const& rpy, Vector4d const& u) {\n VectorXd x0 = VectorXd::Zero(sys->getNumStates());\n auto const & tree = sys->getRigidBodyTree();\n x0.head(tree->num_positions) = tree->getZeroConfiguration();\n x0.segment(3, 4) = rpy2quat(rpy);\n auto const& system_output = sys->output(0, x0, u);\n return system_output.tail<3>();\n}\n\n\nint main(int argc, char* argv[]) { \n\n DrakeJoint::FloatingBaseType floating_base_type = DrakeJoint::QUATERNION;\n auto rigid_body_sys = make_shared<RigidBodySystem>();\n rigid_body_sys->addRobotFromFile(getDrakePath()+\"\/examples\/Quadrotor\/quadrotor.urdf\", floating_base_type);\n auto const & tree = rigid_body_sys->getRigidBodyTree();\n auto sensor_frame = tree->frames[0]; \/\/this is a propellor frame. probably want a body frame for this\n auto accelerometer = make_shared<RigidBodyAccelerometer>(*rigid_body_sys, \"accelerometer\", sensor_frame);\n rigid_body_sys->addSensor(accelerometer);\n const double g = 9.81;\n const double tol = 1e-6;\n const Vector4d hoverThrust = 1.226250 * Vector4d::Ones();\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d::Zero(), Vector4d::Zero()),\n Vector3d(0, 0, -g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI, 0, 0), Vector4d::Zero()), \/\/inverted\n Vector3d(0, 0, g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d::Zero(), hoverThrust),\n Vector3d(0, 0, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI, 0, 0), hoverThrust), \/\/inverted with thrust\n Vector3d(0, 0, 2*g),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(M_PI\/2, 0, 0), Vector4d::Zero()),\n Vector3d(0, -g, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(-M_PI\/2, 0, 0), Vector4d::Zero()),\n Vector3d(0, g, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(0, M_PI\/2, 0), Vector4d::Zero()),\n Vector3d(g, 0, 0),\n tol);\n\n valuecheckMatrix(getAccelerometerOutput(rigid_body_sys, Vector3d(0, -M_PI\/2, 0), Vector4d::Zero()),\n Vector3d(-g, 0, 0),\n tol);\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include \"nbind\/api.h\"\n#include \"control.h\"\n#include \"ui.h\"\n\nclass UiCheckbox : public UiControl {\n\tDEFINE_EVENT(onToggled)\n\n public:\n\tUiCheckbox(std::string text);\n\tUiCheckbox();\n\tDEFINE_CONTROL_METHODS()\n\tvoid setText(std::string text);\n\tstd::string getText();\n\tvoid setChecked(bool checked);\n\tbool getChecked();\n\t~UiCheckbox();\n\tvoid onDestroy(uiControl *control) override;\n};\n\nvoid UiCheckbox::onDestroy(uiControl *control) {\n\t\/*\n\t\tfreeing event callbacks to allow JS to garbage collect this class\n\t\twhen there are no references to it left in JS code.\n\t*\/\n\tDISPOSE_EVENT(onToggled);\n}\n\nUiCheckbox::~UiCheckbox() {\n\t\/\/ printf(\"UiCheckbox %p destroyed with wrapper %p.\\n\", getHandle(), this);\n}\n\nIMPLEMENT_EVENT(UiCheckbox, uiCheckbox, onToggled, uiCheckboxOnToggled)\n\nUiCheckbox::UiCheckbox(std::string text)\n\t: UiControl(uiControl(uiNewCheckbox(text.c_str()))) {}\nUiCheckbox::UiCheckbox() : UiControl(uiControl(uiNewCheckbox(\"\"))) {}\n\nINHERITS_CONTROL_METHODS(UiCheckbox)\n\nvoid UiCheckbox::setText(std::string text) {\n\tuiCheckboxSetText(uiCheckbox(getHandle()), text.c_str());\n}\n\nstd::string UiCheckbox::getText() {\n\tchar *char_ptr = uiCheckboxText(uiCheckbox(getHandle()));\n\tstd::string s(char_ptr);\n\tuiFreeText(char_ptr);\n\treturn s;\n}\n\nvoid UiCheckbox::setChecked(bool checked) {\n\tuiCheckboxSetChecked(uiCheckbox(getHandle()), checked);\n\tif (onToggledCallback != NULL) {\n\t\t(*onToggledCallback)();\n\t}\n}\n\nbool UiCheckbox::getChecked() {\n\treturn uiCheckboxChecked(uiCheckbox(getHandle()));\n}\n\nNBIND_CLASS(UiCheckbox) {\n\tconstruct<std::string>();\n\tconstruct<>();\n\tDECLARE_CHILD_CONTROL_METHODS()\n\tgetset(getChecked, setChecked);\n\tgetset(getText, setText);\n\tmethod(getChecked);\n\tmethod(setChecked);\n\tmethod(getText);\n\tmethod(setText);\n\tmethod(onToggled);\n}\n<commit_msg>removed macro -> UiCheckbox<commit_after>#include <string>\n#include \"nbind\/api.h\"\n#include \"control.h\"\n#include \"ui.h\"\n\nclass UiCheckbox : public UiControl {\n\tDEFINE_EVENT(onToggled)\n\n public:\n\tUiCheckbox(std::string text);\n\tUiCheckbox();\n\tvoid setText(std::string text);\n\tstd::string getText();\n\tvoid setChecked(bool checked);\n\tbool getChecked();\n\t~UiCheckbox();\n\tvoid onDestroy(uiControl *control) override;\n};\n\nvoid UiCheckbox::onDestroy(uiControl *control) {\n\t\/*\n\t\tfreeing event callbacks to allow JS to garbage collect this class\n\t\twhen there are no references to it left in JS code.\n\t*\/\n\tDISPOSE_EVENT(onToggled);\n}\n\nUiCheckbox::~UiCheckbox() {\n\t\/\/ printf(\"UiCheckbox %p destroyed with wrapper %p.\\n\", getHandle(), this);\n}\n\nIMPLEMENT_EVENT(UiCheckbox, uiCheckbox, onToggled, uiCheckboxOnToggled)\n\nUiCheckbox::UiCheckbox(std::string text)\n\t: UiControl(uiControl(uiNewCheckbox(text.c_str()))) {}\nUiCheckbox::UiCheckbox() : UiControl(uiControl(uiNewCheckbox(\"\"))) {}\n\nvoid UiCheckbox::setText(std::string text) {\n\tuiCheckboxSetText(uiCheckbox(getHandle()), text.c_str());\n}\n\nstd::string UiCheckbox::getText() {\n\tchar *char_ptr = uiCheckboxText(uiCheckbox(getHandle()));\n\tstd::string s(char_ptr);\n\tuiFreeText(char_ptr);\n\treturn s;\n}\n\nvoid UiCheckbox::setChecked(bool checked) {\n\tuiCheckboxSetChecked(uiCheckbox(getHandle()), checked);\n\tif (onToggledCallback != NULL) {\n\t\t(*onToggledCallback)();\n\t}\n}\n\nbool UiCheckbox::getChecked() {\n\treturn uiCheckboxChecked(uiCheckbox(getHandle()));\n}\n\nNBIND_CLASS(UiCheckbox) {\n\tinherit(UiControl);\n\tconstruct<std::string>();\n\tconstruct<>();\n\tgetset(getChecked, setChecked);\n\tgetset(getText, setText);\n\tmethod(getChecked);\n\tmethod(setChecked);\n\tmethod(getText);\n\tmethod(setText);\n\tmethod(onToggled);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"VDTexture.h\"\n\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/Xml.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nnamespace VideoDromm {\n\tVDTexture::VDTexture(TextureType aType)\n\t\t: mFilePathOrText(\"\")\n\t\t, mName(\"\")\n\t\t, mTopDown(true)\n\t\t, mFlipV(false)\n\t\t, mFlipH(true)\n\t\t, mWidth(640)\n\t\t, mHeight(480)\n\t{\n\n\t\tif (mName.length() == 0) {\n\t\t\tmName = mFilePathOrText;\n\t\t}\n\t\t\/\/ init the texture whatever happens next\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tmTexture = ci::gl::Texture::create(ci::loadImage(mFilePathOrText), ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t}\n\t\telse {\n\t\t\tmTexture = ci::gl::Texture::create(mWidth, mHeight, ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t}\n\t}\n\tVDTexture::~VDTexture(void) {\n\n\t}\n\n\tVDTextureList VDTexture::readSettings(const DataSourceRef &source)\n\t{\n\t\tXmlTree\t\t\tdoc;\n\t\tVDTextureList\tvdtexturelist;\n\n\t\t\/\/ try to load the specified xml file\n\t\ttry { doc = XmlTree(source); }\n\t\tcatch (...) { return vdtexturelist; }\n\n\t\t\/\/ check if this is a valid file \n\t\tbool isOK = doc.hasChild(\"textures\");\n\t\tif (!isOK) return vdtexturelist;\n\n\t\t\/\/\n\t\tif (isOK) {\n\n\t\t\tXmlTree texturesXml = doc.getChild(\"textures\");\n\n\t\t\t\/\/ iterate textures\n\t\t\tfor (XmlTree::ConstIter child = texturesXml.begin(\"texture\"); child != texturesXml.end(); ++child) {\n\t\t\t\t\/\/ create texture of the correct type\n\t\t\t\tstd::string texturetype = child->getAttributeValue<std::string>(\"texturetype\", \"unknown\");\n\t\t\t\tXmlTree detailsXml = child->getChild(\"details\");\n\n\t\t\t\t\/\/std::string filepath = detailsXml.getAttributeValue<std::string>(\"filepath\", \"\");\n\t\t\t\tif (texturetype == \"image\") {\n\t\t\t\t\tTextureImageRef t(new TextureImage());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"text\") {\n\t\t\t\t\tTextureTextRef t(new TextureText());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"movie\") {\n\t\t\t\t\tTextureMovieRef t(new TextureMovie());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"camera\") {\n\t\t\t\t\tTextureCameraRef t(new TextureCamera());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn vdtexturelist;\n\t}\n\n\tvoid VDTexture::writeSettings(const VDTextureList &vdtexturelist, const ci::DataTargetRef &target) {\n\n\t\t\/\/ create config document and root <textures>\n\t\tXmlTree\t\t\tdoc;\n\t\tdoc.setTag(\"textures\");\n\t\tdoc.setAttribute(\"version\", \"1.0\");\n\n\t\t\/\/ \n\t\tfor (unsigned i = 0; i < vdtexturelist.size(); ++i) {\n\t\t\t\/\/ create <texture>\n\t\t\tXmlTree\t\t\ttexture;\n\t\t\ttexture.setTag(\"texture\");\n\t\t\ttexture.setAttribute(\"id\", i + 1);\n\t\t\tswitch (vdtexturelist[i]->mType) {\n\t\t\tcase IMAGE: texture.setAttribute(\"texturetype\", \"image\"); break;\n\t\t\tcase TEXT: texture.setAttribute(\"texturetype\", \"text\"); break;\n\t\t\tcase MOVIE: texture.setAttribute(\"texturetype\", \"movie\"); break;\n\t\t\tcase CAMERA: texture.setAttribute(\"texturetype\", \"camera\"); break;\n\t\t\tdefault: texture.setAttribute(\"texturetype\", \"unknown\"); break;\n\t\t\t}\n\t\t\t\/\/ details specific to texture type\n\t\t\ttexture.push_back(vdtexturelist[i]->toXml());\n\n\t\t\t\/\/ add texture doc\n\t\t\t\/\/texture.setAttribute(\"filepath\", vdtexturelist[i]->mFilePathOrText);\n\t\t\tdoc.push_back(texture);\n\t\t}\n\n\t\t\/\/ write file\n\t\tdoc.write(target);\n\t}\n\tXmlTree\tVDTexture::toXml() const\n\t{\n\t\tXmlTree\t\txml;\n\t\txml.setTag(\"details\");\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\txml.setAttribute(\"width\", mWidth);\n\t\txml.setAttribute(\"height\", mHeight);\n\n\t\treturn xml;\n\t}\n\n\tvoid VDTexture::fromXml(const XmlTree &xml)\n\t{\n\n\t}\n\n\tint VDTexture::getTextureWidth() {\n\t\treturn mWidth;\n\t};\n\n\tint VDTexture::getTextureHeight() {\n\t\treturn mHeight;\n\t};\n\n\tci::ivec2 VDTexture::getSize() {\n\t\treturn mTexture->getSize();\n\t}\n\n\tci::Area VDTexture::getBounds() {\n\t\treturn mTexture->getBounds();\n\t}\n\n\tGLuint VDTexture::getId() {\n\t\treturn mTexture->getId();\n\t}\n\n\tstd::string VDTexture::getName(){\n\t\treturn mName;\n\t}\n\n\tci::gl::TextureRef VDTexture::getTexture() {\n\t\treturn mTexture;\n\t}\n\t\/\/ --------- child classes\n\tTextureImage::TextureImage() {\n\t}\n\tXmlTree\tTextureImage::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"path\", getAssetPath(\"\").string());\n\t\txml.setAttribute(\"topdown\", mTopDown);\n\t\treturn xml;\n\t}\n\n\tvoid TextureImage::fromXml(const XmlTree &xml)\n\t{\n\t\tVDTexture::fromXml(xml);\n\t\tmType = IMAGE;\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmTopDown = xml.getAttributeValue<bool>(\"topdown\", \"false\");\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tfs::path fullPath = getAssetPath(\"\") \/ mFilePathOrText;\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\tif (fs::exists(fullPath)) {\n\t\t\t\t\/\/ TODO mTopDown has no effect!?!\n\t\t\t\tmTexture = ci::gl::Texture::create(loadImage(loadAsset(mFilePathOrText)), ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmTexture = ci::gl::Texture::create(mWidth, mHeight, ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t\t}\n\t\t}\n\t}\n\tci::gl::Texture2dRef TextureImage::getTexture() {\n\t\treturn mTexture;\n\t}\n\tTextureImage::~TextureImage(void) {\n\n\t}\n\t\/\/ TextureText\n\tTextureText::TextureText() {\n\t\t\/\/ font\n\t\tFont customFont(Font(loadAsset(\"Signika-Regular.ttf\"), 100));\n\t\tgl::TextureFont::Format f;\n\t\tf.enableMipmapping(true);\n\t\tmTextureFont = gl::TextureFont::create(customFont, f);\n\n\t\t\/\/ camera\n\t\tmCamDist = 600.0f;\n\t\tmCam.setPerspective(75.0f, getWindowAspectRatio(), 0.1f, 15000.0f);\n\t\tmCam.lookAt(vec3(0.0f, 0.0f, mCamDist), vec3(0), vec3(0, 1, 0));\n\t\tmCam.setLensShiftHorizontal(-0.6);\n\t\t\/\/ scene\n\t\tmSceneMatrix = mSceneDestMatrix = mat4(1.0f); \/\/ identity\n\n\t\t\/\/ init text\n\t\taddChar('Y'); addChar('O'); \n\t\tstringIndex = 0;\n\n\t\tcurrentFrame = -1;\n\t\tstartFrame = 0;\n\t\t\/\/ fbo\n\t\tgl::Fbo::Format format;\n\t\t\/\/format.setSamples( 4 ); \/\/ uncomment this to enable 4x antialiasing\n\t\tmFbo = gl::Fbo::create(mWidth, mHeight, format.depthTexture());\n\t}\n\tvoid TextureText::fromXml(const XmlTree &xml)\n\t{\n\t\tmType = TEXT;\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tfs::path fullPath = getAssetPath(\"\") \/ mFilePathOrText;\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\tif (fs::exists(fullPath)) {\n\n\t\t\t\ttry {\n\t\t\t\t\tmText = JsonTree(app::loadAsset(mFilePathOrText));\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\t\t\tmStrings.clear();\n\n\t\t\t\t\tfor (const auto &line : mText[\"lines\"]) {\n\t\t\t\t\t\tmStrings.push_back(line.getValue());\n\t\t\t\t\t}\n\n\t\t\t\t\tCI_LOG_V(\"successfully loaded \" + mFilePathOrText);\n\t\t\t\t}\n\t\t\t\tcatch (Exception &exc) {\n\t\t\t\t\tCI_LOG_EXCEPTION(\"error loading \", exc);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tXmlTree\tTextureText::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureText::getTexture() {\n#if defined( CINDER_MSW )\n\t\t\/\/ should be in update?\n\t\t\/\/addChar('O');\n\n\t\tif (frame < mStrings[stringIndex].size() - 1) {\n\t\t\tchar c[2];\n\t\t\tprintf_s(c, \"%s\", mStrings[stringIndex].substr(frame, 1).c_str());\n\t\t\taddChar(*c);\n\t\t}\n\t\tgl::ScopedFramebuffer fbScp(mFbo);\n\t\tgl::clear(Color::black());\n\t\t\/\/ setup the viewport to match the dimensions of the FBO\n\t\tgl::ScopedViewport scpVp(ivec2(0), mFbo->getSize());\n\t\tfor (vector<Character>::iterator it = mCharacters.begin(); it != mCharacters.end(); ++it)\n\t\t\tit->draw();\n\n\t\tfor (list<Character>::iterator it = mDyingCharacters.begin(); it != mDyingCharacters.end(); ++it)\n\t\t\tit->draw();\n\n\t\tif ((!mDyingCharacters.empty()) && mDyingCharacters.front().isDead())\n\t\t\tmDyingCharacters.pop_front();\n\t\treturn mFbo->getColorTexture();\n#else\n\t\treturn mTexture;\n#endif\t\t\n\t}\n#if defined( CINDER_MSW )\n\tvoid TextureText::addChar(char c)\n\t{\n\t\tif (c == 32) {\n\t\t\tc = 97;\n\t\t}\n\t\telse {\n\t\t\tc = toupper(c);\n\t\t}\n\t\tint count = mCharacters.size();\n\n\t\tif (count > 0)\n\t\t\tmSceneDestMatrix = glm::translate(mSceneDestMatrix, vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\n\t\tglm::mat4 randStartMatrix = mSceneDestMatrix;\n\t\trandStartMatrix = glm::translate(randStartMatrix, vec3(300.0f));\n\n\t\tmCharacters.push_back(Character(mTextureFont, string(&c, 1), randStartMatrix));\n\n\t\t\/\/mSceneDestMatrix.translate(vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\t\tmSceneDestMatrix = glm::translate(mSceneDestMatrix, vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\n\t\tfloat t = (count + 281) \/ 50.0f;\n\t\t\/\/mSceneDestMatrix.rotate(Vec3f(sin(t)*0.1f, cos(t)*0.2f, cos(t)*0.05f)); \/\/ makes the scene meander\n\n\t\tmCharacters.back().animIn(timeline(), mSceneDestMatrix);\n\n\t\ttimeline().apply(&mSceneMatrix, mSceneDestMatrix, 1.0f, EaseOutAtan(10));\n\n\t}\n\n\tvoid TextureText::removeChar()\n\t{\n\t\tif (!mCharacters.empty()) {\n\t\t\tmDyingCharacters.push_back(mCharacters.back());\n\t\t\tmCharacters.pop_back();\n\n\t\t\tif (!mCharacters.empty())\n\t\t\t\tmSceneDestMatrix = mCharacters.back().getDestMatrix();\n\t\t\telse\n\t\t\t\tmSceneDestMatrix = mat4(1.0f);\n\n\t\t\tmat4 randStartMatrix = glm::translate( mSceneDestMatrix, vec3(300.0f));\n\t\t\t\/\/randStartMatrix.translate(300.0f);\n\n\t\t\t\/\/randStartMatrix.rotate(getRandomVec3f(2.0f, 6.0f));\n\n\t\t\tmDyingCharacters.back().animOut(timeline(), randStartMatrix);\n\n\t\t\ttimeline().apply(&mSceneMatrix, mSceneDestMatrix, 1.0f, EaseOutAtan(10));\n\t\t}\n\t}\n#else\n\n#endif\n\tTextureText::~TextureText(void) {\n\n\t}\n\n\t\/\/ TextureMovie\n\tTextureMovie::TextureMovie() {\n\n\t}\n\tvoid TextureMovie::fromXml(const XmlTree &xml)\n\t{\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tmType = MOVIE;\n\n\t}\n\tXmlTree\tTextureMovie::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureMovie::getTexture() {\n\t\treturn mTexture;\n\t}\n\tTextureMovie::~TextureMovie(void) {\n\n\t}\n\n\t\/\/ TextureCamera\n#if (defined( CINDER_MSW) ) || (defined( CINDER_MAC ))\n\tTextureCamera::TextureCamera() {\n\t\tmFirstCameraDeviceName = \"\";\n\t\tprintDevices();\n\n\t\ttry {\n\t\t\tmCapture = Capture::create(640, 480);\n\t\t\tmCapture->start();\n\t\t}\n\t\tcatch (ci::Exception &exc) {\n\t\t\tCI_LOG_EXCEPTION(\"Failed to init capture \", exc);\n\t\t}\n\t}\n\tvoid TextureCamera::fromXml(const XmlTree &xml)\n\t{\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tmType = CAMERA;\n\n\t}\n\tXmlTree\tTextureCamera::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"camera\", mFirstCameraDeviceName);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureCamera::getTexture() {\n\t\tif (mCapture && mCapture->checkNewFrame()) {\n\t\t\tif (!mTexture) {\n\t\t\t\t\/\/ Capture images come back as top-down, and it's more efficient to keep them that way\n\t\t\t\tmTexture = gl::Texture::create(*mCapture->getSurface(), gl::Texture::Format().loadTopDown());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmTexture->update(*mCapture->getSurface());\n\t\t\t}\n\t\t}\n\t\treturn mTexture;\n\t}\n\tvoid TextureCamera::printDevices()\n\t{\n\t\tfor (const auto &device : Capture::getDevices()) {\n\t\t\tconsole() << \"Device: \" << device->getName() << \" \"\n#if defined( CINDER_COCOA_TOUCH )\n\t\t\t\t<< (device->isFrontFacing() ? \"Front\" : \"Rear\") << \"-facing\"\n#endif\n\t\t\t\t<< endl;\n\t\t\tmFirstCameraDeviceName = device->getName();\n\t\t}\n\t}\n\tTextureCamera::~TextureCamera(void) {\n\n\t}\n#else\n\n#endif\n} \/\/ namespace VideoDromm\n<commit_msg>mac fix<commit_after>#include \"VDTexture.h\"\n\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/Xml.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nnamespace VideoDromm {\n\tVDTexture::VDTexture(TextureType aType)\n\t\t: mFilePathOrText(\"\")\n\t\t, mName(\"\")\n\t\t, mTopDown(true)\n\t\t, mFlipV(false)\n\t\t, mFlipH(true)\n\t\t, mWidth(640)\n\t\t, mHeight(480)\n\t{\n\n\t\tif (mName.length() == 0) {\n\t\t\tmName = mFilePathOrText;\n\t\t}\n\t\t\/\/ init the texture whatever happens next\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tmTexture = ci::gl::Texture::create(ci::loadImage(mFilePathOrText), ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t}\n\t\telse {\n\t\t\tmTexture = ci::gl::Texture::create(mWidth, mHeight, ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t}\n\t}\n\tVDTexture::~VDTexture(void) {\n\n\t}\n\n\tVDTextureList VDTexture::readSettings(const DataSourceRef &source)\n\t{\n\t\tXmlTree\t\t\tdoc;\n\t\tVDTextureList\tvdtexturelist;\n\n\t\t\/\/ try to load the specified xml file\n\t\ttry { doc = XmlTree(source); }\n\t\tcatch (...) { return vdtexturelist; }\n\n\t\t\/\/ check if this is a valid file \n\t\tbool isOK = doc.hasChild(\"textures\");\n\t\tif (!isOK) return vdtexturelist;\n\n\t\t\/\/\n\t\tif (isOK) {\n\n\t\t\tXmlTree texturesXml = doc.getChild(\"textures\");\n\n\t\t\t\/\/ iterate textures\n\t\t\tfor (XmlTree::ConstIter child = texturesXml.begin(\"texture\"); child != texturesXml.end(); ++child) {\n\t\t\t\t\/\/ create texture of the correct type\n\t\t\t\tstd::string texturetype = child->getAttributeValue<std::string>(\"texturetype\", \"unknown\");\n\t\t\t\tXmlTree detailsXml = child->getChild(\"details\");\n\n\t\t\t\t\/\/std::string filepath = detailsXml.getAttributeValue<std::string>(\"filepath\", \"\");\n\t\t\t\tif (texturetype == \"image\") {\n\t\t\t\t\tTextureImageRef t(new TextureImage());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"text\") {\n\t\t\t\t\tTextureTextRef t(new TextureText());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"movie\") {\n\t\t\t\t\tTextureMovieRef t(new TextureMovie());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t\telse if (texturetype == \"camera\") {\n\t\t\t\t\tTextureCameraRef t(new TextureCamera());\n\t\t\t\t\tt->fromXml(detailsXml);\n\t\t\t\t\tvdtexturelist.push_back(t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn vdtexturelist;\n\t}\n\n\tvoid VDTexture::writeSettings(const VDTextureList &vdtexturelist, const ci::DataTargetRef &target) {\n\n\t\t\/\/ create config document and root <textures>\n\t\tXmlTree\t\t\tdoc;\n\t\tdoc.setTag(\"textures\");\n\t\tdoc.setAttribute(\"version\", \"1.0\");\n\n\t\t\/\/ \n\t\tfor (unsigned i = 0; i < vdtexturelist.size(); ++i) {\n\t\t\t\/\/ create <texture>\n\t\t\tXmlTree\t\t\ttexture;\n\t\t\ttexture.setTag(\"texture\");\n\t\t\ttexture.setAttribute(\"id\", i + 1);\n\t\t\tswitch (vdtexturelist[i]->mType) {\n\t\t\tcase IMAGE: texture.setAttribute(\"texturetype\", \"image\"); break;\n\t\t\tcase TEXT: texture.setAttribute(\"texturetype\", \"text\"); break;\n\t\t\tcase MOVIE: texture.setAttribute(\"texturetype\", \"movie\"); break;\n\t\t\tcase CAMERA: texture.setAttribute(\"texturetype\", \"camera\"); break;\n\t\t\tdefault: texture.setAttribute(\"texturetype\", \"unknown\"); break;\n\t\t\t}\n\t\t\t\/\/ details specific to texture type\n\t\t\ttexture.push_back(vdtexturelist[i]->toXml());\n\n\t\t\t\/\/ add texture doc\n\t\t\t\/\/texture.setAttribute(\"filepath\", vdtexturelist[i]->mFilePathOrText);\n\t\t\tdoc.push_back(texture);\n\t\t}\n\n\t\t\/\/ write file\n\t\tdoc.write(target);\n\t}\n\tXmlTree\tVDTexture::toXml() const\n\t{\n\t\tXmlTree\t\txml;\n\t\txml.setTag(\"details\");\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\txml.setAttribute(\"width\", mWidth);\n\t\txml.setAttribute(\"height\", mHeight);\n\n\t\treturn xml;\n\t}\n\n\tvoid VDTexture::fromXml(const XmlTree &xml)\n\t{\n\n\t}\n\n\tint VDTexture::getTextureWidth() {\n\t\treturn mWidth;\n\t};\n\n\tint VDTexture::getTextureHeight() {\n\t\treturn mHeight;\n\t};\n\n\tci::ivec2 VDTexture::getSize() {\n\t\treturn mTexture->getSize();\n\t}\n\n\tci::Area VDTexture::getBounds() {\n\t\treturn mTexture->getBounds();\n\t}\n\n\tGLuint VDTexture::getId() {\n\t\treturn mTexture->getId();\n\t}\n\n\tstd::string VDTexture::getName(){\n\t\treturn mName;\n\t}\n\n\tci::gl::TextureRef VDTexture::getTexture() {\n\t\treturn mTexture;\n\t}\n\t\/\/ --------- child classes\n\tTextureImage::TextureImage() {\n\t}\n\tXmlTree\tTextureImage::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"path\", getAssetPath(\"\").string());\n\t\txml.setAttribute(\"topdown\", mTopDown);\n\t\treturn xml;\n\t}\n\n\tvoid TextureImage::fromXml(const XmlTree &xml)\n\t{\n\t\tVDTexture::fromXml(xml);\n\t\tmType = IMAGE;\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmTopDown = xml.getAttributeValue<bool>(\"topdown\", \"false\");\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tfs::path fullPath = getAssetPath(\"\") \/ mFilePathOrText;\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\tif (fs::exists(fullPath)) {\n\t\t\t\t\/\/ TODO mTopDown has no effect!?!\n\t\t\t\tmTexture = ci::gl::Texture::create(loadImage(loadAsset(mFilePathOrText)), ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmTexture = ci::gl::Texture::create(mWidth, mHeight, ci::gl::Texture::Format().loadTopDown(mTopDown));\n\t\t\t}\n\t\t}\n\t}\n\tci::gl::Texture2dRef TextureImage::getTexture() {\n\t\treturn mTexture;\n\t}\n\tTextureImage::~TextureImage(void) {\n\n\t}\n\t\/\/ TextureText\n\tTextureText::TextureText() {\n\t\t\/\/ font\n\t\tFont customFont(Font(loadAsset(\"Signika-Regular.ttf\"), 100));\n\t\tgl::TextureFont::Format f;\n\t\tf.enableMipmapping(true);\n\t\tmTextureFont = gl::TextureFont::create(customFont, f);\n\n\t\t\/\/ camera\n\t\tmCamDist = 600.0f;\n\t\tmCam.setPerspective(75.0f, getWindowAspectRatio(), 0.1f, 15000.0f);\n\t\tmCam.lookAt(vec3(0.0f, 0.0f, mCamDist), vec3(0), vec3(0, 1, 0));\n\t\tmCam.setLensShiftHorizontal(-0.6);\n\t\t\/\/ scene\n\t\tmSceneMatrix = mSceneDestMatrix = mat4(1.0f); \/\/ identity\n\n\t\t\/\/ init text\n#if defined( CINDER_MSW )\n\t\taddChar('Y'); addChar('O'); \n#endif\n\t\tstringIndex = 0;\n\n\t\tcurrentFrame = -1;\n\t\tstartFrame = 0;\n\t\t\/\/ fbo\n\t\tgl::Fbo::Format format;\n\t\t\/\/format.setSamples( 4 ); \/\/ uncomment this to enable 4x antialiasing\n\t\tmFbo = gl::Fbo::create(mWidth, mHeight, format.depthTexture());\n\t}\n\tvoid TextureText::fromXml(const XmlTree &xml)\n\t{\n\t\tmType = TEXT;\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tif (mFilePathOrText.length() > 0) {\n\t\t\tfs::path fullPath = getAssetPath(\"\") \/ mFilePathOrText;\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\tif (fs::exists(fullPath)) {\n\n\t\t\t\ttry {\n\t\t\t\t\tmText = JsonTree(app::loadAsset(mFilePathOrText));\/\/ TODO \/ mVDSettings->mAssetsPath\n\t\t\t\t\tmStrings.clear();\n\n\t\t\t\t\tfor (const auto &line : mText[\"lines\"]) {\n\t\t\t\t\t\tmStrings.push_back(line.getValue());\n\t\t\t\t\t}\n\n\t\t\t\t\tCI_LOG_V(\"successfully loaded \" + mFilePathOrText);\n\t\t\t\t}\n\t\t\t\tcatch (Exception &exc) {\n\t\t\t\t\tCI_LOG_EXCEPTION(\"error loading \", exc);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tXmlTree\tTextureText::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureText::getTexture() {\n#if defined( CINDER_MSW )\n\t\t\/\/ should be in update?\n\t\t\/\/addChar('O');\n\n\t\tif (frame < mStrings[stringIndex].size() - 1) {\n\t\t\tchar c[2];\n\t\t\tprintf_s(c, \"%s\", mStrings[stringIndex].substr(frame, 1).c_str());\n\t\t\taddChar(*c);\n\t\t}\n\t\tgl::ScopedFramebuffer fbScp(mFbo);\n\t\tgl::clear(Color::black());\n\t\t\/\/ setup the viewport to match the dimensions of the FBO\n\t\tgl::ScopedViewport scpVp(ivec2(0), mFbo->getSize());\n\t\tfor (vector<Character>::iterator it = mCharacters.begin(); it != mCharacters.end(); ++it)\n\t\t\tit->draw();\n\n\t\tfor (list<Character>::iterator it = mDyingCharacters.begin(); it != mDyingCharacters.end(); ++it)\n\t\t\tit->draw();\n\n\t\tif ((!mDyingCharacters.empty()) && mDyingCharacters.front().isDead())\n\t\t\tmDyingCharacters.pop_front();\n\t\treturn mFbo->getColorTexture();\n#else\n\t\treturn mTexture;\n#endif\t\t\n\t}\n#if defined( CINDER_MSW )\n\tvoid TextureText::addChar(char c)\n\t{\n\t\tif (c == 32) {\n\t\t\tc = 97;\n\t\t}\n\t\telse {\n\t\t\tc = toupper(c);\n\t\t}\n\t\tint count = mCharacters.size();\n\n\t\tif (count > 0)\n\t\t\tmSceneDestMatrix = glm::translate(mSceneDestMatrix, vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\n\t\tglm::mat4 randStartMatrix = mSceneDestMatrix;\n\t\trandStartMatrix = glm::translate(randStartMatrix, vec3(300.0f));\n\n\t\tmCharacters.push_back(Character(mTextureFont, string(&c, 1), randStartMatrix));\n\n\t\t\/\/mSceneDestMatrix.translate(vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\t\tmSceneDestMatrix = glm::translate(mSceneDestMatrix, vec3(mCharacters.back().getKernBounds().getWidth() \/ 2.0f, 0.0f, 0.0f));\n\n\t\tfloat t = (count + 281) \/ 50.0f;\n\t\t\/\/mSceneDestMatrix.rotate(Vec3f(sin(t)*0.1f, cos(t)*0.2f, cos(t)*0.05f)); \/\/ makes the scene meander\n\n\t\tmCharacters.back().animIn(timeline(), mSceneDestMatrix);\n\n\t\ttimeline().apply(&mSceneMatrix, mSceneDestMatrix, 1.0f, EaseOutAtan(10));\n\n\t}\n\n\tvoid TextureText::removeChar()\n\t{\n\t\tif (!mCharacters.empty()) {\n\t\t\tmDyingCharacters.push_back(mCharacters.back());\n\t\t\tmCharacters.pop_back();\n\n\t\t\tif (!mCharacters.empty())\n\t\t\t\tmSceneDestMatrix = mCharacters.back().getDestMatrix();\n\t\t\telse\n\t\t\t\tmSceneDestMatrix = mat4(1.0f);\n\n\t\t\tmat4 randStartMatrix = glm::translate( mSceneDestMatrix, vec3(300.0f));\n\t\t\t\/\/randStartMatrix.translate(300.0f);\n\n\t\t\t\/\/randStartMatrix.rotate(getRandomVec3f(2.0f, 6.0f));\n\n\t\t\tmDyingCharacters.back().animOut(timeline(), randStartMatrix);\n\n\t\t\ttimeline().apply(&mSceneMatrix, mSceneDestMatrix, 1.0f, EaseOutAtan(10));\n\t\t}\n\t}\n#else\n\n#endif\n\tTextureText::~TextureText(void) {\n\n\t}\n\n\t\/\/ TextureMovie\n\tTextureMovie::TextureMovie() {\n\n\t}\n\tvoid TextureMovie::fromXml(const XmlTree &xml)\n\t{\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tmType = MOVIE;\n\n\t}\n\tXmlTree\tTextureMovie::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"filepath\", mFilePathOrText);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureMovie::getTexture() {\n\t\treturn mTexture;\n\t}\n\tTextureMovie::~TextureMovie(void) {\n\n\t}\n\n\t\/\/ TextureCamera\n#if (defined( CINDER_MSW) ) || (defined( CINDER_MAC ))\n\tTextureCamera::TextureCamera() {\n\t\tmFirstCameraDeviceName = \"\";\n\t\tprintDevices();\n\n\t\ttry {\n\t\t\tmCapture = Capture::create(640, 480);\n\t\t\tmCapture->start();\n\t\t}\n\t\tcatch (ci::Exception &exc) {\n\t\t\tCI_LOG_EXCEPTION(\"Failed to init capture \", exc);\n\t\t}\n\t}\n\tvoid TextureCamera::fromXml(const XmlTree &xml)\n\t{\n\t\t\/\/ retrieve attributes specific to this type of texture\n\t\tmFilePathOrText = xml.getAttributeValue<string>(\"filepath\", \"\");\n\t\tmType = CAMERA;\n\n\t}\n\tXmlTree\tTextureCamera::toXml() const {\n\t\tXmlTree xml = VDTexture::toXml();\n\n\t\t\/\/ add attributes specific to this type of texture\n\t\txml.setAttribute(\"camera\", mFirstCameraDeviceName);\n\t\treturn xml;\n\t}\n\tci::gl::Texture2dRef TextureCamera::getTexture() {\n\t\tif (mCapture && mCapture->checkNewFrame()) {\n\t\t\tif (!mTexture) {\n\t\t\t\t\/\/ Capture images come back as top-down, and it's more efficient to keep them that way\n\t\t\t\tmTexture = gl::Texture::create(*mCapture->getSurface(), gl::Texture::Format().loadTopDown());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmTexture->update(*mCapture->getSurface());\n\t\t\t}\n\t\t}\n\t\treturn mTexture;\n\t}\n\tvoid TextureCamera::printDevices()\n\t{\n\t\tfor (const auto &device : Capture::getDevices()) {\n\t\t\tconsole() << \"Device: \" << device->getName() << \" \"\n#if defined( CINDER_COCOA_TOUCH )\n\t\t\t\t<< (device->isFrontFacing() ? \"Front\" : \"Rear\") << \"-facing\"\n#endif\n\t\t\t\t<< endl;\n\t\t\tmFirstCameraDeviceName = device->getName();\n\t\t}\n\t}\n\tTextureCamera::~TextureCamera(void) {\n\n\t}\n#else\n\n#endif\n} \/\/ namespace VideoDromm\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file ViewStyle.cxx\n ** Store information on how the document is to be viewed.\n **\/\n\/\/ Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <string.h>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"Indicator.h\"\n#include \"XPM.h\"\n#include \"LineMarker.h\"\n#include \"Style.h\"\n#include \"ViewStyle.h\"\n\nMarginStyle::MarginStyle() :\n\tsymbol(false), width(16), mask(0xffffffff), sensitive(false) {\n}\n\n\/\/ A list of the fontnames - avoids wasting space in each style\nFontNames::FontNames() {\n\tmax = 0;\n}\n\nFontNames::~FontNames() {\n\tClear();\n}\n\nvoid FontNames::Clear() {\n\tfor (int i=0;i<max;i++) {\n\t\tdelete []names[i];\n\t}\n\tmax = 0;\n}\n\nconst char *FontNames::Save(const char *name) {\n\tif (!name)\n\t\treturn 0;\n\tfor (int i=0;i<max;i++) {\n\t\tif (strcmp(names[i], name) == 0) {\n\t\t\treturn names[i];\n\t\t}\n\t}\n\tnames[max] = new char[strlen(name) + 1];\n\tstrcpy(names[max], name);\n\tmax++;\n\treturn names[max-1];\n}\n\nViewStyle::ViewStyle() {\n\tInit();\n}\n\nViewStyle::ViewStyle(const ViewStyle &source) {\n\tInit();\n\tfor (unsigned int sty=0;sty<(sizeof(styles)\/sizeof(styles[0]));sty++) {\n\t\tstyles[sty] = source.styles[sty];\n\t\t\/\/ Can't just copy fontname as its lifetime is relative to its owning ViewStyle\n\t\tstyles[sty].fontName = fontNames.Save(source.styles[sty].fontName);\n\t}\n\tfor (int mrk=0;mrk<=MARKER_MAX;mrk++) {\n\t\tmarkers[mrk] = source.markers[mrk];\n\t}\n\tfor (int ind=0;ind<=INDIC_MAX;ind++) {\n\t\tindicators[ind] = source.indicators[ind];\n\t}\n\n\tselforeset = source.selforeset;\n\tselforeground.desired = source.selforeground.desired;\n\tselbackset = source.selbackset;\n\tselbackground.desired = source.selbackground.desired;\n\tselbackground2.desired = source.selbackground2.desired;\n\n\tfoldmarginColourSet = source.foldmarginColourSet;\n\tfoldmarginColour.desired = source.foldmarginColour.desired;\n\tfoldmarginHighlightColourSet = source.foldmarginHighlightColourSet;\n\tfoldmarginHighlightColour.desired = source.foldmarginHighlightColour.desired;\n\n\thotspotForegroundSet = source.hotspotForegroundSet;\n\thotspotForeground.desired = source.hotspotForeground.desired;\n\thotspotBackgroundSet = source.hotspotBackgroundSet;\n\thotspotBackground.desired = source.hotspotBackground.desired;\n\thotspotUnderline = source.hotspotUnderline;\n\thotspotSingleLine = source.hotspotSingleLine;\n\n\twhitespaceForegroundSet = source.whitespaceForegroundSet;\n\twhitespaceForeground.desired = source.whitespaceForeground.desired;\n\twhitespaceBackgroundSet = source.whitespaceBackgroundSet;\n\twhitespaceBackground.desired = source.whitespaceBackground.desired;\n\tselbar.desired = source.selbar.desired;\n\tselbarlight.desired = source.selbarlight.desired;\n\tcaretcolour.desired = source.caretcolour.desired;\n\tshowCaretLineBackground = source.showCaretLineBackground;\n\tcaretLineBackground.desired = source.caretLineBackground.desired;\n\tedgecolour.desired = source.edgecolour.desired;\n\tedgeState = source.edgeState;\n\tcaretWidth = source.caretWidth;\n\tleftMarginWidth = source.leftMarginWidth;\n\trightMarginWidth = source.rightMarginWidth;\n\tfor (int i=0;i < margins; i++) {\n\t\tms[i] = source.ms[i];\n\t}\n\tsymbolMargin = source.symbolMargin;\n\tmaskInLine = source.maskInLine;\n\tfixedColumnWidth = source.fixedColumnWidth;\n\tzoomLevel = source.zoomLevel;\n\tviewWhitespace = source.viewWhitespace;\n\tviewIndentationGuides = source.viewIndentationGuides;\n\tviewEOL = source.viewEOL;\n\tshowMarkedLines = source.showMarkedLines;\n}\n\nViewStyle::~ViewStyle() {\n}\n\nvoid ViewStyle::Init() {\n\tfontNames.Clear();\n\tResetDefaultStyle();\n\n\tindicators[0].style = INDIC_SQUIGGLE;\n\tindicators[0].fore = ColourDesired(0, 0x7f, 0);\n\tindicators[1].style = INDIC_TT;\n\tindicators[1].fore = ColourDesired(0, 0, 0xff);\n\tindicators[2].style = INDIC_PLAIN;\n\tindicators[2].fore = ColourDesired(0xff, 0, 0);\n\n\tlineHeight = 1;\n\tmaxAscent = 1;\n\tmaxDescent = 1;\n\taveCharWidth = 8;\n\tspaceWidth = 8;\n\n\tselforeset = false;\n\tselforeground.desired = ColourDesired(0xff, 0, 0);\n\tselbackset = true;\n\tselbackground.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\tselbackground2.desired = ColourDesired(0xb0, 0xb0, 0xb0);\n\n\tfoldmarginColourSet = false;\n\tfoldmarginColour.desired = ColourDesired(0xff, 0, 0);\n\tfoldmarginHighlightColourSet = false;\n\tfoldmarginHighlightColour.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\n\twhitespaceForegroundSet = false;\n\twhitespaceForeground.desired = ColourDesired(0, 0, 0);\n\twhitespaceBackgroundSet = false;\n\twhitespaceBackground.desired = ColourDesired(0xff, 0xff, 0xff);\n\tselbar.desired = Platform::Chrome();\n\tselbarlight.desired = Platform::ChromeHighlight();\n\tstyles[STYLE_LINENUMBER].fore.desired = ColourDesired(0, 0, 0);\n\tstyles[STYLE_LINENUMBER].back.desired = Platform::Chrome();\n\tcaretcolour.desired = ColourDesired(0, 0, 0);\n\tshowCaretLineBackground = false;\n\tcaretLineBackground.desired = ColourDesired(0xff, 0xff, 0);\n\tedgecolour.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\tedgeState = EDGE_NONE;\n\tcaretWidth = 1;\n\tsomeStylesProtected = false;\n\n\thotspotForegroundSet = false;\n\thotspotForeground.desired = ColourDesired(0, 0, 0xff);\n\thotspotBackgroundSet = false;\n\thotspotBackground.desired = ColourDesired(0xff, 0xff, 0xff);\n\thotspotUnderline = true;\n\thotspotSingleLine = true;\n\n\tleftMarginWidth = 1;\n\trightMarginWidth = 1;\n\tms[0].symbol = false;\n\tms[0].width = 0;\n\tms[0].mask = 0;\n\tms[1].symbol = true;\n\tms[1].width = 16;\n\tms[1].mask = ~SC_MASK_FOLDERS;\n\tms[2].symbol = true;\n\tms[2].width = 0;\n\tms[2].mask = 0;\n\tfixedColumnWidth = leftMarginWidth;\n\tsymbolMargin = false;\n\tmaskInLine = 0xffffffff;\n\tfor (int margin=0; margin < margins; margin++) {\n\t\tfixedColumnWidth += ms[margin].width;\n\t\tsymbolMargin = symbolMargin || ms[margin].symbol;\n\t\tif (ms[margin].width > 0)\n\t\t\tmaskInLine &= ~ms[margin].mask;\n\t}\n\tzoomLevel = 0;\n\tviewWhitespace = wsInvisible;\n\tviewIndentationGuides = false;\n\tviewEOL = false;\n\tshowMarkedLines = true;\n}\n\nvoid ViewStyle::RefreshColourPalette(Palette &pal, bool want) {\n\tunsigned int i;\n\tfor (i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tpal.WantFind(styles[i].fore, want);\n\t\tpal.WantFind(styles[i].back, want);\n\t}\n\tfor (i=0;i<(sizeof(indicators)\/sizeof(indicators[0]));i++) {\n\t\tpal.WantFind(indicators[i].fore, want);\n\t}\n\tfor (i=0;i<(sizeof(markers)\/sizeof(markers[0]));i++) {\n\t\tmarkers[i].RefreshColourPalette(pal, want);\n\t}\n\tpal.WantFind(selforeground, want);\n\tpal.WantFind(selbackground, want);\n\tpal.WantFind(selbackground2, want);\n\n\tpal.WantFind(foldmarginColour, want);\n\tpal.WantFind(foldmarginHighlightColour, want);\n\n\tpal.WantFind(whitespaceForeground, want);\n\tpal.WantFind(whitespaceBackground, want);\n\tpal.WantFind(selbar, want);\n\tpal.WantFind(selbarlight, want);\n\tpal.WantFind(caretcolour, want);\n\tpal.WantFind(caretLineBackground, want);\n\tpal.WantFind(edgecolour, want);\n\tpal.WantFind(hotspotForeground, want);\n\tpal.WantFind(hotspotBackground, want);\n}\n\nvoid ViewStyle::Refresh(Surface &surface) {\n\tselbar.desired = Platform::Chrome();\n\tselbarlight.desired = Platform::ChromeHighlight();\n\tstyles[STYLE_DEFAULT].Realise(surface, zoomLevel);\n\tmaxAscent = styles[STYLE_DEFAULT].ascent;\n\tmaxDescent = styles[STYLE_DEFAULT].descent;\n\tsomeStylesProtected = false;\n\tfor (unsigned int i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tif (i != STYLE_DEFAULT) {\n\t\t\tstyles[i].Realise(surface, zoomLevel, &styles[STYLE_DEFAULT]);\n\t\t\tif (maxAscent < styles[i].ascent)\n\t\t\t\tmaxAscent = styles[i].ascent;\n\t\t\tif (maxDescent < styles[i].descent)\n\t\t\t\tmaxDescent = styles[i].descent;\n\t\t}\n\t\tif (styles[i].IsProtected()) {\n\t\t\tsomeStylesProtected = true;\n\t\t}\n\t}\n\n\tlineHeight = maxAscent + maxDescent;\n\taveCharWidth = styles[STYLE_DEFAULT].aveCharWidth;\n\tspaceWidth = styles[STYLE_DEFAULT].spaceWidth;\n\n\tfixedColumnWidth = leftMarginWidth;\n\tsymbolMargin = false;\n\tmaskInLine = 0xffffffff;\n\tfor (int margin=0; margin < margins; margin++) {\n\t\tfixedColumnWidth += ms[margin].width;\n\t\tsymbolMargin = symbolMargin || ms[margin].symbol;\n\t\tif (ms[margin].width > 0)\n\t\t\tmaskInLine &= ~ms[margin].mask;\n\t}\n}\n\nvoid ViewStyle::ResetDefaultStyle() {\n\tstyles[STYLE_DEFAULT].Clear(ColourDesired(0,0,0),\n\t\tColourDesired(0xff,0xff,0xff),\n\t Platform::DefaultFontSize(), fontNames.Save(Platform::DefaultFont()),\n\t\tSC_CHARSET_DEFAULT,\n\t\tfalse, false, false, false, Style::caseMixed, true, true, false);\n}\n\nvoid ViewStyle::ClearStyles() {\n\t\/\/ Reset all styles to be like the default style\n\tfor (unsigned int i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tif (i != STYLE_DEFAULT) {\n\t\t\tstyles[i].ClearTo(styles[STYLE_DEFAULT]);\n\t\t}\n\t}\n\tstyles[STYLE_LINENUMBER].back.desired = Platform::Chrome();\n}\n\nvoid ViewStyle::SetStyleFontName(int styleIndex, const char *name) {\n\tstyles[styleIndex].fontName = fontNames.Save(name);\n}\n\nbool ViewStyle::ProtectionActive() const {\n return someStylesProtected;\n}\n<commit_msg>Ensure someStylesProtected is initialised.<commit_after>\/\/ Scintilla source code edit control\n\/** @file ViewStyle.cxx\n ** Store information on how the document is to be viewed.\n **\/\n\/\/ Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <string.h>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"Indicator.h\"\n#include \"XPM.h\"\n#include \"LineMarker.h\"\n#include \"Style.h\"\n#include \"ViewStyle.h\"\n\nMarginStyle::MarginStyle() :\n\tsymbol(false), width(16), mask(0xffffffff), sensitive(false) {\n}\n\n\/\/ A list of the fontnames - avoids wasting space in each style\nFontNames::FontNames() {\n\tmax = 0;\n}\n\nFontNames::~FontNames() {\n\tClear();\n}\n\nvoid FontNames::Clear() {\n\tfor (int i=0;i<max;i++) {\n\t\tdelete []names[i];\n\t}\n\tmax = 0;\n}\n\nconst char *FontNames::Save(const char *name) {\n\tif (!name)\n\t\treturn 0;\n\tfor (int i=0;i<max;i++) {\n\t\tif (strcmp(names[i], name) == 0) {\n\t\t\treturn names[i];\n\t\t}\n\t}\n\tnames[max] = new char[strlen(name) + 1];\n\tstrcpy(names[max], name);\n\tmax++;\n\treturn names[max-1];\n}\n\nViewStyle::ViewStyle() {\n\tInit();\n}\n\nViewStyle::ViewStyle(const ViewStyle &source) {\n\tInit();\n\tfor (unsigned int sty=0;sty<(sizeof(styles)\/sizeof(styles[0]));sty++) {\n\t\tstyles[sty] = source.styles[sty];\n\t\t\/\/ Can't just copy fontname as its lifetime is relative to its owning ViewStyle\n\t\tstyles[sty].fontName = fontNames.Save(source.styles[sty].fontName);\n\t}\n\tfor (int mrk=0;mrk<=MARKER_MAX;mrk++) {\n\t\tmarkers[mrk] = source.markers[mrk];\n\t}\n\tfor (int ind=0;ind<=INDIC_MAX;ind++) {\n\t\tindicators[ind] = source.indicators[ind];\n\t}\n\n\tselforeset = source.selforeset;\n\tselforeground.desired = source.selforeground.desired;\n\tselbackset = source.selbackset;\n\tselbackground.desired = source.selbackground.desired;\n\tselbackground2.desired = source.selbackground2.desired;\n\n\tfoldmarginColourSet = source.foldmarginColourSet;\n\tfoldmarginColour.desired = source.foldmarginColour.desired;\n\tfoldmarginHighlightColourSet = source.foldmarginHighlightColourSet;\n\tfoldmarginHighlightColour.desired = source.foldmarginHighlightColour.desired;\n\n\thotspotForegroundSet = source.hotspotForegroundSet;\n\thotspotForeground.desired = source.hotspotForeground.desired;\n\thotspotBackgroundSet = source.hotspotBackgroundSet;\n\thotspotBackground.desired = source.hotspotBackground.desired;\n\thotspotUnderline = source.hotspotUnderline;\n\thotspotSingleLine = source.hotspotSingleLine;\n\n\twhitespaceForegroundSet = source.whitespaceForegroundSet;\n\twhitespaceForeground.desired = source.whitespaceForeground.desired;\n\twhitespaceBackgroundSet = source.whitespaceBackgroundSet;\n\twhitespaceBackground.desired = source.whitespaceBackground.desired;\n\tselbar.desired = source.selbar.desired;\n\tselbarlight.desired = source.selbarlight.desired;\n\tcaretcolour.desired = source.caretcolour.desired;\n\tshowCaretLineBackground = source.showCaretLineBackground;\n\tcaretLineBackground.desired = source.caretLineBackground.desired;\n\tedgecolour.desired = source.edgecolour.desired;\n\tedgeState = source.edgeState;\n\tcaretWidth = source.caretWidth;\n\tsomeStylesProtected = false;\n\tleftMarginWidth = source.leftMarginWidth;\n\trightMarginWidth = source.rightMarginWidth;\n\tfor (int i=0;i < margins; i++) {\n\t\tms[i] = source.ms[i];\n\t}\n\tsymbolMargin = source.symbolMargin;\n\tmaskInLine = source.maskInLine;\n\tfixedColumnWidth = source.fixedColumnWidth;\n\tzoomLevel = source.zoomLevel;\n\tviewWhitespace = source.viewWhitespace;\n\tviewIndentationGuides = source.viewIndentationGuides;\n\tviewEOL = source.viewEOL;\n\tshowMarkedLines = source.showMarkedLines;\n}\n\nViewStyle::~ViewStyle() {\n}\n\nvoid ViewStyle::Init() {\n\tfontNames.Clear();\n\tResetDefaultStyle();\n\n\tindicators[0].style = INDIC_SQUIGGLE;\n\tindicators[0].fore = ColourDesired(0, 0x7f, 0);\n\tindicators[1].style = INDIC_TT;\n\tindicators[1].fore = ColourDesired(0, 0, 0xff);\n\tindicators[2].style = INDIC_PLAIN;\n\tindicators[2].fore = ColourDesired(0xff, 0, 0);\n\n\tlineHeight = 1;\n\tmaxAscent = 1;\n\tmaxDescent = 1;\n\taveCharWidth = 8;\n\tspaceWidth = 8;\n\n\tselforeset = false;\n\tselforeground.desired = ColourDesired(0xff, 0, 0);\n\tselbackset = true;\n\tselbackground.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\tselbackground2.desired = ColourDesired(0xb0, 0xb0, 0xb0);\n\n\tfoldmarginColourSet = false;\n\tfoldmarginColour.desired = ColourDesired(0xff, 0, 0);\n\tfoldmarginHighlightColourSet = false;\n\tfoldmarginHighlightColour.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\n\twhitespaceForegroundSet = false;\n\twhitespaceForeground.desired = ColourDesired(0, 0, 0);\n\twhitespaceBackgroundSet = false;\n\twhitespaceBackground.desired = ColourDesired(0xff, 0xff, 0xff);\n\tselbar.desired = Platform::Chrome();\n\tselbarlight.desired = Platform::ChromeHighlight();\n\tstyles[STYLE_LINENUMBER].fore.desired = ColourDesired(0, 0, 0);\n\tstyles[STYLE_LINENUMBER].back.desired = Platform::Chrome();\n\tcaretcolour.desired = ColourDesired(0, 0, 0);\n\tshowCaretLineBackground = false;\n\tcaretLineBackground.desired = ColourDesired(0xff, 0xff, 0);\n\tedgecolour.desired = ColourDesired(0xc0, 0xc0, 0xc0);\n\tedgeState = EDGE_NONE;\n\tcaretWidth = 1;\n\tsomeStylesProtected = false;\n\n\thotspotForegroundSet = false;\n\thotspotForeground.desired = ColourDesired(0, 0, 0xff);\n\thotspotBackgroundSet = false;\n\thotspotBackground.desired = ColourDesired(0xff, 0xff, 0xff);\n\thotspotUnderline = true;\n\thotspotSingleLine = true;\n\n\tleftMarginWidth = 1;\n\trightMarginWidth = 1;\n\tms[0].symbol = false;\n\tms[0].width = 0;\n\tms[0].mask = 0;\n\tms[1].symbol = true;\n\tms[1].width = 16;\n\tms[1].mask = ~SC_MASK_FOLDERS;\n\tms[2].symbol = true;\n\tms[2].width = 0;\n\tms[2].mask = 0;\n\tfixedColumnWidth = leftMarginWidth;\n\tsymbolMargin = false;\n\tmaskInLine = 0xffffffff;\n\tfor (int margin=0; margin < margins; margin++) {\n\t\tfixedColumnWidth += ms[margin].width;\n\t\tsymbolMargin = symbolMargin || ms[margin].symbol;\n\t\tif (ms[margin].width > 0)\n\t\t\tmaskInLine &= ~ms[margin].mask;\n\t}\n\tzoomLevel = 0;\n\tviewWhitespace = wsInvisible;\n\tviewIndentationGuides = false;\n\tviewEOL = false;\n\tshowMarkedLines = true;\n}\n\nvoid ViewStyle::RefreshColourPalette(Palette &pal, bool want) {\n\tunsigned int i;\n\tfor (i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tpal.WantFind(styles[i].fore, want);\n\t\tpal.WantFind(styles[i].back, want);\n\t}\n\tfor (i=0;i<(sizeof(indicators)\/sizeof(indicators[0]));i++) {\n\t\tpal.WantFind(indicators[i].fore, want);\n\t}\n\tfor (i=0;i<(sizeof(markers)\/sizeof(markers[0]));i++) {\n\t\tmarkers[i].RefreshColourPalette(pal, want);\n\t}\n\tpal.WantFind(selforeground, want);\n\tpal.WantFind(selbackground, want);\n\tpal.WantFind(selbackground2, want);\n\n\tpal.WantFind(foldmarginColour, want);\n\tpal.WantFind(foldmarginHighlightColour, want);\n\n\tpal.WantFind(whitespaceForeground, want);\n\tpal.WantFind(whitespaceBackground, want);\n\tpal.WantFind(selbar, want);\n\tpal.WantFind(selbarlight, want);\n\tpal.WantFind(caretcolour, want);\n\tpal.WantFind(caretLineBackground, want);\n\tpal.WantFind(edgecolour, want);\n\tpal.WantFind(hotspotForeground, want);\n\tpal.WantFind(hotspotBackground, want);\n}\n\nvoid ViewStyle::Refresh(Surface &surface) {\n\tselbar.desired = Platform::Chrome();\n\tselbarlight.desired = Platform::ChromeHighlight();\n\tstyles[STYLE_DEFAULT].Realise(surface, zoomLevel);\n\tmaxAscent = styles[STYLE_DEFAULT].ascent;\n\tmaxDescent = styles[STYLE_DEFAULT].descent;\n\tsomeStylesProtected = false;\n\tfor (unsigned int i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tif (i != STYLE_DEFAULT) {\n\t\t\tstyles[i].Realise(surface, zoomLevel, &styles[STYLE_DEFAULT]);\n\t\t\tif (maxAscent < styles[i].ascent)\n\t\t\t\tmaxAscent = styles[i].ascent;\n\t\t\tif (maxDescent < styles[i].descent)\n\t\t\t\tmaxDescent = styles[i].descent;\n\t\t}\n\t\tif (styles[i].IsProtected()) {\n\t\t\tsomeStylesProtected = true;\n\t\t}\n\t}\n\n\tlineHeight = maxAscent + maxDescent;\n\taveCharWidth = styles[STYLE_DEFAULT].aveCharWidth;\n\tspaceWidth = styles[STYLE_DEFAULT].spaceWidth;\n\n\tfixedColumnWidth = leftMarginWidth;\n\tsymbolMargin = false;\n\tmaskInLine = 0xffffffff;\n\tfor (int margin=0; margin < margins; margin++) {\n\t\tfixedColumnWidth += ms[margin].width;\n\t\tsymbolMargin = symbolMargin || ms[margin].symbol;\n\t\tif (ms[margin].width > 0)\n\t\t\tmaskInLine &= ~ms[margin].mask;\n\t}\n}\n\nvoid ViewStyle::ResetDefaultStyle() {\n\tstyles[STYLE_DEFAULT].Clear(ColourDesired(0,0,0),\n\t\tColourDesired(0xff,0xff,0xff),\n\t Platform::DefaultFontSize(), fontNames.Save(Platform::DefaultFont()),\n\t\tSC_CHARSET_DEFAULT,\n\t\tfalse, false, false, false, Style::caseMixed, true, true, false);\n}\n\nvoid ViewStyle::ClearStyles() {\n\t\/\/ Reset all styles to be like the default style\n\tfor (unsigned int i=0;i<(sizeof(styles)\/sizeof(styles[0]));i++) {\n\t\tif (i != STYLE_DEFAULT) {\n\t\t\tstyles[i].ClearTo(styles[STYLE_DEFAULT]);\n\t\t}\n\t}\n\tstyles[STYLE_LINENUMBER].back.desired = Platform::Chrome();\n}\n\nvoid ViewStyle::SetStyleFontName(int styleIndex, const char *name) {\n\tstyles[styleIndex].fontName = fontNames.Save(name);\n}\n\nbool ViewStyle::ProtectionActive() const {\n return someStylesProtected;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.0.0, packaged on August, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_camera.cpp Implementation of the GLC_Camera class.\n\n\n#include \"glc_camera.h\"\n#include \"glc_openglexception.h\"\n\n#include <QtDebug>\n\nusing namespace glc;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor Destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGLC_Camera::GLC_Camera()\n: GLC_Object(\"Camera\")\n, m_Eye(0,0,1)\n, m_Target()\n, m_VectUp(0,1,0)\n{\n\t\n}\n\nGLC_Camera::GLC_Camera(const GLC_Point4d &Eye, const GLC_Point4d &Target, const GLC_Vector4d &Up)\n: GLC_Object(\"Camera\")\n, m_Eye()\n, m_Target()\n, m_VectUp()\n\n{\n\tsetCam(Eye, Target, Up);\t\n\tcreateMatComp();\n}\n\n\/\/ Copy constructor\nGLC_Camera::GLC_Camera(const GLC_Camera& cam)\n: GLC_Object(cam)\n, m_Eye(cam.m_Eye)\n, m_Target(cam.m_Target)\n, m_VectUp(cam.m_VectUp)\n, m_MatCompOrbit(cam.m_MatCompOrbit)\n{\n\t\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Get the distance between the eye and the target of camera\ndouble GLC_Camera::getDistEyeTarget(void) const\n{\n\treturn (m_Eye - m_Target).getNorm();\n}\n\n\/\/ Get camera's eye coordinate point\nconst GLC_Point4d GLC_Camera::getEye(void) const\n{\n\treturn m_Eye;\n}\n\n\/\/ Get camera's target coordinate point\nconst GLC_Point4d GLC_Camera::getTarget(void) const\n{\n\treturn m_Target;\n}\n\n\/\/ Get camera's Up vector\nconst GLC_Vector4d GLC_Camera::getVectUp(void) const\n{\n\treturn m_VectUp;\n}\n\n\/\/ Get camera's Vector (from eye to target)\nGLC_Vector4d GLC_Camera::getVectCam(void) const\n{\n\treturn m_Eye - m_Target;\n}\n\n\/\/ Get camera's orbit composition matrix\nconst GLC_Matrix4x4 GLC_Camera::getMatCompOrbit(void) const\n{\n\treturn m_MatCompOrbit;\n}\n\n\/\/ equality operator\nbool GLC_Camera::operator==(const GLC_Camera& cam) const\n{\n\treturn (m_Eye == cam.m_Eye) && (m_Target == cam.m_Target)\n\t\t\t&& (m_VectUp == cam.m_VectUp);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GLC_Camera::orbit(GLC_Vector4d VectOldPoss, GLC_Vector4d VectCurPoss)\n{\n\t\/\/ Map Vectors\n\tVectOldPoss= m_MatCompOrbit * VectOldPoss;\n\tVectCurPoss= m_MatCompOrbit * VectCurPoss;\n\t\n\t\/\/ Compute rotation matrix\n\tconst GLC_Vector4d VectAxeRot(VectCurPoss ^ VectOldPoss);\n\t\/\/ Check if rotation vector is not null\n\tif (!VectAxeRot.isNull())\n\t{ \/\/ Ok, is not null\n\t\tconst double Angle= acos(VectCurPoss * VectOldPoss);\n\t\tconst GLC_Matrix4x4 MatOrbit(VectAxeRot, Angle);\n\t\n\t\t\/\/ Camera transformation\n\t\tm_Eye= (MatOrbit * (m_Eye - m_Target)) + m_Target;\n\t\tm_VectUp= MatOrbit * m_VectUp;\n\t\tm_MatCompOrbit= MatOrbit * m_MatCompOrbit;\n\t}\n}\n\nvoid GLC_Camera::pan(GLC_Vector4d VectDep)\n{\n\t\/\/ Vector mapping\n\tVectDep= m_MatCompOrbit * VectDep;\n\t\n\t\/\/ Camera transformation\n\tm_Eye= m_Eye + VectDep;\n\tm_Target= m_Target + VectDep;\n}\n\nvoid GLC_Camera::zoom(double factor)\n{\n\tQ_ASSERT(factor > 0);\n\t\/\/ Eye->target vector\n\tGLC_Vector4d VectCam(m_Eye - m_Target);\n\t\n\t\/\/ Compute new vector length\n\tconst double Norme= VectCam.getNorm() * 1 \/ factor;\n\tVectCam.setNormal(Norme);\n\t\n\tm_Eye= VectCam + m_Target;\n\t\n}\n\nvoid GLC_Camera::move(const GLC_Matrix4x4 &MatMove)\n{\n\tm_Eye= MatMove * m_Eye;\n\tm_Target= MatMove * m_Target;\n\t\n\t\/\/ Up vector computation\t\n\t\/\/ In case of translation in matrix\n\tconst GLC_Vector4d VectOrigine(0,0,0);\n\t\/\/ Backup m_VectUp\n\tconst GLC_Vector4d VectUpOld(m_VectUp);\n\tm_VectUp= (MatMove * VectUpOld) - (MatMove * VectOrigine); \/\/ Up Vector Origin must be equal to 0,0,0\n\tcreateMatComp();\n}\n\nvoid GLC_Camera::translate(const GLC_Vector4d &VectTrans)\n{\n\tm_Eye= m_Eye + VectTrans;\n\tm_Target= m_Target + VectTrans;\n}\n\nvoid GLC_Camera::setEyeCam(const GLC_Point4d &Eye)\n{\n\t\/\/ Old camera's vector\n\tGLC_Vector4d VectOldCam(m_Eye - m_Target);\n\t\/\/ New camera's vector\n\tGLC_Vector4d VectCam(Eye - m_Target);\n\tif ( !(VectOldCam - VectCam).isNull() )\n\t{\n\t\tVectOldCam.setNormal(1);\n\t\tVectCam.setNormal(1);\n\t\tconst double Angle= acos(VectOldCam * VectCam);\n\t\tif ( (Angle > EPSILON) && ( (PI - Angle) > EPSILON) )\n\t\t{\n\t\t\tconst GLC_Vector4d VectAxeRot(VectOldCam ^ VectCam);\n\t\t\tconst GLC_Matrix4x4 MatRot(VectAxeRot, Angle);\n\t\t\tm_VectUp= MatRot * m_VectUp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( (PI - Angle) < EPSILON)\n\t\t\t{\t\/\/ Angle de 180�\n\t\t\t\tm_VectUp.setInv();\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetCam(Eye, m_Target, m_VectUp);\n\t}\n}\n\nvoid GLC_Camera::setTargetCam(const GLC_Point4d &Target)\n{\n\t\/\/ Old camera's vector\n\tGLC_Vector4d VectOldCam(m_Eye - m_Target);\n\t\/\/ New camera's vector\n\tGLC_Vector4d VectCam(m_Eye - Target);\n\tif ( !(VectOldCam - VectCam).isNull() )\n\t{\n\t\tVectOldCam.setNormal(1);\n\t\tVectCam.setNormal(1);\n\t\tconst double Angle= acos(VectOldCam * VectCam);\n\t\tif ( (Angle > EPSILON) && ( (PI - Angle) > EPSILON) )\n\t\t{\n\t\t\tconst GLC_Vector4d VectAxeRot(VectOldCam ^ VectCam);\n\t\t\tconst GLC_Matrix4x4 MatRot(VectAxeRot, Angle);\n\t\t\tm_VectUp= MatRot * m_VectUp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( (PI - Angle) < EPSILON)\n\t\t\t{\t\/\/ Angle of 180�\n\t\t\t\tm_VectUp.setInv();\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetCam(m_Eye, Target, m_VectUp);\n\t}\n}\n\nvoid GLC_Camera::setUpCam(const GLC_Vector4d &Up)\n{\n\tif ( !(m_VectUp - Up).isNull() )\n\t{\n\t\tsetCam(m_Eye, m_Target, Up);\n\t}\n}\n\nvoid GLC_Camera::setCam(GLC_Point4d Eye, GLC_Point4d Target, GLC_Vector4d Up)\n{\n\tUp.setNormal(1);\n\n\tconst GLC_Vector4d VectCam((Eye - Target).setNormal(1));\n\tconst double Angle= acos(VectCam * Up);\n\t\n\t\/* m_VectUp and VectCam could not be parallel\n\t * m_VectUp could not be NULL\n\t * VectCam could not be NULL *\/\n\t\/\/Q_ASSERT((Angle > EPSILON) && ((PI - Angle) > EPSILON));\n\tif ( fabs(Angle - (PI \/ 2)) > EPSILON)\n\t{\t\/\/ Angle not equal to 90�\n\t\tconst GLC_Vector4d AxeRot(VectCam ^ Up);\n\t\tGLC_Matrix4x4 MatRot(AxeRot, PI \/ 2);\n\t\tUp= MatRot * VectCam;\n\t}\t\n\n\tm_Eye= Eye;\n\tm_Target= Target;\n\tm_VectUp= Up;\n\tcreateMatComp();\n}\n\n\/\/! Set the camera by copying another camera\nvoid GLC_Camera::setCam(const GLC_Camera& cam)\n{\n\tm_Eye= cam.m_Eye;\n\tm_Target= cam.m_Target;\n\tm_VectUp= cam.m_VectUp;\n\tm_MatCompOrbit= cam.m_MatCompOrbit;\n}\n\n\nvoid GLC_Camera::setDistEyeTarget(double Longueur)\n{\n GLC_Vector4d VectCam(m_Eye - m_Target);\n VectCam.setNormal(Longueur);\n m_Eye= VectCam + m_Target;\n}\n\/\/ Assignement operator\nGLC_Camera &GLC_Camera::operator=(const GLC_Camera& cam)\n{\n\tGLC_Object::operator=(cam);\n\tm_Eye= cam.m_Eye;\n\tm_Target= cam.m_Target;\n\tm_VectUp= cam.m_VectUp;\n\tm_MatCompOrbit= cam.m_MatCompOrbit;\n\treturn *this;\n}\t\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenGL Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GLC_Camera::glExecute(GLenum Mode)\n{\n\tgluLookAt(m_Eye.getX(), m_Eye.getY(), m_Eye.getZ(),\n\t\tm_Target.getX(), m_Target.getY(), m_Target.getZ(),\n\t\tm_VectUp.getX(), m_VectUp.getY(), m_VectUp.getZ());\n\t\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Camera::GlExecute \", error);\n\t\tthrow(OpenGlException);\n\t}\n\t\t\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private services Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GLC_Camera::createMatComp(void)\n{\n\t\/\/ Calcule de la matrice de rotation entre VectZ et VectCam\n\t\/\/ Compute rotation matrix between Z axis and camera\n\tconst GLC_Vector4d VectCam((m_Eye - m_Target).setNormal(1));\n\t\n\tif ( fabs( fabs(VectCam.getZ()) - 1.0 ) > EPSILON)\n\t{ \/\/ Camera's vector not equal to Z axis\n\t\tconst GLC_Vector4d VectAxeRot= (AxeZ ^ VectCam);\n\t\tconst double Angle= acos(AxeZ * VectCam);\n\t\tm_MatCompOrbit.setMatRot(VectAxeRot, Angle);\n\t}\n\telse \/\/ Camera's Vector equal to Z axis\n\t{\t\t\n\t\tif (VectCam.getZ() < 0)\n\t\t{\n\t\t\t\t\t\t\n\t\t\tm_MatCompOrbit.setMatRot(m_VectUp, PI);\n\t\t}\n\t\telse\n\t\t\tm_MatCompOrbit.setToIdentity();\n\t}\n\n\t\/\/ Angle between InitVectUp and m_VectUp\n\tGLC_Vector4d InitVectUp(0,1,0); \/\/ Par d�faut m_VectUp est Y\n\tInitVectUp= m_MatCompOrbit * InitVectUp;\n\t\/\/ Compute the angle\n\tconst double AngleVectUp= acos(InitVectUp * m_VectUp);\n\t\n\tGLC_Matrix4x4 MatInt; \/\/ intermediate matrix\n\n\tif (( AngleVectUp > EPSILON) && ( (PI - AngleVectUp) > EPSILON) )\n\n\t{ \/\/ Angle not equal to 0 or 180�\n\t\tconst GLC_Vector4d VectAxeRot(InitVectUp ^ m_VectUp);\n\n\t\tMatInt.setMatRot(VectAxeRot, AngleVectUp);\n\t}\n\telse\t\/\/ Angle equal to 0 or 180�\n\t{\n\t\tMatInt.setMatRot(VectCam, AngleVectUp);\n\t}\n\n\tm_MatCompOrbit= MatInt * m_MatCompOrbit;\t\n}\n\n\n<commit_msg>Fix a bug on windows plateform : Before calcul the angle between to vector, check if these vector are equal.<commit_after>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.0.0, packaged on August, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_camera.cpp Implementation of the GLC_Camera class.\n\n\n#include \"glc_camera.h\"\n#include \"glc_openglexception.h\"\n\n#include <QtDebug>\n\nusing namespace glc;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor Destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGLC_Camera::GLC_Camera()\n: GLC_Object(\"Camera\")\n, m_Eye(0,0,1)\n, m_Target()\n, m_VectUp(0,1,0)\n{\n\t\n}\n\nGLC_Camera::GLC_Camera(const GLC_Point4d &Eye, const GLC_Point4d &Target, const GLC_Vector4d &Up)\n: GLC_Object(\"Camera\")\n, m_Eye()\n, m_Target()\n, m_VectUp()\n\n{\n\tsetCam(Eye, Target, Up);\t\n\tcreateMatComp();\n}\n\n\/\/ Copy constructor\nGLC_Camera::GLC_Camera(const GLC_Camera& cam)\n: GLC_Object(cam)\n, m_Eye(cam.m_Eye)\n, m_Target(cam.m_Target)\n, m_VectUp(cam.m_VectUp)\n, m_MatCompOrbit(cam.m_MatCompOrbit)\n{\n\t\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Get the distance between the eye and the target of camera\ndouble GLC_Camera::getDistEyeTarget(void) const\n{\n\treturn (m_Eye - m_Target).getNorm();\n}\n\n\/\/ Get camera's eye coordinate point\nconst GLC_Point4d GLC_Camera::getEye(void) const\n{\n\treturn m_Eye;\n}\n\n\/\/ Get camera's target coordinate point\nconst GLC_Point4d GLC_Camera::getTarget(void) const\n{\n\treturn m_Target;\n}\n\n\/\/ Get camera's Up vector\nconst GLC_Vector4d GLC_Camera::getVectUp(void) const\n{\n\treturn m_VectUp;\n}\n\n\/\/ Get camera's Vector (from eye to target)\nGLC_Vector4d GLC_Camera::getVectCam(void) const\n{\n\treturn m_Eye - m_Target;\n}\n\n\/\/ Get camera's orbit composition matrix\nconst GLC_Matrix4x4 GLC_Camera::getMatCompOrbit(void) const\n{\n\treturn m_MatCompOrbit;\n}\n\n\/\/ equality operator\nbool GLC_Camera::operator==(const GLC_Camera& cam) const\n{\n\treturn (m_Eye == cam.m_Eye) && (m_Target == cam.m_Target)\n\t\t\t&& (m_VectUp == cam.m_VectUp);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GLC_Camera::orbit(GLC_Vector4d VectOldPoss, GLC_Vector4d VectCurPoss)\n{\n\t\/\/ Map Vectors\n\tVectOldPoss= m_MatCompOrbit * VectOldPoss;\n\tVectCurPoss= m_MatCompOrbit * VectCurPoss;\n\t\n\t\/\/ Compute rotation matrix\n\tconst GLC_Vector4d VectAxeRot(VectCurPoss ^ VectOldPoss);\n\t\/\/ Check if rotation vector is not null\n\tif (!VectAxeRot.isNull())\n\t{ \/\/ Ok, is not null\n\t\tconst double Angle= acos(VectCurPoss * VectOldPoss);\n\t\tconst GLC_Matrix4x4 MatOrbit(VectAxeRot, Angle);\n\t\n\t\t\/\/ Camera transformation\n\t\tm_Eye= (MatOrbit * (m_Eye - m_Target)) + m_Target;\n\t\tm_VectUp= MatOrbit * m_VectUp;\n\t\tm_MatCompOrbit= MatOrbit * m_MatCompOrbit;\n\t}\n}\n\nvoid GLC_Camera::pan(GLC_Vector4d VectDep)\n{\n\t\/\/ Vector mapping\n\tVectDep= m_MatCompOrbit * VectDep;\n\t\n\t\/\/ Camera transformation\n\tm_Eye= m_Eye + VectDep;\n\tm_Target= m_Target + VectDep;\n}\n\nvoid GLC_Camera::zoom(double factor)\n{\n\tQ_ASSERT(factor > 0);\n\t\/\/ Eye->target vector\n\tGLC_Vector4d VectCam(m_Eye - m_Target);\n\t\n\t\/\/ Compute new vector length\n\tconst double Norme= VectCam.getNorm() * 1 \/ factor;\n\tVectCam.setNormal(Norme);\n\t\n\tm_Eye= VectCam + m_Target;\n\t\n}\n\nvoid GLC_Camera::move(const GLC_Matrix4x4 &MatMove)\n{\n\tm_Eye= MatMove * m_Eye;\n\tm_Target= MatMove * m_Target;\n\t\n\t\/\/ Up vector computation\t\n\t\/\/ In case of translation in matrix\n\tconst GLC_Vector4d VectOrigine(0,0,0);\n\t\/\/ Backup m_VectUp\n\tconst GLC_Vector4d VectUpOld(m_VectUp);\n\tm_VectUp= (MatMove * VectUpOld) - (MatMove * VectOrigine); \/\/ Up Vector Origin must be equal to 0,0,0\n\tcreateMatComp();\n}\n\nvoid GLC_Camera::translate(const GLC_Vector4d &VectTrans)\n{\n\tm_Eye= m_Eye + VectTrans;\n\tm_Target= m_Target + VectTrans;\n}\n\nvoid GLC_Camera::setEyeCam(const GLC_Point4d &Eye)\n{\n\t\/\/ Old camera's vector\n\tGLC_Vector4d VectOldCam(m_Eye - m_Target);\n\t\/\/ New camera's vector\n\tGLC_Vector4d VectCam(Eye - m_Target);\n\tif ( !(VectOldCam - VectCam).isNull() )\n\t{\n\t\tVectOldCam.setNormal(1);\n\t\tVectCam.setNormal(1);\n\t\tconst double Angle= acos(VectOldCam * VectCam);\n\t\tif ( (Angle > EPSILON) && ( (PI - Angle) > EPSILON) )\n\t\t{\n\t\t\tconst GLC_Vector4d VectAxeRot(VectOldCam ^ VectCam);\n\t\t\tconst GLC_Matrix4x4 MatRot(VectAxeRot, Angle);\n\t\t\tm_VectUp= MatRot * m_VectUp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( (PI - Angle) < EPSILON)\n\t\t\t{\t\/\/ Angle de 180�\n\t\t\t\tm_VectUp.setInv();\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetCam(Eye, m_Target, m_VectUp);\n\t}\n}\n\nvoid GLC_Camera::setTargetCam(const GLC_Point4d &Target)\n{\n\t\/\/ Old camera's vector\n\tGLC_Vector4d VectOldCam(m_Eye - m_Target);\n\t\/\/ New camera's vector\n\tGLC_Vector4d VectCam(m_Eye - Target);\n\tif ( !(VectOldCam - VectCam).isNull() )\n\t{\n\t\tVectOldCam.setNormal(1);\n\t\tVectCam.setNormal(1);\n\t\tconst double Angle= acos(VectOldCam * VectCam);\n\t\tif ( (Angle > EPSILON) && ( (PI - Angle) > EPSILON) )\n\t\t{\n\t\t\tconst GLC_Vector4d VectAxeRot(VectOldCam ^ VectCam);\n\t\t\tconst GLC_Matrix4x4 MatRot(VectAxeRot, Angle);\n\t\t\tm_VectUp= MatRot * m_VectUp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( (PI - Angle) < EPSILON)\n\t\t\t{\t\/\/ Angle of 180�\n\t\t\t\tm_VectUp.setInv();\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetCam(m_Eye, Target, m_VectUp);\n\t}\n}\n\nvoid GLC_Camera::setUpCam(const GLC_Vector4d &Up)\n{\n\tif ( !(m_VectUp - Up).isNull() )\n\t{\n\t\tsetCam(m_Eye, m_Target, Up);\n\t}\n}\n\nvoid GLC_Camera::setCam(GLC_Point4d Eye, GLC_Point4d Target, GLC_Vector4d Up)\n{\n\tUp.setNormal(1);\n\n\tconst GLC_Vector4d VectCam((Eye - Target).setNormal(1));\n\tconst double Angle= acos(VectCam * Up);\n\t\n\t\/* m_VectUp and VectCam could not be parallel\n\t * m_VectUp could not be NULL\n\t * VectCam could not be NULL *\/\n\t\/\/Q_ASSERT((Angle > EPSILON) && ((PI - Angle) > EPSILON));\n\tif ( fabs(Angle - (PI \/ 2)) > EPSILON)\n\t{\t\/\/ Angle not equal to 90�\n\t\tconst GLC_Vector4d AxeRot(VectCam ^ Up);\n\t\tGLC_Matrix4x4 MatRot(AxeRot, PI \/ 2);\n\t\tUp= MatRot * VectCam;\n\t}\t\n\n\tm_Eye= Eye;\n\tm_Target= Target;\n\tm_VectUp= Up;\n\tcreateMatComp();\n}\n\n\/\/! Set the camera by copying another camera\nvoid GLC_Camera::setCam(const GLC_Camera& cam)\n{\n\tm_Eye= cam.m_Eye;\n\tm_Target= cam.m_Target;\n\tm_VectUp= cam.m_VectUp;\n\tm_MatCompOrbit= cam.m_MatCompOrbit;\n}\n\n\nvoid GLC_Camera::setDistEyeTarget(double Longueur)\n{\n GLC_Vector4d VectCam(m_Eye - m_Target);\n VectCam.setNormal(Longueur);\n m_Eye= VectCam + m_Target;\n}\n\/\/ Assignement operator\nGLC_Camera &GLC_Camera::operator=(const GLC_Camera& cam)\n{\n\tGLC_Object::operator=(cam);\n\tm_Eye= cam.m_Eye;\n\tm_Target= cam.m_Target;\n\tm_VectUp= cam.m_VectUp;\n\tm_MatCompOrbit= cam.m_MatCompOrbit;\n\treturn *this;\n}\t\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenGL Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GLC_Camera::glExecute(GLenum Mode)\n{\n\tgluLookAt(m_Eye.getX(), m_Eye.getY(), m_Eye.getZ(),\n\t\tm_Target.getX(), m_Target.getY(), m_Target.getZ(),\n\t\tm_VectUp.getX(), m_VectUp.getY(), m_VectUp.getZ());\n\t\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Camera::GlExecute \", error);\n\t\tthrow(OpenGlException);\n\t}\n\t\t\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private services Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GLC_Camera::createMatComp(void)\n{\n\t\/\/ Compute rotation matrix between Z axis and camera\n\tconst GLC_Vector4d VectCam((m_Eye - m_Target).setNormal(1));\n\t\n\tif ( fabs( fabs(VectCam.getZ()) - 1.0 ) > EPSILON)\n\t{ \/\/ Camera's vector not equal to Z axis\n\t\tconst GLC_Vector4d VectAxeRot= (AxeZ ^ VectCam);\n\t\tconst double Angle= acos(AxeZ * VectCam);\n\t\tm_MatCompOrbit.setMatRot(VectAxeRot, Angle);\n\t}\n\telse \/\/ Camera's Vector equal to Z axis\n\t{\t\t\n\t\tif (VectCam.getZ() < 0)\n\t\t{\n\t\t\t\t\t\t\n\t\t\tm_MatCompOrbit.setMatRot(m_VectUp, PI);\n\t\t}\n\t\telse\n\t\t\tm_MatCompOrbit.setToIdentity();\n\t}\n\n\t\/\/ Angle between InitVectUp and m_VectUp\n\tGLC_Vector4d InitVectUp(0,1,0); \/\/ m_VectUp is Y by default\n\tInitVectUp= m_MatCompOrbit * InitVectUp;\n\t\/\/ Compute the angle if vector are not equal\n\tif (InitVectUp != InitVectUp)\n\t{\n\t\tconst double AngleVectUp= acos(InitVectUp * m_VectUp);\n\t\t\n\t\tGLC_Matrix4x4 MatInt; \/\/ intermediate matrix\n\t\n\t\tif (( AngleVectUp > EPSILON) && ( (PI - AngleVectUp) > EPSILON) )\n\t\n\t\t{ \/\/ Angle not equal to 0 or 180\n\t\t\tconst GLC_Vector4d VectAxeRot(InitVectUp ^ m_VectUp);\n\t\t\tMatInt.setMatRot(VectAxeRot, AngleVectUp);\n\t\t}\n\t\telse\t\/\/ Angle equal to 0 or 180\n\t\t{\n\t\t\tMatInt.setMatRot(VectCam, AngleVectUp);\n\t\t}\n\t\tqDebug() << \"MatInt \" << MatInt.toString();\n\t\tm_MatCompOrbit= MatInt * m_MatCompOrbit;\t\t\t\n\t}\t\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <iomanip>\r\n#include \"performance.h\"\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n\r\nvoid Test::gen(Mat& mat, int rows, int cols, int type, Scalar low, Scalar high)\r\n{ \r\n mat.create(rows, cols, type);\r\n\r\n RNG rng(0);\r\n rng.fill(mat, RNG::UNIFORM, low, high);\r\n}\r\n\r\n\r\nvoid Test::gen(Mat& mat, int rows, int cols, int type)\r\n{ \r\n mat.create(rows, cols, type);\r\n\r\n Mat mat8u(rows, cols * mat.elemSize(), CV_8U, mat.data, mat.step);\r\n\r\n RNG rng(0);\r\n rng.fill(mat, RNG::UNIFORM, Scalar(0), Scalar(256));\r\n}\r\n\r\n\r\nvoid TestSystem::run()\r\n{\r\n cout << setiosflags(ios_base::left);\r\n cout << \" \" << setw(10) << \"CPU, ms\" << setw(10) << \"GPU, ms\" \r\n << setw(10) << \"SPEEDUP\" << \"DESCRIPTION\\n\";\r\n cout << resetiosflags(ios_base::left);\r\n\r\n vector<Test*>::iterator it = tests_.begin();\r\n for (; it != tests_.end(); ++it)\r\n {\r\n can_flush_ = false;\r\n Test* test = *it;\r\n\r\n cout << endl << test->name() << \":\\n\";\r\n test->run();\r\n\r\n flush();\r\n }\r\n\r\n cout << setiosflags(ios_base::fixed | ios_base::left);\r\n cout << \"\\nCPU Total: \" << setprecision(3) << cpu_total_ \/ getTickFrequency() << \" sec\\n\";\r\n cout << \"GPU Total: \" << setprecision(3) << gpu_total_ \/ getTickFrequency() << \" sec (x\" \r\n << setprecision(3) << (double)cpu_total_ \/ gpu_total_ << \")\\n\";\r\n cout << resetiosflags(ios_base::fixed | ios_base::left);\r\n}\r\n\r\n\r\nvoid TestSystem::flush()\r\n{\r\n if (!can_flush_)\r\n return;\r\n\r\n int cpu_time = static_cast<int>(cpu_elapsed_ \/ getTickFrequency() * 1000.0);\r\n int gpu_time = static_cast<int>(gpu_elapsed_ \/ getTickFrequency() * 1000.0);\r\n double speedup = (double)cpu_time \/ gpu_time;\r\n\r\n cpu_elapsed_ = 0;\r\n gpu_elapsed_ = 0;\r\n\r\n cout << \" \" << setiosflags(ios_base::fixed | ios_base::left);\r\n\r\n stringstream stream;\r\n stream << cpu_time;\r\n cout << setw(10) << stream.str();\r\n\r\n stream.str(\"\");\r\n stream << gpu_time;\r\n cout << setw(10) << stream.str();\r\n\r\n stream.str(\"\");\r\n stream << \"x\" << setprecision(3) << speedup;\r\n cout << setw(10) << stream.str();\r\n\r\n cout << description_.str();\r\n description_.str(\"\");\r\n\r\n cout << resetiosflags(ios_base::fixed | ios_base::left) << endl;\r\n can_flush_ = false;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n TestSystem::instance()->run();\r\n return 0;\r\n}<commit_msg>minor refactoring of gpu perf. tests<commit_after>#include <iomanip>\r\n#include \"performance.h\"\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n\r\nvoid Test::gen(Mat& mat, int rows, int cols, int type, Scalar low, Scalar high)\r\n{ \r\n mat.create(rows, cols, type);\r\n\r\n RNG rng(0);\r\n rng.fill(mat, RNG::UNIFORM, low, high);\r\n}\r\n\r\n\r\nvoid Test::gen(Mat& mat, int rows, int cols, int type)\r\n{ \r\n mat.create(rows, cols, type);\r\n\r\n Mat mat8u(rows, cols * mat.elemSize(), CV_8U, mat.data, mat.step);\r\n\r\n RNG rng(0);\r\n rng.fill(mat, RNG::UNIFORM, Scalar(0), Scalar(256));\r\n}\r\n\r\n\r\nvoid TestSystem::run()\r\n{\r\n cout << setiosflags(ios_base::left);\r\n cout << \" \" << setw(10) << \"CPU, ms\" << setw(10) << \"GPU, ms\" \r\n << setw(10) << \"SPEEDUP\" << \"DESCRIPTION\\n\";\r\n cout << resetiosflags(ios_base::left);\r\n\r\n vector<Test*>::iterator it = tests_.begin();\r\n for (; it != tests_.end(); ++it)\r\n {\r\n can_flush_ = false;\r\n Test* test = *it;\r\n\r\n cout << endl << test->name() << \":\\n\";\r\n test->run();\r\n\r\n flush();\r\n }\r\n\r\n cout << setiosflags(ios_base::fixed | ios_base::left);\r\n cout << \"\\nCPU Total: \" << setprecision(3) << cpu_total_ \/ getTickFrequency() << \" sec\\n\";\r\n cout << \"GPU Total: \" << setprecision(3) << gpu_total_ \/ getTickFrequency() << \" sec (x\" \r\n << setprecision(3) << static_cast<double>(cpu_total_) \/ gpu_total_ << \")\\n\";\r\n cout << resetiosflags(ios_base::fixed | ios_base::left);\r\n}\r\n\r\n\r\nvoid TestSystem::flush()\r\n{\r\n if (!can_flush_)\r\n return;\r\n\r\n int cpu_time = static_cast<int>(cpu_elapsed_ \/ getTickFrequency() * 1000.0);\r\n int gpu_time = static_cast<int>(gpu_elapsed_ \/ getTickFrequency() * 1000.0);\r\n double speedup = static_cast<double>(cpu_time) \/ gpu_time;\r\n\r\n cpu_elapsed_ = 0;\r\n gpu_elapsed_ = 0;\r\n\r\n cout << \" \" << setiosflags(ios_base::fixed | ios_base::left);\r\n\r\n stringstream stream;\r\n stream << cpu_time;\r\n cout << setw(10) << stream.str();\r\n\r\n stream.str(\"\");\r\n stream << gpu_time;\r\n cout << setw(10) << stream.str();\r\n\r\n stream.str(\"\");\r\n stream << \"x\" << setprecision(3) << speedup;\r\n cout << setw(10) << stream.str();\r\n\r\n cout << description_.str();\r\n description_.str(\"\");\r\n\r\n cout << resetiosflags(ios_base::fixed | ios_base::left) << endl;\r\n can_flush_ = false;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n TestSystem::instance()->run();\r\n return 0;\r\n}<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_ISOLF_ATTRACTIVE_POTENTIAL_HPP\n#define MJOLNIR_POTENTIAL_GLOBAL_ISOLF_ATTRACTIVE_POTENTIAL_HPP\n#include <mjolnir\/core\/ExclusionList.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/math\/math.hpp>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <tuple>\n#include <cmath>\n\nnamespace mjolnir\n{\n\n\/\/ attractive part of the iSoLF potential for coarse-grained lipids developed by\n\/\/ - Diego Ugarte La Torre and Shoji Takada (2020)\n\/\/\n\/\/ This class contains sigmas, epsilons, and omegas of the particles and\n\/\/ calculates energy and derivative of the potential function.\ntemplate<typename traitsT>\nclass iSoLFAttractivePotential\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using system_type = System<traits_type>;\n using parameter_type = std::tuple<real_type, real_type, real_type>;\n using container_type = std::vector<parameter_type>;\n\n \/\/ cache sigma_ij, epsilon_ij, omega_ij, 1 \/ 2omega_ij.\n using pair_parameter_type = std::tuple<real_type, real_type, real_type, real_type>;\n\n \/\/ topology stuff\n using topology_type = Topology;\n using molecule_id_type = typename topology_type::molecule_id_type;\n using group_id_type = typename topology_type::group_id_type;\n using connection_kind_type = typename topology_type::connection_kind_type;\n using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;\n using ignore_group_type = IgnoreGroup <group_id_type>;\n using exclusion_list_type = ExclusionList <traits_type>;\n\n static constexpr parameter_type default_parameter() noexcept\n {\n return parameter_type{real_type(0), real_type(0), real_type(0)};\n }\n\n public:\n\n iSoLFAttractivePotential(\n const std::vector<std::pair<std::size_t, parameter_type>>& parameters,\n const std::map<connection_kind_type, std::size_t>& exclusions,\n ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)\n : exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))\n {\n this->parameters_ .reserve(parameters.size());\n this->participants_.reserve(parameters.size());\n for(const auto& idxp : parameters)\n {\n const auto idx = idxp.first;\n this->participants_.push_back(idx);\n if(idx >= this->parameters_.size())\n {\n this->parameters_.resize(idx+1, default_parameter());\n }\n this->parameters_.at(idx) = idxp.second;\n }\n }\n ~iSoLFAttractivePotential() = default;\n\n pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept\n {\n const auto sgm1 = std::get<0>(parameters_[i]);\n const auto eps1 = std::get<1>(parameters_[i]);\n const auto omg1 = std::get<2>(parameters_[i]);\n\n const auto sgm2 = std::get<0>(parameters_[j]);\n const auto eps2 = std::get<1>(parameters_[j]);\n const auto omg2 = std::get<2>(parameters_[j]);\n\n return std::make_tuple((sgm1 + sgm2) \/ 2,\n ((eps1 == eps2) ? eps1 : std::sqrt(eps1 * eps2)),\n (omg1 + omg2) \/ 2,\n real_type(1.0) \/ (omg1 + omg2));\n }\n\n \/\/ forwarding functions for clarity...\n real_type potential(const std::size_t i, const std::size_t j,\n const real_type r) const noexcept\n {\n return this->potential(r, this->prepare_params(i, j));\n }\n real_type derivative(const std::size_t i, const std::size_t j,\n const real_type r) const noexcept\n {\n return this->derivative(r, this->prepare_params(i, j));\n }\n\n real_type potential(const real_type r, const pair_parameter_type& p) const noexcept\n {\n constexpr real_type rc = 1.12246204831;\n constexpr real_type pi = math::constants<real_type>::pi();\n\n const real_type sigma = std::get<0>(p);\n const real_type epsilon = std::get<1>(p);\n const real_type omega = std::get<2>(p);\n\n const real_type r_sigma_rc = r - sigma * rc; \/\/ r - sqrt[6]{2} sigma\n\n if (r_sigma_rc <= 0) {return -epsilon;}\n else if(omega < r_sigma_rc){return 0;}\n\n const real_type romega = std::get<3>(p); \/\/ 1 \/ 2omega_ij\n const real_type cosine = std::cos(pi * romega * r_sigma_rc);\n\n return -epsilon * cosine * cosine;\n }\n real_type derivative(const real_type r, const pair_parameter_type& p) const noexcept\n {\n constexpr real_type rc = 1.12246204831;\n constexpr real_type pi = math::constants<real_type>::pi();\n\n const real_type sigma = std::get<0>(p);\n const real_type epsilon = std::get<1>(p);\n const real_type omega = std::get<2>(p);\n\n const real_type r_sigma_rc = r - sigma * rc; \/\/ r - sqrt[6]{2} sigma\n\n if (r_sigma_rc <= 0 || omega < r_sigma_rc) {return 0;}\n\n const real_type romega = std::get<3>(p); \/\/ 1 \/ 2omega_ij\n const real_type sine = std::sin(2 * pi * romega * r_sigma_rc);\n\n return epsilon * pi * romega * sine;\n }\n\n real_type cutoff_ratio() const noexcept {return std::numeric_limits<real_type>::infinity();}\n real_type coef_at_cutoff() const noexcept {return 0.0;}\n\n real_type max_cutoff_length() const noexcept\n {\n constexpr real_type rc = 1.12246204831; \/\/ sqrt[6]{2}\n\n if(this->parameters_.empty())\n {\n return 0.0;\n }\n\n const real_type max_sigma = std::get<0>(*std::max_element(\n this->parameters_.cbegin(), this->parameters_.cend(),\n [](const parameter_type& lhs, const parameter_type& rhs) noexcept {\n return std::get<0>(lhs) < std::get<0>(rhs);\n }));\n const real_type max_omega = std::get<2>(*std::max_element(\n this->parameters_.cbegin(), this->parameters_.cend(),\n [](const parameter_type& lhs, const parameter_type& rhs) noexcept {\n return std::get<2>(lhs) < std::get<2>(rhs);\n }));\n\n return max_sigma * rc + max_omega;\n }\n\n void initialize(const system_type& sys, const topology_type& topol) noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n this->update(sys, topol);\n return;\n }\n\n void update(const system_type& sys, const topology_type& topol) noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n \/\/ update exclusion list based on sys.topology()\n exclusion_list_.make(sys, topol);\n return;\n }\n\n \/\/ -----------------------------------------------------------------------\n \/\/ for spatial partitions\n \/\/\n \/\/ Here, the default implementation uses Newton's 3rd law to reduce\n \/\/ calculation. For an interacting pair (i, j), forces applied to i and j\n \/\/ are equal in magnitude and opposite in direction. So, if a pair (i, j) is\n \/\/ listed, (j, i) is not needed.\n \/\/ See implementation of VerletList, CellList and GlobalPairInteraction\n \/\/ for more details about the usage of these functions.\n\n std::vector<std::size_t> const& participants() const noexcept {return participants_;}\n\n range<typename std::vector<std::size_t>::const_iterator>\n leading_participants() const noexcept\n {\n return make_range(participants_.begin(), std::prev(participants_.end()));\n }\n range<typename std::vector<std::size_t>::const_iterator>\n possible_partners_of(const std::size_t participant_idx,\n const std::size_t \/*particle_idx*\/) const noexcept\n {\n return make_range(participants_.begin() + participant_idx + 1, participants_.end());\n }\n bool has_interaction(const std::size_t i, const std::size_t j) const noexcept\n {\n \/\/ if not excluded, the pair has interaction.\n return (i < j) && !exclusion_list_.is_excluded(i, j);\n }\n \/\/ for testing\n exclusion_list_type const& exclusion_list() const noexcept\n {\n return exclusion_list_;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ used by Observer.\n static const char* name() noexcept {return \"iSoLF\";}\n\n \/\/ ------------------------------------------------------------------------\n \/\/ the following accessers would be used in tests.\n\n \/\/ access to the parameters...\n std::vector<parameter_type>& parameters() noexcept {return parameters_;}\n std::vector<parameter_type> const& parameters() const noexcept {return parameters_;}\n\n private:\n\n container_type parameters_;\n std::vector<std::size_t> participants_;\n exclusion_list_type exclusion_list_;\n};\n\n} \/\/ mjolnir\n\n#ifdef MJOLNIR_SEPARATE_BUILD\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n\nnamespace mjolnir\n{\nextern template class iSoLFAttractivePotential<SimulatorTraits<double, UnlimitedBoundary> >;\nextern template class iSoLFAttractivePotential<SimulatorTraits<float, UnlimitedBoundary> >;\nextern template class iSoLFAttractivePotential<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class iSoLFAttractivePotential<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_SEPARATE_BUILD\n\n#endif \/* MJOLNIR_ISOLF_ATTRACTIVE_POTENTIAL *\/\n<commit_msg>chore: add bibliographic info<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_ISOLF_ATTRACTIVE_POTENTIAL_HPP\n#define MJOLNIR_POTENTIAL_GLOBAL_ISOLF_ATTRACTIVE_POTENTIAL_HPP\n#include <mjolnir\/core\/ExclusionList.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/math\/math.hpp>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <tuple>\n#include <cmath>\n\nnamespace mjolnir\n{\n\n\/\/ attractive part of the iSoLF potential for coarse-grained lipids developed by\n\/\/ - Diego Ugarte La Torre and Shoji Takada (2020) J. Chem. Phys 153, 205101\n\/\/ https:\/\/doi.org\/10.1063\/5.0026342\n\/\/\n\/\/ This class contains sigmas, epsilons, and omegas of the particles and\n\/\/ calculates energy and derivative of the potential function.\ntemplate<typename traitsT>\nclass iSoLFAttractivePotential\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using system_type = System<traits_type>;\n using parameter_type = std::tuple<real_type, real_type, real_type>;\n using container_type = std::vector<parameter_type>;\n\n \/\/ cache sigma_ij, epsilon_ij, omega_ij, 1 \/ 2omega_ij.\n using pair_parameter_type = std::tuple<real_type, real_type, real_type, real_type>;\n\n \/\/ topology stuff\n using topology_type = Topology;\n using molecule_id_type = typename topology_type::molecule_id_type;\n using group_id_type = typename topology_type::group_id_type;\n using connection_kind_type = typename topology_type::connection_kind_type;\n using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;\n using ignore_group_type = IgnoreGroup <group_id_type>;\n using exclusion_list_type = ExclusionList <traits_type>;\n\n static constexpr parameter_type default_parameter() noexcept\n {\n return parameter_type{real_type(0), real_type(0), real_type(0)};\n }\n\n public:\n\n iSoLFAttractivePotential(\n const std::vector<std::pair<std::size_t, parameter_type>>& parameters,\n const std::map<connection_kind_type, std::size_t>& exclusions,\n ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)\n : exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))\n {\n this->parameters_ .reserve(parameters.size());\n this->participants_.reserve(parameters.size());\n for(const auto& idxp : parameters)\n {\n const auto idx = idxp.first;\n this->participants_.push_back(idx);\n if(idx >= this->parameters_.size())\n {\n this->parameters_.resize(idx+1, default_parameter());\n }\n this->parameters_.at(idx) = idxp.second;\n }\n }\n ~iSoLFAttractivePotential() = default;\n\n pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept\n {\n const auto sgm1 = std::get<0>(parameters_[i]);\n const auto eps1 = std::get<1>(parameters_[i]);\n const auto omg1 = std::get<2>(parameters_[i]);\n\n const auto sgm2 = std::get<0>(parameters_[j]);\n const auto eps2 = std::get<1>(parameters_[j]);\n const auto omg2 = std::get<2>(parameters_[j]);\n\n return std::make_tuple((sgm1 + sgm2) \/ 2,\n ((eps1 == eps2) ? eps1 : std::sqrt(eps1 * eps2)),\n (omg1 + omg2) \/ 2,\n real_type(1.0) \/ (omg1 + omg2));\n }\n\n \/\/ forwarding functions for clarity...\n real_type potential(const std::size_t i, const std::size_t j,\n const real_type r) const noexcept\n {\n return this->potential(r, this->prepare_params(i, j));\n }\n real_type derivative(const std::size_t i, const std::size_t j,\n const real_type r) const noexcept\n {\n return this->derivative(r, this->prepare_params(i, j));\n }\n\n real_type potential(const real_type r, const pair_parameter_type& p) const noexcept\n {\n constexpr real_type rc = 1.12246204831;\n constexpr real_type pi = math::constants<real_type>::pi();\n\n const real_type sigma = std::get<0>(p);\n const real_type epsilon = std::get<1>(p);\n const real_type omega = std::get<2>(p);\n\n const real_type r_sigma_rc = r - sigma * rc; \/\/ r - sqrt[6]{2} sigma\n\n if (r_sigma_rc <= 0) {return -epsilon;}\n else if(omega < r_sigma_rc){return 0;}\n\n const real_type romega = std::get<3>(p); \/\/ 1 \/ 2omega_ij\n const real_type cosine = std::cos(pi * romega * r_sigma_rc);\n\n return -epsilon * cosine * cosine;\n }\n real_type derivative(const real_type r, const pair_parameter_type& p) const noexcept\n {\n constexpr real_type rc = 1.12246204831;\n constexpr real_type pi = math::constants<real_type>::pi();\n\n const real_type sigma = std::get<0>(p);\n const real_type epsilon = std::get<1>(p);\n const real_type omega = std::get<2>(p);\n\n const real_type r_sigma_rc = r - sigma * rc; \/\/ r - sqrt[6]{2} sigma\n\n if (r_sigma_rc <= 0 || omega < r_sigma_rc) {return 0;}\n\n const real_type romega = std::get<3>(p); \/\/ 1 \/ 2omega_ij\n const real_type sine = std::sin(2 * pi * romega * r_sigma_rc);\n\n return epsilon * pi * romega * sine;\n }\n\n real_type cutoff_ratio() const noexcept {return std::numeric_limits<real_type>::infinity();}\n real_type coef_at_cutoff() const noexcept {return 0.0;}\n\n real_type max_cutoff_length() const noexcept\n {\n constexpr real_type rc = 1.12246204831; \/\/ sqrt[6]{2}\n\n if(this->parameters_.empty())\n {\n return 0.0;\n }\n\n const real_type max_sigma = std::get<0>(*std::max_element(\n this->parameters_.cbegin(), this->parameters_.cend(),\n [](const parameter_type& lhs, const parameter_type& rhs) noexcept {\n return std::get<0>(lhs) < std::get<0>(rhs);\n }));\n const real_type max_omega = std::get<2>(*std::max_element(\n this->parameters_.cbegin(), this->parameters_.cend(),\n [](const parameter_type& lhs, const parameter_type& rhs) noexcept {\n return std::get<2>(lhs) < std::get<2>(rhs);\n }));\n\n return max_sigma * rc + max_omega;\n }\n\n void initialize(const system_type& sys, const topology_type& topol) noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n this->update(sys, topol);\n return;\n }\n\n void update(const system_type& sys, const topology_type& topol) noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n \/\/ update exclusion list based on sys.topology()\n exclusion_list_.make(sys, topol);\n return;\n }\n\n \/\/ -----------------------------------------------------------------------\n \/\/ for spatial partitions\n \/\/\n \/\/ Here, the default implementation uses Newton's 3rd law to reduce\n \/\/ calculation. For an interacting pair (i, j), forces applied to i and j\n \/\/ are equal in magnitude and opposite in direction. So, if a pair (i, j) is\n \/\/ listed, (j, i) is not needed.\n \/\/ See implementation of VerletList, CellList and GlobalPairInteraction\n \/\/ for more details about the usage of these functions.\n\n std::vector<std::size_t> const& participants() const noexcept {return participants_;}\n\n range<typename std::vector<std::size_t>::const_iterator>\n leading_participants() const noexcept\n {\n return make_range(participants_.begin(), std::prev(participants_.end()));\n }\n range<typename std::vector<std::size_t>::const_iterator>\n possible_partners_of(const std::size_t participant_idx,\n const std::size_t \/*particle_idx*\/) const noexcept\n {\n return make_range(participants_.begin() + participant_idx + 1, participants_.end());\n }\n bool has_interaction(const std::size_t i, const std::size_t j) const noexcept\n {\n \/\/ if not excluded, the pair has interaction.\n return (i < j) && !exclusion_list_.is_excluded(i, j);\n }\n \/\/ for testing\n exclusion_list_type const& exclusion_list() const noexcept\n {\n return exclusion_list_;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ used by Observer.\n static const char* name() noexcept {return \"iSoLF\";}\n\n \/\/ ------------------------------------------------------------------------\n \/\/ the following accessers would be used in tests.\n\n \/\/ access to the parameters...\n std::vector<parameter_type>& parameters() noexcept {return parameters_;}\n std::vector<parameter_type> const& parameters() const noexcept {return parameters_;}\n\n private:\n\n container_type parameters_;\n std::vector<std::size_t> participants_;\n exclusion_list_type exclusion_list_;\n};\n\n} \/\/ mjolnir\n\n#ifdef MJOLNIR_SEPARATE_BUILD\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n\nnamespace mjolnir\n{\nextern template class iSoLFAttractivePotential<SimulatorTraits<double, UnlimitedBoundary> >;\nextern template class iSoLFAttractivePotential<SimulatorTraits<float, UnlimitedBoundary> >;\nextern template class iSoLFAttractivePotential<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class iSoLFAttractivePotential<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_SEPARATE_BUILD\n\n#endif \/* MJOLNIR_ISOLF_ATTRACTIVE_POTENTIAL *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <p4est_base.h>\n\n#include \"amr_utils.H\"\n#include \"fclaw2d_solvers.H\"\n\nint pow_int(int a, int n)\n{\n int b = 1;\n for(int i = 0; i < n; i++)\n {\n b *= a;\n }\n return b;\n}\n\nstatic void problem_setup_default(fclaw2d_domain_t* domain)\n{\n}\n\n\n\/* -----------------------------------------------------------------\n Initialize data\n ----------------------------------------------------------------- *\/\n\n\/\/ Should this maybe be 'allocate_domain_data' instead? Reserve 'init'\n\/\/ assigning default values to items?\nvoid init_domain_data(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t* ddata = (fclaw2d_domain_data_t*) domain->user;\n ddata = FCLAW2D_ALLOC_ZERO(fclaw2d_domain_data_t, 1);\n domain->user = (void *) ddata;\n\n ddata->count_set_clawpatch = ddata->count_delete_clawpatch = 0;\n ddata->count_amr_advance = 0;\n ddata->count_ghost_exchange = 0;\n ddata->count_amr_regrid = 0;\n ddata->is_latest_domain = 0; \/* set 1 by amrinit or rebuild_domain *\/\n\n ddata->domain_exchange = NULL;\n\n ddata->amropts = NULL;\n ddata->curr_time = 0;\n\n \/* I put this here because somehow it is not part of a 'solver' *\/\n ddata->f_problem_setup = &problem_setup_default;\n\n fclaw2d_solver_functions_t* solver_functions = FCLAW2D_ALLOC(fclaw2d_solver_functions_t, 1);\n initialize_solver_functions(solver_functions);\n ddata->solver_functions = solver_functions;\n\n fclaw2d_regrid_functions_t* regrid_functions = FCLAW2D_ALLOC(fclaw2d_regrid_functions_t, 1);\n initialize_regrid_functions(regrid_functions);\n ddata->regrid_functions = regrid_functions;\n\n fclaw2d_output_functions_t* output_functions = FCLAW2D_ALLOC(fclaw2d_output_functions_t, 1);\n initialize_output_functions(output_functions);\n ddata->output_functions = output_functions;\n}\n\nvoid delete_domain_data(fclaw2d_domain_t* domain)\n{\n fclaw2d_domain_data_t* ddata = (fclaw2d_domain_data_t*) domain->user;\n\n fclaw2d_solver_functions_t *sf = (fclaw2d_solver_functions_t*) ddata->solver_functions;\n if (sf != NULL)\n {\n FCLAW2D_FREE(sf);\n ddata->solver_functions = (fclaw2d_solver_functions_t*) NULL;\n }\n\n fclaw2d_regrid_functions_t *rf = (fclaw2d_regrid_functions_t*) ddata->regrid_functions;\n if (rf != NULL)\n {\n FCLAW2D_FREE(rf);\n ddata->regrid_functions = (fclaw2d_regrid_functions_t*) NULL;\n }\n\n fclaw2d_output_functions_t *of = (fclaw2d_output_functions_t*) ddata->output_functions;\n if (of != NULL)\n {\n FCLAW2D_FREE(of);\n ddata->output_functions = (fclaw2d_output_functions_t*) NULL;\n }\n\n FCLAW2D_FREE (ddata);\n domain->user = NULL;\n}\n\nvoid init_block_data(fclaw2d_block_t *block)\n{\n fclaw2d_block_data_t *bdata = FCLAW2D_ALLOC_ZERO (fclaw2d_block_data_t, 1);\n block->user = (void *) bdata;\n}\n\n\nvoid init_patch_data(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pdata = FCLAW2D_ALLOC(fclaw2d_patch_data_t, 1);\n patch->user = (void *) pdata;\n}\n\nvoid delete_patch_data(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pd = (fclaw2d_patch_data_t*) patch->user;\n FCLAW2D_FREE(pd);\n}\n\n\/* -----------------------------------------------------------------\n Work with timers\n ----------------------------------------------------------------- *\/\n\ndouble\nfclaw2d_timer_wtime (void)\n{\n return MPI_Wtime ();\n}\n\nvoid\nfclaw2d_timer_init (fclaw2d_timer_t *timer)\n{\n memset (timer, 0, sizeof (fclaw2d_timer_t));\n}\n\nvoid\nfclaw2d_timer_start (fclaw2d_timer_t *timer)\n{\n if (!timer->running) {\n timer->started = fclaw2d_timer_wtime ();\n timer->stopped = 0.;\n timer->running = 1;\n }\n else\n {\n SC_ABORT_NOT_REACHED ();\n }\n}\n\nvoid\nfclaw2d_timer_stop (fclaw2d_timer_t *timer)\n{\n if (timer->running) {\n timer->stopped = fclaw2d_timer_wtime ();\n timer->cumulative += timer->stopped - timer->started;\n timer->running = 0;\n }\n else\n {\n SC_ABORT_NOT_REACHED ();\n }\n}\n\n\/\/ -----------------------------------------------------------------\n\/\/ Return pointer to user data\n\/\/ -----------------------------------------------------------------\nfclaw2d_domain_data_t *get_domain_data(fclaw2d_domain_t *domain)\n{\n return (fclaw2d_domain_data_t *) domain->user;\n}\n\n\nfclaw2d_block_data_t *get_block_data(fclaw2d_block_t *block)\n{\n return (fclaw2d_block_data_t *) block->user;\n}\n\n\nfclaw2d_patch_data_t *get_patch_data(fclaw2d_patch_t *patch)\n{\n return (fclaw2d_patch_data_t *) patch->user;\n}\n\n\n\/\/ -----------------------------------------------------------------\n\/\/ Set user data with user defined variables, etc.\n\/\/ -----------------------------------------------------------------\n\nvoid copy_domain_data(fclaw2d_domain_t *old_domain, fclaw2d_domain_t *new_domain)\n{\n fclaw2d_domain_data_t *ddata_old = get_domain_data(old_domain);\n\n \/* Has the data already been allocated? *\/\n fclaw2d_domain_data_t *ddata_new = get_domain_data(new_domain);\n\n\n \/* Move timers over to the new domain *\/\n ddata_old->is_latest_domain = 0;\n memcpy (ddata_new->timers, ddata_old->timers,\n sizeof (fclaw2d_timer_t) * FCLAW2D_TIMER_COUNT);\n ddata_new->is_latest_domain = 1;\n ddata_new->count_amr_advance = ddata_old->count_amr_advance;\n ddata_new->count_ghost_exchange = ddata_old->count_ghost_exchange;\n ddata_new->count_amr_regrid = ddata_old->count_amr_regrid;\n\n\n \/*\n We don't need to copy domain_exchange, since it is rebuilt whenever\n we create a new domain.\n *\/\n\n \/* Copy data members *\/\n ddata_new->amropts = ddata_old->amropts;\n ddata_new->waveprop_parms = ddata_old->waveprop_parms;\n ddata_new->manyclaw_parms = ddata_old->manyclaw_parms;\n\n ddata_new->curr_time = ddata_old->curr_time;\n\n ddata_new->f_problem_setup = ddata_old->f_problem_setup;\n\n copy_solver_functions(ddata_old->solver_functions,ddata_new->solver_functions);\n copy_regrid_functions(ddata_old->regrid_functions,ddata_new->regrid_functions);\n copy_output_functions(ddata_old->output_functions,ddata_new->output_functions);\n}\n\n\n\nvoid set_block_data(fclaw2d_block_t *block, const int mthbc[])\n{\n fclaw2d_block_data_t *bdata = get_block_data(block);\n for(int i = 0; i < 4; i++)\n {\n bdata->mthbc[i] = mthbc[i];\n }\n}\n\n\nvoid set_patch_data(fclaw2d_patch_t *patch, ClawPatch* cp)\n{\n fclaw2d_patch_data_t *pdata = get_patch_data(patch);\n pdata->cp = cp;\n}\n\n\n\/\/ -----------------------------------------------------------------\n\/\/ Some lazy helper functions that really do make things easier..\n\/\/ -----------------------------------------------------------------\nvoid init_block_and_patch_data(fclaw2d_domain_t *domain)\n{\n fclaw2d_block_t *block;\n fclaw2d_patch_t *patch;\n\n \/\/ init_domain_data(domain);\n\n for (int i = 0; i < domain->num_blocks; i++)\n {\n block = &domain->blocks[i];\n init_block_data(block);\n for (int j = 0; j < block->num_patches; j++)\n {\n patch = &block->patches[j];\n init_patch_data(patch);\n }\n }\n}\n\n\nvoid link_problem_setup(fclaw2d_domain_t* domain, fclaw2d_problem_setup_t f_problem_setup)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->f_problem_setup = f_problem_setup;\n}\n\nconst amr_options_t* get_domain_parms(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->amropts;\n}\n\nvoid set_domain_parms(fclaw2d_domain_t *domain, const amr_options_t* gparms)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->amropts = gparms;\n}\n\nvoid set_domain_time(fclaw2d_domain_t *domain, double time)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->curr_time = time;\n}\n\ndouble get_domain_time(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->curr_time;\n}\n\nfclaw2d_domain_exchange_t*\n get_domain_exchange_data(fclaw2d_domain_t* domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->domain_exchange;\n}\n\nvoid set_domain_exchange_data(fclaw2d_domain_t* domain,fclaw2d_domain_exchange_t *e)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->domain_exchange = e;\n}\n\n\n\n\n\n\/\/ Will change the name of this to 'get_clawpatch' eventually\nClawPatch* get_clawpatch(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;\n\n return pdata->cp;\n}\n\n\/* end of helper functions *\/\n\n\nstatic void cb_num_patches(fclaw2d_domain_t *domain,\n\tfclaw2d_patch_t *patch, int block_no, int patch_no, void *user)\n{\n (*(int *) user)++;\n}\n\nint num_patches(fclaw2d_domain_t *domain, int level, int include_shadow)\n{\n int count = 0;\n if (include_shadow == 0)\n {\n fclaw2d_domain_iterate_level(domain, level,\n cb_num_patches,\n &count);\n }\n else\n {\n \/\/ Include shadow patches\n }\n return count;\n}\n\n\/* Functions with C prototypes to use forestclaw from C code *\/\n\nvoid\nfclaw_mpi_init (int * argc, char *** argv, MPI_Comm mpicomm, int lp)\n{\n int mpiret;\n\n mpiret = MPI_Init (argc, argv);\n SC_CHECK_MPI (mpiret);\n\n sc_init (mpicomm, 0, 0, NULL, lp);\n p4est_init (NULL, lp);\n}\n\nvoid\nfclaw_mpi_finalize (void)\n{\n int mpiret;\n\n sc_finalize ();\n\n mpiret = MPI_Finalize ();\n SC_CHECK_MPI (mpiret);\n}\n<commit_msg>Use mpi_init_threads.<commit_after>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <p4est_base.h>\n\n#include \"amr_utils.H\"\n#include \"fclaw2d_solvers.H\"\n\nint pow_int(int a, int n)\n{\n int b = 1;\n for(int i = 0; i < n; i++)\n {\n b *= a;\n }\n return b;\n}\n\nstatic void problem_setup_default(fclaw2d_domain_t* domain)\n{\n}\n\n\n\/* -----------------------------------------------------------------\n Initialize data\n ----------------------------------------------------------------- *\/\n\n\/\/ Should this maybe be 'allocate_domain_data' instead? Reserve 'init'\n\/\/ assigning default values to items?\nvoid init_domain_data(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t* ddata = (fclaw2d_domain_data_t*) domain->user;\n ddata = FCLAW2D_ALLOC_ZERO(fclaw2d_domain_data_t, 1);\n domain->user = (void *) ddata;\n\n ddata->count_set_clawpatch = ddata->count_delete_clawpatch = 0;\n ddata->count_amr_advance = 0;\n ddata->count_ghost_exchange = 0;\n ddata->count_amr_regrid = 0;\n ddata->is_latest_domain = 0; \/* set 1 by amrinit or rebuild_domain *\/\n\n ddata->domain_exchange = NULL;\n\n ddata->amropts = NULL;\n ddata->curr_time = 0;\n\n \/* I put this here because somehow it is not part of a 'solver' *\/\n ddata->f_problem_setup = &problem_setup_default;\n\n fclaw2d_solver_functions_t* solver_functions = FCLAW2D_ALLOC(fclaw2d_solver_functions_t, 1);\n initialize_solver_functions(solver_functions);\n ddata->solver_functions = solver_functions;\n\n fclaw2d_regrid_functions_t* regrid_functions = FCLAW2D_ALLOC(fclaw2d_regrid_functions_t, 1);\n initialize_regrid_functions(regrid_functions);\n ddata->regrid_functions = regrid_functions;\n\n fclaw2d_output_functions_t* output_functions = FCLAW2D_ALLOC(fclaw2d_output_functions_t, 1);\n initialize_output_functions(output_functions);\n ddata->output_functions = output_functions;\n}\n\nvoid delete_domain_data(fclaw2d_domain_t* domain)\n{\n fclaw2d_domain_data_t* ddata = (fclaw2d_domain_data_t*) domain->user;\n\n fclaw2d_solver_functions_t *sf = (fclaw2d_solver_functions_t*) ddata->solver_functions;\n if (sf != NULL)\n {\n FCLAW2D_FREE(sf);\n ddata->solver_functions = (fclaw2d_solver_functions_t*) NULL;\n }\n\n fclaw2d_regrid_functions_t *rf = (fclaw2d_regrid_functions_t*) ddata->regrid_functions;\n if (rf != NULL)\n {\n FCLAW2D_FREE(rf);\n ddata->regrid_functions = (fclaw2d_regrid_functions_t*) NULL;\n }\n\n fclaw2d_output_functions_t *of = (fclaw2d_output_functions_t*) ddata->output_functions;\n if (of != NULL)\n {\n FCLAW2D_FREE(of);\n ddata->output_functions = (fclaw2d_output_functions_t*) NULL;\n }\n\n FCLAW2D_FREE (ddata);\n domain->user = NULL;\n}\n\nvoid init_block_data(fclaw2d_block_t *block)\n{\n fclaw2d_block_data_t *bdata = FCLAW2D_ALLOC_ZERO (fclaw2d_block_data_t, 1);\n block->user = (void *) bdata;\n}\n\n\nvoid init_patch_data(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pdata = FCLAW2D_ALLOC(fclaw2d_patch_data_t, 1);\n patch->user = (void *) pdata;\n}\n\nvoid delete_patch_data(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pd = (fclaw2d_patch_data_t*) patch->user;\n FCLAW2D_FREE(pd);\n}\n\n\/* -----------------------------------------------------------------\n Work with timers\n ----------------------------------------------------------------- *\/\n\ndouble\nfclaw2d_timer_wtime (void)\n{\n return MPI_Wtime ();\n}\n\nvoid\nfclaw2d_timer_init (fclaw2d_timer_t *timer)\n{\n memset (timer, 0, sizeof (fclaw2d_timer_t));\n}\n\nvoid\nfclaw2d_timer_start (fclaw2d_timer_t *timer)\n{\n if (!timer->running) {\n timer->started = fclaw2d_timer_wtime ();\n timer->stopped = 0.;\n timer->running = 1;\n }\n else\n {\n SC_ABORT_NOT_REACHED ();\n }\n}\n\nvoid\nfclaw2d_timer_stop (fclaw2d_timer_t *timer)\n{\n if (timer->running) {\n timer->stopped = fclaw2d_timer_wtime ();\n timer->cumulative += timer->stopped - timer->started;\n timer->running = 0;\n }\n else\n {\n SC_ABORT_NOT_REACHED ();\n }\n}\n\n\/\/ -----------------------------------------------------------------\n\/\/ Return pointer to user data\n\/\/ -----------------------------------------------------------------\nfclaw2d_domain_data_t *get_domain_data(fclaw2d_domain_t *domain)\n{\n return (fclaw2d_domain_data_t *) domain->user;\n}\n\n\nfclaw2d_block_data_t *get_block_data(fclaw2d_block_t *block)\n{\n return (fclaw2d_block_data_t *) block->user;\n}\n\n\nfclaw2d_patch_data_t *get_patch_data(fclaw2d_patch_t *patch)\n{\n return (fclaw2d_patch_data_t *) patch->user;\n}\n\n\n\/\/ -----------------------------------------------------------------\n\/\/ Set user data with user defined variables, etc.\n\/\/ -----------------------------------------------------------------\n\nvoid copy_domain_data(fclaw2d_domain_t *old_domain, fclaw2d_domain_t *new_domain)\n{\n fclaw2d_domain_data_t *ddata_old = get_domain_data(old_domain);\n\n \/* Has the data already been allocated? *\/\n fclaw2d_domain_data_t *ddata_new = get_domain_data(new_domain);\n\n\n \/* Move timers over to the new domain *\/\n ddata_old->is_latest_domain = 0;\n memcpy (ddata_new->timers, ddata_old->timers,\n sizeof (fclaw2d_timer_t) * FCLAW2D_TIMER_COUNT);\n ddata_new->is_latest_domain = 1;\n ddata_new->count_amr_advance = ddata_old->count_amr_advance;\n ddata_new->count_ghost_exchange = ddata_old->count_ghost_exchange;\n ddata_new->count_amr_regrid = ddata_old->count_amr_regrid;\n\n\n \/*\n We don't need to copy domain_exchange, since it is rebuilt whenever\n we create a new domain.\n *\/\n\n \/* Copy data members *\/\n ddata_new->amropts = ddata_old->amropts;\n ddata_new->waveprop_parms = ddata_old->waveprop_parms;\n ddata_new->manyclaw_parms = ddata_old->manyclaw_parms;\n\n ddata_new->curr_time = ddata_old->curr_time;\n\n ddata_new->f_problem_setup = ddata_old->f_problem_setup;\n\n copy_solver_functions(ddata_old->solver_functions,ddata_new->solver_functions);\n copy_regrid_functions(ddata_old->regrid_functions,ddata_new->regrid_functions);\n copy_output_functions(ddata_old->output_functions,ddata_new->output_functions);\n}\n\n\n\nvoid set_block_data(fclaw2d_block_t *block, const int mthbc[])\n{\n fclaw2d_block_data_t *bdata = get_block_data(block);\n for(int i = 0; i < 4; i++)\n {\n bdata->mthbc[i] = mthbc[i];\n }\n}\n\n\nvoid set_patch_data(fclaw2d_patch_t *patch, ClawPatch* cp)\n{\n fclaw2d_patch_data_t *pdata = get_patch_data(patch);\n pdata->cp = cp;\n}\n\n\n\/\/ -----------------------------------------------------------------\n\/\/ Some lazy helper functions that really do make things easier..\n\/\/ -----------------------------------------------------------------\nvoid init_block_and_patch_data(fclaw2d_domain_t *domain)\n{\n fclaw2d_block_t *block;\n fclaw2d_patch_t *patch;\n\n \/\/ init_domain_data(domain);\n\n for (int i = 0; i < domain->num_blocks; i++)\n {\n block = &domain->blocks[i];\n init_block_data(block);\n for (int j = 0; j < block->num_patches; j++)\n {\n patch = &block->patches[j];\n init_patch_data(patch);\n }\n }\n}\n\n\nvoid link_problem_setup(fclaw2d_domain_t* domain, fclaw2d_problem_setup_t f_problem_setup)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->f_problem_setup = f_problem_setup;\n}\n\nconst amr_options_t* get_domain_parms(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->amropts;\n}\n\nvoid set_domain_parms(fclaw2d_domain_t *domain, const amr_options_t* gparms)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->amropts = gparms;\n}\n\nvoid set_domain_time(fclaw2d_domain_t *domain, double time)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->curr_time = time;\n}\n\ndouble get_domain_time(fclaw2d_domain_t *domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->curr_time;\n}\n\nfclaw2d_domain_exchange_t*\n get_domain_exchange_data(fclaw2d_domain_t* domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n return ddata->domain_exchange;\n}\n\nvoid set_domain_exchange_data(fclaw2d_domain_t* domain,fclaw2d_domain_exchange_t *e)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (domain);\n ddata->domain_exchange = e;\n}\n\n\n\n\n\n\/\/ Will change the name of this to 'get_clawpatch' eventually\nClawPatch* get_clawpatch(fclaw2d_patch_t *patch)\n{\n fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;\n\n return pdata->cp;\n}\n\n\/* end of helper functions *\/\n\n\nstatic void cb_num_patches(fclaw2d_domain_t *domain,\n\tfclaw2d_patch_t *patch, int block_no, int patch_no, void *user)\n{\n (*(int *) user)++;\n}\n\nint num_patches(fclaw2d_domain_t *domain, int level, int include_shadow)\n{\n int count = 0;\n if (include_shadow == 0)\n {\n fclaw2d_domain_iterate_level(domain, level,\n cb_num_patches,\n &count);\n }\n else\n {\n \/\/ Include shadow patches\n }\n return count;\n}\n\n\/* Functions with C prototypes to use forestclaw from C code *\/\n\nvoid\nfclaw_mpi_init (int * argc, char *** argv, MPI_Comm mpicomm, int lp)\n{\n int mpiret;\n\n \/\/mpiret = MPI_Init (argc, argv);\n \/\/SC_CHECK_MPI (mpiret);\n\n int provided;\n mpiret = MPI_Init_thread (argc, argv, MPI_THREAD_FUNNELED, &provided);\n if (provided != MPI_THREAD_FUNNELED) printf(\"Recieved mpi_init_thread level %d\\n\", provided);\n SC_CHECK_MPI (mpiret);\n\n sc_init (mpicomm, 0, 0, NULL, lp);\n p4est_init (NULL, lp);\n}\n\nvoid\nfclaw_mpi_finalize (void)\n{\n int mpiret;\n\n sc_finalize ();\n\n mpiret = MPI_Finalize ();\n SC_CHECK_MPI (mpiret);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ c4-console.cpp : Defines the entry point for the console application.\n\/\/\n\n\/\/#include \"stdafx.h\"\n\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include <sstream>\n#include <boost\/asio.hpp>\n#include <boost\/program_options.hpp>\n\n#include \"director.hpp\"\n#include \"c4socket.hpp\"\n#include \"cmd_parser.hpp\"\n\n#define THROW_BOOST_ERROR( e ) if (e.value() > 0) throw e\n\nnamespace po = boost::program_options;\nusing boost::asio::ip::tcp;\n\nstatic const std::string ver = \"1.0.3\";\nstatic const std::string bld_date_time = \"9\/12\/14; 8:45 AM\";\n\nvoid \nprint(const std::string& out)\n{\n std::cout << out;\n}\n\nvoid \nprint_ln(const std::string& out)\n{\n print(out);\n std::cout << std::endl;\n}\n\nvoid\nprint_error(const std::string& err)\n{\n\tstd::string out = \"ERROR: \" + err;\n\tprint_ln(out);\n}\n\nvoid\nprint_banner(void)\n{\n\tprint_ln(\"c4-console - A command line tool to send C4SOAP commands to a Control4 controller.\");\n\tprint_ln(\"Version: \" + ver);\n\tprint_ln(\"Built: \" + bld_date_time);\n\tprint_ln(\"(c) Terry Seyler 2014. All rights reserved.\");\n\tprint_ln(\"------------\");\n}\n\nvoid \nprint_usage(void)\n{\n std::cout << \"Usage:\" << std::endl;\n std::cout << \"$ c4-console <host> <command> [id] [param1] [param2] ...\" << std::endl;\n}\n\nbool \nprocess_cmd(bool is_shell, cmd_parser& parser)\n{\n\n\treturn is_shell;\n}\n\nchar**\nget_args(char* argv[], int first_arg)\n{\n return &argv[first_arg];\n}\n\nint \nmain(int argc, \n\tchar *argv[])\n{\n\tbool silent(false);\n\tbool is_shell(false);\n\tint first_arg(1);\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"help,h\", \"Prints the help message\")\n\t\t(\"silent,s\", \"Suppresses the copyright banner\");\n\n\tpo::variables_map vm;\n\ttry\n\t{\n\t\tpo::store(po::parse_command_line(argc--, argv, desc), vm);\n\n\n\t\tif (vm.count(\"silent\"))\n\t\t{\n\t\t\tsilent = true;\n\t\t\targc--;\n\t\t\tfirst_arg++;\n\t\t}\n\n\t\tif (!silent) \n\t\t\tprint_banner();\n\n\t\tif (vm.count(\"help\"))\n\t\t{\n\t\t\tprint_usage();\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcatch (po::error& e)\n\t{\n\n\n\t}\n\t\n if (argc > 1)\n {\n\t\tchar** args = get_args(argv, first_arg);\n\t\tcmd_parser parser(args, argc);\n\t\tstd::string host = parser.host();\n\t\tstd::string cmd = parser.cmd();\n\n\t\tboost::system::error_code ec;\n\t\tboost::asio::io_service io_service;\n\t\ttcp::resolver resolver(io_service);\n\t\ttcp::resolver::query query(host.c_str(), \"5020\");\n\t\ttcp::resolver::iterator iterator;\n\t\ttry\n\t\t{\n\t\t\titerator = resolver.resolve(query, ec);\n\t\t\tTHROW_BOOST_ERROR( ec );\n\t\t}\n\t\tcatch (boost::system::error_code& e)\n\t\t{\n\t\t\tprint_error(e.message());\n\t\t\treturn e.value();\n\t\t}\n\t\t\n\t\ttcp::socket s(io_service);\n\t\ttry\n\t\t{\n\t\t\ttcp::endpoint ep = *iterator;\n\t\t\ts.connect(ep, ec);\n\t\t\tTHROW_BOOST_ERROR( ec );\n\t\t}\n\t\tcatch (boost::system::error_code& e)\n\t\t{\n\t\t\tprint_error(e.message());\n\t\t\treturn e.value();\n\t\t}\n\n\n\t\t\/\/ authenticate\n\t\tint seq(1);\n\t\tstd::string msg = parser.to_authenticate(seq);\n\t\tc4socket::write_msg(s, msg);\n\t\tstd::string reply = c4socket::read_msg(s);\n\t\tprint_ln(reply);\n\n\t\tmsg = parser.to_c4soap(seq);\n\t\tif (parser.parsed())\n\t\t{\n\t\t\tc4socket::write_msg(s, msg);\n\t\t\treply = c4socket::read_msg(s);\n\t\t\tprint_ln(reply);\n\t\t}\n\t\telse\n\t\t\tprint_ln(\"Unknown or malformed command: \" + cmd);\n\t}\n\telse\n\t\tprint_usage();\n\n\treturn 0;\n}\n\n<commit_msg>Made more changes to c4-console<commit_after>\/\/ c4-console.cpp : Defines the entry point for the console application.\n\/\/\n\n\/\/#include \"stdafx.h\"\n\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include <sstream>\n#include <boost\/asio.hpp>\n#include <boost\/program_options.hpp>\n\n#include \"director.hpp\"\n#include \"c4socket.hpp\"\n#include \"cmd_parser.hpp\"\n\n#define THROW_BOOST_ERROR( e ) if (e.value() > 0) throw e\n\nnamespace po = boost::program_options;\nusing boost::asio::ip::tcp;\n\nstatic const std::string ver = \"1.0.4\";\nstatic const std::string bld_date_time = \"9\/12\/14; 11:10 AM\";\n\nvoid \nprint(const std::string& out)\n{\n std::cout << out;\n}\n\nvoid \nprint_ln(const std::string& out)\n{\n print(out);\n std::cout << std::endl;\n}\n\nvoid\nprint_error(const std::string& err)\n{\n\tstd::string out = \"ERROR: \" + err;\n\tprint_ln(out);\n}\n\nvoid\nprint_banner(void)\n{\n\tprint_ln(\"c4-console - A command line tool to send C4SOAP commands to a Control4 controller.\");\n\tprint_ln(\"Version: \" + ver);\n\tprint_ln(\"Built: \" + bld_date_time);\n\tprint_ln(\"(c) Terry Seyler 2014. All rights reserved.\");\n\tprint_ln(\"------------\");\n}\n\nvoid \nprint_usage(void)\n{\n std::cout << \"Usage:\" << std::endl;\n std::cout << \"$ c4-console <host> <command> [id] [param1] [param2] ...\" << std::endl;\n}\n\nchar**\nget_args(char* argv[], int first_arg)\n{\n return &argv[first_arg];\n}\n\nint \nmain(int argc, \n\tchar *argv[])\n{\n\tbool silent(false);\n\tbool is_shell(false);\n\tint first_arg(1);\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"help,h\", \"Prints the help message\")\n\t\t(\"silent,s\", \"Suppresses the copyright banner\");\n\n\tpo::variables_map vm;\n\ttry\n\t{\n\t\tpo::store(po::parse_command_line(argc--, argv, desc), vm);\n\n\n\t\tif (vm.count(\"silent\"))\n\t\t{\n\t\t\tsilent = true;\n\t\t\targc--;\n\t\t\tfirst_arg++;\n\t\t}\n\n\t\tif (!silent) \n\t\t\tprint_banner();\n\n\t\tif (vm.count(\"help\"))\n\t\t{\n\t\t\tprint_usage();\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcatch (po::error& e)\n\t{\n\n\n\t}\n\t\n if (argc > 1)\n {\n\t\tchar** args = get_args(argv, first_arg);\n\t\tcmd_parser parser(args, argc);\n\t\tstd::string host = parser.host();\n\t\tstd::string cmd = parser.cmd();\n\n\t\tboost::system::error_code ec;\n\t\tboost::asio::io_service io_service;\n\t\ttcp::resolver resolver(io_service);\n\t\ttcp::resolver::query query(host.c_str(), \"5020\");\n\t\ttcp::resolver::iterator iterator;\n\t\ttry\n\t\t{\n\t\t\titerator = resolver.resolve(query, ec);\n\t\t\tTHROW_BOOST_ERROR( ec );\n\t\t}\n\t\tcatch (boost::system::error_code& e)\n\t\t{\n\t\t\tprint_error(e.message());\n\t\t\treturn e.value();\n\t\t}\n\t\t\n\t\ttcp::socket s(io_service);\n\t\ttry\n\t\t{\n\t\t\ttcp::endpoint ep = *iterator;\n\t\t\ts.connect(ep, ec);\n\t\t\tTHROW_BOOST_ERROR( ec );\n\t\t}\n\t\tcatch (boost::system::error_code& e)\n\t\t{\n\t\t\tprint_error(e.message());\n\t\t\treturn e.value();\n\t\t}\n\n\t\t\/\/ authenticate\n\t\tint seq(1);\n\t\tstd::string msg = parser.to_authenticate(seq);\n\t\tc4socket::write_msg(s, msg);\n\t\tstd::string reply = c4socket::read_msg(s);\n\t\tprint_ln(reply);\n\n\t\tdo\n\t\t{\n\t\t\tmsg = parser.to_c4soap(seq);\n\t\t\tif (parser.parsed())\n\t\t\t{\n\t\t\t\tc4socket::write_msg(s, msg);\n\t\t\t\treply = c4socket::read_msg(s);\n\t\t\t\tprint_ln(reply);\n\t\t\t}\n\t\t\telse\n\t\t\t\tprint_ln(\"Unknown or malformed command: \" + cmd);\n\t\t}\n\t\twhile (is_shell);\n\t}\n\telse\n\t\tprint_usage();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"libcellml\/annotator.h\"\n\n#include <algorithm>\n\n#include \"libcellml\/component.h\"\n#include \"libcellml\/importsource.h\"\n#include \"libcellml\/model.h\"\n#include \"libcellml\/namedentity.h\"\n#include \"libcellml\/printer.h\"\n#include \"libcellml\/reset.h\"\n#include \"libcellml\/types.h\"\n#include \"libcellml\/units.h\"\n#include \"libcellml\/variable.h\"\n\n#include \"internaltypes.h\"\n#include \"namespaces.h\"\n#include \"utilities.h\"\n\nnamespace libcellml {\n\nstruct Annotator::AnnotatorImpl\n{\n Annotator *mAnnotator = nullptr;\n ItemList mIdList;\n bool isBuilt = false;\n ModelPtr mModel = nullptr;\n};\n\nAnnotator::Annotator()\n : mPimpl(new AnnotatorImpl())\n{\n mPimpl->mAnnotator = this;\n mPimpl->mIdList = std::map<std::string, AnyItem>();\n mPimpl->isBuilt = false;\n}\n\nAnnotator::~Annotator()\n{\n delete mPimpl;\n}\n\nAnnotatorPtr Annotator::create() noexcept\n{\n return std::shared_ptr<Annotator> {new Annotator {}};\n}\n\nvoid listComponentIdsAndItems(const ComponentPtr &component, ItemList &idList)\n{\n std::string id = component->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::COMPONENT, component)));\n }\n \/\/ Imports.\n if (component->isImport() && component->importSource() != nullptr) {\n id = component->importSource()->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::IMPORT, component->importSource())));\n }\n }\n \/\/ Component reference in encapsulation structure.\n id = component->encapsulationId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::COMPONENT_REF, component)));\n }\n \/\/ Variables.\n for (size_t v = 0; v < component->variableCount(); ++v) {\n id = component->variable(v)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::VARIABLE, component->variable(v))));\n }\n\n for (size_t e = 0; e < component->variable(v)->equivalentVariableCount(); ++e) {\n \/\/ Equivalent variable mappings.\n id = Variable::equivalenceMappingId(component->variable(v), component->variable(v)->equivalentVariable(e));\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::MAP_VARIABLES, std::make_pair(component->variable(v), component->variable(v)->equivalentVariable(e)))));\n }\n \/\/ Connections.\n id = Variable::equivalenceConnectionId(component->variable(v), component->variable(v)->equivalentVariable(e));\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::CONNECTION, std::make_pair(component->variable(v), component->variable(v)->equivalentVariable(e)))));\n }\n }\n }\n \/\/ Resets.\n for (size_t r = 0; r < component->resetCount(); ++r) {\n id = component->reset(r)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET, component->reset(r))));\n }\n id = component->reset(r)->testValueId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::TEST_VALUE, component->reset(r))));\n \/\/ idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::TEST_VALUE, component->reset(r)->testValue())));\n }\n id = component->reset(r)->resetValueId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET_VALUE, component->reset(r))));\n \/\/ idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET_VALUE, component->reset(r)->resetValue())));\n }\n }\n\n for (size_t c = 0; c < component->componentCount(); ++c) {\n listComponentIdsAndItems(component->component(c), idList);\n }\n}\n\nItemList listIdsAndItems(const ModelPtr &model)\n{\n \/\/ Collect all existing ids in a list and return. NB can't use a map or a set as we need to be able to print\n \/\/ invalid models (with duplicated ids) too.\n\n ItemList idList;\n \/\/ Model.\n std::string id = model->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::MODEL, model)));\n }\n \/\/ Units.\n for (size_t u = 0; u < model->unitsCount(); ++u) {\n id = model->units(u)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::UNITS, model->units(u))));\n }\n for (size_t i = 0; i < model->units(u)->unitCount(); ++i) {\n std::string prefix;\n std::string reference;\n double exponent;\n double multiplier;\n model->units(u)->unitAttributes(i, reference, prefix, exponent, multiplier, id);\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::UNIT, std::make_pair(model->units(u), i))));\n }\n }\n if (model->units(u)->isImport() && model->units(u)->importSource() != nullptr) {\n id = model->units(u)->importSource()->id();\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::IMPORT, model->units(u)->importSource())));\n }\n }\n \/\/ Components.\n for (size_t c = 0; c < model->componentCount(); ++c) {\n listComponentIdsAndItems(model->component(c), idList);\n }\n \/\/ Encapsulation.\n id = model->encapsulationId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::ENCAPSULATION, std::string())));\n }\n\n return idList;\n}\n\nvoid Annotator::build(const ModelPtr &model)\n{\n mPimpl->isBuilt = false;\n removeAllIssues();\n mPimpl->mIdList.clear();\n mPimpl->mIdList = listIdsAndItems(model);\n mPimpl->isBuilt = true;\n mPimpl->mModel = model;\n}\n\nAnyItem Annotator::item(const std::string &id)\n{\n AnyItem item;\n if (!mPimpl->isBuilt) {\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Please call the Annotator::build function before attempting to access items by their id.\");\n issue->setLevel(libcellml::Issue::Level::ERROR);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n return item;\n }\n if (mPimpl->mIdList.empty()) {\n \/\/ Setting the error message to be the same as below.\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Could not find an item with id='\" + id + \"' in the model.\");\n issue->setLevel(libcellml::Issue::Level::WARNING);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n return item;\n }\n\n \/\/ Retrieve the item from the idList.\n ItemList::iterator it;\n it = mPimpl->mIdList.find(id);\n\n if (it == mPimpl->mIdList.end()) {\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Could not find an item with id='\" + id + \"' in the model.\");\n issue->setLevel(libcellml::Issue::Level::WARNING);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n \/\/ Adding the requested id string and this issue to the map, so that future requests (ie: to the .second)\n \/\/ will return the same IssuePtr rather than creating a new one.\n mPimpl->mIdList.insert(std::make_pair(id, item));\n return item;\n }\n return mPimpl->mIdList[id];\n}\n\nComponentPtr Annotator::component(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ComponentPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nVariablePtr Annotator::variable(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<VariablePtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nModelPtr Annotator::model(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ModelPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nUnitsPtr Annotator::units(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<UnitsPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nImportSourcePtr Annotator::importSource(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ImportSourcePtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::reset(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ResetPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nVariablePair Annotator::connection(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<VariablePair>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, nullptr);\n }\n}\n\nVariablePair Annotator::mapVariables(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<VariablePair>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, nullptr);\n }\n}\n\nUnitItem Annotator::unit(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<UnitItem>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, -1);\n }\n}\n\nComponentPtr Annotator::componentRef(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ComponentPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::testValue(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ResetPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::resetValue(const std::string &id)\n{\n auto i = item(id);\n try {\n auto j = std::any_cast<ResetPtr>(i.second);\n return j;\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\n} \/\/ namespace libcellml\n<commit_msg>Update annotator.cpp<commit_after>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"libcellml\/annotator.h\"\n\n#include <algorithm>\n\n#include \"libcellml\/component.h\"\n#include \"libcellml\/importsource.h\"\n#include \"libcellml\/model.h\"\n#include \"libcellml\/namedentity.h\"\n#include \"libcellml\/printer.h\"\n#include \"libcellml\/reset.h\"\n#include \"libcellml\/types.h\"\n#include \"libcellml\/units.h\"\n#include \"libcellml\/variable.h\"\n\n#include \"internaltypes.h\"\n#include \"namespaces.h\"\n#include \"utilities.h\"\n\nnamespace libcellml {\n\nstruct Annotator::AnnotatorImpl\n{\n Annotator *mAnnotator = nullptr;\n ItemList mIdList;\n bool isBuilt = false;\n ModelPtr mModel = nullptr;\n};\n\nAnnotator::Annotator()\n : mPimpl(new AnnotatorImpl())\n{\n mPimpl->mAnnotator = this;\n mPimpl->mIdList = std::map<std::string, AnyItem>();\n mPimpl->isBuilt = false;\n}\n\nAnnotator::~Annotator()\n{\n delete mPimpl;\n}\n\nAnnotatorPtr Annotator::create() noexcept\n{\n return std::shared_ptr<Annotator> {new Annotator {}};\n}\n\nvoid listComponentIdsAndItems(const ComponentPtr &component, ItemList &idList)\n{\n std::string id = component->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::COMPONENT, component)));\n }\n \/\/ Imports.\n if (component->isImport() && component->importSource() != nullptr) {\n id = component->importSource()->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::IMPORT, component->importSource())));\n }\n }\n \/\/ Component reference in encapsulation structure.\n id = component->encapsulationId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::COMPONENT_REF, component)));\n }\n \/\/ Variables.\n for (size_t v = 0; v < component->variableCount(); ++v) {\n id = component->variable(v)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::VARIABLE, component->variable(v))));\n }\n\n for (size_t e = 0; e < component->variable(v)->equivalentVariableCount(); ++e) {\n \/\/ Equivalent variable mappings.\n id = Variable::equivalenceMappingId(component->variable(v), component->variable(v)->equivalentVariable(e));\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::MAP_VARIABLES, std::make_pair(component->variable(v), component->variable(v)->equivalentVariable(e)))));\n }\n \/\/ Connections.\n id = Variable::equivalenceConnectionId(component->variable(v), component->variable(v)->equivalentVariable(e));\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::CONNECTION, std::make_pair(component->variable(v), component->variable(v)->equivalentVariable(e)))));\n }\n }\n }\n \/\/ Resets.\n for (size_t r = 0; r < component->resetCount(); ++r) {\n id = component->reset(r)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET, component->reset(r))));\n }\n id = component->reset(r)->testValueId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::TEST_VALUE, component->reset(r))));\n \/\/ idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::TEST_VALUE, component->reset(r)->testValue())));\n }\n id = component->reset(r)->resetValueId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET_VALUE, component->reset(r))));\n \/\/ idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::RESET_VALUE, component->reset(r)->resetValue())));\n }\n }\n\n for (size_t c = 0; c < component->componentCount(); ++c) {\n listComponentIdsAndItems(component->component(c), idList);\n }\n}\n\nItemList listIdsAndItems(const ModelPtr &model)\n{\n \/\/ Collect all existing ids in a list and return. NB can't use a map or a set as we need to be able to print\n \/\/ invalid models (with duplicated ids) too.\n\n ItemList idList;\n \/\/ Model.\n std::string id = model->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::MODEL, model)));\n }\n \/\/ Units.\n for (size_t u = 0; u < model->unitsCount(); ++u) {\n id = model->units(u)->id();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::UNITS, model->units(u))));\n }\n for (size_t i = 0; i < model->units(u)->unitCount(); ++i) {\n std::string prefix;\n std::string reference;\n double exponent;\n double multiplier;\n model->units(u)->unitAttributes(i, reference, prefix, exponent, multiplier, id);\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::UNIT, std::make_pair(model->units(u), i))));\n }\n }\n if (model->units(u)->isImport() && model->units(u)->importSource() != nullptr) {\n id = model->units(u)->importSource()->id();\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::IMPORT, model->units(u)->importSource())));\n }\n }\n \/\/ Components.\n for (size_t c = 0; c < model->componentCount(); ++c) {\n listComponentIdsAndItems(model->component(c), idList);\n }\n \/\/ Encapsulation.\n id = model->encapsulationId();\n if (!id.empty()) {\n idList.insert(std::make_pair(id, std::make_pair(Annotator::Type::ENCAPSULATION, std::string())));\n }\n\n return idList;\n}\n\nvoid Annotator::build(const ModelPtr &model)\n{\n mPimpl->isBuilt = false;\n removeAllIssues();\n mPimpl->mIdList.clear();\n mPimpl->mIdList = listIdsAndItems(model);\n mPimpl->isBuilt = true;\n mPimpl->mModel = model;\n}\n\nAnyItem Annotator::item(const std::string &id)\n{\n AnyItem item;\n if (!mPimpl->isBuilt) {\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Please call the Annotator::build function before attempting to access items by their id.\");\n issue->setLevel(libcellml::Issue::Level::ERROR);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n return item;\n }\n if (mPimpl->mIdList.empty()) {\n \/\/ Setting the error message to be the same as below.\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Could not find an item with id='\" + id + \"' in the model.\");\n issue->setLevel(libcellml::Issue::Level::WARNING);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n return item;\n }\n\n \/\/ Retrieve the item from the idList.\n ItemList::iterator it;\n it = mPimpl->mIdList.find(id);\n\n if (it == mPimpl->mIdList.end()) {\n auto issue = libcellml::Issue::create();\n issue->setDescription(\"Could not find an item with id='\" + id + \"' in the model.\");\n issue->setLevel(libcellml::Issue::Level::WARNING);\n addIssue(issue);\n item = std::make_pair(Annotator::Type::ISSUE, issue);\n \/\/ Adding the requested id string and this issue to the map, so that future requests (ie: to the .second)\n \/\/ will return the same IssuePtr rather than creating a new one.\n mPimpl->mIdList.insert(std::make_pair(id, item));\n return item;\n }\n return mPimpl->mIdList[id];\n}\n\nComponentPtr Annotator::component(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ComponentPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nVariablePtr Annotator::variable(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<VariablePtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nModelPtr Annotator::model(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ModelPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nUnitsPtr Annotator::units(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<UnitsPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nImportSourcePtr Annotator::importSource(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ImportSourcePtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::reset(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ResetPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nVariablePair Annotator::connection(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<VariablePair>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, nullptr);\n }\n}\n\nVariablePair Annotator::mapVariables(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<VariablePair>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, nullptr);\n }\n}\n\nUnitItem Annotator::unit(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<UnitItem>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return std::make_pair(nullptr, -1);\n }\n}\n\nComponentPtr Annotator::componentRef(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ComponentPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::testValue(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ResetPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\nResetPtr Annotator::resetValue(const std::string &id)\n{\n auto i = item(id);\n try {\n return std::any_cast<ResetPtr>(i.second);\n } catch (std::bad_any_cast &e) {\n (void)e;\n return nullptr;\n }\n}\n\n} \/\/ namespace libcellml\n<|endoftext|>"} {"text":"<commit_before><?hh \/\/strict\n\n\/**\n * This file is part of package.\n *\n * (c) Noritaka Horio <holy.shared.design@gmail.com>\n *\n * This source file is subject to the MIT license that is bundled\n * with this source code in the file LICENSE.\n *\/\n\nnamespace package;\n\nuse \\Exception;\n\nclass NotPackageFileException extends Exception\n{\n\n public function __construct(\n protected string $message = '',\n protected int $code = 0,\n protected ?Exception $previous = null\n )\n {\n parent::__construct($message, $code, $previous);\n }\n\n}\n<commit_msg>Remove NotPackageFileException<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"xchainer\/python\/device.h\"\n\n#include <cstdint>\n#include <memory>\n#include <sstream>\n#include <string>\n\n#include \"xchainer\/backend.h\"\n#include \"xchainer\/context.h\"\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/python\/dtype.h\"\n#include \"xchainer\/python\/shape.h\"\n#include \"xchainer\/python\/strides.h\"\n\n#include \"xchainer\/python\/common.h\"\n\nnamespace xchainer {\nnamespace python {\nnamespace internal {\n\nnamespace py = pybind11; \/\/ standard convention\n\nDevice& GetDevice(py::handle handle) {\n if (handle.is_none()) {\n return GetDefaultDevice();\n }\n\n if (py::isinstance<Device&>(handle)) {\n return py::cast<Device&>(handle);\n }\n\n if (py::isinstance<py::str>(handle)) {\n \/\/ Device ID\n std::string device_id = py::cast<std::string>(handle);\n return GetDefaultContext().GetDevice(device_id);\n }\n\n throw py::type_error{\"Device not understood: \" + py::cast<std::string>(py::repr(handle))};\n}\n\nclass PyDeviceScope {\npublic:\n explicit PyDeviceScope(Device& target) : target_(target) {}\n void Enter() { scope_ = std::make_unique<DeviceScope>(target_); }\n void Exit(py::args args) {\n (void)args; \/\/ unused\n scope_.reset();\n }\n\nprivate:\n \/\/ TODO(beam2d): better to replace it by \"optional\"...\n std::unique_ptr<DeviceScope> scope_;\n Device& target_;\n};\n\n\/\/ A device buffer that upon construction allocates device memory and creates a py::buffer_info, sharing ownership of the managed data\n\/\/ (py::buffer_info only holds a raw pointer and does not manage the lifetime of the pointed data). Memoryviews created from this buffer\n\/\/ will also share ownership. Note that accessing the .obj attribute of a memoryview may increase the reference count and should thus be\n\/\/ avoided.\nclass PyDeviceBuffer {\npublic:\n PyDeviceBuffer(const std::shared_ptr<void>& data, const std::shared_ptr<py::buffer_info>& info) : data_{data}, info_{info} {}\n\n PyDeviceBuffer(\n const std::shared_ptr<void>& data,\n int64_t item_size,\n std::string format,\n int8_t ndim,\n const Shape& shape,\n const Strides& strides)\n : PyDeviceBuffer{data, std::make_shared<py::buffer_info>(data.get(), item_size, std::move(format), ndim, shape, strides)} {}\n\n std::shared_ptr<py::buffer_info> info() const { return info_; }\n\nprivate:\n std::shared_ptr<void> data_;\n std::shared_ptr<py::buffer_info> info_;\n};\n\nvoid InitXchainerDevice(pybind11::module& m) {\n py::class_<Device> c{m, \"Device\"};\n c.def(\"__repr__\", &Device::name);\n c.def(\"synchronize\", &Device::Synchronize);\n c.def_property_readonly(\"name\", &Device::name);\n c.def_property_readonly(\"backend\", &Device::backend, py::return_value_policy::reference);\n c.def_property_readonly(\"context\", &Device::context, py::return_value_policy::reference);\n c.def_property_readonly(\"index\", &Device::index);\n\n m.def(\"get_default_device\", []() -> Device& { return GetDefaultDevice(); }, py::return_value_policy::reference);\n m.def(\"set_default_device\", [](Device& device) { SetDefaultDevice(&device); });\n m.def(\"set_default_device\", [](const std::string& device_name) { SetDefaultDevice(&GetDefaultContext().GetDevice(device_name)); });\n}\n\nvoid InitXchainerDeviceScope(pybind11::module& m) {\n py::class_<PyDeviceScope> c{m, \"DeviceScope\"};\n c.def(\"__enter__\", &PyDeviceScope::Enter);\n c.def(\"__exit__\", &PyDeviceScope::Exit);\n\n m.def(\"device_scope\", [](Device& device) { return PyDeviceScope(device); });\n m.def(\"device_scope\", [](const std::string& device_name) { return PyDeviceScope(GetDefaultContext().GetDevice(device_name)); });\n m.def(\"device_scope\", [](const std::string& backend_name, int index) {\n return PyDeviceScope(GetDefaultContext().GetDevice({backend_name, index}));\n });\n}\n\nvoid InitXchainerDeviceBuffer(pybind11::module& m) {\n py::class_<PyDeviceBuffer> c{m, \"DeviceBuffer\", py::buffer_protocol()};\n c.def(py::init([](const py::list& list, const py::tuple& shape_tup, const py::handle& dtype_handle, const py::handle& device) {\n Shape shape = ToShape(shape_tup);\n int64_t total_size = shape.GetTotalSize();\n if (static_cast<size_t>(total_size) != list.size()) {\n throw DimensionError{\"Invalid data length\"};\n }\n\n \/\/ Copy the Python list to a buffer on the host.\n Dtype dtype = GetDtype(dtype_handle);\n int64_t item_size = GetItemSize(dtype);\n int64_t bytes = item_size * total_size;\n std::shared_ptr<void> host_data = std::make_unique<uint8_t[]>(bytes);\n std::string format = VisitDtype(dtype, [&host_data, &list](auto pt) {\n using T = typename decltype(pt)::type;\n std::transform(list.begin(), list.end(), static_cast<T*>(host_data.get()), [](auto& item) { return py::cast<T>(item); });\n return py::format_descriptor<T>::format(); \/\/ Return the dtype format, e.g. \"f\" for xchainer.float32.\n });\n\n \/\/ Copy the data on the host buffer to the target device.\n std::shared_ptr<void> device_data = internal::GetDevice(device).FromHostMemory(host_data, bytes);\n return PyDeviceBuffer{device_data, item_size, format, shape.ndim(), shape, Strides{shape, dtype}};\n }),\n py::arg(\"shape\"),\n py::arg(\"dtype\"),\n py::arg(\"data\"),\n py::arg(\"device\") = nullptr);\n c.def_buffer([](const PyDeviceBuffer& self) {\n \/\/ py::buffer_info cannot be copied.\n std::shared_ptr<py::buffer_info> info = self.info();\n return py::buffer_info{info->ptr, info->itemsize, info->format, info->ndim, info->shape, info->strides};\n });\n}\n\n} \/\/ namespace internal\n} \/\/ namespace python\n} \/\/ namespace xchainer\n<commit_msg>Add missing include<commit_after>#include \"xchainer\/python\/device.h\"\n\n#include <algorithm>\n#include <cstdint>\n#include <memory>\n#include <sstream>\n#include <string>\n\n#include \"xchainer\/backend.h\"\n#include \"xchainer\/context.h\"\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/python\/dtype.h\"\n#include \"xchainer\/python\/shape.h\"\n#include \"xchainer\/python\/strides.h\"\n\n#include \"xchainer\/python\/common.h\"\n\nnamespace xchainer {\nnamespace python {\nnamespace internal {\n\nnamespace py = pybind11; \/\/ standard convention\n\nDevice& GetDevice(py::handle handle) {\n if (handle.is_none()) {\n return GetDefaultDevice();\n }\n\n if (py::isinstance<Device&>(handle)) {\n return py::cast<Device&>(handle);\n }\n\n if (py::isinstance<py::str>(handle)) {\n \/\/ Device ID\n std::string device_id = py::cast<std::string>(handle);\n return GetDefaultContext().GetDevice(device_id);\n }\n\n throw py::type_error{\"Device not understood: \" + py::cast<std::string>(py::repr(handle))};\n}\n\nclass PyDeviceScope {\npublic:\n explicit PyDeviceScope(Device& target) : target_(target) {}\n void Enter() { scope_ = std::make_unique<DeviceScope>(target_); }\n void Exit(py::args args) {\n (void)args; \/\/ unused\n scope_.reset();\n }\n\nprivate:\n \/\/ TODO(beam2d): better to replace it by \"optional\"...\n std::unique_ptr<DeviceScope> scope_;\n Device& target_;\n};\n\n\/\/ A device buffer that upon construction allocates device memory and creates a py::buffer_info, sharing ownership of the managed data\n\/\/ (py::buffer_info only holds a raw pointer and does not manage the lifetime of the pointed data). Memoryviews created from this buffer\n\/\/ will also share ownership. Note that accessing the .obj attribute of a memoryview may increase the reference count and should thus be\n\/\/ avoided.\nclass PyDeviceBuffer {\npublic:\n PyDeviceBuffer(const std::shared_ptr<void>& data, const std::shared_ptr<py::buffer_info>& info) : data_{data}, info_{info} {}\n\n PyDeviceBuffer(\n const std::shared_ptr<void>& data,\n int64_t item_size,\n std::string format,\n int8_t ndim,\n const Shape& shape,\n const Strides& strides)\n : PyDeviceBuffer{data, std::make_shared<py::buffer_info>(data.get(), item_size, std::move(format), ndim, shape, strides)} {}\n\n std::shared_ptr<py::buffer_info> info() const { return info_; }\n\nprivate:\n std::shared_ptr<void> data_;\n std::shared_ptr<py::buffer_info> info_;\n};\n\nvoid InitXchainerDevice(pybind11::module& m) {\n py::class_<Device> c{m, \"Device\"};\n c.def(\"__repr__\", &Device::name);\n c.def(\"synchronize\", &Device::Synchronize);\n c.def_property_readonly(\"name\", &Device::name);\n c.def_property_readonly(\"backend\", &Device::backend, py::return_value_policy::reference);\n c.def_property_readonly(\"context\", &Device::context, py::return_value_policy::reference);\n c.def_property_readonly(\"index\", &Device::index);\n\n m.def(\"get_default_device\", []() -> Device& { return GetDefaultDevice(); }, py::return_value_policy::reference);\n m.def(\"set_default_device\", [](Device& device) { SetDefaultDevice(&device); });\n m.def(\"set_default_device\", [](const std::string& device_name) { SetDefaultDevice(&GetDefaultContext().GetDevice(device_name)); });\n}\n\nvoid InitXchainerDeviceScope(pybind11::module& m) {\n py::class_<PyDeviceScope> c{m, \"DeviceScope\"};\n c.def(\"__enter__\", &PyDeviceScope::Enter);\n c.def(\"__exit__\", &PyDeviceScope::Exit);\n\n m.def(\"device_scope\", [](Device& device) { return PyDeviceScope(device); });\n m.def(\"device_scope\", [](const std::string& device_name) { return PyDeviceScope(GetDefaultContext().GetDevice(device_name)); });\n m.def(\"device_scope\", [](const std::string& backend_name, int index) {\n return PyDeviceScope(GetDefaultContext().GetDevice({backend_name, index}));\n });\n}\n\nvoid InitXchainerDeviceBuffer(pybind11::module& m) {\n py::class_<PyDeviceBuffer> c{m, \"DeviceBuffer\", py::buffer_protocol()};\n c.def(py::init([](const py::list& list, const py::tuple& shape_tup, const py::handle& dtype_handle, const py::handle& device) {\n Shape shape = ToShape(shape_tup);\n int64_t total_size = shape.GetTotalSize();\n if (static_cast<size_t>(total_size) != list.size()) {\n throw DimensionError{\"Invalid data length\"};\n }\n\n \/\/ Copy the Python list to a buffer on the host.\n Dtype dtype = GetDtype(dtype_handle);\n int64_t item_size = GetItemSize(dtype);\n int64_t bytes = item_size * total_size;\n std::shared_ptr<void> host_data = std::make_unique<uint8_t[]>(bytes);\n std::string format = VisitDtype(dtype, [&host_data, &list](auto pt) {\n using T = typename decltype(pt)::type;\n std::transform(list.begin(), list.end(), static_cast<T*>(host_data.get()), [](auto& item) { return py::cast<T>(item); });\n return py::format_descriptor<T>::format(); \/\/ Return the dtype format, e.g. \"f\" for xchainer.float32.\n });\n\n \/\/ Copy the data on the host buffer to the target device.\n std::shared_ptr<void> device_data = internal::GetDevice(device).FromHostMemory(host_data, bytes);\n return PyDeviceBuffer{device_data, item_size, format, shape.ndim(), shape, Strides{shape, dtype}};\n }),\n py::arg(\"shape\"),\n py::arg(\"dtype\"),\n py::arg(\"data\"),\n py::arg(\"device\") = nullptr);\n c.def_buffer([](const PyDeviceBuffer& self) {\n \/\/ py::buffer_info cannot be copied.\n std::shared_ptr<py::buffer_info> info = self.info();\n return py::buffer_info{info->ptr, info->itemsize, info->format, info->ndim, info->shape, info->strides};\n });\n}\n\n} \/\/ namespace internal\n} \/\/ namespace python\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"<commit_before>\n#include \"gdb\/gdbmi.h\"\n\n#include <QtTest>\n\n\nclass tst_Version : public QObject\n{\n Q_OBJECT\n\npublic:\n tst_Version() {}\n\nprivate slots:\n void version();\n void version_data();\n};\n\nvoid tst_Version::version()\n{\n QFETCH(QString, msg);\n QFETCH(int, gdbVersion);\n QFETCH(int, gdbBuildVersion);\n QFETCH(bool, isMacGdb);\n int v = 0, bv = 0;\n bool mac = true;\n Debugger::Internal::extractGdbVersion(msg, &v, &bv, &mac);\n qDebug() << msg << \" -> \" << v << bv << mac;\n QCOMPARE(v, gdbVersion);\n QCOMPARE(bv, gdbBuildVersion);\n QCOMPARE(mac, isMacGdb);\n}\n\nvoid tst_Version::version_data()\n{\n QTest::addColumn<QString>(\"msg\");\n QTest::addColumn<int>(\"gdbVersion\");\n QTest::addColumn<int>(\"gdbBuildVersion\");\n QTest::addColumn<bool>(\"isMacGdb\");\n\n QTest::newRow(\"Debian\")\n << \"GNU gdb (GDB) 7.0.1-debian\"\n << 70001 << 0 << false;\n\n QTest::newRow(\"CVS 7.0.90\")\n << \"GNU gdb (GDB) 7.0.90.20100226-cvs\"\n << 70090 << 20100226 << false;\n\n QTest::newRow(\"Ubuntu Lucid\")\n << \"GNU gdb (GDB) 7.1-ubuntu\"\n << 70100 << 0 << false;\n\n QTest::newRow(\"Fedora 13\")\n << \"GNU gdb (GDB) Fedora (7.1-22.fc13)\"\n << 70100 << 22 << false;\n\n QTest::newRow(\"Gentoo\")\n << \"GNU gdb (Gentoo 7.1 p1) 7.1\"\n << 70100 << 1 << false;\n\n QTest::newRow(\"Fedora EL5\")\n << \"GNU gdb Fedora (6.8-37.el5)\"\n << 60800 << 37 << false;\n\n QTest::newRow(\"SUSE\")\n << \"GNU gdb (GDB) SUSE (6.8.91.20090930-2.4)\"\n << 60891 << 20090930 << false;\n\n QTest::newRow(\"Apple\")\n << \"GNU gdb 6.3.50-20050815 (Apple version gdb-1461.2)\"\n << 60350 << 1461 << true;\n}\n\n\nint main(int argc, char *argv[])\n{\n tst_Version test;\n return QTest::qExec(&test, argc, argv);\n}\n\n#include \"tst_version.moc\"\n\n<commit_msg>debugger: add another version string to the auto test<commit_after>\n#include \"gdb\/gdbmi.h\"\n\n#include <QtTest>\n\n\nclass tst_Version : public QObject\n{\n Q_OBJECT\n\npublic:\n tst_Version() {}\n\nprivate slots:\n void version();\n void version_data();\n};\n\nvoid tst_Version::version()\n{\n QFETCH(QString, msg);\n QFETCH(int, gdbVersion);\n QFETCH(int, gdbBuildVersion);\n QFETCH(bool, isMacGdb);\n int v = 0, bv = 0;\n bool mac = true;\n Debugger::Internal::extractGdbVersion(msg, &v, &bv, &mac);\n qDebug() << msg << \" -> \" << v << bv << mac;\n QCOMPARE(v, gdbVersion);\n QCOMPARE(bv, gdbBuildVersion);\n QCOMPARE(mac, isMacGdb);\n}\n\nvoid tst_Version::version_data()\n{\n QTest::addColumn<QString>(\"msg\");\n QTest::addColumn<int>(\"gdbVersion\");\n QTest::addColumn<int>(\"gdbBuildVersion\");\n QTest::addColumn<bool>(\"isMacGdb\");\n\n QTest::newRow(\"Debian\")\n << \"GNU gdb (GDB) 7.0.1-debian\"\n << 70001 << 0 << false;\n\n QTest::newRow(\"CVS 7.0.90\")\n << \"GNU gdb (GDB) 7.0.90.20100226-cvs\"\n << 70090 << 20100226 << false;\n\n QTest::newRow(\"Ubuntu Lucid\")\n << \"GNU gdb (GDB) 7.1-ubuntu\"\n << 70100 << 0 << false;\n\n QTest::newRow(\"Fedora 13\")\n << \"GNU gdb (GDB) Fedora (7.1-22.fc13)\"\n << 70100 << 22 << false;\n\n QTest::newRow(\"Gentoo\")\n << \"GNU gdb (Gentoo 7.1 p1) 7.1\"\n << 70100 << 1 << false;\n\n QTest::newRow(\"Fedora EL5\")\n << \"GNU gdb Fedora (6.8-37.el5)\"\n << 60800 << 37 << false;\n\n QTest::newRow(\"SUSE\")\n << \"GNU gdb (GDB) SUSE (6.8.91.20090930-2.4)\"\n << 60891 << 20090930 << false;\n\n QTest::newRow(\"Apple\")\n << \"GNU gdb 6.3.50-20050815 (Apple version gdb-1461.2)\"\n << 60350 << 1461 << true;\n\n QTest::newRow(\"Apple\")\n << \"GNU gdb 6.3.50-20050815 (Apple version gdb-960)\"\n << 60350 << 960 << true;\n}\n\n\nint main(int argc, char *argv[])\n{\n tst_Version test;\n return QTest::qExec(&test, argc, argv);\n}\n\n#include \"tst_version.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ implementation for p_basis.h\n\n#include <cassert>\n#include <cmath>\n#include <numerics\/schoenberg_splines.h>\n#include <algebra\/triangular_matrix.h>\n#include <utils\/tiny_tools.h>\n#include <interval\/boundary_gramian.h>\n\nnamespace WaveletTL\n{\n template <int d, int dT>\n PBasis<d,dT>::PBasis(const int s0, const int s1) {\n assert(d >= 2 && d <= 3);\n assert(s0 >= d-2 && s1 >= d-2);\n\n this->s0 = s0;\n this->s1 = s1;\n\n setup();\n }\n\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup() {\n \/\/ For simplicity, we do not implement a fully generic setup here\n \/\/ but only setup the parameters for several important special cases from [P].\n \/\/ Namely, we restrict the setting to the case s0 >= d-2, where no \"additional\"\n \/\/ interior dual generators have to be constructed. In a later version of\n \/\/ this class, we will fix this.\n\n j0_ = (int) ceil(log(std::max(ellT_l(),ellT_r())+ell2T<d,dT>()-1.)\/M_LN2+1);\n\n \/\/ setup the refinement matrix block for all \"real\" primal boundary B-splines,\n \/\/ obeying the block structure (3.15)\n \/\/ (ignoring the current values of s0 (and s1))\n MathTL::SchoenbergKnotSequence<d> sknots;\n Matrix<double> ML_0;\n MathTL::compute_Bspline_refinement_matrix<d>(&sknots, ML_0);\n \n \/\/ The total number of (left) boundary generators is always exactly dT\n \/\/ (to be able reproduce all polynomials by the dual generators).\n ML_.resize(3*dT+s0-1, dT);\n for (int column = s0; column < d-1; column++)\n for (int row = s0; row < 2*(d-1); row++)\n\tML_.set_entry(row-s0, column-s0, ML_0.get_entry(row,column));\n for (int k = d; k <= dT+s0; k++)\n for (int n = 2*k-d; n <= 2*k; n++)\n \tML_.set_entry(n-1-s0,k-1-s0,cdf.a().get_coefficient(MultiIndex<int,1>(-(d\/2)+n+d-2*k)));\n cout << \"ML=\" << endl << ML_;\n\n MR_.resize(3*dT+s1-1, dT);\n for (int column = s1; column < d-1; column++)\n for (int row = s1; row < 2*(d-1); row++)\n\tMR_.set_entry(row-s1, column-s1, ML_0.get_entry(row,column));\n for (int k = d; k <= dT+s1; k++)\n for (int n = 2*k-d; n <= 2*k; n++)\n \tMR_.set_entry(n-1-s1,k-1-s1,cdf.a().get_coefficient(MultiIndex<int,1>(-(d\/2)+n+d-2*k)));\n cout << \"MR=\" << endl << MR_;\n\n setup_Mj0(ML_, MR_, Mj0); \/\/ [DKU, (3.5.1)]\n\n \/\/ setup the expansion coefficients of the unbiorthogonalized dual generators\n \/\/ w.r.t. the truncated CDF generators, see [DKU, Lemma 3.1]\n Matrix<double> MLTp(3*dT+s0-1, dT);\n for (unsigned int r = 0; r < dT; r++) {\n MLTp.set_entry(r, r, ldexp(1.0, -r));\n for (int m = ellT_l(); m <= 2*ellT_l()+ell1T<d,dT>()-1; m++)\n\tMLTp.set_entry(dT+m-ellT_l(), r, alpha(m, r));\n for (int m = 2*ellT_l()+ell1T<d,dT>(); m <= 2*ellT_l()+ell2T<d,dT>()-2; m++)\n\tMLTp.set_entry(dT+m-ellT_l(), r, betaL(m, r));\n }\n cout << \"MLTp=\" << endl << MLTp;\n \n Matrix<double> MRTp(3*dT+s1-1, dT);\n for (unsigned int r = 0; r < dT; r++) {\n MRTp.set_entry(r, r, ldexp(1.0, -r));\n for (int m = ellT_r(); m <= 2*ellT_r()+ell1T<d,dT>()-1; m++)\n\tMRTp.set_entry(dT+m-ellT_r(), r, alpha(m, r));\n for (int m = 2*ellT_r()+ell1T<d,dT>(); m <= 2*ellT_r()+ell2T<d,dT>()-2; m++)\n\tMRTp.set_entry(dT+m-ellT_r(), r, betaR(m, r));\n }\n cout << \"MRTp=\" << endl << MRTp;\n\n SparseMatrix<double> mj0tp; setup_Mj0Tp(MLTp, MRTp, mj0tp); \/\/ [DKU, (3.5.5)]\n\n \/\/ for the biorthogonalization of the generators,\n \/\/ compute the gramian matrix of the primal and dual boundary generators\n compute_biorthogonal_boundary_gramian\n <CDFMask_primal<d>,CDFMask_dual<d,dT> >(ML_, MLTp, GammaL);\n cout << \"GammaL=\" << endl << GammaL;\n\n compute_biorthogonal_boundary_gramian\n <CDFMask_primal<d>,CDFMask_dual<d,dT> >(MR_, MRTp, GammaR);\n cout << \"GammaR=\" << endl << GammaR;\n\n \/\/ biorthogonalize the generators\n setup_Cj();\n Mj0T = transpose(inv_CjpT) * mj0tp * transpose(CjT); \/\/ [DKU, (2.4.3)]\n\n#if 1\n cout << \"PBasis(): check biorthogonality of Mj0, Mj0T:\" << endl;\n\/\/ cout << \"Mj0=\" << endl << Mj0 << endl << \"Mj0T=\" << endl << Mj0T << endl;\n\n SparseMatrix<double> testbio0 = transpose(Mj0) * Mj0T;\n\/\/ cout << \"Mj0^T*Mj0T=\" << endl << testbio0 << endl;\n for (unsigned int i = 0; i < testbio0.row_dimension(); i++)\n testbio0.set_entry(i, i, testbio0.get_entry(i, i) - 2.0);\n cout << \"* ||Mj0^T*Mj0T-2*I||_infty: \" << row_sum_norm(testbio0) << endl;\n\n testbio0 = transpose(Mj0T) * Mj0;\n \/\/ cout << \"Mj0T*Mj0^T=\" << endl << testbio0 << endl;\n for (unsigned int i = 0; i < testbio0.row_dimension(); i++)\n testbio0.set_entry(i, i, testbio0.get_entry(i, i) - 2.0);\n cout << \"* ||Mj0T^T*Mj0-2*I||_infty: \" << row_sum_norm(testbio0) << endl;\n#endif \n\n\n }\n\n template <int d, int dT>\n const double\n PBasis<d,dT>::alpha(const int m, const unsigned int r) const {\n double result = 0;\n if (r == 0)\n return 1; \/\/ [DKU] (5.1.1)\n else {\n if (m == 0) {\n\t\/\/ [DKU] (5.1.3)\n\tfor (int k = ell1<d>(); k <= ell2<d>(); k++) {\n\t double help = 0;\n\t for (unsigned int s = 0; s < r; s++)\n\t help += binomial(r, s) * intpower(k, r-s) * alpha(0, s);\n\t result += cdf.a().get_coefficient(MultiIndex<int,1>(k)) * help;\n\t}\n\tresult \/= ldexp(1.0, r+1) - 2.0;\n } else {\n\t\/\/ [DKU] (5.1.2)\n\tfor (unsigned int i = 0; i <= r; i++)\n\t result += binomial(r, i) * intpower(m, i) * alpha(0, r-i);\n }\n }\n return result;\n }\n \n template <int d, int dT>\n const double\n PBasis<d,dT>::betaL(const int m, const unsigned int r) const {\n \/\/ [DKU] (3.2.31)\n double result = 0;\n for (int q = (int)ceil((m-ell2T<d,dT>())\/2.0); q < ellT_l(); q++)\n result += alpha(q, r) * cdf.aT().get_coefficient(MultiIndex<int,1>(m-2*q));\n return result;\n }\n\n template <int d, int dT>\n const double\n PBasis<d,dT>::betaR(const int m, const unsigned int r) const {\n \/\/ [DKU] (3.2.31)\n double result = 0;\n for (int q = (int)ceil((m-ell2T<d,dT>())\/2.0); q < ellT_r(); q++)\n result += alpha(q, r) * cdf.aT().get_coefficient(MultiIndex<int,1>(m-2*q));\n return result;\n }\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup_Mj0(const Matrix<double>& ML, const Matrix<double>& MR, SparseMatrix<double>& Mj0) {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::Mj0()\n \/\/ cf. [DKU section 3.5]\n\n const int nj = Deltasize(j0());\n const int njp = Deltasize(j0()+1);\n Mj0.resize(njp, nj);\n\n for (unsigned int i = 0; i < ML.row_dimension(); i++)\n for (unsigned int k = 0; k < ML.column_dimension(); k++)\n\tMj0.set_entry(i, k, ML.get_entry(i, k));\n \n for (unsigned int i = 0; i < MR.row_dimension(); i++)\n for (unsigned int k = 0; k < MR.column_dimension(); k++)\n\tMj0.set_entry(njp-i-1, nj-k-1, MR.get_entry(i, k));\n \n int startrow = d+ell_l()+ell1<d>()-2*s0;\n for (int col = d-s0; col < nj-(d-s1); col++, startrow+=2) {\n int row = startrow;\n for (MultivariateLaurentPolynomial<double, 1>::const_iterator it(cdf.a().begin());\n\t it != cdf.a().end(); ++it, row++)\n\tMj0.set_entry(row, col, *it);\n }\n \n\/\/ cout << \"Mj0=\" << endl << Mj0 << endl;\n }\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup_Mj0Tp(const Matrix<double>& MLTp, const Matrix<double>& MRTp, SparseMatrix<double>& Mj0Tp) {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::Mj0ts()\n \n const int nj = Deltasize(j0());\n const int njp = Deltasize(j0()+1);\n Mj0Tp.resize(njp, nj);\n \n for (unsigned int i = 0; i < MLTp.row_dimension(); i++)\n for (unsigned int k = 0; k < MLTp.column_dimension(); k++)\n\tMj0Tp.set_entry(i, k, MLTp.get_entry(i, k));\n \n for (unsigned int i = 0; i < MRTp.row_dimension(); i++)\n for (unsigned int k = 0; k < MRTp.column_dimension(); k++)\n\tMj0Tp.set_entry(njp-i-1, nj-k-1, MRTp.get_entry(i, k));\n \n int startrow = dT+ellT_l()+ell1T<d,dT>();\n for (int col = dT; col < nj-dT; col++, startrow+=2) {\n int row = startrow;\n for (MultivariateLaurentPolynomial<double, 1>::const_iterator it(cdf.aT().begin());\n\t it != cdf.aT().end(); ++it, row++)\n\tMj0Tp.set_entry(row, col, *it);\n }\n \n\/\/ cout << \"Mj0Tp=\" << endl << Mj0Tp << endl;\n }\n\n template <int d, int dT>\n void PBasis<d,dT>::setup_Cj() {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::setup_Cj(), ::put_Mat()\n\n \/\/ [DKU (5.2.5)]\n\n Matrix<double> CLGammaLInv;\n QUDecomposition<double>(GammaL).inverse(CLGammaLInv);\n Matrix<double> CLT = transpose(CLGammaLInv);\n \n Matrix<double> CRGammaRInv;\n QUDecomposition<double>(GammaR).inverse(CRGammaRInv);\n Matrix<double> CRT = transpose(CRGammaRInv);\n \n CjT.diagonal(Deltasize(j0()), 1.0);\n CjT.set_block(0, 0, CLT);\n CjT.set_block(Deltasize(j0())-CRT.row_dimension(),\n \t\t Deltasize(j0())-CRT.column_dimension(),\n \t\t CRT, true);\n\n Matrix<double> inv_CLT, inv_CRT;\n QUDecomposition<double>(CLT).inverse(inv_CLT);\n QUDecomposition<double>(CRT).inverse(inv_CRT);\n\n inv_CjT.diagonal(Deltasize(j0()), 1.0);\n inv_CjT.set_block(0, 0, inv_CLT);\n inv_CjT.set_block(Deltasize(j0())-inv_CRT.row_dimension(),\n \t\t Deltasize(j0())-inv_CRT.column_dimension(),\n \t\t inv_CRT, true);\n\n CjpT.diagonal(Deltasize(j0()+1), 1.0);\n CjpT.set_block(0, 0, CLT);\n CjpT.set_block(Deltasize(j0()+1)-CRT.row_dimension(),\n \t\t Deltasize(j0()+1)-CRT.column_dimension(),\n \t\t CRT, true);\n\n inv_CjpT.diagonal(Deltasize(j0()+1), 1.0);\n inv_CjpT.set_block(0, 0, inv_CLT);\n inv_CjpT.set_block(Deltasize(j0()+1)-inv_CRT.row_dimension(),\n \t\t Deltasize(j0()+1)-inv_CRT.column_dimension(),\n \t\t inv_CRT, true);\n\n#if 0\n cout << \"PBasis: testing setup of Cj:\" << endl;\n\n SparseMatrix<double> test1 = CjT * inv_CjT;\n for (unsigned int i = 0; i < test1.row_dimension(); i++)\n test1.set_entry(i, i, test1.get_entry(i, i) - 1.0);\n cout << \"* ||CjT*inv_CjT-I||_infty: \" << row_sum_norm(test1) << endl;\n\n SparseMatrix<double> test3 = CjpT * inv_CjpT;\n for (unsigned int i = 0; i < test3.row_dimension(); i++)\n test3.set_entry(i, i, test3.get_entry(i, i) - 1.0);\n cout << \"* ||CjpT*inv_CjpT-I||_infty: \" << row_sum_norm(test3) << endl;\n\n#endif\n }\n\n}\n<commit_msg>changed formula for j0<commit_after>\/\/ implementation for p_basis.h\n\n#include <cassert>\n#include <cmath>\n#include <numerics\/schoenberg_splines.h>\n#include <algebra\/triangular_matrix.h>\n#include <utils\/tiny_tools.h>\n#include <interval\/boundary_gramian.h>\n\nnamespace WaveletTL\n{\n template <int d, int dT>\n PBasis<d,dT>::PBasis(const int s0, const int s1) {\n assert(d >= 2 && d <= 3);\n assert(s0 >= d-2 && s1 >= d-2);\n\n this->s0 = s0;\n this->s1 = s1;\n\n setup();\n }\n\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup() {\n \/\/ For simplicity, we do not implement a fully generic setup here\n \/\/ but only setup the parameters for several important special cases from [P].\n \/\/ Namely, we restrict the setting to the case s0 >= d-2, where no \"additional\"\n \/\/ interior dual generators have to be constructed. In a later version of\n \/\/ this class, we will fix this.\n\n j0_ = (int) ceil(log(ell2T<d,dT>()-ell1T<d,dT>()+std::max(s0,s1)+1.-d)\/M_LN2+1);\n \n \/\/ setup the refinement matrix block for all \"real\" primal boundary B-splines,\n \/\/ obeying the block structure (3.15)\n \/\/ (ignoring the current values of s0 (and s1))\n MathTL::SchoenbergKnotSequence<d> sknots;\n Matrix<double> ML_0;\n MathTL::compute_Bspline_refinement_matrix<d>(&sknots, ML_0);\n \n \/\/ The total number of (left) boundary generators is always exactly dT\n \/\/ (to be able reproduce all polynomials by the dual generators).\n ML_.resize(3*dT+s0-1, dT);\n for (int column = s0; column < d-1; column++)\n for (int row = s0; row < 2*(d-1); row++)\n\tML_.set_entry(row-s0, column-s0, ML_0.get_entry(row,column));\n for (int k = d; k <= dT+s0; k++)\n for (int n = 2*k-d; n <= 2*k; n++)\n \tML_.set_entry(n-1-s0,k-1-s0,cdf.a().get_coefficient(MultiIndex<int,1>(-(d\/2)+n+d-2*k)));\n cout << \"ML=\" << endl << ML_;\n\n MR_.resize(3*dT+s1-1, dT);\n for (int column = s1; column < d-1; column++)\n for (int row = s1; row < 2*(d-1); row++)\n\tMR_.set_entry(row-s1, column-s1, ML_0.get_entry(row,column));\n for (int k = d; k <= dT+s1; k++)\n for (int n = 2*k-d; n <= 2*k; n++)\n \tMR_.set_entry(n-1-s1,k-1-s1,cdf.a().get_coefficient(MultiIndex<int,1>(-(d\/2)+n+d-2*k)));\n cout << \"MR=\" << endl << MR_;\n\n setup_Mj0(ML_, MR_, Mj0); \/\/ [DKU, (3.5.1)]\n\n \/\/ setup the expansion coefficients of the unbiorthogonalized dual generators\n \/\/ w.r.t. the truncated CDF generators, see [DKU, Lemma 3.1]\n Matrix<double> MLTp(3*dT+s0-1, dT);\n for (unsigned int r = 0; r < dT; r++) {\n MLTp.set_entry(r, r, ldexp(1.0, -r));\n for (int m = ellT_l(); m <= 2*ellT_l()+ell1T<d,dT>()-1; m++)\n\tMLTp.set_entry(dT+m-ellT_l(), r, alpha(m, r));\n for (int m = 2*ellT_l()+ell1T<d,dT>(); m <= 2*ellT_l()+ell2T<d,dT>()-2; m++)\n\tMLTp.set_entry(dT+m-ellT_l(), r, betaL(m, r));\n }\n cout << \"MLTp=\" << endl << MLTp;\n \n Matrix<double> MRTp(3*dT+s1-1, dT);\n for (unsigned int r = 0; r < dT; r++) {\n MRTp.set_entry(r, r, ldexp(1.0, -r));\n for (int m = ellT_r(); m <= 2*ellT_r()+ell1T<d,dT>()-1; m++)\n\tMRTp.set_entry(dT+m-ellT_r(), r, alpha(m, r));\n for (int m = 2*ellT_r()+ell1T<d,dT>(); m <= 2*ellT_r()+ell2T<d,dT>()-2; m++)\n\tMRTp.set_entry(dT+m-ellT_r(), r, betaR(m, r));\n }\n cout << \"MRTp=\" << endl << MRTp;\n\n SparseMatrix<double> mj0tp; setup_Mj0Tp(MLTp, MRTp, mj0tp); \/\/ [DKU, (3.5.5)]\n\n \/\/ for the biorthogonalization of the generators,\n \/\/ compute the gramian matrix of the primal and dual boundary generators\n compute_biorthogonal_boundary_gramian\n <CDFMask_primal<d>,CDFMask_dual<d,dT> >(ML_, MLTp, GammaL);\n cout << \"GammaL=\" << endl << GammaL;\n\n compute_biorthogonal_boundary_gramian\n <CDFMask_primal<d>,CDFMask_dual<d,dT> >(MR_, MRTp, GammaR);\n cout << \"GammaR=\" << endl << GammaR;\n\n \/\/ biorthogonalize the generators\n setup_Cj();\n Mj0T = transpose(inv_CjpT) * mj0tp * transpose(CjT); \/\/ [DKU, (2.4.3)]\n\n#if 0\n cout << \"PBasis(): check biorthogonality of Mj0, Mj0T:\" << endl;\n\/\/ cout << \"Mj0=\" << endl << Mj0 << endl << \"Mj0T=\" << endl << Mj0T << endl;\n\n SparseMatrix<double> testbio0 = transpose(Mj0) * Mj0T;\n\/\/ cout << \"Mj0^T*Mj0T=\" << endl << testbio0 << endl;\n for (unsigned int i = 0; i < testbio0.row_dimension(); i++)\n testbio0.set_entry(i, i, testbio0.get_entry(i, i) - 2.0);\n cout << \"* ||Mj0^T*Mj0T-2*I||_infty: \" << row_sum_norm(testbio0) << endl;\n\n testbio0 = transpose(Mj0T) * Mj0;\n \/\/ cout << \"Mj0T*Mj0^T=\" << endl << testbio0 << endl;\n for (unsigned int i = 0; i < testbio0.row_dimension(); i++)\n testbio0.set_entry(i, i, testbio0.get_entry(i, i) - 2.0);\n cout << \"* ||Mj0T^T*Mj0-2*I||_infty: \" << row_sum_norm(testbio0) << endl;\n#endif \n\n\n }\n\n template <int d, int dT>\n const double\n PBasis<d,dT>::alpha(const int m, const unsigned int r) const {\n double result = 0;\n if (r == 0)\n return 1; \/\/ [DKU] (5.1.1)\n else {\n if (m == 0) {\n\t\/\/ [DKU] (5.1.3)\n\tfor (int k = ell1<d>(); k <= ell2<d>(); k++) {\n\t double help = 0;\n\t for (unsigned int s = 0; s < r; s++)\n\t help += binomial(r, s) * intpower(k, r-s) * alpha(0, s);\n\t result += cdf.a().get_coefficient(MultiIndex<int,1>(k)) * help;\n\t}\n\tresult \/= ldexp(1.0, r+1) - 2.0;\n } else {\n\t\/\/ [DKU] (5.1.2)\n\tfor (unsigned int i = 0; i <= r; i++)\n\t result += binomial(r, i) * intpower(m, i) * alpha(0, r-i);\n }\n }\n return result;\n }\n \n template <int d, int dT>\n const double\n PBasis<d,dT>::betaL(const int m, const unsigned int r) const {\n \/\/ [DKU] (3.2.31)\n double result = 0;\n for (int q = (int)ceil((m-ell2T<d,dT>())\/2.0); q < ellT_l(); q++)\n result += alpha(q, r) * cdf.aT().get_coefficient(MultiIndex<int,1>(m-2*q));\n return result;\n }\n\n template <int d, int dT>\n const double\n PBasis<d,dT>::betaR(const int m, const unsigned int r) const {\n \/\/ [DKU] (3.2.31)\n double result = 0;\n for (int q = (int)ceil((m-ell2T<d,dT>())\/2.0); q < ellT_r(); q++)\n result += alpha(q, r) * cdf.aT().get_coefficient(MultiIndex<int,1>(m-2*q));\n return result;\n }\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup_Mj0(const Matrix<double>& ML, const Matrix<double>& MR, SparseMatrix<double>& Mj0) {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::Mj0()\n \/\/ cf. [DKU section 3.5]\n\n const int nj = Deltasize(j0());\n const int njp = Deltasize(j0()+1);\n Mj0.resize(njp, nj);\n\n for (unsigned int i = 0; i < ML.row_dimension(); i++)\n for (unsigned int k = 0; k < ML.column_dimension(); k++)\n\tMj0.set_entry(i, k, ML.get_entry(i, k));\n \n for (unsigned int i = 0; i < MR.row_dimension(); i++)\n for (unsigned int k = 0; k < MR.column_dimension(); k++)\n\tMj0.set_entry(njp-i-1, nj-k-1, MR.get_entry(i, k));\n \n int startrow = d+ell_l()+ell1<d>()-2*s0;\n for (int col = d-s0; col < nj-(d-s1); col++, startrow+=2) {\n int row = startrow;\n for (MultivariateLaurentPolynomial<double, 1>::const_iterator it(cdf.a().begin());\n\t it != cdf.a().end(); ++it, row++)\n\tMj0.set_entry(row, col, *it);\n }\n \n\/\/ cout << \"Mj0=\" << endl << Mj0 << endl;\n }\n\n template <int d, int dT>\n void\n PBasis<d,dT>::setup_Mj0Tp(const Matrix<double>& MLTp, const Matrix<double>& MRTp, SparseMatrix<double>& Mj0Tp) {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::Mj0ts()\n \n const int nj = Deltasize(j0());\n const int njp = Deltasize(j0()+1);\n Mj0Tp.resize(njp, nj);\n \n for (unsigned int i = 0; i < MLTp.row_dimension(); i++)\n for (unsigned int k = 0; k < MLTp.column_dimension(); k++)\n\tMj0Tp.set_entry(i, k, MLTp.get_entry(i, k));\n \n for (unsigned int i = 0; i < MRTp.row_dimension(); i++)\n for (unsigned int k = 0; k < MRTp.column_dimension(); k++)\n\tMj0Tp.set_entry(njp-i-1, nj-k-1, MRTp.get_entry(i, k));\n \n int startrow = dT+ellT_l()+ell1T<d,dT>();\n for (int col = dT; col < nj-dT; col++, startrow+=2) {\n int row = startrow;\n for (MultivariateLaurentPolynomial<double, 1>::const_iterator it(cdf.aT().begin());\n\t it != cdf.aT().end(); ++it, row++)\n\tMj0Tp.set_entry(row, col, *it);\n }\n \n\/\/ cout << \"Mj0Tp=\" << endl << Mj0Tp << endl;\n }\n\n template <int d, int dT>\n void PBasis<d,dT>::setup_Cj() {\n \/\/ IGPMlib reference: I_Basis_Bspline_s::setup_Cj(), ::put_Mat()\n\n \/\/ [DKU (5.2.5)]\n\n Matrix<double> CLGammaLInv;\n QUDecomposition<double>(GammaL).inverse(CLGammaLInv);\n Matrix<double> CLT = transpose(CLGammaLInv);\n \n Matrix<double> CRGammaRInv;\n QUDecomposition<double>(GammaR).inverse(CRGammaRInv);\n Matrix<double> CRT = transpose(CRGammaRInv);\n \n CjT.diagonal(Deltasize(j0()), 1.0);\n CjT.set_block(0, 0, CLT);\n CjT.set_block(Deltasize(j0())-CRT.row_dimension(),\n \t\t Deltasize(j0())-CRT.column_dimension(),\n \t\t CRT, true);\n\n Matrix<double> inv_CLT, inv_CRT;\n QUDecomposition<double>(CLT).inverse(inv_CLT);\n QUDecomposition<double>(CRT).inverse(inv_CRT);\n\n inv_CjT.diagonal(Deltasize(j0()), 1.0);\n inv_CjT.set_block(0, 0, inv_CLT);\n inv_CjT.set_block(Deltasize(j0())-inv_CRT.row_dimension(),\n \t\t Deltasize(j0())-inv_CRT.column_dimension(),\n \t\t inv_CRT, true);\n\n CjpT.diagonal(Deltasize(j0()+1), 1.0);\n CjpT.set_block(0, 0, CLT);\n CjpT.set_block(Deltasize(j0()+1)-CRT.row_dimension(),\n \t\t Deltasize(j0()+1)-CRT.column_dimension(),\n \t\t CRT, true);\n\n inv_CjpT.diagonal(Deltasize(j0()+1), 1.0);\n inv_CjpT.set_block(0, 0, inv_CLT);\n inv_CjpT.set_block(Deltasize(j0()+1)-inv_CRT.row_dimension(),\n \t\t Deltasize(j0()+1)-inv_CRT.column_dimension(),\n \t\t inv_CRT, true);\n\n#if 1\n cout << \"PBasis: testing setup of Cj:\" << endl;\n\n SparseMatrix<double> test1 = CjT * inv_CjT;\n for (unsigned int i = 0; i < test1.row_dimension(); i++)\n test1.set_entry(i, i, test1.get_entry(i, i) - 1.0);\n cout << \"* ||CjT*inv_CjT-I||_infty: \" << row_sum_norm(test1) << endl;\n\n SparseMatrix<double> test3 = CjpT * inv_CjpT;\n for (unsigned int i = 0; i < test3.row_dimension(); i++)\n test3.set_entry(i, i, test3.get_entry(i, i) - 1.0);\n cout << \"* ||CjpT*inv_CjpT-I||_infty: \" << row_sum_norm(test3) << endl;\n\n#endif\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n\n#include \"SkColorFilter.h\"\n#include \"SkMultiPictureDraw.h\"\n#include \"SkPictureRecorder.h\"\n#include \"SkSurface.h\"\n\nstatic const SkScalar kRoot3Over2 = 0.86602545f; \/\/ sin(60)\n\nstatic const int kHexSide = 30;\nstatic const int kNumHexX = 6;\nstatic const int kNumHexY = 6;\nstatic const int kPicWidth = kNumHexX * kHexSide;\nstatic const int kPicHeight = SkScalarCeilToInt((kNumHexY - 0.5f) * 2 * kHexSide * kRoot3Over2);\nstatic const SkScalar kInset = 20.0f;\n\n\/\/ Create a hexagon centered at (originX, originY)\nstatic SkPath make_hex_path(SkScalar originX, SkScalar originY) {\n SkPath hex;\n hex.moveTo(originX-kHexSide, originY);\n hex.rLineTo(SkScalarHalf(kHexSide), kRoot3Over2 * kHexSide);\n hex.rLineTo(SkIntToScalar(kHexSide), 0);\n hex.rLineTo(SkScalarHalf(kHexSide), -kHexSide * kRoot3Over2);\n hex.rLineTo(-SkScalarHalf(kHexSide), -kHexSide * kRoot3Over2);\n hex.rLineTo(-SkIntToScalar(kHexSide), 0);\n hex.close();\n return hex;\n}\n\n\/\/ Make a picture that is a tiling of the plane with stroked hexagons where\n\/\/ each hexagon is in its own layer. The layers are to exercise Ganesh's\n\/\/ layer hoisting.\nstatic const SkPicture* make_picture(SkColor fillColor) {\n\n \/\/ Create a hexagon with its center at the origin\n SkPath hex = make_hex_path(0, 0);\n\n SkPaint fill;\n fill.setStyle(SkPaint::kFill_Style);\n fill.setColor(fillColor);\n\n SkPaint stroke;\n stroke.setStyle(SkPaint::kStroke_Style);\n stroke.setStrokeWidth(3);\n\n SkPictureRecorder recorder;\n\n SkCanvas* canvas = recorder.beginRecording(kPicWidth, kPicHeight);\n\n SkScalar xPos, yPos = 0;\n\n for (int y = 0; y < kNumHexY; ++y) {\n xPos = 0;\n\n for (int x = 0; x < kNumHexX; ++x) {\n canvas->saveLayer(NULL, NULL);\n canvas->translate(xPos, yPos + ((x % 2) ? kRoot3Over2 * kHexSide : 0));\n canvas->drawPath(hex, fill);\n canvas->drawPath(hex, stroke);\n canvas->restore();\n\n xPos += 1.5f * kHexSide;\n }\n\n yPos += 2 * kHexSide * kRoot3Over2;\n }\n\n return recorder.endRecording();\n}\n\nstatic SkSurface* create_compat_surface(SkCanvas* canvas, int width, int height) {\n SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);\n\n SkSurface* surface = canvas->newSurface(info);\n if (NULL == surface) {\n \/\/ picture canvas returns NULL so fall back to raster\n surface = SkSurface::NewRaster(info);\n }\n\n return surface;\n}\n\n\/\/ This class stores the information required to compose all the result\n\/\/ fragments potentially generated by the MultiPictureDraw object\nclass ComposeStep {\npublic:\n ComposeStep() : fSurf(NULL), fX(0.0f), fY(0.0f), fPaint(NULL) { }\n ~ComposeStep() { SkSafeUnref(fSurf); SkDELETE(fPaint); }\n\n SkSurface* fSurf;\n SkScalar fX;\n SkScalar fY;\n SkPaint* fPaint;\n};\n\ntypedef void (*PFContentMtd)(SkCanvas* canvas, const SkPicture* pictures[2]);\n\n\/\/ Just a single picture with no clip\nstatic void no_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n}\n\n\/\/ Two pictures with a rect clip on the second one\nstatic void rect_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n SkRect rect = SkRect::MakeWH(SkIntToScalar(kPicWidth), SkIntToScalar(kPicHeight));\n rect.inset(kInset, kInset);\n\n canvas->clipRect(rect);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with a round rect clip on the second one\nstatic void rrect_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n SkRect rect = SkRect::MakeWH(SkIntToScalar(kPicWidth), SkIntToScalar(kPicHeight));\n rect.inset(kInset, kInset);\n \n SkRRect rrect;\n rrect.setRectXY(rect, kInset, kInset);\n\n canvas->clipRRect(rrect);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with a clip path on the second one\nstatic void path_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n \/\/ Create a hexagon centered on the middle of the hex grid\n SkPath hex = make_hex_path((kNumHexX \/ 2.0f) * kHexSide, kNumHexY * kHexSide * kRoot3Over2);\n\n canvas->clipPath(hex);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with an inverse clip path on the second one\nstatic void invpath_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n \/\/ Create a hexagon centered on the middle of the hex grid\n SkPath hex = make_hex_path((kNumHexX \/ 2.0f) * kHexSide, kNumHexY * kHexSide * kRoot3Over2);\n hex.setFillType(SkPath::kInverseEvenOdd_FillType);\n\n canvas->clipPath(hex);\n\n canvas->drawPicture(pictures[1]);\n}\n\nstatic const PFContentMtd gContentMthds[] = {\n no_clip,\n rect_clip,\n rrect_clip,\n path_clip,\n invpath_clip\n};\n\nstatic void create_content(SkMultiPictureDraw* mpd, PFContentMtd pfGen,\n const SkPicture* pictures[2],\n SkCanvas* dest, const SkMatrix& xform) {\n SkAutoTUnref<SkPicture> composite;\n\n {\n SkPictureRecorder recorder;\n\n SkCanvas* pictureCanvas = recorder.beginRecording(kPicWidth, kPicHeight);\n\n (*pfGen)(pictureCanvas, pictures);\n\n composite.reset(recorder.endRecording());\n }\n\n mpd->add(dest, composite, &xform);\n}\n\ntypedef void(*PFLayoutMtd)(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd, \n PFContentMtd pfGen, const SkPicture* pictures[2],\n SkTArray<ComposeStep>* composeSteps);\n\n\/\/ Draw the content into a single canvas\nstatic void simple(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd, \n PFContentMtd pfGen, \n const SkPicture* pictures[2],\n SkTArray<ComposeStep> *composeSteps) {\n\n ComposeStep& step = composeSteps->push_back();\n\n step.fSurf = create_compat_surface(finalCanvas, kPicWidth, kPicHeight);\n\n SkCanvas* subCanvas = step.fSurf->getCanvas();\n\n create_content(mpd, pfGen, pictures, subCanvas, SkMatrix::I());\n}\n\n\/\/ Draw the content into multiple canvases\/tiles\nstatic void tiled(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd,\n PFContentMtd pfGen, \n const SkPicture* pictures[2],\n SkTArray<ComposeStep> *composeSteps) {\n static const int kNumTilesX = 2;\n static const int kNumTilesY = 2;\n static const int kTileWidth = kPicWidth \/ kNumTilesX;\n static const int kTileHeight = kPicHeight \/ kNumTilesY;\n\n SkASSERT(kPicWidth == kNumTilesX * kTileWidth);\n SkASSERT(kPicHeight == kNumTilesY * kTileHeight);\n\n static const SkColor colors[kNumTilesX][kNumTilesY] = {\n { SK_ColorCYAN, SK_ColorMAGENTA }, \n { SK_ColorYELLOW, SK_ColorGREEN }\n };\n\n for (int y = 0; y < kNumTilesY; ++y) {\n for (int x = 0; x < kNumTilesX; ++x) {\n ComposeStep& step = composeSteps->push_back();\n\n step.fX = SkIntToScalar(x*kTileWidth);\n step.fY = SkIntToScalar(y*kTileHeight);\n step.fPaint = SkNEW(SkPaint);\n step.fPaint->setColorFilter(\n SkColorFilter::CreateModeFilter(colors[x][y], SkXfermode::kModulate_Mode))->unref();\n\n step.fSurf = create_compat_surface(finalCanvas, kTileWidth, kTileHeight);\n\n SkCanvas* subCanvas = step.fSurf->getCanvas();\n\n SkMatrix trans;\n trans.setTranslate(-SkIntToScalar(x*kTileWidth), -SkIntToScalar(y*kTileHeight));\n\n create_content(mpd, pfGen, pictures, subCanvas, trans);\n }\n }\n}\n\nstatic const PFLayoutMtd gLayoutMthds[] = { simple, tiled };\n\nnamespace skiagm {\n \/**\n * This GM exercises the SkMultiPictureDraw object. It tests the\n * cross product of:\n * tiled vs. all-at-once rendering (e.g., into many or just 1 canvas)\n * different clips (e.g., none, rect, rrect)\n * single vs. multiple pictures (e.g., normal vs. picture-pile-style content)\n *\/\n class MultiPictureDraw : public GM {\n public:\n enum Content {\n kNoClipSingle_Content,\n kRectClipMulti_Content,\n kRRectClipMulti_Content,\n kPathClipMulti_Content,\n kInvPathClipMulti_Content,\n\n kLast_Content = kInvPathClipMulti_Content\n };\n\n static const int kContentCnt = kLast_Content + 1;\n\n enum Layout {\n kSimple_Layout,\n kTiled_Layout,\n\n kLast_Layout = kTiled_Layout\n };\n\n static const int kLayoutCnt = kLast_Layout + 1;\n\n MultiPictureDraw(Content content, Layout layout) : fContent(content), fLayout(layout) {\n SkASSERT(SK_ARRAY_COUNT(gLayoutMthds) == kLayoutCnt);\n SkASSERT(SK_ARRAY_COUNT(gContentMthds) == kContentCnt);\n\n fPictures[0] = fPictures[1] = NULL;\n }\n\n virtual ~MultiPictureDraw() {\n SkSafeUnref(fPictures[0]);\n SkSafeUnref(fPictures[1]);\n }\n\n protected:\n Content fContent;\n Layout fLayout;\n const SkPicture* fPictures[2];\n\n virtual void onOnceBeforeDraw() SK_OVERRIDE {\n fPictures[0] = SkRef(make_picture(SK_ColorWHITE));\n fPictures[1] = SkRef(make_picture(SK_ColorGRAY));\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE{\n SkMultiPictureDraw mpd;\n SkTArray<ComposeStep> composeSteps;\n\n \/\/ Fill up the MultiPictureDraw\n (*gLayoutMthds[fLayout])(canvas, &mpd, \n gContentMthds[fContent], \n fPictures, &composeSteps);\n\n mpd.draw();\n\n \/\/ Compose all the drawn canvases into the final canvas\n for (int i = 0; i < composeSteps.count(); ++i) {\n const ComposeStep& step = composeSteps[i];\n\n SkAutoTUnref<SkImage> image(step.fSurf->newImageSnapshot());\n\n image->draw(canvas, step.fX, step.fY, step.fPaint);\n }\n }\n\n virtual SkISize onISize() SK_OVERRIDE{ return SkISize::Make(kPicWidth, kPicHeight); }\n\n virtual SkString onShortName() SK_OVERRIDE{\n static const char* gContentNames[] = { \n \"noclip\", \"rectclip\", \"rrectclip\", \"pathclip\", \"invpathclip\" \n };\n static const char* gLayoutNames[] = { \"simple\", \"tiled\" };\n\n SkASSERT(SK_ARRAY_COUNT(gLayoutNames) == kLayoutCnt);\n SkASSERT(SK_ARRAY_COUNT(gContentNames) == kContentCnt);\n\n SkString name(\"multipicturedraw_\");\n\n name.append(gContentNames[fContent]);\n name.append(\"_\");\n name.append(gLayoutNames[fLayout]);\n return name;\n }\n\n virtual uint32_t onGetFlags() const SK_OVERRIDE { return kAsBench_Flag | kSkipTiled_Flag; }\n\n private:\n typedef GM INHERITED;\n };\n\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kNoClipSingle_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRectClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRRectClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kPathClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kInvPathClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kNoClipSingle_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRectClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRRectClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kPathClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kInvPathClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n}\n<commit_msg>Fix leak in multipicturedraw GMs.<commit_after>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n\n#include \"SkColorFilter.h\"\n#include \"SkMultiPictureDraw.h\"\n#include \"SkPictureRecorder.h\"\n#include \"SkSurface.h\"\n\nstatic const SkScalar kRoot3Over2 = 0.86602545f; \/\/ sin(60)\n\nstatic const int kHexSide = 30;\nstatic const int kNumHexX = 6;\nstatic const int kNumHexY = 6;\nstatic const int kPicWidth = kNumHexX * kHexSide;\nstatic const int kPicHeight = SkScalarCeilToInt((kNumHexY - 0.5f) * 2 * kHexSide * kRoot3Over2);\nstatic const SkScalar kInset = 20.0f;\n\n\/\/ Create a hexagon centered at (originX, originY)\nstatic SkPath make_hex_path(SkScalar originX, SkScalar originY) {\n SkPath hex;\n hex.moveTo(originX-kHexSide, originY);\n hex.rLineTo(SkScalarHalf(kHexSide), kRoot3Over2 * kHexSide);\n hex.rLineTo(SkIntToScalar(kHexSide), 0);\n hex.rLineTo(SkScalarHalf(kHexSide), -kHexSide * kRoot3Over2);\n hex.rLineTo(-SkScalarHalf(kHexSide), -kHexSide * kRoot3Over2);\n hex.rLineTo(-SkIntToScalar(kHexSide), 0);\n hex.close();\n return hex;\n}\n\n\/\/ Make a picture that is a tiling of the plane with stroked hexagons where\n\/\/ each hexagon is in its own layer. The layers are to exercise Ganesh's\n\/\/ layer hoisting.\nstatic const SkPicture* make_picture(SkColor fillColor) {\n\n \/\/ Create a hexagon with its center at the origin\n SkPath hex = make_hex_path(0, 0);\n\n SkPaint fill;\n fill.setStyle(SkPaint::kFill_Style);\n fill.setColor(fillColor);\n\n SkPaint stroke;\n stroke.setStyle(SkPaint::kStroke_Style);\n stroke.setStrokeWidth(3);\n\n SkPictureRecorder recorder;\n\n SkCanvas* canvas = recorder.beginRecording(kPicWidth, kPicHeight);\n\n SkScalar xPos, yPos = 0;\n\n for (int y = 0; y < kNumHexY; ++y) {\n xPos = 0;\n\n for (int x = 0; x < kNumHexX; ++x) {\n canvas->saveLayer(NULL, NULL);\n canvas->translate(xPos, yPos + ((x % 2) ? kRoot3Over2 * kHexSide : 0));\n canvas->drawPath(hex, fill);\n canvas->drawPath(hex, stroke);\n canvas->restore();\n\n xPos += 1.5f * kHexSide;\n }\n\n yPos += 2 * kHexSide * kRoot3Over2;\n }\n\n return recorder.endRecording();\n}\n\nstatic SkSurface* create_compat_surface(SkCanvas* canvas, int width, int height) {\n SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);\n\n SkSurface* surface = canvas->newSurface(info);\n if (NULL == surface) {\n \/\/ picture canvas returns NULL so fall back to raster\n surface = SkSurface::NewRaster(info);\n }\n\n return surface;\n}\n\n\/\/ This class stores the information required to compose all the result\n\/\/ fragments potentially generated by the MultiPictureDraw object\nclass ComposeStep {\npublic:\n ComposeStep() : fSurf(NULL), fX(0.0f), fY(0.0f), fPaint(NULL) { }\n ~ComposeStep() { SkSafeUnref(fSurf); SkDELETE(fPaint); }\n\n SkSurface* fSurf;\n SkScalar fX;\n SkScalar fY;\n SkPaint* fPaint;\n};\n\ntypedef void (*PFContentMtd)(SkCanvas* canvas, const SkPicture* pictures[2]);\n\n\/\/ Just a single picture with no clip\nstatic void no_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n}\n\n\/\/ Two pictures with a rect clip on the second one\nstatic void rect_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n SkRect rect = SkRect::MakeWH(SkIntToScalar(kPicWidth), SkIntToScalar(kPicHeight));\n rect.inset(kInset, kInset);\n\n canvas->clipRect(rect);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with a round rect clip on the second one\nstatic void rrect_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n SkRect rect = SkRect::MakeWH(SkIntToScalar(kPicWidth), SkIntToScalar(kPicHeight));\n rect.inset(kInset, kInset);\n \n SkRRect rrect;\n rrect.setRectXY(rect, kInset, kInset);\n\n canvas->clipRRect(rrect);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with a clip path on the second one\nstatic void path_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n \/\/ Create a hexagon centered on the middle of the hex grid\n SkPath hex = make_hex_path((kNumHexX \/ 2.0f) * kHexSide, kNumHexY * kHexSide * kRoot3Over2);\n\n canvas->clipPath(hex);\n\n canvas->drawPicture(pictures[1]);\n}\n\n\/\/ Two pictures with an inverse clip path on the second one\nstatic void invpath_clip(SkCanvas* canvas, const SkPicture* pictures[2]) {\n canvas->drawPicture(pictures[0]);\n\n \/\/ Create a hexagon centered on the middle of the hex grid\n SkPath hex = make_hex_path((kNumHexX \/ 2.0f) * kHexSide, kNumHexY * kHexSide * kRoot3Over2);\n hex.setFillType(SkPath::kInverseEvenOdd_FillType);\n\n canvas->clipPath(hex);\n\n canvas->drawPicture(pictures[1]);\n}\n\nstatic const PFContentMtd gContentMthds[] = {\n no_clip,\n rect_clip,\n rrect_clip,\n path_clip,\n invpath_clip\n};\n\nstatic void create_content(SkMultiPictureDraw* mpd, PFContentMtd pfGen,\n const SkPicture* pictures[2],\n SkCanvas* dest, const SkMatrix& xform) {\n SkAutoTUnref<SkPicture> composite;\n\n {\n SkPictureRecorder recorder;\n\n SkCanvas* pictureCanvas = recorder.beginRecording(kPicWidth, kPicHeight);\n\n (*pfGen)(pictureCanvas, pictures);\n\n composite.reset(recorder.endRecording());\n }\n\n mpd->add(dest, composite, &xform);\n}\n\ntypedef void(*PFLayoutMtd)(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd, \n PFContentMtd pfGen, const SkPicture* pictures[2],\n SkTArray<ComposeStep>* composeSteps);\n\n\/\/ Draw the content into a single canvas\nstatic void simple(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd, \n PFContentMtd pfGen, \n const SkPicture* pictures[2],\n SkTArray<ComposeStep> *composeSteps) {\n\n ComposeStep& step = composeSteps->push_back();\n\n step.fSurf = create_compat_surface(finalCanvas, kPicWidth, kPicHeight);\n\n SkCanvas* subCanvas = step.fSurf->getCanvas();\n\n create_content(mpd, pfGen, pictures, subCanvas, SkMatrix::I());\n}\n\n\/\/ Draw the content into multiple canvases\/tiles\nstatic void tiled(SkCanvas* finalCanvas, SkMultiPictureDraw* mpd,\n PFContentMtd pfGen, \n const SkPicture* pictures[2],\n SkTArray<ComposeStep> *composeSteps) {\n static const int kNumTilesX = 2;\n static const int kNumTilesY = 2;\n static const int kTileWidth = kPicWidth \/ kNumTilesX;\n static const int kTileHeight = kPicHeight \/ kNumTilesY;\n\n SkASSERT(kPicWidth == kNumTilesX * kTileWidth);\n SkASSERT(kPicHeight == kNumTilesY * kTileHeight);\n\n static const SkColor colors[kNumTilesX][kNumTilesY] = {\n { SK_ColorCYAN, SK_ColorMAGENTA }, \n { SK_ColorYELLOW, SK_ColorGREEN }\n };\n\n for (int y = 0; y < kNumTilesY; ++y) {\n for (int x = 0; x < kNumTilesX; ++x) {\n ComposeStep& step = composeSteps->push_back();\n\n step.fX = SkIntToScalar(x*kTileWidth);\n step.fY = SkIntToScalar(y*kTileHeight);\n step.fPaint = SkNEW(SkPaint);\n step.fPaint->setColorFilter(\n SkColorFilter::CreateModeFilter(colors[x][y], SkXfermode::kModulate_Mode))->unref();\n\n step.fSurf = create_compat_surface(finalCanvas, kTileWidth, kTileHeight);\n\n SkCanvas* subCanvas = step.fSurf->getCanvas();\n\n SkMatrix trans;\n trans.setTranslate(-SkIntToScalar(x*kTileWidth), -SkIntToScalar(y*kTileHeight));\n\n create_content(mpd, pfGen, pictures, subCanvas, trans);\n }\n }\n}\n\nstatic const PFLayoutMtd gLayoutMthds[] = { simple, tiled };\n\nnamespace skiagm {\n \/**\n * This GM exercises the SkMultiPictureDraw object. It tests the\n * cross product of:\n * tiled vs. all-at-once rendering (e.g., into many or just 1 canvas)\n * different clips (e.g., none, rect, rrect)\n * single vs. multiple pictures (e.g., normal vs. picture-pile-style content)\n *\/\n class MultiPictureDraw : public GM {\n public:\n enum Content {\n kNoClipSingle_Content,\n kRectClipMulti_Content,\n kRRectClipMulti_Content,\n kPathClipMulti_Content,\n kInvPathClipMulti_Content,\n\n kLast_Content = kInvPathClipMulti_Content\n };\n\n static const int kContentCnt = kLast_Content + 1;\n\n enum Layout {\n kSimple_Layout,\n kTiled_Layout,\n\n kLast_Layout = kTiled_Layout\n };\n\n static const int kLayoutCnt = kLast_Layout + 1;\n\n MultiPictureDraw(Content content, Layout layout) : fContent(content), fLayout(layout) {\n SkASSERT(SK_ARRAY_COUNT(gLayoutMthds) == kLayoutCnt);\n SkASSERT(SK_ARRAY_COUNT(gContentMthds) == kContentCnt);\n\n fPictures[0] = fPictures[1] = NULL;\n }\n\n virtual ~MultiPictureDraw() {\n SkSafeUnref(fPictures[0]);\n SkSafeUnref(fPictures[1]);\n }\n\n protected:\n Content fContent;\n Layout fLayout;\n const SkPicture* fPictures[2];\n\n virtual void onOnceBeforeDraw() SK_OVERRIDE {\n fPictures[0] = make_picture(SK_ColorWHITE);\n fPictures[1] = make_picture(SK_ColorGRAY);\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE{\n SkMultiPictureDraw mpd;\n SkTArray<ComposeStep> composeSteps;\n\n \/\/ Fill up the MultiPictureDraw\n (*gLayoutMthds[fLayout])(canvas, &mpd, \n gContentMthds[fContent], \n fPictures, &composeSteps);\n\n mpd.draw();\n\n \/\/ Compose all the drawn canvases into the final canvas\n for (int i = 0; i < composeSteps.count(); ++i) {\n const ComposeStep& step = composeSteps[i];\n\n SkAutoTUnref<SkImage> image(step.fSurf->newImageSnapshot());\n\n image->draw(canvas, step.fX, step.fY, step.fPaint);\n }\n }\n\n virtual SkISize onISize() SK_OVERRIDE{ return SkISize::Make(kPicWidth, kPicHeight); }\n\n virtual SkString onShortName() SK_OVERRIDE{\n static const char* gContentNames[] = { \n \"noclip\", \"rectclip\", \"rrectclip\", \"pathclip\", \"invpathclip\" \n };\n static const char* gLayoutNames[] = { \"simple\", \"tiled\" };\n\n SkASSERT(SK_ARRAY_COUNT(gLayoutNames) == kLayoutCnt);\n SkASSERT(SK_ARRAY_COUNT(gContentNames) == kContentCnt);\n\n SkString name(\"multipicturedraw_\");\n\n name.append(gContentNames[fContent]);\n name.append(\"_\");\n name.append(gLayoutNames[fLayout]);\n return name;\n }\n\n virtual uint32_t onGetFlags() const SK_OVERRIDE { return kAsBench_Flag | kSkipTiled_Flag; }\n\n private:\n typedef GM INHERITED;\n };\n\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kNoClipSingle_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRectClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRRectClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kPathClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kInvPathClipMulti_Content, \n MultiPictureDraw::kSimple_Layout));)\n\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kNoClipSingle_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRectClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kRRectClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kPathClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n DEF_GM(return SkNEW_ARGS(MultiPictureDraw, (MultiPictureDraw::kInvPathClipMulti_Content, \n MultiPictureDraw::kTiled_Layout));)\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2015, Hobu Inc., hobu@hobu.co\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"BpfWriter.hpp\"\n\n#include <pdal\/pdal_internal.hpp>\n\n#include <zlib.h>\n\n#include <pdal\/Charbuf.hpp>\n#include <pdal\/Options.hpp>\n\n#include \"BpfCompressor.hpp\"\n\nnamespace pdal\n{\n\nOptions BpfWriter::getDefaultOptions()\n{\n Options ops;\n\n ops.add(\"filename\", \"\", \"Filename for BPF output\");\n ops.add(\"compression\", false, \"Whether zlib compression should be used\");\n ops.add(\"format\", \"dimension\", \"Point output format: \"\n \"non-interleaved(\\\"dimension\\\"), interleaved(\\\"point\\\") or \"\n \"byte-segregated(\\\"byte\\\")\");\n ops.add(\"coord_id\", 0, \"Coordinate ID (UTM zone).\");\n return ops;\n}\n\n\nvoid BpfWriter::processOptions(const Options& options)\n{\n if (m_filename.empty())\n throw pdal_error(\"Can't write BPF file without filename.\");\n bool compression = options.getValueOrDefault(\"compression\", false);\n m_header.m_compression = compression ? BpfCompression::Zlib :\n BpfCompression::None;\n\n std::string fileFormat =\n options.getValueOrDefault<std::string>(\"format\", \"POINT\");\n std::transform(fileFormat.begin(), fileFormat.end(), fileFormat.begin(),\n ::toupper);\n if (fileFormat.find(\"POINT\") != std::string::npos)\n m_header.m_pointFormat = BpfFormat::PointMajor;\n else if (fileFormat.find(\"BYTE\") != std::string::npos)\n m_header.m_pointFormat = BpfFormat::ByteMajor;\n else\n m_header.m_pointFormat = BpfFormat::DimMajor;\n if (options.hasOption(\"coord_id\"))\n {\n m_header.m_coordType = BpfCoordType::UTM;\n m_header.m_coordId = options.getValueOrThrow<int>(\"coord_id\");\n }\n else\n {\n m_header.m_coordType = BpfCoordType::None;\n m_header.m_coordId = 0;\n }\n}\n\n\nvoid BpfWriter::ready(PointContextRef ctx)\n{\n loadBpfDimensions(ctx);\n m_stream = FileUtils::createFile(m_filename, true);\n m_header.m_version = 3;\n m_header.m_numDim = m_dims.size();\n m_header.setLog(log());\n\n \/\/ We will re-write the header and dimensions to account for the point\n \/\/ count and dimension min\/max.\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_header.m_len = m_stream.position();\n m_header.m_xform.m_vals[0] = m_xXform.m_scale;\n m_header.m_xform.m_vals[5] = m_yXform.m_scale;\n m_header.m_xform.m_vals[10] = m_zXform.m_scale;\n}\n\n\nvoid BpfWriter::loadBpfDimensions(PointContextRef ctx)\n{\n \/\/ Verify that we have X, Y and Z and that they're the first three\n \/\/ dimensions.\n Dimension::IdList dims = ctx.dims();\n std::sort(dims.begin(), dims.end());\n if (dims.size() < 3 || dims[0] != Dimension::Id::X ||\n dims[1] != Dimension::Id::Y || dims[2] != Dimension::Id::Z)\n {\n throw pdal_error(\"Missing one of dimensions X, Y or Z. \"\n \"Can't write BPF.\");\n }\n\n for (auto id : dims)\n {\n BpfDimension dim;\n dim.m_id = id;\n dim.m_label = ctx.dimName(id);\n m_dims.push_back(dim);\n }\n}\n\n\nvoid BpfWriter::write(const PointBuffer& data)\n{\n setAutoOffset(data);\n\n \/\/ We know that X, Y and Z are dimensions 0, 1 and 2.\n m_dims[0].m_offset = m_xXform.m_offset;\n m_dims[1].m_offset = m_yXform.m_offset;\n m_dims[2].m_offset = m_zXform.m_offset;\n\n switch (m_header.m_pointFormat)\n {\n case BpfFormat::PointMajor:\n writePointMajor(data);\n break;\n case BpfFormat::DimMajor:\n writeDimMajor(data);\n break;\n case BpfFormat::ByteMajor:\n writeByteMajor(data);\n break;\n }\n m_header.m_numPts += data.size();\n}\n\n\nvoid BpfWriter::writePointMajor(const PointBuffer& data)\n{\n \/\/ Blocks of 10,000 points will ensure that we're under 16MB, even\n \/\/ for 255 dimensions.\n size_t blockpoints = std::min(10000UL, data.size());\n\n \/\/ For compression we're going to write to a buffer so that it can be\n \/\/ compressed before it's written to the file stream.\n BpfCompressor compressor(m_stream,\n blockpoints * sizeof(float) * m_dims.size());\n PointId idx = 0;\n while (idx < data.size())\n {\n if (m_header.m_compression)\n compressor.startBlock();\n size_t blockId;\n for (blockId = 0; idx < data.size() && blockId < blockpoints;\n ++idx, ++blockId)\n {\n for (auto & bpfDim : m_dims)\n {\n double d = getAdjustedValue(data, bpfDim, idx);\n m_stream << (float)d;\n }\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n }\n}\n\n\nvoid BpfWriter::writeDimMajor(const PointBuffer& data)\n{\n \/\/ We're going to pretend for now that we only even have one point buffer.\n BpfCompressor compressor(m_stream, data.size() * sizeof(float));\n\n for (auto & bpfDim : m_dims)\n {\n\n if (m_header.m_compression)\n compressor.startBlock();\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n double d = getAdjustedValue(data, bpfDim, idx);\n m_stream << (float)d;\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n }\n}\n\n\nvoid BpfWriter::writeByteMajor(const PointBuffer& data)\n{\n union\n {\n float f;\n uint32_t u32;\n } uu;\n\n \/\/ We're going to pretend for now that we only even have one point buffer.\n\n BpfCompressor compressor(m_stream,\n data.size() * sizeof(float) * m_dims.size());\n\n if (m_header.m_compression)\n compressor.startBlock();\n for (auto & bpfDim : m_dims)\n {\n for (size_t b = 0; b < sizeof(float); b++)\n {\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n uu.f = (float)getAdjustedValue(data, bpfDim, idx);\n uint8_t u8 = (uint8_t)(uu.u32 >> (b * CHAR_BIT));\n m_stream << u8;\n }\n }\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n}\n\n\ndouble BpfWriter::getAdjustedValue(const PointBuffer& buf,\n BpfDimension& bpfDim, PointId idx)\n{\n double d = buf.getFieldAs<double>(bpfDim.m_id, idx);\n bpfDim.m_min = std::min(bpfDim.m_min, d);\n bpfDim.m_max = std::max(bpfDim.m_max, d);\n\n if (bpfDim.m_id == Dimension::Id::X)\n d \/= m_xXform.m_scale;\n else if (bpfDim.m_id == Dimension::Id::Y)\n d \/= m_yXform.m_scale;\n else if (bpfDim.m_id == Dimension::Id::Z)\n d \/= m_zXform.m_scale;\n d -= bpfDim.m_offset;\n return (d - bpfDim.m_offset);\n}\n\n\nvoid BpfWriter::done(PointContextRef)\n{\n \/\/ Rewrite the header to update the the correct number of points and\n \/\/ statistics.\n m_stream.seek(0);\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_stream.flush();\n}\n\n} \/\/namespace pdal\n<commit_msg>Fix duplicate backout of offset.<commit_after>\/******************************************************************************\n* Copyright (c) 2015, Hobu Inc., hobu@hobu.co\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"BpfWriter.hpp\"\n\n#include <pdal\/pdal_internal.hpp>\n\n#include <zlib.h>\n\n#include <pdal\/Charbuf.hpp>\n#include <pdal\/Options.hpp>\n\n#include \"BpfCompressor.hpp\"\n\nnamespace pdal\n{\n\nOptions BpfWriter::getDefaultOptions()\n{\n Options ops;\n\n ops.add(\"filename\", \"\", \"Filename for BPF output\");\n ops.add(\"compression\", false, \"Whether zlib compression should be used\");\n ops.add(\"format\", \"dimension\", \"Point output format: \"\n \"non-interleaved(\\\"dimension\\\"), interleaved(\\\"point\\\") or \"\n \"byte-segregated(\\\"byte\\\")\");\n ops.add(\"coord_id\", 0, \"Coordinate ID (UTM zone).\");\n return ops;\n}\n\n\nvoid BpfWriter::processOptions(const Options& options)\n{\n if (m_filename.empty())\n throw pdal_error(\"Can't write BPF file without filename.\");\n bool compression = options.getValueOrDefault(\"compression\", false);\n m_header.m_compression = compression ? BpfCompression::Zlib :\n BpfCompression::None;\n\n std::string fileFormat =\n options.getValueOrDefault<std::string>(\"format\", \"POINT\");\n std::transform(fileFormat.begin(), fileFormat.end(), fileFormat.begin(),\n ::toupper);\n if (fileFormat.find(\"POINT\") != std::string::npos)\n m_header.m_pointFormat = BpfFormat::PointMajor;\n else if (fileFormat.find(\"BYTE\") != std::string::npos)\n m_header.m_pointFormat = BpfFormat::ByteMajor;\n else\n m_header.m_pointFormat = BpfFormat::DimMajor;\n if (options.hasOption(\"coord_id\"))\n {\n m_header.m_coordType = BpfCoordType::UTM;\n m_header.m_coordId = options.getValueOrThrow<int>(\"coord_id\");\n }\n else\n {\n m_header.m_coordType = BpfCoordType::None;\n m_header.m_coordId = 0;\n }\n}\n\n\nvoid BpfWriter::ready(PointContextRef ctx)\n{\n loadBpfDimensions(ctx);\n m_stream = FileUtils::createFile(m_filename, true);\n m_header.m_version = 3;\n m_header.m_numDim = m_dims.size();\n m_header.setLog(log());\n\n \/\/ We will re-write the header and dimensions to account for the point\n \/\/ count and dimension min\/max.\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_header.m_len = m_stream.position();\n m_header.m_xform.m_vals[0] = m_xXform.m_scale;\n m_header.m_xform.m_vals[5] = m_yXform.m_scale;\n m_header.m_xform.m_vals[10] = m_zXform.m_scale;\n}\n\n\nvoid BpfWriter::loadBpfDimensions(PointContextRef ctx)\n{\n \/\/ Verify that we have X, Y and Z and that they're the first three\n \/\/ dimensions.\n Dimension::IdList dims = ctx.dims();\n std::sort(dims.begin(), dims.end());\n if (dims.size() < 3 || dims[0] != Dimension::Id::X ||\n dims[1] != Dimension::Id::Y || dims[2] != Dimension::Id::Z)\n {\n throw pdal_error(\"Missing one of dimensions X, Y or Z. \"\n \"Can't write BPF.\");\n }\n\n for (auto id : dims)\n {\n BpfDimension dim;\n dim.m_id = id;\n dim.m_label = ctx.dimName(id);\n m_dims.push_back(dim);\n }\n}\n\n\nvoid BpfWriter::write(const PointBuffer& data)\n{\n setAutoOffset(data);\n\n \/\/ We know that X, Y and Z are dimensions 0, 1 and 2.\n m_dims[0].m_offset = m_xXform.m_offset;\n m_dims[1].m_offset = m_yXform.m_offset;\n m_dims[2].m_offset = m_zXform.m_offset;\n\n switch (m_header.m_pointFormat)\n {\n case BpfFormat::PointMajor:\n writePointMajor(data);\n break;\n case BpfFormat::DimMajor:\n writeDimMajor(data);\n break;\n case BpfFormat::ByteMajor:\n writeByteMajor(data);\n break;\n }\n m_header.m_numPts += data.size();\n}\n\n\nvoid BpfWriter::writePointMajor(const PointBuffer& data)\n{\n \/\/ Blocks of 10,000 points will ensure that we're under 16MB, even\n \/\/ for 255 dimensions.\n size_t blockpoints = std::min(10000UL, data.size());\n\n \/\/ For compression we're going to write to a buffer so that it can be\n \/\/ compressed before it's written to the file stream.\n BpfCompressor compressor(m_stream,\n blockpoints * sizeof(float) * m_dims.size());\n PointId idx = 0;\n while (idx < data.size())\n {\n if (m_header.m_compression)\n compressor.startBlock();\n size_t blockId;\n for (blockId = 0; idx < data.size() && blockId < blockpoints;\n ++idx, ++blockId)\n {\n for (auto & bpfDim : m_dims)\n {\n double d = getAdjustedValue(data, bpfDim, idx);\n m_stream << (float)d;\n }\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n }\n}\n\n\nvoid BpfWriter::writeDimMajor(const PointBuffer& data)\n{\n \/\/ We're going to pretend for now that we only even have one point buffer.\n BpfCompressor compressor(m_stream, data.size() * sizeof(float));\n\n for (auto & bpfDim : m_dims)\n {\n\n if (m_header.m_compression)\n compressor.startBlock();\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n double d = getAdjustedValue(data, bpfDim, idx);\n m_stream << (float)d;\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n }\n}\n\n\nvoid BpfWriter::writeByteMajor(const PointBuffer& data)\n{\n union\n {\n float f;\n uint32_t u32;\n } uu;\n\n \/\/ We're going to pretend for now that we only even have one point buffer.\n\n BpfCompressor compressor(m_stream,\n data.size() * sizeof(float) * m_dims.size());\n\n if (m_header.m_compression)\n compressor.startBlock();\n for (auto & bpfDim : m_dims)\n {\n for (size_t b = 0; b < sizeof(float); b++)\n {\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n uu.f = (float)getAdjustedValue(data, bpfDim, idx);\n uint8_t u8 = (uint8_t)(uu.u32 >> (b * CHAR_BIT));\n m_stream << u8;\n }\n }\n }\n if (m_header.m_compression)\n {\n compressor.compress();\n compressor.finish();\n }\n}\n\n\ndouble BpfWriter::getAdjustedValue(const PointBuffer& buf,\n BpfDimension& bpfDim, PointId idx)\n{\n double d = buf.getFieldAs<double>(bpfDim.m_id, idx);\n bpfDim.m_min = std::min(bpfDim.m_min, d);\n bpfDim.m_max = std::max(bpfDim.m_max, d);\n\n if (bpfDim.m_id == Dimension::Id::X)\n d \/= m_xXform.m_scale;\n else if (bpfDim.m_id == Dimension::Id::Y)\n d \/= m_yXform.m_scale;\n else if (bpfDim.m_id == Dimension::Id::Z)\n d \/= m_zXform.m_scale;\n return (d - bpfDim.m_offset);\n}\n\n\nvoid BpfWriter::done(PointContextRef)\n{\n \/\/ Rewrite the header to update the the correct number of points and\n \/\/ statistics.\n m_stream.seek(0);\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_stream.flush();\n}\n\n} \/\/namespace pdal\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#pragma once\n\n#include <pdal\/Compression.hpp>\n#include <pdal\/FlexWriter.hpp>\n\n#include \"HeaderVal.hpp\"\n#include \"LasError.hpp\"\n#include \"LasHeader.hpp\"\n#include \"LasUtils.hpp\"\n#include \"SummaryData.hpp\"\n#include \"ZipPoint.hpp\"\n\nextern \"C\" int32_t LasWriter_ExitFunc();\nextern \"C\" PF_ExitFunc LasWriter_InitPlugin();\n\nnamespace pdal\n{\nclass LasTester;\nclass NitfWriter;\nclass GeotiffSupport;\n\nstruct VlrOptionInfo\n{\n std::string m_name;\n std::string m_value;\n std::string m_userId;\n uint16_t m_recordId;\n std::string m_description;\n};\n\nclass PDAL_DLL LasWriter : public FlexWriter\n{\n friend class LasTester;\n friend class NitfWriter;\npublic:\n static void * create();\n static int32_t destroy(void *);\n std::string getName() const;\n\n LasWriter();\n\n Options getDefaultOptions();\n\nprotected:\n void prepOutput(std::ostream *out, const SpatialReference& srs);\n void finishOutput();\n\nprivate:\n LasError m_error;\n LasHeader m_lasHeader;\n std::unique_ptr<SummaryData> m_summaryData;\n std::unique_ptr<LASzipper> m_zipper;\n std::unique_ptr<ZipPoint> m_zipPoint;\n std::unique_ptr<LazPerfVlrCompressor> m_compressor;\n bool m_discardHighReturnNumbers;\n std::map<std::string, std::string> m_headerVals;\n std::vector<VlrOptionInfo> m_optionInfos;\n std::ostream *m_ostream;\n std::vector<VariableLengthRecord> m_vlrs;\n std::vector<ExtVariableLengthRecord> m_eVlrs;\n std::vector<ExtraDim> m_extraDims;\n uint16_t m_extraByteLen;\n SpatialReference m_srs;\n std::string m_curFilename;\n std::set<std::string> m_forwards;\n bool m_forwardVlrs;\n LasCompression::Enum m_compression;\n\n NumHeaderVal<uint8_t, 1, 1> m_majorVersion;\n NumHeaderVal<uint8_t, 1, 4> m_minorVersion;\n NumHeaderVal<uint8_t, 0, 10> m_dataformatId;\n \/\/ MSVC doesn't see numeric_limits::max() as constexpr do doesn't allow\n \/\/ it as defaults for templates. Remove when possible.\n NumHeaderVal<uint16_t, 0, 65535> m_filesourceId;\n NumHeaderVal<uint16_t, 0, 15> m_globalEncoding;\n UuidHeaderVal m_projectId;\n StringHeaderVal<32> m_systemId;\n StringHeaderVal<32> m_softwareId;\n NumHeaderVal<uint16_t, 0, 366> m_creationDoy;\n \/\/ MSVC doesn't see numeric_limits::max() as constexpr do doesn't allow\n \/\/ them as defaults for templates. Remove when possible.\n NumHeaderVal<uint16_t, 0, 65535> m_creationYear;\n StringHeaderVal<20> m_scaleX;\n StringHeaderVal<20> m_scaleY;\n StringHeaderVal<20> m_scaleZ;\n StringHeaderVal<20> m_offsetX;\n StringHeaderVal<20> m_offsetY;\n StringHeaderVal<20> m_offsetZ;\n MetadataNode m_forwardMetadata;\n\n virtual void processOptions(const Options& options);\n virtual void prepared(PointTableRef table);\n virtual void readyTable(PointTableRef table);\n virtual void readyFile(const std::string& filename,\n const SpatialReference& srs);\n virtual void writeView(const PointViewPtr view);\n virtual void doneFile();\n\n void fillForwardList(const Options& options);\n void getHeaderOptions(const Options& options);\n template <typename T>\n void handleHeaderForward(const std::string& s, T& headerVal,\n const MetadataNode& base);\n void handleHeaderForwards(MetadataNode& forward);\n void fillHeader();\n point_count_t fillWriteBuf(const PointView& view, PointId startId,\n std::vector<char>& buf);\n void writeLasZipBuf(char *data, size_t pointLen, point_count_t numPts);\n void writeLazPerfBuf(char *data, size_t pointLen, point_count_t numPts);\n void setVlrsFromMetadata(MetadataNode& forward);\n MetadataNode findVlrMetadata(MetadataNode node, uint16_t recordId,\n const std::string& userId);\n void setExtraBytesVlr();\n void setVlrsFromSpatialRef();\n void readyCompression();\n void readyLasZipCompression();\n void readyLazPerfCompression();\n void openCompression();\n void addVlr(const std::string& userId, uint16_t recordId,\n const std::string& description, std::vector<uint8_t>& data);\n void deleteVlr(const std::string& userId, uint16_t recordId);\n void addGeotiffVlrs();\n void addGeotiffVlr(GeotiffSupport& geotiff, uint16_t recordId,\n const std::string& description);\n bool addWktVlr();\n void finishLasZipOutput();\n void finishLazPerfOutput();\n\n LasWriter& operator=(const LasWriter&); \/\/ not implemented\n LasWriter(const LasWriter&); \/\/ not implemented\n};\n\n} \/\/ namespace pdal\n<commit_msg>Valid global_encoding values can go up to 31. Close #1064<commit_after>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#pragma once\n\n#include <pdal\/Compression.hpp>\n#include <pdal\/FlexWriter.hpp>\n\n#include \"HeaderVal.hpp\"\n#include \"LasError.hpp\"\n#include \"LasHeader.hpp\"\n#include \"LasUtils.hpp\"\n#include \"SummaryData.hpp\"\n#include \"ZipPoint.hpp\"\n\nextern \"C\" int32_t LasWriter_ExitFunc();\nextern \"C\" PF_ExitFunc LasWriter_InitPlugin();\n\nnamespace pdal\n{\nclass LasTester;\nclass NitfWriter;\nclass GeotiffSupport;\n\nstruct VlrOptionInfo\n{\n std::string m_name;\n std::string m_value;\n std::string m_userId;\n uint16_t m_recordId;\n std::string m_description;\n};\n\nclass PDAL_DLL LasWriter : public FlexWriter\n{\n friend class LasTester;\n friend class NitfWriter;\npublic:\n static void * create();\n static int32_t destroy(void *);\n std::string getName() const;\n\n LasWriter();\n\n Options getDefaultOptions();\n\nprotected:\n void prepOutput(std::ostream *out, const SpatialReference& srs);\n void finishOutput();\n\nprivate:\n LasError m_error;\n LasHeader m_lasHeader;\n std::unique_ptr<SummaryData> m_summaryData;\n std::unique_ptr<LASzipper> m_zipper;\n std::unique_ptr<ZipPoint> m_zipPoint;\n std::unique_ptr<LazPerfVlrCompressor> m_compressor;\n bool m_discardHighReturnNumbers;\n std::map<std::string, std::string> m_headerVals;\n std::vector<VlrOptionInfo> m_optionInfos;\n std::ostream *m_ostream;\n std::vector<VariableLengthRecord> m_vlrs;\n std::vector<ExtVariableLengthRecord> m_eVlrs;\n std::vector<ExtraDim> m_extraDims;\n uint16_t m_extraByteLen;\n SpatialReference m_srs;\n std::string m_curFilename;\n std::set<std::string> m_forwards;\n bool m_forwardVlrs;\n LasCompression::Enum m_compression;\n\n NumHeaderVal<uint8_t, 1, 1> m_majorVersion;\n NumHeaderVal<uint8_t, 1, 4> m_minorVersion;\n NumHeaderVal<uint8_t, 0, 10> m_dataformatId;\n \/\/ MSVC doesn't see numeric_limits::max() as constexpr do doesn't allow\n \/\/ it as defaults for templates. Remove when possible.\n NumHeaderVal<uint16_t, 0, 65535> m_filesourceId;\n NumHeaderVal<uint16_t, 0, 31> m_globalEncoding;\n UuidHeaderVal m_projectId;\n StringHeaderVal<32> m_systemId;\n StringHeaderVal<32> m_softwareId;\n NumHeaderVal<uint16_t, 0, 366> m_creationDoy;\n \/\/ MSVC doesn't see numeric_limits::max() as constexpr do doesn't allow\n \/\/ them as defaults for templates. Remove when possible.\n NumHeaderVal<uint16_t, 0, 65535> m_creationYear;\n StringHeaderVal<20> m_scaleX;\n StringHeaderVal<20> m_scaleY;\n StringHeaderVal<20> m_scaleZ;\n StringHeaderVal<20> m_offsetX;\n StringHeaderVal<20> m_offsetY;\n StringHeaderVal<20> m_offsetZ;\n MetadataNode m_forwardMetadata;\n\n virtual void processOptions(const Options& options);\n virtual void prepared(PointTableRef table);\n virtual void readyTable(PointTableRef table);\n virtual void readyFile(const std::string& filename,\n const SpatialReference& srs);\n virtual void writeView(const PointViewPtr view);\n virtual void doneFile();\n\n void fillForwardList(const Options& options);\n void getHeaderOptions(const Options& options);\n template <typename T>\n void handleHeaderForward(const std::string& s, T& headerVal,\n const MetadataNode& base);\n void handleHeaderForwards(MetadataNode& forward);\n void fillHeader();\n point_count_t fillWriteBuf(const PointView& view, PointId startId,\n std::vector<char>& buf);\n void writeLasZipBuf(char *data, size_t pointLen, point_count_t numPts);\n void writeLazPerfBuf(char *data, size_t pointLen, point_count_t numPts);\n void setVlrsFromMetadata(MetadataNode& forward);\n MetadataNode findVlrMetadata(MetadataNode node, uint16_t recordId,\n const std::string& userId);\n void setExtraBytesVlr();\n void setVlrsFromSpatialRef();\n void readyCompression();\n void readyLasZipCompression();\n void readyLazPerfCompression();\n void openCompression();\n void addVlr(const std::string& userId, uint16_t recordId,\n const std::string& description, std::vector<uint8_t>& data);\n void deleteVlr(const std::string& userId, uint16_t recordId);\n void addGeotiffVlrs();\n void addGeotiffVlr(GeotiffSupport& geotiff, uint16_t recordId,\n const std::string& description);\n bool addWktVlr();\n void finishLasZipOutput();\n void finishLazPerfOutput();\n\n LasWriter& operator=(const LasWriter&); \/\/ not implemented\n LasWriter(const LasWriter&); \/\/ not implemented\n};\n\n} \/\/ namespace pdal\n<|endoftext|>"} {"text":"<commit_before>#include <taichi\/lang.h>\n#include <taichi\/util.h>\n#include <taichi\/visual\/gui.h>\n#include <taichi\/system\/profiler.h>\n#include <taichi\/visualization\/particle_visualization.h>\n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nconstexpr int n = 256;\n\nconstexpr int num_ch1 = 16, num_ch2 = 16;\n\nauto cnn = [](std::vector<std::string> cli_param) {\n CoreState::set_trigger_gdb_when_crash(true);\n auto param = parse_param(cli_param);\n auto gpu = param.get(\"gpu\", true);\n auto opt = param.get(\"opt\", true);\n auto use_dense = param.get(\"use_dense\", false);\n auto write_input_voxel = param.get(\"write_input\", true);\n TC_P(use_dense);\n\n Program prog(gpu ? Arch::gpu : Arch::x86_64);\n prog.config.simplify_before_lower_access = opt;\n prog.config.lower_access = opt;\n prog.config.simplify_after_lower_access = opt;\n \/\/ prog.config.print_ir = true;\n\n \/\/ constexpr int dim = 3;\n\n int block_size = gpu ? 4 : 8;\n\n Global(layer1, f32);\n Global(layer2, f32);\n Global(weights, f32);\n\n layout([&]() {\n auto ijkl = Indices(0, 1, 2, 3);\n if (use_dense) {\n root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);\n root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);\n } else {\n root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n .bitmasked()\n .dense(ijkl, {block_size, block_size, block_size, num_ch1})\n .place(layer1);\n root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n .bitmasked()\n .dense(ijkl, {block_size, block_size, block_size, num_ch2})\n .place(layer2);\n }\n root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);\n });\n\n auto tex = create_instance<Texture>(\n \"mesh\", Dict()\n .set(\"resolution\", Vector3(n))\n .set(\"translate\", Vector3(0.55, 0.35, 0.47))\n .set(\"scale\", Vector3(0.5))\n .set(\"adaptive\", false)\n .set(\"filename\", \"$mpm\/bunny_small.obj\"));\n float *in_data = new float[num_ch1 * n * n * n];\n memset(in_data, 0, sizeof(float) * num_ch1 * n * n * n);\n int count = 0;\n for (int i = 1; i < n - 2; i++) {\n for (int j = 1; j < n - 2; j++) {\n for (int k = 1; k < n - 2; k++) {\n bool inside = tex->sample((Vector3(0.5f) + Vector3(i, j, k)) *\n Vector3(1.0f \/ (n - 1)))\n .x > 0.5f;\n \/\/ inside = pow<2>(i - n \/ 2) + pow<2>(k - n \/ 2) < pow<2>(n \/ 2) \/ 2;\n \/\/ inside = i < n * 0.8 && j < n * 0.8 && k < n * 0.8;\n if (inside) {\n for (int c = 0; c < num_ch1; c++) {\n in_data[c * n * n * n + k * n * n + j * n + i] = 1.f;\n layer1.val<float32>(i, j, k, c) = 1.f;\n count++;\n }\n }\n }\n }\n }\n std::cout << \"non_zero:\" << count << \", total:\" << (num_ch1 * n * n * n)\n << std::endl;\n if (write_input_voxel) {\n auto f = fopen(\"bunny_sparse.bin\", \"wb\");\n fwrite(in_data, sizeof(float), num_ch1 * n * n * n, f);\n fclose(f);\n }\n\n Kernel(forward).def([&] {\n \/\/ Cache(0, layer1);\n bool use_cache = false;\n if (opt && gpu) {\n use_cache = true;\n CacheL1(weights);\n }\n if (!gpu) {\n Parallelize(8);\n Vectorize(block_size);\n } else {\n BlockDim(256);\n }\n For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {\n auto sum = Var(0.0f);\n for (int c_in = 0; c_in < num_ch1; c_in++) {\n for (int dx = -1; dx < 2; dx++) {\n for (int dy = -1; dy < 2; dy++) {\n for (int dz = -1; dz < 2; dz++) {\n auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),\n c_in * num_ch2 + c_out];\n auto c_in2 = use_cache ? AssumeInRange(c_in, c_out, 0, 1) : c_in;\n sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];\n \/\/ layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +\n \/\/ dz, c_in];\n }\n }\n }\n }\n layer2[i, j, k, c_out] = sum;\n });\n });\n\n \/\/ expand blocks\n kernel([&] {\n if (!gpu) {\n Parallelize(8);\n \/\/ Vectorize(block_size);\n } else {\n BlockDim(256);\n }\n\n kernel_name(\"dilate\");\n For(layer1, [&](Expr i, Expr j, Expr k) {\n If(i % block_size == 0 && j % block_size == 0 && k % block_size == 0)\n .Then([&] {\n for (int x = -1; x < 2; x++) {\n for (int y = -1; y < 2; y++) {\n for (int z = -1; z < 2; z++) {\n layer2[i + x * block_size, j + y * block_size,\n k + z * block_size, 0] =\n 0.0f; \/\/ simply activate the block\n }\n }\n }\n });\n });\n })();\n\n for (int c_out = 0; c_out < num_ch2; c_out++) {\n for (int c_in = 0; c_in < num_ch1; c_in++) {\n float inc = 0.1f;\n for (int dx = -1; dx < 2; dx++) {\n for (int dy = -1; dy < 2; dy++) {\n for (int dz = -1; dz < 2; dz++) {\n if (dx == 0 && dy == 0 && dz == 0)\n weights.val<float32>(dx + 1, dy + 1, dz + 1,\n c_in * num_ch2 + c_out) = inc;\n inc += 0.1f;\n }\n }\n }\n }\n }\n\n \/\/ prog.config.print_ir = true;\n for (int i = 0; i < 50; i++) {\n forward();\n }\n prog.profiler_print();\n\n \/\/ Write the first layer of output\n float *data = new float[(n - 2) * (n - 2) * (n - 2)];\n int non_zero = 0;\n int zero = 0;\n for (int i = 1; i < (n - 1); i++) {\n for (int j = 1; j < (n - 1); j++) {\n for (int k = 1; k < (n - 1); k++) {\n data[((0 * (n - 2) + (k - 1)) * (n - 2) + (j - 1)) * (n - 2) +\n (i - 1)] = layer2.val<float32>(i, j, k, 0);\n if (layer2.val<float32>(i, j, k, 0) != 0) {\n non_zero++;\n } else {\n zero++;\n }\n }\n }\n }\n std::cout << \"Non zero:\" << non_zero << \", zero:\" << zero << std::endl;\n std::cerr << \"Sparsity:\" << (double)non_zero \/ (double)(non_zero + zero)\n << std::endl;\n auto f_out = fopen(\"our_bunny.bin\", \"wb\");\n fwrite(data, sizeof(float), (n - 2) * (n - 2) * (n - 2), f_out);\n fclose(f_out);\n\n#if 0\n int gui_res = 512;\n GUI gui(\"Sparse CNN\", Vector2i(gui_res + 200, gui_res), false);\n int layer = 1;\n int k = 0;\n int channel = 0;\n gui.slider(\"z\", k, 0, n - 1)\n .slider(\"Layer\", layer, 1, 2)\n .slider(\"Channel\", channel, 0, num_ch1);\n\n int scale = gui_res \/ n;\n auto &canvas = gui.get_canvas();\n for (int frame = 1;; frame++) {\n for (int i = 0; i < gui_res - scale; i++) {\n for (int j = 0; j < gui_res - scale; j++) {\n real dx;\n if (layer == 1) {\n dx = layer1.val<float32>(i \/ scale, j \/ scale, k, channel);\n } else {\n dx = layer2.val<float32>(i \/ scale, j \/ scale, k, channel);\n }\n canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;\n }\n }\n gui.update();\n }\n#endif\n};\nTC_REGISTER_TASK(cnn);\n\nTC_NAMESPACE_END\n<commit_msg>explicit cache_l1 hint for cnn<commit_after>#include <taichi\/lang.h>\n#include <taichi\/util.h>\n#include <taichi\/visual\/gui.h>\n#include <taichi\/system\/profiler.h>\n#include <taichi\/visualization\/particle_visualization.h>\n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nconstexpr int n = 256;\n\nconstexpr int num_ch1 = 16, num_ch2 = 16;\n\nauto cnn = [](std::vector<std::string> cli_param) {\n CoreState::set_trigger_gdb_when_crash(true);\n auto param = parse_param(cli_param);\n auto gpu = param.get(\"gpu\", true);\n auto opt = param.get(\"opt\", true);\n auto cache_l1 = param.get(\"cache_l1\", true);\n auto use_dense = param.get(\"use_dense\", false);\n auto write_input_voxel = param.get(\"write_input\", true);\n TC_P(use_dense);\n\n Program prog(gpu ? Arch::gpu : Arch::x86_64);\n prog.config.simplify_before_lower_access = opt;\n prog.config.lower_access = opt;\n prog.config.simplify_after_lower_access = opt;\n \/\/ prog.config.print_ir = true;\n\n \/\/ constexpr int dim = 3;\n\n int block_size = gpu ? 4 : 8;\n\n Global(layer1, f32);\n Global(layer2, f32);\n Global(weights, f32);\n\n layout([&]() {\n auto ijkl = Indices(0, 1, 2, 3);\n if (use_dense) {\n root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);\n root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);\n } else {\n root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n .bitmasked()\n .dense(ijkl, {block_size, block_size, block_size, num_ch1})\n .place(layer1);\n root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n .bitmasked()\n .dense(ijkl, {block_size, block_size, block_size, num_ch2})\n .place(layer2);\n }\n root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);\n });\n\n auto tex = create_instance<Texture>(\n \"mesh\", Dict()\n .set(\"resolution\", Vector3(n))\n .set(\"translate\", Vector3(0.55, 0.35, 0.47))\n .set(\"scale\", Vector3(0.5))\n .set(\"adaptive\", false)\n .set(\"filename\", \"$mpm\/bunny_small.obj\"));\n float *in_data = new float[num_ch1 * n * n * n];\n memset(in_data, 0, sizeof(float) * num_ch1 * n * n * n);\n int count = 0;\n for (int i = 1; i < n - 2; i++) {\n for (int j = 1; j < n - 2; j++) {\n for (int k = 1; k < n - 2; k++) {\n bool inside = tex->sample((Vector3(0.5f) + Vector3(i, j, k)) *\n Vector3(1.0f \/ (n - 1)))\n .x > 0.5f;\n \/\/ inside = pow<2>(i - n \/ 2) + pow<2>(k - n \/ 2) < pow<2>(n \/ 2) \/ 2;\n \/\/ inside = i < n * 0.8 && j < n * 0.8 && k < n * 0.8;\n if (inside) {\n for (int c = 0; c < num_ch1; c++) {\n in_data[c * n * n * n + k * n * n + j * n + i] = 1.f;\n layer1.val<float32>(i, j, k, c) = 1.f;\n count++;\n }\n }\n }\n }\n }\n std::cout << \"non_zero:\" << count << \", total:\" << (num_ch1 * n * n * n)\n << std::endl;\n if (write_input_voxel) {\n auto f = fopen(\"bunny_sparse.bin\", \"wb\");\n fwrite(in_data, sizeof(float), num_ch1 * n * n * n, f);\n fclose(f);\n }\n\n Kernel(forward).def([&] {\n bool use_cache = false;\n if (opt && gpu) {\n use_cache = true;\n if (cache_l1)\n CacheL1(weights);\n }\n if (!gpu) {\n Parallelize(8);\n Vectorize(block_size);\n } else {\n BlockDim(256);\n }\n For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {\n auto sum = Var(0.0f);\n for (int c_in = 0; c_in < num_ch1; c_in++) {\n for (int dx = -1; dx < 2; dx++) {\n for (int dy = -1; dy < 2; dy++) {\n for (int dz = -1; dz < 2; dz++) {\n auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),\n c_in * num_ch2 + c_out];\n auto c_in2 = use_cache ? AssumeInRange(c_in, c_out, 0, 1) : c_in;\n sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];\n \/\/ layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +\n \/\/ dz, c_in];\n }\n }\n }\n }\n layer2[i, j, k, c_out] = sum;\n });\n });\n\n \/\/ expand blocks\n kernel([&] {\n if (!gpu) {\n Parallelize(8);\n \/\/ Vectorize(block_size);\n } else {\n BlockDim(256);\n }\n\n kernel_name(\"dilate\");\n For(layer1, [&](Expr i, Expr j, Expr k) {\n If(i % block_size == 0 && j % block_size == 0 && k % block_size == 0)\n .Then([&] {\n for (int x = -1; x < 2; x++) {\n for (int y = -1; y < 2; y++) {\n for (int z = -1; z < 2; z++) {\n layer2[i + x * block_size, j + y * block_size,\n k + z * block_size, 0] =\n 0.0f; \/\/ simply activate the block\n }\n }\n }\n });\n });\n })();\n\n for (int c_out = 0; c_out < num_ch2; c_out++) {\n for (int c_in = 0; c_in < num_ch1; c_in++) {\n float inc = 0.1f;\n for (int dx = -1; dx < 2; dx++) {\n for (int dy = -1; dy < 2; dy++) {\n for (int dz = -1; dz < 2; dz++) {\n if (dx == 0 && dy == 0 && dz == 0)\n weights.val<float32>(dx + 1, dy + 1, dz + 1,\n c_in * num_ch2 + c_out) = inc;\n inc += 0.1f;\n }\n }\n }\n }\n }\n\n \/\/ prog.config.print_ir = true;\n for (int i = 0; i < 50; i++) {\n forward();\n }\n prog.profiler_print();\n\n \/\/ Write the first layer of output\n float *data = new float[(n - 2) * (n - 2) * (n - 2)];\n int non_zero = 0;\n int zero = 0;\n for (int i = 1; i < (n - 1); i++) {\n for (int j = 1; j < (n - 1); j++) {\n for (int k = 1; k < (n - 1); k++) {\n data[((0 * (n - 2) + (k - 1)) * (n - 2) + (j - 1)) * (n - 2) +\n (i - 1)] = layer2.val<float32>(i, j, k, 0);\n if (layer2.val<float32>(i, j, k, 0) != 0) {\n non_zero++;\n } else {\n zero++;\n }\n }\n }\n }\n std::cout << \"Non zero:\" << non_zero << \", zero:\" << zero << std::endl;\n std::cerr << \"Sparsity:\" << (double)non_zero \/ (double)(non_zero + zero)\n << std::endl;\n auto f_out = fopen(\"our_bunny.bin\", \"wb\");\n fwrite(data, sizeof(float), (n - 2) * (n - 2) * (n - 2), f_out);\n fclose(f_out);\n\n#if 0\n int gui_res = 512;\n GUI gui(\"Sparse CNN\", Vector2i(gui_res + 200, gui_res), false);\n int layer = 1;\n int k = 0;\n int channel = 0;\n gui.slider(\"z\", k, 0, n - 1)\n .slider(\"Layer\", layer, 1, 2)\n .slider(\"Channel\", channel, 0, num_ch1);\n\n int scale = gui_res \/ n;\n auto &canvas = gui.get_canvas();\n for (int frame = 1;; frame++) {\n for (int i = 0; i < gui_res - scale; i++) {\n for (int j = 0; j < gui_res - scale; j++) {\n real dx;\n if (layer == 1) {\n dx = layer1.val<float32>(i \/ scale, j \/ scale, k, channel);\n } else {\n dx = layer2.val<float32>(i \/ scale, j \/ scale, k, channel);\n }\n canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;\n }\n }\n gui.update();\n }\n#endif\n};\nTC_REGISTER_TASK(cnn);\n\nTC_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n* Copyright (c) 1993 - 2008 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <sstream>\n#include \"plugin_files.h\"\n#include \"plugin_utils.h\"\n\n\n\n#ifdef _WIN32\n#define _DirDelim '\\\\'\n\n#define WIN32_LEAN_AND_MEAN\t\t\/\/ Exclude rarely-used stuff from Windows headers\n#include <windows.h>\n#include <io.h>\n#include <direct.h>\n\nbool WindowsAddFileStack ( const char *szPathName, const char* fileMask, bool bRecursive,std::vector<std::string> &list, bool justDirs = false )\n{\n struct _finddata_t fileInfo;\n\n long\t\thFile;\n std::string searchstr;\n\n std::string FilePath;\n\n bool\tbDone = false;\n\n searchstr = szPathName;\n searchstr += \"\\\\\";\n if (bRecursive)\n searchstr += \"*.*\";\n else if (fileMask)\n searchstr += fileMask;\n else\n searchstr += \"*.*\";\n\n std::string extenstionSearch;\n\n if ( fileMask && strchr(fileMask,'.'))\n extenstionSearch = strchr(fileMask,'.')+1;\n\n hFile = (long)_findfirst(searchstr.c_str(),&fileInfo);\n\n if (hFile != -1)\n {\n while (!bDone)\n {\n if ((strlen(fileInfo.name) >0) && (strcmp(fileInfo.name,\".\") != 0) && \n\t(strcmp(fileInfo.name,\"..\") != 0))\n {\n\tFilePath = szPathName;\n\t\/\/if (!(fileInfo.attrib & _A_SUBDIR ))\n\t FilePath += \"\\\\\";\n\tFilePath += fileInfo.name;\n\n\tif (justDirs && (fileInfo.attrib & _A_SUBDIR ))\t\/\/ we neever do just dirs recrusively\n\t list.push_back(FilePath);\n\telse if (!justDirs)\n\t{\n\t if ( (fileInfo.attrib & _A_SUBDIR ) && bRecursive)\n\t WindowsAddFileStack(FilePath.c_str(),fileMask,bRecursive,list);\n\t else if (!(fileInfo.attrib & _A_SUBDIR) )\n\t {\n\t if (bRecursive && fileMask)\t\/\/ if we are recusive we need to check extension manualy, so we get dirs and stuf\n\t {\n\t if (strrchr(FilePath.c_str(),'.'))\n\t {\n\t\tif ( stricmp(strrchr(FilePath.c_str(),'.')+1, extenstionSearch.c_str() ) == 0 )\n\t\t list.push_back(FilePath);\n\t }\n\t }\n\t else\n\t list.push_back(FilePath);\n\t }\n\t}\n }\n if (_findnext(hFile,&fileInfo) == -1)\n\tbDone = true;\n }\n }\n return true;\n}\n#else\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <ctype.h>\n\n#define _DirDelim '\/'\nstatic int match_multi (const char **mask, const char **string)\n{\n const char *msk;\n const char *str;\n const char *msktop;\n const char *strtop;\n\n msk = *mask;\n str = *string;\n\n while ((*msk != '\\0') && (*msk == '*'))\n msk++; \/* get rid of multiple '*'s *\/\n\n if (*msk == '\\0')\t\t\t\t\/* '*' was last, auto-match *\/\n return +1;\n\n msktop = msk;\n strtop = str;\n\n while (*msk != '\\0')\n {\n if (*msk == '*')\n {\n *mask = msk;\n *string = str;\n return 0; \/* matched this segment *\/\n }\n else if (*str == '\\0')\n return -1; \/* can't match *\/\n else\n {\n if ((*msk == '?') || (*msk == *str))\n {\n\tmsk++;\n\tstr++;\n\tif ((*msk == '\\0') && (*str != '\\0'))\t\/* advanced check *\/\n\t{\t\t\t\t\t\t\t\t\t\t\n\t str++;\n\t strtop++;\n\t str = strtop;\n\t msk = msktop;\n\t}\n }\n else\n {\n\tstr++;\n\tstrtop++;\n\tstr = strtop;\n\tmsk = msktop;\n }\n }\n }\n\n *mask = msk;\n *string = str;\n return +1;\t\t\t\t\t\t\t\t\t\t\t \/* full match *\/\n}\n\nstatic int match_mask (const char *mask, const char *string)\n{ \n if (mask == NULL)\n return 0;\n\n if (string == NULL)\n return 0;\n\n if ((mask[0] == '*') && (mask[1] == '\\0'))\n return 1;\t\t\t\t\t\t\t\t\t\/* instant match *\/\n\n while (*mask != '\\0')\n {\n if (*mask == '*')\n {\n mask++;\n switch (match_multi (&mask, &string))\n {\n case +1:\n\treturn 1;\n case -1:\n\treturn 0;\n }\n }\n else if (*string == '\\0')\n return 0;\n else if ((*mask == '?') || (*mask == *string))\n {\n mask++;\n string++;\n }\n else\n return 0;\n }\n\n if (*string == '\\0')\n return 1;\n else\n return 0;\n}\n\nbool LinuxAddFileStack ( const char *szPathName, const char* fileMask, bool bRecursive, std::vector<std::string> &list, bool justDirs = false )\n{\n DIR\t*directory;\n dirent\t*fileInfo;\n struct stat\tstatbuf;\n char\tsearchstr[1024];\n std::string\tFilePath;\n\n strcpy(searchstr, szPathName);\n if (searchstr[strlen(searchstr) - 1] != '\/')\n strcat(searchstr, \"\/\");\n directory = opendir(searchstr);\n if (!directory)\n return false;\n\n \/\/ TODO: make it use the filemask\n while ((fileInfo = readdir(directory)))\n {\n if (!((strcmp(fileInfo->d_name, \".\") == 0) || (strcmp(fileInfo->d_name, \"..\") == 0)))\n {\n FilePath = searchstr;\n FilePath += fileInfo->d_name;\n\n\n stat(FilePath.c_str(), &statbuf);\n\n if (justDirs && S_ISDIR(statbuf.st_mode))\t\/\/ we never do just dirs recrusively\n\tlist.push_back(FilePath);\n else if (!justDirs)\n {\n\tif (S_ISDIR(statbuf.st_mode) && bRecursive)\n\t LinuxAddFileStack(FilePath.c_str(),fileMask,bRecursive, list);\n\telse if (match_mask (fileMask, fileInfo->d_name))\n\t list.push_back(FilePath);\n }\n }\n }\n closedir(directory);\n return true;\n}\n#endif \n\nstd::string convertPathToDelims ( const char* file ) \/\/ ensures all the delims are constant\n{\n if (!file)\n return std::string();\n\n std::string delim;\n delim += _DirDelim;\n return replace_all(replace_all(file,\"\/\",delim),\"\\\\\",delim);\n}\n\nstd::vector<std::string> getFilesInDir ( const char* dir, const char* filter, bool recrusive )\n{\n std::vector<std::string> list;\n if (!dir)\n return list;\n\n std::string realFilter = \"*.*\";\n if ( filter )\n realFilter = filter;\n\n std::string directory = convertPathToDelims(dir);\n\n#ifdef _WIN32\n WindowsAddFileStack (directory.c_str(), realFilter.c_str(),recrusive,list);\n#else\n LinuxAddFileStack(directory.c_str(), realFilter.c_str(),recrusive,list);\n#endif\n return list;\n}\n\nstd::vector<std::string> getDirsInDir ( const char* dir)\n{\n std::vector<std::string> list;\n if (!dir)\n return list;\n\n std::string directory = convertPathToDelims(dir);\n\n#ifdef _WIN32\n WindowsAddFileStack (directory.c_str(), \"*.*\",false,list,true);\n#else\n LinuxAddFileStack (directory.c_str(), \"*.*\",false,list,true);\n#endif\n return list;\n}\n\nstd::string getPathForOS ( const char* file )\n{\n return convertPathToDelims(file);\n}\n\nstd::string getFileDir ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n \n char *p = (char*)strrchr(f.c_str(),_DirDelim);\n if (p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n *(p+1) = 0;\n\n return std::string(f.c_str());\n}\n\nstd::string getFileExtension ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n\n char *p = (char*)strrchr(f.c_str(),'.');\n if (!p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n return std::string();\n\n return std::string(p+1);\n}\n\nstd::string getFileTitle ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n\n std::string temp = f;\n\n const char *p = strrchr(f.c_str(),_DirDelim);\n if (p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n temp = p+1;\n\n char *p2 = (char*)strrchr(temp.c_str(),'.');\n if (p2)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n *(p2+1) = 0;\n\n return std::string(temp.c_str());\n}\n\nstd::string getFileText ( const char* file )\n{\n std::string text;\n if (!file)\n return text;\n\n FILE *fp = fopen(convertPathToDelims(file).c_str(),\"rb\");\n if (!fp)\n return text;\n\n fseek(fp,0,SEEK_END);\n unsigned int i = (unsigned int)ftell(fp);\n fseek(fp,0,SEEK_SET);\n\n char *temp = (char*)malloc(i+1);\n fread(temp,i,1,fp);\n temp[i] = 0;\n text = temp;\n free(temp);\n fclose(fp);\n\n return replace_all(text,\"\\r\",std::string());\n}\n\nstd::vector<std::string> getFileTextLines ( const char* file )\n{\n return tokenize(getFileText(file),\"\\n\",0,false);\n}\n\nunsigned int getFileLen ( const char* file )\n{\n if (!file)\n return 0;\n\n FILE *fp = fopen(convertPathToDelims(file).c_str(),\"rb\");\n if (!fp)\n return 0;\n\n fseek(fp,0,SEEK_END);\n unsigned int i = (unsigned int)ftell(fp);\n fclose(fp);\n\n return i;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>use compare_nocase instead of stricmp<commit_after>\/* bzflag\n* Copyright (c) 1993 - 2008 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <sstream>\n#include \"plugin_files.h\"\n#include \"plugin_utils.h\"\n\n\n\n#ifdef _WIN32\n#define _DirDelim '\\\\'\n\n#define WIN32_LEAN_AND_MEAN\t\t\/\/ Exclude rarely-used stuff from Windows headers\n#include <windows.h>\n#include <io.h>\n#include <direct.h>\n\nbool WindowsAddFileStack ( const char *szPathName, const char* fileMask, bool bRecursive,std::vector<std::string> &list, bool justDirs = false )\n{\n struct _finddata_t fileInfo;\n\n long\t\thFile;\n std::string searchstr;\n\n std::string FilePath;\n\n bool\tbDone = false;\n\n searchstr = szPathName;\n searchstr += \"\\\\\";\n if (bRecursive)\n searchstr += \"*.*\";\n else if (fileMask)\n searchstr += fileMask;\n else\n searchstr += \"*.*\";\n\n std::string extenstionSearch;\n\n if ( fileMask && strchr(fileMask,'.'))\n extenstionSearch = strchr(fileMask,'.')+1;\n\n hFile = (long)_findfirst(searchstr.c_str(),&fileInfo);\n\n if (hFile != -1)\n {\n while (!bDone)\n {\n if ((strlen(fileInfo.name) >0) && (strcmp(fileInfo.name,\".\") != 0) && \n\t(strcmp(fileInfo.name,\"..\") != 0))\n {\n\tFilePath = szPathName;\n\t\/\/if (!(fileInfo.attrib & _A_SUBDIR ))\n\t FilePath += \"\\\\\";\n\tFilePath += fileInfo.name;\n\n\tif (justDirs && (fileInfo.attrib & _A_SUBDIR ))\t\/\/ we neever do just dirs recrusively\n\t list.push_back(FilePath);\n\telse if (!justDirs)\n\t{\n\t if ( (fileInfo.attrib & _A_SUBDIR ) && bRecursive)\n\t WindowsAddFileStack(FilePath.c_str(),fileMask,bRecursive,list);\n\t else if (!(fileInfo.attrib & _A_SUBDIR) )\n\t {\n\t if (bRecursive && fileMask)\t\/\/ if we are recusive we need to check extension manualy, so we get dirs and stuf\n\t {\n\t if (strrchr(FilePath.c_str(),'.'))\n\t {\n\t\tif ( compare_nocase(std::string(strrchr(FilePath.c_str(),'.')+1), extenstionSearch ) == 0 )\n\t\t list.push_back(FilePath);\n\t }\n\t }\n\t else\n\t list.push_back(FilePath);\n\t }\n\t}\n }\n if (_findnext(hFile,&fileInfo) == -1)\n\tbDone = true;\n }\n }\n return true;\n}\n#else\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <ctype.h>\n\n#define _DirDelim '\/'\nstatic int match_multi (const char **mask, const char **string)\n{\n const char *msk;\n const char *str;\n const char *msktop;\n const char *strtop;\n\n msk = *mask;\n str = *string;\n\n while ((*msk != '\\0') && (*msk == '*'))\n msk++; \/* get rid of multiple '*'s *\/\n\n if (*msk == '\\0')\t\t\t\t\/* '*' was last, auto-match *\/\n return +1;\n\n msktop = msk;\n strtop = str;\n\n while (*msk != '\\0')\n {\n if (*msk == '*')\n {\n *mask = msk;\n *string = str;\n return 0; \/* matched this segment *\/\n }\n else if (*str == '\\0')\n return -1; \/* can't match *\/\n else\n {\n if ((*msk == '?') || (*msk == *str))\n {\n\tmsk++;\n\tstr++;\n\tif ((*msk == '\\0') && (*str != '\\0'))\t\/* advanced check *\/\n\t{\t\t\t\t\t\t\t\t\t\t\n\t str++;\n\t strtop++;\n\t str = strtop;\n\t msk = msktop;\n\t}\n }\n else\n {\n\tstr++;\n\tstrtop++;\n\tstr = strtop;\n\tmsk = msktop;\n }\n }\n }\n\n *mask = msk;\n *string = str;\n return +1;\t\t\t\t\t\t\t\t\t\t\t \/* full match *\/\n}\n\nstatic int match_mask (const char *mask, const char *string)\n{ \n if (mask == NULL)\n return 0;\n\n if (string == NULL)\n return 0;\n\n if ((mask[0] == '*') && (mask[1] == '\\0'))\n return 1;\t\t\t\t\t\t\t\t\t\/* instant match *\/\n\n while (*mask != '\\0')\n {\n if (*mask == '*')\n {\n mask++;\n switch (match_multi (&mask, &string))\n {\n case +1:\n\treturn 1;\n case -1:\n\treturn 0;\n }\n }\n else if (*string == '\\0')\n return 0;\n else if ((*mask == '?') || (*mask == *string))\n {\n mask++;\n string++;\n }\n else\n return 0;\n }\n\n if (*string == '\\0')\n return 1;\n else\n return 0;\n}\n\nbool LinuxAddFileStack ( const char *szPathName, const char* fileMask, bool bRecursive, std::vector<std::string> &list, bool justDirs = false )\n{\n DIR\t*directory;\n dirent\t*fileInfo;\n struct stat\tstatbuf;\n char\tsearchstr[1024];\n std::string\tFilePath;\n\n strcpy(searchstr, szPathName);\n if (searchstr[strlen(searchstr) - 1] != '\/')\n strcat(searchstr, \"\/\");\n directory = opendir(searchstr);\n if (!directory)\n return false;\n\n \/\/ TODO: make it use the filemask\n while ((fileInfo = readdir(directory)))\n {\n if (!((strcmp(fileInfo->d_name, \".\") == 0) || (strcmp(fileInfo->d_name, \"..\") == 0)))\n {\n FilePath = searchstr;\n FilePath += fileInfo->d_name;\n\n\n stat(FilePath.c_str(), &statbuf);\n\n if (justDirs && S_ISDIR(statbuf.st_mode))\t\/\/ we never do just dirs recrusively\n\tlist.push_back(FilePath);\n else if (!justDirs)\n {\n\tif (S_ISDIR(statbuf.st_mode) && bRecursive)\n\t LinuxAddFileStack(FilePath.c_str(),fileMask,bRecursive, list);\n\telse if (match_mask (fileMask, fileInfo->d_name))\n\t list.push_back(FilePath);\n }\n }\n }\n closedir(directory);\n return true;\n}\n#endif \n\nstd::string convertPathToDelims ( const char* file ) \/\/ ensures all the delims are constant\n{\n if (!file)\n return std::string();\n\n std::string delim;\n delim += _DirDelim;\n return replace_all(replace_all(file,\"\/\",delim),\"\\\\\",delim);\n}\n\nstd::vector<std::string> getFilesInDir ( const char* dir, const char* filter, bool recrusive )\n{\n std::vector<std::string> list;\n if (!dir)\n return list;\n\n std::string realFilter = \"*.*\";\n if ( filter )\n realFilter = filter;\n\n std::string directory = convertPathToDelims(dir);\n\n#ifdef _WIN32\n WindowsAddFileStack (directory.c_str(), realFilter.c_str(),recrusive,list);\n#else\n LinuxAddFileStack(directory.c_str(), realFilter.c_str(),recrusive,list);\n#endif\n return list;\n}\n\nstd::vector<std::string> getDirsInDir ( const char* dir)\n{\n std::vector<std::string> list;\n if (!dir)\n return list;\n\n std::string directory = convertPathToDelims(dir);\n\n#ifdef _WIN32\n WindowsAddFileStack (directory.c_str(), \"*.*\",false,list,true);\n#else\n LinuxAddFileStack (directory.c_str(), \"*.*\",false,list,true);\n#endif\n return list;\n}\n\nstd::string getPathForOS ( const char* file )\n{\n return convertPathToDelims(file);\n}\n\nstd::string getFileDir ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n \n char *p = (char*)strrchr(f.c_str(),_DirDelim);\n if (p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n *(p+1) = 0;\n\n return std::string(f.c_str());\n}\n\nstd::string getFileExtension ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n\n char *p = (char*)strrchr(f.c_str(),'.');\n if (!p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n return std::string();\n\n return std::string(p+1);\n}\n\nstd::string getFileTitle ( const char* file )\n{\n std::string f = convertPathToDelims(file);\n\n std::string temp = f;\n\n const char *p = strrchr(f.c_str(),_DirDelim);\n if (p)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n temp = p+1;\n\n char *p2 = (char*)strrchr(temp.c_str(),'.');\n if (p2)\t\t\t\t \/\/ it's ok to go one past, cus even if it's the end, that's the NULL char so we can set it to NULL again with out worry\n *(p2+1) = 0;\n\n return std::string(temp.c_str());\n}\n\nstd::string getFileText ( const char* file )\n{\n std::string text;\n if (!file)\n return text;\n\n FILE *fp = fopen(convertPathToDelims(file).c_str(),\"rb\");\n if (!fp)\n return text;\n\n fseek(fp,0,SEEK_END);\n unsigned int i = (unsigned int)ftell(fp);\n fseek(fp,0,SEEK_SET);\n\n char *temp = (char*)malloc(i+1);\n fread(temp,i,1,fp);\n temp[i] = 0;\n text = temp;\n free(temp);\n fclose(fp);\n\n return replace_all(text,\"\\r\",std::string());\n}\n\nstd::vector<std::string> getFileTextLines ( const char* file )\n{\n return tokenize(getFileText(file),\"\\n\",0,false);\n}\n\nunsigned int getFileLen ( const char* file )\n{\n if (!file)\n return 0;\n\n FILE *fp = fopen(convertPathToDelims(file).c_str(),\"rb\");\n if (!fp)\n return 0;\n\n fseek(fp,0,SEEK_END);\n unsigned int i = (unsigned int)ftell(fp);\n fclose(fp);\n\n return i;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <memory>\n#include <cmath>\n\nstruct Car {\n\tstd::vector<int> point_start;\n\tstd::vector<int> point_stop;\n\tstd::vector<int> point_current;\n\n\tCar(std::vector<int> point_start_, std::vector<int> point_stop_): point_start(point_start_), point_stop(point_stop_) {}; \n};\n\nstruct EuclideanDistance {\n\tinline double operator()(std::shared_ptr<Car> car) {\n\t\tconst double x_diff = car->point_current[0] - car->point_stop[0];\n\t\tconst double y_diff = car->point_current[1] - car->point_stop[1];\n\t\tconst double result = std::sqrt(x_diff * x_diff + y_diff * y_diff);\n\t\treturn result;\n\t}\n\t\n};\n\ntemplate <class H> class Map{\n\tprivate:\n\t\tstd::vector<std::shared_ptr<Car>> cars;\n\t\tstd::vector<std::vector<int>> matrix;\n\t\tint rows;\n\t\tint cols;\n\t\tH heuristic;\n\tpublic:\n\t\tMap(int rows_ = 10, int cols_ = 10): rows(rows_), cols(cols_){\n\t\t\tthis->matrix=std::vector<std::vector<int>>(rows, std::vector<int>(cols, 0));\n\t\t};\n\t\tvoid appendCar(std::shared_ptr<Car> car) {\n\t\t\tthis->cars.push_back(car);\n\t\t\tmatrix[car->point_start[0]][car->point_start[1]] = this->cars.size();\n\t\t\tcar->point_current = car->point_start;\n\t\t}\n\n\t\tvoid appendCars(std::vector<std::shared_ptr<Car>> cars){\n\t\t\tthis->cars.insert(this->cars.end(), cars.begin(), cars.end());\n\t\t}\n\t\t\n\t\tvoid print() {\n\t\t\tfor (auto row: matrix) {\n\t\t\t\tfor (auto elem: row) {\n\t\t\t\t\tstd::cout << elem << \" \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t}\n\t\t}\n\t\tstd::vector<std::vector<int>> generate_new_poses(auto point_current) {\n\t\t\tstd::vector<std::vector<int>> new_poses;\n\t\t\tfor (int i = -1; i++; i < 2) {\n\t\t\t\t for (int j = -1; j++; j < 2) {\n\t\t\t\t\tif (i >= 0 && i < this->rows && j >= 0 && j < this->cols) {\n\t\t\t\t \t\tnew_poses.push_back({point_current[0]+i,point_current[1]+j});\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t}\n\t\t\treturn new_poses;\n\t\t}\n\t\tvoid move(int index_car) {\n\t\t}\n\t\t\n\t\t void update() {\n\n\t\t\t for (int index_car = 0; index_car++; index_car < this->cars.size()) {\n\t\t\t\tauto new_poses = generate_new_poses(this->cars[index_car]->point_current);\n\t\t\t\tif (new_poses.size() == 0) {\n\t\t\t\t\tstd::cout<<\"We lost the route\\n\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (auto pose: new_poses) {\n\t\t\t\t\t \/\/this->move(index_car, pose);\n\t\t\t\t\t std::cout << heuristic(this->cars[index_car]) << \"\\n\";\n\t\t\t\t\t \n\t\t\t\t}\n\t\t\t }\n\t\t}\n};\n\nint main () {\n\tint rows = 10;\n\tint cols = 10;\n\t\n\tauto car = std::make_shared<Car>(std::vector{0, 0}, std::vector{5, 5});\n\tauto car2 = std::make_shared<Car>(std::vector{2, 2}, std::vector{7, 7});\n\tauto map = Map<EuclideanDistance>();\n\tmap.appendCar(car);\n\tmap.appendCar(car2);\n\tmap.print();\n\t\n\tint time_clocks = 30;\n\tfor (int val = 0; val < time_clocks; val++) {\n\t\tstd::cout << \"clock time=\"<<val<<\"\\n\";\n\t\tmap.update();\n\t}\n\t\/\/std::for_each(std::begin(matrix), std::end(matrix), [] (auto & v) mutable { for (auto& e: v) std::cin >> e;});\n\n\n}\n<commit_msg>Added function to calculate min distance heuristic<commit_after>#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <memory>\n#include <cmath>\n\nstruct Car {\n\tstd::vector<int> point_start;\n\tstd::vector<int> point_stop;\n\tstd::vector<int> point_current;\n\n\tCar(std::vector<int> point_start_, std::vector<int> point_stop_): point_start(point_start_), point_stop(point_stop_) {}; \n};\n\nstruct EuclideanDistance {\n\tinline double operator()(auto current_pos, auto new_pos) {\n\t\tconst double x_diff = current_pos[0] - new_pos[0];\n\t\tconst double y_diff = current_pos[1] - new_pos[1];\n\t\tconst double result = std::sqrt(x_diff * x_diff + y_diff * y_diff);\n\t\treturn result;\n\t}\n\t\n};\n\ntemplate <class H> class Map{\n\tprivate:\n\t\tstd::vector<std::shared_ptr<Car>> cars;\n\t\tstd::vector<std::vector<int>> matrix;\n\t\tint rows;\n\t\tint cols;\n\t\tH heuristic;\n\tpublic:\n\t\tMap(int rows_ = 10, int cols_ = 10): rows(rows_), cols(cols_){\n\t\t\tthis->matrix=std::vector<std::vector<int>>(rows, std::vector<int>(cols, 0));\n\t\t};\n\t\tvoid appendCar(std::shared_ptr<Car> car) {\n\t\t\tthis->cars.push_back(car);\n\t\t\tmatrix[car->point_start[0]][car->point_start[1]] = this->cars.size();\n\t\t\tcar->point_current = car->point_start;\n\t\t}\n\n\t\tvoid appendCars(std::vector<std::shared_ptr<Car>> cars){\n\t\t\tthis->cars.insert(this->cars.end(), cars.begin(), cars.end());\n\t\t}\n\t\t\n\t\tvoid print() {\n\t\t\tfor (auto row: matrix) {\n\t\t\t\tfor (auto elem: row) {\n\t\t\t\t\tstd::cout << elem << \" \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t}\n\t\t}\n\t\tstd::vector<std::vector<int>> generate_new_poses(auto point_current) {\n\t\t\tstd::vector<std::vector<int>> new_poses;\n\t\t\tfor (int i = -1; i++; i < 2) {\n\t\t\t\t for (int j = -1; j++; j < 2) {\n\t\t\t\t\tif ((point_current[0] + i) >= 0 && (point_current[0] + i) < this->rows && (point_current[1] + j) >= 0 && (point_current[1] + j) < this->cols) {\n\t\t\t\t \t\tnew_poses.push_back({point_current[0]+i,point_current[1]+j});\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t}\n\t\t\treturn new_poses;\n\t\t}\n\t\tvoid move(int index_car) {\n\t\t}\n\t\t void update() {\n\t\t\t for (int index_car = 0; index_car++; index_car < this->cars.size()) {\n\t\t\t\tauto current_pos = this->cars[index_car]->point_current;\n\t\t\t\tauto new_poses = generate_new_poses(current_pos);\n\t\t\t\tif (new_poses.size() == 0) {\n\t\t\t\t\tstd::cout<<\"We lost the route\\n\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tauto min_pos = current_pos;\n\t\t\t\tdouble min_value = -1.;\n\t\t\t\tfor (auto pose: new_poses) {\n\t\t\t\t\t double distanc = heuristic(current_pos, pose);\n\t\t\t\t\t std::cout << distanc << \"\\n\";\n\t\t\t\t\t if (min_value == -1. || distanc < min_value) {\n\t\t\t\t\t \tmin_pos = pose;\n\t\t\t\t\t\tmin_value = distanc;\n\t\t\t\t\t }\n\t\t\t\t\t \n\t\t\t\t}\n\t\t\t }\n\t\t}\n};\n\nint main () {\n\tint rows = 10;\n\tint cols = 10;\n\t\n\tauto car = std::make_shared<Car>(std::vector{0, 0}, std::vector{5, 5});\n\tauto car2 = std::make_shared<Car>(std::vector{2, 2}, std::vector{7, 7});\n\tauto map = Map<EuclideanDistance>();\n\tmap.appendCar(car);\n\tmap.appendCar(car2);\n\tmap.print();\n\t\n\tint time_clocks = 30;\n\tfor (int val = 0; val < time_clocks; val++) {\n\t\tstd::cout << \"clock time=\"<<val<<\"\\n\";\n\t\tmap.update();\n\t}\n\t\/\/std::for_each(std::begin(matrix), std::end(matrix), [] (auto & v) mutable { for (auto& e: v) std::cin >> e;});\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <cmath>\n#include <fstream>\n#include <numeric>\n\n#include \"modules\/prediction\/evaluator\/vehicle\/mlp_evaluator.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/prediction\/common\/prediction_util.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nvoid MLPEvaluator::Clear() {\n obstacle_feature_values_map_.clear();\n}\n\nvoid MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {\n Clear();\n if (obstacle_ptr == nullptr) {\n AERROR << \"Invalid obstacle.\";\n return;\n }\n\n int id = obstacle_ptr->id();\n Feature latest_feature = obstacle_ptr->latest_feature();\n if (!latest_feature.IsInitialized()) {\n ADEBUG << \"Obstacle [\" << id << \"] has no latest feature.\";\n return;\n }\n\n Lane* lane_ptr = latest_feature.mutable_lane();\n if (!latest_feature.has_lane() || lane_ptr == nullptr) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane feature.\";\n return;\n }\n\n LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();\n if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane graph.\";\n return;\n }\n\n if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane sequences.\";\n return;\n }\n\n for (int i = 0;\n i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {\n LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);\n CHECK(lane_sequence_ptr != nullptr);\n ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);\n }\n}\n\nvoid MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,\n LaneSequence* lane_sequence_ptr) {\n feature_values_.clear();\n int id = obstacle_ptr->id();\n std::vector<double> obstacle_feature_values;\n if (obstacle_feature_values_map_.find(id) ==\n obstacle_feature_values_map_.end()) {\n SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);\n } else {\n obstacle_feature_values = obstacle_feature_values_map_[id];\n }\n\n if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {\n ADEBUG << \"Obstacle [\" << id << \"] has fewer than \"\n << \"expected obstacle feature_values \"\n << obstacle_feature_values.size() << \".\";\n return;\n }\n\n std::vector<double> lane_feature_values;\n SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);\n if (lane_feature_values.size() != LANE_FEATURE_SIZE) {\n ADEBUG << \"Obstacle [\" << id << \"] has fewer than \"\n << \"expected lane feature_values\"\n << lane_feature_values.size() << \".\";\n return;\n }\n\n feature_values_.insert(feature_values_.end(),\n lane_feature_values.begin(), lane_feature_values.end());\n feature_values_.insert(feature_values_.end(),\n lane_feature_values.begin(), lane_feature_values.end());\n}\n\nvoid MLPEvaluator::SetObstacleFeatureValues(\n Obstacle* obstacle_ptr, std::vector<double>* feature_values) {\n feature_values->clear();\n feature_values->reserve(OBSTACLE_FEATURE_SIZE);\n\n std::vector<double> thetas;\n std::vector<double> lane_ls;\n std::vector<double> dist_lbs;\n std::vector<double> dist_rbs;\n std::vector<int> lane_types;\n std::vector<double> speeds;\n std::vector<double> timestamps;\n\n double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;\n int count = 0;\n for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {\n const Feature& feature = obstacle_ptr->feature(i);\n if (!feature.IsInitialized()) {\n continue;\n }\n if (apollo::common::math::DoubleCompare(\n feature.timestamp(), duration) < 0) {\n break;\n }\n if (feature.has_lane() && feature.lane().has_lane_feature()) {\n thetas.push_back(feature.lane().lane_feature().angle_diff());\n lane_ls.push_back(feature.lane().lane_feature().lane_l());\n dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());\n dist_rbs.push_back(\n feature.lane().lane_feature().dist_to_right_boundary());\n lane_types.push_back(feature.lane().lane_feature().lane_turn_type());\n timestamps.push_back(feature.timestamp());\n if (FLAGS_enable_kf_tracking) {\n speeds.push_back(feature.t_speed());\n } else {\n speeds.push_back(feature.speed());\n }\n ++count;\n }\n }\n if (count <= 0) {\n return;\n }\n double theta_mean =\n std::accumulate(thetas.begin(), thetas.end(), 0.0) \/ thetas.size();\n double theta_filtered =\n (thetas.size() > 1) ? (thetas[0] + thetas[1]) \/ 2.0 : thetas[0];\n double lane_l_mean =\n std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) \/ lane_ls.size();\n double lane_l_filtered =\n (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) \/ 2.0 : lane_ls[0];\n double speed_mean =\n std::accumulate(speeds.begin(), speeds.end(), 0.0) \/ speeds.size();\n double speed_lateral = sin(theta_filtered) * speed_mean;\n double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;\n double time_to_lb = (abs(speed_lateral) > 0.05)\n ? dist_lbs[0] \/ speed_lateral\n : 20 * dist_lbs[0] * speed_sign;\n double time_to_rb = (abs(speed_lateral) > 0.05)\n ? -1 * dist_rbs[0] \/ speed_lateral\n : -20 * dist_rbs[0] * speed_sign;\n double time_diff = timestamps.front() - timestamps.back();\n double dist_lb_rate = (timestamps.size() > 1)\n ? (dist_lbs.front() - dist_lbs.back()) \/ time_diff\n : 0.0;\n double dist_rb_rate = (timestamps.size() > 1)\n ? (dist_rbs.front() - dist_rbs.back()) \/ time_diff\n : 0.0;\n \/\/ setup obstacle feature values\n feature_values->push_back(theta_filtered);\n feature_values->push_back(theta_mean);\n feature_values->push_back(theta_filtered - theta_mean);\n feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]\n : thetas[0]);\n feature_values->push_back(lane_l_filtered);\n feature_values->push_back(lane_l_mean);\n feature_values->push_back(lane_l_filtered - lane_l_mean);\n feature_values->push_back(speed_mean);\n feature_values->push_back(dist_lbs.front());\n feature_values->push_back(dist_lb_rate);\n feature_values->push_back(time_to_lb);\n feature_values->push_back(dist_rbs.front());\n feature_values->push_back(dist_rb_rate);\n feature_values->push_back(time_to_rb);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0\n \/\/ : 0.0);\n}\n\nvoid MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,\n LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {\n feature_values->clear();\n feature_values->reserve(LANE_FEATURE_SIZE);\n const Feature& feature = obstacle_ptr->latest_feature();\n if (!feature.IsInitialized()) {\n ADEBUG << \"Obstacle [\" << obstacle_ptr->id() << \"] has no latest feature.\";\n return;\n } else if (!feature.has_position()) {\n ADEBUG << \"Obstacle [\" << obstacle_ptr->id() << \"] has no position.\";\n return;\n }\n\n double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()\n : feature.theta();\n for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {\n if (feature_values->size() >= LANE_FEATURE_SIZE) {\n break;\n }\n const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);\n for (int j = 0; j < lane_segment.lane_point_size(); ++j) {\n if (feature_values->size() >= LANE_FEATURE_SIZE) {\n break;\n }\n const LanePoint& lane_point = lane_segment.lane_point(j);\n if (!lane_point.has_position()) {\n AERROR << \"Lane point has no position.\";\n continue;\n }\n double diff_x = lane_point.position().x() - feature.position().x();\n double diff_y = lane_point.position().y() - feature.position().y();\n double angle = std::atan2(diff_x, diff_y);\n feature_values->push_back(std::sin(angle - heading));\n feature_values->push_back(lane_point.relative_l());\n feature_values->push_back(lane_point.heading());\n feature_values->push_back(lane_point.angle_diff());\n }\n }\n\n std::size_t size = feature_values->size();\n while (size >= 4 && size < LANE_FEATURE_SIZE) {\n double heading_diff = feature_values->operator[](size - 4);\n double lane_l_diff = feature_values->operator[](size - 3);\n double heading = feature_values->operator[](size - 2);\n double angle_diff = feature_values->operator[](size - 1);\n feature_values->push_back(heading_diff);\n feature_values->push_back(lane_l_diff);\n feature_values->push_back(heading);\n feature_values->push_back(angle_diff);\n size = feature_values->size();\n }\n}\n\nvoid MLPEvaluator::LoadModel(const std::string& model_file) {\n model_ptr_.reset(new FnnVehicleModel());\n CHECK(model_ptr_ != nullptr);\n std::fstream file_stream(model_file, std::ios::in | std::ios::binary);\n if (!file_stream.good()) {\n AERROR << \"Unable to open the model file: \" << model_file << \".\";\n return;\n }\n if (!model_ptr_->ParseFromIstream(&file_stream)) {\n AERROR << \"Unable to load the model file: \" << model_file << \".\";\n return;\n }\n ADEBUG << \"Succeeded in loading the model file: \" << model_file << \".\";\n}\n\ndouble MLPEvaluator::ComputeProbability() {\n CHECK(model_ptr_.get() != nullptr);\n double probability = 0.0;\n\n if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {\n AERROR << \"Model feature size not consistent with model proto definition.\";\n return probability;\n }\n std::vector<double> layer_input;\n layer_input.reserve(model_ptr_->dim_input());\n std::vector<double> layer_output;\n\n \/\/ normalization\n for (int i = 0; i < model_ptr_->dim_input(); ++i) {\n double mean = model_ptr_->samples_mean().columns(i);\n double std = model_ptr_->samples_std().columns(i);\n layer_input.push_back(\n apollo::prediction::util::Normalize(feature_values_[i], mean, std));\n }\n\n for (int i = 0; i < model_ptr_->num_layer(); ++i) {\n if (i > 0) {\n layer_input.clear();\n layer_output.swap(layer_output);\n }\n const Layer& layer = model_ptr_->layer(i);\n for (int col = 0; col < layer.layer_output_dim(); ++col) {\n double neuron_output = layer.layer_bias().columns(col);\n for (int row = 0; row < layer.layer_input_dim(); ++row) {\n double weight = layer.layer_input_weight().rows(row).columns(col);\n neuron_output += (layer_input[row] * weight);\n }\n if (layer.layer_activation_type() == \"relu\") {\n neuron_output = apollo::prediction::util::Relu(neuron_output);\n } else if (layer.layer_activation_type() == \"sigmoid\") {\n neuron_output = apollo::prediction::util::Sigmoid(neuron_output);\n } else if (layer.layer_activation_type() == \"tanh\") {\n neuron_output = std::tanh(neuron_output);\n } else {\n LOG(ERROR) << \"Undefined activation func: \"\n << layer.layer_activation_type()\n << \", and default sigmoid will be used instead.\";\n neuron_output = apollo::prediction::util::Sigmoid(neuron_output);\n }\n layer_output.push_back(neuron_output);\n }\n }\n\n if (layer_output.size() != 1) {\n AERROR << \"Model output layer has incorrect # outputs: \"\n << layer_output.size();\n } else {\n probability = layer_output[0];\n }\n\n return probability;\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<commit_msg>add writing back the lane sequence probability to the feature proto<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <cmath>\n#include <fstream>\n#include <numeric>\n\n#include \"modules\/prediction\/evaluator\/vehicle\/mlp_evaluator.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/prediction\/common\/prediction_util.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nvoid MLPEvaluator::Clear() {\n obstacle_feature_values_map_.clear();\n}\n\nvoid MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {\n Clear();\n if (obstacle_ptr == nullptr) {\n AERROR << \"Invalid obstacle.\";\n return;\n }\n\n int id = obstacle_ptr->id();\n Feature latest_feature = obstacle_ptr->latest_feature();\n if (!latest_feature.IsInitialized()) {\n ADEBUG << \"Obstacle [\" << id << \"] has no latest feature.\";\n return;\n }\n\n Lane* lane_ptr = latest_feature.mutable_lane();\n if (!latest_feature.has_lane() || lane_ptr == nullptr) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane feature.\";\n return;\n }\n\n LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();\n if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane graph.\";\n return;\n }\n\n if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {\n ADEBUG << \"Obstacle [\" << id << \"] has no lane sequences.\";\n return;\n }\n\n for (int i = 0;\n i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {\n LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);\n CHECK(lane_sequence_ptr != nullptr);\n ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);\n double probability = ComputeProbability();\n lane_sequence_ptr->set_probability(probability);\n }\n}\n\nvoid MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,\n LaneSequence* lane_sequence_ptr) {\n feature_values_.clear();\n int id = obstacle_ptr->id();\n std::vector<double> obstacle_feature_values;\n if (obstacle_feature_values_map_.find(id) ==\n obstacle_feature_values_map_.end()) {\n SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);\n } else {\n obstacle_feature_values = obstacle_feature_values_map_[id];\n }\n\n if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {\n ADEBUG << \"Obstacle [\" << id << \"] has fewer than \"\n << \"expected obstacle feature_values \"\n << obstacle_feature_values.size() << \".\";\n return;\n }\n\n std::vector<double> lane_feature_values;\n SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);\n if (lane_feature_values.size() != LANE_FEATURE_SIZE) {\n ADEBUG << \"Obstacle [\" << id << \"] has fewer than \"\n << \"expected lane feature_values\"\n << lane_feature_values.size() << \".\";\n return;\n }\n\n feature_values_.insert(feature_values_.end(),\n lane_feature_values.begin(), lane_feature_values.end());\n feature_values_.insert(feature_values_.end(),\n lane_feature_values.begin(), lane_feature_values.end());\n}\n\nvoid MLPEvaluator::SetObstacleFeatureValues(\n Obstacle* obstacle_ptr, std::vector<double>* feature_values) {\n feature_values->clear();\n feature_values->reserve(OBSTACLE_FEATURE_SIZE);\n\n std::vector<double> thetas;\n std::vector<double> lane_ls;\n std::vector<double> dist_lbs;\n std::vector<double> dist_rbs;\n std::vector<int> lane_types;\n std::vector<double> speeds;\n std::vector<double> timestamps;\n\n double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;\n int count = 0;\n for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {\n const Feature& feature = obstacle_ptr->feature(i);\n if (!feature.IsInitialized()) {\n continue;\n }\n if (apollo::common::math::DoubleCompare(\n feature.timestamp(), duration) < 0) {\n break;\n }\n if (feature.has_lane() && feature.lane().has_lane_feature()) {\n thetas.push_back(feature.lane().lane_feature().angle_diff());\n lane_ls.push_back(feature.lane().lane_feature().lane_l());\n dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());\n dist_rbs.push_back(\n feature.lane().lane_feature().dist_to_right_boundary());\n lane_types.push_back(feature.lane().lane_feature().lane_turn_type());\n timestamps.push_back(feature.timestamp());\n if (FLAGS_enable_kf_tracking) {\n speeds.push_back(feature.t_speed());\n } else {\n speeds.push_back(feature.speed());\n }\n ++count;\n }\n }\n if (count <= 0) {\n return;\n }\n double theta_mean =\n std::accumulate(thetas.begin(), thetas.end(), 0.0) \/ thetas.size();\n double theta_filtered =\n (thetas.size() > 1) ? (thetas[0] + thetas[1]) \/ 2.0 : thetas[0];\n double lane_l_mean =\n std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) \/ lane_ls.size();\n double lane_l_filtered =\n (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) \/ 2.0 : lane_ls[0];\n double speed_mean =\n std::accumulate(speeds.begin(), speeds.end(), 0.0) \/ speeds.size();\n double speed_lateral = sin(theta_filtered) * speed_mean;\n double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;\n double time_to_lb = (abs(speed_lateral) > 0.05)\n ? dist_lbs[0] \/ speed_lateral\n : 20 * dist_lbs[0] * speed_sign;\n double time_to_rb = (abs(speed_lateral) > 0.05)\n ? -1 * dist_rbs[0] \/ speed_lateral\n : -20 * dist_rbs[0] * speed_sign;\n double time_diff = timestamps.front() - timestamps.back();\n double dist_lb_rate = (timestamps.size() > 1)\n ? (dist_lbs.front() - dist_lbs.back()) \/ time_diff\n : 0.0;\n double dist_rb_rate = (timestamps.size() > 1)\n ? (dist_rbs.front() - dist_rbs.back()) \/ time_diff\n : 0.0;\n \/\/ setup obstacle feature values\n feature_values->push_back(theta_filtered);\n feature_values->push_back(theta_mean);\n feature_values->push_back(theta_filtered - theta_mean);\n feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]\n : thetas[0]);\n feature_values->push_back(lane_l_filtered);\n feature_values->push_back(lane_l_mean);\n feature_values->push_back(lane_l_filtered - lane_l_mean);\n feature_values->push_back(speed_mean);\n feature_values->push_back(dist_lbs.front());\n feature_values->push_back(dist_lb_rate);\n feature_values->push_back(time_to_lb);\n feature_values->push_back(dist_rbs.front());\n feature_values->push_back(dist_rb_rate);\n feature_values->push_back(time_to_rb);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0\n \/\/ : 0.0);\n \/\/ feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0\n \/\/ : 0.0);\n}\n\nvoid MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,\n LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {\n feature_values->clear();\n feature_values->reserve(LANE_FEATURE_SIZE);\n const Feature& feature = obstacle_ptr->latest_feature();\n if (!feature.IsInitialized()) {\n ADEBUG << \"Obstacle [\" << obstacle_ptr->id() << \"] has no latest feature.\";\n return;\n } else if (!feature.has_position()) {\n ADEBUG << \"Obstacle [\" << obstacle_ptr->id() << \"] has no position.\";\n return;\n }\n\n double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()\n : feature.theta();\n for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {\n if (feature_values->size() >= LANE_FEATURE_SIZE) {\n break;\n }\n const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);\n for (int j = 0; j < lane_segment.lane_point_size(); ++j) {\n if (feature_values->size() >= LANE_FEATURE_SIZE) {\n break;\n }\n const LanePoint& lane_point = lane_segment.lane_point(j);\n if (!lane_point.has_position()) {\n AERROR << \"Lane point has no position.\";\n continue;\n }\n double diff_x = lane_point.position().x() - feature.position().x();\n double diff_y = lane_point.position().y() - feature.position().y();\n double angle = std::atan2(diff_x, diff_y);\n feature_values->push_back(std::sin(angle - heading));\n feature_values->push_back(lane_point.relative_l());\n feature_values->push_back(lane_point.heading());\n feature_values->push_back(lane_point.angle_diff());\n }\n }\n\n std::size_t size = feature_values->size();\n while (size >= 4 && size < LANE_FEATURE_SIZE) {\n double heading_diff = feature_values->operator[](size - 4);\n double lane_l_diff = feature_values->operator[](size - 3);\n double heading = feature_values->operator[](size - 2);\n double angle_diff = feature_values->operator[](size - 1);\n feature_values->push_back(heading_diff);\n feature_values->push_back(lane_l_diff);\n feature_values->push_back(heading);\n feature_values->push_back(angle_diff);\n size = feature_values->size();\n }\n}\n\nvoid MLPEvaluator::LoadModel(const std::string& model_file) {\n model_ptr_.reset(new FnnVehicleModel());\n CHECK(model_ptr_ != nullptr);\n std::fstream file_stream(model_file, std::ios::in | std::ios::binary);\n if (!file_stream.good()) {\n AERROR << \"Unable to open the model file: \" << model_file << \".\";\n return;\n }\n if (!model_ptr_->ParseFromIstream(&file_stream)) {\n AERROR << \"Unable to load the model file: \" << model_file << \".\";\n return;\n }\n ADEBUG << \"Succeeded in loading the model file: \" << model_file << \".\";\n}\n\ndouble MLPEvaluator::ComputeProbability() {\n CHECK(model_ptr_.get() != nullptr);\n double probability = 0.0;\n\n if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {\n AERROR << \"Model feature size not consistent with model proto definition.\";\n return probability;\n }\n std::vector<double> layer_input;\n layer_input.reserve(model_ptr_->dim_input());\n std::vector<double> layer_output;\n\n \/\/ normalization\n for (int i = 0; i < model_ptr_->dim_input(); ++i) {\n double mean = model_ptr_->samples_mean().columns(i);\n double std = model_ptr_->samples_std().columns(i);\n layer_input.push_back(\n apollo::prediction::util::Normalize(feature_values_[i], mean, std));\n }\n\n for (int i = 0; i < model_ptr_->num_layer(); ++i) {\n if (i > 0) {\n layer_input.clear();\n layer_output.swap(layer_output);\n }\n const Layer& layer = model_ptr_->layer(i);\n for (int col = 0; col < layer.layer_output_dim(); ++col) {\n double neuron_output = layer.layer_bias().columns(col);\n for (int row = 0; row < layer.layer_input_dim(); ++row) {\n double weight = layer.layer_input_weight().rows(row).columns(col);\n neuron_output += (layer_input[row] * weight);\n }\n if (layer.layer_activation_type() == \"relu\") {\n neuron_output = apollo::prediction::util::Relu(neuron_output);\n } else if (layer.layer_activation_type() == \"sigmoid\") {\n neuron_output = apollo::prediction::util::Sigmoid(neuron_output);\n } else if (layer.layer_activation_type() == \"tanh\") {\n neuron_output = std::tanh(neuron_output);\n } else {\n LOG(ERROR) << \"Undefined activation func: \"\n << layer.layer_activation_type()\n << \", and default sigmoid will be used instead.\";\n neuron_output = apollo::prediction::util::Sigmoid(neuron_output);\n }\n layer_output.push_back(neuron_output);\n }\n }\n\n if (layer_output.size() != 1) {\n AERROR << \"Model output layer has incorrect # outputs: \"\n << layer_output.size();\n } else {\n probability = layer_output[0];\n }\n\n return probability;\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/graf:$Name: $:$Id: TPaveStats.cxx,v 1.9 2002\/03\/16 08:52:43 brun Exp $\n\/\/ Author: Rene Brun 15\/03\/99\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"Riostream.h\"\n#include \"TPaveStats.h\"\n#include \"TVirtualPad.h\"\n#include \"TStyle.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TLatex.h\"\n\nClassImp(TPaveStats)\n\n\/\/______________________________________________________________________________\n\/\/ A PaveStats is a PaveText to draw histogram statistics\n\/\/ The type of information printed in the histogram statistics box\n\/\/ can be selected via gStyle->SetOptStat(mode).\n\/\/ or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).\n\/\/ The parameter mode can be = ourmen (default = 001111)\n\/\/ n = 1; name of histogram is printed\n\/\/ e = 1; number of entries printed\n\/\/ m = 1; mean value printed\n\/\/ r = 1; rms printed\n\/\/ u = 1; number of underflows printed\n\/\/ o = 1; number of overflows printed\n\/\/ Example: gStyle->SetOptStat(11);\n\/\/ print only name of histogram and number of entries.\n\/\/\n\/\/ The type of information about fit parameters printed in the histogram\n\/\/ statistics box can be selected via the parameter mode.\n\/\/ The parameter mode can be = pcev (default = 0111)\n\/\/ v = 1; print name\/values of parameters\n\/\/ e = 1; print errors (if e=1, v must be 1)\n\/\/ c = 1; print Chisquare\/Number of degress of freedom\n\/\/ p = 1; print Probability\n\/\/ Example: gStyle->SetOptFit(1011);\n\/\/ or this->SetOptFit(1011);\n\/\/ print fit probability, parameter names\/values and errors.\n\/\/\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(): TPaveText()\n{\n \/\/ TPaveStats default constructor\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option)\n :TPaveText(x1,y1,x2,y2,option)\n{\n \/\/ TPaveStats normal constructor\n\n fOptFit = gStyle->GetOptFit();\n fOptStat = gStyle->GetOptStat();\n SetFitFormat(gStyle->GetFitFormat());\n SetStatFormat(gStyle->GetStatFormat());\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::~TPaveStats()\n{\n \/\/ TPaveStats default destructor\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SaveStyle()\n{\n \/\/ Save This TPaveStats options in current style\n\n gStyle->SetOptFit(fOptFit);\n gStyle->SetOptStat(fOptStat);\n gStyle->SetFitFormat(fFitFormat.Data());\n gStyle->SetStatFormat(fStatFormat.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetFitFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing fit parameters in statistics box\n\n fFitFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetStatFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing statistics\n\n fStatFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Paint(Option_t *option)\n{\n TPave::ConvertNDCtoPad();\n TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);\n\n if (!fLines) return;\n Double_t dx = fX2 - fX1;\n Double_t textsize = GetTextSize();\n Int_t nlines = GetSize();\n if (nlines == 0) nlines = 5;\n\n \/\/ Evaluate text size as a function of the number of lines\n Double_t y1 = gPad->GetY1();\n Double_t y2 = gPad->GetY2();\n Float_t margin = fMargin*(fX2-fX1);\n Double_t yspace = (fY2 - fY1)\/Double_t(nlines);\n Double_t textsave = textsize;\n TObject *line;\n TLatex *latex, *latex_tok;\n TIter next(fLines);\n Double_t longest = 0;\n Double_t w, wtok[2];\n char *st, *sl;\n if (textsize == 0) {\n textsize = 0.85*yspace\/(y2 - y1);\n wtok[0] = 0; wtok[1] = 0;\n while ((line = (TObject*) next())) {\n\t if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t itok = 0;\n while ( st !=0 ) {\n latex_tok = new TLatex(0.,0.,st);\n latex_tok->SetTextSize(textsize);\n w = latex_tok->GetXsize();\n if (w > wtok[itok]) wtok[itok] = w;\n st = strtok(0, \"=\");\n ++itok;\n delete latex_tok;\n }\n }\n }\n }\n longest = wtok[0]+wtok[1]+2.*margin;\n if (longest > 0.98*dx) textsize *= 0.98*dx\/longest;\n SetTextSize(textsize);\n }\n Double_t ytext = fY2 + 0.5*yspace;\n Double_t xtext = 0;\n\n \/\/ Iterate over all lines\n \/\/ Copy pavetext attributes to line attributes if line attributes not set\n next.Reset();\n while ((line = (TObject*) next())) {\n if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n ytext -= yspace;\n Double_t xl = latex->GetX();\n Double_t yl = latex->GetY();\n Short_t talign = latex->GetTextAlign();\n Color_t tcolor = latex->GetTextColor();\n Style_t tfont = latex->GetTextFont();\n Size_t tsize = latex->GetTextSize();\n if (tcolor == 0) latex->SetTextColor(GetTextColor());\n if (tfont == 0) latex->SetTextFont(GetTextFont());\n if (tsize == 0) latex->SetTextSize(GetTextSize());\n\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n\t \/\/ Draw all the histogram except the 2D under\/overflow\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t halign = 12;\n while ( st !=0 ) {\n latex->SetTextAlign(halign);\n if (halign == 12) xtext = fX1 + margin;\n if (halign == 32) {\n xtext = fX2 - margin;\n\t\t \/\/ Clean trailing blanks in case of right alignment.\n char *stc;\n\t\t stc=st+strlen(st)-1;\n\t\t while (*stc == ' ') {\n *stc = '\\0';\n --stc;\n }\n }\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n st = strtok(0, \"=\");\n halign = 32;\n }\n\t \/\/ Draw the 2D under\/overflow\n } else if (strpbrk(sl, \"|\") !=0) {\n Double_t Yline1 = ytext+yspace\/2.;\n Double_t Yline2 = ytext-yspace\/2.;\n Double_t Xline1 = (fX2-fX1)\/3+fX1;\n Double_t Xline2 = 2*(fX2-fX1)\/3+fX1;\n gPad->PaintLine(fX1,Yline1,fX2,Yline1);\n gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);\n gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);\n st = strtok(sl, \"|\");\n\t Int_t Index = 0;\n while ( st !=0 ) {\n latex->SetTextAlign(22);\n\t if (Index == 0) xtext = 0.5*(fX1+Xline1);\n\t if (Index == 1) xtext = 0.5*(fX1+fX2);\n\t if (Index == 2) xtext = 0.5*(Xline2+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n Index++;\n st = strtok(0, \"|\");\n }\n\t \/\/ Draw the histogram identifier\n } else {\n latex->SetTextAlign(22);\n xtext = 0.5*(fX1+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n sl);\n gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);\n }\n delete [] sl;\n\n latex->SetTextAlign(talign);\n latex->SetTextColor(tcolor);\n latex->SetTextFont(tfont);\n latex->SetTextSize(tsize);\n latex->SetX(xl); \/\/paintlatex modifies fX and fY\n latex->SetY(yl);\n }\n }\n SetTextSize(textsave);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TPaveStats.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 2) {\n TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TPaveText::Streamer(R__b);\n R__b >> fOptFit;\n R__b >> fOptStat;\n TFile *file = (TFile*)R__b.GetParent();\n if (R__v > 1 || (file && file->GetVersion() == 22304)) {\n fFitFormat.Streamer(R__b);\n fStatFormat.Streamer(R__b);\n } else {\n SetFitFormat();\n SetStatFormat();\n }\n R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());\n \/\/====end of old versions\n\n } else {\n TPaveStats::Class()->WriteBuffer(R__b,this);\n }\n}\n<commit_msg>Improvements by Olivier in TPaveStats::Paint. The size of the histogram name is optimized to always fit in the box.<commit_after>\/\/ @(#)root\/graf:$Name: $:$Id: TPaveStats.cxx,v 1.10 2002\/03\/16 18:41:41 rdm Exp $\n\/\/ Author: Rene Brun 15\/03\/99\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"Riostream.h\"\n#include \"TPaveStats.h\"\n#include \"TVirtualPad.h\"\n#include \"TStyle.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TLatex.h\"\n\nClassImp(TPaveStats)\n\n\/\/______________________________________________________________________________\n\/\/ A PaveStats is a PaveText to draw histogram statistics\n\/\/ The type of information printed in the histogram statistics box\n\/\/ can be selected via gStyle->SetOptStat(mode).\n\/\/ or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).\n\/\/ The parameter mode can be = ourmen (default = 001111)\n\/\/ n = 1; name of histogram is printed\n\/\/ e = 1; number of entries printed\n\/\/ m = 1; mean value printed\n\/\/ r = 1; rms printed\n\/\/ u = 1; number of underflows printed\n\/\/ o = 1; number of overflows printed\n\/\/ Example: gStyle->SetOptStat(11);\n\/\/ print only name of histogram and number of entries.\n\/\/\n\/\/ The type of information about fit parameters printed in the histogram\n\/\/ statistics box can be selected via the parameter mode.\n\/\/ The parameter mode can be = pcev (default = 0111)\n\/\/ v = 1; print name\/values of parameters\n\/\/ e = 1; print errors (if e=1, v must be 1)\n\/\/ c = 1; print Chisquare\/Number of degress of freedom\n\/\/ p = 1; print Probability\n\/\/ Example: gStyle->SetOptFit(1011);\n\/\/ or this->SetOptFit(1011);\n\/\/ print fit probability, parameter names\/values and errors.\n\/\/\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(): TPaveText()\n{\n \/\/ TPaveStats default constructor\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option)\n :TPaveText(x1,y1,x2,y2,option)\n{\n \/\/ TPaveStats normal constructor\n\n fOptFit = gStyle->GetOptFit();\n fOptStat = gStyle->GetOptStat();\n SetFitFormat(gStyle->GetFitFormat());\n SetStatFormat(gStyle->GetStatFormat());\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::~TPaveStats()\n{\n \/\/ TPaveStats default destructor\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SaveStyle()\n{\n \/\/ Save This TPaveStats options in current style\n\n gStyle->SetOptFit(fOptFit);\n gStyle->SetOptStat(fOptStat);\n gStyle->SetFitFormat(fFitFormat.Data());\n gStyle->SetStatFormat(fStatFormat.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetFitFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing fit parameters in statistics box\n\n fFitFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetStatFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing statistics\n\n fStatFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Paint(Option_t *option)\n{\n TPave::ConvertNDCtoPad();\n TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);\n\n if (!fLines) return;\n Double_t dx = fX2 - fX1;\n Double_t titlesize=0;\n Double_t textsize = GetTextSize();\n Int_t nlines = GetSize();\n if (nlines == 0) nlines = 5;\n\n \/\/ Evaluate text size as a function of the number of lines\n Double_t y1 = gPad->GetY1();\n Double_t y2 = gPad->GetY2();\n Float_t margin = fMargin*(fX2-fX1);\n Double_t yspace = (fY2 - fY1)\/Double_t(nlines);\n Double_t textsave = textsize;\n TObject *line;\n TLatex *latex, *latex_tok;\n TIter next(fLines);\n Double_t longest = 0, titlelength = 0;\n Double_t w, wtok[2];\n char *st, *sl;\n if (textsize == 0) {\n textsize = 0.85*yspace\/(y2 - y1);\n titlesize = textsize;\n wtok[0] = 0; wtok[1] = 0;\n while ((line = (TObject*) next())) {\n\t if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t itok = 0;\n while ( st !=0 ) {\n latex_tok = new TLatex(0.,0.,st);\n latex_tok->SetTextSize(textsize);\n w = latex_tok->GetXsize();\n if (w > wtok[itok]) wtok[itok] = w;\n st = strtok(0, \"=\");\n ++itok;\n delete latex_tok;\n }\n } else if (strpbrk(sl, \"|\") !=0) {\n } else {\n latex->SetTextSize(titlesize);\n titlelength = latex->GetXsize()+2.*margin;\n if (titlelength > 0.98*dx) titlesize *= 0.98*dx\/titlelength;\n }\n }\n }\n longest = wtok[0]+wtok[1]+2.*margin;\n if (longest > 0.98*dx) textsize *= 0.98*dx\/longest;\n SetTextSize(textsize);\n }\n Double_t ytext = fY2 + 0.5*yspace;\n Double_t xtext = 0;\n\n \/\/ Iterate over all lines\n \/\/ Copy pavetext attributes to line attributes if line attributes not set\n next.Reset();\n while ((line = (TObject*) next())) {\n if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n ytext -= yspace;\n Double_t xl = latex->GetX();\n Double_t yl = latex->GetY();\n Short_t talign = latex->GetTextAlign();\n Color_t tcolor = latex->GetTextColor();\n Style_t tfont = latex->GetTextFont();\n Size_t tsize = latex->GetTextSize();\n if (tcolor == 0) latex->SetTextColor(GetTextColor());\n if (tfont == 0) latex->SetTextFont(GetTextFont());\n if (tsize == 0) latex->SetTextSize(GetTextSize());\n\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n \/\/ Draw all the histogram stats except the 2D under\/overflow\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t halign = 12;\n while ( st !=0 ) {\n latex->SetTextAlign(halign);\n if (halign == 12) xtext = fX1 + margin;\n if (halign == 32) {\n xtext = fX2 - margin;\n\t\t \/\/ Clean trailing blanks in case of right alignment.\n char *stc;\n\t\t stc=st+strlen(st)-1;\n\t\t while (*stc == ' ') {\n *stc = '\\0';\n --stc;\n }\n }\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n st = strtok(0, \"=\");\n halign = 32;\n }\n\t \/\/ Draw the 2D under\/overflow\n } else if (strpbrk(sl, \"|\") !=0) {\n Double_t Yline1 = ytext+yspace\/2.;\n Double_t Yline2 = ytext-yspace\/2.;\n Double_t Xline1 = (fX2-fX1)\/3+fX1;\n Double_t Xline2 = 2*(fX2-fX1)\/3+fX1;\n gPad->PaintLine(fX1,Yline1,fX2,Yline1);\n gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);\n gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);\n st = strtok(sl, \"|\");\n\t Int_t Index = 0;\n while ( st !=0 ) {\n latex->SetTextAlign(22);\n\t if (Index == 0) xtext = 0.5*(fX1+Xline1);\n\t if (Index == 1) xtext = 0.5*(fX1+fX2);\n\t if (Index == 2) xtext = 0.5*(Xline2+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n Index++;\n st = strtok(0, \"|\");\n }\n\t \/\/ Draw the histogram identifier\n } else {\n latex->SetTextAlign(22);\n xtext = 0.5*(fX1+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n titlesize,\n sl);\n gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);\n }\n delete [] sl;\n\n latex->SetTextAlign(talign);\n latex->SetTextColor(tcolor);\n latex->SetTextFont(tfont);\n latex->SetTextSize(tsize);\n latex->SetX(xl); \/\/paintlatex modifies fX and fY\n latex->SetY(yl);\n }\n }\n SetTextSize(textsave);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TPaveStats.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 2) {\n TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TPaveText::Streamer(R__b);\n R__b >> fOptFit;\n R__b >> fOptStat;\n TFile *file = (TFile*)R__b.GetParent();\n if (R__v > 1 || (file && file->GetVersion() == 22304)) {\n fFitFormat.Streamer(R__b);\n fStatFormat.Streamer(R__b);\n } else {\n SetFitFormat();\n SetStatFormat();\n }\n R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());\n \/\/====end of old versions\n\n } else {\n TPaveStats::Class()->WriteBuffer(R__b,this);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/graf:$Name: $:$Id: TPaveStats.cxx,v 1.8 2002\/03\/13 17:00:33 rdm Exp $\n\/\/ Author: Rene Brun 15\/03\/99\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"Riostream.h\"\n#include \"TPaveStats.h\"\n#include \"TVirtualPad.h\"\n#include \"TStyle.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TLatex.h\"\n\nClassImp(TPaveStats)\n\n\/\/______________________________________________________________________________\n\/\/ A PaveStats is a PaveText to draw histogram statistics\n\/\/ The type of information printed in the histogram statistics box\n\/\/ can be selected via gStyle->SetOptStat(mode).\n\/\/ or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).\n\/\/ The parameter mode can be = ourmen (default = 001111)\n\/\/ n = 1; name of histogram is printed\n\/\/ e = 1; number of entries printed\n\/\/ m = 1; mean value printed\n\/\/ r = 1; rms printed\n\/\/ u = 1; number of underflows printed\n\/\/ o = 1; number of overflows printed\n\/\/ Example: gStyle->SetOptStat(11);\n\/\/ print only name of histogram and number of entries.\n\/\/\n\/\/ The type of information about fit parameters printed in the histogram\n\/\/ statistics box can be selected via the parameter mode.\n\/\/ The parameter mode can be = pcev (default = 0111)\n\/\/ v = 1; print name\/values of parameters\n\/\/ e = 1; print errors (if e=1, v must be 1)\n\/\/ c = 1; print Chisquare\/Number of degress of freedom\n\/\/ p = 1; print Probability\n\/\/ Example: gStyle->SetOptFit(1011);\n\/\/ or this->SetOptFit(1011);\n\/\/ print fit probability, parameter names\/values and errors.\n\/\/\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(): TPaveText()\n{\n \/\/ TPaveStats default constructor\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option)\n :TPaveText(x1,y1,x2,y2,option)\n{\n \/\/ TPaveStats normal constructor\n\n fOptFit = gStyle->GetOptFit();\n fOptStat = gStyle->GetOptStat();\n SetFitFormat(gStyle->GetFitFormat());\n SetStatFormat(gStyle->GetStatFormat());\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::~TPaveStats()\n{\n \/\/ TPaveStats default destructor\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SaveStyle()\n{\n \/\/ Save This TPaveStats options in current style\n\n gStyle->SetOptFit(fOptFit);\n gStyle->SetOptStat(fOptStat);\n gStyle->SetFitFormat(fFitFormat.Data());\n gStyle->SetStatFormat(fStatFormat.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetFitFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing fit parameters in statistics box\n\n fFitFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetStatFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing statistics\n\n fStatFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Paint(Option_t *option)\n{\n TPave::ConvertNDCtoPad();\n TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);\n\n if (!fLines) return;\n Double_t dx = fX2 - fX1;\n Double_t dy = fY2 - fY1;\n Double_t textsize = GetTextSize();\n Int_t nlines = GetSize();\n if (nlines == 0) nlines = 5;\n\n \/\/ Evaluate text size as a function of the number of lines\n Double_t y1 = gPad->GetY1();\n Double_t y2 = gPad->GetY2();\n Float_t margin = fMargin*(fX2-fX1);\n Double_t yspace = (fY2 - fY1)\/Double_t(nlines);\n Double_t textsave = textsize;\n TObject *line;\n TLatex *latex, *latex_tok;\n TIter next(fLines);\n Double_t longest = 0;\n Double_t w, wtok[2];\n char *st, *sl;\n if (textsize == 0) {\n textsize = 0.85*yspace\/(y2 - y1);\n wtok[0] = 0; wtok[1] = 0;\n while ((line = (TObject*) next())) {\n\t if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t itok = 0;\n while ( st !=0 ) {\n latex_tok = new TLatex(0.,0.,st);\n latex_tok->SetTextSize(textsize);\n w = latex_tok->GetXsize();\n if (w > wtok[itok]) wtok[itok] = w;\n st = strtok(0, \"=\");\n ++itok;\n delete latex_tok;\n }\n }\n }\n }\n longest = wtok[0]+wtok[1]+2.*margin;\n if (longest > 0.98*dx) textsize *= 0.98*dx\/longest;\n SetTextSize(textsize);\n }\n Double_t ytext = fY2 + 0.5*yspace;\n Double_t xtext = 0;\n\n \/\/ Iterate over all lines\n \/\/ Copy pavetext attributes to line attributes if line attributes not set\n next.Reset();\n while ((line = (TObject*) next())) {\n if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n ytext -= yspace;\n Double_t xl = latex->GetX();\n Double_t yl = latex->GetY();\n Short_t talign = latex->GetTextAlign();\n Color_t tcolor = latex->GetTextColor();\n Style_t tfont = latex->GetTextFont();\n Size_t tsize = latex->GetTextSize();\n if (tcolor == 0) latex->SetTextColor(GetTextColor());\n if (tfont == 0) latex->SetTextFont(GetTextFont());\n if (tsize == 0) latex->SetTextSize(GetTextSize());\n\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n\t \/\/ Draw all the histogram except the 2D under\/overflow \n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t halign = 12;\n while ( st !=0 ) {\n latex->SetTextAlign(halign);\n if (halign == 12) xtext = fX1 + margin;\n if (halign == 32) {\n xtext = fX2 - margin;\n\t\t \/\/ Clean trailing blanks in case of right alignment.\n char *stc;\n\t\t stc=st+strlen(st)-1;\n\t\t while (*stc == ' ') {\n *stc = '\\0';\n --stc;\n }\n }\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n st = strtok(0, \"=\");\n halign = 32;\n }\n\t \/\/ Draw the 2D under\/overflow\n } else if (strpbrk(sl, \"|\") !=0) {\n Double_t Yline1 = ytext+yspace\/2.;\n Double_t Yline2 = ytext-yspace\/2.;\n Double_t Xline1 = (fX2-fX1)\/3+fX1;\n Double_t Xline2 = 2*(fX2-fX1)\/3+fX1;\n gPad->PaintLine(fX1,Yline1,fX2,Yline1);\n gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);\n gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);\n st = strtok(sl, \"|\");\n\t Int_t Index = 0;\n while ( st !=0 ) {\n latex->SetTextAlign(22);\n\t if (Index == 0) xtext = 0.5*(fX1+Xline1);\n\t if (Index == 1) xtext = 0.5*(fX1+fX2);\n\t if (Index == 2) xtext = 0.5*(Xline2+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n Index++;\n st = strtok(0, \"|\");\n }\n\t \/\/ Draw the histogram identifier\n } else {\n latex->SetTextAlign(22);\n xtext = 0.5*(fX1+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n sl);\n gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);\n }\n delete [] sl;\n\n latex->SetTextAlign(talign);\n latex->SetTextColor(tcolor);\n latex->SetTextFont(tfont);\n latex->SetTextSize(tsize);\n latex->SetX(xl); \/\/paintlatex modifies fX and fY\n latex->SetY(yl);\n }\n }\n SetTextSize(textsave);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TPaveStats.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 2) {\n TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TPaveText::Streamer(R__b);\n R__b >> fOptFit;\n R__b >> fOptStat;\n TFile *file = (TFile*)R__b.GetParent();\n if (R__v > 1 || (file && file->GetVersion() == 22304)) {\n fFitFormat.Streamer(R__b);\n fStatFormat.Streamer(R__b);\n } else {\n SetFitFormat();\n SetStatFormat();\n }\n R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());\n \/\/====end of old versions\n\n } else {\n TPaveStats::Class()->WriteBuffer(R__b,this);\n }\n}\n<commit_msg>remove unused dy.<commit_after>\/\/ @(#)root\/graf:$Name: $:$Id: TPaveStats.cxx,v 1.9 2002\/03\/16 08:52:43 brun Exp $\n\/\/ Author: Rene Brun 15\/03\/99\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"Riostream.h\"\n#include \"TPaveStats.h\"\n#include \"TVirtualPad.h\"\n#include \"TStyle.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TLatex.h\"\n\nClassImp(TPaveStats)\n\n\/\/______________________________________________________________________________\n\/\/ A PaveStats is a PaveText to draw histogram statistics\n\/\/ The type of information printed in the histogram statistics box\n\/\/ can be selected via gStyle->SetOptStat(mode).\n\/\/ or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).\n\/\/ The parameter mode can be = ourmen (default = 001111)\n\/\/ n = 1; name of histogram is printed\n\/\/ e = 1; number of entries printed\n\/\/ m = 1; mean value printed\n\/\/ r = 1; rms printed\n\/\/ u = 1; number of underflows printed\n\/\/ o = 1; number of overflows printed\n\/\/ Example: gStyle->SetOptStat(11);\n\/\/ print only name of histogram and number of entries.\n\/\/\n\/\/ The type of information about fit parameters printed in the histogram\n\/\/ statistics box can be selected via the parameter mode.\n\/\/ The parameter mode can be = pcev (default = 0111)\n\/\/ v = 1; print name\/values of parameters\n\/\/ e = 1; print errors (if e=1, v must be 1)\n\/\/ c = 1; print Chisquare\/Number of degress of freedom\n\/\/ p = 1; print Probability\n\/\/ Example: gStyle->SetOptFit(1011);\n\/\/ or this->SetOptFit(1011);\n\/\/ print fit probability, parameter names\/values and errors.\n\/\/\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(): TPaveText()\n{\n \/\/ TPaveStats default constructor\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option)\n :TPaveText(x1,y1,x2,y2,option)\n{\n \/\/ TPaveStats normal constructor\n\n fOptFit = gStyle->GetOptFit();\n fOptStat = gStyle->GetOptStat();\n SetFitFormat(gStyle->GetFitFormat());\n SetStatFormat(gStyle->GetStatFormat());\n}\n\n\/\/______________________________________________________________________________\nTPaveStats::~TPaveStats()\n{\n \/\/ TPaveStats default destructor\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SaveStyle()\n{\n \/\/ Save This TPaveStats options in current style\n\n gStyle->SetOptFit(fOptFit);\n gStyle->SetOptStat(fOptStat);\n gStyle->SetFitFormat(fFitFormat.Data());\n gStyle->SetStatFormat(fStatFormat.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetFitFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing fit parameters in statistics box\n\n fFitFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::SetStatFormat(const char *form)\n{\n \/\/ Change (i.e. set) the format for printing statistics\n\n fStatFormat = form;\n}\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Paint(Option_t *option)\n{\n TPave::ConvertNDCtoPad();\n TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);\n\n if (!fLines) return;\n Double_t dx = fX2 - fX1;\n Double_t textsize = GetTextSize();\n Int_t nlines = GetSize();\n if (nlines == 0) nlines = 5;\n\n \/\/ Evaluate text size as a function of the number of lines\n Double_t y1 = gPad->GetY1();\n Double_t y2 = gPad->GetY2();\n Float_t margin = fMargin*(fX2-fX1);\n Double_t yspace = (fY2 - fY1)\/Double_t(nlines);\n Double_t textsave = textsize;\n TObject *line;\n TLatex *latex, *latex_tok;\n TIter next(fLines);\n Double_t longest = 0;\n Double_t w, wtok[2];\n char *st, *sl;\n if (textsize == 0) {\n textsize = 0.85*yspace\/(y2 - y1);\n wtok[0] = 0; wtok[1] = 0;\n while ((line = (TObject*) next())) {\n\t if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t itok = 0;\n while ( st !=0 ) {\n latex_tok = new TLatex(0.,0.,st);\n latex_tok->SetTextSize(textsize);\n w = latex_tok->GetXsize();\n if (w > wtok[itok]) wtok[itok] = w;\n st = strtok(0, \"=\");\n ++itok;\n delete latex_tok;\n }\n }\n }\n }\n longest = wtok[0]+wtok[1]+2.*margin;\n if (longest > 0.98*dx) textsize *= 0.98*dx\/longest;\n SetTextSize(textsize);\n }\n Double_t ytext = fY2 + 0.5*yspace;\n Double_t xtext = 0;\n\n \/\/ Iterate over all lines\n \/\/ Copy pavetext attributes to line attributes if line attributes not set\n next.Reset();\n while ((line = (TObject*) next())) {\n if (line->IsA() == TLatex::Class()) {\n latex = (TLatex*)line;\n ytext -= yspace;\n Double_t xl = latex->GetX();\n Double_t yl = latex->GetY();\n Short_t talign = latex->GetTextAlign();\n Color_t tcolor = latex->GetTextColor();\n Style_t tfont = latex->GetTextFont();\n Size_t tsize = latex->GetTextSize();\n if (tcolor == 0) latex->SetTextColor(GetTextColor());\n if (tfont == 0) latex->SetTextFont(GetTextFont());\n if (tsize == 0) latex->SetTextSize(GetTextSize());\n\n sl = new char[strlen(latex->GetTitle())+1];\n strcpy(sl, latex->GetTitle());\n\t \/\/ Draw all the histogram except the 2D under\/overflow\n if (strpbrk(sl, \"=\") !=0) {\n st = strtok(sl, \"=\");\n Int_t halign = 12;\n while ( st !=0 ) {\n latex->SetTextAlign(halign);\n if (halign == 12) xtext = fX1 + margin;\n if (halign == 32) {\n xtext = fX2 - margin;\n\t\t \/\/ Clean trailing blanks in case of right alignment.\n char *stc;\n\t\t stc=st+strlen(st)-1;\n\t\t while (*stc == ' ') {\n *stc = '\\0';\n --stc;\n }\n }\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n st = strtok(0, \"=\");\n halign = 32;\n }\n\t \/\/ Draw the 2D under\/overflow\n } else if (strpbrk(sl, \"|\") !=0) {\n Double_t Yline1 = ytext+yspace\/2.;\n Double_t Yline2 = ytext-yspace\/2.;\n Double_t Xline1 = (fX2-fX1)\/3+fX1;\n Double_t Xline2 = 2*(fX2-fX1)\/3+fX1;\n gPad->PaintLine(fX1,Yline1,fX2,Yline1);\n gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);\n gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);\n st = strtok(sl, \"|\");\n\t Int_t Index = 0;\n while ( st !=0 ) {\n latex->SetTextAlign(22);\n\t if (Index == 0) xtext = 0.5*(fX1+Xline1);\n\t if (Index == 1) xtext = 0.5*(fX1+fX2);\n\t if (Index == 2) xtext = 0.5*(Xline2+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n st);\n Index++;\n st = strtok(0, \"|\");\n }\n\t \/\/ Draw the histogram identifier\n } else {\n latex->SetTextAlign(22);\n xtext = 0.5*(fX1+fX2);\n latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),\n latex->GetTextSize(),\n sl);\n gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);\n }\n delete [] sl;\n\n latex->SetTextAlign(talign);\n latex->SetTextColor(tcolor);\n latex->SetTextFont(tfont);\n latex->SetTextSize(tsize);\n latex->SetX(xl); \/\/paintlatex modifies fX and fY\n latex->SetY(yl);\n }\n }\n SetTextSize(textsave);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPaveStats::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TPaveStats.\n\n if (R__b.IsReading()) {\n UInt_t R__s, R__c;\n Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n if (R__v > 2) {\n TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n return;\n }\n \/\/====process old versions before automatic schema evolution\n TPaveText::Streamer(R__b);\n R__b >> fOptFit;\n R__b >> fOptStat;\n TFile *file = (TFile*)R__b.GetParent();\n if (R__v > 1 || (file && file->GetVersion() == 22304)) {\n fFitFormat.Streamer(R__b);\n fStatFormat.Streamer(R__b);\n } else {\n SetFitFormat();\n SetStatFormat();\n }\n R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());\n \/\/====end of old versions\n\n } else {\n TPaveStats::Class()->WriteBuffer(R__b,this);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"IECorePython\/Wrapper.h\"\n#include \"IECorePython\/RefCountedBinding.h\"\n#include \"IECorePython\/ScopedGILLock.h\"\n\n#include \"IECore\/LevenbergMarquardt.h\"\n#include \"IECorePython\/LevenbergMarquardtBinding.h\"\n\nusing namespace boost::python;\nusing namespace IECore;\n\nnamespace IECorePython\n{\n\ntemplate<typename T>\nclass LevenbergMarquardtErrorFn : public RefCounted\n{\n\tpublic :\n\n\t\tIE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFn<T> );\n\n\t\tLevenbergMarquardtErrorFn()\n\t\t{\n\t\t}\n\n\t\tvirtual ~LevenbergMarquardtErrorFn()\n\t\t{\n\t\t}\n\n\t\tvoid operator()(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t)\n\t\t{\n\t\t\tcomputeErrors( parameters, errors );\n\t\t\tassert( errors->readable().size() == numErrors() );\n\t\t}\n\n\t\tvirtual unsigned numErrors() = 0;\n\n\t\tvirtual void computeErrors(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t) = 0;\n\n};\n\ntemplate<typename T>\nclass LevenbergMarquardtErrorFnWrapper : public LevenbergMarquardtErrorFn<T>, public Wrapper< LevenbergMarquardtErrorFn<T> >\n{\n\tpublic:\n\n\t\tIE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFnWrapper<T> );\n\n\t\tLevenbergMarquardtErrorFnWrapper(PyObject *self ) : LevenbergMarquardtErrorFn<T>(), Wrapper< LevenbergMarquardtErrorFn<T> >( self, this )\n\t\t{\n\t\t}\n\n\t\tvirtual ~LevenbergMarquardtErrorFnWrapper()\n\t\t{\n\t\t}\n\n\t\tvirtual unsigned numErrors()\n\t\t{\n\t\t\tScopedGILLock gilLock;\n\t\t\toverride o = this->get_override( \"numErrors\" );\n\t\t\tif( o )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n \t\treturn o();\n\t\t\t\t}\n\t\t\t\tcatch ( error_already_set )\n\t\t\t\t{\n\t\t\t\t\tPyErr_Print();\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n \t\tthrow Exception( \"LevenbergMarquardt: Error function does not define 'numErrors' instance method\" );\n\t\t\t}\n\t\t}\n\n\t\tvirtual void computeErrors(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t)\n\t\t{\n\t\t\tScopedGILLock gilLock;\n\t\t\toverride o = this->get_override( \"computeErrors\" );\n\t\t\tif( o )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n \t\t\t\to( parameters, errors );\n\t\t\t\t}\n\t\t\t\tcatch ( error_already_set )\n\t\t\t\t{\n\t\t\t\t\tPyErr_Print();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow Exception( \"LevenbergMarquardt: Error function does not define 'computeErrors' instance method\" );\n\t\t\t}\n\t\t}\n};\n\ntemplate< typename T>\nclass LevenbergMarquardtWrapper : public LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >\n{\n\tpublic:\n\n\t\ttuple getParameters()\n\t\t{\n\t\t\tT ftol, xtol, gtol, epsilon, stepBound;\n\t\t\tLevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >::getParameters( ftol, xtol, gtol, epsilon, stepBound );\n\t\t\treturn make_tuple(ftol, xtol, gtol, epsilon, stepBound);\n\t\t}\n};\n\ntemplate<typename T>\nvoid bindLevenbergMarquardt( const char *name )\n{\n\tobject lm = class_< LevenbergMarquardtWrapper<T>, boost::noncopyable >( name, no_init )\n\t\t.def( init<>() )\n\t\t.def( \"setParameters\", &LevenbergMarquardtWrapper<T>::setParameters )\n\t\t.def( \"getParameters\", &LevenbergMarquardtWrapper<T>::getParameters )\n\t\t.def( \"solve\", &LevenbergMarquardtWrapper<T>::solve )\n\t\t.def( \"setMaxCalls\", &LevenbergMarquardtWrapper<T>::setMaxCalls )\n\t\t.def( \"getMaxCalls\", &LevenbergMarquardtWrapper<T>::getMaxCalls )\n\t;\n\n\t{\n\t\tscope lmS( lm );\n\n\t\tenum_< typename LevenbergMarquardtWrapper<T>::Status >( \"Status\" )\n\t\t\t.value( \"Success\", LevenbergMarquardtWrapper<T>::Success )\n\t\t;\n\n\t\tRefCountedClass<LevenbergMarquardtErrorFn<T>, RefCounted, LevenbergMarquardtErrorFnWrapper<T> >( \"ErrorFn\" )\n\t\t\t.def( init<>() )\n\t\t\t.def( \"numErrors\", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::numErrors ) )\n\t\t\t.def( \"computeErrors\", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::computeErrors ) )\n\t\t;\n\t}\n}\n\nvoid bindLevenbergMarquardt()\n{\n\tbindLevenbergMarquardt< float >( \"LevenbergMarquardtf\" );\n\tbindLevenbergMarquardt< double >( \"LevenbergMarquardtd\" );\n}\n\n} \/\/ namespace IECorePython\n<commit_msg>LevenbergMarquardt Binding : Use RefCountedWrapper<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"IECorePython\/RefCountedBinding.h\"\n#include \"IECorePython\/ScopedGILLock.h\"\n\n#include \"IECore\/LevenbergMarquardt.h\"\n#include \"IECorePython\/LevenbergMarquardtBinding.h\"\n\nusing namespace boost::python;\nusing namespace IECore;\n\nnamespace IECorePython\n{\n\ntemplate<typename T>\nclass LevenbergMarquardtErrorFn : public RefCounted\n{\n\tpublic :\n\n\t\tIE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFn<T> );\n\n\t\tLevenbergMarquardtErrorFn()\n\t\t{\n\t\t}\n\n\t\tvirtual ~LevenbergMarquardtErrorFn()\n\t\t{\n\t\t}\n\n\t\tvoid operator()(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t)\n\t\t{\n\t\t\tcomputeErrors( parameters, errors );\n\t\t\tassert( errors->readable().size() == numErrors() );\n\t\t}\n\n\t\tvirtual unsigned numErrors() = 0;\n\n\t\tvirtual void computeErrors(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t) = 0;\n\n};\n\ntemplate<typename T>\nclass LevenbergMarquardtErrorFnWrapper : public RefCountedWrapper< LevenbergMarquardtErrorFn<T> >\n{\n\tpublic:\n\n\t\tIE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFnWrapper<T> );\n\n\t\tLevenbergMarquardtErrorFnWrapper( PyObject *self )\n\t\t\t: RefCountedWrapper< LevenbergMarquardtErrorFn<T> >( self )\n\t\t{\n\t\t}\n\n\t\tvirtual ~LevenbergMarquardtErrorFnWrapper()\n\t\t{\n\t\t}\n\n\t\tvirtual unsigned numErrors()\n\t\t{\n\t\t\tScopedGILLock gilLock;\n\t\t\tobject o = this->methodOverride( \"numErrors\" );\n\t\t\tif( o )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\treturn extract<unsigned>( o() );\n\t\t\t\t}\n\t\t\t\tcatch( error_already_set )\n\t\t\t\t{\n\t\t\t\t\tPyErr_Print();\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow Exception( \"LevenbergMarquardt: Error function does not define 'numErrors' instance method\" );\n\t\t\t}\n\t\t}\n\n\t\tvirtual void computeErrors(\n\t\t typename TypedData< std::vector<T> >::Ptr parameters,\n\t\t typename TypedData< std::vector<T> >::Ptr errors\n\t\t)\n\t\t{\n\t\t\tScopedGILLock gilLock;\n\t\t\tobject o = this->methodOverride( \"computeErrors\" );\n\t\t\tif( o )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\to( parameters, errors );\n\t\t\t\t}\n\t\t\t\tcatch( error_already_set )\n\t\t\t\t{\n\t\t\t\t\tPyErr_Print();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow Exception( \"LevenbergMarquardt: Error function does not define 'computeErrors' instance method\" );\n\t\t\t}\n\t\t}\n};\n\ntemplate< typename T>\nclass LevenbergMarquardtWrapper : public LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >\n{\n\tpublic:\n\n\t\ttuple getParameters()\n\t\t{\n\t\t\tT ftol, xtol, gtol, epsilon, stepBound;\n\t\t\tLevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >::getParameters( ftol, xtol, gtol, epsilon, stepBound );\n\t\t\treturn make_tuple(ftol, xtol, gtol, epsilon, stepBound);\n\t\t}\n};\n\ntemplate<typename T>\nvoid bindLevenbergMarquardt( const char *name )\n{\n\tobject lm = class_< LevenbergMarquardtWrapper<T>, boost::noncopyable >( name, no_init )\n\t\t.def( init<>() )\n\t\t.def( \"setParameters\", &LevenbergMarquardtWrapper<T>::setParameters )\n\t\t.def( \"getParameters\", &LevenbergMarquardtWrapper<T>::getParameters )\n\t\t.def( \"solve\", &LevenbergMarquardtWrapper<T>::solve )\n\t\t.def( \"setMaxCalls\", &LevenbergMarquardtWrapper<T>::setMaxCalls )\n\t\t.def( \"getMaxCalls\", &LevenbergMarquardtWrapper<T>::getMaxCalls )\n\t;\n\n\t{\n\t\tscope lmS( lm );\n\n\t\tenum_< typename LevenbergMarquardtWrapper<T>::Status >( \"Status\" )\n\t\t\t.value( \"Success\", LevenbergMarquardtWrapper<T>::Success )\n\t\t;\n\n\t\tRefCountedClass<LevenbergMarquardtErrorFn<T>, RefCounted, LevenbergMarquardtErrorFnWrapper<T> >( \"ErrorFn\" )\n\t\t\t.def( init<>() )\n\t\t\t.def( \"numErrors\", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::numErrors ) )\n\t\t\t.def( \"computeErrors\", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::computeErrors ) )\n\t\t;\n\t}\n}\n\nvoid bindLevenbergMarquardt()\n{\n\tbindLevenbergMarquardt< float >( \"LevenbergMarquardtf\" );\n\tbindLevenbergMarquardt< double >( \"LevenbergMarquardtd\" );\n}\n\n} \/\/ namespace IECorePython\n<|endoftext|>"} {"text":"<commit_before>#include \"ddrawoverlay.h\"\n#include <detourxs.h>\n#include <ddraw.h>\n\n\ntypedef HRESULT(WINAPI *TYPE_DirectDrawCreate) (\n\tGUID FAR *, \n\tLPDIRECTDRAW FAR *, \n\tIUnknown FAR *\n\t);\n\nTYPE_DirectDrawCreate pDirectDrawCreate;\n\n\nHRESULT WINAPI DirectDrawCreate_Hook(\n\tGUID FAR *lpGUID, \n\tLPDIRECTDRAW FAR *lplpDD, \n\tIUnknown FAR *pUnkOuter\n\t)\n{\n\tHRESULT returnValue = 0;\n\n\tOutputDebugStringW(L\"[OVRENDER] DirectDrawCreate Called!\");\n\treturnValue = pDirectDrawCreate(lpGUID, lplpDD, pUnkOuter);\n\n\treturn returnValue;\n}\n\n\nDDrawOverlay::DDrawOverlay( OV_RENDER RenderFunction )\n{\n\tHMODULE base;\n\tDetourXS *detour;\n\tOutputDebugStringW(L\"[OVRENDER] Creating DirectDraw Overlay!\");\n\tbase = (HMODULE)LoadLibraryW(L\"ddraw.dll\");\n\t\n\tdetour = new DetourXS(\n\t\tGetProcAddress(base, \"DirectDrawCreateEx\"), \n\t\tDirectDrawCreate_Hook\n\t\t);\n\n\tpDirectDrawCreate = (TYPE_DirectDrawCreate)detour->GetTrampoline();\n\n\tUserRenderFunction = RenderFunction;\n}\n\n\nVOID\nDDrawOverlay::DrawText(WCHAR* Text)\n{\n\tDrawText(Text, FALSE);\n}\n\n\nVOID DDrawOverlay::DrawText(\n\tWCHAR* Text,\n\tDWORD Color\n\t)\n{\n\tDrawText(Text, 20, Line, Color);\n\n\tLine += 15;\n}\n\n\nVOID DDrawOverlay::DrawText(\n\tWCHAR* Text,\n\tint X,\n\tint Y,\n\tDWORD Color\n\t)\n{\n\n}\n\n\nVOID\nDDrawOverlay::Begin()\n{\n\n}\n\n\nVOID\nDDrawOverlay::End()\n{\n\n}\n\n\nVOID*\nDDrawOverlay::GetDevice()\n{\n\treturn NULL;\n}<commit_msg>fixed incorrect calling convention. fixes #51<commit_after>#include \"ddrawoverlay.h\"\n#include <detourxs.h>\n#include <ddraw.h>\n\n\ntypedef HRESULT(WINAPI *TYPE_DirectDrawCreate) (\n GUID FAR *, \n LPDIRECTDRAW FAR *, \n IUnknown FAR *\n );\n\nTYPE_DirectDrawCreate pDirectDrawCreate;\n\n\nHRESULT WINAPI DirectDrawCreate_Hook(\n GUID FAR *lpGUID, \n LPDIRECTDRAW FAR *lplpDD, \n IUnknown FAR *pUnkOuter\n )\n{\n HRESULT returnValue = 0;\n\n OutputDebugStringW(L\"[OVRENDER] DirectDrawCreate Called!\");\n returnValue = pDirectDrawCreate(lpGUID, lplpDD, pUnkOuter);\n\n return returnValue;\n}\n\n\nDDrawOverlay::DDrawOverlay( OV_RENDER RenderFunction )\n{\n HMODULE base;\n DetourXS *detour;\n OutputDebugStringW(L\"[OVRENDER] Creating DirectDraw Overlay!\");\n base = (HMODULE)LoadLibraryW(L\"ddraw.dll\");\n \n detour = new DetourXS(\n GetProcAddress(base, \"DirectDrawCreate\"),\n DirectDrawCreate_Hook\n );\n\n pDirectDrawCreate = (TYPE_DirectDrawCreate)detour->GetTrampoline();\n\n UserRenderFunction = RenderFunction;\n}\n\n\nVOID\nDDrawOverlay::DrawText(WCHAR* Text)\n{\n DrawText(Text, FALSE);\n}\n\n\nVOID DDrawOverlay::DrawText(\n WCHAR* Text,\n DWORD Color\n )\n{\n DrawText(Text, 20, Line, Color);\n\n Line += 15;\n}\n\n\nVOID DDrawOverlay::DrawText(\n WCHAR* Text,\n int X,\n int Y,\n DWORD Color\n )\n{\n\n}\n\n\nVOID\nDDrawOverlay::Begin()\n{\n\n}\n\n\nVOID\nDDrawOverlay::End()\n{\n\n}\n\n\nVOID*\nDDrawOverlay::GetDevice()\n{\n return NULL;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <random>\n\n#include <timeit\/timeit.h>\n\nint main()\n{\n std::minstd_rand rnd;\n std::cout << timeit::total<std::chrono::nanoseconds>([&rnd](){ rnd(); }, 10000000).count() << \" ns\" << std::endl;\n\n return 0;\n}<commit_msg>added precise (nanoseconds) example<commit_after>#include <iostream>\n#include <string>\n#include <random>\n\n#include <timeit\/timeit.h>\n\ntemplate <typename Random>\nvoid benchmark(const std::string &engine, size_t iterations)\n{\n Random rnd;\n std::cout << engine << \" - \" << timeit::average<std::chrono::nanoseconds>([&rnd](){ rnd(); }, iterations).count() << \" ns\" << std::endl;\n}\n\nint main()\n{\n auto iterations = 1000000;\n benchmark<std::minstd_rand>(\"minstd_rand\");\n benchmark<std::mt19937>(\"mt19937\");\n benchmark<std::ranlux24>(\"ranlux24\");\n benchmark<std::knuth_b>(\"knuth_b\");\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <components\/screen_butler.hpp>\n\nnamespace bookwyrm::tui {\n\nstd::shared_ptr<screen_butler> make_with(script_butler &butler, vector<py::module> &sources)\n{\n auto tui = std::make_shared<screen_butler>(butler.results());\n butler.set_screens(tui);\n butler.async_search(sources); \/\/ Watch out, it's hot!\n return tui;\n}\n\n\/* ns bookwyrm::tui *\/\n}\n<commit_msg>remove unused source file<commit_after><|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * plan_transformer.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/n-store\/src\/bridge\/plan_transformer.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include <cstring>\n#include <cassert>\n\n#include \"backend\/bridge\/dml\/mapper\/mapper.h\"\n\n#include \"nodes\/print.h\"\n#include \"nodes\/pprint.h\"\n#include \"utils\/lsyscache.h\"\n#include \"executor\/executor.h\"\n#include \"parser\/parsetree.h\"\n\nvoid printPlanStateTree(const PlanState * planstate);\n\nnamespace peloton {\nnamespace bridge {\n\nextern const ValueArray BuildParams(const ParamListInfo param_list);\n\n\/**\n * @brief Pretty print the plan state tree.\n * @return none.\n *\/\nvoid PlanTransformer::PrintPlanState(const PlanState *plan_state) {\n printPlanStateTree(plan_state);\n}\n\n\/**\n * @brief Convert Postgres PlanState (tree) into AbstractPlanNode (tree).\n * @return Pointer to the constructed AbstractPlan`Node.\n *\/\nplanner::AbstractPlanNode *PlanTransformer::TransformPlan(\n const PlanState *plan_state) {\n assert(plan_state);\n\n Plan *plan = plan_state->plan;\n\n if(plan == nullptr)\n return nullptr;\n\n planner::AbstractPlanNode *plan_node;\n ValueArray params;\n\n LOG_INFO(\"planstate %d with #param\", nodeTag(plan_state));\n\n if(plan_state->state != nullptr)\n params = BuildParams(plan_state->state->es_param_list_info);\n\n switch (nodeTag(plan)) {\n case T_ModifyTable:\n plan_node = PlanTransformer::TransformModifyTable(\n reinterpret_cast<const ModifyTableState *>(plan_state), params);\n break;\n case T_SeqScan:\n plan_node = PlanTransformer::TransformSeqScan(\n reinterpret_cast<const SeqScanState*>(plan_state), params);\n break;\n case T_IndexScan:\n plan_node = PlanTransformer::TransformIndexScan(\n reinterpret_cast<const IndexScanState*>(plan_state), params);\n break;\n case T_IndexOnlyScan:\n plan_node = PlanTransformer::TransformIndexOnlyScan(\n reinterpret_cast<const IndexOnlyScanState*>(plan_state), params);\n break;\n case T_Limit:\n plan_node = PlanTransformer::TransformLimit(\n reinterpret_cast<const LimitState*>(plan_state));\n break;\n default: {\n plan_node = nullptr;\n LOG_ERROR(\"Unsupported Postgres Plan Tag: %u Plan : %p\", nodeTag(plan),\n plan);\n break;\n }\n }\n\n return plan_node;\n}\n\n\/**\n * @brief Recursively destroy the nodes in a plan node tree.\n *\/\nbool PlanTransformer::CleanPlanNodeTree(planner::AbstractPlanNode* root) {\n if (!root)\n return false;\n\n \/\/ Clean all children subtrees\n auto children = root->GetChildren();\n for (auto child : children) {\n auto rv = CleanPlanNodeTree(child);\n assert(rv);\n }\n\n \/\/ Clean the root\n delete root;\n return true;\n}\n\ninline const ValueArray BuildParams(const ParamListInfo param_list) {\n ValueArray params;\n if (param_list != nullptr) {\n params.Reset(param_list->numParams);\n for (int i = 0; i < params.GetSize(); ++i) {\n ParamExternData param = param_list->params[i];\n params[i] = TupleTransformer::GetValue(param.value, param.ptype);\n }\n }\n LOG_INFO(\"Built param list of size %d\", params.GetSize());\n return params;\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n\n<commit_msg>minor change<commit_after>\/*-------------------------------------------------------------------------\n *\n * plan_transformer.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/n-store\/src\/bridge\/plan_transformer.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include <cstring>\n#include <cassert>\n\n#include \"backend\/bridge\/dml\/mapper\/mapper.h\"\n\n#include \"nodes\/print.h\"\n#include \"nodes\/pprint.h\"\n#include \"utils\/lsyscache.h\"\n#include \"executor\/executor.h\"\n#include \"parser\/parsetree.h\"\n\nvoid printPlanStateTree(const PlanState * planstate);\n\nnamespace peloton {\nnamespace bridge {\n\nextern const ValueArray BuildParams(const ParamListInfo param_list);\n\n\/**\n * @brief Pretty print the plan state tree.\n * @return none.\n *\/\nvoid PlanTransformer::PrintPlanState(const PlanState *plan_state) {\n printPlanStateTree(plan_state);\n}\n\n\/**\n * @brief Convert Postgres PlanState (tree) into AbstractPlanNode (tree).\n * @return Pointer to the constructed AbstractPlan`Node.\n *\/\nplanner::AbstractPlanNode *PlanTransformer::TransformPlan(\n const PlanState *plan_state) {\n assert(plan_state);\n\n Plan *plan = plan_state->plan;\n\n if(plan == nullptr)\n return nullptr;\n\n planner::AbstractPlanNode *plan_node;\n ValueArray params;\n\n LOG_INFO(\"planstate %d\", nodeTag(plan_state));\n\n if(plan_state->state != nullptr)\n params = BuildParams(plan_state->state->es_param_list_info);\n\n switch (nodeTag(plan)) {\n case T_ModifyTable:\n plan_node = PlanTransformer::TransformModifyTable(\n reinterpret_cast<const ModifyTableState *>(plan_state), params);\n break;\n case T_SeqScan:\n plan_node = PlanTransformer::TransformSeqScan(\n reinterpret_cast<const SeqScanState*>(plan_state), params);\n break;\n case T_IndexScan:\n plan_node = PlanTransformer::TransformIndexScan(\n reinterpret_cast<const IndexScanState*>(plan_state), params);\n break;\n case T_IndexOnlyScan:\n plan_node = PlanTransformer::TransformIndexOnlyScan(\n reinterpret_cast<const IndexOnlyScanState*>(plan_state), params);\n break;\n case T_Limit:\n plan_node = PlanTransformer::TransformLimit(\n reinterpret_cast<const LimitState*>(plan_state));\n break;\n default: {\n plan_node = nullptr;\n LOG_ERROR(\"Unsupported Postgres Plan Tag: %u Plan : %p\", nodeTag(plan),\n plan);\n break;\n }\n }\n\n return plan_node;\n}\n\n\/**\n * @brief Recursively destroy the nodes in a plan node tree.\n *\/\nbool PlanTransformer::CleanPlanNodeTree(planner::AbstractPlanNode* root) {\n if (!root)\n return false;\n\n \/\/ Clean all children subtrees\n auto children = root->GetChildren();\n for (auto child : children) {\n auto rv = CleanPlanNodeTree(child);\n assert(rv);\n }\n\n \/\/ Clean the root\n delete root;\n return true;\n}\n\ninline const ValueArray BuildParams(const ParamListInfo param_list) {\n ValueArray params;\n if (param_list != nullptr) {\n params.Reset(param_list->numParams);\n for (int i = 0; i < params.GetSize(); ++i) {\n ParamExternData param = param_list->params[i];\n params[i] = TupleTransformer::GetValue(param.value, param.ptype);\n }\n }\n LOG_INFO(\"Built param list of size %d\", params.GetSize());\n return params;\n}\n\n} \/\/ namespace bridge\n} \/\/ namespace peloton\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n#include <string>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <atomic>\n#include <typeinfo>\n#include <cxxabi.h>\n#include <sys\/time.h>\n#include <stdarg.h>\n\n#include <zcm\/zcm-cpp.hpp>\n#include <zcm\/util\/circular.hpp>\n\nstatic bool ZCM_DEBUG_ENABLED = (NULL != getenv(\"ZCM_DEBUG\"));\n#define ZCM_DEBUG(...) \\\n do {\\\n __ZCM_PRINT_OBFUSCATE__(std::cout, \"ZCM-DEBUG: \", __VA_ARGS__, '\\n'); \\\n } while(0)\n\ntemplate <typename T>\nclass MessageTracker\n{\n public:\n typedef void (*callback)(const T* msg, void* usr);\n\n private:\n zcm::ZCM* zcmLocal = nullptr;\n\n std::atomic_bool done {false};\n\n Circular<T> *buf;\n std::mutex bufLock;\n std::condition_variable newMsg;\n zcm::Subscription *s;\n\n std::thread *thr = nullptr;\n callback onMsg;\n void* usr;\n\n uint64_t maxTimeErr_us;\n\n void callbackThreadFunc()\n {\n while (!done) {\n T* localMsg = get();\n if (done) return;\n onMsg(localMsg, usr);\n }\n }\n\n void handle(const zcm::ReceiveBuffer* rbuf, const std::string& chan, const T* _msg)\n {\n if (done)\n return;\n\n T* tmp = new T(*_msg);\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n\n if (buf->isFull())\n buf->removeFront();\n\n while (!buf->isEmpty()) {\n if (getMsgUtime(buf->front()) + maxTimeErr_us > getMsgUtime(_msg))\n break;\n buf->removeFront();\n }\n\n buf->pushBack(tmp);\n }\n newMsg.notify_all();\n }\n\n MessageTracker() {}\n\n protected:\n virtual uint64_t getMsgUtime(const T* msg)\n {\n return hasUtime<T>::utime(msg);\n }\n\n virtual T* interpolate(uint64_t utimeTarget,\n const T* A, uint64_t utimeA,\n const T* B, uint64_t utimeB)\n {\n return utimeTarget - utimeA < utimeB - utimeTarget ? new T(*A) : new T(*B);\n }\n\n public:\n static const bool NONBLOCKING = false;\n static const bool BLOCKING = true;\n\n MessageTracker(zcm::ZCM* zcmLocal, std::string channel,\n uint64_t maxTimeErr_us = 0.25e6, size_t maxMsgs = 1,\n callback onMsg = nullptr, void* usr = nullptr)\n : zcmLocal(zcmLocal), maxTimeErr_us(maxTimeErr_us), onMsg(onMsg), usr(usr)\n {\n if (hasUtime<T>::present == true) {\n T tmp;\n std::string name = demangle(getType(tmp));\n ZCM_DEBUG(\"Message trackers using 'utime' field of zcmtype \", name);\n } else {\n T tmp;\n std::string name = demangle(getType(tmp));\n ZCM_DEBUG(\"Message trackers using local system receive utime for \",\n \"tracking zcmtype \", name);\n }\n buf = new Circular<T>(maxMsgs);\n if (onMsg != nullptr)\n thr = new std::thread(&MessageTracker<T>::callbackThreadFunc, this);\n s = zcmLocal->subscribe(channel, &MessageTracker<T>::handle, this);\n }\n\n virtual ~MessageTracker()\n {\n zcmLocal->unsubscribe(s);\n done = true;\n newMsg.notify_all();\n if (thr) {\n thr->join();\n delete thr;\n }\n while (!buf->isEmpty())\n buf->removeFront();\n delete buf;\n }\n\n \/\/ You must free the memory returned here\n virtual T* get(bool blocking = NONBLOCKING)\n {\n T* ret = nullptr;\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n if (blocking == BLOCKING) {\n if (buf->isEmpty())\n newMsg.wait(lk, [&]{ return !buf->isEmpty() || done; });\n if (done) return nullptr;\n }\n if (!buf->isEmpty())\n ret = new T(*buf->back());\n }\n\n return ret;\n }\n\n virtual T* get(uint64_t utime, bool blocking = NONBLOCKING)\n {\n T *m0 = nullptr, *m1 = nullptr; \/\/ two poses bracketing the desired utime\n uint64_t m0Utime, m1Utime;\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n\n if (blocking == BLOCKING) {\n if (buf->isEmpty())\n newMsg.wait(lk, [&]{ return !buf->isEmpty() || done; });\n if (done) return nullptr;\n }\n\n size_t size = buf->size();\n\n const T *_m0 = nullptr;\n const T *_m1 = nullptr;\n\n for (size_t i = 0; i < size; ++i) {\n const T* m = (*buf)[i];\n uint64_t mUtime = getMsgUtime(m);\n\n if (mUtime <= utime && (_m0 == nullptr || mUtime > m0Utime)) {\n _m0 = m;\n m0Utime = getMsgUtime(_m0);\n }\n\n if (mUtime >= utime && (_m1 == nullptr || mUtime < m1Utime)) {\n _m1 = m;\n m1Utime = getMsgUtime(_m1);\n }\n }\n\n if (_m0 != nullptr)\n m0 = new T(*_m0);\n\n if (_m1 != nullptr)\n m1 = new T(*_m1);\n\n }\n\n if (m0 && utime - m0Utime > maxTimeErr_us) {\n delete m0;\n m0 = nullptr;\n }\n\n if (m1 && m1Utime - utime > maxTimeErr_us) {\n delete m1;\n m1 = nullptr;\n }\n\n if (m0 && m1) {\n if (m0Utime == m1Utime) {\n delete m1;\n return m0;\n }\n\n T* elt = interpolate(utime, m0, m0Utime, m1, m1Utime);\n\n delete m0;\n delete m1;\n\n return elt;\n }\n\n if (m0) return m0;\n if (m1) return m1;\n\n return nullptr;\n }\n\n private:\n \/\/ *****************************************************************************\n \/\/ Insanely hacky trick to determine at compile time if a zcmtype has a\n \/\/ field called \"utime\"\n template <typename F> struct hasUtime {\n struct Fallback { void* utime; }; \/\/ introduce member name \"utime\"\n struct Derived : F, Fallback {};\n\n template <typename C, C> struct ChT;\n\n template <typename C>\n static uint64_t _utime(ChT<void* Fallback::*, &C::utime>*, const F* msg)\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (uint64_t)tv.tv_sec * 1000000 + tv.tv_usec;\n };\n template <typename C>\n static uint64_t _utime(void*, ...)\n {\n va_list args;\n va_start(args, 1);\n const F* msg = va_arg(args, const F*);\n va_end(args);\n return msg->utime;\n }\n\n template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];\n template<typename C> static char (&f(...))[2];\n\n static bool const present = sizeof(f<Derived>(0)) == 2;\n\n static uint64_t const utime(const F* msg)\n {\n return _utime<Derived>(0,msg);\n }\n };\n\n template<typename F>\n static inline std::string getType(const F t) { return typeid(t).name(); }\n\n static inline std::string demangle(std::string name)\n {\n int status = -4; \/\/ some arbitrary value to eliminate the compiler warning\n std::unique_ptr<char, void(*)(void*)> res {\n abi::__cxa_demangle(name.c_str(), NULL, NULL, &status),\n std::free\n };\n return (status==0) ? res.get() : name ;\n }\n\n static void __ZCM_PRINT_OBFUSCATE__(std::ostream& o) { }\n\n template<typename First, typename ...Rest>\n static void __ZCM_PRINT_OBFUSCATE__(std::ostream& o, First && first, Rest && ...rest)\n {\n o << std::forward<First>(first);\n __ZCM_PRINT_OBFUSCATE__(o, std::forward<Rest>(rest)...);\n }\n \/\/ *****************************************************************************\n\n};\n\n#undef ZCM_DEBUG\n<commit_msg>Printing only when printing enabled<commit_after>#pragma once\n\n#include <iostream>\n#include <string>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <atomic>\n#include <typeinfo>\n#include <cxxabi.h>\n#include <sys\/time.h>\n#include <stdarg.h>\n\n#include <zcm\/zcm-cpp.hpp>\n#include <zcm\/util\/circular.hpp>\n\nstatic bool ZCM_DEBUG_ENABLED = (NULL != getenv(\"ZCM_DEBUG\"));\n#define ZCM_DEBUG(...) \\\n do { \\\n if (ZCM_DEBUG_ENABLED) \\\n __ZCM_PRINT_OBFUSCATE__(std::cout, \"ZCM-DEBUG: \", __VA_ARGS__, '\\n'); \\\n } while(0)\n\ntemplate <typename T>\nclass MessageTracker\n{\n public:\n typedef void (*callback)(const T* msg, void* usr);\n\n private:\n zcm::ZCM* zcmLocal = nullptr;\n\n std::atomic_bool done {false};\n\n Circular<T> *buf;\n std::mutex bufLock;\n std::condition_variable newMsg;\n zcm::Subscription *s;\n\n std::thread *thr = nullptr;\n callback onMsg;\n void* usr;\n\n uint64_t maxTimeErr_us;\n\n void callbackThreadFunc()\n {\n while (!done) {\n T* localMsg = get();\n if (done) return;\n onMsg(localMsg, usr);\n }\n }\n\n void handle(const zcm::ReceiveBuffer* rbuf, const std::string& chan, const T* _msg)\n {\n if (done)\n return;\n\n T* tmp = new T(*_msg);\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n\n if (buf->isFull())\n buf->removeFront();\n\n while (!buf->isEmpty()) {\n if (getMsgUtime(buf->front()) + maxTimeErr_us > getMsgUtime(_msg))\n break;\n buf->removeFront();\n }\n\n buf->pushBack(tmp);\n }\n newMsg.notify_all();\n }\n\n MessageTracker() {}\n\n protected:\n virtual uint64_t getMsgUtime(const T* msg)\n {\n return hasUtime<T>::utime(msg);\n }\n\n virtual T* interpolate(uint64_t utimeTarget,\n const T* A, uint64_t utimeA,\n const T* B, uint64_t utimeB)\n {\n return utimeTarget - utimeA < utimeB - utimeTarget ? new T(*A) : new T(*B);\n }\n\n public:\n static const bool NONBLOCKING = false;\n static const bool BLOCKING = true;\n\n MessageTracker(zcm::ZCM* zcmLocal, std::string channel,\n uint64_t maxTimeErr_us = 0.25e6, size_t maxMsgs = 1,\n callback onMsg = nullptr, void* usr = nullptr)\n : zcmLocal(zcmLocal), maxTimeErr_us(maxTimeErr_us), onMsg(onMsg), usr(usr)\n {\n if (hasUtime<T>::present == true) {\n T tmp;\n std::string name = demangle(getType(tmp));\n ZCM_DEBUG(\"Message trackers using 'utime' field of zcmtype \", name);\n } else {\n T tmp;\n std::string name = demangle(getType(tmp));\n ZCM_DEBUG(\"Message trackers using local system receive utime for \",\n \"tracking zcmtype \", name);\n }\n buf = new Circular<T>(maxMsgs);\n if (onMsg != nullptr)\n thr = new std::thread(&MessageTracker<T>::callbackThreadFunc, this);\n s = zcmLocal->subscribe(channel, &MessageTracker<T>::handle, this);\n }\n\n virtual ~MessageTracker()\n {\n zcmLocal->unsubscribe(s);\n done = true;\n newMsg.notify_all();\n if (thr) {\n thr->join();\n delete thr;\n }\n while (!buf->isEmpty())\n buf->removeFront();\n delete buf;\n }\n\n \/\/ You must free the memory returned here\n virtual T* get(bool blocking = NONBLOCKING)\n {\n T* ret = nullptr;\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n if (blocking == BLOCKING) {\n if (buf->isEmpty())\n newMsg.wait(lk, [&]{ return !buf->isEmpty() || done; });\n if (done) return nullptr;\n }\n if (!buf->isEmpty())\n ret = new T(*buf->back());\n }\n\n return ret;\n }\n\n virtual T* get(uint64_t utime, bool blocking = NONBLOCKING)\n {\n T *m0 = nullptr, *m1 = nullptr; \/\/ two poses bracketing the desired utime\n uint64_t m0Utime, m1Utime;\n\n {\n std::unique_lock<std::mutex> lk(bufLock);\n\n if (blocking == BLOCKING) {\n if (buf->isEmpty())\n newMsg.wait(lk, [&]{ return !buf->isEmpty() || done; });\n if (done) return nullptr;\n }\n\n size_t size = buf->size();\n\n const T *_m0 = nullptr;\n const T *_m1 = nullptr;\n\n for (size_t i = 0; i < size; ++i) {\n const T* m = (*buf)[i];\n uint64_t mUtime = getMsgUtime(m);\n\n if (mUtime <= utime && (_m0 == nullptr || mUtime > m0Utime)) {\n _m0 = m;\n m0Utime = getMsgUtime(_m0);\n }\n\n if (mUtime >= utime && (_m1 == nullptr || mUtime < m1Utime)) {\n _m1 = m;\n m1Utime = getMsgUtime(_m1);\n }\n }\n\n if (_m0 != nullptr)\n m0 = new T(*_m0);\n\n if (_m1 != nullptr)\n m1 = new T(*_m1);\n\n }\n\n if (m0 && utime - m0Utime > maxTimeErr_us) {\n delete m0;\n m0 = nullptr;\n }\n\n if (m1 && m1Utime - utime > maxTimeErr_us) {\n delete m1;\n m1 = nullptr;\n }\n\n if (m0 && m1) {\n if (m0Utime == m1Utime) {\n delete m1;\n return m0;\n }\n\n T* elt = interpolate(utime, m0, m0Utime, m1, m1Utime);\n\n delete m0;\n delete m1;\n\n return elt;\n }\n\n if (m0) return m0;\n if (m1) return m1;\n\n return nullptr;\n }\n\n private:\n \/\/ *****************************************************************************\n \/\/ Insanely hacky trick to determine at compile time if a zcmtype has a\n \/\/ field called \"utime\"\n template <typename F> struct hasUtime {\n struct Fallback { void* utime; }; \/\/ introduce member name \"utime\"\n struct Derived : F, Fallback {};\n\n template <typename C, C> struct ChT;\n\n template <typename C>\n static uint64_t _utime(ChT<void* Fallback::*, &C::utime>*, const F* msg)\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (uint64_t)tv.tv_sec * 1000000 + tv.tv_usec;\n };\n template <typename C>\n static uint64_t _utime(void*, ...)\n {\n va_list args;\n va_start(args, 1);\n const F* msg = va_arg(args, const F*);\n va_end(args);\n return msg->utime;\n }\n\n template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];\n template<typename C> static char (&f(...))[2];\n\n static bool const present = sizeof(f<Derived>(0)) == 2;\n\n static uint64_t const utime(const F* msg)\n {\n return _utime<Derived>(0,msg);\n }\n };\n\n template<typename F>\n static inline std::string getType(const F t) { return typeid(t).name(); }\n\n static inline std::string demangle(std::string name)\n {\n int status = -4; \/\/ some arbitrary value to eliminate the compiler warning\n std::unique_ptr<char, void(*)(void*)> res {\n abi::__cxa_demangle(name.c_str(), NULL, NULL, &status),\n std::free\n };\n return (status==0) ? res.get() : name ;\n }\n\n static void __ZCM_PRINT_OBFUSCATE__(std::ostream& o) { }\n\n template<typename First, typename ...Rest>\n static void __ZCM_PRINT_OBFUSCATE__(std::ostream& o, First && first, Rest && ...rest)\n {\n o << std::forward<First>(first);\n __ZCM_PRINT_OBFUSCATE__(o, std::forward<Rest>(rest)...);\n }\n \/\/ *****************************************************************************\n\n};\n\n#undef ZCM_DEBUG\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-07-26 13:27\n * Last modified : 2017-07-26 13:27\n * Filename : MatrixOperator.cpp\n * Description : \n **********************************************\/\n\n#include <string.h>\n#include \"algebra\/Matrix.h\"\n#include \"utils\/ParallelOperator.h\"\n\n\nusing abcdl::utils::ParallelOperator;\n\nnamespace abcdl{\nnamespace algebra{\n\ntemplate<class T>\nT& Matrix<T>::operator [] (const size_t idx) const{\n CHECK(idx < get_size());\n\treturn _data[idx];\n}\n\ntemplate<class T>\nbool Matrix<T>::operator == (const Matrix<T>& mat) const{\n\tif(this == &mat){\n\t\treturn true;\n\t}\n\tif(get_size() != mat.get_size()){\n\t\treturn false;\n\t}\n\n bool result_value = true;\n auto lamda = [](bool* a, const T& b, const T& c){*a = (b == c);};\n utils::ParallelOperator po;\n po.parallel_reduce_boolean<T>(&result_value, _data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn result_value;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator = (const T& value){\n reset(value);\n return *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator = (const Matrix<T>& mat){\n if(this != &mat){\n if(get_size() != mat.get_size()){\n if(_data != nullptr){\n delete[] _data;\n }\n \t_data = new T[mat.get_size()];\n }\n\n _rows = mat.rows();\n _cols = mat.cols();\n memcpy(_data, mat.data(), sizeof(T) * mat.get_size());\n }\n return *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator + (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), mat.get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator + (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), mat.get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator += (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 0){ *a += b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n return *this;\n}\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator += (const Matrix<T>& mat){\n if(get_size() == 0){\n set_data(mat);\n return *this;\n }\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n return *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator - (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), mat.get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator - (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator -= (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda); \n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator -= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator * (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 0){*a *= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator * (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ *a *= b; };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), get_size(), mat.data(), mat.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator *= (const T& value){\n auto lamda = [](T* a, const T& b){ *a *= b; };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator *= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ *a *= b; };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator \/ (const T& value) const{\n auto lamda = [](T* a, const T& b){ *a \/= b; };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator \/ (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ *a \/= b; };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), mat.get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator \/= (const T& value){\n auto lamda = [](T* a, const T& b){ *a \/= b; };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator \/= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ *a \/= b; };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\n\ntemplate class Matrix<int>;\ntemplate class Matrix<float>;\ntemplate class Matrix<double>;\n}\/\/namespace algebra\n}\/\/namespace abcdl\n<commit_msg>initialized<commit_after>\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-07-26 13:27\n * Last modified : 2017-07-26 13:27\n * Filename : MatrixOperator.cpp\n * Description : \n **********************************************\/\n\n#include <string.h>\n#include \"algebra\/Matrix.h\"\n#include \"utils\/ParallelOperator.h\"\n\n\nusing abcdl::utils::ParallelOperator;\n\nnamespace abcdl{\nnamespace algebra{\n\ntemplate<class T>\nT& Matrix<T>::operator [] (const size_t idx) const{\n CHECK(idx < get_size());\n\treturn _data[idx];\n}\n\ntemplate<class T>\nbool Matrix<T>::operator == (const Matrix<T>& mat) const{\n\tif(this == &mat){\n\t\treturn true;\n\t}\n\tif(get_size() != mat.get_size()){\n\t\treturn false;\n\t}\n\n bool result_value = true;\n auto lamda = [](bool* a, const T& b, const T& c){*a = (b == c);};\n utils::ParallelOperator po;\n po.parallel_reduce_boolean<T>(&result_value, _data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn result_value;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator = (const T& value){\n reset(value);\n return *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator = (const Matrix<T>& mat){\n if(this != &mat){\n if(get_size() != mat.get_size()){\n if(_data != nullptr){\n delete[] _data;\n }\n \t_data = new T[mat.get_size()];\n }\n\n _rows = mat.rows();\n _cols = mat.cols();\n memcpy(_data, mat.data(), sizeof(T) * mat.get_size());\n }\n return *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator + (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), mat.get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator + (const Matrix<T>& mat_a) const{\n Matrix<T> mat;\n if(get_size() == 0){\n mat.set_data(mat_a);\n return mat;\n }\n\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul_repeat<T>(mat.data(), mat.get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator += (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 0){ *a += b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n return *this;\n}\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator += (const Matrix<T>& mat){\n if(get_size() == 0){\n set_data(mat);\n return *this;\n }\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a += b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n return *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator - (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), mat.get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator - (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator -= (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda); \n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator -= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 0){*a -= b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator * (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 1){*a *= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator * (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 1){*a *= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul_repeat<T>(mat.data(), get_size(), mat.data(), mat.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator *= (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 1){*a *= b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator *= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 1){*a *= b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator \/ (const T& value) const{\n auto lamda = [](T* a, const T& b){ if(b != 1){*a \/= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2one<T>(mat.data(), get_size(), value, lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T> Matrix<T>::operator \/ (const Matrix<T>& mat_a) const{\n CHECK(equal_shape(mat_a));\n auto lamda = [](T* a, const T& b){ if(b != 1){ *a \/= b;} };\n Matrix<T> mat;\n clone(mat);\n ParallelOperator po;\n po.parallel_mul2mul<T>(mat.data(), mat.get_size(), mat_a.data(), mat_a.get_size(), lamda);\n return mat;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator \/= (const T& value){\n auto lamda = [](T* a, const T& b){ if(b != 1){*a \/= b;} };\n ParallelOperator po;\n po.parallel_mul2one<T>(_data, get_size(), value, lamda);\n\treturn *this;\n}\n\ntemplate<class T>\nMatrix<T>& Matrix<T>::operator \/= (const Matrix<T>& mat){\n CHECK(equal_shape(mat));\n auto lamda = [](T* a, const T& b){ if(b != 1){*a \/= b;} };\n ParallelOperator po;\n po.parallel_mul2mul<T>(_data, get_size(), mat.data(), mat.get_size(), lamda);\n\treturn *this;\n}\n\n\ntemplate class Matrix<int>;\ntemplate class Matrix<float>;\ntemplate class Matrix<double>;\n}\/\/namespace algebra\n}\/\/namespace abcdl\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n#define DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalEvaluation {\n\n\ntemplate< class DiffusionFactorType, class DiffusionTensorType >\nclass Elliptic\n : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< DiffusionFactorType, DiffusionTensorType >, 2 >\n{\npublic:\n typedef internal::EllipticTraits< DiffusionFactorType, DiffusionTensorType > Traits;\n\n Elliptic(const DiffusionFactorType& diffusion_factor,\n const DiffusionTensorType& diffusion_tensor)\n : diffusion_factor_(diffusion_factor)\n , diffusion_tensor_(diffusion_tensor)\n {}\n\n template< class EntityType >\n class LocalfunctionTuple\n {\n typedef typename DiffusionFactorType::LocalfunctionType LocalDiffusionFactorFunctionType;\n typedef typename DiffusionTensorType::LocalfunctionType LocalDiffusionTensorFunctionType;\n public:\n typedef std::tuple< std::shared_ptr< LocalDiffusionFactorFunctionType >\n , std::shared_ptr< LocalDiffusionTensorFunctionType > > Type;\n }; \/\/ class LocalfunctionTuple\n\n template< class EntityType >\n typename LocalfunctionTuple< EntityType >::Type localFunctions(const EntityType& entity) const\n {\n return std::make_tuple(diffusion_factor_.local_function(entity),\n diffusion_tensor_.local_function(entity));\n } \/\/ ... localFunctions(...)\n\n \/**\n * \\brief extracts the local functions and calls the correct order() method\n *\/\n template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA >\n size_t order(const typename LocalfunctionTuple< E >::Type& local_functions_tuple,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const\n {\n const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n return order(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase);\n } \/\/ ... order(...)\n\n template< class E, class D, int d, class R, int rDF, int rCDF, int rDT, int rCDT, int rT, int rCT, int rA, int rCA >\n size_t order(const Stuff::LocalfunctionInterface< E, D, d, R, rDF, rCDF >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< E, D, d, R, rDT, rCDT >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const\n {\n return local_diffusion_factor.order()\n + local_diffusion_tensor.order()\n + std::max(ssize_t(testBase.order()) - 1, ssize_t(0))\n + std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0));\n } \/\/ ... order(...)\n\n \/**\n * \\brief extracts the local functions and calls the correct evaluate() method\n *\/\n template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA >\n void evaluate(const typename LocalfunctionTuple< E >::Type& local_functions_tuple,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase,\n const Dune::FieldVector< D, d >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n evaluate(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\n template< class E, class D, int d, class R, int rDF, int rCDF, int rDT, int rCDT, int rT, int rCT, int rA, int rCA >\n void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, rDF, rCDF >& \/*local_diffusion_factor*\/,\n const Stuff::LocalfunctionInterface< E, D, d, R, rDT, rCDT >& \/*local_diffusion_tensor*\/,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& \/*testBase*\/,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& \/*ansatzBase*\/,\n const Dune::FieldVector< D, d >& \/*localPoint*\/,\n Dune::DynamicMatrix< R >& \/*ret*\/) const\n {\n static_assert(Dune::AlwaysFalse< R >::value, \"Not implemented for these dimensions!\");\n }\n\n template< class E, class D, int d, class R, int r >\n void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& ansatzBase,\n const Dune::FieldVector< D, d >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >::JacobianRangeType JacobianRangeType;\n \/\/ evaluate local functions\n const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n const auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n \/\/ evaluate test gradient\n const size_t rows = testBase.size();\n std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n testBase.jacobian(localPoint, testGradients);\n \/\/ evaluate ansatz gradient\n const size_t cols = ansatzBase.size();\n std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n ansatzBase.jacobian(localPoint, ansatzGradients);\n \/\/ compute products\n assert(ret.rows() >= rows);\n assert(ret.cols() >= cols);\n for (size_t ii = 0; ii < rows; ++ii) {\n auto& retRow = ret[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n retRow[jj] = local_diffusion_factor_value * local_diffusion_tensor_value\n * (ansatzGradients[jj][0] * testGradients[ii][0]);\n }\n }\n } \/\/ ... evaluate< ..., 1, 1 >(...)\n\n template< class E, class D, int d, class R >\n void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< E, D, d, R, 2, 2 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< D, d >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\n template< class E, class D, int d, class R >\n void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< E, D, d, R, 3, 3 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< D, d >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\nprivate:\n template< class E, class D, int d, class R >\n void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< E, D, d, R, d, d >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< D, d >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >::JacobianRangeType JacobianRangeType;\n \/\/ evaluate local functions\n const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n local_diffusion_tensor_value *= local_diffusion_factor_value[0];\n \/\/ evaluate test gradient\n const size_t rows = testBase.size();\n std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n testBase.jacobian(localPoint, testGradients);\n \/\/ evaluate ansatz gradient\n const size_t cols = ansatzBase.size();\n std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n ansatzBase.jacobian(localPoint, ansatzGradients);\n \/\/ compute products\n assert(ret.rows() >= rows);\n assert(ret.cols() >= cols);\n FieldVector< D, d > product(0.0);\n for (size_t ii = 0; ii < rows; ++ii) {\n auto& retRow = ret[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n local_diffusion_tensor_value.mv(ansatzGradients[jj][0], product);\n retRow[jj] = product * testGradients[ii][0];\n }\n }\n } \/\/ ... evaluate_matrix_valued_(...)\n\n const DiffusionFactorType& diffusion_factor_;\n const DiffusionTensorType& diffusion_tensor_;\n}; \/\/ class LocalElliptic\n\n\n} \/\/ namespace Evaluation\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n<commit_msg>[playground.localevaluation.elliptic] adapt to interface changes<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n#define DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalEvaluation {\n\n\ntemplate< class DiffusionFactorImp, class DiffusionTensorImp >\nclass Elliptic\n : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< DiffusionFactorImp, DiffusionTensorImp >, 2 >\n{\npublic:\n typedef internal::EllipticTraits< DiffusionFactorImp, DiffusionTensorImp > Traits;\n typedef typename Traits::LocalizableDiffusionFactorFunctionType LocalizableDiffusionFactorFunctionType;\n typedef typename Traits::LocalizableDiffusionTensorFunctionType LocalizableDiffusionTensorFunctionType;\n typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;\n typedef typename Traits::EntityType EntityType;\n typedef typename Traits::DomainFieldType DomainFieldType;\n static const unsigned int dimDomain = Traits::dimDomain;\n\n Elliptic(const LocalizableDiffusionFactorFunctionType& diffusion_factor,\n const LocalizableDiffusionTensorFunctionType& diffusion_tensor)\n : diffusion_factor_(diffusion_factor)\n , diffusion_tensor_(diffusion_tensor)\n {}\n\n LocalfunctionTupleType localFunctions(const EntityType& entity) const\n {\n return std::make_tuple(diffusion_factor_.local_function(entity),\n diffusion_tensor_.local_function(entity));\n } \/\/ ... localFunctions(...)\n\n \/**\n * \\brief extracts the local functions and calls the correct order() method\n *\/\n template< class R, int rT, int rCT, int rA, int rCA >\n size_t order(const LocalfunctionTupleType& local_functions_tuple,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rA, rCA >& ansatzBase) const\n {\n const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n return order(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase);\n } \/\/ ... order(...)\n\n \/**\n * \\brief extracts the local functions and calls the correct evaluate() method\n *\/\n template< class R, int rT, int rCT, int rA, int rCA >\n void evaluate(const LocalfunctionTupleType& local_functions_tuple,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rA, rCA >& ansatzBase,\n const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n evaluate(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\nprivate:\n template< class R, int rDF, int rCDF, int rDT, int rCDT, int rT, int rCT, int rA, int rCA >\n size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, rDF, rCDF >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, rDT, rCDT >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rT, rCT >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rA, rCA >& ansatzBase) const\n {\n return local_diffusion_factor.order()\n + local_diffusion_tensor.order()\n + std::max(ssize_t(testBase.order()) - 1, ssize_t(0))\n + std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0));\n } \/\/ ... order(...)\n\n template< class R, int rDF, int rCDF, int rDT, int rCDT, int rT, int rCT, int rA, int rCA >\n void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, rDF, rCDF >& \/*local_diffusion_factor*\/,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, rDT, rCDT >& \/*local_diffusion_tensor*\/,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rT, rCT >& \/*testBase*\/,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, rA, rCA >& \/*ansatzBase*\/,\n const Dune::FieldVector< DomainFieldType, dimDomain >& \/*localPoint*\/,\n Dune::DynamicMatrix< R >& \/*ret*\/) const\n {\n static_assert(Dune::AlwaysFalse< R >::value, \"Not implemented for these dimensions!\");\n } \/\/ ... evaluate< ... >(...)\n\n template< class R, int r >\n void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, r, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, r, 1 >& ansatzBase,\n const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n typedef typename Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, r, 1 >::JacobianRangeType JacobianRangeType;\n \/\/ evaluate local functions\n const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n const auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n \/\/ evaluate test gradient\n const size_t rows = testBase.size();\n std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n testBase.jacobian(localPoint, testGradients);\n \/\/ evaluate ansatz gradient\n const size_t cols = ansatzBase.size();\n std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n ansatzBase.jacobian(localPoint, ansatzGradients);\n \/\/ compute products\n assert(ret.rows() >= rows);\n assert(ret.cols() >= cols);\n for (size_t ii = 0; ii < rows; ++ii) {\n auto& retRow = ret[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n retRow[jj] = local_diffusion_factor_value * local_diffusion_tensor_value\n * (ansatzGradients[jj][0] * testGradients[ii][0]);\n }\n }\n } \/\/ ... evaluate< ..., 1, 1 >(...)\n\n template< class R >\n void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 2, 2 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\n template< class R >\n void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 3, 3 >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n }\n\n template< class R >\n void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& local_diffusion_factor,\n const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain\n , R, dimDomain, dimDomain >& local_diffusion_tensor,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& testBase,\n const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >& ansatzBase,\n const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n Dune::DynamicMatrix< R >& ret) const\n {\n typedef typename Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain\n , R, 1, 1 >::JacobianRangeType JacobianRangeType;\n \/\/ evaluate local functions\n const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n local_diffusion_tensor_value *= local_diffusion_factor_value[0];\n \/\/ evaluate test gradient\n const size_t rows = testBase.size();\n std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n testBase.jacobian(localPoint, testGradients);\n \/\/ evaluate ansatz gradient\n const size_t cols = ansatzBase.size();\n std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n ansatzBase.jacobian(localPoint, ansatzGradients);\n \/\/ compute products\n assert(ret.rows() >= rows);\n assert(ret.cols() >= cols);\n FieldVector< DomainFieldType, dimDomain > product(0.0);\n for (size_t ii = 0; ii < rows; ++ii) {\n auto& retRow = ret[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n local_diffusion_tensor_value.mv(ansatzGradients[jj][0], product);\n retRow[jj] = product * testGradients[ii][0];\n }\n }\n } \/\/ ... evaluate_matrix_valued_(...)\n\n const LocalizableDiffusionFactorFunctionType& diffusion_factor_;\n const LocalizableDiffusionTensorFunctionType& diffusion_tensor_;\n}; \/\/ class LocalElliptic\n\n\n} \/\/ namespace Evaluation\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PLAYGROUND_EVALUATION_ELLIPTIC_HH\n<|endoftext|>"} {"text":"<commit_before><commit_msg>[FIXED] 打包时picture的offset没有乘scale系数<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ GUI.cpp\n\/\/ 29. April 2017\n\/\/ Created by:\n\/\/ \t\tBryan Burkhardt (bmburkhardt@alaska.edu) \n\/\/ \t\tAlexander Eckert (aeckert@alaska.edu) \n\/\/ \t\tJeremiah Jacobson (jjjacobson2@alaska.edu) \n\/\/ \t\tJarye Murphy (@alaska.edu)\n\/\/ \t\tCameron Showalter (@alaska.edu) \n\/\/\n\/\/ Source file for GUI class\n\n#include <SFML\/Graphics.hpp>\n#include <SFML\/Audio.hpp>\n#include <iostream>\n\n#include \"..\/include\/textureManager.hpp\"\n#include \"..\/include\/GUI.hpp\"\n\nGUI::GUI(std::shared_ptr<Music> music) : music(music) {\n\tstd::cout << \"ctor GUI\\n\";\n\ttexmgr = std::make_unique<TextureManager>();\n\tloadTextures();\n\twindow.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), \"MusicPlayer\",\n\t\tsf::Style::Titlebar | sf::Style::Close);\n\tsetTextures();\n\n}\n\nbool GUI::clickInSprite(sf::Sprite s, int x , int y) {\n\tif (x > s.getGlobalBounds().left && x <\n\t\t\t(s.getGlobalBounds().left + s.getGlobalBounds().width) &&\n\t\t\ty > s.getGlobalBounds().top && y < (s.getGlobalBounds().top\n\t\t\t+ s.getGlobalBounds().height)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nstd::string GUI::trimFilename(const std::string& str) {\n std::size_t found = str.find_last_of(\"\/\\\\\");\n return str.substr(found+1);\n}\n\nvoid GUI::draw() {\n\twindow.clear(sf::Color::Green);\n\n\t\/\/ draw buttons\n\twindow.draw(musicPlayerBG );\n\twindow.draw(playPauseButton);\t\t\t\/\/0\n\twindow.draw(prevButton); \t\t\t\t\/\/1\n\twindow.draw(nextButton);\t\t\t\t\/\/2\n\twindow.draw(muteButton); \t\t\t\t\/\/3\n\twindow.draw(increaseVolumeButton);\t\t\/\/4\n\twindow.draw(decreaseVolumeButton);\t\t\/\/5\n\n\twindow.draw(prevSong);\n\twindow.draw(currentSong);\n\twindow.draw(nextSong);\n\twindow.draw(next2Song);\n\twindow.draw(next3Song);\n\twindow.draw(next4Song);\n\twindow.display();\n\n\treturn;\n}\n\nvoid GUI::loadTextures() {\n\ttexmgr->loadTexture(\"musicPlayerBGTex\", \"..\/res\/background\/musicplayerbg.png\");\n\ttexmgr->loadTexture(\"playTex\", \"..\/res\/icons\/play.png\");\n\ttexmgr->loadTexture(\"pauseTex\", \"..\/res\/icons\/pause.png\");\n\ttexmgr->loadTexture(\"prevTex\", \"..\/res\/icons\/previous.png\");\n\ttexmgr->loadTexture(\"nextTex\", \"..\/res\/icons\/next.png\");\n\ttexmgr->loadTexture(\"decreaseVolumeTex\", \"..\/res\/icons\/volume_down.png\");\n\ttexmgr->loadTexture(\"increaseVolumeTex\", \"..\/res\/icons\/volume_up.png\");\n\ttexmgr->loadTexture(\"muteTex\", \"..\/res\/icons\/mute.png\");\n\ttexmgr->loadTexture(\"playTex2\", \"..\/res\/icons\/play2.png\");\n\ttexmgr->loadTexture(\"pauseTex2\", \"..\/res\/icons\/pause2.png\");\n\ttexmgr->loadTexture(\"prevTex2\", \"..\/res\/icons\/previous2.png\");\n\ttexmgr->loadTexture(\"nextTex2\", \"..\/res\/icons\/next2.png\");\n\ttexmgr->loadTexture(\"decreaseVolumeTex2\", \"..\/res\/icons\/volume_down2.png\");\n\ttexmgr->loadTexture(\"increaseVolumeTex2\", \"..\/res\/icons\/volume_up2.png\");\n\ttexmgr->loadTexture(\"muteTexv2\", \"..\/res\/icons\/mutev2.png\");\n\ttexmgr->loadTexture(\"muteTex2\", \"..\/res\/icons\/mute2.png\");\n\ttexmgr->loadTexture(\"muteTexv22\", \"..\/res\/icons\/mutev2-2.png\");\n\tstd::cout << \"Textures loaded\" << std::endl;\n}\n\nvoid GUI::setTextures() {\n\tspriteVec = { \n\t\tplayPauseButton,\t\t\t\/\/ 0\n\t\tprevButton, \t\t\t\t\/\/ 1\n\t\tnextButton, \t\t\t\t\/\/ 2\n\t\tmuteButton, \t\t\t\t\/\/ 3\n\t\tdecreaseVolumeButton, \t\t\/\/ 4\n\t\tincreaseVolumeButton\n\t};\n\n\t\/\/ set textures\n\tmusicPlayerBG.setTexture(this->texmgr->getRef(\"musicPlayerBGTex\"));\n\tplayPauseButton.setTexture(this->texmgr->getRef(\"pauseTex\"));\n\tprevButton.setTexture(this->texmgr->getRef(\"prevTex\"));\n\tnextButton.setTexture(this->texmgr->getRef(\"nextTex\"));\n\tmuteButton.setTexture(this->texmgr->getRef(\"muteTex\"));\n\tdecreaseVolumeButton.setTexture(this->texmgr->getRef(\"decreaseVolumeTex\"));\n\tincreaseVolumeButton.setTexture(this->texmgr->getRef(\"increaseVolumeTex\"));\n\n\t\/\/ set positions\n\tplayPauseButton.setPosition(120,210);\n\tprevButton.setPosition(30,210);\n\tnextButton.setPosition(210,210);\n\tdecreaseVolumeButton.setPosition(120,120);\n\tmuteButton.setPosition(30,120);\n\tincreaseVolumeButton.setPosition(210,120);\n}\n\nvoid GUI::stylePlaylist() {\n\tif(!font.loadFromFile(\"..\/res\/fonts\/TravelingTypewriter.ttf\"))\n\t\tstd::cout << \"Font couldn't be found\" << std::endl;\n\telse \n\t\tstd::cout << \"Font was found\" << std::endl;\n\n\ttextVec = {\n\t\tprevSong,\n\t\tcurrentSong,\n\t\tnextSong,\n\t\tnext2Song,\n\t\tnext3Song,\n\t\tnext4Song\n\t};\n\n\tint counter = 35;\n\tfor(auto i=0; textVec.size()-1; ++i) {\n\t\ttextVec[i].setFont(font);\n\t\ttextVec[i].setCharacterSize(24);\n\t\tif(i == 1)\n\t\t\ttextVec[i].setColor(sf::Color::Blue);\n\t\telse\n\t\t\ttextVec[i].setColor(sf::Color::Black);\n\t\ttextVec[i].setPosition(360,counter);\n\t\tcounter += 25;\n\t}\n}\n\nvoid GUI::displayPlaylist() {\n\tif (music->songListIndex_ == 0) {\n\t\tprevSong.setString(trimFilename(music->songList_[music->songList_.size() - 1]));\n\t}\n\telse {\n\t\tprevSong.setString(trimFilename(music->songList_[music->songListIndex_ - 1]));\n\t}\n\n\tcurrentSong.setString(trimFilename(music->songList_[music->songListIndex_]));\n\n\tif (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnextSong.setString(trimFilename(music->songList_[0]));\n\t}\n\telse {\n\t\tnextSong.setString(trimFilename(music->songList_[music->songListIndex_ + 1]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext2Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext2Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse {\n\t\tnext2Song.setString(trimFilename(music->songList_[music->songListIndex_ + 2]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 3) {\n\t\tnext3Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext3Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext3Song.setString(trimFilename(music->songList_[2]));\n\t}\n\telse {\n\t\tnext3Song.setString(trimFilename(music->songList_[music->songListIndex_ + 3]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 4) {\n\t\tnext4Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 3) {\n\t\tnext4Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext4Song.setString(trimFilename(music->songList_[2]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext4Song.setString(trimFilename(music->songList_[3]));\n\t}\n\telse {\n\t\tnext4Song.setString(trimFilename(music->songList_[music->songListIndex_ + 4]));\n\t}\n}\n\nvoid GUI::update() {\n\t\/\/stylePlaylist();\n\tdisplayPlaylist();\n\treturn;\n}<commit_msg>set font in ctor<commit_after>\/\/ GUI.cpp\n\/\/ 29. April 2017\n\/\/ Created by:\n\/\/ \t\tBryan Burkhardt (bmburkhardt@alaska.edu) \n\/\/ \t\tAlexander Eckert (aeckert@alaska.edu) \n\/\/ \t\tJeremiah Jacobson (jjjacobson2@alaska.edu) \n\/\/ \t\tJarye Murphy (@alaska.edu)\n\/\/ \t\tCameron Showalter (@alaska.edu) \n\/\/\n\/\/ Source file for GUI class\n\n#include <SFML\/Graphics.hpp>\n#include <SFML\/Audio.hpp>\n#include <iostream>\n\n#include \"..\/include\/textureManager.hpp\"\n#include \"..\/include\/GUI.hpp\"\n\nGUI::GUI(std::shared_ptr<Music> music) : music(music) {\n\tstd::cout << \"ctor GUI\\n\";\n\ttexmgr = std::make_unique<TextureManager>();\n\tloadTextures();\n\twindow.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), \"MusicPlayer\",\n\t\tsf::Style::Titlebar | sf::Style::Close);\n\twindow.setFramerateLimit(60);\n\tsetTextures();\n\tif(!font.loadFromFile(\"..\/res\/fonts\/TravelingTypewriter.ttf\"))\n\t\tstd::cout << \"Font couldn't be found\" << std::endl;\n\telse\n\t\tstd::cout << \"Font was found\" << std::endl;\n}\n\nbool GUI::clickInSprite(sf::Sprite s, int x , int y) {\n\tif (x > s.getGlobalBounds().left && x <\n\t\t\t(s.getGlobalBounds().left + s.getGlobalBounds().width) &&\n\t\t\ty > s.getGlobalBounds().top && y < (s.getGlobalBounds().top\n\t\t\t+ s.getGlobalBounds().height)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nstd::string GUI::trimFilename(const std::string& str) {\n std::size_t found = str.find_last_of(\"\/\\\\\");\n return str.substr(found+1);\n}\n\nvoid GUI::draw() {\n\twindow.clear(sf::Color::Green);\n\n\t\/\/ draw buttons\n\twindow.draw(musicPlayerBG );\n\twindow.draw(playPauseButton);\t\t\t\/\/0\n\twindow.draw(prevButton); \t\t\t\t\/\/1\n\twindow.draw(nextButton);\t\t\t\t\/\/2\n\twindow.draw(muteButton); \t\t\t\t\/\/3\n\twindow.draw(increaseVolumeButton);\t\t\/\/4\n\twindow.draw(decreaseVolumeButton);\t\t\/\/5\n\n\twindow.draw(prevSong);\n\twindow.draw(currentSong);\n\twindow.draw(nextSong);\n\twindow.draw(next2Song);\n\twindow.draw(next3Song);\n\twindow.draw(next4Song);\n\twindow.display();\n\n\treturn;\n}\n\nvoid GUI::loadTextures() {\n\ttexmgr->loadTexture(\"musicPlayerBGTex\", \"..\/res\/background\/musicplayerbg.png\");\n\ttexmgr->loadTexture(\"playTex\", \"..\/res\/icons\/play.png\");\n\ttexmgr->loadTexture(\"pauseTex\", \"..\/res\/icons\/pause.png\");\n\ttexmgr->loadTexture(\"prevTex\", \"..\/res\/icons\/previous.png\");\n\ttexmgr->loadTexture(\"nextTex\", \"..\/res\/icons\/next.png\");\n\ttexmgr->loadTexture(\"decreaseVolumeTex\", \"..\/res\/icons\/volume_down.png\");\n\ttexmgr->loadTexture(\"increaseVolumeTex\", \"..\/res\/icons\/volume_up.png\");\n\ttexmgr->loadTexture(\"muteTex\", \"..\/res\/icons\/mute.png\");\n\ttexmgr->loadTexture(\"playTex2\", \"..\/res\/icons\/play2.png\");\n\ttexmgr->loadTexture(\"pauseTex2\", \"..\/res\/icons\/pause2.png\");\n\ttexmgr->loadTexture(\"prevTex2\", \"..\/res\/icons\/previous2.png\");\n\ttexmgr->loadTexture(\"nextTex2\", \"..\/res\/icons\/next2.png\");\n\ttexmgr->loadTexture(\"decreaseVolumeTex2\", \"..\/res\/icons\/volume_down2.png\");\n\ttexmgr->loadTexture(\"increaseVolumeTex2\", \"..\/res\/icons\/volume_up2.png\");\n\ttexmgr->loadTexture(\"muteTexv2\", \"..\/res\/icons\/mutev2.png\");\n\ttexmgr->loadTexture(\"muteTex2\", \"..\/res\/icons\/mute2.png\");\n\ttexmgr->loadTexture(\"muteTexv22\", \"..\/res\/icons\/mutev2-2.png\");\n\tstd::cout << \"Textures loaded\" << std::endl;\n}\n\nvoid GUI::setTextures() {\n\tspriteVec = { \n\t\tplayPauseButton,\t\t\t\/\/ 0\n\t\tprevButton, \t\t\t\t\/\/ 1\n\t\tnextButton, \t\t\t\t\/\/ 2\n\t\tmuteButton, \t\t\t\t\/\/ 3\n\t\tdecreaseVolumeButton, \t\t\/\/ 4\n\t\tincreaseVolumeButton\n\t};\n\n\t\/\/ set textures\n\tmusicPlayerBG.setTexture(this->texmgr->getRef(\"musicPlayerBGTex\"));\n\tplayPauseButton.setTexture(this->texmgr->getRef(\"pauseTex\"));\n\tprevButton.setTexture(this->texmgr->getRef(\"prevTex\"));\n\tnextButton.setTexture(this->texmgr->getRef(\"nextTex\"));\n\tmuteButton.setTexture(this->texmgr->getRef(\"muteTex\"));\n\tdecreaseVolumeButton.setTexture(this->texmgr->getRef(\"decreaseVolumeTex\"));\n\tincreaseVolumeButton.setTexture(this->texmgr->getRef(\"increaseVolumeTex\"));\n\n\t\/\/ set positions\n\tplayPauseButton.setPosition(120,210);\n\tprevButton.setPosition(30,210);\n\tnextButton.setPosition(210,210);\n\tdecreaseVolumeButton.setPosition(120,120);\n\tmuteButton.setPosition(30,120);\n\tincreaseVolumeButton.setPosition(210,120);\n}\n\nvoid GUI::stylePlaylist() {\n\ttextVec = {\n\t\tprevSong,\n\t\tcurrentSong,\n\t\tnextSong,\n\t\tnext2Song,\n\t\tnext3Song,\n\t\tnext4Song\n\t};\n\n\tint counter = 35;\n\tfor(auto i=0; i <= textVec.size()-1; ++i) {\n\t\ttextVec[i].setFont(font);\n\t\ttextVec[i].setCharacterSize(24);\n\t\tif(i == 1)\n\t\t\ttextVec[i].setColor(sf::Color::Blue);\n\t\telse\n\t\t\ttextVec[i].setColor(sf::Color::Black);\n\t\ttextVec[i].setPosition(360,counter);\n\t\tcounter += 25;\n\t}\n}\n\nvoid GUI::displayPlaylist() {\n\tif (music->songListIndex_ == 0) {\n\t\tprevSong.setString(trimFilename(music->songList_[music->songList_.size() - 1]));\n\t}\n\telse {\n\t\tprevSong.setString(trimFilename(music->songList_[music->songListIndex_ - 1]));\n\t}\n\n\tcurrentSong.setString(trimFilename(music->songList_[music->songListIndex_]));\n\n\tif (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnextSong.setString(trimFilename(music->songList_[0]));\n\t}\n\telse {\n\t\tnextSong.setString(trimFilename(music->songList_[music->songListIndex_ + 1]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext2Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext2Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse {\n\t\tnext2Song.setString(trimFilename(music->songList_[music->songListIndex_ + 2]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 3) {\n\t\tnext3Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext3Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext3Song.setString(trimFilename(music->songList_[2]));\n\t}\n\telse {\n\t\tnext3Song.setString(trimFilename(music->songList_[music->songListIndex_ + 3]));\n\t}\n\n\tif (music->songListIndex_ == music->songList_.size() - 4) {\n\t\tnext4Song.setString(trimFilename(music->songList_[0]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 3) {\n\t\tnext4Song.setString(trimFilename(music->songList_[1]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 2) {\n\t\tnext4Song.setString(trimFilename(music->songList_[2]));\n\t}\n\telse if (music->songListIndex_ == music->songList_.size() - 1) {\n\t\tnext4Song.setString(trimFilename(music->songList_[3]));\n\t}\n\telse {\n\t\tnext4Song.setString(trimFilename(music->songList_[music->songListIndex_ + 4]));\n\t}\n}\n\nvoid GUI::update() {\n\tstylePlaylist();\n\tdisplayPlaylist();\n\treturn;\n}<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ VoxelTest Main.cc\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"Core\/Main.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"Dbg\/Dbg.h\"\n#include \"Core\/Time\/Clock.h\"\n#include \"shaders.h\"\n#include \"GeomPool.h\"\n#include \"GeomMesher.h\"\n#include \"VoxelGenerator.h\"\n#include \"VisTree.h\"\n#include \"Camera.h\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\nusing namespace Oryol;\n\nconst int MaxChunksGeneratedPerFrame = 1;\n\nclass VoxelTest : public App {\npublic:\n AppState::Code OnInit();\n AppState::Code OnRunning();\n AppState::Code OnCleanup();\n\n void init_blocks(int frameIndex);\n int bake_geom(const GeomMesher::Result& meshResult);\n void handle_input();\n\n int frameIndex = 0;\n int lastFrameIndex = -1;\n glm::vec3 lightDir;\n ClearState clearState;\n\n Camera camera;\n GeomPool geomPool;\n GeomMesher geomMesher;\n VoxelGenerator voxelGenerator;\n VisTree visTree;\n};\nOryolMain(VoxelTest);\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnInit() {\n this->clearState = ClearState::ClearAll(glm::vec4(0.2f, 0.2f, 0.5f, 1.0f), 1.0f, 0);\n auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, \"Oryol Voxel Test\");\n gfxSetup.SetPoolSize(GfxResourceType::Pipeline, 1024);\n gfxSetup.SetPoolSize(GfxResourceType::Mesh, 1024);\n gfxSetup.ClearHint = this->clearState;\n Gfx::Setup(gfxSetup);\n Input::Setup();\n Input::SetMousePointerLockHandler([](const InputEvent& event) -> PointerLockMode::Code {\n \/\/ switch pointer-lock on\/off on left-mouse-button\n if ((event.Button == MouseButton::Left) || (event.Button == MouseButton::Right)) {\n if (event.Type == InputEvent::MouseButtonDown) {\n return PointerLockMode::Enable;\n }\n else if (event.Type == InputEvent::MouseButtonUp) {\n return PointerLockMode::Disable;\n }\n }\n return PointerLockMode::DontCare;\n });\n Dbg::Setup();\n\n const float fbWidth = (const float) Gfx::DisplayAttrs().FramebufferWidth;\n const float fbHeight = (const float) Gfx::DisplayAttrs().FramebufferHeight;\n this->camera.Setup(glm::vec3(4096, 128, 4096), glm::radians(45.0f), fbWidth, fbHeight, 0.1f, 10000.0f);\n this->lightDir = glm::normalize(glm::vec3(0.5f, 1.0f, 0.25f));\n\n this->geomPool.Setup(gfxSetup);\n this->geomMesher.Setup();\n \/\/ use a fixed display width, otherwise the geom pool could\n \/\/ run out of items at high resolutions\n const float displayWidth = 800;\n this->visTree.Setup(displayWidth, glm::radians(45.0f));\n\n return App::OnInit();\n}\n\n\/\/------------------------------------------------------------------------------\nint\nVoxelTest::bake_geom(const GeomMesher::Result& meshResult) {\n if (meshResult.NumQuads > 0) {\n int geomIndex = this->geomPool.Alloc();\n auto& geom = this->geomPool.Geoms[geomIndex];\n Gfx::UpdateVertices(geom.Mesh, meshResult.Vertices, meshResult.NumBytes);\n geom.NumQuads = meshResult.NumQuads;\n geom.VSParams.Model = glm::mat4();\n geom.VSParams.LightDir = this->lightDir;\n geom.VSParams.Scale = meshResult.Scale;\n geom.VSParams.Translate = meshResult.Translate;\n geom.VSParams.TexTranslate = meshResult.TexTranslate;\n return geomIndex;\n }\n else {\n return VisNode::EmptyGeom;\n }\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnRunning() {\n this->frameIndex++;\n this->handle_input();\n\n Gfx::ApplyDefaultRenderTarget(this->clearState);\n\n \/\/ traverse the vis-tree\n this->visTree.Traverse(this->camera);\n \/\/ free any geoms to be freed\n while (!this->visTree.freeGeoms.Empty()) {\n int geom = this->visTree.freeGeoms.PopBack();\n this->geomPool.Free(geom);\n }\n \/\/ init new geoms\n if (!this->visTree.geomGenJobs.Empty()) {\n int numProcessedJobs = 0;\n while ((numProcessedJobs < MaxChunksGeneratedPerFrame) && !this->visTree.geomGenJobs.Empty()) {\n numProcessedJobs++;\n int16_t geoms[VisNode::NumGeoms];\n int numGeoms = 0;\n VisTree::GeomGenJob job = this->visTree.geomGenJobs.PopBack();\n Volume vol = this->voxelGenerator.GenSimplex(job.Bounds);\n GeomMesher::Result meshResult;\n this->geomMesher.Start();\n this->geomMesher.StartVolume(vol);\n do {\n meshResult = this->geomMesher.Meshify();\n meshResult.Scale = job.Scale;\n meshResult.Translate = job.Translate;\n if (meshResult.BufferFull) {\n int geom = this->bake_geom(meshResult);\n o_assert(numGeoms < VisNode::NumGeoms);\n geoms[numGeoms++] = geom;\n }\n }\n while (!meshResult.VolumeDone);\n int geom = this->bake_geom(meshResult);\n o_assert(numGeoms < VisNode::NumGeoms);\n geoms[numGeoms++] = geom;\n this->visTree.ApplyGeoms(job.NodeIndex, geoms, numGeoms);\n }\n }\n\n \/\/ render visible geoms\n const int numDrawNodes = this->visTree.drawNodes.Size();\n int numQuads = 0;\n int numGeoms = 0;\n DrawState drawState;\n drawState.Mesh[0] = this->geomPool.IndexMesh;\n drawState.Pipeline = this->geomPool.Pipeline;\n for (int i = 0; i < numDrawNodes; i++) {\n const VisNode& node = this->visTree.NodeAt(this->visTree.drawNodes[i]);\n for (int geomIndex = 0; geomIndex < VisNode::NumGeoms; geomIndex++) {\n if (node.geoms[geomIndex] >= 0) {\n auto& geom = this->geomPool.Geoms[node.geoms[geomIndex]];\n drawState.Mesh[1] = geom.Mesh;\n geom.VSParams.ModelViewProjection = this->camera.ViewProj;\n Gfx::ApplyDrawState(drawState);\n Gfx::ApplyUniformBlock(geom.VSParams);\n Gfx::Draw(PrimitiveGroup(0, geom.NumQuads*6));\n numQuads += geom.NumQuads;\n numGeoms++;\n }\n }\n }\n Dbg::PrintF(\"\\n\\r\"\n \" Desktop: LMB+Mouse or AWSD to move, RMB+Mouse to look around\\n\\r\"\n \" Mobile: touch+pan to fly\\n\\n\\r\"\n \" draws: %d\\n\\r\"\n \" tris: %d\\n\\r\"\n \" avail geoms: %d\\n\\r\"\n \" avail nodes: %d\\n\\r\"\n \" pending chunks: %d\\n\\r\",\n numGeoms, numQuads*2,\n this->geomPool.freeGeoms.Size(),\n this->visTree.freeNodes.Size(),\n this->visTree.geomGenJobs.Size());\n Dbg::DrawTextBuffer();\n Gfx::CommitFrame();\n\n return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnCleanup() {\n this->visTree.Discard();\n this->geomMesher.Discard();\n this->geomPool.Discard();\n Dbg::Discard();\n Input::Discard();\n Gfx::Discard();\n return App::OnCleanup();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nVoxelTest::handle_input() {\n glm::vec3 move;\n glm::vec2 rot;\n const float vel = 0.75f;\n if (Input::KeyboardAttached()) {\n if (Input::KeyPressed(Key::W) || Input::KeyPressed(Key::Up)) {\n move.z -= vel;\n }\n if (Input::KeyPressed(Key::S) || Input::KeyPressed(Key::Down)) {\n move.z += vel;\n }\n if (Input::KeyPressed(Key::A) || Input::KeyPressed(Key::Left)) {\n move.x -= vel;\n }\n if (Input::KeyPressed(Key::D) || Input::KeyPressed(Key::Right)) {\n move.x += vel;\n }\n }\n if (Input::MouseAttached) {\n if (Input::MouseButtonPressed(MouseButton::Left)) {\n move.z -= vel;\n }\n if (Input::MouseButtonPressed(MouseButton::Left) || Input::MouseButtonPressed(MouseButton::Right)) {\n rot = Input::MouseMovement() * glm::vec2(-0.01f, -0.007f);\n }\n }\n if (Input::TouchpadAttached) {\n if (Input::TouchPanning()) {\n move.z -= vel;\n rot = Input::TouchMovement(0) * glm::vec2(-0.01f, 0.01f);\n }\n }\n this->camera.MoveRotate(move, rot);\n}\n<commit_msg>More Input API tweaks<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ VoxelTest Main.cc\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"Core\/Main.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"Dbg\/Dbg.h\"\n#include \"Core\/Time\/Clock.h\"\n#include \"shaders.h\"\n#include \"GeomPool.h\"\n#include \"GeomMesher.h\"\n#include \"VoxelGenerator.h\"\n#include \"VisTree.h\"\n#include \"Camera.h\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\nusing namespace Oryol;\n\nconst int MaxChunksGeneratedPerFrame = 1;\n\nclass VoxelTest : public App {\npublic:\n AppState::Code OnInit();\n AppState::Code OnRunning();\n AppState::Code OnCleanup();\n\n void init_blocks(int frameIndex);\n int bake_geom(const GeomMesher::Result& meshResult);\n void handle_input();\n\n int frameIndex = 0;\n int lastFrameIndex = -1;\n glm::vec3 lightDir;\n ClearState clearState;\n\n Camera camera;\n GeomPool geomPool;\n GeomMesher geomMesher;\n VoxelGenerator voxelGenerator;\n VisTree visTree;\n};\nOryolMain(VoxelTest);\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnInit() {\n this->clearState = ClearState::ClearAll(glm::vec4(0.2f, 0.2f, 0.5f, 1.0f), 1.0f, 0);\n auto gfxSetup = GfxSetup::WindowMSAA4(800, 600, \"Oryol Voxel Test\");\n gfxSetup.SetPoolSize(GfxResourceType::Pipeline, 1024);\n gfxSetup.SetPoolSize(GfxResourceType::Mesh, 1024);\n gfxSetup.ClearHint = this->clearState;\n Gfx::Setup(gfxSetup);\n Input::Setup();\n Input::SetPointerLockHandler([](const InputEvent& event) -> PointerLockMode::Code {\n \/\/ switch pointer-lock on\/off on left-mouse-button\n if ((event.Button == MouseButton::Left) || (event.Button == MouseButton::Right)) {\n if (event.Type == InputEvent::MouseButtonDown) {\n return PointerLockMode::Enable;\n }\n else if (event.Type == InputEvent::MouseButtonUp) {\n return PointerLockMode::Disable;\n }\n }\n return PointerLockMode::DontCare;\n });\n Dbg::Setup();\n\n const float fbWidth = (const float) Gfx::DisplayAttrs().FramebufferWidth;\n const float fbHeight = (const float) Gfx::DisplayAttrs().FramebufferHeight;\n this->camera.Setup(glm::vec3(4096, 128, 4096), glm::radians(45.0f), fbWidth, fbHeight, 0.1f, 10000.0f);\n this->lightDir = glm::normalize(glm::vec3(0.5f, 1.0f, 0.25f));\n\n this->geomPool.Setup(gfxSetup);\n this->geomMesher.Setup();\n \/\/ use a fixed display width, otherwise the geom pool could\n \/\/ run out of items at high resolutions\n const float displayWidth = 800;\n this->visTree.Setup(displayWidth, glm::radians(45.0f));\n\n return App::OnInit();\n}\n\n\/\/------------------------------------------------------------------------------\nint\nVoxelTest::bake_geom(const GeomMesher::Result& meshResult) {\n if (meshResult.NumQuads > 0) {\n int geomIndex = this->geomPool.Alloc();\n auto& geom = this->geomPool.Geoms[geomIndex];\n Gfx::UpdateVertices(geom.Mesh, meshResult.Vertices, meshResult.NumBytes);\n geom.NumQuads = meshResult.NumQuads;\n geom.VSParams.Model = glm::mat4();\n geom.VSParams.LightDir = this->lightDir;\n geom.VSParams.Scale = meshResult.Scale;\n geom.VSParams.Translate = meshResult.Translate;\n geom.VSParams.TexTranslate = meshResult.TexTranslate;\n return geomIndex;\n }\n else {\n return VisNode::EmptyGeom;\n }\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnRunning() {\n this->frameIndex++;\n this->handle_input();\n\n Gfx::ApplyDefaultRenderTarget(this->clearState);\n\n \/\/ traverse the vis-tree\n this->visTree.Traverse(this->camera);\n \/\/ free any geoms to be freed\n while (!this->visTree.freeGeoms.Empty()) {\n int geom = this->visTree.freeGeoms.PopBack();\n this->geomPool.Free(geom);\n }\n \/\/ init new geoms\n if (!this->visTree.geomGenJobs.Empty()) {\n int numProcessedJobs = 0;\n while ((numProcessedJobs < MaxChunksGeneratedPerFrame) && !this->visTree.geomGenJobs.Empty()) {\n numProcessedJobs++;\n int16_t geoms[VisNode::NumGeoms];\n int numGeoms = 0;\n VisTree::GeomGenJob job = this->visTree.geomGenJobs.PopBack();\n Volume vol = this->voxelGenerator.GenSimplex(job.Bounds);\n GeomMesher::Result meshResult;\n this->geomMesher.Start();\n this->geomMesher.StartVolume(vol);\n do {\n meshResult = this->geomMesher.Meshify();\n meshResult.Scale = job.Scale;\n meshResult.Translate = job.Translate;\n if (meshResult.BufferFull) {\n int geom = this->bake_geom(meshResult);\n o_assert(numGeoms < VisNode::NumGeoms);\n geoms[numGeoms++] = geom;\n }\n }\n while (!meshResult.VolumeDone);\n int geom = this->bake_geom(meshResult);\n o_assert(numGeoms < VisNode::NumGeoms);\n geoms[numGeoms++] = geom;\n this->visTree.ApplyGeoms(job.NodeIndex, geoms, numGeoms);\n }\n }\n\n \/\/ render visible geoms\n const int numDrawNodes = this->visTree.drawNodes.Size();\n int numQuads = 0;\n int numGeoms = 0;\n DrawState drawState;\n drawState.Mesh[0] = this->geomPool.IndexMesh;\n drawState.Pipeline = this->geomPool.Pipeline;\n for (int i = 0; i < numDrawNodes; i++) {\n const VisNode& node = this->visTree.NodeAt(this->visTree.drawNodes[i]);\n for (int geomIndex = 0; geomIndex < VisNode::NumGeoms; geomIndex++) {\n if (node.geoms[geomIndex] >= 0) {\n auto& geom = this->geomPool.Geoms[node.geoms[geomIndex]];\n drawState.Mesh[1] = geom.Mesh;\n geom.VSParams.ModelViewProjection = this->camera.ViewProj;\n Gfx::ApplyDrawState(drawState);\n Gfx::ApplyUniformBlock(geom.VSParams);\n Gfx::Draw(PrimitiveGroup(0, geom.NumQuads*6));\n numQuads += geom.NumQuads;\n numGeoms++;\n }\n }\n }\n Dbg::PrintF(\"\\n\\r\"\n \" Desktop: LMB+Mouse or AWSD to move, RMB+Mouse to look around\\n\\r\"\n \" Mobile: touch+pan to fly\\n\\n\\r\"\n \" draws: %d\\n\\r\"\n \" tris: %d\\n\\r\"\n \" avail geoms: %d\\n\\r\"\n \" avail nodes: %d\\n\\r\"\n \" pending chunks: %d\\n\\r\",\n numGeoms, numQuads*2,\n this->geomPool.freeGeoms.Size(),\n this->visTree.freeNodes.Size(),\n this->visTree.geomGenJobs.Size());\n Dbg::DrawTextBuffer();\n Gfx::CommitFrame();\n\n return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nVoxelTest::OnCleanup() {\n this->visTree.Discard();\n this->geomMesher.Discard();\n this->geomPool.Discard();\n Dbg::Discard();\n Input::Discard();\n Gfx::Discard();\n return App::OnCleanup();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nVoxelTest::handle_input() {\n glm::vec3 move;\n glm::vec2 rot;\n const float vel = 0.75f;\n if (Input::KeyboardAttached()) {\n if (Input::KeyPressed(Key::W) || Input::KeyPressed(Key::Up)) {\n move.z -= vel;\n }\n if (Input::KeyPressed(Key::S) || Input::KeyPressed(Key::Down)) {\n move.z += vel;\n }\n if (Input::KeyPressed(Key::A) || Input::KeyPressed(Key::Left)) {\n move.x -= vel;\n }\n if (Input::KeyPressed(Key::D) || Input::KeyPressed(Key::Right)) {\n move.x += vel;\n }\n }\n if (Input::MouseAttached) {\n if (Input::MouseButtonPressed(MouseButton::Left)) {\n move.z -= vel;\n }\n if (Input::MouseButtonPressed(MouseButton::Left) || Input::MouseButtonPressed(MouseButton::Right)) {\n rot = Input::MouseMovement() * glm::vec2(-0.01f, -0.007f);\n }\n }\n if (Input::TouchpadAttached) {\n if (Input::TouchPanning()) {\n move.z -= vel;\n rot = Input::TouchMovement(0) * glm::vec2(-0.01f, 0.01f);\n }\n }\n this->camera.MoveRotate(move, rot);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n#include <memory>\n\n#include <boost\/variant\/variant.hpp>\n\n#include \"ast\/VariablesAnnotator.hpp\"\n#include \"ast\/SourceFile.hpp\"\n#include \"ast\/TypeTransformer.hpp\"\n#include \"ast\/IsConstantVisitor.hpp\"\n#include \"ast\/ASTVisitor.hpp\"\n\n#include \"SemanticalException.hpp\"\n#include \"Context.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Types.hpp\"\n#include \"Variable.hpp\"\n#include \"Utils.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"SymbolTable.hpp\"\n\nusing namespace eddic;\n\nstruct VariablesVisitor : public boost::static_visitor<> {\n AUTO_RECURSE_PROGRAM()\n AUTO_RECURSE_FUNCTION_CALLS()\n AUTO_RECURSE_SIMPLE_LOOPS()\n AUTO_RECURSE_BRANCHES()\n AUTO_RECURSE_BINARY_CONDITION()\n AUTO_RECURSE_BUILTIN_OPERATORS()\n AUTO_RECURSE_MINUS_PLUS_VALUES()\n AUTO_RECURSE_CAST_VALUES()\n AUTO_RECURSE_RETURN_VALUES()\n\n AUTO_IGNORE_FALSE()\n AUTO_IGNORE_TRUE()\n AUTO_IGNORE_LITERAL()\n AUTO_IGNORE_FLOAT()\n AUTO_IGNORE_INTEGER()\n AUTO_IGNORE_INTEGER_SUFFIX()\n AUTO_IGNORE_IMPORT()\n AUTO_IGNORE_STANDARD_IMPORT()\n AUTO_IGNORE_STRUCT()\n \n void operator()(ast::FunctionDeclaration& declaration){\n \/\/Add all the parameters to the function context\n for(auto& parameter : declaration.Content->parameters){\n Type type = visit(ast::TypeTransformer(), parameter.parameterType);\n \n declaration.Content->context->addParameter(parameter.parameterName, type); \n }\n\n visit_each(*this, declaration.Content->instructions);\n }\n \n void operator()(ast::GlobalVariableDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->variableName)) {\n throw SemanticalException(\"The global Variable \" + declaration.Content->variableName + \" has already been declared\", declaration.Content->position);\n }\n \n if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){\n throw SemanticalException(\"The value must be constant\", declaration.Content->position);\n }\n \n declaration.Content->context->addVariable(declaration.Content->variableName, \n newSimpleType(declaration.Content->variableType, declaration.Content->constant), *declaration.Content->value);\n }\n\n void operator()(ast::GlobalArrayDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n throw SemanticalException(\"The global Variable \" + declaration.Content->arrayName + \" has already been declared\", declaration.Content->position);\n }\n\n declaration.Content->context->addVariable(declaration.Content->arrayName, newArrayType(declaration.Content->arrayType, declaration.Content->arraySize));\n }\n \n void operator()(ast::Foreach& foreach){\n if(foreach.Content->context->exists(foreach.Content->variableName)){\n throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName + \" has already been declared\", foreach.Content->position);\n }\n\n foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));\n\n visit_each(*this, foreach.Content->instructions);\n }\n \n void operator()(ast::ForeachIn& foreach){\n if(foreach.Content->context->exists(foreach.Content->variableName)){\n throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName + \" has already been declared\", foreach.Content->position);\n }\n \n if(!foreach.Content->context->exists(foreach.Content->arrayName)){\n throw SemanticalException(\"The foreach array \" + foreach.Content->arrayName + \" has not been declared\", foreach.Content->position);\n }\n\n static int generated = 0;\n\n foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));\n foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);\n foreach.Content->iterVar = foreach.Content->context->addVariable(\"foreach_iter_\" + toString(++generated), newType(\"int\"));\n\n visit_each(*this, foreach.Content->instructions);\n }\n\n template<typename A>\n void annotateAssignment(A& assignment){\n if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n throw SemanticalException(\"Variable \" + assignment.Content->variableName + \" has not been declared\", assignment.Content->position);\n }\n\n visit(*this, assignment.Content->value);\n\n assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n }\n\n void operator()(ast::Assignment& assignment){\n annotateAssignment(assignment);\n }\n \n void operator()(ast::CompoundAssignment& assignment){\n annotateAssignment(assignment);\n }\n \n void operator()(ast::StructCompoundAssignment& assignment){\n annotateAssignment(assignment);\n }\n\n void operator()(ast::StructAssignment& assignment){\n annotateAssignment(assignment);\n\n auto var = (*assignment.Content->context)[assignment.Content->variableName];\n auto struct_name = var->type().type();\n auto struct_type = symbols.get_struct(struct_name);\n \n \/\/Add a reference to the struct\n struct_type->add_reference();\n\n auto& members = assignment.Content->memberNames;\n for(std::size_t i = 0; i < members.size(); ++i){\n auto& member = members[i];\n\n if(!struct_type->member_exists(member)){ \n throw SemanticalException(\"The struct \" + struct_name + \" has no member named \" + member, assignment.Content->position);\n }\n\n \/\/Add a reference to the member\n (*struct_type)[member]->add_reference();\n\n \/\/If it is not the last member\n if(i != members.size() - 1){\n \/\/The next member will be a member of the current member type\n struct_type = symbols.get_struct((*struct_type)[member]->type.type());\n struct_name = struct_type->name;\n }\n }\n }\n\n template<typename Operation>\n void annotateSuffixOrPrefixOperation(Operation& operation){\n if (!operation.Content->context->exists(operation.Content->variableName)) {\n throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not been declared\", operation.Content->position);\n }\n\n operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n operation.Content->variable->addReference();\n }\n \n void operator()(ast::SuffixOperation& operation){\n annotateSuffixOrPrefixOperation(operation);\n }\n \n void operator()(ast::PrefixOperation& operation){\n annotateSuffixOrPrefixOperation(operation);\n }\n\n void operator()(ast::ArrayAssignment& assignment){\n if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n throw SemanticalException(\"Array \" + assignment.Content->variableName + \" has not been declared\", assignment.Content->position);\n }\n\n visit(*this, assignment.Content->indexValue);\n visit(*this, assignment.Content->value);\n\n assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n }\n \n void operator()(ast::VariableDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->variableName)) {\n throw SemanticalException(\"Variable \" + declaration.Content->variableName + \" has already been declared\", declaration.Content->position);\n }\n \n visit_optional(*this, declaration.Content->value);\n\n \/\/If it's a standard type\n if(is_standard_type(declaration.Content->variableType)){\n Type type = newSimpleType(declaration.Content->variableType, declaration.Content->const_);\n\n if(type.isConst()){\n if(!declaration.Content->value){\n throw SemanticalException(\"A constant variable must have a value\", declaration.Content->position);\n }\n\n if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){\n throw SemanticalException(\"The value must be constant\", declaration.Content->position);\n }\n\n declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n } else {\n declaration.Content->context->addVariable(declaration.Content->variableName, type);\n }\n }\n \/\/If it's a custom type\n else {\n if(symbols.struct_exists(declaration.Content->variableType)){\n if(declaration.Content->const_){\n throw SemanticalException(\"Custom types cannot be const\", declaration.Content->position);\n }\n\n Type type = new_custom_type(declaration.Content->variableType);\n\n declaration.Content->context->addVariable(declaration.Content->variableName, type);\n } else {\n throw SemanticalException(\"The type \\\"\" + declaration.Content->variableType + \"\\\" does not exists\", declaration.Content->position);\n }\n }\n }\n \n void operator()(ast::ArrayDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n throw SemanticalException(\"The variable \" + declaration.Content->arrayName + \" has already been declared\", declaration.Content->position);\n }\n\n Type type = newArrayType(declaration.Content->arrayType, declaration.Content->arraySize);\n declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n }\n \n void operator()(ast::Swap& swap){\n if (swap.Content->lhs == swap.Content->rhs) {\n throw SemanticalException(\"Cannot swap a variable with itself\", swap.Content->position);\n }\n\n if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {\n throw SemanticalException(\"Variable has not been declared in the swap\", swap.Content->position);\n }\n\n swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);\n swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);\n\n \/\/Reference both variables\n swap.Content->lhs_var->addReference();\n swap.Content->rhs_var->addReference();\n }\n\n void operator()(ast::VariableValue& variable){\n if (!variable.Content->context->exists(variable.Content->variableName)) {\n throw SemanticalException(\"Variable \" + variable.Content->variableName + \" has not been declared\", variable.Content->position);\n }\n\n \/\/Reference the variable\n variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);\n variable.Content->var->addReference();\n }\n \n void operator()(ast::StructValue& struct_){\n if (!struct_.Content->context->exists(struct_.Content->variableName)) {\n throw SemanticalException(\"Variable \" + struct_.Content->variableName + \" has not been declared\", struct_.Content->position);\n }\n \n auto var = (*struct_.Content->context)[struct_.Content->variableName];\n auto struct_name = var->type().type();\n auto struct_type = symbols.get_struct(struct_name);\n\n if(!struct_type->member_exists(struct_.Content->memberNames[0])){ \/\/TODO Handle several members\n throw SemanticalException(\"The struct \" + struct_name + \" has no member named \" + struct_.Content->memberNames[0], struct_.Content->position);\n }\n\n \/\/Reference the variable\n struct_.Content->variable = var;\n struct_.Content->variable->addReference();\n\n \/\/Reference the member\n struct_type->add_reference();\n (*struct_type)[struct_.Content->memberNames[0]]->add_reference();\n }\n\n void operator()(ast::ArrayValue& array){\n if (!array.Content->context->exists(array.Content->arrayName)) {\n throw SemanticalException(\"Array \" + array.Content->arrayName + \" has not been declared\", array.Content->position);\n }\n \n \/\/Reference the variable\n array.Content->var = array.Content->context->getVariable(array.Content->arrayName);\n array.Content->var->addReference();\n\n visit(*this, array.Content->indexValue);\n }\n\n void operator()(ast::Expression& value){\n visit(*this, value.Content->first);\n \n for_each(value.Content->operations.begin(), value.Content->operations.end(), \n [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });\n }\n};\n\nvoid ast::defineVariables(ast::SourceFile& program){\n VariablesVisitor visitor;\n visit_non_variant(visitor, program);\n}\n<commit_msg>Do the same verifications for struct compound assignment<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n#include <memory>\n\n#include <boost\/variant\/variant.hpp>\n\n#include \"ast\/VariablesAnnotator.hpp\"\n#include \"ast\/SourceFile.hpp\"\n#include \"ast\/TypeTransformer.hpp\"\n#include \"ast\/IsConstantVisitor.hpp\"\n#include \"ast\/ASTVisitor.hpp\"\n\n#include \"SemanticalException.hpp\"\n#include \"Context.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Types.hpp\"\n#include \"Variable.hpp\"\n#include \"Utils.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"SymbolTable.hpp\"\n\nusing namespace eddic;\n\nstruct VariablesVisitor : public boost::static_visitor<> {\n AUTO_RECURSE_PROGRAM()\n AUTO_RECURSE_FUNCTION_CALLS()\n AUTO_RECURSE_SIMPLE_LOOPS()\n AUTO_RECURSE_BRANCHES()\n AUTO_RECURSE_BINARY_CONDITION()\n AUTO_RECURSE_BUILTIN_OPERATORS()\n AUTO_RECURSE_MINUS_PLUS_VALUES()\n AUTO_RECURSE_CAST_VALUES()\n AUTO_RECURSE_RETURN_VALUES()\n\n AUTO_IGNORE_FALSE()\n AUTO_IGNORE_TRUE()\n AUTO_IGNORE_LITERAL()\n AUTO_IGNORE_FLOAT()\n AUTO_IGNORE_INTEGER()\n AUTO_IGNORE_INTEGER_SUFFIX()\n AUTO_IGNORE_IMPORT()\n AUTO_IGNORE_STANDARD_IMPORT()\n AUTO_IGNORE_STRUCT()\n \n void operator()(ast::FunctionDeclaration& declaration){\n \/\/Add all the parameters to the function context\n for(auto& parameter : declaration.Content->parameters){\n Type type = visit(ast::TypeTransformer(), parameter.parameterType);\n \n declaration.Content->context->addParameter(parameter.parameterName, type); \n }\n\n visit_each(*this, declaration.Content->instructions);\n }\n \n void operator()(ast::GlobalVariableDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->variableName)) {\n throw SemanticalException(\"The global Variable \" + declaration.Content->variableName + \" has already been declared\", declaration.Content->position);\n }\n \n if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){\n throw SemanticalException(\"The value must be constant\", declaration.Content->position);\n }\n \n declaration.Content->context->addVariable(declaration.Content->variableName, \n newSimpleType(declaration.Content->variableType, declaration.Content->constant), *declaration.Content->value);\n }\n\n void operator()(ast::GlobalArrayDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n throw SemanticalException(\"The global Variable \" + declaration.Content->arrayName + \" has already been declared\", declaration.Content->position);\n }\n\n declaration.Content->context->addVariable(declaration.Content->arrayName, newArrayType(declaration.Content->arrayType, declaration.Content->arraySize));\n }\n \n void operator()(ast::Foreach& foreach){\n if(foreach.Content->context->exists(foreach.Content->variableName)){\n throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName + \" has already been declared\", foreach.Content->position);\n }\n\n foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));\n\n visit_each(*this, foreach.Content->instructions);\n }\n \n void operator()(ast::ForeachIn& foreach){\n if(foreach.Content->context->exists(foreach.Content->variableName)){\n throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName + \" has already been declared\", foreach.Content->position);\n }\n \n if(!foreach.Content->context->exists(foreach.Content->arrayName)){\n throw SemanticalException(\"The foreach array \" + foreach.Content->arrayName + \" has not been declared\", foreach.Content->position);\n }\n\n static int generated = 0;\n\n foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));\n foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);\n foreach.Content->iterVar = foreach.Content->context->addVariable(\"foreach_iter_\" + toString(++generated), newType(\"int\"));\n\n visit_each(*this, foreach.Content->instructions);\n }\n\n template<typename A>\n void annotateAssignment(A& assignment){\n if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n throw SemanticalException(\"Variable \" + assignment.Content->variableName + \" has not been declared\", assignment.Content->position);\n }\n\n visit(*this, assignment.Content->value);\n\n assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n }\n\n void operator()(ast::Assignment& assignment){\n annotateAssignment(assignment);\n }\n \n void operator()(ast::CompoundAssignment& assignment){\n annotateAssignment(assignment);\n }\n\n template<typename A>\n void verify_struct_assignment(A& assignment){\n annotateAssignment(assignment);\n\n auto var = (*assignment.Content->context)[assignment.Content->variableName];\n auto struct_name = var->type().type();\n auto struct_type = symbols.get_struct(struct_name);\n \n \/\/Add a reference to the struct\n struct_type->add_reference();\n\n auto& members = assignment.Content->memberNames;\n for(std::size_t i = 0; i < members.size(); ++i){\n auto& member = members[i];\n\n if(!struct_type->member_exists(member)){ \n throw SemanticalException(\"The struct \" + struct_name + \" has no member named \" + member, assignment.Content->position);\n }\n\n \/\/Add a reference to the member\n (*struct_type)[member]->add_reference();\n\n \/\/If it is not the last member\n if(i != members.size() - 1){\n \/\/The next member will be a member of the current member type\n struct_type = symbols.get_struct((*struct_type)[member]->type.type());\n struct_name = struct_type->name;\n }\n }\n }\n \n void operator()(ast::StructCompoundAssignment& assignment){\n verify_struct_assignment(assignment);\n }\n\n void operator()(ast::StructAssignment& assignment){\n verify_struct_assignment(assignment);\n }\n\n template<typename Operation>\n void annotateSuffixOrPrefixOperation(Operation& operation){\n if (!operation.Content->context->exists(operation.Content->variableName)) {\n throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not been declared\", operation.Content->position);\n }\n\n operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n operation.Content->variable->addReference();\n }\n \n void operator()(ast::SuffixOperation& operation){\n annotateSuffixOrPrefixOperation(operation);\n }\n \n void operator()(ast::PrefixOperation& operation){\n annotateSuffixOrPrefixOperation(operation);\n }\n\n void operator()(ast::ArrayAssignment& assignment){\n if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n throw SemanticalException(\"Array \" + assignment.Content->variableName + \" has not been declared\", assignment.Content->position);\n }\n\n visit(*this, assignment.Content->indexValue);\n visit(*this, assignment.Content->value);\n\n assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n }\n \n void operator()(ast::VariableDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->variableName)) {\n throw SemanticalException(\"Variable \" + declaration.Content->variableName + \" has already been declared\", declaration.Content->position);\n }\n \n visit_optional(*this, declaration.Content->value);\n\n \/\/If it's a standard type\n if(is_standard_type(declaration.Content->variableType)){\n Type type = newSimpleType(declaration.Content->variableType, declaration.Content->const_);\n\n if(type.isConst()){\n if(!declaration.Content->value){\n throw SemanticalException(\"A constant variable must have a value\", declaration.Content->position);\n }\n\n if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){\n throw SemanticalException(\"The value must be constant\", declaration.Content->position);\n }\n\n declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n } else {\n declaration.Content->context->addVariable(declaration.Content->variableName, type);\n }\n }\n \/\/If it's a custom type\n else {\n if(symbols.struct_exists(declaration.Content->variableType)){\n if(declaration.Content->const_){\n throw SemanticalException(\"Custom types cannot be const\", declaration.Content->position);\n }\n\n Type type = new_custom_type(declaration.Content->variableType);\n\n declaration.Content->context->addVariable(declaration.Content->variableName, type);\n } else {\n throw SemanticalException(\"The type \\\"\" + declaration.Content->variableType + \"\\\" does not exists\", declaration.Content->position);\n }\n }\n }\n \n void operator()(ast::ArrayDeclaration& declaration){\n if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n throw SemanticalException(\"The variable \" + declaration.Content->arrayName + \" has already been declared\", declaration.Content->position);\n }\n\n Type type = newArrayType(declaration.Content->arrayType, declaration.Content->arraySize);\n declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n }\n \n void operator()(ast::Swap& swap){\n if (swap.Content->lhs == swap.Content->rhs) {\n throw SemanticalException(\"Cannot swap a variable with itself\", swap.Content->position);\n }\n\n if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {\n throw SemanticalException(\"Variable has not been declared in the swap\", swap.Content->position);\n }\n\n swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);\n swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);\n\n \/\/Reference both variables\n swap.Content->lhs_var->addReference();\n swap.Content->rhs_var->addReference();\n }\n\n void operator()(ast::VariableValue& variable){\n if (!variable.Content->context->exists(variable.Content->variableName)) {\n throw SemanticalException(\"Variable \" + variable.Content->variableName + \" has not been declared\", variable.Content->position);\n }\n\n \/\/Reference the variable\n variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);\n variable.Content->var->addReference();\n }\n \n void operator()(ast::StructValue& struct_){\n if (!struct_.Content->context->exists(struct_.Content->variableName)) {\n throw SemanticalException(\"Variable \" + struct_.Content->variableName + \" has not been declared\", struct_.Content->position);\n }\n \n auto var = (*struct_.Content->context)[struct_.Content->variableName];\n auto struct_name = var->type().type();\n auto struct_type = symbols.get_struct(struct_name);\n\n if(!struct_type->member_exists(struct_.Content->memberNames[0])){ \/\/TODO Handle several members\n throw SemanticalException(\"The struct \" + struct_name + \" has no member named \" + struct_.Content->memberNames[0], struct_.Content->position);\n }\n\n \/\/Reference the variable\n struct_.Content->variable = var;\n struct_.Content->variable->addReference();\n\n \/\/Reference the member\n struct_type->add_reference();\n (*struct_type)[struct_.Content->memberNames[0]]->add_reference();\n }\n\n void operator()(ast::ArrayValue& array){\n if (!array.Content->context->exists(array.Content->arrayName)) {\n throw SemanticalException(\"Array \" + array.Content->arrayName + \" has not been declared\", array.Content->position);\n }\n \n \/\/Reference the variable\n array.Content->var = array.Content->context->getVariable(array.Content->arrayName);\n array.Content->var->addReference();\n\n visit(*this, array.Content->indexValue);\n }\n\n void operator()(ast::Expression& value){\n visit(*this, value.Content->first);\n \n for_each(value.Content->operations.begin(), value.Content->operations.end(), \n [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });\n }\n};\n\nvoid ast::defineVariables(ast::SourceFile& program){\n VariablesVisitor visitor;\n visit_non_variant(visitor, program);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file ViewManager.cpp\n \\author Dane Gardner <dane.gardner@gmail.com>\n\n \\section LICENSE\n This file is part of the Parallel Tools GUI Framework (PTGF)\n Copyright (C) 2010-2013 Argo Navis Technologies, LLC\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by the\n Free Software Foundation; either version 2.1 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"ViewManagerPrivate.h\"\n\n#include <QDebug>\n\n#include <PluginManager\/PluginManager.h>\n\n#include \"AbstractView.h\"\n#include \"IViewFactory.h\"\n\nnamespace Core {\nnamespace ViewManager {\n\nViewManager &ViewManager::instance()\n{\n static ViewManager m_Instance;\n return m_Instance;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::ViewManager\n *\/\nViewManager::ViewManager() :\n QObject(0),\n d(new ViewManagerPrivate)\n{\n d->q = this;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::~ViewManager\n *\/\nViewManager::~ViewManager()\n{\n}\n\n\/*!\n \\internal\n \\brief ViewManager::initialize\n \\return true if successful\n *\/\nbool ViewManager::initialize()\n{\n if(d->m_Initialized) {\n return false;\n }\n\n try {\n\n PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();\n pluginManager.addObject(this);\n\n \/* Check the object pool for anything we should manage *\/\n foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }\n connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));\n connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));\n\n } catch(...) {\n return false;\n }\n\n return d->m_Initialized = true;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::shutdown\n *\/\nvoid ViewManager::shutdown()\n{\n if(!d->m_Initialized) {\n return;\n }\n\n \/\/ ...\n}\n\n\/*!\n \\fn ViewManager::viewNames\n\n \\brief Returns a list of names of views that can handle the supplied model.\n\n A NULL model will return all names.\n\n \\param model\n \\return\n \\sa viewWidget\n *\/\nQStringList ViewManager::viewNames(QAbstractItemModel *model)\n{\n QStringList nameList;\n foreach(IViewFactory *viewPlugin, d->m_viewFactories.values()) {\n if(model) {\n if(viewPlugin->viewHandles(model)) {\n nameList.append(viewPlugin->viewName());\n }\n } else {\n nameList.append(viewPlugin->viewName());\n }\n }\n return nameList;\n}\n\n\/*!\n \\fn ViewManager::viewWidget\n\n \\brief Creates the specified view using the supplied model, and returns it.\n\n You should not create a view from it's constructor directly, but rather from its associated IViewFactory\n through the ViewManager::viewWidget method. For example:\n\n \\code\n \/\/ Grab the instance of the ViewManager\n Core::ViewManager::ViewManager &viewManager = Core::ViewManager::ViewManager::instance();\n\n \/\/ Create your own data model\n QAbstractItemModel *model = new DataModel(data);\n\n \/\/ Check to see if this view can handle your model\n if(viewManager.viewNames(model).contains(\"A View Name\")) {\n\n \/\/ Create the view using the model, and display it to the user\n QAbstractItemView *view = viewManager.viewWidget(\"A View Name\", model);\n this->layout()->insertWidget(view);\n\n }\n \\endcode\n\n If the creation should fail for some reason, a NULL pointer will be returned. Failure can occur when: a name was\n not specified; a named view doesn't exist; a named view cannot handle the specified model. A NULL model will not\n be checked, and will always return a view if it exists.\n\n The returned object does not have a parent, and should be immediately reparented, or deconstruction should be\n handled manually.\n\n \\param name\n \\param model\n \\return\n \\sa viewNames IViewFactory\n *\/\nAbstractView *ViewManager::viewWidget(QString name, QAbstractItemModel *model)\n{\n if(name.isEmpty()) {\n return NULL;\n }\n\n IViewFactory *viewPlugin = d->m_viewFactories.value(name, NULL);\n\n if(model != NULL && !viewPlugin->viewHandles(model)) {\n return NULL;\n }\n\n return viewPlugin->viewWidget(model);\n}\n\n\n\n\n\/***** PRIVATE IMPLEMENTATION *****\/\nViewManagerPrivate::ViewManagerPrivate() :\n QObject(NULL),\n m_Initialized(false)\n{\n}\n\nvoid ViewManagerPrivate::registerViewFactory(IViewFactory *viewFactory)\n{\n qDebug() << Q_FUNC_INFO << tr(\"Registering view: %1\").arg(viewFactory->viewName());\n if(!m_viewFactories.contains(viewFactory->viewName())) {\n m_viewFactories.insert(viewFactory->viewName(), viewFactory);\n }\n}\n\nvoid ViewManagerPrivate::deregisterViewFactory(IViewFactory *viewFactory)\n{\n if(m_viewFactories.contains(viewFactory->viewName())) {\n m_viewFactories.remove(viewFactory->viewName());\n }\n}\n\nvoid ViewManagerPrivate::pluginObjectRegistered(QObject *object)\n{\n if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {\n registerViewFactory(viewFactory);\n }\n}\n\nvoid ViewManagerPrivate::pluginObjectDeregistered(QObject *object)\n{\n if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {\n deregisterViewFactory(viewFactory);\n }\n}\n\n\n\n} \/\/ namespace ViewManager\n} \/\/ namespace Core\n<commit_msg>Fixed stray debug statement<commit_after>\/*!\n \\file ViewManager.cpp\n \\author Dane Gardner <dane.gardner@gmail.com>\n\n \\section LICENSE\n This file is part of the Parallel Tools GUI Framework (PTGF)\n Copyright (C) 2010-2013 Argo Navis Technologies, LLC\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by the\n Free Software Foundation; either version 2.1 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"ViewManagerPrivate.h\"\n\n#include <QDebug>\n\n#include <PluginManager\/PluginManager.h>\n\n#include \"AbstractView.h\"\n#include \"IViewFactory.h\"\n\nnamespace Core {\nnamespace ViewManager {\n\nViewManager &ViewManager::instance()\n{\n static ViewManager m_Instance;\n return m_Instance;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::ViewManager\n *\/\nViewManager::ViewManager() :\n QObject(0),\n d(new ViewManagerPrivate)\n{\n d->q = this;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::~ViewManager\n *\/\nViewManager::~ViewManager()\n{\n}\n\n\/*!\n \\internal\n \\brief ViewManager::initialize\n \\return true if successful\n *\/\nbool ViewManager::initialize()\n{\n if(d->m_Initialized) {\n return false;\n }\n\n try {\n\n PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();\n pluginManager.addObject(this);\n\n \/* Check the object pool for anything we should manage *\/\n foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }\n connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));\n connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));\n\n } catch(...) {\n return false;\n }\n\n return d->m_Initialized = true;\n}\n\n\/*!\n \\internal\n \\brief ViewManager::shutdown\n *\/\nvoid ViewManager::shutdown()\n{\n if(!d->m_Initialized) {\n return;\n }\n\n \/\/ ...\n}\n\n\/*!\n \\fn ViewManager::viewNames\n\n \\brief Returns a list of names of views that can handle the supplied model.\n\n A NULL model will return all names.\n\n \\param model\n \\return\n \\sa viewWidget\n *\/\nQStringList ViewManager::viewNames(QAbstractItemModel *model)\n{\n QStringList nameList;\n foreach(IViewFactory *viewPlugin, d->m_viewFactories.values()) {\n if(model) {\n if(viewPlugin->viewHandles(model)) {\n nameList.append(viewPlugin->viewName());\n }\n } else {\n nameList.append(viewPlugin->viewName());\n }\n }\n return nameList;\n}\n\n\/*!\n \\fn ViewManager::viewWidget\n\n \\brief Creates the specified view using the supplied model, and returns it.\n\n You should not create a view from it's constructor directly, but rather from its associated IViewFactory\n through the ViewManager::viewWidget method. For example:\n\n \\code\n \/\/ Grab the instance of the ViewManager\n Core::ViewManager::ViewManager &viewManager = Core::ViewManager::ViewManager::instance();\n\n \/\/ Create your own data model\n QAbstractItemModel *model = new DataModel(data);\n\n \/\/ Check to see if this view can handle your model\n if(viewManager.viewNames(model).contains(\"A View Name\")) {\n\n \/\/ Create the view using the model, and display it to the user\n QAbstractItemView *view = viewManager.viewWidget(\"A View Name\", model);\n this->layout()->insertWidget(view);\n\n }\n \\endcode\n\n If the creation should fail for some reason, a NULL pointer will be returned. Failure can occur when: a name was\n not specified; a named view doesn't exist; a named view cannot handle the specified model. A NULL model will not\n be checked, and will always return a view if it exists.\n\n The returned object does not have a parent, and should be immediately reparented, or deconstruction should be\n handled manually.\n\n \\param name\n \\param model\n \\return\n \\sa viewNames IViewFactory\n *\/\nAbstractView *ViewManager::viewWidget(QString name, QAbstractItemModel *model)\n{\n if(name.isEmpty()) {\n return NULL;\n }\n\n IViewFactory *viewPlugin = d->m_viewFactories.value(name, NULL);\n\n if(model != NULL && !viewPlugin->viewHandles(model)) {\n return NULL;\n }\n\n return viewPlugin->viewWidget(model);\n}\n\n\n\n\n\/***** PRIVATE IMPLEMENTATION *****\/\nViewManagerPrivate::ViewManagerPrivate() :\n QObject(NULL),\n m_Initialized(false)\n{\n}\n\nvoid ViewManagerPrivate::registerViewFactory(IViewFactory *viewFactory)\n{\n if(!m_viewFactories.contains(viewFactory->viewName())) {\n m_viewFactories.insert(viewFactory->viewName(), viewFactory);\n }\n}\n\nvoid ViewManagerPrivate::deregisterViewFactory(IViewFactory *viewFactory)\n{\n if(m_viewFactories.contains(viewFactory->viewName())) {\n m_viewFactories.remove(viewFactory->viewName());\n }\n}\n\nvoid ViewManagerPrivate::pluginObjectRegistered(QObject *object)\n{\n if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {\n registerViewFactory(viewFactory);\n }\n}\n\nvoid ViewManagerPrivate::pluginObjectDeregistered(QObject *object)\n{\n if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {\n deregisterViewFactory(viewFactory);\n }\n}\n\n\n\n} \/\/ namespace ViewManager\n} \/\/ namespace Core\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <SNR.hpp>\n\nnamespace PulsarSearch {\n\nsnrConf::snrConf() : nrThreadsD0(0), nrItemsD0(0) {}\n\nsnrConf::~snrConf() {}\n\nstd::string snrConf::print() const {\n return isa::utils::toString(nrThreadsD0) + \" \" + isa::utils::toString(nrItemsD0);\n}\n\nvoid readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename) {\n unsigned int nrDMs = 0;\n unsigned int nrSamples = 0;\n std::string temp;\n std::string deviceName;\n PulsarSearch::snrConf * parameters = 0;\n std::ifstream snrFile;\n\n snrFile.open(snrFilename);\n while ( ! snrFile.eof() ) {\n unsigned int splitPoint = 0;\n\n std::getline(snrFile, temp);\n if ( ! std::isalpha(temp[0]) ) {\n continue;\n }\n parameters = new PulsarSearch::snrConf();\n\n splitPoint = temp.find(\" \");\n deviceName = temp.substr(0, splitPoint);\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n parameters->setNrThreadsD0(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n temp = temp.substr(splitPoint + 1);\n parameters->setNrItemsD0(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( tunedSNR.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * externalContainer = new std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * >();\n std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();\n\n\t\t\tinternalContainer->insert(std::make_pair(nrSamples, parameters));\n\t\t\texternalContainer->insert(std::make_pair(nrDMs, internalContainer));\n\t\t\ttunedSNR.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( tunedSNR.at(deviceName)->count(nrDMs) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();\n\n\t\t\tinternalContainer->insert(std::make_pair(nrSamples, parameters));\n\t\t\ttunedSNR.at(deviceName)->insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\ttunedSNR.at(deviceName)->at(nrDMs)->insert(std::make_pair(nrSamples, parameters));\n\t\t}\n }\n snrFile.close();\n}\n\nvoid readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::snrDedispersedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\n\t\tif ( tunedSNR.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\ttunedSNR.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\ttunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\nvoid readTunedSNRFoldedConf(tunedSNRFoldedConf & tunedSNR, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n\t\tunsigned int nrPeriods = 0;\n PulsarSearch::snrFoldedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( tunedSNR.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;\n std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\texternalContainer.insert(std::make_pair(nrDMs, internalContainer));\n\t\t\ttunedSNR.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( tunedSNR[deviceName].count(nrDMs) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\ttunedSNR[deviceName].insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\ttunedSNR[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));\n\t\t}\n\t}\n}\n\n} \/\/ PulsarSearch\n\n<commit_msg>Removing spurious parts introduced during the merge.<commit_after>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <SNR.hpp>\n\nnamespace PulsarSearch {\n\nsnrConf::snrConf() : nrThreadsD0(0), nrItemsD0(0) {}\n\nsnrConf::~snrConf() {}\n\nstd::string snrConf::print() const {\n return isa::utils::toString(nrThreadsD0) + \" \" + isa::utils::toString(nrItemsD0);\n}\n\nvoid readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename) {\n unsigned int nrDMs = 0;\n unsigned int nrSamples = 0;\n std::string temp;\n std::string deviceName;\n PulsarSearch::snrConf * parameters = 0;\n std::ifstream snrFile;\n\n snrFile.open(snrFilename);\n while ( ! snrFile.eof() ) {\n unsigned int splitPoint = 0;\n\n std::getline(snrFile, temp);\n if ( ! std::isalpha(temp[0]) ) {\n continue;\n }\n parameters = new PulsarSearch::snrConf();\n\n splitPoint = temp.find(\" \");\n deviceName = temp.substr(0, splitPoint);\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n temp = temp.substr(splitPoint + 1);\n splitPoint = temp.find(\" \");\n parameters->setNrThreadsD0(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n temp = temp.substr(splitPoint + 1);\n parameters->setNrItemsD0(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( tunedSNR.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * externalContainer = new std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * >();\n std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();\n\n\t\t\tinternalContainer->insert(std::make_pair(nrSamples, parameters));\n\t\t\texternalContainer->insert(std::make_pair(nrDMs, internalContainer));\n\t\t\ttunedSNR.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( tunedSNR.at(deviceName)->count(nrDMs) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();\n\n\t\t\tinternalContainer->insert(std::make_pair(nrSamples, parameters));\n\t\t\ttunedSNR.at(deviceName)->insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\ttunedSNR.at(deviceName)->at(nrDMs)->insert(std::make_pair(nrSamples, parameters));\n\t\t}\n }\n snrFile.close();\n}\n\nvoid readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::snrDedispersedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\n\t\tif ( tunedSNR.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\ttunedSNR.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\ttunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\n} \/\/ PulsarSearch\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include <vector>\n\n#include <dune\/common\/shared_ptr.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/function\/parametric\/separable\/checkerboard.hh>\n\n#include \"..\/..\/default.hh\"\n#include \"default.hh\"\n\nnamespace Dune {\nnamespace Detailed {\nnamespace Solvers {\nnamespace Stationary {\nnamespace Linear {\nnamespace Elliptic {\nnamespace Model {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass SeparableThermalblock;\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass SeparableThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n : public SeparableDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\npublic:\n typedef SeparableThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n typedef SeparableDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const int dimRange = BaseType::dimRange;\n typedef typename BaseType::ParamFieldType ParamFieldType;\n static const int maxParamDim = BaseType::maxParamDim;\n\n typedef typename Dune::Stuff::Function::SeparableCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >\n CheckerboardFunctionType;\n typedef typename BaseType::FunctionType FunctionType;\n\n static const std::string id()\n {\n return BaseType::BaseType::id() + \".parametric.separable.thermalblock\";\n }\n\n SeparableThermalblock(const Dune::shared_ptr< const CheckerboardFunctionType > _diffusion,\n const Dune::shared_ptr< const FunctionType > _force,\n const Dune::shared_ptr< const FunctionType > _dirichlet,\n const Dune::shared_ptr< const FunctionType > _neumann)\n : BaseType(_diffusion, _force, _dirichlet, _neumann)\n {}\n\n SeparableThermalblock(const ThisType& other)\n : BaseType(other.diffusion(),\n other.force(),\n other.dirichlet(),\n other.neumann())\n {}\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n BaseType::operator=(other);\n }\n return *this;\n }\n\n static ThisType createFromDescription(const Dune::ParameterTree& _description, const std::string _subName = id())\n {\n \/\/ get correct description\n typedef Stuff::Common::ExtendedParameterTree DescriptionType;\n DescriptionType description;\n if (_description.hasSub(_subName))\n description = _description.sub(_subName);\n else\n description = _description;\n \/\/ create the checkerboard diffusion\n const DescriptionType diffusionDescription = description.sub(\"diffusion\");\n const shared_ptr< const CheckerboardFunctionType > diffusion(new CheckerboardFunctionType(\n CheckerboardFunctionType::createFromDescription(diffusionDescription)));\n \/\/ create the rest of the functions\n \/\/ * therefore create a fake diffusion subdescription,\n description.sub(\"diffusion\") = CheckerboardFunctionType::createSampleDescription();\n description[\"diffusion.type\"] = \"function.parametric.separable.checkerboard\";\n \/\/ * create a default model\n const BaseType baseModel = BaseType::createFromDescription(description);\n \/\/ create and return\n return ThisType(diffusion,\n baseModel.force(),\n baseModel.dirichlet(),\n baseModel.neumann());\n } \/\/ static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())\n}; \/\/ class SeparableThermalblock\n\n\n} \/\/ namespace Model\n} \/\/ namespace Elliptic\n} \/\/ namespace Linear\n} \/\/ namespace Stationary\n} \/\/ namespace Solvers\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n<commit_msg>[...elliptic.model...separable.thermalblock] added createSampleDescription()<commit_after>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include <vector>\n\n#include <dune\/common\/shared_ptr.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/function\/parametric\/separable\/checkerboard.hh>\n#include <dune\/stuff\/function.hh>\n\n#include \"..\/..\/default.hh\"\n#include \"default.hh\"\n\nnamespace Dune {\nnamespace Detailed {\nnamespace Solvers {\nnamespace Stationary {\nnamespace Linear {\nnamespace Elliptic {\nnamespace Model {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass SeparableThermalblock;\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass SeparableThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n : public SeparableDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\npublic:\n typedef SeparableThermalblock< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n typedef SeparableDefault< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const int dimRange = BaseType::dimRange;\n typedef typename BaseType::ParamFieldType ParamFieldType;\n static const int maxParamDim = BaseType::maxParamDim;\n\n typedef typename Dune::Stuff::Function::SeparableCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >\n CheckerboardFunctionType;\n typedef typename BaseType::FunctionType FunctionType;\n\n static const std::string id()\n {\n return BaseType::BaseType::id() + \".parametric.separable.thermalblock\";\n }\n\n SeparableThermalblock(const Dune::shared_ptr< const CheckerboardFunctionType > _diffusion,\n const Dune::shared_ptr< const FunctionType > _force,\n const Dune::shared_ptr< const FunctionType > _dirichlet,\n const Dune::shared_ptr< const FunctionType > _neumann)\n : BaseType(_diffusion, _force, _dirichlet, _neumann)\n {}\n\n SeparableThermalblock(const ThisType& other)\n : BaseType(other.diffusion(),\n other.force(),\n other.dirichlet(),\n other.neumann())\n {}\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n BaseType::operator=(other);\n }\n return *this;\n }\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::Stuff::Common::ExtendedParameterTree description;\n description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,\n RangeFieldType, dimRange >(\"function.separable.checkerboard\"),\n \"diffusion\");\n description[\"diffusion.name\"] = \"diffusion\";\n description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,\n RangeFieldType, dimRange >(\"function.expression\"),\n \"force\");\n description[\"force.name\"] = \"force\";\n description[\"force.expression\"] = \"1.0\";\n description[\"force.order\"] = \"0\";\n description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,\n RangeFieldType, dimRange >(\"function.expression\"),\n \"neumann\");\n description[\"neumann.name\"] = \"neumann\";\n description[\"neumann.expression\"] = \"0.1\";\n description[\"neumann.order\"] = \"0\";\n description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,\n RangeFieldType, dimRange >(\"function.expression\"),\n \"dirichlet\");\n description[\"dirichlet.name\"] = \"dirichlet\";\n description[\"dirichlet.expression\"] = \"0.1*x[0]\";\n description[\"dirichlet.order\"] = \"1\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n }\n\n static ThisType createFromDescription(const Dune::ParameterTree& _description, const std::string _subName = id())\n {\n \/\/ get correct description\n typedef Stuff::Common::ExtendedParameterTree DescriptionType;\n DescriptionType description;\n if (_description.hasSub(_subName))\n description = _description.sub(_subName);\n else\n description = _description;\n \/\/ create the checkerboard diffusion\n const DescriptionType diffusionDescription = description.sub(\"diffusion\");\n const shared_ptr< const CheckerboardFunctionType > diffusion(new CheckerboardFunctionType(\n CheckerboardFunctionType::createFromDescription(diffusionDescription)));\n \/\/ create the rest of the functions\n \/\/ * therefore create a fake diffusion subdescription,\n description.sub(\"diffusion\") = CheckerboardFunctionType::createSampleDescription();\n description[\"diffusion.type\"] = \"function.separable.checkerboard\";\n \/\/ * create a default model\n const BaseType baseModel = BaseType::createFromDescription(description);\n \/\/ create and return\n return ThisType(diffusion,\n baseModel.force(),\n baseModel.dirichlet(),\n baseModel.neumann());\n } \/\/ static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())\n}; \/\/ class SeparableThermalblock\n\n\n} \/\/ namespace Model\n} \/\/ namespace Elliptic\n} \/\/ namespace Linear\n} \/\/ namespace Stationary\n} \/\/ namespace Solvers\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ v8\n#include <v8.h>\n\n\/\/ node\n#include <node.h>\n#include <node_version.h>\n\n\/\/ stl\n#include <sstream>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n\n\/\/ osr\n#include \"ogr_spatialref.h\"\n\/\/#include \"ogr_core.h\"\n\/\/#include \"cpl_conv.h\"\n#include \"cpl_string.h\"\n\/\/#include \"ogr_p.h\"\n\/\/#include \"cpl_multiproc.h\"\n\/\/#include \"ogr_srs_api.h\"\n\nusing namespace node;\nusing namespace v8;\n\n#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))\n\n\n\/*\nOGRERR_DICT = { 1 : (OGRException, \"Not enough data.\"),\n 2 : (OGRException, \"Not enough memory.\"),\n 3 : (OGRException, \"Unsupported geometry type.\"),\n 4 : (OGRException, \"Unsupported operation.\"),\n 5 : (OGRException, \"Corrupt data.\"),\n 6 : (OGRException, \"OGR failure.\"),\n 7 : (SRSException, \"Unsupported SRS.\"),\n 8 : (OGRException, \"Invalid handle.\"),\n }\n*\/\n\nstatic Handle<Value> parse(const Arguments& args)\n{\n HandleScope scope;\n\n if (args.Length() != 1 || !args[0]->IsString())\n return ThrowException(Exception::TypeError(\n String::New(\"first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string\")));\n\n OGRSpatialReference oSRS;\n\n Local<Object> result = Object::New();\n\n result->Set(String::NewSymbol(\"input\"), args[0]->ToString());\n \/\/ intialize as undefined\n result->Set(String::NewSymbol(\"proj4\"), Undefined());\n result->Set(String::NewSymbol(\"srid\"), Undefined());\n result->Set(String::NewSymbol(\"auth\"), Undefined());\n result->Set(String::NewSymbol(\"pretty_wkt\"), Undefined());\n result->Set(String::NewSymbol(\"esri\"), Undefined());\n result->Set(String::NewSymbol(\"name\"), Undefined());\n\n std::string wkt_string = TOSTR(args[0]->ToString());\n\n const char *wkt_char = wkt_string.data();\n\n bool error = false;\n\n Handle<Value> err;\n \n if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )\n {\n error = true;\n std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined\n << \" problem occured importing from srs wkt: \" << wkt_string << \".\\n\";;\n err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n\n \/\/ try again to import from ESRI\n oSRS.Clear();\n char **wkt_lines = NULL;\n wkt_lines = CSLTokenizeString2( wkt_char, \" \\t\\n\", \n CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );\n if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )\n {\n error = true;\n oSRS.Clear();\n \/\/std::ostringstream s;\n \/\/s << \"b: OGR Error type #\" << CPLE_AppDefined \n \/\/ << \" problem occured importing assuming esri wkt \" << wkt_string << \".\\n\";\n \/\/err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n }\n else\n {\n error = false;\n std::clog << \"imported assuming esri format...\\n\";\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(true));\n }\n }\n else\n {\n error = false;\n if (wkt_string.substr(0,6) == \"ESRI::\")\n {\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(true));\n }\n else\n {\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(false));\n }\n }\n \n if (error)\n return err;\n \n char *srs_output = NULL;\n if( oSRS.Validate() == OGRERR_NONE)\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(true));\n else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(false)); \n else\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(false));\n \n \/\/ TODO - trim output of proj4 result\n if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )\n {\n std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined \n << \" problem occured when converting to proj4 format \" << wkt_string << \".\\n\";\n \/\/ for now let proj4 errors be non-fatal so that some info can be known...\n \/\/std::clog << s.str();\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n \n }\n else\n {\n \/\/ proj4 strings from osr have an uneeded trailing slash, so we trim it...\n result->Set(String::NewSymbol(\"proj4\"), String::New(CPLString(srs_output).Trim()));\n }\n\n CPLFree( srs_output );\n\n if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )\n {\n \/*std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined \n << \" problem occured when attempting to auto identify epsg code \" << wkt_string << \".\\n\";\n std::clog << s.str();\n *\/\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n }\n\n if (oSRS.IsGeographic())\n {\n result->Set(String::NewSymbol(\"is_geographic\"), Boolean::New(true));\n const char *code = oSRS.GetAuthorityCode(\"GEOGCS\");\n if (code)\n result->Set(String::NewSymbol(\"srid\"), Integer::New(atoi(code)));\n const char *auth = oSRS.GetAuthorityName(\"GEOGCS\");\n if (auth)\n result->Set(String::NewSymbol(\"auth\"), String::New(auth));\n const char *name = oSRS.GetAttrValue(\"GEOGCS\");\n if (name)\n result->Set(String::NewSymbol(\"name\"), String::New(name));\n }\n else\n {\n result->Set(String::NewSymbol(\"is_geographic\"), Boolean::New(false));\n const char *code = oSRS.GetAuthorityCode(\"PROJCS\");\n if (code)\n result->Set(String::NewSymbol(\"srid\"), Integer::New(atoi(code)));\n const char *auth = oSRS.GetAuthorityName(\"PROJCS\");\n if (auth)\n result->Set(String::NewSymbol(\"auth\"), String::New(auth));\n const char *name = oSRS.GetAttrValue(\"PROJCS\");\n if (name)\n result->Set(String::NewSymbol(\"name\"), String::New(name));\n }\n\n char *srs_output2 = NULL;\n if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )\n {\n \/\/ this does not yet actually return errors\n std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined \n << \" problem occured when converting to pretty wkt format \" << wkt_string << \".\\n\";\n \/\/std::clog << s.str();\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n }\n else\n {\n result->Set(String::NewSymbol(\"pretty_wkt\"), String::New(srs_output2));\n }\n\n CPLFree( srs_output2 );\n \/\/OGRSpatialReference::DestroySpatialReference( &oSRS );\n return scope.Close(result);\n}\n\n\nextern \"C\" {\n\n static void init (Handle<Object> target)\n {\n\n NODE_SET_METHOD(target, \"_parse\", parse);\n \n \/\/ versions of deps\n Local<Object> versions = Object::New();\n versions->Set(String::NewSymbol(\"node\"), String::New(NODE_VERSION+1));\n versions->Set(String::NewSymbol(\"v8\"), String::New(V8::GetVersion()));\n \/\/ ogr\/osr ?\n target->Set(String::NewSymbol(\"versions\"), versions);\n\n }\n\n NODE_MODULE(_srs, init);\n}\n<commit_msg>cleanup<commit_after>\/\/ v8\n#include <v8.h>\n\n\/\/ node\n#include <node.h>\n#include <node_version.h>\n\n\/\/ stl\n#include <sstream>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n\n\/\/ osr\n#include \"ogr_spatialref.h\"\n#include \"cpl_error.h\" \/\/ CPLE_AppDefined\n#include \"cpl_conv.h\" \/\/ CPLFree\n#include \"cpl_string.h\" \/\/ CPLString\n\nusing namespace node;\nusing namespace v8;\n\n#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))\n\n\/*\nOGRERR_DICT = { 1 : (OGRException, \"Not enough data.\"),\n 2 : (OGRException, \"Not enough memory.\"),\n 3 : (OGRException, \"Unsupported geometry type.\"),\n 4 : (OGRException, \"Unsupported operation.\"),\n 5 : (OGRException, \"Corrupt data.\"),\n 6 : (OGRException, \"OGR failure.\"),\n 7 : (SRSException, \"Unsupported SRS.\"),\n 8 : (OGRException, \"Invalid handle.\"),\n }\n*\/\n\nstatic Handle<Value> parse(const Arguments& args)\n{\n HandleScope scope;\n\n if (args.Length() != 1 || !args[0]->IsString())\n return ThrowException(Exception::TypeError(\n String::New(\"first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string\")));\n\n OGRSpatialReference oSRS;\n\n Local<Object> result = Object::New();\n\n result->Set(String::NewSymbol(\"input\"), args[0]->ToString());\n \/\/ intialize as undefined\n result->Set(String::NewSymbol(\"proj4\"), Undefined());\n result->Set(String::NewSymbol(\"srid\"), Undefined());\n result->Set(String::NewSymbol(\"auth\"), Undefined());\n result->Set(String::NewSymbol(\"pretty_wkt\"), Undefined());\n result->Set(String::NewSymbol(\"esri\"), Undefined());\n result->Set(String::NewSymbol(\"name\"), Undefined());\n\n std::string wkt_string = TOSTR(args[0]->ToString());\n\n const char *wkt_char = wkt_string.data();\n\n bool error = false;\n\n Handle<Value> err;\n \n if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )\n {\n error = true;\n std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined\n << \" problem occured importing from srs wkt: \" << wkt_string << \".\\n\";;\n err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n\n \/\/ try again to import from ESRI\n oSRS.Clear();\n char **wkt_lines = NULL;\n wkt_lines = CSLTokenizeString2( wkt_char, \" \\t\\n\", \n CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );\n if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )\n {\n error = true;\n oSRS.Clear();\n }\n else\n {\n error = false;\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(true));\n }\n }\n else\n {\n error = false;\n if (wkt_string.substr(0,6) == \"ESRI::\")\n {\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(true));\n }\n else\n {\n result->Set(String::NewSymbol(\"esri\"), Boolean::New(false));\n }\n }\n \n if (error)\n return err;\n \n char *srs_output = NULL;\n if( oSRS.Validate() == OGRERR_NONE)\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(true));\n else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(false)); \n else\n result->Set(String::NewSymbol(\"valid\"), Boolean::New(false));\n \n \/\/ TODO - trim output of proj4 result\n if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )\n {\n \/\/std::ostringstream s;\n \/\/s << \"OGR Error type #\" << CPLE_AppDefined\n \/\/ << \" problem occured when converting to proj4 format \" << wkt_string << \".\\n\";\n \/\/ for now let proj4 errors be non-fatal so that some info can be known...\n \/\/std::clog << s.str();\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n \n }\n else\n {\n \/\/ proj4 strings from osr have an uneeded trailing slash, so we trim it...\n result->Set(String::NewSymbol(\"proj4\"), String::New(CPLString(srs_output).Trim()));\n }\n\n CPLFree( srs_output );\n\n if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )\n {\n \/*std::ostringstream s;\n s << \"OGR Error type #\" << CPLE_AppDefined\n << \" problem occured when attempting to auto identify epsg code \" << wkt_string << \".\\n\";\n std::clog << s.str();\n *\/\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n }\n\n if (oSRS.IsGeographic())\n {\n result->Set(String::NewSymbol(\"is_geographic\"), Boolean::New(true));\n const char *code = oSRS.GetAuthorityCode(\"GEOGCS\");\n if (code)\n result->Set(String::NewSymbol(\"srid\"), Integer::New(atoi(code)));\n const char *auth = oSRS.GetAuthorityName(\"GEOGCS\");\n if (auth)\n result->Set(String::NewSymbol(\"auth\"), String::New(auth));\n const char *name = oSRS.GetAttrValue(\"GEOGCS\");\n if (name)\n result->Set(String::NewSymbol(\"name\"), String::New(name));\n }\n else\n {\n result->Set(String::NewSymbol(\"is_geographic\"), Boolean::New(false));\n const char *code = oSRS.GetAuthorityCode(\"PROJCS\");\n if (code)\n result->Set(String::NewSymbol(\"srid\"), Integer::New(atoi(code)));\n const char *auth = oSRS.GetAuthorityName(\"PROJCS\");\n if (auth)\n result->Set(String::NewSymbol(\"auth\"), String::New(auth));\n const char *name = oSRS.GetAttrValue(\"PROJCS\");\n if (name)\n result->Set(String::NewSymbol(\"name\"), String::New(name));\n }\n\n char *srs_output2 = NULL;\n if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )\n {\n \/\/ this does not yet actually return errors\n \/\/std::ostringstream s;\n \/\/s << \"OGR Error type #\" << CPLE_AppDefined\n \/\/ << \" problem occured when converting to pretty wkt format \" << wkt_string << \".\\n\";\n \/\/std::clog << s.str();\n \/\/return ThrowException(Exception::TypeError(String::New(s.str().c_str())));\n }\n else\n {\n result->Set(String::NewSymbol(\"pretty_wkt\"), String::New(srs_output2));\n }\n\n CPLFree( srs_output2 );\n \/\/OGRSpatialReference::DestroySpatialReference( &oSRS );\n return scope.Close(result);\n}\n\n\nextern \"C\" {\n\n static void init (Handle<Object> target)\n {\n\n NODE_SET_METHOD(target, \"_parse\", parse);\n \n \/\/ versions of deps\n Local<Object> versions = Object::New();\n versions->Set(String::NewSymbol(\"node\"), String::New(NODE_VERSION+1));\n versions->Set(String::NewSymbol(\"v8\"), String::New(V8::GetVersion()));\n \/\/ ogr\/osr ?\n target->Set(String::NewSymbol(\"versions\"), versions);\n\n }\n\n NODE_MODULE(_srs, init);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QAction>\n#include <QDir>\n#include <QFileDialog>\n#include <QFileInfo>\n#include <QLayout>\n#include <QListWidgetItem>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QInputDialog>\n#include <QWidget>\n#include <iostream>\n\n#include \"app.h\"\n#include \"db.h\"\n#include \"executables.h\"\n#include \"settings.h\"\n#include \"models\/platform.h\"\n#include \"ui_app.h\"\n\nApp::App(int & argc, char** argv) :\n\tQApplication(argc,argv),\n\tmainWidget(nullptr),\n\texecutablesWidget(nullptr),\n\tsettingsWidget(nullptr),\n\tscraping(nullptr), \n\timport(nullptr),\n\tplatforms(nullptr) {\n\tsetApplicationName(\"mehstation-config\");\n\tconnect(this, SIGNAL(aboutToQuit()), SLOT(onQuit()));\n}\n\nApp::~App() {\n\tif (scraping != nullptr) {\n\t\tdelete scraping;\n\t}\n\tif (platforms != nullptr) {\n\t\tdelete platforms;\n\t}\n}\n\nbool App::loadWindow() {\n\tthis->ui.setupUi(&this->mainWidget);\n\n\t\/*\n\t * Menu\n\t *\/\n\n\t\/\/ Quit action\n\tQAction* actionQuit = this->ui.actionQuit;\n\tconnect(actionQuit, SIGNAL(triggered()), this, SLOT(onClickQuit()));\n\t\/\/ Open action\n\tQAction* actionOpen = this->ui.actionOpen;\n\tconnect(actionOpen, SIGNAL(triggered()), this, SLOT(onClickOpen()));\n\tconnect(&fileDialog, SIGNAL(fileSelected(const QString&)), this, SLOT(onFileSelected(const QString&)));\n\t\/\/ Scraping action\n\tconnect(this->ui.actionScraping, SIGNAL(triggered()), this, SLOT(onOpenScraping()));\n\t\/\/ Import from ES\n\tconnect(this->ui.actionImport, SIGNAL(triggered()), this, SLOT(onImport()));\n\n\tQAction* actionAbout = this->ui.actionAbout;\n\tconnect(actionAbout, SIGNAL(triggered()), this, SLOT(onAbout()));\n\n\t\/*\n\t * Platforms list\n\t *\/\n\n\t\/\/ Select an entry\n\tQListWidget* listPlatforms = this->ui.listPlatforms;\n\tconnect(listPlatforms, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onPlatformSelected(QListWidgetItem*, QListWidgetItem*)));\n\n\tQPushButton *deletePlatform = this->ui.deletePlatform;\n\tconnect(deletePlatform, SIGNAL(clicked()), this, SLOT(onDeletePlatform()));\n\n\tQPushButton *addPlatform = this->ui.addPlatform;\n\tconnect(addPlatform, SIGNAL(clicked()), this, SLOT(onNewPlatform()));\n\taddPlatform->setEnabled(true);\n\n\t\/\/ NOTE We forces the use of the non-native dialog because with the native\n\t\/\/ NOTE the slot onFileSelected is called two times. - remy\n\tfileDialog.setOption(QFileDialog::DontUseNativeDialog, true);\n\n\t\/\/ Prepares the scraping window\n\tthis->scraping = new Scraping(this);\n\n\tthis->import = new Import(this);\n\n\treturn true;\n}\n\nvoid App::showWindow() {\n\tthis->mainWidget.show();\n\tthis->mainWidget.raise();\n}\n\nvoid App::onQuit() {\n\tstd::cout << \"Exiting mehstation-config.\" << std::endl;\n\n\t\/\/ Closes all windows.\n\tif (this->scraping != nullptr) {\n\t\tdelete this->scraping;\n\t\tthis->scraping = nullptr;\n\t}\n\n\tif (this->import != nullptr) {\n\t\tdelete this->import;\n\t\tthis->import = nullptr;\n\t}\n}\n\nvoid App::onClickQuit() {\n\tthis->exit();\n}\n\nvoid App::onAbout() {\n\tQMessageBox::about(NULL, \"mehstation config\", \"<b>mehstation configuration<\/b><br>Interface to setup your mehstation<br>Bad code written by Rémy 'remeh' Mathieu\");\n}\n\nvoid App::onClickOpen() {\n\tthis->fileDialog.show();\n}\n\nvoid App::onOpenScraping() {\n\tscraping->show();\n\tscraping->getPlatforms();\n}\n\nvoid App::onImport() {\n\timport->show();\n\timport->reset();\n}\n\nvoid App::onNewPlatform() {\n\tQString name = QInputDialog::getText(NULL, \"Platform name ?\", \"Enter a name for the new platform\");\n\tif (name.length() == 0) {\n\t\treturn;\n\t}\n\tPlatform p = this->getDb()->createNewPlatform(name);\n\tthis->platforms->append(p);\n\tPlatformItem* item = new PlatformItem(p.name, p.id);\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tlistPlatforms->addItem(item);\n\tlistPlatforms->setCurrentItem(item);\n\tthis->onPlatformSelected(NULL, item);\n}\n\nvoid App::onDeletePlatform() {\n\tQMessageBox::StandardButton result = QMessageBox::question(NULL, \"Deletion confirmation\", \"Are you sure to delete this platform along with all its executables and executable resources ? This can't be undone!\");\n\tif (result == QMessageBox::StandardButton::Yes) {\n\t\tthis->getDb()->deletePlatform(this->selectedPlatform);\n\t\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\t\tdelete listPlatforms->currentItem();\n\t\tif (listPlatforms->currentItem() != NULL) {\n\t\t\tthis->onPlatformSelected(NULL, listPlatforms->currentItem());\n\t\t}\n\t}\n}\n\nvoid App::updatePlatformList() {\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tQListWidgetItem* item = listPlatforms->currentItem();\n\tif (item != NULL) {\n\t\titem->setText(this->selectedPlatform.name);\n\t}\n}\n\ninline QListWidget* App::getPlatformListWidget() {\n\treturn this->ui.listPlatforms;\n}\n\nvoid App::onPlatformSelected(QListWidgetItem* item, QListWidgetItem*) {\n\tif (item == NULL || platforms == NULL) {\n\t\treturn;\n\t}\n\n\titem->setSelected(true);\n\n\t\/\/ look for the platform in the list of loaded platforms.\n\tPlatform p;\n\tPlatform clickedPlatform;\n\tforeach (p, *platforms) {\n\t\tif (p.id == item->data(MEH_ROLE_PLATFORM_ITEM).toInt()) {\n\t\t\tclickedPlatform = p;\n\n\t\t\tthis->scraping->setPlatformId(p.id);\n\t\t\tthis->import->setPlatformId(p.id);\n\n\t\t\tif (p.id >= 0) {\n\t\t\t\tthis->ui.actionScraping->setEnabled(true);\n\t\t\t\tthis->ui.actionImport->setEnabled(true);\n\t\t\t} else {\n\t\t\t\tthis->ui.actionScraping->setEnabled(false);\n\t\t\t\tthis->ui.actionImport->setEnabled(false);\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ same platform, stop here.\n\tif (clickedPlatform.id == this->selectedPlatform.id) {\n\t\treturn;\n\t}\n\n\tthis->selectedPlatform = clickedPlatform;\n\n\t\/\/ create the executable widget.\n\tif (this->executablesWidget != nullptr) {\n\t\tdelete this->executablesWidget;\n\t}\n\tif (this->settingsWidget != nullptr) {\n\t\tdelete this->settingsWidget;\n\t}\n\n\tQWidget* executablesTab = this->ui.executables;\n\tExecutables* executables = new Executables(this, NULL);\n\texecutablesTab->layout()->addWidget(executables);\n\t\/\/ load all the executables of this platform and assign it to the widget.\n\texecutables->setExecutables(this->db.getExecutables(this->selectedPlatform.id));\n\tthis->executablesWidget = executables;\n\n\tQWidget* settingsTab = this->ui.settings;\n\tSettings* settings = new Settings(this, NULL);\n\tsettingsTab->layout()->addWidget(settings);\n\tthis->settingsWidget = settings;\n\n\t\/\/ enable the tab\n\tQWidget* tabWidget = this->ui.tabWidget;\n\ttabWidget->setEnabled(true);\n\n\tQPushButton *deletePlatform = this->ui.deletePlatform;\n\tdeletePlatform->setEnabled(true);\n}\n\n\/\/ onFileSelected called when a database file has been selected.\nvoid App::onFileSelected(const QString& filename) {\n\tQFile file(filename);\n\tif (!file.exists()) {\n\t\tQMessageBox msgBox(QMessageBox::Critical, \"Error\", \"This file doesn't exist. Please select an existing database.\");\n\t\tmsgBox.exec();\n\t\treturn;\n\t}\n\n\t\/\/ open the database\n\tdb.open(filename);\n\n\tif (this->platforms != nullptr) {\n\t\tdelete this->platforms;\n\t}\n\tQList<Platform>* platforms = db.getPlatforms();\n\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tlistPlatforms->clear();\n\n\tif (platforms != nullptr) {\n\t\t\/\/ store the list pointer\n\t\tthis->platforms = platforms;\n\n\t\t\/\/ add all platforms in the view.\n\t\tPlatform p;\n\t\tforeach (p, *platforms) {\n\t\t\tPlatformItem* item = new PlatformItem(p.name, p.id);\n\t\t\tlistPlatforms->addItem(item);\n\t\t}\n\t}\n}\n\nQString App::mehtadataPath() {\n\tQFileInfo current(QDir::currentPath() + \"\/mehtadata\");\n\n\tif (current.exists() && current.isFile()) {\n\t\treturn \".\/mehtadata\";\n\t}\n\n#ifdef Q_OS_LINUX\n\tcurrent = QFileInfo(\"\/usr\/bin\/mehtadata\");\n\n\tif (current.exists() && current.isFile()) {\n\t\treturn \"\/usr\/bin\/mehtadata\";\n\t}\n#endif\n\n\treturn \"\";\n}\n<commit_msg>Add .exe on windows when looking for mehtadata<commit_after>#include <QAction>\n#include <QDebug>\n#include <QDir>\n#include <QFileDialog>\n#include <QFileInfo>\n#include <QLayout>\n#include <QListWidgetItem>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QInputDialog>\n#include <QWidget>\n#include <iostream>\n\n#include \"app.h\"\n#include \"db.h\"\n#include \"executables.h\"\n#include \"settings.h\"\n#include \"models\/platform.h\"\n#include \"ui_app.h\"\n\nApp::App(int & argc, char** argv) :\n\tQApplication(argc,argv),\n\tmainWidget(nullptr),\n\texecutablesWidget(nullptr),\n\tsettingsWidget(nullptr),\n\tscraping(nullptr), \n\timport(nullptr),\n\tplatforms(nullptr) {\n\tsetApplicationName(\"mehstation-config\");\n\tconnect(this, SIGNAL(aboutToQuit()), SLOT(onQuit()));\n}\n\nApp::~App() {\n\tif (scraping != nullptr) {\n\t\tdelete scraping;\n\t}\n\tif (platforms != nullptr) {\n\t\tdelete platforms;\n\t}\n}\n\nbool App::loadWindow() {\n\tthis->ui.setupUi(&this->mainWidget);\n\n\t\/*\n\t * Menu\n\t *\/\n\n\t\/\/ Quit action\n\tQAction* actionQuit = this->ui.actionQuit;\n\tconnect(actionQuit, SIGNAL(triggered()), this, SLOT(onClickQuit()));\n\t\/\/ Open action\n\tQAction* actionOpen = this->ui.actionOpen;\n\tconnect(actionOpen, SIGNAL(triggered()), this, SLOT(onClickOpen()));\n\tconnect(&fileDialog, SIGNAL(fileSelected(const QString&)), this, SLOT(onFileSelected(const QString&)));\n\t\/\/ Scraping action\n\tconnect(this->ui.actionScraping, SIGNAL(triggered()), this, SLOT(onOpenScraping()));\n\t\/\/ Import from ES\n\tconnect(this->ui.actionImport, SIGNAL(triggered()), this, SLOT(onImport()));\n\n\tQAction* actionAbout = this->ui.actionAbout;\n\tconnect(actionAbout, SIGNAL(triggered()), this, SLOT(onAbout()));\n\n\t\/*\n\t * Platforms list\n\t *\/\n\n\t\/\/ Select an entry\n\tQListWidget* listPlatforms = this->ui.listPlatforms;\n\tconnect(listPlatforms, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onPlatformSelected(QListWidgetItem*, QListWidgetItem*)));\n\n\tQPushButton *deletePlatform = this->ui.deletePlatform;\n\tconnect(deletePlatform, SIGNAL(clicked()), this, SLOT(onDeletePlatform()));\n\n\tQPushButton *addPlatform = this->ui.addPlatform;\n\tconnect(addPlatform, SIGNAL(clicked()), this, SLOT(onNewPlatform()));\n\taddPlatform->setEnabled(true);\n\n\t\/\/ NOTE We forces the use of the non-native dialog because with the native\n\t\/\/ NOTE the slot onFileSelected is called two times. - remy\n\tfileDialog.setOption(QFileDialog::DontUseNativeDialog, true);\n\n\t\/\/ Prepares the scraping window\n\tthis->scraping = new Scraping(this);\n\n\tthis->import = new Import(this);\n\n\treturn true;\n}\n\nvoid App::showWindow() {\n\tthis->mainWidget.show();\n\tthis->mainWidget.raise();\n}\n\nvoid App::onQuit() {\n\tstd::cout << \"Exiting mehstation-config.\" << std::endl;\n\n\t\/\/ Closes all windows.\n\tif (this->scraping != nullptr) {\n\t\tdelete this->scraping;\n\t\tthis->scraping = nullptr;\n\t}\n\n\tif (this->import != nullptr) {\n\t\tdelete this->import;\n\t\tthis->import = nullptr;\n\t}\n}\n\nvoid App::onClickQuit() {\n\tthis->exit();\n}\n\nvoid App::onAbout() {\n\tQMessageBox::about(NULL, \"mehstation config\", \"<b>mehstation configuration<\/b><br>Interface to setup your mehstation<br>Bad code written by Rémy 'remeh' Mathieu\");\n}\n\nvoid App::onClickOpen() {\n\tthis->fileDialog.show();\n}\n\nvoid App::onOpenScraping() {\n\tscraping->show();\n\tscraping->getPlatforms();\n}\n\nvoid App::onImport() {\n\timport->show();\n\timport->reset();\n}\n\nvoid App::onNewPlatform() {\n\tQString name = QInputDialog::getText(NULL, \"Platform name ?\", \"Enter a name for the new platform\");\n\tif (name.length() == 0) {\n\t\treturn;\n\t}\n\tPlatform p = this->getDb()->createNewPlatform(name);\n\tthis->platforms->append(p);\n\tPlatformItem* item = new PlatformItem(p.name, p.id);\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tlistPlatforms->addItem(item);\n\tlistPlatforms->setCurrentItem(item);\n\tthis->onPlatformSelected(NULL, item);\n}\n\nvoid App::onDeletePlatform() {\n\tQMessageBox::StandardButton result = QMessageBox::question(NULL, \"Deletion confirmation\", \"Are you sure to delete this platform along with all its executables and executable resources ? This can't be undone!\");\n\tif (result == QMessageBox::StandardButton::Yes) {\n\t\tthis->getDb()->deletePlatform(this->selectedPlatform);\n\t\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\t\tdelete listPlatforms->currentItem();\n\t\tif (listPlatforms->currentItem() != NULL) {\n\t\t\tthis->onPlatformSelected(NULL, listPlatforms->currentItem());\n\t\t}\n\t}\n}\n\nvoid App::updatePlatformList() {\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tQListWidgetItem* item = listPlatforms->currentItem();\n\tif (item != NULL) {\n\t\titem->setText(this->selectedPlatform.name);\n\t}\n}\n\ninline QListWidget* App::getPlatformListWidget() {\n\treturn this->ui.listPlatforms;\n}\n\nvoid App::onPlatformSelected(QListWidgetItem* item, QListWidgetItem*) {\n\tif (item == NULL || platforms == NULL) {\n\t\treturn;\n\t}\n\n\titem->setSelected(true);\n\n\t\/\/ look for the platform in the list of loaded platforms.\n\tPlatform p;\n\tPlatform clickedPlatform;\n\tforeach (p, *platforms) {\n\t\tif (p.id == item->data(MEH_ROLE_PLATFORM_ITEM).toInt()) {\n\t\t\tclickedPlatform = p;\n\n\t\t\tthis->scraping->setPlatformId(p.id);\n\t\t\tthis->import->setPlatformId(p.id);\n\n\t\t\tif (p.id >= 0) {\n\t\t\t\tthis->ui.actionScraping->setEnabled(true);\n\t\t\t\tthis->ui.actionImport->setEnabled(true);\n\t\t\t} else {\n\t\t\t\tthis->ui.actionScraping->setEnabled(false);\n\t\t\t\tthis->ui.actionImport->setEnabled(false);\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ same platform, stop here.\n\tif (clickedPlatform.id == this->selectedPlatform.id) {\n\t\treturn;\n\t}\n\n\tthis->selectedPlatform = clickedPlatform;\n\n\t\/\/ create the executable widget.\n\tif (this->executablesWidget != nullptr) {\n\t\tdelete this->executablesWidget;\n\t}\n\tif (this->settingsWidget != nullptr) {\n\t\tdelete this->settingsWidget;\n\t}\n\n\tQWidget* executablesTab = this->ui.executables;\n\tExecutables* executables = new Executables(this, NULL);\n\texecutablesTab->layout()->addWidget(executables);\n\t\/\/ load all the executables of this platform and assign it to the widget.\n\texecutables->setExecutables(this->db.getExecutables(this->selectedPlatform.id));\n\tthis->executablesWidget = executables;\n\n\tQWidget* settingsTab = this->ui.settings;\n\tSettings* settings = new Settings(this, NULL);\n\tsettingsTab->layout()->addWidget(settings);\n\tthis->settingsWidget = settings;\n\n\t\/\/ enable the tab\n\tQWidget* tabWidget = this->ui.tabWidget;\n\ttabWidget->setEnabled(true);\n\n\tQPushButton *deletePlatform = this->ui.deletePlatform;\n\tdeletePlatform->setEnabled(true);\n}\n\n\/\/ onFileSelected called when a database file has been selected.\nvoid App::onFileSelected(const QString& filename) {\n\tQFile file(filename);\n\tif (!file.exists()) {\n\t\tQMessageBox msgBox(QMessageBox::Critical, \"Error\", \"This file doesn't exist. Please select an existing database.\");\n\t\tmsgBox.exec();\n\t\treturn;\n\t}\n\n\t\/\/ open the database\n\tdb.open(filename);\n\n\tif (this->platforms != nullptr) {\n\t\tdelete this->platforms;\n\t}\n\tQList<Platform>* platforms = db.getPlatforms();\n\n\tQListWidget* listPlatforms = this->getPlatformListWidget();\n\tlistPlatforms->clear();\n\n\tif (platforms != nullptr) {\n\t\t\/\/ store the list pointer\n\t\tthis->platforms = platforms;\n\n\t\t\/\/ add all platforms in the view.\n\t\tPlatform p;\n\t\tforeach (p, *platforms) {\n\t\t\tPlatformItem* item = new PlatformItem(p.name, p.id);\n\t\t\tlistPlatforms->addItem(item);\n\t\t}\n\t}\n}\n\nQString App::mehtadataPath() {\n\tQString mehtadata(\"\/mehtadata\");\n\n#ifdef Q_OS_WIN\n\tmehtadata += \".exe\";\n#endif\n\n\tQFileInfo current(QDir::currentPath() + mehtadata);\n\n\tif (current.exists() && current.isFile()) {\n\t\treturn QDir::currentPath() + mehtadata;\n\t}\n\n\tqDebug() << QString( QDir::currentPath() + mehtadata );\n\n#ifdef Q_OS_LINUX\n\tcurrent = QFileInfo(\"\/usr\/bin\/mehtadata\");\n\n\tif (current.exists() && current.isFile()) {\n\t\treturn \"\/usr\/bin\/mehtadata\";\n\t}\n#endif\n\n\treturn \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named LICENSE that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\/* bzflag special common - 1st one *\/\n#include \"common.h\"\n\n#include <iostream>\n#include <string>\n\n#include \"WorldEventManager.h\"\n\n\/\/-------------------BaseEventData--------------------\nBaseEventData::BaseEventData()\n{\n\teventType = eNullEvent;\n}\n\n\/\/-------------------CTFCaptureEventData--------------------\nCTFCaptureEventData::CTFCaptureEventData()\n{\n\teventType = eCaptureEvent;\n\tteamCAped = -1;\n\tteamCaping = -1;\n\tplayerCaping = -1;\n}\n\nCTFCaptureEventData::~CTFCaptureEventData()\n{\n}\n\n\/\/-------------------PlayerDieEventData--------------------\nPlayerDieEventData::PlayerDieEventData()\n{\n\teventType = ePlayerDieEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\tkillerID = -1;\n\tkillerTeamID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nPlayerDieEventData::~PlayerDieEventData()\n{\n}\n\n\/\/-------------------PlayerSpawnEventData--------------------\nPlayerSpawnEventData::PlayerSpawnEventData()\n{\n\teventType = ePlayerSpawnEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nPlayerSpawnEventData::~PlayerSpawnEventData()\n{\n}\n\n\/\/-------------------ZoneEntryExitEventData--------------------\nZoneEntryExitEventData::ZoneEntryExitEventData()\n{\n\teventType = eZoneEntryEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\tzoneID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nZoneEntryExitEventData::~ZoneEntryExitEventData()\n{\n}\n\n\/\/-------------------PlayerJoinPartEventData--------------------\nPlayerJoinPartEventData::PlayerJoinPartEventData()\n{\n\teventType = ePlayerJoinEvent;\n\n\tplayerID = -1;\n\tteamID = -1;\n\ttime = 0.0;\n}\n\nPlayerJoinPartEventData::~PlayerJoinPartEventData()\n{\n}\n\n\/\/-------------------WorldEventManager--------------------\nWorldEventManager::WorldEventManager()\n{\n}\n\nWorldEventManager::~WorldEventManager()\n{\n\ttmEventMap::iterator teamItr = eventtMap.begin();\n\twhile ( teamItr != eventtMap.end() )\n\t{\n\t\ttmEventTypeList::iterator eventItr = teamItr->second.begin();\n\t\twhile (eventItr == teamItr->second.end())\n\t\t{\n\t\t\ttvEventList::iterator itr = eventItr->second.begin();\n\t\t\twhile ( itr != eventItr->second.end() )\n\t\t\t{\n\t\t\t\tif ((*itr) && (*itr)->autoDelete())\n\t\t\t\t\tdelete (*itr++);\n\t\t\t}\n\t\t\teventItr++;\n\t\t}\n\t\tteamItr++;\n\t}\n}\n\nvoid WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )\n{\n\tif (!theEvetnt)\n\t\treturn;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\tif (teamEvents->find(eventType) == teamEvents->end())\n\t{\n\t\ttvEventList newList;\n\t\t(*teamEvents)[eventType] = newList;\n\t}\n\n\tteamEvents->find(eventType)->second.push_back(theEvetnt);\n}\n\nvoid WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )\n{\n\tif (!theEvetnt)\n\t\treturn;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\tif (teamEvents->find(eventType) == teamEvents->end())\n\t\treturn;\n\n\ttmEventTypeList::iterator eventTypeItr = teamEvents->begin();\n\tif ( eventTypeItr != teamEvents->end() )\n\t{\n\t\ttvEventList::iterator itr = eventTypeItr->second.begin();\n\t\twhile (itr == eventTypeItr->second.end())\n\t\t{\n\t\t\tif (*itr == theEvetnt)\n\t\t\t\titr = eventTypeItr->second.erase(itr);\n\t\t\telse\n\t\t\t\titr++;\n\t\t}\n\t}\n}\n\ntvEventList WorldEventManager::getEventList ( teEventType eventType, int team )\n\n{\n\ttvEventList\teventList;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\ttmEventTypeList::iterator teamItr = teamEvents->find(eventType);\n\tif ( teamItr == teamEvents->end() )\n\t\treturn eventList;\n\n\teventList = teamItr->second;\n\treturn eventList;\n}\n\nvoid WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData\t*eventData )\n{\n\tif (!eventData)\n\t\treturn;\n\n\ttvEventList\teventList = getEventList(eventType,team);\n\n\tfor ( unsigned int i = 0; i < eventList.size(); i++)\n\t\teventList[i]->process(eventData);\n}\n\ntmEventTypeList* WorldEventManager::getTeamEventList ( int team )\n{\n\tif (eventtMap.find(team) == eventtMap.end())\n\t{\n\t\ttmEventTypeList newList;\n\t\teventtMap[team] = newList;\n\t}\n\treturn &(eventtMap.find(team)->second);\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>really make sure you don't delete a null<commit_after>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named LICENSE that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\/* bzflag special common - 1st one *\/\n#include \"common.h\"\n\n#include <iostream>\n#include <string>\n\n#include \"WorldEventManager.h\"\n\n\/\/-------------------BaseEventData--------------------\nBaseEventData::BaseEventData()\n{\n\teventType = eNullEvent;\n}\n\n\/\/-------------------CTFCaptureEventData--------------------\nCTFCaptureEventData::CTFCaptureEventData()\n{\n\teventType = eCaptureEvent;\n\tteamCAped = -1;\n\tteamCaping = -1;\n\tplayerCaping = -1;\n}\n\nCTFCaptureEventData::~CTFCaptureEventData()\n{\n}\n\n\/\/-------------------PlayerDieEventData--------------------\nPlayerDieEventData::PlayerDieEventData()\n{\n\teventType = ePlayerDieEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\tkillerID = -1;\n\tkillerTeamID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nPlayerDieEventData::~PlayerDieEventData()\n{\n}\n\n\/\/-------------------PlayerSpawnEventData--------------------\nPlayerSpawnEventData::PlayerSpawnEventData()\n{\n\teventType = ePlayerSpawnEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nPlayerSpawnEventData::~PlayerSpawnEventData()\n{\n}\n\n\/\/-------------------ZoneEntryExitEventData--------------------\nZoneEntryExitEventData::ZoneEntryExitEventData()\n{\n\teventType = eZoneEntryEvent;\n\tplayerID = -1;\n\tteamID = -1;\n\tzoneID = -1;\n\n\tpos[0] = pos[1] = pos[2] = 0.0f;\n\trot = 0.0f;\n\ttime = 0.0;\n}\n\nZoneEntryExitEventData::~ZoneEntryExitEventData()\n{\n}\n\n\/\/-------------------PlayerJoinPartEventData--------------------\nPlayerJoinPartEventData::PlayerJoinPartEventData()\n{\n\teventType = ePlayerJoinEvent;\n\n\tplayerID = -1;\n\tteamID = -1;\n\ttime = 0.0;\n}\n\nPlayerJoinPartEventData::~PlayerJoinPartEventData()\n{\n}\n\n\/\/-------------------WorldEventManager--------------------\nWorldEventManager::WorldEventManager()\n{\n}\n\nWorldEventManager::~WorldEventManager()\n{\n\ttmEventMap::iterator teamItr = eventtMap.begin();\n\twhile ( teamItr != eventtMap.end() )\n\t{\n\t\ttmEventTypeList::iterator eventItr = teamItr->second.begin();\n\t\twhile (eventItr == teamItr->second.end())\n\t\t{\n\t\t\ttvEventList::iterator itr = eventItr->second.begin();\n\t\t\twhile ( itr != eventItr->second.end() )\n\t\t\t{\n\t\t\t\tif ((*itr) && (*itr)->autoDelete())\n\t\t\t\t\tdelete (*itr++);\n\t\t\t\t*itr = NULL;\n\t\t\t}\n\t\t\teventItr++;\n\t\t}\n\t\tteamItr++;\n\t}\n}\n\nvoid WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )\n{\n\tif (!theEvetnt)\n\t\treturn;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\tif (teamEvents->find(eventType) == teamEvents->end())\n\t{\n\t\ttvEventList newList;\n\t\t(*teamEvents)[eventType] = newList;\n\t}\n\n\tteamEvents->find(eventType)->second.push_back(theEvetnt);\n}\n\nvoid WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )\n{\n\tif (!theEvetnt)\n\t\treturn;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\tif (teamEvents->find(eventType) == teamEvents->end())\n\t\treturn;\n\n\ttmEventTypeList::iterator eventTypeItr = teamEvents->begin();\n\tif ( eventTypeItr != teamEvents->end() )\n\t{\n\t\ttvEventList::iterator itr = eventTypeItr->second.begin();\n\t\twhile (itr == eventTypeItr->second.end())\n\t\t{\n\t\t\tif (*itr == theEvetnt)\n\t\t\t\titr = eventTypeItr->second.erase(itr);\n\t\t\telse\n\t\t\t\titr++;\n\t\t}\n\t}\n}\n\ntvEventList WorldEventManager::getEventList ( teEventType eventType, int team )\n\n{\n\ttvEventList\teventList;\n\n\ttmEventTypeList*\tteamEvents = getTeamEventList(team);\n\n\ttmEventTypeList::iterator teamItr = teamEvents->find(eventType);\n\tif ( teamItr == teamEvents->end() )\n\t\treturn eventList;\n\n\teventList = teamItr->second;\n\treturn eventList;\n}\n\nvoid WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData\t*eventData )\n{\n\tif (!eventData)\n\t\treturn;\n\n\ttvEventList\teventList = getEventList(eventType,team);\n\n\tfor ( unsigned int i = 0; i < eventList.size(); i++)\n\t\teventList[i]->process(eventData);\n}\n\ntmEventTypeList* WorldEventManager::getTeamEventList ( int team )\n{\n\tif (eventtMap.find(team) == eventtMap.end())\n\t{\n\t\ttmEventTypeList newList;\n\t\teventtMap[team] = newList;\n\t}\n\treturn &(eventtMap.find(team)->second);\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Laura Schlimmer <laura@eventql.io>\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/commands\/table_import.h>\n#include <eventql\/util\/cli\/flagparser.h>\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/transport\/native\/frames\/insert.h\"\n#include \"eventql\/transport\/native\/frames\/error.h\"\n\nnamespace eventql {\nnamespace cli {\n\nconst String TableImport::kName_ = \"table-import\";\nconst String TableImport::kDescription_ = \"Import json or csv data to a table.\";\n\nTableImport::TableImport(\n RefPtr<ProcessConfig> process_cfg) :\n process_cfg_(process_cfg),\n status_(ReturnCode::success()),\n complete_(false) {}\n\nStatus TableImport::execute(\n const std::vector<std::string>& argv,\n FileInputStream* stdin_is,\n OutputStream* stdout_os,\n OutputStream* stderr_os) {\n ::cli::FlagParser flags;\n\n flags.defineFlag(\n \"database\",\n ::cli::FlagParser::T_STRING,\n true,\n \"d\",\n NULL,\n \"database\",\n \"<string>\");\n\n flags.defineFlag(\n \"table\",\n ::cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<string>\");\n\n flags.defineFlag(\n \"host\",\n ::cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"host name\",\n \"<string>\");\n\n flags.defineFlag(\n \"port\",\n ::cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"port\",\n \"<integer>\");\n\n flags.defineFlag(\n \"file\",\n ::cli::FlagParser::T_STRING,\n true,\n \"f\",\n NULL,\n \"file path\",\n \"<string>\");\n\n flags.defineFlag(\n \"connections\",\n ::cli::FlagParser::T_INTEGER,\n false,\n \"c\",\n \"10\",\n \"number of connections\",\n \"<num>\");\n\n try {\n flags.parseArgv(argv);\n\n } catch (const Exception& e) {\n\n stderr_os->write(StringUtil::format(\n \"$0: $1\\n\",\n e.getTypeName(),\n e.getMessage()));\n return Status(e);\n }\n\n database_ = flags.getString(\"database\");\n table_ = flags.getString(\"table\");\n host_ = flags.getString(\"host\");\n port_ = flags.getInt(\"port\");\n num_threads_ = flags.isSet(\"connections\") ?\n flags.getInt(\"connections\") :\n kDefaultNumThreads;\n threads_.resize(num_threads_);\n\n \/* auth data *\/\n if (process_cfg_->hasProperty(\"client.user\")) {\n auth_data_.emplace_back(\n \"user\",\n process_cfg_->getString(\"client.user\").get());\n }\n\n if (process_cfg_->hasProperty(\"client.password\")) {\n auth_data_.emplace_back(\n \"password\",\n process_cfg_->getString(\"client.\").get());\n }\n\n if (process_cfg_->hasProperty(\"client.auth_token\")) {\n auth_data_.emplace_back(\n \"auth_token\",\n process_cfg_->getString(\"client.auth_token\").get());\n }\n\n return run(flags.getString(\"file\"));\n}\n\nStatus TableImport::run(const std::string& file) {\n std::unique_ptr<FileInputStream> is;\n try {\n is = FileInputStream::openFile(file);\n\n } catch (const Exception& e) {\n return Status(e);\n }\n\n\n \/* start threads *\/\n for (size_t i = 0; i < num_threads_; ++i) {\n threads_[i] = std::thread(std::bind(&TableImport::runThread, this));\n }\n\n \/* read and enqueue lines in batches *\/\n std::vector<std::string> batch;\n std::string line;\n uint64_t cur_size = 0;\n while (is->readLine(&line)) {\n if (cur_size + line.size() > kDefaultBatchSize) {\n if (!enqueueBatch(std::move(batch))) {\n goto exit;\n }\n\n batch.clear();\n cur_size = 0;\n }\n\n batch.emplace_back(line);\n cur_size += line.size();\n line.clear();\n }\n\n if (batch.size() > 0) {\n if (!enqueueBatch(std::move(batch))) {\n goto exit;\n }\n }\n\n \/* send upload complete signal to trigger thread shutdown *\/\n {\n std::unique_lock<std::mutex> lk(mutex_);\n complete_ = true;\n cv_.notify_all();\n }\n\nexit:\n\n \/* join threads *\/\n for (auto& t : threads_) {\n if (t.joinable()) {\n t.join();\n }\n }\n\n return status_;\n}\n\nvoid TableImport::runThread() {\n try {\n native_transport::TCPClient client(nullptr, nullptr);\n \/* connect to server *\/\n auto rc = client.connect(\n host_,\n port_,\n false,\n auth_data_);\n if (!rc.isSuccess()) {\n setError(rc);\n return;\n }\n\n UploadBatch batch;\n while (popBatch(&batch)) {\n auto rc = uploadBatch(&client, batch);\n if (!rc.isSuccess()) {\n setError(rc);\n client.close();\n return;\n }\n\n batch.clear();\n }\n\n client.close();\n\n } catch (const std::exception& e) {\n setError(e);\n }\n}\n\nstatic const size_t kMaxQueueSize = 32;\n\nbool TableImport::enqueueBatch(UploadBatch&& batch) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n for (;;) {\n if (!status_.isSuccess() || complete_) {\n return false;\n }\n\n if (queue_.size() < kMaxQueueSize) {\n break;\n }\n\n cv_.wait(lk);\n }\n\n\n queue_.push_back(std::move(batch));\n cv_.notify_all();\n return true;\n}\n\nbool TableImport::popBatch(UploadBatch* batch) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n for (;;) {\n if (!status_.isSuccess()) {\n return false;\n }\n\n if (!queue_.empty()) {\n break;\n }\n\n if (complete_) {\n return false;\n } else {\n cv_.wait(lk);\n }\n }\n\n\n *batch = queue_.front();\n queue_.pop_front();\n cv_.notify_all();\n return true;\n}\n\nvoid TableImport::setError(const ReturnCode& err) {\n std::unique_lock<std::mutex> lk(mutex_);\n status_ = err;\n cv_.notify_all();\n}\n\nStatus TableImport::uploadBatch(\n native_transport::TCPClient* client,\n const UploadBatch& batch) {\n \/* insert *\/\n native_transport::InsertFrame i_frame;\n i_frame.setDatabase(database_);\n i_frame.setTable(table_);\n i_frame.setRecordEncoding(EVQL_INSERT_CTYPE_JSON);\n\n for (auto l : batch) {\n i_frame.addRecord(l);\n }\n\n auto rc = client->sendFrame(&i_frame, 0);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n uint16_t ret_opcode = 0;\n uint16_t ret_flags;\n std::string ret_payload;\n while (ret_opcode != EVQL_OP_ACK) {\n auto rc = client->recvFrame(\n &ret_opcode,\n &ret_flags,\n &ret_payload,\n kMicrosPerSecond); \/\/ FIXME\n\n if (!rc.isSuccess()) {\n return rc;\n }\n\n switch (ret_opcode) {\n case EVQL_OP_ACK:\n case EVQL_OP_HEARTBEAT:\n continue;\n case EVQL_OP_ERROR: {\n native_transport::ErrorFrame eframe;\n eframe.parseFrom(ret_payload.data(), ret_payload.size());\n return ReturnCode::error(\"ERUNTIME\", eframe.getError());\n }\n default:\n return ReturnCode::error(\"ERUNTIME\", \"unexpected opcode\");\n }\n }\n\n return Status::success();\n}\n\nconst String& TableImport::getName() const {\n return kName_;\n}\n\nconst String& TableImport::getDescription() const {\n return kDescription_;\n}\n\nvoid TableImport::printHelp(OutputStream* stdout_os) const {\n stdout_os->write(StringUtil::format(\n \"\\nevqlctl-$0 - $1\\n\\n\", kName_, kDescription_));\n\n stdout_os->write(\n \"Usage: evqlctl table-import [OPTIONS]\\n\"\n \" -c, --connections <num> Number of concurrent connections\\n\"\n \" -d, --database <db> Select a database.\\n\"\n \" -t, --table <tbl> Select a destination table.\\n\"\n \" -f, --file <file> Set the path of the file to import.\\n\"\n \" -h, --host <hostname> Set the EventQL hostname.\\n\"\n \" -p, --port <port> Set the EventQL port.\\n\");\n}\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n<commit_msg>fixed set error from exception<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Laura Schlimmer <laura@eventql.io>\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/commands\/table_import.h>\n#include <eventql\/util\/cli\/flagparser.h>\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/transport\/native\/frames\/insert.h\"\n#include \"eventql\/transport\/native\/frames\/error.h\"\n\nnamespace eventql {\nnamespace cli {\n\nconst String TableImport::kName_ = \"table-import\";\nconst String TableImport::kDescription_ = \"Import json or csv data to a table.\";\n\nTableImport::TableImport(\n RefPtr<ProcessConfig> process_cfg) :\n process_cfg_(process_cfg),\n status_(ReturnCode::success()),\n complete_(false) {}\n\nStatus TableImport::execute(\n const std::vector<std::string>& argv,\n FileInputStream* stdin_is,\n OutputStream* stdout_os,\n OutputStream* stderr_os) {\n ::cli::FlagParser flags;\n\n flags.defineFlag(\n \"database\",\n ::cli::FlagParser::T_STRING,\n true,\n \"d\",\n NULL,\n \"database\",\n \"<string>\");\n\n flags.defineFlag(\n \"table\",\n ::cli::FlagParser::T_STRING,\n true,\n \"t\",\n NULL,\n \"table name\",\n \"<string>\");\n\n flags.defineFlag(\n \"host\",\n ::cli::FlagParser::T_STRING,\n true,\n \"h\",\n NULL,\n \"host name\",\n \"<string>\");\n\n flags.defineFlag(\n \"port\",\n ::cli::FlagParser::T_INTEGER,\n true,\n \"p\",\n NULL,\n \"port\",\n \"<integer>\");\n\n flags.defineFlag(\n \"file\",\n ::cli::FlagParser::T_STRING,\n true,\n \"f\",\n NULL,\n \"file path\",\n \"<string>\");\n\n flags.defineFlag(\n \"connections\",\n ::cli::FlagParser::T_INTEGER,\n false,\n \"c\",\n \"10\",\n \"number of connections\",\n \"<num>\");\n\n try {\n flags.parseArgv(argv);\n\n } catch (const Exception& e) {\n\n stderr_os->write(StringUtil::format(\n \"$0: $1\\n\",\n e.getTypeName(),\n e.getMessage()));\n return Status(e);\n }\n\n database_ = flags.getString(\"database\");\n table_ = flags.getString(\"table\");\n host_ = flags.getString(\"host\");\n port_ = flags.getInt(\"port\");\n num_threads_ = flags.isSet(\"connections\") ?\n flags.getInt(\"connections\") :\n kDefaultNumThreads;\n threads_.resize(num_threads_);\n\n \/* auth data *\/\n if (process_cfg_->hasProperty(\"client.user\")) {\n auth_data_.emplace_back(\n \"user\",\n process_cfg_->getString(\"client.user\").get());\n }\n\n if (process_cfg_->hasProperty(\"client.password\")) {\n auth_data_.emplace_back(\n \"password\",\n process_cfg_->getString(\"client.\").get());\n }\n\n if (process_cfg_->hasProperty(\"client.auth_token\")) {\n auth_data_.emplace_back(\n \"auth_token\",\n process_cfg_->getString(\"client.auth_token\").get());\n }\n\n return run(flags.getString(\"file\"));\n}\n\nStatus TableImport::run(const std::string& file) {\n std::unique_ptr<FileInputStream> is;\n try {\n is = FileInputStream::openFile(file);\n\n } catch (const Exception& e) {\n return Status(e);\n }\n\n\n \/* start threads *\/\n for (size_t i = 0; i < num_threads_; ++i) {\n threads_[i] = std::thread(std::bind(&TableImport::runThread, this));\n }\n\n \/* read and enqueue lines in batches *\/\n std::vector<std::string> batch;\n std::string line;\n uint64_t cur_size = 0;\n while (is->readLine(&line)) {\n if (cur_size + line.size() > kDefaultBatchSize) {\n if (!enqueueBatch(std::move(batch))) {\n goto exit;\n }\n\n batch.clear();\n cur_size = 0;\n }\n\n batch.emplace_back(line);\n cur_size += line.size();\n line.clear();\n }\n\n if (batch.size() > 0) {\n if (!enqueueBatch(std::move(batch))) {\n goto exit;\n }\n }\n\n \/* send upload complete signal to trigger thread shutdown *\/\n {\n std::unique_lock<std::mutex> lk(mutex_);\n complete_ = true;\n cv_.notify_all();\n }\n\nexit:\n\n \/* join threads *\/\n for (auto& t : threads_) {\n if (t.joinable()) {\n t.join();\n }\n }\n\n return status_;\n}\n\nvoid TableImport::runThread() {\n try {\n native_transport::TCPClient client(nullptr, nullptr);\n \/* connect to server *\/\n auto rc = client.connect(\n host_,\n port_,\n false,\n auth_data_);\n if (!rc.isSuccess()) {\n setError(rc);\n return;\n }\n\n UploadBatch batch;\n while (popBatch(&batch)) {\n auto rc = uploadBatch(&client, batch);\n if (!rc.isSuccess()) {\n setError(rc);\n client.close();\n return;\n }\n\n batch.clear();\n }\n\n client.close();\n\n } catch (const std::exception& e) {\n setError(ReturnCode::exception(e));\n }\n}\n\nstatic const size_t kMaxQueueSize = 32;\n\nbool TableImport::enqueueBatch(UploadBatch&& batch) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n for (;;) {\n if (!status_.isSuccess() || complete_) {\n return false;\n }\n\n if (queue_.size() < kMaxQueueSize) {\n break;\n }\n\n cv_.wait(lk);\n }\n\n\n queue_.push_back(std::move(batch));\n cv_.notify_all();\n return true;\n}\n\nbool TableImport::popBatch(UploadBatch* batch) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n for (;;) {\n if (!status_.isSuccess()) {\n return false;\n }\n\n if (!queue_.empty()) {\n break;\n }\n\n if (complete_) {\n return false;\n } else {\n cv_.wait(lk);\n }\n }\n\n\n *batch = queue_.front();\n queue_.pop_front();\n cv_.notify_all();\n return true;\n}\n\nvoid TableImport::setError(const ReturnCode& err) {\n std::unique_lock<std::mutex> lk(mutex_);\n status_ = err;\n cv_.notify_all();\n}\n\nStatus TableImport::uploadBatch(\n native_transport::TCPClient* client,\n const UploadBatch& batch) {\n \/* insert *\/\n native_transport::InsertFrame i_frame;\n i_frame.setDatabase(database_);\n i_frame.setTable(table_);\n i_frame.setRecordEncoding(EVQL_INSERT_CTYPE_JSON);\n\n for (auto l : batch) {\n i_frame.addRecord(l);\n }\n\n auto rc = client->sendFrame(&i_frame, 0);\n if (!rc.isSuccess()) {\n return rc;\n }\n\n uint16_t ret_opcode = 0;\n uint16_t ret_flags;\n std::string ret_payload;\n while (ret_opcode != EVQL_OP_ACK) {\n auto rc = client->recvFrame(\n &ret_opcode,\n &ret_flags,\n &ret_payload,\n kMicrosPerSecond); \/\/ FIXME\n\n if (!rc.isSuccess()) {\n return rc;\n }\n\n switch (ret_opcode) {\n case EVQL_OP_ACK:\n case EVQL_OP_HEARTBEAT:\n continue;\n case EVQL_OP_ERROR: {\n native_transport::ErrorFrame eframe;\n eframe.parseFrom(ret_payload.data(), ret_payload.size());\n return ReturnCode::error(\"ERUNTIME\", eframe.getError());\n }\n default:\n return ReturnCode::error(\"ERUNTIME\", \"unexpected opcode\");\n }\n }\n\n return Status::success();\n}\n\nconst String& TableImport::getName() const {\n return kName_;\n}\n\nconst String& TableImport::getDescription() const {\n return kDescription_;\n}\n\nvoid TableImport::printHelp(OutputStream* stdout_os) const {\n stdout_os->write(StringUtil::format(\n \"\\nevqlctl-$0 - $1\\n\\n\", kName_, kDescription_));\n\n stdout_os->write(\n \"Usage: evqlctl table-import [OPTIONS]\\n\"\n \" -c, --connections <num> Number of concurrent connections\\n\"\n \" -d, --database <db> Select a database.\\n\"\n \" -t, --table <tbl> Select a destination table.\\n\"\n \" -f, --file <file> Set the path of the file to import.\\n\"\n \" -h, --host <hostname> Set the EventQL hostname.\\n\"\n \" -p, --port <port> Set the EventQL port.\\n\");\n}\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: StartMarker.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-20 19:12:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n\n#ifndef RPTUI_STARTMARKER_HXX\n#include \"StartMarker.hxx\"\n#endif\n#ifndef _SV_IMAGE_HXX\n#include <vcl\/image.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _RPTUI_DLGRESID_HRC\n#include \"RptResId.hrc\"\n#endif\n#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_\n#include \"ModuleHelper.hxx\"\n#endif\n#ifndef RPTUI_COLORCHANGER_HXX\n#include \"ColorChanger.hxx\"\n#endif\n#ifndef RPTUI_REPORT_DEFINES_HXX\n#include \"ReportDefines.hxx\"\n#endif\n#ifndef RPTUI_SECTIONSWINDOW_HXX\n#include \"SectionsWindow.hxx\"\n#endif\n#ifndef RTPUI_REPORTDESIGN_HELPID_HRC\n#include \"helpids.hrc\"\n#endif\n#ifndef _SV_HELP_HXX\n#include <vcl\/help.hxx>\n#endif\n#include <vcl\/gradient.hxx>\n#include <vcl\/lineinfo.hxx>\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <svtools\/syslocale.hxx>\n#ifndef _SFXSMPLHINT_HXX\n#include <svtools\/smplhint.hxx>\n#endif\n\n#define CORNER_SPACE 5\n#define TEXT_WIDTH 10\n#define STRT_BORDER 6\n\n\/\/=====================================================================\nnamespace rptui\n{\n\/\/=====================================================================\n\nImage* OStartMarker::s_pDefCollapsed = NULL;\nImage* OStartMarker::s_pDefExpanded = NULL;\nImage* OStartMarker::s_pDefCollapsedHC = NULL;\nImage* OStartMarker::s_pDefExpandedHC = NULL;\noslInterlockedCount OStartMarker::s_nImageRefCount = 0;\n\nDBG_NAME( rpt_OStartMarker )\n\/\/ -----------------------------------------------------------------------------\nOStartMarker::OStartMarker(OSectionsWindow* _pParent,const ::rtl::OUString& _sColorEntry)\n: OColorListener(_pParent,_sColorEntry)\n,m_aVRuler(this,WB_VERT)\n,m_aText(this,WB_WORDBREAK)\n,m_aImage(this,WB_LEFT|WB_TOP)\n,m_pParent(_pParent)\n,m_nCornerSize(CORNER_SPACE)\n,m_bShowRuler(sal_True)\n{\n DBG_CTOR( rpt_OStartMarker,NULL);\n SetUniqueId(HID_STARTMARKER);\n osl_incrementInterlockedCount(&s_nImageRefCount);\n initDefaultNodeImages();\n ImplInitSettings();\n m_aText.SetHelpId(HID_START_TITLE);\n m_aImage.SetHelpId(HID_START_IMAGE);\n m_aText.Show();\n m_aImage.Show();\n m_aVRuler.Show();\n m_aVRuler.Activate();\n m_aVRuler.SetPagePos(0);\n m_aVRuler.SetBorders();\n m_aVRuler.SetIndents();\n m_aVRuler.SetMargin1();\n m_aVRuler.SetMargin2();\n const MeasurementSystem eSystem = SvtSysLocale().GetLocaleData().getMeasurementSystemEnum();\n m_aVRuler.SetUnit(MEASURE_METRIC == eSystem ? FUNIT_CM : FUNIT_INCH);\n\n}\n\/\/ -----------------------------------------------------------------------------\nOStartMarker::~OStartMarker()\n{\n DBG_DTOR( rpt_OStartMarker,NULL);\n if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )\n {\n DELETEZ(s_pDefCollapsed);\n DELETEZ(s_pDefExpanded);\n DELETEZ(s_pDefCollapsedHC);\n DELETEZ(s_pDefExpandedHC);\n } \/\/ if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 OStartMarker::getWidth() const\n{\n return (GetDisplayBackground().GetColor().IsDark() ? s_pDefExpandedHC : s_pDefCollapsed)->GetSizePixel().Width() + GetTextWidth(m_aText.GetText(),0,::std::min<USHORT>(TEXT_WIDTH,m_aText.GetText().Len())) + 2*REPORT_EXTRA_SPACE;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 OStartMarker::getMinHeight() const\n{\n return m_aText.GetTextHeight() + 2*STRT_BORDER + 2;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::Paint( const Rectangle& rRect )\n{\n Window::Paint( rRect );\n \/\/SetUpdateMode(FALSE);\n Size aSize = GetSizePixel();\n long nSize = aSize.Width();\n if ( !isCollapsed() )\n nSize = aSize.Width() - m_aVRuler.GetSizePixel().Width() - m_nCornerSize;\n SetClipRegion(Region(Rectangle(Point(),Size( nSize,aSize.Height()))));\n aSize.Width() += m_nCornerSize;\n\n Point aGcc3WorkaroundTemporary;\n Rectangle aWholeRect(aGcc3WorkaroundTemporary,aSize);\n {\n const ColorChanger aColors( this, m_nTextBoundaries, m_nColor );\n\n \/\/aGradient.SetBorder(static_cast<USHORT>(m_nCornerSize));\n PolyPolygon aPoly;\n aPoly.Insert(Polygon(aWholeRect,m_nCornerSize,m_nCornerSize));\n\n Color aStartColor(m_nColor);\n aStartColor.IncreaseLuminance(10);\n USHORT nHue = 0;\n USHORT nSat = 0;\n USHORT nBri = 0;\n aStartColor.RGBtoHSB(nHue, nSat, nBri);\n nSat += 40;\n Color aEndColor(Color::HSBtoRGB(nHue, nSat, nBri));\n Gradient aGradient(GRADIENT_LINEAR,aStartColor,aEndColor);\n aGradient.SetSteps(static_cast<USHORT>(aSize.Height()));\n\n DrawGradient(aPoly ,aGradient);\n }\n if ( m_bMarked )\n {\n#define DIFF_DIST 2\n Rectangle aRect( Point(m_nCornerSize,m_nCornerSize),\n Size(aSize.Width() - m_nCornerSize- m_nCornerSize,aSize.Height() - m_nCornerSize- m_nCornerSize));\n ColorChanger aColors( this, COL_WHITE, COL_WHITE );\n DrawPolyLine(Polygon(aRect),LineInfo(LINE_SOLID,2));\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setColor()\n{\n const Color aColor(m_nColor);\n Color aTextColor = GetTextColor();\n if ( aColor.GetLuminance() < 128 )\n aTextColor = COL_WHITE;\n m_aText.SetTextColor(aTextColor);\n m_aText.SetLineColor(m_nColor);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::MouseButtonUp( const MouseEvent& rMEvt )\n{\n if ( !rMEvt.IsLeft() )\n return;\n\n Point aPos( rMEvt.GetPosPixel());\n\n const Size aOutputSize = GetOutputSizePixel();\n if( aPos.X() > aOutputSize.Width() || aPos.Y() > aOutputSize.Height() )\n return;\n Rectangle aRect(m_aImage.GetPosPixel(),m_aImage.GetImage().GetSizePixel());\n if ( rMEvt.GetClicks() == 2 || aRect.IsInside( aPos ) )\n {\n m_bCollapsed = !m_bCollapsed;\n\n Image* pImage = NULL;\n if ( GetDisplayBackground().GetColor().IsDark() )\n pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;\n else\n pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;\n m_aImage.SetImage(*pImage);\n\n m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);\n m_nCornerSize = CORNER_SPACE;\n if ( m_aCollapsedLink.IsSet() )\n m_aCollapsedLink.Call(this);\n }\n\n m_pParent->showProperties(this);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::initDefaultNodeImages()\n{\n if ( !s_pDefCollapsed )\n {\n s_pDefCollapsed = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED) );\n s_pDefCollapsedHC = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED_HC ) );\n s_pDefExpanded = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED ) );\n s_pDefExpandedHC = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED_HC ) );\n }\n\n Image* pImage = NULL;\n if ( GetDisplayBackground().GetColor().IsDark() )\n {\n pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;\n }\n else\n {\n pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;\n }\n m_aImage.SetImage(*pImage);\n m_aImage.SetMouseTransparent(TRUE);\n m_aImage.SetBackground();\n m_aText.SetBackground();\n m_aText.SetMouseTransparent(TRUE);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::ImplInitSettings()\n{\n SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );\n SetFillColor( Application::GetSettings().GetStyleSettings().GetDialogColor() );\n \/\/SetTextFillColor( Application::GetSettings().GetStyleSettings().GetDarkShadowColor() );\n setColor();\n}\n\/\/------------------------------------------------------------------------------\nvoid OStartMarker::Resize()\n{\n const Size aOutputSize( GetOutputSize() );\n const long nOutputWidth = aOutputSize.Width();\n const long nOutputHeight = aOutputSize.Height();\n\n const Size aImageSize = m_aImage.GetImage().GetSizePixel();\n sal_Int32 nY = ::std::min<sal_Int32>(static_cast<sal_Int32>(REPORT_EXTRA_SPACE),static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5));\n if ( m_bCollapsed )\n nY = static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5);\n Point aPos(REPORT_EXTRA_SPACE,nY);\n\n m_aImage.SetPosSizePixel(aPos,Size(aImageSize.Width() + REPORT_EXTRA_SPACE,nOutputHeight - 2*nY));\n aPos.X() += aImageSize.Width() + REPORT_EXTRA_SPACE;\n aPos.Y() -= 2;\n\n const long nVRulerWidth = m_aVRuler.GetSizePixel().Width();\n const Point aRulerPos(nOutputWidth - nVRulerWidth - 5,0);\n\n m_aText.SetPosSizePixel(aPos,Size(aRulerPos.X() - aPos.X(),nOutputHeight - 2*aPos.Y()));\n\n\n m_aVRuler.SetPosSizePixel(aRulerPos,Size(nVRulerWidth,nOutputHeight));\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setTitle(const String& _sTitle)\n{\n m_aText.SetText(_sTitle);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::Notify(SfxBroadcaster & rBc, SfxHint const & rHint)\n{\n OColorListener::Notify(rBc, rHint);\n if (rHint.ISA(SfxSimpleHint)\n && (static_cast< SfxSimpleHint const & >(rHint).GetId()\n == SFX_HINT_COLORS_CHANGED))\n {\n setColor();\n \/\/m_aText.Invalidate();\n Invalidate(INVALIDATE_CHILDREN);\n }\n}\n\/\/----------------------------------------------------------------------------\nvoid OStartMarker::showRuler(sal_Bool _bShow)\n{\n m_bShowRuler = _bShow;\n m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);\n}\n\/\/------------------------------------------------------------------------------\nsal_Int32 OStartMarker::getRulerOffset() const\n{\n return m_aVRuler.GetSizePixel().Width();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OStartMarker::RequestHelp( const HelpEvent& rHEvt )\n{\n if( m_aText.GetText().Len())\n {\n \/\/ Hilfe anzeigen\n Rectangle aItemRect(rHEvt.GetMousePosPixel(),Size(GetSizePixel().Width(),getMinHeight()));\n \/\/aItemRect = LogicToPixel( aItemRect );\n Point aPt = OutputToScreenPixel( aItemRect.TopLeft() );\n aItemRect.Left() = aPt.X();\n aItemRect.Top() = aPt.Y();\n aPt = OutputToScreenPixel( aItemRect.BottomRight() );\n aItemRect.Right() = aPt.X();\n aItemRect.Bottom() = aPt.Y();\n if( rHEvt.GetMode() == HELPMODE_BALLOON )\n Help::ShowBalloon( this, aItemRect.Center(), aItemRect, m_aText.GetText());\n else\n Help::ShowQuickHelp( this, aItemRect, m_aText.GetText() );\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setCollapsed(sal_Bool _bCollapsed)\n{\n OColorListener::setCollapsed(_bCollapsed);\n showRuler(_bCollapsed);\n}\n\/\/ -----------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------\n\/\/ =======================================================================\n}\n\/\/ =======================================================================\n<commit_msg>INTEGRATION: CWS reportdesign02 (1.4.18); FILE MERGED 2008\/01\/15 11:50:21 oj 1.4.18.1: change helpid names<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: StartMarker.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2008-01-29 13:52:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n\n#ifndef RPTUI_STARTMARKER_HXX\n#include \"StartMarker.hxx\"\n#endif\n#ifndef _SV_IMAGE_HXX\n#include <vcl\/image.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _RPTUI_DLGRESID_HRC\n#include \"RptResId.hrc\"\n#endif\n#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_\n#include \"ModuleHelper.hxx\"\n#endif\n#ifndef RPTUI_COLORCHANGER_HXX\n#include \"ColorChanger.hxx\"\n#endif\n#ifndef RPTUI_REPORT_DEFINES_HXX\n#include \"ReportDefines.hxx\"\n#endif\n#ifndef RPTUI_SECTIONSWINDOW_HXX\n#include \"SectionsWindow.hxx\"\n#endif\n#ifndef RTPUI_REPORTDESIGN_HELPID_HRC\n#include \"helpids.hrc\"\n#endif\n#ifndef _SV_HELP_HXX\n#include <vcl\/help.hxx>\n#endif\n#include <vcl\/gradient.hxx>\n#include <vcl\/lineinfo.hxx>\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <svtools\/syslocale.hxx>\n#ifndef _SFXSMPLHINT_HXX\n#include <svtools\/smplhint.hxx>\n#endif\n\n#define CORNER_SPACE 5\n#define TEXT_WIDTH 10\n#define STRT_BORDER 6\n\n\/\/=====================================================================\nnamespace rptui\n{\n\/\/=====================================================================\n\nImage* OStartMarker::s_pDefCollapsed = NULL;\nImage* OStartMarker::s_pDefExpanded = NULL;\nImage* OStartMarker::s_pDefCollapsedHC = NULL;\nImage* OStartMarker::s_pDefExpandedHC = NULL;\noslInterlockedCount OStartMarker::s_nImageRefCount = 0;\n\nDBG_NAME( rpt_OStartMarker )\n\/\/ -----------------------------------------------------------------------------\nOStartMarker::OStartMarker(OSectionsWindow* _pParent,const ::rtl::OUString& _sColorEntry)\n: OColorListener(_pParent,_sColorEntry)\n,m_aVRuler(this,WB_VERT)\n,m_aText(this,WB_WORDBREAK)\n,m_aImage(this,WB_LEFT|WB_TOP)\n,m_pParent(_pParent)\n,m_nCornerSize(CORNER_SPACE)\n,m_bShowRuler(sal_True)\n{\n DBG_CTOR( rpt_OStartMarker,NULL);\n SetUniqueId(HID_RPT_STARTMARKER);\n osl_incrementInterlockedCount(&s_nImageRefCount);\n initDefaultNodeImages();\n ImplInitSettings();\n m_aText.SetHelpId(HID_RPT_START_TITLE);\n m_aImage.SetHelpId(HID_RPT_START_IMAGE);\n m_aText.Show();\n m_aImage.Show();\n m_aVRuler.Show();\n m_aVRuler.Activate();\n m_aVRuler.SetPagePos(0);\n m_aVRuler.SetBorders();\n m_aVRuler.SetIndents();\n m_aVRuler.SetMargin1();\n m_aVRuler.SetMargin2();\n const MeasurementSystem eSystem = SvtSysLocale().GetLocaleData().getMeasurementSystemEnum();\n m_aVRuler.SetUnit(MEASURE_METRIC == eSystem ? FUNIT_CM : FUNIT_INCH);\n\n}\n\/\/ -----------------------------------------------------------------------------\nOStartMarker::~OStartMarker()\n{\n DBG_DTOR( rpt_OStartMarker,NULL);\n if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )\n {\n DELETEZ(s_pDefCollapsed);\n DELETEZ(s_pDefExpanded);\n DELETEZ(s_pDefCollapsedHC);\n DELETEZ(s_pDefExpandedHC);\n } \/\/ if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 OStartMarker::getWidth() const\n{\n return (GetDisplayBackground().GetColor().IsDark() ? s_pDefExpandedHC : s_pDefCollapsed)->GetSizePixel().Width() + GetTextWidth(m_aText.GetText(),0,::std::min<USHORT>(TEXT_WIDTH,m_aText.GetText().Len())) + 2*REPORT_EXTRA_SPACE;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 OStartMarker::getMinHeight() const\n{\n return m_aText.GetTextHeight() + 2*STRT_BORDER + 2;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::Paint( const Rectangle& rRect )\n{\n Window::Paint( rRect );\n \/\/SetUpdateMode(FALSE);\n Size aSize = GetSizePixel();\n long nSize = aSize.Width();\n if ( !isCollapsed() )\n nSize = aSize.Width() - m_aVRuler.GetSizePixel().Width() - m_nCornerSize;\n SetClipRegion(Region(Rectangle(Point(),Size( nSize,aSize.Height()))));\n aSize.Width() += m_nCornerSize;\n\n Point aGcc3WorkaroundTemporary;\n Rectangle aWholeRect(aGcc3WorkaroundTemporary,aSize);\n {\n const ColorChanger aColors( this, m_nTextBoundaries, m_nColor );\n\n \/\/aGradient.SetBorder(static_cast<USHORT>(m_nCornerSize));\n PolyPolygon aPoly;\n aPoly.Insert(Polygon(aWholeRect,m_nCornerSize,m_nCornerSize));\n\n Color aStartColor(m_nColor);\n aStartColor.IncreaseLuminance(10);\n USHORT nHue = 0;\n USHORT nSat = 0;\n USHORT nBri = 0;\n aStartColor.RGBtoHSB(nHue, nSat, nBri);\n nSat += 40;\n Color aEndColor(Color::HSBtoRGB(nHue, nSat, nBri));\n Gradient aGradient(GRADIENT_LINEAR,aStartColor,aEndColor);\n aGradient.SetSteps(static_cast<USHORT>(aSize.Height()));\n\n DrawGradient(aPoly ,aGradient);\n }\n if ( m_bMarked )\n {\n#define DIFF_DIST 2\n Rectangle aRect( Point(m_nCornerSize,m_nCornerSize),\n Size(aSize.Width() - m_nCornerSize- m_nCornerSize,aSize.Height() - m_nCornerSize- m_nCornerSize));\n ColorChanger aColors( this, COL_WHITE, COL_WHITE );\n DrawPolyLine(Polygon(aRect),LineInfo(LINE_SOLID,2));\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setColor()\n{\n const Color aColor(m_nColor);\n Color aTextColor = GetTextColor();\n if ( aColor.GetLuminance() < 128 )\n aTextColor = COL_WHITE;\n m_aText.SetTextColor(aTextColor);\n m_aText.SetLineColor(m_nColor);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::MouseButtonUp( const MouseEvent& rMEvt )\n{\n if ( !rMEvt.IsLeft() )\n return;\n\n Point aPos( rMEvt.GetPosPixel());\n\n const Size aOutputSize = GetOutputSizePixel();\n if( aPos.X() > aOutputSize.Width() || aPos.Y() > aOutputSize.Height() )\n return;\n Rectangle aRect(m_aImage.GetPosPixel(),m_aImage.GetImage().GetSizePixel());\n if ( rMEvt.GetClicks() == 2 || aRect.IsInside( aPos ) )\n {\n m_bCollapsed = !m_bCollapsed;\n\n Image* pImage = NULL;\n if ( GetDisplayBackground().GetColor().IsDark() )\n pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;\n else\n pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;\n m_aImage.SetImage(*pImage);\n\n m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);\n m_nCornerSize = CORNER_SPACE;\n if ( m_aCollapsedLink.IsSet() )\n m_aCollapsedLink.Call(this);\n }\n\n m_pParent->showProperties(this);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::initDefaultNodeImages()\n{\n if ( !s_pDefCollapsed )\n {\n s_pDefCollapsed = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED) );\n s_pDefCollapsedHC = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED_HC ) );\n s_pDefExpanded = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED ) );\n s_pDefExpandedHC = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED_HC ) );\n }\n\n Image* pImage = NULL;\n if ( GetDisplayBackground().GetColor().IsDark() )\n {\n pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;\n }\n else\n {\n pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;\n }\n m_aImage.SetImage(*pImage);\n m_aImage.SetMouseTransparent(TRUE);\n m_aImage.SetBackground();\n m_aText.SetBackground();\n m_aText.SetMouseTransparent(TRUE);\n}\n\/\/ -----------------------------------------------------------------------\nvoid OStartMarker::ImplInitSettings()\n{\n SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );\n SetFillColor( Application::GetSettings().GetStyleSettings().GetDialogColor() );\n \/\/SetTextFillColor( Application::GetSettings().GetStyleSettings().GetDarkShadowColor() );\n setColor();\n}\n\/\/------------------------------------------------------------------------------\nvoid OStartMarker::Resize()\n{\n const Size aOutputSize( GetOutputSize() );\n const long nOutputWidth = aOutputSize.Width();\n const long nOutputHeight = aOutputSize.Height();\n\n const Size aImageSize = m_aImage.GetImage().GetSizePixel();\n sal_Int32 nY = ::std::min<sal_Int32>(static_cast<sal_Int32>(REPORT_EXTRA_SPACE),static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5));\n if ( m_bCollapsed )\n nY = static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5);\n Point aPos(REPORT_EXTRA_SPACE,nY);\n\n m_aImage.SetPosSizePixel(aPos,Size(aImageSize.Width() + REPORT_EXTRA_SPACE,nOutputHeight - 2*nY));\n aPos.X() += aImageSize.Width() + REPORT_EXTRA_SPACE;\n aPos.Y() -= 2;\n\n const long nVRulerWidth = m_aVRuler.GetSizePixel().Width();\n const Point aRulerPos(nOutputWidth - nVRulerWidth - 5,0);\n\n m_aText.SetPosSizePixel(aPos,Size(aRulerPos.X() - aPos.X(),nOutputHeight - 2*aPos.Y()));\n\n\n m_aVRuler.SetPosSizePixel(aRulerPos,Size(nVRulerWidth,nOutputHeight));\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setTitle(const String& _sTitle)\n{\n m_aText.SetText(_sTitle);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::Notify(SfxBroadcaster & rBc, SfxHint const & rHint)\n{\n OColorListener::Notify(rBc, rHint);\n if (rHint.ISA(SfxSimpleHint)\n && (static_cast< SfxSimpleHint const & >(rHint).GetId()\n == SFX_HINT_COLORS_CHANGED))\n {\n setColor();\n \/\/m_aText.Invalidate();\n Invalidate(INVALIDATE_CHILDREN);\n }\n}\n\/\/----------------------------------------------------------------------------\nvoid OStartMarker::showRuler(sal_Bool _bShow)\n{\n m_bShowRuler = _bShow;\n m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);\n}\n\/\/------------------------------------------------------------------------------\nsal_Int32 OStartMarker::getRulerOffset() const\n{\n return m_aVRuler.GetSizePixel().Width();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OStartMarker::RequestHelp( const HelpEvent& rHEvt )\n{\n if( m_aText.GetText().Len())\n {\n \/\/ Hilfe anzeigen\n Rectangle aItemRect(rHEvt.GetMousePosPixel(),Size(GetSizePixel().Width(),getMinHeight()));\n \/\/aItemRect = LogicToPixel( aItemRect );\n Point aPt = OutputToScreenPixel( aItemRect.TopLeft() );\n aItemRect.Left() = aPt.X();\n aItemRect.Top() = aPt.Y();\n aPt = OutputToScreenPixel( aItemRect.BottomRight() );\n aItemRect.Right() = aPt.X();\n aItemRect.Bottom() = aPt.Y();\n if( rHEvt.GetMode() == HELPMODE_BALLOON )\n Help::ShowBalloon( this, aItemRect.Center(), aItemRect, m_aText.GetText());\n else\n Help::ShowQuickHelp( this, aItemRect, m_aText.GetText() );\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OStartMarker::setCollapsed(sal_Bool _bCollapsed)\n{\n OColorListener::setCollapsed(_bCollapsed);\n showRuler(_bCollapsed);\n}\n\/\/ -----------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------\n\/\/ =======================================================================\n}\n\/\/ =======================================================================\n<|endoftext|>"} {"text":"<commit_before>#include \"src\/block_sync.h\"\n\n#include <vector>\n\n#include \"src\/util.h\"\n\nnamespace redsea {\n\nnamespace {\n\nconst unsigned kBitmask16 = 0x000FFFF;\nconst unsigned kBitmask26 = 0x3FFFFFF;\nconst unsigned kBitmask28 = 0xFFFFFFF;\n\n\/\/ \"...the error-correction system should be enabled, but should be restricted\n\/\/ by attempting to correct bursts of errors spanning one or two bits.\"\n\/\/ Kopitz & Marks 1999: \"RDS: The Radio Data System\", p. 224\nconst unsigned kMaxErrorLength = 2;\n\nconst std::vector<uint16_t> offset_words =\n {0x0FC, 0x198, 0x168, 0x350, 0x1B4};\nconst std::map<uint16_t,eOffset> offset_syndromes =\n {{0x3D8,OFFSET_A}, {0x3D4,OFFSET_B}, {0x25C,OFFSET_C},\n {0x3CC,OFFSET_CI}, {0x258,OFFSET_D}};\nconst std::vector<uint16_t> block_number_for_offset =\n {0, 1, 2, 2, 3};\n\n\/\/ Section B.1.1: '-- calculated by the modulo-two addition of all the rows of\n\/\/ the -- matrix for which the corresponding coefficient in the -- vector is 1.'\nuint32_t matrixMultiply(uint32_t vec, const std::vector<uint32_t>& matrix) {\n\n uint32_t result = 0;\n\n for (size_t k=0; k < matrix.size(); k++)\n if ((vec >> k) & 0x01)\n result ^= matrix[matrix.size() - 1 - k];\n\n return result;\n}\n\n\/\/ Section B.2.1: 'The calculation of the syndromes -- can easily be done by\n\/\/ multiplying each word with the parity matrix H.'\nuint32_t calcSyndrome(uint32_t vec) {\n\n static const std::vector<uint32_t> parity_check_matrix({\n 0x200, 0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004,\n 0x002, 0x001, 0x2dc, 0x16e, 0x0b7, 0x287, 0x39f, 0x313,\n 0x355, 0x376, 0x1bb, 0x201, 0x3dc,\n 0x1ee, 0x0f7, 0x2a7, 0x38f, 0x31b\n });\n\n return matrixMultiply(vec, parity_check_matrix);\n}\n\neOffset nextOffsetFor(eOffset o) {\n static const std::map<eOffset,eOffset> next_offset({\n {OFFSET_A, OFFSET_B}, {OFFSET_B, OFFSET_C},\n {OFFSET_C, OFFSET_D}, {OFFSET_CI, OFFSET_D},\n {OFFSET_D, OFFSET_A}\n });\n return next_offset.at(o);\n}\n\n\/\/ Precompute mapping of syndromes to error vectors\nstd::map<uint16_t,uint32_t> makeErrorLookupTable() {\n\n std::map<uint16_t,uint32_t> result;\n\n for (uint32_t e=1; e < (1 << kMaxErrorLength); e++) {\n for (unsigned shift=0; shift < 26; shift++) {\n uint32_t errvec = ((e << shift) & kBitmask26);\n\n uint32_t sy = calcSyndrome(errvec);\n result[sy] = errvec;\n }\n }\n return result;\n}\n\n} \/\/ namespace\n\nBlockStream::BlockStream(eInputType input_type, bool has_echo) : bitcount_(0),\n prevbitcount_(0), left_to_read_(0), wideblock_(0), prevsync_(0),\n block_counter_(0), expected_offset_(OFFSET_A),\n received_offset_(OFFSET_INVALID), pi_(0), is_in_sync_(false),\n block_has_errors_(50),\n#ifdef HAVE_LIQUID\n subcarrier_(has_echo),\n#endif\n ascii_bits_(has_echo),\n error_lookup_(makeErrorLookupTable()),\n input_type_(input_type), is_eof_(false) {\n\n}\n\nint BlockStream::getNextBit() {\n int result = 0;\n#ifdef HAVE_LIQUID\n if (input_type_ == INPUT_MPX) {\n result = subcarrier_.getNextBit();\n is_eof_ = subcarrier_.isEOF();\n }\n#endif\n if (input_type_ == INPUT_ASCIIBITS) {\n result = ascii_bits_.getNextBit();\n is_eof_ = ascii_bits_.isEOF();\n }\n\n return result;\n}\n\n\/\/ Section B.2.2\nuint32_t BlockStream::correctBurstErrors(uint32_t block) const {\n\n uint16_t synd_reg =\n calcSyndrome(block ^ offset_words[expected_offset_]);\n\n uint32_t corrected_block = block;\n\n if (error_lookup_.find(synd_reg) != error_lookup_.end()) {\n corrected_block = (block ^ offset_words[expected_offset_])\n ^ (error_lookup_.at(synd_reg));\n }\n\n return corrected_block;\n\n}\n\n\/\/ A block can't be decoded\nvoid BlockStream::uncorrectable() {\n\n block_has_errors_[block_counter_ % block_has_errors_.size()] = true;\n\n unsigned num_erroneous_blocks = 0;\n for (bool e : block_has_errors_) {\n if (e)\n num_erroneous_blocks++;\n }\n\n \/\/ Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)\n if (is_in_sync_ && num_erroneous_blocks > 45) {\n is_in_sync_ = false;\n for (size_t i=0; i < block_has_errors_.size(); i++)\n block_has_errors_[i] = false;\n pi_ = 0x0000;\n }\n\n}\n\nbool BlockStream::acquireSync() {\n\n if (is_in_sync_)\n return true;\n\n \/\/ Try to find the repeating offset sequence\n if (received_offset_ != OFFSET_INVALID) {\n int dist = bitcount_ - prevbitcount_;\n\n if (dist % 26 == 0 && dist <= 156 &&\n (block_number_for_offset[prevsync_] + dist\/26) % 4 ==\n block_number_for_offset[received_offset_]) {\n is_in_sync_ = true;\n expected_offset_ = received_offset_;\n } else {\n prevbitcount_ = bitcount_;\n prevsync_ = received_offset_;\n }\n }\n\n return is_in_sync_;\n\n}\n\nGroup BlockStream::getNextGroup() {\n\n Group group;\n\n while (!isEOF()) {\n\n \/\/ Compensate for clock slip corrections\n bitcount_ += 26 - left_to_read_;\n\n \/\/ Read from radio\n for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) {\n wideblock_ = (wideblock_ << 1) + getNextBit();\n }\n\n left_to_read_ = 26;\n wideblock_ &= kBitmask28;\n\n uint32_t block = (wideblock_ >> 1) & kBitmask26;\n\n uint16_t syndrome = calcSyndrome(block);\n received_offset_ = (offset_syndromes.count(syndrome) > 0 ?\n offset_syndromes.at(syndrome) : OFFSET_INVALID);\n\n if (!acquireSync())\n continue;\n\n block_counter_++;\n uint16_t message = block >> 10;\n bool was_valid_word = true;\n\n if (expected_offset_ == OFFSET_C && received_offset_ == OFFSET_CI)\n expected_offset_ = OFFSET_CI;\n\n block_has_errors_[block_counter_ % block_has_errors_.size()] = false;\n\n if (received_offset_ != expected_offset_) {\n\n block_has_errors_[block_counter_ % block_has_errors_.size()] = true;\n\n was_valid_word = false;\n\n \/\/ Detect & correct clock slips (Section C.1.2)\n if (expected_offset_ == OFFSET_A && pi_ != 0 &&\n ((wideblock_ >> 12) & kBitmask16) == pi_) {\n message = pi_;\n wideblock_ >>= 1;\n received_offset_ = OFFSET_A;\n } else if (expected_offset_ == OFFSET_A && pi_ != 0 &&\n ((wideblock_ >> 10) & kBitmask16) == pi_) {\n message = pi_;\n wideblock_ = (wideblock_ << 1) + getNextBit();\n received_offset_ = OFFSET_A;\n left_to_read_ = 25;\n\n } else {\n\n block = correctBurstErrors(block);\n if (calcSyndrome(block) == 0x000) {\n message = block >> 10;\n received_offset_ = expected_offset_;\n }\n\n }\n\n \/\/ Still no valid syndrome\n if (received_offset_ != expected_offset_)\n uncorrectable();\n }\n\n \/\/ Error-free block received\n\n if (received_offset_ == expected_offset_) {\n\n group.block[expected_offset_] = message;\n group.hasOffset[expected_offset_] = true;\n\n if (expected_offset_ == OFFSET_A || expected_offset_ == OFFSET_CI) {\n group.pi = message;\n group.hasPi = true;\n if (was_valid_word)\n pi_ = message;\n }\n\n }\n\n expected_offset_ = nextOffsetFor(expected_offset_);\n\n if (expected_offset_ == OFFSET_A) {\n break;\n }\n\n }\n\n if (group.hasOffset[OFFSET_B]) {\n group.type = GroupType(bits(group.block[OFFSET_B], 11, 5));\n group.hasType = true;\n } else if (group.hasOffset[OFFSET_CI] && group.hasOffset[OFFSET_D]) {\n GroupType potential(bits(group.block[OFFSET_D], 11, 5));\n if (potential.num == 15 && potential.ab == VERSION_B) {\n group.type = potential;\n group.hasType = true;\n }\n }\n\n return group;\n\n}\n\nbool BlockStream::isEOF() const {\n return is_eof_;\n}\n\n#ifdef DEBUG\nfloat BlockStream::getT() const {\n return subcarrier_.getT();\n}\n#endif\n\n} \/\/ namespace redsea\n<commit_msg>whitespace<commit_after>#include \"src\/block_sync.h\"\n\n#include <vector>\n\n#include \"src\/util.h\"\n\nnamespace redsea {\n\nnamespace {\n\nconst unsigned kBitmask16 = 0x000FFFF;\nconst unsigned kBitmask26 = 0x3FFFFFF;\nconst unsigned kBitmask28 = 0xFFFFFFF;\n\n\/\/ \"...the error-correction system should be enabled, but should be restricted\n\/\/ by attempting to correct bursts of errors spanning one or two bits.\"\n\/\/ Kopitz & Marks 1999: \"RDS: The Radio Data System\", p. 224\nconst unsigned kMaxErrorLength = 2;\n\nconst std::vector<uint16_t> offset_words =\n {0x0FC, 0x198, 0x168, 0x350, 0x1B4};\nconst std::map<uint16_t,eOffset> offset_syndromes =\n {{0x3D8,OFFSET_A}, {0x3D4,OFFSET_B}, {0x25C,OFFSET_C},\n {0x3CC,OFFSET_CI}, {0x258,OFFSET_D}};\nconst std::vector<uint16_t> block_number_for_offset =\n {0, 1, 2, 2, 3};\n\n\/\/ Section B.1.1: '-- calculated by the modulo-two addition of all the rows of\n\/\/ the -- matrix for which the corresponding coefficient in the -- vector is 1.'\nuint32_t matrixMultiply(uint32_t vec, const std::vector<uint32_t>& matrix) {\n uint32_t result = 0;\n\n for (size_t k=0; k < matrix.size(); k++)\n if ((vec >> k) & 0x01)\n result ^= matrix[matrix.size() - 1 - k];\n\n return result;\n}\n\n\/\/ Section B.2.1: 'The calculation of the syndromes -- can easily be done by\n\/\/ multiplying each word with the parity matrix H.'\nuint32_t calcSyndrome(uint32_t vec) {\n static const std::vector<uint32_t> parity_check_matrix({\n 0x200, 0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004,\n 0x002, 0x001, 0x2dc, 0x16e, 0x0b7, 0x287, 0x39f, 0x313,\n 0x355, 0x376, 0x1bb, 0x201, 0x3dc,\n 0x1ee, 0x0f7, 0x2a7, 0x38f, 0x31b\n });\n\n return matrixMultiply(vec, parity_check_matrix);\n}\n\neOffset nextOffsetFor(eOffset o) {\n static const std::map<eOffset,eOffset> next_offset({\n {OFFSET_A, OFFSET_B}, {OFFSET_B, OFFSET_C},\n {OFFSET_C, OFFSET_D}, {OFFSET_CI, OFFSET_D},\n {OFFSET_D, OFFSET_A}\n });\n return next_offset.at(o);\n}\n\n\/\/ Precompute mapping of syndromes to error vectors\nstd::map<uint16_t,uint32_t> makeErrorLookupTable() {\n std::map<uint16_t,uint32_t> result;\n\n for (uint32_t e=1; e < (1 << kMaxErrorLength); e++) {\n for (unsigned shift=0; shift < 26; shift++) {\n uint32_t errvec = ((e << shift) & kBitmask26);\n\n uint32_t sy = calcSyndrome(errvec);\n result[sy] = errvec;\n }\n }\n return result;\n}\n\n} \/\/ namespace\n\nBlockStream::BlockStream(eInputType input_type, bool has_echo) : bitcount_(0),\n prevbitcount_(0), left_to_read_(0), wideblock_(0), prevsync_(0),\n block_counter_(0), expected_offset_(OFFSET_A),\n received_offset_(OFFSET_INVALID), pi_(0), is_in_sync_(false),\n block_has_errors_(50),\n#ifdef HAVE_LIQUID\n subcarrier_(has_echo),\n#endif\n ascii_bits_(has_echo),\n error_lookup_(makeErrorLookupTable()),\n input_type_(input_type), is_eof_(false) {\n\n}\n\nint BlockStream::getNextBit() {\n int result = 0;\n#ifdef HAVE_LIQUID\n if (input_type_ == INPUT_MPX) {\n result = subcarrier_.getNextBit();\n is_eof_ = subcarrier_.isEOF();\n }\n#endif\n if (input_type_ == INPUT_ASCIIBITS) {\n result = ascii_bits_.getNextBit();\n is_eof_ = ascii_bits_.isEOF();\n }\n\n return result;\n}\n\n\/\/ Section B.2.2\nuint32_t BlockStream::correctBurstErrors(uint32_t block) const {\n uint16_t synd_reg =\n calcSyndrome(block ^ offset_words[expected_offset_]);\n\n uint32_t corrected_block = block;\n\n if (error_lookup_.find(synd_reg) != error_lookup_.end()) {\n corrected_block = (block ^ offset_words[expected_offset_])\n ^ (error_lookup_.at(synd_reg));\n }\n\n return corrected_block;\n\n}\n\n\/\/ A block can't be decoded\nvoid BlockStream::uncorrectable() {\n block_has_errors_[block_counter_ % block_has_errors_.size()] = true;\n\n unsigned num_erroneous_blocks = 0;\n for (bool e : block_has_errors_) {\n if (e)\n num_erroneous_blocks++;\n }\n\n \/\/ Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2)\n if (is_in_sync_ && num_erroneous_blocks > 45) {\n is_in_sync_ = false;\n for (size_t i=0; i < block_has_errors_.size(); i++)\n block_has_errors_[i] = false;\n pi_ = 0x0000;\n }\n}\n\nbool BlockStream::acquireSync() {\n if (is_in_sync_)\n return true;\n\n \/\/ Try to find the repeating offset sequence\n if (received_offset_ != OFFSET_INVALID) {\n int dist = bitcount_ - prevbitcount_;\n\n if (dist % 26 == 0 && dist <= 156 &&\n (block_number_for_offset[prevsync_] + dist\/26) % 4 ==\n block_number_for_offset[received_offset_]) {\n is_in_sync_ = true;\n expected_offset_ = received_offset_;\n } else {\n prevbitcount_ = bitcount_;\n prevsync_ = received_offset_;\n }\n }\n\n return is_in_sync_;\n}\n\nGroup BlockStream::getNextGroup() {\n Group group;\n\n while (!isEOF()) {\n\n \/\/ Compensate for clock slip corrections\n bitcount_ += 26 - left_to_read_;\n\n \/\/ Read from radio\n for (int i=0; i < (is_in_sync_ ? left_to_read_ : 1); i++, bitcount_++) {\n wideblock_ = (wideblock_ << 1) + getNextBit();\n }\n\n left_to_read_ = 26;\n wideblock_ &= kBitmask28;\n\n uint32_t block = (wideblock_ >> 1) & kBitmask26;\n\n uint16_t syndrome = calcSyndrome(block);\n received_offset_ = (offset_syndromes.count(syndrome) > 0 ?\n offset_syndromes.at(syndrome) : OFFSET_INVALID);\n\n if (!acquireSync())\n continue;\n\n block_counter_++;\n uint16_t message = block >> 10;\n bool was_valid_word = true;\n\n if (expected_offset_ == OFFSET_C && received_offset_ == OFFSET_CI)\n expected_offset_ = OFFSET_CI;\n\n block_has_errors_[block_counter_ % block_has_errors_.size()] = false;\n\n if (received_offset_ != expected_offset_) {\n\n block_has_errors_[block_counter_ % block_has_errors_.size()] = true;\n\n was_valid_word = false;\n\n \/\/ Detect & correct clock slips (Section C.1.2)\n if (expected_offset_ == OFFSET_A && pi_ != 0 &&\n ((wideblock_ >> 12) & kBitmask16) == pi_) {\n message = pi_;\n wideblock_ >>= 1;\n received_offset_ = OFFSET_A;\n } else if (expected_offset_ == OFFSET_A && pi_ != 0 &&\n ((wideblock_ >> 10) & kBitmask16) == pi_) {\n message = pi_;\n wideblock_ = (wideblock_ << 1) + getNextBit();\n received_offset_ = OFFSET_A;\n left_to_read_ = 25;\n\n } else {\n\n block = correctBurstErrors(block);\n if (calcSyndrome(block) == 0x000) {\n message = block >> 10;\n received_offset_ = expected_offset_;\n }\n }\n\n \/\/ Still no valid syndrome\n if (received_offset_ != expected_offset_)\n uncorrectable();\n }\n\n \/\/ Error-free block received\n\n if (received_offset_ == expected_offset_) {\n\n group.block[expected_offset_] = message;\n group.hasOffset[expected_offset_] = true;\n\n if (expected_offset_ == OFFSET_A || expected_offset_ == OFFSET_CI) {\n group.pi = message;\n group.hasPi = true;\n if (was_valid_word)\n pi_ = message;\n }\n }\n\n expected_offset_ = nextOffsetFor(expected_offset_);\n\n if (expected_offset_ == OFFSET_A) {\n break;\n }\n }\n\n if (group.hasOffset[OFFSET_B]) {\n group.type = GroupType(bits(group.block[OFFSET_B], 11, 5));\n group.hasType = true;\n } else if (group.hasOffset[OFFSET_CI] && group.hasOffset[OFFSET_D]) {\n GroupType potential(bits(group.block[OFFSET_D], 11, 5));\n if (potential.num == 15 && potential.ab == VERSION_B) {\n group.type = potential;\n group.hasType = true;\n }\n }\n\n return group;\n}\n\nbool BlockStream::isEOF() const {\n return is_eof_;\n}\n\n#ifdef DEBUG\nfloat BlockStream::getT() const {\n return subcarrier_.getT();\n}\n#endif\n\n} \/\/ namespace redsea\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * 1. Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the\n * following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n#include \"schema.h\"\n#include \"user_def.h\"\n#include \"engine.h\"\n#include \"space.h\"\n#include \"func.h\"\n#include \"tuple.h\"\n#include \"assoc.h\"\n#include \"lua\/utils.h\"\n#include \"lua\/space.h\"\n#include \"key_def.h\"\n#include \"alter.h\"\n#include \"scoped_guard.h\"\n#include <stdio.h>\n\/**\n * @module Data Dictionary\n *\n * The data dictionary is responsible for storage and caching\n * of system metadata, such as information about existing\n * spaces, indexes, tuple formats. Space and index metadata\n * is called in dedicated spaces, _space and _index respectively.\n * The contents of these spaces is fully cached in a cache of\n * struct space objects.\n *\n * struct space is an in-memory instance representing a single\n * space with its metadata, space data, and methods to manage\n * it.\n *\/\n\n\/** All existing spaces. *\/\nstatic struct mh_i32ptr_t *spaces;\nstatic struct mh_i32ptr_t *funcs;\nint sc_version;\n\nbool\nspace_is_system(struct space *space)\n{\n\treturn space->def.id > SC_SYSTEM_ID_MIN &&\n\t\tspace->def.id < SC_SYSTEM_ID_MAX;\n}\n\n\/** Return space by its number *\/\nextern \"C\" struct space *\nspace_by_id(uint32_t id)\n{\n\tmh_int_t space = mh_i32ptr_find(spaces, id, NULL);\n\tif (space == mh_end(spaces))\n\t\treturn NULL;\n\treturn (struct space *) mh_i32ptr_node(spaces, space)->val;\n}\n\nextern \"C\" const char *\nspace_name_by_id(uint32_t id)\n{\n\tstruct space *space = space_by_id(id);\n\treturn space ? space_name(space) : \"\";\n}\n\n\/**\n * Visit all spaces and apply 'func'.\n *\/\nvoid\nspace_foreach(void (*func)(struct space *sp, void *udata), void *udata)\n{\n\tmh_int_t i;\n\tstruct space *space;\n\tchar key[6];\n\tassert(mp_sizeof_uint(SC_SYSTEM_ID_MIN) <= sizeof(key));\n\tmp_encode_uint(key, SC_SYSTEM_ID_MIN);\n\n\t\/*\n\t * Make sure we always visit system spaces first,\n\t * in order from lowest space id to the highest..\n\t * This is essential for correctly recovery from the\n\t * snapshot, and harmless otherwise.\n\t *\/\n\tspace = space_by_id(SC_SPACE_ID);\n\tIndex *pk = space ? space_index(space, 0) : NULL;\n\tif (pk) {\n\t\tstruct iterator *it = pk->allocIterator();\n\t\tauto scoped_guard = make_scoped_guard([=] { it->free(it); });\n\t\tpk->initIterator(it, ITER_GE, key, 1);\n\t\tIteratorGuard it_guard(it);\n\n\t\tstruct tuple *tuple;\n\t\twhile ((tuple = it->next(it))) {\n\t\t\t\/* Get space id, primary key, field 0. *\/\n\t\t\tuint32_t id = tuple_field_u32(tuple, 0);\n\t\t\tspace = space_cache_find(id);\n\t\t\tif (! space_is_system(space))\n\t\t\t\tbreak;\n\t\t\tfunc(space, udata);\n\t\t}\n\t}\n\n\tmh_foreach(spaces, i) {\n\t\tspace = (struct space *) mh_i32ptr_node(spaces, i)->val;\n\t\tif (space_is_system(space))\n\t\t\tcontinue;\n\t\tfunc(space, udata);\n\t}\n}\n\n\/** Delete a space from the space cache and Lua. *\/\nstruct space *\nspace_cache_delete(uint32_t id)\n{\n\tif (tarantool_L)\n\t\tbox_lua_space_delete(tarantool_L, id);\n\tmh_int_t k = mh_i32ptr_find(spaces, id, NULL);\n\tassert(k != mh_end(spaces));\n\tstruct space *space = (struct space *)mh_i32ptr_node(spaces, k)->val;\n\tmh_i32ptr_del(spaces, k, NULL);\n\tsc_version++;\n\treturn space;\n}\n\n\/**\n * Update the space in the space cache and in Lua. Returns\n * the old space instance, if any, or NULL if it's a new space.\n *\/\nstruct space *\nspace_cache_replace(struct space *space)\n{\n\tconst struct mh_i32ptr_node_t node = { space_id(space), space };\n\tstruct mh_i32ptr_node_t old, *p_old = &old;\n\tmh_int_t k = mh_i32ptr_put(spaces, &node, &p_old, NULL);\n\tif (k == mh_end(spaces)) {\n\t\tpanic_syserror(\"Out of memory for the data \"\n\t\t\t \"dictionary cache.\");\n\t}\n\tsc_version++;\n\t\/*\n\t * Must be after the space is put into the hash, since\n\t * box.schema.space.bless() uses hash look up to find the\n\t * space and create userdata objects for space objects.\n\t *\/\n\tbox_lua_space_new(tarantool_L, space);\n\treturn p_old ? (struct space *) p_old->val : NULL;\n}\n\n\/** A wrapper around space_new() for data dictionary spaces. *\/\nstruct space *\nsc_space_new(struct space_def *space_def,\n\t struct key_def *key_def,\n\t struct trigger *trigger)\n{\n\tstruct rlist key_list;\n\trlist_create(&key_list);\n\trlist_add_entry(&key_list, key_def, link);\n\tstruct space *space = space_new(space_def, &key_list);\n\t(void) space_cache_replace(space);\n\tif (trigger)\n\t\ttrigger_add(&space->on_replace, trigger);\n\t\/*\n\t * Data dictionary spaces are fully built since:\n\t * - they contain data right from the start\n\t * - they are fully operable already during recovery\n\t * - if there is a record in the snapshot which mandates\n\t * addition of a new index to a system space, this\n\t * index is built tuple-by-tuple, not in bulk, which\n\t * ensures validation of tuples when starting from\n\t * a snapshot of older version.\n\t *\/\n\tspace->handler->engine->initSystemSpace(space);\n\treturn space;\n}\n\nuint32_t\nschema_find_id(uint32_t system_space_id, uint32_t index_id,\n\t const char *name, uint32_t len)\n{\n\tstruct space *space = space_cache_find(system_space_id);\n\tIndex *index = index_find(space, index_id);\n\tstruct iterator *it = index->position();\n\tchar key[5 \/* str len *\/ + BOX_NAME_MAX];\n\tmp_encode_str(key, name, len);\n\tindex->initIterator(it, ITER_EQ, key, 1);\n\tIteratorGuard it_guard(it);\n\n\tstruct tuple *tuple;\n\twhile ((tuple = it->next(it))) {\n\t\t\/* id is always field #1 *\/\n\t\treturn tuple_field_u32(tuple, 0);\n\t}\n\treturn SC_ID_NIL;\n}\n\n\/**\n * Initialize a prototype for the two mandatory data\n * dictionary spaces and create a cache entry for them.\n * When restoring data from the snapshot these spaces\n * will get altered automatically to their actual format.\n *\/\nvoid\nschema_init()\n{\n\t\/* Initialize the space cache. *\/\n\tspaces = mh_i32ptr_new();\n\tfuncs = mh_i32ptr_new();\n\t\/*\n\t * Create surrogate space objects for the mandatory system\n\t * spaces (the primal eggs from which we get all the\n\t * chicken). Their definitions will be overwritten by the\n\t * data in the snapshot, and they will thus be\n\t * *re-created* during recovery. Note, the index type\n\t * must be TREE and space identifiers must be the smallest\n\t * one to ensure that these spaces are always recovered\n\t * (and re-created) first.\n\t *\/\n\t\/* _schema - key\/value space with schema description *\/\n\tstruct space_def def = {\n\t\tSC_SCHEMA_ID, ADMIN, 0, \"_schema\", \"memtx\", false\n\t};\n\tstruct key_def *key_def = key_def_new(def.id,\n\t\t\t\t\t 0 \/* index id *\/,\n\t\t\t\t\t \"primary\", \/* name *\/\n\t\t\t\t\t TREE \/* index type *\/,\n\t\t\t\t\t true \/* unique *\/,\n\t\t\t\t\t 1 \/* part count *\/);\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, STRING);\n\t(void) sc_space_new(&def, key_def, &on_replace_schema);\n\n\t\/* _space - home for all spaces. *\/\n\tkey_def->space_id = def.id = SC_SPACE_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_space\");\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, NUM);\n\n\t(void) sc_space_new(&def, key_def, &alter_space_on_replace_space);\n\n\t\/* _user - all existing users *\/\n\tkey_def->space_id = def.id = SC_USER_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_user\");\n\t(void) sc_space_new(&def, key_def, &on_replace_user);\n\n\t\/* _func - all executable objects on which one can have grants *\/\n\tkey_def->space_id = def.id = SC_FUNC_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_func\");\n\t(void) sc_space_new(&def, key_def, &on_replace_func);\n\t\/*\n\t * _priv - association user <-> object\n\t * The real index is defined in the snapshot.\n\t *\/\n\tkey_def->space_id = def.id = SC_PRIV_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_priv\");\n\t(void) sc_space_new(&def, key_def, &on_replace_priv);\n\t\/*\n\t * _cluster - association server uuid <-> server id\n\t * The real index is defined in the snapshot.\n\t *\/\n\tkey_def->space_id = def.id = SC_CLUSTER_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_cluster\");\n\t(void) sc_space_new(&def, key_def, &on_replace_cluster);\n\tkey_def_delete(key_def);\n\n\t\/* _index - definition of indexes in all spaces *\/\n\tdef.id = SC_INDEX_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_index\");\n\tkey_def = key_def_new(def.id,\n\t\t\t 0 \/* index id *\/,\n\t\t\t \"primary\",\n\t\t\t TREE \/* index type *\/,\n\t\t\t true \/* unique *\/,\n\t\t\t 2 \/* part count *\/);\n\t\/* space no *\/\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, NUM);\n\t\/* index no *\/\n\tkey_def_set_part(key_def, 1 \/* part no *\/, 1 \/* field no *\/, NUM);\n\t(void) sc_space_new(&def, key_def, &alter_space_on_replace_index);\n\tkey_def_delete(key_def);\n}\n\nvoid\nschema_free(void)\n{\n\tif (spaces == NULL)\n\t\treturn;\n\twhile (mh_size(spaces) > 0) {\n\t\tmh_int_t i = mh_first(spaces);\n\n\t\tstruct space *space = (struct space *)\n\t\t\t\tmh_i32ptr_node(spaces, i)->val;\n\t\tspace_cache_delete(space_id(space));\n\t\tspace_delete(space);\n\t}\n\tmh_i32ptr_delete(spaces);\n\twhile (mh_size(funcs) > 0) {\n\t\tmh_int_t i = mh_first(funcs);\n\n\t\tstruct func *func = ((struct func *)\n\t\t\t\t mh_i32ptr_node(funcs, i)->val);\n\t\tfunc_cache_delete(func->def.fid);\n\t}\n\tmh_i32ptr_delete(funcs);\n}\n\nvoid\nfunc_cache_replace(struct func_def *def)\n{\n\tstruct func *old = func_by_id(def->fid);\n\tif (old) {\n\t\tfunc_update(old, def);\n\t\treturn;\n\t}\n\tif (mh_size(funcs) >= BOX_FUNCTION_MAX)\n\t\ttnt_raise(ClientError, ER_FUNCTION_MAX, BOX_FUNCTION_MAX);\n\tstruct func *func = func_new(def);\n\tif (func == NULL) {\nerror:\n\t\tpanic_syserror(\"Out of memory for the data \"\n\t\t\t \"dictionary cache (stored function).\");\n\t}\n\tconst struct mh_i32ptr_node_t node = { def->fid, func };\n\tmh_int_t k = mh_i32ptr_put(funcs, &node, NULL, NULL);\n\tif (k == mh_end(funcs)) {\n\t\tfunc_delete(func);\n\t\tgoto error;\n\t}\n}\n\nvoid\nfunc_cache_delete(uint32_t fid)\n{\n\tmh_int_t k = mh_i32ptr_find(funcs, fid, NULL);\n\tif (k == mh_end(funcs))\n\t\treturn;\n\tstruct func *func = (struct func *)\n\t\tmh_i32ptr_node(funcs, k)->val;\n\tmh_i32ptr_del(funcs, k, NULL);\n\tfunc_delete(func);\n}\n\nstruct func *\nfunc_by_id(uint32_t fid)\n{\n\tmh_int_t func = mh_i32ptr_find(funcs, fid, NULL);\n\tif (func == mh_end(funcs))\n\t\treturn NULL;\n\treturn (struct func *) mh_i32ptr_node(funcs, func)->val;\n}\n\nbool\nschema_find_grants(const char *type, uint32_t id)\n{\n\tstruct space *priv = space_cache_find(SC_PRIV_ID);\n\t\/** \"object\" index *\/\n\tIndex *index = index_find(priv, 2);\n\tstruct iterator *it = index->position();\n\tchar key[10 + BOX_NAME_MAX];\n\tmp_encode_uint(mp_encode_str(key, type, strlen(type)), id);\n\tindex->initIterator(it, ITER_EQ, key, 2);\n\tIteratorGuard it_guard(it);\n\treturn it->next(it);\n}\n<commit_msg>fixed gh-899 : added dynamic length buffer for msgpack string<commit_after>\/*\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * 1. Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the\n * following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n#include \"schema.h\"\n#include \"user_def.h\"\n#include \"engine.h\"\n#include \"space.h\"\n#include \"func.h\"\n#include \"tuple.h\"\n#include \"assoc.h\"\n#include \"lua\/utils.h\"\n#include \"lua\/space.h\"\n#include \"key_def.h\"\n#include \"alter.h\"\n#include \"scoped_guard.h\"\n#include <stdio.h>\n\/**\n * @module Data Dictionary\n *\n * The data dictionary is responsible for storage and caching\n * of system metadata, such as information about existing\n * spaces, indexes, tuple formats. Space and index metadata\n * is called in dedicated spaces, _space and _index respectively.\n * The contents of these spaces is fully cached in a cache of\n * struct space objects.\n *\n * struct space is an in-memory instance representing a single\n * space with its metadata, space data, and methods to manage\n * it.\n *\/\n\n\/** All existing spaces. *\/\nstatic struct mh_i32ptr_t *spaces;\nstatic struct mh_i32ptr_t *funcs;\nint sc_version;\n\nbool\nspace_is_system(struct space *space)\n{\n\treturn space->def.id > SC_SYSTEM_ID_MIN &&\n\t\tspace->def.id < SC_SYSTEM_ID_MAX;\n}\n\n\/** Return space by its number *\/\nextern \"C\" struct space *\nspace_by_id(uint32_t id)\n{\n\tmh_int_t space = mh_i32ptr_find(spaces, id, NULL);\n\tif (space == mh_end(spaces))\n\t\treturn NULL;\n\treturn (struct space *) mh_i32ptr_node(spaces, space)->val;\n}\n\nextern \"C\" const char *\nspace_name_by_id(uint32_t id)\n{\n\tstruct space *space = space_by_id(id);\n\treturn space ? space_name(space) : \"\";\n}\n\n\/**\n * Visit all spaces and apply 'func'.\n *\/\nvoid\nspace_foreach(void (*func)(struct space *sp, void *udata), void *udata)\n{\n\tmh_int_t i;\n\tstruct space *space;\n\tchar key[6];\n\tassert(mp_sizeof_uint(SC_SYSTEM_ID_MIN) <= sizeof(key));\n\tmp_encode_uint(key, SC_SYSTEM_ID_MIN);\n\n\t\/*\n\t * Make sure we always visit system spaces first,\n\t * in order from lowest space id to the highest..\n\t * This is essential for correctly recovery from the\n\t * snapshot, and harmless otherwise.\n\t *\/\n\tspace = space_by_id(SC_SPACE_ID);\n\tIndex *pk = space ? space_index(space, 0) : NULL;\n\tif (pk) {\n\t\tstruct iterator *it = pk->allocIterator();\n\t\tauto scoped_guard = make_scoped_guard([=] { it->free(it); });\n\t\tpk->initIterator(it, ITER_GE, key, 1);\n\t\tIteratorGuard it_guard(it);\n\n\t\tstruct tuple *tuple;\n\t\twhile ((tuple = it->next(it))) {\n\t\t\t\/* Get space id, primary key, field 0. *\/\n\t\t\tuint32_t id = tuple_field_u32(tuple, 0);\n\t\t\tspace = space_cache_find(id);\n\t\t\tif (! space_is_system(space))\n\t\t\t\tbreak;\n\t\t\tfunc(space, udata);\n\t\t}\n\t}\n\n\tmh_foreach(spaces, i) {\n\t\tspace = (struct space *) mh_i32ptr_node(spaces, i)->val;\n\t\tif (space_is_system(space))\n\t\t\tcontinue;\n\t\tfunc(space, udata);\n\t}\n}\n\n\/** Delete a space from the space cache and Lua. *\/\nstruct space *\nspace_cache_delete(uint32_t id)\n{\n\tif (tarantool_L)\n\t\tbox_lua_space_delete(tarantool_L, id);\n\tmh_int_t k = mh_i32ptr_find(spaces, id, NULL);\n\tassert(k != mh_end(spaces));\n\tstruct space *space = (struct space *)mh_i32ptr_node(spaces, k)->val;\n\tmh_i32ptr_del(spaces, k, NULL);\n\tsc_version++;\n\treturn space;\n}\n\n\/**\n * Update the space in the space cache and in Lua. Returns\n * the old space instance, if any, or NULL if it's a new space.\n *\/\nstruct space *\nspace_cache_replace(struct space *space)\n{\n\tconst struct mh_i32ptr_node_t node = { space_id(space), space };\n\tstruct mh_i32ptr_node_t old, *p_old = &old;\n\tmh_int_t k = mh_i32ptr_put(spaces, &node, &p_old, NULL);\n\tif (k == mh_end(spaces)) {\n\t\tpanic_syserror(\"Out of memory for the data \"\n\t\t\t \"dictionary cache.\");\n\t}\n\tsc_version++;\n\t\/*\n\t * Must be after the space is put into the hash, since\n\t * box.schema.space.bless() uses hash look up to find the\n\t * space and create userdata objects for space objects.\n\t *\/\n\tbox_lua_space_new(tarantool_L, space);\n\treturn p_old ? (struct space *) p_old->val : NULL;\n}\n\n\/** A wrapper around space_new() for data dictionary spaces. *\/\nstruct space *\nsc_space_new(struct space_def *space_def,\n\t struct key_def *key_def,\n\t struct trigger *trigger)\n{\n\tstruct rlist key_list;\n\trlist_create(&key_list);\n\trlist_add_entry(&key_list, key_def, link);\n\tstruct space *space = space_new(space_def, &key_list);\n\t(void) space_cache_replace(space);\n\tif (trigger)\n\t\ttrigger_add(&space->on_replace, trigger);\n\t\/*\n\t * Data dictionary spaces are fully built since:\n\t * - they contain data right from the start\n\t * - they are fully operable already during recovery\n\t * - if there is a record in the snapshot which mandates\n\t * addition of a new index to a system space, this\n\t * index is built tuple-by-tuple, not in bulk, which\n\t * ensures validation of tuples when starting from\n\t * a snapshot of older version.\n\t *\/\n\tspace->handler->engine->initSystemSpace(space);\n\treturn space;\n}\n\nuint32_t\nschema_find_id(uint32_t system_space_id, uint32_t index_id,\n\t const char *name, uint32_t len)\n{\n\tstruct space *space = space_cache_find(system_space_id);\n\tIndex *index = index_find(space, index_id);\n\n\tconst uint32_t local_len = BOX_NAME_MAX * 2;\n\tchar buf[5 + local_len];\n\tchar *key = len <= local_len ? buf : (char *)malloc(5 + len);\n\tauto key_guard =\n\t\tmake_scoped_guard([key, &buf]{ if (key != buf) free(key); });\n\tmp_encode_str(key, name, len);\n\n\tstruct iterator *it = index->position();\n\tindex->initIterator(it, ITER_EQ, key, 1);\n\tIteratorGuard it_guard(it);\n\n\tstruct tuple *tuple = it->next(it);\n\tif (tuple) {\n\t\t\/* id is always field #1 *\/\n\t\treturn tuple_field_u32(tuple, 0);\n\t}\n\treturn SC_ID_NIL;\n}\n\n\/**\n * Initialize a prototype for the two mandatory data\n * dictionary spaces and create a cache entry for them.\n * When restoring data from the snapshot these spaces\n * will get altered automatically to their actual format.\n *\/\nvoid\nschema_init()\n{\n\t\/* Initialize the space cache. *\/\n\tspaces = mh_i32ptr_new();\n\tfuncs = mh_i32ptr_new();\n\t\/*\n\t * Create surrogate space objects for the mandatory system\n\t * spaces (the primal eggs from which we get all the\n\t * chicken). Their definitions will be overwritten by the\n\t * data in the snapshot, and they will thus be\n\t * *re-created* during recovery. Note, the index type\n\t * must be TREE and space identifiers must be the smallest\n\t * one to ensure that these spaces are always recovered\n\t * (and re-created) first.\n\t *\/\n\t\/* _schema - key\/value space with schema description *\/\n\tstruct space_def def = {\n\t\tSC_SCHEMA_ID, ADMIN, 0, \"_schema\", \"memtx\", false\n\t};\n\tstruct key_def *key_def = key_def_new(def.id,\n\t\t\t\t\t 0 \/* index id *\/,\n\t\t\t\t\t \"primary\", \/* name *\/\n\t\t\t\t\t TREE \/* index type *\/,\n\t\t\t\t\t true \/* unique *\/,\n\t\t\t\t\t 1 \/* part count *\/);\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, STRING);\n\t(void) sc_space_new(&def, key_def, &on_replace_schema);\n\n\t\/* _space - home for all spaces. *\/\n\tkey_def->space_id = def.id = SC_SPACE_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_space\");\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, NUM);\n\n\t(void) sc_space_new(&def, key_def, &alter_space_on_replace_space);\n\n\t\/* _user - all existing users *\/\n\tkey_def->space_id = def.id = SC_USER_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_user\");\n\t(void) sc_space_new(&def, key_def, &on_replace_user);\n\n\t\/* _func - all executable objects on which one can have grants *\/\n\tkey_def->space_id = def.id = SC_FUNC_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_func\");\n\t(void) sc_space_new(&def, key_def, &on_replace_func);\n\t\/*\n\t * _priv - association user <-> object\n\t * The real index is defined in the snapshot.\n\t *\/\n\tkey_def->space_id = def.id = SC_PRIV_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_priv\");\n\t(void) sc_space_new(&def, key_def, &on_replace_priv);\n\t\/*\n\t * _cluster - association server uuid <-> server id\n\t * The real index is defined in the snapshot.\n\t *\/\n\tkey_def->space_id = def.id = SC_CLUSTER_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_cluster\");\n\t(void) sc_space_new(&def, key_def, &on_replace_cluster);\n\tkey_def_delete(key_def);\n\n\t\/* _index - definition of indexes in all spaces *\/\n\tdef.id = SC_INDEX_ID;\n\tsnprintf(def.name, sizeof(def.name), \"_index\");\n\tkey_def = key_def_new(def.id,\n\t\t\t 0 \/* index id *\/,\n\t\t\t \"primary\",\n\t\t\t TREE \/* index type *\/,\n\t\t\t true \/* unique *\/,\n\t\t\t 2 \/* part count *\/);\n\t\/* space no *\/\n\tkey_def_set_part(key_def, 0 \/* part no *\/, 0 \/* field no *\/, NUM);\n\t\/* index no *\/\n\tkey_def_set_part(key_def, 1 \/* part no *\/, 1 \/* field no *\/, NUM);\n\t(void) sc_space_new(&def, key_def, &alter_space_on_replace_index);\n\tkey_def_delete(key_def);\n}\n\nvoid\nschema_free(void)\n{\n\tif (spaces == NULL)\n\t\treturn;\n\twhile (mh_size(spaces) > 0) {\n\t\tmh_int_t i = mh_first(spaces);\n\n\t\tstruct space *space = (struct space *)\n\t\t\t\tmh_i32ptr_node(spaces, i)->val;\n\t\tspace_cache_delete(space_id(space));\n\t\tspace_delete(space);\n\t}\n\tmh_i32ptr_delete(spaces);\n\twhile (mh_size(funcs) > 0) {\n\t\tmh_int_t i = mh_first(funcs);\n\n\t\tstruct func *func = ((struct func *)\n\t\t\t\t mh_i32ptr_node(funcs, i)->val);\n\t\tfunc_cache_delete(func->def.fid);\n\t}\n\tmh_i32ptr_delete(funcs);\n}\n\nvoid\nfunc_cache_replace(struct func_def *def)\n{\n\tstruct func *old = func_by_id(def->fid);\n\tif (old) {\n\t\tfunc_update(old, def);\n\t\treturn;\n\t}\n\tif (mh_size(funcs) >= BOX_FUNCTION_MAX)\n\t\ttnt_raise(ClientError, ER_FUNCTION_MAX, BOX_FUNCTION_MAX);\n\tstruct func *func = func_new(def);\n\tif (func == NULL) {\nerror:\n\t\tpanic_syserror(\"Out of memory for the data \"\n\t\t\t \"dictionary cache (stored function).\");\n\t}\n\tconst struct mh_i32ptr_node_t node = { def->fid, func };\n\tmh_int_t k = mh_i32ptr_put(funcs, &node, NULL, NULL);\n\tif (k == mh_end(funcs)) {\n\t\tfunc_delete(func);\n\t\tgoto error;\n\t}\n}\n\nvoid\nfunc_cache_delete(uint32_t fid)\n{\n\tmh_int_t k = mh_i32ptr_find(funcs, fid, NULL);\n\tif (k == mh_end(funcs))\n\t\treturn;\n\tstruct func *func = (struct func *)\n\t\tmh_i32ptr_node(funcs, k)->val;\n\tmh_i32ptr_del(funcs, k, NULL);\n\tfunc_delete(func);\n}\n\nstruct func *\nfunc_by_id(uint32_t fid)\n{\n\tmh_int_t func = mh_i32ptr_find(funcs, fid, NULL);\n\tif (func == mh_end(funcs))\n\t\treturn NULL;\n\treturn (struct func *) mh_i32ptr_node(funcs, func)->val;\n}\n\nbool\nschema_find_grants(const char *type, uint32_t id)\n{\n\tstruct space *priv = space_cache_find(SC_PRIV_ID);\n\t\/** \"object\" index *\/\n\tIndex *index = index_find(priv, 2);\n\tstruct iterator *it = index->position();\n\tchar key[10 + BOX_NAME_MAX];\n\tmp_encode_uint(mp_encode_str(key, type, strlen(type)), id);\n\tindex->initIterator(it, ITER_EQ, key, 2);\n\tIteratorGuard it_guard(it);\n\treturn it->next(it);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by mistlight on 1\/28\/2017.\n\/\/\n\n#include <src\/core\/tasks\/PlayerScanTask.h>\n#include <QDebug>\n#include <include\/vlc\/vlc.h>\n#include <src\/simple-lib\/ThreadPool.h>\n#include <QThread>\n#include \"ScanPlayer.h\"\n\nCore::ScanPlayer::ScanPlayer() {\n \/* Load the VLC engine *\/\n this->inst = libvlc_new(0, NULL);\n if(this->inst == NULL) {\n qWarning() << \"ERROR\";\n throw \"Exception has occured, cannot init vlc engine from Scanning\";\n }\n\n this->mediaPlayer = libvlc_media_player_new(this->inst);\n if(this->mediaPlayer == NULL) {\n qWarning() << \"ERROR: Could not create media player in Scanning\";\n }\n\n this->threadPool = std::unique_ptr<ThreadPool>(new ThreadPool(1));\n this->hasScanFinished = true;\n}\n\nvoid Core::ScanPlayer::addAudiobook(std::shared_ptr<AudiobookProxy> audiobook) {\n qDebug() << \"Scan audiobook called\";\n auto fileList = audiobook->getFilesForAudiobook();\n this->mutex.lock();\n for(int i = 0; i < fileList.size(); i++) {\n this->fileQueue.push(fileList[i]);\n }\n this->mutex.unlock();\n\n this->startScanTask(audiobook);\n}\n\nvoid Core::ScanPlayer::addAudiobookFile(std::shared_ptr<AudiobookFileProxy> file) {\n \/\/ don't need to call this function on already scanned items\n if(file->getMediaDuration() > 0) {\n return;\n }\n\n this->mutex.lock();\n this->fileQueue.push(file);\n this->mutex.unlock();\n\n this->startScanTask(nullptr);\n}\n\nvoid Core::ScanPlayer::startScanTask(std::shared_ptr<AudiobookProxy> audiobook) {\n auto scanTask = new PlayerScanTask(this, audiobook);\n this->scanThread.start(scanTask);\n}\n\n\nvoid Core::ScanPlayer::performScan() {\n this->mutex.lock();\n\n qDebug() << \"Scan task started\";\n\n while(!this->fileQueue.empty()) {\n this->hasScanFinished = false;\n std::shared_ptr<AudiobookFileProxy> & element = this->fileQueue.front();\n this->currentlyScanning = element;\n qDebug() << \"Currently scanning file: \" << element->path();\n\n auto path = element->path();\n auto currentFile = std::unique_ptr<QFile>(new QFile(path));\n\n if(!currentFile->open(QIODevice::ReadWrite)) {\n qDebug() << \"QFILE FAILED!: \" << path;\n return;\n }\n\n this->mediaItem = libvlc_media_new_fd(this->inst, currentFile->handle());\n if(this->mediaItem == NULL) {\n return;\n }\n\n libvlc_media_player_set_media(this->mediaPlayer, this->mediaItem);\n libvlc_media_player_play(this->mediaPlayer);\n\n libvlc_event_manager_t* eventManager = libvlc_media_event_manager(this->mediaItem);\n\n libvlc_event_attach(eventManager,\n libvlc_MediaStateChanged,\n (libvlc_callback_t) [](const struct libvlc_event_t * event, void *data) {\n auto newState = event->u.media_state_changed.new_state;\n if(newState == libvlc_Playing) {\n auto player = reinterpret_cast<ScanPlayer*>(data);\n\n player->threadPool->enqueue([player]() {\n long long duration = libvlc_media_get_duration(player->mediaItem);\n if(duration == -1) {\n player->currentlyScanning->setMediaDuration(duration);\n } else {\n qWarning() << \"performScan() failed for: \" << player->currentlyScanning->path();\n }\n\n\n libvlc_media_player_stop(player->mediaPlayer);\n\n player->hasScanFinished = true;\n qDebug() << \"scan finisehd for file: \" << player->currentlyScanning->path();\n });\n }\n },\n this);\n\n\n while(!hasScanFinished) {\n QThread::msleep(10);\n }\n\n this->fileQueue.pop();\n }\n\n this->mutex.unlock();\n qDebug() << \"Scan task ended\";\n\n}\n\nvoid Core::ScanPlayer::retrieveScanResults() {\n\n}\n\n<commit_msg>fix conditional<commit_after>\/\/\n\/\/ Created by mistlight on 1\/28\/2017.\n\/\/\n\n#include <src\/core\/tasks\/PlayerScanTask.h>\n#include <QDebug>\n#include <include\/vlc\/vlc.h>\n#include <src\/simple-lib\/ThreadPool.h>\n#include <QThread>\n#include \"ScanPlayer.h\"\n\nCore::ScanPlayer::ScanPlayer() {\n \/* Load the VLC engine *\/\n this->inst = libvlc_new(0, NULL);\n if(this->inst == NULL) {\n qWarning() << \"ERROR\";\n throw \"Exception has occured, cannot init vlc engine from Scanning\";\n }\n\n this->mediaPlayer = libvlc_media_player_new(this->inst);\n if(this->mediaPlayer == NULL) {\n qWarning() << \"ERROR: Could not create media player in Scanning\";\n }\n\n this->threadPool = std::unique_ptr<ThreadPool>(new ThreadPool(1));\n this->hasScanFinished = true;\n}\n\nvoid Core::ScanPlayer::addAudiobook(std::shared_ptr<AudiobookProxy> audiobook) {\n qDebug() << \"Scan audiobook called\";\n auto fileList = audiobook->getFilesForAudiobook();\n this->mutex.lock();\n for(int i = 0; i < fileList.size(); i++) {\n this->fileQueue.push(fileList[i]);\n }\n this->mutex.unlock();\n\n this->startScanTask(audiobook);\n}\n\nvoid Core::ScanPlayer::addAudiobookFile(std::shared_ptr<AudiobookFileProxy> file) {\n \/\/ don't need to call this function on already scanned items\n if(file->getMediaDuration() > 0) {\n return;\n }\n\n this->mutex.lock();\n this->fileQueue.push(file);\n this->mutex.unlock();\n\n this->startScanTask(nullptr);\n}\n\nvoid Core::ScanPlayer::startScanTask(std::shared_ptr<AudiobookProxy> audiobook) {\n auto scanTask = new PlayerScanTask(this, audiobook);\n this->scanThread.start(scanTask);\n}\n\n\nvoid Core::ScanPlayer::performScan() {\n this->mutex.lock();\n\n qDebug() << \"Scan task started\";\n\n while(!this->fileQueue.empty()) {\n this->hasScanFinished = false;\n std::shared_ptr<AudiobookFileProxy> & element = this->fileQueue.front();\n this->currentlyScanning = element;\n qDebug() << \"Currently scanning file: \" << element->path();\n\n auto path = element->path();\n auto currentFile = std::unique_ptr<QFile>(new QFile(path));\n\n if(!currentFile->open(QIODevice::ReadWrite)) {\n qDebug() << \"QFILE FAILED!: \" << path;\n return;\n }\n\n this->mediaItem = libvlc_media_new_fd(this->inst, currentFile->handle());\n if(this->mediaItem == NULL) {\n return;\n }\n\n libvlc_media_player_set_media(this->mediaPlayer, this->mediaItem);\n libvlc_media_player_play(this->mediaPlayer);\n\n libvlc_event_manager_t* eventManager = libvlc_media_event_manager(this->mediaItem);\n\n libvlc_event_attach(eventManager,\n libvlc_MediaParsedChanged,\n (libvlc_callback_t) [](const struct libvlc_event_t * event, void *data) {\n auto player = reinterpret_cast<ScanPlayer*>(data);\n int parsedStatus = libvlc_media_is_parsed(player->mediaItem);\n\n if(parsedStatus) {\n player->threadPool->enqueue([player]() {\n long long duration = libvlc_media_get_duration(player->mediaItem);\n if(duration > 0) {\n player->currentlyScanning->setMediaDuration(duration);\n qDebug() << \"performScan() SUCCESS: \" << player->currentlyScanning->path();\n } else {\n qWarning() << \"performScan() failed for: \" << player->currentlyScanning->path();\n }\n\n player->hasScanFinished = true;\n });\n }\n },\n this);\n\n\n while(!hasScanFinished) {\n QThread::msleep(10);\n }\n\n libvlc_media_player_stop(this->mediaPlayer);\n\n this->fileQueue.pop();\n }\n\n this->mutex.unlock();\n qDebug() << \"Scan task ended\";\n\n}\n\nvoid Core::ScanPlayer::retrieveScanResults() {\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"SearchForm.hpp\"\n#include \"SceneRegister.hpp\"\n#include \"MapsWithMeForm.hpp\"\n#include \"AppResourceId.h\"\n\n#include \"..\/..\/..\/map\/user_mark.hpp\"\n#include \"..\/..\/..\/map\/framework.hpp\"\n#include \"..\/..\/..\/search\/result.hpp\"\n#include \"..\/..\/..\/platform\/settings.hpp\"\n#include \"..\/..\/..\/platform\/tizen_utils.hpp\"\n#include \"..\/..\/..\/base\/logging.hpp\"\n\n#include <FWeb.h>\n#include <FAppApp.h>\n#include <FApp.h>\n#include \"Utils.hpp\"\n#include \"Framework.hpp\"\n#include \"Constants.hpp\"\n\nusing namespace Tizen::Base;\nusing namespace Tizen::Ui;\nusing namespace Tizen::Ui::Controls;\nusing namespace Tizen::Ui::Scenes;\nusing namespace Tizen::Base::Collection;\nusing namespace Tizen::Graphics;\nusing namespace search;\nusing namespace consts;\n\nnamespace detail\n{\ntypedef vector<String> CategoriesT;\nCategoriesT const & GetCategories()\n{\n static CategoriesT vr;\n if (vr.empty())\n {\n vr.push_back(GetString(IDS_FOOD));\n vr.push_back(GetString(IDS_SHOP));\n vr.push_back(GetString(IDS_HOTEL));\n vr.push_back(GetString(IDS_TOURISM));\n vr.push_back(GetString(IDS_ENTERTAINMENT));\n vr.push_back(GetString(IDS_ATM));\n vr.push_back(GetString(IDS_BANK));\n vr.push_back(GetString(IDS_TRANSPORT));\n vr.push_back(GetString(IDS_FUEL));\n vr.push_back(GetString(IDS_PARKING));\n vr.push_back(GetString(IDS_PHARMACY));\n vr.push_back(GetString(IDS_HOSPITAL));\n vr.push_back(GetString(IDS_TOILET));\n vr.push_back(GetString(IDS_POST));\n vr.push_back(GetString(IDS_POLICE));\n }\n return vr;\n}\n\nCustomItem * CreateFeatureItem(Result const & val, double itemWidth)\n{\n String itemText = val.GetString();\n CustomItem * pItem = new CustomItem();\n\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n FloatRectangle imgRect(btwWdth, topHght, imgWdth, imgHght);\n pItem->AddElement(imgRect, 0, *GetBitmap(IDB_SINGLE_RESULT), null, null);\n int txtWdht = itemWidth - btwWdth - imgWdth - backWdth;\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, 15, txtWdht, imgHght), 1, val.GetString(), mainFontSz, white, white, white);\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, 60.0f, txtWdht, imgHght), 2, val.GetRegionString(), minorFontSz, white, white, white);\n String feature = val.GetFeatureType();\n pItem->AddElement(FloatRectangle(itemWidth - backWdth, 10, backWdth, imgHght), 3, GetFeature(feature), minorFontSz, gray, gray, gray);\n double lat, lon;\n GetFramework()->GetCurrentPosition(lat, lon);\n double north = 0;\n string distance;\n double azimut;\n GetFramework()->GetDistanceAndAzimut(val.GetFeatureCenter(), lat, lon, north, distance, azimut);\n String dist(distance.c_str());\n pItem->AddElement(FloatRectangle(itemWidth - backWdth, 50, backWdth, imgHght), 4, dist, minorFontSz, gray, gray, gray);\n\n return pItem;\n}\n\nCustomItem * CreateSuggestionItem(String const & val, double itemWidth)\n{\n String itemText = val;\n CustomItem * pItem = new CustomItem();\n\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n FloatRectangle imgRect(btwWdth, topHght, imgWdth, imgHght);\n pItem->AddElement(imgRect, 0, *GetBitmap(IDB_SUGGESTION_RESULT), null, null);\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, topHght, itemWidth, imgHght), 1, itemText, mainFontSz, white, white, white);\n\n return pItem;\n}\n\n} \/\/ detail\n\nusing namespace detail;\n\n\nSearchForm::SearchForm()\n:m_searchBar(0)\n{\n}\n\nSearchForm::~SearchForm(void)\n{\n}\n\nbool SearchForm::Initialize(void)\n{\n Construct(IDF_SEARCH_FORM);\n return true;\n}\n\nresult SearchForm::OnInitializing(void)\n{\n m_searchBar = static_cast<SearchBar *>(GetControl(IDC_SEARCHBAR, true));\n m_searchBar->SetMode(SEARCH_BAR_MODE_INPUT);\n m_searchBar->AddActionEventListener(*this);\n m_searchBar->AddTextEventListener(*this);\n m_searchBar->AddKeypadEventListener(*this);\n\n ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW, true));\n pList->SetItemProvider(*this);\n pList->AddListViewItemEventListener(*this);\n pList->AddScrollEventListener(*this);\n\n SetFormBackEventListener(this);\n\n return E_SUCCESS;\n}\n\nvoid SearchForm::OnActionPerformed(Tizen::Ui::Control const & source, int actionId)\n{\n if (actionId == m_searchBar->GetButtonActionId())\n {\n GetFramework()->CancelInteractiveSearch();\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n }\n}\n\nvoid SearchForm::OnTextValueChanged(Tizen::Ui::Control const & source)\n{\n Search(GetSearchString());\n}\n\nvoid SearchForm::OnSearchResultsReceived(search::Results const & results)\n{\n if (results.IsEndMarker())\n {\n if (!results.IsEndedNormal())\n m_curResults.Clear();\n UpdateList();\n }\n else\n m_curResults = results;\n}\n\nvoid SearchForm::OnFormBackRequested(Tizen::Ui::Controls::Form & source)\n{\n GetFramework()->CancelInteractiveSearch();\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n}\n\nListItemBase * SearchForm::CreateItem (int index, float itemWidth)\n{\n if(IsShowCategories())\n {\n return CreateSuggestionItem(GetCategories()[index], itemWidth);\n }\n else\n {\n if (m_curResults.GetCount() == 0)\n {\n String itemText = GetString(IDS_NO_SEARCH_RESULTS_FOUND);\n CustomItem * pItem = new CustomItem();\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n pItem->AddElement(FloatRectangle(btwWdth, topHght, itemWidth, imgHght), 0, itemText, mainFontSz, white, white, white);\n return pItem;\n }\n else\n {\n Result const & res = m_curResults.GetResult(index);\n if (res.GetResultType() == Result::RESULT_SUGGESTION)\n return CreateSuggestionItem(res.GetString(), itemWidth);\n else\n return CreateFeatureItem(res, itemWidth);\n }\n }\n}\n\nvoid SearchForm::OnListViewItemStateChanged(Tizen::Ui::Controls::ListView & listView, int index, int elementId, Tizen::Ui::Controls::ListItemStatus status)\n{\n if(IsShowCategories())\n {\n m_searchBar->SetText(GetCategories()[index]);\n Search(GetSearchString());\n Invalidate(true);\n }\n else\n {\n if (m_curResults.GetCount() > 0)\n {\n Result res = m_curResults.GetResult(index);\n if (res.GetResultType() == Result::RESULT_SUGGESTION)\n {\n m_searchBar->SetText(res.GetString());\n Search(GetSearchString());\n Invalidate(true);\n }\n else\n {\n GetFramework()->ShowSearchResult(res);\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n }\n }\n }\n}\n\nvoid SearchForm::OnScrollPositionChanged(Tizen::Ui::Control & source, int scrollPosition)\n{\n m_searchBar->HideKeypad();\n}\n\nbool SearchForm::DeleteItem (int index, Tizen::Ui::Controls::ListItemBase * pItem, float itemWidth)\n{\n delete pItem;\n return true;\n}\n\nint SearchForm::GetItemCount(void)\n{\n if (IsShowCategories())\n {\n return GetCategories().size();\n }\n else\n {\n if (m_curResults.GetCount() == 0)\n return 1;\n else\n return m_curResults.GetCount();\n }\n}\n\nvoid SearchForm::UpdateList()\n{\n ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW));\n pList->UpdateList();\n pList->RemoveScrollEventListener(*this);\n pList->ScrollToItem(0);\n pList->AddScrollEventListener(*this);\n}\n\nvoid SearchForm::Search(String const & val)\n{\n search::SearchParams params;\n params.m_callback = bind(&SearchForm::OnSearchResultsReceived, this, _1);\n params.m_query = FromTizenString(val);\n\n Tizen::Locales::LanguageCode language;\n if (m_searchBar->GetCurrentLanguage(language) == E_SUCCESS)\n params.SetInputLanguage(CodeFromISO369_2to_1(GetLanguageCode(language)));\n double lat, lon;\n GetFramework()->GetCurrentPosition(lat, lon);\n params.SetPosition(lat, lon);\n\n GetFramework()->Search(params);\n}\n\nString SearchForm::GetSearchString() const\n{\n return m_searchBar->GetText();\n}\n\nbool SearchForm::IsShowCategories() const\n{\n return GetSearchString().IsEmpty();\n}\n\nvoid SearchForm::OnKeypadActionPerformed (Tizen::Ui::Control & source, Tizen::Ui::KeypadAction keypadAction)\n{\n if (keypadAction == KEYPAD_ACTION_SEARCH)\n {\n GetFramework()->ShowAllSearchResults();\n ArrayList * pList = new ArrayList;\n pList->Construct();\n pList->Add(new String(GetSearchString()));\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT), pList);\n }\n}\n\nvoid SearchForm::OnSceneActivatedN(const Tizen::Ui::Scenes::SceneId& previousSceneId,\n const Tizen::Ui::Scenes::SceneId& currentSceneId, Tizen::Base::Collection::IList* pArgs)\n{\n if (pArgs != null)\n {\n \/\/ Come from Main page in resume mode\n if (pArgs->GetCount() == 1)\n {\n String * pSearchText = dynamic_cast<String *>(pArgs->GetAt(0));\n m_searchBar->SetText(*pSearchText);\n Search(GetSearchString());\n }\n pArgs->RemoveAll(true);\n delete pArgs;\n }\n}\n<commit_msg>[Tizen] Enable interactive search.<commit_after>#include \"SearchForm.hpp\"\n#include \"SceneRegister.hpp\"\n#include \"MapsWithMeForm.hpp\"\n#include \"AppResourceId.h\"\n\n#include \"..\/..\/..\/map\/user_mark.hpp\"\n#include \"..\/..\/..\/map\/framework.hpp\"\n#include \"..\/..\/..\/search\/result.hpp\"\n#include \"..\/..\/..\/platform\/settings.hpp\"\n#include \"..\/..\/..\/platform\/tizen_utils.hpp\"\n#include \"..\/..\/..\/base\/logging.hpp\"\n\n#include <FWeb.h>\n#include <FAppApp.h>\n#include <FApp.h>\n#include \"Utils.hpp\"\n#include \"Framework.hpp\"\n#include \"Constants.hpp\"\n\nusing namespace Tizen::Base;\nusing namespace Tizen::Ui;\nusing namespace Tizen::Ui::Controls;\nusing namespace Tizen::Ui::Scenes;\nusing namespace Tizen::Base::Collection;\nusing namespace Tizen::Graphics;\nusing namespace search;\nusing namespace consts;\n\nnamespace detail\n{\ntypedef vector<String> CategoriesT;\nCategoriesT const & GetCategories()\n{\n static CategoriesT vr;\n if (vr.empty())\n {\n vr.push_back(GetString(IDS_FOOD));\n vr.push_back(GetString(IDS_SHOP));\n vr.push_back(GetString(IDS_HOTEL));\n vr.push_back(GetString(IDS_TOURISM));\n vr.push_back(GetString(IDS_ENTERTAINMENT));\n vr.push_back(GetString(IDS_ATM));\n vr.push_back(GetString(IDS_BANK));\n vr.push_back(GetString(IDS_TRANSPORT));\n vr.push_back(GetString(IDS_FUEL));\n vr.push_back(GetString(IDS_PARKING));\n vr.push_back(GetString(IDS_PHARMACY));\n vr.push_back(GetString(IDS_HOSPITAL));\n vr.push_back(GetString(IDS_TOILET));\n vr.push_back(GetString(IDS_POST));\n vr.push_back(GetString(IDS_POLICE));\n }\n return vr;\n}\n\nCustomItem * CreateFeatureItem(Result const & val, double itemWidth)\n{\n String itemText = val.GetString();\n CustomItem * pItem = new CustomItem();\n\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n FloatRectangle imgRect(btwWdth, topHght, imgWdth, imgHght);\n pItem->AddElement(imgRect, 0, *GetBitmap(IDB_SINGLE_RESULT), null, null);\n int txtWdht = itemWidth - btwWdth - imgWdth - backWdth;\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, 15, txtWdht, imgHght), 1, val.GetString(), mainFontSz, white, white, white);\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, 60.0f, txtWdht, imgHght), 2, val.GetRegionString(), minorFontSz, white, white, white);\n String feature = val.GetFeatureType();\n pItem->AddElement(FloatRectangle(itemWidth - backWdth, 10, backWdth, imgHght), 3, GetFeature(feature), minorFontSz, gray, gray, gray);\n double lat, lon;\n GetFramework()->GetCurrentPosition(lat, lon);\n double north = 0;\n string distance;\n double azimut;\n GetFramework()->GetDistanceAndAzimut(val.GetFeatureCenter(), lat, lon, north, distance, azimut);\n String dist(distance.c_str());\n pItem->AddElement(FloatRectangle(itemWidth - backWdth, 50, backWdth, imgHght), 4, dist, minorFontSz, gray, gray, gray);\n\n return pItem;\n}\n\nCustomItem * CreateSuggestionItem(String const & val, double itemWidth)\n{\n String itemText = val;\n CustomItem * pItem = new CustomItem();\n\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n FloatRectangle imgRect(btwWdth, topHght, imgWdth, imgHght);\n pItem->AddElement(imgRect, 0, *GetBitmap(IDB_SUGGESTION_RESULT), null, null);\n pItem->AddElement(FloatRectangle(btwWdth + imgWdth + btwWdth, topHght, itemWidth, imgHght), 1, itemText, mainFontSz, white, white, white);\n\n return pItem;\n}\n\n} \/\/ detail\n\nusing namespace detail;\n\n\nSearchForm::SearchForm()\n:m_searchBar(0)\n{\n}\n\nSearchForm::~SearchForm(void)\n{\n}\n\nbool SearchForm::Initialize(void)\n{\n Construct(IDF_SEARCH_FORM);\n return true;\n}\n\nresult SearchForm::OnInitializing(void)\n{\n m_searchBar = static_cast<SearchBar *>(GetControl(IDC_SEARCHBAR, true));\n m_searchBar->SetMode(SEARCH_BAR_MODE_INPUT);\n m_searchBar->AddActionEventListener(*this);\n m_searchBar->AddTextEventListener(*this);\n m_searchBar->AddKeypadEventListener(*this);\n\n ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW, true));\n pList->SetItemProvider(*this);\n pList->AddListViewItemEventListener(*this);\n pList->AddScrollEventListener(*this);\n\n SetFormBackEventListener(this);\n\n return E_SUCCESS;\n}\n\nvoid SearchForm::OnActionPerformed(Tizen::Ui::Control const & source, int actionId)\n{\n if (actionId == m_searchBar->GetButtonActionId())\n {\n GetFramework()->CancelInteractiveSearch();\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n }\n}\n\nvoid SearchForm::OnTextValueChanged(Tizen::Ui::Control const & source)\n{\n Search(GetSearchString());\n}\n\nvoid SearchForm::OnSearchResultsReceived(search::Results const & results)\n{\n if (results.IsEndMarker())\n {\n if (!results.IsEndedNormal())\n m_curResults.Clear();\n UpdateList();\n }\n else\n m_curResults = results;\n}\n\nvoid SearchForm::OnFormBackRequested(Tizen::Ui::Controls::Form & source)\n{\n GetFramework()->CancelInteractiveSearch();\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n}\n\nListItemBase * SearchForm::CreateItem (int index, float itemWidth)\n{\n if(IsShowCategories())\n {\n return CreateSuggestionItem(GetCategories()[index], itemWidth);\n }\n else\n {\n if (m_curResults.GetCount() == 0)\n {\n String itemText = GetString(IDS_NO_SEARCH_RESULTS_FOUND);\n CustomItem * pItem = new CustomItem();\n pItem->Construct(FloatDimension(itemWidth, lstItmHght), LIST_ANNEX_STYLE_NORMAL);\n pItem->AddElement(FloatRectangle(btwWdth, topHght, itemWidth, imgHght), 0, itemText, mainFontSz, white, white, white);\n return pItem;\n }\n else\n {\n Result const & res = m_curResults.GetResult(index);\n if (res.GetResultType() == Result::RESULT_SUGGESTION)\n return CreateSuggestionItem(res.GetString(), itemWidth);\n else\n return CreateFeatureItem(res, itemWidth);\n }\n }\n}\n\nvoid SearchForm::OnListViewItemStateChanged(Tizen::Ui::Controls::ListView & listView, int index, int elementId, Tizen::Ui::Controls::ListItemStatus status)\n{\n if(IsShowCategories())\n {\n m_searchBar->SetText(GetCategories()[index]);\n Search(GetSearchString());\n Invalidate(true);\n }\n else\n {\n if (m_curResults.GetCount() > 0)\n {\n Result res = m_curResults.GetResult(index);\n if (res.GetResultType() == Result::RESULT_SUGGESTION)\n {\n m_searchBar->SetText(res.GetString());\n Search(GetSearchString());\n Invalidate(true);\n }\n else\n {\n GetFramework()->ShowSearchResult(res);\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT));\n }\n }\n }\n}\n\nvoid SearchForm::OnScrollPositionChanged(Tizen::Ui::Control & source, int scrollPosition)\n{\n m_searchBar->HideKeypad();\n}\n\nbool SearchForm::DeleteItem (int index, Tizen::Ui::Controls::ListItemBase * pItem, float itemWidth)\n{\n delete pItem;\n return true;\n}\n\nint SearchForm::GetItemCount(void)\n{\n if (IsShowCategories())\n {\n return GetCategories().size();\n }\n else\n {\n if (m_curResults.GetCount() == 0)\n return 1;\n else\n return m_curResults.GetCount();\n }\n}\n\nvoid SearchForm::UpdateList()\n{\n ListView * pList = static_cast<ListView *>(GetControl(IDC_LISTVIEW));\n pList->UpdateList();\n pList->RemoveScrollEventListener(*this);\n pList->ScrollToItem(0);\n pList->AddScrollEventListener(*this);\n}\n\nvoid SearchForm::Search(String const & val)\n{\n search::SearchParams params;\n params.m_callback = bind(&SearchForm::OnSearchResultsReceived, this, _1);\n params.m_query = FromTizenString(val);\n\n Tizen::Locales::LanguageCode language;\n if (m_searchBar->GetCurrentLanguage(language) == E_SUCCESS)\n params.SetInputLanguage(CodeFromISO369_2to_1(GetLanguageCode(language)));\n double lat, lon;\n GetFramework()->GetCurrentPosition(lat, lon);\n params.SetPosition(lat, lon);\n\n GetFramework()->Search(params);\n}\n\nString SearchForm::GetSearchString() const\n{\n return m_searchBar->GetText();\n}\n\nbool SearchForm::IsShowCategories() const\n{\n return GetSearchString().IsEmpty();\n}\n\nvoid SearchForm::OnKeypadActionPerformed (Tizen::Ui::Control & source, Tizen::Ui::KeypadAction keypadAction)\n{\n if (keypadAction == KEYPAD_ACTION_SEARCH)\n {\n search::SearchParams params;\n params.m_query = FromTizenString(GetSearchString());\n Tizen::Locales::LanguageCode language;\n if (m_searchBar->GetCurrentLanguage(language) == E_SUCCESS)\n params.SetInputLanguage(CodeFromISO369_2to_1(GetLanguageCode(language)));\n double lat, lon;\n GetFramework()->GetCurrentPosition(lat, lon);\n params.SetPosition(lat, lon);\n\n GetFramework()->StartInteractiveSearch(params);\n ArrayList * pList = new ArrayList;\n pList->Construct();\n pList->Add(new String(GetSearchString()));\n SceneManager * pSceneManager = SceneManager::GetInstance();\n pSceneManager->GoBackward(BackwardSceneTransition(SCENE_TRANSITION_ANIMATION_TYPE_RIGHT), pList);\n }\n}\n\nvoid SearchForm::OnSceneActivatedN(const Tizen::Ui::Scenes::SceneId& previousSceneId,\n const Tizen::Ui::Scenes::SceneId& currentSceneId, Tizen::Base::Collection::IList* pArgs)\n{\n if (pArgs != null)\n {\n \/\/ Come from Main page in resume mode\n if (pArgs->GetCount() == 1)\n {\n String * pSearchText = dynamic_cast<String *>(pArgs->GetAt(0));\n m_searchBar->SetText(*pSearchText);\n Search(GetSearchString());\n }\n pArgs->RemoveAll(true);\n delete pArgs;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005 Tommi Maekitalo\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <tntdb\/postgresql\/impl\/connection.h>\n#include <tntdb\/postgresql\/impl\/result.h>\n#include <tntdb\/postgresql\/impl\/statement.h>\n#include <tntdb\/postgresql\/error.h>\n#include <tntdb\/result.h>\n#include <tntdb\/statement.h>\n#include <cxxtools\/log.h>\n#include <new>\n#include <sstream>\n\nlog_define(\"tntdb.postgresql.connection\")\n\nnamespace tntdb\n{\n namespace postgresql\n {\n Connection::Connection(const char* conninfo)\n : transactionActive(0)\n {\n log_debug(\"PQconnectdb(\\\"\" << conninfo << \"\\\")\");\n\n conn = PQconnectdb(conninfo);\n if (conn == 0)\n throw std::bad_alloc();\n\n if (PQstatus(conn) == CONNECTION_BAD )\n throw PgConnError(\"PQconnectdb\", conn);\n }\n\n Connection::~Connection()\n {\n if (conn)\n {\n clearStatementCache();\n\n log_debug(\"PQfinish(\" << conn << \")\");\n PQfinish(conn);\n }\n }\n\n void Connection::beginTransaction()\n {\n if (transactionActive == 0)\n execute(\"BEGIN\");\n ++transactionActive;\n }\n\n void Connection::commitTransaction()\n {\n if (transactionActive == 0 || --transactionActive == 0)\n execute(\"COMMIT\");\n }\n\n void Connection::rollbackTransaction()\n {\n if (transactionActive == 0 || --transactionActive == 0)\n execute(\"ROLLBACK\");\n }\n\n Connection::size_type Connection::execute(const std::string& query)\n {\n log_debug(\"execute(\\\"\" << query << \"\\\")\");\n\n log_debug(\"PQexec(\" << conn << \", \\\"\" << query << \"\\\")\");\n PGresult* result = PQexec(conn, query.c_str());\n if (isError(result))\n {\n log_error(PQresultErrorMessage(result));\n throw PgSqlError(query, \"PQexec\", result, true);\n }\n\n std::istringstream tuples(PQcmdTuples(result));\n Connection::size_type ret = 0;\n tuples >> ret;\n\n log_debug(\"PQclear(\" << result << ')');\n PQclear(result);\n\n return ret;\n }\n\n tntdb::Result Connection::select(const std::string& query)\n {\n log_debug(\"select(\\\"\" << query << \"\\\")\");\n\n log_debug(\"PQexec(\" << conn << \", \\\"\" << query << \"\\\")\");\n PGresult* result = PQexec(conn, query.c_str());\n if (isError(result))\n {\n log_error(PQresultErrorMessage(result));\n throw PgSqlError(query, \"PQexec\", result, true);\n }\n\n return tntdb::Result(new Result(tntdb::Connection(this), result));\n }\n\n Row Connection::selectRow(const std::string& query)\n {\n log_debug(\"selectRow(\\\"\" << query << \"\\\")\");\n tntdb::Result result = select(query);\n if (result.empty())\n throw NotFound();\n\n return result.getRow(0);\n }\n\n Value Connection::selectValue(const std::string& query)\n {\n log_debug(\"selectValue(\\\"\" << query << \"\\\")\");\n Row t = selectRow(query);\n if (t.empty())\n throw NotFound();\n\n return t.getValue(0);\n }\n\n tntdb::Statement Connection::prepare(const std::string& query)\n {\n log_debug(\"prepare(\\\"\" << query << \"\\\")\");\n return tntdb::Statement(new Statement(this, query));\n }\n\n bool Connection::ping()\n {\n log_debug(\"ping()\");\n try\n {\n select(\"select 1\");\n return true;\n }\n catch (const PgError&)\n {\n return false;\n }\n }\n\n long Connection::lastInsertId(const std::string& name)\n {\n if (!currvalStmt)\n currvalStmt = prepare(\"select currval(:name)\");\n\n long ret;\n currvalStmt.set(\"name\", name)\n .selectValue()\n .get(ret);\n\n return ret;\n }\n\n }\n}\n<commit_msg>fix warning in postgresql driver about failed deallocation of statement on close connection when lastInserId was used<commit_after>\/*\n * Copyright (C) 2005 Tommi Maekitalo\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <tntdb\/postgresql\/impl\/connection.h>\n#include <tntdb\/postgresql\/impl\/result.h>\n#include <tntdb\/postgresql\/impl\/statement.h>\n#include <tntdb\/postgresql\/error.h>\n#include <tntdb\/result.h>\n#include <tntdb\/statement.h>\n#include <cxxtools\/log.h>\n#include <new>\n#include <sstream>\n\nlog_define(\"tntdb.postgresql.connection\")\n\nnamespace tntdb\n{\n namespace postgresql\n {\n Connection::Connection(const char* conninfo)\n : transactionActive(0)\n {\n log_debug(\"PQconnectdb(\\\"\" << conninfo << \"\\\")\");\n\n conn = PQconnectdb(conninfo);\n if (conn == 0)\n throw std::bad_alloc();\n\n if (PQstatus(conn) == CONNECTION_BAD )\n throw PgConnError(\"PQconnectdb\", conn);\n }\n\n Connection::~Connection()\n {\n if (conn)\n {\n clearStatementCache();\n currvalStmt = tntdb::Statement();\n\n log_debug(\"PQfinish(\" << conn << \")\");\n PQfinish(conn);\n }\n }\n\n void Connection::beginTransaction()\n {\n if (transactionActive == 0)\n execute(\"BEGIN\");\n ++transactionActive;\n }\n\n void Connection::commitTransaction()\n {\n if (transactionActive == 0 || --transactionActive == 0)\n execute(\"COMMIT\");\n }\n\n void Connection::rollbackTransaction()\n {\n if (transactionActive == 0 || --transactionActive == 0)\n execute(\"ROLLBACK\");\n }\n\n Connection::size_type Connection::execute(const std::string& query)\n {\n log_debug(\"execute(\\\"\" << query << \"\\\")\");\n\n log_debug(\"PQexec(\" << conn << \", \\\"\" << query << \"\\\")\");\n PGresult* result = PQexec(conn, query.c_str());\n if (isError(result))\n {\n log_error(PQresultErrorMessage(result));\n throw PgSqlError(query, \"PQexec\", result, true);\n }\n\n std::istringstream tuples(PQcmdTuples(result));\n Connection::size_type ret = 0;\n tuples >> ret;\n\n log_debug(\"PQclear(\" << result << ')');\n PQclear(result);\n\n return ret;\n }\n\n tntdb::Result Connection::select(const std::string& query)\n {\n log_debug(\"select(\\\"\" << query << \"\\\")\");\n\n log_debug(\"PQexec(\" << conn << \", \\\"\" << query << \"\\\")\");\n PGresult* result = PQexec(conn, query.c_str());\n if (isError(result))\n {\n log_error(PQresultErrorMessage(result));\n throw PgSqlError(query, \"PQexec\", result, true);\n }\n\n return tntdb::Result(new Result(tntdb::Connection(this), result));\n }\n\n Row Connection::selectRow(const std::string& query)\n {\n log_debug(\"selectRow(\\\"\" << query << \"\\\")\");\n tntdb::Result result = select(query);\n if (result.empty())\n throw NotFound();\n\n return result.getRow(0);\n }\n\n Value Connection::selectValue(const std::string& query)\n {\n log_debug(\"selectValue(\\\"\" << query << \"\\\")\");\n Row t = selectRow(query);\n if (t.empty())\n throw NotFound();\n\n return t.getValue(0);\n }\n\n tntdb::Statement Connection::prepare(const std::string& query)\n {\n log_debug(\"prepare(\\\"\" << query << \"\\\")\");\n return tntdb::Statement(new Statement(this, query));\n }\n\n bool Connection::ping()\n {\n log_debug(\"ping()\");\n try\n {\n select(\"select 1\");\n return true;\n }\n catch (const PgError&)\n {\n return false;\n }\n }\n\n long Connection::lastInsertId(const std::string& name)\n {\n if (!currvalStmt)\n currvalStmt = prepare(\"select currval(:name)\");\n\n long ret;\n currvalStmt.set(\"name\", name)\n .selectValue()\n .get(ret);\n\n return ret;\n }\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* openssl.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n#include \"tnt\/openssl.h\"\n#include <cxxtools\/thread.h>\n#include <openssl\/err.h>\n#include <cxxtools\/log.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/poll.h>\n\nlog_define(\"tntnet.ssl\")\n\nnamespace tnt\n{\n static void checkSslError()\n {\n log_debug(\"ERR_get_error\");\n unsigned long code = ERR_get_error();\n if (code != 0)\n {\n char buffer[120];\n log_debug(\"ERR_error_string\");\n if (ERR_error_string(code, buffer))\n {\n log_debug(\"SSL-Error \" << code << \": \\\"\" << buffer << '\"');\n throw OpensslException(buffer, code);\n }\n else\n {\n log_debug(\"unknown SSL-Error \" << code);\n throw OpensslException(\"unknown SSL-Error\", code);\n }\n }\n }\n\n static cxxtools::Mutex *openssl_mutex;\n\n static unsigned long pthreads_thread_id()\n {\n return (unsigned long)pthread_self();\n }\n\n static void pthreads_locking_callback(int mode, int n, const char *file,\n int line)\n {\n \/*\n log_debug(\"pthreads_locking_callback \" << CRYPTO_thread_id()\n << \" n=\" << n\n << \" mode=\" << ((mode & CRYPTO_LOCK) ? 'l' : 'u')\n << ' ' << file << ':' << line); *\/\n\n if (mode & CRYPTO_LOCK)\n openssl_mutex[n].lock();\n else\n openssl_mutex[n].unlock();\n }\n\n static void thread_setup(void)\n {\n openssl_mutex = new cxxtools::Mutex[CRYPTO_num_locks()];\n\n CRYPTO_set_id_callback(pthreads_thread_id);\n CRYPTO_set_locking_callback(pthreads_locking_callback);\n }\n\n static cxxtools::Mutex mutex;\n static void openssl_init()\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n cxxtools::MutexLock lock(mutex);\n if (!initialized)\n {\n log_debug(\"SSL_load_error_strings\");\n SSL_load_error_strings();\n log_debug(\"SSL_library_init\");\n SSL_library_init();\n\n checkSslError();\n thread_setup();\n initialized = true;\n }\n }\n }\n\n void OpensslServer::installCertificates(const char* certificateFile, const char* privateKeyFile)\n {\n log_debug(\"use certificate file \" << certificateFile);\n if (SSL_CTX_use_certificate_file(ctx, certificateFile, SSL_FILETYPE_PEM) <= 0)\n checkSslError();\n\n log_debug(\"use private key file \" << privateKeyFile);\n if (SSL_CTX_use_PrivateKey_file(ctx, privateKeyFile, SSL_FILETYPE_PEM) <= 0)\n checkSslError();\n\n log_debug(\"check private key\");\n if (!SSL_CTX_check_private_key(ctx))\n throw OpensslException(\"private key does not match the certificate public key\", 0);\n\n log_debug(\"private key ok\");\n }\n\n OpensslServer::OpensslServer(const char* certificateFile)\n {\n openssl_init();\n\n log_debug(\"SSL_CTX_new(SSLv23_server_method())\");\n ctx = SSL_CTX_new(SSLv23_server_method());\n checkSslError();\n\n installCertificates(certificateFile, certificateFile);\n }\n\n OpensslServer::OpensslServer(const char* certificateFile, const char* privateKeyFile)\n {\n openssl_init();\n\n log_debug(\"SSL_CTX_new(SSLv23_server_method())\");\n ctx = SSL_CTX_new(SSLv23_server_method());\n checkSslError();\n\n installCertificates(certificateFile, privateKeyFile);\n }\n\n OpensslServer::~OpensslServer()\n {\n if (ctx)\n {\n log_debug(\"SSL_CTX_free(ctx)\");\n SSL_CTX_free(ctx);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ OpensslStream\n \/\/\n OpensslStream::OpensslStream()\n : ssl(0)\n {\n openssl_init();\n }\n\n OpensslStream::OpensslStream(const OpensslServer& server)\n : ssl(0)\n {\n openssl_init();\n accept(server);\n }\n\n OpensslStream::~OpensslStream()\n {\n if (ssl)\n {\n try\n {\n shutdown();\n }\n catch (const std::exception& e)\n {\n log_debug(\"error closing ssl-connection: \" << e.what());\n }\n\n log_debug(\"SSL_free(\" << ssl << ')');\n SSL_free(ssl);\n }\n }\n\n void OpensslStream::accept(const OpensslServer& server)\n {\n log_debug(\"accept\");\n Stream::accept(server);\n\n log_debug(\"tcp-connection established - build ssltunnel\");\n\n log_debug(\"SSL_new(\" << server.getSslContext() << ')');\n ssl = SSL_new( server.getSslContext() );\n checkSslError();\n\n log_debug(\"SSL_set_fd(\" << ssl << \", \" << getFd() << ')');\n SSL_set_fd(ssl, getFd());\n\n log_debug(\"SSL_set_accept_state(\" << ssl << ')');\n SSL_set_accept_state(ssl);\n }\n\n int OpensslStream::sslRead(char* buffer, int bufsize) const\n {\n \/\/ I had crashes without this (and the lock in sslWrite) lock:\n \/\/ openssl should be thread-safe, with the installed callbacks, but I did not\n \/\/ get it working\n cxxtools::MutexLock lock(mutex);\n\n log_debug(\"read\");\n\n int n;\n int err;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking\n do\n {\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << \") (blocking)\");\n n = ::SSL_read(ssl, buffer, bufsize);\n } while (n <= 0 &&\n ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n checkSslError();\n }\n else\n {\n \/\/ non-blocking\/with timeout\n\n \/\/ try read\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << ')');\n n = ::SSL_read(ssl, buffer, bufsize);\n log_debug(\"ssl-read => \" << n);\n\n if (n > 0)\n return n;\n\n log_debug(\"SSL_get_error(\" << ssl << \", \" << n << ')');\n if ((err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE)\n checkSslError();\n\n if (getTimeout() == 0)\n {\n log_debug(\"read-timeout\");\n throw cxxtools::net::Timeout();\n }\n\n \/\/ no read, timeout > 0 - poll\n do\n {\n poll(SSL_get_error(ssl, n) == SSL_ERROR_WANT_WRITE\n ? POLLIN|POLLOUT : POLLIN);\n\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << ')');\n n = ::SSL_read(ssl, buffer, bufsize);\n log_debug(\"SSL_read returns \" << n);\n checkSslError();\n\n } while (n < 0\n && ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE\n || err == SSL_ERROR_SYSCALL && errno == EAGAIN));\n }\n return n;\n }\n\n int OpensslStream::sslWrite(const char* buffer, int bufsize) const\n {\n \/\/ I had crashes without this (and the lock in sslRead) lock:\n \/\/ openssl should be thread-safe, with the installed callbacks, but I did not\n \/\/ get it working\n cxxtools::MutexLock lock(mutex);\n\n int n = 0;\n int s = bufsize;\n\n while (true)\n {\n log_debug(\"SSL_write(\" << ssl << \", buffer, \" << s << ')');\n n = SSL_write(ssl, buffer, s);\n checkSslError();\n\n int err;\n if (n > 0)\n {\n buffer += n;\n s -= n;\n }\n else if (n < 0\n && (err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE\n && (err != SSL_ERROR_SYSCALL || errno != EAGAIN))\n {\n log_debug(\"error \" << err << \" occured in SSL_write; n=\" << n);\n throw OpensslException(\"error from TLS\/SSL I\/O operation\", err);\n }\n\n if (s <= 0)\n break;\n\n poll(SSL_get_error(ssl, n) == SSL_ERROR_WANT_WRITE\n ? POLLIN|POLLOUT : POLLIN);\n }\n\n log_debug(\"OpensslStream::sslWrite returns \" << bufsize);\n return bufsize;\n }\n\n void OpensslStream::shutdown() const\n {\n cxxtools::MutexLock lock(mutex);\n\n int n, err;\n if (getTimeout() < 0)\n {\n \/\/ blocking\n do\n {\n log_debug(\"shutdown unbuffered\");\n n = ::SSL_shutdown(ssl);\n } while (n <= 0 &&\n ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n checkSslError();\n }\n else\n {\n \/\/ non-blocking\/with timeout\n\n \/\/ try read\n log_debug(\"SSL_shutdown(\" << ssl << ')');\n n = ::SSL_shutdown(ssl);\n log_debug(\"ssl-shutdown => \" << n);\n\n log_debug(\"SSL_get_error(\" << ssl << \", \" << n << ')');\n if ((err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE)\n checkSslError();\n\n if (getTimeout() == 0)\n {\n log_debug(\"shutdown-timeout\");\n throw cxxtools::net::Timeout();\n }\n\n do\n {\n log_debug(\"poll\");\n poll(err == SSL_ERROR_WANT_WRITE ? POLLIN|POLLOUT : POLLIN);\n\n log_debug(\"SSL_shutdown(\" << ssl << ')');\n n = ::SSL_shutdown(ssl);\n log_debug(\"SSL_shutdown returns \" << n);\n\n checkSslError();\n\n } while (n <= 0\n && ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ openssl_streambuf\n \/\/\n openssl_streambuf::openssl_streambuf(OpensslStream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_buffer(new char_type[bufsize]),\n m_bufsize(bufsize)\n {\n setTimeout(timeout);\n }\n\n openssl_streambuf::int_type openssl_streambuf::overflow(openssl_streambuf::int_type c)\n {\n try\n {\n if (pptr() != pbase())\n {\n int n = m_stream.sslWrite(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n catch (const std::exception& e)\n {\n log_error(\"error int openssl_streambuf::overflow: \" << e.what());\n return traits_type::eof();\n }\n }\n\n openssl_streambuf::int_type openssl_streambuf::underflow()\n {\n int n = m_stream.sslRead(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n\n int openssl_streambuf::sync()\n {\n try\n {\n if (pptr() != pbase())\n {\n int n = m_stream.sslWrite(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n return 0;\n }\n catch (const std::exception& e)\n {\n log_error(\"error in openssl_streambuf::sync(): \" << e.what());\n return traits_type::eof();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ openssl_iostream\n \/\/\n}\n<commit_msg>another fix in error handling of openssl<commit_after>\/* openssl.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n#include \"tnt\/openssl.h\"\n#include <cxxtools\/thread.h>\n#include <openssl\/err.h>\n#include <cxxtools\/log.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/poll.h>\n\nlog_define(\"tntnet.ssl\")\n\nnamespace tnt\n{\n static void checkSslError()\n {\n log_debug(\"ERR_get_error\");\n unsigned long code = ERR_get_error();\n if (code != 0)\n {\n char buffer[120];\n log_debug(\"ERR_error_string\");\n if (ERR_error_string(code, buffer))\n {\n log_debug(\"SSL-Error \" << code << \": \\\"\" << buffer << '\"');\n throw OpensslException(buffer, code);\n }\n else\n {\n log_debug(\"unknown SSL-Error \" << code);\n throw OpensslException(\"unknown SSL-Error\", code);\n }\n }\n }\n\n static cxxtools::Mutex *openssl_mutex;\n\n static unsigned long pthreads_thread_id()\n {\n return (unsigned long)pthread_self();\n }\n\n static void pthreads_locking_callback(int mode, int n, const char *file,\n int line)\n {\n \/*\n log_debug(\"pthreads_locking_callback \" << CRYPTO_thread_id()\n << \" n=\" << n\n << \" mode=\" << ((mode & CRYPTO_LOCK) ? 'l' : 'u')\n << ' ' << file << ':' << line); *\/\n\n if (mode & CRYPTO_LOCK)\n openssl_mutex[n].lock();\n else\n openssl_mutex[n].unlock();\n }\n\n static void thread_setup(void)\n {\n openssl_mutex = new cxxtools::Mutex[CRYPTO_num_locks()];\n\n CRYPTO_set_id_callback(pthreads_thread_id);\n CRYPTO_set_locking_callback(pthreads_locking_callback);\n }\n\n static cxxtools::Mutex mutex;\n static void openssl_init()\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n cxxtools::MutexLock lock(mutex);\n if (!initialized)\n {\n log_debug(\"SSL_load_error_strings\");\n SSL_load_error_strings();\n log_debug(\"SSL_library_init\");\n SSL_library_init();\n\n checkSslError();\n thread_setup();\n initialized = true;\n }\n }\n }\n\n void OpensslServer::installCertificates(const char* certificateFile, const char* privateKeyFile)\n {\n log_debug(\"use certificate file \" << certificateFile);\n if (SSL_CTX_use_certificate_file(ctx, certificateFile, SSL_FILETYPE_PEM) <= 0)\n checkSslError();\n\n log_debug(\"use private key file \" << privateKeyFile);\n if (SSL_CTX_use_PrivateKey_file(ctx, privateKeyFile, SSL_FILETYPE_PEM) <= 0)\n checkSslError();\n\n log_debug(\"check private key\");\n if (!SSL_CTX_check_private_key(ctx))\n throw OpensslException(\"private key does not match the certificate public key\", 0);\n\n log_debug(\"private key ok\");\n }\n\n OpensslServer::OpensslServer(const char* certificateFile)\n {\n openssl_init();\n\n log_debug(\"SSL_CTX_new(SSLv23_server_method())\");\n ctx = SSL_CTX_new(SSLv23_server_method());\n checkSslError();\n\n installCertificates(certificateFile, certificateFile);\n }\n\n OpensslServer::OpensslServer(const char* certificateFile, const char* privateKeyFile)\n {\n openssl_init();\n\n log_debug(\"SSL_CTX_new(SSLv23_server_method())\");\n ctx = SSL_CTX_new(SSLv23_server_method());\n checkSslError();\n\n installCertificates(certificateFile, privateKeyFile);\n }\n\n OpensslServer::~OpensslServer()\n {\n if (ctx)\n {\n log_debug(\"SSL_CTX_free(ctx)\");\n SSL_CTX_free(ctx);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ OpensslStream\n \/\/\n OpensslStream::OpensslStream()\n : ssl(0)\n {\n openssl_init();\n }\n\n OpensslStream::OpensslStream(const OpensslServer& server)\n : ssl(0)\n {\n openssl_init();\n accept(server);\n }\n\n OpensslStream::~OpensslStream()\n {\n if (ssl)\n {\n try\n {\n shutdown();\n }\n catch (const std::exception& e)\n {\n log_debug(\"error closing ssl-connection: \" << e.what());\n }\n\n log_debug(\"SSL_free(\" << ssl << ')');\n SSL_free(ssl);\n }\n }\n\n void OpensslStream::accept(const OpensslServer& server)\n {\n log_debug(\"accept\");\n Stream::accept(server);\n\n log_debug(\"tcp-connection established - build ssltunnel\");\n\n log_debug(\"SSL_new(\" << server.getSslContext() << ')');\n ssl = SSL_new( server.getSslContext() );\n checkSslError();\n\n log_debug(\"SSL_set_fd(\" << ssl << \", \" << getFd() << ')');\n SSL_set_fd(ssl, getFd());\n\n log_debug(\"SSL_set_accept_state(\" << ssl << ')');\n SSL_set_accept_state(ssl);\n }\n\n int OpensslStream::sslRead(char* buffer, int bufsize) const\n {\n \/\/ I had crashes without this (and the lock in sslWrite) lock:\n \/\/ openssl should be thread-safe, with the installed callbacks, but I did not\n \/\/ get it working\n cxxtools::MutexLock lock(mutex);\n\n log_debug(\"read\");\n\n int n;\n int err;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking\n do\n {\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << \") (blocking)\");\n n = ::SSL_read(ssl, buffer, bufsize);\n } while (n <= 0 &&\n ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n checkSslError();\n }\n else\n {\n \/\/ non-blocking\/with timeout\n\n \/\/ try read\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << ')');\n n = ::SSL_read(ssl, buffer, bufsize);\n log_debug(\"ssl-read => \" << n);\n\n if (n > 0)\n return n;\n\n log_debug(\"SSL_get_error(\" << ssl << \", \" << n << ')');\n if ((err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE)\n checkSslError();\n\n if (getTimeout() == 0)\n {\n log_debug(\"read-timeout\");\n throw cxxtools::net::Timeout();\n }\n\n \/\/ no read, timeout > 0 - poll\n do\n {\n poll(SSL_get_error(ssl, n) == SSL_ERROR_WANT_WRITE\n ? POLLIN|POLLOUT : POLLIN);\n\n log_debug(\"SSL_read(\" << ssl << \", buffer, \" << bufsize << ')');\n n = ::SSL_read(ssl, buffer, bufsize);\n log_debug(\"SSL_read returns \" << n);\n checkSslError();\n\n } while (n < 0\n && ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE\n || err == SSL_ERROR_SYSCALL && errno == EAGAIN));\n }\n return n;\n }\n\n int OpensslStream::sslWrite(const char* buffer, int bufsize) const\n {\n \/\/ I had crashes without this (and the lock in sslRead) lock:\n \/\/ openssl should be thread-safe, with the installed callbacks, but I did not\n \/\/ get it working\n cxxtools::MutexLock lock(mutex);\n\n int n = 0;\n int s = bufsize;\n\n while (true)\n {\n log_debug(\"SSL_write(\" << ssl << \", buffer, \" << s << ')');\n n = SSL_write(ssl, buffer, s);\n checkSslError();\n\n int err;\n if (n > 0)\n {\n buffer += n;\n s -= n;\n }\n else if (n < 0\n && (err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE\n && (err != SSL_ERROR_SYSCALL || errno != EAGAIN))\n {\n log_debug(\"error \" << err << \" occured in SSL_write; n=\" << n);\n throw OpensslException(\"error from TLS\/SSL I\/O operation\", err);\n }\n\n if (s <= 0)\n break;\n\n poll(SSL_get_error(ssl, n) == SSL_ERROR_WANT_READ\n ? POLLIN : POLLIN|POLLOUT);\n }\n\n log_debug(\"OpensslStream::sslWrite returns \" << bufsize);\n return bufsize;\n }\n\n void OpensslStream::shutdown() const\n {\n cxxtools::MutexLock lock(mutex);\n\n int n, err;\n if (getTimeout() < 0)\n {\n \/\/ blocking\n do\n {\n log_debug(\"shutdown unbuffered\");\n n = ::SSL_shutdown(ssl);\n } while (n <= 0 &&\n ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n checkSslError();\n }\n else\n {\n \/\/ non-blocking\/with timeout\n\n \/\/ try read\n log_debug(\"SSL_shutdown(\" << ssl << ')');\n n = ::SSL_shutdown(ssl);\n log_debug(\"ssl-shutdown => \" << n);\n\n log_debug(\"SSL_get_error(\" << ssl << \", \" << n << ')');\n if ((err = SSL_get_error(ssl, n)) != SSL_ERROR_WANT_READ\n && err != SSL_ERROR_WANT_WRITE)\n checkSslError();\n\n if (getTimeout() == 0)\n {\n log_debug(\"shutdown-timeout\");\n throw cxxtools::net::Timeout();\n }\n\n do\n {\n log_debug(\"poll\");\n poll(err == SSL_ERROR_WANT_WRITE ? POLLIN|POLLOUT : POLLIN);\n\n log_debug(\"SSL_shutdown(\" << ssl << ')');\n n = ::SSL_shutdown(ssl);\n log_debug(\"SSL_shutdown returns \" << n);\n\n checkSslError();\n\n } while (n <= 0\n && ((err = SSL_get_error(ssl, n)) == SSL_ERROR_WANT_READ\n || err == SSL_ERROR_WANT_WRITE));\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ openssl_streambuf\n \/\/\n openssl_streambuf::openssl_streambuf(OpensslStream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_buffer(new char_type[bufsize]),\n m_bufsize(bufsize)\n {\n setTimeout(timeout);\n }\n\n openssl_streambuf::int_type openssl_streambuf::overflow(openssl_streambuf::int_type c)\n {\n try\n {\n if (pptr() != pbase())\n {\n int n = m_stream.sslWrite(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n catch (const std::exception& e)\n {\n log_error(\"error int openssl_streambuf::overflow: \" << e.what());\n return traits_type::eof();\n }\n }\n\n openssl_streambuf::int_type openssl_streambuf::underflow()\n {\n int n = m_stream.sslRead(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n\n int openssl_streambuf::sync()\n {\n try\n {\n if (pptr() != pbase())\n {\n int n = m_stream.sslWrite(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n return 0;\n }\n catch (const std::exception& e)\n {\n log_error(\"error in openssl_streambuf::sync(): \" << e.what());\n return traits_type::eof();\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ openssl_iostream\n \/\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdint>\n\n#include <algorithm>\n#include <chrono>\n#include <stdexcept>\n#include <sstream>\n\n#include \"connection.hpp\"\n#include \"message.hpp\"\n#include \"message_builder.hpp\"\n#include \"state.hpp\"\n#include \"use.hpp\"\n#include <deepstream\/core\/buffer.hpp>\n#include <deepstream\/core\/client.hpp>\n#include <deepstream\/core\/error_handler.hpp>\n#include <deepstream\/core\/event.hpp>\n#include <deepstream\/core\/presence.hpp>\n\n#include <cassert>\n\n#ifndef NDEBUG\n#include <iostream>\n#define DEBUG_MSG(str) do { std::cout << \"\\033[1,31m#\\033[0m \" << str << std::endl; } while( false )\n#else\n#define DEBUG_MSG(str) do { } while ( false )\n#endif\n\nnamespace deepstream {\n\n Connection::Connection(const std::string &uri, WSHandler &ws_handler,\n ErrorHandler &error_handler, Event &event, Presence &presence)\n : state_(ConnectionState::CLOSED)\n , error_handler_(error_handler)\n , ws_handler_(ws_handler)\n , p_login_callback_(nullptr)\n , p_auth_params_(nullptr)\n , event_(event)\n , presence_(presence)\n {\n assert(ws_handler.state() == WSState::CLOSED);\n\n ws_handler.URI(uri);\n\n using namespace std::placeholders;\n ws_handler.on_message(std::bind(&Connection::on_message, this, _1));\n ws_handler.on_error(std::bind(&Connection::on_error, this, _1));\n ws_handler.on_open(std::bind(&Connection::on_open, this));\n ws_handler.on_close(std::bind(&Connection::on_close, this));\n\n ws_handler.open();\n }\n\n void Connection::login(const std::string& auth_params, const Client::LoginCallback &callback)\n {\n if (state_ == ConnectionState::OPEN) {\n return;\n }\n\n p_login_callback_ = std::unique_ptr<Client::LoginCallback>(new Client::LoginCallback(callback));\n\n p_auth_params_ = std::unique_ptr<std::string>(new std::string(auth_params));\n\n if (state_ == ConnectionState::AWAIT_AUTHENTICATION) {\n send_authentication_request();\n }\n }\n\n void Connection::send_authentication_request()\n {\n assert(state_ == ConnectionState::AWAIT_AUTHENTICATION);\n assert(p_auth_params_);\n\n MessageBuilder authentication_request(Topic::AUTH, Action::REQUEST);\n authentication_request.add_argument(*p_auth_params_);\n\n send(authentication_request);\n }\n\n void Connection::close()\n {\n deliberate_close_ = true;\n ws_handler_.close();\n }\n\n ConnectionState Connection::state()\n {\n return state_;\n }\n\n void Connection::state(const ConnectionState state)\n {\n if (state != state_) {\n state_ = state;\n on_connection_state_change_();\n }\n }\n\n void Connection::on_connection_state_change_()\n {\n DEBUG_MSG(\"Connection state change: \" << state_);\n event_.on_connection_state_change_(state_);\n \/\/presence_.on_connection_state_change_(state_);\n }\n\n void Connection::on_message(const Buffer &&raw_message)\n {\n Buffer buffer(raw_message.size() + 2, 0);\n std::copy(raw_message.cbegin(), raw_message.cend(), buffer.begin());\n\n auto parser_result = parser::execute(buffer.data(), buffer.size());\n const parser::ErrorList& errors = parser_result.second;\n\n for (auto it = errors.cbegin(); it != errors.cend(); ++it) {\n const parser::Error &error = *it;\n std::stringstream error_message;\n error_message << \"parser error: \" << error << \" \\\"\"\n << Message::to_human_readable(raw_message) << \"\\\"\";\n error_handler_.on_error(error_message.str());\n }\n\n parser::MessageList parsed_messages(std::move(parser_result.first));\n\n for (auto it = parsed_messages.cbegin(); it != parsed_messages.cend(); ++it) {\n const Message &parsed_message = *it;\n DEBUG_MSG(\"Message received: \" << parsed_message.header());\n\n switch (parsed_message.topic()) {\n case Topic::EVENT:\n event_.notify_(parsed_message);\n break;\n\n case Topic::PRESENCE:\n presence_.notify_(parsed_message);\n break;\n\n case Topic::CONNECTION:\n handle_connection_response(parsed_message);\n break;\n\n case Topic::AUTH:\n handle_authentication_response(parsed_message);\n break;\n\n default:\n {\n std::stringstream error_message;\n error_message << \"unsolicited message: \" << parsed_message.header();\n error_handler_.on_error(error_message.str());\n assert(0);\n }\n }\n\n }\n }\n\n void Connection::handle_connection_response(const Message &message)\n {\n ConnectionState new_state = transition_incoming(state_, message);\n\n if (new_state == ConnectionState::ERROR) {\n std::stringstream error_message;\n error_message << \"connection error state reached, previous state: \" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n\n state(new_state);\n switch(message.action()) {\n case Action::PING:\n {\n const MessageBuilder pong(Topic::CONNECTION, Action::PONG);\n send(pong);\n } break;\n case Action::CHALLENGE:\n {\n MessageBuilder challenge_response(Topic::CONNECTION, Action::CHALLENGE_RESPONSE);\n challenge_response.add_argument(ws_handler_.URI());\n send(challenge_response);\n } break;\n case Action::CHALLENGE_RESPONSE:\n {\n if (p_auth_params_) {\n send_authentication_request();\n }\n } break;\n case Action::REDIRECT:\n {\n if (message.num_arguments() < 1) {\n error_handler_.on_error(\"No URI given in connection redirect message\");\n break;\n }\n const Buffer &uri_buff(message[0]);\n const std::string uri(uri_buff.cbegin(), uri_buff.cend());\n DEBUG_MSG(\"redirecting to \\\"\" << uri << \"\\\"\");\n ws_handler_.URI(uri);\n } break;\n default:\n {\n std::stringstream error_message;\n error_message << \"connection message with unknown action \" << state_\n << std::endl << '\\t' << message.header();\n error_handler_.on_error(error_message.str());\n }\n }\n }\n\n void Connection::handle_authentication_response(const Message &message)\n {\n switch(message.action()) {\n case Action::ERROR_TOO_MANY_AUTH_ATTEMPTS:\n {\n error_handler_.on_error(\"too many authentication attempts\");\n close();\n } break;\n case Action::ERROR_INVALID_AUTH_DATA:\n {\n error_handler_.on_error(\"invalid auth data\");\n close();\n } break;\n case Action::ERROR_INVALID_AUTH_MSG:\n {\n error_handler_.on_error(\"invalid auth message\");\n close();\n } break;\n case Action::REQUEST:\n {\n assert(message.is_ack());\n \/\/TODO: flush message buffer\n if (p_login_callback_) {\n const auto login_callback = *p_login_callback_;\n if (message.num_arguments() < 1) {\n login_callback(std::unique_ptr<Buffer>(nullptr));\n } else {\n login_callback(std::unique_ptr<Buffer>(new Buffer(message[0])));\n }\n }\n } break;\n default:\n {\n std::stringstream error_message;\n error_message << \"authentication message with unknown action\" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n }\n\n ConnectionState new_state = transition_incoming(state_, message);\n\n if (new_state == ConnectionState::ERROR) {\n std::stringstream error_message;\n error_message << \"connection error state reached, previous state: \" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n\n state(new_state);\n }\n\n void Connection::on_error(const std::string &&error)\n {\n DEBUG_MSG(\"Websocket error: \" << error);\n state(ConnectionState::RECONNECTING);\n ws_handler_.reconnect();\n }\n\n void Connection::on_open()\n {\n state(ConnectionState::AWAIT_CONNECTION);\n }\n\n void Connection::on_close()\n {\n if (deliberate_close_) {\n state(ConnectionState::CLOSED);\n return;\n }\n state(ConnectionState::RECONNECTING);\n ws_handler_.open();\n }\n\n bool Connection::send(const Message& message)\n {\n DEBUG_MSG(\"--> Sending message: \" << message.header());\n\n if (message.topic() == Topic::CONNECTION || message.topic() == Topic::AUTH) {\n ConnectionState new_state = transition_outgoing(state_, message);\n assert(new_state != ConnectionState::ERROR);\n\n if (new_state == ConnectionState::ERROR) {\n throw std::logic_error(\"Invalid client state transition\");\n }\n\n state(new_state);\n } else if (state_ != ConnectionState::OPEN) {\n return false;\n }\n\n return ws_handler_.send(message.to_binary());\n }\n\n ConnectionState transition_incoming(const ConnectionState state, const Message& message)\n {\n assert(state != ConnectionState::ERROR);\n assert(state != ConnectionState::CLOSED);\n\n const Topic topic = message.topic();\n const Action action = message.action();\n const bool is_ack = message.is_ack();\n\n const auto expected_num_args = Message::num_arguments(message.header());\n const std::size_t& num_args = message.num_arguments();\n\n use(expected_num_args);\n use(num_args);\n assert(num_args >= expected_num_args.first);\n assert(num_args <= expected_num_args.second);\n\n \/\/ deepstream ping\/pong (distinct from websocket heartbeats)\n if (topic == Topic::CONNECTION && action == Action::PING) {\n assert(!is_ack);\n\n return state;\n }\n\n \/\/ actual state transitions\n if (state == ConnectionState::AWAIT_CONNECTION && topic == Topic::CONNECTION\n && action == Action::CHALLENGE) {\n assert(!is_ack);\n\n return ConnectionState::CHALLENGING;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::CHALLENGE_RESPONSE) {\n assert(is_ack);\n return ConnectionState::AWAIT_AUTHENTICATION;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::REDIRECT) {\n assert(!is_ack);\n\n return ConnectionState::AWAIT_CONNECTION;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::REJECT) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::REQUEST) {\n assert(is_ack);\n return ConnectionState::OPEN;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_INVALID_AUTH_DATA) {\n assert(!is_ack);\n\n return ConnectionState::AWAIT_AUTHENTICATION;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_INVALID_AUTH_MSG) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::OPEN) {\n return state;\n }\n\n return ConnectionState::ERROR;\n }\n\n ConnectionState transition_outgoing(const ConnectionState state, const Message& message)\n {\n assert(state != ConnectionState::ERROR);\n assert(state != ConnectionState::CLOSED);\n\n const Topic topic = message.topic();\n const Action action = message.action();\n const bool is_ack = message.is_ack();\n\n const auto expected_num_args = Message::num_arguments(message.header());\n const std::size_t& num_args = message.num_arguments();\n\n use(expected_num_args);\n use(num_args);\n assert(num_args >= expected_num_args.first);\n assert(num_args <= expected_num_args.second);\n\n if (topic == Topic::CONNECTION && action == Action::PONG) {\n assert(!is_ack);\n\n return state;\n }\n\n if (state == ConnectionState::CHALLENGING && topic == Topic::CONNECTION\n && action == Action::CHALLENGE_RESPONSE) {\n assert(!is_ack);\n return ConnectionState::CHALLENGING_WAIT;\n }\n\n if (state == ConnectionState::AWAIT_AUTHENTICATION && topic == Topic::AUTH\n && action == Action::REQUEST) {\n assert(!is_ack);\n return ConnectionState::AUTHENTICATING;\n }\n\n return ConnectionState::ERROR;\n }\n}\n<commit_msg>fix: remove incorrect TODO comment<commit_after>\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdint>\n\n#include <algorithm>\n#include <chrono>\n#include <stdexcept>\n#include <sstream>\n\n#include \"connection.hpp\"\n#include \"message.hpp\"\n#include \"message_builder.hpp\"\n#include \"state.hpp\"\n#include \"use.hpp\"\n#include <deepstream\/core\/buffer.hpp>\n#include <deepstream\/core\/client.hpp>\n#include <deepstream\/core\/error_handler.hpp>\n#include <deepstream\/core\/event.hpp>\n#include <deepstream\/core\/presence.hpp>\n\n#include <cassert>\n\n#ifndef NDEBUG\n#include <iostream>\n#define DEBUG_MSG(str) do { std::cout << \"\\033[1,31m#\\033[0m \" << str << std::endl; } while( false )\n#else\n#define DEBUG_MSG(str) do { } while ( false )\n#endif\n\nnamespace deepstream {\n\n Connection::Connection(const std::string &uri, WSHandler &ws_handler,\n ErrorHandler &error_handler, Event &event, Presence &presence)\n : state_(ConnectionState::CLOSED)\n , error_handler_(error_handler)\n , ws_handler_(ws_handler)\n , p_login_callback_(nullptr)\n , p_auth_params_(nullptr)\n , event_(event)\n , presence_(presence)\n {\n assert(ws_handler.state() == WSState::CLOSED);\n\n ws_handler.URI(uri);\n\n using namespace std::placeholders;\n ws_handler.on_message(std::bind(&Connection::on_message, this, _1));\n ws_handler.on_error(std::bind(&Connection::on_error, this, _1));\n ws_handler.on_open(std::bind(&Connection::on_open, this));\n ws_handler.on_close(std::bind(&Connection::on_close, this));\n\n ws_handler.open();\n }\n\n void Connection::login(const std::string& auth_params, const Client::LoginCallback &callback)\n {\n if (state_ == ConnectionState::OPEN) {\n return;\n }\n\n p_login_callback_ = std::unique_ptr<Client::LoginCallback>(new Client::LoginCallback(callback));\n\n p_auth_params_ = std::unique_ptr<std::string>(new std::string(auth_params));\n\n if (state_ == ConnectionState::AWAIT_AUTHENTICATION) {\n send_authentication_request();\n }\n }\n\n void Connection::send_authentication_request()\n {\n assert(state_ == ConnectionState::AWAIT_AUTHENTICATION);\n assert(p_auth_params_);\n\n MessageBuilder authentication_request(Topic::AUTH, Action::REQUEST);\n authentication_request.add_argument(*p_auth_params_);\n\n send(authentication_request);\n }\n\n void Connection::close()\n {\n deliberate_close_ = true;\n ws_handler_.close();\n }\n\n ConnectionState Connection::state()\n {\n return state_;\n }\n\n void Connection::state(const ConnectionState state)\n {\n if (state != state_) {\n state_ = state;\n on_connection_state_change_();\n }\n }\n\n void Connection::on_connection_state_change_()\n {\n DEBUG_MSG(\"Connection state change: \" << state_);\n event_.on_connection_state_change_(state_);\n \/\/presence_.on_connection_state_change_(state_);\n }\n\n void Connection::on_message(const Buffer &&raw_message)\n {\n Buffer buffer(raw_message.size() + 2, 0);\n std::copy(raw_message.cbegin(), raw_message.cend(), buffer.begin());\n\n auto parser_result = parser::execute(buffer.data(), buffer.size());\n const parser::ErrorList& errors = parser_result.second;\n\n for (auto it = errors.cbegin(); it != errors.cend(); ++it) {\n const parser::Error &error = *it;\n std::stringstream error_message;\n error_message << \"parser error: \" << error << \" \\\"\"\n << Message::to_human_readable(raw_message) << \"\\\"\";\n error_handler_.on_error(error_message.str());\n }\n\n parser::MessageList parsed_messages(std::move(parser_result.first));\n\n for (auto it = parsed_messages.cbegin(); it != parsed_messages.cend(); ++it) {\n const Message &parsed_message = *it;\n DEBUG_MSG(\"Message received: \" << parsed_message.header());\n\n switch (parsed_message.topic()) {\n case Topic::EVENT:\n event_.notify_(parsed_message);\n break;\n\n case Topic::PRESENCE:\n presence_.notify_(parsed_message);\n break;\n\n case Topic::CONNECTION:\n handle_connection_response(parsed_message);\n break;\n\n case Topic::AUTH:\n handle_authentication_response(parsed_message);\n break;\n\n default:\n {\n std::stringstream error_message;\n error_message << \"unsolicited message: \" << parsed_message.header();\n error_handler_.on_error(error_message.str());\n assert(0);\n }\n }\n\n }\n }\n\n void Connection::handle_connection_response(const Message &message)\n {\n ConnectionState new_state = transition_incoming(state_, message);\n\n if (new_state == ConnectionState::ERROR) {\n std::stringstream error_message;\n error_message << \"connection error state reached, previous state: \" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n\n state(new_state);\n switch(message.action()) {\n case Action::PING:\n {\n const MessageBuilder pong(Topic::CONNECTION, Action::PONG);\n send(pong);\n } break;\n case Action::CHALLENGE:\n {\n MessageBuilder challenge_response(Topic::CONNECTION, Action::CHALLENGE_RESPONSE);\n challenge_response.add_argument(ws_handler_.URI());\n send(challenge_response);\n } break;\n case Action::CHALLENGE_RESPONSE:\n {\n if (p_auth_params_) {\n send_authentication_request();\n }\n } break;\n case Action::REDIRECT:\n {\n if (message.num_arguments() < 1) {\n error_handler_.on_error(\"No URI given in connection redirect message\");\n break;\n }\n const Buffer &uri_buff(message[0]);\n const std::string uri(uri_buff.cbegin(), uri_buff.cend());\n DEBUG_MSG(\"redirecting to \\\"\" << uri << \"\\\"\");\n ws_handler_.URI(uri);\n } break;\n default:\n {\n std::stringstream error_message;\n error_message << \"connection message with unknown action \" << state_\n << std::endl << '\\t' << message.header();\n error_handler_.on_error(error_message.str());\n }\n }\n }\n\n void Connection::handle_authentication_response(const Message &message)\n {\n switch(message.action()) {\n case Action::ERROR_TOO_MANY_AUTH_ATTEMPTS:\n {\n error_handler_.on_error(\"too many authentication attempts\");\n close();\n } break;\n case Action::ERROR_INVALID_AUTH_DATA:\n {\n error_handler_.on_error(\"invalid auth data\");\n close();\n } break;\n case Action::ERROR_INVALID_AUTH_MSG:\n {\n error_handler_.on_error(\"invalid auth message\");\n close();\n } break;\n case Action::REQUEST:\n {\n assert(message.is_ack());\n if (p_login_callback_) {\n const auto login_callback = *p_login_callback_;\n if (message.num_arguments() < 1) {\n login_callback(std::unique_ptr<Buffer>(nullptr));\n } else {\n login_callback(std::unique_ptr<Buffer>(new Buffer(message[0])));\n }\n }\n } break;\n default:\n {\n std::stringstream error_message;\n error_message << \"authentication message with unknown action\" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n }\n\n ConnectionState new_state = transition_incoming(state_, message);\n\n if (new_state == ConnectionState::ERROR) {\n std::stringstream error_message;\n error_message << \"connection error state reached, previous state: \" << state_\n << \", message header: \" << message.header();\n error_handler_.on_error(error_message.str());\n }\n\n state(new_state);\n }\n\n void Connection::on_error(const std::string &&error)\n {\n DEBUG_MSG(\"Websocket error: \" << error);\n state(ConnectionState::RECONNECTING);\n ws_handler_.reconnect();\n }\n\n void Connection::on_open()\n {\n state(ConnectionState::AWAIT_CONNECTION);\n }\n\n void Connection::on_close()\n {\n if (deliberate_close_) {\n state(ConnectionState::CLOSED);\n return;\n }\n state(ConnectionState::RECONNECTING);\n ws_handler_.open();\n }\n\n bool Connection::send(const Message& message)\n {\n DEBUG_MSG(\"--> Sending message: \" << message.header());\n\n if (message.topic() == Topic::CONNECTION || message.topic() == Topic::AUTH) {\n ConnectionState new_state = transition_outgoing(state_, message);\n assert(new_state != ConnectionState::ERROR);\n\n if (new_state == ConnectionState::ERROR) {\n throw std::logic_error(\"Invalid client state transition\");\n }\n\n state(new_state);\n } else if (state_ != ConnectionState::OPEN) {\n return false;\n }\n\n return ws_handler_.send(message.to_binary());\n }\n\n ConnectionState transition_incoming(const ConnectionState state, const Message& message)\n {\n assert(state != ConnectionState::ERROR);\n assert(state != ConnectionState::CLOSED);\n\n const Topic topic = message.topic();\n const Action action = message.action();\n const bool is_ack = message.is_ack();\n\n const auto expected_num_args = Message::num_arguments(message.header());\n const std::size_t& num_args = message.num_arguments();\n\n use(expected_num_args);\n use(num_args);\n assert(num_args >= expected_num_args.first);\n assert(num_args <= expected_num_args.second);\n\n \/\/ deepstream ping\/pong (distinct from websocket heartbeats)\n if (topic == Topic::CONNECTION && action == Action::PING) {\n assert(!is_ack);\n\n return state;\n }\n\n \/\/ actual state transitions\n if (state == ConnectionState::AWAIT_CONNECTION && topic == Topic::CONNECTION\n && action == Action::CHALLENGE) {\n assert(!is_ack);\n\n return ConnectionState::CHALLENGING;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::CHALLENGE_RESPONSE) {\n assert(is_ack);\n return ConnectionState::AWAIT_AUTHENTICATION;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::REDIRECT) {\n assert(!is_ack);\n\n return ConnectionState::AWAIT_CONNECTION;\n }\n\n if (state == ConnectionState::CHALLENGING_WAIT && topic == Topic::CONNECTION\n && action == Action::REJECT) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::REQUEST) {\n assert(is_ack);\n return ConnectionState::OPEN;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_INVALID_AUTH_DATA) {\n assert(!is_ack);\n\n return ConnectionState::AWAIT_AUTHENTICATION;\n }\n\n if (state == ConnectionState::AUTHENTICATING && topic == Topic::AUTH\n && action == Action::ERROR_INVALID_AUTH_MSG) {\n assert(!is_ack);\n\n return ConnectionState::CLOSED;\n }\n\n if (state == ConnectionState::OPEN) {\n return state;\n }\n\n return ConnectionState::ERROR;\n }\n\n ConnectionState transition_outgoing(const ConnectionState state, const Message& message)\n {\n assert(state != ConnectionState::ERROR);\n assert(state != ConnectionState::CLOSED);\n\n const Topic topic = message.topic();\n const Action action = message.action();\n const bool is_ack = message.is_ack();\n\n const auto expected_num_args = Message::num_arguments(message.header());\n const std::size_t& num_args = message.num_arguments();\n\n use(expected_num_args);\n use(num_args);\n assert(num_args >= expected_num_args.first);\n assert(num_args <= expected_num_args.second);\n\n if (topic == Topic::CONNECTION && action == Action::PONG) {\n assert(!is_ack);\n\n return state;\n }\n\n if (state == ConnectionState::CHALLENGING && topic == Topic::CONNECTION\n && action == Action::CHALLENGE_RESPONSE) {\n assert(!is_ack);\n return ConnectionState::CHALLENGING_WAIT;\n }\n\n if (state == ConnectionState::AWAIT_AUTHENTICATION && topic == Topic::AUTH\n && action == Action::REQUEST) {\n assert(!is_ack);\n return ConnectionState::AUTHENTICATING;\n }\n\n return ConnectionState::ERROR;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <smoke.h>\n#ifdef HAVE_QTGUI\n#include <smoke\/qtgui_smoke.h>\n#endif\n\n#include <algorithm>\n#include <vector>\n#include <stdlib.h>\n#include <stdio.h>\n\nextern \"C\" {\n Smoke** smokeInitialize()\n {\n std::vector<Smoke*> smokes;\n\n#ifdef HAVE_QTGUI\n init_qtgui_Smoke();\n smokes.push_back(qtgui_Smoke);\n printf(\"Initialized qtgui\\n\");\n#endif\n smokes.push_back(0);\n printf(\"%d smokes (w\/ null terminator)\\n\", smokes.size());\n\n Smoke **ret = (Smoke**)calloc(smokes.size(), sizeof(Smoke*));\n std::copy(smokes.begin(), smokes.end(), ret);\n\n return ret;\n }\n\n Smoke::Class* smokeClasses(Smoke *smoke)\n {\n return smoke->classes;\n }\n\n int smokeNumClasses(Smoke *smoke)\n {\n return smoke->numClasses;\n }\n\n Smoke::Method* smokeMethods(Smoke *smoke)\n {\n return smoke->methods;\n }\n\n int smokeNumMethods(Smoke *smoke)\n {\n return smoke->numMethods;\n }\n\n const char** smokeMethodNames(Smoke *smoke)\n {\n return smoke->methodNames;\n }\n\n const int smokeNumMethodNames(Smoke *smoke)\n {\n return smoke->numMethodNames;\n }\n\n Smoke::Type* smokeTypes(Smoke *smoke)\n {\n return smoke->types;\n }\n\n int smokeNumTypes(Smoke *smoke)\n {\n return smoke->numTypes;\n }\n\n short* smokeArgumentList(Smoke *smoke)\n {\n return smoke->argumentList;\n }\n\n const char* smokeModuleName(Smoke *smoke)\n {\n return smoke->moduleName();\n }\n\n const char* smokeClassName(Smoke::Class *klass)\n {\n return klass->className;\n }\n\n int smokeClassExternal(Smoke::Class *klass)\n {\n return klass->external;\n }\n\n int smokeClassParents(Smoke::Class *klass)\n {\n return klass->parents;\n }\n\n unsigned int smokeClassFlags(Smoke::Class *klass)\n {\n return klass->flags;\n }\n\n int smokeClassSize(Smoke::Class *klass)\n {\n return klass->size;\n }\n\n int smokeMethodClassId(Smoke::Method *m)\n {\n return m->classId;\n }\n\n int smokeMethodName(Smoke::Method *m)\n {\n return m->name;\n }\n\n int smokeMethodArgs(Smoke::Method *m)\n {\n return m->args;\n }\n\n int smokeMethodNumArgs(Smoke::Method *m)\n {\n return m->numArgs;\n }\n\n unsigned int smokeMethodFlags(Smoke::Method *m)\n {\n return m->flags;\n }\n\n int smokeMethodRet(Smoke::Method *m)\n {\n return m->ret;\n }\n\n int smokeMethodMethod(Smoke::Method *m)\n {\n return m->method;\n }\n\n const char* smokeTypeName(Smoke::Type *t)\n {\n return t->name;\n }\n\n int smokeTypeClassId(Smoke::Type *t)\n {\n return t->classId;\n }\n\n unsigned int smokeTypeFlags(Smoke::Type *t)\n {\n return t->flags;\n }\n}\n\n#if defined(PROBE)\ntemplate<typename T> struct align { char c; T member; };\n#define ALIGNOF(ty) offsetof(align<ty>, member)\n\n#include <stdio.h>\n\nint main() {\n printf(\"Class align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Class), sizeof(Smoke::Class));\n printf(\"Method align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Method), sizeof(Smoke::Method));\n printf(\"Type align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Type), sizeof(Smoke::Type));\n\n return 0;\n}\n#endif\n<commit_msg>Remove printfs<commit_after>#include <smoke.h>\n#ifdef HAVE_QTGUI\n#include <smoke\/qtgui_smoke.h>\n#endif\n\n#include <algorithm>\n#include <vector>\n#include <stdlib.h>\n\nextern \"C\" {\n Smoke** smokeInitialize()\n {\n std::vector<Smoke*> smokes;\n\n#ifdef HAVE_QTGUI\n init_qtgui_Smoke();\n smokes.push_back(qtgui_Smoke);\n#endif\n smokes.push_back(0);\n\n Smoke **ret = (Smoke**)calloc(smokes.size(), sizeof(Smoke*));\n std::copy(smokes.begin(), smokes.end(), ret);\n\n return ret;\n }\n\n Smoke::Class* smokeClasses(Smoke *smoke)\n {\n return smoke->classes;\n }\n\n int smokeNumClasses(Smoke *smoke)\n {\n return smoke->numClasses;\n }\n\n Smoke::Method* smokeMethods(Smoke *smoke)\n {\n return smoke->methods;\n }\n\n int smokeNumMethods(Smoke *smoke)\n {\n return smoke->numMethods;\n }\n\n const char** smokeMethodNames(Smoke *smoke)\n {\n return smoke->methodNames;\n }\n\n const int smokeNumMethodNames(Smoke *smoke)\n {\n return smoke->numMethodNames;\n }\n\n Smoke::Type* smokeTypes(Smoke *smoke)\n {\n return smoke->types;\n }\n\n int smokeNumTypes(Smoke *smoke)\n {\n return smoke->numTypes;\n }\n\n short* smokeArgumentList(Smoke *smoke)\n {\n return smoke->argumentList;\n }\n\n const char* smokeModuleName(Smoke *smoke)\n {\n return smoke->moduleName();\n }\n\n const char* smokeClassName(Smoke::Class *klass)\n {\n return klass->className;\n }\n\n int smokeClassExternal(Smoke::Class *klass)\n {\n return klass->external;\n }\n\n int smokeClassParents(Smoke::Class *klass)\n {\n return klass->parents;\n }\n\n unsigned int smokeClassFlags(Smoke::Class *klass)\n {\n return klass->flags;\n }\n\n int smokeClassSize(Smoke::Class *klass)\n {\n return klass->size;\n }\n\n int smokeMethodClassId(Smoke::Method *m)\n {\n return m->classId;\n }\n\n int smokeMethodName(Smoke::Method *m)\n {\n return m->name;\n }\n\n int smokeMethodArgs(Smoke::Method *m)\n {\n return m->args;\n }\n\n int smokeMethodNumArgs(Smoke::Method *m)\n {\n return m->numArgs;\n }\n\n unsigned int smokeMethodFlags(Smoke::Method *m)\n {\n return m->flags;\n }\n\n int smokeMethodRet(Smoke::Method *m)\n {\n return m->ret;\n }\n\n int smokeMethodMethod(Smoke::Method *m)\n {\n return m->method;\n }\n\n const char* smokeTypeName(Smoke::Type *t)\n {\n return t->name;\n }\n\n int smokeTypeClassId(Smoke::Type *t)\n {\n return t->classId;\n }\n\n unsigned int smokeTypeFlags(Smoke::Type *t)\n {\n return t->flags;\n }\n}\n\n#if defined(PROBE)\ntemplate<typename T> struct align { char c; T member; };\n#define ALIGNOF(ty) offsetof(align<ty>, member)\n\n#include <stdio.h>\n\nint main() {\n printf(\"Class align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Class), sizeof(Smoke::Class));\n printf(\"Method align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Method), sizeof(Smoke::Method));\n printf(\"Type align=%d and size=%d\\n\",\n ALIGNOF(Smoke::Type), sizeof(Smoke::Type));\n\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TableFieldDescription.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 03:13:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_TABLEFIELDDESC_HXX\n#define DBAUI_TABLEFIELDDESC_HXX\n\n#ifndef INCLUDED_VECTOR\n#define INCLUDED_VECTOR\n#include <vector>\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n\nclass Window;\nnamespace dbaui\n{\n class OTableFieldDesc : public ::vos::OReference\n {\n private:\n ::std::vector< ::rtl::OUString> m_vecCriteria;\n\n ::rtl::OUString m_aTableName;\n ::rtl::OUString m_aAliasName; \/\/ table range\n ::rtl::OUString m_aFieldName; \/\/ column\n ::rtl::OUString m_aFieldAlias; \/\/ column alias\n ::rtl::OUString m_aDatabaseName; \/\/ qualifier or catalog\n ::rtl::OUString m_aFunctionName; \/\/ enth\"alt den Funktionsnamen, nur wenn m_eFunctionType != FKT_NONE gesetzt\n\n Window* m_pTabWindow;\n\n sal_Int32 m_eDataType;\n sal_Int32 m_eFunctionType;\n ETableFieldType m_eFieldType;\n EOrderDir m_eOrderDir;\n sal_Int32 m_nIndex;\n sal_Int32 m_nColWidth;\n sal_uInt16 m_nColumnId;\n sal_Bool m_bGroupBy;\n sal_Bool m_bVisible;\n\n \/\/ !!!! bitte bei Erweiterung um neue Felder auch IsEmpty mitpflegen !!!!\n\n public:\n OTableFieldDesc();\n OTableFieldDesc(const ::rtl::OUString& rTable, const ::rtl::OUString& rField );\n OTableFieldDesc(const OTableFieldDesc& rRS);\n ~OTableFieldDesc();\n\n inline sal_Bool IsEmpty() const;\n\n sal_Bool operator==( const OTableFieldDesc& rDesc );\n\n void clear();\n\n sal_Bool IsVisible() const { return m_bVisible;}\n sal_Bool IsNumericDataType() const;\n sal_Bool IsGroupBy() const { return m_bGroupBy;}\n\n void SetVisible( sal_Bool bVis=sal_True ){ m_bVisible = bVis;}\n void SetGroupBy( sal_Bool bGb=sal_False ){ m_bGroupBy = bGb;}\n void SetTabWindow( Window* pWin ){ m_pTabWindow = pWin;}\n void SetField( const ::rtl::OUString& rF ){ m_aFieldName = rF;}\n void SetFieldAlias( const ::rtl::OUString& rF ){ m_aFieldAlias = rF;}\n void SetTable( const ::rtl::OUString& rT ){ m_aTableName = rT;}\n void SetAlias( const ::rtl::OUString& rT ){ m_aAliasName = rT;}\n void SetDatabase( const ::rtl::OUString& rT ) { m_aDatabaseName = rT;}\n void SetFunction( const ::rtl::OUString& rT ) { m_aFunctionName = rT;}\n void SetOrderDir( EOrderDir eDir ) { m_eOrderDir = eDir; }\n void SetDataType( sal_Int32 eTyp ) { m_eDataType = eTyp; }\n void SetFieldType( ETableFieldType eTyp ) { m_eFieldType = eTyp; }\n void SetCriteria( sal_uInt16 nIdx, const ::rtl::OUString& rCrit);\n void SetColWidth( sal_Int32 nWidth ) { m_nColWidth = nWidth; }\n void SetFieldIndex( sal_Int32 nFieldIndex ) { m_nIndex = nFieldIndex; }\n void SetFunctionType( sal_Int32 eTyp ) { m_eFunctionType = eTyp; }\n void SetColumnId(sal_uInt16 _nColumnId) { m_nColumnId = _nColumnId; }\n\n\n ::rtl::OUString GetField() const { return m_aFieldName;}\n ::rtl::OUString GetFieldAlias() const { return m_aFieldAlias;}\n ::rtl::OUString GetTable() const { return m_aTableName;}\n ::rtl::OUString GetAlias() const { return m_aAliasName;}\n ::rtl::OUString GetDatabase() const { return m_aDatabaseName;}\n ::rtl::OUString GetFunction() const { return m_aFunctionName;}\n sal_Int32 GetDataType() const { return m_eDataType; }\n ETableFieldType GetFieldType() const { return m_eFieldType; }\n EOrderDir GetOrderDir() const { return m_eOrderDir; }\n ::rtl::OUString GetCriteria( sal_uInt16 nIdx ) const;\n sal_Int32 GetColWidth() const { return m_nColWidth; }\n sal_Int32 GetFieldIndex() const { return m_nIndex; }\n Window* GetTabWindow() const { return m_pTabWindow;}\n sal_Int32 GetFunctionType() const { return m_eFunctionType; }\n sal_uInt16 GetColumnId() const { return m_nColumnId;}\n\n inline sal_Bool isAggreateFunction() const { return (m_eFunctionType & FKT_AGGREGATE) == FKT_AGGREGATE; }\n inline sal_Bool isOtherFunction() const { return (m_eFunctionType & FKT_OTHER) == FKT_OTHER; }\n inline sal_Bool isNumeric() const { return (m_eFunctionType & FKT_NUMERIC) == FKT_NUMERIC; }\n inline sal_Bool isNoneFunction() const { return m_eFunctionType == FKT_NONE; }\n inline sal_Bool isCondition() const { return (m_eFunctionType & FKT_CONDITION) == FKT_CONDITION; }\n inline sal_Bool isNumericOrAggreateFunction() const { return isNumeric() || isAggreateFunction(); }\n\n sal_Bool HasCriteria() const\n {\n ::std::vector< ::rtl::OUString>::const_iterator aIter = m_vecCriteria.begin();\n for(;aIter != m_vecCriteria.end();++aIter)\n if(aIter->getLength())\n break;\n return aIter != m_vecCriteria.end();\n }\n\n void NextOrderDir();\n const ::std::vector< ::rtl::OUString>& GetCriteria() const { return m_vecCriteria;}\n\n void Load(const ::com::sun::star::beans::PropertyValue& _rProperty);\n void Save(::com::sun::star::beans::PropertyValue& _rProperty);\n };\n\n \/\/------------------------------------------------------------------\n inline sal_Bool OTableFieldDesc::IsEmpty() const\n {\n sal_Bool bEmpty = (!m_aTableName.getLength() &&\n !m_aAliasName.getLength() &&\n !m_aFieldName.getLength() &&\n !m_aFieldAlias.getLength() &&\n !m_aDatabaseName.getLength() &&\n !m_aFunctionName.getLength() &&\n !HasCriteria());\n return bEmpty;\n }\n \/\/------------------------------------------------------------------\n typedef ::vos::ORef< OTableFieldDesc> OTableFieldDescRef;\n typedef ::std::vector<OTableFieldDescRef> OTableFields;\n}\n#endif \/\/\n\n<commit_msg>INTEGRATION: CWS dba204c (1.6.28); FILE MERGED 2006\/07\/19 13:35:17 fs 1.6.28.1: during #i67530#: m_aDatabaseName is never used<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TableFieldDescription.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: ihi $ $Date: 2006-08-04 13:57:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_TABLEFIELDDESC_HXX\n#define DBAUI_TABLEFIELDDESC_HXX\n\n#ifndef INCLUDED_VECTOR\n#define INCLUDED_VECTOR\n#include <vector>\n#endif\n#ifndef DBAUI_ENUMTYPES_HXX\n#include \"QEnumTypes.hxx\"\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n\nclass Window;\nnamespace dbaui\n{\n class OTableFieldDesc : public ::vos::OReference\n {\n private:\n ::std::vector< ::rtl::OUString> m_vecCriteria;\n\n ::rtl::OUString m_aTableName;\n ::rtl::OUString m_aAliasName; \/\/ table range\n ::rtl::OUString m_aFieldName; \/\/ column\n ::rtl::OUString m_aFieldAlias; \/\/ column alias\n ::rtl::OUString m_aFunctionName; \/\/ enth\"alt den Funktionsnamen, nur wenn m_eFunctionType != FKT_NONE gesetzt\n\n Window* m_pTabWindow;\n\n sal_Int32 m_eDataType;\n sal_Int32 m_eFunctionType;\n ETableFieldType m_eFieldType;\n EOrderDir m_eOrderDir;\n sal_Int32 m_nIndex;\n sal_Int32 m_nColWidth;\n sal_uInt16 m_nColumnId;\n sal_Bool m_bGroupBy;\n sal_Bool m_bVisible;\n\n \/\/ !!!! bitte bei Erweiterung um neue Felder auch IsEmpty mitpflegen !!!!\n\n public:\n OTableFieldDesc();\n OTableFieldDesc(const ::rtl::OUString& rTable, const ::rtl::OUString& rField );\n OTableFieldDesc(const OTableFieldDesc& rRS);\n ~OTableFieldDesc();\n\n inline sal_Bool IsEmpty() const;\n\n sal_Bool operator==( const OTableFieldDesc& rDesc );\n\n void clear();\n\n sal_Bool IsVisible() const { return m_bVisible;}\n sal_Bool IsNumericDataType() const;\n sal_Bool IsGroupBy() const { return m_bGroupBy;}\n\n void SetVisible( sal_Bool bVis=sal_True ){ m_bVisible = bVis;}\n void SetGroupBy( sal_Bool bGb=sal_False ){ m_bGroupBy = bGb;}\n void SetTabWindow( Window* pWin ){ m_pTabWindow = pWin;}\n void SetField( const ::rtl::OUString& rF ){ m_aFieldName = rF;}\n void SetFieldAlias( const ::rtl::OUString& rF ){ m_aFieldAlias = rF;}\n void SetTable( const ::rtl::OUString& rT ){ m_aTableName = rT;}\n void SetAlias( const ::rtl::OUString& rT ){ m_aAliasName = rT;}\n void SetFunction( const ::rtl::OUString& rT ) { m_aFunctionName = rT;}\n void SetOrderDir( EOrderDir eDir ) { m_eOrderDir = eDir; }\n void SetDataType( sal_Int32 eTyp ) { m_eDataType = eTyp; }\n void SetFieldType( ETableFieldType eTyp ) { m_eFieldType = eTyp; }\n void SetCriteria( sal_uInt16 nIdx, const ::rtl::OUString& rCrit);\n void SetColWidth( sal_Int32 nWidth ) { m_nColWidth = nWidth; }\n void SetFieldIndex( sal_Int32 nFieldIndex ) { m_nIndex = nFieldIndex; }\n void SetFunctionType( sal_Int32 eTyp ) { m_eFunctionType = eTyp; }\n void SetColumnId(sal_uInt16 _nColumnId) { m_nColumnId = _nColumnId; }\n\n\n ::rtl::OUString GetField() const { return m_aFieldName;}\n ::rtl::OUString GetFieldAlias() const { return m_aFieldAlias;}\n ::rtl::OUString GetTable() const { return m_aTableName;}\n ::rtl::OUString GetAlias() const { return m_aAliasName;}\n ::rtl::OUString GetFunction() const { return m_aFunctionName;}\n sal_Int32 GetDataType() const { return m_eDataType; }\n ETableFieldType GetFieldType() const { return m_eFieldType; }\n EOrderDir GetOrderDir() const { return m_eOrderDir; }\n ::rtl::OUString GetCriteria( sal_uInt16 nIdx ) const;\n sal_Int32 GetColWidth() const { return m_nColWidth; }\n sal_Int32 GetFieldIndex() const { return m_nIndex; }\n Window* GetTabWindow() const { return m_pTabWindow;}\n sal_Int32 GetFunctionType() const { return m_eFunctionType; }\n sal_uInt16 GetColumnId() const { return m_nColumnId;}\n\n inline sal_Bool isAggreateFunction() const { return (m_eFunctionType & FKT_AGGREGATE) == FKT_AGGREGATE; }\n inline sal_Bool isOtherFunction() const { return (m_eFunctionType & FKT_OTHER) == FKT_OTHER; }\n inline sal_Bool isNumeric() const { return (m_eFunctionType & FKT_NUMERIC) == FKT_NUMERIC; }\n inline sal_Bool isNoneFunction() const { return m_eFunctionType == FKT_NONE; }\n inline sal_Bool isCondition() const { return (m_eFunctionType & FKT_CONDITION) == FKT_CONDITION; }\n inline sal_Bool isNumericOrAggreateFunction() const { return isNumeric() || isAggreateFunction(); }\n\n sal_Bool HasCriteria() const\n {\n ::std::vector< ::rtl::OUString>::const_iterator aIter = m_vecCriteria.begin();\n for(;aIter != m_vecCriteria.end();++aIter)\n if(aIter->getLength())\n break;\n return aIter != m_vecCriteria.end();\n }\n\n void NextOrderDir();\n const ::std::vector< ::rtl::OUString>& GetCriteria() const { return m_vecCriteria;}\n\n void Load(const ::com::sun::star::beans::PropertyValue& _rProperty);\n void Save(::com::sun::star::beans::PropertyValue& _rProperty);\n };\n\n \/\/------------------------------------------------------------------\n inline sal_Bool OTableFieldDesc::IsEmpty() const\n {\n sal_Bool bEmpty = (!m_aTableName.getLength() &&\n !m_aAliasName.getLength() &&\n !m_aFieldName.getLength() &&\n !m_aFieldAlias.getLength() &&\n !m_aFunctionName.getLength() &&\n !HasCriteria());\n return bEmpty;\n }\n \/\/------------------------------------------------------------------\n typedef ::vos::ORef< OTableFieldDesc> OTableFieldDescRef;\n typedef ::std::vector<OTableFieldDescRef> OTableFields;\n}\n#endif \/\/\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <utility>\n\nconst double Q0 = 0.5; \/\/if > then, exploration\nconst double BETA = 0.5; \/\/ must be in range [0,1], a lower q favors exploration over exploitation\nconst double ALPHA = 0.5; \/\/ must be in range [0,1], pheremone decay factor\nconst int GENERATIONS = 100; \/\/how many times will we run this thingy\n\/\/const double PHERBASE = 0.5; \/\/base level of pheromones\n\n\/\/ returns the dist array, it is directional\nstd::vector< std::vector<int> > read_the_file(std::string s);\nstd::vector< std::vector<double> > setup_pheromones(std::vector< std::vector<int> > p);\n\n\/\/ euclidean distance\ndouble distance(std::pair<double, double>, std::pair<double, double>);\ndouble distance(std::pair<int, int>, std::pair<int, int>);\ndouble distance(int, int, int, int);\ndouble distance(double, double, double, double);\n\n\/*\neqauation 1 and equation 2s interfaces are subject to change\n*\/\n\n\/\/ returns the index of the next city to go to\nint eq1(std::vector< std::vector<int> >& dist, std::vector< std::vector<double> >& pheromones);\n\n\/\/ returns the value computed by equation 2\ndouble eq2(std::vector<std::vector<int> >& dist, std::vector<std::vector<double> >& pheromones);\n\n\/\/ returns the new pheromone level\ndouble eq3(double old_pheromone, double nextCost);\n\n\/\/ returns the new pheromone level to update the current global best path\ndouble eq4(double old_pheromone, int total_path_cost);\n\n#endif<commit_msg>Header changes.<commit_after>#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <utility>\n\nconst double Q0 = 0.5; \/\/if > then, exploration\nconst double BETA = 0.5; \/\/ must be in range [0,1], a lower q favors exploration over exploitation\nconst double ALPHA = 0.1; \/\/ must be in range [0,1], pheremone decay factor\nconst double TAU = 0.3;\nconst int GENERATIONS = 100; \/\/how many times will we run this thingy\n\/\/const double PHERBASE = 0.5; \/\/base level of pheromones\n\n\/\/ returns the dist array, it is directional\nstd::vector< std::vector<int> > read_the_file(std::string s);\nstd::vector< std::vector<double> > setup_pheromones(std::vector< std::vector<int> > p);\n\n\/\/ euclidean distance\ndouble distance(std::pair<double, double>, std::pair<double, double>);\ndouble distance(std::pair<int, int>, std::pair<int, int>);\ndouble distance(int, int, int, int);\ndouble distance(double, double, double, double);\n\n\/*\nequation 1 and equation 2s interfaces are subject to change\n*\/\n\n\/\/ returns the index of the next city to go to\nint eq1(std::vector< std::vector<int> >& dist, std::vector< std::vector<double> >& pheromones);\n\n\/\/ returns the value computed by equation 2\ndouble eq2(std::vector<std::vector<int> >& dist, std::vector<std::vector<double> >& pheromones);\n\n\/\/ returns the new pheromone level\ndouble eq3(double old_pheromone, double nextCost);\n\n\/\/ returns the new pheromone level to update the current global best path\ndouble eq4(double old_pheromone, int total_path_cost);\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ATables.cxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 11:30:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#ifndef _CONNECTIVITY_ADO_TABLES_HXX_\n#include \"ado\/ATables.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_TABLE_HXX_\n#include \"ado\/ATable.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_\n#include <com\/sun\/star\/sdbc\/ColumnValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include <com\/sun\/star\/sdbc\/KeyRule.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_\n#include <com\/sun\/star\/sdbcx\/KeyType.hpp>\n#endif\n#ifndef _CONNECTIVITY_ADO_CATALOG_HXX_\n#include \"ado\/ACatalog.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_\n#include \"ado\/Awrapado.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include <connectivity\/dbexception.hxx>\n#endif\n\nusing namespace ::cppu;\nusing namespace connectivity;\nusing namespace comphelper;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::lang;\n\ntypedef connectivity::sdbcx::OCollection OCollection_TYPE;\n\nsdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OTables::impl_refresh( ) throw(RuntimeException)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n m_aCollection.Refresh();\n m_pCatalog->refreshTables();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OTables::createDescriptor()\n{\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OTables::appendObject( const ::rtl::OUString&, const Reference< XPropertySet >& descriptor )\n{\n OAdoTable* pTable = NULL;\n if ( !getImplementation( pTable, descriptor ) || pTable == NULL )\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create table: invalid object descriptor.\" ),\n static_cast<XTypeProvider*>(this)\n );\n\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n if(!m_aCollection.Append(pTable->getImpl()))\n ADOS::ThrowException(*m_pCatalog->getConnection()->getConnection(),static_cast<XTypeProvider*>(this));\n m_aCollection.Refresh();\n\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog,pTable->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OTables::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n if ( !m_aCollection.Delete(_sElementName) )\n ADOS::ThrowException(*m_pCatalog->getConnection()->getConnection(),static_cast<XTypeProvider*>(this));\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OTables::appendNew(const ::rtl::OUString& _rsNewTable)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n m_aCollection.Refresh();\n\n insertElement(_rsNewTable,NULL);\n\n \/\/ notify our container listeners\n ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());\n OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);\n while (aListenerLoop.hasMoreElements())\n static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.20.204); FILE MERGED 2008\/04\/01 15:08:37 thb 1.20.204.3: #i85898# Stripping all external header guards 2008\/04\/01 10:52:50 thb 1.20.204.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:27 rt 1.20.204.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ATables.cxx,v $\n * $Revision: 1.21 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n#include \"ado\/ATables.hxx\"\n#include \"ado\/ATable.hxx\"\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#include <com\/sun\/star\/sdbc\/ColumnValue.hpp>\n#include <com\/sun\/star\/sdbc\/KeyRule.hpp>\n#include <com\/sun\/star\/sdbcx\/KeyType.hpp>\n#include \"ado\/ACatalog.hxx\"\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#include \"ado\/Awrapado.hxx\"\n#include \"TConnection.hxx\"\n#include <comphelper\/types.hxx>\n#include <cppuhelper\/interfacecontainer.h>\n#include <connectivity\/dbexception.hxx>\n\nusing namespace ::cppu;\nusing namespace connectivity;\nusing namespace comphelper;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::lang;\n\ntypedef connectivity::sdbcx::OCollection OCollection_TYPE;\n\nsdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OTables::impl_refresh( ) throw(RuntimeException)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n m_aCollection.Refresh();\n m_pCatalog->refreshTables();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OTables::createDescriptor()\n{\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OTables::appendObject( const ::rtl::OUString&, const Reference< XPropertySet >& descriptor )\n{\n OAdoTable* pTable = NULL;\n if ( !getImplementation( pTable, descriptor ) || pTable == NULL )\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create table: invalid object descriptor.\" ),\n static_cast<XTypeProvider*>(this)\n );\n\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n if(!m_aCollection.Append(pTable->getImpl()))\n ADOS::ThrowException(*m_pCatalog->getConnection()->getConnection(),static_cast<XTypeProvider*>(this));\n m_aCollection.Refresh();\n\n return new OAdoTable(this,isCaseSensitive(),m_pCatalog,pTable->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OTables::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n if ( !m_aCollection.Delete(_sElementName) )\n ADOS::ThrowException(*m_pCatalog->getConnection()->getConnection(),static_cast<XTypeProvider*>(this));\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OTables::appendNew(const ::rtl::OUString& _rsNewTable)\n{\n OSL_ENSURE(m_aCollection.IsValid(),\"Collection isn't valid\");\n m_aCollection.Refresh();\n\n insertElement(_rsNewTable,NULL);\n\n \/\/ notify our container listeners\n ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());\n OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);\n while (aListenerLoop.hasMoreElements())\n static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>VFS: Fixed flow wrt state progression post-encoding of a file<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: AConnection.hxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 17:11:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_\n#define _CONNECTIVITY_ADO_ACONNECTION_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_\n#include <com\/sun\/star\/sdbc\/SQLWarning.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XTablesSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_\n#include \"OSubComponent.hxx\"\n#endif\n#include <map>\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_OTYPEINFO_HXX_\n#include \"OTypeInfo.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n#include \"ado\/Awrapado.hxx\"\n\nnamespace connectivity\n{\n namespace ado\n {\n struct OExtendedTypeInfo\n {\n ::connectivity::OTypeInfo aSimpleType; \/\/ the general type info\n DataTypeEnum eType;\n\n inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; }\n };\n\n class WpADOConnection;\n class ODriver;\n class OCatalog;\n typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*> OTypeInfoMap;\n typedef connectivity::OMetaConnection OConnection_BASE;\n\n\n class OConnection : public OConnection_BASE,\n public connectivity::OSubComponent<OConnection, OConnection_BASE>\n {\n friend class connectivity::OSubComponent<OConnection, OConnection_BASE>;\n\n protected:\n \/\/====================================================================\n \/\/ Data attributes\n \/\/====================================================================\n OTypeInfoMap m_aTypeInfo; \/\/ vector containing an entry\n \/\/ for each row returned by\n \/\/ DatabaseMetaData.getTypeInfo.\n ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;\n\n connectivity::OWeakRefArray m_aStatements; \/\/ vector containing a list\n \/\/ of all the Statement objects\n \/\/ for this Connection\n ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog;\n ODriver* m_pDriver;\n private:\n WpADOConnection* m_pAdoConnection;\n OCatalog* m_pCatalog;\n sal_Int32 m_nEngineType;\n sal_Bool m_bClosed;\n sal_Bool m_bAutocommit;\n\n protected:\n void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException);\n public:\n\n OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info,\n ODriver* _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ OConnection(const SQLHANDLE _pConnectionHandle);\n ~OConnection();\n void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info);\n\n void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException);\n\n \/\/XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n \/\/ XInterface\n virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XConnection\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XCloseable\n virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XWarningsSupplier\n virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/\n WpADOConnection* getConnection() { return m_pAdoConnection; }\n void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; }\n void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; }\n\n const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;}\n OCatalog* getAdoCatalog() const\n {\n if ( m_xCatalog.get().is() )\n return m_pCatalog;\n return NULL;\n }\n\n sal_Int32 getEngineType() const { return m_nEngineType; }\n ODriver* getDriver() const { return m_pDriver; }\n\n static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,\n DataTypeEnum _nType,\n const ::rtl::OUString& _sTypeName,\n sal_Int32 _nPrecision,\n sal_Int32 _nScale,\n sal_Bool& _brForceToType);\n };\n }\n}\n#endif \/\/ _CONNECTIVITY_ADO_ACONNECTION_HXX_\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.14.132); FILE MERGED 2005\/09\/05 17:24:59 rt 1.14.132.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AConnection.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:49:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_\n#define _CONNECTIVITY_ADO_ACONNECTION_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_\n#include <com\/sun\/star\/sdbc\/SQLWarning.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XTablesSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_\n#include \"OSubComponent.hxx\"\n#endif\n#include <map>\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_OTYPEINFO_HXX_\n#include \"OTypeInfo.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n#include \"ado\/Awrapado.hxx\"\n\nnamespace connectivity\n{\n namespace ado\n {\n struct OExtendedTypeInfo\n {\n ::connectivity::OTypeInfo aSimpleType; \/\/ the general type info\n DataTypeEnum eType;\n\n inline ::rtl::OUString getDBName() const { return aSimpleType.aTypeName; }\n };\n\n class WpADOConnection;\n class ODriver;\n class OCatalog;\n typedef ::std::multimap<DataTypeEnum, OExtendedTypeInfo*> OTypeInfoMap;\n typedef connectivity::OMetaConnection OConnection_BASE;\n\n\n class OConnection : public OConnection_BASE,\n public connectivity::OSubComponent<OConnection, OConnection_BASE>\n {\n friend class connectivity::OSubComponent<OConnection, OConnection_BASE>;\n\n protected:\n \/\/====================================================================\n \/\/ Data attributes\n \/\/====================================================================\n OTypeInfoMap m_aTypeInfo; \/\/ vector containing an entry\n \/\/ for each row returned by\n \/\/ DatabaseMetaData.getTypeInfo.\n ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;\n\n connectivity::OWeakRefArray m_aStatements; \/\/ vector containing a list\n \/\/ of all the Statement objects\n \/\/ for this Connection\n ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier> m_xCatalog;\n ODriver* m_pDriver;\n private:\n WpADOConnection* m_pAdoConnection;\n OCatalog* m_pCatalog;\n sal_Int32 m_nEngineType;\n sal_Bool m_bClosed;\n sal_Bool m_bAutocommit;\n\n protected:\n void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException);\n public:\n\n OConnection(const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info,\n ODriver* _pDriver) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ OConnection(const SQLHANDLE _pConnectionHandle);\n ~OConnection();\n void construct(const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info);\n\n void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException);\n\n \/\/XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n \/\/ XInterface\n virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XConnection\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XCloseable\n virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/ XWarningsSupplier\n virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n \/\/\n WpADOConnection* getConnection() { return m_pAdoConnection; }\n void setCatalog(const ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbcx::XTablesSupplier>& _xCat) { m_xCatalog = _xCat; }\n void setCatalog(OCatalog* _pCatalog) { m_pCatalog = _pCatalog; }\n\n const OTypeInfoMap* getTypeInfo() const { return &m_aTypeInfo;}\n OCatalog* getAdoCatalog() const\n {\n if ( m_xCatalog.get().is() )\n return m_pCatalog;\n return NULL;\n }\n\n sal_Int32 getEngineType() const { return m_nEngineType; }\n ODriver* getDriver() const { return m_pDriver; }\n\n static const OExtendedTypeInfo* getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,\n DataTypeEnum _nType,\n const ::rtl::OUString& _sTypeName,\n sal_Int32 _nPrecision,\n sal_Int32 _nScale,\n sal_Bool& _brForceToType);\n };\n }\n}\n#endif \/\/ _CONNECTIVITY_ADO_ACONNECTION_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>#include \"LPC17xx.h\"\n#include \"cmsis_nvic.h\" \n#include <assert.h>\n\nextern \"C\"{ \n\tvoid TIMER0_IRQHandler() {\n\t\tLPC_GPIO1->FIOPIN = ~(LPC_GPIO1->FIOPIN); \/\/toggle LED 1\t\n\t\tLPC_TIM0->IR |= 1 << 0; \/\/ clear the interrupt flag\n\t\tassert(LPC_TIM0->IR == 0) ; \/\/ read the interrupt flag to make sure it has been set\n\t}\n}\n \n \nint main() {\n\t\/\/ LED 1 init\n\tLPC_GPIO1->FIODIR |= (1<<18); \/\/select p1.18 (LED 1) and write 1 to make it an output\n\tLPC_GPIO1->FIOMASK = ~(1<<18); \/\/mask only the 18th bit when reading or writing to FIOPIN\n\n\t\n\tNVIC_EnableIRQ(TIMER0_IRQn); \/\/Enable the interrupt vector\n\n\tLPC_TIM0->MR0 = 3600000; \/\/ Match count for 150ms\n LPC_TIM0->MCR = 3; \/\/ Interrupt and Reset on Match\n LPC_TIM0->TCR = 1; \/\/ Enable Timer0\n \n while (1) {} \/\/ wait here for interrupts\n}\n<commit_msg>removed unused header<commit_after>#include \"LPC17xx.h\"\n#include <assert.h>\n\nextern \"C\"{\n\tvoid TIMER0_IRQHandler() {\n\t\tLPC_GPIO1->FIOPIN = ~(LPC_GPIO1->FIOPIN); \/\/toggle LED 1\n\t\tLPC_TIM0->IR |= 1 << 0; \/\/ clear the interrupt flag\n\t\tassert(LPC_TIM0->IR == 0) ; \/\/ read the interrupt flag to make sure it has been set\n\t}\n}\n\n\nint main() {\n\t\/\/ LED 1 init\n\tLPC_GPIO1->FIODIR |= (1<<18); \/\/select p1.18 (LED 1) and write 1 to make it an output\n\tLPC_GPIO1->FIOMASK = ~(1<<18); \/\/mask only the 18th bit when reading or writing to FIOPIN\n\n\n\tNVIC_EnableIRQ(TIMER0_IRQn); \/\/Enable the interrupt vector\n\n\tLPC_TIM0->MR0 = 3600000; \/\/ Match count for 150ms\n LPC_TIM0->MCR = 3; \/\/ Interrupt and Reset on Match\n LPC_TIM0->TCR = 1; \/\/ Enable Timer0\n\n while (1) {} \/\/ wait here for interrupts\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/browser\/web_contents\/web_contents_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace content {\n\nclass WebrtcBrowserTest: public ContentBrowserTest {\n public:\n WebrtcBrowserTest() {}\n virtual ~WebrtcBrowserTest() {}\n\n virtual void SetUp() OVERRIDE {\n \/\/ We need fake devices in this test since we want to run on naked VMs. We\n \/\/ assume this switch is set by default in content_browsertests.\n ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n\n ASSERT_TRUE(test_server()->Start());\n ContentBrowserTest::SetUp();\n }\n protected:\n bool ExecuteJavascript(const std::string& javascript) {\n return ExecuteScript(shell()->web_contents(), javascript);\n }\n\n void ExpectTitle(const std::string& expected_title) const {\n string16 expected_title16(ASCIIToUTF16(expected_title));\n TitleWatcher title_watcher(shell()->web_contents(), expected_title16);\n EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());\n }\n};\n\n\/\/ These tests will all make a getUserMedia call with different constraints and\n\/\/ see that the success callback is called. If the error callback is called or\n\/\/ none of the callbacks are called the tests will simply time out and fail.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true, audio: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\n\/\/ These tests will make a complete PeerConnection-based call and verify that\n\/\/ video is playing for the call.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true, audio: true});\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a complete PeerConnection-based call but remove the\n\/\/ MSID and bundle attribute from the initial offer to verify that\n\/\/ video is playing for the call even if the initiating client don't support\n\/\/ MSID. http:\/\/tools.ietf.org\/html\/draft-alvestrand-rtcweb-msid-02\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanSetupAudioAndVideoCallWithoutMsidAndBundle) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithoutMsidAndBundle();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataOnly();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and audio and video tracks.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and later add an audio and video track.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndLaterAddMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndLaterAddMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n} \/\/ namespace content\n\n<commit_msg>Disable WebrtcBrowserTest.CallWithDataAndLaterAddMedia on Linux as it flakily crashes<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/browser\/web_contents\/web_contents_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace content {\n\nclass WebrtcBrowserTest: public ContentBrowserTest {\n public:\n WebrtcBrowserTest() {}\n virtual ~WebrtcBrowserTest() {}\n\n virtual void SetUp() OVERRIDE {\n \/\/ We need fake devices in this test since we want to run on naked VMs. We\n \/\/ assume this switch is set by default in content_browsertests.\n ASSERT_TRUE(CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kUseFakeDeviceForMediaStream));\n\n ASSERT_TRUE(test_server()->Start());\n ContentBrowserTest::SetUp();\n }\n protected:\n bool ExecuteJavascript(const std::string& javascript) {\n return ExecuteScript(shell()->web_contents(), javascript);\n }\n\n void ExpectTitle(const std::string& expected_title) const {\n string16 expected_title16(ASCIIToUTF16(expected_title));\n TitleWatcher title_watcher(shell()->web_contents(), expected_title16);\n EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle());\n }\n};\n\n\/\/ These tests will all make a getUserMedia call with different constraints and\n\/\/ see that the success callback is called. If the error callback is called or\n\/\/ none of the callbacks are called the tests will simply time out and fail.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, GetAudioAndVideoStreamAndStop) {\n GURL url(test_server()->GetURL(\"files\/media\/getusermedia_and_stop.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"getUserMedia({video: true, audio: true});\"));\n\n ExpectTitle(\"OK\");\n}\n\n\/\/ These tests will make a complete PeerConnection-based call and verify that\n\/\/ video is playing for the call.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true});\"));\n ExpectTitle(\"OK\");\n}\n\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CanSetupAudioAndVideoCall) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"call({video: true, audio: true});\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a complete PeerConnection-based call but remove the\n\/\/ MSID and bundle attribute from the initial offer to verify that\n\/\/ video is playing for the call even if the initiating client don't support\n\/\/ MSID. http:\/\/tools.ietf.org\/html\/draft-alvestrand-rtcweb-msid-02\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest,\n CanSetupAudioAndVideoCallWithoutMsidAndBundle) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithoutMsidAndBundle();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataOnly) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataOnly();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and audio and video tracks.\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, CallWithDataAndMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n\/\/ This test will make a PeerConnection-based call and test an unreliable text\n\/\/ dataChannel and later add an audio and video track.\n#if defined(OS_LINUX)\n\/\/ Flaky on Linux. http:\/\/crbug.com\/175683\n#define MAYBE_CallWithDataAndLaterAddMedia DISABLED_CallWithDataAndLaterAddMedia\n#else\n#define MAYBE_CallWithDataAndLaterAddMedia CallWithDataAndLaterAddMedia\n#endif\nIN_PROC_BROWSER_TEST_F(WebrtcBrowserTest, MAYBE_CallWithDataAndLaterAddMedia) {\n GURL url(test_server()->GetURL(\"files\/media\/peerconnection-call.html\"));\n NavigateToURL(shell(), url);\n\n EXPECT_TRUE(ExecuteJavascript(\"callWithDataAndLaterAddMedia();\"));\n ExpectTitle(\"OK\");\n}\n\n} \/\/ namespace content\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dp_gui_service.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: vg $ $Date: 2006-11-22 10:58:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_desktop.hxx\"\n\n#include \"dp_gui.h\"\n#include \"cppuhelper\/implbase2.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"unotools\/configmgr.hxx\"\n#include \"comphelper\/servicedecl.hxx\"\n#include \"comphelper\/unwrapargs.hxx\"\n#include <i18npool\/mslangid.hxx>\n#include \"vcl\/svapp.hxx\"\n#include \"vcl\/msgbox.hxx\"\n#include \"com\/sun\/star\/lang\/XServiceInfo.hpp\"\n#include \"com\/sun\/star\/task\/XJobExecutor.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XAsynchronousExecutableDialog.hpp\"\n\n#include \"boost\/bind.hpp\"\n#include \"license_dialog.hxx\"\n\nusing namespace ::dp_misc;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing ::rtl::OUString;\n\nnamespace dp_gui {\n\n\/\/==============================================================================\nclass MyApp : public Application, private boost::noncopyable\n{\npublic:\n MyApp();\n virtual ~MyApp();\n\n \/\/ Application\n virtual void Main();\n};\n\n\/\/______________________________________________________________________________\nMyApp::~MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nMyApp::MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid MyApp::Main()\n{\n}\n\n\/\/##############################################################################\n\n\/\/==============================================================================\nclass ServiceImpl\n : public ::cppu::WeakImplHelper2<ui::dialogs::XAsynchronousExecutableDialog,\n task::XJobExecutor>\n{\n Reference<XComponentContext> const m_xComponentContext;\n boost::optional< Reference<awt::XWindow> > \/* const *\/ m_parent;\n boost::optional<OUString> \/* const *\/ m_view;\n OUString m_initialTitle;\n\npublic:\n ServiceImpl( Sequence<Any> const & args,\n Reference<XComponentContext> const & xComponentContext );\n\n \/\/ XAsynchronousExecutableDialog\n virtual void SAL_CALL setDialogTitle( OUString const & aTitle )\n throw (RuntimeException);\n virtual void SAL_CALL startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException);\n\n \/\/ XJobExecutor\n virtual void SAL_CALL trigger( OUString const & event )\n throw (RuntimeException);\n};\n\n\/\/______________________________________________________________________________\nServiceImpl::ServiceImpl( Sequence<Any> const& args,\n Reference<XComponentContext> const& xComponentContext)\n : m_xComponentContext(xComponentContext)\n{\n comphelper::unwrapArgs( args, m_parent, m_view );\n}\n\n\/\/ XAsynchronousExecutableDialog\n\/\/______________________________________________________________________________\nvoid ServiceImpl::setDialogTitle( OUString const & title )\n throw (RuntimeException)\n{\n if (::dp_gui::DialogImpl::s_dialog.is()) {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::dp_gui::DialogImpl::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference<awt::XWindow>(),\n m_view ? *m_view : OUString() )->SetText( title );\n }\n else\n m_initialTitle = title;\n}\n\n\/\/______________________________________________________________________________\nvoid ServiceImpl::startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException)\n{\n ::std::auto_ptr<Application> app;\n if (! dp_gui::DialogImpl::s_dialog.is())\n {\n const bool bAppUp = (GetpApp() != 0);\n bool bOfficePipePresent;\n try {\n bOfficePipePresent = dp_misc::office_is_running();\n }\n catch (Exception & exc) {\n if (bAppUp) {\n const vos::OGuard guard( Application::GetSolarMutex() );\n std::auto_ptr<ErrorBox> box(\n new ErrorBox( Application::GetActiveTopWindow(),\n WB_OK, exc.Message ) );\n box->Execute();\n }\n throw;\n }\n\n if (! bOfficePipePresent) {\n OSL_ASSERT( ! bAppUp );\n app.reset( new MyApp );\n if (! InitVCL( Reference<lang::XMultiServiceFactory>(\n m_xComponentContext->getServiceManager(),\n UNO_QUERY_THROW ) ))\n throw RuntimeException( OUSTR(\"Cannot initialize VCL!\"),\n static_cast<OWeakObject *>(this) );\n AllSettings as = app->GetSettings();\n OUString slang;\n if (! (::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::LOCALE ) >>= slang))\n throw RuntimeException( OUSTR(\"Cannot determine language!\"),\n static_cast<OWeakObject *>(this) );\n as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );\n app->SetSettings( as );\n }\n }\n\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::DialogImpl > dialog(\n ::dp_gui::DialogImpl::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference<awt::XWindow>(),\n m_view ? *m_view : OUString() ) );\n if (m_initialTitle.getLength() > 0) {\n dialog->SetText( m_initialTitle );\n m_initialTitle = OUString();\n }\n dialog->Show();\n dialog->ToTop( TOTOP_RESTOREWHENMIN );\n }\n\n if (app.get() != 0) {\n Application::Execute();\n DeInitVCL();\n }\n\n if (xListener.is())\n xListener->dialogClosed(\n ui::dialogs::DialogClosedEvent(\n static_cast< ::cppu::OWeakObject * >(this),\n sal_Int16(0)) );\n}\n\n\/\/ XJobExecutor\n\/\/______________________________________________________________________________\nvoid ServiceImpl::trigger( OUString const & ) throw (RuntimeException)\n{\n startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );\n}\n\nnamespace sdecl = comphelper::service_decl;\nsdecl::class_<ServiceImpl, sdecl::with_args<true> > serviceSI;\nsdecl::ServiceDecl const serviceDecl(\n serviceSI,\n \"com.sun.star.comp.deployment.ui.PackageManagerDialog\",\n \"com.sun.star.deployment.ui.PackageManagerDialog\" );\n\nsdecl::class_<LicenseDialog, sdecl::with_args<true> > licenseSI;\nsdecl::ServiceDecl const licenseDecl(\n licenseSI,\n \"com.sun.star.comp.deployment.ui.LicenseDialog\",\n \"com.sun.star.deployment.ui.LicenseDialog\" );\n} \/\/ namespace dp_gui\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nsal_Bool SAL_CALL component_writeInfo(\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_writeInfoHelper(\n pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl );\n}\n\nvoid * SAL_CALL component_getFactory(\n sal_Char const * pImplName,\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_getFactoryHelper(\n pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl );\n}\n\n} \/\/ extern \"C\"\n<commit_msg>INTEGRATION: CWS jl46 (1.12.34); FILE MERGED 2006\/12\/04 18:03:12 jl 1.12.34.4: RESYNC: (1.13-1.15); FILE MERGED 2006\/10\/27 15:17:49 jl 1.12.34.3: #69173# message when another unopkg is running 2006\/10\/10 17:00:46 jl 1.12.34.2: RESYNC: (1.12-1.13); FILE MERGED 2006\/09\/15 13:05:41 jl 1.12.34.1: #i69173# adding gui + extension mode<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dp_gui_service.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: ihi $ $Date: 2006-12-19 11:43:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_desktop.hxx\"\n\n#include \"dp_gui_shared.hxx\"\n#include \"dp_gui.h\"\n#include \"cppuhelper\/implbase2.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"unotools\/configmgr.hxx\"\n#include \"comphelper\/servicedecl.hxx\"\n#include \"comphelper\/unwrapargs.hxx\"\n#include <i18npool\/mslangid.hxx>\n#include \"vcl\/svapp.hxx\"\n#include \"vcl\/msgbox.hxx\"\n#include \"com\/sun\/star\/lang\/XServiceInfo.hpp\"\n#include \"com\/sun\/star\/task\/XJobExecutor.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XAsynchronousExecutableDialog.hpp\"\n\n#include \"boost\/bind.hpp\"\n#include \"license_dialog.hxx\"\n\nusing namespace ::dp_misc;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nusing ::rtl::OUString;\n\nnamespace css = ::com::sun::star;\nnamespace dp_gui {\n\n\/\/==============================================================================\nclass MyApp : public Application, private boost::noncopyable\n{\npublic:\n MyApp();\n virtual ~MyApp();\n\n \/\/ Application\n virtual void Main();\n};\n\n\/\/______________________________________________________________________________\nMyApp::~MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nMyApp::MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid MyApp::Main()\n{\n}\n\n\/\/##############################################################################\n\n\/\/==============================================================================\nclass ServiceImpl\n : public ::cppu::WeakImplHelper2<ui::dialogs::XAsynchronousExecutableDialog,\n task::XJobExecutor>\n{\n Reference<XComponentContext> const m_xComponentContext;\n boost::optional< Reference<awt::XWindow> > \/* const *\/ m_parent;\n boost::optional<OUString> \/* const *\/ m_view;\n boost::optional<Sequence<OUString> > m_extensions;\n OUString m_initialTitle;\n\npublic:\n ServiceImpl( Sequence<Any> const & args,\n Reference<XComponentContext> const & xComponentContext );\n\n \/\/ XAsynchronousExecutableDialog\n virtual void SAL_CALL setDialogTitle( OUString const & aTitle )\n throw (RuntimeException);\n virtual void SAL_CALL startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException);\n\n \/\/ XJobExecutor\n virtual void SAL_CALL trigger( OUString const & event )\n throw (RuntimeException);\n};\n\n\/\/______________________________________________________________________________\nServiceImpl::ServiceImpl( Sequence<Any> const& args,\n Reference<XComponentContext> const& xComponentContext)\n : m_xComponentContext(xComponentContext)\n{\n try {\n comphelper::unwrapArgs( args, m_parent, m_view );\n return;\n } catch (css::lang::IllegalArgumentException & ) {\n }\n try {\n comphelper::unwrapArgs( args, m_extensions, m_view );\n } catch (css::lang::IllegalArgumentException & ) {\n }\n\n}\n\n\/\/ XAsynchronousExecutableDialog\n\/\/______________________________________________________________________________\nvoid ServiceImpl::setDialogTitle( OUString const & title )\n throw (RuntimeException)\n{\n if (::dp_gui::DialogImpl::s_dialog.is()) {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::dp_gui::DialogImpl::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference<awt::XWindow>(),\n m_extensions ? *m_extensions : Sequence<OUString>(),\n m_view ? *m_view : OUString() )->SetText( title );\n }\n else\n m_initialTitle = title;\n}\n\n\/\/______________________________________________________________________________\nvoid ServiceImpl::startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException)\n{\n ::std::auto_ptr<Application> app;\n if (! dp_gui::DialogImpl::s_dialog.is())\n {\n const bool bAppUp = (GetpApp() != 0);\n bool bOfficePipePresent;\n try {\n bOfficePipePresent = dp_misc::office_is_running();\n }\n catch (Exception & exc) {\n if (bAppUp) {\n const vos::OGuard guard( Application::GetSolarMutex() );\n std::auto_ptr<ErrorBox> box(\n new ErrorBox( Application::GetActiveTopWindow(),\n WB_OK, exc.Message ) );\n box->Execute();\n }\n throw;\n }\n\n if (! bOfficePipePresent) {\n OSL_ASSERT( ! bAppUp );\n app.reset( new MyApp );\n if (! InitVCL( Reference<lang::XMultiServiceFactory>(\n m_xComponentContext->getServiceManager(),\n UNO_QUERY_THROW ) ))\n throw RuntimeException( OUSTR(\"Cannot initialize VCL!\"),\n static_cast<OWeakObject *>(this) );\n AllSettings as = app->GetSettings();\n OUString slang;\n if (! (::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::LOCALE ) >>= slang))\n throw RuntimeException( OUSTR(\"Cannot determine language!\"),\n static_cast<OWeakObject *>(this) );\n as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );\n app->SetSettings( as );\n }\n }\n else\n {\n \/\/Currently we do not support the case that if the Extension Manager is\n \/\/open in an office an unopkg can be executed. This should be fixed in the future.\n ResId warnId(WARNINGBOX_CONCURRENTINSTANCE,DeploymentGuiResMgr::get() );\n WarningBox warn(NULL, warnId);\n warn.Execute();\n }\n\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::DialogImpl > dialog(\n ::dp_gui::DialogImpl::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference<awt::XWindow>(),\n m_extensions ? *m_extensions : Sequence<OUString>(),\n m_view ? *m_view : OUString() ) );\n if (m_initialTitle.getLength() > 0) {\n dialog->SetText( m_initialTitle );\n m_initialTitle = OUString();\n }\n dialog->Show();\n dialog->ToTop( TOTOP_RESTOREWHENMIN );\n }\n\n if (app.get() != 0) {\n Application::Execute();\n DeInitVCL();\n }\n\n if (xListener.is())\n xListener->dialogClosed(\n ui::dialogs::DialogClosedEvent(\n static_cast< ::cppu::OWeakObject * >(this),\n sal_Int16(0)) );\n}\n\n\/\/ XJobExecutor\n\/\/______________________________________________________________________________\nvoid ServiceImpl::trigger( OUString const & ) throw (RuntimeException)\n{\n startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );\n}\n\nnamespace sdecl = comphelper::service_decl;\nsdecl::class_<ServiceImpl, sdecl::with_args<true> > serviceSI;\nsdecl::ServiceDecl const serviceDecl(\n serviceSI,\n \"com.sun.star.comp.deployment.ui.PackageManagerDialog\",\n \"com.sun.star.deployment.ui.PackageManagerDialog\" );\n\nsdecl::class_<LicenseDialog, sdecl::with_args<true> > licenseSI;\nsdecl::ServiceDecl const licenseDecl(\n licenseSI,\n \"com.sun.star.comp.deployment.ui.LicenseDialog\",\n \"com.sun.star.deployment.ui.LicenseDialog\" );\n} \/\/ namespace dp_gui\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nsal_Bool SAL_CALL component_writeInfo(\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_writeInfoHelper(\n pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl );\n}\n\nvoid * SAL_CALL component_getFactory(\n sal_Char const * pImplName,\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_getFactoryHelper(\n pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl );\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file nbc_main.cc\n * \n * This program test drives the Simple Naive Bayes Classifier\n * \n * This classifier does parametric naive bayes classification\n * assuming that the features are sampled from a Gaussian\n * distribution.\n *\n * PARAMETERS TO BE INPUT:\n * \n * --train \n * This is the file that contains the training data\n *\n * --nbc\/classes\n * This is the number of classes present in the training data\n *\n * --test\n * This file contains the data points which the trained\n * classifier would classify\n *\n * --output\n * This file will contain the classes to which the corresponding\n * data points in the testing data \n * \n *\/\n#include \"simple_nbc.h\"\n\n#include <armadillo>\n#include <fastlib\/base\/arma_compat.h>\n\n#include <iostream>\n#include <fstream>\n\nconst fx_entry_doc parm_nbc_main_entries[] = {\n {\"train\", FX_REQUIRED, FX_STR, NULL,\n \" A file containing the training set\\n\"},\n {\"test\", FX_REQUIRED, FX_STR, NULL,\n \" A file containing the test set\\n\"},\n {\"output\", FX_PARAM, FX_STR, NULL,\n \" The file in which the output of the test would be \"\n \"written (defaults to 'output.csv')\\n\"},\n FX_ENTRY_DOC_DONE\n};\n\nconst fx_submodule_doc parm_nbc_main_submodules[] = {\n {\"nbc\", &parm_nbc_doc,\n \" Trains on a given set and number of classes and \"\n \"tests them on a given set\\n\"},\n FX_SUBMODULE_DOC_DONE\n};\n\nconst fx_module_doc parm_nbc_main_doc = {\n parm_nbc_main_entries, parm_nbc_main_submodules,\n \"This program test drives the Parametric Naive Bayes \\n\"\n \"Classifier assuming that the features are sampled \\n\"\n \"from a Gaussian distribution.\\n\"\n};\n\nint main(int argc, char* argv[]) {\n\n fx_module *root = fx_init(argc, argv, &parm_nbc_main_doc);\n\n \/\/\/\/\/\/ READING PARAMETERS AND LOADING DATA \/\/\/\/\/\/\n\n const char *training_data_filename = fx_param_str_req(root, \"train\");\n arma::mat training_data;\n data::Load(training_data_filename, training_data);\n\n const char *testing_data_filename = fx_param_str_req(root, \"test\");\n arma::mat testing_data;\n data::Load(testing_data_filename, testing_data);\n\n \/\/\/\/\/\/ SIMPLE NAIVE BAYES CLASSIFICATION ASSUMING THE DATA TO BE UNIFORMLY DISTRIBUTED \/\/\/\/\/\/\n\n \/\/\/\/\/\/ Declaration of an object of the class SimpleNaiveBayesClassifier\n SimpleNaiveBayesClassifier nbc;\n\n struct datanode* nbc_module = fx_submodule(root, \"nbc\");\n \n \/\/\/\/\/\/ Timing the training of the Naive Bayes Classifier \/\/\/\/\/\/\n fx_timer_start(nbc_module, \"training\");\n\n \/\/\/\/\/\/ Calling the function that trains the classifier\n nbc.InitTrain(training_data, nbc_module);\n\n fx_timer_stop(nbc_module, \"training\");\n\n \/\/\/\/\/\/ Timing the testing of the Naive Bayes Classifier \/\/\/\/\/\/\n \/\/\/\/\/\/ The variable that contains the result of the classification\n arma::vec results;\n\n fx_timer_start(nbc_module, \"testing\");\n\n \/\/\/\/\/\/ Calling the function that classifies the test data\n nbc.Classify(testing_data, &results);\n\n fx_timer_stop(nbc_module, \"testing\");\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n std::string output_filename = fx_param_str(root, \"output\", \"output.csv\");\n\n std::ofstream output_file (output_filename.c_str());\n if(output_file.is_open()) {\n output_file << results;\n }\n output_file.close();\n\n fx_done(root);\n\n return 1;\n}\n<commit_msg>Uses data::Save to save as a CSV file<commit_after>\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file nbc_main.cc\n * \n * This program test drives the Simple Naive Bayes Classifier\n * \n * This classifier does parametric naive bayes classification\n * assuming that the features are sampled from a Gaussian\n * distribution.\n *\n * PARAMETERS TO BE INPUT:\n * \n * --train \n * This is the file that contains the training data\n *\n * --nbc\/classes\n * This is the number of classes present in the training data\n *\n * --test\n * This file contains the data points which the trained\n * classifier would classify\n *\n * --output\n * This file will contain the classes to which the corresponding\n * data points in the testing data \n * \n *\/\n#include \"simple_nbc.h\"\n\n#include <armadillo>\n#include <fastlib\/data\/dataset.h> \n#include <fastlib\/base\/arma_compat.h>\n\n#include <iostream>\n#include <fstream>\n\nconst fx_entry_doc parm_nbc_main_entries[] = {\n {\"train\", FX_REQUIRED, FX_STR, NULL,\n \" A file containing the training set\\n\"},\n {\"test\", FX_REQUIRED, FX_STR, NULL,\n \" A file containing the test set\\n\"},\n {\"output\", FX_PARAM, FX_STR, NULL,\n \" The file in which the output of the test would be \"\n \"written (defaults to 'output.csv')\\n\"},\n FX_ENTRY_DOC_DONE\n};\n\nconst fx_submodule_doc parm_nbc_main_submodules[] = {\n {\"nbc\", &parm_nbc_doc,\n \" Trains on a given set and number of classes and \"\n \"tests them on a given set\\n\"},\n FX_SUBMODULE_DOC_DONE\n};\n\nconst fx_module_doc parm_nbc_main_doc = {\n parm_nbc_main_entries, parm_nbc_main_submodules,\n \"This program test drives the Parametric Naive Bayes \\n\"\n \"Classifier assuming that the features are sampled \\n\"\n \"from a Gaussian distribution.\\n\"\n};\n\nint main(int argc, char* argv[]) {\n\n fx_module *root = fx_init(argc, argv, &parm_nbc_main_doc);\n\n \/\/\/\/\/\/ READING PARAMETERS AND LOADING DATA \/\/\/\/\/\/\n\n const char *training_data_filename = fx_param_str_req(root, \"train\");\n arma::mat training_data;\n data::Load(training_data_filename, training_data);\n\n const char *testing_data_filename = fx_param_str_req(root, \"test\");\n arma::mat testing_data;\n data::Load(testing_data_filename, testing_data);\n\n \/\/\/\/\/\/ SIMPLE NAIVE BAYES CLASSIFICATION ASSUMING THE DATA TO BE UNIFORMLY DISTRIBUTED \/\/\/\/\/\/\n\n \/\/\/\/\/\/ Declaration of an object of the class SimpleNaiveBayesClassifier\n SimpleNaiveBayesClassifier nbc;\n\n struct datanode* nbc_module = fx_submodule(root, \"nbc\");\n \n \/\/\/\/\/\/ Timing the training of the Naive Bayes Classifier \/\/\/\/\/\/\n fx_timer_start(nbc_module, \"training\");\n\n \/\/\/\/\/\/ Calling the function that trains the classifier\n nbc.InitTrain(training_data, nbc_module);\n\n fx_timer_stop(nbc_module, \"training\");\n\n \/\/\/\/\/\/ Timing the testing of the Naive Bayes Classifier \/\/\/\/\/\/\n \/\/\/\/\/\/ The variable that contains the result of the classification\n arma::vec results;\n\n fx_timer_start(nbc_module, \"testing\");\n\n \/\/\/\/\/\/ Calling the function that classifies the test data\n nbc.Classify(testing_data, &results);\n\n fx_timer_stop(nbc_module, \"testing\");\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n std::string output_filename = fx_param_str(root, \"output\", \"output.csv\");\n\n data::Save(output_filename.c_str(), results);\n\n fx_done(root);\n\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <array>\r\n#include <vector>\r\n#include <fstream>\r\n\r\n#include \"png\/png.h\"\r\n#include \"png\/zlib.h\"\r\n\r\n#include \"ArcV\/Processing\/Image.hpp\"\r\n\r\nnamespace Arcv {\r\n\r\nnamespace {\r\n\r\nbool validatePng(std::istream& file) {\r\n std::array<png_byte, PNG_HEADER_SIZE> header;\r\n\r\n file.read(reinterpret_cast<char*>(header.data()), PNG_HEADER_SIZE);\r\n\r\n return (png_sig_cmp(header.data(), 0, PNG_HEADER_SIZE) == 0);\r\n}\r\n\r\nvoid readPng(png_structp pngReadPtr, png_bytep data, png_size_t length) {\r\n png_voidp inPtr = png_get_io_ptr(pngReadPtr);\r\n static_cast<std::istream*>(inPtr)->read(reinterpret_cast<char*>(data), length);\r\n}\r\n\r\nvoid writePng(png_structp pngWritePtr, png_bytep data, png_size_t length) {\r\n png_voidp outPtr = png_get_io_ptr(pngWritePtr);\r\n static_cast<std::ostream*>(outPtr)->write(reinterpret_cast<const char*>(data), length);\r\n}\r\n\r\n} \/\/ namespace\r\n\r\nMatrix<> Image::read(const std::string& fileName) {\r\n std::ifstream file(fileName, std::ios_base::in | std::ios_base::binary);\r\n assert((\"Error: Not a valid PNG\", file.good() && validatePng(file)));\r\n\r\n png_structp pngReadStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\r\n assert((\"Error: Couldn't initialize PNG read struct\", pngReadStruct));\r\n\r\n png_infop pngInfoStruct = png_create_info_struct(pngReadStruct);\r\n assert((\"Error: Couldn't initialize PNG info struct\", pngInfoStruct));\r\n\r\n png_set_read_fn(pngReadStruct, &file, readPng);\r\n\r\n \/\/ Setting the amount signature bytes we've already read\r\n png_set_sig_bytes(pngReadStruct, PNG_HEADER_SIZE);\r\n\r\n png_read_info(pngReadStruct, pngInfoStruct);\r\n\r\n uint32_t width = static_cast<uint32_t>(png_get_image_width(pngReadStruct, pngInfoStruct));\r\n uint32_t height = static_cast<uint32_t>(png_get_image_height(pngReadStruct, pngInfoStruct));\r\n uint32_t bitDepth = png_get_bit_depth(pngReadStruct, pngInfoStruct);\r\n uint8_t channels = png_get_channels(pngReadStruct, pngInfoStruct);\r\n uint8_t colorType = png_get_color_type(pngReadStruct, pngInfoStruct);\r\n Colorspace colorspace;\r\n\r\n switch (colorType) {\r\n case PNG_COLOR_TYPE_GRAY:\r\n if (bitDepth < 8)\r\n png_set_expand_gray_1_2_4_to_8(pngReadStruct);\r\n colorspace = ARCV_COLORSPACE_GRAY;\r\n bitDepth = 8;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_GRAY_ALPHA:\r\n colorspace = ARCV_COLORSPACE_GRAY_ALPHA;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_PALETTE:\r\n png_set_palette_to_rgb(pngReadStruct);\r\n colorspace = ARCV_COLORSPACE_RGB;\r\n channels = 3;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_RGB:\r\n default:\r\n colorspace = ARCV_COLORSPACE_RGB;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_RGB_ALPHA:\r\n colorspace = ARCV_COLORSPACE_RGBA;\r\n break;\r\n }\r\n\r\n png_set_scale_16(pngReadStruct);\r\n\r\n \/\/ Adding full alpha channel to the image if it possesses transparency\r\n if (png_get_valid(pngReadStruct, pngInfoStruct, PNG_INFO_tRNS)) {\r\n png_set_tRNS_to_alpha(pngReadStruct);\r\n channels += 1;\r\n }\r\n\r\n png_read_update_info(pngReadStruct, pngInfoStruct);\r\n\r\n Matrix<uint8_t> mat(width, height, channels, static_cast<uint8_t>(bitDepth), colorspace);\r\n\r\n std::vector<png_bytep> rowPtrs(height);\r\n\r\n \/\/ Defining an array to contain image's pixels\r\n mat.getData().resize(width * height * channels);\r\n\r\n \/\/ Mapping row's elements to data's\r\n for (uint32_t i = 0; i < height; ++i) {\r\n rowPtrs[i] = &mat.getData()[width * channels * i];\r\n }\r\n\r\n png_read_image(pngReadStruct, rowPtrs.data());\r\n png_read_end(pngReadStruct, pngInfoStruct);\r\n png_destroy_read_struct(&pngReadStruct, 0, static_cast<const png_infopp>(0));\r\n\r\n return Matrix<>(mat);\r\n}\r\n\r\nvoid Image::write(const Matrix<>& mat, const std::string& fileName) {\r\n std::ofstream file(fileName);\r\n const Matrix<uint8_t> matToWrite(mat);\r\n\r\n png_structp pngWriteStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\r\n assert((\"Error: Couldn't initialize PNG write struct\", pngWriteStruct));\r\n\r\n png_infop pngInfoStruct = png_create_info_struct(pngWriteStruct);\r\n assert((\"Error: Couldn't initialize PNG info struct\", pngInfoStruct));\r\n\r\n uint32_t colorType;\r\n unsigned short channels = 0;\r\n switch (matToWrite.getColorspace()) {\r\n case ARCV_COLORSPACE_GRAY:\r\n colorType = PNG_COLOR_TYPE_GRAY;\r\n channels = 1;\r\n break;\r\n\r\n case ARCV_COLORSPACE_GRAY_ALPHA:\r\n colorType = PNG_COLOR_TYPE_GRAY_ALPHA;\r\n channels = 2;\r\n break;\r\n\r\n case ARCV_COLORSPACE_RGB:\r\n case ARCV_COLORSPACE_HSV:\r\n default:\r\n colorType = PNG_COLOR_TYPE_RGB;\r\n channels = 3;\r\n break;\r\n\r\n case ARCV_COLORSPACE_RGBA:\r\n colorType = PNG_COLOR_TYPE_RGBA;\r\n channels = 4;\r\n break;\r\n }\r\n\r\n png_set_compression_level(pngWriteStruct, 6);\r\n\r\n if (channels * matToWrite.getImgBitDepth() >= 16) {\r\n png_set_compression_strategy(pngWriteStruct, Z_FILTERED);\r\n png_set_filter(pngWriteStruct, 0, PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH);\r\n } else {\r\n png_set_compression_strategy(pngWriteStruct, Z_DEFAULT_STRATEGY);\r\n }\r\n\r\n png_set_IHDR(pngWriteStruct,\r\n pngInfoStruct,\r\n matToWrite.getWidth(),\r\n matToWrite.getHeight(),\r\n matToWrite.getImgBitDepth(),\r\n colorType,\r\n PNG_INTERLACE_NONE,\r\n PNG_COMPRESSION_TYPE_BASE,\r\n PNG_FILTER_TYPE_BASE);\r\n\r\n png_set_write_fn(pngWriteStruct, &file, writePng, nullptr);\r\n png_write_info(pngWriteStruct, pngInfoStruct);\r\n\r\n for (uint32_t i = 0; i < matToWrite.getHeight(); ++i) {\r\n png_write_row(pngWriteStruct,\r\n &matToWrite.getData()[matToWrite.getWidth() * channels * i]);\r\n }\r\n\r\n png_write_end(pngWriteStruct, pngInfoStruct);\r\n png_destroy_write_struct(&pngWriteStruct, &pngInfoStruct);\r\n}\r\n\r\n} \/\/ namespace Arcv\r\n<commit_msg>[Update] Removed useless stuff in PNG's saving function<commit_after>#include <array>\r\n#include <vector>\r\n#include <fstream>\r\n\r\n#include \"png\/png.h\"\r\n#include \"png\/zlib.h\"\r\n\r\n#include \"ArcV\/Processing\/Image.hpp\"\r\n\r\nnamespace Arcv {\r\n\r\nnamespace {\r\n\r\nbool validatePng(std::istream& file) {\r\n std::array<png_byte, PNG_HEADER_SIZE> header;\r\n\r\n file.read(reinterpret_cast<char*>(header.data()), PNG_HEADER_SIZE);\r\n\r\n return (png_sig_cmp(header.data(), 0, PNG_HEADER_SIZE) == 0);\r\n}\r\n\r\nvoid readPng(png_structp pngReadPtr, png_bytep data, png_size_t length) {\r\n png_voidp inPtr = png_get_io_ptr(pngReadPtr);\r\n static_cast<std::istream*>(inPtr)->read(reinterpret_cast<char*>(data), length);\r\n}\r\n\r\nvoid writePng(png_structp pngWritePtr, png_bytep data, png_size_t length) {\r\n png_voidp outPtr = png_get_io_ptr(pngWritePtr);\r\n static_cast<std::ostream*>(outPtr)->write(reinterpret_cast<const char*>(data), length);\r\n}\r\n\r\n} \/\/ namespace\r\n\r\nMatrix<> Image::read(const std::string& fileName) {\r\n std::ifstream file(fileName, std::ios_base::in | std::ios_base::binary);\r\n assert((\"Error: Not a valid PNG\", file.good() && validatePng(file)));\r\n\r\n png_structp pngReadStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\r\n assert((\"Error: Couldn't initialize PNG read struct\", pngReadStruct));\r\n\r\n png_infop pngInfoStruct = png_create_info_struct(pngReadStruct);\r\n assert((\"Error: Couldn't initialize PNG info struct\", pngInfoStruct));\r\n\r\n png_set_read_fn(pngReadStruct, &file, readPng);\r\n\r\n \/\/ Setting the amount signature bytes we've already read\r\n png_set_sig_bytes(pngReadStruct, PNG_HEADER_SIZE);\r\n\r\n png_read_info(pngReadStruct, pngInfoStruct);\r\n\r\n uint32_t width = static_cast<uint32_t>(png_get_image_width(pngReadStruct, pngInfoStruct));\r\n uint32_t height = static_cast<uint32_t>(png_get_image_height(pngReadStruct, pngInfoStruct));\r\n uint32_t bitDepth = png_get_bit_depth(pngReadStruct, pngInfoStruct);\r\n uint8_t channels = png_get_channels(pngReadStruct, pngInfoStruct);\r\n uint8_t colorType = png_get_color_type(pngReadStruct, pngInfoStruct);\r\n Colorspace colorspace;\r\n\r\n switch (colorType) {\r\n case PNG_COLOR_TYPE_GRAY:\r\n if (bitDepth < 8)\r\n png_set_expand_gray_1_2_4_to_8(pngReadStruct);\r\n colorspace = ARCV_COLORSPACE_GRAY;\r\n bitDepth = 8;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_GRAY_ALPHA:\r\n colorspace = ARCV_COLORSPACE_GRAY_ALPHA;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_PALETTE:\r\n png_set_palette_to_rgb(pngReadStruct);\r\n colorspace = ARCV_COLORSPACE_RGB;\r\n channels = 3;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_RGB:\r\n default:\r\n colorspace = ARCV_COLORSPACE_RGB;\r\n break;\r\n\r\n case PNG_COLOR_TYPE_RGB_ALPHA:\r\n colorspace = ARCV_COLORSPACE_RGBA;\r\n break;\r\n }\r\n\r\n png_set_scale_16(pngReadStruct);\r\n\r\n \/\/ Adding full alpha channel to the image if it possesses transparency\r\n if (png_get_valid(pngReadStruct, pngInfoStruct, PNG_INFO_tRNS)) {\r\n png_set_tRNS_to_alpha(pngReadStruct);\r\n channels += 1;\r\n }\r\n\r\n png_read_update_info(pngReadStruct, pngInfoStruct);\r\n\r\n Matrix<uint8_t> mat(width, height, channels, static_cast<uint8_t>(bitDepth), colorspace);\r\n\r\n std::vector<png_bytep> rowPtrs(height);\r\n\r\n \/\/ Defining an array to contain image's pixels\r\n mat.getData().resize(width * height * channels);\r\n\r\n \/\/ Mapping row's elements to data's\r\n for (uint32_t i = 0; i < height; ++i) {\r\n rowPtrs[i] = &mat.getData()[width * channels * i];\r\n }\r\n\r\n png_read_image(pngReadStruct, rowPtrs.data());\r\n png_read_end(pngReadStruct, pngInfoStruct);\r\n png_destroy_read_struct(&pngReadStruct, 0, static_cast<const png_infopp>(0));\r\n\r\n return Matrix<>(mat);\r\n}\r\n\r\nvoid Image::write(const Matrix<>& mat, const std::string& fileName) {\r\n std::ofstream file(fileName);\r\n const Matrix<uint8_t> matToWrite(mat);\r\n\r\n png_structp pngWriteStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);\r\n assert((\"Error: Couldn't initialize PNG write struct\", pngWriteStruct));\r\n\r\n png_infop pngInfoStruct = png_create_info_struct(pngWriteStruct);\r\n assert((\"Error: Couldn't initialize PNG info struct\", pngInfoStruct));\r\n\r\n uint32_t colorType;\r\n switch (matToWrite.getColorspace()) {\r\n case ARCV_COLORSPACE_GRAY:\r\n colorType = PNG_COLOR_TYPE_GRAY;\r\n break;\r\n\r\n case ARCV_COLORSPACE_GRAY_ALPHA:\r\n colorType = PNG_COLOR_TYPE_GRAY_ALPHA;\r\n break;\r\n\r\n case ARCV_COLORSPACE_RGB:\r\n case ARCV_COLORSPACE_HSV:\r\n default:\r\n colorType = PNG_COLOR_TYPE_RGB;\r\n break;\r\n\r\n case ARCV_COLORSPACE_RGBA:\r\n colorType = PNG_COLOR_TYPE_RGBA;\r\n break;\r\n }\r\n\r\n png_set_compression_level(pngWriteStruct, 6);\r\n\r\n if (matToWrite.getChannelCount() * matToWrite.getImgBitDepth() >= 16) {\r\n png_set_compression_strategy(pngWriteStruct, Z_FILTERED);\r\n png_set_filter(pngWriteStruct, 0, PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH);\r\n } else {\r\n png_set_compression_strategy(pngWriteStruct, Z_DEFAULT_STRATEGY);\r\n }\r\n\r\n png_set_IHDR(pngWriteStruct,\r\n pngInfoStruct,\r\n matToWrite.getWidth(),\r\n matToWrite.getHeight(),\r\n matToWrite.getImgBitDepth(),\r\n colorType,\r\n PNG_INTERLACE_NONE,\r\n PNG_COMPRESSION_TYPE_BASE,\r\n PNG_FILTER_TYPE_BASE);\r\n\r\n png_set_write_fn(pngWriteStruct, &file, writePng, nullptr);\r\n png_write_info(pngWriteStruct, pngInfoStruct);\r\n\r\n for (uint32_t i = 0; i < matToWrite.getHeight(); ++i) {\r\n png_write_row(pngWriteStruct, &matToWrite.getData()[matToWrite.getWidth() * matToWrite.getChannelCount() * i]);\r\n }\r\n\r\n png_write_end(pngWriteStruct, pngInfoStruct);\r\n png_destroy_write_struct(&pngWriteStruct, &pngInfoStruct);\r\n}\r\n\r\n} \/\/ namespace Arcv\r\n<|endoftext|>"} {"text":"<commit_before>#include \"hornet\/java.hh\"\n\n#include \"hornet\/vm.hh\"\n\n#include <classfile_constants.h>\n#include <cassert>\n#include <stack>\n\nnamespace hornet {\n\nstatic inline uint16_t read_opc_u2(char *p)\n{\n return p[1] << 8 | p[2];\n}\n\nvoid interp(method* method)\n{\n std::valarray<object*> locals(method->max_locals);\n\n std::stack<object*> ostack;\n\n uint16_t pc = 0;\n\nnext_insn:\n assert(pc < method->code_length);\n\n uint8_t opc = method->code[pc];\n\n switch (opc) {\n case JVM_OPC_aload_0:\n case JVM_OPC_aload_1:\n case JVM_OPC_aload_2:\n case JVM_OPC_aload_3: {\n uint16_t idx = opc - JVM_OPC_aload_0;\n ostack.push(locals[idx]);\n break;\n }\n case JVM_OPC_pop: {\n ostack.pop();\n break;\n }\n case JVM_OPC_dup: {\n auto value = ostack.top();\n ostack.push(value);\n break;\n }\n case JVM_OPC_goto: {\n int16_t offset = read_opc_u2(method->code + pc);\n pc += offset;\n goto next_insn;\n }\n case JVM_OPC_return: {\n ostack.empty();\n return;\n }\n case JVM_OPC_invokespecial: {\n break;\n }\n case JVM_OPC_new: {\n auto obj = gc_new_object(nullptr);\n ostack.push(obj);\n break;\n }\n default:\n fprintf(stderr, \"error: unsupported bytecode: %u\\n\", opc);\n abort();\n }\n\n pc += opcode_length[opc];\n\n goto next_insn;\n}\n\n}\n<commit_msg>interp: Switch to value type<commit_after>#include \"hornet\/java.hh\"\n\n#include \"hornet\/vm.hh\"\n\n#include <classfile_constants.h>\n#include <cassert>\n#include <stack>\n\nnamespace hornet {\n\nstatic inline uint16_t read_opc_u2(char *p)\n{\n return p[1] << 8 | p[2];\n}\n\ntypedef uint64_t value_t;\n\nvalue_t object_to_value(object* obj)\n{\n return reinterpret_cast<value_t>(obj);\n}\n\nvalue_t int32_to_value(int32_t n)\n{\n return static_cast<value_t>(n);\n}\n\nvoid interp(method* method)\n{\n std::valarray<value_t> locals(method->max_locals);\n\n std::stack<value_t> ostack;\n\n uint16_t pc = 0;\n\nnext_insn:\n assert(pc < method->code_length);\n\n uint8_t opc = method->code[pc];\n\n switch (opc) {\n case JVM_OPC_aload_0:\n case JVM_OPC_aload_1:\n case JVM_OPC_aload_2:\n case JVM_OPC_aload_3: {\n uint16_t idx = opc - JVM_OPC_aload_0;\n ostack.push(locals[idx]);\n break;\n }\n case JVM_OPC_pop: {\n ostack.pop();\n break;\n }\n case JVM_OPC_dup: {\n auto value = ostack.top();\n ostack.push(value);\n break;\n }\n case JVM_OPC_goto: {\n int16_t offset = read_opc_u2(method->code + pc);\n pc += offset;\n goto next_insn;\n }\n case JVM_OPC_return: {\n ostack.empty();\n return;\n }\n case JVM_OPC_invokespecial: {\n break;\n }\n case JVM_OPC_new: {\n auto obj = gc_new_object(nullptr);\n ostack.push(object_to_value(obj));\n break;\n }\n default:\n fprintf(stderr, \"error: unsupported bytecode: %u\\n\", opc);\n abort();\n }\n\n pc += opcode_length[opc];\n\n goto next_insn;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/string-split.hh\"\n#include \"acmacs-base\/read-file.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/factory-export.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\" && path.stem().extension() == \".acd1\")\n return true;\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::chart::Name;\n using Passage = acmacs::virus::Passage;\n using Reassortant = acmacs::virus::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_string_t<struct SerumIdRootTag>;\n using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;\n using TableEntry = std::tuple<acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;\n using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies,\n acmacs::chart::TableDate, Passage>;\n using Entries = std::vector<Entry>;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple<EntryPtr, EntryPtr>;\n using PerSerumIdRootEntry = std::tuple<EntryPtr, EntryPtr, std::vector<PerSerumIdEntry>>;\n using PerSerumIdRootEntries = std::vector<PerSerumIdRootEntry>;\n\n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n\n \/\/ returns number of files processed\n size_t scan_directory(std::string dirname)\n {\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n auto chart = acmacs::chart::import_from_file(pathname);\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n ++charts_processed;\n }\n }\n sort();\n scan();\n return charts_processed;\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get<acmacs::chart::VirusType>(*std::get<0>(per_root_.front())) == \"A(H3N2)\";\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << fmt::format(\"{} {}\\n\", std::get<SerumIdRoot>(*std::get<0>(per_root_entry)), std::get<1>(per_root_entry) - std::get<0>(per_root_entry));\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << fmt::format(\" {} {} [{}]\", std::get<SerumId>(*std::get<0>(per_serum_id_entry)), tabs.size(), make_name(std::get<0>(per_serum_id_entry)));\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get<SerumId>(*std::get<0>(sids.front())) != std::get<SerumId>(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(),\n [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n std::cout << \" --fix \";\n const auto sid1 = std::get<SerumId>(*std::get<0>(*ep)), sid2 = std::get<SerumId>(*std::get<0>(*sid));\n if ((std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid)) && sid2.size() < sid1.size())\n std::cout << sid2 << '^' << sid1;\n else\n std::cout << sid1 << '^' << sid2;\n std::cout << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum), std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),\n std::get<acmacs::chart::VirusType>(table), std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table),\n std::get<acmacs::chart::TableDate>(table), std::get<Passage>(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get<SerumIdRoot>(*entry_ptr) != std::get<SerumIdRoot>(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector<PerSerumIdEntry>{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get<SerumId>(*entry_ptr) != std::get<SerumId>(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get<SerumId>(serum);\n if (std::get<acmacs::chart::Lab>(table) == \"MELB\") {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R' || serum_id[0] == 'A') && serum_id[5] == '-' && serum_id.back() == 'D')\n return SerumIdRoot(serum_id.substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr) { return string::join({std::get<Name>(*ptr), std::get<Reassortant>(*ptr), string::join(\" \", std::get<Annotations>(*ptr))}); }\n\n static inline std::vector<std::string> tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector<std::string> tables(static_cast<size_t>(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector<std::string> fields;\n if (assay)\n fields.push_back(*std::get<acmacs::chart::Assay>(entry));\n if (rbc)\n fields.push_back(*std::get<acmacs::chart::RbcSpecies>(entry));\n fields.push_back(*std::get<acmacs::chart::TableDate>(entry));\n return string::join(\":\", fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n}; \/\/ class SerumIds\n\n\/\/ ======================================================================\n\nclass FixSerumIds\n{\n public:\n FixSerumIds(std::string_view program_name) : program_name_(program_name) {}\n void add_fix(std::string_view fix_entry)\n {\n const auto fields = acmacs::string::split(fix_entry, \"^\");\n data_.emplace_back(fields[0], fields[1]);\n }\n\n \/\/ returns number of files updated\n size_t fix_charts_in_directory(std::string dirname)\n {\n size_t fixed_charts = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(pathname));\n if (fix_in_chart(chart)) {\n acmacs::file::backup(pathname, acmacs::file::backup_move::yes);\n acmacs::chart::export_factory(chart, make_export_filename(pathname), fs::path(program_name_).filename(), report_time::no);\n ++fixed_charts;\n }\n }\n }\n return fixed_charts;\n }\n\n private:\n std::string_view program_name_;\n std::vector<std::pair<std::string, std::string>> data_;\n\n bool fix_in_chart(acmacs::chart::ChartModify& chart)\n {\n auto sera = chart.sera_modify();\n bool modified = false;\n for (size_t serum_no = 0; serum_no < sera->size(); ++ serum_no) {\n auto& serum = sera->at(serum_no);\n const auto sid = serum.serum_id();\n for (const auto& fix : data_) {\n if (sid == fix.first) {\n std::cout << chart.info()->make_name() << \" FIX \" << *serum.name() << ' ' << *serum.reassortant() << ' ' << string::join(\" \", serum.annotations()) << ' ' << serum.serum_id()\n << \" --> \" << fix.second << '\\n';\n serum.serum_id(fix.second);\n modified = true;\n break;\n }\n }\n }\n return modified;\n }\n\n fs::path make_export_filename(const fs::path& pathname) const\n {\n if (pathname.extension() == \".ace\")\n return pathname;\n if (pathname.extension() == \".bz2\" && pathname.stem().extension() == \".acd1\")\n return pathname.stem().stem() += \".ace\";\n throw std::runtime_error(\"cannot figure out export filename for: \" + pathname.string());\n }\n\n}; \/\/ class FixSerumIds\n\n\/\/ ======================================================================\n\nusing namespace acmacs::argv;\n\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n option<str_array> fix{*this, \"fix\"};\n \/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n \/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n \/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n \/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n std::vector<std::pair<std::string, std::string>> fix_data;\n if (opt.fix.has_value()) {\n FixSerumIds fix_serum_ids(opt.program_name());\n for (const auto& fix_entry : opt.fix.get())\n fix_serum_ids.add_fix(fix_entry);\n const auto charts_modified = fix_serum_ids.fix_charts_in_directory(\".\");\n std::cerr << \"INFO: charts modified: \" << charts_modified << '\\n';\n }\n else {\n SerumIds serum_ids;\n const auto charts_processed = serum_ids.scan_directory(\".\");\n std::cout << charts_processed << \" charts processed\\n\";\n serum_ids.print(false);\n }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>acmacs::chart::Date, Continent, SerumId, SerumSpecies are named_string_t based<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-base\/string-split.hh\"\n#include \"acmacs-base\/read-file.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/factory-export.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\" && path.stem().extension() == \".acd1\")\n return true;\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::chart::Name;\n using Passage = acmacs::virus::Passage;\n using Reassortant = acmacs::virus::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_string_t<struct SerumIdRootTag>;\n using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;\n using TableEntry = std::tuple<acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;\n using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies,\n acmacs::chart::TableDate, Passage>;\n using Entries = std::vector<Entry>;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple<EntryPtr, EntryPtr>;\n using PerSerumIdRootEntry = std::tuple<EntryPtr, EntryPtr, std::vector<PerSerumIdEntry>>;\n using PerSerumIdRootEntries = std::vector<PerSerumIdRootEntry>;\n\n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n\n \/\/ returns number of files processed\n size_t scan_directory(std::string dirname)\n {\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n auto chart = acmacs::chart::import_from_file(pathname);\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n ++charts_processed;\n }\n }\n sort();\n scan();\n return charts_processed;\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get<acmacs::chart::VirusType>(*std::get<0>(per_root_.front())) == \"A(H3N2)\";\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << fmt::format(\"{} {}\\n\", std::get<SerumIdRoot>(*std::get<0>(per_root_entry)), std::get<1>(per_root_entry) - std::get<0>(per_root_entry));\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << fmt::format(\" {} {} [{}]\", std::get<SerumId>(*std::get<0>(per_serum_id_entry)), tabs.size(), make_name(std::get<0>(per_serum_id_entry)));\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get<SerumId>(*std::get<0>(sids.front())) != std::get<SerumId>(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(),\n [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n std::cout << \" --fix \";\n const auto sid1 = std::get<SerumId>(*std::get<0>(*ep)), sid2 = std::get<SerumId>(*std::get<0>(*sid));\n if ((std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid)) && sid2.size() < sid1.size())\n std::cout << *sid2 << '^' << *sid1;\n else\n std::cout << *sid1 << '^' << *sid2;\n std::cout << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum), std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),\n std::get<acmacs::chart::VirusType>(table), std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table),\n std::get<acmacs::chart::TableDate>(table), std::get<Passage>(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get<SerumIdRoot>(*entry_ptr) != std::get<SerumIdRoot>(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector<PerSerumIdEntry>{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get<SerumId>(*entry_ptr) != std::get<SerumId>(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get<SerumId>(serum);\n if (std::get<acmacs::chart::Lab>(table) == \"MELB\") {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R' || serum_id[0] == 'A') && serum_id[5] == '-' && serum_id->back() == 'D')\n return SerumIdRoot(serum_id->substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr) { return string::join({std::get<Name>(*ptr), std::get<Reassortant>(*ptr), string::join(\" \", std::get<Annotations>(*ptr))}); }\n\n static inline std::vector<std::string> tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector<std::string> tables(static_cast<size_t>(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector<std::string> fields;\n if (assay)\n fields.push_back(*std::get<acmacs::chart::Assay>(entry));\n if (rbc)\n fields.push_back(*std::get<acmacs::chart::RbcSpecies>(entry));\n fields.push_back(*std::get<acmacs::chart::TableDate>(entry));\n return string::join(\":\", fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n}; \/\/ class SerumIds\n\n\/\/ ======================================================================\n\nclass FixSerumIds\n{\n public:\n FixSerumIds(std::string_view program_name) : program_name_(program_name) {}\n void add_fix(std::string_view fix_entry)\n {\n const auto fields = acmacs::string::split(fix_entry, \"^\");\n data_.emplace_back(fields[0], fields[1]);\n }\n\n \/\/ returns number of files updated\n size_t fix_charts_in_directory(std::string dirname)\n {\n size_t fixed_charts = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(pathname));\n if (fix_in_chart(chart)) {\n acmacs::file::backup(pathname, acmacs::file::backup_move::yes);\n acmacs::chart::export_factory(chart, make_export_filename(pathname), fs::path(program_name_).filename(), report_time::no);\n ++fixed_charts;\n }\n }\n }\n return fixed_charts;\n }\n\n private:\n std::string_view program_name_;\n std::vector<std::pair<std::string, std::string>> data_;\n\n bool fix_in_chart(acmacs::chart::ChartModify& chart)\n {\n auto sera = chart.sera_modify();\n bool modified = false;\n for (size_t serum_no = 0; serum_no < sera->size(); ++ serum_no) {\n auto& serum = sera->at(serum_no);\n const auto sid = serum.serum_id();\n for (const auto& fix : data_) {\n if (sid == fix.first) {\n std::cout << fmt::format(\"{} FIX {} {} {} {} --> {}\\n\", chart.info()->make_name(), serum.name(), serum.reassortant(), string::join(\" \", serum.annotations()), serum.serum_id(), fix.second);\n serum.serum_id(acmacs::chart::SerumId{fix.second});\n modified = true;\n break;\n }\n }\n }\n return modified;\n }\n\n fs::path make_export_filename(const fs::path& pathname) const\n {\n if (pathname.extension() == \".ace\")\n return pathname;\n if (pathname.extension() == \".bz2\" && pathname.stem().extension() == \".acd1\")\n return pathname.stem().stem() += \".ace\";\n throw std::runtime_error(\"cannot figure out export filename for: \" + pathname.string());\n }\n\n}; \/\/ class FixSerumIds\n\n\/\/ ======================================================================\n\nusing namespace acmacs::argv;\n\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n option<str_array> fix{*this, \"fix\"};\n \/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n \/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n \/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n \/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n std::vector<std::pair<std::string, std::string>> fix_data;\n if (opt.fix.has_value()) {\n FixSerumIds fix_serum_ids(opt.program_name());\n for (const auto& fix_entry : opt.fix.get())\n fix_serum_ids.add_fix(fix_entry);\n const auto charts_modified = fix_serum_ids.fix_charts_in_directory(\".\");\n std::cerr << \"INFO: charts modified: \" << charts_modified << '\\n';\n }\n else {\n SerumIds serum_ids;\n const auto charts_processed = serum_ids.scan_directory(\".\");\n std::cout << charts_processed << \" charts processed\\n\";\n serum_ids.print(false);\n }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/ using namespace acmacs::argv;\n\n\/\/ struct Options : public argv\n\/\/ {\n\/\/ Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n\/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n\/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n\/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n\/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n\/\/ };\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\") {\n if (path.stem().extension() == \".acd1\")\n return true;\n }\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstruct NameId\n{\n NameId(std::string n, std::string si, std::string d) : name(n), serum_id(si), date(d) {}\n bool operator<(const NameId& rhs) const { if (name == rhs.name) { if (serum_id == rhs.serum_id) return date < rhs.date; else return serum_id < rhs.serum_id; } else return name < rhs.name; }\n bool operator==(const NameId& rhs) const { return name == rhs.name && serum_id == rhs.serum_id && date == rhs.date; }\n bool operator!=(const NameId& rhs) const { return !operator==(rhs); }\n std::string name;\n std::string serum_id;\n std::string date;\n};\n\nstruct NameIds\n{\n NameIds(std::string n) : name(n) {}\n std::string name;\n std::vector<std::pair<std::string, size_t>> id_count;\n};\n\n\/\/ ----------------------------------------------------------------------\n\n\nint main(int \/*argc*\/, const char* \/*argv*\/[])\n{\n int exit_code = 0;\n try {\n \/\/ Options opt(argc, argv);\n std::vector<NameId> name_id;\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(\".\")) {\n if (entry.is_regular_file() && is_acmacs_file(entry.path())) {\n \/\/ std::cout << entry.path() << '\\n';\n auto chart = acmacs::chart::import_from_file(entry.path());\n const std::string date = chart->info()->date();\n auto sera = chart->sera();\n for (auto serum : *sera)\n name_id.emplace_back(serum->designation_without_serum_id(), serum->serum_id(), date);\n ++charts_processed;\n }\n }\n std::cout << charts_processed << \" charts processed\\n\";\n std::sort(name_id.begin(), name_id.end());\n \/\/ std::cout << name_id.size() << \" sera found\\n\";\n \/\/ name_id.erase(std::unique(name_id.begin(), name_id.end()), name_id.end());\n std::cout << name_id.size() << \" sera found\\n\";\n\n \/* std::vector<std::pair<std::string, std::vector<std::string>>> name_ids; *\/\n \/* for (const auto& entry : name_id) { *\/\n \/* if (name_ids.empty() || name_ids.back().first != entry.first) *\/\n \/* name_ids.emplace_back(entry.first, std::vector<std::string>{entry.second}); *\/\n \/* else *\/\n \/* name_ids.back().second.push_back(entry.second); *\/\n \/* } *\/\n \/* std::cout << name_ids.size() << \" serum names found\\n\"; *\/\n\n \/* for (const auto& entry : name_ids) { *\/\n \/* std::cout << entry.first << '\\n'; *\/\n \/* for (const auto& serum_id : entry.second) { *\/\n \/* std::cout << \" \" << serum_id; *\/\n \/* if (serum_id[0] == 'F' || serum_id[0] == 'R') { *\/\n \/* if (serum_id.back() != 'D') *\/\n \/* std::cout << \" Warning: FIX!\"; *\/\n \/* } *\/\n \/* else *\/\n \/* std::cout << \" Warning: not MELB\"; *\/\n \/* std::cout << '\\n'; *\/\n \/* } *\/\n \/* } *\/\n \n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>scan serum ids of MELB tables<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/ using namespace acmacs::argv;\n\n\/\/ struct Options : public argv\n\/\/ {\n\/\/ Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n\/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n\/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n\/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n\/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n\/\/ };\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\") {\n if (path.stem().extension() == \".acd1\")\n return true;\n }\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::chart::Name;\n using Passage = acmacs::chart::Passage;\n using Reassortant = acmacs::chart::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = std::string;\n using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;\n using TableEntry = std::tuple<>;\n \n SerumIds() = default;\n\n void add(const Name& name, const Reassortant& reassortant, const Annotations& annotations, const SerumId& serum_id, const Passage& passage);\n\n private:\n \/\/ std::map<SerumIdRoot, std::tuple<\n};\n\nstruct NameId\n{\n NameId(std::string n, std::string si, std::string d) : name(n), serum_id(si), date(d) {}\n bool operator<(const NameId& rhs) const { if (name == rhs.name) { if (serum_id == rhs.serum_id) return date < rhs.date; else return serum_id < rhs.serum_id; } else return name < rhs.name; }\n bool operator==(const NameId& rhs) const { return name == rhs.name && serum_id == rhs.serum_id && date == rhs.date; }\n bool operator!=(const NameId& rhs) const { return !operator==(rhs); }\n std::string name;\n std::string serum_id;\n std::string date;\n};\n\nstruct NameIds\n{\n NameIds(std::string n) : name(n) {}\n std::string name;\n std::vector<std::pair<std::string, size_t>> id_count;\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int \/*argc*\/, const char* \/*argv*\/[])\n{\n int exit_code = 0;\n try {\n \/\/ Options opt(argc, argv);\n std::vector<NameId> name_id;\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(\".\")) {\n if (entry.is_regular_file() && is_acmacs_file(entry.path())) {\n \/\/ std::cout << entry.path() << '\\n';\n auto chart = acmacs::chart::import_from_file(entry.path());\n const std::string date = chart->info()->date();\n auto sera = chart->sera();\n for (auto serum : *sera)\n name_id.emplace_back(serum->designation_without_serum_id(), serum->serum_id(), date);\n ++charts_processed;\n }\n }\n std::cout << charts_processed << \" charts processed\\n\";\n std::sort(name_id.begin(), name_id.end());\n \/\/ std::cout << name_id.size() << \" sera found\\n\";\n \/\/ name_id.erase(std::unique(name_id.begin(), name_id.end()),\n \/\/ name_id.end());\n std::cout << name_id.size() << \" sera found\\n\";\n\n \/\/ std::vector<std::pair<std::string, std::vector<std::string>>> name_ids;\n \/\/ for (const auto& entry : name_id) {\n \/\/ if (name_ids.empty() || name_ids.back().first != entry.first)\n \/\/ name_ids.emplace_back(entry.first, std::vector<std::string>{entry.second});\n \/\/ else\n \/\/ name_ids.back().second.push_back(entry.second);\n \/\/ }\n \/\/ std::cout << name_ids.size() << \" serum names found\\n\";\n\n \/\/ for (const auto& entry : name_ids) {\n \/\/ std::cout << entry.first << '\\n';\n \/\/ for (const auto& serum_id : entry.second) {\n \/\/ std::cout << \" \" << serum_id;\n \/\/ if (serum_id[0] == 'F' || serum_id[0] == 'R') {\n \/\/ if (serum_id.back() != 'D')\n \/\/ std::cout << \" Warning: FIX!\";\n \/\/ }\n \/\/ else\n \/\/ std::cout << \" Warning: not MELB\";\n \/\/ std::cout << '\\n';\n \/\/ }\n \/\/ }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include \"cmd.hpp\"\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\nCmd::Cmd ()\n{}\n\nCmd::Cmd(string input1)\n{\n\tuCmd = input1;\n\/\/\tcout << \"uCmd: \" << uCmd << endl;\n}\n\n\n\n\/\/where the magic happens\n\/\/uses fork and exec to execute commands and returns bool values to indicate a valid\/invalid command\nbool Cmd::execute(string cmd_s)\n{\n \n pid_t pid;\n char* args[2];\n args[0] = (char*)cmd_s.c_str();\n args[1] = NULL;\n pid = fork();\n\tint status;\n\n\tif (pid == -1)\n\t{\n\t\tperror(\"fork\");\n\t\texit(1);\n }\n if (pid == 0) \/\/ child process\n {\n if(execvp(args[0], args) == -1)\n {\n\t\t perror(\"exec\");\n\t\t exit(1);\n\t\t\t \n }\n\t\t valid = true;\n }\n else \/\/ parent process\n {\n\t\tif (wait(0) == -1)\n\t\t{\n\t\t\tperror(\"wait\");\n\t\t\texit(1);\n\t\t}\n\t\tif (WEXITSTATUS(status) != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n }\n\n\treturn true;\n\t \n}\n\n\n\n<commit_msg>added WEXITSTATUS<commit_after>#include \"cmd.hpp\"\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\nCmd::Cmd ()\n{}\n\nCmd::Cmd(string input1)\n{\n\tuCmd = input1;\n\/\/\tcout << \"uCmd: \" << uCmd << endl;\n}\n\n\n\n\/\/where the magic happens\n\/\/uses fork and exec to execute commands and returns bool values to indicate a valid\/invalid command\nbool Cmd::execute(string cmd_s)\n{\n \n pid_t pid;\n char* args[2];\n args[0] = (char*)cmd_s.c_str();\n args[1] = NULL;\n pid = fork();\n\tint status;\n\n\tif (pid == -1)\n\t{\n\t\tperror(\"fork\");\n\t\texit(1);\n }\n if (pid == 0) \/\/ child process\n {\n if(execvp(args[0], args) == -1)\n {\n\t\t perror(\"exec\");\n\t\t exit(1);\n\t\t\t \n }\n }\n else \/\/ parent process\n {\n\t\tif (wait(0) == -1)\n\t\t{\n\t\t\tperror(\"wait\");\n\t\t\texit(1);\n\t\t}\n\t\tif (WEXITSTATUS(status) != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n }\n\n\treturn true;\n\t \n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <cctag\/geometry\/Ellipse.hpp>\n#include <cctag\/geometry\/point.hpp>\n#include <cctag\/algebra\/invert.hpp>\n#include <cctag\/progBase\/exceptions.hpp>\n#include <cctag\/global.hpp>\n\n#include <boost\/math\/special_functions\/sign.hpp>\n#include <boost\/numeric\/ublas\/banded.hpp>\n#include <boost\/numeric\/ublas\/matrix.hpp>\n#include <boost\/numeric\/ublas\/vector.hpp>\n#include <boost\/numeric\/ublas\/matrix_expression.hpp>\n\n#include <algorithm>\n#include <cmath>\n\nnamespace cctag {\nnamespace numerical {\nnamespace geometry {\n\nusing namespace boost::numeric::ublas;\n\nEllipse::Ellipse( const bounded_matrix<double, 3, 3>& matrix )\n{\n\t_matrix = matrix;\n\tcomputeParameters();\n}\n\nEllipse::Ellipse( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tinit( center, a, b, angle );\n}\n\nvoid Ellipse::init( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tif( a < 0.0 || b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\n\t_center = center;\n\t_a = a;\n\t_b = b;\n\t_angle = angle;\n\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setMatrix( const bounded_matrix<double, 3, 3>& matrix )\n{\n\t_matrix = matrix;\n\tcomputeParameters();\n}\n\nvoid Ellipse::setParameters( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tif( a < 0.0 || b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_center = center;\n\t_a = a;\n\t_b = b;\n\t_angle = angle;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setCenter( const Point2dN<double>& center )\n{\n\t_center = center;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setA( const double a )\n{\n\tif( a < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_a = a;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setB( const double b )\n{\n\tif( b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_b = b;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setAngle( const double angle )\n{\n\t_angle = angle;\n\tcomputeMatrix();\n}\n\nEllipse Ellipse::transform(const Matrix& mT) const\n{\n\tusing namespace boost::numeric::ublas;\n\tconst Matrix a = prec_prod( boost::numeric::ublas::trans(mT), _matrix );\n\tconst Matrix mET = prec_prod( a, mT );\n\treturn Ellipse( mET );\n}\n\nvoid Ellipse::computeParameters()\n{\n\tbounded_vector<double, 6> par;\n\tpar( 0 ) = _matrix( 0, 0 );\n\tpar( 1 ) = 2.0 * _matrix( 0, 1 );\n\tpar( 2 ) = _matrix( 1, 1 );\n\tpar( 3 ) = 2 * _matrix( 0, 2 );\n\tpar( 4 ) = 2 * _matrix( 1, 2 );\n\tpar( 5 ) = _matrix( 2, 2 );\n\n\tconst double thetarad = 0.5 * std::atan2( par( 1 ), par( 0 ) - par( 2 ) );\n\tconst double cost = std::cos( thetarad );\n\tconst double sint = std::sin( thetarad );\n\tconst double sin_squared = sint * sint;\n\tconst double cos_squared = cost * cost;\n\tconst double cos_sin = sint * cost;\n\n\tconst double Ao = par( 5 );\n\tconst double Au = par( 3 ) * cost + par( 4 ) * sint;\n\tconst double Av = -par( 3 ) * sint + par( 4 ) * cost;\n\tconst double Auu = par( 0 ) * cos_squared + par( 2 ) * sin_squared + par( 1 ) * cos_sin;\n\tconst double Avv = par( 0 ) * sin_squared + par( 2 ) * cos_squared - par( 1 ) * cos_sin;\n\n\tif( Auu == 0 || Avv == 0 )\n\t{\n\t\t_center = Point2dN<double>( 0.0, 0.0 );\n\t\t_a = 0.0;\n\t\t_b = 0.0;\n\t\t_angle = 0.0;\n\t}\n\telse\n\t{\n\t\tconst double tuCentre = -Au \/ ( 2.0 * Auu );\n\t\tconst double tvCentre = -Av \/ ( 2.0 * Avv );\n\t\tconst double wCentre = Ao - Auu * tuCentre * tuCentre - Avv * tvCentre * tvCentre;\n\n\t\t_center = Point2dN<double>( tuCentre * cost - tvCentre * sint, tuCentre * sint + tvCentre * cost );\n\n\t\tconst double Ru = -wCentre \/ Auu;\n\t\tconst double Rv = -wCentre \/ Avv;\n\n\t\tconst double aAux = std::sqrt( std::abs( Ru ) ) * boost::math::sign( Ru );\n\t\tconst double bAux = std::sqrt( std::abs( Rv ) ) * boost::math::sign( Rv );\n\n\t\tif( aAux < 0.0 || bAux < 0.0 )\n\t\t{\n\t\t\tCCTAG_THROW( exception::Bug()\n\t\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t\t}\n\n\t\t_a = aAux;\n\t\t_b = bAux;\n\t\t_angle = thetarad;\n\t}\n}\n\n\/*\n * @brief Compute \n *\/\nvoid Ellipse::getCanonicForm(Matrix& mCanonic, Matrix& mTprimal, Matrix& mTdual) const \n{\n\n double q1 = _matrix(0,0);\n double q2 = _matrix(0,1);\n double q3 = _matrix(0,2);\n double q4 = _matrix(1,1);\n double q5 = _matrix(1,2);\n double q6 = _matrix(2,2);\n \n double par1 = q1;\n double par2 = 2*q2;\n double par3 = q4;\n double par4 = 2*q3;\n double par5 = 2*q5;\n double par6 = q6;\n \n double thetarad = 0.5*atan2(par2,par1 - par3);\n double cost = cos(thetarad);\n double sint = sin(thetarad);\n double sin_squared = sint * sint;\n double cos_squared = cost * cost;\n double cos_sin = sint * cost;\n\n double Ao = par6;\n double Au = par4 * cost + par5 * sint;\n double Av = -par4 * sint + par5 * cost;\n double Auu = par1 * cos_squared + par3 * sin_squared + par2 * cos_sin;\n double Avv = par1 * sin_squared + par3 * cos_squared - par2 * cos_sin;\n\n double tuCentre = - Au\/(2*Auu);\n double tvCentre = - Av\/(2*Avv);\n\n double uCentre = tuCentre * cost - tvCentre * sint;\n double vCentre = tuCentre * sint + tvCentre * cost;\n \n double qt1 = cost*(cost*q1 + q2*sint) + sint*(cost*q2 + q4*sint);\n double qt2 = cost*(cost*q2 + q4*sint) - sint*(cost*q1 + q2*sint);\n double qt3 = cost*q3 + q5*sint + uCentre*(cost*q1 + q2*sint) + vCentre*(cost*q2 + q4*sint);\n double qt4 = cost*(cost*q4 - q2*sint) - sint*(cost*q2 - q1*sint);\n double qt5 = cost*q5 - q3*sint + uCentre*(cost*q2 - q1*sint) + vCentre*(cost*q4 - q2*sint);\n double qt6 = q6 + uCentre*(q3 + q1*uCentre + q2*vCentre) + vCentre*(q5 + q2*uCentre + q4*vCentre) + q3*uCentre + q5*vCentre;\n \n mCanonic(0,0) = qt1; mCanonic(0,1) = qt2; mCanonic(0,2) = qt3;\n mCanonic(1,0) = qt2; mCanonic(1,1) = qt4; mCanonic(1,2) = qt5;\n mCanonic(2,0) = qt3; mCanonic(2,1) = qt5; mCanonic(2,2) = qt6;\n\n mTprimal(0,0) = cost; mTprimal(0,1) = sint; mTprimal(0,2) = - cost*uCentre - sint*vCentre;\n mTprimal(1,0) = -sint; mTprimal(1,1) = cost; mTprimal(1,2) = sint*uCentre - cost*vCentre;\n mTprimal(2,0) = 0; mTprimal(2,1) = 0; mTprimal(2,2) = cost*cost + sint*sint;\n \n mTdual(0,0) = cost; mTdual(0,1) = -sint; mTdual(0,2) = uCentre;\n mTdual(1,0) = sint; mTdual(1,1) = cost; mTdual(1,2) = vCentre;\n mTdual(2,0) = 0; mTdual(2,1) = 0; mTdual(2,2) = 1.0;\n \n}\n\nvoid Ellipse::computeMatrix()\n{\n bounded_matrix<double, 3, 3> tmp;\n tmp( 0, 0 ) = std::cos( _angle ); tmp( 0, 1 ) = -std::sin( _angle ); tmp( 0, 2 ) = _center.x();\n tmp( 1, 0 ) = std::sin( _angle ); tmp( 1, 1 ) = std::cos( _angle ); tmp( 1, 2 ) = _center.y();\n tmp( 2, 0 ) = 0.0; tmp( 2, 1 ) = 0.0; tmp( 2, 2 ) = 1.0;\n\n bounded_matrix<double, 3, 3> tmpInv;\n diagonal_matrix<double> diag( 3, 3 );\n diag( 0, 0 ) = 1.0 \/ ( _a * _a );\n diag( 1, 1 ) = 1.0 \/ ( _b * _b );\n diag( 2, 2 ) = -1.0;\n\n if( invert( tmp, tmpInv ) )\n {\n _matrix = prec_prod( diag, tmpInv );\n _matrix = prec_prod( trans( tmpInv ), _matrix );\n }\n else\n {\n CCTAG_THROW( exception::Bug()\n << exception::dev( \"Singular matrix!\" ) );\n }\n}\n\nvoid scale(const Ellipse & ellipse, Ellipse & rescaleEllipse, double scale)\n{\n rescaleEllipse.setCenter(Point2dN<double>( ellipse.center().x() * scale, ellipse.center().y() * scale ));\n rescaleEllipse.setA(ellipse.a() * scale);\n rescaleEllipse.setB(ellipse.b() * scale);\n rescaleEllipse.setAngle(ellipse.angle());\n}\n\nstd::ostream& operator<<(std::ostream& os, const Ellipse& e)\n{\n os << \"e = [ \" << e.matrix()(0,0) << \" \" << e.matrix()(0,1) << \" \" << e.matrix()(0,2) << \" ; \"\n << e.matrix()(1,0) << \" \" << e.matrix()(1,1) << \" \" << e.matrix()(1,2) << \" ; \"\n << e.matrix()(2,0) << \" \" << e.matrix()(2,1) << \" \" << e.matrix()(2,2) << \" ] \";\n return os;\n}\n\n\/* \n * @brief Sort a set of points by angle along an elliptical arc. Possibly return a subset of these \n * points if requested.\n *\/\nvoid getSortedOuterPoints(\n const Ellipse & ellipse,\n const std::vector< cctag::DirectedPoint2d<double> > & points,\n std::vector< cctag::DirectedPoint2d<double> > & resPoints,\n const std::size_t requestedSize)\n{\n \/\/ map with the key = angle and the point index\n \/\/ Sort points in points by angle\n \/\/std::map<double, std::size_t> mapAngle;\n std::vector< std::pair<double, std::size_t> > vAngles;\n vAngles.reserve(points.size());\n for(std::size_t iPoint = 0 ; iPoint < points.size() ; ++iPoint)\n {\n double angle = atan2( ellipse.center().y() - points[iPoint].y() , ellipse.center().x() - points[iPoint].x() );\n \/\/mapAngle.emplace(angle, iPoint);\n \n vAngles.emplace_back(angle, iPoint);\n }\n \n std::sort (vAngles.begin(), vAngles.end());\n \n \/\/ Get the final expected size of resPoints\n const std::size_t nOuterPoints = std::min( requestedSize, points.size() );\n std::size_t step = std::size_t( points.size() \/ ( nOuterPoints - 1 ) );\n \n CCTAG_COUT_VAR(vAngles.size());\n \n resPoints.clear();\n resPoints.reserve(nOuterPoints);\n \n CCTAG_COUT_VAR(points.size());\n CCTAG_COUT_VAR(step);\n \n \/\/ Get the final expected size of resPoints\n \n for(std::size_t iPoint = 0 ; iPoint < points.size() ; iPoint += step)\n {\n resPoints.push_back(points[vAngles[iPoint].second]);\n }\n CCTAG_COUT_VAR(resPoints.size());\n}\n\n}\n}\n}\n<commit_msg>[identification] Clean getSortedOuterPoints function.<commit_after>#include <cctag\/geometry\/Ellipse.hpp>\n#include <cctag\/geometry\/point.hpp>\n#include <cctag\/algebra\/invert.hpp>\n#include <cctag\/progBase\/exceptions.hpp>\n#include <cctag\/global.hpp>\n\n#include <boost\/math\/special_functions\/sign.hpp>\n#include <boost\/numeric\/ublas\/banded.hpp>\n#include <boost\/numeric\/ublas\/matrix.hpp>\n#include <boost\/numeric\/ublas\/vector.hpp>\n#include <boost\/numeric\/ublas\/matrix_expression.hpp>\n\n#include <algorithm>\n#include <cmath>\n\nnamespace cctag {\nnamespace numerical {\nnamespace geometry {\n\nusing namespace boost::numeric::ublas;\n\nEllipse::Ellipse( const bounded_matrix<double, 3, 3>& matrix )\n{\n\t_matrix = matrix;\n\tcomputeParameters();\n}\n\nEllipse::Ellipse( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tinit( center, a, b, angle );\n}\n\nvoid Ellipse::init( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tif( a < 0.0 || b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\n\t_center = center;\n\t_a = a;\n\t_b = b;\n\t_angle = angle;\n\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setMatrix( const bounded_matrix<double, 3, 3>& matrix )\n{\n\t_matrix = matrix;\n\tcomputeParameters();\n}\n\nvoid Ellipse::setParameters( const Point2dN<double>& center, const double a, const double b, const double angle )\n{\n\tif( a < 0.0 || b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_center = center;\n\t_a = a;\n\t_b = b;\n\t_angle = angle;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setCenter( const Point2dN<double>& center )\n{\n\t_center = center;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setA( const double a )\n{\n\tif( a < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_a = a;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setB( const double b )\n{\n\tif( b < 0.0 )\n\t{\n\t\tCCTAG_THROW( exception::Bug()\n\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t}\n\t_b = b;\n\tcomputeMatrix();\n}\n\nvoid Ellipse::setAngle( const double angle )\n{\n\t_angle = angle;\n\tcomputeMatrix();\n}\n\nEllipse Ellipse::transform(const Matrix& mT) const\n{\n\tusing namespace boost::numeric::ublas;\n\tconst Matrix a = prec_prod( boost::numeric::ublas::trans(mT), _matrix );\n\tconst Matrix mET = prec_prod( a, mT );\n\treturn Ellipse( mET );\n}\n\nvoid Ellipse::computeParameters()\n{\n\tbounded_vector<double, 6> par;\n\tpar( 0 ) = _matrix( 0, 0 );\n\tpar( 1 ) = 2.0 * _matrix( 0, 1 );\n\tpar( 2 ) = _matrix( 1, 1 );\n\tpar( 3 ) = 2 * _matrix( 0, 2 );\n\tpar( 4 ) = 2 * _matrix( 1, 2 );\n\tpar( 5 ) = _matrix( 2, 2 );\n\n\tconst double thetarad = 0.5 * std::atan2( par( 1 ), par( 0 ) - par( 2 ) );\n\tconst double cost = std::cos( thetarad );\n\tconst double sint = std::sin( thetarad );\n\tconst double sin_squared = sint * sint;\n\tconst double cos_squared = cost * cost;\n\tconst double cos_sin = sint * cost;\n\n\tconst double Ao = par( 5 );\n\tconst double Au = par( 3 ) * cost + par( 4 ) * sint;\n\tconst double Av = -par( 3 ) * sint + par( 4 ) * cost;\n\tconst double Auu = par( 0 ) * cos_squared + par( 2 ) * sin_squared + par( 1 ) * cos_sin;\n\tconst double Avv = par( 0 ) * sin_squared + par( 2 ) * cos_squared - par( 1 ) * cos_sin;\n\n\tif( Auu == 0 || Avv == 0 )\n\t{\n\t\t_center = Point2dN<double>( 0.0, 0.0 );\n\t\t_a = 0.0;\n\t\t_b = 0.0;\n\t\t_angle = 0.0;\n\t}\n\telse\n\t{\n\t\tconst double tuCentre = -Au \/ ( 2.0 * Auu );\n\t\tconst double tvCentre = -Av \/ ( 2.0 * Avv );\n\t\tconst double wCentre = Ao - Auu * tuCentre * tuCentre - Avv * tvCentre * tvCentre;\n\n\t\t_center = Point2dN<double>( tuCentre * cost - tvCentre * sint, tuCentre * sint + tvCentre * cost );\n\n\t\tconst double Ru = -wCentre \/ Auu;\n\t\tconst double Rv = -wCentre \/ Avv;\n\n\t\tconst double aAux = std::sqrt( std::abs( Ru ) ) * boost::math::sign( Ru );\n\t\tconst double bAux = std::sqrt( std::abs( Rv ) ) * boost::math::sign( Rv );\n\n\t\tif( aAux < 0.0 || bAux < 0.0 )\n\t\t{\n\t\t\tCCTAG_THROW( exception::Bug()\n\t\t\t\t<< exception::dev( \"Semi axes must be real positive!\" ) );\n\t\t}\n\n\t\t_a = aAux;\n\t\t_b = bAux;\n\t\t_angle = thetarad;\n\t}\n}\n\n\/*\n * @brief Compute \n *\/\nvoid Ellipse::getCanonicForm(Matrix& mCanonic, Matrix& mTprimal, Matrix& mTdual) const \n{\n\n double q1 = _matrix(0,0);\n double q2 = _matrix(0,1);\n double q3 = _matrix(0,2);\n double q4 = _matrix(1,1);\n double q5 = _matrix(1,2);\n double q6 = _matrix(2,2);\n \n double par1 = q1;\n double par2 = 2*q2;\n double par3 = q4;\n double par4 = 2*q3;\n double par5 = 2*q5;\n double par6 = q6;\n \n double thetarad = 0.5*atan2(par2,par1 - par3);\n double cost = cos(thetarad);\n double sint = sin(thetarad);\n double sin_squared = sint * sint;\n double cos_squared = cost * cost;\n double cos_sin = sint * cost;\n\n double Ao = par6;\n double Au = par4 * cost + par5 * sint;\n double Av = -par4 * sint + par5 * cost;\n double Auu = par1 * cos_squared + par3 * sin_squared + par2 * cos_sin;\n double Avv = par1 * sin_squared + par3 * cos_squared - par2 * cos_sin;\n\n double tuCentre = - Au\/(2*Auu);\n double tvCentre = - Av\/(2*Avv);\n\n double uCentre = tuCentre * cost - tvCentre * sint;\n double vCentre = tuCentre * sint + tvCentre * cost;\n \n double qt1 = cost*(cost*q1 + q2*sint) + sint*(cost*q2 + q4*sint);\n double qt2 = cost*(cost*q2 + q4*sint) - sint*(cost*q1 + q2*sint);\n double qt3 = cost*q3 + q5*sint + uCentre*(cost*q1 + q2*sint) + vCentre*(cost*q2 + q4*sint);\n double qt4 = cost*(cost*q4 - q2*sint) - sint*(cost*q2 - q1*sint);\n double qt5 = cost*q5 - q3*sint + uCentre*(cost*q2 - q1*sint) + vCentre*(cost*q4 - q2*sint);\n double qt6 = q6 + uCentre*(q3 + q1*uCentre + q2*vCentre) + vCentre*(q5 + q2*uCentre + q4*vCentre) + q3*uCentre + q5*vCentre;\n \n mCanonic(0,0) = qt1; mCanonic(0,1) = qt2; mCanonic(0,2) = qt3;\n mCanonic(1,0) = qt2; mCanonic(1,1) = qt4; mCanonic(1,2) = qt5;\n mCanonic(2,0) = qt3; mCanonic(2,1) = qt5; mCanonic(2,2) = qt6;\n\n mTprimal(0,0) = cost; mTprimal(0,1) = sint; mTprimal(0,2) = - cost*uCentre - sint*vCentre;\n mTprimal(1,0) = -sint; mTprimal(1,1) = cost; mTprimal(1,2) = sint*uCentre - cost*vCentre;\n mTprimal(2,0) = 0; mTprimal(2,1) = 0; mTprimal(2,2) = cost*cost + sint*sint;\n \n mTdual(0,0) = cost; mTdual(0,1) = -sint; mTdual(0,2) = uCentre;\n mTdual(1,0) = sint; mTdual(1,1) = cost; mTdual(1,2) = vCentre;\n mTdual(2,0) = 0; mTdual(2,1) = 0; mTdual(2,2) = 1.0;\n \n}\n\nvoid Ellipse::computeMatrix()\n{\n bounded_matrix<double, 3, 3> tmp;\n tmp( 0, 0 ) = std::cos( _angle ); tmp( 0, 1 ) = -std::sin( _angle ); tmp( 0, 2 ) = _center.x();\n tmp( 1, 0 ) = std::sin( _angle ); tmp( 1, 1 ) = std::cos( _angle ); tmp( 1, 2 ) = _center.y();\n tmp( 2, 0 ) = 0.0; tmp( 2, 1 ) = 0.0; tmp( 2, 2 ) = 1.0;\n\n bounded_matrix<double, 3, 3> tmpInv;\n diagonal_matrix<double> diag( 3, 3 );\n diag( 0, 0 ) = 1.0 \/ ( _a * _a );\n diag( 1, 1 ) = 1.0 \/ ( _b * _b );\n diag( 2, 2 ) = -1.0;\n\n if( invert( tmp, tmpInv ) )\n {\n _matrix = prec_prod( diag, tmpInv );\n _matrix = prec_prod( trans( tmpInv ), _matrix );\n }\n else\n {\n CCTAG_THROW( exception::Bug()\n << exception::dev( \"Singular matrix!\" ) );\n }\n}\n\nvoid scale(const Ellipse & ellipse, Ellipse & rescaleEllipse, double scale)\n{\n rescaleEllipse.setCenter(Point2dN<double>( ellipse.center().x() * scale, ellipse.center().y() * scale ));\n rescaleEllipse.setA(ellipse.a() * scale);\n rescaleEllipse.setB(ellipse.b() * scale);\n rescaleEllipse.setAngle(ellipse.angle());\n}\n\nstd::ostream& operator<<(std::ostream& os, const Ellipse& e)\n{\n os << \"e = [ \" << e.matrix()(0,0) << \" \" << e.matrix()(0,1) << \" \" << e.matrix()(0,2) << \" ; \"\n << e.matrix()(1,0) << \" \" << e.matrix()(1,1) << \" \" << e.matrix()(1,2) << \" ; \"\n << e.matrix()(2,0) << \" \" << e.matrix()(2,1) << \" \" << e.matrix()(2,2) << \" ] \";\n return os;\n}\n\n\/* \n * @brief Sort a set of points by angle along an elliptical arc. Possibly return a subset of these \n * points if requested.\n *\/\nvoid getSortedOuterPoints(\n const Ellipse & ellipse,\n const std::vector< cctag::DirectedPoint2d<double> > & points,\n std::vector< cctag::DirectedPoint2d<double> > & resPoints,\n const std::size_t requestedSize)\n{\n \/\/ map with the key = angle and the point index\n \/\/ Sort points in points by angle\n \/\/std::map<double, std::size_t> mapAngle;\n std::vector< std::pair<double, std::size_t> > vAngles;\n vAngles.reserve(points.size());\n for(std::size_t iPoint = 0 ; iPoint < points.size() ; ++iPoint)\n {\n double angle = atan2( ellipse.center().y() - points[iPoint].y() , ellipse.center().x() - points[iPoint].x() );\n \/\/mapAngle.emplace(angle, iPoint);\n \n vAngles.emplace_back(angle, iPoint);\n }\n \n std::sort (vAngles.begin(), vAngles.end());\n \n \/\/ Get the final expected size of resPoints\n const std::size_t nOuterPoints = std::min( requestedSize, points.size() );\n std::size_t step = std::size_t( points.size() \/ ( nOuterPoints - 1 ) );\n \n resPoints.clear();\n resPoints.reserve(nOuterPoints);\n \n \/\/ Get the final expected size of resPoints\n \n for(std::size_t iPoint = 0 ; iPoint < points.size() ; iPoint += step)\n {\n resPoints.push_back(points[vAngles[iPoint].second]);\n }\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llvm-config.cpp - LLVM project configuration utility --------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tool encapsulates information about an LLVM project configuration for\n\/\/ use by other project's build environments (to determine installed path,\n\/\/ available features, required libraries, etc.).\n\/\/\n\/\/ Note that although this tool *may* be used by some parts of LLVM's build\n\/\/ itself (i.e., the Makefiles use it to compute required libraries when linking\n\/\/ tools), this tool is primarily designed to support external projects.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <set>\n#include <vector>\n\nusing namespace llvm;\n\n\/\/ Include the build time variables we can report to the user. This is generated\n\/\/ at build time from the BuildVariables.inc.in file by the build system.\n#include \"BuildVariables.inc\"\n\n\/\/ Include the component table. This creates an array of struct\n\/\/ AvailableComponent entries, which record the component name, library name,\n\/\/ and required components for all of the available libraries.\n\/\/\n\/\/ Not all components define a library, we also use \"library groups\" as a way to\n\/\/ create entries for pseudo groups like x86 or all-targets.\n#include \"LibraryDependencies.inc\"\n\n\/\/\/ \\brief Traverse a single component adding to the topological ordering in\n\/\/\/ \\arg RequiredLibs.\n\/\/\/\n\/\/\/ \\param Name - The component to traverse.\n\/\/\/ \\param ComponentMap - A prebuilt map of component names to descriptors.\n\/\/\/ \\param VisitedComponents [in] [out] - The set of already visited components.\n\/\/\/ \\param RequiredLibs [out] - The ordered list of required libraries.\nstatic void VisitComponent(StringRef Name,\n const StringMap<AvailableComponent*> &ComponentMap,\n std::set<AvailableComponent*> &VisitedComponents,\n std::vector<StringRef> &RequiredLibs) {\n \/\/ Lookup the component.\n AvailableComponent *AC = ComponentMap.lookup(Name);\n assert(AC && \"Invalid component name!\");\n\n \/\/ Add to the visited table.\n if (!VisitedComponents.insert(AC).second) {\n \/\/ We are done if the component has already been visited.\n return;\n }\n\n \/\/ Otherwise, visit all the dependencies.\n for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {\n VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ Add to the required library list.\n if (AC->Library)\n RequiredLibs.push_back(AC->Library);\n}\n\n\/\/\/ \\brief Compute the list of required libraries for a given list of\n\/\/\/ components, in an order suitable for passing to a linker (that is, libraries\n\/\/\/ appear prior to their dependencies).\n\/\/\/\n\/\/\/ \\param Components - The names of the components to find libraries for.\n\/\/\/ \\param RequiredLibs [out] - On return, the ordered list of libraries that\n\/\/\/ are required to link the given components.\nvoid ComputeLibsForComponents(const std::vector<StringRef> &Components,\n std::vector<StringRef> &RequiredLibs) {\n std::set<AvailableComponent*> VisitedComponents;\n\n \/\/ Build a map of component names to information.\n StringMap<AvailableComponent*> ComponentMap;\n for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {\n AvailableComponent *AC = &AvailableComponents[i];\n ComponentMap[AC->Name] = AC;\n }\n\n \/\/ Visit the components.\n for (unsigned i = 0, e = Components.size(); i != e; ++i) {\n \/\/ Users are allowed to provide mixed case component names.\n std::string ComponentLower = Components[i].lower();\n\n \/\/ Validate that the user supplied a valid component name.\n if (!ComponentMap.count(ComponentLower)) {\n llvm::errs() << \"llvm-config: unknown component name: \" << Components[i]\n << \"\\n\";\n exit(1);\n }\n\n VisitComponent(ComponentLower, ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ The list is now ordered with leafs first, we want the libraries to printed\n \/\/ in the reverse order of dependency.\n std::reverse(RequiredLibs.begin(), RequiredLibs.end());\n}\n\n\/* *** *\/\n\nvoid usage() {\n errs() << \"\\\nusage: llvm-config <OPTION>... [<COMPONENT>...]\\n\\\n\\n\\\nGet various configuration information needed to compile programs which use\\n\\\nLLVM. Typically called from 'configure' scripts. Examples:\\n\\\n llvm-config --cxxflags\\n\\\n llvm-config --ldflags\\n\\\n llvm-config --libs engine bcreader scalaropts\\n\\\n\\n\\\nOptions:\\n\\\n --version Print LLVM version.\\n\\\n --prefix Print the installation prefix.\\n\\\n --src-root Print the source root LLVM was built from.\\n\\\n --obj-root Print the object root used to build LLVM.\\n\\\n --bindir Directory containing LLVM executables.\\n\\\n --includedir Directory containing LLVM headers.\\n\\\n --libdir Directory containing LLVM libraries.\\n\\\n --cppflags C preprocessor flags for files that include LLVM headers.\\n\\\n --cflags C compiler flags for files that include LLVM headers.\\n\\\n --cxxflags C++ compiler flags for files that include LLVM headers.\\n\\\n --ldflags Print Linker flags.\\n\\\n --libs Libraries needed to link against LLVM components.\\n\\\n --libnames Bare library names for in-tree builds.\\n\\\n --libfiles Fully qualified library filenames for makefile depends.\\n\\\n --components List of all possible components.\\n\\\n --targets-built List of all targets currently built.\\n\\\n --host-target Target triple used to configure LLVM.\\n\\\n --build-mode Print build mode of LLVM tree (e.g. Debug or Release).\\n\\\nTypical components:\\n\\\n all All LLVM libraries (default).\\n\\\n backend Either a native backend or the C backend.\\n\\\n engine Either a native JIT or a bitcode interpreter.\\n\";\n exit(1);\n}\n\n\/\/\/ \\brief Compute the path to the main executable.\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *P = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nint main(int argc, char **argv) {\n std::vector<StringRef> Components;\n bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;\n bool HasAnyOption = false;\n\n \/\/ llvm-config is designed to support being run both from a development tree\n \/\/ and from an installed path. We try and auto-detect which case we are in so\n \/\/ that we can report the correct information when run from a development\n \/\/ tree.\n bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;\n llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());\n std::string CurrentExecPrefix;\n std::string ActiveObjRoot;\n\n \/\/ Create an absolute path, and pop up one directory (we expect to be inside a\n \/\/ bin dir).\n sys::fs::make_absolute(CurrentPath);\n CurrentExecPrefix = sys::path::parent_path(\n sys::path::parent_path(CurrentPath)).str();\n\n \/\/ Check to see if we are inside a development tree by comparing to possible\n \/\/ locations (prefix style or CMake style). This could be wrong in the face of\n \/\/ symbolic links, but is good enough.\n if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/\" + LLVM_BUILDMODE) {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = false;\n\n \/\/ If we are in a development tree, then check if we are in a BuildTools\n \/\/ directory. This indicates we are built for the build triple, but we\n \/\/ always want to provide information for the host triple.\n if (sys::path::filename(LLVM_OBJ_ROOT) == \"BuildTools\") {\n ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);\n } else {\n ActiveObjRoot = LLVM_OBJ_ROOT;\n }\n } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/bin\") {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = true;\n ActiveObjRoot = LLVM_OBJ_ROOT;\n } else {\n IsInDevelopmentTree = false;\n }\n\n \/\/ Compute various directory locations based on the derived location\n \/\/ information.\n std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;\n std::string ActiveIncludeOption;\n if (IsInDevelopmentTree) {\n ActivePrefix = CurrentExecPrefix;\n\n \/\/ CMake organizes the products differently than a normal prefix style\n \/\/ layout.\n if (DevelopmentTreeLayoutIsCMakeStyle) {\n ActiveIncludeDir = ActiveObjRoot + \"\/include\";\n ActiveBinDir = ActiveObjRoot + \"\/bin\/\" + LLVM_BUILDMODE;\n ActiveLibDir = ActiveObjRoot + \"\/lib\/\" + LLVM_BUILDMODE;\n } else {\n ActiveIncludeDir = ActiveObjRoot + \"\/include\";\n ActiveBinDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/bin\";\n ActiveLibDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/lib\";\n }\n\n \/\/ We need to include files from both the source and object trees.\n ActiveIncludeOption = (\"-I\" + ActiveIncludeDir + \" \" +\n \"-I\" + ActiveObjRoot + \"\/include\");\n } else {\n ActivePrefix = CurrentExecPrefix;\n ActiveIncludeDir = ActivePrefix + \"\/include\";\n ActiveBinDir = ActivePrefix + \"\/bin\";\n ActiveLibDir = ActivePrefix + \"\/lib\";\n ActiveIncludeOption = \"-I\" + ActiveIncludeDir;\n }\n\n raw_ostream &OS = outs();\n for (int i = 1; i != argc; ++i) {\n StringRef Arg = argv[i];\n\n if (Arg.startswith(\"-\")) {\n HasAnyOption = true;\n if (Arg == \"--version\") {\n OS << PACKAGE_VERSION << '\\n';\n } else if (Arg == \"--prefix\") {\n OS << ActivePrefix << '\\n';\n } else if (Arg == \"--bindir\") {\n OS << ActiveBinDir << '\\n';\n } else if (Arg == \"--includedir\") {\n OS << ActiveIncludeDir << '\\n';\n } else if (Arg == \"--libdir\") {\n OS << ActiveLibDir << '\\n';\n } else if (Arg == \"--cppflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\\n';\n } else if (Arg == \"--cflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\\n';\n } else if (Arg == \"--cxxflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\\n';\n } else if (Arg == \"--ldflags\") {\n OS << \"-L\" << ActiveLibDir << ' ' << LLVM_LDFLAGS\n << ' ' << LLVM_SYSTEM_LIBS << '\\n';\n } else if (Arg == \"--libs\") {\n PrintLibs = true;\n } else if (Arg == \"--libnames\") {\n PrintLibNames = true;\n } else if (Arg == \"--libfiles\") {\n PrintLibFiles = true;\n } else if (Arg == \"--components\") {\n for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {\n OS << ' ';\n OS << AvailableComponents[j].Name;\n }\n OS << '\\n';\n } else if (Arg == \"--targets-built\") {\n bool First = true;\n for (TargetRegistry::iterator I = TargetRegistry::begin(),\n E = TargetRegistry::end(); I != E; First = false, ++I) {\n if (!First)\n OS << ' ';\n OS << I->getName();\n }\n OS << '\\n';\n } else if (Arg == \"--host-target\") {\n OS << LLVM_DEFAULT_TARGET_TRIPLE << '\\n';\n } else if (Arg == \"--build-mode\") {\n OS << LLVM_BUILDMODE << '\\n';\n } else if (Arg == \"--obj-root\") {\n OS << LLVM_OBJ_ROOT << '\\n';\n } else if (Arg == \"--src-root\") {\n OS << LLVM_SRC_ROOT << '\\n';\n } else {\n usage();\n }\n } else {\n Components.push_back(Arg);\n }\n }\n\n if (!HasAnyOption)\n usage();\n\n if (PrintLibs || PrintLibNames || PrintLibFiles) {\n \/\/ Construct the list of all the required libraries.\n std::vector<StringRef> RequiredLibs;\n ComputeLibsForComponents(Components, RequiredLibs);\n\n for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {\n StringRef Lib = RequiredLibs[i];\n if (i)\n OS << ' ';\n\n if (PrintLibNames) {\n OS << Lib;\n } else if (PrintLibFiles) {\n OS << ActiveLibDir << '\/' << Lib;\n } else if (PrintLibs) {\n \/\/ If this is a typical library name, include it using -l.\n if (Lib.startswith(\"lib\") && Lib.endswith(\".a\")) {\n OS << \"-l\" << Lib.slice(3, Lib.size()-2);\n continue;\n }\n\n \/\/ Otherwise, print the full path.\n OS << ActiveLibDir << '\/' << Lib;\n }\n }\n OS << '\\n';\n } else if (!Components.empty()) {\n errs() << \"llvm-config: error: components given, but unused\\n\\n\";\n usage();\n }\n\n return 0;\n}\n<commit_msg>llvm-config-2: Fix --cflags and --includedir which pointed at the wrong directory when running from a build directory.<commit_after>\/\/===-- llvm-config.cpp - LLVM project configuration utility --------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tool encapsulates information about an LLVM project configuration for\n\/\/ use by other project's build environments (to determine installed path,\n\/\/ available features, required libraries, etc.).\n\/\/\n\/\/ Note that although this tool *may* be used by some parts of LLVM's build\n\/\/ itself (i.e., the Makefiles use it to compute required libraries when linking\n\/\/ tools), this tool is primarily designed to support external projects.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Config\/llvm-config.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <set>\n#include <vector>\n\nusing namespace llvm;\n\n\/\/ Include the build time variables we can report to the user. This is generated\n\/\/ at build time from the BuildVariables.inc.in file by the build system.\n#include \"BuildVariables.inc\"\n\n\/\/ Include the component table. This creates an array of struct\n\/\/ AvailableComponent entries, which record the component name, library name,\n\/\/ and required components for all of the available libraries.\n\/\/\n\/\/ Not all components define a library, we also use \"library groups\" as a way to\n\/\/ create entries for pseudo groups like x86 or all-targets.\n#include \"LibraryDependencies.inc\"\n\n\/\/\/ \\brief Traverse a single component adding to the topological ordering in\n\/\/\/ \\arg RequiredLibs.\n\/\/\/\n\/\/\/ \\param Name - The component to traverse.\n\/\/\/ \\param ComponentMap - A prebuilt map of component names to descriptors.\n\/\/\/ \\param VisitedComponents [in] [out] - The set of already visited components.\n\/\/\/ \\param RequiredLibs [out] - The ordered list of required libraries.\nstatic void VisitComponent(StringRef Name,\n const StringMap<AvailableComponent*> &ComponentMap,\n std::set<AvailableComponent*> &VisitedComponents,\n std::vector<StringRef> &RequiredLibs) {\n \/\/ Lookup the component.\n AvailableComponent *AC = ComponentMap.lookup(Name);\n assert(AC && \"Invalid component name!\");\n\n \/\/ Add to the visited table.\n if (!VisitedComponents.insert(AC).second) {\n \/\/ We are done if the component has already been visited.\n return;\n }\n\n \/\/ Otherwise, visit all the dependencies.\n for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {\n VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ Add to the required library list.\n if (AC->Library)\n RequiredLibs.push_back(AC->Library);\n}\n\n\/\/\/ \\brief Compute the list of required libraries for a given list of\n\/\/\/ components, in an order suitable for passing to a linker (that is, libraries\n\/\/\/ appear prior to their dependencies).\n\/\/\/\n\/\/\/ \\param Components - The names of the components to find libraries for.\n\/\/\/ \\param RequiredLibs [out] - On return, the ordered list of libraries that\n\/\/\/ are required to link the given components.\nvoid ComputeLibsForComponents(const std::vector<StringRef> &Components,\n std::vector<StringRef> &RequiredLibs) {\n std::set<AvailableComponent*> VisitedComponents;\n\n \/\/ Build a map of component names to information.\n StringMap<AvailableComponent*> ComponentMap;\n for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {\n AvailableComponent *AC = &AvailableComponents[i];\n ComponentMap[AC->Name] = AC;\n }\n\n \/\/ Visit the components.\n for (unsigned i = 0, e = Components.size(); i != e; ++i) {\n \/\/ Users are allowed to provide mixed case component names.\n std::string ComponentLower = Components[i].lower();\n\n \/\/ Validate that the user supplied a valid component name.\n if (!ComponentMap.count(ComponentLower)) {\n llvm::errs() << \"llvm-config: unknown component name: \" << Components[i]\n << \"\\n\";\n exit(1);\n }\n\n VisitComponent(ComponentLower, ComponentMap, VisitedComponents,\n RequiredLibs);\n }\n\n \/\/ The list is now ordered with leafs first, we want the libraries to printed\n \/\/ in the reverse order of dependency.\n std::reverse(RequiredLibs.begin(), RequiredLibs.end());\n}\n\n\/* *** *\/\n\nvoid usage() {\n errs() << \"\\\nusage: llvm-config <OPTION>... [<COMPONENT>...]\\n\\\n\\n\\\nGet various configuration information needed to compile programs which use\\n\\\nLLVM. Typically called from 'configure' scripts. Examples:\\n\\\n llvm-config --cxxflags\\n\\\n llvm-config --ldflags\\n\\\n llvm-config --libs engine bcreader scalaropts\\n\\\n\\n\\\nOptions:\\n\\\n --version Print LLVM version.\\n\\\n --prefix Print the installation prefix.\\n\\\n --src-root Print the source root LLVM was built from.\\n\\\n --obj-root Print the object root used to build LLVM.\\n\\\n --bindir Directory containing LLVM executables.\\n\\\n --includedir Directory containing LLVM headers.\\n\\\n --libdir Directory containing LLVM libraries.\\n\\\n --cppflags C preprocessor flags for files that include LLVM headers.\\n\\\n --cflags C compiler flags for files that include LLVM headers.\\n\\\n --cxxflags C++ compiler flags for files that include LLVM headers.\\n\\\n --ldflags Print Linker flags.\\n\\\n --libs Libraries needed to link against LLVM components.\\n\\\n --libnames Bare library names for in-tree builds.\\n\\\n --libfiles Fully qualified library filenames for makefile depends.\\n\\\n --components List of all possible components.\\n\\\n --targets-built List of all targets currently built.\\n\\\n --host-target Target triple used to configure LLVM.\\n\\\n --build-mode Print build mode of LLVM tree (e.g. Debug or Release).\\n\\\nTypical components:\\n\\\n all All LLVM libraries (default).\\n\\\n backend Either a native backend or the C backend.\\n\\\n engine Either a native JIT or a bitcode interpreter.\\n\";\n exit(1);\n}\n\n\/\/\/ \\brief Compute the path to the main executable.\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *P = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nint main(int argc, char **argv) {\n std::vector<StringRef> Components;\n bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;\n bool HasAnyOption = false;\n\n \/\/ llvm-config is designed to support being run both from a development tree\n \/\/ and from an installed path. We try and auto-detect which case we are in so\n \/\/ that we can report the correct information when run from a development\n \/\/ tree.\n bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;\n llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());\n std::string CurrentExecPrefix;\n std::string ActiveObjRoot;\n\n \/\/ Create an absolute path, and pop up one directory (we expect to be inside a\n \/\/ bin dir).\n sys::fs::make_absolute(CurrentPath);\n CurrentExecPrefix = sys::path::parent_path(\n sys::path::parent_path(CurrentPath)).str();\n\n \/\/ Check to see if we are inside a development tree by comparing to possible\n \/\/ locations (prefix style or CMake style). This could be wrong in the face of\n \/\/ symbolic links, but is good enough.\n if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/\" + LLVM_BUILDMODE) {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = false;\n\n \/\/ If we are in a development tree, then check if we are in a BuildTools\n \/\/ directory. This indicates we are built for the build triple, but we\n \/\/ always want to provide information for the host triple.\n if (sys::path::filename(LLVM_OBJ_ROOT) == \"BuildTools\") {\n ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);\n } else {\n ActiveObjRoot = LLVM_OBJ_ROOT;\n }\n } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + \"\/bin\") {\n IsInDevelopmentTree = true;\n DevelopmentTreeLayoutIsCMakeStyle = true;\n ActiveObjRoot = LLVM_OBJ_ROOT;\n } else {\n IsInDevelopmentTree = false;\n }\n\n \/\/ Compute various directory locations based on the derived location\n \/\/ information.\n std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;\n std::string ActiveIncludeOption;\n if (IsInDevelopmentTree) {\n ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + \"\/include\";\n ActivePrefix = CurrentExecPrefix;\n\n \/\/ CMake organizes the products differently than a normal prefix style\n \/\/ layout.\n if (DevelopmentTreeLayoutIsCMakeStyle) {\n ActiveBinDir = ActiveObjRoot + \"\/bin\/\" + LLVM_BUILDMODE;\n ActiveLibDir = ActiveObjRoot + \"\/lib\/\" + LLVM_BUILDMODE;\n } else {\n ActiveBinDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/bin\";\n ActiveLibDir = ActiveObjRoot + \"\/\" + LLVM_BUILDMODE + \"\/lib\";\n }\n\n \/\/ We need to include files from both the source and object trees.\n ActiveIncludeOption = (\"-I\" + ActiveIncludeDir + \" \" +\n \"-I\" + ActiveObjRoot + \"\/include\");\n } else {\n ActivePrefix = CurrentExecPrefix;\n ActiveIncludeDir = ActivePrefix + \"\/include\";\n ActiveBinDir = ActivePrefix + \"\/bin\";\n ActiveLibDir = ActivePrefix + \"\/lib\";\n ActiveIncludeOption = \"-I\" + ActiveIncludeDir;\n }\n\n raw_ostream &OS = outs();\n for (int i = 1; i != argc; ++i) {\n StringRef Arg = argv[i];\n\n if (Arg.startswith(\"-\")) {\n HasAnyOption = true;\n if (Arg == \"--version\") {\n OS << PACKAGE_VERSION << '\\n';\n } else if (Arg == \"--prefix\") {\n OS << ActivePrefix << '\\n';\n } else if (Arg == \"--bindir\") {\n OS << ActiveBinDir << '\\n';\n } else if (Arg == \"--includedir\") {\n OS << ActiveIncludeDir << '\\n';\n } else if (Arg == \"--libdir\") {\n OS << ActiveLibDir << '\\n';\n } else if (Arg == \"--cppflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\\n';\n } else if (Arg == \"--cflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\\n';\n } else if (Arg == \"--cxxflags\") {\n OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\\n';\n } else if (Arg == \"--ldflags\") {\n OS << \"-L\" << ActiveLibDir << ' ' << LLVM_LDFLAGS\n << ' ' << LLVM_SYSTEM_LIBS << '\\n';\n } else if (Arg == \"--libs\") {\n PrintLibs = true;\n } else if (Arg == \"--libnames\") {\n PrintLibNames = true;\n } else if (Arg == \"--libfiles\") {\n PrintLibFiles = true;\n } else if (Arg == \"--components\") {\n for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {\n OS << ' ';\n OS << AvailableComponents[j].Name;\n }\n OS << '\\n';\n } else if (Arg == \"--targets-built\") {\n bool First = true;\n for (TargetRegistry::iterator I = TargetRegistry::begin(),\n E = TargetRegistry::end(); I != E; First = false, ++I) {\n if (!First)\n OS << ' ';\n OS << I->getName();\n }\n OS << '\\n';\n } else if (Arg == \"--host-target\") {\n OS << LLVM_DEFAULT_TARGET_TRIPLE << '\\n';\n } else if (Arg == \"--build-mode\") {\n OS << LLVM_BUILDMODE << '\\n';\n } else if (Arg == \"--obj-root\") {\n OS << LLVM_OBJ_ROOT << '\\n';\n } else if (Arg == \"--src-root\") {\n OS << LLVM_SRC_ROOT << '\\n';\n } else {\n usage();\n }\n } else {\n Components.push_back(Arg);\n }\n }\n\n if (!HasAnyOption)\n usage();\n\n if (PrintLibs || PrintLibNames || PrintLibFiles) {\n \/\/ Construct the list of all the required libraries.\n std::vector<StringRef> RequiredLibs;\n ComputeLibsForComponents(Components, RequiredLibs);\n\n for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {\n StringRef Lib = RequiredLibs[i];\n if (i)\n OS << ' ';\n\n if (PrintLibNames) {\n OS << Lib;\n } else if (PrintLibFiles) {\n OS << ActiveLibDir << '\/' << Lib;\n } else if (PrintLibs) {\n \/\/ If this is a typical library name, include it using -l.\n if (Lib.startswith(\"lib\") && Lib.endswith(\".a\")) {\n OS << \"-l\" << Lib.slice(3, Lib.size()-2);\n continue;\n }\n\n \/\/ Otherwise, print the full path.\n OS << ActiveLibDir << '\/' << Lib;\n }\n }\n OS << '\\n';\n } else if (!Components.empty()) {\n errs() << \"llvm-config: error: components given, but unused\\n\\n\";\n usage();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *\t notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *\t notice, this list of conditions and the following disclaimer in\n *\t the documentation and\/or other materials provided with the\n *\t distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *\t if any, must include the following acknowledgment: \n *\t\t \"This product includes software developed by the\n *\t\t Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *\t Alternately, this acknowledgment may appear in the software itself,\n *\t if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *\t not be used to endorse or promote products derived from this\n *\t software without prior written permission. For written \n *\t permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *\t nor may \"Apache\" appear in their name, without prior written\n *\t permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.\tIN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XercesPARSERLIAISON_HEADER_GUARD_1357924680)\n#define XercesPARSERLIAISON_HEADER_GUARD_1357924680\n\n\n\/\/ Base include file. Must be first.\n#include <XercesParserLiaison\/XercesParserLiaisonDefinitions.hpp>\n\n\n\n\/\/ Standard Library header files.\n#include <map>\n\n\n\n\/\/ Xerces DOM header files\n#include <util\/XercesDefs.hpp>\n#include <sax\/ErrorHandler.hpp>\n#include <dom\/DOM_Document.hpp>\n\n\n\n\/\/ Base class header file.\n#include <XMLSupport\/XMLParserLiaison.hpp>\n\n\n\nclass DOMParser;\nclass DOMSupport;\nclass EntityResolver;\nclass InputSource;\nclass SAXParser;\nclass XercesDOMSupport;\nclass XercesDocumentBridge;\nclass XSLProcessor;\n\n\n\nclass XALAN_XERCESPARSERLIAISON_EXPORT XercesParserLiaison : public XMLParserLiaison, public ErrorHandler\n{\npublic:\n\n\t\/**\n\t * Construct a XercesParserLiaison instance.\n\t *\n\t * @param theSupport instance of DOMSupport object\n\t * @param theStartingNumber the starting number for documents\n\t *\n\t * @deprecated This constructor is deprecated. Use the next constructor instead.\n\t *\/\n\tXercesParserLiaison(\n\t\t\tXercesDOMSupport&\ttheSupport,\n\t\t\tDocumentNumberType\ttheStartingNumber);\n\n\t\/**\n\t * Construct a XercesParserLiaison instance.\n\t *\n\t * @param theStartingNumber the starting number for documents\n\t *\/\n\tXercesParserLiaison(DocumentNumberType\ttheStartingNumber = 0);\n\n\tvirtual\n\t~XercesParserLiaison();\n\n\t\/\/ These interfaces are inherited from XMLParserLiaison...\n\n\tvirtual void\n\treset();\n\n\tvirtual ExecutionContext*\n\tgetExecutionContext() const;\n\n\tvirtual void\n\tsetExecutionContext(ExecutionContext&\ttheContext);\n\n\tvirtual XalanDocument*\n\tparseXMLStream(\n\t\t\tconst InputSource&\t\treader,\n\t\t\tconst XalanDOMString&\tidentifier = XalanDOMString());\n\n\tvirtual void\n\tparseXMLStream(\n\t\t\tconst InputSource&\t\turlInputSource,\n\t\t\tDocumentHandler&\t\thandler,\n\t\t\tconst XalanDOMString&\tidentifier = XalanDOMString());\n\n\t\/\/ Create a non-thread safe document, with no synchronization and no bridge...\n\tvirtual XalanDocument*\n\tcreateDocument();\n\n\t\/\/ Create a non-thread safe document, with no synchronization and no bridge...\n\tvirtual XalanDocument*\n\tcreateDOMFactory();\n\n\tvirtual void\n\tdestroyDocument(XalanDocument*\ttheDocument);\n\n\tvirtual DocumentNumberType\n\tgetNextDocumentNumber();\n\n\tvirtual int\n\tgetIndent() const;\n\n\tvirtual void\n\tsetIndent(int\ti);\n\n\tvirtual bool\n\tgetUseValidation() const;\n\n\tvirtual void\n\tsetUseValidation(bool\tb);\n\n\tvirtual const XalanDOMString\n\tgetParserDescription() const;\n\n\tvirtual EntityResolver*\n\tgetEntityResolver() const;\n\n\tvirtual void\n\tsetEntityResolver(EntityResolver*\tresolver);\n\n\n\t\/\/ These interfaces are new to XercesParserLiaison...\n\n\t\/** Get the 'include ignorable whitespace' flag.\n\t *\n\t * This method returns the state of the parser's include ignorable\n\t * whitespace flag.\n\t *\n\t * @return 'true' if the include ignorable whitespace flag is set on\n\t * \t\tthe parser, 'false' otherwise.\n\t *\n\t * @see #setIncludeIgnorableWhitespace\n\t *\/\n\tvirtual bool\n\tgetIncludeIgnorableWhitespace() const;\n\n\t\/** Set the 'include ignorable whitespace' flag\n\t *\n\t * This method allows the user to specify whether a validating parser\n\t * should include ignorable whitespaces as text nodes. It has no effect\n\t * on non-validating parsers which always include non-markup text.\n\t * <p>When set to true (also the default), ignorable whitespaces will be\n\t * added to the DOM tree as text nodes. The method\n\t * DOM_Text::isIgnorableWhitespace() will return true for those text\n\t * nodes only.\n\t * <p>When set to false, all ignorable whitespace will be discarded and\n\t * no text node is added to the DOM tree.\tNote: applications intended\n\t * to process the \"xml:space\" attribute should not set this flag to false.\n\t *\n\t * @param include The new state of the include ignorable whitespace\n\t * \t\t\t flag.\n\t *\n\t * @see #getIncludeIgnorableWhitespace\n\t *\/\n\tvirtual void\n\tsetIncludeIgnorableWhitespace(bool\tinclude);\n\n\t\/**\n\t * This method returns the installed error handler.\n\t *\n\t * @return A pointer to the installed error handler object.\n\t *\/\n\tvirtual ErrorHandler*\n\tgetErrorHandler() const;\n\n\t\/**\n\t * This method installs the user specified error handler on\n\t * the parser.\n\t *\n\t * @param handler A pointer to the error handler to be called\n\t * \t\t\t when the parser comes across 'error' events\n\t * \t\t\t as per the SAX specification.\n\t *\/\n\tvirtual void\n\tsetErrorHandler(ErrorHandler*\thandler);\n\n\t\/**\n\t * This method returns the state of the parser's namespace\n\t * handling capability.\n\t *\n\t * @return true, if the parser is currently configured to\n\t * \t\tunderstand namespaces, false otherwise.\n\t *\n\t * @see #setDoNamespaces\n\t *\/\n\tvirtual bool\n\tgetDoNamespaces() const;\n\n\t\/**\n\t * This method allows users to enable or disable the parser's\n\t * namespace processing. When set to true, parser starts enforcing\n\t * all the constraints \/ rules specified by the NameSpace\n\t * specification.\n\t *\n\t * <p>The parser's default state is: false.<\/p>\n\t *\n\t * <p>This flag is ignored by the underlying scanner if the installed\n\t * validator indicates that namespace constraints should be\n\t * enforced.<\/p>\n\t *\n\t * @param newState The value specifying whether NameSpace rules should\n\t * \t\t\t\tbe enforced or not.\n\t *\n\t * @see #getDoNamespaces\n\t *\/\n\tvirtual void\n\tsetDoNamespaces(bool\tnewState);\n\n\t\/**\n\t * This method returns the state of the parser's\n\t * exit-on-First-Fatal-Error flag.\n\t *\n\t * @return true, if the parser is currently configured to\n\t * \t\texit on the first fatal error, false otherwise.\n\t *\n\t * @see #setExitOnFirstFatalError\n\t *\/\n\tvirtual bool\n\tgetExitOnFirstFatalError() const;\n\n\t\/**\n\t * This method allows users to set the parser's behaviour when it\n\t * encounters the first fatal error. If set to true, the parser\n\t * will exit at the first fatal error. If false, then it will\n\t * report the error and continue processing.\n\t *\n\t * <p>The default value is 'true' and the parser exits on the\n\t * first fatal error.<\/p>\n\t *\n\t * @param newState The value specifying whether the parser should\n\t * \t\t\t\tcontinue or exit when it encounters the first\n\t * \t\t\t\tfatal error.\n\t *\n\t * @see #getExitOnFirstFatalError\n\t *\/\n\tvirtual void\n\tsetExitOnFirstFatalError(bool\tnewState);\n\n\t\/**\n\t * Create a XalanDocument proxy for an existing Xerces document.\n\t * The parser liaison owns the instance, and you must not delete\n\t * it.\tThe liaison will delete it when reset() is called, or the\n\t * liaison is destroyed.\n\t *\n\t * @param theXercesDocument The Xerces document.\n\t * @param threadSafe If true, read access to the tree will be thread-safe (implies buildBridge == true).\n\t * @param buildBridge If true, the entire bridge structure is built.\n\t * @return a pointer to a new XalanDocument-derived instance.\n\t *\/\n\tvirtual XalanDocument*\n\tcreateDocument(\n\t\t\tconst DOM_Document&\t\ttheXercesDocument,\n\t\t\tbool\t\t\t\t\tthreadSafe = false,\n\t\t\tbool\t\t\t\t\tbuildBridge = false);\n\n\t\/** \n\t * Map a pointer to a XalanDocument instance to its implementation\n\t * class pointer. Normally, you should have no reason for doing\n\t * this. The liaison will return a null pointer if it did not\n\t * create the instance passed.\n\t *\n\t * @param theDocument A pointer to a XalanDocument instance.\n\t * @return A pointer to the XercesDocumentBridge instance.\n\t *\/\n\tXercesDocumentBridge*\n\tmapDocument(const XalanDocument*\ttheDocument) const;\n\n\t\/** \n\t * Map a pointer to a XalanDocument instance to its corresponding\n\t * class pointer. Normally, you should have no reason for doing\n\t * this. The liaison will return a null pointer if it did not\n\t * create the instance passed.\n\t *\n\t * @param theDocument A pointer to a XalanDocument instance.\n\t * @return A pointer to the XercesDocumentBridge instance.\n\t *\/\n\tDOM_Document\n\tmapXercesDocument(const XalanDocument*\ttheDocument) const;\n\n\t\/\/ Implementations for SAX ErrorHandler\n\n\tvirtual void\n\twarning(const SAXParseException& exception);\n\n\tvirtual void\n\terror(const SAXParseException& exception);\n \n\tvirtual void\n\tfatalError(const SAXParseException& exception);\n\n\tvirtual void\n\tresetErrors();\n\n#if defined(XALAN_NO_NAMESPACES)\n\ttypedef map<const XalanDocument*,\n\t\t\t\tXercesDocumentBridge*,\n\t\t\t\tless<const XalanDocument*> >\tDocumentMapType;\n#else\n\ttypedef std::map<const XalanDocument*,\n\t\t\t\t\t XercesDocumentBridge*>\t\tDocumentMapType;\n#endif\n\n\t\/**\n\t * This functions returns the state of the liaison's build-bridge-nodes flag.\n\t *\n\t * @return true, if the bridge nodes are automatically built, false otherwise.\n\t *\/\n\tbool\n\tgetBuildBridgeNodes() const\n\t\n\t{\n\t\treturn m_buildBridge;\n\t}\n\n\t\/**\n\t * This functions sets the state of the liaison's build-bridge-nodes flag.\n\t * This flag must be set for the document to be thread safe. It can also be\n\t * set to true to increase performance. If this flag is set to false, then\n\t * the thread-safe flag will also be set to false.\n\t *\n\t * @param newState The new state for the flag.\n\t *\n\t *\/\n\tvoid\n\tsetBuildBridgeNodes(bool\tnewState)\n\t{\n\t\tm_buildBridge = newState;\n\n\t\tif (newState == false)\n\t\t{\n\t\t\tm_threadSafe = false;\n\t\t}\n\t}\n\n\t\/**\n\t * This functions returns the state of the liaison's thread-safe flag.\n\t * If true, documents created will be safe when data is read. By default,\n\t * documents are _not_ thread-safe.\n\t *\n\t * Note -- modifications are _never_ synchronized.\n\t *\n\t * @return true, if the new documents will be thread safe, false otherwise.\n\t *\/\n\tbool\n\tgetThreadSafe() const\n\t\n\t{\n\t\treturn m_threadSafe;\n\t}\n\n\t\/**\n\t * This functions sets the state of the liaison's thread-safe flag.\n\t * This flag must be set for the document to be thread safe. If this\n\t * flag is set to true, then the build-bridge-nodes flag will also be\n\t * set to true.\n\t *\n\t * @param newState The new state for the flag.\n\t *\n\t *\/\n\tvoid\n\tsetThreadSafe(bool\tnewState)\n\t{\n\t\tm_threadSafe = newState;\n\n\t\tif (m_threadSafe == true)\n\t\t{\n\t\t\tm_buildBridge = true;\n\t\t}\n\t}\n\n\tDocumentNumberType\n\tgetDocumentNumber() const\n\t{\n\t\treturn m_documentNumber;\n\t}\n\nprotected:\n\n\tstatic void\n\tformatErrorMessage(\n\t\t\tconst SAXParseException&\te,\n\t\t\tXalanDOMString&\t\t\t\ttheMessage);\n\n\tvirtual DOMParser*\n\tCreateDOMParser();\n\n\tvirtual SAXParser*\n\tCreateSAXParser();\n\n\t\/**\n\t * Create a XalanDocument proxy for an existing Xerces document.\n\t *\n\t * @param theXercesDocument The Xerces document.\n\t * @param threadSafe If true, read access to the tree will be thread-safe (implies buildBridge == true).\n\t * @param buildBridge If true, the entire bridge structure is built.\n\t * @return a pointer to a new XercesDocumentBridge instance.\n\t *\/\n\tvirtual XercesDocumentBridge*\n\tdoCreateDocument(\n\t\t\tconst DOM_Document&\t\ttheXercesDocument,\n\t\t\tbool\t\t\t\t\tthreadSafe,\n\t\t\tbool\t\t\t\t\tbuildBridge);\n\nprivate:\n\n\t\/\/ Data members...\n\tunsigned long\t\tm_documentNumber;\n\n\tint \t\t\t\tm_indent;\n\n\tbool\t\t\t\tm_useValidation;\n\n\tbool\t\t\t\tm_includeIgnorableWhitespace;\n\n\tbool\t\t\t\tm_doNamespaces;\n\n\tbool\t\t\t\tm_exitOnFirstFatalError;\n\n\tEntityResolver* \tm_entityResolver;\n\n\tErrorHandler*\t\tm_errorHandler;\n\n\tDocumentMapType \tm_documentMap;\n\n\tbool\t\t\t\tm_buildBridge;\n\n\tbool\t\t\t\tm_threadSafe;\n\n\tExecutionContext*\tm_executionContext;\n};\n\n\n\n#endif\t\/\/ XercesPARSERLIAISON_HEADER_GUARD_1357924680\n<commit_msg>Added default for parameter.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2001 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *\t notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *\t notice, this list of conditions and the following disclaimer in\n *\t the documentation and\/or other materials provided with the\n *\t distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *\t if any, must include the following acknowledgment: \n *\t\t \"This product includes software developed by the\n *\t\t Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *\t Alternately, this acknowledgment may appear in the software itself,\n *\t if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *\t not be used to endorse or promote products derived from this\n *\t software without prior written permission. For written \n *\t permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *\t nor may \"Apache\" appear in their name, without prior written\n *\t permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.\tIN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XercesPARSERLIAISON_HEADER_GUARD_1357924680)\n#define XercesPARSERLIAISON_HEADER_GUARD_1357924680\n\n\n\/\/ Base include file. Must be first.\n#include <XercesParserLiaison\/XercesParserLiaisonDefinitions.hpp>\n\n\n\n\/\/ Standard Library header files.\n#include <map>\n\n\n\n\/\/ Xerces DOM header files\n#include <util\/XercesDefs.hpp>\n#include <sax\/ErrorHandler.hpp>\n#include <dom\/DOM_Document.hpp>\n\n\n\n\/\/ Base class header file.\n#include <XMLSupport\/XMLParserLiaison.hpp>\n\n\n\nclass DOMParser;\nclass DOMSupport;\nclass EntityResolver;\nclass InputSource;\nclass SAXParser;\nclass XercesDOMSupport;\nclass XercesDocumentBridge;\nclass XSLProcessor;\n\n\n\nclass XALAN_XERCESPARSERLIAISON_EXPORT XercesParserLiaison : public XMLParserLiaison, public ErrorHandler\n{\npublic:\n\n\t\/**\n\t * Construct a XercesParserLiaison instance.\n\t *\n\t * @param theSupport instance of DOMSupport object\n\t * @param theStartingNumber the starting number for documents\n\t *\n\t * @deprecated This constructor is deprecated. Use the next constructor instead.\n\t *\/\n\tXercesParserLiaison(\n\t\t\tXercesDOMSupport&\ttheSupport,\n\t\t\tDocumentNumberType\ttheStartingNumber = 0);\n\n\t\/**\n\t * Construct a XercesParserLiaison instance.\n\t *\n\t * @param theStartingNumber the starting number for documents\n\t *\/\n\tXercesParserLiaison(DocumentNumberType\ttheStartingNumber = 0);\n\n\tvirtual\n\t~XercesParserLiaison();\n\n\t\/\/ These interfaces are inherited from XMLParserLiaison...\n\n\tvirtual void\n\treset();\n\n\tvirtual ExecutionContext*\n\tgetExecutionContext() const;\n\n\tvirtual void\n\tsetExecutionContext(ExecutionContext&\ttheContext);\n\n\tvirtual XalanDocument*\n\tparseXMLStream(\n\t\t\tconst InputSource&\t\treader,\n\t\t\tconst XalanDOMString&\tidentifier = XalanDOMString());\n\n\tvirtual void\n\tparseXMLStream(\n\t\t\tconst InputSource&\t\turlInputSource,\n\t\t\tDocumentHandler&\t\thandler,\n\t\t\tconst XalanDOMString&\tidentifier = XalanDOMString());\n\n\t\/\/ Create a non-thread safe document, with no synchronization and no bridge...\n\tvirtual XalanDocument*\n\tcreateDocument();\n\n\t\/\/ Create a non-thread safe document, with no synchronization and no bridge...\n\tvirtual XalanDocument*\n\tcreateDOMFactory();\n\n\tvirtual void\n\tdestroyDocument(XalanDocument*\ttheDocument);\n\n\tvirtual DocumentNumberType\n\tgetNextDocumentNumber();\n\n\tvirtual int\n\tgetIndent() const;\n\n\tvirtual void\n\tsetIndent(int\ti);\n\n\tvirtual bool\n\tgetUseValidation() const;\n\n\tvirtual void\n\tsetUseValidation(bool\tb);\n\n\tvirtual const XalanDOMString\n\tgetParserDescription() const;\n\n\tvirtual EntityResolver*\n\tgetEntityResolver() const;\n\n\tvirtual void\n\tsetEntityResolver(EntityResolver*\tresolver);\n\n\n\t\/\/ These interfaces are new to XercesParserLiaison...\n\n\t\/** Get the 'include ignorable whitespace' flag.\n\t *\n\t * This method returns the state of the parser's include ignorable\n\t * whitespace flag.\n\t *\n\t * @return 'true' if the include ignorable whitespace flag is set on\n\t * \t\tthe parser, 'false' otherwise.\n\t *\n\t * @see #setIncludeIgnorableWhitespace\n\t *\/\n\tvirtual bool\n\tgetIncludeIgnorableWhitespace() const;\n\n\t\/** Set the 'include ignorable whitespace' flag\n\t *\n\t * This method allows the user to specify whether a validating parser\n\t * should include ignorable whitespaces as text nodes. It has no effect\n\t * on non-validating parsers which always include non-markup text.\n\t * <p>When set to true (also the default), ignorable whitespaces will be\n\t * added to the DOM tree as text nodes. The method\n\t * DOM_Text::isIgnorableWhitespace() will return true for those text\n\t * nodes only.\n\t * <p>When set to false, all ignorable whitespace will be discarded and\n\t * no text node is added to the DOM tree.\tNote: applications intended\n\t * to process the \"xml:space\" attribute should not set this flag to false.\n\t *\n\t * @param include The new state of the include ignorable whitespace\n\t * \t\t\t flag.\n\t *\n\t * @see #getIncludeIgnorableWhitespace\n\t *\/\n\tvirtual void\n\tsetIncludeIgnorableWhitespace(bool\tinclude);\n\n\t\/**\n\t * This method returns the installed error handler.\n\t *\n\t * @return A pointer to the installed error handler object.\n\t *\/\n\tvirtual ErrorHandler*\n\tgetErrorHandler() const;\n\n\t\/**\n\t * This method installs the user specified error handler on\n\t * the parser.\n\t *\n\t * @param handler A pointer to the error handler to be called\n\t * \t\t\t when the parser comes across 'error' events\n\t * \t\t\t as per the SAX specification.\n\t *\/\n\tvirtual void\n\tsetErrorHandler(ErrorHandler*\thandler);\n\n\t\/**\n\t * This method returns the state of the parser's namespace\n\t * handling capability.\n\t *\n\t * @return true, if the parser is currently configured to\n\t * \t\tunderstand namespaces, false otherwise.\n\t *\n\t * @see #setDoNamespaces\n\t *\/\n\tvirtual bool\n\tgetDoNamespaces() const;\n\n\t\/**\n\t * This method allows users to enable or disable the parser's\n\t * namespace processing. When set to true, parser starts enforcing\n\t * all the constraints \/ rules specified by the NameSpace\n\t * specification.\n\t *\n\t * <p>The parser's default state is: false.<\/p>\n\t *\n\t * <p>This flag is ignored by the underlying scanner if the installed\n\t * validator indicates that namespace constraints should be\n\t * enforced.<\/p>\n\t *\n\t * @param newState The value specifying whether NameSpace rules should\n\t * \t\t\t\tbe enforced or not.\n\t *\n\t * @see #getDoNamespaces\n\t *\/\n\tvirtual void\n\tsetDoNamespaces(bool\tnewState);\n\n\t\/**\n\t * This method returns the state of the parser's\n\t * exit-on-First-Fatal-Error flag.\n\t *\n\t * @return true, if the parser is currently configured to\n\t * \t\texit on the first fatal error, false otherwise.\n\t *\n\t * @see #setExitOnFirstFatalError\n\t *\/\n\tvirtual bool\n\tgetExitOnFirstFatalError() const;\n\n\t\/**\n\t * This method allows users to set the parser's behaviour when it\n\t * encounters the first fatal error. If set to true, the parser\n\t * will exit at the first fatal error. If false, then it will\n\t * report the error and continue processing.\n\t *\n\t * <p>The default value is 'true' and the parser exits on the\n\t * first fatal error.<\/p>\n\t *\n\t * @param newState The value specifying whether the parser should\n\t * \t\t\t\tcontinue or exit when it encounters the first\n\t * \t\t\t\tfatal error.\n\t *\n\t * @see #getExitOnFirstFatalError\n\t *\/\n\tvirtual void\n\tsetExitOnFirstFatalError(bool\tnewState);\n\n\t\/**\n\t * Create a XalanDocument proxy for an existing Xerces document.\n\t * The parser liaison owns the instance, and you must not delete\n\t * it.\tThe liaison will delete it when reset() is called, or the\n\t * liaison is destroyed.\n\t *\n\t * @param theXercesDocument The Xerces document.\n\t * @param threadSafe If true, read access to the tree will be thread-safe (implies buildBridge == true).\n\t * @param buildBridge If true, the entire bridge structure is built.\n\t * @return a pointer to a new XalanDocument-derived instance.\n\t *\/\n\tvirtual XalanDocument*\n\tcreateDocument(\n\t\t\tconst DOM_Document&\t\ttheXercesDocument,\n\t\t\tbool\t\t\t\t\tthreadSafe = false,\n\t\t\tbool\t\t\t\t\tbuildBridge = false);\n\n\t\/** \n\t * Map a pointer to a XalanDocument instance to its implementation\n\t * class pointer. Normally, you should have no reason for doing\n\t * this. The liaison will return a null pointer if it did not\n\t * create the instance passed.\n\t *\n\t * @param theDocument A pointer to a XalanDocument instance.\n\t * @return A pointer to the XercesDocumentBridge instance.\n\t *\/\n\tXercesDocumentBridge*\n\tmapDocument(const XalanDocument*\ttheDocument) const;\n\n\t\/** \n\t * Map a pointer to a XalanDocument instance to its corresponding\n\t * class pointer. Normally, you should have no reason for doing\n\t * this. The liaison will return a null pointer if it did not\n\t * create the instance passed.\n\t *\n\t * @param theDocument A pointer to a XalanDocument instance.\n\t * @return A pointer to the XercesDocumentBridge instance.\n\t *\/\n\tDOM_Document\n\tmapXercesDocument(const XalanDocument*\ttheDocument) const;\n\n\t\/\/ Implementations for SAX ErrorHandler\n\n\tvirtual void\n\twarning(const SAXParseException& exception);\n\n\tvirtual void\n\terror(const SAXParseException& exception);\n \n\tvirtual void\n\tfatalError(const SAXParseException& exception);\n\n\tvirtual void\n\tresetErrors();\n\n#if defined(XALAN_NO_NAMESPACES)\n\ttypedef map<const XalanDocument*,\n\t\t\t\tXercesDocumentBridge*,\n\t\t\t\tless<const XalanDocument*> >\tDocumentMapType;\n#else\n\ttypedef std::map<const XalanDocument*,\n\t\t\t\t\t XercesDocumentBridge*>\t\tDocumentMapType;\n#endif\n\n\t\/**\n\t * This functions returns the state of the liaison's build-bridge-nodes flag.\n\t *\n\t * @return true, if the bridge nodes are automatically built, false otherwise.\n\t *\/\n\tbool\n\tgetBuildBridgeNodes() const\n\t\n\t{\n\t\treturn m_buildBridge;\n\t}\n\n\t\/**\n\t * This functions sets the state of the liaison's build-bridge-nodes flag.\n\t * This flag must be set for the document to be thread safe. It can also be\n\t * set to true to increase performance. If this flag is set to false, then\n\t * the thread-safe flag will also be set to false.\n\t *\n\t * @param newState The new state for the flag.\n\t *\n\t *\/\n\tvoid\n\tsetBuildBridgeNodes(bool\tnewState)\n\t{\n\t\tm_buildBridge = newState;\n\n\t\tif (newState == false)\n\t\t{\n\t\t\tm_threadSafe = false;\n\t\t}\n\t}\n\n\t\/**\n\t * This functions returns the state of the liaison's thread-safe flag.\n\t * If true, documents created will be safe when data is read. By default,\n\t * documents are _not_ thread-safe.\n\t *\n\t * Note -- modifications are _never_ synchronized.\n\t *\n\t * @return true, if the new documents will be thread safe, false otherwise.\n\t *\/\n\tbool\n\tgetThreadSafe() const\n\t\n\t{\n\t\treturn m_threadSafe;\n\t}\n\n\t\/**\n\t * This functions sets the state of the liaison's thread-safe flag.\n\t * This flag must be set for the document to be thread safe. If this\n\t * flag is set to true, then the build-bridge-nodes flag will also be\n\t * set to true.\n\t *\n\t * @param newState The new state for the flag.\n\t *\n\t *\/\n\tvoid\n\tsetThreadSafe(bool\tnewState)\n\t{\n\t\tm_threadSafe = newState;\n\n\t\tif (m_threadSafe == true)\n\t\t{\n\t\t\tm_buildBridge = true;\n\t\t}\n\t}\n\n\tDocumentNumberType\n\tgetDocumentNumber() const\n\t{\n\t\treturn m_documentNumber;\n\t}\n\nprotected:\n\n\tstatic void\n\tformatErrorMessage(\n\t\t\tconst SAXParseException&\te,\n\t\t\tXalanDOMString&\t\t\t\ttheMessage);\n\n\tvirtual DOMParser*\n\tCreateDOMParser();\n\n\tvirtual SAXParser*\n\tCreateSAXParser();\n\n\t\/**\n\t * Create a XalanDocument proxy for an existing Xerces document.\n\t *\n\t * @param theXercesDocument The Xerces document.\n\t * @param threadSafe If true, read access to the tree will be thread-safe (implies buildBridge == true).\n\t * @param buildBridge If true, the entire bridge structure is built.\n\t * @return a pointer to a new XercesDocumentBridge instance.\n\t *\/\n\tvirtual XercesDocumentBridge*\n\tdoCreateDocument(\n\t\t\tconst DOM_Document&\t\ttheXercesDocument,\n\t\t\tbool\t\t\t\t\tthreadSafe,\n\t\t\tbool\t\t\t\t\tbuildBridge);\n\nprivate:\n\n\t\/\/ Data members...\n\tunsigned long\t\tm_documentNumber;\n\n\tint \t\t\t\tm_indent;\n\n\tbool\t\t\t\tm_useValidation;\n\n\tbool\t\t\t\tm_includeIgnorableWhitespace;\n\n\tbool\t\t\t\tm_doNamespaces;\n\n\tbool\t\t\t\tm_exitOnFirstFatalError;\n\n\tEntityResolver* \tm_entityResolver;\n\n\tErrorHandler*\t\tm_errorHandler;\n\n\tDocumentMapType \tm_documentMap;\n\n\tbool\t\t\t\tm_buildBridge;\n\n\tbool\t\t\t\tm_threadSafe;\n\n\tExecutionContext*\tm_executionContext;\n};\n\n\n\n#endif\t\/\/ XercesPARSERLIAISON_HEADER_GUARD_1357924680\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <iostream>\n#include <memory>\n#include <string>\n\n#include <grpc\/support\/log.h>\n#include <grpcpp\/grpcpp.h>\n\n#ifdef BAZEL_BUILD\n#include \"examples\/protos\/helloworld.grpc.pb.h\"\n#else\n#include \"helloworld.grpc.pb.h\"\n#endif\n\nusing grpc::Channel;\nusing grpc::ClientAsyncResponseReader;\nusing grpc::ClientContext;\nusing grpc::CompletionQueue;\nusing grpc::Status;\nusing helloworld::Greeter;\nusing helloworld::HelloReply;\nusing helloworld::HelloRequest;\n\nclass GreeterClient {\n public:\n explicit GreeterClient(std::shared_ptr<Channel> channel)\n : stub_(Greeter::NewStub(channel)) {}\n\n \/\/ Assembles the client's payload, sends it and presents the response back\n \/\/ from the server.\n std::string SayHello(const std::string& user) {\n \/\/ Data we are sending to the server.\n HelloRequest request;\n request.set_name(user);\n\n \/\/ Container for the data we expect from the server.\n HelloReply reply;\n\n \/\/ Context for the client. It could be used to convey extra information to\n \/\/ the server and\/or tweak certain RPC behaviors.\n ClientContext context;\n\n \/\/ The producer-consumer queue we use to communicate asynchronously with the\n \/\/ gRPC runtime.\n CompletionQueue cq;\n\n \/\/ Storage for the status of the RPC upon completion.\n Status status;\n\n \/\/ stub_->PrepareAsyncSayHello() creates an RPC object, returning\n \/\/ an instance to store in \"call\" but does not actually start the RPC\n \/\/ Because we are using the asynchronous API, we need to hold on to\n \/\/ the \"call\" instance in order to get updates on the ongoing RPC.\n std::unique_ptr<ClientAsyncResponseReader<HelloReply> > rpc(\n stub_->PrepareAsyncSayHello(&context, request, &cq));\n\n \/\/ StartCall initiates the RPC call\n rpc->StartCall();\n\n \/\/ Request that, upon completion of the RPC, \"reply\" be updated with the\n \/\/ server's response; \"status\" with the indication of whether the operation\n \/\/ was successful. Tag the request with the integer 1.\n rpc->Finish(&reply, &status, (void*)1);\n void* got_tag;\n bool ok = false;\n \/\/ Block until the next result is available in the completion queue \"cq\".\n \/\/ The return value of Next should always be checked. This return value\n \/\/ tells us whether there is any kind of event or the cq_ is shutting down.\n GPR_ASSERT(cq.Next(&got_tag, &ok));\n\n \/\/ Verify that the result from \"cq\" corresponds, by its tag, our previous\n \/\/ request.\n GPR_ASSERT(got_tag == (void*)1);\n \/\/ ... and that the request was completed successfully. Note that \"ok\"\n \/\/ corresponds solely to the request for updates introduced by Finish().\n GPR_ASSERT(ok);\n\n \/\/ Act upon the status of the actual RPC.\n if (status.ok()) {\n return reply.message();\n } else {\n return \"RPC failed\";\n }\n }\n\n private:\n \/\/ Out of the passed in Channel comes the stub, stored here, our view of the\n \/\/ server's exposed services.\n std::unique_ptr<Greeter::Stub> stub_;\n};\n\nint main(int argc, char** argv) {\n \/\/ Instantiate the client. It requires a channel, out of which the actual RPCs\n \/\/ are created. This channel models a connection to an endpoint (in this case,\n \/\/ localhost at port 50051). We indicate that the channel isn't authenticated\n \/\/ (use of InsecureChannelCredentials()).\n GreeterClient greeter(grpc::CreateChannel(\n \"localhost:50051\", grpc::InsecureChannelCredentials()));\n std::string user(\"world\");\n std::string reply = greeter.SayHello(user); \/\/ The actual RPC call!\n std::cout << \"Greeter received: \" << reply << std::endl;\n\n return 0;\n}\n<commit_msg>Match the greeter async example to the tutorial (#30731)<commit_after>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <iostream>\n#include <memory>\n#include <string>\n\n#include <grpc\/support\/log.h>\n#include <grpcpp\/grpcpp.h>\n\n#ifdef BAZEL_BUILD\n#include \"examples\/protos\/helloworld.grpc.pb.h\"\n#else\n#include \"helloworld.grpc.pb.h\"\n#endif\n\nusing grpc::Channel;\nusing grpc::ClientAsyncResponseReader;\nusing grpc::ClientContext;\nusing grpc::CompletionQueue;\nusing grpc::Status;\nusing helloworld::Greeter;\nusing helloworld::HelloReply;\nusing helloworld::HelloRequest;\n\nclass GreeterClient {\n public:\n explicit GreeterClient(std::shared_ptr<Channel> channel)\n : stub_(Greeter::NewStub(channel)) {}\n\n \/\/ Assembles the client's payload, sends it and presents the response back\n \/\/ from the server.\n std::string SayHello(const std::string& user) {\n \/\/ Data we are sending to the server.\n HelloRequest request;\n request.set_name(user);\n\n \/\/ Container for the data we expect from the server.\n HelloReply reply;\n\n \/\/ Context for the client. It could be used to convey extra information to\n \/\/ the server and\/or tweak certain RPC behaviors.\n ClientContext context;\n\n \/\/ The producer-consumer queue we use to communicate asynchronously with the\n \/\/ gRPC runtime.\n CompletionQueue cq;\n\n \/\/ Storage for the status of the RPC upon completion.\n Status status;\n\n std::unique_ptr<ClientAsyncResponseReader<HelloReply> > rpc(\n stub_->AsyncSayHello(&context, request, &cq));\n\n \/\/ Request that, upon completion of the RPC, \"reply\" be updated with the\n \/\/ server's response; \"status\" with the indication of whether the operation\n \/\/ was successful. Tag the request with the integer 1.\n rpc->Finish(&reply, &status, (void*)1);\n void* got_tag;\n bool ok = false;\n \/\/ Block until the next result is available in the completion queue \"cq\".\n \/\/ The return value of Next should always be checked. This return value\n \/\/ tells us whether there is any kind of event or the cq_ is shutting down.\n GPR_ASSERT(cq.Next(&got_tag, &ok));\n\n \/\/ Verify that the result from \"cq\" corresponds, by its tag, our previous\n \/\/ request.\n GPR_ASSERT(got_tag == (void*)1);\n \/\/ ... and that the request was completed successfully. Note that \"ok\"\n \/\/ corresponds solely to the request for updates introduced by Finish().\n GPR_ASSERT(ok);\n\n \/\/ Act upon the status of the actual RPC.\n if (status.ok()) {\n return reply.message();\n } else {\n return \"RPC failed\";\n }\n }\n\n private:\n \/\/ Out of the passed in Channel comes the stub, stored here, our view of the\n \/\/ server's exposed services.\n std::unique_ptr<Greeter::Stub> stub_;\n};\n\nint main(int argc, char** argv) {\n \/\/ Instantiate the client. It requires a channel, out of which the actual RPCs\n \/\/ are created. This channel models a connection to an endpoint (in this case,\n \/\/ localhost at port 50051). We indicate that the channel isn't authenticated\n \/\/ (use of InsecureChannelCredentials()).\n GreeterClient greeter(grpc::CreateChannel(\n \"localhost:50051\", grpc::InsecureChannelCredentials()));\n std::string user(\"world\");\n std::string reply = greeter.SayHello(user); \/\/ The actual RPC call!\n std::cout << \"Greeter received: \" << reply << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"TestUtil.h\"\n#include \"ClientException.h\"\n#include \"CoordinatorClient.h\"\n#include \"CoordinatorService.h\"\n#include \"MasterService.h\"\n#include \"MembershipService.h\"\n#include \"MockCluster.h\"\n#include \"RamCloud.h\"\n#include \"Recovery.h\"\n#include \"TaskQueue.h\"\n\nnamespace RAMCloud {\n\nclass CoordinatorServiceTest : public ::testing::Test {\n public:\n TestLog::Enable logEnabler;\n Context context;\n ServerConfig masterConfig;\n MockCluster cluster;\n Tub<RamCloud> ramcloud;\n CoordinatorService* service;\n MasterService* master;\n ServerId masterServerId;\n\n CoordinatorServiceTest()\n : logEnabler()\n , context()\n , masterConfig(ServerConfig::forTesting())\n , cluster(&context)\n , ramcloud()\n , service()\n , master()\n , masterServerId()\n {\n Logger::get().setLogLevels(RAMCloud::SILENT_LOG_LEVEL);\n\n service = cluster.coordinator.get();\n\n masterConfig.services = {WireFormat::MASTER_SERVICE,\n WireFormat::PING_SERVICE,\n WireFormat::MEMBERSHIP_SERVICE};\n masterConfig.localLocator = \"mock:host=master\";\n Server* masterServer = cluster.addServer(masterConfig);\n master = masterServer->master.get();\n master->objectManager.log.sync();\n masterServerId = masterServer->serverId;\n\n ramcloud.construct(&context, \"mock:host=coordinator\");\n }\n\n \/\/ Generate a string containing all of the service locators in a\n \/\/ list of servers.\n string\n getLocators(ProtoBuf::ServerList& serverList)\n {\n string result;\n foreach (const ProtoBuf::ServerList::Entry& server,\n serverList.server()) {\n if (result.size() != 0) {\n result += \" \";\n }\n result += server.service_locator();\n }\n return result;\n }\n\n DISALLOW_COPY_AND_ASSIGN(CoordinatorServiceTest);\n};\n\nTEST_F(CoordinatorServiceTest, createTable_idempotence) {\n EXPECT_EQ(1UL, ramcloud->createTable(\"duplicate\", 1));\n EXPECT_EQ(1UL, ramcloud->createTable(\"duplicate\", 1));\n EXPECT_EQ(2UL, ramcloud->createTable(\"another\", 1));\n}\n\nTEST_F(CoordinatorServiceTest, getServerList) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getServerList(&context, &list);\n EXPECT_EQ(\"mock:host=master mock:host=master2 mock:host=backup1\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getServerList_backups) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getBackupList(&context, &list);\n EXPECT_EQ(\"mock:host=master2 mock:host=backup1\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getRuntimeOption){\n Buffer value;\n ramcloud->setRuntimeOption(\"failRecoveryMasters\", \"1 2 3\");\n ASSERT_EQ(3u, service->runtimeOptions.failRecoveryMasters.size());\n ramcloud->getRuntimeOption(\"failRecoveryMasters\", &value);\n EXPECT_STREQ(\"1 2 3\", service->getString(&value, 0,\n value.getTotalLength()));\n EXPECT_THROW(ramcloud->getRuntimeOption(\"optionNotExisting\",\n &value),\n ObjectDoesntExistException);\n}\n\nTEST_F(CoordinatorServiceTest, getServerList_masters) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getMasterList(&context, &list);\n EXPECT_EQ(\"mock:host=master mock:host=master2\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getTabletMap) {\n ramcloud->createTable(\"foo\");\n ProtoBuf::Tablets tabletMapProtoBuf;\n CoordinatorClient::getTabletMap(&context, &tabletMapProtoBuf);\n EXPECT_EQ(\"tablet { table_id: 1 start_key_hash: 0 \"\n \"end_key_hash: 18446744073709551615 \"\n \"state: NORMAL server_id: 1 \"\n \"service_locator: \\\"mock:host=master\\\" \"\n \"ctime_log_head_id: 0 ctime_log_head_offset: 0 }\",\n tabletMapProtoBuf.ShortDebugString());\n}\n\nTEST_F(CoordinatorServiceTest, setRuntimeOption) {\n ramcloud->setRuntimeOption(\"failRecoveryMasters\", \"1 2 3\");\n ASSERT_EQ(3u, service->runtimeOptions.failRecoveryMasters.size());\n EXPECT_EQ(1u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(2u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(3u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(0u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_THROW(ramcloud->setRuntimeOption(\"BAD\", \"1 2 3\"),\n ObjectDoesntExistException);\n}\n\nTEST_F(CoordinatorServiceTest, setMasterRecoveryInfo) {\n ProtoBuf::MasterRecoveryInfo info;\n info.set_min_open_segment_id(10);\n info.set_min_open_segment_epoch(1);\n CoordinatorClient::setMasterRecoveryInfo(&context, masterServerId, info);\n EXPECT_EQ(10u, service->context->coordinatorServerList->operator[](\n masterServerId).masterRecoveryInfo.min_open_segment_id());\n}\n\nTEST_F(CoordinatorServiceTest, setMasterRecoveryInfo_noSuchServer) {\n string message = \"no exception\";\n try {\n ProtoBuf::MasterRecoveryInfo info;\n info.set_min_open_segment_id(10);\n info.set_min_open_segment_epoch(1);\n CoordinatorClient::setMasterRecoveryInfo(&context, {999, 999}, info);\n }\n catch (const ServerNotUpException& e) {\n message = e.toSymbol();\n }\n EXPECT_EQ(\"STATUS_SERVER_NOT_UP\", message);\n}\n\nTEST_F(CoordinatorServiceTest, verifyMembership) {\n CoordinatorClient::verifyMembership(&context, masterServerId);\n ServerId bogus(3, 2);\n EXPECT_THROW(CoordinatorClient::verifyMembership(&context, bogus, false),\n CallerNotInClusterException);\n}\n\nTEST_F(CoordinatorServiceTest, verifyServerFailure) {\n \/\/ Case 1: server up.\n EXPECT_FALSE(service->verifyServerFailure(masterServerId));\n\n \/\/ Case 2: server incommunicado.\n MockTransport mockTransport(&context);\n context.transportManager->registerMock(&mockTransport, \"mock2\");\n ServerId deadId = service->serverList->enlistServer(\n {WireFormat::PING_SERVICE}, 100, \"mock2:\");\n EXPECT_TRUE(service->verifyServerFailure(deadId));\n}\n\n} \/\/ namespace RAMCloud\n<commit_msg>Fixed crash in CoordinatorServiceTest (I'm not sure why this didn't start causing problems a long time ago).<commit_after>\/* Copyright (c) 2010-2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"TestUtil.h\"\n#include \"ClientException.h\"\n#include \"CoordinatorClient.h\"\n#include \"CoordinatorService.h\"\n#include \"MasterService.h\"\n#include \"MembershipService.h\"\n#include \"MockCluster.h\"\n#include \"RamCloud.h\"\n#include \"Recovery.h\"\n#include \"TaskQueue.h\"\n\nnamespace RAMCloud {\n\nclass CoordinatorServiceTest : public ::testing::Test {\n public:\n TestLog::Enable logEnabler;\n Context context;\n ServerConfig masterConfig;\n MockCluster cluster;\n Tub<RamCloud> ramcloud;\n CoordinatorService* service;\n MasterService* master;\n ServerId masterServerId;\n\n CoordinatorServiceTest()\n : logEnabler()\n , context()\n , masterConfig(ServerConfig::forTesting())\n , cluster(&context)\n , ramcloud()\n , service()\n , master()\n , masterServerId()\n {\n Logger::get().setLogLevels(RAMCloud::SILENT_LOG_LEVEL);\n\n service = cluster.coordinator.get();\n\n masterConfig.services = {WireFormat::MASTER_SERVICE,\n WireFormat::PING_SERVICE,\n WireFormat::MEMBERSHIP_SERVICE};\n masterConfig.localLocator = \"mock:host=master\";\n Server* masterServer = cluster.addServer(masterConfig);\n master = masterServer->master.get();\n master->objectManager.log.sync();\n masterServerId = masterServer->serverId;\n\n ramcloud.construct(&context, \"mock:host=coordinator\");\n }\n\n \/\/ Generate a string containing all of the service locators in a\n \/\/ list of servers.\n string\n getLocators(ProtoBuf::ServerList& serverList)\n {\n string result;\n foreach (const ProtoBuf::ServerList::Entry& server,\n serverList.server()) {\n if (result.size() != 0) {\n result += \" \";\n }\n result += server.service_locator();\n }\n return result;\n }\n\n DISALLOW_COPY_AND_ASSIGN(CoordinatorServiceTest);\n};\n\nTEST_F(CoordinatorServiceTest, createTable_idempotence) {\n EXPECT_EQ(1UL, ramcloud->createTable(\"duplicate\", 1));\n EXPECT_EQ(1UL, ramcloud->createTable(\"duplicate\", 1));\n EXPECT_EQ(2UL, ramcloud->createTable(\"another\", 1));\n}\n\nTEST_F(CoordinatorServiceTest, getServerList) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getServerList(&context, &list);\n EXPECT_EQ(\"mock:host=master mock:host=master2 mock:host=backup1\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getServerList_backups) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getBackupList(&context, &list);\n EXPECT_EQ(\"mock:host=master2 mock:host=backup1\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getRuntimeOption){\n Buffer value;\n ramcloud->setRuntimeOption(\"failRecoveryMasters\", \"1 2 3\");\n ASSERT_EQ(3u, service->runtimeOptions.failRecoveryMasters.size());\n ramcloud->getRuntimeOption(\"failRecoveryMasters\", &value);\n EXPECT_STREQ(\"1 2 3\", service->getString(&value, 0,\n value.getTotalLength()));\n EXPECT_THROW(ramcloud->getRuntimeOption(\"optionNotExisting\",\n &value),\n ObjectDoesntExistException);\n}\n\nTEST_F(CoordinatorServiceTest, getServerList_masters) {\n ServerConfig master2Config = masterConfig;\n master2Config.localLocator = \"mock:host=master2\";\n master2Config.services = {WireFormat::MASTER_SERVICE,\n WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(master2Config);\n ServerConfig backupConfig = masterConfig;\n backupConfig.localLocator = \"mock:host=backup1\";\n backupConfig.services = {WireFormat::BACKUP_SERVICE,\n WireFormat::PING_SERVICE};\n cluster.addServer(backupConfig);\n ProtoBuf::ServerList list;\n CoordinatorClient::getMasterList(&context, &list);\n EXPECT_EQ(\"mock:host=master mock:host=master2\",\n getLocators(list));\n}\n\nTEST_F(CoordinatorServiceTest, getTabletMap) {\n ramcloud->createTable(\"foo\");\n ProtoBuf::Tablets tabletMapProtoBuf;\n CoordinatorClient::getTabletMap(&context, &tabletMapProtoBuf);\n EXPECT_EQ(\"tablet { table_id: 1 start_key_hash: 0 \"\n \"end_key_hash: 18446744073709551615 \"\n \"state: NORMAL server_id: 1 \"\n \"service_locator: \\\"mock:host=master\\\" \"\n \"ctime_log_head_id: 0 ctime_log_head_offset: 0 }\",\n tabletMapProtoBuf.ShortDebugString());\n}\n\nTEST_F(CoordinatorServiceTest, setRuntimeOption) {\n ramcloud->setRuntimeOption(\"failRecoveryMasters\", \"1 2 3\");\n ASSERT_EQ(3u, service->runtimeOptions.failRecoveryMasters.size());\n EXPECT_EQ(1u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(2u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(3u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_EQ(0u, service->runtimeOptions.popFailRecoveryMasters());\n EXPECT_THROW(ramcloud->setRuntimeOption(\"BAD\", \"1 2 3\"),\n ObjectDoesntExistException);\n}\n\nTEST_F(CoordinatorServiceTest, setMasterRecoveryInfo) {\n ProtoBuf::MasterRecoveryInfo info;\n info.set_min_open_segment_id(10);\n info.set_min_open_segment_epoch(1);\n CoordinatorClient::setMasterRecoveryInfo(&context, masterServerId, info);\n EXPECT_EQ(10u, service->context->coordinatorServerList->operator[](\n masterServerId).masterRecoveryInfo.min_open_segment_id());\n}\n\nTEST_F(CoordinatorServiceTest, setMasterRecoveryInfo_noSuchServer) {\n string message = \"no exception\";\n try {\n ProtoBuf::MasterRecoveryInfo info;\n info.set_min_open_segment_id(10);\n info.set_min_open_segment_epoch(1);\n CoordinatorClient::setMasterRecoveryInfo(&context, {999, 999}, info);\n }\n catch (const ServerNotUpException& e) {\n message = e.toSymbol();\n }\n EXPECT_EQ(\"STATUS_SERVER_NOT_UP\", message);\n}\n\nTEST_F(CoordinatorServiceTest, verifyMembership) {\n CoordinatorClient::verifyMembership(&context, masterServerId);\n ServerId bogus(3, 2);\n EXPECT_THROW(CoordinatorClient::verifyMembership(&context, bogus, false),\n CallerNotInClusterException);\n}\n\nTEST_F(CoordinatorServiceTest, verifyServerFailure) {\n \/\/ Case 1: server up.\n EXPECT_FALSE(service->verifyServerFailure(masterServerId));\n\n \/\/ Case 2: server incommunicado.\n MockTransport mockTransport(&context);\n context.transportManager->registerMock(&mockTransport, \"mock2\");\n service->serverList->haltUpdater();\n ServerId deadId = service->serverList->enlistServer(\n {WireFormat::PING_SERVICE}, 100, \"mock2:\");\n EXPECT_TRUE(service->verifyServerFailure(deadId));\n}\n\n} \/\/ namespace RAMCloud\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FTGL - OpenGL font library\n *\n * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>\n * Copyright (c) 2008 Éric Beets <ericbeets@free.fr>\n * Copyright (c) 2008 Sam Hocevar <sam@hocevar.net>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"config.h\"\n\n#include \"FTInternals.h\"\n\nstatic const FTBBox static_ftbbox;\n\nFTGL_BEGIN_C_DECLS\n\n#define C_TOR(cname, cargs, cxxname, cxxarg, cxxtype) \\\n FTGLlayout* cname cargs \\\n { \\\n cxxname *l = new cxxname cxxarg; \\\n if(l->Error()) \\\n { \\\n delete l; \\\n return NULL; \\\n } \\\n FTGLlayout *ftgl = (FTGLlayout *)malloc(sizeof(FTGLlayout)); \\\n ftgl->ptr = l; \\\n ftgl->type = cxxtype; \\\n return ftgl; \\\n }\n\n\/\/ FTSimpleLayout::FTSimpleLayout();\nC_TOR(ftglCreateSimpleLayout, (), FTSimpleLayout, (), LAYOUT_SIMPLE);\n\n#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \\\n cret cname cargs \\\n { \\\n if(!l || !l->ptr) \\\n { \\\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", #cname); \\\n cxxerr; \\\n } \\\n return l->ptr->cxxname cxxarg; \\\n }\n\n\/\/ FTLayout::~FTLayout();\nvoid ftglDestroyLayout(FTGLlayout *l)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return;\n }\n delete l->ptr;\n free(l);\n}\n\n\/\/ virtual FTBBox FTLayout::BBox(const char* string)\nextern \"C++\" {\nC_FUN(static FTBBox, _ftglGetLayoutBBox, (FTGLlayout *l, const char *s),\n return static_ftbbox, BBox, (s));\n}\n\nvoid ftglGetLayoutBBox(FTGLlayout *l, const char * s, float c[6])\n{\n FTBBox ret = _ftglGetLayoutBBox(l, s);\n FTPoint lower = ret.Lower(), upper = ret.Upper();\n c[0] = lower.Xf(); c[1] = lower.Yf(); c[2] = lower.Zf();\n c[3] = upper.Xf(); c[4] = upper.Yf(); c[5] = upper.Zf();\n}\n\n\/\/ virtual void FTLayout::Render(const char* string, int renderMode);\nC_FUN(void, ftglRenderLayout, (FTGLlayout *l, const char *s, int r),\n return, Render, (s, r));\n\n\/\/ FT_Error FTLayout::Error() const;\nC_FUN(FT_Error, ftglGetLayoutError, (FTGLlayout *l), return -1, Error, ());\n\n\/\/ void FTSimpleLayout::SetFont(FTFont *fontInit)\nvoid ftglSetLayoutFont(FTGLlayout *l, FTGLfont *font)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return;\n }\n if(l->type != FTGL::LAYOUT_SIMPLE)\n {\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\",\n __FUNCTION__, l->type);\n }\n l->font = font;\n return dynamic_cast<FTSimpleLayout*>(l->ptr)->SetFont(font->ptr);\n}\n\n\/\/ FTFont *FTSimpleLayout::GetFont()\nFTGLfont *ftglGetLayoutFont(FTGLlayout *l)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return NULL;\n }\n if(l->type != FTGL::LAYOUT_SIMPLE)\n {\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\",\n __FUNCTION__, l->type);\n }\n return l->font;\n}\n\n#undef C_FUN\n\n#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \\\n cret cname cargs \\\n { \\\n if(!l || !l->ptr) \\\n { \\\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", #cname); \\\n cxxerr; \\\n } \\\n if(l->type != FTGL::LAYOUT_SIMPLE) \\\n { \\\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\", \\\n __FUNCTION__, l->type); \\\n cxxerr; \\\n } \\\n return dynamic_cast<FTSimpleLayout*>(l->ptr)->cxxname cxxarg; \\\n }\n\n\/\/ void FTSimpleLayout::SetLineLength(const float LineLength);\nC_FUN(void, ftglSetLayoutLineLength, (FTGLlayout *l, const float length),\n return, SetLineLength, (length));\n\n\/\/ float FTSimpleLayout::GetLineLength() const\nC_FUN(float, ftglGetLayoutLineLength, (FTGLlayout *l),\n return 0.0f, GetLineLength, ());\n\n\/\/ void FTSimpleLayout::SetAlignment(const TextAlignment Alignment)\nC_FUN(void, ftglSetLayoutAlignment, (FTGLlayout *l, const int a),\n return, SetAlignment, ((FTGL::TextAlignment)a));\n\n\/\/ TextAlignment FTSimpleLayout::GetAlignment() const\nC_FUN(int, ftglGetLayoutAlignment, (FTGLlayout *l),\n return FTGL::ALIGN_LEFT, GetAlignment, ());\nC_FUN(int, ftglGetLayoutAlignement, (FTGLlayout *l),\n return FTGL::ALIGN_LEFT, GetAlignment, ()); \/\/ old typo\n\n\/\/ void FTSimpleLayout::SetLineSpacing(const float LineSpacing)\nC_FUN(void, ftglSetLayoutLineSpacing, (FTGLlayout *l, const float f),\n return, SetLineSpacing, (f));\n\nFTGL_END_C_DECLS\n\n<commit_msg>Fix ftglRenderLayout() implementation. Fix courtesy of Tobias Gunkel. Addresses SF bug #2122839.<commit_after>\/*\n * FTGL - OpenGL font library\n *\n * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>\n * Copyright (c) 2008 Éric Beets <ericbeets@free.fr>\n * Copyright (c) 2008 Sam Hocevar <sam@hocevar.net>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"config.h\"\n\n#include \"FTInternals.h\"\n\nstatic const FTBBox static_ftbbox;\n\nFTGL_BEGIN_C_DECLS\n\n#define C_TOR(cname, cargs, cxxname, cxxarg, cxxtype) \\\n FTGLlayout* cname cargs \\\n { \\\n cxxname *l = new cxxname cxxarg; \\\n if(l->Error()) \\\n { \\\n delete l; \\\n return NULL; \\\n } \\\n FTGLlayout *ftgl = (FTGLlayout *)malloc(sizeof(FTGLlayout)); \\\n ftgl->ptr = l; \\\n ftgl->type = cxxtype; \\\n return ftgl; \\\n }\n\n\/\/ FTSimpleLayout::FTSimpleLayout();\nC_TOR(ftglCreateSimpleLayout, (), FTSimpleLayout, (), LAYOUT_SIMPLE);\n\n#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \\\n cret cname cargs \\\n { \\\n if(!l || !l->ptr) \\\n { \\\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", #cname); \\\n cxxerr; \\\n } \\\n return l->ptr->cxxname cxxarg; \\\n }\n\n\/\/ FTLayout::~FTLayout();\nvoid ftglDestroyLayout(FTGLlayout *l)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return;\n }\n delete l->ptr;\n free(l);\n}\n\n\/\/ virtual FTBBox FTLayout::BBox(const char* string)\nextern \"C++\" {\nC_FUN(static FTBBox, _ftglGetLayoutBBox, (FTGLlayout *l, const char *s),\n return static_ftbbox, BBox, (s));\n}\n\nvoid ftglGetLayoutBBox(FTGLlayout *l, const char * s, float c[6])\n{\n FTBBox ret = _ftglGetLayoutBBox(l, s);\n FTPoint lower = ret.Lower(), upper = ret.Upper();\n c[0] = lower.Xf(); c[1] = lower.Yf(); c[2] = lower.Zf();\n c[3] = upper.Xf(); c[4] = upper.Yf(); c[5] = upper.Zf();\n}\n\n\/\/ virtual void FTLayout::Render(const char* string, int renderMode);\nC_FUN(void, ftglRenderLayout, (FTGLlayout *l, const char *s, int r),\n return, Render, (s, -1, FTPoint(), r));\n\n\/\/ FT_Error FTLayout::Error() const;\nC_FUN(FT_Error, ftglGetLayoutError, (FTGLlayout *l), return -1, Error, ());\n\n\/\/ void FTSimpleLayout::SetFont(FTFont *fontInit)\nvoid ftglSetLayoutFont(FTGLlayout *l, FTGLfont *font)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return;\n }\n if(l->type != FTGL::LAYOUT_SIMPLE)\n {\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\",\n __FUNCTION__, l->type);\n }\n l->font = font;\n return dynamic_cast<FTSimpleLayout*>(l->ptr)->SetFont(font->ptr);\n}\n\n\/\/ FTFont *FTSimpleLayout::GetFont()\nFTGLfont *ftglGetLayoutFont(FTGLlayout *l)\n{\n if(!l || !l->ptr)\n {\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", __FUNCTION__);\n return NULL;\n }\n if(l->type != FTGL::LAYOUT_SIMPLE)\n {\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\",\n __FUNCTION__, l->type);\n }\n return l->font;\n}\n\n#undef C_FUN\n\n#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \\\n cret cname cargs \\\n { \\\n if(!l || !l->ptr) \\\n { \\\n fprintf(stderr, \"FTGL warning: NULL pointer in %s\\n\", #cname); \\\n cxxerr; \\\n } \\\n if(l->type != FTGL::LAYOUT_SIMPLE) \\\n { \\\n fprintf(stderr, \"FTGL warning: %s not implemented for %d\\n\", \\\n __FUNCTION__, l->type); \\\n cxxerr; \\\n } \\\n return dynamic_cast<FTSimpleLayout*>(l->ptr)->cxxname cxxarg; \\\n }\n\n\/\/ void FTSimpleLayout::SetLineLength(const float LineLength);\nC_FUN(void, ftglSetLayoutLineLength, (FTGLlayout *l, const float length),\n return, SetLineLength, (length));\n\n\/\/ float FTSimpleLayout::GetLineLength() const\nC_FUN(float, ftglGetLayoutLineLength, (FTGLlayout *l),\n return 0.0f, GetLineLength, ());\n\n\/\/ void FTSimpleLayout::SetAlignment(const TextAlignment Alignment)\nC_FUN(void, ftglSetLayoutAlignment, (FTGLlayout *l, const int a),\n return, SetAlignment, ((FTGL::TextAlignment)a));\n\n\/\/ TextAlignment FTSimpleLayout::GetAlignment() const\nC_FUN(int, ftglGetLayoutAlignment, (FTGLlayout *l),\n return FTGL::ALIGN_LEFT, GetAlignment, ());\nC_FUN(int, ftglGetLayoutAlignement, (FTGLlayout *l),\n return FTGL::ALIGN_LEFT, GetAlignment, ()); \/\/ old typo\n\n\/\/ void FTSimpleLayout::SetLineSpacing(const float LineSpacing)\nC_FUN(void, ftglSetLayoutLineSpacing, (FTGLlayout *l, const float f),\n return, SetLineSpacing, (f));\n\nFTGL_END_C_DECLS\n\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef CLIENT_H\n#define CLIENT_H\n\nclass Client\n{\n};\n\n#endif \/\/ CLIENT_H\n<commit_msg>Delete client.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Gaffer\/DependencyNode.h\"\n#include \"Gaffer\/CompoundPlug.h\"\n\nusing namespace Gaffer;\n\nIE_CORE_DEFINERUNTIMETYPED( DependencyNode );\n\nDependencyNode::DependencyNode( const std::string &name )\n\t:\tNode( name )\n{\n}\n\nDependencyNode::~DependencyNode()\n{\n}\n\nvoid DependencyNode::affects( const Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tif( input->isInstanceOf( CompoundPlug::staticTypeId() ) )\n\t{\n\t\tthrow IECore::Exception( \"DependencyNode::affects() called with non-leaf plug \" + input->fullName() );\n\t}\n}\n\n\nBoolPlug *DependencyNode::enabledPlug()\n{\n\treturn 0;\n}\n\nconst BoolPlug *DependencyNode::enabledPlug() const\n{\n\treturn 0;\n}\n\nPlug *DependencyNode::correspondingInput( const Plug *output )\n{\n\treturn 0;\n}\n\nconst Plug *DependencyNode::correspondingInput( const Plug *output ) const\n{\n\treturn 0;\n}\n<commit_msg>DependencyNode : Remove use of CompoundPlug.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Gaffer\/DependencyNode.h\"\n\nusing namespace Gaffer;\n\nIE_CORE_DEFINERUNTIMETYPED( DependencyNode );\n\nDependencyNode::DependencyNode( const std::string &name )\n\t:\tNode( name )\n{\n}\n\nDependencyNode::~DependencyNode()\n{\n}\n\nvoid DependencyNode::affects( const Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tif( !input->children().empty() )\n\t{\n\t\tthrow IECore::Exception( \"DependencyNode::affects() called with non-leaf plug \" + input->fullName() );\n\t}\n}\n\n\nBoolPlug *DependencyNode::enabledPlug()\n{\n\treturn 0;\n}\n\nconst BoolPlug *DependencyNode::enabledPlug() const\n{\n\treturn 0;\n}\n\nPlug *DependencyNode::correspondingInput( const Plug *output )\n{\n\treturn 0;\n}\n\nconst Plug *DependencyNode::correspondingInput( const Plug *output ) const\n{\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\r\n*\r\n* Flood Project (2008-201x)\r\n* Licensed under the simplified BSD license. All rights reserved.\r\n*\r\n************************************************************************\/\r\n\r\n#include \"Graphics\/API.h\"\r\n\r\n#ifdef ENABLE_RENDERER_OPENGL\r\n\r\n#include \"Graphics\/RenderDevice.h\"\r\n#include \"Graphics\/RenderContext.h\"\r\n#include \"Graphics\/RenderBackend.h\"\r\n#include \"Graphics\/RenderBatch.h\"\r\n#include \"Graphics\/RenderView.h\"\r\n#include \"Graphics\/ShaderProgram.h\"\r\n#include \"Graphics\/GeometryBuffer.h\"\r\n\r\n#include \"Graphics\/BufferManager.h\"\r\n#include \"Graphics\/ShaderProgramManager.h\"\r\n#include \"Graphics\/TextureManager.h\"\r\n\r\n#include \"Core\/Utilities.h\"\r\n#include <algorithm>\r\n\r\nNAMESPACE_GRAPHICS_BEGIN\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nREFLECT_ENUM(RenderPipeline)\r\n\tENUM(Fixed)\r\n\tENUM(ShaderForward)\r\n\tENUM(ShaderDeferred)\r\nREFLECT_ENUM_END()\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic RenderDevice* gs_RenderDevice = nullptr;\r\nRenderDevice* GetRenderDevice() { return gs_RenderDevice; }\r\n\r\nRenderDevice::RenderDevice()\r\n\t: activeContext(nullptr)\r\n\t, activeTarget(nullptr)\r\n\t, activeView(nullptr)\r\n\t, renderBackend(nullptr)\r\n\t\/\/, shadowDepthBuffer(nullptr)\r\n\t, pipeline(RenderPipeline::ShaderForward)\r\n{\r\n\tgs_RenderDevice = this;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nRenderDevice::~RenderDevice()\r\n{\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::updateRenderTargets()\r\n{\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool RenderStateSorter(const RenderState& lhs, const RenderState& rhs)\r\n{\r\n\tint rA = (int) lhs.renderable->getRenderLayer();\r\n\tint rB = (int) rhs.renderable->getRenderLayer();\r\n\tint pA = lhs.priority;\r\n\tint pB = rhs.priority;\r\n\r\n\treturn (rA == rB) ? (pA < pB) : (rA < rB);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::render( RenderBlock& queue ) \r\n{\r\n\t#pragma TODO(\"Sort the render group by depth distance\")\r\n\r\n\t\/\/ Sort the renderables by render group.\r\n\tstd::sort( queue.renderables.begin(), queue.renderables.end(), &RenderStateSorter );\r\n\r\n\t\/\/ Render all the renderables in the queue.\r\n\tfor( size_t i = 0; i < queue.renderables.size(); i++ )\r\n\t{\r\n\t\tconst RenderState& state = queue.renderables[i];\r\n\t\trender(state, queue.lights);\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::render( const RenderState& state, const LightQueue& lights )\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tProgramManager* programs = activeContext->programManager;\r\n\t\r\n\tRenderBatch* renderable = state.renderable;\r\n\tbindBuffers(renderable);\r\n\r\n\tconst GeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\tif( gb->data.empty() ) return;\r\n\r\n\tBufferEntry* bufs = buffers->getBuffer(gb);\r\n\r\n\t\/\/ Setup the vertex buffer format.\r\n\tVertexBuffer* vb = bufs->vb.get();\r\n\trenderBackend->setupVertexBuffer(vb);\r\n\t\r\n\tMaterial* material = state.material;\r\n\tShaderMaterial* shader = material->getShader().Resolve();\r\n\r\n\tShaderProgram* shaderProgram = programs->getProgram(shader);\r\n\tif( !shaderProgram ) return;\r\n\r\n\tif( !shaderProgram->isLinked() && !shaderProgram->link() )\r\n\t\treturn;\r\n\r\n\tshaderProgram->bind();\r\n\r\n\trenderBackend->setupRenderState(state, true);\r\n\tbindTextureUnits(state, true);\r\n\r\n\tif( !renderable->onPreRender.empty() )\r\n\t{\r\n\t\t\/\/ Call the user pre render hook.\r\n\t\trenderable->onPreRender(activeView, state);\r\n\t}\r\n\r\n\tRenderLayer stage = renderable->getRenderLayer();\r\n\r\n\tif( stage != RenderLayer::Overlays )\r\n\t{\r\n\t\tif( !setupRenderStateMatrix(state) )\r\n\t\t\treturn;\r\n\r\n\t\t\/\/if( !setupRenderStateLight(state, lights) )\r\n\t\t\/\/\treturn;\r\n\t}\r\n\telse if( stage == RenderLayer::Overlays )\r\n\t{\r\n\t\tif( !setupRenderStateOverlay(state) )\r\n\t\t\treturn;\r\n\t}\r\n\r\n\tUniformBuffer* ub = renderable->getUniformBuffer().get();\r\n\tshaderProgram->setUniforms(ub);\r\n\r\n\trenderBackend->renderBatch(renderable);\r\n\t\r\n\tif( !renderable->onPostRender.empty() )\r\n\t{\r\n\t\t\/\/ Call the user post render hook.\r\n\t\trenderable->onPostRender(activeView, state);\r\n\t}\r\n\t\r\n\trenderBackend->unsetupRenderState(state);\r\n\tunbindTextureUnits(state.material);\r\n\t\r\n\tshaderProgram->unbind();\r\n\r\n\trenderBackend->unbindVertexBuffer(vb);\r\n\tunbindBuffers(renderable);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::bindTextureUnits(const RenderState& state, bool bindUniforms)\r\n{\r\n\tTextureUnitMap& units = state.material->textureUnits;\r\n\tUniformBuffer* ub = state.renderable->getUniformBuffer().get();\r\n\r\n\tTextureUnitMap::const_iterator it;\r\n\tfor( it = units.begin(); it != units.end(); it++ )\r\n\t{\r\n\t\tconst TextureUnit& unit = it->second;\r\n\t\tconst ImageHandle& handle = unit.image;\r\n\r\n\t\tTexture* texture = activeContext->textureManager->getTexture(handle).get();\r\n\t\tif( !texture ) continue;\r\n\r\n\t\tif( !texture->isUploaded() )\r\n\t\t{\r\n\t\t\trenderBackend->uploadTexture(texture);\r\n\t\t\trenderBackend->configureTexture(texture);\r\n\t\t}\r\n\r\n\t\trenderBackend->setupTextureUnit(texture, unit);\r\n\t\trenderBackend->bindTexture(texture);\r\n\t\t\r\n\t\tif( !bindUniforms ) continue;\r\n\r\n\t\tchar s_TextureUniform[] = \"vp_Texture0\";\r\n\t\tsize_t s_TextureUniformSize = FLD_ARRAY_SIZE(s_TextureUniform) - 2;\r\n\r\n\t\t\/\/ Build the uniform string without allocating memory.\r\n\t\tuint8 index = unit.unit;\r\n\t\tchar indexChar = (index + '0');\r\n\t\t\r\n\t\ts_TextureUniform[s_TextureUniformSize] = indexChar;\r\n\t\tub->setUniform( s_TextureUniform, (int32) index );\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::unbindTextureUnits(Material* material)\r\n{\r\n\tTextureUnitMap& units = material->textureUnits;\r\n\tTextureManager* textureManager = activeContext->textureManager;\r\n\r\n\tTextureUnitMap::const_iterator it;\r\n\tfor( it = units.begin(); it != units.end(); it++ )\r\n\t{\r\n\t\tconst TextureUnit& unit = it->second;\r\n\t\tconst ImageHandle& handle = unit.image;\r\n\r\n\t\tTexture* texture = textureManager->getTexture(handle).get();\r\n\t\tif( !texture ) continue;\r\n\r\n\t\trenderBackend->setupTextureUnit(texture, unit);\r\n\t\trenderBackend->unbindTexture(texture);\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateMatrix( const RenderState& state )\r\n{\r\n\tconst Matrix4x3& matModel = state.modelMatrix;\r\n\tconst Matrix4x3& matView = activeView->viewMatrix;\r\n\tconst Matrix4x4& matProjection = activeView->projectionMatrix;\r\n\r\n\tUniformBuffer* ub = state.renderable->getUniformBuffer().get();\r\n\tub->setUniform( \"vp_ModelMatrix\", matModel );\r\n\tub->setUniform( \"vp_ViewMatrix\", matView );\r\n\tub->setUniform( \"vp_ProjectionMatrix\", matProjection );\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::bindBuffers(RenderBatch* renderable)\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tGeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\r\n\tVertexBuffer* vb = buffers->getVertexBuffer(gb).get();\r\n\tIndexBuffer* ib = buffers->getIndexBuffer(gb).get();\r\n\t\r\n\tif( !vb ) return false;\r\n\r\n\tif( !vb->isBuilt() || gb->needsRebuild )\r\n\t{\r\n\t\t\/\/ If the vertex buffer is not built yet, then we build it.\r\n\t\trenderBackend->buildVertexBuffer(vb);\r\n\t}\r\n\r\n\trenderBackend->bindVertexBuffer(vb);\r\n\r\n\t\/\/ If there is no index buffer associated with the geometry, we are done.\r\n\tif( !ib ) goto done;\r\n\r\n\trenderBackend->bindIndexBuffer(ib);\r\n\t\r\n\tif( !ib->isBuilt || gb->needsRebuild )\r\n\t{\r\n\t\t\/\/ If the index buffer is not built, we also need to build it.\r\n\t\trenderBackend->buildIndexBuffer(ib);\r\n\t}\r\n\r\ndone:\r\n\r\n\tgb->needsRebuild = false;\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::unbindBuffers(RenderBatch* renderable)\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tconst GeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\t\r\n\tVertexBuffer* vb = buffers->getVertexBuffer(gb).get();\r\n\tif( !vb ) return false;\r\n\t\r\n\trenderBackend->unbindVertexBuffer(vb);\r\n\r\n\tIndexBuffer* ib = buffers->getIndexBuffer(gb).get();\r\n\tif( ib ) renderBackend->unbindIndexBuffer(ib);\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n#if 0\r\nvoid RenderDevice::updateLightDepth( LightState& state )\r\n{\r\n#if 0\r\n\tconst LightPtr& light = state.light;\r\n\tassert( light->getLightType() == LightType::Directional );\r\n\r\n\tTexture* shadowDepthTexture;\r\n\t\r\n\tif( !shadowDepthBuffer )\r\n\t{\r\n\t\tshadowDepthBuffer = createRenderBuffer( Settings(512, 512) );\r\n\t}\r\n\r\n\tif( shadowTextures.find(light) == shadowTextures.end() )\r\n\t{\r\n\t\tshadowDepthTexture = shadowDepthBuffer->createRenderTexture();\r\n\t\tshadowTextures[light] = shadowDepthTexture;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tshadowDepthTexture = shadowTextures[light];\r\n\t}\r\n\r\n\tCameraPtr lightCamera( new Camera(*camera) );\r\n\tTransformPtr lightTransform( new Transform(*state.transform.get()) );\r\n\t\r\n\tEntityPtr lightCameraEntity( new Entity(\"ShadowCamera\") );\r\n\tlightCameraEntity->addTransform(); \/*Component( lightTransform );*\/\r\n\tlightCameraEntity->addComponent( lightCamera );\r\n\r\n\tRenderView* lightView = new View(lightCamera, shadowDepthBuffer);\r\n\r\n\tif( !shadowDepthBuffer->check() )\r\n\t\treturn;\r\n\r\n\t\/\/ TODO: turn off color writes (glColorMask?)\r\n\tlightView->update();\r\n\tshadowDepthBuffer->unbind();\r\n\r\n\tMatrix4x4 bias;\r\n\tbias.identity();\r\n\tbias.m11 = 0.5f;\r\n\tbias.m22 = 0.5f;\r\n\tbias.m33 = 0.5f;\r\n\tbias.tx = 0.5f;\r\n\tbias.ty = 0.5f;\r\n\tbias.tz = 0.5f;\r\n\r\n\tconst Frustum& frustum = lightCamera->getFrustum();\r\n\tconst Matrix4x4& matProjection = frustum.projectionMatrix;\r\n\r\n\tstate.projection = lightCamera->getViewMatrix()\r\n\t\t* matProjection * bias;\r\n#endif\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateShadow( LightQueue& lights )\r\n{\r\n#if 0\r\n\tif( lights.empty() ) return true;\r\n\r\n\tfor( size_t i = 0; i < lights.size(); i++ )\r\n\t{\r\n\t\tLightState& state = lights[i];\r\n\t\tconst Light* light = state.light;\r\n\r\n\t\tif( !light->getCastsShadows() )\r\n\t\t\tcontinue;\r\n\r\n\t\tupdateLightDepth( state );\r\n\t}\r\n#endif\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateLight( const RenderState& state, const LightQueue& lights )\r\n{\r\n#if 0\r\n\tconst UniformBufferPtr& ub = state.renderable->getUniformBuffer();\r\n\r\n\tfor( size_t i = 0; i < lights.size(); i++ )\r\n\t{\r\n\t\tconst LightState& lightState = lights[i];\r\n\t\tconst Light* light = lightState.light;\r\n\r\n\t\t\/\/TexturePtr shadowDepthTexture;\r\n\t\t\/\/shadowDepthTexture = shadowTextures[light];\r\n\t\t\/\/assert( shadowDepthTexture != nullptr );\r\n\r\n\t\tstd::vector< Color > colors;\r\n\t\tcolors.push_back( light->getDiffuseColor() );\r\n\t\tcolors.push_back( light->getSpecularColor() );\r\n\t\tcolors.push_back( light->getEmissiveColor() );\r\n\t\tcolors.push_back( light->getAmbientColor() );\r\n\r\n\t\tconst Transform* transform = lightState.transform;\r\n\r\n\t\t\/\/ TODO: fix the lighting stuff\r\n\t\tub->setUniform( \"vp_LightColors\", colors );\r\n\t\tub->setUniform( \"vp_LightDirection\", transform->getRotationMatrix() );\r\n\t\t\/\/ub->setUniform( \"vp_ShadowMap\", shadowDepthTexture->id() );\r\n\t\t\/\/ub->setUniform( \"vp_CameraProj\", state.modelMatrix * lightState.projection );\r\n\t}\r\n#endif\r\n\r\n\treturn true;\r\n}\r\n#endif\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateOverlay( const RenderState& state )\r\n{\r\n\tVector2i size = activeTarget->getSettings().getSize();\r\n\tMatrix4x4 projection = Matrix4x4::createOrthographic(0, size.x, size.y, 0, -100, 100);\r\n\r\n\tconst UniformBufferPtr& ub = state.renderable->getUniformBuffer();\r\n\tub->setUniform( \"vp_ProjectionMatrix\", projection );\r\n\tub->setUniform( \"vp_ModelMatrix\", state.modelMatrix );\r\n\tub->setUniform( \"vp_ViewMatrix\", Matrix4x4::Identity );\r\n\tub->setUniform( \"vp_ModelViewMatrix\", state.modelMatrix );\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::setActiveView( RenderView* view )\r\n{\r\n\tactiveView = view;\r\n\tif( !activeView ) return;\r\n\r\n\tsetRenderTarget(view->getRenderTarget());\r\n\trenderBackend->setupRenderView(view);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::clearView()\r\n{\r\n\trenderBackend->clearRenderView(activeView);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::setRenderTarget(RenderTarget* target)\r\n{\r\n\tactiveTarget = target;\r\n\tif( !activeTarget ) return;\r\n\r\n\t\/\/activeTarget->makeCurrent();\r\n\tactiveContext = activeTarget->getContext();\r\n\r\n\trenderBackend = activeContext->backend;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::isFixedPipeline() const\r\n{\r\n\treturn pipeline == RenderPipeline::Fixed;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nNAMESPACE_GRAPHICS_END\r\n\r\n#endif<commit_msg>Fixed bug causing TextureUnits with bad wrap on the first frame.<commit_after>\/************************************************************************\r\n*\r\n* Flood Project (2008-201x)\r\n* Licensed under the simplified BSD license. All rights reserved.\r\n*\r\n************************************************************************\/\r\n\r\n#include \"Graphics\/API.h\"\r\n\r\n#ifdef ENABLE_RENDERER_OPENGL\r\n\r\n#include \"Graphics\/RenderDevice.h\"\r\n#include \"Graphics\/RenderContext.h\"\r\n#include \"Graphics\/RenderBackend.h\"\r\n#include \"Graphics\/RenderBatch.h\"\r\n#include \"Graphics\/RenderView.h\"\r\n#include \"Graphics\/ShaderProgram.h\"\r\n#include \"Graphics\/GeometryBuffer.h\"\r\n\r\n#include \"Graphics\/BufferManager.h\"\r\n#include \"Graphics\/ShaderProgramManager.h\"\r\n#include \"Graphics\/TextureManager.h\"\r\n\r\n#include \"Core\/Utilities.h\"\r\n#include <algorithm>\r\n\r\nNAMESPACE_GRAPHICS_BEGIN\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nREFLECT_ENUM(RenderPipeline)\r\n\tENUM(Fixed)\r\n\tENUM(ShaderForward)\r\n\tENUM(ShaderDeferred)\r\nREFLECT_ENUM_END()\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic RenderDevice* gs_RenderDevice = nullptr;\r\nRenderDevice* GetRenderDevice() { return gs_RenderDevice; }\r\n\r\nRenderDevice::RenderDevice()\r\n\t: activeContext(nullptr)\r\n\t, activeTarget(nullptr)\r\n\t, activeView(nullptr)\r\n\t, renderBackend(nullptr)\r\n\t\/\/, shadowDepthBuffer(nullptr)\r\n\t, pipeline(RenderPipeline::ShaderForward)\r\n{\r\n\tgs_RenderDevice = this;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nRenderDevice::~RenderDevice()\r\n{\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::updateRenderTargets()\r\n{\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool RenderStateSorter(const RenderState& lhs, const RenderState& rhs)\r\n{\r\n\tint rA = (int) lhs.renderable->getRenderLayer();\r\n\tint rB = (int) rhs.renderable->getRenderLayer();\r\n\tint pA = lhs.priority;\r\n\tint pB = rhs.priority;\r\n\r\n\treturn (rA == rB) ? (pA < pB) : (rA < rB);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::render( RenderBlock& queue ) \r\n{\r\n\t#pragma TODO(\"Sort the render group by depth distance\")\r\n\r\n\t\/\/ Sort the renderables by render group.\r\n\tstd::sort( queue.renderables.begin(), queue.renderables.end(), &RenderStateSorter );\r\n\r\n\t\/\/ Render all the renderables in the queue.\r\n\tfor( size_t i = 0; i < queue.renderables.size(); i++ )\r\n\t{\r\n\t\tconst RenderState& state = queue.renderables[i];\r\n\t\trender(state, queue.lights);\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::render( const RenderState& state, const LightQueue& lights )\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tProgramManager* programs = activeContext->programManager;\r\n\t\r\n\tRenderBatch* renderable = state.renderable;\r\n\tbindBuffers(renderable);\r\n\r\n\tconst GeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\tif( gb->data.empty() ) return;\r\n\r\n\tBufferEntry* bufs = buffers->getBuffer(gb);\r\n\r\n\t\/\/ Setup the vertex buffer format.\r\n\tVertexBuffer* vb = bufs->vb.get();\r\n\trenderBackend->setupVertexBuffer(vb);\r\n\t\r\n\tMaterial* material = state.material;\r\n\tShaderMaterial* shader = material->getShader().Resolve();\r\n\r\n\tShaderProgram* shaderProgram = programs->getProgram(shader);\r\n\tif( !shaderProgram ) return;\r\n\r\n\tif( !shaderProgram->isLinked() && !shaderProgram->link() )\r\n\t\treturn;\r\n\r\n\tshaderProgram->bind();\r\n\r\n\trenderBackend->setupRenderState(state, true);\r\n\tbindTextureUnits(state, true);\r\n\r\n\tif( !renderable->onPreRender.empty() )\r\n\t{\r\n\t\t\/\/ Call the user pre render hook.\r\n\t\trenderable->onPreRender(activeView, state);\r\n\t}\r\n\r\n\tRenderLayer stage = renderable->getRenderLayer();\r\n\r\n\tif( stage != RenderLayer::Overlays )\r\n\t{\r\n\t\tif( !setupRenderStateMatrix(state) )\r\n\t\t\treturn;\r\n\r\n\t\t\/\/if( !setupRenderStateLight(state, lights) )\r\n\t\t\/\/\treturn;\r\n\t}\r\n\telse if( stage == RenderLayer::Overlays )\r\n\t{\r\n\t\tif( !setupRenderStateOverlay(state) )\r\n\t\t\treturn;\r\n\t}\r\n\r\n\tUniformBuffer* ub = renderable->getUniformBuffer().get();\r\n\tshaderProgram->setUniforms(ub);\r\n\r\n\trenderBackend->renderBatch(renderable);\r\n\t\r\n\tif( !renderable->onPostRender.empty() )\r\n\t{\r\n\t\t\/\/ Call the user post render hook.\r\n\t\trenderable->onPostRender(activeView, state);\r\n\t}\r\n\t\r\n\trenderBackend->unsetupRenderState(state);\r\n\tunbindTextureUnits(state.material);\r\n\t\r\n\tshaderProgram->unbind();\r\n\r\n\trenderBackend->unbindVertexBuffer(vb);\r\n\tunbindBuffers(renderable);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::bindTextureUnits(const RenderState& state, bool bindUniforms)\r\n{\r\n\tTextureUnitMap& units = state.material->textureUnits;\r\n\tUniformBuffer* ub = state.renderable->getUniformBuffer().get();\r\n\r\n\tTextureUnitMap::const_iterator it;\r\n\tfor( it = units.begin(); it != units.end(); it++ )\r\n\t{\r\n\t\tconst TextureUnit& unit = it->second;\r\n\t\tconst ImageHandle& handle = unit.image;\r\n\r\n\t\tTexture* texture = activeContext->textureManager->getTexture(handle).get();\r\n\t\tif( !texture ) continue;\r\n\r\n\t\tif( !texture->isUploaded() )\r\n\t\t{\r\n\t\t\trenderBackend->uploadTexture(texture);\r\n\t\t\trenderBackend->configureTexture(texture);\r\n\t\t}\r\n\r\n\t\trenderBackend->bindTexture(texture);\r\n\t\trenderBackend->setupTextureUnit(texture, unit);\r\n\t\t\r\n\t\tif( !bindUniforms ) continue;\r\n\r\n\t\tchar s_TextureUniform[] = \"vp_Texture0\";\r\n\t\tsize_t s_TextureUniformSize = FLD_ARRAY_SIZE(s_TextureUniform) - 2;\r\n\r\n\t\t\/\/ Build the uniform string without allocating memory.\r\n\t\tuint8 index = unit.unit;\r\n\t\tchar indexChar = (index + '0');\r\n\t\t\r\n\t\ts_TextureUniform[s_TextureUniformSize] = indexChar;\r\n\t\tub->setUniform( s_TextureUniform, (int32) index );\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::unbindTextureUnits(Material* material)\r\n{\r\n\tTextureUnitMap& units = material->textureUnits;\r\n\tTextureManager* textureManager = activeContext->textureManager;\r\n\r\n\tTextureUnitMap::const_iterator it;\r\n\tfor( it = units.begin(); it != units.end(); it++ )\r\n\t{\r\n\t\tconst TextureUnit& unit = it->second;\r\n\t\tconst ImageHandle& handle = unit.image;\r\n\r\n\t\tTexture* texture = textureManager->getTexture(handle).get();\r\n\t\tif( !texture ) continue;\r\n\r\n\t\trenderBackend->setupTextureUnit(texture, unit);\r\n\t\trenderBackend->unbindTexture(texture);\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateMatrix( const RenderState& state )\r\n{\r\n\tconst Matrix4x3& matModel = state.modelMatrix;\r\n\tconst Matrix4x3& matView = activeView->viewMatrix;\r\n\tconst Matrix4x4& matProjection = activeView->projectionMatrix;\r\n\r\n\tUniformBuffer* ub = state.renderable->getUniformBuffer().get();\r\n\tub->setUniform( \"vp_ModelMatrix\", matModel );\r\n\tub->setUniform( \"vp_ViewMatrix\", matView );\r\n\tub->setUniform( \"vp_ProjectionMatrix\", matProjection );\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::bindBuffers(RenderBatch* renderable)\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tGeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\r\n\tVertexBuffer* vb = buffers->getVertexBuffer(gb).get();\r\n\tIndexBuffer* ib = buffers->getIndexBuffer(gb).get();\r\n\t\r\n\tif( !vb ) return false;\r\n\r\n\tif( !vb->isBuilt() || gb->needsRebuild )\r\n\t{\r\n\t\t\/\/ If the vertex buffer is not built yet, then we build it.\r\n\t\trenderBackend->buildVertexBuffer(vb);\r\n\t}\r\n\r\n\trenderBackend->bindVertexBuffer(vb);\r\n\r\n\t\/\/ If there is no index buffer associated with the geometry, we are done.\r\n\tif( !ib ) goto done;\r\n\r\n\trenderBackend->bindIndexBuffer(ib);\r\n\t\r\n\tif( !ib->isBuilt || gb->needsRebuild )\r\n\t{\r\n\t\t\/\/ If the index buffer is not built, we also need to build it.\r\n\t\trenderBackend->buildIndexBuffer(ib);\r\n\t}\r\n\r\ndone:\r\n\r\n\tgb->needsRebuild = false;\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::unbindBuffers(RenderBatch* renderable)\r\n{\r\n\tBufferManager* buffers = activeContext->bufferManager;\r\n\tconst GeometryBuffer* gb = renderable->getGeometryBuffer().get();\r\n\t\r\n\tVertexBuffer* vb = buffers->getVertexBuffer(gb).get();\r\n\tif( !vb ) return false;\r\n\t\r\n\trenderBackend->unbindVertexBuffer(vb);\r\n\r\n\tIndexBuffer* ib = buffers->getIndexBuffer(gb).get();\r\n\tif( ib ) renderBackend->unbindIndexBuffer(ib);\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n#if 0\r\nvoid RenderDevice::updateLightDepth( LightState& state )\r\n{\r\n#if 0\r\n\tconst LightPtr& light = state.light;\r\n\tassert( light->getLightType() == LightType::Directional );\r\n\r\n\tTexture* shadowDepthTexture;\r\n\t\r\n\tif( !shadowDepthBuffer )\r\n\t{\r\n\t\tshadowDepthBuffer = createRenderBuffer( Settings(512, 512) );\r\n\t}\r\n\r\n\tif( shadowTextures.find(light) == shadowTextures.end() )\r\n\t{\r\n\t\tshadowDepthTexture = shadowDepthBuffer->createRenderTexture();\r\n\t\tshadowTextures[light] = shadowDepthTexture;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tshadowDepthTexture = shadowTextures[light];\r\n\t}\r\n\r\n\tCameraPtr lightCamera( new Camera(*camera) );\r\n\tTransformPtr lightTransform( new Transform(*state.transform.get()) );\r\n\t\r\n\tEntityPtr lightCameraEntity( new Entity(\"ShadowCamera\") );\r\n\tlightCameraEntity->addTransform(); \/*Component( lightTransform );*\/\r\n\tlightCameraEntity->addComponent( lightCamera );\r\n\r\n\tRenderView* lightView = new View(lightCamera, shadowDepthBuffer);\r\n\r\n\tif( !shadowDepthBuffer->check() )\r\n\t\treturn;\r\n\r\n\t\/\/ TODO: turn off color writes (glColorMask?)\r\n\tlightView->update();\r\n\tshadowDepthBuffer->unbind();\r\n\r\n\tMatrix4x4 bias;\r\n\tbias.identity();\r\n\tbias.m11 = 0.5f;\r\n\tbias.m22 = 0.5f;\r\n\tbias.m33 = 0.5f;\r\n\tbias.tx = 0.5f;\r\n\tbias.ty = 0.5f;\r\n\tbias.tz = 0.5f;\r\n\r\n\tconst Frustum& frustum = lightCamera->getFrustum();\r\n\tconst Matrix4x4& matProjection = frustum.projectionMatrix;\r\n\r\n\tstate.projection = lightCamera->getViewMatrix()\r\n\t\t* matProjection * bias;\r\n#endif\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateShadow( LightQueue& lights )\r\n{\r\n#if 0\r\n\tif( lights.empty() ) return true;\r\n\r\n\tfor( size_t i = 0; i < lights.size(); i++ )\r\n\t{\r\n\t\tLightState& state = lights[i];\r\n\t\tconst Light* light = state.light;\r\n\r\n\t\tif( !light->getCastsShadows() )\r\n\t\t\tcontinue;\r\n\r\n\t\tupdateLightDepth( state );\r\n\t}\r\n#endif\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateLight( const RenderState& state, const LightQueue& lights )\r\n{\r\n#if 0\r\n\tconst UniformBufferPtr& ub = state.renderable->getUniformBuffer();\r\n\r\n\tfor( size_t i = 0; i < lights.size(); i++ )\r\n\t{\r\n\t\tconst LightState& lightState = lights[i];\r\n\t\tconst Light* light = lightState.light;\r\n\r\n\t\t\/\/TexturePtr shadowDepthTexture;\r\n\t\t\/\/shadowDepthTexture = shadowTextures[light];\r\n\t\t\/\/assert( shadowDepthTexture != nullptr );\r\n\r\n\t\tstd::vector< Color > colors;\r\n\t\tcolors.push_back( light->getDiffuseColor() );\r\n\t\tcolors.push_back( light->getSpecularColor() );\r\n\t\tcolors.push_back( light->getEmissiveColor() );\r\n\t\tcolors.push_back( light->getAmbientColor() );\r\n\r\n\t\tconst Transform* transform = lightState.transform;\r\n\r\n\t\t\/\/ TODO: fix the lighting stuff\r\n\t\tub->setUniform( \"vp_LightColors\", colors );\r\n\t\tub->setUniform( \"vp_LightDirection\", transform->getRotationMatrix() );\r\n\t\t\/\/ub->setUniform( \"vp_ShadowMap\", shadowDepthTexture->id() );\r\n\t\t\/\/ub->setUniform( \"vp_CameraProj\", state.modelMatrix * lightState.projection );\r\n\t}\r\n#endif\r\n\r\n\treturn true;\r\n}\r\n#endif\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::setupRenderStateOverlay( const RenderState& state )\r\n{\r\n\tVector2i size = activeTarget->getSettings().getSize();\r\n\tMatrix4x4 projection = Matrix4x4::createOrthographic(0, size.x, size.y, 0, -100, 100);\r\n\r\n\tconst UniformBufferPtr& ub = state.renderable->getUniformBuffer();\r\n\tub->setUniform( \"vp_ProjectionMatrix\", projection );\r\n\tub->setUniform( \"vp_ModelMatrix\", state.modelMatrix );\r\n\tub->setUniform( \"vp_ViewMatrix\", Matrix4x4::Identity );\r\n\tub->setUniform( \"vp_ModelViewMatrix\", state.modelMatrix );\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::setActiveView( RenderView* view )\r\n{\r\n\tactiveView = view;\r\n\tif( !activeView ) return;\r\n\r\n\tsetRenderTarget(view->getRenderTarget());\r\n\trenderBackend->setupRenderView(view);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::clearView()\r\n{\r\n\trenderBackend->clearRenderView(activeView);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nvoid RenderDevice::setRenderTarget(RenderTarget* target)\r\n{\r\n\tactiveTarget = target;\r\n\tif( !activeTarget ) return;\r\n\r\n\t\/\/activeTarget->makeCurrent();\r\n\tactiveContext = activeTarget->getContext();\r\n\r\n\trenderBackend = activeContext->backend;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nbool RenderDevice::isFixedPipeline() const\r\n{\r\n\treturn pipeline == RenderPipeline::Fixed;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nNAMESPACE_GRAPHICS_END\r\n\r\n#endif<|endoftext|>"} {"text":"<commit_before>#include \"LoadSupportController.h\"\n\n\n#include <string>\n#include <iostream>\n\n\nLoadSupportController::LoadSupportController(ros::NodeHandle &n,\n double frequency,\n double M_object,\n double Z_ceiling,\n double Z_level,\n double Max_Weitht_compensation,\n std::vector<double> ee_rest_position,\n std::string topic_wrench_external,\n std::string topic_wrench_control,\n std::string topic_desired_equilibrium)\n\t: nh_(n),\n\t loop_rate_(frequency),\n\t M_object_(M_object),\n\t MAX_weight_(Max_Weitht_compensation),\n\t ee_rest_position_(ee_rest_position.data()),\n\t Z_ceiling_(Z_ceiling),\n\t Z_level_(Z_level),\n\t dt_(1 \/ frequency) {\n\n\tROS_INFO_STREAM(\"Load-Support-Controoler is created at: \" << nh_.getNamespace() << \" with freq: \" << frequency << \"Hz\");\n\n\t\/\/ a subscriber to get read the external forces\n\tsub_external_wrench_ = nh_.subscribe(topic_wrench_external, 5,\n\t &LoadSupportController::UpdateExternalForce, this,\n\t ros::TransportHints().reliable().tcpNoDelay());\n\n\t\/\/ a publisher to send the control wrench:\n\tpub_control_wrench_ = nh_.advertise<geometry_msgs::WrenchStamped>(topic_wrench_control, 5);\n\n\t\/\/ a publisher to send the desired equilibrium point:\n\tpub_desired_equilibrium_ = nh_.advertise<geometry_msgs::Point>(topic_desired_equilibrium, 5);\n\n\n\t\/\/ initializing the sensed weight as zero\n\tWeight_ = 0;\n\n\t\/\/ initializing the load-share as zero\n\tloadShare_ = 0;\n\n\t\/\/ initializing the control force as zero\n\tForce_control_.setZero();\n\n\t\/\/ initializing the attractor at the rest position\n\tattractor_ = ee_rest_position_;\n\n\t\/\/ initializing the position of the object at the rest position\n\tobject_position_ = ee_rest_position_;\n\n\t\/\/ assuming the object is far away\n\tdist_object_ee_ground_ = 1e2;\n\n\t\/\/ a refractory period (e.g 2seconds) between each talking commands\n\ttalking_rate_ = 2;\n\t\/\/ a time-duration that robot should not stay silent more than\n\ttalking_forced_rate_ = 10;\n\n\t\/\/ intializing some sentence for the robot\n\tspeech_statement_ = \"I have nothing to say!\";\n\tspeech_statement_last_ = speech_statement_;\n}\n\n\n\nvoid LoadSupportController::Run() {\n\n\t\/\/ wait for soundplay to start running\n\tros::Duration(1).sleep();\n\t\/\/ Say something on the startup\n\tsoundclinet_.say(\"I am alive! How can I serve you?\");\n\t\/\/ wait for the sound to be played\n\tros::Duration(2).sleep();\n\n\t\/\/ reseting ROS-Time (not really necessary I guess).\n\tros::Time::now();\n\n\t\/\/ next time that the robot is allowed to speak\n\ttime_to_be_silient_ = ros::Time::now() + ros::Duration(talking_rate_);\n\t\/\/ next maximum time that the robot say something\n\ttime_to_say_something_ = ros::Time::now() + ros::Duration(talking_forced_rate_);\n\n\n\twhile (nh_.ok() ) {\n\n\t\tFindObject();\n\n\t\tComputeLoadShare();\n\n\t\tWeightCompensation();\n\n\t\tComputeEquilibriumPoint();\n\n\t\t\/\/ the robot only talks if a refractory period has passed (i.e., talking_rate_)\n\t\tif ( (ros::Time::now() - time_to_be_silient_).toSec() > 0 ) {\n\t\t\tif (speech_statement_.compare(speech_statement_last_) || (ros::Time::now() - time_to_say_something_).toSec() > 0) {\n\t\t\t\tSayWhatIsHappining();\n\t\t\t\ttime_to_be_silient_ = ros::Time::now() + ros::Duration(talking_rate_);\n\t\t\t\ttime_to_say_something_ = ros::Time::now() + ros::Duration(talking_forced_rate_);\n\t\t\t}\n\t\t}\n\n\t\tros::spinOnce();\n\t\tloop_rate_.sleep();\n\t}\n\n}\n\n\/\/ The robot says what is stored in \"speech_statement_\"\nvoid LoadSupportController::SayWhatIsHappining() {\n\n\t\/\/ only talk if the robot has something new to say\n\t\/\/ if (speech_statement_.compare(speech_statement_last_) ) {\n\tspeech_statement_last_ = speech_statement_;\n\tsoundclinet_.say(speech_statement_);\n\tROS_INFO_STREAM_THROTTLE(1, \"Talking: \" << speech_statement_);\n\t\/\/ }\n}\n\nvoid LoadSupportController::FindObject() {\n\n\ttf::StampedTransform transform;\n\tVector3d object_to_ee;\n\n\tobject_to_ee.setZero();\n\n\t\/\/ first we read and check the distance of the object with respect to the end-effector of the robot\n\ttry {\n\t\tlistener_object_.lookupTransform(\"robotiq_force_torque_frame_id\", \"object\",\n\t\t \/\/ listener_object_.lookupTransform(\"mocap_palm\", \"mocap_object\",\n\t\t ros::Time(0), transform);\n\n\t\tobject_to_ee << transform.getOrigin().x(),\n\t\t transform.getOrigin().y(),\n\t\t transform.getOrigin().z();\n\n\t\tdist_object_ee_ground_ = object_to_ee.segment(0, 2).norm();\n\n\t\tif (dist_object_ee_ground_ > 1) {\n\t\t\tspeech_statement_ = \"The object is too far.\";\n\t\t\tobject_position_ = ee_rest_position_;\n\n\n\t\t\tif (loadShare_ > 0.8) {\n\t\t\t\tspeech_statement_ = \"The marker is too far. I keep the object here.\";\n\t\t\t}\n\n\n\t\t}\n\t\telse {\n\t\t\tspeech_statement_ = \"I am coming to help you.\";\n\n\t\t\ttry {\n\t\t\t\tlistener_object_.lookupTransform(\"ur5_arm_base_link\", \"object\",\n\t\t\t\t ros::Time(0), transform);\n\n\t\t\t\tobject_position_ << transform.getOrigin().x(),\n\t\t\t\t transform.getOrigin().y(),\n\t\t\t\t transform.getOrigin().z();\n\n\t\t\t}\n\t\t\tcatch (tf::TransformException ex) {\n\t\t\t\tROS_WARN_THROTTLE(1, \"Couldn't find transform between arm and the object\");\n\t\t\t}\n\n\n\t\t\tif (loadShare_ > 0.8) {\n\t\t\t\tspeech_statement_ = \"I am bringing the object for you\";\n\t\t\t}\n\n\n\t\t\tif (dist_object_ee_ground_ < .1) {\n\t\t\t\tspeech_statement_ = \"I am under the marker.\";\n\n\t\t\t\tif (loadShare_ > 0.6) {\n\t\t\t\t\tspeech_statement_ = \"I am holding the object.\";\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t}\n\t}\n\tcatch (tf::TransformException ex) {\n\t\tROS_WARN_THROTTLE(1, \"Couldn't find transform between ee and the object\");\n\t\tspeech_statement_ = \"I can not find the object!\";\n\t\tdist_object_ee_ground_ = 1e2;\n\t}\n\n\tROS_INFO_STREAM_THROTTLE(1, \"distance to ee: \" << dist_object_ee_ground_);\n\n\n\n\t\/\/ double dt = loop_rate_.expectedCycleTime().toSec();\n\n\t\/\/ attractor_ += pow(0.95,1\/dt) * (object_position_ - attractor_);\n\t\/\/ ROS_INFO_STREAM_THROTTLE(1, \"dt :\" << loop_rate_.expectedCycleTime().toSec());\n\n\t\/\/ update only the x and y of the attractor based on the location of the object\n\tattractor_.segment(0, 2) += 0.05 * (object_position_.segment(0, 2) - attractor_.segment(0, 2) );\n\n\n\n\t\/\/ ROS_INFO_STREAM_THROTTLE(1, \"X_att:\" << attractor_ );\n\n}\n\n\n\nvoid LoadSupportController::UpdateExternalForce(const geometry_msgs::WrenchStamped::ConstPtr& msg) {\n\n\twrench_external_ << msg->wrench.force.x, msg->wrench.force.y, msg->wrench.force.z,\n\t msg->wrench.torque.x, msg->wrench.torque.y, msg->wrench.torque.z;\n\n}\n\n\nvoid LoadSupportController::ComputeLoadShare() {\n\n\t\/\/ filtering the z-axis forces to meausre the weight supported by the robot\n\tWeight_ += 0.1 * ( -wrench_external_(2) - Weight_);\n\n\tROS_INFO_STREAM_THROTTLE(1, \"weight: \" << Weight_);\n\n\n\n\t\/\/ constraining the sensed weight between 0 and allowed-maximum of what is expected\n\tWeight_ = (Weight_ < 0) ? 0 : Weight_;\n\tWeight_ = (Weight_ > MAX_weight_) ? MAX_weight_ : Weight_;\n\n\t\/\/ computing the load-share\n\tloadShare_ = Weight_ \/ M_object_ \/ gravity_acc;\n\n\t\/\/ display load-share on the screen every second\n\tROS_INFO_STREAM_THROTTLE(1, \"load-share \" << loadShare_);\n\n\t\/\/ saturating the load-share at 1\n\tloadShare_ = (loadShare_ > 1) ? 1 : loadShare_;\n}\n\n\n\nvoid LoadSupportController::WeightCompensation() {\n\n\t\/\/ computing the remainder of the weight for the expected object\n\tdouble Weight_missing = (M_object_ * gravity_acc) - Weight_;\n\tWeight_missing = (Weight_missing < 0) ? 0 : Weight_missing;\n\n\t\/\/ forces applied side-way to the end-effector\n\tdouble Weight_sidway = wrench_external_.segment(0, 2).norm();\n\n\t\/\/ by default we cancel all external forces\n\tForce_control_ = -wrench_external_.segment(0, 3);\n\n\t\/\/ if the side-way forces are more than missing weight, we just add a deadzone\n\tif ( Weight_sidway > Weight_missing) {\n\t\tForce_control_ = (Weight_missing \/ Weight_sidway) * Force_control_;\n\t}\n\n\t\/\/ simply compensating the weight by applying the exact opposite force\n\tForce_control_(2) = Weight_;\n\n\t\/\/ sending the control Force over the corresponding ROS-topic\n\tgeometry_msgs::WrenchStamped msg_wrench;\n\n\tmsg_wrench.header.stamp = ros::Time::now();\n\tmsg_wrench.header.frame_id = \"ur5_arm_base_link\";\n\tmsg_wrench.wrench.force.x = Force_control_(0);\n\tmsg_wrench.wrench.force.y = Force_control_(1);\n\tmsg_wrench.wrench.force.z = Force_control_(2);\n\tmsg_wrench.wrench.torque.x = 0;\n\tmsg_wrench.wrench.torque.y = 0;\n\tmsg_wrench.wrench.torque.z = 0;\n\tpub_control_wrench_.publish(msg_wrench);\n\n}\n\n\n\n\n\nvoid LoadSupportController::ComputeEquilibriumPoint() {\n\n\n\n\t\/\/ starting by the rest hieght of the arm\n\tdouble att_target = (dist_object_ee_ground_ > 0.2) ? ee_rest_position_(2) : Z_ceiling_;\n\n\tif (loadShare_ > 0.8) {\n\t\tdouble beta = (loadShare_ - 0.8) \/ 0.1;\n\t\tbeta = (beta > 1) ? 1 : beta;\n\t\tatt_target = (1 - beta) * Z_ceiling_ + beta * Z_level_;\n\t\tROS_INFO_STREAM_THROTTLE(1, \"Lowering the weight \" << att_target);\n\t}\n\n\n\t\/\/ filtering the Location of the attractor\n\tdouble att_err = att_target - attractor_(2);\n\n\t\/\/ attractor_(2) += ((att_err > 0) ? 0.001 : 0.0005 ) * att_err;\n\tattractor_(2) += 0.005 * att_err;\n\n\t\/\/ saturating the Z_attractor\n\tattractor_(2) = (attractor_(2) < Z_level_ ) ? Z_level_ : attractor_(2);\n\tattractor_(2) = (attractor_(2) > Z_ceiling_) ? Z_ceiling_ : attractor_(2);\n\n\t\/\/ sending the desired attractor over the corresponding ROS-topic\n\tgeometry_msgs::Point msg_point;\n\tmsg_point.x = attractor_(0);\n\tmsg_point.y = attractor_(1);\n\tmsg_point.z = attractor_(2);\n\tpub_desired_equilibrium_.publish(msg_point);\n\n}\n<commit_msg>add comments for each function<commit_after>#include \"LoadSupportController.h\"\n\n\n#include <string>\n#include <iostream>\n\n\nLoadSupportController::LoadSupportController(ros::NodeHandle &n,\n double frequency,\n double M_object,\n double Z_ceiling,\n double Z_level,\n double Max_Weitht_compensation,\n std::vector<double> ee_rest_position,\n std::string topic_wrench_external,\n std::string topic_wrench_control,\n std::string topic_desired_equilibrium)\n\t: nh_(n),\n\t loop_rate_(frequency),\n\t M_object_(M_object),\n\t MAX_weight_(Max_Weitht_compensation),\n\t ee_rest_position_(ee_rest_position.data()),\n\t Z_ceiling_(Z_ceiling),\n\t Z_level_(Z_level),\n\t dt_(1 \/ frequency) {\n\n\tROS_INFO_STREAM(\"Load-Support-Controoler is created at: \" << nh_.getNamespace() << \" with freq: \" << frequency << \"Hz\");\n\n\t\/\/ a subscriber to get read the external forces\n\tsub_external_wrench_ = nh_.subscribe(topic_wrench_external, 5,\n\t &LoadSupportController::UpdateExternalForce, this,\n\t ros::TransportHints().reliable().tcpNoDelay());\n\n\t\/\/ a publisher to send the control wrench:\n\tpub_control_wrench_ = nh_.advertise<geometry_msgs::WrenchStamped>(topic_wrench_control, 5);\n\n\t\/\/ a publisher to send the desired equilibrium point:\n\tpub_desired_equilibrium_ = nh_.advertise<geometry_msgs::Point>(topic_desired_equilibrium, 5);\n\n\n\t\/\/ initializing the sensed weight as zero\n\tWeight_ = 0;\n\n\t\/\/ initializing the load-share as zero\n\tloadShare_ = 0;\n\n\t\/\/ initializing the control force as zero\n\tForce_control_.setZero();\n\n\t\/\/ initializing the attractor at the rest position\n\tattractor_ = ee_rest_position_;\n\n\t\/\/ initializing the position of the object at the rest position\n\tobject_position_ = ee_rest_position_;\n\n\t\/\/ assuming the object is far away\n\tdist_object_ee_ground_ = 1e2;\n\n\t\/\/ a refractory period (e.g 2seconds) between each talking commands\n\ttalking_rate_ = 3;\n\t\/\/ a time-duration that robot should not stay silent more than\n\ttalking_forced_rate_ = 9;\n\n\t\/\/ intializing the sentence for the robot\n\tspeech_statement_ = \"I have nothing to say!\";\n\tspeech_statement_last_ = speech_statement_;\n}\n\n\n\nvoid LoadSupportController::Run() {\n\n\t\/\/ wait for soundplay to start running\n\tros::Duration(1).sleep();\n\t\/\/ Say something on the startup\n\tsoundclinet_.say(\"I am alive! How can I serve you?\");\n\t\/\/ wait for the sound to be played\n\tros::Duration(2).sleep();\n\n\t\/\/ reseting ROS-Time (not really necessary I guess).\n\tros::Time::now();\n\n\t\/\/ next time that the robot is allowed to speak\n\ttime_to_be_silient_ = ros::Time::now() + ros::Duration(talking_rate_);\n\t\/\/ next maximum time that the robot say something\n\ttime_to_say_something_ = ros::Time::now() + ros::Duration(talking_forced_rate_);\n\n\n\twhile (nh_.ok() ) {\n\n\t\tFindObject();\n\n\t\tComputeLoadShare();\n\n\t\tWeightCompensation();\n\n\t\tComputeEquilibriumPoint();\n\n\t\t\/\/ the robot only talks if a refractory period has passed (i.e., talking_rate_)\n\t\tif ( (ros::Time::now() - time_to_be_silient_).toSec() > 0 ) {\n\t\t\tif (speech_statement_.compare(speech_statement_last_) || (ros::Time::now() - time_to_say_something_).toSec() > 0) {\n\t\t\t\tSayWhatIsHappining();\n\t\t\t\ttime_to_be_silient_ = ros::Time::now() + ros::Duration(talking_rate_);\n\t\t\t\ttime_to_say_something_ = ros::Time::now() + ros::Duration(talking_forced_rate_);\n\t\t\t}\n\t\t}\n\n\t\tros::spinOnce();\n\t\tloop_rate_.sleep();\n\t}\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Here we comput how of the object is held by the robot \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::ComputeLoadShare() {\n\n\t\/\/ filtering the z-axis forces to meausre the weight supported by the robot\n\tWeight_ += 0.1 * ( -wrench_external_(2) - Weight_);\n\n\tROS_INFO_STREAM_THROTTLE(1, \"weight: \" << Weight_);\n\n\n\n\t\/\/ constraining the sensed weight between 0 and allowed-maximum of what is expected\n\tWeight_ = (Weight_ < 0) ? 0 : Weight_;\n\tWeight_ = (Weight_ > MAX_weight_) ? MAX_weight_ : Weight_;\n\n\t\/\/ computing the load-share\n\tloadShare_ = Weight_ \/ M_object_ \/ gravity_acc;\n\n\t\/\/ display load-share on the screen every second\n\tROS_INFO_STREAM_THROTTLE(1, \"load-share \" << loadShare_);\n\n\t\/\/ saturating the load-share at 1\n\tloadShare_ = (loadShare_ > 1) ? 1 : loadShare_;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Here, we compensate for the weight of the object and \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ add a deadzone for the sideway forces in order to not \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ to react to forces created by a tilted object \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::WeightCompensation() {\n\n\t\/\/ computing the remainder of the weight for the expected object\n\tdouble Weight_missing = (M_object_ * gravity_acc) - Weight_;\n\tWeight_missing = (Weight_missing < 0) ? 0 : Weight_missing;\n\n\t\/\/ forces applied side-way to the end-effector\n\tdouble Weight_sidway = wrench_external_.segment(0, 2).norm();\n\n\t\/\/ by default we cancel all external forces\n\tForce_control_ = -wrench_external_.segment(0, 3);\n\n\t\/\/ if the side-way forces are more than missing weight, we just add a deadzone\n\tif ( Weight_sidway > Weight_missing) {\n\t\tForce_control_ = (Weight_missing \/ Weight_sidway) * Force_control_;\n\t}\n\n\t\/\/ simply compensating the weight by applying the exact opposite force\n\tForce_control_(2) = Weight_;\n\n\t\/\/ sending the control Force over the corresponding ROS-topic\n\tgeometry_msgs::WrenchStamped msg_wrench;\n\n\tmsg_wrench.header.stamp = ros::Time::now();\n\tmsg_wrench.header.frame_id = \"ur5_arm_base_link\";\n\tmsg_wrench.wrench.force.x = Force_control_(0);\n\tmsg_wrench.wrench.force.y = Force_control_(1);\n\tmsg_wrench.wrench.force.z = Force_control_(2);\n\tmsg_wrench.wrench.torque.x = 0;\n\tmsg_wrench.wrench.torque.y = 0;\n\tmsg_wrench.wrench.torque.z = 0;\n\tpub_control_wrench_.publish(msg_wrench);\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ based on the load that the robot is holding, it \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ computes a new equilibrium point for the admittance \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ control in order to bring dwon the object. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::ComputeEquilibriumPoint() {\n\n\t\/\/ starting by the rest hieght of the arm\n\tdouble att_target = (dist_object_ee_ground_ > 0.2) ? ee_rest_position_(2) : Z_ceiling_;\n\n\tif (loadShare_ > 0.8) {\n\t\tdouble beta = (loadShare_ - 0.8) \/ 0.1;\n\t\tbeta = (beta > 1) ? 1 : beta;\n\t\tatt_target = (1 - beta) * Z_ceiling_ + beta * Z_level_;\n\t\tROS_INFO_STREAM_THROTTLE(1, \"Lowering the weight \" << att_target);\n\t}\n\n\t\/\/ filtering the Location of the attractor\n\tdouble att_err = att_target - attractor_(2);\n\n\t\/\/ attractor_(2) += ((att_err > 0) ? 0.001 : 0.0005 ) * att_err;\n\tattractor_(2) += 0.005 * att_err;\n\n\t\/\/ saturating the Z_attractor\n\tattractor_(2) = (attractor_(2) < Z_level_ ) ? Z_level_ : attractor_(2);\n\tattractor_(2) = (attractor_(2) > Z_ceiling_) ? Z_ceiling_ : attractor_(2);\n\n\t\/\/ sending the desired attractor over the corresponding ROS-topic\n\tgeometry_msgs::Point msg_point;\n\tmsg_point.x = attractor_(0);\n\tmsg_point.y = attractor_(1);\n\tmsg_point.z = attractor_(2);\n\tpub_desired_equilibrium_.publish(msg_point);\n\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Here, the robot say the 'speach_statement_' \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::SayWhatIsHappining() {\n\n\t\/\/ only talk if the robot has something new to say\n\t\/\/ if (speech_statement_.compare(speech_statement_last_) ) {\n\tspeech_statement_last_ = speech_statement_;\n\tsoundclinet_.say(speech_statement_);\n\tROS_INFO_STREAM_THROTTLE(1, \"Talking: \" << speech_statement_);\n\t\/\/ }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ In this function, the robot look for the marker \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ and based on the distance of the object to its \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end-effector and the value of the load-share \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ it decides to either follow the marker or stay \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ put. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::FindObject() {\n\n\ttf::StampedTransform transform;\n\tVector3d object_to_ee;\n\n\tobject_to_ee.setZero();\n\n\t\/\/ first we read and check the distance of the object with respect to the end-effector of the robot\n\ttry {\n\t\tlistener_object_.lookupTransform(\"robotiq_force_torque_frame_id\", \"object\",\n\t\t \/\/ listener_object_.lookupTransform(\"mocap_palm\", \"mocap_object\",\n\t\t ros::Time(0), transform);\n\n\t\tobject_to_ee << transform.getOrigin().x(),\n\t\t transform.getOrigin().y(),\n\t\t transform.getOrigin().z();\n\n\t\tdist_object_ee_ground_ = object_to_ee.segment(0, 2).norm();\n\n\t\tif (dist_object_ee_ground_ > 1) {\n\t\t\tspeech_statement_ = \"The object is too far.\";\n\t\t\tobject_position_ = ee_rest_position_;\n\n\t\t\tif (loadShare_ > 0.8) {\n\t\t\t\tspeech_statement_ = \"The marker is too far.\";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tspeech_statement_ = \"Coming to help.\";\n\n\t\t\ttry {\n\t\t\t\tlistener_object_.lookupTransform(\"ur5_arm_base_link\", \"object\",\n\t\t\t\t ros::Time(0), transform);\n\n\t\t\t\tobject_position_ << transform.getOrigin().x(),\n\t\t\t\t transform.getOrigin().y(),\n\t\t\t\t transform.getOrigin().z();\n\n\t\t\t}\n\t\t\tcatch (tf::TransformException ex) {\n\t\t\t\tROS_WARN_THROTTLE(1, \"Couldn't find transform between arm and the object\");\n\t\t\t}\n\n\t\t\tif (loadShare_ > 0.8) {\n\t\t\t\tspeech_statement_ = \"Bringing the object\";\n\t\t\t}\n\t\t\tif (dist_object_ee_ground_ < .1) {\n\t\t\t\tspeech_statement_ = \"Under the marker.\";\n\n\t\t\t\tif (loadShare_ > 0.6) {\n\t\t\t\t\tspeech_statement_ = \"Holding the object.\";\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\tcatch (tf::TransformException ex) {\n\t\tROS_WARN_THROTTLE(1, \"Couldn't find transform between ee and the object\");\n\t\tspeech_statement_ = \"I can not find the marker!\";\n\t\tdist_object_ee_ground_ = 1e2;\n\t}\n\n\t\/\/ ROS_INFO_STREAM_THROTTLE(1, \"distance to ee: \" << dist_object_ee_ground_);\n\t\/\/ double dt = loop_rate_.expectedCycleTime().toSec();\n\n\t\/\/ attractor_ += pow(0.95,1\/dt) * (object_position_ - attractor_);\n\t\/\/ ROS_INFO_STREAM_THROTTLE(1, \"dt :\" << loop_rate_.expectedCycleTime().toSec());\n\n\t\/\/ update only the x and y of the attractor based on the location of the object\n\tattractor_.segment(0, 2) += 0.05 * (object_position_.segment(0, 2) - attractor_.segment(0, 2) );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ A callback to receive the external forces \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid LoadSupportController::UpdateExternalForce(const geometry_msgs::WrenchStamped::ConstPtr& msg) {\n\n\twrench_external_ << msg->wrench.force.x, msg->wrench.force.y, msg->wrench.force.z,\n\t msg->wrench.torque.x, msg->wrench.torque.y, msg->wrench.torque.z;\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/CopasiDataModel\/CCopasiDataModel.cpp,v $\n $Revision: 1.15 $\n $Name: $\n $Author: ssahle $ \n $Date: 2005\/04\/12 15:09:13 $\n End CVS Header *\/\n\n#include \"copasi.h\"\n#include \"copasiversion.h\"\n#include \"CCopasiDataModel.h\"\n\n#include \"commandline\/COptions.h\"\n#include \"function\/CFunctionDB.h\"\n#include \"model\/CModel.h\"\n#include \"utilities\/CCopasiVector.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"utilities\/CCopasiProblem.h\"\n#include \"steadystate\/CSteadyStateTask.h\"\n#include \"trajectory\/CTrajectoryTask.h\"\n#include \"scan\/CScanTask.h\"\n#include \"optimization\/COptTask.h\"\n#include \"steadystate\/CMCATask.h\"\n#include \"steadystate\/CMCAMethod.h\"\n#include \"report\/CReportDefinitionVector.h\"\n#include \"plot\/CPlotSpecification.h\"\n#include \"xml\/CCopasiXML.h\"\n#include \"sbml\/SBMLImporter.h\"\n#include \"sbml\/SBMLExporter.h\"\n\nCDataModelRenameHandler::CDataModelRenameHandler(CCopasiDataModel* dm)\n : mpDataModel(dm)\n{}\n\nbool CDataModelRenameHandler::handle(const std::string & oldCN, const std::string & newCN) const\n {\n std::cout << \"CDataModelRenameHandler::handle()\" << std::endl;\n std::cout << \" old: \" << oldCN << std::endl;\n std::cout << \" new: \" << newCN << std::endl << std::endl;\n\n return true;\n }\n\n\/\/********************************************************************\n\nCCopasiDataModel * CCopasiDataModel::Global = NULL;\n\nCCopasiDataModel::CCopasiDataModel(const bool withGUI):\n mpVersion(new CVersion),\n mpFunctionList(new CFunctionDB),\n mpModel(NULL),\n mpTaskList(NULL),\n mpReportDefinitionList(NULL),\n mpPlotDefinitionList(NULL),\n mWithGUI(withGUI),\n mpGUI(NULL),\n mChanged(false),\n mAutoSaveNeeded(false),\n mRenameHandler(this),\n pOldMetabolites(new CCopasiVectorS < CMetabOld >)\n{\n mpVersion->setVersion(COPASI_VERSION_MAJOR,\n COPASI_VERSION_MINOR,\n COPASI_VERSION_BUILD);\n\n mpFunctionList->load();\n newModel();\n CCopasiObject::setRenameHandler(&mRenameHandler); \/\/TODO where in the contructor should this be called?\n}\n\nCCopasiDataModel::~CCopasiDataModel()\n{\n pdelete(mpVersion);\n pdelete(mpFunctionList);\n pdelete(mpModel);\n pdelete(mpTaskList);\n pdelete(mpReportDefinitionList);\n pdelete(mpPlotDefinitionList);\n pdelete(mpGUI);\n pdelete(pOldMetabolites);\n}\n\nbool CCopasiDataModel::loadModel(const std::string & fileName)\n{\n std::ifstream File(fileName.c_str());\n\n if (File.fail())\n {\n CCopasiMessage Message(CCopasiMessage::RAW,\n \"File error when opening '%s'.\",\n fileName.c_str());\n return false;\n }\n\n std::string Line;\n File >> Line;\n\n if (!Line.compare(0, 8, \"Version=\"))\n {\n if (fileName.rfind(\".gps\") == fileName.length() - 4 ||\n fileName.rfind(\".GPS\") == fileName.length() - 4)\n mSaveFileName = fileName.substr(0, fileName.length() - 4) + \".cps\";\n else\n mSaveFileName = fileName + \".cps\";\n\n File.close();\n CReadConfig inbuf(fileName.c_str());\n\n newModel();\n mpModel->load(inbuf);\n\n dynamic_cast<CSteadyStateTask *>((*mpTaskList)[\"Steady-State\"])->load(inbuf);\n dynamic_cast<CTrajectoryTask *>((*mpTaskList)[\"Time-Course\"])->load(inbuf);\n }\n else if (!Line.compare(0, 5, \"<?xml\"))\n {\n mSaveFileName = fileName;\n\n std::cout << \"XML Format\" << std::endl;\n File.seekg(0, std::ios_base::beg);\n\n CCopasiXML XML;\n\n XML.setFunctionList(mpFunctionList->loadedFunctions());\n\n SCopasiXMLGUI *pGUI = NULL;\n\n if (mWithGUI)\n {\n pGUI = new SCopasiXMLGUI;\n XML.setGUI(*pGUI);\n }\n\n if (!XML.load(File))\n {\n XML.freeModel();\n XML.freeTaskList();\n XML.freeReportList();\n XML.freePlotList();\n XML.freeGUI();\n\n return false;\n }\n\n newModel();\n\n if (XML.getModel())\n {\n pdelete(mpModel);\n mpModel = XML.getModel();\n }\n\n if (XML.getTaskList())\n {\n pdelete(mpTaskList);\n mpTaskList = XML.getTaskList();\n mpTaskList->setObjectName(\"TaskList\");\n CCopasiContainer::Root->add(mpTaskList, true);\n addDefaultTasks();\n }\n\n if (XML.getReportList())\n {\n pdelete(mpReportDefinitionList);\n mpReportDefinitionList = new CReportDefinitionVector;\n *static_cast< CCopasiVector< CReportDefinition > * >(mpReportDefinitionList) = *XML.getReportList();\n }\n\n if (XML.getPlotList())\n {\n pdelete(mpPlotDefinitionList);\n mpPlotDefinitionList = XML.getPlotList();\n mpPlotDefinitionList->setObjectName(\"PlotList\");\n CCopasiContainer::Root->add(mpPlotDefinitionList, true);\n }\n\n if (mWithGUI)\n {\n pdelete(mpGUI);\n mpGUI = pGUI;\n }\n }\n\n if (mpModel) mpModel->setCompileFlag();\n\n changed(false);\n return true;\n}\n\nbool CCopasiDataModel::saveModel(const std::string & fileName, bool overwriteFile,\n const bool & autoSave)\n{\n std::string FileName = (fileName != \"\") ? fileName : mSaveFileName;\n\n \/\/ test first if a file would accidentaly overwritten.\n std::ifstream testInfile(FileName.c_str(), std::ios::in);\n\n if (testInfile && !overwriteFile)\n {\n CCopasiMessage(CCopasiMessage::ERROR, MCSBML + 1, FileName.c_str());\n return false;\n }\n\n mpModel->compileIfNecessary();\n\n CCopasiXML XML;\n\n XML.setModel(*mpModel);\n XML.setTaskList(*mpTaskList);\n XML.setReportList(*mpReportDefinitionList);\n XML.setPlotList(*mpPlotDefinitionList);\n XML.setGUI(*mpGUI);\n\n \/\/ We are first writing to a temporary stream to prevent accidental\n \/\/ destruction of an existing file in case the save command fails.\n std::ostringstream tmp;\n if (!XML.save(tmp)) return false;\n\n std::ofstream os(FileName.c_str());\n if (os.fail()) return false;\n\n os << tmp.str();\n if (os.fail()) return false;\n\n if (!autoSave) changed(false);\n\n return true;\n}\n\nbool CCopasiDataModel::autoSave()\n{\n if (!mAutoSaveNeeded) return true;\n\n std::string AutoSave;\n int index;\n COptions::getValue(\"Tmp\", AutoSave);\n if (AutoSave == \"\") return false;\n#ifdef WIN32\n AutoSave += \"\\\\\";\n#else\n AutoSave += \"\/\";\n#endif\n\n if ((index = mSaveFileName.find_last_of('\\\\')) == -1)\n index = mSaveFileName.find_last_of('\/');\n \/\/index = mSaveFileName.find_last_of('\/' || '\\\\');\n AutoSave += \"tmp_\" + mSaveFileName.substr(index + 1, mSaveFileName.length() - index - 5) + \".cps\";\n\n if (!saveModel(AutoSave, true)) return false;\n\n mAutoSaveNeeded = false;\n return true;\n}\n\nbool CCopasiDataModel::newModel(CModel * pModel)\n{\n pdelete(mpModel);\n mpModel = (pModel) ? pModel : new CModel();\n\n pdelete(mpTaskList);\n mpTaskList = new CCopasiVectorN< CCopasiTask >(\"TaskList\", CCopasiContainer::Root);\n\n \/\/ We have at least one task of every type\n addDefaultTasks();\n\n pdelete(mpReportDefinitionList);\n mpReportDefinitionList = new CReportDefinitionVector;\n\n pdelete(mpPlotDefinitionList);\n mpPlotDefinitionList = new CCopasiVectorN< CPlotSpecification >(\"PlotList\", CCopasiContainer::Root);\n\n if (mWithGUI)\n {\n pdelete(mpGUI);\n mpGUI = new SCopasiXMLGUI;\n }\n\n changed(false);\n\n return true;\n}\n\nbool CCopasiDataModel::importSBML(const std::string & fileName)\n{\n if (fileName.rfind(\".xml\") == fileName.length() - 4 ||\n fileName.rfind(\".XML\") == fileName.length() - 4)\n mSaveFileName = fileName.substr(0, fileName.length() - 4) + \".cps\";\n else\n mSaveFileName = fileName + \".cps\";\n\n SBMLImporter importer;\n CModel * pModel = importer.readSBML(fileName, mpFunctionList);\n\n if (pModel == NULL) return false;\n\n return newModel(pModel);\n}\n\nbool CCopasiDataModel::exportSBML(const std::string & fileName, bool overwriteFile)\n{\n if (fileName == \"\") return false;\n\n SBMLExporter exporter;\n\n return exporter.exportSBML(mpModel, fileName.c_str(), overwriteFile);\n}\n\nCModel * CCopasiDataModel::getModel()\n{return mpModel;}\n\nCCopasiVectorN< CCopasiTask > * CCopasiDataModel::getTaskList()\n{return mpTaskList;}\n\n\/\/ static\nCCopasiTask * CCopasiDataModel::addTask(const CCopasiTask::Type & taskType)\n{\n CCopasiTask * pTask = NULL;\n\n switch (taskType)\n {\n case CCopasiTask::steadyState:\n pTask = new CSteadyStateTask(mpTaskList);\n break;\n\n case CCopasiTask::timeCourse:\n pTask = new CTrajectoryTask(mpTaskList);\n break;\n\n case CCopasiTask::scan:\n pTask = new CScanTask(mpTaskList);\n break;\n\n case CCopasiTask::fluxMode:\n \/\/ :TODO: implement task for elementary flux mode analysis\n return pTask;\n break;\n\n case CCopasiTask::optimization:\n \/\/ :TODO: implement task for optimization\n return pTask;\n break;\n\n case CCopasiTask::parameterFitting:\n \/\/ :TODO: implement task for parameter fitting\n return pTask;\n break;\n\n case CCopasiTask::mca:\n pTask = new CMCATask(mpTaskList);\n \/\/ :TODO: This must be avoided.\n static_cast<CMCAMethod *>(pTask->getMethod())->setModel(mpModel);\n break;\n\n default:\n return pTask;\n }\n\n pTask->getProblem()->setModel(mpModel);\n mpTaskList->add(pTask);\n\n return pTask;\n}\n\nbool CCopasiDataModel::addDefaultTasks()\n{\n if (mpTaskList->getIndex(\"Steady-State\") == C_INVALID_INDEX)\n addTask(CCopasiTask::steadyState);\n\n if (mpTaskList->getIndex(\"Time-Course\") == C_INVALID_INDEX)\n addTask(CCopasiTask::timeCourse);\n\n if (mpTaskList->getIndex(\"Scan\") == C_INVALID_INDEX)\n addTask(CCopasiTask::scan);\n\n if (mpTaskList->getIndex(\"Elementary Flux Modes\") == C_INVALID_INDEX)\n addTask(CCopasiTask::fluxMode);\n\n if (mpTaskList->getIndex(\"Optimization\") == C_INVALID_INDEX)\n addTask(CCopasiTask::optimization);\n\n if (mpTaskList->getIndex(\"Parameter Fitting\") == C_INVALID_INDEX)\n addTask(CCopasiTask::parameterFitting);\n\n if (mpTaskList->getIndex(\"Metabolic Control Analysis\") == C_INVALID_INDEX)\n addTask(CCopasiTask::mca);\n\n return true;\n}\n\nCReportDefinitionVector * CCopasiDataModel::getReportDefinitionList()\n{return mpReportDefinitionList;}\n\nCCopasiVectorN<CPlotSpecification> * CCopasiDataModel::getPlotDefinitionList()\n{return mpPlotDefinitionList;}\n\nCFunctionDB * CCopasiDataModel::getFunctionList()\n{return mpFunctionList;}\n\nSCopasiXMLGUI * CCopasiDataModel::getGUI()\n{return mpGUI;}\n\nCVersion * CCopasiDataModel::getVersion()\n{return mpVersion;}\n\nbool CCopasiDataModel::isChanged() const\n {return mChanged;}\n\nvoid CCopasiDataModel::changed(const bool & changed)\n{\n mChanged = changed;\n mAutoSaveNeeded = changed;\n}\n<commit_msg>the rename handler gets the list of CNs from CRegisteredObjectNames. It does not yet do anything with it.<commit_after>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/CopasiDataModel\/CCopasiDataModel.cpp,v $\n $Revision: 1.16 $\n $Name: $\n $Author: ssahle $ \n $Date: 2005\/04\/12 22:13:15 $\n End CVS Header *\/\n\n#include \"copasi.h\"\n#include \"copasiversion.h\"\n#include \"CCopasiDataModel.h\"\n\n#include \"commandline\/COptions.h\"\n#include \"function\/CFunctionDB.h\"\n#include \"model\/CModel.h\"\n#include \"utilities\/CCopasiVector.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"utilities\/CCopasiProblem.h\"\n#include \"steadystate\/CSteadyStateTask.h\"\n#include \"trajectory\/CTrajectoryTask.h\"\n#include \"scan\/CScanTask.h\"\n#include \"optimization\/COptTask.h\"\n#include \"steadystate\/CMCATask.h\"\n#include \"steadystate\/CMCAMethod.h\"\n#include \"report\/CReportDefinitionVector.h\"\n#include \"plot\/CPlotSpecification.h\"\n#include \"xml\/CCopasiXML.h\"\n#include \"sbml\/SBMLImporter.h\"\n#include \"sbml\/SBMLExporter.h\"\n\nCDataModelRenameHandler::CDataModelRenameHandler(CCopasiDataModel* dm)\n : mpDataModel(dm)\n{}\n\nbool CDataModelRenameHandler::handle(const std::string & oldCN, const std::string & newCN) const\n {\n std::cout << \"CDataModelRenameHandler::handle()\" << std::endl;\n std::cout << \" old: \" << oldCN << std::endl;\n std::cout << \" new: \" << newCN << std::endl;\n\n const std::set<CRegisteredObjectName*> nameSet = CRegisteredObjectName::getSet();\n\n std::cout << \" ************ \" << nameSet.size() << std::endl;\n std::set<CRegisteredObjectName*>::const_iterator it, itEnd = nameSet.end();\n for (it = nameSet.begin(); it != itEnd; ++it)\n {\n std::cout << \" \" << **it << std::endl;\n }\n\n std::cout << \" \" << std::endl;\n return true;\n }\n\n\/\/********************************************************************\n\nCCopasiDataModel * CCopasiDataModel::Global = NULL;\n\nCCopasiDataModel::CCopasiDataModel(const bool withGUI):\n mpVersion(new CVersion),\n mpFunctionList(new CFunctionDB),\n mpModel(NULL),\n mpTaskList(NULL),\n mpReportDefinitionList(NULL),\n mpPlotDefinitionList(NULL),\n mWithGUI(withGUI),\n mpGUI(NULL),\n mChanged(false),\n mAutoSaveNeeded(false),\n mRenameHandler(this),\n pOldMetabolites(new CCopasiVectorS < CMetabOld >)\n{\n mpVersion->setVersion(COPASI_VERSION_MAJOR,\n COPASI_VERSION_MINOR,\n COPASI_VERSION_BUILD);\n\n mpFunctionList->load();\n newModel();\n CCopasiObject::setRenameHandler(&mRenameHandler); \/\/TODO where in the contructor should this be called?\n}\n\nCCopasiDataModel::~CCopasiDataModel()\n{\n pdelete(mpVersion);\n pdelete(mpFunctionList);\n pdelete(mpModel);\n pdelete(mpTaskList);\n pdelete(mpReportDefinitionList);\n pdelete(mpPlotDefinitionList);\n pdelete(mpGUI);\n pdelete(pOldMetabolites);\n}\n\nbool CCopasiDataModel::loadModel(const std::string & fileName)\n{\n std::ifstream File(fileName.c_str());\n\n if (File.fail())\n {\n CCopasiMessage Message(CCopasiMessage::RAW,\n \"File error when opening '%s'.\",\n fileName.c_str());\n return false;\n }\n\n std::string Line;\n File >> Line;\n\n if (!Line.compare(0, 8, \"Version=\"))\n {\n if (fileName.rfind(\".gps\") == fileName.length() - 4 ||\n fileName.rfind(\".GPS\") == fileName.length() - 4)\n mSaveFileName = fileName.substr(0, fileName.length() - 4) + \".cps\";\n else\n mSaveFileName = fileName + \".cps\";\n\n File.close();\n CReadConfig inbuf(fileName.c_str());\n\n newModel();\n mpModel->load(inbuf);\n\n dynamic_cast<CSteadyStateTask *>((*mpTaskList)[\"Steady-State\"])->load(inbuf);\n dynamic_cast<CTrajectoryTask *>((*mpTaskList)[\"Time-Course\"])->load(inbuf);\n }\n else if (!Line.compare(0, 5, \"<?xml\"))\n {\n mSaveFileName = fileName;\n\n std::cout << \"XML Format\" << std::endl;\n File.seekg(0, std::ios_base::beg);\n\n CCopasiXML XML;\n\n XML.setFunctionList(mpFunctionList->loadedFunctions());\n\n SCopasiXMLGUI *pGUI = NULL;\n\n if (mWithGUI)\n {\n pGUI = new SCopasiXMLGUI;\n XML.setGUI(*pGUI);\n }\n\n if (!XML.load(File))\n {\n XML.freeModel();\n XML.freeTaskList();\n XML.freeReportList();\n XML.freePlotList();\n XML.freeGUI();\n\n return false;\n }\n\n newModel();\n\n if (XML.getModel())\n {\n pdelete(mpModel);\n mpModel = XML.getModel();\n }\n\n if (XML.getTaskList())\n {\n pdelete(mpTaskList);\n mpTaskList = XML.getTaskList();\n mpTaskList->setObjectName(\"TaskList\");\n CCopasiContainer::Root->add(mpTaskList, true);\n addDefaultTasks();\n }\n\n if (XML.getReportList())\n {\n pdelete(mpReportDefinitionList);\n mpReportDefinitionList = new CReportDefinitionVector;\n *static_cast< CCopasiVector< CReportDefinition > * >(mpReportDefinitionList) = *XML.getReportList();\n }\n\n if (XML.getPlotList())\n {\n pdelete(mpPlotDefinitionList);\n mpPlotDefinitionList = XML.getPlotList();\n mpPlotDefinitionList->setObjectName(\"PlotList\");\n CCopasiContainer::Root->add(mpPlotDefinitionList, true);\n }\n\n if (mWithGUI)\n {\n pdelete(mpGUI);\n mpGUI = pGUI;\n }\n }\n\n if (mpModel) mpModel->setCompileFlag();\n\n changed(false);\n return true;\n}\n\nbool CCopasiDataModel::saveModel(const std::string & fileName, bool overwriteFile,\n const bool & autoSave)\n{\n std::string FileName = (fileName != \"\") ? fileName : mSaveFileName;\n\n \/\/ test first if a file would accidentaly overwritten.\n std::ifstream testInfile(FileName.c_str(), std::ios::in);\n\n if (testInfile && !overwriteFile)\n {\n CCopasiMessage(CCopasiMessage::ERROR, MCSBML + 1, FileName.c_str());\n return false;\n }\n\n mpModel->compileIfNecessary();\n\n CCopasiXML XML;\n\n XML.setModel(*mpModel);\n XML.setTaskList(*mpTaskList);\n XML.setReportList(*mpReportDefinitionList);\n XML.setPlotList(*mpPlotDefinitionList);\n XML.setGUI(*mpGUI);\n\n \/\/ We are first writing to a temporary stream to prevent accidental\n \/\/ destruction of an existing file in case the save command fails.\n std::ostringstream tmp;\n if (!XML.save(tmp)) return false;\n\n std::ofstream os(FileName.c_str());\n if (os.fail()) return false;\n\n os << tmp.str();\n if (os.fail()) return false;\n\n if (!autoSave) changed(false);\n\n return true;\n}\n\nbool CCopasiDataModel::autoSave()\n{\n if (!mAutoSaveNeeded) return true;\n\n std::string AutoSave;\n int index;\n COptions::getValue(\"Tmp\", AutoSave);\n if (AutoSave == \"\") return false;\n#ifdef WIN32\n AutoSave += \"\\\\\";\n#else\n AutoSave += \"\/\";\n#endif\n\n if ((index = mSaveFileName.find_last_of('\\\\')) == -1)\n index = mSaveFileName.find_last_of('\/');\n \/\/index = mSaveFileName.find_last_of('\/' || '\\\\');\n AutoSave += \"tmp_\" + mSaveFileName.substr(index + 1, mSaveFileName.length() - index - 5) + \".cps\";\n\n if (!saveModel(AutoSave, true)) return false;\n\n mAutoSaveNeeded = false;\n return true;\n}\n\nbool CCopasiDataModel::newModel(CModel * pModel)\n{\n pdelete(mpModel);\n mpModel = (pModel) ? pModel : new CModel();\n\n pdelete(mpTaskList);\n mpTaskList = new CCopasiVectorN< CCopasiTask >(\"TaskList\", CCopasiContainer::Root);\n\n \/\/ We have at least one task of every type\n addDefaultTasks();\n\n pdelete(mpReportDefinitionList);\n mpReportDefinitionList = new CReportDefinitionVector;\n\n pdelete(mpPlotDefinitionList);\n mpPlotDefinitionList = new CCopasiVectorN< CPlotSpecification >(\"PlotList\", CCopasiContainer::Root);\n\n if (mWithGUI)\n {\n pdelete(mpGUI);\n mpGUI = new SCopasiXMLGUI;\n }\n\n changed(false);\n\n return true;\n}\n\nbool CCopasiDataModel::importSBML(const std::string & fileName)\n{\n if (fileName.rfind(\".xml\") == fileName.length() - 4 ||\n fileName.rfind(\".XML\") == fileName.length() - 4)\n mSaveFileName = fileName.substr(0, fileName.length() - 4) + \".cps\";\n else\n mSaveFileName = fileName + \".cps\";\n\n SBMLImporter importer;\n CModel * pModel = importer.readSBML(fileName, mpFunctionList);\n\n if (pModel == NULL) return false;\n\n return newModel(pModel);\n}\n\nbool CCopasiDataModel::exportSBML(const std::string & fileName, bool overwriteFile)\n{\n if (fileName == \"\") return false;\n\n SBMLExporter exporter;\n\n return exporter.exportSBML(mpModel, fileName.c_str(), overwriteFile);\n}\n\nCModel * CCopasiDataModel::getModel()\n{return mpModel;}\n\nCCopasiVectorN< CCopasiTask > * CCopasiDataModel::getTaskList()\n{return mpTaskList;}\n\n\/\/ static\nCCopasiTask * CCopasiDataModel::addTask(const CCopasiTask::Type & taskType)\n{\n CCopasiTask * pTask = NULL;\n\n switch (taskType)\n {\n case CCopasiTask::steadyState:\n pTask = new CSteadyStateTask(mpTaskList);\n break;\n\n case CCopasiTask::timeCourse:\n pTask = new CTrajectoryTask(mpTaskList);\n break;\n\n case CCopasiTask::scan:\n pTask = new CScanTask(mpTaskList);\n break;\n\n case CCopasiTask::fluxMode:\n \/\/ :TODO: implement task for elementary flux mode analysis\n return pTask;\n break;\n\n case CCopasiTask::optimization:\n \/\/ :TODO: implement task for optimization\n return pTask;\n break;\n\n case CCopasiTask::parameterFitting:\n \/\/ :TODO: implement task for parameter fitting\n return pTask;\n break;\n\n case CCopasiTask::mca:\n pTask = new CMCATask(mpTaskList);\n \/\/ :TODO: This must be avoided.\n static_cast<CMCAMethod *>(pTask->getMethod())->setModel(mpModel);\n break;\n\n default:\n return pTask;\n }\n\n pTask->getProblem()->setModel(mpModel);\n mpTaskList->add(pTask);\n\n return pTask;\n}\n\nbool CCopasiDataModel::addDefaultTasks()\n{\n if (mpTaskList->getIndex(\"Steady-State\") == C_INVALID_INDEX)\n addTask(CCopasiTask::steadyState);\n\n if (mpTaskList->getIndex(\"Time-Course\") == C_INVALID_INDEX)\n addTask(CCopasiTask::timeCourse);\n\n if (mpTaskList->getIndex(\"Scan\") == C_INVALID_INDEX)\n addTask(CCopasiTask::scan);\n\n if (mpTaskList->getIndex(\"Elementary Flux Modes\") == C_INVALID_INDEX)\n addTask(CCopasiTask::fluxMode);\n\n if (mpTaskList->getIndex(\"Optimization\") == C_INVALID_INDEX)\n addTask(CCopasiTask::optimization);\n\n if (mpTaskList->getIndex(\"Parameter Fitting\") == C_INVALID_INDEX)\n addTask(CCopasiTask::parameterFitting);\n\n if (mpTaskList->getIndex(\"Metabolic Control Analysis\") == C_INVALID_INDEX)\n addTask(CCopasiTask::mca);\n\n return true;\n}\n\nCReportDefinitionVector * CCopasiDataModel::getReportDefinitionList()\n{return mpReportDefinitionList;}\n\nCCopasiVectorN<CPlotSpecification> * CCopasiDataModel::getPlotDefinitionList()\n{return mpPlotDefinitionList;}\n\nCFunctionDB * CCopasiDataModel::getFunctionList()\n{return mpFunctionList;}\n\nSCopasiXMLGUI * CCopasiDataModel::getGUI()\n{return mpGUI;}\n\nCVersion * CCopasiDataModel::getVersion()\n{return mpVersion;}\n\nbool CCopasiDataModel::isChanged() const\n {return mChanged;}\n\nvoid CCopasiDataModel::changed(const bool & changed)\n{\n mChanged = changed;\n mAutoSaveNeeded = changed;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Workspace.h\"\r\n#include <algorithm>\r\n#include <QtCore\/QMetaType>\r\n#include \"Logger.h\"\r\n#include \"Scripter.h\"\r\n#include \"pjobrunnerpool.h\"\r\n#include \"PJobRunnerSessionThread.h\"\r\n\r\nWorkspace::Workspace(void)\r\n: m_pjob_file(0), m_running(false)\r\n{\r\n\tqRegisterMetaType< QHash<QString,double> >(\"QHash<QString,double>\");\r\n\tqRegisterMetaType<QHash< QHash<QString,double>, QHash<QString,double> > >(\"QHash< QHash<QString,double>, QHash<QString,double> >\");\r\n connect(this, SIGNAL(jobAdded(Job*,unsigned int)), &Logger::getInstance(), SLOT(jobAdded(Job*,unsigned int)));\r\n connect(this, SIGNAL(jobRemoved(Job*)), &Logger::getInstance(), SLOT(jobRemoved(Job*)));\r\n connect(this, SIGNAL(jobMoved(Job*,unsigned int)), &Logger::getInstance(), SLOT(jobMoved(Job*,unsigned int)));\r\n\tconnect(this, SIGNAL(started()), &Logger::getInstance(), SLOT(started()));\r\n\tconnect(this, SIGNAL(stopped()), &Logger::getInstance(), SLOT(stopped()));\r\n\tconnect(&m_results, SIGNAL(newValueSet(QString , QString , QHash<QString,double> , double )),\r\n\t\t&Logger::getInstance(), SLOT(newValueSet(QString , QString , QHash<QString,double> , double )));\r\n\tScripter::getInstance();\r\n}\r\n\r\nWorkspace::~Workspace(void)\r\n{\r\n}\r\n\r\nWorkspace& Workspace::getInstace(void)\r\n{\r\n static Workspace p;\r\n\treturn p;\r\n}\r\n\r\nResults& Workspace::getResults(){\r\n\treturn m_results;\r\n}\r\n\r\nvoid Workspace::setPJobFile(PJobFile* p){\r\n m_pjob_file = p;\r\n emit pjobFileChanged(p);\r\n}\r\n\r\nPJobFile* Workspace::getPJobFile(){\r\n return m_pjob_file;\r\n}\r\n\r\nvoid Workspace::addJob(Job* j){\r\n\tm_jobsQueued.push_back(j);\r\n connect(j, SIGNAL(stateChanged(Job*, Job::State)), this, SLOT(jobStateChanged(Job*, Job::State)));\r\n connect(j, SIGNAL(stateChanged(Job*, Job::State)), &Logger::getInstance(), SLOT(jobStateChanged(Job*, Job::State)));\r\n\tconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&m_results, SLOT(newValues(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n\tconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&Logger::getInstance(), SLOT(jobResults(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n connect(j, SIGNAL(problemReadingResults(Job*,QString)), &Logger::getInstance(), SLOT(jobHasProblemsReadingResult(Job*,QString)));\r\n\temit jobAdded(j, m_jobsQueued.indexOf(j));\r\n}\r\n\r\nvoid Workspace::removeJob(Job* j){\r\n\tm_jobsSubmited.removeOne(j);\r\n\tm_jobsRunning.removeOne(j);\r\n\tm_jobsFinished.removeOne(j);\r\n\tm_jobsQueued.removeOne(j);\r\n disconnect(j, SIGNAL(stateChanged(Job*, Job::State)), this, SLOT(jobStateChanged(Job*, Job::State)));\r\n disconnect(j, SIGNAL(stateChanged(Job*, Job::State)), &Logger::getInstance(), SLOT(jobStateChanged(Job*, Job::State)));\r\n\tdisconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&m_results, SLOT(newValues(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n\tdisconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&Logger::getInstance(), SLOT(jobResults(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n\temit jobRemoved(j);\r\n}\r\n\r\nvoid Workspace::setQueuePosition(Job* j, unsigned int position){\r\n if(static_cast<int>(position) >= m_jobsQueued.size()) position = m_jobsQueued.size()-1;\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsQueued.insert(position,j);\r\n\temit jobMoved(j,position);\r\n}\r\n\r\nvoid Workspace::start(){\r\n populate_session_threads();\r\n foreach(PJobRunnerSessionThread* thread, m_session_threads){\r\n thread->start();\r\n }\r\n\r\n m_running = true;\r\n emit started();\r\n}\r\n\r\nvoid Workspace::stop(){\r\n\tm_running = false;\r\n\temit stopped();\r\n}\r\n\r\n\r\nvoid Workspace::jobStateChanged(Job* job, Job::State state){\r\n\tswitch(state){\r\n case Job::FINISHED:\r\n\t\t\tjobFinished(job);\r\n\t\t\tbreak;\r\n case Job::SUBMITED:\r\n\t\t\tjobSubmited(job);\r\n\t\t\tbreak;\r\n case Job::RUNNING:\r\n\t\t\tjobStarted(job);\r\n\t\t\tbreak;\r\n case Job::QUEUED:\r\n\t\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid Workspace::jobSubmited(Job* j){\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsSubmited.push_back(j);\r\n}\r\n\r\nvoid Workspace::jobStarted(Job* j){\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsSubmited.removeOne(j);\r\n\tm_jobsRunning.push_back(j);\r\n}\r\n\r\nvoid Workspace::jobFinished(Job* j){\r\n\tm_jobsRunning.removeOne(j);\r\n\tm_jobsFinished.push_back(j);\r\n}\r\n\r\n\r\nbool Workspace::isRunning(){\r\n\treturn m_running;\r\n}\r\n\r\nvoid Workspace::import_results_from_pjobfile(QString filename)\r\n{\r\n\tPJobFile file(filename);\r\n\tQStringList runList = file.runDirectoryEntries();\r\n\t\r\n\t\/\/run_DATUM - Strings herausfiltern\r\n\tint i = 0;\r\n\tforeach(QString s, runList)\r\n\t{\r\n\t\trunList.replace(i++,s.section('\/',0,1));\r\n\t}\r\n\r\n\t\/\/doppelte Einträge verwerfen (jeder run soll logischerweise nur einmal geladen werden)\r\n\trunList.removeDuplicates();\r\n\t\r\n\tunsigned int size = runList.size();\r\n\tQString message = QString(\"Importing results from %1...\").arg(filename);\r\n\tif(size > 10) emit progress(message,0);\r\n\ti = 0;\r\n\tforeach(QString s, runList)\r\n\t{\r\n\t\t\/\/Results auslesen...\r\n\t\tQHash< QHash<QString,double>, QHash<QString,double> > result;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tresult = file.getResultsForRun(s);\r\n\t\t}\r\n\t\tcatch(QString s)\r\n\t\t{\r\n\t\t\t\/\/Ursache z.B.: Dateien unvollständig => parametercombination.xml passt nicht zu den Ergebnissen)\r\n\t\t\t\/\/=> überspringen\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/...und weiterleiten\r\n\t\tm_results.newValues(result,file.pjobFile());\r\n\t\tif(size > 10) emit progress(message,i++*100\/size);\r\n\t\tif(m_progresses_to_abort.contains(message)){\r\n\t\t\tm_progresses_to_abort.remove(message);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(size > 10) emit progress(message,100);\r\n}\r\n\r\nvoid Workspace::abort_progress(const QString& what){\r\n\tm_progresses_to_abort.insert(what);\r\n}\r\n\r\nJob* Workspace::startNextQueuedJob(){\r\n QMutexLocker locker(&m_mutex);\r\n if(m_jobsQueued.isEmpty()) return 0;\r\n Job* job = m_jobsQueued.takeFirst();\r\n m_jobsRunning.push_back(job);\r\n return job;\r\n}\r\n\r\nvoid Workspace::session_finished(){\r\n if(!m_running) return;\r\n QObject* object = sender();\r\n PJobRunnerSessionThread* thread = dynamic_cast<PJobRunnerSessionThread*>(object);\r\n if(!thread) return;\r\n thread->start();\r\n}\r\n\r\nvoid Workspace::populate_session_threads(){\r\n clear_session_threads();\r\n unsigned int jobs = m_jobsQueued.size();\r\n foreach(QHostAddress host, PJobRunnerPool::instance().known_pjob_runners()){\r\n unsigned int thread_count = PJobRunnerPool::instance().thread_count(host);\r\n for(unsigned int i=0; i<thread_count; i++){\r\n PJobRunnerSessionThread* thread = new PJobRunnerSessionThread(host, this);\r\n connect(thread, SIGNAL(finished()), this, SLOT(session_finished()), Qt::QueuedConnection);\r\n m_session_threads.insert(thread);\r\n jobs--;\r\n if(jobs <= 0) return;\r\n }\r\n }\r\n}\r\n\r\nvoid Workspace::clear_session_threads(){\r\n foreach(PJobRunnerSessionThread* thread, m_session_threads){\r\n if(thread->isRunning()) continue;\r\n m_session_threads.remove(thread);\r\n delete thread;\r\n }\r\n}\r\n<commit_msg>PQueue: Workspace: fixed Job::State signal\/slot connections.<commit_after>#include \"Workspace.h\"\r\n#include <algorithm>\r\n#include <QtCore\/QMetaType>\r\n#include \"Logger.h\"\r\n#include \"Scripter.h\"\r\n#include \"pjobrunnerpool.h\"\r\n#include \"PJobRunnerSessionThread.h\"\r\n\r\nWorkspace::Workspace(void)\r\n: m_pjob_file(0), m_running(false)\r\n{\r\n\tqRegisterMetaType< QHash<QString,double> >(\"QHash<QString,double>\");\r\n\tqRegisterMetaType<QHash< QHash<QString,double>, QHash<QString,double> > >(\"QHash< QHash<QString,double>, QHash<QString,double> >\");\r\n connect(this, SIGNAL(jobAdded(Job*,unsigned int)), &Logger::getInstance(), SLOT(jobAdded(Job*,unsigned int)));\r\n connect(this, SIGNAL(jobRemoved(Job*)), &Logger::getInstance(), SLOT(jobRemoved(Job*)));\r\n connect(this, SIGNAL(jobMoved(Job*,unsigned int)), &Logger::getInstance(), SLOT(jobMoved(Job*,unsigned int)));\r\n\tconnect(this, SIGNAL(started()), &Logger::getInstance(), SLOT(started()));\r\n\tconnect(this, SIGNAL(stopped()), &Logger::getInstance(), SLOT(stopped()));\r\n\tconnect(&m_results, SIGNAL(newValueSet(QString , QString , QHash<QString,double> , double )),\r\n\t\t&Logger::getInstance(), SLOT(newValueSet(QString , QString , QHash<QString,double> , double )));\r\n\tScripter::getInstance();\r\n qRegisterMetaType<Job::State>(\"Job::State\");\r\n}\r\n\r\nWorkspace::~Workspace(void)\r\n{\r\n}\r\n\r\nWorkspace& Workspace::getInstace(void)\r\n{\r\n static Workspace p;\r\n\treturn p;\r\n}\r\n\r\nResults& Workspace::getResults(){\r\n\treturn m_results;\r\n}\r\n\r\nvoid Workspace::setPJobFile(PJobFile* p){\r\n m_pjob_file = p;\r\n emit pjobFileChanged(p);\r\n}\r\n\r\nPJobFile* Workspace::getPJobFile(){\r\n return m_pjob_file;\r\n}\r\n\r\nvoid Workspace::addJob(Job* j){\r\n\tm_jobsQueued.push_back(j);\r\n connect(j, SIGNAL(stateChanged(Job*, Job::State)), this, SLOT(jobStateChanged(Job*, Job::State)), Qt::QueuedConnection);\r\n connect(j, SIGNAL(stateChanged(Job*, Job::State)), &Logger::getInstance(), SLOT(jobStateChanged(Job*, Job::State)), Qt::QueuedConnection);\r\n\tconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n &m_results, SLOT(newValues(QHash< QHash<QString,double>, QHash<QString,double> > , QString )), Qt::QueuedConnection);\r\n\tconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n &Logger::getInstance(), SLOT(jobResults(QHash< QHash<QString,double>, QHash<QString,double> > , QString )), Qt::QueuedConnection);\r\n connect(j, SIGNAL(problemReadingResults(Job*,QString)), &Logger::getInstance(), SLOT(jobHasProblemsReadingResult(Job*,QString)), Qt::QueuedConnection);\r\n\temit jobAdded(j, m_jobsQueued.indexOf(j));\r\n}\r\n\r\nvoid Workspace::removeJob(Job* j){\r\n\tm_jobsSubmited.removeOne(j);\r\n\tm_jobsRunning.removeOne(j);\r\n\tm_jobsFinished.removeOne(j);\r\n\tm_jobsQueued.removeOne(j);\r\n disconnect(j, SIGNAL(stateChanged(Job*, Job::State)), this, SLOT(jobStateChanged(Job*, Job::State)));\r\n disconnect(j, SIGNAL(stateChanged(Job*, Job::State)), &Logger::getInstance(), SLOT(jobStateChanged(Job*, Job::State)));\r\n\tdisconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&m_results, SLOT(newValues(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n\tdisconnect(j, SIGNAL(results(QHash< QHash<QString,double>, QHash<QString,double> > , QString )),\r\n\t\t&Logger::getInstance(), SLOT(jobResults(QHash< QHash<QString,double>, QHash<QString,double> > , QString )));\r\n\temit jobRemoved(j);\r\n}\r\n\r\nvoid Workspace::setQueuePosition(Job* j, unsigned int position){\r\n if(static_cast<int>(position) >= m_jobsQueued.size()) position = m_jobsQueued.size()-1;\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsQueued.insert(position,j);\r\n\temit jobMoved(j,position);\r\n}\r\n\r\nvoid Workspace::start(){\r\n populate_session_threads();\r\n foreach(PJobRunnerSessionThread* thread, m_session_threads){\r\n thread->start();\r\n }\r\n\r\n m_running = true;\r\n emit started();\r\n}\r\n\r\nvoid Workspace::stop(){\r\n\tm_running = false;\r\n\temit stopped();\r\n}\r\n\r\n\r\nvoid Workspace::jobStateChanged(Job* job, Job::State state){\r\n\tswitch(state){\r\n case Job::FINISHED:\r\n\t\t\tjobFinished(job);\r\n\t\t\tbreak;\r\n case Job::SUBMITED:\r\n\t\t\tjobSubmited(job);\r\n\t\t\tbreak;\r\n case Job::RUNNING:\r\n\t\t\tjobStarted(job);\r\n\t\t\tbreak;\r\n case Job::QUEUED:\r\n\t\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid Workspace::jobSubmited(Job* j){\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsSubmited.push_back(j);\r\n}\r\n\r\nvoid Workspace::jobStarted(Job* j){\r\n\tm_jobsQueued.removeOne(j);\r\n\tm_jobsSubmited.removeOne(j);\r\n\tm_jobsRunning.push_back(j);\r\n}\r\n\r\nvoid Workspace::jobFinished(Job* j){\r\n\tm_jobsRunning.removeOne(j);\r\n\tm_jobsFinished.push_back(j);\r\n}\r\n\r\n\r\nbool Workspace::isRunning(){\r\n\treturn m_running;\r\n}\r\n\r\nvoid Workspace::import_results_from_pjobfile(QString filename)\r\n{\r\n\tPJobFile file(filename);\r\n\tQStringList runList = file.runDirectoryEntries();\r\n\t\r\n\t\/\/run_DATUM - Strings herausfiltern\r\n\tint i = 0;\r\n\tforeach(QString s, runList)\r\n\t{\r\n\t\trunList.replace(i++,s.section('\/',0,1));\r\n\t}\r\n\r\n\t\/\/doppelte Einträge verwerfen (jeder run soll logischerweise nur einmal geladen werden)\r\n\trunList.removeDuplicates();\r\n\t\r\n\tunsigned int size = runList.size();\r\n\tQString message = QString(\"Importing results from %1...\").arg(filename);\r\n\tif(size > 10) emit progress(message,0);\r\n\ti = 0;\r\n\tforeach(QString s, runList)\r\n\t{\r\n\t\t\/\/Results auslesen...\r\n\t\tQHash< QHash<QString,double>, QHash<QString,double> > result;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tresult = file.getResultsForRun(s);\r\n\t\t}\r\n\t\tcatch(QString s)\r\n\t\t{\r\n\t\t\t\/\/Ursache z.B.: Dateien unvollständig => parametercombination.xml passt nicht zu den Ergebnissen)\r\n\t\t\t\/\/=> überspringen\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t\/\/...und weiterleiten\r\n\t\tm_results.newValues(result,file.pjobFile());\r\n\t\tif(size > 10) emit progress(message,i++*100\/size);\r\n\t\tif(m_progresses_to_abort.contains(message)){\r\n\t\t\tm_progresses_to_abort.remove(message);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(size > 10) emit progress(message,100);\r\n}\r\n\r\nvoid Workspace::abort_progress(const QString& what){\r\n\tm_progresses_to_abort.insert(what);\r\n}\r\n\r\nJob* Workspace::startNextQueuedJob(){\r\n QMutexLocker locker(&m_mutex);\r\n if(m_jobsQueued.isEmpty()) return 0;\r\n Job* job = m_jobsQueued.takeFirst();\r\n m_jobsRunning.push_back(job);\r\n return job;\r\n}\r\n\r\nvoid Workspace::session_finished(){\r\n if(!m_running) return;\r\n QObject* object = sender();\r\n PJobRunnerSessionThread* thread = dynamic_cast<PJobRunnerSessionThread*>(object);\r\n if(!thread) return;\r\n thread->start();\r\n}\r\n\r\nvoid Workspace::populate_session_threads(){\r\n clear_session_threads();\r\n unsigned int jobs = m_jobsQueued.size();\r\n foreach(QHostAddress host, PJobRunnerPool::instance().known_pjob_runners()){\r\n unsigned int thread_count = PJobRunnerPool::instance().thread_count(host);\r\n for(unsigned int i=0; i<thread_count; i++){\r\n PJobRunnerSessionThread* thread = new PJobRunnerSessionThread(host, this);\r\n connect(thread, SIGNAL(finished()), this, SLOT(session_finished()), Qt::QueuedConnection);\r\n m_session_threads.insert(thread);\r\n jobs--;\r\n if(jobs <= 0) return;\r\n }\r\n }\r\n}\r\n\r\nvoid Workspace::clear_session_threads(){\r\n foreach(PJobRunnerSessionThread* thread, m_session_threads){\r\n if(thread->isRunning()) continue;\r\n m_session_threads.remove(thread);\r\n delete thread;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"EmbeddedPython.h\"\n#include \"ModsLocation.h\"\n#include \"ExceptionFetcher.h\"\n#include \"ResourceLoader.h\"\n#include <iostream>\n#include \"Logger.h\"\n#include \"ResponseWriter.h\"\n#include \"SQFReader.h\"\n#include \"SQFWriter.h\"\n#include \"Paths.h\"\n#include \"Modules\/pythiainternal.h\"\n#include \"Modules\/pythialogger.h\"\n\n#ifndef _WIN32\n#include <dlfcn.h>\n#endif\n\n#define THROW_PYEXCEPTION(_msg_) throw std::runtime_error(_msg_ + std::string(\": \") + PyExceptionFetcher().getError());\n\/\/#define EXTENSION_DEVELOPMENT 1\n\nEmbeddedPython *python = nullptr;\nstd::string pythonInitializationError = \"\";\nunsigned long multipartCounter = 0;\nstd::unordered_map<unsigned long long int, multipart_t> multiparts;\n\nnamespace\n{\n class PyObjectGuard final\n {\n public:\n PyObjectGuard(PyObject* source) : ptr(source)\n {\n }\n\n ~PyObjectGuard()\n {\n if (ptr != nullptr)\n {\n Py_DECREF(ptr);\n }\n }\n\n PyObject* get() const\n {\n return ptr;\n }\n\n explicit operator bool() const\n {\n return ptr != nullptr;\n }\n\n \/\/\/ Release ownership\n PyObject* transfer()\n {\n PyObject* tmp = ptr;\n ptr = nullptr;\n return tmp;\n }\n\n private:\n PyObjectGuard(const PyObjectGuard&) = delete;\n void operator=(const PyObjectGuard&) = delete;\n\n private:\n PyObject *ptr;\n };\n}\n\nstd::wstring joinPaths(std::vector<std::wstring> const paths)\n{\n std::wstring out;\n bool firstTime = true;\n for(const auto& path : paths)\n {\n if(firstTime)\n {\n firstTime = false;\n out += path;\n }\n else\n {\n#ifdef _WIN32\n out += L\";\";\n#else\n out += L\":\";\n#endif\n out += path;\n }\n }\n return out;\n}\n\nvoid EmbeddedPython::DoPythonMagic(tstring path)\n{\n \/\/ Python pre-initialization magic\n LOG_INFO(std::string(\"Python version: \") + Py_GetVersion());\n\n \/\/ Clear the env variables, just in case\n #ifdef _WIN32\n _putenv_s(\"PYTHONHOME\", \"\");\n _putenv_s(\"PYTHONPATH\", \"\");\n _putenv_s(\"PYTHONNOUSERSITE\", \"1\"); \/\/ Disable custom user site\n std::wstring wpath = path;\n #else\n setenv(\"PYTHONHOME\", \"\", true);\n setenv(\"PYTHONPATH\", \"\", true);\n setenv(\"PYTHONNOUSERSITE\", \"1\", true); \/\/ Disable custom user site\n\n std::wstring wpath = Logger::s2w(path);\n #endif\n\n Py_IgnoreEnvironmentFlag = 1;\n Py_IsolatedFlag = 1;\n Py_NoSiteFlag = 1;\n Py_NoUserSiteDirectory = 1;\n\n \/\/ Py_SetPythonHome(L\"D:\\\\Steam\\\\steamapps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\");\n this->pythonHomeString = wpath;\n Py_SetPythonHome(pythonHomeString.data());\n LOG_INFO(std::string(\"Python home: \") + Logger::w2s(Py_GetPythonHome()));\n\n \/\/ Py_SetProgramName(L\"D:\\\\Steam\\\\steamapps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\python.exe\");\n#ifdef _WIN32\n this->programNameString = wpath + L\"\\\\python.exe\"; \/\/ Not sure if that should be the value here\n#else\n this->programNameString = wpath + L\"\/bin\/python\"; \/\/ Not sure if that should be the value here\n#endif\n Py_SetProgramName(programNameString.data());\n LOG_INFO(std::string(\"Program name: \") + Logger::w2s(Py_GetProgramName()));\n\n \/*\n Py_SetPath(L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\python35.zip;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\DLLs;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\lib;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\Lib\\\\site-packages;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\");\n *\/\n\n \/*\n # Obtain the current paths by running the embedded python binary\n import sys\n base_dir = sys.executable.split('\/bin\/')[0]\n for path in sys.path:\n print(path.replace(base_dir, ''))\n *\/\n\n #ifdef _WIN32\n std::wstring allPaths = joinPaths({\n wpath + L\"\\\\python\" PYTHON_VERSION + L\".zip\",\n wpath + L\"\\\\DLLs\",\n wpath + L\"\\\\lib\",\n wpath,\n wpath + L\"\\\\Lib\\\\site-packages\",\n getProgramDirectory() \/\/ For `python\/` directory access. TODO: Use import hooks for that\n });\n #else\n std::wstring allPaths = joinPaths({\n wpath + L\"\/lib\/python\" PYTHON_VERSION + L\".zip\",\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED,\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED L\"\/lib-dynload\",\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED L\"\/site-packages\",\n wpath,\n Logger::s2w(getProgramDirectory()) \/\/ For `python\/` directory access. TODO: Use import hooks for that\n });\n #endif\n\n \/\/ Not setting PySetPath overwrites the Py_SetProgramName value (it seems to be ignored then),\n Py_SetPath(allPaths.c_str());;\n LOG_INFO(std::string(\"Python paths: \") + Logger::w2s(Py_GetPath()));\n LOG_INFO(std::string(\"Current directory: \") + GetCurrentWorkingDir());\n\n #ifndef _WIN32\n \/\/ https:\/\/stackoverflow.com\/a\/60746446\/6543759\n \/\/ https:\/\/docs.python.org\/3\/whatsnew\/3.8.html#changes-in-the-c-api\n \/\/ undefined symbol: PyExc_ImportError\n \/\/ Manually load libpythonX.Y.so with dlopen(RTLD_GLOBAL) to allow numpy to access python symbols\n \/\/ and in Python 3.8+ any C extension\n \/\/ FIXME: Technically speaking, this is a leak\n void* const libpython_handle = dlopen(\"libpython\" PYTHON_VERSION_DOTTED \"m.so\", RTLD_LAZY | RTLD_GLOBAL);\n if(!libpython_handle)\n {\n LOG_INFO(\"Could not load libpython3.7m.so\");\n }\n #endif \/\/ ifndef _WIN32\n}\n\nEmbeddedPython::EmbeddedPython()\n{\n DoPythonMagic(getPythonPath());\n PyImport_AppendInittab(\"pythiainternal\", PyInit_pythiainternal);\n PyImport_AppendInittab(\"pythialogger\", PyInit_pythialogger);\n Py_Initialize();\n PyEval_InitThreads(); \/\/ Initialize and acquire GIL\n initialize();\n leavePythonThread();\n}\n\nvoid EmbeddedPython::enterPythonThread()\n{\n PyEval_RestoreThread(pThreadState);\n}\n\nvoid EmbeddedPython::leavePythonThread()\n{\n pThreadState = PyEval_SaveThread();\n}\n\nvoid EmbeddedPython::initialize()\n{\n #ifdef EXTENSION_DEVELOPMENT\n PyObjectGuard mainModuleName(PyUnicode_DecodeFSDefault(\"python.Adapter\"));\n if (!mainModuleName)\n {\n THROW_PYEXCEPTION(\"Failed to create unicode module name\");\n }\n\n PyObjectGuard moduleOriginal(PyImport_Import(mainModuleName.get()));\n if (!moduleOriginal)\n {\n THROW_PYEXCEPTION(\"Failed to import adapter module\");\n }\n\n \/\/ Reload the module to force re-reading the file\n PyObjectGuard module(PyImport_ReloadModule(moduleOriginal.get()));\n if (!module)\n {\n THROW_PYEXCEPTION(\"Failed to reload adapter module\");\n }\n\n #else\n\n const std::string text_resource = ResourceLoader::loadTextResource();\n PyObject *compiledString = Py_CompileString(\n text_resource.c_str(),\n \"python-adapter.py\",\n Py_file_input);\n\n PyObjectGuard pCompiledContents(compiledString);\n if (!pCompiledContents)\n {\n THROW_PYEXCEPTION(\"Failed to compile embedded python module\");\n }\n\n PyObjectGuard module(PyImport_ExecCodeModule(\"adapter\", pCompiledContents.get()));\n if (!module)\n {\n THROW_PYEXCEPTION(\"Failed to add compiled module\");\n }\n #endif\n\n PyObjectGuard function(PyObject_GetAttrString(module.get(), \"python_adapter\"));\n if (!function || !PyCallable_Check(function.get()))\n {\n THROW_PYEXCEPTION(\"Failed to reference python function 'python_adapter'\");\n }\n\n pModule = module.transfer();\n pFunc = function.transfer();\n}\n\nvoid EmbeddedPython::initModules(modules_t mods)\n{\n \/**\n Initialize python sources for modules.\n The sources passed here will be used to import `pythia.modulename`.\n *\/\n\n if (!pModule)\n {\n THROW_PYEXCEPTION(\"Pythia adapter not loaded correctly. Not initializing python modules.\")\n }\n\n PyObjectGuard pDict(PyDict_New());\n if (!pDict)\n {\n THROW_PYEXCEPTION(\"Could not create a new python dict.\")\n }\n\n \/\/ Fill the dict with the items in the unordered_map\n for (const auto& entry: mods)\n {\n #ifdef _WIN32\n PyObjectGuard pString(PyUnicode_FromWideChar(entry.second.c_str(), -1));\n #else\n PyObjectGuard pString(PyUnicode_FromString(entry.second.c_str()));\n #endif\n if (!pString)\n {\n continue;\n }\n\n int retval = PyDict_SetItemString(pDict.get(), entry.first.c_str(), pString.get());\n if (retval == -1)\n {\n THROW_PYEXCEPTION(\"Error while running PyDict_SetItemString.\")\n }\n }\n\n \/\/ Perform the call adding the mods sources\n PyObjectGuard function(PyObject_GetAttrString(pModule, \"init_modules\"));\n if (!function || !PyCallable_Check(function.get()))\n {\n THROW_PYEXCEPTION(\"Failed to reference python function 'init_modules'\");\n }\n\n PyObjectGuard pResult(PyObject_CallFunctionObjArgs(function.get(), pDict.get(), NULL));\n if (pResult)\n {\n return; \/\/ Yay!\n }\n else\n {\n THROW_PYEXCEPTION(\"Failed to execute python init_modules function\");\n }\n}\n\nvoid EmbeddedPython::deinitialize()\n{\n Py_CLEAR(pFunc);\n Py_CLEAR(pModule);\n}\n\nvoid EmbeddedPython::reload()\n{\n deinitialize();\n try\n {\n initialize();\n LOG_INFO(\"Python extension successfully reloaded\");\n }\n catch (const std::exception& ex)\n {\n LOG_ERROR(std::string(\"Caught error when reloading the extension: \") + ex.what());\n pythonInitializationError = ex.what();\n }\n}\n\nEmbeddedPython::~EmbeddedPython()\n{\n enterPythonThread();\n deinitialize();\n Py_Finalize();\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\nvoid handleMultipart(char *output, int outputSize, multipart_t entry)\n{\n if (entry.empty())\n {\n return;\n }\n\n multiparts[multipartCounter] = entry;\n\n \/\/[\"m\", MULTIPART_COUNTER, len(responses)]\n snprintf(output, outputSize - 1, \"[\\\"m\\\",%lu,%lu]\", multipartCounter++, (unsigned long)entry.size());\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\nvoid returnMultipart(unsigned long multipartID, char *output, int outputSize)\n{\n try\n {\n auto &entry = multiparts.at(multipartID);\n auto &retval = entry.front();\n\n size_t minSize = std::min<size_t>((size_t)outputSize, retval.size() + 1);\n snprintf(output, minSize, \"%s\", retval.data());\n\n entry.pop();\n if (entry.empty())\n {\n multiparts.erase(multipartID);\n }\n }\n catch (std::out_of_range)\n {\n output[0] = '\\0';\n }\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\n\/\/ A value of 10240 means that you can have 10239 characters + '\\0' there\nvoid EmbeddedPython::execute(char *output, int outputSize, const char *input)\n{\n #ifdef EXTENSION_DEVELOPMENT\n reload();\n #endif\n\n auto timeStart = std::chrono::high_resolution_clock::now();\n if (!pFunc)\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"No bootstrapping function. Additional error: \" + pythonInitializationError);\n }\n\n PyObjectGuard pArgs(SQFReader::decode(input));\n auto timeDecodeEnded = std::chrono::high_resolution_clock::now();\n\n PyObjectGuard pTuple(PyTuple_Pack(1, pArgs.get()));\n if (!pTuple)\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Failed to convert argument string to tuple\");\n }\n\n PyObject* PyFunction = PyList_GetItem(pArgs.get(), 0); \/\/ Borrows reference\n if (PyFunction)\n {\n \/\/ Multipart\n \/\/ TODO: Do a Python string comparison\n if (PyUnicode_CompareWithASCIIString(PyFunction, \"pythia.multipart\") == 0)\n {\n PyObject* PyMultipartID = PyList_GetItem(pArgs.get(), 1); \/\/ Borrows reference\n if (PyMultipartID)\n {\n int overflow;\n long multipartID = PyLong_AsLongAndOverflow(PyMultipartID, &overflow);\n if (overflow == 0 && multipartID >= 0)\n {\n returnMultipart(multipartID, output, outputSize);\n \/\/ Do not log multipart requests for performance reasons\n return;\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Could not read the multipart ID\");\n }\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Could not get the multipart ID from the request\");\n }\n }\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Failed to get the function name from the request\");\n }\n\n auto timeAfterMultipartCheck = std::chrono::high_resolution_clock::now();\n\n PyObjectGuard pResult(PyObject_CallObject(pFunc, pTuple.get()));\n auto timeAfterCall = std::chrono::high_resolution_clock::now();\n if (pResult)\n {\n MultipartResponseWriter writer(output, outputSize);\n writer.initialize();\n SQFWriter::encode(pResult.get(), &writer);\n writer.finalize();\n\n auto multipartResponse = writer.getMultipart();\n handleMultipart(output, outputSize, multipartResponse);\n auto timeEnd = std::chrono::high_resolution_clock::now();\n LOG_INFO(\n \"Calling function {}(...). Total: {}us\", \/\/, Decoding: {}us, Call: {}us, Encoding: {}us, Multipart: {}us\",\n PyUnicode_AsUTF8(PyFunction),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeEnd - timeStart)).count()\/*,\n (std::chrono::duration_cast<std::chrono::microseconds>(timeDecodeEnded - timeStart)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeAfterCall - timeAfterMultipartCheck)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeEnd - timeAfterCall)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeAfterMultipartCheck - timeDecodeEnded)).count()*\/\n );\n return;\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n THROW_PYEXCEPTION(\"Failed to execute python extension\");\n }\n}\n<commit_msg>Using outputSize - 1 is not needed<commit_after>#include \"stdafx.h\"\n#include \"EmbeddedPython.h\"\n#include \"ModsLocation.h\"\n#include \"ExceptionFetcher.h\"\n#include \"ResourceLoader.h\"\n#include <iostream>\n#include \"Logger.h\"\n#include \"ResponseWriter.h\"\n#include \"SQFReader.h\"\n#include \"SQFWriter.h\"\n#include \"Paths.h\"\n#include \"Modules\/pythiainternal.h\"\n#include \"Modules\/pythialogger.h\"\n\n#ifndef _WIN32\n#include <dlfcn.h>\n#endif\n\n#define THROW_PYEXCEPTION(_msg_) throw std::runtime_error(_msg_ + std::string(\": \") + PyExceptionFetcher().getError());\n\/\/#define EXTENSION_DEVELOPMENT 1\n\nEmbeddedPython *python = nullptr;\nstd::string pythonInitializationError = \"\";\nunsigned long multipartCounter = 0;\nstd::unordered_map<unsigned long long int, multipart_t> multiparts;\n\nnamespace\n{\n class PyObjectGuard final\n {\n public:\n PyObjectGuard(PyObject* source) : ptr(source)\n {\n }\n\n ~PyObjectGuard()\n {\n if (ptr != nullptr)\n {\n Py_DECREF(ptr);\n }\n }\n\n PyObject* get() const\n {\n return ptr;\n }\n\n explicit operator bool() const\n {\n return ptr != nullptr;\n }\n\n \/\/\/ Release ownership\n PyObject* transfer()\n {\n PyObject* tmp = ptr;\n ptr = nullptr;\n return tmp;\n }\n\n private:\n PyObjectGuard(const PyObjectGuard&) = delete;\n void operator=(const PyObjectGuard&) = delete;\n\n private:\n PyObject *ptr;\n };\n}\n\nstd::wstring joinPaths(std::vector<std::wstring> const paths)\n{\n std::wstring out;\n bool firstTime = true;\n for(const auto& path : paths)\n {\n if(firstTime)\n {\n firstTime = false;\n out += path;\n }\n else\n {\n#ifdef _WIN32\n out += L\";\";\n#else\n out += L\":\";\n#endif\n out += path;\n }\n }\n return out;\n}\n\nvoid EmbeddedPython::DoPythonMagic(tstring path)\n{\n \/\/ Python pre-initialization magic\n LOG_INFO(std::string(\"Python version: \") + Py_GetVersion());\n\n \/\/ Clear the env variables, just in case\n #ifdef _WIN32\n _putenv_s(\"PYTHONHOME\", \"\");\n _putenv_s(\"PYTHONPATH\", \"\");\n _putenv_s(\"PYTHONNOUSERSITE\", \"1\"); \/\/ Disable custom user site\n std::wstring wpath = path;\n #else\n setenv(\"PYTHONHOME\", \"\", true);\n setenv(\"PYTHONPATH\", \"\", true);\n setenv(\"PYTHONNOUSERSITE\", \"1\", true); \/\/ Disable custom user site\n\n std::wstring wpath = Logger::s2w(path);\n #endif\n\n Py_IgnoreEnvironmentFlag = 1;\n Py_IsolatedFlag = 1;\n Py_NoSiteFlag = 1;\n Py_NoUserSiteDirectory = 1;\n\n \/\/ Py_SetPythonHome(L\"D:\\\\Steam\\\\steamapps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\");\n this->pythonHomeString = wpath;\n Py_SetPythonHome(pythonHomeString.data());\n LOG_INFO(std::string(\"Python home: \") + Logger::w2s(Py_GetPythonHome()));\n\n \/\/ Py_SetProgramName(L\"D:\\\\Steam\\\\steamapps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\python.exe\");\n#ifdef _WIN32\n this->programNameString = wpath + L\"\\\\python.exe\"; \/\/ Not sure if that should be the value here\n#else\n this->programNameString = wpath + L\"\/bin\/python\"; \/\/ Not sure if that should be the value here\n#endif\n Py_SetProgramName(programNameString.data());\n LOG_INFO(std::string(\"Program name: \") + Logger::w2s(Py_GetProgramName()));\n\n \/*\n Py_SetPath(L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\python35.zip;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\DLLs;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\lib;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\\\\@Pythia\\\\python-embed-amd64\\\\Lib\\\\site-packages;\"\n L\"D:\\\\Steam\\\\SteamApps\\\\common\\\\Arma 3\");\n *\/\n\n \/*\n # Obtain the current paths by running the embedded python binary\n import sys\n base_dir = sys.executable.split('\/bin\/')[0]\n for path in sys.path:\n print(path.replace(base_dir, ''))\n *\/\n\n #ifdef _WIN32\n std::wstring allPaths = joinPaths({\n wpath + L\"\\\\python\" PYTHON_VERSION + L\".zip\",\n wpath + L\"\\\\DLLs\",\n wpath + L\"\\\\lib\",\n wpath,\n wpath + L\"\\\\Lib\\\\site-packages\",\n getProgramDirectory() \/\/ For `python\/` directory access. TODO: Use import hooks for that\n });\n #else\n std::wstring allPaths = joinPaths({\n wpath + L\"\/lib\/python\" PYTHON_VERSION + L\".zip\",\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED,\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED L\"\/lib-dynload\",\n wpath + L\"\/lib\/python\" PYTHON_VERSION_DOTTED L\"\/site-packages\",\n wpath,\n Logger::s2w(getProgramDirectory()) \/\/ For `python\/` directory access. TODO: Use import hooks for that\n });\n #endif\n\n \/\/ Not setting PySetPath overwrites the Py_SetProgramName value (it seems to be ignored then),\n Py_SetPath(allPaths.c_str());;\n LOG_INFO(std::string(\"Python paths: \") + Logger::w2s(Py_GetPath()));\n LOG_INFO(std::string(\"Current directory: \") + GetCurrentWorkingDir());\n\n #ifndef _WIN32\n \/\/ https:\/\/stackoverflow.com\/a\/60746446\/6543759\n \/\/ https:\/\/docs.python.org\/3\/whatsnew\/3.8.html#changes-in-the-c-api\n \/\/ undefined symbol: PyExc_ImportError\n \/\/ Manually load libpythonX.Y.so with dlopen(RTLD_GLOBAL) to allow numpy to access python symbols\n \/\/ and in Python 3.8+ any C extension\n \/\/ FIXME: Technically speaking, this is a leak\n void* const libpython_handle = dlopen(\"libpython\" PYTHON_VERSION_DOTTED \"m.so\", RTLD_LAZY | RTLD_GLOBAL);\n if(!libpython_handle)\n {\n LOG_INFO(\"Could not load libpython3.7m.so\");\n }\n #endif \/\/ ifndef _WIN32\n}\n\nEmbeddedPython::EmbeddedPython()\n{\n DoPythonMagic(getPythonPath());\n PyImport_AppendInittab(\"pythiainternal\", PyInit_pythiainternal);\n PyImport_AppendInittab(\"pythialogger\", PyInit_pythialogger);\n Py_Initialize();\n PyEval_InitThreads(); \/\/ Initialize and acquire GIL\n initialize();\n leavePythonThread();\n}\n\nvoid EmbeddedPython::enterPythonThread()\n{\n PyEval_RestoreThread(pThreadState);\n}\n\nvoid EmbeddedPython::leavePythonThread()\n{\n pThreadState = PyEval_SaveThread();\n}\n\nvoid EmbeddedPython::initialize()\n{\n #ifdef EXTENSION_DEVELOPMENT\n PyObjectGuard mainModuleName(PyUnicode_DecodeFSDefault(\"python.Adapter\"));\n if (!mainModuleName)\n {\n THROW_PYEXCEPTION(\"Failed to create unicode module name\");\n }\n\n PyObjectGuard moduleOriginal(PyImport_Import(mainModuleName.get()));\n if (!moduleOriginal)\n {\n THROW_PYEXCEPTION(\"Failed to import adapter module\");\n }\n\n \/\/ Reload the module to force re-reading the file\n PyObjectGuard module(PyImport_ReloadModule(moduleOriginal.get()));\n if (!module)\n {\n THROW_PYEXCEPTION(\"Failed to reload adapter module\");\n }\n\n #else\n\n const std::string text_resource = ResourceLoader::loadTextResource();\n PyObject *compiledString = Py_CompileString(\n text_resource.c_str(),\n \"python-adapter.py\",\n Py_file_input);\n\n PyObjectGuard pCompiledContents(compiledString);\n if (!pCompiledContents)\n {\n THROW_PYEXCEPTION(\"Failed to compile embedded python module\");\n }\n\n PyObjectGuard module(PyImport_ExecCodeModule(\"adapter\", pCompiledContents.get()));\n if (!module)\n {\n THROW_PYEXCEPTION(\"Failed to add compiled module\");\n }\n #endif\n\n PyObjectGuard function(PyObject_GetAttrString(module.get(), \"python_adapter\"));\n if (!function || !PyCallable_Check(function.get()))\n {\n THROW_PYEXCEPTION(\"Failed to reference python function 'python_adapter'\");\n }\n\n pModule = module.transfer();\n pFunc = function.transfer();\n}\n\nvoid EmbeddedPython::initModules(modules_t mods)\n{\n \/**\n Initialize python sources for modules.\n The sources passed here will be used to import `pythia.modulename`.\n *\/\n\n if (!pModule)\n {\n THROW_PYEXCEPTION(\"Pythia adapter not loaded correctly. Not initializing python modules.\")\n }\n\n PyObjectGuard pDict(PyDict_New());\n if (!pDict)\n {\n THROW_PYEXCEPTION(\"Could not create a new python dict.\")\n }\n\n \/\/ Fill the dict with the items in the unordered_map\n for (const auto& entry: mods)\n {\n #ifdef _WIN32\n PyObjectGuard pString(PyUnicode_FromWideChar(entry.second.c_str(), -1));\n #else\n PyObjectGuard pString(PyUnicode_FromString(entry.second.c_str()));\n #endif\n if (!pString)\n {\n continue;\n }\n\n int retval = PyDict_SetItemString(pDict.get(), entry.first.c_str(), pString.get());\n if (retval == -1)\n {\n THROW_PYEXCEPTION(\"Error while running PyDict_SetItemString.\")\n }\n }\n\n \/\/ Perform the call adding the mods sources\n PyObjectGuard function(PyObject_GetAttrString(pModule, \"init_modules\"));\n if (!function || !PyCallable_Check(function.get()))\n {\n THROW_PYEXCEPTION(\"Failed to reference python function 'init_modules'\");\n }\n\n PyObjectGuard pResult(PyObject_CallFunctionObjArgs(function.get(), pDict.get(), NULL));\n if (pResult)\n {\n return; \/\/ Yay!\n }\n else\n {\n THROW_PYEXCEPTION(\"Failed to execute python init_modules function\");\n }\n}\n\nvoid EmbeddedPython::deinitialize()\n{\n Py_CLEAR(pFunc);\n Py_CLEAR(pModule);\n}\n\nvoid EmbeddedPython::reload()\n{\n deinitialize();\n try\n {\n initialize();\n LOG_INFO(\"Python extension successfully reloaded\");\n }\n catch (const std::exception& ex)\n {\n LOG_ERROR(std::string(\"Caught error when reloading the extension: \") + ex.what());\n pythonInitializationError = ex.what();\n }\n}\n\nEmbeddedPython::~EmbeddedPython()\n{\n enterPythonThread();\n deinitialize();\n Py_Finalize();\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\nvoid handleMultipart(char *output, int outputSize, multipart_t entry)\n{\n if (entry.empty())\n {\n return;\n }\n\n multiparts[multipartCounter] = entry;\n\n \/\/[\"m\", MULTIPART_COUNTER, len(responses)]\n snprintf(output, outputSize, \"[\\\"m\\\",%lu,%lu]\", multipartCounter++, (unsigned long)entry.size());\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\nvoid returnMultipart(unsigned long multipartID, char *output, int outputSize)\n{\n try\n {\n auto &entry = multiparts.at(multipartID);\n auto &retval = entry.front();\n\n size_t minSize = std::min<size_t>((size_t)outputSize, retval.size() + 1);\n snprintf(output, minSize, \"%s\", retval.data());\n\n entry.pop();\n if (entry.empty())\n {\n multiparts.erase(multipartID);\n }\n }\n catch (std::out_of_range)\n {\n output[0] = '\\0';\n }\n}\n\n\/\/ Note: outputSize is the size CONTAINING the null terminator\n\/\/ A value of 10240 means that you can have 10239 characters + '\\0' there\nvoid EmbeddedPython::execute(char *output, int outputSize, const char *input)\n{\n #ifdef EXTENSION_DEVELOPMENT\n reload();\n #endif\n\n auto timeStart = std::chrono::high_resolution_clock::now();\n if (!pFunc)\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"No bootstrapping function. Additional error: \" + pythonInitializationError);\n }\n\n PyObjectGuard pArgs(SQFReader::decode(input));\n auto timeDecodeEnded = std::chrono::high_resolution_clock::now();\n\n PyObjectGuard pTuple(PyTuple_Pack(1, pArgs.get()));\n if (!pTuple)\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Failed to convert argument string to tuple\");\n }\n\n PyObject* PyFunction = PyList_GetItem(pArgs.get(), 0); \/\/ Borrows reference\n if (PyFunction)\n {\n \/\/ Multipart\n \/\/ TODO: Do a Python string comparison\n if (PyUnicode_CompareWithASCIIString(PyFunction, \"pythia.multipart\") == 0)\n {\n PyObject* PyMultipartID = PyList_GetItem(pArgs.get(), 1); \/\/ Borrows reference\n if (PyMultipartID)\n {\n int overflow;\n long multipartID = PyLong_AsLongAndOverflow(PyMultipartID, &overflow);\n if (overflow == 0 && multipartID >= 0)\n {\n returnMultipart(multipartID, output, outputSize);\n \/\/ Do not log multipart requests for performance reasons\n return;\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Could not read the multipart ID\");\n }\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Could not get the multipart ID from the request\");\n }\n }\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n throw std::runtime_error(\"Failed to get the function name from the request\");\n }\n\n auto timeAfterMultipartCheck = std::chrono::high_resolution_clock::now();\n\n PyObjectGuard pResult(PyObject_CallObject(pFunc, pTuple.get()));\n auto timeAfterCall = std::chrono::high_resolution_clock::now();\n if (pResult)\n {\n MultipartResponseWriter writer(output, outputSize);\n writer.initialize();\n SQFWriter::encode(pResult.get(), &writer);\n writer.finalize();\n\n auto multipartResponse = writer.getMultipart();\n handleMultipart(output, outputSize, multipartResponse);\n auto timeEnd = std::chrono::high_resolution_clock::now();\n LOG_INFO(\n \"Calling function {}(...). Total: {}us\", \/\/, Decoding: {}us, Call: {}us, Encoding: {}us, Multipart: {}us\",\n PyUnicode_AsUTF8(PyFunction),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeEnd - timeStart)).count()\/*,\n (std::chrono::duration_cast<std::chrono::microseconds>(timeDecodeEnded - timeStart)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeAfterCall - timeAfterMultipartCheck)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeEnd - timeAfterCall)).count(),\n (std::chrono::duration_cast<std::chrono::microseconds>(timeAfterMultipartCheck - timeDecodeEnded)).count()*\/\n );\n return;\n }\n else\n {\n LOG_ERROR(\"Calling function {}\", input);\n THROW_PYEXCEPTION(\"Failed to execute python extension\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n\n licence: see nui3\/LICENCE.TXT\n*\/\n\n\/\/ nuiGradient.cpp\n\n#include \"nui.h\"\n#include \"nuiColor.h\"\n#include \"nuiRect.h\"\n#include \"nuiGradient.h\"\n#include \"nuiDrawContext.h\"\n#include \"nuiContour.h\"\n\nnuiGradient::nuiGradient()\n{\n}\n\nnuiGradient::nuiGradient(const nuiGradient& rGradient)\n{\n mStops.assign(rGradient.GetStopList().begin(), rGradient.GetStopList().end());\n}\n\nnuiGradient::~nuiGradient()\n{\n}\n\nstatic bool PositionIsLesser(const nuiGradientPair& rElem1, const nuiGradientPair& rElem2)\n{\n return rElem1.first < rElem2.first;\n}\n\nvoid nuiGradient::AddStop(const nuiColor& rColor, nuiSize position)\n{\n mStops.push_back(nuiGradientPair(position, rColor));\n mStops.sort(PositionIsLesser);\n}\n\nconst nuiGradientStopList& nuiGradient::GetStopList() const\n{\n return mStops;\n}\n\nconst nuiColor nuiGradient::GetColorAt(nuiSize position) const\n{\n if (mStops.size() == 0)\n {\n return nuiColor(0.f, 0.f, 0.f);\n }\n \n nuiGradientStopList::const_iterator stopIt = mStops.begin();\n nuiGradientStopList::const_iterator stopEnd = mStops.end();\n if (position <= (*stopIt).first)\n {\n return (*stopIt).second;\n }\n \n bool found = false;\n nuiGradientPair leftStop;\n for (; stopIt != stopEnd && !found; ++stopIt)\n {\n if (position > (*stopIt).first)\n {\n found = true;\n leftStop = *stopIt;\n }\n }\n \n if (stopIt == stopEnd)\n {\n return leftStop.second;\n }\n else\n {\n nuiGradientPair rightStop = *stopIt;\n float ratio = (position - leftStop.first) \/ (rightStop.first - leftStop.first);\n float red = ((rightStop.second.Red() - leftStop.second.Red()) * ratio) + leftStop.second.Red();\n float green = ((rightStop.second.Green() - leftStop.second.Green()) * ratio) + leftStop.second.Green();\n float blue = ((rightStop.second.Blue() - leftStop.second.Blue()) * ratio) + leftStop.second.Blue();\n float alpha = ((rightStop.second.Alpha() - leftStop.second.Alpha()) * ratio) + leftStop.second.Alpha();\n return nuiColor(red, green, blue, alpha);\n }\n}\n\nnuiTexture* nuiGradient::CreateTexture(int32 size, nglImagePixelFormat format) const\n{\n \/\/ int32 bpp = 32;\n \/\/ switch (format)\n \/\/ {\n \/\/ case eImagePixelRGB:\n \/\/ {\n \/\/ bpp = 24;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelRGBA:\n \/\/ {\n \/\/ bpp = 32;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelAlpha:\n \/\/ case eImagePixelLum:\n \/\/ {\n \/\/ bpp = 8;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelLumA:\n \/\/ {\n \/\/ bpp = 16;\n \/\/ }\n \/\/ break;\n \/\/ }\n \n format = eImagePixelRGBA; \n nglImageInfo imageinfo(size, 1, 32);\n imageinfo.mPixelFormat = format;\n imageinfo.AllocateBuffer();\n \n uint32* pBuffer = (uint32*)imageinfo.mpBuffer;\n\n nuiGradientStopList::const_iterator it = mStops.begin();\n nuiGradientStopList::const_iterator end = mStops.end();\n \n if (it == end)\n memset(pBuffer, 0, size * 4);\n float pos0 = 0;\n nuiColor col0 = it->second;\n \n \n while (it != end)\n {\n float pos1 = it->first;\n nuiColor col1 = it->second;\n \n int32 ipos0 = ToBelow(pos0) * size;\n int32 ipos1 = ToBelow(pos1) * size;\n \n float r = 0;\n const float incr = 1.0f \/ (pos1 - pos0);\n for (int32 i = pos0; i < pos1; i++)\n {\n nuiColor col(col0);\n col.Mix(col1, r);\n *pBuffer = col.GetRGBA();\n pBuffer++;\n }\n \n pos0 = pos1;\n col0 = col1;\n \n ++it;\n }\n \n \/\/ go to the end of the line:\n float pos1 = size;\n \n int32 ipos0 = ToBelow(pos0) * size;\n int32 ipos1 = ToBelow(pos1) * size;\n \n float r = 0;\n const float incr = 1.0f \/ (pos1 - pos0);\n for (int32 i = pos0; i < pos1; i++)\n {\n *pBuffer = col0.GetRGBA();\n pBuffer++;\n }\n \n nglImage* pImage = new nglImage(imageinfo);\n nuiTexture* pTexture = nuiTexture::GetTexture(pImage, true);\n return pTexture;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnuiReflection::nuiReflection(float Intensity, float Center)\n{\n mColor = nuiColor(1.f,1.f,1.f, Intensity);\n mCenter = Center;\n mpSkyGradient = NULL;\n mpGroundGradient = NULL;\n mRecalc = true;\n}\n\nnuiReflection::~nuiReflection()\n{\n delete mpSkyGradient;\n delete mpGroundGradient;\n}\n\nvoid nuiReflection::Draw(nuiDrawContext* pContext, const nuiRect& rRect, nuiShape* pShp)\n{\n if (!(mRect == rRect))\n mRecalc = true;\n\n mRect = rRect;\n float x = mRect.Left();\n float y = mRect.Top();\n\n float h = mRect.GetHeight();\n if (mRecalc)\n Recalc();\n\n \/\/ Draw the sky:\n pContext->SetBlendFunc(nuiBlendTransp);\n pContext->DrawGradient(*mpSkyGradient, mRect, x, y, x, y+mCenter * h);\n\n\n \/\/ Draw the ground:\n pContext->SetBlendFunc(nuiBlendTransp);\n pContext->DrawGradient(*mpGroundGradient, mRect, x, y + mCenter * h, x, y + h);\n}\n\nvoid nuiReflection::Recalc()\n{\n float x = mRect.Left();\n float y = mRect.Top();\n float w = mRect.GetWidth();\n float h = mRect.GetHeight();\n float h_2 = h * mCenter;\n\n mRecalc = false;\n\n delete mpSkyGradient;\n delete mpGroundGradient;\n mpSkyGradient = new nuiGradient();\n mpGroundGradient = new nuiGradient();\n\n nuiColor tmp;\n \n \/\/ Sky:\n tmp = mColor;\n float alpha = mColor.Alpha();\n tmp.SetOpacity(alpha * .2f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, 0); \n\n mpSkyGradient->AddStop(nuiColor(1.f,1.f,1.f, alpha), 0.1f); \n\n tmp.SetOpacity(alpha * .6f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, .4f); \n\n tmp.SetOpacity(alpha * .4f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, 1); \n\n \/\/ Ground:\n mpGroundGradient = new nuiGradient();\n tmp.SetOpacity(alpha * .1f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, 0); \n\n tmp.SetOpacity(alpha * .4f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, .8f); \n\n tmp.SetOpacity(alpha *.6f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, 1); \n}\n\n<commit_msg>started to debug nuiGradient texture (from Seb Metrot)<commit_after>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n\n licence: see nui3\/LICENCE.TXT\n*\/\n\n\/\/ nuiGradient.cpp\n\n#include \"nui.h\"\n#include \"nuiColor.h\"\n#include \"nuiRect.h\"\n#include \"nuiGradient.h\"\n#include \"nuiDrawContext.h\"\n#include \"nuiContour.h\"\n\nnuiGradient::nuiGradient()\n{\n}\n\nnuiGradient::nuiGradient(const nuiGradient& rGradient)\n{\n mStops.assign(rGradient.GetStopList().begin(), rGradient.GetStopList().end());\n}\n\nnuiGradient::~nuiGradient()\n{\n}\n\nstatic bool PositionIsLesser(const nuiGradientPair& rElem1, const nuiGradientPair& rElem2)\n{\n return rElem1.first < rElem2.first;\n}\n\nvoid nuiGradient::AddStop(const nuiColor& rColor, nuiSize position)\n{\n mStops.push_back(nuiGradientPair(position, rColor));\n mStops.sort(PositionIsLesser);\n}\n\nconst nuiGradientStopList& nuiGradient::GetStopList() const\n{\n return mStops;\n}\n\nconst nuiColor nuiGradient::GetColorAt(nuiSize position) const\n{\n if (mStops.size() == 0)\n {\n return nuiColor(0.f, 0.f, 0.f);\n }\n \n nuiGradientStopList::const_iterator stopIt = mStops.begin();\n nuiGradientStopList::const_iterator stopEnd = mStops.end();\n if (position <= (*stopIt).first)\n {\n return (*stopIt).second;\n }\n \n bool found = false;\n nuiGradientPair leftStop;\n for (; stopIt != stopEnd && !found; ++stopIt)\n {\n if (position > (*stopIt).first)\n {\n found = true;\n leftStop = *stopIt;\n }\n }\n \n if (stopIt == stopEnd)\n {\n return leftStop.second;\n }\n else\n {\n nuiGradientPair rightStop = *stopIt;\n float ratio = (position - leftStop.first) \/ (rightStop.first - leftStop.first);\n float red = ((rightStop.second.Red() - leftStop.second.Red()) * ratio) + leftStop.second.Red();\n float green = ((rightStop.second.Green() - leftStop.second.Green()) * ratio) + leftStop.second.Green();\n float blue = ((rightStop.second.Blue() - leftStop.second.Blue()) * ratio) + leftStop.second.Blue();\n float alpha = ((rightStop.second.Alpha() - leftStop.second.Alpha()) * ratio) + leftStop.second.Alpha();\n return nuiColor(red, green, blue, alpha);\n }\n}\n\nnuiTexture* nuiGradient::CreateTexture(int32 size, nglImagePixelFormat format) const\n{\n \/\/ int32 bpp = 32;\n \/\/ switch (format)\n \/\/ {\n \/\/ case eImagePixelRGB:\n \/\/ {\n \/\/ bpp = 24;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelRGBA:\n \/\/ {\n \/\/ bpp = 32;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelAlpha:\n \/\/ case eImagePixelLum:\n \/\/ {\n \/\/ bpp = 8;\n \/\/ }\n \/\/ break;\n \/\/ case eImagePixelLumA:\n \/\/ {\n \/\/ bpp = 16;\n \/\/ }\n \/\/ break;\n \/\/ }\n \n format = eImagePixelRGBA; \n nglImageInfo imageinfo(size, 1, 32);\n imageinfo.mPixelFormat = format;\n imageinfo.AllocateBuffer();\n \n uint32* pBuffer = (uint32*)imageinfo.mpBuffer;\n\n nuiGradientStopList::const_iterator it = mStops.begin();\n nuiGradientStopList::const_iterator end = mStops.end();\n \n if (it == end)\n memset(pBuffer, 0, size * 4);\n float pos0 = 0;\n nuiColor col0 = it->second;\n \n \n while (it != end)\n {\n float pos1 = it->first;\n nuiColor col1 = it->second;\n \n int32 ipos0 = ToBelow(pos0 * size);\n int32 ipos1 = ToBelow(pos1 * size);\n \n float r = 0;\n const float incr = 1.0f \/ (pos1 - pos0);\n for (int32 i = pos0; i < pos1; i++)\n {\n nuiColor col(col0);\n col.Mix(col1, r);\n *pBuffer = col.GetRGBA();\n pBuffer++;\n }\n \n pos0 = pos1;\n col0 = col1;\n \n ++it;\n }\n \n \/\/ go to the end of the line:\n float pos1 = size;\n \n int32 ipos0 = ToBelow(pos0 * size);\n int32 ipos1 = ToBelow(pos1 * size);\n \n float r = 0;\n const float incr = 1.0f \/ (pos1 - pos0);\n for (int32 i = pos0; i < pos1; i++)\n {\n *pBuffer = col0.GetRGBA();\n pBuffer++;\n }\n \n nglImage* pImage = new nglImage(imageinfo);\n nuiTexture* pTexture = nuiTexture::GetTexture(pImage, true);\n return pTexture;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnuiReflection::nuiReflection(float Intensity, float Center)\n{\n mColor = nuiColor(1.f,1.f,1.f, Intensity);\n mCenter = Center;\n mpSkyGradient = NULL;\n mpGroundGradient = NULL;\n mRecalc = true;\n}\n\nnuiReflection::~nuiReflection()\n{\n delete mpSkyGradient;\n delete mpGroundGradient;\n}\n\nvoid nuiReflection::Draw(nuiDrawContext* pContext, const nuiRect& rRect, nuiShape* pShp)\n{\n if (!(mRect == rRect))\n mRecalc = true;\n\n mRect = rRect;\n float x = mRect.Left();\n float y = mRect.Top();\n\n float h = mRect.GetHeight();\n if (mRecalc)\n Recalc();\n\n \/\/ Draw the sky:\n pContext->SetBlendFunc(nuiBlendTransp);\n pContext->DrawGradient(*mpSkyGradient, mRect, x, y, x, y+mCenter * h);\n\n\n \/\/ Draw the ground:\n pContext->SetBlendFunc(nuiBlendTransp);\n pContext->DrawGradient(*mpGroundGradient, mRect, x, y + mCenter * h, x, y + h);\n}\n\nvoid nuiReflection::Recalc()\n{\n float x = mRect.Left();\n float y = mRect.Top();\n float w = mRect.GetWidth();\n float h = mRect.GetHeight();\n float h_2 = h * mCenter;\n\n mRecalc = false;\n\n delete mpSkyGradient;\n delete mpGroundGradient;\n mpSkyGradient = new nuiGradient();\n mpGroundGradient = new nuiGradient();\n\n nuiColor tmp;\n \n \/\/ Sky:\n tmp = mColor;\n float alpha = mColor.Alpha();\n tmp.SetOpacity(alpha * .2f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, 0); \n\n mpSkyGradient->AddStop(nuiColor(1.f,1.f,1.f, alpha), 0.1f); \n\n tmp.SetOpacity(alpha * .6f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, .4f); \n\n tmp.SetOpacity(alpha * .4f);\n tmp.Crop();\n mpSkyGradient->AddStop(tmp, 1); \n\n \/\/ Ground:\n mpGroundGradient = new nuiGradient();\n tmp.SetOpacity(alpha * .1f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, 0); \n\n tmp.SetOpacity(alpha * .4f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, .8f); \n\n tmp.SetOpacity(alpha *.6f);\n tmp.Crop();\n mpGroundGradient->AddStop(tmp, 1); \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*! \\brief serial_controller_node.\n * Manages serial communications with AVR-Master.\n *\n * This node manages serial communications with the AVR-Master.\n * Therefore it first requests all data from AVR-Master and then sends all\n * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,\n * commands to be send are read from md49_commands.txt.\n *\n *\/\n\n\/\/ Includes\n\/\/ *********************************************************\n#include <iostream> \/* allows to perform standard input and output operations *\/\n\/\/#include <fstream> \/* Input\/output stream class to operate on files. *\/\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n\/\/#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n\/\/#include <ctype.h> \/* isxxx() *\/\n\/\/#include<ros\/ros.h>\n#include <sqlite3.h>\n\n\n\/\/ Global variables\nconst char* serialport_name=\"\/\/dev\/ttyAMA0\"; \/* defines used serialport on BPi. Use \"\/dev\/ttyAMA0\" for RPi*\/\nint serialport_bps=B9600; \/* defines used baudrate on serialport *\/\n\/\/int filedesc; \/* File descriptor of serial port we will talk to*\/\nint fd; \/* serial port file descriptor *\/\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\nunsigned char last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\nunsigned char serialBuffer[16]; \/* Serial buffer to store uart data *\/\nstruct termios orig; \/\/ backuped port options\n\n\/\/ sqlite globals\nsqlite3 *db;\nchar *zErrMsg = 0;\nint rc;\nconst char *sql;\nconst char* data = \"Callback function called\";\n\nusing namespace std;\n\n\/\/ Declare functions\n\/\/ *********************************************************\nint openSerialPort(const char * device, int bps);\nvoid writeBytes(int descriptor, int count);\nvoid readBytes(int descriptor, int count);\nvoid open_sqlite_db_md49data(void);\nstatic int sql_callback(void *data, int argc, char **argv, char **azColName);\nvoid read_MD49_Data_serial (void);\nvoid read_md49_commands(void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\n\n\n\nint main( int argc, char* argv[] ){\n\n \/\/ Init as ROS node\n \/\/ ****************\n \/\/ros::init(argc, argv, \"serial_controller\");\n \/\/ros::NodeHandle n;\n\n \/\/ Open sqlite database md49data.db\n \/\/ ********************************\n open_sqlite_db_md49data();\n\n \/\/ Open serial port\n \/\/ ****************\n fd = openSerialPort(serialport_name, serialport_bps);\n if (fd == -1) exit(1);\n \/\/ROS_INFO(\"Opend serial port at %s with %i Bps\",serialport_name,serialport_bps);\n usleep(10000); \/\/ Sleep for UART to power up and set options\n\n \/\/ROS_DEBUG(\"Starting Mainloop...\");\n \/\/ROS_DEBUG(\"reading data from MD49 and pushing commands to MD49 @ 5Hz...\");\n\n\n \/\/ Mainloop\n \/\/ ***********************************\n \/\/while( n.ok() ){\n while( 1 ){\n \/\/ Read encodervalues and other data from MD49\n \/\/ serial. Data ist stored in md49_data.txt\n \/\/ ****************************************\n read_MD49_Data_serial();\n usleep(100000);\n\n \/\/ Read commands from md49_commands.txt:\n \/\/ *************************************\n read_md49_commands();\n\n \/\/ Set speed and other commands as\n \/\/ read from md49_commands.txt\n \/\/ *******************************\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n set_MD49_speed(speed_l, speed_r);\n last_speed_l=speed_l;\n last_speed_r=speed_r;\n }\n\n usleep(100000);\n\n }\/\/ end.mainloop\n sqlite3_close(db);\n return 1;\n} \/\/ end.main\n\nvoid read_MD49_Data_serial (void){\n \/\/ Read serial MD49 data from AVR-Master\n \/\/ *************************************\n serialBuffer[0] = 82; \/\/ 82=R Steuerbyte um alle Daten vom MD49 zu lesen\n writeBytes(fd, 1);\n readBytes(fd, 18); \n\n \/\/ Put toghether encoder values from their\n \/\/ corresponding bytes, read from MD49\n \/\/ ***************************************\n EncoderL = serialBuffer[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (serialBuffer[1] << 16);\n EncoderL |= (serialBuffer[2] << 8);\n EncoderL |= (serialBuffer[3]);\n EncoderR = serialBuffer[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (serialBuffer[5] << 16);\n EncoderR |= (serialBuffer[6] << 8);\n EncoderR |= (serialBuffer[7]);\n\n \/\/ Write data read from MD49 into\n \/\/ sqlite3 database md49data.db\n \/\/ ******************************\n char sql_buffer[300];\n int cx;\n cx = snprintf (sql_buffer,300,\"UPDATE md49data SET Encoderbyte1L, Encoderbyte2L, Encoderbyte3L, Encoderbyte4L,\" \\\n \"Encoderbyte1R, Encoderbyte2R, Encoderbyte3R, Encoderbyte4R, EncoderL=%i, EncoderR=%i, \" \\\n \" SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout\" \\\n \"WHERE ID=1\", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3], \\\n serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7], EncoderL, EncoderR, \\\n serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], \\\n serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]);\n\n rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n \/\/fprintf(stdout, \"Operation done successfully\\n\");\n }\n\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",serialBuffer[0]);\n printf(\"Byte2: %i \",serialBuffer[1]);\n printf(\"Byte3: % i \",serialBuffer[2]);\n printf(\"Byte4: %i \\n\",serialBuffer[3]);\n printf(\"Encoder2 Byte1: %i \",serialBuffer[4]);\n printf(\"Byte2: %i \",serialBuffer[5]);\n printf(\"Byte3: %i \",serialBuffer[6]);\n printf(\"Byte4: %i \\n\",serialBuffer[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"SpeedL: %i \",serialBuffer[8]);\n printf(\"SpeedR: %i \\n\",serialBuffer[9]);\n printf(\"Volts: %i \\n\",serialBuffer[10]);\n printf(\"CurrentL: %i \",serialBuffer[11]);\n printf(\"CurrentR: %i \\n\",serialBuffer[12]);\n printf(\"Error: %i \\n\",serialBuffer[13]);\n printf(\"Acceleration: %i \\n\",serialBuffer[14]);\n printf(\"Mode: %i \\n\",serialBuffer[15]);\n printf(\"Regulator: %i \\n\",serialBuffer[16]);\n printf(\"Timeout: %i \\n\",serialBuffer[17]);\n\n}\n\n\/\/ Write serial command to change left and right speed\n\/\/ ***************************************************\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n serialBuffer[0] = 88; \/\/ 88 =X Steuerbyte um Commands an MD49 zu senden\n serialBuffer[1] = 115; \/\/ 115=s Steuerbyte setSpeed\n serialBuffer[2] = speed_l; \/\/ set speed1\n serialBuffer[3] = speed_r; \/\/ set speed2\n writeBytes(fd, 4);\n}\n\n\/\/ Read SpeedL and SpeedR from\n\/\/ table md49commands(md49data.db)\n\/\/ *******************************\nvoid read_md49_commands(void){\n\n \/\/ Create SQL statement\n sql = \"SELECT * from md49commands WHERE ID=1\";\n\n \/\/ Execute SQL statement\n rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n \/\/fprintf(stdout, \"Query done successfully\\n\");\n }\n}\n\n\/\/ Open serialport\n\/\/ ***************\nint openSerialPort(const char * device, int bps){\n\n struct termios neu;\n char buf[128];\n\n \/\/fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);\n fd = open(device, O_RDWR | O_NOCTTY);\n\n if (fd == -1)\n {\n sprintf(buf, \"openSerialPort %s error\", device);\n perror(buf);\n }\n else\n {\n tcgetattr(fd, &orig); \/* save current serial settings *\/\n tcgetattr(fd, &neu);\n cfmakeraw(&neu);\n cfsetispeed(&neu, bps);\n cfsetospeed(&neu, bps);\n tcflush(fd, TCIFLUSH);\n tcsetattr(fd, TCSANOW, &neu); \/* set new serial settings *\/\n fcntl (fd, F_SETFL, O_RDWR);\n }\n return fd;\n}\n\n\/\/ Write bytes serial to UART\n\/\/ **************************\nvoid writeBytes(int descriptor, int count) {\n if ((write(descriptor, serialBuffer, count)) == -1) { \/\/ Send data out\n perror(\"Error writing\");\n close(descriptor); \/\/ Close port if there is an error\n exit(1);\n }\n\n}\n\n\/\/ Read bytes serial from UART\n\/\/ ***************************\nvoid readBytes(int descriptor, int count) {\n if (read(descriptor, serialBuffer, count) == -1) { \/\/ Read back data into buf[]\n perror(\"Error reading \");\n close(descriptor); \/\/ Close port if there is an error\n exit(1);\n }\n}\n\n\/\/ Open sqlite db md49data.db and create\n\/\/ table md49data if not existing\n\/\/ *************************************\nvoid open_sqlite_db_md49data(void){\n\n \/\/ Open database md49data.db and add table md49data\n \/\/ ************************************************\n rc = sqlite3_open(\"data\/md49data.db\", &db);\n if( rc ){\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n exit(0);\n }else{\n fprintf(stdout, \"Opened database successfully,\\n\");\n }\n\n \/\/ Create table md49data\n \/\/ *********************\n sql = \"CREATE TABLE md49data(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"Encoderbyte1L INT DEFAULT 0, Encoderbyte2L INT DEFAULT 0,\" \\\n \"Encoderbyte3L INT DEFAULT 0, Encoderbyte4L INT DEFAULT 0,\" \\\n \"Encoderbyte1R INT DEFAULT 0, Encoderbyte2R INT DEFAULT 0,\" \\\n \"Encoderbyte3R INT DEFAULT 0, Encoderbyte4R INT DEFAULT 0,\" \\\n \"EncoderL INT DEFAULT 0, EncoderR INT DEFAULT 0,\" \\\n \"SpeedL INT DEFAULT 0, SpeedR INT DEFAULT 0,\" \\\n \"Volts INT DEFAULT 0,\" \\\n \"CurrentL INT DEFAULT 0, CurrentR INT DEFAULT 0,\" \\\n \"Error INT DEFAULT 0, Acceleration INT DEFAULT 0,\" \\\n \"Mode INT DEFAULT 0, Regulator INT DEFAULT 0,\" \\\n \"Timeout INT DEFAULT 0 );\" \\\n \"INSERT INTO md49data (ID) VALUES (1);\";\n\n \/* Execute SQL statement *\/\n rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n fprintf(stdout, \"table created successfully\\n\");\n }\n}\n\n\/\/ Callbackfunction executed if table md49commands in md49data.db is queried\n\/\/ *************************************************************************\nstatic int sql_callback(void *data, int argc, char **argv, char **azColName){\n speed_l= atoi(argv[1]);\n speed_r= atoi(argv[2]);\n return 0;\n}\n\n\n<commit_msg>Remove txt files<commit_after>\/*! \\brief serial_controller_node.\n * Manages serial communications with AVR-Master.\n *\n * This node manages serial communications with the AVR-Master.\n * Therefore it first requests all data from AVR-Master and then sends all\n * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,\n * commands to be send are read from md49_commands.txt.\n *\n *\/\n\n\/\/ Includes\n\/\/ *********************************************************\n#include <iostream> \/* allows to perform standard input and output operations *\/\n\/\/#include <fstream> \/* Input\/output stream class to operate on files. *\/\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n\/\/#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n\/\/#include <ctype.h> \/* isxxx() *\/\n\/\/#include<ros\/ros.h>\n#include <sqlite3.h>\n\n\n\/\/ Global variables\nconst char* serialport_name=\"\/\/dev\/ttyAMA0\"; \/* defines used serialport on BPi. Use \"\/dev\/ttyAMA0\" for RPi*\/\nint serialport_bps=B9600; \/* defines used baudrate on serialport *\/\n\/\/int filedesc; \/* File descriptor of serial port we will talk to*\/\nint fd; \/* serial port file descriptor *\/\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\nunsigned char last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\nunsigned char serialBuffer[16]; \/* Serial buffer to store uart data *\/\nstruct termios orig; \/\/ backuped port options\n\n\/\/ sqlite globals\nsqlite3 *db;\nchar *zErrMsg = 0;\nint rc;\nconst char *sql;\nconst char* data = \"Callback function called\";\n\nusing namespace std;\n\n\/\/ Declare functions\n\/\/ *********************************************************\nint openSerialPort(const char * device, int bps);\nvoid writeBytes(int descriptor, int count);\nvoid readBytes(int descriptor, int count);\nvoid open_sqlite_db_md49data(void);\nstatic int sql_callback(void *data, int argc, char **argv, char **azColName);\nvoid read_MD49_Data_serial (void);\nvoid read_md49_commands(void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\n\n\n\nint main( int argc, char* argv[] ){\n\n \/\/ Init as ROS node\n \/\/ ****************\n \/\/ros::init(argc, argv, \"serial_controller\");\n \/\/ros::NodeHandle n;\n\n \/\/ Open sqlite database md49data.db\n \/\/ ********************************\n open_sqlite_db_md49data();\n\n \/\/ Open serial port\n \/\/ ****************\n fd = openSerialPort(serialport_name, serialport_bps);\n if (fd == -1) exit(1);\n \/\/ROS_INFO(\"Opend serial port at %s with %i Bps\",serialport_name,serialport_bps);\n usleep(10000); \/\/ Sleep for UART to power up and set options\n\n \/\/ROS_DEBUG(\"Starting Mainloop...\");\n \/\/ROS_DEBUG(\"reading data from MD49 and pushing commands to MD49 @ 5Hz...\");\n\n\n \/\/ Mainloop\n \/\/ ***********************************\n \/\/while( n.ok() ){\n while( 1 ){\n \/\/ Read encodervalues and other data from MD49\n \/\/ serial. Data ist stored in md49_data.txt\n \/\/ ****************************************\n read_MD49_Data_serial();\n usleep(100000);\n\n \/\/ Read commands from md49_commands.txt:\n \/\/ *************************************\n read_md49_commands();\n\n \/\/ Set speed and other commands as\n \/\/ read from md49_commands.txt\n \/\/ *******************************\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n set_MD49_speed(speed_l, speed_r);\n last_speed_l=speed_l;\n last_speed_r=speed_r;\n }\n\n usleep(100000);\n\n }\/\/ end.mainloop\n sqlite3_close(db);\n return 1;\n} \/\/ end.main\n\nvoid read_MD49_Data_serial (void){\n \/\/ Read serial MD49 data from AVR-Master\n \/\/ *************************************\n serialBuffer[0] = 82; \/\/ 82=R Steuerbyte um alle Daten vom MD49 zu lesen\n writeBytes(fd, 1);\n readBytes(fd, 18); \n\n \/\/ Put toghether encoder values from their\n \/\/ corresponding bytes, read from MD49\n \/\/ ***************************************\n EncoderL = serialBuffer[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (serialBuffer[1] << 16);\n EncoderL |= (serialBuffer[2] << 8);\n EncoderL |= (serialBuffer[3]);\n EncoderR = serialBuffer[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (serialBuffer[5] << 16);\n EncoderR |= (serialBuffer[6] << 8);\n EncoderR |= (serialBuffer[7]);\n\n \/\/ Write data read from MD49 into\n \/\/ sqlite3 database md49data.db\n \/\/ ******************************\n char sql_buffer[300];\n int cx;\n cx = snprintf (sql_buffer,300,\"UPDATE md49data SET Encoderbyte1L, Encoderbyte2L, Encoderbyte3L, Encoderbyte4L,\" \\\n \"Encoderbyte1R, Encoderbyte2R, Encoderbyte3R, Encoderbyte4R, EncoderL=%i, EncoderR=%i, \" \\\n \" SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout\" \\\n \"WHERE ID=1\", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3], serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7], EncoderL, EncoderR, serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]);\n\n rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n \/\/fprintf(stdout, \"Operation done successfully\\n\");\n }\n\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",serialBuffer[0]);\n printf(\"Byte2: %i \",serialBuffer[1]);\n printf(\"Byte3: % i \",serialBuffer[2]);\n printf(\"Byte4: %i \\n\",serialBuffer[3]);\n printf(\"Encoder2 Byte1: %i \",serialBuffer[4]);\n printf(\"Byte2: %i \",serialBuffer[5]);\n printf(\"Byte3: %i \",serialBuffer[6]);\n printf(\"Byte4: %i \\n\",serialBuffer[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"SpeedL: %i \",serialBuffer[8]);\n printf(\"SpeedR: %i \\n\",serialBuffer[9]);\n printf(\"Volts: %i \\n\",serialBuffer[10]);\n printf(\"CurrentL: %i \",serialBuffer[11]);\n printf(\"CurrentR: %i \\n\",serialBuffer[12]);\n printf(\"Error: %i \\n\",serialBuffer[13]);\n printf(\"Acceleration: %i \\n\",serialBuffer[14]);\n printf(\"Mode: %i \\n\",serialBuffer[15]);\n printf(\"Regulator: %i \\n\",serialBuffer[16]);\n printf(\"Timeout: %i \\n\",serialBuffer[17]);\n\n}\n\n\/\/ Write serial command to change left and right speed\n\/\/ ***************************************************\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n serialBuffer[0] = 88; \/\/ 88 =X Steuerbyte um Commands an MD49 zu senden\n serialBuffer[1] = 115; \/\/ 115=s Steuerbyte setSpeed\n serialBuffer[2] = speed_l; \/\/ set speed1\n serialBuffer[3] = speed_r; \/\/ set speed2\n writeBytes(fd, 4);\n}\n\n\/\/ Read SpeedL and SpeedR from\n\/\/ table md49commands(md49data.db)\n\/\/ *******************************\nvoid read_md49_commands(void){\n\n \/\/ Create SQL statement\n sql = \"SELECT * from md49commands WHERE ID=1\";\n\n \/\/ Execute SQL statement\n rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n \/\/fprintf(stdout, \"Query done successfully\\n\");\n }\n}\n\n\/\/ Open serialport\n\/\/ ***************\nint openSerialPort(const char * device, int bps){\n\n struct termios neu;\n char buf[128];\n\n \/\/fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);\n fd = open(device, O_RDWR | O_NOCTTY);\n\n if (fd == -1)\n {\n sprintf(buf, \"openSerialPort %s error\", device);\n perror(buf);\n }\n else\n {\n tcgetattr(fd, &orig); \/* save current serial settings *\/\n tcgetattr(fd, &neu);\n cfmakeraw(&neu);\n cfsetispeed(&neu, bps);\n cfsetospeed(&neu, bps);\n tcflush(fd, TCIFLUSH);\n tcsetattr(fd, TCSANOW, &neu); \/* set new serial settings *\/\n fcntl (fd, F_SETFL, O_RDWR);\n }\n return fd;\n}\n\n\/\/ Write bytes serial to UART\n\/\/ **************************\nvoid writeBytes(int descriptor, int count) {\n if ((write(descriptor, serialBuffer, count)) == -1) { \/\/ Send data out\n perror(\"Error writing\");\n close(descriptor); \/\/ Close port if there is an error\n exit(1);\n }\n\n}\n\n\/\/ Read bytes serial from UART\n\/\/ ***************************\nvoid readBytes(int descriptor, int count) {\n if (read(descriptor, serialBuffer, count) == -1) { \/\/ Read back data into buf[]\n perror(\"Error reading \");\n close(descriptor); \/\/ Close port if there is an error\n exit(1);\n }\n}\n\n\/\/ Open sqlite db md49data.db and create\n\/\/ table md49data if not existing\n\/\/ *************************************\nvoid open_sqlite_db_md49data(void){\n\n \/\/ Open database md49data.db and add table md49data\n \/\/ ************************************************\n rc = sqlite3_open(\"data\/md49data.db\", &db);\n if( rc ){\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n exit(0);\n }else{\n fprintf(stdout, \"Opened database successfully,\\n\");\n }\n\n \/\/ Create table md49data\n \/\/ *********************\n sql = \"CREATE TABLE md49data(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"Encoderbyte1L INT DEFAULT 0, Encoderbyte2L INT DEFAULT 0,\" \\\n \"Encoderbyte3L INT DEFAULT 0, Encoderbyte4L INT DEFAULT 0,\" \\\n \"Encoderbyte1R INT DEFAULT 0, Encoderbyte2R INT DEFAULT 0,\" \\\n \"Encoderbyte3R INT DEFAULT 0, Encoderbyte4R INT DEFAULT 0,\" \\\n \"EncoderL INT DEFAULT 0, EncoderR INT DEFAULT 0,\" \\\n \"SpeedL INT DEFAULT 0, SpeedR INT DEFAULT 0,\" \\\n \"Volts INT DEFAULT 0,\" \\\n \"CurrentL INT DEFAULT 0, CurrentR INT DEFAULT 0,\" \\\n \"Error INT DEFAULT 0, Acceleration INT DEFAULT 0,\" \\\n \"Mode INT DEFAULT 0, Regulator INT DEFAULT 0,\" \\\n \"Timeout INT DEFAULT 0 );\" \\\n \"INSERT INTO md49data (ID) VALUES (1);\";\n\n \/* Execute SQL statement *\/\n rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);\n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL message: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n }else{\n fprintf(stdout, \"table created successfully\\n\");\n }\n}\n\n\/\/ Callbackfunction executed if table md49commands in md49data.db is queried\n\/\/ *************************************************************************\nstatic int sql_callback(void *data, int argc, char **argv, char **azColName){\n speed_l= atoi(argv[1]);\n speed_r= atoi(argv[2]);\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: typeselectionpage.cxx,v $\n * $Revision: 1.16 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n#include \"typeselectionpage.hxx\"\n#include \"addresssettings.hxx\"\n#include \"abspilot.hxx\"\n#include <vcl\/msgbox.hxx>\n#include <com\/sun\/star\/sdbc\/XDriverAccess.hpp>\n\n\/\/.........................................................................\nnamespace abp\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::sdbc;\n\n \/\/=====================================================================\n \/\/= TypeSelectionPage\n \/\/=====================================================================\n \/\/---------------------------------------------------------------------\n TypeSelectionPage::TypeSelectionPage( OAddessBookSourcePilot* _pParent )\n :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_SELECTABTYPE))\n ,m_aHint (this, ModuleRes(FT_TYPE_HINTS))\n ,m_aTypeSep (this, ModuleRes(FL_TYPE))\n ,m_aMORK (this, ModuleRes(RB_MORK))\n ,m_aThunderbird (this, ModuleRes(RB_THUNDERBIRD))\n ,m_aEvolutionGroupwise (this, ModuleRes(RB_EVOLUTION_GROUPWISE))\n ,m_aEvolutionLdap (this, ModuleRes(RB_EVOLUTION_LDAP))\n ,m_aEvolution (this, ModuleRes(RB_EVOLUTION))\n ,m_aKab (this, ModuleRes(RB_KAB))\n ,m_aMacab (this, ModuleRes(RB_MACAB))\n ,m_aLDAP (this, ModuleRes(RB_LDAP))\n ,m_aOutlook (this, ModuleRes(RB_OUTLOOK))\n ,m_aOE (this, ModuleRes(RB_OUTLOOKEXPRESS))\n ,m_aOther (this, ModuleRes(RB_OTHER))\n {\n Point aTopLeft;\n Size aItemSize;\n\n FreeResource();\n\n aTopLeft = m_aMORK.GetPosPixel();\n aItemSize = m_aMORK.GetSizePixel();\n\n bool bWithMozilla = true, bUnx = true;\n bool bHaveEvolution = true, bHaveKab = true;\n bool bHaveMacab = true;\n\n#ifndef WITH_MOZILLA\n bWithMozilla = false;\n#endif\n#ifndef UNX\n bUnx = false;\n bHaveEvolution = false;\n bHaveKab = false;\n bHaveMacab = false;\n#else\n Reference< XDriverAccess> xManager(_pParent->getORB()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdbc.DriverManager\"))), UNO_QUERY);\n\n \/\/ check whether Evolution is available\n Reference< XDriver > xDriver( xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:evolution:local\"))) );\n if ( !xDriver.is() )\n bHaveEvolution = false;\n\n \/\/ check whether KDE address book is available\n xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:kab\")));\n if ( !xDriver.is() )\n bHaveKab = false;\n\n \/\/ check whether Mac OS X address book is available\n xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:macab\")));\n if ( !xDriver.is() )\n bHaveMacab = false;\n#endif\n\n \/\/ Items are displayed in list order\n m_aAllTypes.push_back( ButtonItem( &m_aEvolution, AST_EVOLUTION, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aEvolutionGroupwise, AST_EVOLUTION_GROUPWISE, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aEvolutionLdap, AST_EVOLUTION_LDAP, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aMORK, AST_MORK, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aThunderbird, AST_THUNDERBIRD, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aKab, AST_KAB, bHaveKab ) );\n m_aAllTypes.push_back( ButtonItem( &m_aMacab, AST_MACAB, bHaveMacab ) );\n m_aAllTypes.push_back( ButtonItem( &m_aLDAP, AST_LDAP, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOutlook, AST_OUTLOOK, bWithMozilla && !bUnx ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOE, AST_OE, bWithMozilla && !bUnx ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOther, AST_OTHER, true ) );\n\n Link aTypeSelectionHandler = LINK(this, TypeSelectionPage, OnTypeSelected );\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = *loop;\n if (!aItem.m_bVisible)\n aItem.m_pItem->Hide();\n else\n {\n aItem.m_pItem->SetPosPixel( aTopLeft );\n aTopLeft.Y() += (aItemSize.Height() * 5) \/ 4;\n aItem.m_pItem->SetClickHdl( aTypeSelectionHandler );\n aItem.m_pItem->Show();\n }\n }\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::ActivatePage()\n {\n AddressBookSourcePage::ActivatePage();\n\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n if( aItem.m_pItem->IsChecked() && aItem.m_bVisible )\n {\n aItem.m_pItem->GrabFocus();\n break;\n }\n }\n\n getDialog()->enableButtons(WZB_PREVIOUS, sal_False);\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::DeactivatePage()\n {\n AddressBookSourcePage::DeactivatePage();\n getDialog()->enableButtons(WZB_PREVIOUS, sal_True);\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::selectType( AddressSourceType _eType )\n {\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n aItem.m_pItem->Check( _eType == aItem.m_eType );\n }\n }\n\n \/\/---------------------------------------------------------------------\n AddressSourceType TypeSelectionPage::getSelectedType() const\n {\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n if ( aItem.m_pItem->IsChecked() )\n return aItem.m_eType;\n }\n\n return AST_INVALID;\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::initializePage()\n {\n AddressBookSourcePage::initializePage();\n\n const AddressSettings& rSettings = getSettings();\n selectType(rSettings.eType);\n }\n\n \/\/---------------------------------------------------------------------\n sal_Bool TypeSelectionPage::commitPage( CommitPageReason _eReason )\n {\n if (!AddressBookSourcePage::commitPage(_eReason))\n return sal_False;\n\n if (AST_INVALID == getSelectedType( ))\n {\n if ( _eReason != eValidateNoUI )\n {\n ErrorBox aError(this, ModuleRes(RID_ERR_NEEDTYPESELECTION));\n aError.Execute();\n }\n return sal_False;\n }\n\n AddressSettings& rSettings = getSettings();\n rSettings.eType = getSelectedType();\n\n return sal_True;\n }\n\n \/\/---------------------------------------------------------------------\n bool TypeSelectionPage::canAdvance() const\n {\n return AddressBookSourcePage::canAdvance()\n && (AST_INVALID != getSelectedType());\n }\n\n \/\/---------------------------------------------------------------------\n IMPL_LINK( TypeSelectionPage, OnTypeSelected, void*, \/*NOTINTERESTEDIN*\/ )\n {\n getDialog()->typeSelectionChanged( getSelectedType() );\n updateDialogTravelUI();\n return 0L;\n }\n\n\/\/.........................................................................\n} \/\/ namespace abp\n\/\/.........................................................................\n\n<commit_msg>INTEGRATION: CWS nomacmozab (1.16.50); FILE MERGED 2008\/07\/01 20:01:31 fs 1.16.50.1: #i91209# no Mozilla-based address books on mac OS X<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: typeselectionpage.cxx,v $\n * $Revision: 1.17 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n#include \"typeselectionpage.hxx\"\n#include \"addresssettings.hxx\"\n#include \"abspilot.hxx\"\n#include <vcl\/msgbox.hxx>\n#include <com\/sun\/star\/sdbc\/XDriverAccess.hpp>\n\n\/\/.........................................................................\nnamespace abp\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::sdbc;\n\n \/\/=====================================================================\n \/\/= TypeSelectionPage\n \/\/=====================================================================\n \/\/---------------------------------------------------------------------\n TypeSelectionPage::TypeSelectionPage( OAddessBookSourcePilot* _pParent )\n :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_SELECTABTYPE))\n ,m_aHint (this, ModuleRes(FT_TYPE_HINTS))\n ,m_aTypeSep (this, ModuleRes(FL_TYPE))\n ,m_aMORK (this, ModuleRes(RB_MORK))\n ,m_aThunderbird (this, ModuleRes(RB_THUNDERBIRD))\n ,m_aEvolutionGroupwise (this, ModuleRes(RB_EVOLUTION_GROUPWISE))\n ,m_aEvolutionLdap (this, ModuleRes(RB_EVOLUTION_LDAP))\n ,m_aEvolution (this, ModuleRes(RB_EVOLUTION))\n ,m_aKab (this, ModuleRes(RB_KAB))\n ,m_aMacab (this, ModuleRes(RB_MACAB))\n ,m_aLDAP (this, ModuleRes(RB_LDAP))\n ,m_aOutlook (this, ModuleRes(RB_OUTLOOK))\n ,m_aOE (this, ModuleRes(RB_OUTLOOKEXPRESS))\n ,m_aOther (this, ModuleRes(RB_OTHER))\n {\n Point aTopLeft;\n Size aItemSize;\n\n FreeResource();\n\n aTopLeft = m_aMORK.GetPosPixel();\n aItemSize = m_aMORK.GetSizePixel();\n\n bool bWithMozilla = true, bUnx = true;\n bool bHaveEvolution = true, bHaveKab = true;\n bool bHaveMacab = true;\n\n#if !defined WITH_MOZILLA || defined MACOSX\n bWithMozilla = false;\n#endif\n#ifndef UNX\n bUnx = false;\n bHaveEvolution = false;\n bHaveKab = false;\n bHaveMacab = false;\n#else\n Reference< XDriverAccess> xManager(_pParent->getORB()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.sdbc.DriverManager\"))), UNO_QUERY);\n\n \/\/ check whether Evolution is available\n Reference< XDriver > xDriver( xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:evolution:local\"))) );\n if ( !xDriver.is() )\n bHaveEvolution = false;\n\n \/\/ check whether KDE address book is available\n xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:kab\")));\n if ( !xDriver.is() )\n bHaveKab = false;\n\n \/\/ check whether Mac OS X address book is available\n xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"sdbc:address:macab\")));\n if ( !xDriver.is() )\n bHaveMacab = false;\n#endif\n\n \/\/ Items are displayed in list order\n m_aAllTypes.push_back( ButtonItem( &m_aEvolution, AST_EVOLUTION, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aEvolutionGroupwise, AST_EVOLUTION_GROUPWISE, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aEvolutionLdap, AST_EVOLUTION_LDAP, bHaveEvolution ) );\n m_aAllTypes.push_back( ButtonItem( &m_aMORK, AST_MORK, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aThunderbird, AST_THUNDERBIRD, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aKab, AST_KAB, bHaveKab ) );\n m_aAllTypes.push_back( ButtonItem( &m_aMacab, AST_MACAB, bHaveMacab ) );\n m_aAllTypes.push_back( ButtonItem( &m_aLDAP, AST_LDAP, bWithMozilla ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOutlook, AST_OUTLOOK, bWithMozilla && !bUnx ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOE, AST_OE, bWithMozilla && !bUnx ) );\n m_aAllTypes.push_back( ButtonItem( &m_aOther, AST_OTHER, true ) );\n\n Link aTypeSelectionHandler = LINK(this, TypeSelectionPage, OnTypeSelected );\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = *loop;\n if (!aItem.m_bVisible)\n aItem.m_pItem->Hide();\n else\n {\n aItem.m_pItem->SetPosPixel( aTopLeft );\n aTopLeft.Y() += (aItemSize.Height() * 5) \/ 4;\n aItem.m_pItem->SetClickHdl( aTypeSelectionHandler );\n aItem.m_pItem->Show();\n }\n }\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::ActivatePage()\n {\n AddressBookSourcePage::ActivatePage();\n\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n if( aItem.m_pItem->IsChecked() && aItem.m_bVisible )\n {\n aItem.m_pItem->GrabFocus();\n break;\n }\n }\n\n getDialog()->enableButtons(WZB_PREVIOUS, sal_False);\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::DeactivatePage()\n {\n AddressBookSourcePage::DeactivatePage();\n getDialog()->enableButtons(WZB_PREVIOUS, sal_True);\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::selectType( AddressSourceType _eType )\n {\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n aItem.m_pItem->Check( _eType == aItem.m_eType );\n }\n }\n\n \/\/---------------------------------------------------------------------\n AddressSourceType TypeSelectionPage::getSelectedType() const\n {\n for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();\n loop != m_aAllTypes.end(); ++loop )\n {\n ButtonItem aItem = (*loop);\n if ( aItem.m_pItem->IsChecked() )\n return aItem.m_eType;\n }\n\n return AST_INVALID;\n }\n\n \/\/---------------------------------------------------------------------\n void TypeSelectionPage::initializePage()\n {\n AddressBookSourcePage::initializePage();\n\n const AddressSettings& rSettings = getSettings();\n selectType(rSettings.eType);\n }\n\n \/\/---------------------------------------------------------------------\n sal_Bool TypeSelectionPage::commitPage( CommitPageReason _eReason )\n {\n if (!AddressBookSourcePage::commitPage(_eReason))\n return sal_False;\n\n if (AST_INVALID == getSelectedType( ))\n {\n if ( _eReason != eValidateNoUI )\n {\n ErrorBox aError(this, ModuleRes(RID_ERR_NEEDTYPESELECTION));\n aError.Execute();\n }\n return sal_False;\n }\n\n AddressSettings& rSettings = getSettings();\n rSettings.eType = getSelectedType();\n\n return sal_True;\n }\n\n \/\/---------------------------------------------------------------------\n bool TypeSelectionPage::canAdvance() const\n {\n return AddressBookSourcePage::canAdvance()\n && (AST_INVALID != getSelectedType());\n }\n\n \/\/---------------------------------------------------------------------\n IMPL_LINK( TypeSelectionPage, OnTypeSelected, void*, \/*NOTINTERESTEDIN*\/ )\n {\n getDialog()->typeSelectionChanged( getSelectedType() );\n updateDialogTravelUI();\n return 0L;\n }\n\n\/\/.........................................................................\n} \/\/ namespace abp\n\/\/.........................................................................\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_utils_to_throttle.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_utils_to_throttle.C\n\/\/\/ @brief Sets throttles\n\/\/\/ TMGT will call this procedure to set the N address operations (commands)\n\/\/\/ allowed within a window of M DRAM clocks given the minimum dram data bus utilization.\n\/\/\/\n\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <p9_mss_utils_to_throttle.H>\n\n\/\/ fapi2\n#include <fapi2.H>\n\n\/\/ mss lib\n#include <lib\/power_thermal\/throttle.H>\n#include <lib\/utils\/index.H>\n#include <lib\/utils\/find.H>\n#include <lib\/utils\/conversions.H>\n#include <lib\/mss_attribute_accessors.H>\n\nusing fapi2::TARGET_TYPE_MCS;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_DIMM;\n\nextern \"C\"\n{\n\n\/\/\/\n\/\/\/ @brief Sets number commands allowed within a given data bus utilization.\n\/\/\/ @param[in] i_targets vector of MCS on the same VDDR domain\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/ @note throttle_per_slot will be equalized so all throttles coming out will be equal to worst case\n\/\/\/\n fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector< fapi2::Target<TARGET_TYPE_MCS> >& i_targets )\n {\n for( const auto& l_mcs : i_targets )\n {\n \/\/TODO RTC 160048 Complete implementing (calculating power and per slot throttles) - JLH\n uint32_t l_databus_util [mss::PORTS_PER_MCS];\n uint32_t l_throttled_cmds_port[mss::PORTS_PER_MCS];\n uint32_t l_throttled_cmds_slot[mss::PORTS_PER_MCS];\n uint32_t l_max_power[mss::PORTS_PER_MCS];\n\n uint32_t l_dram_clocks = 0;\n FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );\n\n FAPI_TRY( mss::databus_util(l_mcs, l_databus_util) );\n\n for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) )\n {\n const auto l_port_num = mss::index( l_mca );\n\n FAPI_INF( \"MRW dram clock window: %d, databus utilization: %d\",\n l_dram_clocks,\n l_databus_util );\n\n \/\/ Calculate programmable N address operations within M dram clock window\n l_throttled_cmds_port[l_port_num] = mss::power_thermal::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );\n l_throttled_cmds_slot[l_port_num] = mss::power_thermal::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );\n \/\/TK - actually implement function - JLH\n \/\/Quick hard code for API purposes\n l_max_power[l_port_num] = 2088;\n FAPI_INF( \"Calculated N commands per port [%d] = %d\",\n l_port_num,\n l_throttled_cmds_port[l_port_num]);\n }\/\/ end for\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_PORT_MAXPOWER,\n l_mcs,\n l_max_power) );\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_SLOT,\n l_mcs,\n l_throttled_cmds_slot) );\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT,\n l_mcs,\n l_throttled_cmds_port) );\n }\n\n fapi_try_exit:\n return fapi2::current_err;\n }\n\n}\/\/ extern C\n<commit_msg>Implement L2 eff_config_thermal, bulk_pwr_throttle<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_utils_to_throttle.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_utils_to_throttle.C\n\/\/\/ @brief Sets throttles\n\/\/\/ TMGT will call this procedure to set the N address operations (commands)\n\/\/\/ allowed within a window of M DRAM clocks given the minimum dram data bus utilization.\n\/\/\/\n\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <p9_mss_utils_to_throttle.H>\n\n\/\/ fapi2\n#include <fapi2.H>\n\n\/\/ mss lib\n#include <lib\/power_thermal\/throttle.H>\n#include <lib\/utils\/index.H>\n#include <lib\/utils\/find.H>\n#include <lib\/utils\/conversions.H>\n#include <lib\/power_thermal\/throttle.H>\n#include <lib\/mss_attribute_accessors.H>\n\nusing fapi2::TARGET_TYPE_MCS;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_DIMM;\n\nextern \"C\"\n{\n\n\/\/\/\n\/\/\/ @brief Sets number commands allowed within a given data bus utilization.\n\/\/\/ @param[in] i_targets vector of MCS on the same VDDR domain\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/ @note throttle_per_slot will be equalized so all throttles coming out will be equal to worst case\n\/\/\/\n fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector< fapi2::Target<TARGET_TYPE_MCS> >& i_targets )\n {\n for( const auto& l_mcs : i_targets )\n {\n uint32_t l_databus_util [mss::PORTS_PER_MCS];\n uint32_t l_dram_clocks = 0;\n\n uint16_t l_throttled_cmds_port[mss::PORTS_PER_MCS];\n uint16_t l_throttled_cmds_slot[mss::PORTS_PER_MCS];\n uint32_t l_max_power[mss::PORTS_PER_MCS];\n\n FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );\n \/\/Util attribute set by OCC\n FAPI_TRY( mss::databus_util(l_mcs, l_databus_util) );\n\n for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) )\n {\n const auto l_port_num = mss::index( l_mca );\n \/\/Make a throttle object in order to calculate the port power\n fapi2::ReturnCode l_rc;\n mss::power_thermal::throttle l_throttle (l_mca, l_rc);\n FAPI_TRY(l_rc, \"Error calculating mss::power_thermal::throttle constructor in p9_mss_utils_to_throttles\");\n\n FAPI_INF( \"MRW dram clock window: %d, databus utilization: %d\",\n l_dram_clocks,\n l_databus_util);\n\n \/\/Calculate programmable N address operations within M dram clock window\n l_throttled_cmds_port[l_port_num] = mss::power_thermal::throttled_cmds(l_databus_util[l_port_num],\n l_dram_clocks );\n l_throttled_cmds_slot[l_port_num] = l_throttled_cmds_port[l_port_num];\n \/\/Calculate the port power needed to reach the calculated N value\n l_max_power[l_port_num] = l_throttle.calc_power_from_n(l_throttled_cmds_slot[l_port_num]);\n\n FAPI_INF( \"Calculated N commands per port [%d] = %d commands, maxpower is %d\",\n l_port_num,\n l_throttled_cmds_port[l_port_num],\n l_max_power[l_port_num]);\n }\/\/ end for\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_PORT_MAXPOWER,\n l_mcs,\n l_max_power) );\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT,\n l_mcs,\n l_throttled_cmds_slot) );\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_PORT,\n l_mcs,\n l_throttled_cmds_port) );\n }\n\n fapi_try_exit:\n return fapi2::current_err;\n }\n\n}\/\/ extern C\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"maintenancecontroller.h\"\n#include \"maintenancejobrunner.h\"\n#include \"document_db_maintenance_config.h\"\n#include \"i_blockable_maintenance_job.h\"\n#include <vespa\/searchcorespi\/index\/i_thread_service.h>\n#include <vespa\/vespalib\/util\/lambdatask.h>\n#include <vespa\/vespalib\/util\/scheduledexecutor.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.maintenancecontroller\");\n\nusing document::BucketId;\nusing vespalib::Executor;\nusing vespalib::makeLambdaTask;\n\nnamespace proton {\n\nnamespace {\n\nclass JobWrapperTask : public Executor::Task\n{\nprivate:\n MaintenanceJobRunner *_job;\npublic:\n JobWrapperTask(MaintenanceJobRunner *job) : _job(job) {}\n void run() override { _job->run(); }\n};\n\n}\n\nMaintenanceController::MaintenanceController(IThreadService &masterThread,\n vespalib::Executor & defaultExecutor,\n const DocTypeName &docTypeName)\n : IBucketFreezeListener(),\n _masterThread(masterThread),\n _defaultExecutor(defaultExecutor),\n _readySubDB(),\n _remSubDB(),\n _notReadySubDB(),\n _periodicTimer(),\n _config(),\n _frozenBuckets(masterThread),\n _state(State::INITIALIZING),\n _docTypeName(docTypeName),\n _jobs(),\n _jobsLock()\n{\n _frozenBuckets.addListener(this); \/\/ forward freeze\/thaw to bmc\n}\n\nMaintenanceController::~MaintenanceController()\n{\n kill();\n _frozenBuckets.removeListener(this);\n}\n\nvoid\nMaintenanceController::registerJobInMasterThread(IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n registerJob(_masterThread, std::move(job));\n}\n\nvoid\nMaintenanceController::registerJobInDefaultPool(IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n registerJob(_defaultExecutor, std::move(job));\n}\n\nvoid\nMaintenanceController::registerJob(Executor & executor, IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n Guard guard(_jobsLock);\n _jobs.push_back(std::make_shared<MaintenanceJobRunner>(executor, std::move(job)));\n}\n\n\nvoid\nMaintenanceController::killJobs()\n{\n if (_state == State::STARTED) {\n _state = State::PAUSED;\n }\n \/\/ Called by master write thread\n assert(_masterThread.isCurrentThread());\n LOG(debug, \"killJobs(): threadId=%zu\", (size_t)FastOS_Thread::GetCurrentThreadId());\n _periodicTimer.reset();\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (auto &job : _jobs) {\n job->stop(); \/\/ Make sure no more tasks are added to the executor\n }\n for (auto &job : _jobs) {\n while (job->isRunning()) {\n std::this_thread::sleep_for(1ms);\n }\n }\n JobList tmpJobs = _jobs;\n {\n Guard guard(_jobsLock);\n _jobs.clear();\n }\n \/\/ Hold jobs until existing tasks have been drained\n _masterThread.execute(makeLambdaTask([this, jobs=std::move(tmpJobs)]() {\n performHoldJobs(std::move(jobs));\n }));\n}\n\nvoid\nMaintenanceController::updateMetrics(DocumentDBTaggedMetrics & metrics)\n{\n Guard guard(_jobsLock);\n for (auto &job : _jobs) {\n job->getJob().updateMetrics(metrics); \/\/ Make sure no more tasks are added to the executor\n }\n}\n\nvoid\nMaintenanceController::performHoldJobs(JobList jobs)\n{\n \/\/ Called by master write thread\n LOG(debug, \"performHoldJobs(): threadId=%zu\", (size_t)FastOS_Thread::GetCurrentThreadId());\n (void) jobs;\n}\n\nvoid\nMaintenanceController::stop()\n{\n assert(!_masterThread.isCurrentThread());\n _masterThread.execute(makeLambdaTask([this]() { _state = State::STOPPING; killJobs(); }));\n _masterThread.sync(); \/\/ Wait for killJobs()\n _masterThread.sync(); \/\/ Wait for already scheduled maintenance jobs and performHoldJobs\n}\n\nvoid\nMaintenanceController::kill()\n{\n stop();\n _readySubDB.clear();\n _remSubDB.clear();\n _notReadySubDB.clear();\n}\n\nvoid\nMaintenanceController::start(const DocumentDBMaintenanceConfig::SP &config)\n{\n \/\/ Called by master write thread\n assert(_state == State::INITIALIZING);\n _config = config;\n _state = State::STARTED;\n restart();\n}\n\n\nvoid\nMaintenanceController::restart()\n{\n \/\/ Called by master write thread\n if (!getStarted() || getStopping() || !_readySubDB.valid()) {\n return;\n }\n _periodicTimer = std::make_unique<vespalib::ScheduledExecutor>();\n\n addJobsToPeriodicTimer();\n}\n\nvoid\nMaintenanceController::addJobsToPeriodicTimer()\n{\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (const auto &jw : _jobs) {\n const IMaintenanceJob &job = jw->getJob();\n LOG(debug, \"addJobsToPeriodicTimer(): docType='%s', job.name='%s', job.delay=%f, job.interval=%f\",\n _docTypeName.getName().c_str(), job.getName().c_str(), vespalib::to_s(job.getDelay()), vespalib::to_s(job.getInterval()));\n if (job.getInterval() == vespalib::duration::zero()) {\n jw->run();\n continue;\n }\n _periodicTimer->scheduleAtFixedRate(std::make_unique<JobWrapperTask>(jw.get()),\n job.getDelay(), job.getInterval());\n }\n}\n\nvoid\nMaintenanceController::newConfig(const DocumentDBMaintenanceConfig::SP &config)\n{\n \/\/ Called by master write thread\n _config = config;\n restart();\n}\n\nnamespace {\n\nvoid\nassert_equal_meta_store_instances(const MaintenanceDocumentSubDB& old_db,\n const MaintenanceDocumentSubDB& new_db)\n{\n if (old_db.valid() && new_db.valid()) {\n assert(old_db.meta_store().get() == new_db.meta_store().get());\n }\n}\n\n}\n\nvoid\nMaintenanceController::syncSubDBs(const MaintenanceDocumentSubDB &readySubDB,\n const MaintenanceDocumentSubDB &remSubDB,\n const MaintenanceDocumentSubDB ¬ReadySubDB)\n{\n \/\/ Called by master write thread\n bool oldValid = _readySubDB.valid();\n assert(readySubDB.valid());\n assert(remSubDB.valid());\n \/\/ Document meta store instances should not change. Maintenance jobs depend on this fact.\n assert_equal_meta_store_instances(_readySubDB, readySubDB);\n assert_equal_meta_store_instances(_remSubDB, remSubDB);\n assert_equal_meta_store_instances(_notReadySubDB, notReadySubDB);\n _readySubDB = readySubDB;\n _remSubDB = remSubDB;\n _notReadySubDB = notReadySubDB;\n if (!oldValid && getStarted()) {\n restart();\n }\n}\n\n\nvoid\nMaintenanceController::notifyThawedBucket(const BucketId &bucket)\n{\n (void) bucket;\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (const auto &jw : _jobs) {\n IBlockableMaintenanceJob *job = jw->getJob().asBlockable();\n if (job && job->isBlocked()) {\n job->unBlock(IBlockableMaintenanceJob::BlockedReason::FROZEN_BUCKET);\n }\n }\n}\n\n\n} \/\/ namespace proton\n<commit_msg>Include thread when needed.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"maintenancecontroller.h\"\n#include \"maintenancejobrunner.h\"\n#include \"document_db_maintenance_config.h\"\n#include \"i_blockable_maintenance_job.h\"\n#include <vespa\/searchcorespi\/index\/i_thread_service.h>\n#include <vespa\/vespalib\/util\/lambdatask.h>\n#include <vespa\/vespalib\/util\/scheduledexecutor.h>\n#include <thread>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.maintenancecontroller\");\n\nusing document::BucketId;\nusing vespalib::Executor;\nusing vespalib::makeLambdaTask;\n\nnamespace proton {\n\nnamespace {\n\nclass JobWrapperTask : public Executor::Task\n{\nprivate:\n MaintenanceJobRunner *_job;\npublic:\n JobWrapperTask(MaintenanceJobRunner *job) : _job(job) {}\n void run() override { _job->run(); }\n};\n\n}\n\nMaintenanceController::MaintenanceController(IThreadService &masterThread,\n vespalib::Executor & defaultExecutor,\n const DocTypeName &docTypeName)\n : IBucketFreezeListener(),\n _masterThread(masterThread),\n _defaultExecutor(defaultExecutor),\n _readySubDB(),\n _remSubDB(),\n _notReadySubDB(),\n _periodicTimer(),\n _config(),\n _frozenBuckets(masterThread),\n _state(State::INITIALIZING),\n _docTypeName(docTypeName),\n _jobs(),\n _jobsLock()\n{\n _frozenBuckets.addListener(this); \/\/ forward freeze\/thaw to bmc\n}\n\nMaintenanceController::~MaintenanceController()\n{\n kill();\n _frozenBuckets.removeListener(this);\n}\n\nvoid\nMaintenanceController::registerJobInMasterThread(IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n registerJob(_masterThread, std::move(job));\n}\n\nvoid\nMaintenanceController::registerJobInDefaultPool(IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n registerJob(_defaultExecutor, std::move(job));\n}\n\nvoid\nMaintenanceController::registerJob(Executor & executor, IMaintenanceJob::UP job)\n{\n \/\/ Called by master write thread\n Guard guard(_jobsLock);\n _jobs.push_back(std::make_shared<MaintenanceJobRunner>(executor, std::move(job)));\n}\n\n\nvoid\nMaintenanceController::killJobs()\n{\n if (_state == State::STARTED) {\n _state = State::PAUSED;\n }\n \/\/ Called by master write thread\n assert(_masterThread.isCurrentThread());\n LOG(debug, \"killJobs(): threadId=%zu\", (size_t)FastOS_Thread::GetCurrentThreadId());\n _periodicTimer.reset();\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (auto &job : _jobs) {\n job->stop(); \/\/ Make sure no more tasks are added to the executor\n }\n for (auto &job : _jobs) {\n while (job->isRunning()) {\n std::this_thread::sleep_for(1ms);\n }\n }\n JobList tmpJobs = _jobs;\n {\n Guard guard(_jobsLock);\n _jobs.clear();\n }\n \/\/ Hold jobs until existing tasks have been drained\n _masterThread.execute(makeLambdaTask([this, jobs=std::move(tmpJobs)]() {\n performHoldJobs(std::move(jobs));\n }));\n}\n\nvoid\nMaintenanceController::updateMetrics(DocumentDBTaggedMetrics & metrics)\n{\n Guard guard(_jobsLock);\n for (auto &job : _jobs) {\n job->getJob().updateMetrics(metrics); \/\/ Make sure no more tasks are added to the executor\n }\n}\n\nvoid\nMaintenanceController::performHoldJobs(JobList jobs)\n{\n \/\/ Called by master write thread\n LOG(debug, \"performHoldJobs(): threadId=%zu\", (size_t)FastOS_Thread::GetCurrentThreadId());\n (void) jobs;\n}\n\nvoid\nMaintenanceController::stop()\n{\n assert(!_masterThread.isCurrentThread());\n _masterThread.execute(makeLambdaTask([this]() { _state = State::STOPPING; killJobs(); }));\n _masterThread.sync(); \/\/ Wait for killJobs()\n _masterThread.sync(); \/\/ Wait for already scheduled maintenance jobs and performHoldJobs\n}\n\nvoid\nMaintenanceController::kill()\n{\n stop();\n _readySubDB.clear();\n _remSubDB.clear();\n _notReadySubDB.clear();\n}\n\nvoid\nMaintenanceController::start(const DocumentDBMaintenanceConfig::SP &config)\n{\n \/\/ Called by master write thread\n assert(_state == State::INITIALIZING);\n _config = config;\n _state = State::STARTED;\n restart();\n}\n\n\nvoid\nMaintenanceController::restart()\n{\n \/\/ Called by master write thread\n if (!getStarted() || getStopping() || !_readySubDB.valid()) {\n return;\n }\n _periodicTimer = std::make_unique<vespalib::ScheduledExecutor>();\n\n addJobsToPeriodicTimer();\n}\n\nvoid\nMaintenanceController::addJobsToPeriodicTimer()\n{\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (const auto &jw : _jobs) {\n const IMaintenanceJob &job = jw->getJob();\n LOG(debug, \"addJobsToPeriodicTimer(): docType='%s', job.name='%s', job.delay=%f, job.interval=%f\",\n _docTypeName.getName().c_str(), job.getName().c_str(), vespalib::to_s(job.getDelay()), vespalib::to_s(job.getInterval()));\n if (job.getInterval() == vespalib::duration::zero()) {\n jw->run();\n continue;\n }\n _periodicTimer->scheduleAtFixedRate(std::make_unique<JobWrapperTask>(jw.get()),\n job.getDelay(), job.getInterval());\n }\n}\n\nvoid\nMaintenanceController::newConfig(const DocumentDBMaintenanceConfig::SP &config)\n{\n \/\/ Called by master write thread\n _config = config;\n restart();\n}\n\nnamespace {\n\nvoid\nassert_equal_meta_store_instances(const MaintenanceDocumentSubDB& old_db,\n const MaintenanceDocumentSubDB& new_db)\n{\n if (old_db.valid() && new_db.valid()) {\n assert(old_db.meta_store().get() == new_db.meta_store().get());\n }\n}\n\n}\n\nvoid\nMaintenanceController::syncSubDBs(const MaintenanceDocumentSubDB &readySubDB,\n const MaintenanceDocumentSubDB &remSubDB,\n const MaintenanceDocumentSubDB ¬ReadySubDB)\n{\n \/\/ Called by master write thread\n bool oldValid = _readySubDB.valid();\n assert(readySubDB.valid());\n assert(remSubDB.valid());\n \/\/ Document meta store instances should not change. Maintenance jobs depend on this fact.\n assert_equal_meta_store_instances(_readySubDB, readySubDB);\n assert_equal_meta_store_instances(_remSubDB, remSubDB);\n assert_equal_meta_store_instances(_notReadySubDB, notReadySubDB);\n _readySubDB = readySubDB;\n _remSubDB = remSubDB;\n _notReadySubDB = notReadySubDB;\n if (!oldValid && getStarted()) {\n restart();\n }\n}\n\n\nvoid\nMaintenanceController::notifyThawedBucket(const BucketId &bucket)\n{\n (void) bucket;\n \/\/ No need to take _jobsLock as modification of _jobs also happens in master write thread.\n for (const auto &jw : _jobs) {\n IBlockableMaintenanceJob *job = jw->getJob().asBlockable();\n if (job && job->isBlocked()) {\n job->unBlock(IBlockableMaintenanceJob::BlockedReason::FROZEN_BUCKET);\n }\n }\n}\n\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>#ifndef ORG_PQRS_TYPES_HPP\n#define ORG_PQRS_TYPES_HPP\n\n#include <IOKit\/IOLib.h>\n#include <IOKit\/IOTimerEventSource.h>\n#include \"bridge.h\"\n#include \"Vector.hpp\"\n\nnamespace org_pqrs_Karabiner {\nclass AddDataType final {\npublic:\n AddDataType(void) : value_(BRIDGE_DATATYPE_NONE) {}\n explicit AddDataType(unsigned int v) : value_(v) {}\n operator unsigned int(void) {\n return value_;\n }\n\nprivate:\n unsigned int value_;\n};\n\nclass AddValue final {\npublic:\n AddValue(void) : value_(0) {}\n explicit AddValue(unsigned int v) : value_(v) {}\n operator unsigned int(void) {\n return value_;\n }\n\nprivate:\n unsigned int value_;\n};\nDECLARE_VECTOR(AddValue);\n\nclass AddValueWithDataType final {\npublic:\n AddValueWithDataType(void) {}\n AddValueWithDataType(AddDataType d, AddValue v) : dataType(d), value(v) {}\n AddDataType dataType;\n AddValue value;\n};\nDECLARE_VECTOR(AddValueWithDataType);\n}\n\nclass AutogenId final {\npublic:\n explicit AutogenId(uint64_t v) : value_(v) {}\n operator uint64_t(void) {\n return value_;\n }\n bool operator>(AutogenId other) const { return value_ > other.value_; }\n bool operator>=(AutogenId other) const { return value_ >= other.value_; }\n bool operator<(AutogenId other) const { return value_ < other.value_; }\n bool operator<=(AutogenId other) const { return value_ <= other.value_; }\n\n static AutogenId maxValue(void) {\n \/\/ 1234567812345678\n return AutogenId(0xffffffffffffffff);\n }\n\nprivate:\n uint64_t value_;\n};\n\n#endif\n<commit_msg>add PhysicalEventType<commit_after>#ifndef ORG_PQRS_TYPES_HPP\n#define ORG_PQRS_TYPES_HPP\n\n#include <IOKit\/IOLib.h>\n#include <IOKit\/IOTimerEventSource.h>\n#include \"bridge.h\"\n#include \"Vector.hpp\"\n\nnamespace org_pqrs_Karabiner {\nclass AddDataType final {\npublic:\n AddDataType(void) : value_(BRIDGE_DATATYPE_NONE) {}\n explicit AddDataType(unsigned int v) : value_(v) {}\n operator unsigned int(void) {\n return value_;\n }\n\nprivate:\n unsigned int value_;\n};\n\nclass AddValue final {\npublic:\n AddValue(void) : value_(0) {}\n explicit AddValue(unsigned int v) : value_(v) {}\n operator unsigned int(void) {\n return value_;\n }\n\nprivate:\n unsigned int value_;\n};\nDECLARE_VECTOR(AddValue);\n\nclass AddValueWithDataType final {\npublic:\n AddValueWithDataType(void) {}\n AddValueWithDataType(AddDataType d, AddValue v) : dataType(d), value(v) {}\n AddDataType dataType;\n AddValue value;\n};\nDECLARE_VECTOR(AddValueWithDataType);\n}\n\nclass AutogenId final {\npublic:\n explicit AutogenId(uint64_t v) : value_(v) {}\n operator uint64_t(void) {\n return value_;\n }\n bool operator>(AutogenId other) const { return value_ > other.value_; }\n bool operator>=(AutogenId other) const { return value_ >= other.value_; }\n bool operator<(AutogenId other) const { return value_ < other.value_; }\n bool operator<=(AutogenId other) const { return value_ <= other.value_; }\n\n static AutogenId maxValue(void) {\n \/\/ 1234567812345678\n return AutogenId(0xffffffffffffffff);\n }\n\nprivate:\n uint64_t value_;\n};\n\nenum class PhysicalEventType {\n DOWN,\n UP,\n \/\/ We do not provide PhysicalEventType::MODIFY. Use DOWN or UP for modifier events.\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0. The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n\n#include \"folderlistmodel.h\"\n#include <QMailAccount>\n#include <QMailFolder>\n#include <QMailMessage>\n#include <QMailMessageKey>\n#include <QMailStore>\n#include <QDateTime>\n#include <QTimer>\n#include <QProcess>\n#include <qmailnamespace.h>\n#include <libedataserver\/e-account-list.h>\n#include <libedataserver\/e-list.h>\n#include <gconf\/gconf-client.h>\n\nFolderListModel::FolderListModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n QHash<int, QByteArray> roles;\n roles.insert(FolderName, \"folderName\");\n roles.insert(FolderId, \"folderId\");\n roles.insert(FolderUnreadCount, \"folderUnreadCount\");\n roles.insert(FolderServerCount, \"folderServerCount\");\n setRoleNames(roles);\n m_outbox_proxy = NULL;\n m_sent_proxy = NULL;\n m_drafts_proxy = NULL;\n}\n\nFolderListModel::~FolderListModel()\n{\n}\n\nint FolderListModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return m_folderlist.count();\n}\n\nQVariant FolderListModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid() || index.row() > m_folderlist.count())\n return QVariant();\n\n \n CamelFolderInfoVariant folder(m_folderlist[index.row()]);\n if (role == FolderName)\n {\n\tQString displayName;\n\n if (folder.full_name == \".#evolution\/Junk\")\n displayName = QString (\"Junk\");\n else if (folder.full_name == \".#evolution\/Trash\")\n displayName = QString (\"Trash\");\n else {\n displayName = QString (folder.full_name);\n displayName.replace (QString(\"\/\"), QString(\" \/ \"));\n }\n\n return QVariant(displayName);\n }\n else if (role == FolderId)\n {\n return QVariant(folder.uri);\n } \n else if (role == FolderUnreadCount)\n {\n return QVariant ((folder.unread_count == -1) ? 0 : folder.unread_count );\n }\n else if (role == FolderServerCount)\n {\n return QVariant ((folder.total_mail_count == -1) ? 0 : folder.total_mail_count);\n }\n\n return QVariant();\n}\n\nEAccount * FolderListModel::getAccountById(EAccountList *account_list, char *id)\n{\n EIterator *iter;\n EAccount *account = NULL;\n\n iter = e_list_get_iterator (E_LIST (account_list));\n while (e_iterator_is_valid (iter)) {\n account = (EAccount *) e_iterator_get (iter);\n if (strcmp (id, account->uid) == 0)\n return account;\n e_iterator_next (iter);\n }\n\n g_object_unref (iter);\n\n return NULL;\n}\n\nvoid FolderListModel::setAccountKey(QVariant id)\n{\n GConfClient *client;\n EAccountList *account_list;\n QString quid;\n const char *url;\n\n client = gconf_client_get_default ();\n account_list = e_account_list_new (client);\n g_object_unref (client);\n\n quid = id.value<QString>(); \n m_account = getAccountById (account_list, (char *)quid.toLocal8Bit().constData());\n url = e_account_get_string (m_account, E_ACCOUNT_SOURCE_URL);\n\n g_print (\"fetching store: %s\\n\", url);\n OrgGnomeEvolutionDataserverMailSessionInterface *instance = OrgGnomeEvolutionDataserverMailSessionInterface::instance(this);\n if (instance && instance->isValid()) {\n\tQDBusPendingReply<QDBusObjectPath> reply = instance->getStore (QString(url));\n reply.waitForFinished();\n m_store_proxy_id = reply.value();\n\tg_print (\"Store PATH: %s\\n\", (char *) m_store_proxy_id.path().toLocal8Bit().constData());\n m_store_proxy = new OrgGnomeEvolutionDataserverMailStoreInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\tm_store_proxy_id.path(),\n\t\t\t\t\t\t\t\t\tQDBusConnection::sessionBus(), this);\n\t\n\tif (m_store_proxy && m_store_proxy->isValid()) {\n\t\tQDBusPendingReply<CamelFolderInfoArrayVariant> reply = m_store_proxy->getFolderInfo (QString(\"\"), \n\t\t\t\t\t\t\t\t\tCAMEL_STORE_FOLDER_INFO_RECURSIVE|CAMEL_STORE_FOLDER_INFO_FAST | CAMEL_STORE_FOLDER_INFO_SUBSCRIBED);\n\t\treply.waitForFinished();\n\t\tm_folderlist = reply.value ();\t\n\tg_print (\"Got folder list....\\n\");\n\n\t}\n\t\n\tif (!m_outbox_proxy) {\n\t\treply = instance->getLocalFolder (QString(\"Outbox\"));\n\t\treply.waitForFinished();\n \tm_outbox_proxy_id = reply.value();\n\n\t\tm_outbox_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t\t m_outbox_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n\t}\n\t\n\treply = instance->getFolderFromUri (QString(m_account->sent_folder_uri));\n reply.waitForFinished();\n m_sent_proxy_id = reply.value();\n\tm_sent_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t m_sent_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n\n\treply = instance->getFolderFromUri (QString(m_account->drafts_folder_uri));\n reply.waitForFinished();\n m_drafts_proxy_id = reply.value();\n\tm_drafts_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t m_drafts_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n }\n}\n\nQStringList FolderListModel::folderNames()\n{\n QStringList folderNames;\n\n foreach (CamelFolderInfoVariant fInfo, m_folderlist)\n {\n QString displayName;\n\n\tif (fInfo.full_name == \".#evolution\/Junk\")\n\t\tdisplayName = QString (\"Junk\");\n\telse if (fInfo.full_name == \".#evolution\/Trash\")\n\t\tdisplayName = QString (\"Trash\");\n\telse {\n\t\tdisplayName = QString (fInfo.full_name);\n\t\tdisplayName.replace (QString(\"\/\"), QString(\" \/ \"));\n\t}\n\t\n if (fInfo.unread_count > 0)\n {\n displayName = displayName + \" (\" + QString::number(fInfo.unread_count) + \")\";\n }\n\t\n folderNames << displayName;\n\tg_print(\"FOLDER: %s\\n\", (char *)displayName.toLocal8Bit().constData());\n }\n return folderNames;\n}\n\nQVariant FolderListModel::folderId(int index)\n{\n if (index < 0 || index >= m_folderlist.count())\n return QVariant();\n \n return m_folderlist[index].uri;\n}\n\nint FolderListModel::indexFromFolderId(QVariant vFolderId)\n{ \n \n QString uri = vFolderId.toString();\n g_print (\"Entering FolderListModel::indexFromFolderId: %s\\n\", (char *)uri.toLocal8Bit().constData());\n for (int i = 0; i < m_folderlist.size(); i ++)\n {\n if (vFolderId == 0) {\n\t CamelFolderInfoVariant folder(m_folderlist[i]);\n \tif (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0)\n\t\t\treturn i;\n\n\t} else {\n \tif (uri == m_folderlist[i].uri)\n \t\treturn i;\n\t}\n }\n return -1;\n}\n\nQVariant FolderListModel::folderServerCount(QVariant vFolderId)\n{\n QString uri = vFolderId.toString();\n\n for (int i = 0; i < m_folderlist.size(); i ++)\n {\n if (uri == m_folderlist[i].uri)\n return QVariant(m_folderlist[i].total_mail_count);\n }\n return QVariant(-1);\n}\n\nQVariant FolderListModel::inboxFolderId()\n{\n for (int i = 0; i < m_folderlist.size(); i++)\n {\n CamelFolderInfoVariant folder(m_folderlist[i]);\n if (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0) {\n\t g_print (\"Returning INBOX URI: %s\\n\", (char *)folder.uri.toLocal8Bit().constData());\n return QVariant(folder.uri);\n\t}\n }\n\n return QVariant();\n}\n\nQVariant FolderListModel::inboxFolderName()\n{\n for (int i = 0; i < m_folderlist.size(); i++)\n {\n CamelFolderInfoVariant folder(m_folderlist[i]);\n\n if (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0) {\n g_print (\"Returning INBOX URI: %s\\n\", (char *)folder.uri.toLocal8Bit().constData());\n return QVariant(folder.folder_name);\n }\n }\n return QVariant(\"\");\n}\n\nint FolderListModel::totalNumberOfFolders()\n{\n return m_folderlist.size();\n}\n<commit_msg>Dont set the same account key again.<commit_after>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0. The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n\n#include \"folderlistmodel.h\"\n#include <QMailAccount>\n#include <QMailFolder>\n#include <QMailMessage>\n#include <QMailMessageKey>\n#include <QMailStore>\n#include <QDateTime>\n#include <QTimer>\n#include <QProcess>\n#include <qmailnamespace.h>\n#include <libedataserver\/e-account-list.h>\n#include <libedataserver\/e-list.h>\n#include <gconf\/gconf-client.h>\n\nFolderListModel::FolderListModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n QHash<int, QByteArray> roles;\n roles.insert(FolderName, \"folderName\");\n roles.insert(FolderId, \"folderId\");\n roles.insert(FolderUnreadCount, \"folderUnreadCount\");\n roles.insert(FolderServerCount, \"folderServerCount\");\n setRoleNames(roles);\n m_outbox_proxy = NULL;\n m_sent_proxy = NULL;\n m_drafts_proxy = NULL;\n}\n\nFolderListModel::~FolderListModel()\n{\n}\n\nint FolderListModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return m_folderlist.count();\n}\n\nQVariant FolderListModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid() || index.row() > m_folderlist.count())\n return QVariant();\n\n \n CamelFolderInfoVariant folder(m_folderlist[index.row()]);\n if (role == FolderName)\n {\n\tQString displayName;\n\n if (folder.full_name == \".#evolution\/Junk\")\n displayName = QString (\"Junk\");\n else if (folder.full_name == \".#evolution\/Trash\")\n displayName = QString (\"Trash\");\n else {\n displayName = QString (folder.full_name);\n displayName.replace (QString(\"\/\"), QString(\" \/ \"));\n }\n\n return QVariant(displayName);\n }\n else if (role == FolderId)\n {\n return QVariant(folder.uri);\n } \n else if (role == FolderUnreadCount)\n {\n return QVariant ((folder.unread_count == -1) ? 0 : folder.unread_count );\n }\n else if (role == FolderServerCount)\n {\n return QVariant ((folder.total_mail_count == -1) ? 0 : folder.total_mail_count);\n }\n\n return QVariant();\n}\n\nEAccount * FolderListModel::getAccountById(EAccountList *account_list, char *id)\n{\n EIterator *iter;\n EAccount *account = NULL;\n\n iter = e_list_get_iterator (E_LIST (account_list));\n while (e_iterator_is_valid (iter)) {\n account = (EAccount *) e_iterator_get (iter);\n if (strcmp (id, account->uid) == 0)\n return account;\n e_iterator_next (iter);\n }\n\n g_object_unref (iter);\n\n return NULL;\n}\n\nvoid FolderListModel::setAccountKey(QVariant id)\n{\n GConfClient *client;\n EAccountList *account_list;\n QString quid;\n const char *url;\n\n if (m_account && m_account->uid && strcmp (m_account->uid, (const char *)id.toString().toLocal8Bit().constData()) == 0) {\n\treturn;\n }\n\n client = gconf_client_get_default ();\n account_list = e_account_list_new (client);\n g_object_unref (client);\n\n quid = id.value<QString>(); \n m_account = getAccountById (account_list, (char *)quid.toLocal8Bit().constData());\n url = e_account_get_string (m_account, E_ACCOUNT_SOURCE_URL);\n\n g_print (\"fetching store: %s\\n\", url);\n OrgGnomeEvolutionDataserverMailSessionInterface *instance = OrgGnomeEvolutionDataserverMailSessionInterface::instance(this);\n if (instance && instance->isValid()) {\n\tQDBusPendingReply<QDBusObjectPath> reply = instance->getStore (QString(url));\n reply.waitForFinished();\n m_store_proxy_id = reply.value();\n\tg_print (\"Store PATH: %s\\n\", (char *) m_store_proxy_id.path().toLocal8Bit().constData());\n m_store_proxy = new OrgGnomeEvolutionDataserverMailStoreInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\tm_store_proxy_id.path(),\n\t\t\t\t\t\t\t\t\tQDBusConnection::sessionBus(), this);\n\t\n\tif (m_store_proxy && m_store_proxy->isValid()) {\n\t\tQDBusPendingReply<CamelFolderInfoArrayVariant> reply = m_store_proxy->getFolderInfo (QString(\"\"), \n\t\t\t\t\t\t\t\t\tCAMEL_STORE_FOLDER_INFO_RECURSIVE|CAMEL_STORE_FOLDER_INFO_FAST | CAMEL_STORE_FOLDER_INFO_SUBSCRIBED);\n\t\treply.waitForFinished();\n\t\tm_folderlist = reply.value ();\t\n\tg_print (\"Got folder list....\\n\");\n\n\t}\n\t\n\tif (!m_outbox_proxy) {\n\t\treply = instance->getLocalFolder (QString(\"Outbox\"));\n\t\treply.waitForFinished();\n \tm_outbox_proxy_id = reply.value();\n\n\t\tm_outbox_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t\t m_outbox_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n\t}\n\t\n\treply = instance->getFolderFromUri (QString(m_account->sent_folder_uri));\n reply.waitForFinished();\n m_sent_proxy_id = reply.value();\n\tm_sent_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t m_sent_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n\n\treply = instance->getFolderFromUri (QString(m_account->drafts_folder_uri));\n reply.waitForFinished();\n m_drafts_proxy_id = reply.value();\n\tm_drafts_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString (\"org.gnome.evolution.dataserver.Mail\"),\n\t\t\t\t\t\t\t\t\t m_drafts_proxy_id.path(),\n\t\t\t\t\t\t\t\t\t QDBusConnection::sessionBus(), this);\n }\n}\n\nQStringList FolderListModel::folderNames()\n{\n QStringList folderNames;\n\n foreach (CamelFolderInfoVariant fInfo, m_folderlist)\n {\n QString displayName;\n\n\tif (fInfo.full_name == \".#evolution\/Junk\")\n\t\tdisplayName = QString (\"Junk\");\n\telse if (fInfo.full_name == \".#evolution\/Trash\")\n\t\tdisplayName = QString (\"Trash\");\n\telse {\n\t\tdisplayName = QString (fInfo.full_name);\n\t\tdisplayName.replace (QString(\"\/\"), QString(\" \/ \"));\n\t}\n\t\n if (fInfo.unread_count > 0)\n {\n displayName = displayName + \" (\" + QString::number(fInfo.unread_count) + \")\";\n }\n\t\n folderNames << displayName;\n\tg_print(\"FOLDER: %s\\n\", (char *)displayName.toLocal8Bit().constData());\n }\n return folderNames;\n}\n\nQVariant FolderListModel::folderId(int index)\n{\n if (index < 0 || index >= m_folderlist.count())\n return QVariant();\n \n return m_folderlist[index].uri;\n}\n\nint FolderListModel::indexFromFolderId(QVariant vFolderId)\n{ \n \n QString uri = vFolderId.toString();\n g_print (\"Entering FolderListModel::indexFromFolderId: %s\\n\", (char *)uri.toLocal8Bit().constData());\n for (int i = 0; i < m_folderlist.size(); i ++)\n {\n if (vFolderId == 0) {\n\t CamelFolderInfoVariant folder(m_folderlist[i]);\n \tif (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0)\n\t\t\treturn i;\n\n\t} else {\n \tif (uri == m_folderlist[i].uri)\n \t\treturn i;\n\t}\n }\n return -1;\n}\n\nQVariant FolderListModel::folderServerCount(QVariant vFolderId)\n{\n QString uri = vFolderId.toString();\n\n for (int i = 0; i < m_folderlist.size(); i ++)\n {\n if (uri == m_folderlist[i].uri)\n return QVariant(m_folderlist[i].total_mail_count);\n }\n return QVariant(-1);\n}\n\nQVariant FolderListModel::inboxFolderId()\n{\n for (int i = 0; i < m_folderlist.size(); i++)\n {\n CamelFolderInfoVariant folder(m_folderlist[i]);\n if (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0) {\n\t g_print (\"Returning INBOX URI: %s\\n\", (char *)folder.uri.toLocal8Bit().constData());\n return QVariant(folder.uri);\n\t}\n }\n\n return QVariant();\n}\n\nQVariant FolderListModel::inboxFolderName()\n{\n for (int i = 0; i < m_folderlist.size(); i++)\n {\n CamelFolderInfoVariant folder(m_folderlist[i]);\n\n if (QString::compare(folder.full_name, \"INBOX\", Qt::CaseInsensitive) == 0) {\n g_print (\"Returning INBOX URI: %s\\n\", (char *)folder.uri.toLocal8Bit().constData());\n return QVariant(folder.folder_name);\n }\n }\n return QVariant(\"\");\n}\n\nint FolderListModel::totalNumberOfFolders()\n{\n return m_folderlist.size();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ SciTE - Scintilla based Text Editor\n\/** @file GUIGTK.cxx\n ** Interface to platform GUI facilities.\n ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.\n **\/\n\/\/ Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <time.h>\n\n#include <string>\n\n#include <gtk\/gtk.h>\n\n#include \"Scintilla.h\"\n#include \"ScintillaWidget.h\"\n\n#include \"GUI.h\"\n\nnamespace GUI {\n\ngui_string StringFromUTF8(const char *s) {\n\treturn gui_string(s);\n}\n\nstd::string UTF8FromString(const gui_string &s) {\n\treturn s;\n}\n\ngui_string StringFromInteger(int i) {\n\tchar number[32];\n\tsprintf(number, \"%0d\", i);\n\treturn gui_string(number);\n}\n\nstatic GtkWidget *PWidget(WindowID wid) {\n\treturn reinterpret_cast<GtkWidget *>(wid);\n}\n\nvoid Window::Destroy() {\n\tif (wid)\n\t\tgtk_widget_destroy(GTK_WIDGET(wid));\n\twid = 0;\n}\n\nbool Window::HasFocus() {\n\treturn GTK_WIDGET_HAS_FOCUS(wid);\n}\n\nRectangle Window::GetPosition() {\n\t\/\/ Before any size allocated pretend its 1000 wide so not scrolled\n\tRectangle rc(0, 0, 1000, 1000);\n\tif (wid) {\n\t\trc.left = PWidget(wid)->allocation.x;\n\t\trc.top = PWidget(wid)->allocation.y;\n\t\tif (PWidget(wid)->allocation.width > 20) {\n\t\t\trc.right = rc.left + PWidget(wid)->allocation.width;\n\t\t\trc.bottom = rc.top + PWidget(wid)->allocation.height;\n\t\t}\n\t}\n\treturn rc;\n}\n\nvoid Window::SetPosition(Rectangle rc) {\n\tGtkAllocation alloc;\n\talloc.x = rc.left;\n\talloc.y = rc.top;\n\talloc.width = rc.Width();\n\talloc.height = rc.Height();\n\tgtk_widget_size_allocate(PWidget(wid), &alloc);\n}\n\nRectangle Window::GetClientPosition() {\n\t\/\/ On GTK+, the client position is the window position\n\treturn GetPosition();\n}\n\nvoid Window::Show(bool show) {\n\tif (show)\n\t\tgtk_widget_show(PWidget(wid));\n}\n\nvoid Window::InvalidateAll() {\n\tif (wid) {\n\t\tgtk_widget_queue_draw(PWidget(wid));\n\t}\n}\n\nvoid Window::SetTitle(const char *s) {\n\tgtk_window_set_title(GTK_WINDOW(wid), s);\n}\n\nvoid Menu::CreatePopUp() {\n\tDestroy();\n\tmid = gtk_item_factory_new(GTK_TYPE_MENU, \"<main>\", NULL);\n}\n\nvoid Menu::Destroy() {\n\tif (mid)\n\t\tg_object_unref(G_OBJECT(mid));\n\tmid = 0;\n}\n\nvoid Menu::Show(Point pt, Window &) {\n\tint screenHeight = gdk_screen_height();\n\tint screenWidth = gdk_screen_width();\n\tGtkItemFactory *factory = reinterpret_cast<GtkItemFactory *>(mid);\n\tGtkWidget *widget = gtk_item_factory_get_widget(factory, \"<main>\");\n\tgtk_widget_show_all(widget);\n\tGtkRequisition requisition;\n\tgtk_widget_size_request(widget, &requisition);\n\tif ((pt.x + requisition.width) > screenWidth) {\n\t\tpt.x = screenWidth - requisition.width;\n\t}\n\tif ((pt.y + requisition.height) > screenHeight) {\n\t\tpt.y = screenHeight - requisition.height;\n\t}\n\tgtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3,\n\t\tgtk_get_current_event_time());\n}\n\nElapsedTime::ElapsedTime() {\n\tGTimeVal curTime;\n\tg_get_current_time(&curTime);\n\tbigBit = curTime.tv_sec;\n\tlittleBit = curTime.tv_usec;\n}\n\ndouble ElapsedTime::Duration(bool reset) {\n\tGTimeVal curTime;\n\tg_get_current_time(&curTime);\n\tlong endBigBit = curTime.tv_sec;\n\tlong endLittleBit = curTime.tv_usec;\n\tdouble result = 1000000.0 * (endBigBit - bigBit);\n\tresult += endLittleBit - littleBit;\n\tresult \/= 1000000.0;\n\tif (reset) {\n\t\tbigBit = endBigBit;\n\t\tlittleBit = endLittleBit;\n\t}\n\treturn result;\n}\n\nlong ScintillaWindow::Send(unsigned int msg, unsigned long wParam, long lParam) {\n\treturn scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam);\n}\n\nlong ScintillaWindow::SendPointer(unsigned int msg, unsigned long wParam, void *lParam) {\n\treturn scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam));\n}\n\nbool IsDBCSLeadByte(int codePage, char ch) {\n\t\/\/ Byte ranges found in Wikipedia articles with relevant search strings in each case\n\tunsigned char uch = static_cast<unsigned char>(ch);\n\tswitch (codePage) {\n\t\tcase 932:\n\t\t\t\/\/ Shift_jis\n\t\t\treturn ((uch >= 0x81) && (uch <= 0x9F)) ||\n\t\t\t\t((uch >= 0xE0) && (uch <= 0xEF));\n\t\tcase 936:\n\t\t\t\/\/ GBK\n\t\t\treturn (uch >= 0x81) && (uch <= 0xFE);\n\t\tcase 950:\n\t\t\t\/\/ Big5\n\t\t\treturn (uch >= 0x81) && (uch <= 0xFE);\n\t\t\/\/ Korean EUC-KR may be code page 949.\n\t}\n\treturn false;\n}\n\n}\n<commit_msg>Fixed crash when creating a GUI::gui_string from NULL.<commit_after>\/\/ SciTE - Scintilla based Text Editor\n\/** @file GUIGTK.cxx\n ** Interface to platform GUI facilities.\n ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.\n **\/\n\/\/ Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <time.h>\n\n#include <string>\n\n#include <gtk\/gtk.h>\n\n#include \"Scintilla.h\"\n#include \"ScintillaWidget.h\"\n\n#include \"GUI.h\"\n\nnamespace GUI {\n\ngui_string StringFromUTF8(const char *s) {\n\tif (s)\n\t\treturn gui_string(s);\n\telse\n\t\treturn gui_string(\"\");\n}\n\nstd::string UTF8FromString(const gui_string &s) {\n\treturn s;\n}\n\ngui_string StringFromInteger(int i) {\n\tchar number[32];\n\tsprintf(number, \"%0d\", i);\n\treturn gui_string(number);\n}\n\nstatic GtkWidget *PWidget(WindowID wid) {\n\treturn reinterpret_cast<GtkWidget *>(wid);\n}\n\nvoid Window::Destroy() {\n\tif (wid)\n\t\tgtk_widget_destroy(GTK_WIDGET(wid));\n\twid = 0;\n}\n\nbool Window::HasFocus() {\n\treturn GTK_WIDGET_HAS_FOCUS(wid);\n}\n\nRectangle Window::GetPosition() {\n\t\/\/ Before any size allocated pretend its 1000 wide so not scrolled\n\tRectangle rc(0, 0, 1000, 1000);\n\tif (wid) {\n\t\trc.left = PWidget(wid)->allocation.x;\n\t\trc.top = PWidget(wid)->allocation.y;\n\t\tif (PWidget(wid)->allocation.width > 20) {\n\t\t\trc.right = rc.left + PWidget(wid)->allocation.width;\n\t\t\trc.bottom = rc.top + PWidget(wid)->allocation.height;\n\t\t}\n\t}\n\treturn rc;\n}\n\nvoid Window::SetPosition(Rectangle rc) {\n\tGtkAllocation alloc;\n\talloc.x = rc.left;\n\talloc.y = rc.top;\n\talloc.width = rc.Width();\n\talloc.height = rc.Height();\n\tgtk_widget_size_allocate(PWidget(wid), &alloc);\n}\n\nRectangle Window::GetClientPosition() {\n\t\/\/ On GTK+, the client position is the window position\n\treturn GetPosition();\n}\n\nvoid Window::Show(bool show) {\n\tif (show)\n\t\tgtk_widget_show(PWidget(wid));\n}\n\nvoid Window::InvalidateAll() {\n\tif (wid) {\n\t\tgtk_widget_queue_draw(PWidget(wid));\n\t}\n}\n\nvoid Window::SetTitle(const char *s) {\n\tgtk_window_set_title(GTK_WINDOW(wid), s);\n}\n\nvoid Menu::CreatePopUp() {\n\tDestroy();\n\tmid = gtk_item_factory_new(GTK_TYPE_MENU, \"<main>\", NULL);\n}\n\nvoid Menu::Destroy() {\n\tif (mid)\n\t\tg_object_unref(G_OBJECT(mid));\n\tmid = 0;\n}\n\nvoid Menu::Show(Point pt, Window &) {\n\tint screenHeight = gdk_screen_height();\n\tint screenWidth = gdk_screen_width();\n\tGtkItemFactory *factory = reinterpret_cast<GtkItemFactory *>(mid);\n\tGtkWidget *widget = gtk_item_factory_get_widget(factory, \"<main>\");\n\tgtk_widget_show_all(widget);\n\tGtkRequisition requisition;\n\tgtk_widget_size_request(widget, &requisition);\n\tif ((pt.x + requisition.width) > screenWidth) {\n\t\tpt.x = screenWidth - requisition.width;\n\t}\n\tif ((pt.y + requisition.height) > screenHeight) {\n\t\tpt.y = screenHeight - requisition.height;\n\t}\n\tgtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3,\n\t\tgtk_get_current_event_time());\n}\n\nElapsedTime::ElapsedTime() {\n\tGTimeVal curTime;\n\tg_get_current_time(&curTime);\n\tbigBit = curTime.tv_sec;\n\tlittleBit = curTime.tv_usec;\n}\n\ndouble ElapsedTime::Duration(bool reset) {\n\tGTimeVal curTime;\n\tg_get_current_time(&curTime);\n\tlong endBigBit = curTime.tv_sec;\n\tlong endLittleBit = curTime.tv_usec;\n\tdouble result = 1000000.0 * (endBigBit - bigBit);\n\tresult += endLittleBit - littleBit;\n\tresult \/= 1000000.0;\n\tif (reset) {\n\t\tbigBit = endBigBit;\n\t\tlittleBit = endLittleBit;\n\t}\n\treturn result;\n}\n\nlong ScintillaWindow::Send(unsigned int msg, unsigned long wParam, long lParam) {\n\treturn scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam);\n}\n\nlong ScintillaWindow::SendPointer(unsigned int msg, unsigned long wParam, void *lParam) {\n\treturn scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam));\n}\n\nbool IsDBCSLeadByte(int codePage, char ch) {\n\t\/\/ Byte ranges found in Wikipedia articles with relevant search strings in each case\n\tunsigned char uch = static_cast<unsigned char>(ch);\n\tswitch (codePage) {\n\t\tcase 932:\n\t\t\t\/\/ Shift_jis\n\t\t\treturn ((uch >= 0x81) && (uch <= 0x9F)) ||\n\t\t\t\t((uch >= 0xE0) && (uch <= 0xEF));\n\t\tcase 936:\n\t\t\t\/\/ GBK\n\t\t\treturn (uch >= 0x81) && (uch <= 0xFE);\n\t\tcase 950:\n\t\t\t\/\/ Big5\n\t\t\treturn (uch >= 0x81) && (uch <= 0xFE);\n\t\t\/\/ Korean EUC-KR may be code page 949.\n\t}\n\treturn false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ViewShellImplementation.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 14:04:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \"ViewShellImplementation.hxx\"\n\n#include \"sdpage.hxx\"\n#include \"drawdoc.hxx\"\n#include \"sdresid.hxx\"\n#include \"glob.hrc\"\n#include \"app.hrc\"\n#include \"new_foil.hrc\"\n#include \"strings.hrc\"\n#include \"strings.hrc\"\n#include \"helpids.h\"\n#include \"sdattr.hxx\"\n#include \"sdabstdlg.hxx\"\n#include \"unmodpg.hxx\"\n#include \"Window.hxx\"\n#include \"optsitem.hxx\"\n#include \"DrawDocShell.hxx\"\n#include \"FactoryIds.hxx\"\n#include \"slideshow.hxx\"\n#include \"TaskPaneViewShell.hxx\"\n#include \"ViewShellBase.hxx\"\n\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/request.hxx>\n#include <svtools\/aeitem.hxx>\n#include <vcl\/msgbox.hxx>\n#include <basic\/sbstar.hxx>\n\n\nnamespace {\nclass ImpUndoDeleteWarning : public ModalDialog\n{\nprivate:\n FixedImage maImage;\n FixedText maWarningFT;\n CheckBox maDisableCB;\n OKButton maYesBtn;\n CancelButton maNoBtn;\n\npublic:\n ImpUndoDeleteWarning(Window* pParent);\n BOOL IsWarningDisabled() const { return maDisableCB.IsChecked(); }\n};\n\nImpUndoDeleteWarning::ImpUndoDeleteWarning(Window* pParent)\n: ModalDialog(pParent, SdResId(RID_UNDO_DELETE_WARNING)),\n maImage(this, SdResId(IMG_UNDO_DELETE_WARNING)),\n maWarningFT(this, SdResId(FT_UNDO_DELETE_WARNING)),\n maDisableCB(this, SdResId(CB_UNDO_DELETE_DISABLE)),\n maYesBtn(this, SdResId(BTN_UNDO_DELETE_YES)),\n maNoBtn(this, SdResId(BTN_UNDO_DELETE_NO))\n{\n FreeResource();\n\n SetHelpId( HID_SD_UNDODELETEWARNING_DLG );\n maDisableCB.SetHelpId( HID_SD_UNDODELETEWARNING_CBX );\n\n maYesBtn.SetText(Button::GetStandardText(BUTTON_YES));\n maNoBtn.SetText(Button::GetStandardText(BUTTON_NO));\n maImage.SetImage(WarningBox::GetStandardImage());\n\n \/\/ #93721# Set focus to YES-Button\n maYesBtn.GrabFocus();\n}\n\n} \/\/ end of anonymous namespace\n\n\n\n\nnamespace sd {\n\nViewShell::Implementation::Implementation (ViewShell& rViewShell)\n : mbIsShowingUIControls(false),\n mbIsMainViewShell(false),\n mrViewShell (rViewShell),\n mbIsInitialized(false)\n{\n}\n\n\n\n\nViewShell::Implementation::~Implementation (void)\n{\n}\n\n\n\n\nvoid ViewShell::Implementation::ProcessModifyPageSlot (\n SfxRequest& rRequest,\n SdPage* pCurrentPage,\n PageKind ePageKind)\n{\n SdDrawDocument* pDocument = mrViewShell.GetDoc();\n SdrLayerAdmin& rLayerAdmin = pDocument->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n SetOfByte aVisibleLayers;\n BOOL bHandoutMode = FALSE;\n SdPage* pHandoutMPage = NULL;\n String aNewName;\n\n \/\/ #95981#\n String aOldName;\n\n AutoLayout aNewAutoLayout;\n\n \/\/ #95981#\n AutoLayout aOldAutoLayout;\n\n BOOL bBVisible;\n BOOL bBObjsVisible;\n const SfxItemSet* pArgs = rRequest.GetArgs();\n\n if (pCurrentPage->TRG_HasMasterPage())\n aVisibleLayers = pCurrentPage->TRG_GetMasterPageVisibleLayers();\n else\n aVisibleLayers.SetAll();\n\n do\n {\n if (!pArgs || pArgs->Count() == 1 || pArgs->Count() == 2 )\n {\n if (pArgs && pArgs->Count() == 2)\n {\n \/\/ We have been called with a request that contains two\n \/\/ arguments. One was used as preselected layout in a\n \/\/ dialog. We could select that layout in the\n \/\/ layout panel instead.\n \/*\n SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);\n eNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue\n ();\n *\/\n }\n\n \/\/ Make the layout menu visible in the tool pane.\n SfxBoolItem aMakeToolPaneVisible (ID_VAL_ISVISIBLE, TRUE);\n SfxUInt32Item aPanelId (ID_VAL_PANEL_INDEX,\n ::sd::toolpanel::TaskPaneViewShell::PID_LAYOUT);\n mrViewShell.GetDispatcher()->Execute (\n SID_TASK_PANE,\n SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aMakeToolPaneVisible,\n &aPanelId,\n NULL);\n\n \/\/ We have activated a non-modal control in the task pane.\n \/\/ Because it does not return anything we can not do anything\n \/\/ more right now and have to exit here.\n break;\n }\n else if (pArgs->Count() == 4)\n {\n SFX_REQUEST_ARG (rRequest, pNewName, SfxStringItem, ID_VAL_PAGENAME, FALSE);\n SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);\n SFX_REQUEST_ARG (rRequest, pBVisible, SfxBoolItem, ID_VAL_ISPAGEBACK, FALSE);\n SFX_REQUEST_ARG (rRequest, pBObjsVisible, SfxBoolItem, ID_VAL_ISPAGEOBJ, FALSE);\n AutoLayout aLayout ((AutoLayout)pNewAutoLayout->GetValue ());\n if (aLayout >= AUTOLAYOUT__START\n && aLayout < AUTOLAYOUT__END)\n {\n aNewName = pNewName->GetValue ();\n aNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue ();\n bBVisible = pBVisible->GetValue ();\n bBObjsVisible = pBObjsVisible->GetValue ();\n }\n else\n {\n StarBASIC::FatalError (SbERR_BAD_PROP_VALUE);\n rRequest.Ignore ();\n break;\n }\n if (ePageKind == PK_HANDOUT)\n {\n bHandoutMode = TRUE;\n pHandoutMPage = pDocument->GetMasterSdPage(0, PK_HANDOUT);\n }\n }\n else\n {\n StarBASIC::FatalError (SbERR_WRONG_ARGS);\n rRequest.Ignore ();\n break;\n }\n\n SdPage* pUndoPage =\n bHandoutMode ? pHandoutMPage : pCurrentPage;\n\n \/\/ #67720#\n SfxUndoManager* pUndoManager = mrViewShell.GetDocSh()->GetUndoManager();\n DBG_ASSERT(pUndoManager, \"No UNDO MANAGER ?!?\");\n\n \/\/ #90356#\n sal_uInt16 nActionCount(pUndoManager->GetUndoActionCount());\n sal_Bool bContinue(sal_True);\n\n if(nActionCount)\n {\n \/\/ #90356# get SdOptions\n SdOptions* pOptions = SD_MOD()->GetSdOptions(pDocument->GetDocumentType());\n \/\/ sal_Bool bShowDialog(pOptions->IsShowUndoDeleteWarning());\n sal_Bool bShowDialog(sal_False);\n\n \/\/ #95981# If only name is changed do not show\n \/\/ ImpUndoDeleteWarning dialog\n if(bShowDialog)\n {\n sal_Bool bNameChanged(aNewName != aOldName);\n sal_Bool bLayoutChanged(aNewAutoLayout != aOldAutoLayout);\n\n if(bNameChanged && !bLayoutChanged)\n bShowDialog = sal_False;\n }\n\n if(bShowDialog)\n {\n \/\/ ask user if he wants to loose UNDO stack\n ImpUndoDeleteWarning aUndoDeleteDlg(mrViewShell.GetActiveWindow());\n\n if(BUTTONID_OK == aUndoDeleteDlg.Execute())\n {\n pUndoManager->Clear();\n }\n else\n {\n bContinue = sal_False;\n }\n\n \/\/ #90356# write option flag back if change was done\n if(aUndoDeleteDlg.IsWarningDisabled())\n {\n pOptions->SetShowUndoDeleteWarning(FALSE);\n }\n }\n }\n\n if(bContinue)\n {\n ModifyPageUndoAction* pAction = new ModifyPageUndoAction(\n pUndoManager, pDocument, pUndoPage, aNewName, aNewAutoLayout, bBVisible, bBObjsVisible);\n pUndoManager->AddUndoAction(pAction);\n\n \/\/ Clear the selection because the selectec object may be removed as\n \/\/ a result of the ssignment of the layout.\n mrViewShell.GetDrawView()->UnmarkAll();\n\n if (!bHandoutMode)\n {\n if (pCurrentPage->GetName() != aNewName)\n {\n pCurrentPage->SetName(aNewName);\n\n if (ePageKind == PK_STANDARD)\n {\n USHORT nPage = (pCurrentPage->GetPageNum()-1) \/ 2;\n SdPage* pNotesPage = pDocument->GetSdPage(nPage, PK_NOTES);\n if (pNotesPage != NULL)\n pNotesPage->SetName(aNewName);\n }\n }\n\n pCurrentPage->SetAutoLayout(aNewAutoLayout, TRUE);\n\n aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n aVisibleLayers.Set(aBckgrnd, bBVisible);\n aVisibleLayers.Set(aBckgrndObj, bBObjsVisible);\n pCurrentPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);\n }\n else\n {\n pHandoutMPage->SetAutoLayout(aNewAutoLayout, TRUE);\n }\n \/\/ The list of presentation objects at the page\n \/\/ has been cleared by SetAutolayout(). We still\n \/\/ have to clear the list of removed presentation\n \/\/ objects held by the model which references the\n \/\/ former list.\n pDocument->ClearDeletedPresObjList();\n\n mrViewShell.GetViewFrame()->GetDispatcher()->Execute(SID_SWITCHPAGE,\n SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);\n\n BOOL bSetModified = TRUE;\n\n if (pArgs && pArgs->Count() == 1)\n {\n bSetModified = (BOOL) ((SfxBoolItem&) pArgs->Get(SID_MODIFYPAGE)).GetValue();\n }\n\n pDocument->SetChanged(bSetModified);\n }\n }\n while (false);\n\n mrViewShell.Cancel();\n rRequest.Done ();\n}\n\n\n\n\nvoid ViewShell::Implementation::AssignLayout (\n SdPage* pPage,\n AutoLayout aLayout)\n{\n \/\/ Transform the given request into the four argument form that is\n \/\/ understood by ProcessModifyPageSlot().\n SdrLayerAdmin& rLayerAdmin (mrViewShell.GetViewShellBase().GetDocument()->GetLayerAdmin());\n BYTE aBackground (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE));\n BYTE aBackgroundObject (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE));\n SetOfByte aVisibleLayers (pPage->TRG_GetMasterPageVisibleLayers());\n SfxRequest aRequest (mrViewShell.GetViewShellBase().GetViewFrame(), SID_MODIFYPAGE);\n aRequest.AppendItem(SfxStringItem (ID_VAL_PAGENAME, pPage->GetName()));\n aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));\n aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEBACK, aVisibleLayers.IsSet(aBackground)));\n aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEOBJ, aVisibleLayers.IsSet(aBackgroundObject)));\n\n \/\/ Forward the call with the new arguments.\n ProcessModifyPageSlot (\n aRequest,\n pPage,\n pPage->GetPageKind());\n}\n\n\n\n\nsal_uInt16 ViewShell::Implementation::GetViewId (void)\n{\n switch (mrViewShell.GetShellType())\n {\n case ViewShell::ST_IMPRESS:\n case ViewShell::ST_NOTES:\n case ViewShell::ST_HANDOUT:\n return IMPRESS_FACTORY_ID;\n\n case ViewShell::ST_DRAW:\n return DRAW_FACTORY_ID;\n\n case ViewShell::ST_OUTLINE:\n return OUTLINE_FACTORY_ID;\n\n case ViewShell::ST_SLIDE:\n case ViewShell::ST_SLIDE_SORTER:\n return SLIDE_SORTER_FACTORY_ID;\n\n case ViewShell::ST_PRESENTATION:\n return PRESENTATION_FACTORY_ID;\n\n \/\/ Since we have to return a view id for every possible shell type\n \/\/ and there is not (yet) a proper ViewShellBase sub class for the\n \/\/ remaining types we chose the Impress factory as a fall back.\n case ViewShell::ST_TASK_PANE:\n case ViewShell::ST_NONE:\n default:\n return IMPRESS_FACTORY_ID;\n }\n}\n\n\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS ooo19126 (1.14.154); FILE MERGED 2005\/09\/05 13:25:31 rt 1.14.154.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ViewShellImplementation.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 07:04:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"ViewShellImplementation.hxx\"\n\n#include \"sdpage.hxx\"\n#include \"drawdoc.hxx\"\n#include \"sdresid.hxx\"\n#include \"glob.hrc\"\n#include \"app.hrc\"\n#include \"new_foil.hrc\"\n#include \"strings.hrc\"\n#include \"strings.hrc\"\n#include \"helpids.h\"\n#include \"sdattr.hxx\"\n#include \"sdabstdlg.hxx\"\n#include \"unmodpg.hxx\"\n#include \"Window.hxx\"\n#include \"optsitem.hxx\"\n#include \"DrawDocShell.hxx\"\n#include \"FactoryIds.hxx\"\n#include \"slideshow.hxx\"\n#include \"TaskPaneViewShell.hxx\"\n#include \"ViewShellBase.hxx\"\n\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/request.hxx>\n#include <svtools\/aeitem.hxx>\n#include <vcl\/msgbox.hxx>\n#include <basic\/sbstar.hxx>\n\n\nnamespace {\nclass ImpUndoDeleteWarning : public ModalDialog\n{\nprivate:\n FixedImage maImage;\n FixedText maWarningFT;\n CheckBox maDisableCB;\n OKButton maYesBtn;\n CancelButton maNoBtn;\n\npublic:\n ImpUndoDeleteWarning(Window* pParent);\n BOOL IsWarningDisabled() const { return maDisableCB.IsChecked(); }\n};\n\nImpUndoDeleteWarning::ImpUndoDeleteWarning(Window* pParent)\n: ModalDialog(pParent, SdResId(RID_UNDO_DELETE_WARNING)),\n maImage(this, SdResId(IMG_UNDO_DELETE_WARNING)),\n maWarningFT(this, SdResId(FT_UNDO_DELETE_WARNING)),\n maDisableCB(this, SdResId(CB_UNDO_DELETE_DISABLE)),\n maYesBtn(this, SdResId(BTN_UNDO_DELETE_YES)),\n maNoBtn(this, SdResId(BTN_UNDO_DELETE_NO))\n{\n FreeResource();\n\n SetHelpId( HID_SD_UNDODELETEWARNING_DLG );\n maDisableCB.SetHelpId( HID_SD_UNDODELETEWARNING_CBX );\n\n maYesBtn.SetText(Button::GetStandardText(BUTTON_YES));\n maNoBtn.SetText(Button::GetStandardText(BUTTON_NO));\n maImage.SetImage(WarningBox::GetStandardImage());\n\n \/\/ #93721# Set focus to YES-Button\n maYesBtn.GrabFocus();\n}\n\n} \/\/ end of anonymous namespace\n\n\n\n\nnamespace sd {\n\nViewShell::Implementation::Implementation (ViewShell& rViewShell)\n : mbIsShowingUIControls(false),\n mbIsMainViewShell(false),\n mrViewShell (rViewShell),\n mbIsInitialized(false)\n{\n}\n\n\n\n\nViewShell::Implementation::~Implementation (void)\n{\n}\n\n\n\n\nvoid ViewShell::Implementation::ProcessModifyPageSlot (\n SfxRequest& rRequest,\n SdPage* pCurrentPage,\n PageKind ePageKind)\n{\n SdDrawDocument* pDocument = mrViewShell.GetDoc();\n SdrLayerAdmin& rLayerAdmin = pDocument->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n SetOfByte aVisibleLayers;\n BOOL bHandoutMode = FALSE;\n SdPage* pHandoutMPage = NULL;\n String aNewName;\n\n \/\/ #95981#\n String aOldName;\n\n AutoLayout aNewAutoLayout;\n\n \/\/ #95981#\n AutoLayout aOldAutoLayout;\n\n BOOL bBVisible;\n BOOL bBObjsVisible;\n const SfxItemSet* pArgs = rRequest.GetArgs();\n\n if (pCurrentPage->TRG_HasMasterPage())\n aVisibleLayers = pCurrentPage->TRG_GetMasterPageVisibleLayers();\n else\n aVisibleLayers.SetAll();\n\n do\n {\n if (!pArgs || pArgs->Count() == 1 || pArgs->Count() == 2 )\n {\n if (pArgs && pArgs->Count() == 2)\n {\n \/\/ We have been called with a request that contains two\n \/\/ arguments. One was used as preselected layout in a\n \/\/ dialog. We could select that layout in the\n \/\/ layout panel instead.\n \/*\n SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);\n eNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue\n ();\n *\/\n }\n\n \/\/ Make the layout menu visible in the tool pane.\n SfxBoolItem aMakeToolPaneVisible (ID_VAL_ISVISIBLE, TRUE);\n SfxUInt32Item aPanelId (ID_VAL_PANEL_INDEX,\n ::sd::toolpanel::TaskPaneViewShell::PID_LAYOUT);\n mrViewShell.GetDispatcher()->Execute (\n SID_TASK_PANE,\n SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,\n &aMakeToolPaneVisible,\n &aPanelId,\n NULL);\n\n \/\/ We have activated a non-modal control in the task pane.\n \/\/ Because it does not return anything we can not do anything\n \/\/ more right now and have to exit here.\n break;\n }\n else if (pArgs->Count() == 4)\n {\n SFX_REQUEST_ARG (rRequest, pNewName, SfxStringItem, ID_VAL_PAGENAME, FALSE);\n SFX_REQUEST_ARG (rRequest, pNewAutoLayout, SfxUInt32Item, ID_VAL_WHATLAYOUT, FALSE);\n SFX_REQUEST_ARG (rRequest, pBVisible, SfxBoolItem, ID_VAL_ISPAGEBACK, FALSE);\n SFX_REQUEST_ARG (rRequest, pBObjsVisible, SfxBoolItem, ID_VAL_ISPAGEOBJ, FALSE);\n AutoLayout aLayout ((AutoLayout)pNewAutoLayout->GetValue ());\n if (aLayout >= AUTOLAYOUT__START\n && aLayout < AUTOLAYOUT__END)\n {\n aNewName = pNewName->GetValue ();\n aNewAutoLayout = (AutoLayout) pNewAutoLayout->GetValue ();\n bBVisible = pBVisible->GetValue ();\n bBObjsVisible = pBObjsVisible->GetValue ();\n }\n else\n {\n StarBASIC::FatalError (SbERR_BAD_PROP_VALUE);\n rRequest.Ignore ();\n break;\n }\n if (ePageKind == PK_HANDOUT)\n {\n bHandoutMode = TRUE;\n pHandoutMPage = pDocument->GetMasterSdPage(0, PK_HANDOUT);\n }\n }\n else\n {\n StarBASIC::FatalError (SbERR_WRONG_ARGS);\n rRequest.Ignore ();\n break;\n }\n\n SdPage* pUndoPage =\n bHandoutMode ? pHandoutMPage : pCurrentPage;\n\n \/\/ #67720#\n SfxUndoManager* pUndoManager = mrViewShell.GetDocSh()->GetUndoManager();\n DBG_ASSERT(pUndoManager, \"No UNDO MANAGER ?!?\");\n\n \/\/ #90356#\n sal_uInt16 nActionCount(pUndoManager->GetUndoActionCount());\n sal_Bool bContinue(sal_True);\n\n if(nActionCount)\n {\n \/\/ #90356# get SdOptions\n SdOptions* pOptions = SD_MOD()->GetSdOptions(pDocument->GetDocumentType());\n \/\/ sal_Bool bShowDialog(pOptions->IsShowUndoDeleteWarning());\n sal_Bool bShowDialog(sal_False);\n\n \/\/ #95981# If only name is changed do not show\n \/\/ ImpUndoDeleteWarning dialog\n if(bShowDialog)\n {\n sal_Bool bNameChanged(aNewName != aOldName);\n sal_Bool bLayoutChanged(aNewAutoLayout != aOldAutoLayout);\n\n if(bNameChanged && !bLayoutChanged)\n bShowDialog = sal_False;\n }\n\n if(bShowDialog)\n {\n \/\/ ask user if he wants to loose UNDO stack\n ImpUndoDeleteWarning aUndoDeleteDlg(mrViewShell.GetActiveWindow());\n\n if(BUTTONID_OK == aUndoDeleteDlg.Execute())\n {\n pUndoManager->Clear();\n }\n else\n {\n bContinue = sal_False;\n }\n\n \/\/ #90356# write option flag back if change was done\n if(aUndoDeleteDlg.IsWarningDisabled())\n {\n pOptions->SetShowUndoDeleteWarning(FALSE);\n }\n }\n }\n\n if(bContinue)\n {\n ModifyPageUndoAction* pAction = new ModifyPageUndoAction(\n pUndoManager, pDocument, pUndoPage, aNewName, aNewAutoLayout, bBVisible, bBObjsVisible);\n pUndoManager->AddUndoAction(pAction);\n\n \/\/ Clear the selection because the selectec object may be removed as\n \/\/ a result of the ssignment of the layout.\n mrViewShell.GetDrawView()->UnmarkAll();\n\n if (!bHandoutMode)\n {\n if (pCurrentPage->GetName() != aNewName)\n {\n pCurrentPage->SetName(aNewName);\n\n if (ePageKind == PK_STANDARD)\n {\n USHORT nPage = (pCurrentPage->GetPageNum()-1) \/ 2;\n SdPage* pNotesPage = pDocument->GetSdPage(nPage, PK_NOTES);\n if (pNotesPage != NULL)\n pNotesPage->SetName(aNewName);\n }\n }\n\n pCurrentPage->SetAutoLayout(aNewAutoLayout, TRUE);\n\n aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n aVisibleLayers.Set(aBckgrnd, bBVisible);\n aVisibleLayers.Set(aBckgrndObj, bBObjsVisible);\n pCurrentPage->TRG_SetMasterPageVisibleLayers(aVisibleLayers);\n }\n else\n {\n pHandoutMPage->SetAutoLayout(aNewAutoLayout, TRUE);\n }\n \/\/ The list of presentation objects at the page\n \/\/ has been cleared by SetAutolayout(). We still\n \/\/ have to clear the list of removed presentation\n \/\/ objects held by the model which references the\n \/\/ former list.\n pDocument->ClearDeletedPresObjList();\n\n mrViewShell.GetViewFrame()->GetDispatcher()->Execute(SID_SWITCHPAGE,\n SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);\n\n BOOL bSetModified = TRUE;\n\n if (pArgs && pArgs->Count() == 1)\n {\n bSetModified = (BOOL) ((SfxBoolItem&) pArgs->Get(SID_MODIFYPAGE)).GetValue();\n }\n\n pDocument->SetChanged(bSetModified);\n }\n }\n while (false);\n\n mrViewShell.Cancel();\n rRequest.Done ();\n}\n\n\n\n\nvoid ViewShell::Implementation::AssignLayout (\n SdPage* pPage,\n AutoLayout aLayout)\n{\n \/\/ Transform the given request into the four argument form that is\n \/\/ understood by ProcessModifyPageSlot().\n SdrLayerAdmin& rLayerAdmin (mrViewShell.GetViewShellBase().GetDocument()->GetLayerAdmin());\n BYTE aBackground (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE));\n BYTE aBackgroundObject (rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE));\n SetOfByte aVisibleLayers (pPage->TRG_GetMasterPageVisibleLayers());\n SfxRequest aRequest (mrViewShell.GetViewShellBase().GetViewFrame(), SID_MODIFYPAGE);\n aRequest.AppendItem(SfxStringItem (ID_VAL_PAGENAME, pPage->GetName()));\n aRequest.AppendItem(SfxUInt32Item (ID_VAL_WHATLAYOUT, aLayout));\n aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEBACK, aVisibleLayers.IsSet(aBackground)));\n aRequest.AppendItem(SfxBoolItem(ID_VAL_ISPAGEOBJ, aVisibleLayers.IsSet(aBackgroundObject)));\n\n \/\/ Forward the call with the new arguments.\n ProcessModifyPageSlot (\n aRequest,\n pPage,\n pPage->GetPageKind());\n}\n\n\n\n\nsal_uInt16 ViewShell::Implementation::GetViewId (void)\n{\n switch (mrViewShell.GetShellType())\n {\n case ViewShell::ST_IMPRESS:\n case ViewShell::ST_NOTES:\n case ViewShell::ST_HANDOUT:\n return IMPRESS_FACTORY_ID;\n\n case ViewShell::ST_DRAW:\n return DRAW_FACTORY_ID;\n\n case ViewShell::ST_OUTLINE:\n return OUTLINE_FACTORY_ID;\n\n case ViewShell::ST_SLIDE:\n case ViewShell::ST_SLIDE_SORTER:\n return SLIDE_SORTER_FACTORY_ID;\n\n case ViewShell::ST_PRESENTATION:\n return PRESENTATION_FACTORY_ID;\n\n \/\/ Since we have to return a view id for every possible shell type\n \/\/ and there is not (yet) a proper ViewShellBase sub class for the\n \/\/ remaining types we chose the Impress factory as a fall back.\n case ViewShell::ST_TASK_PANE:\n case ViewShell::ST_NONE:\n default:\n return IMPRESS_FACTORY_ID;\n }\n}\n\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n * Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"mountbutton.h\"\n#include <XdgIcon>\n\n\nMountButton::MountButton(QWidget * parent) :\n QToolButton(parent)\n{\n setIcon(XdgIcon::fromTheme(QStringList() << \"device-notifier\" << \"drive-removable-media-usb\" << \"drive-removable-media\"));\n\n setToolTip(tr(\"Removable media\/devices manager\"));\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n}\n\n\nMountButton::~MountButton()\n{\n}\n\n\nvoid MountButton::setDown(bool down)\n{\n QToolButton::setDown(down);\n}\n<commit_msg>plugin-mount: Use only one icon instead a list of possible ones<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n * Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"mountbutton.h\"\n#include <XdgIcon>\n\n\nMountButton::MountButton(QWidget * parent) :\n QToolButton(parent)\n{\n setIcon(XdgIcon::fromTheme(QStringLiteral(\"drive-removable-media\")));\n\n setToolTip(tr(\"Removable media\/devices manager\"));\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n}\n\n\nMountButton::~MountButton()\n{\n}\n\n\nvoid MountButton::setDown(bool down)\n{\n QToolButton::setDown(down);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <GL\/glut.h>\n#include \"Ising_simulator.hpp\"\n#include \"spin.hpp\"\n#include \"Ising_simulator_traits.hpp\"\n#include \"drawer\/Ising_window_traits.hpp\"\n#include \"..\/openGLwrapper\/make_canvas.hpp\"\n#include \"..\/openGLwrapper\/drawquads.hpp\"\n\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~parameter set~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nusing numerical_type = Default_simulator_traits::numerical_type;\n\nconstexpr std::size_t system_row_num(250);\nconstexpr std::size_t system_column_num(250);\nconstexpr int random_seed(53);\nconstexpr numerical_type tempreture(1);\nconstexpr numerical_type magnetic_flux_density(0.0);\nconstexpr numerical_type spin_interaction(0.5);\n\nusing simulator_type = Ising_simulator<\n Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>;\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global func declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntemplate<typename window_traits>\nvoid set_canvas(int& argc, char** argv);\n\ntemplate<typename window_traits>\nvoid draw_pixel();\n\ntemplate<typename window_traits>\nvoid display();\n\nvoid update_canvas(int);\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global variable declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nconst simulator_type::array_matrix* Ising_field_ptr(nullptr);\nsimulator_type* Ising_simulator_ptr(nullptr); \nstd::size_t step(0);\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~main~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint main(int argc, char *argv[]){\n Ising_simulator_ptr = new simulator_type\n \t(random_seed, tempreture, magnetic_flux_density, spin_interaction);\n \n Ising_field_ptr = &(Ising_simulator_ptr->spins_state());\n \n set_canvas<Ising_window_traits>(argc ,argv);\n glutTimerFunc(10, update_canvas, 0);\n glutMainLoop();\n \n delete Ising_simulator_ptr;\n return 0;\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global func definition~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntemplate<typename window_traits>\nvoid set_canvas(int& argc, char** argv)\n{\n setWindow<window_traits>(argc, argv);\n setBackground();\n glClear(GL_COLOR_BUFFER_BIT);\n glutDisplayFunc(display<window_traits>);\n return;\n}\n\ntemplate<typename window_traits>\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n draw_pixel<window_traits>();\n glFlush();\n return;\n}\n\nvoid update_canvas(int value)\n{\n std::size_t roop_num = 1000;\n ++step;\n std::cout << step * roop_num << std::endl;\n for(std::size_t roop = 0; roop < roop_num; ++roop)\n\tIsing_simulator_ptr->step();\n glutPostRedisplay();\n glutTimerFunc(50, update_canvas, 0);\n return;\n}\n\ntemplate<typename window_traits>\nvoid draw_pixel()\n{\n const std::size_t row_n = Ising_field_ptr->row_num();\n const std::size_t column_n = Ising_field_ptr->column_num();\n constexpr float margin = window_traits::margin;\n constexpr float frame_size = 2 - 2.0 * margin;\n const double x_pixel_size = frame_size \/ row_n;\n const double y_pixel_size = frame_size \/ column_n;\n\n const double initial_x_coord = -1 + margin + x_pixel_size * 0.5;\n const double initial_y_coord = -1 + margin + y_pixel_size * 0.5;\n\n double x_coord = initial_x_coord;\n double y_coord = initial_y_coord;\n for(std::size_t row = 0; row < row_n; ++row){\n\tfor(std::size_t column = 0; column < column_n; ++column){\n\t if(Ising_field_ptr->at(row, column).get() == 1)\n\t\tdrawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 0.0, 0.0, 0.0);\n\t else\n\t\tdrawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 1.0, 1.0, 1.0);\n\t x_coord += x_pixel_size;\n\t}\n\tx_coord = initial_x_coord;\n\ty_coord += y_pixel_size;\n }\n return;\n}\n\n\n\n\n<commit_msg>fix include file pass<commit_after>#include <iostream>\n#include <GL\/glut.h>\n#include \"Ising_simulator.hpp\"\n#include \"spin.hpp\"\n#include \"Ising_simulator_traits.hpp\"\n#include \"Ising_window_traits.hpp\"\n#include \"..\/openGLwrapper\/make_canvas.hpp\"\n#include \"..\/openGLwrapper\/drawquads.hpp\"\n\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~parameter set~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nusing numerical_type = Default_simulator_traits::numerical_type;\n\nconstexpr std::size_t system_row_num(250);\nconstexpr std::size_t system_column_num(250);\nconstexpr int random_seed(53);\nconstexpr numerical_type tempreture(1);\nconstexpr numerical_type magnetic_flux_density(0.0);\nconstexpr numerical_type spin_interaction(0.5);\n\nusing simulator_type = Ising_simulator<\n Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>;\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global func declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntemplate<typename window_traits>\nvoid set_canvas(int& argc, char** argv);\n\ntemplate<typename window_traits>\nvoid draw_pixel();\n\ntemplate<typename window_traits>\nvoid display();\n\nvoid update_canvas(int);\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global variable declaration~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nconst simulator_type::array_matrix* Ising_field_ptr(nullptr);\nsimulator_type* Ising_simulator_ptr(nullptr); \nstd::size_t step(0);\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~main~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint main(int argc, char *argv[]){\n Ising_simulator_ptr = new simulator_type\n \t(random_seed, tempreture, magnetic_flux_density, spin_interaction);\n \n Ising_field_ptr = &(Ising_simulator_ptr->spins_state());\n \n set_canvas<Ising_window_traits>(argc ,argv);\n glutTimerFunc(10, update_canvas, 0);\n glutMainLoop();\n \n delete Ising_simulator_ptr;\n return 0;\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~global func definition~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ntemplate<typename window_traits>\nvoid set_canvas(int& argc, char** argv)\n{\n setWindow<window_traits>(argc, argv);\n setBackground();\n glClear(GL_COLOR_BUFFER_BIT);\n glutDisplayFunc(display<window_traits>);\n return;\n}\n\ntemplate<typename window_traits>\nvoid display()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n draw_pixel<window_traits>();\n glFlush();\n return;\n}\n\nvoid update_canvas(int value)\n{\n std::size_t roop_num = 1000;\n ++step;\n std::cout << step * roop_num << std::endl;\n for(std::size_t roop = 0; roop < roop_num; ++roop)\n\tIsing_simulator_ptr->step();\n glutPostRedisplay();\n glutTimerFunc(50, update_canvas, 0);\n return;\n}\n\ntemplate<typename window_traits>\nvoid draw_pixel()\n{\n const std::size_t row_n = Ising_field_ptr->row_num();\n const std::size_t column_n = Ising_field_ptr->column_num();\n constexpr float margin = window_traits::margin;\n constexpr float frame_size = 2 - 2.0 * margin;\n const double x_pixel_size = frame_size \/ row_n;\n const double y_pixel_size = frame_size \/ column_n;\n\n const double initial_x_coord = -1 + margin + x_pixel_size * 0.5;\n const double initial_y_coord = -1 + margin + y_pixel_size * 0.5;\n\n double x_coord = initial_x_coord;\n double y_coord = initial_y_coord;\n for(std::size_t row = 0; row < row_n; ++row){\n\tfor(std::size_t column = 0; column < column_n; ++column){\n\t if(Ising_field_ptr->at(row, column).get() == 1)\n\t\tdrawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 0.0, 0.0, 0.0);\n\t else\n\t\tdrawquads(x_coord, y_coord, x_pixel_size, y_pixel_size, 1.0, 1.0, 1.0);\n\t x_coord += x_pixel_size;\n\t}\n\tx_coord = initial_x_coord;\n\ty_coord += y_pixel_size;\n }\n return;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2004 by Frank Osterfeld *\n * frank.osterfeld AT kdemail.net *\n * *\n * Licensed under GPL. *\n ***************************************************************************\/\n\n#include \"feedgroup.h\"\n#include \"treenode.h\"\n\n#include \"kdebug.h\"\n\nusing namespace Akregator;\n\nTreeNode::TreeNode()\n : QObject(0, 0), m_title(\"\"), m_parent(0), m_doNotify(true), m_changeOccured(false)\n{\n}\n\nTreeNode::~TreeNode()\n{\n \/\/ tell the world that this node is destroyed\n emit signalDestroyed(this);\n}\n\nconst QString& TreeNode::title() const\n{\n return m_title;\n}\n\nvoid TreeNode::setTitle(const QString& title)\n{\n \n if (m_title != title)\n {\n m_title = title;\n modified(); \n }\n}\n\nTreeNode* TreeNode::nextSibling() const\n{\n if (!m_parent) \n return 0;\n QPtrList<TreeNode> children = m_parent->children();\n children.find(this);\n return children.next();\n}\n\nTreeNode* TreeNode::prevSibling() const\n{\n if (!m_parent) \n return 0;\n QPtrList<TreeNode> children = m_parent->children();\n children.find(this);\n return children.prev();\n}\n \nFeedGroup* TreeNode::parent() const\n{\n return m_parent;\n}\n \nvoid TreeNode::setParent(FeedGroup* parent)\n{\n m_parent = parent;\n} \n\nvoid TreeNode::setNotificationMode(bool doNotify, bool notifyOccuredChanges)\n{\n if (doNotify && !m_doNotify) \/\/ turned on\n {\n m_doNotify = true;\n if (m_changeOccured && notifyOccuredChanges)\n emit signalChanged(this);\n m_changeOccured = false; \n } \n if (!doNotify && m_doNotify) \/\/turned off\n {\n m_changeOccured = false;\n m_doNotify = false;\n }\n}\n\nvoid TreeNode::modified()\n{\n\/\/ kdDebug() << \"enter TreeNode::modified\" << title() << endl;\n if (m_doNotify)\n emit signalChanged(this);\n else\n m_changeOccured = true;\n\/\/ kdDebug() << \"leave TreeNode::modified\" << title()<< endl;\n}\n \n#include \"treenode.moc\"\n<commit_msg>Warning--<commit_after>\/***************************************************************************\n * Copyright (C) 2004 by Frank Osterfeld *\n * frank.osterfeld AT kdemail.net *\n * *\n * Licensed under GPL. *\n ***************************************************************************\/\n\n#include \"feedgroup.h\"\n#include \"treenode.h\"\n\n#include \"kdebug.h\"\n\nusing namespace Akregator;\n\nTreeNode::TreeNode()\n : QObject(0, 0), m_doNotify(true), m_changeOccured(false), m_title(\"\"), m_parent(0)\n{\n}\n\nTreeNode::~TreeNode()\n{\n \/\/ tell the world that this node is destroyed\n emit signalDestroyed(this);\n}\n\nconst QString& TreeNode::title() const\n{\n return m_title;\n}\n\nvoid TreeNode::setTitle(const QString& title)\n{\n\n if (m_title != title)\n {\n m_title = title;\n modified();\n }\n}\n\nTreeNode* TreeNode::nextSibling() const\n{\n if (!m_parent)\n return 0;\n QPtrList<TreeNode> children = m_parent->children();\n children.find(this);\n return children.next();\n}\n\nTreeNode* TreeNode::prevSibling() const\n{\n if (!m_parent)\n return 0;\n QPtrList<TreeNode> children = m_parent->children();\n children.find(this);\n return children.prev();\n}\n\nFeedGroup* TreeNode::parent() const\n{\n return m_parent;\n}\n\nvoid TreeNode::setParent(FeedGroup* parent)\n{\n m_parent = parent;\n}\n\nvoid TreeNode::setNotificationMode(bool doNotify, bool notifyOccuredChanges)\n{\n if (doNotify && !m_doNotify) \/\/ turned on\n {\n m_doNotify = true;\n if (m_changeOccured && notifyOccuredChanges)\n emit signalChanged(this);\n m_changeOccured = false;\n }\n if (!doNotify && m_doNotify) \/\/turned off\n {\n m_changeOccured = false;\n m_doNotify = false;\n }\n}\n\nvoid TreeNode::modified()\n{\n\/\/ kdDebug() << \"enter TreeNode::modified\" << title() << endl;\n if (m_doNotify)\n emit signalChanged(this);\n else\n m_changeOccured = true;\n\/\/ kdDebug() << \"leave TreeNode::modified\" << title()<< endl;\n}\n\n#include \"treenode.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All rights reserved\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build ignore\n\n#include \"command.h\"\n\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"dep.h\"\n#include \"eval.h\"\n#include \"flags.h\"\n#include \"log.h\"\n#include \"strutil.h\"\n#include \"var.h\"\n\nnamespace {\n\nclass AutoVar : public Var {\n public:\n virtual const char* Flavor() const override {\n return \"undefined\";\n }\n virtual VarOrigin Origin() const override {\n return VarOrigin::AUTOMATIC;\n }\n\n virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); }\n\n virtual StringPiece String() const override {\n ERROR(\"$(value %s) is not implemented yet\", sym_);\n return \"\";\n }\n\n virtual string DebugString() const override {\n return string(\"AutoVar(\") + sym_ + \")\";\n }\n\n protected:\n AutoVar(CommandEvaluator* ce, const char* sym) : ce_(ce), sym_(sym) {}\n virtual ~AutoVar() = default;\n\n CommandEvaluator* ce_;\n const char* sym_;\n};\n\n#define DECLARE_AUTO_VAR_CLASS(name) \\\n class name : public AutoVar { \\\n public: \\\n name(CommandEvaluator* ce, const char* sym) \\\n : AutoVar(ce, sym) {} \\\n virtual ~name() = default; \\\n virtual void Eval(Evaluator* ev, string* s) const override; \\\n }\n\nDECLARE_AUTO_VAR_CLASS(AutoAtVar);\nDECLARE_AUTO_VAR_CLASS(AutoLessVar);\nDECLARE_AUTO_VAR_CLASS(AutoHatVar);\nDECLARE_AUTO_VAR_CLASS(AutoPlusVar);\nDECLARE_AUTO_VAR_CLASS(AutoStarVar);\n\nclass AutoSuffixDVar : public AutoVar {\n public:\n AutoSuffixDVar(CommandEvaluator* ce, const char* sym, Var* wrapped)\n : AutoVar(ce, sym), wrapped_(wrapped) {\n }\n virtual ~AutoSuffixDVar() = default;\n virtual void Eval(Evaluator* ev, string* s) const override;\n\n private:\n Var* wrapped_;\n};\n\nclass AutoSuffixFVar : public AutoVar {\n public:\n AutoSuffixFVar(CommandEvaluator* ce, const char* sym, Var* wrapped)\n : AutoVar(ce, sym), wrapped_(wrapped) {}\n virtual ~AutoSuffixFVar() = default;\n virtual void Eval(Evaluator* ev, string* s) const override;\n\n private:\n Var* wrapped_;\n};\n\nvoid AutoAtVar::Eval(Evaluator*, string* s) const {\n *s += ce_->current_dep_node()->output.str();\n}\n\nvoid AutoLessVar::Eval(Evaluator*, string* s) const {\n auto& ai = ce_->current_dep_node()->actual_inputs;\n if (!ai.empty())\n *s += ai[0].str();\n}\n\nvoid AutoHatVar::Eval(Evaluator*, string* s) const {\n unordered_set<StringPiece> seen;\n WordWriter ww(s);\n for (Symbol ai : ce_->current_dep_node()->actual_inputs) {\n if (seen.insert(ai.str()).second)\n ww.Write(ai.str());\n }\n}\n\nvoid AutoPlusVar::Eval(Evaluator*, string* s) const {\n WordWriter ww(s);\n for (Symbol ai : ce_->current_dep_node()->actual_inputs) {\n ww.Write(ai.str());\n }\n}\n\nvoid AutoStarVar::Eval(Evaluator*, string* s) const {\n const DepNode* n = ce_->current_dep_node();\n if (!n->output_pattern.IsValid())\n return;\n Pattern pat(n->output_pattern.str());\n pat.Stem(n->output.str()).AppendToString(s);\n}\n\nvoid AutoSuffixDVar::Eval(Evaluator* ev, string* s) const {\n string buf;\n wrapped_->Eval(ev, &buf);\n WordWriter ww(s);\n for (StringPiece tok : WordScanner(buf)) {\n ww.Write(Dirname(tok));\n }\n}\n\nvoid AutoSuffixFVar::Eval(Evaluator* ev, string* s) const {\n string buf;\n wrapped_->Eval(ev, &buf);\n WordWriter ww(s);\n for (StringPiece tok : WordScanner(buf)) {\n ww.Write(Basename(tok));\n }\n}\n\nvoid ParseCommandPrefixes(StringPiece* s, bool* echo, bool* ignore_error) {\n *s = TrimLeftSpace(*s);\n while (true) {\n char c = s->get(0);\n if (c == '@') {\n *echo = false;\n } else if (c == '-') {\n *ignore_error = true;\n } else {\n break;\n }\n *s = TrimLeftSpace(s->substr(1));\n }\n}\n\n} \/\/ namespace\n\nCommandEvaluator::CommandEvaluator(Evaluator* ev)\n : ev_(ev) {\n Vars* vars = ev_->mutable_vars();\n#define INSERT_AUTO_VAR(name, sym) do { \\\n Var* v = new name(this, sym); \\\n (*vars)[Intern(sym)] = v; \\\n (*vars)[Intern(sym\"D\")] = new AutoSuffixDVar(this, sym\"D\", v); \\\n (*vars)[Intern(sym\"F\")] = new AutoSuffixFVar(this, sym\"F\", v); \\\n } while (0)\n INSERT_AUTO_VAR(AutoAtVar, \"@\");\n INSERT_AUTO_VAR(AutoLessVar, \"<\");\n INSERT_AUTO_VAR(AutoHatVar, \"^\");\n INSERT_AUTO_VAR(AutoPlusVar, \"+\");\n INSERT_AUTO_VAR(AutoStarVar, \"*\");\n}\n\nvoid CommandEvaluator::Eval(DepNode* n, vector<Command*>* commands) {\n ev_->set_loc(n->loc);\n ev_->set_current_scope(n->rule_vars);\n current_dep_node_ = n;\n for (Value* v : n->cmds) {\n const string&& cmds_buf = v->Eval(ev_);\n StringPiece cmds = cmds_buf;\n bool global_echo = !g_flags.is_silent_mode;\n bool global_ignore_error = false;\n ParseCommandPrefixes(&cmds, &global_echo, &global_ignore_error);\n if (cmds == \"\")\n continue;\n while (true) {\n size_t lf_cnt;\n size_t index = FindEndOfLine(cmds, 0, &lf_cnt);\n if (index == cmds.size())\n index = string::npos;\n StringPiece cmd = TrimLeftSpace(cmds.substr(0, index));\n cmds = cmds.substr(index + 1);\n\n bool echo = global_echo;\n bool ignore_error = global_ignore_error;\n ParseCommandPrefixes(&cmd, &echo, &ignore_error);\n\n if (!cmd.empty()) {\n Command* command = new Command(n->output);\n command->cmd = cmd.as_string();\n command->echo = echo;\n command->ignore_error = ignore_error;\n commands->push_back(command);\n }\n if (index == string::npos)\n break;\n }\n continue;\n }\n\n if (!ev_->delayed_output_commands().empty()) {\n vector<Command*> output_commands;\n for (const string& cmd : ev_->delayed_output_commands()) {\n Command* c = new Command(n->output);\n c->cmd = cmd;\n c->echo = false;\n c->ignore_error = false;\n output_commands.push_back(c);\n }\n \/\/ Prepend |output_commands|.\n commands->swap(output_commands);\n copy(output_commands.begin(), output_commands.end(),\n back_inserter(*commands));\n ev_->clear_delayed_output_commands();\n }\n\n ev_->set_current_scope(NULL);\n}\n<commit_msg>[C++] Fail early for unsupported automatic variables<commit_after>\/\/ Copyright 2015 Google Inc. All rights reserved\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build ignore\n\n#include \"command.h\"\n\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"dep.h\"\n#include \"eval.h\"\n#include \"flags.h\"\n#include \"log.h\"\n#include \"strutil.h\"\n#include \"var.h\"\n\nnamespace {\n\nclass AutoVar : public Var {\n public:\n virtual const char* Flavor() const override {\n return \"undefined\";\n }\n virtual VarOrigin Origin() const override {\n return VarOrigin::AUTOMATIC;\n }\n\n virtual void AppendVar(Evaluator*, Value*) override { CHECK(false); }\n\n virtual StringPiece String() const override {\n ERROR(\"$(value %s) is not implemented yet\", sym_);\n return \"\";\n }\n\n virtual string DebugString() const override {\n return string(\"AutoVar(\") + sym_ + \")\";\n }\n\n protected:\n AutoVar(CommandEvaluator* ce, const char* sym) : ce_(ce), sym_(sym) {}\n virtual ~AutoVar() = default;\n\n CommandEvaluator* ce_;\n const char* sym_;\n};\n\n#define DECLARE_AUTO_VAR_CLASS(name) \\\n class name : public AutoVar { \\\n public: \\\n name(CommandEvaluator* ce, const char* sym) \\\n : AutoVar(ce, sym) {} \\\n virtual ~name() = default; \\\n virtual void Eval(Evaluator* ev, string* s) const override; \\\n }\n\nDECLARE_AUTO_VAR_CLASS(AutoAtVar);\nDECLARE_AUTO_VAR_CLASS(AutoLessVar);\nDECLARE_AUTO_VAR_CLASS(AutoHatVar);\nDECLARE_AUTO_VAR_CLASS(AutoPlusVar);\nDECLARE_AUTO_VAR_CLASS(AutoStarVar);\nDECLARE_AUTO_VAR_CLASS(AutoNotImplementedVar);\n\nclass AutoSuffixDVar : public AutoVar {\n public:\n AutoSuffixDVar(CommandEvaluator* ce, const char* sym, Var* wrapped)\n : AutoVar(ce, sym), wrapped_(wrapped) {\n }\n virtual ~AutoSuffixDVar() = default;\n virtual void Eval(Evaluator* ev, string* s) const override;\n\n private:\n Var* wrapped_;\n};\n\nclass AutoSuffixFVar : public AutoVar {\n public:\n AutoSuffixFVar(CommandEvaluator* ce, const char* sym, Var* wrapped)\n : AutoVar(ce, sym), wrapped_(wrapped) {}\n virtual ~AutoSuffixFVar() = default;\n virtual void Eval(Evaluator* ev, string* s) const override;\n\n private:\n Var* wrapped_;\n};\n\nvoid AutoAtVar::Eval(Evaluator*, string* s) const {\n *s += ce_->current_dep_node()->output.str();\n}\n\nvoid AutoLessVar::Eval(Evaluator*, string* s) const {\n auto& ai = ce_->current_dep_node()->actual_inputs;\n if (!ai.empty())\n *s += ai[0].str();\n}\n\nvoid AutoHatVar::Eval(Evaluator*, string* s) const {\n unordered_set<StringPiece> seen;\n WordWriter ww(s);\n for (Symbol ai : ce_->current_dep_node()->actual_inputs) {\n if (seen.insert(ai.str()).second)\n ww.Write(ai.str());\n }\n}\n\nvoid AutoPlusVar::Eval(Evaluator*, string* s) const {\n WordWriter ww(s);\n for (Symbol ai : ce_->current_dep_node()->actual_inputs) {\n ww.Write(ai.str());\n }\n}\n\nvoid AutoStarVar::Eval(Evaluator*, string* s) const {\n const DepNode* n = ce_->current_dep_node();\n if (!n->output_pattern.IsValid())\n return;\n Pattern pat(n->output_pattern.str());\n pat.Stem(n->output.str()).AppendToString(s);\n}\n\nvoid AutoNotImplementedVar::Eval(Evaluator*, string*) const {\n ERROR(\"Automatic variable `$%s' isn't supported yet\", sym_);\n}\n\nvoid AutoSuffixDVar::Eval(Evaluator* ev, string* s) const {\n string buf;\n wrapped_->Eval(ev, &buf);\n WordWriter ww(s);\n for (StringPiece tok : WordScanner(buf)) {\n ww.Write(Dirname(tok));\n }\n}\n\nvoid AutoSuffixFVar::Eval(Evaluator* ev, string* s) const {\n string buf;\n wrapped_->Eval(ev, &buf);\n WordWriter ww(s);\n for (StringPiece tok : WordScanner(buf)) {\n ww.Write(Basename(tok));\n }\n}\n\nvoid ParseCommandPrefixes(StringPiece* s, bool* echo, bool* ignore_error) {\n *s = TrimLeftSpace(*s);\n while (true) {\n char c = s->get(0);\n if (c == '@') {\n *echo = false;\n } else if (c == '-') {\n *ignore_error = true;\n } else {\n break;\n }\n *s = TrimLeftSpace(s->substr(1));\n }\n}\n\n} \/\/ namespace\n\nCommandEvaluator::CommandEvaluator(Evaluator* ev)\n : ev_(ev) {\n Vars* vars = ev_->mutable_vars();\n#define INSERT_AUTO_VAR(name, sym) do { \\\n Var* v = new name(this, sym); \\\n (*vars)[Intern(sym)] = v; \\\n (*vars)[Intern(sym\"D\")] = new AutoSuffixDVar(this, sym\"D\", v); \\\n (*vars)[Intern(sym\"F\")] = new AutoSuffixFVar(this, sym\"F\", v); \\\n } while (0)\n INSERT_AUTO_VAR(AutoAtVar, \"@\");\n INSERT_AUTO_VAR(AutoLessVar, \"<\");\n INSERT_AUTO_VAR(AutoHatVar, \"^\");\n INSERT_AUTO_VAR(AutoPlusVar, \"+\");\n INSERT_AUTO_VAR(AutoStarVar, \"*\");\n \/\/ TODO: Implement them.\n INSERT_AUTO_VAR(AutoNotImplementedVar, \"%\");\n INSERT_AUTO_VAR(AutoNotImplementedVar, \"?\");\n INSERT_AUTO_VAR(AutoNotImplementedVar, \"|\");\n}\n\nvoid CommandEvaluator::Eval(DepNode* n, vector<Command*>* commands) {\n ev_->set_loc(n->loc);\n ev_->set_current_scope(n->rule_vars);\n current_dep_node_ = n;\n for (Value* v : n->cmds) {\n const string&& cmds_buf = v->Eval(ev_);\n StringPiece cmds = cmds_buf;\n bool global_echo = !g_flags.is_silent_mode;\n bool global_ignore_error = false;\n ParseCommandPrefixes(&cmds, &global_echo, &global_ignore_error);\n if (cmds == \"\")\n continue;\n while (true) {\n size_t lf_cnt;\n size_t index = FindEndOfLine(cmds, 0, &lf_cnt);\n if (index == cmds.size())\n index = string::npos;\n StringPiece cmd = TrimLeftSpace(cmds.substr(0, index));\n cmds = cmds.substr(index + 1);\n\n bool echo = global_echo;\n bool ignore_error = global_ignore_error;\n ParseCommandPrefixes(&cmd, &echo, &ignore_error);\n\n if (!cmd.empty()) {\n Command* command = new Command(n->output);\n command->cmd = cmd.as_string();\n command->echo = echo;\n command->ignore_error = ignore_error;\n commands->push_back(command);\n }\n if (index == string::npos)\n break;\n }\n continue;\n }\n\n if (!ev_->delayed_output_commands().empty()) {\n vector<Command*> output_commands;\n for (const string& cmd : ev_->delayed_output_commands()) {\n Command* c = new Command(n->output);\n c->cmd = cmd;\n c->echo = false;\n c->ignore_error = false;\n output_commands.push_back(c);\n }\n \/\/ Prepend |output_commands|.\n commands->swap(output_commands);\n copy(output_commands.begin(), output_commands.end(),\n back_inserter(*commands));\n ev_->clear_delayed_output_commands();\n }\n\n ev_->set_current_scope(NULL);\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************** \n* Copyright (c) 2010, Dynamic Network Services, Inc.\n* Jake Montgomery (jmontgomery@dyn.com) & Tom Daly (tom@dyn.com)\n* Distributed under the FreeBSD License - see LICENSE\n***************************************************************\/\n\/\/ Common code for beacon and control\n#include \"common.h\"\n\nnamespace openbfdd\n{\n static uint8_t tempMagicMessageNumber[4] = {0xfe, 0xed, 0x19, 0x66};\n const uint32_t MagicMessageNumber = *(uint32_t *)tempMagicMessageNumber;\n const char *SofwareVesrion = PACKAGE_VERSION;\n const char *ControlAppName = \"bfdd-control\";\n const char *BeaconAppName = \"bfdd-beacon\";\n} \n\n\n\n\n\n\n<commit_msg>MagicMessageNumber code caused compile error on Ubuntu. MagicMessageNumber was implemented in such a way that the beacon could not be controlled from a system with opposite endianess.<commit_after>\/************************************************************** \n* Copyright (c) 2010, Dynamic Network Services, Inc.\n* Jake Montgomery (jmontgomery@dyn.com) & Tom Daly (tom@dyn.com)\n* Distributed under the FreeBSD License - see LICENSE\n***************************************************************\/\n\/\/ Common code for beacon and control\n#include \"common.h\"\n\nnamespace openbfdd\n{\n const uint32_t MagicMessageNumber = 0xfeed1966;\n const char *SofwareVesrion = PACKAGE_VERSION;\n const char *ControlAppName = \"bfdd-control\";\n const char *BeaconAppName = \"bfdd-beacon\";\n} \n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n\n#include \"base\/logging.h\"\n#include \"base\/NativeApp.h\"\n#include \"gl_state.h\"\n\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n#if defined(USING_GLES2)\n#if defined(ANDROID) || defined(BLACKBERRY)\nPFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;\nPFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;\nPFNGLDRAWTEXTURENVPROC glDrawTextureNV;\nPFNGLCOPYIMAGESUBDATANVPROC glCopyImageSubDataNV ;\nPFNGLMAPBUFFERPROC glMapBuffer;\n\nPFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;\nPFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;\nPFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;\nPFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;\nPFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;\n#endif\n#endif\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\nstd::string g_all_gl_extensions;\nstd::string g_all_egl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif (initialized)\n\t\treturn;\n\tinitialized = true;\n\n\tRestore();\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFuncSeparate.restore(); count++;\n\tblendColor.restore(); count++;\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n#if !defined(USING_GLES2)\n\tcolorLogicOp.restore(); count++;\n\tlogicOp.restore(); count++;\n#endif\n\n\tif (count != state_count) {\n\t\tFLOG(\"OpenGLState::Restore is missing some states\");\n\t}\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\t\/\/ Make sure to only do this once. It's okay to call CheckGLExtensions from wherever.\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *renderer = (const char *)glGetString(GL_RENDERER);\n\tconst char *versionStr = (const char *)glGetString(GL_VERSION);\n\n\t\/\/ Check vendor string to try and guess GPU\n\tconst char *cvendor = (char *)glGetString(GL_VENDOR);\n\t\/\/ TODO: move this stuff to gpu_features.cpp\n\tif (cvendor) {\n\t\tconst std::string vendor(cvendor);\n\t\tif (vendor == \"NVIDIA Corporation\"\n\t\t\t|| vendor == \"Nouveau\"\n\t\t\t|| vendor == \"nouveau\") {\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_NVIDIA;\n\t\t} else if (vendor == \"Advanced Micro Devices, Inc.\"\n\t\t\t|| vendor == \"ATI Technologies Inc.\") {\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_AMD;\n\t\t} else if (vendor == \"Intel\"\n\t\t\t|| vendor == \"Intel Inc.\"\n\t\t\t|| vendor == \"Intel Corporation\"\n\t\t\t|| vendor == \"Tungsten Graphics, Inc\") { \/\/ We'll assume this last one means Intel\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_INTEL;\n\t\t} else if (vendor == \"ARM\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_ARM;\n\t\t} else if (vendor == \"Imagination Technologies\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_POWERVR;\n\t\t} else if (vendor == \"Qualcomm\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_ADRENO;\n\t\t} else if (vendor == \"Broadcom\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_BROADCOM;\n\t\t\t\/\/ Just for reference: Galaxy Y has renderer == \"VideoCore IV HW\"\n\t\t} else {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;\n\t\t}\n\t} else {\n\t\tgl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;\n\t}\n\n\tILOG(\"GPU Vendor : %s ; GL version str: %s\", cvendor, versionStr ? versionStr : \"N\/A\");\n\n#ifndef USING_GLES2\n\tchar buffer[64] = {0};\n\tif (versionStr) {\n\t\tstrncpy(buffer, versionStr, 63);\n\t}\n\tconst char *lastNumStart = buffer;\n\tint numVer = 0;\n\tint len = (int)strlen(buffer);\n\tfor (int i = 0; i < len && numVer < 3; i++) {\n\t\tif (buffer[i] == '.') {\n\t\t\tbuffer[i] = 0;\n\t\t\tgl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);\n\t\t\ti++;\n\t\t\tlastNumStart = buffer + i;\n\t\t}\n\t}\n\tif (numVer < 3)\n\t\tgl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);\n#else\n\tgl_extensions.ver[0] = 2;\n#endif\n\n#if defined(USING_GLES2)\n\t\/\/ MAY_HAVE_GLES3 defined on all platforms that support it\n#if defined(MAY_HAVE_GLES3)\n\t\/\/ Try to load GLES 3.0 only if \"3.0\" found in version\n\t\/\/ This simple heuristic avoids issues on older devices where you can only call eglGetProcAddress a limited\n\t\/\/ number of times.\n\tif (strstr(versionStr, \"3.0\") && GL_TRUE == gl3stubInit()) {\n\t\tgl_extensions.ver[0] = 3;\n\t\tgl_extensions.GLES3 = true;\n\t\tILOG(\"Full OpenGL ES 3.0 support detected!\\n\");\n\t\t\/\/ Though, let's ban Mali from the GLES 3 path for now, see #4078\n\t\tif (strstr(renderer, \"Mali\") != 0) {\n\t\t\tgl_extensions.GLES3 = false;\n\t\t}\n\t}\n#endif\n#else\n\t\/\/ If the GL version >= 4.3, we know it's a true superset of OpenGL ES 3.0 and can thus enable\n\t\/\/ modern paths.\n\t\/\/ Most of it could be enabled on lower GPUs as well, but let's start this way.\n\tif ((gl_extensions.ver[0] == 4 && gl_extensions.ver[1] >= 3) || gl_extensions.ver[0] > 4) {\n\t\tgl_extensions.GLES3 = true;\n\t}\n#endif\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\tif (extString) {\n\t\tg_all_gl_extensions = extString;\n\t} else {\n\t\tg_all_gl_extensions = \"\";\n\t}\n\n#ifdef WIN32\n\tconst char *wglString = 0;\n\tif (wglGetExtensionsStringEXT)\n\t\twglString = wglGetExtensionsStringEXT();\n\tif (wglString) {\n\t\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n\t\tg_all_egl_extensions = wglString;\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\n\tgl_extensions.NV_draw_texture = strstr(extString, \"GL_NV_draw_texture\") != 0;\n\tgl_extensions.ARB_blend_func_extended = strstr(extString, \"GL_ARB_blend_func_extended\") != 0;\n\n#ifdef USING_GLES2\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.OES_mapbuffer = strstr(extString, \"GL_OES_mapbuffer\") != 0;\n\tgl_extensions.EXT_blend_minmax = strstr(extString, \"GL_EXT_blend_minmax\") != 0;\n\tgl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, \"GL_EXT_shader_framebuffer_fetch\") != 0) || (strstr(extString, \"GL_NV_shader_framebuffer_fetch\") != 0);\n\tgl_extensions.NV_copy_image = strstr(extString, \"GL_NV_copy_image\") != 0;\n\tgl_extensions.EXT_unpack_subimage = strstr(extString, \"GL_EXT_unpack_subimage\") != 0;\n#if defined(ANDROID) || defined(BLACKBERRY)\n\t\/\/ On Android, incredibly, this is not consistently non-zero! It does seem to have the same value though.\n\t\/\/ https:\/\/twitter.com\/ID_AA_Carmack\/status\/387383037794603008\n#ifdef _DEBUG\n\tvoid *invalidAddress = (void *)eglGetProcAddress(\"InvalidGlCall1\");\n\tvoid *invalidAddress2 = (void *)eglGetProcAddress(\"AnotherInvalidGlCall2\");\n\tDLOG(\"Addresses returned for invalid extensions: %p %p\", invalidAddress, invalidAddress2);\n#endif\n\n\tif (gl_extensions.NV_draw_texture) {\n\t\tglDrawTextureNV = (PFNGLDRAWTEXTURENVPROC)eglGetProcAddress(\"glDrawTextureNV\");\n\t}\n\n\tif (gl_extensions.NV_copy_image) {\n\t\tglCopyImageSubDataNV = (PFNGLCOPYIMAGESUBDATANVPROC)eglGetProcAddress(\"glCopyImageSubDataNV\");\n\t}\n\n\tgl_extensions.OES_vertex_array_object = strstr(extString, \"GL_OES_vertex_array_object\") != 0;\n\tif (gl_extensions.OES_vertex_array_object) {\n\t\tglGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glGenVertexArraysOES\" );\n\t\tglBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( \"glBindVertexArrayOES\" );\n\t\tglDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glDeleteVertexArraysOES\" );\n\t\tglIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( \"glIsVertexArrayOES\" );\n\t}\n\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\tif (gl_extensions.EXT_discard_framebuffer) {\n\t\tglDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress(\"glDiscardFramebufferEXT\");\n\t}\n#else\n\tgl_extensions.OES_vertex_array_object = false;\n\tgl_extensions.EXT_discard_framebuffer = false;\n#endif\n#else\n\t\/\/ Desktops support minmax and subimage unpack (GL_UNPACK_ROW_LENGTH etc)\n\tgl_extensions.EXT_blend_minmax = true;\n\tgl_extensions.EXT_unpack_subimage = true;\n#endif\n\t\/\/ GLES 3 subsumes many ES2 extensions.\n\tif (gl_extensions.GLES3) {\n\t\tgl_extensions.EXT_unpack_subimage = true;\n\t}\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.OES_mapbuffer) {\n\t\tglMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( \"glMapBufferOES\" );\n\t}\n\n\t\/\/ Look for EGL extensions\n\tEGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n\tconst char *eglString = eglQueryString(display, EGL_EXTENSIONS);\n\tif (eglString) {\n\t\tg_all_egl_extensions = eglString;\n\n\t\tgl_extensions.EGL_NV_system_time = strstr(eglString, \"EGL_NV_system_time\") != 0;\n\t\tgl_extensions.EGL_NV_coverage_sample = strstr(eglString, \"EGL_NV_coverage_sample\") != 0;\n\n\t\tif (gl_extensions.EGL_NV_system_time) {\n\t\t\teglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress(\"eglGetSystemTimeNV\");\n\t\t\teglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress(\"eglGetSystemTimeFrequencyNV\");\n\t\t}\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = false;\n\tgl_extensions.FBO_EXT = false;\n\tgl_extensions.PBO_ARB = true;\n\tif (extString) {\n\t\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\t\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n\t\tgl_extensions.PBO_ARB = strstr(extString, \"GL_ARB_pixel_buffer_object\") != 0;\n\t\tgl_extensions.ATIClampBug = ((strncmp(renderer, \"ATI RADEON X\", 12) == 0) || (strncmp(renderer, \"ATI MOBILITY RADEON X\", 21) == 0));\n\t}\n#endif\n\n\tProcessGPUFeatures();\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif (wglSwapIntervalEXT)\n\t\twglSwapIntervalEXT(interval);\n#endif\n}\n<commit_msg>Force ARB_blend_func_extended off on OpenGL < 3.0.<commit_after>#include <stdlib.h>\n\n#include \"base\/logging.h\"\n#include \"base\/NativeApp.h\"\n#include \"gl_state.h\"\n\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n#if defined(USING_GLES2)\n#if defined(ANDROID) || defined(BLACKBERRY)\nPFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;\nPFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;\nPFNGLDRAWTEXTURENVPROC glDrawTextureNV;\nPFNGLCOPYIMAGESUBDATANVPROC glCopyImageSubDataNV ;\nPFNGLMAPBUFFERPROC glMapBuffer;\n\nPFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;\nPFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;\nPFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;\nPFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;\nPFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;\n#endif\n#endif\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\nstd::string g_all_gl_extensions;\nstd::string g_all_egl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif (initialized)\n\t\treturn;\n\tinitialized = true;\n\n\tRestore();\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFuncSeparate.restore(); count++;\n\tblendColor.restore(); count++;\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n#if !defined(USING_GLES2)\n\tcolorLogicOp.restore(); count++;\n\tlogicOp.restore(); count++;\n#endif\n\n\tif (count != state_count) {\n\t\tFLOG(\"OpenGLState::Restore is missing some states\");\n\t}\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\t\/\/ Make sure to only do this once. It's okay to call CheckGLExtensions from wherever.\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *renderer = (const char *)glGetString(GL_RENDERER);\n\tconst char *versionStr = (const char *)glGetString(GL_VERSION);\n\n\t\/\/ Check vendor string to try and guess GPU\n\tconst char *cvendor = (char *)glGetString(GL_VENDOR);\n\t\/\/ TODO: move this stuff to gpu_features.cpp\n\tif (cvendor) {\n\t\tconst std::string vendor(cvendor);\n\t\tif (vendor == \"NVIDIA Corporation\"\n\t\t\t|| vendor == \"Nouveau\"\n\t\t\t|| vendor == \"nouveau\") {\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_NVIDIA;\n\t\t} else if (vendor == \"Advanced Micro Devices, Inc.\"\n\t\t\t|| vendor == \"ATI Technologies Inc.\") {\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_AMD;\n\t\t} else if (vendor == \"Intel\"\n\t\t\t|| vendor == \"Intel Inc.\"\n\t\t\t|| vendor == \"Intel Corporation\"\n\t\t\t|| vendor == \"Tungsten Graphics, Inc\") { \/\/ We'll assume this last one means Intel\n\t\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_INTEL;\n\t\t} else if (vendor == \"ARM\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_ARM;\n\t\t} else if (vendor == \"Imagination Technologies\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_POWERVR;\n\t\t} else if (vendor == \"Qualcomm\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_ADRENO;\n\t\t} else if (vendor == \"Broadcom\") {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_BROADCOM;\n\t\t\t\/\/ Just for reference: Galaxy Y has renderer == \"VideoCore IV HW\"\n\t\t} else {\n\t\t\tgl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;\n\t\t}\n\t} else {\n\t\tgl_extensions.gpuVendor = GPU_VENDOR_UNKNOWN;\n\t}\n\n\tILOG(\"GPU Vendor : %s ; GL version str: %s\", cvendor, versionStr ? versionStr : \"N\/A\");\n\n#ifndef USING_GLES2\n\tchar buffer[64] = {0};\n\tif (versionStr) {\n\t\tstrncpy(buffer, versionStr, 63);\n\t}\n\tconst char *lastNumStart = buffer;\n\tint numVer = 0;\n\tint len = (int)strlen(buffer);\n\tfor (int i = 0; i < len && numVer < 3; i++) {\n\t\tif (buffer[i] == '.') {\n\t\t\tbuffer[i] = 0;\n\t\t\tgl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);\n\t\t\ti++;\n\t\t\tlastNumStart = buffer + i;\n\t\t}\n\t}\n\tif (numVer < 3)\n\t\tgl_extensions.ver[numVer++] = strtol(lastNumStart, NULL, 10);\n#else\n\tgl_extensions.ver[0] = 2;\n#endif\n\n#if defined(USING_GLES2)\n\t\/\/ MAY_HAVE_GLES3 defined on all platforms that support it\n#if defined(MAY_HAVE_GLES3)\n\t\/\/ Try to load GLES 3.0 only if \"3.0\" found in version\n\t\/\/ This simple heuristic avoids issues on older devices where you can only call eglGetProcAddress a limited\n\t\/\/ number of times.\n\tif (strstr(versionStr, \"3.0\") && GL_TRUE == gl3stubInit()) {\n\t\tgl_extensions.ver[0] = 3;\n\t\tgl_extensions.GLES3 = true;\n\t\tILOG(\"Full OpenGL ES 3.0 support detected!\\n\");\n\t\t\/\/ Though, let's ban Mali from the GLES 3 path for now, see #4078\n\t\tif (strstr(renderer, \"Mali\") != 0) {\n\t\t\tgl_extensions.GLES3 = false;\n\t\t}\n\t}\n#endif\n#else\n\t\/\/ If the GL version >= 4.3, we know it's a true superset of OpenGL ES 3.0 and can thus enable\n\t\/\/ all the same modern paths.\n\t\/\/ Most of it could be enabled on lower GPUs as well, but let's start this way.\n\tif (gl_extensions.VersionGEThan(4, 3, 0)) {\n\t\tgl_extensions.GLES3 = true;\n\t}\n#endif\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\tif (extString) {\n\t\tg_all_gl_extensions = extString;\n\t} else {\n\t\tg_all_gl_extensions = \"\";\n\t}\n\n#ifdef WIN32\n\tconst char *wglString = 0;\n\tif (wglGetExtensionsStringEXT)\n\t\twglString = wglGetExtensionsStringEXT();\n\tif (wglString) {\n\t\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n\t\tg_all_egl_extensions = wglString;\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\n\tgl_extensions.NV_draw_texture = strstr(extString, \"GL_NV_draw_texture\") != 0;\n\tgl_extensions.ARB_blend_func_extended = strstr(extString, \"GL_ARB_blend_func_extended\") != 0;\n\tif (!gl_extensions.VersionGEThan(3, 0, 0)) {\n\t\t\/\/ Force this extension to off on sub 3.0 OpenGL versions as it does not seem reliable\n\t\tgl_extensions.ARB_blend_func_extended = false;\n\t}\n\n#ifdef USING_GLES2\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.OES_mapbuffer = strstr(extString, \"GL_OES_mapbuffer\") != 0;\n\tgl_extensions.EXT_blend_minmax = strstr(extString, \"GL_EXT_blend_minmax\") != 0;\n\tgl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, \"GL_EXT_shader_framebuffer_fetch\") != 0) || (strstr(extString, \"GL_NV_shader_framebuffer_fetch\") != 0);\n\tgl_extensions.NV_copy_image = strstr(extString, \"GL_NV_copy_image\") != 0;\n\tgl_extensions.EXT_unpack_subimage = strstr(extString, \"GL_EXT_unpack_subimage\") != 0;\n#if defined(ANDROID) || defined(BLACKBERRY)\n\t\/\/ On Android, incredibly, this is not consistently non-zero! It does seem to have the same value though.\n\t\/\/ https:\/\/twitter.com\/ID_AA_Carmack\/status\/387383037794603008\n#ifdef _DEBUG\n\tvoid *invalidAddress = (void *)eglGetProcAddress(\"InvalidGlCall1\");\n\tvoid *invalidAddress2 = (void *)eglGetProcAddress(\"AnotherInvalidGlCall2\");\n\tDLOG(\"Addresses returned for invalid extensions: %p %p\", invalidAddress, invalidAddress2);\n#endif\n\n\tif (gl_extensions.NV_draw_texture) {\n\t\tglDrawTextureNV = (PFNGLDRAWTEXTURENVPROC)eglGetProcAddress(\"glDrawTextureNV\");\n\t}\n\n\tif (gl_extensions.NV_copy_image) {\n\t\tglCopyImageSubDataNV = (PFNGLCOPYIMAGESUBDATANVPROC)eglGetProcAddress(\"glCopyImageSubDataNV\");\n\t}\n\n\tgl_extensions.OES_vertex_array_object = strstr(extString, \"GL_OES_vertex_array_object\") != 0;\n\tif (gl_extensions.OES_vertex_array_object) {\n\t\tglGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glGenVertexArraysOES\" );\n\t\tglBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( \"glBindVertexArrayOES\" );\n\t\tglDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glDeleteVertexArraysOES\" );\n\t\tglIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( \"glIsVertexArrayOES\" );\n\t}\n\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\tif (gl_extensions.EXT_discard_framebuffer) {\n\t\tglDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress(\"glDiscardFramebufferEXT\");\n\t}\n#else\n\tgl_extensions.OES_vertex_array_object = false;\n\tgl_extensions.EXT_discard_framebuffer = false;\n#endif\n#else\n\t\/\/ Desktops support minmax and subimage unpack (GL_UNPACK_ROW_LENGTH etc)\n\tgl_extensions.EXT_blend_minmax = true;\n\tgl_extensions.EXT_unpack_subimage = true;\n#endif\n\t\/\/ GLES 3 subsumes many ES2 extensions.\n\tif (gl_extensions.GLES3) {\n\t\tgl_extensions.EXT_unpack_subimage = true;\n\t}\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.OES_mapbuffer) {\n\t\tglMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( \"glMapBufferOES\" );\n\t}\n\n\t\/\/ Look for EGL extensions\n\tEGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n\tconst char *eglString = eglQueryString(display, EGL_EXTENSIONS);\n\tif (eglString) {\n\t\tg_all_egl_extensions = eglString;\n\n\t\tgl_extensions.EGL_NV_system_time = strstr(eglString, \"EGL_NV_system_time\") != 0;\n\t\tgl_extensions.EGL_NV_coverage_sample = strstr(eglString, \"EGL_NV_coverage_sample\") != 0;\n\n\t\tif (gl_extensions.EGL_NV_system_time) {\n\t\t\teglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress(\"eglGetSystemTimeNV\");\n\t\t\teglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress(\"eglGetSystemTimeFrequencyNV\");\n\t\t}\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = false;\n\tgl_extensions.FBO_EXT = false;\n\tgl_extensions.PBO_ARB = true;\n\tif (extString) {\n\t\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\t\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n\t\tgl_extensions.PBO_ARB = strstr(extString, \"GL_ARB_pixel_buffer_object\") != 0;\n\t\tgl_extensions.ATIClampBug = ((strncmp(renderer, \"ATI RADEON X\", 12) == 0) || (strncmp(renderer, \"ATI MOBILITY RADEON X\", 21) == 0));\n\t}\n#endif\n\n\tProcessGPUFeatures();\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif (wglSwapIntervalEXT)\n\t\twglSwapIntervalEXT(interval);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_processing_channel.cpp\n\/\/\n\n#include \"yas_processing_channel.h\"\n#include \"yas_processing_event.h\"\n#include \"yas_processing_signal_event.h\"\n\nusing namespace yas;\n\n#pragma mark - processing::channel::impl\n\nstruct processing::channel::impl : base::impl {\n events_map_t _events;\n\n impl() {\n }\n\n impl(events_map_t &&events) : _events(std::move(events)) {\n }\n};\n\n#pragma mark - processing::channel\n\nprocessing::channel::channel() : base(std::make_shared<impl>()) {\n}\n\nprocessing::channel::channel(events_map_t events) : base(std::make_shared<impl>(std::move(events))) {\n}\n\nprocessing::channel::channel(std::nullptr_t) : base(nullptr) {\n}\n\nprocessing::channel::events_map_t const &processing::channel::events() const {\n return this->impl_ptr<impl>()->_events;\n}\n\nprocessing::channel::events_map_t &processing::channel::events() {\n return this->impl_ptr<impl>()->_events;\n}\n\nvoid processing::channel::insert_event(time time, event event) {\n if (!event.validate_time(time)) {\n throw \"invalid time for event.\";\n }\n\n this->impl_ptr<impl>()->_events.emplace(std::move(time), std::move(event));\n}\n\nvoid processing::channel::insert_events(events_map_t events) {\n for (auto &event_pair : events) {\n this->insert_event(event_pair.first, std::move(event_pair.second));\n }\n}\n\nprocessing::channel::events_map_t processing::channel::copied_events(time::range const ©_range) const {\n events_map_t result;\n\n for (auto const &event_pair : this->events()) {\n auto const &event_time = event_pair.first;\n auto const &event = event_pair.second;\n if (event_time.is_any_type()) {\n result.emplace(std::make_pair(event_time, event.copy()));\n } else if (event_time.is_frame_type()) {\n if (copy_range.is_contain(event_time.get<time::frame>())) {\n result.emplace(std::make_pair(event_time, event.copy()));\n }\n } else if (event_time.is_range_type()) {\n auto const &event_range = event_time.get<time::range>();\n if (auto const overlap_range_opt = copy_range.intersect(event_range)) {\n auto const &overlap_range = *overlap_range_opt;\n auto const signal = cast<signal_event>(event);\n auto copied_signal =\n signal.copy_in_range(time::range{overlap_range.frame - event_range.frame, overlap_range.length});\n result.emplace(std::make_pair(time{overlap_range}, std::move(copied_signal)));\n }\n } else {\n throw \"unreachable code.\";\n }\n }\n\n return result;\n}\n\nvoid processing::channel::erase_events(time::range const &erase_range) {\n signal_event::pair_vector_t remained_signal;\n\n erase_if(this->events(), [erase_range, &remained_signal](auto const &event_pair) {\n time const &event_time = event_pair.first;\n if (event_time.is_any_type()) {\n return true;\n } else if (event_time.is_frame_type()) {\n if (erase_range.is_contain(event_time.get<time::frame>())) {\n return true;\n }\n } else if (event_time.is_range_type()) {\n auto const &event_range = event_time.get<time::range>();\n if (auto overlapped_range = erase_range.intersect(event_range)) {\n auto const signal = cast<signal_event>(event_pair.second);\n auto const range = time::range{overlapped_range->frame - event_range.frame, overlapped_range->length};\n signal_event::pair_vector_t erased_signals = signal.erased_in_range(range);\n for (auto const &erased_signal : erased_signals) {\n auto const &erased_range = erased_signal.first;\n remained_signal.emplace_back(\n std::make_pair(time::range{erased_range.frame + event_range.frame, erased_range.length},\n erased_signal.second));\n }\n\n return true;\n }\n } else {\n throw \"unreachable code.\";\n }\n\n return false;\n });\n\n if (remained_signal.size() > 0) {\n for (auto const &signal_pair : remained_signal) {\n this->insert_event(time{signal_pair.first}, signal_pair.second);\n }\n }\n}\n<commit_msg>use offset<commit_after>\/\/\n\/\/ yas_processing_channel.cpp\n\/\/\n\n#include \"yas_processing_channel.h\"\n#include \"yas_processing_event.h\"\n#include \"yas_processing_signal_event.h\"\n\nusing namespace yas;\n\n#pragma mark - processing::channel::impl\n\nstruct processing::channel::impl : base::impl {\n events_map_t _events;\n\n impl() {\n }\n\n impl(events_map_t &&events) : _events(std::move(events)) {\n }\n};\n\n#pragma mark - processing::channel\n\nprocessing::channel::channel() : base(std::make_shared<impl>()) {\n}\n\nprocessing::channel::channel(events_map_t events) : base(std::make_shared<impl>(std::move(events))) {\n}\n\nprocessing::channel::channel(std::nullptr_t) : base(nullptr) {\n}\n\nprocessing::channel::events_map_t const &processing::channel::events() const {\n return this->impl_ptr<impl>()->_events;\n}\n\nprocessing::channel::events_map_t &processing::channel::events() {\n return this->impl_ptr<impl>()->_events;\n}\n\nvoid processing::channel::insert_event(time time, event event) {\n if (!event.validate_time(time)) {\n throw \"invalid time for event.\";\n }\n\n this->impl_ptr<impl>()->_events.emplace(std::move(time), std::move(event));\n}\n\nvoid processing::channel::insert_events(events_map_t events) {\n for (auto &event_pair : events) {\n this->insert_event(event_pair.first, std::move(event_pair.second));\n }\n}\n\nprocessing::channel::events_map_t processing::channel::copied_events(time::range const ©_range) const {\n events_map_t result;\n\n for (auto const &event_pair : this->events()) {\n auto const &event_time = event_pair.first;\n auto const &event = event_pair.second;\n if (event_time.is_any_type()) {\n result.emplace(std::make_pair(event_time, event.copy()));\n } else if (event_time.is_frame_type()) {\n if (copy_range.is_contain(event_time.get<time::frame>())) {\n result.emplace(std::make_pair(event_time, event.copy()));\n }\n } else if (event_time.is_range_type()) {\n auto const &event_range = event_time.get<time::range>();\n if (auto const overlap_range_opt = copy_range.intersect(event_range)) {\n auto const &overlap_range = *overlap_range_opt;\n auto const signal = cast<signal_event>(event);\n auto copied_signal =\n signal.copy_in_range(time::range{overlap_range.frame - event_range.frame, overlap_range.length});\n result.emplace(std::make_pair(time{overlap_range}, std::move(copied_signal)));\n }\n } else {\n throw \"unreachable code.\";\n }\n }\n\n return result;\n}\n\nvoid processing::channel::erase_events(time::range const &erase_range) {\n signal_event::pair_vector_t remained_signal;\n\n erase_if(this->events(), [erase_range, &remained_signal](auto const &event_pair) {\n time const &event_time = event_pair.first;\n if (event_time.is_any_type()) {\n return true;\n } else if (event_time.is_frame_type()) {\n if (erase_range.is_contain(event_time.get<time::frame>())) {\n return true;\n }\n } else if (event_time.is_range_type()) {\n auto const &event_range = event_time.get<time::range>();\n if (auto overlapped_range = erase_range.intersect(event_range)) {\n auto const signal = cast<signal_event>(event_pair.second);\n auto const range = time::range{overlapped_range->frame - event_range.frame, overlapped_range->length};\n signal_event::pair_vector_t erased_signals = signal.erased_in_range(range);\n for (auto const &erased_signal : erased_signals) {\n auto const &erased_range = erased_signal.first;\n remained_signal.emplace_back(\n std::make_pair(erased_range.offset(event_range.frame), erased_signal.second));\n }\n\n return true;\n }\n } else {\n throw \"unreachable code.\";\n }\n\n return false;\n });\n\n if (remained_signal.size() > 0) {\n for (auto const &signal_pair : remained_signal) {\n this->insert_event(time{signal_pair.first}, signal_pair.second);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"proctor\/scanning_model_source.h\"\n\n#include <cstdio>\n#include <vector>\n#include <sstream>\n#include <fstream>\n\n#include <vtkCellArray.h>\n#include <vtkFloatArray.h>\n#include <vtkPoints.h>\n#include <vtkSmartPointer.h>\n\n#include <pcl\/filters\/filter.h>\n#include <pcl\/filters\/voxel_grid.h>\n#include <pcl\/io\/ply_io.h>\n#include <pcl\/common\/eigen.h>\n#include <pcl\/common\/transforms.h>\n#include <pcl\/common\/common.h>\n\n#include \"proctor\/PSBClaParse.h\"\n\nnamespace pcl\n{\n\n namespace proctor\n {\n\n const float theta_start = M_PI \/ 12;\n const float theta_step = 0.0f;\n const int theta_count = 1;\n const float phi_start = 0.0f;\n const float phi_step = M_PI \/ 6;\n const int phi_count = 12;\n const float theta_min = 0.0f;\n const float theta_max = M_PI \/ 6;\n const float phi_min = 0.0f;\n const float phi_max = M_PI * 2;\n\n IndicesPtr\n ScanningModelSource::randomSubset(int n, int r)\n {\n IndicesPtr subset (new std::vector<int>());\n std::vector<int> bag (n);\n for (int i = 0; i < n; i++) bag[i] = i;\n int edge = n;\n subset->resize(r);\n for (int i = 0; i < r; i++) {\n int pick = rand() % edge;\n (*subset)[i] = bag[pick];\n bag[pick] = bag[--edge];\n }\n return subset;\n }\n\n \/\/ TODO Finish this\n void\n ScanningModelSource::pickUniqueModels(std::vector<int>& ids)\n {\n std::stringstream path;\n path << dir_ << \"\/classification\/v1\/base\/test.cla\";\n\n PSBCategoryList* list = parseFile((char *) (path.str().c_str()), false);\n\n ids.clear();\n for (int i = 0; i < list->_numCategories; i++)\n {\n PSBCategory *category = list->_categories[i];\n\n if (category->_numModels > 0)\n {\n \/\/ Pick the first model from each category\n char* model = category->_models[0];\n ids.push_back(atoi(model));\n }\n }\n\n }\n\n void\n ScanningModelSource::loadModels()\n {\n std::vector<int> ids;\n pickUniqueModels(ids);\n\n \/\/int max_models = 1814;\n \/\/srand(0);\n \/\/IndicesPtr model_subset = randomSubset(max_models, max_models);\n\n \/\/for (int mi = 0; mi < ids.size(); mi++) {\n for (auto it = ids.begin(); it != ids.end(); ++it)\n {\n int id = *it;\n std::stringstream path;\n FILE *file;\n int vertices, faces, edges;\n\n \/\/ Put model in map\n Model* new_model = new Model;\n std::stringstream ss;\n ss << name_ << id;\n std::string new_id = ss.str();\n new_model->id = new_id;\n\n \/\/ read mesh\n path << dir_ << \"\/db\/\" << id \/ 100 << \"\/m\" << id << \"\/m\" << id << \".off\";\n file = fopen(path.str ().c_str (), \"r\");\n\n if (file == NULL) {\n cerr << \"Could not find \" << path.str() << endl;\n continue;\n \/\/exit(-1);\n }\n\n int line = 1;\n\n \/\/ read header\n if (fscanf(file, \"OFF\\n%d %d %d\\n\", &vertices, &faces, &edges) != 3) {\n cerr << \"invalid OFF header in file \" << path << endl;\n exit(-1);\n } else {\n line += 2;\n }\n\n \/\/ read vertices\n vtkFloatArray *fa = vtkFloatArray::New();\n fa->SetNumberOfComponents(3);\n float (*v)[3] = reinterpret_cast<float (*)[3]>(fa->WritePointer(0, 3 * vertices));\n for (int j = 0; j < vertices; j++) {\n if (fscanf(file, \"%f %f %f\\n\", &v[j][0], &v[j][1], &v[j][2]) != 3) {\n cerr << \"invalid vertex in file \" << path << \" on line \" << line << endl;\n exit(-1);\n } else {\n ++line;\n }\n }\n vtkPoints *p = vtkPoints::New();\n p->SetData(fa); fa->Delete();\n\n \/\/ read faces\n vtkCellArray *ca = vtkCellArray::New();\n vtkIdType (*f)[4] = reinterpret_cast<vtkIdType (*)[4]>(ca->WritePointer(faces, 4 * faces));\n for (int j = 0; j < faces; j++) {\n f[j][0] = 3; \/\/ only supports triangles...\n if (fscanf (file, \"3 %lld %lld %lld\\n\", (long long int*)&f[j][1], (long long int*)&f[j][2], (long long int*)&f[j][3]) != 3) \n {\n cerr << \"invalid face in file \" << path << \" on line \" << line << endl;\n exit(-1);\n } else {\n ++line;\n }\n }\n\n fclose(file);\n\n\n vtkPolyData* new_mesh = vtkPolyData::New();\n new_mesh->SetPoints(p);\/\/ p->Delete();\n new_mesh->SetPolys(ca);\/\/ ca->Delete();\n\n new_model->mesh = new_mesh->GetProducerPort();\n\n \/\/ read metadata\n path.str (\"\");\n path << dir_ << \"\/db\/\" << id \/ 100 << \"\/m\" << id << \"\/m\" << id << \"_info.txt\";\n file = fopen(path.str ().c_str (), \"r\");\n while (!feof(file)) {\n char buf[256];\n if (fgets(buf, sizeof(buf), file) != NULL) {\n if (!strncmp(\"center: \", buf, 8)) {\n if (sscanf(buf, \"center: (%f,%f,%f)\\n\", &new_model->cx, &new_model->cy, &new_model->cz) != 3) {\n cerr << \"invalid centroid in file \" << path << endl;\n cerr << buf;\n exit(-1);\n }\n } else if (!strncmp(\"scale: \", buf, 7)) {\n if (sscanf(buf, \"scale: %f\\n\", &new_model->scale) != 1) {\n cerr << \"invalid scale in file \" << path << endl;\n cerr << buf;\n exit(-1);\n }\n }\n }\n } \/\/ end while over info lines\n fclose(file);\n\n models_[new_id] = *new_model;\n } \/\/ end for over models\n }\n\n void\n ScanningModelSource::getModelIDs(std::vector<std::string> &output)\n {\n std::map<std::string, Model>::iterator it;\n output.clear();\n\n for ( it = models_.begin() ; it != models_.end(); it++ ) {\n output.push_back((*it).first);\n }\n \/\/output.push_back(\"princeton1298\");\n \/\/output.push_back(\"princeton1303\");\n \/\/output.push_back(\"princeton48\");\n \/\/output.push_back(\"princeton97\");\n \/\/output.push_back(\"princeton99\");\n \/\/output.push_back(\"princeton70\");\n \/\/output.push_back(\"princeton725\");\n \/\/output.push_back(\"princeton688\");\n \/\/output.push_back(\"princeton1779\");\n \/\/output.push_back(\"princeton382\");\n \/\/output.push_back(\"princeton398\");\n \/\/output.push_back(\"princeton407\");\n\n sort(output.begin(), output.end());\n }\n\n PointCloud<PointNormal>::Ptr\n ScanningModelSource::getTrainingModel(std::string model_id)\n {\n PointCloud<PointNormal>::Ptr full_cloud(new PointCloud<PointNormal>());\n\n for (int ti = 0; ti < theta_count; ti++) {\n for (int pi = 0; pi < phi_count; pi++) {\n float theta = Scanner::theta_start + ti * Scanner::theta_step;\n float phi = Scanner::phi_start + pi * Scanner::phi_step;\n\n *full_cloud += *Scanner::getCloudCached(theta, phi, models_[model_id]);\n flush(cout << '.');\n }\n }\n cout << endl;\n\n \/\/ Remove NaNs\n PointCloud<PointNormal>::Ptr dense_cloud (new PointCloud<PointNormal>());\n\n std::vector<int> index;\n pcl::removeNaNFromPointCloud<PointNormal>(*full_cloud, *dense_cloud, index);\n\n PointCloud<PointNormal>::Ptr cloud_subsampled (new PointCloud<PointNormal> ());\n VoxelGrid<PointNormal> subsampling_filter;\n subsampling_filter.setInputCloud(dense_cloud);\n subsampling_filter.setLeafSize(0.001, 0.001, 0.001);\n subsampling_filter.filter(*cloud_subsampled);\n\n assert(cloud_subsampled->is_dense == true);\n\n return cloud_subsampled;\n }\n\n PointCloud<PointNormal>::Ptr\n ScanningModelSource::getTestModel(std::string model_id)\n {\n float theta = (*theta_gen)();\n float phi = (*phi_gen)();\n\n cout << \"Theta: \" << theta << endl;\n cout << \"Phi: \" << phi << endl;\n\n PointCloud<PointNormal>::Ptr test_scan = Scanner::getCloudCached(theta, phi, models_[model_id]);\n Eigen::Affine3f t;\n getTransformation(0, 0, 0, M_PI, 0.5, 1.5, t);\n PointCloud<PointNormal>::Ptr rotated_scan(new PointCloud<PointNormal>());\n transformPointCloudWithNormals(*test_scan, *rotated_scan, t);\n \/\/return test_scan;\n return rotated_scan;\n }\n\n void\n ScanningModelSource::resetTestGenerator()\n {\n rng_.seed(0);\n theta_u = boost::uniform_real<float>(theta_min, theta_max);\n phi_u = boost::uniform_real<float>(phi_min, phi_max);\n theta_gen = new boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >(rng_, theta_u);\n phi_gen = new boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >(rng_, phi_u);\n }\n }\n\n}\n<commit_msg>auto->int<commit_after>#include \"proctor\/scanning_model_source.h\"\n\n#include <cstdio>\n#include <vector>\n#include <sstream>\n#include <fstream>\n\n#include <vtkCellArray.h>\n#include <vtkFloatArray.h>\n#include <vtkPoints.h>\n#include <vtkSmartPointer.h>\n\n#include <pcl\/filters\/filter.h>\n#include <pcl\/filters\/voxel_grid.h>\n#include <pcl\/io\/ply_io.h>\n#include <pcl\/common\/eigen.h>\n#include <pcl\/common\/transforms.h>\n#include <pcl\/common\/common.h>\n\n#include \"proctor\/PSBClaParse.h\"\n\nnamespace pcl\n{\n\n namespace proctor\n {\n\n const float theta_start = M_PI \/ 12;\n const float theta_step = 0.0f;\n const int theta_count = 1;\n const float phi_start = 0.0f;\n const float phi_step = M_PI \/ 6;\n const int phi_count = 12;\n const float theta_min = 0.0f;\n const float theta_max = M_PI \/ 6;\n const float phi_min = 0.0f;\n const float phi_max = M_PI * 2;\n\n IndicesPtr\n ScanningModelSource::randomSubset(int n, int r)\n {\n IndicesPtr subset (new std::vector<int>());\n std::vector<int> bag (n);\n for (int i = 0; i < n; i++) bag[i] = i;\n int edge = n;\n subset->resize(r);\n for (int i = 0; i < r; i++) {\n int pick = rand() % edge;\n (*subset)[i] = bag[pick];\n bag[pick] = bag[--edge];\n }\n return subset;\n }\n\n \/\/ TODO Finish this\n void\n ScanningModelSource::pickUniqueModels(std::vector<int>& ids)\n {\n std::stringstream path;\n path << dir_ << \"\/classification\/v1\/base\/test.cla\";\n\n PSBCategoryList* list = parseFile((char *) (path.str().c_str()), false);\n\n ids.clear();\n for (int i = 0; i < list->_numCategories; i++)\n {\n PSBCategory *category = list->_categories[i];\n\n if (category->_numModels > 0)\n {\n \/\/ Pick the first model from each category\n char* model = category->_models[0];\n ids.push_back(atoi(model));\n }\n }\n\n }\n\n void\n ScanningModelSource::loadModels()\n {\n std::vector<int> ids;\n pickUniqueModels(ids);\n\n \/\/int max_models = 1814;\n \/\/srand(0);\n \/\/IndicesPtr model_subset = randomSubset(max_models, max_models);\n\n \/\/for (int mi = 0; mi < ids.size(); mi++) {\n for (int it = ids.begin(); it != ids.end(); ++it)\n {\n int id = *it;\n std::stringstream path;\n FILE *file;\n int vertices, faces, edges;\n\n \/\/ Put model in map\n Model* new_model = new Model;\n std::stringstream ss;\n ss << name_ << id;\n std::string new_id = ss.str();\n new_model->id = new_id;\n\n \/\/ read mesh\n path << dir_ << \"\/db\/\" << id \/ 100 << \"\/m\" << id << \"\/m\" << id << \".off\";\n file = fopen(path.str ().c_str (), \"r\");\n\n if (file == NULL) {\n cerr << \"Could not find \" << path.str() << endl;\n continue;\n \/\/exit(-1);\n }\n\n int line = 1;\n\n \/\/ read header\n if (fscanf(file, \"OFF\\n%d %d %d\\n\", &vertices, &faces, &edges) != 3) {\n cerr << \"invalid OFF header in file \" << path << endl;\n exit(-1);\n } else {\n line += 2;\n }\n\n \/\/ read vertices\n vtkFloatArray *fa = vtkFloatArray::New();\n fa->SetNumberOfComponents(3);\n float (*v)[3] = reinterpret_cast<float (*)[3]>(fa->WritePointer(0, 3 * vertices));\n for (int j = 0; j < vertices; j++) {\n if (fscanf(file, \"%f %f %f\\n\", &v[j][0], &v[j][1], &v[j][2]) != 3) {\n cerr << \"invalid vertex in file \" << path << \" on line \" << line << endl;\n exit(-1);\n } else {\n ++line;\n }\n }\n vtkPoints *p = vtkPoints::New();\n p->SetData(fa); fa->Delete();\n\n \/\/ read faces\n vtkCellArray *ca = vtkCellArray::New();\n vtkIdType (*f)[4] = reinterpret_cast<vtkIdType (*)[4]>(ca->WritePointer(faces, 4 * faces));\n for (int j = 0; j < faces; j++) {\n f[j][0] = 3; \/\/ only supports triangles...\n if (fscanf (file, \"3 %lld %lld %lld\\n\", (long long int*)&f[j][1], (long long int*)&f[j][2], (long long int*)&f[j][3]) != 3) \n {\n cerr << \"invalid face in file \" << path << \" on line \" << line << endl;\n exit(-1);\n } else {\n ++line;\n }\n }\n\n fclose(file);\n\n\n vtkPolyData* new_mesh = vtkPolyData::New();\n new_mesh->SetPoints(p);\/\/ p->Delete();\n new_mesh->SetPolys(ca);\/\/ ca->Delete();\n\n new_model->mesh = new_mesh->GetProducerPort();\n\n \/\/ read metadata\n path.str (\"\");\n path << dir_ << \"\/db\/\" << id \/ 100 << \"\/m\" << id << \"\/m\" << id << \"_info.txt\";\n file = fopen(path.str ().c_str (), \"r\");\n while (!feof(file)) {\n char buf[256];\n if (fgets(buf, sizeof(buf), file) != NULL) {\n if (!strncmp(\"center: \", buf, 8)) {\n if (sscanf(buf, \"center: (%f,%f,%f)\\n\", &new_model->cx, &new_model->cy, &new_model->cz) != 3) {\n cerr << \"invalid centroid in file \" << path << endl;\n cerr << buf;\n exit(-1);\n }\n } else if (!strncmp(\"scale: \", buf, 7)) {\n if (sscanf(buf, \"scale: %f\\n\", &new_model->scale) != 1) {\n cerr << \"invalid scale in file \" << path << endl;\n cerr << buf;\n exit(-1);\n }\n }\n }\n } \/\/ end while over info lines\n fclose(file);\n\n models_[new_id] = *new_model;\n } \/\/ end for over models\n }\n\n void\n ScanningModelSource::getModelIDs(std::vector<std::string> &output)\n {\n std::map<std::string, Model>::iterator it;\n output.clear();\n\n for ( it = models_.begin() ; it != models_.end(); it++ ) {\n output.push_back((*it).first);\n }\n \/\/output.push_back(\"princeton1298\");\n \/\/output.push_back(\"princeton1303\");\n \/\/output.push_back(\"princeton48\");\n \/\/output.push_back(\"princeton97\");\n \/\/output.push_back(\"princeton99\");\n \/\/output.push_back(\"princeton70\");\n \/\/output.push_back(\"princeton725\");\n \/\/output.push_back(\"princeton688\");\n \/\/output.push_back(\"princeton1779\");\n \/\/output.push_back(\"princeton382\");\n \/\/output.push_back(\"princeton398\");\n \/\/output.push_back(\"princeton407\");\n\n sort(output.begin(), output.end());\n }\n\n PointCloud<PointNormal>::Ptr\n ScanningModelSource::getTrainingModel(std::string model_id)\n {\n PointCloud<PointNormal>::Ptr full_cloud(new PointCloud<PointNormal>());\n\n for (int ti = 0; ti < theta_count; ti++) {\n for (int pi = 0; pi < phi_count; pi++) {\n float theta = Scanner::theta_start + ti * Scanner::theta_step;\n float phi = Scanner::phi_start + pi * Scanner::phi_step;\n\n *full_cloud += *Scanner::getCloudCached(theta, phi, models_[model_id]);\n flush(cout << '.');\n }\n }\n cout << endl;\n\n \/\/ Remove NaNs\n PointCloud<PointNormal>::Ptr dense_cloud (new PointCloud<PointNormal>());\n\n std::vector<int> index;\n pcl::removeNaNFromPointCloud<PointNormal>(*full_cloud, *dense_cloud, index);\n\n PointCloud<PointNormal>::Ptr cloud_subsampled (new PointCloud<PointNormal> ());\n VoxelGrid<PointNormal> subsampling_filter;\n subsampling_filter.setInputCloud(dense_cloud);\n subsampling_filter.setLeafSize(0.001, 0.001, 0.001);\n subsampling_filter.filter(*cloud_subsampled);\n\n assert(cloud_subsampled->is_dense == true);\n\n return cloud_subsampled;\n }\n\n PointCloud<PointNormal>::Ptr\n ScanningModelSource::getTestModel(std::string model_id)\n {\n float theta = (*theta_gen)();\n float phi = (*phi_gen)();\n\n cout << \"Theta: \" << theta << endl;\n cout << \"Phi: \" << phi << endl;\n\n PointCloud<PointNormal>::Ptr test_scan = Scanner::getCloudCached(theta, phi, models_[model_id]);\n Eigen::Affine3f t;\n getTransformation(0, 0, 0, M_PI, 0.5, 1.5, t);\n PointCloud<PointNormal>::Ptr rotated_scan(new PointCloud<PointNormal>());\n transformPointCloudWithNormals(*test_scan, *rotated_scan, t);\n \/\/return test_scan;\n return rotated_scan;\n }\n\n void\n ScanningModelSource::resetTestGenerator()\n {\n rng_.seed(0);\n theta_u = boost::uniform_real<float>(theta_min, theta_max);\n phi_u = boost::uniform_real<float>(phi_min, phi_max);\n theta_gen = new boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >(rng_, theta_u);\n phi_gen = new boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >(rng_, phi_u);\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-- includes -----\n#include \"ClientControllerView.h\"\n#include \"PSMoveProtocol.pb.h\"\n#include <chrono>\n#include <assert.h>\n\n\/\/-- pre-declarations -----\n\n\/\/-- constants -----\nconst PSMoveVector3 g_psmove_vector3_zero= {0.f, 0.f, 0.f};\nconst PSMoveVector3 *k_psmove_vector3_zero= &g_psmove_vector3_zero;\n\nconst PSMoveQuaternion g_psmove_quaternion_identity= {1.f, 0.f, 0.f, 0.f};\nconst PSMoveQuaternion *k_psmove_quaternion_identity= &g_psmove_quaternion_identity;\n\n\/\/-- prototypes ----\nstatic void update_button_state(PSMoveButtonState &button, unsigned int button_bitmask, unsigned int button_bit);\n\n\/\/-- implementation -----\n\n\/\/-- ClientPSMoveView -----\nvoid ClientPSMoveView::Clear()\n{\n bValid= false;\n bIsTrackingEnabled= false;\n bIsCurrentlyTracking= false;\n\n Pose.Clear();\n\n TriangleButton= PSMoveButton_UP;\n CircleButton= PSMoveButton_UP;\n CrossButton= PSMoveButton_UP;\n SquareButton= PSMoveButton_UP;\n SelectButton= PSMoveButton_UP;\n StartButton= PSMoveButton_UP;\n PSButton= PSMoveButton_UP;\n MoveButton= PSMoveButton_UP;\n TriggerButton= PSMoveButton_UP;\n\n TriggerValue= 0;\n}\n\nvoid ClientPSMoveView::ApplyControllerDataFrame(const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n if (data_frame->isconnected())\n {\n const PSMoveProtocol::ControllerDataFrame_PSMoveState &psmove_data_frame= data_frame->psmove_state();\n\n this->bIsTrackingEnabled= psmove_data_frame.istrackingenabled();\n this->bIsCurrentlyTracking= psmove_data_frame.iscurrentlytracking();\n\n this->Pose.Orientation.w= psmove_data_frame.orientation().w();\n this->Pose.Orientation.x= psmove_data_frame.orientation().x();\n this->Pose.Orientation.y= psmove_data_frame.orientation().y();\n this->Pose.Orientation.z= psmove_data_frame.orientation().z();\n\n this->Pose.Position.x= psmove_data_frame.position().x();\n this->Pose.Position.y= psmove_data_frame.position().y();\n this->Pose.Position.z= psmove_data_frame.position().z();\n\n unsigned int button_bitmask= data_frame->button_down_bitmask();\n update_button_state(TriangleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIANGLE);\n update_button_state(CircleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CIRCLE);\n update_button_state(CrossButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CROSS);\n update_button_state(SquareButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_SQUARE);\n update_button_state(SelectButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_SELECT);\n update_button_state(StartButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_START);\n update_button_state(PSButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_PS);\n update_button_state(MoveButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_MOVE);\n update_button_state(TriggerButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIGGER);\n\n \/\/###bwalker $TODO make sure this is in the range [0, 255]\n this->TriggerValue= static_cast<unsigned char>(psmove_data_frame.trigger_value());\n\n this->bValid= true;\n }\n else\n {\n Clear();\n }\n}\n\n\/\/-- ClientPSNaviView -----\nvoid ClientPSNaviView::Clear()\n{\n bValid= false;\n\n L1Button= PSMoveButton_UP;\n L2Button= PSMoveButton_UP;\n L3Button= PSMoveButton_UP;\n CircleButton= PSMoveButton_UP;\n CrossButton= PSMoveButton_UP;\n PSButton= PSMoveButton_UP;\n TriggerButton= PSMoveButton_UP;\n DPadUpButton= PSMoveButton_UP;\n DPadRightButton= PSMoveButton_UP;\n DPadDownButton= PSMoveButton_UP;\n DPadLeftButton= PSMoveButton_UP;\n\n TriggerValue= 0;\n Stick_XAxis= 0x80;\n Stick_YAxis= 0x80;\n}\n\nvoid ClientPSNaviView::ApplyControllerDataFrame(const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n if (data_frame->isconnected())\n {\n const PSMoveProtocol::ControllerDataFrame_PSNaviState &psnavi_data_frame= data_frame->psnavi_state();\n\n unsigned int button_bitmask= data_frame->button_down_bitmask();\n update_button_state(L1Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L1);\n update_button_state(L2Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L2);\n update_button_state(L3Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L3);\n update_button_state(CircleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CIRCLE);\n update_button_state(CrossButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CROSS);\n update_button_state(PSButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_PS);\n update_button_state(TriggerButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIGGER);\n update_button_state(DPadUpButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_UP);\n update_button_state(DPadRightButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_RIGHT);\n update_button_state(DPadDownButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_DOWN);\n update_button_state(DPadLeftButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_LEFT);\n\n \/\/###bwalker $TODO make sure this is in the range [0, 255]\n this->TriggerValue= static_cast<unsigned char>(psnavi_data_frame.trigger_value());\n this->Stick_XAxis= static_cast<unsigned char>(psnavi_data_frame.stick_xaxis());\n this->Stick_YAxis= static_cast<unsigned char>(psnavi_data_frame.stick_yaxis());\n\n this->bValid= true;\n }\n else\n {\n Clear();\n }\n}\n\n\/\/-- ClientControllerView -----\nClientControllerView::ClientControllerView(int PSMoveID)\n{\n Clear();\n this->ControllerID= PSMoveID;\n}\n\nvoid ClientControllerView::Clear()\n{\n ControllerID = -1;\n SequenceNum= -1;\n ListenerCount= 0;\n\n IsConnected= false;\n\n ControllerViewType= None;\n memset(&ViewState, 0, sizeof(ViewState));\n\n data_frame_last_received_time= \n std::chrono::duration_cast< std::chrono::milliseconds >(\n std::chrono::system_clock::now().time_since_epoch()).count();\n data_frame_average_fps= 0.f;\n}\n\nvoid ClientControllerView::ApplyControllerDataFrame(\n const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n assert(data_frame->controller_id() == ControllerID);\n\n \/\/ Compute the data frame receive window statistics if we have received enough samples\n {\n long long now = \n std::chrono::duration_cast< std::chrono::milliseconds >(\n std::chrono::system_clock::now().time_since_epoch()).count();\n float seconds= static_cast<float>(now - data_frame_last_received_time) \/ 1000.f;\n float fps= 1.f \/ seconds;\n\n data_frame_average_fps= (0.9f)*data_frame_average_fps + (0.1f)*fps;\n data_frame_last_received_time= now;\n }\n\n if (data_frame->sequence_num() > this->SequenceNum)\n {\n this->SequenceNum= data_frame->sequence_num();\n this->IsConnected= data_frame->isconnected();\n\n switch(data_frame->controller_type())\n {\n case PSMoveProtocol::ControllerDataFrame_ControllerType_PSMOVE:\n {\n this->ControllerViewType= PSMove;\n this->ViewState.PSMoveView.ApplyControllerDataFrame(data_frame);\n } break;\n\n case PSMoveProtocol::ControllerDataFrame_ControllerType_PSNAVI:\n {\n this->ControllerViewType= PSNavi;\n this->ViewState.PSNaviView.ApplyControllerDataFrame(data_frame);\n } break;\n\n default:\n assert(0 && \"Unhandled controller type\");\n }\n }\n}\n\n\/\/-- helper functions -----\nstatic void update_button_state(\n PSMoveButtonState &button,\n unsigned int button_bitmask,\n unsigned int button_bit)\n{\n const bool is_down= (button_bitmask & (1 << button_bit)) > 0;\n\n switch (button)\n {\n case PSMoveButton_UP:\n button= is_down ? PSMoveButton_PRESSED : PSMoveButton_UP;\n break;\n case PSMoveButton_PRESSED:\n button= is_down ? PSMoveButton_DOWN : PSMoveButton_RELEASED;\n break;\n case PSMoveButton_DOWN:\n button= is_down ? PSMoveButton_DOWN : PSMoveButton_RELEASED;\n break;\n case PSMoveButton_RELEASED:\n button= is_down ? PSMoveButton_PRESSED : PSMoveButton_UP;\n break;\n };\n}<commit_msg>Fixed uncaught divide by zero case in client controller view update fps calculation.<commit_after>\/\/-- includes -----\n#include \"ClientControllerView.h\"\n#include \"PSMoveProtocol.pb.h\"\n#include <chrono>\n#include <assert.h>\n\n\/\/-- pre-declarations -----\n\n\/\/-- constants -----\nconst PSMoveVector3 g_psmove_vector3_zero= {0.f, 0.f, 0.f};\nconst PSMoveVector3 *k_psmove_vector3_zero= &g_psmove_vector3_zero;\n\nconst PSMoveQuaternion g_psmove_quaternion_identity= {1.f, 0.f, 0.f, 0.f};\nconst PSMoveQuaternion *k_psmove_quaternion_identity= &g_psmove_quaternion_identity;\n\n\/\/-- prototypes ----\nstatic void update_button_state(PSMoveButtonState &button, unsigned int button_bitmask, unsigned int button_bit);\n\n\/\/-- implementation -----\n\n\/\/-- ClientPSMoveView -----\nvoid ClientPSMoveView::Clear()\n{\n bValid= false;\n bIsTrackingEnabled= false;\n bIsCurrentlyTracking= false;\n\n Pose.Clear();\n\n TriangleButton= PSMoveButton_UP;\n CircleButton= PSMoveButton_UP;\n CrossButton= PSMoveButton_UP;\n SquareButton= PSMoveButton_UP;\n SelectButton= PSMoveButton_UP;\n StartButton= PSMoveButton_UP;\n PSButton= PSMoveButton_UP;\n MoveButton= PSMoveButton_UP;\n TriggerButton= PSMoveButton_UP;\n\n TriggerValue= 0;\n}\n\nvoid ClientPSMoveView::ApplyControllerDataFrame(const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n if (data_frame->isconnected())\n {\n const PSMoveProtocol::ControllerDataFrame_PSMoveState &psmove_data_frame= data_frame->psmove_state();\n\n this->bIsTrackingEnabled= psmove_data_frame.istrackingenabled();\n this->bIsCurrentlyTracking= psmove_data_frame.iscurrentlytracking();\n\n this->Pose.Orientation.w= psmove_data_frame.orientation().w();\n this->Pose.Orientation.x= psmove_data_frame.orientation().x();\n this->Pose.Orientation.y= psmove_data_frame.orientation().y();\n this->Pose.Orientation.z= psmove_data_frame.orientation().z();\n\n this->Pose.Position.x= psmove_data_frame.position().x();\n this->Pose.Position.y= psmove_data_frame.position().y();\n this->Pose.Position.z= psmove_data_frame.position().z();\n\n unsigned int button_bitmask= data_frame->button_down_bitmask();\n update_button_state(TriangleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIANGLE);\n update_button_state(CircleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CIRCLE);\n update_button_state(CrossButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CROSS);\n update_button_state(SquareButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_SQUARE);\n update_button_state(SelectButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_SELECT);\n update_button_state(StartButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_START);\n update_button_state(PSButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_PS);\n update_button_state(MoveButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_MOVE);\n update_button_state(TriggerButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIGGER);\n\n \/\/###bwalker $TODO make sure this is in the range [0, 255]\n this->TriggerValue= static_cast<unsigned char>(psmove_data_frame.trigger_value());\n\n this->bValid= true;\n }\n else\n {\n Clear();\n }\n}\n\n\/\/-- ClientPSNaviView -----\nvoid ClientPSNaviView::Clear()\n{\n bValid= false;\n\n L1Button= PSMoveButton_UP;\n L2Button= PSMoveButton_UP;\n L3Button= PSMoveButton_UP;\n CircleButton= PSMoveButton_UP;\n CrossButton= PSMoveButton_UP;\n PSButton= PSMoveButton_UP;\n TriggerButton= PSMoveButton_UP;\n DPadUpButton= PSMoveButton_UP;\n DPadRightButton= PSMoveButton_UP;\n DPadDownButton= PSMoveButton_UP;\n DPadLeftButton= PSMoveButton_UP;\n\n TriggerValue= 0;\n Stick_XAxis= 0x80;\n Stick_YAxis= 0x80;\n}\n\nvoid ClientPSNaviView::ApplyControllerDataFrame(const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n if (data_frame->isconnected())\n {\n const PSMoveProtocol::ControllerDataFrame_PSNaviState &psnavi_data_frame= data_frame->psnavi_state();\n\n unsigned int button_bitmask= data_frame->button_down_bitmask();\n update_button_state(L1Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L1);\n update_button_state(L2Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L2);\n update_button_state(L3Button, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_L3);\n update_button_state(CircleButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CIRCLE);\n update_button_state(CrossButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_CROSS);\n update_button_state(PSButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_PS);\n update_button_state(TriggerButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_TRIGGER);\n update_button_state(DPadUpButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_UP);\n update_button_state(DPadRightButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_RIGHT);\n update_button_state(DPadDownButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_DOWN);\n update_button_state(DPadLeftButton, button_bitmask, PSMoveProtocol::ControllerDataFrame_ButtonType_LEFT);\n\n \/\/###bwalker $TODO make sure this is in the range [0, 255]\n this->TriggerValue= static_cast<unsigned char>(psnavi_data_frame.trigger_value());\n this->Stick_XAxis= static_cast<unsigned char>(psnavi_data_frame.stick_xaxis());\n this->Stick_YAxis= static_cast<unsigned char>(psnavi_data_frame.stick_yaxis());\n\n this->bValid= true;\n }\n else\n {\n Clear();\n }\n}\n\n\/\/-- ClientControllerView -----\nClientControllerView::ClientControllerView(int PSMoveID)\n{\n Clear();\n this->ControllerID= PSMoveID;\n}\n\nvoid ClientControllerView::Clear()\n{\n ControllerID = -1;\n SequenceNum= -1;\n ListenerCount= 0;\n\n IsConnected= false;\n\n ControllerViewType= None;\n memset(&ViewState, 0, sizeof(ViewState));\n\n data_frame_last_received_time= \n std::chrono::duration_cast< std::chrono::milliseconds >(\n std::chrono::system_clock::now().time_since_epoch()).count();\n data_frame_average_fps= 0.f;\n}\n\nvoid ClientControllerView::ApplyControllerDataFrame(\n const PSMoveProtocol::ControllerDataFrame *data_frame)\n{\n assert(data_frame->controller_id() == ControllerID);\n\n \/\/ Compute the data frame receive window statistics if we have received enough samples\n {\n long long now = \n std::chrono::duration_cast< std::chrono::milliseconds >(\n std::chrono::system_clock::now().time_since_epoch()).count();\n long long diff= now - data_frame_last_received_time;\n\n if (diff > 0)\n {\n float seconds= static_cast<float>(diff) \/ 1000.f;\n float fps= 1.f \/ seconds;\n\n data_frame_average_fps= (0.9f)*data_frame_average_fps + (0.1f)*fps;\n }\n\n data_frame_last_received_time= now;\n }\n\n if (data_frame->sequence_num() > this->SequenceNum)\n {\n this->SequenceNum= data_frame->sequence_num();\n this->IsConnected= data_frame->isconnected();\n\n switch(data_frame->controller_type())\n {\n case PSMoveProtocol::ControllerDataFrame_ControllerType_PSMOVE:\n {\n this->ControllerViewType= PSMove;\n this->ViewState.PSMoveView.ApplyControllerDataFrame(data_frame);\n } break;\n\n case PSMoveProtocol::ControllerDataFrame_ControllerType_PSNAVI:\n {\n this->ControllerViewType= PSNavi;\n this->ViewState.PSNaviView.ApplyControllerDataFrame(data_frame);\n } break;\n\n default:\n assert(0 && \"Unhandled controller type\");\n }\n }\n}\n\n\/\/-- helper functions -----\nstatic void update_button_state(\n PSMoveButtonState &button,\n unsigned int button_bitmask,\n unsigned int button_bit)\n{\n const bool is_down= (button_bitmask & (1 << button_bit)) > 0;\n\n switch (button)\n {\n case PSMoveButton_UP:\n button= is_down ? PSMoveButton_PRESSED : PSMoveButton_UP;\n break;\n case PSMoveButton_PRESSED:\n button= is_down ? PSMoveButton_DOWN : PSMoveButton_RELEASED;\n break;\n case PSMoveButton_DOWN:\n button= is_down ? PSMoveButton_DOWN : PSMoveButton_RELEASED;\n break;\n case PSMoveButton_RELEASED:\n button= is_down ? PSMoveButton_PRESSED : PSMoveButton_UP;\n break;\n };\n}<|endoftext|>"} {"text":"<commit_before>#include \"command.h\"\n#include \"..\/CommandHandler.h\"\n#include \"..\/OptionParser.h\"\n#include \"..\/version.h\"\n\n\/* full name of the command *\/\nCMDNAME(\"about\");\n\/* description of the command *\/\nCMDDESCR(\"print bot information\");\n\/* command usage synopsis *\/\nCMDUSAGE(\"$about\");\n\n\/* about: print bot information *\/\nstd::string CommandHandler::about(struct cmdinfo *c)\n{\n\tint opt;\n\tOptionParser op(c->fullCmd, \"\");\n\tstatic struct OptionParser::option long_opts[] = {\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\twhile ((opt = op.getopt_long(long_opts)) != EOF) {\n\t\tswitch (opt) {\n\t\tcase 'h':\n\t\t\treturn HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);\n\t\tcase '?':\n\t\t\treturn std::string(op.opterr());\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\treturn \"[ABOUT] \" + m_name + \" is running \" + std::string(BOT_NAME)\n\t\t+ \" \" + std::string(BOT_VERSION) + \". Find out more at \"\n\t\t+ std::string(BOT_WEBSITE);\n}\n<commit_msg>Add source option to about<commit_after>#include \"command.h\"\n#include \"..\/CommandHandler.h\"\n#include \"..\/OptionParser.h\"\n#include \"..\/version.h\"\n\n\/* full name of the command *\/\nCMDNAME(\"about\");\n\/* description of the command *\/\nCMDDESCR(\"print bot information\");\n\/* command usage synopsis *\/\nCMDUSAGE(\"$about [-s]\");\n\n\/* about: print bot information *\/\nstd::string CommandHandler::about(struct cmdinfo *c)\n{\n\tint opt;\n\tOptionParser op(c->fullCmd, \"s\");\n\tstatic struct OptionParser::option long_opts[] = {\n\t\t{ \"help\", NO_ARG, 'h' },\n\t\t{ \"source\", NO_ARG, 's' },\n\t\t{ 0, 0, 0 }\n\t};\n\n\twhile ((opt = op.getopt_long(long_opts)) != EOF) {\n\t\tswitch (opt) {\n\t\tcase 'h':\n\t\t\treturn HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);\n\t\tcase 's':\n\t\t\treturn \"[ABOUT] source: \" + SOURCE;\n\t\tcase '?':\n\t\t\treturn std::string(op.opterr());\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\treturn \"[ABOUT] \" + m_name + \" is running \" + std::string(BOT_NAME)\n\t\t+ \" \" + std::string(BOT_VERSION) + \". Find out more at \"\n\t\t+ std::string(BOT_WEBSITE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"shell\/browser\/extensions\/api\/resources_private\/resources_private_api.h\"\n\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/extensions\/api\/resources_private.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"components\/strings\/grit\/components_strings.h\"\n#include \"components\/zoom\/page_zoom_constants.h\"\n#include \"pdf\/buildflags.h\"\n#include \"printing\/buildflags\/buildflags.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/webui\/web_ui_util.h\"\n\n#if BUILDFLAG(ENABLE_PDF)\n#include \"pdf\/pdf_features.h\"\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n\n\/\/ To add a new component to this API, simply:\n\/\/ 1. Add your component to the Component enum in\n\/\/ chrome\/common\/extensions\/api\/resources_private.idl\n\/\/ 2. Create an AddStringsForMyComponent(base::DictionaryValue * dict) method.\n\/\/ 3. Tie in that method to the switch statement in Run()\n\nnamespace extensions {\n\nnamespace {\n\nvoid AddStringsForPdf(base::DictionaryValue* dict) {\n#if BUILDFLAG(ENABLE_PDF)\n static constexpr webui::LocalizedString kPdfResources[] = {\n {\"passwordDialogTitle\", IDS_PDF_PASSWORD_DIALOG_TITLE},\n {\"passwordPrompt\", IDS_PDF_NEED_PASSWORD},\n {\"passwordSubmit\", IDS_PDF_PASSWORD_SUBMIT},\n {\"passwordInvalid\", IDS_PDF_PASSWORD_INVALID},\n {\"pageLoading\", IDS_PDF_PAGE_LOADING},\n {\"pageLoadFailed\", IDS_PDF_PAGE_LOAD_FAILED},\n {\"errorDialogTitle\", IDS_PDF_ERROR_DIALOG_TITLE},\n {\"pageReload\", IDS_PDF_PAGE_RELOAD_BUTTON},\n {\"bookmarks\", IDS_PDF_BOOKMARKS},\n {\"labelPageNumber\", IDS_PDF_LABEL_PAGE_NUMBER},\n {\"tooltipRotateCW\", IDS_PDF_TOOLTIP_ROTATE_CW},\n {\"tooltipDownload\", IDS_PDF_TOOLTIP_DOWNLOAD},\n {\"tooltipPrint\", IDS_PDF_TOOLTIP_PRINT},\n {\"tooltipFitToPage\", IDS_PDF_TOOLTIP_FIT_PAGE},\n {\"tooltipFitToWidth\", IDS_PDF_TOOLTIP_FIT_WIDTH},\n {\"tooltipZoomIn\", IDS_PDF_TOOLTIP_ZOOM_IN},\n {\"tooltipZoomOut\", IDS_PDF_TOOLTIP_ZOOM_OUT},\n };\n for (const auto& resource : kPdfResources)\n dict->SetString(resource.name, l10n_util::GetStringUTF16(resource.id));\n\n dict->SetString(\"presetZoomFactors\", zoom::GetPresetZoomFactorsAsJSON());\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n}\n\nvoid AddAdditionalDataForPdf(base::DictionaryValue* dict) {\n#if BUILDFLAG(ENABLE_PDF)\n dict->SetKey(\"pdfFormSaveEnabled\",\n base::Value(base::FeatureList::IsEnabled(\n chrome_pdf::features::kSaveEditedPDFForm)));\n dict->SetKey(\"pdfAnnotationsEnabled\",\n base::Value(base::FeatureList::IsEnabled(\n chrome_pdf::features::kPDFAnnotations)));\n\n \/\/ TODO(nornagon): enable printing once it works.\n bool enable_printing = false;\n dict->SetKey(\"printingEnabled\", base::Value(enable_printing));\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n}\n\n} \/\/ namespace\n\nnamespace get_strings = api::resources_private::GetStrings;\n\nResourcesPrivateGetStringsFunction::ResourcesPrivateGetStringsFunction() {}\n\nResourcesPrivateGetStringsFunction::~ResourcesPrivateGetStringsFunction() {}\n\nExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() {\n std::unique_ptr<get_strings::Params> params(\n get_strings::Params::Create(*args_));\n auto dict = std::make_unique<base::DictionaryValue>();\n\n api::resources_private::Component component = params->component;\n\n switch (component) {\n case api::resources_private::COMPONENT_PDF:\n AddStringsForPdf(dict.get());\n AddAdditionalDataForPdf(dict.get());\n break;\n case api::resources_private::COMPONENT_IDENTITY:\n NOTREACHED();\n break;\n case api::resources_private::COMPONENT_NONE:\n NOTREACHED();\n break;\n }\n\n const std::string& app_locale = g_browser_process->GetApplicationLocale();\n webui::SetLoadTimeDataDefaults(app_locale, dict.get());\n\n return RespondNow(OneArgument(std::move(dict)));\n}\n\n} \/\/ namespace extensions\n<commit_msg>fix: add missing pdfTwoUpViewEnabled status (#22735)<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"shell\/browser\/extensions\/api\/resources_private\/resources_private_api.h\"\n\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/extensions\/api\/resources_private.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"components\/strings\/grit\/components_strings.h\"\n#include \"components\/zoom\/page_zoom_constants.h\"\n#include \"pdf\/buildflags.h\"\n#include \"printing\/buildflags\/buildflags.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/webui\/web_ui_util.h\"\n\n#if BUILDFLAG(ENABLE_PDF)\n#include \"pdf\/pdf_features.h\"\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n\n\/\/ To add a new component to this API, simply:\n\/\/ 1. Add your component to the Component enum in\n\/\/ chrome\/common\/extensions\/api\/resources_private.idl\n\/\/ 2. Create an AddStringsForMyComponent(base::DictionaryValue * dict) method.\n\/\/ 3. Tie in that method to the switch statement in Run()\n\nnamespace extensions {\n\nnamespace {\n\nvoid AddStringsForPdf(base::DictionaryValue* dict) {\n#if BUILDFLAG(ENABLE_PDF)\n static constexpr webui::LocalizedString kPdfResources[] = {\n {\"passwordDialogTitle\", IDS_PDF_PASSWORD_DIALOG_TITLE},\n {\"passwordPrompt\", IDS_PDF_NEED_PASSWORD},\n {\"passwordSubmit\", IDS_PDF_PASSWORD_SUBMIT},\n {\"passwordInvalid\", IDS_PDF_PASSWORD_INVALID},\n {\"pageLoading\", IDS_PDF_PAGE_LOADING},\n {\"pageLoadFailed\", IDS_PDF_PAGE_LOAD_FAILED},\n {\"errorDialogTitle\", IDS_PDF_ERROR_DIALOG_TITLE},\n {\"pageReload\", IDS_PDF_PAGE_RELOAD_BUTTON},\n {\"bookmarks\", IDS_PDF_BOOKMARKS},\n {\"labelPageNumber\", IDS_PDF_LABEL_PAGE_NUMBER},\n {\"tooltipRotateCW\", IDS_PDF_TOOLTIP_ROTATE_CW},\n {\"tooltipDownload\", IDS_PDF_TOOLTIP_DOWNLOAD},\n {\"tooltipPrint\", IDS_PDF_TOOLTIP_PRINT},\n {\"tooltipFitToPage\", IDS_PDF_TOOLTIP_FIT_PAGE},\n {\"tooltipFitToWidth\", IDS_PDF_TOOLTIP_FIT_WIDTH},\n {\"tooltipTwoUpViewDisable\", IDS_PDF_TOOLTIP_TWO_UP_VIEW_DISABLE},\n {\"tooltipTwoUpViewEnable\", IDS_PDF_TOOLTIP_TWO_UP_VIEW_ENABLE},\n {\"tooltipZoomIn\", IDS_PDF_TOOLTIP_ZOOM_IN},\n {\"tooltipZoomOut\", IDS_PDF_TOOLTIP_ZOOM_OUT},\n };\n for (const auto& resource : kPdfResources)\n dict->SetString(resource.name, l10n_util::GetStringUTF16(resource.id));\n\n dict->SetString(\"presetZoomFactors\", zoom::GetPresetZoomFactorsAsJSON());\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n}\n\nvoid AddAdditionalDataForPdf(base::DictionaryValue* dict) {\n#if BUILDFLAG(ENABLE_PDF)\n dict->SetKey(\"pdfFormSaveEnabled\",\n base::Value(base::FeatureList::IsEnabled(\n chrome_pdf::features::kSaveEditedPDFForm)));\n dict->SetKey(\"pdfAnnotationsEnabled\",\n base::Value(base::FeatureList::IsEnabled(\n chrome_pdf::features::kPDFAnnotations)));\n dict->SetKey(\"pdfTwoUpViewEnabled\",\n base::Value(base::FeatureList::IsEnabled(\n chrome_pdf::features::kPDFTwoUpView)));\n\n \/\/ TODO(nornagon): enable printing once it works.\n bool enable_printing = false;\n dict->SetKey(\"printingEnabled\", base::Value(enable_printing));\n#endif \/\/ BUILDFLAG(ENABLE_PDF)\n}\n\n} \/\/ namespace\n\nnamespace get_strings = api::resources_private::GetStrings;\n\nResourcesPrivateGetStringsFunction::ResourcesPrivateGetStringsFunction() {}\n\nResourcesPrivateGetStringsFunction::~ResourcesPrivateGetStringsFunction() {}\n\nExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() {\n std::unique_ptr<get_strings::Params> params(\n get_strings::Params::Create(*args_));\n auto dict = std::make_unique<base::DictionaryValue>();\n\n api::resources_private::Component component = params->component;\n\n switch (component) {\n case api::resources_private::COMPONENT_PDF:\n AddStringsForPdf(dict.get());\n AddAdditionalDataForPdf(dict.get());\n break;\n case api::resources_private::COMPONENT_IDENTITY:\n NOTREACHED();\n break;\n case api::resources_private::COMPONENT_NONE:\n NOTREACHED();\n break;\n }\n\n const std::string& app_locale = g_browser_process->GetApplicationLocale();\n webui::SetLoadTimeDataDefaults(app_locale, dict.get());\n\n return RespondNow(OneArgument(std::move(dict)));\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"<commit_before>\/*\n * XGL\n *\n * Copyright (C) 2014 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * Authors:\n * LunarG\n *\/\n\n#include \"shader.h\"\n#include \"pipeline.h\"\n#include \"compiler\/shader\/compiler_interface.h\"\n#include \"compiler\/pipeline\/pipeline_compiler_interface.h\"\n#include \"compiler\/pipeline\/brw_context.h\"\n#include \"compiler\/pipeline\/brw_shader.h\"\n#include \"compiler\/mesa-utils\/src\/mesa\/main\/context.h\"\n#include \"compiler\/mesa-utils\/src\/glsl\/ralloc.h\"\n#include \"compiler\/pipeline\/brw_device_info.h\"\n#include \"compiler\/pipeline\/brw_wm.h\"\n\n\nvoid initialize_brw_context(struct brw_context *brw)\n{\n\n \/\/ create a stripped down context for compilation\n initialize_mesa_context_to_defaults(&brw->ctx);\n\n \/\/\n \/\/ init the things pulled from DRI in brwCreateContext\n \/\/\n struct brw_device_info *devInfo = rzalloc(brw, struct brw_device_info);\n devInfo->gen = 7;\n devInfo->gt = 3;\n devInfo->is_g4x = false;\n devInfo->is_baytrail = false;\n devInfo->is_haswell = true;\n devInfo->has_llc = true;\n devInfo->has_pln = true;\n devInfo->has_compr4 = true;\n devInfo->has_negative_rhw_bug = false;\n devInfo->needs_unlit_centroid_workaround = true;\n\n \/\/ hand code values until we have something to pull from\n \/\/ use brw_device_info_hsw_gt3\n brw->intelScreen = rzalloc(brw, struct intel_screen);\n brw->intelScreen->devinfo = devInfo;\n\n brw->gen = brw->intelScreen->devinfo->gen;\n brw->gt = brw->intelScreen->devinfo->gt;\n brw->is_g4x = brw->intelScreen->devinfo->is_g4x;\n brw->is_baytrail = brw->intelScreen->devinfo->is_baytrail;\n brw->is_haswell = brw->intelScreen->devinfo->is_haswell;\n brw->has_llc = brw->intelScreen->devinfo->has_llc;\n brw->has_pln = brw->intelScreen->devinfo->has_pln;\n brw->has_compr4 = brw->intelScreen->devinfo->has_compr4;\n brw->has_negative_rhw_bug = brw->intelScreen->devinfo->has_negative_rhw_bug;\n brw->needs_unlit_centroid_workaround =\n brw->intelScreen->devinfo->needs_unlit_centroid_workaround;\n\n brw->vs.base.stage = MESA_SHADER_VERTEX;\n brw->gs.base.stage = MESA_SHADER_GEOMETRY;\n brw->wm.base.stage = MESA_SHADER_FRAGMENT;\n\n \/\/\n \/\/ init what remains of intel_screen\n \/\/\n brw->intelScreen->deviceID = 0;\n brw->intelScreen->program_id = 0;\n\n brw_fs_alloc_reg_sets(brw->intelScreen);\n brw_vec4_alloc_reg_set(brw->intelScreen);\n\n brw->shader_prog = brw_new_shader_program(&brw->ctx, 0);\n}\n\nstatic inline void pipeline_destroy_compile(struct brw_context *brw) {\n ralloc_free(brw->shader_prog);\n ralloc_free(brw);\n}\n\nstatic void hexdump(FILE *fp, void *ptr, int buflen) {\n unsigned int *buf = (unsigned int*)ptr;\n int i, j;\n for (i=0; i<(buflen\/4); i+=4) {\n fprintf(fp,\"%06x: \", i);\n for (j=0; j<4; j++)\n if (i+j < (buflen\/4))\n fprintf(fp,\"%08x \", buf[i+j]);\n else\n fprintf(fp,\" \");\n fprintf(fp,\"\\n\");\n }\n\n fflush(fp);\n}\n\nstatic void fs_data_dump(FILE *fp, struct brw_wm_prog_data* data)\n{\n fprintf(fp, \"\\n=== begin brw_wm_prog_data ===\\n\");\n\n fprintf(fp, \"data->base.binding_table.size_bytes = %u\\n\",\n data->base.binding_table.size_bytes);\n fprintf(fp, \"data->base.binding_table.pull_constants_start = %u\\n\",\n data->base.binding_table.pull_constants_start);\n fprintf(fp, \"data->base.binding_table.texture_start = %u\\n\",\n data->base.binding_table.texture_start);\n fprintf(fp, \"data->base.binding_table.gather_texture_start = %u\\n\",\n data->base.binding_table.gather_texture_start);\n fprintf(fp, \"data->base.binding_table.ubo_start = %u\\n\",\n data->base.binding_table.ubo_start);\n fprintf(fp, \"data->base.binding_table.abo_start = %u\\n\",\n data->base.binding_table.abo_start);\n fprintf(fp, \"data->base.binding_table.shader_time_start = %u\\n\",\n data->base.binding_table.shader_time_start);\n\n fprintf(fp, \"data->base.nr_params = %u\\n\",\n data->base.nr_params);\n fprintf(fp, \"data->base.nr_pull_params = %u\\n\",\n data->base.nr_pull_params);\n\n \/\/ invalid pointers\n \/\/data->base.param;\n \/\/data->base.pull_param;\n\n fprintf(fp, \"data->curb_read_length = %u\\n\",\n data->curb_read_length);\n fprintf(fp, \"data->num_varying_inputs = %u\\n\",\n data->num_varying_inputs);\n\n fprintf(fp, \"data->first_curbe_grf = %u\\n\",\n data->first_curbe_grf);\n fprintf(fp, \"data->first_curbe_grf_16 = %u\\n\",\n data->first_curbe_grf_16);\n fprintf(fp, \"data->reg_blocks = %u\\n\",\n data->reg_blocks);\n fprintf(fp, \"data->reg_blocks_16 = %u\\n\",\n data->reg_blocks_16);\n fprintf(fp, \"data->total_scratch = %u\\n\",\n data->total_scratch);\n fprintf(fp, \"data->binding_table.render_target_start = %u\\n\",\n data->binding_table.render_target_start);\n\n fprintf(fp, \"data->dual_src_blend = %s\\n\",\n data->dual_src_blend ? \"true\" : \"false\");\n fprintf(fp, \"data->uses_pos_offset = %s\\n\",\n data->uses_pos_offset ? \"true\" : \"false\");\n fprintf(fp, \"data->uses_omask = %s\\n\",\n data->uses_omask ? \"true\" : \"false\");\n fprintf(fp, \"data->prog_offset_16 = %u\\n\",\n data->prog_offset_16);\n\n fprintf(fp, \"data->barycentric_interp_modes = %u\\n\",\n data->barycentric_interp_modes);\n\n for (int i = 0; i < VARYING_SLOT_MAX; ++i) {\n fprintf(fp, \"data->urb_setup[%i] = %i\\n\",\n i, data->urb_setup[i]);\n }\n\n fprintf(fp, \"=== end brw_wm_prog_data ===\\n\");\n\n fflush(fp);\n}\n\nextern \"C\" {\n\n\/\/ invoke backend compiler to generate ISA and supporting data structures\nXGL_RESULT intel_pipeline_shader_compile(struct intel_pipeline_shader *pipe_shader,\n const struct intel_shader *shader)\n{\n XGL_RESULT status = XGL_SUCCESS;\n\n \/\/ create a brw_context\n struct brw_context *brw = rzalloc(NULL, struct brw_context);\n\n \/\/ allocate sub structures on the stack\n initialize_brw_context(brw);\n\n \/\/ LunarG : TODO - should this have been set for us somewhere?\n shader->ir->shader_program->Type =\n shader->ir->shader_program->Shaders[0]->Stage;\n\n if (brw_link_shader(&brw->ctx, shader->ir->shader_program)) {\n\n \/\/ first take at standalone backend compile\n switch(shader->ir->shader_program->Shaders[0]->Type) {\n case GL_VERTEX_SHADER:\n {\n pipe_shader->codeSize = get_vs_program_size(brw->shader_prog);\n\n pipe_shader->pCode = icd_alloc(pipe_shader->codeSize, 0, XGL_SYSTEM_ALLOC_INTERNAL_SHADER);\n if (!pipe_shader->pCode) {\n status = XGL_ERROR_OUT_OF_MEMORY;\n break;\n }\n\n \/\/ copy the ISA out of our compile context, it is about to poof away\n memcpy(pipe_shader->pCode, get_vs_program(brw->shader_prog), pipe_shader->codeSize);\n\n struct brw_vs_prog_data *data = get_vs_prog_data(brw->shader_prog);\n\n if (data->uses_vertexid)\n pipe_shader->uses |= INTEL_SHADER_USE_VID;\n\n \/\/ These are really best guesses, and will require more work to\n \/\/ understand as we turn on more features\n pipe_shader->in_count = data->base.urb_read_length;\/\/ = 1;\n pipe_shader->out_count = data->base.vue_map.num_slots;\/\/ = 2;\n pipe_shader->urb_grf_start = data->base.dispatch_grf_start_reg;\/\/ = 1;\n\n \/\/ The following continue to match what is baked in to test case\n pipe_shader->sampler_count = shader->sampler_count;\n pipe_shader->barycentric_interps = shader->barycentric_interps;\n\n\n fprintf(stdout,\"\\nISA generated by compiler:\\n\");\n fprintf(stdout,\"ISA size: %i\\n\", pipe_shader->codeSize);\n hexdump(stdout, pipe_shader->pCode, pipe_shader->codeSize);\n fflush(stdout);\n }\n break;\n\n case GL_FRAGMENT_SHADER:\n {\n \/\/ Start pulling bits out of our compile result.\n \/\/ see upload_ps_state() for references about what I believe each of these values are\n\n \/\/ I would prefer to find a way to pull this data out without exposing\n \/\/ the internals of the compiler, but it hasn't presented itself yet\n\n pipe_shader->codeSize = get_wm_program_size(brw->shader_prog);\n\n pipe_shader->pCode = icd_alloc(pipe_shader->codeSize, 0, XGL_SYSTEM_ALLOC_INTERNAL_SHADER);\n if (!pipe_shader->pCode) {\n status = XGL_ERROR_OUT_OF_MEMORY;\n break;\n }\n\n \/\/ copy the ISA out of our compile context, it is about to poof away\n memcpy(pipe_shader->pCode, get_wm_program(brw->shader_prog), pipe_shader->codeSize);\n\n struct brw_wm_prog_data *data = get_wm_prog_data(brw->shader_prog);\n\n \/\/ print out the supporting structures generated by the BE compile:\n fs_data_dump(stdout, data);\n\n pipe_shader->surface_count = data->base.binding_table.size_bytes \/ 4;\n pipe_shader->urb_grf_start = data->first_curbe_grf;\n pipe_shader->in_count = data->num_varying_inputs;\n\n \/\/ Ensure this is 1:1, or create a converter\n pipe_shader->barycentric_interps = data->barycentric_interp_modes;\n\n \/\/ The following continue to match what is baked in to test case\n pipe_shader->uses = shader->uses;\n pipe_shader->out_count = shader->out_count;\n pipe_shader->sampler_count = shader->sampler_count;\n\n\n fprintf(stdout,\"\\nISA generated by compiler:\\n\");\n fprintf(stdout,\"ISA size: %i\\n\", pipe_shader->codeSize);\n hexdump(stdout, pipe_shader->pCode, pipe_shader->codeSize);\n fflush(stdout);\n }\n break;\n\n case GL_GEOMETRY_SHADER:\n case GL_COMPUTE_SHADER:\n default:\n assert(0);\n status = XGL_ERROR_BAD_PIPELINE_DATA;\n }\n } else {\n assert(0);\n status = XGL_ERROR_BAD_PIPELINE_DATA;\n }\n\n pipeline_destroy_compile(brw);\n\n return status;\n}\n\n\n} \/\/ extern \"C\"\n<commit_msg>compiler: Print out more push\/pull param info<commit_after>\/*\n * XGL\n *\n * Copyright (C) 2014 LunarG, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * Authors:\n * LunarG\n *\/\n\n#include \"shader.h\"\n#include \"pipeline.h\"\n#include \"compiler\/shader\/compiler_interface.h\"\n#include \"compiler\/pipeline\/pipeline_compiler_interface.h\"\n#include \"compiler\/pipeline\/brw_context.h\"\n#include \"compiler\/pipeline\/brw_shader.h\"\n#include \"compiler\/mesa-utils\/src\/mesa\/main\/context.h\"\n#include \"compiler\/mesa-utils\/src\/glsl\/ralloc.h\"\n#include \"compiler\/pipeline\/brw_device_info.h\"\n#include \"compiler\/pipeline\/brw_wm.h\"\n\n\nvoid initialize_brw_context(struct brw_context *brw)\n{\n\n \/\/ create a stripped down context for compilation\n initialize_mesa_context_to_defaults(&brw->ctx);\n\n \/\/\n \/\/ init the things pulled from DRI in brwCreateContext\n \/\/\n struct brw_device_info *devInfo = rzalloc(brw, struct brw_device_info);\n devInfo->gen = 7;\n devInfo->gt = 3;\n devInfo->is_g4x = false;\n devInfo->is_baytrail = false;\n devInfo->is_haswell = true;\n devInfo->has_llc = true;\n devInfo->has_pln = true;\n devInfo->has_compr4 = true;\n devInfo->has_negative_rhw_bug = false;\n devInfo->needs_unlit_centroid_workaround = true;\n\n \/\/ hand code values until we have something to pull from\n \/\/ use brw_device_info_hsw_gt3\n brw->intelScreen = rzalloc(brw, struct intel_screen);\n brw->intelScreen->devinfo = devInfo;\n\n brw->gen = brw->intelScreen->devinfo->gen;\n brw->gt = brw->intelScreen->devinfo->gt;\n brw->is_g4x = brw->intelScreen->devinfo->is_g4x;\n brw->is_baytrail = brw->intelScreen->devinfo->is_baytrail;\n brw->is_haswell = brw->intelScreen->devinfo->is_haswell;\n brw->has_llc = brw->intelScreen->devinfo->has_llc;\n brw->has_pln = brw->intelScreen->devinfo->has_pln;\n brw->has_compr4 = brw->intelScreen->devinfo->has_compr4;\n brw->has_negative_rhw_bug = brw->intelScreen->devinfo->has_negative_rhw_bug;\n brw->needs_unlit_centroid_workaround =\n brw->intelScreen->devinfo->needs_unlit_centroid_workaround;\n\n brw->vs.base.stage = MESA_SHADER_VERTEX;\n brw->gs.base.stage = MESA_SHADER_GEOMETRY;\n brw->wm.base.stage = MESA_SHADER_FRAGMENT;\n\n \/\/\n \/\/ init what remains of intel_screen\n \/\/\n brw->intelScreen->deviceID = 0;\n brw->intelScreen->program_id = 0;\n\n brw_fs_alloc_reg_sets(brw->intelScreen);\n brw_vec4_alloc_reg_set(brw->intelScreen);\n\n brw->shader_prog = brw_new_shader_program(&brw->ctx, 0);\n}\n\nstatic inline void pipeline_destroy_compile(struct brw_context *brw) {\n ralloc_free(brw->shader_prog);\n ralloc_free(brw);\n}\n\nstatic void hexdump(FILE *fp, void *ptr, int buflen) {\n unsigned int *buf = (unsigned int*)ptr;\n int i, j;\n for (i=0; i<(buflen\/4); i+=4) {\n fprintf(fp,\"%06x: \", i);\n for (j=0; j<4; j++)\n if (i+j < (buflen\/4))\n fprintf(fp,\"%08x \", buf[i+j]);\n else\n fprintf(fp,\" \");\n fprintf(fp,\"\\n\");\n }\n\n fflush(fp);\n}\n\nstatic void fs_data_dump(FILE *fp, struct brw_wm_prog_data* data)\n{\n fprintf(fp, \"\\n=== begin brw_wm_prog_data ===\\n\");\n\n fprintf(fp, \"data->base.binding_table.size_bytes = %u\\n\",\n data->base.binding_table.size_bytes);\n fprintf(fp, \"data->base.binding_table.pull_constants_start = %u\\n\",\n data->base.binding_table.pull_constants_start);\n fprintf(fp, \"data->base.binding_table.texture_start = %u\\n\",\n data->base.binding_table.texture_start);\n fprintf(fp, \"data->base.binding_table.gather_texture_start = %u\\n\",\n data->base.binding_table.gather_texture_start);\n fprintf(fp, \"data->base.binding_table.ubo_start = %u\\n\",\n data->base.binding_table.ubo_start);\n fprintf(fp, \"data->base.binding_table.abo_start = %u\\n\",\n data->base.binding_table.abo_start);\n fprintf(fp, \"data->base.binding_table.shader_time_start = %u\\n\",\n data->base.binding_table.shader_time_start);\n\n fprintf(fp, \"data->base.nr_params = %u\\n\",\n data->base.nr_params);\n fprintf(fp, \"data->base.nr_pull_params = %u\\n\",\n data->base.nr_pull_params);\n\n fprintf(fp, \"== push constants: ==\\n\");\n fprintf(fp, \"data->base.nr_params = %u\\n\",\n data->base.nr_params);\n\n for (int i = 0; i < data->base.nr_params; ++i) {\n fprintf(fp, \"data->base.param = %p\\n\",\n data->base.param);\n fprintf(fp, \"*data->base.param = %p\\n\",\n *data->base.param);\n fprintf(fp, \"**data->base.param = %f\\n\",\n **data->base.param);\n }\n\n fprintf(fp, \"== pull constants: ==\\n\");\n fprintf(fp, \"data->base.nr_pull_params = %u\\n\",\n data->base.nr_pull_params);\n\n for (int i = 0; i < data->base.nr_pull_params; ++i) {\n fprintf(fp, \"data->base.pull_param = %p\\n\",\n data->base.pull_param);\n fprintf(fp, \"*data->base.pull_param = %p\\n\",\n *data->base.pull_param);\n fprintf(fp, \"**data->base.pull_param = %f\\n\",\n **data->base.pull_param);\n }\n\n\n fprintf(fp, \"data->curb_read_length = %u\\n\",\n data->curb_read_length);\n fprintf(fp, \"data->num_varying_inputs = %u\\n\",\n data->num_varying_inputs);\n\n fprintf(fp, \"data->first_curbe_grf = %u\\n\",\n data->first_curbe_grf);\n fprintf(fp, \"data->first_curbe_grf_16 = %u\\n\",\n data->first_curbe_grf_16);\n fprintf(fp, \"data->reg_blocks = %u\\n\",\n data->reg_blocks);\n fprintf(fp, \"data->reg_blocks_16 = %u\\n\",\n data->reg_blocks_16);\n fprintf(fp, \"data->total_scratch = %u\\n\",\n data->total_scratch);\n fprintf(fp, \"data->binding_table.render_target_start = %u\\n\",\n data->binding_table.render_target_start);\n\n fprintf(fp, \"data->dual_src_blend = %s\\n\",\n data->dual_src_blend ? \"true\" : \"false\");\n fprintf(fp, \"data->uses_pos_offset = %s\\n\",\n data->uses_pos_offset ? \"true\" : \"false\");\n fprintf(fp, \"data->uses_omask = %s\\n\",\n data->uses_omask ? \"true\" : \"false\");\n fprintf(fp, \"data->prog_offset_16 = %u\\n\",\n data->prog_offset_16);\n\n fprintf(fp, \"data->barycentric_interp_modes = %u\\n\",\n data->barycentric_interp_modes);\n\n for (int i = 0; i < VARYING_SLOT_MAX; ++i) {\n fprintf(fp, \"data->urb_setup[%i] = %i\\n\",\n i, data->urb_setup[i]);\n }\n\n fprintf(fp, \"=== end brw_wm_prog_data ===\\n\");\n\n fflush(fp);\n}\n\nextern \"C\" {\n\n\/\/ invoke backend compiler to generate ISA and supporting data structures\nXGL_RESULT intel_pipeline_shader_compile(struct intel_pipeline_shader *pipe_shader,\n const struct intel_shader *shader)\n{\n XGL_RESULT status = XGL_SUCCESS;\n\n \/\/ create a brw_context\n struct brw_context *brw = rzalloc(NULL, struct brw_context);\n\n \/\/ allocate sub structures on the stack\n initialize_brw_context(brw);\n\n \/\/ LunarG : TODO - should this have been set for us somewhere?\n shader->ir->shader_program->Type =\n shader->ir->shader_program->Shaders[0]->Stage;\n\n if (brw_link_shader(&brw->ctx, shader->ir->shader_program)) {\n\n \/\/ first take at standalone backend compile\n switch(shader->ir->shader_program->Shaders[0]->Type) {\n case GL_VERTEX_SHADER:\n {\n pipe_shader->codeSize = get_vs_program_size(brw->shader_prog);\n\n pipe_shader->pCode = icd_alloc(pipe_shader->codeSize, 0, XGL_SYSTEM_ALLOC_INTERNAL_SHADER);\n if (!pipe_shader->pCode) {\n status = XGL_ERROR_OUT_OF_MEMORY;\n break;\n }\n\n \/\/ copy the ISA out of our compile context, it is about to poof away\n memcpy(pipe_shader->pCode, get_vs_program(brw->shader_prog), pipe_shader->codeSize);\n\n struct brw_vs_prog_data *data = get_vs_prog_data(brw->shader_prog);\n\n if (data->uses_vertexid)\n pipe_shader->uses |= INTEL_SHADER_USE_VID;\n\n \/\/ These are really best guesses, and will require more work to\n \/\/ understand as we turn on more features\n pipe_shader->in_count = data->base.urb_read_length;\/\/ = 1;\n pipe_shader->out_count = data->base.vue_map.num_slots;\/\/ = 2;\n pipe_shader->urb_grf_start = data->base.dispatch_grf_start_reg;\/\/ = 1;\n\n \/\/ The following continue to match what is baked in to test case\n pipe_shader->sampler_count = shader->sampler_count;\n pipe_shader->barycentric_interps = shader->barycentric_interps;\n\n\n fprintf(stdout,\"\\nISA generated by compiler:\\n\");\n fprintf(stdout,\"ISA size: %i\\n\", pipe_shader->codeSize);\n hexdump(stdout, pipe_shader->pCode, pipe_shader->codeSize);\n fflush(stdout);\n }\n break;\n\n case GL_FRAGMENT_SHADER:\n {\n \/\/ Start pulling bits out of our compile result.\n \/\/ see upload_ps_state() for references about what I believe each of these values are\n\n \/\/ I would prefer to find a way to pull this data out without exposing\n \/\/ the internals of the compiler, but it hasn't presented itself yet\n\n pipe_shader->codeSize = get_wm_program_size(brw->shader_prog);\n\n pipe_shader->pCode = icd_alloc(pipe_shader->codeSize, 0, XGL_SYSTEM_ALLOC_INTERNAL_SHADER);\n if (!pipe_shader->pCode) {\n status = XGL_ERROR_OUT_OF_MEMORY;\n break;\n }\n\n \/\/ copy the ISA out of our compile context, it is about to poof away\n memcpy(pipe_shader->pCode, get_wm_program(brw->shader_prog), pipe_shader->codeSize);\n\n struct brw_wm_prog_data *data = get_wm_prog_data(brw->shader_prog);\n\n \/\/ print out the supporting structures generated by the BE compile:\n fs_data_dump(stdout, data);\n\n pipe_shader->surface_count = data->base.binding_table.size_bytes \/ 4;\n pipe_shader->urb_grf_start = data->first_curbe_grf;\n pipe_shader->in_count = data->num_varying_inputs;\n\n \/\/ Ensure this is 1:1, or create a converter\n pipe_shader->barycentric_interps = data->barycentric_interp_modes;\n\n \/\/ The following continue to match what is baked in to test case\n pipe_shader->uses = shader->uses;\n pipe_shader->out_count = shader->out_count;\n pipe_shader->sampler_count = shader->sampler_count;\n\n\n fprintf(stdout,\"\\nISA generated by compiler:\\n\");\n fprintf(stdout,\"ISA size: %i\\n\", pipe_shader->codeSize);\n hexdump(stdout, pipe_shader->pCode, pipe_shader->codeSize);\n fflush(stdout);\n }\n break;\n\n case GL_GEOMETRY_SHADER:\n case GL_COMPUTE_SHADER:\n default:\n assert(0);\n status = XGL_ERROR_BAD_PIPELINE_DATA;\n }\n } else {\n assert(0);\n status = XGL_ERROR_BAD_PIPELINE_DATA;\n }\n\n pipeline_destroy_compile(brw);\n\n return status;\n}\n\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"RawImgDetections.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/Timestamp.hpp\"\n#include \"depthai-shared\/utility\/Serialization.hpp\"\n\nnamespace dai {\n\n\/**\n * SpatialImgDetection structure\n *\n * Contains image detection results together with spatial location data.\n *\/\nstruct SpatialImgDetection : public ImgDetection {\n Point3f spatialCoordinates;\n};\n\nDEPTHAI_SERIALIZE_EXT(SpatialImgDetection, label, confidence, xmin, ymin, xmax, ymax, spatialCoordinates);\n\n\/\/\/ RawSpatialImgDetections structure\nstruct RawSpatialImgDetections : public RawBuffer {\n std::vector<SpatialImgDetection> detections;\n\n \/\/ Related to input ImgFrame\n int64_t sequenceNum = 0; \/\/ increments for each frame\n Timestamp ts = {}; \/\/ generation timestamp, synced to host time\n Timestamp tsDevice = {}; \/\/ generation timestamp, direct device monotonic clock\n\n void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {\n metadata = utility::serialize(*this);\n datatype = DatatypeEnum::SpatialImgDetections;\n };\n\n DEPTHAI_SERIALIZE(RawSpatialImgDetections, detections, sequenceNum, ts, tsDevice);\n};\n\n} \/\/ namespace dai\n<commit_msg>Expand spatial image detections with original config<commit_after>#pragma once\n\n#include \"RawImgDetections.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/Timestamp.hpp\"\n#include \"depthai-shared\/datatype\/RawSpatialLocationCalculatorConfig.hpp\"\n#include \"depthai-shared\/utility\/Serialization.hpp\"\n\nnamespace dai {\n\n\/**\n * SpatialImgDetection structure\n *\n * Contains image detection results together with spatial location data.\n *\/\nstruct SpatialImgDetection : public ImgDetection {\n Point3f spatialCoordinates;\n SpatialLocationCalculatorConfigData boundingBoxMapping;\n};\n\nDEPTHAI_SERIALIZE_EXT(SpatialImgDetection, label, confidence, xmin, ymin, xmax, ymax, spatialCoordinates, boundingBoxMapping);\n\n\/\/\/ RawSpatialImgDetections structure\nstruct RawSpatialImgDetections : public RawBuffer {\n std::vector<SpatialImgDetection> detections;\n\n \/\/ Related to input ImgFrame\n int64_t sequenceNum = 0; \/\/ increments for each frame\n Timestamp ts = {}; \/\/ generation timestamp, synced to host time\n Timestamp tsDevice = {}; \/\/ generation timestamp, direct device monotonic clock\n\n void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {\n metadata = utility::serialize(*this);\n datatype = DatatypeEnum::SpatialImgDetections;\n };\n\n DEPTHAI_SERIALIZE(RawSpatialImgDetections, detections, sequenceNum, ts, tsDevice);\n};\n\n} \/\/ namespace dai\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"dll\/neural_layer.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Batch Normalization layer\n *\/\ntemplate <typename Desc>\nstruct batch_normalization_4d_layer_impl : neural_layer<batch_normalization_4d_layer_impl<Desc>, Desc> {\n using desc = Desc; \/\/\/< The descriptor type\n using base_type = neural_layer<batch_normalization_4d_layer_impl<Desc>, Desc>; \/\/\/< The base type\n using weight = typename desc::weight; \/\/\/< The data type of the layer\n using this_type = batch_normalization_4d_layer_impl<Desc>; \/\/\/< The type of this layer\n using layer_t = this_type; \/\/\/< This layer's type\n using dyn_layer_t = typename desc::dyn_layer_t; \/\/\/< The dynamic version of this layer\n\n static constexpr size_t Kernels = desc::Kernels; \/\/\/< The number of feature maps\n static constexpr size_t W = desc::Width; \/\/\/< The width of feature maps\n static constexpr size_t H = desc::Height; \/\/\/< The height of feature maps\n static constexpr weight e = 1e-8; \/\/\/< Epsilon for numerical stability\n\n using input_one_t = etl::fast_dyn_matrix<weight, Kernels, W, H>; \/\/\/< The type of one input\n using output_one_t = etl::fast_dyn_matrix<weight, Kernels, W, H>; \/\/\/< The type of one output\n using input_t = std::vector<input_one_t>; \/\/\/< The type of the input\n using output_t = std::vector<output_one_t>; \/\/\/< The type of the output\n\n etl::fast_matrix<weight, Kernels> gamma;\n etl::fast_matrix<weight, Kernels> beta;\n\n etl::fast_matrix<weight, Kernels> mean;\n etl::fast_matrix<weight, Kernels> var;\n\n etl::fast_matrix<weight, Kernels> last_mean;\n etl::fast_matrix<weight, Kernels> last_var;\n etl::fast_matrix<weight, Kernels> inv_var;\n\n etl::dyn_matrix<weight, 4> input_pre; \/\/\/ B x K x W x H\n\n weight momentum = 0.9;\n\n \/\/Backup gamma and beta\n std::unique_ptr<etl::fast_matrix<weight, Kernels>> bak_gamma; \/\/\/< Backup gamma\n std::unique_ptr<etl::fast_matrix<weight, Kernels>> bak_beta; \/\/\/< Backup beta\n\n batch_normalization_4d_layer_impl() : base_type() {\n gamma = 1.0;\n beta = 0.0;\n }\n\n \/*!\n * \\brief Returns a string representation of the layer\n *\/\n static std::string to_short_string([[maybe_unused]] std::string pre = \"\") {\n return \"batch_norm\";\n }\n\n \/*!\n * \\brief Returns a string representation of the layer\n *\/\n static std::string to_full_string([[maybe_unused]] std::string pre = \"\") {\n return \"batch_norm\";\n }\n\n \/*!\n * \\brief Return the number of trainable parameters of this network.\n * \\return The the number of trainable parameters of this network.\n *\/\n static constexpr size_t parameters() noexcept {\n return 4 * Kernels;\n }\n\n \/*!\n * \\brief Return the size of the input of this layer\n * \\return The size of the input of this layer\n *\/\n static constexpr size_t input_size() noexcept {\n return Kernels * W * H;\n }\n\n \/*!\n * \\brief Return the size of the output of this layer\n * \\return The size of the output of this layer\n *\/\n static constexpr size_t output_size() noexcept {\n return Kernels * W * H;\n }\n\n \/*!\n * \\brief Returns the output shape\n * \\return an std::string containing the description of the output shape\n *\/\n std::vector<size_t> output_shape([[maybe_unused]] const std::vector<size_t>& input_shape) const {\n return {Kernels, W, H};\n }\n\n using base_type::test_forward_batch;\n using base_type::train_forward_batch;\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void forward_batch(Output& output, const Input& input) const {\n test_forward_batch(output, input);\n }\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void test_forward_batch(Output& output, const Input& input) const {\n const auto B = etl::dim<0>(input);\n\n auto inv_var = etl::force_temporary(1.0 \/ etl::sqrt(var + e));\n\n for (size_t b = 0; b < B; ++b) {\n for (size_t k = 0; k < Kernels; ++k) {\n output(b)(k) = (gamma(k) >> ((input(b)(k) - mean(k)) >> inv_var(k))) + beta(k);\n }\n }\n }\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void train_forward_batch(Output& output, const Input& input) {\n const auto B = etl::dim<0>(input);\n const auto S = B * W * H;\n\n \/\/ Compute the mean of the mini-batch\n last_mean = etl::bias_batch_mean_4d(input);\n\n \/\/ Compute the variance of the mini-batch\n last_var = 0;\n\n for (size_t b = 0; b < B; ++b) {\n for (size_t k = 0; k < Kernels; ++k) {\n last_var(k) += etl::sum((input(b)(k) - last_mean(k)) >> (input(b)(k) - last_mean(k)));\n }\n }\n\n last_var \/= S;\n\n inv_var = 1.0 \/ etl::sqrt(last_var + e);\n\n input_pre.inherit_if_null(input);\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n input_pre(b)(k) = (input(b)(k) - last_mean(k)) >> inv_var(k);\n output(b)(k) = (gamma(k) >> input_pre(b)(k)) + beta(k);\n }\n }\n\n \/\/\/\/ Update the current mean and variance\n mean = momentum * mean + (1.0 - momentum) * last_mean;\n var = momentum * var + (1.0 - momentum) * (S \/ (S - 1) * last_var);\n }\n\n \/*!\n * \\brief Adapt the errors, called before backpropagation of the errors.\n *\n * This must be used by layers that have both an activation fnction and a non-linearity.\n *\n * \\param context the training context\n *\/\n template <typename C>\n void adapt_errors([[maybe_unused]] C& context) const {}\n\n \/*!\n * \\brief Backpropagate the errors to the previous layers\n * \\param output The ETL expression into which write the output\n * \\param context The training context\n *\/\n template<typename HH, typename C>\n void backward_batch(HH&& output, C& context) const {\n const auto B = etl::dim<0>(context.input);\n const auto S = B * W * H;\n\n auto dxhat = etl::force_temporary_dim_only(context.errors);\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n dxhat(b)(k) = context.errors(b)(k) >> gamma(k);\n }\n }\n\n auto dxhat_l = etl::bias_batch_sum_4d(dxhat);\n auto dxhat_xhat_l = etl::bias_batch_sum_4d(dxhat >> input_pre);\n\n *dxhat_l;\n *dxhat_xhat_l;\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n output(b)(k) = ((1.0 \/ S) * inv_var(k)) >> (S * dxhat(b)(k) - dxhat_l(k) - (input_pre(b)(k) >> dxhat_xhat_l(k)));\n }\n }\n }\n\n \/*!\n * \\brief Compute the gradients for this layer, if any\n * \\param context The trainng context\n *\/\n template<typename C>\n void compute_gradients(C& context) const {\n \/\/ Gradients of gamma\n std::get<0>(context.up.context)->grad = etl::bias_batch_sum_4d(input_pre >> context.errors);\n\n \/\/ Gradients of beta\n std::get<1>(context.up.context)->grad = etl::bias_batch_sum_4d(context.errors);\n }\n\n \/*!\n * \\brief Prepare one empty output for this layer\n * \\return an empty ETL matrix suitable to store one output of this layer\n *\n * \\tparam Input The type of one Input\n *\/\n template <typename InputType>\n output_one_t prepare_one_output() const {\n return {};\n }\n\n \/*!\n * \\brief Prepare a set of empty outputs for this layer\n * \\param samples The number of samples to prepare the output for\n * \\return a container containing empty ETL matrices suitable to store samples output of this layer\n * \\tparam Input The type of one input\n *\/\n template <typename InputType>\n static output_t prepare_output(size_t samples) {\n return output_t{samples};\n }\n\n \/*!\n * \\brief Initialize the dynamic version of the layer from the fast version of the layer\n * \\param dyn Reference to the dynamic version of the layer that needs to be initialized\n *\/\n template<typename DLayer>\n static void dyn_init(DLayer& dyn){\n dyn.init_layer(Kernels, W, H);\n }\n\n \/*!\n * \\brief Returns the trainable variables of this layer.\n * \\return a tuple containing references to the variables of this layer\n *\/\n decltype(auto) trainable_parameters(){\n return std::make_tuple(std::ref(gamma), std::ref(beta));\n }\n\n \/*!\n * \\brief Returns the trainable variables of this layer.\n * \\return a tuple containing references to the variables of this layer\n *\/\n decltype(auto) trainable_parameters() const {\n return std::make_tuple(std::cref(gamma), std::cref(beta));\n }\n\n \/*!\n * \\brief Backup the weights in the secondary weights matrix\n *\/\n void backup_weights() {\n unique_safe_get(bak_gamma) = gamma;\n unique_safe_get(bak_beta) = beta;\n }\n\n \/*!\n * \\brief Restore the weights from the secondary weights matrix\n *\/\n void restore_weights() {\n gamma = *bak_gamma;\n beta = *bak_beta;\n }\n};\n\n\/\/ Declare the traits for the layer\n\ntemplate<typename Desc>\nstruct layer_base_traits<batch_normalization_4d_layer_impl<Desc>> {\n static constexpr bool is_neural = true; \/\/\/< Indicates if the layer is a neural layer\n static constexpr bool is_dense = false; \/\/\/< Indicates if the layer is dense\n static constexpr bool is_conv = false; \/\/\/< Indicates if the layer is convolutional\n static constexpr bool is_deconv = false; \/\/\/< Indicates if the layer is deconvolutional\n static constexpr bool is_standard = false; \/\/\/< Indicates if the layer is standard\n static constexpr bool is_rbm = false; \/\/\/< Indicates if the layer is RBM\n static constexpr bool is_pooling = false; \/\/\/< Indicates if the layer is a pooling layer\n static constexpr bool is_unpooling = false; \/\/\/< Indicates if the layer is an unpooling laye\n static constexpr bool is_transform = false; \/\/\/< Indicates if the layer is a transform layer\n static constexpr bool is_recurrent = false; \/\/\/< Indicates if the layer is a recurrent layer\n static constexpr bool is_multi = false; \/\/\/< Indicates if the layer is a multi-layer layer\n static constexpr bool is_dynamic = false; \/\/\/< Indicates if the layer is dynamic\n static constexpr bool pretrain_last = false; \/\/\/< Indicates if the layer is dynamic\n static constexpr bool sgd_supported = true; \/\/\/< Indicates if the layer is supported by SGD\n};\n\n\/*!\n * \\brief Specialization of sgd_context for batch_normalization_4d_layer_impl\n *\/\ntemplate <typename DBN, typename Desc, size_t L>\nstruct sgd_context<DBN, batch_normalization_4d_layer_impl<Desc>, L> {\n using layer_t = batch_normalization_4d_layer_impl<Desc>; \/\/\/< The current layer type\n using weight = typename layer_t::weight; \/\/\/< The data type for this layer\n\n static constexpr auto batch_size = DBN::batch_size;\n\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> input; \/\/\/< A batch of input\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> output; \/\/\/< A batch of output\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> errors; \/\/\/< A batch of errors\n\n sgd_context(const layer_t& \/*layer*\/){}\n};\n\n} \/\/end of dll namespace\n<commit_msg>Add missing timers<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"dll\/neural_layer.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Batch Normalization layer\n *\/\ntemplate <typename Desc>\nstruct batch_normalization_4d_layer_impl : neural_layer<batch_normalization_4d_layer_impl<Desc>, Desc> {\n using desc = Desc; \/\/\/< The descriptor type\n using base_type = neural_layer<batch_normalization_4d_layer_impl<Desc>, Desc>; \/\/\/< The base type\n using weight = typename desc::weight; \/\/\/< The data type of the layer\n using this_type = batch_normalization_4d_layer_impl<Desc>; \/\/\/< The type of this layer\n using layer_t = this_type; \/\/\/< This layer's type\n using dyn_layer_t = typename desc::dyn_layer_t; \/\/\/< The dynamic version of this layer\n\n static constexpr size_t Kernels = desc::Kernels; \/\/\/< The number of feature maps\n static constexpr size_t W = desc::Width; \/\/\/< The width of feature maps\n static constexpr size_t H = desc::Height; \/\/\/< The height of feature maps\n static constexpr weight e = 1e-8; \/\/\/< Epsilon for numerical stability\n\n using input_one_t = etl::fast_dyn_matrix<weight, Kernels, W, H>; \/\/\/< The type of one input\n using output_one_t = etl::fast_dyn_matrix<weight, Kernels, W, H>; \/\/\/< The type of one output\n using input_t = std::vector<input_one_t>; \/\/\/< The type of the input\n using output_t = std::vector<output_one_t>; \/\/\/< The type of the output\n\n etl::fast_matrix<weight, Kernels> gamma;\n etl::fast_matrix<weight, Kernels> beta;\n\n etl::fast_matrix<weight, Kernels> mean;\n etl::fast_matrix<weight, Kernels> var;\n\n etl::fast_matrix<weight, Kernels> last_mean;\n etl::fast_matrix<weight, Kernels> last_var;\n etl::fast_matrix<weight, Kernels> inv_var;\n\n etl::dyn_matrix<weight, 4> input_pre; \/\/\/ B x K x W x H\n\n weight momentum = 0.9;\n\n \/\/Backup gamma and beta\n std::unique_ptr<etl::fast_matrix<weight, Kernels>> bak_gamma; \/\/\/< Backup gamma\n std::unique_ptr<etl::fast_matrix<weight, Kernels>> bak_beta; \/\/\/< Backup beta\n\n batch_normalization_4d_layer_impl() : base_type() {\n gamma = 1.0;\n beta = 0.0;\n }\n\n \/*!\n * \\brief Returns a string representation of the layer\n *\/\n static std::string to_short_string([[maybe_unused]] std::string pre = \"\") {\n return \"batch_norm\";\n }\n\n \/*!\n * \\brief Returns a string representation of the layer\n *\/\n static std::string to_full_string([[maybe_unused]] std::string pre = \"\") {\n return \"batch_norm\";\n }\n\n \/*!\n * \\brief Return the number of trainable parameters of this network.\n * \\return The the number of trainable parameters of this network.\n *\/\n static constexpr size_t parameters() noexcept {\n return 4 * Kernels;\n }\n\n \/*!\n * \\brief Return the size of the input of this layer\n * \\return The size of the input of this layer\n *\/\n static constexpr size_t input_size() noexcept {\n return Kernels * W * H;\n }\n\n \/*!\n * \\brief Return the size of the output of this layer\n * \\return The size of the output of this layer\n *\/\n static constexpr size_t output_size() noexcept {\n return Kernels * W * H;\n }\n\n \/*!\n * \\brief Returns the output shape\n * \\return an std::string containing the description of the output shape\n *\/\n std::vector<size_t> output_shape([[maybe_unused]] const std::vector<size_t>& input_shape) const {\n return {Kernels, W, H};\n }\n\n using base_type::test_forward_batch;\n using base_type::train_forward_batch;\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void forward_batch(Output& output, const Input& input) const {\n test_forward_batch(output, input);\n }\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void test_forward_batch(Output& output, const Input& input) const {\n dll::auto_timer timer(\"bn:4d:test:forward\");\n\n const auto B = etl::dim<0>(input);\n\n auto inv_var = etl::force_temporary(1.0 \/ etl::sqrt(var + e));\n\n for (size_t b = 0; b < B; ++b) {\n for (size_t k = 0; k < Kernels; ++k) {\n output(b)(k) = (gamma(k) >> ((input(b)(k) - mean(k)) >> inv_var(k))) + beta(k);\n }\n }\n }\n\n \/*!\n * \\brief Apply the layer to the batch of input\n * \\param output The batch of output\n * \\param input The batch of input to apply the layer to\n *\/\n template <typename Input, typename Output>\n void train_forward_batch(Output& output, const Input& input) {\n dll::auto_timer timer(\"bn:4d:train:forward\");\n\n const auto B = etl::dim<0>(input);\n const auto S = B * W * H;\n\n \/\/ Compute the mean of the mini-batch\n last_mean = etl::bias_batch_mean_4d(input);\n\n \/\/ Compute the variance of the mini-batch\n last_var = 0;\n\n for (size_t b = 0; b < B; ++b) {\n for (size_t k = 0; k < Kernels; ++k) {\n last_var(k) += etl::sum((input(b)(k) - last_mean(k)) >> (input(b)(k) - last_mean(k)));\n }\n }\n\n last_var \/= S;\n\n inv_var = 1.0 \/ etl::sqrt(last_var + e);\n\n input_pre.inherit_if_null(input);\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n input_pre(b)(k) = (input(b)(k) - last_mean(k)) >> inv_var(k);\n output(b)(k) = (gamma(k) >> input_pre(b)(k)) + beta(k);\n }\n }\n\n \/\/\/\/ Update the current mean and variance\n mean = momentum * mean + (1.0 - momentum) * last_mean;\n var = momentum * var + (1.0 - momentum) * (S \/ (S - 1) * last_var);\n }\n\n \/*!\n * \\brief Adapt the errors, called before backpropagation of the errors.\n *\n * This must be used by layers that have both an activation fnction and a non-linearity.\n *\n * \\param context the training context\n *\/\n template <typename C>\n void adapt_errors([[maybe_unused]] C& context) const {}\n\n \/*!\n * \\brief Backpropagate the errors to the previous layers\n * \\param output The ETL expression into which write the output\n * \\param context The training context\n *\/\n template<typename HH, typename C>\n void backward_batch(HH&& output, C& context) const {\n dll::unsafe_auto_timer timer(\"bn:4d:backward\");\n\n const auto B = etl::dim<0>(context.input);\n const auto S = B * W * H;\n\n auto dxhat = etl::force_temporary_dim_only(context.errors);\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n dxhat(b)(k) = context.errors(b)(k) >> gamma(k);\n }\n }\n\n auto dxhat_l = etl::bias_batch_sum_4d(dxhat);\n auto dxhat_xhat_l = etl::bias_batch_sum_4d(dxhat >> input_pre);\n\n *dxhat_l;\n *dxhat_xhat_l;\n\n for(size_t b = 0; b < B; ++b){\n for (size_t k = 0; k < Kernels; ++k) {\n output(b)(k) = ((1.0 \/ S) * inv_var(k)) >> (S * dxhat(b)(k) - dxhat_l(k) - (input_pre(b)(k) >> dxhat_xhat_l(k)));\n }\n }\n }\n\n \/*!\n * \\brief Compute the gradients for this layer, if any\n * \\param context The trainng context\n *\/\n template<typename C>\n void compute_gradients(C& context) const {\n dll::unsafe_auto_timer timer(\"bn:4d:gradients\");\n\n \/\/ Gradients of gamma\n std::get<0>(context.up.context)->grad = etl::bias_batch_sum_4d(input_pre >> context.errors);\n\n \/\/ Gradients of beta\n std::get<1>(context.up.context)->grad = etl::bias_batch_sum_4d(context.errors);\n }\n\n \/*!\n * \\brief Prepare one empty output for this layer\n * \\return an empty ETL matrix suitable to store one output of this layer\n *\n * \\tparam Input The type of one Input\n *\/\n template <typename InputType>\n output_one_t prepare_one_output() const {\n return {};\n }\n\n \/*!\n * \\brief Prepare a set of empty outputs for this layer\n * \\param samples The number of samples to prepare the output for\n * \\return a container containing empty ETL matrices suitable to store samples output of this layer\n * \\tparam Input The type of one input\n *\/\n template <typename InputType>\n static output_t prepare_output(size_t samples) {\n return output_t{samples};\n }\n\n \/*!\n * \\brief Initialize the dynamic version of the layer from the fast version of the layer\n * \\param dyn Reference to the dynamic version of the layer that needs to be initialized\n *\/\n template<typename DLayer>\n static void dyn_init(DLayer& dyn){\n dyn.init_layer(Kernels, W, H);\n }\n\n \/*!\n * \\brief Returns the trainable variables of this layer.\n * \\return a tuple containing references to the variables of this layer\n *\/\n decltype(auto) trainable_parameters(){\n return std::make_tuple(std::ref(gamma), std::ref(beta));\n }\n\n \/*!\n * \\brief Returns the trainable variables of this layer.\n * \\return a tuple containing references to the variables of this layer\n *\/\n decltype(auto) trainable_parameters() const {\n return std::make_tuple(std::cref(gamma), std::cref(beta));\n }\n\n \/*!\n * \\brief Backup the weights in the secondary weights matrix\n *\/\n void backup_weights() {\n unique_safe_get(bak_gamma) = gamma;\n unique_safe_get(bak_beta) = beta;\n }\n\n \/*!\n * \\brief Restore the weights from the secondary weights matrix\n *\/\n void restore_weights() {\n gamma = *bak_gamma;\n beta = *bak_beta;\n }\n};\n\n\/\/ Declare the traits for the layer\n\ntemplate<typename Desc>\nstruct layer_base_traits<batch_normalization_4d_layer_impl<Desc>> {\n static constexpr bool is_neural = true; \/\/\/< Indicates if the layer is a neural layer\n static constexpr bool is_dense = false; \/\/\/< Indicates if the layer is dense\n static constexpr bool is_conv = false; \/\/\/< Indicates if the layer is convolutional\n static constexpr bool is_deconv = false; \/\/\/< Indicates if the layer is deconvolutional\n static constexpr bool is_standard = false; \/\/\/< Indicates if the layer is standard\n static constexpr bool is_rbm = false; \/\/\/< Indicates if the layer is RBM\n static constexpr bool is_pooling = false; \/\/\/< Indicates if the layer is a pooling layer\n static constexpr bool is_unpooling = false; \/\/\/< Indicates if the layer is an unpooling laye\n static constexpr bool is_transform = false; \/\/\/< Indicates if the layer is a transform layer\n static constexpr bool is_recurrent = false; \/\/\/< Indicates if the layer is a recurrent layer\n static constexpr bool is_multi = false; \/\/\/< Indicates if the layer is a multi-layer layer\n static constexpr bool is_dynamic = false; \/\/\/< Indicates if the layer is dynamic\n static constexpr bool pretrain_last = false; \/\/\/< Indicates if the layer is dynamic\n static constexpr bool sgd_supported = true; \/\/\/< Indicates if the layer is supported by SGD\n};\n\n\/*!\n * \\brief Specialization of sgd_context for batch_normalization_4d_layer_impl\n *\/\ntemplate <typename DBN, typename Desc, size_t L>\nstruct sgd_context<DBN, batch_normalization_4d_layer_impl<Desc>, L> {\n using layer_t = batch_normalization_4d_layer_impl<Desc>; \/\/\/< The current layer type\n using weight = typename layer_t::weight; \/\/\/< The data type for this layer\n\n static constexpr auto batch_size = DBN::batch_size;\n\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> input; \/\/\/< A batch of input\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> output; \/\/\/< A batch of output\n etl::fast_matrix<weight, batch_size, layer_t::Kernels, layer_t::W, layer_t::H> errors; \/\/\/< A batch of errors\n\n sgd_context(const layer_t& \/*layer*\/){}\n};\n\n} \/\/end of dll namespace\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: AdabasStat.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 15:38:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _DBAUI_ADASTAT_HXX_\n#include \"AdabasStat.hxx\"\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_\n#include <com\/sun\/star\/sdbc\/XStatement.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef DBAUI_ADABASSTAT_HRC\n#include \"AdabasStat.hrc\"\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _DBAUI_SQLMESSAGE_HXX_\n#include \"sqlmessage.hxx\"\n#endif\n\nusing namespace dbaui;\nDBG_NAME(OAdabasStatistics);\nnamespace dbaui\n{\n using namespace dbtools;\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::sdbc;\n using namespace ::com::sun::star::lang;\n\n\n\nOAdabasStatistics::OAdabasStatistics( Window* pParent,\n const ::rtl::OUString& _rUser,\n const Reference< ::com::sun::star::sdbc::XConnection >& _xCurrentConnection,\n const Reference< XMultiServiceFactory >& _xFactory)\n : ModalDialog( pParent, ModuleRes(DLG_ADABASSTAT) )\n ,m_FL_FILES( this , ResId(FL_FILES))\n ,m_FT_SYSDEVSPACE( this , ResId(FT_SYSDEVSPACE))\n ,m_ET_SYSDEVSPACE( this , STR_ADABAS_HELP_SYSDEVSPACE,ResId(ET_SYSDEVSPACE))\n ,m_FT_TRANSACTIONLOG( this , ResId(FT_TRANSACTIONLOG))\n ,m_ET_TRANSACTIONLOG( this , STR_ADABAS_HELP_TRANSACT,ResId(ET_TRANSACTIONLOG))\n ,m_FT_DATADEVSPACE( this , ResId(FT_DATADEVSPACE))\n ,m_LB_DATADEVS( this , STR_ADABAS_HELP_DATADEVSPACES,ResId(LB_DATADEVS))\n ,m_FL_SIZES( this , ResId(FL_SIZES))\n ,m_FT_SIZE( this , ResId(FT_SIZE))\n ,m_ET_SIZE( this , STR_ADABAS_HELP_SIZE,ResId(ET_SIZE))\n ,m_FT_FREESIZE( this , ResId(FT_FREESIZE))\n ,m_ET_FREESIZE( this , STR_ADABAS_HELP_FREESIZE,ResId(ET_FREESIZE))\n ,m_FT_MEMORYUSING( this , ResId(FT_MEMORYUSING))\n ,m_ET_MEMORYUSING( this , STR_ADABAS_HELP_MEMORYUSING,ResId(ET_MEMORYUSING))\n ,m_PB_OK( this , ResId(PB_OK))\n ,m_xConnection(_xCurrentConnection)\n ,m_bErrorShown(sal_False)\n{\n DBG_CTOR(OAdabasStatistics,NULL);\n\n FreeResource();\n\n DBG_ASSERT(m_xConnection.is(),\"No connection\");\n if(m_xConnection.is())\n {\n Reference<XStatement> xStmt;\n Reference<XResultSet> xRes;\n\n sal_Bool bCanSelect = sal_False;\n ::rtl::OUString aStmt;\n ::rtl::OUString sSchema = _rUser.toAsciiUpperCase();\n\n Reference<XDatabaseMetaData> xMetaData;\n \/\/ first read the sizes\n try\n {\n xMetaData = m_xConnection->getMetaData();\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"SERVERDBSTATISTICS\"),sSchema);\n\n if(bCanSelect)\n {\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT SERVERDBSIZE, UNUSEDPAGES FROM \");\n\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".\\\"SERVERDBSTATISTICS\\\"\");\n\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n\n\n Reference<XRow> xRow(xRes,UNO_QUERY);\n \/\/ first the db sizes\n if(xRes.is() && xRes->next())\n {\n double nUsedPages = xRow->getInt(1) \/ 256;\n double nFreePages = xRow->getInt(2) \/ 256;\n\n m_ET_SIZE.SetText(::rtl::OUString::valueOf((INT32)nUsedPages));\n m_ET_FREESIZE.SetText(::rtl::OUString::valueOf((INT32)nFreePages));\n m_ET_MEMORYUSING.SetValue(static_cast<sal_Int32>(((nUsedPages-nFreePages)\/nUsedPages)*100));\n }\n else\n showError();\n\n xRow = NULL;\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n\n \/\/ now fill the datadev spaces\n if(bCanSelect)\n {\n try\n {\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"DATADEVSPACES\"),sSchema);\n\n if(bCanSelect)\n {\n \/\/ then the db files\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT DEVSPACENAME FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".\\\"DATADEVSPACES\\\"\");\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n\n Reference<XRow> xRow(xRes,UNO_QUERY);\n while(xRes.is() && xRes->next())\n {\n m_LB_DATADEVS.InsertEntry(xRow->getString(1));\n }\n if(!m_LB_DATADEVS.GetEntryCount())\n showError();\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n\n \/\/ now fill the sysdatadev spaces\n if(bCanSelect)\n {\n try\n {\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"CONFIGURATION\"),sSchema);\n\n if(bCanSelect)\n {\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT * FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".CONFIGURATION WHERE DESCRIPTION LIKE 'SYS%DEVSPACE%NAME'\");\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n if(xRes.is() && xRes->next())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n m_ET_SYSDEVSPACE.SetText(xRow->getString(2));\n }\n else\n showError();\n\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT * FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".CONFIGURATION WHERE DESCRIPTION = 'TRANSACTION LOG NAME'\");\n xRes = xStmt->executeQuery(aStmt);\n if(xRes.is() && xRes->next())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n m_ET_TRANSACTIONLOG.SetText(xRow->getString(2));\n }\n else\n showError();\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n }\n }\n }\n\n m_ET_SYSDEVSPACE.SetSpecialReadOnly(sal_True);\n m_ET_TRANSACTIONLOG.SetSpecialReadOnly(sal_True);\n m_LB_DATADEVS.SetSpecialReadOnly(sal_True);\n m_ET_SIZE.SetSpecialReadOnly(sal_True);\n m_ET_FREESIZE.SetSpecialReadOnly(sal_True);\n m_ET_MEMORYUSING.SetSpecialReadOnly(sal_True);\n}\n\/\/------------------------------------------------------------------------\nOAdabasStatistics::~OAdabasStatistics()\n{\n DBG_DTOR(OAdabasStatistics,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool OAdabasStatistics::checkSystemTable(const ::rtl::OUString& _rsSystemTable, ::rtl::OUString& _rsSchemaName )\n{\n sal_Bool bCanSelect = sal_False;\n Reference<XDatabaseMetaData> xMeta = m_xConnection->getMetaData();\n if ( xMeta.is() )\n {\n Reference<XResultSet> xRes = xMeta->getTablePrivileges(Any(),::rtl::OUString::createFromAscii(\"%\"), _rsSystemTable);\n if(xRes.is())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n static const ::rtl::OUString sSelect = ::rtl::OUString::createFromAscii(\"SELECT\");\n \/\/ first the db sizes\n while( xRow.is() && xRes->next() )\n {\n _rsSchemaName = xRow->getString(2);\n if(sSelect == xRow->getString(6) && !xRow->wasNull())\n {\n bCanSelect = sal_True;\n break;\n }\n }\n ::comphelper::disposeComponent(xRes);\n }\n }\n\n return bCanSelect;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OAdabasStatistics::showError()\n{\n if(!m_bErrorShown)\n {\n OSQLMessageBox aMsg(GetParent(),GetText(),String(ModuleRes(STR_ADABAS_ERROR_SYSTEMTABLES)));\n aMsg.Execute();\n m_bErrorShown = sal_True;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n}\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.12.204); FILE MERGED 2005\/09\/05 17:33:29 rt 1.12.204.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AdabasStat.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 14:39:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _DBAUI_ADASTAT_HXX_\n#include \"AdabasStat.hxx\"\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_\n#include <com\/sun\/star\/sdbc\/XStatement.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef DBAUI_ADABASSTAT_HRC\n#include \"AdabasStat.hrc\"\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _DBAUI_SQLMESSAGE_HXX_\n#include \"sqlmessage.hxx\"\n#endif\n\nusing namespace dbaui;\nDBG_NAME(OAdabasStatistics);\nnamespace dbaui\n{\n using namespace dbtools;\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::sdbc;\n using namespace ::com::sun::star::lang;\n\n\n\nOAdabasStatistics::OAdabasStatistics( Window* pParent,\n const ::rtl::OUString& _rUser,\n const Reference< ::com::sun::star::sdbc::XConnection >& _xCurrentConnection,\n const Reference< XMultiServiceFactory >& _xFactory)\n : ModalDialog( pParent, ModuleRes(DLG_ADABASSTAT) )\n ,m_FL_FILES( this , ResId(FL_FILES))\n ,m_FT_SYSDEVSPACE( this , ResId(FT_SYSDEVSPACE))\n ,m_ET_SYSDEVSPACE( this , STR_ADABAS_HELP_SYSDEVSPACE,ResId(ET_SYSDEVSPACE))\n ,m_FT_TRANSACTIONLOG( this , ResId(FT_TRANSACTIONLOG))\n ,m_ET_TRANSACTIONLOG( this , STR_ADABAS_HELP_TRANSACT,ResId(ET_TRANSACTIONLOG))\n ,m_FT_DATADEVSPACE( this , ResId(FT_DATADEVSPACE))\n ,m_LB_DATADEVS( this , STR_ADABAS_HELP_DATADEVSPACES,ResId(LB_DATADEVS))\n ,m_FL_SIZES( this , ResId(FL_SIZES))\n ,m_FT_SIZE( this , ResId(FT_SIZE))\n ,m_ET_SIZE( this , STR_ADABAS_HELP_SIZE,ResId(ET_SIZE))\n ,m_FT_FREESIZE( this , ResId(FT_FREESIZE))\n ,m_ET_FREESIZE( this , STR_ADABAS_HELP_FREESIZE,ResId(ET_FREESIZE))\n ,m_FT_MEMORYUSING( this , ResId(FT_MEMORYUSING))\n ,m_ET_MEMORYUSING( this , STR_ADABAS_HELP_MEMORYUSING,ResId(ET_MEMORYUSING))\n ,m_PB_OK( this , ResId(PB_OK))\n ,m_xConnection(_xCurrentConnection)\n ,m_bErrorShown(sal_False)\n{\n DBG_CTOR(OAdabasStatistics,NULL);\n\n FreeResource();\n\n DBG_ASSERT(m_xConnection.is(),\"No connection\");\n if(m_xConnection.is())\n {\n Reference<XStatement> xStmt;\n Reference<XResultSet> xRes;\n\n sal_Bool bCanSelect = sal_False;\n ::rtl::OUString aStmt;\n ::rtl::OUString sSchema = _rUser.toAsciiUpperCase();\n\n Reference<XDatabaseMetaData> xMetaData;\n \/\/ first read the sizes\n try\n {\n xMetaData = m_xConnection->getMetaData();\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"SERVERDBSTATISTICS\"),sSchema);\n\n if(bCanSelect)\n {\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT SERVERDBSIZE, UNUSEDPAGES FROM \");\n\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".\\\"SERVERDBSTATISTICS\\\"\");\n\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n\n\n Reference<XRow> xRow(xRes,UNO_QUERY);\n \/\/ first the db sizes\n if(xRes.is() && xRes->next())\n {\n double nUsedPages = xRow->getInt(1) \/ 256;\n double nFreePages = xRow->getInt(2) \/ 256;\n\n m_ET_SIZE.SetText(::rtl::OUString::valueOf((INT32)nUsedPages));\n m_ET_FREESIZE.SetText(::rtl::OUString::valueOf((INT32)nFreePages));\n m_ET_MEMORYUSING.SetValue(static_cast<sal_Int32>(((nUsedPages-nFreePages)\/nUsedPages)*100));\n }\n else\n showError();\n\n xRow = NULL;\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n\n \/\/ now fill the datadev spaces\n if(bCanSelect)\n {\n try\n {\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"DATADEVSPACES\"),sSchema);\n\n if(bCanSelect)\n {\n \/\/ then the db files\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT DEVSPACENAME FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".\\\"DATADEVSPACES\\\"\");\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n\n Reference<XRow> xRow(xRes,UNO_QUERY);\n while(xRes.is() && xRes->next())\n {\n m_LB_DATADEVS.InsertEntry(xRow->getString(1));\n }\n if(!m_LB_DATADEVS.GetEntryCount())\n showError();\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n\n \/\/ now fill the sysdatadev spaces\n if(bCanSelect)\n {\n try\n {\n bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii(\"CONFIGURATION\"),sSchema);\n\n if(bCanSelect)\n {\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT * FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".CONFIGURATION WHERE DESCRIPTION LIKE 'SYS%DEVSPACE%NAME'\");\n xStmt = m_xConnection->createStatement();\n xRes = xStmt->executeQuery(aStmt);\n if(xRes.is() && xRes->next())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n m_ET_SYSDEVSPACE.SetText(xRow->getString(2));\n }\n else\n showError();\n\n aStmt = ::rtl::OUString::createFromAscii(\"SELECT * FROM \");\n aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);\n aStmt += ::rtl::OUString::createFromAscii(\".CONFIGURATION WHERE DESCRIPTION = 'TRANSACTION LOG NAME'\");\n xRes = xStmt->executeQuery(aStmt);\n if(xRes.is() && xRes->next())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n m_ET_TRANSACTIONLOG.SetText(xRow->getString(2));\n }\n else\n showError();\n }\n else\n showError();\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n try\n {\n ::comphelper::disposeComponent(xStmt);\n }\n catch(const Exception&)\n {\n OSL_ENSURE(sal_False, \"OAdabasStatistics::OAdabasStatistics: caught an exception!\");\n }\n }\n }\n }\n\n m_ET_SYSDEVSPACE.SetSpecialReadOnly(sal_True);\n m_ET_TRANSACTIONLOG.SetSpecialReadOnly(sal_True);\n m_LB_DATADEVS.SetSpecialReadOnly(sal_True);\n m_ET_SIZE.SetSpecialReadOnly(sal_True);\n m_ET_FREESIZE.SetSpecialReadOnly(sal_True);\n m_ET_MEMORYUSING.SetSpecialReadOnly(sal_True);\n}\n\/\/------------------------------------------------------------------------\nOAdabasStatistics::~OAdabasStatistics()\n{\n DBG_DTOR(OAdabasStatistics,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool OAdabasStatistics::checkSystemTable(const ::rtl::OUString& _rsSystemTable, ::rtl::OUString& _rsSchemaName )\n{\n sal_Bool bCanSelect = sal_False;\n Reference<XDatabaseMetaData> xMeta = m_xConnection->getMetaData();\n if ( xMeta.is() )\n {\n Reference<XResultSet> xRes = xMeta->getTablePrivileges(Any(),::rtl::OUString::createFromAscii(\"%\"), _rsSystemTable);\n if(xRes.is())\n {\n Reference<XRow> xRow(xRes,UNO_QUERY);\n static const ::rtl::OUString sSelect = ::rtl::OUString::createFromAscii(\"SELECT\");\n \/\/ first the db sizes\n while( xRow.is() && xRes->next() )\n {\n _rsSchemaName = xRow->getString(2);\n if(sSelect == xRow->getString(6) && !xRow->wasNull())\n {\n bCanSelect = sal_True;\n break;\n }\n }\n ::comphelper::disposeComponent(xRes);\n }\n }\n\n return bCanSelect;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OAdabasStatistics::showError()\n{\n if(!m_bErrorShown)\n {\n OSQLMessageBox aMsg(GetParent(),GetText(),String(ModuleRes(STR_ADABAS_ERROR_SYSTEMTABLES)));\n aMsg.Execute();\n m_bErrorShown = sal_True;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/ details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements Live Variables analysis for source-level CFGs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/CFG.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtDeclVisitor.h\"\n#include \"clang\/Analysis\/FlowSensitive\/DataflowSolver.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Dataflow initialization logic.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\nclass VISIBILITY_HIDDEN RegisterDecls \n : public CFGRecStmtDeclVisitor<RegisterDecls> {\n \n LiveVariables::AnalysisDataTy& AD;\npublic:\n RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {} \n void VisitVarDecl(VarDecl* VD) { AD.Register(VD); }\n CFG& getCFG() { return AD.getCFG(); }\n};\n} \/\/ end anonymous namespace\n\n\nLiveVariables::LiveVariables(CFG& cfg, FunctionDecl& FD) {\n getAnalysisData().setCFG(&cfg);\n\n for (FunctionDecl::param_iterator I=FD.param_begin(), E=FD.param_end();\n I !=E; ++I)\n getAnalysisData().Register(*I);\n \n \/\/ Now register all the other VarDecls;\n RegisterDecls R(getAnalysisData());\n cfg.VisitBlockStmts(R);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer functions.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n \nstatic const bool Alive = true;\nstatic const bool Dead = false; \n\nclass VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{\n LiveVariables::AnalysisDataTy& AD;\n LiveVariables::ValTy LiveState;\npublic:\n TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n LiveVariables::ValTy& getVal() { return LiveState; }\n CFG& getCFG() { return AD.getCFG(); }\n \n void VisitDeclRefExpr(DeclRefExpr* DR);\n void VisitBinaryOperator(BinaryOperator* B);\n void VisitAssign(BinaryOperator* B);\n void VisitDeclStmt(DeclStmt* DS);\n void VisitUnaryOperator(UnaryOperator* U);\n void Visit(Stmt *S);\n};\n \nvoid TransferFuncs::Visit(Stmt *S) {\n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n if (S == getCurrentBlkStmt()) {\n if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;\n StmtVisitor<TransferFuncs,void>::Visit(S);\n }\n else if (!getCFG().isBlkExpr(S))\n StmtVisitor<TransferFuncs,void>::Visit(S);\n else\n \/\/ For block-level expressions, mark that they are live.\n LiveState(S,AD) = Alive;\n}\n\nvoid TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {\n if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl())) \n LiveState(V,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { \n if (B->isAssignmentOp()) VisitAssign(B);\n else VisitStmt(B);\n}\n\nvoid TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {\n Expr *E = U->getSubExpr();\n \n switch (U->getOpcode()) {\n case UnaryOperator::SizeOf: return; \n case UnaryOperator::PostInc:\n case UnaryOperator::PostDec:\n case UnaryOperator::PreInc:\n case UnaryOperator::PreDec:\n case UnaryOperator::AddrOf:\n \/\/ Walk through the subexpressions, blasting through ParenExprs\n \/\/ until we either find a DeclRefExpr or some non-DeclRefExpr\n \/\/ expression.\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens())) \n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) { \n \/\/ Treat the --\/++\/& operator as a kill.\n LiveState(VD, AD) = Dead;\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n return VisitDeclRefExpr(DR);\n }\n\n \/\/ Fall-through.\n \n default:\n return Visit(E);\n }\n}\n \nvoid TransferFuncs::VisitAssign(BinaryOperator* B) { \n Expr* LHS = B->getLHS();\n\n \/\/ Assigning to a variable?\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {\n LiveState(DR->getDecl(),AD) = Dead;\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n \n \/\/ Handle things like +=, etc., which also generate \"uses\"\n \/\/ of a variable. Do this just by visiting the subexpression.\n if (B->getOpcode() != BinaryOperator::Assign)\n VisitDeclRefExpr(DR);\n }\n else \/\/ Not assigning to a variable. Process LHS as usual.\n Visit(LHS);\n \n Visit(B->getRHS());\n}\n\nvoid TransferFuncs::VisitDeclStmt(DeclStmt* DS) {\n \/\/ Declarations effectively \"kill\" a variable since they cannot\n \/\/ possibly be live before they are declared.\n for (ScopedDecl* D = DS->getDecl(); D != NULL; D = D->getNextDeclarator()) {\n LiveState(D,AD) = Dead;\n\n if (VarDecl* VD = dyn_cast<VarDecl>(D))\n if (Expr* Init = VD->getInit())\n Visit(Init);\n }\n}\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Merge operator: if something is live on any successor block, it is live\n\/\/ in the current block (a set union).\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\ntypedef DeclBitVector_Types::Union Merge;\ntypedef DataflowSolver<LiveVariables,TransferFuncs,Merge> Solver;\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ External interface to run Liveness analysis.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nvoid LiveVariables::runOnCFG(CFG& cfg) {\n Solver S(*this);\n S.runOnCFG(cfg);\n}\n\nvoid LiveVariables::runOnAllBlocks(const CFG& cfg,\n LiveVariables::ObserverTy* Obs,\n bool recordStmtValues) {\n Solver S(*this);\n ObserverTy* OldObserver = getAnalysisData().Observer;\n getAnalysisData().Observer = Obs;\n S.runOnAllBlocks(cfg, recordStmtValues);\n getAnalysisData().Observer = OldObserver;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ liveness queries\n\/\/\n\nbool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {\n return getBlockData(B)(D,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {\n return Live(D,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {\n return getStmtData(Loc)(StmtVal,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {\n return getStmtData(Loc)(D,getAnalysisData());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ printing liveness state for debugging\n\/\/\n\nvoid LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {\n const AnalysisDataTy& AD = getAnalysisData();\n \n for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),\n E = AD.end_decl(); I!=E; ++I)\n if (V.getDeclBit(I->second)) { \n SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());\n \n fprintf(stderr, \" %s <%s:%u:%u>\\n\", \n I->first->getIdentifier()->getName(),\n SM.getSourceName(PhysLoc),\n SM.getLineNumber(PhysLoc),\n SM.getColumnNumber(PhysLoc));\n }\n} \n\nvoid LiveVariables::dumpBlockLiveness(SourceManager& M) const {\n for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),\n E = getBlockDataMap().end(); I!=E; ++I) {\n fprintf(stderr, \"\\n[ B%d (live variables at block exit) ]\\n\",\n I->first->getBlockID());\n \n dumpLiveness(I->second,M);\n }\n\n fprintf(stderr,\"\\n\");\n}\n<commit_msg>Fixed horrid bug in LiveVariables analysis where we were only merging at confluence points the liveness information for variables (Decls) and NOT block-level expressions.<commit_after>\/\/=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/ details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements Live Variables analysis for source-level CFGs.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/CFG.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtDeclVisitor.h\"\n#include \"clang\/Analysis\/FlowSensitive\/DataflowSolver.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Dataflow initialization logic.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\nclass VISIBILITY_HIDDEN RegisterDecls \n : public CFGRecStmtDeclVisitor<RegisterDecls> {\n \n LiveVariables::AnalysisDataTy& AD;\npublic:\n RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {} \n void VisitVarDecl(VarDecl* VD) { AD.Register(VD); }\n CFG& getCFG() { return AD.getCFG(); }\n};\n} \/\/ end anonymous namespace\n\n\nLiveVariables::LiveVariables(CFG& cfg, FunctionDecl& FD) {\n getAnalysisData().setCFG(&cfg);\n\n for (FunctionDecl::param_iterator I=FD.param_begin(), E=FD.param_end();\n I !=E; ++I)\n getAnalysisData().Register(*I);\n \n \/\/ Now register all the other VarDecls;\n RegisterDecls R(getAnalysisData());\n cfg.VisitBlockStmts(R);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer functions.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\n \nstatic const bool Alive = true;\nstatic const bool Dead = false; \n\nclass VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{\n LiveVariables::AnalysisDataTy& AD;\n LiveVariables::ValTy LiveState;\npublic:\n TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}\n\n LiveVariables::ValTy& getVal() { return LiveState; }\n CFG& getCFG() { return AD.getCFG(); }\n \n void VisitDeclRefExpr(DeclRefExpr* DR);\n void VisitBinaryOperator(BinaryOperator* B);\n void VisitAssign(BinaryOperator* B);\n void VisitDeclStmt(DeclStmt* DS);\n void VisitUnaryOperator(UnaryOperator* U);\n void Visit(Stmt *S);\n};\n \nvoid TransferFuncs::Visit(Stmt *S) {\n if (AD.Observer)\n AD.Observer->ObserveStmt(S,AD,LiveState);\n \n if (S == getCurrentBlkStmt()) {\n if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;\n StmtVisitor<TransferFuncs,void>::Visit(S);\n }\n else if (!getCFG().isBlkExpr(S))\n StmtVisitor<TransferFuncs,void>::Visit(S);\n else\n \/\/ For block-level expressions, mark that they are live.\n LiveState(S,AD) = Alive;\n}\n\nvoid TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {\n if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl())) \n LiveState(V,AD) = Alive;\n}\n \nvoid TransferFuncs::VisitBinaryOperator(BinaryOperator* B) { \n if (B->isAssignmentOp()) VisitAssign(B);\n else VisitStmt(B);\n}\n\nvoid TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {\n Expr *E = U->getSubExpr();\n \n switch (U->getOpcode()) {\n case UnaryOperator::SizeOf: return; \n case UnaryOperator::PostInc:\n case UnaryOperator::PostDec:\n case UnaryOperator::PreInc:\n case UnaryOperator::PreDec:\n case UnaryOperator::AddrOf:\n \/\/ Walk through the subexpressions, blasting through ParenExprs\n \/\/ until we either find a DeclRefExpr or some non-DeclRefExpr\n \/\/ expression.\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens())) \n if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) { \n \/\/ Treat the --\/++\/& operator as a kill.\n LiveState(VD, AD) = Dead;\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n return VisitDeclRefExpr(DR);\n }\n\n \/\/ Fall-through.\n \n default:\n return Visit(E);\n }\n}\n \nvoid TransferFuncs::VisitAssign(BinaryOperator* B) { \n Expr* LHS = B->getLHS();\n\n \/\/ Assigning to a variable?\n if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {\n LiveState(DR->getDecl(),AD) = Dead;\n if (AD.Observer) { AD.Observer->ObserverKill(DR); }\n \n \/\/ Handle things like +=, etc., which also generate \"uses\"\n \/\/ of a variable. Do this just by visiting the subexpression.\n if (B->getOpcode() != BinaryOperator::Assign)\n VisitDeclRefExpr(DR);\n }\n else \/\/ Not assigning to a variable. Process LHS as usual.\n Visit(LHS);\n \n Visit(B->getRHS());\n}\n\nvoid TransferFuncs::VisitDeclStmt(DeclStmt* DS) {\n \/\/ Declarations effectively \"kill\" a variable since they cannot\n \/\/ possibly be live before they are declared.\n for (ScopedDecl* D = DS->getDecl(); D != NULL; D = D->getNextDeclarator()) {\n LiveState(D,AD) = Dead;\n\n if (VarDecl* VD = dyn_cast<VarDecl>(D))\n if (Expr* Init = VD->getInit())\n Visit(Init);\n }\n}\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Merge operator: if something is live on any successor block, it is live\n\/\/ in the current block (a set union).\n\/\/===----------------------------------------------------------------------===\/\/ \n\nnamespace {\ntypedef ExprDeclBitVector_Types::Union Merge;\ntypedef DataflowSolver<LiveVariables,TransferFuncs,Merge> Solver;\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ External interface to run Liveness analysis.\n\/\/===----------------------------------------------------------------------===\/\/ \n\nvoid LiveVariables::runOnCFG(CFG& cfg) {\n Solver S(*this);\n S.runOnCFG(cfg);\n}\n\nvoid LiveVariables::runOnAllBlocks(const CFG& cfg,\n LiveVariables::ObserverTy* Obs,\n bool recordStmtValues) {\n Solver S(*this);\n ObserverTy* OldObserver = getAnalysisData().Observer;\n getAnalysisData().Observer = Obs;\n S.runOnAllBlocks(cfg, recordStmtValues);\n getAnalysisData().Observer = OldObserver;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ liveness queries\n\/\/\n\nbool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {\n return getBlockData(B)(D,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {\n return Live(D,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {\n return getStmtData(Loc)(StmtVal,getAnalysisData());\n}\n\nbool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {\n return getStmtData(Loc)(D,getAnalysisData());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ printing liveness state for debugging\n\/\/\n\nvoid LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {\n const AnalysisDataTy& AD = getAnalysisData();\n \n for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),\n E = AD.end_decl(); I!=E; ++I)\n if (V.getDeclBit(I->second)) { \n SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());\n \n fprintf(stderr, \" %s <%s:%u:%u>\\n\", \n I->first->getIdentifier()->getName(),\n SM.getSourceName(PhysLoc),\n SM.getLineNumber(PhysLoc),\n SM.getColumnNumber(PhysLoc));\n }\n} \n\nvoid LiveVariables::dumpBlockLiveness(SourceManager& M) const {\n for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),\n E = getBlockDataMap().end(); I!=E; ++I) {\n fprintf(stderr, \"\\n[ B%d (live variables at block exit) ]\\n\",\n I->first->getBlockID());\n \n dumpLiveness(I->second,M);\n }\n\n fprintf(stderr,\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2017-2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.02.25\n\n\/\/ main.cpp\n\n\n#include <iostream>\n#include \"..\/src\/thread\/ThreadPool.hpp\"\n#include \"..\/src\/configs\/Options.hpp\"\n#include \"..\/src\/configs\/Config.hpp\"\n#include \"..\/src\/server\/Server.hpp\"\n#include \"..\/src\/utils\/Daemon.hpp\"\n#include \"..\/src\/log\/LoggerManager.hpp\"\n\nint main(int argc, char *argv[])\n{\n\tDaemon::SetProcessName();\n\tDaemon::StartManageSignals();\n\n\tstd::shared_ptr<Options> options;\n\ttry\n\t{\n\t\toptions = std::make_shared<Options>(argc, argv);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail get opptions ← %s\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstd::shared_ptr<Config> configs;\n\ttry\n\t{\n\t\tconfigs = std::make_shared<Config>(options);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail get configuration ← %s\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tLoggerManager::init(configs);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail logging initialize ← %s\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tP7_Set_Crash_Handler();\n\n\tLog log(\"Main\");\n\tlog.info(\"Start daemon\");\n\n\tstd::shared_ptr<Server> server;\n\ttry\n\t{\n\t\tserver = std::make_shared<Server>(configs);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tlog.error(\"Fail init server ← %s\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\/\/\tDaemon::SetDaemonMode();\n\n\tserver->start();\n\n\tDaemon::doAtShutdown([server](){\n\t\tserver->stop();\n\t});\n\n\tserver->wait();\n\n\tlog.info(\"Stop daemon\");\n\n\tLog::finalFlush();\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Little change<commit_after>\/\/ Copyright © 2017-2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.02.25\n\n\/\/ main.cpp\n\n\n#include <iostream>\n#include \"..\/src\/thread\/ThreadPool.hpp\"\n#include \"..\/src\/configs\/Options.hpp\"\n#include \"..\/src\/configs\/Config.hpp\"\n#include \"..\/src\/server\/Server.hpp\"\n#include \"..\/src\/utils\/Daemon.hpp\"\n#include \"..\/src\/log\/LoggerManager.hpp\"\n\nint main(int argc, char *argv[])\n{\n\tDaemon::SetProcessName();\n\tDaemon::StartManageSignals();\n\n\tstd::shared_ptr<Options> options;\n\ttry\n\t{\n\t\toptions = std::make_shared<Options>(argc, argv);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail get opptions ← %s\\n\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tstd::shared_ptr<Config> configs;\n\ttry\n\t{\n\t\tconfigs = std::make_shared<Config>(options);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail get configuration ← %s\\n\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tLoggerManager::init(configs);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tprintf(\"Fail logging initialize ← %s\\n\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tP7_Set_Crash_Handler();\n\n\tLog log(\"Main\");\n\tlog.info(\"Start daemon\");\n\n\tstd::shared_ptr<Server> server;\n\ttry\n\t{\n\t\tserver = std::make_shared<Server>(configs);\n\t}\n\tcatch (const std::exception& exception)\n\t{\n\t\tlog.error(\"Fail init server ← %s\", exception.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\/\/\tDaemon::SetDaemonMode();\n\n\tserver->start();\n\n\tDaemon::doAtShutdown([server](){\n\t\tserver->stop();\n\t});\n\n\tserver->wait();\n\n\tlog.info(\"Stop daemon\");\n\n\tLog::finalFlush();\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>303. Range Sum Query - Immutable<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"PhysicsThread.h\"\n#include \"PhysicsObject.h\"\n#include \"Collision.h\"\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <QDebug>\n\n\n\n\n\nPhysicsThread::PhysicsThread()\n{\n}\n\nPhysicsThread::PhysicsThread(int minx ,int miny ,int minz ,int maxx ,int maxy ,int maxz)\n{\n\n\tthis->minx = minx;\n\tthis->miny = miny;\n\tthis->minz = minz;\n\n\tthis->maxx = maxx;\n\tthis->maxy = maxy;\n\tthis->maxz = maxz;\n\n}\n\nPhysicsThread::~PhysicsThread()\n{\n\n}\n\nvoid PhysicsThread::run(){\n\tqDebug() << \"SUCCESSFULLY STARTED UP PHYSICS-SIMULATION\";\n\tforever{\n\t\tmutex.lock();\n\t\tqDebug() << \"RUNNING PHYSICS-SIMULATION\";\n\t\trunSimulation(1.0\/60.0);\n\t\tif(stop){\n\t\t\tbreak;\n\t\t}\n\t\tif(bPause){\n\t\t\tpauseManager.wait(&mutex);\n\t\t}\n\t\tmutex.unlock();\n\t}\n}\n\nvoid PhysicsThread::TogglePause()\n{\n\tbPause = !bPause;\n\tif(!bPause){\n\t\tpauseManager.wakeAll();\n\t}\n}\n\nvoid PhysicsThread::pause()\n{\n\tbPause = true;\n}\n\nvoid PhysicsThread::resume()\n{\n\tbPause = false;\n\tpauseManager.wakeAll();\n}\n\nvoid PhysicsThread::quit()\n{\n\tstop = true;\n\tQThread::quit();\n\tqDebug() << \"STOPPING PHYSICS-THREAD\";\n}\n\nvoid PhysicsThread::runSimulation(const double& delta){\n\n\t\/\/ Collision Border\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\n\t\tPhysicsSphere* op = pobjectsSphere.at(i);\n\t\tif(op->getIsMovable()){\n\t\t\t\/\/ is Sphere TODO\n\t\t\tif(true){\n\t\t\t\tif(op->getX()-(op->getSize()) < minx ){\n\t\t\t\t\tif(op->getVelocityX() < 0){\n\t\t\t\t\t\top->setVelocityX(-op->getVelocityX());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityX(op->getVelocityX());\n\t\t\t\t\t}\n\t\t\t\t}else if(op->getX()+(op->getSize()) > maxx) {\n\t\t\t\t\tif(op->getVelocityX() > 0){\n\t\t\t\t\t\top->setVelocityX(-op->getVelocityX());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityX(op->getVelocityX());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(op->getY()-(op->getSize()) < miny){\n\t\t\t\t\tif(op->getVelocityY() < 0){\n\t\t\t\t\t\top->setVelocityY(-op->getVelocityY() * op->getRemainingEnergy());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityY(op->getVelocityY());\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif(op->getY()+(op->getSize()) > maxy){\n\t\t\t\t\t\tif(op->getVelocityY() > 0){\n\t\t\t\t\t\t\top->setVelocityY(-op->getVelocityY());\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\top->setVelocityY(op->getVelocityY());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Gravity\n\t\t\t\t\top->setVelocityY(op->getVelocityY() + g*delta*op->getMass());\n\t\t\t\t}\n\n\t\t\t\tif(op->getZ()-(op->getSize()) < minz){\n\t\t\t\t\tif(op->getVelocityZ() < 0){\n\t\t\t\t\t\top->setVelocityZ(-op->getVelocityZ());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityZ(op->getVelocityZ());\n\t\t\t\t\t}\n\t\t\t\t}else if(op->getZ()+(op->getSize()) > maxz){\n\t\t\t\t\tif(op->getVelocityZ() > 0){\n\t\t\t\t\t\top->setVelocityZ(-op->getVelocityZ());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityZ(op->getVelocityZ());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Collision Sphere on Sphere\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\t\tPhysicsSphere* op1 = pobjectsSphere.at(i);\n\t\tfor(int j = i ; j < pobjectsSphere.size() ; j++) {\n\t\t\tPhysicsSphere* op2 = pobjectsSphere.at(j);\n\n\t\t\t\/\/ bool Collision::SphereVersusSphere(const int& x1 , const int& y1 , const int& z1 , const int& size1 , const int& x2 , const int& y2 , const int& z2 , const int& size2)\n\t\t\t\/\/ Sphere on Sphere\n\t\t\t\/\/ SIZE\n\t\t\tif(i != j && Collision::SphereVersusSphere(op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getX() ,op2->getY() ,op2->getZ() ,op2->getSize())){\n\n\t\t\t\tdouble tempX (op1->getX() - op2->getX());\n\t\t\t\tdouble tempY (op1->getY() - op2->getY());\n\t\t\t\tdouble tempZ (op1->getZ() - op2->getZ());\n\n\t\t\t\tdouble norm = sqrt(tempX*tempX + tempY*tempY + tempZ*tempZ);\n\n\t\t\t\ttempX = tempX \/ norm;\n\t\t\t\ttempY = tempY \/ norm;\n\t\t\t\ttempZ = tempZ \/ norm;\n\n\t\t\t\tdouble a1 = (op1->getVelocityX() * tempX) + (op1->getVelocityY() * tempY) + (op1->getVelocityZ() * tempZ);\n\t\t\t\tdouble a2 = (op2->getVelocityX() * tempX) + (op2->getVelocityY() * tempY) + (op2->getVelocityZ() * tempZ);\n\n\t\t\t\t\/\/ double optimizedP = (2.0D * (a1 - a2)) \/ (e1.getWhight() + e2.getWhight());\n\n\t\t\t\tdouble optimizedP = (2.0 * (a1 - a2)) \/ (op1->getMass() + op2->getMass());\n\n\t\t\t\t\/\/ fix\n\t\t\t\toptimizedP = std::abs(optimizedP);\n\n\t\t\t\tqDebug() << optimizedP;\n\n\t\t\t\t\/\/ 0.9 Verlusst\n\t\t\t\tif(op1->getIsMovable()){\n\t\t\t\t\top1->setVelocityX( op1->getVelocityX() + (optimizedP * op2->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top1->setVelocityY( op1->getVelocityY() + (optimizedP * op2->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top1->setVelocityZ( op1->getVelocityZ() + (optimizedP * op2->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t}\n\n\t\t\t\tif(op2->getIsMovable()){\n\t\t\t\t\top2->setVelocityX( op2->getVelocityX() - (optimizedP * op1->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top2->setVelocityY( op2->getVelocityY() - (optimizedP * op1->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top2->setVelocityZ( op2->getVelocityZ() - (optimizedP * op1->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO\n\t\t\t\tqDebug() << op1->getPosition() << \"BEFORE\";\n\t\t\t\top1->setX(op1->getX() + op1->getVelocityX() * delta);\n\t\t\t\top1->setY(op1->getY() + op1->getVelocityY() * delta);\n\t\t\t\top1->setZ(op1->getZ() + op1->getVelocityZ() * delta);\n\n\t\t\t\top2->setX(op2->getX() + op2->getVelocityX() * delta);\n\t\t\t\top2->setY(op2->getY() + op2->getVelocityY() * delta);\n\t\t\t\top2->setZ(op2->getZ() + op2->getVelocityZ() * delta);\n\t\t\t\tqDebug() << op1->getPosition() << \"AFTER\";\n\t\t\t}\n\t\t}\n\t}\n\n\/\/\t\/\/ Collision Shere on Box\n\/\/\t\/\/ bool Collision::SphereVersusBox\n\/\/\t\/\/(const int& sphereX ,const int& sphereY ,const int& sphereZ ,const int& sphereSize\n\/\/\t\/\/ ,const int& boxMinX ,const int& boxMinY ,const int& boxMinZ ,const int& boxMaxX ,const int& boxMaxY ,const int& boxMaxZ)\n\n\n for(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n PhysicsSphere* op1 = pobjectsSphere.at(i);\n for(int j = 0 ; j < pobjectsBox.size() ; j++) {\n PhysicsBox* op2 = pobjectsBox.at(j);\n\n\n\n if(Collision::SphereVersusBox( op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getMinX()+op2->getX() ,op2->getMinY()+op2->getY() ,op2->getMinZ()+op2->getZ() ,op2->getMaxX()+op2->getX() ,op2->getMaxY()+op2->getY() ,op2->getMaxZ()+op2->getZ())){\n\n qDebug() << \"Test\";\n\n if((op1->getX()+op1->getSize()) > op2->getMinX() && op1->getX() < op2->getMinX()+op2->getX()){\n\n if(op1->getVelocityX() > 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }\n if((op1->getX()-op1->getSize()) < op2->getMaxX() && op1->getX() > op2->getMaxX()+op2->getX()){\n if(op1->getVelocityX() < 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }\n\n if((op1->getY()+op1->getSize()) > op2->getMinY() && op1->getY() < op2->getMinY()+op2->getY()){\n if(op1->getVelocityY() > 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }\n if((op1->getY()-op1->getSize()) < op2->getMaxY() && op1->getY() > op2->getMaxY()+op2->getY()){\n\n if(op1->getVelocityY() < 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }\n\n if((op1->getZ()+op1->getSize()) > op2->getMinZ() && op1->getZ() < op2->getMinZ()+op2->getZ()){\n if(op1->getVelocityZ() > 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }\n if((op1->getZ()-op1->getSize()) < op2->getMaxZ() && op1->getZ() > op2->getMaxZ()+op2->getZ()){\n if(op1->getVelocityZ() < 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }\n\n\n\n\n \/*\n if(closeDistance > std::abs( op1->getX() - op2->getMinX()) && op1->getX() > op2->getMaxX()){\n closeDistance = std::abs( op1->getX() - op2->getMaxX());\n point = 0;\n\n }\n\n if(closeDistance > std::abs( op1->getX() - op2->getMinX()) && op1->getX() < op2->getMinX()){\n closeDistance = std::abs( op1->getX() - op2->getMinX());\n point = 1;\n }\n\n if(closeDistance > std::abs( op1->getY() - op2->getMaxY()) && op1->getY() > op2->getMaxY()){\n closeDistance = std::abs( op1->getY() - op2->getMaxY());\n point = 2;\n }\n\n if(closeDistance > std::abs( op1->getY() - op2->getMinY()) && op1->getY() < op2->getMinY()){\n closeDistance = std::abs( op1->getY() - op2->getMinY());\n point = 3;\n }\n\n if(closeDistance > std::abs( op1->getZ() - op2->getMaxZ()) && op1->getZ() > op2->getMaxZ()){\n closeDistance = std::abs( op1->getZ() - op2->getMaxZ());\n point = 4;\n }\n\n if(closeDistance > std::abs( op1->getZ() - op2->getMinZ()) && op1->getZ() < op2->getMinZ()){\n closeDistance = std::abs( op1->getZ() - op2->getMinZ());\n point = 5;\n }\n\n qDebug() << point << \" p \";\n\n if(point == 0){\n \/\/ maxX\n if(op1->getVelocityX() < 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }else if(point == 1){\n \/\/ minX\n if(op1->getVelocityX() > 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }else if(point == 2){\n \/\/ maxY\n if(op1->getVelocityY() < 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }else if(point == 3){\n \/\/ minY\n if(op1->getVelocityY() > 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }else if(point == 4){\n \/\/ maxZ\n if(op1->getVelocityZ() < 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }else if(point == 5){\n \/\/ minZ\n if(op1->getVelocityZ() > 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }\n *\/\n }\n }\n }\n\n\t\/\/ Move\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\t\tPhysicsSphere* op = pobjectsSphere.at(i);\n\t\top->setX(op->getX() + op->getVelocityX()*delta);\n\t\top->setY(op->getY() + op->getVelocityY()*delta);\n\t\top->setZ(op->getZ() + op->getVelocityZ()*delta);\n\t\t\/\/qDebug() << op->getVelocity();\n\n\t}\n\tthis->msleep(pauseTickTime);\n}\n\nint PhysicsThread::getMiny() const\n{\n\treturn miny;\n}\n\nvoid PhysicsThread::setMiny(const int value)\n{\n\tminy = value;\n}\n\nint PhysicsThread::getMinz() const\n{\n\treturn minz;\n}\n\nvoid PhysicsThread::setMinz(const int value)\n{\n\tminz = value;\n}\n\nint PhysicsThread::getMaxx() const\n{\n\treturn maxx;\n}\n\nvoid PhysicsThread::setMaxx(const int value)\n{\n\tmaxx = value;\n}\n\nint PhysicsThread::getMaxy() const\n{\n\treturn maxy;\n}\n\nvoid PhysicsThread::setMaxy(const int value)\n{\n\tmaxy = value;\n}\n\nint PhysicsThread::getMaxz() const\n{\n\treturn maxz;\n}\n\nvoid PhysicsThread::setMaxz(const int value)\n{\n\tmaxz = value;\n}\n\nint PhysicsThread::getMinx() const\n{\n\treturn minx;\n}\n\nvoid PhysicsThread::setMinx(const int value)\n{\n\tminx = value;\n}\n\nvoid PhysicsThread::registerPhysicsSphere(PhysicsSphere* physicsObject)\n{\n\tpobjectsSphere.push_back(physicsObject);\n}\n\nvoid PhysicsThread::deregisterPhysicsSphere(PhysicsSphere* physicsObject)\n{\n\tpobjectsSphere.erase(std::remove(pobjectsSphere.begin(), pobjectsSphere.end(),physicsObject), pobjectsSphere.end());\n}\n\nvoid PhysicsThread::registerPhysicsBox(PhysicsBox* physicsObject)\n{\n\tpobjectsBox.push_back(physicsObject);\n}\n\nvoid PhysicsThread::deregisterPhysicsBox(PhysicsBox* physicsObject)\n{\n\tpobjectsBox.erase(std::remove(pobjectsBox.begin(), pobjectsBox.end(),physicsObject), pobjectsBox.end());\n}\n\n<commit_msg>fixed Collision Shere vs Static Shere<commit_after>#include \"PhysicsThread.h\"\n#include \"PhysicsObject.h\"\n#include \"Collision.h\"\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <QDebug>\n\n\n\n\n\nPhysicsThread::PhysicsThread()\n{\n}\n\nPhysicsThread::PhysicsThread(int minx ,int miny ,int minz ,int maxx ,int maxy ,int maxz)\n{\n\n\tthis->minx = minx;\n\tthis->miny = miny;\n\tthis->minz = minz;\n\n\tthis->maxx = maxx;\n\tthis->maxy = maxy;\n\tthis->maxz = maxz;\n\n}\n\nPhysicsThread::~PhysicsThread()\n{\n\n}\n\nvoid PhysicsThread::run(){\n\tqDebug() << \"SUCCESSFULLY STARTED UP PHYSICS-SIMULATION\";\n\tforever{\n\t\tmutex.lock();\n\t\tqDebug() << \"RUNNING PHYSICS-SIMULATION\";\n\t\trunSimulation(1.0\/60.0);\n\t\tif(stop){\n\t\t\tbreak;\n\t\t}\n\t\tif(bPause){\n\t\t\tpauseManager.wait(&mutex);\n\t\t}\n\t\tmutex.unlock();\n\t}\n}\n\nvoid PhysicsThread::TogglePause()\n{\n\tbPause = !bPause;\n\tif(!bPause){\n\t\tpauseManager.wakeAll();\n\t}\n}\n\nvoid PhysicsThread::pause()\n{\n\tbPause = true;\n}\n\nvoid PhysicsThread::resume()\n{\n\tbPause = false;\n\tpauseManager.wakeAll();\n}\n\nvoid PhysicsThread::quit()\n{\n\tstop = true;\n\tQThread::quit();\n\tqDebug() << \"STOPPING PHYSICS-THREAD\";\n}\n\nvoid PhysicsThread::runSimulation(const double& delta){\n\n\t\/\/ Collision Border\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\n\t\tPhysicsSphere* op = pobjectsSphere.at(i);\n\t\tif(op->getIsMovable()){\n\t\t\t\/\/ is Sphere TODO\n\t\t\tif(true){\n\t\t\t\tif(op->getX()-(op->getSize()) < minx ){\n\t\t\t\t\tif(op->getVelocityX() < 0){\n\t\t\t\t\t\top->setVelocityX(-op->getVelocityX());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityX(op->getVelocityX());\n\t\t\t\t\t}\n\t\t\t\t}else if(op->getX()+(op->getSize()) > maxx) {\n\t\t\t\t\tif(op->getVelocityX() > 0){\n\t\t\t\t\t\top->setVelocityX(-op->getVelocityX());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityX(op->getVelocityX());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(op->getY()-(op->getSize()) < miny){\n\t\t\t\t\tif(op->getVelocityY() < 0){\n\t\t\t\t\t\top->setVelocityY(-op->getVelocityY() * op->getRemainingEnergy());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityY(op->getVelocityY());\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif(op->getY()+(op->getSize()) > maxy){\n\t\t\t\t\t\tif(op->getVelocityY() > 0){\n\t\t\t\t\t\t\top->setVelocityY(-op->getVelocityY());\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\top->setVelocityY(op->getVelocityY());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Gravity\n\t\t\t\t\top->setVelocityY(op->getVelocityY() + g*delta*op->getMass());\n\t\t\t\t}\n\n\t\t\t\tif(op->getZ()-(op->getSize()) < minz){\n\t\t\t\t\tif(op->getVelocityZ() < 0){\n\t\t\t\t\t\top->setVelocityZ(-op->getVelocityZ());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityZ(op->getVelocityZ());\n\t\t\t\t\t}\n\t\t\t\t}else if(op->getZ()+(op->getSize()) > maxz){\n\t\t\t\t\tif(op->getVelocityZ() > 0){\n\t\t\t\t\t\top->setVelocityZ(-op->getVelocityZ());\n\t\t\t\t\t}else{\n\t\t\t\t\t\top->setVelocityZ(op->getVelocityZ());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Collision Sphere on Sphere\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\t\tPhysicsSphere* op1 = pobjectsSphere.at(i);\n\t\tfor(int j = i ; j < pobjectsSphere.size() ; j++) {\n\t\t\tPhysicsSphere* op2 = pobjectsSphere.at(j);\n\n\t\t\t\/\/ bool Collision::SphereVersusSphere(const int& x1 , const int& y1 , const int& z1 , const int& size1 , const int& x2 , const int& y2 , const int& z2 , const int& size2)\n\t\t\t\/\/ Sphere on Sphere\n\t\t\t\/\/ SIZE\n\t\t\tif(i != j && Collision::SphereVersusSphere(op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getX() ,op2->getY() ,op2->getZ() ,op2->getSize())){\n\n\t\t\t\tdouble tempX (op1->getX() - op2->getX());\n\t\t\t\tdouble tempY (op1->getY() - op2->getY());\n\t\t\t\tdouble tempZ (op1->getZ() - op2->getZ());\n\n\t\t\t\tdouble norm = sqrt(tempX*tempX + tempY*tempY + tempZ*tempZ);\n\n\t\t\t\ttempX = tempX \/ norm;\n\t\t\t\ttempY = tempY \/ norm;\n\t\t\t\ttempZ = tempZ \/ norm;\n\n\t\t\t\tdouble a1 = (op1->getVelocityX() * tempX) + (op1->getVelocityY() * tempY) + (op1->getVelocityZ() * tempZ);\n\t\t\t\tdouble a2 = (op2->getVelocityX() * tempX) + (op2->getVelocityY() * tempY) + (op2->getVelocityZ() * tempZ);\n\n\t\t\t\t\/\/ double optimizedP = (2.0D * (a1 - a2)) \/ (e1.getWhight() + e2.getWhight());\n\n\t\t\t\tdouble optimizedP = (2.0 * (a1 - a2)) \/ (op1->getMass() + op2->getMass());\n\n\t\t\t\t\/\/ fix\n\t\t\t\toptimizedP = std::abs(optimizedP);\n\n\t\t\t\tqDebug() << optimizedP;\n\n\t\t\t\t\/\/ 0.9 Verlusst\n\t\t\t\tif(op1->getIsMovable()){\n\t\t\t\t\top1->setVelocityX( op1->getVelocityX() + (optimizedP * op2->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top1->setVelocityY( op1->getVelocityY() + (optimizedP * op2->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top1->setVelocityZ( op1->getVelocityZ() + (optimizedP * op2->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t}\n\n\t\t\t\tif(op2->getIsMovable()){\n\t\t\t\t\top2->setVelocityX( op2->getVelocityX() - (optimizedP * op1->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top2->setVelocityY( op2->getVelocityY() - (optimizedP * op1->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t\top2->setVelocityZ( op2->getVelocityZ() - (optimizedP * op1->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO\n\t\t\t\tqDebug() << op1->getPosition() << \"BEFORE\";\n if(!op1->getIsMovable() && op2->getIsMovable){\n op2->setX(op2->getX() - op1->getVelocityX() * delta);\n op2->setY(op2->getY() - op1->getVelocityY() * delta);\n op2->setZ(op2->getZ() - op1->getVelocityZ() * delta);\n\n op1->setVelocityX(0.0);\n op1->setVelocityY(0.0);\n op1->setVelocityZ(0.0);\n\n }else if(op1->getIsMovable() && !op2->getIsMovable){\n op1->setX(op1->getX() - op2->getVelocityX() * delta);\n op1->setY(op1->getY() - op2->getVelocityY() * delta);\n op1->setZ(op1->getZ() - op2->getVelocityZ() * delta);\n\n op2->setVelocityX(0.0);\n op2->setVelocityY(0.0);\n op2->setVelocityZ(0.0);\n }\n\n\n\t\t\t\top1->setX(op1->getX() + op1->getVelocityX() * delta);\n\t\t\t\top1->setY(op1->getY() + op1->getVelocityY() * delta);\n\t\t\t\top1->setZ(op1->getZ() + op1->getVelocityZ() * delta);\n\n\t\t\t\top2->setX(op2->getX() + op2->getVelocityX() * delta);\n\t\t\t\top2->setY(op2->getY() + op2->getVelocityY() * delta);\n\t\t\t\top2->setZ(op2->getZ() + op2->getVelocityZ() * delta);\n\t\t\t\tqDebug() << op1->getPosition() << \"AFTER\";\n\t\t\t}\n\t\t}\n\t}\n\n\/\/\t\/\/ Collision Shere on Box\n\/\/\t\/\/ bool Collision::SphereVersusBox\n\/\/\t\/\/(const int& sphereX ,const int& sphereY ,const int& sphereZ ,const int& sphereSize\n\/\/\t\/\/ ,const int& boxMinX ,const int& boxMinY ,const int& boxMinZ ,const int& boxMaxX ,const int& boxMaxY ,const int& boxMaxZ)\n\n\n for(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n PhysicsSphere* op1 = pobjectsSphere.at(i);\n for(int j = 0 ; j < pobjectsBox.size() ; j++) {\n PhysicsBox* op2 = pobjectsBox.at(j);\n\n\n\n if(Collision::SphereVersusBox( op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getMinX()+op2->getX() ,op2->getMinY()+op2->getY() ,op2->getMinZ()+op2->getZ() ,op2->getMaxX()+op2->getX() ,op2->getMaxY()+op2->getY() ,op2->getMaxZ()+op2->getZ())){\n\n qDebug() << \"Test\";\n\n if((op1->getX()+op1->getSize()) > op2->getMinX() && op1->getX() < op2->getMinX()+op2->getX()){\n\n if(op1->getVelocityX() > 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }\n if((op1->getX()-op1->getSize()) < op2->getMaxX() && op1->getX() > op2->getMaxX()+op2->getX()){\n if(op1->getVelocityX() < 0){\n op1->setVelocityX(-op1->getVelocityX());\n }\n }\n\n if((op1->getY()+op1->getSize()) > op2->getMinY() && op1->getY() < op2->getMinY()+op2->getY()){\n if(op1->getVelocityY() > 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }\n if((op1->getY()-op1->getSize()) < op2->getMaxY() && op1->getY() > op2->getMaxY()+op2->getY()){\n\n if(op1->getVelocityY() < 0){\n op1->setVelocityY(-op1->getVelocityY());\n }\n }\n\n if((op1->getZ()+op1->getSize()) > op2->getMinZ() && op1->getZ() < op2->getMinZ()+op2->getZ()){\n if(op1->getVelocityZ() > 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }\n if((op1->getZ()-op1->getSize()) < op2->getMaxZ() && op1->getZ() > op2->getMaxZ()+op2->getZ()){\n if(op1->getVelocityZ() < 0){\n op1->setVelocityZ(-op1->getVelocityZ());\n }\n }\n }\n }\n }\n\n\t\/\/ Move\n\tfor(int i = 0 ; i < pobjectsSphere.size() ; i++) {\n\t\tPhysicsSphere* op = pobjectsSphere.at(i);\n\t\top->setX(op->getX() + op->getVelocityX()*delta);\n\t\top->setY(op->getY() + op->getVelocityY()*delta);\n\t\top->setZ(op->getZ() + op->getVelocityZ()*delta);\n\t\t\/\/qDebug() << op->getVelocity();\n\n\t}\n\tthis->msleep(pauseTickTime);\n}\n\nint PhysicsThread::getMiny() const\n{\n\treturn miny;\n}\n\nvoid PhysicsThread::setMiny(const int value)\n{\n\tminy = value;\n}\n\nint PhysicsThread::getMinz() const\n{\n\treturn minz;\n}\n\nvoid PhysicsThread::setMinz(const int value)\n{\n\tminz = value;\n}\n\nint PhysicsThread::getMaxx() const\n{\n\treturn maxx;\n}\n\nvoid PhysicsThread::setMaxx(const int value)\n{\n\tmaxx = value;\n}\n\nint PhysicsThread::getMaxy() const\n{\n\treturn maxy;\n}\n\nvoid PhysicsThread::setMaxy(const int value)\n{\n\tmaxy = value;\n}\n\nint PhysicsThread::getMaxz() const\n{\n\treturn maxz;\n}\n\nvoid PhysicsThread::setMaxz(const int value)\n{\n\tmaxz = value;\n}\n\nint PhysicsThread::getMinx() const\n{\n\treturn minx;\n}\n\nvoid PhysicsThread::setMinx(const int value)\n{\n\tminx = value;\n}\n\nvoid PhysicsThread::registerPhysicsSphere(PhysicsSphere* physicsObject)\n{\n\tpobjectsSphere.push_back(physicsObject);\n}\n\nvoid PhysicsThread::deregisterPhysicsSphere(PhysicsSphere* physicsObject)\n{\n\tpobjectsSphere.erase(std::remove(pobjectsSphere.begin(), pobjectsSphere.end(),physicsObject), pobjectsSphere.end());\n}\n\nvoid PhysicsThread::registerPhysicsBox(PhysicsBox* physicsObject)\n{\n\tpobjectsBox.push_back(physicsObject);\n}\n\nvoid PhysicsThread::deregisterPhysicsBox(PhysicsBox* physicsObject)\n{\n\tpobjectsBox.erase(std::remove(pobjectsBox.begin(), pobjectsBox.end(),physicsObject), pobjectsBox.end());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#include <Eigen\/CXX11\/Tensor>\n\nusing Eigen::Tensor;\nusing Eigen::TensorMap;\n\nstatic void test_assign()\n{\n std::string data1[6];\n TensorMap<Tensor<std::string, 2>> mat1(data1, 2, 3);\n std::string data2[6];\n const TensorMap<Tensor<const std::string, 2>> mat2(data2, 2, 3);\n\n for (int i = 0; i < 6; ++i) {\n std::ostringstream s1;\n s1 << \"abc\" << i*3;\n data1[i] = s1.str();\n std::ostringstream s2;\n s2 << \"def\" << i*5;\n data2[i] = s2.str();\n }\n\n Tensor<std::string, 2> rslt1;\n rslt1 = mat1;\n Tensor<std::string, 2> rslt2;\n rslt2 = mat2;\n\n Tensor<std::string, 2> rslt3 = mat1;\n Tensor<std::string, 2> rslt4 = mat2;\n\n Tensor<std::string, 2> rslt5(mat1);\n Tensor<std::string, 2> rslt6(mat2);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(rslt1(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt2(i,j), data2[i+2*j]);\n VERIFY_IS_EQUAL(rslt3(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt4(i,j), data2[i+2*j]);\n VERIFY_IS_EQUAL(rslt5(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt6(i,j), data2[i+2*j]);\n }\n }\n}\n\n\nstatic void test_concat()\n{\n Tensor<std::string, 2> t1(2, 3);\n Tensor<std::string, 2> t2(2, 3);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n std::ostringstream s1;\n s1 << \"abc\" << i + j*2;\n t1(i, j) = s1.str();\n std::ostringstream s2;\n s2 << \"def\" << i*5 + j*32;\n t2(i, j) = s2.str();\n }\n }\n\n Tensor<std::string, 2> result = t1.concatenate(t2, 1);\n VERIFY_IS_EQUAL(result.dimension(0), 2);\n VERIFY_IS_EQUAL(result.dimension(1), 6);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(result(i, j), t1(i, j));\n VERIFY_IS_EQUAL(result(i, j+3), t2(i, j));\n }\n }\n}\n\n\nstatic void test_slices()\n{\n Tensor<std::string, 2> data(2, 6);\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n std::ostringstream s1;\n s1 << \"abc\" << i + j*2;\n data(i, j) = s1.str();\n }\n }\n\n const Eigen::DSizes<ptrdiff_t, 2> half_size{{2, 3}};\n const Eigen::DSizes<ptrdiff_t, 2> first_half{{0, 0}};\n const Eigen::DSizes<ptrdiff_t, 2> second_half{{0, 3}};\n\n Tensor<std::string, 2> t1 = data.slice(first_half, half_size);\n Tensor<std::string, 2> t2 = data.slice(second_half, half_size);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(data(i, j), t1(i, j));\n VERIFY_IS_EQUAL(data(i, j+3), t2(i, j));\n }\n }\n}\n\n\nstatic void test_additions()\n{\n Tensor<std::string, 1> data1(3);\n Tensor<std::string, 1> data2(3);\n for (int i = 0; i < 3; ++i) {\n data1(i) = \"abc\";\n std::ostringstream s1;\n s1 << i;\n data2(i) = s1.str();\n }\n\n Tensor<std::string, 1> sum = data1 + data2;\n for (int i = 0; i < 3; ++i) {\n std::ostringstream concat;\n concat << \"abc\" << i;\n std::string expected = concat.str();\n VERIFY_IS_EQUAL(sum(i), expected);\n }\n}\n\n\nstatic void test_initialization()\n{\n Tensor<std::string, 2> a(2, 3);\n a.setConstant(std::string(\"foo\"));\n for (int i = 0; i < 2*3; ++i) {\n VERIFY_IS_EQUAL(a(i), std::string(\"foo\"));\n }\n}\n\n\nvoid test_cxx11_tensor_of_strings()\n{\n \/\/ Beware: none of this is likely to ever work on a GPU.\n CALL_SUBTEST(test_assign());\n CALL_SUBTEST(test_concat());\n CALL_SUBTEST(test_slices());\n CALL_SUBTEST(test_additions());\n CALL_SUBTEST(test_initialization());\n}\n<commit_msg>Fixed compilation warnings<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#include <Eigen\/CXX11\/Tensor>\n\nusing Eigen::Tensor;\nusing Eigen::TensorMap;\n\nstatic void test_assign()\n{\n std::string data1[6];\n TensorMap<Tensor<std::string, 2>> mat1(data1, 2, 3);\n std::string data2[6];\n const TensorMap<Tensor<const std::string, 2>> mat2(data2, 2, 3);\n\n for (int i = 0; i < 6; ++i) {\n std::ostringstream s1;\n s1 << \"abc\" << i*3;\n data1[i] = s1.str();\n std::ostringstream s2;\n s2 << \"def\" << i*5;\n data2[i] = s2.str();\n }\n\n Tensor<std::string, 2> rslt1;\n rslt1 = mat1;\n Tensor<std::string, 2> rslt2;\n rslt2 = mat2;\n\n Tensor<std::string, 2> rslt3 = mat1;\n Tensor<std::string, 2> rslt4 = mat2;\n\n Tensor<std::string, 2> rslt5(mat1);\n Tensor<std::string, 2> rslt6(mat2);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(rslt1(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt2(i,j), data2[i+2*j]);\n VERIFY_IS_EQUAL(rslt3(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt4(i,j), data2[i+2*j]);\n VERIFY_IS_EQUAL(rslt5(i,j), data1[i+2*j]);\n VERIFY_IS_EQUAL(rslt6(i,j), data2[i+2*j]);\n }\n }\n}\n\n\nstatic void test_concat()\n{\n Tensor<std::string, 2> t1(2, 3);\n Tensor<std::string, 2> t2(2, 3);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n std::ostringstream s1;\n s1 << \"abc\" << i + j*2;\n t1(i, j) = s1.str();\n std::ostringstream s2;\n s2 << \"def\" << i*5 + j*32;\n t2(i, j) = s2.str();\n }\n }\n\n Tensor<std::string, 2> result = t1.concatenate(t2, 1);\n VERIFY_IS_EQUAL(result.dimension(0), 2);\n VERIFY_IS_EQUAL(result.dimension(1), 6);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(result(i, j), t1(i, j));\n VERIFY_IS_EQUAL(result(i, j+3), t2(i, j));\n }\n }\n}\n\n\nstatic void test_slices()\n{\n Tensor<std::string, 2> data(2, 6);\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n std::ostringstream s1;\n s1 << \"abc\" << i + j*2;\n data(i, j) = s1.str();\n }\n }\n\n const Eigen::DSizes<ptrdiff_t, 2> half_size(2, 3);\n const Eigen::DSizes<ptrdiff_t, 2> first_half(0, 0);\n const Eigen::DSizes<ptrdiff_t, 2> second_half(0, 3);\n\n Tensor<std::string, 2> t1 = data.slice(first_half, half_size);\n Tensor<std::string, 2> t2 = data.slice(second_half, half_size);\n\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 3; ++j) {\n VERIFY_IS_EQUAL(data(i, j), t1(i, j));\n VERIFY_IS_EQUAL(data(i, j+3), t2(i, j));\n }\n }\n}\n\n\nstatic void test_additions()\n{\n Tensor<std::string, 1> data1(3);\n Tensor<std::string, 1> data2(3);\n for (int i = 0; i < 3; ++i) {\n data1(i) = \"abc\";\n std::ostringstream s1;\n s1 << i;\n data2(i) = s1.str();\n }\n\n Tensor<std::string, 1> sum = data1 + data2;\n for (int i = 0; i < 3; ++i) {\n std::ostringstream concat;\n concat << \"abc\" << i;\n std::string expected = concat.str();\n VERIFY_IS_EQUAL(sum(i), expected);\n }\n}\n\n\nstatic void test_initialization()\n{\n Tensor<std::string, 2> a(2, 3);\n a.setConstant(std::string(\"foo\"));\n for (int i = 0; i < 2*3; ++i) {\n VERIFY_IS_EQUAL(a(i), std::string(\"foo\"));\n }\n}\n\n\nvoid test_cxx11_tensor_of_strings()\n{\n \/\/ Beware: none of this is likely to ever work on a GPU.\n CALL_SUBTEST(test_assign());\n CALL_SUBTEST(test_concat());\n CALL_SUBTEST(test_slices());\n CALL_SUBTEST(test_additions());\n CALL_SUBTEST(test_initialization());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/gui:$Name: $:$Id: TGuiBuilder.cxx,v 1.7 2006\/05\/26 09:16:29 brun Exp $\n\/\/ Author: Valeriy Onuchin 12\/08\/04\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TGuiBuilder\n\/\/\n\/\/\n\/\/ ************************************************\n\/\/ ROOT GUI Builder principles\n\/\/ ************************************************\n\/\/\n\/\/ With the GUI builder, we try to make the next step from WYSIWYG\n\/\/ to embedded editing concept - WYSIWYE (\"what you see is what you edit\").\n\/\/ The ROOT GUI Builder allows modifying real GUI objects.\n\/\/ For example, one can edit the existing GUI application $ROOTSYS\/tutorials\/guitest.C.\n\/\/ GUI components can be added to a design area from a widget palette,\n\/\/ or can be borrowed from another application.\n\/\/ One can drag and and drop TCanvas's menu bar into the application.\n\/\/ GUI objects can be resized and dragged, copied and pasted.\n\/\/ ROOT GUI Builder allows changing the layout, snap to grid, change object's\n\/\/ layout order via the GUI Builder toolbar, or by options in the right-click\n\/\/ context menus.\n\/\/ A final design can be immediatly tested and used, or saved as a C++ macro.\n\/\/ For example, it's possible to rearrange buttons in control bar,\n\/\/ add separators etc. and continue to use a new fancy control bar in the\n\/\/ application.\n\/\/\n\/\/ ************************************************\n\/\/\n\/\/ The following is a short description of the GUI Builder actions and key shortcuts:\n\/\/\n\/\/ o Press Ctrl-Double-Click to start\/stop edit mode\n\/\/ o Press Double-Click to activate quick edit action (defined in root.mimes)\n\/\/\n\/\/ Selection, grabbing, dropping\n\/\/ ************************************************\n\/\/ It is possible to select, drag any frame and drop it to any frame\n\/\/\n\/\/ o Click left mouse button or Ctrl-Click to select an object to edit.\n\/\/ o Press right mouse button to activate context menu\n\/\/ o Mutiple selection (grabbing):\n\/\/ - draw lasso and press Return key\n\/\/ - press Shift key and draw lasso\n\/\/ o Dropping:\n\/\/ - select frame and press Ctrl-Return key\n\/\/ o Changing layout order:\n\/\/ - select frame and use arrow keys to change layout order\n\/\/ o Alignment:\n\/\/ - draw lasso and press arrow keys (or Shift-Arrow key) to align frames\n\/\/\n\/\/ Key shortcuts\n\/\/ ************************************************\n\/\/ o Return - grab selected frames\n\/\/ o Ctrl-Return - drop frames\n\/\/ o Del - delete selected frame\n\/\/ o Shift-Del - crop action\n\/\/ o Ctrl-X - cut action\n\/\/ o Ctrl-C - copy action\n\/\/ o Ctrl-V - paste action\n\/\/ o Ctrl-R - replace action\n\/\/ o Ctrl-L - compact layout\n\/\/ o Ctrl-B - break layout\n\/\/ o Ctrl-H - switch horizontal-vertical layout\n\/\/ o Ctrl-G - switch on\/off grid\n\/\/ o Ctrl-S - save action\n\/\/ o Ctrl-O - open and execute a ROOT macro file. GUI components created\n\/\/ after macro execution will be emebedded to currently edited\n\/\/ design area.\n\/\/ o Ctrl-N - create new main frame\n\/\/\n\/\/Begin_Html\n\/*\n<img src=\"gif\/RootGuiBuilder.gif\">\n*\/\n\/\/End_Html\n\n\n#include \"TGuiBuilder.h\"\n#include \"TVirtualDragManager.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n\nClassImp(TGuiBuilder)\nClassImp(TGuiBldAction)\n\nTGuiBuilder *gGuiBuilder = 0;\nstatic TPluginHandler *gHandler = 0;\n\n\/\/______________________________________________________________________________\nTGuiBldAction::TGuiBldAction(const char *name, const char *title,\n Int_t type, TGLayoutHints *hints) :\n TNamed(name, title), fType(type), fHints(hints)\n{\n \/\/ constructor\n\n fPicture = 0;\n fPic = 0; \n fAct = \"\";\n}\n\n\/\/______________________________________________________________________________\nTGuiBldAction::~TGuiBldAction()\n{\n \/\/ destructor\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder::TGuiBuilder()\n{\n \/\/ constructor\n\n \/\/ load plugin\n if (!gGuiBuilder) {\n gHandler = gROOT->GetPluginManager()->FindHandler(\"TGuiBuilder\");\n\n if (!gHandler || (gHandler->LoadPlugin() == -1)) return;\n\n gGuiBuilder = this;\n gHandler->ExecPlugin(0);\n } else {\n fAction = 0;\n gGuiBuilder->Show();\n }\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder::~TGuiBuilder()\n{\n \/\/ destructor\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder *TGuiBuilder::Instance()\n{\n \/\/ return an instance of TGuiBuilder object\n\n return (gGuiBuilder? gGuiBuilder : new TGuiBuilder());\n}\n<commit_msg>Change comments according to the new $ROOTSYS\/tutorials structure.<commit_after>\/\/ @(#)root\/gui:$Name: $:$Id: TGuiBuilder.cxx,v 1.8 2006\/05\/28 20:08:00 brun Exp $\n\/\/ Author: Valeriy Onuchin 12\/08\/04\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TGuiBuilder\n\/\/\n\/\/\n\/\/ ************************************************\n\/\/ ROOT GUI Builder principles\n\/\/ ************************************************\n\/\/\n\/\/ With the GUI builder, we try to make the next step from WYSIWYG\n\/\/ to embedded editing concept - WYSIWYE (\"what you see is what you edit\").\n\/\/ The ROOT GUI Builder allows modifying real GUI objects.\n\/\/ For example, one can edit the existing GUI application created by\n\/\/ $ROOTSYS\/tutorials\/gui\/guitest.C.\n\/\/ GUI components can be added to a design area from a widget palette,\n\/\/ or can be borrowed from another application.\n\/\/ One can drag and and drop TCanvas's menu bar into the application.\n\/\/ GUI objects can be resized and dragged, copied and pasted.\n\/\/ ROOT GUI Builder allows changing the layout, snap to grid, change object's\n\/\/ layout order via the GUI Builder toolbar, or by options in the right-click\n\/\/ context menus.\n\/\/ A final design can be immediatly tested and used, or saved as a C++ macro.\n\/\/ For example, it's possible to rearrange buttons in control bar,\n\/\/ add separators etc. and continue to use a new fancy control bar in the\n\/\/ application.\n\/\/\n\/\/ ************************************************\n\/\/\n\/\/ The following is a short description of the GUI Builder actions and key shortcuts:\n\/\/\n\/\/ o Press Ctrl-Double-Click to start\/stop edit mode\n\/\/ o Press Double-Click to activate quick edit action (defined in root.mimes)\n\/\/\n\/\/ Selection, grabbing, dropping\n\/\/ ************************************************\n\/\/ It is possible to select, drag any frame and drop it to any frame\n\/\/\n\/\/ o Click left mouse button or Ctrl-Click to select an object to edit.\n\/\/ o Press right mouse button to activate context menu\n\/\/ o Mutiple selection (grabbing):\n\/\/ - draw lasso and press Return key\n\/\/ - press Shift key and draw lasso\n\/\/ o Dropping:\n\/\/ - select frame and press Ctrl-Return key\n\/\/ o Changing layout order:\n\/\/ - select frame and use arrow keys to change layout order\n\/\/ o Alignment:\n\/\/ - draw lasso and press arrow keys (or Shift-Arrow key) to align frames\n\/\/\n\/\/ Key shortcuts\n\/\/ ************************************************\n\/\/ o Return - grab selected frames\n\/\/ o Ctrl-Return - drop frames\n\/\/ o Del - delete selected frame\n\/\/ o Shift-Del - crop action\n\/\/ o Ctrl-X - cut action\n\/\/ o Ctrl-C - copy action\n\/\/ o Ctrl-V - paste action\n\/\/ o Ctrl-R - replace action\n\/\/ o Ctrl-L - compact layout\n\/\/ o Ctrl-B - break layout\n\/\/ o Ctrl-H - switch horizontal-vertical layout\n\/\/ o Ctrl-G - switch on\/off grid\n\/\/ o Ctrl-S - save action\n\/\/ o Ctrl-O - open and execute a ROOT macro file. GUI components created\n\/\/ after macro execution will be emebedded to currently edited\n\/\/ design area.\n\/\/ o Ctrl-N - create new main frame\n\/\/\n\/\/Begin_Html\n\/*\n<img src=\"gif\/RootGuiBuilder.gif\">\n*\/\n\/\/End_Html\n\n\n#include \"TGuiBuilder.h\"\n#include \"TVirtualDragManager.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n\nClassImp(TGuiBuilder)\nClassImp(TGuiBldAction)\n\nTGuiBuilder *gGuiBuilder = 0;\nstatic TPluginHandler *gHandler = 0;\n\n\/\/______________________________________________________________________________\nTGuiBldAction::TGuiBldAction(const char *name, const char *title,\n Int_t type, TGLayoutHints *hints) :\n TNamed(name, title), fType(type), fHints(hints)\n{\n \/\/ constructor\n\n fPicture = 0;\n fPic = 0; \n fAct = \"\";\n}\n\n\/\/______________________________________________________________________________\nTGuiBldAction::~TGuiBldAction()\n{\n \/\/ destructor\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder::TGuiBuilder()\n{\n \/\/ constructor\n\n \/\/ load plugin\n if (!gGuiBuilder) {\n gHandler = gROOT->GetPluginManager()->FindHandler(\"TGuiBuilder\");\n\n if (!gHandler || (gHandler->LoadPlugin() == -1)) return;\n\n gGuiBuilder = this;\n gHandler->ExecPlugin(0);\n } else {\n fAction = 0;\n gGuiBuilder->Show();\n }\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder::~TGuiBuilder()\n{\n \/\/ destructor\n}\n\n\/\/______________________________________________________________________________\nTGuiBuilder *TGuiBuilder::Instance()\n{\n \/\/ return an instance of TGuiBuilder object\n\n return (gGuiBuilder? gGuiBuilder : new TGuiBuilder());\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Compositor.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names\n** of its contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"waylandeglintegration.h\"\n\n#include <QtCompositor\/private\/qwlcompositor_p.h>\n#include <QtCompositor\/private\/qwlsurface_p.h>\n#include <qpa\/qplatformnativeinterface.h>\n#include <QtGui\/QGuiApplication>\n#include <QtGui\/QOpenGLContext>\n#include <qpa\/qplatformscreen.h>\n#include <QtGui\/QWindow>\n#include <QtCore\/QPointer>\n\n#include <QDebug>\n\n#include <EGL\/egl.h>\n#include <EGL\/eglext.h>\n\n#include <GLES2\/gl2.h>\n#include <GLES2\/gl2ext.h>\n\n#ifndef EGL_WL_bind_wayland_display\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYWAYLANDBUFFERWL) (EGLDisplay dpy, struct wl_buffer *buffer, EGLint attribute, EGLint *value);\n#endif\n\n#ifndef EGL_KHR_image\ntypedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);\n#endif\n\n#ifndef GL_OES_EGL_image\ntypedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);\ntypedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);\n#endif\n\nQT_BEGIN_NAMESPACE\n\nclass WaylandEglIntegrationPrivate\n{\npublic:\n WaylandEglIntegrationPrivate()\n : egl_display(EGL_NO_DISPLAY)\n , valid(false)\n , display_bound(false)\n , flipperConnected(false)\n , egl_bind_wayland_display(0)\n , egl_unbind_wayland_display(0)\n , egl_query_wayland_buffer(0)\n , egl_create_image(0)\n , egl_destroy_image(0)\n , gl_egl_image_target_texture_2d(0)\n { }\n EGLDisplay egl_display;\n bool valid;\n bool display_bound;\n bool flipperConnected;\n PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;\n PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;\n PFNEGLQUERYWAYLANDBUFFERWL egl_query_wayland_buffer;\n\n PFNEGLCREATEIMAGEKHRPROC egl_create_image;\n PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;\n\n PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;\n};\n\nWaylandEglIntegration::WaylandEglIntegration()\n : QWaylandGraphicsHardwareIntegration()\n , d_ptr(new WaylandEglIntegrationPrivate)\n{\n}\n\nvoid WaylandEglIntegration::initializeHardware(QtWayland::Display *waylandDisplay)\n{\n Q_D(WaylandEglIntegration);\n\n const bool ignoreBindDisplay = !qgetenv(\"QT_WAYLAND_IGNORE_BIND_DISPLAY\").isEmpty();\n\n QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();\n if (!nativeInterface) {\n qWarning(\"Failed to initialize egl display. No native platform interface available.\\n\");\n return;\n }\n\n d->egl_display = nativeInterface->nativeResourceForWindow(\"EglDisplay\", m_compositor->window());\n if (!d->egl_display) {\n qWarning(\"Failed to initialize egl display. Could not get EglDisplay for window.\\n\");\n return;\n }\n\n const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);\n if ((!extensionString || !strstr(extensionString, \"EGL_WL_bind_wayland_display\")) && !ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. There is no EGL_WL_bind_wayland_display extension.\\n\");\n return;\n }\n\n d->egl_bind_wayland_display = reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress(\"eglBindWaylandDisplayWL\"));\n d->egl_unbind_wayland_display = reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress(\"eglUnbindWaylandDisplayWL\"));\n if (!d->egl_bind_wayland_display || !d->egl_unbind_wayland_display && !ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. Could not find eglBindWaylandDisplayWL and eglUnbindWaylandDisplayWL.\\n\");\n return;\n }\n\n d->egl_query_wayland_buffer = reinterpret_cast<PFNEGLQUERYWAYLANDBUFFERWL>(eglGetProcAddress(\"eglQueryWaylandBufferWL\"));\n if (!d->egl_query_wayland_buffer) {\n qWarning(\"Failed to initialize egl display. Could not find eglQueryWaylandBufferWL.\\n\");\n return;\n }\n\n d->egl_create_image = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress(\"eglCreateImageKHR\"));\n d->egl_destroy_image = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress(\"eglDestroyImageKHR\"));\n if (!d->egl_create_image || !d->egl_destroy_image) {\n qWarning(\"Failed to initialize egl display. Could not find eglCreateImageKHR and eglDestroyImageKHR.\\n\");\n return;\n }\n\n d->gl_egl_image_target_texture_2d = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress(\"glEGLImageTargetTexture2DOES\"));\n if (!d->gl_egl_image_target_texture_2d) {\n qWarning(\"Failed to initialize egl display. Could not find glEGLImageTargetTexture2DOES.\\n\");\n return;\n }\n\n if (d->egl_bind_wayland_display && d->egl_unbind_wayland_display) {\n d->display_bound = d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle());\n if (!d->display_bound || ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. Could not bind Wayland display.\\n\");\n return;\n }\n }\n\n d->valid = true;\n\n qWarning(\"EGL Wayland extension successfully initialized.%s\\n\", !d->display_bound ? \" eglBindWaylandDisplayWL ignored\" : \"\");\n}\n\nGLuint WaylandEglIntegration::createTextureFromBuffer(struct ::wl_resource *buffer, QOpenGLContext *)\n{\n Q_D(WaylandEglIntegration);\n if (!d->valid) {\n qWarning(\"createTextureFromBuffer() failed\\n\");\n return 0;\n }\n\n EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,\n EGL_WAYLAND_BUFFER_WL,\n buffer, NULL);\n\n GLuint textureId;\n glGenTextures(1,&textureId);\n\n glBindTexture(GL_TEXTURE_2D, textureId);\n\n d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\n d->egl_destroy_image(d->egl_display, image);\n\n return textureId;\n}\n\nbool WaylandEglIntegration::isYInverted(struct ::wl_resource *buffer) const\n{\n Q_D(const WaylandEglIntegration);\n\n#if defined(EGL_WAYLAND_Y_INVERTED_WL)\n EGLint isYInverted;\n EGLBoolean ret;\n ret = d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WAYLAND_Y_INVERTED_WL, &isYInverted);\n\n \/\/ Yes, this looks strange, but the specification says that EGL_FALSE return\n \/\/ value (not supported) should be treated the same as EGL_TRUE return value\n \/\/ and EGL_TRUE in value.\n if (ret == EGL_FALSE || isYInverted == EGL_TRUE)\n return true;\n#endif\n\n return QWaylandGraphicsHardwareIntegration::isYInverted(buffer);\n}\n\n\nbool WaylandEglIntegration::setDirectRenderSurface(QWaylandSurface *surface)\n{\n Q_D(WaylandEglIntegration);\n\n QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());\n QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;\n if (flipper && !d->flipperConnected) {\n QObject::connect(flipper, SIGNAL(bufferReleased(QPlatformScreenBuffer*)), m_compositor->handle(), SLOT(releaseBuffer(QPlatformScreenBuffer*)));\n d->flipperConnected = true;\n }\n Q_UNUSED(surface);\n return flipper;\n}\n\nvoid *WaylandEglIntegration::lockNativeBuffer(struct ::wl_resource *buffer, QOpenGLContext *) const\n{\n Q_D(const WaylandEglIntegration);\n\n EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,\n EGL_WAYLAND_BUFFER_WL,\n buffer, NULL);\n return image;\n}\n\nvoid WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const\n{\n Q_D(const WaylandEglIntegration);\n EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);\n\n d->egl_destroy_image(d->egl_display, image);\n}\n\nQSize WaylandEglIntegration::bufferSize(struct ::wl_resource *buffer) const\n{\n Q_D(const WaylandEglIntegration);\n\n int width, height;\n d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WIDTH, &width);\n d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_HEIGHT, &height);\n\n return QSize(width, height);\n}\n\nQT_END_NAMESPACE\n<commit_msg>Fix initialization without eglBindWaylandDisplayWL<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Compositor.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names\n** of its contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"waylandeglintegration.h\"\n\n#include <QtCompositor\/private\/qwlcompositor_p.h>\n#include <QtCompositor\/private\/qwlsurface_p.h>\n#include <qpa\/qplatformnativeinterface.h>\n#include <QtGui\/QGuiApplication>\n#include <QtGui\/QOpenGLContext>\n#include <qpa\/qplatformscreen.h>\n#include <QtGui\/QWindow>\n#include <QtCore\/QPointer>\n\n#include <QDebug>\n\n#include <EGL\/egl.h>\n#include <EGL\/eglext.h>\n\n#include <GLES2\/gl2.h>\n#include <GLES2\/gl2ext.h>\n\n#ifndef EGL_WL_bind_wayland_display\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYWAYLANDBUFFERWL) (EGLDisplay dpy, struct wl_buffer *buffer, EGLint attribute, EGLint *value);\n#endif\n\n#ifndef EGL_KHR_image\ntypedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);\ntypedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);\n#endif\n\n#ifndef GL_OES_EGL_image\ntypedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);\ntypedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);\n#endif\n\nQT_BEGIN_NAMESPACE\n\nclass WaylandEglIntegrationPrivate\n{\npublic:\n WaylandEglIntegrationPrivate()\n : egl_display(EGL_NO_DISPLAY)\n , valid(false)\n , display_bound(false)\n , flipperConnected(false)\n , egl_bind_wayland_display(0)\n , egl_unbind_wayland_display(0)\n , egl_query_wayland_buffer(0)\n , egl_create_image(0)\n , egl_destroy_image(0)\n , gl_egl_image_target_texture_2d(0)\n { }\n EGLDisplay egl_display;\n bool valid;\n bool display_bound;\n bool flipperConnected;\n PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;\n PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;\n PFNEGLQUERYWAYLANDBUFFERWL egl_query_wayland_buffer;\n\n PFNEGLCREATEIMAGEKHRPROC egl_create_image;\n PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;\n\n PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;\n};\n\nWaylandEglIntegration::WaylandEglIntegration()\n : QWaylandGraphicsHardwareIntegration()\n , d_ptr(new WaylandEglIntegrationPrivate)\n{\n}\n\nvoid WaylandEglIntegration::initializeHardware(QtWayland::Display *waylandDisplay)\n{\n Q_D(WaylandEglIntegration);\n\n const bool ignoreBindDisplay = !qgetenv(\"QT_WAYLAND_IGNORE_BIND_DISPLAY\").isEmpty();\n\n QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();\n if (!nativeInterface) {\n qWarning(\"Failed to initialize egl display. No native platform interface available.\\n\");\n return;\n }\n\n d->egl_display = nativeInterface->nativeResourceForWindow(\"EglDisplay\", m_compositor->window());\n if (!d->egl_display) {\n qWarning(\"Failed to initialize egl display. Could not get EglDisplay for window.\\n\");\n return;\n }\n\n const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);\n if ((!extensionString || !strstr(extensionString, \"EGL_WL_bind_wayland_display\")) && !ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. There is no EGL_WL_bind_wayland_display extension.\\n\");\n return;\n }\n\n d->egl_bind_wayland_display = reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress(\"eglBindWaylandDisplayWL\"));\n d->egl_unbind_wayland_display = reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress(\"eglUnbindWaylandDisplayWL\"));\n if (!d->egl_bind_wayland_display || !d->egl_unbind_wayland_display && !ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. Could not find eglBindWaylandDisplayWL and eglUnbindWaylandDisplayWL.\\n\");\n return;\n }\n\n d->egl_query_wayland_buffer = reinterpret_cast<PFNEGLQUERYWAYLANDBUFFERWL>(eglGetProcAddress(\"eglQueryWaylandBufferWL\"));\n if (!d->egl_query_wayland_buffer) {\n qWarning(\"Failed to initialize egl display. Could not find eglQueryWaylandBufferWL.\\n\");\n return;\n }\n\n d->egl_create_image = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress(\"eglCreateImageKHR\"));\n d->egl_destroy_image = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress(\"eglDestroyImageKHR\"));\n if (!d->egl_create_image || !d->egl_destroy_image) {\n qWarning(\"Failed to initialize egl display. Could not find eglCreateImageKHR and eglDestroyImageKHR.\\n\");\n return;\n }\n\n d->gl_egl_image_target_texture_2d = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress(\"glEGLImageTargetTexture2DOES\"));\n if (!d->gl_egl_image_target_texture_2d) {\n qWarning(\"Failed to initialize egl display. Could not find glEGLImageTargetTexture2DOES.\\n\");\n return;\n }\n\n if (d->egl_bind_wayland_display && d->egl_unbind_wayland_display) {\n d->display_bound = d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle());\n if (!d->display_bound && !ignoreBindDisplay) {\n qWarning(\"Failed to initialize egl display. Could not bind Wayland display.\\n\");\n return;\n }\n }\n\n d->valid = true;\n\n qWarning(\"EGL Wayland extension successfully initialized.%s\\n\", !d->display_bound ? \" eglBindWaylandDisplayWL ignored\" : \"\");\n}\n\nGLuint WaylandEglIntegration::createTextureFromBuffer(struct ::wl_resource *buffer, QOpenGLContext *)\n{\n Q_D(WaylandEglIntegration);\n if (!d->valid) {\n qWarning(\"createTextureFromBuffer() failed\\n\");\n return 0;\n }\n\n EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,\n EGL_WAYLAND_BUFFER_WL,\n buffer, NULL);\n\n GLuint textureId;\n glGenTextures(1,&textureId);\n\n glBindTexture(GL_TEXTURE_2D, textureId);\n\n d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\n d->egl_destroy_image(d->egl_display, image);\n\n return textureId;\n}\n\nbool WaylandEglIntegration::isYInverted(struct ::wl_resource *buffer) const\n{\n Q_D(const WaylandEglIntegration);\n\n#if defined(EGL_WAYLAND_Y_INVERTED_WL)\n EGLint isYInverted;\n EGLBoolean ret;\n ret = d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WAYLAND_Y_INVERTED_WL, &isYInverted);\n\n \/\/ Yes, this looks strange, but the specification says that EGL_FALSE return\n \/\/ value (not supported) should be treated the same as EGL_TRUE return value\n \/\/ and EGL_TRUE in value.\n if (ret == EGL_FALSE || isYInverted == EGL_TRUE)\n return true;\n#endif\n\n return QWaylandGraphicsHardwareIntegration::isYInverted(buffer);\n}\n\n\nbool WaylandEglIntegration::setDirectRenderSurface(QWaylandSurface *surface)\n{\n Q_D(WaylandEglIntegration);\n\n QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());\n QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;\n if (flipper && !d->flipperConnected) {\n QObject::connect(flipper, SIGNAL(bufferReleased(QPlatformScreenBuffer*)), m_compositor->handle(), SLOT(releaseBuffer(QPlatformScreenBuffer*)));\n d->flipperConnected = true;\n }\n Q_UNUSED(surface);\n return flipper;\n}\n\nvoid *WaylandEglIntegration::lockNativeBuffer(struct ::wl_resource *buffer, QOpenGLContext *) const\n{\n Q_D(const WaylandEglIntegration);\n\n EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,\n EGL_WAYLAND_BUFFER_WL,\n buffer, NULL);\n return image;\n}\n\nvoid WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const\n{\n Q_D(const WaylandEglIntegration);\n EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);\n\n d->egl_destroy_image(d->egl_display, image);\n}\n\nQSize WaylandEglIntegration::bufferSize(struct ::wl_resource *buffer) const\n{\n Q_D(const WaylandEglIntegration);\n\n int width, height;\n d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WIDTH, &width);\n d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_HEIGHT, &height);\n\n return QSize(width, height);\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * HTTP server implementation.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"direct.hxx\"\n#include \"istream\/istream_oo.hxx\"\n\n#include <daemon\/log.h>\n\n#include <sys\/socket.h>\n#include <errno.h>\n#include <string.h>\n\nsize_t\nHttpServerConnection::OnData(const void *data, size_t length)\n{\n assert(socket.IsConnected() || request.request == nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n if (!socket.IsConnected())\n return 0;\n\n ssize_t nbytes = socket.Write(data, length);\n\n if (likely(nbytes >= 0)) {\n response.bytes_sent += nbytes;\n response.length += (off_t)nbytes;\n ScheduleWrite();\n return (size_t)nbytes;\n }\n\n if (gcc_likely(nbytes == WRITE_BLOCKING)) {\n response.want_write = true;\n return 0;\n }\n\n if (nbytes == WRITE_DESTROYED)\n return 0;\n\n ErrorErrno(\"write error on HTTP connection\");\n return 0;\n}\n\nssize_t\nHttpServerConnection::OnDirect(FdType type, int fd, size_t max_length)\n{\n assert(socket.IsConnected() || request.request == nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n if (!socket.IsConnected())\n return 0;\n\n ssize_t nbytes = socket.WriteFrom(fd, type, max_length);\n if (likely(nbytes > 0)) {\n response.bytes_sent += nbytes;\n response.length += (off_t)nbytes;\n ScheduleWrite();\n } else if (nbytes == WRITE_BLOCKING) {\n response.want_write = true;\n return ISTREAM_RESULT_BLOCKING;\n } else if (nbytes == WRITE_DESTROYED)\n return ISTREAM_RESULT_CLOSED;\n\n return nbytes;\n}\n\nvoid\nHttpServerConnection::OnEof()\n{\n assert(request.read_state != Request::START &&\n request.read_state != Request::HEADERS);\n assert(request.request != nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n response.istream.Clear();\n\n ResponseIstreamFinished();\n}\n\nvoid\nHttpServerConnection::OnError(GError *error)\n{\n assert(response.istream.IsDefined());\n\n response.istream.Clear();\n\n \/* we clear this async_ref here so http_server_request_close()\n won't think we havn't sent a response yet *\/\n request.async_ref.Clear();\n\n g_prefix_error(&error, \"error on HTTP response stream: \");\n Error(error);\n}\n\nvoid\nHttpServerConnection::SetResponseIstream(Istream &r)\n{\n response.istream.Set(r, *this, socket.GetDirectMask());\n}\n\nbool\nHttpServerConnection::ResponseIstreamFinished()\n{\n socket.UnscheduleWrite();\n\n Log();\n\n if (request.read_state == Request::BODY &&\n !request.expect_100_continue) {\n \/* We are still reading the request body, which we don't need\n anymore. To discard it, we simply close the connection by\n disabling keepalive; this seems cheaper than redirecting\n the rest of the body to \/dev\/null *\/\n keep_alive = false;\n request.read_state = Request::END;\n\n GError *error =\n g_error_new_literal(http_server_quark(), 0,\n \"request body discarded\");\n request_body_reader->DestroyError(error);\n if (!IsValid())\n return false;\n }\n\n pool_trash(request.request->pool);\n pool_unref(request.request->pool);\n request.request = nullptr;\n request.bytes_received = 0;\n response.bytes_sent = 0;\n\n request.read_state = Request::START;\n\n if (keep_alive) {\n \/* handle pipelined request (if any), or set up events for\n next request *\/\n\n socket.ScheduleReadNoTimeout(false);\n idle_timeout.Add(http_server_idle_timeout);\n\n return true;\n } else {\n \/* keepalive disabled and response is finished: we must close\n the connection *\/\n\n if (socket.IsDrained()) {\n Done();\n return false;\n } else {\n \/* there is still data in the filter's output buffer; wait for\n that to drain, which will trigger\n http_server_socket_drained() *\/\n assert(!response.pending_drained);\n\n response.pending_drained = true;\n\n return true;\n }\n }\n}\n<commit_msg>http_server: check for end of chunked request body again in ResponseIstreamFinished()<commit_after>\/*\n * HTTP server implementation.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"direct.hxx\"\n#include \"istream\/istream_oo.hxx\"\n\n#include <daemon\/log.h>\n\n#include <sys\/socket.h>\n#include <errno.h>\n#include <string.h>\n\nsize_t\nHttpServerConnection::OnData(const void *data, size_t length)\n{\n assert(socket.IsConnected() || request.request == nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n if (!socket.IsConnected())\n return 0;\n\n ssize_t nbytes = socket.Write(data, length);\n\n if (likely(nbytes >= 0)) {\n response.bytes_sent += nbytes;\n response.length += (off_t)nbytes;\n ScheduleWrite();\n return (size_t)nbytes;\n }\n\n if (gcc_likely(nbytes == WRITE_BLOCKING)) {\n response.want_write = true;\n return 0;\n }\n\n if (nbytes == WRITE_DESTROYED)\n return 0;\n\n ErrorErrno(\"write error on HTTP connection\");\n return 0;\n}\n\nssize_t\nHttpServerConnection::OnDirect(FdType type, int fd, size_t max_length)\n{\n assert(socket.IsConnected() || request.request == nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n if (!socket.IsConnected())\n return 0;\n\n ssize_t nbytes = socket.WriteFrom(fd, type, max_length);\n if (likely(nbytes > 0)) {\n response.bytes_sent += nbytes;\n response.length += (off_t)nbytes;\n ScheduleWrite();\n } else if (nbytes == WRITE_BLOCKING) {\n response.want_write = true;\n return ISTREAM_RESULT_BLOCKING;\n } else if (nbytes == WRITE_DESTROYED)\n return ISTREAM_RESULT_CLOSED;\n\n return nbytes;\n}\n\nvoid\nHttpServerConnection::OnEof()\n{\n assert(request.read_state != Request::START &&\n request.read_state != Request::HEADERS);\n assert(request.request != nullptr);\n assert(response.istream.IsDefined());\n assert(!response.pending_drained);\n\n response.istream.Clear();\n\n ResponseIstreamFinished();\n}\n\nvoid\nHttpServerConnection::OnError(GError *error)\n{\n assert(response.istream.IsDefined());\n\n response.istream.Clear();\n\n \/* we clear this async_ref here so http_server_request_close()\n won't think we havn't sent a response yet *\/\n request.async_ref.Clear();\n\n g_prefix_error(&error, \"error on HTTP response stream: \");\n Error(error);\n}\n\nvoid\nHttpServerConnection::SetResponseIstream(Istream &r)\n{\n response.istream.Set(r, *this, socket.GetDirectMask());\n}\n\nbool\nHttpServerConnection::ResponseIstreamFinished()\n{\n socket.UnscheduleWrite();\n\n Log();\n\n \/* check for end of chunked request body again, just in case\n DechunkIstream has announced this in a derred event *\/\n if (request.read_state == Request::BODY && request_body_reader->IsEOF()) {\n request.read_state = Request::END;\n request_body_reader->DestroyEof();\n if (!IsValid())\n return false;\n }\n\n if (request.read_state == Request::BODY &&\n !request.expect_100_continue) {\n \/* We are still reading the request body, which we don't need\n anymore. To discard it, we simply close the connection by\n disabling keepalive; this seems cheaper than redirecting\n the rest of the body to \/dev\/null *\/\n keep_alive = false;\n request.read_state = Request::END;\n\n GError *error =\n g_error_new_literal(http_server_quark(), 0,\n \"request body discarded\");\n request_body_reader->DestroyError(error);\n if (!IsValid())\n return false;\n }\n\n pool_trash(request.request->pool);\n pool_unref(request.request->pool);\n request.request = nullptr;\n request.bytes_received = 0;\n response.bytes_sent = 0;\n\n request.read_state = Request::START;\n\n if (keep_alive) {\n \/* handle pipelined request (if any), or set up events for\n next request *\/\n\n socket.ScheduleReadNoTimeout(false);\n idle_timeout.Add(http_server_idle_timeout);\n\n return true;\n } else {\n \/* keepalive disabled and response is finished: we must close\n the connection *\/\n\n if (socket.IsDrained()) {\n Done();\n return false;\n } else {\n \/* there is still data in the filter's output buffer; wait for\n that to drain, which will trigger\n http_server_socket_drained() *\/\n assert(!response.pending_drained);\n\n response.pending_drained = true;\n\n return true;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainscene.h\"\n#include \"..\/types.h\"\n#include <QGraphicsItem>\n#include <QDebug>\n#include <QGraphicsItemAnimation>\n#include <QTimeLine>\n#include <QGraphicsOpacityEffect>\n#include <QPropertyAnimation>\n#include <QtGlobal>\n#include <QFileInfo>\n\n\n\/\/ Constructor & Destructor\nMainScene::MainScene(qreal x, qreal y,\n qreal width, qreal height,\n QObject *parent)\n : QGraphicsScene(x,y,width,height,parent)\n{\n this->window = dynamic_cast<MainWindow*>(parent);\n Q_CHECK_PTR(this->window);\n\n setupMain();\n}\n\n\nMainScene::~MainScene()\n{\n delete background;\n delete start_button;\n delete credit_button;\n delete gplus_button;\n delete fb_button;\n delete all;\n delete copy;\n delete bgm_player;\n\n qDebug() << \"Main Scene Destroyed\";\n}\n\n\n\/\/ Methods\nvoid MainScene::setupMain()\n{\n \/\/ setup for main\n\n \/\/ set background\n background = new QGameItem(this, window);\n background->setImage(\":images\/main\/main_background.png\");\n background->setPos(0, 0);\n\n \/\/ set buttons\n start_button = new StartButton(this, window);\n start_button->setPos(535,470);\n\n credit_button = new CreditButton(this, window);\n credit_button->setPos(535,560);\n\n gplus_button = new QGameItem(this, window);\n gplus_button->setImage(\":images\/main\/social_g+.png\");\n gplus_button->setPos(1080, 610);\n\n fb_button = new QGameItem(this, window);\n fb_button->setImage(\":images\/main\/social_fb.png\");\n fb_button->setPos(1170, 610);\n\n all = new QGameItem(this, window);\n all->setImage(\":images\/main\/all.png\");\n all->setPos(1175, 5);\n\n copy = new QGameItem(this, window);\n copy->setImage(\":images\/main\/copy.png\");\n copy->setPos(350, 690);\n\n \/\/ setup BGM\n bgm_player = new QMediaPlayer();\n bgm_player->setMedia(QUrl::fromLocalFile(QFileInfo(\"sound\/postech_marble_bgm.mp3\").absoluteFilePath()));\n}\n\n\nvoid MainScene::animateMain()\n{\n bgm_player->play();\n}\n\n\n\/\/ StartButton\nStartButton::StartButton(QGraphicsScene *scene, MainWindow *window)\n : QGameItem(scene, window)\n{\n \/\/ 버튼 초기 이미\n this->setImage(\":\/images\/main\/button_main_start.png\");\n}\n\nStartButton::~StartButton()\n{\n\n}\n\nvoid StartButton::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n qDebug() << \"Start button clicked.\";\n setImage(\":images\/main\/button_main_start_pressed.png\");\n}\n\nvoid StartButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n setImage(\":images\/main\/button_main_start.png\");\n\n \/\/ move to ready scene\n window->switchScene(SceneType::READY);\n}\n\nvoid StartButton::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)\n{\n \/\/ ignore input in this case\n setImage(\":images\/main\/button_main_start.png\");\n}\n\n\n\/\/ CreditButton\nCreditButton::CreditButton(QGraphicsScene *scene, MainWindow *window)\n : QGameItem(scene, window)\n{\n \/\/ 버튼 초기 이미지\n this->setImage(\":\/images\/main\/button_main_credit.png\");\n}\n\nCreditButton::~CreditButton()\n{\n\n}\n\nvoid CreditButton::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n qDebug() << \"Credit button clicked.\";\n setImage(\":images\/main\/button_main_credit_pressed.png\");\n}\n\nvoid CreditButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n setImage(\":images\/main\/button_main_credit.png\");\n\n \/\/ move to ready scene\n window->switchScene(SceneType::CREDIT);\n}\n\nvoid CreditButton::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)\n{\n \/\/ ignore input in this case\n setImage(\":images\/main\/button_main_credit.png\");\n}\n<commit_msg>MainScene: BGM repeat<commit_after>#include \"mainscene.h\"\n#include \"..\/types.h\"\n#include <QGraphicsItem>\n#include <QDebug>\n#include <QGraphicsItemAnimation>\n#include <QTimeLine>\n#include <QGraphicsOpacityEffect>\n#include <QPropertyAnimation>\n#include <QtGlobal>\n#include <QFileInfo>\n\n\n\/\/ Constructor & Destructor\nMainScene::MainScene(qreal x, qreal y,\n qreal width, qreal height,\n QObject *parent)\n : QGraphicsScene(x,y,width,height,parent)\n{\n this->window = dynamic_cast<MainWindow*>(parent);\n Q_CHECK_PTR(this->window);\n\n setupMain();\n connect(bgm_player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), bgm_player, SLOT(play()));\n}\n\n\nMainScene::~MainScene()\n{\n delete background;\n delete start_button;\n delete credit_button;\n delete gplus_button;\n delete fb_button;\n delete all;\n delete copy;\n delete bgm_player;\n\n qDebug() << \"Main Scene Destroyed\";\n}\n\n\n\/\/ Methods\nvoid MainScene::setupMain()\n{\n \/\/ setup for main\n\n \/\/ set background\n background = new QGameItem(this, window);\n background->setImage(\":images\/main\/main_background.png\");\n background->setPos(0, 0);\n\n \/\/ set buttons\n start_button = new StartButton(this, window);\n start_button->setPos(535,470);\n\n credit_button = new CreditButton(this, window);\n credit_button->setPos(535,560);\n\n gplus_button = new QGameItem(this, window);\n gplus_button->setImage(\":images\/main\/social_g+.png\");\n gplus_button->setPos(1080, 610);\n\n fb_button = new QGameItem(this, window);\n fb_button->setImage(\":images\/main\/social_fb.png\");\n fb_button->setPos(1170, 610);\n\n all = new QGameItem(this, window);\n all->setImage(\":images\/main\/all.png\");\n all->setPos(1175, 5);\n\n copy = new QGameItem(this, window);\n copy->setImage(\":images\/main\/copy.png\");\n copy->setPos(350, 690);\n\n \/\/ setup BGM\n bgm_player = new QMediaPlayer();\n bgm_player->setMedia(QUrl::fromLocalFile(QFileInfo(\"sound\/postech_marble_bgm.mp3\").absoluteFilePath()));\n}\n\n\nvoid MainScene::animateMain()\n{\n bgm_player->play();\n}\n\n\n\/\/ StartButton\nStartButton::StartButton(QGraphicsScene *scene, MainWindow *window)\n : QGameItem(scene, window)\n{\n \/\/ 버튼 초기 이미\n this->setImage(\":\/images\/main\/button_main_start.png\");\n}\n\nStartButton::~StartButton()\n{\n\n}\n\nvoid StartButton::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n qDebug() << \"Start button clicked.\";\n setImage(\":images\/main\/button_main_start_pressed.png\");\n}\n\nvoid StartButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n setImage(\":images\/main\/button_main_start.png\");\n\n \/\/ move to ready scene\n window->switchScene(SceneType::READY);\n}\n\nvoid StartButton::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)\n{\n \/\/ ignore input in this case\n setImage(\":images\/main\/button_main_start.png\");\n}\n\n\n\/\/ CreditButton\nCreditButton::CreditButton(QGraphicsScene *scene, MainWindow *window)\n : QGameItem(scene, window)\n{\n \/\/ 버튼 초기 이미지\n this->setImage(\":\/images\/main\/button_main_credit.png\");\n}\n\nCreditButton::~CreditButton()\n{\n\n}\n\nvoid CreditButton::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n qDebug() << \"Credit button clicked.\";\n setImage(\":images\/main\/button_main_credit_pressed.png\");\n}\n\nvoid CreditButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n setImage(\":images\/main\/button_main_credit.png\");\n\n \/\/ move to ready scene\n window->switchScene(SceneType::CREDIT);\n}\n\nvoid CreditButton::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)\n{\n \/\/ ignore input in this case\n setImage(\":images\/main\/button_main_credit.png\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2021 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\nnamespace openspace::luascriptfunctions {\n\n\nint startRecording(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startRecording\");\n\n using ghoul::lua::luaTypeToString;\n\n const std::string recordFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (recordFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->setRecordDataFormat(\n interaction::SessionRecording::DataMode::Binary\n );\n global::sessionRecording->startRecording(recordFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startRecordingAscii(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startRecordingAscii\");\n\n using ghoul::lua::luaTypeToString;\n\n const std::string recordFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (recordFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->setRecordDataFormat(\n interaction::SessionRecording::DataMode::Ascii\n );\n global::sessionRecording->startRecording(recordFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint stopRecording(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::stopRecording\");\n\n global::sessionRecording->stopRecording();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode,\n bool forceSimTimeAtStart)\n{\n using ghoul::lua::luaTypeToString;\n const int nArguments = lua_gettop(L);\n bool loop = false;\n\n if (nArguments == 2) {\n loop = lua_toboolean(L, 2) == 1;\n }\n else if (nArguments != 1) {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 1 or 2, got %i\",\n nArguments\n );\n }\n\n const std::string playbackFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (playbackFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n\n global::sessionRecording->startPlayback(\n const_cast<std::string&>(playbackFilePath),\n timeMode,\n forceSimTimeAtStart,\n loop\n );\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startPlaybackDefault(lua_State* L) {\n using interaction::KeyframeNavigator;\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_recordedStart, true);\n}\n\nint startPlaybackApplicationTime(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startPlaybackApplicationTime\");\n\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_applicationStart, false);\n}\n\nint startPlaybackRecordedTime(lua_State* L) {\n using interaction::KeyframeNavigator;\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_recordedStart, false);\n}\n\nint startPlaybackSimulationTime(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startPlaybackSimulationTime\");\n using interaction::KeyframeNavigator;\n return startPlayback(L,\n interaction::KeyframeTimeRef::Absolute_simTimeJ2000, false);\n}\n\nint stopPlayback(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::stopPlayback\");\n\n global::sessionRecording->stopPlayback();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint enableTakeScreenShotDuringPlayback(lua_State* L) {\n const int nArguments = ghoul::lua::checkArgumentsAndThrow(\n L,\n { 0, 1 },\n \"lua::enableTakeScreenShotDuringPlayback\"\n );\n\n const int fps = nArguments == 0 ? 60 : ghoul::lua::value<int>(L, 1);\n\n global::sessionRecording->enableTakeScreenShotDuringPlayback(fps);\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint disableTakeScreenShotDuringPlayback(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::disableTakeScreenShotDuringPlayback\");\n\n global::sessionRecording->disableTakeScreenShotDuringPlayback();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint fileFormatConversion(lua_State* L) {\n using ghoul::lua::luaTypeToString;\n\n const std::string convertFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (convertFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->convertFile(convertFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint setPlaybackPause(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments == 1) {\n const bool pause = lua_toboolean(L, 1) == 1;\n global::sessionRecording->setPlaybackPause(pause);\n }\n else {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 1, got %i\",\n nArguments\n );\n }\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint togglePlaybackPause(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments == 0) {\n bool isPlaybackPaused = global::sessionRecording->isPlaybackPaused();\n global::sessionRecording->setPlaybackPause(!isPlaybackPaused);\n }\n else {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 0, got %i\",\n nArguments\n );\n }\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint isPlayingBack(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments != 0) {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 0, got %i\",\n nArguments\n );\n }\n\n ghoul::lua::push(L, global::sessionRecording->isPlayingBack());\n ghoul_assert(lua_gettop(L) == 1, \"Incorrect number of items left on stack\");\n return 1;\n}\n\n} \/\/ namespace openspace::luascriptfunctions\n<commit_msg>Restored a few asserts on lua commands<commit_after>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2021 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\nnamespace openspace::luascriptfunctions {\n\n\nint startRecording(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startRecording\");\n\n using ghoul::lua::luaTypeToString;\n\n const std::string recordFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (recordFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->setRecordDataFormat(\n interaction::SessionRecording::DataMode::Binary\n );\n global::sessionRecording->startRecording(recordFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startRecordingAscii(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startRecordingAscii\");\n\n using ghoul::lua::luaTypeToString;\n\n const std::string recordFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (recordFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->setRecordDataFormat(\n interaction::SessionRecording::DataMode::Ascii\n );\n global::sessionRecording->startRecording(recordFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint stopRecording(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::stopRecording\");\n\n global::sessionRecording->stopRecording();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startPlayback(lua_State* L, interaction::KeyframeTimeRef timeMode,\n bool forceSimTimeAtStart)\n{\n using ghoul::lua::luaTypeToString;\n const int nArguments = lua_gettop(L);\n bool loop = false;\n\n if (nArguments == 2) {\n loop = lua_toboolean(L, 2) == 1;\n }\n else if (nArguments != 1) {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 1 or 2, got %i\",\n nArguments\n );\n }\n\n const std::string playbackFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (playbackFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n\n global::sessionRecording->startPlayback(\n const_cast<std::string&>(playbackFilePath),\n timeMode,\n forceSimTimeAtStart,\n loop\n );\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint startPlaybackDefault(lua_State* L) {\n using interaction::KeyframeNavigator;\n ghoul::lua::checkArgumentsAndThrow(L, {1, 2}, \"lua::startPlaybackDefault\");\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_recordedStart, true);\n}\n\nint startPlaybackApplicationTime(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startPlaybackApplicationTime\");\n\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_applicationStart, false);\n}\n\nint startPlaybackRecordedTime(lua_State* L) {\n using interaction::KeyframeNavigator;\n ghoul::lua::checkArgumentsAndThrow(L, {1, 2}, \"lua::startPlaybackRecordedTime\");\n return startPlayback(L,\n interaction::KeyframeTimeRef::Relative_recordedStart, false);\n}\n\nint startPlaybackSimulationTime(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 1, \"lua::startPlaybackSimulationTime\");\n using interaction::KeyframeNavigator;\n return startPlayback(L,\n interaction::KeyframeTimeRef::Absolute_simTimeJ2000, false);\n}\n\nint stopPlayback(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::stopPlayback\");\n\n global::sessionRecording->stopPlayback();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint enableTakeScreenShotDuringPlayback(lua_State* L) {\n const int nArguments = ghoul::lua::checkArgumentsAndThrow(\n L,\n { 0, 1 },\n \"lua::enableTakeScreenShotDuringPlayback\"\n );\n\n const int fps = nArguments == 0 ? 60 : ghoul::lua::value<int>(L, 1);\n\n global::sessionRecording->enableTakeScreenShotDuringPlayback(fps);\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint disableTakeScreenShotDuringPlayback(lua_State* L) {\n ghoul::lua::checkArgumentsAndThrow(L, 0, \"lua::disableTakeScreenShotDuringPlayback\");\n\n global::sessionRecording->disableTakeScreenShotDuringPlayback();\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint fileFormatConversion(lua_State* L) {\n using ghoul::lua::luaTypeToString;\n\n const std::string convertFilePath = ghoul::lua::value<std::string>(\n L,\n 1,\n ghoul::lua::PopValue::Yes\n );\n\n if (convertFilePath.empty()) {\n return luaL_error(L, \"filepath string is empty\");\n }\n global::sessionRecording->convertFile(convertFilePath);\n\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint setPlaybackPause(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments == 1) {\n const bool pause = lua_toboolean(L, 1) == 1;\n global::sessionRecording->setPlaybackPause(pause);\n }\n else {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 1, got %i\",\n nArguments\n );\n }\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint togglePlaybackPause(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments == 0) {\n bool isPlaybackPaused = global::sessionRecording->isPlaybackPaused();\n global::sessionRecording->setPlaybackPause(!isPlaybackPaused);\n }\n else {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 0, got %i\",\n nArguments\n );\n }\n\n lua_settop(L, 0);\n ghoul_assert(lua_gettop(L) == 0, \"Incorrect number of items left on stack\");\n return 0;\n}\n\nint isPlayingBack(lua_State* L) {\n const int nArguments = lua_gettop(L);\n\n if (nArguments != 0) {\n lua_settop(L, 0);\n return luaL_error(\n L,\n \"bad number of arguments, expected 0, got %i\",\n nArguments\n );\n }\n\n ghoul::lua::push(L, global::sessionRecording->isPlayingBack());\n ghoul_assert(lua_gettop(L) == 1, \"Incorrect number of items left on stack\");\n return 1;\n}\n\n} \/\/ namespace openspace::luascriptfunctions\n<|endoftext|>"} {"text":"<commit_before>#include \"Console.hpp\"\n\n#include \"logger.hpp\"\n\n#define PUTC(c) pc.putc(c)\n#define GETC pc.getc\n#define PRINTF(...) pc.printf(__VA_ARGS__)\n\nconst std::string Console::RX_BUFFER_FULL_MSG = \"RX BUFFER FULL\";\nconst std::string Console::COMMAND_BREAK_MSG = \"*BREAK*\\033[K\";\n\nshared_ptr<Console> Console::instance;\n\nbool Console::iter_break_req = false;\nbool Console::command_handled = true;\nbool Console::command_ready = false;\n\nConsole::Console() : pc(USBTX, USBRX) {}\n\nConsole::~Console() { instance.reset(); }\n\nshared_ptr<Console>& Console::Instance() {\n if (instance.get() == nullptr) instance.reset(new Console);\n\n return instance;\n}\n\nvoid Console::Init() {\n auto instance = Instance();\n\n \/\/ Set default values for the header parameters\n instance->CONSOLE_USER = \"anon\";\n instance->CONSOLE_HOSTNAME = \"robot\";\n instance->setHeader();\n\n \/\/ set baud rate, store the value before\n Baudrate(57600);\n\n \/\/ clear buffers\n instance->ClearRXBuffer();\n instance->ClearTXBuffer();\n\n \/\/ attach interrupt handlers\n \/\/ instance->pc.attach(&Console::RXCallback_MODSERIAL, MODSERIAL::RxIrq);\n \/\/ instance->pc.attach(&Console::TXCallback_MODSERIAL, MODSERIAL::TxIrq);\n instance->pc.attach(instance.get(), &Console::RXCallback, Serial::RxIrq);\n instance->pc.attach(instance.get(), &Console::TXCallback, Serial::TxIrq);\n\n \/\/ reset indicces\n instance->rxIndex = 0;\n instance->txIndex = 0;\n\n \/\/ Default for a host response escaped input terminating character\n \/\/ instance->SetEscEnd('R');\n\n LOG(INF3, \"Hello from the 'common2015' library!\");\n}\n\nvoid Console::PrintHeader() {\n \/\/ prints out a bash-like header\n Flush();\n instance->PRINTF(\"\\r\\n%s\", instance->CONSOLE_HEADER.c_str());\n Flush();\n}\n\nvoid Console::ClearRXBuffer() { memset(rxBuffer, '\\0', BUFFER_LENGTH); }\n\nvoid Console::ClearTXBuffer() { memset(txBuffer, '\\0', BUFFER_LENGTH); }\n\nvoid Console::Flush() { fflush(stdout); }\n\nvoid Console::RXCallback() {\n \/\/ If for some reason more than one character is in the buffer when the\n \/\/ interrupt is called, handle them all.\n while (pc.readable()) {\n \/\/ If there is an command that hasn't finished yet, ignore the character\n \/\/ for now\n if (command_handled == false && command_ready == true) {\n return;\n\n } else {\n \/\/ Otherwise, continue as normal\n \/\/ read the char that caused the interrupt\n char c = GETC();\n\n \/\/ if the buffer is full, ignore the chracter and print a\n \/\/ warning to the console\n if (rxIndex >= (BUFFER_LENGTH - 5) && c != BACKSPACE_FLAG_CHAR) {\n rxIndex = 0;\n PRINTF(\"%s\\r\\n\", RX_BUFFER_FULL_MSG.c_str());\n Flush();\n\n \/\/ Execute the function that sets up the console after a\n \/\/ command's execution.\n \/\/ This will ensure everything flushes corectly on a full buffer\n CommandHandled(true);\n }\n\n \/\/ if a new line character is sent, process the current buffer\n else if (c == NEW_LINE_CHAR) {\n \/\/ print new line prior to executing\n PRINTF(\"%c\\n\", NEW_LINE_CHAR);\n Flush();\n rxBuffer[rxIndex] = '\\0';\n\n command_ready = true;\n command_handled = false;\n }\n\n \/\/ if a backspace is requested, handle it.\n else if (c == BACKSPACE_FLAG_CHAR)\n if (rxIndex > 0) { \/\/ instance->CONSOLE_HEADER.length()) {\n \/\/ re-terminate the string\n rxBuffer[--rxIndex] = '\\0';\n\n \/\/ 1) Move cursor back\n \/\/ 2) Write a space to clear the character\n \/\/ 3) Move back cursor again\n PUTC(BACKSPACE_REPLY_CHAR);\n PUTC(BACKSPACE_REPLACE_CHAR);\n PUTC(BACKSPACE_REPLY_CHAR);\n Flush();\n } else {\n \/* do nothing if we can't back space any more *\/\n }\n\n \/\/ set that a command break was requested flag if we received a\n \/\/ break character\n else if (c == BREAK_CHAR) {\n iter_break_req = true;\n }\n\n \/\/ No special character, add it to the buffer and return it to\n \/\/ the terminal to be visible.\n else {\n if (!(c == ARROW_UP_KEY || c == ARROW_DOWN_KEY ||\n c == ARROW_DOWN_KEY || c == ARROW_DOWN_KEY)) {\n rxBuffer[rxIndex++] = c;\n }\n PUTC(c);\n Flush();\n }\n }\n }\n}\n\nvoid Console::TXCallback() {\n NVIC_DisableIRQ(UART0_IRQn);\n \/\/ handle transmission interrupts if necessary here\n NVIC_EnableIRQ(UART0_IRQn);\n}\n\nvoid Console::RequestSystemStop() { Instance()->sysStopReq = true; }\n\nbool Console::IsSystemStopRequested() { return Instance()->sysStopReq; }\n\nbool Console::IterCmdBreakReq() { return iter_break_req; }\n\nvoid Console::IterCmdBreakReq(bool newState) {\n iter_break_req = newState;\n\n \/\/ Print out the header if an iterating command is stopped\n if (newState == false) {\n instance->PRINTF(\"%s\", COMMAND_BREAK_MSG.c_str());\n PrintHeader();\n }\n}\n\nchar* Console::rxBufferPtr() { return instance->rxBuffer; }\n\nbool Console::CommandReady() { return command_ready; }\n\nvoid Console::CommandHandled(bool cmdDoneState) {\n \/\/ update the class's flag for if a command was handled or not\n command_handled = cmdDoneState;\n\n \/\/ Clean up after command execution\n instance->rxIndex = 0;\n\n \/\/ reset our outgoing flag saying if there's a valid command sequence in the\n \/\/ RX buffer or now\n command_ready = false;\n\n \/\/ print out the header without a newline first\n if (iter_break_req == false) {\n instance->PRINTF(\"%s\", instance->CONSOLE_HEADER.c_str());\n Flush();\n }\n}\n\nvoid Console::changeHostname(const std::string& hostname) {\n instance->CONSOLE_HOSTNAME = hostname;\n instance->setHeader();\n}\n\nvoid Console::changeUser(const std::string& user) {\n instance->CONSOLE_USER = user;\n instance->setHeader();\n}\n\nvoid Console::setHeader() {\n instance->CONSOLE_HEADER =\n \"\\033[1;36m\" + instance->CONSOLE_USER + \"\\033[1;32m@\\033[01;33m\" +\n instance->CONSOLE_HOSTNAME + \" \\033[36m$\\033[0m \\033[0J\\033[0m\";\n \/\/ instance->CONSOLE_HEADER = instance->CONSOLE_USER + \"@\" +\n \/\/ instance->CONSOLE_HOSTNAME + \" $ \";\n}\n\nvoid Console::Baudrate(uint16_t baud) {\n instance->baudrate = baud;\n instance->pc.baud(instance->baudrate);\n}\n\nuint16_t Console::Baudrate() { return instance->baudrate; }\n\nvoid Console::RXCallback_MODSERIAL(MODSERIAL_IRQ_INFO* info) {\n Console::RXCallback();\n}\n\nvoid Console::TXCallback_MODSERIAL(MODSERIAL_IRQ_INFO* info) {\n Console::TXCallback();\n}\n\nvoid Console::SetEscEnd(char c) { instance->esc_host_end_char = c; }\n\nstd::string Console::GetHostResponse() {\n if (instance->esc_host_res_rdy == true) {\n instance->esc_host_res_rdy = false;\n\n return instance->esc_host_res;\n } else {\n return \"\";\n }\n}\n\nvoid Console::ShowLogo() {\n Flush();\n\n instance->PRINTF(\n \"\\033[01;33m\"\n \" _____ _ _ _ _\\r\\n\"\n \" | __ \\\\ | | | | | | | | \\r\\n\"\n \" | |__) |___ | |__ ___ | | __ _ ___| | _____| |_ ___ \\r\\n\"\n \" | _ \/\/ _ \\\\| '_ \\\\ \/ _ \\\\ _ | |\/ _` |\/ __| |\/ \/ _ \\\\ __\/ __|\\r\\n\"\n \" | | \\\\ \\\\ (_) | |_) | (_) | |__| | (_| | (__| < __\/ |_\\\\__ \\\\\\r\\n\"\n \" |_| \\\\_\\\\___\/|_.__\/ \\\\___\/ \\\\____\/ \"\n \"\\\\__,_|\\\\___|_|\\\\_\\\\___|\\\\__|___\/\\r\\n\\033[0m\");\n\n Flush();\n}\n\nvoid Console::SetTitle(const std::string& title) {\n instance->PRINTF(\"\\033]0;%s\\007\", title.c_str());\n Flush();\n}\n<commit_msg>stopping interrupt changes on tx callback<commit_after>#include \"Console.hpp\"\n\n#include \"logger.hpp\"\n\n#define PUTC(c) pc.putc(c)\n#define GETC pc.getc\n#define PRINTF(...) pc.printf(__VA_ARGS__)\n\nconst std::string Console::RX_BUFFER_FULL_MSG = \"RX BUFFER FULL\";\nconst std::string Console::COMMAND_BREAK_MSG = \"*BREAK*\\033[K\";\n\nshared_ptr<Console> Console::instance;\n\nbool Console::iter_break_req = false;\nbool Console::command_handled = true;\nbool Console::command_ready = false;\n\nConsole::Console() : pc(USBTX, USBRX) {}\n\nConsole::~Console() { instance.reset(); }\n\nshared_ptr<Console>& Console::Instance() {\n if (instance.get() == nullptr) instance.reset(new Console);\n\n return instance;\n}\n\nvoid Console::Init() {\n auto instance = Instance();\n\n \/\/ Set default values for the header parameters\n instance->CONSOLE_USER = \"anon\";\n instance->CONSOLE_HOSTNAME = \"robot\";\n instance->setHeader();\n\n \/\/ set baud rate, store the value before\n Baudrate(57600);\n\n \/\/ clear buffers\n instance->ClearRXBuffer();\n instance->ClearTXBuffer();\n\n \/\/ attach interrupt handlers\n \/\/ instance->pc.attach(&Console::RXCallback_MODSERIAL, MODSERIAL::RxIrq);\n \/\/ instance->pc.attach(&Console::TXCallback_MODSERIAL, MODSERIAL::TxIrq);\n instance->pc.attach(instance.get(), &Console::RXCallback, Serial::RxIrq);\n instance->pc.attach(instance.get(), &Console::TXCallback, Serial::TxIrq);\n\n \/\/ reset indicces\n instance->rxIndex = 0;\n instance->txIndex = 0;\n\n \/\/ Default for a host response escaped input terminating character\n \/\/ instance->SetEscEnd('R');\n\n LOG(INF3, \"Hello from the 'common2015' library!\");\n}\n\nvoid Console::PrintHeader() {\n \/\/ prints out a bash-like header\n Flush();\n instance->PRINTF(\"\\r\\n%s\", instance->CONSOLE_HEADER.c_str());\n Flush();\n}\n\nvoid Console::ClearRXBuffer() { memset(rxBuffer, '\\0', BUFFER_LENGTH); }\n\nvoid Console::ClearTXBuffer() { memset(txBuffer, '\\0', BUFFER_LENGTH); }\n\nvoid Console::Flush() { fflush(stdout); }\n\nvoid Console::RXCallback() {\n \/\/ If for some reason more than one character is in the buffer when the\n \/\/ interrupt is called, handle them all.\n while (pc.readable()) {\n \/\/ If there is an command that hasn't finished yet, ignore the character\n \/\/ for now\n if (command_handled == false && command_ready == true) {\n return;\n\n } else {\n \/\/ Otherwise, continue as normal\n \/\/ read the char that caused the interrupt\n char c = GETC();\n\n \/\/ if the buffer is full, ignore the chracter and print a\n \/\/ warning to the console\n if (rxIndex >= (BUFFER_LENGTH - 5) && c != BACKSPACE_FLAG_CHAR) {\n rxIndex = 0;\n PRINTF(\"%s\\r\\n\", RX_BUFFER_FULL_MSG.c_str());\n Flush();\n\n \/\/ Execute the function that sets up the console after a\n \/\/ command's execution.\n \/\/ This will ensure everything flushes corectly on a full buffer\n CommandHandled(true);\n }\n\n \/\/ if a new line character is sent, process the current buffer\n else if (c == NEW_LINE_CHAR) {\n \/\/ print new line prior to executing\n PRINTF(\"%c\\n\", NEW_LINE_CHAR);\n Flush();\n rxBuffer[rxIndex] = '\\0';\n\n command_ready = true;\n command_handled = false;\n }\n\n \/\/ if a backspace is requested, handle it.\n else if (c == BACKSPACE_FLAG_CHAR)\n if (rxIndex > 0) { \/\/ instance->CONSOLE_HEADER.length()) {\n \/\/ re-terminate the string\n rxBuffer[--rxIndex] = '\\0';\n\n \/\/ 1) Move cursor back\n \/\/ 2) Write a space to clear the character\n \/\/ 3) Move back cursor again\n PUTC(BACKSPACE_REPLY_CHAR);\n PUTC(BACKSPACE_REPLACE_CHAR);\n PUTC(BACKSPACE_REPLY_CHAR);\n Flush();\n } else {\n \/* do nothing if we can't back space any more *\/\n }\n\n \/\/ set that a command break was requested flag if we received a\n \/\/ break character\n else if (c == BREAK_CHAR) {\n iter_break_req = true;\n }\n\n \/\/ No special character, add it to the buffer and return it to\n \/\/ the terminal to be visible.\n else {\n if (!(c == ARROW_UP_KEY || c == ARROW_DOWN_KEY ||\n c == ARROW_DOWN_KEY || c == ARROW_DOWN_KEY)) {\n rxBuffer[rxIndex++] = c;\n }\n PUTC(c);\n Flush();\n }\n }\n }\n}\n\nvoid Console::TXCallback() {\n \/\/ NVIC_DisableIRQ(UART0_IRQn);\n \/\/ handle transmission interrupts if necessary here\n \/\/ NVIC_EnableIRQ(UART0_IRQn);\n}\n\nvoid Console::RequestSystemStop() { Instance()->sysStopReq = true; }\n\nbool Console::IsSystemStopRequested() { return Instance()->sysStopReq; }\n\nbool Console::IterCmdBreakReq() { return iter_break_req; }\n\nvoid Console::IterCmdBreakReq(bool newState) {\n iter_break_req = newState;\n\n \/\/ Print out the header if an iterating command is stopped\n if (newState == false) {\n instance->PRINTF(\"%s\", COMMAND_BREAK_MSG.c_str());\n PrintHeader();\n }\n}\n\nchar* Console::rxBufferPtr() { return instance->rxBuffer; }\n\nbool Console::CommandReady() { return command_ready; }\n\nvoid Console::CommandHandled(bool cmdDoneState) {\n \/\/ update the class's flag for if a command was handled or not\n command_handled = cmdDoneState;\n\n \/\/ Clean up after command execution\n instance->rxIndex = 0;\n\n \/\/ reset our outgoing flag saying if there's a valid command sequence in the\n \/\/ RX buffer or now\n command_ready = false;\n\n \/\/ print out the header without a newline first\n if (iter_break_req == false) {\n instance->PRINTF(\"%s\", instance->CONSOLE_HEADER.c_str());\n Flush();\n }\n}\n\nvoid Console::changeHostname(const std::string& hostname) {\n instance->CONSOLE_HOSTNAME = hostname;\n instance->setHeader();\n}\n\nvoid Console::changeUser(const std::string& user) {\n instance->CONSOLE_USER = user;\n instance->setHeader();\n}\n\nvoid Console::setHeader() {\n instance->CONSOLE_HEADER =\n \"\\033[1;36m\" + instance->CONSOLE_USER + \"\\033[1;32m@\\033[01;33m\" +\n instance->CONSOLE_HOSTNAME + \" \\033[36m$\\033[0m \\033[0J\\033[0m\";\n \/\/ instance->CONSOLE_HEADER = instance->CONSOLE_USER + \"@\" +\n \/\/ instance->CONSOLE_HOSTNAME + \" $ \";\n}\n\nvoid Console::Baudrate(uint16_t baud) {\n instance->baudrate = baud;\n instance->pc.baud(instance->baudrate);\n}\n\nuint16_t Console::Baudrate() { return instance->baudrate; }\n\nvoid Console::RXCallback_MODSERIAL(MODSERIAL_IRQ_INFO* info) {\n Console::RXCallback();\n}\n\nvoid Console::TXCallback_MODSERIAL(MODSERIAL_IRQ_INFO* info) {\n Console::TXCallback();\n}\n\nvoid Console::SetEscEnd(char c) { instance->esc_host_end_char = c; }\n\nstd::string Console::GetHostResponse() {\n if (instance->esc_host_res_rdy == true) {\n instance->esc_host_res_rdy = false;\n\n return instance->esc_host_res;\n } else {\n return \"\";\n }\n}\n\nvoid Console::ShowLogo() {\n Flush();\n\n instance->PRINTF(\n \"\\033[01;33m\"\n \" _____ _ _ _ _\\r\\n\"\n \" | __ \\\\ | | | | | | | | \\r\\n\"\n \" | |__) |___ | |__ ___ | | __ _ ___| | _____| |_ ___ \\r\\n\"\n \" | _ \/\/ _ \\\\| '_ \\\\ \/ _ \\\\ _ | |\/ _` |\/ __| |\/ \/ _ \\\\ __\/ __|\\r\\n\"\n \" | | \\\\ \\\\ (_) | |_) | (_) | |__| | (_| | (__| < __\/ |_\\\\__ \\\\\\r\\n\"\n \" |_| \\\\_\\\\___\/|_.__\/ \\\\___\/ \\\\____\/ \"\n \"\\\\__,_|\\\\___|_|\\\\_\\\\___|\\\\__|___\/\\r\\n\\033[0m\");\n\n Flush();\n}\n\nvoid Console::SetTitle(const std::string& title) {\n instance->PRINTF(\"\\033]0;%s\\007\", title.c_str());\n Flush();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GameLogger.h\"\n\nGameLogger::GameLogger()\n{\n logfileManager.openFile(\"\/home\/nao\/game.log\");\n}\n\nvoid GameLogger::execute()\n{\n std::stringstream& stream =\n logfileManager.log(getFrameInfo().getFrameNumber(), \"BehaviorStatus\");\n Serializer<BehaviorStatus>::serialize(getBehaviorStatus(), stream);\n}\n\nGameLogger::~GameLogger()\n{\n logfileManager.closeFile();\n}\n<commit_msg>always log the full ringbuffer<commit_after>#include \"GameLogger.h\"\n\nGameLogger::GameLogger()\n : logfileManager(true)\n{\n logfileManager.openFile(\"\/home\/nao\/game.log\");\n}\n\nvoid GameLogger::execute()\n{\n std::stringstream& stream =\n logfileManager.log(getFrameInfo().getFrameNumber(), \"BehaviorStatus\");\n Serializer<BehaviorStatus>::serialize(getBehaviorStatus(), stream);\n}\n\nGameLogger::~GameLogger()\n{\n logfileManager.closeFile();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"coreapplication.h\"\n#include \"debug.h\"\n#include \"utils.h\"\n#include \"widgets\/setupdialog.h\"\n\n#include <QDialog>\n#include <QFontDatabase>\n#include <QMessageBox>\n\nCoreApplication::CoreApplication(int &argc, char **argv)\n : QApplication(argc, argv),\n _mainWindow(NULL),\n _notification(),\n _jobsOption(false)\n{\n qRegisterMetaType<TaskStatus>(\"TaskStatus\");\n qRegisterMetaType<QList<QUrl>>(\"QList<QUrl>\");\n qRegisterMetaType<BackupTaskPtr>(\"BackupTaskPtr\");\n qRegisterMetaType<QList<ArchivePtr>>(\"QList<ArchivePtr >\");\n qRegisterMetaType<ArchivePtr>(\"ArchivePtr\");\n qRegisterMetaType<ArchiveRestoreOptions>(\"ArchiveRestoreOptions\");\n qRegisterMetaType<QSqlQuery>(\"QSqlQuery\");\n qRegisterMetaType<JobPtr>(\"JobPtr\");\n qRegisterMetaType<QMap<QString, JobPtr>>(\"QMap<QString, JobPtr>\");\n qRegisterMetaType<QSystemTrayIcon::ActivationReason>(\"QSystemTrayIcon::ActivationReason\");\n qRegisterMetaType<TarsnapError>(\"TarsnapError\");\n\n QCoreApplication::setOrganizationName(QLatin1String(\"Tarsnap Backup Inc.\"));\n QCoreApplication::setOrganizationDomain(QLatin1String(\"tarsnap.com\"));\n QCoreApplication::setApplicationName(QLatin1String(\"Tarsnap\"));\n QCoreApplication::setApplicationVersion(APP_VERSION);\n}\n\nCoreApplication::~CoreApplication()\n{\n if(_mainWindow)\n delete _mainWindow;\n}\n\nvoid CoreApplication::parseArgs()\n{\n QCommandLineParser parser;\n parser.setApplicationDescription(QLatin1String(\"Tarsnap GUI - Online backups for the truly lazy\"));\n parser.addHelpOption();\n parser.addVersionOption();\n QCommandLineOption jobsOption(QStringList() << \"j\" << \"jobs\",\n tr(\"Executes all jobs sequentially that have the \\'Include in scheduled backups\\' option checked.\"\n \" The application runs headless and useful information is printed to standard out and error.\"));\n QCommandLineOption appDataOption(QStringList() << \"a\" << \"appdata\",\n tr(\"Use the specified app data directory.\"\n \" Useful for multiple configurations on the same machine (INI format is implied).\"),\n tr(\"directory\"));\n parser.addOption(jobsOption);\n parser.addOption(appDataOption);\n parser.process(arguments());\n _jobsOption = parser.isSet(jobsOption);\n _appDataDir = parser.value(appDataOption);\n}\n\nbool CoreApplication::initialize()\n{\n parseArgs();\n\n QSettings settings;\n\n if(!_appDataDir.isEmpty())\n {\n settings.setPath(QSettings::IniFormat, QSettings::UserScope, _appDataDir);\n settings.setDefaultFormat(QSettings::IniFormat);\n }\n\n bool wizardDone = settings.value(\"app\/wizard_done\", false).toBool();\n if(!wizardDone)\n {\n \/\/ Show the first time setup dialog\n SetupDialog wizard;\n connect(&wizard, &SetupDialog::getTarsnapVersion, &_taskManager,\n &TaskManager::getTarsnapVersion);\n connect(&_taskManager, &TaskManager::tarsnapVersion, &wizard,\n &SetupDialog::setTarsnapVersion);\n connect(&wizard, &SetupDialog::requestRegisterMachine, &_taskManager,\n &TaskManager::registerMachine);\n connect(&_taskManager, &TaskManager::registerMachineStatus, &wizard,\n &SetupDialog::registerMachineStatus);\n connect(&_taskManager, &TaskManager::idle, &wizard,\n &SetupDialog::updateLoadingAnimation);\n\n if(QDialog::Rejected == wizard.exec())\n {\n quit(); \/\/ if we're running in the loop\n return false; \/\/ if called from main\n }\n }\n\n bool iniFormat = settings.value(\"app\/ini_format\", false).toBool();\n if(iniFormat)\n {\n QString appData = settings.value(\"app\/app_data\", APPDATA).toString();\n settings.setPath(QSettings::IniFormat, QSettings::UserScope, appData);\n settings.setDefaultFormat(QSettings::IniFormat);\n }\n\n connect(&_taskManager, &TaskManager::displayNotification,\n &_notification, &Notification::displayNotification, QUEUED);\n QMetaObject::invokeMethod(&_taskManager, \"loadSettings\", QUEUED);\n QMetaObject::invokeMethod(&_journal, \"load\", QUEUED);\n\n if(_jobsOption)\n {\n connect(&_notification, &Notification::activated, this,\n &CoreApplication::showMainWindow, QUEUED);\n connect(&_notification, &Notification::messageClicked, this,\n &CoreApplication::showMainWindow, QUEUED);\n _taskManager.setHeadless(true);\n QMetaObject::invokeMethod(&_taskManager, \"runScheduledJobs\", QUEUED);\n }\n else\n {\n showMainWindow();\n }\n\n return true;\n}\n\nvoid CoreApplication::showMainWindow()\n{\n if(_mainWindow != NULL)\n return;\n\n _taskManager.setHeadless(false);\n disconnect(&_notification, &Notification::activated, this,\n &CoreApplication::showMainWindow);\n disconnect(&_notification, &Notification::messageClicked, this,\n &CoreApplication::showMainWindow);\n\n _mainWindow = new MainWindow();\n Q_ASSERT(_mainWindow != NULL);\n\n connect(_mainWindow, &MainWindow::getTarsnapVersion, &_taskManager,\n &TaskManager::getTarsnapVersion, QUEUED);\n connect(&_taskManager, &TaskManager::tarsnapVersion, _mainWindow,\n &MainWindow::setTarsnapVersion, QUEUED);\n connect(_mainWindow, &MainWindow::backupNow, &_taskManager,\n &TaskManager::backupNow, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchives, &_taskManager,\n &TaskManager::loadArchives, QUEUED);\n connect(&_taskManager, &TaskManager::archiveList, _mainWindow,\n &MainWindow::archiveList, QUEUED);\n connect(_mainWindow, &MainWindow::deleteArchives, &_taskManager,\n &TaskManager::deleteArchives, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchiveStats, &_taskManager,\n &TaskManager::getArchiveStats, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchiveContents, &_taskManager,\n &TaskManager::getArchiveContents, QUEUED);\n connect(&_taskManager, &TaskManager::idle, _mainWindow,\n &MainWindow::updateLoadingAnimation, QUEUED);\n connect(_mainWindow, &MainWindow::getOverallStats, &_taskManager,\n &TaskManager::getOverallStats, QUEUED);\n connect(&_taskManager, &TaskManager::overallStats, _mainWindow,\n &MainWindow::updateSettingsSummary, QUEUED);\n connect(_mainWindow, &MainWindow::repairCache, &_taskManager,\n &TaskManager::fsck, QUEUED);\n connect(_mainWindow, &MainWindow::settingsChanged, &_taskManager,\n &TaskManager::loadSettings, QUEUED);\n connect(_mainWindow, &MainWindow::purgeArchives, &_taskManager,\n &TaskManager::nuke, QUEUED);\n connect(_mainWindow, &MainWindow::restoreArchive, &_taskManager,\n &TaskManager::restoreArchive, QUEUED);\n connect(_mainWindow, &MainWindow::runSetupWizard, this,\n &CoreApplication::reinit, QUEUED);\n connect(_mainWindow, &MainWindow::stopTasks, &_taskManager,\n &TaskManager::stopTasks, QUEUED);\n connect(_mainWindow, &MainWindow::loadJobs, &_taskManager,\n &TaskManager::loadJobs, QUEUED);\n connect(&_taskManager, &TaskManager::jobsList, _mainWindow,\n &MainWindow::jobsList, QUEUED);\n connect(_mainWindow, &MainWindow::deleteJob, &_taskManager,\n &TaskManager::deleteJob, QUEUED);\n connect(_mainWindow, &MainWindow::getTaskInfo, &_taskManager,\n &TaskManager::getTaskInfo, QUEUED);\n connect(&_taskManager, &TaskManager::taskInfo, _mainWindow,\n &MainWindow::displayStopTasks, QUEUED);\n connect(_mainWindow, &MainWindow::jobAdded, &_taskManager,\n &TaskManager::addJob, QUEUED);\n connect(&_taskManager, &TaskManager::message, _mainWindow,\n &MainWindow::updateStatusMessage, QUEUED);\n connect(&_taskManager, &TaskManager::message, &_journal, &Journal::log,\n QUEUED);\n connect(&_taskManager, &TaskManager::error, _mainWindow,\n &MainWindow::tarsnapError, QUEUED);\n connect(&_notification, &Notification::activated, _mainWindow,\n &MainWindow::notificationRaise, QUEUED);\n connect(&_notification, &Notification::messageClicked, _mainWindow,\n &MainWindow::notificationRaise, QUEUED);\n connect(_mainWindow, &MainWindow::displayNotification, &_notification,\n &Notification::displayNotification, QUEUED);\n connect(_mainWindow, &MainWindow::logMessage, &_journal, &Journal::log,\n QUEUED);\n connect(_mainWindow, &MainWindow::getJournal, &_journal,\n &Journal::getJournal, QUEUED);\n connect(&_journal, &Journal::journal, _mainWindow,\n &MainWindow::setJournal, QUEUED);\n connect(&_journal, &Journal::logEntry, _mainWindow,\n &MainWindow::appendToJournalLog, QUEUED);\n\n QMetaObject::invokeMethod(_mainWindow, \"loadArchives\", QUEUED);\n QMetaObject::invokeMethod(_mainWindow, \"loadJobs\", QUEUED);\n QMetaObject::invokeMethod(_mainWindow, \"getJournal\", QUEUED);\n _mainWindow->show();\n}\n\nbool CoreApplication::reinit()\n{\n if(_mainWindow)\n {\n delete _mainWindow;\n _mainWindow = NULL;\n }\n\n \/\/ reset existing persistent store and app settings\n PersistentStore &store = PersistentStore::instance();\n store.purge();\n\n QSettings settings;\n settings.setDefaultFormat(QSettings::NativeFormat);\n QSettings defaultSettings;\n if(defaultSettings.contains(\"app\/wizard_done\"))\n {\n defaultSettings.clear();\n defaultSettings.sync();\n }\n\n return initialize();\n}\n<commit_msg>Send TaskManager messages to Journal always.<commit_after>#include \"coreapplication.h\"\n#include \"debug.h\"\n#include \"utils.h\"\n#include \"widgets\/setupdialog.h\"\n\n#include <QDialog>\n#include <QFontDatabase>\n#include <QMessageBox>\n\nCoreApplication::CoreApplication(int &argc, char **argv)\n : QApplication(argc, argv),\n _mainWindow(NULL),\n _notification(),\n _jobsOption(false)\n{\n qRegisterMetaType<TaskStatus>(\"TaskStatus\");\n qRegisterMetaType<QList<QUrl>>(\"QList<QUrl>\");\n qRegisterMetaType<BackupTaskPtr>(\"BackupTaskPtr\");\n qRegisterMetaType<QList<ArchivePtr>>(\"QList<ArchivePtr >\");\n qRegisterMetaType<ArchivePtr>(\"ArchivePtr\");\n qRegisterMetaType<ArchiveRestoreOptions>(\"ArchiveRestoreOptions\");\n qRegisterMetaType<QSqlQuery>(\"QSqlQuery\");\n qRegisterMetaType<JobPtr>(\"JobPtr\");\n qRegisterMetaType<QMap<QString, JobPtr>>(\"QMap<QString, JobPtr>\");\n qRegisterMetaType<QSystemTrayIcon::ActivationReason>(\"QSystemTrayIcon::ActivationReason\");\n qRegisterMetaType<TarsnapError>(\"TarsnapError\");\n\n QCoreApplication::setOrganizationName(QLatin1String(\"Tarsnap Backup Inc.\"));\n QCoreApplication::setOrganizationDomain(QLatin1String(\"tarsnap.com\"));\n QCoreApplication::setApplicationName(QLatin1String(\"Tarsnap\"));\n QCoreApplication::setApplicationVersion(APP_VERSION);\n}\n\nCoreApplication::~CoreApplication()\n{\n if(_mainWindow)\n delete _mainWindow;\n}\n\nvoid CoreApplication::parseArgs()\n{\n QCommandLineParser parser;\n parser.setApplicationDescription(QLatin1String(\"Tarsnap GUI - Online backups for the truly lazy\"));\n parser.addHelpOption();\n parser.addVersionOption();\n QCommandLineOption jobsOption(QStringList() << \"j\" << \"jobs\",\n tr(\"Executes all jobs sequentially that have the \\'Include in scheduled backups\\' option checked.\"\n \" The application runs headless and useful information is printed to standard out and error.\"));\n QCommandLineOption appDataOption(QStringList() << \"a\" << \"appdata\",\n tr(\"Use the specified app data directory.\"\n \" Useful for multiple configurations on the same machine (INI format is implied).\"),\n tr(\"directory\"));\n parser.addOption(jobsOption);\n parser.addOption(appDataOption);\n parser.process(arguments());\n _jobsOption = parser.isSet(jobsOption);\n _appDataDir = parser.value(appDataOption);\n}\n\nbool CoreApplication::initialize()\n{\n parseArgs();\n\n QSettings settings;\n\n if(!_appDataDir.isEmpty())\n {\n settings.setPath(QSettings::IniFormat, QSettings::UserScope, _appDataDir);\n settings.setDefaultFormat(QSettings::IniFormat);\n }\n\n bool wizardDone = settings.value(\"app\/wizard_done\", false).toBool();\n if(!wizardDone)\n {\n \/\/ Show the first time setup dialog\n SetupDialog wizard;\n connect(&wizard, &SetupDialog::getTarsnapVersion, &_taskManager,\n &TaskManager::getTarsnapVersion);\n connect(&_taskManager, &TaskManager::tarsnapVersion, &wizard,\n &SetupDialog::setTarsnapVersion);\n connect(&wizard, &SetupDialog::requestRegisterMachine, &_taskManager,\n &TaskManager::registerMachine);\n connect(&_taskManager, &TaskManager::registerMachineStatus, &wizard,\n &SetupDialog::registerMachineStatus);\n connect(&_taskManager, &TaskManager::idle, &wizard,\n &SetupDialog::updateLoadingAnimation);\n\n if(QDialog::Rejected == wizard.exec())\n {\n quit(); \/\/ if we're running in the loop\n return false; \/\/ if called from main\n }\n }\n\n bool iniFormat = settings.value(\"app\/ini_format\", false).toBool();\n if(iniFormat)\n {\n QString appData = settings.value(\"app\/app_data\", APPDATA).toString();\n settings.setPath(QSettings::IniFormat, QSettings::UserScope, appData);\n settings.setDefaultFormat(QSettings::IniFormat);\n }\n\n connect(&_taskManager, &TaskManager::displayNotification,\n &_notification, &Notification::displayNotification, QUEUED);\n connect(&_taskManager, &TaskManager::message, &_journal, &Journal::log,\n QUEUED);\n\n QMetaObject::invokeMethod(&_taskManager, \"loadSettings\", QUEUED);\n QMetaObject::invokeMethod(&_journal, \"load\", QUEUED);\n\n if(_jobsOption)\n {\n connect(&_notification, &Notification::activated, this,\n &CoreApplication::showMainWindow, QUEUED);\n connect(&_notification, &Notification::messageClicked, this,\n &CoreApplication::showMainWindow, QUEUED);\n _taskManager.setHeadless(true);\n QMetaObject::invokeMethod(&_taskManager, \"runScheduledJobs\", QUEUED);\n }\n else\n {\n showMainWindow();\n }\n\n return true;\n}\n\nvoid CoreApplication::showMainWindow()\n{\n if(_mainWindow != NULL)\n return;\n\n _taskManager.setHeadless(false);\n disconnect(&_notification, &Notification::activated, this,\n &CoreApplication::showMainWindow);\n disconnect(&_notification, &Notification::messageClicked, this,\n &CoreApplication::showMainWindow);\n\n _mainWindow = new MainWindow();\n Q_ASSERT(_mainWindow != NULL);\n\n connect(_mainWindow, &MainWindow::getTarsnapVersion, &_taskManager,\n &TaskManager::getTarsnapVersion, QUEUED);\n connect(&_taskManager, &TaskManager::tarsnapVersion, _mainWindow,\n &MainWindow::setTarsnapVersion, QUEUED);\n connect(_mainWindow, &MainWindow::backupNow, &_taskManager,\n &TaskManager::backupNow, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchives, &_taskManager,\n &TaskManager::loadArchives, QUEUED);\n connect(&_taskManager, &TaskManager::archiveList, _mainWindow,\n &MainWindow::archiveList, QUEUED);\n connect(_mainWindow, &MainWindow::deleteArchives, &_taskManager,\n &TaskManager::deleteArchives, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchiveStats, &_taskManager,\n &TaskManager::getArchiveStats, QUEUED);\n connect(_mainWindow, &MainWindow::loadArchiveContents, &_taskManager,\n &TaskManager::getArchiveContents, QUEUED);\n connect(&_taskManager, &TaskManager::idle, _mainWindow,\n &MainWindow::updateLoadingAnimation, QUEUED);\n connect(_mainWindow, &MainWindow::getOverallStats, &_taskManager,\n &TaskManager::getOverallStats, QUEUED);\n connect(&_taskManager, &TaskManager::overallStats, _mainWindow,\n &MainWindow::updateSettingsSummary, QUEUED);\n connect(_mainWindow, &MainWindow::repairCache, &_taskManager,\n &TaskManager::fsck, QUEUED);\n connect(_mainWindow, &MainWindow::settingsChanged, &_taskManager,\n &TaskManager::loadSettings, QUEUED);\n connect(_mainWindow, &MainWindow::purgeArchives, &_taskManager,\n &TaskManager::nuke, QUEUED);\n connect(_mainWindow, &MainWindow::restoreArchive, &_taskManager,\n &TaskManager::restoreArchive, QUEUED);\n connect(_mainWindow, &MainWindow::runSetupWizard, this,\n &CoreApplication::reinit, QUEUED);\n connect(_mainWindow, &MainWindow::stopTasks, &_taskManager,\n &TaskManager::stopTasks, QUEUED);\n connect(_mainWindow, &MainWindow::loadJobs, &_taskManager,\n &TaskManager::loadJobs, QUEUED);\n connect(&_taskManager, &TaskManager::jobsList, _mainWindow,\n &MainWindow::jobsList, QUEUED);\n connect(_mainWindow, &MainWindow::deleteJob, &_taskManager,\n &TaskManager::deleteJob, QUEUED);\n connect(_mainWindow, &MainWindow::getTaskInfo, &_taskManager,\n &TaskManager::getTaskInfo, QUEUED);\n connect(&_taskManager, &TaskManager::taskInfo, _mainWindow,\n &MainWindow::displayStopTasks, QUEUED);\n connect(_mainWindow, &MainWindow::jobAdded, &_taskManager,\n &TaskManager::addJob, QUEUED);\n connect(&_taskManager, &TaskManager::message, _mainWindow,\n &MainWindow::updateStatusMessage, QUEUED);\n connect(&_taskManager, &TaskManager::error, _mainWindow,\n &MainWindow::tarsnapError, QUEUED);\n connect(&_notification, &Notification::activated, _mainWindow,\n &MainWindow::notificationRaise, QUEUED);\n connect(&_notification, &Notification::messageClicked, _mainWindow,\n &MainWindow::notificationRaise, QUEUED);\n connect(_mainWindow, &MainWindow::displayNotification, &_notification,\n &Notification::displayNotification, QUEUED);\n connect(_mainWindow, &MainWindow::logMessage, &_journal, &Journal::log,\n QUEUED);\n connect(_mainWindow, &MainWindow::getJournal, &_journal,\n &Journal::getJournal, QUEUED);\n connect(&_journal, &Journal::journal, _mainWindow,\n &MainWindow::setJournal, QUEUED);\n connect(&_journal, &Journal::logEntry, _mainWindow,\n &MainWindow::appendToJournalLog, QUEUED);\n\n QMetaObject::invokeMethod(_mainWindow, \"loadArchives\", QUEUED);\n QMetaObject::invokeMethod(_mainWindow, \"loadJobs\", QUEUED);\n QMetaObject::invokeMethod(_mainWindow, \"getJournal\", QUEUED);\n _mainWindow->show();\n}\n\nbool CoreApplication::reinit()\n{\n if(_mainWindow)\n {\n delete _mainWindow;\n _mainWindow = NULL;\n }\n\n \/\/ reset existing persistent store and app settings\n PersistentStore &store = PersistentStore::instance();\n store.purge();\n\n QSettings settings;\n settings.setDefaultFormat(QSettings::NativeFormat);\n QSettings defaultSettings;\n if(defaultSettings.contains(\"app\/wizard_done\"))\n {\n defaultSettings.clear();\n defaultSettings.sync();\n }\n\n return initialize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright 2015-2019 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include \"board\/Board.h\"\n#include \"board\/common\/constants\/LEDs.h\"\n#include \"board\/common\/digital\/Output.h\"\n#include \"board\/common\/Map.h\"\n#include \"core\/src\/general\/BitManipulation.h\"\n#include \"Pins.h\"\n#include \"interface\/digital\/output\/leds\/Helpers.h\"\n#ifndef BOARD_A_xu2\n#include \"interface\/digital\/output\/leds\/LEDs.h\"\n#endif\n\n#ifdef LED_INDICATORS\nnamespace\n{\n \/\/\/\n \/\/\/ \\brief Variables used to control the time MIDI in\/out LED indicators on board are active.\n \/\/\/ When these LEDs need to be turned on, variables are set to value representing time in\n \/\/\/ milliseconds during which they should be on. ISR decreases variable value by 1 every 1 millsecond.\n \/\/\/ Once the variables have value 0, specific LED indicator is turned off.\n \/\/\/ @{\n\n volatile uint8_t midiIn_timeout;\n volatile uint8_t midiOut_timeout;\n\n \/\/\/ @}\n} \/\/ namespace\n#endif\n\n#ifndef BOARD_A_xu2\nnamespace\n{\n volatile uint8_t pwmSteps;\n volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS];\n\n \/\/\/\n \/\/\/ \\brief Array holding values needed to achieve more natural LED transition between states.\n \/\/\/\n const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = {\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 16,\n 17,\n 19,\n 21,\n 23,\n 25,\n 28,\n 30,\n 33,\n 36,\n 40,\n 44,\n 48,\n 52,\n 57,\n 62,\n 68,\n 74,\n 81,\n 89,\n 97,\n 106,\n 115,\n 126,\n 138,\n 150,\n 164,\n 179,\n 195,\n 213,\n 255\n };\n\n#ifdef NUMBER_OF_LED_COLUMNS\n \/\/\/\n \/\/\/ \\brief Holds value of currently active output matrix column.\n \/\/\/\n volatile uint8_t activeOutColumn;\n#endif\n} \/\/ namespace\n#endif\n\nnamespace Board\n{\n namespace interface\n {\n namespace digital\n {\n namespace output\n {\n#ifndef BOARD_A_xu2\n#ifdef LEDS_SUPPORTED\n bool setLEDfadeSpeed(uint8_t transitionSpeed)\n {\n if (transitionSpeed > FADE_TIME_MAX)\n {\n return false;\n }\n\n\/\/reset transition counter\n#ifdef __AVR__\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n#endif\n {\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n transitionCounter[i] = 0;\n\n pwmSteps = transitionSpeed;\n }\n\n return true;\n }\n\n uint8_t getRGBaddress(uint8_t rgbID, Interface::digital::output::LEDs::rgbIndex_t index)\n {\n#ifdef NUMBER_OF_LED_COLUMNS\n uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS;\n uint8_t row = (rgbID \/ NUMBER_OF_LED_COLUMNS) * 3;\n uint8_t address = column + NUMBER_OF_LED_COLUMNS * row;\n\n switch (index)\n {\n case Interface::digital::output::LEDs::rgbIndex_t::r:\n return address;\n\n case Interface::digital::output::LEDs::rgbIndex_t::g:\n return address + NUMBER_OF_LED_COLUMNS * 1;\n\n case Interface::digital::output::LEDs::rgbIndex_t::b:\n return address + NUMBER_OF_LED_COLUMNS * 2;\n }\n\n return 0;\n#else\n return rgbID * 3 + static_cast<uint8_t>(index);\n#endif\n }\n\n uint8_t getRGBID(uint8_t ledID)\n {\n#ifdef NUMBER_OF_LED_COLUMNS\n uint8_t row = ledID \/ NUMBER_OF_LED_COLUMNS;\n\n uint8_t mod = row % 3;\n row -= mod;\n\n uint8_t column = ledID % NUMBER_OF_LED_COLUMNS;\n\n uint8_t result = (row * NUMBER_OF_LED_COLUMNS) \/ 3 + column;\n\n if (result >= MAX_NUMBER_OF_RGB_LEDS)\n return MAX_NUMBER_OF_RGB_LEDS - 1;\n else\n return result;\n#else\n uint8_t result = ledID \/ 3;\n\n if (result >= MAX_NUMBER_OF_RGB_LEDS)\n return MAX_NUMBER_OF_RGB_LEDS - 1;\n else\n return result;\n#endif\n }\n#endif\n#endif\n\n namespace detail\n {\n#ifdef LED_INDICATORS\n void checkIndicators()\n {\n if (Board::USB::trafficIndicator.received || Board::UART::trafficIndicator.received)\n {\n INT_LED_ON(LED_IN_PORT, LED_IN_PIN);\n Board::USB::trafficIndicator.received = false;\n Board::UART::trafficIndicator.received = false;\n midiIn_timeout = MIDI_INDICATOR_TIMEOUT;\n }\n\n if (midiIn_timeout)\n midiIn_timeout--;\n else\n INT_LED_OFF(LED_IN_PORT, LED_IN_PIN);\n\n if (Board::USB::trafficIndicator.sent || Board::UART::trafficIndicator.sent)\n {\n INT_LED_ON(LED_OUT_PORT, LED_OUT_PIN);\n Board::USB::trafficIndicator.sent = false;\n Board::UART::trafficIndicator.sent = false;\n midiOut_timeout = MIDI_INDICATOR_TIMEOUT;\n }\n\n if (midiOut_timeout)\n midiOut_timeout--;\n else\n INT_LED_OFF(LED_OUT_PORT, LED_OUT_PIN);\n }\n#endif\n\n#ifndef BOARD_A_xu2\n#ifdef NUMBER_OF_LED_COLUMNS\n \/\/\/\n \/\/\/ \\brief Switches to next LED matrix column.\n \/\/\/\n inline void activateOutputColumn()\n {\n BIT_READ(activeOutColumn, 0) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN);\n BIT_READ(activeOutColumn, 1) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN);\n BIT_READ(activeOutColumn, 2) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN);\n }\n\n namespace\n {\n core::CORE_ARCH::pins::mcuPin_t pin;\n uint8_t ledNumber;\n uint8_t ledStateSingle;\n } \/\/ namespace\n\n \/\/\/\n \/\/\/ \\brief Used to turn the given LED row off.\n \/\/\/\n inline void ledRowOff(uint8_t row)\n {\n#ifdef LED_FADING\n \/\/turn off pwm\n core::CORE_ARCH::pins::pwmOff(Board::map::pwmChannel(row));\n#endif\n\n pin = Board::map::led(row);\n EXT_LED_OFF(*pin.port, pin.pin);\n }\n\n \/\/\/\n \/\/\/ \\brief Used to turn the given LED row on.\n \/\/\/ If led fading is supported on board, intensity must be specified as well.\n \/\/\/\n inline void ledRowOn(uint8_t row\n#ifdef LED_FADING\n ,\n uint8_t intensity\n#endif\n )\n {\n#ifdef LED_FADING\n if (intensity == 255)\n#endif\n {\n pin = Board::map::led(row);\n\n \/\/max value, don't use pwm\n EXT_LED_ON(*pin.port, pin.pin);\n }\n#ifdef LED_FADING\n else\n {\n#ifdef LED_EXT_INVERT\n intensity = 255 - intensity;\n#endif\n\n core::CORE_ARCH::pins::pwmOn(Board::map::pwmChannel(row), intensity);\n }\n#endif\n }\n\n void checkDigitalOutputs()\n {\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n ledRowOff(i);\n\n activateOutputColumn();\n\n \/\/if there is an active LED in current column, turn on LED row\n \/\/do fancy transitions here\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n {\n ledNumber = activeOutColumn + i * NUMBER_OF_LED_COLUMNS;\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(ledNumber));\n\n ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS - 1);\n\n \/\/don't bother with pwm if it's disabled\n if (!pwmSteps && ledStateSingle)\n {\n ledRowOn(i\n#ifdef LED_FADING\n ,\n 255\n#endif\n );\n }\n else\n {\n if (ledTransitionScale[transitionCounter[ledNumber]])\n ledRowOn(i\n#ifdef LED_FADING\n ,\n ledTransitionScale[transitionCounter[ledNumber]]\n#endif\n );\n\n if (transitionCounter[ledNumber] != ledStateSingle)\n {\n \/\/fade up\n if (transitionCounter[ledNumber] < ledStateSingle)\n {\n transitionCounter[ledNumber] += pwmSteps;\n\n if (transitionCounter[ledNumber] > ledStateSingle)\n transitionCounter[ledNumber] = ledStateSingle;\n }\n else\n {\n \/\/fade down\n transitionCounter[ledNumber] -= pwmSteps;\n\n if (transitionCounter[ledNumber] < 0)\n transitionCounter[ledNumber] = 0;\n }\n }\n }\n }\n\n if (++activeOutColumn == NUMBER_OF_LED_COLUMNS)\n activeOutColumn = 0;\n }\n#else\n namespace\n {\n uint8_t lastLEDstate[MAX_NUMBER_OF_LEDS];\n uint8_t ledStateSingle;\n } \/\/ namespace\n\n#ifdef NUMBER_OF_OUT_SR\n \/\/\/\n \/\/\/ \\brief Checks if any LED state has been changed and writes changed state to output shift registers.\n \/\/\/\n void checkDigitalOutputs()\n {\n bool updateSR = false;\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i));\n\n if (ledStateSingle != lastLEDstate[i])\n {\n lastLEDstate[i] = ledStateSingle;\n updateSR = true;\n }\n }\n\n if (updateSR)\n {\n CORE_AVR_PIN_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n LED_ON(Interface::digital::output::LEDs::getLEDstate(i)) ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);\n CORE_AVR_PIN_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n _NOP();\n _NOP();\n CORE_AVR_PIN_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n }\n\n CORE_AVR_PIN_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n }\n }\n#else\n namespace\n {\n core::CORE_ARCH::pins::mcuPin_t pin;\n }\n\n void checkDigitalOutputs()\n {\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i));\n pin = Board::map::led(i);\n\n if (ledStateSingle != lastLEDstate[i])\n {\n if (ledStateSingle)\n EXT_LED_ON(*pin.port, pin.pin);\n else\n EXT_LED_OFF(*pin.port, pin.pin);\n\n lastLEDstate[i] = ledStateSingle;\n }\n }\n }\n#endif\n#endif\n#endif\n } \/\/ namespace detail\n } \/\/ namespace output\n } \/\/ namespace digital\n } \/\/ namespace interface\n} \/\/ namespace Board<commit_msg>fix 74HC595 handling<commit_after>\/*\n\nCopyright 2015-2019 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include \"board\/Board.h\"\n#include \"board\/common\/constants\/LEDs.h\"\n#include \"board\/common\/digital\/Output.h\"\n#include \"board\/common\/Map.h\"\n#include \"core\/src\/general\/BitManipulation.h\"\n#include \"Pins.h\"\n#include \"interface\/digital\/output\/leds\/Helpers.h\"\n#ifndef BOARD_A_xu2\n#include \"interface\/digital\/output\/leds\/LEDs.h\"\n#endif\n\n#ifdef LED_INDICATORS\nnamespace\n{\n \/\/\/\n \/\/\/ \\brief Variables used to control the time MIDI in\/out LED indicators on board are active.\n \/\/\/ When these LEDs need to be turned on, variables are set to value representing time in\n \/\/\/ milliseconds during which they should be on. ISR decreases variable value by 1 every 1 millsecond.\n \/\/\/ Once the variables have value 0, specific LED indicator is turned off.\n \/\/\/ @{\n\n volatile uint8_t midiIn_timeout;\n volatile uint8_t midiOut_timeout;\n\n \/\/\/ @}\n} \/\/ namespace\n#endif\n\n#ifndef BOARD_A_xu2\nnamespace\n{\n volatile uint8_t pwmSteps;\n volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS];\n\n \/\/\/\n \/\/\/ \\brief Array holding values needed to achieve more natural LED transition between states.\n \/\/\/\n const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = {\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 16,\n 17,\n 19,\n 21,\n 23,\n 25,\n 28,\n 30,\n 33,\n 36,\n 40,\n 44,\n 48,\n 52,\n 57,\n 62,\n 68,\n 74,\n 81,\n 89,\n 97,\n 106,\n 115,\n 126,\n 138,\n 150,\n 164,\n 179,\n 195,\n 213,\n 255\n };\n\n#ifdef NUMBER_OF_LED_COLUMNS\n \/\/\/\n \/\/\/ \\brief Holds value of currently active output matrix column.\n \/\/\/\n volatile uint8_t activeOutColumn;\n#endif\n} \/\/ namespace\n#endif\n\nnamespace Board\n{\n namespace interface\n {\n namespace digital\n {\n namespace output\n {\n#ifndef BOARD_A_xu2\n#ifdef LEDS_SUPPORTED\n bool setLEDfadeSpeed(uint8_t transitionSpeed)\n {\n if (transitionSpeed > FADE_TIME_MAX)\n {\n return false;\n }\n\n\/\/reset transition counter\n#ifdef __AVR__\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n#endif\n {\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n transitionCounter[i] = 0;\n\n pwmSteps = transitionSpeed;\n }\n\n return true;\n }\n\n uint8_t getRGBaddress(uint8_t rgbID, Interface::digital::output::LEDs::rgbIndex_t index)\n {\n#ifdef NUMBER_OF_LED_COLUMNS\n uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS;\n uint8_t row = (rgbID \/ NUMBER_OF_LED_COLUMNS) * 3;\n uint8_t address = column + NUMBER_OF_LED_COLUMNS * row;\n\n switch (index)\n {\n case Interface::digital::output::LEDs::rgbIndex_t::r:\n return address;\n\n case Interface::digital::output::LEDs::rgbIndex_t::g:\n return address + NUMBER_OF_LED_COLUMNS * 1;\n\n case Interface::digital::output::LEDs::rgbIndex_t::b:\n return address + NUMBER_OF_LED_COLUMNS * 2;\n }\n\n return 0;\n#else\n return rgbID * 3 + static_cast<uint8_t>(index);\n#endif\n }\n\n uint8_t getRGBID(uint8_t ledID)\n {\n#ifdef NUMBER_OF_LED_COLUMNS\n uint8_t row = ledID \/ NUMBER_OF_LED_COLUMNS;\n\n uint8_t mod = row % 3;\n row -= mod;\n\n uint8_t column = ledID % NUMBER_OF_LED_COLUMNS;\n\n uint8_t result = (row * NUMBER_OF_LED_COLUMNS) \/ 3 + column;\n\n if (result >= MAX_NUMBER_OF_RGB_LEDS)\n return MAX_NUMBER_OF_RGB_LEDS - 1;\n else\n return result;\n#else\n uint8_t result = ledID \/ 3;\n\n if (result >= MAX_NUMBER_OF_RGB_LEDS)\n return MAX_NUMBER_OF_RGB_LEDS - 1;\n else\n return result;\n#endif\n }\n#endif\n#endif\n\n namespace detail\n {\n#ifdef LED_INDICATORS\n void checkIndicators()\n {\n if (Board::USB::trafficIndicator.received || Board::UART::trafficIndicator.received)\n {\n INT_LED_ON(LED_IN_PORT, LED_IN_PIN);\n Board::USB::trafficIndicator.received = false;\n Board::UART::trafficIndicator.received = false;\n midiIn_timeout = MIDI_INDICATOR_TIMEOUT;\n }\n\n if (midiIn_timeout)\n midiIn_timeout--;\n else\n INT_LED_OFF(LED_IN_PORT, LED_IN_PIN);\n\n if (Board::USB::trafficIndicator.sent || Board::UART::trafficIndicator.sent)\n {\n INT_LED_ON(LED_OUT_PORT, LED_OUT_PIN);\n Board::USB::trafficIndicator.sent = false;\n Board::UART::trafficIndicator.sent = false;\n midiOut_timeout = MIDI_INDICATOR_TIMEOUT;\n }\n\n if (midiOut_timeout)\n midiOut_timeout--;\n else\n INT_LED_OFF(LED_OUT_PORT, LED_OUT_PIN);\n }\n#endif\n\n#ifndef BOARD_A_xu2\n#ifdef NUMBER_OF_LED_COLUMNS\n \/\/\/\n \/\/\/ \\brief Switches to next LED matrix column.\n \/\/\/\n inline void activateOutputColumn()\n {\n BIT_READ(activeOutColumn, 0) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN);\n BIT_READ(activeOutColumn, 1) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN);\n BIT_READ(activeOutColumn, 2) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN);\n }\n\n namespace\n {\n core::CORE_ARCH::pins::mcuPin_t pin;\n uint8_t ledNumber;\n uint8_t ledStateSingle;\n } \/\/ namespace\n\n \/\/\/\n \/\/\/ \\brief Used to turn the given LED row off.\n \/\/\/\n inline void ledRowOff(uint8_t row)\n {\n#ifdef LED_FADING\n \/\/turn off pwm\n core::CORE_ARCH::pins::pwmOff(Board::map::pwmChannel(row));\n#endif\n\n pin = Board::map::led(row);\n EXT_LED_OFF(*pin.port, pin.pin);\n }\n\n \/\/\/\n \/\/\/ \\brief Used to turn the given LED row on.\n \/\/\/ If led fading is supported on board, intensity must be specified as well.\n \/\/\/\n inline void ledRowOn(uint8_t row\n#ifdef LED_FADING\n ,\n uint8_t intensity\n#endif\n )\n {\n#ifdef LED_FADING\n if (intensity == 255)\n#endif\n {\n pin = Board::map::led(row);\n\n \/\/max value, don't use pwm\n EXT_LED_ON(*pin.port, pin.pin);\n }\n#ifdef LED_FADING\n else\n {\n#ifdef LED_EXT_INVERT\n intensity = 255 - intensity;\n#endif\n\n core::CORE_ARCH::pins::pwmOn(Board::map::pwmChannel(row), intensity);\n }\n#endif\n }\n\n void checkDigitalOutputs()\n {\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n ledRowOff(i);\n\n activateOutputColumn();\n\n \/\/if there is an active LED in current column, turn on LED row\n \/\/do fancy transitions here\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n {\n ledNumber = activeOutColumn + i * NUMBER_OF_LED_COLUMNS;\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(ledNumber));\n\n ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS - 1);\n\n \/\/don't bother with pwm if it's disabled\n if (!pwmSteps && ledStateSingle)\n {\n ledRowOn(i\n#ifdef LED_FADING\n ,\n 255\n#endif\n );\n }\n else\n {\n if (ledTransitionScale[transitionCounter[ledNumber]])\n ledRowOn(i\n#ifdef LED_FADING\n ,\n ledTransitionScale[transitionCounter[ledNumber]]\n#endif\n );\n\n if (transitionCounter[ledNumber] != ledStateSingle)\n {\n \/\/fade up\n if (transitionCounter[ledNumber] < ledStateSingle)\n {\n transitionCounter[ledNumber] += pwmSteps;\n\n if (transitionCounter[ledNumber] > ledStateSingle)\n transitionCounter[ledNumber] = ledStateSingle;\n }\n else\n {\n \/\/fade down\n transitionCounter[ledNumber] -= pwmSteps;\n\n if (transitionCounter[ledNumber] < 0)\n transitionCounter[ledNumber] = 0;\n }\n }\n }\n }\n\n if (++activeOutColumn == NUMBER_OF_LED_COLUMNS)\n activeOutColumn = 0;\n }\n#else\n namespace\n {\n uint8_t lastLEDstate[MAX_NUMBER_OF_LEDS];\n uint8_t ledStateSingle;\n } \/\/ namespace\n\n#ifdef NUMBER_OF_OUT_SR\n \/\/\/\n \/\/\/ \\brief Checks if any LED state has been changed and writes changed state to output shift registers.\n \/\/\/\n void checkDigitalOutputs()\n {\n bool updateSR = false;\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i));\n\n if (ledStateSingle != lastLEDstate[i])\n {\n lastLEDstate[i] = ledStateSingle;\n updateSR = true;\n }\n }\n\n if (updateSR)\n {\n CORE_AVR_PIN_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n LED_ON(Interface::digital::output::LEDs::getLEDstate(i)) ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);\n CORE_AVR_PIN_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n _NOP();\n _NOP();\n CORE_AVR_PIN_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n }\n\n CORE_AVR_PIN_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n }\n }\n#else\n namespace\n {\n core::CORE_ARCH::pins::mcuPin_t pin;\n }\n\n void checkDigitalOutputs()\n {\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i));\n pin = Board::map::led(i);\n\n if (ledStateSingle != lastLEDstate[i])\n {\n if (ledStateSingle)\n EXT_LED_ON(*pin.port, pin.pin);\n else\n EXT_LED_OFF(*pin.port, pin.pin);\n\n lastLEDstate[i] = ledStateSingle;\n }\n }\n }\n#endif\n#endif\n#endif\n } \/\/ namespace detail\n } \/\/ namespace output\n } \/\/ namespace digital\n } \/\/ namespace interface\n} \/\/ namespace Board<|endoftext|>"} {"text":"<commit_before>#include \"arma3client.hpp\"\n\n#include <algorithm>\n#include <filesystem>\n#include <string>\n\n#include <fmt\/format.h>\n#include <fmt\/ostream.h>\n\n#include <static_todo.hpp>\n\n#include \"cppfilter.hpp\"\n#include \"filesystem_utils.hpp\"\n#include \"steam_utils.hpp\"\n#include \"std_utils.hpp\"\n#include \"string_utils.hpp\"\n\n#include \"exceptions\/directory_not_found.hpp\"\n#include \"exceptions\/file_no_access.hpp\"\n#include \"exceptions\/file_not_found.hpp\"\n#include \"exceptions\/not_a_symlink.hpp\"\n#include \"exceptions\/syntax_error.hpp\"\n\nusing namespace std;\nusing namespace std::filesystem;\n\nusing namespace StdUtils;\nusing namespace StringUtils;\n\nnamespace fs = FilesystemUtils;\n\n#ifdef __linux\nnamespace\n{\n std::string get_esync_prefix(bool disable_esync)\n {\n if (disable_esync)\n return \"PROTON_NO_ESYNC=1\";\n return \"\";\n }\n\n std::string optional_steam_runtime(SteamUtils const &steam_utils)\n {\n if (StdUtils::IsLibraryAvailable(\"libpng12.so\"))\n return \"\";\n auto const steam_runtime_path = steam_utils.GetSteamPath() \/ \"ubuntu12_32\/steam-runtime\/run.sh\";\n if (fs::Exists(steam_runtime_path))\n return steam_runtime_path;\n fmt::print(stderr, \"Did not find {} and libpng12.so is missing. Thermal optics will be broken!\\n\", steam_runtime_path);\n return \"\";\n }\n\n std::string get_verb(std::string const &arguments)\n {\n return StringUtils::Replace(arguments, \"%verb%\", \"run\");;\n }\n\n void direct_launch(std::filesystem::path const &arma_path, std::filesystem::path const &executable_path,\n string const &arguments, bool is_proton, string const &user_environment_variables, bool disable_esync)\n {\n if (!is_proton)\n {\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} {} {}\", user_environment_variables, executable_path, arguments),\n arma_path.string());\n return;\n }\n\n try\n {\n SteamUtils steam_utils;\n auto const arma3_id = std::stoull(ARMA3::Definitions::app_id);\n auto const compatibility_tool = steam_utils.GetCompatibilityToolForAppId(arma3_id);\n\n auto ld_preload_path = fmt::format(\"{}\/ubuntu12_64\/gameoverlayrenderer.so\", steam_utils.GetSteamPath().string());\n if (char const *old_ld_preload = getenv(\"LD_PRELOAD\"); old_ld_preload)\n ld_preload_path = fmt::format(\"{}:{}\", ld_preload_path, old_ld_preload);\n\n auto const steam_compat_data_path = steam_utils.GetInstallPathFromGamePath(arma_path) \/ \"steamapps\/compatdata\" \/\n ARMA3::Definitions::app_id;\n\n auto const environment = fmt::format(R\"env({} SteamGameId={} LD_PRELOAD={} STEAM_COMPAT_DATA_PATH=\"{}\")env\",\n get_esync_prefix(disable_esync), arma3_id, ld_preload_path, steam_compat_data_path.string());\n auto const command = fmt::format(R\"command(env {} {} {} {} {} \"{}\" {})command\", environment, user_environment_variables,\n optional_steam_runtime(steam_utils), compatibility_tool.first,\n get_verb(compatibility_tool.second), executable_path.string(), arguments);\n fmt::print(\"Running Arma:\\n{}\\n\", command);\n StdUtils::StartBackgroundProcess(command, arma_path.string());\n }\n catch (std::exception const &e)\n {\n fmt::print(stderr, \"Direct launch failed, exception: {}\\n\", e.what());\n }\n }\n\n void indirect_flatpak_launch(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync)\n {\n if (is_proton)\n StdUtils::StartBackgroundProcess(\n fmt::format(\"flatpak run --env=\\\"{} {}\\\" com.valvesoftware.Steam -applaunch 107410 -nolauncher {}\",\n get_esync_prefix(disable_esync), user_environment_variables, arguments));\n else\n StdUtils::StartBackgroundProcess(fmt::format(\"flatpak run com.valvesoftware.Steam -applaunch 107410 -nolauncher {}\",\n arguments));\n }\n\n void indirect_launch(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync)\n {\n if (is_proton)\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} {} steam -applaunch 107410 -nolauncher {}\",\n get_esync_prefix(disable_esync), user_environment_variables, arguments));\n else\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} steam -applaunch 107410 {}\", user_environment_variables,\n arguments));\n }\n\n void indirect_launch_through_steam(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync, bool is_flatpak)\n {\n if (is_flatpak)\n indirect_flatpak_launch(arguments, is_proton, user_environment_variables, disable_esync);\n else\n indirect_launch(arguments, is_proton, user_environment_variables, disable_esync);\n }\n}\n#endif\n\nnamespace ARMA3\n{\n Client::Client(std::filesystem::path const &arma_path, std::filesystem::path const &target_workshop_path)\n {\n path_ = arma_path;\n for (auto const &executable : Definitions::executable_names)\n {\n if (fs::Exists(path_ \/ executable))\n {\n path_executable_ = path_ \/ executable;\n break;\n }\n }\n if (path_executable_.empty())\n throw FileNotFoundException(\"arma3.exe\");\n path_workshop_target_ = target_workshop_path;\n }\n\n void Client::CreateArmaCfg(vector<path> const &mod_paths, path cfg_path)\n {\n if (cfg_path.empty())\n cfg_path = GetCfgPath();\n if (!fs::Exists(cfg_path))\n {\n if (!fs::Exists(cfg_path.parent_path()))\n fs::CreateDirectories(cfg_path.parent_path());\n StdUtils::CreateFile(cfg_path);\n }\n std::string existing_config = FileReadAllText(cfg_path);\n\n CppFilter cpp_filter{existing_config};\n auto stripped_config = cpp_filter.RemoveClass(\"class ModLauncherList\");\n stripped_config += R\"cpp(class ModLauncherList\n{\n)cpp\";\n\n int mod_number = 1;\n for (auto const& mod_path : mod_paths)\n stripped_config += GenerateCfgCppForMod(mod_path, mod_number++);\n\n stripped_config += \"};\\n\";\n\n FileWriteAllText(cfg_path, stripped_config);\n }\n\n bool Client::IsProton()\n {\n return path_executable_.filename() == \"arma3_x64.exe\";\n }\n\n void Client::Start(string const &arguments, string const& user_environment_variables, bool launch_directly, bool disable_esync)\n {\n #ifdef __linux\n if (launch_directly)\n direct_launch(GetPath(), GetPathExecutable(), arguments, IsProton(), user_environment_variables, disable_esync);\n else\n indirect_launch_through_steam(arguments, IsProton(), user_environment_variables, disable_esync, IsFlatpak());\n #else\n (void)disable_esync; \/\/ esync does not apply on Mac OS X\n if (launch_directly)\n {\n try\n {\n SteamUtils steam_utils;\n auto ld_preload_path = fmt::format(\"{}\/Steam.AppBundle\/Steam\/Contents\/MacOS\/gameoverlayrenderer.dylib\", steam_utils.GetSteamPath().string());\n if (char const *old_ld_preload = getenv(\"DYLD_INSERT_LIBRARIES\"); old_ld_preload)\n ld_preload_path += fmt::format(\"{}:{}\", ld_preload_path, old_ld_preload);\n auto const environment = fmt::format(R\"env(DYLD_INSERT_LIBRARIES=\"{}\")env\", ld_preload_path);\n auto const command = fmt::format(R\"command(env {} {} \"{}\/Contents\/MacOS\/ArmA3\" {})command\", environment, user_environment_variables, GetPathExecutable().string(), arguments);\n fmt::print(\"Running Arma:\\n{}\\n\", command);\n StdUtils::StartBackgroundProcess(command, GetPath().string());\n }\n catch (std::exception const& e)\n {\n fmt::print(stderr, \"Direct launch failed, exception: {}\\n\", e.what());\n }\n }\n else\n {\n std::string launch_command = fmt::format(\"env {} open steam:\/\/run\/107410\/\/\" + StringUtils::Replace(arguments, \" \", \"%20\"), user_environment_variables);\n StdUtils::StartBackgroundProcess(launch_command);\n }\n #endif\n }\n\n std::vector<Mod> Client::GetHomeMods()\n {\n return GetModsFromDirectory(GetPath());\n }\n\n std::vector<Mod> Client::GetWorkshopMods()\n {\n return GetModsFromDirectory(GetPathWorkshop());\n }\n\n std::filesystem::path Client::GetCfgPath()\n {\n if (IsProton())\n return GetPath() \/ Definitions::proton_config_relative_path;\n else if (IsFlatpak())\n return std::filesystem::path(Definitions::home_directory)\n \/ Definitions::flatpak_prefix\n \/ Definitions::local_share_prefix\n \/ Definitions::bohemia_interactive_prefix\n \/ Definitions::game_config_path;\n else\n return std::filesystem::path(Definitions::home_directory)\n \/ Definitions::local_share_prefix\n \/ Definitions::bohemia_interactive_prefix\n \/ Definitions::game_config_path;\n }\n\n char Client::GetFakeDriveLetter()\n {\n return IsProton() ? 'Z' : 'C';\n }\n\n string Client::GenerateCfgCppForMod(path const &mod_path, int mod_index)\n {\n constexpr char const *mod_template =\n R\"cpp( class Mod{}\n {{\n dir=\"{}\";\n name=\"{}\";\n origin=\"GAME DIR\";\n fullPath=\"{}\";\n }};\n)cpp\";\n\n Mod mod(mod_path);\n path mod_path_absolute = trim(mod.path_.string(), \"\\\"\");\n path final_path = StringUtils::ToWindowsPath(mod_path_absolute, GetFakeDriveLetter());\n path dir = trim(mod_path_absolute.filename().string(), \"\\\"\");\n auto name = mod.GetValueOrReturnDefault(dir, \"name\", \"dir\", \"tooltip\", \"name_read_failed\");\n name = StringUtils::Replace(name, \"\\\"\", \"_\");\n\n return fmt::format(mod_template, mod_index, dir.string(), name, final_path.string());\n }\n\n bool Client::IsFlatpak()\n {\n#ifdef __linux\n try\n {\n SteamUtils steam_utils;\n return steam_utils.IsFlatpak();\n }\n catch (std::exception const &e)\n {\n fmt::print(stderr, \"Exception trying to determine if Flatpak, exception text: {}\\n\", e.what());\n return false;\n }\n#else\n return false;\n#endif\n }\n\n std::filesystem::path const &Client::GetPath()\n {\n return path_;\n }\n\n std::filesystem::path const &Client::GetPathExecutable()\n {\n return path_executable_;\n }\n\n std::filesystem::path const &Client::GetPathWorkshop()\n {\n return path_workshop_target_;\n }\n\n std::vector<Mod> Client::GetModsFromDirectory(path const &dir)\n {\n std::vector<Mod> ret;\n\n for (auto const &ent : fs::Ls(dir))\n {\n if (StdUtils::Contains(Definitions::exclusions, ent))\n continue;\n\n std::filesystem::path mod_dir = dir \/ ent;\n if (!fs::IsDirectory(mod_dir))\n continue;\n if (!StdUtils::Contains(fs::Ls(mod_dir, true), \"addons\"))\n continue;\n\n ret.emplace_back(mod_dir);\n }\n\n std::sort(ret.begin(), ret.end(), [](Mod const & m1, Mod const & m2)\n {\n return m1.GetValueOrReturnDefault(\"name\", \"dir\", StringUtils::Lowercase(m1.path_)) < m2.GetValueOrReturnDefault(\"name\", \"dir\", StringUtils::Lowercase(m2.path_));\n });\n\n return ret;\n }\n}\n<commit_msg>arma3client: print config before writing it to disk<commit_after>#include \"arma3client.hpp\"\n\n#include <algorithm>\n#include <filesystem>\n#include <string>\n\n#include <fmt\/format.h>\n#include <fmt\/ostream.h>\n\n#include <static_todo.hpp>\n\n#include \"cppfilter.hpp\"\n#include \"filesystem_utils.hpp\"\n#include \"steam_utils.hpp\"\n#include \"std_utils.hpp\"\n#include \"string_utils.hpp\"\n\n#include \"exceptions\/directory_not_found.hpp\"\n#include \"exceptions\/file_no_access.hpp\"\n#include \"exceptions\/file_not_found.hpp\"\n#include \"exceptions\/not_a_symlink.hpp\"\n#include \"exceptions\/syntax_error.hpp\"\n\nusing namespace std;\nusing namespace std::filesystem;\n\nusing namespace StdUtils;\nusing namespace StringUtils;\n\nnamespace fs = FilesystemUtils;\n\n#ifdef __linux\nnamespace\n{\n std::string get_esync_prefix(bool disable_esync)\n {\n if (disable_esync)\n return \"PROTON_NO_ESYNC=1\";\n return \"\";\n }\n\n std::string optional_steam_runtime(SteamUtils const &steam_utils)\n {\n if (StdUtils::IsLibraryAvailable(\"libpng12.so\"))\n return \"\";\n auto const steam_runtime_path = steam_utils.GetSteamPath() \/ \"ubuntu12_32\/steam-runtime\/run.sh\";\n if (fs::Exists(steam_runtime_path))\n return steam_runtime_path;\n fmt::print(stderr, \"Did not find {} and libpng12.so is missing. Thermal optics will be broken!\\n\", steam_runtime_path);\n return \"\";\n }\n\n std::string get_verb(std::string const &arguments)\n {\n return StringUtils::Replace(arguments, \"%verb%\", \"run\");;\n }\n\n void direct_launch(std::filesystem::path const &arma_path, std::filesystem::path const &executable_path,\n string const &arguments, bool is_proton, string const &user_environment_variables, bool disable_esync)\n {\n if (!is_proton)\n {\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} {} {}\", user_environment_variables, executable_path, arguments),\n arma_path.string());\n return;\n }\n\n try\n {\n SteamUtils steam_utils;\n auto const arma3_id = std::stoull(ARMA3::Definitions::app_id);\n auto const compatibility_tool = steam_utils.GetCompatibilityToolForAppId(arma3_id);\n\n auto ld_preload_path = fmt::format(\"{}\/ubuntu12_64\/gameoverlayrenderer.so\", steam_utils.GetSteamPath().string());\n if (char const *old_ld_preload = getenv(\"LD_PRELOAD\"); old_ld_preload)\n ld_preload_path = fmt::format(\"{}:{}\", ld_preload_path, old_ld_preload);\n\n auto const steam_compat_data_path = steam_utils.GetInstallPathFromGamePath(arma_path) \/ \"steamapps\/compatdata\" \/\n ARMA3::Definitions::app_id;\n\n auto const environment = fmt::format(R\"env({} SteamGameId={} LD_PRELOAD={} STEAM_COMPAT_DATA_PATH=\"{}\")env\",\n get_esync_prefix(disable_esync), arma3_id, ld_preload_path, steam_compat_data_path.string());\n auto const command = fmt::format(R\"command(env {} {} {} {} {} \"{}\" {})command\", environment, user_environment_variables,\n optional_steam_runtime(steam_utils), compatibility_tool.first,\n get_verb(compatibility_tool.second), executable_path.string(), arguments);\n fmt::print(\"Running Arma:\\n{}\\n\", command);\n StdUtils::StartBackgroundProcess(command, arma_path.string());\n }\n catch (std::exception const &e)\n {\n fmt::print(stderr, \"Direct launch failed, exception: {}\\n\", e.what());\n }\n }\n\n void indirect_flatpak_launch(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync)\n {\n if (is_proton)\n StdUtils::StartBackgroundProcess(\n fmt::format(\"flatpak run --env=\\\"{} {}\\\" com.valvesoftware.Steam -applaunch 107410 -nolauncher {}\",\n get_esync_prefix(disable_esync), user_environment_variables, arguments));\n else\n StdUtils::StartBackgroundProcess(fmt::format(\"flatpak run com.valvesoftware.Steam -applaunch 107410 -nolauncher {}\",\n arguments));\n }\n\n void indirect_launch(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync)\n {\n if (is_proton)\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} {} steam -applaunch 107410 -nolauncher {}\",\n get_esync_prefix(disable_esync), user_environment_variables, arguments));\n else\n StdUtils::StartBackgroundProcess(fmt::format(\"env {} steam -applaunch 107410 {}\", user_environment_variables,\n arguments));\n }\n\n void indirect_launch_through_steam(string const &arguments, bool is_proton, string const &user_environment_variables,\n bool disable_esync, bool is_flatpak)\n {\n if (is_flatpak)\n indirect_flatpak_launch(arguments, is_proton, user_environment_variables, disable_esync);\n else\n indirect_launch(arguments, is_proton, user_environment_variables, disable_esync);\n }\n}\n#endif\n\nnamespace ARMA3\n{\n Client::Client(std::filesystem::path const &arma_path, std::filesystem::path const &target_workshop_path)\n {\n path_ = arma_path;\n for (auto const &executable : Definitions::executable_names)\n {\n if (fs::Exists(path_ \/ executable))\n {\n path_executable_ = path_ \/ executable;\n break;\n }\n }\n if (path_executable_.empty())\n throw FileNotFoundException(\"arma3.exe\");\n path_workshop_target_ = target_workshop_path;\n }\n\n void Client::CreateArmaCfg(vector<path> const &mod_paths, path cfg_path)\n {\n if (cfg_path.empty())\n cfg_path = GetCfgPath();\n if (!fs::Exists(cfg_path))\n {\n if (!fs::Exists(cfg_path.parent_path()))\n fs::CreateDirectories(cfg_path.parent_path());\n StdUtils::CreateFile(cfg_path);\n }\n std::string existing_config = FileReadAllText(cfg_path);\n\n CppFilter cpp_filter{existing_config};\n auto stripped_config = cpp_filter.RemoveClass(\"class ModLauncherList\");\n stripped_config += R\"cpp(class ModLauncherList\n{\n)cpp\";\n\n int mod_number = 1;\n for (auto const& mod_path : mod_paths)\n stripped_config += GenerateCfgCppForMod(mod_path, mod_number++);\n\n stripped_config += \"};\\n\";\n\n fmt::print(stderr, \"Writing config to '{}':\\n{}\\n\", cfg_path.string(), stripped_config);\n\n FileWriteAllText(cfg_path, stripped_config);\n }\n\n bool Client::IsProton()\n {\n return path_executable_.filename() == \"arma3_x64.exe\";\n }\n\n void Client::Start(string const &arguments, string const& user_environment_variables, bool launch_directly, bool disable_esync)\n {\n #ifdef __linux\n if (launch_directly)\n direct_launch(GetPath(), GetPathExecutable(), arguments, IsProton(), user_environment_variables, disable_esync);\n else\n indirect_launch_through_steam(arguments, IsProton(), user_environment_variables, disable_esync, IsFlatpak());\n #else\n (void)disable_esync; \/\/ esync does not apply on Mac OS X\n if (launch_directly)\n {\n try\n {\n SteamUtils steam_utils;\n auto ld_preload_path = fmt::format(\"{}\/Steam.AppBundle\/Steam\/Contents\/MacOS\/gameoverlayrenderer.dylib\", steam_utils.GetSteamPath().string());\n if (char const *old_ld_preload = getenv(\"DYLD_INSERT_LIBRARIES\"); old_ld_preload)\n ld_preload_path += fmt::format(\"{}:{}\", ld_preload_path, old_ld_preload);\n auto const environment = fmt::format(R\"env(DYLD_INSERT_LIBRARIES=\"{}\")env\", ld_preload_path);\n auto const command = fmt::format(R\"command(env {} {} \"{}\/Contents\/MacOS\/ArmA3\" {})command\", environment, user_environment_variables, GetPathExecutable().string(), arguments);\n fmt::print(\"Running Arma:\\n{}\\n\", command);\n StdUtils::StartBackgroundProcess(command, GetPath().string());\n }\n catch (std::exception const& e)\n {\n fmt::print(stderr, \"Direct launch failed, exception: {}\\n\", e.what());\n }\n }\n else\n {\n std::string launch_command = fmt::format(\"env {} open steam:\/\/run\/107410\/\/\" + StringUtils::Replace(arguments, \" \", \"%20\"), user_environment_variables);\n StdUtils::StartBackgroundProcess(launch_command);\n }\n #endif\n }\n\n std::vector<Mod> Client::GetHomeMods()\n {\n return GetModsFromDirectory(GetPath());\n }\n\n std::vector<Mod> Client::GetWorkshopMods()\n {\n return GetModsFromDirectory(GetPathWorkshop());\n }\n\n std::filesystem::path Client::GetCfgPath()\n {\n if (IsProton())\n return GetPath() \/ Definitions::proton_config_relative_path;\n else if (IsFlatpak())\n return std::filesystem::path(Definitions::home_directory)\n \/ Definitions::flatpak_prefix\n \/ Definitions::local_share_prefix\n \/ Definitions::bohemia_interactive_prefix\n \/ Definitions::game_config_path;\n else\n return std::filesystem::path(Definitions::home_directory)\n \/ Definitions::local_share_prefix\n \/ Definitions::bohemia_interactive_prefix\n \/ Definitions::game_config_path;\n }\n\n char Client::GetFakeDriveLetter()\n {\n return IsProton() ? 'Z' : 'C';\n }\n\n string Client::GenerateCfgCppForMod(path const &mod_path, int mod_index)\n {\n constexpr char const *mod_template =\n R\"cpp( class Mod{}\n {{\n dir=\"{}\";\n name=\"{}\";\n origin=\"GAME DIR\";\n fullPath=\"{}\";\n }};\n)cpp\";\n\n Mod mod(mod_path);\n path mod_path_absolute = trim(mod.path_.string(), \"\\\"\");\n path final_path = StringUtils::ToWindowsPath(mod_path_absolute, GetFakeDriveLetter());\n path dir = trim(mod_path_absolute.filename().string(), \"\\\"\");\n auto name = mod.GetValueOrReturnDefault(dir, \"name\", \"dir\", \"tooltip\", \"name_read_failed\");\n name = StringUtils::Replace(name, \"\\\"\", \"_\");\n\n return fmt::format(mod_template, mod_index, dir.string(), name, final_path.string());\n }\n\n bool Client::IsFlatpak()\n {\n#ifdef __linux\n try\n {\n SteamUtils steam_utils;\n return steam_utils.IsFlatpak();\n }\n catch (std::exception const &e)\n {\n fmt::print(stderr, \"Exception trying to determine if Flatpak, exception text: {}\\n\", e.what());\n return false;\n }\n#else\n return false;\n#endif\n }\n\n std::filesystem::path const &Client::GetPath()\n {\n return path_;\n }\n\n std::filesystem::path const &Client::GetPathExecutable()\n {\n return path_executable_;\n }\n\n std::filesystem::path const &Client::GetPathWorkshop()\n {\n return path_workshop_target_;\n }\n\n std::vector<Mod> Client::GetModsFromDirectory(path const &dir)\n {\n std::vector<Mod> ret;\n\n for (auto const &ent : fs::Ls(dir))\n {\n if (StdUtils::Contains(Definitions::exclusions, ent))\n continue;\n\n std::filesystem::path mod_dir = dir \/ ent;\n if (!fs::IsDirectory(mod_dir))\n continue;\n if (!StdUtils::Contains(fs::Ls(mod_dir, true), \"addons\"))\n continue;\n\n ret.emplace_back(mod_dir);\n }\n\n std::sort(ret.begin(), ret.end(), [](Mod const & m1, Mod const & m2)\n {\n return m1.GetValueOrReturnDefault(\"name\", \"dir\", StringUtils::Lowercase(m1.path_)) < m2.GetValueOrReturnDefault(\"name\", \"dir\", StringUtils::Lowercase(m2.path_));\n });\n\n return ret;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Crashpad Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"handler\/handler_main.h\"\n\n#include <getopt.h>\n#include <stdlib.h>\n\n#include <map>\n#include <string>\n\n#include \"base\/auto_reset.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_file.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/scoped_generic.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"build\/build_config.h\"\n#include \"client\/crash_report_database.h\"\n#include \"client\/crashpad_client.h\"\n#include \"tools\/tool_support.h\"\n#include \"handler\/crash_report_upload_thread.h\"\n#include \"util\/file\/file_io.h\"\n#include \"util\/stdlib\/move.h\"\n#include \"util\/stdlib\/map_insert.h\"\n#include \"util\/stdlib\/string_number_conversion.h\"\n#include \"util\/string\/split_string.h\"\n#include \"util\/synchronization\/semaphore.h\"\n\n#if defined(OS_MACOSX)\n#include <libgen.h>\n#include <signal.h>\n\n#include \"base\/mac\/scoped_mach_port.h\"\n#include \"handler\/mac\/crash_report_exception_handler.h\"\n#include \"handler\/mac\/exception_handler_server.h\"\n#include \"util\/mach\/child_port_handshake.h\"\n#include \"util\/mach\/mach_extensions.h\"\n#include \"util\/posix\/close_stdio.h\"\n#elif defined(OS_WIN)\n#include <windows.h>\n\n#include \"handler\/win\/crash_report_exception_handler.h\"\n#include \"util\/win\/exception_handler_server.h\"\n#include \"util\/win\/handle.h\"\n#endif \/\/ OS_MACOSX\n\nnamespace crashpad {\n\nnamespace {\n\nvoid Usage(const base::FilePath& me) {\n fprintf(stderr,\n\"Usage: %\" PRFilePath \" [OPTION]...\\n\"\n\"Crashpad's exception handler server.\\n\"\n\"\\n\"\n\" --annotation=KEY=VALUE set a process annotation in each crash report\\n\"\n\" --database=PATH store the crash report database at PATH\\n\"\n#if defined(OS_MACOSX)\n\" --handshake-fd=FD establish communication with the client over FD\\n\"\n\" --mach-service=SERVICE register SERVICE with the bootstrap server\\n\"\n\" --reset-own-crash-exception-port-to-system-default\\n\"\n\" reset the server's exception handler to default\\n\"\n#elif defined(OS_WIN)\n\" --handshake-handle=HANDLE\\n\"\n\" create a new pipe and send its name via HANDLE\\n\"\n\" --pipe-name=PIPE communicate with the client over PIPE\\n\"\n#endif \/\/ OS_MACOSX\n\" --url=URL send crash reports to this Breakpad server URL,\\n\"\n\" only if uploads are enabled for the database\\n\"\n\" --help display this help and exit\\n\"\n\" --version output version information and exit\\n\",\n me.value().c_str());\n ToolSupport::UsageTail(me);\n}\n\n#if defined(OS_MACOSX)\n\nstruct ResetSIGTERMTraits {\n static struct sigaction* InvalidValue() {\n return nullptr;\n }\n\n static void Free(struct sigaction* sa) {\n int rv = sigaction(SIGTERM, sa, nullptr);\n PLOG_IF(ERROR, rv != 0) << \"sigaction\";\n }\n};\nusing ScopedResetSIGTERM =\n base::ScopedGeneric<struct sigaction*, ResetSIGTERMTraits>;\n\nExceptionHandlerServer* g_exception_handler_server;\n\n\/\/ This signal handler is only operative when being run from launchd.\nvoid HandleSIGTERM(int sig, siginfo_t* siginfo, void* context) {\n DCHECK(g_exception_handler_server);\n g_exception_handler_server->Stop();\n}\n\n#endif \/\/ OS_MACOSX\n\n} \/\/ namespace\n\nint HandlerMain(int argc, char* argv[]) {\n const base::FilePath argv0(\n ToolSupport::CommandLineArgumentToFilePathStringType(argv[0]));\n const base::FilePath me(argv0.BaseName());\n\n enum OptionFlags {\n \/\/ Long options without short equivalents.\n kOptionLastChar = 255,\n kOptionAnnotation,\n kOptionDatabase,\n#if defined(OS_MACOSX)\n kOptionHandshakeFD,\n kOptionMachService,\n kOptionResetOwnCrashExceptionPortToSystemDefault,\n#elif defined(OS_WIN)\n kOptionHandshakeHandle,\n kOptionPipeName,\n#endif \/\/ OS_MACOSX\n kOptionURL,\n\n \/\/ Standard options.\n kOptionHelp = -2,\n kOptionVersion = -3,\n };\n\n struct {\n std::map<std::string, std::string> annotations;\n std::string url;\n const char* database;\n#if defined(OS_MACOSX)\n int handshake_fd;\n std::string mach_service;\n bool reset_own_crash_exception_port_to_system_default;\n#elif defined(OS_WIN)\n HANDLE handshake_handle;\n std::string pipe_name;\n#endif \/\/ OS_MACOSX\n } options = {};\n#if defined(OS_MACOSX)\n options.handshake_fd = -1;\n#elif defined(OS_WIN)\n options.handshake_handle = INVALID_HANDLE_VALUE;\n#endif\n\n const option long_options[] = {\n {\"annotation\", required_argument, nullptr, kOptionAnnotation},\n {\"database\", required_argument, nullptr, kOptionDatabase},\n#if defined(OS_MACOSX)\n {\"handshake-fd\", required_argument, nullptr, kOptionHandshakeFD},\n {\"mach-service\", required_argument, nullptr, kOptionMachService},\n {\"reset-own-crash-exception-port-to-system-default\",\n no_argument,\n nullptr,\n kOptionResetOwnCrashExceptionPortToSystemDefault},\n#elif defined(OS_WIN)\n {\"handshake-handle\", required_argument, nullptr, kOptionHandshakeHandle},\n {\"pipe-name\", required_argument, nullptr, kOptionPipeName},\n#endif \/\/ OS_MACOSX\n {\"url\", required_argument, nullptr, kOptionURL},\n {\"help\", no_argument, nullptr, kOptionHelp},\n {\"version\", no_argument, nullptr, kOptionVersion},\n {nullptr, 0, nullptr, 0},\n };\n\n int opt;\n while ((opt = getopt_long(argc, argv, \"\", long_options, nullptr)) != -1) {\n switch (opt) {\n case kOptionAnnotation: {\n std::string key;\n std::string value;\n if (!SplitString(optarg, '=', &key, &value)) {\n ToolSupport::UsageHint(me, \"--annotation requires KEY=VALUE\");\n return EXIT_FAILURE;\n }\n std::string old_value;\n if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) {\n LOG(WARNING) << \"duplicate key \" << key << \", discarding value \"\n << old_value;\n }\n break;\n }\n case kOptionDatabase: {\n options.database = optarg;\n break;\n }\n#if defined(OS_MACOSX)\n case kOptionHandshakeFD: {\n if (!StringToNumber(optarg, &options.handshake_fd) ||\n options.handshake_fd < 0) {\n ToolSupport::UsageHint(me,\n \"--handshake-fd requires a file descriptor\");\n return EXIT_FAILURE;\n }\n break;\n }\n case kOptionMachService: {\n options.mach_service = optarg;\n break;\n }\n case kOptionResetOwnCrashExceptionPortToSystemDefault: {\n options.reset_own_crash_exception_port_to_system_default = true;\n break;\n }\n#elif defined(OS_WIN)\n case kOptionHandshakeHandle: {\n \/\/ Use unsigned int, because the handle was presented by the client in\n \/\/ 0x%x format.\n unsigned int handle_uint;\n if (!StringToNumber(optarg, &handle_uint) ||\n (options.handshake_handle = IntToHandle(handle_uint)) ==\n INVALID_HANDLE_VALUE) {\n ToolSupport::UsageHint(me, \"--handshake-handle requires a HANDLE\");\n return EXIT_FAILURE;\n }\n break;\n }\n case kOptionPipeName: {\n options.pipe_name = optarg;\n break;\n }\n#endif \/\/ OS_MACOSX\n case kOptionURL: {\n options.url = optarg;\n break;\n }\n case kOptionHelp: {\n Usage(me);\n return EXIT_SUCCESS;\n }\n case kOptionVersion: {\n ToolSupport::Version(me);\n return EXIT_SUCCESS;\n }\n default: {\n ToolSupport::UsageHint(me, nullptr);\n return EXIT_FAILURE;\n }\n }\n }\n argc -= optind;\n argv += optind;\n\n#if defined(OS_MACOSX)\n if (options.handshake_fd < 0 && options.mach_service.empty()) {\n ToolSupport::UsageHint(me, \"--handshake-fd or --mach-service is required\");\n return EXIT_FAILURE;\n }\n if (options.handshake_fd >= 0 && !options.mach_service.empty()) {\n ToolSupport::UsageHint(\n me, \"--handshake-fd and --mach-service are incompatible\");\n return EXIT_FAILURE;\n }\n#elif defined(OS_WIN)\n if (options.handshake_handle == INVALID_HANDLE_VALUE &&\n options.pipe_name.empty()) {\n ToolSupport::UsageHint(me, \"--handshake-handle or --pipe-name is required\");\n return EXIT_FAILURE;\n }\n if (options.handshake_handle != INVALID_HANDLE_VALUE &&\n !options.pipe_name.empty()) {\n ToolSupport::UsageHint(\n me, \"--handshake-handle and --pipe-name are incompatible\");\n return EXIT_FAILURE;\n }\n#endif \/\/ OS_MACOSX\n\n if (!options.database) {\n ToolSupport::UsageHint(me, \"--database is required\");\n return EXIT_FAILURE;\n }\n\n if (argc) {\n ToolSupport::UsageHint(me, nullptr);\n return EXIT_FAILURE;\n }\n\n#if defined(OS_MACOSX)\n if (options.mach_service.empty()) {\n \/\/ Don’t do this when being run by launchd. See launchd.plist(5).\n CloseStdinAndStdout();\n }\n\n if (options.reset_own_crash_exception_port_to_system_default) {\n CrashpadClient::UseSystemDefaultHandler();\n }\n\n base::mac::ScopedMachReceiveRight receive_right;\n\n if (options.handshake_fd >= 0) {\n receive_right.reset(\n ChildPortHandshake::RunServerForFD(\n base::ScopedFD(options.handshake_fd),\n ChildPortHandshake::PortRightType::kReceiveRight));\n } else if (!options.mach_service.empty()) {\n receive_right = BootstrapCheckIn(options.mach_service);\n }\n\n if (!receive_right.is_valid()) {\n return EXIT_FAILURE;\n }\n\n ExceptionHandlerServer exception_handler_server(\n crashpad::move(receive_right), !options.mach_service.empty());\n base::AutoReset<ExceptionHandlerServer*> reset_g_exception_handler_server(\n &g_exception_handler_server, &exception_handler_server);\n\n struct sigaction old_sa;\n ScopedResetSIGTERM reset_sigterm;\n if (!options.mach_service.empty()) {\n \/\/ When running from launchd, no no-senders notification could ever be\n \/\/ triggered, because launchd maintains a send right to the service. When\n \/\/ launchd wants the job to exit, it will send a SIGTERM. See\n \/\/ launchd.plist(5).\n \/\/\n \/\/ Set up a SIGTERM handler that will call exception_handler_server.Stop().\n struct sigaction sa = {};\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = SA_SIGINFO;\n sa.sa_sigaction = HandleSIGTERM;\n int rv = sigaction(SIGTERM, &sa, &old_sa);\n PCHECK(rv == 0) << \"sigaction\";\n reset_sigterm.reset(&old_sa);\n }\n#elif defined(OS_WIN)\n ExceptionHandlerServer exception_handler_server(!options.pipe_name.empty());\n\n if (!options.pipe_name.empty()) {\n exception_handler_server.SetPipeName(base::UTF8ToUTF16(options.pipe_name));\n } else if (options.handshake_handle != INVALID_HANDLE_VALUE) {\n std::wstring pipe_name = exception_handler_server.CreatePipe();\n\n uint32_t pipe_name_length = static_cast<uint32_t>(pipe_name.size());\n if (!LoggingWriteFile(options.handshake_handle,\n &pipe_name_length,\n sizeof(pipe_name_length))) {\n return EXIT_FAILURE;\n }\n if (!LoggingWriteFile(options.handshake_handle,\n pipe_name.c_str(),\n pipe_name.size() * sizeof(pipe_name[0]))) {\n return EXIT_FAILURE;\n }\n }\n#endif \/\/ OS_MACOSX\n\n scoped_ptr<CrashReportDatabase> database(CrashReportDatabase::Initialize(\n base::FilePath(ToolSupport::CommandLineArgumentToFilePathStringType(\n options.database))));\n if (!database) {\n return EXIT_FAILURE;\n }\n\n CrashReportUploadThread upload_thread(database.get(), options.url);\n upload_thread.Start();\n\n CrashReportExceptionHandler exception_handler(\n database.get(), &upload_thread, &options.annotations);\n\n exception_handler_server.Run(&exception_handler);\n\n upload_thread.Stop();\n\n return EXIT_SUCCESS;\n}\n\n} \/\/ namespace crashpad\n<commit_msg>win: Set shutdown order to make the handler shutdown as late as possible<commit_after>\/\/ Copyright 2014 The Crashpad Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"handler\/handler_main.h\"\n\n#include <getopt.h>\n#include <stdlib.h>\n\n#include <map>\n#include <string>\n\n#include \"base\/auto_reset.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_file.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/scoped_generic.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"build\/build_config.h\"\n#include \"client\/crash_report_database.h\"\n#include \"client\/crashpad_client.h\"\n#include \"tools\/tool_support.h\"\n#include \"handler\/crash_report_upload_thread.h\"\n#include \"util\/file\/file_io.h\"\n#include \"util\/stdlib\/move.h\"\n#include \"util\/stdlib\/map_insert.h\"\n#include \"util\/stdlib\/string_number_conversion.h\"\n#include \"util\/string\/split_string.h\"\n#include \"util\/synchronization\/semaphore.h\"\n\n#if defined(OS_MACOSX)\n#include <libgen.h>\n#include <signal.h>\n\n#include \"base\/mac\/scoped_mach_port.h\"\n#include \"handler\/mac\/crash_report_exception_handler.h\"\n#include \"handler\/mac\/exception_handler_server.h\"\n#include \"util\/mach\/child_port_handshake.h\"\n#include \"util\/mach\/mach_extensions.h\"\n#include \"util\/posix\/close_stdio.h\"\n#elif defined(OS_WIN)\n#include <windows.h>\n\n#include \"handler\/win\/crash_report_exception_handler.h\"\n#include \"util\/win\/exception_handler_server.h\"\n#include \"util\/win\/handle.h\"\n#endif \/\/ OS_MACOSX\n\nnamespace crashpad {\n\nnamespace {\n\nvoid Usage(const base::FilePath& me) {\n fprintf(stderr,\n\"Usage: %\" PRFilePath \" [OPTION]...\\n\"\n\"Crashpad's exception handler server.\\n\"\n\"\\n\"\n\" --annotation=KEY=VALUE set a process annotation in each crash report\\n\"\n\" --database=PATH store the crash report database at PATH\\n\"\n#if defined(OS_MACOSX)\n\" --handshake-fd=FD establish communication with the client over FD\\n\"\n\" --mach-service=SERVICE register SERVICE with the bootstrap server\\n\"\n\" --reset-own-crash-exception-port-to-system-default\\n\"\n\" reset the server's exception handler to default\\n\"\n#elif defined(OS_WIN)\n\" --handshake-handle=HANDLE\\n\"\n\" create a new pipe and send its name via HANDLE\\n\"\n\" --pipe-name=PIPE communicate with the client over PIPE\\n\"\n#endif \/\/ OS_MACOSX\n\" --url=URL send crash reports to this Breakpad server URL,\\n\"\n\" only if uploads are enabled for the database\\n\"\n\" --help display this help and exit\\n\"\n\" --version output version information and exit\\n\",\n me.value().c_str());\n ToolSupport::UsageTail(me);\n}\n\n#if defined(OS_MACOSX)\n\nstruct ResetSIGTERMTraits {\n static struct sigaction* InvalidValue() {\n return nullptr;\n }\n\n static void Free(struct sigaction* sa) {\n int rv = sigaction(SIGTERM, sa, nullptr);\n PLOG_IF(ERROR, rv != 0) << \"sigaction\";\n }\n};\nusing ScopedResetSIGTERM =\n base::ScopedGeneric<struct sigaction*, ResetSIGTERMTraits>;\n\nExceptionHandlerServer* g_exception_handler_server;\n\n\/\/ This signal handler is only operative when being run from launchd.\nvoid HandleSIGTERM(int sig, siginfo_t* siginfo, void* context) {\n DCHECK(g_exception_handler_server);\n g_exception_handler_server->Stop();\n}\n\n#endif \/\/ OS_MACOSX\n\n} \/\/ namespace\n\nint HandlerMain(int argc, char* argv[]) {\n const base::FilePath argv0(\n ToolSupport::CommandLineArgumentToFilePathStringType(argv[0]));\n const base::FilePath me(argv0.BaseName());\n\n enum OptionFlags {\n \/\/ Long options without short equivalents.\n kOptionLastChar = 255,\n kOptionAnnotation,\n kOptionDatabase,\n#if defined(OS_MACOSX)\n kOptionHandshakeFD,\n kOptionMachService,\n kOptionResetOwnCrashExceptionPortToSystemDefault,\n#elif defined(OS_WIN)\n kOptionHandshakeHandle,\n kOptionPipeName,\n#endif \/\/ OS_MACOSX\n kOptionURL,\n\n \/\/ Standard options.\n kOptionHelp = -2,\n kOptionVersion = -3,\n };\n\n struct {\n std::map<std::string, std::string> annotations;\n std::string url;\n const char* database;\n#if defined(OS_MACOSX)\n int handshake_fd;\n std::string mach_service;\n bool reset_own_crash_exception_port_to_system_default;\n#elif defined(OS_WIN)\n HANDLE handshake_handle;\n std::string pipe_name;\n#endif \/\/ OS_MACOSX\n } options = {};\n#if defined(OS_MACOSX)\n options.handshake_fd = -1;\n#elif defined(OS_WIN)\n options.handshake_handle = INVALID_HANDLE_VALUE;\n#endif\n\n const option long_options[] = {\n {\"annotation\", required_argument, nullptr, kOptionAnnotation},\n {\"database\", required_argument, nullptr, kOptionDatabase},\n#if defined(OS_MACOSX)\n {\"handshake-fd\", required_argument, nullptr, kOptionHandshakeFD},\n {\"mach-service\", required_argument, nullptr, kOptionMachService},\n {\"reset-own-crash-exception-port-to-system-default\",\n no_argument,\n nullptr,\n kOptionResetOwnCrashExceptionPortToSystemDefault},\n#elif defined(OS_WIN)\n {\"handshake-handle\", required_argument, nullptr, kOptionHandshakeHandle},\n {\"pipe-name\", required_argument, nullptr, kOptionPipeName},\n#endif \/\/ OS_MACOSX\n {\"url\", required_argument, nullptr, kOptionURL},\n {\"help\", no_argument, nullptr, kOptionHelp},\n {\"version\", no_argument, nullptr, kOptionVersion},\n {nullptr, 0, nullptr, 0},\n };\n\n int opt;\n while ((opt = getopt_long(argc, argv, \"\", long_options, nullptr)) != -1) {\n switch (opt) {\n case kOptionAnnotation: {\n std::string key;\n std::string value;\n if (!SplitString(optarg, '=', &key, &value)) {\n ToolSupport::UsageHint(me, \"--annotation requires KEY=VALUE\");\n return EXIT_FAILURE;\n }\n std::string old_value;\n if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) {\n LOG(WARNING) << \"duplicate key \" << key << \", discarding value \"\n << old_value;\n }\n break;\n }\n case kOptionDatabase: {\n options.database = optarg;\n break;\n }\n#if defined(OS_MACOSX)\n case kOptionHandshakeFD: {\n if (!StringToNumber(optarg, &options.handshake_fd) ||\n options.handshake_fd < 0) {\n ToolSupport::UsageHint(me,\n \"--handshake-fd requires a file descriptor\");\n return EXIT_FAILURE;\n }\n break;\n }\n case kOptionMachService: {\n options.mach_service = optarg;\n break;\n }\n case kOptionResetOwnCrashExceptionPortToSystemDefault: {\n options.reset_own_crash_exception_port_to_system_default = true;\n break;\n }\n#elif defined(OS_WIN)\n case kOptionHandshakeHandle: {\n \/\/ Use unsigned int, because the handle was presented by the client in\n \/\/ 0x%x format.\n unsigned int handle_uint;\n if (!StringToNumber(optarg, &handle_uint) ||\n (options.handshake_handle = IntToHandle(handle_uint)) ==\n INVALID_HANDLE_VALUE) {\n ToolSupport::UsageHint(me, \"--handshake-handle requires a HANDLE\");\n return EXIT_FAILURE;\n }\n break;\n }\n case kOptionPipeName: {\n options.pipe_name = optarg;\n break;\n }\n#endif \/\/ OS_MACOSX\n case kOptionURL: {\n options.url = optarg;\n break;\n }\n case kOptionHelp: {\n Usage(me);\n return EXIT_SUCCESS;\n }\n case kOptionVersion: {\n ToolSupport::Version(me);\n return EXIT_SUCCESS;\n }\n default: {\n ToolSupport::UsageHint(me, nullptr);\n return EXIT_FAILURE;\n }\n }\n }\n argc -= optind;\n argv += optind;\n\n#if defined(OS_MACOSX)\n if (options.handshake_fd < 0 && options.mach_service.empty()) {\n ToolSupport::UsageHint(me, \"--handshake-fd or --mach-service is required\");\n return EXIT_FAILURE;\n }\n if (options.handshake_fd >= 0 && !options.mach_service.empty()) {\n ToolSupport::UsageHint(\n me, \"--handshake-fd and --mach-service are incompatible\");\n return EXIT_FAILURE;\n }\n#elif defined(OS_WIN)\n if (options.handshake_handle == INVALID_HANDLE_VALUE &&\n options.pipe_name.empty()) {\n ToolSupport::UsageHint(me, \"--handshake-handle or --pipe-name is required\");\n return EXIT_FAILURE;\n }\n if (options.handshake_handle != INVALID_HANDLE_VALUE &&\n !options.pipe_name.empty()) {\n ToolSupport::UsageHint(\n me, \"--handshake-handle and --pipe-name are incompatible\");\n return EXIT_FAILURE;\n }\n#endif \/\/ OS_MACOSX\n\n if (!options.database) {\n ToolSupport::UsageHint(me, \"--database is required\");\n return EXIT_FAILURE;\n }\n\n if (argc) {\n ToolSupport::UsageHint(me, nullptr);\n return EXIT_FAILURE;\n }\n\n#if defined(OS_MACOSX)\n if (options.mach_service.empty()) {\n \/\/ Don’t do this when being run by launchd. See launchd.plist(5).\n CloseStdinAndStdout();\n }\n\n if (options.reset_own_crash_exception_port_to_system_default) {\n CrashpadClient::UseSystemDefaultHandler();\n }\n\n base::mac::ScopedMachReceiveRight receive_right;\n\n if (options.handshake_fd >= 0) {\n receive_right.reset(\n ChildPortHandshake::RunServerForFD(\n base::ScopedFD(options.handshake_fd),\n ChildPortHandshake::PortRightType::kReceiveRight));\n } else if (!options.mach_service.empty()) {\n receive_right = BootstrapCheckIn(options.mach_service);\n }\n\n if (!receive_right.is_valid()) {\n return EXIT_FAILURE;\n }\n\n ExceptionHandlerServer exception_handler_server(\n crashpad::move(receive_right), !options.mach_service.empty());\n base::AutoReset<ExceptionHandlerServer*> reset_g_exception_handler_server(\n &g_exception_handler_server, &exception_handler_server);\n\n struct sigaction old_sa;\n ScopedResetSIGTERM reset_sigterm;\n if (!options.mach_service.empty()) {\n \/\/ When running from launchd, no no-senders notification could ever be\n \/\/ triggered, because launchd maintains a send right to the service. When\n \/\/ launchd wants the job to exit, it will send a SIGTERM. See\n \/\/ launchd.plist(5).\n \/\/\n \/\/ Set up a SIGTERM handler that will call exception_handler_server.Stop().\n struct sigaction sa = {};\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = SA_SIGINFO;\n sa.sa_sigaction = HandleSIGTERM;\n int rv = sigaction(SIGTERM, &sa, &old_sa);\n PCHECK(rv == 0) << \"sigaction\";\n reset_sigterm.reset(&old_sa);\n }\n#elif defined(OS_WIN)\n \/\/ Shut down as late as possible relative to programs we're watching.\n if (!SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY))\n PLOG(ERROR) << \"SetProcessShutdownParameters\";\n\n ExceptionHandlerServer exception_handler_server(!options.pipe_name.empty());\n\n if (!options.pipe_name.empty()) {\n exception_handler_server.SetPipeName(base::UTF8ToUTF16(options.pipe_name));\n } else if (options.handshake_handle != INVALID_HANDLE_VALUE) {\n std::wstring pipe_name = exception_handler_server.CreatePipe();\n\n uint32_t pipe_name_length = static_cast<uint32_t>(pipe_name.size());\n if (!LoggingWriteFile(options.handshake_handle,\n &pipe_name_length,\n sizeof(pipe_name_length))) {\n return EXIT_FAILURE;\n }\n if (!LoggingWriteFile(options.handshake_handle,\n pipe_name.c_str(),\n pipe_name.size() * sizeof(pipe_name[0]))) {\n return EXIT_FAILURE;\n }\n }\n#endif \/\/ OS_MACOSX\n\n scoped_ptr<CrashReportDatabase> database(CrashReportDatabase::Initialize(\n base::FilePath(ToolSupport::CommandLineArgumentToFilePathStringType(\n options.database))));\n if (!database) {\n return EXIT_FAILURE;\n }\n\n CrashReportUploadThread upload_thread(database.get(), options.url);\n upload_thread.Start();\n\n CrashReportExceptionHandler exception_handler(\n database.get(), &upload_thread, &options.annotations);\n\n exception_handler_server.Run(&exception_handler);\n\n upload_thread.Stop();\n\n return EXIT_SUCCESS;\n}\n\n} \/\/ namespace crashpad\n<|endoftext|>"} {"text":"<commit_before>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005, 2006, 2007 Roman Schindlauer\n * \n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\n\/**\n * @file AtomSet.cpp\n * @author Roman Schindlauer\n * @date Tue Feb 7 17:19:18 CET 2006\n *\n * @brief AtomSet class.\n *\n *\n *\/\n\n#include <vector>\n#include <algorithm>\n\n#include \"dlvhex\/AtomSet.h\"\n\n\nDLVHEX_NAMESPACE_BEGIN\n\nvoid\nmultiplySets(std::vector<AtomSet>& s1,\n\t\t\t std::vector<AtomSet>& s2,\n\t\t\t std::vector<AtomSet>& result)\n{\n\t\/\/\n\t\/\/ write result into temporary vector. in case the result parameter\n\t\/\/ is one of the two input vectors\n\t\/\/\n\tstd::vector<AtomSet> tmpset;\n\n\tAtomSet un;\n\n\/\/\tunsigned outer = 1;\n\tfor (std::vector<AtomSet>::iterator i1 = s1.begin();\n\t\t\ti1 != s1.end();\n\t\t\t++i1)\n\t{\n\/\/\t\tunsigned inner = 1;\n\/\/\t\tstd::cerr << \"outer loop: \" << outer++ << std::endl;\n\/\/\t\tstd::cerr << \"outer set has: \" << (*i1).size() << std::endl;\n\t\tfor (std::vector<AtomSet>::iterator i2 = s2.begin();\n\t\t\t\ti2 != s2.end();\n\t\t\t\t++i2)\n\t\t{\n\/\/\t\t\tstd::cerr << \"inner loop: \" << inner++ << std::endl;\n\t\t\t\/\/\n\t\t\t\/\/ make union of two atomsets:\n\t\t\t\/\/\n\t\t\tun = *i1;\n\t\t\tun.insert(*i2);\n\n\t\t\t\/\/\n\t\t\t\/\/ now ensure minimality:\n\t\t\t\/\/\n\t\t\tbool add = true;\n\n\t\t\tstd::vector<AtomSet>::iterator curras = tmpset.begin();\n\n\/\/\t\t\tunsigned i = 1;\n\n\t\t\tif (((*i1).size() > 0) && ((*i2).size() > 0))\n\t\t\twhile (curras != tmpset.end())\n\t\t\t{\n\/\/\t\t\t\tstd::cerr << \"looking at existing set \" << i++\n\/\/\t\t\t\t\t<< \" new union: \" << un.size() << \" current: \" << (*curras).size() << std::endl;\n\t\t\t\t\/\/\n\t\t\t\t\/\/ is the new one a superset (or equal) than an existing one\n\t\t\t\t\/\/\n\t\t\t\tif (std::includes(un.begin(), un.end(), (*curras).begin(), (*curras).end()))\n\t\t\t\t{\n\/\/\t\t\t\t\tstd::cerr << \"\t new union is superset!\" << std::endl;\n\/\/\t\t\t\t\tstd::cerr << \"\t new union: \" << un.size() << \" current: \" << (*curras).size() << std::endl;\n\t\t\t\t\tadd = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/\n\t\t\t\t\/\/ is the new one a subset of an existing one? Must be a *real* subset,\n\t\t\t\t\/\/ if we passed the previous \"if\"!\n\t\t\t\t\/\/\n\t\t\t\tif (std::includes((*curras).begin(), (*curras).end(), un.begin(), un.end()))\n\t\t\t\t{\n\/\/\t\t\t\t\tstd::cerr << \"\t new union is subset!\" << std::endl;\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ remove existing one\n\t\t\t\t\t\/\/\n\t\t\t\t\ttmpset.erase(curras);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcurras++;\n\t\t\t}\n\n\t\t\tif (add)\n\t\t\t\ttmpset.push_back(un);\n\t\t}\n\t}\n\n\t\/\/\n\t\/\/ now we can write the result\n\t\/\/\n\tswap(result, tmpset);\n}\n\n\nAtomSet::const_iterator\nAtomSet::begin() const\n{\n\treturn const_iterator(atoms.begin());\n}\n\n\nAtomSet::const_iterator\nAtomSet::end() const\n{\n\treturn const_iterator(atoms.end());\n}\n\n\nvoid\nAtomSet::clear()\n{\n\tatoms.clear();\n}\n\n\nbool\nAtomSet::empty() const\n{\n\treturn atoms.empty();\n}\n\n\nsize_t\nAtomSet::size() const\n{\n\treturn atoms.size();\n}\n\n\n\nvoid\nAtomSet::insert(const AtomPtr& ap)\n{\n\t\/\/\/ @todo test if *ap really exists\n\n\tatoms.insert(ap);\n}\n\n\n\nvoid\nAtomSet::insert(const AtomSet& add)\n{\n\tatoms.insert(add.atoms.begin(), add.atoms.end());\n}\n\n\nAtomSet\nAtomSet::difference(const AtomSet& as) const\n{\n AtomSet res;\n\n\/\/ std::set_difference(this->atoms.begin(), this->atoms.end(),\n\/\/ \t\t as.atoms.begin(), as.atoms.end(),\n\/\/ \t\t std::inserter(res.atoms, res.atoms.begin())\n\/\/ \t\t );\n\n for (atomset_t::const_iterator a = atoms.begin();\n a != atoms.end();\n ++a)\n {\n if (as.atoms.find(*a) == as.atoms.end())\n\tres.atoms.insert(*a);\n }\n\n return res;\n}\n\n\nvoid\nAtomSet::matchPredicate(const std::string& pred,\n\t\t\tAtomSet& matched) const\n{\n\t\/\/\/ @todo: stdlib algorithm!\n\tfor (atomset_t::const_iterator a = atoms.begin();\n\t\t a != atoms.end();\n\t\t a++)\n\t{\n\t\tif ((*a)->getPredicate() == pred)\n\t\t\tmatched.atoms.insert(*a);\n\t}\n}\n\n\nvoid\nAtomSet::matchAtom(const AtomPtr& atom,\n\t\t AtomSet& matched) const\n{\n\t\/\/\/ @todo: stdlib algorithm!\n\tfor (atomset_t::const_iterator a = atoms.begin();\n\t\t a != atoms.end();\n\t\t a++)\n\t{\n\t\tif ((*a)->unifiesWith(atom))\n\t\t\tmatched.atoms.insert(*a);\n\t}\n}\n\n\nvoid\nAtomSet::accept(BaseVisitor& v)\n{\n v.visit(this);\n}\n\n\n\/**\n * @brief General purpose predicate functor, which returns true iff\n * predicate of g matches pred.\n *\/\nstruct PredicateMatches : public std::binary_function<AtomPtr, std::string, bool>\n{\n bool\n operator() (const AtomPtr& g, const std::string& pred) const\n {\n return (g->getPredicate() == Term(pred));\n }\n};\n\n\nvoid\nAtomSet::remove(const std::string& pred)\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\twhile ((cur = std::find_if(cur, last, std::bind2nd(PredicateMatches(), pred))) != last)\n\t{\n\t\tatomset_t::iterator tmp = cur++;\n\n\t\tatoms.erase(tmp);\n\t}\n}\n\n\nvoid\nAtomSet::remove(const std::vector<std::string>& preds)\n{\n\tfor (std::vector<std::string>::const_iterator predit = preds.begin();\n\t\t predit != preds.end();\n\t\t ++predit)\n\t{\n\t\tremove(*predit);\n\t}\n}\n\nvoid\nAtomSet::keep(const std::vector<std::string>& preds)\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\t\/\/\n\t\t\/\/ look if the current atom is in the filter set\n\t\t\/\/\n\t\tif ((std::find_if(preds.begin(),\n\t\t\t\t\t\t preds.end(),\n\t\t\t\t std::bind1st(PredicateMatches(), *cur))) == preds.end())\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ if not, delete this atom\n\t\t\t\/\/\n\t\t\tatomset_t::iterator tmp = cur++;\n\n\t\t\tatoms.erase(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcur++;\n\t\t}\n\t}\n}\n\n\nvoid\nAtomSet::keepPos()\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\tif ((*cur)->isStronglyNegated())\n\t\t{\n\t\t\tatomset_t::iterator tmp = cur++;\n\n\t\t\tatoms.erase(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcur++;\n\t\t}\n\t}\n}\n\n\n\/**\n * @brief General purpose predicate functor, which returns true iff\n * (*g == a).\n *\/\nstruct AtomMatches : public std::binary_function<AtomPtr, Atom, bool>\n{\n bool\n operator() (const AtomPtr& g, const Atom& a) const\n {\n return (*g == a);\n }\n};\n\n\nbool\nAtomSet::isConsistent() const\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\tAtom a(**cur);\n\t\ta.negate();\n\n\t\t\/\/\n\t\t\/\/ see if 'cur' occurs negated (i.e., 'a') in the range of 'cur+1' to\n\t\t\/\/ 'last'\n\t\t\/\/\n\t\tif (std::find_if(++cur, last, std::bind2nd(AtomMatches(), a)) != last)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\nbool\nAtomSet::operator== (const AtomSet& atomset2) const\n{\n\treturn ((this->size() == atomset2.size()) \n\t && std::equal(this->begin(), this->end(), atomset2.begin()));\n}\n\n\nbool\nAtomSet::operator!= (const AtomSet& atomset2) const\n{\n\treturn !(*this == atomset2);\n}\n\n\nint\nAtomSet::operator< (const AtomSet& atomset2) const\n{\n\tif (this->size() < atomset2.size())\n\t\treturn true;\n\n\tif (this->size() > atomset2.size())\n\t\treturn false;\n\n\t\/\/return !(std::includes(this->begin(), this->end(), atomset2.begin(), atomset2.end()));\n\n\t\/\/ find first mismatch\n\tstd::pair<AtomSet::const_iterator, AtomSet::const_iterator> result;\n\tresult = std::mismatch(this->begin(), this->end(), atomset2.begin());\n\n\t\/\/\n\t\/\/ no mismatch? then they are equal!\n\t\/\/\n\tif (result.first == this->end())\n\t\treturn false;\n\n\treturn *(result.first) < *(result.second);\n}\n\nDLVHEX_NAMESPACE_END\n\n\/* vim: set noet sw=4 ts=4 tw=80: *\/\n\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ End:\n<commit_msg>(AtomSet::operator<): Sanitize code.<commit_after>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005, 2006, 2007 Roman Schindlauer\n * \n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\n\/**\n * @file AtomSet.cpp\n * @author Roman Schindlauer\n * @date Tue Feb 7 17:19:18 CET 2006\n *\n * @brief AtomSet class.\n *\n *\n *\/\n\n#include <vector>\n#include <algorithm>\n\n#include \"dlvhex\/AtomSet.h\"\n\n\nDLVHEX_NAMESPACE_BEGIN\n\nvoid\nmultiplySets(std::vector<AtomSet>& s1,\n\t\t\t std::vector<AtomSet>& s2,\n\t\t\t std::vector<AtomSet>& result)\n{\n\t\/\/\n\t\/\/ write result into temporary vector. in case the result parameter\n\t\/\/ is one of the two input vectors\n\t\/\/\n\tstd::vector<AtomSet> tmpset;\n\n\tAtomSet un;\n\n\/\/\tunsigned outer = 1;\n\tfor (std::vector<AtomSet>::iterator i1 = s1.begin();\n\t\t\ti1 != s1.end();\n\t\t\t++i1)\n\t{\n\/\/\t\tunsigned inner = 1;\n\/\/\t\tstd::cerr << \"outer loop: \" << outer++ << std::endl;\n\/\/\t\tstd::cerr << \"outer set has: \" << (*i1).size() << std::endl;\n\t\tfor (std::vector<AtomSet>::iterator i2 = s2.begin();\n\t\t\t\ti2 != s2.end();\n\t\t\t\t++i2)\n\t\t{\n\/\/\t\t\tstd::cerr << \"inner loop: \" << inner++ << std::endl;\n\t\t\t\/\/\n\t\t\t\/\/ make union of two atomsets:\n\t\t\t\/\/\n\t\t\tun = *i1;\n\t\t\tun.insert(*i2);\n\n\t\t\t\/\/\n\t\t\t\/\/ now ensure minimality:\n\t\t\t\/\/\n\t\t\tbool add = true;\n\n\t\t\tstd::vector<AtomSet>::iterator curras = tmpset.begin();\n\n\/\/\t\t\tunsigned i = 1;\n\n\t\t\tif (((*i1).size() > 0) && ((*i2).size() > 0))\n\t\t\twhile (curras != tmpset.end())\n\t\t\t{\n\/\/\t\t\t\tstd::cerr << \"looking at existing set \" << i++\n\/\/\t\t\t\t\t<< \" new union: \" << un.size() << \" current: \" << (*curras).size() << std::endl;\n\t\t\t\t\/\/\n\t\t\t\t\/\/ is the new one a superset (or equal) than an existing one\n\t\t\t\t\/\/\n\t\t\t\tif (std::includes(un.begin(), un.end(), (*curras).begin(), (*curras).end()))\n\t\t\t\t{\n\/\/\t\t\t\t\tstd::cerr << \"\t new union is superset!\" << std::endl;\n\/\/\t\t\t\t\tstd::cerr << \"\t new union: \" << un.size() << \" current: \" << (*curras).size() << std::endl;\n\t\t\t\t\tadd = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/\n\t\t\t\t\/\/ is the new one a subset of an existing one? Must be a *real* subset,\n\t\t\t\t\/\/ if we passed the previous \"if\"!\n\t\t\t\t\/\/\n\t\t\t\tif (std::includes((*curras).begin(), (*curras).end(), un.begin(), un.end()))\n\t\t\t\t{\n\/\/\t\t\t\t\tstd::cerr << \"\t new union is subset!\" << std::endl;\n\t\t\t\t\t\/\/\n\t\t\t\t\t\/\/ remove existing one\n\t\t\t\t\t\/\/\n\t\t\t\t\ttmpset.erase(curras);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcurras++;\n\t\t\t}\n\n\t\t\tif (add)\n\t\t\t\ttmpset.push_back(un);\n\t\t}\n\t}\n\n\t\/\/\n\t\/\/ now we can write the result\n\t\/\/\n\tswap(result, tmpset);\n}\n\n\nAtomSet::const_iterator\nAtomSet::begin() const\n{\n\treturn const_iterator(atoms.begin());\n}\n\n\nAtomSet::const_iterator\nAtomSet::end() const\n{\n\treturn const_iterator(atoms.end());\n}\n\n\nvoid\nAtomSet::clear()\n{\n\tatoms.clear();\n}\n\n\nbool\nAtomSet::empty() const\n{\n\treturn atoms.empty();\n}\n\n\nsize_t\nAtomSet::size() const\n{\n\treturn atoms.size();\n}\n\n\n\nvoid\nAtomSet::insert(const AtomPtr& ap)\n{\n\t\/\/\/ @todo test if *ap really exists\n\n\tatoms.insert(ap);\n}\n\n\n\nvoid\nAtomSet::insert(const AtomSet& add)\n{\n\tatoms.insert(add.atoms.begin(), add.atoms.end());\n}\n\n\nAtomSet\nAtomSet::difference(const AtomSet& as) const\n{\n AtomSet res;\n\n\/\/ std::set_difference(this->atoms.begin(), this->atoms.end(),\n\/\/ \t\t as.atoms.begin(), as.atoms.end(),\n\/\/ \t\t std::inserter(res.atoms, res.atoms.begin())\n\/\/ \t\t );\n\n for (atomset_t::const_iterator a = atoms.begin();\n a != atoms.end();\n ++a)\n {\n if (as.atoms.find(*a) == as.atoms.end())\n\tres.atoms.insert(*a);\n }\n\n return res;\n}\n\n\nvoid\nAtomSet::matchPredicate(const std::string& pred,\n\t\t\tAtomSet& matched) const\n{\n\t\/\/\/ @todo: stdlib algorithm!\n\tfor (atomset_t::const_iterator a = atoms.begin();\n\t\t a != atoms.end();\n\t\t a++)\n\t{\n\t\tif ((*a)->getPredicate() == pred)\n\t\t\tmatched.atoms.insert(*a);\n\t}\n}\n\n\nvoid\nAtomSet::matchAtom(const AtomPtr& atom,\n\t\t AtomSet& matched) const\n{\n\t\/\/\/ @todo: stdlib algorithm!\n\tfor (atomset_t::const_iterator a = atoms.begin();\n\t\t a != atoms.end();\n\t\t a++)\n\t{\n\t\tif ((*a)->unifiesWith(atom))\n\t\t\tmatched.atoms.insert(*a);\n\t}\n}\n\n\nvoid\nAtomSet::accept(BaseVisitor& v)\n{\n v.visit(this);\n}\n\n\n\/**\n * @brief General purpose predicate functor, which returns true iff\n * predicate of g matches pred.\n *\/\nstruct PredicateMatches : public std::binary_function<AtomPtr, std::string, bool>\n{\n bool\n operator() (const AtomPtr& g, const std::string& pred) const\n {\n return (g->getPredicate() == Term(pred));\n }\n};\n\n\nvoid\nAtomSet::remove(const std::string& pred)\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\twhile ((cur = std::find_if(cur, last, std::bind2nd(PredicateMatches(), pred))) != last)\n\t{\n\t\tatomset_t::iterator tmp = cur++;\n\n\t\tatoms.erase(tmp);\n\t}\n}\n\n\nvoid\nAtomSet::remove(const std::vector<std::string>& preds)\n{\n\tfor (std::vector<std::string>::const_iterator predit = preds.begin();\n\t\t predit != preds.end();\n\t\t ++predit)\n\t{\n\t\tremove(*predit);\n\t}\n}\n\nvoid\nAtomSet::keep(const std::vector<std::string>& preds)\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\t\/\/\n\t\t\/\/ look if the current atom is in the filter set\n\t\t\/\/\n\t\tif ((std::find_if(preds.begin(),\n\t\t\t\t\t\t preds.end(),\n\t\t\t\t std::bind1st(PredicateMatches(), *cur))) == preds.end())\n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ if not, delete this atom\n\t\t\t\/\/\n\t\t\tatomset_t::iterator tmp = cur++;\n\n\t\t\tatoms.erase(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcur++;\n\t\t}\n\t}\n}\n\n\nvoid\nAtomSet::keepPos()\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\tif ((*cur)->isStronglyNegated())\n\t\t{\n\t\t\tatomset_t::iterator tmp = cur++;\n\n\t\t\tatoms.erase(tmp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcur++;\n\t\t}\n\t}\n}\n\n\n\/**\n * @brief General purpose predicate functor, which returns true iff\n * (*g == a).\n *\/\nstruct AtomMatches : public std::binary_function<AtomPtr, Atom, bool>\n{\n bool\n operator() (const AtomPtr& g, const Atom& a) const\n {\n return (*g == a);\n }\n};\n\n\nbool\nAtomSet::isConsistent() const\n{\n\tatomset_t::iterator cur = atoms.begin();\n\n\tatomset_t::const_iterator last = atoms.end();\n\n\t\/\/\n\t\/\/ go through all atoms of this set\n\t\/\/\n\twhile (cur != last)\n\t{\n\t\tAtom a(**cur);\n\t\ta.negate();\n\n\t\t\/\/\n\t\t\/\/ see if 'cur' occurs negated (i.e., 'a') in the range of 'cur+1' to\n\t\t\/\/ 'last'\n\t\t\/\/\n\t\tif (std::find_if(++cur, last, std::bind2nd(AtomMatches(), a)) != last)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\nbool\nAtomSet::operator== (const AtomSet& atomset2) const\n{\n\treturn ((this->size() == atomset2.size()) \n\t && std::equal(this->begin(), this->end(), atomset2.begin()));\n}\n\n\nbool\nAtomSet::operator!= (const AtomSet& atomset2) const\n{\n\treturn !(*this == atomset2);\n}\n\n\nint\nAtomSet::operator< (const AtomSet& atomset2) const\n{\n if (this->size() < atomset2.size()) \/\/ <\n {\n return true;\n }\n else if (this->size() > atomset2.size()) \/\/ >\n {\n return false;\n }\n else \/\/ same size, they can still be < or >=\n {\n \/\/ find first mismatch\n std::pair<AtomSet::const_iterator, AtomSet::const_iterator> result;\n result = std::mismatch(this->begin(), this->end(), atomset2.begin());\n\n \/\/ no mismatch: ==, otw. check if the found mismatch is < or >=\n return result.first == this->end() ? false : *result.first < *result.second;\n }\n}\n\nDLVHEX_NAMESPACE_END\n\n\/* vim: set noet sw=4 ts=4 tw=80: *\/\n\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/**\\file euclidean_transformation_validator.cpp\n * \\brief Description...\n *\n * @version 1.0\n * @author Carlos Miguel Correia da Costa\n *\/\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n#include <dynamic_robot_localization\/transformation_validators\/euclidean_transformation_validator.h>\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nnamespace dynamic_robot_localization {\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ ============================================================================= <public-section> ============================================================================\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nEuclideanTransformationValidator::EuclideanTransformationValidator() :\n\t\tmax_transformation_angle_(1.59),\n\t\tmax_transformation_distance_(0.1),\n\t\tmax_new_pose_diff_angle_(1.59),\n\t\tmax_new_pose_diff_distance_(0.2),\n\t\tmax_root_mean_square_error_(0.05),\n\t\tmax_root_mean_square_error_reference_pointcloud_(-1.0),\n\t\tmax_outliers_percentage_(0.6),\n\t\tmax_outliers_percentage_reference_pointcloud_(-1.0),\n\t\tmin_inliers_angular_distribution_(0.125),\n\t\tmax_outliers_angular_distribution_(0.875) {}\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <EuclideanTransformationValidator-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid EuclideanTransformationValidator::setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle, std::string configuration_namespace) {\n\tprivate_node_handle->param(configuration_namespace + \"max_transformation_angle\", max_transformation_angle_, 0.7);\n\tprivate_node_handle->param(configuration_namespace + \"max_transformation_distance\", max_transformation_distance_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"max_new_pose_diff_angle\", max_new_pose_diff_angle_, 1.59);\n\tprivate_node_handle->param(configuration_namespace + \"max_new_pose_diff_distance\", max_new_pose_diff_distance_, 0.2);\n\tprivate_node_handle->param(configuration_namespace + \"max_root_mean_square_error\", max_root_mean_square_error_, 0.05);\n\tprivate_node_handle->param(configuration_namespace + \"max_root_mean_square_error_reference_pointcloud\", max_root_mean_square_error_reference_pointcloud_, -1.0);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_root_mean_square_error\", min_overriding_root_mean_square_error_, 0.01);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_percentage\", max_outliers_percentage_, 0.6);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_percentage_reference_pointcloud\", max_outliers_percentage_reference_pointcloud_, -1.0);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_outliers_percentage\", min_overriding_outliers_percentage_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_outliers_percentage_reference_pointcloud\", min_overriding_outliers_percentage_reference_pointcloud_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"min_inliers_angular_distribution\", min_inliers_angular_distribution_, 0.125);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_angular_distribution\", max_outliers_angular_distribution_, 0.875);\n}\n\nbool EuclideanTransformationValidator::validateNewLocalizationPose(const tf2::Transform& last_accepted_pose, const tf2::Transform& initial_guess, tf2::Transform& new_pose,\n\t\tdouble root_mean_square_error, double root_mean_square_error_reference_pointcloud, double outliers_percentage, double outliers_percentage_reference_pointcloud, double inliers_angular_distribution, double outliers_angular_distribution) {\n\tdouble transform_distance = (new_pose.getOrigin() - initial_guess.getOrigin()).length();\n\tdouble transform_angle = std::abs(new_pose.getRotation().normalize().angleShortestPath(initial_guess.getRotation().normalize()));\n\n\tdouble new_pose_distance = (new_pose.getOrigin() - last_accepted_pose.getOrigin()).length();\n\tdouble new_pose_angle = std::abs(new_pose.getRotation().normalize().angleShortestPath(last_accepted_pose.getRotation().normalize()));\n\n\tstd::stringstream validation_info;\n\tvalidation_info << \"\\n\\t correction translation: \" \t\t\t\t\t\t\t\t<< transform_distance << \" | (max_transformation_distance: \" << max_transformation_distance_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t correction rotation: \" \t\t\t\t\t\t\t\t\t\t\t\t\t<< transform_angle << \" | (max_transformation_angle_: \" << max_transformation_angle_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t new pose diff translation: \" \t\t\t\t\t\t\t\t\t\t<< new_pose_distance << \" | (max_new_pose_diff_distance_: \" << max_new_pose_diff_distance_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t new pose diff rotation: \" \t\t\t\t\t\t\t\t\t\t\t\t<< new_pose_angle << \" | (max_new_pose_diff_angle_: \" << max_new_pose_diff_angle_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t root_mean_square_error: \" \t\t\t\t\t\t\t\t\t\t\t\t<< root_mean_square_error << \" | (max_root_mean_square_error_: \" << max_root_mean_square_error_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t root_mean_square_error_reference_pointcloud: \" \t<< root_mean_square_error_reference_pointcloud << \" | (max_root_mean_square_error_reference_pointcloud_: \" << max_root_mean_square_error_reference_pointcloud_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_percentage: \"\t\t\t\t\t\t\t\t\t\t\t\t\t\t<< outliers_percentage << \" | (max_outliers_percentage_: \" << max_outliers_percentage_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_percentage_reference_pointcloud: \"\t\t\t<< outliers_percentage_reference_pointcloud << \" | (max_outliers_percentage_reference_pointcloud_: \" << max_outliers_percentage_reference_pointcloud_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t inliers_angular_distribution: \"\t\t\t\t\t\t\t\t\t<< inliers_angular_distribution << \" | (min_inliers_angular_distribution_: \" << min_inliers_angular_distribution_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_angular_distribution: \"\t\t\t\t\t\t\t\t\t<< outliers_angular_distribution << \" | (max_outliers_angular_distribution_: \" << max_outliers_angular_distribution_ << \")\";\n\n\tif (root_mean_square_error < min_overriding_root_mean_square_error_ &&\n\t\t\toutliers_percentage < min_overriding_outliers_percentage_ &&\n\t\t\toutliers_percentage_reference_pointcloud < min_overriding_outliers_percentage_reference_pointcloud_) {\n\t\tROS_DEBUG_STREAM(\"EuclideanTransformationValidator accepted new pose at time \" << ros::Time::now() << \" using overriding thresholds -> \" << validation_info.str());\n\t\treturn true;\n\t}\n\n\tif (max_root_mean_square_error_ > 0 && (root_mean_square_error > max_root_mean_square_error_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to root_mean_square_error -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_root_mean_square_error_reference_pointcloud_ > 0 && (root_mean_square_error_reference_pointcloud > max_root_mean_square_error_reference_pointcloud_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to root_mean_square_error_reference_pointcloud -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_percentage_ > 0 && outliers_percentage > max_outliers_percentage_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_percentage -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_percentage_reference_pointcloud_ > 0 && (outliers_percentage_reference_pointcloud > max_outliers_percentage_reference_pointcloud_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_percentage_reference_pointcloud -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_transformation_distance_ > 0 && transform_distance > max_transformation_distance_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_transformation_distance -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_transformation_angle_ > 0 && transform_angle > max_transformation_angle_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_transformation_angle -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_new_pose_diff_distance_ > 0 && new_pose_distance > max_new_pose_diff_distance_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_new_pose_diff_distance -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_new_pose_diff_angle_ > 0 && new_pose_angle < max_new_pose_diff_angle_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_new_pose_diff_angle -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (min_inliers_angular_distribution_ > 0 && inliers_angular_distribution < min_inliers_angular_distribution_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to min_inliers_angular_distribution -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_angular_distribution_ > 0 && outliers_angular_distribution > max_outliers_angular_distribution_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_angular_distribution -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tROS_DEBUG_STREAM(\"EuclideanTransformationValidator accepted new pose at time \" << ros::Time::now() << \" -> \" << validation_info.str());\n\treturn true;\n}\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/EuclideanTransformationValidator-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ ============================================================================= <\/public-section> ===========================================================================\n\n\/\/ ============================================================================= <protected-section> =======================================================================\n\/\/ ============================================================================= <\/protected-section> =======================================================================\n\n\/\/ ============================================================================= <private-section> =========================================================================\n\/\/ ============================================================================= <\/private-section> =========================================================================\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n} \/* namespace dynamic_robot_localization *\/\n<commit_msg>Fixed comparison signal in euclidean transformation validator for max_new_pose_diff_angle threshold.<commit_after>\/**\\file euclidean_transformation_validator.cpp\n * \\brief Description...\n *\n * @version 1.0\n * @author Carlos Miguel Correia da Costa\n *\/\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n#include <dynamic_robot_localization\/transformation_validators\/euclidean_transformation_validator.h>\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nnamespace dynamic_robot_localization {\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/imports> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ ============================================================================= <public-section> ============================================================================\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nEuclideanTransformationValidator::EuclideanTransformationValidator() :\n\t\tmax_transformation_angle_(1.59),\n\t\tmax_transformation_distance_(0.1),\n\t\tmax_new_pose_diff_angle_(1.59),\n\t\tmax_new_pose_diff_distance_(0.2),\n\t\tmax_root_mean_square_error_(0.05),\n\t\tmax_root_mean_square_error_reference_pointcloud_(-1.0),\n\t\tmax_outliers_percentage_(0.6),\n\t\tmax_outliers_percentage_reference_pointcloud_(-1.0),\n\t\tmin_inliers_angular_distribution_(0.125),\n\t\tmax_outliers_angular_distribution_(0.875) {}\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/constructors-destructor> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <EuclideanTransformationValidator-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid EuclideanTransformationValidator::setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle, std::string configuration_namespace) {\n\tprivate_node_handle->param(configuration_namespace + \"max_transformation_angle\", max_transformation_angle_, 0.7);\n\tprivate_node_handle->param(configuration_namespace + \"max_transformation_distance\", max_transformation_distance_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"max_new_pose_diff_angle\", max_new_pose_diff_angle_, 1.59);\n\tprivate_node_handle->param(configuration_namespace + \"max_new_pose_diff_distance\", max_new_pose_diff_distance_, 0.2);\n\tprivate_node_handle->param(configuration_namespace + \"max_root_mean_square_error\", max_root_mean_square_error_, 0.05);\n\tprivate_node_handle->param(configuration_namespace + \"max_root_mean_square_error_reference_pointcloud\", max_root_mean_square_error_reference_pointcloud_, -1.0);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_root_mean_square_error\", min_overriding_root_mean_square_error_, 0.01);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_percentage\", max_outliers_percentage_, 0.6);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_percentage_reference_pointcloud\", max_outliers_percentage_reference_pointcloud_, -1.0);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_outliers_percentage\", min_overriding_outliers_percentage_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"min_overriding_outliers_percentage_reference_pointcloud\", min_overriding_outliers_percentage_reference_pointcloud_, 0.1);\n\tprivate_node_handle->param(configuration_namespace + \"min_inliers_angular_distribution\", min_inliers_angular_distribution_, 0.125);\n\tprivate_node_handle->param(configuration_namespace + \"max_outliers_angular_distribution\", max_outliers_angular_distribution_, 0.875);\n}\n\nbool EuclideanTransformationValidator::validateNewLocalizationPose(const tf2::Transform& last_accepted_pose, const tf2::Transform& initial_guess, tf2::Transform& new_pose,\n\t\tdouble root_mean_square_error, double root_mean_square_error_reference_pointcloud, double outliers_percentage, double outliers_percentage_reference_pointcloud, double inliers_angular_distribution, double outliers_angular_distribution) {\n\tdouble transform_distance = (new_pose.getOrigin() - initial_guess.getOrigin()).length();\n\tdouble transform_angle = std::abs(new_pose.getRotation().normalize().angleShortestPath(initial_guess.getRotation().normalize()));\n\n\tdouble new_pose_distance = (new_pose.getOrigin() - last_accepted_pose.getOrigin()).length();\n\tdouble new_pose_angle = std::abs(new_pose.getRotation().normalize().angleShortestPath(last_accepted_pose.getRotation().normalize()));\n\n\tstd::stringstream validation_info;\n\tvalidation_info << \"\\n\\t correction translation: \" \t\t\t\t\t\t\t\t<< transform_distance << \" | (max_transformation_distance: \" << max_transformation_distance_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t correction rotation: \" \t\t\t\t\t\t\t\t\t\t\t\t\t<< transform_angle << \" | (max_transformation_angle_: \" << max_transformation_angle_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t new pose diff translation: \" \t\t\t\t\t\t\t\t\t\t<< new_pose_distance << \" | (max_new_pose_diff_distance_: \" << max_new_pose_diff_distance_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t new pose diff rotation: \" \t\t\t\t\t\t\t\t\t\t\t\t<< new_pose_angle << \" | (max_new_pose_diff_angle_: \" << max_new_pose_diff_angle_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t root_mean_square_error: \" \t\t\t\t\t\t\t\t\t\t\t\t<< root_mean_square_error << \" | (max_root_mean_square_error_: \" << max_root_mean_square_error_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t root_mean_square_error_reference_pointcloud: \" \t<< root_mean_square_error_reference_pointcloud << \" | (max_root_mean_square_error_reference_pointcloud_: \" << max_root_mean_square_error_reference_pointcloud_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_percentage: \"\t\t\t\t\t\t\t\t\t\t\t\t\t\t<< outliers_percentage << \" | (max_outliers_percentage_: \" << max_outliers_percentage_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_percentage_reference_pointcloud: \"\t\t\t<< outliers_percentage_reference_pointcloud << \" | (max_outliers_percentage_reference_pointcloud_: \" << max_outliers_percentage_reference_pointcloud_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t inliers_angular_distribution: \"\t\t\t\t\t\t\t\t\t<< inliers_angular_distribution << \" | (min_inliers_angular_distribution_: \" << min_inliers_angular_distribution_ << \")\" \\\n\t\t\t\t\t<< \"\\n\\t outliers_angular_distribution: \"\t\t\t\t\t\t\t\t\t<< outliers_angular_distribution << \" | (max_outliers_angular_distribution_: \" << max_outliers_angular_distribution_ << \")\";\n\n\tif (root_mean_square_error < min_overriding_root_mean_square_error_ &&\n\t\t\toutliers_percentage < min_overriding_outliers_percentage_ &&\n\t\t\toutliers_percentage_reference_pointcloud < min_overriding_outliers_percentage_reference_pointcloud_) {\n\t\tROS_DEBUG_STREAM(\"EuclideanTransformationValidator accepted new pose at time \" << ros::Time::now() << \" using overriding thresholds -> \" << validation_info.str());\n\t\treturn true;\n\t}\n\n\tif (max_root_mean_square_error_ > 0 && (root_mean_square_error > max_root_mean_square_error_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to root_mean_square_error -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_root_mean_square_error_reference_pointcloud_ > 0 && (root_mean_square_error_reference_pointcloud > max_root_mean_square_error_reference_pointcloud_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to root_mean_square_error_reference_pointcloud -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_percentage_ > 0 && outliers_percentage > max_outliers_percentage_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_percentage -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_percentage_reference_pointcloud_ > 0 && (outliers_percentage_reference_pointcloud > max_outliers_percentage_reference_pointcloud_)) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_percentage_reference_pointcloud -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_transformation_distance_ > 0 && transform_distance > max_transformation_distance_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_transformation_distance -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_transformation_angle_ > 0 && transform_angle > max_transformation_angle_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_transformation_angle -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_new_pose_diff_distance_ > 0 && new_pose_distance > max_new_pose_diff_distance_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_new_pose_diff_distance -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_new_pose_diff_angle_ > 0 && new_pose_angle > max_new_pose_diff_angle_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_new_pose_diff_angle -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (min_inliers_angular_distribution_ > 0 && inliers_angular_distribution < min_inliers_angular_distribution_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to min_inliers_angular_distribution -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tif (max_outliers_angular_distribution_ > 0 && outliers_angular_distribution > max_outliers_angular_distribution_) {\n\t\tROS_WARN_STREAM(\"EuclideanTransformationValidator rejected new pose at time \" << ros::Time::now() << \" due to max_outliers_angular_distribution -> \" << validation_info.str());\n\t\treturn false;\n\t}\n\n\tROS_DEBUG_STREAM(\"EuclideanTransformationValidator accepted new pose at time \" << ros::Time::now() << \" -> \" << validation_info.str());\n\treturn true;\n}\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/EuclideanTransformationValidator-functions> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ ============================================================================= <\/public-section> ===========================================================================\n\n\/\/ ============================================================================= <protected-section> =======================================================================\n\/\/ ============================================================================= <\/protected-section> =======================================================================\n\n\/\/ ============================================================================= <private-section> =========================================================================\n\/\/ ============================================================================= <\/private-section> =========================================================================\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <\/template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n} \/* namespace dynamic_robot_localization *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"postal.h\"\n#include \"geocoder.h\"\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace GeoNLP;\n\nint main(int argc, char *argv[])\n{\n Postal postal;\n \/\/postal.set_initialize_every_call(true);\n\n if (argc < 5)\n {\n std::cout << \"Use: \" << argv[0] << \" dbase postal_global postal_country address\\n\"\n\t\t<< \"where\\n\"\n\t\t<< \" dbase - path to Geocoder-NLP database folder\\n\"\n\t\t<< \" postal_global - path to libpostal database with language classifier\\n\"\n\t\t<< \" postal_country - path to libpostal database covering country\\n\"\n\t\t<< \" address - address to be parsed (please enclose it in \\\" \\\" to ensure that its a singe argument)\\n\";\n return -1;\n }\n\n char *query = argv[4];\n std::vector< Postal::ParseResult > parsed_query;\n Postal::ParseResult nonorm;\n\n postal.set_postal_datadir(argv[2], argv[3]);\n postal.add_language(\"da\");\n postal.add_language(\"et\");\n postal.add_language(\"en\");\n postal.set_initialize_every_call(true);\n \n postal.parse(query, parsed_query, nonorm);\n\n std::cout << \"\\nAddress parsing before full normalization:\\n\\n\";\n for (auto v: nonorm)\n {\n std::cout << v.first << \" \";\n for (auto k: v.second) std::cout << k << \" \";\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n\n std::cout << \"Normalization:\\n\\n\";\n for (auto r: parsed_query)\n {\n for (auto v: r)\n {\n std::cout << v.first << \" \";\n for (auto k: v.second) std::cout << k << \" \";\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n }\n\n std::cout << std::endl;\n \n Geocoder geo(argv[1]);\n geo.set_max_queries_per_hierarchy(30);\n geo.set_max_results(25);\n \/\/geo.set_result_language(\"en\");\n\n std::vector<Geocoder::GeoResult> result;\n\n std::cout << \"Geocoder loaded\" << std::endl;\n \n geo.search(parsed_query, result);\n\n std::cout << std::setprecision(8);\n std::cout << \"Search results: \\n\\n\";\n size_t counter = 0;\n for (const Geocoder::GeoResult &r: result)\n {\n std::cout << r.title << \"\\n\"\n\t\t<< r.address << \"\\n\"\n\t\t<< r.latitude << \", \" << r.longitude << \"\\n\"\n\t\t<< r.type << \" \/ \" << r.id << \" \/ \" << r.admin_levels << \" \/ \" << r.levels_resolved << \"\\n\\n\";\n counter++;\n }\n\n std::cout << \"Number of results: \" << counter << std::endl;\n\n return 0;\n}\n<commit_msg>update demo<commit_after>#include \"postal.h\"\n#include \"geocoder.h\"\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace GeoNLP;\n\nint main(int argc, char *argv[])\n{\n Postal postal;\n \/\/postal.set_initialize_every_call(true);\n\n if (argc < 5)\n {\n std::cout << \"Use: \" << argv[0] << \" dbase postal_global postal_country address\\n\"\n\t\t<< \"where\\n\"\n\t\t<< \" dbase - path to Geocoder-NLP database folder\\n\"\n\t\t<< \" postal_global - path to libpostal database with language classifier\\n\"\n\t\t<< \" postal_country - path to libpostal database covering country\\n\"\n\t\t<< \" address - address to be parsed (please enclose it in \\\" \\\" to ensure that its a singe argument)\\n\";\n return -1;\n }\n\n char *query = argv[4];\n std::vector< Postal::ParseResult > parsed_query;\n Postal::ParseResult nonorm;\n\n postal.set_postal_datadir(argv[2], argv[3]);\n \/\/ postal.add_language(\"da\");\n \/\/ postal.add_language(\"et\");\n \/\/ postal.add_language(\"en\");\n postal.set_initialize_every_call(true);\n \n postal.parse(query, parsed_query, nonorm);\n\n std::cout << \"\\nAddress parsing before full normalization:\\n\\n\";\n for (auto v: nonorm)\n {\n std::cout << v.first << \" \";\n for (auto k: v.second) std::cout << k << \" \";\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n\n std::cout << \"Normalization:\\n\\n\";\n for (auto r: parsed_query)\n {\n for (auto v: r)\n {\n std::cout << v.first << \" \";\n for (auto k: v.second) std::cout << k << \" \";\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n }\n\n std::cout << std::endl;\n \n Geocoder geo(argv[1]);\n geo.set_max_queries_per_hierarchy(30);\n geo.set_max_results(25);\n \/\/geo.set_result_language(\"en\");\n\n std::vector<Geocoder::GeoResult> result;\n\n std::cout << \"Geocoder loaded\" << std::endl;\n \n geo.search(parsed_query, result);\n\n std::cout << std::setprecision(8);\n std::cout << \"Search results: \\n\\n\";\n size_t counter = 0;\n for (const Geocoder::GeoResult &r: result)\n {\n std::cout << r.title << \"\\n\"\n\t\t<< r.address << \"\\n\"\n\t\t<< r.latitude << \", \" << r.longitude << \"\\n\"\n\t\t<< r.type << \" \/ \" << r.id << \" \/ \" << r.admin_levels << \" \/ \" << r.levels_resolved << \"\\n\\n\";\n counter++;\n }\n\n std::cout << \"Number of results: \" << counter << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Clever language\r\n * Copyright (c) 2010 Clever Team\r\n *\r\n * Permission is hereby granted, free of charge, to any person\r\n * obtaining a copy of this software and associated documentation\r\n * files (the \"Software\"), to deal in the Software without\r\n * restriction, including without limitation the rights to use,\r\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the\r\n * Software is furnished to do so, subject to the following\r\n * conditions:\r\n * The above copyright notice and this permission notice shall be\r\n * included in all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n * OTHER DEALINGS IN THE SOFTWARE.\r\n *\r\n * $Id$\r\n *\/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include \"testrunner.h\"\r\n\r\nTestRunner::~TestRunner()\r\n{\r\n std::vector<std::string>::iterator it;\r\n\r\n for (it = tmp_files.begin(); it != tmp_files.end(); ++it) {\r\n unlink(it->c_str());\r\n }\r\n}\r\n\r\nvoid TestRunner::show_result(void) const\r\n{\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Tests: \" << files.size() << std::endl;\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Passed tests: \" << pass << std::endl;\r\n std::cout << \"Failed tests: \" << fail << std::endl;\r\n if (valgrind) {\r\n std::cout << \"Leaked tests: \" << leak << std::endl;\r\n }\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Time taken: \" << (((double)clock() - start_time) \/ CLOCKS_PER_SEC) << \" seconds\" << std::endl;\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n}\r\n\r\nvoid TestRunner::find(char* dir)\r\n{\r\n DIR *dp;\r\n std::fstream filep;\r\n std::string path;\r\n\r\n \/\/ Ignore .log files\r\n path = std::string(dir);\r\n if ((path.size()-4 == path.rfind(\".log\")) || (path.size()-4 == path.rfind(\".mem\"))) {\r\n return;\r\n }\r\n\r\n \/\/ If it's not a file, then it must be a directory\r\n filep.open(dir);\r\n if (filep.is_open()) {\r\n filep.close();\r\n files.push_back(std::string(dir));\r\n } else if ((dp = opendir(dir)) != NULL) {\r\n closedir(dp);\r\n path = std::string(dir);\r\n if (path[path.size()-1] != '\/') {\r\n path = path + \"\/\";\r\n }\r\n load_folder(path.c_str());\r\n } else {\r\n std::cout << \"Couldn't open the file or directory specified: \" << std::string(dir) << std::endl;\r\n \/\/exit(1);\r\n return;\r\n }\r\n}\r\n\r\nvoid TestRunner::run(void)\r\n{\r\n FILE *fp;\r\n std::vector<std::string>::iterator it;\r\n std::string file_name, tmp_file;\r\n pcrecpp::RE regex(\"((?s:.(?!==CODE==))+)\\\\s*==CODE==\\\\s*((?s:.(?!==RESULT==))+)\\\\s*==RESULT==\\\\s*((?s:.+))\\\\s+\");\r\n\r\n if (!files.size()) {\r\n std::cout << \"No files found.\";\r\n exit(1);\r\n }\r\n\r\n for (it = files.begin(); it != files.end(); ++it) {\r\n char result[300] = {0};\r\n std::string title, source, expect, log_line, command;\r\n unsigned int filesize;\r\n\r\n file_name = *it;\r\n\r\n tmp_file = file_name + \".tmp\";\r\n\r\n regex.FullMatch(read_file(file_name.c_str()), &title, &source, &expect);\r\n\r\n write_file(tmp_file, source);\r\n\r\n if (valgrind) {\r\n command = std::string(\"valgrind -q --tool=memcheck --leak-check=yes --num-callers=30 --log-file=\") + file_name + std::string(\".mem\");\r\n command = command + std::string(\" .\/clever -f \") + tmp_file;\r\n fp = _popen(command.c_str(), \"r\");\r\n } else {\r\n command = std::string(\".\/clever -f \") + tmp_file;\r\n fp = _popen(command.c_str(), \"r\");\r\n }\r\n fread(result, 1, sizeof(result)-1, fp);\r\n fclose(fp);\r\n\r\n \/\/ Valgrind log is empty?\r\n if (valgrind) {\r\n filesize = file_size(file_name + std::string(\".mem\"));\r\n if (filesize == 0) {\r\n remove(std::string(file_name + std::string(\".mem\")).c_str());\r\n } else {\r\n std::cout << \"[LEAK] \";\r\n leak++;\r\n }\r\n }\r\n\r\n if (pcrecpp::RE(expect).FullMatch(result)) {\r\n if ((valgrind && filesize == 0) || !valgrind) {\r\n std::cout << \"[OKAY] \";\r\n }\r\n pass++;\r\n } else {\r\n if ((valgrind && filesize == 0) || !valgrind) {\r\n std::cout << \"[FAIL] \";\r\n }\r\n log_line = std::string(\"== Expected ==\\n\") + expect + std::string(\"\\n\");\r\n log_line.append(std::string(\"== Got ==\\n\") + std::string(result));\r\n write_log(file_name,log_line);\r\n fail++;\r\n }\r\n\r\n std::cout << title << \" (\" << file_name << \")\" << std::endl;\r\n }\r\n}\r\n\r\nvoid TestRunner::write_file(std::string& name, std::string& source)\r\n{\r\n std::ofstream file(name.c_str());\r\n\r\n file << source;\r\n file.close();\r\n\r\n tmp_files.push_back(name);\r\n}\r\n\r\nstd::string TestRunner::read_file(const char* name) const\r\n{\r\n std::string source, line;\r\n std::ifstream file;\r\n\r\n file.open(name);\r\n\r\n if (!file) {\r\n std::cout << \"Couldn't open file \" << name << std::endl;\r\n exit(1);\r\n }\r\n\r\n while (!file.eof()) {\r\n getline(file, line);\r\n source += line + '\\n';\r\n }\r\n file.close();\r\n\r\n return source;\r\n}\r\n\r\nvoid TestRunner::load_folder(const char* dir)\r\n{\r\n DIR *dp, *dpr;\r\n struct dirent *dirp;\r\n std::string path,file;\r\n\r\n if ((dp = opendir(dir)) != NULL) {\r\n while ((dirp = readdir(dp)) != NULL) {\r\n if (strcmp(dirp->d_name, \".\") == 0 ||\r\n strcmp(dirp->d_name, \"..\") == 0 ||\r\n strstr(dirp->d_name, \".tmp\") ||\r\n strstr(dirp->d_name, \".svn\")) {\r\n continue;\r\n }\r\n \/\/ Ignore .log files\r\n file = std::string(dirp->d_name);\r\n if ((file.size()-4 == file.rfind(\".log\")) || (file.size()-4 == file.rfind(\".mem\"))) {\r\n continue;\r\n }\r\n \/\/ Is this a folder or a file?\r\n path = std::string(dir) + std::string(dirp->d_name) + \"\/\";\r\n if ((dpr = opendir(path.c_str())) != NULL) {\r\n closedir(dpr);\r\n load_folder(path.c_str());\r\n } else {\r\n path = std::string(dir) + std::string(dirp->d_name);\r\n files.push_back(path.c_str());\r\n }\r\n }\r\n closedir(dp);\r\n }\r\n}\r\n\r\nstd::string TestRunner::extract_folder(const char* file) const\r\n{\r\n std::string path;\r\n size_t found;\r\n\r\n path = std::string(file);\r\n found = path.rfind(\"\/\");\r\n if (found != path.npos) {\r\n path = path.substr(0,found+1);\r\n }\r\n\r\n return path;\r\n}\r\n\r\nvoid TestRunner::write_log(std::string testname, std::string message) {\r\n FILE *log;\r\n\r\n testname = testname + \".log\";\r\n log = fopen(testname.c_str(),\"w\");\r\n if (log) {\r\n fputs(message.c_str(),log);\r\n fclose(log);\r\n }\r\n}\r\n\r\nunsigned int TestRunner::file_size(std::string file) {\r\n std::ifstream stream;\r\n unsigned int length;\r\n\r\n stream.open(file.c_str());\r\n if (stream.is_open()) {\r\n stream.seekg(0,std::ios::end);\r\n length = stream.tellg();\r\n stream.close();\r\n\r\n return length;\r\n }\r\n\r\n return 0;\r\n}\r\n\r\n\/\/ ---------------------\r\n\r\nvoid usage(void)\r\n{\r\n std::cout << \"Clever Language - Testrunner\" << std::endl;\r\n std::cout << \"Usage: testrunner [options] path-of-test-file\/dir\" << std::endl;\r\n std::cout << \"\\t-m: run valgrind on each test\" << std::endl;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n TestRunner testrunner;\r\n int start_paths = 1;\r\n\r\n if (argc == 1) {\r\n usage();\r\n return 1;\r\n } else {\r\n if (std::string(argv[1]) == std::string(\"-m\")) {\r\n if (argc == 2) {\r\n \/\/ .\/testrunner -m?\r\n usage();\r\n return 1;\r\n }\r\n \/\/ .\/testrunner -m <something here>?\r\n testrunner.valgrind = true;\r\n start_paths = 2;\r\n } else {\r\n \/\/ .\/testrunner <something here>\r\n testrunner.valgrind = false;\r\n start_paths = 1;\r\n }\r\n }\r\n\r\n for (; start_paths < argc; start_paths++) {\r\n testrunner.find(argv[start_paths]);\r\n }\r\n testrunner.run();\r\n testrunner.show_result();\r\n\r\n return 0;\r\n}<commit_msg>_popen -> popen<commit_after>\/*\r\n * Clever language\r\n * Copyright (c) 2010 Clever Team\r\n *\r\n * Permission is hereby granted, free of charge, to any person\r\n * obtaining a copy of this software and associated documentation\r\n * files (the \"Software\"), to deal in the Software without\r\n * restriction, including without limitation the rights to use,\r\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the\r\n * Software is furnished to do so, subject to the following\r\n * conditions:\r\n * The above copyright notice and this permission notice shall be\r\n * included in all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n * OTHER DEALINGS IN THE SOFTWARE.\r\n *\r\n * $Id$\r\n *\/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include \"testrunner.h\"\r\n\r\nTestRunner::~TestRunner()\r\n{\r\n std::vector<std::string>::iterator it;\r\n\r\n for (it = tmp_files.begin(); it != tmp_files.end(); ++it) {\r\n unlink(it->c_str());\r\n }\r\n}\r\n\r\nvoid TestRunner::show_result(void) const\r\n{\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Tests: \" << files.size() << std::endl;\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Passed tests: \" << pass << std::endl;\r\n std::cout << \"Failed tests: \" << fail << std::endl;\r\n if (valgrind) {\r\n std::cout << \"Leaked tests: \" << leak << std::endl;\r\n }\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n std::cout << \"Time taken: \" << (((double)clock() - start_time) \/ CLOCKS_PER_SEC) << \" seconds\" << std::endl;\r\n std::cout << \"-----------------------------------\" << std::endl;\r\n}\r\n\r\nvoid TestRunner::find(char* dir)\r\n{\r\n DIR *dp;\r\n std::fstream filep;\r\n std::string path;\r\n\r\n \/\/ Ignore .log files\r\n path = std::string(dir);\r\n if ((path.size()-4 == path.rfind(\".log\")) || (path.size()-4 == path.rfind(\".mem\"))) {\r\n return;\r\n }\r\n\r\n \/\/ If it's not a file, then it must be a directory\r\n filep.open(dir);\r\n if (filep.is_open()) {\r\n filep.close();\r\n files.push_back(std::string(dir));\r\n } else if ((dp = opendir(dir)) != NULL) {\r\n closedir(dp);\r\n path = std::string(dir);\r\n if (path[path.size()-1] != '\/') {\r\n path = path + \"\/\";\r\n }\r\n load_folder(path.c_str());\r\n } else {\r\n std::cout << \"Couldn't open the file or directory specified: \" << std::string(dir) << std::endl;\r\n \/\/exit(1);\r\n return;\r\n }\r\n}\r\n\r\nvoid TestRunner::run(void)\r\n{\r\n FILE *fp;\r\n std::vector<std::string>::iterator it;\r\n std::string file_name, tmp_file;\r\n pcrecpp::RE regex(\"((?s:.(?!==CODE==))+)\\\\s*==CODE==\\\\s*((?s:.(?!==RESULT==))+)\\\\s*==RESULT==\\\\s*((?s:.+))\\\\s+\");\r\n\r\n if (!files.size()) {\r\n std::cout << \"No files found.\";\r\n exit(1);\r\n }\r\n\r\n for (it = files.begin(); it != files.end(); ++it) {\r\n char result[300] = {0};\r\n std::string title, source, expect, log_line, command;\r\n unsigned int filesize;\r\n\r\n file_name = *it;\r\n\r\n tmp_file = file_name + \".tmp\";\r\n\r\n regex.FullMatch(read_file(file_name.c_str()), &title, &source, &expect);\r\n\r\n write_file(tmp_file, source);\r\n\r\n if (valgrind) {\r\n command = std::string(\"valgrind -q --tool=memcheck --leak-check=yes --num-callers=30 --log-file=\") + file_name + std::string(\".mem\");\r\n command = command + std::string(\" .\/clever -f \") + tmp_file;\r\n fp = popen(command.c_str(), \"r\");\r\n } else {\r\n command = std::string(\".\/clever -f \") + tmp_file;\r\n fp = popen(command.c_str(), \"r\");\r\n }\r\n fread(result, 1, sizeof(result)-1, fp);\r\n fclose(fp);\r\n\r\n \/\/ Valgrind log is empty?\r\n if (valgrind) {\r\n filesize = file_size(file_name + std::string(\".mem\"));\r\n if (filesize == 0) {\r\n remove(std::string(file_name + std::string(\".mem\")).c_str());\r\n } else {\r\n std::cout << \"[LEAK] \";\r\n leak++;\r\n }\r\n }\r\n\r\n if (pcrecpp::RE(expect).FullMatch(result)) {\r\n if ((valgrind && filesize == 0) || !valgrind) {\r\n std::cout << \"[OKAY] \";\r\n }\r\n pass++;\r\n } else {\r\n if ((valgrind && filesize == 0) || !valgrind) {\r\n std::cout << \"[FAIL] \";\r\n }\r\n log_line = std::string(\"== Expected ==\\n\") + expect + std::string(\"\\n\");\r\n log_line.append(std::string(\"== Got ==\\n\") + std::string(result));\r\n write_log(file_name,log_line);\r\n fail++;\r\n }\r\n\r\n std::cout << title << \" (\" << file_name << \")\" << std::endl;\r\n }\r\n}\r\n\r\nvoid TestRunner::write_file(std::string& name, std::string& source)\r\n{\r\n std::ofstream file(name.c_str());\r\n\r\n file << source;\r\n file.close();\r\n\r\n tmp_files.push_back(name);\r\n}\r\n\r\nstd::string TestRunner::read_file(const char* name) const\r\n{\r\n std::string source, line;\r\n std::ifstream file;\r\n\r\n file.open(name);\r\n\r\n if (!file) {\r\n std::cout << \"Couldn't open file \" << name << std::endl;\r\n exit(1);\r\n }\r\n\r\n while (!file.eof()) {\r\n getline(file, line);\r\n source += line + '\\n';\r\n }\r\n file.close();\r\n\r\n return source;\r\n}\r\n\r\nvoid TestRunner::load_folder(const char* dir)\r\n{\r\n DIR *dp, *dpr;\r\n struct dirent *dirp;\r\n std::string path,file;\r\n\r\n if ((dp = opendir(dir)) != NULL) {\r\n while ((dirp = readdir(dp)) != NULL) {\r\n if (strcmp(dirp->d_name, \".\") == 0 ||\r\n strcmp(dirp->d_name, \"..\") == 0 ||\r\n strstr(dirp->d_name, \".tmp\") ||\r\n strstr(dirp->d_name, \".svn\")) {\r\n continue;\r\n }\r\n \/\/ Ignore .log files\r\n file = std::string(dirp->d_name);\r\n if ((file.size()-4 == file.rfind(\".log\")) || (file.size()-4 == file.rfind(\".mem\"))) {\r\n continue;\r\n }\r\n \/\/ Is this a folder or a file?\r\n path = std::string(dir) + std::string(dirp->d_name) + \"\/\";\r\n if ((dpr = opendir(path.c_str())) != NULL) {\r\n closedir(dpr);\r\n load_folder(path.c_str());\r\n } else {\r\n path = std::string(dir) + std::string(dirp->d_name);\r\n files.push_back(path.c_str());\r\n }\r\n }\r\n closedir(dp);\r\n }\r\n}\r\n\r\nstd::string TestRunner::extract_folder(const char* file) const\r\n{\r\n std::string path;\r\n size_t found;\r\n\r\n path = std::string(file);\r\n found = path.rfind(\"\/\");\r\n if (found != path.npos) {\r\n path = path.substr(0,found+1);\r\n }\r\n\r\n return path;\r\n}\r\n\r\nvoid TestRunner::write_log(std::string testname, std::string message) {\r\n FILE *log;\r\n\r\n testname = testname + \".log\";\r\n log = fopen(testname.c_str(),\"w\");\r\n if (log) {\r\n fputs(message.c_str(),log);\r\n fclose(log);\r\n }\r\n}\r\n\r\nunsigned int TestRunner::file_size(std::string file) {\r\n std::ifstream stream;\r\n unsigned int length;\r\n\r\n stream.open(file.c_str());\r\n if (stream.is_open()) {\r\n stream.seekg(0,std::ios::end);\r\n length = stream.tellg();\r\n stream.close();\r\n\r\n return length;\r\n }\r\n\r\n return 0;\r\n}\r\n\r\n\/\/ ---------------------\r\n\r\nvoid usage(void)\r\n{\r\n std::cout << \"Clever Language - Testrunner\" << std::endl;\r\n std::cout << \"Usage: testrunner [options] path-of-test-file\/dir\" << std::endl;\r\n std::cout << \"\\t-m: run valgrind on each test\" << std::endl;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n TestRunner testrunner;\r\n int start_paths = 1;\r\n\r\n if (argc == 1) {\r\n usage();\r\n return 1;\r\n } else {\r\n if (std::string(argv[1]) == std::string(\"-m\")) {\r\n if (argc == 2) {\r\n \/\/ .\/testrunner -m?\r\n usage();\r\n return 1;\r\n }\r\n \/\/ .\/testrunner -m <something here>?\r\n testrunner.valgrind = true;\r\n start_paths = 2;\r\n } else {\r\n \/\/ .\/testrunner <something here>\r\n testrunner.valgrind = false;\r\n start_paths = 1;\r\n }\r\n }\r\n\r\n for (; start_paths < argc; start_paths++) {\r\n testrunner.find(argv[start_paths]);\r\n }\r\n testrunner.run();\r\n testrunner.show_result();\r\n\r\n return 0;\r\n}<|endoftext|>"} {"text":"<commit_before>\/\/ *************************************************************************\n\/\/ * GSM TA\/ME library\n\/\/ *\n\/\/ * File: gsm_parser.cc\n\/\/ *\n\/\/ * Purpose: Parser to parse MA\/TA result strings\n\/\/ *\n\/\/ * Author: Peter Hofmann (software@pxh.de)\n\/\/ *\n\/\/ * Created: 13.5.1999\n\/\/ *************************************************************************\n\n#ifdef HAVE_CONFIG_H\n#include <gsm_config.h>\n#endif\n#include <gsmlib\/gsm_parser.h>\n#include <gsmlib\/gsm_nls.h>\n#include <ctype.h>\n#include <assert.h>\n#include <sstream>\n\nusing namespace gsmlib;\n\n\/\/ Parser members\n\nint Parser::nextChar(bool skipWhiteSpace)\n{\n if (skipWhiteSpace)\n while (_i < _s.length() && isspace(_s[_i])) ++_i;\n\n if (_i == _s.length())\n {\n _eos = true;\n return -1;\n }\n\n return _s[_i++];\n}\n\nbool Parser::checkEmptyParameter(bool allowNoParameter) throw(GsmException)\n{\n int c = nextChar();\n if (c == ',' || c == -1)\n {\n if (allowNoParameter)\n\t{\n\t putBackChar();\n\t return true;\n\t}\n else\n\tthrowParseException(_(\"expected parameter\"));\n\n putBackChar();\n }\n return false;\n}\n\nstd::string Parser::parseString2(bool stringWithQuotationMarks)\n throw(GsmException)\n{\n int c;\n std::string result;\n if (parseChar('\"', true)) \/\/ OK, std::string starts and ends with quotation mark\n if (stringWithQuotationMarks)\n {\n\t\/\/ read till end of line\n\twhile ((c = nextChar(false)) != -1)\n\t result += c;\n\n\t\/\/ check for \"\"\" at end of line\n\tif (result.length() == 0 || result[result.length() - 1] != '\"')\n\t throwParseException(_(\"expected '\\\"'\"));\n\n\t\/\/ remove \"\"\" at the end\n\tresult.resize(result.length() - 1);\n }\n else\n {\n\t\/\/ read till next \"\"\"\n\twhile ((c = nextChar(false)) != '\"')\n\t if (c == -1)\n\t throwParseException();\n\t else\n\t result += c;\n }\n else \/\/ std::string ends with \",\" or EOL\n {\n c = nextChar(false);\n while (c != ',' && c != -1)\n\t{\n\t result += c;\n\t c = nextChar(false);\n\t}\n if (c == ',') putBackChar();\n }\n\n return result;\n}\n\nint Parser::parseInt2() throw(GsmException)\n{\n std::string s;\n int c;\n int result;\n\n while (isdigit(c = nextChar())) s += c;\n\n putBackChar();\n if (s.length() == 0)\n throwParseException(_(\"expected number\"));\n\n std::istringstream is(s.c_str());\n is >> result;\n return result;\n}\n\nvoid Parser::throwParseException(std::string message) throw(GsmException)\n{\n std::ostringstream os;\n if (message.length() == 0)\n throw GsmException(stringPrintf(_(\"unexpected end of std::string '%s'\"),\n _s.c_str()), ParserError);\n else\n throw GsmException(message +\n stringPrintf(_(\" (at position %d of std::string '%s')\"), _i,\n _s.c_str()), ParserError);\n}\n\nParser::Parser(std::string s) : _i(0), _s(s), _eos(false)\n{\n}\n\nbool Parser::parseChar(char c, bool allowNoChar) throw(GsmException)\n{\n if (nextChar() != c)\n {\n if (allowNoChar)\n\t{\n\t putBackChar();\n\t return false;\n\t}\n else\n\tthrowParseException(stringPrintf(_(\"expected '%c'\"), c));\n }\n return true;\n}\n\nstd::vector<std::string> Parser::parseStringList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::vector<std::string> result;\n if (checkEmptyParameter(allowNoList)) return result;\n\n parseChar('(');\n if (nextChar() != ')')\n {\n putBackChar();\n while (1)\n\t{\n\t result.push_back(parseString());\n\t int c = nextChar();\n\t if (c == ')')\n\t break;\n\t if (c == -1)\n\t throwParseException();\n\t if (c != ',')\n\t throwParseException(_(\"expected ')' or ','\"));\n\t}\n }\n\n return result;\n}\n\nstd::vector<bool> Parser::parseIntList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n bool isRange = false;\n std::vector<bool> result;\n int resultCapacity = 0;\n unsigned int saveI = _i;\n\n if (checkEmptyParameter(allowNoList)) return result;\n\n \/\/ check for the case of a integer list consisting of only one parameter\n \/\/ some TAs omit the parentheses in this case\n if (isdigit(nextChar()))\n {\n putBackChar();\n int num = parseInt();\n result.resize(num + 1, false);\n result[num] = true;\n return result;\n }\n putBackChar();\n\n \/\/ run in two passes\n \/\/ pass 0: find capacity needed for result\n \/\/ pass 1: resize result and fill it in\n for (int pass = 0; pass < 2; ++pass)\n {\n if (pass == 1)\n\t{\n\t _i = saveI;\n\t result.resize(resultCapacity + 1, false);\n\t}\n\n parseChar('(');\n if (nextChar() != ')')\n\t{\n\t putBackChar();\n\t int lastInt = -1;\n\t while (1)\n\t {\n\t int thisInt = parseInt();\n\n\t if (isRange)\n\t\t{\n\t\t assert(lastInt != -1);\n\t\t if (lastInt <= thisInt)\n\t\t for (int i = lastInt; i < thisInt; ++i)\n\t\t {\n\t\t\tif (i > resultCapacity)\n\t\t\t resultCapacity = i;\n\t\t\tif (pass == 1)\n\t\t\t result[i] = true;\n\t\t }\n\t\t else\n\t\t for (int i = thisInt; i < lastInt; ++i)\n\t\t {\n\t\t\tif (i > resultCapacity)\n\t\t\t resultCapacity = i;\n\t\t\tif (pass == 1)\n\t\t\t result[i] = true;\n\t\t }\n\t\t isRange = false;\n\t\t}\n\n\t if (thisInt > resultCapacity)\n\t\tresultCapacity = thisInt;\n\t if (pass == 1)\n\t\tresult[thisInt] = true;\n\t lastInt = thisInt;\n\n\t int c = nextChar();\n\t if (c == ')')\n\t\tbreak;\n\n\t if (c == -1)\n\t\tthrowParseException();\n\n\t if (c != ',' && c != '-')\n\t\tthrowParseException(_(\"expected ')', ',' or '-'\"));\n\n\t if (c == ',')\n\t\tisRange = false;\n\t else \/\/ is '-'\n\t\tif (isRange)\n\t\t throwParseException(_(\"range of the form a-b-c not allowed\"));\n\t\telse\n\t\t isRange = true;\n\t }\n\t}\n }\n if (isRange)\n throwParseException(_(\"range of the form a- no allowed\"));\n return result;\n}\n\nstd::vector<ParameterRange> Parser::parseParameterRangeList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::vector<ParameterRange> result;\n if (checkEmptyParameter(allowNoList)) return result;\n\n result.push_back(parseParameterRange());\n while (parseComma(true))\n {\n result.push_back(parseParameterRange());\n }\n\n return result;\n}\n\nParameterRange Parser::parseParameterRange(bool allowNoParameterRange)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n ParameterRange result;\n if (checkEmptyParameter(allowNoParameterRange)) return result;\n\n parseChar('(');\n result._parameter = parseString();\n parseComma();\n result._range = parseRange(false, true);\n parseChar(')');\n\n return result;\n}\n\nIntRange Parser::parseRange(bool allowNoRange, bool allowNonRange)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n IntRange result;\n if (checkEmptyParameter(allowNoRange)) return result;\n\n parseChar('(');\n result._low = parseInt();\n \/\/ allow non-ranges is allowNonRange == true\n if (parseChar('-', allowNonRange))\n result._high = parseInt();\n parseChar(')');\n\n return result;\n}\n\nint Parser::parseInt(bool allowNoInt) throw(GsmException)\n{\n \/\/ handle case of empty parameter\n int result = NOT_SET;\n if (checkEmptyParameter(allowNoInt)) return result;\n\n result = parseInt2();\n\n return result;\n}\n\nstd::string Parser::parseString(bool allowNoString,\n\t\t\t\tbool stringWithQuotationMarks)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::string result;\n if (checkEmptyParameter(allowNoString)) return result;\n\n result = parseString2(stringWithQuotationMarks);\n\n return result;\n}\n\nbool Parser::parseComma(bool allowNoComma) throw(GsmException)\n{\n if (nextChar() != ',')\n {\n if(allowNoComma)\n\t{\n\t putBackChar();\n\t return false;\n\t}\n else\n\tthrowParseException(_(\"expected comma\"));\n }\n return true;\n}\n\nstd::string Parser::parseEol() throw(GsmException)\n{\n std::string result;\n int c;\n\n while ((c = nextChar()) != -1) result += c;\n return result;\n}\n\nvoid Parser::checkEol() throw(GsmException)\n{\n if (nextChar() != -1)\n {\n putBackChar();\n throwParseException(_(\"expected end of line\"));\n }\n}\n\nstd::string Parser::getEol()\n{\n std::string result;\n int c;\n unsigned int saveI = _i;\n bool saveEos = _eos;\n\n while ((c = nextChar()) != -1) result += c;\n _i = saveI;\n _eos = saveEos;\n return result;\n}\n<commit_msg>fix parseInt2 expected number<commit_after>\/\/ *************************************************************************\n\/\/ * GSM TA\/ME library\n\/\/ *\n\/\/ * File: gsm_parser.cc\n\/\/ *\n\/\/ * Purpose: Parser to parse MA\/TA result strings\n\/\/ *\n\/\/ * Author: Peter Hofmann (software@pxh.de)\n\/\/ *\n\/\/ * Created: 13.5.1999\n\/\/ *************************************************************************\n\n#ifdef HAVE_CONFIG_H\n#include <gsm_config.h>\n#endif\n#include <gsmlib\/gsm_parser.h>\n#include <gsmlib\/gsm_nls.h>\n#include <ctype.h>\n#include <assert.h>\n#include <sstream>\n\nusing namespace gsmlib;\n\n\/\/ Parser members\n\nint Parser::nextChar(bool skipWhiteSpace)\n{\n if (skipWhiteSpace)\n while (_i < _s.length() && isspace(_s[_i])) ++_i;\n\n if (_i == _s.length())\n {\n _eos = true;\n return -1;\n }\n\n return _s[_i++];\n}\n\nbool Parser::checkEmptyParameter(bool allowNoParameter) throw(GsmException)\n{\n int c = nextChar();\n if (c == ',' || c == -1)\n {\n if (allowNoParameter)\n\t{\n\t putBackChar();\n\t return true;\n\t}\n else\n\tthrowParseException(_(\"expected parameter\"));\n\n }\n putBackChar();\n return false;\n}\n\nstd::string Parser::parseString2(bool stringWithQuotationMarks)\n throw(GsmException)\n{\n int c;\n std::string result;\n if (parseChar('\"', true)) \/\/ OK, std::string starts and ends with quotation mark\n if (stringWithQuotationMarks)\n {\n\t\/\/ read till end of line\n\twhile ((c = nextChar(false)) != -1)\n\t result += c;\n\n\t\/\/ check for \"\"\" at end of line\n\tif (result.length() == 0 || result[result.length() - 1] != '\"')\n\t throwParseException(_(\"expected '\\\"'\"));\n\n\t\/\/ remove \"\"\" at the end\n\tresult.resize(result.length() - 1);\n }\n else\n {\n\t\/\/ read till next \"\"\"\n\twhile ((c = nextChar(false)) != '\"')\n\t if (c == -1)\n\t throwParseException();\n\t else\n\t result += c;\n }\n else \/\/ std::string ends with \",\" or EOL\n {\n c = nextChar(false);\n while (c != ',' && c != -1)\n\t{\n\t result += c;\n\t c = nextChar(false);\n\t}\n if (c == ',') putBackChar();\n }\n\n return result;\n}\n\nint Parser::parseInt2() throw(GsmException)\n{\n std::string s;\n int c;\n int result;\n\n while (isdigit(c = nextChar())) s += c;\n\n putBackChar();\n if (s.length() == 0)\n throwParseException(_(\"expected number\"));\n\n std::istringstream is(s.c_str());\n is >> result;\n return result;\n}\n\nvoid Parser::throwParseException(std::string message) throw(GsmException)\n{\n std::ostringstream os;\n if (message.length() == 0)\n throw GsmException(stringPrintf(_(\"unexpected end of std::string '%s'\"),\n _s.c_str()), ParserError);\n else\n throw GsmException(message +\n stringPrintf(_(\" (at position %d of std::string '%s')\"), _i,\n _s.c_str()), ParserError);\n}\n\nParser::Parser(std::string s) : _i(0), _s(s), _eos(false)\n{\n}\n\nbool Parser::parseChar(char c, bool allowNoChar) throw(GsmException)\n{\n if (nextChar() != c)\n {\n if (allowNoChar)\n\t{\n\t putBackChar();\n\t return false;\n\t}\n else\n\tthrowParseException(stringPrintf(_(\"expected '%c'\"), c));\n }\n return true;\n}\n\nstd::vector<std::string> Parser::parseStringList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::vector<std::string> result;\n if (checkEmptyParameter(allowNoList)) return result;\n\n parseChar('(');\n if (nextChar() != ')')\n {\n putBackChar();\n while (1)\n\t{\n\t result.push_back(parseString());\n\t int c = nextChar();\n\t if (c == ')')\n\t break;\n\t if (c == -1)\n\t throwParseException();\n\t if (c != ',')\n\t throwParseException(_(\"expected ')' or ','\"));\n\t}\n }\n\n return result;\n}\n\nstd::vector<bool> Parser::parseIntList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n bool isRange = false;\n std::vector<bool> result;\n int resultCapacity = 0;\n unsigned int saveI = _i;\n\n if (checkEmptyParameter(allowNoList)) return result;\n\n \/\/ check for the case of a integer list consisting of only one parameter\n \/\/ some TAs omit the parentheses in this case\n if (isdigit(nextChar()))\n {\n putBackChar();\n int num = parseInt();\n result.resize(num + 1, false);\n result[num] = true;\n return result;\n }\n putBackChar();\n\n \/\/ run in two passes\n \/\/ pass 0: find capacity needed for result\n \/\/ pass 1: resize result and fill it in\n for (int pass = 0; pass < 2; ++pass)\n {\n if (pass == 1)\n\t{\n\t _i = saveI;\n\t result.resize(resultCapacity + 1, false);\n\t}\n\n parseChar('(');\n if (nextChar() != ')')\n\t{\n\t putBackChar();\n\t int lastInt = -1;\n\t while (1)\n\t {\n\t int thisInt = parseInt();\n\n\t if (isRange)\n\t\t{\n\t\t assert(lastInt != -1);\n\t\t if (lastInt <= thisInt)\n\t\t for (int i = lastInt; i < thisInt; ++i)\n\t\t {\n\t\t\tif (i > resultCapacity)\n\t\t\t resultCapacity = i;\n\t\t\tif (pass == 1)\n\t\t\t result[i] = true;\n\t\t }\n\t\t else\n\t\t for (int i = thisInt; i < lastInt; ++i)\n\t\t {\n\t\t\tif (i > resultCapacity)\n\t\t\t resultCapacity = i;\n\t\t\tif (pass == 1)\n\t\t\t result[i] = true;\n\t\t }\n\t\t isRange = false;\n\t\t}\n\n\t if (thisInt > resultCapacity)\n\t\tresultCapacity = thisInt;\n\t if (pass == 1)\n\t\tresult[thisInt] = true;\n\t lastInt = thisInt;\n\n\t int c = nextChar();\n\t if (c == ')')\n\t\tbreak;\n\n\t if (c == -1)\n\t\tthrowParseException();\n\n\t if (c != ',' && c != '-')\n\t\tthrowParseException(_(\"expected ')', ',' or '-'\"));\n\n\t if (c == ',')\n\t\tisRange = false;\n\t else \/\/ is '-'\n\t\tif (isRange)\n\t\t throwParseException(_(\"range of the form a-b-c not allowed\"));\n\t\telse\n\t\t isRange = true;\n\t }\n\t}\n }\n if (isRange)\n throwParseException(_(\"range of the form a- no allowed\"));\n return result;\n}\n\nstd::vector<ParameterRange> Parser::parseParameterRangeList(bool allowNoList)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::vector<ParameterRange> result;\n if (checkEmptyParameter(allowNoList)) return result;\n\n result.push_back(parseParameterRange());\n while (parseComma(true))\n {\n result.push_back(parseParameterRange());\n }\n\n return result;\n}\n\nParameterRange Parser::parseParameterRange(bool allowNoParameterRange)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n ParameterRange result;\n if (checkEmptyParameter(allowNoParameterRange)) return result;\n\n parseChar('(');\n result._parameter = parseString();\n parseComma();\n result._range = parseRange(false, true);\n parseChar(')');\n\n return result;\n}\n\nIntRange Parser::parseRange(bool allowNoRange, bool allowNonRange)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n IntRange result;\n if (checkEmptyParameter(allowNoRange)) return result;\n\n parseChar('(');\n result._low = parseInt();\n \/\/ allow non-ranges is allowNonRange == true\n if (parseChar('-', allowNonRange))\n result._high = parseInt();\n parseChar(')');\n\n return result;\n}\n\nint Parser::parseInt(bool allowNoInt) throw(GsmException)\n{\n \/\/ handle case of empty parameter\n int result = NOT_SET;\n if (checkEmptyParameter(allowNoInt)) return result;\n\n result = parseInt2();\n\n return result;\n}\n\nstd::string Parser::parseString(bool allowNoString,\n\t\t\t\tbool stringWithQuotationMarks)\n throw(GsmException)\n{\n \/\/ handle case of empty parameter\n std::string result;\n if (checkEmptyParameter(allowNoString)) return result;\n\n result = parseString2(stringWithQuotationMarks);\n\n return result;\n}\n\nbool Parser::parseComma(bool allowNoComma) throw(GsmException)\n{\n if (nextChar() != ',')\n {\n if(allowNoComma)\n\t{\n\t putBackChar();\n\t return false;\n\t}\n else\n\tthrowParseException(_(\"expected comma\"));\n }\n return true;\n}\n\nstd::string Parser::parseEol() throw(GsmException)\n{\n std::string result;\n int c;\n\n while ((c = nextChar()) != -1) result += c;\n return result;\n}\n\nvoid Parser::checkEol() throw(GsmException)\n{\n if (nextChar() != -1)\n {\n putBackChar();\n throwParseException(_(\"expected end of line\"));\n }\n}\n\nstd::string Parser::getEol()\n{\n std::string result;\n int c;\n unsigned int saveI = _i;\n bool saveEos = _eos;\n\n while ((c = nextChar()) != -1) result += c;\n _i = saveI;\n _eos = saveEos;\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"hdfscpp.h\"\n\n#include <iostream>\n\n#include <assert.h>\n\n#include \"filebuf.h\"\n#include <vector>\n\n#include <zlib.h>\n\/**********************************************************************\/\n\n\/** Reads a int written by java's DataOutput#writeInt\n *\n * FIXME Move to propper namespace\n *\/\ninline int32_t ReadInt(tmacam::filebuf* data) {\n\tassert(sizeof(int32_t) == 4);\n\tconst char* bytes = data->read(sizeof(int32_t));\n\treturn (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |\n\t\t ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));\n}\n\n \n\/**********************************************************************\/\nnamespace tmacam {\n\nclass HdfsDumpReader {\npublic:\n static const size_t kDefaultBufferSize = 10<<20; \/\/ 10 MB\n\n HdfsDumpReader(hdfs::FileSystem* fs,\n const char* path,\n size_t buffer_size = kDefaultBufferSize);\n\n bool HasNext();\n\n tmacam::filebuf GetNext();\n\n void ReadFile();\nprivate:\n hdfs::FileSystem* fs_;\n std::string path_;\n hdfs::File file_;\n tOffset file_size_;\n size_t buffer_size_;\n std::vector<char> buffer_;\n \/\/ Used for iteration control and state-keeping\n size_t bytes_read_;\n tmacam::filebuf available_data_;\n const tmacam::filebuf empty_file_buffer_;\n\n \/\/ No copy, no atribution and no default constructor for this class\n DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);\n HdfsDumpReader();\n};\n\n\nHdfsDumpReader::HdfsDumpReader(hdfs::FileSystem* fs, const char* path,\n size_t buffer_size) :\n fs_(fs),\n path_(path),\n file_(*fs, path, O_RDONLY, buffer_size, 0, 0),\n file_size_(0), \/\/ we will get to you in a momment, sir\n buffer_size_(buffer_size),\n buffer_(buffer_size),\n bytes_read_(0),\n available_data_(),\n empty_file_buffer_()\n{\n hdfs::FileInfoList file_info;\n fs_->GetPathInfo(path, &file_info);\n file_size_ = file_info->mSize;\n std::cout << \"Constructor \" << file_.Available() << std::endl;\n}\n\nbool HdfsDumpReader::HasNext()\n{\n \/\/ We won't be done untill we have read all the file and\n \/\/ there is nothing left in available_data_ to be read.\n return (bytes_read_ < file_size_) || !available_data_.eof();\n}\n\ntmacam::filebuf HdfsDumpReader::GetNext()\n{\n \/\/ Missing closures?\n \/* First of all, remember that this code originally was something along\n * the lines:\n *\n * for (bytes_read_ = 0; bytes_read_ < file_size_;) {\n * (...)\n * try {\n * while(!available_data_.eof()) {\n * (...)\n * \/\/ yield data unit\n * }\n * } catch (std::out_of_range) {\n * (...)\n * }\n *\n * Missing closures now? \n *\n * Using Pread() and exceptions for doing this is ugly and lame.\n * We should have used Read() and proper tests but, you know what,\n * this works and is easy to understand -- and this scores +1 in\n * my book.\n *\/\n\n assert(HasNext()); \/\/ Simplify corner cases for the next if\n \/\/ Do we need to perform a read operation? Can we perform a read?\n if (available_data_.eof() && (bytes_read_ < file_size_)) {\n tSize read_length = file_.Pread(bytes_read_, &buffer_[0], buffer_size_);\n bytes_read_ += read_length;\n available_data_ = tmacam::filebuf(&buffer_[0], read_length);\n }\n\n \n return tmacam::filebuf();\n}\n\nvoid HdfsDumpReader::ReadFile()\n{\n size_t data_left_len = 0;\n\n for (bytes_read_ = 0; bytes_read_ < file_size_;) {\n \/* Using Pread() and exceptions for doing this is ugly and lame.\n * We should have used Read() and proper tests but, you know what,\n * this works and is easy to understand -- and this scores +1 in\n * my book.\n *\/\n tSize read_length = file_.Pread(bytes_read_, &buffer_[0], buffer_size_);\n bytes_read_ += read_length;\n\n available_data_ = tmacam::filebuf(&buffer_[0], read_length);\n\n std::cout << \"READ \" << read_length << std::endl;\n\n try {\n while (!available_data_.eof()) {\n \/\/ Save current progress\n data_left_len = available_data_.len();\n \/\/ Read header, payload and CRC. Abort if payload is too big\n int32_t payload_len = ReadInt(&available_data_);\n assert(payload_len + 2*sizeof(int32_t) < buffer_size_);\n const char* payload_data = available_data_.read(payload_len);\n int32_t expected_checksum = ReadInt(&available_data_);\n#ifndef DUMPREADER_FAST_PASS\n \/\/ Calc CRC32\n uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);\n if (expected_checksum != static_cast<int32_t>(crc)) {\n std::cerr << \"CRC MISSMATCH -- found \" << crc << \n \" expected\" << expected_checksum <<\n std::endl; \n exit(EXIT_FAILURE);\n }\n#endif\n std::cout << \"P: \" << payload_len << std::endl;\n }\n } catch(std::out_of_range) {\n std::cout << \"ooops \" << std::endl;\n \/\/ not enough data... \n \/\/ rewind reading position\n bytes_read_ -= data_left_len;\n }\n }\n}\n\n\n}; \/\/ namespace tmacam\n\n\/**********************************************************************\/\n\n\nvoid ShowUsage()\n{\n std::cerr << \"Usage: hdfsls <path> \" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n using namespace tmacam;\n\n \/\/ Check command line arguments\n if ( argc != 2) {\n std::cerr << \"Wrong number of arguments\" << std::endl;\n ShowUsage();\n exit(EXIT_FAILURE);\n }\n const char* path = argv[1];\n\n \/\/ Connect to HDFS \/ get filesystem handle\n hdfs::FileSystem fs; \n\n \/\/ Path is a file, right?\n if (!fs.Exists(path)) {\n std::cerr << \"Path '\" << path << \"' does not exist.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n hdfs::FileInfoList path_info;\n fs.GetPathInfo(path, &path_info);\n if (path_info->mKind != kObjectKindFile ) {\n std::cerr << \"Path '\" << path << \"' is not a regular file.\"\n << std::endl;\n exit(EXIT_FAILURE);\n }\n\n HdfsDumpReader reader(&fs, path);\n\n reader.ReadFile();\n\n\n \n\treturn 0;\n}\n\n\/\/ vim: et ai sts=4 ts=4 sw=4\n<commit_msg>HdfsDumpReader::GetNext() initial code landed.<commit_after>#include \"hdfscpp.h\"\n\n#include <iostream>\n\n#include <assert.h>\n\n#include \"filebuf.h\"\n#include <vector>\n\n#include <zlib.h>\n\/**********************************************************************\/\n\n\/** Reads a int written by java's DataOutput#writeInt\n *\n * FIXME Move to propper namespace\n *\/\ninline int32_t ReadInt(tmacam::filebuf* data) {\n\tassert(sizeof(int32_t) == 4);\n\tconst char* bytes = data->read(sizeof(int32_t));\n\treturn (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |\n\t\t ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));\n}\n\n \n\/**********************************************************************\/\nnamespace tmacam {\n\nclass HdfsDumpReader {\npublic:\n static const size_t kDefaultBufferSize = 10<<20; \/\/ 10 MB\n\n HdfsDumpReader(hdfs::FileSystem* fs,\n const char* path,\n size_t buffer_size = kDefaultBufferSize);\n\n bool HasNext();\n\n tmacam::filebuf GetNext();\n\n void ReadFile();\nprivate:\n hdfs::FileSystem* fs_;\n std::string path_;\n hdfs::File file_;\n tOffset file_size_;\n size_t buffer_size_;\n std::vector<char> buffer_;\n \/\/ Used for iteration control and state-keeping\n size_t bytes_read_;\n tmacam::filebuf available_data_;\n const tmacam::filebuf empty_file_buffer_;\n\n \/\/ No copy, no atribution and no default constructor for this class\n DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);\n HdfsDumpReader();\n};\n\n\nHdfsDumpReader::HdfsDumpReader(hdfs::FileSystem* fs, const char* path,\n size_t buffer_size) :\n fs_(fs),\n path_(path),\n file_(*fs, path, O_RDONLY, buffer_size, 0, 0),\n file_size_(0), \/\/ we will get to you in a momment, sir\n buffer_size_(buffer_size),\n buffer_(buffer_size),\n bytes_read_(0),\n available_data_(),\n empty_file_buffer_()\n{\n hdfs::FileInfoList file_info;\n fs_->GetPathInfo(path, &file_info);\n file_size_ = file_info->mSize;\n std::cout << \"Constructor \" << file_.Available() << std::endl;\n}\n\nbool HdfsDumpReader::HasNext()\n{\n \/\/ We won't be done untill we have read all the file and\n \/\/ there is nothing left in available_data_ to be read.\n return (bytes_read_ < file_size_) || !available_data_.eof();\n}\n\ntmacam::filebuf HdfsDumpReader::GetNext()\n{\n \/\/ Missing closures?\n \/* First of all, remember that this code originally was something along\n * the lines:\n *\n * for (bytes_read_ = 0; bytes_read_ < file_size_;) {\n * (...)\n * try {\n * while(!available_data_.eof()) {\n * (...)\n * \/\/ yield data unit\n * }\n * } catch (std::out_of_range) {\n * (...)\n * }\n *\n * Missing closures now? \n *\n * Using Pread() and exceptions for doing this is ugly and lame.\n * We should have used Read() and proper tests but, you know what,\n * this works and is easy to understand -- and this scores +1 in\n * my book.\n *\/\n\n assert(HasNext()); \/\/ Simplify corner cases for the next if\n\n \/\/ Do we need to perform a read operation? Can we perform a read?\n if (available_data_.eof() && (bytes_read_ < file_size_)) {\n tSize read_length = file_.Pread(bytes_read_, &buffer_[0], buffer_size_);\n bytes_read_ += read_length;\n available_data_ = tmacam::filebuf(&buffer_[0], read_length);\n }\n\n \/\/ Save current progress\n size_t data_left_len = available_data_.len();\n\n try {\n assert(data_left_len);\n const char* pkt_start = available_data_.current;\n \/\/ Read header, payload and CRC. Abort if payload is too big\n int32_t payload_len = ReadInt(&available_data_);\n assert(payload_len + 2*sizeof(int32_t) < buffer_size_);\n const char* payload_data = available_data_.read(payload_len);\n int32_t expected_checksum = ReadInt(&available_data_);\n#ifndef DUMPREADER_FAST_PASS\n \/\/ Calc CRC32\n uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);\n if (expected_checksum != static_cast<int32_t>(crc)) {\n std::cerr << \"CRC MISSMATCH -- found \" << crc << \n \" expected\" << expected_checksum <<\n std::endl; \n exit(EXIT_FAILURE);\n }\n#endif\n \/\/ Ok, pkt content was read and is sane. Return it.\n size_t pkt_len = data_left_len - available_data_.len();\n return tmacam::filebuf(pkt_start, pkt_len);\n std::cout << \"P: \" << payload_len << std::endl;\n } catch(std::out_of_range) {\n std::cout << \"ooops \" << std::endl;\n \/\/ not enough data... \n \/\/ rewind reading position\n bytes_read_ -= data_left_len;\n \/\/ and retry\n return GetNext();\n }\n}\n\nvoid HdfsDumpReader::ReadFile()\n{\n size_t data_left_len = 0;\n\n for (bytes_read_ = 0; bytes_read_ < file_size_;) {\n \/* Using Pread() and exceptions for doing this is ugly and lame.\n * We should have used Read() and proper tests but, you know what,\n * this works and is easy to understand -- and this scores +1 in\n * my book.\n *\/\n tSize read_length = file_.Pread(bytes_read_, &buffer_[0], buffer_size_);\n bytes_read_ += read_length;\n\n available_data_ = tmacam::filebuf(&buffer_[0], read_length);\n\n std::cout << \"READ \" << read_length << std::endl;\n\n try {\n while (!available_data_.eof()) {\n \/\/ Save current progress\n data_left_len = available_data_.len();\n \/\/ Read header, payload and CRC. Abort if payload is too big\n int32_t payload_len = ReadInt(&available_data_);\n assert(payload_len + 2*sizeof(int32_t) < buffer_size_);\n const char* payload_data = available_data_.read(payload_len);\n int32_t expected_checksum = ReadInt(&available_data_);\n#ifndef DUMPREADER_FAST_PASS\n \/\/ Calc CRC32\n uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);\n if (expected_checksum != static_cast<int32_t>(crc)) {\n std::cerr << \"CRC MISSMATCH -- found \" << crc << \n \" expected\" << expected_checksum <<\n std::endl; \n exit(EXIT_FAILURE);\n }\n#endif\n std::cout << \"P: \" << payload_len << std::endl;\n }\n } catch(std::out_of_range) {\n std::cout << \"ooops \" << std::endl;\n \/\/ not enough data... \n \/\/ rewind reading position\n bytes_read_ -= data_left_len;\n }\n }\n}\n\n\n}; \/\/ namespace tmacam\n\n\/**********************************************************************\/\n\n\nvoid ShowUsage()\n{\n std::cerr << \"Usage: hdfsls <path> \" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n using namespace tmacam;\n\n \/\/ Check command line arguments\n if ( argc != 2) {\n std::cerr << \"Wrong number of arguments\" << std::endl;\n ShowUsage();\n exit(EXIT_FAILURE);\n }\n const char* path = argv[1];\n\n \/\/ Connect to HDFS \/ get filesystem handle\n hdfs::FileSystem fs; \n\n \/\/ Path is a file, right?\n if (!fs.Exists(path)) {\n std::cerr << \"Path '\" << path << \"' does not exist.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n hdfs::FileInfoList path_info;\n fs.GetPathInfo(path, &path_info);\n if (path_info->mKind != kObjectKindFile ) {\n std::cerr << \"Path '\" << path << \"' is not a regular file.\"\n << std::endl;\n exit(EXIT_FAILURE);\n }\n\n HdfsDumpReader reader(&fs, path);\n\n reader.ReadFile();\n\n\n \n\treturn 0;\n}\n\n\/\/ vim: et ai sts=4 ts=4 sw=4\n<|endoftext|>"} {"text":"<commit_before>\/\/===- InstrProfilingRuntime.cpp - PGO runtime initialization -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nextern \"C\" {\n\n#include \"InstrProfiling.h\"\n\nextern int __llvm_profile_runtime;\nint __llvm_profile_runtime;\n\n}\n\nnamespace {\n\nclass RegisterAtExit {\npublic:\n RegisterAtExit() { __llvm_profile_register_write_file_atexit(); }\n};\n\nRegisterAtExit Registration;\n\n}\n<commit_msg>InstrProf: Remove redundant declaration<commit_after>\/\/===- InstrProfilingRuntime.cpp - PGO runtime initialization -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\nextern \"C\" {\n\n#include \"InstrProfiling.h\"\n\nint __llvm_profile_runtime;\n\n}\n\nnamespace {\n\nclass RegisterAtExit {\npublic:\n RegisterAtExit() { __llvm_profile_register_write_file_atexit(); }\n};\n\nRegisterAtExit Registration;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n\/**\n * @file heaptrack_interpret.cpp\n *\n * @brief Interpret raw heaptrack data and add Dwarf based debug information.\n *\/\n\n#include <iostream>\n#include <sstream>\n#include <unordered_map>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n\n#include <cxxabi.h>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include \"libbacktrace\/backtrace.h\"\n#include \"linereader.h\"\n\nusing namespace std;\n\nnamespace {\n\nstring demangle(const char* function)\n{\n if (!function) {\n return {};\n } else if (function[0] != '_' || function[1] != 'Z') {\n return {function};\n }\n\n string ret;\n int status = 0;\n char* demangled = abi::__cxa_demangle(function, 0, 0, &status);\n if (demangled) {\n ret = demangled;\n free(demangled);\n }\n return ret;\n}\n\nstruct AddressInformation\n{\n string function;\n string file;\n int line = 0;\n};\n\nstruct Module\n{\n Module(string _fileName, uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState)\n : fileName(move(_fileName))\n , addressStart(addressStart)\n , addressEnd(addressEnd)\n , backtraceState(backtraceState)\n {\n }\n\n AddressInformation resolveAddress(uintptr_t address) const\n {\n AddressInformation info;\n if (!backtraceState) {\n return info;\n }\n\n backtrace_pcinfo(backtraceState, address,\n [] (void *data, uintptr_t \/*addr*\/, const char *file, int line, const char *function) -> int {\n auto info = reinterpret_cast<AddressInformation*>(data);\n info->function = demangle(function);\n info->file = file ? file : \"\";\n info->line = line;\n return 0;\n }, &emptyErrorCallback, &info);\n\n if (info.function.empty()) {\n backtrace_syminfo(backtraceState, address,\n [] (void *data, uintptr_t \/*pc*\/, const char *symname, uintptr_t \/*symval*\/, uintptr_t \/*symsize*\/) {\n if (symname) {\n reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);\n }\n }, &errorCallback, &info);\n }\n\n return info;\n }\n\n static void errorCallback(void *\/*data*\/, const char *msg, int errnum)\n {\n cerr << \"Module backtrace error (code \" << errnum << \"): \" << msg << endl;\n }\n\n static void emptyErrorCallback(void *\/*data*\/, const char *\/*msg*\/, int \/*errnum*\/)\n {\n }\n\n bool operator<(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, fileName)\n < make_tuple(module.addressStart, module.addressEnd, module.fileName);\n }\n\n bool operator!=(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, fileName)\n != make_tuple(module.addressStart, module.addressEnd, module.fileName);\n }\n\n backtrace_state* backtraceState;\n string fileName;\n uintptr_t addressStart;\n uintptr_t addressEnd;\n};\n\nstruct Allocation\n{\n \/\/ backtrace entry point\n size_t ipIndex;\n \/\/ number of allocations\n size_t allocations;\n \/\/ amount of bytes leaked\n size_t leaked;\n};\n\n\/**\n * Information for a single call to an allocation function\n *\/\nstruct AllocationInfo\n{\n size_t ipIndex;\n size_t size;\n};\n\nstruct ResolvedIP\n{\n size_t moduleIndex = 0;\n size_t fileIndex = 0;\n size_t functionIndex = 0;\n int line = 0;\n};\n\nstruct AccumulatedTraceData\n{\n AccumulatedTraceData()\n {\n m_modules.reserve(256);\n m_backtraceStates.reserve(64);\n m_internedData.reserve(4096);\n m_encounteredIps.reserve(32768);\n }\n\n ~AccumulatedTraceData()\n {\n cout << dec;\n cout << \"# strings: \" << m_internedData.size() << '\\n';\n cout << \"# ips: \" << m_encounteredIps.size() << '\\n';\n }\n\n ResolvedIP resolve(const uintptr_t ip)\n {\n if (m_modulesDirty) {\n \/\/ sort by addresses, required for binary search below\n sort(m_modules.begin(), m_modules.end());\n\n for (size_t i = 0; i < m_modules.size(); ++i) {\n const auto& m1 = m_modules[i];\n for (size_t j = i + 1; j < m_modules.size(); ++j) {\n if (i == j) {\n continue;\n }\n const auto& m2 = m_modules[j];\n if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||\n (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))\n {\n cerr << \"OVERLAPPING MODULES: \" << hex\n << m1.fileName << \" (\" << m1.addressStart << \" to \" << m1.addressEnd << \") and \"\n << m2.fileName << \" (\" << m2.addressStart << \" to \" << m2.addressEnd << \")\\n\"\n << dec;\n } else if (m2.addressStart >= m1.addressEnd) {\n break;\n }\n }\n }\n\n m_modulesDirty = false;\n }\n\n ResolvedIP data;\n \/\/ find module for this instruction pointer\n auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,\n [] (const Module& module, const uintptr_t ip) -> bool {\n return module.addressEnd < ip;\n });\n if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {\n data.moduleIndex = intern(module->fileName);\n const auto info = module->resolveAddress(ip);\n data.fileIndex = intern(info.file);\n data.functionIndex = intern(info.function);\n data.line = info.line;\n }\n return data;\n }\n\n size_t intern(const string& str)\n {\n if (str.empty()) {\n return 0;\n }\n\n auto it = m_internedData.find(str);\n if (it != m_internedData.end()) {\n return it->second;\n }\n const size_t id = m_internedData.size() + 1;\n m_internedData.insert(it, make_pair(str, id));\n cout << \"s \" << str << '\\n';\n return id;\n }\n\n void addModule(const string& fileName, const bool isExe, const uintptr_t addressStart, const uintptr_t addressEnd)\n {\n backtrace_state* backtraceState = findBacktraceState(fileName, addressStart, isExe);\n\n m_modules.emplace_back(fileName, addressStart, addressEnd, backtraceState);\n m_modulesDirty = true;\n }\n\n void clearModules()\n {\n \/\/ TODO: optimize this, reuse modules that are still valid\n m_modules.clear();\n m_modulesDirty = true;\n }\n\n size_t addIp(const uintptr_t instructionPointer)\n {\n if (!instructionPointer) {\n return 0;\n }\n\n auto it = m_encounteredIps.find(instructionPointer);\n if (it != m_encounteredIps.end()) {\n return it->second;\n }\n\n const size_t ipId = m_encounteredIps.size() + 1;\n m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));\n\n const auto ip = resolve(instructionPointer);\n cout << \"i \" << instructionPointer << ' ' << ip.moduleIndex;\n if (ip.functionIndex || ip.fileIndex) {\n cout << ' ' << ip.functionIndex;\n if (ip.fileIndex) {\n cout << ' ' << ip.fileIndex << ' ' << ip.line;\n }\n }\n cout << '\\n';\n return ipId;\n }\n\nprivate:\n \/**\n * Prevent the same file from being initialized multiple times.\n * This drastically cuts the memory consumption down\n *\/\n backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)\n {\n if (boost::algorithm::starts_with(fileName, \"linux-vdso.so\")) {\n \/\/ prevent warning, since this will always fail\n return nullptr;\n }\n\n auto it = m_backtraceStates.find(fileName);\n if (it != m_backtraceStates.end()) {\n return it->second;\n }\n auto state = backtrace_create_state(fileName.c_str(), \/* we are single threaded, so: not thread safe *\/ false,\n [] (void *data, const char *msg, int errnum) {\n const Module* module = reinterpret_cast<Module*>(data);\n cerr << \"Failed to create backtrace state for file \" << module->fileName\n << \": \" << msg << \" (error code \" << errnum << \")\" << endl;\n }, this);\n\n if (state) {\n \/\/ when we could initialize the backtrace state, we initialize it with the first address\n \/\/ we get since that is the lowest one\n backtrace_fileline_initialize(state, addressStart, isExe,\n [] (void *data, const char *msg, int errnum) {\n const Module* module = reinterpret_cast<Module*>(data);\n cerr << \"Failed to initialize backtrace fileline for module \"\n << module->fileName\n << \": \" << msg << \" (error code \" << errnum << \")\" << endl;\n }, this);\n }\n\n m_backtraceStates.insert(it, make_pair(fileName, state));\n\n return state;\n }\n\n vector<Module> m_modules;\n unordered_map<string, backtrace_state*> m_backtraceStates;\n bool m_modulesDirty = false;\n\n unordered_map<string, size_t> m_internedData;\n unordered_map<uintptr_t, size_t> m_encounteredIps;\n};\n\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n \/\/ optimize: we only have a single thread\n ios_base::sync_with_stdio(false);\n\n AccumulatedTraceData data;\n\n LineReader reader;\n cin >> hex;\n cout << hex;\n\n while (reader.getLine(cin)) {\n if (reader.mode() == 'm') {\n string fileName;\n reader >> fileName;\n if (fileName == \"-\") {\n data.clearModules();\n } else {\n bool isExe = false;\n uintptr_t addressStart = 0;\n uintptr_t addressEnd = 0;\n if (!(reader >> isExe) || !(reader >> addressStart) || !(reader >> addressEnd)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n data.addModule(fileName, isExe, addressStart, addressEnd);\n }\n } else if (reader.mode() == 't') {\n uintptr_t instructionPointer = 0;\n size_t parentIndex = 0;\n if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n \/\/ ensure ip is encountered\n const auto ipId = data.addIp(instructionPointer);\n \/\/ trace point, map current output index to parent index\n cout << \"t \" << ipId << ' ' << parentIndex << '\\n';\n } else {\n cout << reader.line() << '\\n';\n }\n }\n\n return 0;\n}\n<commit_msg>Fixup callback handlers, the wrong data was passed in.<commit_after>\/*\n * Copyright 2014 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n\/**\n * @file heaptrack_interpret.cpp\n *\n * @brief Interpret raw heaptrack data and add Dwarf based debug information.\n *\/\n\n#include <iostream>\n#include <sstream>\n#include <unordered_map>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n\n#include <cxxabi.h>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include \"libbacktrace\/backtrace.h\"\n#include \"linereader.h\"\n\nusing namespace std;\n\nnamespace {\n\nstring demangle(const char* function)\n{\n if (!function) {\n return {};\n } else if (function[0] != '_' || function[1] != 'Z') {\n return {function};\n }\n\n string ret;\n int status = 0;\n char* demangled = abi::__cxa_demangle(function, 0, 0, &status);\n if (demangled) {\n ret = demangled;\n free(demangled);\n }\n return ret;\n}\n\nstruct AddressInformation\n{\n string function;\n string file;\n int line = 0;\n};\n\nstruct Module\n{\n Module(string _fileName, uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState)\n : fileName(move(_fileName))\n , addressStart(addressStart)\n , addressEnd(addressEnd)\n , backtraceState(backtraceState)\n {\n }\n\n AddressInformation resolveAddress(uintptr_t address) const\n {\n AddressInformation info;\n if (!backtraceState) {\n return info;\n }\n\n backtrace_pcinfo(backtraceState, address,\n [] (void *data, uintptr_t \/*addr*\/, const char *file, int line, const char *function) -> int {\n auto info = reinterpret_cast<AddressInformation*>(data);\n info->function = demangle(function);\n info->file = file ? file : \"\";\n info->line = line;\n return 0;\n }, &emptyErrorCallback, &info);\n\n if (info.function.empty()) {\n backtrace_syminfo(backtraceState, address,\n [] (void *data, uintptr_t \/*pc*\/, const char *symname, uintptr_t \/*symval*\/, uintptr_t \/*symsize*\/) {\n if (symname) {\n reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);\n }\n }, &errorCallback, &info);\n }\n\n return info;\n }\n\n static void errorCallback(void *\/*data*\/, const char *msg, int errnum)\n {\n cerr << \"Module backtrace error (code \" << errnum << \"): \" << msg << endl;\n }\n\n static void emptyErrorCallback(void *\/*data*\/, const char *\/*msg*\/, int \/*errnum*\/)\n {\n }\n\n bool operator<(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, fileName)\n < make_tuple(module.addressStart, module.addressEnd, module.fileName);\n }\n\n bool operator!=(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, fileName)\n != make_tuple(module.addressStart, module.addressEnd, module.fileName);\n }\n\n backtrace_state* backtraceState;\n string fileName;\n uintptr_t addressStart;\n uintptr_t addressEnd;\n};\n\nstruct Allocation\n{\n \/\/ backtrace entry point\n size_t ipIndex;\n \/\/ number of allocations\n size_t allocations;\n \/\/ amount of bytes leaked\n size_t leaked;\n};\n\n\/**\n * Information for a single call to an allocation function\n *\/\nstruct AllocationInfo\n{\n size_t ipIndex;\n size_t size;\n};\n\nstruct ResolvedIP\n{\n size_t moduleIndex = 0;\n size_t fileIndex = 0;\n size_t functionIndex = 0;\n int line = 0;\n};\n\nstruct AccumulatedTraceData\n{\n AccumulatedTraceData()\n {\n m_modules.reserve(256);\n m_backtraceStates.reserve(64);\n m_internedData.reserve(4096);\n m_encounteredIps.reserve(32768);\n }\n\n ~AccumulatedTraceData()\n {\n cout << dec;\n cout << \"# strings: \" << m_internedData.size() << '\\n';\n cout << \"# ips: \" << m_encounteredIps.size() << '\\n';\n }\n\n ResolvedIP resolve(const uintptr_t ip)\n {\n if (m_modulesDirty) {\n \/\/ sort by addresses, required for binary search below\n sort(m_modules.begin(), m_modules.end());\n\n for (size_t i = 0; i < m_modules.size(); ++i) {\n const auto& m1 = m_modules[i];\n for (size_t j = i + 1; j < m_modules.size(); ++j) {\n if (i == j) {\n continue;\n }\n const auto& m2 = m_modules[j];\n if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||\n (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))\n {\n cerr << \"OVERLAPPING MODULES: \" << hex\n << m1.fileName << \" (\" << m1.addressStart << \" to \" << m1.addressEnd << \") and \"\n << m2.fileName << \" (\" << m2.addressStart << \" to \" << m2.addressEnd << \")\\n\"\n << dec;\n } else if (m2.addressStart >= m1.addressEnd) {\n break;\n }\n }\n }\n\n m_modulesDirty = false;\n }\n\n ResolvedIP data;\n \/\/ find module for this instruction pointer\n auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,\n [] (const Module& module, const uintptr_t ip) -> bool {\n return module.addressEnd < ip;\n });\n if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {\n data.moduleIndex = intern(module->fileName);\n const auto info = module->resolveAddress(ip);\n data.fileIndex = intern(info.file);\n data.functionIndex = intern(info.function);\n data.line = info.line;\n }\n return data;\n }\n\n size_t intern(const string& str)\n {\n if (str.empty()) {\n return 0;\n }\n\n auto it = m_internedData.find(str);\n if (it != m_internedData.end()) {\n return it->second;\n }\n const size_t id = m_internedData.size() + 1;\n m_internedData.insert(it, make_pair(str, id));\n cout << \"s \" << str << '\\n';\n return id;\n }\n\n void addModule(const string& fileName, const bool isExe, const uintptr_t addressStart, const uintptr_t addressEnd)\n {\n backtrace_state* backtraceState = findBacktraceState(fileName, addressStart, isExe);\n\n m_modules.emplace_back(fileName, addressStart, addressEnd, backtraceState);\n m_modulesDirty = true;\n }\n\n void clearModules()\n {\n \/\/ TODO: optimize this, reuse modules that are still valid\n m_modules.clear();\n m_modulesDirty = true;\n }\n\n size_t addIp(const uintptr_t instructionPointer)\n {\n if (!instructionPointer) {\n return 0;\n }\n\n auto it = m_encounteredIps.find(instructionPointer);\n if (it != m_encounteredIps.end()) {\n return it->second;\n }\n\n const size_t ipId = m_encounteredIps.size() + 1;\n m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));\n\n const auto ip = resolve(instructionPointer);\n cout << \"i \" << instructionPointer << ' ' << ip.moduleIndex;\n if (ip.functionIndex || ip.fileIndex) {\n cout << ' ' << ip.functionIndex;\n if (ip.fileIndex) {\n cout << ' ' << ip.fileIndex << ' ' << ip.line;\n }\n }\n cout << '\\n';\n return ipId;\n }\n\nprivate:\n \/**\n * Prevent the same file from being initialized multiple times.\n * This drastically cuts the memory consumption down\n *\/\n backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)\n {\n if (boost::algorithm::starts_with(fileName, \"linux-vdso.so\")) {\n \/\/ prevent warning, since this will always fail\n return nullptr;\n }\n\n auto it = m_backtraceStates.find(fileName);\n if (it != m_backtraceStates.end()) {\n return it->second;\n }\n\n struct CallbackData {\n const string* fileName;\n };\n CallbackData data = {&fileName};\n\n auto state = backtrace_create_state(fileName.c_str(), \/* we are single threaded, so: not thread safe *\/ false,\n [] (void *rawData, const char *msg, int errnum) {\n auto data = reinterpret_cast<const CallbackData*>(rawData);\n cerr << \"Failed to create backtrace state for module \"\n << *data->fileName << \": \" << msg\n << \" (error code \" << errnum << \")\" << endl;\n }, &data);\n\n if (state) {\n \/\/ when we could initialize the backtrace state, we initialize it with the first address\n \/\/ we get since that is the lowest one\n backtrace_fileline_initialize(state, addressStart, isExe,\n [] (void *rawData, const char *msg, int errnum) {\n auto data = reinterpret_cast<CallbackData*>(rawData);\n cerr << \"Failed to initialize backtrace fileline for module \"\n << *data->fileName << \": \" << msg\n << \" (error code \" << errnum << \")\" << endl;\n }, &data);\n }\n\n m_backtraceStates.insert(it, make_pair(fileName, state));\n\n return state;\n }\n\n vector<Module> m_modules;\n unordered_map<string, backtrace_state*> m_backtraceStates;\n bool m_modulesDirty = false;\n\n unordered_map<string, size_t> m_internedData;\n unordered_map<uintptr_t, size_t> m_encounteredIps;\n};\n\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n \/\/ optimize: we only have a single thread\n ios_base::sync_with_stdio(false);\n\n AccumulatedTraceData data;\n\n LineReader reader;\n cin >> hex;\n cout << hex;\n\n while (reader.getLine(cin)) {\n if (reader.mode() == 'm') {\n string fileName;\n reader >> fileName;\n if (fileName == \"-\") {\n data.clearModules();\n } else {\n bool isExe = false;\n uintptr_t addressStart = 0;\n uintptr_t addressEnd = 0;\n if (!(reader >> isExe) || !(reader >> addressStart) || !(reader >> addressEnd)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n data.addModule(fileName, isExe, addressStart, addressEnd);\n }\n } else if (reader.mode() == 't') {\n uintptr_t instructionPointer = 0;\n size_t parentIndex = 0;\n if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n \/\/ ensure ip is encountered\n const auto ipId = data.addIp(instructionPointer);\n \/\/ trace point, map current output index to parent index\n cout << \"t \" << ipId << ' ' << parentIndex << '\\n';\n } else {\n cout << reader.line() << '\\n';\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visomics\n\n Copyright (c) Kitware, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=========================================================================*\/\n\n\/\/ Qt includes\n#include <QAction>\n#include <QDebug>\n#include <QDesktopServices>\n#include <QFileDialog>\n#include <QTableView>\n#include <QLayout>\n#include <QStandardItemModel>\n#include <QWidget>\n#include <QHeaderView>\n\n\/\/ Visomics includes\n#include \"voDataObject.h\"\n#include \"voIOManager.h\"\n#include \"voTableView.h\"\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include <vtkIdTypeArray.h>\n#include <vtkQtTableRepresentation.h>\n#include <vtkQtTableView.h>\n#include <vtkTable.h>\n\n\/\/ --------------------------------------------------------------------------\nclass voTableViewPrivate\n{\npublic:\n voTableViewPrivate();\n\n QTableView* TableView;\n QStandardItemModel Model;\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voTableViewPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoTableViewPrivate::voTableViewPrivate()\n{\n this->TableView = 0;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voTableView methods\n\n\/\/ --------------------------------------------------------------------------\nvoTableView::voTableView(QWidget* newParent):\n Superclass(newParent), d_ptr(new voTableViewPrivate)\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoTableView::~voTableView()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nQList<QAction*> voTableView::actions()\n{\n QList<QAction*> actionList = this->Superclass::actions();\n\n QAction * exportToCsvAction = new QAction(QIcon(\":\/Icons\/csv_text.png\"), \"Export as CSV\", this);\n exportToCsvAction->setToolTip(\"Export current table view as CSV text file.\");\n connect(exportToCsvAction, SIGNAL(triggered()), this, SLOT(onExportToCsvActionTriggered()));\n actionList << exportToCsvAction;\n\n return actionList;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::onExportToCsvActionTriggered()\n{\n QString defaultFileName = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)\n + \"\/\" + voUtils::cleanString(this->objectName()) + \".csv\";\n\n QString fileName = QFileDialog::getSaveFileName(\n 0, tr(\"Save table data...\"), defaultFileName, \"Comma Separated Value (*.csv)\");\n if(fileName.isEmpty())\n {\n return;\n }\n vtkTable * table = vtkTable::SafeDownCast(this->dataObject()->dataAsVTKDataObject());\n Q_ASSERT(table);\n voIOManager::writeTableToCVSFile(table, fileName);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::setupUi(QLayout *layout)\n{\n Q_D(voTableView);\n\n d->TableView = new QTableView();\n d->TableView->setModel(&d->Model);\n\n layout->addWidget(d->TableView);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::setDataObjectInternal(const voDataObject& dataObject)\n{\n Q_D(voTableView);\n\n vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());\n if (!table)\n {\n qCritical() << \"voTableView - Failed to setDataObject - vtkTable data is expected !\";\n return;\n }\n\n \/\/ Update the model if necessary\n \/\/if (t->GetMTime() > this->LastModelMTime)\n \/\/ {\n \/\/ Note: this will clear the current selection.\n vtkIdType num_rows = table->GetNumberOfRows();\n vtkIdType num_cols = table->GetNumberOfColumns();\n d->Model.setRowCount(static_cast<int>(num_rows));\n d->Model.setColumnCount(static_cast<int>(num_cols - 1));\n for (vtkIdType c = 1; c < num_cols; ++c)\n {\n d->Model.setHeaderData(static_cast<int>(c-1), Qt::Horizontal, QString(table->GetColumnName(c)));\n for (vtkIdType r = 0; r < num_rows; ++r)\n {\n QStandardItem* item = new QStandardItem(QString(table->GetValue(r, c).ToString()));\n item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); \/\/ Item is view-only\n d->Model.setItem(static_cast<int>(r), static_cast<int>(c-1), item);\n }\n }\n for (vtkIdType r = 0; r < num_rows; ++r)\n {\n d->Model.setHeaderData(static_cast<int>(r), Qt::Vertical, QString(table->GetValue(r, 0).ToString()));\n }\n \/\/ this->LastModelMTime = table->GetMTime();\n \/\/ }\n\n d->TableView->horizontalHeader()->setMinimumSectionSize(100);\n d->TableView->resizeColumnsToContents();\n\n \/\/ Retrieve the selected subtable\n \/\/vtkSmartPointer<vtkTable> ot = vtkSmartPointer<vtkTable>::New();\n \/\/this->selectedTable(ot);\n \/\/this->Outputs[\"output\"] = ot;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/void voTableView::selectedTable(vtkTable* table)\n\/\/{\n\/\/ vtkTable* t = vtkTable::SafeDownCast(this->input().data());\n\/\/ if (!t)\n\/\/ {\n\/\/ return;\n\/\/ }\n\n\/\/ QSet<vtkIdType> rows;\n\/\/ QSet<vtkIdType> cols;\n\n\/\/ \/\/ Always select the first column (headers)\n\/\/ cols << 0;\n\n\/\/ const QModelIndexList selected = this->View->selectionModel()->selectedIndexes();\n\/\/ if (selected.size() == 0)\n\/\/ {\n\/\/ table->ShallowCopy(t);\n\/\/ return;\n\/\/ }\n\/\/ foreach (QModelIndex ind, selected)\n\/\/ {\n\/\/ cols << ind.row();\n\/\/ rows << ind.column();\n\/\/ }\n\n\/\/ foreach (vtkIdType c, cols)\n\/\/ {\n\/\/ vtkAbstractArray* col = t->GetColumn(c);\n\/\/ vtkAbstractArray* new_col = col->NewInstance();\n\/\/ new_col->SetName(col->GetName());\n\/\/ new_col->SetNumberOfTuples(rows.size());\n\/\/ table->AddColumn(new_col);\n\/\/ int ind = 0;\n\/\/ foreach (vtkIdType r, rows)\n\/\/ {\n\/\/ new_col->InsertTuple(ind, r, col);\n\/\/ ++ind;\n\/\/ }\n\/\/ new_col->Delete();\n\/\/ }\n\/\/}\n<commit_msg>Remove old code, reformat voTableView::setDataObject()<commit_after>\/*=========================================================================\n\n Program: Visomics\n\n Copyright (c) Kitware, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=========================================================================*\/\n\n\/\/ Qt includes\n#include <QAction>\n#include <QDebug>\n#include <QDesktopServices>\n#include <QFileDialog>\n#include <QTableView>\n#include <QLayout>\n#include <QStandardItemModel>\n#include <QWidget>\n#include <QHeaderView>\n\n\/\/ Visomics includes\n#include \"voDataObject.h\"\n#include \"voIOManager.h\"\n#include \"voTableView.h\"\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include <vtkIdTypeArray.h>\n#include <vtkQtTableRepresentation.h>\n#include <vtkQtTableView.h>\n#include <vtkTable.h>\n\n\/\/ --------------------------------------------------------------------------\nclass voTableViewPrivate\n{\npublic:\n voTableViewPrivate();\n\n QTableView* TableView;\n QStandardItemModel Model;\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voTableViewPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoTableViewPrivate::voTableViewPrivate()\n{\n this->TableView = 0;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voTableView methods\n\n\/\/ --------------------------------------------------------------------------\nvoTableView::voTableView(QWidget* newParent):\n Superclass(newParent), d_ptr(new voTableViewPrivate)\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoTableView::~voTableView()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nQList<QAction*> voTableView::actions()\n{\n QList<QAction*> actionList = this->Superclass::actions();\n\n QAction * exportToCsvAction = new QAction(QIcon(\":\/Icons\/csv_text.png\"), \"Export as CSV\", this);\n exportToCsvAction->setToolTip(\"Export current table view as CSV text file.\");\n connect(exportToCsvAction, SIGNAL(triggered()), this, SLOT(onExportToCsvActionTriggered()));\n actionList << exportToCsvAction;\n\n return actionList;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::onExportToCsvActionTriggered()\n{\n QString defaultFileName = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)\n + \"\/\" + voUtils::cleanString(this->objectName()) + \".csv\";\n\n QString fileName = QFileDialog::getSaveFileName(\n 0, tr(\"Save table data...\"), defaultFileName, \"Comma Separated Value (*.csv)\");\n if(fileName.isEmpty())\n {\n return;\n }\n vtkTable * table = vtkTable::SafeDownCast(this->dataObject()->dataAsVTKDataObject());\n Q_ASSERT(table);\n voIOManager::writeTableToCVSFile(table, fileName);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::setupUi(QLayout *layout)\n{\n Q_D(voTableView);\n\n d->TableView = new QTableView();\n d->TableView->setModel(&d->Model);\n\n layout->addWidget(d->TableView);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voTableView::setDataObjectInternal(const voDataObject& dataObject)\n{\n Q_D(voTableView);\n\n vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());\n if (!table)\n {\n qCritical() << \"voTableView - Failed to setDataObject - vtkTable data is expected !\";\n return;\n }\n\n vtkIdType num_rows = table->GetNumberOfRows();\n vtkIdType num_cols = table->GetNumberOfColumns();\n d->Model.setRowCount(static_cast<int>(num_rows));\n d->Model.setColumnCount(static_cast<int>(num_cols - 1));\n for (vtkIdType c = 1; c < num_cols; ++c)\n {\n d->Model.setHeaderData(static_cast<int>(c-1), Qt::Horizontal, QString(table->GetColumnName(c)));\n for (vtkIdType r = 0; r < num_rows; ++r)\n {\n QStandardItem* item = new QStandardItem(QString(table->GetValue(r, c).ToString()));\n item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); \/\/ Item is view-only\n d->Model.setItem(static_cast<int>(r), static_cast<int>(c-1), item);\n }\n }\n for (vtkIdType r = 0; r < num_rows; ++r)\n {\n d->Model.setHeaderData(static_cast<int>(r), Qt::Vertical, QString(table->GetValue(r, 0).ToString()));\n }\n\n d->TableView->horizontalHeader()->setMinimumSectionSize(100);\n d->TableView->resizeColumnsToContents();\n\n \/\/ Retrieve the selected subtable\n \/\/vtkSmartPointer<vtkTable> ot = vtkSmartPointer<vtkTable>::New();\n \/\/this->selectedTable(ot);\n \/\/this->Outputs[\"output\"] = ot;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/void voTableView::selectedTable(vtkTable* table)\n\/\/{\n\/\/ vtkTable* t = vtkTable::SafeDownCast(this->input().data());\n\/\/ if (!t)\n\/\/ {\n\/\/ return;\n\/\/ }\n\n\/\/ QSet<vtkIdType> rows;\n\/\/ QSet<vtkIdType> cols;\n\n\/\/ \/\/ Always select the first column (headers)\n\/\/ cols << 0;\n\n\/\/ const QModelIndexList selected = this->View->selectionModel()->selectedIndexes();\n\/\/ if (selected.size() == 0)\n\/\/ {\n\/\/ table->ShallowCopy(t);\n\/\/ return;\n\/\/ }\n\/\/ foreach (QModelIndex ind, selected)\n\/\/ {\n\/\/ cols << ind.row();\n\/\/ rows << ind.column();\n\/\/ }\n\n\/\/ foreach (vtkIdType c, cols)\n\/\/ {\n\/\/ vtkAbstractArray* col = t->GetColumn(c);\n\/\/ vtkAbstractArray* new_col = col->NewInstance();\n\/\/ new_col->SetName(col->GetName());\n\/\/ new_col->SetNumberOfTuples(rows.size());\n\/\/ table->AddColumn(new_col);\n\/\/ int ind = 0;\n\/\/ foreach (vtkIdType r, rows)\n\/\/ {\n\/\/ new_col->InsertTuple(ind, r, col);\n\/\/ ++ind;\n\/\/ }\n\/\/ new_col->Delete();\n\/\/ }\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CheckpointEntry.cpp\n *\n * Created on Sep 27, 2016\n * Author: Pete Schultz\n *\/\n\n#include \"CheckpointEntryDataStore.hpp\"\n#include \"structures\/Buffer.hpp\"\n#include \"utils\/BufferUtilsMPI.hpp\"\n#include \"utils\/BufferUtilsPvp.hpp\"\n\nnamespace PV {\n\nvoid CheckpointEntryDataStore::initialize(DataStore *dataStore, PVLayerLoc const *layerLoc) {\n mDataStore = dataStore;\n mLayerLoc = layerLoc;\n}\n\nvoid CheckpointEntryDataStore::write(\n std::string const &checkpointDirectory,\n double simTime,\n bool verifyWritesFlag) const {\n int const numBuffers = mDataStore->getNumBuffers();\n int const numLevels = mDataStore->getNumLevels();\n FileStream *fileStream = nullptr;\n if (getCommunicator()->commRank() == 0) {\n std::string path = generatePath(checkpointDirectory, \"pvp\");\n fileStream = new FileStream(path.c_str(), std::ios_base::out, verifyWritesFlag);\n int const numBands = numBuffers * numLevels;\n int *params = pvp_set_nonspiking_act_params(\n getCommunicator(), simTime, mLayerLoc, PV_FLOAT_TYPE, numLevels);\n pvAssert(params && params[1] == NUM_BIN_PARAMS);\n fileStream->write(params, params[0]);\n }\n int const nxExt = mLayerLoc->nx + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExt = mLayerLoc->ny + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n int const nf = mLayerLoc->nf;\n int const numElements = nxExt * nyExt * nf;\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n double lastUpdateTime = mDataStore->getLastUpdateTime(b, l);\n pvdata_t const *localData = mDataStore->buffer(b, l);\n Buffer<pvdata_t> localPvpBuffer = Buffer<pvdata_t>{localData, nxExt, nyExt, nf};\n Buffer<pvdata_t> globalPvpBuffer = BufferUtils::gather<pvdata_t>(\n getCommunicator(), localPvpBuffer, mLayerLoc->nx, mLayerLoc->ny);\n if (fileStream) {\n BufferUtils::writeFrame(*fileStream, &globalPvpBuffer, lastUpdateTime);\n }\n }\n }\n delete fileStream;\n}\n\nvoid CheckpointEntryDataStore::read(std::string const &checkpointDirectory, double *simTimePtr)\n const {\n int const numBuffers = mDataStore->getNumBuffers();\n int const numLevels = mDataStore->getNumLevels();\n int const numBands = numBuffers * numLevels;\n FileStream *fileStream = nullptr;\n if (getCommunicator()->commRank() == 0) {\n std::string path = generatePath(checkpointDirectory, \"pvp\");\n fileStream = new FileStream(path.c_str(), std::ios_base::in, false);\n std::vector<int> header = BufferUtils::readHeader(*fileStream);\n pvErrorIf(\n header.at(INDEX_NBANDS) != numBands,\n \"readDataStoreFromFile error reading \\\"%s\\\": delays*batchwidth in file is %d, \"\n \"but delays*batchwidth in layer is %d\\n\",\n path,\n header.at(INDEX_NBANDS),\n numBands);\n }\n int const nxExtGlobal = mLayerLoc->nxGlobal + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExtGlobal = mLayerLoc->nyGlobal + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n int const nf = mLayerLoc->nf;\n Buffer<pvdata_t> pvpBuffer;\n std::vector<double> updateTimes;\n updateTimes.resize(numBands);\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n if (fileStream) {\n pvpBuffer.resize(nxExtGlobal, nyExtGlobal, nf);\n double updateTime = BufferUtils::readFrame(*fileStream, &pvpBuffer);\n updateTimes.at(b * numLevels + l) = updateTime;\n }\n else {\n int const nxExtLocal = mLayerLoc->nx + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExtLocal = mLayerLoc->ny + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n pvpBuffer.resize(nxExtLocal, nyExtLocal, nf);\n }\n BufferUtils::scatter(getCommunicator(), pvpBuffer, mLayerLoc->nx, mLayerLoc->ny);\n pvdata_t *localData = mDataStore->buffer(b, l);\n memcpy(\n localData,\n pvpBuffer.asVector().data(),\n (std::size_t)pvpBuffer.getTotalElements() * sizeof(pvdata_t));\n }\n }\n MPI_Bcast(\n updateTimes.data(), numBands, MPI_DOUBLE, 0 \/*root*\/, getCommunicator()->communicator());\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n mDataStore->setLastUpdateTime(b, l, updateTimes[b * numLevels + l]);\n }\n }\n delete fileStream;\n}\n\nvoid CheckpointEntryDataStore::remove(std::string const &checkpointDirectory) const {\n deleteFile(checkpointDirectory, \"pvp\");\n}\n\n} \/\/ end namespace PV\n<commit_msg>Hotfix to fix build errors on certain machines.<commit_after>\/*\n * CheckpointEntry.cpp\n *\n * Created on Sep 27, 2016\n * Author: Pete Schultz\n *\/\n\n#include \"CheckpointEntryDataStore.hpp\"\n#include \"structures\/Buffer.hpp\"\n#include \"utils\/BufferUtilsMPI.hpp\"\n#include \"utils\/BufferUtilsPvp.hpp\"\n\nnamespace PV {\n\nvoid CheckpointEntryDataStore::initialize(DataStore *dataStore, PVLayerLoc const *layerLoc) {\n mDataStore = dataStore;\n mLayerLoc = layerLoc;\n}\n\nvoid CheckpointEntryDataStore::write(\n std::string const &checkpointDirectory,\n double simTime,\n bool verifyWritesFlag) const {\n int const numBuffers = mDataStore->getNumBuffers();\n int const numLevels = mDataStore->getNumLevels();\n FileStream *fileStream = nullptr;\n if (getCommunicator()->commRank() == 0) {\n std::string path = generatePath(checkpointDirectory, \"pvp\");\n fileStream = new FileStream(path.c_str(), std::ios_base::out, verifyWritesFlag);\n int const numBands = numBuffers * numLevels;\n int *params = pvp_set_nonspiking_act_params(\n getCommunicator(), simTime, mLayerLoc, PV_FLOAT_TYPE, numLevels);\n pvAssert(params && params[1] == NUM_BIN_PARAMS);\n fileStream->write(params, params[0]);\n }\n int const nxExt = mLayerLoc->nx + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExt = mLayerLoc->ny + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n int const nf = mLayerLoc->nf;\n int const numElements = nxExt * nyExt * nf;\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n double lastUpdateTime = mDataStore->getLastUpdateTime(b, l);\n pvdata_t const *localData = mDataStore->buffer(b, l);\n Buffer<pvdata_t> localPvpBuffer = Buffer<pvdata_t>{localData, nxExt, nyExt, nf};\n Buffer<pvdata_t> globalPvpBuffer = BufferUtils::gather<pvdata_t>(\n getCommunicator(), localPvpBuffer, mLayerLoc->nx, mLayerLoc->ny);\n if (fileStream) {\n BufferUtils::writeFrame(*fileStream, &globalPvpBuffer, lastUpdateTime);\n }\n }\n }\n delete fileStream;\n}\n\nvoid CheckpointEntryDataStore::read(std::string const &checkpointDirectory, double *simTimePtr)\n const {\n int const numBuffers = mDataStore->getNumBuffers();\n int const numLevels = mDataStore->getNumLevels();\n int const numBands = numBuffers * numLevels;\n FileStream *fileStream = nullptr;\n if (getCommunicator()->commRank() == 0) {\n std::string path = generatePath(checkpointDirectory, \"pvp\");\n fileStream = new FileStream(path.c_str(), std::ios_base::in, false);\n std::vector<int> header = BufferUtils::readHeader(*fileStream);\n pvErrorIf(\n header.at(INDEX_NBANDS) != numBands,\n \"readDataStoreFromFile error reading \\\"%s\\\": delays*batchwidth in file is %d, \"\n \"but delays*batchwidth in layer is %d\\n\",\n path.c_str(),\n header.at(INDEX_NBANDS),\n numBands);\n }\n int const nxExtGlobal = mLayerLoc->nxGlobal + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExtGlobal = mLayerLoc->nyGlobal + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n int const nf = mLayerLoc->nf;\n Buffer<pvdata_t> pvpBuffer;\n std::vector<double> updateTimes;\n updateTimes.resize(numBands);\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n if (fileStream) {\n pvpBuffer.resize(nxExtGlobal, nyExtGlobal, nf);\n double updateTime = BufferUtils::readFrame(*fileStream, &pvpBuffer);\n updateTimes.at(b * numLevels + l) = updateTime;\n }\n else {\n int const nxExtLocal = mLayerLoc->nx + mLayerLoc->halo.lt + mLayerLoc->halo.rt;\n int const nyExtLocal = mLayerLoc->ny + mLayerLoc->halo.dn + mLayerLoc->halo.up;\n pvpBuffer.resize(nxExtLocal, nyExtLocal, nf);\n }\n BufferUtils::scatter(getCommunicator(), pvpBuffer, mLayerLoc->nx, mLayerLoc->ny);\n pvdata_t *localData = mDataStore->buffer(b, l);\n memcpy(\n localData,\n pvpBuffer.asVector().data(),\n (std::size_t)pvpBuffer.getTotalElements() * sizeof(pvdata_t));\n }\n }\n MPI_Bcast(\n updateTimes.data(), numBands, MPI_DOUBLE, 0 \/*root*\/, getCommunicator()->communicator());\n for (int b = 0; b < numBuffers; b++) {\n for (int l = 0; l < numLevels; l++) {\n mDataStore->setLastUpdateTime(b, l, updateTimes[b * numLevels + l]);\n }\n }\n delete fileStream;\n}\n\nvoid CheckpointEntryDataStore::remove(std::string const &checkpointDirectory) const {\n deleteFile(checkpointDirectory, \"pvp\");\n}\n\n} \/\/ end namespace PV\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n#define MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n\n\/\/ mapnik\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/box2d.hpp>\n#include <iostream>\n\n\/\/ boost\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include <tuple>\n\nnamespace mapnik { namespace json {\n\nusing position = std::tuple<double,double>;\nusing boxes = std::vector<std::pair<box2d<double>, std::pair<std::size_t, std::size_t>>>;\n\nnamespace qi = boost::spirit::qi;\nnamespace standard_wide = boost::spirit::standard_wide;\nusing standard_wide::space_type;\n\nstruct calculate_bounding_box_impl\n{\n using result_type = void;\n template <typename T0, typename T1>\n result_type operator() (T0 & bbox, T1 const& pos) const\n {\n if (pos)\n {\n double x = std::get<0>(*pos);\n double y = std::get<1>(*pos);\n if (!bbox.valid())\n {\n bbox.init(x, y, x, y); \/\/ TODO: add init(x,y) convinience method\n }\n else\n {\n bbox.expand_to_include(x, y);\n }\n }\n }\n};\n\nstruct push_box_impl\n{\n using result_type = void;\n template <typename T0, typename T1, typename T2, typename T3>\n void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const\n {\n boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end())));\n }\n};\n\ntemplate <typename Iterator, typename ErrorHandler = error_handler<Iterator> >\nstruct extract_bounding_box_grammar :\n qi::grammar<Iterator, void(boxes&) ,space_type>\n{\n extract_bounding_box_grammar();\n \/\/ rules\n qi::rule<Iterator, void(boxes&), space_type> start;\n qi::rule<Iterator, qi::locals<Iterator>, void(boxes&), space_type> features;\n qi::rule<Iterator, qi::locals<int, box2d<double>>, void(boxes&, Iterator const&), space_type> feature;\n qi::rule<Iterator, qi::locals<box2d<double>>, box2d<double>(), space_type> coords;\n qi::rule<Iterator, boost::optional<position>(), space_type> pos;\n qi::rule<Iterator, void(box2d<double>&), space_type> ring;\n qi::rule<Iterator, void(box2d<double>&), space_type> rings;\n qi::rule<Iterator, void(box2d<double>&), space_type> rings_array;\n\n \/\/ phoenix functions\n boost::phoenix::function<push_box_impl> push_box;\n boost::phoenix::function<calculate_bounding_box_impl> calculate_bounding_box;\n \/\/ error handler\n boost::phoenix::function<ErrorHandler> const error_handler;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n<commit_msg>ignore invalid bounding boxes from \"geometry\": null<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n#define MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n\n\/\/ mapnik\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/box2d.hpp>\n#include <iostream>\n\n\/\/ boost\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#pragma GCC diagnostic ignored \"-Wunused-local-typedef\"\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include <tuple>\n\nnamespace mapnik { namespace json {\n\nusing position = std::tuple<double,double>;\nusing boxes = std::vector<std::pair<box2d<double>, std::pair<std::size_t, std::size_t>>>;\n\nnamespace qi = boost::spirit::qi;\nnamespace standard_wide = boost::spirit::standard_wide;\nusing standard_wide::space_type;\n\nstruct calculate_bounding_box_impl\n{\n using result_type = void;\n template <typename T0, typename T1>\n result_type operator() (T0 & bbox, T1 const& pos) const\n {\n if (pos)\n {\n double x = std::get<0>(*pos);\n double y = std::get<1>(*pos);\n if (!bbox.valid())\n {\n bbox.init(x, y, x, y); \/\/ TODO: add init(x,y) convinience method\n }\n else\n {\n bbox.expand_to_include(x, y);\n }\n }\n }\n};\n\nstruct push_box_impl\n{\n using result_type = void;\n template <typename T0, typename T1, typename T2, typename T3>\n void operator() (T0 & boxes, T1 const& begin, T2 const& box, T3 const& range) const\n {\n if (box.valid()) boxes.emplace_back(box, std::make_pair(std::distance(begin, range.begin()), std::distance(range.begin(), range.end())));\n }\n};\n\ntemplate <typename Iterator, typename ErrorHandler = error_handler<Iterator> >\nstruct extract_bounding_box_grammar :\n qi::grammar<Iterator, void(boxes&) ,space_type>\n{\n extract_bounding_box_grammar();\n \/\/ rules\n qi::rule<Iterator, void(boxes&), space_type> start;\n qi::rule<Iterator, qi::locals<Iterator>, void(boxes&), space_type> features;\n qi::rule<Iterator, qi::locals<int, box2d<double>>, void(boxes&, Iterator const&), space_type> feature;\n qi::rule<Iterator, qi::locals<box2d<double>>, box2d<double>(), space_type> coords;\n qi::rule<Iterator, boost::optional<position>(), space_type> pos;\n qi::rule<Iterator, void(box2d<double>&), space_type> ring;\n qi::rule<Iterator, void(box2d<double>&), space_type> rings;\n qi::rule<Iterator, void(box2d<double>&), space_type> rings_array;\n\n \/\/ phoenix functions\n boost::phoenix::function<push_box_impl> push_box;\n boost::phoenix::function<calculate_bounding_box_impl> calculate_bounding_box;\n \/\/ error handler\n boost::phoenix::function<ErrorHandler> const error_handler;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_EXTRACT_BOUNDING_BOX_GRAMMAR_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"filedecompressor.h\"\n#include <QMap>\n#include <QBuffer>\n\nFileDecompressor::FileDecompressor()\n{\n\n}\n\nFileDecompressor::~FileDecompressor()\n{\n\n}\n\nvoid FileDecompressor::decompress()\n{\n \/\/Opens HZIP file\n qDebug() << endl << endl;\n QString filePath;\n QFileDialog dialog;\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setNameFilter(\"HuffmanZip (*.hzip)\");\n int result = dialog.exec();\n if (result)\n filePath = dialog.selectedFiles().first();\n else\n filePath = \"\";\n \/\/Now we need to separate HEADER from DATA\n\n std::ifstream inputFile;\n inputFile.open(filePath.toStdString().c_str(), std::ifstream::binary);\n\n stringstream strStream;\n strStream << inputFile.rdbuf();\n string allfile = strStream.str();\n\n qDebug() << \"ARCHIVO COMPLETO \" << allfile.size();\n\n\n std::string width;\n getline(strStream, width);\n std::string height;\n getline(strStream, height);\n std::string huffmancodes;\n getline(strStream, huffmancodes);\n std::string data;\n int position = width.size()+1+height.size()+1+huffmancodes.size()+1;\n allfile.erase (0,position);\n qDebug() << \"DESPUES DE CORTAR \"<< allfile.size();\n data = allfile;\n\n inputFile.close();\n\n this->width = atoi(width.c_str());\n this->height = atoi(height.c_str());\n QString mixedcodes = QString::fromUtf8( huffmancodes.data(), huffmancodes.size() );\n QStringList newHeader = mixedcodes.split(\"#\");\n\n this->header = newHeader;\n\n this->decodificate(data);\n this->headerInterpreter();\n this->generateFile();\n}\n\nvoid FileDecompressor::decodificate(std::string data)\n{\n QString image;\n for (int i = 0; i < data.size(); i++) {\n char mander = data.at(i);\n char mask = 1 << 7;\n for(int e = 0; e<8; e++){\n if((mander & mask)==mask)\n image.append(\"1\");\n else\n image.append(\"0\");\n mander = (mander << 1);\n }\n }\n this->imagedata = image;\n}\n\nvoid FileDecompressor::headerInterpreter()\n{\n QStringList::iterator it;\n for(it=this->header.begin(); it!=this->header.end(); it++)\n {\n this->codes.insert(it->mid(6), it->mid(0,6).prepend(\"#\"));\n }\n}\n\nvoid FileDecompressor::generateFile()\n{\n qDebug() << \"CANTIDAD DE BITS\" << this->imagedata.size();\n QString aux;\n QVector<QColor> colors;\n QString::iterator it;\n for(it=this->imagedata.begin(); it!=this->imagedata.end(); it++)\n {\n aux += *it;\n if(this->codes.contains(aux))\n {\n colors.push_back(QColor(this->codes.find(aux).value()));\n aux.clear();\n }\n }\n qDebug() << colors.size();\n\n \/\/qDebug() << colors;\n\n QImage img(this->width, this->height, QImage::Format_ARGB32);\n QByteArray ba;\n QBuffer buffer(&ba);\n qDebug() << \"LLEGA\";\n \/\/Esto va a tardar por la resolucion de la imagen, no es que se colgo el programa\n int k = 0;\n for(int i=0; i<this->height; i++)\n {\n for(int j=0; j<this->width; j++)\n {\n \/\/Por cada pixel asigno un valor del Map. Deberia haber la misma cantidad de pixeles que tamaño del map.\n\n img.setPixel(j,i,colors.at(k).rgb());\n k++;\n }\n\n }\n qDebug() << \"SALE?\";\n\n\n \/\/Tengo que ver como guardar la imagen\n \/\/img.save(&buffer, \"PNG\");\n}\n\n<commit_msg>Changed file compression<commit_after>#include \"filedecompressor.h\"\n#include <QMap>\n#include <QBuffer>\n\nFileDecompressor::FileDecompressor()\n{\n\n}\n\nFileDecompressor::~FileDecompressor()\n{\n\n}\n\nvoid FileDecompressor::decompress()\n{\n \/\/Opens HZIP file\n qDebug() << endl << endl;\n QString filePath;\n QFileDialog dialog;\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setNameFilter(\"HuffmanZip (*.hzip)\");\n int result = dialog.exec();\n if (result)\n filePath = dialog.selectedFiles().first();\n else\n filePath = \"\";\n \/\/Now we need to separate HEADER from DATA\n\n std::ifstream inputFile;\n inputFile.open(filePath.toStdString().c_str(), std::ifstream::binary);\n\n stringstream strStream;\n strStream << inputFile.rdbuf();\n string allfile = strStream.str();\n\n qDebug() << \"ARCHIVO COMPLETO \" << allfile.size();\n\n\n std::string width;\n getline(strStream, width);\n std::string height;\n getline(strStream, height);\n std::string huffmancodes;\n getline(strStream, huffmancodes);\n std::string data;\n int position = width.size()+1+height.size()+1+huffmancodes.size()+1;\n allfile.erase (0,position);\n qDebug() << \"DESPUES DE CORTAR \"<< allfile.size();\n data = allfile;\n\n inputFile.close();\n\n this->width = atoi(width.c_str());\n this->height = atoi(height.c_str());\n QString mixedcodes = QString::fromUtf8( huffmancodes.data(), huffmancodes.size() );\n QStringList newHeader = mixedcodes.split(\"#\");\n\n this->header = newHeader;\n\n this->decodificate(data);\n this->headerInterpreter();\n this->generateFile();\n}\n\nvoid FileDecompressor::decodificate(std::string data)\n{\n QString image;\n for (int i = 0; i < data.size(); i++) {\n char mander = data.at(i);\n char mask = 1 << 7;\n for(int e = 0; e<8; e++){\n if((mander & mask)==mask)\n image.append(\"1\");\n else\n image.append(\"0\");\n mander = (mander << 1);\n }\n }\n this->imagedata = image;\n}\n\nvoid FileDecompressor::headerInterpreter()\n{\n QStringList::iterator it;\n for(it=this->header.begin(); it!=this->header.end(); it++)\n {\n this->codes.insert(it->mid(6), it->mid(0,6).prepend(\"#\"));\n }\n}\n\nvoid FileDecompressor::generateFile()\n{\n qDebug() << \"CANTIDAD DE BITS\" << this->imagedata.size();\n QString aux;\n QVector<QColor> colors;\n QString::iterator it;\n for(it=this->imagedata.begin(); it!=this->imagedata.end(); it++)\n {\n aux += *it;\n if(this->codes.contains(aux))\n {\n colors.push_back(QColor(this->codes.find(aux).value()));\n aux.clear();\n }\n }\n qDebug() << colors.size();\n\n \/\/qDebug() << colors;\n\n QImage img(this->width, this->height, QImage::Format_RGB32);\n QByteArray ba;\n QBuffer buffer(&ba);\n qDebug() << \"LLEGA\";\n \/\/Esto va a tardar por la resolucion de la imagen, no es que se colgo el programa\n int k = 0;\n for(int i=0; i<this->height; i++)\n {\n for(int j=0; j<this->width; j++)\n {\n \/\/Por cada pixel asigno un valor del Map. Deberia haber la misma cantidad de pixeles que tamaño del map.\n img.setPixel(j,i,colors.at(k).rgb());\n k++;\n }\n\n }\n qDebug() << \"SALE?\";\n\n\n \/\/Tengo que ver como guardar la imagen\n\n img.save(\"asd.png\",0,0);\/*\n img.save(&buffer, \"PNG\");\n QFile file(\"hola.png\");\n file.open(QIODevice::WriteOnly);\n file.write(ba);\n file.close();*\/\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*===========================================================================*\\\n * *\n * OpenMesh *\n * Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen *\n * www.openmesh.org *\n * *\n *---------------------------------------------------------------------------*\n * *\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Lesser General Public License as published *\n * by the Free Software Foundation, version 2.1. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*===========================================================================*\/\n\n\n\/\/== INCLUDES =================================================================\n\n\n\/\/ OpenMesh\n#include <OpenMesh\/Core\/IO\/reader\/OBJReader.hh>\n#include <OpenMesh\/Core\/IO\/IOManager.hh>\n#include <OpenMesh\/Core\/System\/omstream.hh>\n#include <OpenMesh\/Core\/Utils\/vector_cast.hh>\n#include <OpenMesh\/Core\/Utils\/color_cast.hh>\n\/\/ STL\n#if defined(OM_CC_MIPS)\n# include <ctype.h>\n\/\/\/ \\bug Workaround for STLPORT 4.6: isspace seems not to be in namespace std!\n#elif defined(_STLPORT_VERSION) && (_STLPORT_VERSION==0x460)\n# include <cctype>\n#else\n# include <cctype>\nusing std::isspace;\n#endif\n\n#ifndef WIN32\n#include <string.h>\n#endif\n\n\/\/=== NAMESPACES ==============================================================\n\n\nnamespace OpenMesh {\nnamespace IO {\n\n\n\/\/=== INSTANCIATE =============================================================\n\n\n_OBJReader_ __OBJReaderInstance;\n_OBJReader_& OBJReader() { return __OBJReaderInstance; }\n\n\n\/\/=== IMPLEMENTATION ==========================================================\n\n\n_OBJReader_::\n_OBJReader_()\n{\n IOManager().register_module(this);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\nbool\n_OBJReader_::\nread(const std::string& _filename, BaseImporter& _bi, Options& _opt)\n{\n std::fstream in( _filename.c_str(), std::ios_base::in );\n\n if (!in)\n {\n omerr() << \"[OBJReader] : cannot not open file \"\n << _filename\n << std::endl;\n return false;\n }\n\n {\n#if defined(WIN32)\n std::string::size_type dot = _filename.find_last_of(\"\\\\\/\");\n#else\n std::string::size_type dot = _filename.rfind(\"\/\");\n#endif\n path_ = (dot == std::string::npos)\n ? \".\/\"\n : std::string(_filename.substr(0,dot+1));\n }\n\n bool result = read(in, _bi, _opt);\n\n in.close();\n return result;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nbool\n_OBJReader_::\nread_material(std::fstream& _in)\n{\n std::string line;\n std::string keyWrd;\n\n std::string key;\n Material mat;\n float f1,f2,f3;\n bool indef = false;\n\n\n mat.cleanup();\n\n while( _in && !_in.eof() )\n {\n std::getline(_in,line);\n if ( _in.bad() ){\n omerr() << \" Warning! Could not read file properly!\\n\";\n return false;\n }\n\n if ( line.empty() )\n continue;\n\n std::stringstream stream(line);\n\n stream >> keyWrd;\n\n if( isspace(line[0]) || line[0] == '#' )\n {\n if (indef && !key.empty() && mat.is_valid())\n {\n materials_[key] = mat;\n mat.cleanup();\n }\n }\n\n else if (keyWrd == \"newmtl\") \/\/ begin new material definition\n {\n stream >> key;\n indef = true;\n }\n\n else if (keyWrd == \"Kd\") \/\/ diffuse color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Kd(f1,f2,f3);\n }\n\n else if (keyWrd == \"Ka\") \/\/ ambient color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Ka(f1,f2,f3);\n }\n\n else if (keyWrd == \"Ks\") \/\/ specular color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Ks(f1,f2,f3);\n }\n#if 0\n else if (keyWrd == \"illum\") \/\/ diffuse\/specular shading model\n {\n ; \/\/ just skip this\n }\n\n else if (keyWrd == \"Ns\") \/\/ Shininess [0..200]\n {\n ; \/\/ just skip this\n }\n\n else if (keyWrd == \"map_\") \/\/ map images\n {\n \/\/ map_Kd, diffuse map\n \/\/ map_Ks, specular map\n \/\/ map_Ka, ambient map\n \/\/ map_Bump, bump map\n \/\/ map_d, opacity map\n ; \/\/ just skip this\n }\n#endif\n\n else if (keyWrd == \"Tr\") \/\/ transparency value\n {\n stream >> f1;\n\n if( !stream.fail() )\n mat.set_Tr(f1);\n }\n else if (keyWrd == \"d\") \/\/ transparency value\n {\n stream >> f1;\n\n if( !stream.fail() )\n mat.set_Tr(f1);\n }\n\n if ( _in && indef && mat.is_valid() && !key.empty())\n materials_[key] = mat;\n }\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\nbool\n_OBJReader_::\nread(std::fstream& _in, BaseImporter& _bi, Options& _opt)\n{\n omlog() << \"[OBJReader] : read file\\n\";\n\n\n std::string line;\n std::string keyWrd;\n\n float x, y, z, u, v;\n\n BaseImporter::VHandles vhandles;\n std::vector<Vec3f> normals;\n std::vector<Vec2f> texcoords;\n\n std::vector<Vec2f> face_texcoords;\n\n std::map<std::string,Material> materials;\n std::string matname;\n\n\n while( _in && !_in.eof() )\n {\n std::getline(_in,line);\n if ( _in.bad() ){\n omerr() << \" Warning! Could not read file properly!\\n\";\n return false;\n }\n\n \/\/ Trim Both leading and trailing spaces\n\n size_t start = line.find_first_not_of(\" \\t\");\n size_t end = line.find_last_not_of(\" \\t\");\n\n if(( std::string::npos == start ) || ( std::string::npos == end))\n line = \"\";\n else\n line = line.substr( start, end-start+1 );\n\n \/\/ comment\n if ( line.size() == 0 || line[0] == '#' || isspace(line[0]) ) {\n continue;\n }\n\n std::stringstream stream(line);\n\n stream >> keyWrd;\n\n \/\/ material file\n if (keyWrd == \"mtllib\")\n {\n std::string matFile;\n\n stream >> matFile;\n\n matFile = path_ + matFile;\n\n omlog() << \"Load material file \" << matFile << std::endl;\n\n std::fstream matStream( matFile.c_str(), std::ios_base::in );\n\n if ( matStream ){\n\n if ( !read_material( matStream ) )\n\t omerr() << \" Warning! Could not read file properly!\\n\";\n matStream.close();\n\t omlog() << \" \" << materials_.size() << \" materials loaded.\\n\";\n\n }else\n\t omerr() << \" Warning! Material file '\" << matFile << \"' not found!\\n\";\n }\n\n \/\/ usemtl\n else if (keyWrd == \"usemtl\")\n {\n stream >> matname;\n if (materials_.find(matname)==materials_.end())\n {\n omerr() << \"Warning! Material '\" << matname\n << \"' not defined in material file.\\n\";\n matname=\"\";\n }\n }\n\n \/\/ vertex\n else if (keyWrd == \"v\")\n {\n stream >> x; stream >> y; stream >> z;\n\n if ( !stream.fail() )\n _bi.add_vertex(OpenMesh::Vec3f(x,y,z));\n }\n\n \/\/ texture coord\n else if (keyWrd == \"vt\")\n {\n stream >> u; stream >> v;\n\n if ( !stream.fail() ){\n\n texcoords.push_back(OpenMesh::Vec2f(u, v));\n _opt += Options::VertexTexCoord;\n\n }else{\n\n omerr() << \"Only single 2D texture coordinate per vertex\"\n << \"allowed!\" << std::endl;\n return false;\n }\n }\n\n\n \/\/ normal\n else if (keyWrd == \"vn\")\n {\n stream >> x; stream >> y; stream >> z;\n\n if ( !stream.fail() ){\n normals.push_back(OpenMesh::Vec3f(x,y,z));\n _opt += Options::VertexNormal;\n }\n }\n\n\n \/\/ face\n else if (keyWrd == \"f\")\n {\n int component(0), nV(0);\n int value;\n\n vhandles.clear();\n face_texcoords.clear();\n\n \/\/ read full line after detecting a face\n std::string faceLine;\n std::getline(stream,faceLine);\n std::stringstream lineData( faceLine );\n\n \/\/ work on the line until nothing left to read\n while ( !lineData.eof() )\n {\n \/\/ read one block from the line ( vertex\/texCoord\/normal )\n std::string vertex;\n lineData >> vertex;\n\n do{\n\n \/\/get the component (vertex\/texCoord\/normal)\n size_t found=vertex.find(\"\/\");\n\n \/\/ parts are seperated by '\/' So if no '\/' found its the last component\n if( found != std::string::npos ){\n\n \/\/ read the index value\n std::stringstream tmp( vertex.substr(0,found) );\n\n \/\/ If we get an empty string this property is undefined in the file\n if ( vertex.substr(0,found).empty() ) {\n \/\/ Switch to next field\n vertex = vertex.substr(found+1);\n\n \/\/ Now we are at the next component\n ++component;\n\n \/\/ Skip further processing of this component\n continue;\n }\n\n \/\/ Read current value\n tmp >> value;\n\n \/\/ remove the read part from the string\n vertex = vertex.substr(found+1);\n\n } else {\n\n \/\/ last component of the vertex, read it.\n std::stringstream tmp( vertex );\n tmp >> value;\n\n \/\/ Clear vertex after finished reading the line\n vertex=\"\";\n\n \/\/ Nothing to read here ( garbage at end of line )\n if ( tmp.fail() ) {\n continue;\n }\n }\n\n \/\/ store the component ( each component is referenced by the index here! )\n switch (component)\n {\n case 0: \/\/ vertex\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ vertex index value\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n vhandles.push_back(VertexHandle(value-1));\n break;\n\n case 1: \/\/ texture coord\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ texture coordinate index value)\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n assert(!vhandles.empty());\n assert((unsigned int)(value-1) < texcoords.size());\n _bi.set_texcoord(vhandles.back(), texcoords[value-1]);\n\t face_texcoords.push_back( texcoords[value-1] );\n break;\n\n case 2: \/\/ normal\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ normal index value)\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n assert(!vhandles.empty());\n assert((unsigned int)(value-1) < normals.size());\n _bi.set_normal(vhandles.back(), normals[value-1]);\n break;\n }\n\n \/\/ Prepare for reading next component\n ++component;\n\n \/\/ Read until line does not contain any other info\n } while ( !vertex.empty() );\n\n component = 0;\n nV++;\n }\n\n\n size_t n_faces = _bi.n_faces();\n FaceHandle fh = _bi.add_face(vhandles);\n\n if( !vhandles.empty() )\n\t_bi.add_face_texcoords( fh, vhandles[0], face_texcoords );\n\n if ( !matname.empty() && materials_[matname].has_Kd() )\n {\n std::vector<FaceHandle> newfaces;\n\n for( size_t i=0; i < _bi.n_faces()-n_faces; ++i )\n newfaces.push_back(FaceHandle(n_faces+i));\n\n Material & mat = materials_[matname];\n\n Vec3uc fc = color_cast<Vec3uc, Vec3f>(mat.Kd());\n\n for (std::vector<FaceHandle>::iterator it = newfaces.begin();\n it != newfaces.end(); ++it)\n _bi.set_color( *it, fc );\n\n _opt += Options::FaceColor;\n }\n }\n }\n\n return true;\n}\n\n\n\/\/=============================================================================\n} \/\/ namespace IO\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n<commit_msg>Improved OBJ Reader to not segfault on problems regarding texture coordinates<commit_after>\/*===========================================================================*\\\n * *\n * OpenMesh *\n * Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen *\n * www.openmesh.org *\n * *\n *---------------------------------------------------------------------------*\n * *\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Lesser General Public License as published *\n * by the Free Software Foundation, version 2.1. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*===========================================================================*\/\n\n\n\/\/== INCLUDES =================================================================\n\n\n\/\/ OpenMesh\n#include <OpenMesh\/Core\/IO\/reader\/OBJReader.hh>\n#include <OpenMesh\/Core\/IO\/IOManager.hh>\n#include <OpenMesh\/Core\/System\/omstream.hh>\n#include <OpenMesh\/Core\/Utils\/vector_cast.hh>\n#include <OpenMesh\/Core\/Utils\/color_cast.hh>\n\/\/ STL\n#if defined(OM_CC_MIPS)\n# include <ctype.h>\n\/\/\/ \\bug Workaround for STLPORT 4.6: isspace seems not to be in namespace std!\n#elif defined(_STLPORT_VERSION) && (_STLPORT_VERSION==0x460)\n# include <cctype>\n#else\n# include <cctype>\nusing std::isspace;\n#endif\n\n#ifndef WIN32\n#include <string.h>\n#endif\n\n\/\/=== NAMESPACES ==============================================================\n\n\nnamespace OpenMesh {\nnamespace IO {\n\n\n\/\/=== INSTANCIATE =============================================================\n\n\n_OBJReader_ __OBJReaderInstance;\n_OBJReader_& OBJReader() { return __OBJReaderInstance; }\n\n\n\/\/=== IMPLEMENTATION ==========================================================\n\n\n_OBJReader_::\n_OBJReader_()\n{\n IOManager().register_module(this);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\nbool\n_OBJReader_::\nread(const std::string& _filename, BaseImporter& _bi, Options& _opt)\n{\n std::fstream in( _filename.c_str(), std::ios_base::in );\n\n if (!in)\n {\n omerr() << \"[OBJReader] : cannot not open file \"\n << _filename\n << std::endl;\n return false;\n }\n\n {\n#if defined(WIN32)\n std::string::size_type dot = _filename.find_last_of(\"\\\\\/\");\n#else\n std::string::size_type dot = _filename.rfind(\"\/\");\n#endif\n path_ = (dot == std::string::npos)\n ? \".\/\"\n : std::string(_filename.substr(0,dot+1));\n }\n\n bool result = read(in, _bi, _opt);\n\n in.close();\n return result;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\nbool\n_OBJReader_::\nread_material(std::fstream& _in)\n{\n std::string line;\n std::string keyWrd;\n\n std::string key;\n Material mat;\n float f1,f2,f3;\n bool indef = false;\n\n\n mat.cleanup();\n\n while( _in && !_in.eof() )\n {\n std::getline(_in,line);\n if ( _in.bad() ){\n omerr() << \" Warning! Could not read file properly!\\n\";\n return false;\n }\n\n if ( line.empty() )\n continue;\n\n std::stringstream stream(line);\n\n stream >> keyWrd;\n\n if( isspace(line[0]) || line[0] == '#' )\n {\n if (indef && !key.empty() && mat.is_valid())\n {\n materials_[key] = mat;\n mat.cleanup();\n }\n }\n\n else if (keyWrd == \"newmtl\") \/\/ begin new material definition\n {\n stream >> key;\n indef = true;\n }\n\n else if (keyWrd == \"Kd\") \/\/ diffuse color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Kd(f1,f2,f3);\n }\n\n else if (keyWrd == \"Ka\") \/\/ ambient color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Ka(f1,f2,f3);\n }\n\n else if (keyWrd == \"Ks\") \/\/ specular color\n {\n stream >> f1; stream >> f2; stream >> f3;\n\n if( !stream.fail() )\n mat.set_Ks(f1,f2,f3);\n }\n#if 0\n else if (keyWrd == \"illum\") \/\/ diffuse\/specular shading model\n {\n ; \/\/ just skip this\n }\n\n else if (keyWrd == \"Ns\") \/\/ Shininess [0..200]\n {\n ; \/\/ just skip this\n }\n\n else if (keyWrd == \"map_\") \/\/ map images\n {\n \/\/ map_Kd, diffuse map\n \/\/ map_Ks, specular map\n \/\/ map_Ka, ambient map\n \/\/ map_Bump, bump map\n \/\/ map_d, opacity map\n ; \/\/ just skip this\n }\n#endif\n\n else if (keyWrd == \"Tr\") \/\/ transparency value\n {\n stream >> f1;\n\n if( !stream.fail() )\n mat.set_Tr(f1);\n }\n else if (keyWrd == \"d\") \/\/ transparency value\n {\n stream >> f1;\n\n if( !stream.fail() )\n mat.set_Tr(f1);\n }\n\n if ( _in && indef && mat.is_valid() && !key.empty())\n materials_[key] = mat;\n }\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\nbool\n_OBJReader_::\nread(std::fstream& _in, BaseImporter& _bi, Options& _opt)\n{\n omlog() << \"[OBJReader] : read file\\n\";\n\n\n std::string line;\n std::string keyWrd;\n\n float x, y, z, u, v;\n\n BaseImporter::VHandles vhandles;\n std::vector<Vec3f> normals;\n std::vector<Vec2f> texcoords;\n\n std::vector<Vec2f> face_texcoords;\n\n std::map<std::string,Material> materials;\n std::string matname;\n\n\n while( _in && !_in.eof() )\n {\n std::getline(_in,line);\n if ( _in.bad() ){\n omerr() << \" Warning! Could not read file properly!\\n\";\n return false;\n }\n\n \/\/ Trim Both leading and trailing spaces\n\n size_t start = line.find_first_not_of(\" \\t\");\n size_t end = line.find_last_not_of(\" \\t\");\n\n if(( std::string::npos == start ) || ( std::string::npos == end))\n line = \"\";\n else\n line = line.substr( start, end-start+1 );\n\n \/\/ comment\n if ( line.size() == 0 || line[0] == '#' || isspace(line[0]) ) {\n continue;\n }\n\n std::stringstream stream(line);\n\n stream >> keyWrd;\n\n \/\/ material file\n if (keyWrd == \"mtllib\")\n {\n std::string matFile;\n\n stream >> matFile;\n\n matFile = path_ + matFile;\n\n omlog() << \"Load material file \" << matFile << std::endl;\n\n std::fstream matStream( matFile.c_str(), std::ios_base::in );\n\n if ( matStream ){\n\n if ( !read_material( matStream ) )\n\t omerr() << \" Warning! Could not read file properly!\\n\";\n matStream.close();\n\t omlog() << \" \" << materials_.size() << \" materials loaded.\\n\";\n\n }else\n\t omerr() << \" Warning! Material file '\" << matFile << \"' not found!\\n\";\n }\n\n \/\/ usemtl\n else if (keyWrd == \"usemtl\")\n {\n stream >> matname;\n if (materials_.find(matname)==materials_.end())\n {\n omerr() << \"Warning! Material '\" << matname\n << \"' not defined in material file.\\n\";\n matname=\"\";\n }\n }\n\n \/\/ vertex\n else if (keyWrd == \"v\")\n {\n stream >> x; stream >> y; stream >> z;\n\n if ( !stream.fail() )\n _bi.add_vertex(OpenMesh::Vec3f(x,y,z));\n }\n\n \/\/ texture coord\n else if (keyWrd == \"vt\")\n {\n stream >> u; stream >> v;\n\n if ( !stream.fail() ){\n\n texcoords.push_back(OpenMesh::Vec2f(u, v));\n _opt += Options::VertexTexCoord;\n\n }else{\n\n omerr() << \"Only single 2D texture coordinate per vertex\"\n << \"allowed!\" << std::endl;\n return false;\n }\n }\n\n\n \/\/ normal\n else if (keyWrd == \"vn\")\n {\n stream >> x; stream >> y; stream >> z;\n\n if ( !stream.fail() ){\n normals.push_back(OpenMesh::Vec3f(x,y,z));\n _opt += Options::VertexNormal;\n }\n }\n\n\n \/\/ face\n else if (keyWrd == \"f\")\n {\n int component(0), nV(0);\n int value;\n\n vhandles.clear();\n face_texcoords.clear();\n\n \/\/ read full line after detecting a face\n std::string faceLine;\n std::getline(stream,faceLine);\n std::stringstream lineData( faceLine );\n\n \/\/ work on the line until nothing left to read\n while ( !lineData.eof() )\n {\n \/\/ read one block from the line ( vertex\/texCoord\/normal )\n std::string vertex;\n lineData >> vertex;\n\n do{\n\n \/\/get the component (vertex\/texCoord\/normal)\n size_t found=vertex.find(\"\/\");\n\n \/\/ parts are seperated by '\/' So if no '\/' found its the last component\n if( found != std::string::npos ){\n\n \/\/ read the index value\n std::stringstream tmp( vertex.substr(0,found) );\n\n \/\/ If we get an empty string this property is undefined in the file\n if ( vertex.substr(0,found).empty() ) {\n \/\/ Switch to next field\n vertex = vertex.substr(found+1);\n\n \/\/ Now we are at the next component\n ++component;\n\n \/\/ Skip further processing of this component\n continue;\n }\n\n \/\/ Read current value\n tmp >> value;\n\n \/\/ remove the read part from the string\n vertex = vertex.substr(found+1);\n\n } else {\n\n \/\/ last component of the vertex, read it.\n std::stringstream tmp( vertex );\n tmp >> value;\n\n \/\/ Clear vertex after finished reading the line\n vertex=\"\";\n\n \/\/ Nothing to read here ( garbage at end of line )\n if ( tmp.fail() ) {\n continue;\n }\n }\n\n \/\/ store the component ( each component is referenced by the index here! )\n switch (component)\n {\n case 0: \/\/ vertex\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ vertex index value\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n vhandles.push_back(VertexHandle(value-1));\n break;\n\n case 1: \/\/ texture coord\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ texture coordinate index value)\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n assert(!vhandles.empty());\n if ( ! texcoords.empty() && (unsigned int)(value-1) < texcoords.size() ) {\n _bi.set_texcoord(vhandles.back(), texcoords[value-1]);\n face_texcoords.push_back( texcoords[value-1] );\n } else {\n omerr() << \"Error setting Texture coordinates\" << std::endl;\n }\n\n break;\n\n case 2: \/\/ normal\n if ( value < 0 ) {\n\/\/ std::cerr << \"Handling negativ normal index value)\" << std::endl;\n value = _bi.n_vertices() + value + 1;\n }\n assert(!vhandles.empty());\n assert((unsigned int)(value-1) < normals.size());\n _bi.set_normal(vhandles.back(), normals[value-1]);\n break;\n }\n\n \/\/ Prepare for reading next component\n ++component;\n\n \/\/ Read until line does not contain any other info\n } while ( !vertex.empty() );\n\n component = 0;\n nV++;\n }\n\n\n size_t n_faces = _bi.n_faces();\n FaceHandle fh = _bi.add_face(vhandles);\n\n if( !vhandles.empty() )\n\t_bi.add_face_texcoords( fh, vhandles[0], face_texcoords );\n\n if ( !matname.empty() && materials_[matname].has_Kd() )\n {\n std::vector<FaceHandle> newfaces;\n\n for( size_t i=0; i < _bi.n_faces()-n_faces; ++i )\n newfaces.push_back(FaceHandle(n_faces+i));\n\n Material & mat = materials_[matname];\n\n Vec3uc fc = color_cast<Vec3uc, Vec3f>(mat.Kd());\n\n for (std::vector<FaceHandle>::iterator it = newfaces.begin();\n it != newfaces.end(); ++it)\n _bi.set_color( *it, fc );\n\n _opt += Options::FaceColor;\n }\n }\n }\n\n return true;\n}\n\n\n\/\/=============================================================================\n} \/\/ namespace IO\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_db_object_event.cpp\n\/\/\n\n#include \"yas_db_object_event.h\"\n\n#include \"yas_db_object.h\"\n\nusing namespace yas;\nusing namespace yas::db;\n\nnamespace yas::db {\nstatic db::object_ptr const _empty_object = nullptr;\nstatic db::object_id const _empty_object_id = nullptr;\nstatic std::string const _empty_string;\nstatic std::vector<std::size_t> const _empty_indices;\nstatic db::value const _empty_value = nullptr;\n\nstruct object_fetched_event {\n static object_event_type const type = object_event_type::fetched;\n db::object_ptr const &object;\n};\n\nstruct object_loaded_event {\n static object_event_type const type = object_event_type::loaded;\n db::object_ptr const &object;\n};\n\nstruct object_cleared_event {\n static object_event_type const type = object_event_type::cleared;\n db::object_ptr const &object;\n};\n\nstruct object_attribute_updated_event {\n static object_event_type const type = object_event_type::attribute_updated;\n db::object_ptr const &object;\n std::string const name;\n db::value const &value;\n};\n\nstruct object_relation_inserted_event {\n static object_event_type const type = object_event_type::relation_inserted;\n db::object_ptr const &object;\n std::string const name;\n std::vector<std::size_t> const indices;\n};\n\nstruct object_relation_removed_event {\n static object_event_type const type = object_event_type::relation_removed;\n db::object_ptr const &object;\n std::string const name;\n std::vector<std::size_t> const indices;\n};\n\nstruct object_relation_replaced_event {\n static object_event_type const type = object_event_type::relation_replaced;\n db::object_ptr const &object;\n std::string const name;\n};\n\nstruct object_erased_event {\n static object_event_type const type = object_event_type::erased;\n std::string const &entity_name;\n db::object_id const &object_id;\n};\n} \/\/ namespace yas::db\n\nobject_event db::object_event::make_fetched(db::object_ptr const &object) {\n return object_event{object_fetched_event{.object = object}};\n}\n\nobject_event db::object_event::make_loaded(db::object_ptr const &object) {\n return object_event{object_loaded_event{.object = object}};\n}\n\nobject_event db::object_event::make_cleared(db::object_ptr const &object) {\n return object_event{object_cleared_event{.object = object}};\n}\n\nobject_event db::object_event::make_attribute_updated(db::object_ptr const &object, std::string const &name,\n db::value const &value) {\n return object_event{object_attribute_updated_event{.object = object, .name = name, .value = value}};\n}\n\nobject_event db::object_event::make_relation_inserted(db::object_ptr const &object, std::string const &name,\n std::vector<std::size_t> &&indices) {\n return object_event{object_relation_inserted_event{.object = object, .name = name, .indices = std::move(indices)}};\n}\n\nobject_event db::object_event::make_relation_removed(db::object_ptr const &object, std::string const &name,\n std::vector<std::size_t> &&indices) {\n return object_event{object_relation_removed_event{.object = object, .name = name, .indices = std::move(indices)}};\n}\n\nobject_event db::object_event::make_relation_replaced(db::object_ptr const &object, std::string const &name) {\n return object_event{object_relation_replaced_event{.object = object, .name = name}};\n}\n\nobject_event db::object_event::make_erased(std::string const &entity_name, db::object_id const &object_id) {\n return object_event{object_erased_event{.entity_name = entity_name, .object_id = object_id}};\n}\n\nstruct object_event::impl_base {\n virtual object_event_type type() {\n throw std::runtime_error(\"type() must be overridden\");\n }\n};\n\ntemplate <typename Event>\nstruct object_event::impl : object_event::impl_base {\n Event const event;\n\n impl(Event &&event) : event(std::move(event)) {\n }\n\n object_event_type type() override {\n return Event::type;\n }\n};\n\nobject_event::object_event(std::shared_ptr<impl_base> &&impl)\n : _impl(std::move(impl)),\n _type(object_event_type::fetched),\n _object(_empty_object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_fetched_event &&event)\n : _type(object_event_type::fetched),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_loaded_event &&event)\n : _type(object_event_type::loaded),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_cleared_event &&event)\n : _type(object_event_type::cleared),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_attribute_updated_event &&event)\n : _type(object_event_type::attribute_updated),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(event.value) {\n}\n\nobject_event::object_event(object_relation_inserted_event &&event)\n : _type(object_event_type::relation_inserted),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(event.indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_relation_removed_event &&event)\n : _type(object_event_type::relation_removed),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(event.indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_relation_replaced_event &&event)\n : object_event(std::make_shared<impl<object_relation_replaced_event>>(std::move(event))) {\n}\n\nobject_event::object_event(object_erased_event &&event)\n : object_event(std::make_shared<impl<object_erased_event>>(std::move(event))) {\n}\n\nobject_event_type object_event::type() const {\n return this->_impl->type();\n}\n\ntemplate <typename Event>\nEvent const &object_event::get() const {\n if (auto ip = std::dynamic_pointer_cast<impl<Event>>(this->_impl)) {\n return ip->event;\n }\n\n throw std::runtime_error(\"get event failed.\");\n}\n\nbool object_event::is_changed() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::relation_replaced:\n return true;\n default:\n return false;\n }\n}\n\nbool object_event::is_erased() const {\n return this->type() == object_event_type::erased;\n}\n\ndb::object_ptr const &object_event::object() const {\n switch (this->type()) {\n case object_event_type::fetched:\n return this->get<db::object_fetched_event>().object;\n case object_event_type::loaded:\n return this->get<db::object_loaded_event>().object;\n case object_event_type::cleared:\n return this->get<db::object_cleared_event>().object;\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().object;\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().object;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().object;\n case object_event_type::relation_replaced:\n return this->get<db::object_relation_replaced_event>().object;\n case object_event_type::erased:\n throw std::runtime_error(\"object not found.\");\n }\n}\n\ndb::object_id const &object_event::object_id() const {\n switch (this->type()) {\n case object_event_type::erased:\n return this->get<db::object_erased_event>().object_id;\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::relation_replaced:\n return this->object()->object_id();\n }\n}\n\nstd::string const &object_event::name() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().name;\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().name;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().name;\n case object_event_type::relation_replaced:\n return this->get<db::object_relation_replaced_event>().name;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::erased:\n throw std::runtime_error(\"name not found.\");\n }\n}\n\nstd::string const &object_event::entity_name() const {\n switch (this->type()) {\n case object_event_type::erased:\n return this->get<db::object_erased_event>().entity_name;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::relation_replaced:\n throw std::runtime_error(\"entity name not found.\");\n }\n}\n\nstd::vector<std::size_t> const &object_event::indices() const {\n switch (this->type()) {\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().indices;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().indices;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::attribute_updated:\n case object_event_type::relation_replaced:\n case object_event_type::erased:\n throw std::runtime_error(\"indices not found.\");\n }\n}\n\ndb::value const &object_event::value() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().value;\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::relation_replaced:\n case object_event_type::erased:\n throw std::runtime_error(\"indices not found.\");\n }\n}\n\ntemplate db::object_fetched_event const &object_event::get<db::object_fetched_event>() const;\ntemplate db::object_loaded_event const &object_event::get<db::object_loaded_event>() const;\ntemplate db::object_cleared_event const &object_event::get<db::object_cleared_event>() const;\ntemplate db::object_attribute_updated_event const &object_event::get<db::object_attribute_updated_event>() const;\ntemplate db::object_relation_inserted_event const &object_event::get<db::object_relation_inserted_event>() const;\ntemplate db::object_relation_removed_event const &object_event::get<db::object_relation_removed_event>() const;\ntemplate db::object_relation_replaced_event const &object_event::get<db::object_relation_replaced_event>() const;\ntemplate db::object_erased_event const &object_event::get<db::object_erased_event>() const;\n<commit_msg>relation_replaced_event<commit_after>\/\/\n\/\/ yas_db_object_event.cpp\n\/\/\n\n#include \"yas_db_object_event.h\"\n\n#include \"yas_db_object.h\"\n\nusing namespace yas;\nusing namespace yas::db;\n\nnamespace yas::db {\nstatic db::object_ptr const _empty_object = nullptr;\nstatic db::object_id const _empty_object_id = nullptr;\nstatic std::string const _empty_string;\nstatic std::vector<std::size_t> const _empty_indices;\nstatic db::value const _empty_value = nullptr;\n\nstruct object_fetched_event {\n static object_event_type const type = object_event_type::fetched;\n db::object_ptr const &object;\n};\n\nstruct object_loaded_event {\n static object_event_type const type = object_event_type::loaded;\n db::object_ptr const &object;\n};\n\nstruct object_cleared_event {\n static object_event_type const type = object_event_type::cleared;\n db::object_ptr const &object;\n};\n\nstruct object_attribute_updated_event {\n static object_event_type const type = object_event_type::attribute_updated;\n db::object_ptr const &object;\n std::string const name;\n db::value const &value;\n};\n\nstruct object_relation_inserted_event {\n static object_event_type const type = object_event_type::relation_inserted;\n db::object_ptr const &object;\n std::string const name;\n std::vector<std::size_t> const indices;\n};\n\nstruct object_relation_removed_event {\n static object_event_type const type = object_event_type::relation_removed;\n db::object_ptr const &object;\n std::string const name;\n std::vector<std::size_t> const indices;\n};\n\nstruct object_relation_replaced_event {\n static object_event_type const type = object_event_type::relation_replaced;\n db::object_ptr const &object;\n std::string const name;\n};\n\nstruct object_erased_event {\n static object_event_type const type = object_event_type::erased;\n std::string const &entity_name;\n db::object_id const &object_id;\n};\n} \/\/ namespace yas::db\n\nobject_event db::object_event::make_fetched(db::object_ptr const &object) {\n return object_event{object_fetched_event{.object = object}};\n}\n\nobject_event db::object_event::make_loaded(db::object_ptr const &object) {\n return object_event{object_loaded_event{.object = object}};\n}\n\nobject_event db::object_event::make_cleared(db::object_ptr const &object) {\n return object_event{object_cleared_event{.object = object}};\n}\n\nobject_event db::object_event::make_attribute_updated(db::object_ptr const &object, std::string const &name,\n db::value const &value) {\n return object_event{object_attribute_updated_event{.object = object, .name = name, .value = value}};\n}\n\nobject_event db::object_event::make_relation_inserted(db::object_ptr const &object, std::string const &name,\n std::vector<std::size_t> &&indices) {\n return object_event{object_relation_inserted_event{.object = object, .name = name, .indices = std::move(indices)}};\n}\n\nobject_event db::object_event::make_relation_removed(db::object_ptr const &object, std::string const &name,\n std::vector<std::size_t> &&indices) {\n return object_event{object_relation_removed_event{.object = object, .name = name, .indices = std::move(indices)}};\n}\n\nobject_event db::object_event::make_relation_replaced(db::object_ptr const &object, std::string const &name) {\n return object_event{object_relation_replaced_event{.object = object, .name = name}};\n}\n\nobject_event db::object_event::make_erased(std::string const &entity_name, db::object_id const &object_id) {\n return object_event{object_erased_event{.entity_name = entity_name, .object_id = object_id}};\n}\n\nstruct object_event::impl_base {\n virtual object_event_type type() {\n throw std::runtime_error(\"type() must be overridden\");\n }\n};\n\ntemplate <typename Event>\nstruct object_event::impl : object_event::impl_base {\n Event const event;\n\n impl(Event &&event) : event(std::move(event)) {\n }\n\n object_event_type type() override {\n return Event::type;\n }\n};\n\nobject_event::object_event(std::shared_ptr<impl_base> &&impl)\n : _impl(std::move(impl)),\n _type(object_event_type::fetched),\n _object(_empty_object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_fetched_event &&event)\n : _type(object_event_type::fetched),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_loaded_event &&event)\n : _type(object_event_type::loaded),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_cleared_event &&event)\n : _type(object_event_type::cleared),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(_empty_string),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_attribute_updated_event &&event)\n : _type(object_event_type::attribute_updated),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(event.value) {\n}\n\nobject_event::object_event(object_relation_inserted_event &&event)\n : _type(object_event_type::relation_inserted),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(event.indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_relation_removed_event &&event)\n : _type(object_event_type::relation_removed),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(event.indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_relation_replaced_event &&event)\n : _type(object_event_type::relation_replaced),\n _object(event.object),\n _object_id(_empty_object_id),\n _name(event.name),\n _entity_name(_empty_string),\n _indices(_empty_indices),\n _value(_empty_value) {\n}\n\nobject_event::object_event(object_erased_event &&event)\n : object_event(std::make_shared<impl<object_erased_event>>(std::move(event))) {\n}\n\nobject_event_type object_event::type() const {\n return this->_impl->type();\n}\n\ntemplate <typename Event>\nEvent const &object_event::get() const {\n if (auto ip = std::dynamic_pointer_cast<impl<Event>>(this->_impl)) {\n return ip->event;\n }\n\n throw std::runtime_error(\"get event failed.\");\n}\n\nbool object_event::is_changed() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::relation_replaced:\n return true;\n default:\n return false;\n }\n}\n\nbool object_event::is_erased() const {\n return this->type() == object_event_type::erased;\n}\n\ndb::object_ptr const &object_event::object() const {\n switch (this->type()) {\n case object_event_type::fetched:\n return this->get<db::object_fetched_event>().object;\n case object_event_type::loaded:\n return this->get<db::object_loaded_event>().object;\n case object_event_type::cleared:\n return this->get<db::object_cleared_event>().object;\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().object;\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().object;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().object;\n case object_event_type::relation_replaced:\n return this->get<db::object_relation_replaced_event>().object;\n case object_event_type::erased:\n throw std::runtime_error(\"object not found.\");\n }\n}\n\ndb::object_id const &object_event::object_id() const {\n switch (this->type()) {\n case object_event_type::erased:\n return this->get<db::object_erased_event>().object_id;\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::relation_replaced:\n return this->object()->object_id();\n }\n}\n\nstd::string const &object_event::name() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().name;\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().name;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().name;\n case object_event_type::relation_replaced:\n return this->get<db::object_relation_replaced_event>().name;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::erased:\n throw std::runtime_error(\"name not found.\");\n }\n}\n\nstd::string const &object_event::entity_name() const {\n switch (this->type()) {\n case object_event_type::erased:\n return this->get<db::object_erased_event>().entity_name;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::attribute_updated:\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::relation_replaced:\n throw std::runtime_error(\"entity name not found.\");\n }\n}\n\nstd::vector<std::size_t> const &object_event::indices() const {\n switch (this->type()) {\n case object_event_type::relation_inserted:\n return this->get<db::object_relation_inserted_event>().indices;\n case object_event_type::relation_removed:\n return this->get<db::object_relation_removed_event>().indices;\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::attribute_updated:\n case object_event_type::relation_replaced:\n case object_event_type::erased:\n throw std::runtime_error(\"indices not found.\");\n }\n}\n\ndb::value const &object_event::value() const {\n switch (this->type()) {\n case object_event_type::attribute_updated:\n return this->get<db::object_attribute_updated_event>().value;\n case object_event_type::relation_inserted:\n case object_event_type::relation_removed:\n case object_event_type::fetched:\n case object_event_type::loaded:\n case object_event_type::cleared:\n case object_event_type::relation_replaced:\n case object_event_type::erased:\n throw std::runtime_error(\"indices not found.\");\n }\n}\n\ntemplate db::object_fetched_event const &object_event::get<db::object_fetched_event>() const;\ntemplate db::object_loaded_event const &object_event::get<db::object_loaded_event>() const;\ntemplate db::object_cleared_event const &object_event::get<db::object_cleared_event>() const;\ntemplate db::object_attribute_updated_event const &object_event::get<db::object_attribute_updated_event>() const;\ntemplate db::object_relation_inserted_event const &object_event::get<db::object_relation_inserted_event>() const;\ntemplate db::object_relation_removed_event const &object_event::get<db::object_relation_removed_event>() const;\ntemplate db::object_relation_replaced_event const &object_event::get<db::object_relation_replaced_event>() const;\ntemplate db::object_erased_event const &object_event::get<db::object_erased_event>() const;\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2008 Larry Gritz and the other authors and contributors.\n All Rights Reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the software's owners nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n (This is the Modified BSD License)\n*\/\n\n#include <boost\/bind.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/regex.hpp>\n\n#include <OpenEXR\/half.h>\n\n#include <cmath>\n\n#include \"OpenImageIO\/imagebuf.h\"\n#include \"OpenImageIO\/imagebufalgo.h\"\n#include \"OpenImageIO\/imagebufalgo_util.h\"\n#include \"OpenImageIO\/dassert.h\"\n#include \"OpenImageIO\/sysutil.h\"\n#include \"OpenImageIO\/filter.h\"\n#include \"OpenImageIO\/thread.h\"\n#include \"OpenImageIO\/filesystem.h\"\n\n#ifdef USE_FREETYPE\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#endif\n\n\nOIIO_NAMESPACE_ENTER {\n\n\n#ifdef USE_FREETYPE\nnamespace { \/\/ anon\nstatic mutex ft_mutex;\nstatic FT_Library ft_library = NULL;\nstatic bool ft_broken = false;\nstatic const char * default_font_name[] = {\n \"cour\", \"Courier New\", \"FreeMono\", NULL\n };\n} \/\/ anon namespace\n#endif\n\n\nbool\nImageBufAlgo::render_text (ImageBuf &R, int x, int y, string_view text,\n int fontsize, string_view font_,\n const float *textcolor)\n{\n if (R.spec().depth > 1) {\n R.error (\"ImageBufAlgo::render_text does not support volume images\");\n return false;\n }\n\n#ifdef USE_FREETYPE\n \/\/ If we know FT is broken, don't bother trying again\n if (ft_broken)\n return false;\n\n \/\/ Thread safety\n lock_guard ft_lock (ft_mutex);\n int error = 0;\n\n \/\/ If FT not yet initialized, do it now.\n if (! ft_library) {\n error = FT_Init_FreeType (&ft_library);\n if (error) {\n ft_broken = true;\n R.error (\"Could not initialize FreeType for font rendering\");\n return false;\n }\n }\n\n \/\/ A set of likely directories for fonts to live, across several systems.\n std::vector<std::string> search_dirs;\n const char *home = getenv (\"HOME\");\n if (home && *home) {\n std::string h (home);\n search_dirs.push_back (h + \"\/fonts\");\n search_dirs.push_back (h + \"\/Fonts\");\n search_dirs.push_back (h + \"\/Library\/Fonts\");\n }\n const char *systemRoot = getenv (\"SystemRoot\");\n if (systemRoot && *systemRoot) {\n std::string sysroot (systemRoot);\n search_dirs.push_back (sysroot + \"\/Fonts\");\n }\n search_dirs.push_back (\"\/usr\/share\/fonts\");\n search_dirs.push_back (\"\/Library\/Fonts\");\n search_dirs.push_back (\"C:\/Windows\/Fonts\");\n search_dirs.push_back (\"\/opt\/local\/share\/fonts\");\n\n \/\/ Try to find the font. Experiment with several extensions\n std::string font = font_;\n if (font.empty()) {\n \/\/ nothing specified -- look for something to use as a default.\n for (int j = 0; default_font_name[j] && font.empty(); ++j) {\n static const char *extensions[] = { \"\", \".ttf\", \".pfa\", \".pfb\", NULL };\n for (int i = 0; font.empty() && extensions[i]; ++i)\n font = Filesystem::searchpath_find (std::string(default_font_name[j])+extensions[i],\n search_dirs, true, true);\n }\n if (font.empty()) {\n R.error (\"Could not set default font face\");\n return false;\n }\n } else if (Filesystem::is_regular (font)) {\n \/\/ directly specified a filename -- use it\n } else {\n \/\/ A font name was specified but it's not a full path, look for it\n std::string f;\n static const char *extensions[] = { \"\", \".ttf\", \".pfa\", \".pfb\", NULL };\n for (int i = 0; f.empty() && extensions[i]; ++i)\n f = Filesystem::searchpath_find (font+extensions[i],\n search_dirs, true, true);\n if (f.empty()) {\n R.error (\"Could not set font face to \\\"%s\\\"\", font);\n return false;\n }\n font = f;\n }\n\n ASSERT (! font.empty());\n if (! Filesystem::is_regular (font)) {\n R.error (\"Could not find font \\\"%s\\\"\", font);\n return false;\n }\n\n FT_Face face; \/\/ handle to face object\n error = FT_New_Face (ft_library, font.c_str(), 0 \/* face index *\/, &face);\n if (error) {\n R.error (\"Could not set font face to \\\"%s\\\"\", font);\n return false; \/\/ couldn't open the face\n }\n\n error = FT_Set_Pixel_Sizes (face, \/\/ handle to face object\n 0, \/\/ pixel_width\n fontsize); \/\/ pixel_heigh\n if (error) {\n FT_Done_Face (face);\n R.error (\"Could not set font size to %d\", fontsize);\n return false; \/\/ couldn't set the character size\n }\n\n FT_GlyphSlot slot = face->glyph; \/\/ a small shortcut\n int nchannels = R.spec().nchannels;\n float *pixelcolor = ALLOCA (float, nchannels);\n if (! textcolor) {\n float *localtextcolor = ALLOCA (float, nchannels);\n for (int c = 0; c < nchannels; ++c)\n localtextcolor[c] = 1.0f;\n textcolor = localtextcolor;\n }\n\n for (size_t n = 0, e = text.size(); n < e; ++n) {\n \/\/ load glyph image into the slot (erase previous one)\n error = FT_Load_Char (face, text[n], FT_LOAD_RENDER);\n if (error)\n continue; \/\/ ignore errors\n \/\/ now, draw to our target surface\n for (int j = 0; j < slot->bitmap.rows; ++j) {\n int ry = y + j - slot->bitmap_top;\n for (int i = 0; i < slot->bitmap.width; ++i) {\n int rx = x + i + slot->bitmap_left;\n float b = slot->bitmap.buffer[slot->bitmap.pitch*j+i] \/ 255.0f;\n R.getpixel (rx, ry, pixelcolor);\n for (int c = 0; c < nchannels; ++c)\n pixelcolor[c] = b*textcolor[c] + (1.0f-b) * pixelcolor[c];\n R.setpixel (rx, ry, pixelcolor);\n }\n }\n \/\/ increment pen position\n x += slot->advance.x >> 6;\n }\n\n FT_Done_Face (face);\n return true;\n\n#else\n R.error (\"OpenImageIO was not compiled with FreeType for font rendering\");\n return false; \/\/ Font rendering not supported\n#endif\n}\n\n\n\n} OIIO_NAMESPACE_EXIT\n<commit_msg>Fix build with freetype>=2.5.4<commit_after>\/*\n Copyright 2008 Larry Gritz and the other authors and contributors.\n All Rights Reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the software's owners nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n (This is the Modified BSD License)\n*\/\n\n#include <boost\/bind.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/regex.hpp>\n\n#include <OpenEXR\/half.h>\n\n#include <cmath>\n\n#include \"OpenImageIO\/imagebuf.h\"\n#include \"OpenImageIO\/imagebufalgo.h\"\n#include \"OpenImageIO\/imagebufalgo_util.h\"\n#include \"OpenImageIO\/dassert.h\"\n#include \"OpenImageIO\/sysutil.h\"\n#include \"OpenImageIO\/filter.h\"\n#include \"OpenImageIO\/thread.h\"\n#include \"OpenImageIO\/filesystem.h\"\n\n#ifdef USE_FREETYPE\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#endif\n\n\nOIIO_NAMESPACE_ENTER {\n\n\n#ifdef USE_FREETYPE\nnamespace { \/\/ anon\nstatic mutex ft_mutex;\nstatic FT_Library ft_library = NULL;\nstatic bool ft_broken = false;\nstatic const char * default_font_name[] = {\n \"cour\", \"Courier New\", \"FreeMono\", NULL\n };\n} \/\/ anon namespace\n#endif\n\n\nbool\nImageBufAlgo::render_text (ImageBuf &R, int x, int y, string_view text,\n int fontsize, string_view font_,\n const float *textcolor)\n{\n if (R.spec().depth > 1) {\n R.error (\"ImageBufAlgo::render_text does not support volume images\");\n return false;\n }\n\n#ifdef USE_FREETYPE\n \/\/ If we know FT is broken, don't bother trying again\n if (ft_broken)\n return false;\n\n \/\/ Thread safety\n lock_guard ft_lock (ft_mutex);\n int error = 0;\n\n \/\/ If FT not yet initialized, do it now.\n if (! ft_library) {\n error = FT_Init_FreeType (&ft_library);\n if (error) {\n ft_broken = true;\n R.error (\"Could not initialize FreeType for font rendering\");\n return false;\n }\n }\n\n \/\/ A set of likely directories for fonts to live, across several systems.\n std::vector<std::string> search_dirs;\n const char *home = getenv (\"HOME\");\n if (home && *home) {\n std::string h (home);\n search_dirs.push_back (h + \"\/fonts\");\n search_dirs.push_back (h + \"\/Fonts\");\n search_dirs.push_back (h + \"\/Library\/Fonts\");\n }\n const char *systemRoot = getenv (\"SystemRoot\");\n if (systemRoot && *systemRoot) {\n std::string sysroot (systemRoot);\n search_dirs.push_back (sysroot + \"\/Fonts\");\n }\n search_dirs.push_back (\"\/usr\/share\/fonts\");\n search_dirs.push_back (\"\/Library\/Fonts\");\n search_dirs.push_back (\"C:\/Windows\/Fonts\");\n search_dirs.push_back (\"\/opt\/local\/share\/fonts\");\n\n \/\/ Try to find the font. Experiment with several extensions\n std::string font = font_;\n if (font.empty()) {\n \/\/ nothing specified -- look for something to use as a default.\n for (int j = 0; default_font_name[j] && font.empty(); ++j) {\n static const char *extensions[] = { \"\", \".ttf\", \".pfa\", \".pfb\", NULL };\n for (int i = 0; font.empty() && extensions[i]; ++i)\n font = Filesystem::searchpath_find (std::string(default_font_name[j])+extensions[i],\n search_dirs, true, true);\n }\n if (font.empty()) {\n R.error (\"Could not set default font face\");\n return false;\n }\n } else if (Filesystem::is_regular (font)) {\n \/\/ directly specified a filename -- use it\n } else {\n \/\/ A font name was specified but it's not a full path, look for it\n std::string f;\n static const char *extensions[] = { \"\", \".ttf\", \".pfa\", \".pfb\", NULL };\n for (int i = 0; f.empty() && extensions[i]; ++i)\n f = Filesystem::searchpath_find (font+extensions[i],\n search_dirs, true, true);\n if (f.empty()) {\n R.error (\"Could not set font face to \\\"%s\\\"\", font);\n return false;\n }\n font = f;\n }\n\n ASSERT (! font.empty());\n if (! Filesystem::is_regular (font)) {\n R.error (\"Could not find font \\\"%s\\\"\", font);\n return false;\n }\n\n FT_Face face; \/\/ handle to face object\n error = FT_New_Face (ft_library, font.c_str(), 0 \/* face index *\/, &face);\n if (error) {\n R.error (\"Could not set font face to \\\"%s\\\"\", font);\n return false; \/\/ couldn't open the face\n }\n\n error = FT_Set_Pixel_Sizes (face, \/\/ handle to face object\n 0, \/\/ pixel_width\n fontsize); \/\/ pixel_heigh\n if (error) {\n FT_Done_Face (face);\n R.error (\"Could not set font size to %d\", fontsize);\n return false; \/\/ couldn't set the character size\n }\n\n FT_GlyphSlot slot = face->glyph; \/\/ a small shortcut\n int nchannels = R.spec().nchannels;\n float *pixelcolor = ALLOCA (float, nchannels);\n if (! textcolor) {\n float *localtextcolor = ALLOCA (float, nchannels);\n for (int c = 0; c < nchannels; ++c)\n localtextcolor[c] = 1.0f;\n textcolor = localtextcolor;\n }\n\n for (size_t n = 0, e = text.size(); n < e; ++n) {\n \/\/ load glyph image into the slot (erase previous one)\n error = FT_Load_Char (face, text[n], FT_LOAD_RENDER);\n if (error)\n continue; \/\/ ignore errors\n \/\/ now, draw to our target surface\n for (int j = 0; j < static_cast<int>(slot->bitmap.rows); ++j) {\n int ry = y + j - slot->bitmap_top;\n for (int i = 0; i < static_cast<int>(slot->bitmap.width); ++i) {\n int rx = x + i + slot->bitmap_left;\n float b = slot->bitmap.buffer[slot->bitmap.pitch*j+i] \/ 255.0f;\n R.getpixel (rx, ry, pixelcolor);\n for (int c = 0; c < nchannels; ++c)\n pixelcolor[c] = b*textcolor[c] + (1.0f-b) * pixelcolor[c];\n R.setpixel (rx, ry, pixelcolor);\n }\n }\n \/\/ increment pen position\n x += slot->advance.x >> 6;\n }\n\n FT_Done_Face (face);\n return true;\n\n#else\n R.error (\"OpenImageIO was not compiled with FreeType for font rendering\");\n return false; \/\/ Font rendering not supported\n#endif\n}\n\n\n\n} OIIO_NAMESPACE_EXIT\n<|endoftext|>"} {"text":"<commit_before>\/* \r\n *\r\n *\/\r\n\r\n#include \"IPyraNet2DLayer.h\"\r\n#include <assert.h>\r\n\r\n#define UNIFORM_PLUS_MINUS_ONE ( static_cast<OutType>((2.0 * rand())\/RAND_MAX - 1.0) )\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::IPyraNet2DLayer() \r\n : IPyraNetLayer<OutType>(),\r\n width(0),\r\n height(0),\r\n receptiveSize(0),\r\n overlap(0),\r\n inhibitorySize(0)\r\n{\r\n\r\n}\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::IPyraNet2DLayer(int receptive, int inhibitory, int overlap, IPyraNetActivationFunction<OutType>* activationFunc) \r\n : IPyraNetLayer<OutType>(),\r\n width(0),\r\n height(0),\r\n receptiveSize(receptive),\r\n overlap(overlap),\r\n inhibitorySize(inhibitory)\r\n{\r\n setActivationFunction(activationFunc);\r\n}\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::~IPyraNet2DLayer() {\r\n\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::initWeights() {\r\n\r\n assert(getParentLayer() != NULL);\r\n\r\n IPyraNetLayer<OutType>* parent = getParentLayer();\r\n \r\n \/\/ get parent size\r\n int parentSize[2];\r\n parent->getSize(parentSize);\r\n\r\n \/\/ we need to have as many weights as the number of neurons in last\r\n \/\/ layer.\r\n weights.resize(parentSize[0]);\r\n\r\n for (int u = 0; u < parentSize[0]; ++u) {\r\n\r\n weights[u].resize(parentSize[1]);\r\n\r\n for (int v = 0; v < parentSize[1]; ++v) {\r\n weights[u][v] = UNIFORM_PLUS_MINUS_ONE;\r\n }\r\n }\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::initBiases() {\r\n\r\n biases.resize(width);\r\n\r\n for (int u = 0; u < width; ++u) {\r\n\r\n biases[u].resize(height);\r\n\r\n for (int v = 0; v < height; ++v) {\r\n biases[u][v] = UNIFORM_PLUS_MINUS_ONE;\r\n }\r\n }\r\n}\r\n\r\ntemplate<class OutType>\r\nOutType IPyraNet2DLayer<OutType>::getNeuronOutput(int dimensions, int* neuronLocation) {\r\n \r\n \/\/ sanity checks\r\n assert (dimensions == 2);\r\n assert (neuronLocation != NULL);\r\n assert (neuronLocation[0] > 0 && neuronLocation[1] > 0);\r\n assert (getParentLayer() != NULL);\r\n assert (getActivationFunction() != NULL);\r\n\r\n \/\/ parent layer pointer\r\n IPyraNetLayer<OutType>* parent = getParentLayer();\r\n\r\n \/\/ compute the gap\r\n const int gap = receptiveSize - overlap;\r\n\r\n \/\/ just for compliance with the article\r\n const int u = neuronLocation[0];\r\n const int v = neuronLocation[1];\r\n\r\n OutType fieldAccumulator = 0;\r\n\r\n int parentLoc[2];\r\n\r\n \/\/ iterate through the neurons inside the receptive field of the previous layer\r\n \/\/ TODO: optimize (bring the condition outside the loop)\r\n for (int i = (u - 1) * gap + 1; i <= ((u - 1) * gap + receptiveSize); ++i) {\r\n\r\n parentLoc[0] = i;\r\n \r\n for (int j = (v - 1) * gap + 1; j <= ((v - 1) * gap + receptiveSize); ++j) {\r\n \r\n parentLoc[1] = j;\r\n\r\n OutType parentOutput = parent->getNeuronOutput(2, parentLoc);\r\n OutType weight = weights[i][j];\r\n OutType bias = biases[u][v];\r\n\r\n fieldAccumulator += parentOutput * weight + bias;\r\n }\r\n }\r\n\r\n OutType result = getActivationFunction()->compute(fieldAccumulator);\r\n\r\n return result;\r\n}\r\n\r\ntemplate<class OutType>\r\nint IPyraNet2DLayer<OutType>::getDimensions() const {\r\n return 2;\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::getSize(int* size) {\r\n assert(size != NULL);\r\n\r\n size[0] = width;\r\n size[1] = height;\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::setParentLayer(IPyraNetLayer<OutType>* parent) { \r\n \r\n assert(parent != NULL);\r\n assert(receptiveSize != 0);\r\n assert(overlap != 0);\r\n\r\n \/\/ calls base class\r\n IPyraNetLayer<OutType>::setParentLayer(parent);\r\n\r\n const int dims = parent->getDimensions();\r\n\r\n \/\/ we can just connect 2d layers to 2d layers\r\n assert(dims == 2);\r\n\r\n \/\/ get parent size\r\n int parentSize[2];\r\n parent->getSize(parentSize);\r\n\r\n \/\/ compute the gap\r\n const float gap = static_cast<float>(receptiveSize - overlap);\r\n\r\n width = static_cast<int>(floor(static_cast<float>(parentSize[0] - overlap) \/ gap));\r\n height = static_cast<int>(floor(static_cast<float>(parentSize[1] - overlap) \/ gap));\r\n\r\n \/\/ init weights and biases\r\n initWeights();\r\n initBiases();\r\n}\r\n\r\n\/\/ explicit instantiations\r\ntemplate class IPyraNet2DLayer<float>;\r\ntemplate class IPyraNet2DLayer<double>;<commit_msg>Slightly refactored 2D Layer<commit_after>\/* \r\n *\r\n *\/\r\n\r\n#include \"IPyraNet2DLayer.h\"\r\n#include <assert.h>\r\n\r\n#define UNIFORM_PLUS_MINUS_ONE ( static_cast<OutType>((2.0 * rand())\/RAND_MAX - 1.0) )\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::IPyraNet2DLayer() \r\n : IPyraNetLayer<OutType>(),\r\n width(0),\r\n height(0),\r\n receptiveSize(0),\r\n overlap(0),\r\n inhibitorySize(0)\r\n{\r\n\r\n}\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::IPyraNet2DLayer(int receptive, int inhibitory, int overlap, IPyraNetActivationFunction<OutType>* activationFunc) \r\n : IPyraNetLayer<OutType>(),\r\n width(0),\r\n height(0),\r\n receptiveSize(receptive),\r\n overlap(overlap),\r\n inhibitorySize(inhibitory)\r\n{\r\n setActivationFunction(activationFunc);\r\n}\r\n\r\ntemplate<class OutType>\r\nIPyraNet2DLayer<OutType>::~IPyraNet2DLayer() {\r\n\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::initWeights() {\r\n\r\n assert(getParentLayer() != NULL);\r\n\r\n IPyraNetLayer<OutType>* parent = getParentLayer();\r\n \r\n \/\/ get parent size\r\n int parentSize[2];\r\n parent->getSize(parentSize);\r\n\r\n \/\/ we need to have as many weights as the number of neurons in last\r\n \/\/ layer.\r\n weights.resize(parentSize[0]);\r\n\r\n for (int u = 0; u < parentSize[0]; ++u) {\r\n\r\n weights[u].resize(parentSize[1]);\r\n\r\n for (int v = 0; v < parentSize[1]; ++v) {\r\n weights[u][v] = UNIFORM_PLUS_MINUS_ONE;\r\n }\r\n }\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::initBiases() {\r\n\r\n biases.resize(width);\r\n\r\n for (int u = 0; u < width; ++u) {\r\n\r\n biases[u].resize(height);\r\n\r\n for (int v = 0; v < height; ++v) {\r\n biases[u][v] = UNIFORM_PLUS_MINUS_ONE;\r\n }\r\n }\r\n}\r\n\r\ntemplate<class OutType>\r\nOutType IPyraNet2DLayer<OutType>::getNeuronOutput(int dimensions, int* neuronLocation) {\r\n \r\n \/\/ sanity checks\r\n assert (dimensions == 2);\r\n assert (neuronLocation != NULL);\r\n assert (neuronLocation[0] > 0 && neuronLocation[1] > 0);\r\n assert (getParentLayer() != NULL);\r\n assert (getActivationFunction() != NULL);\r\n\r\n \/\/ parent layer pointer\r\n IPyraNetLayer<OutType>* parent = getParentLayer();\r\n\r\n \/\/ compute the gap\r\n const int gap = receptiveSize - overlap;\r\n\r\n \/\/ just for compliance with the article\r\n const int u = neuronLocation[0];\r\n const int v = neuronLocation[1];\r\n\r\n OutType receptiveAccumulator = 0;\r\n OutType inhibitoryAccumulator = 0;\r\n OutType bias = biases[u][v];\r\n\r\n int parentLoc[2];\r\n\r\n \/\/ iterate through the neurons inside the receptive field of the previous layer\r\n const int max_u = (u - 1) * gap + receptiveSize;\r\n const int max_v = (v - 1) * gap + receptiveSize;\r\n\r\n for (int i = (u - 1) * gap + 1; i <= max_u; ++i) {\r\n\r\n parentLoc[0] = i;\r\n \r\n for (int j = (v - 1) * gap + 1; j <= max_v; ++j) {\r\n \r\n parentLoc[1] = j;\r\n\r\n OutType parentOutput = parent->getNeuronOutput(2, parentLoc);\r\n OutType weight = weights[i][j];\r\n\r\n receptiveAccumulator += parentOutput * weight;\r\n }\r\n }\r\n\r\n \/\/ iterate through the neurons inside the inhibitory field\r\n \/\/ TODO\r\n\r\n OutType result = getActivationFunction()->compute(receptiveAccumulator - inhibitoryAccumulator + bias);\r\n\r\n return result;\r\n}\r\n\r\ntemplate<class OutType>\r\nint IPyraNet2DLayer<OutType>::getDimensions() const {\r\n return 2;\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::getSize(int* size) {\r\n assert(size != NULL);\r\n\r\n size[0] = width;\r\n size[1] = height;\r\n}\r\n\r\ntemplate<class OutType>\r\nvoid IPyraNet2DLayer<OutType>::setParentLayer(IPyraNetLayer<OutType>* parent) { \r\n \r\n assert(parent != NULL);\r\n assert(receptiveSize != 0);\r\n assert(overlap != 0);\r\n\r\n \/\/ calls base class\r\n IPyraNetLayer<OutType>::setParentLayer(parent);\r\n\r\n const int dims = parent->getDimensions();\r\n\r\n \/\/ we can just connect 2d layers to 2d layers\r\n assert(dims == 2);\r\n\r\n \/\/ get parent size\r\n int parentSize[2];\r\n parent->getSize(parentSize);\r\n\r\n \/\/ compute the gap\r\n const float gap = static_cast<float>(receptiveSize - overlap);\r\n\r\n width = static_cast<int>(floor(static_cast<float>(parentSize[0] - overlap) \/ gap));\r\n height = static_cast<int>(floor(static_cast<float>(parentSize[1] - overlap) \/ gap));\r\n\r\n \/\/ init weights and biases\r\n initWeights();\r\n initBiases();\r\n}\r\n\r\n\/\/ explicit instantiations\r\ntemplate class IPyraNet2DLayer<float>;\r\ntemplate class IPyraNet2DLayer<double>;<|endoftext|>"} {"text":"<commit_before>#include \"btc_ma.h\"\n#include \"..\/..\/log\/logger.h\"\n#include \"..\/..\/network\/networkmanager.h\"\n\n#include <QDataStream>\n#include <numeric>\n#include <QtCore\/QtMath>\n\nLOGGER(BulkTransportCapacityMA);\n\nBulkTransportCapacityMA::BulkTransportCapacityMA(QObject *parent)\n: Measurement(parent)\n, m_preTest(true)\n, m_tcpSocket(NULL)\n, m_lasttime(-1)\n, m_status(Unknown)\n{\n}\n\nbool BulkTransportCapacityMA::start()\n{\n m_status = BulkTransportCapacityMA::Running;\n sendInitialRequest();\n return true;\n}\n\nvoid BulkTransportCapacityMA::sendRequest(quint64 bytes)\n{\n \/\/ invalidate timer\n m_time.invalidate();\n\n m_bytesExpected = bytes;\n QDataStream out(m_tcpSocket);\n out<<bytes;\n}\n\nvoid BulkTransportCapacityMA::sendInitialRequest()\n{\n LOG_INFO(\"Sending initial data size to server\");\n sendRequest(definition->initialDataSize);\n}\n\nvoid BulkTransportCapacityMA::receiveResponse()\n{\n qint64 time = m_time.nsecsElapsed();\n\n \/\/ if the timer is not valid this is the first response packet\n if (!m_time.isValid())\n {\n \/\/ reset variables\n m_bytesReceived = 0;\n m_lasttime = 0;\n\n \/\/ this packet counts to the total bytes, but not to the measurement bytes in m_bytesReceived\n m_totalBytesReceived = m_tcpSocket->bytesAvailable();\n\n \/\/ ignor the first data received\n m_tcpSocket->readAll();\n\n m_time.restart();\n }\n else \/\/ this is a response within an active measurement\n {\n qint64 bytes = m_tcpSocket->bytesAvailable();\n m_bytesReceivedList<<bytes;\n m_times<<time - m_lasttime;\n m_bytesReceived += bytes;\n m_totalBytesReceived += bytes;\n m_tcpSocket->readAll(); \/\/ we don't care for the data-content\n m_lasttime = time;\n }\n\n \/\/ check if all measurement data was received\n if (m_totalBytesReceived >= m_bytesExpected)\n {\n \/\/ if this was the pretest we need to calculate the bytes for the real test\n if (m_preTest)\n {\n \/\/ get the download speed in kbyte\n qreal downloadSpeed = (m_bytesReceived \/ 1024.0) \/ (((m_lasttime \/ 1000.0) \/ 1000) \/ 1000);\n\n LOG_INFO(QString(\"Speed (pretest): %1 KByte\/s\").arg(downloadSpeed, 0, 'f', 0));\n\n \/\/ Calculate new test size\n m_bytesExpected = downloadSpeed * 1024 * 3; \/\/ should be <3 seconds if the calculated speed was correct\n\n m_preTest = false;\n\n LOG_INFO(\"Sending test data size to server\");\n\n \/\/ set next state\n sendRequest(m_bytesExpected);\n }\n else\n {\n \/\/ calculate download speed for n slices\n int slices = 10; \/\/ TODO 10 slices, as parameter?\n int slice_size = m_times.size() \/ slices;\n\n \/\/ counters\n qint64 bytes = 0;\n qint64 time = 0;\n\n \/\/ calculate slices\n for (int i=0; i<m_times.size(); i++)\n {\n bytes += m_bytesReceivedList.at(i);\n time += m_times.at(i);\n\n if (((i+1) % slice_size) == 0) \/\/ calculate a slice\n {\n qreal speed = (bytes \/ 1024.0) \/ (((time \/ 1000.0) \/ 1000) \/ 1000);\n m_downloadSpeeds<<speed;\n\n \/\/ reset counters\n bytes = 0;\n time = 0;\n }\n }\n\n \/\/ calculate mean speed\n qreal sum = std::accumulate(m_downloadSpeeds.begin(), m_downloadSpeeds.end(), 0.0);\n qreal mean = sum \/ m_downloadSpeeds.size();\n LOG_INFO(QString(\"Speed (mean): %1 KByte\/s\").arg(mean, 0, 'f', 0));\n\n \/* At the moment deactivated\n \/\/ calculate standard deviation\n qreal sq_sum = std::inner_product(speeds.begin(), speeds.end(), speeds.begin(), 0.0);\n qreal stdev = qSqrt(sq_sum \/ speeds.size() - mean * mean);\n LOG_INFO(QString(\"Standard deviation: %1\").arg(stdev, 0, 'f', 0));\n *\/\n\n \/* At the moment deactivated to get all results\n \/\/ get ride of the lower and upper 20%\n qSort(speeds);\n int percentil = slices * 0.2;\n sum = std::accumulate(speeds.begin()+percentil, speeds.end()-percentil, 0.0);\n mean = sum \/ (speeds.size() - 2 * percentil);\n LOG_INFO(QString(\"Speed (60 percentil mean): %1 KByte\/s\").arg(mean, 0, 'f', 0));\n *\/\n\n m_status = BulkTransportCapacityMA::Finished;\n\n emit finished();\n }\n }\n}\n\nvoid BulkTransportCapacityMA::serverDisconnected()\n{\n if (m_status != BulkTransportCapacityMA::Finished)\n {\n LOG_WARNING(\"Server closed connection, this should not happen\");\n }\n}\n\nvoid BulkTransportCapacityMA::handleError(QAbstractSocket::SocketError socketError)\n{\n if (socketError == QAbstractSocket::RemoteHostClosedError)\n {\n return;\n }\n\n QAbstractSocket* socket = qobject_cast<QAbstractSocket*>(sender());\n LOG_ERROR(QString(\"Socket Error: %1\").arg(socket->errorString()));\n}\n\nMeasurement::Status BulkTransportCapacityMA::status() const\n{\n return m_status;\n}\n\nbool BulkTransportCapacityMA::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition)\n{\n definition = measurementDefinition.dynamicCast<BulkTransportCapacityDefinition>();\n if ( definition.isNull() )\n {\n LOG_WARNING(\"Definition is empty\");\n }\n\n QString hostname = QString(\"%1:%2\").arg(definition->host).arg(definition->port);\n\n m_tcpSocket = qobject_cast<QTcpSocket*>(networkManager->establishConnection(hostname, \"btc_mp\", definition->toVariant(), NetworkManager::TcpSocket));\n if (!m_tcpSocket)\n {\n LOG_ERROR(\"Preparation failed\");\n return false;\n }\n\n m_tcpSocket->setParent(this);\n m_bytesExpected = 0;\n m_preTest = true;\n\n \/\/ Signal for new data\n connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(receiveResponse()));\n\n \/\/ Signal for errors\n connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleError(QAbstractSocket::SocketError)));\n\n \/\/ Signal for end of data transmission\n connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));\n\n return true;\n}\n\nbool BulkTransportCapacityMA::stop()\n{\n if (m_tcpSocket)\n {\n m_tcpSocket->disconnectFromHost();\n if (m_tcpSocket->state() != QTcpSocket::UnconnectedState &&\n !m_tcpSocket->waitForDisconnected(1000))\n {\n return false;\n }\n }\n\n return true;\n}\n\nResultPtr BulkTransportCapacityMA::result() const\n{\n QVariantList res;\n foreach(qreal val, m_downloadSpeeds)\n {\n res<<QString::number(val, 'f');\n }\n\n return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant()));\n}\n<commit_msg>Fixed a bug in the BTC slices<commit_after>#include \"btc_ma.h\"\n#include \"..\/..\/log\/logger.h\"\n#include \"..\/..\/network\/networkmanager.h\"\n\n#include <QDataStream>\n#include <numeric>\n#include <QtCore\/QtMath>\n\nLOGGER(BulkTransportCapacityMA);\n\nBulkTransportCapacityMA::BulkTransportCapacityMA(QObject *parent)\n: Measurement(parent)\n, m_preTest(true)\n, m_tcpSocket(NULL)\n, m_lasttime(-1)\n, m_status(Unknown)\n{\n}\n\nbool BulkTransportCapacityMA::start()\n{\n m_status = BulkTransportCapacityMA::Running;\n sendInitialRequest();\n return true;\n}\n\nvoid BulkTransportCapacityMA::sendRequest(quint64 bytes)\n{\n \/\/ invalidate timer\n m_time.invalidate();\n\n m_bytesExpected = bytes;\n QDataStream out(m_tcpSocket);\n out<<bytes;\n}\n\nvoid BulkTransportCapacityMA::sendInitialRequest()\n{\n LOG_INFO(\"Sending initial data size to server\");\n sendRequest(definition->initialDataSize);\n}\n\nvoid BulkTransportCapacityMA::receiveResponse()\n{\n qint64 time = m_time.nsecsElapsed();\n\n \/\/ if the timer is not valid this is the first response packet\n if (!m_time.isValid())\n {\n \/\/ reset variables\n m_bytesReceived = 0;\n m_lasttime = 0;\n\n \/\/ this packet counts to the total bytes, but not to the measurement bytes in m_bytesReceived\n m_totalBytesReceived = m_tcpSocket->bytesAvailable();\n\n \/\/ ignor the first data received\n m_tcpSocket->readAll();\n\n m_time.restart();\n }\n else \/\/ this is a response within an active measurement\n {\n qint64 bytes = m_tcpSocket->bytesAvailable();\n m_bytesReceivedList<<bytes;\n m_times<<time - m_lasttime;\n m_bytesReceived += bytes;\n m_totalBytesReceived += bytes;\n m_tcpSocket->readAll(); \/\/ we don't care for the data-content\n m_lasttime = time;\n }\n\n \/\/ check if all measurement data was received\n if (m_totalBytesReceived >= m_bytesExpected)\n {\n \/\/ if this was the pretest we need to calculate the bytes for the real test\n if (m_preTest)\n {\n \/\/ get the download speed in kbyte\n qreal downloadSpeed = (m_bytesReceived \/ 1024.0) \/ (((m_lasttime \/ 1000.0) \/ 1000) \/ 1000);\n\n LOG_INFO(QString(\"Speed (pretest): %1 KByte\/s\").arg(downloadSpeed, 0, 'f', 0));\n\n \/\/ Calculate new test size\n m_bytesExpected = downloadSpeed * 1024 * 3; \/\/ should be <3 seconds if the calculated speed was correct\n\n m_preTest = false;\n\n LOG_INFO(\"Sending test data size to server\");\n\n \/\/ set next state\n sendRequest(m_bytesExpected);\n }\n else\n {\n \/\/ calculate download speed for n slices\n int slices = 10; \/\/ TODO 10 slices, as parameter?\n int slice_size = ceil((double)m_times.size() \/ slices); \/\/ round up to get the correct number of slices\n\n \/\/ counters\n qint64 bytes = 0;\n qint64 time = 0;\n\n \/\/ calculate slices\n for (int i=0; i<m_times.size(); i++)\n {\n bytes += m_bytesReceivedList.at(i);\n time += m_times.at(i);\n\n \/\/ calculate a slice if enough samples are added up or if this is the last iteration\n if (((i+1) % slice_size) == 0 || i == m_times.size() - 1) \/\/ calculate a slice\n {\n qreal speed = (bytes \/ 1024.0) \/ (((time \/ 1000.0) \/ 1000) \/ 1000);\n m_downloadSpeeds<<speed;\n\n \/\/ reset counters\n bytes = 0;\n time = 0;\n }\n }\n\n \/\/ calculate mean speed\n qreal sum = std::accumulate(m_downloadSpeeds.begin(), m_downloadSpeeds.end(), 0.0);\n qreal mean = sum \/ m_downloadSpeeds.size();\n LOG_INFO(QString(\"Speed (mean): %1 KByte\/s\").arg(mean, 0, 'f', 0));\n\n \/* At the moment deactivated\n \/\/ calculate standard deviation\n qreal sq_sum = std::inner_product(speeds.begin(), speeds.end(), speeds.begin(), 0.0);\n qreal stdev = qSqrt(sq_sum \/ speeds.size() - mean * mean);\n LOG_INFO(QString(\"Standard deviation: %1\").arg(stdev, 0, 'f', 0));\n *\/\n\n \/* At the moment deactivated to get all results\n \/\/ get ride of the lower and upper 20%\n qSort(speeds);\n int percentil = slices * 0.2;\n sum = std::accumulate(speeds.begin()+percentil, speeds.end()-percentil, 0.0);\n mean = sum \/ (speeds.size() - 2 * percentil);\n LOG_INFO(QString(\"Speed (60 percentil mean): %1 KByte\/s\").arg(mean, 0, 'f', 0));\n *\/\n\n m_status = BulkTransportCapacityMA::Finished;\n\n emit finished();\n }\n }\n}\n\nvoid BulkTransportCapacityMA::serverDisconnected()\n{\n if (m_status != BulkTransportCapacityMA::Finished)\n {\n LOG_WARNING(\"Server closed connection, this should not happen\");\n }\n}\n\nvoid BulkTransportCapacityMA::handleError(QAbstractSocket::SocketError socketError)\n{\n if (socketError == QAbstractSocket::RemoteHostClosedError)\n {\n return;\n }\n\n QAbstractSocket* socket = qobject_cast<QAbstractSocket*>(sender());\n LOG_ERROR(QString(\"Socket Error: %1\").arg(socket->errorString()));\n}\n\nMeasurement::Status BulkTransportCapacityMA::status() const\n{\n return m_status;\n}\n\nbool BulkTransportCapacityMA::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition)\n{\n definition = measurementDefinition.dynamicCast<BulkTransportCapacityDefinition>();\n if ( definition.isNull() )\n {\n LOG_WARNING(\"Definition is empty\");\n }\n\n QString hostname = QString(\"%1:%2\").arg(definition->host).arg(definition->port);\n\n m_tcpSocket = qobject_cast<QTcpSocket*>(networkManager->establishConnection(hostname, \"btc_mp\", definition->toVariant(), NetworkManager::TcpSocket));\n if (!m_tcpSocket)\n {\n LOG_ERROR(\"Preparation failed\");\n return false;\n }\n\n m_tcpSocket->setParent(this);\n m_bytesExpected = 0;\n m_preTest = true;\n\n \/\/ Signal for new data\n connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(receiveResponse()));\n\n \/\/ Signal for errors\n connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleError(QAbstractSocket::SocketError)));\n\n \/\/ Signal for end of data transmission\n connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));\n\n return true;\n}\n\nbool BulkTransportCapacityMA::stop()\n{\n if (m_tcpSocket)\n {\n m_tcpSocket->disconnectFromHost();\n if (m_tcpSocket->state() != QTcpSocket::UnconnectedState &&\n !m_tcpSocket->waitForDisconnected(1000))\n {\n return false;\n }\n }\n\n return true;\n}\n\nResultPtr BulkTransportCapacityMA::result() const\n{\n QVariantList res;\n foreach(qreal val, m_downloadSpeeds)\n {\n res<<QString::number(val, 'f');\n }\n\n return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant()));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <v8.h>\n#include <node.h>\n#include <string>\n#include <cstring>\n#include <stdlib.h>\n#include <dbus\/dbus.h>\n#include <nan.h>\n\n#include \"dbus.h\"\n#include \"decoder.h\"\n#include \"connection.h\"\n#include \"signal.h\"\n\nnamespace Connection {\n\n\tusing namespace node;\n\tusing namespace v8;\n\tusing namespace std;\n\n\tstatic void connection_loop_free(uv_handle_t* handle) {\n\t\tuv_async_t *connection_loop = reinterpret_cast<uv_async_t *>(handle);\n\t\tdelete connection_loop;\n\t}\n\n\tstatic void watcher_free(uv_handle_t* handle) {\n\t\tuv_poll_t *watcher = reinterpret_cast<uv_poll_t *>(handle);\n\t\tdelete watcher;\n\t}\n\n\tstatic void timer_free(uv_handle_t* handle) {\n\t\tuv_timer_t *timer = reinterpret_cast<uv_timer_t *>(handle);\n\t\tdelete timer;\n\t}\n\n\tstatic void watcher_handle(uv_poll_t *watcher, int status, int events)\n\t{\n\t\tDBusWatch *watch = static_cast<DBusWatch *>(watcher->data);\n\t\tunsigned int flags = 0;\n\n\t\tif (events & UV_READABLE)\n\t\t\tflags |= DBUS_WATCH_READABLE;\n\n\t\tif (events & UV_WRITABLE)\n\t\t\tflags |= DBUS_WATCH_WRITABLE;\n\n\t\tdbus_watch_handle(watch, flags);\n\t}\n\n\tstatic void watcher_close(void *data)\n\t{\n\t\tuv_poll_t *watcher = static_cast<uv_poll_t *>(data);\n\n\t\tif (watcher == NULL)\n\t\t\treturn;\n\n\t\twatcher->data = NULL;\n\n\t\t\/\/ Stop watching\n\t\tuv_ref((uv_handle_t *)watcher);\n\t\tuv_poll_stop(watcher);\n\t\tuv_close((uv_handle_t *)watcher, (uv_close_cb)watcher_free);\n\t}\n\n\tstatic dbus_bool_t watch_add(DBusWatch *watch, void *data)\n\t{\n\t\tif (!dbus_watch_get_enabled(watch) || dbus_watch_get_data(watch) != NULL)\n\t\t\treturn true;\n\n\t\tint events = 0;\n\t\tint fd = dbus_watch_get_unix_fd(watch);\n\t\tunsigned int flags = dbus_watch_get_flags(watch);\n\n\t\tif (flags & DBUS_WATCH_READABLE)\n\t\t\tevents |= UV_READABLE;\n\n\t\tif (flags & DBUS_WATCH_WRITABLE)\n\t\t\tevents |= UV_WRITABLE;\n\n\t\t\/\/ Initializing watcher\n\t\tuv_poll_t *watcher = new uv_poll_t;\n\t\twatcher->data = (void *)watch;\n\n\t\t\/\/ Start watching\n\t\tuv_poll_init(uv_default_loop(), watcher, fd);\n\t\tuv_poll_start(watcher, events, watcher_handle);\n\t\tuv_unref((uv_handle_t *)watcher);\n\n\t\tdbus_watch_set_data(watch, (void *)watcher, watcher_close);\n\n\t\treturn true;\n\t}\n\n\tstatic void watch_remove(DBusWatch *watch, void *data)\n\t{\n\t\tuv_poll_t *watcher = static_cast<uv_poll_t *>(dbus_watch_get_data(watch));\n\n\t\tif (watcher == NULL)\n\t\t\treturn;\n\n\t\tdbus_watch_set_data(watch, NULL, NULL);\n\t}\n\n\tstatic void watch_handle(DBusWatch *watch, void *data)\n\t{\n\t\tif (dbus_watch_get_enabled(watch))\n\t\t\twatch_add(watch, data);\n\t\telse\n\t\t\twatch_remove(watch, data);\n\t}\n\n#if UV_VERSION_MAJOR == 0\n\tstatic void timer_handle(uv_timer_t *timer, int status)\n#else\n\tstatic void timer_handle(uv_timer_t *timer)\n#endif\n\t{\n\t\tDBusTimeout *timeout = static_cast<DBusTimeout *>(timer->data);\n\t\tdbus_timeout_handle(timeout);\n\t}\n\n\tstatic void timer_close(void *data)\n\t{\n\t\tuv_timer_t *timer = static_cast<uv_timer_t *>(data);\n\n\t\tif (timer == NULL)\n\t\t\treturn;\n\n\t\ttimer->data = NULL;\n\n\t\t\/\/ Stop timer\n\t\tuv_timer_stop(timer);\n\t\tuv_unref((uv_handle_t *)timer);\n\t\tuv_close((uv_handle_t *)timer, (uv_close_cb)timer_free);\n\t}\n\n\tstatic dbus_bool_t timeout_add(DBusTimeout *timeout, void *data)\n\t{ \n\t\tif (!dbus_timeout_get_enabled(timeout) || dbus_timeout_get_data(timeout) != NULL)\n\t\t\treturn true;\n\n\t\tuv_timer_t *timer = new uv_timer_t;\n\t\ttimer->data = timeout;\n\n\t\t\/\/ Initializing timer\n\t\tuv_timer_init(uv_default_loop(), timer);\n\t\tuv_timer_start(timer, timer_handle, dbus_timeout_get_interval(timeout), 0);\n\n\t\tdbus_timeout_set_data(timeout, (void *)timer, timer_close);\n\n\t\treturn true;\n\t}\n\n\tstatic void timeout_remove(DBusTimeout *timeout, void *data)\n\t{\n\t\tdbus_timeout_set_data(timeout, NULL, NULL);\n\t}\n\n\tstatic void timeout_toggled(DBusTimeout *timeout, void *data)\n\t{\n\t\tif (dbus_timeout_get_enabled(timeout))\n\t\t\ttimeout_add(timeout, data);\n\t\telse\n\t\t\ttimeout_remove(timeout, data);\n\t}\n\n#if UV_VERSION_MAJOR == 0\n\tstatic void connection_loop_handle(uv_async_t *connection_loop, int status)\n#else\n\tstatic void connection_loop_handle(uv_async_t *connection_loop)\n#endif\n\t{\n\t\tDBusConnection *connection = static_cast<DBusConnection *>(connection_loop->data);\n\t\tdbus_connection_read_write(connection, 0);\n\n\t\twhile(dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS);\n\t}\n\n\tstatic void connection_loop_close(void *data) {\n\t\tuv_async_t *connection_loop = static_cast<uv_async_t *>(data);\n\n\t\tif (connection_loop == NULL)\n\t\t\treturn;\n\n\t\tconnection_loop->data = NULL;\n\n\t\tuv_close((uv_handle_t *)connection_loop, (uv_close_cb)connection_loop_free);\n\t}\n\n\tstatic void connection_wakeup(void *data)\n\t{\n\t\tuv_async_t *connection_loop = static_cast<uv_async_t *>(data);\n\t\tuv_async_send(connection_loop);\n\t}\n\n\tstatic DBusHandlerResult signal_filter(DBusConnection *connection, DBusMessage *message, void *user_data)\n\t{\n\t\t\/\/ Ignore message if it's not a valid signal\n\t\tif (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL) {\n\t\t\treturn DBUS_HANDLER_RESULT_NOT_YET_HANDLED;\n\t\t}\n\n\t\t\/\/ Getting the interface name and signal name\n\t\tconst char *sender = dbus_message_get_sender(message);\n\t\tconst char *object_path = dbus_message_get_path(message);\n\t\tconst char *interface = dbus_message_get_interface(message);\n\t\tconst char *signal_name = dbus_message_get_member(message);\n\t\tif (interface == NULL || signal_name == NULL) {\n\t\t\treturn DBUS_HANDLER_RESULT_NOT_YET_HANDLED;\n\t\t}\n\n\t\t\/\/ Getting V8 context\n\/*\n\t\tLocal<Context> context = Context::GetCurrent();\n\t\tContext::Scope ctxScope(context); \n\t\tHandleScope scope;\n*\/\n\t\tNanScope();\n\n\t\t\/\/ Getting arguments of signal\n\t\tHandle<Value> arguments = Decoder::DecodeArguments(message);\n\t\tLocal<Value> senderValue = NanNull();\n\t\tif (sender)\n\t\t\tsenderValue = NanNew<String>(sender);\n\n\t\tHandle<Value> args[] = {\n\t\t\tNanNew<String>(dbus_bus_get_unique_name(connection)),\n\t\t\tsenderValue,\n\t\t\tNanNew<String>(object_path),\n\t\t\tNanNew<String>(interface),\n\t\t\tNanNew<String>(signal_name),\n\t\t\targuments\n\t\t};\n\n\t\tSignal::DispatchSignal(args);\n\n\t\treturn DBUS_HANDLER_RESULT_HANDLED;\n\t}\n\n\tvoid Init(NodeDBus::BusObject *bus)\n\t{\n\t\tDBusConnection *connection = bus->connection;\n\n\t\tdbus_connection_set_exit_on_disconnect(connection, false);\n\n\t\t\/\/ Initializing watcher\n\t\tdbus_connection_set_watch_functions(connection, watch_add, watch_remove, watch_handle, NULL, NULL);\n\n\t\t\/\/ Initializing timeout handlers\n\t\tdbus_connection_set_timeout_functions(connection, timeout_add, timeout_remove, timeout_toggled, NULL, NULL);\n\n\t\t\/\/ Initializing loop\n\t\tuv_async_t *connection_loop = new uv_async_t;\n\t\tconnection_loop->data = (void *)connection;\n\t\tuv_async_init(uv_default_loop(), connection_loop, connection_loop_handle);\n\t\tbus->loop = connection_loop;\n\n\t\tdbus_connection_set_wakeup_main_function(connection, connection_wakeup, connection_loop, connection_loop_close);\n\n\t\t\/\/ Initializing signal handler\n\t\tdbus_connection_add_filter(connection, signal_filter, NULL, NULL);\n\t}\n\n\tvoid UnInit(NodeDBus::BusObject *bus)\n\t{\n\t\tDBusConnection *connection = bus->connection;\n\n\t\tuv_unref((uv_handle_t *)bus->loop);\n\n\t\tif (dbus_connection_get_is_connected(connection))\n\t\t\tdbus_connection_close(connection);\n\n\t\tdbus_connection_unref(connection);\n\t}\n\n}\n\n<commit_msg>connection.cc: don't add two watchers for one fd<commit_after>#include <stdlib.h>\n#include <v8.h>\n#include <node.h>\n#include <string>\n#include <cstring>\n#include <stdlib.h>\n#include <dbus\/dbus.h>\n#include <nan.h>\n\n#include \"dbus.h\"\n#include \"decoder.h\"\n#include \"connection.h\"\n#include \"signal.h\"\n\nnamespace Connection {\n\n\tusing namespace node;\n\tusing namespace v8;\n\tusing namespace std;\n\n\tstatic void connection_loop_free(uv_handle_t* handle) {\n\t\tuv_async_t *connection_loop = reinterpret_cast<uv_async_t *>(handle);\n\t\tdelete connection_loop;\n\t}\n\n\tstatic void watcher_free(uv_handle_t* handle) {\n\t\tuv_poll_t *watcher = reinterpret_cast<uv_poll_t *>(handle);\n\t\tdelete watcher;\n\t}\n\n\tstatic void timer_free(uv_handle_t* handle) {\n\t\tuv_timer_t *timer = reinterpret_cast<uv_timer_t *>(handle);\n\t\tdelete timer;\n\t}\n\n\tstatic void watcher_handle(uv_poll_t *watcher, int status, int events)\n\t{\n\t\tDBusWatch *watch = static_cast<DBusWatch *>(watcher->data);\n\t\tunsigned int flags = 0;\n\n\t\tif (events & UV_READABLE)\n\t\t\tflags |= DBUS_WATCH_READABLE;\n\n\t\tif (events & UV_WRITABLE)\n\t\t\tflags |= DBUS_WATCH_WRITABLE;\n\n\t\tdbus_watch_handle(watch, flags);\n\t}\n\n\tstatic void watcher_close(void *data)\n\t{\n\t\tuv_poll_t *watcher = static_cast<uv_poll_t *>(data);\n\n\t\tif (watcher == NULL)\n\t\t\treturn;\n\n\t\twatcher->data = NULL;\n\n\t\t\/\/ Stop watching\n\t\tuv_ref((uv_handle_t *)watcher);\n\t\tuv_poll_stop(watcher);\n\t\tuv_close((uv_handle_t *)watcher, (uv_close_cb)watcher_free);\n\t}\n\n\tstatic dbus_bool_t watch_add(DBusWatch *watch, void *data)\n\t{\n\t\tif (!dbus_watch_get_enabled(watch) || dbus_watch_get_data(watch) != NULL)\n\t\t\treturn true;\n\n\t\tint events = 0;\n\t\tint fd = dbus_watch_get_unix_fd(watch);\n\t\tunsigned int flags = dbus_watch_get_flags(watch);\n\n\t\tif (flags & DBUS_WATCH_READABLE)\n\t\t\tevents |= UV_READABLE;\n\n\t\tif (flags & DBUS_WATCH_WRITABLE)\n\t\t\tevents |= UV_WRITABLE;\n\n\t\t\/\/ Initializing watcher\n\t\tuv_poll_t *watcher = new uv_poll_t;\n\t\twatcher->data = (void *)watch;\n\n\t\t\/\/ Start watching\n\t\tuv_poll_init(uv_default_loop(), watcher, fd);\n\t\tuv_poll_start(watcher, events, watcher_handle);\n\t\tuv_unref((uv_handle_t *)watcher);\n\n\t\tdbus_watch_set_data(watch, (void *)watcher, watcher_close);\n\n\t\treturn true;\n\t}\n\n\tstatic void watch_remove(DBusWatch *watch, void *data)\n\t{\n\t\tuv_poll_t *watcher = static_cast<uv_poll_t *>(dbus_watch_get_data(watch));\n\n\t\tif (watcher == NULL)\n\t\t\treturn;\n\n\t\tdbus_watch_set_data(watch, NULL, NULL);\n\t}\n\n\tstatic void watch_handle(DBusWatch *watch, void *data)\n\t{\n\t\t\/\/ This watch was never added, so don't do anything!\n\t\t\/\/ If we would react in this case, it can happen that we add\n\t\t\/\/ two watches for one filehandler, this crashes libuv!\n\t\tif (dbus_watch_get_data(watch) == NULL) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (dbus_watch_get_enabled(watch))\n\t\t\twatch_add(watch, data);\n\t\telse\n\t\t\twatch_remove(watch, data);\n\t}\n\n#if UV_VERSION_MAJOR == 0\n\tstatic void timer_handle(uv_timer_t *timer, int status)\n#else\n\tstatic void timer_handle(uv_timer_t *timer)\n#endif\n\t{\n\t\tDBusTimeout *timeout = static_cast<DBusTimeout *>(timer->data);\n\t\tdbus_timeout_handle(timeout);\n\t}\n\n\tstatic void timer_close(void *data)\n\t{\n\t\tuv_timer_t *timer = static_cast<uv_timer_t *>(data);\n\n\t\tif (timer == NULL)\n\t\t\treturn;\n\n\t\ttimer->data = NULL;\n\n\t\t\/\/ Stop timer\n\t\tuv_timer_stop(timer);\n\t\tuv_unref((uv_handle_t *)timer);\n\t\tuv_close((uv_handle_t *)timer, (uv_close_cb)timer_free);\n\t}\n\n\tstatic dbus_bool_t timeout_add(DBusTimeout *timeout, void *data)\n\t{\n\t\tif (!dbus_timeout_get_enabled(timeout) || dbus_timeout_get_data(timeout) != NULL)\n\t\t\treturn true;\n\n\t\tuv_timer_t *timer = new uv_timer_t;\n\t\ttimer->data = timeout;\n\n\t\t\/\/ Initializing timer\n\t\tuv_timer_init(uv_default_loop(), timer);\n\t\tuv_timer_start(timer, timer_handle, dbus_timeout_get_interval(timeout), 0);\n\n\t\tdbus_timeout_set_data(timeout, (void *)timer, timer_close);\n\n\t\treturn true;\n\t}\n\n\tstatic void timeout_remove(DBusTimeout *timeout, void *data)\n\t{\n\t\tdbus_timeout_set_data(timeout, NULL, NULL);\n\t}\n\n\tstatic void timeout_toggled(DBusTimeout *timeout, void *data)\n\t{\n\t\tif (dbus_timeout_get_enabled(timeout))\n\t\t\ttimeout_add(timeout, data);\n\t\telse\n\t\t\ttimeout_remove(timeout, data);\n\t}\n\n#if UV_VERSION_MAJOR == 0\n\tstatic void connection_loop_handle(uv_async_t *connection_loop, int status)\n#else\n\tstatic void connection_loop_handle(uv_async_t *connection_loop)\n#endif\n\t{\n\t\tDBusConnection *connection = static_cast<DBusConnection *>(connection_loop->data);\n\t\tdbus_connection_read_write(connection, 0);\n\n\t\twhile(dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS);\n\t}\n\n\tstatic void connection_loop_close(void *data) {\n\t\tuv_async_t *connection_loop = static_cast<uv_async_t *>(data);\n\n\t\tif (connection_loop == NULL)\n\t\t\treturn;\n\n\t\tconnection_loop->data = NULL;\n\n\t\tuv_close((uv_handle_t *)connection_loop, (uv_close_cb)connection_loop_free);\n\t}\n\n\tstatic void connection_wakeup(void *data)\n\t{\n\t\tuv_async_t *connection_loop = static_cast<uv_async_t *>(data);\n\t\tuv_async_send(connection_loop);\n\t}\n\n\tstatic DBusHandlerResult signal_filter(DBusConnection *connection, DBusMessage *message, void *user_data)\n\t{\n\t\t\/\/ Ignore message if it's not a valid signal\n\t\tif (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL) {\n\t\t\treturn DBUS_HANDLER_RESULT_NOT_YET_HANDLED;\n\t\t}\n\n\t\t\/\/ Getting the interface name and signal name\n\t\tconst char *sender = dbus_message_get_sender(message);\n\t\tconst char *object_path = dbus_message_get_path(message);\n\t\tconst char *interface = dbus_message_get_interface(message);\n\t\tconst char *signal_name = dbus_message_get_member(message);\n\t\tif (interface == NULL || signal_name == NULL) {\n\t\t\treturn DBUS_HANDLER_RESULT_NOT_YET_HANDLED;\n\t\t}\n\n\t\t\/\/ Getting V8 context\n\/*\n\t\tLocal<Context> context = Context::GetCurrent();\n\t\tContext::Scope ctxScope(context);\n\t\tHandleScope scope;\n*\/\n\t\tNanScope();\n\n\t\t\/\/ Getting arguments of signal\n\t\tHandle<Value> arguments = Decoder::DecodeArguments(message);\n\t\tLocal<Value> senderValue = NanNull();\n\t\tif (sender)\n\t\t\tsenderValue = NanNew<String>(sender);\n\n\t\tHandle<Value> args[] = {\n\t\t\tNanNew<String>(dbus_bus_get_unique_name(connection)),\n\t\t\tsenderValue,\n\t\t\tNanNew<String>(object_path),\n\t\t\tNanNew<String>(interface),\n\t\t\tNanNew<String>(signal_name),\n\t\t\targuments\n\t\t};\n\n\t\tSignal::DispatchSignal(args);\n\n\t\treturn DBUS_HANDLER_RESULT_HANDLED;\n\t}\n\n\tvoid Init(NodeDBus::BusObject *bus)\n\t{\n\t\tDBusConnection *connection = bus->connection;\n\n\t\tdbus_connection_set_exit_on_disconnect(connection, false);\n\n\t\t\/\/ Initializing watcher\n\t\tdbus_connection_set_watch_functions(connection, watch_add, watch_remove, watch_handle, NULL, NULL);\n\n\t\t\/\/ Initializing timeout handlers\n\t\tdbus_connection_set_timeout_functions(connection, timeout_add, timeout_remove, timeout_toggled, NULL, NULL);\n\n\t\t\/\/ Initializing loop\n\t\tuv_async_t *connection_loop = new uv_async_t;\n\t\tconnection_loop->data = (void *)connection;\n\t\tuv_async_init(uv_default_loop(), connection_loop, connection_loop_handle);\n\t\tbus->loop = connection_loop;\n\n\t\tdbus_connection_set_wakeup_main_function(connection, connection_wakeup, connection_loop, connection_loop_close);\n\n\t\t\/\/ Initializing signal handler\n\t\tdbus_connection_add_filter(connection, signal_filter, NULL, NULL);\n\t}\n\n\tvoid UnInit(NodeDBus::BusObject *bus)\n\t{\n\t\tDBusConnection *connection = bus->connection;\n\n\t\tuv_unref((uv_handle_t *)bus->loop);\n\n\t\tif (dbus_connection_get_is_connected(connection))\n\t\t\tdbus_connection_close(connection);\n\n\t\tdbus_connection_unref(connection);\n\t}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef BEEEON_AUTH_SERVICE_TEST_H\n#define BEEEON_AUTH_SERVICE_TEST_H\n\n#include <Poco\/Exception.h>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"provider\/MockRandomProvider.h\"\n#include \"provider\/RandomProvider.h\"\n#include \"service\/AuthService.h\"\n#include \"provider\/PermitAuthProvider.h\"\n#include \"dao\/UserDao.h\"\n#include \"dao\/IdentityDao.h\"\n#include \"dao\/VerifiedIdentityDao.h\"\n#include \"util\/Base64.h\"\n\nusing namespace std;\nusing namespace Poco;\n\nnamespace BeeeOn {\n\nclass AuthServiceTest : public CppUnit::TestFixture {\n\tCPPUNIT_TEST_SUITE(AuthServiceTest);\n\tCPPUNIT_TEST(testPermitAuth);\n\tCPPUNIT_TEST_SUITE_END();\n\npublic:\n\tvoid setUp();\n\tvoid tearDown();\n\tvoid testPermitAuth();\n\nprivate:\n\tMockUserDao m_userDao;\n\tMockIdentityDao m_identityDao;\n\tMockVerifiedIdentityDao m_verifiedIdentityDao;\n\tSessionManager m_manager;\n\tMockRandomProvider m_mockRandomProvider;\n\tInsecureRandomProvider m_insecureRandomProvider;\n\tAuthService *m_service;\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(AuthServiceTest);\n\n#define SESSION_ID64 string( \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\")\n\nvoid AuthServiceTest::setUp()\n{\n\tm_userDao.storage().clear();\n\tm_identityDao.storage().clear();\n\tm_verifiedIdentityDao.storage().clear();\n\n\tm_mockRandomProvider.setNextRandom(SESSION_ID64);\n\tm_insecureRandomProvider.setProviderImpl(&m_mockRandomProvider);\n\tm_manager.setSecureRandomProvider(&m_insecureRandomProvider);\n\tm_manager.setMaxUserSessions(10);\n\tm_manager.setSessionExpireTime(1);\n\n\tm_service = new AuthService();\n\tm_service->setUserDao(&m_userDao);\n\tm_service->setIdentityDao(&m_identityDao);\n\tm_service->setVerifiedIdentityDao(&m_verifiedIdentityDao);\n\tm_service->setSessionManager(&m_manager);\n}\n\nvoid AuthServiceTest::tearDown()\n{\n\tdelete m_service;\n}\n\nvoid AuthServiceTest::testPermitAuth()\n{\n\tUserID newID(UUIDGenerator::defaultGenerator().createRandom());\n\tUser::Ptr user(new User(newID));\n\tm_userDao.storage().insert(make_pair(user->id(), user));\n\n\tIdentity identity;\n\tidentity.setEmail(\"permit@example.org\");\n\tidentity.setUser(*user);\n\tm_identityDao.create(identity);\n\n\tVerifiedIdentity verifiedIdentity;\n\tverifiedIdentity.setIdentity(identity);\n\tverifiedIdentity.setProvider(\"3rd-party\");\n\tm_verifiedIdentityDao.create(verifiedIdentity);\n\n\tPermitAuthProvider provider;\n\tprovider.setResultProvider(\"3rd-party\");\n\n\tm_service->registerProvider(&provider);\n\n\tAuthCodeCredentials cred(\"permit\", \"permit@example.org\");\n\n\ttry {\n\t\tconst ExpirableSession::Ptr session = m_service->login(cred);\n\t\tconst SessionID id = session->sessionID();\n\t\tCPPUNIT_ASSERT(Base64::decode(id).compare(SESSION_ID64) == 0);\n\t\tm_service->logout(id);\n\t} catch(Exception &e) {\n\t\tCPPUNIT_FAIL(\"unexpected exception: \" + e.displayText());\n\t}\n}\n\n}\n\n#endif\n<commit_msg>AuthServiceTest: introduce TestableAuthService<commit_after>#ifndef BEEEON_AUTH_SERVICE_TEST_H\n#define BEEEON_AUTH_SERVICE_TEST_H\n\n#include <Poco\/Exception.h>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"provider\/MockRandomProvider.h\"\n#include \"provider\/RandomProvider.h\"\n#include \"service\/AuthService.h\"\n#include \"provider\/PermitAuthProvider.h\"\n#include \"dao\/UserDao.h\"\n#include \"dao\/IdentityDao.h\"\n#include \"dao\/VerifiedIdentityDao.h\"\n#include \"util\/Base64.h\"\n\nusing namespace std;\nusing namespace Poco;\n\nnamespace BeeeOn {\n\nclass TestableAuthService;\n\nclass AuthServiceTest : public CppUnit::TestFixture {\n\tCPPUNIT_TEST_SUITE(AuthServiceTest);\n\tCPPUNIT_TEST(testPermitAuth);\n\tCPPUNIT_TEST_SUITE_END();\n\npublic:\n\tvoid setUp();\n\tvoid tearDown();\n\tvoid testPermitAuth();\n\nprivate:\n\tMockUserDao m_userDao;\n\tMockIdentityDao m_identityDao;\n\tMockVerifiedIdentityDao m_verifiedIdentityDao;\n\tSessionManager m_manager;\n\tMockRandomProvider m_mockRandomProvider;\n\tInsecureRandomProvider m_insecureRandomProvider;\n\tTestableAuthService *m_service;\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(AuthServiceTest);\n\nclass TestableAuthService : public AuthService {\npublic:\n};\n\n#define SESSION_ID64 string( \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\" \\\n\t\"abcdef0123456789\")\n\nvoid AuthServiceTest::setUp()\n{\n\tm_userDao.storage().clear();\n\tm_identityDao.storage().clear();\n\tm_verifiedIdentityDao.storage().clear();\n\n\tm_mockRandomProvider.setNextRandom(SESSION_ID64);\n\tm_insecureRandomProvider.setProviderImpl(&m_mockRandomProvider);\n\tm_manager.setSecureRandomProvider(&m_insecureRandomProvider);\n\tm_manager.setMaxUserSessions(10);\n\tm_manager.setSessionExpireTime(1);\n\n\tm_service = new TestableAuthService();\n\tm_service->setUserDao(&m_userDao);\n\tm_service->setIdentityDao(&m_identityDao);\n\tm_service->setVerifiedIdentityDao(&m_verifiedIdentityDao);\n\tm_service->setSessionManager(&m_manager);\n}\n\nvoid AuthServiceTest::tearDown()\n{\n\tdelete m_service;\n}\n\nvoid AuthServiceTest::testPermitAuth()\n{\n\tUserID newID(UUIDGenerator::defaultGenerator().createRandom());\n\tUser::Ptr user(new User(newID));\n\tm_userDao.storage().insert(make_pair(user->id(), user));\n\n\tIdentity identity;\n\tidentity.setEmail(\"permit@example.org\");\n\tidentity.setUser(*user);\n\tm_identityDao.create(identity);\n\n\tVerifiedIdentity verifiedIdentity;\n\tverifiedIdentity.setIdentity(identity);\n\tverifiedIdentity.setProvider(\"3rd-party\");\n\tm_verifiedIdentityDao.create(verifiedIdentity);\n\n\tPermitAuthProvider provider;\n\tprovider.setResultProvider(\"3rd-party\");\n\n\tm_service->registerProvider(&provider);\n\n\tAuthCodeCredentials cred(\"permit\", \"permit@example.org\");\n\n\ttry {\n\t\tconst ExpirableSession::Ptr session = m_service->login(cred);\n\t\tconst SessionID id = session->sessionID();\n\t\tCPPUNIT_ASSERT(Base64::decode(id).compare(SESSION_ID64) == 0);\n\t\tm_service->logout(id);\n\t} catch(Exception &e) {\n\t\tCPPUNIT_FAIL(\"unexpected exception: \" + e.displayText());\n\t}\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\r\n#include <gloperate-text\/FontImporter.h>\r\n\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <functional>\r\n#include <set>\r\n#include <algorithm>\r\n\r\n#include <loggingzeug\/logging.h>\r\n\r\n#include <stringzeug\/conversion.h>\r\n\r\n#include <iozeug\/FilePath.h>\r\n\r\n#include <gloperate\/resources\/ResourceManager.h>\r\n\r\n#include <gloperate-text\/FontFace.h>\r\n\r\n\r\nnamespace\r\n{\r\n\r\nvoid extractKeyValuePairs(std::stringstream & stream, std::function<void(const std::string &, const std::string)> callback)\r\n{\r\n std::string key;\r\n std::string value;\r\n\r\n while (stream)\r\n {\r\n if (std::getline(stream, key, '='))\r\n {\r\n if (std::getline(stream, value, ' '))\r\n {\r\n callback(key, value);\r\n }\r\n }\r\n }\r\n}\r\n\r\nstd::string stripped(const std::string & string, const std::set<char> & blacklist)\r\n{\r\n std::string result = string;\r\n\r\n result.erase(std::remove_if(result.begin(), result.end(), [&blacklist] (char x) { return blacklist.count(x) > 0; } ), result.end());\r\n\r\n return result;\r\n}\r\n\r\n} \/\/ namespace\r\n\r\n\r\nnamespace gloperate_text\r\n{\r\n\r\n\r\nFontImporter::FontImporter(gloperate::ResourceManager & resourceManager)\r\n: m_resourceManager(resourceManager)\r\n{\r\n}\r\n\r\nFontFace * FontImporter::loadFont(const std::string & filename)\r\n{\r\n std::ifstream in(filename, std::ios::in | std::ios::binary);\r\n\r\n if (!in)\r\n {\r\n return nullptr;\r\n }\r\n\r\n FontFace * font = new FontFace();\r\n\r\n std::string line;\r\n std::string identifier;\r\n while (std::getline(in, line))\r\n {\r\n auto ss = std::stringstream();\r\n ss << line;\r\n\r\n if (std::getline(ss, identifier, ' '))\r\n {\r\n if (identifier == \"info\")\r\n {\r\n handleInfo(ss, font);\r\n }\r\n else if (identifier == \"common\")\r\n {\r\n handleCommon(ss, font);\r\n }\r\n else if (identifier == \"page\")\r\n {\r\n handlePage(ss, font, filename);\r\n }\r\n else if (identifier == \"chars\")\r\n {\r\n handleChars(ss, font);\r\n }\r\n else if (identifier == \"char\")\r\n {\r\n handleChar(ss, font);\r\n }\r\n else if (identifier == \"kernings\")\r\n {\r\n handleKernings(ss, font);\r\n }\r\n else if (identifier == \"kerning\")\r\n {\r\n handleKerning(ss, font);\r\n }\r\n else\r\n {\r\n assert(false);\r\n }\r\n }\r\n else\r\n {\r\n assert(false);\r\n }\r\n }\r\n\r\n if (!font->glyphTexture())\r\n {\r\n delete font;\r\n\r\n return nullptr;\r\n }\r\n\r\n return font;\r\n}\r\n\r\nvoid FontImporter::handleInfo(std::stringstream & stream, FontFace * font)\r\n{\r\n extractKeyValuePairs(stream, [font](const std::string & key, const std::string & value) {\r\n font->setConfiguration(key, value);\r\n });\r\n}\r\n\r\nvoid FontImporter::handleCommon(std::stringstream & stream, FontFace * font)\r\n{\r\n extractKeyValuePairs(stream, [font](const std::string & key, const std::string & value) {\r\n font->setConfiguration(key, value);\r\n });\r\n}\r\n\r\nvoid FontImporter::handlePage(std::stringstream & stream, FontFace * font, const std::string & filename)\r\n{\r\n const std::string path = iozeug::FilePath(filename).directoryPath();\r\n extractKeyValuePairs(stream, [this, font, &path](const std::string & key, const std::string & value) {\r\n if (key == \"file\")\r\n {\r\n std::string filename = stripped(value, { '\"', '\\r' });\r\n\r\n font->setGlyphTexture(m_resourceManager.load<globjects::Texture>(path + \"\/\" + filename));\r\n }\r\n else if (key == \"id\")\r\n {\r\n \/\/ nothing for now\r\n }\r\n });\r\n}\r\n\r\nvoid FontImporter::handleChars(std::stringstream & stream, FontFace * font)\r\n{\r\n \/\/ nothing\r\n}\r\n\r\nvoid FontImporter::handleChar(std::stringstream & stream, FontFace * font)\r\n{\r\n Glyph glyph;\r\n\r\n extractKeyValuePairs(stream, [&glyph](const std::string & key, const std::string & value) {\r\n std::uint32_t number = stringzeug::fromString<std::uint32_t>(value);\r\n\r\n if (key == \"id\")\r\n {\r\n glyph.setIndex(number);\r\n }\r\n else if (key == \"x\")\r\n {\r\n glyph.setX(number);\r\n }\r\n else if (key == \"y\")\r\n {\r\n glyph.setY(number);\r\n }\r\n else if (key == \"width\")\r\n {\r\n glyph.setWidth(number);\r\n }\r\n else if (key == \"height\")\r\n {\r\n glyph.setHeight(number);\r\n }\r\n else if (key == \"xoffset\")\r\n {\r\n glyph.setXOffset(number);\r\n }\r\n else if (key == \"yoffset\")\r\n {\r\n glyph.setYOffset(number);\r\n }\r\n else if (key == \"xadvance\")\r\n {\r\n glyph.setXAdvance(number);\r\n }\r\n else if (key == \"page\")\r\n {\r\n glyph.setPage(number);\r\n }\r\n else if (key == \"chnl\")\r\n {\r\n glyph.setChannel(number);\r\n }\r\n });\r\n\r\n if (glyph.index() > 0)\r\n {\r\n font->addGlyph(glyph);\r\n }\r\n}\r\n\r\nvoid FontImporter::handleKernings(std::stringstream & stream, FontFace * font)\r\n{\r\n \/\/ nothing\r\n}\r\n\r\nvoid FontImporter::handleKerning(std::stringstream & stream, FontFace * font)\r\n{\r\n std::uint32_t first = 0;\r\n std::uint32_t second = 0;\r\n int amount = 0;\r\n\r\n extractKeyValuePairs(stream, [this, font, &first, &second, &amount](const std::string & key, const std::string & value) {\r\n if (key == \"first\")\r\n {\r\n first = stringzeug::fromString<std::uint32_t>(value);\r\n }\r\n else if (key == \"second\")\r\n {\r\n second = stringzeug::fromString<std::uint32_t>(value);\r\n }\r\n else if (key == \"amount\")\r\n {\r\n \/\/ nothing for now\r\n amount = stringzeug::fromString<int>(value);\r\n }\r\n });\r\n}\r\n\r\n\r\n} \/\/ namespace gloperate_text\r\n<commit_msg>Fix compilation for GCC 4.8<commit_after>\r\n#include <gloperate-text\/FontImporter.h>\r\n\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <functional>\r\n#include <set>\r\n#include <algorithm>\r\n\r\n#include <loggingzeug\/logging.h>\r\n\r\n#include <stringzeug\/conversion.h>\r\n\r\n#include <iozeug\/FilePath.h>\r\n\r\n#include <gloperate\/resources\/ResourceManager.h>\r\n\r\n#include <gloperate-text\/FontFace.h>\r\n\r\n\r\nnamespace\r\n{\r\n\r\nvoid extractKeyValuePairs(std::stringstream & stream, std::function<void(const std::string &, const std::string)> callback)\r\n{\r\n std::string key;\r\n std::string value;\r\n\r\n while (stream)\r\n {\r\n if (std::getline(stream, key, '='))\r\n {\r\n if (std::getline(stream, value, ' '))\r\n {\r\n callback(key, value);\r\n }\r\n }\r\n }\r\n}\r\n\r\nstd::string stripped(const std::string & string, const std::set<char> & blacklist)\r\n{\r\n std::string result = string;\r\n\r\n result.erase(std::remove_if(result.begin(), result.end(), [&blacklist] (char x) { return blacklist.count(x) > 0; } ), result.end());\r\n\r\n return result;\r\n}\r\n\r\n} \/\/ namespace\r\n\r\n\r\nnamespace gloperate_text\r\n{\r\n\r\n\r\nFontImporter::FontImporter(gloperate::ResourceManager & resourceManager)\r\n: m_resourceManager(resourceManager)\r\n{\r\n}\r\n\r\nFontFace * FontImporter::loadFont(const std::string & filename)\r\n{\r\n std::ifstream in(filename, std::ios::in | std::ios::binary);\r\n\r\n if (!in)\r\n {\r\n return nullptr;\r\n }\r\n\r\n FontFace * font = new FontFace();\r\n\r\n std::string line;\r\n std::string identifier;\r\n while (std::getline(in, line))\r\n {\r\n std::stringstream ss(line);\r\n\r\n if (std::getline(ss, identifier, ' '))\r\n {\r\n if (identifier == \"info\")\r\n {\r\n handleInfo(ss, font);\r\n }\r\n else if (identifier == \"common\")\r\n {\r\n handleCommon(ss, font);\r\n }\r\n else if (identifier == \"page\")\r\n {\r\n handlePage(ss, font, filename);\r\n }\r\n else if (identifier == \"chars\")\r\n {\r\n handleChars(ss, font);\r\n }\r\n else if (identifier == \"char\")\r\n {\r\n handleChar(ss, font);\r\n }\r\n else if (identifier == \"kernings\")\r\n {\r\n handleKernings(ss, font);\r\n }\r\n else if (identifier == \"kerning\")\r\n {\r\n handleKerning(ss, font);\r\n }\r\n else\r\n {\r\n assert(false);\r\n }\r\n }\r\n else\r\n {\r\n assert(false);\r\n }\r\n }\r\n\r\n if (!font->glyphTexture())\r\n {\r\n delete font;\r\n\r\n return nullptr;\r\n }\r\n\r\n return font;\r\n}\r\n\r\nvoid FontImporter::handleInfo(std::stringstream & stream, FontFace * font)\r\n{\r\n extractKeyValuePairs(stream, [font](const std::string & key, const std::string & value) {\r\n font->setConfiguration(key, value);\r\n });\r\n}\r\n\r\nvoid FontImporter::handleCommon(std::stringstream & stream, FontFace * font)\r\n{\r\n extractKeyValuePairs(stream, [font](const std::string & key, const std::string & value) {\r\n font->setConfiguration(key, value);\r\n });\r\n}\r\n\r\nvoid FontImporter::handlePage(std::stringstream & stream, FontFace * font, const std::string & filename)\r\n{\r\n const std::string path = iozeug::FilePath(filename).directoryPath();\r\n extractKeyValuePairs(stream, [this, font, &path](const std::string & key, const std::string & value) {\r\n if (key == \"file\")\r\n {\r\n std::string filename = stripped(value, { '\"', '\\r' });\r\n\r\n font->setGlyphTexture(m_resourceManager.load<globjects::Texture>(path + \"\/\" + filename));\r\n }\r\n else if (key == \"id\")\r\n {\r\n \/\/ nothing for now\r\n }\r\n });\r\n}\r\n\r\nvoid FontImporter::handleChars(std::stringstream & stream, FontFace * font)\r\n{\r\n \/\/ nothing\r\n}\r\n\r\nvoid FontImporter::handleChar(std::stringstream & stream, FontFace * font)\r\n{\r\n Glyph glyph;\r\n\r\n extractKeyValuePairs(stream, [&glyph](const std::string & key, const std::string & value) {\r\n std::uint32_t number = stringzeug::fromString<std::uint32_t>(value);\r\n\r\n if (key == \"id\")\r\n {\r\n glyph.setIndex(number);\r\n }\r\n else if (key == \"x\")\r\n {\r\n glyph.setX(number);\r\n }\r\n else if (key == \"y\")\r\n {\r\n glyph.setY(number);\r\n }\r\n else if (key == \"width\")\r\n {\r\n glyph.setWidth(number);\r\n }\r\n else if (key == \"height\")\r\n {\r\n glyph.setHeight(number);\r\n }\r\n else if (key == \"xoffset\")\r\n {\r\n glyph.setXOffset(number);\r\n }\r\n else if (key == \"yoffset\")\r\n {\r\n glyph.setYOffset(number);\r\n }\r\n else if (key == \"xadvance\")\r\n {\r\n glyph.setXAdvance(number);\r\n }\r\n else if (key == \"page\")\r\n {\r\n glyph.setPage(number);\r\n }\r\n else if (key == \"chnl\")\r\n {\r\n glyph.setChannel(number);\r\n }\r\n });\r\n\r\n if (glyph.index() > 0)\r\n {\r\n font->addGlyph(glyph);\r\n }\r\n}\r\n\r\nvoid FontImporter::handleKernings(std::stringstream & stream, FontFace * font)\r\n{\r\n \/\/ nothing\r\n}\r\n\r\nvoid FontImporter::handleKerning(std::stringstream & stream, FontFace * font)\r\n{\r\n std::uint32_t first = 0;\r\n std::uint32_t second = 0;\r\n int amount = 0;\r\n\r\n extractKeyValuePairs(stream, [this, font, &first, &second, &amount](const std::string & key, const std::string & value) {\r\n if (key == \"first\")\r\n {\r\n first = stringzeug::fromString<std::uint32_t>(value);\r\n }\r\n else if (key == \"second\")\r\n {\r\n second = stringzeug::fromString<std::uint32_t>(value);\r\n }\r\n else if (key == \"amount\")\r\n {\r\n \/\/ nothing for now\r\n amount = stringzeug::fromString<int>(value);\r\n }\r\n });\r\n}\r\n\r\n\r\n} \/\/ namespace gloperate_text\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: HINFile_test.C,v 1.2 2000\/07\/12 19:36:46 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/system.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(HINFile, \"$Id: HINFile_test.C,v 1.2 2000\/07\/12 19:36:46 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nCHECK(HINFile::HINFile())\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::~HINFile())\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::write(const System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::read(System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::HINFile& operator >> (System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::HINFile& operator << (const System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::hasPeriodicBoundary() const )\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::getPeriodicBoundary() const )\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::getTemperature() const )\n \/\/BAUSTELLE\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added some trivial tests<commit_after>\/\/ $Id: HINFile_test.C,v 1.3 2001\/03\/11 21:03:07 anker Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/system.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(HINFile, \"$Id: HINFile_test.C,v 1.3 2001\/03\/11 21:03:07 anker Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nHINFile* ptr;\n\nCHECK(HINFile::HINFile())\n\tptr = new HINFile;\n\tCHECK_NOT_EQUAL(ptr, 0)\nRESULT\n\n\nCHECK(HINFile::~HINFile())\n delete ptr;\nRESULT\n\n\nCHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::write(const System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::read(System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::HINFile& operator >> (System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::HINFile& operator << (const System& system))\n \/\/BAUSTELLE\nRESULT\n\n\nCHECK(HINFile::hasPeriodicBoundary() const )\n HINFile box(\"data\/water.hin\");\n\tTEST_EQUAL(box.hasPeriodicBoundary(), true)\nRESULT\n\n\nCHECK(HINFile::getPeriodicBoundary() const )\n HINFile box(\"data\/water.hin\");\nRESULT\n\n\nCHECK(HINFile::getTemperature() const )\n \/\/BAUSTELLE\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2021, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * The file implements the DNS-SD Discovery Proxy.\n *\/\n\n#if OTBR_ENABLE_DNSSD_DISCOVERY_PROXY\n\n#define OTBR_LOG_TAG \"DPROXY\"\n\n#include \"agent\/discovery_proxy.hpp\"\n\n#include <algorithm>\n#include <string>\n\n#include <assert.h>\n\n#include <openthread\/dnssd_server.h>\n\n#include \"common\/code_utils.hpp\"\n#include \"common\/dns_utils.hpp\"\n#include \"common\/logging.hpp\"\n\nnamespace otbr {\nnamespace Dnssd {\n\nDiscoveryProxy::DiscoveryProxy(Ncp::ControllerOpenThread &aNcp, Mdns::Publisher &aPublisher)\n : mNcp(aNcp)\n , mMdnsPublisher(aPublisher)\n{\n}\n\nvoid DiscoveryProxy::Start(void)\n{\n otDnssdQuerySetCallbacks(mNcp.GetInstance(), &DiscoveryProxy::OnDiscoveryProxySubscribe,\n &DiscoveryProxy::OnDiscoveryProxyUnsubscribe, this);\n\n mMdnsPublisher.SetSubscriptionCallbacks(\n [this](const std::string &aType, const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo) {\n OnServiceDiscovered(aType, aInstanceInfo);\n },\n\n [this](const std::string &aHostName, const Mdns::Publisher::DiscoveredHostInfo &aHostInfo) {\n OnHostDiscovered(aHostName, aHostInfo);\n });\n\n otbrLogInfo(\"started\");\n}\n\nvoid DiscoveryProxy::Stop(void)\n{\n otDnssdQuerySetCallbacks(mNcp.GetInstance(), nullptr, nullptr, nullptr);\n mMdnsPublisher.SetSubscriptionCallbacks(nullptr, nullptr);\n\n otbrLogInfo(\"stopped\");\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxySubscribe(void *aContext, const char *aFullName)\n{\n reinterpret_cast<DiscoveryProxy *>(aContext)->OnDiscoveryProxySubscribe(aFullName);\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxySubscribe(const char *aFullName)\n{\n std::string fullName(aFullName);\n otbrError error = OTBR_ERROR_NONE;\n MdnsSubscriptionList::iterator it;\n DnsNameInfo nameInfo = SplitFullDnsName(fullName);\n\n otbrLogInfo(\"subscribe: %s\", fullName.c_str());\n\n it = std::find_if(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n return aSubscription.Matches(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName,\n nameInfo.mDomain);\n });\n\n VerifyOrExit(it == mSubscriptions.end(), it->mSubscriptionCount++);\n\n mSubscriptions.emplace_back(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName, nameInfo.mDomain);\n\n {\n MdnsSubscription &subscription = mSubscriptions.back();\n\n otbrLogDebug(\"subscriptions: %sx%d\", subscription.ToString().c_str(), subscription.mSubscriptionCount);\n\n if (GetServiceSubscriptionCount(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName) == 1)\n {\n if (subscription.mHostName.empty())\n {\n mMdnsPublisher.SubscribeService(nameInfo.mServiceName, nameInfo.mInstanceName);\n }\n else\n {\n mMdnsPublisher.SubscribeHost(nameInfo.mHostName);\n }\n }\n }\n\nexit:\n if (error != OTBR_ERROR_NONE)\n {\n otbrLogWarning(\"failed to subscribe %s: %s\", fullName.c_str(), otbrErrorString(error));\n }\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxyUnsubscribe(void *aContext, const char *aFullName)\n{\n reinterpret_cast<DiscoveryProxy *>(aContext)->OnDiscoveryProxyUnsubscribe(aFullName);\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxyUnsubscribe(const char *aFullName)\n{\n std::string fullName(aFullName);\n otbrError error = OTBR_ERROR_NONE;\n MdnsSubscriptionList::iterator it;\n DnsNameInfo nameInfo = SplitFullDnsName(fullName);\n\n otbrLogInfo(\"unsubscribe: %s\", fullName.c_str());\n\n it = std::find_if(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n return aSubscription.Matches(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName,\n nameInfo.mDomain);\n });\n\n VerifyOrExit(it != mSubscriptions.end(), error = OTBR_ERROR_NOT_FOUND);\n\n {\n MdnsSubscription &subscription = *it;\n\n subscription.mSubscriptionCount--;\n assert(subscription.mSubscriptionCount >= 0);\n\n if (subscription.mSubscriptionCount == 0)\n {\n mSubscriptions.erase(it);\n }\n\n otbrLogDebug(\"service subscriptions: %sx%d\", it->ToString().c_str(), it->mSubscriptionCount);\n\n if (GetServiceSubscriptionCount(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName) == 0)\n {\n if (subscription.mHostName.empty())\n {\n mMdnsPublisher.UnsubscribeService(nameInfo.mServiceName, nameInfo.mInstanceName);\n }\n else\n {\n mMdnsPublisher.UnsubscribeHost(nameInfo.mHostName);\n }\n }\n }\nexit:\n if (error != OTBR_ERROR_NONE)\n {\n otbrLogWarning(\"failed to unsubscribe %s: %s\", fullName.c_str(), otbrErrorString(error));\n }\n}\n\nvoid DiscoveryProxy::OnServiceDiscovered(const std::string & aType,\n const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)\n{\n otDnssdServiceInstanceInfo instanceInfo;\n\n otbrLogInfo(\"service discovered: %s, instance %s hostname %s addresses %zu port %d priority %d \"\n \"weight %d\",\n aType.c_str(), aInstanceInfo.mName.c_str(), aInstanceInfo.mHostName.c_str(),\n aInstanceInfo.mAddresses.size(), aInstanceInfo.mPort, aInstanceInfo.mPriority, aInstanceInfo.mWeight);\n\n CheckServiceNameSanity(aType);\n CheckHostnameSanity(aInstanceInfo.mHostName);\n\n instanceInfo.mAddressNum = aInstanceInfo.mAddresses.size();\n\n if (!aInstanceInfo.mAddresses.empty())\n {\n instanceInfo.mAddresses = reinterpret_cast<const otIp6Address *>(&aInstanceInfo.mAddresses[0]);\n }\n else\n {\n instanceInfo.mAddresses = nullptr;\n }\n\n instanceInfo.mPort = aInstanceInfo.mPort;\n instanceInfo.mPriority = aInstanceInfo.mPriority;\n instanceInfo.mWeight = aInstanceInfo.mWeight;\n instanceInfo.mTxtLength = static_cast<uint16_t>(aInstanceInfo.mTxtData.size());\n instanceInfo.mTxtData = aInstanceInfo.mTxtData.data();\n instanceInfo.mTtl = CapTtl(aInstanceInfo.mTtl);\n\n std::for_each(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n if (aSubscription.MatchesServiceInstance(aType, aInstanceInfo.mName))\n {\n std::string serviceFullName = aType + \".\" + aSubscription.mDomain;\n std::string hostName = TranslateDomain(aInstanceInfo.mHostName, aSubscription.mDomain);\n std::string instanceFullName = aInstanceInfo.mName + \".\" + serviceFullName;\n\n instanceInfo.mFullName = instanceFullName.c_str();\n instanceInfo.mHostName = hostName.c_str();\n\n otDnssdQueryHandleDiscoveredServiceInstance(mNcp.GetInstance(), serviceFullName.c_str(), &instanceInfo);\n }\n });\n}\n\nvoid DiscoveryProxy::OnHostDiscovered(const std::string & aHostName,\n const Mdns::Publisher::DiscoveredHostInfo &aHostInfo)\n{\n otDnssdHostInfo hostInfo;\n\n otbrLogInfo(\"host discovered: %s hostname %s addresses %zu\", aHostName.c_str(), aHostInfo.mHostName.c_str(),\n aHostInfo.mAddresses.size());\n\n CheckHostnameSanity(aHostInfo.mHostName);\n\n hostInfo.mAddressNum = aHostInfo.mAddresses.size();\n if (!aHostInfo.mAddresses.empty())\n {\n hostInfo.mAddresses = reinterpret_cast<const otIp6Address *>(&aHostInfo.mAddresses[0]);\n }\n else\n {\n hostInfo.mAddresses = nullptr;\n }\n\n hostInfo.mTtl = CapTtl(aHostInfo.mTtl);\n\n std::for_each(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n if (aSubscription.MatchesHost(aHostName))\n {\n std::string hostFullName = TranslateDomain(aHostInfo.mHostName, aSubscription.mDomain);\n\n otDnssdQueryHandleDiscoveredHost(mNcp.GetInstance(), hostFullName.c_str(), &hostInfo);\n }\n });\n}\n\nstd::string DiscoveryProxy::TranslateDomain(const std::string &aName, const std::string &aTargetDomain)\n{\n std::string targetName;\n std::string hostName, domain;\n\n VerifyOrExit(OTBR_ERROR_NONE == SplitFullHostName(aName, hostName, domain), targetName = aName);\n VerifyOrExit(domain == \"local.\", targetName = aName);\n\n targetName = hostName + \".\" + aTargetDomain;\n\nexit:\n otbrLogDebug(\"translate domain: %s => %s\", aName.c_str(), targetName.c_str());\n return targetName;\n}\n\nint DiscoveryProxy::GetServiceSubscriptionCount(const std::string &aInstanceName,\n const std::string &aServiceName,\n const std::string &aHostName)\n{\n return std::accumulate(\n mSubscriptions.begin(), mSubscriptions.end(), 0, [&](int aAccum, const MdnsSubscription &aSubscription) {\n return aAccum + ((aSubscription.mInstanceName == aInstanceName &&\n aSubscription.mServiceName == aServiceName && aSubscription.mHostName == aHostName)\n ? aSubscription.mSubscriptionCount\n : 0);\n });\n}\n\nvoid DiscoveryProxy::CheckServiceNameSanity(const std::string &aType)\n{\n size_t dotpos;\n\n OTBR_UNUSED_VARIABLE(aType);\n OTBR_UNUSED_VARIABLE(dotpos);\n\n assert(aType.length() > 0);\n assert(aType[aType.length() - 1] != '.');\n dotpos = aType.find_first_of('.');\n assert(dotpos != std::string::npos);\n assert(dotpos == aType.find_last_of('.'));\n}\n\nvoid DiscoveryProxy::CheckHostnameSanity(const std::string &aHostName)\n{\n OTBR_UNUSED_VARIABLE(aHostName);\n\n assert(aHostName.length() > 0);\n assert(aHostName[aHostName.length() - 1] == '.');\n}\n\nuint32_t DiscoveryProxy::CapTtl(uint32_t aTtl)\n{\n return std::min(aTtl, static_cast<uint32_t>(kServiceTtlCapLimit));\n}\n\nstd::string DiscoveryProxy::MdnsSubscription::ToString(void) const\n{\n std::string str;\n\n if (!mHostName.empty())\n {\n str = mHostName + \".\" + mDomain;\n }\n else if (!mInstanceName.empty())\n {\n str = mInstanceName + \".\" + mServiceName + \".\" + mDomain;\n }\n else\n {\n str = mServiceName + \".\" + mDomain;\n }\n\n return str;\n}\n\nbool DiscoveryProxy::MdnsSubscription::Matches(const std::string &aInstanceName,\n const std::string &aServiceName,\n const std::string &aHostName,\n const std::string &aDomain) const\n{\n return mInstanceName == aInstanceName && mServiceName == aServiceName && mHostName == aHostName &&\n mDomain == aDomain;\n}\n\nbool DiscoveryProxy::MdnsSubscription::MatchesServiceInstance(const std::string &aType,\n const std::string &aInstanceName) const\n{\n return mServiceName == aType && (mInstanceName.empty() || mInstanceName == aInstanceName);\n}\n\nbool DiscoveryProxy::MdnsSubscription::MatchesHost(const std::string &aHostName) const\n{\n return mHostName == aHostName;\n}\n\n} \/\/ namespace Dnssd\n} \/\/ namespace otbr\n\n#endif \/\/ OTBR_ENABLE_DNSSD_DISCOVERY_PROXY\n<commit_msg>[dnssd] fix printing string after its destruction (#857)<commit_after>\/*\n * Copyright (c) 2021, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * The file implements the DNS-SD Discovery Proxy.\n *\/\n\n#if OTBR_ENABLE_DNSSD_DISCOVERY_PROXY\n\n#define OTBR_LOG_TAG \"DPROXY\"\n\n#include \"agent\/discovery_proxy.hpp\"\n\n#include <algorithm>\n#include <string>\n\n#include <assert.h>\n\n#include <openthread\/dnssd_server.h>\n\n#include \"common\/code_utils.hpp\"\n#include \"common\/dns_utils.hpp\"\n#include \"common\/logging.hpp\"\n\nnamespace otbr {\nnamespace Dnssd {\n\nDiscoveryProxy::DiscoveryProxy(Ncp::ControllerOpenThread &aNcp, Mdns::Publisher &aPublisher)\n : mNcp(aNcp)\n , mMdnsPublisher(aPublisher)\n{\n}\n\nvoid DiscoveryProxy::Start(void)\n{\n otDnssdQuerySetCallbacks(mNcp.GetInstance(), &DiscoveryProxy::OnDiscoveryProxySubscribe,\n &DiscoveryProxy::OnDiscoveryProxyUnsubscribe, this);\n\n mMdnsPublisher.SetSubscriptionCallbacks(\n [this](const std::string &aType, const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo) {\n OnServiceDiscovered(aType, aInstanceInfo);\n },\n\n [this](const std::string &aHostName, const Mdns::Publisher::DiscoveredHostInfo &aHostInfo) {\n OnHostDiscovered(aHostName, aHostInfo);\n });\n\n otbrLogInfo(\"started\");\n}\n\nvoid DiscoveryProxy::Stop(void)\n{\n otDnssdQuerySetCallbacks(mNcp.GetInstance(), nullptr, nullptr, nullptr);\n mMdnsPublisher.SetSubscriptionCallbacks(nullptr, nullptr);\n\n otbrLogInfo(\"stopped\");\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxySubscribe(void *aContext, const char *aFullName)\n{\n reinterpret_cast<DiscoveryProxy *>(aContext)->OnDiscoveryProxySubscribe(aFullName);\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxySubscribe(const char *aFullName)\n{\n std::string fullName(aFullName);\n otbrError error = OTBR_ERROR_NONE;\n MdnsSubscriptionList::iterator it;\n DnsNameInfo nameInfo = SplitFullDnsName(fullName);\n\n otbrLogInfo(\"subscribe: %s\", fullName.c_str());\n\n it = std::find_if(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n return aSubscription.Matches(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName,\n nameInfo.mDomain);\n });\n\n VerifyOrExit(it == mSubscriptions.end(), it->mSubscriptionCount++);\n\n mSubscriptions.emplace_back(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName, nameInfo.mDomain);\n\n {\n MdnsSubscription &subscription = mSubscriptions.back();\n\n otbrLogDebug(\"subscriptions: %sx%d\", subscription.ToString().c_str(), subscription.mSubscriptionCount);\n\n if (GetServiceSubscriptionCount(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName) == 1)\n {\n if (subscription.mHostName.empty())\n {\n mMdnsPublisher.SubscribeService(nameInfo.mServiceName, nameInfo.mInstanceName);\n }\n else\n {\n mMdnsPublisher.SubscribeHost(nameInfo.mHostName);\n }\n }\n }\n\nexit:\n if (error != OTBR_ERROR_NONE)\n {\n otbrLogWarning(\"failed to subscribe %s: %s\", fullName.c_str(), otbrErrorString(error));\n }\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxyUnsubscribe(void *aContext, const char *aFullName)\n{\n reinterpret_cast<DiscoveryProxy *>(aContext)->OnDiscoveryProxyUnsubscribe(aFullName);\n}\n\nvoid DiscoveryProxy::OnDiscoveryProxyUnsubscribe(const char *aFullName)\n{\n std::string fullName(aFullName);\n otbrError error = OTBR_ERROR_NONE;\n MdnsSubscriptionList::iterator it;\n DnsNameInfo nameInfo = SplitFullDnsName(fullName);\n\n otbrLogInfo(\"unsubscribe: %s\", fullName.c_str());\n\n it = std::find_if(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n return aSubscription.Matches(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName,\n nameInfo.mDomain);\n });\n\n VerifyOrExit(it != mSubscriptions.end(), error = OTBR_ERROR_NOT_FOUND);\n\n {\n MdnsSubscription &subscription = *it;\n\n subscription.mSubscriptionCount--;\n assert(subscription.mSubscriptionCount >= 0);\n\n otbrLogDebug(\"service subscriptions: %sx%d\", it->ToString().c_str(), it->mSubscriptionCount);\n\n if (subscription.mSubscriptionCount == 0)\n {\n mSubscriptions.erase(it);\n }\n\n if (GetServiceSubscriptionCount(nameInfo.mInstanceName, nameInfo.mServiceName, nameInfo.mHostName) == 0)\n {\n if (subscription.mHostName.empty())\n {\n mMdnsPublisher.UnsubscribeService(nameInfo.mServiceName, nameInfo.mInstanceName);\n }\n else\n {\n mMdnsPublisher.UnsubscribeHost(nameInfo.mHostName);\n }\n }\n }\nexit:\n if (error != OTBR_ERROR_NONE)\n {\n otbrLogWarning(\"failed to unsubscribe %s: %s\", fullName.c_str(), otbrErrorString(error));\n }\n}\n\nvoid DiscoveryProxy::OnServiceDiscovered(const std::string & aType,\n const Mdns::Publisher::DiscoveredInstanceInfo &aInstanceInfo)\n{\n otDnssdServiceInstanceInfo instanceInfo;\n\n otbrLogInfo(\"service discovered: %s, instance %s hostname %s addresses %zu port %d priority %d \"\n \"weight %d\",\n aType.c_str(), aInstanceInfo.mName.c_str(), aInstanceInfo.mHostName.c_str(),\n aInstanceInfo.mAddresses.size(), aInstanceInfo.mPort, aInstanceInfo.mPriority, aInstanceInfo.mWeight);\n\n CheckServiceNameSanity(aType);\n CheckHostnameSanity(aInstanceInfo.mHostName);\n\n instanceInfo.mAddressNum = aInstanceInfo.mAddresses.size();\n\n if (!aInstanceInfo.mAddresses.empty())\n {\n instanceInfo.mAddresses = reinterpret_cast<const otIp6Address *>(&aInstanceInfo.mAddresses[0]);\n }\n else\n {\n instanceInfo.mAddresses = nullptr;\n }\n\n instanceInfo.mPort = aInstanceInfo.mPort;\n instanceInfo.mPriority = aInstanceInfo.mPriority;\n instanceInfo.mWeight = aInstanceInfo.mWeight;\n instanceInfo.mTxtLength = static_cast<uint16_t>(aInstanceInfo.mTxtData.size());\n instanceInfo.mTxtData = aInstanceInfo.mTxtData.data();\n instanceInfo.mTtl = CapTtl(aInstanceInfo.mTtl);\n\n std::for_each(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n if (aSubscription.MatchesServiceInstance(aType, aInstanceInfo.mName))\n {\n std::string serviceFullName = aType + \".\" + aSubscription.mDomain;\n std::string hostName = TranslateDomain(aInstanceInfo.mHostName, aSubscription.mDomain);\n std::string instanceFullName = aInstanceInfo.mName + \".\" + serviceFullName;\n\n instanceInfo.mFullName = instanceFullName.c_str();\n instanceInfo.mHostName = hostName.c_str();\n\n otDnssdQueryHandleDiscoveredServiceInstance(mNcp.GetInstance(), serviceFullName.c_str(), &instanceInfo);\n }\n });\n}\n\nvoid DiscoveryProxy::OnHostDiscovered(const std::string & aHostName,\n const Mdns::Publisher::DiscoveredHostInfo &aHostInfo)\n{\n otDnssdHostInfo hostInfo;\n\n otbrLogInfo(\"host discovered: %s hostname %s addresses %zu\", aHostName.c_str(), aHostInfo.mHostName.c_str(),\n aHostInfo.mAddresses.size());\n\n CheckHostnameSanity(aHostInfo.mHostName);\n\n hostInfo.mAddressNum = aHostInfo.mAddresses.size();\n if (!aHostInfo.mAddresses.empty())\n {\n hostInfo.mAddresses = reinterpret_cast<const otIp6Address *>(&aHostInfo.mAddresses[0]);\n }\n else\n {\n hostInfo.mAddresses = nullptr;\n }\n\n hostInfo.mTtl = CapTtl(aHostInfo.mTtl);\n\n std::for_each(mSubscriptions.begin(), mSubscriptions.end(), [&](const MdnsSubscription &aSubscription) {\n if (aSubscription.MatchesHost(aHostName))\n {\n std::string hostFullName = TranslateDomain(aHostInfo.mHostName, aSubscription.mDomain);\n\n otDnssdQueryHandleDiscoveredHost(mNcp.GetInstance(), hostFullName.c_str(), &hostInfo);\n }\n });\n}\n\nstd::string DiscoveryProxy::TranslateDomain(const std::string &aName, const std::string &aTargetDomain)\n{\n std::string targetName;\n std::string hostName, domain;\n\n VerifyOrExit(OTBR_ERROR_NONE == SplitFullHostName(aName, hostName, domain), targetName = aName);\n VerifyOrExit(domain == \"local.\", targetName = aName);\n\n targetName = hostName + \".\" + aTargetDomain;\n\nexit:\n otbrLogDebug(\"translate domain: %s => %s\", aName.c_str(), targetName.c_str());\n return targetName;\n}\n\nint DiscoveryProxy::GetServiceSubscriptionCount(const std::string &aInstanceName,\n const std::string &aServiceName,\n const std::string &aHostName)\n{\n return std::accumulate(\n mSubscriptions.begin(), mSubscriptions.end(), 0, [&](int aAccum, const MdnsSubscription &aSubscription) {\n return aAccum + ((aSubscription.mInstanceName == aInstanceName &&\n aSubscription.mServiceName == aServiceName && aSubscription.mHostName == aHostName)\n ? aSubscription.mSubscriptionCount\n : 0);\n });\n}\n\nvoid DiscoveryProxy::CheckServiceNameSanity(const std::string &aType)\n{\n size_t dotpos;\n\n OTBR_UNUSED_VARIABLE(aType);\n OTBR_UNUSED_VARIABLE(dotpos);\n\n assert(aType.length() > 0);\n assert(aType[aType.length() - 1] != '.');\n dotpos = aType.find_first_of('.');\n assert(dotpos != std::string::npos);\n assert(dotpos == aType.find_last_of('.'));\n}\n\nvoid DiscoveryProxy::CheckHostnameSanity(const std::string &aHostName)\n{\n OTBR_UNUSED_VARIABLE(aHostName);\n\n assert(aHostName.length() > 0);\n assert(aHostName[aHostName.length() - 1] == '.');\n}\n\nuint32_t DiscoveryProxy::CapTtl(uint32_t aTtl)\n{\n return std::min(aTtl, static_cast<uint32_t>(kServiceTtlCapLimit));\n}\n\nstd::string DiscoveryProxy::MdnsSubscription::ToString(void) const\n{\n std::string str;\n\n if (!mHostName.empty())\n {\n str = mHostName + \".\" + mDomain;\n }\n else if (!mInstanceName.empty())\n {\n str = mInstanceName + \".\" + mServiceName + \".\" + mDomain;\n }\n else\n {\n str = mServiceName + \".\" + mDomain;\n }\n\n return str;\n}\n\nbool DiscoveryProxy::MdnsSubscription::Matches(const std::string &aInstanceName,\n const std::string &aServiceName,\n const std::string &aHostName,\n const std::string &aDomain) const\n{\n return mInstanceName == aInstanceName && mServiceName == aServiceName && mHostName == aHostName &&\n mDomain == aDomain;\n}\n\nbool DiscoveryProxy::MdnsSubscription::MatchesServiceInstance(const std::string &aType,\n const std::string &aInstanceName) const\n{\n return mServiceName == aType && (mInstanceName.empty() || mInstanceName == aInstanceName);\n}\n\nbool DiscoveryProxy::MdnsSubscription::MatchesHost(const std::string &aHostName) const\n{\n return mHostName == aHostName;\n}\n\n} \/\/ namespace Dnssd\n} \/\/ namespace otbr\n\n#endif \/\/ OTBR_ENABLE_DNSSD_DISCOVERY_PROXY\n<|endoftext|>"} {"text":"<commit_before>#include \"compiler\/build_tables\/build_parse_table.h\"\n#include <algorithm>\n#include <map>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include \"compiler\/parse_table.h\"\n#include \"compiler\/build_tables\/parse_conflict_manager.h\"\n#include \"compiler\/build_tables\/remove_duplicate_states.h\"\n#include \"compiler\/build_tables\/parse_item.h\"\n#include \"compiler\/build_tables\/item_set_closure.h\"\n#include \"compiler\/lexical_grammar.h\"\n#include \"compiler\/syntax_grammar.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/rules\/built_in_symbols.h\"\n#include \"compiler\/build_tables\/recovery_tokens.h\"\n\nnamespace tree_sitter {\nnamespace build_tables {\n\nusing std::find;\nusing std::pair;\nusing std::vector;\nusing std::set;\nusing std::map;\nusing std::string;\nusing std::to_string;\nusing std::unordered_map;\nusing std::make_shared;\nusing rules::Symbol;\n\nclass ParseTableBuilder {\n const SyntaxGrammar grammar;\n const LexicalGrammar lexical_grammar;\n ParseConflictManager conflict_manager;\n unordered_map<Symbol, ParseItemSet> recovery_states;\n unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;\n vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;\n ParseTable parse_table;\n std::set<string> conflicts;\n ParseItemSet null_item_set;\n std::set<const Production *> fragile_productions;\n bool allow_any_conflict;\n\n public:\n ParseTableBuilder(const SyntaxGrammar &grammar,\n const LexicalGrammar &lex_grammar)\n : grammar(grammar),\n lexical_grammar(lex_grammar),\n allow_any_conflict(false) {}\n\n pair<ParseTable, CompileError> build() {\n Symbol start_symbol = Symbol(0, grammar.variables.empty());\n Production start_production({\n ProductionStep(start_symbol, 0, rules::AssociativityNone),\n });\n\n add_parse_state(ParseItemSet({\n {\n ParseItem(rules::START(), start_production, 0),\n LookaheadSet({ rules::END_OF_INPUT() }),\n },\n }));\n\n CompileError error = process_part_state_queue();\n if (error.type != TSCompileErrorTypeNone) {\n return { parse_table, error };\n }\n\n add_out_of_context_parse_states();\n allow_any_conflict = true;\n process_part_state_queue();\n allow_any_conflict = false;\n\n for (ParseStateId state = 0; state < parse_table.states.size(); state++) {\n add_shift_extra_actions(state);\n add_reduce_extra_actions(state);\n }\n\n mark_fragile_actions();\n remove_duplicate_parse_states();\n\n return { parse_table, CompileError::none() };\n }\n\n private:\n CompileError process_part_state_queue() {\n while (!item_sets_to_process.empty()) {\n auto pair = item_sets_to_process.back();\n ParseItemSet item_set = item_set_closure(pair.first, grammar);\n\n ParseStateId state_id = pair.second;\n item_sets_to_process.pop_back();\n\n add_reduce_actions(item_set, state_id);\n add_shift_actions(item_set, state_id);\n\n if (!conflicts.empty()) {\n return CompileError(TSCompileErrorTypeParseConflict,\n \"Unresolved conflict.\\n\\n\" + *conflicts.begin());\n }\n }\n\n return CompileError::none();\n }\n\n void add_out_of_context_parse_states() {\n for (const Symbol &symbol : recovery_tokens(lexical_grammar)) {\n add_out_of_context_parse_state(symbol);\n }\n\n for (size_t i = 0; i < grammar.variables.size(); i++) {\n Symbol symbol(i, false);\n add_out_of_context_parse_state(symbol);\n }\n\n parse_table.error_state.actions[rules::END_OF_INPUT()].push_back(\n ParseAction::Shift(0, PrecedenceRange()));\n }\n\n void add_out_of_context_parse_state(const rules::Symbol &symbol) {\n const ParseItemSet &item_set = recovery_states[symbol];\n if (!item_set.entries.empty()) {\n ParseStateId state = add_parse_state(item_set);\n parse_table.error_state.actions[symbol].push_back(\n ParseAction::Shift(state, PrecedenceRange()));\n }\n }\n\n ParseStateId add_parse_state(const ParseItemSet &item_set) {\n auto pair = parse_state_ids.find(item_set);\n if (pair == parse_state_ids.end()) {\n ParseStateId state_id = parse_table.add_state();\n\n parse_state_ids[item_set] = state_id;\n item_sets_to_process.push_back({ item_set, state_id });\n return state_id;\n } else {\n return pair->second;\n }\n }\n\n void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &transition : item_set.transitions()) {\n const Symbol &symbol = transition.first;\n const ParseItemSet &next_item_set = transition.second.first;\n const PrecedenceRange &precedence = transition.second.second;\n\n ParseAction *new_action = add_action(\n state_id, symbol, ParseAction::Shift(0, precedence), item_set);\n\n if (!allow_any_conflict)\n recovery_states[symbol].add(next_item_set);\n\n if (new_action)\n new_action->state_index = add_parse_state(next_item_set);\n }\n }\n\n void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &pair : item_set.entries) {\n const ParseItem &item = pair.first;\n const auto &lookahead_symbols = pair.second;\n\n ParseItem::CompletionStatus status = item.completion_status();\n if (status.is_done) {\n ParseAction action;\n if (item.lhs() == rules::START()) {\n if (state_id == 1) {\n action = ParseAction::Accept();\n } else {\n continue;\n }\n } else {\n action = ParseAction::Reduce(Symbol(item.variable_index),\n item.step_index, status.precedence,\n status.associativity, *item.production);\n }\n\n for (const auto &lookahead_sym : *lookahead_symbols.entries)\n add_action(state_id, lookahead_sym, action, item_set);\n }\n }\n }\n\n void add_shift_extra_actions(ParseStateId state_id) {\n ParseAction action = ParseAction::ShiftExtra();\n for (const Symbol &extra_symbol : grammar.extra_tokens)\n add_action(state_id, extra_symbol, action, null_item_set);\n }\n\n void add_reduce_extra_actions(ParseStateId state_id) {\n const ParseState &state = parse_table.states[state_id];\n\n for (const Symbol &extra_symbol : grammar.extra_tokens) {\n const auto &actions_for_symbol = state.actions.find(extra_symbol);\n if (actions_for_symbol == state.actions.end())\n continue;\n\n for (const ParseAction &action : actions_for_symbol->second)\n if (action.type == ParseActionTypeShift && !action.extra) {\n size_t dest_state_id = action.state_index;\n ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);\n for (const auto &pair : state.actions)\n add_action(dest_state_id, pair.first, reduce_extra, null_item_set);\n }\n }\n }\n\n void mark_fragile_actions() {\n for (ParseState &state : parse_table.states) {\n set<Symbol> symbols_with_multiple_actions;\n\n for (auto &entry : state.actions) {\n if (entry.second.size() > 1)\n symbols_with_multiple_actions.insert(entry.first);\n\n for (ParseAction &action : entry.second) {\n if (action.type == ParseActionTypeReduce && !action.extra) {\n if (has_fragile_production(action.production))\n action.fragile = true;\n\n action.production = NULL;\n action.precedence_range = PrecedenceRange();\n action.associativity = rules::AssociativityNone;\n }\n }\n\n for (auto i = entry.second.begin(); i != entry.second.end();) {\n bool erased = false;\n for (auto j = entry.second.begin(); j != i; j++) {\n if (*j == *i) {\n entry.second.erase(i);\n erased = true;\n break;\n }\n }\n if (!erased)\n ++i;\n }\n }\n\n if (!symbols_with_multiple_actions.empty()) {\n for (auto &entry : state.actions) {\n if (!entry.first.is_token) {\n set<Symbol> first_set = get_first_set(entry.first);\n for (const Symbol &symbol : symbols_with_multiple_actions) {\n if (first_set.count(symbol)) {\n entry.second[0].can_hide_split = true;\n break;\n }\n }\n }\n }\n }\n }\n }\n\n void remove_duplicate_parse_states() {\n auto replacements =\n remove_duplicate_states<ParseState, ParseAction>(&parse_table.states);\n\n parse_table.error_state.each_advance_action(\n [&replacements](ParseAction *action) {\n auto replacement = replacements.find(action->state_index);\n if (replacement != replacements.end())\n action->state_index = replacement->second;\n });\n }\n\n ParseAction *add_action(ParseStateId state_id, Symbol lookahead,\n const ParseAction &new_action,\n const ParseItemSet &item_set) {\n const auto ¤t_actions = parse_table.states[state_id].actions;\n const auto ¤t_entry = current_actions.find(lookahead);\n if (current_entry == current_actions.end())\n return &parse_table.set_action(state_id, lookahead, new_action);\n if (allow_any_conflict)\n return &parse_table.add_action(state_id, lookahead, new_action);\n\n const ParseAction old_action = current_entry->second[0];\n auto resolution = conflict_manager.resolve(new_action, old_action);\n\n switch (resolution.second) {\n case ConflictTypeNone:\n if (resolution.first)\n return &parse_table.set_action(state_id, lookahead, new_action);\n break;\n\n case ConflictTypeResolved: {\n if (resolution.first) {\n if (old_action.type == ParseActionTypeReduce)\n fragile_productions.insert(old_action.production);\n return &parse_table.set_action(state_id, lookahead, new_action);\n } else {\n if (new_action.type == ParseActionTypeReduce)\n fragile_productions.insert(new_action.production);\n break;\n }\n }\n\n case ConflictTypeUnresolved: {\n if (handle_unresolved_conflict(item_set, lookahead)) {\n if (old_action.type == ParseActionTypeReduce)\n fragile_productions.insert(old_action.production);\n if (new_action.type == ParseActionTypeReduce)\n fragile_productions.insert(new_action.production);\n return &parse_table.add_action(state_id, lookahead, new_action);\n }\n break;\n }\n }\n\n return nullptr;\n }\n\n bool handle_unresolved_conflict(const ParseItemSet &item_set,\n const Symbol &lookahead) {\n set<Symbol> involved_symbols;\n set<ParseItem> reduce_items;\n set<ParseItem> core_shift_items;\n set<ParseItem> other_shift_items;\n\n for (const auto &pair : item_set.entries) {\n const ParseItem &item = pair.first;\n const LookaheadSet &lookahead_set = pair.second;\n\n Symbol next_symbol = item.next_symbol();\n if (next_symbol == rules::NONE()) {\n if (lookahead_set.contains(lookahead)) {\n involved_symbols.insert(item.lhs());\n reduce_items.insert(item);\n }\n } else {\n if (item.step_index > 0) {\n set<Symbol> first_set = get_first_set(next_symbol);\n if (first_set.count(lookahead)) {\n involved_symbols.insert(item.lhs());\n core_shift_items.insert(item);\n }\n } else if (next_symbol == lookahead) {\n other_shift_items.insert(item);\n }\n }\n }\n\n for (const auto &conflict_set : grammar.expected_conflicts)\n if (involved_symbols == conflict_set)\n return true;\n\n string description = \"Lookahead symbol: \" + symbol_name(lookahead) + \"\\n\";\n\n if (!reduce_items.empty()) {\n description += \"Reduce items:\\n\";\n for (const ParseItem &item : reduce_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n if (!core_shift_items.empty()) {\n description += \"Core shift items:\\n\";\n for (const ParseItem &item : core_shift_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n if (!other_shift_items.empty()) {\n description += \"Other shift items:\\n\";\n for (const ParseItem &item : other_shift_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n conflicts.insert(description);\n return false;\n }\n\n string item_string(const ParseItem &item) const {\n string result = symbol_name(item.lhs()) + \" ->\";\n size_t i = 0;\n for (const ProductionStep &step : *item.production) {\n if (i == item.step_index)\n result += \" \\u2022\";\n result += \" \" + symbol_name(step.symbol);\n i++;\n }\n if (i == item.step_index)\n result += \" \\u2022\";\n\n result += \" (prec \" + to_string(item.precedence());\n\n switch (item.associativity()) {\n case rules::AssociativityNone:\n result += \")\";\n break;\n case rules::AssociativityLeft:\n result += \", assoc left)\";\n break;\n case rules::AssociativityRight:\n result += \", assoc right)\";\n break;\n }\n\n return result;\n }\n\n set<Symbol> get_first_set(const Symbol &start_symbol) {\n set<Symbol> result;\n vector<Symbol> symbols_to_process({ start_symbol });\n\n while (!symbols_to_process.empty()) {\n Symbol symbol = symbols_to_process.back();\n symbols_to_process.pop_back();\n if (result.insert(symbol).second)\n for (const Production &production : grammar.productions(symbol))\n if (!production.empty())\n symbols_to_process.push_back(production[0].symbol);\n }\n\n return result;\n }\n\n string symbol_name(const rules::Symbol &symbol) const {\n if (symbol.is_built_in()) {\n if (symbol == rules::END_OF_INPUT())\n return \"END_OF_INPUT\";\n else\n return \"\";\n } else if (symbol.is_token) {\n const Variable &variable = lexical_grammar.variables[symbol.index];\n if (variable.type == VariableTypeNamed)\n return variable.name;\n else\n return \"'\" + variable.name + \"'\";\n } else {\n return grammar.variables[symbol.index].name;\n }\n }\n\n bool has_fragile_production(const Production *production) {\n auto end = fragile_productions.end();\n return std::find(fragile_productions.begin(), end, production) != end;\n }\n};\n\npair<ParseTable, CompileError> build_parse_table(\n const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {\n return ParseTableBuilder(grammar, lex_grammar).build();\n}\n\n} \/\/ namespace build_tables\n} \/\/ namespace tree_sitter\n<commit_msg>Include shift-extra actions alongside other actions in recovery states<commit_after>#include \"compiler\/build_tables\/build_parse_table.h\"\n#include <algorithm>\n#include <map>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include \"compiler\/parse_table.h\"\n#include \"compiler\/build_tables\/parse_conflict_manager.h\"\n#include \"compiler\/build_tables\/remove_duplicate_states.h\"\n#include \"compiler\/build_tables\/parse_item.h\"\n#include \"compiler\/build_tables\/item_set_closure.h\"\n#include \"compiler\/lexical_grammar.h\"\n#include \"compiler\/syntax_grammar.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/rules\/built_in_symbols.h\"\n#include \"compiler\/build_tables\/recovery_tokens.h\"\n\nnamespace tree_sitter {\nnamespace build_tables {\n\nusing std::find;\nusing std::pair;\nusing std::vector;\nusing std::set;\nusing std::map;\nusing std::string;\nusing std::to_string;\nusing std::unordered_map;\nusing std::make_shared;\nusing rules::Symbol;\n\nclass ParseTableBuilder {\n const SyntaxGrammar grammar;\n const LexicalGrammar lexical_grammar;\n ParseConflictManager conflict_manager;\n unordered_map<Symbol, ParseItemSet> recovery_states;\n unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;\n vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;\n ParseTable parse_table;\n std::set<string> conflicts;\n ParseItemSet null_item_set;\n std::set<const Production *> fragile_productions;\n bool allow_any_conflict;\n\n public:\n ParseTableBuilder(const SyntaxGrammar &grammar,\n const LexicalGrammar &lex_grammar)\n : grammar(grammar),\n lexical_grammar(lex_grammar),\n allow_any_conflict(false) {}\n\n pair<ParseTable, CompileError> build() {\n Symbol start_symbol = Symbol(0, grammar.variables.empty());\n Production start_production({\n ProductionStep(start_symbol, 0, rules::AssociativityNone),\n });\n\n add_parse_state(ParseItemSet({\n {\n ParseItem(rules::START(), start_production, 0),\n LookaheadSet({ rules::END_OF_INPUT() }),\n },\n }));\n\n CompileError error = process_part_state_queue();\n if (error.type != TSCompileErrorTypeNone)\n return { parse_table, error };\n\n add_out_of_context_parse_states();\n\n allow_any_conflict = true;\n process_part_state_queue();\n allow_any_conflict = false;\n\n for (ParseStateId state = 0; state < parse_table.states.size(); state++)\n add_reduce_extra_actions(state);\n\n mark_fragile_actions();\n remove_duplicate_parse_states();\n\n return { parse_table, CompileError::none() };\n }\n\n private:\n CompileError process_part_state_queue() {\n while (!item_sets_to_process.empty()) {\n auto pair = item_sets_to_process.back();\n ParseItemSet item_set = item_set_closure(pair.first, grammar);\n\n ParseStateId state_id = pair.second;\n item_sets_to_process.pop_back();\n\n add_reduce_actions(item_set, state_id);\n add_shift_actions(item_set, state_id);\n add_shift_extra_actions(state_id);\n\n if (!conflicts.empty()) {\n return CompileError(TSCompileErrorTypeParseConflict,\n \"Unresolved conflict.\\n\\n\" + *conflicts.begin());\n }\n }\n\n return CompileError::none();\n }\n\n void add_out_of_context_parse_states() {\n for (const Symbol &symbol : recovery_tokens(lexical_grammar)) {\n add_out_of_context_parse_state(symbol);\n }\n\n for (size_t i = 0; i < grammar.variables.size(); i++) {\n Symbol symbol(i, false);\n add_out_of_context_parse_state(symbol);\n }\n\n parse_table.error_state.actions[rules::END_OF_INPUT()].push_back(\n ParseAction::Shift(0, PrecedenceRange()));\n }\n\n void add_out_of_context_parse_state(const rules::Symbol &symbol) {\n const ParseItemSet &item_set = recovery_states[symbol];\n if (!item_set.entries.empty()) {\n ParseStateId state = add_parse_state(item_set);\n parse_table.error_state.actions[symbol].push_back(\n ParseAction::Shift(state, PrecedenceRange()));\n }\n }\n\n ParseStateId add_parse_state(const ParseItemSet &item_set) {\n auto pair = parse_state_ids.find(item_set);\n if (pair == parse_state_ids.end()) {\n ParseStateId state_id = parse_table.add_state();\n\n parse_state_ids[item_set] = state_id;\n item_sets_to_process.push_back({ item_set, state_id });\n return state_id;\n } else {\n return pair->second;\n }\n }\n\n void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &transition : item_set.transitions()) {\n const Symbol &symbol = transition.first;\n const ParseItemSet &next_item_set = transition.second.first;\n const PrecedenceRange &precedence = transition.second.second;\n\n ParseAction *new_action = add_action(\n state_id, symbol, ParseAction::Shift(0, precedence), item_set);\n\n if (!allow_any_conflict)\n recovery_states[symbol].add(next_item_set);\n\n if (new_action)\n new_action->state_index = add_parse_state(next_item_set);\n }\n }\n\n void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &pair : item_set.entries) {\n const ParseItem &item = pair.first;\n const auto &lookahead_symbols = pair.second;\n\n ParseItem::CompletionStatus status = item.completion_status();\n if (status.is_done) {\n ParseAction action;\n if (item.lhs() == rules::START()) {\n if (state_id == 1) {\n action = ParseAction::Accept();\n } else {\n continue;\n }\n } else {\n action = ParseAction::Reduce(Symbol(item.variable_index),\n item.step_index, status.precedence,\n status.associativity, *item.production);\n }\n\n for (const auto &lookahead_sym : *lookahead_symbols.entries)\n add_action(state_id, lookahead_sym, action, item_set);\n }\n }\n }\n\n void add_shift_extra_actions(ParseStateId state_id) {\n ParseAction action = ParseAction::ShiftExtra();\n for (const Symbol &extra_symbol : grammar.extra_tokens)\n add_action(state_id, extra_symbol, action, null_item_set);\n }\n\n void add_reduce_extra_actions(ParseStateId state_id) {\n const ParseState &state = parse_table.states[state_id];\n\n for (const Symbol &extra_symbol : grammar.extra_tokens) {\n const auto &actions_for_symbol = state.actions.find(extra_symbol);\n if (actions_for_symbol == state.actions.end())\n continue;\n\n for (const ParseAction &action : actions_for_symbol->second)\n if (action.type == ParseActionTypeShift && !action.extra) {\n size_t dest_state_id = action.state_index;\n ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);\n for (const auto &pair : state.actions)\n add_action(dest_state_id, pair.first, reduce_extra, null_item_set);\n }\n }\n }\n\n void mark_fragile_actions() {\n for (ParseState &state : parse_table.states) {\n set<Symbol> symbols_with_multiple_actions;\n\n for (auto &entry : state.actions) {\n if (entry.second.size() > 1)\n symbols_with_multiple_actions.insert(entry.first);\n\n for (ParseAction &action : entry.second) {\n if (action.type == ParseActionTypeReduce && !action.extra) {\n if (has_fragile_production(action.production))\n action.fragile = true;\n\n action.production = NULL;\n action.precedence_range = PrecedenceRange();\n action.associativity = rules::AssociativityNone;\n }\n }\n\n for (auto i = entry.second.begin(); i != entry.second.end();) {\n bool erased = false;\n for (auto j = entry.second.begin(); j != i; j++) {\n if (*j == *i) {\n entry.second.erase(i);\n erased = true;\n break;\n }\n }\n if (!erased)\n ++i;\n }\n }\n\n if (!symbols_with_multiple_actions.empty()) {\n for (auto &entry : state.actions) {\n if (!entry.first.is_token) {\n set<Symbol> first_set = get_first_set(entry.first);\n for (const Symbol &symbol : symbols_with_multiple_actions) {\n if (first_set.count(symbol)) {\n entry.second[0].can_hide_split = true;\n break;\n }\n }\n }\n }\n }\n }\n }\n\n void remove_duplicate_parse_states() {\n auto replacements =\n remove_duplicate_states<ParseState, ParseAction>(&parse_table.states);\n\n parse_table.error_state.each_advance_action(\n [&replacements](ParseAction *action) {\n auto replacement = replacements.find(action->state_index);\n if (replacement != replacements.end())\n action->state_index = replacement->second;\n });\n }\n\n ParseAction *add_action(ParseStateId state_id, Symbol lookahead,\n const ParseAction &new_action,\n const ParseItemSet &item_set) {\n const auto ¤t_actions = parse_table.states[state_id].actions;\n const auto ¤t_entry = current_actions.find(lookahead);\n if (current_entry == current_actions.end())\n return &parse_table.set_action(state_id, lookahead, new_action);\n if (allow_any_conflict)\n return &parse_table.add_action(state_id, lookahead, new_action);\n\n const ParseAction old_action = current_entry->second[0];\n auto resolution = conflict_manager.resolve(new_action, old_action);\n\n switch (resolution.second) {\n case ConflictTypeNone:\n if (resolution.first)\n return &parse_table.set_action(state_id, lookahead, new_action);\n break;\n\n case ConflictTypeResolved: {\n if (resolution.first) {\n if (old_action.type == ParseActionTypeReduce)\n fragile_productions.insert(old_action.production);\n return &parse_table.set_action(state_id, lookahead, new_action);\n } else {\n if (new_action.type == ParseActionTypeReduce)\n fragile_productions.insert(new_action.production);\n break;\n }\n }\n\n case ConflictTypeUnresolved: {\n if (handle_unresolved_conflict(item_set, lookahead)) {\n if (old_action.type == ParseActionTypeReduce)\n fragile_productions.insert(old_action.production);\n if (new_action.type == ParseActionTypeReduce)\n fragile_productions.insert(new_action.production);\n return &parse_table.add_action(state_id, lookahead, new_action);\n }\n break;\n }\n }\n\n return nullptr;\n }\n\n bool handle_unresolved_conflict(const ParseItemSet &item_set,\n const Symbol &lookahead) {\n set<Symbol> involved_symbols;\n set<ParseItem> reduce_items;\n set<ParseItem> core_shift_items;\n set<ParseItem> other_shift_items;\n\n for (const auto &pair : item_set.entries) {\n const ParseItem &item = pair.first;\n const LookaheadSet &lookahead_set = pair.second;\n\n Symbol next_symbol = item.next_symbol();\n if (next_symbol == rules::NONE()) {\n if (lookahead_set.contains(lookahead)) {\n involved_symbols.insert(item.lhs());\n reduce_items.insert(item);\n }\n } else {\n if (item.step_index > 0) {\n set<Symbol> first_set = get_first_set(next_symbol);\n if (first_set.count(lookahead)) {\n involved_symbols.insert(item.lhs());\n core_shift_items.insert(item);\n }\n } else if (next_symbol == lookahead) {\n other_shift_items.insert(item);\n }\n }\n }\n\n for (const auto &conflict_set : grammar.expected_conflicts)\n if (involved_symbols == conflict_set)\n return true;\n\n string description = \"Lookahead symbol: \" + symbol_name(lookahead) + \"\\n\";\n\n if (!reduce_items.empty()) {\n description += \"Reduce items:\\n\";\n for (const ParseItem &item : reduce_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n if (!core_shift_items.empty()) {\n description += \"Core shift items:\\n\";\n for (const ParseItem &item : core_shift_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n if (!other_shift_items.empty()) {\n description += \"Other shift items:\\n\";\n for (const ParseItem &item : other_shift_items)\n description += \" \" + item_string(item) + \"\\n\";\n }\n\n conflicts.insert(description);\n return false;\n }\n\n string item_string(const ParseItem &item) const {\n string result = symbol_name(item.lhs()) + \" ->\";\n size_t i = 0;\n for (const ProductionStep &step : *item.production) {\n if (i == item.step_index)\n result += \" \\u2022\";\n result += \" \" + symbol_name(step.symbol);\n i++;\n }\n if (i == item.step_index)\n result += \" \\u2022\";\n\n result += \" (prec \" + to_string(item.precedence());\n\n switch (item.associativity()) {\n case rules::AssociativityNone:\n result += \")\";\n break;\n case rules::AssociativityLeft:\n result += \", assoc left)\";\n break;\n case rules::AssociativityRight:\n result += \", assoc right)\";\n break;\n }\n\n return result;\n }\n\n set<Symbol> get_first_set(const Symbol &start_symbol) {\n set<Symbol> result;\n vector<Symbol> symbols_to_process({ start_symbol });\n\n while (!symbols_to_process.empty()) {\n Symbol symbol = symbols_to_process.back();\n symbols_to_process.pop_back();\n if (result.insert(symbol).second)\n for (const Production &production : grammar.productions(symbol))\n if (!production.empty())\n symbols_to_process.push_back(production[0].symbol);\n }\n\n return result;\n }\n\n string symbol_name(const rules::Symbol &symbol) const {\n if (symbol.is_built_in()) {\n if (symbol == rules::END_OF_INPUT())\n return \"END_OF_INPUT\";\n else\n return \"\";\n } else if (symbol.is_token) {\n const Variable &variable = lexical_grammar.variables[symbol.index];\n if (variable.type == VariableTypeNamed)\n return variable.name;\n else\n return \"'\" + variable.name + \"'\";\n } else {\n return grammar.variables[symbol.index].name;\n }\n }\n\n bool has_fragile_production(const Production *production) {\n auto end = fragile_productions.end();\n return std::find(fragile_productions.begin(), end, production) != end;\n }\n};\n\npair<ParseTable, CompileError> build_parse_table(\n const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {\n return ParseTableBuilder(grammar, lex_grammar).build();\n}\n\n} \/\/ namespace build_tables\n} \/\/ namespace tree_sitter\n<|endoftext|>"} {"text":"<commit_before>#include \"hopsanc.h\"\n#include <iostream>\n\n#include \"HopsanCore.h\"\n#include \"HopsanEssentials.h\"\n#include \"ComponentSystem.h\"\n\nstatic hopsan::ComponentSystem *spCoreComponentSystem = nullptr;\nstatic hopsan::HopsanEssentials gHopsanCore;\n\nstatic double startTime, stopTime;\n\n\/\/! @brief Prints all waiting messages\n\/\/! @param[in] printDebug Should debug messages also be printed\nvoid printWaitingMessages(hopsan::HopsanEssentials& hopsanCore, bool printDebug, bool silent)\n{\n if(silent) return;\n\n hopsan::HString msg, type, tag;\n while (hopsanCore.checkMessage() > 0) {\n hopsanCore.getMessage(msg,type,tag);\n if (type == \"debug\") {\n if (printDebug) {\n std::cout << msg.c_str() << \"\\n\";\n }\n }\n else {\n std::cout << msg.c_str() << \"\\n\";\n }\n }\n}\n\n\nint loadModel(const char* path) {\n spCoreComponentSystem = gHopsanCore.loadHMFModelFile(path, startTime, stopTime);\n if(!spCoreComponentSystem) {\n std::cout << \"Failed to instantiate model!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n const hopsan::HString modelName = spCoreComponentSystem->getName();\n spCoreComponentSystem->addSearchPath(modelName+\"-resources\");\n std::cout << \"Loaded model: \" << modelName.c_str() << \"\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\n\n\/\/! @brief Returns specified data vector as C array\n\/\/! @param [in] variable Variable name (\"component.port.variable\")\n\/\/! @param [out] size Size of returned data array\n\/\/! @returns Pointer to data array\ndouble *getDataVector(const char* variable, int &size)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"No model is loaded.\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Parse variable string\n hopsan::HString varStr(variable);\n hopsan::HVector<hopsan::HString>splitVar = varStr.split('.');\n if(splitVar.size() < 3) {\n std::cout << \"Component name, port name and variable name must be specified.\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Find component\n hopsan::Component *pComp = spCoreComponentSystem->getSubComponent(splitVar[0]);\n if(!pComp) {\n std::cout << \"No such component: \" << splitVar[0].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Find port\n hopsan::Port *pPort = pComp->getPort(splitVar[1]);\n if(!pPort) {\n std::cout << \"No such port: \" << splitVar[1].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n int varId = pPort->getNodeDataIdFromName(splitVar[2]);\n if(varId < 0) {\n std::cout << \"No such variable: \" << splitVar[2].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n size = int(spCoreComponentSystem->getNumActuallyLoggedSamples());\n double *data = new double[size];\n std::vector< std::vector<double> > *pLogData = pPort->getLogDataVectorPtr();\n for (size_t t=0; t<spCoreComponentSystem->getNumActuallyLoggedSamples(); ++t) {\n data[t] = (*pLogData)[t][size_t(varId)];\n }\n\n return data;\n}\n\nint loadLibrary(const char *path)\n{\n if(!gHopsanCore.loadExternalComponentLib(path)) {\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n };\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\nint setStartTime(double value)\n{\n startTime = value;\n return 0;\n}\n\nint setTimeStep(double value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded!\\n\";\n return -1;\n }\n spCoreComponentSystem->setDesiredTimestep(value);\n return 0;\n}\n\nint setStopTime(double value)\n{\n stopTime = value;\n return 0;\n}\n\nint simulate()\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded!\\n\";\n return -1;\n }\n std::cout << \"Checking model... \";\n if (spCoreComponentSystem->checkModelBeforeSimulation()) {\n std::cout << \"Success!\\n\";\n }\n else {\n std::cout << \"Failed!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n\n std::cout << \"Initializing model... \";\n if(spCoreComponentSystem->initialize(startTime, stopTime)) {\n std::cout << \"Success!\\n\";\n }\n else {\n std::cout << \"Failed!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n printWaitingMessages(gHopsanCore, false, false);\n\n std::cout << \"Simulating... \";\n spCoreComponentSystem->simulate(stopTime);\n std::cout << \"Finished!\\n\";\n\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\ndouble *getTimeVector(int &size)\n{\n if(!spCoreComponentSystem) {\n size = -1;\n return nullptr;\n }\n size = int(spCoreComponentSystem->getNumActuallyLoggedSamples());\n return spCoreComponentSystem->getLogTimeVector()->data();\n}\n\n\n\nint setParameter(const char *name, const char *value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"No model is loaded.\\n\";\n return -1;\n }\n\n hopsan::HString nameStr(name);\n hopsan::HVector<hopsan::HString> nameVec = nameStr.split('.');\n\n if(nameVec.size() == 1) {\n if(spCoreComponentSystem->setParameterValue(nameVec[0], hopsan::HString(value))) {\n return 0;\n }\n else {\n std::cout << \"Failed to set parameter value: \" << nameVec[0].c_str() << \"\\n\";\n return -1;\n }\n }\n else if(nameVec.size() == 2) {\n hopsan::Component *pComp = spCoreComponentSystem->getSubComponent(nameVec[0]);\n if(!pComp) {\n std::cout << \"No such component: \" << nameVec[0].c_str() << \"\\n\";\n return -1;\n }\n if(pComp->setParameterValue(nameVec[1], hopsan::HString(value))) {\n return 0;\n }\n else {\n std::cout << \"Failed to set parameter value: \" << nameVec[1].c_str() << \"\\n\";\n return -1;\n }\n }\n\n std::cout << \"Wrong number of arguments.\\n\";\n return -1;\n}\n\nint setLogSamples(unsigned long value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded.\\n\";\n return -1;\n }\n std::cout << \"Setting samples to \" << size_t(value) << \"\\n\";\n spCoreComponentSystem->setNumLogSamples(value);\n return 0;\n}\n<commit_msg>Support subsystems in C wrapper<commit_after>#include \"hopsanc.h\"\n#include <iostream>\n\n#include \"HopsanCore.h\"\n#include \"HopsanEssentials.h\"\n#include \"ComponentSystem.h\"\n\nstatic hopsan::ComponentSystem *spCoreComponentSystem = nullptr;\nstatic hopsan::HopsanEssentials gHopsanCore;\n\nstatic double startTime, stopTime;\n\n\/\/! @brief Prints all waiting messages\n\/\/! @param[in] printDebug Should debug messages also be printed\nvoid printWaitingMessages(hopsan::HopsanEssentials& hopsanCore, bool printDebug, bool silent)\n{\n if(silent) return;\n\n hopsan::HString msg, type, tag;\n while (hopsanCore.checkMessage() > 0) {\n hopsanCore.getMessage(msg,type,tag);\n if (type == \"debug\") {\n if (printDebug) {\n std::cout << msg.c_str() << \"\\n\";\n }\n }\n else {\n std::cout << msg.c_str() << \"\\n\";\n }\n }\n}\n\n\nint loadModel(const char* path) {\n spCoreComponentSystem = gHopsanCore.loadHMFModelFile(path, startTime, stopTime);\n if(!spCoreComponentSystem) {\n std::cout << \"Failed to instantiate model!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n const hopsan::HString modelName = spCoreComponentSystem->getName();\n spCoreComponentSystem->addSearchPath(modelName+\"-resources\");\n std::cout << \"Loaded model: \" << modelName.c_str() << \"\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\n\n\/\/! @brief Returns specified data vector as C array\n\/\/! @param [in] variable Variable name (\"component.port.variable\")\n\/\/! @param [out] size Size of returned data array\n\/\/! @returns Pointer to data array\ndouble *getDataVector(const char* variable, int &size)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"No model is loaded.\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Parse variable string\n hopsan::HString varStr(variable);\n hopsan::HVector<hopsan::HString> splitSys = varStr.split('|');\n hopsan::HVector<hopsan::HString> splitVar = splitSys.last().split('.');\n splitSys.resize(splitSys.size()-1);\n if(splitVar.size() < 3) {\n std::cout << \"Component name, port name and variable name must be specified.\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Find system\n hopsan::ComponentSystem *pSystem = spCoreComponentSystem;\n for(size_t i=0; i<splitSys.size(); ++i) {\n pSystem = pSystem->getSubComponentSystem(splitSys[i]);\n if(!pSystem) {\n std::cout << \"Error: Subsystem not found: \" << splitSys[i].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n }\n\n \/\/Find component\n hopsan::Component *pComp = pSystem->getSubComponent(splitVar[0]);\n if(!pComp) {\n std::cout << \"No such component: \" << splitVar[0].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n \/\/Find port\n hopsan::Port *pPort = pComp->getPort(splitVar[1]);\n if(!pPort) {\n std::cout << \"No such port: \" << splitVar[1].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n int varId = pPort->getNodeDataIdFromName(splitVar[2]);\n if(varId < 0) {\n std::cout << \"No such variable: \" << splitVar[2].c_str() << \"\\n\";\n size = -1;\n return nullptr;\n }\n\n size = int(spCoreComponentSystem->getNumActuallyLoggedSamples());\n double *data = new double[size];\n std::vector< std::vector<double> > *pLogData = pPort->getLogDataVectorPtr();\n for (size_t t=0; t<spCoreComponentSystem->getNumActuallyLoggedSamples(); ++t) {\n data[t] = (*pLogData)[t][size_t(varId)];\n }\n\n return data;\n}\n\nint loadLibrary(const char *path)\n{\n if(!gHopsanCore.loadExternalComponentLib(path)) {\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n };\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\nint setStartTime(double value)\n{\n startTime = value;\n return 0;\n}\n\nint setTimeStep(double value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded!\\n\";\n return -1;\n }\n spCoreComponentSystem->setDesiredTimestep(value);\n return 0;\n}\n\nint setStopTime(double value)\n{\n stopTime = value;\n return 0;\n}\n\nint simulate()\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded!\\n\";\n return -1;\n }\n std::cout << \"Checking model... \";\n if (spCoreComponentSystem->checkModelBeforeSimulation()) {\n std::cout << \"Success!\\n\";\n }\n else {\n std::cout << \"Failed!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n\n std::cout << \"Initializing model... \";\n if(spCoreComponentSystem->initialize(startTime, stopTime)) {\n std::cout << \"Success!\\n\";\n }\n else {\n std::cout << \"Failed!\\n\";\n printWaitingMessages(gHopsanCore, false, false);\n return -1;\n }\n printWaitingMessages(gHopsanCore, false, false);\n\n std::cout << \"Simulating... \";\n spCoreComponentSystem->simulate(stopTime);\n std::cout << \"Finished!\\n\";\n\n printWaitingMessages(gHopsanCore, false, false);\n return 0;\n}\n\ndouble *getTimeVector(int &size)\n{\n if(!spCoreComponentSystem) {\n size = -1;\n return nullptr;\n }\n size = int(spCoreComponentSystem->getNumActuallyLoggedSamples());\n return spCoreComponentSystem->getLogTimeVector()->data();\n}\n\n\n\nint setParameter(const char *name, const char *value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"No model is loaded.\\n\";\n return -1;\n }\n\n \/\/Parse arguments\n hopsan::HString nameStr(name);\n hopsan::HVector<hopsan::HString> sysVec = nameStr.split('|');\n hopsan::HVector<hopsan::HString> nameVec = sysVec.last().split('.');\n sysVec.resize(sysVec.size()-1);\n\n \/\/Generate component name and parameter name\n hopsan::HString compName, parName;\n if(nameVec.size() == 1) { \/\/System parameter\n compName = \"\";\n parName = nameVec[0];\n }\n else if(nameVec.size() == 2) { \/\/Constant\n compName = nameVec[0];\n parName = nameVec[1];\n }\n else if(nameVec.size() == 3) { \/\/Input variable\n compName = nameVec[0];\n parName = nameVec[1]+\"#\"+nameVec[2];\n }\n else {\n std::cout << \"Error: Parameter name not specified.\\n\";\n return -1;\n }\n\n \/\/Find system\n hopsan::ComponentSystem *pSystem = spCoreComponentSystem;\n for(size_t i=0; i<sysVec.size(); ++i) {\n pSystem = pSystem->getSubComponentSystem(sysVec[i]);\n if(!pSystem) {\n std::cout << \"Error: Subsystem not found: \" << sysVec[i].c_str() << \"\\n\";\n return -1;\n }\n }\n\n if(compName.empty()) { \/\/Set system parameter\n if(pSystem->setParameterValue(parName, hopsan::HString(value))) {\n return 0;\n }\n else {\n std::cout << \"Error: Failed to set parameter value: \" << parName.c_str() << \"\\n\";\n return -1;\n }\n }\n else if(nameVec.size() == 2 || nameVec.size() == 3) { \/\/Set constant or input variable\n hopsan::Component *pComp = pSystem->getSubComponent(compName);\n if(!pComp) {\n std::cout << \"Error: No such component: \" << compName.c_str() << \"\\n\";\n return -1;\n }\n if(pComp->setParameterValue(parName, hopsan::HString(value))) {\n return 0;\n }\n else {\n std::cout << \"Error: Failed to set parameter value: \" << parName.c_str() << \"\\n\";\n return -1;\n }\n }\n\n std::cout << \"Wrong number of arguments.\\n\";\n return -1;\n}\n\nint setLogSamples(unsigned long value)\n{\n if(!spCoreComponentSystem) {\n std::cout << \"Error: No model is loaded.\\n\";\n return -1;\n }\n std::cout << \"Setting samples to \" << size_t(value) << \"\\n\";\n spCoreComponentSystem->setNumLogSamples(value);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"interface.h\"\n#include \"def.h\"\n#include \"CoordSimilarity.h\"\n#include \"TimeSimilarity.h\"\n#include \"param.h\"\n\n#include <string>\n#include <time.h>\n#include <windows.h>\n#include <vector>\n#include <iostream>\n#include <chrono>\n#include <functional>\n#include <sstream>\n\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem.hpp> \n\nusing namespace std;\n\n\/\/#define UNICODE\n\nvector<string> csvname;\nBoost_Sock bm(IP, REQUESTPORT, nullptr, \"Request Sock\");\nBoost_Sock bmpop(IP, PARAMPORT, paramop_coord, \"Param Sock\");\n\nstd::string ws2s(const std::wstring& ws)\n{\n\tstd::string curLocale = setlocale(LC_ALL, NULL); \/\/ curLocale = \"C\";\n\tsetlocale(LC_ALL, \"chs\");\n\tconst wchar_t* _Source = ws.c_str();\n\tsize_t _Dsize = 2 * ws.size() + 1;\n\tchar *_Dest = new char[_Dsize];\n\tmemset(_Dest, 0, _Dsize);\n\twcstombs(_Dest, _Source, _Dsize);\n\tstd::string result = _Dest;\n\tdelete[] _Dest;\n\tsetlocale(LC_ALL, curLocale.c_str());\n\treturn result;\n}\n\nstd::wstring s2ws(const std::string& s)\n{\n\tsetlocale(LC_ALL, \"chs\");\n\tconst char* _Source = s.c_str();\n\tsize_t _Dsize = s.size() + 1;\n\twchar_t *_Dest = new wchar_t[_Dsize];\n\twmemset(_Dest, 0, _Dsize);\n\tmbstowcs(_Dest, _Source, _Dsize);\n\tstd::wstring result = _Dest;\n\tdelete[] _Dest;\n\tsetlocale(LC_ALL, \"C\");\n\treturn result;\n}\n\nvector<Point> read_csv(wstring path) {\n\tint record_count = 0;\n\tHANDLE hfile = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_READONLY, NULL);\n\tDWORD dwFileSize = GetFileSize(hfile, NULL);\n\tHANDLE hmapping = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, 0);\n\tLPVOID buffer_void = MapViewOfFile(hmapping, FILE_MAP_READ, 0, 0, 0);\n\t\/\/ Attetion to that not all csv are UNICODE, in our case, they are ANSI\n\tPCHAR abuf = (PCHAR)buffer_void;\n\t\/\/setlocale(LC_ALL, \"\");\n\n\tvector<Point> vp;\n\tPCHAR rows = abuf, cols = abuf;\n\tbool beheaded = false;\n\tdouble x = 0, y = 0;\n\tfor (DWORD offset = 0; offset < dwFileSize; offset++)\n\t{\n\t\tif (*abuf == '\\r') {\n\n\t\t}\n\t\telse if (*abuf == '\\n') {\n\t\t\tif (beheaded) {\n\t\t\t\ty = atof(string(cols, abuf - 1).c_str());\n\t\t\t\t\/\/ add point\n\t\t\t\tvp.push_back(Point(x, y));\n\t\t\t}\n\t\t\t\/\/ renew rows and cols\n\t\t\trows = abuf + 1;\n\t\t\tcols = abuf + 1;\n\t\t\tbeheaded = true;\n\t\t}\n\t\telse if (beheaded && *abuf == ',') {\n\t\t\tx = atof(string(cols, abuf).c_str());\n\t\t\t\/\/ renew cols\n\t\t\tcols = abuf + 1;\n\t\t}\n\t\tabuf++;\n\t}\n\tUnmapViewOfFile(buffer_void);\n\tCloseHandle(hmapping);\n\tCloseHandle(hfile);\n\treturn vp;\n}\n\nvector<TPoint> read_csv_time(wstring path) {\n\tint record_count = 0;\n\tHANDLE hfile = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_READONLY, NULL);\n\tDWORD dwFileSize = GetFileSize(hfile, NULL);\n\tHANDLE hmapping = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, 0);\n\tLPVOID buffer_void = MapViewOfFile(hmapping, FILE_MAP_READ, 0, 0, 0);\n\t\/\/ Attetion to that not all csv are UNICODE, in our case, they are ANSI\n\tPCHAR abuf = (PCHAR)buffer_void;\n\n\tvector<TPoint> vp;\n\tPCHAR rows = abuf, cols = abuf;\n\tbool beheaded = false;\n\tdouble x = 0, y = 0;\n\tunsigned long long t = 0;\n\tint state = 0;\n\tfor (DWORD offset = 0; offset < dwFileSize; offset++)\n\t{\n\t\tif (*abuf == '\\r') {\n\n\t\t}\n\t\telse if (*abuf == '\\n') {\n\t\t\tif (beheaded) {\n\t\t\t\ttm tmtime; tmtime.tm_sec = 0; tmtime.tm_isdst = -1;\n\t\t\t\tsscanf(cols, \"%04d\/%02d\/%02d %02d:%02d\\r\", &tmtime.tm_year, &tmtime.tm_mon, &tmtime.tm_mday, &tmtime.tm_hour, &tmtime.tm_min);\n\t\t\t\ttmtime.tm_year -= 1900;\n\t\t\t\tt = mktime(&tmtime);\n\t\t\t\t\/\/ add point\n\t\t\t\tvp.push_back(TPoint(x, y, t));\n\t\t\t}\n\t\t\t\/\/ renew rows and cols\n\t\t\trows = abuf + 1;\n\t\t\tcols = abuf + 1;\n\t\t\t\/\/ renew state\n\t\t\tstate = 0;\n\t\t\tbeheaded = true;\n\t\t}\n\t\telse if (beheaded && *abuf == ',') {\n\t\t\tif (state == 0)\n\t\t\t\tx = atof(string(cols, abuf).c_str());\n\t\t\telse if (state == 1)\n\t\t\t\ty = atof(string(cols, abuf).c_str());\n\t\t\t\/\/ renew cols\n\t\t\tcols = abuf + 1;\n\t\t\t\/\/ renew state\n\t\t\tstate++;\n\t\t}\n\t\tabuf++;\n\t}\n\tUnmapViewOfFile(buffer_void);\n\tCloseHandle(hmapping);\n\tCloseHandle(hfile);\n\treturn vp;\n}\n\nvoid get_all_csv(string fullpath = \"..\/..\/case\/origin\") {\n\tnamespace fs = boost::filesystem;\n\tfs::path full_path(fullpath, fs::native);\n\tif (!fs::exists(fullpath)) {\n\t\treturn;\n\t}\n\tfs::directory_iterator end_iter;\n\tfor (fs::directory_iterator iter(fullpath); iter != end_iter; iter++) {\n\t\ttry {\n\n\t\t\tif (fs::extension(*iter) == \".csv\") {\n\t\t\t\tcsvname.push_back(iter->path().filename().string());\n\t\t\t\t\/\/csvname.push_back(iter->path().string());\n\t\t\t}\n\t\t}\n\t\tcatch (const std::exception & ex) {\n\t\t\tstd::cerr << ex.what() << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nstring find_coord(string tracename) {\n\tusing namespace std;\n\tvector<vector<Point>> tofind;\n\tvector<Point> trace;\n\tif (csvname.empty())\n\t{\n\t\tget_all_csv();\n\t}\n\tfor (int i = 0; i < csvname.size(); i++)\n\t{\n\t\tif (tracename == csvname[i])\n\t\t{\n\t\t\ttrace = read_csv(s2ws(csvname[i]));\n\t\t}\n\t\telse {\n\t\t\ttofind.push_back(read_csv(s2ws(csvname[i])));\n\t\t}\n\t}\n\tCoordSimilarityList coord_list = CoordSort(trace, tofind);\n\tstring res1;\n\tfor (int i = 0;i < min(5, (int)coord_list.similarities.size());i++) {\n\t\tres1 += tracename;\n\t\tint j, k = coord_list.similarities[i].first;\n\t\tfor (j = 0;j < coord_list.trace_sections.size();j++) {\n\t\t\tif (coord_list.trace_sections[j].index == k) break;\n\t\t}\n\t\tif (j < coord_list.trace_sections.size()) {\n\t\t\tres1 += '&';\n\t\t\tstring tmp;\n\t\t\tstringstream ss;\n\t\t\tss << coord_list.trace_sections[j].t1_begin;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp;\n\t\t\tres1 += '!';\n\t\t\tss << coord_list.trace_sections[j].t1_end;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp;\n\t\t\tres1 += '*';\n\t\t\tres1 += csvname[k];\n\t\t\tres1 += '&';\n\t\t\tss << coord_list.trace_sections[j].t2_begin;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp;\n\t\t\tres1 += '!';\n\t\t\tss << coord_list.trace_sections[j].t2_end;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp;\n\t\t}\n\t}\n\treturn res1;\n}\n\nTimeSimilarityList find_time(string tracename) {\n\tusing namespace std;\n\tvector<vector<TPoint>> tofind;\n\tvector<TPoint> trace;\n\tif (csvname.empty())\n\t{\n\t\tget_all_csv();\n\t}\n\tfor (int i = 0; i < csvname.size(); i++)\n\t{\n\t\tif (tracename == csvname[i])\n\t\t{\n\t\t\ttrace = read_csv_time(s2ws(csvname[i]));\n\t\t}\n\t\telse {\n\t\t\ttofind.push_back(read_csv_time(s2ws(csvname[i])));\n\t\t}\n\t}\n\treturn TimeSort(trace, tofind);\n}\n\nstring cmp_coord(string tracename1, string tracename2) {\n\tusing namespace std;\n\tvector<Point> trace1, trace2;\n\ttrace1 = read_csv(s2ws(tracename1));\n\ttrace2 = read_csv(s2ws(tracename2));\n\tCoordSimilarity coord_simi = CoordCompare(trace1, trace2);\n\tstring res1 = tracename1;\n\tres1 += '&';\n\tstring tmp;\n\tstringstream ss;\n\tss << coord_simi.trace_sections[0].t1_begin;\n\tss >> tmp;\n\tres1 += tmp;\n\tres1 += '!';\n\tss << coord_simi.trace_sections[0].t1_end;\n\tss >> tmp;\n\tres1 += tmp;\n\tres1 += '*';\n\tres1 += tracename2;\n\tres1 += '&';\n\tss << coord_simi.trace_sections[0].t2_begin;\n\tss >> tmp;\n\tres1 += tmp;\n\tres1 += '!';\n\tss << coord_simi.trace_sections[0].t2_end;\n\tss >> tmp;\n\tres1 += tmp;\n\treturn res1;\n}\n\nTimeSimilarity cmp_time(string tracename1, string tracename2) {\n\tusing namespace std;\n\tvector<TPoint> trace1, trace2;\n\ttrace1 = read_csv_time(s2ws(tracename1));\n\ttrace2 = read_csv_time(s2ws(tracename2));\n\treturn TimeCompare(trace1, trace2);\n}\n\n\/*\n\tFlow Line\n\t* get_all_csv\n\tfind_coord\/find_time\n\tresult_encode(+4)\n\txxx_return\n*\/\n\n\nint wmain(int argc, TCHAR* argv[], TCHAR* env[]) {\n\t\/\/return_by_socket();\n\t\/\/paramop_return();\n\t\/\/get_all_csv();\n\n\n\t\/\/vector<Point> trace_coord[4];\n\t\/\/vector<TPoint> trace_time[4];\n\n\t\/\/for (int i = 0;i < 4;i++) {\n\t\/\/\twstring path = L\"..\/..\/case\/origin\/\";\n\t\/\/\twstring patht = L\"..\/..\/case\/origin\/\";\n\t\/\/\tpath += (i + '0');\n\t\/\/\tpath += L\".csv\";\n\t\/\/\tpatht += (i + '0');\n\t\/\/\tpatht += L\"t.csv\";\n\t\/\/\t\/\/cout << elapse_time(read_csv, path) << endl;\n\t\/\/\ttrace_coord[i] = read_csv(path);\n\t\/\/\ttrace_time[i] = read_csv_time(patht);\n\t\/\/}\n\n\tcout << cmp_coord(\"..\/..\/case\/origin\/1.csv\", \"..\/..\/case\/oringin\/2.csv\") << endl;\n\n\t\/\/printf(\"Sort Test\");\n\t\/\/std::vector< std::vector<Point> > traces;\n\t\/\/for (int i = 0;i < 3;i++) traces.push_back(trace_coord[i]);\n\t\/\/CoordSimilarityList coordlist = CoordSort(trace_coord[3], traces);\n\t\/\/for (int i = 0;i < coordlist.similarities.size();i++) {\n\t\/\/\tcout << coordlist.similarities[i].first << \" \";\n\t\/\/\tprintf(\"%.2f%%\\n\", coordlist.similarities[i].second * 100);\n\t\/\/}\n\t\/\/puts(\"\");\n\t\/\/for (int i = 0;i < coordlist.trace_sections.size();i++) {\n\t\/\/\tcout << \"mine between \";\n\t\/\/\tcout << coordlist.trace_sections[i].t1_begin << \" \";\n\t\/\/\tcout << coordlist.trace_sections[i].t1_end << \" \";\n\t\/\/\tcout << \"with trace \" << coordlist.trace_sections[i].index << \" between \";\n\t\/\/\tcout << coordlist.trace_sections[i].t2_begin << \" \";\n\t\/\/\tcout << coordlist.trace_sections[i].t2_end << \" \";\n\t\/\/\tprintf(\"%.2f%%\\n\", coordlist.trace_sections[i].coord_sim * 100);\n\t\/\/}\n\t\/\/puts(\"\");\n\n\tcout << \"׼\" << endl;\n\tbmpop.msg_loop();\n\tbm.msg_loop();\n\n\tsystem(\"pause\");\n\treturn 0;\n}<commit_msg>update<commit_after>#include \"interface.h\"\n#include \"def.h\"\n#include \"CoordSimilarity.h\"\n#include \"TimeSimilarity.h\"\n#include \"param.h\"\n\n#include <string>\n#include <time.h>\n#include <windows.h>\n#include <vector>\n#include <iostream>\n#include <chrono>\n#include <functional>\n#include <sstream>\n\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem.hpp> \n\nusing namespace std;\n\n\/\/#define UNICODE\n\nvector<string> csvname;\nBoost_Sock bm(IP, REQUESTPORT, nullptr, \"Request Sock\");\nBoost_Sock bmpop(IP, PARAMPORT, paramop_coord, \"Param Sock\");\n\nstd::string ws2s(const std::wstring& ws)\n{\n\tstd::string curLocale = setlocale(LC_ALL, NULL); \/\/ curLocale = \"C\";\n\tsetlocale(LC_ALL, \"chs\");\n\tconst wchar_t* _Source = ws.c_str();\n\tsize_t _Dsize = 2 * ws.size() + 1;\n\tchar *_Dest = new char[_Dsize];\n\tmemset(_Dest, 0, _Dsize);\n\twcstombs(_Dest, _Source, _Dsize);\n\tstd::string result = _Dest;\n\tdelete[] _Dest;\n\tsetlocale(LC_ALL, curLocale.c_str());\n\treturn result;\n}\n\nstd::wstring s2ws(const std::string& s)\n{\n\tsetlocale(LC_ALL, \"chs\");\n\tconst char* _Source = s.c_str();\n\tsize_t _Dsize = s.size() + 1;\n\twchar_t *_Dest = new wchar_t[_Dsize];\n\twmemset(_Dest, 0, _Dsize);\n\tmbstowcs(_Dest, _Source, _Dsize);\n\tstd::wstring result = _Dest;\n\tdelete[] _Dest;\n\tsetlocale(LC_ALL, \"C\");\n\treturn result;\n}\n\nvector<Point> read_csv(wstring path) {\n\tint record_count = 0;\n\tHANDLE hfile = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_READONLY, NULL);\n\tDWORD dwFileSize = GetFileSize(hfile, NULL);\n\tHANDLE hmapping = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, 0);\n\tLPVOID buffer_void = MapViewOfFile(hmapping, FILE_MAP_READ, 0, 0, 0);\n\t\/\/ Attetion to that not all csv are UNICODE, in our case, they are ANSI\n\tPCHAR abuf = (PCHAR)buffer_void;\n\t\/\/setlocale(LC_ALL, \"\");\n\n\tvector<Point> vp;\n\tPCHAR rows = abuf, cols = abuf;\n\tbool beheaded = false;\n\tdouble x = 0, y = 0;\n\tfor (DWORD offset = 0; offset < dwFileSize; offset++)\n\t{\n\t\tif (*abuf == '\\r') {\n\n\t\t}\n\t\telse if (*abuf == '\\n') {\n\t\t\tif (beheaded) {\n\t\t\t\ty = atof(string(cols, abuf - 1).c_str());\n\t\t\t\t\/\/ add point\n\t\t\t\tvp.push_back(Point(x, y));\n\t\t\t}\n\t\t\t\/\/ renew rows and cols\n\t\t\trows = abuf + 1;\n\t\t\tcols = abuf + 1;\n\t\t\tbeheaded = true;\n\t\t}\n\t\telse if (beheaded && *abuf == ',') {\n\t\t\tx = atof(string(cols, abuf).c_str());\n\t\t\t\/\/ renew cols\n\t\t\tcols = abuf + 1;\n\t\t}\n\t\tabuf++;\n\t}\n\tUnmapViewOfFile(buffer_void);\n\tCloseHandle(hmapping);\n\tCloseHandle(hfile);\n\treturn vp;\n}\n\nvector<TPoint> read_csv_time(wstring path) {\n\tint record_count = 0;\n\tHANDLE hfile = CreateFile(path.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_READONLY, NULL);\n\tDWORD dwFileSize = GetFileSize(hfile, NULL);\n\tHANDLE hmapping = CreateFileMapping(hfile, 0, PAGE_READONLY, 0, 0, 0);\n\tLPVOID buffer_void = MapViewOfFile(hmapping, FILE_MAP_READ, 0, 0, 0);\n\t\/\/ Attetion to that not all csv are UNICODE, in our case, they are ANSI\n\tPCHAR abuf = (PCHAR)buffer_void;\n\n\tvector<TPoint> vp;\n\tPCHAR rows = abuf, cols = abuf;\n\tbool beheaded = false;\n\tdouble x = 0, y = 0;\n\tunsigned long long t = 0;\n\tint state = 0;\n\tfor (DWORD offset = 0; offset < dwFileSize; offset++)\n\t{\n\t\tif (*abuf == '\\r') {\n\n\t\t}\n\t\telse if (*abuf == '\\n') {\n\t\t\tif (beheaded) {\n\t\t\t\ttm tmtime; tmtime.tm_sec = 0; tmtime.tm_isdst = -1;\n\t\t\t\tsscanf(cols, \"%04d\/%02d\/%02d %02d:%02d\\r\", &tmtime.tm_year, &tmtime.tm_mon, &tmtime.tm_mday, &tmtime.tm_hour, &tmtime.tm_min);\n\t\t\t\ttmtime.tm_year -= 1900;\n\t\t\t\tt = mktime(&tmtime);\n\t\t\t\t\/\/ add point\n\t\t\t\tvp.push_back(TPoint(x, y, t));\n\t\t\t}\n\t\t\t\/\/ renew rows and cols\n\t\t\trows = abuf + 1;\n\t\t\tcols = abuf + 1;\n\t\t\t\/\/ renew state\n\t\t\tstate = 0;\n\t\t\tbeheaded = true;\n\t\t}\n\t\telse if (beheaded && *abuf == ',') {\n\t\t\tif (state == 0)\n\t\t\t\tx = atof(string(cols, abuf).c_str());\n\t\t\telse if (state == 1)\n\t\t\t\ty = atof(string(cols, abuf).c_str());\n\t\t\t\/\/ renew cols\n\t\t\tcols = abuf + 1;\n\t\t\t\/\/ renew state\n\t\t\tstate++;\n\t\t}\n\t\tabuf++;\n\t}\n\tUnmapViewOfFile(buffer_void);\n\tCloseHandle(hmapping);\n\tCloseHandle(hfile);\n\treturn vp;\n}\n\nvoid get_all_csv(string fullpath = \"..\/..\/case\/origin\") {\n\tnamespace fs = boost::filesystem;\n\tfs::path full_path(fullpath, fs::native);\n\tif (!fs::exists(fullpath)) {\n\t\treturn;\n\t}\n\tfs::directory_iterator end_iter;\n\tfor (fs::directory_iterator iter(fullpath); iter != end_iter; iter++) {\n\t\ttry {\n\n\t\t\tif (fs::extension(*iter) == \".csv\") {\n\t\t\t\tcsvname.push_back(iter->path().filename().string());\n\t\t\t\t\/\/csvname.push_back(iter->path().string());\n\t\t\t}\n\t\t}\n\t\tcatch (const std::exception & ex) {\n\t\t\tstd::cerr << ex.what() << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nstring find_coord(string tracename) {\n\tusing namespace std;\n\tvector<vector<Point>> tofind;\n\tvector<Point> trace;\n\tif (csvname.empty()) {\n\t\tget_all_csv();\n\t}\n\tfor (int i = 0; i < csvname.size(); i++) {\n\t\tif (tracename == csvname[i]) {\n\t\t\ttrace = read_csv(s2ws(csvname[i]));\n\t\t}\n\t\telse {\n\t\t\ttofind.push_back(read_csv(s2ws(csvname[i])));\n\t\t}\n\t}\n\tCoordSimilarityList coord_list = CoordSort(trace, tofind);\n\tstring res1;\n\tfor (int i = 0;i < min(5, (int)coord_list.similarities.size());i++) {\n\t\tif (i > 0) res1 += ':';\n\t\tres1 += tracename;\n\t\tint j, k = coord_list.similarities[i].first;\n\t\tfor (j = 0;j < coord_list.trace_sections.size();j++) {\n\t\t\tif (coord_list.trace_sections[j].index == k) break;\n\t\t}\n\t\tif (j < coord_list.trace_sections.size()) {\n\t\t\tres1 += '&';\n\t\t\tstring tmp;\n\t\t\tstringstream ss;\n\t\t\tss.clear();\n\t\t\tss << coord_list.trace_sections[j].t1_begin;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp + '!';\n\t\t\tss.clear();\n\t\t\tss << coord_list.trace_sections[j].t1_end;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp + '*' + csvname[k] + '&';\n\t\t\tss.clear();\n\t\t\tss << coord_list.trace_sections[j].t2_begin;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp + '!';\n\t\t\tss.clear();\n\t\t\tss << coord_list.trace_sections[j].t2_end;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp + '*';\n\t\t\tss.clear();\n\t\t\tss << coord_list.similarities[i].second;\n\t\t\tss >> tmp;\n\t\t\tres1 += tmp;\n\t\t}\n\t}\n\treturn res1;\n}\n\nTimeSimilarityList find_time(string tracename) {\n\tusing namespace std;\n\tvector<vector<TPoint>> tofind;\n\tvector<TPoint> trace;\n\tif (csvname.empty())\n\t{\n\t\tget_all_csv();\n\t}\n\tfor (int i = 0; i < csvname.size(); i++)\n\t{\n\t\tif (tracename == csvname[i])\n\t\t{\n\t\t\ttrace = read_csv_time(s2ws(csvname[i]));\n\t\t}\n\t\telse {\n\t\t\ttofind.push_back(read_csv_time(s2ws(csvname[i])));\n\t\t}\n\t}\n\treturn TimeSort(trace, tofind);\n}\n\nstring cmp_coord(string tracename1, string tracename2) {\n\tusing namespace std;\n\tvector<Point> trace1, trace2;\n\ttrace1 = read_csv(s2ws(tracename1));\n\ttrace2 = read_csv(s2ws(tracename2));\n\tCoordSimilarity coord_simi = CoordCompare(trace1, trace2);\n\tstring res1 = tracename1;\n\tres1 += '&';\n\tstring tmp;\n\tstringstream ss;\n\tss.clear();\n\tss << coord_simi.trace_sections[0].t1_begin;\n\tss >> tmp;\n\tres1 += tmp + '!';\n\tss.clear();\n\tss << coord_simi.trace_sections[0].t1_end;\n\tss >> tmp;\n\tres1 += tmp + '*' + tracename2 + '&';\n\tss.clear();\n\tss << coord_simi.trace_sections[0].t2_begin;\n\tss >> tmp;\n\tres1 += tmp + '!';\n\tss.clear();\n\tss << coord_simi.trace_sections[0].t2_end;\n\tss >> tmp;\n\tres1 += tmp;\n\treturn res1;\n}\n\nTimeSimilarity cmp_time(string tracename1, string tracename2) {\n\tusing namespace std;\n\tvector<TPoint> trace1, trace2;\n\ttrace1 = read_csv_time(s2ws(tracename1));\n\ttrace2 = read_csv_time(s2ws(tracename2));\n\treturn TimeCompare(trace1, trace2);\n}\n\n\/*\n\tFlow Line\n\t* get_all_csv\n\tfind_coord\/find_time\n\tresult_encode(+4)\n\txxx_return\n*\/\n\n\nint wmain(int argc, TCHAR* argv[], TCHAR* env[]) {\n\t\/\/return_by_socket();\n\t\/\/paramop_return();\n\t\/\/get_all_csv();\n\n\n\tvector<Point> trace_coord[4];\n\t\/\/vector<TPoint> trace_time[4];\n\n\t\/\/for (int i = 0;i < 4;i++) {\n\t\/\/\twstring path = L\"..\/..\/case\/origin\/\";\n\t\/\/\twstring patht = L\"..\/..\/case\/origin\/\";\n\t\/\/\tpath += (i + '0');\n\t\/\/\tpath += L\".csv\";\n\t\/\/\tpatht += (i + '0');\n\t\/\/\tpatht += L\"t.csv\";\n\t\/\/\t\/\/cout << elapse_time(read_csv, path) << endl;\n\t\/\/\ttrace_coord[i] = read_csv(path);\n\t\/\/\ttrace_time[i] = read_csv_time(patht);\n\t\/\/}\n\n\tstring s1 = \"..\/..\/case\/origin\/1.csv\";\n\tstring s2 = \"..\/..\/case\/origin\/2.csv\";\n\tcout << cmp_coord(s1, s2) << endl;\n\t\/\/cout << find_coord(\"1.csv\") << endl;\n\n\t\/\/printf(\"Sort Test\");\n\t\/\/std::vector< std::vector<Point> > traces;\n\t\/\/for (int i = 0;i < 3;i++) traces.push_back(trace_coord[i]);\n\t\/\/CoordSimilarityList coordlist = CoordSort(trace_coord[3], traces);\n\t\/\/for (int i = 0;i < coordlist.similarities.size();i++) {\n\t\/\/\tcout << coordlist.similarities[i].first << \" \";\n\t\/\/\tprintf(\"%.2f%%\\n\", coordlist.similarities[i].second * 100);\n\t\/\/}\n\t\/\/puts(\"\");\n\t\/\/for (int i = 0;i < coordlist.trace_sections.size();i++) {\n\t\/\/\tcout << \"mine between \";\n\t\/\/\tcout << coordlist.trace_sections[i].t1_begin << \" \";\n\t\/\/\tcout << coordlist.trace_sections[i].t1_end << \" \";\n\t\/\/\tcout << \"with trace \" << coordlist.trace_sections[i].index << \" between \";\n\t\/\/\tcout << coordlist.trace_sections[i].t2_begin << \" \";\n\t\/\/\tcout << coordlist.trace_sections[i].t2_end << \" \";\n\t\/\/\tprintf(\"%.2f%%\\n\", coordlist.trace_sections[i].coord_sim * 100);\n\t\/\/}\n\t\/\/puts(\"\");\n\n\tcout << \"׼\" << endl;\n\tbmpop.msg_loop();\n\tbm.msg_loop();\n\n\tsystem(\"pause\");\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include \"compiler\/prepare_grammar\/extract_tokens.h\"\n#include <map>\n#include <vector>\n#include <set>\n#include <string>\n#include \"tree_sitter\/compiler.h\"\n#include \"compiler\/prepared_grammar.h\"\n#include \"compiler\/rules\/visitor.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/rules\/string.h\"\n#include \"compiler\/rules\/metadata.h\"\n#include \"compiler\/rules\/pattern.h\"\n#include \"compiler\/prepare_grammar\/token_description.h\"\n#include \"compiler\/prepare_grammar\/is_token.h\"\n\nnamespace tree_sitter {\nnamespace prepare_grammar {\n\nusing std::pair;\nusing std::tuple;\nusing std::string;\nusing std::map;\nusing std::to_string;\nusing std::vector;\nusing std::set;\nusing std::make_shared;\nusing std::make_tuple;\nusing std::dynamic_pointer_cast;\nusing rules::rule_ptr;\nusing rules::Symbol;\nusing rules::SymbolOptionToken;\nusing rules::SymbolOptionAuxToken;\n\nclass UsedSymbols : public rules::IdentityRuleFn {\n set<Symbol> used_symbols_;\n\n rules::rule_ptr apply(rules::Symbol *sym) {\n used_symbols_.insert(*sym);\n return sym->copy();\n }\n};\n\nclass SymbolInliner : public rules::IdentityRuleFn {\n map<Symbol, Symbol> replacements;\n using rules::IdentityRuleFn::apply_to;\n\n int new_index_for_symbol(const Symbol &symbol) {\n int result = symbol.index;\n for (const auto &pair : replacements)\n if (pair.first.index < symbol.index &&\n pair.first.is_auxiliary() == symbol.is_auxiliary())\n result--;\n return result;\n }\n\n rule_ptr apply_to(const Symbol *rule) { return replace_symbol(*rule).copy(); }\n\n public:\n Symbol replace_symbol(const Symbol &rule) {\n if (rule.is_built_in())\n return rule;\n auto replacement_pair = replacements.find(rule);\n if (replacement_pair != replacements.end())\n return replacement_pair->second;\n else\n return Symbol(new_index_for_symbol(rule), rule.options);\n }\n\n explicit SymbolInliner(const map<Symbol, Symbol> &replacements)\n : replacements(replacements) {}\n};\n\nclass TokenExtractor : public rules::IdentityRuleFn {\n\n rule_ptr apply_to_token(const rules::Rule *input) {\n auto rule = input->copy();\n for (size_t i = 0; i < tokens.size(); i++)\n if (tokens[i].second->operator==(*rule))\n return make_shared<Symbol>(i, SymbolOptionAuxToken);\n size_t index = tokens.size();\n tokens.push_back({ token_description(rule), rule });\n return make_shared<Symbol>(index, SymbolOptionAuxToken);\n }\n\n rule_ptr default_apply(const rules::Rule *rule) {\n auto result = rule->copy();\n if (is_token(rule->copy())) {\n return apply_to_token(rule);\n } else {\n return result;\n }\n }\n\n rule_ptr apply_to(const rules::Metadata *rule) {\n auto result = rule->copy();\n if (is_token(rule->copy())) {\n return apply_to_token(rule);\n } else {\n return rules::IdentityRuleFn::apply_to(rule);\n }\n }\n\n public:\n vector<pair<string, rule_ptr>> tokens;\n};\n\nstatic const GrammarError *ubiq_token_err(const string &msg) {\n return new GrammarError(GrammarErrorTypeInvalidUbiquitousToken, msg);\n}\n\ntuple<SyntaxGrammar, LexicalGrammar, const GrammarError *> extract_tokens(\n const Grammar &grammar) {\n vector<pair<string, rule_ptr>> rules, tokens, aux_rules, aux_tokens;\n vector<rule_ptr> separators;\n set<Symbol> ubiquitous_tokens;\n map<Symbol, Symbol> symbol_replacements;\n\n TokenExtractor extractor;\n\n for (size_t i = 0; i < grammar.rules().size(); i++) {\n auto pair = grammar.rules()[i];\n if (is_token(pair.second)) {\n tokens.push_back(pair);\n symbol_replacements.insert(\n { Symbol(i), Symbol(tokens.size() - 1, SymbolOptionToken) });\n } else {\n rules.push_back({ pair.first, extractor.apply(pair.second) });\n }\n }\n\n aux_tokens.insert(aux_tokens.end(), extractor.tokens.begin(),\n extractor.tokens.end());\n\n SymbolInliner inliner(symbol_replacements);\n for (auto &pair : rules)\n pair.second = inliner.apply(pair.second);\n\n for (auto rule : grammar.ubiquitous_tokens()) {\n if (is_token(rule)) {\n separators.push_back(rule);\n } else {\n auto sym = dynamic_pointer_cast<const Symbol>(extractor.apply(rule));\n if (!sym.get())\n return make_tuple(SyntaxGrammar(), LexicalGrammar(),\n ubiq_token_err(\"Not a token: \" + rule->to_string()));\n\n Symbol symbol = inliner.replace_symbol(*sym);\n if (!symbol.is_token())\n return make_tuple(SyntaxGrammar(), LexicalGrammar(),\n ubiq_token_err(\"Not a token: \" + symbol.to_string()));\n\n ubiquitous_tokens.insert(symbol);\n }\n }\n\n return make_tuple(SyntaxGrammar(rules, aux_rules, ubiquitous_tokens),\n LexicalGrammar(tokens, aux_tokens, separators), nullptr);\n}\n\n} \/\/ namespace prepare_grammar\n} \/\/ namespace tree_sitter\n<commit_msg>Remove unused code in extract_tokens.cc<commit_after>#include \"compiler\/prepare_grammar\/extract_tokens.h\"\n#include <map>\n#include <vector>\n#include <set>\n#include <string>\n#include \"tree_sitter\/compiler.h\"\n#include \"compiler\/prepared_grammar.h\"\n#include \"compiler\/rules\/visitor.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/rules\/string.h\"\n#include \"compiler\/rules\/metadata.h\"\n#include \"compiler\/rules\/pattern.h\"\n#include \"compiler\/prepare_grammar\/token_description.h\"\n#include \"compiler\/prepare_grammar\/is_token.h\"\n\nnamespace tree_sitter {\nnamespace prepare_grammar {\n\nusing std::dynamic_pointer_cast;\nusing std::make_shared;\nusing std::make_tuple;\nusing std::map;\nusing std::pair;\nusing std::set;\nusing std::string;\nusing std::tuple;\nusing std::vector;\nusing rules::rule_ptr;\nusing rules::Symbol;\nusing rules::SymbolOptionToken;\nusing rules::SymbolOptionAuxToken;\n\nclass SymbolInliner : public rules::IdentityRuleFn {\n map<Symbol, Symbol> replacements;\n using rules::IdentityRuleFn::apply_to;\n\n int new_index_for_symbol(const Symbol &symbol) {\n int result = symbol.index;\n for (const auto &pair : replacements)\n if (pair.first.index < symbol.index &&\n pair.first.is_auxiliary() == symbol.is_auxiliary())\n result--;\n return result;\n }\n\n rule_ptr apply_to(const Symbol *rule) { return replace_symbol(*rule).copy(); }\n\n public:\n Symbol replace_symbol(const Symbol &rule) {\n if (rule.is_built_in())\n return rule;\n auto replacement_pair = replacements.find(rule);\n if (replacement_pair != replacements.end())\n return replacement_pair->second;\n else\n return Symbol(new_index_for_symbol(rule), rule.options);\n }\n\n explicit SymbolInliner(const map<Symbol, Symbol> &replacements)\n : replacements(replacements) {}\n};\n\nclass TokenExtractor : public rules::IdentityRuleFn {\n rule_ptr apply_to_token(const rules::Rule *input) {\n auto rule = input->copy();\n for (size_t i = 0; i < tokens.size(); i++)\n if (tokens[i].second->operator==(*rule))\n return make_shared<Symbol>(i, SymbolOptionAuxToken);\n size_t index = tokens.size();\n tokens.push_back({ token_description(rule), rule });\n return make_shared<Symbol>(index, SymbolOptionAuxToken);\n }\n\n rule_ptr default_apply(const rules::Rule *rule) {\n auto result = rule->copy();\n if (is_token(rule->copy())) {\n return apply_to_token(rule);\n } else {\n return result;\n }\n }\n\n rule_ptr apply_to(const rules::Metadata *rule) {\n auto result = rule->copy();\n if (is_token(rule->copy())) {\n return apply_to_token(rule);\n } else {\n return rules::IdentityRuleFn::apply_to(rule);\n }\n }\n\n public:\n vector<pair<string, rule_ptr>> tokens;\n};\n\nstatic const GrammarError *ubiq_token_err(const string &msg) {\n return new GrammarError(GrammarErrorTypeInvalidUbiquitousToken, msg);\n}\n\ntuple<SyntaxGrammar, LexicalGrammar, const GrammarError *> extract_tokens(\n const Grammar &grammar) {\n vector<pair<string, rule_ptr>> rules, tokens, aux_rules, aux_tokens;\n vector<rule_ptr> separators;\n set<Symbol> ubiquitous_tokens;\n map<Symbol, Symbol> symbol_replacements;\n\n TokenExtractor extractor;\n\n for (size_t i = 0; i < grammar.rules().size(); i++) {\n auto pair = grammar.rules()[i];\n if (is_token(pair.second)) {\n tokens.push_back(pair);\n symbol_replacements.insert(\n { Symbol(i), Symbol(tokens.size() - 1, SymbolOptionToken) });\n } else {\n rules.push_back({ pair.first, extractor.apply(pair.second) });\n }\n }\n\n aux_tokens.insert(aux_tokens.end(), extractor.tokens.begin(),\n extractor.tokens.end());\n\n SymbolInliner inliner(symbol_replacements);\n for (auto &pair : rules)\n pair.second = inliner.apply(pair.second);\n\n for (auto rule : grammar.ubiquitous_tokens()) {\n if (is_token(rule)) {\n separators.push_back(rule);\n } else {\n auto sym = dynamic_pointer_cast<const Symbol>(extractor.apply(rule));\n if (!sym.get())\n return make_tuple(SyntaxGrammar(), LexicalGrammar(),\n ubiq_token_err(\"Not a token: \" + rule->to_string()));\n\n Symbol symbol = inliner.replace_symbol(*sym);\n if (!symbol.is_token())\n return make_tuple(SyntaxGrammar(), LexicalGrammar(),\n ubiq_token_err(\"Not a token: \" + symbol.to_string()));\n\n ubiquitous_tokens.insert(symbol);\n }\n }\n\n return make_tuple(SyntaxGrammar(rules, aux_rules, ubiquitous_tokens),\n LexicalGrammar(tokens, aux_tokens, separators), nullptr);\n}\n\n} \/\/ namespace prepare_grammar\n} \/\/ namespace tree_sitter\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------- data_out.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- data_out.cc ---------------------------\n\n\n#include <base\/quadrature_lib.h>\n#include <lac\/vector.h>\n#include <numerics\/data_out.h>\n#include <grid\/tria.h>\n#include <dofs\/dof_handler.h>\n#include <dofs\/dof_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <fe\/fe.h>\n#include <fe\/fe_values.h>\n\n#ifdef DEAL_II_USE_MT\n#include <base\/thread_manager.h>\n#endif\n\ntemplate <int dim>\nDataOut_DoFData<dim>::DataEntry::DataEntry (const Vector<double> *data,\n\t\t\t\t\t const vector<string> &names) :\n\t\tdata(data),\n\t\tnames(names)\n{};\n\ntemplate <int dim>\nDataOut_DoFData<dim>::DataOut_DoFData () :\n\t\tdofs(0)\n{};\n\ntemplate <int dim>\nDataOut_DoFData<dim>::~DataOut_DoFData ()\n{\n clear ();\n};\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::attach_dof_handler (const DoFHandler<dim> &d)\n{\n Assert (dof_data.size() == 0, ExcOldDataStillPresent());\n Assert (cell_data.size() == 0, ExcOldDataStillPresent());\n \n if (dofs != 0)\n dofs->unsubscribe ();\n \n dofs = &d;\n if (dofs != 0)\n dofs->subscribe ();\n};\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,\n\t\t\t\t\t const vector<string> &names)\n{\n Assert (dofs != 0, ExcNoDoFHandlerSelected ());\n\t\t\t\t \/\/ either cell data and one name,\n\t\t\t\t \/\/ or dof data and n_components names\n Assert (((vec.size() == dofs->get_tria().n_active_cells()) &&\n\t (names.size() == 1))\n\t ||\n\t ((vec.size() == dofs->n_dofs()) &&\n\t (names.size() == dofs->get_fe().n_components())),\n\t ExcInvalidNumberOfNames (names.size(), dofs->get_fe().n_components()));\n for (unsigned int i=0; i<names.size(); ++i)\n Assert (names[i].find_first_not_of(\"abcdefghijklmnopqrstuvwxyz\"\n\t\t\t\t \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\t\t \"0123456789_<>()\") == string::npos,\n\t ExcInvalidCharacter (names[i]));\n \n DataEntry new_entry (&vec, names);\n if (vec.size() == dofs->n_dofs())\n dof_data.push_back (new_entry);\n else\n if (vec.size() == dofs->get_tria().n_active_cells())\n cell_data.push_back (new_entry);\n else\n Assert (false,\n\t ExcInvalidVectorSize (vec.size(),\n\t\t\t\t dofs->n_dofs(),\n\t\t\t\t dofs->get_tria().n_active_cells()));\n};\n\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,\n\t\t\t\t\t const string &name)\n{\n\/\/ unsigned int n = dofs->get_fe().n_components ();\n\/\/ if (n > 1)\n\/\/ {\n\/\/ vector<string> names (dofs->get_fe().n_components ());\n\/\/ for (unsigned int i=0;i<n;++i)\n\/\/ \t{\n\/\/ \t names[i] = name + string(\"_\");\n\/\/ \t}\n\/\/ }\n\/\/TODO: Murks hier\n add_data_vector (vec, vector<string>(1,name));\n}\n\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::clear ()\n{\n dof_data.erase (dof_data.begin(), dof_data.end());\n cell_data.erase (cell_data.begin(), cell_data.end());\n\n if (dofs != 0)\n {\n dofs->unsubscribe ();\n dofs = 0;\n };\n\n\t\t\t\t \/\/ delete patches\n vector<DataOutBase::Patch<dim> > dummy;\n patches.swap (dummy);\n};\n\n\ntemplate <int dim>\nvector<string> DataOut_DoFData<dim>::get_dataset_names () const \n{\n vector<string> names;\n\t\t\t\t \/\/ collect the names of dof\n\t\t\t\t \/\/ and cell data\n for (vector<DataEntry>::const_iterator d=dof_data.begin(); d!=dof_data.end(); ++d)\n for (unsigned int i=0; i<d->names.size(); ++i)\n names.push_back (d->names[i]);\n for (vector<DataEntry>::const_iterator d=cell_data.begin(); d!=cell_data.end(); ++d)\n {\n Assert (d->names.size() == 1, ExcInternalError());\n names.push_back (d->names[0]);\n };\n\n return names;\n};\n\n\n\ntemplate <int dim>\nconst vector<typename DataOutBase::Patch<dim> > &\nDataOut_DoFData<dim>::get_patches () const\n{\n return patches;\n};\n\n\n\ntemplate <int dim>\nvoid DataOut<dim>::build_some_patches (Data data)\n{\n QTrapez<1> q_trapez;\n QIterated<dim> patch_points (q_trapez, data.n_subdivisions);\n \n FEValues<dim> fe_patch_values(dofs->get_fe(),\n\t\t\t\tpatch_points,\n\t\t\t\tupdate_default);\n\n const unsigned int n_q_points = patch_points.n_quadrature_points;\n \n unsigned int cell_number = 0;\n vector<DataOutBase::Patch<dim> >::iterator patch = patches.begin();\n DoFHandler<dim>::cell_iterator cell=first_cell();\n\n\t\t\t\t \/\/ get first cell in this thread\n for (unsigned int i=0;i<data.this_thread;++i,++patch,++cell_number,\n\t\t cell=next_cell(cell));\n \n \t\t\t\t \/\/ now loop over all cells and\n\t\t\t\t \/\/ actually create the patches\n for (;cell != dofs->end();)\n {\n Assert (patch != patches.end(), ExcInternalError());\n \n for (unsigned int vertex=0; vertex<GeometryInfo<dim>::vertices_per_cell; ++vertex)\n\tpatch->vertices[vertex] = cell->vertex(vertex);\n \n if (data.n_datasets > 0)\n\t{\n\t fe_patch_values.reinit (cell);\n\t \n\t\t\t\t\t \/\/ first fill dof_data\n\t for (unsigned int dataset=0; dataset<dof_data.size(); ++dataset)\n\t {\n\t if (data.n_components == 1)\n\t\t{\n\t\t fe_patch_values.get_function_values (*dof_data[dataset].data,\n\t\t\t\t\t\t data.patch_values);\n\t\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\t patch->data(dataset,q) = data.patch_values[q];\n\t\t}\n\t else\n\t\t\t\t\t\t \/\/ system of components\n\t\t{\n\t\t fe_patch_values.get_function_values (*dof_data[dataset].data,\n\t\t\t\t\t\t data.patch_values_system);\n\t\t for (unsigned int component=0; component<data.n_components;\n\t\t ++component)\n\t\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\t patch->data(dataset*data.n_components+component,q) =\n\t\t\tdata.patch_values_system[q](component);\n\t\t};\n\t };\n\n\t\t\t\t\t \/\/ then do the cell data\n\t for (unsigned int dataset=0; dataset<cell_data.size(); ++dataset)\n\t {\n\t const double value = (*cell_data[dataset].data)(cell_number);\n\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\tpatch->data(dataset+dof_data.size()*data.n_components,q) =\n\t\t value;\n\t };\n\t};\n \t\t\t\t \/\/ next cell (patch) in this thread\n for (unsigned int i=0;((i<data.n_threads)&&(cell != dofs->end()));\n\t ++i,++patch,++cell_number,cell=next_cell(cell));\n \n };\n}\n\n\ntemplate <int dim>\nvoid DataOut<dim>::build_patches (const unsigned int n_subdivisions,\n\t\t\t\t const unsigned int n_threads_) \n{\n Assert (dofs != 0, ExcNoDoFHandlerSelected());\n\n#ifdef DEAL_II_USE_MT\n const unsigned int n_threads = n_threads_;\n#else\n const unsigned int n_threads = 1;\n#endif\n\n\n\/\/ before we start the loop:\n\t\t\t\t \/\/ create a quadrature rule that\n\t\t\t\t \/\/ actually has the points on this\n\t\t\t\t \/\/ patch\n QTrapez<1> q_trapez;\n QIterated<dim> patch_points (q_trapez, n_subdivisions);\n\n const unsigned int n_q_points = patch_points.n_quadrature_points;\n const unsigned int n_components = dofs->get_fe().n_components();\n const unsigned int n_datasets = dof_data.size() * n_components +\n\t\t\t\t cell_data.size();\n \n\t\t\t\t \/\/ clear the patches array\n if (true)\n {\n vector<DataOutBase::Patch<dim> > dummy;\n patches.swap (dummy);\n };\n \n\t\t\t\t \/\/ first count the cells we want to\n\t\t\t\t \/\/ create patches of and make sure\n\t\t\t\t \/\/ there is enough memory for that\n unsigned int n_patches = 0;\n for (DoFHandler<dim>::cell_iterator cell=first_cell();\n cell != dofs->end();\n cell = next_cell(cell))\n ++n_patches;\n\n vector<Data> thread_data(n_threads);\n\n\t\t\t\t \/\/ init data for the threads\n for (unsigned int i=0;i<n_threads;++i)\n {\n thread_data[i].n_threads = n_threads;\n thread_data[i].this_thread = i;\n thread_data[i].n_components = n_components;\n thread_data[i].n_datasets = n_datasets;\n thread_data[i].n_subdivisions = n_subdivisions;\n thread_data[i].patch_values.resize (n_q_points);\n thread_data[i].patch_values_system.resize (n_q_points);\n \n for (unsigned int k=0; k<n_q_points; ++k)\n\tthread_data[i].patch_values_system[k].reinit(n_components);\n }\n\n\t\t\t\t \/\/ create the patches with\n\t\t\t\t \/\/ default values\n DataOutBase::Patch<dim> default_patch;\n default_patch.n_subdivisions = n_subdivisions;\n default_patch.data.reinit (n_datasets, n_q_points);\n patches.insert (patches.end(), n_patches, default_patch);\n\n#ifdef DEAL_II_USE_MT\n\n ThreadManager thread_manager;\n \n typedef ThreadManager::Mem_Fun_Data1\n <DataOut<dim>, Data> MemFunData;\n \n\t\t\t\t \/\/ One struct of this type for every thread\n vector<MemFunData> mem_fun_data (n_threads,\n\t\t\t\t MemFunData (this,\n\t\t\t\t\t thread_data[0],\n\t\t\t\t\t &DataOut<dim>::build_some_patches));\n \n\t\t\t\t \/\/ get start cells for each thread\n for (unsigned int l=0;l<n_threads;++l)\n {\n mem_fun_data[l].arg=thread_data[l];\n thread_manager.spawn(&mem_fun_data[l],THR_SCOPE_SYSTEM | THR_DETACHED);\n };\n\t\t\t\t \/\/ wait for all threads to return\n thread_manager.wait();\n \n\t\t\t\t \/\/ just one thread\n#else\n build_some_patches(thread_data[0]);\n#endif\n};\n\n\ntemplate <int dim>\ntypename DoFHandler<dim>::cell_iterator\nDataOut<dim>::first_cell () \n{\n return dofs->begin_active ();\n};\n\n\ntemplate <int dim>\ntypename DoFHandler<dim>::cell_iterator\nDataOut<dim>::next_cell (const typename DoFHandler<dim>::cell_iterator &cell) \n{\n\t\t\t\t \/\/ convert the iterator to an\n\t\t\t\t \/\/ active_iterator and advance\n\t\t\t\t \/\/ this to the next active cell\n typename DoFHandler<dim>::active_cell_iterator active_cell = cell;\n ++active_cell;\n return active_cell;\n};\n\n\n\/\/ explicit instantiations\ntemplate class DataOut_DoFData<deal_II_dimension>;\ntemplate class DataOut<deal_II_dimension>;\n\n\n<commit_msg>Avoid compiler warning.<commit_after>\/\/---------------------------- data_out.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- data_out.cc ---------------------------\n\n\n#include <base\/quadrature_lib.h>\n#include <lac\/vector.h>\n#include <numerics\/data_out.h>\n#include <grid\/tria.h>\n#include <dofs\/dof_handler.h>\n#include <dofs\/dof_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <fe\/fe.h>\n#include <fe\/fe_values.h>\n\n#ifdef DEAL_II_USE_MT\n#include <base\/thread_manager.h>\n#endif\n\ntemplate <int dim>\nDataOut_DoFData<dim>::DataEntry::DataEntry (const Vector<double> *data,\n\t\t\t\t\t const vector<string> &names) :\n\t\tdata(data),\n\t\tnames(names)\n{};\n\ntemplate <int dim>\nDataOut_DoFData<dim>::DataOut_DoFData () :\n\t\tdofs(0)\n{};\n\ntemplate <int dim>\nDataOut_DoFData<dim>::~DataOut_DoFData ()\n{\n clear ();\n};\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::attach_dof_handler (const DoFHandler<dim> &d)\n{\n Assert (dof_data.size() == 0, ExcOldDataStillPresent());\n Assert (cell_data.size() == 0, ExcOldDataStillPresent());\n \n if (dofs != 0)\n dofs->unsubscribe ();\n \n dofs = &d;\n if (dofs != 0)\n dofs->subscribe ();\n};\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,\n\t\t\t\t\t const vector<string> &names)\n{\n Assert (dofs != 0, ExcNoDoFHandlerSelected ());\n\t\t\t\t \/\/ either cell data and one name,\n\t\t\t\t \/\/ or dof data and n_components names\n Assert (((vec.size() == dofs->get_tria().n_active_cells()) &&\n\t (names.size() == 1))\n\t ||\n\t ((vec.size() == dofs->n_dofs()) &&\n\t (names.size() == dofs->get_fe().n_components())),\n\t ExcInvalidNumberOfNames (names.size(), dofs->get_fe().n_components()));\n for (unsigned int i=0; i<names.size(); ++i)\n Assert (names[i].find_first_not_of(\"abcdefghijklmnopqrstuvwxyz\"\n\t\t\t\t \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\t\t\t \"0123456789_<>()\") == string::npos,\n\t ExcInvalidCharacter (names[i]));\n \n DataEntry new_entry (&vec, names);\n if (vec.size() == dofs->n_dofs())\n dof_data.push_back (new_entry);\n else\n if (vec.size() == dofs->get_tria().n_active_cells())\n cell_data.push_back (new_entry);\n else\n Assert (false,\n\t ExcInvalidVectorSize (vec.size(),\n\t\t\t\t dofs->n_dofs(),\n\t\t\t\t dofs->get_tria().n_active_cells()));\n};\n\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::add_data_vector (const Vector<double> &vec,\n\t\t\t\t\t const string &name)\n{\n\/\/ unsigned int n = dofs->get_fe().n_components ();\n\/\/ if (n > 1)\n\/\/ {\n\/\/ vector<string> names (dofs->get_fe().n_components ());\n\/\/ for (unsigned int i=0;i<n;++i)\n\/\/ \t{\n\/\/ \t names[i] = name + string(\"_\");\n\/\/ \t}\n\/\/ }\n\/\/TODO: Murks hier\n add_data_vector (vec, vector<string>(1,name));\n}\n\n\ntemplate <int dim>\nvoid DataOut_DoFData<dim>::clear ()\n{\n dof_data.erase (dof_data.begin(), dof_data.end());\n cell_data.erase (cell_data.begin(), cell_data.end());\n\n if (dofs != 0)\n {\n dofs->unsubscribe ();\n dofs = 0;\n };\n\n\t\t\t\t \/\/ delete patches\n vector<DataOutBase::Patch<dim> > dummy;\n patches.swap (dummy);\n};\n\n\ntemplate <int dim>\nvector<string> DataOut_DoFData<dim>::get_dataset_names () const \n{\n vector<string> names;\n\t\t\t\t \/\/ collect the names of dof\n\t\t\t\t \/\/ and cell data\n for (vector<DataEntry>::const_iterator d=dof_data.begin(); d!=dof_data.end(); ++d)\n for (unsigned int i=0; i<d->names.size(); ++i)\n names.push_back (d->names[i]);\n for (vector<DataEntry>::const_iterator d=cell_data.begin(); d!=cell_data.end(); ++d)\n {\n Assert (d->names.size() == 1, ExcInternalError());\n names.push_back (d->names[0]);\n };\n\n return names;\n};\n\n\n\ntemplate <int dim>\nconst vector<typename DataOutBase::Patch<dim> > &\nDataOut_DoFData<dim>::get_patches () const\n{\n return patches;\n};\n\n\n\ntemplate <int dim>\nvoid DataOut<dim>::build_some_patches (Data data)\n{\n QTrapez<1> q_trapez;\n QIterated<dim> patch_points (q_trapez, data.n_subdivisions);\n \n FEValues<dim> fe_patch_values(dofs->get_fe(),\n\t\t\t\tpatch_points,\n\t\t\t\tupdate_default);\n\n const unsigned int n_q_points = patch_points.n_quadrature_points;\n \n unsigned int cell_number = 0;\n vector<DataOutBase::Patch<dim> >::iterator patch = patches.begin();\n DoFHandler<dim>::cell_iterator cell=first_cell();\n\n\t\t\t\t \/\/ get first cell in this thread\n for (unsigned int i=0;i<data.this_thread;++i,++patch,++cell_number,\n\t\t cell=next_cell(cell));\n \n \t\t\t\t \/\/ now loop over all cells and\n\t\t\t\t \/\/ actually create the patches\n for (;cell != dofs->end();)\n {\n Assert (patch != patches.end(), ExcInternalError());\n \n for (unsigned int vertex=0; vertex<GeometryInfo<dim>::vertices_per_cell; ++vertex)\n\tpatch->vertices[vertex] = cell->vertex(vertex);\n \n if (data.n_datasets > 0)\n\t{\n\t fe_patch_values.reinit (cell);\n\t \n\t\t\t\t\t \/\/ first fill dof_data\n\t for (unsigned int dataset=0; dataset<dof_data.size(); ++dataset)\n\t {\n\t if (data.n_components == 1)\n\t\t{\n\t\t fe_patch_values.get_function_values (*dof_data[dataset].data,\n\t\t\t\t\t\t data.patch_values);\n\t\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\t patch->data(dataset,q) = data.patch_values[q];\n\t\t}\n\t else\n\t\t\t\t\t\t \/\/ system of components\n\t\t{\n\t\t fe_patch_values.get_function_values (*dof_data[dataset].data,\n\t\t\t\t\t\t data.patch_values_system);\n\t\t for (unsigned int component=0; component<data.n_components;\n\t\t ++component)\n\t\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\t patch->data(dataset*data.n_components+component,q) =\n\t\t\tdata.patch_values_system[q](component);\n\t\t};\n\t };\n\n\t\t\t\t\t \/\/ then do the cell data\n\t for (unsigned int dataset=0; dataset<cell_data.size(); ++dataset)\n\t {\n\t const double value = (*cell_data[dataset].data)(cell_number);\n\t for (unsigned int q=0; q<n_q_points; ++q)\n\t\tpatch->data(dataset+dof_data.size()*data.n_components,q) =\n\t\t value;\n\t };\n\t};\n \t\t\t\t \/\/ next cell (patch) in this thread\n for (unsigned int i=0;((i<data.n_threads)&&(cell != dofs->end()));\n\t ++i,++patch,++cell_number,cell=next_cell(cell));\n \n };\n}\n\n\ntemplate <int dim>\nvoid DataOut<dim>::build_patches (const unsigned int n_subdivisions,\n\t\t\t\t const unsigned int n_threads_) \n{\n Assert (dofs != 0, ExcNoDoFHandlerSelected());\n\n#ifdef DEAL_II_USE_MT\n const unsigned int n_threads = n_threads_;\n#else\n\t\t\t\t \/\/ access this variable to avoid\n\t\t\t\t \/\/ compiler warning about unused\n\t\t\t\t \/\/ var:\n (void)n_threads_;\n const unsigned int n_threads = 1;\n#endif\n\n\n\/\/ before we start the loop:\n\t\t\t\t \/\/ create a quadrature rule that\n\t\t\t\t \/\/ actually has the points on this\n\t\t\t\t \/\/ patch\n QTrapez<1> q_trapez;\n QIterated<dim> patch_points (q_trapez, n_subdivisions);\n\n const unsigned int n_q_points = patch_points.n_quadrature_points;\n const unsigned int n_components = dofs->get_fe().n_components();\n const unsigned int n_datasets = dof_data.size() * n_components +\n\t\t\t\t cell_data.size();\n \n\t\t\t\t \/\/ clear the patches array\n if (true)\n {\n vector<DataOutBase::Patch<dim> > dummy;\n patches.swap (dummy);\n };\n \n\t\t\t\t \/\/ first count the cells we want to\n\t\t\t\t \/\/ create patches of and make sure\n\t\t\t\t \/\/ there is enough memory for that\n unsigned int n_patches = 0;\n for (DoFHandler<dim>::cell_iterator cell=first_cell();\n cell != dofs->end();\n cell = next_cell(cell))\n ++n_patches;\n\n vector<Data> thread_data(n_threads);\n\n\t\t\t\t \/\/ init data for the threads\n for (unsigned int i=0;i<n_threads;++i)\n {\n thread_data[i].n_threads = n_threads;\n thread_data[i].this_thread = i;\n thread_data[i].n_components = n_components;\n thread_data[i].n_datasets = n_datasets;\n thread_data[i].n_subdivisions = n_subdivisions;\n thread_data[i].patch_values.resize (n_q_points);\n thread_data[i].patch_values_system.resize (n_q_points);\n \n for (unsigned int k=0; k<n_q_points; ++k)\n\tthread_data[i].patch_values_system[k].reinit(n_components);\n }\n\n\t\t\t\t \/\/ create the patches with\n\t\t\t\t \/\/ default values\n DataOutBase::Patch<dim> default_patch;\n default_patch.n_subdivisions = n_subdivisions;\n default_patch.data.reinit (n_datasets, n_q_points);\n patches.insert (patches.end(), n_patches, default_patch);\n\n#ifdef DEAL_II_USE_MT\n\n ThreadManager thread_manager;\n \n typedef ThreadManager::Mem_Fun_Data1\n <DataOut<dim>, Data> MemFunData;\n \n\t\t\t\t \/\/ One struct of this type for every thread\n vector<MemFunData> mem_fun_data (n_threads,\n\t\t\t\t MemFunData (this,\n\t\t\t\t\t thread_data[0],\n\t\t\t\t\t &DataOut<dim>::build_some_patches));\n \n\t\t\t\t \/\/ get start cells for each thread\n for (unsigned int l=0;l<n_threads;++l)\n {\n mem_fun_data[l].arg=thread_data[l];\n thread_manager.spawn(&mem_fun_data[l],THR_SCOPE_SYSTEM | THR_DETACHED);\n };\n\t\t\t\t \/\/ wait for all threads to return\n thread_manager.wait();\n \n\t\t\t\t \/\/ just one thread\n#else\n build_some_patches(thread_data[0]);\n#endif\n};\n\n\ntemplate <int dim>\ntypename DoFHandler<dim>::cell_iterator\nDataOut<dim>::first_cell () \n{\n return dofs->begin_active ();\n};\n\n\ntemplate <int dim>\ntypename DoFHandler<dim>::cell_iterator\nDataOut<dim>::next_cell (const typename DoFHandler<dim>::cell_iterator &cell) \n{\n\t\t\t\t \/\/ convert the iterator to an\n\t\t\t\t \/\/ active_iterator and advance\n\t\t\t\t \/\/ this to the next active cell\n typename DoFHandler<dim>::active_cell_iterator active_cell = cell;\n ++active_cell;\n return active_cell;\n};\n\n\n\/\/ explicit instantiations\ntemplate class DataOut_DoFData<deal_II_dimension>;\ntemplate class DataOut<deal_II_dimension>;\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n Stepper.cpp - - Stepper library for Wiring\/Arduino - Version 0.6\n\n Original library (0.1) by Tom Igoe.\n Two-wire modifications (0.2) by Sebastian Gassner\n Combination version (0.3) by Tom Igoe and David Mellis\n Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley\n Wave step mode for 4 wire systems (0.5) by Geoff Day\n Sleep mode for 4 wire systems (0.6) by Geoff Day\n \n Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires\n When wiring multiple stepper motors to a microcontroller,\n you quickly run out of output pins, with each motor requiring 4 connections.\n By making use of the fact that at any time two of the four motor\n coils are the inverse of the other two, the number of\n control connections can be reduced from 4 to 2.\n A slightly modified circuit around a Darlington transistor array or an L293 H-bridge\n connects to only 2 microcontroler pins, inverts the signals received,\n and delivers the 4 (2 plus 2 inverted ones) output signals required\n for driving a stepper motor.\n The sequence of control signals for 4 control wires is as follows:\n Step C0 C1 C2 C3\n 1 1 0 1 0\n 2 0 1 1 0\n 3 0 1 0 1\n 4 1 0 0 1\n The sequence of controls signals for 2 control wires is as follows\n (columns C1 and C2 from above):\n Step C0 C1\n 1 0 1\n 2 1 1\n 3 1 0\n 4 0 0\n The circuits can be found at\n http:\/\/www.arduino.cc\/en\/Tutorial\/Stepper\n \n The Wave step sequence of control signals for 4 control wires is as follows:\n Step C0 C1 C2 C3\n 1 1 0 0 0\n 2 0 0 1 0\n 3 0 1 0 0\n 4 0 0 0 1\n \n Good for lower power operation where lower torque is ok. \n sleep mode when high sends all outputs low. No holding torque! \n *\/\n\n#include \"application.h\"\n#include \"Stepper.h\"\n\n\/*\n * two-wire constructor.\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in ms of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n\n \/\/ When there are only 2 pins, set the other two to 0:\n this->motor_pin_3 = 0;\n this->motor_pin_4 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 2;\n}\n\n\n\/*\n * constructor for four-pin version\n * Sets which wires should control the motor.\n *\/\n\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)\n{\n this->sleep = 0; \/\/ default to 0 - no sleeping. 1 to sleep. All output drives to zero so no holding torque!\n this->mode = 0; \/\/ full step mode = 0\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in ms of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 4;\n}\n\n\/* \n set to sleep mode for lower power consumption. Only valid in 4 wire mode.\n Remember there's no holding torque!!!\n*\/\n\n void Stepper::setSleep(int sleep)\n {\n this->sleep = sleep;\n \n if (this->sleep == 1) {\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, LOW);\n } else {\n stepMotor(this->step_number % 4);\n }\n }\n \n\n\n\/* \n set stepper mode, full or wave currently. Wave mode for low power applications.\n only applicable in 4 wire setups.\n*\/\n\n void Stepper::setMode(int mode)\n {\n this->mode = mode;\n }\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative,\n the motor moves in the reverse direction.\n *\/\nvoid Stepper::step(int steps_to_move)\n{\n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n\n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n\n\n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n this->step_number++;\n if (this->step_number == this->number_of_steps) {\n this->step_number = 0;\n }\n }\n else {\n if (this->step_number == 0) {\n this->step_number = this->number_of_steps;\n }\n this->step_number--;\n }\n \/\/ decrement the steps left:\n steps_left--;\n \/\/ step the motor to step number 0, 1, 2, or 3:\n stepMotor(this->step_number % 4);\n }\n }\n}\n\n\/*\n * Moves the motor forward or backwards.\n *\/\nvoid Stepper::stepMotor(int thisStep)\n{\n if (this->pin_count == 2) {\n switch (thisStep) {\n case 0: \/* 01 *\/\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 1: \/* 11 *\/\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 2: \/* 10 *\/\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n break;\n case 3: \/* 00 *\/\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n break;\n }\n }\n if (this->pin_count == 4) {\n switch (thisStep) {\n case 0: \/\/ 1010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_3, LOW);\n } else {\n digitalWrite(motor_pin_3, HIGH);\n }\n digitalWrite(motor_pin_4, LOW);\n break;\n case 1: \/\/ 0110\n digitalWrite(motor_pin_1, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_2, LOW);\n } else {\n digitalWrite(motor_pin_2, HIGH);\n }\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 2: \/\/0101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_4, LOW);\n } else {\n digitalWrite(motor_pin_4, HIGH);\n }\n break;\n case 3: \/\/1001\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_1, LOW);\n } else {\n digitalWrite(motor_pin_1, HIGH);\n }\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint Stepper::version(void)\n{\n return 6;\n}\n<commit_msg>Update Stepper.cpp<commit_after>\n\/*\n Stepper.cpp - - Stepper library for Wiring\/Arduino - Version 0.6\n\n Original library (0.1) by Tom Igoe.\n Two-wire modifications (0.2) by Sebastian Gassner\n Combination version (0.3) by Tom Igoe and David Mellis\n Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley\n Wave step mode for 4 wire systems (0.5) by Geoff Day\n Sleep mode for 4 wire systems (0.6) by Geoff Day\n \n Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires\n When wiring multiple stepper motors to a microcontroller,\n you quickly run out of output pins, with each motor requiring 4 connections.\n By making use of the fact that at any time two of the four motor\n coils are the inverse of the other two, the number of\n control connections can be reduced from 4 to 2.\n A slightly modified circuit around a Darlington transistor array or an L293 H-bridge\n connects to only 2 microcontroler pins, inverts the signals received,\n and delivers the 4 (2 plus 2 inverted ones) output signals required\n for driving a stepper motor.\n The sequence of control signals for 4 control wires is as follows:\n Step C0 C1 C2 C3\n 1 1 0 1 0\n 2 0 1 1 0\n 3 0 1 0 1\n 4 1 0 0 1\n The sequence of controls signals for 2 control wires is as follows\n (columns C1 and C2 from above):\n Step C0 C1\n 1 0 1\n 2 1 1\n 3 1 0\n 4 0 0\n The circuits can be found at\n http:\/\/www.arduino.cc\/en\/Tutorial\/Stepper\n \n The Wave step sequence of control signals for 4 control wires is as follows:\n Step C0 C1 C2 C3\n 1 1 0 0 0\n 2 0 0 1 0\n 3 0 1 0 0\n 4 0 0 0 1\n \n Good for lower power operation where lower torque is ok. \n sleep mode when high sends all outputs low. No holding torque! \n *\/\n\n#include \"application.h\"\n#include \"Stepper.h\"\n\n\/*\n * two-wire constructor.\n * Sets which wires should control the motor.\n *\/\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2)\n{\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in ms of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n\n \/\/ When there are only 2 pins, set the other two to 0:\n this->motor_pin_3 = 0;\n this->motor_pin_4 = 0;\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 2;\n}\n\n\n\/*\n * constructor for four-pin version\n * Sets which wires should control the motor.\n *\/\n\nStepper::Stepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)\n{\n this->sleep = 0; \/\/ default to 0 - no sleeping. 1 to sleep. All output drives to zero so no holding torque!\n this->mode = 0; \/\/ full step mode = 0\n this->step_number = 0; \/\/ which step the motor is on\n this->speed = 0; \/\/ the motor speed, in revolutions per minute\n this->direction = 0; \/\/ motor direction\n this->last_step_time = 0; \/\/ time stamp in ms of the last step taken\n this->number_of_steps = number_of_steps; \/\/ total number of steps for this motor\n\n \/\/ Arduino pins for the motor control connection:\n this->motor_pin_1 = motor_pin_1;\n this->motor_pin_2 = motor_pin_2;\n this->motor_pin_3 = motor_pin_3;\n this->motor_pin_4 = motor_pin_4;\n\n \/\/ setup the pins on the microcontroller:\n pinMode(this->motor_pin_1, OUTPUT);\n pinMode(this->motor_pin_2, OUTPUT);\n pinMode(this->motor_pin_3, OUTPUT);\n pinMode(this->motor_pin_4, OUTPUT);\n\n \/\/ pin_count is used by the stepMotor() method:\n this->pin_count = 4;\n}\n\n\/* \n set to sleep mode for lower power consumption. Only valid in 4 wire mode.\n Remember there's no holding torque!!!\n*\/\n\n void Stepper::setSleep(int sleep)\n {\n this->sleep = sleep;\n \n if (this->sleep == 1) {\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, LOW);\n } else {\n stepMotor(this->step_number % 4);\n }\n }\n \n\n\n\/* \n set stepper mode, full or wave currently. Wave mode for low power applications.\n only applicable in 4 wire setups.\n*\/\n\n void Stepper::setMode(int mode)\n {\n this->mode = mode;\n }\n\n\/*\n Sets the speed in revs per minute\n\n*\/\nvoid Stepper::setSpeed(long whatSpeed)\n{\n this->step_delay = 60L * 1000L \/ this->number_of_steps \/ whatSpeed;\n}\n\n\/*\n Moves the motor steps_to_move steps. If the number is negative,\n the motor moves in the reverse direction.\n *\/\nvoid Stepper::step(int steps_to_move)\n{\n int steps_left = abs(steps_to_move); \/\/ how many steps to take\n\n \/\/ determine direction based on whether steps_to_mode is + or -:\n if (steps_to_move > 0) {this->direction = 1;}\n if (steps_to_move < 0) {this->direction = 0;}\n\n\n \/\/ decrement the number of steps, moving one step each time:\n while(steps_left > 0) {\n \/\/ move only if the appropriate delay has passed:\n if (millis() - this->last_step_time >= this->step_delay) {\n \/\/ get the timeStamp of when you stepped:\n this->last_step_time = millis();\n \/\/ increment or decrement the step number,\n \/\/ depending on direction:\n if (this->direction == 1) {\n this->step_number++;\n if (this->step_number == this->number_of_steps) {\n this->step_number = 0;\n }\n }\n else {\n if (this->step_number == 0) {\n this->step_number = this->number_of_steps;\n }\n this->step_number--;\n }\n \/\/ decrement the steps left:\n steps_left--;\n \/\/ step the motor to step number 0, 1, 2, or 3:\n stepMotor(this->step_number % 4);\n }\n }\n}\n\n\/*\n * Moves the motor forward or backwards.\n *\/\nvoid Stepper::stepMotor(int thisStep)\n{\n if (this->pin_count == 2) {\n switch (thisStep) {\n case 0: \/* 01 *\/\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 1: \/* 11 *\/\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, HIGH);\n break;\n case 2: \/* 10 *\/\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n break;\n case 3: \/* 00 *\/\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, LOW);\n break;\n }\n }\n if (this->pin_count == 4) {\n switch (thisStep) {\n case 0: \/\/ 1010\n digitalWrite(motor_pin_1, HIGH);\n digitalWrite(motor_pin_2, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_3, LOW);\n } else {\n digitalWrite(motor_pin_3, HIGH);\n }\n digitalWrite(motor_pin_4, LOW);\n break;\n case 1: \/\/ 0110\n digitalWrite(motor_pin_1, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_2, LOW);\n } else {\n digitalWrite(motor_pin_2, HIGH);\n }\n digitalWrite(motor_pin_3, HIGH);\n digitalWrite(motor_pin_4, LOW);\n break;\n case 2: \/\/0101\n digitalWrite(motor_pin_1, LOW);\n digitalWrite(motor_pin_2, HIGH);\n digitalWrite(motor_pin_3, LOW);\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_4, LOW);\n } else {\n digitalWrite(motor_pin_4, HIGH);\n }\n break;\n case 3: \/\/1001\n \/\/ mode high for wave step\n if (this->mode) { \n digitalWrite(motor_pin_1, LOW);\n } else {\n digitalWrite(motor_pin_1, HIGH);\n }\n digitalWrite(motor_pin_2, LOW);\n digitalWrite(motor_pin_3, LOW);\n digitalWrite(motor_pin_4, HIGH);\n break;\n }\n }\n}\n\n\/*\n version() returns the version of the library:\n*\/\nint Stepper::version(void)\n{\n return 7;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qwmpmetadata.h\"\n\n#include \"qwmpevents.h\"\n#include \"qwmpglobal.h\"\n\n#include <multimedia\/qmediacontent.h>\n\n#include <QtCore\/qdatetime.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qfileinfo.h>\n#include <QtCore\/qsize.h>\n#include <QtCore\/qstringlist.h>\n#include <QtCore\/qurl.h>\n#include <QtCore\/qvariant.h>\n\n\nstruct QWmpMetaDataKeyLookup\n{\n QtMedia::MetaData key;\n const wchar_t *token;\n};\n\nstatic const QWmpMetaDataKeyLookup qt_wmpMetaDataKeys[] =\n{\n { QtMedia::Title, L\"Title\" },\n { QtMedia::SubTitle, L\"WM\/SubTitle\" },\n { QtMedia::Author, L\"Author\" },\n { QtMedia::Comment, L\"Comment\" },\n { QtMedia::Description, L\"Description\" },\n { QtMedia::Category, L\"WM\/Category\" },\n { QtMedia::Genre, L\"WM\/Genre\" },\n \/\/{ QtMedia::Date, 0 },\n { QtMedia::Year, L\"WM\/Year\" },\n { QtMedia::UserRating, L\"UserRating\" },\n \/\/{ QtMedia::MetaDatawords, 0 },\n { QtMedia::Language, L\"Language\" },\n { QtMedia::Publisher, L\"WM\/Publisher\" },\n { QtMedia::Copyright, L\"Copyright\" },\n { QtMedia::ParentalRating, L\"ParentalRating\" },\n { QtMedia::RatingOrganisation, L\"RatingOrganisation\" },\n\n \/\/ Media\n { QtMedia::Size, L\"FileSize\" },\n { QtMedia::MediaType, L\"MediaType\" },\n { QtMedia::Duration, L\"Duration\" },\n\n \/\/ Audio\n { QtMedia::AudioBitrate, L\"AudioBitrate\" },\n { QtMedia::AudioCodec, L\"AudioCodec\" },\n { QtMedia::Channels, L\"Channels\" },\n { QtMedia::Frequency, L\"Frequency\" },\n\n \/\/ Music\n { QtMedia::AlbumTitle, L\"WM\/AlbumTitle\" },\n { QtMedia::AlbumArtist, L\"WM\/AlbumArtist\" },\n { QtMedia::ContributingArtist, L\"Author\" },\n { QtMedia::Composer, L\"WM\/Composer\" },\n { QtMedia::Conductor, L\"WM\/Conductor\" },\n { QtMedia::Lyrics, L\"WM\/Lyrics\" },\n { QtMedia::Mood, L\"WM\/Mood\" },\n { QtMedia::TrackNumber, L\"WM\/TrackNumber\" },\n \/\/{ QtMedia::TrackCount, 0 },\n \/\/{ QtMedia::CoverArtUriSmall, 0 },\n \/\/{ QtMedia::CoverArtUriLarge, 0 },\n\n \/\/ Image\/Video\n \/\/{ QtMedia::Resolution, 0 },\n \/\/{ QtMedia::PixelAspectRatio, 0 },\n\n \/\/ Video\n \/\/{ QtMedia::FrameRate, 0 },\n { QtMedia::VideoBitRate, L\"VideoBitRate\" },\n { QtMedia::VideoCodec, L\"VideoCodec\" },\n\n \/\/{ QtMedia::PosterUri, 0 },\n\n \/\/ Movie\n { QtMedia::ChapterNumber, L\"ChapterNumber\" },\n { QtMedia::Director, L\"WM\/Director\" },\n { QtMedia::LeadPerformer, L\"LeadPerformer\" },\n { QtMedia::Writer, L\"WM\/Writer\" },\n\n \/\/ Photos\n { QtMedia::CameraManufacturer, L\"CameraManufacturer\" },\n { QtMedia::CameraModel, L\"CameraModel\" },\n { QtMedia::Event, L\"Event\" },\n { QtMedia::Subject, L\"Subject\" }\n};\n\nQWmpMetaData::QWmpMetaData(IWMPCore3 *player, QWmpEvents *events, QObject *parent)\n : QMetaDataControl(parent)\n , m_media(0)\n{\n player->get_currentMedia(&m_media);\n\n connect(events, SIGNAL(CurrentItemChange(IDispatch*)),\n this, SLOT(currentItemChangeEvent(IDispatch*)));\n connect(events, SIGNAL(MediaChange(IDispatch*)), this, SLOT(mediaChangeEvent(IDispatch*)));\n}\n\nQWmpMetaData::~QWmpMetaData()\n{\n if (m_media)\n m_media->Release();\n}\n\nbool QWmpMetaData::isMetaDataAvailable() const\n{\n return m_media != 0;\n}\n\nbool QWmpMetaData::isWritable() const\n{\n return m_media != 0;\n}\n\nQVariant QWmpMetaData::metaData(QtMedia::MetaData key) const\n{\n static const int count = sizeof(qt_wmpMetaDataKeys) \/ sizeof(QWmpMetaDataKeyLookup);\n\n switch (key) {\n case QtMedia::Date:\n {\n QVariant day = value(m_media, QAutoBStr(L\"ReleaseDateDay\"));\n QVariant month = value(m_media, QAutoBStr(L\"ReleaseDateMonth\"));\n QVariant year = value(m_media, QAutoBStr(L\"ReleaseDateYear\"));\n\n if (!day.isNull() && !month.isNull() && !year.isNull())\n return QDate(year.toInt(), month.toInt(), day.toInt());\n }\n break;\n case QtMedia::CoverArtUriSmall:\n return albumArtUri(m_media, \"_Small.jpg\");\n case QtMedia::CoverArtUriLarge:\n return albumArtUri(m_media, \"_Large.jpg\");\n case QtMedia::Resolution:\n {\n QVariant width = value(m_media, QAutoBStr(L\"WM\/VideoWidth\"));\n QVariant height = value(m_media, QAutoBStr(L\"WM\/VideoHeight\"));\n\n if (!width.isNull() && !height.isNull())\n return QSize(width.toInt(), height.toInt());\n }\n break;\n case QtMedia::PixelAspectRatio:\n {\n QVariant x = value(m_media, QAutoBStr(L\"PixelAspectRatioX\"));\n QVariant y = value(m_media, QAutoBStr(L\"PixelAspectRatioY\"));\n\n if (!x.isNull() && !y.isNull())\n return QSize(x.toInt(), y.toInt());\n }\n break;\n case QtMedia::FrameRate:\n break;\n default:\n for (int i = 0; i < count; ++i) {\n if (qt_wmpMetaDataKeys[i].key == key)\n return value(m_media, QAutoBStr(qt_wmpMetaDataKeys[i].token));\n }\n break;\n }\n return QVariant();\n}\n\nvoid QWmpMetaData::setMetaData(QtMedia::MetaData key, const QVariant &value)\n{\n static const int count = sizeof(qt_wmpMetaDataKeys) \/ sizeof(QWmpMetaDataKeyLookup);\n\n for (int i = 0; i < count; ++i) {\n if (qt_wmpMetaDataKeys[i].key == key) {\n setValue(m_media, QAutoBStr(qt_wmpMetaDataKeys[i].token), value);\n return;\n }\n }\n}\n\nQVariant QWmpMetaData::extendedMetaData(const QString &key) const\n{\n return value(m_media, QAutoBStr(key));\n}\n\nvoid QWmpMetaData::setExtendedMetaData(const QString &key, const QVariant &value)\n{\n setValue(m_media, QAutoBStr(key), value);\n}\n\nvoid QWmpMetaData::currentItemChangeEvent(IDispatch *dispatch)\n{\n IWMPMedia *media = m_media;\n\n m_media = 0;\n if (dispatch)\n dispatch->QueryInterface(__uuidof(IWMPMedia), reinterpret_cast<void **>(&m_media));\n\n if (media) {\n if (m_media)\n emit metaDataChanged();\n else\n emit metaDataAvailableChanged(false);\n\n media->Release();\n } else {\n if (m_media)\n emit metaDataAvailableChanged(false);\n }\n}\n\nvoid QWmpMetaData::mediaChangeEvent(IDispatch *dispatch)\n{\n IWMPMedia *media = 0;\n if (dispatch && dispatch->QueryInterface(\n __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) {\n VARIANT_BOOL isEqual = VARIANT_FALSE;\n if (media->get_isIdentical(m_media, &isEqual) == S_OK && isEqual)\n emit metaDataChanged();\n media->Release();\n }\n}\n\n\nQStringList QWmpMetaData::keys(IWMPMedia *media)\n{\n QStringList keys;\n\n long count = 0;\n if (media && media->get_attributeCount(&count) == S_OK) {\n for (long i = 0; i < count; ++i) {\n BSTR string;\n if (media->getAttributeName(i, &string) == S_OK) {\n keys.append(QString::fromWCharArray(string, ::SysStringLen(string)));\n\n ::SysFreeString(string);\n }\n }\n }\n return keys;\n}\n\nQVariant QWmpMetaData::value(IWMPMedia *media, BSTR key)\n{\n QVariantList values;\n IWMPMedia3 *media3 = 0;\n if (media && media->QueryInterface(\n __uuidof(IWMPMedia3), reinterpret_cast<void **>(&media3)) == S_OK) {\n long count = 0;\n media3->getAttributeCountByType(key, 0, &count);\n\n \/\/ The count appears to only be valid for static properties, dynamic properties like\n \/\/ PlaylistIndex will have a count of zero but return a value for index 0.\n if (count == 0)\n count = 1;\n\n for (long i = 0; i < count; ++i) {\n VARIANT var;\n VariantInit(&var);\n\n if (media3->getItemInfoByType(key, 0, i, &var) == S_OK) {\n QVariant value = convertVariant(var);\n\n if (!value.isNull())\n values.append(value);\n\n VariantClear(&var);\n }\n }\n media3->Release();\n }\n\n switch (values.count()) {\n case 0:\n return QVariant();\n case 1:\n return values.first();\n default:\n return values;\n }\n}\n\nvoid QWmpMetaData::setValue(IWMPMedia *media, BSTR key, const QVariant &value)\n{\n if (qVariantCanConvert<QString>(value))\n media->setItemInfo(key, QAutoBStr(value.toString()));\n}\n\nQMediaContent QWmpMetaData::resources(IWMPMedia *media)\n{\n QMediaContent content;\n\n BSTR string = 0;\n if (media->get_sourceURL(&string) == S_OK) {\n QString uri = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n content = QMediaContent(QUrl(uri));\n\n if (media->getItemInfo(QAutoBStr(L\"WM\/WMCollectionGroupID\"), &string) == S_OK) {\n QString uuid = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n QString albumArtLarge = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(\"_Large.jpg\");\n QString albumArtSmall = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(\"_Small.jpg\");\n\n QDir dir = QFileInfo(uri).absoluteDir();\n\n if (dir.exists(albumArtLarge))\n content.setCoverArtUriLarge(QUrl(dir.absoluteFilePath(albumArtLarge)));\n\n if (dir.exists(albumArtSmall))\n content.setCoverArtUriSmall(QUrl(dir.absoluteFilePath(albumArtSmall)));\n }\n }\n\n return content;\n}\n\nQVariant QWmpMetaData::convertVariant(const VARIANT &variant)\n{\n switch (variant.vt) {\n case VT_I2:\n return variant.iVal;\n case VT_I4:\n return variant.lVal;\n case VT_I8:\n return variant.llVal;\n case VT_UI2:\n return variant.uiVal;\n case VT_UI4:\n return quint32(variant.ulVal);\n case VT_UI8:\n return variant.ullVal;\n case VT_INT:\n return variant.intVal;\n case VT_UINT:\n return variant.uintVal;\n case VT_BSTR:\n return QString::fromWCharArray(variant.bstrVal, ::SysStringLen(variant.bstrVal));\n case VT_DISPATCH:\n {\n IWMPMetadataPicture *picture = 0;\n IWMPMetadataText *text = 0;\n\n if (variant.pdispVal->QueryInterface(\n __uuidof(IWMPMetadataPicture), reinterpret_cast<void **>(&picture)) == S_OK) {\n QUrl uri;\n BSTR string;\n if (picture->get_URL(&string) == S_OK) {\n uri = QUrl(QString::fromWCharArray(string, ::SysStringLen(string)));\n\n ::SysFreeString(string);\n }\n picture->Release();\n return qVariantFromValue(uri);\n } else if (variant.pdispVal->QueryInterface(\n __uuidof(IWMPMetadataText), reinterpret_cast<void **>(&text)) == S_OK) {\n QString description;\n BSTR string;\n if (text->get_description(&string) == S_OK) {\n description = QString::fromWCharArray(string, SysStringLen(string));\n\n ::SysFreeString(string);\n }\n text->Release();\n return description;\n } else {\n qWarning(\"Unknown dispatch type\");\n }\n }\n break;\n default:\n qWarning(\"Unsupported Type %d %x\", variant.vt, variant.vt);\n break;\n }\n\n return QVariant();\n}\n\nQVariant QWmpMetaData::albumArtUri(IWMPMedia *media, const char *suffix)\n{\n BSTR string = 0;\n if (media && media->get_sourceURL(&string) == S_OK) {\n QString uri = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n if (media->getItemInfo(QAutoBStr(L\"WM\/WMCollectionGroupID\"), &string) == S_OK) {\n QString uuid = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n QString fileName = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(suffix);\n\n QDir dir = QFileInfo(uri).absoluteDir();\n\n if (dir.exists(fileName)) {\n return qVariantFromValue(\n QUrl(QLatin1String(\"file:\/\/\/\") + dir.absoluteFilePath(fileName)));\n }\n }\n }\n return QVariant();\n}\n<commit_msg>wmp; FrameRate -> VideoFrameRate.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qwmpmetadata.h\"\n\n#include \"qwmpevents.h\"\n#include \"qwmpglobal.h\"\n\n#include <multimedia\/qmediacontent.h>\n\n#include <QtCore\/qdatetime.h>\n#include <QtCore\/qdir.h>\n#include <QtCore\/qfileinfo.h>\n#include <QtCore\/qsize.h>\n#include <QtCore\/qstringlist.h>\n#include <QtCore\/qurl.h>\n#include <QtCore\/qvariant.h>\n\n\nstruct QWmpMetaDataKeyLookup\n{\n QtMedia::MetaData key;\n const wchar_t *token;\n};\n\nstatic const QWmpMetaDataKeyLookup qt_wmpMetaDataKeys[] =\n{\n { QtMedia::Title, L\"Title\" },\n { QtMedia::SubTitle, L\"WM\/SubTitle\" },\n { QtMedia::Author, L\"Author\" },\n { QtMedia::Comment, L\"Comment\" },\n { QtMedia::Description, L\"Description\" },\n { QtMedia::Category, L\"WM\/Category\" },\n { QtMedia::Genre, L\"WM\/Genre\" },\n \/\/{ QtMedia::Date, 0 },\n { QtMedia::Year, L\"WM\/Year\" },\n { QtMedia::UserRating, L\"UserRating\" },\n \/\/{ QtMedia::MetaDatawords, 0 },\n { QtMedia::Language, L\"Language\" },\n { QtMedia::Publisher, L\"WM\/Publisher\" },\n { QtMedia::Copyright, L\"Copyright\" },\n { QtMedia::ParentalRating, L\"ParentalRating\" },\n { QtMedia::RatingOrganisation, L\"RatingOrganisation\" },\n\n \/\/ Media\n { QtMedia::Size, L\"FileSize\" },\n { QtMedia::MediaType, L\"MediaType\" },\n { QtMedia::Duration, L\"Duration\" },\n\n \/\/ Audio\n { QtMedia::AudioBitrate, L\"AudioBitrate\" },\n { QtMedia::AudioCodec, L\"AudioCodec\" },\n { QtMedia::Channels, L\"Channels\" },\n { QtMedia::Frequency, L\"Frequency\" },\n\n \/\/ Music\n { QtMedia::AlbumTitle, L\"WM\/AlbumTitle\" },\n { QtMedia::AlbumArtist, L\"WM\/AlbumArtist\" },\n { QtMedia::ContributingArtist, L\"Author\" },\n { QtMedia::Composer, L\"WM\/Composer\" },\n { QtMedia::Conductor, L\"WM\/Conductor\" },\n { QtMedia::Lyrics, L\"WM\/Lyrics\" },\n { QtMedia::Mood, L\"WM\/Mood\" },\n { QtMedia::TrackNumber, L\"WM\/TrackNumber\" },\n \/\/{ QtMedia::TrackCount, 0 },\n \/\/{ QtMedia::CoverArtUriSmall, 0 },\n \/\/{ QtMedia::CoverArtUriLarge, 0 },\n\n \/\/ Image\/Video\n \/\/{ QtMedia::Resolution, 0 },\n \/\/{ QtMedia::PixelAspectRatio, 0 },\n\n \/\/ Video\n \/\/{ QtMedia::FrameRate, 0 },\n { QtMedia::VideoBitRate, L\"VideoBitRate\" },\n { QtMedia::VideoCodec, L\"VideoCodec\" },\n\n \/\/{ QtMedia::PosterUri, 0 },\n\n \/\/ Movie\n { QtMedia::ChapterNumber, L\"ChapterNumber\" },\n { QtMedia::Director, L\"WM\/Director\" },\n { QtMedia::LeadPerformer, L\"LeadPerformer\" },\n { QtMedia::Writer, L\"WM\/Writer\" },\n\n \/\/ Photos\n { QtMedia::CameraManufacturer, L\"CameraManufacturer\" },\n { QtMedia::CameraModel, L\"CameraModel\" },\n { QtMedia::Event, L\"Event\" },\n { QtMedia::Subject, L\"Subject\" }\n};\n\nQWmpMetaData::QWmpMetaData(IWMPCore3 *player, QWmpEvents *events, QObject *parent)\n : QMetaDataControl(parent)\n , m_media(0)\n{\n player->get_currentMedia(&m_media);\n\n connect(events, SIGNAL(CurrentItemChange(IDispatch*)),\n this, SLOT(currentItemChangeEvent(IDispatch*)));\n connect(events, SIGNAL(MediaChange(IDispatch*)), this, SLOT(mediaChangeEvent(IDispatch*)));\n}\n\nQWmpMetaData::~QWmpMetaData()\n{\n if (m_media)\n m_media->Release();\n}\n\nbool QWmpMetaData::isMetaDataAvailable() const\n{\n return m_media != 0;\n}\n\nbool QWmpMetaData::isWritable() const\n{\n return m_media != 0;\n}\n\nQVariant QWmpMetaData::metaData(QtMedia::MetaData key) const\n{\n static const int count = sizeof(qt_wmpMetaDataKeys) \/ sizeof(QWmpMetaDataKeyLookup);\n\n switch (key) {\n case QtMedia::Date:\n {\n QVariant day = value(m_media, QAutoBStr(L\"ReleaseDateDay\"));\n QVariant month = value(m_media, QAutoBStr(L\"ReleaseDateMonth\"));\n QVariant year = value(m_media, QAutoBStr(L\"ReleaseDateYear\"));\n\n if (!day.isNull() && !month.isNull() && !year.isNull())\n return QDate(year.toInt(), month.toInt(), day.toInt());\n }\n break;\n case QtMedia::CoverArtUriSmall:\n return albumArtUri(m_media, \"_Small.jpg\");\n case QtMedia::CoverArtUriLarge:\n return albumArtUri(m_media, \"_Large.jpg\");\n case QtMedia::Resolution:\n {\n QVariant width = value(m_media, QAutoBStr(L\"WM\/VideoWidth\"));\n QVariant height = value(m_media, QAutoBStr(L\"WM\/VideoHeight\"));\n\n if (!width.isNull() && !height.isNull())\n return QSize(width.toInt(), height.toInt());\n }\n break;\n case QtMedia::PixelAspectRatio:\n {\n QVariant x = value(m_media, QAutoBStr(L\"PixelAspectRatioX\"));\n QVariant y = value(m_media, QAutoBStr(L\"PixelAspectRatioY\"));\n\n if (!x.isNull() && !y.isNull())\n return QSize(x.toInt(), y.toInt());\n }\n break;\n case QtMedia::VideoFrameRate:\n break;\n default:\n for (int i = 0; i < count; ++i) {\n if (qt_wmpMetaDataKeys[i].key == key)\n return value(m_media, QAutoBStr(qt_wmpMetaDataKeys[i].token));\n }\n break;\n }\n return QVariant();\n}\n\nvoid QWmpMetaData::setMetaData(QtMedia::MetaData key, const QVariant &value)\n{\n static const int count = sizeof(qt_wmpMetaDataKeys) \/ sizeof(QWmpMetaDataKeyLookup);\n\n for (int i = 0; i < count; ++i) {\n if (qt_wmpMetaDataKeys[i].key == key) {\n setValue(m_media, QAutoBStr(qt_wmpMetaDataKeys[i].token), value);\n return;\n }\n }\n}\n\nQVariant QWmpMetaData::extendedMetaData(const QString &key) const\n{\n return value(m_media, QAutoBStr(key));\n}\n\nvoid QWmpMetaData::setExtendedMetaData(const QString &key, const QVariant &value)\n{\n setValue(m_media, QAutoBStr(key), value);\n}\n\nvoid QWmpMetaData::currentItemChangeEvent(IDispatch *dispatch)\n{\n IWMPMedia *media = m_media;\n\n m_media = 0;\n if (dispatch)\n dispatch->QueryInterface(__uuidof(IWMPMedia), reinterpret_cast<void **>(&m_media));\n\n if (media) {\n if (m_media)\n emit metaDataChanged();\n else\n emit metaDataAvailableChanged(false);\n\n media->Release();\n } else {\n if (m_media)\n emit metaDataAvailableChanged(false);\n }\n}\n\nvoid QWmpMetaData::mediaChangeEvent(IDispatch *dispatch)\n{\n IWMPMedia *media = 0;\n if (dispatch && dispatch->QueryInterface(\n __uuidof(IWMPMedia), reinterpret_cast<void **>(&media)) == S_OK) {\n VARIANT_BOOL isEqual = VARIANT_FALSE;\n if (media->get_isIdentical(m_media, &isEqual) == S_OK && isEqual)\n emit metaDataChanged();\n media->Release();\n }\n}\n\n\nQStringList QWmpMetaData::keys(IWMPMedia *media)\n{\n QStringList keys;\n\n long count = 0;\n if (media && media->get_attributeCount(&count) == S_OK) {\n for (long i = 0; i < count; ++i) {\n BSTR string;\n if (media->getAttributeName(i, &string) == S_OK) {\n keys.append(QString::fromWCharArray(string, ::SysStringLen(string)));\n\n ::SysFreeString(string);\n }\n }\n }\n return keys;\n}\n\nQVariant QWmpMetaData::value(IWMPMedia *media, BSTR key)\n{\n QVariantList values;\n IWMPMedia3 *media3 = 0;\n if (media && media->QueryInterface(\n __uuidof(IWMPMedia3), reinterpret_cast<void **>(&media3)) == S_OK) {\n long count = 0;\n media3->getAttributeCountByType(key, 0, &count);\n\n \/\/ The count appears to only be valid for static properties, dynamic properties like\n \/\/ PlaylistIndex will have a count of zero but return a value for index 0.\n if (count == 0)\n count = 1;\n\n for (long i = 0; i < count; ++i) {\n VARIANT var;\n VariantInit(&var);\n\n if (media3->getItemInfoByType(key, 0, i, &var) == S_OK) {\n QVariant value = convertVariant(var);\n\n if (!value.isNull())\n values.append(value);\n\n VariantClear(&var);\n }\n }\n media3->Release();\n }\n\n switch (values.count()) {\n case 0:\n return QVariant();\n case 1:\n return values.first();\n default:\n return values;\n }\n}\n\nvoid QWmpMetaData::setValue(IWMPMedia *media, BSTR key, const QVariant &value)\n{\n if (qVariantCanConvert<QString>(value))\n media->setItemInfo(key, QAutoBStr(value.toString()));\n}\n\nQMediaContent QWmpMetaData::resources(IWMPMedia *media)\n{\n QMediaContent content;\n\n BSTR string = 0;\n if (media->get_sourceURL(&string) == S_OK) {\n QString uri = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n content = QMediaContent(QUrl(uri));\n\n if (media->getItemInfo(QAutoBStr(L\"WM\/WMCollectionGroupID\"), &string) == S_OK) {\n QString uuid = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n QString albumArtLarge = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(\"_Large.jpg\");\n QString albumArtSmall = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(\"_Small.jpg\");\n\n QDir dir = QFileInfo(uri).absoluteDir();\n\n if (dir.exists(albumArtLarge))\n content.setCoverArtUriLarge(QUrl(dir.absoluteFilePath(albumArtLarge)));\n\n if (dir.exists(albumArtSmall))\n content.setCoverArtUriSmall(QUrl(dir.absoluteFilePath(albumArtSmall)));\n }\n }\n\n return content;\n}\n\nQVariant QWmpMetaData::convertVariant(const VARIANT &variant)\n{\n switch (variant.vt) {\n case VT_I2:\n return variant.iVal;\n case VT_I4:\n return variant.lVal;\n case VT_I8:\n return variant.llVal;\n case VT_UI2:\n return variant.uiVal;\n case VT_UI4:\n return quint32(variant.ulVal);\n case VT_UI8:\n return variant.ullVal;\n case VT_INT:\n return variant.intVal;\n case VT_UINT:\n return variant.uintVal;\n case VT_BSTR:\n return QString::fromWCharArray(variant.bstrVal, ::SysStringLen(variant.bstrVal));\n case VT_DISPATCH:\n {\n IWMPMetadataPicture *picture = 0;\n IWMPMetadataText *text = 0;\n\n if (variant.pdispVal->QueryInterface(\n __uuidof(IWMPMetadataPicture), reinterpret_cast<void **>(&picture)) == S_OK) {\n QUrl uri;\n BSTR string;\n if (picture->get_URL(&string) == S_OK) {\n uri = QUrl(QString::fromWCharArray(string, ::SysStringLen(string)));\n\n ::SysFreeString(string);\n }\n picture->Release();\n return qVariantFromValue(uri);\n } else if (variant.pdispVal->QueryInterface(\n __uuidof(IWMPMetadataText), reinterpret_cast<void **>(&text)) == S_OK) {\n QString description;\n BSTR string;\n if (text->get_description(&string) == S_OK) {\n description = QString::fromWCharArray(string, SysStringLen(string));\n\n ::SysFreeString(string);\n }\n text->Release();\n return description;\n } else {\n qWarning(\"Unknown dispatch type\");\n }\n }\n break;\n default:\n qWarning(\"Unsupported Type %d %x\", variant.vt, variant.vt);\n break;\n }\n\n return QVariant();\n}\n\nQVariant QWmpMetaData::albumArtUri(IWMPMedia *media, const char *suffix)\n{\n BSTR string = 0;\n if (media && media->get_sourceURL(&string) == S_OK) {\n QString uri = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n if (media->getItemInfo(QAutoBStr(L\"WM\/WMCollectionGroupID\"), &string) == S_OK) {\n QString uuid = QString::fromWCharArray(static_cast<const wchar_t *>(string));\n ::SysFreeString(string);\n\n QString fileName = QLatin1String(\"AlbumArt_\") + uuid + QLatin1String(suffix);\n\n QDir dir = QFileInfo(uri).absoluteDir();\n\n if (dir.exists(fileName)) {\n return qVariantFromValue(\n QUrl(QLatin1String(\"file:\/\/\/\") + dir.absoluteFilePath(fileName)));\n }\n }\n }\n return QVariant();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ------------------------------------------------------------------------\n\/\/ audioio-jack.cpp: Interface to JACK audio framework\n\/\/ Copyright (C) 2001,2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#include <iostream>\n\n#include <jack\/jack.h>\n#include <kvu_dbc.h>\n#include <kvu_numtostr.h>\n\n#include \"audioio.h\"\n#include \"eca-version.h\"\n#include \"eca-logger.h\"\n\n#include \"audioio_jack.h\"\n#include \"audioio_jack_manager.h\"\n\n#ifdef ECA_ENABLE_AUDIOIO_PLUGINS\n\/* see eca-static-object-maps.cpp *\/\nstatic const char* audio_io_keyword_const = \"jack\";\nstatic const char* audio_io_keyword_regex_const = \"(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)\";\n\nAUDIO_IO* audio_io_descriptor(void) { return(new AUDIO_IO_JACK()); }\nconst char* audio_io_keyword(void){return(audio_io_keyword_const); }\nconst char* audio_io_keyword_regex(void){return(audio_io_keyword_regex_const); }\nint audio_io_interface_version(void) { return(ecasound_library_version_current); }\n#endif\n\nAUDIO_IO_JACK::AUDIO_IO_JACK (void)\n{\n ECA_LOG_MSG(ECA_LOGGER::functions, \"(audioio-jack) constructor\");\n \n jackmgr_rep = 0;\n myid_rep = 0;\n secondparam_rep = \"\";\n}\n\nAUDIO_IO_JACK::~AUDIO_IO_JACK(void)\n{ \n if (is_open() == true && is_running()) stop();\n if (is_open() == true) {\n close();\n }\n}\n\nAUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const\n{\n return(new AUDIO_IO_JACK_MANAGER());\n}\n\nvoid AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id)\n{\n string mgrname = (mgr == 0 ? mgr->name() : \"null\");\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \n\t\t\"(audioio-jack) setting manager to \" + mgr->name());\n jackmgr_rep = mgr;\n myid_rep = id;\n}\n\nvoid AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) open\");\n\n set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le);\n toggle_interleaved_channels(false);\n\n if (jackmgr_rep != 0) {\n string my_in_portname (\"in\"), my_out_portname (\"out\");\n\n if (label() == \"jack_generic\") {\n my_in_portname = my_out_portname = secondparam_rep;\n }\n\n \/\/ FIXME: required?\n \/\/ if (workstring.size() == 0) workstring = label();\n\n jackmgr_rep->open(myid_rep);\n\n if (jackmgr_rep->is_open() != true) {\n \/* unable to open connection to jackd, exit *\/\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \"AUDIOIO-JACK: Unable to open JACK-client\"));\n }\n\n if (samples_per_second() != jackmgr_rep->samples_per_second()) {\n jackmgr_rep->close(myid_rep);\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \n\t\t\t\"AUDIOIO-JACK: Cannot connect open connection! Samplerate \" +\n\t\t\tkvu_numtostr(samples_per_second()) + \" differs from JACK server's buffersize of \" + \n\t\t\tkvu_numtostr(jackmgr_rep->samples_per_second()) + \".\"));\n }\n \n if (buffersize() != jackmgr_rep->buffersize()) {\n long int jackd_bsize = jackmgr_rep->buffersize();\n jackmgr_rep->close(myid_rep);\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \n\t\t\t\"AUDIOIO-JACK: Cannot connect open connection! Buffersize \" +\n\t\t\tkvu_numtostr(buffersize()) + \" differs from JACK server's buffersize of \" + \n\t\t\tkvu_numtostr(jackd_bsize) + \".\"));\n }\n\n if (io_mode() == AUDIO_IO::io_read) {\n jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname);\n }\n else {\n jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname);\n }\n\n if (label() != \"jack_generic\" && label() != \"jack\") {\n string in_aconn_portprefix, out_aconn_portprefix;\n\n if (label() == \"jack_alsa\") {\n\tin_aconn_portprefix = \"alsa_pcm:capture_\";\n\tout_aconn_portprefix = \"alsa_pcm:playback_\";\n }\n else if (label() == \"jack_auto\") {\n\tin_aconn_portprefix = secondparam_rep + \":out_\";\n\tout_aconn_portprefix = secondparam_rep + \":in_\";\n }\n \n for(int n = 0; n < channels(); n++) {\n\tif (io_mode() == AUDIO_IO::io_read) {\n\t jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1));\n\t}\n\telse {\n\t jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1));\n\t}\n }\n }\n }\n\n AUDIO_IO_DEVICE::open();\n}\n\nvoid AUDIO_IO_JACK::close(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) close\");\n\n if (jackmgr_rep != 0) {\n jackmgr_rep->unregister_jack_ports(myid_rep);\n jackmgr_rep->close(myid_rep);\n }\n \n AUDIO_IO_DEVICE::close();\n}\n\nbool AUDIO_IO_JACK::finished(void) const \n{\n if (is_open() != true ||\n jackmgr_rep == 0 ||\n jackmgr_rep->is_open() != true)\n return(true);\n\n return(false);\n}\n\nlong int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples)\n{\n if (jackmgr_rep != 0) {\n long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples);\n return(res);\n }\n \n return(0);\n}\n\nvoid AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples)\n{\n if (jackmgr_rep != 0) {\n jackmgr_rep->write_samples(myid_rep, target_buffer, samples);\n }\n}\n\nvoid AUDIO_IO_JACK::prepare(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) prepare \/ \" + label());\n AUDIO_IO_DEVICE::prepare();\n}\n\nvoid AUDIO_IO_JACK::start(void)\n{ \n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) start \/ \" + label());\n AUDIO_IO_DEVICE::start();\n}\n\nvoid AUDIO_IO_JACK::stop(void)\n{ \n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) stop \/ \" + label());\n AUDIO_IO_DEVICE::stop();\n}\n\nlong int AUDIO_IO_JACK::latency(void) const\n{\n return(jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep));\n}\n\nstd::string AUDIO_IO_JACK::parameter_names(void) const\n{ \n if (label() == \"jack_generic\")\n return(\"label,portname\");\n\n if (label() == \"jack_auto\")\n return(\"label,client\");\n\n \/* jack, jack_alsa *\/\n return(\"label\");\n}\n\nvoid AUDIO_IO_JACK::set_parameter(int param, std::string value)\n{\n switch(param) \n {\n case 1: { set_label(value); break; }\n case 2: { secondparam_rep = value; break; }\n }\n}\n\nstd::string AUDIO_IO_JACK::get_parameter(int param) const\n{\n switch(param) \n {\n case 1: { return(label()); }\n case 2: { return(secondparam_rep); }\n } \n\n return(\"\");\n}\n<commit_msg>Typo in the error message.<commit_after>\/\/ ------------------------------------------------------------------------\n\/\/ audioio-jack.cpp: Interface to JACK audio framework\n\/\/ Copyright (C) 2001,2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ ------------------------------------------------------------------------\n\n#include <iostream>\n\n#include <jack\/jack.h>\n#include <kvu_dbc.h>\n#include <kvu_numtostr.h>\n\n#include \"audioio.h\"\n#include \"eca-version.h\"\n#include \"eca-logger.h\"\n\n#include \"audioio_jack.h\"\n#include \"audioio_jack_manager.h\"\n\n#ifdef ECA_ENABLE_AUDIOIO_PLUGINS\n\/* see eca-static-object-maps.cpp *\/\nstatic const char* audio_io_keyword_const = \"jack\";\nstatic const char* audio_io_keyword_regex_const = \"(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)\";\n\nAUDIO_IO* audio_io_descriptor(void) { return(new AUDIO_IO_JACK()); }\nconst char* audio_io_keyword(void){return(audio_io_keyword_const); }\nconst char* audio_io_keyword_regex(void){return(audio_io_keyword_regex_const); }\nint audio_io_interface_version(void) { return(ecasound_library_version_current); }\n#endif\n\nAUDIO_IO_JACK::AUDIO_IO_JACK (void)\n{\n ECA_LOG_MSG(ECA_LOGGER::functions, \"(audioio-jack) constructor\");\n \n jackmgr_rep = 0;\n myid_rep = 0;\n secondparam_rep = \"\";\n}\n\nAUDIO_IO_JACK::~AUDIO_IO_JACK(void)\n{ \n if (is_open() == true && is_running()) stop();\n if (is_open() == true) {\n close();\n }\n}\n\nAUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const\n{\n return(new AUDIO_IO_JACK_MANAGER());\n}\n\nvoid AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id)\n{\n string mgrname = (mgr == 0 ? mgr->name() : \"null\");\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \n\t\t\"(audioio-jack) setting manager to \" + mgr->name());\n jackmgr_rep = mgr;\n myid_rep = id;\n}\n\nvoid AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) open\");\n\n set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le);\n toggle_interleaved_channels(false);\n\n if (jackmgr_rep != 0) {\n string my_in_portname (\"in\"), my_out_portname (\"out\");\n\n if (label() == \"jack_generic\") {\n my_in_portname = my_out_portname = secondparam_rep;\n }\n\n \/\/ FIXME: required?\n \/\/ if (workstring.size() == 0) workstring = label();\n\n jackmgr_rep->open(myid_rep);\n\n if (jackmgr_rep->is_open() != true) {\n \/* unable to open connection to jackd, exit *\/\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \"AUDIOIO-JACK: Unable to open JACK-client\"));\n }\n\n if (samples_per_second() != jackmgr_rep->samples_per_second()) {\n jackmgr_rep->close(myid_rep);\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \n\t\t\t\"AUDIOIO-JACK: Cannot connect open connection! Samplerate \" +\n\t\t\tkvu_numtostr(samples_per_second()) + \" differs from JACK server's sample rate of \" + \n\t\t\tkvu_numtostr(jackmgr_rep->samples_per_second()) + \".\"));\n }\n \n if (buffersize() != jackmgr_rep->buffersize()) {\n long int jackd_bsize = jackmgr_rep->buffersize();\n jackmgr_rep->close(myid_rep);\n throw(SETUP_ERROR(SETUP_ERROR::unexpected, \n\t\t\t\"AUDIOIO-JACK: Cannot connect open connection! Buffersize \" +\n\t\t\tkvu_numtostr(buffersize()) + \" differs from JACK server's buffersize of \" + \n\t\t\tkvu_numtostr(jackd_bsize) + \".\"));\n }\n\n if (io_mode() == AUDIO_IO::io_read) {\n jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname);\n }\n else {\n jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname);\n }\n\n if (label() != \"jack_generic\" && label() != \"jack\") {\n string in_aconn_portprefix, out_aconn_portprefix;\n\n if (label() == \"jack_alsa\") {\n\tin_aconn_portprefix = \"alsa_pcm:capture_\";\n\tout_aconn_portprefix = \"alsa_pcm:playback_\";\n }\n else if (label() == \"jack_auto\") {\n\tin_aconn_portprefix = secondparam_rep + \":out_\";\n\tout_aconn_portprefix = secondparam_rep + \":in_\";\n }\n \n for(int n = 0; n < channels(); n++) {\n\tif (io_mode() == AUDIO_IO::io_read) {\n\t jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1));\n\t}\n\telse {\n\t jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1));\n\t}\n }\n }\n }\n\n AUDIO_IO_DEVICE::open();\n}\n\nvoid AUDIO_IO_JACK::close(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) close\");\n\n if (jackmgr_rep != 0) {\n jackmgr_rep->unregister_jack_ports(myid_rep);\n jackmgr_rep->close(myid_rep);\n }\n \n AUDIO_IO_DEVICE::close();\n}\n\nbool AUDIO_IO_JACK::finished(void) const \n{\n if (is_open() != true ||\n jackmgr_rep == 0 ||\n jackmgr_rep->is_open() != true)\n return(true);\n\n return(false);\n}\n\nlong int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples)\n{\n if (jackmgr_rep != 0) {\n long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples);\n return(res);\n }\n \n return(0);\n}\n\nvoid AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples)\n{\n if (jackmgr_rep != 0) {\n jackmgr_rep->write_samples(myid_rep, target_buffer, samples);\n }\n}\n\nvoid AUDIO_IO_JACK::prepare(void)\n{\n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) prepare \/ \" + label());\n AUDIO_IO_DEVICE::prepare();\n}\n\nvoid AUDIO_IO_JACK::start(void)\n{ \n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) start \/ \" + label());\n AUDIO_IO_DEVICE::start();\n}\n\nvoid AUDIO_IO_JACK::stop(void)\n{ \n ECA_LOG_MSG(ECA_LOGGER::system_objects, \"(audioio-jack) stop \/ \" + label());\n AUDIO_IO_DEVICE::stop();\n}\n\nlong int AUDIO_IO_JACK::latency(void) const\n{\n return(jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep));\n}\n\nstd::string AUDIO_IO_JACK::parameter_names(void) const\n{ \n if (label() == \"jack_generic\")\n return(\"label,portname\");\n\n if (label() == \"jack_auto\")\n return(\"label,client\");\n\n \/* jack, jack_alsa *\/\n return(\"label\");\n}\n\nvoid AUDIO_IO_JACK::set_parameter(int param, std::string value)\n{\n switch(param) \n {\n case 1: { set_label(value); break; }\n case 2: { secondparam_rep = value; break; }\n }\n}\n\nstd::string AUDIO_IO_JACK::get_parameter(int param) const\n{\n switch(param) \n {\n case 1: { return(label()); }\n case 2: { return(secondparam_rep); }\n } \n\n return(\"\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <raytracer.h>\n#include <bodies.h>\n\n#include <cmath>\n#include <cassert>\n\nusing namespace raytracer;\n\n\n\nCylinder::Cylinder() {\n\tsetSize(1.0);\n\tsetOrientation(Vector(0.0,1.0,0.0));\n\tsetPosition(Vector(0.0,0.0,0.0));\n}\n\n\n\nCylinder::Cylinder(const Vector & p, const Vector & v, double radius) {\n\tsetSize(radius);\n\tsetOrientation(v);\n\tsetPosition(p);\n}\n\n\n\nBody * Cylinder::clone() const {\n\treturn (Body*) new Cylinder(*this);\n}\n\n\n\nvoid Cylinder::setSize(double radius) {\n\tassert(radius > DIV_LIMIT);\n\n\tsize = radius;\n\tmagnitude = radius * radius;\n\treciprocal = 1 \/ radius;\n}\n\n\n\n\/\/Cylinder uses the z_axis orientation vector from BasicBody as its axis\nvoid Cylinder::setOrientation(const Vector & v) {\n\tx_axis.copy(1.0,0.0,0.0);\n\ty_axis.copy(0.0,1.0,0.0);\n\tz_axis.copy(v);\n}\n\n\n\ndouble Cylinder::getDistance(const Ray & r) const {\n\t\/\/magnitude is radius squared\n\t\/\/position and direction are vectors defining position\/orientation\n\tVector v = r.p, w = r.v;\n\tv.subtract(position);\n\tv.cross(z_axis);\n\tw.cross(z_axis);\n\tdouble vv = v.dot(), vw = v.dot(w), ww = w.dot();\n\tdouble radical = vw*vw + ww \/ magnitude - vv*ww;\n\t\n\tif (radical < DIV_LIMIT) return -1.0;\n\telse radical = std::sqrt(radical) \/ ww;\n\n\tdouble distance = -vw \/ ww - radical;\n\tif (distance < DIV_LIMIT) {\n\t\tdistance = -vw \/ ww + radical;\n\t\tif (distance < DIV_LIMIT) {\n\t\t\treturn -1.0;\n\t\t}\n\t\telse return distance;\n\t}\n\n\telse return distance;\n}\n\n\n\nVector Cylinder::getNormal(const Vector & p) const {\n\tVector result = p, projection = z_axis;\n\tprojection.dot(p);\n\tresult.subtract(projection);\n\tresult.scale(reciprocal);\n\treturn result;\n}\n<commit_msg>using new api<commit_after>#include <raytracer.h>\n#include <bodies.h>\n\n#include <cmath>\n#include <cassert>\n\nusing namespace raytracer;\n\n\n\nCylinder::Cylinder() {\n\tuseDefaults();\n}\n\n\n\nBody * Cylinder::clone() const {\n\treturn (Body*) new Cylinder(*this);\n}\n\n\n\ndouble Cylinder::getDistance(const Ray & r) const {\n\t\/\/magnitude is radius squared\n\t\/\/position and direction are vectors defining position\/orientation\n\tVector v = r.p, w = r.v;\n\tv.subtract(position);\n\tv.cross(orientation);\n\tw.cross(orientation);\n\tdouble vv = v.dot(), vw = v.dot(w), ww = w.dot();\n\tdouble radical = vw*vw + ww \/ magnitude - vv*ww;\n\t\n\tif (radical < ZERO) return -1.0;\n\telse radical = std::sqrt(radical) \/ ww;\n\n\tdouble distance = -vw \/ ww - radical;\n\tif (distance < ZERO) {\n\t\tdistance = -vw \/ ww + radical;\n\t\tif (distance < ZERO) {\n\t\t\treturn -1.0;\n\t\t}\n\t\telse return distance;\n\t}\n\n\telse return distance;\n}\n\n\n\nVector Cylinder::getNormal(const Vector & p) const {\n\tVector result = p, projection = orientation;\n\tprojection.dot(p);\n\tresult.subtract(projection);\n\tresult.scale(reciprocal);\n\t\n\tif (matte) {\n\t\tresult.add(Vector::random(normal_delta);\n\t\tresult.normalize();\n\t}\n\t\n\tassert(std::abs(result.dot() - 1.0) < ZERO);\n\t\n\treturn result;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n#if !defined(__CINT__) || defined(__MAKECINT__)\n\n\/\/\/ This macro runs the test preprocessor for MUON.\n\/\/\/ It uses AliTestShuttle to simulate a full Shuttle process\n\/\/\/\n\/\/\/ The input data has to be created first by other processes (or is created\n\/\/\/ here by CreateDCSAliasMap() for tracker HV).\n\/\/\/\n\/\/\/ To play with it, you'll have to set\/modify several lines, to\n\/\/\/ a) select input files, using shuttle->AddInputFile()\n\/\/\/ b) select run type, using shuttle->AddInputRunParameter() (the run type\n\/\/\/ dictates which task is really performed by the MUONPreprocessor\n\/\/\/\n\/\/\/ You must load relevant libraries (besides normal MUON ones) before\n\/\/\/ compiling this macro :\n\/\/\/\n\/\/\/ gSystem->Load(\"$ALICE_ROOT\/SHUTTLE\/TestShuttle\/libTestShuttle\");\n\/\/\/ gSystem->Load(\"libMUONshuttle.so\");\n\/\/\/\n\/\/\/\n\/\/\/ For more information on usage, please see READMEshuttle.\n\/\/\/\n\/\/ By Laurent Aphecetche, SUBATECH Nantes\n\n#include \"TestMUONPreprocessor.h\"\n\n#include \"AliMUONTrackerPreprocessor.h\"\n#include \"AliMUONTriggerPreprocessor.h\"\n\n#include \"AliLog.h\"\n\n#include \"AliMpExMap.h\"\n#include \"AliMpHelper.h\"\n#include \"AliMpHVNamer.h\"\n#include \"AliMpCDB.h\"\n\n#include \"AliCDBManager.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliCDBId.h\"\n#include \"AliShuttleInterface.h\"\n#include \"AliTestShuttle.h\"\n#include \"AliDCSValue.h\"\n\n#include \"Riostream.h\"\n#include \"TSystem.h\"\n#include \"TMap.h\"\n#include \"TObjArray.h\"\n#include \"TObjString.h\"\n#include \"TString.h\"\n#include \"TRandom.h\"\n#endif\n\nvoid TestMUONPreprocessor(Int_t runNumber=80, const char* runType=\"PEDESTAL_RUN\")\n{\n \/\/ runType can be :\n \/\/\n \/\/ PEDESTAL_RUN -> pedestals\n \/\/ ELECTRONICS_CALIBRATION_RUN -> gains\n \/\/ PHYSICS -> HV\n \/\/ GMS\n \n \/\/ create AliTestShuttle instance\n \/\/ The parameters are run, startTime, endTime\n AliTestShuttle* shuttle = new AliTestShuttle(runNumber, 0, 1);\n \n const char* inputCDB = \"local:\/\/$ALICE_ROOT\/SHUTTLE\/TestShuttle\/TestCDB\";\n \n AliTestShuttle::SetMainCDB(inputCDB);\n AliTestShuttle::SetMainRefStorage(\"local:\/\/$ALICE_ROOT\/SHUTTLE\/TestShuttle\/TestReference\");\n\n \/\/ Create DCS HV aliases\n TMap* dcsAliasMap = CreateDCSAliasMap(inputCDB);\n \n if ( dcsAliasMap ) \n {\n \/\/ now give the alias map to the shuttle\n shuttle->SetDCSInput(dcsAliasMap);\n }\n \n \n printf(\"Test Shuttle temp dir: %s\\n\", AliShuttleInterface::GetShuttleTempDir());\n printf(\"Test Shuttle log dir: %s\\n\", AliShuttleInterface::GetShuttleLogDir());\n printf(\"Test OCDB storage Uri: %s\\n\", AliShuttleInterface::GetMainCDB().Data());\n printf(\"Test Reference storage Uri: %s\\n\", AliShuttleInterface::GetMainRefStorage().Data());\n \n \/\/ The shuttle can process files that originate from DCS, DAQ and HLT.\n \/\/ To test it, we provide some local files and locations where these would be found when\n \/\/ the online machinery would be there.\n \/\/ In real life this functions would be produces by the sub-detectors\n \/\/ calibration programs in DCS, DAQ or HLT. These files can then be retrieved using the Shuttle.\n \/\/\n \/\/ Files are added with the function AliTestShuttle::AddInputFile. The syntax is:\n \/\/ AddInputFile(<system>, <detector>, <id>, <source>, <local-file>)\n \/\/ In this example we add 4 files originating from different LDCs but with the same id (PEDESTALS)\n\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/LDC0.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC1\",\"$ALICE_ROOT\/MUON\/data\/LDC1.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC2\",\"$ALICE_ROOT\/MUON\/data\/LDC2.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC3\",\"$ALICE_ROOT\/MUON\/data\/LDC3.ped\");\n \n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/LDC0.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC1\",\"$ALICE_ROOT\/MUON\/data\/LDC1.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC2\",\"$ALICE_ROOT\/MUON\/data\/LDC2.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC3\",\"$ALICE_ROOT\/MUON\/data\/LDC3.gain\");\n \n \/\/ and GMS file\n shuttle->AddInputFile(AliTestShuttle::kDCS,\"MCH\",\"GMS\",\"GMS\",\"$ALICE_ROOT\/MUON\/data\/GMS.root\");\n\n \/\/ and then the trigger stuff\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"LOCAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgLocalMask-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"REGIONAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgRegionalCrate-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"GLOBAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgGlobalCrate-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"LUT\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgLocalLut-1.dat\");\n \n \/\/ The shuttle can read run parameters stored in the DAQ run logbook.\n \/\/ To test it, we must provide the run parameters manually. They will be retrieved in the preprocessor\n \/\/ using GetRunParameter function.\n \/\/ In real life the parameters will be retrieved automatically from the run logbook;\n shuttle->SetInputRunType(runType);\n \n \/\/ Create the preprocessor that should be tested, it registers itself automatically to the shuttle\n new AliMUONTrackerPreprocessor(shuttle);\n new AliMUONTriggerPreprocessor(shuttle);\n \n shuttle->Print();\n \n \/\/ Test the preprocessor\n shuttle->Process();\n}\n\nTMap* CreateDCSAliasMap(const char* inputCDB)\n{\n \/\/\/ Creates a DCS structure for MUON Tracker HV\n \/\/\/\n \/\/\/ The structure is the following:\n \/\/\/ TMap (key --> value)\n \/\/\/ <DCSAlias> --> <valueList>\n \/\/\/ <DCSAlias> is a string\n \/\/\/ <valueList> is a TObjArray of AliDCSValue\n \/\/\/ An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue\n \n Bool_t undefStorage(kFALSE);\n \n AliCDBManager* man = AliCDBManager::Instance();\n if (!man->IsDefaultStorageSet())\n {\n undefStorage = kTRUE;\n man->SetDefaultStorage(inputCDB);\n }\n \n \/\/ Load mapping\n Bool_t ok = AliMpCDB::LoadDDLStore();\n \n if (undefStorage)\n {\n man->UnsetDefaultStorage();\n }\n \n if (!ok)\n {\n AliErrorGeneral(\"CreateDCSAliasMap\",\"Could not load DDLStore from OCDB\");\n return 0x0;\n }\n\n TMap* aliasMap = new TMap;\n aliasMap->SetOwner(kTRUE);\n \n TRandom random(0);\n \n AliMpHVNamer hvNamer;\n \n TObjArray* aliases = hvNamer.GenerateAliases();\n \n for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) \n {\n TObjString* alias = static_cast<TObjString*>(aliases->At(i));\n TString& aliasName = alias->String();\n if ( aliasName.Contains(\"sw\") ) \n {\n \/\/ HV Switch (St345 only)\n TObjArray* valueSet = new TObjArray;\n valueSet->SetOwner(kTRUE);\n Bool_t value = kTRUE;\n\/\/ Float_t r = random.Uniform();\n\/\/ if ( r < 0.007 ) value = kFALSE; \n\/\/ if ( aliasName.Contains(\"DE513sw2\") ) value = kFALSE;\n \n for ( UInt_t timeStamp = 0; timeStamp < 60*3; timeStamp += 60 )\n {\n AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);\n valueSet->Add(dcsValue);\n }\n aliasMap->Add(new TObjString(*alias),valueSet);\n }\n else\n {\n TObjArray* valueSet = new TObjArray;\n valueSet->SetOwner(kTRUE);\n for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )\n {\n Float_t value = random.Gaus(1750,62.5);\n if ( aliasName == \"MchHvLvLeft\/Chamber00Left\/Quad2Sect1.actual.vMon\") value = 500;\n AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);\n valueSet->Add(dcsValue);\n }\n if ( aliasName == \"MchHvLvLeft\/Chamber04Left\/Slat06.actual.vMon\" ) continue;\n aliasMap->Add(new TObjString(*alias),valueSet);\n }\n }\n \n delete aliases;\n \n return aliasMap;\n}\n\n<commit_msg>Adding MtgCurrent.dat input file for trigger (Laurent)<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n#if !defined(__CINT__) || defined(__MAKECINT__)\n\n\/\/\/ This macro runs the test preprocessor for MUON.\n\/\/\/ It uses AliTestShuttle to simulate a full Shuttle process\n\/\/\/\n\/\/\/ The input data has to be created first by other processes (or is created\n\/\/\/ here by CreateDCSAliasMap() for tracker HV).\n\/\/\/\n\/\/\/ To play with it, you'll have to set\/modify several lines, to\n\/\/\/ a) select input files, using shuttle->AddInputFile()\n\/\/\/ b) select run type, using shuttle->AddInputRunParameter() (the run type\n\/\/\/ dictates which task is really performed by the MUONPreprocessor\n\/\/\/\n\/\/\/ You must load relevant libraries (besides normal MUON ones) before\n\/\/\/ compiling this macro :\n\/\/\/\n\/\/\/ gSystem->Load(\"$ALICE_ROOT\/SHUTTLE\/TestShuttle\/libTestShuttle\");\n\/\/\/ gSystem->Load(\"libMUONshuttle.so\");\n\/\/\/\n\/\/\/\n\/\/\/ For more information on usage, please see READMEshuttle.\n\/\/\/\n\/\/ By Laurent Aphecetche, SUBATECH Nantes\n\n#include \"TestMUONPreprocessor.h\"\n\n#include \"AliMUONTrackerPreprocessor.h\"\n#include \"AliMUONTriggerPreprocessor.h\"\n\n#include \"AliLog.h\"\n\n#include \"AliMpExMap.h\"\n#include \"AliMpHelper.h\"\n#include \"AliMpHVNamer.h\"\n#include \"AliMpCDB.h\"\n\n#include \"AliCDBManager.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliCDBId.h\"\n#include \"AliShuttleInterface.h\"\n#include \"AliTestShuttle.h\"\n#include \"AliDCSValue.h\"\n\n#include \"Riostream.h\"\n#include \"TSystem.h\"\n#include \"TMap.h\"\n#include \"TObjArray.h\"\n#include \"TObjString.h\"\n#include \"TString.h\"\n#include \"TRandom.h\"\n#endif\n\nvoid TestMUONPreprocessor(Int_t runNumber=80, const char* runType=\"PEDESTAL_RUN\")\n{\n \/\/ runType can be :\n \/\/\n \/\/ PEDESTAL_RUN -> pedestals\n \/\/ ELECTRONICS_CALIBRATION_RUN -> gains\n \/\/ PHYSICS -> HV\n \/\/ GMS\n \n \/\/ create AliTestShuttle instance\n \/\/ The parameters are run, startTime, endTime\n AliTestShuttle* shuttle = new AliTestShuttle(runNumber, 0, 1);\n \n const char* inputCDB = \"local:\/\/$ALICE_ROOT\/SHUTTLE\/TestShuttle\/TestCDB\";\n \n AliTestShuttle::SetMainCDB(inputCDB);\n AliTestShuttle::SetMainRefStorage(\"local:\/\/$ALICE_ROOT\/SHUTTLE\/TestShuttle\/TestReference\");\n\n \/\/ Create DCS HV aliases\n TMap* dcsAliasMap = CreateDCSAliasMap(inputCDB);\n \n if ( dcsAliasMap ) \n {\n \/\/ now give the alias map to the shuttle\n shuttle->SetDCSInput(dcsAliasMap);\n }\n \n \n printf(\"Test Shuttle temp dir: %s\\n\", AliShuttleInterface::GetShuttleTempDir());\n printf(\"Test Shuttle log dir: %s\\n\", AliShuttleInterface::GetShuttleLogDir());\n printf(\"Test OCDB storage Uri: %s\\n\", AliShuttleInterface::GetMainCDB().Data());\n printf(\"Test Reference storage Uri: %s\\n\", AliShuttleInterface::GetMainRefStorage().Data());\n \n \/\/ The shuttle can process files that originate from DCS, DAQ and HLT.\n \/\/ To test it, we provide some local files and locations where these would be found when\n \/\/ the online machinery would be there.\n \/\/ In real life this functions would be produces by the sub-detectors\n \/\/ calibration programs in DCS, DAQ or HLT. These files can then be retrieved using the Shuttle.\n \/\/\n \/\/ Files are added with the function AliTestShuttle::AddInputFile. The syntax is:\n \/\/ AddInputFile(<system>, <detector>, <id>, <source>, <local-file>)\n \/\/ In this example we add 4 files originating from different LDCs but with the same id (PEDESTALS)\n\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/LDC0.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC1\",\"$ALICE_ROOT\/MUON\/data\/LDC1.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC2\",\"$ALICE_ROOT\/MUON\/data\/LDC2.ped\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"PEDESTALS\",\"LDC3\",\"$ALICE_ROOT\/MUON\/data\/LDC3.ped\");\n \n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/LDC0.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC1\",\"$ALICE_ROOT\/MUON\/data\/LDC1.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC2\",\"$ALICE_ROOT\/MUON\/data\/LDC2.gain\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MCH\",\"GAINS\",\"LDC3\",\"$ALICE_ROOT\/MUON\/data\/LDC3.gain\");\n \n \/\/ and GMS file\n shuttle->AddInputFile(AliTestShuttle::kDCS,\"MCH\",\"GMS\",\"GMS\",\"$ALICE_ROOT\/MUON\/data\/GMS.root\");\n\n \/\/ and then the trigger stuff\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"LOCAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgLocalMask-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"REGIONAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgRegionalCrate-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"GLOBAL\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgGlobalCrate-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"LUT\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgLocalLut-1.dat\");\n shuttle->AddInputFile(AliTestShuttle::kDAQ,\"MTR\",\"CURRENT\",\"LDC0\",\"$ALICE_ROOT\/MUON\/data\/MtgCurrent.dat\");\n \n \/\/ The shuttle can read run parameters stored in the DAQ run logbook.\n \/\/ To test it, we must provide the run parameters manually. They will be retrieved in the preprocessor\n \/\/ using GetRunParameter function.\n \/\/ In real life the parameters will be retrieved automatically from the run logbook;\n shuttle->SetInputRunType(runType);\n \n \/\/ Create the preprocessor that should be tested, it registers itself automatically to the shuttle\n new AliMUONTrackerPreprocessor(shuttle);\n new AliMUONTriggerPreprocessor(shuttle);\n \n shuttle->Print();\n \n \/\/ Test the preprocessor\n shuttle->Process();\n}\n\nTMap* CreateDCSAliasMap(const char* inputCDB)\n{\n \/\/\/ Creates a DCS structure for MUON Tracker HV\n \/\/\/\n \/\/\/ The structure is the following:\n \/\/\/ TMap (key --> value)\n \/\/\/ <DCSAlias> --> <valueList>\n \/\/\/ <DCSAlias> is a string\n \/\/\/ <valueList> is a TObjArray of AliDCSValue\n \/\/\/ An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue\n \n Bool_t undefStorage(kFALSE);\n \n AliCDBManager* man = AliCDBManager::Instance();\n if (!man->IsDefaultStorageSet())\n {\n undefStorage = kTRUE;\n man->SetDefaultStorage(inputCDB);\n }\n \n \/\/ Load mapping\n Bool_t ok = AliMpCDB::LoadDDLStore();\n \n if (undefStorage)\n {\n man->UnsetDefaultStorage();\n }\n \n if (!ok)\n {\n AliErrorGeneral(\"CreateDCSAliasMap\",\"Could not load DDLStore from OCDB\");\n return 0x0;\n }\n\n TMap* aliasMap = new TMap;\n aliasMap->SetOwner(kTRUE);\n \n TRandom random(0);\n \n AliMpHVNamer hvNamer;\n \n TObjArray* aliases = hvNamer.GenerateAliases();\n \n for ( Int_t i = 0; i < aliases->GetEntries(); ++i ) \n {\n TObjString* alias = static_cast<TObjString*>(aliases->At(i));\n TString& aliasName = alias->String();\n if ( aliasName.Contains(\"sw\") ) \n {\n \/\/ HV Switch (St345 only)\n TObjArray* valueSet = new TObjArray;\n valueSet->SetOwner(kTRUE);\n Bool_t value = kTRUE;\n\/\/ Float_t r = random.Uniform();\n\/\/ if ( r < 0.007 ) value = kFALSE; \n\/\/ if ( aliasName.Contains(\"DE513sw2\") ) value = kFALSE;\n \n for ( UInt_t timeStamp = 0; timeStamp < 60*3; timeStamp += 60 )\n {\n AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);\n valueSet->Add(dcsValue);\n }\n aliasMap->Add(new TObjString(*alias),valueSet);\n }\n else\n {\n TObjArray* valueSet = new TObjArray;\n valueSet->SetOwner(kTRUE);\n for ( UInt_t timeStamp = 0; timeStamp < 60*15; timeStamp += 120 )\n {\n Float_t value = random.Gaus(1750,62.5);\n if ( aliasName == \"MchHvLvLeft\/Chamber00Left\/Quad2Sect1.actual.vMon\") value = 500;\n AliDCSValue* dcsValue = new AliDCSValue(value,timeStamp);\n valueSet->Add(dcsValue);\n }\n if ( aliasName == \"MchHvLvLeft\/Chamber04Left\/Slat06.actual.vMon\" ) continue;\n aliasMap->Add(new TObjString(*alias),valueSet);\n }\n }\n \n delete aliases;\n \n return aliasMap;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <CMDParser.hpp>\n#include <DataTypes.hpp>\n#include <sensor.hpp>\n#include <devicemanager.hpp>\n#include <device.hpp>\n#include <FileValue.hpp>\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <zmq.hpp>\n#include <cmath>\n#include <iostream>\n#include <chrono> \/\/ std::chrono::seconds\n#include <thread>\n\n\n\n\nstruct feedback{\n glm::mat4 cyclops_mat;\n glm::mat4 screen_mat;\n glm::mat4 model_mat;\n unsigned recon_mode;\n};\n\nint main(int argc, char* argv[]){\n\n\n unsigned model_tracking_id = 0;\n unsigned art_port = 5000;\n unsigned start_port = 9000;\n std::string sender_ip = \"127.0.0.1\";\n\n CMDParser p(\"glass_ids\");\n p.addOpt(\"m\",1,\"model_tracking_id\", \"default: 0\");\n p.addOpt(\"r\",1,\"reconmodefilename\", \"default: none\");\n p.addOpt(\"a\",1,\"artport\", \"default: 5000\");\n p.addOpt(\"s\",1,\"senderip\", \"default: 127.0.0.1\");\n p.addOpt(\"p\",1,\"port\", \"default: 9000\");\n\n\n p.init(argc,argv);\n\n if(p.isOptSet(\"m\")){\n model_tracking_id = p.getOptsInt(\"m\")[0];\n }\n\n if(p.isOptSet(\"a\")){\n art_port = p.getOptsInt(\"a\")[0];\n }\n\n if(p.isOptSet(\"p\")){\n start_port = p.getOptsInt(\"p\")[0];\n }\n\n if(p.isOptSet(\"s\")){\n sender_ip = p.getOptsString(\"s\")[0];\n }\n\n\n\n sensor::FileValue* recon_mode = 0;\n if(p.isOptSet(\"r\")){\n recon_mode = new sensor::FileValue(p.getOptsString(\"r\")[0].c_str());\n }\n\n\n\n \/\/ prepare tracking system\n sensor::device* d = sensor::devicemanager::the()->get_dtrack(art_port, sensor::timevalue::const_050_ms);\n sensor::sensor* model = new sensor::sensor(d, model_tracking_id);\n\n zmq::context_t ctx(1); \/\/ means single threaded\n uint32_t hwm = 1;\n std::vector<zmq::socket_t*> sockets;\n std::vector<sensor::sensor*> glasses;\n \/\/ parse glass_ids and generate socket endpoints\n for(const auto& g_id : p.getArgs()){\n std::string endpoint = std::string(\"tcp:\/\/\" + sender_ip + \":\" + std::to_string(start_port));\n ++start_port;\n zmq::socket_t* socket = new zmq::socket_t(ctx, ZMQ_PUB); \/\/ means a publisher\n socket->setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm));\n socket->bind(endpoint.c_str());\n sockets.push_back(socket);\n glasses.push_back(new sensor::sensor(d, std::stoi(g_id)));\n std::cout << \"sending glass id \" << std::stoi(g_id) << \" to endpoint \" << endpoint << std::endl;\n }\n\n\n#if 0\n std::string socket_name(p.getArgs()[0]);\n\n zmq::context_t ctx(1); \/\/ means single threaded\n zmq::socket_t socket(ctx, ZMQ_PUB); \/\/ means a publisher\n uint32_t hwm = 1;\n socket.setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm));\n\n std::string endpoint(\"tcp:\/\/\" + socket_name);\n socket.bind(endpoint.c_str());\n\n \/\/ prepare tracking system\n sensor::device* d = sensor::devicemanager::the()->get_dtrack(art_port, sensor::timevalue::const_050_ms);\n sensor::sensor* head = new sensor::sensor(d, head_tracking_id);\n sensor::sensor* model = new sensor::sensor(d, model_tracking_id);\n#endif\n \n\n glm::mat4 scale_mat;\n scale_mat[0][0] = 0.25;\n scale_mat[1][1] = 0.25;\n scale_mat[2][2] = 0.25;\n\n glm::mat4 trans_mat;\n trans_mat[3][0] = 0.0;\n trans_mat[3][1] = 0.15;\n trans_mat[3][2] = 0.0;\n \n feedback fb;\n fb.recon_mode = 1;\n fb.cyclops_mat[3][0] = 0.0;\n fb.cyclops_mat[3][1] = 1.8;\n fb.cyclops_mat[3][2] = 0.0;\n\n fb.screen_mat[3][0] = 0.0; \/\/ -0.05\n fb.screen_mat[3][1] = 1.445; \/\/ 1.24\n fb.screen_mat[3][2] = -2.03;\n\n \/\/ initial model is at center screen position\n fb.model_mat = fb.screen_mat * (trans_mat * scale_mat);\n \n\n while(true){\n\n#if 0\n \/\/ receive data from tracking system\n if((head_tracking_id) != 0 && (model_tracking_id != 0)){\n fb.cyclops_mat = head->getMatrix();\n fb.model_mat = model->getMatrix() * (trans_mat * scale_mat);\n }\n#endif\n\n if(recon_mode != 0){\n recon_mode->read(fb.recon_mode);\n }\n\n fb.model_mat = model->getMatrix() * (trans_mat * scale_mat);\n for(unsigned i = 0; i != glasses.size(); ++i){\n fb.cyclops_mat = glasses[i]->getMatrix();\n zmq::message_t zmqm(sizeof(feedback));\n memcpy( (unsigned char* ) zmqm.data(), (const unsigned char*) &fb, sizeof(feedback));\n sockets[i]->send(zmqm);\n }\n\n#if 0\n zmq::message_t zmqm(sizeof(feedback));\n memcpy( (unsigned char* ) zmqm.data(), (const unsigned char*) &fb, sizeof(feedback));\n socket.send(zmqm);\n#endif\n\n std::this_thread::sleep_for( std::chrono::milliseconds(16) );\n\n }\n\n return 0;\n}\n\n<commit_msg>added stream slot for input<commit_after>#include <CMDParser.hpp>\n#include <DataTypes.hpp>\n#include <sensor.hpp>\n#include <devicemanager.hpp>\n#include <device.hpp>\n#include <FileValue.hpp>\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <zmq.hpp>\n#include <cmath>\n#include <iostream>\n#include <chrono> \/\/ std::chrono::seconds\n#include <thread>\n\n\n\n\nstruct feedback{\n glm::mat4 cyclops_mat;\n glm::mat4 screen_mat;\n glm::mat4 model_mat;\n unsigned recon_mode;\n unsigned stream_slot;\n};\n\nint main(int argc, char* argv[]){\n\n\n unsigned model_tracking_id = 0;\n unsigned art_port = 5000;\n unsigned start_port = 9000;\n std::string sender_ip = \"127.0.0.1\";\n\n CMDParser p(\"glass_ids\");\n p.addOpt(\"m\",1,\"model_tracking_id\", \"default: 0\");\n p.addOpt(\"r\",1,\"reconmodefilename\", \"specifiy a file for selecting the reconstruction mode default: none\");\n p.addOpt(\"x\",1,\"streamslotfilename\", \"specifiy a file for selecting the stream slot default: none\");\n p.addOpt(\"a\",1,\"artport\", \"default: 5000\");\n p.addOpt(\"s\",1,\"senderip\", \"default: 127.0.0.1\");\n p.addOpt(\"p\",1,\"port\", \"default: 9000\");\n\n\n p.init(argc,argv);\n\n if(p.isOptSet(\"m\")){\n model_tracking_id = p.getOptsInt(\"m\")[0];\n }\n\n if(p.isOptSet(\"a\")){\n art_port = p.getOptsInt(\"a\")[0];\n }\n\n if(p.isOptSet(\"p\")){\n start_port = p.getOptsInt(\"p\")[0];\n }\n\n if(p.isOptSet(\"s\")){\n sender_ip = p.getOptsString(\"s\")[0];\n }\n\n\n\n sensor::FileValue* recon_mode = 0;\n if(p.isOptSet(\"r\")){\n recon_mode = new sensor::FileValue(p.getOptsString(\"r\")[0].c_str());\n }\n\n sensor::FileValue* stream_slot = 0;\n if(p.isOptSet(\"x\")){\n stream_slot = new sensor::FileValue(p.getOptsString(\"x\")[0].c_str());\n }\n\n \/\/ prepare tracking system\n sensor::device* d = sensor::devicemanager::the()->get_dtrack(art_port, sensor::timevalue::const_050_ms);\n sensor::sensor* model = new sensor::sensor(d, model_tracking_id);\n\n zmq::context_t ctx(1); \/\/ means single threaded\n uint32_t hwm = 1;\n std::vector<zmq::socket_t*> sockets;\n std::vector<sensor::sensor*> glasses;\n \/\/ parse glass_ids and generate socket endpoints\n for(const auto& g_id : p.getArgs()){\n std::string endpoint = std::string(\"tcp:\/\/\" + sender_ip + \":\" + std::to_string(start_port));\n ++start_port;\n zmq::socket_t* socket = new zmq::socket_t(ctx, ZMQ_PUB); \/\/ means a publisher\n socket->setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm));\n socket->bind(endpoint.c_str());\n sockets.push_back(socket);\n glasses.push_back(new sensor::sensor(d, std::stoi(g_id)));\n std::cout << \"sending glass id \" << std::stoi(g_id) << \" to endpoint \" << endpoint << std::endl;\n }\n\n\n glm::mat4 scale_mat;\n scale_mat[0][0] = 0.25;\n scale_mat[1][1] = 0.25;\n scale_mat[2][2] = 0.25;\n\n glm::mat4 trans_mat;\n trans_mat[3][0] = 0.0;\n trans_mat[3][1] = 0.15;\n trans_mat[3][2] = 0.0;\n \n feedback fb;\n fb.recon_mode = 1;\n fb.stream_slot = 0;\n fb.cyclops_mat[3][0] = 0.0;\n fb.cyclops_mat[3][1] = 1.8;\n fb.cyclops_mat[3][2] = 0.0;\n\n fb.screen_mat[3][0] = 0.0; \/\/ -0.05\n fb.screen_mat[3][1] = 1.445; \/\/ 1.24\n fb.screen_mat[3][2] = -2.03;\n\n \/\/ initial model is at center screen position\n fb.model_mat = fb.screen_mat * (trans_mat * scale_mat);\n \n\n while(true){\n\n\n\n if(recon_mode != 0){\n recon_mode->read(fb.recon_mode);\n }\n\n if(stream_slot != 0){\n stream_slot->read(fb.stream_slot);\n }\n\n fb.model_mat = model->getMatrix() * (trans_mat * scale_mat);\n for(unsigned i = 0; i != glasses.size(); ++i){\n fb.cyclops_mat = glasses[i]->getMatrix();\n zmq::message_t zmqm(sizeof(feedback));\n memcpy( (unsigned char* ) zmqm.data(), (const unsigned char*) &fb, sizeof(feedback));\n sockets[i]->send(zmqm);\n }\n\n\n\n std::this_thread::sleep_for( std::chrono::milliseconds(16) );\n\n }\n\n\n if(recon_mode != 0){\n delete recon_mode;\n }\n\n if(stream_slot != 0){\n delete stream_slot;\n }\n\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"renderclipboardhandler.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/rendering\/renderwidget.h\"\n\n\/\/ Qt headers.\n#include <QApplication>\n#include <QClipboard>\n#include <QEvent>\n#include <QKeyEvent>\n#include <Qt>\n\nnamespace appleseed {\nnamespace studio {\n\nRenderClipboardHandler::RenderClipboardHandler(RenderWidget* widget)\n : m_widget(widget)\n{\n m_widget->installEventFilter(this);\n}\n\nRenderClipboardHandler::~RenderClipboardHandler()\n{\n m_widget->removeEventFilter(this);\n}\n\nbool RenderClipboardHandler::eventFilter(QObject* object, QEvent* event)\n{\n if (event->type() == QEvent::KeyPress)\n {\n const QKeyEvent* key_event = static_cast<QKeyEvent*>(event);\n\n if (key_event->modifiers() == Qt::ControlModifier && key_event->key() == Qt::Key_C)\n {\n QApplication::clipboard()->setImage(m_widget->get_image());\n return true;\n }\n }\n\n return QObject::eventFilter(object, event);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<commit_msg>print a log message when copying the render to the clipboard.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"renderclipboardhandler.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/rendering\/renderwidget.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/log.h\"\n\n\/\/ Qt headers.\n#include <QApplication>\n#include <QClipboard>\n#include <QEvent>\n#include <QKeyEvent>\n#include <Qt>\n\nnamespace appleseed {\nnamespace studio {\n\nRenderClipboardHandler::RenderClipboardHandler(RenderWidget* widget)\n : m_widget(widget)\n{\n m_widget->installEventFilter(this);\n}\n\nRenderClipboardHandler::~RenderClipboardHandler()\n{\n m_widget->removeEventFilter(this);\n}\n\nbool RenderClipboardHandler::eventFilter(QObject* object, QEvent* event)\n{\n if (event->type() == QEvent::KeyPress)\n {\n const QKeyEvent* key_event = static_cast<QKeyEvent*>(event);\n\n if (key_event->modifiers() == Qt::ControlModifier && key_event->key() == Qt::Key_C)\n {\n QApplication::clipboard()->setImage(m_widget->get_image());\n RENDERER_LOG_INFO(\"copied render to the clipboard.\");\n return true;\n }\n }\n\n return QObject::eventFilter(object, event);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n#include <unordered_map>\n#include <ros\/ros.h>\n#include <std_msgs\/Float64MultiArray.h>\n#include <std_msgs\/Float64.h>\n#include <eigen3\/Eigen\/Eigen>\n\nnamespace zubax_posekf\n{\n\nclass DebugPublisher\n{\n static constexpr unsigned QueueSize = 10;\n\n ros::NodeHandle node_;\n std::unordered_map<std::string, ros::Publisher> pubs_;\n\n template <typename Message>\n ros::Publisher& getPublisher(const std::string& name)\n {\n auto pub = pubs_.find(name);\n if (pub == pubs_.end())\n {\n (void)pubs_.insert({name, node_.advertise<Message>(name, QueueSize)});\n pub = pubs_.find(name);\n ROS_INFO(\"Debug publisher: New topic '%s' of type '%s'\",\n name.c_str(), ros::message_traits::DataType<Message>::value());\n }\n ROS_ASSERT(pub != pubs_.end());\n return pub->second;\n }\n\npublic:\n DebugPublisher(const std::string& ros_ns = \"debug\")\n : node_(ros_ns)\n { }\n\n template <class Message>\n void publishROSMessage(const std::string& name, const Message& msg)\n {\n getPublisher<Message>(name).publish(msg);\n }\n\n template <typename Derived>\n void publish(const std::string& name, const Eigen::MatrixBase<Derived>& matrix)\n {\n std_msgs::Float64MultiArray msg;\n\n msg.layout.dim.resize(2);\n msg.layout.dim[0].stride = static_cast<unsigned>(matrix.rows() * matrix.cols());\n msg.layout.dim[0].size = static_cast<unsigned>(matrix.rows());\n msg.layout.dim[1].stride = static_cast<unsigned>(matrix.cols());\n msg.layout.dim[1].size = static_cast<unsigned>(matrix.cols());\n msg.data.resize(static_cast<unsigned>(matrix.size()));\n\n {\n unsigned write_idx = 0;\n for (int row_idx = 0; row_idx < matrix.rows(); row_idx++)\n {\n \/\/ We can't access the matrix elements directly via coeff() in a generic way\n const auto row = matrix.row(row_idx);\n for (int col_idx = 0; col_idx < matrix.cols(); col_idx++)\n {\n msg.data[write_idx++] = row[col_idx];\n }\n }\n }\n\n publishROSMessage(name, msg);\n }\n\n void publish(const std::string& name, const double scalar)\n {\n std_msgs::Float64 msg;\n msg.data = scalar;\n publishROSMessage(name, msg);\n }\n};\n\n}\n<commit_msg>Debug publisher generalization<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#pragma once\n\n#include <unordered_map>\n#include <ros\/ros.h>\n#include <std_msgs\/Float64MultiArray.h>\n#include <std_msgs\/Float64.h>\n#include <eigen3\/Eigen\/Eigen>\n\nnamespace zubax_posekf\n{\n\nclass DebugPublisher\n{\n static constexpr unsigned QueueSize = 10;\n\n ros::NodeHandle node_;\n std::unordered_map<std::string, ros::Publisher> pubs_;\n\n template <typename Message>\n ros::Publisher& getPublisher(const std::string& name)\n {\n auto pub = pubs_.find(name);\n if (pub == pubs_.end())\n {\n (void)pubs_.insert({name, node_.advertise<Message>(name, QueueSize)});\n pub = pubs_.find(name);\n ROS_INFO(\"Debug publisher: New topic '%s' of type '%s'\",\n name.c_str(), ros::message_traits::DataType<Message>::value());\n }\n ROS_ASSERT(pub != pubs_.end());\n return pub->second;\n }\n\npublic:\n DebugPublisher(const std::string& ros_ns = \"debug\")\n : node_(ros_ns)\n { }\n\n template <class Message>\n void publishROSMessage(const std::string& name, const Message& msg)\n {\n getPublisher<Message>(name).publish(msg);\n }\n\n template <typename Derived>\n void publish(const std::string& name, const Eigen::MatrixBase<Derived>& matrix)\n {\n std_msgs::Float64MultiArray msg;\n\n msg.layout.dim.resize(2);\n msg.layout.dim[0].stride = static_cast<unsigned>(matrix.rows() * matrix.cols());\n msg.layout.dim[0].size = static_cast<unsigned>(matrix.rows());\n msg.layout.dim[1].stride = static_cast<unsigned>(matrix.cols());\n msg.layout.dim[1].size = static_cast<unsigned>(matrix.cols());\n msg.data.resize(static_cast<unsigned>(matrix.size()));\n\n {\n unsigned write_idx = 0;\n for (int row_idx = 0; row_idx < matrix.rows(); row_idx++)\n {\n \/\/ We can't access the matrix elements directly via coeff() in a generic way\n const auto row = matrix.row(row_idx);\n for (int col_idx = 0; col_idx < matrix.cols(); col_idx++)\n {\n msg.data[write_idx++] = static_cast<double>(row[col_idx]);\n }\n }\n }\n\n publishROSMessage(name, msg);\n }\n\n void publish(const std::string& name, const double scalar)\n {\n std_msgs::Float64 msg;\n msg.data = scalar;\n publishROSMessage(name, msg);\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This material contains unpublished, proprietary software of \n * Entropic Research Laboratory, Inc. Any reproduction, distribution, \n * or publication of this work must be authorized in writing by Entropic \n * Research Laboratory, Inc., and must bear the notice: \n *\n * \"Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. \n * All rights reserved\"\n *\n * The copyright notice above does not evidence any actual or intended \n * publication of this source code. \n *\n * Written by: Derek Lin\n * Checked by:\n * Revised by: David Talkin\n *\n * Brief description: Estimates F0 using normalized cross correlation and\n * dynamic programming.\n *\n *\/\n\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <malloc.h>\n#include <limits.h>\n#include <stdexcept>\n#include <sstream>\n#include <vector>\n\n#include \"f0.h\"\n\nint\t debug_level = 0;\n\n\/\/ ----------------------------------------\n\/\/ Externs\nextern \"C\" {\nint init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep);\nint dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par,\n float **f0p_pt, float **vuvp_pt, float **rms_speech_pt,\n float **acpkp_pt, int *vecsize, int last_time);\n}\n\n\n\f\nnamespace GetF0 {\n\f\n\n\/\/ EXCEPTIONS\n\n#define CREATE_ERROR(_Name, _Base) \\\n class _Name : public _Base { \\\n public: \\\n explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \\\n };\n\nCREATE_ERROR(RuntimeError, std::runtime_error);\nCREATE_ERROR(LogicError, std::logic_error);\nCREATE_ERROR(ParameterError, RuntimeError);\nCREATE_ERROR(ProcessingError, RuntimeError);\nCREATE_ERROR(AssertionError, LogicError);\n\n#undef CREATE_ERROR\n\n\n#define THROW_ERROR(condition, exception, s) \\\n do { \\\n if (condition) { \\\n std::stringstream ss; \\\n ss << s; \\\n throw exception(ss.str()); \\\n } \\\n } while (0);\n\n\f\n\nclass GetF0 {\npublic:\n GetF0();\n\n int derp();\n\nprotected:\n\n \/\/\/ @brief Provide a `buffer` we can read `num_records` samples\n \/\/\/ from, returning how many samples we can read. Returning less\n \/\/\/ than requested samples is a termination condition.\n \/\/\/\n \/\/\/ `buffer` is not guaranteed to not be written to. (TODO: check to\n \/\/\/ see if buffer can be written to.)\n virtual long readSamples(float **buffer, long num_records) { return 0; }\n\n \/\/\/ @brief Like `readSamples`, but read `step` samples from previous\n \/\/\/ buffer.\n virtual long readSamplesOverlap(float **buffer, long num_records, long step)\n {\n return 0;\n }\n\n virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech,\n float *acpkp, int vecsize)\n {\n }\n\nprivate:\n\n static void check_f0_params(F0_params *par, double sample_freq);\n\n};\n\n\n\nint GetF0::derp()\n{\n int done;\n long buff_size, actsize;\n double sf, output_starts, frame_rate;\n float *f0p, *vuvp, *rms_speech, *acpkp;\n int i, vecsize;\n long sdstep = 0;\n\n F0_params par;\n par.cand_thresh = 0.3;\n par.lag_weight = 0.3;\n par.freq_weight = 0.02;\n par.trans_cost = 0.005;\n par.trans_amp = 0.5;\n par.trans_spec = 0.5;\n par.voice_bias = 0.0;\n par.double_cost = 0.35;\n par.min_f0 = 50;\n par.max_f0 = 550;\n par.frame_step = 0.01;\n par.wind_dur = 0.0075;\n par.n_cands = 20;\n par.mean_f0 = 200; \/* unused *\/\n par.mean_f0_weight = 0.0; \/* unused *\/\n par.conditioning = 0; \/*unused *\/\n\n#define SW_CUSTOMIZABLE(x) \/\/TODO(sw)\n SW_CUSTOMIZABLE(debug_level);\n\n SW_CUSTOMIZABLE(par.frame_step);\n SW_CUSTOMIZABLE(par.cand_thresh);\n SW_CUSTOMIZABLE(par.lag_weight);\n SW_CUSTOMIZABLE(par.freq_weight);\n SW_CUSTOMIZABLE(par.trans_cost);\n SW_CUSTOMIZABLE(par.trans_amp);\n SW_CUSTOMIZABLE(par.trans_spec);\n SW_CUSTOMIZABLE(par.voice_bias);\n SW_CUSTOMIZABLE(par.double_cost);\n SW_CUSTOMIZABLE(par.min_f0);\n SW_CUSTOMIZABLE(par.max_f0);\n SW_CUSTOMIZABLE(par.wind_dur);\n SW_CUSTOMIZABLE(par.n_cands);\n#undef SW_CUSTOMIZABLE\n\n#define SW_FILE_PARAMS(x, y) \/\/TODO (sw)\n SW_FILE_PARAMS(sf, \"sampling frequency\");\n#undef SW_FILE_PARAMS\n\n check_f0_params(&par, sf);\n\n \/*SW: Removed range restricter, but this may be interesting:\n if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then\n input range too small*\/\n\n output_starts = par.wind_dur\/2.0;\n \/* Average delay due to loc. of ref. window center. *\/\n frame_rate = 1.0 \/ par.frame_step;\n\n\n \/* Initialize variables in get_f0.c; allocate data structures;\n * determine length and overlap of input frames to read.\n *\n * sw: Looks like init_dp_f0 never returns errors via rcode, but put\n * under assertion.\n *\/\n THROW_ERROR(init_dp_f0(sf, &par, &buff_size, &sdstep) ||\n buff_size > INT_MAX || sdstep > INT_MAX,\n AssertionError, \"problem in init_dp_f0().\");\n\n \/*SW: pass sdstep to caller so it knows how much we have to buffer. *\/\n\n if (debug_level)\n Fprintf(stderr, \"init_dp_f0 returned buff_size %ld, sdstep %ld.\\n\",\n\t buff_size, sdstep);\n\n float* fdata = nullptr;\n actsize = readSamples(&fdata, buff_size);\n\n while (1) {\n\n done = (actsize < buff_size);\n\n THROW_ERROR(dp_f0(fdata, (int)actsize, (int)sdstep, sf, &par, &f0p, &vuvp,\n &rms_speech, &acpkp, &vecsize, done),\n ProcessingError, \"problem in dp_f0().\");\n\n writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize);\n\n if (done)\n break;\n\n actsize = readSamplesOverlap(&fdata, buff_size, sdstep);\n\n }\n\n exit(0);\n}\n\n\/*\n * Some consistency checks on parameter values.\n *\/\nvoid GetF0::check_f0_params(F0_params *par, double sample_freq)\n{\n std::vector<std::string> errors;\n\n if ((par->cand_thresh < 0.01) || (par->cand_thresh > 0.99)) {\n errors.push_back(\"cand_thresh parameter must be between [0.01, 0.99].\");\n }\n if ((par->wind_dur > .1) || (par->wind_dur < .0001)) {\n errors.push_back(\"wind_dur parameter must be between [0.0001, 0.1].\");\n }\n if ((par->n_cands > 100) || (par->n_cands < 3)) {\n errors.push_back(\"n_cands parameter must be between [3,100].\");\n }\n if ((par->max_f0 <= par->min_f0) || (par->max_f0 >= (sample_freq \/ 2.0)) ||\n (par->min_f0 < (sample_freq \/ 10000.0))) {\n errors.push_back(\n \"min(max)_f0 parameter inconsistent with sampling frequency.\");\n }\n double dstep =\n ((double)((int)(0.5 + (sample_freq * par->frame_step)))) \/ sample_freq;\n if (dstep != par->frame_step) {\n if (debug_level)\n Fprintf(stderr,\n \"Frame step set to %f to exactly match signal sample rate.\\n\",\n dstep);\n par->frame_step = dstep;\n }\n if ((par->frame_step > 0.1) || (par->frame_step < (1.0 \/ sample_freq))) {\n errors.push_back(\n \"frame_step parameter must be between [1\/sampling rate, \"\n \"0.1].\");\n }\n\n if (!errors.empty()) {\n std::stringstream ss;\n bool first = true;\n for (auto &error : errors) {\n if (!first) ss << \" \";\n ss << error;\n }\n\n THROW_ERROR(true, ParameterError, ss.str());\n }\n}\n\n} \/\/ namespace GetF0\n<commit_msg>Pulled out init_params<commit_after>\/*\n * This material contains unpublished, proprietary software of \n * Entropic Research Laboratory, Inc. Any reproduction, distribution, \n * or publication of this work must be authorized in writing by Entropic \n * Research Laboratory, Inc., and must bear the notice: \n *\n * \"Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. \n * All rights reserved\"\n *\n * The copyright notice above does not evidence any actual or intended \n * publication of this source code. \n *\n * Written by: Derek Lin\n * Checked by:\n * Revised by: David Talkin\n *\n * Brief description: Estimates F0 using normalized cross correlation and\n * dynamic programming.\n *\n *\/\n\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <malloc.h>\n#include <limits.h>\n#include <stdexcept>\n#include <sstream>\n#include <vector>\n\n#include \"f0.h\"\n\nint\t debug_level = 0;\n\n\/\/ ----------------------------------------\n\/\/ Externs\nextern \"C\" {\nint init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep);\nint dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par,\n float **f0p_pt, float **vuvp_pt, float **rms_speech_pt,\n float **acpkp_pt, int *vecsize, int last_time);\n}\n\n\n\f\nnamespace GetF0 {\n\f\n\n\/\/ EXCEPTIONS\n\n#define CREATE_ERROR(_Name, _Base) \\\n class _Name : public _Base { \\\n public: \\\n explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \\\n };\n\nCREATE_ERROR(RuntimeError, std::runtime_error);\nCREATE_ERROR(LogicError, std::logic_error);\nCREATE_ERROR(ParameterError, RuntimeError);\nCREATE_ERROR(ProcessingError, RuntimeError);\nCREATE_ERROR(AssertionError, LogicError);\n\n#undef CREATE_ERROR\n\n\n#define THROW_ERROR(condition, exception, s) \\\n do { \\\n if (condition) { \\\n std::stringstream ss; \\\n ss << s; \\\n throw exception(ss.str()); \\\n } \\\n } while (0);\n\n\f\n\nclass GetF0 {\npublic:\n GetF0();\n\n int derp();\n\nprotected:\n\n \/\/\/ @brief Provide a `buffer` we can read `num_records` samples\n \/\/\/ from, returning how many samples we can read. Returning less\n \/\/\/ than requested samples is a termination condition.\n \/\/\/\n \/\/\/ `buffer` is not guaranteed to not be written to. (TODO: check to\n \/\/\/ see if buffer can be written to.)\n virtual long readSamples(float **buffer, long num_records) { return 0; }\n\n \/\/\/ @brief Like `readSamples`, but read `step` samples from previous\n \/\/\/ buffer.\n virtual long readSamplesOverlap(float **buffer, long num_records, long step)\n {\n return 0;\n }\n\n virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech,\n float *acpkp, int vecsize)\n {\n }\n\nprivate:\n\n F0_params m_par;\n\n void init_params();\n\n static void check_f0_params(F0_params *par, double sample_freq);\n\n};\n\nGetF0::GetF0()\n{\n init_params();\n}\n\nvoid GetF0::init_params()\n{\n m_par.cand_thresh = 0.3;\n m_par.lag_weight = 0.3;\n m_par.freq_weight = 0.02;\n m_par.trans_cost = 0.005;\n m_par.trans_amp = 0.5;\n m_par.trans_spec = 0.5;\n m_par.voice_bias = 0.0;\n m_par.double_cost = 0.35;\n m_par.min_f0 = 50;\n m_par.max_f0 = 550;\n m_par.frame_step = 0.01;\n m_par.wind_dur = 0.0075;\n m_par.n_cands = 20;\n m_par.mean_f0 = 200; \/* unused *\/\n m_par.mean_f0_weight = 0.0; \/* unused *\/\n m_par.conditioning = 0; \/*unused *\/\n}\n\nint GetF0::derp()\n{\n int done;\n long buff_size, actsize;\n double sf, output_starts, frame_rate;\n float *f0p, *vuvp, *rms_speech, *acpkp;\n int i, vecsize;\n long sdstep = 0;\n\n\n#define SW_CUSTOMIZABLE(x) \/\/TODO(sw)\n SW_CUSTOMIZABLE(debug_level);\n\n SW_CUSTOMIZABLE(m_par.frame_step);\n SW_CUSTOMIZABLE(m_par.cand_thresh);\n SW_CUSTOMIZABLE(m_par.lag_weight);\n SW_CUSTOMIZABLE(m_par.freq_weight);\n SW_CUSTOMIZABLE(m_par.trans_cost);\n SW_CUSTOMIZABLE(m_par.trans_amp);\n SW_CUSTOMIZABLE(m_par.trans_spec);\n SW_CUSTOMIZABLE(m_par.voice_bias);\n SW_CUSTOMIZABLE(m_par.double_cost);\n SW_CUSTOMIZABLE(m_par.min_f0);\n SW_CUSTOMIZABLE(m_par.max_f0);\n SW_CUSTOMIZABLE(m_par.wind_dur);\n SW_CUSTOMIZABLE(m_par.n_cands);\n#undef SW_CUSTOMIZABLE\n\n#define SW_FILE_PARAMS(x, y) \/\/TODO (sw)\n SW_FILE_PARAMS(sf, \"sampling frequency\");\n#undef SW_FILE_PARAMS\n\n check_f0_params(&m_par, sf);\n\n \/*SW: Removed range restricter, but this may be interesting:\n if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then\n input range too small*\/\n\n output_starts = m_par.wind_dur\/2.0;\n \/* Average delay due to loc. of ref. window center. *\/\n frame_rate = 1.0 \/ m_par.frame_step;\n\n\n \/* Initialize variables in get_f0.c; allocate data structures;\n * determine length and overlap of input frames to read.\n *\n * sw: Looks like init_dp_f0 never returns errors via rcode, but put\n * under assertion.\n *\/\n THROW_ERROR(init_dp_f0(sf, &m_par, &buff_size, &sdstep) ||\n buff_size > INT_MAX || sdstep > INT_MAX,\n AssertionError, \"problem in init_dp_f0().\");\n\n \/*SW: pass sdstep to caller so it knows how much we have to buffer. *\/\n\n if (debug_level)\n Fprintf(stderr, \"init_dp_f0 returned buff_size %ld, sdstep %ld.\\n\",\n\t buff_size, sdstep);\n\n float* fdata = nullptr;\n actsize = readSamples(&fdata, buff_size);\n\n while (1) {\n\n done = (actsize < buff_size);\n\n THROW_ERROR(dp_f0(fdata, (int)actsize, (int)sdstep, sf, &m_par, &f0p, &vuvp,\n &rms_speech, &acpkp, &vecsize, done),\n ProcessingError, \"problem in dp_f0().\");\n\n writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize);\n\n if (done)\n break;\n\n actsize = readSamplesOverlap(&fdata, buff_size, sdstep);\n\n }\n\n exit(0);\n}\n\n\/*\n * Some consistency checks on parameter values.\n *\/\nvoid GetF0::check_f0_params(F0_params *par, double sample_freq)\n{\n std::vector<std::string> errors;\n\n if ((par->cand_thresh < 0.01) || (par->cand_thresh > 0.99)) {\n errors.push_back(\"cand_thresh parameter must be between [0.01, 0.99].\");\n }\n if ((par->wind_dur > .1) || (par->wind_dur < .0001)) {\n errors.push_back(\"wind_dur parameter must be between [0.0001, 0.1].\");\n }\n if ((par->n_cands > 100) || (par->n_cands < 3)) {\n errors.push_back(\"n_cands parameter must be between [3,100].\");\n }\n if ((par->max_f0 <= par->min_f0) || (par->max_f0 >= (sample_freq \/ 2.0)) ||\n (par->min_f0 < (sample_freq \/ 10000.0))) {\n errors.push_back(\n \"min(max)_f0 parameter inconsistent with sampling frequency.\");\n }\n double dstep =\n ((double)((int)(0.5 + (sample_freq * par->frame_step)))) \/ sample_freq;\n if (dstep != par->frame_step) {\n if (debug_level)\n Fprintf(stderr,\n \"Frame step set to %f to exactly match signal sample rate.\\n\",\n dstep);\n par->frame_step = dstep;\n }\n if ((par->frame_step > 0.1) || (par->frame_step < (1.0 \/ sample_freq))) {\n errors.push_back(\n \"frame_step parameter must be between [1\/sampling rate, \"\n \"0.1].\");\n }\n\n if (!errors.empty()) {\n std::stringstream ss;\n bool first = true;\n for (auto &error : errors) {\n if (!first) ss << \" \";\n ss << error;\n }\n\n THROW_ERROR(true, ParameterError, ss.str());\n }\n}\n\n} \/\/ namespace GetF0\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/file\/FeatureFS.hpp>\n\n#include <nix\/util\/util.hpp>\n#include <nix\/DataArray.hpp>\n#include <nix\/file\/DataArrayFS.hpp>\n\n\nusing namespace std;\nusing namespace nix::base;\n\nnamespace nix {\nnamespace file {\n\n\nstring linkTypeToString(LinkType link_type) {\n static vector<string> type_names = {\"tagged\", \"untagged\", \"indexed\"};\n return type_names[static_cast<int>(link_type)];\n}\n\n\nLinkType linkTypeFromString(const string &str) {\n if (str == \"tagged\")\n return LinkType::Tagged;\n else if (str == \"untagged\")\n return LinkType::Untagged;\n else if (str == \"indexed\")\n return LinkType::Indexed;\n else\n throw runtime_error(\"Unable to create a LinkType from the string: \" + str);\n}\n\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc)\n : EntityFS(file, loc), block(block)\n{\n}\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,\n const string &id, DataArray data, LinkType link_type)\n : FeatureFS(file, block, loc, id, data, link_type, util::getTime())\n{\n}\n\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,\n const string &id, DataArray data, LinkType link_type, time_t time)\n : EntityFS(file, loc, id, time), block(block)\n{\n linkType(link_type);\n \/\/ TODO: the line below currently throws an exception if the DataArray\n \/\/ is not in block - to consider if we prefer copying it to the block\n this->data(data.id());\n}\n\n\nvoid FeatureFS::linkType(LinkType link_type) {\n \/\/ linkTypeToString will generate an error if link_type is invalid\n setAttr(\"link_type\", linkTypeToString(link_type));\n forceUpdatedAt();\n}\n\n\nvoid FeatureFS::data(const std::string &name_or_id) {\n if (name_or_id.empty())\n throw EmptyString(\"data(id)\");\n if (!block->hasDataArray(name_or_id))\n throw std::runtime_error(\"FeatureFS::data: DataArray not found in block!\");\n\n auto target = dynamic_pointer_cast<DataArrayFS>(block->getDataArray(name_or_id));\n \/\/ FIXME create Link\n \/\/group().createLink(target->group(), \"data\");\n forceUpdatedAt();\n}\n\n\nshared_ptr<IDataArray> FeatureFS::data() const {\n shared_ptr<IDataArray> da;\n \/*\n bool error = false;\n \n if (group().hasGroup(\"data\")) {\n Group other_group = group().openGroup(\"data\", false);\n da = make_shared<DataArrayHDF5>(file(), block, other_group);\n if (!block->hasDataArray(da->id())) error = true;\n }\n else error = true;\n\n \/\/ NOTE: we check that link exists in both places, here & in entity\n \/\/ if error = true it was missing in one of the two\n if (error)\n throw std::runtime_error(\"FeatureHDF5::data: DataArray not found!\");\n *\/\n return da;\n}\n\n\nLinkType FeatureFS::linkType() const {\n if (hasAttr(\"link_type\")) {\n string link_type;\n getAttr(\"link_type\", link_type);\n return linkTypeFromString(link_type);\n } else {\n throw MissingAttr(\"data\");\n }\n}\n\n\nFeatureFS::~FeatureFS() {}\n\n} \/\/ ns nix::file\n} \/\/ ns nix\n<commit_msg>[file_backend\/Feature] avoid warning...<commit_after>\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <nix\/file\/FeatureFS.hpp>\n\n#include <nix\/util\/util.hpp>\n#include <nix\/DataArray.hpp>\n#include <nix\/file\/DataArrayFS.hpp>\n\n\nusing namespace std;\nusing namespace nix::base;\n\nnamespace nix {\nnamespace file {\n\n\nstring linkTypeToString(LinkType link_type) {\n static vector<string> type_names = {\"tagged\", \"untagged\", \"indexed\"};\n return type_names[static_cast<int>(link_type)];\n}\n\n\nLinkType linkTypeFromString(const string &str) {\n if (str == \"tagged\")\n return LinkType::Tagged;\n else if (str == \"untagged\")\n return LinkType::Untagged;\n else if (str == \"indexed\")\n return LinkType::Indexed;\n else\n throw runtime_error(\"Unable to create a LinkType from the string: \" + str);\n}\n\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc)\n : EntityFS(file, loc), block(block)\n{\n}\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,\n const string &id, DataArray data, LinkType link_type)\n : FeatureFS(file, block, loc, id, data, link_type, util::getTime())\n{\n}\n\n\nFeatureFS::FeatureFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,\n const string &id, DataArray data, LinkType link_type, time_t time)\n : EntityFS(file, loc, id, time), block(block)\n{\n linkType(link_type);\n \/\/ TODO: the line below currently throws an exception if the DataArray\n \/\/ is not in block - to consider if we prefer copying it to the block\n this->data(data.id());\n}\n\n\nvoid FeatureFS::linkType(LinkType link_type) {\n \/\/ linkTypeToString will generate an error if link_type is invalid\n setAttr(\"link_type\", linkTypeToString(link_type));\n forceUpdatedAt();\n}\n\n\nvoid FeatureFS::data(const std::string &name_or_id) {\n if (name_or_id.empty())\n throw EmptyString(\"data(id)\");\n if (!block->hasDataArray(name_or_id))\n throw std::runtime_error(\"FeatureFS::data: DataArray not found in block!\");\n\n auto target = dynamic_pointer_cast<DataArrayFS>(block->getDataArray(name_or_id));\n \/\/ FIXME create Link\n \/\/group().createLink(target->group(), \"data\");\n forceUpdatedAt();\n}\n\n\nshared_ptr<IDataArray> FeatureFS::data() const {\n shared_ptr<IDataArray> da;\n \/*\n bool error = false;\n\n if (group().hasGroup(\"data\")) {\n Group other_group = group().openGroup(\"data\", false);\n da = make_shared<DataArrayHDF5>(file(), block, other_group);\n if (!block->hasDataArray(da->id())) error = true;\n }\n else error = true;\n\n \/\/ NOTE: we check that link exists in both places, here & in entity\n \/\/ if error = true it was missing in one of the two\n if (error)\n throw std::runtime_error(\"FeatureHDF5::data: DataArray not found!\");\n *\/\n return da;\n}\n\n\nLinkType FeatureFS::linkType() const {\n if (hasAttr(\"link_type\")) {\n string link_type;\n getAttr(\"link_type\", link_type);\n return linkTypeFromString(link_type);\n } else {\n throw MissingAttr(\"data\");\n }\n}\n\n\nFeatureFS::~FeatureFS() {}\n\n} \/\/ ns nix::file\n} \/\/ ns nix\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"MethodSimilarityOrderer.h\"\n\n#include \"DexInstruction.h\"\n#include \"Show.h\"\n#include \"Trace.h\"\n#include \"WorkQueue.h\"\n\nnamespace {\n\/\/ Similarity score for each candidate method, based on the number of\n\/\/ shared, missing and additional hash ids when compared to the previously\n\/\/ chosen method.\nstruct Score {\n uint32_t shared{0};\n uint32_t missing{0};\n uint32_t additional{0};\n int32_t value() const { return 2 * shared - missing - 2 * additional; }\n};\n\ntemplate <typename T>\nstruct CountingFakeOutputIterator {\n uint32_t& counter;\n T fake;\n explicit CountingFakeOutputIterator(uint32_t& c) : counter(c) {}\n CountingFakeOutputIterator& operator++() {\n counter++;\n return *this;\n }\n T& operator*() { return fake; }\n};\n}; \/\/ namespace\n\nvoid MethodSimilarityOrderer::gather_code_hash_ids(\n const std::vector<DexInstruction*>& instructions,\n std::vector<CodeHashId>& code_hash_ids) {\n\n std::unordered_set<StableHash> stable_hashes;\n\n \/\/ For any instruction,we can compute a (stable) hash representing\n \/\/ it.\n for (size_t i = 0; i < instructions.size(); i++) {\n uint64_t code_hash{0};\n auto insn = instructions.at(i);\n auto op = insn->opcode();\n code_hash = code_hash * 23 + op;\n if (insn->has_literal()) {\n code_hash = code_hash * 7 + insn->get_literal();\n }\n if (insn->has_range()) {\n code_hash =\n (code_hash * 11 + insn->range_base()) * 11 + insn->range_size();\n }\n if (insn->has_dest()) {\n code_hash = code_hash * 13 + insn->dest();\n }\n for (unsigned j = 0; j < insn->srcs_size(); j++) {\n code_hash = code_hash * 17 + insn->src(j);\n }\n stable_hashes.insert(code_hash);\n };\n\n \/\/ Initialize the vector for code hash.\n \/\/ Publish code hash ids from stable hashes.\n code_hash_ids.reserve(stable_hashes.size());\n for (StableHash stable_hash : stable_hashes) {\n if (m_stable_hash_to_code_hash_id.count(stable_hash) == 0) {\n \/\/ Assign a unique code hash id if it appears for the first time.\n auto code_hash_id = m_stable_hash_to_code_hash_id.size();\n m_stable_hash_to_code_hash_id[stable_hash] = code_hash_id;\n }\n code_hash_ids.push_back(m_stable_hash_to_code_hash_id[stable_hash]);\n }\n \/\/ Sort the code hash Ids to check the overlaps in the linear time.\n std::sort(code_hash_ids.begin(), code_hash_ids.end());\n}\n\n\/\/ For the given code hash ids (i) and code hash ids (j), get score for j\n\/\/ against i.\nstatic inline Score get_score(\n const std::vector<MethodSimilarityOrderer::CodeHashId>& code_hash_ids_i,\n const std::vector<MethodSimilarityOrderer::CodeHashId>& code_hash_ids_j) {\n uint32_t i_size = code_hash_ids_i.size();\n uint32_t j_size = code_hash_ids_j.size();\n\n Score score;\n std::set_intersection(\n code_hash_ids_i.begin(), code_hash_ids_i.end(), code_hash_ids_j.begin(),\n code_hash_ids_j.end(),\n CountingFakeOutputIterator<MethodSimilarityOrderer::CodeHashId>(\n score.shared));\n\n score.missing = i_size - score.shared;\n score.additional = j_size - score.shared;\n\n return score;\n}\n\nvoid MethodSimilarityOrderer::compute_score() {\n m_score_map.clear();\n m_score_map.resize(m_id_to_method.size());\n\n \/\/ Maximum number of code items can be 65536.\n redex_assert(m_id_to_method.size() <= (1 << 16));\n\n std::vector<MethodId> indices(m_id_to_method.size());\n std::iota(indices.begin(), indices.end(), 0);\n workqueue_run<MethodId>(\n [&](MethodId i_id) {\n const auto& code_hash_ids_i = m_method_id_to_code_hash_ids[i_id];\n std::unordered_map<ScoreValue, boost::dynamic_bitset<>> score_map;\n\n for (uint32_t j_id = 0; j_id < (uint32_t)m_id_to_method.size();\n j_id++) {\n if (i_id == j_id) {\n continue;\n }\n\n const auto& code_hash_ids_j = m_method_id_to_code_hash_ids[j_id];\n auto score = get_score(code_hash_ids_i, code_hash_ids_j);\n if (score.value() >= 0) {\n auto& method_id_bitset = score_map[score.value()];\n if (method_id_bitset.size() <= j_id) {\n method_id_bitset.resize(j_id + 1);\n }\n method_id_bitset.set(static_cast<size_t>(j_id));\n }\n }\n\n if (!score_map.empty()) {\n std::map<ScoreValue, boost::dynamic_bitset<>,\n std::greater<ScoreValue>>\n map;\n \/\/ Mapping from score value (key) to Method Ids. The key is in a\n \/\/ decreasing score order. Becuase it iterates Method Id in order,\n \/\/ the vector is already sorted by Method index (source order).\n for (auto&& [score_value, method_ids] : score_map) {\n map[score_value] = std::move(method_ids);\n }\n m_score_map[i_id] = std::move(map);\n }\n },\n indices);\n}\n\nvoid MethodSimilarityOrderer::insert(DexMethod* method) {\n always_assert(m_method_to_id.count(method) == 0);\n \/\/ While the number of methods can reach 65536 (2^16), at\n \/\/ this stage not all methods have been added, so we assert that\n \/\/ the number can fit on 16 bits and safely be assigned to a MethodId index.\n redex_assert(m_id_to_method.size() < (1 << 16));\n MethodId index = m_id_to_method.size();\n m_id_to_method.emplace(index, method);\n m_method_to_id.emplace(method, index);\n\n auto& code_hash_ids = m_method_id_to_code_hash_ids[index];\n auto* code = method->get_dex_code();\n if (code) {\n gather_code_hash_ids(code->get_instructions(), code_hash_ids);\n }\n}\n\nboost::optional<MethodSimilarityOrderer::MethodId>\nMethodSimilarityOrderer::get_next() {\n \/\/ Clear best candidates.\n if (m_id_to_method.empty()) {\n return {};\n }\n\n if (m_last_method_id != boost::none) {\n \/\/ Iterate m_score_map from the highest score..\n for (const auto& [score, method_id_bitset] :\n m_score_map[*m_last_method_id]) {\n for (auto meth_id = method_id_bitset.find_first();\n meth_id != boost::dynamic_bitset<>::npos;\n meth_id = method_id_bitset.find_next(meth_id)) {\n \/\/ The first match is the one with the highest score\n \/\/ at the smallest index in the source order.\n if (m_id_to_method.count(static_cast<MethodId>(meth_id))) {\n TRACE(OPUT, 3,\n \"[method-similarity-orderer] selected %s with score %d\",\n SHOW(m_id_to_method[static_cast<MethodId>(meth_id)]), score);\n return meth_id;\n }\n }\n }\n }\n boost::optional<MethodId> best_method_id = m_id_to_method.begin()->first;\n TRACE(OPUT,\n 3,\n \"[method-similarity-orderer] reverted to %s\",\n SHOW(*best_method_id));\n return best_method_id;\n}\n\nvoid MethodSimilarityOrderer::remove_method(DexMethod* meth) {\n if (!m_method_to_id.count(meth)) return;\n\n auto method_id = m_method_to_id[meth];\n m_id_to_method.erase(method_id);\n m_method_to_id.erase(meth);\n}\n\nvoid MethodSimilarityOrderer::order(std::vector<DexMethod*>& methods) {\n Timer t(\"Reordering methods by similarity\");\n\n for (auto* method : methods) {\n insert(method);\n }\n\n methods.clear();\n\n \/\/ Compute scores among methods in parallel.\n compute_score();\n\n m_last_method_id = boost::none;\n for (boost::optional<MethodId> best_method_id = get_next();\n best_method_id != boost::none;\n best_method_id = get_next()) {\n m_last_method_id = best_method_id;\n auto meth = m_id_to_method[*m_last_method_id];\n methods.push_back(meth);\n remove_method(meth);\n }\n}\n<commit_msg>Hash callee method names for better compression<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"MethodSimilarityOrderer.h\"\n\n#include \"DexInstruction.h\"\n#include \"Show.h\"\n#include \"Trace.h\"\n#include \"WorkQueue.h\"\n\nnamespace {\n\/\/ Similarity score for each candidate method, based on the number of\n\/\/ shared, missing and additional hash ids when compared to the previously\n\/\/ chosen method.\nstruct Score {\n uint32_t shared{0};\n uint32_t missing{0};\n uint32_t additional{0};\n int32_t value() const { return 2 * shared - missing - 2 * additional; }\n};\n\ntemplate <typename T>\nstruct CountingFakeOutputIterator {\n uint32_t& counter;\n T fake;\n explicit CountingFakeOutputIterator(uint32_t& c) : counter(c) {}\n CountingFakeOutputIterator& operator++() {\n counter++;\n return *this;\n }\n T& operator*() { return fake; }\n};\n}; \/\/ namespace\n\nvoid MethodSimilarityOrderer::gather_code_hash_ids(\n const std::vector<DexInstruction*>& instructions,\n std::vector<CodeHashId>& code_hash_ids) {\n\n std::unordered_set<StableHash> stable_hashes;\n\n \/\/ For any instruction,we can compute a (stable) hash representing\n \/\/ it.\n for (size_t i = 0; i < instructions.size(); i++) {\n uint64_t code_hash{0};\n auto insn = instructions.at(i);\n auto op = insn->opcode();\n code_hash = code_hash * 23 + op;\n if (insn->has_literal()) {\n code_hash = code_hash * 7 + insn->get_literal();\n }\n if (insn->has_range()) {\n code_hash =\n (code_hash * 11 + insn->range_base()) * 11 + insn->range_size();\n }\n if (insn->has_dest()) {\n code_hash = code_hash * 13 + insn->dest();\n }\n for (unsigned j = 0; j < insn->srcs_size(); j++) {\n code_hash = code_hash * 17 + insn->src(j);\n }\n if (insn->has_method()) {\n auto callee = ((DexOpcodeMethod*)insn)->get_method();\n stable_hashes.insert(std::hash<std::string>{}(show(callee)));\n }\n stable_hashes.insert(code_hash);\n };\n\n \/\/ Initialize the vector for code hash.\n \/\/ Publish code hash ids from stable hashes.\n code_hash_ids.reserve(stable_hashes.size());\n for (StableHash stable_hash : stable_hashes) {\n if (m_stable_hash_to_code_hash_id.count(stable_hash) == 0) {\n \/\/ Assign a unique code hash id if it appears for the first time.\n auto code_hash_id = m_stable_hash_to_code_hash_id.size();\n m_stable_hash_to_code_hash_id[stable_hash] = code_hash_id;\n }\n code_hash_ids.push_back(m_stable_hash_to_code_hash_id[stable_hash]);\n }\n \/\/ Sort the code hash Ids to check the overlaps in the linear time.\n std::sort(code_hash_ids.begin(), code_hash_ids.end());\n}\n\n\/\/ For the given code hash ids (i) and code hash ids (j), get score for j\n\/\/ against i.\nstatic inline Score get_score(\n const std::vector<MethodSimilarityOrderer::CodeHashId>& code_hash_ids_i,\n const std::vector<MethodSimilarityOrderer::CodeHashId>& code_hash_ids_j) {\n uint32_t i_size = code_hash_ids_i.size();\n uint32_t j_size = code_hash_ids_j.size();\n\n Score score;\n std::set_intersection(\n code_hash_ids_i.begin(), code_hash_ids_i.end(), code_hash_ids_j.begin(),\n code_hash_ids_j.end(),\n CountingFakeOutputIterator<MethodSimilarityOrderer::CodeHashId>(\n score.shared));\n\n score.missing = i_size - score.shared;\n score.additional = j_size - score.shared;\n\n return score;\n}\n\nvoid MethodSimilarityOrderer::compute_score() {\n m_score_map.clear();\n m_score_map.resize(m_id_to_method.size());\n\n \/\/ Maximum number of code items can be 65536.\n redex_assert(m_id_to_method.size() <= (1 << 16));\n\n std::vector<MethodId> indices(m_id_to_method.size());\n std::iota(indices.begin(), indices.end(), 0);\n workqueue_run<MethodId>(\n [&](MethodId i_id) {\n const auto& code_hash_ids_i = m_method_id_to_code_hash_ids[i_id];\n std::unordered_map<ScoreValue, boost::dynamic_bitset<>> score_map;\n\n for (uint32_t j_id = 0; j_id < (uint32_t)m_id_to_method.size();\n j_id++) {\n if (i_id == j_id) {\n continue;\n }\n\n const auto& code_hash_ids_j = m_method_id_to_code_hash_ids[j_id];\n auto score = get_score(code_hash_ids_i, code_hash_ids_j);\n if (score.value() >= 0) {\n auto& method_id_bitset = score_map[score.value()];\n if (method_id_bitset.size() <= j_id) {\n method_id_bitset.resize(j_id + 1);\n }\n method_id_bitset.set(static_cast<size_t>(j_id));\n }\n }\n\n if (!score_map.empty()) {\n std::map<ScoreValue, boost::dynamic_bitset<>,\n std::greater<ScoreValue>>\n map;\n \/\/ Mapping from score value (key) to Method Ids. The key is in a\n \/\/ decreasing score order. Becuase it iterates Method Id in order,\n \/\/ the vector is already sorted by Method index (source order).\n for (auto&& [score_value, method_ids] : score_map) {\n map[score_value] = std::move(method_ids);\n }\n m_score_map[i_id] = std::move(map);\n }\n },\n indices);\n}\n\nvoid MethodSimilarityOrderer::insert(DexMethod* method) {\n always_assert(m_method_to_id.count(method) == 0);\n \/\/ While the number of methods can reach 65536 (2^16), at\n \/\/ this stage not all methods have been added, so we assert that\n \/\/ the number can fit on 16 bits and safely be assigned to a MethodId index.\n redex_assert(m_id_to_method.size() < (1 << 16));\n MethodId index = m_id_to_method.size();\n m_id_to_method.emplace(index, method);\n m_method_to_id.emplace(method, index);\n\n auto& code_hash_ids = m_method_id_to_code_hash_ids[index];\n auto* code = method->get_dex_code();\n if (code) {\n gather_code_hash_ids(code->get_instructions(), code_hash_ids);\n }\n}\n\nboost::optional<MethodSimilarityOrderer::MethodId>\nMethodSimilarityOrderer::get_next() {\n \/\/ Clear best candidates.\n if (m_id_to_method.empty()) {\n return {};\n }\n\n if (m_last_method_id != boost::none) {\n \/\/ Iterate m_score_map from the highest score..\n for (const auto& [score, method_id_bitset] :\n m_score_map[*m_last_method_id]) {\n for (auto meth_id = method_id_bitset.find_first();\n meth_id != boost::dynamic_bitset<>::npos;\n meth_id = method_id_bitset.find_next(meth_id)) {\n \/\/ The first match is the one with the highest score\n \/\/ at the smallest index in the source order.\n if (m_id_to_method.count(static_cast<MethodId>(meth_id))) {\n TRACE(OPUT, 3,\n \"[method-similarity-orderer] selected %s with score %d\",\n SHOW(m_id_to_method[static_cast<MethodId>(meth_id)]), score);\n return meth_id;\n }\n }\n }\n }\n boost::optional<MethodId> best_method_id = m_id_to_method.begin()->first;\n TRACE(OPUT,\n 3,\n \"[method-similarity-orderer] reverted to %s\",\n SHOW(*best_method_id));\n return best_method_id;\n}\n\nvoid MethodSimilarityOrderer::remove_method(DexMethod* meth) {\n if (!m_method_to_id.count(meth)) return;\n\n auto method_id = m_method_to_id[meth];\n m_id_to_method.erase(method_id);\n m_method_to_id.erase(meth);\n}\n\nvoid MethodSimilarityOrderer::order(std::vector<DexMethod*>& methods) {\n Timer t(\"Reordering methods by similarity\");\n\n for (auto* method : methods) {\n insert(method);\n }\n\n methods.clear();\n\n \/\/ Compute scores among methods in parallel.\n compute_score();\n\n m_last_method_id = boost::none;\n for (boost::optional<MethodId> best_method_id = get_next();\n best_method_id != boost::none;\n best_method_id = get_next()) {\n m_last_method_id = best_method_id;\n auto meth = m_id_to_method[*m_last_method_id];\n methods.push_back(meth);\n remove_method(meth);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(1)\n\/\/ Space: O(1)\n\n\/\/ Below is the interface for Iterator, which is already defined for you.\n\/\/ **DO NOT** modify the interface for Iterator.\nclass Iterator {\n struct Data;\n\tData* data;\npublic:\n\tIterator(const vector<int>& nums);\n\tIterator(const Iterator& iter);\n\tvirtual ~Iterator();\n\t\/\/ Returns the next element in the iteration.\n\tint next();\n\t\/\/ Returns true if the iteration has more elements.\n\tbool hasNext() const;\n};\n\n\nclass PeekingIterator : public Iterator {\npublic:\n PeekingIterator(const vector<int>& nums) : Iterator(nums), has_next_(Iterator::hasNext()) {\n \/\/ Initialize any member here.\n \/\/ **DO NOT** save a copy of nums and manipulate it directly.\n \/\/ You should only use the Iterator interface methods.\n }\n\n \/\/ Returns the next element in the iteration without advancing the iterator.\n int peek() {\n if (!has_peeked_) {\n has_peeked_ = true;\n val_ = Iterator::next();\n }\n return val_;\n }\n\n \/\/ hasNext() and next() should behave the same as in the Iterator interface.\n \/\/ Override them if needed.\n int next() {\n val_ = peek();\n has_peeked_ = false;\n has_next_ = Iterator::hasNext();\n return val_;\n }\n\n bool hasNext() const {\n return has_next_;\n }\n\nprivate:\n int val_;\n bool has_next_;\n bool has_peeked_ = false;\n};\n<commit_msg>Update peeking-iterator.cpp<commit_after>\/\/ Time: O(1) per peek(), next(), hasNext()\n\/\/ Space: O(1)\n\n\/\/ Below is the interface for Iterator, which is already defined for you.\n\/\/ **DO NOT** modify the interface for Iterator.\nclass Iterator {\n struct Data;\n\tData* data;\npublic:\n\tIterator(const vector<int>& nums);\n\tIterator(const Iterator& iter);\n\tvirtual ~Iterator();\n\t\/\/ Returns the next element in the iteration.\n\tint next();\n\t\/\/ Returns true if the iteration has more elements.\n\tbool hasNext() const;\n};\n\n\nclass PeekingIterator : public Iterator {\npublic:\n PeekingIterator(const vector<int>& nums) : Iterator(nums), has_next_(Iterator::hasNext()) {\n \/\/ Initialize any member here.\n \/\/ **DO NOT** save a copy of nums and manipulate it directly.\n \/\/ You should only use the Iterator interface methods.\n }\n\n \/\/ Returns the next element in the iteration without advancing the iterator.\n int peek() {\n if (!has_peeked_) {\n has_peeked_ = true;\n val_ = Iterator::next();\n }\n return val_;\n }\n\n \/\/ hasNext() and next() should behave the same as in the Iterator interface.\n \/\/ Override them if needed.\n int next() {\n val_ = peek();\n has_peeked_ = false;\n has_next_ = Iterator::hasNext();\n return val_;\n }\n\n bool hasNext() const {\n return has_next_;\n }\n\nprivate:\n int val_;\n bool has_next_;\n bool has_peeked_ = false;\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008-2009 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"StdAfx.h\"\n\ninitialiseSingleton( AddonMgr );\n\n\/\/#define DEBUG_PRINT_ADDON_PACKET\t\t\t\/\/ Prints out Received addon packet when char logging in\n\n\/\/ hacky key\nstatic uint8 PublicKey[265] = { 0x02, 0x01, 0x01, 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54, 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75, 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34, 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8, 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8, 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A, 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3, 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9, 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22, 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E, 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB, 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7, 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0, 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6, 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A, 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2, 0x00, 0x00, 0x00, 0x00, 0x00};\n\nAddonMgr::AddonMgr()\n{\n\tKnownAddons.clear();\n}\n\nAddonMgr::~AddonMgr()\n{\n\tstd::map<std::string, AddonEntry*>::iterator itr;\n\tfor(itr = KnownAddons.begin(); itr!=KnownAddons.end(); ++itr) \n\t{\n\t\tdelete itr->second;\n\t}\n\tKnownAddons.clear();\n}\n\nbool AddonMgr::IsAddonBanned(uint64 crc, std::string name)\n{\n\treturn false;\t\/\/ bleh needs work\n}\n\nbool AddonMgr::IsAddonBanned(std::string name, uint64 crc)\n{\n\tstd::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name);\n\tif(i != KnownAddons.end())\n\t{\n\t\tif(i->second->banned)\n\t\t{\n\t\t\tsLog.outDebug(\"Addon %s is banned.\", name.c_str());\n\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ New addon. It'll be saved to db at server shutdown.\n\t\tAddonEntry *ent = new AddonEntry;\n\t\tent->name = name;\n\t\tent->crc = crc;\n\t\tent->banned = false;\t\/\/ by default.. we can change this I guess..\n\t\tent->isNew = true;\n\t\tent->showinlist = true;\n\n\t\tsLog.outDebug(\"Discovered new addon %s sent by client.\", name.c_str());\n\n\t\tKnownAddons[ent->name] = ent;\n\t}\n\n\treturn false;\n}\n\nbool AddonMgr::ShouldShowInList(std::string name)\n{\n\tstd::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name);\n\tif(i != KnownAddons.end())\n\t{\n\t\tif(i->second->showinlist)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\telse\n\t{\n\t\t\/\/ New addon. It'll be saved to db at server shutdown.\t\t\n\t\tAddonEntry *ent = new AddonEntry;\n\t\tent->name = name;\n\t\tent->crc = 0;\n\t\tent->banned = false;\t\/\/ by default.. we can change this I guess..\n\t\tent->isNew = true;\n\t\tent->showinlist = true;\n\n\t\tsLog.outDebug(\"Discovered new addon %s sent by client.\", name.c_str());\n\n\t\tKnownAddons[ent->name] = ent;\n\t}\n\n\treturn true;\n}\n\nvoid AddonMgr::SendAddonInfoPacket(WorldPacket *source, uint32 pos, WorldSession *m_session)\n{\n\tWorldPacket returnpacket;\n\treturnpacket.Initialize(SMSG_ADDON_INFO);\t\/\/ SMSG_ADDON_INFO\n\n\tuint32 realsize;\n\tuLongf rsize;\n\t\n\t\/\/source->hexlike();\n\n\ttry\n\t{\n\t\t*source >> realsize;\n\t}\n\tcatch (ByteBuffer::error &)\n\t{\n\t\tsLog.outDebug(\"Warning: Incomplete auth session sent.\");\n\t\treturn;\n\t}\t\n\trsize = realsize;\n\tsize_t position = source->rpos();\n\n\tByteBuffer unpacked;\n\tunpacked.resize(realsize);\n\n\tif((source->size() - position) < 4 || realsize == 0)\n\t{\n\t\t\/\/ we shouldnt get here.. but just in case this will stop any crash here.\n\t\tsLog.outDebug(\"Warning: Incomplete auth session sent.\");\n\t\treturn;\n\t}\n\tint32 result;\n\tresult = uncompress((uint8*)unpacked.contents(), &rsize, (uint8*)(*source).contents() + position, (uLong)((*source).size() - position));\n\n\tif(result != Z_OK)\n\t{\n\t\tsLog.outError(\"Decompression of addon section of CMSG_AUTH_SESSION failed.\");\n\t\treturn;\n\t}\n\n\tsLog.outDetail(\"Decompression of addon section of CMSG_AUTH_SESSION succeeded.\");\n\t\n\t\n\tuint8 Enable; \/\/ based on the parsed files from retool\n\tuint32 crc;\n\tuint32 unknown;\n\t\n\tstd::string name;\n\n\tuint32 addoncount;\n\tunpacked >> addoncount;\n\n\tfor(uint32 i = 0; i < addoncount; i++)\n\t{\n\t\tunpacked >> name;\n\t\tunpacked >> Enable;\n\t\tunpacked >> crc;\n\t\tunpacked >> unknown;\n\t\t\n\t\t\/\/ Hacky fix, Yea I know its a hacky fix I will make a proper handler one's I got the crc crap\n\t\tif (crc != 0x4C1C776D) \/\/ CRC of public key version 2.0.1\n\t\t\treturnpacket.append(PublicKey,264); \/\/ part of the hacky fix\n\t\telse\n\t\t\treturnpacket << uint8(0x02) << uint8(0x01) << uint8(0x00) << uint32(0) << uint8(0);\n\t\t\/*if(!AppendPublicKey(returnpacket, name, crc))\n\t\t\treturnpacket << uint8(1) << uint8(0) << uint8(0);*\/\n\t}\n\tm_session->SendPacket(&returnpacket);\n}\n\nbool AddonMgr::AppendPublicKey(WorldPacket& data, string AddonName, uint32 CRC)\n{\n\tif(CRC == 0x4C1C776D)\n\t{\n\t\t\/\/ Open public key file with that addon\n\t\tmap<string, ByteBuffer>::iterator itr = AddonData.find(AddonName);\n\t\tif(itr != AddonData.end())\n\t\t\tdata.append(itr->second);\n\t\telse\n\t\t{\n\t\t\t\/\/ open the file\n\t\t\tchar path[500];\n\t\t\tsnprintf(path, 500, \"addons\\\\%s.pub\", AddonName.c_str());\n\t\t\tFILE * f = fopen(path, \"rb\");\n\t\t\tif(f != 0)\n\t\t\t{\n\t\t\t\t\/\/ read the file into a bytebuffer\n\t\t\t\tByteBuffer buf;\n\t\t\t\tfseek(f, 0, SEEK_END);\n\t\t\t\tuint32 length = 264\/*ftell(f)*\/;\n\t\t\t\tfseek(f, 0, SEEK_SET);\n\t\t\t\tbuf.resize(length);\n\t\t\t\tfread((void*)buf.contents(), length, 1, f);\n\t\t\t\tfclose(f);\n\n\t\t\t\tAddonData[AddonName] = buf;\n\t\t\t\tdata.append(buf);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tByteBuffer buf;\n\t\t\t\tbuf.append(PublicKey, 264);\n\t\t\t\tAddonData[AddonName] = buf;\n\t\t\t\tdata.append(buf);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid AddonMgr::LoadFromDB()\n{\n\tQueryResult *result = WorldDatabase.Query(\"SELECT * FROM clientaddons\");\n\tif(!result)\n\t{\n\t\tsLog.outString(\"Query failed: SELECT * FROM clientaddons\");\n\t\treturn;\n\t}\n\n\tdo \n\t{\n\t\tField *field = result->Fetch();\n\t\tAddonEntry *ent = new AddonEntry;\n\n\t\tent->name = field[1].GetString();\n\t\tent->crc = field[2].GetUInt64();\n\t\tent->banned = (field[3].GetUInt32()>0? true:false);\n\t\tent->isNew = false;\n\t\tif(result->GetFieldCount() == 5)\t\t\t\t\/\/ To avoid crashes for stilly nubs who don't update table :P\n\t\t\tent->showinlist = (field[4].GetUInt32()>0 ? true : false);\n\n\t\tKnownAddons[ent->name] = ent;\n\t} while(result->NextRow());\n\n\tdelete result;\n}\n\nvoid AddonMgr::SaveToDB()\n{\n\tsLog.outString(\"AddonMgr: Saving any new addons discovered in this session to database.\");\n\tfor(std::map<std::string, AddonEntry*>::iterator itr = KnownAddons.begin();itr!=KnownAddons.end();++itr)\n\t{\n\t\tif(itr->second->isNew)\n\t\t{\n\t\t\tsLog.outDetail(\"Saving new addon %s\", itr->second->name.c_str());\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"INSERT INTO clientaddons (name, crc, banned, showinlist) VALUES(\\\"\"\n\t\t\t\t<< WorldDatabase.EscapeString(itr->second->name) << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->crc << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->banned << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->showinlist << \"\\\");\";\n\n\t\t\tWorldDatabase.Execute(ss.str().c_str());\n\t\t}\n\t}\n}\n<commit_msg>- hmm this should not fix the potential problem completely because of the dynamicness of the packet.. this one should be atleast something.<commit_after>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008-2009 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"StdAfx.h\"\n\ninitialiseSingleton( AddonMgr );\n\n\/\/#define DEBUG_PRINT_ADDON_PACKET\t\t\t\/\/ Prints out Received addon packet when char logging in\n\n\/\/ hacky key\nstatic uint8 PublicKey[265] = { 0x02, 0x01, 0x01, 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54, 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75, 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34, 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8, 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8, 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A, 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3, 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9, 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22, 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E, 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB, 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7, 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0, 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6, 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A, 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2, 0x00, 0x00, 0x00, 0x00, 0x00};\n\nAddonMgr::AddonMgr()\n{\n\tKnownAddons.clear();\n}\n\nAddonMgr::~AddonMgr()\n{\n\tstd::map<std::string, AddonEntry*>::iterator itr;\n\tfor(itr = KnownAddons.begin(); itr!=KnownAddons.end(); ++itr) \n\t{\n\t\tdelete itr->second;\n\t}\n\tKnownAddons.clear();\n}\n\nbool AddonMgr::IsAddonBanned(uint64 crc, std::string name)\n{\n\treturn false;\t\/\/ bleh needs work\n}\n\nbool AddonMgr::IsAddonBanned(std::string name, uint64 crc)\n{\n\tstd::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name);\n\tif(i != KnownAddons.end())\n\t{\n\t\tif(i->second->banned)\n\t\t{\n\t\t\tsLog.outDebug(\"Addon %s is banned.\", name.c_str());\n\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ New addon. It'll be saved to db at server shutdown.\n\t\tAddonEntry *ent = new AddonEntry;\n\t\tent->name = name;\n\t\tent->crc = crc;\n\t\tent->banned = false;\t\/\/ by default.. we can change this I guess..\n\t\tent->isNew = true;\n\t\tent->showinlist = true;\n\n\t\tsLog.outDebug(\"Discovered new addon %s sent by client.\", name.c_str());\n\n\t\tKnownAddons[ent->name] = ent;\n\t}\n\n\treturn false;\n}\n\nbool AddonMgr::ShouldShowInList(std::string name)\n{\n\tstd::map<std::string,AddonEntry*>::iterator i = KnownAddons.find(name);\n\tif(i != KnownAddons.end())\n\t{\n\t\tif(i->second->showinlist)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\telse\n\t{\n\t\t\/\/ New addon. It'll be saved to db at server shutdown.\t\t\n\t\tAddonEntry *ent = new AddonEntry;\n\t\tent->name = name;\n\t\tent->crc = 0;\n\t\tent->banned = false;\t\/\/ by default.. we can change this I guess..\n\t\tent->isNew = true;\n\t\tent->showinlist = true;\n\n\t\tsLog.outDebug(\"Discovered new addon %s sent by client.\", name.c_str());\n\n\t\tKnownAddons[ent->name] = ent;\n\t}\n\n\treturn true;\n}\n\nvoid AddonMgr::SendAddonInfoPacket(WorldPacket *source, uint32 pos, WorldSession *m_session)\n{\n\tWorldPacket returnpacket;\n\treturnpacket.Initialize(SMSG_ADDON_INFO);\t\/\/ SMSG_ADDON_INFO\n\n\tuint32 realsize;\n\tuLongf rsize;\n\t\n\t\/\/source->hexlike();\n\n\ttry\n\t{\n\t\t*source >> realsize;\n\t}\n\tcatch (ByteBuffer::error &)\n\t{\n\t\tsLog.outDebug(\"Warning: Incomplete auth session sent.\");\n\t\treturn;\n\t}\t\n\trsize = realsize;\n\tsize_t position = source->rpos();\n\n\tByteBuffer unpacked;\n\tunpacked.resize(realsize);\n\n\tif((source->size() - position) < 4 || realsize == 0)\n\t{\n\t\t\/\/ we shouldnt get here.. but just in case this will stop any crash here.\n\t\tsLog.outDebug(\"Warning: Incomplete auth session sent.\");\n\t\treturn;\n\t}\n\tint32 result;\n\tresult = uncompress((uint8*)unpacked.contents(), &rsize, (uint8*)(*source).contents() + position, (uLong)((*source).size() - position));\n\n\tif(result != Z_OK)\n\t{\n\t\tsLog.outError(\"Decompression of addon section of CMSG_AUTH_SESSION failed.\");\n\t\treturn;\n\t}\n\n\tsLog.outDetail(\"Decompression of addon section of CMSG_AUTH_SESSION succeeded.\");\n\t\n\t\n\tuint8 Enable; \/\/ based on the parsed files from retool\n\tuint32 crc;\n\tuint32 unknown;\n\t\n\tstd::string name;\n\n\tuint32 addoncount;\n\tunpacked >> addoncount;\n\n\tfor(uint32 i = 0; i < addoncount; i++)\n\t{\n\t\tif(unpacked.rpos() >= unpacked.size())\n\t\t\tbreak;\n\n\t\tunpacked >> name;\n\t\tunpacked >> Enable;\n\t\tunpacked >> crc;\n\t\tunpacked >> unknown;\n\t\t\n\t\t\/\/ Hacky fix, Yea I know its a hacky fix I will make a proper handler one's I got the crc crap\n\t\tif (crc != 0x4C1C776D) \/\/ CRC of public key version 2.0.1\n\t\t\treturnpacket.append(PublicKey,264); \/\/ part of the hacky fix\n\t\telse\n\t\t\treturnpacket << uint8(0x02) << uint8(0x01) << uint8(0x00) << uint32(0) << uint8(0);\n\t\t\/*if(!AppendPublicKey(returnpacket, name, crc))\n\t\t\treturnpacket << uint8(1) << uint8(0) << uint8(0);*\/\n\t}\n\tm_session->SendPacket(&returnpacket);\n}\n\nbool AddonMgr::AppendPublicKey(WorldPacket& data, string AddonName, uint32 CRC)\n{\n\tif(CRC == 0x4C1C776D)\n\t{\n\t\t\/\/ Open public key file with that addon\n\t\tmap<string, ByteBuffer>::iterator itr = AddonData.find(AddonName);\n\t\tif(itr != AddonData.end())\n\t\t\tdata.append(itr->second);\n\t\telse\n\t\t{\n\t\t\t\/\/ open the file\n\t\t\tchar path[500];\n\t\t\tsnprintf(path, 500, \"addons\\\\%s.pub\", AddonName.c_str());\n\t\t\tFILE * f = fopen(path, \"rb\");\n\t\t\tif(f != 0)\n\t\t\t{\n\t\t\t\t\/\/ read the file into a bytebuffer\n\t\t\t\tByteBuffer buf;\n\t\t\t\tfseek(f, 0, SEEK_END);\n\t\t\t\tuint32 length = 264\/*ftell(f)*\/;\n\t\t\t\tfseek(f, 0, SEEK_SET);\n\t\t\t\tbuf.resize(length);\n\t\t\t\tfread((void*)buf.contents(), length, 1, f);\n\t\t\t\tfclose(f);\n\n\t\t\t\tAddonData[AddonName] = buf;\n\t\t\t\tdata.append(buf);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tByteBuffer buf;\n\t\t\t\tbuf.append(PublicKey, 264);\n\t\t\t\tAddonData[AddonName] = buf;\n\t\t\t\tdata.append(buf);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid AddonMgr::LoadFromDB()\n{\n\tQueryResult *result = WorldDatabase.Query(\"SELECT * FROM clientaddons\");\n\tif(!result)\n\t{\n\t\tsLog.outString(\"Query failed: SELECT * FROM clientaddons\");\n\t\treturn;\n\t}\n\n\tdo \n\t{\n\t\tField *field = result->Fetch();\n\t\tAddonEntry *ent = new AddonEntry;\n\n\t\tent->name = field[1].GetString();\n\t\tent->crc = field[2].GetUInt64();\n\t\tent->banned = (field[3].GetUInt32()>0? true:false);\n\t\tent->isNew = false;\n\t\tif(result->GetFieldCount() == 5)\t\t\t\t\/\/ To avoid crashes for stilly nubs who don't update table :P\n\t\t\tent->showinlist = (field[4].GetUInt32()>0 ? true : false);\n\n\t\tKnownAddons[ent->name] = ent;\n\t} while(result->NextRow());\n\n\tdelete result;\n}\n\nvoid AddonMgr::SaveToDB()\n{\n\tsLog.outString(\"AddonMgr: Saving any new addons discovered in this session to database.\");\n\tfor(std::map<std::string, AddonEntry*>::iterator itr = KnownAddons.begin();itr!=KnownAddons.end();++itr)\n\t{\n\t\tif(itr->second->isNew)\n\t\t{\n\t\t\tsLog.outDetail(\"Saving new addon %s\", itr->second->name.c_str());\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"INSERT INTO clientaddons (name, crc, banned, showinlist) VALUES(\\\"\"\n\t\t\t\t<< WorldDatabase.EscapeString(itr->second->name) << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->crc << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->banned << \"\\\",\\\"\"\n\t\t\t\t<< itr->second->showinlist << \"\\\");\";\n\n\t\t\tWorldDatabase.Execute(ss.str().c_str());\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file exists to provide some stat monitors for process statistics and the like. *\/\n\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/syscall.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <stdarg.h>\n\n#include <vector>\n\n#include \"arch\/io\/io_utils.hpp\"\n#include \"containers\/printf_buffer.hpp\"\n#include \"perfmon.hpp\"\n#include \"logger.hpp\"\n#include \"utils.hpp\"\n#include \"thread_local.hpp\"\n\n\/* Class to represent and parse the contents of \/proc\/[pid]\/stat *\/\n\nstruct proc_pid_stat_exc_t : public std::exception {\n explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {\n va_list ap;\n va_start(ap, format);\n msg = vstrprintf(format, ap);\n va_end(ap);\n }\n std::string msg;\n const char *what() const throw () {\n return msg.c_str();\n }\n ~proc_pid_stat_exc_t() throw () { }\n};\n\nstruct proc_pid_stat_t {\n int pid;\n char name[500];\n char state;\n int ppid, pgrp, session, tty_nr, tpgid;\n unsigned int flags;\n uint64_t minflt, cminflt, majflt, cmajflt, utime, stime;\n int64_t cutime, cstime, priority, nice, num_threads, itrealvalue;\n uint64_t starttime;\n uint64_t vsize;\n int64_t rss;\n uint64_t rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,\n sigignore, sigcatch, wchan, nswap, cnswap;\n int exit_signal, processor;\n unsigned int rt_priority, policy;\n uint64_t delayacct_blkio_ticks;\n uint64_t guest_time;\n int64_t cguest_time;\n\n static proc_pid_stat_t for_pid(pid_t pid) {\n printf_buffer_t<100> path(\"\/proc\/%d\/stat\", pid);\n proc_pid_stat_t stat;\n stat.read_from_file(path.c_str());\n return stat;\n }\n\n static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {\n printf_buffer_t<100> path(\"\/proc\/%d\/task\/%d\/stat\", pid, tid);\n proc_pid_stat_t stat;\n stat.read_from_file(path.c_str());\n return stat;\n }\n\nprivate:\n void read_from_file(const char * path) {\n scoped_fd_t stat_file(open(path, O_RDONLY));\n if (stat_file.get() == INVALID_FD) {\n throw proc_pid_stat_exc_t(\"Could not open '%s': %s (errno = %d)\", path, strerror(errno), errno);\n }\n\n char buffer[1000];\n int res = ::read(stat_file.get(), buffer, sizeof(buffer));\n if (res <= 0) {\n throw proc_pid_stat_exc_t(\"Could not read '%s': %s (errno = %d)\", path, strerror(errno), errno);\n }\n\n buffer[res] = '\\0';\n\n const int items_to_parse = 44;\n int res2 = sscanf(buffer, \"%d %s %c %d %d %d %d %d %u\"\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNd64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %d %d\"\n \" %u %u\"\n \" %\" SCNu64\n \" %\" SCNu64\n \" %\" SCNd64,\n &pid,\n name,\n &state,\n &ppid, &pgrp, &session, &tty_nr, &tpgid,\n &flags,\n &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,\n &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,\n &starttime,\n &vsize,\n &rss,\n &rsslim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked,\n &sigignore, &sigcatch, &wchan, &nswap, &cnswap,\n &exit_signal, &processor,\n &rt_priority, &policy,\n &delayacct_blkio_ticks,\n &guest_time,\n &cguest_time);\n if (res2 != items_to_parse) {\n throw proc_pid_stat_exc_t(\"Could not parse '%s': expected to parse %d items, parsed \"\n \"%d. Buffer contents: %s\", path, items_to_parse, res2, buffer);\n }\n }\n};\n\n\/* perfmon_system_t is used to monitor system stats that do not need to be polled. *\/\nstruct perfmon_system_t : public perfmon_t {\n bool have_reported_error;\n explicit perfmon_system_t(perfmon_collection_t *parent = NULL) : perfmon_t(parent), have_reported_error(false), start_time(time(NULL)) { }\n\n void *begin_stats() {\n return NULL;\n }\n void visit_stats(void *) {\n }\n void end_stats(void *, perfmon_result_t *dest) {\n put_timestamp(dest);\n dest->insert(\"version\", new perfmon_result_t(std::string(RETHINKDB_VERSION)));\n dest->insert(\"pid\", new perfmon_result_t(strprintf(\"%d\", getpid())));\n\n proc_pid_stat_t pid_stat;\n try {\n pid_stat = proc_pid_stat_t::for_pid(getpid());\n } catch (proc_pid_stat_exc_t e) {\n if (!have_reported_error) {\n logWRN(\"Error in reporting system stats: %s (Further errors like this will be suppressed.)\", e.what());\n have_reported_error = true;\n }\n return;\n }\n\n dest->insert(\"memory_virtual\", new perfmon_result_t(strprintf(\"%lu\", pid_stat.vsize)));\n dest->insert(\"memory_real\", new perfmon_result_t(strprintf(\"%ld\", pid_stat.rss * sysconf(_SC_PAGESIZE))));\n }\n void put_timestamp(perfmon_result_t *dest) {\n struct timespec now;\n int res = clock_gettime(CLOCK_REALTIME, &now);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_REALTIME) failed\");\n dest->insert(\"uptime\", new perfmon_result_t(strprintf(\"%d\", int(difftime(start_time, now.tv_sec)))));\n dest->insert(\"timestamp\", new perfmon_result_t(format_time(now)));\n }\n\n time_t start_time;\n} pm_system;\n\n\/* Some of the stats need to be polled periodically. Call this function periodically on each\nthread to ensure that stats are up to date. It takes a void* so that it can be called as a timer\ncallback. *\/\n\nperfmon_sampler_t\n pm_cpu_user(\"cpu_user\", secs_to_ticks(5), false, NULL),\n pm_cpu_system(\"cpu_system\", secs_to_ticks(5), false, NULL),\n pm_cpu_combined(\"cpu_combined\", secs_to_ticks(5), false, NULL),\n pm_memory_faults(\"memory_faults\", secs_to_ticks(5), false, NULL);\n\n\nTLS(proc_pid_stat_t, last_stats);\nTLS_with_init(ticks_t, last_ticks, 0);\nTLS_with_init(bool, have_reported_stats_error, false);\n\nvoid poll_system_stats(void *) {\n\n proc_pid_stat_t current_stats;\n try {\n current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));\n } catch (proc_pid_stat_exc_t e) {\n if (!TLS_get_have_reported_stats_error()) {\n logWRN(\"Error in reporting per-thread stats: %s (Further errors like this will \"\n \"be suppressed.)\", e.what());\n TLS_set_have_reported_stats_error(true);\n }\n }\n ticks_t current_ticks = get_ticks();\n\n if (TLS_get_last_ticks() == 0) {\n TLS_set_last_stats(current_stats);\n TLS_set_last_ticks(current_ticks);\n } else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {\n double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);\n pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) \/ realtime_elapsed);\n pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) \/ realtime_elapsed);\n pm_cpu_combined.record(\n (current_stats.utime - TLS_get_last_stats().utime +\n current_stats.stime - TLS_get_last_stats().stime) \/\n realtime_elapsed);\n pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) \/ realtime_elapsed);\n\n TLS_set_last_stats(current_stats);\n TLS_set_last_ticks(current_ticks);\n }\n}\n\n<commit_msg>Fixing uptime stat. Tsk tsk tsk.<commit_after>\/* This file exists to provide some stat monitors for process statistics and the like. *\/\n\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/syscall.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <stdarg.h>\n\n#include <vector>\n\n#include \"arch\/io\/io_utils.hpp\"\n#include \"containers\/printf_buffer.hpp\"\n#include \"perfmon.hpp\"\n#include \"logger.hpp\"\n#include \"utils.hpp\"\n#include \"thread_local.hpp\"\n\n\/* Class to represent and parse the contents of \/proc\/[pid]\/stat *\/\n\nstruct proc_pid_stat_exc_t : public std::exception {\n explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {\n va_list ap;\n va_start(ap, format);\n msg = vstrprintf(format, ap);\n va_end(ap);\n }\n std::string msg;\n const char *what() const throw () {\n return msg.c_str();\n }\n ~proc_pid_stat_exc_t() throw () { }\n};\n\nstruct proc_pid_stat_t {\n int pid;\n char name[500];\n char state;\n int ppid, pgrp, session, tty_nr, tpgid;\n unsigned int flags;\n uint64_t minflt, cminflt, majflt, cmajflt, utime, stime;\n int64_t cutime, cstime, priority, nice, num_threads, itrealvalue;\n uint64_t starttime;\n uint64_t vsize;\n int64_t rss;\n uint64_t rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,\n sigignore, sigcatch, wchan, nswap, cnswap;\n int exit_signal, processor;\n unsigned int rt_priority, policy;\n uint64_t delayacct_blkio_ticks;\n uint64_t guest_time;\n int64_t cguest_time;\n\n static proc_pid_stat_t for_pid(pid_t pid) {\n printf_buffer_t<100> path(\"\/proc\/%d\/stat\", pid);\n proc_pid_stat_t stat;\n stat.read_from_file(path.c_str());\n return stat;\n }\n\n static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {\n printf_buffer_t<100> path(\"\/proc\/%d\/task\/%d\/stat\", pid, tid);\n proc_pid_stat_t stat;\n stat.read_from_file(path.c_str());\n return stat;\n }\n\nprivate:\n void read_from_file(const char * path) {\n scoped_fd_t stat_file(open(path, O_RDONLY));\n if (stat_file.get() == INVALID_FD) {\n throw proc_pid_stat_exc_t(\"Could not open '%s': %s (errno = %d)\", path, strerror(errno), errno);\n }\n\n char buffer[1000];\n int res = ::read(stat_file.get(), buffer, sizeof(buffer));\n if (res <= 0) {\n throw proc_pid_stat_exc_t(\"Could not read '%s': %s (errno = %d)\", path, strerror(errno), errno);\n }\n\n buffer[res] = '\\0';\n\n const int items_to_parse = 44;\n int res2 = sscanf(buffer, \"%d %s %c %d %d %d %d %d %u\"\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64 \" %\" SCNd64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNd64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64 \" %\" SCNu64\n \" %d %d\"\n \" %u %u\"\n \" %\" SCNu64\n \" %\" SCNu64\n \" %\" SCNd64,\n &pid,\n name,\n &state,\n &ppid, &pgrp, &session, &tty_nr, &tpgid,\n &flags,\n &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,\n &cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,\n &starttime,\n &vsize,\n &rss,\n &rsslim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked,\n &sigignore, &sigcatch, &wchan, &nswap, &cnswap,\n &exit_signal, &processor,\n &rt_priority, &policy,\n &delayacct_blkio_ticks,\n &guest_time,\n &cguest_time);\n if (res2 != items_to_parse) {\n throw proc_pid_stat_exc_t(\"Could not parse '%s': expected to parse %d items, parsed \"\n \"%d. Buffer contents: %s\", path, items_to_parse, res2, buffer);\n }\n }\n};\n\n\/* perfmon_system_t is used to monitor system stats that do not need to be polled. *\/\nstruct perfmon_system_t : public perfmon_t {\n bool have_reported_error;\n explicit perfmon_system_t(perfmon_collection_t *parent = NULL) : perfmon_t(parent), have_reported_error(false) {\n struct timespec now;\n int res = clock_gettime(CLOCK_MONOTONIC, &now);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_MONOTONIC) failed\");\n start_time = now.tv_sec;\n }\n\n void *begin_stats() {\n return NULL;\n }\n void visit_stats(void *) {\n }\n void end_stats(void *, perfmon_result_t *dest) {\n put_timestamp(dest);\n dest->insert(\"version\", new perfmon_result_t(std::string(RETHINKDB_VERSION)));\n dest->insert(\"pid\", new perfmon_result_t(strprintf(\"%d\", getpid())));\n\n proc_pid_stat_t pid_stat;\n try {\n pid_stat = proc_pid_stat_t::for_pid(getpid());\n } catch (proc_pid_stat_exc_t e) {\n if (!have_reported_error) {\n logWRN(\"Error in reporting system stats: %s (Further errors like this will be suppressed.)\", e.what());\n have_reported_error = true;\n }\n return;\n }\n\n dest->insert(\"memory_virtual\", new perfmon_result_t(strprintf(\"%lu\", pid_stat.vsize)));\n dest->insert(\"memory_real\", new perfmon_result_t(strprintf(\"%ld\", pid_stat.rss * sysconf(_SC_PAGESIZE))));\n }\n void put_timestamp(perfmon_result_t *dest) {\n struct timespec now;\n int res = clock_gettime(CLOCK_MONOTONIC, &now);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_MONOTONIC) failed\");\n dest->insert(\"uptime\", new perfmon_result_t(strprintf(\"%ld\", now.tv_sec - start_time)));\n dest->insert(\"timestamp\", new perfmon_result_t(format_time(now)));\n }\n\n long start_time;\n} pm_system;\n\n\/* Some of the stats need to be polled periodically. Call this function periodically on each\nthread to ensure that stats are up to date. It takes a void* so that it can be called as a timer\ncallback. *\/\n\nperfmon_sampler_t\n pm_cpu_user(\"cpu_user\", secs_to_ticks(5), false, NULL),\n pm_cpu_system(\"cpu_system\", secs_to_ticks(5), false, NULL),\n pm_cpu_combined(\"cpu_combined\", secs_to_ticks(5), false, NULL),\n pm_memory_faults(\"memory_faults\", secs_to_ticks(5), false, NULL);\n\n\nTLS(proc_pid_stat_t, last_stats);\nTLS_with_init(ticks_t, last_ticks, 0);\nTLS_with_init(bool, have_reported_stats_error, false);\n\nvoid poll_system_stats(void *) {\n\n proc_pid_stat_t current_stats;\n try {\n current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));\n } catch (proc_pid_stat_exc_t e) {\n if (!TLS_get_have_reported_stats_error()) {\n logWRN(\"Error in reporting per-thread stats: %s (Further errors like this will \"\n \"be suppressed.)\", e.what());\n TLS_set_have_reported_stats_error(true);\n }\n }\n ticks_t current_ticks = get_ticks();\n\n if (TLS_get_last_ticks() == 0) {\n TLS_set_last_stats(current_stats);\n TLS_set_last_ticks(current_ticks);\n } else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {\n double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);\n pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) \/ realtime_elapsed);\n pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) \/ realtime_elapsed);\n pm_cpu_combined.record(\n (current_stats.utime - TLS_get_last_stats().utime +\n current_stats.stime - TLS_get_last_stats().stime) \/\n realtime_elapsed);\n pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) \/ realtime_elapsed);\n\n TLS_set_last_stats(current_stats);\n TLS_set_last_ticks(current_ticks);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Matthew Harvey. All rights reserved.\n\n#include \"transaction_type_ctrl.hpp\"\n#include \"b_string.hpp\"\n#include \"string_set_validator.hpp\"\n#include \"transaction_ctrl.hpp\"\n#include \"transaction_type.hpp\"\n#include <boost\/optional.hpp>\n#include <jewel\/optional.hpp>\n#include <wx\/arrstr.h>\n#include <wx\/combobox.h>\n#include <wx\/gdicmn.h>\n#include <wx\/window.h>\n#include <wx\/windowid.h>\n#include <vector>\n\nusing boost::optional;\nusing jewel::value;\nusing std::vector;\n\n\n\/\/ For debugging\n\t#include <jewel\/debug_log.hpp>\n\t#include <iostream>\n\tusing std::endl;\n\n\nnamespace phatbooks\n{\n\nusing transaction_type::num_transaction_types;\nusing transaction_type::TransactionType;\n\nnamespace gui\n{\n\nBEGIN_EVENT_TABLE(TransactionTypeCtrl, wxComboBox)\n\tEVT_KILL_FOCUS\n\t(\tTransactionTypeCtrl::on_kill_focus\n\t)\n\tEVT_COMBOBOX\n\t(\twxID_ANY,\n\t\tTransactionTypeCtrl::on_change\n\t)\nEND_EVENT_TABLE()\n\n\nTransactionTypeCtrl::TransactionTypeCtrl\n(\twxWindow* p_parent,\n\twxWindowID p_id,\n\twxSize const& p_size\n):\n\twxComboBox\n\t(\tp_parent,\n\t\tp_id,\n\t\tbstring_to_wx\n\t\t(\ttransaction_type_to_verb(static_cast<TransactionType>(0))\n\t\t),\n\t\twxDefaultPosition,\n\t\tp_size,\n\t\twxArrayString()\n\t\t\/\/, wxCB_READONLY\n\t)\n{\n\twxArrayString transaction_type_verbs;\n\tassert (transaction_type_verbs.IsEmpty());\n\tvector<TransactionType> const tt = transaction_types();\n\tvector<TransactionType>::const_iterator it = tt.begin();\n\tvector<TransactionType>::const_iterator const end = tt.end();\n\tfor ( ; it != end; ++it)\n\t{\n\t\twxString const verb = bstring_to_wx\n\t\t(\ttransaction_type_to_verb(*it)\n\t\t);\n\t\ttransaction_type_verbs.Add(verb); \/\/ remember as valid name\n\t\tAppend(verb); \/\/ add to combobox\n\t}\n\tStringSetValidator validator\n\t(\tGetValue(),\n\t\ttransaction_type_verbs,\n\t\t\"transaction type\"\n\t);\n\tSetValidator(validator);\n\tSetSelection(0); \/\/ In effort to avoid apparent bug in Windows.\n\t\/\/ TODO AutoComplete is irrelevant if we have the wxComboBox as readonly.\n\t\/\/ But we still might want to let the user select by just typing the first\n\t\/\/ letter or something.\n\tAutoComplete(transaction_type_verbs);\n}\n\noptional<transaction_type::TransactionType>\nTransactionTypeCtrl::transaction_type() const\n{\n\toptional<transaction_type::TransactionType> ret;\n\tint const selection = GetSelection();\n\tif (selection < 0)\n\t{\n\t\treturn ret;\n\t}\n\ttransaction_type::TransactionType const ttype =\n\t\tstatic_cast<transaction_type::TransactionType>(selection);\n\tassert_transaction_type_validity(ttype);\n\tret = ttype;\n\treturn ret;\n}\n\nvoid\nTransactionTypeCtrl::set_transaction_type\n(\ttransaction_type::TransactionType p_transaction_type\n)\n{\n\tSetSelection(static_cast<int>(p_transaction_type));\n\treturn;\n}\n\nvoid\nTransactionTypeCtrl::on_kill_focus(wxFocusEvent& event)\n{\n\t\/\/ TODO Make a class from which we can privately inherit, to capture\n\t\/\/ this on_kill_focus behaviour, which is shared by several custom\n\t\/\/ widget classes in phatbooks::gui.\n\n\t\/\/ Unfortunately if we call Validate() and TransferDataToWindow()\n\t\/\/ directly on the AccountCtrl, it doesn't work. We have to call\n\t\/\/ through parent instead.\n\tGetParent()->Validate();\n\tGetParent()->TransferDataToWindow();\n\tevent.Skip();\n\treturn;\n}\n\nvoid\nTransactionTypeCtrl::on_change(wxCommandEvent& event)\n{\n\t(void)event; \/\/ silence compiler re. unused param.\n\tTransactionCtrl* parent = dynamic_cast<TransactionCtrl*>(GetParent());\n\tassert(parent);\n\toptional<transaction_type::TransactionType> const maybe_ttype =\n\t\ttransaction_type();\n\tif (!maybe_ttype)\n\t{\n\t\treturn;\n\t}\n\tassert_transaction_type_validity(value(maybe_ttype));\n\tparent->refresh_for_transaction_type(value(maybe_ttype));\n\treturn;\n}\n\n\n} \/\/ namespace gui\n} \/\/ namespace phatbooks\n<commit_msg>Made TransactionTypeCtrl read-only. This avoids having to handle EVT_TEXT events which are not EVT_COMBOBOX events. (Handling EVT_TEXT in this context has proven to be a problematic exercise.)<commit_after>\/\/ Copyright (c) 2013, Matthew Harvey. All rights reserved.\n\n#include \"transaction_type_ctrl.hpp\"\n#include \"b_string.hpp\"\n#include \"string_set_validator.hpp\"\n#include \"transaction_ctrl.hpp\"\n#include \"transaction_type.hpp\"\n#include <boost\/optional.hpp>\n#include <jewel\/optional.hpp>\n#include <wx\/arrstr.h>\n#include <wx\/combobox.h>\n#include <wx\/gdicmn.h>\n#include <wx\/window.h>\n#include <wx\/windowid.h>\n#include <vector>\n\nusing boost::optional;\nusing jewel::value;\nusing std::vector;\n\n\n\/\/ For debugging\n\t#include <jewel\/debug_log.hpp>\n\t#include <iostream>\n\tusing std::endl;\n\n\nnamespace phatbooks\n{\n\nusing transaction_type::num_transaction_types;\nusing transaction_type::TransactionType;\n\nnamespace gui\n{\n\nBEGIN_EVENT_TABLE(TransactionTypeCtrl, wxComboBox)\n\tEVT_KILL_FOCUS\n\t(\tTransactionTypeCtrl::on_kill_focus\n\t)\n\tEVT_COMBOBOX\n\t(\twxID_ANY,\n\t\tTransactionTypeCtrl::on_change\n\t)\nEND_EVENT_TABLE()\n\n\nTransactionTypeCtrl::TransactionTypeCtrl\n(\twxWindow* p_parent,\n\twxWindowID p_id,\n\twxSize const& p_size\n):\n\twxComboBox\n\t(\tp_parent,\n\t\tp_id,\n\t\tbstring_to_wx\n\t\t(\ttransaction_type_to_verb(static_cast<TransactionType>(0))\n\t\t),\n\t\twxDefaultPosition,\n\t\tp_size,\n\t\twxArrayString(),\n\t\twxCB_READONLY\n\t)\n{\n\twxArrayString transaction_type_verbs;\n\tassert (transaction_type_verbs.IsEmpty());\n\tvector<TransactionType> const tt = transaction_types();\n\tvector<TransactionType>::const_iterator it = tt.begin();\n\tvector<TransactionType>::const_iterator const end = tt.end();\n\tfor ( ; it != end; ++it)\n\t{\n\t\twxString const verb = bstring_to_wx\n\t\t(\ttransaction_type_to_verb(*it)\n\t\t);\n\t\ttransaction_type_verbs.Add(verb); \/\/ remember as valid name\n\t\tAppend(verb); \/\/ add to combobox\n\t}\n\tStringSetValidator validator\n\t(\tGetValue(),\n\t\ttransaction_type_verbs,\n\t\t\"transaction type\"\n\t);\n\tSetValidator(validator);\n\tSetSelection(0); \/\/ In effort to avoid apparent bug in Windows.\n\t\/\/ TODO AutoComplete is irrelevant if we have the wxComboBox as readonly.\n\t\/\/ But we still might want to let the user select by just typing the first\n\t\/\/ letter or something.\n\tAutoComplete(transaction_type_verbs);\n}\n\noptional<transaction_type::TransactionType>\nTransactionTypeCtrl::transaction_type() const\n{\n\toptional<transaction_type::TransactionType> ret;\n\tint const selection = GetSelection();\n\tif (selection < 0)\n\t{\n\t\treturn ret;\n\t}\n\ttransaction_type::TransactionType const ttype =\n\t\tstatic_cast<transaction_type::TransactionType>(selection);\n\tassert_transaction_type_validity(ttype);\n\tret = ttype;\n\treturn ret;\n}\n\nvoid\nTransactionTypeCtrl::set_transaction_type\n(\ttransaction_type::TransactionType p_transaction_type\n)\n{\n\tSetSelection(static_cast<int>(p_transaction_type));\n\treturn;\n}\n\nvoid\nTransactionTypeCtrl::on_kill_focus(wxFocusEvent& event)\n{\n\t\/\/ TODO Make a class from which we can privately inherit, to capture\n\t\/\/ this on_kill_focus behaviour, which is shared by several custom\n\t\/\/ widget classes in phatbooks::gui.\n\n\t\/\/ Unfortunately if we call Validate() and TransferDataToWindow()\n\t\/\/ directly on the AccountCtrl, it doesn't work. We have to call\n\t\/\/ through parent instead.\n\tGetParent()->Validate();\n\tGetParent()->TransferDataToWindow();\n\tevent.Skip();\n\treturn;\n}\n\nvoid\nTransactionTypeCtrl::on_change(wxCommandEvent& event)\n{\n\t(void)event; \/\/ silence compiler re. unused param.\n\tTransactionCtrl* parent = dynamic_cast<TransactionCtrl*>(GetParent());\n\tassert(parent);\n\toptional<transaction_type::TransactionType> const maybe_ttype =\n\t\ttransaction_type();\n\tif (!maybe_ttype)\n\t{\n\t\treturn;\n\t}\n\tassert_transaction_type_validity(value(maybe_ttype));\n\tparent->refresh_for_transaction_type(value(maybe_ttype));\n\treturn;\n}\n\n\n} \/\/ namespace gui\n} \/\/ namespace phatbooks\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/ Read background particles from a FLUKA boundary source file\n\/\/ This is a very special generator that works for background studies for the muon-spectrometer.\n\/\/ The input files come from FLUKA simulations.\n\/\/ Files can be chained. \n\/\/ Author: andreas.morsch@cern.ch\n\n#include \"TPDGCode.h\"\n#include \"TDatabasePDG.h\"\n\n#include \"AliGenFLUKAsource.h\"\n#include \"AliRun.h\"\n\n\n#include <TFile.h>\n#include <TTree.h>\n#include <TChain.h>\n#include <stdlib.h>\nClassImp(AliGenFLUKAsource)\n\nAliGenFLUKAsource::AliGenFLUKAsource()\n\t :AliGenerator(-1)\n{\n \/\/ Constructor\n fName=\"FLUKA\";\n fTitle=\"FLUKA Boundary Source\";\n \/\/ Read in all particle types by default\n fIkine=6;\n \/\/ Set maximum admitted age of particles to 1.e-05 by default \n fAgeMax=1.e-05;\n \/\/ Do not add weight\n fAddWeight=1.;\n \/\/ Shift the z-coordinate of the impact point by 4.5 cm only if it reads \n \/\/ from specific boundary source to the chamber (fZshift=4.5;),else there \n \/\/ is no need to shift as it reads boundary source for the whole volume of \n \/\/ the Muon Arm; the default value corresponds to boundary source for the\n \/\/ whole volume of the MUON Arm \n fZshift=0;\n \/\/ Set the default file \n fFileName=\"\";\n\n fTreeFluka=0;\n fTreeChain = new TChain(\"h1\");\n\/\/\n\/\/ Read all particles\n fNpart=-1;\n}\n\nAliGenFLUKAsource::AliGenFLUKAsource(Int_t npart)\n :AliGenerator(npart)\n{\n \/\/ Constructor\n fName = \"FLUKA\";\n fTitle = \"FLUKA Boundary Source\";\n \/\/ Read in all particle types by default\n fIkine=6;\n \/\/ Set maximum admitted age of particles to 1.e-05 by default \n fAgeMax=1.e-05;\n \/\/ Do not add weight\n fAddWeight=1.;\n \/\/ Shift the z-coordinate of the impact point by 4.5 cm only if it reads \n \/\/ from specific boundary source to the chamber (fZshift=4.5;),else there \n \/\/ is no need to shift as it reads boundary source for the whole volume of \n \/\/ the Muon Arm; the default value corresponds to boundary source for the\n \/\/ whole volume of the MUON Arm \n fZshift=0;\n \/\/ Set the default file \n fFileName=\"\";\n\n fTreeFluka=0;\n fTreeChain = new TChain(\"h1\"); \n fSourceId=-1;\n}\n\nAliGenFLUKAsource::AliGenFLUKAsource(const AliGenFLUKAsource & FLUKAsource):\n AliGenerator(FLUKAsource)\n{\n\/\/ Copy constructor\n FLUKAsource.Copy(*this);\n}\n\n\n\/\/____________________________________________________________\nAliGenFLUKAsource::~AliGenFLUKAsource()\n{\n\/\/ Destructor\n if (fTreeFluka) delete fTreeFluka;\n if (fTreeChain) delete fTreeChain;\n}\n\nvoid AliGenFLUKAsource::AddFile(const Text_t *filename)\n{\n\/\/ Add a file to the chain\n fTreeChain->Add(filename);\n \n}\n\n\n\/\/____________________________________________________________\nvoid AliGenFLUKAsource::FlukaInit() \n{\n\/\/ Set branch addresses of data entries\n TChain *h2=fTreeChain;\n\/\/Set branch addresses\n h2->SetBranchAddress(\"Ip\",&fIp);\n h2->SetBranchAddress(\"Ipp\",&fIpp);\n h2->SetBranchAddress(\"Xi\",&fXi);\n h2->SetBranchAddress(\"Yi\",&fYi);\n h2->SetBranchAddress(\"Zi\",&fZi);\n h2->SetBranchAddress(\"Px\",&fPx);\n h2->SetBranchAddress(\"Py\",&fPy);\n h2->SetBranchAddress(\"Pz\",&fPz);\n h2->SetBranchAddress(\"Ekin\",&fEkin);\n h2->SetBranchAddress(\"Zv\",&fZv);\n h2->SetBranchAddress(\"Rv\",&fRv);\n h2->SetBranchAddress(\"Itra\",&fItra);\n h2->SetBranchAddress(\"Igas\",&fIgas);\n h2->SetBranchAddress(\"Wgt\",&fWgt);\n h2->SetBranchAddress(\"Etag\",&fEtag);\n h2->SetBranchAddress(\"Ptg\",&fPtg);\n h2->SetBranchAddress(\"Age\",&fAge);\n}\n\n\/\/____________________________________________________________\nvoid AliGenFLUKAsource::Generate()\n{\n\/\/ Generate one event \n\n const Int_t kIfluge[28]={kProton, kProtonBar, kElectron, kPositron,\n\t\t\t kNuE, kNuEBar, kGamma, kNeutron, kNeutronBar,\n\t\t\t kMuonPlus, kMuonMinus, kK0Long , kPiPlus, kPiMinus,\n\t\t\t kKPlus, kKMinus, kLambda0, kLambda0Bar, kK0Short,\n\t\t\t kSigmaMinus, kSigmaPlus, kSigma0, kPi0, kK0, kK0Bar,\n\t\t\t 0,kNuMu,kNuMuBar};\n Float_t polar[3]= {0,0,0};\n \/\/\n Float_t origin[3];\n Float_t p[3];\n Float_t prwn;\n Float_t wgt, fwgt;\n Float_t phi;\n Float_t amass;\n Int_t iwgt;\n Int_t i, j, part, nt;\n static Int_t irwn=0;\n \/\/\n Float_t random[2];\n \/\/\n FlukaInit();\n TChain *h2=fTreeChain;\n Int_t nentries = (Int_t) h2->GetEntries();\n if (fNpart == -1) fNpart=Int_t(nentries*fFrac);\n \n\n \/\/ loop over number of particles\n Int_t nb=0;\n Int_t ev=gMC->CurrentEvent();\n for (i=0; i<fNpart;i++) {\n\tInt_t entry=fNpart*(ev-1)+i; \n\tnb = (Int_t)h2->GetEvent(entry); \n\tif (irwn > nentries) {\n\t printf(\"No more entries in the FLUKA boundary source file\\n\");\n\t TFile *pFile=0;\n\t \/\/ Get AliRun object or create it \n\t if (!gAlice) {\n\t\tgAlice = (AliRun*)pFile->Get(\"gAlice\");\n\t\tif (gAlice) printf(\"AliRun object found on file\\n\");\n\t\tif (!gAlice) gAlice = new AliRun(\"gAlice\",\"Alice test program\");\n\t }\n\t TTree *fAli=gAlice->TreeK();\n\t if (fAli) pFile =fAli->GetCurrentFile();\n\t pFile->cd();\n\t printf(\"Generate - I'm out \\n\");\n\t return;\n\t} \n\t\n\tInt_t ifip = Int_t(fIp);\n\t\n\n\tif (fSourceId != -1 && fIgas !=fSourceId) {\n\t irwn++;\n\t continue;\n\t}\n\t\n\tif (ifip > 28 || ifip < 0) {\n\t irwn++;\n\t continue;\n\t}\n\t\n\tif ((ifip != fIkine && fIkine != kAll && fIkine != kCharged \n\t && fIkine != 10) || fAge > fAgeMax){\n\t irwn++;\n\t continue;\n\t} else if (fIkine == kCharged) {\n\t if (ifip == 7 || ifip == 8 || fAge > fAgeMax) { \n\t\tirwn++;\n\t\tcontinue;\n\t }\n\t} else if (fIkine == kNoNeutron) {\n\t if (ifip == 8 || fAge > fAgeMax) { \n\t\tirwn++;\n\t\tcontinue;\n\t }\n\t}\n \n\n\tirwn++;\n\/\/\n\/\/ PDG code from FLUKA particle type (ifip)\n\tpart=kIfluge[int(ifip)-1];\t\n\/\/\n\/\/ Calculate momentum from kinetic energy and mass of the particle\n#if ROOT_VERSION_CODE > 197895\n amass = gMC->ParticleMass(part);\n#else\n\tamass = (TDatabasePDG::Instance())->GetParticle(part)->Mass();\n#endif\n\tprwn=fEkin*sqrt(1. + 2.*amass\/fEkin);\n\n\n\torigin[0]=fYi;\n\torigin[1]=fXi;\n\torigin[2]=fZi;\n\t\n\tp[0]=fPy*prwn;\n\tp[1]=fPx*prwn;\n\tp[2]=fPz*prwn;\n\n\t\/\/handle particle weight correctly\n\twgt = (part == 13) ? fWgt*fAddWeight : fWgt;\n\tiwgt=Int_t(wgt);\n\tfwgt=wgt-Float_t(iwgt);\n\tRndm(random,2);\n\tif (random[0] < fwgt) iwgt++;\n\tif (part==1 && iwgt>100) iwgt=100;\n\tInt_t nstack=0;\n\tfor (j=0; j<iwgt; j++) {\n\t PushTrack(fTrackIt,-1,part,p,origin,polar,fAge,kPPrimary,nt);\n\t Rndm(random,2);\n\t phi=2*random[1]*TMath::Pi();\n\t Float_t pn1=p[0]*TMath::Sin(phi) - p[1]*TMath::Cos(phi);\n\t Float_t pn2=p[0]*TMath::Cos(phi) + p[1]*TMath::Sin(phi);\n\t p[0]=pn1;\n\t p[1]=pn2;\n\t Float_t on1=origin[0]*TMath::Sin(phi)-origin[1]*TMath::Cos(phi);\n\t Float_t on2=origin[0]*TMath::Cos(phi)+origin[1]*TMath::Sin(phi);\n\t origin[0]=on1;\n\t origin[1]=on2;\n\t nstack++;\n\t}\n\tif (nstack == 0) continue;\n }\n \n TFile *pFile=0;\n\/\/ Get AliRun object or create it \n if (!gAlice) {\n\tgAlice = (AliRun*)pFile->Get(\"gAlice\");\n\tif (gAlice) printf(\"AliRun object found on file\\n\");\n\tif (!gAlice) gAlice = new AliRun(\"gAlice\",\"Alice test program\");\n }\n TTree *fAli=gAlice->TreeK();\n if (fAli) pFile =fAli->GetCurrentFile();\n pFile->cd();\n}\n\n\nAliGenFLUKAsource& AliGenFLUKAsource::operator=(const AliGenFLUKAsource& rhs)\n{\n\/\/ Assignment operator\n rhs.Copy(*this);\n return (*this);\n}\n\n\nvoid AliGenFLUKAsource::Copy(AliGenFLUKAsource &) const\n{\n Fatal(\"Copy\",\"Not implemented!\\n\");\n}\n\n\n\n\n\n<commit_msg>Including RVersion.h<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/ Read background particles from a FLUKA boundary source file\n\/\/ This is a very special generator that works for background studies for the muon-spectrometer.\n\/\/ The input files come from FLUKA simulations.\n\/\/ Files can be chained. \n\/\/ Author: andreas.morsch@cern.ch\n\n#include <RVersion.h>\n#include \"TPDGCode.h\"\n#include \"TDatabasePDG.h\"\n\n#include \"AliGenFLUKAsource.h\"\n#include \"AliRun.h\"\n\n\n#include <TFile.h>\n#include <TTree.h>\n#include <TChain.h>\n#include <stdlib.h>\nClassImp(AliGenFLUKAsource)\n\nAliGenFLUKAsource::AliGenFLUKAsource()\n\t :AliGenerator(-1)\n{\n \/\/ Constructor\n fName=\"FLUKA\";\n fTitle=\"FLUKA Boundary Source\";\n \/\/ Read in all particle types by default\n fIkine=6;\n \/\/ Set maximum admitted age of particles to 1.e-05 by default \n fAgeMax=1.e-05;\n \/\/ Do not add weight\n fAddWeight=1.;\n \/\/ Shift the z-coordinate of the impact point by 4.5 cm only if it reads \n \/\/ from specific boundary source to the chamber (fZshift=4.5;),else there \n \/\/ is no need to shift as it reads boundary source for the whole volume of \n \/\/ the Muon Arm; the default value corresponds to boundary source for the\n \/\/ whole volume of the MUON Arm \n fZshift=0;\n \/\/ Set the default file \n fFileName=\"\";\n\n fTreeFluka=0;\n fTreeChain = new TChain(\"h1\");\n\/\/\n\/\/ Read all particles\n fNpart=-1;\n}\n\nAliGenFLUKAsource::AliGenFLUKAsource(Int_t npart)\n :AliGenerator(npart)\n{\n \/\/ Constructor\n fName = \"FLUKA\";\n fTitle = \"FLUKA Boundary Source\";\n \/\/ Read in all particle types by default\n fIkine=6;\n \/\/ Set maximum admitted age of particles to 1.e-05 by default \n fAgeMax=1.e-05;\n \/\/ Do not add weight\n fAddWeight=1.;\n \/\/ Shift the z-coordinate of the impact point by 4.5 cm only if it reads \n \/\/ from specific boundary source to the chamber (fZshift=4.5;),else there \n \/\/ is no need to shift as it reads boundary source for the whole volume of \n \/\/ the Muon Arm; the default value corresponds to boundary source for the\n \/\/ whole volume of the MUON Arm \n fZshift=0;\n \/\/ Set the default file \n fFileName=\"\";\n\n fTreeFluka=0;\n fTreeChain = new TChain(\"h1\"); \n fSourceId=-1;\n}\n\nAliGenFLUKAsource::AliGenFLUKAsource(const AliGenFLUKAsource & FLUKAsource):\n AliGenerator(FLUKAsource)\n{\n\/\/ Copy constructor\n FLUKAsource.Copy(*this);\n}\n\n\n\/\/____________________________________________________________\nAliGenFLUKAsource::~AliGenFLUKAsource()\n{\n\/\/ Destructor\n if (fTreeFluka) delete fTreeFluka;\n if (fTreeChain) delete fTreeChain;\n}\n\nvoid AliGenFLUKAsource::AddFile(const Text_t *filename)\n{\n\/\/ Add a file to the chain\n fTreeChain->Add(filename);\n \n}\n\n\n\/\/____________________________________________________________\nvoid AliGenFLUKAsource::FlukaInit() \n{\n\/\/ Set branch addresses of data entries\n TChain *h2=fTreeChain;\n\/\/Set branch addresses\n h2->SetBranchAddress(\"Ip\",&fIp);\n h2->SetBranchAddress(\"Ipp\",&fIpp);\n h2->SetBranchAddress(\"Xi\",&fXi);\n h2->SetBranchAddress(\"Yi\",&fYi);\n h2->SetBranchAddress(\"Zi\",&fZi);\n h2->SetBranchAddress(\"Px\",&fPx);\n h2->SetBranchAddress(\"Py\",&fPy);\n h2->SetBranchAddress(\"Pz\",&fPz);\n h2->SetBranchAddress(\"Ekin\",&fEkin);\n h2->SetBranchAddress(\"Zv\",&fZv);\n h2->SetBranchAddress(\"Rv\",&fRv);\n h2->SetBranchAddress(\"Itra\",&fItra);\n h2->SetBranchAddress(\"Igas\",&fIgas);\n h2->SetBranchAddress(\"Wgt\",&fWgt);\n h2->SetBranchAddress(\"Etag\",&fEtag);\n h2->SetBranchAddress(\"Ptg\",&fPtg);\n h2->SetBranchAddress(\"Age\",&fAge);\n}\n\n\/\/____________________________________________________________\nvoid AliGenFLUKAsource::Generate()\n{\n\/\/ Generate one event \n\n const Int_t kIfluge[28]={kProton, kProtonBar, kElectron, kPositron,\n\t\t\t kNuE, kNuEBar, kGamma, kNeutron, kNeutronBar,\n\t\t\t kMuonPlus, kMuonMinus, kK0Long , kPiPlus, kPiMinus,\n\t\t\t kKPlus, kKMinus, kLambda0, kLambda0Bar, kK0Short,\n\t\t\t kSigmaMinus, kSigmaPlus, kSigma0, kPi0, kK0, kK0Bar,\n\t\t\t 0,kNuMu,kNuMuBar};\n Float_t polar[3]= {0,0,0};\n \/\/\n Float_t origin[3];\n Float_t p[3];\n Float_t prwn;\n Float_t wgt, fwgt;\n Float_t phi;\n Float_t amass;\n Int_t iwgt;\n Int_t i, j, part, nt;\n static Int_t irwn=0;\n \/\/\n Float_t random[2];\n \/\/\n FlukaInit();\n TChain *h2=fTreeChain;\n Int_t nentries = (Int_t) h2->GetEntries();\n if (fNpart == -1) fNpart=Int_t(nentries*fFrac);\n \n\n \/\/ loop over number of particles\n Int_t nb=0;\n Int_t ev=gMC->CurrentEvent();\n for (i=0; i<fNpart;i++) {\n\tInt_t entry=fNpart*(ev-1)+i; \n\tnb = (Int_t)h2->GetEvent(entry); \n\tif (irwn > nentries) {\n\t printf(\"No more entries in the FLUKA boundary source file\\n\");\n\t TFile *pFile=0;\n\t \/\/ Get AliRun object or create it \n\t if (!gAlice) {\n\t\tgAlice = (AliRun*)pFile->Get(\"gAlice\");\n\t\tif (gAlice) printf(\"AliRun object found on file\\n\");\n\t\tif (!gAlice) gAlice = new AliRun(\"gAlice\",\"Alice test program\");\n\t }\n\t TTree *fAli=gAlice->TreeK();\n\t if (fAli) pFile =fAli->GetCurrentFile();\n\t pFile->cd();\n\t printf(\"Generate - I'm out \\n\");\n\t return;\n\t} \n\t\n\tInt_t ifip = Int_t(fIp);\n\t\n\n\tif (fSourceId != -1 && fIgas !=fSourceId) {\n\t irwn++;\n\t continue;\n\t}\n\t\n\tif (ifip > 28 || ifip < 0) {\n\t irwn++;\n\t continue;\n\t}\n\t\n\tif ((ifip != fIkine && fIkine != kAll && fIkine != kCharged \n\t && fIkine != 10) || fAge > fAgeMax){\n\t irwn++;\n\t continue;\n\t} else if (fIkine == kCharged) {\n\t if (ifip == 7 || ifip == 8 || fAge > fAgeMax) { \n\t\tirwn++;\n\t\tcontinue;\n\t }\n\t} else if (fIkine == kNoNeutron) {\n\t if (ifip == 8 || fAge > fAgeMax) { \n\t\tirwn++;\n\t\tcontinue;\n\t }\n\t}\n \n\n\tirwn++;\n\/\/\n\/\/ PDG code from FLUKA particle type (ifip)\n\tpart=kIfluge[int(ifip)-1];\t\n\/\/\n\/\/ Calculate momentum from kinetic energy and mass of the particle\n#if ROOT_VERSION_CODE > 197895\n amass = gMC->ParticleMass(part);\n#else\n\tamass = (TDatabasePDG::Instance())->GetParticle(part)->Mass();\n#endif\n\tprwn=fEkin*sqrt(1. + 2.*amass\/fEkin);\n\n\n\torigin[0]=fYi;\n\torigin[1]=fXi;\n\torigin[2]=fZi;\n\t\n\tp[0]=fPy*prwn;\n\tp[1]=fPx*prwn;\n\tp[2]=fPz*prwn;\n\n\t\/\/handle particle weight correctly\n\twgt = (part == 13) ? fWgt*fAddWeight : fWgt;\n\tiwgt=Int_t(wgt);\n\tfwgt=wgt-Float_t(iwgt);\n\tRndm(random,2);\n\tif (random[0] < fwgt) iwgt++;\n\tif (part==1 && iwgt>100) iwgt=100;\n\tInt_t nstack=0;\n\tfor (j=0; j<iwgt; j++) {\n\t PushTrack(fTrackIt,-1,part,p,origin,polar,fAge,kPPrimary,nt);\n\t Rndm(random,2);\n\t phi=2*random[1]*TMath::Pi();\n\t Float_t pn1=p[0]*TMath::Sin(phi) - p[1]*TMath::Cos(phi);\n\t Float_t pn2=p[0]*TMath::Cos(phi) + p[1]*TMath::Sin(phi);\n\t p[0]=pn1;\n\t p[1]=pn2;\n\t Float_t on1=origin[0]*TMath::Sin(phi)-origin[1]*TMath::Cos(phi);\n\t Float_t on2=origin[0]*TMath::Cos(phi)+origin[1]*TMath::Sin(phi);\n\t origin[0]=on1;\n\t origin[1]=on2;\n\t nstack++;\n\t}\n\tif (nstack == 0) continue;\n }\n \n TFile *pFile=0;\n\/\/ Get AliRun object or create it \n if (!gAlice) {\n\tgAlice = (AliRun*)pFile->Get(\"gAlice\");\n\tif (gAlice) printf(\"AliRun object found on file\\n\");\n\tif (!gAlice) gAlice = new AliRun(\"gAlice\",\"Alice test program\");\n }\n TTree *fAli=gAlice->TreeK();\n if (fAli) pFile =fAli->GetCurrentFile();\n pFile->cd();\n}\n\n\nAliGenFLUKAsource& AliGenFLUKAsource::operator=(const AliGenFLUKAsource& rhs)\n{\n\/\/ Assignment operator\n rhs.Copy(*this);\n return (*this);\n}\n\n\nvoid AliGenFLUKAsource::Copy(AliGenFLUKAsource &) const\n{\n Fatal(\"Copy\",\"Not implemented!\\n\");\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ coding: utf-8\n\/* Copyright (c) 2013, Roboterclub Aachen e.V.\n* All Rights Reserved.\n*\n* The file is part of the xpcc library and is released under the 3-clause BSD\n* license. See the file `LICENSE` for the full license governing this code.\n*\/\n\/\/ ----------------------------------------------------------------------------\n\n\/\/\n\/\/ STM32F4DISCOVERY\n\/\/ Discovery kit for STM32F407\/417 lines\n\/\/ http:\/\/www.st.com\/web\/en\/catalog\/tools\/FM116\/SC959\/SS1532\/PF252419\n\/\/\n\n#ifndef XPCC_STM32_F4_DISCOVERY_HPP\n#define XPCC_STM32_F4_DISCOVERY_HPP\n\n#include <xpcc\/architecture\/platform.hpp>\n#include <xpcc\/driver\/inertial\/lis3dsh.hpp>\n\nusing namespace xpcc::stm32;\n\n\nnamespace Board\n{\n\n\/\/\/ STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the\n\/\/\/ external on-board 8MHz crystal\ntypedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock;\n\n\ntypedef GpioInputA0 Button;\t\/\/ Blue PushButton\ntypedef GpioOutputA8 ClockOut;\ntypedef GpioOutputC9 SystemClockOut;\n\n\ntypedef GpioOutputD13 LedOrange;\t\/\/ User LED 3\ntypedef GpioOutputD12 LedGreen;\t\t\/\/ User LED 4\ntypedef GpioOutputD14 LedRed;\t\t\/\/ User LED 5\ntypedef GpioOutputD15 LedBlue;\t\t\/\/ User LED 6\n\n\nnamespace lis3\n{\ntypedef GpioInputE1\t\tInt;\t\/\/ LIS302DL_INT2\n\ntypedef GpioOutputE3\tCs;\t\t\/\/ LIS302DL_CS_I2C\/SPI\ntypedef GpioOutputA5\tSck;\t\/\/ SPI1_SCK\ntypedef GpioOutputA7\tMosi;\t\/\/ SPI1_MOSI\ntypedef GpioInputA6\t\tMiso;\t\/\/ SPI1_MISO\n\ntypedef SpiMaster1 SpiMaster;\ntypedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport;\n}\n\n\nnamespace cs43\n{\ntypedef GpioOutputA4\tLrck;\t\/\/ I2S3_WS\ntypedef GpioOutputC7\tMclk;\t\/\/ I2S3_MCK\ntypedef GpioOutputC10\tSclk;\t\/\/ I2S3_SCK\ntypedef GpioOutputC12\tSdin;\t\/\/ I2S3_SD\n\ntypedef GpioOutputD4\tReset;\t\/\/ Audio_RST\ntypedef GpioB6\t\t\tScl;\t\/\/ Audio_SCL\ntypedef GpioB9\t\t\tSda;\t\/\/ Audio_SDA\n\ntypedef I2cMaster1 I2cMaster;\n\/\/typedef I2sMaster3 I2sMaster;\n}\n\n\nnamespace mp45\n{\ntypedef GpioOutputB10\tClk;\t\/\/ CLK_IN: I2S2_CK\ntypedef GpioInputC3\t\tDout;\t\/\/ PDM_OUT: I2S2_SD\n\/\/typedef I2sMaster2 I2sMaster;\n}\n\n\nnamespace usb\n{\ntypedef GpioA11\tDm;\t\t\/\/ OTG_FS_DM: USB_OTG_FS_DM\ntypedef GpioA12\tDp;\t\t\/\/ OTG_FS_DP: USB_OTG_FS_DP\ntypedef GpioA10\tId;\t\t\/\/ OTG_FS_ID: USB_OTG_FS_ID\n\ntypedef GpioD5\t\t\tOvercurrent;\t\/\/ OTG_FS_OverCurrent\ntypedef GpioOutputC0\tPower;\t\t\t\/\/ OTG_FS_PowerSwitchOn\ntypedef GpioInputA9\t\tVBus;\t\t\t\/\/ VBUS_FS: USB_OTG_HS_VBUS\n\/\/typedef UsbFs Device;\n}\n\n\ninline void\ninitialize()\n{\n\tsystemClock::enable();\n\txpcc::cortex::SysTickTimer::enable();\n\n\tLedOrange::setOutput(xpcc::Gpio::Low);\n\tLedGreen::setOutput(xpcc::Gpio::Low);\n\tLedRed::setOutput(xpcc::Gpio::Low);\n\tLedBlue::setOutput(xpcc::Gpio::Low);\n\n\tButton::setInput();\n\tButton::setInputTrigger(Gpio::InputTrigger::RisingEdge);\n\tButton::enableExternalInterrupt();\n\/\/\tButton::enableExternalInterruptVector(12);\n}\n\ninline void\ninitializeLis3()\n{\n\tlis3::Int::setInput();\n\tlis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge);\n\tlis3::Int::enableExternalInterrupt();\n\/\/\tlis3::Int::enableExternalInterruptVector(12);\n\n\tlis3::Cs::setOutput(xpcc::Gpio::High);\n\n\tlis3::Sck::connect(lis3::SpiMaster::Sck);\n\tlis3::Mosi::connect(lis3::SpiMaster::Mosi);\n\tlis3::Miso::connect(lis3::SpiMaster::Miso);\n\n\tlis3::SpiMaster::initialize<systemClock, MHz10>();\n\tlis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3);\n}\n\n\/\/\/ not supported yet, due to missing I2S driver\ninline void\ninitializeCs43()\n{\n\/\/\tcs43::Lrck::connect(cs43::I2sMaster::Ws);\n\/\/\tcs43::Mclk::connect(cs43::I2sMaster::Mck);\n\/\/\tcs43::Sclk::connect(cs43::I2sMaster::Ck);\n\/\/\tcs43::Sdin::connect(cs43::I2sMaster::Sd);\n\n\tcs43::Reset::setOutput(xpcc::Gpio::High);\n\n\tcs43::Scl::connect(cs43::I2cMaster::Scl);\n\tcs43::Sda::connect(cs43::I2cMaster::Sda);\n\tcs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>();\n}\n\n\/\/\/ not supported yet, due to missing I2S driver\ninline void\ninitializeMp45()\n{\n\/\/\tmp45::Clk::connect(mp45::I2sMaster::Ck);\n\/\/\tmp45::Dout::connect(mp45::I2sMaster::Sd);\n}\n\n\/\/\/ not supported yet, due to missing USB driver\ninline void\ninitializeUsb()\n{\n\/\/\tusb::Dm::connect(usb::Device::Dm);\n\/\/\tusb::Dp::connect(usb::Device::Dp);\n\/\/\tusb::Id::connect(usb::Device::Id);\n\n\tusb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2);\n\n\tusb::Overcurrent::setInput(Gpio::InputType::Floating);\n\tusb::Vbus::setInput(Gpio::InputType::Floating);\n}\n\n}\n\n#endif\t\/\/ XPCC_STM32_F4_DISCOVERY_HPP\n<commit_msg>Examples: STM32F4: Typo.<commit_after>\/\/ coding: utf-8\n\/* Copyright (c) 2013, Roboterclub Aachen e.V.\n* All Rights Reserved.\n*\n* The file is part of the xpcc library and is released under the 3-clause BSD\n* license. See the file `LICENSE` for the full license governing this code.\n*\/\n\/\/ ----------------------------------------------------------------------------\n\n\/\/\n\/\/ STM32F4DISCOVERY\n\/\/ Discovery kit for STM32F407\/417 lines\n\/\/ http:\/\/www.st.com\/web\/en\/catalog\/tools\/FM116\/SC959\/SS1532\/PF252419\n\/\/\n\n#ifndef XPCC_STM32_F4_DISCOVERY_HPP\n#define XPCC_STM32_F4_DISCOVERY_HPP\n\n#include <xpcc\/architecture\/platform.hpp>\n#include <xpcc\/driver\/inertial\/lis3dsh.hpp>\n\nusing namespace xpcc::stm32;\n\n\nnamespace Board\n{\n\n\/\/\/ STM32F4 running at 168MHz (USB Clock qt 48MHz) generated from the\n\/\/\/ external on-board 8MHz crystal\ntypedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz168, MHz48> > systemClock;\n\n\ntypedef GpioInputA0 Button;\t\/\/ Blue PushButton\ntypedef GpioOutputA8 ClockOut;\ntypedef GpioOutputC9 SystemClockOut;\n\n\ntypedef GpioOutputD13 LedOrange;\t\/\/ User LED 3\ntypedef GpioOutputD12 LedGreen;\t\t\/\/ User LED 4\ntypedef GpioOutputD14 LedRed;\t\t\/\/ User LED 5\ntypedef GpioOutputD15 LedBlue;\t\t\/\/ User LED 6\n\n\nnamespace lis3\n{\ntypedef GpioInputE1\t\tInt;\t\/\/ LIS302DL_INT2\n\ntypedef GpioOutputE3\tCs;\t\t\/\/ LIS302DL_CS_I2C\/SPI\ntypedef GpioOutputA5\tSck;\t\/\/ SPI1_SCK\ntypedef GpioOutputA7\tMosi;\t\/\/ SPI1_MOSI\ntypedef GpioInputA6\t\tMiso;\t\/\/ SPI1_MISO\n\ntypedef SpiMaster1 SpiMaster;\ntypedef xpcc::Lis3TransportSpi< SpiMaster, Cs > Transport;\n}\n\n\nnamespace cs43\n{\ntypedef GpioOutputA4\tLrck;\t\/\/ I2S3_WS\ntypedef GpioOutputC7\tMclk;\t\/\/ I2S3_MCK\ntypedef GpioOutputC10\tSclk;\t\/\/ I2S3_SCK\ntypedef GpioOutputC12\tSdin;\t\/\/ I2S3_SD\n\ntypedef GpioOutputD4\tReset;\t\/\/ Audio_RST\ntypedef GpioB6\t\t\tScl;\t\/\/ Audio_SCL\ntypedef GpioB9\t\t\tSda;\t\/\/ Audio_SDA\n\ntypedef I2cMaster1 I2cMaster;\n\/\/typedef I2sMaster3 I2sMaster;\n}\n\n\nnamespace mp45\n{\ntypedef GpioOutputB10\tClk;\t\/\/ CLK_IN: I2S2_CK\ntypedef GpioInputC3\t\tDout;\t\/\/ PDM_OUT: I2S2_SD\n\/\/typedef I2sMaster2 I2sMaster;\n}\n\n\nnamespace usb\n{\ntypedef GpioA11\tDm;\t\t\/\/ OTG_FS_DM: USB_OTG_FS_DM\ntypedef GpioA12\tDp;\t\t\/\/ OTG_FS_DP: USB_OTG_FS_DP\ntypedef GpioA10\tId;\t\t\/\/ OTG_FS_ID: USB_OTG_FS_ID\n\ntypedef GpioD5\t\t\tOvercurrent;\t\/\/ OTG_FS_OverCurrent\ntypedef GpioOutputC0\tPower;\t\t\t\/\/ OTG_FS_PowerSwitchOn\ntypedef GpioInputA9\t\tVBus;\t\t\t\/\/ VBUS_FS: USB_OTG_HS_VBUS\n\/\/typedef UsbFs Device;\n}\n\n\ninline void\ninitialize()\n{\n\tsystemClock::enable();\n\txpcc::cortex::SysTickTimer::enable();\n\n\tLedOrange::setOutput(xpcc::Gpio::Low);\n\tLedGreen::setOutput(xpcc::Gpio::Low);\n\tLedRed::setOutput(xpcc::Gpio::Low);\n\tLedBlue::setOutput(xpcc::Gpio::Low);\n\n\tButton::setInput();\n\tButton::setInputTrigger(Gpio::InputTrigger::RisingEdge);\n\tButton::enableExternalInterrupt();\n\/\/\tButton::enableExternalInterruptVector(12);\n}\n\ninline void\ninitializeLis3()\n{\n\tlis3::Int::setInput();\n\tlis3::Int::setInputTrigger(Gpio::InputTrigger::RisingEdge);\n\tlis3::Int::enableExternalInterrupt();\n\/\/\tlis3::Int::enableExternalInterruptVector(12);\n\n\tlis3::Cs::setOutput(xpcc::Gpio::High);\n\n\tlis3::Sck::connect(lis3::SpiMaster::Sck);\n\tlis3::Mosi::connect(lis3::SpiMaster::Mosi);\n\tlis3::Miso::connect(lis3::SpiMaster::Miso);\n\n\tlis3::SpiMaster::initialize<systemClock, MHz10>();\n\tlis3::SpiMaster::setDataMode(lis3::SpiMaster::DataMode::Mode3);\n}\n\n\/\/\/ not supported yet, due to missing I2S driver\ninline void\ninitializeCs43()\n{\n\/\/\tcs43::Lrck::connect(cs43::I2sMaster::Ws);\n\/\/\tcs43::Mclk::connect(cs43::I2sMaster::Mck);\n\/\/\tcs43::Sclk::connect(cs43::I2sMaster::Ck);\n\/\/\tcs43::Sdin::connect(cs43::I2sMaster::Sd);\n\n\tcs43::Reset::setOutput(xpcc::Gpio::High);\n\n\tcs43::Scl::connect(cs43::I2cMaster::Scl);\n\tcs43::Sda::connect(cs43::I2cMaster::Sda);\n\tcs43::I2cMaster::initialize<systemClock, cs43::I2cMaster::Baudrate::Standard>();\n}\n\n\/\/\/ not supported yet, due to missing I2S driver\ninline void\ninitializeMp45()\n{\n\/\/\tmp45::Clk::connect(mp45::I2sMaster::Ck);\n\/\/\tmp45::Dout::connect(mp45::I2sMaster::Sd);\n}\n\n\/\/\/ not supported yet, due to missing USB driver\ninline void\ninitializeUsb()\n{\n\/\/\tusb::Dm::connect(usb::Device::Dm);\n\/\/\tusb::Dp::connect(usb::Device::Dp);\n\/\/\tusb::Id::connect(usb::Device::Id);\n\n\tusb::Power::setOutput(Gpio::OutputType::PushPull, Gpio::OutputSpeed::MHz2);\n\n\tusb::Overcurrent::setInput(Gpio::InputType::Floating);\n\tusb::VBus::setInput(Gpio::InputType::Floating);\n}\n\n}\n\n#endif\t\/\/ XPCC_STM32_F4_DISCOVERY_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_get_poundv_bucket_attr.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_get_poundv_bucket_attr.C\n\/\/\/ @brief Grab PM data from certain bucket in #V keyword in LRPX record\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_pm_get_poundv_bucket_attr.H>\n#include <p9_pm_get_poundv_bucket.H>\n#include <mvpd_access_defs.H>\n#include <attribute_ids.H>\n\nfapi2::ReturnCode p9_pm_get_poundv_bucket_attr(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n uint8_t* o_data)\n{\n FAPI_DBG(\"Entering p9_pm_get_poundv_bucket_attr ....\");\n uint8_t* l_prDataPtr = NULL;\n uint8_t* l_fullVpdData = NULL;\n uint8_t l_overridePresent = 0;\n uint32_t l_tempVpdSize = 0;\n uint32_t l_vpdSize = 0;\n uint8_t l_eqChipUnitPos = 0;\n uint8_t l_bucketId;\n uint8_t l_bucketSize = 0;\n uint32_t l_sysNestFreq = 0;\n fapi2::voltageBucketData_t* l_currentBucket = NULL;\n uint8_t l_numMatches = 0;\n\n fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;\n \/\/To read MVPD we will need the proc parent of the inputted EQ target\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =\n i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();\n\n\n \/\/Need to determine which LRP record to read from depending on which\n \/\/bucket we are getting the power management data from. FapiPos will\n \/\/tell us which LRP record to use.\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,\n i_target,\n l_eqChipUnitPos));\n\n FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,\n fapi2::INVALID_EQ_CHIP_POS().\n set_EQ_POSITION( l_eqChipUnitPos ),\n \"Invalid EQ chip unit position = 0x%X\",\n l_eqChipUnitPos);\n\n \/\/The enumeration for the LRPx records are just 3 more\n \/\/than the EQ chip unit pos. See mvpd_access_defs.H\n lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +\n fapi2::MVPD_RECORD_LRP0 );\n\n\n \/\/check if bucket num has been overriden\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,\n i_target,\n l_overridePresent));\n\n if(l_overridePresent != 0)\n {\n \/\/If it has been overriden then get the override\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,\n i_target,\n l_bucketId));\n }\n else\n {\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n\n \/\/save off the actual vpd size\n l_vpdSize = l_tempVpdSize;\n \/\/Allocate memory for vpd data\n l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n l_fullVpdData,\n l_tempVpdSize) );\n\n \/\/Version 2:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x33 byte\n \/\/bucket b: 0x33 byte\n \/\/bucket c: 0x33 byte\n \/\/bucket d: 0x33 byte\n \/\/bucket e: 0x33 byte\n \/\/bucket f: 0x33 byte\n if( *l_fullVpdData == POUNDV_VERSION_2)\n {\n \/\/Set the size of the bucket\n l_bucketSize = VERSION_2_BUCKET_SIZE;\n\n \/\/Reset VPD size because we want to find size of another VPD record\n l_tempVpdSize = 0;\n\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n l_prDataPtr,\n l_tempVpdSize) );\n\n \/\/Bucket ID is byte[4] of the PR keyword\n memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));\n\n }\n \/\/Version 3:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x3D byte\n \/\/bucket b: 0x3D byte\n \/\/bucket c: 0x3D byte\n \/\/bucket d: 0x3D byte\n \/\/bucket e: 0x3D byte\n \/\/bucket f: 0x3D byte\n else if( *l_fullVpdData == POUNDV_VERSION_3 )\n {\n \/\/ Set the size of the bucket\n l_bucketSize = VERSION_3_BUCKET_SIZE;\n\n \/\/ Version 3 uses the nest frequency to choose the bucket Id\n \/\/ get the system target to find the NEST_FREQ_MHZ\n fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;\n\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,\n l_sysParent,\n l_sysNestFreq));\n \/\/cast the voltage data into an array of buckets\n fapi2::voltageBucketData_t* l_buckets = reinterpret_cast\n <fapi2::voltageBucketData_t*>\n (l_fullVpdData + POUNDV_BUCKET_OFFSET);\n\n for(int i = 0; i < NUM_BUCKETS; i++)\n {\n if(l_buckets[i].pbFreq == l_sysNestFreq)\n {\n l_numMatches++;\n\n \/*\n * TODO RTC: 157341\n * Modify function to fail if multiple buckets have same nest\n *\/\n if(l_numMatches > 1)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::\"\n \" Multiple buckets (%d) reporting the same nest frequency\",\n l_numMatches);\n }\n\n \/*\n else\n {\n l_currentBucket = &l_buckets[i];\n }\n *\/\n l_currentBucket = &l_buckets[i];\n }\n }\n\n \/*\n * TODO RTC: 157341\n * Modify function to fail if multiple buckets have same nest\n if(l_numMatches == 1)\n {\n l_bucketId = l_currentBucket->bucketId;\n }\n else\n {\n\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d\",\n l_numMatches );\n FAPI_ASSERT(0,\n fapi2::INVALID_MATCHING_FREQ_NUMBER().\n set_MATCHES_FOUND(l_numMatches),\n \"Matches found is NOT 1\" );\n }\n *\/\n l_bucketId = l_currentBucket->bucketId;\n }\n else\n {\n FAPI_ASSERT( false,\n fapi2::INVALID_POUNDV_VERSION()\n .set_POUNDV_VERSION(*l_fullVpdData),\n \"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x\",\n *l_fullVpdData);\n }\n\n \/\/ This assert ensures the size of the calculated data is correct\n FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *\n l_bucketSize) >= l_bucketSize,\n fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))\n .set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -\n ((l_bucketId - 1) * l_bucketSize)),\n \"#V data read was too small!\" );\n\n }\/\/ else no override\n\n \/\/ Ensure we got a valid bucket id\n \/\/ NOTE: Bucket IDs range from 1-6\n FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),\n fapi2::INVALID_BUCKET_ID()\n .set_TARGET(i_target)\n .set_BUCKET_ID(l_bucketId),\n \"Invalid Bucket Id = %d\",\n l_bucketId );\n\n\n \/\/ Use the selected bucket id to populate the output data\n memcpy(o_data,\n l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,\n l_bucketSize);\n\nfapi_try_exit:\n\n if(l_fullVpdData != NULL)\n {\n free(l_fullVpdData);\n l_fullVpdData = NULL;\n }\n\n if(l_prDataPtr != NULL)\n {\n free(l_prDataPtr);\n l_prDataPtr = NULL;\n }\n\n FAPI_DBG(\"Exiting p9_pm_get_poundv_bucket_attr ....\");\n\n return fapi2::current_err;\n}\n<commit_msg>Modify #V accessor to fail if multiple buckets report same nest<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_get_poundv_bucket_attr.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_get_poundv_bucket_attr.C\n\/\/\/ @brief Grab PM data from certain bucket in #V keyword in LRPX record\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_pm_get_poundv_bucket_attr.H>\n#include <p9_pm_get_poundv_bucket.H>\n#include <mvpd_access_defs.H>\n#include <attribute_ids.H>\n\nfapi2::ReturnCode p9_pm_get_poundv_bucket_attr(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n uint8_t* o_data)\n{\n FAPI_DBG(\"Entering p9_pm_get_poundv_bucket_attr ....\");\n uint8_t* l_prDataPtr = NULL;\n uint8_t* l_fullVpdData = NULL;\n uint8_t l_overridePresent = 0;\n uint32_t l_tempVpdSize = 0;\n uint32_t l_vpdSize = 0;\n uint8_t l_eqChipUnitPos = 0;\n uint8_t l_bucketId;\n uint8_t l_bucketSize = 0;\n uint32_t l_sysNestFreq = 0;\n fapi2::voltageBucketData_t* l_currentBucket = NULL;\n uint8_t l_numMatches = 0;\n\n fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;\n \/\/To read MVPD we will need the proc parent of the inputted EQ target\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =\n i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();\n\n\n \/\/Need to determine which LRP record to read from depending on which\n \/\/bucket we are getting the power management data from. FapiPos will\n \/\/tell us which LRP record to use.\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,\n i_target,\n l_eqChipUnitPos));\n\n FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,\n fapi2::INVALID_EQ_CHIP_POS().\n set_EQ_POSITION( l_eqChipUnitPos ),\n \"Invalid EQ chip unit position = 0x%X\",\n l_eqChipUnitPos);\n\n \/\/The enumeration for the LRPx records are just 3 more\n \/\/than the EQ chip unit pos. See mvpd_access_defs.H\n lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +\n fapi2::MVPD_RECORD_LRP0 );\n\n\n \/\/check if bucket num has been overriden\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,\n i_target,\n l_overridePresent));\n\n if(l_overridePresent != 0)\n {\n \/\/If it has been overriden then get the override\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,\n i_target,\n l_bucketId));\n }\n else\n {\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n\n \/\/save off the actual vpd size\n l_vpdSize = l_tempVpdSize;\n \/\/Allocate memory for vpd data\n l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n l_fullVpdData,\n l_tempVpdSize) );\n\n \/\/Version 2:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x33 byte\n \/\/bucket b: 0x33 byte\n \/\/bucket c: 0x33 byte\n \/\/bucket d: 0x33 byte\n \/\/bucket e: 0x33 byte\n \/\/bucket f: 0x33 byte\n if( *l_fullVpdData == POUNDV_VERSION_2)\n {\n \/\/Set the size of the bucket\n l_bucketSize = VERSION_2_BUCKET_SIZE;\n\n \/\/Reset VPD size because we want to find size of another VPD record\n l_tempVpdSize = 0;\n\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n l_prDataPtr,\n l_tempVpdSize) );\n\n \/\/Bucket ID is byte[4] of the PR keyword\n memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));\n\n }\n \/\/Version 3:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x3D byte\n \/\/bucket b: 0x3D byte\n \/\/bucket c: 0x3D byte\n \/\/bucket d: 0x3D byte\n \/\/bucket e: 0x3D byte\n \/\/bucket f: 0x3D byte\n else if( *l_fullVpdData == POUNDV_VERSION_3 )\n {\n \/\/ Set the size of the bucket\n l_bucketSize = VERSION_3_BUCKET_SIZE;\n\n \/\/ Version 3 uses the nest frequency to choose the bucket Id\n \/\/ get the system target to find the NEST_FREQ_MHZ\n fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;\n\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,\n l_sysParent,\n l_sysNestFreq));\n \/\/cast the voltage data into an array of buckets\n fapi2::voltageBucketData_t* l_buckets = reinterpret_cast\n <fapi2::voltageBucketData_t*>\n (l_fullVpdData + POUNDV_BUCKET_OFFSET);\n\n for(int i = 0; i < NUM_BUCKETS; i++)\n {\n if(l_buckets[i].pbFreq == l_sysNestFreq)\n {\n l_numMatches++;\n\n if(l_numMatches > 1)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::\"\n \" Multiple buckets (%d) reporting the same nest frequency\"\n \" Bucket Nest = %d Bucket ID = %d\",\n l_numMatches,\n l_buckets[i].pbFreq,\n (i + 1));\n\n }\n else\n {\n l_currentBucket = &l_buckets[i];\n }\n }\n }\n\n if(l_numMatches == 1)\n {\n l_bucketId = l_currentBucket->bucketId;\n }\n else\n {\n\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d\",\n l_numMatches );\n FAPI_ASSERT(false,\n fapi2::INVALID_MATCHING_FREQ_NUMBER().\n set_MATCHES_FOUND(l_numMatches),\n \"Matches found is NOT 1\" );\n }\n }\n else\n {\n FAPI_ASSERT( false,\n fapi2::INVALID_POUNDV_VERSION()\n .set_POUNDV_VERSION(*l_fullVpdData),\n \"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x\",\n *l_fullVpdData);\n }\n\n \/\/ This assert ensures the size of the calculated data is correct\n FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *\n l_bucketSize) >= l_bucketSize,\n fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))\n .set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -\n ((l_bucketId - 1) * l_bucketSize)),\n \"#V data read was too small!\" );\n\n }\/\/ else no override\n\n \/\/ Ensure we got a valid bucket id\n \/\/ NOTE: Bucket IDs range from 1-6\n FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),\n fapi2::INVALID_BUCKET_ID()\n .set_TARGET(i_target)\n .set_BUCKET_ID(l_bucketId),\n \"Invalid Bucket Id = %d\",\n l_bucketId );\n\n\n \/\/ Use the selected bucket id to populate the output data\n memcpy(o_data,\n l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,\n l_bucketSize);\n\nfapi_try_exit:\n\n if(l_fullVpdData != NULL)\n {\n free(l_fullVpdData);\n l_fullVpdData = NULL;\n }\n\n if(l_prDataPtr != NULL)\n {\n free(l_prDataPtr);\n l_prDataPtr = NULL;\n }\n\n FAPI_DBG(\"Exiting p9_pm_get_poundv_bucket_attr ....\");\n\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Zillians MMO\n * Copyright (C) 2007-2011 Zillians.com, Inc.\n * For more information see http:\/\/www.zillians.com\n *\n * Zillians MMO is the library and runtime for massive multiplayer online game\n * development in utility computing model, which runs as a service for every\n * developer to build their virtual world running on our GPU-assisted machines.\n *\n * This is a close source library intended to be used solely within Zillians.com\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"language\/stage\/StageConductor.h\"\n#include \"language\/logging\/Logger.h\"\n#include \"utility\/TemplateTricks.h\"\n\nnamespace zillians { namespace language { namespace stage {\n\nStageConductor::StageConductor()\n{ }\n\nStageConductor::~StageConductor()\n{ }\n\nvoid StageConductor::appendStage(shared_ptr<Stage> stage)\n{\n\tmStages.push_back(stage);\n}\n\nint StageConductor::main(int argc, const char** argv)\n{\n\t\/\/ prepare simple logger appender\n\tif(true)\n\t{\n\n\t}\n\telse\n\t{\n\t\tlog4cxx::BasicConfigurator::configure();\n\t}\n\n\t\/\/ call implementation's initialize() to append stages\n\tinitialize();\n\n\tif(true)\n\t{\n\t\tpo::options_description option_desc;\n\t\tpo::positional_options_description positional_option_desc;\n\t\tpo::variables_map vm;\n\n\t\t\/\/ built-in help option\n\t option_desc.add_options()\n\t (\"help,h\", \"show help\");\n\n\t \/\/ ask each stage to append their option description\n\t\tforeach(stage, mStages)\n\t\t\t(*stage)->initializeOptions(option_desc, positional_option_desc);\n\n\t\t\/\/ try to parse the command line\n\t try\n\t {\n\t \tpo::store(po::command_line_parser(argc, argv).options(option_desc).positional(positional_option_desc).run(), vm);\n\t \tpo::notify(vm);\n\t }\n\t catch(...)\n\t {\n\t \tstd::cerr << \"failed to parse command line\" << std::endl;\n\t \tstd::cerr << option_desc << std::endl;\n\t \treturn -1;\n\t }\n\n\t \/\/ if help option is specified, print the options and exit\n\t if(vm.count(\"help\") > 0 || argc < 2)\n\t {\n\t \tstd::cout << \"command line options: \" << std::endl << std::endl;\n\t \tstd::cout << option_desc << std::endl;\n\t \treturn 0;\n\t }\n\n\t \/\/ otherwise, process the given commands through each staged execution\n\n\t \/\/ let each stage determine what to do\n\t\tforeach(stage, mStages)\n\t\t{\n\t\t\tif(!(*stage)->parseOptions(vm))\n\t\t\t{\n\t\t\t\tstd::cerr << \"failed to process command option for stage: \" << (*stage)->name() << std::endl;\n\t\t\t\tstd::cerr << option_desc << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ perform the execution\n\t\tforeach(stage, mStages)\n\t\t{\n\t\t\tif(!(*stage)->execute())\n\t\t\t{\n\t\t\t\tstd::cerr << \"execution failed at stage: \" << (*stage)->name() << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ call implementation's finalize() to remove stages or collect summary\n\tfinalize();\n\n\treturn 0;\n}\n\n} } }\n<commit_msg>initialize logger in stage conductor<commit_after>\/**\n * Zillians MMO\n * Copyright (C) 2007-2011 Zillians.com, Inc.\n * For more information see http:\/\/www.zillians.com\n *\n * Zillians MMO is the library and runtime for massive multiplayer online game\n * development in utility computing model, which runs as a service for every\n * developer to build their virtual world running on our GPU-assisted machines.\n *\n * This is a close source library intended to be used solely within Zillians.com\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"language\/stage\/StageConductor.h\"\n#include \"language\/logging\/Logger.h\"\n#include \"utility\/TemplateTricks.h\"\n\nnamespace zillians { namespace language { namespace stage {\n\nStageConductor::StageConductor()\n{ }\n\nStageConductor::~StageConductor()\n{ }\n\nvoid StageConductor::appendStage(shared_ptr<Stage> stage)\n{\n\tmStages.push_back(stage);\n}\n\nint StageConductor::main(int argc, const char** argv)\n{\n\t\/\/ prepare simple logger appender\n\tif(true)\n\t{\n\t\tLogger::initialize();\n\t}\n\telse\n\t{\n\t\tlog4cxx::BasicConfigurator::configure();\n\t}\n\n\t\/\/ call implementation's initialize() to append stages\n\tinitialize();\n\n\tif(true)\n\t{\n\t\tpo::options_description option_desc;\n\t\tpo::positional_options_description positional_option_desc;\n\t\tpo::variables_map vm;\n\n\t\t\/\/ built-in help option\n\t option_desc.add_options()\n\t (\"help,h\", \"show help\");\n\n\t \/\/ ask each stage to append their option description\n\t\tforeach(stage, mStages)\n\t\t\t(*stage)->initializeOptions(option_desc, positional_option_desc);\n\n\t\t\/\/ try to parse the command line\n\t try\n\t {\n\t \tpo::store(po::command_line_parser(argc, argv).options(option_desc).positional(positional_option_desc).run(), vm);\n\t \tpo::notify(vm);\n\t }\n\t catch(...)\n\t {\n\t \tstd::cerr << \"failed to parse command line\" << std::endl;\n\t \tstd::cerr << option_desc << std::endl;\n\t \treturn -1;\n\t }\n\n\t \/\/ if help option is specified, print the options and exit\n\t if(vm.count(\"help\") > 0 || argc < 2)\n\t {\n\t \tstd::cout << \"command line options: \" << std::endl << std::endl;\n\t \tstd::cout << option_desc << std::endl;\n\t \treturn 0;\n\t }\n\n\t \/\/ otherwise, process the given commands through each staged execution\n\n\t \/\/ let each stage determine what to do\n\t\tforeach(stage, mStages)\n\t\t{\n\t\t\tif(!(*stage)->parseOptions(vm))\n\t\t\t{\n\t\t\t\tstd::cerr << \"failed to process command option for stage: \" << (*stage)->name() << std::endl;\n\t\t\t\tstd::cerr << option_desc << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ perform the execution\n\t\tforeach(stage, mStages)\n\t\t{\n\t\t\tif(!(*stage)->execute())\n\t\t\t{\n\t\t\t\tstd::cerr << \"execution failed at stage: \" << (*stage)->name() << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ call implementation's finalize() to remove stages or collect summary\n\tfinalize();\n\n\treturn 0;\n}\n\n} } }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * GameState.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 15.02.12.\n * code under LGPL\n *\n *\/\n\n#include \"GameState.h\"\n#include \"Game.h\"\n#include \"Settings.h\"\n#include \"CWorm.h\"\n#include \"CBytestream.h\"\n#include \"ClassInfo.h\"\n#include \"ProfileSystem.h\"\n#include \"CServerConnection.h\"\n\nScriptVar_t ObjectState::getValue(AttribRef a) const {\n\tAttribs::const_iterator it = attribs.find(a);\n\tif(it == attribs.end())\n\t\treturn a.getAttrDesc()->defaultValue;\n\treturn it->second.value;\n}\n\nGameStateUpdates::operator bool() const {\n\tif(!objs.empty()) return true;\n\tif(!objCreations.empty()) return true;\n\tif(!objDeletions.empty()) return true;\n\treturn false;\n}\n\nvoid GameStateUpdates::writeToBs(CBytestream* bs) const {\n\tbs->writeInt16((uint16_t)objCreations.size());\n\tforeach(o, objCreations) {\n\t\to->writeToBs(bs);\n\t}\n\n\tbs->writeInt16((uint16_t)objDeletions.size());\n\tforeach(o, objDeletions) {\n\t\to->writeToBs(bs);\n\t}\n\n\tbs->writeInt((uint32_t)objs.size(), 4);\n\tforeach(a, objs) {\n\t\tconst ObjAttrRef& attr = *a;\n\t\tScriptVar_t curValue = a->get();\n\t\tattr.writeToBs(bs);\n\t\tbs->writeVar(curValue);\n\t}\n}\n\nstatic BaseObject* getObjFromRef(ObjRef r) {\n\tswitch(r.classId) {\n\tcase LuaID<Game>::value: return &game;\n\tcase LuaID<CWorm>::value: return game.wormById(r.objId, false);\n\tdefault: break;\n\t}\n\treturn NULL;\n}\n\nstatic bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) {\n\treturn classInfo->isTypeOf(attrDesc->objTypeId);\n}\n\nstatic bool ownObject(ObjRef o) {\n\t\/\/ This is very custom right now and need to be made somewhat more general.\n\tif(o.classId == LuaID<CWorm>::value) {\n\t\tCWorm* w = game.wormById(o.objId, false);\n\t\tif(!w) return false;\n\t\treturn w->getLocal();\n\t}\n\tif(game.isServer()) return true;\n\treturn false;\n}\n\n\/\/ This only make sense as server.\nstatic bool ownObject(CServerConnection* source, ObjRef o) {\n\tassert(game.isServer());\n\t\/\/ This is very custom right now and need to be made somewhat more general.\n\tif(o.classId == LuaID<CWorm>::value) {\n\t\treturn source->OwnsWorm(o.objId);\n\t}\n\treturn false;\n}\n\nvoid GameStateUpdates::handleFromBs(CBytestream* bs, CServerConnection* source) {\n\tif(game.isServer()) {\n\t\tassert(source != NULL);\n\t\tif(source->isLocalClient()) {\n\t\t\t\/\/ This shouldn't happen. It means sth in our server connection list is messed up.\n\t\t\terrors << \"GameStateUpdates::handleFromBs as server from local client\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t}\n\telse\n\t\tassert(source == NULL);\n\n\tuint16_t creationsNum = bs->readInt16();\n\tfor(uint16_t i = 0; i < creationsNum; ++i) {\n\t\tObjRef r;\n\t\tr.readFromBs(bs);\n\t\t\/\/BaseObject* o = getClassInfo(r.classId)->createInstance();\n\t\t\/\/o->thisRef.classId = r.classId;\n\t\t\/\/o->thisRef.objId = r.objId;\n\n\t\t\/\/ we only handle\/support CWorm objects for now...\n\t\tif(game.isServer()) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: got obj creation as server: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(r.classId != LuaID<CWorm>::value) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-creation: invalid class: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(game.wormById(r.objId, false) != NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: worm-creation: worm \" << r.objId << \" already exists\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tgame.createNewWorm(r.objId, false, NULL, Version());\n\t}\n\n\tuint16_t deletionsNum = bs->readInt16();\n\tfor(uint16_t i = 0; i < deletionsNum; ++i) {\n\t\tObjRef r;\n\t\tr.readFromBs(bs);\n\n\t\t\/\/ we only handle\/support CWorm objects for now...\n\t\tif(game.isServer()) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: got obj deletion as server: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(r.classId != LuaID<CWorm>::value) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-deletion: invalid class: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tCWorm* w = game.wormById(r.objId, false);\n\t\tif(!w) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-deletion: worm \" << r.objId << \" does not exist\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tgame.removeWorm(w);\n\t}\n\n\tuint32_t attrUpdatesNum = bs->readInt(4);\n\tfor(uint32_t i = 0; i < attrUpdatesNum; ++i) {\n\t\tObjAttrRef r;\n\t\tr.readFromBs(bs);\n\n\t\tconst AttrDesc* attrDesc = r.attr.getAttrDesc();\n\t\tif(attrDesc == NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: AttrDesc for update not found\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\tconst ClassInfo* classInfo = getClassInfo(r.obj.classId);\n\t\tif(classInfo == NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: class \" << r.obj.classId << \" for obj-update unknown\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\tif(!attrBelongsToClass(classInfo, attrDesc)) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: attr \" << attrDesc->description() << \" does not belong to class \" << r.obj.classId << \" for obj-update\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ see GameStateUpdates::diffFromStateToCurrent for the other side\n\t\tif(attrDesc->serverside) {\n\t\t\tif(game.isServer()) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got serverside attr update as server: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse { \/\/ client-side attr\n\t\t\tif(game.isServer() && !ownObject(source, r.obj)) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got update from not-authorized client \" << source->debugName() << \": \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tScriptVar_t v;\n\t\tbs->readVar(v);\n\n\t\t\/\/ for now, this is somewhat specific to the only types we support\n\t\tif(r.obj.classId == LuaID<Settings>::value) {\n\t\t\tif(game.isServer()) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got settings update as server\" << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(!Settings::getAttrDescs().belongsToUs(attrDesc)) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: settings update AttrDesc \" << attrDesc->description() << \" is not a setting attr\" << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tFeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc);\n\t\t\tcClient->getGameLobby().overwrite[fIndex] = v;\n\t\t}\n\t\telse {\n\t\t\tBaseObject* o = getObjFromRef(r.obj);\n\t\t\tif(o == NULL) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: object for attr update not found: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(o->thisRef != r.obj) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: object-ref for attr update invalid: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(attrDesc == game.state.attrDesc()) {\n\t\t\t\tif((int)v == Game::S_Quit) {\n\t\t\t\t\tnotes << \"GameStateUpdates: server quitted OLX, we just go to inactive\" << endl;\n\t\t\t\t\tv = Game::S_Inactive;\n\t\t\t\t}\n\t\t\t}\n\t\t\tattrDesc->set(o, v, true);\n\t\t}\n\n\t\t\/\/notes << \"game state update: <\" << r.obj.description() << \"> \" << attrDesc->attrName << \" to \" << v.toString() << endl;\n\t}\n}\n\nvoid GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) {\n\tobjs.insert(a);\n}\n\nvoid GameStateUpdates::pushObjCreation(ObjRef o) {\n\tobjDeletions.erase(o);\n\tobjCreations.insert(o);\n}\n\nvoid GameStateUpdates::pushObjDeletion(ObjRef o) {\n\tObjs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o));\n\tObjs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o));\n\tobjs.erase(itStart, itEnd);\n\tobjCreations.erase(o);\n\tobjDeletions.insert(o);\n}\n\nvoid GameStateUpdates::reset() {\n\tobjs.clear();\n\tobjCreations.clear();\n\tobjDeletions.clear();\n}\n\nvoid GameStateUpdates::diffFromStateToCurrent(const GameState& s) {\n\treset();\n\tforeach(o, game.gameStateUpdates->objCreations) {\n\t\tif(game.isClient()) continue; \/\/ none-at-all right now... worm-creation is handled independently atm\n\t\tif(!ownObject(*o)) continue;\n\t\tif(!s.haveObject(*o))\n\t\t\tpushObjCreation(*o);\n\t}\n\tforeach(u, game.gameStateUpdates->objs) {\n\t\tif(!ownObject(u->obj)) continue;\n\t\tconst AttrDesc* attrDesc = u->attr.getAttrDesc();\n\t\tif(attrDesc->serverside) {\n\t\t\tif(game.isClient()) continue;\n\t\t}\n\t\telse { \/\/ non serverside attr\n\t\t\tif(game.isClient() && !ownObject(u->obj)) continue;\n\t\t}\n\t\tScriptVar_t curValue = u->get();\n\t\tScriptVar_t stateValue = attrDesc->defaultValue;\n\t\tif(s.haveObject(u->obj))\n\t\t\tstateValue = s.getValue(*u);\n\t\t\/\/notes << \"update \" << u->description() << \": \" << curValue.toString() << \" -> \" << stateValue.toString() << endl;\n\t\tif(curValue != stateValue)\n\t\t\tpushObjAttrUpdate(*u);\n\t}\n\tforeach(o, game.gameStateUpdates->objDeletions) {\n\t\tif(game.isClient()) continue; \/\/ see obj-creations\n\t\tif(!ownObject(*o)) continue;\n\t\tif(s.haveObject(*o))\n\t\t\tpushObjDeletion(*o);\n\t}\n}\n\nstatic ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) {\n\treturn s.objs[obj->thisRef] = ObjectState(obj);\n}\n\nGameState::GameState() {\n\t\/\/ register singletons which are always there\n\tGameState_registerObj(*this, &game);\n\tGameState_registerObj(*this, &gameSettings);\n}\n\nGameState GameState::Current() {\n\tGameState s;\n\ts.updateToCurrent();\n\treturn s;\n}\n\nvoid GameState::reset() {\n\t*this = GameState();\n}\n\nvoid GameState::updateToCurrent() {\n\treset();\n\tforeach(o, game.gameStateUpdates->objCreations) {\n\t\tobjs[*o] = ObjectState(*o);\n\t}\n\tforeach(u, game.gameStateUpdates->objs) {\n\t\tObjAttrRef r = *u;\n\t\tObjs::iterator it = objs.find(r.obj);\n\t\tassert(it != objs.end());\n\t\tObjectState& s = it->second;\n\t\tassert(s.obj == it->first);\n\t\ts.attribs[u->attr].value = r.get();\n\t}\n}\n\nvoid GameState::addObject(ObjRef o) {\n\tassert(!haveObject(o));\n\tobjs[o] = ObjectState(o);\n}\n\nbool GameState::haveObject(ObjRef o) const {\n\tObjs::const_iterator it = objs.find(o);\n\treturn it != objs.end();\n}\n\nScriptVar_t GameState::getValue(ObjAttrRef a) const {\n\tObjs::const_iterator it = objs.find(a.obj);\n\tassert(it != objs.end());\n\tassert(it->second.obj == a.obj);\n\treturn it->second.getValue(a.attr);\n}\n\n<commit_msg>fix for game.state client-side update<commit_after>\/*\n * GameState.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 15.02.12.\n * code under LGPL\n *\n *\/\n\n#include \"GameState.h\"\n#include \"Game.h\"\n#include \"Settings.h\"\n#include \"CWorm.h\"\n#include \"CBytestream.h\"\n#include \"ClassInfo.h\"\n#include \"ProfileSystem.h\"\n#include \"CServerConnection.h\"\n\nScriptVar_t ObjectState::getValue(AttribRef a) const {\n\tAttribs::const_iterator it = attribs.find(a);\n\tif(it == attribs.end())\n\t\treturn a.getAttrDesc()->defaultValue;\n\treturn it->second.value;\n}\n\nGameStateUpdates::operator bool() const {\n\tif(!objs.empty()) return true;\n\tif(!objCreations.empty()) return true;\n\tif(!objDeletions.empty()) return true;\n\treturn false;\n}\n\nvoid GameStateUpdates::writeToBs(CBytestream* bs) const {\n\tbs->writeInt16((uint16_t)objCreations.size());\n\tforeach(o, objCreations) {\n\t\to->writeToBs(bs);\n\t}\n\n\tbs->writeInt16((uint16_t)objDeletions.size());\n\tforeach(o, objDeletions) {\n\t\to->writeToBs(bs);\n\t}\n\n\tbs->writeInt((uint32_t)objs.size(), 4);\n\tforeach(a, objs) {\n\t\tconst ObjAttrRef& attr = *a;\n\t\tScriptVar_t curValue = a->get();\n\t\tattr.writeToBs(bs);\n\t\tbs->writeVar(curValue);\n\t}\n}\n\nstatic BaseObject* getObjFromRef(ObjRef r) {\n\tswitch(r.classId) {\n\tcase LuaID<Game>::value: return &game;\n\tcase LuaID<CWorm>::value: return game.wormById(r.objId, false);\n\tdefault: break;\n\t}\n\treturn NULL;\n}\n\nstatic bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) {\n\treturn classInfo->isTypeOf(attrDesc->objTypeId);\n}\n\nstatic bool ownObject(ObjRef o) {\n\t\/\/ This is very custom right now and need to be made somewhat more general.\n\tif(o.classId == LuaID<CWorm>::value) {\n\t\tCWorm* w = game.wormById(o.objId, false);\n\t\tif(!w) return false;\n\t\treturn w->getLocal();\n\t}\n\tif(game.isServer()) return true;\n\treturn false;\n}\n\n\/\/ This only make sense as server.\nstatic bool ownObject(CServerConnection* source, ObjRef o) {\n\tassert(game.isServer());\n\t\/\/ This is very custom right now and need to be made somewhat more general.\n\tif(o.classId == LuaID<CWorm>::value) {\n\t\treturn source->OwnsWorm(o.objId);\n\t}\n\treturn false;\n}\n\nvoid GameStateUpdates::handleFromBs(CBytestream* bs, CServerConnection* source) {\n\tif(game.isServer()) {\n\t\tassert(source != NULL);\n\t\tif(source->isLocalClient()) {\n\t\t\t\/\/ This shouldn't happen. It means sth in our server connection list is messed up.\n\t\t\terrors << \"GameStateUpdates::handleFromBs as server from local client\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t}\n\telse\n\t\tassert(source == NULL);\n\n\tuint16_t creationsNum = bs->readInt16();\n\tfor(uint16_t i = 0; i < creationsNum; ++i) {\n\t\tObjRef r;\n\t\tr.readFromBs(bs);\n\t\t\/\/BaseObject* o = getClassInfo(r.classId)->createInstance();\n\t\t\/\/o->thisRef.classId = r.classId;\n\t\t\/\/o->thisRef.objId = r.objId;\n\n\t\t\/\/ we only handle\/support CWorm objects for now...\n\t\tif(game.isServer()) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: got obj creation as server: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(r.classId != LuaID<CWorm>::value) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-creation: invalid class: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(game.wormById(r.objId, false) != NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: worm-creation: worm \" << r.objId << \" already exists\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tgame.createNewWorm(r.objId, false, NULL, Version());\n\t}\n\n\tuint16_t deletionsNum = bs->readInt16();\n\tfor(uint16_t i = 0; i < deletionsNum; ++i) {\n\t\tObjRef r;\n\t\tr.readFromBs(bs);\n\n\t\t\/\/ we only handle\/support CWorm objects for now...\n\t\tif(game.isServer()) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: got obj deletion as server: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tif(r.classId != LuaID<CWorm>::value) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-deletion: invalid class: \" << r.description() << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tCWorm* w = game.wormById(r.objId, false);\n\t\tif(!w) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: obj-deletion: worm \" << r.objId << \" does not exist\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\t\tgame.removeWorm(w);\n\t}\n\n\tuint32_t attrUpdatesNum = bs->readInt(4);\n\tfor(uint32_t i = 0; i < attrUpdatesNum; ++i) {\n\t\tObjAttrRef r;\n\t\tr.readFromBs(bs);\n\n\t\tconst AttrDesc* attrDesc = r.attr.getAttrDesc();\n\t\tif(attrDesc == NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: AttrDesc for update not found\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\tconst ClassInfo* classInfo = getClassInfo(r.obj.classId);\n\t\tif(classInfo == NULL) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: class \" << r.obj.classId << \" for obj-update unknown\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\tif(!attrBelongsToClass(classInfo, attrDesc)) {\n\t\t\terrors << \"GameStateUpdates::handleFromBs: attr \" << attrDesc->description() << \" does not belong to class \" << r.obj.classId << \" for obj-update\" << endl;\n\t\t\tbs->SkipAll();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ see GameStateUpdates::diffFromStateToCurrent for the other side\n\t\tif(attrDesc->serverside) {\n\t\t\tif(game.isServer()) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got serverside attr update as server: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse { \/\/ client-side attr\n\t\t\tif(game.isServer() && !ownObject(source, r.obj)) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got update from not-authorized client \" << source->debugName() << \": \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tScriptVar_t v;\n\t\tbs->readVar(v);\n\n\t\t\/\/ for now, this is somewhat specific to the only types we support\n\t\tif(r.obj.classId == LuaID<Settings>::value) {\n\t\t\tif(game.isServer()) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: got settings update as server\" << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(!Settings::getAttrDescs().belongsToUs(attrDesc)) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: settings update AttrDesc \" << attrDesc->description() << \" is not a setting attr\" << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tFeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc);\n\t\t\tcClient->getGameLobby().overwrite[fIndex] = v;\n\t\t}\n\t\telse {\n\t\t\tBaseObject* o = getObjFromRef(r.obj);\n\t\t\tif(o == NULL) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: object for attr update not found: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(o->thisRef != r.obj) {\n\t\t\t\terrors << \"GameStateUpdates::handleFromBs: object-ref for attr update invalid: \" << r.description() << endl;\n\t\t\t\tbs->SkipAll();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(attrDesc == game.state.attrDesc()) {\n\t\t\t\tif((int)v < Game::S_Lobby) {\n\t\t\t\t\tnotes << \"GameStateUpdates: server changed to \" << Game::StateAsStr(v) << \", we wait for drop\/leaving package\" << endl;\n\t\t\t\t\t\/\/v = Game::S_Inactive;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tattrDesc->set(o, v, true);\n\t\t}\n\n\t\t\/\/notes << \"game state update: <\" << r.obj.description() << \"> \" << attrDesc->attrName << \" to \" << v.toString() << endl;\n\t}\n}\n\nvoid GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) {\n\tobjs.insert(a);\n}\n\nvoid GameStateUpdates::pushObjCreation(ObjRef o) {\n\tobjDeletions.erase(o);\n\tobjCreations.insert(o);\n}\n\nvoid GameStateUpdates::pushObjDeletion(ObjRef o) {\n\tObjs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o));\n\tObjs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o));\n\tobjs.erase(itStart, itEnd);\n\tobjCreations.erase(o);\n\tobjDeletions.insert(o);\n}\n\nvoid GameStateUpdates::reset() {\n\tobjs.clear();\n\tobjCreations.clear();\n\tobjDeletions.clear();\n}\n\nvoid GameStateUpdates::diffFromStateToCurrent(const GameState& s) {\n\treset();\n\tforeach(o, game.gameStateUpdates->objCreations) {\n\t\tif(game.isClient()) continue; \/\/ none-at-all right now... worm-creation is handled independently atm\n\t\tif(!ownObject(*o)) continue;\n\t\tif(!s.haveObject(*o))\n\t\t\tpushObjCreation(*o);\n\t}\n\tforeach(u, game.gameStateUpdates->objs) {\n\t\tif(!ownObject(u->obj)) continue;\n\t\tconst AttrDesc* attrDesc = u->attr.getAttrDesc();\n\t\tif(attrDesc->serverside) {\n\t\t\tif(game.isClient()) continue;\n\t\t}\n\t\telse { \/\/ non serverside attr\n\t\t\tif(game.isClient() && !ownObject(u->obj)) continue;\n\t\t}\n\t\tScriptVar_t curValue = u->get();\n\t\tScriptVar_t stateValue = attrDesc->defaultValue;\n\t\tif(s.haveObject(u->obj))\n\t\t\tstateValue = s.getValue(*u);\n\t\t\/\/notes << \"update \" << u->description() << \": \" << curValue.toString() << \" -> \" << stateValue.toString() << endl;\n\t\tif(curValue != stateValue)\n\t\t\tpushObjAttrUpdate(*u);\n\t}\n\tforeach(o, game.gameStateUpdates->objDeletions) {\n\t\tif(game.isClient()) continue; \/\/ see obj-creations\n\t\tif(!ownObject(*o)) continue;\n\t\tif(s.haveObject(*o))\n\t\t\tpushObjDeletion(*o);\n\t}\n}\n\nstatic ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) {\n\treturn s.objs[obj->thisRef] = ObjectState(obj);\n}\n\nGameState::GameState() {\n\t\/\/ register singletons which are always there\n\tGameState_registerObj(*this, &game);\n\tGameState_registerObj(*this, &gameSettings);\n}\n\nGameState GameState::Current() {\n\tGameState s;\n\ts.updateToCurrent();\n\treturn s;\n}\n\nvoid GameState::reset() {\n\t*this = GameState();\n}\n\nvoid GameState::updateToCurrent() {\n\treset();\n\tforeach(o, game.gameStateUpdates->objCreations) {\n\t\tobjs[*o] = ObjectState(*o);\n\t}\n\tforeach(u, game.gameStateUpdates->objs) {\n\t\tObjAttrRef r = *u;\n\t\tObjs::iterator it = objs.find(r.obj);\n\t\tassert(it != objs.end());\n\t\tObjectState& s = it->second;\n\t\tassert(s.obj == it->first);\n\t\ts.attribs[u->attr].value = r.get();\n\t}\n}\n\nvoid GameState::addObject(ObjRef o) {\n\tassert(!haveObject(o));\n\tobjs[o] = ObjectState(o);\n}\n\nbool GameState::haveObject(ObjRef o) const {\n\tObjs::const_iterator it = objs.find(o);\n\treturn it != objs.end();\n}\n\nScriptVar_t GameState::getValue(ObjAttrRef a) const {\n\tObjs::const_iterator it = objs.find(a.obj);\n\tassert(it != objs.end());\n\tassert(it->second.obj == a.obj);\n\treturn it->second.getValue(a.attr);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"services\/surfaces\/surfaces_scheduler.h\"\n\nnamespace surfaces {\n\nSurfacesScheduler::Client::~Client() {\n}\n\nSurfacesScheduler::SurfacesScheduler(Client* client) : client_(client) {\n cc::SchedulerSettings settings;\n scheduler_ = cc::Scheduler::Create(\n this, settings, 0, base::MessageLoop::current()->task_runner(), nullptr,\n nullptr);\n scheduler_->SetCanStart();\n scheduler_->SetVisible(true);\n scheduler_->SetCanDraw(true);\n}\n\nSurfacesScheduler::~SurfacesScheduler() {\n}\n\nvoid SurfacesScheduler::SetNeedsDraw() {\n scheduler_->SetNeedsRedraw();\n}\n\nvoid SurfacesScheduler::OnVSyncParametersUpdated(base::TimeTicks timebase,\n base::TimeDelta interval) {\n scheduler_->CommitVSyncParameters(timebase, interval);\n}\n\nvoid SurfacesScheduler::WillBeginImplFrame(const cc::BeginFrameArgs& args) {\n}\n\nvoid SurfacesScheduler::ScheduledActionSendBeginMainFrame() {\n}\n\ncc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapIfPossible() {\n base::TimeTicks start = base::TimeTicks::Now();\n client_->Draw();\n base::TimeDelta duration = base::TimeTicks::Now() - start;\n\n draw_estimate_ = (duration + draw_estimate_) \/ 2;\n return cc::DRAW_SUCCESS;\n}\n\ncc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapForced() {\n NOTREACHED() << \"ScheduledActionDrawAndSwapIfPossible always succeeds.\";\n return cc::DRAW_SUCCESS;\n}\n\nvoid SurfacesScheduler::ScheduledActionAnimate() {\n}\n\nvoid SurfacesScheduler::ScheduledActionCommit() {\n}\n\nvoid SurfacesScheduler::ScheduledActionActivateSyncTree() {\n}\n\nvoid SurfacesScheduler::ScheduledActionBeginOutputSurfaceCreation() {\n scheduler_->DidCreateAndInitializeOutputSurface();\n}\n\nvoid SurfacesScheduler::ScheduledActionPrepareTiles() {\n}\n\nvoid SurfacesScheduler::DidAnticipatedDrawTimeChange(base::TimeTicks time) {\n}\n\nbase::TimeDelta SurfacesScheduler::DrawDurationEstimate() {\n return draw_estimate_;\n}\n\nbase::TimeDelta SurfacesScheduler::BeginMainFrameToCommitDurationEstimate() {\n return base::TimeDelta();\n}\n\nbase::TimeDelta SurfacesScheduler::CommitToActivateDurationEstimate() {\n return base::TimeDelta();\n}\n\nvoid SurfacesScheduler::DidBeginImplFrameDeadline() {\n}\n\nvoid SurfacesScheduler::SendBeginFramesToChildren(\n const cc::BeginFrameArgs& args) {\n}\n\n} \/\/ namespace mojo\n<commit_msg>Fix surfaces scheduler so apps can draw<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"services\/surfaces\/surfaces_scheduler.h\"\n\nnamespace surfaces {\n\nSurfacesScheduler::Client::~Client() {\n}\n\nSurfacesScheduler::SurfacesScheduler(Client* client) : client_(client) {\n cc::SchedulerSettings settings;\n scheduler_ = cc::Scheduler::Create(\n this, settings, 0, base::MessageLoop::current()->task_runner(), nullptr,\n nullptr);\n scheduler_->SetCanStart();\n scheduler_->SetVisible(true);\n scheduler_->SetCanDraw(true);\n scheduler_->SetNeedsCommit();\n}\n\nSurfacesScheduler::~SurfacesScheduler() {\n}\n\nvoid SurfacesScheduler::SetNeedsDraw() {\n scheduler_->SetNeedsRedraw();\n}\n\nvoid SurfacesScheduler::OnVSyncParametersUpdated(base::TimeTicks timebase,\n base::TimeDelta interval) {\n scheduler_->CommitVSyncParameters(timebase, interval);\n}\n\nvoid SurfacesScheduler::WillBeginImplFrame(const cc::BeginFrameArgs& args) {\n}\n\nvoid SurfacesScheduler::ScheduledActionSendBeginMainFrame() {\n scheduler_->NotifyBeginMainFrameStarted();\n scheduler_->NotifyReadyToCommit();\n}\n\ncc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapIfPossible() {\n base::TimeTicks start = base::TimeTicks::Now();\n client_->Draw();\n base::TimeDelta duration = base::TimeTicks::Now() - start;\n\n draw_estimate_ = (duration + draw_estimate_) \/ 2;\n return cc::DRAW_SUCCESS;\n}\n\ncc::DrawResult SurfacesScheduler::ScheduledActionDrawAndSwapForced() {\n NOTREACHED() << \"ScheduledActionDrawAndSwapIfPossible always succeeds.\";\n return cc::DRAW_SUCCESS;\n}\n\nvoid SurfacesScheduler::ScheduledActionAnimate() {\n}\n\nvoid SurfacesScheduler::ScheduledActionCommit() {\n}\n\nvoid SurfacesScheduler::ScheduledActionActivateSyncTree() {\n}\n\nvoid SurfacesScheduler::ScheduledActionBeginOutputSurfaceCreation() {\n scheduler_->DidCreateAndInitializeOutputSurface();\n}\n\nvoid SurfacesScheduler::ScheduledActionPrepareTiles() {\n}\n\nvoid SurfacesScheduler::DidAnticipatedDrawTimeChange(base::TimeTicks time) {\n}\n\nbase::TimeDelta SurfacesScheduler::DrawDurationEstimate() {\n return draw_estimate_;\n}\n\nbase::TimeDelta SurfacesScheduler::BeginMainFrameToCommitDurationEstimate() {\n return base::TimeDelta();\n}\n\nbase::TimeDelta SurfacesScheduler::CommitToActivateDurationEstimate() {\n return base::TimeDelta();\n}\n\nvoid SurfacesScheduler::DidBeginImplFrameDeadline() {\n}\n\nvoid SurfacesScheduler::SendBeginFramesToChildren(\n const cc::BeginFrameArgs& args) {\n}\n\n} \/\/ namespace mojo\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n\n#include \"BindingHandler.h\"\n#include \"ClientAdapter.h\"\n#include \"CefSharp.h\"\n#include \"IBeforePopup.h\"\n#include \"IBeforeResourceLoad.h\"\n#include \"IBeforeMenu.h\"\n#include \"IAfterResponse.h\"\n#include \"StreamAdapter.h\"\n\nnamespace CefSharp \n{\n bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings)\n {\n IBeforePopup^ handler = _browserControl->BeforePopupHandler;\n return handler != nullptr &&\n handler->HandleBeforePopup(toClr(url), windowInfo.m_x, windowInfo.m_y, windowInfo.m_nWidth, windowInfo.m_nHeight);\n }\n\n void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser)\n {\n if(!browser->IsPopup())\n {\n _browserHwnd = browser->GetWindowHandle();\n _cefBrowser = browser;\n\n _browserControl->OnInitialized();\n }\n }\n\n void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser)\n {\n if (_browserHwnd == browser->GetWindowHandle())\n {\n _cefBrowser = nullptr;\n }\n }\n\n void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url)\n {\n if(frame->IsMain())\n {\n _browserControl->SetAddress(toClr(url));\n }\n }\n\n void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title)\n {\n _browserControl->SetTitle(toClr(title));\n }\n\n bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text)\n {\n String^ str = toClr(text);\n\n if (str != _tooltip)\n {\n _tooltip = str;\n _browserControl->SetToolTip(_tooltip);\n }\n\n return true;\n }\n\n bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line)\n {\n String^ messageStr = toClr(message);\n String^ sourceStr = toClr(source);\n _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line);\n\n return true;\n }\n\n void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame)\n {\n if (browser->IsPopup())\n {\n return;\n }\n\n AutoLock lock_scope(this);\n if (frame->IsMain())\n {\n _browserControl->SetNavState(true, false, false);\n }\n\n _browserControl->AddFrame(frame);\n }\n\n void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode)\n {\n if(browser->IsPopup())\n {\n return;\n }\n\n AutoLock lock_scope(this);\n if (frame->IsMain())\n {\n _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward()); \n }\n\n _browserControl->FrameLoadComplete(frame);\n }\n\n bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefRefPtr<CefResponse> response, int loadFlags)\n {\n IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler;\n if(handler != nullptr)\n {\n CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request);\n RequestResponse^ requestResponse = gcnew RequestResponse(wrapper);\n \n handler->HandleBeforeResourceLoad(_browserControl, requestResponse);\n\n if(requestResponse->Action == ResponseAction::Respond)\n {\n CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream);\n resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter));\n \/\/mimeType = toNative(requestResponse->MimeType);\n return false;\n }\n else if(requestResponse->Action == ResponseAction::Cancel)\n {\n return true;\n }\n else if(requestResponse->Action == ResponseAction::Redirect)\n {\n redirectUrl = toNative(requestResponse->RedirectUrl);\n }\n }\n\n return false; \n }\n\n void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter)\n {\n IAfterResponse^ handler = _browserControl->AfterResponseHandler;\n if (handler != nullptr)\n {\n String^ cookie = toClr(response->GetHeader(\"Set-Cookie\"));\n if (!String::IsNullOrEmpty(cookie))\n {\n handler->HandleSetCookie(cookie);\n }\n }\n }\n\n void ClientAdapter::OnJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object)\n {\n for each(KeyValuePair<String^, Object^>^ kvp in CEF::GetBoundObjects())\n {\n BindingHandler::Bind(kvp->Key, kvp->Value, object);\n }\n }\n\n bool ClientAdapter::OnBeforeMenu(CefRefPtr<CefBrowser> browser, const MenuInfo& menuInfo)\n {\n IBeforeMenu^ beforeMenuHandler = _browserControl->BeforeMenuHandler;\n return beforeMenuHandler != nullptr &&\n beforeMenuHandler->HandleBeforeMenu();\n }\n}<commit_msg>+response->SetMimeType(toNative(requestResponse->MimeType)); without setting mimeType CEF doesnt start to work with the stream<commit_after>#include \"stdafx.h\"\n\n#include \"BindingHandler.h\"\n#include \"ClientAdapter.h\"\n#include \"CefSharp.h\"\n#include \"IBeforePopup.h\"\n#include \"IBeforeResourceLoad.h\"\n#include \"IBeforeMenu.h\"\n#include \"IAfterResponse.h\"\n#include \"StreamAdapter.h\"\n\nnamespace CefSharp \n{\n bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings)\n {\n IBeforePopup^ handler = _browserControl->BeforePopupHandler;\n return handler != nullptr &&\n handler->HandleBeforePopup(toClr(url), windowInfo.m_x, windowInfo.m_y, windowInfo.m_nWidth, windowInfo.m_nHeight);\n }\n\n void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser)\n {\n if(!browser->IsPopup())\n {\n _browserHwnd = browser->GetWindowHandle();\n _cefBrowser = browser;\n\n _browserControl->OnInitialized();\n }\n }\n\n void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser)\n {\n if (_browserHwnd == browser->GetWindowHandle())\n {\n _cefBrowser = nullptr;\n }\n }\n\n void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url)\n {\n if(frame->IsMain())\n {\n _browserControl->SetAddress(toClr(url));\n }\n }\n\n void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title)\n {\n _browserControl->SetTitle(toClr(title));\n }\n\n bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text)\n {\n String^ str = toClr(text);\n\n if (str != _tooltip)\n {\n _tooltip = str;\n _browserControl->SetToolTip(_tooltip);\n }\n\n return true;\n }\n\n bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line)\n {\n String^ messageStr = toClr(message);\n String^ sourceStr = toClr(source);\n _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line);\n\n return true;\n }\n\n void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame)\n {\n if (browser->IsPopup())\n {\n return;\n }\n\n AutoLock lock_scope(this);\n if (frame->IsMain())\n {\n _browserControl->SetNavState(true, false, false);\n }\n\n _browserControl->AddFrame(frame);\n }\n\n void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode)\n {\n if(browser->IsPopup())\n {\n return;\n }\n\n AutoLock lock_scope(this);\n if (frame->IsMain())\n {\n _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward()); \n }\n\n _browserControl->FrameLoadComplete(frame);\n }\n\n bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefRefPtr<CefResponse> response, int loadFlags)\n {\n IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler;\n if(handler != nullptr)\n {\n CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request);\n RequestResponse^ requestResponse = gcnew RequestResponse(wrapper);\n \n handler->HandleBeforeResourceLoad(_browserControl, requestResponse);\n\n if(requestResponse->Action == ResponseAction::Respond)\n {\n CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream);\n resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter));\n response->SetMimeType(toNative(requestResponse->MimeType));\n return false;\n }\n else if(requestResponse->Action == ResponseAction::Cancel)\n {\n return true;\n }\n else if(requestResponse->Action == ResponseAction::Redirect)\n {\n redirectUrl = toNative(requestResponse->RedirectUrl);\n }\n }\n\n return false; \n }\n\n void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter)\n {\n IAfterResponse^ handler = _browserControl->AfterResponseHandler;\n if (handler != nullptr)\n {\n String^ cookie = toClr(response->GetHeader(\"Set-Cookie\"));\n if (!String::IsNullOrEmpty(cookie))\n {\n handler->HandleSetCookie(cookie);\n }\n }\n }\n\n void ClientAdapter::OnJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object)\n {\n for each(KeyValuePair<String^, Object^>^ kvp in CEF::GetBoundObjects())\n {\n BindingHandler::Bind(kvp->Key, kvp->Value, object);\n }\n }\n\n bool ClientAdapter::OnBeforeMenu(CefRefPtr<CefBrowser> browser, const MenuInfo& menuInfo)\n {\n IBeforeMenu^ beforeMenuHandler = _browserControl->BeforeMenuHandler;\n return beforeMenuHandler != nullptr &&\n beforeMenuHandler->HandleBeforeMenu();\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2005-2008 Greg Landrum and Rational Discovery LLC\n\/\/\n\/\/ @@ All Rights Reserved @@\n\/\/\n#include \"RDLog.h\"\n\n#if 1\n#include <iomanip>\n#include <string>\n#include <time.h>\n\nboost::logging::rdLogger *rdAppLog=0;\nboost::logging::rdLogger *rdDebugLog=0;\nboost::logging::rdLogger *rdInfoLog=0;\nboost::logging::rdLogger *rdErrorLog=0;\nboost::logging::rdLogger *rdWarningLog=0;\nboost::logging::rdLogger *rdStatusLog=0;\n\nnamespace boost {\n namespace logging {\n\n void enable_logs(const char *arg) { enable_logs(std::string(arg));};\n void enable_logs(const std::string &arg) {\n \/\/ Yes... this is extremely crude\n if(arg==\"rdApp.debug\"||arg==\"rdApp.*\"){\n if(rdDebugLog) rdDebugLog->df_enabled=true;\n }\n if(arg==\"rdApp.info\"||arg==\"rdApp.*\"){\n if(rdInfoLog) rdInfoLog->df_enabled=true;\n }\n if(arg==\"rdApp.warning\"||arg==\"rdApp.*\"){\n if(rdWarningLog) rdWarningLog->df_enabled=true;\n }\n if(arg==\"rdApp.error\"||arg==\"rdApp.*\"){\n if(rdErrorLog) rdErrorLog->df_enabled=true;\n }\n };\n void disable_logs(const char *arg) {disable_logs(std::string(arg));};\n void disable_logs(const std::string &arg) {\n \/\/ Yes... this is extremely crude\n if(arg==\"rdApp.debug\"||arg==\"rdApp.*\"){\n if(rdDebugLog) rdDebugLog->df_enabled=false;\n }\n if(arg==\"rdApp.info\"||arg==\"rdApp.*\"){\n if(rdInfoLog) rdInfoLog->df_enabled=false;\n }\n if(arg==\"rdApp.warning\"||arg==\"rdApp.*\"){\n if(rdWarningLog) rdWarningLog->df_enabled=false;\n }\n if(arg==\"rdApp.error\"||arg==\"rdApp.*\"){\n if(rdErrorLog) rdErrorLog->df_enabled=false;\n }\n };\n }\n}\n\n\nnamespace RDLog {\n void InitLogs(){\n rdDebugLog=new boost::logging::rdLogger(&std::cerr);\n rdInfoLog=new boost::logging::rdLogger(&std::cout);\n rdWarningLog=new boost::logging::rdLogger(&std::cerr);\n rdErrorLog=new boost::logging::rdLogger(&std::cerr);\n }\n std::ostream &toStream(std::ostream &logstrm) {\n time_t t = time(0); \n tm details = *localtime( &t);\n logstrm << \"[\"<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<\":\"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<\":\"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<\"] \";\n return logstrm;\n }\n\n}\n\n#else\n#include <boost\/log\/functions.hpp>\n#if defined(BOOST_HAS_THREADS2)\n#include <boost\/log\/extra\/functions_ts.hpp>\n#endif\n#include <iostream>\nnamespace logging = boost::logging;\n\nBOOST_DEFINE_LOG(rdAppLog,\"rdApp\")\nBOOST_DEFINE_LOG(rdDebugLog,\"rdApp.debug\")\nBOOST_DEFINE_LOG(rdInfoLog,\"rdApp.info\")\nBOOST_DEFINE_LOG(rdErrorLog,\"rdApp.error\")\nBOOST_DEFINE_LOG(rdWarningLog,\"rdApp.warning\")\nBOOST_DEFINE_LOG(rdStatusLog,\"rdApp.status\")\n\nnamespace RDLog {\n void write_to_cout(const std::string &, const std::string &msg) {\n std::cout << msg; std::cout.flush();\n }\n void write_to_cerr(const std::string &, const std::string &msg) {\n std::cerr << msg; std::cerr.flush();\n }\n\n void InitLogs(){\n static bool callOnce=true;\n if(!callOnce) return;\n callOnce=false;\n\n \/\/ turn off caching:\n logging::set_log_caching(false);\n logging::manipulate_logs(\"rdApp.*\")\n .add_modifier(logging::prepend_time(\"[$hh:$mm:$ss] \"),\n\t\t logging::DEFAULT_INDEX-10);\n logging::manipulate_logs(\"rdApp.info\")\n .add_appender(write_to_cout,\n\t\t logging::DEFAULT_INDEX+1);\n#if defined(BOOST_HAS_THREADS2)\n logging::manipulate_logs(\"rdApp.error\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.warning\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.status\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.debug\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n#else\n logging::manipulate_logs(\"rdApp.error\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.warning\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.status\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.debug\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n#endif\n \/\/ start with the debug log disabled:\n logging::disable_logs(\"rdApp.debug\");\n };\n}\n#endif\n<commit_msg>add a hack to get the console stuff working on windows. this needs to be tested on lin and mac<commit_after>\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2005-2010 Greg Landrum and Rational Discovery LLC\n\/\/\n\/\/ @@ All Rights Reserved @@\n\/\/\n#include \"RDLog.h\"\n\n#if 1\n#include <iomanip>\n#include <string>\n#include <time.h>\n\nnamespace {\n \/\/ this is a \"bit\" of a hack to work around shared\/static library problems\n \/\/ on windows\n boost::logging::rdLogger cerrLogger(&std::cerr); \n boost::logging::rdLogger coutLogger(&std::cout); \n}\n\nboost::logging::rdLogger *rdAppLog=0;\nboost::logging::rdLogger *rdDebugLog=0;\nboost::logging::rdLogger *rdInfoLog=&coutLogger;\nboost::logging::rdLogger *rdErrorLog=&cerrLogger;\nboost::logging::rdLogger *rdWarningLog=&cerrLogger;\nboost::logging::rdLogger *rdStatusLog=0;\n\nnamespace boost {\n namespace logging {\n\n void enable_logs(const char *arg) { enable_logs(std::string(arg));};\n void enable_logs(const std::string &arg) {\n \/\/ Yes... this is extremely crude\n if(arg==\"rdApp.debug\"||arg==\"rdApp.*\"){\n if(rdDebugLog) rdDebugLog->df_enabled=true;\n }\n if(arg==\"rdApp.info\"||arg==\"rdApp.*\"){\n if(rdInfoLog) rdInfoLog->df_enabled=true;\n }\n if(arg==\"rdApp.warning\"||arg==\"rdApp.*\"){\n if(rdWarningLog) rdWarningLog->df_enabled=true;\n }\n if(arg==\"rdApp.error\"||arg==\"rdApp.*\"){\n if(rdErrorLog) rdErrorLog->df_enabled=true;\n }\n };\n void disable_logs(const char *arg) {disable_logs(std::string(arg));};\n void disable_logs(const std::string &arg) {\n \/\/ Yes... this is extremely crude\n if(arg==\"rdApp.debug\"||arg==\"rdApp.*\"){\n if(rdDebugLog) rdDebugLog->df_enabled=false;\n }\n if(arg==\"rdApp.info\"||arg==\"rdApp.*\"){\n if(rdInfoLog) rdInfoLog->df_enabled=false;\n }\n if(arg==\"rdApp.warning\"||arg==\"rdApp.*\"){\n if(rdWarningLog) rdWarningLog->df_enabled=false;\n }\n if(arg==\"rdApp.error\"||arg==\"rdApp.*\"){\n if(rdErrorLog) rdErrorLog->df_enabled=false;\n }\n };\n }\n}\n\n\nnamespace RDLog {\n void InitLogs(){\n rdDebugLog=new boost::logging::rdLogger(&std::cerr);\n rdInfoLog=new boost::logging::rdLogger(&std::cout);\n rdWarningLog=new boost::logging::rdLogger(&std::cerr);\n rdErrorLog=new boost::logging::rdLogger(&std::cerr);\n }\n std::ostream &toStream(std::ostream &logstrm) {\n time_t t = time(0); \n tm details = *localtime( &t);\n logstrm << \"[\"<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<\":\"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<\":\"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<\"] \";\n return logstrm;\n }\n\n}\n\n#else\n#include <boost\/log\/functions.hpp>\n#if defined(BOOST_HAS_THREADS2)\n#include <boost\/log\/extra\/functions_ts.hpp>\n#endif\n#include <iostream>\nnamespace logging = boost::logging;\n\nBOOST_DEFINE_LOG(rdAppLog,\"rdApp\")\nBOOST_DEFINE_LOG(rdDebugLog,\"rdApp.debug\")\nBOOST_DEFINE_LOG(rdInfoLog,\"rdApp.info\")\nBOOST_DEFINE_LOG(rdErrorLog,\"rdApp.error\")\nBOOST_DEFINE_LOG(rdWarningLog,\"rdApp.warning\")\nBOOST_DEFINE_LOG(rdStatusLog,\"rdApp.status\")\n\nnamespace RDLog {\n void write_to_cout(const std::string &, const std::string &msg) {\n std::cout << msg; std::cout.flush();\n }\n void write_to_cerr(const std::string &, const std::string &msg) {\n std::cerr << msg; std::cerr.flush();\n }\n\n void InitLogs(){\n static bool callOnce=true;\n if(!callOnce) return;\n callOnce=false;\n\n \/\/ turn off caching:\n logging::set_log_caching(false);\n logging::manipulate_logs(\"rdApp.*\")\n .add_modifier(logging::prepend_time(\"[$hh:$mm:$ss] \"),\n\t\t logging::DEFAULT_INDEX-10);\n logging::manipulate_logs(\"rdApp.info\")\n .add_appender(write_to_cout,\n\t\t logging::DEFAULT_INDEX+1);\n#if defined(BOOST_HAS_THREADS2)\n logging::manipulate_logs(\"rdApp.error\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.warning\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.status\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.debug\")\n .add_appender(logging::ts_appender(write_to_cerr,100),\n\t\t logging::DEFAULT_INDEX+1);\n#else\n logging::manipulate_logs(\"rdApp.error\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.warning\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.status\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n logging::manipulate_logs(\"rdApp.debug\")\n .add_appender(write_to_cerr,\n\t\t logging::DEFAULT_INDEX+1);\n#endif\n \/\/ start with the debug log disabled:\n logging::disable_logs(\"rdApp.debug\");\n };\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\\\n**\n** TODDLER: Slimmed-down version of CHILD without Vegetation,\n** Stream Meandering, or mesh densification.\n**\n** C H I L D\n**\n** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL\n**\n** VERSION 2.1.2, JUNE 2000\n**\n** Designed and created by Gregory E. Tucker, Stephen T. Lancaster,\n** Nicole M. Gasparini, and Rafael L. Bras, Department of Civil\n** and Environmental Engineering, Massachusetts Institute of\n** Technology, Cambridge, MA, USA.\n**\n** MAIN.CPP -- This file contains the main() routine that handles\n** top-level initialization and implements the main\n** time-loop.\n**\n** NOTE: This source code is copyrighted material. It is distributed\n** solely for noncommercial research and educational purposes\n** only. Use in whole or in part for commercial purposes without \n** a written license from the copyright holder(s) is expressly\n** prohibited. Copies of this source code or any of its components \n** may not be transferred to any other individuals or organizations\n** without written consent. Copyright (C) Massachusetts Institute\n** of Technology, 1997-2000. All rights reserved.\n**\n** For information regarding this program, please contact Greg Tucker at:\n**\n** School of Geography and the Environment\n** University of Oxford\n** Mansfield Road\n** Oxford OX1 3TB United Kingdom\n**\n** $Id: toddlermain.cpp,v 1.3 2000-12-07 11:50:05 gtucker Exp $\n\\**************************************************************************\/\n\n\n#include \"Inclusions.h\"\n#include \"tFloodplain\/tFloodplain.h\"\n#include \"tEolian\/tEolian.h\"\n\nPredicates predicate;\n\n\nmain( int argc, char **argv )\n{\n int silent_mode, \/\/ Option for silent mode (no time output to stdout)\n optDetachLim, \/\/ Option for detachment-limited erosion only\n optFloodplainDep, \/\/ Option for floodplain (overbank) deposition\n optLoessDep, \/\/ Option for eolian deposition\n optDiffuseDepo; \/\/ Option for deposition \/ no deposition by diff'n\n tFloodplain *floodplain; \/\/ -> floodplain object\n tEolian *loess; \/\/ -> eolian deposition object\n \n \/****************** INITIALIZATION *************************************\\\n ** ALGORITHM\n ** Get command-line arguments (name of input file + any other opts)\n ** Set silent_mode flag\n ** Open main input file\n ** Create and initialize objects for...\n ** Mesh\n ** Output files\n ** Storm\n ** Stream network\n ** Erosion\n ** Uplift (or baselevel change)\n ** Run timer\n ** Write output for initial state\n ** Get options for erosion type, meandering, etc.\n \\**********************************************************************\/\n \n \/\/ Check command-line arguments\n if( argc<2 )\n {\n cerr << \"Usage: \" << argv[0] << \" <input file>\" << endl;\n ReportFatalError( \"You need to give the name of an input file.\" );\n }\n\n \/\/ Check whether we're in silent mode\n silent_mode = ( argc>2 && argv[2][1]=='s' );\n \n \/\/ Say hello\n cout << \"\\nThis is TODDLER, version \" << VERSION << endl << endl;\n \n \/\/ Open main input file\n tInputFile inputFile( argv[1] );\n\n \/\/ Create and initialize objects:\n cout << \"Creating mesh...\\n\";\n tMesh<tLNode> mesh( inputFile );\n cout << \"Creating output files...\\n\";\n tLOutput<tLNode> output( &mesh, inputFile );\n tStorm storm( inputFile );\n cout << \"Creating stream network...\\n\";\n tStreamNet strmNet( mesh, storm, inputFile );\n tErosion erosion( &mesh, inputFile );\n tUplift uplift( inputFile );\n cout << \"Writing data for time zero...\\n\";\n tRunTimer time( inputFile, !silent_mode );\n output.WriteOutput( 0 );\n cout << \"Initialization done.\\n\";\n\n \/\/ Get various options\n optDetachLim = inputFile.ReadItem( optDetachLim, \"OPTDETACHLIM\" );\n optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, \"OPTDIFFDEP\" );\n optFloodplainDep = inputFile.ReadItem( optFloodplainDep, \"OPTFLOODPLAIN\" );\n optLoessDep = inputFile.ReadItem( optLoessDep, \"OPTLOESSDEP\" );\n\n \/\/ If applicable, create floodplain object\n if( optFloodplainDep )\n floodplain = new tFloodplain( inputFile, &mesh );\n\n \/\/ If applicable, create eolian deposition object\n if( optLoessDep )\n loess = new tEolian( inputFile );\n\n \/\/ Temporary -- for canyon range stuff\n cout << \"Densifying around fold strike ...\\n\";\n int optFoldDens = inputFile.ReadItem( optFoldDens, \"OPTFOLDDENS\" );\n if( optFoldDens )\n {\n double foldDensYmin = inputFile.ReadItem( foldDensYmin, \"FOLDDENSYMIN\" );\n double foldDensYmax = inputFile.ReadItem( foldDensYmax, \"FOLDDENSYMAX\" );\n for( int i=1; i<=optFoldDens; i++ )\n\t {\n\t tPtrList<tLNode> foldPoints;\n\t tMeshListIter<tLNode> ni( mesh.getNodeList() );\n\t tLNode *cn;\n\t for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )\n\t if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax )\n\t foldPoints.insertAtBack( cn );\n\t tPtrListIter<tLNode> fpi( foldPoints );\n\t for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )\n\t mesh.AddNodesAround( cn, 0.0 );\n\t foldPoints.Flush();\n\t }\n }\n\n\n \/**************** MAIN LOOP ******************************************\\\n ** ALGORITHM\n ** Generate storm\n ** Do storm...\n ** Update network (flow directions, drainage area, runoff)\n ** Water erosion\/deposition (vertical)\n ** Meandering (if applicable)\n ** Floodplain deposition (if applicable)\n ** Do interstorm...\n ** Hillslope transport\n ** Vegetation (if applicable)\n ** Exposure history\n ** Mesh densification (if applicable)\n ** Eolian (loess) deposition (if applicable)\n ** Uplift (or baselevel change)\n **********************************************************************\/\n while( !time.IsFinished() )\n {\n time.ReportTimeStatus();\n\n \/\/ Do storm...\n storm.GenerateStorm( time.getCurrentTime(),\n strmNet.getInfilt(), strmNet.getSoilStore() );\n cout << storm.getRainrate() << \" \" << storm.getStormDuration() << \" \"\n << storm.interstormDur() << endl;\n\n strmNet.UpdateNet( time.getCurrentTime(), storm );\n \n if( optDetachLim )\n erosion.ErodeDetachLim( storm.getStormDuration() );\n else\n erosion.DetachErode( storm.getStormDuration(), &strmNet,\n time.getCurrentTime() );\n\n if( optFloodplainDep )\n floodplain->DepositOverbank( storm.getRainrate(),\n storm.getStormDuration(),\n time.getCurrentTime() );\n\n \/\/ Do interstorm...\n erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),\n optDiffuseDepo );\n\n erosion.UpdateExposureTime( storm.getStormDuration() + \n storm.interstormDur() );\n\n if( optLoessDep )\n loess->DepositLoess( &mesh, \n storm.getStormDuration()+storm.interstormDur(),\n time.getCurrentTime() );\n\n if( time.getCurrentTime() < uplift.getDuration() )\n uplift.DoUplift( &mesh,\n storm.getStormDuration() + storm.interstormDur() );\n\n time.Advance( storm.getStormDuration() + storm.interstormDur() );\n\n if( time.CheckOutputTime() )\n output.WriteOutput( time.getCurrentTime() );\n\n } \/\/ end of main loop\n \n}\n\n<commit_msg>just debugging, no chgs<commit_after>\/**************************************************************************\\\n**\n** TODDLER: Slimmed-down version of CHILD without Vegetation,\n** Stream Meandering, or mesh densification.\n**\n** C H I L D\n**\n** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL\n**\n** VERSION 2.1.2, JUNE 2000\n**\n** Designed and created by Gregory E. Tucker, Stephen T. Lancaster,\n** Nicole M. Gasparini, and Rafael L. Bras, Department of Civil\n** and Environmental Engineering, Massachusetts Institute of\n** Technology, Cambridge, MA, USA.\n**\n** MAIN.CPP -- This file contains the main() routine that handles\n** top-level initialization and implements the main\n** time-loop.\n**\n** NOTE: This source code is copyrighted material. It is distributed\n** solely for noncommercial research and educational purposes\n** only. Use in whole or in part for commercial purposes without \n** a written license from the copyright holder(s) is expressly\n** prohibited. Copies of this source code or any of its components \n** may not be transferred to any other individuals or organizations\n** without written consent. Copyright (C) Massachusetts Institute\n** of Technology, 1997-2000. All rights reserved.\n**\n** For information regarding this program, please contact Greg Tucker at:\n**\n** School of Geography and the Environment\n** University of Oxford\n** Mansfield Road\n** Oxford OX1 3TB United Kingdom\n**\n** $Id: toddlermain.cpp,v 1.4 2002-02-11 09:22:15 gtucker Exp $\n\\**************************************************************************\/\n\n\n#include \"Inclusions.h\"\n#include \"tFloodplain\/tFloodplain.h\"\n#include \"tEolian\/tEolian.h\"\n\nPredicates predicate;\n\n\nmain( int argc, char **argv )\n{\n int silent_mode, \/\/ Option for silent mode (no time output to stdout)\n optDetachLim, \/\/ Option for detachment-limited erosion only\n optFloodplainDep, \/\/ Option for floodplain (overbank) deposition\n optLoessDep, \/\/ Option for eolian deposition\n optVegetation, \/\/ Option for dynamic vegetation cover\n optDiffuseDepo; \/\/ Option for deposition \/ no deposition by diff'n\n tVegetation *vegetation; \/\/ -> vegetation object\n tFloodplain *floodplain; \/\/ -> floodplain object\n tEolian *loess; \/\/ -> eolian deposition object\n \n \/****************** INITIALIZATION *************************************\\\n ** ALGORITHM\n ** Get command-line arguments (name of input file + any other opts)\n ** Set silent_mode flag\n ** Open main input file\n ** Create and initialize objects for...\n ** Mesh\n ** Output files\n ** Storm\n ** Stream network\n ** Erosion\n ** Uplift (or baselevel change)\n ** Run timer\n ** Write output for initial state\n ** Get options for erosion type, meandering, etc.\n \\**********************************************************************\/\n \n \/\/ Check command-line arguments\n if( argc<2 )\n {\n cerr << \"Usage: \" << argv[0] << \" <input file>\" << endl;\n ReportFatalError( \"You need to give the name of an input file.\" );\n }\n\n \/\/ Check whether we're in silent mode\n silent_mode = ( argc>2 && argv[2][1]=='s' );\n \n \/\/ Say hello\n cout << \"\\nThis is TODDLER, version \" << VERSION << endl << endl;\n \n \/\/ Open main input file\n tInputFile inputFile( argv[1] );\n\n \/\/ Create and initialize objects:\n cout << \"Creating mesh...\\n\";\n tMesh<tLNode> mesh( inputFile );\n cout << \"Creating output files...\\n\";\n tLOutput<tLNode> output( &mesh, inputFile );\n tStorm storm( inputFile );\n cout << \"Creating stream network...\\n\";\n tStreamNet strmNet( mesh, storm, inputFile );\n tErosion erosion( &mesh, inputFile );\n tUplift uplift( inputFile );\n cout << \"Writing data for time zero...\\n\";\n tRunTimer time( inputFile, !silent_mode );\n output.WriteOutput( 0 );\n cout << \"Initialization done.\\n\";\n\n \/\/ Get various options\n optDetachLim = inputFile.ReadItem( optDetachLim, \"OPTDETACHLIM\" );\n optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, \"OPTDIFFDEP\" );\n optVegetation = inputFile.ReadItem( optVegetation, \"OPTVEG\" );\n optFloodplainDep = inputFile.ReadItem( optFloodplainDep, \"OPTFLOODPLAIN\" );\n optLoessDep = inputFile.ReadItem( optLoessDep, \"OPTLOESSDEP\" );\n\n \/\/ If applicable, create Vegetation object\n if( optVegetation )\n vegetation = new tVegetation( &mesh, inputFile );\n\n \/\/ If applicable, create floodplain object\n if( optFloodplainDep )\n floodplain = new tFloodplain( inputFile, &mesh );\n\n \/\/ If applicable, create eolian deposition object\n if( optLoessDep )\n loess = new tEolian( inputFile );\n\n \/\/ Option for time series output (IN PROGRESS)\n \/* switch( optTSOutput ){\n case 1: \/\/ Volume output each N years.\n if( time.CheckTSOutputTime() )\n output.WriteVolOutput();\n break;\n case 2: \/\/ Volume and vegetation cover output each N years.\n cout << \"here\" << endl;\n if( time.CheckTSOutputTime() ){\n cout << \"there\" << endl;\n output.WriteVolVegOutput();}\n break;\n case 3: \/\/ All data at each storm.\n output.WriteTSOutput();\n break; \n case 0: \/\/ No additional timeseries output.\n break;\n default: \/\/ Invalid option.\n ReportFatalError( \"The input file contains an invalid value for \nOptTSOutput.\" );\n } *\/\n\n \/\/ Temporary -- for canyon range stuff\n \/*cout << \"Densifying around fold strike ...\\n\";\n int optFoldDens = inputFile.ReadItem( optFoldDens, \"OPTFOLDDENS\" );\n if( optFoldDens )\n {\n double foldDensYmin = inputFile.ReadItem( foldDensYmin, \"FOLDDENSYMIN\" );\n double foldDensYmax = inputFile.ReadItem( foldDensYmax, \"FOLDDENSYMAX\" );\n double fault = inputFile.ReadItem( fault, \"FAULTPOS\" );\n for( int i=1; i<=optFoldDens; i++ )\n\t {\n\t tPtrList<tLNode> foldPoints;\n\t tMeshListIter<tLNode> ni( mesh.getNodeList() );\n\t tLNode *cn;\n\t for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )\n\t {\n\t if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&\n\t\t cn->getX()>=7500 && cn->getX()<=92500 )\n\t foldPoints.insertAtBack( cn );\n\t if( cn->getY()<fault )\n\t cn->setAlluvThickness( 100000 );\n\t }\n\t tPtrListIter<tLNode> fpi( foldPoints );\n\t for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )\n\t mesh.AddNodesAround( cn, 0.0 );\n\t foldPoints.Flush();\n\t }\n\t }*\/\n\n\n \/**************** MAIN LOOP ******************************************\\\n ** ALGORITHM\n ** Generate storm\n ** Do storm...\n ** Update network (flow directions, drainage area, runoff)\n ** Water erosion\/deposition (vertical)\n ** Meandering (if applicable)\n ** Floodplain deposition (if applicable)\n ** Do interstorm...\n ** Hillslope transport\n ** Vegetation (if applicable)\n ** Exposure history\n ** Mesh densification (if applicable)\n ** Eolian (loess) deposition (if applicable)\n ** Uplift (or baselevel change)\n **********************************************************************\/\n while( !time.IsFinished() )\n {\n time.ReportTimeStatus();\n\n \/\/ Do storm...\n storm.GenerateStorm( time.getCurrentTime(),\n strmNet.getInfilt(), strmNet.getSoilStore() );\n cout << storm.getRainrate() << \" \" << storm.getStormDuration() << \" \"\n << storm.interstormDur() << endl;\n\n strmNet.UpdateNet( time.getCurrentTime(), storm );\n \n if( optDetachLim )\n erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );\n else\n erosion.DetachErode( storm.getStormDuration(), &strmNet,\n time.getCurrentTime() );\n\n if( optVegetation )\n\t vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),\n\t\t\t\t\tstorm.interstormDur() );\n\n if( optFloodplainDep )\n floodplain->DepositOverbank( storm.getRainrate(),\n storm.getStormDuration(),\n time.getCurrentTime() );\n\n \/\/ Do interstorm...\n erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),\n optDiffuseDepo );\n\n erosion.UpdateExposureTime( storm.getStormDuration() + \n storm.interstormDur() );\n\n if( optLoessDep )\n loess->DepositLoess( &mesh, \n storm.getStormDuration()+storm.interstormDur(),\n time.getCurrentTime() );\n\n if( time.getCurrentTime() < uplift.getDuration() )\n uplift.DoUplift( &mesh,\n storm.getStormDuration() + storm.interstormDur() );\n\n time.Advance( storm.getStormDuration() + storm.interstormDur() );\n\n if( time.CheckOutputTime() )\n output.WriteOutput( time.getCurrentTime() );\n\n if( output.OptTSOutput() ) output.WriteTSOutput();\n\n \/* IN PROGRESS\n switch( optTSOutput ){\n case 1: \/\/ Volume output each N years.\n if( time.CheckTSOutputTime() )\n output.WriteVolOutput();\nbreak;\n case 2: \/\/ Volume and vegetation cover output each N years.\nif( time.CheckTSOutputTime() )\n output.WriteVolVegOutput();\nbreak;\n case 3: \/\/ All data at each storm.\noutput.WriteTSOutput();\nbreak; \n case 0: \/\/ No additional timeseries output.\nbreak;\n default: \/\/ Invalid option.\nReportFatalError( \"The input file contains an invalid value for OptTSOutput.\" \n*\/ \n\n \/*tMeshListIter<tLNode> ni( mesh.getNodeList() );\n tLNode *cn;\n for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )\n\t{\n\t if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )\n\t cn->TellAll();\n\t}*\/\n\n } \/\/ end of main loop\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <random>\n#include <numeric>\n\n#include <OpenMS\/FORMAT\/FASTAFile.h>\n#include <OpenMS\/CHEMISTRY\/AASequence.h>\n#include <OpenMS\/CHEMISTRY\/ElementDB.h>\n#include <OpenMS\/CHEMISTRY\/Residue.h>\n#include <OpenMS\/CHEMISTRY\/EnzymaticDigestion.h>\n#include <OpenMS\/CHEMISTRY\/IsotopeDistribution.h>\n#include <OpenMS\/MATH\/STATISTICS\/StatisticFunctions.h>\n\n#include \"Stats.h\"\n\nusing namespace OpenMS;\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_real_distribution<> dis(0, 1);\n\nstd::vector<double> sampleDecoy(int length)\n{\n std::vector<double> probabilities;\n double sum = 0;\n for (int i = 0; i < length; ++i)\n {\n probabilities.push_back(dis(gen));\n sum+= probabilities[i];\n }\n for (int i = 0; i < length; ++i)\n {\n probabilities[i] \/= sum;\n }\n\n return probabilities;\n}\n\nstd::vector<double> sampleFromDistribution(std::vector<double>& probabilities)\n{\n static int SAMPLE_SIZE = 1e3;\n\n std::vector<double> prefix_sum(probabilities.size());\n std::partial_sum(probabilities.begin(), probabilities.end(), prefix_sum.begin());\n\n std::vector<double> sample(probabilities.size(),0);\n\n for (int i = 0; i < SAMPLE_SIZE; ++i)\n {\n double ran = dis(gen);\n int index = std::upper_bound(prefix_sum.begin(), prefix_sum.end(), ran) - prefix_sum.begin();\n sample[index] += 1.0\/SAMPLE_SIZE;\n }\n return sample;\n}\n\nstd::vector<double> fillProbabilities(IsotopeDistribution& dist, UInt length)\n{\n std::vector<double> probabilities;\n for (Size i = 0; i < dist.size(); ++i)\n {\n probabilities.push_back(dist.getContainer()[i].second);\n }\n\n for (Size i = dist.size(); i < length; ++i) {\n probabilities.push_back(0);\n }\n\n return probabilities;\n}\n\nstd::vector<double> calculateScores(std::vector<double>& l, std::vector<double>& r)\n{\n std::vector<double> result;\n result.push_back(Math::pearsonCorrelationCoefficient(l.begin(), l.end(), r.begin(), r.end()));\n result.push_back(Stats::totalVariationDistance(l.begin(), l.end(), r.begin(), r.end()));\n result.push_back(Stats::chiSquared(l.begin(), l.end(), r.begin(), r.end()));\n return result;\n}\n\nvoid testTheoreticalIon(AASequence& pep, AASequence& frag, EmpiricalFormula& precursor, EmpiricalFormula& fragment)\n{\n static Size MAX_ISOTOPE = 3;\n static Size LENGTH = MAX_ISOTOPE+1;\n static Size num_processed = 0;\n\n int num_s = fragment.getNumberOf(ElementDB::getInstance()->getElement(\"Sulfur\"));\n int num_cs = precursor.getNumberOf(ElementDB::getInstance()->getElement(\"Sulfur\")) - num_s;\n\n std::vector<UInt> isolated_precursor_isotopes(1,0);\n for (UInt i = 1; i <= MAX_ISOTOPE; ++i) {\n isolated_precursor_isotopes.push_back(i);\n IsotopeDistribution frag_dist = fragment.getConditionalFragmentIsotopeDist(precursor, isolated_precursor_isotopes);\n\n IsotopeDistribution dist_averagine_precursor(i+1);\n dist_averagine_precursor.estimateFromPeptideWeight(fragment.getAverageWeight());\n dist_averagine_precursor.renormalize();\n IsotopeDistribution dist_exact_precursor = fragment.getIsotopeDistribution(i+1);\n\n std::vector<double> prob_averagine_precursor = fillProbabilities(dist_averagine_precursor, i+1);\n std::vector<double> prob_exact_precursor = fillProbabilities(dist_averagine_precursor, i+1);\n std::vector<double> prob_decoy = sampleDecoy(i+1);\n std::vector<double> prob_exact_fragment = fillProbabilities(frag_dist, i+1);\n std::vector<double> prob_sampled_exact_fragment = sampleFromDistribution(prob_exact_fragment);\n\n std::vector<double> scores;\n\n scores = calculateScores(prob_averagine_precursor, prob_exact_fragment);\n\n \/\/std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n \/\/ << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << 0 << std::endl;\n\n scores = calculateScores(prob_exact_precursor, prob_exact_fragment);\n\n \/\/std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n \/\/ << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << 0 << std::endl;\n\n scores = calculateScores(prob_decoy, prob_exact_fragment);\n\n \/\/std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n \/\/ << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << 1 << std::endl;\n\n scores = calculateScores(prob_sampled_exact_fragment, prob_exact_fragment);\n\n \/\/std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n \/\/ << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << 0 << std::endl;\n }\n\n num_processed++;\n if (num_processed % 10000 == 0) {\n std::cout << num_processed << std::endl;\n }\n}\n\nvoid testTheoreticalPeptide(AASequence& pep)\n{\n EmpiricalFormula precursor = pep.getFormula();\n EmpiricalFormula fragment;\n for (Size i = 1; i < pep.size(); i++)\n {\n AASequence frag = pep.getPrefix(i);\n\n fragment = frag.getFormula(Residue::ResidueType::BIon);\n testTheoreticalIon(pep, frag, precursor, fragment);\n\n fragment = pep.getPrefix(i).getFormula(Residue::ResidueType::YIon);\n testTheoreticalIon(pep, frag, precursor, fragment);\n }\n}\n\nvoid testTheoreticalProtein(FASTAFile::FASTAEntry& protein, EnzymaticDigestion& digestor)\n{\n static Size MIN_PEPTIDE_LENGTH = 5;\n static Size MAX_PEPTIDE_LENGTH = 80;\n\n std::vector<AASequence> peptides;\n digestor.digest(AASequence::fromString(protein.sequence), peptides);\n for (Size j = 0; j < peptides.size(); ++j)\n {\n if (peptides[j].size() >= MIN_PEPTIDE_LENGTH && peptides[j].size() <= MAX_PEPTIDE_LENGTH)\n {\n testTheoreticalPeptide(peptides[j]);\n }\n }\n}\n\nvoid testTheoreticalPeptides(std::string fasta_path)\n{\n std::vector<FASTAFile::FASTAEntry> proteins;\n FASTAFile().load(fasta_path, proteins);\n\n EnzymaticDigestion digestor; \/\/ default parameters are fully tryptic with 0 missed cleavages\n\n for (Size i = 0; i < proteins.size(); ++i)\n {\n testTheoreticalProtein(proteins[i], digestor);\n }\n}\n\nint main(int argc, char * argv[])\n{\n testTheoreticalPeptides(argv[1]);\n return 0;\n}<commit_msg>Evaluation of approx precursor, approx fragment, approx fragment_S, and exact precursor in comparison to exact fragment<commit_after>#include <iostream>\n#include <random>\n#include <numeric>\n\n#include <OpenMS\/FORMAT\/FASTAFile.h>\n#include <OpenMS\/CHEMISTRY\/AASequence.h>\n#include <OpenMS\/CHEMISTRY\/ElementDB.h>\n#include <OpenMS\/CHEMISTRY\/Residue.h>\n#include <OpenMS\/CHEMISTRY\/EnzymaticDigestion.h>\n#include <OpenMS\/CHEMISTRY\/IsotopeDistribution.h>\n#include <OpenMS\/MATH\/STATISTICS\/StatisticFunctions.h>\n\n#include \"Stats.h\"\n\nusing namespace OpenMS;\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_real_distribution<> dis(0, 1);\n\nstd::vector<double> sampleDecoy(int length)\n{\n std::vector<double> probabilities;\n double sum = 0;\n for (int i = 0; i < length; ++i)\n {\n probabilities.push_back(dis(gen));\n sum+= probabilities[i];\n }\n for (int i = 0; i < length; ++i)\n {\n probabilities[i] \/= sum;\n }\n\n return probabilities;\n}\n\nstd::vector<double> sampleFromDistribution(std::vector<double>& probabilities)\n{\n static int SAMPLE_SIZE = 1e3;\n\n std::vector<double> prefix_sum(probabilities.size());\n std::partial_sum(probabilities.begin(), probabilities.end(), prefix_sum.begin());\n\n std::vector<double> sample(probabilities.size(),0);\n\n for (int i = 0; i < SAMPLE_SIZE; ++i)\n {\n double ran = dis(gen);\n int index = std::upper_bound(prefix_sum.begin(), prefix_sum.end(), ran) - prefix_sum.begin();\n sample[index] += 1.0\/SAMPLE_SIZE;\n }\n return sample;\n}\n\nstd::vector<double> fillProbabilities(IsotopeDistribution& dist, UInt length)\n{\n std::vector<double> probabilities;\n for (Size i = 0; i < dist.size(); ++i)\n {\n probabilities.push_back(dist.getContainer()[i].second);\n }\n\n for (Size i = dist.size(); i < length; ++i) {\n probabilities.push_back(0);\n }\n\n return probabilities;\n}\n\nstd::vector<double> calculateScores(std::vector<double>& l, std::vector<double>& r)\n{\n std::vector<double> result;\n result.push_back(Math::pearsonCorrelationCoefficient(l.begin(), l.end(), r.begin(), r.end()));\n result.push_back(Stats::totalVariationDistance(l.begin(), l.end(), r.begin(), r.end()));\n result.push_back(Stats::chiSquared(l.begin(), l.end(), r.begin(), r.end()));\n return result;\n}\n\nvoid testTheoreticalIon(AASequence& pep, AASequence& frag, EmpiricalFormula& precursor, EmpiricalFormula& fragment)\n{\n static Size MAX_ISOTOPE = 10;\n static Size LENGTH = MAX_ISOTOPE+1;\n\n int num_s = fragment.getNumberOf(ElementDB::getInstance()->getElement(\"Sulfur\"));\n int num_cs = precursor.getNumberOf(ElementDB::getInstance()->getElement(\"Sulfur\")) - num_s;\n\n double pep_mass = precursor.getAverageWeight();\n double frag_mass = fragment.getAverageWeight();\n\n std::vector<UInt> isolated_precursor_isotopes(1,0);\n for (UInt i = 1; i <= MAX_ISOTOPE; ++i) {\n \/\/isolated_precursor_isotopes.clear();\n isolated_precursor_isotopes.push_back(i);\n\n IsotopeDistribution exact_fragment_dist = fragment.getConditionalFragmentIsotopeDist(precursor, isolated_precursor_isotopes);\n IsotopeDistribution exact_precursor_dist = fragment.getIsotopeDistribution(i+1);\n\n IsotopeDistribution approx_precursor_dist(i+1);\n approx_precursor_dist.estimateFromPeptideWeight(fragment.getAverageWeight());\n approx_precursor_dist.renormalize();\n\n IsotopeDistribution approx_fragment_dist(i+1);\n approx_fragment_dist.estimateForFragmentFromPeptideWeight(precursor.getAverageWeight(), fragment.getAverageWeight(), isolated_precursor_isotopes);\n approx_fragment_dist.renormalize();\n\n IsotopeDistribution approx_fragment_S_dist(i+1);\n approx_fragment_S_dist.estimateForFragmentFromPeptideWeightAndS(precursor.getAverageWeight(), num_s+num_cs, fragment.getAverageWeight(), num_s, isolated_precursor_isotopes);\n approx_fragment_S_dist.renormalize();\n\n\n\n std::vector<double> exact_fragment_prob = fillProbabilities(exact_fragment_dist, i+1);\n std::vector<double> exact_precursor_prob = fillProbabilities(exact_precursor_dist, i+1);\n std::vector<double> approx_precursor_prob = fillProbabilities(approx_precursor_dist, i+1);\n std::vector<double> approx_fragment_prob = fillProbabilities(approx_fragment_dist, i+1);\n std::vector<double> approx_fragment_S_prob = fillProbabilities(approx_fragment_S_dist, i+1);\n\n \/\/std::vector<double> decoy_prob = sampleDecoy(i+1);\n \/\/std::vector<double> sampled_exact_fragment_prob = sampleFromDistribution(exact_fragment_prob);\n\n std::vector<double> scores;\n\n scores = calculateScores(exact_fragment_prob, exact_precursor_prob);\n\n std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << \"exact_precursor\" << std::endl;\n\n scores = calculateScores(exact_fragment_prob, approx_precursor_prob);\n\n std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << \"approx_precursor\" << std::endl;\n\n scores = calculateScores(exact_fragment_prob, approx_fragment_prob);\n\n std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << \"approx_fragment\" << std::endl;\n\n scores = calculateScores(exact_fragment_prob, approx_fragment_S_prob);\n\n std::cout << scores[0] << \"\\t\" << scores[1] << \"\\t\" << scores[2] << \"\\t\" << pep_mass << \"\\t\"\n << frag_mass << \"\\t\" << i << \"\\t\" << num_s << \"\\t\" << num_cs << \"\\t\" << \"approx_fragment_S\" << std::endl;\n }\n}\n\nvoid testTheoreticalPeptide(AASequence& pep)\n{\n EmpiricalFormula precursor = pep.getFormula();\n EmpiricalFormula fragment;\n for (Size i = 1; i < pep.size(); i++)\n {\n AASequence frag = pep.getPrefix(i);\n\n fragment = frag.getFormula(Residue::ResidueType::BIon);\n testTheoreticalIon(pep, frag, precursor, fragment);\n\n fragment = pep.getPrefix(i).getFormula(Residue::ResidueType::YIon);\n testTheoreticalIon(pep, frag, precursor, fragment);\n }\n}\n\nvoid testTheoreticalProtein(FASTAFile::FASTAEntry& protein, EnzymaticDigestion& digestor)\n{\n static Size MIN_PEPTIDE_LENGTH = 5;\n static Size MAX_PEPTIDE_LENGTH = 80;\n\n std::vector<AASequence> peptides;\n digestor.digest(AASequence::fromString(protein.sequence), peptides);\n for (Size j = 0; j < peptides.size(); ++j)\n {\n if (peptides[j].size() >= MIN_PEPTIDE_LENGTH && peptides[j].size() <= MAX_PEPTIDE_LENGTH)\n {\n testTheoreticalPeptide(peptides[j]);\n }\n }\n}\n\nvoid testTheoreticalPeptides(std::string fasta_path, int job_id, int num_jobs)\n{\n std::vector<FASTAFile::FASTAEntry> proteins;\n FASTAFile().load(fasta_path, proteins);\n\n EnzymaticDigestion digestor; \/\/ default parameters are fully tryptic with 0 missed cleavages\n\n for (Size i = job_id; i < proteins.size(); i+=num_jobs)\n {\n testTheoreticalProtein(proteins[i], digestor);\n }\n}\n\nint main(int argc, char * argv[])\n{\n testTheoreticalPeptides(argv[1], atoi(argv[2])-1, atoi(argv[3]));\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <AnyValue.h>\n#include <Serialize\/Serializable.h>\n#include <Bundle.h>\n#include <DynamicObjectHelper.h>\n\nusing namespace EasyCpp;\n\nnamespace EasyCppTest\n{\n\tTEST(AnyValue, Int)\n\t{\n\t\tint val = 10;\n\t\tAnyValue any(val);\n\t\tASSERT_TRUE(any.isType<int>());\n\t\tASSERT_TRUE(any.isConvertibleTo<int>());\n\t\tASSERT_EQ(val, any.as<int>());\n\t}\n\n\tTEST(AnyValue, Default)\n\t{\n\t\tAnyValue any;\n\t\tASSERT_TRUE(any.isType<nullptr_t>());\n\t}\n\n\tTEST(AnyValue, Convert)\n\t{\n\t\tAnyValue any(true);\n\t\tASSERT_TRUE(any.isType<bool>());\n\t\tASSERT_TRUE(any.isConvertibleTo<std::string>());\n\t\tASSERT_EQ(std::string(\"true\"), any.as<std::string>());\n\t}\n\n\tTEST(AnyValue, isSerializable)\n\t{\n\t\tclass SimpleSerializable : public Serialize::Serializable\n\t\t{\n\t\tpublic:\n\t\t\tvirtual AnyValue toAnyValue() const override\n\t\t\t{\n\t\t\t\treturn AnyValue();\n\t\t\t}\n\t\t\tvirtual void fromAnyValue(const AnyValue& any) override\n\t\t\t{}\n\t\t};\n\n\t\tSimpleSerializable t;\n\t\tAnyValue any(t);\n\t\tASSERT_TRUE(any.isType<SimpleSerializable>());\n\t\tASSERT_TRUE(any.isSerializable());\n\n\t\tAnyValue any2(true);\n\t\tASSERT_TRUE(any2.isType<bool>());\n\t\tASSERT_FALSE(any2.isSerializable());\n\t}\n\n\tTEST(AnyValue, CastOperator)\n\t{\n\t\tAnyValue a = std::string(\"20\");\n\n\t\tstd::string s = a;\n\t\tASSERT_EQ(std::string(\"20\"), s);\n\t\tint i = a;\n\t\tASSERT_EQ(20, i);\n\t}\n\n\tTEST(AnyValue, NullNotNullptr)\n\t{\n\t\tAnyValue a((void*)0x00);\n\t\tASSERT_FALSE(a.isType<nullptr_t>());\n\t}\n\n\tclass SimpleSample\n\t{\n\tpublic:\n\t\tSimpleSample()\n\t\t{\n\t\t\tsetText(\"Hello\");\n\t\t}\n\n\t\tstd::string getText()\n\t\t{\n\t\t\treturn _text;\n\t\t}\n\n\t\tvoid setText(const std::string& text)\n\t\t{\n\t\t\t_text = text;\n\t\t}\n\n\tprivate:\n\t\tstd::string _text;\n\t};\n}\n\ntemplate<>\nstruct EasyCpp::TypeCheck<EasyCppTest::SimpleSample*>\n{\n\ttypedef EasyCppTest::SimpleSample Type;\n\tstatic bool IsSerializable()\n\t{\n\t\treturn false;\n\t}\n\n\tstatic bool IsDynamicObject()\n\t{\n\t\treturn true;\n\t}\n\n\tstatic const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample* value)\n\t{\n\t\tthrow std::runtime_error(\"This Anyvalue does not implement Serializable\");\n\t}\n\n\tstatic std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample* value)\n\t{\n\t\tclass DynamicWrapper : public DynamicObjectHelper\n\t\t{\n\t\tpublic:\n\t\t\tDynamicWrapper(EasyCppTest::SimpleSample* value)\n\t\t\t\t:_value(value)\n\t\t\t{\n\t\t\t\tthis->addFunction(\"setText\", AnyFunction::fromDynamicFunction([this](const AnyArray& params) {\n\t\t\t\t\tthis->_value->setText(params[0].as<std::string>());\n\t\t\t\t\treturn AnyValue();\n\t\t\t\t}));\n\t\t\t}\n\t\tprivate:\n\t\t\tEasyCppTest::SimpleSample* _value;\n\t\t};\n\t\treturn std::make_shared<DynamicWrapper>(value);\n\t}\n};\n\ntemplate<>\nstruct EasyCpp::TypeCheck<EasyCppTest::SimpleSample>\n{\n\ttypedef EasyCppTest::SimpleSample Type;\n\tstatic bool IsSerializable()\n\t{\n\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::IsSerializable();\n\t}\n\n\tstatic bool IsDynamicObject()\n\t{\n\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::IsDynamicObject();\n\t}\n\n\tstatic const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample& value)\n\t{\n\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::AsSerializable(&value);\n\t}\n\n\tstatic std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample& value)\n\t{\n\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::AsDynamicObject(&value);\n\t}\n};\n\nnamespace EasyCppTest\n{\n\tTEST(AnyValue, ExternalTypeCheck)\n\t{\n\t\tSimpleSample sample;\n\t\tAnyValue val(&sample);\n\n\t\tASSERT_TRUE(val.isDynamicObject());\n\t\tauto& obj = val.asDynamicObject();\n\t\tobj.callFunction(\"setText\", { std::string(\"test_value\") });\n\n\t\tASSERT_EQ(\"test_value\", sample.getText());\n\t}\n}<commit_msg>Linux Buildfix<commit_after>#include <gtest\/gtest.h>\n#include <AnyValue.h>\n#include <Serialize\/Serializable.h>\n#include <Bundle.h>\n#include <DynamicObjectHelper.h>\n\nusing namespace EasyCpp;\n\nnamespace EasyCppTest\n{\n\tTEST(AnyValue, Int)\n\t{\n\t\tint val = 10;\n\t\tAnyValue any(val);\n\t\tASSERT_TRUE(any.isType<int>());\n\t\tASSERT_TRUE(any.isConvertibleTo<int>());\n\t\tASSERT_EQ(val, any.as<int>());\n\t}\n\n\tTEST(AnyValue, Default)\n\t{\n\t\tAnyValue any;\n\t\tASSERT_TRUE(any.isType<nullptr_t>());\n\t}\n\n\tTEST(AnyValue, Convert)\n\t{\n\t\tAnyValue any(true);\n\t\tASSERT_TRUE(any.isType<bool>());\n\t\tASSERT_TRUE(any.isConvertibleTo<std::string>());\n\t\tASSERT_EQ(std::string(\"true\"), any.as<std::string>());\n\t}\n\n\tTEST(AnyValue, isSerializable)\n\t{\n\t\tclass SimpleSerializable : public Serialize::Serializable\n\t\t{\n\t\tpublic:\n\t\t\tvirtual AnyValue toAnyValue() const override\n\t\t\t{\n\t\t\t\treturn AnyValue();\n\t\t\t}\n\t\t\tvirtual void fromAnyValue(const AnyValue& any) override\n\t\t\t{}\n\t\t};\n\n\t\tSimpleSerializable t;\n\t\tAnyValue any(t);\n\t\tASSERT_TRUE(any.isType<SimpleSerializable>());\n\t\tASSERT_TRUE(any.isSerializable());\n\n\t\tAnyValue any2(true);\n\t\tASSERT_TRUE(any2.isType<bool>());\n\t\tASSERT_FALSE(any2.isSerializable());\n\t}\n\n\tTEST(AnyValue, CastOperator)\n\t{\n\t\tAnyValue a = std::string(\"20\");\n\n\t\tstd::string s = a;\n\t\tASSERT_EQ(std::string(\"20\"), s);\n\t\tint i = a;\n\t\tASSERT_EQ(20, i);\n\t}\n\n\tTEST(AnyValue, NullNotNullptr)\n\t{\n\t\tAnyValue a((void*)0x00);\n\t\tASSERT_FALSE(a.isType<nullptr_t>());\n\t}\n\n\tclass SimpleSample\n\t{\n\tpublic:\n\t\tSimpleSample()\n\t\t{\n\t\t\tsetText(\"Hello\");\n\t\t}\n\n\t\tstd::string getText()\n\t\t{\n\t\t\treturn _text;\n\t\t}\n\n\t\tvoid setText(const std::string& text)\n\t\t{\n\t\t\t_text = text;\n\t\t}\n\n\tprivate:\n\t\tstd::string _text;\n\t};\n}\n\nnamespace EasyCpp\n{\n\ttemplate<>\n\tstruct TypeCheck<EasyCppTest::SimpleSample*>\n\t{\n\t\ttypedef EasyCppTest::SimpleSample Type;\n\t\tstatic bool IsSerializable()\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tstatic bool IsDynamicObject()\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\tstatic const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample* value)\n\t\t{\n\t\t\tthrow std::runtime_error(\"This Anyvalue does not implement Serializable\");\n\t\t}\n\n\t\tstatic std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample* value)\n\t\t{\n\t\t\tclass DynamicWrapper : public DynamicObjectHelper\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tDynamicWrapper(EasyCppTest::SimpleSample* value)\n\t\t\t\t\t:_value(value)\n\t\t\t\t{\n\t\t\t\t\tthis->addFunction(\"setText\", AnyFunction::fromDynamicFunction([this](const AnyArray& params) {\n\t\t\t\t\t\tthis->_value->setText(params[0].as<std::string>());\n\t\t\t\t\t\treturn AnyValue();\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\tprivate:\n\t\t\t\tEasyCppTest::SimpleSample* _value;\n\t\t\t};\n\t\t\treturn std::make_shared<DynamicWrapper>(value);\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct TypeCheck<EasyCppTest::SimpleSample>\n\t{\n\t\ttypedef EasyCppTest::SimpleSample Type;\n\t\tstatic bool IsSerializable()\n\t\t{\n\t\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::IsSerializable();\n\t\t}\n\n\t\tstatic bool IsDynamicObject()\n\t\t{\n\t\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::IsDynamicObject();\n\t\t}\n\n\t\tstatic const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample& value)\n\t\t{\n\t\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::AsSerializable(&value);\n\t\t}\n\n\t\tstatic std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample& value)\n\t\t{\n\t\t\treturn TypeCheck<EasyCppTest::SimpleSample*>::AsDynamicObject(&value);\n\t\t}\n\t};\n}\nnamespace EasyCppTest\n{\n\tTEST(AnyValue, ExternalTypeCheck)\n\t{\n\t\tSimpleSample sample;\n\t\tAnyValue val(&sample);\n\n\t\tASSERT_TRUE(val.isDynamicObject());\n\t\tauto& obj = val.asDynamicObject();\n\t\tobj.callFunction(\"setText\", { std::string(\"test_value\") });\n\n\t\tASSERT_EQ(\"test_value\", sample.getText());\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#ifndef FAST_MOVIE_STREAMER_HPP_\n#define FAST_MOVIE_STREAMER_HPP_\n\n#include \"FAST\/Streamers\/Streamer.hpp\"\n#include <QObject>\n\nclass QMediaPlayer;\nclass QThread;\n\nnamespace fast {\n\nclass Image;\n\nclass MovieStreamerWorker;\n\nclass FAST_EXPORT MovieStreamer : public Streamer {\n FAST_OBJECT(MovieStreamer)\n public:\n void setFilename(std::string filename);\n std::string getFilename() const;\n bool hasReachedEnd();\n void addNewImageFrame(const uchar* data, int width, int height);\n void setGrayscale(bool grayscale);\n bool getGrayscale() const;\n void setFinished(bool finished);\n int getFramesAdded() const;\n ~MovieStreamer();\n void loadAttributes() override;\n void addLastFrame();\n private:\n MovieStreamer();\n void execute();\n void generateStream() override {};\n\n std::string mFilename;\n bool mGrayscale = true;\n bool m_finished = false;\n int64_t m_framesAdded = 0;\n std::chrono::high_resolution_clock::time_point m_startTime;\n QThread* thread;\n MovieStreamerWorker* worker;\n std::shared_ptr<Image> m_currentImage;\n\n};\n\nclass VideoSurface;\n\nclass MovieStreamerWorker : public QObject {\n Q_OBJECT\n public:\n MovieStreamerWorker(MovieStreamer* streamer);\n ~MovieStreamerWorker();\n public Q_SLOTS:\n void run();\n Q_SIGNALS:\n void finished();\n void error(QString err);\n private:\n MovieStreamer* mStreamer;\n std::unique_ptr<QMediaPlayer> m_player;\n std::unique_ptr<VideoSurface> m_myVideoSurface;\n};\n\n}\n\n#endif\n<commit_msg>Fixed windows build issue with movie streamer worker<commit_after>#pragma once\n\n#include \"FAST\/Streamers\/Streamer.hpp\"\n#include <QObject>\n\nclass QMediaPlayer;\nclass QThread;\n\nnamespace fast {\n\nclass Image;\n\nclass MovieStreamerWorker;\n\nclass FAST_EXPORT MovieStreamer : public Streamer {\n FAST_OBJECT(MovieStreamer)\n public:\n void setFilename(std::string filename);\n std::string getFilename() const;\n bool hasReachedEnd();\n void addNewImageFrame(const uchar* data, int width, int height);\n void setGrayscale(bool grayscale);\n bool getGrayscale() const;\n void setFinished(bool finished);\n int getFramesAdded() const;\n ~MovieStreamer();\n void loadAttributes() override;\n void addLastFrame();\n private:\n MovieStreamer();\n void execute();\n void generateStream() override {};\n\n std::string mFilename;\n bool mGrayscale = true;\n bool m_finished = false;\n int64_t m_framesAdded = 0;\n std::chrono::high_resolution_clock::time_point m_startTime;\n QThread* thread;\n MovieStreamerWorker* worker;\n std::shared_ptr<Image> m_currentImage;\n\n};\n\nclass VideoSurface;\n\nclass FAST_EXPORT MovieStreamerWorker : public QObject {\n Q_OBJECT\n public:\n MovieStreamerWorker(MovieStreamer* streamer);\n ~MovieStreamerWorker();\n public Q_SLOTS:\n void run();\n Q_SIGNALS:\n void finished();\n void error(QString err);\n private:\n MovieStreamer* mStreamer;\n std::unique_ptr<QMediaPlayer> m_player;\n std::unique_ptr<VideoSurface> m_myVideoSurface;\n};\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ThreadPlanStepInRange.cpp -------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Target\/ThreadPlanStepInRange.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Target\/ThreadPlanStepOut.h\"\n#include \"lldb\/Target\/ThreadPlanStepThrough.h\"\n#include \"lldb\/Core\/RegularExpression.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nuint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eAvoidNoDebug;\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanStepInRange: Step through a stack range, either stepping over or into\n\/\/ based on the value of \\a type.\n\/\/----------------------------------------------------------------------\n\nThreadPlanStepInRange::ThreadPlanStepInRange\n(\n Thread &thread,\n const AddressRange &range,\n const SymbolContext &addr_context,\n lldb::RunMode stop_others\n) :\n ThreadPlanStepRange (ThreadPlan::eKindStepInRange, \"Step Range stepping in\", thread, range, addr_context, stop_others),\n ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),\n m_step_past_prologue (true),\n m_virtual_step (false)\n{\n SetFlagsToDefault ();\n}\n\nThreadPlanStepInRange::ThreadPlanStepInRange\n(\n Thread &thread,\n const AddressRange &range,\n const SymbolContext &addr_context,\n const char *step_into_target,\n lldb::RunMode stop_others\n) :\n ThreadPlanStepRange (ThreadPlan::eKindStepInRange, \"Step Range stepping in\", thread, range, addr_context, stop_others),\n ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),\n m_step_past_prologue (true),\n m_virtual_step (false),\n m_step_into_target (step_into_target)\n{\n SetFlagsToDefault ();\n}\n\nThreadPlanStepInRange::~ThreadPlanStepInRange ()\n{\n}\n\nvoid\nThreadPlanStepInRange::GetDescription (Stream *s, lldb::DescriptionLevel level)\n{\n if (level == lldb::eDescriptionLevelBrief)\n s->Printf(\"step in\");\n else\n {\n s->Printf (\"Stepping through range (stepping into functions): \");\n DumpRanges(s);\n s->Printf (\"targeting %s.\", m_step_into_target.AsCString());\n }\n}\n\nbool\nThreadPlanStepInRange::ShouldStop (Event *event_ptr)\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n m_no_more_plans = false;\n \n if (log)\n {\n StreamString s;\n s.Address (m_thread.GetRegisterContext()->GetPC(), \n m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());\n log->Printf(\"ThreadPlanStepInRange reached %s.\", s.GetData());\n }\n\n if (IsPlanComplete())\n return true;\n \n ThreadPlan* new_plan = NULL;\n\n if (m_virtual_step)\n {\n \/\/ If we've just completed a virtual step, all we need to do is check for a ShouldStopHere plan, and otherwise\n \/\/ we're done.\n new_plan = InvokeShouldStopHereCallback();\n }\n else\n {\n \/\/ Stepping through should be done running other threads in general, since we're setting a breakpoint and\n \/\/ continuing. So only stop others if we are explicitly told to do so.\n \n bool stop_others;\n if (m_stop_others == lldb::eOnlyThisThread)\n stop_others = false;\n else\n stop_others = true;\n \n FrameComparison frame_order = CompareCurrentFrameToStartFrame();\n \n if (frame_order == eFrameCompareOlder)\n {\n \/\/ If we're in an older frame then we should stop.\n \/\/\n \/\/ A caveat to this is if we think the frame is older but we're actually in a trampoline.\n \/\/ I'm going to make the assumption that you wouldn't RETURN to a trampoline. So if we are\n \/\/ in a trampoline we think the frame is older because the trampoline confused the backtracer.\n new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);\n if (new_plan == NULL)\n return true;\n else if (log)\n {\n log->Printf(\"Thought I stepped out, but in fact arrived at a trampoline.\");\n }\n\n }\n else if (frame_order == eFrameCompareEqual && InSymbol())\n {\n \/\/ If we are not in a place we should step through, we're done.\n \/\/ One tricky bit here is that some stubs don't push a frame, so we have to check\n \/\/ both the case of a frame that is younger, or the same as this frame. \n \/\/ However, if the frame is the same, and we are still in the symbol we started\n \/\/ in, the we don't need to do this. This first check isn't strictly necessary,\n \/\/ but it is more efficient.\n \n \/\/ If we're still in the range, keep going, either by running to the next branch breakpoint, or by\n \/\/ stepping.\n if (InRange())\n {\n SetNextBranchBreakpoint();\n return false;\n }\n \n SetPlanComplete();\n m_no_more_plans = true;\n return true;\n }\n \n \/\/ If we get to this point, we're not going to use a previously set \"next branch\" breakpoint, so delete it:\n ClearNextBranchBreakpoint();\n \n \/\/ We may have set the plan up above in the FrameIsOlder section:\n \n if (new_plan == NULL)\n new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);\n \n if (log)\n {\n if (new_plan != NULL)\n log->Printf (\"Found a step through plan: %s\", new_plan->GetName());\n else\n log->Printf (\"No step through plan found.\");\n }\n \n \/\/ If not, give the \"should_stop\" callback a chance to push a plan to get us out of here.\n \/\/ But only do that if we actually have stepped in.\n if (!new_plan && frame_order == eFrameCompareYounger)\n new_plan = InvokeShouldStopHereCallback();\n\n \/\/ If we've stepped in and we are going to stop here, check to see if we were asked to\n \/\/ run past the prologue, and if so do that.\n \n if (new_plan == NULL && frame_order == eFrameCompareYounger && m_step_past_prologue)\n {\n lldb::StackFrameSP curr_frame = m_thread.GetStackFrameAtIndex(0);\n if (curr_frame)\n {\n size_t bytes_to_skip = 0;\n lldb::addr_t curr_addr = m_thread.GetRegisterContext()->GetPC();\n Address func_start_address;\n \n SymbolContext sc = curr_frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextSymbol);\n \n if (sc.function)\n {\n func_start_address = sc.function->GetAddressRange().GetBaseAddress();\n if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))\n bytes_to_skip = sc.function->GetPrologueByteSize();\n }\n else if (sc.symbol)\n {\n func_start_address = sc.symbol->GetAddress();\n if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))\n bytes_to_skip = sc.symbol->GetPrologueByteSize();\n }\n \n if (bytes_to_skip != 0)\n {\n func_start_address.Slide (bytes_to_skip);\n log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);\n if (log)\n log->Printf (\"Pushing past prologue \");\n \n new_plan = m_thread.QueueThreadPlanForRunToAddress(false, func_start_address,true);\n }\n }\n }\n }\n \n if (new_plan == NULL)\n {\n m_no_more_plans = true;\n SetPlanComplete();\n return true;\n }\n else\n {\n m_no_more_plans = false;\n return false;\n }\n}\n\nvoid\nThreadPlanStepInRange::SetFlagsToDefault ()\n{\n GetFlags().Set(ThreadPlanStepInRange::s_default_flag_values);\n}\n\nvoid \nThreadPlanStepInRange::SetAvoidRegexp(const char *name)\n{\n if (m_avoid_regexp_ap.get() == NULL)\n m_avoid_regexp_ap.reset (new RegularExpression(name));\n\n m_avoid_regexp_ap->Compile (name);\n}\n\nvoid\nThreadPlanStepInRange::SetDefaultFlagValue (uint32_t new_value)\n{\n \/\/ TODO: Should we test this for sanity?\n ThreadPlanStepInRange::s_default_flag_values = new_value;\n}\n\nbool\nThreadPlanStepInRange::FrameMatchesAvoidRegexp ()\n{\n StackFrame *frame = GetThread().GetStackFrameAtIndex(0).get();\n\n const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get();\n if (avoid_regexp_to_use == NULL)\n avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();\n \n if (avoid_regexp_to_use != NULL)\n {\n SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);\n if (sc.symbol != NULL)\n {\n const char *frame_function_name = sc.GetFunctionName().GetCString();\n if (frame_function_name)\n return avoid_regexp_to_use->Execute(frame_function_name);\n }\n }\n return false;\n}\n\nThreadPlan *\nThreadPlanStepInRange::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, void *baton)\n{\n bool should_step_out = false;\n StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get();\n\n if (flags.Test(eAvoidNoDebug))\n {\n if (!frame->HasDebugInformation())\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf (\"Stepping out of frame with no debug info\");\n\n should_step_out = true;\n }\n }\n \n if (current_plan->GetKind() == eKindStepInRange)\n {\n ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);\n if (step_in_range_plan->m_step_into_target)\n {\n SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);\n if (sc.symbol != NULL)\n {\n \/\/ First try an exact match, since that's cheap with ConstStrings. Then do a strstr compare.\n if (step_in_range_plan->m_step_into_target == sc.GetFunctionName())\n {\n should_step_out = false;\n }\n else\n {\n const char *target_name = step_in_range_plan->m_step_into_target.AsCString();\n const char *function_name = sc.GetFunctionName().AsCString();\n \n if (function_name == NULL)\n should_step_out = true;\n else if (strstr (function_name, target_name) == NULL)\n should_step_out = true;\n }\n }\n }\n \n if (!should_step_out)\n {\n ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);\n should_step_out = step_in_range_plan->FrameMatchesAvoidRegexp ();\n }\n }\n \n \n if (should_step_out)\n {\n \/\/ FIXME: Make sure the ThreadPlanForStepOut does the right thing with inlined functions.\n \/\/ We really should have all plans take the tri-state for \"stop others\" so we can do the right\n \/\/ thing. For now let's be safe and always run others when we are likely to run arbitrary code.\n const bool stop_others = false;\n return current_plan->GetThread().QueueThreadPlanForStepOut (false, \n NULL, \n true, \n stop_others,\n eVoteNo, \n eVoteNoOpinion,\n 0); \/\/ Frame index\n }\n\n return NULL;\n}\n\nbool\nThreadPlanStepInRange::PlanExplainsStop (Event *event_ptr)\n{\n \/\/ We always explain a stop. Either we've just done a single step, in which\n \/\/ case we'll do our ordinary processing, or we stopped for some\n \/\/ reason that isn't handled by our sub-plans, in which case we want to just stop right\n \/\/ away.\n \/\/ In general, we don't want to mark the plan as complete for unexplained stops.\n \/\/ For instance, if you step in to some code with no debug info, so you step out\n \/\/ and in the course of that hit a breakpoint, then you want to stop & show the user\n \/\/ the breakpoint, but not unship the step in plan, since you still may want to complete that\n \/\/ plan when you continue. This is particularly true when doing \"step in to target function.\"\n \/\/ stepping.\n \/\/\n \/\/ The only variation is that if we are doing \"step by running to next branch\" in which case\n \/\/ if we hit our branch breakpoint we don't set the plan to complete.\n \n if (m_virtual_step)\n return true;\n \n StopInfoSP stop_info_sp = GetPrivateStopReason();\n if (stop_info_sp)\n {\n StopReason reason = stop_info_sp->GetStopReason();\n\n switch (reason)\n {\n case eStopReasonBreakpoint:\n if (NextRangeBreakpointExplainsStop(stop_info_sp))\n return true;\n case eStopReasonWatchpoint:\n case eStopReasonSignal:\n case eStopReasonException:\n case eStopReasonExec:\n case eStopReasonThreadExiting:\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->PutCString (\"ThreadPlanStepInRange got asked if it explains the stop for some reason other than step.\");\n }\n return false;\n break;\n default:\n break;\n }\n }\n return true;\n}\n\nbool\nThreadPlanStepInRange::WillResume (lldb::StateType resume_state, bool current_plan)\n{\n if (resume_state == eStateStepping && current_plan)\n {\n \/\/ See if we are about to step over a virtual inlined call.\n bool step_without_resume = m_thread.DecrementCurrentInlinedDepth();\n if (step_without_resume)\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf (\"ThreadPlanStepInRange::WillResume: returning false, inline_depth: %d\",\n m_thread.GetCurrentInlinedDepth());\n SetStopInfo(StopInfo::CreateStopReasonToTrace(m_thread));\n \n \/\/ FIXME: Maybe it would be better to create a InlineStep stop reason, but then\n \/\/ the whole rest of the world would have to handle that stop reason.\n m_virtual_step = true;\n }\n return !step_without_resume;\n }\n else\n return ThreadPlan::WillResume(resume_state, current_plan);\n \n}\n<commit_msg>Add some logging to track cases where “step-in” steps out due to the avoid-regexp and the step-in target.<commit_after>\/\/===-- ThreadPlanStepInRange.cpp -------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Target\/ThreadPlanStepInRange.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/Target.h\"\n#include \"lldb\/Target\/Thread.h\"\n#include \"lldb\/Target\/ThreadPlanStepOut.h\"\n#include \"lldb\/Target\/ThreadPlanStepThrough.h\"\n#include \"lldb\/Core\/RegularExpression.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nuint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eAvoidNoDebug;\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanStepInRange: Step through a stack range, either stepping over or into\n\/\/ based on the value of \\a type.\n\/\/----------------------------------------------------------------------\n\nThreadPlanStepInRange::ThreadPlanStepInRange\n(\n Thread &thread,\n const AddressRange &range,\n const SymbolContext &addr_context,\n lldb::RunMode stop_others\n) :\n ThreadPlanStepRange (ThreadPlan::eKindStepInRange, \"Step Range stepping in\", thread, range, addr_context, stop_others),\n ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),\n m_step_past_prologue (true),\n m_virtual_step (false)\n{\n SetFlagsToDefault ();\n}\n\nThreadPlanStepInRange::ThreadPlanStepInRange\n(\n Thread &thread,\n const AddressRange &range,\n const SymbolContext &addr_context,\n const char *step_into_target,\n lldb::RunMode stop_others\n) :\n ThreadPlanStepRange (ThreadPlan::eKindStepInRange, \"Step Range stepping in\", thread, range, addr_context, stop_others),\n ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),\n m_step_past_prologue (true),\n m_virtual_step (false),\n m_step_into_target (step_into_target)\n{\n SetFlagsToDefault ();\n}\n\nThreadPlanStepInRange::~ThreadPlanStepInRange ()\n{\n}\n\nvoid\nThreadPlanStepInRange::GetDescription (Stream *s, lldb::DescriptionLevel level)\n{\n if (level == lldb::eDescriptionLevelBrief)\n s->Printf(\"step in\");\n else\n {\n s->Printf (\"Stepping through range (stepping into functions): \");\n DumpRanges(s);\n s->Printf (\"targeting %s.\", m_step_into_target.AsCString());\n }\n}\n\nbool\nThreadPlanStepInRange::ShouldStop (Event *event_ptr)\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n m_no_more_plans = false;\n \n if (log)\n {\n StreamString s;\n s.Address (m_thread.GetRegisterContext()->GetPC(), \n m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());\n log->Printf(\"ThreadPlanStepInRange reached %s.\", s.GetData());\n }\n\n if (IsPlanComplete())\n return true;\n \n ThreadPlan* new_plan = NULL;\n\n if (m_virtual_step)\n {\n \/\/ If we've just completed a virtual step, all we need to do is check for a ShouldStopHere plan, and otherwise\n \/\/ we're done.\n new_plan = InvokeShouldStopHereCallback();\n }\n else\n {\n \/\/ Stepping through should be done running other threads in general, since we're setting a breakpoint and\n \/\/ continuing. So only stop others if we are explicitly told to do so.\n \n bool stop_others;\n if (m_stop_others == lldb::eOnlyThisThread)\n stop_others = false;\n else\n stop_others = true;\n \n FrameComparison frame_order = CompareCurrentFrameToStartFrame();\n \n if (frame_order == eFrameCompareOlder)\n {\n \/\/ If we're in an older frame then we should stop.\n \/\/\n \/\/ A caveat to this is if we think the frame is older but we're actually in a trampoline.\n \/\/ I'm going to make the assumption that you wouldn't RETURN to a trampoline. So if we are\n \/\/ in a trampoline we think the frame is older because the trampoline confused the backtracer.\n new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);\n if (new_plan == NULL)\n return true;\n else if (log)\n {\n log->Printf(\"Thought I stepped out, but in fact arrived at a trampoline.\");\n }\n\n }\n else if (frame_order == eFrameCompareEqual && InSymbol())\n {\n \/\/ If we are not in a place we should step through, we're done.\n \/\/ One tricky bit here is that some stubs don't push a frame, so we have to check\n \/\/ both the case of a frame that is younger, or the same as this frame. \n \/\/ However, if the frame is the same, and we are still in the symbol we started\n \/\/ in, the we don't need to do this. This first check isn't strictly necessary,\n \/\/ but it is more efficient.\n \n \/\/ If we're still in the range, keep going, either by running to the next branch breakpoint, or by\n \/\/ stepping.\n if (InRange())\n {\n SetNextBranchBreakpoint();\n return false;\n }\n \n SetPlanComplete();\n m_no_more_plans = true;\n return true;\n }\n \n \/\/ If we get to this point, we're not going to use a previously set \"next branch\" breakpoint, so delete it:\n ClearNextBranchBreakpoint();\n \n \/\/ We may have set the plan up above in the FrameIsOlder section:\n \n if (new_plan == NULL)\n new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);\n \n if (log)\n {\n if (new_plan != NULL)\n log->Printf (\"Found a step through plan: %s\", new_plan->GetName());\n else\n log->Printf (\"No step through plan found.\");\n }\n \n \/\/ If not, give the \"should_stop\" callback a chance to push a plan to get us out of here.\n \/\/ But only do that if we actually have stepped in.\n if (!new_plan && frame_order == eFrameCompareYounger)\n new_plan = InvokeShouldStopHereCallback();\n\n \/\/ If we've stepped in and we are going to stop here, check to see if we were asked to\n \/\/ run past the prologue, and if so do that.\n \n if (new_plan == NULL && frame_order == eFrameCompareYounger && m_step_past_prologue)\n {\n lldb::StackFrameSP curr_frame = m_thread.GetStackFrameAtIndex(0);\n if (curr_frame)\n {\n size_t bytes_to_skip = 0;\n lldb::addr_t curr_addr = m_thread.GetRegisterContext()->GetPC();\n Address func_start_address;\n \n SymbolContext sc = curr_frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextSymbol);\n \n if (sc.function)\n {\n func_start_address = sc.function->GetAddressRange().GetBaseAddress();\n if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))\n bytes_to_skip = sc.function->GetPrologueByteSize();\n }\n else if (sc.symbol)\n {\n func_start_address = sc.symbol->GetAddress();\n if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))\n bytes_to_skip = sc.symbol->GetPrologueByteSize();\n }\n \n if (bytes_to_skip != 0)\n {\n func_start_address.Slide (bytes_to_skip);\n log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);\n if (log)\n log->Printf (\"Pushing past prologue \");\n \n new_plan = m_thread.QueueThreadPlanForRunToAddress(false, func_start_address,true);\n }\n }\n }\n }\n \n if (new_plan == NULL)\n {\n m_no_more_plans = true;\n SetPlanComplete();\n return true;\n }\n else\n {\n m_no_more_plans = false;\n return false;\n }\n}\n\nvoid\nThreadPlanStepInRange::SetFlagsToDefault ()\n{\n GetFlags().Set(ThreadPlanStepInRange::s_default_flag_values);\n}\n\nvoid \nThreadPlanStepInRange::SetAvoidRegexp(const char *name)\n{\n if (m_avoid_regexp_ap.get() == NULL)\n m_avoid_regexp_ap.reset (new RegularExpression(name));\n\n m_avoid_regexp_ap->Compile (name);\n}\n\nvoid\nThreadPlanStepInRange::SetDefaultFlagValue (uint32_t new_value)\n{\n \/\/ TODO: Should we test this for sanity?\n ThreadPlanStepInRange::s_default_flag_values = new_value;\n}\n\nbool\nThreadPlanStepInRange::FrameMatchesAvoidRegexp ()\n{\n StackFrame *frame = GetThread().GetStackFrameAtIndex(0).get();\n\n const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get();\n if (avoid_regexp_to_use == NULL)\n avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();\n \n if (avoid_regexp_to_use != NULL)\n {\n SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);\n if (sc.symbol != NULL)\n {\n const char *frame_function_name = sc.GetFunctionName().GetCString();\n if (frame_function_name)\n {\n bool return_value = avoid_regexp_to_use->Execute(frame_function_name);\n if (return_value)\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf (\"Stepping out of function %s because it matches the avoid regexp \\\"%s\\\".\",\n frame_function_name,\n avoid_regexp_to_use->GetText());\n\n }\n return return_value;\n }\n }\n }\n return false;\n}\n\nThreadPlan *\nThreadPlanStepInRange::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, void *baton)\n{\n bool should_step_out = false;\n StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get();\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n\n if (flags.Test(eAvoidNoDebug))\n {\n if (!frame->HasDebugInformation())\n {\n if (log)\n log->Printf (\"Stepping out of frame with no debug info\");\n\n should_step_out = true;\n }\n }\n \n if (current_plan->GetKind() == eKindStepInRange)\n {\n ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);\n if (step_in_range_plan->m_step_into_target)\n {\n SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);\n if (sc.symbol != NULL)\n {\n \/\/ First try an exact match, since that's cheap with ConstStrings. Then do a strstr compare.\n if (step_in_range_plan->m_step_into_target == sc.GetFunctionName())\n {\n should_step_out = false;\n }\n else\n {\n const char *target_name = step_in_range_plan->m_step_into_target.AsCString();\n const char *function_name = sc.GetFunctionName().AsCString();\n \n if (function_name == NULL)\n should_step_out = true;\n else if (strstr (function_name, target_name) == NULL)\n should_step_out = true;\n }\n if (log && should_step_out)\n log->Printf(\"Stepping out of frame %s which did not match step into target %s.\",\n sc.GetFunctionName().AsCString(),\n step_in_range_plan->m_step_into_target.AsCString());\n }\n }\n \n if (!should_step_out)\n {\n ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);\n \/\/ Don't log the should_step_out here, it's easier to do it in FrameMatchesAvoidRegexp.\n should_step_out = step_in_range_plan->FrameMatchesAvoidRegexp ();\n }\n }\n \n \n if (should_step_out)\n {\n \/\/ FIXME: Make sure the ThreadPlanForStepOut does the right thing with inlined functions.\n \/\/ We really should have all plans take the tri-state for \"stop others\" so we can do the right\n \/\/ thing. For now let's be safe and always run others when we are likely to run arbitrary code.\n const bool stop_others = false;\n return current_plan->GetThread().QueueThreadPlanForStepOut (false, \n NULL, \n true, \n stop_others,\n eVoteNo, \n eVoteNoOpinion,\n 0); \/\/ Frame index\n }\n\n return NULL;\n}\n\nbool\nThreadPlanStepInRange::PlanExplainsStop (Event *event_ptr)\n{\n \/\/ We always explain a stop. Either we've just done a single step, in which\n \/\/ case we'll do our ordinary processing, or we stopped for some\n \/\/ reason that isn't handled by our sub-plans, in which case we want to just stop right\n \/\/ away.\n \/\/ In general, we don't want to mark the plan as complete for unexplained stops.\n \/\/ For instance, if you step in to some code with no debug info, so you step out\n \/\/ and in the course of that hit a breakpoint, then you want to stop & show the user\n \/\/ the breakpoint, but not unship the step in plan, since you still may want to complete that\n \/\/ plan when you continue. This is particularly true when doing \"step in to target function.\"\n \/\/ stepping.\n \/\/\n \/\/ The only variation is that if we are doing \"step by running to next branch\" in which case\n \/\/ if we hit our branch breakpoint we don't set the plan to complete.\n \n if (m_virtual_step)\n return true;\n \n StopInfoSP stop_info_sp = GetPrivateStopReason();\n if (stop_info_sp)\n {\n StopReason reason = stop_info_sp->GetStopReason();\n\n switch (reason)\n {\n case eStopReasonBreakpoint:\n if (NextRangeBreakpointExplainsStop(stop_info_sp))\n return true;\n case eStopReasonWatchpoint:\n case eStopReasonSignal:\n case eStopReasonException:\n case eStopReasonExec:\n case eStopReasonThreadExiting:\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->PutCString (\"ThreadPlanStepInRange got asked if it explains the stop for some reason other than step.\");\n }\n return false;\n break;\n default:\n break;\n }\n }\n return true;\n}\n\nbool\nThreadPlanStepInRange::WillResume (lldb::StateType resume_state, bool current_plan)\n{\n if (resume_state == eStateStepping && current_plan)\n {\n \/\/ See if we are about to step over a virtual inlined call.\n bool step_without_resume = m_thread.DecrementCurrentInlinedDepth();\n if (step_without_resume)\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf (\"ThreadPlanStepInRange::WillResume: returning false, inline_depth: %d\",\n m_thread.GetCurrentInlinedDepth());\n SetStopInfo(StopInfo::CreateStopReasonToTrace(m_thread));\n \n \/\/ FIXME: Maybe it would be better to create a InlineStep stop reason, but then\n \/\/ the whole rest of the world would have to handle that stop reason.\n m_virtual_step = true;\n }\n return !step_without_resume;\n }\n else\n return ThreadPlan::WillResume(resume_state, current_plan);\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: client\/file_transfer_uploader.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"client\/file_transfer_uploader.h\"\r\n#include \"base\/logging.h\"\r\n\r\nnamespace aspia {\r\n\r\nnamespace fs = std::experimental::filesystem;\r\n\r\nFileTransferUploader::FileTransferUploader(\r\n std::shared_ptr<FileRequestSenderProxy> sender,\r\n Delegate* delegate)\r\n : FileTransfer(std::move(sender), delegate)\r\n{\r\n \/\/ Nothing\r\n}\r\n\r\nuint64_t FileTransferUploader::BuildTaskListForDirectoryContent(\r\n const FilePath& source_path,\r\n const FilePath& target_path)\r\n{\r\n std::error_code code;\r\n uint64_t size = 0;\r\n\r\n for (const auto& entry : fs::directory_iterator(source_path, code))\r\n {\r\n FilePath target_object_path;\r\n\r\n target_object_path.assign(target_path);\r\n target_object_path.append(entry.path().filename());\r\n\r\n if (fs::is_directory(entry.status()))\r\n {\r\n task_queue_.push(Task(entry.path(), target_object_path, true));\r\n\r\n size += BuildTaskListForDirectoryContent(entry.path(),\r\n target_object_path);\r\n }\r\n else\r\n {\r\n task_queue_.push(Task(entry.path(), target_object_path, false));\r\n\r\n size += fs::file_size(entry.path(), code);\r\n }\r\n }\r\n\r\n return size;\r\n}\r\n\r\nvoid FileTransferUploader::Start(const FilePath& source_path,\r\n const FilePath& target_path,\r\n const FileList& file_list)\r\n{\r\n uint64_t total_size = 0;\r\n std::error_code code;\r\n\r\n for (const auto& file : file_list)\r\n {\r\n FilePath source_object_path;\r\n\r\n source_object_path.assign(source_path);\r\n source_object_path.append(fs::u8path(file.name()));\r\n\r\n FilePath target_object_path;\r\n\r\n target_object_path.assign(target_path);\r\n target_object_path.append(fs::u8path(file.name()));\r\n\r\n if (file.is_directory())\r\n {\r\n task_queue_.push(Task(source_object_path, target_object_path, true));\r\n\r\n total_size += BuildTaskListForDirectoryContent(source_object_path,\r\n target_object_path);\r\n }\r\n else\r\n {\r\n task_queue_.push(Task(source_object_path, target_object_path, false));\r\n\r\n uintmax_t file_size = fs::file_size(source_object_path, code);\r\n\r\n if (file_size != static_cast<uintmax_t>(-1))\r\n total_size += file_size;\r\n }\r\n }\r\n\r\n delegate_->OnObjectSizeNotify(total_size);\r\n\r\n \/\/ Run first task.\r\n RunTask(task_queue_.front());\r\n}\r\n\r\nvoid FileTransferUploader::RunTask(const Task& task)\r\n{\r\n if (task.IsDirectory())\r\n {\r\n sender_->SendCreateDirectoryRequest(This(), task.TargetPath());\r\n }\r\n else\r\n {\r\n \/\/ TODO: Start file uploading.\r\n }\r\n}\r\n\r\nvoid FileTransferUploader::RunNextTask()\r\n{\r\n \/\/ Delete the task only after confirmation of its successful execution.\r\n if (!task_queue_.empty())\r\n task_queue_.pop();\r\n\r\n if (task_queue_.empty())\r\n {\r\n delegate_->OnTransferCompletionNotify();\r\n return;\r\n }\r\n\r\n const Task& task = task_queue_.front();\r\n\r\n delegate_->OnObjectTransferNotify(task.SourcePath(), task.TargetPath());\r\n\r\n \/\/ Run next task.\r\n RunTask(task);\r\n}\r\n\r\nvoid FileTransferUploader::OnDriveListRequestReply(\r\n std::unique_ptr<proto::DriveList> drive_list)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of drives\";\r\n}\r\n\r\nvoid FileTransferUploader::OnDriveListRequestFailure(\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnFileListRequestReply(\r\n const FilePath& path,\r\n std::unique_ptr<proto::FileList> file_list)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of file\";\r\n}\r\n\r\nvoid FileTransferUploader::OnFileListRequestFailure(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of files\";\r\n}\r\n\r\nvoid FileTransferUploader::OnDirectorySizeRequestReply(\r\n const FilePath& path,\r\n uint64_t size)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnDirectorySizeRequestFailure(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnCreateDirectoryRequestReply(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n RunNextTask();\r\n}\r\n\r\nvoid FileTransferUploader::OnRemoveRequestReply(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnRenameRequestReply(\r\n const FilePath& old_name,\r\n const FilePath& new_name,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<commit_msg>Added check of the returned value<commit_after>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: client\/file_transfer_uploader.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"client\/file_transfer_uploader.h\"\r\n#include \"base\/logging.h\"\r\n\r\nnamespace aspia {\r\n\r\nnamespace fs = std::experimental::filesystem;\r\n\r\nFileTransferUploader::FileTransferUploader(\r\n std::shared_ptr<FileRequestSenderProxy> sender,\r\n Delegate* delegate)\r\n : FileTransfer(std::move(sender), delegate)\r\n{\r\n \/\/ Nothing\r\n}\r\n\r\nuint64_t FileTransferUploader::BuildTaskListForDirectoryContent(\r\n const FilePath& source_path,\r\n const FilePath& target_path)\r\n{\r\n std::error_code code;\r\n uint64_t size = 0;\r\n\r\n for (const auto& entry : fs::directory_iterator(source_path, code))\r\n {\r\n FilePath target_object_path;\r\n\r\n target_object_path.assign(target_path);\r\n target_object_path.append(entry.path().filename());\r\n\r\n if (fs::is_directory(entry.status()))\r\n {\r\n task_queue_.push(Task(entry.path(), target_object_path, true));\r\n\r\n size += BuildTaskListForDirectoryContent(entry.path(),\r\n target_object_path);\r\n }\r\n else\r\n {\r\n task_queue_.push(Task(entry.path(), target_object_path, false));\r\n\r\n uintmax_t file_size = fs::file_size(entry.path(), code);\r\n\r\n if (file_size != static_cast<uintmax_t>(-1))\r\n size += file_size;\r\n }\r\n }\r\n\r\n return size;\r\n}\r\n\r\nvoid FileTransferUploader::Start(const FilePath& source_path,\r\n const FilePath& target_path,\r\n const FileList& file_list)\r\n{\r\n uint64_t total_size = 0;\r\n std::error_code code;\r\n\r\n for (const auto& file : file_list)\r\n {\r\n FilePath source_object_path;\r\n\r\n source_object_path.assign(source_path);\r\n source_object_path.append(fs::u8path(file.name()));\r\n\r\n FilePath target_object_path;\r\n\r\n target_object_path.assign(target_path);\r\n target_object_path.append(fs::u8path(file.name()));\r\n\r\n if (file.is_directory())\r\n {\r\n task_queue_.push(Task(source_object_path, target_object_path, true));\r\n\r\n total_size += BuildTaskListForDirectoryContent(source_object_path,\r\n target_object_path);\r\n }\r\n else\r\n {\r\n task_queue_.push(Task(source_object_path, target_object_path, false));\r\n\r\n uintmax_t file_size = fs::file_size(source_object_path, code);\r\n\r\n if (file_size != static_cast<uintmax_t>(-1))\r\n total_size += file_size;\r\n }\r\n }\r\n\r\n delegate_->OnObjectSizeNotify(total_size);\r\n\r\n \/\/ Run first task.\r\n RunTask(task_queue_.front());\r\n}\r\n\r\nvoid FileTransferUploader::RunTask(const Task& task)\r\n{\r\n if (task.IsDirectory())\r\n {\r\n sender_->SendCreateDirectoryRequest(This(), task.TargetPath());\r\n }\r\n else\r\n {\r\n \/\/ TODO: Start file uploading.\r\n }\r\n}\r\n\r\nvoid FileTransferUploader::RunNextTask()\r\n{\r\n \/\/ Delete the task only after confirmation of its successful execution.\r\n if (!task_queue_.empty())\r\n task_queue_.pop();\r\n\r\n if (task_queue_.empty())\r\n {\r\n delegate_->OnTransferCompletionNotify();\r\n return;\r\n }\r\n\r\n const Task& task = task_queue_.front();\r\n\r\n delegate_->OnObjectTransferNotify(task.SourcePath(), task.TargetPath());\r\n\r\n \/\/ Run next task.\r\n RunTask(task);\r\n}\r\n\r\nvoid FileTransferUploader::OnDriveListRequestReply(\r\n std::unique_ptr<proto::DriveList> drive_list)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of drives\";\r\n}\r\n\r\nvoid FileTransferUploader::OnDriveListRequestFailure(\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnFileListRequestReply(\r\n const FilePath& path,\r\n std::unique_ptr<proto::FileList> file_list)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of file\";\r\n}\r\n\r\nvoid FileTransferUploader::OnFileListRequestFailure(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n DLOG(FATAL) << \"Unexpectedly received a list of files\";\r\n}\r\n\r\nvoid FileTransferUploader::OnDirectorySizeRequestReply(\r\n const FilePath& path,\r\n uint64_t size)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnDirectorySizeRequestFailure(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnCreateDirectoryRequestReply(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n RunNextTask();\r\n}\r\n\r\nvoid FileTransferUploader::OnRemoveRequestReply(\r\n const FilePath& path,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid FileTransferUploader::OnRenameRequestReply(\r\n const FilePath& old_name,\r\n const FilePath& new_name,\r\n proto::RequestStatus status)\r\n{\r\n \/\/ TODO\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2006-2012, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NASA Vision Workbench is licensed under the Apache License,\n\/\/ Version 2.0 (the \"License\"); you may not use this file except in\n\/\/ compliance with the License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ __END_LICENSE__\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <vw\/FileIO\/DiskImageView.h>\n#include <vw\/Stereo\/DisparityMap.h>\n\nusing namespace vw;\nusing namespace std;\n\n\/\/ Average the rows in a given disparity image. Save them to disk as\n\/\/ two text files (x and y values), with as many entries as there\n\/\/ were columns in the disparity.\n\nint main( int argc, char *argv[] ){\n\n \/\/ TODO: Use Boost program options.\n\n \/\/ TODO: No need for outdx.txt and outdy.txt, just save with with same prefix.\n if (argc <= 3) {\n vw_out() << \"Usage: disp_avg disp.tif outdx.txt outdy.txt [row_start] [num_rows] [col_start] [num_cols]\\n\";\n return 1;\n }\n\n std::string in_file = argv[1], outx = argv[2], outy = argv[3];\n\n std::cout << \"Reading: \" << in_file << std::endl;\n DiskImageView < PixelMask<Vector2f> > D(in_file);\n\n int cols = D.cols(), rows = D.rows();\n std::cout << \"Number of cols and rows is \" << cols << ' ' << rows << std::endl;\n\n \/\/ Handle optional row ROI arguments.\n \/\/ - No col ROI since we want the entire column range.\n int row_start = 0;\n int row_stop = rows;\n int col_start = 0;\n int col_stop = cols;\n if (argc > 4) row_start = atoi(argv[4]);\n if (argc > 5) row_stop = row_start + atoi(argv[5]);\n if (argc > 6) col_start = atoi(argv[6]);\n if (argc > 7) col_stop = col_start + atoi(argv[7]);\n\n \/\/ TODO: Add a progress bar.\n vector<double> Dx(cols, 0), Dy(cols, 0); \/\/ Always full sized, even if crop is used.\n for (int col = col_start; col < col_stop; col++){\n if (col%100 == 0){\n std::cout << \"column \" << col << std::endl;\n }\n vector<double> px, py;\n for (int row = row_start; row < row_stop; row++){\n PixelMask<Vector2f> p = D(col, row);\n if (! is_valid(p)) continue;\n px.push_back(p.child()[0]);\n py.push_back(p.child()[1]);\n }\n std::sort(px.begin(), px.end());\n std::sort(py.begin(), py.end());\n int len = px.size();\n int num_valid = 0;\n Dx[col] = 0;\n Dy[col] = 0;\n for (int k = 0; k < len; k++){\n num_valid++;\n Dx[col] += px[k];\n Dy[col] += py[k];\n }\n\n if (num_valid > 0){\n Dx[col] \/= num_valid;\n Dy[col] \/= num_valid;\n }\n }\n\n \/\/ Write dx file\n ofstream dx(outx.c_str());\n dx.precision(16);\n std::cout << \"Writing: \" << outx << std::endl;\n dx << col_start << std::endl << col_stop << std::endl; \/\/ Column crop on header lines\n for (int col = 0; col < cols; col++) \n dx << Dx[col] << std::endl;\n\n \/\/ Write dy file\n ofstream dy(outy.c_str());\n dy.precision(16);\n std::cout << \"Writing: \" << outy << std::endl;\n dy << col_start << std::endl << col_stop << std::endl; \/\/ Column crop on header lines\n for (int col = 0; col < cols; col++) \n dy << Dy[col] << std::endl;\n\n return 0;\n}\n<commit_msg>disp_avg: Ability to filter outliers. Commented out by default<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2006-2012, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NASA Vision Workbench is licensed under the Apache License,\n\/\/ Version 2.0 (the \"License\"); you may not use this file except in\n\/\/ compliance with the License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ __END_LICENSE__\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <vw\/FileIO\/DiskImageView.h>\n#include <vw\/Stereo\/DisparityMap.h>\n\n#include <asp\/Core\/Macros.h>\n#include <asp\/Core\/Common.h>\n#include <vw\/Image\/Statistics.h>\n\nusing namespace vw;\n\n\/\/ Average the rows in a given disparity image. Save them to disk as\n\/\/ two text files (x and y values), with as many entries as there\n\/\/ were columns in the disparity.\n\nint main( int argc, char *argv[] ){\n\n \/\/ TODO: Use Boost program options.\n\n \/\/ TODO: No need for outdx.txt and outdy.txt, just save with with same prefix.\n if (argc <= 3) {\n vw_out() << \"Usage: disp_avg disp.tif outdx.txt outdy.txt [row_start] [num_rows] [col_start] [num_cols]\\n\";\n return 1;\n }\n\n std::string in_file = argv[1], outx = argv[2], outy = argv[3];\n\n std::cout << \"Reading: \" << in_file << std::endl;\n DiskImageView < PixelMask<Vector2f> > D(in_file);\n\n int cols = D.cols(), rows = D.rows();\n std::cout << \"Number of cols and rows is \" << cols << ' ' << rows << std::endl;\n\n \/\/ Handle optional row ROI arguments.\n \/\/ - No col ROI since we want the entire column range.\n int row_start = 0;\n int row_stop = rows;\n int col_start = 0;\n int col_stop = cols;\n if (argc > 4) row_start = atoi(argv[4]);\n if (argc > 5) row_stop = row_start + atoi(argv[5]);\n if (argc > 6) col_start = atoi(argv[6]);\n if (argc > 7) col_stop = col_start + atoi(argv[7]);\n\n TerminalProgressCallback disp_progress(\"asp\", \"\\tAveraging: \");\n double disp_progress_mult = 1.0\/double(std::max(col_stop - col_start, 1));\n\n std::vector<double> Dx(cols, 0), Dy(cols, 0); \/\/ Always full-sized, even if crop is used.\n for (int col = col_start; col < col_stop; col++){\n disp_progress.report_progress((col - col_start) * disp_progress_mult);\n\n std::vector<double> px, py;\n for (int row = row_start; row < row_stop; row++){\n PixelMask<Vector2f> p = D(col, row);\n if (! is_valid(p)) continue;\n px.push_back(p.child()[0]);\n py.push_back(p.child()[1]);\n }\n std::sort(px.begin(), px.end());\n std::sort(py.begin(), py.end());\n\n double pct_factor = 0.75;\n double outlier_factor = 3.0;\n double bx, ex;\n if (!vw::math::find_outlier_brackets(px, pct_factor, outlier_factor, bx, ex))\n continue;\n double by, ey;\n if (!vw::math::find_outlier_brackets(py, pct_factor, outlier_factor, by, ey))\n continue;\n \n int len = px.size();\n int num_valid = 0;\n Dx[col] = 0;\n Dy[col] = 0;\n for (int k = 0; k < len; k++){\n\n \/\/ TODO(oalexan1): This was tested only with WV3 pan to color disparity.\n \/\/ if (px[k] < bx || px[k] > ex || py[k] < by || py[k] > ey) continue;\n \n num_valid++;\n Dx[col] += px[k];\n Dy[col] += py[k];\n }\n\n if (num_valid > 0){\n Dx[col] \/= num_valid;\n Dy[col] \/= num_valid;\n }\n }\n\n disp_progress.report_finished();\n \n \/\/ Write dx file\n std::ofstream dx(outx.c_str());\n dx.precision(16);\n std::cout << \"Writing: \" << outx << std::endl;\n dx << col_start << std::endl << col_stop << std::endl; \/\/ Column crop on header lines\n for (int col = 0; col < cols; col++) \n dx << Dx[col] << std::endl;\n dx.close();\n \n \/\/ Write dy file\n std::ofstream dy(outy.c_str());\n dy.precision(16);\n std::cout << \"Writing: \" << outy << std::endl;\n dy << col_start << std::endl << col_stop << std::endl; \/\/ Column crop on header lines\n for (int col = 0; col < cols; col++) \n dy << Dy[col] << std::endl;\n dy.close();\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>sal_Bool->bool<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlwrap.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:04:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_XMLWRAP_HXX\n#define SC_XMLWRAP_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\nclass ScDocument;\nclass SfxMedium;\nclass ScMySharedData;\n\n#include <tools\/errcode.hxx>\n\nnamespace com { namespace sun { namespace star {\n namespace beans { struct PropertyValue; }\n namespace frame { class XModel; }\n namespace task { class XStatusIndicator; }\n namespace lang { class XMultiServiceFactory; }\n namespace uno { class XInterface; }\n namespace embed { class XStorage; }\n namespace xml {\n namespace sax { struct InputSource; } }\n} } }\n\nclass ScXMLImportWrapper\n{\n ScDocument& rDoc;\n SfxMedium* pMedium;\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;\n\n com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(\n com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);\n com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();\n\n sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,\n com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,\n com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,\n com::sun::star::xml::sax::InputSource& aParserInput,\n const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,\n com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,\n sal_Bool bMustBeSuccessfull);\n\n sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,\n com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,\n com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,\n com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,\n const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,\n const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,\n ScMySharedData*& pSharedData);\n\npublic:\n ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);\n BOOL Import(sal_Bool bStylesOnly, ErrCode& );\n BOOL Export(sal_Bool bStylesOnly);\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.15.700); FILE MERGED 2008\/04\/01 15:29:47 thb 1.15.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:13:36 rt 1.15.700.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlwrap.hxx,v $\n * $Revision: 1.16 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_XMLWRAP_HXX\n#define SC_XMLWRAP_HXX\n\n#include <tools\/solar.h>\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\nclass ScDocument;\nclass SfxMedium;\nclass ScMySharedData;\n\n#include <tools\/errcode.hxx>\n\nnamespace com { namespace sun { namespace star {\n namespace beans { struct PropertyValue; }\n namespace frame { class XModel; }\n namespace task { class XStatusIndicator; }\n namespace lang { class XMultiServiceFactory; }\n namespace uno { class XInterface; }\n namespace embed { class XStorage; }\n namespace xml {\n namespace sax { struct InputSource; } }\n} } }\n\nclass ScXMLImportWrapper\n{\n ScDocument& rDoc;\n SfxMedium* pMedium;\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;\n\n com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(\n com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);\n com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();\n\n sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,\n com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,\n com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,\n com::sun::star::xml::sax::InputSource& aParserInput,\n const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,\n com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,\n sal_Bool bMustBeSuccessfull);\n\n sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,\n com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,\n com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,\n com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,\n const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,\n const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,\n ScMySharedData*& pSharedData);\n\npublic:\n ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);\n BOOL Import(sal_Bool bStylesOnly, ErrCode& );\n BOOL Export(sal_Bool bStylesOnly);\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#ifdef __linux__\n#include <QDebug>\n#include \"LuminaOS.h\"\n#include <unistd.h>\n#include <stdio.h> \/\/ Needed for BUFSIZ\n\n\/\/can't read xbrightness settings - assume invalid until set\nstatic int screenbrightness = -1;\n\nQString LOS::OSName(){ return \"Slackware Linux\"; }\n\n\/\/OS-specific prefix(s)\n\/\/ NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in\nQString LOS::LuminaShare(){ return (L_SHAREDIR+\"\/lumina-desktop\/\"); } \/\/Install dir for Lumina share files\nQString LOS::AppPrefix(){ return \"\/usr\/\"; } \/\/Prefix for applications\nQString LOS::SysPrefix(){ return \"\/etc\/\"; } \/\/Prefix for system\n\n\/\/OS-specific application shortcuts (*.desktop files)\nQString LOS::ControlPanelShortcut(){ return \"\"; } \/\/system control panel\nQString LOS::AppStoreShortcut(){ return \"\"; } \/\/graphical app\/pkg manager\n\/\/OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )\nQStringList LOS::RSSFeeds(){ return QStringList(); } \n\n\/\/ ==== ExternalDevicePaths() ====\nQStringList LOS::ExternalDevicePaths(){\n \/\/Returns: QStringList[<type>::::<filesystem>::::<path>]\n \/\/Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]\n QStringList devs = LUtils::getCmdOutput(\"mount\");\n \/\/Now check the output\n for(int i=0; i<devs.length(); i++){\n if(devs[i].startsWith(\"\/dev\/\")){\n devs[i] = devs[i].simplified();\n QString type = devs[i].section(\" \",0,0);\n type.remove(\"\/dev\/\");\n \/\/Determine the type of hardware device based on the dev node\n if(type.startsWith(\"sd\") || type.startsWith(\"nvme\")){ type = \"HDRIVE\"; }\n else if(type.startsWith(\"sr\")){ type=\"DVD\"; }\n else if(type.contains(\"mapper\")){ type=\"LVM\"; }\n else{ type = \"UNKNOWN\"; }\n \/\/Now put the device in the proper output format\n devs[i] = type+\"::::\"+devs[i].section(\" \",4,4)+\"::::\"+devs[i].section(\" \",2,2);\n }else{\n \/\/invalid device - remove it from the list\n devs.removeAt(i);\n i--;\n }\n }\n return devs;\n}\n\n\/\/Read screen brightness information\nint LOS::ScreenBrightness(){\n \/\/Returns: Screen Brightness as a percentage (0-100, with -1 for errors)\n if(screenbrightness==-1){\n if(QFile::exists(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\")){\n int val = LUtils::readFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\").join(\"\").simplified().toInt();\n screenbrightness = val;\n }\n }\n return screenbrightness;\n\n}\n\n\/\/Set screen brightness\nvoid LOS::setScreenBrightness(int percent){\n \/\/ensure bounds\n if(percent<0){percent=0;}\n else if(percent>100){ percent=100; }\n \/\/ float pf = percent\/100.0; \/\/convert to a decimel\n \/\/Run the command\n QString cmd = \"xbacklight -set %1\";\n \/\/ cmd = cmd.arg( QString::number( int(65535*pf) ) );\n cmd = cmd.arg( QString::number( percent ) );\n int ret = LUtils::runCmd(cmd);\n \/\/Save the result for later\n if(ret!=0){ screenbrightness = -1; }\n else{ screenbrightness = percent; }\n LUtils::writeFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\", QStringList() << QString::number(screenbrightness), true);\n\n}\n\n\/\/Read the current volume\nint LOS::audioVolume(){ \/\/Returns: audio volume as a percentage (0-100, with -1 for errors)\nQString info = LUtils::getCmdOutput(\"amixer get Master\").join(\"\").simplified();;\n int out = -1;\n int start_position, end_position;\n QString current_volume;\n if(!info.isEmpty()){\n start_position = info.indexOf(\"[\");\n start_position++;\n end_position = info.indexOf(\"%\");\n current_volume = info.mid(start_position, end_position - start_position);\n out = current_volume.toInt();\n }\n return out;\n\n\n}\n\n\/\/Set the current volume\nvoid LOS::setAudioVolume(int percent){\n if(percent<0){percent=0;}\n else if(percent>100){percent=100;}\n QString info = \"amixer set Master \" + QString::number(percent) + \"%\";\n \/\/Run Command\n LUtils::runCmd(info);\n}\n\n\/\/Change the current volume a set amount (+ or -)\nvoid LOS::changeAudioVolume(int percentdiff){\n int old_volume = audioVolume();\n int new_volume = old_volume + percentdiff;\n if (new_volume < 0)\n new_volume = 0;\n if (new_volume > 100)\n new_volume = 100;\n qDebug() << \"Setting new volume to: \" << new_volume;\n setAudioVolume(new_volume);\n}\n\n\/\/Check if a graphical audio mixer is installed\nbool LOS::hasMixerUtility(){\n return QFile::exists(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Launch the graphical audio mixer utility\nvoid LOS::startMixerUtility(){\n QProcess::startDetached(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Check for user system permission (shutdown\/restart)\nbool LOS::userHasShutdownAccess(){\n return true; \/\/not implemented yet\n}\n\n\/\/Check for whether the system is safe to power off (no updates being perfomed)\nbool LOS::systemPerformingUpdates(){\n return false; \/\/Not implemented yet\n}\n\n\/\/Return the details of any updates which are waiting to apply on shutdown\nQString LOS::systemPendingUpdates(){\n return \"\";\n}\n\n\/\/System Shutdown\nvoid LOS::systemShutdown(bool){ \/\/start poweroff sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply=literal --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.Stop\");\n}\n\n\/\/System Restart\nvoid LOS::systemRestart(bool){ \/\/start reboot sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply=literal --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.Restart\");\n}\n\n\/\/Check for suspend support\nbool LOS::systemCanSuspend(){\n return false;\n}\n\n\/\/Put the system into the suspend state\nvoid LOS::systemSuspend(){\n\n}\n\n\/\/Battery Availability\nbool LOS::hasBattery(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool no_battery = my_status.contains(\"No support\");\n if (no_battery) return false;\n return true;\n}\n\n\/\/Battery Charge Level\nint LOS::batteryCharge(){ \/\/Returns: percent charge (0-100), anything outside that range is counted as an error\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n int my_start = my_status.indexOf(\"%\");\n \/\/ get the number right before the % sign\n int my_end = my_start;\n my_start--;\n while ( (my_status[my_start] != ' ') && (my_start > 0) )\n my_start--;\n my_start++;\n int my_charge = my_status.mid(my_start, my_end - my_start).toInt();\n if ( (my_charge < 0) || (my_charge > 100) ) return -1;\n return my_charge;\n}\n\n\/\/Battery Charging State\n\/\/ Many possible values are returned if the laptop is plugged in\n\/\/ these include \"Unknown, Full and No support.\n\/\/ However, it seems just one status is returned when running\n\/\/ on battery and that is \"Discharging\". So if the value we get\n\/\/ is NOT Discharging then we assume the battery is charging.\nbool LOS::batteryIsCharging(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool discharging = my_status.contains(\"Discharging\");\n if (discharging) return false;\n return true;\n}\n\n\/\/Battery Time Remaining\nint LOS::batterySecondsLeft(){ \/\/Returns: estimated number of seconds remaining\n return 0; \/\/not implemented yet for Linux\n}\n\n\/\/File Checksums\nQStringList LOS::Checksums(QStringList filepaths){ \/\/Return: checksum of the input file\n QStringList info = LUtils::getCmdOutput(\"md5sum \\\"\"+filepaths.join(\"\\\" \\\"\")+\"\\\"\");\n for(int i=0; i<info.length(); i++){\n \/\/ first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput\n if( info[i].startsWith(\"md5sum:\") || info[i].isEmpty()){ info.removeAt(i); i--; }\n else{\n \/\/Strip out the extra information\n info[i] = info[i].section(\" \",0,0);\n }\n }\n return info;\n}\n\n\/\/file system capacity\nQString LOS::FileSystemCapacity(QString dir) { \/\/Return: percentage capacity as give by the df command\n QStringList mountInfo = LUtils::getCmdOutput(\"df \\\"\" + dir+\"\\\"\");\n QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;\n \/\/we take the 5th word on the 2 line\n QString capacity = mountInfo[1].section(\" \",4,4, skipEmpty) + \" used\";\n return capacity;\n}\n\nQStringList LOS::CPUTemperatures(){ \/\/Returns: List containing the temperature of any CPU's (\"50C\" for example)\n return QStringList(); \/\/not implemented yet\n}\n\nint LOS::CPUUsagePercent(){ \/\/Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)\n return -1; \/\/not implemented yet\n}\n\nint LOS::MemoryUsagePercent(){\n return -1; \/\/not implemented yet\n}\n\nQStringList LOS::DiskUsage(){ \/\/Returns: List of current read\/write stats for each device\n return QStringList(); \/\/not implemented yet\n}\n\n#endif\n<commit_msg>OS: Support suspend on Slackware<commit_after>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#ifdef __linux__\n#include <QDebug>\n#include \"LuminaOS.h\"\n#include <unistd.h>\n#include <stdio.h> \/\/ Needed for BUFSIZ\n\n\/\/can't read xbrightness settings - assume invalid until set\nstatic int screenbrightness = -1;\n\nQString LOS::OSName(){ return \"Slackware Linux\"; }\n\n\/\/OS-specific prefix(s)\n\/\/ NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in\nQString LOS::LuminaShare(){ return (L_SHAREDIR+\"\/lumina-desktop\/\"); } \/\/Install dir for Lumina share files\nQString LOS::AppPrefix(){ return \"\/usr\/\"; } \/\/Prefix for applications\nQString LOS::SysPrefix(){ return \"\/etc\/\"; } \/\/Prefix for system\n\n\/\/OS-specific application shortcuts (*.desktop files)\nQString LOS::ControlPanelShortcut(){ return \"\"; } \/\/system control panel\nQString LOS::AppStoreShortcut(){ return \"\"; } \/\/graphical app\/pkg manager\n\/\/OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )\nQStringList LOS::RSSFeeds(){ return QStringList(); } \n\n\/\/ ==== ExternalDevicePaths() ====\nQStringList LOS::ExternalDevicePaths(){\n \/\/Returns: QStringList[<type>::::<filesystem>::::<path>]\n \/\/Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]\n QStringList devs = LUtils::getCmdOutput(\"mount\");\n \/\/Now check the output\n for(int i=0; i<devs.length(); i++){\n if(devs[i].startsWith(\"\/dev\/\")){\n devs[i] = devs[i].simplified();\n QString type = devs[i].section(\" \",0,0);\n type.remove(\"\/dev\/\");\n \/\/Determine the type of hardware device based on the dev node\n if(type.startsWith(\"sd\") || type.startsWith(\"nvme\")){ type = \"HDRIVE\"; }\n else if(type.startsWith(\"sr\")){ type=\"DVD\"; }\n else if(type.contains(\"mapper\")){ type=\"LVM\"; }\n else{ type = \"UNKNOWN\"; }\n \/\/Now put the device in the proper output format\n devs[i] = type+\"::::\"+devs[i].section(\" \",4,4)+\"::::\"+devs[i].section(\" \",2,2);\n }else{\n \/\/invalid device - remove it from the list\n devs.removeAt(i);\n i--;\n }\n }\n return devs;\n}\n\n\/\/Read screen brightness information\nint LOS::ScreenBrightness(){\n \/\/Returns: Screen Brightness as a percentage (0-100, with -1 for errors)\n if(screenbrightness==-1){\n if(QFile::exists(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\")){\n int val = LUtils::readFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\").join(\"\").simplified().toInt();\n screenbrightness = val;\n }\n }\n return screenbrightness;\n\n}\n\n\/\/Set screen brightness\nvoid LOS::setScreenBrightness(int percent){\n \/\/ensure bounds\n if(percent<0){percent=0;}\n else if(percent>100){ percent=100; }\n \/\/ float pf = percent\/100.0; \/\/convert to a decimel\n \/\/Run the command\n QString cmd = \"xbacklight -set %1\";\n \/\/ cmd = cmd.arg( QString::number( int(65535*pf) ) );\n cmd = cmd.arg( QString::number( percent ) );\n int ret = LUtils::runCmd(cmd);\n \/\/Save the result for later\n if(ret!=0){ screenbrightness = -1; }\n else{ screenbrightness = percent; }\n LUtils::writeFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\", QStringList() << QString::number(screenbrightness), true);\n\n}\n\n\/\/Read the current volume\nint LOS::audioVolume(){ \/\/Returns: audio volume as a percentage (0-100, with -1 for errors)\nQString info = LUtils::getCmdOutput(\"amixer get Master\").join(\"\").simplified();;\n int out = -1;\n int start_position, end_position;\n QString current_volume;\n if(!info.isEmpty()){\n start_position = info.indexOf(\"[\");\n start_position++;\n end_position = info.indexOf(\"%\");\n current_volume = info.mid(start_position, end_position - start_position);\n out = current_volume.toInt();\n }\n return out;\n\n\n}\n\n\/\/Set the current volume\nvoid LOS::setAudioVolume(int percent){\n if(percent<0){percent=0;}\n else if(percent>100){percent=100;}\n QString info = \"amixer set Master \" + QString::number(percent) + \"%\";\n \/\/Run Command\n LUtils::runCmd(info);\n}\n\n\/\/Change the current volume a set amount (+ or -)\nvoid LOS::changeAudioVolume(int percentdiff){\n int old_volume = audioVolume();\n int new_volume = old_volume + percentdiff;\n if (new_volume < 0)\n new_volume = 0;\n if (new_volume > 100)\n new_volume = 100;\n qDebug() << \"Setting new volume to: \" << new_volume;\n setAudioVolume(new_volume);\n}\n\n\/\/Check if a graphical audio mixer is installed\nbool LOS::hasMixerUtility(){\n return QFile::exists(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Launch the graphical audio mixer utility\nvoid LOS::startMixerUtility(){\n QProcess::startDetached(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Check for user system permission (shutdown\/restart)\nbool LOS::userHasShutdownAccess(){\n return true; \/\/not implemented yet\n}\n\n\/\/Check for whether the system is safe to power off (no updates being perfomed)\nbool LOS::systemPerformingUpdates(){\n return false; \/\/Not implemented yet\n}\n\n\/\/Return the details of any updates which are waiting to apply on shutdown\nQString LOS::systemPendingUpdates(){\n return \"\";\n}\n\n\/\/System Shutdown\nvoid LOS::systemShutdown(bool){ \/\/start poweroff sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply=literal --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.Stop\");\n}\n\n\/\/System Restart\nvoid LOS::systemRestart(bool){ \/\/start reboot sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply=literal --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.Restart\");\n}\n\n\/\/Check for suspend support\nbool LOS::systemCanSuspend(){\n return true;\n}\n\n\/\/Put the system into the suspend state\nvoid LOS::systemSuspend(){\n QProcess::startDetached(\"dbus-send --system --print-reply=literal --dest=org.freedesktop.UPower \/org\/freedesktop\/UPower org.freedesktop.UPower.Suspend\");\n}\n\n\/\/Battery Availability\nbool LOS::hasBattery(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool no_battery = my_status.contains(\"No support\");\n if (no_battery) return false;\n return true;\n}\n\n\/\/Battery Charge Level\nint LOS::batteryCharge(){ \/\/Returns: percent charge (0-100), anything outside that range is counted as an error\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n int my_start = my_status.indexOf(\"%\");\n \/\/ get the number right before the % sign\n int my_end = my_start;\n my_start--;\n while ( (my_status[my_start] != ' ') && (my_start > 0) )\n my_start--;\n my_start++;\n int my_charge = my_status.mid(my_start, my_end - my_start).toInt();\n if ( (my_charge < 0) || (my_charge > 100) ) return -1;\n return my_charge;\n}\n\n\/\/Battery Charging State\n\/\/ Many possible values are returned if the laptop is plugged in\n\/\/ these include \"Unknown, Full and No support.\n\/\/ However, it seems just one status is returned when running\n\/\/ on battery and that is \"Discharging\". So if the value we get\n\/\/ is NOT Discharging then we assume the battery is charging.\nbool LOS::batteryIsCharging(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool discharging = my_status.contains(\"Discharging\");\n if (discharging) return false;\n return true;\n}\n\n\/\/Battery Time Remaining\nint LOS::batterySecondsLeft(){ \/\/Returns: estimated number of seconds remaining\n return 0; \/\/not implemented yet for Linux\n}\n\n\/\/File Checksums\nQStringList LOS::Checksums(QStringList filepaths){ \/\/Return: checksum of the input file\n QStringList info = LUtils::getCmdOutput(\"md5sum \\\"\"+filepaths.join(\"\\\" \\\"\")+\"\\\"\");\n for(int i=0; i<info.length(); i++){\n \/\/ first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput\n if( info[i].startsWith(\"md5sum:\") || info[i].isEmpty()){ info.removeAt(i); i--; }\n else{\n \/\/Strip out the extra information\n info[i] = info[i].section(\" \",0,0);\n }\n }\n return info;\n}\n\n\/\/file system capacity\nQString LOS::FileSystemCapacity(QString dir) { \/\/Return: percentage capacity as give by the df command\n QStringList mountInfo = LUtils::getCmdOutput(\"df \\\"\" + dir+\"\\\"\");\n QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;\n \/\/we take the 5th word on the 2 line\n QString capacity = mountInfo[1].section(\" \",4,4, skipEmpty) + \" used\";\n return capacity;\n}\n\nQStringList LOS::CPUTemperatures(){ \/\/Returns: List containing the temperature of any CPU's (\"50C\" for example)\n return QStringList(); \/\/not implemented yet\n}\n\nint LOS::CPUUsagePercent(){ \/\/Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)\n return -1; \/\/not implemented yet\n}\n\nint LOS::MemoryUsagePercent(){\n return -1; \/\/not implemented yet\n}\n\nQStringList LOS::DiskUsage(){ \/\/Returns: List of current read\/write stats for each device\n return QStringList(); \/\/not implemented yet\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"fcp\/client\/engine\/caching_error_reporter.h\"\n\n#include <string>\n\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"fcp\/testing\/testing.h\"\n#include \"tensorflow\/lite\/core\/api\/error_reporter.h\"\n\nnamespace fcp {\nnamespace client {\nnamespace engine {\nnamespace {\n\nusing ::testing::IsEmpty;\n\nTEST(CachingErrorReporterTest, CachingMultiple) {\n CachingErrorReporter reporter;\n std::string first_error = \"Op a is not found.\";\n TF_LITE_REPORT_ERROR(&reporter, \"%s%d\", first_error.c_str(), 1);\n std::string second_error = \"Op b is not found.\";\n TF_LITE_REPORT_ERROR(&reporter, \"%s%d\", second_error.c_str(), 2);\n EXPECT_THAT(reporter.GetFirstErrorMessage(), absl::StrCat(first_error, \"1\"));\n}\n\nTEST(CachingErrorReporterTest, Empty) {\n CachingErrorReporter reporter;\n EXPECT_THAT(reporter.GetFirstErrorMessage(), IsEmpty());\n}\n\n} \/\/ anonymous namespace\n} \/\/ namespace engine\n} \/\/ namespace client\n} \/\/ namespace fcp\n<commit_msg>TFLite Micro introduced the macro TF_LITE_REPORT_ERROR as an attempt to wrap the error logging functionality to check for TF_LITE_STRIP_ERROR_STRINGS (an ifdef var to ignore calls to message logging API).<commit_after>\/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"fcp\/client\/engine\/caching_error_reporter.h\"\n\n#include <string>\n\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"fcp\/testing\/testing.h\"\n#include \"tensorflow\/lite\/core\/api\/error_reporter.h\"\n\nnamespace fcp {\nnamespace client {\nnamespace engine {\nnamespace {\n\nusing ::testing::IsEmpty;\n\nTEST(CachingErrorReporterTest, CachingMultiple) {\n CachingErrorReporter reporter;\n std::string first_error = \"Op a is not found.\";\n static_cast<tflite::ErrorReporter*>(&reporter)->Report(\n \"%s%d\", first_error.c_str(), 1);\n std::string second_error = \"Op b is not found.\";\n static_cast<tflite::ErrorReporter*>(&reporter)->Report(\n \"%s%d\", second_error.c_str(), 2);\n EXPECT_THAT(reporter.GetFirstErrorMessage(), absl::StrCat(first_error, \"1\"));\n}\n\nTEST(CachingErrorReporterTest, Empty) {\n CachingErrorReporter reporter;\n EXPECT_THAT(reporter.GetFirstErrorMessage(), IsEmpty());\n}\n\n} \/\/ anonymous namespace\n} \/\/ namespace engine\n} \/\/ namespace client\n} \/\/ namespace fcp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"fcp\/client\/http\/curl\/curl_http_request_handle.h\"\n\n#include <memory>\n#include <optional>\n#include <string>\n#include <utility>\n\n#include \"absl\/strings\/match.h\"\n#include \"curl\/curl.h\"\n#include \"fcp\/base\/monitoring.h\"\n#include \"fcp\/client\/http\/curl\/curl_api.h\"\n#include \"fcp\/client\/http\/curl\/curl_header_parser.h\"\n#include \"fcp\/client\/http\/curl\/curl_http_response.h\"\n#include \"fcp\/client\/http\/http_client_util.h\"\n\nnamespace fcp::client::http::curl {\nnamespace {\n\/\/ A type check for the macro.\ninline CURLcode AsCode(CURLcode code) { return code; }\n\/**\n * Macro which allows to check for a status code and return from the\n * current method if not OK. Example:\n *\n * Status DoSomething() {\n * CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(...));\n * }\n *\/\n#define CURL_RETURN_IF_ERROR(expr) \\\n do { \\\n CURLcode __code = AsCode(expr); \\\n if (__code != CURLE_OK) { \\\n FCP_LOG(ERROR) << \"Easy handle failed with \" \\\n << CurlEasyHandle::StrError(__code); \\\n return (__code); \\\n } \\\n } while (false)\n} \/\/ namespace\n\nsize_t CurlHttpRequestHandle::HeaderCallback(char* buffer, size_t size,\n size_t n_items, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n std::string str_header(static_cast<char*>(buffer), size * n_items);\n\n self->header_parser_.ParseHeader(str_header);\n if (!self->header_parser_.IsLastHeader()) {\n return size * n_items;\n }\n\n self->response_ =\n std::make_unique<CurlHttpResponse>(self->header_parser_.GetStatusCode(),\n self->header_parser_.GetHeaderList());\n\n FCP_CHECK(self->callback_ != nullptr);\n absl::Status status =\n self->callback_->OnResponseStarted(*self->request_, *self->response_);\n\n if (!status.ok()) {\n FCP_LOG(ERROR) << \"Called OnResponseStarted. Received status: \" << status;\n self->callback_->OnResponseError(*self->request_, status);\n }\n\n return size * n_items;\n}\n\nsize_t CurlHttpRequestHandle::DownloadCallback(void* body, size_t size,\n size_t nmemb, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n absl::string_view str_body(static_cast<char*>(body), size * nmemb);\n\n absl::Status status = self->callback_->OnResponseBody(\n *self->request_, *self->response_, str_body);\n\n if (!status.ok()) {\n FCP_LOG(ERROR) << \"Called OnResponseBody. Received status: \" << status;\n self->callback_->OnResponseBodyError(*self->request_, *self->response_,\n status);\n }\n\n return size * nmemb;\n}\n\nsize_t CurlHttpRequestHandle::UploadCallback(char* buffer, size_t size,\n size_t num, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n size_t buffer_size = size * num;\n\n absl::StatusOr<int64_t> read_size =\n self->request_->ReadBody(buffer, buffer_size);\n if (read_size.ok()) {\n return read_size.value();\n } else if (read_size.status().code() == absl::StatusCode::kOutOfRange) {\n return 0;\n }\n return CURL_READFUNC_ABORT;\n}\n\nsize_t CurlHttpRequestHandle::ProgressCallback(void* user_data,\n curl_off_t dltotal,\n curl_off_t dlnow,\n curl_off_t ultotal,\n curl_off_t ulnow) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n absl::MutexLock lock(&self->mutex_);\n \/\/ Abort is any number except zero.\n return (self->is_cancelled_) ? 1 : 0;\n}\n\nCurlHttpRequestHandle::CurlHttpRequestHandle(\n std::unique_ptr<HttpRequest> request,\n std::unique_ptr<CurlEasyHandle> easy_handle,\n const std::string& test_cert_path)\n : request_(std::move(request)),\n response_(nullptr),\n easy_handle_(std::move(easy_handle)),\n callback_(nullptr),\n is_being_performed_(false),\n is_completed_(false),\n is_cancelled_(false),\n header_list_(nullptr) {\n FCP_CHECK(request_ != nullptr);\n FCP_CHECK(easy_handle_ != nullptr);\n\n CURLcode code = InitializeConnection(test_cert_path);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"easy_handle initialization failed with code \"\n << CurlEasyHandle::StrError(code);\n FCP_LOG(ERROR) << error_buffer_;\n callback_->OnResponseError(*request_, absl::InternalError(error_buffer_));\n return;\n }\n}\n\nCurlHttpRequestHandle::~CurlHttpRequestHandle() {\n curl_slist_free_all(header_list_);\n}\n\nvoid CurlHttpRequestHandle::Cancel() {\n absl::MutexLock lock(&mutex_);\n\n if (callback_ == nullptr || is_cancelled_ || is_completed_) {\n return;\n }\n if (response_ != nullptr) {\n callback_->OnResponseBodyError(*request_, *response_,\n absl::CancelledError());\n } else {\n callback_->OnResponseError(*request_, absl::CancelledError());\n }\n is_cancelled_ = true;\n}\n\nvoid CurlHttpRequestHandle::MarkAsCompleted() {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(callback_ != nullptr);\n if (!is_cancelled_ && !is_completed_) {\n FCP_CHECK(response_ != nullptr);\n callback_->OnResponseCompleted(*request_, *response_);\n }\n is_completed_ = true;\n}\n\nabsl::Status CurlHttpRequestHandle::AddToMulti(CurlMultiHandle* multi_handle,\n HttpRequestCallback* callback) {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(callback != nullptr);\n FCP_CHECK(multi_handle != nullptr);\n\n if (is_cancelled_) {\n callback->OnResponseError(*request_, absl::CancelledError());\n return absl::CancelledError();\n } else if (is_being_performed_ || is_completed_) {\n return absl::ResourceExhaustedError(\n \"The handle was previously passed to another PerformRequests call.\");\n }\n\n is_being_performed_ = true;\n callback_ = callback;\n\n CURLMcode code = multi_handle->AddEasyHandle(easy_handle_.get());\n if (code != CURLM_OK) {\n FCP_LOG(ERROR) << \"AddEasyHandle failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n callback_->OnResponseError(*request_, absl::InternalError(error_buffer_));\n return absl::InternalError(error_buffer_);\n }\n\n return absl::OkStatus();\n}\n\nvoid CurlHttpRequestHandle::RemoveFromMulti(CurlMultiHandle* multi_handle) {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(multi_handle != nullptr);\n CURLMcode code = multi_handle->RemoveEasyHandle(easy_handle_.get());\n if (code != CURLM_OK) {\n FCP_LOG(ERROR) << \"RemoveEasyHandle failed with code \"\n << CurlMultiHandle::StrError(code);\n FCP_LOG(ERROR) << error_buffer_;\n }\n}\n\nHttpRequestHandle::SentReceivedBytes\nCurlHttpRequestHandle::TotalSentReceivedBytes() const {\n absl::MutexLock lock(&mutex_);\n curl_off_t total_sent_bytes = 0;\n CURLcode code =\n easy_handle_->GetInfo(CURLINFO_SIZE_UPLOAD_T, &total_sent_bytes);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"TotalSentBytes failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n }\n curl_off_t total_received_bytes = 0;\n code = easy_handle_->GetInfo(CURLINFO_SIZE_DOWNLOAD_T, &total_received_bytes);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"TotalReceivedBytes failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n }\n return {.sent_bytes = total_sent_bytes,\n .received_bytes = total_received_bytes};\n}\n\nCURLcode CurlHttpRequestHandle::InitializeConnection(\n const std::string& test_cert_path) {\n error_buffer_[0] = 0;\n \/\/ Needed to read an error message.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ERRORBUFFER, error_buffer_));\n\n \/\/ Skip all signal handling because is not thread-safe.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOSIGNAL, 1L));\n\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_URL, std::string(request_->uri())));\n\n \/\/ Forces curl to follow redirects.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_FOLLOWLOCATION, 1L));\n\n \/\/ Suppresses headers added by a proxy.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L));\n\n \/\/ Force curl to verify the ssl connection.\n CURL_RETURN_IF_ERROR(\n test_cert_path.empty()\n ? easy_handle_->SetOpt(CURLOPT_CAINFO, nullptr)\n : easy_handle_->SetOpt(CURLOPT_CAINFO, test_cert_path));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_SSL_VERIFYPEER, 2L));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_SSL_VERIFYHOST, 1L));\n\n \/\/ Force curl to never timeout.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_TIMEOUT_MS,\n std::numeric_limits<int>::max()));\n\n \/\/ Called when a response header received.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_HEADERFUNCTION, &CurlHttpRequestHandle::HeaderCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HEADERDATA, this));\n\n \/\/ Called when a response body received.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_WRITEFUNCTION, &CurlHttpRequestHandle::DownloadCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_WRITEDATA, this));\n\n \/\/ Called to send a request body\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_READFUNCTION, &CurlHttpRequestHandle::UploadCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_READDATA, this));\n\n \/\/ Called periodically. We use it to check whether the request is cancelled.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_XFERINFOFUNCTION, &CurlHttpRequestHandle::ProgressCallback));\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_XFERINFODATA, this));\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOPROGRESS, 0L));\n\n \/\/ Private storage. Used by a multi-handle.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_PRIVATE, this));\n\n switch (request_->method()) {\n case HttpRequest::Method::kGet:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HTTPGET, 1L));\n break;\n case HttpRequest::Method::kHead:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOBODY, 1L));\n break;\n case HttpRequest::Method::kPost:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_POST, 1L));\n \/\/ Forces curl to use the callback.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_POSTFIELDS, nullptr));\n break;\n case HttpRequest::Method::kPut:\n case HttpRequest::Method::kPatch:\n case HttpRequest::Method::kDelete:\n \/\/ TODO(team): Implement the requests when they are needed\n FCP_LOG(ERROR) << \"Unsupported request type\";\n return CURLE_UNSUPPORTED_PROTOCOL;\n }\n\n return InitializeHeaders(request_->extra_headers());\n}\n\nCURLcode CurlHttpRequestHandle::InitializeHeaders(\n const HeaderList& extra_headers) {\n \/\/ If no \"Accept-Encoding\" request header is explicitly specified\n \/\/ advertise an \"Accept-Encoding: gzip\" else leave decoded.\n std::optional<std::string> accept_encoding =\n FindHeader(request_->extra_headers(), kAcceptEncodingHdr);\n if (!accept_encoding.has_value()) {\n \/\/ Libcurl is responsible for the encoding.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ACCEPT_ENCODING, kGzipEncodingHdrValue));\n header_parser_.UseCurlEncoding();\n } else {\n \/\/ The caller is responsible for the encoding.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ACCEPT_ENCODING, nullptr));\n }\n\n for (auto& [key, value] : extra_headers) {\n if (absl::EqualsIgnoreCase(key, kAcceptEncodingHdr)) {\n continue;\n } else if (absl::EqualsIgnoreCase(key, kContentLengthHdr)) {\n \/\/ For post less than 2GB\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_POSTFIELDSIZE, std::stol(value)));\n } else {\n curl_slist* tmp = curl_slist_append(\n header_list_, absl::StrCat(key, \": \", value).c_str());\n FCP_CHECK(tmp != nullptr);\n header_list_ = tmp;\n }\n }\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HTTPHEADER, header_list_));\n return CURLE_OK;\n}\n} \/\/ namespace fcp::client::http::curl\n<commit_msg>Return an error when response_ is nullptr instead of crashing. This happens when server is inaccessible.<commit_after>\/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"fcp\/client\/http\/curl\/curl_http_request_handle.h\"\n\n#include <memory>\n#include <optional>\n#include <string>\n#include <utility>\n\n#include \"absl\/strings\/match.h\"\n#include \"curl\/curl.h\"\n#include \"fcp\/base\/monitoring.h\"\n#include \"fcp\/client\/http\/curl\/curl_api.h\"\n#include \"fcp\/client\/http\/curl\/curl_header_parser.h\"\n#include \"fcp\/client\/http\/curl\/curl_http_response.h\"\n#include \"fcp\/client\/http\/http_client_util.h\"\n\nnamespace fcp::client::http::curl {\nnamespace {\n\/\/ A type check for the macro.\ninline CURLcode AsCode(CURLcode code) { return code; }\n\/**\n * Macro which allows to check for a status code and return from the\n * current method if not OK. Example:\n *\n * Status DoSomething() {\n * CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(...));\n * }\n *\/\n#define CURL_RETURN_IF_ERROR(expr) \\\n do { \\\n CURLcode __code = AsCode(expr); \\\n if (__code != CURLE_OK) { \\\n FCP_LOG(ERROR) << \"Easy handle failed with \" \\\n << CurlEasyHandle::StrError(__code); \\\n return (__code); \\\n } \\\n } while (false)\n} \/\/ namespace\n\nsize_t CurlHttpRequestHandle::HeaderCallback(char* buffer, size_t size,\n size_t n_items, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n std::string str_header(static_cast<char*>(buffer), size * n_items);\n\n self->header_parser_.ParseHeader(str_header);\n if (!self->header_parser_.IsLastHeader()) {\n return size * n_items;\n }\n\n self->response_ =\n std::make_unique<CurlHttpResponse>(self->header_parser_.GetStatusCode(),\n self->header_parser_.GetHeaderList());\n\n FCP_CHECK(self->callback_ != nullptr);\n absl::Status status =\n self->callback_->OnResponseStarted(*self->request_, *self->response_);\n\n if (!status.ok()) {\n FCP_LOG(ERROR) << \"Called OnResponseStarted. Received status: \" << status;\n self->callback_->OnResponseError(*self->request_, status);\n }\n\n return size * n_items;\n}\n\nsize_t CurlHttpRequestHandle::DownloadCallback(void* body, size_t size,\n size_t nmemb, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n absl::string_view str_body(static_cast<char*>(body), size * nmemb);\n\n absl::Status status = self->callback_->OnResponseBody(\n *self->request_, *self->response_, str_body);\n\n if (!status.ok()) {\n FCP_LOG(ERROR) << \"Called OnResponseBody. Received status: \" << status;\n self->callback_->OnResponseBodyError(*self->request_, *self->response_,\n status);\n }\n\n return size * nmemb;\n}\n\nsize_t CurlHttpRequestHandle::UploadCallback(char* buffer, size_t size,\n size_t num, void* user_data) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n size_t buffer_size = size * num;\n\n absl::StatusOr<int64_t> read_size =\n self->request_->ReadBody(buffer, buffer_size);\n if (read_size.ok()) {\n return read_size.value();\n } else if (read_size.status().code() == absl::StatusCode::kOutOfRange) {\n return 0;\n }\n return CURL_READFUNC_ABORT;\n}\n\nsize_t CurlHttpRequestHandle::ProgressCallback(void* user_data,\n curl_off_t dltotal,\n curl_off_t dlnow,\n curl_off_t ultotal,\n curl_off_t ulnow) {\n auto self = static_cast<CurlHttpRequestHandle*>(user_data);\n absl::MutexLock lock(&self->mutex_);\n \/\/ Abort is any number except zero.\n return (self->is_cancelled_) ? 1 : 0;\n}\n\nCurlHttpRequestHandle::CurlHttpRequestHandle(\n std::unique_ptr<HttpRequest> request,\n std::unique_ptr<CurlEasyHandle> easy_handle,\n const std::string& test_cert_path)\n : request_(std::move(request)),\n response_(nullptr),\n easy_handle_(std::move(easy_handle)),\n callback_(nullptr),\n is_being_performed_(false),\n is_completed_(false),\n is_cancelled_(false),\n header_list_(nullptr) {\n FCP_CHECK(request_ != nullptr);\n FCP_CHECK(easy_handle_ != nullptr);\n\n CURLcode code = InitializeConnection(test_cert_path);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"easy_handle initialization failed with code \"\n << CurlEasyHandle::StrError(code);\n FCP_LOG(ERROR) << error_buffer_;\n callback_->OnResponseError(*request_, absl::InternalError(error_buffer_));\n return;\n }\n}\n\nCurlHttpRequestHandle::~CurlHttpRequestHandle() {\n curl_slist_free_all(header_list_);\n}\n\nvoid CurlHttpRequestHandle::Cancel() {\n absl::MutexLock lock(&mutex_);\n\n if (callback_ == nullptr || is_cancelled_ || is_completed_) {\n return;\n }\n if (response_ != nullptr) {\n callback_->OnResponseBodyError(*request_, *response_,\n absl::CancelledError());\n } else {\n callback_->OnResponseError(*request_, absl::CancelledError());\n }\n is_cancelled_ = true;\n}\n\nvoid CurlHttpRequestHandle::MarkAsCompleted() {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(callback_ != nullptr);\n if (!is_cancelled_ && !is_completed_) {\n if (response_ != nullptr) {\n callback_->OnResponseCompleted(*request_, *response_);\n } else {\n callback_->OnResponseError(*request_,\n absl::InternalError(\"response_ is nullptr\"));\n }\n }\n is_completed_ = true;\n}\n\nabsl::Status CurlHttpRequestHandle::AddToMulti(CurlMultiHandle* multi_handle,\n HttpRequestCallback* callback) {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(callback != nullptr);\n FCP_CHECK(multi_handle != nullptr);\n\n if (is_cancelled_) {\n callback->OnResponseError(*request_, absl::CancelledError());\n return absl::CancelledError();\n } else if (is_being_performed_ || is_completed_) {\n return absl::ResourceExhaustedError(\n \"The handle was previously passed to another PerformRequests call.\");\n }\n\n is_being_performed_ = true;\n callback_ = callback;\n\n CURLMcode code = multi_handle->AddEasyHandle(easy_handle_.get());\n if (code != CURLM_OK) {\n FCP_LOG(ERROR) << \"AddEasyHandle failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n callback_->OnResponseError(*request_, absl::InternalError(error_buffer_));\n return absl::InternalError(error_buffer_);\n }\n\n return absl::OkStatus();\n}\n\nvoid CurlHttpRequestHandle::RemoveFromMulti(CurlMultiHandle* multi_handle) {\n absl::MutexLock lock(&mutex_);\n\n FCP_CHECK(multi_handle != nullptr);\n CURLMcode code = multi_handle->RemoveEasyHandle(easy_handle_.get());\n if (code != CURLM_OK) {\n FCP_LOG(ERROR) << \"RemoveEasyHandle failed with code \"\n << CurlMultiHandle::StrError(code);\n FCP_LOG(ERROR) << error_buffer_;\n }\n}\n\nHttpRequestHandle::SentReceivedBytes\nCurlHttpRequestHandle::TotalSentReceivedBytes() const {\n absl::MutexLock lock(&mutex_);\n curl_off_t total_sent_bytes = 0;\n CURLcode code =\n easy_handle_->GetInfo(CURLINFO_SIZE_UPLOAD_T, &total_sent_bytes);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"TotalSentBytes failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n }\n curl_off_t total_received_bytes = 0;\n code = easy_handle_->GetInfo(CURLINFO_SIZE_DOWNLOAD_T, &total_received_bytes);\n if (code != CURLE_OK) {\n FCP_LOG(ERROR) << \"TotalReceivedBytes failed with code \" << code;\n FCP_LOG(ERROR) << error_buffer_;\n }\n return {.sent_bytes = total_sent_bytes,\n .received_bytes = total_received_bytes};\n}\n\nCURLcode CurlHttpRequestHandle::InitializeConnection(\n const std::string& test_cert_path) {\n error_buffer_[0] = 0;\n \/\/ Needed to read an error message.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ERRORBUFFER, error_buffer_));\n\n \/\/ Skip all signal handling because is not thread-safe.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOSIGNAL, 1L));\n\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_URL, std::string(request_->uri())));\n\n \/\/ Forces curl to follow redirects.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_FOLLOWLOCATION, 1L));\n\n \/\/ Suppresses headers added by a proxy.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L));\n\n \/\/ Force curl to verify the ssl connection.\n CURL_RETURN_IF_ERROR(\n test_cert_path.empty()\n ? easy_handle_->SetOpt(CURLOPT_CAINFO, nullptr)\n : easy_handle_->SetOpt(CURLOPT_CAINFO, test_cert_path));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_SSL_VERIFYPEER, 2L));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_SSL_VERIFYHOST, 1L));\n\n \/\/ Force curl to never timeout.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_TIMEOUT_MS,\n std::numeric_limits<int>::max()));\n\n \/\/ Called when a response header received.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_HEADERFUNCTION, &CurlHttpRequestHandle::HeaderCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HEADERDATA, this));\n\n \/\/ Called when a response body received.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_WRITEFUNCTION, &CurlHttpRequestHandle::DownloadCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_WRITEDATA, this));\n\n \/\/ Called to send a request body\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_READFUNCTION, &CurlHttpRequestHandle::UploadCallback));\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_READDATA, this));\n\n \/\/ Called periodically. We use it to check whether the request is cancelled.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(\n CURLOPT_XFERINFOFUNCTION, &CurlHttpRequestHandle::ProgressCallback));\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_XFERINFODATA, this));\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOPROGRESS, 0L));\n\n \/\/ Private storage. Used by a multi-handle.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_PRIVATE, this));\n\n switch (request_->method()) {\n case HttpRequest::Method::kGet:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HTTPGET, 1L));\n break;\n case HttpRequest::Method::kHead:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_NOBODY, 1L));\n break;\n case HttpRequest::Method::kPost:\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_POST, 1L));\n \/\/ Forces curl to use the callback.\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_POSTFIELDS, nullptr));\n break;\n case HttpRequest::Method::kPut:\n case HttpRequest::Method::kPatch:\n case HttpRequest::Method::kDelete:\n \/\/ TODO(team): Implement the requests when they are needed\n FCP_LOG(ERROR) << \"Unsupported request type\";\n return CURLE_UNSUPPORTED_PROTOCOL;\n }\n\n return InitializeHeaders(request_->extra_headers());\n}\n\nCURLcode CurlHttpRequestHandle::InitializeHeaders(\n const HeaderList& extra_headers) {\n \/\/ If no \"Accept-Encoding\" request header is explicitly specified\n \/\/ advertise an \"Accept-Encoding: gzip\" else leave decoded.\n std::optional<std::string> accept_encoding =\n FindHeader(request_->extra_headers(), kAcceptEncodingHdr);\n if (!accept_encoding.has_value()) {\n \/\/ Libcurl is responsible for the encoding.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ACCEPT_ENCODING, kGzipEncodingHdrValue));\n header_parser_.UseCurlEncoding();\n } else {\n \/\/ The caller is responsible for the encoding.\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_ACCEPT_ENCODING, nullptr));\n }\n\n for (auto& [key, value] : extra_headers) {\n if (absl::EqualsIgnoreCase(key, kAcceptEncodingHdr)) {\n continue;\n } else if (absl::EqualsIgnoreCase(key, kContentLengthHdr)) {\n \/\/ For post less than 2GB\n CURL_RETURN_IF_ERROR(\n easy_handle_->SetOpt(CURLOPT_POSTFIELDSIZE, std::stol(value)));\n } else {\n curl_slist* tmp = curl_slist_append(\n header_list_, absl::StrCat(key, \": \", value).c_str());\n FCP_CHECK(tmp != nullptr);\n header_list_ = tmp;\n }\n }\n\n CURL_RETURN_IF_ERROR(easy_handle_->SetOpt(CURLOPT_HTTPHEADER, header_list_));\n return CURLE_OK;\n}\n} \/\/ namespace fcp::client::http::curl\n<|endoftext|>"} {"text":"<commit_before>#include \"DiagnosticStream.h\"\n#include \"BitFunnel\/Utilities\/Factories.h\"\n\n\nnamespace BitFunnel\n{\n std::unique_ptr<IDiagnosticStream> Factories::CreateDiagnosticStream(std::ostream& stream)\n {\n return std::unique_ptr<IDiagnosticStream>(new DiagnosticStream(stream));\n }\n\n\n DiagnosticStream::DiagnosticStream(std::ostream& stream)\n : m_stream(stream)\n {\n }\n\n\n void DiagnosticStream::Enable(char const * diagnostic)\n {\n \/\/ TODO: REVIEW: check for duplicates?\n m_enabled.push_back(diagnostic);\n }\n\n\n void DiagnosticStream::Disable(char const * diagnostic)\n {\n \/\/ TODO: REVIEW: check for mismatch?\n for (unsigned i = 0 ; i < m_enabled.size(); ++i)\n {\n if (m_enabled[i].compare(diagnostic) == 0)\n {\n m_enabled.erase(m_enabled.begin() + i);\n\n \/\/ TODO: REVIEW: Assuming there is only one to remove.\n break;\n }\n }\n }\n\n\n \/\/ Returns true if text starts with prefix.\n bool StartsWith(char const * text, std::string const & prefix)\n {\n for (unsigned i = 0 ; i < prefix.size(); ++i)\n {\n if (*text != prefix[i])\n {\n return false;\n }\n ++text;\n }\n return true;\n }\n\n\n bool DiagnosticStream::IsEnabled(char const * diagnostic) const\n {\n for (unsigned i = 0; i < m_enabled.size(); ++i)\n {\n if (StartsWith(diagnostic, m_enabled[i]))\n {\n return true;\n }\n }\n return false;\n }\n\n\n std::ostream& DiagnosticStream::GetStream()\n {\n return m_stream;\n }\n}\n<commit_msg>Add missing license.<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2016, Microsoft\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\n#include \"DiagnosticStream.h\"\n#include \"BitFunnel\/Utilities\/Factories.h\"\n\n\nnamespace BitFunnel\n{\n std::unique_ptr<IDiagnosticStream> Factories::CreateDiagnosticStream(std::ostream& stream)\n {\n return std::unique_ptr<IDiagnosticStream>(new DiagnosticStream(stream));\n }\n\n\n DiagnosticStream::DiagnosticStream(std::ostream& stream)\n : m_stream(stream)\n {\n }\n\n\n void DiagnosticStream::Enable(char const * diagnostic)\n {\n \/\/ TODO: REVIEW: check for duplicates?\n m_enabled.push_back(diagnostic);\n }\n\n\n void DiagnosticStream::Disable(char const * diagnostic)\n {\n \/\/ TODO: REVIEW: check for mismatch?\n for (unsigned i = 0 ; i < m_enabled.size(); ++i)\n {\n if (m_enabled[i].compare(diagnostic) == 0)\n {\n m_enabled.erase(m_enabled.begin() + i);\n\n \/\/ TODO: REVIEW: Assuming there is only one to remove.\n break;\n }\n }\n }\n\n\n \/\/ Returns true if text starts with prefix.\n bool StartsWith(char const * text, std::string const & prefix)\n {\n for (unsigned i = 0 ; i < prefix.size(); ++i)\n {\n if (*text != prefix[i])\n {\n return false;\n }\n ++text;\n }\n return true;\n }\n\n\n bool DiagnosticStream::IsEnabled(char const * diagnostic) const\n {\n for (unsigned i = 0; i < m_enabled.size(); ++i)\n {\n if (StartsWith(diagnostic, m_enabled[i]))\n {\n return true;\n }\n }\n return false;\n }\n\n\n std::ostream& DiagnosticStream::GetStream()\n {\n return m_stream;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Native.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Native.h\"\n#include <cstdlib>\n\ntemplate <typename T>\ninline T clamp(T x, T min, T max)\n{\n\tif (x < min) return min;\n\tif (x > max) return max;\n\treturn x;\n}\n\ntemplate <typename T>\ninline T randf() { return (T)rand() \/ (T)RAND_MAX; }\n\ntemplate <typename T>\ninline T dither(T x)\n{\n\treturn x + randf<T>();\n}\n\ntemplate <int Bits, typename Fixed, typename Float>\nvoid FixedToFloat(const Fixed * In, Float * Out, int Count)\n{\n\tstatic const Float Max = (Float)((1UL << (Bits - 1)) - 1);\n\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Float)In[i] * (Float)(1.0 \/ Max);\n}\n\ntemplate <int Bits, typename Float, typename Fixed>\nvoid FloatToFixed(const Float * In, Fixed * Out, int Count)\n{\n\tstatic const Float Max = (Float)((1UL << (Bits - 1)) - 1);\n\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Fixed)(clamp(dither(In[i] * Max), -Max, Max));\n}\n\ntemplate <typename Float1, typename Float2>\nvoid FloatToFloat(const Float1 * In, Float2 * Out, int Count)\n{\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Float2)In[i];\n}\n\nextern \"C\" NATIVE_API void LEi16ToLEf32(const short * In, float * Out, int Count) { FixedToFloat<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi16ToLEf64(const short * In, double * Out, int Count) { FixedToFloat<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi32ToLEf32(const int * In, float * Out, int Count) { FixedToFloat<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi32ToLEf64(const int * In, double * Out, int Count) { FixedToFloat<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf32ToLEf64(const float * In, double * Out, int Count) { FloatToFloat(In, Out, Count); }\n\nextern \"C\" NATIVE_API void LEf32ToLEi16(const float * In, short * Out, int Count) { FloatToFixed<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEi16(const double * In, short * Out, int Count) { FloatToFixed<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf32ToLEi32(const float * In, short * Out, int Count) { FloatToFixed<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEi32(const double * In, short * Out, int Count) { FloatToFixed<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEf32(const double * In, float * Out, int Count) { FloatToFloat(In, Out, Count); }\n\n \/\/case AsioWrapper.SampleType.Int16MSB:\n \/\/case AsioWrapper.SampleType.Int24MSB:\n \/\/case AsioWrapper.SampleType.Int32MSB:\n \/\/case AsioWrapper.SampleType.Float32MSB:\n \/\/case AsioWrapper.SampleType.Float64MSB:\n \/\/case AsioWrapper.SampleType.Int32MSB16:\n \/\/case AsioWrapper.SampleType.Int32MSB18:\n \/\/case AsioWrapper.SampleType.Int32MSB20:\n \/\/case AsioWrapper.SampleType.Int32MSB24:\n \/\/case AsioWrapper.SampleType.Int16LSB:\n \/\/case AsioWrapper.SampleType.Int24LSB:\n \/\/case AsioWrapper.SampleType.Int32LSB:\n \/\/case AsioWrapper.SampleType.Float32LSB:\n \/\/case AsioWrapper.SampleType.Float64LSB:\n \/\/case AsioWrapper.SampleType.Int32LSB16:\n \/\/case AsioWrapper.SampleType.Int32LSB18:\n \/\/case AsioWrapper.SampleType.Int32LSB20:\n \/\/case AsioWrapper.SampleType.Int32LSB24:\n \/\/case AsioWrapper.SampleType.DSDInt8LSB1:\n \/\/case AsioWrapper.SampleType.DSDInt8MSB1:\n \/\/case AsioWrapper.SampleType.DSDInt8NER8:<commit_msg>Fixed Toi32 functions<commit_after>\/\/ Native.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"Native.h\"\n#include <cstdlib>\n\ntemplate <typename T>\ninline T clamp(T x, T min, T max)\n{\n\tif (x < min) return min;\n\tif (x > max) return max;\n\treturn x;\n}\n\ntemplate <typename T>\ninline T randf() { return (T)rand() \/ (T)RAND_MAX; }\n\ntemplate <typename T>\ninline T dither(T x)\n{\n\treturn x + randf<T>();\n}\n\ntemplate <int Bits, typename Fixed, typename Float>\nvoid FixedToFloat(const Fixed * In, Float * Out, int Count)\n{\n\tstatic const Float Max = (Float)((1UL << (Bits - 1)) - 1);\n\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Float)In[i] * (Float)(1.0 \/ Max);\n}\n\ntemplate <int Bits, typename Float, typename Fixed>\nvoid FloatToFixed(const Float * In, Fixed * Out, int Count)\n{\n\tstatic const Float Max = (Float)((1UL << (Bits - 1)) - 1);\n\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Fixed)(clamp(dither(In[i] * Max), -Max, Max));\n}\n\ntemplate <typename Float1, typename Float2>\nvoid FloatToFloat(const Float1 * In, Float2 * Out, int Count)\n{\n\tfor (int i = 0; i < Count; ++i)\n\t\tOut[i] = (Float2)In[i];\n}\n\nextern \"C\" NATIVE_API void LEi16ToLEf32(const short * In, float * Out, int Count) { FixedToFloat<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi16ToLEf64(const short * In, double * Out, int Count) { FixedToFloat<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi32ToLEf32(const int * In, float * Out, int Count) { FixedToFloat<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEi32ToLEf64(const int * In, double * Out, int Count) { FixedToFloat<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf32ToLEf64(const float * In, double * Out, int Count) { FloatToFloat(In, Out, Count); }\n\nextern \"C\" NATIVE_API void LEf32ToLEi16(const float * In, short * Out, int Count) { FloatToFixed<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEi16(const double * In, short * Out, int Count) { FloatToFixed<16>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf32ToLEi32(const float * In, int * Out, int Count) { FloatToFixed<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEi32(const double * In, int * Out, int Count) { FloatToFixed<32>(In, Out, Count); }\nextern \"C\" NATIVE_API void LEf64ToLEf32(const double * In, float * Out, int Count) { FloatToFloat(In, Out, Count); }\n\n \/\/case AsioWrapper.SampleType.Int16MSB:\n \/\/case AsioWrapper.SampleType.Int24MSB:\n \/\/case AsioWrapper.SampleType.Int32MSB:\n \/\/case AsioWrapper.SampleType.Float32MSB:\n \/\/case AsioWrapper.SampleType.Float64MSB:\n \/\/case AsioWrapper.SampleType.Int32MSB16:\n \/\/case AsioWrapper.SampleType.Int32MSB18:\n \/\/case AsioWrapper.SampleType.Int32MSB20:\n \/\/case AsioWrapper.SampleType.Int32MSB24:\n \/\/case AsioWrapper.SampleType.Int16LSB:\n \/\/case AsioWrapper.SampleType.Int24LSB:\n \/\/case AsioWrapper.SampleType.Int32LSB:\n \/\/case AsioWrapper.SampleType.Float32LSB:\n \/\/case AsioWrapper.SampleType.Float64LSB:\n \/\/case AsioWrapper.SampleType.Int32LSB16:\n \/\/case AsioWrapper.SampleType.Int32LSB18:\n \/\/case AsioWrapper.SampleType.Int32LSB20:\n \/\/case AsioWrapper.SampleType.Int32LSB24:\n \/\/case AsioWrapper.SampleType.DSDInt8LSB1:\n \/\/case AsioWrapper.SampleType.DSDInt8MSB1:\n \/\/case AsioWrapper.SampleType.DSDInt8NER8:<|endoftext|>"} {"text":"<commit_before>\/**\r\n* @file Main.cpp\r\n*\/\r\n#include \"GLFWEW.h\"\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n\/\/\/ _f[^^.\r\nstruct Vertex\r\n{\r\n glm::vec3 position; \/\/\/< W.\r\n glm::vec4 color; \/\/\/< F.\r\n glm::vec2 texCoord; \/\/\/< eNX`W.\r\n};\r\n\r\n\/\/\/ _f[^.\r\nconst Vertex vertices[] = {\r\n { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f}, {0.0f, 0.0f} },\r\n { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.3f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },\r\n { {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },\r\n\r\n { {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },\r\n { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },\r\n { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },\r\n { {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f} },\r\n};\r\n\r\n\/\/\/ CfbNXf[^.\r\nconst GLuint indices[] = {\r\n 0, 1, 2, 2, 3, 0,\r\n 4, 5, 6, 7, 8, 9,\r\n};\r\n\r\n\/\/\/ _VF[_.\r\nstatic const char* vsCode =\r\n\"#version 410 \\n\"\r\n\"layout(location=0) in vec3 vPosition;\"\r\n\"layout(location=1) in vec4 vColor;\"\r\n\"layout(location=0) out vec4 outColor;\"\r\n\"uniform mat4x4 matMVP;\"\r\n\"void main() {\"\r\n\" outColor = vColor;\"\r\n\" gl_Position = matMVP * vec4(vPosition, 1.0);\"\r\n\"}\";\r\n\r\n\/\/\/ tOgVF[_.\r\nstatic const char* fsCode =\r\n\"#version 410 \\n\"\r\n\"layout(location=0) in vec4 inColor;\"\r\n\"out vec4 fragColor;\"\r\n\"void main() {\"\r\n\" fragColor = inColor;\"\r\n\"}\";\r\n\r\n\/**\r\n* Vertex Buffer Object쐬.\r\n*\r\n* @param size _f[^̃TCY.\r\n* @param data _f[^ւ̃|C^.\r\n*\r\n* @return 쐬VBO.\r\n*\/\r\nGLuint CreateVBO(GLsizeiptr size, const GLvoid* data)\r\n{\r\n GLuint vbo = 0;\r\n glGenBuffers(1, &vbo);\r\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);\r\n glBindBuffer(GL_ARRAY_BUFFER, 0);\r\n return vbo;\r\n}\r\n\r\n\/**\r\n* Index Buffer Object쐬.\r\n*\r\n* @param size CfbNXf[^̃TCY.\r\n* @param data CfbNXf[^ւ̃|C^.\r\n*\r\n* @return 쐬IBO.\r\n*\/\r\nGLuint CreateIBO(GLsizeiptr size, const GLvoid* data)\r\n{\r\n GLuint ibo = 0;\r\n glGenBuffers(1, &ibo);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n return ibo;\r\n}\r\n\r\n\/**\r\n* _Agr[gݒ肷.\r\n*\r\n* @param index _Agr[g̃CfbNX.\r\n* @param cls _f[^^.\r\n* @param mbr _Agr[gɐݒ肷cls̃oϐ.\r\n*\/\r\n#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \\\r\n index, \\\r\n sizeof(cls::mbr) \/ sizeof(float), \\\r\n sizeof(cls), \\\r\n reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))\r\n\r\nvoid SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)\r\n{\r\n glEnableVertexAttribArray(index);\r\n glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);\r\n}\r\n\r\n\/**\r\n* Vertex Array Object쐬.\r\n*\r\n* @param vbo VAOɊ֘AtVBO.\r\n* @param ibo VAOɊ֘AtIBO.\r\n*\r\n* @return 쐬VAO.\r\n*\/\r\nGLuint CreateVAO(GLuint vbo, GLuint ibo)\r\n{\r\n GLuint vao = 0;\r\n glGenVertexArrays(1, &vao);\r\n glBindVertexArray(vao);\r\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n SetVertexAttribPointer(0, Vertex, position);\r\n SetVertexAttribPointer(1, Vertex, color);\r\n glBindVertexArray(0);\r\n glDeleteBuffers(1, &vbo);\r\n glDeleteBuffers(1, &ibo);\r\n return vao;\r\n}\r\n\r\n\/**\r\n* VF[_R[hRpC.\r\n*\r\n* @param type VF[_̎.\r\n* @param string VF[_R[hւ̃|C^.\r\n*\r\n* @return 쐬VF[_IuWFNg.\r\n*\/\r\nGLuint CompileShader(GLenum type, const GLchar* string)\r\n{\r\n GLuint shader = glCreateShader(type);\r\n glShaderSource(shader, 1, &string, nullptr);\r\n glCompileShader(shader);\r\n GLint compiled = 0;\r\n glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);\r\n if (!compiled) {\r\n GLint infoLen = 0;\r\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);\r\n if (infoLen) {\r\n std::vector<char> buf;\r\n buf.resize(infoLen);\r\n if (static_cast<int>(buf.size()) >= infoLen) {\r\n glGetShaderInfoLog(shader, infoLen, NULL, buf.data());\r\n std::cerr << \"ERROR: VF[_̃RpCɎsn\" << buf.data() << std::endl;\r\n }\r\n }\r\n glDeleteShader(shader);\r\n return 0;\r\n }\r\n return shader;\r\n}\r\n\r\n\/**\r\n* vOIuWFNg쐬.\r\n*\r\n* @param vsCode _VF[_R[hւ̃|C^.\r\n* @param fsCode tOgVF[_R[hւ̃|C^.\r\n*\r\n* @return 쐬vOIuWFNg.\r\n*\/\r\nGLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode)\r\n{\r\n GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode);\r\n GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode);\r\n if (!vs || !fs) {\r\n return 0;\r\n }\r\n GLuint program = glCreateProgram();\r\n glAttachShader(program, fs);\r\n glDeleteShader(fs);\r\n glAttachShader(program, vs);\r\n glDeleteShader(vs);\r\n glLinkProgram(program);\r\n GLint linkStatus = GL_FALSE;\r\n glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);\r\n if (linkStatus != GL_TRUE) {\r\n GLint infoLen = 0;\r\n glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);\r\n if (infoLen) {\r\n std::vector<char> buf;\r\n buf.resize(infoLen);\r\n if (static_cast<int>(buf.size()) >= infoLen) {\r\n glGetProgramInfoLog(program, infoLen, NULL, buf.data());\r\n std::cerr << \"ERROR: VF[_̃NɎsn\"<< buf.data() << std::endl;\r\n }\r\n }\r\n glDeleteProgram(program);\r\n return 0;\r\n }\r\n return program;\r\n}\r\n\r\n\/\/\/ Gg[|Cg.\r\nint main()\r\n{\r\n GLFWEW::Window& window = GLFWEW::Window::Instance();\r\n if (!window.Init(800, 600, \"OpenGL Tutorial\")) {\r\n return 1;\r\n }\r\n\r\n const GLuint vbo = CreateVBO(sizeof(vertices), vertices);\r\n const GLuint ibo = CreateIBO(sizeof(indices), indices);\r\n const GLuint vao = CreateVAO(vbo, ibo);\r\n const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode);\r\n if (!vbo || !ibo || !vao || !shaderProgram) {\r\n return 1;\r\n }\r\n\r\n glEnable(GL_DEPTH_TEST);\r\n\r\n \/\/ C[v.\r\n while (!window.ShouldClose()) {\r\n glClearColor(0.1f, 0.3f, 0.5f, 1.0f);\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\r\n \/\/ _]ړ.\r\n static float degree = 0.0f;\r\n degree += 0.1f;\r\n if (degree >= 360.0f) { degree -= 360.0f; }\r\n const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);\r\n\r\n glUseProgram(shaderProgram);\r\n const GLint matMVPLoc = glGetUniformLocation(shaderProgram, \"matMVP\");\r\n if (matMVPLoc >= 0) {\r\n const glm::mat4x4 matProj =\r\n glm::perspective(glm::radians(45.0f), 800.0f \/ 600.0f, 0.1f, 100.0f);\r\n const glm::mat4x4 matView =\r\n glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));\r\n const glm::mat4x4 matMVP = matProj * matView;\r\n glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);\r\n }\r\n glBindVertexArray(vao);\r\n glDrawElements(\r\n GL_TRIANGLES, sizeof(indices)\/sizeof(indices[0]),\r\n GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0));\r\n\r\n window.SwapBuffers();\r\n }\r\n\r\n glDeleteProgram(shaderProgram);\r\n glDeleteVertexArrays(1, &vao);\r\n\r\n return 0;\r\n}<commit_msg>第04回6章まで実装.<commit_after>\/**\r\n* @file Main.cpp\r\n*\/\r\n#include \"GLFWEW.h\"\r\n#include \"Texture.h\"\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n\/\/\/ _f[^^.\r\nstruct Vertex\r\n{\r\n glm::vec3 position; \/\/\/< W.\r\n glm::vec4 color; \/\/\/< F.\r\n glm::vec2 texCoord; \/\/\/< eNX`W.\r\n};\r\n\r\n\/\/\/ _f[^.\r\nconst Vertex vertices[] = {\r\n { {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f}, {0.0f, 0.0f} },\r\n { { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.3f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },\r\n { {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },\r\n\r\n { {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },\r\n { {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },\r\n { { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f} },\r\n { { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },\r\n { {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f} },\r\n};\r\n\r\n\/\/\/ CfbNXf[^.\r\nconst GLuint indices[] = {\r\n 0, 1, 2, 2, 3, 0,\r\n 4, 5, 6, 7, 8, 9,\r\n};\r\n\r\n\/\/\/ _VF[_.\r\nstatic const char* vsCode =\r\n\"#version 410 \\n\"\r\n\"layout(location=0) in vec3 vPosition;\"\r\n\"layout(location=1) in vec4 vColor;\"\r\n\"layout(location=2) in vec2 vTexCoord;\"\r\n\"layout(location=0) out vec4 outColor;\"\r\n\"layout(location=1) out vec2 outTexCoord;\"\r\n\"uniform mat4x4 matMVP;\"\r\n\"void main() {\"\r\n\" outColor = vColor;\"\r\n\" outTexCoord = vTexCoord;\"\r\n\" gl_Position = matMVP * vec4(vPosition, 1.0);\"\r\n\"}\";\r\n\r\n\/\/\/ tOgVF[_.\r\nstatic const char* fsCode =\r\n\"#version 410 \\n\"\r\n\"layout(location=0) in vec4 inColor;\"\r\n\"layout(location=1) in vec2 inTexCoord;\"\r\n\"uniform sampler2D colorSampler;\"\r\n\"out vec4 fragColor;\"\r\n\"void main() {\"\r\n\" fragColor = inColor * texture(colorSampler, inTexCoord);\"\r\n\"}\";\r\n\r\n\/**\r\n* Vertex Buffer Object쐬.\r\n*\r\n* @param size _f[^̃TCY.\r\n* @param data _f[^ւ̃|C^.\r\n*\r\n* @return 쐬VBO.\r\n*\/\r\nGLuint CreateVBO(GLsizeiptr size, const GLvoid* data)\r\n{\r\n GLuint vbo = 0;\r\n glGenBuffers(1, &vbo);\r\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);\r\n glBindBuffer(GL_ARRAY_BUFFER, 0);\r\n return vbo;\r\n}\r\n\r\n\/**\r\n* Index Buffer Object쐬.\r\n*\r\n* @param size CfbNXf[^̃TCY.\r\n* @param data CfbNXf[^ւ̃|C^.\r\n*\r\n* @return 쐬IBO.\r\n*\/\r\nGLuint CreateIBO(GLsizeiptr size, const GLvoid* data)\r\n{\r\n GLuint ibo = 0;\r\n glGenBuffers(1, &ibo);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n return ibo;\r\n}\r\n\r\n\/**\r\n* _Agr[gݒ肷.\r\n*\r\n* @param index _Agr[g̃CfbNX.\r\n* @param cls _f[^^.\r\n* @param mbr _Agr[gɐݒ肷cls̃oϐ.\r\n*\/\r\n#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \\\r\n index, \\\r\n sizeof(cls::mbr) \/ sizeof(float), \\\r\n sizeof(cls), \\\r\n reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))\r\n\r\nvoid SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)\r\n{\r\n glEnableVertexAttribArray(index);\r\n glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);\r\n}\r\n\r\n\/**\r\n* Vertex Array Object쐬.\r\n*\r\n* @param vbo VAOɊ֘AtVBO.\r\n* @param ibo VAOɊ֘AtIBO.\r\n*\r\n* @return 쐬VAO.\r\n*\/\r\nGLuint CreateVAO(GLuint vbo, GLuint ibo)\r\n{\r\n GLuint vao = 0;\r\n glGenVertexArrays(1, &vao);\r\n glBindVertexArray(vao);\r\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\r\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);\r\n SetVertexAttribPointer(0, Vertex, position);\r\n SetVertexAttribPointer(1, Vertex, color);\r\n SetVertexAttribPointer(2, Vertex, texCoord);\r\n glBindVertexArray(0);\r\n glDeleteBuffers(1, &vbo);\r\n glDeleteBuffers(1, &ibo);\r\n return vao;\r\n}\r\n\r\n\/**\r\n* VF[_R[hRpC.\r\n*\r\n* @param type VF[_̎.\r\n* @param string VF[_R[hւ̃|C^.\r\n*\r\n* @return 쐬VF[_IuWFNg.\r\n*\/\r\nGLuint CompileShader(GLenum type, const GLchar* string)\r\n{\r\n GLuint shader = glCreateShader(type);\r\n glShaderSource(shader, 1, &string, nullptr);\r\n glCompileShader(shader);\r\n GLint compiled = 0;\r\n glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);\r\n if (!compiled) {\r\n GLint infoLen = 0;\r\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);\r\n if (infoLen) {\r\n std::vector<char> buf;\r\n buf.resize(infoLen);\r\n if (static_cast<int>(buf.size()) >= infoLen) {\r\n glGetShaderInfoLog(shader, infoLen, NULL, buf.data());\r\n std::cerr << \"ERROR: VF[_̃RpCɎsn\" << buf.data() << std::endl;\r\n }\r\n }\r\n glDeleteShader(shader);\r\n return 0;\r\n }\r\n return shader;\r\n}\r\n\r\n\/**\r\n* vOIuWFNg쐬.\r\n*\r\n* @param vsCode _VF[_R[hւ̃|C^.\r\n* @param fsCode tOgVF[_R[hւ̃|C^.\r\n*\r\n* @return 쐬vOIuWFNg.\r\n*\/\r\nGLuint CreateShaderProgram(const GLchar* vsCode, const GLchar* fsCode)\r\n{\r\n GLuint vs = CompileShader(GL_VERTEX_SHADER, vsCode);\r\n GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsCode);\r\n if (!vs || !fs) {\r\n return 0;\r\n }\r\n GLuint program = glCreateProgram();\r\n glAttachShader(program, fs);\r\n glDeleteShader(fs);\r\n glAttachShader(program, vs);\r\n glDeleteShader(vs);\r\n glLinkProgram(program);\r\n GLint linkStatus = GL_FALSE;\r\n glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);\r\n if (linkStatus != GL_TRUE) {\r\n GLint infoLen = 0;\r\n glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);\r\n if (infoLen) {\r\n std::vector<char> buf;\r\n buf.resize(infoLen);\r\n if (static_cast<int>(buf.size()) >= infoLen) {\r\n glGetProgramInfoLog(program, infoLen, NULL, buf.data());\r\n std::cerr << \"ERROR: VF[_̃NɎsn\"<< buf.data() << std::endl;\r\n }\r\n }\r\n glDeleteProgram(program);\r\n return 0;\r\n }\r\n return program;\r\n}\r\n\r\n\/\/\/ Gg[|Cg.\r\nint main()\r\n{\r\n GLFWEW::Window& window = GLFWEW::Window::Instance();\r\n if (!window.Init(800, 600, \"OpenGL Tutorial\")) {\r\n return 1;\r\n }\r\n\r\n const GLuint vbo = CreateVBO(sizeof(vertices), vertices);\r\n const GLuint ibo = CreateIBO(sizeof(indices), indices);\r\n const GLuint vao = CreateVAO(vbo, ibo);\r\n const GLuint shaderProgram = CreateShaderProgram(vsCode, fsCode);\r\n if (!vbo || !ibo || !vao || !shaderProgram) {\r\n return 1;\r\n }\r\n\r\n \/\/\/ eNX`f[^.\r\n static const uint32_t textureData[] = {\r\n 0xffffffff, 0xffcccccc, 0xffffffff, 0xffcccccc, 0xffffffff,\r\n 0xff888888, 0xffffffff, 0xff888888, 0xffffffff, 0xff888888,\r\n 0xffffffff, 0xff444444, 0xffffffff, 0xff444444, 0xffffffff,\r\n 0xff000000, 0xffffffff, 0xff000000, 0xffffffff, 0xff000000,\r\n 0xffffffff, 0xff000000, 0xffffffff, 0xff000000, 0xffffffff,\r\n };\r\n TexturePtr tex = Texture::Create(5, 5, GL_RGBA8, GL_RGBA, textureData);\r\n if (!tex) {\r\n return 1;\r\n }\r\n\r\n glEnable(GL_DEPTH_TEST);\r\n\r\n \/\/ C[v.\r\n while (!window.ShouldClose()) {\r\n glClearColor(0.1f, 0.3f, 0.5f, 1.0f);\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\r\n \/\/ _]ړ.\r\n static float degree = 0.0f;\r\n degree += 0.1f;\r\n if (degree >= 360.0f) { degree -= 360.0f; }\r\n const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);\r\n\r\n glUseProgram(shaderProgram);\r\n const GLint matMVPLoc = glGetUniformLocation(shaderProgram, \"matMVP\");\r\n if (matMVPLoc >= 0) {\r\n const glm::mat4x4 matProj =\r\n glm::perspective(glm::radians(45.0f), 800.0f \/ 600.0f, 0.1f, 100.0f);\r\n const glm::mat4x4 matView =\r\n glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));\r\n const glm::mat4x4 matMVP = matProj * matView;\r\n glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);\r\n }\r\n const GLint colorSamplerLoc = glGetUniformLocation(shaderProgram, \"colorSampler\");\r\n if (colorSamplerLoc >= 0) {\r\n glUniform1i(colorSamplerLoc, 0);\r\n glActiveTexture(GL_TEXTURE0);\r\n glBindTexture(GL_TEXTURE_2D, tex->Id());\r\n }\r\n glBindVertexArray(vao);\r\n glDrawElements(\r\n GL_TRIANGLES, sizeof(indices)\/sizeof(indices[0]),\r\n GL_UNSIGNED_INT, reinterpret_cast<const GLvoid*>(0));\r\n\r\n window.SwapBuffers();\r\n }\r\n\r\n glDeleteProgram(shaderProgram);\r\n glDeleteVertexArrays(1, &vao);\r\n\r\n return 0;\r\n}<|endoftext|>"} {"text":"<commit_before>#include \"LinuxPerfData.h\"\n#include \"SerializationMacros.h\"\n#include \"Serialization.h\"\n\n\nvoid LinuxPerfData::Clear()\n{\n m_CS.m_Data.clear();\n m_header = \"\";\n m_time = 0;\n m_tid = 0;\n m_numCallstacks = 0;\n}\n\nORBIT_SERIALIZE( LinuxPerfData, 0 )\n{\n ORBIT_NVP_VAL( 0, m_header );\n ORBIT_NVP_VAL( 0, m_tid );\n ORBIT_NVP_VAL( 0, m_time );\n ORBIT_NVP_VAL( 0, m_numCallstacks );\n ORBIT_NVP_VAL( 0, m_CS );\n}<commit_msg>Clear callstack hash in LinuxPerfData.Clear() otherwise we end up assigning the same hash to all sampling events.<commit_after>#include \"LinuxPerfData.h\"\n#include \"SerializationMacros.h\"\n#include \"Serialization.h\"\n\n\nvoid LinuxPerfData::Clear()\n{\n m_CS.m_Data.clear();\n m_CS.m_Hash = 0;\n m_header = \"\";\n m_time = 0;\n m_tid = 0;\n m_numCallstacks = 0;\n}\n\nORBIT_SERIALIZE( LinuxPerfData, 0 )\n{\n ORBIT_NVP_VAL( 0, m_header );\n ORBIT_NVP_VAL( 0, m_tid );\n ORBIT_NVP_VAL( 0, m_time );\n ORBIT_NVP_VAL( 0, m_numCallstacks );\n ORBIT_NVP_VAL( 0, m_CS );\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 David Farrell\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ResourceManager.h\"\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\nchar * ResourceManager::Load(const char *path, long *len)\n{\n char *buffer = NULL;\n long err = 0;\n\n \/\/ open binary file for reading\n FILE *fh = fopen(path, \"rb\");\n if(!fh)\n {\n fprintf(stderr, \"fopen: error\\n\");\n return NULL;\n }\n\n \/\/ fseek to end\n err = fseek(fh, 0L, SEEK_END);\n if(err != 0)\n {\n fprintf(stderr, \"fseek: error\\n\");\n return NULL;\n }\n\n \/\/ get file size\n *len = ftell(fh);\n if(*len == -1L)\n {\n fprintf(stderr, \"ftell: error\\n\");\n return NULL;\n }\n\n \/\/ fseek to start\n err = fseek(fh, 0L, SEEK_SET);\n if(err != 0)\n {\n fprintf(stderr, \"fseek: error\\n\");\n return NULL;\n }\n\n \/\/ allocate buffer\n buffer = (char *)malloc(*len);\n if(buffer == NULL)\n {\n fprintf(stderr, \"malloc: error\\n\");\n return NULL;\n }\n\n \/\/ read into buffer\n err = fread(buffer, *len, 1, fh);\n if(err != 1)\n {\n fprintf(stderr, \"fread: error\\n\");\n return NULL;\n }\n\n \/\/ close file\n err = fclose(fh);\n if(err == EOF) fprintf(stderr, \"fclose: error\\n\");\n\n return buffer;\n}\n<commit_msg>Added more useful fopen error message.<commit_after>\/*\n * Copyright 2013 David Farrell\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ResourceManager.h\"\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\nchar * ResourceManager::Load(const char *path, long *len)\n{\n char *buffer = NULL;\n long err = 0;\n\n \/\/ open binary file for reading\n FILE *fh = fopen(path, \"rb\");\n if(!fh)\n {\n fprintf(stderr, \"fopen: error opening `%s`\\n\", path);\n return NULL;\n }\n\n \/\/ fseek to end\n err = fseek(fh, 0L, SEEK_END);\n if(err != 0)\n {\n fprintf(stderr, \"fseek: error\\n\");\n return NULL;\n }\n\n \/\/ get file size\n *len = ftell(fh);\n if(*len == -1L)\n {\n fprintf(stderr, \"ftell: error\\n\");\n return NULL;\n }\n\n \/\/ fseek to start\n err = fseek(fh, 0L, SEEK_SET);\n if(err != 0)\n {\n fprintf(stderr, \"fseek: error\\n\");\n return NULL;\n }\n\n \/\/ allocate buffer\n buffer = (char *)malloc(*len);\n if(buffer == NULL)\n {\n fprintf(stderr, \"malloc: error\\n\");\n return NULL;\n }\n\n \/\/ read into buffer\n err = fread(buffer, *len, 1, fh);\n if(err != 1)\n {\n fprintf(stderr, \"fread: error\\n\");\n return NULL;\n }\n\n \/\/ close file\n err = fclose(fh);\n if(err == EOF) fprintf(stderr, \"fclose: error\\n\");\n\n return buffer;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- examples\/Tooling\/RemoveCStrCalls.cpp - Redundant c_str call removal ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a tool that prints replacements that remove redundant\n\/\/ calls of c_str() on strings.\n\/\/\n\/\/ Usage:\n\/\/ remove-cstr-calls <cmake-output-dir> <file1> <file2> ...\n\/\/\n\/\/ Where <cmake-output-dir> is a CMake build directory in which a file named\n\/\/ compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in\n\/\/ CMake to get this output).\n\/\/\n\/\/ <file1> ... specify the paths of files in the CMake source tree. This path\n\/\/ is looked up in the compile command database. If the path of a file is\n\/\/ absolute, it needs to point into CMake's source tree. If the path is\n\/\/ relative, the current working directory needs to be in the CMake source\n\/\/ tree and the file must be in a subdirectory of the current working\n\/\/ directory. \".\/\" prefixes in the relative files will be automatically\n\/\/ removed, but the rest of a relative path must be a suffix of a path in\n\/\/ the compile command line database.\n\/\/\n\/\/ For example, to use remove-cstr-calls on all files in a subtree of the\n\/\/ source tree, use:\n\/\/\n\/\/ \/path\/in\/subtree $ find . -name '*.cpp'|\n\/\/ xargs remove-cstr-calls \/path\/to\/build\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchers.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace llvm;\nusing clang::tooling::newFrontendActionFactory;\nusing clang::tooling::Replacement;\nusing clang::tooling::CompilationDatabase;\n\n\/\/ FIXME: Pull out helper methods in here into more fitting places.\n\n\/\/ Returns the text that makes up 'node' in the source.\n\/\/ Returns an empty string if the text cannot be found.\ntemplate <typename T>\nstatic std::string getText(const SourceManager &SourceManager, const T &Node) {\n SourceLocation StartSpellingLocatino =\n SourceManager.getSpellingLoc(Node.getLocStart());\n SourceLocation EndSpellingLocation =\n SourceManager.getSpellingLoc(Node.getLocEnd());\n if (!StartSpellingLocatino.isValid() || !EndSpellingLocation.isValid()) {\n return std::string();\n }\n bool Invalid = true;\n const char *Text =\n SourceManager.getCharacterData(StartSpellingLocatino, &Invalid);\n if (Invalid) {\n return std::string();\n }\n std::pair<FileID, unsigned> Start =\n SourceManager.getDecomposedLoc(StartSpellingLocatino);\n std::pair<FileID, unsigned> End =\n SourceManager.getDecomposedLoc(Lexer::getLocForEndOfToken(\n EndSpellingLocation, 0, SourceManager, LangOptions()));\n if (Start.first != End.first) {\n \/\/ Start and end are in different files.\n return std::string();\n }\n if (End.second < Start.second) {\n \/\/ Shuffling text with macros may cause this.\n return std::string();\n }\n return std::string(Text, End.second - Start.second);\n}\n\n\/\/ Return true if expr needs to be put in parens when it is an\n\/\/ argument of a prefix unary operator, e.g. when it is a binary or\n\/\/ ternary operator syntactically.\nstatic bool needParensAfterUnaryOperator(const Expr &ExprNode) {\n if (dyn_cast<clang::BinaryOperator>(&ExprNode) ||\n dyn_cast<clang::ConditionalOperator>(&ExprNode)) {\n return true;\n }\n if (const CXXOperatorCallExpr *op =\n dyn_cast<CXXOperatorCallExpr>(&ExprNode)) {\n return op->getNumArgs() == 2 &&\n op->getOperator() != OO_PlusPlus &&\n op->getOperator() != OO_MinusMinus &&\n op->getOperator() != OO_Call &&\n op->getOperator() != OO_Subscript;\n }\n return false;\n}\n\n\/\/ Format a pointer to an expression: prefix with '*' but simplify\n\/\/ when it already begins with '&'. Return empty string on failure.\nstatic std::string formatDereference(const SourceManager &SourceManager,\n const Expr &ExprNode) {\n if (const clang::UnaryOperator *Op =\n dyn_cast<clang::UnaryOperator>(&ExprNode)) {\n if (Op->getOpcode() == UO_AddrOf) {\n \/\/ Strip leading '&'.\n return getText(SourceManager, *Op->getSubExpr()->IgnoreParens());\n }\n }\n const std::string Text = getText(SourceManager, ExprNode);\n if (Text.empty()) return std::string();\n \/\/ Add leading '*'.\n if (needParensAfterUnaryOperator(ExprNode)) {\n return std::string(\"*(\") + Text + \")\";\n }\n return std::string(\"*\") + Text;\n}\n\nnamespace {\nclass FixCStrCall : public ast_matchers::MatchFinder::MatchCallback {\n public:\n FixCStrCall(tooling::Replacements *Replace)\n : Replace(Replace) {}\n\n virtual void run(const ast_matchers::MatchFinder::MatchResult &Result) {\n const CallExpr *Call =\n Result.Nodes.getStmtAs<CallExpr>(\"call\");\n const Expr *Arg =\n Result.Nodes.getStmtAs<Expr>(\"arg\");\n const bool Arrow =\n Result.Nodes.getStmtAs<MemberExpr>(\"member\")->isArrow();\n \/\/ Replace the \"call\" node with the \"arg\" node, prefixed with '*'\n \/\/ if the call was using '->' rather than '.'.\n const std::string ArgText = Arrow ?\n formatDereference(*Result.SourceManager, *Arg) :\n getText(*Result.SourceManager, *Arg);\n if (ArgText.empty()) return;\n\n Replace->insert(Replacement(*Result.SourceManager, Call, ArgText));\n }\n\n private:\n tooling::Replacements *Replace;\n};\n} \/\/ end namespace\n\nconst char *StringConstructor =\n \"::std::basic_string<char, std::char_traits<char>, std::allocator<char> >\"\n \"::basic_string\";\n\nconst char *StringCStrMethod =\n \"::std::basic_string<char, std::char_traits<char>, std::allocator<char> >\"\n \"::c_str\";\n\ncl::opt<std::string> BuildPath(\n cl::Positional,\n cl::desc(\"<build-path>\"));\n\ncl::list<std::string> SourcePaths(\n cl::Positional,\n cl::desc(\"<source0> [... <sourceN>]\"),\n cl::OneOrMore);\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv);\n std::string ErrorMessage;\n llvm::OwningPtr<CompilationDatabase> Compilations(\n CompilationDatabase::loadFromDirectory(BuildPath, ErrorMessage));\n if (!Compilations)\n llvm::report_fatal_error(ErrorMessage);\n tooling::RefactoringTool Tool(*Compilations, SourcePaths);\n ast_matchers::MatchFinder Finder;\n FixCStrCall Callback(&Tool.getReplacements());\n Finder.addMatcher(\n constructorCall(\n hasDeclaration(method(hasName(StringConstructor))),\n argumentCountIs(2),\n \/\/ The first argument must have the form x.c_str() or p->c_str()\n \/\/ where the method is string::c_str(). We can use the copy\n \/\/ constructor of string instead (or the compiler might share\n \/\/ the string object).\n hasArgument(\n 0,\n id(\"call\", memberCall(\n callee(id(\"member\", memberExpression())),\n callee(method(hasName(StringCStrMethod))),\n on(id(\"arg\", expression()))))),\n \/\/ The second argument is the alloc object which must not be\n \/\/ present explicitly.\n hasArgument(\n 1,\n defaultArgument())),\n &Callback);\n Finder.addMatcher(\n constructorCall(\n \/\/ Implicit constructors of these classes are overloaded\n \/\/ wrt. string types and they internally make a StringRef\n \/\/ referring to the argument. Passing a string directly to\n \/\/ them is preferred to passing a char pointer.\n hasDeclaration(method(anyOf(\n hasName(\"::llvm::StringRef::StringRef\"),\n hasName(\"::llvm::Twine::Twine\")))),\n argumentCountIs(1),\n \/\/ The only argument must have the form x.c_str() or p->c_str()\n \/\/ where the method is string::c_str(). StringRef also has\n \/\/ a constructor from string which is more efficient (avoids\n \/\/ strlen), so we can construct StringRef from the string\n \/\/ directly.\n hasArgument(\n 0,\n id(\"call\", memberCall(\n callee(id(\"member\", memberExpression())),\n callee(method(hasName(StringCStrMethod))),\n on(id(\"arg\", expression())))))),\n &Callback);\n return Tool.run(newFrontendActionFactory(&Finder));\n}\n\n<commit_msg>Added code to let the user specify a compilation database on the command line<commit_after>\/\/===- examples\/Tooling\/RemoveCStrCalls.cpp - Redundant c_str call removal ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a tool that prints replacements that remove redundant\n\/\/ calls of c_str() on strings.\n\/\/\n\/\/ Usage:\n\/\/ remove-cstr-calls <cmake-output-dir> <file1> <file2> ...\n\/\/\n\/\/ Where <cmake-output-dir> is a CMake build directory in which a file named\n\/\/ compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in\n\/\/ CMake to get this output).\n\/\/\n\/\/ <file1> ... specify the paths of files in the CMake source tree. This path\n\/\/ is looked up in the compile command database. If the path of a file is\n\/\/ absolute, it needs to point into CMake's source tree. If the path is\n\/\/ relative, the current working directory needs to be in the CMake source\n\/\/ tree and the file must be in a subdirectory of the current working\n\/\/ directory. \".\/\" prefixes in the relative files will be automatically\n\/\/ removed, but the rest of a relative path must be a suffix of a path in\n\/\/ the compile command line database.\n\/\/\n\/\/ For example, to use remove-cstr-calls on all files in a subtree of the\n\/\/ source tree, use:\n\/\/\n\/\/ \/path\/in\/subtree $ find . -name '*.cpp'|\n\/\/ xargs remove-cstr-calls \/path\/to\/build\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchers.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace llvm;\nusing clang::tooling::newFrontendActionFactory;\nusing clang::tooling::Replacement;\nusing clang::tooling::CompilationDatabase;\n\n\/\/ FIXME: Pull out helper methods in here into more fitting places.\n\n\/\/ Returns the text that makes up 'node' in the source.\n\/\/ Returns an empty string if the text cannot be found.\ntemplate <typename T>\nstatic std::string getText(const SourceManager &SourceManager, const T &Node) {\n SourceLocation StartSpellingLocatino =\n SourceManager.getSpellingLoc(Node.getLocStart());\n SourceLocation EndSpellingLocation =\n SourceManager.getSpellingLoc(Node.getLocEnd());\n if (!StartSpellingLocatino.isValid() || !EndSpellingLocation.isValid()) {\n return std::string();\n }\n bool Invalid = true;\n const char *Text =\n SourceManager.getCharacterData(StartSpellingLocatino, &Invalid);\n if (Invalid) {\n return std::string();\n }\n std::pair<FileID, unsigned> Start =\n SourceManager.getDecomposedLoc(StartSpellingLocatino);\n std::pair<FileID, unsigned> End =\n SourceManager.getDecomposedLoc(Lexer::getLocForEndOfToken(\n EndSpellingLocation, 0, SourceManager, LangOptions()));\n if (Start.first != End.first) {\n \/\/ Start and end are in different files.\n return std::string();\n }\n if (End.second < Start.second) {\n \/\/ Shuffling text with macros may cause this.\n return std::string();\n }\n return std::string(Text, End.second - Start.second);\n}\n\n\/\/ Return true if expr needs to be put in parens when it is an\n\/\/ argument of a prefix unary operator, e.g. when it is a binary or\n\/\/ ternary operator syntactically.\nstatic bool needParensAfterUnaryOperator(const Expr &ExprNode) {\n if (dyn_cast<clang::BinaryOperator>(&ExprNode) ||\n dyn_cast<clang::ConditionalOperator>(&ExprNode)) {\n return true;\n }\n if (const CXXOperatorCallExpr *op =\n dyn_cast<CXXOperatorCallExpr>(&ExprNode)) {\n return op->getNumArgs() == 2 &&\n op->getOperator() != OO_PlusPlus &&\n op->getOperator() != OO_MinusMinus &&\n op->getOperator() != OO_Call &&\n op->getOperator() != OO_Subscript;\n }\n return false;\n}\n\n\/\/ Format a pointer to an expression: prefix with '*' but simplify\n\/\/ when it already begins with '&'. Return empty string on failure.\nstatic std::string formatDereference(const SourceManager &SourceManager,\n const Expr &ExprNode) {\n if (const clang::UnaryOperator *Op =\n dyn_cast<clang::UnaryOperator>(&ExprNode)) {\n if (Op->getOpcode() == UO_AddrOf) {\n \/\/ Strip leading '&'.\n return getText(SourceManager, *Op->getSubExpr()->IgnoreParens());\n }\n }\n const std::string Text = getText(SourceManager, ExprNode);\n if (Text.empty()) return std::string();\n \/\/ Add leading '*'.\n if (needParensAfterUnaryOperator(ExprNode)) {\n return std::string(\"*(\") + Text + \")\";\n }\n return std::string(\"*\") + Text;\n}\n\nnamespace {\nclass FixCStrCall : public ast_matchers::MatchFinder::MatchCallback {\n public:\n FixCStrCall(tooling::Replacements *Replace)\n : Replace(Replace) {}\n\n virtual void run(const ast_matchers::MatchFinder::MatchResult &Result) {\n const CallExpr *Call =\n Result.Nodes.getStmtAs<CallExpr>(\"call\");\n const Expr *Arg =\n Result.Nodes.getStmtAs<Expr>(\"arg\");\n const bool Arrow =\n Result.Nodes.getStmtAs<MemberExpr>(\"member\")->isArrow();\n \/\/ Replace the \"call\" node with the \"arg\" node, prefixed with '*'\n \/\/ if the call was using '->' rather than '.'.\n const std::string ArgText = Arrow ?\n formatDereference(*Result.SourceManager, *Arg) :\n getText(*Result.SourceManager, *Arg);\n if (ArgText.empty()) return;\n\n Replace->insert(Replacement(*Result.SourceManager, Call, ArgText));\n }\n\n private:\n tooling::Replacements *Replace;\n};\n} \/\/ end namespace\n\nconst char *StringConstructor =\n \"::std::basic_string<char, std::char_traits<char>, std::allocator<char> >\"\n \"::basic_string\";\n\nconst char *StringCStrMethod =\n \"::std::basic_string<char, std::char_traits<char>, std::allocator<char> >\"\n \"::c_str\";\n\ncl::opt<std::string> BuildPath(\n cl::Positional,\n cl::desc(\"<build-path>\"));\n\ncl::list<std::string> SourcePaths(\n cl::Positional,\n cl::desc(\"<source0> [... <sourceN>]\"),\n cl::OneOrMore);\n\nint main(int argc, const char **argv) {\n llvm::OwningPtr<CompilationDatabase> Compilations(\n tooling::FixedCompilationDatabase::loadFromCommandLine(argc, argv));\n cl::ParseCommandLineOptions(argc, argv);\n if (!Compilations) {\n std::string ErrorMessage;\n Compilations.reset(\n CompilationDatabase::loadFromDirectory(BuildPath, ErrorMessage));\n if (!Compilations)\n llvm::report_fatal_error(ErrorMessage);\n }\n tooling::RefactoringTool Tool(*Compilations, SourcePaths);\n ast_matchers::MatchFinder Finder;\n FixCStrCall Callback(&Tool.getReplacements());\n Finder.addMatcher(\n constructorCall(\n hasDeclaration(method(hasName(StringConstructor))),\n argumentCountIs(2),\n \/\/ The first argument must have the form x.c_str() or p->c_str()\n \/\/ where the method is string::c_str(). We can use the copy\n \/\/ constructor of string instead (or the compiler might share\n \/\/ the string object).\n hasArgument(\n 0,\n id(\"call\", memberCall(\n callee(id(\"member\", memberExpression())),\n callee(method(hasName(StringCStrMethod))),\n on(id(\"arg\", expression()))))),\n \/\/ The second argument is the alloc object which must not be\n \/\/ present explicitly.\n hasArgument(\n 1,\n defaultArgument())),\n &Callback);\n Finder.addMatcher(\n constructorCall(\n \/\/ Implicit constructors of these classes are overloaded\n \/\/ wrt. string types and they internally make a StringRef\n \/\/ referring to the argument. Passing a string directly to\n \/\/ them is preferred to passing a char pointer.\n hasDeclaration(method(anyOf(\n hasName(\"::llvm::StringRef::StringRef\"),\n hasName(\"::llvm::Twine::Twine\")))),\n argumentCountIs(1),\n \/\/ The only argument must have the form x.c_str() or p->c_str()\n \/\/ where the method is string::c_str(). StringRef also has\n \/\/ a constructor from string which is more efficient (avoids\n \/\/ strlen), so we can construct StringRef from the string\n \/\/ directly.\n hasArgument(\n 0,\n id(\"call\", memberCall(\n callee(id(\"member\", memberExpression())),\n callee(method(hasName(StringCStrMethod))),\n on(id(\"arg\", expression())))))),\n &Callback);\n return Tool.run(newFrontendActionFactory(&Finder));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2017 Baldur Karlsson\n * Copyright (c) 2014 Crytek\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n\/\/ in this file we define the shell extension that renderdoc sets up to be able to\n\/\/ display thumbnails of captures in windows explorer. We register as a thumbnail\n\/\/ provider and either the installer or the UI installs the appropriate registry keys.\n\n#include <thumbcache.h>\n#include <windows.h>\n#include \"common\/common.h\"\n#include \"core\/core.h\"\n#include \"jpeg-compressor\/jpgd.h\"\n#include \"serialise\/serialiser.h\"\n\n\/\/ {5D6BF029-A6BA-417A-8523-120492B1DCE3}\nstatic const GUID CLSID_RDCThumbnailProvider = {0x5d6bf029,\n 0xa6ba,\n 0x417a,\n {0x85, 0x23, 0x12, 0x4, 0x92, 0xb1, 0xdc, 0xe3}};\n\nunsigned int numProviders = 0;\n\nstruct RDCThumbnailProvider : public IThumbnailProvider, IInitializeWithStream\n{\n unsigned int m_iRefcount;\n bool m_Inited;\n Serialiser *m_Ser;\n\n RDCThumbnailProvider() : m_iRefcount(1), m_Inited(false), m_Ser(NULL)\n {\n InterlockedIncrement(&numProviders);\n }\n\n virtual ~RDCThumbnailProvider()\n {\n InterlockedDecrement(&numProviders);\n SAFE_DELETE(m_Ser);\n }\n\n ULONG STDMETHODCALLTYPE AddRef()\n {\n InterlockedIncrement(&m_iRefcount);\n return m_iRefcount;\n }\n ULONG STDMETHODCALLTYPE Release()\n {\n unsigned int ret = InterlockedDecrement(&m_iRefcount);\n if(ret == 0)\n delete this;\n return ret;\n }\n\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)\n {\n if(riid == CLSID_RDCThumbnailProvider)\n {\n *ppvObject = (void *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)(IThumbnailProvider *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IThumbnailProvider))\n {\n *ppvObject = (void *)(IThumbnailProvider *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IInitializeWithStream))\n {\n *ppvObject = (void *)(IInitializeWithStream *)this;\n AddRef();\n return S_OK;\n }\n\n *ppvObject = NULL;\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE Initialize(IStream *pstream, DWORD grfMode)\n {\n if(m_Inited)\n return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);\n\n byte *buf = new byte[2 * 1024 * 1024 + 1];\n ULONG numRead = 0;\n HRESULT hr = pstream->Read(buf, 2 * 1024 * 1024, &numRead);\n\n if(hr != S_OK && hr != S_FALSE)\n {\n delete[] buf;\n return E_INVALIDARG;\n }\n\n RDCLOG(\"RDCThumbnailProvider Initialize read %d bytes from file\", numRead);\n\n m_Ser = new Serialiser(numRead, buf, true);\n\n delete[] buf;\n\n m_Inited = true;\n\n return S_OK;\n }\n\n virtual HRESULT STDMETHODCALLTYPE GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha)\n {\n RDCLOG(\"RDCThumbnailProvider GetThumbnail %d\", cx);\n\n if(!m_Inited || !m_Ser)\n {\n RDCERR(\"Not initialized\");\n return E_NOTIMPL;\n }\n\n if(m_Ser->HasError())\n {\n RDCERR(\"Problem serialising file\");\n return E_NOTIMPL;\n }\n\n int ctx = m_Ser->PushContext(NULL, NULL, 1, false);\n\n if(ctx != THUMBNAIL_DATA)\n {\n return E_NOTIMPL;\n }\n\n bool HasThumbnail = false;\n m_Ser->Serialise(NULL, HasThumbnail);\n\n if(!HasThumbnail)\n {\n return E_NOTIMPL;\n }\n\n byte *jpgbuf = NULL;\n size_t thumblen = 0;\n uint32_t thumbwidth = 0, thumbheight = 0;\n {\n m_Ser->Serialise(\"ThumbWidth\", thumbwidth);\n m_Ser->Serialise(\"ThumbHeight\", thumbheight);\n m_Ser->SerialiseBuffer(\"ThumbnailPixels\", jpgbuf, thumblen);\n }\n\n if(jpgbuf == NULL)\n {\n return E_NOTIMPL;\n }\n\n int w = thumbwidth;\n int h = thumbheight;\n int comp = 3;\n byte *thumbpixels =\n jpgd::decompress_jpeg_image_from_memory(jpgbuf, (int)thumblen, &w, &h, &comp, 3);\n\n delete[] jpgbuf;\n\n float aspect = float(thumbwidth) \/ float(thumbheight);\n\n BITMAPV5HEADER bi;\n RDCEraseEl(bi);\n bi.bV5Size = sizeof(BITMAPV5HEADER);\n bi.bV5Width = RDCMIN((LONG)cx, (LONG)thumbwidth);\n bi.bV5Height = (LONG)(bi.bV5Width \/ aspect);\n bi.bV5Planes = 1;\n bi.bV5BitCount = 32;\n bi.bV5Compression = BI_BITFIELDS;\n bi.bV5RedMask = 0x00FF0000;\n bi.bV5GreenMask = 0x0000FF00;\n bi.bV5BlueMask = 0x000000FF;\n bi.bV5AlphaMask = 0xFF000000;\n\n HDC dc = ::CreateCompatibleDC(0);\n\n RGBQUAD *pArgb;\n *phbmp = ::CreateDIBSection(dc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, (void **)&pArgb, NULL, 0);\n\n float widthf = float(thumbwidth);\n float heightf = float(thumbheight);\n\n if(*phbmp)\n {\n DWORD *pBits = (DWORD *)pArgb;\n for(int y = 0; y < bi.bV5Height; y++)\n {\n for(int x = 0; x < bi.bV5Width; x++)\n {\n *pBits = 0xff000000;\n\n byte *srcPixel = NULL;\n\n float xf = float(x) \/ float(bi.bV5Width);\n float yf = float(bi.bV5Height - y - 1) \/ float(bi.bV5Height);\n\n srcPixel = &thumbpixels[3 * (uint32_t(xf * widthf) + thumbwidth * uint32_t(yf * heightf))];\n\n *pBits |= (srcPixel[0] << 16);\n *pBits |= (srcPixel[1] << 8);\n *pBits |= (srcPixel[2] << 0);\n\n pBits++;\n }\n }\n }\n\n free(thumbpixels);\n\n DeleteObject(dc);\n\n *pdwAlpha = WTSAT_ARGB;\n\n return S_OK;\n }\n};\n\nstruct RDCThumbnailProviderFactory : public IClassFactory\n{\n unsigned int m_iRefcount;\n\n RDCThumbnailProviderFactory() : m_iRefcount(1), locked(false) {}\n virtual ~RDCThumbnailProviderFactory() {}\n ULONG STDMETHODCALLTYPE AddRef()\n {\n InterlockedIncrement(&m_iRefcount);\n return m_iRefcount;\n }\n ULONG STDMETHODCALLTYPE Release()\n {\n unsigned int ret = InterlockedDecrement(&m_iRefcount);\n if(ret == 0)\n delete this;\n return ret;\n }\n\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)\n {\n if(riid == __uuidof(IClassFactory))\n {\n *ppvObject = (void *)(IClassFactory *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)this;\n AddRef();\n return S_OK;\n }\n\n *ppvObject = NULL;\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject)\n {\n if(pUnkOuter != NULL)\n {\n return CLASS_E_NOAGGREGATION;\n }\n\n if(riid == CLSID_RDCThumbnailProvider)\n {\n *ppvObject = (void *)(new RDCThumbnailProvider());\n return S_OK;\n }\n else if(riid == __uuidof(IThumbnailProvider))\n {\n *ppvObject = (void *)(new RDCThumbnailProvider());\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)(IThumbnailProvider *)(new RDCThumbnailProvider());\n return S_OK;\n }\n\n *ppvObject = NULL;\n\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE LockServer(BOOL fLock)\n {\n locked = (fLock == TRUE);\n return S_OK;\n }\n\n bool locked;\n};\n\n_Check_return_ STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, LPVOID *ppv)\n{\n if(rclsid == CLSID_RDCThumbnailProvider)\n {\n if(ppv)\n *ppv = (LPVOID)(new RDCThumbnailProviderFactory);\n return S_OK;\n }\n\n if(ppv)\n *ppv = NULL;\n\n return CLASS_E_CLASSNOTAVAILABLE;\n}\n\nSTDAPI DllCanUnloadNow()\n{\n if(numProviders > 0)\n return S_FALSE;\n\n return S_OK;\n}\n<commit_msg>Update win32 thumbnail shell extension to use RDCFile to fetch thumbnail<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2015-2017 Baldur Karlsson\n * Copyright (c) 2014 Crytek\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n\/\/ in this file we define the shell extension that renderdoc sets up to be able to\n\/\/ display thumbnails of captures in windows explorer. We register as a thumbnail\n\/\/ provider and either the installer or the UI installs the appropriate registry keys.\n\n#include <thumbcache.h>\n#include <windows.h>\n#include \"3rdparty\/stb\/stb_image_resize.h\"\n#include \"common\/common.h\"\n#include \"core\/core.h\"\n#include \"jpeg-compressor\/jpgd.h\"\n#include \"serialise\/rdcfile.h\"\n\n\/\/ {5D6BF029-A6BA-417A-8523-120492B1DCE3}\nstatic const GUID CLSID_RDCThumbnailProvider = {0x5d6bf029,\n 0xa6ba,\n 0x417a,\n {0x85, 0x23, 0x12, 0x4, 0x92, 0xb1, 0xdc, 0xe3}};\n\nunsigned int numProviders = 0;\n\nstruct RDCThumbnailProvider : public IThumbnailProvider, IInitializeWithStream\n{\n unsigned int m_iRefcount;\n bool m_Inited;\n RDCFile m_RDC;\n\n RDCThumbnailProvider() : m_iRefcount(1), m_Inited(false) { InterlockedIncrement(&numProviders); }\n virtual ~RDCThumbnailProvider() { InterlockedDecrement(&numProviders); }\n ULONG STDMETHODCALLTYPE AddRef()\n {\n InterlockedIncrement(&m_iRefcount);\n return m_iRefcount;\n }\n ULONG STDMETHODCALLTYPE Release()\n {\n unsigned int ret = InterlockedDecrement(&m_iRefcount);\n if(ret == 0)\n delete this;\n return ret;\n }\n\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)\n {\n if(riid == CLSID_RDCThumbnailProvider)\n {\n *ppvObject = (void *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)(IThumbnailProvider *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IThumbnailProvider))\n {\n *ppvObject = (void *)(IThumbnailProvider *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IInitializeWithStream))\n {\n *ppvObject = (void *)(IInitializeWithStream *)this;\n AddRef();\n return S_OK;\n }\n\n *ppvObject = NULL;\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE Initialize(IStream *pstream, DWORD grfMode)\n {\n if(m_Inited)\n return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);\n\n byte *buf = new byte[2 * 1024 * 1024 + 1];\n ULONG numRead = 0;\n HRESULT hr = pstream->Read(buf, 2 * 1024 * 1024, &numRead);\n\n if(hr != S_OK && hr != S_FALSE)\n {\n delete[] buf;\n return E_INVALIDARG;\n }\n\n RDCDEBUG(\"RDCThumbnailProvider Initialize read %d bytes from file\", numRead);\n\n m_RDC.Open(std::vector<byte>(buf, buf + numRead));\n\n delete[] buf;\n\n m_Inited = true;\n\n return S_OK;\n }\n\n virtual HRESULT STDMETHODCALLTYPE GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha)\n {\n RDCDEBUG(\"RDCThumbnailProvider GetThumbnail %d\", cx);\n\n if(!m_Inited)\n {\n RDCERR(\"Not initialized\");\n return E_NOTIMPL;\n }\n\n if(m_RDC.ErrorCode() != ContainerError::NoError)\n {\n RDCERR(\"Problem opening file\");\n return E_NOTIMPL;\n }\n\n const RDCThumb &thumb = m_RDC.GetThumbnail();\n\n const byte *jpgbuf = thumb.pixels;\n size_t thumblen = thumb.len;\n uint32_t thumbwidth = thumb.width, thumbheight = thumb.height;\n\n if(jpgbuf == NULL)\n return E_NOTIMPL;\n\n int w = thumbwidth;\n int h = thumbheight;\n int comp = 3;\n byte *thumbpixels =\n jpgd::decompress_jpeg_image_from_memory(jpgbuf, (int)thumblen, &w, &h, &comp, 3);\n\n float aspect = float(thumbwidth) \/ float(thumbheight);\n\n BITMAPV5HEADER bi;\n RDCEraseEl(bi);\n bi.bV5Size = sizeof(BITMAPV5HEADER);\n bi.bV5Width = RDCMIN((LONG)cx, (LONG)thumbwidth);\n bi.bV5Height = (LONG)(bi.bV5Width \/ aspect);\n bi.bV5Planes = 1;\n bi.bV5BitCount = 32;\n bi.bV5Compression = BI_BITFIELDS;\n bi.bV5RedMask = 0x00FF0000;\n bi.bV5GreenMask = 0x0000FF00;\n bi.bV5BlueMask = 0x000000FF;\n bi.bV5AlphaMask = 0xFF000000;\n\n if(cx != thumbwidth)\n {\n byte *resizedpixels = (byte *)malloc(3 * bi.bV5Width * bi.bV5Height);\n\n stbir_resize_uint8_srgb(thumbpixels, thumbwidth, thumbheight, 0, resizedpixels, bi.bV5Width,\n bi.bV5Height, 0, 3, -1, 0);\n\n free(thumbpixels);\n\n thumbpixels = resizedpixels;\n }\n\n HDC dc = ::CreateCompatibleDC(0);\n\n RGBQUAD *pArgb;\n *phbmp = ::CreateDIBSection(dc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, (void **)&pArgb, NULL, 0);\n\n if(*phbmp)\n {\n DWORD *pBits = (DWORD *)pArgb;\n for(int y = bi.bV5Height - 1; y >= 0; y--)\n {\n for(int x = 0; x < bi.bV5Width; x++)\n {\n byte *srcPixel = &thumbpixels[3 * (x + bi.bV5Width * y)];\n\n *pBits = 0xff << 24 | (srcPixel[0] << 16) | (srcPixel[1] << 8) | (srcPixel[2] << 0);\n\n pBits++;\n }\n }\n }\n\n free(thumbpixels);\n\n DeleteObject(dc);\n\n *pdwAlpha = WTSAT_ARGB;\n\n return S_OK;\n }\n};\n\nstruct RDCThumbnailProviderFactory : public IClassFactory\n{\n unsigned int m_iRefcount;\n\n RDCThumbnailProviderFactory() : m_iRefcount(1), locked(false) {}\n virtual ~RDCThumbnailProviderFactory() {}\n ULONG STDMETHODCALLTYPE AddRef()\n {\n InterlockedIncrement(&m_iRefcount);\n return m_iRefcount;\n }\n ULONG STDMETHODCALLTYPE Release()\n {\n unsigned int ret = InterlockedDecrement(&m_iRefcount);\n if(ret == 0)\n delete this;\n return ret;\n }\n\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject)\n {\n if(riid == __uuidof(IClassFactory))\n {\n *ppvObject = (void *)(IClassFactory *)this;\n AddRef();\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)this;\n AddRef();\n return S_OK;\n }\n\n *ppvObject = NULL;\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject)\n {\n if(pUnkOuter != NULL)\n {\n return CLASS_E_NOAGGREGATION;\n }\n\n if(riid == CLSID_RDCThumbnailProvider)\n {\n *ppvObject = (void *)(new RDCThumbnailProvider());\n return S_OK;\n }\n else if(riid == __uuidof(IThumbnailProvider))\n {\n *ppvObject = (void *)(new RDCThumbnailProvider());\n return S_OK;\n }\n else if(riid == __uuidof(IUnknown))\n {\n *ppvObject = (void *)(IUnknown *)(IThumbnailProvider *)(new RDCThumbnailProvider());\n return S_OK;\n }\n\n *ppvObject = NULL;\n\n return E_NOINTERFACE;\n }\n\n virtual HRESULT STDMETHODCALLTYPE LockServer(BOOL fLock)\n {\n locked = (fLock == TRUE);\n return S_OK;\n }\n\n bool locked;\n};\n\n_Check_return_ STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, LPVOID *ppv)\n{\n if(rclsid == CLSID_RDCThumbnailProvider)\n {\n if(ppv)\n *ppv = (LPVOID)(new RDCThumbnailProviderFactory);\n return S_OK;\n }\n\n if(ppv)\n *ppv = NULL;\n\n return CLASS_E_CLASSNOTAVAILABLE;\n}\n\nSTDAPI DllCanUnloadNow()\n{\n if(numProviders > 0)\n return S_FALSE;\n\n return S_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-pymor project:\n\/\/ https:\/\/github.com\/pyMor\/dune-pymor\n\/\/ Copyright Holders: Felix Albrecht, Stephan Rave\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n#define DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <dune\/common\/float_cmp.hh>\n\nnamespace Dune {\nnamespace Pymor {\nnamespace LA {\n\n\nclass VectorInterface\n{\npublic:\n\n virtual ~VectorInterface() {}\n\n \/**\n * \\brief A unique (per class, not per instance) identifier.\n * \\return\n *\/\n virtual std::string type() const = 0;\n\n \/**\n * \\brief A list of types which are compatible.\n * \\return A list of types which are compatible.\n *\/\n virtual std::vector< std::string > compatibleTypes() const = 0;\n\n \/**\n * \\brief The dimension of the vector.\n * \\return The dimension of the vector.\n *\/\n virtual int dim() const = 0;\n\n \/**\n * \\brief Check vectors for equality.\n * Equality of two vectors is defined as in Dune::FloatCmp componentwise.\n * \\param other A vector of same dimension to compare with.\n * \\param epsilon See Dune::FloatCmp.\n * \\return Truth value of the comparison.\n *\/\n virtual bool almost_equal(const VectorInterface* other,\n const double epsilon = Dune::FloatCmp::DefaultEpsilon< double >::value()) const = 0;\n\n \/**\n * \\brief BLAS SCAL operation (in-place sclar multiplication).\n * \\param alpha The scalar coefficient with which the vector is multiplied.\n *\/\n virtual void scal(const double alpha) = 0;\n\n \/**\n * \\brief BLAS AXPY operation.\n * \\param alpha The scalar coefficient with which the vector is multiplied\n * \\param x Vector that is to be added.\n *\/\n virtual void axpy(const double alpha, const VectorInterface* x) = 0;\n\n \/**\n * \\brief Computes the scalar products between two vectors.\n * \\param other The second factor.\n * \\return The scalar product.\n *\/\n virtual double dot(const VectorInterface* other) const = 0;\n\n \/**\n * \\brief The l1-norm of the vector.\n * \\return The l1-norm of the vector.\n *\/\n virtual double l1_norm() const = 0;\n\n \/**\n * \\brief The l2-norm of the vector.\n * \\return The l2-norm of the vector.\n *\/\n virtual double l2_norm() const = 0;\n\n \/**\n * \\brief The l-infintiy-norm of the vector.\n * \\return The l-infintiy-norm of the vector.\n *\/\n virtual double sup_norm() const = 0;\n\n \/**\n * \\brief Extract components of the vector.\n * \\param component_indices Indices of the vector components that are to be returned.\n * \\return A Dune::DynamicVector `result` such that `result[i]` is the `component_indices[i]`-th\n component of the vector.\n *\/\n virtual std::vector< double > components(const std::vector< int >& component_indices) const = 0;\n\n \/**\n * \\brief The maximum absolute value of the vector.\n * \\return A pair< max_ind, max_val >, where max_ind is the index at which the maximum is attained and max_val is the\n * absolute value.\n *\/\n virtual std::vector< double > amax() const = 0;\n\n \/**\n * \\brief Adds two vectors.\n * \\param other The right summand.\n * \\return The sum of this and other.\n *\/\n virtual VectorInterface* add(const VectorInterface* other) const = 0;\n\n \/**\n * \\brief Inplace variant of add().\n * \\param other The right summand.\n *\/\n virtual void iadd(const VectorInterface* other) = 0;\n\n \/**\n * \\brief Subtracts two vectors.\n * \\param other The subtrahend.\n * \\return The difference between this and other.\n *\/\n virtual VectorInterface* sub(const VectorInterface* other) const = 0;\n\n \/**\n * \\brief Inplace variant of sub().\n * \\param other The subtrahend.\n *\/\n virtual void isub(const VectorInterface* other) = 0;\n}; \/\/ class VectorInterface\n\n\n} \/\/ namespace LA\n} \/\/ namespace Pymor\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n<commit_msg>[la.container.interfaces] add proper exceptions<commit_after>\/\/ This file is part of the dune-pymor project:\n\/\/ https:\/\/github.com\/pyMor\/dune-pymor\n\/\/ Copyright Holders: Felix Albrecht, Stephan Rave\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n#define DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <dune\/common\/float_cmp.hh>\n\n#include <dune\/pymor\/common\/exceptions.hh>\n\nnamespace Dune {\nnamespace Pymor {\nnamespace LA {\n\n\nclass VectorInterface\n{\npublic:\n\n virtual ~VectorInterface() {}\n\n \/**\n * \\brief A unique (per class, not per instance) identifier.\n * \\return A unique (per class, not per instance) identifier.\n *\/\n virtual std::string type() const = 0;\n\n \/**\n * \\brief A list of types which are compatible.\n * \\return A list of types which are compatible.\n *\/\n virtual std::vector< std::string > compatibleTypes() const = 0;\n\n \/**\n * \\brief The dimension of the vector.\n * \\return The dimension of the vector.\n *\/\n virtual int dim() const = 0;\n\n \/**\n * \\brief Check vectors for equality.\n * Equality of two vectors is defined as in Dune::FloatCmp componentwise.\n * \\param other A vector of same dimension to compare with.\n * \\param epsilon See Dune::FloatCmp.\n * \\return Truth value of the comparison.\n *\/\n virtual bool almost_equal(const VectorInterface* other,\n const double epsilon = Dune::FloatCmp::DefaultEpsilon< double >::value()) const\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief BLAS SCAL operation (in-place sclar multiplication).\n * \\param alpha The scalar coefficient with which the vector is multiplied.\n *\/\n virtual void scal(const double alpha) = 0;\n\n \/**\n * \\brief BLAS AXPY operation.\n * \\param alpha The scalar coefficient with which the vector is multiplied\n * \\param x Vector that is to be added.\n *\/\n virtual void axpy(const double alpha, const VectorInterface* x)\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief Computes the scalar products between two vectors.\n * \\param other The second factor.\n * \\return The scalar product.\n *\/\n virtual double dot(const VectorInterface* other) const\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief The l1-norm of the vector.\n * \\return The l1-norm of the vector.\n *\/\n virtual double l1_norm() const = 0;\n\n \/**\n * \\brief The l2-norm of the vector.\n * \\return The l2-norm of the vector.\n *\/\n virtual double l2_norm() const = 0;\n\n \/**\n * \\brief The l-infintiy-norm of the vector.\n * \\return The l-infintiy-norm of the vector.\n *\/\n virtual double sup_norm() const = 0;\n\n \/**\n * \\brief Extract components of the vector.\n * \\param component_indices Indices of the vector components that are to be returned.\n * \\return A Dune::DynamicVector `result` such that `result[i]` is the `component_indices[i]`-th\n component of the vector.\n *\/\n virtual std::vector< double > components(const std::vector< int >& component_indices) const\n throw (Exception::sizes_do_not_match, Exception::index_out_of_range) = 0;\n\n \/**\n * \\brief The maximum absolute value of the vector.\n * \\return A pair< max_ind, max_val >, where max_ind is the index at which the maximum is attained and max_val is the\n * absolute value.\n *\/\n virtual std::vector< double > amax() const = 0;\n\n \/**\n * \\brief Adds two vectors.\n * \\param other The right summand.\n * \\return The sum of this and other.\n *\/\n virtual VectorInterface* add(const VectorInterface* other) const\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief Inplace variant of add().\n * \\param other The right summand.\n *\/\n virtual void iadd(const VectorInterface* other)\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief Subtracts two vectors.\n * \\param other The subtrahend.\n * \\return The difference between this and other.\n *\/\n virtual VectorInterface* sub(const VectorInterface* other) const\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n\n \/**\n * \\brief Inplace variant of sub().\n * \\param other The subtrahend.\n *\/\n virtual void isub(const VectorInterface* other)\n throw (Exception::not_implemented_for_this_combination, Exception::sizes_do_not_match) = 0;\n}; \/\/ class VectorInterface\n\n\n} \/\/ namespace LA\n} \/\/ namespace Pymor\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_PYMOR_LA_CONTAINER_INTERFACES_HH\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\n\n#include <botan\/botan.h>\n#include <botan\/look_pk.h>\n#include <botan\/dsa.h>\n#include <botan\/numthry.h>\nusing namespace Botan;\n\nbool check(std::map<std::string, std::string>);\n\nint main()\n {\n try {\n LibraryInitializer init(\"use_engines\");\n\n std::ifstream in(\"PQGGen.rsp\");\n if(!in)\n throw Exception(\"Can't open response file\");\n\n std::map<std::string, std::string> inputs;\n\n while(in.good())\n {\n std::string line;\n std::getline(in, line);\n\n if(line == \"\" || line[0] == '[' || line[0] == '#')\n continue;\n\n std::vector<std::string> name_and_val = split_on(line, '=');\n\n if(name_and_val.size() != 2)\n throw Decoding_Error(\"Unexpected input: \" + line);\n\n name_and_val[0].erase(name_and_val[0].size()-1);\n name_and_val[1].erase(0, 1);\n\n std::string name = name_and_val[0], value = name_and_val[1];\n\n inputs[name] = value;\n\n if(name == \"H\")\n {\n bool result = check(inputs);\n std::cout << \".\" << std::flush;\n if(result == false)\n {\n std::cout << \" Check failed\\n\";\n\n std::map<std::string, std::string>::const_iterator i;\n\n for(i = inputs.begin(); i != inputs.end(); i++)\n std::cout << i->first << \" = \" << i->second << \"\\n\";\n\n std::cout << \"\\n\";\n }\n\n inputs.clear();\n }\n }\n }\n catch(std::exception& e)\n {\n std::cout << e.what() << std::endl;\n return 1;\n }\n return 0;\n }\n\nbool check(std::map<std::string, std::string> inputs)\n {\n BigInt p(\"0x\"+inputs[\"P\"]),\n q(\"0x\"+inputs[\"Q\"]),\n g(\"0x\"+inputs[\"G\"]),\n h(\"0x\"+inputs[\"H\"]);\n\n if(h < 1 || h >= p-1) return false;\n\n u32bit c = to_u32bit(inputs[\"c\"]);\n\n Pipe pipe(new Hex_Decoder);\n pipe.process_msg(inputs[\"Seed\"]);\n SecureVector<byte> seed = pipe.read_all();\n\n BigInt our_p, our_q;\n\n bool found = generate_dsa_primes(our_p, our_q, seed, seed.size(),\n p.bits(), 0);\n\n if(!found) \/* bad seed *\/\n return false;\n\n if(our_p != p) return false;\n if(our_q != q) return false;\n\n BigInt our_g = power_mod(h, (p-1)\/q, p);\n\n if(our_g != g) return false;\n\n return true;\n }\n<commit_msg>Create a RNG object, update for new interface for DSA paramater generation<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\n#include <memory>\n\n#include <botan\/botan.h>\n#include <botan\/look_pk.h>\n#include <botan\/dsa.h>\n#include <botan\/numthry.h>\n#include <botan\/dl_group.h>\nusing namespace Botan;\n\nbool check(RandomNumberGenerator& rng,\n std::map<std::string, std::string>);\n\nint main()\n {\n try {\n LibraryInitializer init(\"use_engines\");\n\n std::auto_ptr<RandomNumberGenerator> rng(\n RandomNumberGenerator::make_rng());\n\n std::ifstream in(\"PQGGen.rsp\");\n if(!in)\n throw Exception(\"Can't open response file\");\n\n std::map<std::string, std::string> inputs;\n\n while(in.good())\n {\n std::string line;\n std::getline(in, line);\n\n if(line == \"\" || line[0] == '[' || line[0] == '#')\n continue;\n\n std::vector<std::string> name_and_val = split_on(line, '=');\n\n if(name_and_val.size() != 2)\n throw Decoding_Error(\"Unexpected input: \" + line);\n\n name_and_val[0].erase(name_and_val[0].size()-1);\n name_and_val[1].erase(0, 1);\n\n std::string name = name_and_val[0], value = name_and_val[1];\n\n inputs[name] = value;\n\n if(name == \"H\")\n {\n bool result = check(*rng, inputs);\n std::cout << \".\" << std::flush;\n if(result == false)\n {\n std::cout << \" Check failed\\n\";\n\n std::map<std::string, std::string>::const_iterator i;\n\n for(i = inputs.begin(); i != inputs.end(); i++)\n std::cout << i->first << \" = \" << i->second << \"\\n\";\n\n std::cout << \"\\n\";\n }\n\n inputs.clear();\n }\n }\n }\n catch(std::exception& e)\n {\n std::cout << e.what() << std::endl;\n return 1;\n }\n return 0;\n }\n\nbool check(RandomNumberGenerator& rng,\n std::map<std::string, std::string> inputs)\n {\n BigInt p(\"0x\"+inputs[\"P\"]),\n q(\"0x\"+inputs[\"Q\"]),\n g(\"0x\"+inputs[\"G\"]),\n h(\"0x\"+inputs[\"H\"]);\n\n if(h < 1 || h >= p-1) return false;\n\n \/\/u32bit c = to_u32bit(inputs[\"c\"]);\n\n Pipe pipe(new Hex_Decoder);\n pipe.process_msg(inputs[\"Seed\"]);\n SecureVector<byte> seed = pipe.read_all();\n\n BigInt our_p, our_q;\n\n u32bit qbits = (p.bits() <= 1024) ? 160 : 256;\n\n bool found = DL_Group::generate_dsa_primes(rng, our_p, our_q,\n p.bits(), qbits, seed);\n\n if(!found) \/* bad seed *\/\n return false;\n\n if(our_p != p) return false;\n if(our_q != q) return false;\n\n BigInt our_g = power_mod(h, (p-1)\/q, p);\n\n if(our_g != g) return false;\n\n return true;\n }\n<|endoftext|>"} {"text":"<commit_before>#include <GLFW\/glfw3.h>\n\n#define LOGURU_IMPLEMENTATION 1\n#include \"app\/EmberApp.h\"\n\nint get_log_level();\nvoid test_loguru( int argc, char **argv );\n\nint main( int argc, char **argv )\n{\n\tusing namespace ember::app;\n\t\n\tEmberApp *app = new EmberApp();\n\tapp->Initialize();\n\t\n\ttest_loguru( argc, argv );\n\t\n\tapp->Run();\n\t\n\tdelete app;\n\tapp = nullptr;\n\t\n\treturn 0;\n}\n\nint get_log_level()\n{\n\treturn loguru::Verbosity_4;\n}\n\nvoid test_loguru( int argc, char **argv )\n{\n\tbool badness = false;\n\tint length = 10;\n\tint a = 5;\n\tint b = 5;\n\t\n\tLOG_SCOPE_F( INFO, \"Will indent all log messages within this scope.\" );\n\tLOG_F( INFO, \"I'm hungry for some %.3f!\", 3.14159 );\n\tLOG_F( 2, \"Will only show if verbosity is 2 or higher\" );\n\tVLOG_F( get_log_level(), \"Use vlog for dynamic log level (integer in the range 0-9, inclusive)\" );\n\tLOG_IF_F( ERROR, badness, \"Will only show if badness happens\" );\n\tCHECK_GT_F( length, 0 ); \/\/ Will print the value of `length` on failure.\n\tCHECK_EQ_F( a, b, \"You can also supply a custom message, like to print something: %d\", a + b );\n}\n<commit_msg>trying out creating & destroying lua.<commit_after>#include <GLFW\/glfw3.h>\n\n#define LOGURU_IMPLEMENTATION 1\n#include \"app\/EmberApp.h\"\n\nextern \"C\" {\n#include <lua.h>\n#include <lauxlib.h>\n#include <lualib.h>\n}\n\nint get_log_level();\nvoid test_loguru( int argc, char **argv );\n\nint main( int argc, char **argv )\n{\n\tusing namespace ember::app;\n\t\n\tEmberApp *app = new EmberApp();\n\tapp->Initialize();\n\t\n\ttest_loguru( argc, argv );\n\t\n\tapp->Run();\n\t\n\tdelete app;\n\tapp = nullptr;\n\t\n\tlua_State *L = luaL_newstate();\n\tluaL_openlibs( L );\n\t\n\tint error = 0;\n\tstd::string luaScript( \"p = 5\\nprint(p)\" );\n\t\n\terror = luaL_loadbuffer( L, luaScript.c_str(), luaScript.size(), \"line\" );\n\tlua_pcall( L, 0, 0, 0 );\n\t\n\tlua_close( L );\n\t\n\treturn 0;\n}\n\nint get_log_level()\n{\n\treturn loguru::Verbosity_4;\n}\n\nvoid test_loguru( int argc, char **argv )\n{\n\tbool badness = false;\n\tint length = 10;\n\tint a = 5;\n\tint b = 5;\n\t\n\tLOG_SCOPE_F( INFO, \"Will indent all log messages within this scope.\" );\n\tLOG_F( INFO, \"I'm hungry for some %.3f!\", 3.14159 );\n\tLOG_F( 2, \"Will only show if verbosity is 2 or higher\" );\n\tVLOG_F( get_log_level(), \"Use vlog for dynamic log level (integer in the range 0-9, inclusive)\" );\n\tLOG_IF_F( ERROR, badness, \"Will only show if badness happens\" );\n\tCHECK_GT_F( length, 0 ); \/\/ Will print the value of `length` on failure.\n\tCHECK_EQ_F( a, b, \"You can also supply a custom message, like to print something: %d\", a + b );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Authors: Tom Stellard <thomas.stellard@amd.com>\n *\n *\/\n#include \"radeon_llvm_emit.h\"\n\n#if HAVE_LLVM < 0x0303\n#include <llvm\/LLVMContext.h>\n#include <llvm\/Module.h>\n#include <llvm\/Function.h>\n#include <llvm\/DataLayout.h>\n#else\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Function.h>\n#include <llvm\/IR\/DataLayout.h>\n#endif\n\n#include <llvm\/PassManager.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/Support\/FormattedStream.h>\n#include <llvm\/Support\/Host.h>\n#include <llvm\/Support\/IRReader.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Support\/TargetRegistry.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Threading.h>\n#include <llvm\/Target\/TargetMachine.h>\n#include <llvm\/Transforms\/Scalar.h>\n#include <llvm-c\/Target.h>\n\n#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n\nusing namespace llvm;\n\nnamespace {\n\nclass LLVMEnsureMultithreaded {\npublic:\n LLVMEnsureMultithreaded()\n {\n llvm_start_multithreaded();\n }\n};\n\nstatic LLVMEnsureMultithreaded lLVMEnsureMultithreaded;\n\n}\n\n\/**\n * Set the shader type we want to compile\n *\n * @param type shader type to set\n *\/\nextern \"C\" void\nradeon_llvm_shader_type(LLVMValueRef F, unsigned type)\n{\n Function *Func = unwrap<Function>(F);\n int Idx = AttributeSet::FunctionIndex;\n AttrBuilder B;\n char Str[2];\n\n sprintf(Str, \"%1d\", type);\n B.addAttribute(\"ShaderType\", Str);\n\n AttributeSet Set = AttributeSet::get(Func->getContext(), Idx, B);\n Func->addAttributes(Idx, Set);\n}\n\n\/**\n * Compile an LLVM module to machine code.\n *\n * @param bytes This function allocates memory for the byte stream, it is the\n * caller's responsibility to free it.\n *\/\nextern \"C\" unsigned\nradeon_llvm_compile(LLVMModuleRef M, unsigned char ** bytes,\n unsigned * byte_count, const char * gpu_family,\n unsigned dump) {\n\n Triple AMDGPUTriple(sys::getDefaultTargetTriple());\n\n LLVMInitializeR600TargetInfo();\n LLVMInitializeR600Target();\n LLVMInitializeR600TargetMC();\n LLVMInitializeR600AsmPrinter();\n\n std::string err;\n const Target * AMDGPUTarget = TargetRegistry::lookupTarget(\"r600\", err);\n if(!AMDGPUTarget) {\n fprintf(stderr, \"Can't find target: %s\\n\", err.c_str());\n return 1;\n }\n \n Triple::ArchType Arch = Triple::getArchTypeForLLVMName(\"r600\");\n if (Arch == Triple::UnknownArch) {\n fprintf(stderr, \"Unknown Arch\\n\");\n }\n AMDGPUTriple.setArch(Arch);\n\n Module * mod = unwrap(M);\n std::string FS;\n TargetOptions TO;\n\n if (dump) {\n mod->dump();\n FS += \"+DumpCode\";\n }\n\n std::auto_ptr<TargetMachine> tm(AMDGPUTarget->createTargetMachine(\n AMDGPUTriple.getTriple(), gpu_family, FS,\n TO, Reloc::Default, CodeModel::Default,\n CodeGenOpt::Default\n ));\n TargetMachine &AMDGPUTargetMachine = *tm.get();\n PassManager PM;\n PM.add(new DataLayout(*AMDGPUTargetMachine.getDataLayout()));\n PM.add(createPromoteMemoryToRegisterPass());\n AMDGPUTargetMachine.setAsmVerbosityDefault(true);\n\n std::string CodeString;\n raw_string_ostream oStream(CodeString);\n formatted_raw_ostream out(oStream);\n\n \/* Optional extra paramater true \/ false to disable verify *\/\n if (AMDGPUTargetMachine.addPassesToEmitFile(PM, out, TargetMachine::CGFT_ObjectFile,\n true)){\n fprintf(stderr, \"AddingPasses failed.\\n\");\n return 1;\n }\n PM.run(*mod);\n\n out.flush();\n std::string &data = oStream.str();\n\n *bytes = (unsigned char*)malloc(data.length() * sizeof(unsigned char));\n memcpy(*bytes, data.c_str(), data.length() * sizeof(unsigned char));\n *byte_count = data.length();\n\n return 0;\n}\n<commit_msg>radeon\/llvm: remove uneeded inclusion<commit_after>\/*\n * Copyright 2011 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Authors: Tom Stellard <thomas.stellard@amd.com>\n *\n *\/\n#include \"radeon_llvm_emit.h\"\n\n#if HAVE_LLVM < 0x0303\n#include <llvm\/LLVMContext.h>\n#include <llvm\/Module.h>\n#include <llvm\/Function.h>\n#include <llvm\/DataLayout.h>\n#else\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Function.h>\n#include <llvm\/IR\/DataLayout.h>\n#endif\n\n#include <llvm\/PassManager.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/Support\/FormattedStream.h>\n#include <llvm\/Support\/Host.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Support\/TargetRegistry.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Threading.h>\n#include <llvm\/Target\/TargetMachine.h>\n#include <llvm\/Transforms\/Scalar.h>\n#include <llvm-c\/Target.h>\n\n#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n\nusing namespace llvm;\n\nnamespace {\n\nclass LLVMEnsureMultithreaded {\npublic:\n LLVMEnsureMultithreaded()\n {\n llvm_start_multithreaded();\n }\n};\n\nstatic LLVMEnsureMultithreaded lLVMEnsureMultithreaded;\n\n}\n\n\/**\n * Set the shader type we want to compile\n *\n * @param type shader type to set\n *\/\nextern \"C\" void\nradeon_llvm_shader_type(LLVMValueRef F, unsigned type)\n{\n Function *Func = unwrap<Function>(F);\n int Idx = AttributeSet::FunctionIndex;\n AttrBuilder B;\n char Str[2];\n\n sprintf(Str, \"%1d\", type);\n B.addAttribute(\"ShaderType\", Str);\n\n AttributeSet Set = AttributeSet::get(Func->getContext(), Idx, B);\n Func->addAttributes(Idx, Set);\n}\n\n\/**\n * Compile an LLVM module to machine code.\n *\n * @param bytes This function allocates memory for the byte stream, it is the\n * caller's responsibility to free it.\n *\/\nextern \"C\" unsigned\nradeon_llvm_compile(LLVMModuleRef M, unsigned char ** bytes,\n unsigned * byte_count, const char * gpu_family,\n unsigned dump) {\n\n Triple AMDGPUTriple(sys::getDefaultTargetTriple());\n\n LLVMInitializeR600TargetInfo();\n LLVMInitializeR600Target();\n LLVMInitializeR600TargetMC();\n LLVMInitializeR600AsmPrinter();\n\n std::string err;\n const Target * AMDGPUTarget = TargetRegistry::lookupTarget(\"r600\", err);\n if(!AMDGPUTarget) {\n fprintf(stderr, \"Can't find target: %s\\n\", err.c_str());\n return 1;\n }\n \n Triple::ArchType Arch = Triple::getArchTypeForLLVMName(\"r600\");\n if (Arch == Triple::UnknownArch) {\n fprintf(stderr, \"Unknown Arch\\n\");\n }\n AMDGPUTriple.setArch(Arch);\n\n Module * mod = unwrap(M);\n std::string FS;\n TargetOptions TO;\n\n if (dump) {\n mod->dump();\n FS += \"+DumpCode\";\n }\n\n std::auto_ptr<TargetMachine> tm(AMDGPUTarget->createTargetMachine(\n AMDGPUTriple.getTriple(), gpu_family, FS,\n TO, Reloc::Default, CodeModel::Default,\n CodeGenOpt::Default\n ));\n TargetMachine &AMDGPUTargetMachine = *tm.get();\n PassManager PM;\n PM.add(new DataLayout(*AMDGPUTargetMachine.getDataLayout()));\n PM.add(createPromoteMemoryToRegisterPass());\n AMDGPUTargetMachine.setAsmVerbosityDefault(true);\n\n std::string CodeString;\n raw_string_ostream oStream(CodeString);\n formatted_raw_ostream out(oStream);\n\n \/* Optional extra paramater true \/ false to disable verify *\/\n if (AMDGPUTargetMachine.addPassesToEmitFile(PM, out, TargetMachine::CGFT_ObjectFile,\n true)){\n fprintf(stderr, \"AddingPasses failed.\\n\");\n return 1;\n }\n PM.run(*mod);\n\n out.flush();\n std::string &data = oStream.str();\n\n *bytes = (unsigned char*)malloc(data.length() * sizeof(unsigned char));\n memcpy(*bytes, data.c_str(), data.length() * sizeof(unsigned char));\n *byte_count = data.length();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ClusterTransport.h\"\n\nvoid ClusterTransport::Init(Endpoint& endpoint_)\n{\n endpoint = endpoint_;\n server.Init(endpoint.GetPort());\n server.SetTransport(this);\n awaitingNodeID = true;\n}\n\nvoid ClusterTransport::SetSelfNodeID(uint64_t nodeID_)\n{\n nodeID = nodeID_;\n awaitingNodeID = false;\n ReconnectAll(); \/\/ so we establish \"regular\" connections with the nodeID\n}\n\nbool ClusterTransport::IsAwaitingNodeID()\n{\n return awaitingNodeID;\n}\n\nuint64_t ClusterTransport::GetSelfNodeID()\n{\n return nodeID;\n}\n\nEndpoint& ClusterTransport::GetSelfEndpoint()\n{\n return endpoint;\n}\n\nvoid ClusterTransport::AddNode(uint64_t nodeID, Endpoint& endpoint)\n{\n ClusterConnection* conn;\n\n if (nodeID < this->nodeID)\n return;\n \n conn = GetConnection(nodeID);\n if (conn != NULL)\n return;\n\n if (nodeID == this->nodeID)\n Log_Trace(\"connecting to self\");\n\n conn = new ClusterConnection;\n conn->SetTransport(this);\n conn->SetNodeID(nodeID);\n conn->SetEndpoint(endpoint);\n conn->Connect(); \n}\n\nbool ClusterTransport::SetConnectionNodeID(Endpoint& endpoint, uint64_t nodeID)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetEndpoint() == endpoint)\n {\n assert(it->GetProgress() == ClusterConnection::AWAITING_NODEID);\n it->SetNodeID(nodeID);\n it->SetProgress(ClusterConnection::READY);\n return true;\n }\n }\n \n return false;\n}\n\nvoid ClusterTransport::SendMessage(uint64_t nodeID, Buffer& prefix, Message& msg)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n {\n Log_Trace(\"no connection to nodeID %\" PRIu64, nodeID);\n return;\n }\n \n if (conn->GetProgress() != ClusterConnection::READY)\n {\n Log_Trace(\"connection to %\" PRIu64 \" has progress: %d\", nodeID, conn->GetProgress());\n return;\n }\n \n msg.Write(msgBuffer);\n conn->Write(prefix, msgBuffer);\n}\n\nvoid ClusterTransport::SendPriorityMessage(uint64_t nodeID, Buffer& prefix, Message& msg)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n {\n Log_Trace(\"no connection to nodeID %\" PRIu64, nodeID);\n return;\n }\n \n if (conn->GetProgress() != ClusterConnection::READY)\n {\n Log_Trace(\"connection to %\" PRIu64 \" has progress: %d\", nodeID, conn->GetProgress());\n return;\n }\n \n msg.Write(msgBuffer);\n conn->WritePriority(prefix, msgBuffer);\n}\n\nvoid ClusterTransport::DropConnection(uint64_t nodeID)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n return;\n \n DeleteConnection(conn);\n}\n\nvoid ClusterTransport::DropConnection(Endpoint endpoint)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(endpoint);\n \n if (!conn)\n return;\n \n DeleteConnection(conn);\n}\n\nbool ClusterTransport::GetNextWaiting(Endpoint& endpoint)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetProgress() == ClusterConnection::AWAITING_NODEID)\n {\n endpoint = it->GetEndpoint();\n return true;\n }\n }\n \n return false;\n}\n\nvoid ClusterTransport::AddConnection(ClusterConnection* conn)\n{\n conns.Append(conn);\n}\n\nClusterConnection* ClusterTransport::GetConnection(uint64_t nodeID)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetNodeID() == nodeID && it->GetProgress() != ClusterConnection::AWAITING_NODEID)\n return it;\n }\n \n return NULL;\n}\n\nClusterConnection* ClusterTransport::GetConnection(Endpoint& endpoint)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetEndpoint() == endpoint)\n return it;\n }\n \n return NULL;\n}\n\nvoid ClusterTransport::DeleteConnection(ClusterConnection* conn)\n{\n conn->Close();\n\n if (conn->next != conn)\n conns.Remove(conn);\n\n delete conn;\n}\n\nvoid ClusterTransport::ReconnectAll()\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n it->Close();\n it->Connect();\n }\n}\n<commit_msg>Fixed nodeID issue.<commit_after>#include \"ClusterTransport.h\"\n\nvoid ClusterTransport::Init(Endpoint& endpoint_)\n{\n endpoint = endpoint_;\n server.Init(endpoint.GetPort());\n server.SetTransport(this);\n awaitingNodeID = true;\n}\n\nvoid ClusterTransport::SetSelfNodeID(uint64_t nodeID_)\n{\n nodeID = nodeID_;\n awaitingNodeID = false;\n ReconnectAll(); \/\/ so we establish \"regular\" connections with the nodeID\n}\n\nbool ClusterTransport::IsAwaitingNodeID()\n{\n return awaitingNodeID;\n}\n\nuint64_t ClusterTransport::GetSelfNodeID()\n{\n return nodeID;\n}\n\nEndpoint& ClusterTransport::GetSelfEndpoint()\n{\n return endpoint;\n}\n\nvoid ClusterTransport::AddNode(uint64_t nodeID, Endpoint& endpoint)\n{\n ClusterConnection* conn;\n\n if (nodeID > this->nodeID)\n return;\n \n conn = GetConnection(nodeID);\n if (conn != NULL)\n return;\n\n if (nodeID == this->nodeID)\n Log_Trace(\"connecting to self\");\n\n conn = new ClusterConnection;\n conn->SetTransport(this);\n conn->SetNodeID(nodeID);\n conn->SetEndpoint(endpoint);\n conn->Connect(); \n}\n\nbool ClusterTransport::SetConnectionNodeID(Endpoint& endpoint, uint64_t nodeID)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetEndpoint() == endpoint)\n {\n assert(it->GetProgress() == ClusterConnection::AWAITING_NODEID);\n it->SetNodeID(nodeID);\n it->SetProgress(ClusterConnection::READY);\n return true;\n }\n }\n \n return false;\n}\n\nvoid ClusterTransport::SendMessage(uint64_t nodeID, Buffer& prefix, Message& msg)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n {\n Log_Trace(\"no connection to nodeID %\" PRIu64, nodeID);\n return;\n }\n \n if (conn->GetProgress() != ClusterConnection::READY)\n {\n Log_Trace(\"connection to %\" PRIu64 \" has progress: %d\", nodeID, conn->GetProgress());\n return;\n }\n \n msg.Write(msgBuffer);\n conn->Write(prefix, msgBuffer);\n}\n\nvoid ClusterTransport::SendPriorityMessage(uint64_t nodeID, Buffer& prefix, Message& msg)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n {\n Log_Trace(\"no connection to nodeID %\" PRIu64, nodeID);\n return;\n }\n \n if (conn->GetProgress() != ClusterConnection::READY)\n {\n Log_Trace(\"connection to %\" PRIu64 \" has progress: %d\", nodeID, conn->GetProgress());\n return;\n }\n \n msg.Write(msgBuffer);\n conn->WritePriority(prefix, msgBuffer);\n}\n\nvoid ClusterTransport::DropConnection(uint64_t nodeID)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(nodeID);\n \n if (!conn)\n return;\n \n DeleteConnection(conn);\n}\n\nvoid ClusterTransport::DropConnection(Endpoint endpoint)\n{\n ClusterConnection* conn;\n \n conn = GetConnection(endpoint);\n \n if (!conn)\n return;\n \n DeleteConnection(conn);\n}\n\nbool ClusterTransport::GetNextWaiting(Endpoint& endpoint)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetProgress() == ClusterConnection::AWAITING_NODEID)\n {\n endpoint = it->GetEndpoint();\n return true;\n }\n }\n \n return false;\n}\n\nvoid ClusterTransport::AddConnection(ClusterConnection* conn)\n{\n conns.Append(conn);\n}\n\nClusterConnection* ClusterTransport::GetConnection(uint64_t nodeID)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetNodeID() == nodeID && it->GetProgress() != ClusterConnection::AWAITING_NODEID)\n return it;\n }\n \n return NULL;\n}\n\nClusterConnection* ClusterTransport::GetConnection(Endpoint& endpoint)\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n if (it->GetEndpoint() == endpoint)\n return it;\n }\n \n return NULL;\n}\n\nvoid ClusterTransport::DeleteConnection(ClusterConnection* conn)\n{\n conn->Close();\n\n if (conn->next != conn)\n conns.Remove(conn);\n\n delete conn;\n}\n\nvoid ClusterTransport::ReconnectAll()\n{\n ClusterConnection* it;\n \n for (it = conns.First(); it != NULL; it = conns.Next(it))\n {\n it->Close();\n it->Connect();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ Local includes\n#include \"libmesh\/elem_cutter.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/serial_mesh.h\"\n#include \"libmesh\/mesh_triangle_interface.h\"\n#include \"libmesh\/mesh_tetgen_interface.h\"\n\n\/\/ C++ includes\n\nnamespace\n{\n unsigned int cut_cntr;\n}\nnamespace libMesh\n{\n\n\n \/\/ ------------------------------------------------------------\n \/\/ ElemCutter implementation\n ElemCutter::ElemCutter()\n {\n _inside_mesh_2D.reset (new SerialMesh); \/**\/ _triangle_inside.reset (new TriangleInterface (*_inside_mesh_2D)); \n _outside_mesh_2D.reset (new SerialMesh); \/**\/ _triangle_outside.reset (new TriangleInterface (*_outside_mesh_2D));\n \n _inside_mesh_3D.reset (new SerialMesh); \/**\/ _tetgen_inside.reset (new TetGenMeshInterface (*_inside_mesh_3D)); \n _outside_mesh_3D.reset (new SerialMesh); \/**\/ _tetgen_outside.reset (new TetGenMeshInterface (*_outside_mesh_3D));\n\n cut_cntr = 0;\n }\n\n\n \n ElemCutter::~ElemCutter()\n {}\n\n\n \n void ElemCutter::operator()(const Elem &elem,\n\t\t\t const std::vector<Real> &vertex_distance_func)\n\n {\n libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());\n\n _inside_elem.clear();\n _outside_elem.clear();\n \n \/\/ check for quick return?\n {\n Real\n\tnmin = vertex_distance_func.front(),\n\tnmax = nmin;\n\n for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();\n\t it!=vertex_distance_func.end(); ++it)\n\t{\n\t nmin = std::min (nmin, *it);\n\t nmax = std::max (nmax, *it);\n\t}\n\n \/\/ completely outside?\n if (nmin >= 0.)\n\t{\n\t \/\/std::cout << \"element completely outside\\n\";\n\t _outside_elem.push_back(&elem);\n\t return;\n\t}\n\n \/\/ completely inside?\n else if (nmax <= 0.)\n\t{\n\t \/\/std::cout << \"element completely inside\\n\";\n\t _inside_elem.push_back(&elem);\n\t return;\n\t}\n\n libmesh_assert_greater (nmax, 0.);\n libmesh_assert_less (nmin, 0.);\n }\n\n\n \n \/\/ we now know we are in a cut element, find the intersecting points.\n this->find_intersection_points (elem, vertex_distance_func);\n \n \/\/ and then dispatch the proper method\n switch (elem.dim())\n {\n case 1: this->cut_1D(); break;\n case 2: this->cut_2D(elem, vertex_distance_func); break;\n case 3: this->cut_3D(); break;\n default: libmesh_error();\n }\n }\n\n \n\n void ElemCutter::find_intersection_points(const Elem &elem,\n\t\t\t\t\t const std::vector<Real> &vertex_distance_func)\n {\n _intersection_pts.clear();\n\n for (unsigned int e=0; e<elem.n_edges(); e++)\n {\n\tAutoPtr<Elem> edge (elem.build_edge(e));\n\n\t\/\/ find the element nodes el0, el1 that map\n\tunsigned int\n\t el0 = elem.get_node_index(edge->get_node(0)),\n\t el1 = elem.get_node_index(edge->get_node(1));\n\n\tlibmesh_assert (elem.is_vertex(el0));\n\tlibmesh_assert (elem.is_vertex(el1));\n\tlibmesh_assert_less (el0, vertex_distance_func.size());\n\tlibmesh_assert_less (el1, vertex_distance_func.size());\n\n\tconst Real\n\t d0 = vertex_distance_func[el0],\n\t d1 = vertex_distance_func[el1];\n\n\t\/\/ if this egde has a 0 crossing\n\tif (d0*d1 < 0.)\n\t {\n\t libmesh_assert_not_equal_to (d0, d1);\n\t \n\t \/\/ then find d_star in [0,1], the\n\t \/\/ distance from el0 to el1 where the 0 lives.\n\t const Real d_star = d0 \/ (d0 - d1);\n\n\n\t \/\/ Prevent adding nodes trivially close to existing\n\t \/\/ nodes.\n\t const Real endpoint_tol = 0.01;\n\t \n\t if ( (d_star > endpoint_tol) &&\n\t\t (d_star < (1.-endpoint_tol)) )\n\t {\n\t\tconst Point x_star = (edge->point(0)*(1.-d_star) +\n\t\t\t\t edge->point(1)*d_star);\n\t\t\n\t\tstd::cout << \"adding cut point (d_star, x_star) = \"\n\t\t\t << d_star << \" , \" << x_star << std::endl;\n\t\t\n\t\t_intersection_pts.push_back (x_star);\n\t }\n\t }\n }\n }\n\n\n\n \n void ElemCutter::cut_1D ()\n {\n libmesh_not_implemented();\n }\n\n \n\n void ElemCutter::cut_2D (const Elem &elem,\n\t\t\t const std::vector<Real> &vertex_distance_func)\n {\n \/\/libmesh_not_implemented();\n std::cout << \"Inside cut element!\\n\";\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n \n libmesh_assert (_inside_mesh_2D.get() != NULL);\n \n _inside_mesh_2D->clear();\n _outside_mesh_2D->clear();\n\n for (unsigned int v=0; v<elem.n_vertices(); v++)\n {\n\tif (vertex_distance_func[v] >= 0.)\n\t _outside_mesh_2D->add_point (elem.point(v));\n\t\n\tif (vertex_distance_func[v] <= 0.)\n\t _inside_mesh_2D->add_point (elem.point(v));\n }\n\n for (std::vector<Point>::const_iterator it=_intersection_pts.begin();\n\t it != _intersection_pts.end(); ++it)\n {\t\n\t_inside_mesh_2D->add_point(*it);\n\t_outside_mesh_2D->add_point(*it);\n }\n\n \n \/\/ Customize the variables for the triangulation\n _triangle_inside->desired_area() = 100.;\n _triangle_outside->desired_area() = 100.;\n \n \/\/ Turn on\/off Laplacian mesh smoothing after generation.\n \/\/ By default this is on.\n _triangle_inside->smooth_after_generating() = false;\n _triangle_outside->smooth_after_generating() = false;\n \n \/\/ Triangulate!\n _triangle_inside->triangulate();\n _triangle_outside->triangulate();\n\n std::ostringstream name;\n \n name << \"cut_face_\"\n\t << cut_cntr++\n\t << \".dat\";\n _inside_mesh_2D->write (\"in_\" + name.str());\n _outside_mesh_2D->write (\"out_\" + name.str());\n#endif\n }\n\n \n\n void ElemCutter::cut_3D ()\n {\n libmesh_not_implemented();\n }\n\n \n\n} \/\/ namespace libMesh\n<commit_msg>5 degree minimum angle, vs. default of 20 - results in fewer triangles.<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ Local includes\n#include \"libmesh\/elem_cutter.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/serial_mesh.h\"\n#include \"libmesh\/mesh_triangle_interface.h\"\n#include \"libmesh\/mesh_tetgen_interface.h\"\n\n\/\/ C++ includes\n\nnamespace\n{\n unsigned int cut_cntr;\n}\nnamespace libMesh\n{\n\n\n \/\/ ------------------------------------------------------------\n \/\/ ElemCutter implementation\n ElemCutter::ElemCutter()\n {\n _inside_mesh_2D.reset (new SerialMesh); \/**\/ _triangle_inside.reset (new TriangleInterface (*_inside_mesh_2D)); \n _outside_mesh_2D.reset (new SerialMesh); \/**\/ _triangle_outside.reset (new TriangleInterface (*_outside_mesh_2D));\n \n _inside_mesh_3D.reset (new SerialMesh); \/**\/ _tetgen_inside.reset (new TetGenMeshInterface (*_inside_mesh_3D)); \n _outside_mesh_3D.reset (new SerialMesh); \/**\/ _tetgen_outside.reset (new TetGenMeshInterface (*_outside_mesh_3D));\n\n cut_cntr = 0;\n }\n\n\n \n ElemCutter::~ElemCutter()\n {}\n\n\n \n void ElemCutter::operator()(const Elem &elem,\n\t\t\t const std::vector<Real> &vertex_distance_func)\n\n {\n libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());\n\n _inside_elem.clear();\n _outside_elem.clear();\n \n \/\/ check for quick return?\n {\n Real\n\tnmin = vertex_distance_func.front(),\n\tnmax = nmin;\n\n for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();\n\t it!=vertex_distance_func.end(); ++it)\n\t{\n\t nmin = std::min (nmin, *it);\n\t nmax = std::max (nmax, *it);\n\t}\n\n \/\/ completely outside?\n if (nmin >= 0.)\n\t{\n\t \/\/std::cout << \"element completely outside\\n\";\n\t _outside_elem.push_back(&elem);\n\t return;\n\t}\n\n \/\/ completely inside?\n else if (nmax <= 0.)\n\t{\n\t \/\/std::cout << \"element completely inside\\n\";\n\t _inside_elem.push_back(&elem);\n\t return;\n\t}\n\n libmesh_assert_greater (nmax, 0.);\n libmesh_assert_less (nmin, 0.);\n }\n\n\n \n \/\/ we now know we are in a cut element, find the intersecting points.\n this->find_intersection_points (elem, vertex_distance_func);\n \n \/\/ and then dispatch the proper method\n switch (elem.dim())\n {\n case 1: this->cut_1D(); break;\n case 2: this->cut_2D(elem, vertex_distance_func); break;\n case 3: this->cut_3D(); break;\n default: libmesh_error();\n }\n }\n\n \n\n void ElemCutter::find_intersection_points(const Elem &elem,\n\t\t\t\t\t const std::vector<Real> &vertex_distance_func)\n {\n _intersection_pts.clear();\n\n for (unsigned int e=0; e<elem.n_edges(); e++)\n {\n\tAutoPtr<Elem> edge (elem.build_edge(e));\n\n\t\/\/ find the element nodes el0, el1 that map\n\tunsigned int\n\t el0 = elem.get_node_index(edge->get_node(0)),\n\t el1 = elem.get_node_index(edge->get_node(1));\n\n\tlibmesh_assert (elem.is_vertex(el0));\n\tlibmesh_assert (elem.is_vertex(el1));\n\tlibmesh_assert_less (el0, vertex_distance_func.size());\n\tlibmesh_assert_less (el1, vertex_distance_func.size());\n\n\tconst Real\n\t d0 = vertex_distance_func[el0],\n\t d1 = vertex_distance_func[el1];\n\n\t\/\/ if this egde has a 0 crossing\n\tif (d0*d1 < 0.)\n\t {\n\t libmesh_assert_not_equal_to (d0, d1);\n\t \n\t \/\/ then find d_star in [0,1], the\n\t \/\/ distance from el0 to el1 where the 0 lives.\n\t const Real d_star = d0 \/ (d0 - d1);\n\n\n\t \/\/ Prevent adding nodes trivially close to existing\n\t \/\/ nodes.\n\t const Real endpoint_tol = 0.01;\n\t \n\t if ( (d_star > endpoint_tol) &&\n\t\t (d_star < (1.-endpoint_tol)) )\n\t {\n\t\tconst Point x_star = (edge->point(0)*(1.-d_star) +\n\t\t\t\t edge->point(1)*d_star);\n\t\t\n\t\tstd::cout << \"adding cut point (d_star, x_star) = \"\n\t\t\t << d_star << \" , \" << x_star << std::endl;\n\t\t\n\t\t_intersection_pts.push_back (x_star);\n\t }\n\t }\n }\n }\n\n\n\n \n void ElemCutter::cut_1D ()\n {\n libmesh_not_implemented();\n }\n\n \n\n void ElemCutter::cut_2D (const Elem &elem,\n\t\t\t const std::vector<Real> &vertex_distance_func)\n {\n \/\/libmesh_not_implemented();\n std::cout << \"Inside cut element!\\n\";\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n \n libmesh_assert (_inside_mesh_2D.get() != NULL);\n \n _inside_mesh_2D->clear();\n _outside_mesh_2D->clear();\n\n for (unsigned int v=0; v<elem.n_vertices(); v++)\n {\n\tif (vertex_distance_func[v] >= 0.)\n\t _outside_mesh_2D->add_point (elem.point(v));\n\t\n\tif (vertex_distance_func[v] <= 0.)\n\t _inside_mesh_2D->add_point (elem.point(v));\n }\n\n for (std::vector<Point>::const_iterator it=_intersection_pts.begin();\n\t it != _intersection_pts.end(); ++it)\n {\t\n\t_inside_mesh_2D->add_point(*it);\n\t_outside_mesh_2D->add_point(*it);\n }\n\n \n \/\/ Customize the variables for the triangulation\n \/\/ we will be cutting reference cell, and want as few triangles\n \/\/ as possible, so jack this up larger than the area we will be\n \/\/ triangulating so we are governed only by accurately defining\n \/\/ the boundaries.\n _triangle_inside->desired_area() = 100.;\n _triangle_outside->desired_area() = 100.;\n\n \/\/ allow for small angles\n _triangle_inside->minimum_angle() = 5.;\n _triangle_outside->minimum_angle() = 5.;\n \n \/\/ Turn off Laplacian mesh smoothing after generation.\n _triangle_inside->smooth_after_generating() = false;\n _triangle_outside->smooth_after_generating() = false;\n \n \/\/ Triangulate!\n _triangle_inside->triangulate();\n _triangle_outside->triangulate();\n\n std::ostringstream name;\n \n name << \"cut_face_\"\n\t << cut_cntr++\n\t << \".dat\";\n _inside_mesh_2D->write (\"in_\" + name.str());\n _outside_mesh_2D->write (\"out_\" + name.str());\n#endif\n }\n\n \n\n void ElemCutter::cut_3D ()\n {\n libmesh_not_implemented();\n }\n\n \n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2008 Free Software Foundation, Inc.\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\n\n\n#include \"Sockets.h\"\n#include \"Threads.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\n\nstatic const int gNumToSend = 10;\n\n\nvoid *testReaderIP(void *)\n{\n\tUDPSocket readSocket(\"127.0.0.1\", 5934, \"localhost\", 5061);\n\treadSocket.nonblocking();\n\tint rc = 0;\n\twhile (rc<gNumToSend) {\n\t\tchar buf[MAX_UDP_LENGTH];\n\t\tint count = readSocket.read(buf, MAX_UDP_LENGTH);\n\t\tif (count>0) {\n\t\t\tCOUT(\"read: \" << buf);\n\t\t\trc++;\n\t\t} else {\n\t\t\tsleep(2);\n\t\t}\n\t}\n\treturn NULL;\n}\n\n\n\nvoid *testReaderUnix(void *)\n{\n\tUDDSocket readSocket(\"testDestination\");\n\treadSocket.nonblocking();\n\tint rc = 0;\n\twhile (rc<gNumToSend) {\n\t\tchar buf[MAX_UDP_LENGTH];\n\t\tint count = readSocket.read(buf, MAX_UDP_LENGTH);\n\t\tif (count>0) {\n\t\t\tCOUT(\"read: \" << buf);\n\t\t\trc++;\n\t\t} else {\n\t\t\tsleep(2);\n\t\t}\n\t}\n\treturn NULL;\n}\n\n\nint main(int argc, char * argv[] )\n{\n\n Thread readerThreadIP;\n readerThreadIP.start(testReaderIP,NULL);\n Thread readerThreadUnix;\n readerThreadUnix.start(testReaderUnix,NULL);\n\n UDPSocket socket1(\"127.0.0.1\", 5061, \"127.0.0.1\", 5934);\n UDDSocket socket1U(\"testSource\",\"testDestination\");\n \n COUT(\"socket1: \" << socket1.port());\n\n \/\/ give the readers time to open\n sleep(1);\n\n for (int i=0; i<gNumToSend; i++) {\n socket1.write(\"Hello IP land\");\t\n\tsocket1U.write(\"Hello Unix domain\");\n\tsleep(1);\n }\n\n readerThreadIP.join();\n readerThreadUnix.join();\n}\n\n\/\/ vim: ts=4 sw=4\n<commit_msg>SocketsTest: Fix printing of non-nul-terminated string<commit_after>\/*\n* Copyright 2008 Free Software Foundation, Inc.\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n\n\n\n#include \"Sockets.h\"\n#include \"Threads.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\n\nstatic const int gNumToSend = 10;\n\n\nvoid *testReaderIP(void *)\n{\n\tUDPSocket readSocket(\"127.0.0.1\", 5934, \"localhost\", 5061);\n\treadSocket.nonblocking();\n\tint rc = 0;\n\twhile (rc<gNumToSend) {\n\t\tchar buf[MAX_UDP_LENGTH];\n\t\tint count = readSocket.read(buf, MAX_UDP_LENGTH);\n\t\tif (count>0) {\n\t\t\tCOUT(\"read: \" << buf);\n\t\t\trc++;\n\t\t} else {\n\t\t\tsleep(2);\n\t\t}\n\t}\n\treturn NULL;\n}\n\n\n\nvoid *testReaderUnix(void *)\n{\n\tUDDSocket readSocket(\"testDestination\");\n\treadSocket.nonblocking();\n\tint rc = 0;\n\twhile (rc<gNumToSend) {\n\t\tchar buf[MAX_UDP_LENGTH+1];\n\t\tbuf[MAX_UDP_LENGTH] = '\\0';\n\t\tint count = readSocket.read(buf, MAX_UDP_LENGTH);\n\t\tif (count>0) {\n\t\t\tCOUT(\"read: \" << buf);\n\t\t\trc++;\n\t\t} else {\n\t\t\tsleep(2);\n\t\t}\n\t}\n\treturn NULL;\n}\n\n\nint main(int argc, char * argv[] )\n{\n\n Thread readerThreadIP;\n readerThreadIP.start(testReaderIP,NULL);\n Thread readerThreadUnix;\n readerThreadUnix.start(testReaderUnix,NULL);\n\n UDPSocket socket1(\"127.0.0.1\", 5061, \"127.0.0.1\", 5934);\n UDDSocket socket1U(\"testSource\",\"testDestination\");\n \n COUT(\"socket1: \" << socket1.port());\n\n \/\/ give the readers time to open\n sleep(1);\n\n for (int i=0; i<gNumToSend; i++) {\n socket1.write(\"Hello IP land\");\t\n\tsocket1U.write(\"Hello Unix domain\");\n\tsleep(1);\n }\n\n readerThreadIP.join();\n readerThreadUnix.join();\n}\n\n\/\/ vim: ts=4 sw=4\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Working on frustum stuff<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief forceContextSwitch() definition\n *\n * \\author Copyright (C) 2014-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/internal\/scheduler\/forceContextSwitch.hpp\"\n\n#include \"distortos\/architecture\/requestContextSwitch.hpp\"\n\n#include \"distortos\/internal\/synchronization\/InterruptUnmaskingLock.hpp\"\n\nnamespace distortos\n{\n\nnamespace internal\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid forceContextSwitch()\n{\n\tarchitecture::requestContextSwitch();\n\tInterruptUnmaskingLock interruptUnmaskingLock;\n}\n\n}\t\/\/ namespace internal\n\n}\t\/\/ namespace distortos\n<commit_msg>Constify all InterruptUnmaskingLock objects<commit_after>\/**\n * \\file\n * \\brief forceContextSwitch() definition\n *\n * \\author Copyright (C) 2014-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/internal\/scheduler\/forceContextSwitch.hpp\"\n\n#include \"distortos\/architecture\/requestContextSwitch.hpp\"\n\n#include \"distortos\/internal\/synchronization\/InterruptUnmaskingLock.hpp\"\n\nnamespace distortos\n{\n\nnamespace internal\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid forceContextSwitch()\n{\n\tarchitecture::requestContextSwitch();\n\tconst InterruptUnmaskingLock interruptUnmaskingLock;\n}\n\n}\t\/\/ namespace internal\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"customdraganddrop.h\"\n\n#include <QMimeData>\n#include <QPoint>\n#include <QLabel>\n\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDebug>\n#include <QPainter>\n\n#ifdef Q_OS_WIN\n#include <private\/qwidget_p.h>\n#endif\n\nnamespace QmlDesigner {\n\nnamespace QmlDesignerItemLibraryDragAndDrop {\n\nvoid CustomDragAndDropIcon::startDrag()\n{\n m_size = m_icon.size();\n m_iconAlpha = 1;\n m_previewAlpha = 0;\n\n QPoint pos = QCursor::pos();\n QWidget *widget = QApplication::topLevelAt(pos);\n setParent(widget);\n raise();\n show();\n\n grabMouseSafely();\n}\n\nvoid CustomDragAndDropIcon::grabMouseSafely()\n{\n#ifdef Q_OS_WIN\n \/\/ grabMouse calls SetWindowsHookEx() - this function causes a system-wide\n \/\/ freeze if any other app on the system installs a hook and fails to\n \/\/ process events.\n QWidgetPrivate *p = qt_widget_private(this);\n p->grabMouseWhileInWindow();\n#else\n grabMouse();\n#endif\n}\n\nvoid CustomDragAndDropIcon::mouseReleaseEvent(QMouseEvent *event)\n{\n QPoint globalPos = event->globalPos();\n releaseMouse();\n move(-1000, -1000); \/\/-1000, -1000 is used to hide because hiding causes propblems with the mouse grabber\n QWidget* target = QApplication::widgetAt(globalPos - QPoint(2,2)); \/\/-(2, 2) because:\n \/\/ otherwise we just get this widget\n\n if (CustomDragAndDrop::isAccepted()) \/\/ if the target widget accepted the enter event,\n \/\/ then create a drop event\n CustomDragAndDrop::drop(target, globalPos);\n CustomDragAndDrop::endCustomDrag();\n}\n\nvoid CustomDragAndDropIcon::mouseMoveEvent(QMouseEvent *event)\n{\n QPoint globalPos = event->globalPos();\n QWidget * widget = QApplication::topLevelAt(globalPos); \/\/ grap the \"current\" top level widget\n if (widget) {\n setParent(widget); \/\/ set the current top level widget as parent\n QPoint pos = parentWidget()->mapFromGlobal(globalPos);\n if ((pos.y() > 30 && CustomDragAndDrop::isVisible())) \/\/ do not allow dragging over the menubar\n move(pos);\n else\n move(-1000, -1000); \/\/ no hiding because of mouse grabbing\n resize(m_size);\n show();\n update();\n }\n else {\n move(-1000, -1000); \/\/ if no top level widget is found we are out of the main window\n }\n QWidget* target = QApplication::widgetAt(globalPos - QPoint(2,2)); \/\/-(2, 2) because:\n \/\/ otherwise we just get this widget\n if (target != m_oldTarget) {\n if (CustomDragAndDrop::isAccepted())\n CustomDragAndDrop::leave(m_oldTarget, globalPos); \/\/ create DragLeave event if drag enter\n \/\/ event was accepted\n bool wasAccepted = CustomDragAndDrop::isAccepted();\n CustomDragAndDrop::enter(target, globalPos); \/\/ create and handle the create enter event\n releaseMouse(); \/\/ to set the cursor we have to disable the mouse grabber\n if (CustomDragAndDrop::isAccepted()) { \/\/ setting the right cursor and trigger animation\n setCursor(Qt::CrossCursor);\n if (!wasAccepted)\n enter(); \/\/ trigger animation if enter event was accepted\n } else {\n setCursor(Qt::ForbiddenCursor);\n if (wasAccepted)\n leave(); \/\/ trigger animation if we leave a widget that accepted\n \/\/ the drag enter event\n }\n \/\/ enable the mouse grabber again - after the curser is set\n grabMouseSafely();\n } else {\n if (CustomDragAndDrop::isAccepted()) \/\/ create DragMoveEvents if the current widget\n \/\/ accepted the DragEnter event\n CustomDragAndDrop::move(target, globalPos);\n }\n m_oldTarget = target;\n}\n\nvoid CustomDragAndDropIcon::paintEvent(QPaintEvent *event)\n{\n QWidget::paintEvent(event);\n QPainter p(this);\n if (CustomDragAndDrop::isAccepted()) {\n p.setOpacity(m_previewAlpha);\n p.drawPixmap(0 ,0 , m_size.width(), m_size.height(), m_preview);\n p.setOpacity(m_iconAlpha);\n p.drawPixmap(0, 0, m_size.width(), m_size.height(), m_icon);\n } else {\n p.setOpacity(m_iconAlpha);\n p.drawPixmap(0, 0, m_size.width(), m_size.height(), m_icon);\n p.setOpacity(m_previewAlpha);\n p.drawPixmap(0 ,0 , m_size.width(), m_size.height(), m_preview);\n }\n}\n\nvoid CustomDragAndDropIcon::enter()\n{\n connect(&m_timeLine, SIGNAL(frameChanged(int)), this, SLOT(animateDrag(int)));\n m_timeLine.setFrameRange(0, 10);\n m_timeLine.setDuration(10);\n m_timeLine.setLoopCount(1);\n m_timeLine.setCurveShape(QTimeLine::EaseInCurve);\n m_timeLine.start();\n m_size = m_icon.size();\n m_iconAlpha = 1;\n m_previewAlpha = 0;\n}\n\nvoid CustomDragAndDropIcon::leave()\n{\n connect(&m_timeLine, SIGNAL(frameChanged(int)), this, SLOT(animateDrag(int)));\n m_timeLine.setFrameRange(0, 10);\n m_timeLine.setDuration(250);\n m_timeLine.setLoopCount(1);\n m_timeLine.setCurveShape(QTimeLine::EaseInCurve);\n m_timeLine.start();\n m_size = m_preview.size();\n m_iconAlpha = 0;\n m_previewAlpha = 1;\n}\n\nvoid CustomDragAndDropIcon::animateDrag(int frame)\n{\n \/\/ interpolation of m_size and alpha values\n if (CustomDragAndDrop::isAccepted()) {\n \/\/ small -> big\n m_iconAlpha = 1.0 - qreal(frame) \/ 10.0;\n m_previewAlpha = qreal(frame) \/ 10.0;\n int width = qreal(m_preview.width()) * (qreal(frame) \/ 10.0) + qreal(m_icon.width()) * (1.0 - qreal(frame) \/ 10.0);\n int height = qreal(m_preview.height()) * (qreal(frame) \/ 10.0) + qreal(m_icon.height()) * (1 - qreal(frame) \/ 10.0);\n m_size = QSize(width, height);\n } else {\n \/\/ big -> small\n m_previewAlpha = 1.0 - qreal(frame) \/ 10.0;\n m_iconAlpha = qreal(frame) \/ 10.0;\n int width = qreal(m_icon.width()) * (qreal(frame) \/ 10.0) + qreal(m_preview.width()) * (1.0 - qreal(frame) \/ 10.0);\n int height = qreal(m_icon.height()) * (qreal(frame) \/ 10.0) + qreal(m_preview.height()) * (1 - qreal(frame) \/ 10.0);\n m_size = QSize(width, height);\n }\n QPoint p = pos();\n resize(m_size);\n move(p);\n update(); \/\/ redrawing needed\n}\n\n\nclass CustomDragAndDropGuard { \/\/ This guard destroys the singleton in its destructor\npublic: \/\/ This should avoid that a memory leak is reported\n ~CustomDragAndDropGuard() {\n if (CustomDragAndDrop::m_instance)\n delete CustomDragAndDrop::m_instance;\n }\n};\n\n\nCustomDragAndDrop* CustomDragAndDrop::m_instance = 0;\n\nCustomDragAndDrop::CustomDragAndDrop() : m_customDragActive(0), m_mimeData(0), m_accepted(false)\n{\n m_widget = new CustomDragAndDropIcon(QApplication::topLevelWidgets().first());\n m_widget->move(-1000, 1000);\n m_widget->resize(32, 32);\n m_widget->show();\n}\n\n\nCustomDragAndDrop* CustomDragAndDrop::instance()\n{\n static CustomDragAndDropGuard guard; \/\/ The destructor destroys the singleton. See above\n if (m_instance == 0)\n m_instance = new CustomDragAndDrop();\n return m_instance;\n}\n\nvoid CustomDragAndDrop::endCustomDrag()\n{\n instance()->m_customDragActive = false;\n}\n\nvoid CustomDragAndDrop::startCustomDrag(const QPixmap icon, const QPixmap preview, QMimeData * mimeData)\n{\n if (instance()->m_customDragActive) {\n qWarning(\"CustomDragAndDrop::startCustomDrag drag is active\");\n return ;\n }\n instance()->m_customDragActive = true;\n instance()-> m_accepted = false;\n show();\n instance()->m_mimeData = mimeData;\n instance()->m_widget->setIcon(icon);\n instance()->m_widget->setPreview(preview);\n instance()->m_widget->startDrag();\n}\n\nbool CustomDragAndDrop::customDragActive()\n{\n return instance()->m_customDragActive;\n}\n\nbool CustomDragAndDrop::isAccepted()\n{\n return instance()->m_accepted;\n}\n\nvoid CustomDragAndDrop::enter(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDragEnterEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n instance()-> m_accepted = event.isAccepted(); \/\/ if the event is accepted we enter the \"accepted\" state\n } else {\n instance()-> m_accepted = false;\n }\n}\n\nvoid CustomDragAndDrop::leave(QWidget *target, QPoint globalPos)\n{\n Q_UNUSED(globalPos)\n if (target) {\n QDragLeaveEvent event;\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::leave leaving invalid target\";\n }\n}\n\nvoid CustomDragAndDrop::move(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDragMoveEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::move move in invalid target\";\n }\n}\n\nvoid CustomDragAndDrop::drop(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDropEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::drop dropping in invalid target\";\n }\n}\n\nbool CustomDragAndDrop::isAnimated()\n{\n if (instance()->m_widget)\n return instance()->m_widget->isAnimated();\n return false;\n}\n\n} \/\/ namespace QmlDesignerItemLibraryDragAndDrop\n} \/\/ namespave QmlDesigner\n<commit_msg>QmlDesigner: fixing compile for Qt 5<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"customdraganddrop.h\"\n\n#include <QMimeData>\n#include <QPoint>\n#include <QLabel>\n\n#include <QMouseEvent>\n#include <QApplication>\n#include <QDebug>\n#include <QPainter>\n\n#if defined(Q_OS_WIN) && QT_VERSION < 0x050000\n#include <private\/qwidget_p.h>\n#endif\n\nnamespace QmlDesigner {\n\nnamespace QmlDesignerItemLibraryDragAndDrop {\n\nvoid CustomDragAndDropIcon::startDrag()\n{\n m_size = m_icon.size();\n m_iconAlpha = 1;\n m_previewAlpha = 0;\n\n QPoint pos = QCursor::pos();\n QWidget *widget = QApplication::topLevelAt(pos);\n setParent(widget);\n raise();\n show();\n\n grabMouseSafely();\n}\n\nvoid CustomDragAndDropIcon::grabMouseSafely()\n{\n#if defined(Q_OS_WIN) && QT_VERSION < 0x050000\n \/\/ grabMouse calls SetWindowsHookEx() - this function causes a system-wide\n \/\/ freeze if any other app on the system installs a hook and fails to\n \/\/ process events.\n QWidgetPrivate *p = qt_widget_private(this);\n p->grabMouseWhileInWindow();\n#else\n grabMouse();\n#endif\n}\n\nvoid CustomDragAndDropIcon::mouseReleaseEvent(QMouseEvent *event)\n{\n QPoint globalPos = event->globalPos();\n releaseMouse();\n move(-1000, -1000); \/\/-1000, -1000 is used to hide because hiding causes propblems with the mouse grabber\n QWidget* target = QApplication::widgetAt(globalPos - QPoint(2,2)); \/\/-(2, 2) because:\n \/\/ otherwise we just get this widget\n\n if (CustomDragAndDrop::isAccepted()) \/\/ if the target widget accepted the enter event,\n \/\/ then create a drop event\n CustomDragAndDrop::drop(target, globalPos);\n CustomDragAndDrop::endCustomDrag();\n}\n\nvoid CustomDragAndDropIcon::mouseMoveEvent(QMouseEvent *event)\n{\n QPoint globalPos = event->globalPos();\n QWidget * widget = QApplication::topLevelAt(globalPos); \/\/ grap the \"current\" top level widget\n if (widget) {\n setParent(widget); \/\/ set the current top level widget as parent\n QPoint pos = parentWidget()->mapFromGlobal(globalPos);\n if ((pos.y() > 30 && CustomDragAndDrop::isVisible())) \/\/ do not allow dragging over the menubar\n move(pos);\n else\n move(-1000, -1000); \/\/ no hiding because of mouse grabbing\n resize(m_size);\n show();\n update();\n }\n else {\n move(-1000, -1000); \/\/ if no top level widget is found we are out of the main window\n }\n QWidget* target = QApplication::widgetAt(globalPos - QPoint(2,2)); \/\/-(2, 2) because:\n \/\/ otherwise we just get this widget\n if (target != m_oldTarget) {\n if (CustomDragAndDrop::isAccepted())\n CustomDragAndDrop::leave(m_oldTarget, globalPos); \/\/ create DragLeave event if drag enter\n \/\/ event was accepted\n bool wasAccepted = CustomDragAndDrop::isAccepted();\n CustomDragAndDrop::enter(target, globalPos); \/\/ create and handle the create enter event\n releaseMouse(); \/\/ to set the cursor we have to disable the mouse grabber\n if (CustomDragAndDrop::isAccepted()) { \/\/ setting the right cursor and trigger animation\n setCursor(Qt::CrossCursor);\n if (!wasAccepted)\n enter(); \/\/ trigger animation if enter event was accepted\n } else {\n setCursor(Qt::ForbiddenCursor);\n if (wasAccepted)\n leave(); \/\/ trigger animation if we leave a widget that accepted\n \/\/ the drag enter event\n }\n \/\/ enable the mouse grabber again - after the curser is set\n grabMouseSafely();\n } else {\n if (CustomDragAndDrop::isAccepted()) \/\/ create DragMoveEvents if the current widget\n \/\/ accepted the DragEnter event\n CustomDragAndDrop::move(target, globalPos);\n }\n m_oldTarget = target;\n}\n\nvoid CustomDragAndDropIcon::paintEvent(QPaintEvent *event)\n{\n QWidget::paintEvent(event);\n QPainter p(this);\n if (CustomDragAndDrop::isAccepted()) {\n p.setOpacity(m_previewAlpha);\n p.drawPixmap(0 ,0 , m_size.width(), m_size.height(), m_preview);\n p.setOpacity(m_iconAlpha);\n p.drawPixmap(0, 0, m_size.width(), m_size.height(), m_icon);\n } else {\n p.setOpacity(m_iconAlpha);\n p.drawPixmap(0, 0, m_size.width(), m_size.height(), m_icon);\n p.setOpacity(m_previewAlpha);\n p.drawPixmap(0 ,0 , m_size.width(), m_size.height(), m_preview);\n }\n}\n\nvoid CustomDragAndDropIcon::enter()\n{\n connect(&m_timeLine, SIGNAL(frameChanged(int)), this, SLOT(animateDrag(int)));\n m_timeLine.setFrameRange(0, 10);\n m_timeLine.setDuration(10);\n m_timeLine.setLoopCount(1);\n m_timeLine.setCurveShape(QTimeLine::EaseInCurve);\n m_timeLine.start();\n m_size = m_icon.size();\n m_iconAlpha = 1;\n m_previewAlpha = 0;\n}\n\nvoid CustomDragAndDropIcon::leave()\n{\n connect(&m_timeLine, SIGNAL(frameChanged(int)), this, SLOT(animateDrag(int)));\n m_timeLine.setFrameRange(0, 10);\n m_timeLine.setDuration(250);\n m_timeLine.setLoopCount(1);\n m_timeLine.setCurveShape(QTimeLine::EaseInCurve);\n m_timeLine.start();\n m_size = m_preview.size();\n m_iconAlpha = 0;\n m_previewAlpha = 1;\n}\n\nvoid CustomDragAndDropIcon::animateDrag(int frame)\n{\n \/\/ interpolation of m_size and alpha values\n if (CustomDragAndDrop::isAccepted()) {\n \/\/ small -> big\n m_iconAlpha = 1.0 - qreal(frame) \/ 10.0;\n m_previewAlpha = qreal(frame) \/ 10.0;\n int width = qreal(m_preview.width()) * (qreal(frame) \/ 10.0) + qreal(m_icon.width()) * (1.0 - qreal(frame) \/ 10.0);\n int height = qreal(m_preview.height()) * (qreal(frame) \/ 10.0) + qreal(m_icon.height()) * (1 - qreal(frame) \/ 10.0);\n m_size = QSize(width, height);\n } else {\n \/\/ big -> small\n m_previewAlpha = 1.0 - qreal(frame) \/ 10.0;\n m_iconAlpha = qreal(frame) \/ 10.0;\n int width = qreal(m_icon.width()) * (qreal(frame) \/ 10.0) + qreal(m_preview.width()) * (1.0 - qreal(frame) \/ 10.0);\n int height = qreal(m_icon.height()) * (qreal(frame) \/ 10.0) + qreal(m_preview.height()) * (1 - qreal(frame) \/ 10.0);\n m_size = QSize(width, height);\n }\n QPoint p = pos();\n resize(m_size);\n move(p);\n update(); \/\/ redrawing needed\n}\n\n\nclass CustomDragAndDropGuard { \/\/ This guard destroys the singleton in its destructor\npublic: \/\/ This should avoid that a memory leak is reported\n ~CustomDragAndDropGuard() {\n if (CustomDragAndDrop::m_instance)\n delete CustomDragAndDrop::m_instance;\n }\n};\n\n\nCustomDragAndDrop* CustomDragAndDrop::m_instance = 0;\n\nCustomDragAndDrop::CustomDragAndDrop() : m_customDragActive(0), m_mimeData(0), m_accepted(false)\n{\n m_widget = new CustomDragAndDropIcon(QApplication::topLevelWidgets().first());\n m_widget->move(-1000, 1000);\n m_widget->resize(32, 32);\n m_widget->show();\n}\n\n\nCustomDragAndDrop* CustomDragAndDrop::instance()\n{\n static CustomDragAndDropGuard guard; \/\/ The destructor destroys the singleton. See above\n if (m_instance == 0)\n m_instance = new CustomDragAndDrop();\n return m_instance;\n}\n\nvoid CustomDragAndDrop::endCustomDrag()\n{\n instance()->m_customDragActive = false;\n}\n\nvoid CustomDragAndDrop::startCustomDrag(const QPixmap icon, const QPixmap preview, QMimeData * mimeData)\n{\n if (instance()->m_customDragActive) {\n qWarning(\"CustomDragAndDrop::startCustomDrag drag is active\");\n return ;\n }\n instance()->m_customDragActive = true;\n instance()-> m_accepted = false;\n show();\n instance()->m_mimeData = mimeData;\n instance()->m_widget->setIcon(icon);\n instance()->m_widget->setPreview(preview);\n instance()->m_widget->startDrag();\n}\n\nbool CustomDragAndDrop::customDragActive()\n{\n return instance()->m_customDragActive;\n}\n\nbool CustomDragAndDrop::isAccepted()\n{\n return instance()->m_accepted;\n}\n\nvoid CustomDragAndDrop::enter(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDragEnterEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n instance()-> m_accepted = event.isAccepted(); \/\/ if the event is accepted we enter the \"accepted\" state\n } else {\n instance()-> m_accepted = false;\n }\n}\n\nvoid CustomDragAndDrop::leave(QWidget *target, QPoint globalPos)\n{\n Q_UNUSED(globalPos)\n if (target) {\n QDragLeaveEvent event;\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::leave leaving invalid target\";\n }\n}\n\nvoid CustomDragAndDrop::move(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDragMoveEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::move move in invalid target\";\n }\n}\n\nvoid CustomDragAndDrop::drop(QWidget *target, QPoint globalPos)\n{\n if (target) {\n QPoint pos = target->mapFromGlobal(globalPos);\n QDropEvent event(pos, Qt::MoveAction, instance()->m_mimeData ,Qt::RightButton, Qt::NoModifier);\n QApplication::sendEvent(target, &event);\n } else {\n qWarning() << \"CustomDragAndDrop::drop dropping in invalid target\";\n }\n}\n\nbool CustomDragAndDrop::isAnimated()\n{\n if (instance()->m_widget)\n return instance()->m_widget->isAnimated();\n return false;\n}\n\n} \/\/ namespace QmlDesignerItemLibraryDragAndDrop\n} \/\/ namespave QmlDesigner\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2017 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_TOPOJSON_GRAMMAR_X3_DEF_HPP\n#define MAPNIK_JSON_TOPOJSON_GRAMMAR_X3_DEF_HPP\n\n#include <mapnik\/json\/topojson_grammar_x3.hpp>\n#include <mapnik\/json\/unicode_string_grammar_x3.hpp>\n#include <mapnik\/json\/generic_json_grammar_x3.hpp>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/fusion\/adapted\/struct.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::coordinate,\n (double, x)\n (double, y)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::arc,\n (std::list<mapnik::topojson::coordinate>, coordinates)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::transform,\n (double, scale_x)\n (double, scale_y)\n (double, translate_x)\n (double, translate_y)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::bounding_box,\n (double, minx)\n (double, miny)\n (double, maxx)\n (double, maxy)\n )\n\nnamespace mapnik { namespace json { namespace grammar {\n\nusing index_type = topojson::index_type;\nstruct create_point\n{\n using result_type = mapnik::topojson::point;\n template <typename T0, typename T1>\n result_type operator()(T0 & coord, T1 & props) const\n {\n mapnik::topojson::point pt;\n if (coord.template is<mapnik::topojson::coordinate>())\n {\n auto const& coord_ = coord.template get<mapnik::topojson::coordinate>();\n pt.coord = coord_;\n pt.props = props;\n }\n return pt;\n }\n};\n\nstruct create_multi_point\n{\n using result_type = mapnik::topojson::multi_point;\n template <typename T0, typename T1>\n result_type operator()(T0 & coords, T1 & props) const\n {\n mapnik::topojson::multi_point mpt;\n if (coords.template is<std::vector<mapnik::topojson::coordinate>>())\n {\n auto const& points = coords.template get<std::vector<mapnik::topojson::coordinate>>();\n mpt. points = points;\n mpt.props = props;\n }\n return mpt;\n }\n};\n\nstruct create_line_string\n{\n using result_type = mapnik::topojson::linestring;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::linestring line;\n if (arcs.template is<std::vector<index_type>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<index_type>>();\n line.rings = arcs_;\n line.props = props;\n }\n return line;\n }\n};\n\nstruct create_multi_line_string\n{\n using result_type = mapnik::topojson::multi_linestring;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::multi_linestring mline;\n if (arcs.template is<std::vector<std::vector<index_type>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<index_type>>>();\n mline.lines = arcs_;\n mline.props = props;\n }\n return mline;\n }\n};\n\nstruct create_polygon\n{\n using result_type = mapnik::topojson::polygon;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::polygon poly;\n if (arcs.template is<std::vector<std::vector<index_type>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<index_type>>>();\n poly.rings = arcs_;\n poly.props = props;\n }\n return poly;\n }\n};\n\nstruct create_multi_polygon\n{\n using result_type = mapnik::topojson::multi_polygon;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::multi_polygon mpoly;\n if (arcs.template is<std::vector<std::vector<std::vector<index_type>>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<std::vector<index_type>>>>();\n mpoly.polygons = arcs_;\n mpoly.props = props;\n }\n return mpoly;\n }\n};\n\n\nauto create_geometry = [] (auto const& ctx)\n{\n auto const geom_type = std::get<0>(_attr(ctx));\n auto const& coord = std::get<1>(_attr(ctx));\n auto const& arcs = std::get<2>(_attr(ctx));\n auto const& props = std::get<3>(_attr(ctx));\n mapnik::topojson::geometry geom; \/\/empty\n switch (geom_type)\n {\n case 1: \/\/Point\n geom = create_point()(coord, props);\n break;\n case 2: \/\/LineString\n geom = create_line_string()(arcs, props);\n break;\n case 3: \/\/Polygon\n geom = create_polygon()(arcs, props);\n break;\n case 4: \/\/MultiPoint\n geom = create_multi_point()(coord, props);\n break;\n case 5: \/\/MultiLineString\n geom = create_multi_line_string()(arcs, props);\n break;\n case 6: \/\/MultiPolygon\n geom = create_multi_polygon()(arcs, props);\n break;\n }\n _val(ctx) = std::move(geom);\n};\n\n\nauto assign_bbox = [] (auto const& ctx)\n{\n _val(ctx).bbox = std::move(_attr(ctx));\n};\n\nauto assign_transform = [] (auto const& ctx)\n{\n _val(ctx).tr = std::move(_attr(ctx));\n};\n\nauto assign_arcs = [] (auto const& ctx)\n{\n _val(ctx).arcs = std::move(_attr(ctx));\n};\n\nauto assign_objects = [] (auto const& ctx)\n{\n _val(ctx).geometries = std::move(_attr(ctx));\n};\n\n\nauto push_geometry = [] (auto const& ctx)\n{\n _val(ctx).push_back(std::move(_attr(ctx)));\n};\n\nauto push_collection = [] (auto const& ctx)\n{\n auto & dest = _val(ctx);\n auto & src = _attr(ctx);\n if (dest.empty()) dest = std::move(src);\n else\n {\n dest.reserve(dest.size() + src.size());\n dest.insert(std::end(dest),\n std::make_move_iterator(std::begin(src)),\n std::make_move_iterator(std::end(src)));\n }\n};\n\n\nauto assign_geometry_type = [] (auto const& ctx)\n{\n std::get<0>(_val(ctx)) = _attr(ctx);\n};\n\nauto assign_coordinates = [] (auto const& ctx)\n{\n std::get<1>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_rings = [] (auto const& ctx)\n{\n std::get<2>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_properties = [] (auto const& ctx)\n{\n std::get<3>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_prop_name = [] (auto const& ctx)\n{\n std::get<0>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_prop_value = [] (auto const& ctx)\n{\n std::get<1>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nnamespace x3 = boost::spirit::x3;\n\nusing x3::lit;\nusing x3::double_;\nusing x3::int_;\nusing x3::omit;\nusing x3::char_;\nnamespace\n{\n\/\/ import unicode string rule\nauto const& json_string = json::unicode_string_grammar();\n\/\/ json value\nauto const& json_value = json::generic_json_grammar();\n}\n\nusing coordinates_type = util::variant<topojson::coordinate,std::vector<topojson::coordinate>>;\nusing arcs_type = util::variant<std::vector<index_type>,\n std::vector<std::vector<index_type>>,\n std::vector<std::vector<std::vector<index_type>>>>;\n\nstruct geometry_type_ : x3::symbols<int>\n{\n geometry_type_()\n {\n add\n (\"\\\"Point\\\"\",1)\n (\"\\\"LineString\\\"\",2)\n (\"\\\"Polygon\\\"\",3)\n (\"\\\"MultiPoint\\\"\",4)\n (\"\\\"MultiLineString\\\"\",5)\n (\"\\\"MultiPolygon\\\"\",6)\n ;\n }\n} geometry_type;\n\n\/\/ start rule\ntopojson_grammar_type const topology = \"Topology\";\n\/\/ rules\nx3::rule<class transform_tag, mapnik::topojson::transform> const transform = \"Transform\";\nx3::rule<class bbox_tag, mapnik::topojson::bounding_box> const bbox = \"Bounding Box\";\nx3::rule<class objects_tag, std::vector<mapnik::topojson::geometry>> const objects= \"Objects\";\nx3::rule<class property_tag, mapnik::topojson::property> const property = \"Property\";\nx3::rule<class properties_tag, mapnik::topojson::properties> const properties = \"Properties\";\nx3::rule<class geometry_tag, mapnik::topojson::geometry> const geometry = \"Geometry\";\nx3::rule<class geometry_collection_tag, std::vector<mapnik::topojson::geometry>> const geometry_collection = \"Geometry Collection\";\nx3::rule<class geometry_tuple_tag,\n std::tuple<int,\n coordinates_type,\n arcs_type,\n mapnik::topojson::properties>> const geometry_tuple = \"Geometry Tuple\";\nx3::rule<class coordinate_tag, mapnik::topojson::coordinate> const coordinate = \"Coordinate\";\nx3::rule<class coordinates_tag, coordinates_type> const coordinates = \"Coordinates\";\nx3::rule<class arc_tag, mapnik::topojson::arc> const arc = \"Arc\";\nx3::rule<class arcs_tag, std::vector<mapnik::topojson::arc>> const arcs = \"Arcs\";\nx3::rule<class ring_type, std::vector<index_type>> const ring = \"Ring\";\nx3::rule<class rings_type, std::vector<std::vector<index_type>>> const rings = \"Rings\";\nx3::rule<class rings_array_type, arcs_type> const rings_array = \"Rings Array\";\n\n\/\/ defs\nauto const topology_def = lit('{') >\n -(((lit(\"\\\"type\\\"\") > lit(':') > lit(\"\\\"Topology\\\"\"))\n |\n bbox[assign_bbox]\n |\n transform[assign_transform]\n |\n objects[assign_objects]\n |\n arcs[assign_arcs]) % lit(','))\n > lit('}')\n ;\n\n\nauto const transform_def = lit(\"\\\"transform\\\"\") > lit(':') > lit('{')\n > lit(\"\\\"scale\\\"\") > lit(':')\n > lit('[')\n > double_ > lit(',')\n > double_ > lit(']') > lit(',')\n > lit(\"\\\"translate\\\"\") > lit(':')\n > lit('[') > double_ > lit(',') > double_ > lit(']')\n > lit('}')\n ;\n\nauto const bbox_def = lit(\"\\\"bbox\\\"\") > lit(':')\n > lit('[') > double_ > lit(',') > double_\n > lit(',') > double_ > lit(',') > double_\n > lit(']')\n ;\n\n\nauto const objects_def = lit(\"\\\"objects\\\"\") > lit(':')\n > lit('{')\n > ((omit[*~char_(':')] > lit(':') > ((geometry_collection[push_collection] | geometry[push_geometry]))) % lit(','))\n > lit('}')\n ;\n\nauto const geometry_tuple_def =\n ((lit(\"\\\"type\\\"\") > lit(':') > geometry_type[assign_geometry_type])\n |\n (lit(\"\\\"coordinates\\\"\") > lit(':') > coordinates[assign_coordinates])\n |\n (lit(\"\\\"arcs\\\"\") > lit(':') > rings_array[assign_rings])\n |\n properties[assign_properties]\n |\n (omit[json_string] > lit(':') > omit[json_value])) % lit(',')\n ;\n\nauto const geometry_def = lit(\"{\") > geometry_tuple[create_geometry] > lit(\"}\");\n\nauto const geometry_collection_def = (lit('{') >> lit(\"\\\"type\\\"\") >> lit(':') >> lit(\"\\\"GeometryCollection\\\"\") >> -omit[lit(',') >> bbox])\n > lit(',') > lit(\"\\\"geometries\\\"\") > lit(':')\n > lit('[')\n > -(geometry[push_geometry] % lit(','))\n > lit(']')\n > lit('}')\n ;\n\n\nauto const ring_def = lit('[') >> (int_ % lit(',')) >> lit(']')\n ;\nauto const rings_def = lit('[') >> (ring % lit(',')) >> lit(']')\n ;\nauto const rings_array_def = (lit('[') >> (rings % lit(',')) >> lit(']'))\n |\n rings\n |\n ring\n ;\n\nauto const property_def = json_string[assign_prop_name] > lit(':') > json_value[assign_prop_value]\n ;\n\nauto const properties_def = lit(\"\\\"properties\\\"\")\n > lit(':')\n > lit('{') > (property % lit(',')) > lit('}')\n ;\n\nauto const arcs_def = lit(\"\\\"arcs\\\"\") >> lit(':') >> lit('[') >> -( arc % lit(',')) >> lit(']') ;\n\nauto const arc_def = lit('[') >> -(coordinate % lit(',')) >> lit(']') ;\n\nauto const coordinate_def = lit('[') >> double_ >> lit(',') >> double_ >> omit[*(lit(',') >> double_)] >> lit(']');\n\nauto const coordinates_def = (lit('[') >> coordinate % lit(',') >> lit(']')) | coordinate;\n\nBOOST_SPIRIT_DEFINE(\n topology,\n transform,\n bbox,\n objects,\n geometry_tuple,\n geometry,\n geometry_collection,\n ring,\n rings,\n rings_array,\n property,\n properties,\n arcs,\n arc,\n coordinate,\n coordinates\n );\n\n}}}\n\nnamespace mapnik { namespace json {\ngrammar::topojson_grammar_type const& topojson_grammar()\n{\n return grammar::topology;\n}\n}}\n\n#endif \/\/MAPNIK_TOPOJSON_GRAMMAR_X3_DEF_HPP\n<commit_msg>rename 'geometry_type' to 'topojson_geometry_type' to avoid names clashing (this was causing miscompilation on linux (ubuntu 17.04\/clang))<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2017 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_TOPOJSON_GRAMMAR_X3_DEF_HPP\n#define MAPNIK_JSON_TOPOJSON_GRAMMAR_X3_DEF_HPP\n\n#include <mapnik\/json\/topojson_grammar_x3.hpp>\n#include <mapnik\/json\/unicode_string_grammar_x3.hpp>\n#include <mapnik\/json\/generic_json_grammar_x3.hpp>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/fusion\/adapted\/struct.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::coordinate,\n (double, x)\n (double, y)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::arc,\n (std::list<mapnik::topojson::coordinate>, coordinates)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::transform,\n (double, scale_x)\n (double, scale_y)\n (double, translate_x)\n (double, translate_y)\n )\n\nBOOST_FUSION_ADAPT_STRUCT(\n mapnik::topojson::bounding_box,\n (double, minx)\n (double, miny)\n (double, maxx)\n (double, maxy)\n )\n\nnamespace mapnik { namespace json { namespace grammar {\n\nusing index_type = topojson::index_type;\nstruct create_point\n{\n using result_type = mapnik::topojson::point;\n template <typename T0, typename T1>\n result_type operator()(T0 & coord, T1 & props) const\n {\n mapnik::topojson::point pt;\n if (coord.template is<mapnik::topojson::coordinate>())\n {\n auto const& coord_ = coord.template get<mapnik::topojson::coordinate>();\n pt.coord = coord_;\n pt.props = props;\n }\n return pt;\n }\n};\n\nstruct create_multi_point\n{\n using result_type = mapnik::topojson::multi_point;\n template <typename T0, typename T1>\n result_type operator()(T0 & coords, T1 & props) const\n {\n mapnik::topojson::multi_point mpt;\n if (coords.template is<std::vector<mapnik::topojson::coordinate>>())\n {\n auto const& points = coords.template get<std::vector<mapnik::topojson::coordinate>>();\n mpt. points = points;\n mpt.props = props;\n }\n return mpt;\n }\n};\n\nstruct create_line_string\n{\n using result_type = mapnik::topojson::linestring;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::linestring line;\n if (arcs.template is<std::vector<index_type>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<index_type>>();\n line.rings = arcs_;\n line.props = props;\n }\n return line;\n }\n};\n\nstruct create_multi_line_string\n{\n using result_type = mapnik::topojson::multi_linestring;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::multi_linestring mline;\n if (arcs.template is<std::vector<std::vector<index_type>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<index_type>>>();\n mline.lines = arcs_;\n mline.props = props;\n }\n return mline;\n }\n};\n\nstruct create_polygon\n{\n using result_type = mapnik::topojson::polygon;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::polygon poly;\n if (arcs.template is<std::vector<std::vector<index_type>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<index_type>>>();\n poly.rings = arcs_;\n poly.props = props;\n }\n return poly;\n }\n};\n\nstruct create_multi_polygon\n{\n using result_type = mapnik::topojson::multi_polygon;\n template <typename T0, typename T1>\n result_type operator()(T0 & arcs, T1 & props) const\n {\n mapnik::topojson::multi_polygon mpoly;\n if (arcs.template is<std::vector<std::vector<std::vector<index_type>>>>())\n {\n auto const& arcs_ = arcs.template get<std::vector<std::vector<std::vector<index_type>>>>();\n mpoly.polygons = arcs_;\n mpoly.props = props;\n }\n return mpoly;\n }\n};\n\n\nauto create_geometry = [] (auto const& ctx)\n{\n auto const geom_type = std::get<0>(_attr(ctx));\n auto const& coord = std::get<1>(_attr(ctx));\n auto const& arcs = std::get<2>(_attr(ctx));\n auto const& props = std::get<3>(_attr(ctx));\n mapnik::topojson::geometry geom; \/\/empty\n switch (geom_type)\n {\n case 1: \/\/Point\n geom = create_point()(coord, props);\n break;\n case 2: \/\/LineString\n geom = create_line_string()(arcs, props);\n break;\n case 3: \/\/Polygon\n geom = create_polygon()(arcs, props);\n break;\n case 4: \/\/MultiPoint\n geom = create_multi_point()(coord, props);\n break;\n case 5: \/\/MultiLineString\n geom = create_multi_line_string()(arcs, props);\n break;\n case 6: \/\/MultiPolygon\n geom = create_multi_polygon()(arcs, props);\n break;\n }\n _val(ctx) = std::move(geom);\n};\n\n\nauto assign_bbox = [] (auto const& ctx)\n{\n _val(ctx).bbox = std::move(_attr(ctx));\n};\n\nauto assign_transform = [] (auto const& ctx)\n{\n _val(ctx).tr = std::move(_attr(ctx));\n};\n\nauto assign_arcs = [] (auto const& ctx)\n{\n _val(ctx).arcs = std::move(_attr(ctx));\n};\n\nauto assign_objects = [] (auto const& ctx)\n{\n _val(ctx).geometries = std::move(_attr(ctx));\n};\n\n\nauto push_geometry = [] (auto const& ctx)\n{\n _val(ctx).push_back(std::move(_attr(ctx)));\n};\n\nauto push_collection = [] (auto const& ctx)\n{\n auto & dest = _val(ctx);\n auto & src = _attr(ctx);\n if (dest.empty()) dest = std::move(src);\n else\n {\n dest.reserve(dest.size() + src.size());\n dest.insert(std::end(dest),\n std::make_move_iterator(std::begin(src)),\n std::make_move_iterator(std::end(src)));\n }\n};\n\n\nauto assign_geometry_type = [] (auto const& ctx)\n{\n std::get<0>(_val(ctx)) = _attr(ctx);\n};\n\nauto assign_coordinates = [] (auto const& ctx)\n{\n std::get<1>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_rings = [] (auto const& ctx)\n{\n std::get<2>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_properties = [] (auto const& ctx)\n{\n std::get<3>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_prop_name = [] (auto const& ctx)\n{\n std::get<0>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nauto assign_prop_value = [] (auto const& ctx)\n{\n std::get<1>(_val(ctx)) = std::move(_attr(ctx));\n};\n\nnamespace x3 = boost::spirit::x3;\n\nusing x3::lit;\nusing x3::double_;\nusing x3::int_;\nusing x3::omit;\nusing x3::char_;\nnamespace\n{\n\/\/ import unicode string rule\nauto const& json_string = json::unicode_string_grammar();\n\/\/ json value\nauto const& json_value = json::generic_json_grammar();\n}\n\nusing coordinates_type = util::variant<topojson::coordinate,std::vector<topojson::coordinate>>;\nusing arcs_type = util::variant<std::vector<index_type>,\n std::vector<std::vector<index_type>>,\n std::vector<std::vector<std::vector<index_type>>>>;\n\nstruct topojson_geometry_type_ : x3::symbols<int>\n{\n topojson_geometry_type_()\n {\n add\n (\"\\\"Point\\\"\",1)\n (\"\\\"LineString\\\"\",2)\n (\"\\\"Polygon\\\"\",3)\n (\"\\\"MultiPoint\\\"\",4)\n (\"\\\"MultiLineString\\\"\",5)\n (\"\\\"MultiPolygon\\\"\",6)\n ;\n }\n} topojson_geometry_type;\n\n\/\/ start rule\ntopojson_grammar_type const topology = \"Topology\";\n\/\/ rules\nx3::rule<class transform_tag, mapnik::topojson::transform> const transform = \"Transform\";\nx3::rule<class bbox_tag, mapnik::topojson::bounding_box> const bbox = \"Bounding Box\";\nx3::rule<class objects_tag, std::vector<mapnik::topojson::geometry>> const objects= \"Objects\";\nx3::rule<class property_tag, mapnik::topojson::property> const property = \"Property\";\nx3::rule<class properties_tag, mapnik::topojson::properties> const properties = \"Properties\";\nx3::rule<class geometry_tag, mapnik::topojson::geometry> const geometry = \"Geometry\";\nx3::rule<class geometry_collection_tag, std::vector<mapnik::topojson::geometry>> const geometry_collection = \"Geometry Collection\";\nx3::rule<class geometry_tuple_tag,\n std::tuple<int,\n coordinates_type,\n arcs_type,\n mapnik::topojson::properties>> const geometry_tuple = \"Geometry Tuple\";\nx3::rule<class coordinate_tag, mapnik::topojson::coordinate> const coordinate = \"Coordinate\";\nx3::rule<class coordinates_tag, coordinates_type> const coordinates = \"Coordinates\";\nx3::rule<class arc_tag, mapnik::topojson::arc> const arc = \"Arc\";\nx3::rule<class arcs_tag, std::vector<mapnik::topojson::arc>> const arcs = \"Arcs\";\nx3::rule<class ring_type, std::vector<index_type>> const ring = \"Ring\";\nx3::rule<class rings_type, std::vector<std::vector<index_type>>> const rings = \"Rings\";\nx3::rule<class rings_array_type, arcs_type> const rings_array = \"Rings Array\";\n\n\/\/ defs\nauto const topology_def = lit('{') >\n -(((lit(\"\\\"type\\\"\") > lit(':') > lit(\"\\\"Topology\\\"\"))\n |\n bbox[assign_bbox]\n |\n transform[assign_transform]\n |\n objects[assign_objects]\n |\n arcs[assign_arcs]) % lit(','))\n > lit('}')\n ;\n\n\nauto const transform_def = lit(\"\\\"transform\\\"\") > lit(':') > lit('{')\n > lit(\"\\\"scale\\\"\") > lit(':')\n > lit('[')\n > double_ > lit(',')\n > double_ > lit(']') > lit(',')\n > lit(\"\\\"translate\\\"\") > lit(':')\n > lit('[') > double_ > lit(',') > double_ > lit(']')\n > lit('}')\n ;\n\nauto const bbox_def = lit(\"\\\"bbox\\\"\") > lit(':')\n > lit('[') > double_ > lit(',') > double_\n > lit(',') > double_ > lit(',') > double_\n > lit(']')\n ;\n\n\nauto const objects_def = lit(\"\\\"objects\\\"\") > lit(':')\n > lit('{')\n > ((omit[*~char_(':')] > lit(':') > ((geometry_collection[push_collection] | geometry[push_geometry]))) % lit(','))\n > lit('}')\n ;\n\nauto const geometry_tuple_def =\n ((lit(\"\\\"type\\\"\") > lit(':') > topojson_geometry_type[assign_geometry_type])\n |\n (lit(\"\\\"coordinates\\\"\") > lit(':') > coordinates[assign_coordinates])\n |\n (lit(\"\\\"arcs\\\"\") > lit(':') > rings_array[assign_rings])\n |\n properties[assign_properties]\n |\n (omit[json_string] > lit(':') > omit[json_value])) % lit(',')\n ;\n\nauto const geometry_def = lit(\"{\") > geometry_tuple[create_geometry] > lit(\"}\");\n\nauto const geometry_collection_def = (lit('{') >> lit(\"\\\"type\\\"\") >> lit(':') >> lit(\"\\\"GeometryCollection\\\"\") >> -omit[lit(',') >> bbox])\n > lit(',') > lit(\"\\\"geometries\\\"\") > lit(':')\n > lit('[')\n > -(geometry[push_geometry] % lit(','))\n > lit(']')\n > lit('}')\n ;\n\n\nauto const ring_def = lit('[') >> (int_ % lit(',')) >> lit(']')\n ;\nauto const rings_def = lit('[') >> (ring % lit(',')) >> lit(']')\n ;\nauto const rings_array_def = (lit('[') >> (rings % lit(',')) >> lit(']'))\n |\n rings\n |\n ring\n ;\n\nauto const property_def = json_string[assign_prop_name] > lit(':') > json_value[assign_prop_value]\n ;\n\nauto const properties_def = lit(\"\\\"properties\\\"\")\n > lit(':')\n > lit('{') > (property % lit(',')) > lit('}')\n ;\n\nauto const arcs_def = lit(\"\\\"arcs\\\"\") >> lit(':') >> lit('[') >> -( arc % lit(',')) >> lit(']') ;\n\nauto const arc_def = lit('[') >> -(coordinate % lit(',')) >> lit(']') ;\n\nauto const coordinate_def = lit('[') >> double_ >> lit(',') >> double_ >> omit[*(lit(',') >> double_)] >> lit(']');\n\nauto const coordinates_def = (lit('[') >> coordinate % lit(',') >> lit(']')) | coordinate;\n\nBOOST_SPIRIT_DEFINE(\n topology,\n transform,\n bbox,\n objects,\n geometry_tuple,\n geometry,\n geometry_collection,\n ring,\n rings,\n rings_array,\n property,\n properties,\n arcs,\n arc,\n coordinate,\n coordinates\n );\n\n}}}\n\nnamespace mapnik { namespace json {\ngrammar::topojson_grammar_type const& topojson_grammar()\n{\n return grammar::topology;\n}\n}}\n\n#endif \/\/MAPNIK_TOPOJSON_GRAMMAR_X3_DEF_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n============================================================================\nDELLY: Structural variant discovery by integrated PE mapping and SR analysis\n============================================================================\nCopyright (C) 2012 Tobias Rausch\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n============================================================================\nContact: Tobias Rausch (rausch@embl.de)\n============================================================================\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/connected_components.hpp>\n#include <boost\/program_options\/cmdline.hpp>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/date_time\/gregorian\/gregorian.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/stream_buffer.hpp>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/zlib.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/tokenizer.hpp>\n#include <boost\/progress.hpp>\n#include \"api\/BamReader.h\"\n#include \"api\/BamIndex.h\"\n\n#ifdef OPENMP\n#include <omp.h>\n#endif\n\n#include \"tags.h\"\n#include \"coverage.h\"\n#include \"version.h\"\n#include \"util.h\"\n\nusing namespace torali;\n\nstruct Config {\n unsigned int window_size;\n unsigned int window_offset;\n uint16_t minMapQual;\n bool bp_flag;\n bool avg_flag;\n bool inclCigar;\n boost::filesystem::path outfile;\n boost::filesystem::path int_file;\n std::vector<boost::filesystem::path> files;\n};\n\n\ntemplate<typename TSingleHit, typename TCoverageType>\ninline int\nrun(Config const& c, TSingleHit, TCoverageType covType)\n{\n \/\/ Create library objects\n typedef std::map<std::string, LibraryInfo> TLibraryMap;\n typedef std::map<std::string, TLibraryMap> TSampleLibrary;\n TSampleLibrary sampleLib;\n\n \/\/ Scan libraries\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get a sample name\n std::string sampleName(c.files[file_c].stem().string());\n\n \/\/ Check that all input bam files exist\n BamTools::BamReader reader;\n if ( ! reader.Open(c.files[file_c].string()) ) {\n std::cerr << \"Could not open input bam file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n \n \/\/ Check that all input bam files are indexed\n reader.LocateIndex();\n if ( !reader.HasIndex() ) {\n std::cerr << \"Missing bam index file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n\n \/\/ Get library parameters and overall maximum insert size\n TLibraryMap libInfo;\n getLibraryParams(c.files[file_c], libInfo, 0, 5);\n sampleLib.insert(std::make_pair(sampleName, libInfo));\n }\n\n \/\/ Get references\n BamTools::BamReader readerRef;\n if ( ! readerRef.Open(c.files[0].string()) ) return -1;\n BamTools::RefVector references = readerRef.GetReferenceData();\n\n \/\/ Read all SV intervals\n typedef std::vector<StructuralVariantRecord> TSVs;\n TSVs svs;\n std::map<unsigned int, std::string> idToName;\n unsigned int intervalCount=1;\n if (boost::filesystem::exists(c.int_file) && boost::filesystem::is_regular_file(c.int_file) && boost::filesystem::file_size(c.int_file)) {\n typedef boost::unordered_map<std::string, unsigned int> TMapChr;\n TMapChr mapChr;\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(unsigned int i = 0;itRef!=references.end();++itRef, ++i) mapChr[ itRef->RefName ] = i;\n std::ifstream interval_file(c.int_file.string().c_str(), std::ifstream::in);\n if (interval_file.is_open()) {\n while (interval_file.good()) {\n\tstd::string intervalLine;\n\tgetline(interval_file, intervalLine);\n\ttypedef boost::tokenizer< boost::char_separator<char> > Tokenizer;\n\tboost::char_separator<char> sep(\" \\t,;\");\n\tTokenizer tokens(intervalLine, sep);\n\tTokenizer::iterator tokIter = tokens.begin();\n\tif (tokIter!=tokens.end()) {\n\t std::string chrName=*tokIter++;\n\t TMapChr::const_iterator mapChrIt = mapChr.find(chrName);\n\t if (mapChrIt != mapChr.end()) {\n\t if (tokIter!=tokens.end()) {\n\t StructuralVariantRecord sv;\t \n\t sv.chr = mapChrIt->second;\n\t sv.chr2 = mapChrIt->second;\n\t sv.svStart = boost::lexical_cast<int32_t>(*tokIter++);\n\t sv.svEnd = boost::lexical_cast<int32_t>(*tokIter++) + 1;\n\t std::string svName = *tokIter;\n\t idToName.insert(std::make_pair(intervalCount, svName));\n\t sv.id = intervalCount++;\n\t svs.push_back(sv);\n\t }\n\t }\n\t}\n }\n interval_file.close();\n }\n } else {\n \/\/ Create artificial intervals\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(int refIndex=0;itRef!=references.end();++itRef, ++refIndex) {\n int32_t pos = 0;\n while (pos < references[refIndex].RefLength) {\n\tint32_t window_len = pos+c.window_size;\n\tif (window_len > references[refIndex].RefLength) window_len = references[refIndex].RefLength;\n\tStructuralVariantRecord sv;\n\tsv.chr = refIndex;\n\tsv.chr2 = refIndex;\n\tsv.svStart = pos;\n\tsv.svEnd = window_len;\n\tstd::stringstream s; \n\ts << references[sv.chr].RefName << \":\" << sv.svStart << \"-\" << sv.svEnd;\n\tidToName.insert(std::make_pair(intervalCount, s.str()));\n\tsv.id = intervalCount++;\n\tsvs.push_back(sv);\n\tpos += c.window_offset;\n }\n }\n }\n\n \/\/ Output data types\n typedef std::pair<std::string, int> TSampleSVPair;\n typedef std::pair<int, int> TBpRead;\n typedef std::map<TSampleSVPair, TBpRead> TCountMap;\n TCountMap countMap;\n\n \/\/ Annotate coverage\n annotateCoverage(c.files, c.minMapQual, c.inclCigar, sampleLib, svs, countMap, TSingleHit(), covType);\n\n \/\/ Output library statistics\n std::cout << \"Library statistics\" << std::endl;\n TSampleLibrary::const_iterator sampleIt=sampleLib.begin();\n for(;sampleIt!=sampleLib.end();++sampleIt) {\n std::cout << \"Sample: \" << sampleIt->first << std::endl;\n TLibraryMap::const_iterator libIt=sampleIt->second.begin();\n for(;libIt!=sampleIt->second.end();++libIt) {\n std::cout << \"RG: ID=\" << libIt->first << \",Median=\" << libIt->second.median << \",MAD=\" << libIt->second.mad << \",Orientation=\" << (int) libIt->second.defaultOrient << \",MappedReads=\" << libIt->second.mappedReads << \",DuplicatePairs=\" << libIt->second.non_unique_pairs << \",UniquePairs=\" << libIt->second.unique_pairs << std::endl;\n }\n }\n\n \/\/ Output file\n boost::iostreams::filtering_ostream dataOut;\n dataOut.push(boost::iostreams::gzip_compressor());\n dataOut.push(boost::iostreams::file_sink(c.outfile.string().c_str(), std::ios_base::out | std::ios_base::binary));\n\n \/\/ Print header\n dataOut << \"#chr\\tstart\\tend\\tid\";\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n std::string sampleName(c.files[file_c].stem().string());\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << sampleName << \"_avgcov\" << \"\\t\";\n if (c.bp_flag) dataOut << sampleName << \"_bpcount\" << \"\\t\";\n dataOut << sampleName << \"_readcount\";\n }\n dataOut << std::endl;\n\n \/\/ Iterate all SVs\n typename TSVs::const_iterator itSV = svs.begin();\n typename TSVs::const_iterator itSVEnd = svs.end();\n for(;itSV!=itSVEnd;++itSV) {\n dataOut << references[itSV->chr].RefName << \"\\t\" << itSV->svStart << \"\\t\" << itSV->svEnd << \"\\t\" << idToName.find(itSV->id)->second;\n \/\/ Iterate all samples\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get the sample name\n std::string sampleName(c.files[file_c].stem().string());\n TSampleSVPair sampleSVPair = std::make_pair(sampleName, itSV->id);\n typename TCountMap::iterator countMapIt=countMap.find(sampleSVPair);\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << ( (countMapIt->second.first) \/ (double) (itSV->svEnd - itSV->svStart)) << \"\\t\";\n if (c.bp_flag) dataOut << countMapIt->second.first << \"\\t\";\n dataOut << countMapIt->second.second;\n }\n dataOut << std::endl;\n }\n\n \/\/ End\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] Done.\" << std::endl;;\n return 0;\n}\n\n\nint main(int argc, char **argv) {\n Config c;\n\n \/\/ Define generic options\n boost::program_options::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,?\", \"show help message\")\n (\"bp-count,b\", \"show base pair count\")\n (\"avg-cov,a\", \"show average coverage\")\n (\"disable-redundancy,d\", \"disable redundancy filtering\")\n (\"quality-cut,q\", boost::program_options::value<uint16_t>(&c.minMapQual)->default_value(0), \"exclude all alignments with quality < q\")\n (\"outfile,f\", boost::program_options::value<boost::filesystem::path>(&c.outfile)->default_value(\"cov.gz\"), \"coverage output file\")\n ;\n\n \/\/ Define window options\n boost::program_options::options_description window(\"Window options\");\n window.add_options()\n (\"window-size,s\", boost::program_options::value<unsigned int>(&c.window_size)->default_value(10000), \"window size\")\n (\"window-offset,o\", boost::program_options::value<unsigned int>(&c.window_offset)->default_value(10000), \"window offset\")\n ;\n\n \/\/ Define interval options\n boost::program_options::options_description interval(\"Interval options\");\n interval.add_options()\n (\"interval-file,i\", boost::program_options::value<boost::filesystem::path>(&c.int_file), \"interval file\")\n ;\n\n \/\/ Define hidden options\n boost::program_options::options_description hidden(\"Hidden options\");\n hidden.add_options()\n (\"input-file\", boost::program_options::value< std::vector<boost::filesystem::path> >(&c.files), \"input file\")\n (\"license,l\", \"show license\")\n (\"warranty,w\", \"show warranty\")\n ;\n boost::program_options::positional_options_description pos_args;\n pos_args.add(\"input-file\", -1);\n\n \/\/ Set the visibility\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(window).add(interval).add(hidden);\n boost::program_options::options_description visible_options;\n visible_options.add(generic).add(window).add(interval);\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);\n boost::program_options::notify(vm);\n\n\n \/\/ Check command line arguments\n if ((vm.count(\"help\")) || (!vm.count(\"input-file\"))) { \n printTitle(\"Coverage calculation\");\n if (vm.count(\"warranty\")) {\n displayWarranty();\n } else if (vm.count(\"license\")) {\n gplV3();\n } else {\n std::cout << \"Usage: \" << argv[0] << \" [OPTIONS] <sample1.bam> <sample2.bam> ...\" << std::endl;\n std::cout << visible_options << \"\\n\"; \n }\n return 1; \n }\n bool disableRedFilter=false;\n if (vm.count(\"disable-redundancy\")) disableRedFilter=true;\n if (vm.count(\"bp-count\")) c.bp_flag = true;\n else c.bp_flag = false;\n if (vm.count(\"avg-cov\")) c.avg_flag = true;\n else c.avg_flag = false;\n if ((c.bp_flag) || (c.avg_flag)) c.inclCigar = true;\n else c.inclCigar = false;\n\n \/\/ Show cmd\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] \";\n for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; }\n std::cout << std::endl;\n \n \/\/ Run coverage annotation\n if (c.inclCigar) {\n if (disableRedFilter) return run(c, SingleHit<int32_t, std::string>(), CoverageType<NoRedundancyFilterTag>());\n else return run(c, SingleHit<int32_t, std::string>(), CoverageType<RedundancyFilterTag>());\n } else {\n if (disableRedFilter) run(c, SingleHit<int32_t, void>(), CoverageType<NoRedundancyFilterTag>());\n else return run(c, SingleHit<int32_t, void>(), CoverageType<RedundancyFilterTag>());\n }\n}\n<commit_msg>Removed _readcount in the header.<commit_after>\/*\n============================================================================\nDELLY: Structural variant discovery by integrated PE mapping and SR analysis\n============================================================================\nCopyright (C) 2012 Tobias Rausch\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n============================================================================\nContact: Tobias Rausch (rausch@embl.de)\n============================================================================\n*\/\n\n#include <iostream>\n#include <fstream>\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/connected_components.hpp>\n#include <boost\/program_options\/cmdline.hpp>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/date_time\/gregorian\/gregorian.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/stream_buffer.hpp>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/zlib.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/tokenizer.hpp>\n#include <boost\/progress.hpp>\n#include \"api\/BamReader.h\"\n#include \"api\/BamIndex.h\"\n\n#ifdef OPENMP\n#include <omp.h>\n#endif\n\n#include \"tags.h\"\n#include \"coverage.h\"\n#include \"version.h\"\n#include \"util.h\"\n\nusing namespace torali;\n\nstruct Config {\n unsigned int window_size;\n unsigned int window_offset;\n uint16_t minMapQual;\n bool bp_flag;\n bool avg_flag;\n bool inclCigar;\n boost::filesystem::path outfile;\n boost::filesystem::path int_file;\n std::vector<boost::filesystem::path> files;\n};\n\n\ntemplate<typename TSingleHit, typename TCoverageType>\ninline int\nrun(Config const& c, TSingleHit, TCoverageType covType)\n{\n \/\/ Create library objects\n typedef std::map<std::string, LibraryInfo> TLibraryMap;\n typedef std::map<std::string, TLibraryMap> TSampleLibrary;\n TSampleLibrary sampleLib;\n\n \/\/ Scan libraries\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get a sample name\n std::string sampleName(c.files[file_c].stem().string());\n\n \/\/ Check that all input bam files exist\n BamTools::BamReader reader;\n if ( ! reader.Open(c.files[file_c].string()) ) {\n std::cerr << \"Could not open input bam file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n \n \/\/ Check that all input bam files are indexed\n reader.LocateIndex();\n if ( !reader.HasIndex() ) {\n std::cerr << \"Missing bam index file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n\n \/\/ Get library parameters and overall maximum insert size\n TLibraryMap libInfo;\n getLibraryParams(c.files[file_c], libInfo, 0, 5);\n sampleLib.insert(std::make_pair(sampleName, libInfo));\n }\n\n \/\/ Get references\n BamTools::BamReader readerRef;\n if ( ! readerRef.Open(c.files[0].string()) ) return -1;\n BamTools::RefVector references = readerRef.GetReferenceData();\n\n \/\/ Read all SV intervals\n typedef std::vector<StructuralVariantRecord> TSVs;\n TSVs svs;\n std::map<unsigned int, std::string> idToName;\n unsigned int intervalCount=1;\n if (boost::filesystem::exists(c.int_file) && boost::filesystem::is_regular_file(c.int_file) && boost::filesystem::file_size(c.int_file)) {\n typedef boost::unordered_map<std::string, unsigned int> TMapChr;\n TMapChr mapChr;\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(unsigned int i = 0;itRef!=references.end();++itRef, ++i) mapChr[ itRef->RefName ] = i;\n std::ifstream interval_file(c.int_file.string().c_str(), std::ifstream::in);\n if (interval_file.is_open()) {\n while (interval_file.good()) {\n\tstd::string intervalLine;\n\tgetline(interval_file, intervalLine);\n\ttypedef boost::tokenizer< boost::char_separator<char> > Tokenizer;\n\tboost::char_separator<char> sep(\" \\t,;\");\n\tTokenizer tokens(intervalLine, sep);\n\tTokenizer::iterator tokIter = tokens.begin();\n\tif (tokIter!=tokens.end()) {\n\t std::string chrName=*tokIter++;\n\t TMapChr::const_iterator mapChrIt = mapChr.find(chrName);\n\t if (mapChrIt != mapChr.end()) {\n\t if (tokIter!=tokens.end()) {\n\t StructuralVariantRecord sv;\t \n\t sv.chr = mapChrIt->second;\n\t sv.chr2 = mapChrIt->second;\n\t sv.svStart = boost::lexical_cast<int32_t>(*tokIter++);\n\t sv.svEnd = boost::lexical_cast<int32_t>(*tokIter++) + 1;\n\t std::string svName = *tokIter;\n\t idToName.insert(std::make_pair(intervalCount, svName));\n\t sv.id = intervalCount++;\n\t svs.push_back(sv);\n\t }\n\t }\n\t}\n }\n interval_file.close();\n }\n } else {\n \/\/ Create artificial intervals\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(int refIndex=0;itRef!=references.end();++itRef, ++refIndex) {\n int32_t pos = 0;\n while (pos < references[refIndex].RefLength) {\n\tint32_t window_len = pos+c.window_size;\n\tif (window_len > references[refIndex].RefLength) window_len = references[refIndex].RefLength;\n\tStructuralVariantRecord sv;\n\tsv.chr = refIndex;\n\tsv.chr2 = refIndex;\n\tsv.svStart = pos;\n\tsv.svEnd = window_len;\n\tstd::stringstream s; \n\ts << references[sv.chr].RefName << \":\" << sv.svStart << \"-\" << sv.svEnd;\n\tidToName.insert(std::make_pair(intervalCount, s.str()));\n\tsv.id = intervalCount++;\n\tsvs.push_back(sv);\n\tpos += c.window_offset;\n }\n }\n }\n\n \/\/ Output data types\n typedef std::pair<std::string, int> TSampleSVPair;\n typedef std::pair<int, int> TBpRead;\n typedef std::map<TSampleSVPair, TBpRead> TCountMap;\n TCountMap countMap;\n\n \/\/ Annotate coverage\n annotateCoverage(c.files, c.minMapQual, c.inclCigar, sampleLib, svs, countMap, TSingleHit(), covType);\n\n \/\/ Output library statistics\n std::cout << \"Library statistics\" << std::endl;\n TSampleLibrary::const_iterator sampleIt=sampleLib.begin();\n for(;sampleIt!=sampleLib.end();++sampleIt) {\n std::cout << \"Sample: \" << sampleIt->first << std::endl;\n TLibraryMap::const_iterator libIt=sampleIt->second.begin();\n for(;libIt!=sampleIt->second.end();++libIt) {\n std::cout << \"RG: ID=\" << libIt->first << \",Median=\" << libIt->second.median << \",MAD=\" << libIt->second.mad << \",Orientation=\" << (int) libIt->second.defaultOrient << \",MappedReads=\" << libIt->second.mappedReads << \",DuplicatePairs=\" << libIt->second.non_unique_pairs << \",UniquePairs=\" << libIt->second.unique_pairs << std::endl;\n }\n }\n\n \/\/ Output file\n boost::iostreams::filtering_ostream dataOut;\n dataOut.push(boost::iostreams::gzip_compressor());\n dataOut.push(boost::iostreams::file_sink(c.outfile.string().c_str(), std::ios_base::out | std::ios_base::binary));\n\n \/\/ Print header\n dataOut << \"#chr\\tstart\\tend\\tid\";\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n std::string sampleName(c.files[file_c].stem().string());\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << sampleName << \"_avgcov\" << \"\\t\";\n if (c.bp_flag) dataOut << sampleName << \"_bpcount\" << \"\\t\";\n if ((c.bp_flag) || (c.avg_flag)) dataOut << sampleName << \"_readcount\";\n else dataOut << sampleName;\n }\n dataOut << std::endl;\n\n \/\/ Iterate all SVs\n typename TSVs::const_iterator itSV = svs.begin();\n typename TSVs::const_iterator itSVEnd = svs.end();\n for(;itSV!=itSVEnd;++itSV) {\n dataOut << references[itSV->chr].RefName << \"\\t\" << itSV->svStart << \"\\t\" << itSV->svEnd << \"\\t\" << idToName.find(itSV->id)->second;\n \/\/ Iterate all samples\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get the sample name\n std::string sampleName(c.files[file_c].stem().string());\n TSampleSVPair sampleSVPair = std::make_pair(sampleName, itSV->id);\n typename TCountMap::iterator countMapIt=countMap.find(sampleSVPair);\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << ( (countMapIt->second.first) \/ (double) (itSV->svEnd - itSV->svStart)) << \"\\t\";\n if (c.bp_flag) dataOut << countMapIt->second.first << \"\\t\";\n dataOut << countMapIt->second.second;\n }\n dataOut << std::endl;\n }\n\n \/\/ End\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] Done.\" << std::endl;;\n return 0;\n}\n\n\nint main(int argc, char **argv) {\n Config c;\n\n \/\/ Define generic options\n boost::program_options::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,?\", \"show help message\")\n (\"bp-count,b\", \"show base pair count\")\n (\"avg-cov,a\", \"show average coverage\")\n (\"disable-redundancy,d\", \"disable redundancy filtering\")\n (\"quality-cut,q\", boost::program_options::value<uint16_t>(&c.minMapQual)->default_value(0), \"exclude all alignments with quality < q\")\n (\"outfile,f\", boost::program_options::value<boost::filesystem::path>(&c.outfile)->default_value(\"cov.gz\"), \"coverage output file\")\n ;\n\n \/\/ Define window options\n boost::program_options::options_description window(\"Window options\");\n window.add_options()\n (\"window-size,s\", boost::program_options::value<unsigned int>(&c.window_size)->default_value(10000), \"window size\")\n (\"window-offset,o\", boost::program_options::value<unsigned int>(&c.window_offset)->default_value(10000), \"window offset\")\n ;\n\n \/\/ Define interval options\n boost::program_options::options_description interval(\"Interval options\");\n interval.add_options()\n (\"interval-file,i\", boost::program_options::value<boost::filesystem::path>(&c.int_file), \"interval file\")\n ;\n\n \/\/ Define hidden options\n boost::program_options::options_description hidden(\"Hidden options\");\n hidden.add_options()\n (\"input-file\", boost::program_options::value< std::vector<boost::filesystem::path> >(&c.files), \"input file\")\n (\"license,l\", \"show license\")\n (\"warranty,w\", \"show warranty\")\n ;\n boost::program_options::positional_options_description pos_args;\n pos_args.add(\"input-file\", -1);\n\n \/\/ Set the visibility\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(window).add(interval).add(hidden);\n boost::program_options::options_description visible_options;\n visible_options.add(generic).add(window).add(interval);\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);\n boost::program_options::notify(vm);\n\n\n \/\/ Check command line arguments\n if ((vm.count(\"help\")) || (!vm.count(\"input-file\"))) { \n printTitle(\"Coverage calculation\");\n if (vm.count(\"warranty\")) {\n displayWarranty();\n } else if (vm.count(\"license\")) {\n gplV3();\n } else {\n std::cout << \"Usage: \" << argv[0] << \" [OPTIONS] <sample1.bam> <sample2.bam> ...\" << std::endl;\n std::cout << visible_options << \"\\n\"; \n }\n return 1; \n }\n bool disableRedFilter=false;\n if (vm.count(\"disable-redundancy\")) disableRedFilter=true;\n if (vm.count(\"bp-count\")) c.bp_flag = true;\n else c.bp_flag = false;\n if (vm.count(\"avg-cov\")) c.avg_flag = true;\n else c.avg_flag = false;\n if ((c.bp_flag) || (c.avg_flag)) c.inclCigar = true;\n else c.inclCigar = false;\n\n \/\/ Show cmd\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] \";\n for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; }\n std::cout << std::endl;\n \n \/\/ Run coverage annotation\n if (c.inclCigar) {\n if (disableRedFilter) return run(c, SingleHit<int32_t, std::string>(), CoverageType<NoRedundancyFilterTag>());\n else return run(c, SingleHit<int32_t, std::string>(), CoverageType<RedundancyFilterTag>());\n } else {\n if (disableRedFilter) run(c, SingleHit<int32_t, void>(), CoverageType<NoRedundancyFilterTag>());\n else return run(c, SingleHit<int32_t, void>(), CoverageType<RedundancyFilterTag>());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2014-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <boost\/lexical_cast.hpp>\n\n#include <pcl\/common\/io.h>\n#include <pcl\/io\/depth_sense_grabber.h>\n#include <pcl\/io\/depth_sense\/depth_sense_grabber_impl.h>\n#include <pcl\/io\/depth_sense\/depth_sense_device_manager.h>\n\npcl::io::depth_sense::DepthSenseGrabberImpl::DepthSenseGrabberImpl (DepthSenseGrabber* parent, const std::string& device_id)\n: p_ (parent)\n, is_running_ (false)\n, confidence_threshold_ (50)\n, temporal_filtering_type_ (DepthSenseGrabber::DepthSense_None)\n, color_data_ (COLOR_SIZE * 3)\n, depth_buffer_ (new pcl::io::SingleBuffer<float> (SIZE))\n{\n if (device_id == \"\")\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this);\n else if (device_id[0] == '#')\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this, boost::lexical_cast<int> (device_id.substr (1)) - 1);\n else\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this, device_id);\n\n point_cloud_signal_ = p_->createSignal<sig_cb_depth_sense_point_cloud> ();\n point_cloud_rgba_signal_ = p_->createSignal<sig_cb_depth_sense_point_cloud_rgba> ();\n}\n\npcl::io::depth_sense::DepthSenseGrabberImpl::~DepthSenseGrabberImpl () throw ()\n{\n stop ();\n\n DepthSenseDeviceManager::getInstance ()->releaseDevice (device_id_);\n\n p_->disconnect_all_slots<sig_cb_depth_sense_point_cloud> ();\n p_->disconnect_all_slots<sig_cb_depth_sense_point_cloud_rgba> ();\n}\n\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::start ()\n{\n need_xyz_ = p_->num_slots<sig_cb_depth_sense_point_cloud> () > 0;\n need_xyzrgba_ = p_->num_slots<sig_cb_depth_sense_point_cloud_rgba> () > 0;\n\n if (!is_running_)\n {\n DepthSenseDeviceManager::getInstance ()->reconfigureDevice (device_id_);\n DepthSenseDeviceManager::getInstance ()->startDevice (device_id_);\n frequency_.reset ();\n is_running_ = true;\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::stop ()\n{\n if (is_running_)\n {\n DepthSenseDeviceManager::getInstance ()->stopDevice (device_id_);\n is_running_ = false;\n }\n}\n\nfloat\npcl::io::depth_sense::DepthSenseGrabberImpl::getFramesPerSecond () const\n{\n boost::mutex::scoped_lock lock (fps_mutex_);\n return (frequency_.getFrequency ());\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::setConfidenceThreshold (int threshold)\n{\n confidence_threshold_ = threshold;\n DepthSenseDeviceManager::getInstance ()->reconfigureDevice (device_id_);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::enableTemporalFiltering (DepthSenseGrabber::TemporalFilteringType type, size_t window_size)\n{\n if (temporal_filtering_type_ != type ||\n (type != DepthSenseGrabber::DepthSense_None && depth_buffer_->size () != window_size))\n {\n bool was_running = is_running_;\n if (was_running)\n stop ();\n switch (type)\n {\n case DepthSenseGrabber::DepthSense_None:\n {\n depth_buffer_.reset (new pcl::io::SingleBuffer<float> (SIZE));\n break;\n }\n case DepthSenseGrabber::DepthSense_Median:\n {\n depth_buffer_.reset (new pcl::io::MedianBuffer<float> (SIZE, window_size));\n break;\n }\n case DepthSenseGrabber::DepthSense_Average:\n {\n depth_buffer_.reset (new pcl::io::AverageBuffer<float> (SIZE, window_size));\n break;\n }\n }\n temporal_filtering_type_ = type;\n if (was_running)\n start ();\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::setCameraParameters (const DepthSense::StereoCameraParameters& parameters)\n{\n projection_.reset (new DepthSense::ProjectionHelper (parameters));\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::configureDepthNode (DepthSense::DepthNode node) const\n{\n DepthSense::DepthNode::Configuration config = node.getConfiguration ();\n config.frameFormat = DepthSense::FRAME_FORMAT_QVGA;\n config.framerate = FRAMERATE;\n config.mode = DepthSense::DepthNode::CAMERA_MODE_CLOSE_MODE;\n config.saturation = false;\n node.setEnableDepthMapFloatingPoint (true);\n node.setEnableUvMap (true);\n node.setEnableConfidenceMap (true);\n node.setConfiguration (config);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::configureColorNode (DepthSense::ColorNode node) const\n{\n DepthSense::ColorNode::Configuration config = node.getConfiguration ();\n config.frameFormat = DepthSense::FRAME_FORMAT_VGA;\n config.compression = DepthSense::COMPRESSION_TYPE_MJPEG;\n config.powerLineFrequency = DepthSense::POWER_LINE_FREQUENCY_50HZ;\n config.framerate = FRAMERATE;\n node.setEnableColorMap (true);\n node.setConfiguration (config);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::onDepthDataReceived (DepthSense::DepthNode node, DepthSense::DepthNode::NewSampleReceivedData data)\n{\n fps_mutex_.lock ();\n frequency_.event ();\n fps_mutex_.unlock ();\n\n static const float nan = std::numeric_limits<float>::quiet_NaN ();\n\n std::vector<float> depth_data (SIZE);\n memcpy (depth_data.data (), &data.depthMapFloatingPoint[0], SIZE * sizeof (float));\n for (int i = 0; i < SIZE; i++)\n if (data.confidenceMap[i] < confidence_threshold_)\n depth_data[i] = nan;\n depth_buffer_->push (depth_data);\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr xyz_cloud;\n pcl::PointCloud<pcl::PointXYZRGBA>::Ptr xyzrgba_cloud;\n\n if (need_xyz_)\n {\n xyz_cloud.reset (new pcl::PointCloud<pcl::PointXYZ> (WIDTH, HEIGHT));\n xyz_cloud->is_dense = false;\n\n computeXYZ (*xyz_cloud);\n\n point_cloud_signal_->operator () (xyz_cloud);\n }\n\n if (need_xyzrgba_)\n {\n xyzrgba_cloud.reset (new pcl::PointCloud<pcl::PointXYZRGBA> (WIDTH, HEIGHT));\n xyzrgba_cloud->is_dense = false;\n\n if (need_xyz_)\n copyPointCloud (*xyz_cloud, *xyzrgba_cloud);\n else\n computeXYZ (*xyzrgba_cloud);\n\n for (int i = 0; i < SIZE; i++)\n {\n const DepthSense::UV& uv = data.uvMap[i];\n int row = static_cast<int> (uv.v * COLOR_HEIGHT);\n int col = static_cast<int> (uv.u * COLOR_WIDTH);\n int pixel = row * COLOR_WIDTH + col;\n if (pixel >=0 && pixel < COLOR_WIDTH * COLOR_HEIGHT)\n memcpy (&xyzrgba_cloud->points[i].rgba, &color_data_[pixel * 3], 3);\n }\n\n point_cloud_rgba_signal_->operator () (xyzrgba_cloud);\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::onColorDataReceived (DepthSense::ColorNode node, DepthSense::ColorNode::NewSampleReceivedData data)\n{\n if (need_xyzrgba_)\n memcpy (&color_data_[0], data.colorMap, color_data_.size ());\n}\n\ntemplate <typename Point> void\npcl::io::depth_sense::DepthSenseGrabberImpl::computeXYZ (PointCloud<Point>& cloud)\n{\n static const float nan = std::numeric_limits<float>::quiet_NaN ();\n\n int i = 0;\n DepthSense::FPExtended2DPoint point (DepthSense::Point2D (0, 0), 0);\n DepthSense::FPVertex vertex;\n while (point.point.y < HEIGHT)\n {\n point.point.x = 0;\n while (point.point.x < WIDTH)\n {\n point.depth = (*depth_buffer_)[i];\n if (pcl_isnan (point.depth))\n {\n cloud.points[i].x = nan;\n cloud.points[i].y = nan;\n cloud.points[i].z = nan;\n }\n else\n {\n projection_->get3DCoordinates (&point, &vertex, 1);\n cloud.points[i].x = vertex.x;\n cloud.points[i].y = vertex.y;\n cloud.points[i].z = vertex.z;\n }\n point.point.x += 1;\n ++i;\n }\n point.point.y += 1;\n }\n}\n\n<commit_msg>Fix warnings: unused parameter ‘node’<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2014-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <boost\/lexical_cast.hpp>\n\n#include <pcl\/common\/io.h>\n#include <pcl\/io\/depth_sense_grabber.h>\n#include <pcl\/io\/depth_sense\/depth_sense_grabber_impl.h>\n#include <pcl\/io\/depth_sense\/depth_sense_device_manager.h>\n\npcl::io::depth_sense::DepthSenseGrabberImpl::DepthSenseGrabberImpl (DepthSenseGrabber* parent, const std::string& device_id)\n: p_ (parent)\n, is_running_ (false)\n, confidence_threshold_ (50)\n, temporal_filtering_type_ (DepthSenseGrabber::DepthSense_None)\n, color_data_ (COLOR_SIZE * 3)\n, depth_buffer_ (new pcl::io::SingleBuffer<float> (SIZE))\n{\n if (device_id == \"\")\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this);\n else if (device_id[0] == '#')\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this, boost::lexical_cast<int> (device_id.substr (1)) - 1);\n else\n device_id_ = DepthSenseDeviceManager::getInstance ()->captureDevice (this, device_id);\n\n point_cloud_signal_ = p_->createSignal<sig_cb_depth_sense_point_cloud> ();\n point_cloud_rgba_signal_ = p_->createSignal<sig_cb_depth_sense_point_cloud_rgba> ();\n}\n\npcl::io::depth_sense::DepthSenseGrabberImpl::~DepthSenseGrabberImpl () throw ()\n{\n stop ();\n\n DepthSenseDeviceManager::getInstance ()->releaseDevice (device_id_);\n\n p_->disconnect_all_slots<sig_cb_depth_sense_point_cloud> ();\n p_->disconnect_all_slots<sig_cb_depth_sense_point_cloud_rgba> ();\n}\n\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::start ()\n{\n need_xyz_ = p_->num_slots<sig_cb_depth_sense_point_cloud> () > 0;\n need_xyzrgba_ = p_->num_slots<sig_cb_depth_sense_point_cloud_rgba> () > 0;\n\n if (!is_running_)\n {\n DepthSenseDeviceManager::getInstance ()->reconfigureDevice (device_id_);\n DepthSenseDeviceManager::getInstance ()->startDevice (device_id_);\n frequency_.reset ();\n is_running_ = true;\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::stop ()\n{\n if (is_running_)\n {\n DepthSenseDeviceManager::getInstance ()->stopDevice (device_id_);\n is_running_ = false;\n }\n}\n\nfloat\npcl::io::depth_sense::DepthSenseGrabberImpl::getFramesPerSecond () const\n{\n boost::mutex::scoped_lock lock (fps_mutex_);\n return (frequency_.getFrequency ());\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::setConfidenceThreshold (int threshold)\n{\n confidence_threshold_ = threshold;\n DepthSenseDeviceManager::getInstance ()->reconfigureDevice (device_id_);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::enableTemporalFiltering (DepthSenseGrabber::TemporalFilteringType type, size_t window_size)\n{\n if (temporal_filtering_type_ != type ||\n (type != DepthSenseGrabber::DepthSense_None && depth_buffer_->size () != window_size))\n {\n bool was_running = is_running_;\n if (was_running)\n stop ();\n switch (type)\n {\n case DepthSenseGrabber::DepthSense_None:\n {\n depth_buffer_.reset (new pcl::io::SingleBuffer<float> (SIZE));\n break;\n }\n case DepthSenseGrabber::DepthSense_Median:\n {\n depth_buffer_.reset (new pcl::io::MedianBuffer<float> (SIZE, window_size));\n break;\n }\n case DepthSenseGrabber::DepthSense_Average:\n {\n depth_buffer_.reset (new pcl::io::AverageBuffer<float> (SIZE, window_size));\n break;\n }\n }\n temporal_filtering_type_ = type;\n if (was_running)\n start ();\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::setCameraParameters (const DepthSense::StereoCameraParameters& parameters)\n{\n projection_.reset (new DepthSense::ProjectionHelper (parameters));\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::configureDepthNode (DepthSense::DepthNode node) const\n{\n DepthSense::DepthNode::Configuration config = node.getConfiguration ();\n config.frameFormat = DepthSense::FRAME_FORMAT_QVGA;\n config.framerate = FRAMERATE;\n config.mode = DepthSense::DepthNode::CAMERA_MODE_CLOSE_MODE;\n config.saturation = false;\n node.setEnableDepthMapFloatingPoint (true);\n node.setEnableUvMap (true);\n node.setEnableConfidenceMap (true);\n node.setConfiguration (config);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::configureColorNode (DepthSense::ColorNode node) const\n{\n DepthSense::ColorNode::Configuration config = node.getConfiguration ();\n config.frameFormat = DepthSense::FRAME_FORMAT_VGA;\n config.compression = DepthSense::COMPRESSION_TYPE_MJPEG;\n config.powerLineFrequency = DepthSense::POWER_LINE_FREQUENCY_50HZ;\n config.framerate = FRAMERATE;\n node.setEnableColorMap (true);\n node.setConfiguration (config);\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::onDepthDataReceived (DepthSense::DepthNode, DepthSense::DepthNode::NewSampleReceivedData data)\n{\n fps_mutex_.lock ();\n frequency_.event ();\n fps_mutex_.unlock ();\n\n static const float nan = std::numeric_limits<float>::quiet_NaN ();\n\n std::vector<float> depth_data (SIZE);\n memcpy (depth_data.data (), &data.depthMapFloatingPoint[0], SIZE * sizeof (float));\n for (int i = 0; i < SIZE; i++)\n if (data.confidenceMap[i] < confidence_threshold_)\n depth_data[i] = nan;\n depth_buffer_->push (depth_data);\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr xyz_cloud;\n pcl::PointCloud<pcl::PointXYZRGBA>::Ptr xyzrgba_cloud;\n\n if (need_xyz_)\n {\n xyz_cloud.reset (new pcl::PointCloud<pcl::PointXYZ> (WIDTH, HEIGHT));\n xyz_cloud->is_dense = false;\n\n computeXYZ (*xyz_cloud);\n\n point_cloud_signal_->operator () (xyz_cloud);\n }\n\n if (need_xyzrgba_)\n {\n xyzrgba_cloud.reset (new pcl::PointCloud<pcl::PointXYZRGBA> (WIDTH, HEIGHT));\n xyzrgba_cloud->is_dense = false;\n\n if (need_xyz_)\n copyPointCloud (*xyz_cloud, *xyzrgba_cloud);\n else\n computeXYZ (*xyzrgba_cloud);\n\n for (int i = 0; i < SIZE; i++)\n {\n const DepthSense::UV& uv = data.uvMap[i];\n int row = static_cast<int> (uv.v * COLOR_HEIGHT);\n int col = static_cast<int> (uv.u * COLOR_WIDTH);\n int pixel = row * COLOR_WIDTH + col;\n if (pixel >=0 && pixel < COLOR_WIDTH * COLOR_HEIGHT)\n memcpy (&xyzrgba_cloud->points[i].rgba, &color_data_[pixel * 3], 3);\n }\n\n point_cloud_rgba_signal_->operator () (xyzrgba_cloud);\n }\n}\n\nvoid\npcl::io::depth_sense::DepthSenseGrabberImpl::onColorDataReceived (DepthSense::ColorNode, DepthSense::ColorNode::NewSampleReceivedData data)\n{\n if (need_xyzrgba_)\n memcpy (&color_data_[0], data.colorMap, color_data_.size ());\n}\n\ntemplate <typename Point> void\npcl::io::depth_sense::DepthSenseGrabberImpl::computeXYZ (PointCloud<Point>& cloud)\n{\n static const float nan = std::numeric_limits<float>::quiet_NaN ();\n\n int i = 0;\n DepthSense::FPExtended2DPoint point (DepthSense::Point2D (0, 0), 0);\n DepthSense::FPVertex vertex;\n while (point.point.y < HEIGHT)\n {\n point.point.x = 0;\n while (point.point.x < WIDTH)\n {\n point.depth = (*depth_buffer_)[i];\n if (pcl_isnan (point.depth))\n {\n cloud.points[i].x = nan;\n cloud.points[i].y = nan;\n cloud.points[i].z = nan;\n }\n else\n {\n projection_->get3DCoordinates (&point, &vertex, 1);\n cloud.points[i].x = vertex.x;\n cloud.points[i].y = vertex.y;\n cloud.points[i].z = vertex.z;\n }\n point.point.x += 1;\n ++i;\n }\n point.point.y += 1;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* \n** Copyright 1994 by Miron Livny, and Mike Litzkow\n** \n** Permission to use, copy, modify, and distribute this software and its\n** documentation for any purpose and without fee is hereby granted,\n** provided that the above copyright notice appear in all copies and that\n** both that copyright notice and this permission notice appear in\n** supporting documentation, and that the names of the University of\n** Wisconsin and the copyright holders not be used in advertising or\n** publicity pertaining to distribution of the software without specific,\n** written prior permission. The University of Wisconsin and the \n** copyright holders make no representations about the suitability of this\n** software for any purpose. It is provided \"as is\" without express\n** or implied warranty.\n** \n** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL\n** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES\n** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF\n** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT\n** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE\n** OR PERFORMANCE OF THIS SOFTWARE.\n** \n** Author: Mike Litzkow\n**\n*\/ \n\n#define _POSIX_SOURCE\n#include <sys\/types.h>\n#include <stdlib.h>\n\n\nvoid * operator new(size_t size)\n{\n\treturn (void *)malloc(size);\n}\n\nvoid operator delete( void *to_free )\n{\n\tif( to_free ) {\n\t\t(void)free( to_free );\n\t}\n}\n<commit_msg>Add routines __builtin_vec_new() and __builtin_vec_delete() needed for G++ version 2.6.0.<commit_after>\/* \n** Copyright 1994 by Miron Livny, and Mike Litzkow\n** \n** Permission to use, copy, modify, and distribute this software and its\n** documentation for any purpose and without fee is hereby granted,\n** provided that the above copyright notice appear in all copies and that\n** both that copyright notice and this permission notice appear in\n** supporting documentation, and that the names of the University of\n** Wisconsin and the copyright holders not be used in advertising or\n** publicity pertaining to distribution of the software without specific,\n** written prior permission. The University of Wisconsin and the \n** copyright holders make no representations about the suitability of this\n** software for any purpose. It is provided \"as is\" without express\n** or implied warranty.\n** \n** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL\n** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES\n** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF\n** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT\n** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE\n** OR PERFORMANCE OF THIS SOFTWARE.\n** \n** Author: Mike Litzkow\n**\n*\/ \n\n#define _POSIX_SOURCE\n#include <sys\/types.h>\n#include <stdlib.h>\n\n\nvoid * operator new(size_t size)\n{\n\treturn (void *)malloc(size);\n}\n\n\nvoid operator delete( void *to_free )\n{\n\tif( to_free ) {\n\t\t(void)free( to_free );\n\t}\n}\n\n#if defined( __GNUC__ )\n#\tif __GNUG__== 2 && __GNUC_MINOR__ == 6\n\t\textern \"C\" {\n\t\t\tvoid *__builtin_new( size_t );\n\t\t\tvoid __builtin_delete( void * );\n\t\t\tvoid *\n\t\t\t__builtin_vec_new (size_t sz)\n\t\t\t{\n\t\t\t\treturn __builtin_new( sz );\n\t\t\t}\n\n\t\t\tvoid\n\t\t\t__builtin_vec_delete( void *to_free )\n\t\t\t{\n\t\t\t\t__builtin_delete( to_free );\n\t\t\t}\n\t\t}\n#\tendif\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <avalanche\/peermanager.h>\n\n#include <avalanche\/delegation.h>\n#include <avalanche\/validation.h>\n#include <random.h>\n#include <validation.h> \/\/ For ChainstateActive()\n\n#include <cassert>\n\nnamespace avalanche {\n\nbool PeerManager::addNode(NodeId nodeid, const ProofId &proofid) {\n auto &pview = peers.get<proof_index>();\n auto it = pview.find(proofid);\n if (it == pview.end()) {\n return false;\n }\n\n return addOrUpdateNode(peers.project<0>(it), nodeid);\n}\n\nbool PeerManager::addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid) {\n assert(it != peers.end());\n\n const PeerId peerid = it->peerid;\n\n auto nit = nodes.find(nodeid);\n if (nit == nodes.end()) {\n if (!nodes.emplace(nodeid, peerid).second) {\n return false;\n }\n } else {\n const PeerId oldpeerid = nit->peerid;\n if (!nodes.modify(nit, [&](Node &n) { n.peerid = peerid; })) {\n return false;\n }\n\n \/\/ We actually have this node already, we need to update it.\n bool success = removeNodeFromPeer(peers.find(oldpeerid));\n assert(success);\n }\n\n bool success = addNodeToPeer(it);\n assert(success);\n\n return true;\n}\n\nbool PeerManager::addNodeToPeer(const PeerSet::iterator &it) {\n assert(it != peers.end());\n return peers.modify(it, [&](Peer &p) {\n if (p.node_count++ > 0) {\n \/\/ We are done.\n return;\n }\n\n \/\/ We need to allocate this peer.\n p.index = uint32_t(slots.size());\n const uint32_t score = p.getScore();\n const uint64_t start = slotCount;\n slots.emplace_back(start, score, it->peerid);\n slotCount = start + score;\n });\n}\n\nbool PeerManager::removeNode(NodeId nodeid) {\n auto it = nodes.find(nodeid);\n if (it == nodes.end()) {\n return false;\n }\n\n const PeerId peerid = it->peerid;\n nodes.erase(it);\n\n \/\/ Keep the track of the reference count.\n bool success = removeNodeFromPeer(peers.find(peerid));\n assert(success);\n\n return true;\n}\n\nbool PeerManager::removeNodeFromPeer(const PeerSet::iterator &it,\n uint32_t count) {\n assert(it != peers.end());\n assert(count <= it->node_count);\n if (count == 0) {\n \/\/ This is a NOOP.\n return false;\n }\n\n const uint32_t new_count = it->node_count - count;\n if (!peers.modify(it, [&](Peer &p) { p.node_count = new_count; })) {\n return false;\n }\n\n if (new_count > 0) {\n \/\/ We are done.\n return true;\n }\n\n \/\/ There are no more node left, we need to cleanup.\n const size_t i = it->index;\n assert(i < slots.size());\n if (i + 1 == slots.size()) {\n slots.pop_back();\n slotCount = slots.empty() ? 0 : slots.back().getStop();\n } else {\n fragmentation += slots[i].getScore();\n slots[i] = slots[i].withPeerId(NO_PEER);\n }\n\n return true;\n}\n\nbool PeerManager::updateNextRequestTime(NodeId nodeid, TimePoint timeout) {\n auto it = nodes.find(nodeid);\n if (it == nodes.end()) {\n return false;\n }\n\n return nodes.modify(it, [&](Node &n) { n.nextRequestTime = timeout; });\n}\n\nbool PeerManager::registerProof(const std::shared_ptr<Proof> &proof) {\n return !getProof(proof->getId()) && getPeerId(proof) != NO_PEER;\n}\n\nNodeId PeerManager::selectNode() {\n for (int retry = 0; retry < SELECT_NODE_MAX_RETRY; retry++) {\n const PeerId p = selectPeer();\n\n \/\/ If we cannot find a peer, it may be due to the fact that it is\n \/\/ unlikely due to high fragmentation, so compact and retry.\n if (p == NO_PEER) {\n compact();\n continue;\n }\n\n \/\/ See if that peer has an available node.\n auto &nview = nodes.get<next_request_time>();\n auto it = nview.lower_bound(boost::make_tuple(p, TimePoint()));\n if (it != nview.end() && it->peerid == p &&\n it->nextRequestTime <= std::chrono::steady_clock::now()) {\n return it->nodeid;\n }\n }\n\n return NO_NODE;\n}\n\nstatic bool isOrphanState(const ProofValidationState &state) {\n return state.GetResult() == ProofValidationResult::MISSING_UTXO ||\n state.GetResult() == ProofValidationResult::HEIGHT_MISMATCH;\n}\n\nvoid PeerManager::updatedBlockTip() {\n std::vector<PeerId> invalidPeers;\n std::vector<std::shared_ptr<Proof>> newOrphans;\n\n {\n LOCK(cs_main);\n\n const CCoinsViewCache &coins = ::ChainstateActive().CoinsTip();\n for (const auto &p : peers) {\n ProofValidationState state;\n if (!p.proof->verify(state, coins)) {\n if (isOrphanState(state)) {\n newOrphans.push_back(p.proof);\n }\n invalidPeers.push_back(p.peerid);\n }\n }\n }\n\n orphanProofs.rescan(*this);\n\n for (auto &p : newOrphans) {\n orphanProofs.addProof(p);\n }\n\n for (const auto &pid : invalidPeers) {\n removePeer(pid);\n }\n}\n\nPeerId PeerManager::getPeerId(const std::shared_ptr<Proof> &proof) {\n auto it = fetchOrCreatePeer(proof);\n return it == peers.end() ? NO_PEER : it->peerid;\n}\n\nstd::shared_ptr<Proof> PeerManager::getProof(const ProofId &proofid) const {\n std::shared_ptr<Proof> proof = nullptr;\n\n forPeer(proofid, [&](const Peer &p) {\n proof = p.proof;\n return true;\n });\n\n return proof;\n}\n\nPeerManager::PeerSet::iterator\nPeerManager::fetchOrCreatePeer(const std::shared_ptr<Proof> &proof) {\n {\n \/\/ Check if we already know of that peer.\n auto &pview = peers.get<proof_index>();\n auto it = pview.find(proof->getId());\n if (it != pview.end()) {\n return peers.project<0>(it);\n }\n }\n\n \/\/ Check the proof's validity.\n ProofValidationState state;\n bool valid = [&](ProofValidationState &state) {\n LOCK(cs_main);\n const CCoinsViewCache &coins = ::ChainstateActive().CoinsTip();\n return proof->verify(state, coins);\n }(state);\n\n if (!valid) {\n if (isOrphanState(state)) {\n orphanProofs.addProof(proof);\n }\n\n \/\/ Reject invalid proof.\n return peers.end();\n }\n\n orphanProofs.removeProof(proof->getId());\n\n \/\/ New peer means new peerid!\n const PeerId peerid = nextPeerId++;\n\n \/\/ Attach UTXOs to this proof.\n std::unordered_set<PeerId> conflicting_peerids;\n for (const auto &s : proof->getStakes()) {\n auto p = utxos.emplace(s.getStake().getUTXO(), peerid);\n if (!p.second) {\n \/\/ We have a collision with an existing proof.\n conflicting_peerids.insert(p.first->second);\n }\n }\n\n \/\/ For now, if there is a conflict, just cleanup the mess.\n if (conflicting_peerids.size() > 0) {\n for (const auto &s : proof->getStakes()) {\n auto it = utxos.find(s.getStake().getUTXO());\n assert(it != utxos.end());\n\n \/\/ We need to delete that one.\n if (it->second == peerid) {\n utxos.erase(it);\n }\n }\n\n return peers.end();\n }\n\n \/\/ We have no peer for this proof, time to create it.\n auto inserted = peers.emplace(peerid, proof);\n assert(inserted.second);\n\n return inserted.first;\n}\n\nbool PeerManager::removePeer(const PeerId peerid) {\n auto it = peers.find(peerid);\n if (it == peers.end()) {\n return false;\n }\n\n \/\/ Remove all nodes from this peer.\n removeNodeFromPeer(it, it->node_count);\n\n \/\/ Remove nodes associated with this peer, unless their timeout is still\n \/\/ active. This ensure that we don't overquery them in case they are\n \/\/ subsequently added to another peer.\n auto &nview = nodes.get<next_request_time>();\n nview.erase(nview.lower_bound(boost::make_tuple(peerid, TimePoint())),\n nview.upper_bound(boost::make_tuple(\n peerid, std::chrono::steady_clock::now())));\n\n \/\/ Release UTXOs attached to this proof.\n for (const auto &s : it->proof->getStakes()) {\n bool deleted = utxos.erase(s.getStake().getUTXO()) > 0;\n assert(deleted);\n }\n\n m_unbroadcast_proofids.erase(it->proof->getId());\n\n peers.erase(it);\n return true;\n}\n\nPeerId PeerManager::selectPeer() const {\n if (slots.empty() || slotCount == 0) {\n return NO_PEER;\n }\n\n const uint64_t max = slotCount;\n for (int retry = 0; retry < SELECT_PEER_MAX_RETRY; retry++) {\n size_t i = selectPeerImpl(slots, GetRand(max), max);\n if (i != NO_PEER) {\n return i;\n }\n }\n\n return NO_PEER;\n}\n\nuint64_t PeerManager::compact() {\n \/\/ There is nothing to compact.\n if (fragmentation == 0) {\n return 0;\n }\n\n std::vector<Slot> newslots;\n newslots.reserve(peers.size());\n\n uint64_t prevStop = 0;\n uint32_t i = 0;\n for (auto it = peers.begin(); it != peers.end(); it++) {\n if (it->node_count == 0) {\n continue;\n }\n\n newslots.emplace_back(prevStop, it->getScore(), it->peerid);\n prevStop = slots[i].getStop();\n if (!peers.modify(it, [&](Peer &p) { p.index = i++; })) {\n return 0;\n }\n }\n\n slots = std::move(newslots);\n\n const uint64_t saved = slotCount - prevStop;\n slotCount = prevStop;\n fragmentation = 0;\n\n return saved;\n}\n\nbool PeerManager::verify() const {\n uint64_t prevStop = 0;\n for (size_t i = 0; i < slots.size(); i++) {\n const Slot &s = slots[i];\n\n \/\/ Slots must be in correct order.\n if (s.getStart() < prevStop) {\n return false;\n }\n\n prevStop = s.getStop();\n\n \/\/ If this is a dead slot, then nothing more needs to be checked.\n if (s.getPeerId() == NO_PEER) {\n continue;\n }\n\n \/\/ We have a live slot, verify index.\n auto it = peers.find(s.getPeerId());\n if (it == peers.end() || it->index != i) {\n return false;\n }\n }\n\n for (const auto &p : peers) {\n \/\/ Count node attached to this peer.\n const auto count_nodes = [&]() {\n size_t count = 0;\n auto &nview = nodes.get<next_request_time>();\n auto begin =\n nview.lower_bound(boost::make_tuple(p.peerid, TimePoint()));\n auto end =\n nview.upper_bound(boost::make_tuple(p.peerid + 1, TimePoint()));\n\n for (auto it = begin; it != end; ++it) {\n count++;\n }\n\n return count;\n };\n\n if (p.node_count != count_nodes()) {\n return false;\n }\n\n \/\/ If there are no nodes attached to this peer, then we are done.\n if (p.node_count == 0) {\n continue;\n }\n\n \/\/ The index must point to a slot refering to this peer.\n if (p.index >= slots.size() || slots[p.index].getPeerId() != p.peerid) {\n return false;\n }\n\n \/\/ If the score do not match, same thing.\n if (slots[p.index].getScore() != p.getScore()) {\n return false;\n }\n }\n\n return true;\n}\n\nPeerId selectPeerImpl(const std::vector<Slot> &slots, const uint64_t slot,\n const uint64_t max) {\n assert(slot <= max);\n\n size_t begin = 0, end = slots.size();\n uint64_t bottom = 0, top = max;\n\n \/\/ Try to find the slot using dichotomic search.\n while ((end - begin) > 8) {\n \/\/ The slot we picked in not allocated.\n if (slot < bottom || slot >= top) {\n return NO_PEER;\n }\n\n \/\/ Guesstimate the position of the slot.\n size_t i = begin + ((slot - bottom) * (end - begin) \/ (top - bottom));\n assert(begin <= i && i < end);\n\n \/\/ We have a match.\n if (slots[i].contains(slot)) {\n return slots[i].getPeerId();\n }\n\n \/\/ We undershooted.\n if (slots[i].precedes(slot)) {\n begin = i + 1;\n if (begin >= end) {\n return NO_PEER;\n }\n\n bottom = slots[begin].getStart();\n continue;\n }\n\n \/\/ We overshooted.\n if (slots[i].follows(slot)) {\n end = i;\n top = slots[end].getStart();\n continue;\n }\n\n \/\/ We have an unalocated slot.\n return NO_PEER;\n }\n\n \/\/ Enough of that nonsense, let fallback to linear search.\n for (size_t i = begin; i < end; i++) {\n \/\/ We have a match.\n if (slots[i].contains(slot)) {\n return slots[i].getPeerId();\n }\n }\n\n \/\/ We failed to find a slot, retry.\n return NO_PEER;\n}\n\nbool PeerManager::isOrphan(const ProofId &id) const {\n return orphanProofs.getProof(id) != nullptr;\n}\n\nstd::shared_ptr<Proof> PeerManager::getOrphan(const ProofId &id) const {\n return orphanProofs.getProof(id);\n}\n\nvoid PeerManager::addUnbroadcastProof(const ProofId &proofid) {\n \/\/ The proof should be known\n if (getProof(proofid)) {\n m_unbroadcast_proofids.insert(proofid);\n }\n}\n\nvoid PeerManager::removeUnbroadcastProof(const ProofId &proofid) {\n m_unbroadcast_proofids.erase(proofid);\n}\n\n} \/\/ namespace avalanche\n<commit_msg>[avalanche] Minor simplification in the fetchOrCreatePeer method<commit_after>\/\/ Copyright (c) 2020 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <avalanche\/peermanager.h>\n\n#include <avalanche\/delegation.h>\n#include <avalanche\/validation.h>\n#include <random.h>\n#include <validation.h> \/\/ For ChainstateActive()\n\n#include <cassert>\n\nnamespace avalanche {\n\nbool PeerManager::addNode(NodeId nodeid, const ProofId &proofid) {\n auto &pview = peers.get<proof_index>();\n auto it = pview.find(proofid);\n if (it == pview.end()) {\n return false;\n }\n\n return addOrUpdateNode(peers.project<0>(it), nodeid);\n}\n\nbool PeerManager::addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid) {\n assert(it != peers.end());\n\n const PeerId peerid = it->peerid;\n\n auto nit = nodes.find(nodeid);\n if (nit == nodes.end()) {\n if (!nodes.emplace(nodeid, peerid).second) {\n return false;\n }\n } else {\n const PeerId oldpeerid = nit->peerid;\n if (!nodes.modify(nit, [&](Node &n) { n.peerid = peerid; })) {\n return false;\n }\n\n \/\/ We actually have this node already, we need to update it.\n bool success = removeNodeFromPeer(peers.find(oldpeerid));\n assert(success);\n }\n\n bool success = addNodeToPeer(it);\n assert(success);\n\n return true;\n}\n\nbool PeerManager::addNodeToPeer(const PeerSet::iterator &it) {\n assert(it != peers.end());\n return peers.modify(it, [&](Peer &p) {\n if (p.node_count++ > 0) {\n \/\/ We are done.\n return;\n }\n\n \/\/ We need to allocate this peer.\n p.index = uint32_t(slots.size());\n const uint32_t score = p.getScore();\n const uint64_t start = slotCount;\n slots.emplace_back(start, score, it->peerid);\n slotCount = start + score;\n });\n}\n\nbool PeerManager::removeNode(NodeId nodeid) {\n auto it = nodes.find(nodeid);\n if (it == nodes.end()) {\n return false;\n }\n\n const PeerId peerid = it->peerid;\n nodes.erase(it);\n\n \/\/ Keep the track of the reference count.\n bool success = removeNodeFromPeer(peers.find(peerid));\n assert(success);\n\n return true;\n}\n\nbool PeerManager::removeNodeFromPeer(const PeerSet::iterator &it,\n uint32_t count) {\n assert(it != peers.end());\n assert(count <= it->node_count);\n if (count == 0) {\n \/\/ This is a NOOP.\n return false;\n }\n\n const uint32_t new_count = it->node_count - count;\n if (!peers.modify(it, [&](Peer &p) { p.node_count = new_count; })) {\n return false;\n }\n\n if (new_count > 0) {\n \/\/ We are done.\n return true;\n }\n\n \/\/ There are no more node left, we need to cleanup.\n const size_t i = it->index;\n assert(i < slots.size());\n if (i + 1 == slots.size()) {\n slots.pop_back();\n slotCount = slots.empty() ? 0 : slots.back().getStop();\n } else {\n fragmentation += slots[i].getScore();\n slots[i] = slots[i].withPeerId(NO_PEER);\n }\n\n return true;\n}\n\nbool PeerManager::updateNextRequestTime(NodeId nodeid, TimePoint timeout) {\n auto it = nodes.find(nodeid);\n if (it == nodes.end()) {\n return false;\n }\n\n return nodes.modify(it, [&](Node &n) { n.nextRequestTime = timeout; });\n}\n\nbool PeerManager::registerProof(const std::shared_ptr<Proof> &proof) {\n return !getProof(proof->getId()) && getPeerId(proof) != NO_PEER;\n}\n\nNodeId PeerManager::selectNode() {\n for (int retry = 0; retry < SELECT_NODE_MAX_RETRY; retry++) {\n const PeerId p = selectPeer();\n\n \/\/ If we cannot find a peer, it may be due to the fact that it is\n \/\/ unlikely due to high fragmentation, so compact and retry.\n if (p == NO_PEER) {\n compact();\n continue;\n }\n\n \/\/ See if that peer has an available node.\n auto &nview = nodes.get<next_request_time>();\n auto it = nview.lower_bound(boost::make_tuple(p, TimePoint()));\n if (it != nview.end() && it->peerid == p &&\n it->nextRequestTime <= std::chrono::steady_clock::now()) {\n return it->nodeid;\n }\n }\n\n return NO_NODE;\n}\n\nstatic bool isOrphanState(const ProofValidationState &state) {\n return state.GetResult() == ProofValidationResult::MISSING_UTXO ||\n state.GetResult() == ProofValidationResult::HEIGHT_MISMATCH;\n}\n\nvoid PeerManager::updatedBlockTip() {\n std::vector<PeerId> invalidPeers;\n std::vector<std::shared_ptr<Proof>> newOrphans;\n\n {\n LOCK(cs_main);\n\n const CCoinsViewCache &coins = ::ChainstateActive().CoinsTip();\n for (const auto &p : peers) {\n ProofValidationState state;\n if (!p.proof->verify(state, coins)) {\n if (isOrphanState(state)) {\n newOrphans.push_back(p.proof);\n }\n invalidPeers.push_back(p.peerid);\n }\n }\n }\n\n orphanProofs.rescan(*this);\n\n for (auto &p : newOrphans) {\n orphanProofs.addProof(p);\n }\n\n for (const auto &pid : invalidPeers) {\n removePeer(pid);\n }\n}\n\nPeerId PeerManager::getPeerId(const std::shared_ptr<Proof> &proof) {\n auto it = fetchOrCreatePeer(proof);\n return it == peers.end() ? NO_PEER : it->peerid;\n}\n\nstd::shared_ptr<Proof> PeerManager::getProof(const ProofId &proofid) const {\n std::shared_ptr<Proof> proof = nullptr;\n\n forPeer(proofid, [&](const Peer &p) {\n proof = p.proof;\n return true;\n });\n\n return proof;\n}\n\nPeerManager::PeerSet::iterator\nPeerManager::fetchOrCreatePeer(const std::shared_ptr<Proof> &proof) {\n assert(proof);\n const ProofId &proofid = proof->getId();\n {\n \/\/ Check if we already know of that peer.\n auto &pview = peers.get<proof_index>();\n auto it = pview.find(proofid);\n if (it != pview.end()) {\n return peers.project<0>(it);\n }\n }\n\n \/\/ Check the proof's validity.\n ProofValidationState state;\n bool valid = [&](ProofValidationState &state) {\n LOCK(cs_main);\n const CCoinsViewCache &coins = ::ChainstateActive().CoinsTip();\n return proof->verify(state, coins);\n }(state);\n\n if (!valid) {\n if (isOrphanState(state)) {\n orphanProofs.addProof(proof);\n }\n\n \/\/ Reject invalid proof.\n return peers.end();\n }\n\n orphanProofs.removeProof(proofid);\n\n \/\/ New peer means new peerid!\n const PeerId peerid = nextPeerId++;\n\n \/\/ Attach UTXOs to this proof.\n std::unordered_set<PeerId> conflicting_peerids;\n for (const auto &s : proof->getStakes()) {\n auto p = utxos.emplace(s.getStake().getUTXO(), peerid);\n if (!p.second) {\n \/\/ We have a collision with an existing proof.\n conflicting_peerids.insert(p.first->second);\n }\n }\n\n \/\/ For now, if there is a conflict, just cleanup the mess.\n if (conflicting_peerids.size() > 0) {\n for (const auto &s : proof->getStakes()) {\n auto it = utxos.find(s.getStake().getUTXO());\n assert(it != utxos.end());\n\n \/\/ We need to delete that one.\n if (it->second == peerid) {\n utxos.erase(it);\n }\n }\n\n return peers.end();\n }\n\n \/\/ We have no peer for this proof, time to create it.\n auto inserted = peers.emplace(peerid, proof);\n assert(inserted.second);\n\n return inserted.first;\n}\n\nbool PeerManager::removePeer(const PeerId peerid) {\n auto it = peers.find(peerid);\n if (it == peers.end()) {\n return false;\n }\n\n \/\/ Remove all nodes from this peer.\n removeNodeFromPeer(it, it->node_count);\n\n \/\/ Remove nodes associated with this peer, unless their timeout is still\n \/\/ active. This ensure that we don't overquery them in case they are\n \/\/ subsequently added to another peer.\n auto &nview = nodes.get<next_request_time>();\n nview.erase(nview.lower_bound(boost::make_tuple(peerid, TimePoint())),\n nview.upper_bound(boost::make_tuple(\n peerid, std::chrono::steady_clock::now())));\n\n \/\/ Release UTXOs attached to this proof.\n for (const auto &s : it->proof->getStakes()) {\n bool deleted = utxos.erase(s.getStake().getUTXO()) > 0;\n assert(deleted);\n }\n\n m_unbroadcast_proofids.erase(it->proof->getId());\n\n peers.erase(it);\n return true;\n}\n\nPeerId PeerManager::selectPeer() const {\n if (slots.empty() || slotCount == 0) {\n return NO_PEER;\n }\n\n const uint64_t max = slotCount;\n for (int retry = 0; retry < SELECT_PEER_MAX_RETRY; retry++) {\n size_t i = selectPeerImpl(slots, GetRand(max), max);\n if (i != NO_PEER) {\n return i;\n }\n }\n\n return NO_PEER;\n}\n\nuint64_t PeerManager::compact() {\n \/\/ There is nothing to compact.\n if (fragmentation == 0) {\n return 0;\n }\n\n std::vector<Slot> newslots;\n newslots.reserve(peers.size());\n\n uint64_t prevStop = 0;\n uint32_t i = 0;\n for (auto it = peers.begin(); it != peers.end(); it++) {\n if (it->node_count == 0) {\n continue;\n }\n\n newslots.emplace_back(prevStop, it->getScore(), it->peerid);\n prevStop = slots[i].getStop();\n if (!peers.modify(it, [&](Peer &p) { p.index = i++; })) {\n return 0;\n }\n }\n\n slots = std::move(newslots);\n\n const uint64_t saved = slotCount - prevStop;\n slotCount = prevStop;\n fragmentation = 0;\n\n return saved;\n}\n\nbool PeerManager::verify() const {\n uint64_t prevStop = 0;\n for (size_t i = 0; i < slots.size(); i++) {\n const Slot &s = slots[i];\n\n \/\/ Slots must be in correct order.\n if (s.getStart() < prevStop) {\n return false;\n }\n\n prevStop = s.getStop();\n\n \/\/ If this is a dead slot, then nothing more needs to be checked.\n if (s.getPeerId() == NO_PEER) {\n continue;\n }\n\n \/\/ We have a live slot, verify index.\n auto it = peers.find(s.getPeerId());\n if (it == peers.end() || it->index != i) {\n return false;\n }\n }\n\n for (const auto &p : peers) {\n \/\/ Count node attached to this peer.\n const auto count_nodes = [&]() {\n size_t count = 0;\n auto &nview = nodes.get<next_request_time>();\n auto begin =\n nview.lower_bound(boost::make_tuple(p.peerid, TimePoint()));\n auto end =\n nview.upper_bound(boost::make_tuple(p.peerid + 1, TimePoint()));\n\n for (auto it = begin; it != end; ++it) {\n count++;\n }\n\n return count;\n };\n\n if (p.node_count != count_nodes()) {\n return false;\n }\n\n \/\/ If there are no nodes attached to this peer, then we are done.\n if (p.node_count == 0) {\n continue;\n }\n\n \/\/ The index must point to a slot refering to this peer.\n if (p.index >= slots.size() || slots[p.index].getPeerId() != p.peerid) {\n return false;\n }\n\n \/\/ If the score do not match, same thing.\n if (slots[p.index].getScore() != p.getScore()) {\n return false;\n }\n }\n\n return true;\n}\n\nPeerId selectPeerImpl(const std::vector<Slot> &slots, const uint64_t slot,\n const uint64_t max) {\n assert(slot <= max);\n\n size_t begin = 0, end = slots.size();\n uint64_t bottom = 0, top = max;\n\n \/\/ Try to find the slot using dichotomic search.\n while ((end - begin) > 8) {\n \/\/ The slot we picked in not allocated.\n if (slot < bottom || slot >= top) {\n return NO_PEER;\n }\n\n \/\/ Guesstimate the position of the slot.\n size_t i = begin + ((slot - bottom) * (end - begin) \/ (top - bottom));\n assert(begin <= i && i < end);\n\n \/\/ We have a match.\n if (slots[i].contains(slot)) {\n return slots[i].getPeerId();\n }\n\n \/\/ We undershooted.\n if (slots[i].precedes(slot)) {\n begin = i + 1;\n if (begin >= end) {\n return NO_PEER;\n }\n\n bottom = slots[begin].getStart();\n continue;\n }\n\n \/\/ We overshooted.\n if (slots[i].follows(slot)) {\n end = i;\n top = slots[end].getStart();\n continue;\n }\n\n \/\/ We have an unalocated slot.\n return NO_PEER;\n }\n\n \/\/ Enough of that nonsense, let fallback to linear search.\n for (size_t i = begin; i < end; i++) {\n \/\/ We have a match.\n if (slots[i].contains(slot)) {\n return slots[i].getPeerId();\n }\n }\n\n \/\/ We failed to find a slot, retry.\n return NO_PEER;\n}\n\nbool PeerManager::isOrphan(const ProofId &id) const {\n return orphanProofs.getProof(id) != nullptr;\n}\n\nstd::shared_ptr<Proof> PeerManager::getOrphan(const ProofId &id) const {\n return orphanProofs.getProof(id);\n}\n\nvoid PeerManager::addUnbroadcastProof(const ProofId &proofid) {\n \/\/ The proof should be known\n if (getProof(proofid)) {\n m_unbroadcast_proofids.insert(proofid);\n }\n}\n\nvoid PeerManager::removeUnbroadcastProof(const ProofId &proofid) {\n m_unbroadcast_proofids.erase(proofid);\n}\n\n} \/\/ namespace avalanche\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_version.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"command_strings.h\"\n#include \"daemon.h\"\n#include \"safe_sock.h\"\n#include \"condor_distribution.h\"\n#include \"daemon_list.h\"\n#include \"dc_collector.h\"\n#include \"my_hostname.h\"\n\nvoid\nusage( const char *cmd , const char * opt)\n{\n\tfprintf(stderr,\"Usage: %s [options] <update-command> [<classad-filename>]\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\" -help Display options\\n\");\n\tfprintf(stderr,\" -version Display Condor version\\n\");\n\tfprintf(stderr,\" -pool <hostname> Use this central manager\\n\");\n\tfprintf(stderr,\" -debug Show extra debugging info\\n\");\n\tfprintf(stderr,\" -tcp Ship classad via TCP (default is UDP)\\n\");\n\tfprintf(stderr,\" -multiple Publish multiple ads, separated by blank lines\\n\");\n\n\tif (opt && ( !strcmp(opt,\"all\") || !strcmp(opt,\"cmd\"))) {\n\t\tfprintf(stderr,\"\\nAnd <update-command> is one of:\\n\");\n\t\tstatic const char * const aPre[] = {\"UPDATE_\", \"MERGE_\", \"INVALIDATE_\"};\n\t\tfor (int jj = 0; jj < (int)COUNTOF(aPre); ++jj) {\n\t\t\tfor (int id = UPDATE_STARTD_AD; id < UPDATE_STARTD_AD + 100; ++id) {\n\t\t\t\tconst char * cmdname = getCollectorCommandString(id);\n\t\t\t\tif (cmdname && starts_with(cmdname, aPre[jj])) {\n\t\t\t\t\tfprintf(stderr,\" %s\\n\",cmdname);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfprintf(stderr, \"\\nIf <classad-filename> does not exist or is -, classads will be read from standard input\\n\");\n\tfprintf(stderr,\"Example: %s -debug UPDATE_STORAGE_AD adfile\\n\\n\",cmd);\n}\n\n\/\/ this class is used to help parse one or more ClassAd's from a FILE*\nclass ToolClassAdFileParseHelper : public ClassAdFileParseHelper\n{\n public:\n\t\/\/ Some compilers whine when you have virtual methods but not an\n\t\/\/ explicit virtual destructor\n\tvirtual ~ToolClassAdFileParseHelper() {}\n\tToolClassAdFileParseHelper(bool multi, FILE* errout) : multiple(multi), out(errout) {};\n\n\t\/\/ return 0 to skip (is_comment), 1 to parse line, 2 for end-of-classad, -1 for abort\n\tvirtual int PreParse(std::string & line, ClassAd & \/*ad*\/, FILE* \/*file*\/) {\n\t\t\/\/ if this line matches the ad delimitor, tell the parser to stop parsing\n\t\tif (multiple && (line.empty() || (line[0] == '\\n')))\n\t\t\treturn 2; \/\/end-of-classad\n\n\t\t\/\/ check for blank lines or lines whose first character is #\n\t\t\/\/ tell the parse to skip those lines, otherwise tell the parser to\n\t\t\/\/ parse the line.\n\t\tfor (size_t ix = 0; ix < line.size(); ++ix) {\n\t\t\tif (line[ix] == '#' || line[ix] == '\\n')\n\t\t\t\treturn 0; \/\/ skip this line, but don't stop parsing.\n\t\t\tif (line[ix] != ' ' && line[ix] != '\\t')\n\t\t\t\treturn 1; \/\/ parse this line\n\t\t}\n\t\treturn 1; \/\/ parse this line.\n\t}\n\n\t\/\/ return 0 to skip and continue, 1 to re-parse line, 2 to quit parsing with success, -1 to abort parsing.\n\tvirtual int OnParseError(std::string & line, ClassAd & \/*ad*\/, FILE* file) {\n\t\t\/\/ print out where we barfed to the log file\n\t\tdprintf(D_ALWAYS,\"failed to create classad; bad expr = '%s'\\n\", line.c_str());\n\n\t\tif ( ! multiple) return -1; \/\/ abort\n\n\t\t\/\/ skip the remainder of the ad by reading until we see eof or a blank line.\n\t\tline = \"\";\n\t\twhile ( ! line.empty() && line[0] != '\\n') {\n\t\t\tif (feof(file))\n\t\t\t\tbreak;\n\t\t\tif ( ! readLine(line, file, false))\n\t\t\t\tbreak;\n\t\t}\n\t\treturn -1; \/\/ abort\n\t}\n\n private:\n\tbool multiple;\n\tFILE * out;\n\tstd::string delim;\n};\n\n\nvoid\nversion()\n{\n\tprintf( \"%s\\n%s\\n\", CondorVersion(), CondorPlatform() );\n}\n\nint main( int argc, char *argv[] )\n{\n\tconst char *filename=0;\n\tchar *pool=0;\n\tint command=-1;\n\tint i;\n\tbool with_ack = false;\n\tbool allow_multiple = false;\n\tbool many_connections = false;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n\tbool use_tcp = param_boolean( \"UPDATE_COLLECTOR_WITH_TCP\", true );\n\n\tfor( i=1; i<argc; i++ ) {\n\t\tif(!strcmp(argv[i],\"-help\") || !strcmp(argv[i],\"--help\")) {\n\t\t\tusage(argv[0], argv[i+1] ? argv[i+1] : \"cmd\");\n\t\t\texit(0);\n\t\t} else if(!strcmp(argv[i],\"-pool\")) {\n\t\t\ti++;\n\t\t\tif(!argv[i]) {\n\t\t\t\tfprintf(stderr,\"-pool requires an argument.\\n\\n\");\n\t\t\t\tusage(argv[0], NULL);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tpool = argv[i];\n\t\t} else if(!strncmp(argv[i],\"-tcp\",strlen(argv[i]))) {\n\t\t\tuse_tcp = true;\n\t\t} else if(!strncmp(argv[i],\"-udp\",strlen(argv[i]))) {\n\t\t\tuse_tcp = false;\n\t\t} else if(!strncmp(argv[i],\"-multiple\",strlen(argv[i]))) {\n\t\t\t\t\/\/ We don't set allow_multiple=true by default, because\n\t\t\t\t\/\/ existing users (e.g. glideinWMS) have stray blank lines\n\t\t\t\t\/\/ in the input file.\n\t\t\tallow_multiple = true;\n\t\t} else if(!strcmp(argv[i],\"-version\")) {\n\t\t\tversion();\n\t\t\texit(0);\n\t\t} else if(!strcmp(argv[i],\"-debug\")) {\n\t\t\t\t\/\/ dprintf to console\n\t\t\tdprintf_set_tool_debug(\"TOOL\", 0);\n\t\t} else if(argv[i][0]!='-' || !strcmp(argv[i],\"-\")) {\n\t\t\tif(command==-1) {\n\t\t\t\tcommand = getCollectorCommandNum(argv[i]);\n\t\t\t\tif(command==-1) {\n\t\t\t\t\tfprintf(stderr,\"Unknown command name %s\\n\\n\",argv[i]);\n\t\t\t\t\tusage(argv[0], \"all\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t} else if(!filename) {\n\t\t\t\tfilename = argv[i];\n\t\t\t} else {\n\t\t\t\tfprintf(stderr,\"Extra argument: %s\\n\\n\",argv[i]);\n\t\t\t\tusage(argv[0], NULL);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t} else if(!strncmp(argv[i],\"-many-connections\", strlen(argv[i]))) { \n\t\t\tmany_connections = true;\n\t\t} else {\n\t\t\tfprintf(stderr,\"Unknown argument: %s\\n\\n\",argv[i]);\n\t\t\tusage(argv[0], NULL);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tFILE *file;\n\tClassAdList ads;\n\tDaemon *collector;\n\tSock *sock;\n\n\tswitch( command ) {\n\tcase UPDATE_STARTD_AD_WITH_ACK:\n\t\twith_ack = true;\n\t\tbreak;\n\t}\n\n\tif( with_ack ) {\n\t\tuse_tcp = true;\n\t}\n\n\tif(!filename || !strcmp(filename,\"-\")) {\n\t\tfile = stdin;\n\t\tfilename = \"(stdin)\";\n\t} else {\n\t\tfile = safe_fopen_wrapper_follow(filename,\"r\");\n\t}\n\tif(!file) {\n\t\tfprintf(stderr,\"couldn't open %s: %s\\n\",filename,strerror(errno));\n\t\treturn 1;\n\t}\n\n\t\/\/ create class that we can use to influence the behavior of Classad::InsertFromFile\n\tToolClassAdFileParseHelper parse_helper(allow_multiple, stderr);\n\n\tfor (;;) {\n\t\tClassAd *ad = new ClassAd();\n\t\tint error;\n\t\tbool eof;\n\t\tint cAttrs = ad->InsertFromFile(file, eof, error, &parse_helper);\n\t\tif (error < 0) {\n\t\t\tfprintf(stderr,\"couldn't parse ClassAd in %s\\n\", filename);\n\t\t\tdelete ad;\n\t\t\treturn 1;\n\t\t}\n\t\tif (cAttrs > 0) {\n\t\t\tads.Insert(ad);\n\t\t} else {\n\t\t\tdelete ad;\n\t\t}\n\t\tif (eof) {\n\t\t\tbreak;\n\t\t}\n\t\tif( !allow_multiple && ads.Length() > 0 ) {\n\t\t\tfprintf(stderr,\"ERROR: multiple ads in %s\\n\", filename);\n\t\t\tdelete ad;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif(ads.Length() == 0) {\n\t\tfprintf(stderr,\"%s is empty\\n\",filename);\n\t\treturn 1;\n\t}\n\n\tCollectorList * collectors;\n\tif ( pool ) {\n\t\tcollector = new Daemon( DT_COLLECTOR, pool, 0 );\n\t\tcollectors = new CollectorList();\n\t\tcollectors->append (collector);\n\t} else {\n\t\tcollectors = CollectorList::create();\n\t}\n\n\tbool had_error = false;\n\n\tcollectors->rewind();\n\twhile (collectors->next(collector)) {\n\n\t\tdprintf(D_FULLDEBUG,\"locating collector %s...\\n\", collector->name());\n\n\t\tif(!collector->locate(Daemon::LOCATE_FOR_LOOKUP)) {\n\t\t\tfprintf(stderr,\"couldn't locate collector: %s\\n\",collector->error());\n\t\t\thad_error = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tdprintf(D_FULLDEBUG,\"collector is %s located at %s\\n\",\n\t\t\t\tcollector->hostname(),collector->addr());\n\n\t\tsock = NULL;\n\n\t\tClassAd *ad;\n\t\tint success_count = 0;\n\t\tint failure_count = 0;\n\t\tads.Rewind();\n\t\twhile( (ad=ads.Next()) ) {\n\n\t\t\t\t\/\/ If there's no \"MyAddress\", generate one..\n\t\t\tif( !ad->Lookup( ATTR_MY_ADDRESS ) ) {\n\t\t\t\tMyString tmp;\n\t\t\t\ttmp.formatstr( \"<%s:0>\", my_ip_string() );\n\t\t\t\tad->Assign( ATTR_MY_ADDRESS, tmp.Value() );\n\t\t\t}\n\n\t\t\tif ( use_tcp ) {\n\t\t\t\tif( !sock ) {\n\t\t\t\t\tsock = collector->startCommand(command,Stream::reli_sock,20);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\t\/\/ Use existing connection.\n\t\t\t\t\tsock->encode();\n\t\t\t\t\tsock->put(command);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\t\/\/ We must open a new UDP socket each time.\n\t\t\t\tdelete sock;\n\t\t\t\tsock = collector->startCommand(command,Stream::safe_sock,20);\n\t\t\t}\n\n\t\t\tint result = 0;\n\t\t\tif ( sock ) {\n\t\t\t\tresult += putClassAd( sock, *ad );\n\t\t\t\tresult += sock->end_of_message();\n\t\t\t}\n\t\t\tif ( result != 2 ) {\n\t\t\t\tfprintf(stderr,\"failed to send classad to %s\\n\",collector->addr());\n\t\t\t\thad_error = true;\n\t\t\t\tfailure_count++;\n\t\t\t\tdelete sock;\n\t\t\t\tsock = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif( with_ack ) {\n\t\t\t\tsock->decode();\n\t\t\t\tint ok = 0;\n\t\t\t\tif( !sock->get(ok) || !sock->end_of_message() ) {\n\t\t\t\t\tfprintf(stderr,\"failed to get ack from %s\\n\",collector->addr());\n\t\t\t\t\thad_error = true;\n\t\t\t\t\tfailure_count++;\n\t\t\t\t\tdelete sock;\n\t\t\t\t\tsock = NULL;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\t\/\/ ack protocol does not allow for multiple updates,\n\t\t\t\t\t\/\/ so close the socket now\n\t\t\t\tdelete sock;\n\t\t\t\tsock = NULL;\n\t\t\t}\n\n\t\t\tsuccess_count++;\n\t\t\tif (many_connections) {\n\t\t\t\tsock = NULL;\n\t\t\t}\n\t\t}\n\t\tif( sock ) {\n\t\t\tCondorVersionInfo const *ver = sock->get_peer_version();\n\t\t\tif( !ver || ver->built_since_version(7,7,3) ) {\n\t\t\t\t\t\/\/ graceful hangup so the collector knows we are done\n\t\t\t\tsock->encode();\n\t\t\t\tint hangup_cmd = DC_NOP;\n\t\t\t\tsock->put(hangup_cmd);\n\t\t\t\tsock->end_of_message();\n\t\t\t}\n\n\t\t\tdelete sock;\n\t\t\tsock = NULL;\n\t\t}\n\n\t\tprintf(\"Sent %d of %d ad%s to %s.\\n\",\n\t\t\t success_count,\n\t\t\t success_count + failure_count,\n\t\t\t success_count+failure_count == 1 ? \"\" : \"s\",\n\t\t\t collector->name());\n\t}\n\n\tif (many_connections) {\n\t\tsleep(3600);\n\t}\n\tdelete collectors;\n\n\treturn (had_error)?1:0;\n}\n<commit_msg>Fix double-delete in condor_advertise<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_version.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"command_strings.h\"\n#include \"daemon.h\"\n#include \"safe_sock.h\"\n#include \"condor_distribution.h\"\n#include \"daemon_list.h\"\n#include \"dc_collector.h\"\n#include \"my_hostname.h\"\n\nvoid\nusage( const char *cmd , const char * opt)\n{\n\tfprintf(stderr,\"Usage: %s [options] <update-command> [<classad-filename>]\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\" -help Display options\\n\");\n\tfprintf(stderr,\" -version Display Condor version\\n\");\n\tfprintf(stderr,\" -pool <hostname> Use this central manager\\n\");\n\tfprintf(stderr,\" -debug Show extra debugging info\\n\");\n\tfprintf(stderr,\" -tcp Ship classad via TCP (default is UDP)\\n\");\n\tfprintf(stderr,\" -multiple Publish multiple ads, separated by blank lines\\n\");\n\n\tif (opt && ( !strcmp(opt,\"all\") || !strcmp(opt,\"cmd\"))) {\n\t\tfprintf(stderr,\"\\nAnd <update-command> is one of:\\n\");\n\t\tstatic const char * const aPre[] = {\"UPDATE_\", \"MERGE_\", \"INVALIDATE_\"};\n\t\tfor (int jj = 0; jj < (int)COUNTOF(aPre); ++jj) {\n\t\t\tfor (int id = UPDATE_STARTD_AD; id < UPDATE_STARTD_AD + 100; ++id) {\n\t\t\t\tconst char * cmdname = getCollectorCommandString(id);\n\t\t\t\tif (cmdname && starts_with(cmdname, aPre[jj])) {\n\t\t\t\t\tfprintf(stderr,\" %s\\n\",cmdname);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfprintf(stderr, \"\\nIf <classad-filename> does not exist or is -, classads will be read from standard input\\n\");\n\tfprintf(stderr,\"Example: %s -debug UPDATE_STORAGE_AD adfile\\n\\n\",cmd);\n}\n\n\/\/ this class is used to help parse one or more ClassAd's from a FILE*\nclass ToolClassAdFileParseHelper : public ClassAdFileParseHelper\n{\n public:\n\t\/\/ Some compilers whine when you have virtual methods but not an\n\t\/\/ explicit virtual destructor\n\tvirtual ~ToolClassAdFileParseHelper() {}\n\tToolClassAdFileParseHelper(bool multi, FILE* errout) : multiple(multi), out(errout) {};\n\n\t\/\/ return 0 to skip (is_comment), 1 to parse line, 2 for end-of-classad, -1 for abort\n\tvirtual int PreParse(std::string & line, ClassAd & \/*ad*\/, FILE* \/*file*\/) {\n\t\t\/\/ if this line matches the ad delimitor, tell the parser to stop parsing\n\t\tif (multiple && (line.empty() || (line[0] == '\\n')))\n\t\t\treturn 2; \/\/end-of-classad\n\n\t\t\/\/ check for blank lines or lines whose first character is #\n\t\t\/\/ tell the parse to skip those lines, otherwise tell the parser to\n\t\t\/\/ parse the line.\n\t\tfor (size_t ix = 0; ix < line.size(); ++ix) {\n\t\t\tif (line[ix] == '#' || line[ix] == '\\n')\n\t\t\t\treturn 0; \/\/ skip this line, but don't stop parsing.\n\t\t\tif (line[ix] != ' ' && line[ix] != '\\t')\n\t\t\t\treturn 1; \/\/ parse this line\n\t\t}\n\t\treturn 1; \/\/ parse this line.\n\t}\n\n\t\/\/ return 0 to skip and continue, 1 to re-parse line, 2 to quit parsing with success, -1 to abort parsing.\n\tvirtual int OnParseError(std::string & line, ClassAd & \/*ad*\/, FILE* file) {\n\t\t\/\/ print out where we barfed to the log file\n\t\tdprintf(D_ALWAYS,\"failed to create classad; bad expr = '%s'\\n\", line.c_str());\n\n\t\tif ( ! multiple) return -1; \/\/ abort\n\n\t\t\/\/ skip the remainder of the ad by reading until we see eof or a blank line.\n\t\tline = \"\";\n\t\twhile ( ! line.empty() && line[0] != '\\n') {\n\t\t\tif (feof(file))\n\t\t\t\tbreak;\n\t\t\tif ( ! readLine(line, file, false))\n\t\t\t\tbreak;\n\t\t}\n\t\treturn -1; \/\/ abort\n\t}\n\n private:\n\tbool multiple;\n\tFILE * out;\n\tstd::string delim;\n};\n\n\nvoid\nversion()\n{\n\tprintf( \"%s\\n%s\\n\", CondorVersion(), CondorPlatform() );\n}\n\nint main( int argc, char *argv[] )\n{\n\tconst char *filename=0;\n\tchar *pool=0;\n\tint command=-1;\n\tint i;\n\tbool with_ack = false;\n\tbool allow_multiple = false;\n\tbool many_connections = false;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n\tbool use_tcp = param_boolean( \"UPDATE_COLLECTOR_WITH_TCP\", true );\n\n\tfor( i=1; i<argc; i++ ) {\n\t\tif(!strcmp(argv[i],\"-help\") || !strcmp(argv[i],\"--help\")) {\n\t\t\tusage(argv[0], argv[i+1] ? argv[i+1] : \"cmd\");\n\t\t\texit(0);\n\t\t} else if(!strcmp(argv[i],\"-pool\")) {\n\t\t\ti++;\n\t\t\tif(!argv[i]) {\n\t\t\t\tfprintf(stderr,\"-pool requires an argument.\\n\\n\");\n\t\t\t\tusage(argv[0], NULL);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tpool = argv[i];\n\t\t} else if(!strncmp(argv[i],\"-tcp\",strlen(argv[i]))) {\n\t\t\tuse_tcp = true;\n\t\t} else if(!strncmp(argv[i],\"-udp\",strlen(argv[i]))) {\n\t\t\tuse_tcp = false;\n\t\t} else if(!strncmp(argv[i],\"-multiple\",strlen(argv[i]))) {\n\t\t\t\t\/\/ We don't set allow_multiple=true by default, because\n\t\t\t\t\/\/ existing users (e.g. glideinWMS) have stray blank lines\n\t\t\t\t\/\/ in the input file.\n\t\t\tallow_multiple = true;\n\t\t} else if(!strcmp(argv[i],\"-version\")) {\n\t\t\tversion();\n\t\t\texit(0);\n\t\t} else if(!strcmp(argv[i],\"-debug\")) {\n\t\t\t\t\/\/ dprintf to console\n\t\t\tdprintf_set_tool_debug(\"TOOL\", 0);\n\t\t} else if(argv[i][0]!='-' || !strcmp(argv[i],\"-\")) {\n\t\t\tif(command==-1) {\n\t\t\t\tcommand = getCollectorCommandNum(argv[i]);\n\t\t\t\tif(command==-1) {\n\t\t\t\t\tfprintf(stderr,\"Unknown command name %s\\n\\n\",argv[i]);\n\t\t\t\t\tusage(argv[0], \"all\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t} else if(!filename) {\n\t\t\t\tfilename = argv[i];\n\t\t\t} else {\n\t\t\t\tfprintf(stderr,\"Extra argument: %s\\n\\n\",argv[i]);\n\t\t\t\tusage(argv[0], NULL);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t} else if(!strncmp(argv[i],\"-many-connections\", strlen(argv[i]))) { \n\t\t\tmany_connections = true;\n\t\t} else {\n\t\t\tfprintf(stderr,\"Unknown argument: %s\\n\\n\",argv[i]);\n\t\t\tusage(argv[0], NULL);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tFILE *file;\n\tClassAdList ads;\n\tDaemon *collector;\n\tSock *sock;\n\n\tswitch( command ) {\n\tcase UPDATE_STARTD_AD_WITH_ACK:\n\t\twith_ack = true;\n\t\tbreak;\n\t}\n\n\tif( with_ack ) {\n\t\tuse_tcp = true;\n\t}\n\n\tif(!filename || !strcmp(filename,\"-\")) {\n\t\tfile = stdin;\n\t\tfilename = \"(stdin)\";\n\t} else {\n\t\tfile = safe_fopen_wrapper_follow(filename,\"r\");\n\t}\n\tif(!file) {\n\t\tfprintf(stderr,\"couldn't open %s: %s\\n\",filename,strerror(errno));\n\t\treturn 1;\n\t}\n\n\t\/\/ create class that we can use to influence the behavior of Classad::InsertFromFile\n\tToolClassAdFileParseHelper parse_helper(allow_multiple, stderr);\n\n\tfor (;;) {\n\t\tClassAd *ad = new ClassAd();\n\t\tint error;\n\t\tbool eof;\n\t\tint cAttrs = ad->InsertFromFile(file, eof, error, &parse_helper);\n\t\tif (error < 0) {\n\t\t\tfprintf(stderr,\"couldn't parse ClassAd in %s\\n\", filename);\n\t\t\tdelete ad;\n\t\t\treturn 1;\n\t\t}\n\t\tif (cAttrs > 0) {\n\t\t\tads.Insert(ad);\n\t\t} else {\n\t\t\tdelete ad;\n\t\t\tad = 0; \/\/ so we don't double delete it\n\t\t}\n\t\tif (eof) {\n\t\t\tbreak;\n\t\t}\n\t\tif( !allow_multiple && ads.Length() > 0 ) {\n\t\t\tfprintf(stderr,\"ERROR: multiple ads in %s\\n\", filename);\n\t\t\tdelete ad;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif(ads.Length() == 0) {\n\t\tfprintf(stderr,\"%s is empty\\n\",filename);\n\t\treturn 1;\n\t}\n\n\tCollectorList * collectors;\n\tif ( pool ) {\n\t\tcollector = new Daemon( DT_COLLECTOR, pool, 0 );\n\t\tcollectors = new CollectorList();\n\t\tcollectors->append (collector);\n\t} else {\n\t\tcollectors = CollectorList::create();\n\t}\n\n\tbool had_error = false;\n\n\tcollectors->rewind();\n\twhile (collectors->next(collector)) {\n\n\t\tdprintf(D_FULLDEBUG,\"locating collector %s...\\n\", collector->name());\n\n\t\tif(!collector->locate(Daemon::LOCATE_FOR_LOOKUP)) {\n\t\t\tfprintf(stderr,\"couldn't locate collector: %s\\n\",collector->error());\n\t\t\thad_error = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tdprintf(D_FULLDEBUG,\"collector is %s located at %s\\n\",\n\t\t\t\tcollector->hostname(),collector->addr());\n\n\t\tsock = NULL;\n\n\t\tClassAd *ad;\n\t\tint success_count = 0;\n\t\tint failure_count = 0;\n\t\tads.Rewind();\n\t\twhile( (ad=ads.Next()) ) {\n\n\t\t\t\t\/\/ If there's no \"MyAddress\", generate one..\n\t\t\tif( !ad->Lookup( ATTR_MY_ADDRESS ) ) {\n\t\t\t\tMyString tmp;\n\t\t\t\ttmp.formatstr( \"<%s:0>\", my_ip_string() );\n\t\t\t\tad->Assign( ATTR_MY_ADDRESS, tmp.Value() );\n\t\t\t}\n\n\t\t\tif ( use_tcp ) {\n\t\t\t\tif( !sock ) {\n\t\t\t\t\tsock = collector->startCommand(command,Stream::reli_sock,20);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\t\/\/ Use existing connection.\n\t\t\t\t\tsock->encode();\n\t\t\t\t\tsock->put(command);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\t\/\/ We must open a new UDP socket each time.\n\t\t\t\tdelete sock;\n\t\t\t\tsock = collector->startCommand(command,Stream::safe_sock,20);\n\t\t\t}\n\n\t\t\tint result = 0;\n\t\t\tif ( sock ) {\n\t\t\t\tresult += putClassAd( sock, *ad );\n\t\t\t\tresult += sock->end_of_message();\n\t\t\t}\n\t\t\tif ( result != 2 ) {\n\t\t\t\tfprintf(stderr,\"failed to send classad to %s\\n\",collector->addr());\n\t\t\t\thad_error = true;\n\t\t\t\tfailure_count++;\n\t\t\t\tdelete sock;\n\t\t\t\tsock = NULL;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif( with_ack ) {\n\t\t\t\tsock->decode();\n\t\t\t\tint ok = 0;\n\t\t\t\tif( !sock->get(ok) || !sock->end_of_message() ) {\n\t\t\t\t\tfprintf(stderr,\"failed to get ack from %s\\n\",collector->addr());\n\t\t\t\t\thad_error = true;\n\t\t\t\t\tfailure_count++;\n\t\t\t\t\tdelete sock;\n\t\t\t\t\tsock = NULL;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\t\/\/ ack protocol does not allow for multiple updates,\n\t\t\t\t\t\/\/ so close the socket now\n\t\t\t\tdelete sock;\n\t\t\t\tsock = NULL;\n\t\t\t}\n\n\t\t\tsuccess_count++;\n\t\t\tif (many_connections) {\n\t\t\t\tsock = NULL;\n\t\t\t}\n\t\t}\n\t\tif( sock ) {\n\t\t\tCondorVersionInfo const *ver = sock->get_peer_version();\n\t\t\tif( !ver || ver->built_since_version(7,7,3) ) {\n\t\t\t\t\t\/\/ graceful hangup so the collector knows we are done\n\t\t\t\tsock->encode();\n\t\t\t\tint hangup_cmd = DC_NOP;\n\t\t\t\tsock->put(hangup_cmd);\n\t\t\t\tsock->end_of_message();\n\t\t\t}\n\n\t\t\tdelete sock;\n\t\t\tsock = NULL;\n\t\t}\n\n\t\tprintf(\"Sent %d of %d ad%s to %s.\\n\",\n\t\t\t success_count,\n\t\t\t success_count + failure_count,\n\t\t\t success_count+failure_count == 1 ? \"\" : \"s\",\n\t\t\t collector->name());\n\t}\n\n\tif (many_connections) {\n\t\tsleep(3600);\n\t}\n\tdelete collectors;\n\n\treturn (had_error)?1:0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/dynet.h\"\n\n#include \"dynet\/exec.h\"\n#include \"dynet\/nodes.h\"\n#include \"dynet\/param-nodes.h\"\n#include \"dynet\/aligned-mem-pool.h\"\n#include \"dynet\/dynet-helper.h\"\n#include \"dynet\/expr.h\"\n\nusing namespace std;\n\nnamespace dynet {\n\nfloat* kSCALAR_MINUSONE;\nfloat* kSCALAR_ONE;\nfloat* kSCALAR_ZERO;\nint n_hgs = 0;\n\nNode::~Node() {}\nsize_t Node::aux_storage_size() const { return 0; }\n\n\/\/ perform the forward\/backward passes in one or multiple calls\n\/\/ TODO: This is a lot of code for something simple. Can it be shortened?\nvoid Node::forward(const std::vector<const Tensor*>& xs,\n Tensor& fx) const {\n if(this->supports_multibatch() || fx.d.batch_elems() == 1) {\n forward_impl(xs, fx);\n } else {\n size_t i;\n std::vector<Tensor> xs_elems(xs.size());\n std::vector<const Tensor*> xs_ptrs(xs.size());\n std::vector<size_t> xs_sizes(xs.size());\n for(i = 0; i < xs.size(); ++i) {\n xs_elems[i] = xs[i]->batch_elem(0);\n xs_ptrs[i] = &xs_elems[i];\n xs_sizes[i] = xs_elems[i].d.size();\n }\n Tensor fx_elem(fx.batch_elem(0));\n size_t fx_size = fx_elem.d.size();\n forward_impl(xs_ptrs, fx_elem);\n for(unsigned b = 1; b < fx.d.batch_elems(); ++b) {\n for(i = 0; i < xs.size(); ++i) xs_elems[i].v += xs_sizes[i];\n fx_elem.v += fx_size;\n forward_impl(xs_ptrs, fx_elem);\n }\n }\n}\nvoid Node::backward(const std::vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned xs_i,\n Tensor& dEdxi) const {\n if(this->supports_multibatch() || fx.d.batch_elems() == 1) {\n backward_impl(xs, fx, dEdf, xs_i, dEdxi);\n } else {\n size_t i;\n std::vector<Tensor> xs_elems(xs.size());\n std::vector<const Tensor*> xs_ptrs(xs.size());\n std::vector<size_t> xs_sizes(xs.size());\n for(i = 0; i < xs.size(); ++i) {\n xs_elems[i] = xs[i]->batch_elem(0);\n xs_ptrs[i] = &xs_elems[i];\n xs_sizes[i] = xs_elems[i].d.size();\n }\n Tensor fx_elem(fx.batch_elem(0));\n size_t fx_size = fx_elem.d.size();\n Tensor dEdf_elem(dEdf.batch_elem(0));\n size_t dEdf_size = dEdf_elem.d.size();\n Tensor dEdxi_elem(dEdxi.batch_elem(0));\n size_t dEdxi_size = dEdxi_elem.d.size();\n backward_impl(xs_ptrs, fx_elem, dEdf_elem, xs_i, dEdxi_elem);\n for(unsigned b = 1; b < fx.d.batch_elems(); ++b) {\n for(i = 0; i < xs.size(); ++i) xs_elems[i].v += xs_sizes[i];\n fx_elem.v += fx_size;\n dEdf_elem.v += dEdf_size;\n dEdxi_elem.v += dEdxi_size;\n backward_impl(xs_ptrs, fx_elem, dEdf_elem, xs_i, dEdxi_elem);\n }\n }\n}\n\nComputationGraph::ComputationGraph() :\n ee(new SimpleExecutionEngine(*this)) {\n ++n_hgs;\n if (n_hgs > 1) {\n cerr << \"Memory allocator assumes only a single ComputationGraph at a time.\\n\";\n throw std::runtime_error(\"Attempted to create >1 CG\");\n }\n}\n\nComputationGraph::~ComputationGraph() {\n this->clear();\n delete ee;\n --n_hgs;\n}\n\nvoid ComputationGraph::clear() {\n parameter_nodes.clear();\n for (auto n : nodes) delete n;\n nodes.clear();\n}\n\nCGCheckpoint ComputationGraph::_get_checkpoint() {\n CGCheckpoint p;\n p.device_mem_checkpoint = default_device->mark(this);\n p.node_idx = nodes.size();\n p.par_node_idx = parameter_nodes.size();\n return p;\n}\n\nvoid ComputationGraph::_revert(CGCheckpoint p) {\n default_device->revert(p.device_mem_checkpoint);\n \/\/ clear all nodes at position >= p.node_idx\n if ((int)nodes.size() > p.node_idx) {\n nodes.resize(p.node_idx); \/\/ TODO verify deletion of nodes.\n ee->invalidate(p.node_idx-1); \/\/ clear precomputed forward values\n }\n \/\/ clear all parameter nodes at position >= p.par_node_idx\n if ((int)parameter_nodes.size() > p.par_node_idx) {\n parameter_nodes.resize(p.par_node_idx);\n }\n}\n\nvoid ComputationGraph::checkpoint() {\n checkpoints.push_back(_get_checkpoint());\n}\n\nvoid ComputationGraph::revert() {\n if (checkpoints.size() == 0) return;\n _revert(checkpoints.back());\n checkpoints.pop_back();\n}\n\n\nVariableIndex ComputationGraph::add_input(real s) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new ScalarInputNode(s));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const real* ps) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new ScalarInputNode(ps));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<float>& pm) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new InputNode(d, pm));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<float>* pm) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new InputNode(d, pm));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<unsigned int>& ids, const vector<float>& data, float defdata) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new SparseInputNode(d, ids, data, defdata));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_parameters(Parameter p) {\n VariableIndex new_node_index(nodes.size());\n ParameterNode* new_node = new ParameterNode(p);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_parameters(Parameter p) {\n VariableIndex new_node_index(nodes.size());\n ConstParameterNode* new_node = new ConstParameterNode(p);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const unsigned* pindex) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, pindex);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, unsigned index) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, index);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const std::vector<unsigned>& indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const std::vector<unsigned>* indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const unsigned* pindex) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, pindex);\n \/\/ get rid of the following in favor of using parameter_nodes to see the needs_derivative\n \/\/ expression\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, unsigned index) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, index);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const std::vector<unsigned>& indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const std::vector<unsigned>* indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\n\/\/ factory function should call this right after creating a new node object\n\/\/ to set its dimensions properly\nvoid ComputationGraph::set_dim_for_new_node(const VariableIndex& i) {\n Node* node = nodes[i];\n vector<Dim> xds(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xds[ai] = nodes[arg]->dim;\n ++ai;\n }\n node->dim = node->dim_forward(xds);\n}\n\nconst Tensor& ComputationGraph::incremental_forward(const expr::Expression& last) { return ee->incremental_forward(last.i); }\nconst Tensor& ComputationGraph::forward(const expr::Expression& last) { return ee->forward(last.i); }\nconst Tensor& ComputationGraph::incremental_forward(VariableIndex last) { return ee->incremental_forward(last); }\nconst Tensor& ComputationGraph::forward(VariableIndex last) { return ee->forward(last); }\nconst Tensor& ComputationGraph::get_value(VariableIndex i) { return ee->get_value(i); }\nconst Tensor& ComputationGraph::get_value(const expr::Expression& e) { return this->get_value(e.i); }\nvoid ComputationGraph::invalidate() { ee->invalidate(); }\nvoid ComputationGraph::backward(const expr::Expression& last) { ee->backward(last.i); }\nvoid ComputationGraph::backward(VariableIndex i) { ee->backward(i); }\n\nvoid ComputationGraph::print_graphviz() const {\n cerr << \"digraph G {\\n rankdir=LR;\\n nodesep=.05;\\n\";\n unsigned nc = 0;\n for (auto node : nodes) {\n vector<string> var_names;\n for (auto arg : node->args)\n var_names.push_back(string(\"v\") + to_string((unsigned)arg));\n cerr << \" N\" << nc << \" [label=\\\"v\" << nc << \" = \"\n << node->as_string(var_names) << \"\\\"];\\n\";\n for (auto arg : node->args)\n cerr << \" N\" << ((unsigned)arg) << \" -> N\" << nc << \";\\n\";\n ++nc;\n }\n cerr << \"}\\n\";\n}\n\n} \/\/ namespace dynet\n\n<commit_msg>Fixed broadcasting in new batching impl<commit_after>#include \"dynet\/dynet.h\"\n\n#include \"dynet\/exec.h\"\n#include \"dynet\/nodes.h\"\n#include \"dynet\/param-nodes.h\"\n#include \"dynet\/aligned-mem-pool.h\"\n#include \"dynet\/dynet-helper.h\"\n#include \"dynet\/expr.h\"\n\nusing namespace std;\n\nnamespace dynet {\n\nfloat* kSCALAR_MINUSONE;\nfloat* kSCALAR_ONE;\nfloat* kSCALAR_ZERO;\nint n_hgs = 0;\n\nNode::~Node() {}\nsize_t Node::aux_storage_size() const { return 0; }\n\n\/\/ perform the forward\/backward passes in one or multiple calls\n\/\/ TODO: This is a lot of code for something simple. Can it be shortened?\nvoid Node::forward(const std::vector<const Tensor*>& xs,\n Tensor& fx) const {\n if(this->supports_multibatch() || fx.d.batch_elems() == 1) {\n forward_impl(xs, fx);\n } else {\n size_t i;\n std::vector<Tensor> xs_elems(xs.size());\n std::vector<const Tensor*> xs_ptrs(xs.size());\n std::vector<size_t> xs_sizes(xs.size());\n for(i = 0; i < xs.size(); ++i) {\n xs_elems[i] = xs[i]->batch_elem(0);\n xs_ptrs[i] = &xs_elems[i];\n xs_sizes[i] = xs_elems[i].d.size();\n }\n Tensor fx_elem(fx.batch_elem(0));\n size_t fx_size = fx_elem.d.size();\n forward_impl(xs_ptrs, fx_elem);\n for(unsigned b = 1; b < fx.d.batch_elems(); ++b) {\n for(i = 0; i < xs.size(); ++i)\n if(xs_elems[i].d.bd > 1)\n xs_elems[i].v += xs_sizes[i];\n fx_elem.v += fx_size;\n forward_impl(xs_ptrs, fx_elem);\n }\n }\n}\nvoid Node::backward(const std::vector<const Tensor*>& xs,\n const Tensor& fx,\n const Tensor& dEdf,\n unsigned xs_i,\n Tensor& dEdxi) const {\n if(this->supports_multibatch() || fx.d.batch_elems() == 1) {\n backward_impl(xs, fx, dEdf, xs_i, dEdxi);\n } else {\n size_t i;\n std::vector<Tensor> xs_elems(xs.size());\n std::vector<const Tensor*> xs_ptrs(xs.size());\n std::vector<size_t> xs_sizes(xs.size());\n for(i = 0; i < xs.size(); ++i) {\n xs_elems[i] = xs[i]->batch_elem(0);\n xs_ptrs[i] = &xs_elems[i];\n xs_sizes[i] = xs_elems[i].d.size();\n }\n Tensor fx_elem(fx.batch_elem(0));\n size_t fx_size = fx_elem.d.size();\n Tensor dEdf_elem(dEdf.batch_elem(0));\n size_t dEdf_size = dEdf_elem.d.size();\n Tensor dEdxi_elem(dEdxi.batch_elem(0));\n size_t dEdxi_size = dEdxi_elem.d.size();\n backward_impl(xs_ptrs, fx_elem, dEdf_elem, xs_i, dEdxi_elem);\n for(unsigned b = 1; b < fx.d.batch_elems(); ++b) {\n for(i = 0; i < xs.size(); ++i)\n if(xs_elems[i].d.bd > 1)\n xs_elems[i].v += xs_sizes[i];\n fx_elem.v += fx_size;\n dEdf_elem.v += dEdf_size;\n if(dEdxi_elem.d.bd > 1)\n dEdxi_elem.v += dEdxi_size;\n backward_impl(xs_ptrs, fx_elem, dEdf_elem, xs_i, dEdxi_elem);\n }\n }\n}\n\nComputationGraph::ComputationGraph() :\n ee(new SimpleExecutionEngine(*this)) {\n ++n_hgs;\n if (n_hgs > 1) {\n cerr << \"Memory allocator assumes only a single ComputationGraph at a time.\\n\";\n throw std::runtime_error(\"Attempted to create >1 CG\");\n }\n}\n\nComputationGraph::~ComputationGraph() {\n this->clear();\n delete ee;\n --n_hgs;\n}\n\nvoid ComputationGraph::clear() {\n parameter_nodes.clear();\n for (auto n : nodes) delete n;\n nodes.clear();\n}\n\nCGCheckpoint ComputationGraph::_get_checkpoint() {\n CGCheckpoint p;\n p.device_mem_checkpoint = default_device->mark(this);\n p.node_idx = nodes.size();\n p.par_node_idx = parameter_nodes.size();\n return p;\n}\n\nvoid ComputationGraph::_revert(CGCheckpoint p) {\n default_device->revert(p.device_mem_checkpoint);\n \/\/ clear all nodes at position >= p.node_idx\n if ((int)nodes.size() > p.node_idx) {\n nodes.resize(p.node_idx); \/\/ TODO verify deletion of nodes.\n ee->invalidate(p.node_idx-1); \/\/ clear precomputed forward values\n }\n \/\/ clear all parameter nodes at position >= p.par_node_idx\n if ((int)parameter_nodes.size() > p.par_node_idx) {\n parameter_nodes.resize(p.par_node_idx);\n }\n}\n\nvoid ComputationGraph::checkpoint() {\n checkpoints.push_back(_get_checkpoint());\n}\n\nvoid ComputationGraph::revert() {\n if (checkpoints.size() == 0) return;\n _revert(checkpoints.back());\n checkpoints.pop_back();\n}\n\n\nVariableIndex ComputationGraph::add_input(real s) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new ScalarInputNode(s));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const real* ps) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new ScalarInputNode(ps));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<float>& pm) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new InputNode(d, pm));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<float>* pm) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new InputNode(d, pm));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_input(const Dim& d, const vector<unsigned int>& ids, const vector<float>& data, float defdata) {\n VariableIndex new_node_index(nodes.size());\n nodes.push_back(new SparseInputNode(d, ids, data, defdata));\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_parameters(Parameter p) {\n VariableIndex new_node_index(nodes.size());\n ParameterNode* new_node = new ParameterNode(p);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_parameters(Parameter p) {\n VariableIndex new_node_index(nodes.size());\n ConstParameterNode* new_node = new ConstParameterNode(p);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const unsigned* pindex) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, pindex);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, unsigned index) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, index);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const std::vector<unsigned>& indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_lookup(LookupParameter p, const std::vector<unsigned>* indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n parameter_nodes.push_back(new_node_index);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const unsigned* pindex) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, pindex);\n \/\/ get rid of the following in favor of using parameter_nodes to see the needs_derivative\n \/\/ expression\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, unsigned index) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, index);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const std::vector<unsigned>& indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\nVariableIndex ComputationGraph::add_const_lookup(LookupParameter p, const std::vector<unsigned>* indices) {\n VariableIndex new_node_index(nodes.size());\n LookupNode* new_node = new LookupNode(p, indices);\n nodes.push_back(new_node);\n set_dim_for_new_node(new_node_index);\n return new_node_index;\n}\n\n\/\/ factory function should call this right after creating a new node object\n\/\/ to set its dimensions properly\nvoid ComputationGraph::set_dim_for_new_node(const VariableIndex& i) {\n Node* node = nodes[i];\n vector<Dim> xds(node->arity());\n unsigned ai = 0;\n for (VariableIndex arg : node->args) {\n xds[ai] = nodes[arg]->dim;\n ++ai;\n }\n node->dim = node->dim_forward(xds);\n}\n\nconst Tensor& ComputationGraph::incremental_forward(const expr::Expression& last) { return ee->incremental_forward(last.i); }\nconst Tensor& ComputationGraph::forward(const expr::Expression& last) { return ee->forward(last.i); }\nconst Tensor& ComputationGraph::incremental_forward(VariableIndex last) { return ee->incremental_forward(last); }\nconst Tensor& ComputationGraph::forward(VariableIndex last) { return ee->forward(last); }\nconst Tensor& ComputationGraph::get_value(VariableIndex i) { return ee->get_value(i); }\nconst Tensor& ComputationGraph::get_value(const expr::Expression& e) { return this->get_value(e.i); }\nvoid ComputationGraph::invalidate() { ee->invalidate(); }\nvoid ComputationGraph::backward(const expr::Expression& last) { ee->backward(last.i); }\nvoid ComputationGraph::backward(VariableIndex i) { ee->backward(i); }\n\nvoid ComputationGraph::print_graphviz() const {\n cerr << \"digraph G {\\n rankdir=LR;\\n nodesep=.05;\\n\";\n unsigned nc = 0;\n for (auto node : nodes) {\n vector<string> var_names;\n for (auto arg : node->args)\n var_names.push_back(string(\"v\") + to_string((unsigned)arg));\n cerr << \" N\" << nc << \" [label=\\\"v\" << nc << \" = \"\n << node->as_string(var_names) << \"\\\"];\\n\";\n for (auto arg : node->args)\n cerr << \" N\" << ((unsigned)arg) << \" -> N\" << nc << \";\\n\";\n ++nc;\n }\n cerr << \"}\\n\";\n}\n\n} \/\/ namespace dynet\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef __PART_DATA_HPP\n#define __PART_DATA_HPP\n\n#include <valarray>\n\n#define FLOAT_TYPE float\n#define N_TYPES 6\n\n\/\/Class to generate a regular grid of particle positions on demand.\nclass part_grid\n{\n public:\n \/* Construct the particle grid parameters.\n * NumPart should be the number of particles per side; the cube root of the total number of particles.\n * Masses are the mass ratios of the different particle species, for making sure no two types share the same position\n * Box is the boxsize.*\/\n part_grid(const int NumPart[], const double Masses[], const double Box);\n \/* Get the position of a particle at some index on a grid.\n * We want to return:\n * size_t index = k + j* NumPart + i * NumPart**2\n * Pos[0] = i \/NumPart * pspace[type]\n * Pos[1] = j \/NumPart * pspace[type]\n * Pos[2] = k \/NumPart * pspace[type]\n * In other words, k is fast, j is medium, i is slow.\n *\/\n double Pos(size_t index, int axis, int type);\n \/\/Get number of particles\n int GetNumPart(int type);\n \/\/Get box size\n inline double GetBox(){\n return Box;\n }\n private:\n const std::valarray<int> NumPart;\n const double Box;\n double pspace[N_TYPES];\n double shift[N_TYPES][3];\n};\n\n\/\/Class to store the Zeldovich and 2LPT displacements for a particle type.\nclass lpt_data\n{\n public:\n \/\/Again, NumPart is the cube root of the particle number!\n lpt_data(const int NumPart, bool twolpt=true): vel_prefac(0), vel_prefac2(0), twolpt(twolpt),Vel_data(3*NumPart*NumPart*NumPart),Vel_2_data(twolpt*3*NumPart*NumPart*NumPart)\n {}\n \/\/Note Vel_2_data takes zero space if !twolpt\n inline void SetVel(FLOAT_TYPE Vel_in, size_t index, int axis){\n Vel_data[3*index+axis] = Vel_in;\n return;\n }\n inline void Set2Vel(FLOAT_TYPE Vel_in, size_t index, int axis){\n Vel_2_data[3*index+axis] = Vel_in;\n return;\n }\n inline double GetVel(size_t index, int axis)\n {\n double vel = vel_prefac*Vel_data[3*index+axis];\n if(twolpt)\n vel += vel_prefac2*Vel_2_data[3*index+axis];\n return vel;\n }\n inline double GetDisp(size_t index, int axis)\n {\n double disp = Vel_data[3*index+axis];\n if(twolpt)\n disp -= 3.\/7.*Vel_2_data[3*index+axis];\n return disp;\n }\n inline size_t GetNumPart(){\n return Vel_data.size()\/3;\n }\n void SetVelPrefac(double vel_prefac_i, double vel_prefac2_i)\n {\n vel_prefac = vel_prefac_i;\n vel_prefac2 = vel_prefac2_i;\n }\n private:\n double vel_prefac;\n double vel_prefac2;\n const bool twolpt;\n std::valarray <FLOAT_TYPE> Vel_data;\n std::valarray <FLOAT_TYPE> Vel_2_data;\n};\n\n#endif\n\n<commit_msg>Explicitly cast to a wider integer type to avoid possible overflows<commit_after>#ifndef __PART_DATA_HPP\n#define __PART_DATA_HPP\n\n#include <valarray>\n\n#define FLOAT_TYPE float\n#define N_TYPES 6\n\n\/\/Class to generate a regular grid of particle positions on demand.\nclass part_grid\n{\n public:\n \/* Construct the particle grid parameters.\n * NumPart should be the number of particles per side; the cube root of the total number of particles.\n * Masses are the mass ratios of the different particle species, for making sure no two types share the same position\n * Box is the boxsize.*\/\n part_grid(const int NumPart[], const double Masses[], const double Box);\n \/* Get the position of a particle at some index on a grid.\n * We want to return:\n * size_t index = k + j* NumPart + i * NumPart**2\n * Pos[0] = i \/NumPart * pspace[type]\n * Pos[1] = j \/NumPart * pspace[type]\n * Pos[2] = k \/NumPart * pspace[type]\n * In other words, k is fast, j is medium, i is slow.\n *\/\n double Pos(size_t index, int axis, int type);\n \/\/Get number of particles\n int GetNumPart(int type);\n \/\/Get box size\n inline double GetBox(){\n return Box;\n }\n private:\n const std::valarray<int> NumPart;\n const double Box;\n double pspace[N_TYPES];\n double shift[N_TYPES][3];\n};\n\n\/\/Class to store the Zeldovich and 2LPT displacements for a particle type.\nclass lpt_data\n{\n public:\n \/\/Again, NumPart is the cube root of the particle number!\n lpt_data(const int NumPart, bool twolpt=true): vel_prefac(0), vel_prefac2(0), twolpt(twolpt),Vel_data(3*static_cast<size_t>(NumPart)*NumPart*NumPart),Vel_2_data(twolpt*3*static_cast<size_t>(NumPart)*NumPart*NumPart)\n {}\n \/\/Note Vel_2_data takes zero space if !twolpt\n inline void SetVel(FLOAT_TYPE Vel_in, size_t index, int axis){\n Vel_data[3*index+axis] = Vel_in;\n return;\n }\n inline void Set2Vel(FLOAT_TYPE Vel_in, size_t index, int axis){\n Vel_2_data[3*index+axis] = Vel_in;\n return;\n }\n inline double GetVel(size_t index, int axis)\n {\n double vel = vel_prefac*Vel_data[3*index+axis];\n if(twolpt)\n vel += vel_prefac2*Vel_2_data[3*index+axis];\n return vel;\n }\n inline double GetDisp(size_t index, int axis)\n {\n double disp = Vel_data[3*index+axis];\n if(twolpt)\n disp -= 3.\/7.*Vel_2_data[3*index+axis];\n return disp;\n }\n inline size_t GetNumPart(){\n return Vel_data.size()\/3;\n }\n void SetVelPrefac(double vel_prefac_i, double vel_prefac2_i)\n {\n vel_prefac = vel_prefac_i;\n vel_prefac2 = vel_prefac2_i;\n }\n private:\n double vel_prefac;\n double vel_prefac2;\n const bool twolpt;\n std::valarray <FLOAT_TYPE> Vel_data;\n std::valarray <FLOAT_TYPE> Vel_2_data;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef GRAPHICSDEVICE_HPP_INCLUDED\n#define GRAPHICSDEVICE_HPP_INCLUDED\n\n#include \"graphicsresource.hpp\"\n#include \"vertexattribute.hpp\"\n\n#include <string>\n#include <vector>\n\nnamespace gst\n{\n class Color;\n class Image;\n class Resolution;\n class ShadowedData;\n class Texture;\n class Texture2D;\n class TextureCube;\n class Viewport;\n\n enum class AttachmentType;\n enum class AttachmentPoint;\n enum class BlendMode;\n enum class BufferTarget;\n enum class CubeFace;\n enum class CullFace;\n enum class DataUsage;\n enum class DrawMode;\n enum class PixelFormat;\n enum class RenderbufferFormat;\n enum class ShaderType;\n enum class TextureFormat;\n enum class TextureTarget;\n\n \/\/ The responsibility of this class is to interact with a graphics card.\n class GraphicsDevice {\n public:\n virtual ~GraphicsDevice() = default;\n\n \/\/ Clear buffers to present values.\n virtual void clear(bool color, bool depth) = 0;\n\n \/\/ Set clear values for color buffers.\n virtual void set_clear_color(Color const & clear_color) = 0;\n \/\/ Set blend mode enabled\/disabled with appropiate blend function.\n virtual void set_blend_mode(BlendMode blend_mode) = 0;\n \/\/ Set faces that can be culled.\n virtual void set_cull_face(CullFace cull_face) = 0;\n \/\/ Set depth mask enabled\/disabled.\n virtual void set_depth_mask(bool depth_mask) = 0;\n \/\/ Set depth test enabled\/disabled.\n virtual void set_depth_test(bool depth_test) = 0;\n \/\/ Set viewport.\n virtual void set_viewport(Viewport const & viewport) = 0;\n\n \/\/ Return new shader object.\n virtual ResourceName create_shader(ShaderType type) = 0;\n \/\/ Destroy shader object.\n virtual void destroy_shader(ResourceName name) = 0;\n \/\/ Compile shader from specified source.\n virtual void compile_shader(ResourceName name, std::string const & source) = 0;\n \/\/ Return status from last compile operation.\n virtual bool get_compile_status(ResourceName name) = 0;\n \/\/ Return error message from last compile operation.\n virtual std::string get_compile_error(ResourceName name) = 0;\n\n \/\/ Return new program object.\n virtual ResourceName create_program() = 0;\n \/\/ Destroy program object.\n virtual void destroy_program(ResourceName name) = 0;\n \/\/ Attach specified shader object to specified program object.\n virtual void attach_shader(ResourceName program_name, ResourceName shader_name) = 0;\n \/\/ Attach specified shader object to specified program object.\n virtual void detach_shader(ResourceName program_name, ResourceName shader_name) = 0;\n \/\/ Link program object.\n virtual void link_program(ResourceName name) = 0;\n \/\/ Return status from last link operation.\n virtual bool get_link_status(ResourceName name) = 0;\n \/\/ Return error message from last compile operation.\n virtual std::string get_link_error(ResourceName name) = 0;\n \/\/ Bind vertex attribute index with a named attribute variable.\n virtual void bind_attribute_location(ResourceName program_name, int index, std::string const & name) = 0;\n \/\/ Return uniform location from specified name.\n virtual int get_uniform_location(ResourceName program_name, std::string const & name) = 0;\n \/\/ Modify value of uniform.\n virtual void uniform(int location, ShadowedData const & data) = 0;\n \/\/ Install specified program object as part of current rendering state.\n virtual void use_program(ResourceName name) = 0;\n\n \/\/ Return new buffer object.\n virtual ResourceName create_buffer() = 0;\n \/\/ Destroy buffer object.\n virtual void destroy_buffer(ResourceName name) = 0;\n \/\/ Bind buffer object.\n virtual void bind_buffer(ResourceName name, BufferTarget target) = 0;\n \/\/ Buffer data to current bound buffer object.\n virtual void buffer_data(BufferTarget target, ShadowedData const & data, DataUsage usage) = 0;\n\n \/\/ Return new vertex array object.\n virtual ResourceName create_vertex_array() = 0;\n \/\/ Destroy vertex array object.\n virtual void destroy_vertex_array(ResourceName name) = 0;\n \/\/ Bind vertex array object.\n virtual void bind_vertex_array(ResourceName name) = 0;\n \/\/ Render primitives from stored array data.\n virtual void draw_arrays(DrawMode mode, int first, int count) = 0;\n \/\/ Render primitives from stored array data.\n virtual void draw_elements(DrawMode mode, int count) = 0;\n \/\/ Enable and define generic vertex attribute.\n virtual void enable_vertex_attribute(VertexAttribute const & attribute) = 0;\n\n \/\/ Return new renderbuffer object.\n virtual ResourceName create_renderbuffer() = 0;\n \/\/ Destroy renderbuffer object.\n virtual void destroy_renderbuffer(ResourceName name) = 0;\n \/\/ Bind renderbuffer object.\n virtual void bind_renderbuffer(ResourceName name) = 0;\n \/\/ Establish data storage of specified format and dimensions for renderbuffer objects image.\n virtual void renderbuffer_storage(Resolution size, RenderbufferFormat format) = 0;\n\n \/\/ Create new texture object.\n virtual ResourceName create_texture() = 0;\n \/\/ Destroy texture object.\n virtual void destroy_texture(ResourceName name) = 0;\n \/\/ Bind texture object.\n virtual void bind_texture(ResourceName name, TextureTarget target, int unit) = 0;\n \/\/ Update texture storage for 2-dimensional texture.\n virtual void update_texture_storage(\n TextureFormat internal_format,\n PixelFormat source_format,\n Resolution size,\n std::vector<unsigned char> const & data) = 0;\n \/\/ Update texture storage for texture cube face.\n virtual void update_texture_storage(\n TextureFormat internal_format,\n PixelFormat source_format,\n Resolution size,\n std::vector<unsigned char> const & data,\n CubeFace face) = 0;\n \/\/ Update texture parameters.\n virtual void update_texture_parameters(Texture const & texture) = 0;\n\n \/\/ Create new framebuffer object.\n virtual ResourceName create_framebuffer() = 0;\n \/\/ Destroy framebuffer object.\n virtual void destroy_framebuffer(ResourceName name) = 0;\n \/\/ Bind framebuffer object.\n virtual void bind_framebuffer(ResourceName name) = 0;\n \/\/ Attach a texture\/renderbuffer object to the currently bound framebuffer object.\n virtual void attach_to_framebuffer(ResourceName attachment, AttachmentType type, AttachmentPoint point) = 0;\n \/\/ Return array of status messages for currently bound framebuffer object.\n virtual std::vector<std::string> check_framebuffer_status() const = 0;\n\n \/\/ Return array of error messages (if any).\n virtual std::vector<std::string> get_errors() const = 0;\n };\n}\n\n#endif\n<commit_msg>change clear comment<commit_after>#ifndef GRAPHICSDEVICE_HPP_INCLUDED\n#define GRAPHICSDEVICE_HPP_INCLUDED\n\n#include \"graphicsresource.hpp\"\n#include \"vertexattribute.hpp\"\n\n#include <string>\n#include <vector>\n\nnamespace gst\n{\n class Color;\n class Image;\n class Resolution;\n class ShadowedData;\n class Texture;\n class Texture2D;\n class TextureCube;\n class Viewport;\n\n enum class AttachmentType;\n enum class AttachmentPoint;\n enum class BlendMode;\n enum class BufferTarget;\n enum class CubeFace;\n enum class CullFace;\n enum class DataUsage;\n enum class DrawMode;\n enum class PixelFormat;\n enum class RenderbufferFormat;\n enum class ShaderType;\n enum class TextureFormat;\n enum class TextureTarget;\n\n \/\/ The responsibility of this class is to interact with a graphics card.\n class GraphicsDevice {\n public:\n virtual ~GraphicsDevice() = default;\n\n \/\/ Clear buffers.\n virtual void clear(bool color, bool depth) = 0;\n\n \/\/ Set clear values for color buffers.\n virtual void set_clear_color(Color const & clear_color) = 0;\n \/\/ Set blend mode enabled\/disabled with appropiate blend function.\n virtual void set_blend_mode(BlendMode blend_mode) = 0;\n \/\/ Set faces that can be culled.\n virtual void set_cull_face(CullFace cull_face) = 0;\n \/\/ Set depth mask enabled\/disabled.\n virtual void set_depth_mask(bool depth_mask) = 0;\n \/\/ Set depth test enabled\/disabled.\n virtual void set_depth_test(bool depth_test) = 0;\n \/\/ Set viewport.\n virtual void set_viewport(Viewport const & viewport) = 0;\n\n \/\/ Return new shader object.\n virtual ResourceName create_shader(ShaderType type) = 0;\n \/\/ Destroy shader object.\n virtual void destroy_shader(ResourceName name) = 0;\n \/\/ Compile shader from specified source.\n virtual void compile_shader(ResourceName name, std::string const & source) = 0;\n \/\/ Return status from last compile operation.\n virtual bool get_compile_status(ResourceName name) = 0;\n \/\/ Return error message from last compile operation.\n virtual std::string get_compile_error(ResourceName name) = 0;\n\n \/\/ Return new program object.\n virtual ResourceName create_program() = 0;\n \/\/ Destroy program object.\n virtual void destroy_program(ResourceName name) = 0;\n \/\/ Attach specified shader object to specified program object.\n virtual void attach_shader(ResourceName program_name, ResourceName shader_name) = 0;\n \/\/ Attach specified shader object to specified program object.\n virtual void detach_shader(ResourceName program_name, ResourceName shader_name) = 0;\n \/\/ Link program object.\n virtual void link_program(ResourceName name) = 0;\n \/\/ Return status from last link operation.\n virtual bool get_link_status(ResourceName name) = 0;\n \/\/ Return error message from last compile operation.\n virtual std::string get_link_error(ResourceName name) = 0;\n \/\/ Bind vertex attribute index with a named attribute variable.\n virtual void bind_attribute_location(ResourceName program_name, int index, std::string const & name) = 0;\n \/\/ Return uniform location from specified name.\n virtual int get_uniform_location(ResourceName program_name, std::string const & name) = 0;\n \/\/ Modify value of uniform.\n virtual void uniform(int location, ShadowedData const & data) = 0;\n \/\/ Install specified program object as part of current rendering state.\n virtual void use_program(ResourceName name) = 0;\n\n \/\/ Return new buffer object.\n virtual ResourceName create_buffer() = 0;\n \/\/ Destroy buffer object.\n virtual void destroy_buffer(ResourceName name) = 0;\n \/\/ Bind buffer object.\n virtual void bind_buffer(ResourceName name, BufferTarget target) = 0;\n \/\/ Buffer data to current bound buffer object.\n virtual void buffer_data(BufferTarget target, ShadowedData const & data, DataUsage usage) = 0;\n\n \/\/ Return new vertex array object.\n virtual ResourceName create_vertex_array() = 0;\n \/\/ Destroy vertex array object.\n virtual void destroy_vertex_array(ResourceName name) = 0;\n \/\/ Bind vertex array object.\n virtual void bind_vertex_array(ResourceName name) = 0;\n \/\/ Render primitives from stored array data.\n virtual void draw_arrays(DrawMode mode, int first, int count) = 0;\n \/\/ Render primitives from stored array data.\n virtual void draw_elements(DrawMode mode, int count) = 0;\n \/\/ Enable and define generic vertex attribute.\n virtual void enable_vertex_attribute(VertexAttribute const & attribute) = 0;\n\n \/\/ Return new renderbuffer object.\n virtual ResourceName create_renderbuffer() = 0;\n \/\/ Destroy renderbuffer object.\n virtual void destroy_renderbuffer(ResourceName name) = 0;\n \/\/ Bind renderbuffer object.\n virtual void bind_renderbuffer(ResourceName name) = 0;\n \/\/ Establish data storage of specified format and dimensions for renderbuffer objects image.\n virtual void renderbuffer_storage(Resolution size, RenderbufferFormat format) = 0;\n\n \/\/ Create new texture object.\n virtual ResourceName create_texture() = 0;\n \/\/ Destroy texture object.\n virtual void destroy_texture(ResourceName name) = 0;\n \/\/ Bind texture object.\n virtual void bind_texture(ResourceName name, TextureTarget target, int unit) = 0;\n \/\/ Update texture storage for 2-dimensional texture.\n virtual void update_texture_storage(\n TextureFormat internal_format,\n PixelFormat source_format,\n Resolution size,\n std::vector<unsigned char> const & data) = 0;\n \/\/ Update texture storage for texture cube face.\n virtual void update_texture_storage(\n TextureFormat internal_format,\n PixelFormat source_format,\n Resolution size,\n std::vector<unsigned char> const & data,\n CubeFace face) = 0;\n \/\/ Update texture parameters.\n virtual void update_texture_parameters(Texture const & texture) = 0;\n\n \/\/ Create new framebuffer object.\n virtual ResourceName create_framebuffer() = 0;\n \/\/ Destroy framebuffer object.\n virtual void destroy_framebuffer(ResourceName name) = 0;\n \/\/ Bind framebuffer object.\n virtual void bind_framebuffer(ResourceName name) = 0;\n \/\/ Attach a texture\/renderbuffer object to the currently bound framebuffer object.\n virtual void attach_to_framebuffer(ResourceName attachment, AttachmentType type, AttachmentPoint point) = 0;\n \/\/ Return array of status messages for currently bound framebuffer object.\n virtual std::vector<std::string> check_framebuffer_status() const = 0;\n\n \/\/ Return array of error messages (if any).\n virtual std::vector<std::string> get_errors() const = 0;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXMLPDataReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLPDataReader.h\"\n\n#include \"vtkDataArraySelection.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkXMLDataElement.h\"\n#include \"vtkXMLDataReader.h\"\n\nvtkCxxRevisionMacro(vtkXMLPDataReader, \"1.1\");\n\n\/\/----------------------------------------------------------------------------\nvtkXMLPDataReader::vtkXMLPDataReader()\n{\n this->GhostLevel = 0;\n \n this->NumberOfPieces = 0;\n \n this->PieceElements = 0;\n this->PieceReaders = 0;\n this->CanReadPieceFlag = 0;\n \n this->PathName = 0; \n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLPDataReader::~vtkXMLPDataReader()\n{\n if(this->NumberOfPieces) { this->DestroyPieces(); } \n if(this->PathName) { delete [] this->PathName; }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"NumberOfPieces: \" << this->NumberOfPieces << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataSet* vtkXMLPDataReader::GetPieceInputAsDataSet(int piece)\n{\n vtkXMLDataReader* reader = this->PieceReaders[piece];\n if(!reader) { return 0; }\n if(reader->GetNumberOfOutputs() < 1) { return 0; }\n return static_cast<vtkDataSet*>(reader->GetOutputs()[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupOutputInformation()\n{\n this->Superclass::SetupOutputInformation();\n int i;\n \n \/\/ Setup the output arrays.\n vtkXMLDataElement* ePointData = this->PPointDataElement;\n vtkXMLDataElement* eCellData = this->PCellDataElement;\n vtkPointData* pointData = this->GetOutputAsDataSet()->GetPointData();\n vtkCellData* cellData = this->GetOutputAsDataSet()->GetCellData(); \n \n \/\/ Setup the point and cell data arrays without allocation.\n this->SetDataArraySelections(ePointData, this->PointDataArraySelection);\n if(ePointData)\n {\n for(i=0;i < ePointData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = ePointData->GetNestedElement(i);\n if(this->PointDataArrayIsEnabled(eNested))\n {\n vtkDataArray* array = this->CreateDataArray(eNested);\n pointData->AddArray(array);\n array->Delete();\n }\n }\n }\n this->SetDataArraySelections(eCellData, this->CellDataArraySelection);\n if(eCellData)\n {\n for(i=0;i < eCellData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = eCellData->GetNestedElement(i);\n if(this->CellDataArrayIsEnabled(eNested))\n {\n vtkDataArray* array = this->CreateDataArray(eNested);\n cellData->AddArray(array);\n array->Delete();\n }\n }\n }\n \n \/\/ Setup attribute indices for the point data and cell data.\n this->ReadAttributeIndices(ePointData, pointData);\n this->ReadAttributeIndices(eCellData, cellData);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupOutputData()\n{\n this->Superclass::SetupOutputData();\n \n vtkDataSet* output = this->GetOutputAsDataSet();\n vtkXMLDataElement* ePointData = this->PPointDataElement;\n vtkXMLDataElement* eCellData = this->PCellDataElement;\n vtkPointData* pointData = output->GetPointData();\n vtkCellData* cellData = output->GetCellData();\n \n \/\/ Get the size of the output arrays.\n unsigned long pointTuples = this->GetNumberOfPoints();\n unsigned long cellTuples = this->GetNumberOfCells(); \n \n \/\/ Allocate data in the arrays.\n int i;\n if(ePointData)\n {\n int a=0;\n for(i=0;i < ePointData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = ePointData->GetNestedElement(i);\n if(this->PointDataArrayIsEnabled(eNested))\n {\n pointData->GetArray(a++)->SetNumberOfTuples(pointTuples);\n }\n }\n }\n if(eCellData)\n {\n int a=0;\n for(i=0;i < eCellData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = eCellData->GetNestedElement(i);\n if(this->CellDataArrayIsEnabled(eNested))\n {\n cellData->GetArray(a++)->SetNumberOfTuples(cellTuples);\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::ReadXMLInformation()\n{\n \/\/ First setup the filename components.\n this->SplitFileName();\n \n \/\/ Now proceed with reading the information.\n this->Superclass::ReadXMLInformation();\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPrimaryElement(vtkXMLDataElement* ePrimary)\n{\n if(!this->Superclass::ReadPrimaryElement(ePrimary)) { return 0; }\n \/\/ Read information about the data.\n if(!ePrimary->GetScalarAttribute(\"GhostLevel\", this->GhostLevel))\n {\n this->GhostLevel = 0;\n }\n \n \/\/ Read information about the pieces.\n this->PPointDataElement = 0;\n this->PCellDataElement = 0;\n int i;\n int numNested = ePrimary->GetNumberOfNestedElements();\n int numPieces = 0;\n for(i=0;i < numNested; ++i)\n {\n vtkXMLDataElement* eNested = ePrimary->GetNestedElement(i);\n if(strcmp(eNested->GetName(), \"Piece\") == 0) { ++numPieces; }\n else if(strcmp(eNested->GetName(), \"PPointData\") == 0)\n {\n this->PPointDataElement = eNested;\n }\n else if(strcmp(eNested->GetName(), \"PCellData\") == 0)\n {\n this->PCellDataElement = eNested;\n }\n }\n this->SetupPieces(numPieces);\n int piece = 0;\n for(i=0;i < numNested; ++i)\n {\n vtkXMLDataElement* eNested = ePrimary->GetNestedElement(i);\n if(strcmp(eNested->GetName(), \"Piece\") == 0)\n {\n if(!this->ReadPiece(eNested, piece++)) { return 0; }\n }\n }\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupPieces(int numPieces)\n{\n if(this->NumberOfPieces) { this->DestroyPieces(); }\n this->NumberOfPieces = numPieces;\n this->PieceElements = new vtkXMLDataElement*[this->NumberOfPieces];\n this->PieceReaders = new vtkXMLDataReader*[this->NumberOfPieces];\n this->CanReadPieceFlag = new int[this->NumberOfPieces];\n int i;\n for(i=0;i < this->NumberOfPieces;++i)\n {\n this->PieceElements[i] = 0;\n this->PieceReaders[i] = 0;\n this->CanReadPieceFlag[i] = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::DestroyPieces()\n{\n int i;\n for(i=0;i < this->NumberOfPieces;++i)\n {\n if(this->PieceReaders[i]) { this->PieceReaders[i]->Delete(); }\n }\n delete [] this->PieceElements;\n delete [] this->CanReadPieceFlag;\n delete [] this->PieceReaders;\n this->PieceElements = 0;\n this->PieceReaders = 0;\n this->NumberOfPieces = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPiece(vtkXMLDataElement* ePiece, int index)\n{\n this->Piece = index;\n return this->ReadPiece(ePiece);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPiece(vtkXMLDataElement* ePiece)\n{\n this->PieceElements[this->Piece] = ePiece;\n \n const char* fileName = ePiece->GetAttribute(\"Source\");\n if(!fileName)\n {\n vtkErrorMacro(\"Piece \" << this->Piece << \" has no Source attribute.\");\n return 0;\n }\n \n \/\/ The file name is relative to the summary file. Convert it to\n \/\/ something we can use.\n char *pieceFileName = this->CreatePieceFileName(fileName);\n \n vtkXMLDataReader* reader = this->CreatePieceReader();\n this->PieceReaders[this->Piece] = reader;\n reader->SetFileName(pieceFileName);\n \n delete [] pieceFileName;\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPieceData(int index)\n{\n this->Piece = index;\n \n \/\/ We need data, make sure the piece can be read.\n if(!this->CanReadPiece(this->Piece))\n {\n vtkErrorMacro(\"File for piece \" << this->Piece << \" cannot be read.\");\n return 0;\n }\n \n \/\/ Actually read the data.\n vtkDataArraySelection* pds =\n this->PieceReaders[this->Piece]->GetPointDataArraySelection();\n vtkDataArraySelection* cds =\n this->PieceReaders[this->Piece]->GetCellDataArraySelection();\n pds->CopySelections(this->PointDataArraySelection);\n cds->CopySelections(this->CellDataArraySelection);\n return this->ReadPieceData();\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPieceData()\n{\n vtkDataSet* input = this->GetPieceInputAsDataSet(this->Piece);\n vtkDataSet* output = this->GetOutputAsDataSet();\n \/\/vtkXMLDataElement* ePointData = this->PPointDataElement;\n \/\/vtkXMLDataElement* eCellData = this->PCellDataElement;\n \n \/\/ Copy point data and cell data for this piece.\n int a=0;\n int i;\n for(i=0;i < output->GetPointData()->GetNumberOfArrays();++i)\n {\n \n this->CopyArrayForPoints(input->GetPointData()->GetArray(i),\n output->GetPointData()->GetArray(i));\n }\n a=0;\n for(i=0;i < output->GetCellData()->GetNumberOfArrays();++i)\n {\n this->CopyArrayForCells(input->GetCellData()->GetArray(i),\n output->GetCellData()->GetArray(i));\n }\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::CanReadPiece(int index)\n{\n \/\/ If necessary, test whether the piece can be read.\n vtkXMLDataReader* reader = this->PieceReaders[index];\n if(reader && !this->CanReadPieceFlag[index])\n {\n if(reader->CanReadFile(reader->GetFileName()))\n {\n \/\/ We can read the piece. Save result to avoid later repeat of\n \/\/ test.\n this->CanReadPieceFlag[index] = 1;\n }\n else\n {\n \/\/ We cannot read the piece. Destroy the reader to avoid later\n \/\/ repeat of test.\n this->PieceReaders[index] = 0;\n reader->Delete();\n }\n }\n \n return (this->PieceReaders[index]? 1:0);\n}\n\n\/\/----------------------------------------------------------------------------\nchar* vtkXMLPDataReader::CreatePieceFileName(const char* fileName)\n{\n ostrstream fn;\n if(this->PathName) { fn << this->PathName; }\n fn << fileName << ends;\n return fn.str();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SplitFileName()\n{\n \/\/ Pull the PathName component out of the FileName.\n size_t length = strlen(this->FileName);\n char* fileName = new char[length+1];\n strcpy(fileName, this->FileName);\n char* begin = fileName;\n char* end = fileName + length;\n char* s;\n \n#if defined(_WIN32)\n \/\/ Convert to UNIX-style slashes.\n for(s=begin;s != end;++s) { if(*s == '\\\\') { *s = '\/'; } }\n#endif\n \n \/\/ Extract the path name up to the last '\/'.\n if(this->PathName) { delete [] this->PathName; this->PathName = 0; }\n char* rbegin = end-1;\n char* rend = begin-1;\n for(s=rbegin;s != rend;--s) { if(*s == '\/') { break; } }\n if(s >= begin)\n {\n length = (s-begin)+1;\n this->PathName = new char[length+1];\n strncpy(this->PathName, this->FileName, length);\n this->PathName[length] = '\\0';\n begin = s+1;\n }\n \n \/\/ Cleanup temporary name.\n delete [] fileName;\n}\n<commit_msg>ERR: Removed unused variable.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXMLPDataReader.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLPDataReader.h\"\n\n#include \"vtkDataArraySelection.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkXMLDataElement.h\"\n#include \"vtkXMLDataReader.h\"\n\nvtkCxxRevisionMacro(vtkXMLPDataReader, \"1.2\");\n\n\/\/----------------------------------------------------------------------------\nvtkXMLPDataReader::vtkXMLPDataReader()\n{\n this->GhostLevel = 0;\n \n this->NumberOfPieces = 0;\n \n this->PieceElements = 0;\n this->PieceReaders = 0;\n this->CanReadPieceFlag = 0;\n \n this->PathName = 0; \n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLPDataReader::~vtkXMLPDataReader()\n{\n if(this->NumberOfPieces) { this->DestroyPieces(); } \n if(this->PathName) { delete [] this->PathName; }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"NumberOfPieces: \" << this->NumberOfPieces << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nvtkDataSet* vtkXMLPDataReader::GetPieceInputAsDataSet(int piece)\n{\n vtkXMLDataReader* reader = this->PieceReaders[piece];\n if(!reader) { return 0; }\n if(reader->GetNumberOfOutputs() < 1) { return 0; }\n return static_cast<vtkDataSet*>(reader->GetOutputs()[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupOutputInformation()\n{\n this->Superclass::SetupOutputInformation();\n int i;\n \n \/\/ Setup the output arrays.\n vtkXMLDataElement* ePointData = this->PPointDataElement;\n vtkXMLDataElement* eCellData = this->PCellDataElement;\n vtkPointData* pointData = this->GetOutputAsDataSet()->GetPointData();\n vtkCellData* cellData = this->GetOutputAsDataSet()->GetCellData(); \n \n \/\/ Setup the point and cell data arrays without allocation.\n this->SetDataArraySelections(ePointData, this->PointDataArraySelection);\n if(ePointData)\n {\n for(i=0;i < ePointData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = ePointData->GetNestedElement(i);\n if(this->PointDataArrayIsEnabled(eNested))\n {\n vtkDataArray* array = this->CreateDataArray(eNested);\n pointData->AddArray(array);\n array->Delete();\n }\n }\n }\n this->SetDataArraySelections(eCellData, this->CellDataArraySelection);\n if(eCellData)\n {\n for(i=0;i < eCellData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = eCellData->GetNestedElement(i);\n if(this->CellDataArrayIsEnabled(eNested))\n {\n vtkDataArray* array = this->CreateDataArray(eNested);\n cellData->AddArray(array);\n array->Delete();\n }\n }\n }\n \n \/\/ Setup attribute indices for the point data and cell data.\n this->ReadAttributeIndices(ePointData, pointData);\n this->ReadAttributeIndices(eCellData, cellData);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupOutputData()\n{\n this->Superclass::SetupOutputData();\n \n vtkDataSet* output = this->GetOutputAsDataSet();\n vtkXMLDataElement* ePointData = this->PPointDataElement;\n vtkXMLDataElement* eCellData = this->PCellDataElement;\n vtkPointData* pointData = output->GetPointData();\n vtkCellData* cellData = output->GetCellData();\n \n \/\/ Get the size of the output arrays.\n unsigned long pointTuples = this->GetNumberOfPoints();\n unsigned long cellTuples = this->GetNumberOfCells(); \n \n \/\/ Allocate data in the arrays.\n int i;\n if(ePointData)\n {\n int a=0;\n for(i=0;i < ePointData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = ePointData->GetNestedElement(i);\n if(this->PointDataArrayIsEnabled(eNested))\n {\n pointData->GetArray(a++)->SetNumberOfTuples(pointTuples);\n }\n }\n }\n if(eCellData)\n {\n int a=0;\n for(i=0;i < eCellData->GetNumberOfNestedElements();++i)\n {\n vtkXMLDataElement* eNested = eCellData->GetNestedElement(i);\n if(this->CellDataArrayIsEnabled(eNested))\n {\n cellData->GetArray(a++)->SetNumberOfTuples(cellTuples);\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::ReadXMLInformation()\n{\n \/\/ First setup the filename components.\n this->SplitFileName();\n \n \/\/ Now proceed with reading the information.\n this->Superclass::ReadXMLInformation();\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPrimaryElement(vtkXMLDataElement* ePrimary)\n{\n if(!this->Superclass::ReadPrimaryElement(ePrimary)) { return 0; }\n \/\/ Read information about the data.\n if(!ePrimary->GetScalarAttribute(\"GhostLevel\", this->GhostLevel))\n {\n this->GhostLevel = 0;\n }\n \n \/\/ Read information about the pieces.\n this->PPointDataElement = 0;\n this->PCellDataElement = 0;\n int i;\n int numNested = ePrimary->GetNumberOfNestedElements();\n int numPieces = 0;\n for(i=0;i < numNested; ++i)\n {\n vtkXMLDataElement* eNested = ePrimary->GetNestedElement(i);\n if(strcmp(eNested->GetName(), \"Piece\") == 0) { ++numPieces; }\n else if(strcmp(eNested->GetName(), \"PPointData\") == 0)\n {\n this->PPointDataElement = eNested;\n }\n else if(strcmp(eNested->GetName(), \"PCellData\") == 0)\n {\n this->PCellDataElement = eNested;\n }\n }\n this->SetupPieces(numPieces);\n int piece = 0;\n for(i=0;i < numNested; ++i)\n {\n vtkXMLDataElement* eNested = ePrimary->GetNestedElement(i);\n if(strcmp(eNested->GetName(), \"Piece\") == 0)\n {\n if(!this->ReadPiece(eNested, piece++)) { return 0; }\n }\n }\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SetupPieces(int numPieces)\n{\n if(this->NumberOfPieces) { this->DestroyPieces(); }\n this->NumberOfPieces = numPieces;\n this->PieceElements = new vtkXMLDataElement*[this->NumberOfPieces];\n this->PieceReaders = new vtkXMLDataReader*[this->NumberOfPieces];\n this->CanReadPieceFlag = new int[this->NumberOfPieces];\n int i;\n for(i=0;i < this->NumberOfPieces;++i)\n {\n this->PieceElements[i] = 0;\n this->PieceReaders[i] = 0;\n this->CanReadPieceFlag[i] = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::DestroyPieces()\n{\n int i;\n for(i=0;i < this->NumberOfPieces;++i)\n {\n if(this->PieceReaders[i]) { this->PieceReaders[i]->Delete(); }\n }\n delete [] this->PieceElements;\n delete [] this->CanReadPieceFlag;\n delete [] this->PieceReaders;\n this->PieceElements = 0;\n this->PieceReaders = 0;\n this->NumberOfPieces = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPiece(vtkXMLDataElement* ePiece, int index)\n{\n this->Piece = index;\n return this->ReadPiece(ePiece);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPiece(vtkXMLDataElement* ePiece)\n{\n this->PieceElements[this->Piece] = ePiece;\n \n const char* fileName = ePiece->GetAttribute(\"Source\");\n if(!fileName)\n {\n vtkErrorMacro(\"Piece \" << this->Piece << \" has no Source attribute.\");\n return 0;\n }\n \n \/\/ The file name is relative to the summary file. Convert it to\n \/\/ something we can use.\n char *pieceFileName = this->CreatePieceFileName(fileName);\n \n vtkXMLDataReader* reader = this->CreatePieceReader();\n this->PieceReaders[this->Piece] = reader;\n reader->SetFileName(pieceFileName);\n \n delete [] pieceFileName;\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPieceData(int index)\n{\n this->Piece = index;\n \n \/\/ We need data, make sure the piece can be read.\n if(!this->CanReadPiece(this->Piece))\n {\n vtkErrorMacro(\"File for piece \" << this->Piece << \" cannot be read.\");\n return 0;\n }\n \n \/\/ Actually read the data.\n vtkDataArraySelection* pds =\n this->PieceReaders[this->Piece]->GetPointDataArraySelection();\n vtkDataArraySelection* cds =\n this->PieceReaders[this->Piece]->GetCellDataArraySelection();\n pds->CopySelections(this->PointDataArraySelection);\n cds->CopySelections(this->CellDataArraySelection);\n return this->ReadPieceData();\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::ReadPieceData()\n{\n vtkDataSet* input = this->GetPieceInputAsDataSet(this->Piece);\n vtkDataSet* output = this->GetOutputAsDataSet();\n \/\/vtkXMLDataElement* ePointData = this->PPointDataElement;\n \/\/vtkXMLDataElement* eCellData = this->PCellDataElement;\n \n \/\/ Copy point data and cell data for this piece.\n int i;\n for(i=0;i < output->GetPointData()->GetNumberOfArrays();++i)\n {\n \n this->CopyArrayForPoints(input->GetPointData()->GetArray(i),\n output->GetPointData()->GetArray(i));\n }\n for(i=0;i < output->GetCellData()->GetNumberOfArrays();++i)\n {\n this->CopyArrayForCells(input->GetCellData()->GetArray(i),\n output->GetCellData()->GetArray(i));\n }\n \n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLPDataReader::CanReadPiece(int index)\n{\n \/\/ If necessary, test whether the piece can be read.\n vtkXMLDataReader* reader = this->PieceReaders[index];\n if(reader && !this->CanReadPieceFlag[index])\n {\n if(reader->CanReadFile(reader->GetFileName()))\n {\n \/\/ We can read the piece. Save result to avoid later repeat of\n \/\/ test.\n this->CanReadPieceFlag[index] = 1;\n }\n else\n {\n \/\/ We cannot read the piece. Destroy the reader to avoid later\n \/\/ repeat of test.\n this->PieceReaders[index] = 0;\n reader->Delete();\n }\n }\n \n return (this->PieceReaders[index]? 1:0);\n}\n\n\/\/----------------------------------------------------------------------------\nchar* vtkXMLPDataReader::CreatePieceFileName(const char* fileName)\n{\n ostrstream fn;\n if(this->PathName) { fn << this->PathName; }\n fn << fileName << ends;\n return fn.str();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLPDataReader::SplitFileName()\n{\n \/\/ Pull the PathName component out of the FileName.\n size_t length = strlen(this->FileName);\n char* fileName = new char[length+1];\n strcpy(fileName, this->FileName);\n char* begin = fileName;\n char* end = fileName + length;\n char* s;\n \n#if defined(_WIN32)\n \/\/ Convert to UNIX-style slashes.\n for(s=begin;s != end;++s) { if(*s == '\\\\') { *s = '\/'; } }\n#endif\n \n \/\/ Extract the path name up to the last '\/'.\n if(this->PathName) { delete [] this->PathName; this->PathName = 0; }\n char* rbegin = end-1;\n char* rend = begin-1;\n for(s=rbegin;s != rend;--s) { if(*s == '\/') { break; } }\n if(s >= begin)\n {\n length = (s-begin)+1;\n this->PathName = new char[length+1];\n strncpy(this->PathName, this->FileName, length);\n this->PathName[length] = '\\0';\n begin = s+1;\n }\n \n \/\/ Cleanup temporary name.\n delete [] fileName;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <ArrayInfo.hpp>\n#include <Array.hpp>\n#include <histogram.hpp>\n\nusing af::dim4;\n\nnamespace cpu\n{\n\ntemplate<typename inType, typename outType>\nArray<outType> histogram(const Array<inType> &in, const unsigned &nbins, const double &minval, const double &maxval)\n{\n float step = (maxval - minval)\/(float)nbins;\n\n const dim4 inDims = in.dims();\n dim4 iStrides = in.strides();\n dim4 outDims = dim4(nbins,1,inDims[2],inDims[3]);\n Array<outType> out = createValueArray<outType>(outDims, outType(0));\n dim4 oStrides = out.strides();\n dim_type nElems = inDims[0]*inDims[1];\n\n outType *outData = out.get();\n const inType* inData= in.get();\n\n for(dim_type b3 = 0; b3 < outDims[2]; b3++) {\n for(dim_type b2 = 0; b2 < outDims[2]; b2++) {\n for(dim_type i=0; i<nElems; i++) {\n int bin = (int)((inData[i] - minval) \/ step);\n bin = std::max(bin, 0);\n bin = std::min(bin, (int)(nbins - 1));\n outData[bin]++;\n }\n inData += iStrides[2];\n outData += oStrides[2];\n }\n inData += iStrides[3];\n outData += oStrides[3];\n }\n\n return out;\n}\n\n#define INSTANTIATE(in_t,out_t)\\\ntemplate Array<out_t> histogram(const Array<in_t> &in, const unsigned &nbins, const double &minval, const double &maxval);\n\nINSTANTIATE(float , uint)\nINSTANTIATE(double, uint)\nINSTANTIATE(char , uint)\nINSTANTIATE(int , uint)\nINSTANTIATE(uint , uint)\nINSTANTIATE(uchar , uint)\n\n}\n<commit_msg>BUGFIX fixed 3rd dimension index in cpu histogram implementation<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <ArrayInfo.hpp>\n#include <Array.hpp>\n#include <histogram.hpp>\n\nusing af::dim4;\n\nnamespace cpu\n{\n\ntemplate<typename inType, typename outType>\nArray<outType> histogram(const Array<inType> &in, const unsigned &nbins, const double &minval, const double &maxval)\n{\n float step = (maxval - minval)\/(float)nbins;\n\n const dim4 inDims = in.dims();\n dim4 iStrides = in.strides();\n dim4 outDims = dim4(nbins,1,inDims[2],inDims[3]);\n Array<outType> out = createValueArray<outType>(outDims, outType(0));\n dim4 oStrides = out.strides();\n dim_type nElems = inDims[0]*inDims[1];\n\n outType *outData = out.get();\n const inType* inData= in.get();\n\n for(dim_type b3 = 0; b3 < outDims[3]; b3++) {\n for(dim_type b2 = 0; b2 < outDims[2]; b2++) {\n for(dim_type i=0; i<nElems; i++) {\n int bin = (int)((inData[i] - minval) \/ step);\n bin = std::max(bin, 0);\n bin = std::min(bin, (int)(nbins - 1));\n outData[bin]++;\n }\n inData += iStrides[2];\n outData += oStrides[2];\n }\n inData += iStrides[3];\n outData += oStrides[3];\n }\n\n return out;\n}\n\n#define INSTANTIATE(in_t,out_t)\\\ntemplate Array<out_t> histogram(const Array<in_t> &in, const unsigned &nbins, const double &minval, const double &maxval);\n\nINSTANTIATE(float , uint)\nINSTANTIATE(double, uint)\nINSTANTIATE(char , uint)\nINSTANTIATE(int , uint)\nINSTANTIATE(uint , uint)\nINSTANTIATE(uchar , uint)\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n Copyright (C) 1999 - 2004, 2006 Simon Peter, <dn.tlp@gmx.net>, et al.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n dmo.cpp - TwinTeam loader by Riven the Mage <riven@ok.ru>\n*\/\n\/*\n NOTES:\n Panning is ignored.\n\n A WORD ist 16 bits, a DWORD is 32 bits and a BYTE is 8 bits in this context.\n*\/\n\n#include <string.h>\n#include <binstr.h>\n\n#include \"dmo.h\"\n#include \"debug.h\"\n\n#define ARRAY_AS_DWORD(a, i) \\\n((a[i + 3] << 24) + (a[i + 2] << 16) + (a[i + 1] << 8) + a[i])\n#define ARRAY_AS_WORD(a, i)\t((a[i + 1] << 8) + a[i])\n\n\/* -------- Public Methods -------------------------------- *\/\n\nCPlayer *CdmoLoader::factory(Copl *newopl)\n{\n return new CdmoLoader(newopl);\n}\n\nbool CdmoLoader::load(const std::string &filename, const CFileProvider &fp)\n{\n int i, j;\n\n binistream *f = fp.open(filename);\n if (!f) return false;\n\n \/\/ check header\n dmo_unpacker unpacker;\n unsigned char chkhdr[16];\n\n f->readString((char *)chkhdr, 16);\n\n if (!unpacker.decrypt(chkhdr, 16))\n {\n fp.close(f);\n return false;\n }\n\n \/\/ get file size\n long packed_length = fp.filesize(f);\n f->seek(0);\n\n unsigned char *packed_module = new unsigned char [packed_length];\n\n \/\/ load file\n f->readString((char *)packed_module, packed_length);\n fp.close(f);\n\n \/\/ decrypt\n unpacker.decrypt(packed_module, packed_length);\n\n long unpacked_length = 0x2000 * ARRAY_AS_WORD(packed_module, 12);\n unsigned char *module = new unsigned char [unpacked_length];\n\n \/\/ unpack\n if (!unpacker.unpack(packed_module, packed_length, module, unpacked_length))\n {\n delete [] packed_module;\n delete [] module;\n return false;\n }\n\n delete [] packed_module;\n\n \/\/ \"TwinTeam\" - signed ?\n if (memcmp(module,\"TwinTeam Module File\"\"\\x0D\\x0A\",22))\n {\n delete [] module;\n return false;\n }\n\n \/\/ load header\n binisstream\tuf(module, unpacked_length);\n uf.setFlag(binio::BigEndian, false); uf.setFlag(binio::FloatIEEE);\n\n memset(&header,0,sizeof(s3mheader));\n\n uf.ignore(22);\t\t\t\t\/\/ ignore DMO header ID string\n uf.readString(header.name, 28);\n\n uf.ignore(2);\t\t\t\t\/\/ _unk_1\n header.ordnum = uf.readInt(2);\n header.insnum = uf.readInt(2);\n header.patnum = uf.readInt(2);\n uf.ignore(2);\t\t\t\t\/\/ _unk_2\n header.is = uf.readInt(2);\n header.it = uf.readInt(2);\n\n memset(header.chanset,0xFF,32);\n\n for (i=0;i<9;i++)\n header.chanset[i] = 0x10 + i;\n\n uf.ignore(32);\t\t\t\t\/\/ ignore panning settings for all 32 channels\n\n \/\/ load orders\n for(i = 0; i < 256; i++) orders[i] = uf.readInt(1);\n\n orders[header.ordnum] = 0xFF;\n\n \/\/ load pattern lengths\n unsigned short my_patlen[100];\n for(i = 0; i < 100; i++) my_patlen[i] = uf.readInt(2);\n\n \/\/ load instruments\n for (i = 0; i < header.insnum; i++)\n {\n memset(&inst[i],0,sizeof(s3minst));\n\n uf.readString(inst[i].name, 28);\n\n inst[i].volume = uf.readInt(1);\n inst[i].dsk = uf.readInt(1);\n inst[i].c2spd = uf.readInt(4);\n inst[i].type = uf.readInt(1);\n inst[i].d00 = uf.readInt(1);\n inst[i].d01 = uf.readInt(1);\n inst[i].d02 = uf.readInt(1);\n inst[i].d03 = uf.readInt(1);\n inst[i].d04 = uf.readInt(1);\n inst[i].d05 = uf.readInt(1);\n inst[i].d06 = uf.readInt(1);\n inst[i].d07 = uf.readInt(1);\n inst[i].d08 = uf.readInt(1);\n inst[i].d09 = uf.readInt(1);\n inst[i].d0a = uf.readInt(1);\n \/*\n * Originally, riven sets d0b = d0a and ignores 1 byte in the\n * stream, but i guess this was a typo, so i read it here.\n *\/\n inst[i].d0b = uf.readInt(1);\n }\n\n \/\/ load patterns\n for (i = 0; i < header.patnum; i++) {\n long cur_pos = uf.pos();\n\n for (j = 0; j < 64; j++) {\n while (1) {\n\tunsigned char token = uf.readInt(1);\n\n\tif (!token)\n\t break;\n\n\tunsigned char chan = token & 31;\n\n\t\/\/ note + instrument ?\n\tif (token & 32) {\n\t unsigned char bufbyte = uf.readInt(1);\n\n\t pattern[i][j][chan].note = bufbyte & 15;\n\t pattern[i][j][chan].oct = bufbyte >> 4;\n\t pattern[i][j][chan].instrument = uf.readInt(1);\n\t}\n\n\t\/\/ volume ?\n\tif (token & 64)\n\t pattern[i][j][chan].volume = uf.readInt(1);\n\n\t\/\/ command ?\n\tif (token & 128) {\n\t pattern[i][j][chan].command = uf.readInt(1);\n\t pattern[i][j][chan].info = uf.readInt(1);\n\t}\n }\n }\n\n uf.seek(cur_pos + my_patlen[i]);\n }\n\n delete [] module;\n rewind(0);\n return true;\n}\n\nstd::string CdmoLoader::gettype()\n{\n return std::string(\"TwinTeam (packed S3M)\");\n}\n\nstd::string CdmoLoader::getauthor()\n{\n \/*\n All available .DMO modules written by one composer. And because all .DMO\n stuff was lost due to hd crash (TwinTeam guys said this), there are\n never(?) be another.\n *\/\n return std::string(\"Benjamin GERARDIN\");\n}\n\n\/* -------- Private Methods ------------------------------- *\/\n\nunsigned short CdmoLoader::dmo_unpacker::brand(unsigned short range)\n{\n bseed *= 0x08088405U;\n bseed++;\n\n return (uint64_t)bseed * range >> 32;\n}\n\nbool CdmoLoader::dmo_unpacker::decrypt(unsigned char *buf, size_t len)\n{\n if (len < headersize)\n return false;\n\n bseed = ARRAY_AS_DWORD(buf, 0);\n\n uint32_t seed = 0;\n for (int i = 0; i <= ARRAY_AS_WORD(buf, 4); i++)\n seed += brand(0xffff);\n\n bseed = seed ^ ARRAY_AS_DWORD(buf, 6);\n\n if (ARRAY_AS_WORD(buf, 10) != brand(0xffff))\n return false;\n\n for (size_t i = headersize; i < len; i++)\n buf[i] ^= brand(0x100);\n\n buf[len - 2] = buf[len - 1] = 0;\n\n return true;\n}\n\nlong CdmoLoader::dmo_unpacker::unpack_block(unsigned char *ibuf, size_t ilen,\n\t\t\t\t\t unsigned char *obuf, size_t olen)\n{\n size_t ipos = 0, opos = 0;\n\n \/\/ LZ77 child\n while (ipos < ilen) {\n size_t cpy = 0, ofs = 0, lit = 0;\n unsigned char code, par1, par2;\n\n code = ibuf[ipos++];\n par1 = ipos < ilen ? ibuf[ipos] : 0;\n par2 = ipos + 1 < ilen ? ibuf[ipos + 1] : 0;\n switch (code >> 6) {\n case 0:\n \/\/ 00xxxxxx: use (X + 1) literal bytes\n lit = (code & 0x3F) + 1;\n break;\n\n case 1:\n \/\/ 01xxxxxx xxxyyyyy: copy (Y + 3) bytes from offset (X + 1)\n ipos++; \/\/ for par1\n ofs = ((code & 0x3F) << 3) + ((par1 & 0xE0) >> 5) + 1;\n cpy = (par1 & 0x1F) + 3;\n break;\n\n case 2:\n \/\/ 10xxxxxx xyyyzzzz: copy (Y + 3) bytes from offset(X + 1);\n \/\/ use Z literal bytes\n ipos++; \/\/ for par1\n ofs = ((code & 0x3F) << 1) + (par1 >> 7) + 1;\n cpy = ((par1 & 0x70) >> 4) + 3;\n lit = par1 & 0x0F;\n break;\n\n case 3:\n \/\/ 11xxxxxx xxxxxxxy yyyyzzzz: copy (Y + 4) from offset X;\n \/\/ use Z literal bytes\n ipos += 2; \/\/ for par1 and par2\n ofs = ((code & 0x3F) << 7) + (par1 >> 1);\n cpy = ((par1 & 0x01) << 4) + (par2 >> 4) + 4;\n lit = par2 & 0x0F;\n break;\n }\n\n \/\/ check lengths and offset\n if (ipos + lit > ilen || opos + cpy + lit > olen || ofs > opos)\n return -1;\n\n \/\/ copy - can't use memcpy() because source and destination may overlap\n for (size_t i = 0; i < cpy; i++)\n obuf[opos + i] = obuf[opos - ofs + i];\n opos += cpy;\n\n \/\/ copy literal bytes\n while (lit--)\n obuf[opos++] = ibuf[ipos++];\n }\n\n return opos;\n}\n\nsize_t CdmoLoader::dmo_unpacker::unpack(unsigned char *ibuf, size_t inputsize,\n\t\t\t\t\tunsigned char *obuf, size_t outputsize)\n{\n if (inputsize < headersize + 2)\n return 0;\n\n unsigned short block_count = ARRAY_AS_WORD(ibuf, headersize);\n unsigned block_start = headersize + 2 + 2 * block_count;\n\n if (inputsize < block_start)\n return 0;\n\n unsigned char *block_length = &ibuf[headersize + 2];\n ibuf += block_start;\n inputsize -= block_start;\n\n size_t olen = 0;\n for (int i = 0; i < block_count; i++) {\n unsigned short blen = ARRAY_AS_WORD(block_length, 2 * i);\n if (blen < 2 || blen > inputsize)\n return 0;\n\n unsigned short bul = ARRAY_AS_WORD(ibuf, 0);\n\n if (unpack_block(ibuf + 2, blen - 2, obuf, outputsize - olen) != bul)\n return 0;\n\n obuf += bul;\n olen += bul;\n\n ibuf += blen;\n inputsize -= blen;\n }\n\n return olen;\n}\n<commit_msg>dmo.cpp: Avoid buffer overflows during load() and terminate strings<commit_after>\/*\n Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n Copyright (C) 1999 - 2004, 2006 Simon Peter, <dn.tlp@gmx.net>, et al.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n dmo.cpp - TwinTeam loader by Riven the Mage <riven@ok.ru>\n*\/\n\/*\n NOTES:\n Panning is ignored.\n\n A WORD ist 16 bits, a DWORD is 32 bits and a BYTE is 8 bits in this context.\n*\/\n\n#include <string.h>\n#include <binstr.h>\n\n#include \"dmo.h\"\n#include \"debug.h\"\n\n#define ARRAY_AS_DWORD(a, i) \\\n((a[i + 3] << 24) + (a[i + 2] << 16) + (a[i + 1] << 8) + a[i])\n#define ARRAY_AS_WORD(a, i)\t((a[i + 1] << 8) + a[i])\n\n\/* -------- Public Methods -------------------------------- *\/\n\nCPlayer *CdmoLoader::factory(Copl *newopl)\n{\n return new CdmoLoader(newopl);\n}\n\nbool CdmoLoader::load(const std::string &filename, const CFileProvider &fp)\n{\n int i, j;\n\n binistream *f = fp.open(filename);\n if (!f) return false;\n\n \/\/ check header\n dmo_unpacker unpacker;\n unsigned char chkhdr[16];\n\n f->readString((char *)chkhdr, 16);\n\n if (!unpacker.decrypt(chkhdr, 16))\n {\n fp.close(f);\n return false;\n }\n\n \/\/ get file size\n long packed_length = fp.filesize(f);\n f->seek(0);\n\n unsigned char *packed_module = new unsigned char [packed_length];\n\n \/\/ load file\n f->readString((char *)packed_module, packed_length);\n fp.close(f);\n\n \/\/ decrypt\n unpacker.decrypt(packed_module, packed_length);\n\n long unpacked_length = 0x2000 * ARRAY_AS_WORD(packed_module, 12);\n unsigned char *module = new unsigned char [unpacked_length];\n\n \/\/ unpack\n if (!unpacker.unpack(packed_module, packed_length, module, unpacked_length))\n {\n delete [] packed_module;\n delete [] module;\n return false;\n }\n\n delete [] packed_module;\n\n \/\/ \"TwinTeam\" - signed ?\n if (memcmp(module,\"TwinTeam Module File\"\"\\x0D\\x0A\",22))\n {\n delete [] module;\n return false;\n }\n\n \/\/ load header\n binisstream\tuf(module, unpacked_length);\n uf.setFlag(binio::BigEndian, false); uf.setFlag(binio::FloatIEEE);\n\n memset(&header,0,sizeof(s3mheader));\n\n uf.ignore(22);\t\t\t\t\/\/ ignore DMO header ID string\n uf.readString(header.name, 28);\n header.name[27] = 0;\t\t\t\t\/\/ ensure termination\n\n uf.ignore(2);\t\t\t\t\/\/ _unk_1\n header.ordnum = uf.readInt(2);\n header.insnum = uf.readInt(2);\n header.patnum = uf.readInt(2);\n uf.ignore(2);\t\t\t\t\/\/ _unk_2\n header.is = uf.readInt(2);\n header.it = uf.readInt(2);\n\n if (header.ordnum >= 256 || header.insnum > 99 || header.patnum > 99) {\n delete [] module;\n return false;\n }\n\n memset(header.chanset,0xFF,32);\n\n for (i=0;i<9;i++)\n header.chanset[i] = 0x10 + i;\n\n uf.ignore(32);\t\t\t\t\/\/ ignore panning settings for all 32 channels\n\n \/\/ load orders\n for(i = 0; i < 256; i++) orders[i] = uf.readInt(1);\n\n orders[header.ordnum] = 0xFF;\n\n \/\/ load pattern lengths\n unsigned short my_patlen[100];\n for(i = 0; i < 100; i++) my_patlen[i] = uf.readInt(2);\n\n \/\/ load instruments\n for (i = 0; i < header.insnum; i++)\n {\n memset(&inst[i],0,sizeof(s3minst));\n\n uf.readString(inst[i].name, 28);\n inst[i].name[27] = 0;\n\n inst[i].volume = uf.readInt(1);\n inst[i].dsk = uf.readInt(1);\n inst[i].c2spd = uf.readInt(4);\n inst[i].type = uf.readInt(1);\n inst[i].d00 = uf.readInt(1);\n inst[i].d01 = uf.readInt(1);\n inst[i].d02 = uf.readInt(1);\n inst[i].d03 = uf.readInt(1);\n inst[i].d04 = uf.readInt(1);\n inst[i].d05 = uf.readInt(1);\n inst[i].d06 = uf.readInt(1);\n inst[i].d07 = uf.readInt(1);\n inst[i].d08 = uf.readInt(1);\n inst[i].d09 = uf.readInt(1);\n inst[i].d0a = uf.readInt(1);\n \/*\n * Originally, riven sets d0b = d0a and ignores 1 byte in the\n * stream, but i guess this was a typo, so i read it here.\n *\/\n inst[i].d0b = uf.readInt(1);\n }\n\n \/\/ load patterns\n for (i = 0; i < header.patnum; i++) {\n long cur_pos = uf.pos();\n\n for (j = 0; j < 64; j++) {\n while (1) {\n\tunsigned char token = uf.readInt(1);\n\n\tif (!token)\n\t break;\n\n\tunsigned char chan = token & 31;\n\n\t\/\/ note + instrument ?\n\tif (token & 32) {\n\t unsigned char bufbyte = uf.readInt(1);\n\n\t pattern[i][j][chan].note = bufbyte & 15;\n\t pattern[i][j][chan].oct = bufbyte >> 4;\n\t pattern[i][j][chan].instrument = uf.readInt(1);\n\t}\n\n\t\/\/ volume ?\n\tif (token & 64)\n\t pattern[i][j][chan].volume = uf.readInt(1);\n\n\t\/\/ command ?\n\tif (token & 128) {\n\t pattern[i][j][chan].command = uf.readInt(1);\n\t pattern[i][j][chan].info = uf.readInt(1);\n\t}\n }\n }\n\n \/\/ TODO: sanitiy checking my_patlen[i] here might be a good idea\n uf.seek(cur_pos + my_patlen[i]);\n }\n\n delete [] module;\n rewind(0);\n return true;\n}\n\nstd::string CdmoLoader::gettype()\n{\n return std::string(\"TwinTeam (packed S3M)\");\n}\n\nstd::string CdmoLoader::getauthor()\n{\n \/*\n All available .DMO modules written by one composer. And because all .DMO\n stuff was lost due to hd crash (TwinTeam guys said this), there are\n never(?) be another.\n *\/\n return std::string(\"Benjamin GERARDIN\");\n}\n\n\/* -------- Private Methods ------------------------------- *\/\n\nunsigned short CdmoLoader::dmo_unpacker::brand(unsigned short range)\n{\n bseed *= 0x08088405U;\n bseed++;\n\n return (uint64_t)bseed * range >> 32;\n}\n\nbool CdmoLoader::dmo_unpacker::decrypt(unsigned char *buf, size_t len)\n{\n if (len < headersize)\n return false;\n\n bseed = ARRAY_AS_DWORD(buf, 0);\n\n uint32_t seed = 0;\n for (int i = 0; i <= ARRAY_AS_WORD(buf, 4); i++)\n seed += brand(0xffff);\n\n bseed = seed ^ ARRAY_AS_DWORD(buf, 6);\n\n if (ARRAY_AS_WORD(buf, 10) != brand(0xffff))\n return false;\n\n for (size_t i = headersize; i < len; i++)\n buf[i] ^= brand(0x100);\n\n buf[len - 2] = buf[len - 1] = 0;\n\n return true;\n}\n\nlong CdmoLoader::dmo_unpacker::unpack_block(unsigned char *ibuf, size_t ilen,\n\t\t\t\t\t unsigned char *obuf, size_t olen)\n{\n size_t ipos = 0, opos = 0;\n\n \/\/ LZ77 child\n while (ipos < ilen) {\n size_t cpy = 0, ofs = 0, lit = 0;\n unsigned char code, par1, par2;\n\n code = ibuf[ipos++];\n par1 = ipos < ilen ? ibuf[ipos] : 0;\n par2 = ipos + 1 < ilen ? ibuf[ipos + 1] : 0;\n switch (code >> 6) {\n case 0:\n \/\/ 00xxxxxx: use (X + 1) literal bytes\n lit = (code & 0x3F) + 1;\n break;\n\n case 1:\n \/\/ 01xxxxxx xxxyyyyy: copy (Y + 3) bytes from offset (X + 1)\n ipos++; \/\/ for par1\n ofs = ((code & 0x3F) << 3) + ((par1 & 0xE0) >> 5) + 1;\n cpy = (par1 & 0x1F) + 3;\n break;\n\n case 2:\n \/\/ 10xxxxxx xyyyzzzz: copy (Y + 3) bytes from offset(X + 1);\n \/\/ use Z literal bytes\n ipos++; \/\/ for par1\n ofs = ((code & 0x3F) << 1) + (par1 >> 7) + 1;\n cpy = ((par1 & 0x70) >> 4) + 3;\n lit = par1 & 0x0F;\n break;\n\n case 3:\n \/\/ 11xxxxxx xxxxxxxy yyyyzzzz: copy (Y + 4) from offset X;\n \/\/ use Z literal bytes\n ipos += 2; \/\/ for par1 and par2\n ofs = ((code & 0x3F) << 7) + (par1 >> 1);\n cpy = ((par1 & 0x01) << 4) + (par2 >> 4) + 4;\n lit = par2 & 0x0F;\n break;\n }\n\n \/\/ check lengths and offset\n if (ipos + lit > ilen || opos + cpy + lit > olen || ofs > opos)\n return -1;\n\n \/\/ copy - can't use memcpy() because source and destination may overlap\n for (size_t i = 0; i < cpy; i++)\n obuf[opos + i] = obuf[opos - ofs + i];\n opos += cpy;\n\n \/\/ copy literal bytes\n while (lit--)\n obuf[opos++] = ibuf[ipos++];\n }\n\n return opos;\n}\n\nsize_t CdmoLoader::dmo_unpacker::unpack(unsigned char *ibuf, size_t inputsize,\n\t\t\t\t\tunsigned char *obuf, size_t outputsize)\n{\n if (inputsize < headersize + 2)\n return 0;\n\n unsigned short block_count = ARRAY_AS_WORD(ibuf, headersize);\n unsigned block_start = headersize + 2 + 2 * block_count;\n\n if (inputsize < block_start)\n return 0;\n\n unsigned char *block_length = &ibuf[headersize + 2];\n ibuf += block_start;\n inputsize -= block_start;\n\n size_t olen = 0;\n for (int i = 0; i < block_count; i++) {\n unsigned short blen = ARRAY_AS_WORD(block_length, 2 * i);\n if (blen < 2 || blen > inputsize)\n return 0;\n\n unsigned short bul = ARRAY_AS_WORD(ibuf, 0);\n\n if (unpack_block(ibuf + 2, blen - 2, obuf, outputsize - olen) != bul)\n return 0;\n\n obuf += bul;\n olen += bul;\n\n ibuf += blen;\n inputsize -= blen;\n }\n\n return olen;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\author ddubois\n * \\date 12-Sep-18.\n *\/\n\n#include \"shaderpack_validator.hpp\"\n#include \"..\/json_utils.hpp\"\n#include \"..\/..\/util\/utils.hpp\"\n#include \"..\/..\/..\/tests\/src\/general_test_setup.hpp\"\n\n#ifdef ERROR\n#undef ERROR\n#endif\n\nnamespace nova {\n \/*!\n * \\brief All the default values for a JSON pipeline\n *\n * If a field is in `pipeline_data` but not in this structure, it is a required field and cannot be given a\n * default value. It will thus cause an exception\n *\/\n nlohmann::json default_graphics_pipeline =\n {\n {\"parentName\", \"\"},\n {\"defines\", std::array<std::string, 0>{}},\n {\"states\", std::array<std::string, 0>{}},\n {\"frontFace\", nlohmann::json::object_t()},\n {\"backFace\", nlohmann::json::object_t()},\n {\"fallback\", \"\"},\n {\"depthBias\", 0},\n {\"slopeScaledDepthBias\", 0},\n {\"stencilRef\", 0},\n {\"stencilReadMask\", 0},\n {\"stencilWriteMask\", 0},\n {\"msaaSupport\", \"None\"},\n {\"primitiveMode\", \"Triangles\"},\n {\"sourceBlendFactor\", \"One\"},\n {\"destinationBlendFactor\", \"Zero\"},\n {\"alphaSrc\", \"One\"},\n {\"alphaDst\", \"Zero\"},\n {\"depthFunc\", \"Less\"},\n {\"renderQueue\", \"Opaque\"},\n {\"fragmentShader\", \"\"},\n {\"tessellationControlShader\", \"\"},\n {\"tessellationEvaluationShader\", \"\"},\n {\"geometryShader\", \"\"}\n };\n\n std::vector<std::string> required_graphics_pipeline_fields = {\"name\", \"pass\", \"vertexFields\", \"vertexShader\"};\n\n nlohmann::json default_texture_format = {{\"pixelFormat\", \"RGBA8\"}, {\"dimensionType\", \"Absolute\"}};\n\n void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report);\n\n#define PIPELINE_MSG(name, msg) \"Pipeline \" + name + \": \" + msg\n\n validation_report validate_graphics_pipeline(nlohmann::json &pipeline_json) {\n validation_report report;\n const std::string name = get_json_value<std::string>(pipeline_json, \"name\").value_or(\"<NAME_MISSING>\");\n \/\/ Don't need to check for the name's existence here, it'll be checked with the rest of the required fields\n\n const std::string pipeline_context = \"Pipeline \" + name;\n \/\/ Check non-required fields first\n for(const auto &str : default_graphics_pipeline.items()) {\n ensure_field_exists(pipeline_json, str.key(), pipeline_context, default_graphics_pipeline, report);\n }\n\n \/\/ Check required items\n report.errors.reserve(required_graphics_pipeline_fields.size());\n for(const std::string &field_name : required_graphics_pipeline_fields) {\n const auto &itr = pipeline_json.find(field_name);\n if(itr == pipeline_json.end()) {\n report.errors.emplace_back(PIPELINE_MSG(name, \"Missing field \" + field_name));\n }\n }\n\n return report;\n }\n\n#define RESOURCES_MSG(msg) (std::string(\"Resources file: \") + msg)\n\n validation_report validate_shaderpack_resources_data(nlohmann::json &resources_json) {\n validation_report report;\n bool missing_textures = false;\n\n const auto &textures_itr = resources_json.find(\"textures\");\n if(textures_itr == resources_json.end()) {\n missing_textures = true;\n\n } else {\n auto &textures_array = *textures_itr;\n if(textures_array.empty()) {\n missing_textures = true;\n\n } else {\n for(auto &tex : textures_array) {\n const validation_report texture_report = validate_texture_data(tex);\n report.merge_in(texture_report);\n }\n }\n }\n\n if(missing_textures) {\n report.warnings.emplace_back(RESOURCES_MSG(\"Missing dynamic resources. If you ONLY use the backbuffer in your shaderpack, you can ignore this message\"));\n }\n\n const nlohmann::json::iterator &samplers_itr = resources_json.find(\"samplers\");\n if(samplers_itr == resources_json.end()) {\n if(!missing_textures) {\n report.errors.emplace_back(RESOURCES_MSG(\"No samplers defined, but dynamic textures are defined. You need to define your own samplers to access a texture with\"));\n }\n\n } else {\n nlohmann::json &all_samplers = *samplers_itr;\n if(!all_samplers.is_array()) {\n report.errors.emplace_back(RESOURCES_MSG(\"Samplers array must be an array, but like it isn't\"));\n\n } else {\n for(nlohmann::json &sampler : all_samplers) {\n const validation_report sampler_report = validate_sampler_data(sampler);\n report.merge_in(sampler_report);\n }\n }\n }\n\n return report;\n }\n\n#define TEXTURE_MSG(name, msg) \"Texture \" + name + \": \" + msg\n\n validation_report validate_texture_data(nlohmann::json &texture_json) {\n validation_report report;\n const auto name_maybe = get_json_value<std::string>(texture_json, \"name\");\n std::string name;\n if(name_maybe) {\n name = name_maybe.value();\n\n } else {\n name = \"<NAME_MISSING>\";\n texture_json[\"name\"] = name;\n report.errors.emplace_back(TEXTURE_MSG(name, \"Missing field name\"));\n }\n\n const auto format_itr = texture_json.find(\"format\");\n if(format_itr == texture_json.end()) {\n report.errors.emplace_back(TEXTURE_MSG(name, \"Missing field format\"));\n\n } else {\n const validation_report format_report = validate_texture_format(*format_itr, name);\n report.merge_in(format_report);\n }\n\n return report;\n }\n\n#define FORMAT_MSG(tex_name, msg) \"Format of texture \" + tex_name + \": \" + msg\n\n validation_report validate_texture_format(nlohmann::json &format_json, const std::string &texture_name) {\n validation_report report;\n\n ensure_field_exists(format_json, \"pixelFormat\", \"Format of texture \" + texture_name, default_texture_format, report);\n ensure_field_exists(format_json, \"dimensionType\", \"Format of texture \" + texture_name, default_texture_format, report);\n\n const bool missing_width = format_json.find(\"width\") == format_json.end();\n if(missing_width) {\n report.errors.emplace_back(FORMAT_MSG(texture_name, \"Missing field width\"));\n }\n\n const bool missing_height = format_json.find(\"height\") == format_json.end();\n if(missing_height) {\n report.errors.emplace_back(FORMAT_MSG(texture_name, \"Missing field height\"));\n }\n\n return report;\n }\n\n#define SAMPLER_MSG(name, msg) \"Sampler \" + name + \": \" + msg\n\n validation_report validate_sampler_data(nlohmann::json &sampler_json) {\n validation_report report;\n const std::string name = get_json_value<std::string>(sampler_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field name\"));\n }\n\n const bool missing_filter = sampler_json.find(\"filter\") == sampler_json.end();\n if(missing_filter) {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field filter\"));\n }\n\n const bool missing_wrap_mode = sampler_json.find(\"wrapMode\") == sampler_json.end();\n if(missing_wrap_mode) {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field wrapMode\"));\n }\n\n return report;\n }\n\n#define MATERIAL_MSG(name, error) \"Material \" + name + \": \" + error\n#define MATERIAL_PASS_MSG(mat_name, pass_name, error) \"Material pass \" + pass_name + \" in material \" + mat_name + \": \" + error\n\n validation_report validate_material(nlohmann::json &material_json) {\n validation_report report;\n\n const std::string name = get_json_value<std::string>(material_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing material name\"));\n }\n\n const bool missing_geometry_filter = material_json.find(\"filter\") == material_json.end();\n if(missing_geometry_filter) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing geometry filter\"));\n }\n\n const bool missing_passes = material_json.find(\"passes\") == material_json.end();\n if(missing_passes) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing material passes\"));\n\n } else {\n const nlohmann::json &passes_json = material_json.at(\"passes\");\n if(!passes_json.is_array()) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Passes field must be an array\"));\n return report;\n\n } else if(passes_json.empty()) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Passes field must have at least one item\"));\n return report;\n }\n\n for(const auto &pass_json : passes_json) {\n const std::string pass_name = get_json_value<std::string>(pass_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(pass_name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field name\"));\n }\n\n const auto pipeline_maybe = get_json_value<std::string>(pass_json, \"pipeline\");\n if(!pipeline_maybe) {\n report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field pipeline\"));\n }\n\n const auto bindings_itr = pass_json.find(\"bindings\");\n if(bindings_itr == pass_json.end()) {\n report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field bindings\"));\n } else {\n const nlohmann::json &bindings = *bindings_itr;\n if(bindings.empty()) {\n report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Field bindings exists but it's empty\"));\n }\n }\n }\n }\n\n return report;\n }\n\n void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report) {\n if(j.find(field_name) == j.end()) {\n j[field_name] = default_value[field_name];\n report.warnings.emplace_back(context + \": Missing field \" + field_name + \". A default value of '\" + j[field_name].dump() + \"' will be used\");\n }\n }\n\n void print(const validation_report &report) {\n for(const auto &error : report.errors) {\n NOVA_LOG(ERROR) << error;\n }\n\n for(const auto &warning : report.warnings) {\n NOVA_LOG(DEBUG) << warning;\n }\n }\n\n void validation_report::merge_in(const validation_report &other) {\n errors.insert(errors.end(), other.errors.begin(), other.errors.end());\n warnings.insert(warnings.begin(), other.warnings.begin(), other.warnings.end());\n }\n} \/\/ namespace nova\n<commit_msg>clang-tidy: bugprone-macro-parentheses<commit_after>\/*!\n * \\author ddubois\n * \\date 12-Sep-18.\n *\/\n\n#include \"shaderpack_validator.hpp\"\n#include \"..\/json_utils.hpp\"\n#include \"..\/..\/util\/utils.hpp\"\n#include \"..\/..\/..\/tests\/src\/general_test_setup.hpp\"\n\n#ifdef ERROR\n#undef ERROR\n#endif\n\nnamespace nova {\n \/*!\n * \\brief All the default values for a JSON pipeline\n *\n * If a field is in `pipeline_data` but not in this structure, it is a required field and cannot be given a\n * default value. It will thus cause an exception\n *\/\n nlohmann::json default_graphics_pipeline =\n {\n {\"parentName\", \"\"},\n {\"defines\", std::array<std::string, 0>{}},\n {\"states\", std::array<std::string, 0>{}},\n {\"frontFace\", nlohmann::json::object_t()},\n {\"backFace\", nlohmann::json::object_t()},\n {\"fallback\", \"\"},\n {\"depthBias\", 0},\n {\"slopeScaledDepthBias\", 0},\n {\"stencilRef\", 0},\n {\"stencilReadMask\", 0},\n {\"stencilWriteMask\", 0},\n {\"msaaSupport\", \"None\"},\n {\"primitiveMode\", \"Triangles\"},\n {\"sourceBlendFactor\", \"One\"},\n {\"destinationBlendFactor\", \"Zero\"},\n {\"alphaSrc\", \"One\"},\n {\"alphaDst\", \"Zero\"},\n {\"depthFunc\", \"Less\"},\n {\"renderQueue\", \"Opaque\"},\n {\"fragmentShader\", \"\"},\n {\"tessellationControlShader\", \"\"},\n {\"tessellationEvaluationShader\", \"\"},\n {\"geometryShader\", \"\"}\n };\n\n std::vector<std::string> required_graphics_pipeline_fields = {\"name\", \"pass\", \"vertexFields\", \"vertexShader\"};\n\n nlohmann::json default_texture_format = {{\"pixelFormat\", \"RGBA8\"}, {\"dimensionType\", \"Absolute\"}};\n\n void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report);\n\n#define PIPELINE_MSG(name, msg) (\"Pipeline \" + (name) + \": \" + (msg))\n\n validation_report validate_graphics_pipeline(nlohmann::json &pipeline_json) {\n validation_report report;\n const std::string name = get_json_value<std::string>(pipeline_json, \"name\").value_or(\"<NAME_MISSING>\");\n \/\/ Don't need to check for the name's existence here, it'll be checked with the rest of the required fields\n\n const std::string pipeline_context = \"Pipeline \" + name;\n \/\/ Check non-required fields first\n for(const auto &str : default_graphics_pipeline.items()) {\n ensure_field_exists(pipeline_json, str.key(), pipeline_context, default_graphics_pipeline, report);\n }\n\n \/\/ Check required items\n report.errors.reserve(required_graphics_pipeline_fields.size());\n for(const std::string &field_name : required_graphics_pipeline_fields) {\n const auto &itr = pipeline_json.find(field_name);\n if(itr == pipeline_json.end()) {\n report.errors.emplace_back(PIPELINE_MSG(name, \"Missing field \" + field_name));\n }\n }\n\n return report;\n }\n\n#define RESOURCES_MSG(msg) (std::string(\"Resources file: \") + (msg))\n\n validation_report validate_shaderpack_resources_data(nlohmann::json &resources_json) {\n validation_report report;\n bool missing_textures = false;\n\n const auto &textures_itr = resources_json.find(\"textures\");\n if(textures_itr == resources_json.end()) {\n missing_textures = true;\n\n } else {\n auto &textures_array = *textures_itr;\n if(textures_array.empty()) {\n missing_textures = true;\n\n } else {\n for(auto &tex : textures_array) {\n const validation_report texture_report = validate_texture_data(tex);\n report.merge_in(texture_report);\n }\n }\n }\n\n if(missing_textures) {\n report.warnings.emplace_back(RESOURCES_MSG(\"Missing dynamic resources. If you ONLY use the backbuffer in your shaderpack, you can ignore this message\"));\n }\n\n const nlohmann::json::iterator &samplers_itr = resources_json.find(\"samplers\");\n if(samplers_itr == resources_json.end()) {\n if(!missing_textures) {\n report.errors.emplace_back(RESOURCES_MSG(\"No samplers defined, but dynamic textures are defined. You need to define your own samplers to access a texture with\"));\n }\n\n } else {\n nlohmann::json &all_samplers = *samplers_itr;\n if(!all_samplers.is_array()) {\n report.errors.emplace_back(RESOURCES_MSG(\"Samplers array must be an array, but like it isn't\"));\n\n } else {\n for(nlohmann::json &sampler : all_samplers) {\n const validation_report sampler_report = validate_sampler_data(sampler);\n report.merge_in(sampler_report);\n }\n }\n }\n\n return report;\n }\n\n#define TEXTURE_MSG(name, msg) (\"Texture \" + (name) + \": \" + (msg))\n\n validation_report validate_texture_data(nlohmann::json &texture_json) {\n validation_report report;\n const auto name_maybe = get_json_value<std::string>(texture_json, \"name\");\n std::string name;\n if(name_maybe) {\n name = name_maybe.value();\n\n } else {\n name = \"<NAME_MISSING>\";\n texture_json[\"name\"] = name;\n report.errors.emplace_back(TEXTURE_MSG(name, \"Missing field name\"));\n }\n\n const auto format_itr = texture_json.find(\"format\");\n if(format_itr == texture_json.end()) {\n report.errors.emplace_back(TEXTURE_MSG(name, \"Missing field format\"));\n\n } else {\n const validation_report format_report = validate_texture_format(*format_itr, name);\n report.merge_in(format_report);\n }\n\n return report;\n }\n\n#define FORMAT_MSG(tex_name, msg) (\"Format of texture \" + (tex_name) + \": \" + (msg))\n\n validation_report validate_texture_format(nlohmann::json &format_json, const std::string &texture_name) {\n validation_report report;\n\n ensure_field_exists(format_json, \"pixelFormat\", \"Format of texture \" + texture_name, default_texture_format, report);\n ensure_field_exists(format_json, \"dimensionType\", \"Format of texture \" + texture_name, default_texture_format, report);\n\n const bool missing_width = format_json.find(\"width\") == format_json.end();\n if(missing_width) {\n report.errors.emplace_back(FORMAT_MSG(texture_name, \"Missing field width\"));\n }\n\n const bool missing_height = format_json.find(\"height\") == format_json.end();\n if(missing_height) {\n report.errors.emplace_back(FORMAT_MSG(texture_name, \"Missing field height\"));\n }\n\n return report;\n }\n\n#define SAMPLER_MSG(name, msg) (\"Sampler \" + (name) + \": \" + (msg))\n\n validation_report validate_sampler_data(nlohmann::json &sampler_json) {\n validation_report report;\n const std::string name = get_json_value<std::string>(sampler_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field name\"));\n }\n\n const bool missing_filter = sampler_json.find(\"filter\") == sampler_json.end();\n if(missing_filter) {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field filter\"));\n }\n\n const bool missing_wrap_mode = sampler_json.find(\"wrapMode\") == sampler_json.end();\n if(missing_wrap_mode) {\n report.errors.emplace_back(SAMPLER_MSG(name, \"Missing field wrapMode\"));\n }\n\n return report;\n }\n\n#define MATERIAL_MSG(name, error) (\"Material \" + (name) + \": \" + (error))\n#define MATERIAL_PASS_MSG(mat_name, pass_name, error) (\"Material pass \" + (pass_name) + \" in material \" + (mat_name) + \": \" + (error))\n\n validation_report validate_material(nlohmann::json &material_json) {\n validation_report report;\n\n const std::string name = get_json_value<std::string>(material_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing material name\"));\n }\n\n const bool missing_geometry_filter = material_json.find(\"filter\") == material_json.end();\n if(missing_geometry_filter) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing geometry filter\"));\n }\n\n const bool missing_passes = material_json.find(\"passes\") == material_json.end();\n if(missing_passes) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Missing material passes\"));\n\n } else {\n const nlohmann::json &passes_json = material_json.at(\"passes\");\n if(!passes_json.is_array()) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Passes field must be an array\"));\n return report;\n\n } else if(passes_json.empty()) {\n report.errors.emplace_back(MATERIAL_MSG(name, \"Passes field must have at least one item\"));\n return report;\n }\n\n for(const auto &pass_json : passes_json) {\n const std::string pass_name = get_json_value<std::string>(pass_json, \"name\").value_or(\"<NAME_MISSING>\");\n if(pass_name == \"<NAME_MISSING>\") {\n report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field name\"));\n }\n\n const auto pipeline_maybe = get_json_value<std::string>(pass_json, \"pipeline\");\n if(!pipeline_maybe) {\n report.errors.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field pipeline\"));\n }\n\n const auto bindings_itr = pass_json.find(\"bindings\");\n if(bindings_itr == pass_json.end()) {\n report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Missing field bindings\"));\n } else {\n const nlohmann::json &bindings = *bindings_itr;\n if(bindings.empty()) {\n report.warnings.emplace_back(MATERIAL_PASS_MSG(name, pass_name, \"Field bindings exists but it's empty\"));\n }\n }\n }\n }\n\n return report;\n }\n\n void ensure_field_exists(nlohmann::json &j, const std::string &field_name, const std::string &context, const nlohmann::json &default_value, validation_report &report) {\n if(j.find(field_name) == j.end()) {\n j[field_name] = default_value[field_name];\n report.warnings.emplace_back(context + \": Missing field \" + field_name + \". A default value of '\" + j[field_name].dump() + \"' will be used\");\n }\n }\n\n void print(const validation_report &report) {\n for(const auto &error : report.errors) {\n NOVA_LOG(ERROR) << error;\n }\n\n for(const auto &warning : report.warnings) {\n NOVA_LOG(DEBUG) << warning;\n }\n }\n\n void validation_report::merge_in(const validation_report &other) {\n errors.insert(errors.end(), other.errors.begin(), other.errors.end());\n warnings.insert(warnings.begin(), other.warnings.begin(), other.warnings.end());\n }\n} \/\/ namespace nova\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright (C) 2007 Dave Robillard <http:\/\/drobilla.net>\n * \n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n * \n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n * \n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <cassert>\n#include \"raul\/Atom.hpp\"\n#include \"interface\/EngineInterface.hpp\"\n#include \"client\/NodeModel.hpp\"\n#include \"client\/PatchModel.hpp\"\n#include \"client\/PluginUI.hpp\"\n#include \"App.hpp\"\n#include \"GladeFactory.hpp\"\n#include \"NodeControlWindow.hpp\"\n#include \"NodeModule.hpp\"\n#include \"PatchCanvas.hpp\"\n#include \"PatchWindow.hpp\"\n#include \"Port.hpp\"\n#include \"RenameWindow.hpp\"\n#include \"SubpatchModule.hpp\"\n#include \"WindowFactory.hpp\"\n#include \"Configuration.hpp\"\n#include \"NodeMenu.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace GUI {\n\n\nNodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)\n\t: FlowCanvas::Module(canvas, node->path().name())\n\t, _node(node)\n\t, _gui_widget(NULL)\n\t, _gui_window(NULL)\n{\n\tassert(_node);\n\n\tnode->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));\n\tnode->signal_removed_port.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::remove_port)));\n\tnode->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable));\n\tnode->signal_property.connect(sigc::mem_fun(this, &NodeModule::set_property));\n\tnode->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));\n}\n\n\nNodeModule::~NodeModule()\n{\n\tNodeControlWindow* win = App::instance().window_factory()->control_window(_node);\n\t\n\tif (win) {\n\t\t\/\/ Should remove from window factory via signal\n\t\tdelete win;\n\t}\n}\n\n\nvoid\nNodeModule::create_menu()\n{\n\tGlib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();\n\txml->get_widget_derived(\"object_menu\", _menu);\n\t_menu->init(_node);\n\t_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));\n\t_menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));\n\t\n\tset_menu(_menu);\n}\n\n\nboost::shared_ptr<NodeModule>\nNodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node, bool human)\n{\n\tboost::shared_ptr<NodeModule> ret;\n\n\tSharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);\n\tif (patch)\n\t\tret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));\n\telse\n\t\tret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));\n\n\tfor (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m)\n\t\tret->set_variable(m->first, m->second);\n\n\tfor (NodeModel::Ports::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {\n\t\tret->add_port(*p, false);\n\t}\n\n\tif (human)\n\t\tret->show_human_names(human); \/\/ FIXME: double port iteration\n\n\tret->resize();\n\tret->set_stacked_border(node->polyphonic());\n\n\treturn ret;\n}\n\n\nvoid\nNodeModule::show_human_names(bool b)\n{\n\tif (b && node()->plugin()) {\n\t\tGlib::Mutex::Lock lock(App::instance().world()->rdf_world->mutex());\n\t\tset_name(((PluginModel*)node()->plugin())->human_name());\n\t} else {\n\t\tb = false;\n\t}\n\t\n\tif (!b)\n\t\tset_name(node()->symbol());\n\n\tuint32_t index = 0;\n\tfor (PortVector::const_iterator i = ports().begin(); i != ports().end(); ++i) {\n\t\tstring name = node()->port(index)->symbol();\n\t\tif (b) {\n\t\t\tstring hn = ((PluginModel*)node()->plugin())->port_human_name(index);\n\t\t\tif (hn != \"\")\n\t\t\t\tname = hn;\n\t\t}\n\t\t(*i)->set_name(name);\n\t\t++index;\n\t}\n\n\tresize();\n}\n\n\t\nvoid\nNodeModule::value_changed(uint32_t index, const Atom& value)\n{\n\tfloat control = 0.0f;\n\tswitch (value.type()) {\n\tcase Atom::FLOAT:\n\t\tcontrol = value.get_float();\n\t\tif (_plugin_ui) {\n\t\t\tSLV2UIInstance inst = _plugin_ui->instance();\n\t\t\tconst LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst);\n\t\t\tLV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst);\n\t\t\tif (ui_descriptor->port_event)\n\t\t\t\tui_descriptor->port_event(ui_handle, index, 4, 0, &control);\n\t\t}\n\t\tbreak;\n\tcase Atom::STRING:\n\t\tcout << \"Port value type is a string? (\\\"\" << value.get_string() << \"\\\")\" << endl;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\n\nvoid\nNodeModule::embed_gui(bool embed)\n{\n\tif (embed) {\n\n\t\tif (_gui_window) {\n\t\t\tcerr << \"LV2 GUI already popped up, cannot embed\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!_plugin_ui) {\n\t\t\tconst PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin());\n\t\t\tassert(pm);\n\t\t\t_plugin_ui = pm->ui(App::instance().world(), _node);\n\t\t}\n\n\t\tif (_plugin_ui) {\n\t\t\tGtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());\n\t\t\t_gui_widget = Glib::wrap(c_widget);\n\t\t\tassert(_gui_widget);\n\n\t\t\tGtk::Container* container = new Gtk::EventBox();\n\t\t\tcontainer->set_name(\"ingen_embedded_node_gui_container\");\n\t\t\tcontainer->add(*_gui_widget);\n\t\t\tFlowCanvas::Module::embed(container);\n\t\t} else {\n\t\t\tcerr << \"ERROR: Failed to create LV2 UI\" << endl;\n\t\t}\n\n\t\tif (_gui_widget) {\n\t\t\t_gui_widget->show_all();\n\n\t\t\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin();\n\t\t\t\t\tp != _node->ports().end(); ++p)\n\t\t\t\tif ((*p)->type().is_control() && (*p)->is_output())\n\t\t\t\t\tApp::instance().engine()->set_property((*p)->path(), \"ingen:broadcast\", true);\n\t\t}\n\n\t} else { \/\/ un-embed\n\n\t\tFlowCanvas::Module::embed(NULL);\n\t\t_plugin_ui.reset();\n\n\t\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)\n\t\t\tif ((*p)->type().is_control() && (*p)->is_output())\n\t\t\t\tApp::instance().engine()->set_property((*p)->path(), \"ingen:broadcast\", false);\n\t}\n\t\t\t\n\tif (embed && _embed_item) {\n\t\tinitialise_gui_values();\n\t\tset_base_color(0x212222FF);\n\t} else {\n\t\tset_default_base_color();\n\t}\n\n\tresize();\n}\n\n\nvoid\nNodeModule::rename()\n{\n\tset_name(_node->path().name());\n\tresize();\n}\n\n\nvoid\nNodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)\n{\n\tuint32_t index = _ports.size(); \/\/ FIXME: kludge, engine needs to tell us this\n\t\n\tstring name = port->path().name();\n\tif (App::instance().configuration()->name_style() == Configuration::HUMAN && node()->plugin()) {\n\t\tstring hn = ((PluginModel*)node()->plugin())->port_human_name(index);\n\t\tif (hn != \"\")\n\t\t\tname = hn;\n\t}\n\n\tModule::add_port(boost::shared_ptr<Port>(\n\t\t\tnew Port(PtrCast<NodeModule>(shared_from_this()), port, name)));\n\t\t\n\tport->signal_value_changed.connect(sigc::bind<0>(\n\t\t\tsigc::mem_fun(this, &NodeModule::value_changed), index));\n\n\tif (resize_to_fit)\n\t\tresize();\n}\n\n\t\nboost::shared_ptr<Port>\nNodeModule::port(boost::shared_ptr<PortModel> model)\n{\n\tfor (PortVector::const_iterator p = ports().begin(); p != ports().end(); ++p) {\n\t\tSharedPtr<Port> port = PtrCast<Port>(*p);\n\t\tif (port->model() == model) {\n\t\t\tcout << \"FOUND: \" << model->path() << endl;\n\t\t\treturn port;\n\t\t}\n\t}\n\treturn boost::shared_ptr<Port>();\n}\n\n\nvoid\nNodeModule::remove_port(SharedPtr<PortModel> model)\n{\n\tSharedPtr<Port> p = port(model);\n\tif (p) {\n\t\tModule::remove_port(p);\n\t\tp.reset();\n\t} else {\n\t\tcerr << \"WARNING: Failed to find port on module: \" << model->path() << endl;\n\t}\n}\n\n\nbool\nNodeModule::popup_gui()\n{\n#ifdef HAVE_SLV2\n\tif (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) {\n\t\tif (_plugin_ui) {\n\t\t\tcerr << \"LV2 GUI already embedded, cannot pop up\" << endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tconst PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());\n\t\tassert(plugin);\n\n\t\t_plugin_ui = plugin->ui(App::instance().world(), _node);\n\n\t\tif (_plugin_ui) {\n\t\t\tGtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());\n\t\t\t_gui_widget = Glib::wrap(c_widget);\n\t\t\t\n\t\t\t_gui_window = new Gtk::Window();\n\t\t\t_gui_window->add(*_gui_widget);\n\t\t\t_gui_widget->show_all();\n\t\t\tinitialise_gui_values();\n\n\t\t\t_gui_window->signal_unmap().connect(\n\t\t\t\t\tsigc::mem_fun(this, &NodeModule::on_gui_window_close));\n\t\t\t_gui_window->present();\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\tcerr << \"No LV2 GUI\" << endl;\n\t\t}\n\t}\n#endif\n\treturn false;\n}\n\n\nvoid\nNodeModule::on_gui_window_close()\n{\n\tdelete _gui_window;\n\t_gui_window = NULL;\n\t_plugin_ui.reset();\n\t_gui_widget = NULL;\n}\n\t\n\nvoid\nNodeModule::initialise_gui_values()\n{\n\tuint32_t index=0;\n\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) {\n\t\tif ((*p)->type().is_control())\n\t\t\tvalue_changed(index, (*p)->value());\n\t\t++index;\n\t}\n}\n\n\nvoid\nNodeModule::show_control_window()\n{\n\tApp::instance().window_factory()->present_controls(_node);\n}\n\t\n\nvoid\nNodeModule::on_double_click(GdkEventButton* ev)\n{\n\tif ( ! popup_gui() )\n\t\tshow_control_window();\n}\n\n\nvoid\nNodeModule::store_location()\n{\n\tconst float x = static_cast<float>(property_x());\n\tconst float y = static_cast<float>(property_y());\n\t\n\tconst Atom& existing_x = _node->get_variable(\"ingenuity:canvas-x\");\n\tconst Atom& existing_y = _node->get_variable(\"ingenuity:canvas-y\");\n\t\n\tif (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT\n\t\t\t|| existing_x.get_float() != x || existing_y.get_float() != y) {\n\t\tApp::instance().engine()->set_variable(_node->path(), \"ingenuity:canvas-x\", Atom(x));\n\t\tApp::instance().engine()->set_variable(_node->path(), \"ingenuity:canvas-y\", Atom(y));\n\t}\n}\n\n\nvoid\nNodeModule::set_variable(const string& key, const Atom& value)\n{\n\tif (key == \"ingenuity:canvas-x\" && value.type() == Atom::FLOAT)\n\t\tmove_to(value.get_float(), property_y());\n\telse if (key == \"ingenuity:canvas-y\" && value.type() == Atom::FLOAT)\n\t\tmove_to(property_x(), value.get_float());\n}\n\n\nvoid\nNodeModule::set_property(const string& key, const Atom& value)\n{\n\tif (key == \"ingen:polyphonic\" && value.type() == Atom::BOOL) {\n\t\tset_stacked_border(value.get_bool());\n\t} else if (key == \"ingen:selected\" && value.type() == Atom::BOOL) {\n\t\tif (value.get_bool() != selected()) {\n\t\t\tif (value.get_bool())\n\t\t\t\t_canvas.lock()->select_item(shared_from_this());\n\t\t\telse\n\t\t\t\t_canvas.lock()->unselect_item(shared_from_this());\n\t\t}\n\t}\n}\n\n\nvoid\nNodeModule::set_selected(bool b)\n{\n\tif (b != selected()) {\n\t\tModule::set_selected(b);\n\t\tif (App::instance().signal())\n\t\t\tApp::instance().engine()->set_property(_node->path(), \"ingen:selected\", b);\n\t}\n}\n\n\n} \/\/ namespace GUI\n} \/\/ namespace Ingen\n<commit_msg>Shutup.<commit_after>\/* This file is part of Ingen.\n * Copyright (C) 2007 Dave Robillard <http:\/\/drobilla.net>\n * \n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n * \n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n * \n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <cassert>\n#include \"raul\/Atom.hpp\"\n#include \"interface\/EngineInterface.hpp\"\n#include \"client\/NodeModel.hpp\"\n#include \"client\/PatchModel.hpp\"\n#include \"client\/PluginUI.hpp\"\n#include \"App.hpp\"\n#include \"GladeFactory.hpp\"\n#include \"NodeControlWindow.hpp\"\n#include \"NodeModule.hpp\"\n#include \"PatchCanvas.hpp\"\n#include \"PatchWindow.hpp\"\n#include \"Port.hpp\"\n#include \"RenameWindow.hpp\"\n#include \"SubpatchModule.hpp\"\n#include \"WindowFactory.hpp\"\n#include \"Configuration.hpp\"\n#include \"NodeMenu.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace GUI {\n\n\nNodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)\n\t: FlowCanvas::Module(canvas, node->path().name())\n\t, _node(node)\n\t, _gui_widget(NULL)\n\t, _gui_window(NULL)\n{\n\tassert(_node);\n\n\tnode->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));\n\tnode->signal_removed_port.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::remove_port)));\n\tnode->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable));\n\tnode->signal_property.connect(sigc::mem_fun(this, &NodeModule::set_property));\n\tnode->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));\n}\n\n\nNodeModule::~NodeModule()\n{\n\tNodeControlWindow* win = App::instance().window_factory()->control_window(_node);\n\t\n\tif (win) {\n\t\t\/\/ Should remove from window factory via signal\n\t\tdelete win;\n\t}\n}\n\n\nvoid\nNodeModule::create_menu()\n{\n\tGlib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();\n\txml->get_widget_derived(\"object_menu\", _menu);\n\t_menu->init(_node);\n\t_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));\n\t_menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));\n\t\n\tset_menu(_menu);\n}\n\n\nboost::shared_ptr<NodeModule>\nNodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node, bool human)\n{\n\tboost::shared_ptr<NodeModule> ret;\n\n\tSharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);\n\tif (patch)\n\t\tret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));\n\telse\n\t\tret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));\n\n\tfor (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m)\n\t\tret->set_variable(m->first, m->second);\n\n\tfor (NodeModel::Ports::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {\n\t\tret->add_port(*p, false);\n\t}\n\n\tif (human)\n\t\tret->show_human_names(human); \/\/ FIXME: double port iteration\n\n\tret->resize();\n\tret->set_stacked_border(node->polyphonic());\n\n\treturn ret;\n}\n\n\nvoid\nNodeModule::show_human_names(bool b)\n{\n\tif (b && node()->plugin()) {\n\t\tGlib::Mutex::Lock lock(App::instance().world()->rdf_world->mutex());\n\t\tset_name(((PluginModel*)node()->plugin())->human_name());\n\t} else {\n\t\tb = false;\n\t}\n\t\n\tif (!b)\n\t\tset_name(node()->symbol());\n\n\tuint32_t index = 0;\n\tfor (PortVector::const_iterator i = ports().begin(); i != ports().end(); ++i) {\n\t\tstring name = node()->port(index)->symbol();\n\t\tif (b) {\n\t\t\tstring hn = ((PluginModel*)node()->plugin())->port_human_name(index);\n\t\t\tif (hn != \"\")\n\t\t\t\tname = hn;\n\t\t}\n\t\t(*i)->set_name(name);\n\t\t++index;\n\t}\n\n\tresize();\n}\n\n\t\nvoid\nNodeModule::value_changed(uint32_t index, const Atom& value)\n{\n\tfloat control = 0.0f;\n\tswitch (value.type()) {\n\tcase Atom::FLOAT:\n\t\tcontrol = value.get_float();\n\t\tif (_plugin_ui) {\n\t\t\tSLV2UIInstance inst = _plugin_ui->instance();\n\t\t\tconst LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst);\n\t\t\tLV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst);\n\t\t\tif (ui_descriptor->port_event)\n\t\t\t\tui_descriptor->port_event(ui_handle, index, 4, 0, &control);\n\t\t}\n\t\tbreak;\n\tcase Atom::STRING:\n\t\tcout << \"Port value type is a string? (\\\"\" << value.get_string() << \"\\\")\" << endl;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\n\nvoid\nNodeModule::embed_gui(bool embed)\n{\n\tif (embed) {\n\n\t\tif (_gui_window) {\n\t\t\tcerr << \"LV2 GUI already popped up, cannot embed\" << endl;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!_plugin_ui) {\n\t\t\tconst PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin());\n\t\t\tassert(pm);\n\t\t\t_plugin_ui = pm->ui(App::instance().world(), _node);\n\t\t}\n\n\t\tif (_plugin_ui) {\n\t\t\tGtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());\n\t\t\t_gui_widget = Glib::wrap(c_widget);\n\t\t\tassert(_gui_widget);\n\n\t\t\tGtk::Container* container = new Gtk::EventBox();\n\t\t\tcontainer->set_name(\"ingen_embedded_node_gui_container\");\n\t\t\tcontainer->add(*_gui_widget);\n\t\t\tFlowCanvas::Module::embed(container);\n\t\t} else {\n\t\t\tcerr << \"ERROR: Failed to create LV2 UI\" << endl;\n\t\t}\n\n\t\tif (_gui_widget) {\n\t\t\t_gui_widget->show_all();\n\n\t\t\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin();\n\t\t\t\t\tp != _node->ports().end(); ++p)\n\t\t\t\tif ((*p)->type().is_control() && (*p)->is_output())\n\t\t\t\t\tApp::instance().engine()->set_property((*p)->path(), \"ingen:broadcast\", true);\n\t\t}\n\n\t} else { \/\/ un-embed\n\n\t\tFlowCanvas::Module::embed(NULL);\n\t\t_plugin_ui.reset();\n\n\t\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)\n\t\t\tif ((*p)->type().is_control() && (*p)->is_output())\n\t\t\t\tApp::instance().engine()->set_property((*p)->path(), \"ingen:broadcast\", false);\n\t}\n\t\t\t\n\tif (embed && _embed_item) {\n\t\tinitialise_gui_values();\n\t\tset_base_color(0x212222FF);\n\t} else {\n\t\tset_default_base_color();\n\t}\n\n\tresize();\n}\n\n\nvoid\nNodeModule::rename()\n{\n\tset_name(_node->path().name());\n\tresize();\n}\n\n\nvoid\nNodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)\n{\n\tuint32_t index = _ports.size(); \/\/ FIXME: kludge, engine needs to tell us this\n\t\n\tstring name = port->path().name();\n\tif (App::instance().configuration()->name_style() == Configuration::HUMAN && node()->plugin()) {\n\t\tstring hn = ((PluginModel*)node()->plugin())->port_human_name(index);\n\t\tif (hn != \"\")\n\t\t\tname = hn;\n\t}\n\n\tModule::add_port(boost::shared_ptr<Port>(\n\t\t\tnew Port(PtrCast<NodeModule>(shared_from_this()), port, name)));\n\t\t\n\tport->signal_value_changed.connect(sigc::bind<0>(\n\t\t\tsigc::mem_fun(this, &NodeModule::value_changed), index));\n\n\tif (resize_to_fit)\n\t\tresize();\n}\n\n\t\nboost::shared_ptr<Port>\nNodeModule::port(boost::shared_ptr<PortModel> model)\n{\n\tfor (PortVector::const_iterator p = ports().begin(); p != ports().end(); ++p) {\n\t\tSharedPtr<Port> port = PtrCast<Port>(*p);\n\t\tif (port->model() == model)\n\t\t\treturn port;\n\t}\n\treturn boost::shared_ptr<Port>();\n}\n\n\nvoid\nNodeModule::remove_port(SharedPtr<PortModel> model)\n{\n\tSharedPtr<Port> p = port(model);\n\tif (p) {\n\t\tModule::remove_port(p);\n\t\tp.reset();\n\t} else {\n\t\tcerr << \"WARNING: Failed to find port on module: \" << model->path() << endl;\n\t}\n}\n\n\nbool\nNodeModule::popup_gui()\n{\n#ifdef HAVE_SLV2\n\tif (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) {\n\t\tif (_plugin_ui) {\n\t\t\tcerr << \"LV2 GUI already embedded, cannot pop up\" << endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tconst PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());\n\t\tassert(plugin);\n\n\t\t_plugin_ui = plugin->ui(App::instance().world(), _node);\n\n\t\tif (_plugin_ui) {\n\t\t\tGtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());\n\t\t\t_gui_widget = Glib::wrap(c_widget);\n\t\t\t\n\t\t\t_gui_window = new Gtk::Window();\n\t\t\t_gui_window->add(*_gui_widget);\n\t\t\t_gui_widget->show_all();\n\t\t\tinitialise_gui_values();\n\n\t\t\t_gui_window->signal_unmap().connect(\n\t\t\t\t\tsigc::mem_fun(this, &NodeModule::on_gui_window_close));\n\t\t\t_gui_window->present();\n\n\t\t\treturn true;\n\t\t} else {\n\t\t\tcerr << \"No LV2 GUI\" << endl;\n\t\t}\n\t}\n#endif\n\treturn false;\n}\n\n\nvoid\nNodeModule::on_gui_window_close()\n{\n\tdelete _gui_window;\n\t_gui_window = NULL;\n\t_plugin_ui.reset();\n\t_gui_widget = NULL;\n}\n\t\n\nvoid\nNodeModule::initialise_gui_values()\n{\n\tuint32_t index=0;\n\tfor (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) {\n\t\tif ((*p)->type().is_control())\n\t\t\tvalue_changed(index, (*p)->value());\n\t\t++index;\n\t}\n}\n\n\nvoid\nNodeModule::show_control_window()\n{\n\tApp::instance().window_factory()->present_controls(_node);\n}\n\t\n\nvoid\nNodeModule::on_double_click(GdkEventButton* ev)\n{\n\tif ( ! popup_gui() )\n\t\tshow_control_window();\n}\n\n\nvoid\nNodeModule::store_location()\n{\n\tconst float x = static_cast<float>(property_x());\n\tconst float y = static_cast<float>(property_y());\n\t\n\tconst Atom& existing_x = _node->get_variable(\"ingenuity:canvas-x\");\n\tconst Atom& existing_y = _node->get_variable(\"ingenuity:canvas-y\");\n\t\n\tif (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT\n\t\t\t|| existing_x.get_float() != x || existing_y.get_float() != y) {\n\t\tApp::instance().engine()->set_variable(_node->path(), \"ingenuity:canvas-x\", Atom(x));\n\t\tApp::instance().engine()->set_variable(_node->path(), \"ingenuity:canvas-y\", Atom(y));\n\t}\n}\n\n\nvoid\nNodeModule::set_variable(const string& key, const Atom& value)\n{\n\tif (key == \"ingenuity:canvas-x\" && value.type() == Atom::FLOAT)\n\t\tmove_to(value.get_float(), property_y());\n\telse if (key == \"ingenuity:canvas-y\" && value.type() == Atom::FLOAT)\n\t\tmove_to(property_x(), value.get_float());\n}\n\n\nvoid\nNodeModule::set_property(const string& key, const Atom& value)\n{\n\tif (key == \"ingen:polyphonic\" && value.type() == Atom::BOOL) {\n\t\tset_stacked_border(value.get_bool());\n\t} else if (key == \"ingen:selected\" && value.type() == Atom::BOOL) {\n\t\tif (value.get_bool() != selected()) {\n\t\t\tif (value.get_bool())\n\t\t\t\t_canvas.lock()->select_item(shared_from_this());\n\t\t\telse\n\t\t\t\t_canvas.lock()->unselect_item(shared_from_this());\n\t\t}\n\t}\n}\n\n\nvoid\nNodeModule::set_selected(bool b)\n{\n\tif (b != selected()) {\n\t\tModule::set_selected(b);\n\t\tif (App::instance().signal())\n\t\t\tApp::instance().engine()->set_property(_node->path(), \"ingen:selected\", b);\n\t}\n}\n\n\n} \/\/ namespace GUI\n} \/\/ namespace Ingen\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <memory.hpp>\n#include <dispatch.hpp>\n#include <map>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <types.hpp>\n\nnamespace opencl\n{\n static size_t memory_resolution = 1024; \/\/1KB\n\n void setMemStepSize(size_t step_bytes)\n {\n memory_resolution = step_bytes;\n }\n\n size_t getMemStepSize(void)\n {\n return memory_resolution;\n }\n\n \/\/ Manager Class\n \/\/ Dummy used to call garbage collection at the end of the program\n class Manager\n {\n public:\n static bool initialized;\n Manager()\n {\n initialized = true;\n }\n\n ~Manager()\n {\n for(int i = 0; i < (int)getDeviceCount(); i++) {\n setDevice(i);\n garbageCollect();\n pinnedGarbageCollect();\n }\n }\n };\n\n bool Manager::initialized = false;\n\n static void managerInit()\n {\n if(Manager::initialized == false)\n static Manager pm = Manager();\n }\n\n typedef struct\n {\n bool is_free;\n bool is_unlinked;\n size_t bytes;\n } mem_info;\n\n static size_t used_bytes[DeviceManager::MAX_DEVICES] = {0};\n static size_t used_buffers[DeviceManager::MAX_DEVICES] = {0};\n static size_t total_bytes[DeviceManager::MAX_DEVICES] = {0};\n\n typedef std::map<cl::Buffer *, mem_info> mem_t;\n typedef mem_t::iterator mem_iter;\n mem_t memory_maps[DeviceManager::MAX_DEVICES];\n\n static void destroy(cl::Buffer *ptr)\n {\n delete ptr;\n }\n\n void garbageCollect()\n {\n int n = getActiveDeviceId();\n for(mem_iter iter = memory_maps[n].begin();\n iter != memory_maps[n].end(); ++iter) {\n\n if ((iter->second).is_free) {\n\n if (!(iter->second).is_unlinked) {\n destroy(iter->first);\n total_bytes[n] -= iter->second.bytes;\n }\n }\n }\n\n mem_iter memory_curr = memory_maps[n].begin();\n mem_iter memory_end = memory_maps[n].end();\n\n while(memory_curr != memory_end) {\n if (memory_curr->second.is_free && !memory_curr->second.is_unlinked) {\n memory_curr = memory_maps[n].erase(memory_curr);\n } else {\n ++memory_curr;\n }\n }\n }\n\n void printMemInfo(const char *msg, const int device)\n {\n std::cout << msg << std::endl;\n std::cout << \"Memory Map for Device: \" << device << std::endl;\n\n static const std::string head(\"| POINTER | SIZE | AF LOCK | USER LOCK |\");\n static const std::string line(head.size(), '-');\n std::cout << line << std::endl << head << std::endl << line << std::endl;\n\n for(mem_iter iter = memory_maps[device].begin();\n iter != memory_maps[device].end(); ++iter) {\n\n std::string status_af(\"Unknown\");\n std::string status_us(\"Unknown\");\n\n if(!(iter->second.is_free)) status_af = \"Yes\";\n else status_af = \" No\";\n\n if((iter->second.is_unlinked)) status_us = \"Yes\";\n else status_us = \" No\";\n\n std::string unit = \"KB\";\n double size = (double)(iter->second.bytes) \/ 1024;\n if(size >= 1024) {\n size = size \/ 1024;\n unit = \"MB\";\n }\n\n std::cout << \"| \" << std::right << std::setw(14) << iter->first << \" \"\n << \" | \" << std::setw(7) << std::setprecision(4) << size << \" \" << unit\n << \" | \" << std::setw(9) << status_af\n << \" | \" << std::setw(9) << status_us\n << \" |\" << std::endl;\n }\n\n std::cout << line << std::endl;\n }\n\n cl::Buffer *bufferAlloc(const size_t &bytes)\n {\n int n = getActiveDeviceId();\n cl::Buffer *ptr = NULL;\n size_t alloc_bytes = divup(bytes, memory_resolution) * memory_resolution;\n\n if (bytes > 0) {\n\n \/\/ FIXME: Add better checks for garbage collection\n \/\/ Perhaps look at total memory available as a metric\n if (memory_maps[n].size() >= MAX_BUFFERS || used_bytes[n] >= MAX_BYTES) {\n garbageCollect();\n }\n\n for(mem_iter iter = memory_maps[n].begin();\n iter != memory_maps[n].end(); ++iter) {\n\n mem_info info = iter->second;\n\n if ( info.is_free &&\n !info.is_unlinked &&\n info.bytes == alloc_bytes) {\n\n iter->second.is_free = false;\n used_bytes[n] += alloc_bytes;\n used_buffers[n]++;\n return iter->first;\n }\n }\n\n try {\n ptr = new cl::Buffer(getContext(), CL_MEM_READ_WRITE, alloc_bytes);\n } catch(...) {\n garbageCollect();\n ptr = new cl::Buffer(getContext(), CL_MEM_READ_WRITE, alloc_bytes);\n }\n\n mem_info info = {false, false, alloc_bytes};\n memory_maps[n][ptr] = info;\n used_bytes[n] += alloc_bytes;\n used_buffers[n]++;\n total_bytes[n] += alloc_bytes;\n }\n return ptr;\n }\n\n void bufferFree(cl::Buffer *ptr)\n {\n bufferFreeUnlinked(ptr, false);\n }\n\n void bufferFreeUnlinked(cl::Buffer *ptr, bool free_unlinked)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n\n iter->second.is_free = true;\n if ((iter->second).is_unlinked && !free_unlinked) return;\n\n iter->second.is_unlinked = false;\n\n used_bytes[n] -= iter->second.bytes;\n used_buffers[n]--;\n } else {\n destroy(ptr); \/\/ Free it because we are not sure what the size is\n }\n }\n\n void bufferPop(cl::Buffer *ptr)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n iter->second.is_unlinked = true;\n } else {\n\n mem_info info = { false,\n false,\n 100 }; \/\/This number is not relevant\n\n memory_maps[n][ptr] = info;\n }\n }\n\n void bufferPush(cl::Buffer *ptr)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n iter->second.is_unlinked = false;\n }\n }\n\n void deviceMemoryInfo(size_t *alloc_bytes, size_t *alloc_buffers,\n size_t *lock_bytes, size_t *lock_buffers)\n {\n int n = getActiveDeviceId();\n if (alloc_bytes ) *alloc_bytes = total_bytes[n];\n if (alloc_buffers ) *alloc_buffers = memory_maps[n].size();\n if (lock_bytes ) *lock_bytes = used_bytes[n];\n if (lock_buffers ) *lock_buffers = used_buffers[n];\n }\n\n template<typename T>\n T *memAlloc(const size_t &elements)\n {\n managerInit();\n return (T *)bufferAlloc(elements * sizeof(T));\n }\n\n template<typename T>\n void memFree(T *ptr)\n {\n return bufferFreeUnlinked((cl::Buffer *)ptr, false);\n }\n\n template<typename T>\n void memFreeUnlinked(T *ptr, bool free_unlinked)\n {\n return bufferFreeUnlinked((cl::Buffer *)ptr, free_unlinked);\n }\n\n template<typename T>\n void memPop(const T *ptr)\n {\n return bufferPop((cl::Buffer *)ptr);\n }\n\n template<typename T>\n void memPush(const T *ptr)\n {\n return bufferPush((cl::Buffer *)ptr);\n }\n\n \/\/ pinned memory manager\n typedef struct {\n cl::Buffer *buf;\n mem_info info;\n } pinned_info;\n\n typedef std::map<void*, pinned_info> pinned_t;\n typedef pinned_t::iterator pinned_iter;\n pinned_t pinned_maps[DeviceManager::MAX_DEVICES];\n static size_t pinned_used_bytes = 0;\n\n static void pinnedDestroy(cl::Buffer *buf, void *ptr)\n {\n getQueue().enqueueUnmapMemObject(*buf, (void *)ptr);\n destroy(buf);\n }\n\n void pinnedGarbageCollect()\n {\n int n = getActiveDeviceId();\n for(auto &iter : pinned_maps[n]) {\n if ((iter.second).info.is_free) {\n pinnedDestroy(iter.second.buf, iter.first);\n }\n }\n\n pinned_iter memory_curr = pinned_maps[n].begin();\n pinned_iter memory_end = pinned_maps[n].end();\n\n while(memory_curr != memory_end) {\n if (memory_curr->second.info.is_free) {\n memory_curr = pinned_maps[n].erase(memory_curr);\n } else {\n ++memory_curr;\n }\n }\n\n }\n\n void *pinnedBufferAlloc(const size_t &bytes)\n {\n void *ptr = NULL;\n int n = getActiveDeviceId();\n \/\/ Allocate the higher megabyte. Overhead of creating pinned memory is\n \/\/ more so we want more resuable memory.\n size_t alloc_bytes = divup(bytes, 1048576) * 1048576;\n\n if (bytes > 0) {\n cl::Buffer *buf = NULL;\n\n \/\/ FIXME: Add better checks for garbage collection\n \/\/ Perhaps look at total memory available as a metric\n if (pinned_maps[n].size() >= MAX_BUFFERS || pinned_used_bytes >= MAX_BYTES) {\n pinnedGarbageCollect();\n }\n\n for(pinned_iter iter = pinned_maps[n].begin();\n iter != pinned_maps[n].end(); ++iter) {\n\n mem_info info = iter->second.info;\n if (info.is_free && info.bytes == alloc_bytes) {\n iter->second.info.is_free = false;\n pinned_used_bytes += alloc_bytes;\n return iter->first;\n }\n }\n\n try {\n buf = new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, alloc_bytes);\n\n ptr = getQueue().enqueueMapBuffer(*buf, true, CL_MAP_READ|CL_MAP_WRITE,\n 0, alloc_bytes);\n } catch(...) {\n pinnedGarbageCollect();\n buf = new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, alloc_bytes);\n\n ptr = getQueue().enqueueMapBuffer(*buf, true, CL_MAP_READ|CL_MAP_WRITE,\n 0, alloc_bytes);\n }\n mem_info info = {false, false, alloc_bytes};\n pinned_info pt = {buf, info};\n pinned_maps[n][ptr] = pt;\n pinned_used_bytes += alloc_bytes;\n }\n return ptr;\n }\n\n void pinnedBufferFree(void *ptr)\n {\n int n = getActiveDeviceId();\n pinned_iter iter = pinned_maps[n].find(ptr);\n\n if (iter != pinned_maps[n].end()) {\n iter->second.info.is_free = true;\n pinned_used_bytes -= iter->second.info.bytes;\n } else {\n pinnedDestroy(iter->second.buf, ptr); \/\/ Free it because we are not sure what the size is\n pinned_maps[n].erase(iter);\n }\n }\n\n template<typename T>\n T* pinnedAlloc(const size_t &elements)\n {\n managerInit();\n return (T *)pinnedBufferAlloc(elements * sizeof(T));\n }\n\n template<typename T>\n void pinnedFree(T* ptr)\n {\n return pinnedBufferFree((void *) ptr);\n }\n\n#define INSTANTIATE(T) \\\n template T* memAlloc(const size_t &elements); \\\n template void memFree(T* ptr); \\\n template void memFreeUnlinked(T* ptr, bool free_unlinked); \\\n template void memPop(const T* ptr); \\\n template void memPush(const T* ptr); \\\n template T* pinnedAlloc(const size_t &elements); \\\n template void pinnedFree(T* ptr); \\\n\n INSTANTIATE(float)\n INSTANTIATE(cfloat)\n INSTANTIATE(double)\n INSTANTIATE(cdouble)\n INSTANTIATE(int)\n INSTANTIATE(uint)\n INSTANTIATE(char)\n INSTANTIATE(uchar)\n INSTANTIATE(intl)\n INSTANTIATE(uintl)\n INSTANTIATE(short)\n INSTANTIATE(ushort)\n}\n<commit_msg>Renamed is_free -> mngr_lock and is_unlinked -> user_lock in opencl memory mngr<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <memory.hpp>\n#include <dispatch.hpp>\n#include <map>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <types.hpp>\n\nnamespace opencl\n{\n static size_t memory_resolution = 1024; \/\/1KB\n\n void setMemStepSize(size_t step_bytes)\n {\n memory_resolution = step_bytes;\n }\n\n size_t getMemStepSize(void)\n {\n return memory_resolution;\n }\n\n \/\/ Manager Class\n \/\/ Dummy used to call garbage collection at the end of the program\n class Manager\n {\n public:\n static bool initialized;\n Manager()\n {\n initialized = true;\n }\n\n ~Manager()\n {\n for(int i = 0; i < (int)getDeviceCount(); i++) {\n setDevice(i);\n garbageCollect();\n pinnedGarbageCollect();\n }\n }\n };\n\n bool Manager::initialized = false;\n\n static void managerInit()\n {\n if(Manager::initialized == false)\n static Manager pm = Manager();\n }\n\n typedef struct\n {\n bool mngr_lock;\n bool user_lock;\n size_t bytes;\n } mem_info;\n\n static size_t used_bytes[DeviceManager::MAX_DEVICES] = {0};\n static size_t used_buffers[DeviceManager::MAX_DEVICES] = {0};\n static size_t total_bytes[DeviceManager::MAX_DEVICES] = {0};\n\n typedef std::map<cl::Buffer *, mem_info> mem_t;\n typedef mem_t::iterator mem_iter;\n mem_t memory_maps[DeviceManager::MAX_DEVICES];\n\n static void destroy(cl::Buffer *ptr)\n {\n delete ptr;\n }\n\n void garbageCollect()\n {\n int n = getActiveDeviceId();\n for(mem_iter iter = memory_maps[n].begin();\n iter != memory_maps[n].end(); ++iter) {\n\n if (!(iter->second).mngr_lock) {\n\n if (!(iter->second).user_lock) {\n destroy(iter->first);\n total_bytes[n] -= iter->second.bytes;\n }\n }\n }\n\n mem_iter memory_curr = memory_maps[n].begin();\n mem_iter memory_end = memory_maps[n].end();\n\n while(memory_curr != memory_end) {\n if (!memory_curr->second.mngr_lock && !memory_curr->second.user_lock) {\n memory_curr = memory_maps[n].erase(memory_curr);\n } else {\n ++memory_curr;\n }\n }\n }\n\n void printMemInfo(const char *msg, const int device)\n {\n std::cout << msg << std::endl;\n std::cout << \"Memory Map for Device: \" << device << std::endl;\n\n static const std::string head(\"| POINTER | SIZE | AF LOCK | USER LOCK |\");\n static const std::string line(head.size(), '-');\n std::cout << line << std::endl << head << std::endl << line << std::endl;\n\n for(mem_iter iter = memory_maps[device].begin();\n iter != memory_maps[device].end(); ++iter) {\n\n std::string status_mngr(\"Unknown\");\n std::string status_user(\"Unknown\");\n\n if(iter->second.mngr_lock) status_mngr = \"Yes\";\n else status_mngr = \" No\";\n\n if(iter->second.user_lock) status_user = \"Yes\";\n else status_user = \" No\";\n\n std::string unit = \"KB\";\n double size = (double)(iter->second.bytes) \/ 1024;\n if(size >= 1024) {\n size = size \/ 1024;\n unit = \"MB\";\n }\n\n std::cout << \"| \" << std::right << std::setw(14) << iter->first << \" \"\n << \" | \" << std::setw(7) << std::setprecision(4) << size << \" \" << unit\n << \" | \" << std::setw(9) << status_mngr\n << \" | \" << std::setw(9) << status_user\n << \" |\" << std::endl;\n }\n\n std::cout << line << std::endl;\n }\n\n cl::Buffer *bufferAlloc(const size_t &bytes)\n {\n int n = getActiveDeviceId();\n cl::Buffer *ptr = NULL;\n size_t alloc_bytes = divup(bytes, memory_resolution) * memory_resolution;\n\n if (bytes > 0) {\n\n \/\/ FIXME: Add better checks for garbage collection\n \/\/ Perhaps look at total memory available as a metric\n if (memory_maps[n].size() >= MAX_BUFFERS || used_bytes[n] >= MAX_BYTES) {\n garbageCollect();\n }\n\n for(mem_iter iter = memory_maps[n].begin();\n iter != memory_maps[n].end(); ++iter) {\n\n mem_info info = iter->second;\n\n if (!info.mngr_lock &&\n !info.user_lock &&\n info.bytes == alloc_bytes) {\n\n iter->second.mngr_lock = true;\n used_bytes[n] += alloc_bytes;\n used_buffers[n]++;\n return iter->first;\n }\n }\n\n try {\n ptr = new cl::Buffer(getContext(), CL_MEM_READ_WRITE, alloc_bytes);\n } catch(...) {\n garbageCollect();\n ptr = new cl::Buffer(getContext(), CL_MEM_READ_WRITE, alloc_bytes);\n }\n\n mem_info info = {true, false, alloc_bytes};\n memory_maps[n][ptr] = info;\n used_bytes[n] += alloc_bytes;\n used_buffers[n]++;\n total_bytes[n] += alloc_bytes;\n }\n return ptr;\n }\n\n void bufferFree(cl::Buffer *ptr)\n {\n bufferFreeUnlinked(ptr, false);\n }\n\n void bufferFreeUnlinked(cl::Buffer *ptr, bool free_unlinked)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n\n iter->second.mngr_lock = false;\n if ((iter->second).user_lock && !free_unlinked) return;\n\n iter->second.user_lock = false;\n\n used_bytes[n] -= iter->second.bytes;\n used_buffers[n]--;\n } else {\n destroy(ptr); \/\/ Free it because we are not sure what the size is\n }\n }\n\n void bufferPop(cl::Buffer *ptr)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n iter->second.user_lock = true;\n } else {\n\n mem_info info = { true,\n true,\n 100 }; \/\/This number is not relevant\n\n memory_maps[n][ptr] = info;\n }\n }\n\n void bufferPush(cl::Buffer *ptr)\n {\n int n = getActiveDeviceId();\n mem_iter iter = memory_maps[n].find(ptr);\n\n if (iter != memory_maps[n].end()) {\n iter->second.user_lock = false;\n }\n }\n\n void deviceMemoryInfo(size_t *alloc_bytes, size_t *alloc_buffers,\n size_t *lock_bytes, size_t *lock_buffers)\n {\n int n = getActiveDeviceId();\n if (alloc_bytes ) *alloc_bytes = total_bytes[n];\n if (alloc_buffers ) *alloc_buffers = memory_maps[n].size();\n if (lock_bytes ) *lock_bytes = used_bytes[n];\n if (lock_buffers ) *lock_buffers = used_buffers[n];\n }\n\n template<typename T>\n T *memAlloc(const size_t &elements)\n {\n managerInit();\n return (T *)bufferAlloc(elements * sizeof(T));\n }\n\n template<typename T>\n void memFree(T *ptr)\n {\n return bufferFreeUnlinked((cl::Buffer *)ptr, false);\n }\n\n template<typename T>\n void memFreeUnlinked(T *ptr, bool free_unlinked)\n {\n return bufferFreeUnlinked((cl::Buffer *)ptr, free_unlinked);\n }\n\n template<typename T>\n void memPop(const T *ptr)\n {\n return bufferPop((cl::Buffer *)ptr);\n }\n\n template<typename T>\n void memPush(const T *ptr)\n {\n return bufferPush((cl::Buffer *)ptr);\n }\n\n \/\/ pinned memory manager\n typedef struct {\n cl::Buffer *buf;\n mem_info info;\n } pinned_info;\n\n typedef std::map<void*, pinned_info> pinned_t;\n typedef pinned_t::iterator pinned_iter;\n pinned_t pinned_maps[DeviceManager::MAX_DEVICES];\n static size_t pinned_used_bytes = 0;\n\n static void pinnedDestroy(cl::Buffer *buf, void *ptr)\n {\n getQueue().enqueueUnmapMemObject(*buf, (void *)ptr);\n destroy(buf);\n }\n\n void pinnedGarbageCollect()\n {\n int n = getActiveDeviceId();\n for(auto &iter : pinned_maps[n]) {\n if (!(iter.second).info.mngr_lock) {\n pinnedDestroy(iter.second.buf, iter.first);\n }\n }\n\n pinned_iter memory_curr = pinned_maps[n].begin();\n pinned_iter memory_end = pinned_maps[n].end();\n\n while(memory_curr != memory_end) {\n if (!memory_curr->second.info.mngr_lock) {\n memory_curr = pinned_maps[n].erase(memory_curr);\n } else {\n ++memory_curr;\n }\n }\n\n }\n\n void *pinnedBufferAlloc(const size_t &bytes)\n {\n void *ptr = NULL;\n int n = getActiveDeviceId();\n \/\/ Allocate the higher megabyte. Overhead of creating pinned memory is\n \/\/ more so we want more resuable memory.\n size_t alloc_bytes = divup(bytes, 1048576) * 1048576;\n\n if (bytes > 0) {\n cl::Buffer *buf = NULL;\n\n \/\/ FIXME: Add better checks for garbage collection\n \/\/ Perhaps look at total memory available as a metric\n if (pinned_maps[n].size() >= MAX_BUFFERS || pinned_used_bytes >= MAX_BYTES) {\n pinnedGarbageCollect();\n }\n\n for(pinned_iter iter = pinned_maps[n].begin();\n iter != pinned_maps[n].end(); ++iter) {\n\n mem_info info = iter->second.info;\n if (!info.mngr_lock && info.bytes == alloc_bytes) {\n iter->second.info.mngr_lock = true;\n pinned_used_bytes += alloc_bytes;\n return iter->first;\n }\n }\n\n try {\n buf = new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, alloc_bytes);\n\n ptr = getQueue().enqueueMapBuffer(*buf, true, CL_MAP_READ|CL_MAP_WRITE,\n 0, alloc_bytes);\n } catch(...) {\n pinnedGarbageCollect();\n buf = new cl::Buffer(getContext(), CL_MEM_ALLOC_HOST_PTR, alloc_bytes);\n\n ptr = getQueue().enqueueMapBuffer(*buf, true, CL_MAP_READ|CL_MAP_WRITE,\n 0, alloc_bytes);\n }\n mem_info info = {true, false, alloc_bytes};\n pinned_info pt = {buf, info};\n pinned_maps[n][ptr] = pt;\n pinned_used_bytes += alloc_bytes;\n }\n return ptr;\n }\n\n void pinnedBufferFree(void *ptr)\n {\n int n = getActiveDeviceId();\n pinned_iter iter = pinned_maps[n].find(ptr);\n\n if (iter != pinned_maps[n].end()) {\n iter->second.info.mngr_lock = false;\n pinned_used_bytes -= iter->second.info.bytes;\n } else {\n pinnedDestroy(iter->second.buf, ptr); \/\/ Free it because we are not sure what the size is\n pinned_maps[n].erase(iter);\n }\n }\n\n template<typename T>\n T* pinnedAlloc(const size_t &elements)\n {\n managerInit();\n return (T *)pinnedBufferAlloc(elements * sizeof(T));\n }\n\n template<typename T>\n void pinnedFree(T* ptr)\n {\n return pinnedBufferFree((void *) ptr);\n }\n\n#define INSTANTIATE(T) \\\n template T* memAlloc(const size_t &elements); \\\n template void memFree(T* ptr); \\\n template void memFreeUnlinked(T* ptr, bool free_unlinked); \\\n template void memPop(const T* ptr); \\\n template void memPush(const T* ptr); \\\n template T* pinnedAlloc(const size_t &elements); \\\n template void pinnedFree(T* ptr); \\\n\n INSTANTIATE(float)\n INSTANTIATE(cfloat)\n INSTANTIATE(double)\n INSTANTIATE(cdouble)\n INSTANTIATE(int)\n INSTANTIATE(uint)\n INSTANTIATE(char)\n INSTANTIATE(uchar)\n INSTANTIATE(intl)\n INSTANTIATE(uintl)\n INSTANTIATE(short)\n INSTANTIATE(ushort)\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <kcombobox.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <klineedit.h>\n\n#include <konnectormanager.h>\n#include <configwidget.h>\n\n#include \"konnectorwizard.h\"\n\n#include \"konnectorprofilewizardintro.h\"\n#include \"konnectorwizardoutro.h\"\n\nusing namespace KSync;\n\nnamespace {\n\nconst int AREA = 5210;\n\nvoid setCurrent( const QString& str, QComboBox* box, bool insert = true )\n{\n if ( str.isEmpty() ) return;\n uint b = box->count();\n for ( uint i = 0; i < b; i++ ) {\n if ( box->text(i) == str ) {\n box->setCurrentItem( i );\n return;\n }\n }\n if ( !insert ) return;\n\n box->insertItem( str );\n box->setCurrentItem( b );\n}\n\n}\n\n\nKonnectorWizard::KonnectorWizard( KonnectorManager *manager )\n : KWizard( 0, \"wizard\", true ), m_manager( manager )\n{\n m_isEdit = false;\n m_conf = 0;\n initUI();\n}\n\nKonnectorWizard::KonnectorWizard( KonnectorManager* manager,\n const KonnectorProfile &prof )\n : KWizard( 0, \"wizard\", true ), m_manager( manager)\n{\n m_isEdit = true;\n m_kaps = prof.kapabilities();\n m_conf = 0;\n initUI();\n\n \/* init the ui *\/\n m_outro->lneName->setText( prof.name() );\n kdDebug(AREA) << \"Current Identify is \" << prof.device().name() << \" \" << prof.device().identify() << endl;\n setCurrent( prof.device().name(), m_intro->cmbDevice, false );\n kdDebug(AREA) << \"Current entry is now \" << m_intro->cmbDevice->currentText() << endl;\n slotKonChanged( m_intro->cmbDevice->currentText() );\n}\n\nKonnectorWizard::~KonnectorWizard()\n{\n}\n\nKonnectorProfile KonnectorWizard::profile() const\n{\n KonnectorProfile prof;\n if ( m_conf ) {\n prof.setKapabilities( m_conf->capabilities() );\n prof.setDevice( byString( m_intro->cmbDevice->currentText() ) );\n prof.setName( m_outro->lneName->text() );\n }\n\n return prof;\n}\n\n\/*\n * let's add some pages\n * and make the Configure widget be kewl\n * basicly we need to recreate it on\n *\n *\/\nvoid KonnectorWizard::initUI()\n{\n m_conf = 0;\n m_intro = new KonnectorProfileWizardIntro();\n m_outro = new KonnectorWizardOutro();\n addPage( m_intro, \"Profile\");\n addPage( m_outro, \"Outro\");\n setFinishEnabled( m_outro, true );\n\n Device::ValueList list = m_manager->query();\n Device::ValueList::Iterator it;\n m_current =i18n(\"Please choose a Konnector\");\n m_intro->cmbDevice->insertItem( m_current );\n for (it = list.begin(); it != list.end(); ++it ) {\n\tkdDebug(AREA) << \"Inserting into Combo \" << (*it).name() << \" \" << (*it).identify() << endl;\n m_intro->cmbDevice->insertItem( (*it).name() );\n m_devices.insert( (*it).name(), (*it) );\n }\n \/\/ connect to textchanges\n connect(m_intro->cmbDevice, SIGNAL(activated(const QString&) ),\n SLOT(slotKonChanged(const QString&) ) );\n}\n\n\/*\n * If the Device Combobox changed we need to update the\n * Configuration Tab\n * First check tif the selection changed\n * Then check if the selection changed to the Kapabilities\n * giving as parameter\n * then recreate the widget\n *\/\nvoid KonnectorWizard::slotKonChanged( const QString& str)\n{\n if ( str == m_current ) \/\/ the selection was not changed\n return;\n if ( str == i18n(\"Please choose a Konnector\") ) {\n kdDebug(5210) << \"Connector \" << endl;\n delete m_conf;\n m_conf =0;\n return;\n }\n m_current = str;\n\n delete m_conf;\n m_conf = 0;\n\n Device dev = byString( str );\n\n \/\/ load the Konnector for getting a ConfigureWidget\n Konnector *k = m_manager->load( dev );\n if ( !k ) return;\n\n if( !m_isEdit )\n m_conf = m_manager->configWidget( k, this, \"config\" ); \/\/ never 0\n else\n m_conf = m_manager->configWidget( k, m_kaps, this, \"config\" );\n\n insertPage(m_conf, i18n(\"Configure\"), 1 );\n m_manager->unload( k );\n}\n\nDevice KonnectorWizard::byString( const QString& str ) const\n{\n return m_devices[str];\n}\n\n\n#include \"konnectorwizard.moc\"\n<commit_msg>Fix creation and editing of Konnectors which don't have a config widget.<commit_after>\n#include <kcombobox.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <klineedit.h>\n\n#include <konnectormanager.h>\n#include <configwidget.h>\n\n#include \"konnectorwizard.h\"\n\n#include \"konnectorprofilewizardintro.h\"\n#include \"konnectorwizardoutro.h\"\n\nusing namespace KSync;\n\nnamespace {\n\nconst int AREA = 5210;\n\nvoid setCurrent( const QString& str, QComboBox* box, bool insert = true )\n{\n if ( str.isEmpty() ) return;\n uint b = box->count();\n for ( uint i = 0; i < b; i++ ) {\n if ( box->text(i) == str ) {\n box->setCurrentItem( i );\n return;\n }\n }\n if ( !insert ) return;\n\n box->insertItem( str );\n box->setCurrentItem( b );\n}\n\n}\n\n\nKonnectorWizard::KonnectorWizard( KonnectorManager *manager )\n : KWizard( 0, \"wizard\", true ), m_manager( manager )\n{\n m_isEdit = false;\n m_conf = 0;\n initUI();\n}\n\nKonnectorWizard::KonnectorWizard( KonnectorManager* manager,\n const KonnectorProfile &prof )\n : KWizard( 0, \"wizard\", true ), m_manager( manager)\n{\n m_isEdit = true;\n m_kaps = prof.kapabilities();\n m_conf = 0;\n initUI();\n\n \/* init the ui *\/\n m_outro->lneName->setText( prof.name() );\n kdDebug(AREA) << \"Current Identify is \" << prof.device().name() << \" \" << prof.device().identify() << endl;\n setCurrent( prof.device().name(), m_intro->cmbDevice, false );\n kdDebug(AREA) << \"Current entry is now \" << m_intro->cmbDevice->currentText() << endl;\n slotKonChanged( m_intro->cmbDevice->currentText() );\n}\n\nKonnectorWizard::~KonnectorWizard()\n{\n}\n\nKonnectorProfile KonnectorWizard::profile() const\n{\n KonnectorProfile prof;\n\n if ( m_conf ) {\n prof.setKapabilities( m_conf->capabilities() );\n }\n\n prof.setDevice( byString( m_intro->cmbDevice->currentText() ) );\n prof.setName( m_outro->lneName->text() );\n\n return prof;\n}\n\n\/*\n * let's add some pages\n * and make the Configure widget be kewl\n * basicly we need to recreate it on\n *\n *\/\nvoid KonnectorWizard::initUI()\n{\n m_conf = 0;\n m_intro = new KonnectorProfileWizardIntro();\n m_outro = new KonnectorWizardOutro();\n addPage( m_intro, \"Profile\");\n addPage( m_outro, \"Outro\");\n setFinishEnabled( m_outro, true );\n\n Device::ValueList list = m_manager->query();\n Device::ValueList::Iterator it;\n m_current =i18n(\"Please choose a Konnector\");\n m_intro->cmbDevice->insertItem( m_current );\n for (it = list.begin(); it != list.end(); ++it ) {\n\tkdDebug(AREA) << \"Inserting into Combo \" << (*it).name() << \" \" << (*it).identify() << endl;\n m_intro->cmbDevice->insertItem( (*it).name() );\n m_devices.insert( (*it).name(), (*it) );\n }\n \/\/ connect to textchanges\n connect(m_intro->cmbDevice, SIGNAL(activated(const QString&) ),\n SLOT(slotKonChanged(const QString&) ) );\n}\n\n\/*\n * If the Device Combobox changed we need to update the\n * Configuration Tab\n * First check tif the selection changed\n * Then check if the selection changed to the Kapabilities\n * giving as parameter\n * then recreate the widget\n *\/\nvoid KonnectorWizard::slotKonChanged( const QString& str)\n{\n if ( str == m_current ) \/\/ the selection was not changed\n return;\n if ( str == i18n(\"Please choose a Konnector\") ) {\n kdDebug(5210) << \"Connector \" << endl;\n delete m_conf;\n m_conf =0;\n return;\n }\n m_current = str;\n\n delete m_conf;\n m_conf = 0;\n\n Device dev = byString( str );\n\n \/\/ load the Konnector for getting a ConfigureWidget\n Konnector *k = m_manager->load( dev );\n if ( !k ) return;\n\n if( !m_isEdit )\n m_conf = m_manager->configWidget( k, this, \"config\" ); \/\/ never 0\n else\n m_conf = m_manager->configWidget( k, m_kaps, this, \"config\" );\n\n insertPage(m_conf, i18n(\"Configure\"), 1 );\n m_manager->unload( k );\n}\n\nDevice KonnectorWizard::byString( const QString& str ) const\n{\n return m_devices[str];\n}\n\n\n#include \"konnectorwizard.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2015-2019, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n\n#include <fg\/defines.h>\n#include <fg\/exception.h>\n#include <err_common.hpp>\n\n#include <glbinding\/gl\/gl.h>\n#include <glbinding\/Binding.h>\n\n#define GLM_FORCE_RADIANS\n#include <glm\/glm.hpp>\n#include <glm\/gtx\/string_cast.hpp>\n\n#include <vector>\n#include <iterator>\n\nstatic const float BLACK[] = {0.0f , 0.0f , 0.0f , 1.0f};\nstatic const float GRAY[] = {0.85f , 0.85f , 0.85f , 1.0f};\nstatic const float WHITE[] = {1.0f , 1.0f , 1.0f , 1.0f};\nstatic const float AF_BLUE[] = {0.0588f , 0.1137f , 0.2745f , 1.0f};\nstatic const glm::mat4 IDENTITY(1.0f);\n\n\/* clamp the float to [0-1] range\n *\n * @pValue is the value to be clamped\n *\/\nfloat clampTo01(const float pValue);\n\n\/* Convert forge type enum to OpenGL enum for GL_* type\n *\n * @pValue is the forge type enum\n *\n * @return GL_* typedef for data type\n *\/\ngl::GLenum dtype2gl(const forge::dtype pValue);\n\n\/* Convert forge channel format enum to OpenGL enum to indicate color component layout\n *\n * @pValue is the forge type enum\n *\n * @return OpenGL enum indicating color component layout\n *\/\ngl::GLenum ctype2gl(const forge::ChannelFormat pMode);\n\n\/* Convert forge channel format enum to OpenGL enum to indicate color component layout\n *\n * This function is used to group color component layout formats based\n * on number of components.\n *\n * @pValue is the forge type enum\n *\n * @return OpenGL enum indicating color component layout\n *\/\ngl::GLenum ictype2gl(const forge::ChannelFormat pMode);\n\n\/* Create OpenGL buffer object\n *\n * @pTarget should be either GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER\n * @pSize is the size of the data in bytes\n * @pPtr is the pointer to host data. This can be NULL\n * @pUsage should be either GL_STATIC_DRAW or GL_DYNAMIC_DRAW\n *\n * @return OpenGL buffer object identifier\n *\/\ntemplate<typename T>\ngl::GLuint createBuffer(gl::GLenum pTarget, size_t pSize, const T* pPtr, gl::GLenum pUsage)\n{\n gl::GLuint retVal = 0;\n gl::glGenBuffers(1, &retVal);\n gl::glBindBuffer(pTarget, retVal);\n gl::glBufferData(pTarget, pSize*sizeof(T), pPtr, pUsage);\n gl::glBindBuffer(pTarget, 0);\n return retVal;\n}\n\n#ifdef OS_WIN\n\/* Get the paths to font files in Windows system directory\n *\n * @pFiles is the output vector to which font file paths are appended to.\n * @pDir is the directory from which font files are looked up\n * @pExt is the target font file extension we are looking for.\n *\/\nvoid getFontFilePaths(std::vector<std::string>& pFiles,\n const std::string& pDir,\n const std::string& pExt);\n#endif\n\n\/* Convert float value to string with given precision\n *\n * @pVal is the float value whose string representation is requested.\n * @pPrecision is the precision of the float used while converting to string.\n *\n * @return is the string representation of input float value.\n *\/\nstd::string toString(const float pVal, const int pPrecision = 2);\n\n\/* Get a vertex buffer object for quad that spans the screen\n *\/\ngl::GLuint screenQuadVBO(const int pWindowId);\n\n\/* Get a vertex array object that uses screenQuadVBO\n *\n * This vertex array object when bound and rendered, basically\n * draws a rectangle over the entire screen with standard\n * texture coordinates. Use of this vao would be as follows\n *\n * `glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);`\n *\/\ngl::GLuint screenQuadVAO(const int pWindowId);\n\n\/* Print glm::mat4 to std::cout stream *\/\nstd::ostream& operator<<(std::ostream&, const glm::mat4&);\n\n\/* get the point of the surface of track ball *\/\nglm::vec3 trackballPoint(const float pX, const float pY,\n const float pWidth, const float pHeight);\n\nnamespace forge\n{\nnamespace opengl\n{\n\ntypedef unsigned int uint;\ntypedef unsigned short ushort;\ntypedef unsigned char uchar;\n\nclass ShaderProgram {\n private:\n gl::GLuint mVertex;\n gl::GLuint mFragment;\n gl::GLuint mGeometry;\n gl::GLuint mProgram;\n\n public:\n ShaderProgram(const char* pVertShaderSrc,\n const char* pFragShaderSrc,\n const char* pGeomShaderSrc=NULL);\n\n ~ShaderProgram();\n\n gl::GLuint getProgramId() const;\n\n gl::GLuint getUniformLocation(const char* pAttributeName);\n gl::GLuint getUniformBlockIndex(const char* pAttributeName);\n gl::GLuint getAttributeLocation(const char* pAttributeName);\n\n void bind();\n void unbind();\n};\n\n\/* Basic renderable class\n *\n * Any object that is renderable to a window should inherit from this\n * class.\n *\/\nclass AbstractRenderable {\n protected:\n \/* OpenGL buffer objects *\/\n gl::GLuint mVBO;\n gl::GLuint mCBO;\n gl::GLuint mABO;\n size_t mVBOSize;\n size_t mCBOSize;\n size_t mABOSize;\n gl::GLfloat mColor[4];\n gl::GLfloat mRange[6];\n std::string mLegend;\n bool mIsPVCOn;\n bool mIsPVAOn;\n\n public:\n \/* Getter functions for OpenGL buffer objects\n * identifiers and their size in bytes\n *\n * vbo is for vertices\n * cbo is for colors of those vertices\n * abo is for alpha values for those vertices\n *\/\n gl::GLuint vbo() const { return mVBO; }\n gl::GLuint cbo() { mIsPVCOn = true; return mCBO; }\n gl::GLuint abo() { mIsPVAOn = true; return mABO; }\n size_t vboSize() const { return mVBOSize; }\n size_t cboSize() const { return mCBOSize; }\n size_t aboSize() const { return mABOSize; }\n\n \/* Set color for rendering\n *\/\n void setColor(const float pRed, const float pGreen,\n const float pBlue, const float pAlpha) {\n mColor[0] = clampTo01(pRed);\n mColor[1] = clampTo01(pGreen);\n mColor[2] = clampTo01(pBlue);\n mColor[3] = clampTo01(pAlpha);\n }\n\n \/* Get renderable solid color\n *\/\n void getColor(float& pRed, float& pGreen, float& pBlue, float& pAlpha) {\n pRed = mColor[0];\n pGreen = mColor[1];\n pBlue = mColor[2];\n pAlpha = mColor[3];\n }\n\n \/* Set legend for rendering\n *\/\n void setLegend(const char* pLegend) {\n mLegend = std::string(pLegend);\n }\n\n \/* Get legend string\n *\/\n const std::string& legend() const {\n return mLegend;\n }\n\n \/* Set 3d world coordinate ranges\n *\n * This method is mostly used for charts and related renderables\n *\/\n void setRanges(const float pMinX, const float pMaxX,\n const float pMinY, const float pMaxY,\n const float pMinZ, const float pMaxZ) {\n mRange[0] = pMinX; mRange[1] = pMaxX;\n mRange[2] = pMinY; mRange[3] = pMaxY;\n mRange[4] = pMinZ; mRange[5] = pMaxZ;\n }\n\n \/* virtual function to set colormap, a derviced class might\n * use it or ignore it if it doesnt have a need for color maps.\n *\/\n virtual void setColorMapUBOParams(const gl::GLuint pUBO, const gl::GLuint pSize) {\n }\n\n \/* render is a pure virtual function.\n *\n * @pWindowId is the window identifier\n * @pX is the X coordinate at which the currently bound viewport begins.\n * @pX is the Y coordinate at which the currently bound viewport begins.\n * @pViewPortWidth is the width of the currently bound viewport.\n * @pViewPortHeight is the height of the currently bound viewport.\n *\n * Any concrete class that inherits AbstractRenderable class needs to\n * implement this method to render their OpenGL objects to\n * the currently bound viewport of the Window bearing identifier pWindowId.\n *\n * @return nothing.\n *\/\n virtual void render(const int pWindowId,\n const int pX, const int pY, const int pVPW, const int pVPH,\n const glm::mat4 &pView, const glm::mat4 &pOrient) = 0;\n};\n\n}\n}\n<commit_msg>Add constructor to AbstractRenderable Class<commit_after>\/*******************************************************\n * Copyright (c) 2015-2019, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n\n#include <fg\/defines.h>\n#include <fg\/exception.h>\n#include <err_common.hpp>\n\n#include <glbinding\/gl\/gl.h>\n#include <glbinding\/Binding.h>\n\n#define GLM_FORCE_RADIANS\n#include <glm\/glm.hpp>\n#include <glm\/gtx\/string_cast.hpp>\n\n#include <vector>\n#include <iterator>\n\nstatic const float BLACK[] = {0.0f , 0.0f , 0.0f , 1.0f};\nstatic const float GRAY[] = {0.85f , 0.85f , 0.85f , 1.0f};\nstatic const float WHITE[] = {1.0f , 1.0f , 1.0f , 1.0f};\nstatic const float AF_BLUE[] = {0.0588f , 0.1137f , 0.2745f , 1.0f};\nstatic const glm::mat4 IDENTITY(1.0f);\n\n\/* clamp the float to [0-1] range\n *\n * @pValue is the value to be clamped\n *\/\nfloat clampTo01(const float pValue);\n\n\/* Convert forge type enum to OpenGL enum for GL_* type\n *\n * @pValue is the forge type enum\n *\n * @return GL_* typedef for data type\n *\/\ngl::GLenum dtype2gl(const forge::dtype pValue);\n\n\/* Convert forge channel format enum to OpenGL enum to indicate color component layout\n *\n * @pValue is the forge type enum\n *\n * @return OpenGL enum indicating color component layout\n *\/\ngl::GLenum ctype2gl(const forge::ChannelFormat pMode);\n\n\/* Convert forge channel format enum to OpenGL enum to indicate color component layout\n *\n * This function is used to group color component layout formats based\n * on number of components.\n *\n * @pValue is the forge type enum\n *\n * @return OpenGL enum indicating color component layout\n *\/\ngl::GLenum ictype2gl(const forge::ChannelFormat pMode);\n\n\/* Create OpenGL buffer object\n *\n * @pTarget should be either GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER\n * @pSize is the size of the data in bytes\n * @pPtr is the pointer to host data. This can be NULL\n * @pUsage should be either GL_STATIC_DRAW or GL_DYNAMIC_DRAW\n *\n * @return OpenGL buffer object identifier\n *\/\ntemplate<typename T>\ngl::GLuint createBuffer(gl::GLenum pTarget, size_t pSize, const T* pPtr, gl::GLenum pUsage)\n{\n gl::GLuint retVal = 0;\n gl::glGenBuffers(1, &retVal);\n gl::glBindBuffer(pTarget, retVal);\n gl::glBufferData(pTarget, pSize*sizeof(T), pPtr, pUsage);\n gl::glBindBuffer(pTarget, 0);\n return retVal;\n}\n\n#ifdef OS_WIN\n\/* Get the paths to font files in Windows system directory\n *\n * @pFiles is the output vector to which font file paths are appended to.\n * @pDir is the directory from which font files are looked up\n * @pExt is the target font file extension we are looking for.\n *\/\nvoid getFontFilePaths(std::vector<std::string>& pFiles,\n const std::string& pDir,\n const std::string& pExt);\n#endif\n\n\/* Convert float value to string with given precision\n *\n * @pVal is the float value whose string representation is requested.\n * @pPrecision is the precision of the float used while converting to string.\n *\n * @return is the string representation of input float value.\n *\/\nstd::string toString(const float pVal, const int pPrecision = 2);\n\n\/* Get a vertex buffer object for quad that spans the screen\n *\/\ngl::GLuint screenQuadVBO(const int pWindowId);\n\n\/* Get a vertex array object that uses screenQuadVBO\n *\n * This vertex array object when bound and rendered, basically\n * draws a rectangle over the entire screen with standard\n * texture coordinates. Use of this vao would be as follows\n *\n * `glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);`\n *\/\ngl::GLuint screenQuadVAO(const int pWindowId);\n\n\/* Print glm::mat4 to std::cout stream *\/\nstd::ostream& operator<<(std::ostream&, const glm::mat4&);\n\n\/* get the point of the surface of track ball *\/\nglm::vec3 trackballPoint(const float pX, const float pY,\n const float pWidth, const float pHeight);\n\nnamespace forge\n{\nnamespace opengl\n{\n\ntypedef unsigned int uint;\ntypedef unsigned short ushort;\ntypedef unsigned char uchar;\n\nclass ShaderProgram {\n private:\n gl::GLuint mVertex;\n gl::GLuint mFragment;\n gl::GLuint mGeometry;\n gl::GLuint mProgram;\n\n public:\n ShaderProgram(const char* pVertShaderSrc,\n const char* pFragShaderSrc,\n const char* pGeomShaderSrc=NULL);\n\n ~ShaderProgram();\n\n gl::GLuint getProgramId() const;\n\n gl::GLuint getUniformLocation(const char* pAttributeName);\n gl::GLuint getUniformBlockIndex(const char* pAttributeName);\n gl::GLuint getAttributeLocation(const char* pAttributeName);\n\n void bind();\n void unbind();\n};\n\n\/* Basic renderable class\n *\n * Any object that is renderable to a window should inherit from this\n * class.\n *\/\nclass AbstractRenderable {\n protected:\n \/* OpenGL buffer objects *\/\n gl::GLuint mVBO;\n gl::GLuint mCBO;\n gl::GLuint mABO;\n size_t mVBOSize;\n size_t mCBOSize;\n size_t mABOSize;\n gl::GLfloat mColor[4];\n gl::GLfloat mRange[6];\n std::string mLegend;\n bool mIsPVCOn;\n bool mIsPVAOn;\n\n AbstractRenderable():\n mVBO(0), mCBO(0), mABO(0),\n mVBOSize(0), mCBOSize(0), mABOSize(0),\n mIsPVCOn(0), mIsPVAOn(0)\n {\n mColor[0] = 0;\n mColor[1] = 0;\n mColor[2] = 0;\n mColor[3] = 0;\n\n mRange[0] = 0;\n mRange[1] = 0;\n mRange[2] = 0;\n mRange[3] = 0;\n mRange[4] = 0;\n mRange[5] = 0;\n }\n\n public:\n \/* Getter functions for OpenGL buffer objects\n * identifiers and their size in bytes\n *\n * vbo is for vertices\n * cbo is for colors of those vertices\n * abo is for alpha values for those vertices\n *\/\n gl::GLuint vbo() const { return mVBO; }\n gl::GLuint cbo() { mIsPVCOn = true; return mCBO; }\n gl::GLuint abo() { mIsPVAOn = true; return mABO; }\n size_t vboSize() const { return mVBOSize; }\n size_t cboSize() const { return mCBOSize; }\n size_t aboSize() const { return mABOSize; }\n\n \/* Set color for rendering\n *\/\n void setColor(const float pRed, const float pGreen,\n const float pBlue, const float pAlpha) {\n mColor[0] = clampTo01(pRed);\n mColor[1] = clampTo01(pGreen);\n mColor[2] = clampTo01(pBlue);\n mColor[3] = clampTo01(pAlpha);\n }\n\n \/* Get renderable solid color\n *\/\n void getColor(float& pRed, float& pGreen, float& pBlue, float& pAlpha) {\n pRed = mColor[0];\n pGreen = mColor[1];\n pBlue = mColor[2];\n pAlpha = mColor[3];\n }\n\n \/* Set legend for rendering\n *\/\n void setLegend(const char* pLegend) {\n mLegend = std::string(pLegend);\n }\n\n \/* Get legend string\n *\/\n const std::string& legend() const {\n return mLegend;\n }\n\n \/* Set 3d world coordinate ranges\n *\n * This method is mostly used for charts and related renderables\n *\/\n void setRanges(const float pMinX, const float pMaxX,\n const float pMinY, const float pMaxY,\n const float pMinZ, const float pMaxZ) {\n mRange[0] = pMinX; mRange[1] = pMaxX;\n mRange[2] = pMinY; mRange[3] = pMaxY;\n mRange[4] = pMinZ; mRange[5] = pMaxZ;\n }\n\n \/* virtual function to set colormap, a derviced class might\n * use it or ignore it if it doesnt have a need for color maps.\n *\/\n virtual void setColorMapUBOParams(const gl::GLuint pUBO, const gl::GLuint pSize) {\n }\n\n \/* render is a pure virtual function.\n *\n * @pWindowId is the window identifier\n * @pX is the X coordinate at which the currently bound viewport begins.\n * @pX is the Y coordinate at which the currently bound viewport begins.\n * @pViewPortWidth is the width of the currently bound viewport.\n * @pViewPortHeight is the height of the currently bound viewport.\n *\n * Any concrete class that inherits AbstractRenderable class needs to\n * implement this method to render their OpenGL objects to\n * the currently bound viewport of the Window bearing identifier pWindowId.\n *\n * @return nothing.\n *\/\n virtual void render(const int pWindowId,\n const int pX, const int pY, const int pVPW, const int pVPH,\n const glm::mat4 &pView, const glm::mat4 &pOrient) = 0;\n};\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"hext\/node-util.h\"\n\n\nnamespace hext {\n\n\nunsigned int GetNodePositionWithinParent(const GumboNode * node)\n{\n if( !node )\n return 0;\n\n const GumboNode * parent = node->parent;\n\n if( !parent || parent->type != GUMBO_NODE_ELEMENT )\n return 0;\n\n unsigned int pos = 0;\n const GumboVector& child_nodes = parent->v.element.children;\n \/\/ We only have to traverse up to node->index_within_parent, and not the\n \/\/ whole GumboVector.\n for(unsigned int i = 0; i <= node->index_within_parent; ++i)\n {\n assert(i < child_nodes.length);\n const GumboNode * child = \n static_cast<const GumboNode *>(child_nodes.data[i]);\n\n if( child && child->type == GUMBO_NODE_ELEMENT )\n ++pos;\n\n if( node == child )\n return pos;\n }\n\n return 0;\n}\n\nstd::string GetNodeText(const GumboNode * node)\n{\n return TrimAndCollapseWs(GetNodeRawText(node));\n}\n\nstd::string GetNodeRawText(const GumboNode * node)\n{\n if( !node || node->type != GUMBO_NODE_ELEMENT )\n return \"\";\n\n std::string inner_text;\n\n const GumboVector * children = &node->v.element.children;\n for(unsigned int i = 0; i < children->length; ++i)\n {\n const GumboNode * child_node =\n static_cast<const GumboNode *>(children->data[i]);\n assert(child_node != nullptr);\n\n if( child_node->type == GUMBO_NODE_TEXT )\n {\n const GumboText * node_text = &child_node->v.text;\n assert(node_text != nullptr);\n assert(node_text->text != nullptr);\n inner_text.push_back(' ');\n inner_text.append(node_text->text);\n }\n else if( child_node->type == GUMBO_NODE_ELEMENT )\n {\n inner_text.push_back(' ');\n inner_text.append(GetNodeRawText(child_node));\n }\n }\n\n return inner_text;\n}\n\nstd::string GetNodeInnerHtml(const GumboNode * node)\n{\n if( !node || node->type != GUMBO_NODE_ELEMENT )\n return \"\";\n\n const GumboStringPiece& b = node->v.element.original_tag;\n const GumboStringPiece& e = node->v.element.original_end_tag;\n\n if( b.data != nullptr && b.length > 0 &&\n e.data != nullptr && e.length > 0 )\n {\n const char * inner_begin = b.data + b.length;\n size_t length = std::distance(inner_begin, e.data);\n return std::string(inner_begin, length);\n }\n\n return \"\";\n}\n\n\n} \/\/ hext\n\n<commit_msg>GetNodeInnerHtml: check if beginning is actually at a lower address than end<commit_after>#include \"hext\/node-util.h\"\n\n\nnamespace hext {\n\n\nunsigned int GetNodePositionWithinParent(const GumboNode * node)\n{\n if( !node )\n return 0;\n\n const GumboNode * parent = node->parent;\n\n if( !parent || parent->type != GUMBO_NODE_ELEMENT )\n return 0;\n\n unsigned int pos = 0;\n const GumboVector& child_nodes = parent->v.element.children;\n \/\/ We only have to traverse up to node->index_within_parent, and not the\n \/\/ whole GumboVector.\n for(unsigned int i = 0; i <= node->index_within_parent; ++i)\n {\n assert(i < child_nodes.length);\n const GumboNode * child = \n static_cast<const GumboNode *>(child_nodes.data[i]);\n\n if( child && child->type == GUMBO_NODE_ELEMENT )\n ++pos;\n\n if( node == child )\n return pos;\n }\n\n return 0;\n}\n\nstd::string GetNodeText(const GumboNode * node)\n{\n return TrimAndCollapseWs(GetNodeRawText(node));\n}\n\nstd::string GetNodeRawText(const GumboNode * node)\n{\n if( !node || node->type != GUMBO_NODE_ELEMENT )\n return \"\";\n\n std::string inner_text;\n\n const GumboVector * children = &node->v.element.children;\n for(unsigned int i = 0; i < children->length; ++i)\n {\n const GumboNode * child_node =\n static_cast<const GumboNode *>(children->data[i]);\n assert(child_node != nullptr);\n\n if( child_node->type == GUMBO_NODE_TEXT )\n {\n const GumboText * node_text = &child_node->v.text;\n assert(node_text != nullptr);\n assert(node_text->text != nullptr);\n inner_text.push_back(' ');\n inner_text.append(node_text->text);\n }\n else if( child_node->type == GUMBO_NODE_ELEMENT )\n {\n inner_text.push_back(' ');\n inner_text.append(GetNodeRawText(child_node));\n }\n }\n\n return inner_text;\n}\n\nstd::string GetNodeInnerHtml(const GumboNode * node)\n{\n if( !node || node->type != GUMBO_NODE_ELEMENT )\n return \"\";\n\n const GumboStringPiece& b = node->v.element.original_tag;\n const GumboStringPiece& e = node->v.element.original_end_tag;\n\n if( b.data && b.length > 0 &&\n e.data && e.length > 0 &&\n ( b.data + b.length ) < e.data )\n {\n const char * inner_begin = b.data + b.length;\n size_t length = std::distance(inner_begin, e.data);\n return std::string(inner_begin, length);\n }\n\n return \"\";\n}\n\n\n} \/\/ hext\n\n<|endoftext|>"} {"text":"<commit_before>c6a9fa88-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6aefd94-2e4c-11e5-9284-b827eb9e62be<commit_after>c6aefd94-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>10c86e78-2e4e-11e5-9284-b827eb9e62be<commit_msg>10cd65cc-2e4e-11e5-9284-b827eb9e62be<commit_after>10cd65cc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>adcfba46-2e4e-11e5-9284-b827eb9e62be<commit_msg>add4b186-2e4e-11e5-9284-b827eb9e62be<commit_after>add4b186-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>405507ce-2e4d-11e5-9284-b827eb9e62be<commit_msg>405a0a76-2e4d-11e5-9284-b827eb9e62be<commit_after>405a0a76-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>d1ea1162-2e4c-11e5-9284-b827eb9e62be<commit_msg>d1ef20e4-2e4c-11e5-9284-b827eb9e62be<commit_after>d1ef20e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>77a6b59c-2e4d-11e5-9284-b827eb9e62be<commit_msg>77aba912-2e4d-11e5-9284-b827eb9e62be<commit_after>77aba912-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>ae44a7cc-2e4c-11e5-9284-b827eb9e62be<commit_msg>ae499afc-2e4c-11e5-9284-b827eb9e62be<commit_after>ae499afc-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>30c77a24-2e4f-11e5-9284-b827eb9e62be<commit_msg>30cd34c8-2e4f-11e5-9284-b827eb9e62be<commit_after>30cd34c8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>f47471b4-2e4c-11e5-9284-b827eb9e62be<commit_msg>f47999b4-2e4c-11e5-9284-b827eb9e62be<commit_after>f47999b4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>ccbf28b0-2e4e-11e5-9284-b827eb9e62be<commit_msg>ccc428ba-2e4e-11e5-9284-b827eb9e62be<commit_after>ccc428ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>bf9243de-2e4e-11e5-9284-b827eb9e62be<commit_msg>bf973b14-2e4e-11e5-9284-b827eb9e62be<commit_after>bf973b14-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>47c08344-2e4d-11e5-9284-b827eb9e62be<commit_msg>47c5944c-2e4d-11e5-9284-b827eb9e62be<commit_after>47c5944c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>bb2d5898-2e4d-11e5-9284-b827eb9e62be<commit_msg>bb32740e-2e4d-11e5-9284-b827eb9e62be<commit_after>bb32740e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>cbc7d85a-2e4c-11e5-9284-b827eb9e62be<commit_msg>cbcccff4-2e4c-11e5-9284-b827eb9e62be<commit_after>cbcccff4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"<commit_before>\/\/===---------------------------- cxa_guard.cpp ---------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"__cxxabi_config.h\"\n\n#include \"abort_message.h\"\n#include <__threading_support>\n\n#include <stdint.h>\n\n\/*\n This implementation must be careful to not call code external to this file\n which will turn around and try to call __cxa_guard_acquire reentrantly.\n For this reason, the headers of this file are as restricted as possible.\n Previous implementations of this code for __APPLE__ have used\n std::__libcpp_mutex_lock and the abort_message utility without problem. This\n implementation also uses std::__libcpp_condvar_wait which has tested\n to not be a problem.\n*\/\n\nnamespace __cxxabiv1\n{\n\nnamespace\n{\n\n#ifdef __arm__\n\/\/ A 32-bit, 4-byte-aligned static data value. The least significant 2 bits must\n\/\/ be statically initialized to 0.\ntypedef uint32_t guard_type;\n\ninline void set_initialized(guard_type* guard_object) {\n *guard_object |= 1;\n}\n\n\/\/ Test the lowest bit.\ninline bool is_initialized(guard_type* guard_object) {\n return (*guard_object) & 1;\n}\n\n#else\ntypedef uint64_t guard_type;\n\nvoid set_initialized(guard_type* guard_object) {\n char* initialized = (char*)guard_object;\n *initialized = 1;\n}\n\nbool is_initialized(guard_type* guard_object) {\n char* initialized = (char*)guard_object;\n return *initialized;\n}\n#endif\n\n#ifndef _LIBCXXABI_HAS_NO_THREADS\nstd::__libcpp_mutex_t guard_mut = _LIBCPP_MUTEX_INITIALIZER;\nstd::__libcpp_condvar_t guard_cv = _LIBCPP_CONDVAR_INITIALIZER;\n#endif\n\n#if defined(__APPLE__) && !defined(__arm__)\n\ntypedef uint32_t lock_type;\n\n#if __LITTLE_ENDIAN__\n\ninline\nlock_type\nget_lock(uint64_t x)\n{\n return static_cast<lock_type>(x >> 32);\n}\n\ninline\nvoid\nset_lock(uint64_t& x, lock_type y)\n{\n x = static_cast<uint64_t>(y) << 32;\n}\n\n#else \/\/ __LITTLE_ENDIAN__\n\ninline\nlock_type\nget_lock(uint64_t x)\n{\n return static_cast<lock_type>(x);\n}\n\ninline\nvoid\nset_lock(uint64_t& x, lock_type y)\n{\n x = y;\n}\n\n#endif \/\/ __LITTLE_ENDIAN__\n\n#else \/\/ !__APPLE__ || __arm__\n\ntypedef bool lock_type;\n\n#if !defined(__arm__)\nstatic_assert(std::is_same<guard_type, uint64_t>::value, \"\");\n\ninline lock_type get_lock(uint64_t x)\n{\n union\n {\n uint64_t guard;\n uint8_t lock[2];\n } f = {x};\n return f.lock[1] != 0;\n}\n\ninline void set_lock(uint64_t& x, lock_type y)\n{\n union\n {\n uint64_t guard;\n uint8_t lock[2];\n } f = {0};\n f.lock[1] = y;\n x = f.guard;\n}\n#else \/\/ defined(__arm__)\nstatic_assert(std::is_same<guard_type, uint32_t>::value, \"\");\n\ninline lock_type get_lock(uint32_t x)\n{\n union\n {\n uint32_t guard;\n uint8_t lock[2];\n } f = {x};\n return f.lock[1] != 0;\n}\n\ninline void set_lock(uint32_t& x, lock_type y)\n{\n union\n {\n uint32_t guard;\n uint8_t lock[2];\n } f = {0};\n f.lock[1] = y;\n x = f.guard;\n}\n\n#endif \/\/ !defined(__arm__)\n\n#endif \/\/ __APPLE__ && !__arm__\n\n} \/\/ unnamed namespace\n\nextern \"C\"\n{\n\n#ifndef _LIBCXXABI_HAS_NO_THREADS\n_LIBCXXABI_FUNC_VIS int __cxa_guard_acquire(guard_type *guard_object) {\n if (std::__libcpp_mutex_lock(&guard_mut))\n abort_message(\"__cxa_guard_acquire failed to acquire mutex\");\n int result = !is_initialized(guard_object);\n if (result)\n {\n#if defined(__APPLE__) && !defined(__arm__)\n \/\/ This is a special-case pthread dependency for Mac. We can't pull this\n \/\/ out into libcxx's threading API (__threading_support) because not all\n \/\/ supported Mac environments provide this function (in pthread.h). To\n \/\/ make it possible to build\/use libcxx in those environments, we have to\n \/\/ keep this pthread dependency local to libcxxabi. If there is some\n \/\/ convenient way to detect precisely when pthread_mach_thread_np is\n \/\/ available in a given Mac environment, it might still be possible to\n \/\/ bury this dependency in __threading_support.\n #ifdef _LIBCPP_HAS_THREAD_API_PTHREAD\n const lock_type id = pthread_mach_thread_np(std::__libcpp_thread_get_current_id());\n #else\n #error \"How do I pthread_mach_thread_np()?\"\n #endif\n lock_type lock = get_lock(*guard_object);\n if (lock)\n {\n \/\/ if this thread set lock for this same guard_object, abort\n if (lock == id)\n abort_message(\"__cxa_guard_acquire detected deadlock\");\n do\n {\n if (std::__libcpp_condvar_wait(&guard_cv, &guard_mut))\n abort_message(\"__cxa_guard_acquire condition variable wait failed\");\n lock = get_lock(*guard_object);\n } while (lock);\n result = !is_initialized(guard_object);\n if (result)\n set_lock(*guard_object, id);\n }\n else\n set_lock(*guard_object, id);\n#else \/\/ !__APPLE__ || __arm__\n while (get_lock(*guard_object))\n if (std::__libcpp_condvar_wait(&guard_cv, &guard_mut))\n abort_message(\"__cxa_guard_acquire condition variable wait failed\");\n result = !is_initialized(guard_object);\n if (result)\n set_lock(*guard_object, true);\n#endif \/\/ !__APPLE__ || __arm__\n }\n if (std::__libcpp_mutex_unlock(&guard_mut))\n abort_message(\"__cxa_guard_acquire failed to release mutex\");\n return result;\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_release(guard_type *guard_object) {\n if (std::__libcpp_mutex_lock(&guard_mut))\n abort_message(\"__cxa_guard_release failed to acquire mutex\");\n *guard_object = 0;\n set_initialized(guard_object);\n if (std::__libcpp_mutex_unlock(&guard_mut))\n abort_message(\"__cxa_guard_release failed to release mutex\");\n if (std::__libcpp_condvar_broadcast(&guard_cv))\n abort_message(\"__cxa_guard_release failed to broadcast condition variable\");\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_abort(guard_type *guard_object) {\n if (std::__libcpp_mutex_lock(&guard_mut))\n abort_message(\"__cxa_guard_abort failed to acquire mutex\");\n *guard_object = 0;\n if (std::__libcpp_mutex_unlock(&guard_mut))\n abort_message(\"__cxa_guard_abort failed to release mutex\");\n if (std::__libcpp_condvar_broadcast(&guard_cv))\n abort_message(\"__cxa_guard_abort failed to broadcast condition variable\");\n}\n\n#else \/\/ _LIBCXXABI_HAS_NO_THREADS\n\n_LIBCXXABI_FUNC_VIS int __cxa_guard_acquire(guard_type *guard_object) {\n return !is_initialized(guard_object);\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_release(guard_type *guard_object) {\n *guard_object = 0;\n set_initialized(guard_object);\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_abort(guard_type *guard_object) {\n *guard_object = 0;\n}\n\n#endif \/\/ !_LIBCXXABI_HAS_NO_THREADS\n\n} \/\/ extern \"C\"\n\n} \/\/ __cxxabiv1\n<commit_msg>Create RAII lock guard for global initialization lock.<commit_after>\/\/===---------------------------- cxa_guard.cpp ---------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"__cxxabi_config.h\"\n\n#include \"abort_message.h\"\n#include <__threading_support>\n\n#include <stdint.h>\n\n\/*\n This implementation must be careful to not call code external to this file\n which will turn around and try to call __cxa_guard_acquire reentrantly.\n For this reason, the headers of this file are as restricted as possible.\n Previous implementations of this code for __APPLE__ have used\n std::__libcpp_mutex_lock and the abort_message utility without problem. This\n implementation also uses std::__libcpp_condvar_wait which has tested\n to not be a problem.\n*\/\n\nnamespace __cxxabiv1\n{\n\nnamespace\n{\n\n#ifdef __arm__\n\/\/ A 32-bit, 4-byte-aligned static data value. The least significant 2 bits must\n\/\/ be statically initialized to 0.\ntypedef uint32_t guard_type;\n\ninline void set_initialized(guard_type* guard_object) {\n *guard_object |= 1;\n}\n\n\/\/ Test the lowest bit.\ninline bool is_initialized(guard_type* guard_object) {\n return (*guard_object) & 1;\n}\n\n#else\ntypedef uint64_t guard_type;\n\nvoid set_initialized(guard_type* guard_object) {\n char* initialized = (char*)guard_object;\n *initialized = 1;\n}\n\nbool is_initialized(guard_type* guard_object) {\n char* initialized = (char*)guard_object;\n return *initialized;\n}\n#endif\n\nenum class OnRelease : char { UNLOCK, UNLOCK_AND_BROADCAST };\n\nstruct GlobalMutexGuard {\n explicit GlobalMutexGuard(const char* calling_func, OnRelease on_release)\n : calling_func(calling_func), on_release(on_release) {\n#ifndef _LIBCXXABI_HAS_NO_THREADS\n if (std::__libcpp_mutex_lock(&guard_mut))\n abort_message(\"%s failed to acquire mutex\", calling_func);\n#endif\n }\n\n ~GlobalMutexGuard() {\n#ifndef _LIBCXXABI_HAS_NO_THREADS\n if (std::__libcpp_mutex_unlock(&guard_mut))\n abort_message(\"%s failed to release mutex\", calling_func);\n if (on_release == OnRelease::UNLOCK_AND_BROADCAST) {\n if (std::__libcpp_condvar_broadcast(&guard_cv))\n abort_message(\"%s failed to broadcast condition variable\",\n calling_func);\n }\n#endif\n }\n\n void wait_for_signal() {\n#ifndef _LIBCXXABI_HAS_NO_THREADS\n if (std::__libcpp_condvar_wait(&guard_cv, &guard_mut))\n abort_message(\"%s condition variable wait failed\", calling_func);\n#endif\n }\n\nprivate:\n GlobalMutexGuard(GlobalMutexGuard const&) = delete;\n GlobalMutexGuard& operator=(GlobalMutexGuard const&) = delete;\n\n const char* const calling_func;\n OnRelease on_release;\n\n#ifndef _LIBCXXABI_HAS_NO_THREADS\n static std::__libcpp_mutex_t guard_mut;\n static std::__libcpp_condvar_t guard_cv;\n#endif\n};\n\n#ifndef _LIBCXXABI_HAS_NO_THREADS\nstd::__libcpp_mutex_t GlobalMutexGuard::guard_mut = _LIBCPP_MUTEX_INITIALIZER;\nstd::__libcpp_condvar_t GlobalMutexGuard::guard_cv =\n _LIBCPP_CONDVAR_INITIALIZER;\n#endif\n\n#if defined(__APPLE__) && !defined(__arm__)\n\ntypedef uint32_t lock_type;\n\n#if __LITTLE_ENDIAN__\n\ninline\nlock_type\nget_lock(uint64_t x)\n{\n return static_cast<lock_type>(x >> 32);\n}\n\ninline\nvoid\nset_lock(uint64_t& x, lock_type y)\n{\n x = static_cast<uint64_t>(y) << 32;\n}\n\n#else \/\/ __LITTLE_ENDIAN__\n\ninline\nlock_type\nget_lock(uint64_t x)\n{\n return static_cast<lock_type>(x);\n}\n\ninline\nvoid\nset_lock(uint64_t& x, lock_type y)\n{\n x = y;\n}\n\n#endif \/\/ __LITTLE_ENDIAN__\n\n#else \/\/ !__APPLE__ || __arm__\n\ntypedef bool lock_type;\n\n#if !defined(__arm__)\nstatic_assert(std::is_same<guard_type, uint64_t>::value, \"\");\n\ninline lock_type get_lock(uint64_t x)\n{\n union\n {\n uint64_t guard;\n uint8_t lock[2];\n } f = {x};\n return f.lock[1] != 0;\n}\n\ninline void set_lock(uint64_t& x, lock_type y)\n{\n union\n {\n uint64_t guard;\n uint8_t lock[2];\n } f = {0};\n f.lock[1] = y;\n x = f.guard;\n}\n#else \/\/ defined(__arm__)\nstatic_assert(std::is_same<guard_type, uint32_t>::value, \"\");\n\ninline lock_type get_lock(uint32_t x)\n{\n union\n {\n uint32_t guard;\n uint8_t lock[2];\n } f = {x};\n return f.lock[1] != 0;\n}\n\ninline void set_lock(uint32_t& x, lock_type y)\n{\n union\n {\n uint32_t guard;\n uint8_t lock[2];\n } f = {0};\n f.lock[1] = y;\n x = f.guard;\n}\n\n#endif \/\/ !defined(__arm__)\n\n#endif \/\/ __APPLE__ && !__arm__\n\n} \/\/ unnamed namespace\n\nextern \"C\"\n{\n\n_LIBCXXABI_FUNC_VIS int __cxa_guard_acquire(guard_type *guard_object) {\n GlobalMutexGuard gmutex(\"__cxa_guard_acquire\", OnRelease::UNLOCK);\n int result = !is_initialized(guard_object);\n if (result) {\n#if defined(_LIBCXXABI_HAS_NO_THREADS)\n \/\/ nothing to do\n#elif defined(__APPLE__) && !defined(__arm__)\n\/\/ This is a special-case pthread dependency for Mac. We can't pull this\n\/\/ out into libcxx's threading API (__threading_support) because not all\n\/\/ supported Mac environments provide this function (in pthread.h). To\n\/\/ make it possible to build\/use libcxx in those environments, we have to\n\/\/ keep this pthread dependency local to libcxxabi. If there is some\n\/\/ convenient way to detect precisely when pthread_mach_thread_np is\n\/\/ available in a given Mac environment, it might still be possible to\n\/\/ bury this dependency in __threading_support.\n#ifdef _LIBCPP_HAS_THREAD_API_PTHREAD\n const lock_type id =\n pthread_mach_thread_np(std::__libcpp_thread_get_current_id());\n#else\n#error \"How do I pthread_mach_thread_np()?\"\n#endif\n lock_type lock = get_lock(*guard_object);\n if (lock) {\n \/\/ if this thread set lock for this same guard_object, abort\n if (lock == id)\n abort_message(\"__cxa_guard_acquire detected deadlock\");\n do {\n gmutex.wait_for_signal();\n lock = get_lock(*guard_object);\n } while (lock);\n result = !is_initialized(guard_object);\n if (result)\n set_lock(*guard_object, id);\n } else\n set_lock(*guard_object, id);\n#else \/\/ !__APPLE__ || __arm__\n while (get_lock(*guard_object)) {\n gmutex.wait_for_signal();\n }\n result = !is_initialized(guard_object);\n if (result)\n set_lock(*guard_object, true);\n#endif \/\/ !__APPLE__ || __arm__\n }\n return result;\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_release(guard_type *guard_object) {\n GlobalMutexGuard gmutex(\"__cxa_guard_release\",\n OnRelease::UNLOCK_AND_BROADCAST);\n *guard_object = 0;\n set_initialized(guard_object);\n}\n\n_LIBCXXABI_FUNC_VIS void __cxa_guard_abort(guard_type *guard_object) {\n GlobalMutexGuard gmutex(\"__cxa_guard_abort\", OnRelease::UNLOCK);\n *guard_object = 0;\n}\n\n\n} \/\/ extern \"C\"\n\n} \/\/ __cxxabiv1\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/ mapnik\n#include <mapnik\/formatting\/text.hpp>\n#include <mapnik\/expression_string.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/text_properties.hpp>\n#include <mapnik\/processed_text.hpp>\n#include <mapnik\/xml_node.hpp>\n#include <mapnik\/value_types.hpp>\n\n\/\/ boost\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/make_shared.hpp>\n\nnamespace mapnik\n{\nnamespace formatting\n{\n\nusing boost::property_tree::ptree;\n\nvoid text_node::to_xml(ptree &xml) const\n{\n ptree &new_node = xml.push_back(ptree::value_type(\n \"<xmltext>\", ptree()))->second;\n new_node.put_value(to_expression_string(*text_));\n}\n\nnode_ptr text_node::from_xml(xml_node const& xml)\n{\n return boost::make_shared<text_node>(xml.get_value<expression_ptr>());\n}\n\nvoid text_node::apply(char_properties const& p, feature_impl const& feature, processed_text &output) const\n{\n mapnik::value_unicode_string text_str = boost::apply_visitor(evaluate<feature_impl,value_type>(feature), *text_).to_unicode();\n if (p.text_transform == UPPERCASE)\n {\n text_str = text_str.toUpper();\n }\n else if (p.text_transform == LOWERCASE)\n {\n text_str = text_str.toLower();\n }\n else if (p.text_transform == CAPITALIZE)\n {\n text_str = text_str.toTitle(NULL);\n }\n if (text_str.length() > 0) {\n output.push_back(p, text_str);\n }\n}\n\n\nvoid text_node::add_expressions(expression_set &output) const\n{\n if (text_) output.insert(text_);\n}\n\n\nvoid text_node::set_text(expression_ptr text)\n{\n text_ = text;\n}\n\n\nexpression_ptr text_node::get_text() const\n{\n return text_;\n}\n\n} \/\/ns formatting\n} \/\/ns mapnik\n<commit_msg>gracefully handle when icu is built without BreakIterator support: -DUCONFIG_NO_BREAK_ITERATION=1<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/ mapnik\n#include <mapnik\/formatting\/text.hpp>\n#include <mapnik\/expression_string.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/text_properties.hpp>\n#include <mapnik\/processed_text.hpp>\n#include <mapnik\/xml_node.hpp>\n#include <mapnik\/value_types.hpp>\n\n\/\/ boost\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/make_shared.hpp>\n\nnamespace mapnik\n{\nnamespace formatting\n{\n\nusing boost::property_tree::ptree;\n\nvoid text_node::to_xml(ptree &xml) const\n{\n ptree &new_node = xml.push_back(ptree::value_type(\n \"<xmltext>\", ptree()))->second;\n new_node.put_value(to_expression_string(*text_));\n}\n\nnode_ptr text_node::from_xml(xml_node const& xml)\n{\n return boost::make_shared<text_node>(xml.get_value<expression_ptr>());\n}\n\nvoid text_node::apply(char_properties const& p, feature_impl const& feature, processed_text &output) const\n{\n mapnik::value_unicode_string text_str = boost::apply_visitor(evaluate<feature_impl,value_type>(feature), *text_).to_unicode();\n if (p.text_transform == UPPERCASE)\n {\n text_str = text_str.toUpper();\n }\n else if (p.text_transform == LOWERCASE)\n {\n text_str = text_str.toLower();\n }\n#if !UCONFIG_NO_BREAK_ITERATION\n else if (p.text_transform == CAPITALIZE)\n {\n \/\/ note: requires BreakIterator support in ICU which is optional\n text_str = text_str.toTitle(NULL);\n }\n#endif\n if (text_str.length() > 0) {\n output.push_back(p, text_str);\n }\n}\n\n\nvoid text_node::add_expressions(expression_set &output) const\n{\n if (text_) output.insert(text_);\n}\n\n\nvoid text_node::set_text(expression_ptr text)\n{\n text_ = text;\n}\n\n\nexpression_ptr text_node::get_text() const\n{\n return text_;\n}\n\n} \/\/ns formatting\n} \/\/ns mapnik\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file sqlite.cpp\n * @brief SQLite DB access layer\n *\n * (c) 2013-2014 by Mega Limited, Auckland, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n\n#ifdef USE_SQLITE\nnamespace mega {\n\nSqliteDbAccess::SqliteDbAccess(const LocalPath& rootPath)\n : mRootPath(rootPath)\n{\n}\n\nSqliteDbAccess::~SqliteDbAccess()\n{\n}\n\nLocalPath SqliteDbAccess::databasePath(const FileSystemAccess& fsAccess,\n const string& name,\n const int version) const\n{\n ostringstream osstream;\n\n osstream << \"megaclient_statecache\"\n << version\n << \"_\"\n << name\n << \".db\";\n\n LocalPath path = mRootPath;\n\n path.appendWithSeparator(\n LocalPath::fromPath(osstream.str(), fsAccess),\n false);\n\n return path;\n}\n\nSqliteDbTable* SqliteDbAccess::open(PrnGen &rng, FileSystemAccess& fsAccess, const string& name, const int flags)\n{\n auto dbPath = databasePath(fsAccess, name, DB_VERSION);\n auto upgraded = true;\n\n {\n auto legacyPath = databasePath(fsAccess, name, LEGACY_DB_VERSION);\n auto fileAccess = fsAccess.newfileaccess();\n\n if (fileAccess->fopen(legacyPath))\n {\n LOG_debug << \"Found legacy database at: \" << legacyPath.toPath(fsAccess);\n\n if (currentDbVersion == LEGACY_DB_VERSION)\n {\n LOG_debug << \"Using a legacy database.\";\n dbPath = std::move(legacyPath);\n upgraded = false;\n }\n else if ((flags & DB_OPEN_FLAG_RECYCLE))\n {\n LOG_debug << \"Trying to recycle a legacy database.\";\n\n if (fsAccess.renamelocal(legacyPath, dbPath, false))\n {\n auto suffix = LocalPath::fromPath(\"-shm\", fsAccess);\n auto from = legacyPath + suffix;\n auto to = dbPath + suffix;\n\n fsAccess.renamelocal(from, to);\n\n suffix = LocalPath::fromPath(\"-wal\", fsAccess);\n from = legacyPath + suffix;\n to = dbPath + suffix;\n\n fsAccess.renamelocal(from, to);\n\n LOG_debug << \"Legacy database recycled.\";\n }\n else\n {\n LOG_debug << \"Unable to recycle database, deleting...\";\n fsAccess.unlinklocal(legacyPath);\n }\n }\n else\n {\n LOG_debug << \"Deleting outdated legacy database.\";\n fsAccess.unlinklocal(legacyPath);\n }\n }\n }\n\n if (upgraded)\n {\n LOG_debug << \"Using an upgraded DB: \" << dbPath.toPath(fsAccess);\n currentDbVersion = DB_VERSION;\n }\n\n const string dbPathStr = dbPath.toPath(fsAccess);\n sqlite3* db;\n int result = sqlite3_open(dbPathStr.c_str(), &db);\n\n if (result)\n {\n if (db)\n {\n sqlite3_close(db);\n }\n\n return nullptr;\n }\n\n#if !(TARGET_OS_IPHONE)\n result = sqlite3_exec(db, \"PRAGMA journal_mode=WAL;\", nullptr, nullptr, nullptr);\n if (result)\n {\n sqlite3_close(db);\n return nullptr;\n }\n#endif \/* ! TARGET_OS_IPHONE *\/\n\n const char* sql =\n \"CREATE TABLE IF NOT EXISTS statecache ( \"\n \" id INTEGER PRIMARY KEY ASC NOT NULL, \"\n \" content BLOB NOT NULL \"\n \");\";\n\n result = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);\n if (result)\n {\n sqlite3_close(db);\n return nullptr;\n }\n\n const char* tableVar = \"CREATE TABLE IF NOT EXISTS vars(name text PRIMARY KEY NOT NULL, value BLOB)\";\n result = sqlite3_exec(db, tableVar, nullptr, nullptr, nullptr);\n if (result)\n {\n sqlite3_close(db);\n return nullptr;\n }\n\n return new SqliteDbTable(rng,\n db,\n fsAccess,\n dbPathStr,\n (flags & DB_OPEN_FLAG_TRANSACTED) > 0);\n}\n\nbool SqliteDbAccess::probe(FileSystemAccess& fsAccess, const string& name) const\n{\n auto fileAccess = fsAccess.newfileaccess();\n\n LocalPath dbPath = databasePath(fsAccess, name, DB_VERSION);\n\n if (fileAccess->isfile(dbPath))\n {\n return true;\n }\n\n dbPath = databasePath(fsAccess, name, LEGACY_DB_VERSION);\n\n return fileAccess->isfile(dbPath);\n}\n\nconst LocalPath& SqliteDbAccess::rootPath() const\n{\n return mRootPath;\n}\n\nSqliteDbTable::SqliteDbTable(PrnGen &rng, sqlite3* db, FileSystemAccess &fsAccess, const string &path, const bool checkAlwaysTransacted)\n : DbTable(rng, checkAlwaysTransacted)\n , db(db)\n , pStmt(nullptr)\n , dbfile(path)\n , fsaccess(&fsAccess)\n{\n}\n\nSqliteDbTable::~SqliteDbTable()\n{\n resetCommitter();\n\n if (!db)\n {\n return;\n }\n\n sqlite3_finalize(pStmt);\n\n if (inTransaction())\n {\n abort();\n }\n\n sqlite3_close(db);\n LOG_debug << \"Database closed \" << dbfile;\n}\n\nbool SqliteDbTable::inTransaction() const\n{\n return sqlite3_get_autocommit(db) == 0;\n}\n\nLocalPath SqliteDbTable::dbFile() const\n{\n return LocalPath::fromPath(dbfile, *fsaccess);\n}\n\n\/\/ set cursor to first record\nvoid SqliteDbTable::rewind()\n{\n if (!db)\n {\n return;\n }\n\n int result;\n\n if (pStmt)\n {\n result = sqlite3_reset(pStmt);\n }\n else\n {\n result = sqlite3_prepare(db, \"SELECT id, content FROM statecache\", -1, &pStmt, NULL);\n }\n\n if (result != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(result));\n LOG_err << \"Unable to rewind database: \" << dbfile << err;\n assert(!\"Unable to rewind database.\");\n }\n}\n\n\/\/ retrieve next record through cursor\nbool SqliteDbTable::next(uint32_t* index, string* data)\n{\n if (!db)\n {\n return false;\n }\n\n if (!pStmt)\n {\n return false;\n }\n\n int rc = sqlite3_step(pStmt);\n\n if (rc != SQLITE_ROW)\n {\n sqlite3_finalize(pStmt);\n pStmt = NULL;\n\n if (rc != SQLITE_DONE)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to get next record from database: \" << dbfile << err;\n assert(!\"Unable to get next record from database.\");\n }\n\n return false;\n }\n\n *index = sqlite3_column_int(pStmt, 0);\n\n data->assign((char*)sqlite3_column_blob(pStmt, 1), sqlite3_column_bytes(pStmt, 1));\n\n return true;\n}\n\n\/\/ retrieve record by index\nbool SqliteDbTable::get(uint32_t index, string* data)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n sqlite3_stmt *stmt;\n int rc;\n\n rc = sqlite3_prepare(db, \"SELECT content FROM statecache WHERE id = ?\", -1, &stmt, NULL);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_int(stmt, 1, index);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_step(stmt);\n if (rc == SQLITE_ROW)\n {\n data->assign((char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));\n }\n }\n }\n\n sqlite3_finalize(stmt);\n\n if (rc != SQLITE_DONE && rc != SQLITE_ROW)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to get record from database: \" << dbfile << err;\n assert(!\"Unable to get record from database.\");\n }\n\n return rc == SQLITE_ROW;\n}\n\n\/\/ add\/update record by index\nbool SqliteDbTable::put(uint32_t index, char* data, unsigned len)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n sqlite3_stmt *stmt;\n bool result = false;\n\n int rc = sqlite3_prepare(db, \"INSERT OR REPLACE INTO statecache (id, content) VALUES (?, ?)\", -1, &stmt, NULL);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_int(stmt, 1, index);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_blob(stmt, 2, data, len, SQLITE_STATIC);\n if (rc == SQLITE_OK)\n {\n\n rc = sqlite3_step(stmt);\n if (rc == SQLITE_DONE)\n {\n result = true;\n }\n }\n }\n }\n\n sqlite3_finalize(stmt);\n\n if (!result)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to put record into database: \" << dbfile << err;\n assert(!\"Unable to put record into database.\");\n }\n\n return result;\n}\n\n\/\/ delete record by index\nbool SqliteDbTable::del(uint32_t index)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n char buf[64];\n\n sprintf(buf, \"DELETE FROM statecache WHERE id = %\" PRIu32, index);\n\n int rc = sqlite3_exec(db, buf, 0, 0, nullptr);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to delete record from database: \" << dbfile << err;\n assert(!\"Unable to delete record from database.\");\n\n return false;\n }\n\n return true;\n}\n\n\/\/ truncate table\nvoid SqliteDbTable::truncate()\n{\n if (!db)\n {\n return;\n }\n\n checkTransaction();\n\n int rc = sqlite3_exec(db, \"DELETE FROM statecache\", 0, 0, NULL);\n if (rc != API_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to truncate database: \" << dbfile << err;\n assert(!\"Unable to truncate database.\");\n }\n}\n\n\/\/ begin transaction\nvoid SqliteDbTable::begin()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction BEGIN \" << dbfile;\n int rc = sqlite3_exec(db, \"BEGIN\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to begin transaction on database: \" << dbfile << err;\n assert(!\"Unable to begin transaction on database.\");\n }\n}\n\n\/\/ commit transaction\nvoid SqliteDbTable::commit()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction COMMIT \" << dbfile;\n\n int rc = sqlite3_exec(db, \"COMMIT\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to commit transaction on database: \" << dbfile << err;\n assert(!\"Unable to commit transaction on database.\");\n }\n}\n\n\/\/ abort transaction\nvoid SqliteDbTable::abort()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction ROLLBACK \" << dbfile;\n\n int rc = sqlite3_exec(db, \"ROLLBACK\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to rollback transaction on database: \" << dbfile << err;\n assert(!\"Unable to rollback transaction on database.\");\n }\n}\n\nvoid SqliteDbTable::remove()\n{\n if (!db)\n {\n return;\n }\n\n sqlite3_finalize(pStmt);\n\n if (inTransaction())\n {\n abort();\n }\n\n sqlite3_close(db);\n\n db = NULL;\n\n auto localpath = LocalPath::fromPath(dbfile, *fsaccess);\n fsaccess->unlinklocal(localpath);\n}\n\n} \/\/ namespace\n\n#endif\n<commit_msg>Remove unneeded changes to DB schema<commit_after>\/**\n * @file sqlite.cpp\n * @brief SQLite DB access layer\n *\n * (c) 2013-2014 by Mega Limited, Auckland, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n\n#ifdef USE_SQLITE\nnamespace mega {\n\nSqliteDbAccess::SqliteDbAccess(const LocalPath& rootPath)\n : mRootPath(rootPath)\n{\n}\n\nSqliteDbAccess::~SqliteDbAccess()\n{\n}\n\nLocalPath SqliteDbAccess::databasePath(const FileSystemAccess& fsAccess,\n const string& name,\n const int version) const\n{\n ostringstream osstream;\n\n osstream << \"megaclient_statecache\"\n << version\n << \"_\"\n << name\n << \".db\";\n\n LocalPath path = mRootPath;\n\n path.appendWithSeparator(\n LocalPath::fromPath(osstream.str(), fsAccess),\n false);\n\n return path;\n}\n\nSqliteDbTable* SqliteDbAccess::open(PrnGen &rng, FileSystemAccess& fsAccess, const string& name, const int flags)\n{\n auto dbPath = databasePath(fsAccess, name, DB_VERSION);\n auto upgraded = true;\n\n {\n auto legacyPath = databasePath(fsAccess, name, LEGACY_DB_VERSION);\n auto fileAccess = fsAccess.newfileaccess();\n\n if (fileAccess->fopen(legacyPath))\n {\n LOG_debug << \"Found legacy database at: \" << legacyPath.toPath(fsAccess);\n\n if (currentDbVersion == LEGACY_DB_VERSION)\n {\n LOG_debug << \"Using a legacy database.\";\n dbPath = std::move(legacyPath);\n upgraded = false;\n }\n else if ((flags & DB_OPEN_FLAG_RECYCLE))\n {\n LOG_debug << \"Trying to recycle a legacy database.\";\n\n if (fsAccess.renamelocal(legacyPath, dbPath, false))\n {\n auto suffix = LocalPath::fromPath(\"-shm\", fsAccess);\n auto from = legacyPath + suffix;\n auto to = dbPath + suffix;\n\n fsAccess.renamelocal(from, to);\n\n suffix = LocalPath::fromPath(\"-wal\", fsAccess);\n from = legacyPath + suffix;\n to = dbPath + suffix;\n\n fsAccess.renamelocal(from, to);\n\n LOG_debug << \"Legacy database recycled.\";\n }\n else\n {\n LOG_debug << \"Unable to recycle database, deleting...\";\n fsAccess.unlinklocal(legacyPath);\n }\n }\n else\n {\n LOG_debug << \"Deleting outdated legacy database.\";\n fsAccess.unlinklocal(legacyPath);\n }\n }\n }\n\n if (upgraded)\n {\n LOG_debug << \"Using an upgraded DB: \" << dbPath.toPath(fsAccess);\n currentDbVersion = DB_VERSION;\n }\n\n const string dbPathStr = dbPath.toPath(fsAccess);\n sqlite3* db;\n int result = sqlite3_open(dbPathStr.c_str(), &db);\n\n if (result)\n {\n if (db)\n {\n sqlite3_close(db);\n }\n\n return nullptr;\n }\n\n#if !(TARGET_OS_IPHONE)\n result = sqlite3_exec(db, \"PRAGMA journal_mode=WAL;\", nullptr, nullptr, nullptr);\n if (result)\n {\n sqlite3_close(db);\n return nullptr;\n }\n#endif \/* ! TARGET_OS_IPHONE *\/\n\n const char* sql =\n \"CREATE TABLE IF NOT EXISTS statecache ( \"\n \" id INTEGER PRIMARY KEY ASC NOT NULL, \"\n \" content BLOB NOT NULL \"\n \");\";\n\n result = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);\n if (result)\n {\n sqlite3_close(db);\n return nullptr;\n }\n\n return new SqliteDbTable(rng,\n db,\n fsAccess,\n dbPathStr,\n (flags & DB_OPEN_FLAG_TRANSACTED) > 0);\n}\n\nbool SqliteDbAccess::probe(FileSystemAccess& fsAccess, const string& name) const\n{\n auto fileAccess = fsAccess.newfileaccess();\n\n LocalPath dbPath = databasePath(fsAccess, name, DB_VERSION);\n\n if (fileAccess->isfile(dbPath))\n {\n return true;\n }\n\n dbPath = databasePath(fsAccess, name, LEGACY_DB_VERSION);\n\n return fileAccess->isfile(dbPath);\n}\n\nconst LocalPath& SqliteDbAccess::rootPath() const\n{\n return mRootPath;\n}\n\nSqliteDbTable::SqliteDbTable(PrnGen &rng, sqlite3* db, FileSystemAccess &fsAccess, const string &path, const bool checkAlwaysTransacted)\n : DbTable(rng, checkAlwaysTransacted)\n , db(db)\n , pStmt(nullptr)\n , dbfile(path)\n , fsaccess(&fsAccess)\n{\n}\n\nSqliteDbTable::~SqliteDbTable()\n{\n resetCommitter();\n\n if (!db)\n {\n return;\n }\n\n sqlite3_finalize(pStmt);\n\n if (inTransaction())\n {\n abort();\n }\n\n sqlite3_close(db);\n LOG_debug << \"Database closed \" << dbfile;\n}\n\nbool SqliteDbTable::inTransaction() const\n{\n return sqlite3_get_autocommit(db) == 0;\n}\n\nLocalPath SqliteDbTable::dbFile() const\n{\n return LocalPath::fromPath(dbfile, *fsaccess);\n}\n\n\/\/ set cursor to first record\nvoid SqliteDbTable::rewind()\n{\n if (!db)\n {\n return;\n }\n\n int result;\n\n if (pStmt)\n {\n result = sqlite3_reset(pStmt);\n }\n else\n {\n result = sqlite3_prepare(db, \"SELECT id, content FROM statecache\", -1, &pStmt, NULL);\n }\n\n if (result != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(result));\n LOG_err << \"Unable to rewind database: \" << dbfile << err;\n assert(!\"Unable to rewind database.\");\n }\n}\n\n\/\/ retrieve next record through cursor\nbool SqliteDbTable::next(uint32_t* index, string* data)\n{\n if (!db)\n {\n return false;\n }\n\n if (!pStmt)\n {\n return false;\n }\n\n int rc = sqlite3_step(pStmt);\n\n if (rc != SQLITE_ROW)\n {\n sqlite3_finalize(pStmt);\n pStmt = NULL;\n\n if (rc != SQLITE_DONE)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to get next record from database: \" << dbfile << err;\n assert(!\"Unable to get next record from database.\");\n }\n\n return false;\n }\n\n *index = sqlite3_column_int(pStmt, 0);\n\n data->assign((char*)sqlite3_column_blob(pStmt, 1), sqlite3_column_bytes(pStmt, 1));\n\n return true;\n}\n\n\/\/ retrieve record by index\nbool SqliteDbTable::get(uint32_t index, string* data)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n sqlite3_stmt *stmt;\n int rc;\n\n rc = sqlite3_prepare(db, \"SELECT content FROM statecache WHERE id = ?\", -1, &stmt, NULL);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_int(stmt, 1, index);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_step(stmt);\n if (rc == SQLITE_ROW)\n {\n data->assign((char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));\n }\n }\n }\n\n sqlite3_finalize(stmt);\n\n if (rc != SQLITE_DONE && rc != SQLITE_ROW)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to get record from database: \" << dbfile << err;\n assert(!\"Unable to get record from database.\");\n }\n\n return rc == SQLITE_ROW;\n}\n\n\/\/ add\/update record by index\nbool SqliteDbTable::put(uint32_t index, char* data, unsigned len)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n sqlite3_stmt *stmt;\n bool result = false;\n\n int rc = sqlite3_prepare(db, \"INSERT OR REPLACE INTO statecache (id, content) VALUES (?, ?)\", -1, &stmt, NULL);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_int(stmt, 1, index);\n if (rc == SQLITE_OK)\n {\n rc = sqlite3_bind_blob(stmt, 2, data, len, SQLITE_STATIC);\n if (rc == SQLITE_OK)\n {\n\n rc = sqlite3_step(stmt);\n if (rc == SQLITE_DONE)\n {\n result = true;\n }\n }\n }\n }\n\n sqlite3_finalize(stmt);\n\n if (!result)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to put record into database: \" << dbfile << err;\n assert(!\"Unable to put record into database.\");\n }\n\n return result;\n}\n\n\/\/ delete record by index\nbool SqliteDbTable::del(uint32_t index)\n{\n if (!db)\n {\n return false;\n }\n\n checkTransaction();\n\n char buf[64];\n\n sprintf(buf, \"DELETE FROM statecache WHERE id = %\" PRIu32, index);\n\n int rc = sqlite3_exec(db, buf, 0, 0, nullptr);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to delete record from database: \" << dbfile << err;\n assert(!\"Unable to delete record from database.\");\n\n return false;\n }\n\n return true;\n}\n\n\/\/ truncate table\nvoid SqliteDbTable::truncate()\n{\n if (!db)\n {\n return;\n }\n\n checkTransaction();\n\n int rc = sqlite3_exec(db, \"DELETE FROM statecache\", 0, 0, NULL);\n if (rc != API_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to truncate database: \" << dbfile << err;\n assert(!\"Unable to truncate database.\");\n }\n}\n\n\/\/ begin transaction\nvoid SqliteDbTable::begin()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction BEGIN \" << dbfile;\n int rc = sqlite3_exec(db, \"BEGIN\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to begin transaction on database: \" << dbfile << err;\n assert(!\"Unable to begin transaction on database.\");\n }\n}\n\n\/\/ commit transaction\nvoid SqliteDbTable::commit()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction COMMIT \" << dbfile;\n\n int rc = sqlite3_exec(db, \"COMMIT\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to commit transaction on database: \" << dbfile << err;\n assert(!\"Unable to commit transaction on database.\");\n }\n}\n\n\/\/ abort transaction\nvoid SqliteDbTable::abort()\n{\n if (!db)\n {\n return;\n }\n\n LOG_debug << \"DB transaction ROLLBACK \" << dbfile;\n\n int rc = sqlite3_exec(db, \"ROLLBACK\", 0, 0, NULL);\n if (rc != SQLITE_OK)\n {\n string err = string(\" Error: \") + (sqlite3_errmsg(db) ? sqlite3_errmsg(db) : std::to_string(rc));\n LOG_err << \"Unable to rollback transaction on database: \" << dbfile << err;\n assert(!\"Unable to rollback transaction on database.\");\n }\n}\n\nvoid SqliteDbTable::remove()\n{\n if (!db)\n {\n return;\n }\n\n sqlite3_finalize(pStmt);\n\n if (inTransaction())\n {\n abort();\n }\n\n sqlite3_close(db);\n\n db = NULL;\n\n auto localpath = LocalPath::fromPath(dbfile, *fsaccess);\n fsaccess->unlinklocal(localpath);\n}\n\n} \/\/ namespace\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"game.h\"\n\n\/\/ My strategy to play the dice sum game\n\/\/ Returns 0 for ten's position, 1 for one's position\nint myStrategy(int gameState[4][2], int diceValue) {\n\tstatic int initialized;\t\t\/\/ Static variable, default to zero\n\t\/\/ Add your declaration of DP structure here\n\tif (!initialized) {\n\t\tinitialized = 1;\n\t\t\/\/ Populate your structure here\n\t}\n\tint tenAvailCount = 0;\t\/\/ No. of available ten's position\n\tfor (int j = 0; j < 4; j++)\n\t\tif (gameState[j][0] <= 0) {tenAvailCount = 4 - j; break;}\n\tint oneAvailCount = 0;\t\/\/ No. of available one's position\n\tfor (int j = 0; j < 4; j++)\n\t\tif (gameState[j][1] <= 0) {oneAvailCount = 4 - j; break;}\n\tif ((tenAvailCount != 0) && (oneAvailCount == 0)) return (0);\n\tif ((tenAvailCount == 0) && (oneAvailCount != 0)) return (1);\n\/\/\tMy strategy\n\tint strategy = 1;\n\tint nextPos, total;\n\tswitch (strategy) {\n\tcase 1:\n\t\tnextPos = rand() % 2;\n\t\tbreak;\n\tcase 2:\n\t\tnextPos = 0;\n\t\ttotal = (gameState[0][0] + gameState[1][0] + gameState[2][0] + gameState[3][0]) * 10\n\t\t + (gameState[0][1] + gameState[1][1] + gameState[2][1] + gameState[3][1]);\n\t\tif (total + diceValue * 10 > SCOREMAX)\n\t\t\tnextPos = 1;\n\t\tbreak;\n\tcase 3:\n\t\t\/\/ Add your own strategy (which uses the DP structure) here\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Error!\\n\");\n\t}\n\treturn (nextPos);\n}\n<commit_msg>add accepted HW5<commit_after>#include \"game.h\"\n#define POSITION_TEN 0\n#define POSITION_ONE 1\n\nstatic int dp[5][5][152];\nstatic int score;\nstatic const int penalty = -100;\n\nstatic int expScore(int tens, int ones, int score) {\n\tif (score > SCOREMAX)\n\t\treturn penalty;\n\n\tif (dp[tens][ones][score])\n\t\treturn dp[tens][ones][score];\n\n\tif (tens == 0 && ones == 0) {\n\t\treturn dp[0][0][score] = score <= SCOREMAX ? score : penalty;\n\t}\n\n\tint expval = 0;\n\tfor (int i = 1; i <= 6; i++) {\n\t\texpval += max(tens > 0 ? expScore(tens - 1, ones, score + i * 10) : 0,\n\t\t ones > 0 ? expScore(tens, ones - 1, score + i) : 0);\n\t}\n\n\treturn dp[tens][ones][score] = expval;\n}\n\nstatic int getAvailCount(int state[][2], int offs) {\n\tfor (int i = 0; i < 4; i++)\n\t\tif (state[i][offs] > 0) {\n\t\t\tscore += state[i][offs] * (offs == POSITION_TEN ? 10 : 1);\n\t\t} else return 4 - i;\n\treturn 0;\n}\n\n__attribute__((constructor))\nstatic void initializeTable() {\n\texpScore(4, 4, 0);\n}\n\n\/\/ My strategy to play the dice sum game\n\/\/ Returns 0 for ten's position, 1 for one's position\nint myStrategy(int gameState[4][2], int diceValue) {\n\tscore = 0;\n\tint tenAvailCount = getAvailCount(gameState, POSITION_TEN);\n\tint oneAvailCount = getAvailCount(gameState, POSITION_ONE);\n\t\/\/ score is calculated now (bad coding style, I know)\n\n\tif (oneAvailCount == 0) return POSITION_TEN;\n\tif (tenAvailCount == 0) return POSITION_ONE;\n\n\treturn (expScore(tenAvailCount - 1, oneAvailCount, score + diceValue * 10) >\n\t expScore(tenAvailCount, oneAvailCount - 1, score + diceValue)) ?\n\t POSITION_TEN : POSITION_ONE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of meshoptimizer library; see meshoptimizer.h for version\/license details\n#include \"meshoptimizer.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <vector>\n\nnamespace meshopt\n{\n\nstatic unsigned int MurmurHash2(const void* key, size_t len, unsigned int seed)\n{\n\tconst unsigned int m = 0x5bd1e995;\n\tconst int r = 24;\n\n\tunsigned int h = seed ^ static_cast<unsigned int>(len);\n\n\t\/\/ Mix 4 bytes at a time into the hash\n\tconst unsigned char* data = (const unsigned char*)key;\n\n\twhile (len >= 4)\n\t{\n\t\tunsigned int k = *(unsigned int*)data;\n\n\t\tk *= m;\n\t\tk ^= k >> r;\n\t\tk *= m;\n\n\t\th *= m;\n\t\th ^= k;\n\n\t\tdata += 4;\n\t\tlen -= 4;\n\t}\n\n\t\/\/ Handle the last few bytes of the input array\n\tswitch (len)\n\t{\n\tcase 3:\n\t\th ^= data[2] << 16;\n\tcase 2:\n\t\th ^= data[1] << 8;\n\tcase 1:\n\t\th ^= data[0];\n\t\th *= m;\n\t};\n\n\t\/\/ Do a few final mixes of the hash to ensure the last few\n\t\/\/ bytes are well-incorporated.\n\n\th ^= h >> 13;\n\th *= m;\n\th ^= h >> 15;\n\n\treturn h;\n}\n\nstruct VertexHasher\n{\n\tconst char* vertices;\n\tsize_t vertex_size;\n\n\tunsigned int empty() const\n\t{\n\t\treturn ~0u;\n\t}\n\n\tsize_t operator()(unsigned int index) const\n\t{\n\t\treturn MurmurHash2(vertices + index * vertex_size, vertex_size, 0);\n\t}\n\n\tsize_t operator()(unsigned int lhs, unsigned int rhs) const\n\t{\n\t\treturn memcmp(vertices + lhs * vertex_size, vertices + rhs * vertex_size, vertex_size) == 0;\n\t}\n};\n\nstruct VertexHashEntry\n{\n\tunsigned int key;\n\tunsigned int value;\n};\n\ntemplate <typename T, typename Hash>\nstatic void hashInit(std::vector<T>& table, const Hash& hash, size_t count)\n{\n\tsize_t buckets = 1;\n\twhile (buckets < count)\n\t\tbuckets *= 2;\n\n\tT dummy = T();\n\tdummy.key = hash.empty();\n\n\ttable.clear();\n\ttable.resize(buckets, dummy);\n}\n\ntemplate <typename T, typename Hash, typename Key>\nstatic T* hashLookup(std::vector<T>& table, const Hash& hash, const Key& key)\n{\n\tassert((table.size() & (table.size() - 1)) == 0);\n\n\tsize_t hashmod = table.size() - 1;\n\tsize_t hashval = hash(key);\n\tsize_t bucket = hashval & hashmod;\n\n\tfor (size_t probe = 0; probe <= hashmod; ++probe)\n\t{\n\t\tT& item = table[bucket];\n\n\t\tif (item.key == hash.empty())\n\t\t\treturn &item;\n\n\t\tif (hash(item.key, key))\n\t\t\treturn &item;\n\n\t\t\/\/ hash collision, quadratic probing\n\t\tbucket = (bucket + probe + 1) & hashmod;\n\t}\n\n\tassert(false && \"Hash table is full\");\n\treturn 0;\n}\n\n} \/\/ namespace meshopt\n\nsize_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)\n{\n\tusing namespace meshopt;\n\n\tassert(indices || index_count == vertex_count);\n\tassert(index_count % 3 == 0);\n\tassert(vertex_size > 0);\n\n\tfor (size_t i = 0; i < vertex_count; ++i)\n\t{\n\t\tdestination[i] = ~0u;\n\t}\n\n\tVertexHasher hasher = {static_cast<const char*>(vertices), vertex_size};\n\n\tstd::vector<VertexHashEntry> table;\n\thashInit(table, hasher, vertex_count);\n\n\tunsigned int next_vertex = 0;\n\n\tfor (size_t i = 0; i < index_count; ++i)\n\t{\n\t\tunsigned int index = indices ? indices[i] : unsigned(i);\n\t\tassert(index < vertex_count);\n\n\t\tif (destination[index] == ~0u)\n\t\t{\n\t\t\tVertexHashEntry* entry = hashLookup(table, hasher, index);\n\n\t\t\tif (entry->key == ~0u)\n\t\t\t{\n\t\t\t\tentry->key = index;\n\t\t\t\tentry->value = next_vertex++;\n\t\t\t}\n\n\t\t\tdestination[index] = entry->value;\n\t\t}\n\t}\n\n\treturn next_vertex;\n}\n\nvoid meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap)\n{\n\tassert(destination != vertices);\n\tassert(vertex_size > 0);\n\n\tfor (size_t i = 0; i < vertex_count; ++i)\n\t{\n\t\tmemcpy(static_cast<char*>(destination) + remap[i] * vertex_size, static_cast<const char*>(vertices) + i * vertex_size, vertex_size);\n\t}\n}\n\nvoid meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap)\n{\n\tassert(index_count % 3 == 0);\n\n\tif (indices)\n\t{\n\t\tfor (size_t i = 0; i < index_count; ++i)\n\t\t{\n\t\t\tdestination[i] = remap[indices[i]];\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (size_t i = 0; i < index_count; ++i)\n\t\t{\n\t\t\tdestination[i] = remap[i];\n\t\t}\n\t}\n}\n<commit_msg>indexgenerator: Fix VB remap when some vertices are unused<commit_after>\/\/ This file is part of meshoptimizer library; see meshoptimizer.h for version\/license details\n#include \"meshoptimizer.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <vector>\n\nnamespace meshopt\n{\n\nstatic unsigned int murmurHash2(const void* key, size_t len, unsigned int seed)\n{\n\tconst unsigned int m = 0x5bd1e995;\n\tconst int r = 24;\n\n\tunsigned int h = seed ^ static_cast<unsigned int>(len);\n\n\t\/\/ Mix 4 bytes at a time into the hash\n\tconst unsigned char* data = (const unsigned char*)key;\n\n\twhile (len >= 4)\n\t{\n\t\tunsigned int k = *(unsigned int*)data;\n\n\t\tk *= m;\n\t\tk ^= k >> r;\n\t\tk *= m;\n\n\t\th *= m;\n\t\th ^= k;\n\n\t\tdata += 4;\n\t\tlen -= 4;\n\t}\n\n\t\/\/ Handle the last few bytes of the input array\n\tswitch (len)\n\t{\n\tcase 3:\n\t\th ^= data[2] << 16;\n\tcase 2:\n\t\th ^= data[1] << 8;\n\tcase 1:\n\t\th ^= data[0];\n\t\th *= m;\n\t};\n\n\t\/\/ Do a few final mixes of the hash to ensure the last few\n\t\/\/ bytes are well-incorporated.\n\n\th ^= h >> 13;\n\th *= m;\n\th ^= h >> 15;\n\n\treturn h;\n}\n\nstruct VertexHasher\n{\n\tconst char* vertices;\n\tsize_t vertex_size;\n\n\tunsigned int empty() const\n\t{\n\t\treturn ~0u;\n\t}\n\n\tsize_t operator()(unsigned int index) const\n\t{\n\t\treturn murmurHash2(vertices + index * vertex_size, vertex_size, 0);\n\t}\n\n\tsize_t operator()(unsigned int lhs, unsigned int rhs) const\n\t{\n\t\treturn memcmp(vertices + lhs * vertex_size, vertices + rhs * vertex_size, vertex_size) == 0;\n\t}\n};\n\nstruct VertexHashEntry\n{\n\tunsigned int key;\n\tunsigned int value;\n};\n\ntemplate <typename T, typename Hash>\nstatic void hashInit(std::vector<T>& table, const Hash& hash, size_t count)\n{\n\tsize_t buckets = 1;\n\twhile (buckets < count)\n\t\tbuckets *= 2;\n\n\tT dummy = T();\n\tdummy.key = hash.empty();\n\n\ttable.clear();\n\ttable.resize(buckets, dummy);\n}\n\ntemplate <typename T, typename Hash, typename Key>\nstatic T* hashLookup(std::vector<T>& table, const Hash& hash, const Key& key)\n{\n\tassert((table.size() & (table.size() - 1)) == 0);\n\n\tsize_t hashmod = table.size() - 1;\n\tsize_t hashval = hash(key);\n\tsize_t bucket = hashval & hashmod;\n\n\tfor (size_t probe = 0; probe <= hashmod; ++probe)\n\t{\n\t\tT& item = table[bucket];\n\n\t\tif (item.key == hash.empty())\n\t\t\treturn &item;\n\n\t\tif (hash(item.key, key))\n\t\t\treturn &item;\n\n\t\t\/\/ hash collision, quadratic probing\n\t\tbucket = (bucket + probe + 1) & hashmod;\n\t}\n\n\tassert(false && \"Hash table is full\");\n\treturn 0;\n}\n\n} \/\/ namespace meshopt\n\nsize_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)\n{\n\tusing namespace meshopt;\n\n\tassert(indices || index_count == vertex_count);\n\tassert(index_count % 3 == 0);\n\tassert(vertex_size > 0);\n\n\tfor (size_t i = 0; i < vertex_count; ++i)\n\t{\n\t\tdestination[i] = ~0u;\n\t}\n\n\tVertexHasher hasher = {static_cast<const char*>(vertices), vertex_size};\n\n\tstd::vector<VertexHashEntry> table;\n\thashInit(table, hasher, vertex_count);\n\n\tunsigned int next_vertex = 0;\n\n\tfor (size_t i = 0; i < index_count; ++i)\n\t{\n\t\tunsigned int index = indices ? indices[i] : unsigned(i);\n\t\tassert(index < vertex_count);\n\n\t\tif (destination[index] == ~0u)\n\t\t{\n\t\t\tVertexHashEntry* entry = hashLookup(table, hasher, index);\n\n\t\t\tif (entry->key == ~0u)\n\t\t\t{\n\t\t\t\tentry->key = index;\n\t\t\t\tentry->value = next_vertex++;\n\t\t\t}\n\n\t\t\tdestination[index] = entry->value;\n\t\t}\n\t}\n\n\treturn next_vertex;\n}\n\nvoid meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap)\n{\n\tassert(destination != vertices);\n\tassert(vertex_size > 0);\n\n\tfor (size_t i = 0; i < vertex_count; ++i)\n\t{\n\t\tif (remap[i] != ~0u)\n\t\t{\n\t\t\tmemcpy(static_cast<char*>(destination) + remap[i] * vertex_size, static_cast<const char*>(vertices) + i * vertex_size, vertex_size);\n\t\t}\n\t}\n}\n\nvoid meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap)\n{\n\tassert(index_count % 3 == 0);\n\n\tfor (size_t i = 0; i < index_count; ++i)\n\t{\n\t\tunsigned int index = indices ? indices[i] : unsigned(i);\n\t\tassert(remap[index] != ~0u);\n\n\t\tdestination[i] = remap[index];\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * * Neither the name of Intel Corporation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include <map>\n#include <functional>\n\n#include \"ApplicationSamplerImp.hpp\"\n#include \"ApplicationRecordLog.hpp\"\n#include \"ApplicationStatus.hpp\"\n#include \"ProfileSampler.hpp\"\n#include \"ProfileIOSample.hpp\"\n#include \"EpochRuntimeRegulator.hpp\"\n#include \"Exception.hpp\"\n#include \"RecordFilter.hpp\"\n#include \"Environment.hpp\"\n#include \"ValidateRecord.hpp\"\n#include \"SharedMemory.hpp\"\n#include \"PlatformTopo.hpp\"\n#include \"record.hpp\"\n#include \"geopm_debug.hpp\"\n#include \"geopm.h\"\n#include \"geopm_hash.h\"\n\nnamespace geopm\n{\n ApplicationSampler &ApplicationSampler::application_sampler(void)\n {\n static ApplicationSamplerImp instance;\n return instance;\n }\n\n std::set<uint64_t> ApplicationSampler::region_hash_network(void)\n {\n static std::set <uint64_t> result = region_hash_network_once();\n return result;\n }\n\n std::set<uint64_t> ApplicationSampler::region_hash_network_once(void)\n {\n std::set<uint64_t> ret;\n std::set<std::string> network_funcs {\"MPI_Allgather\",\n \"MPI_Allgatherv\",\n \"MPI_Allreduce\",\n \"MPI_Alltoall\",\n \"MPI_Alltoallv\",\n \"MPI_Alltoallw\",\n \"MPI_Barrier\",\n \"MPI_Bcast\"\n \"MPI_Bsend\",\n \"MPI_Bsend_init\",\n \"MPI_Gather\",\n \"MPI_Gatherv\",\n \"MPI_Neighbor_allgather\",\n \"MPI_Neighbor_allgatherv\",\n \"MPI_Neighbor_alltoall\",\n \"MPI_Neighbor_alltoallv\",\n \"MPI_Neighbor_alltoallw\",\n \"MPI_Reduce\",\n \"MPI_Reduce_scatter\",\n \"MPI_Reduce_scatter_block\",\n \"MPI_Rsend\"\n \"MPI_Rsend_init\",\n \"MPI_Scan\",\n \"MPI_Scatter\",\n \"MPI_Scatterv\",\n \"MPI_Waitall\",\n \"MPI_Waitany\",\n \"MPI_Wait\",\n \"MPI_Waitsome\",\n \"MPI_Exscan\",\n \"MPI_Recv\",\n \"MPI_Send\",\n \"MPI_Sendrecv\",\n \"MPI_Sendrecv_replace\",\n \"MPI_Ssend\"};\n for (auto const &func_name : network_funcs) {\n ret.insert(geopm_crc32_str(func_name.c_str()));\n }\n return ret;\n }\n\n ApplicationSamplerImp::ApplicationSamplerImp()\n : ApplicationSamplerImp(nullptr,\n platform_topo().num_domain(GEOPM_DOMAIN_CPU),\n std::map<int, m_process_s> {},\n environment().do_record_filter(),\n environment().record_filter())\n {\n\n }\n\n const std::map<uint64_t, double> ApplicationSamplerImp::m_hint_time_init = {\n {GEOPM_REGION_HINT_UNKNOWN, 0.0},\n {GEOPM_REGION_HINT_COMPUTE, 0.0},\n {GEOPM_REGION_HINT_MEMORY, 0.0},\n {GEOPM_REGION_HINT_NETWORK, 0.0},\n {GEOPM_REGION_HINT_IO, 0.0},\n {GEOPM_REGION_HINT_SERIAL, 0.0},\n {GEOPM_REGION_HINT_PARALLEL, 0.0},\n {GEOPM_REGION_HINT_IGNORE, 0.0},\n };\n\n\n ApplicationSamplerImp::ApplicationSamplerImp(std::shared_ptr<ApplicationStatus> status,\n int num_cpu,\n const std::map<int, m_process_s> &process_map,\n bool is_filtered,\n const std::string &filter_name)\n : m_time_zero(geopm::time_zero())\n , m_status(status)\n , m_num_cpu(num_cpu)\n , m_process_map(process_map)\n , m_is_filtered(is_filtered)\n , m_filter_name(filter_name)\n , m_hint_time(m_num_cpu, m_hint_time_init)\n , m_update_time({{0, 0}})\n , m_is_first_update(true)\n {\n\n }\n\n void ApplicationSamplerImp::time_zero(const geopm_time_s &start_time)\n {\n m_time_zero = start_time;\n }\n\n void ApplicationSamplerImp::update(const geopm_time_s &curr_time)\n {\n m_status->update_cache();\n if (!m_is_first_update) {\n double time_delta = geopm_time_diff(&m_update_time, &curr_time);\n for (int cpu_idx = 0; cpu_idx != m_num_cpu; ++cpu_idx) {\n uint64_t hint = m_status->get_hint(cpu_idx);\n m_hint_time[cpu_idx].at(hint) += time_delta;\n }\n }\n m_is_first_update = false;\n m_update_time = curr_time;\n \/\/ Dump the record log from each process, filter the results,\n \/\/ and reindex the short region event signals.\n\n \/\/ Clear the buffers that we will be building.\n m_record_buffer.clear();\n m_short_region_buffer.clear();\n \/\/ Iterate over the record log for each process\n for (auto &proc_map_it : m_process_map) {\n \/\/ Record the location in the record buffer where this\n \/\/ process' data begins for updating the short region\n \/\/ event signals.\n size_t record_offset = m_record_buffer.size();\n \/\/ Get data from the record log\n auto &proc_it = proc_map_it.second;\n proc_it.record_log->dump(proc_it.records, proc_it.short_regions);\n if (m_is_filtered) {\n \/\/ Filter and check the records and push them onto\n \/\/ m_record_buffer\n for (const auto &record_it : proc_it.records) {\n for (auto &filtered_it : proc_it.filter->filter(record_it)) {\n proc_it.valid.check(filtered_it);\n m_record_buffer.push_back(filtered_it);\n }\n }\n }\n else {\n \/\/ Check the records and push them onto m_record_buffer\n for (const auto &record : proc_it.records) {\n proc_it.valid.check(record);\n }\n m_record_buffer.insert(m_record_buffer.end(),\n proc_it.records.begin(),\n proc_it.records.end());\n }\n \/\/ Update the \"signal\" field for all of the short region\n \/\/ events to have the right offset.\n size_t short_region_remain = proc_it.short_regions.size();\n for (auto record_it = m_record_buffer.begin() + record_offset;\n short_region_remain > 0 &&\n record_it != m_record_buffer.end();\n ++record_it) {\n if (record_it->event == EVENT_SHORT_REGION) {\n record_it->signal += m_short_region_buffer.size();\n --short_region_remain;\n }\n }\n m_short_region_buffer.insert(m_short_region_buffer.end(),\n proc_it.short_regions.begin(),\n proc_it.short_regions.end());\n }\n }\n\n std::vector<record_s> ApplicationSamplerImp::get_records(void) const\n {\n return m_record_buffer;\n }\n\n short_region_s ApplicationSamplerImp::get_short_region(uint64_t event_signal) const\n {\n if (event_signal >= m_short_region_buffer.size()) {\n throw Exception(\"ApplicationSampler::get_short_region(), event_signal does not match any short region handle\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return m_short_region_buffer[event_signal];\n }\n\n std::map<uint64_t, std::string> ApplicationSamplerImp::get_name_map(uint64_t name_key) const\n {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"() is not yet implemented\",\n GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__);\n return {};\n }\n\n uint64_t ApplicationSamplerImp::cpu_hint(int cpu_idx) const\n {\n return m_status->get_hint(cpu_idx);\n }\n\n double ApplicationSamplerImp::cpu_hint_time(int cpu_idx, uint64_t hint) const\n {\n if (cpu_idx < 0 || cpu_idx >= m_num_cpu) {\n throw Exception(\"ApplicationSampler::\" + std::string(__func__) +\n \"(): cpu_idx is out of range: \" + std::to_string(cpu_idx),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n auto &hint_map = m_hint_time[cpu_idx];\n auto it = hint_map.find(hint);\n if (it == hint_map.end()) {\n throw Exception(\"ApplicationSampler::\" + std::string(__func__) +\n \"(): hint is invalid: \" + std::to_string(hint),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n double ApplicationSamplerImp::cpu_progress(int cpu_idx) const\n {\n return m_status->get_progress_cpu(cpu_idx);\n }\n\n std::vector<int> ApplicationSamplerImp::per_cpu_process(void) const\n {\n std::vector<int> result(m_num_cpu);\n for (int cpu_idx = 0; cpu_idx != m_num_cpu; ++cpu_idx) {\n result[cpu_idx] = m_status->get_process(cpu_idx);\n }\n return result;\n }\n\n void ApplicationSamplerImp::connect(const std::string &shm_key)\n {\n if (!m_status) {\n std::string shmem_name = shm_key + \"-status\";\n std::shared_ptr<SharedMemory> status_shmem =\n SharedMemory::make_unique_owner(shmem_name,\n ApplicationStatus::buffer_size(m_num_cpu));\n m_status = ApplicationStatus::make_unique(m_num_cpu, status_shmem);\n GEOPM_DEBUG_ASSERT(m_process_map.empty(),\n \"m_process_map is not empty, but we are connecting\");\n \/\/ Convert per-cpu process to a set of the unique process id's\n std::set<int> proc_set;\n for (const auto &proc_it : per_cpu_process()) {\n proc_set.insert(proc_it);\n }\n \/\/ For each unique process id create a record log and\n \/\/ insert it into map indexed by process id\n for (const auto &proc_it : proc_set) {\n std::string shmem_name = shm_key + \"-record-log-\" + std::to_string(proc_it);\n std::shared_ptr<SharedMemory> record_log_shmem =\n SharedMemory::make_unique_owner(shmem_name,\n ApplicationRecordLog::buffer_size());\n auto emplace_ret = m_process_map.emplace(proc_it, m_process_s {});\n auto &process = emplace_ret.first->second;\n if (m_is_filtered) {\n process.filter = RecordFilter::make_unique(m_filter_name);\n }\n process.record_log = ApplicationRecordLog::make_unique(record_log_shmem);\n process.records.reserve(ApplicationRecordLog::max_record());\n process.short_regions.reserve(ApplicationRecordLog::max_region());\n }\n }\n }\n\n void ApplicationSamplerImp::set_sampler(std::shared_ptr<ProfileSampler> sampler)\n {\n m_sampler = sampler;\n }\n\n std::shared_ptr<ProfileSampler> ApplicationSamplerImp::get_sampler(void)\n {\n return m_sampler;\n }\n\n void ApplicationSamplerImp::set_regulator(std::shared_ptr<EpochRuntimeRegulator> regulator)\n {\n m_regulator = regulator;\n }\n\n std::shared_ptr<EpochRuntimeRegulator> ApplicationSamplerImp::get_regulator(void)\n {\n return m_regulator;\n }\n\n void ApplicationSamplerImp::set_io_sample(std::shared_ptr<ProfileIOSample> io_sample)\n {\n m_io_sample = io_sample;\n }\n\n std::shared_ptr<ProfileIOSample> ApplicationSamplerImp::get_io_sample(void)\n {\n return m_io_sample;\n }\n}\n<commit_msg>Add exceptions to AppSampler for using status before connect()<commit_after>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * * Neither the name of Intel Corporation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include <map>\n#include <functional>\n\n#include \"ApplicationSamplerImp.hpp\"\n#include \"ApplicationRecordLog.hpp\"\n#include \"ApplicationStatus.hpp\"\n#include \"ProfileSampler.hpp\"\n#include \"ProfileIOSample.hpp\"\n#include \"EpochRuntimeRegulator.hpp\"\n#include \"Exception.hpp\"\n#include \"RecordFilter.hpp\"\n#include \"Environment.hpp\"\n#include \"ValidateRecord.hpp\"\n#include \"SharedMemory.hpp\"\n#include \"PlatformTopo.hpp\"\n#include \"record.hpp\"\n#include \"geopm_debug.hpp\"\n#include \"geopm.h\"\n#include \"geopm_hash.h\"\n\nnamespace geopm\n{\n ApplicationSampler &ApplicationSampler::application_sampler(void)\n {\n static ApplicationSamplerImp instance;\n return instance;\n }\n\n std::set<uint64_t> ApplicationSampler::region_hash_network(void)\n {\n static std::set <uint64_t> result = region_hash_network_once();\n return result;\n }\n\n std::set<uint64_t> ApplicationSampler::region_hash_network_once(void)\n {\n std::set<uint64_t> ret;\n std::set<std::string> network_funcs {\"MPI_Allgather\",\n \"MPI_Allgatherv\",\n \"MPI_Allreduce\",\n \"MPI_Alltoall\",\n \"MPI_Alltoallv\",\n \"MPI_Alltoallw\",\n \"MPI_Barrier\",\n \"MPI_Bcast\"\n \"MPI_Bsend\",\n \"MPI_Bsend_init\",\n \"MPI_Gather\",\n \"MPI_Gatherv\",\n \"MPI_Neighbor_allgather\",\n \"MPI_Neighbor_allgatherv\",\n \"MPI_Neighbor_alltoall\",\n \"MPI_Neighbor_alltoallv\",\n \"MPI_Neighbor_alltoallw\",\n \"MPI_Reduce\",\n \"MPI_Reduce_scatter\",\n \"MPI_Reduce_scatter_block\",\n \"MPI_Rsend\"\n \"MPI_Rsend_init\",\n \"MPI_Scan\",\n \"MPI_Scatter\",\n \"MPI_Scatterv\",\n \"MPI_Waitall\",\n \"MPI_Waitany\",\n \"MPI_Wait\",\n \"MPI_Waitsome\",\n \"MPI_Exscan\",\n \"MPI_Recv\",\n \"MPI_Send\",\n \"MPI_Sendrecv\",\n \"MPI_Sendrecv_replace\",\n \"MPI_Ssend\"};\n for (auto const &func_name : network_funcs) {\n ret.insert(geopm_crc32_str(func_name.c_str()));\n }\n return ret;\n }\n\n ApplicationSamplerImp::ApplicationSamplerImp()\n : ApplicationSamplerImp(nullptr,\n platform_topo().num_domain(GEOPM_DOMAIN_CPU),\n std::map<int, m_process_s> {},\n environment().do_record_filter(),\n environment().record_filter())\n {\n\n }\n\n const std::map<uint64_t, double> ApplicationSamplerImp::m_hint_time_init = {\n {GEOPM_REGION_HINT_UNKNOWN, 0.0},\n {GEOPM_REGION_HINT_COMPUTE, 0.0},\n {GEOPM_REGION_HINT_MEMORY, 0.0},\n {GEOPM_REGION_HINT_NETWORK, 0.0},\n {GEOPM_REGION_HINT_IO, 0.0},\n {GEOPM_REGION_HINT_SERIAL, 0.0},\n {GEOPM_REGION_HINT_PARALLEL, 0.0},\n {GEOPM_REGION_HINT_IGNORE, 0.0},\n };\n\n\n ApplicationSamplerImp::ApplicationSamplerImp(std::shared_ptr<ApplicationStatus> status,\n int num_cpu,\n const std::map<int, m_process_s> &process_map,\n bool is_filtered,\n const std::string &filter_name)\n : m_time_zero(geopm::time_zero())\n , m_status(status)\n , m_num_cpu(num_cpu)\n , m_process_map(process_map)\n , m_is_filtered(is_filtered)\n , m_filter_name(filter_name)\n , m_hint_time(m_num_cpu, m_hint_time_init)\n , m_update_time({{0, 0}})\n , m_is_first_update(true)\n {\n\n }\n\n void ApplicationSamplerImp::time_zero(const geopm_time_s &start_time)\n {\n m_time_zero = start_time;\n }\n\n void ApplicationSamplerImp::update(const geopm_time_s &curr_time)\n {\n if (!m_status) {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"(): cannot read process info before connect().\",\n GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);\n }\n m_status->update_cache();\n if (!m_is_first_update) {\n double time_delta = geopm_time_diff(&m_update_time, &curr_time);\n for (int cpu_idx = 0; cpu_idx != m_num_cpu; ++cpu_idx) {\n uint64_t hint = m_status->get_hint(cpu_idx);\n m_hint_time[cpu_idx].at(hint) += time_delta;\n }\n }\n m_is_first_update = false;\n m_update_time = curr_time;\n \/\/ Dump the record log from each process, filter the results,\n \/\/ and reindex the short region event signals.\n\n \/\/ Clear the buffers that we will be building.\n m_record_buffer.clear();\n m_short_region_buffer.clear();\n \/\/ Iterate over the record log for each process\n for (auto &proc_map_it : m_process_map) {\n \/\/ Record the location in the record buffer where this\n \/\/ process' data begins for updating the short region\n \/\/ event signals.\n size_t record_offset = m_record_buffer.size();\n \/\/ Get data from the record log\n auto &proc_it = proc_map_it.second;\n proc_it.record_log->dump(proc_it.records, proc_it.short_regions);\n if (m_is_filtered) {\n \/\/ Filter and check the records and push them onto\n \/\/ m_record_buffer\n for (const auto &record_it : proc_it.records) {\n for (auto &filtered_it : proc_it.filter->filter(record_it)) {\n proc_it.valid.check(filtered_it);\n m_record_buffer.push_back(filtered_it);\n }\n }\n }\n else {\n \/\/ Check the records and push them onto m_record_buffer\n for (const auto &record : proc_it.records) {\n proc_it.valid.check(record);\n }\n m_record_buffer.insert(m_record_buffer.end(),\n proc_it.records.begin(),\n proc_it.records.end());\n }\n \/\/ Update the \"signal\" field for all of the short region\n \/\/ events to have the right offset.\n size_t short_region_remain = proc_it.short_regions.size();\n for (auto record_it = m_record_buffer.begin() + record_offset;\n short_region_remain > 0 &&\n record_it != m_record_buffer.end();\n ++record_it) {\n if (record_it->event == EVENT_SHORT_REGION) {\n record_it->signal += m_short_region_buffer.size();\n --short_region_remain;\n }\n }\n m_short_region_buffer.insert(m_short_region_buffer.end(),\n proc_it.short_regions.begin(),\n proc_it.short_regions.end());\n }\n }\n\n std::vector<record_s> ApplicationSamplerImp::get_records(void) const\n {\n return m_record_buffer;\n }\n\n short_region_s ApplicationSamplerImp::get_short_region(uint64_t event_signal) const\n {\n if (event_signal >= m_short_region_buffer.size()) {\n throw Exception(\"ApplicationSampler::get_short_region(), event_signal does not match any short region handle\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return m_short_region_buffer[event_signal];\n }\n\n std::map<uint64_t, std::string> ApplicationSamplerImp::get_name_map(uint64_t name_key) const\n {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"() is not yet implemented\",\n GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__);\n return {};\n }\n\n uint64_t ApplicationSamplerImp::cpu_hint(int cpu_idx) const\n {\n if (!m_status) {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"(): cannot read process info before connect().\",\n GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);\n }\n return m_status->get_hint(cpu_idx);\n }\n\n double ApplicationSamplerImp::cpu_hint_time(int cpu_idx, uint64_t hint) const\n {\n if (cpu_idx < 0 || cpu_idx >= m_num_cpu) {\n throw Exception(\"ApplicationSampler::\" + std::string(__func__) +\n \"(): cpu_idx is out of range: \" + std::to_string(cpu_idx),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n auto &hint_map = m_hint_time[cpu_idx];\n auto it = hint_map.find(hint);\n if (it == hint_map.end()) {\n throw Exception(\"ApplicationSampler::\" + std::string(__func__) +\n \"(): hint is invalid: \" + std::to_string(hint),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n double ApplicationSamplerImp::cpu_progress(int cpu_idx) const\n {\n if (!m_status) {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"(): cannot read process info before connect().\",\n GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);\n }\n return m_status->get_progress_cpu(cpu_idx);\n }\n\n std::vector<int> ApplicationSamplerImp::per_cpu_process(void) const\n {\n if (!m_status) {\n throw Exception(\"ApplicationSamplerImp::\" + std::string(__func__) + \"(): cannot read process info before connect().\",\n GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);\n }\n std::vector<int> result(m_num_cpu);\n for (int cpu_idx = 0; cpu_idx != m_num_cpu; ++cpu_idx) {\n result[cpu_idx] = m_status->get_process(cpu_idx);\n }\n return result;\n }\n\n void ApplicationSamplerImp::connect(const std::string &shm_key)\n {\n if (!m_status) {\n std::string shmem_name = shm_key + \"-status\";\n std::shared_ptr<SharedMemory> status_shmem =\n SharedMemory::make_unique_owner(shmem_name,\n ApplicationStatus::buffer_size(m_num_cpu));\n m_status = ApplicationStatus::make_unique(m_num_cpu, status_shmem);\n GEOPM_DEBUG_ASSERT(m_process_map.empty(),\n \"m_process_map is not empty, but we are connecting\");\n \/\/ Convert per-cpu process to a set of the unique process id's\n std::set<int> proc_set;\n for (const auto &proc_it : per_cpu_process()) {\n proc_set.insert(proc_it);\n }\n \/\/ For each unique process id create a record log and\n \/\/ insert it into map indexed by process id\n for (const auto &proc_it : proc_set) {\n std::string shmem_name = shm_key + \"-record-log-\" + std::to_string(proc_it);\n std::shared_ptr<SharedMemory> record_log_shmem =\n SharedMemory::make_unique_owner(shmem_name,\n ApplicationRecordLog::buffer_size());\n auto emplace_ret = m_process_map.emplace(proc_it, m_process_s {});\n auto &process = emplace_ret.first->second;\n if (m_is_filtered) {\n process.filter = RecordFilter::make_unique(m_filter_name);\n }\n process.record_log = ApplicationRecordLog::make_unique(record_log_shmem);\n process.records.reserve(ApplicationRecordLog::max_record());\n process.short_regions.reserve(ApplicationRecordLog::max_region());\n }\n }\n }\n\n void ApplicationSamplerImp::set_sampler(std::shared_ptr<ProfileSampler> sampler)\n {\n m_sampler = sampler;\n }\n\n std::shared_ptr<ProfileSampler> ApplicationSamplerImp::get_sampler(void)\n {\n return m_sampler;\n }\n\n void ApplicationSamplerImp::set_regulator(std::shared_ptr<EpochRuntimeRegulator> regulator)\n {\n m_regulator = regulator;\n }\n\n std::shared_ptr<EpochRuntimeRegulator> ApplicationSamplerImp::get_regulator(void)\n {\n return m_regulator;\n }\n\n void ApplicationSamplerImp::set_io_sample(std::shared_ptr<ProfileIOSample> io_sample)\n {\n m_io_sample = io_sample;\n }\n\n std::shared_ptr<ProfileIOSample> ApplicationSamplerImp::get_io_sample(void)\n {\n return m_io_sample;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * METISParser.cpp\n *\n * Created on: 27.11.2012\n * Author: cls\n *\/\n\n#include \"METISParser.h\"\n\n\nnamespace EnsembleClustering {\n\n\n\/**\n * Extract a vector of indices from a line in the file.\n *\n * @param[in]\tline\t\tline from input file containing node indices\n *\n * @param[out]\tindices\t\tnode indices extracted from line\n *\/\nstatic std::vector<node> parseLine(std::string line) {\n\n\tstd::stringstream stream(line);\n\tstd::string token;\n\tchar delim = ' ';\n\tstd::vector<node> adjacencies;\n\n\t\/\/ split string and push adjacent nodes\n\twhile (std::getline(stream, token, delim)) {\n\t\tif (token.size() != 0) {\n\t\t\tnode v = atoi(token.c_str());\n\t\t\tadjacencies.push_back(v);\n\t\t}\n\t}\n\n\treturn adjacencies;\n}\n\n\nstatic inline std::vector<node> parseLineDIY(std::string line) {\n\t\/\/ TODO: is this faster?\n\n\tstd::string token;\n\tchar delim = ' ';\n\tstd::vector<node> adjacencies;\n\n\tfor (char& c : line) {\n\t\tif (c == delim) {\n\t\t\tnode v = atoi(token.c_str());\n\t\t\tadjacencies.push_back(v);\n\t\t\ttoken.clear();\n\t\t} else if (c == '\\n') {\n\t\t\tbreak;\n\t\t} else {\n\t\t\ttoken.push_back(c);\n\t\t}\n\t}\n\n\treturn adjacencies;\n}\n\n\nMETISParser::METISParser(std::string path) : graphFile(path) {\n\tif (!(this->graphFile)) {\n\t\tERROR(\"invalid graph file: \" << path);\n\t\tthrow std::runtime_error(\"invalid graph file\");\n\t}\n}\n\n\n\nMETISParser::~METISParser() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\n\n\nstd::pair<int, int> METISParser::getHeader() {\n\n\t\/\/ handle header line\n\tint n; \/\/ number of nodes\n\tint m;\t\/\/ number of edges\n\n\tstd::string line = \"\";\n\tassert (this->graphFile);\n\tif (std::getline(this->graphFile, line)) {\n\t\tstd::vector<node> tokens = parseLine(line);\n\t\tn = tokens[0];\n\t\tm = tokens[1];\n\n\t\treturn std::make_pair(n, m);\n\t} else {\n\t\tERROR(\"getline not successful\");\n\t\tthrow std::runtime_error(\"getting METIS file header failed\");\n\t\treturn std::make_pair(0,0);\n\t}\n\n}\n\n\nbool METISParser::hasNext() {\n\t\/\/ if graph file has lines left, return true\n\treturn this->graphFile.good();\n}\n\n\nstd::vector<node> METISParser::getNext() {\n\n\tstd::string line;\n\tbool comment = false;\n\tdo {\n\t\tcomment = false;\n\t\tstd::getline(this->graphFile, line);\n\t\t\/\/ check for comment line starting with '%'\n\t\tif (line[0] == '%') {\n\t\t\tcomment = true;\n\t\t} else {\n\t\t\treturn parseLine(line);\n\t\t}\n\n\t} while (comment);\n\n\tthrow std::runtime_error(\"bad METIS file structure\");\n\tstd::vector<node> fail;\n\treturn fail;\n}\n\n\n\n\n} \/* namespace EnsembleClustering *\/\n<commit_msg>fixed: METISParser can read files beginning with comment lines<commit_after>\/*\n * METISParser.cpp\n *\n * Created on: 27.11.2012\n * Author: cls\n *\/\n\n#include \"METISParser.h\"\n\n\nnamespace EnsembleClustering {\n\n\n\/**\n * Extract a vector of indices from a line in the file.\n *\n * @param[in]\tline\t\tline from input file containing node indices\n *\n * @param[out]\tindices\t\tnode indices extracted from line\n *\/\nstatic std::vector<node> parseLine(std::string line) {\n\n\tstd::stringstream stream(line);\n\tstd::string token;\n\tchar delim = ' ';\n\tstd::vector<node> adjacencies;\n\n\t\/\/ split string and push adjacent nodes\n\twhile (std::getline(stream, token, delim)) {\n\t\tif (token.size() != 0) {\n\t\t\tnode v = atoi(token.c_str());\n\t\t\tadjacencies.push_back(v);\n\t\t}\n\t}\n\n\treturn adjacencies;\n}\n\n\nstatic inline std::vector<node> parseLineDIY(std::string line) {\n\t\/\/ TODO: is this faster?\n\n\tstd::string token;\n\tchar delim = ' ';\n\tstd::vector<node> adjacencies;\n\n\tfor (char& c : line) {\n\t\tif (c == delim) {\n\t\t\tnode v = atoi(token.c_str());\n\t\t\tadjacencies.push_back(v);\n\t\t\ttoken.clear();\n\t\t} else if (c == '\\n') {\n\t\t\tbreak;\n\t\t} else {\n\t\t\ttoken.push_back(c);\n\t\t}\n\t}\n\n\treturn adjacencies;\n}\n\n\nMETISParser::METISParser(std::string path) : graphFile(path) {\n\tif (!(this->graphFile)) {\n\t\tERROR(\"invalid graph file: \" << path);\n\t\tthrow std::runtime_error(\"invalid graph file\");\n\t}\n}\n\n\n\nMETISParser::~METISParser() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\n\n\nstd::pair<int, int> METISParser::getHeader() {\n\n\t\/\/ handle header line\n\tint n; \/\/ number of nodes\n\tint m;\t\/\/ number of edges\n\n\tstd::string line = \"\";\n\tassert (this->graphFile);\n\n\tif (std::getline(this->graphFile, line)) {\n\t\twhile (line[0] == '%') {\n\t\t\tstd::getline(this->graphFile, line);\n\t\t}\n\n\t\tstd::vector<node> tokens = parseLine(line);\n\t\tn = tokens[0];\n\t\tm = tokens[1];\n\n\t\treturn std::make_pair(n, m);\n\t} else {\n\t\tERROR(\"getline not successful\");\n\t\tthrow std::runtime_error(\"getting METIS file header failed\");\n\t\treturn std::make_pair(0,0);\n\t}\n\n}\n\n\nbool METISParser::hasNext() {\n\t\/\/ if graph file has lines left, return true\n\treturn this->graphFile.good();\n}\n\n\nstd::vector<node> METISParser::getNext() {\n\n\tstd::string line;\n\tbool comment = false;\n\tdo {\n\t\tcomment = false;\n\t\tstd::getline(this->graphFile, line);\n\t\t\/\/ check for comment line starting with '%'\n\t\tif (line[0] == '%') {\n\t\t\tcomment = true;\n\t\t} else {\n\t\t\treturn parseLine(line);\n\t\t}\n\n\t} while (comment);\n\n\tthrow std::runtime_error(\"bad METIS file structure\");\n\tstd::vector<node> fail;\n\treturn fail;\n}\n\n\n\n\n} \/* namespace EnsembleClustering *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ echo_server.cpp\n\/\/ ~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n\/\/ Copyright (c) 2015 Andrew Hundt\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\n#include \"robone\/AzmqFlatbuffer.hpp\"\n\n\/\/\/ Send messages between a client and server asynchronously. \n\/\/\/\n\/\/\/ @see overview of zmq socket types https:\/\/sachabarbs.wordpress.com\/2014\/08\/21\/zeromq-2-the-socket-types-2\/\n\/\/\/ @see bounce is based on https:\/\/github.com\/zeromq\/azmq\/blob\/master\/test\/socket\/main.cpp\n\/\/\/ @see flatbuffers https:\/\/google.github.io\/flatbuffers\/md__cpp_usage.html\nvoid bounce(std::shared_ptr<AzmqFlatbuffer> sendP, std::shared_ptr<AzmqFlatbuffer> receiveP, bool shouldReceive = true) {\n\t\n\treceiveP->start_async_receive_buffers();\n\t\n\tfor (int x = 0; x<1000; ++x) {\n\t\t\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Client sends to server asynchronously!\n\t\t{\n\t\t\tauto fbbP = sendP->GetUnusedBufferBuilder();\n\t\t\t\n\t\t\trobone::Vector3d rv(x,0,0);\n\t\t\tauto controlPoint = robone::CreateVrepControlPoint(*fbbP,&rv);\n\t\t\trobone::FinishVrepControlPointBuffer(*fbbP, controlPoint);\n\t\t\tsendP->async_send_flatbuffer(fbbP);\n\t\t}\n\t\t\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Server receives from client asynchronously!\n\t\twhile (shouldReceive && !receiveP->receive_buffers_empty()) {\n\t\t\tauto rbP = receiveP->get_back_receive_buffer_with_data();\n\t\t\tauto rbPstart = &(rbP->begin()[0]);\n\t\t\tauto verifier = flatbuffers::Verifier(rbPstart,rbP->size());\n\t\t\tauto bufOK = robone::VerifyVrepControlPointBuffer(verifier);\n\t\t\n\t\t\tif(bufOK){\n\t\t\t\tconst robone::VrepControlPoint* VCPin = robone::GetVrepControlPoint(rbPstart);\n\t\t\t\tstd::cout << \"received: \" << VCPin->position()->x() << \"\\n\";\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Failed verification. bufOk: \" <<bufOK << \"\\n\";\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tstd::this_thread::sleep_for( std::chrono::milliseconds(1) );\n }\n}\n\n\nint main(int argc, char* argv[])\n{\n\/\/ try\n\/\/ {\n \n std::string localhost(\"127.0.0.1\");\n std::string localport(\"9998\");\n std::string remotehost(\"127.0.0.1\");\n std::string remoteport(\"9998\");\n \n std::cout << \"argc: \" << argc << \"\\n\";\n\t \/\/\/ @todo add default localhost\/localport\n if (argc != 5 && argc != 1 && argc != 3)\n {\n std::cerr << \"Usage: \" << argv[0] << \" <localip> <localport> <remoteip> <remoteport>\\n\";\n return 1;\n }\n \n bool shouldReceive = false;\n \n if(argc == 3){\n remotehost = std::string(argv[1]);\n remoteport = std::string(argv[2]);\n shouldReceive = false;\n }\n \n if(argc == 5){\n localhost = std::string(argv[1]);\n localport = std::string(argv[2]);\n remotehost = std::string(argv[3]);\n remoteport = std::string(argv[4]);\n shouldReceive = true;\n }\n \n std::cout << \"using: \" << argv[0] << \" \";\n if(shouldReceive) std::cout << localhost << \" \" << localport << \" \";\n std::cout << remotehost << \" \" << remoteport << \"\\n\";\n boost::asio::io_service io_service;\n\t\n\t\n \/\/ Register signal handlers so that the daemon may be shut down when a signal is received.\n boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);\n signals.async_wait( std::bind(&boost::asio::io_service::stop, &io_service));\n#if 0\n\tstd::shared_ptr<AzmqFlatbuffer> sendP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tsocket.connect(\"tcp:\/\/\"+ remotehost + \":\" + remoteport);\n\t\tsendP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\tstd::shared_ptr<AzmqFlatbuffer> receiveP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tif (shouldReceive) socket.bind(\"tcp:\/\/\" + localhost + \":\" + localport);\n\t\treceiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\n\t\/\/ Will run until signal is received, using separate objects for send and receive\n std::thread t(bounce,sendP,receiveP);\n#else\n\n\tstd::shared_ptr<AzmqFlatbuffer> receiveP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tif(shouldReceive) socket.bind(\"tcp:\/\/\" + localhost + \":\" + localport);\n\t\tsocket.connect(\"tcp:\/\/\"+ remotehost + \":\" + remoteport);\n\t\treceiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\n\t\/\/ Will run until signal is received, using one object for both send and receive\n std::thread t(bounce,receiveP,receiveP,shouldReceive);\n#endif\n\t\n\tio_service.run();\n\t\n\/\/ }\n\/\/ catch (std::exception& e)\n\/\/ {\n\/\/ std::cerr << \"Exception: \" << e.what() << \"\\n\";\n\/\/ }\n\n return 0;\n}<commit_msg>#51 fixed send to self bug in AzmqFlatbufferTest<commit_after>\/\/\n\/\/ echo_server.cpp\n\/\/ ~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n\/\/ Copyright (c) 2015 Andrew Hundt\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\n#include \"robone\/AzmqFlatbuffer.hpp\"\n\n\/\/\/ Send messages between a client and server asynchronously. \n\/\/\/\n\/\/\/ @see overview of zmq socket types https:\/\/sachabarbs.wordpress.com\/2014\/08\/21\/zeromq-2-the-socket-types-2\/\n\/\/\/ @see bounce is based on https:\/\/github.com\/zeromq\/azmq\/blob\/master\/test\/socket\/main.cpp\n\/\/\/ @see flatbuffers https:\/\/google.github.io\/flatbuffers\/md__cpp_usage.html\nvoid bounce(std::shared_ptr<AzmqFlatbuffer> sendP, std::shared_ptr<AzmqFlatbuffer> receiveP, bool shouldReceive = true) {\n\t\n\treceiveP->start_async_receive_buffers();\n\t\n\tfor (int x = 0; x<1000; ++x) {\n\t\t\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Client sends to server asynchronously!\n\t\t{\n\t\t\tauto fbbP = sendP->GetUnusedBufferBuilder();\n\t\t\t\n\t\t\trobone::Vector3d rv(x,0,0);\n\t\t\tauto controlPoint = robone::CreateVrepControlPoint(*fbbP,&rv);\n\t\t\trobone::FinishVrepControlPointBuffer(*fbbP, controlPoint);\n\t\t\tsendP->async_send_flatbuffer(fbbP);\n\t\t}\n\t\t\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Server receives from client asynchronously!\n\t\twhile (shouldReceive && !receiveP->receive_buffers_empty()) {\n\t\t\tauto rbP = receiveP->get_back_receive_buffer_with_data();\n\t\t\tauto rbPstart = &(rbP->begin()[0]);\n\t\t\tauto verifier = flatbuffers::Verifier(rbPstart,rbP->size());\n\t\t\tauto bufOK = robone::VerifyVrepControlPointBuffer(verifier);\n\t\t\n\t\t\tif(bufOK){\n\t\t\t\tconst robone::VrepControlPoint* VCPin = robone::GetVrepControlPoint(rbPstart);\n\t\t\t\tstd::cout << \"received: \" << VCPin->position()->x() << \"\\n\";\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Failed verification. bufOk: \" <<bufOK << \"\\n\";\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tstd::this_thread::sleep_for( std::chrono::milliseconds(1) );\n }\n}\n\n\nint main(int argc, char* argv[])\n{\n\/\/ try\n\/\/ {\n \n std::string localhost(\"127.0.0.1\");\n std::string localport(\"9998\");\n std::string remotehost(\"127.0.0.1\");\n std::string remoteport(\"9998\");\n \n std::cout << \"argc: \" << argc << \"\\n\";\n\t \/\/\/ @todo add default localhost\/localport\n if (argc != 5 && argc != 1 && argc != 3)\n {\n std::cerr << \"Usage: \" << argv[0] << \" <localip> <localport> <remoteip> <remoteport>\\n\";\n return 1;\n }\n \n bool shouldReceive = true;\n \n if(argc == 3){\n remotehost = std::string(argv[1]);\n remoteport = std::string(argv[2]);\n shouldReceive = false;\n }\n \n if(argc == 5){\n localhost = std::string(argv[1]);\n localport = std::string(argv[2]);\n remotehost = std::string(argv[3]);\n remoteport = std::string(argv[4]);\n shouldReceive = true;\n }\n \n std::cout << \"using: \" << argv[0] << \" \";\n if(shouldReceive) std::cout << localhost << \" \" << localport << \" \";\n std::cout << remotehost << \" \" << remoteport << \"\\n\";\n boost::asio::io_service io_service;\n\t\n\t\n \/\/ Register signal handlers so that the daemon may be shut down when a signal is received.\n boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);\n signals.async_wait( std::bind(&boost::asio::io_service::stop, &io_service));\n#if 0\n\tstd::shared_ptr<AzmqFlatbuffer> sendP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tsocket.connect(\"tcp:\/\/\"+ remotehost + \":\" + remoteport);\n\t\tsendP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\tstd::shared_ptr<AzmqFlatbuffer> receiveP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tsocket.bind(\"tcp:\/\/\" + localhost + \":\" + localport);\n\t\treceiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\n\t\/\/ Will run until signal is received, using separate objects for send and receive\n std::thread t(bounce,sendP,receiveP);\n#else\n\n\tstd::shared_ptr<AzmqFlatbuffer> receiveP;\n\t{\n\t\tboost::system::error_code ec;\n\t\tazmq::socket socket(io_service, ZMQ_DEALER);\n\t\tsocket.bind(\"tcp:\/\/\" + localhost + \":\" + localport);\n\t\tsocket.connect(\"tcp:\/\/\"+ remotehost + \":\" + remoteport);\n\t\treceiveP = std::make_shared<AzmqFlatbuffer>(std::move(socket));\n\t}\n\n\t\/\/ Will run until signal is received, using one object for both send and receive\n std::thread t(bounce,receiveP,receiveP,shouldReceive);\n#endif\n\t\n\tio_service.run();\n\t\n\/\/ }\n\/\/ catch (std::exception& e)\n\/\/ {\n\/\/ std::cerr << \"Exception: \" << e.what() << \"\\n\";\n\/\/ }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <vtkDataSet.h>\n#include <vtkXMLImageDataReader.h>\n#include <vtkXMLStructuredGridReader.h>\n#include <vtkImageData.h>\n#include <vtkNew.h>\n\n#include \"io\/path.h\"\n#include \"dataset\/abstract_sampling_array.h\"\n\n#include \"io\/gmm_vtk_data_array.h\"\n#include \"io\/edda_reader.h\"\n\nusing namespace std;\n\nnamespace edda {\n\ntemplate <typename T>\nshared_ptr<Dataset<T> > loadEddaRandomSamplingDataset(const string &edda_file, const string &array_name)\n{\n string ext = getFileExtension(edda_file);\n if (ext.compare(\"vti\")==0) {\n vtkNew<vtkXMLImageDataReader> reader;\n reader->SetFileName(edda_file.c_str());\n reader->Update();\n vtkImageData *vtkdata = reader->GetOutput();\n\n int *dim = vtkdata->GetDimensions();\n printf(\"dim: %d %d %d\\n\", dim[0], dim[1], dim[2]);\n\n \/\/ TODO : check if gmm dataset\n shared_ptr<Dataset<T> > dataset = make_Dataset<T>(\n new RegularCartesianGrid(dim[0], dim[1], dim[2]),\n new AbstractSamplingArray( new GmmVtkDataArray( vtkdata->GetPointData(), array_name.c_str() ) )\n );\n \/\/ or is histogram dataset\n\n return dataset;\n\n } else if (ext.compare(\"vts\")==0){ \/\/ structured grids\n\n vtkNew<vtkXMLStructuredGridReader> reader;\n reader->SetFileName(edda_file.c_str());\n reader->Update();\n vtkStructuredGrid *vtkdata = reader->GetOutput();\n\n int *dim = vtkdata->GetDimensions();\n printf(\"dim: %d %d %d\\n\", dim[0], dim[1], dim[2]);\n\n \/\/ TODO : check if gmm dataset\n\t\t\/\/ TODO: check if is Curvilinear grids\n\tint numPoints = dim[0] * dim[1] * dim[2];\n\tCVertex* pVertexGeom = new CVertex[numPoints];\n\tdouble tempd[3];\n\tfor (int k = 0; k < dim[2]; k++){\n\t\tfor (int j = 0; j < dim[1]; j++){\n\t\t\tfor (int i = 0; i < dim[0]; i++){\n\t\t\t\tint ind = k*dim[1] * dim[0] + j*dim[0] + i;\/\/ !!! need to confirm !!!\n\t\t\t\tvtkdata->GetPoint(i, j, k, tempd);\n\t\t\t\tpVertexGeom[ind].position[0] = tempd[0];\n\t\t\t\tpVertexGeom[ind].position[1] = tempd[1];\n\t\t\t\tpVertexGeom[ind].position[2] = tempd[2];\n\n\t\t\t}\n\t\t}\n\t}\n\n shared_ptr<Dataset<T> > dataset = make_Dataset<T>(\n\t\t\tnew CurvilinearGrid(dim, pVertexGeom),\n new AbstractSamplingArray( new GmmVtkDataArray( vtkdata->GetPointData(), array_name.c_str() ) )\n );\n\t\t\/\/ or is other structured grids\n \/\/ or is histogram dataset\n\n return dataset;\n } else {\n printf(\"File format of %s not supported\\n\", edda_file.c_str());\n exit(1);\n }\n}\n\nshared_ptr<Dataset<Real> > loadEddaScalarDataset(const string &edda_file, const string &array_name)\n{\n return loadEddaRandomSamplingDataset<Real>(edda_file, array_name);\n}\n\nshared_ptr<Dataset<VECTOR3> > loadEddaVector3Dataset(const string &edda_file, const string &array_name)\n{\n return loadEddaRandomSamplingDataset<VECTOR3>(edda_file, array_name);\n}\n\n\n} \/\/ edda\n<commit_msg>further solve conflict<commit_after><|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"PlayerInfo.h\"\n\n\/* system implementation headers *\/\n#include <errno.h>\n#include <string>\n\n\/* implementation-specific common headers *\/\n#include \"TextUtils.h\"\n\nWordFilter PlayerInfo::serverSpoofingFilter;\nTimeKeeper PlayerInfo::now = TimeKeeper::getCurrent();\n\nPlayerInfo::PlayerInfo(int _playerIndex) :\n playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1),\n spamWarns(0), lastMsgTime(now), paused(false),\n pausedSince(TimeKeeper::getNullTime()), autopilot(false), tracker(0)\n{\n notResponding = false;\n memset(email, 0, EmailLen);\n memset(callSign, 0, CallSignLen);\n memset(token, 0, TokenLen);\n memset(clientVersion, 0, VersionLen);\n}\n\nvoid PlayerInfo::resetPlayer(bool ctf) {\n wasRabbit = false;\n\n lastupdate = now;\n lastmsg = now;\n\n replayState = ReplayNone;\n\n playedEarly = false;\n\n restartOnBase = ctf;\n}\n\nvoid PlayerInfo::setRestartOnBase(bool on) {\n restartOnBase = on;\n};\n\nbool PlayerInfo::shouldRestartAtBase() {\n return restartOnBase;\n};\n\nvoid PlayerInfo::signingOn() {\n state = PlayerDead;\n};\n\nbool PlayerInfo::isAlive() {\n return state == PlayerAlive;\n};\n\nvoid PlayerInfo::setAlive() {\n state = PlayerAlive;\n flag = -1;\n};\n\nvoid PlayerInfo::setDead() {\n state = PlayerDead;\n};\n\nvoid *PlayerInfo::packUpdate(void *buf) {\n buf = nboPackUShort(buf, uint16_t(type));\n buf = nboPackUShort(buf, uint16_t(team));\n return buf;\n};\n\nvoid *PlayerInfo::packId(void *buf) {\n buf = nboPackString(buf, callSign, CallSignLen);\n buf = nboPackString(buf, email, EmailLen);\n return buf;\n}\n\nbool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg)\n{\n \/\/ data: type, team, name, email\n uint16_t _type;\n int16_t _team;\n buf = nboUnpackUShort(buf, _type);\n buf = nboUnpackShort(buf, _team);\n type = PlayerType(_type);\n team = TeamColor(_team);\n buf = nboUnpackString(buf, callSign, CallSignLen);\n buf = nboUnpackString(buf, email, EmailLen);\n buf = nboUnpackString(buf, token, TokenLen);\n buf = nboUnpackString(buf, clientVersion, VersionLen);\n cleanEMail();\n\n DEBUG2(\"Player %s [%d] sent version string: %s\\n\",\n\t callSign, playerIndex, clientVersion);\n\n \/\/ spoof filter holds \"SERVER\" for robust name comparisons\n if (serverSpoofingFilter.wordCount() == 0) {\n serverSpoofingFilter.addToFilter(\"SERVER\", \"\");\n }\n\n if (!isCallSignReadable()) {\n DEBUG2(\"rejecting unreadable callsign: %s\\n\", callSign);\n rejectCode = RejectBadCallsign;\n strcpy(rejectMsg, errorString.c_str());\n return false;\n }\n \/\/ no spoofing the server name\n if (serverSpoofingFilter.filter(callSign)) {\n rejectCode = RejectRepeatCallsign;\n strcpy(rejectMsg, \"The callsign specified is already in use.\");\n return false;\n }\n if (!isEMailReadable()) {\n DEBUG2(\"rejecting unreadable player email: %s (%s)\\n\", callSign, email);\n rejectCode = RejectBadEmail;\n strcpy(rejectMsg, \"The e-mail was rejected. Try a different e-mail.\");\n return false;\n }\n return true;\n};\n\nconst char *PlayerInfo::getCallSign() const {\n return callSign;\n};\n\nbool PlayerInfo::isCallSignReadable() {\n \/\/ callsign readability filter, make sure there are more alphanum than non\n \/\/ keep a count of alpha-numerics\n\n int callsignlen = (int)strlen(callSign);\n \/\/ reject less than 3 characters\n if (callsignlen < 3) {\n errorString = \"Callsigns must be at least 3 characters.\";\n return false;\n }\n\n \/\/ reject trailing space\n if (isspace(callSign[strlen(callSign) - 1])) {\n errorString = \"Trailing spaces are not allowed in callsigns.\";\n return false;\n }\n\n \/\/ start with true to reject leading space\n bool lastWasSpace = true;\n int alnumCount = 0;\n const char *sp = callSign;\n do {\n \/\/ reject sequential spaces\n if (lastWasSpace && isspace(*sp)) {\n errorString = \"Leading or consecutive spaces are not allowed in callsigns.\";\n return false;\n }\n\n \/\/ reject ' and \" and any nonprintable\n if ((*sp == '\\'') || (*sp == '\"') || ((unsigned)*sp > 0x7f)\n\t|| !isprint(*sp)) {\n errorString = \"Non-printable characters and quotes are not allowed in callsigns.\";\n return false;\n }\n if (isspace(*sp)) {\n \/\/ only space is valid, not tab etc.\n if (*sp != ' ') {\n\terrorString = \"Invalid whitespace in callsign.\";\n\treturn false;\n }\n lastWasSpace = true;\n } else {\n lastWasSpace = false;\n if (isalnum(*sp))\n\talnumCount++;\n }\n } while (*++sp);\n\n bool readable = ((float)alnumCount \/ (float)callsignlen) > 0.5f;\n if (!readable)\n errorString = \"Callsign rejected. Please use mostly letters and numbers.\";\n return readable;\n};\n\nconst char *PlayerInfo::getEMail() const {\n return email;\n};\n\nvoid PlayerInfo::cleanEMail() {\n \/\/ strip leading whitespace from email\n char *sp = email;\n char *tp = sp;\n while (isspace(*sp))\n sp++;\n\n \/\/ strip any non-printable characters and ' and \" from email\n do {\n if (isprint(*sp) && (*sp != '\\'') && (*sp != '\"')) {\n *tp++ = *sp;\n }\n } while (*++sp);\n *tp = *sp;\n\n \/\/ strip trailing whitespace from email\n while (isspace(*--tp)) {\n *tp=0;\n }\n};\n\nbool PlayerInfo::isEMailReadable() {\n \/\/ email\/\"team\" readability filter, make sure there are more\n \/\/ alphanum than non\n int emailAlnumCount = 0;\n char *sp = email;\n do {\n if (isalnum(*sp)) {\n emailAlnumCount++;\n }\n } while (*++sp);\n int emaillen = (int)strlen(email);\n return (emaillen <= 4) || (((float)emailAlnumCount \/ (float)emaillen) > 0.5);\n};\n\nconst char *PlayerInfo::getToken() const {\n return token;\n};\n\nvoid PlayerInfo::clearToken() {\n token[0] = '\\0';\n};\n\nvoid *PlayerInfo::packVirtualFlagCapture(void *buf) {\n buf = nboPackUShort(buf, uint16_t(int(team) - 1));\n buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4)));\n return buf;\n};\n\nbool PlayerInfo::isTeam(TeamColor _team) const {\n return team == _team;\n};\n\nbool PlayerInfo::isObserver() const {\n return team == ObserverTeam;\n};\n\nTeamColor PlayerInfo::getTeam() {\n return team;\n};\n\nvoid PlayerInfo::setTeam(TeamColor _team) {\n team = _team;\n};\n\nvoid PlayerInfo::wasARabbit() {\n team = RogueTeam;\n wasRabbit = true;\n};\n\nvoid PlayerInfo::wasNotARabbit() {\n wasRabbit = false;\n};\n\nvoid PlayerInfo::resetFlag() {\n flag = -1;\n lastFlagDropTime = now;\n};\n\nvoid PlayerInfo::setFlag(int _flag) {\n flag = _flag;\n};\n\nbool PlayerInfo::isFlagTransitSafe() {\n return now - lastFlagDropTime >= 2.0f;\n};\n\nconst char *PlayerInfo::getClientVersion() {\n return clientVersion;\n};\n\nstd::string PlayerInfo::getIdleStat() {\n std::string reply;\n if ((state > PlayerInLimbo) && (team != ObserverTeam)) {\n reply = TextUtils::format(\"%s\\t: %4ds\", callSign,\n\t\t\t\tint(now - lastupdate));\n if (paused) {\n reply += TextUtils::format(\" paused %4ds\", int(now - pausedSince));\n }\n }\n return reply;\n};\n\nbool PlayerInfo::canBeRabbit(bool relaxing) {\n if (paused || notResponding || (team == ObserverTeam))\n return false;\n return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive);\n};\n\nvoid PlayerInfo::setPaused(bool _paused) {\n paused = _paused;\n pausedSince = now;\n};\n\nvoid PlayerInfo::setAutoPilot(bool _autopilot) {\n autopilot = _autopilot;\n};\n\nbool PlayerInfo::isTooMuchIdling(float kickThresh) {\n bool idling = false;\n if ((state > PlayerInLimbo) && (team != ObserverTeam)) {\n int idletime = (int)(now - lastupdate);\n int pausetime = 0;\n if (paused && now - pausedSince > idletime)\n pausetime = (int)(now - pausedSince);\n idletime = idletime > pausetime ? idletime : pausetime;\n if (idletime\n\t> (now - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) {\n DEBUG1(\"Kicking player %s [%d] idle %d\\n\", callSign, playerIndex,\n\t idletime);\n idling = true;\n }\n }\n return idling;\n};\n\nbool PlayerInfo::hasStartedToNotRespond() {\n float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME);\n bool startingToNotRespond = false;\n if (state > PlayerInLimbo) {\n bool oldnr = notResponding;\n notResponding = (now - lastupdate) > notRespondingTime;\n if (!oldnr && notResponding)\n startingToNotRespond = true;\n }\n return startingToNotRespond;\n}\n\nvoid PlayerInfo::hasSent(char message[]) {\n lastmsg = now;\n DEBUG1(\"Player %s [%d]: %s\\n\", callSign, playerIndex, message);\n};\n\nbool PlayerInfo::hasPlayedEarly() {\n bool returnValue = playedEarly;\n playedEarly = false;\n return returnValue;\n};\n\nvoid PlayerInfo::setPlayedEarly(bool early) {\n playedEarly = early;\n};\n\nvoid PlayerInfo::updateIdleTime() {\n lastupdate = now;\n};\n\nvoid\tPlayerInfo::setReplayState(PlayerReplayState state) {\n replayState = state;\n}\n\nPlayerReplayState PlayerInfo::getReplayState()\n{\n return replayState;\n}\n\n\nvoid PlayerInfo::setTrackerID(unsigned short int t)\n{\n tracker = t;\n}\n\n\nunsigned short int PlayerInfo::trackerID()\n{\n return tracker;\n}\n\nvoid PlayerInfo::setCurrentTime(TimeKeeper tm)\n{\n now = tm;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>When coming alive a player is unpaused. Fix sf BUG 1102836.<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"PlayerInfo.h\"\n\n\/* system implementation headers *\/\n#include <errno.h>\n#include <string>\n\n\/* implementation-specific common headers *\/\n#include \"TextUtils.h\"\n\nWordFilter PlayerInfo::serverSpoofingFilter;\nTimeKeeper PlayerInfo::now = TimeKeeper::getCurrent();\n\nPlayerInfo::PlayerInfo(int _playerIndex) :\n playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1),\n spamWarns(0), lastMsgTime(now), paused(false),\n pausedSince(TimeKeeper::getNullTime()), autopilot(false), tracker(0)\n{\n notResponding = false;\n memset(email, 0, EmailLen);\n memset(callSign, 0, CallSignLen);\n memset(token, 0, TokenLen);\n memset(clientVersion, 0, VersionLen);\n}\n\nvoid PlayerInfo::resetPlayer(bool ctf) {\n wasRabbit = false;\n\n lastupdate = now;\n lastmsg = now;\n\n replayState = ReplayNone;\n\n playedEarly = false;\n\n restartOnBase = ctf;\n}\n\nvoid PlayerInfo::setRestartOnBase(bool on) {\n restartOnBase = on;\n};\n\nbool PlayerInfo::shouldRestartAtBase() {\n return restartOnBase;\n};\n\nvoid PlayerInfo::signingOn() {\n state = PlayerDead;\n};\n\nbool PlayerInfo::isAlive() {\n return state == PlayerAlive;\n};\n\nvoid PlayerInfo::setAlive() {\n state = PlayerAlive;\n paused = false;\n flag = -1;\n};\n\nvoid PlayerInfo::setDead() {\n state = PlayerDead;\n};\n\nvoid *PlayerInfo::packUpdate(void *buf) {\n buf = nboPackUShort(buf, uint16_t(type));\n buf = nboPackUShort(buf, uint16_t(team));\n return buf;\n};\n\nvoid *PlayerInfo::packId(void *buf) {\n buf = nboPackString(buf, callSign, CallSignLen);\n buf = nboPackString(buf, email, EmailLen);\n return buf;\n}\n\nbool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg)\n{\n \/\/ data: type, team, name, email\n uint16_t _type;\n int16_t _team;\n buf = nboUnpackUShort(buf, _type);\n buf = nboUnpackShort(buf, _team);\n type = PlayerType(_type);\n team = TeamColor(_team);\n buf = nboUnpackString(buf, callSign, CallSignLen);\n buf = nboUnpackString(buf, email, EmailLen);\n buf = nboUnpackString(buf, token, TokenLen);\n buf = nboUnpackString(buf, clientVersion, VersionLen);\n cleanEMail();\n\n DEBUG2(\"Player %s [%d] sent version string: %s\\n\",\n\t callSign, playerIndex, clientVersion);\n\n \/\/ spoof filter holds \"SERVER\" for robust name comparisons\n if (serverSpoofingFilter.wordCount() == 0) {\n serverSpoofingFilter.addToFilter(\"SERVER\", \"\");\n }\n\n if (!isCallSignReadable()) {\n DEBUG2(\"rejecting unreadable callsign: %s\\n\", callSign);\n rejectCode = RejectBadCallsign;\n strcpy(rejectMsg, errorString.c_str());\n return false;\n }\n \/\/ no spoofing the server name\n if (serverSpoofingFilter.filter(callSign)) {\n rejectCode = RejectRepeatCallsign;\n strcpy(rejectMsg, \"The callsign specified is already in use.\");\n return false;\n }\n if (!isEMailReadable()) {\n DEBUG2(\"rejecting unreadable player email: %s (%s)\\n\", callSign, email);\n rejectCode = RejectBadEmail;\n strcpy(rejectMsg, \"The e-mail was rejected. Try a different e-mail.\");\n return false;\n }\n return true;\n};\n\nconst char *PlayerInfo::getCallSign() const {\n return callSign;\n};\n\nbool PlayerInfo::isCallSignReadable() {\n \/\/ callsign readability filter, make sure there are more alphanum than non\n \/\/ keep a count of alpha-numerics\n\n int callsignlen = (int)strlen(callSign);\n \/\/ reject less than 3 characters\n if (callsignlen < 3) {\n errorString = \"Callsigns must be at least 3 characters.\";\n return false;\n }\n\n \/\/ reject trailing space\n if (isspace(callSign[strlen(callSign) - 1])) {\n errorString = \"Trailing spaces are not allowed in callsigns.\";\n return false;\n }\n\n \/\/ start with true to reject leading space\n bool lastWasSpace = true;\n int alnumCount = 0;\n const char *sp = callSign;\n do {\n \/\/ reject sequential spaces\n if (lastWasSpace && isspace(*sp)) {\n errorString = \"Leading or consecutive spaces are not allowed in callsigns.\";\n return false;\n }\n\n \/\/ reject ' and \" and any nonprintable\n if ((*sp == '\\'') || (*sp == '\"') || ((unsigned)*sp > 0x7f)\n\t|| !isprint(*sp)) {\n errorString = \"Non-printable characters and quotes are not allowed in callsigns.\";\n return false;\n }\n if (isspace(*sp)) {\n \/\/ only space is valid, not tab etc.\n if (*sp != ' ') {\n\terrorString = \"Invalid whitespace in callsign.\";\n\treturn false;\n }\n lastWasSpace = true;\n } else {\n lastWasSpace = false;\n if (isalnum(*sp))\n\talnumCount++;\n }\n } while (*++sp);\n\n bool readable = ((float)alnumCount \/ (float)callsignlen) > 0.5f;\n if (!readable)\n errorString = \"Callsign rejected. Please use mostly letters and numbers.\";\n return readable;\n};\n\nconst char *PlayerInfo::getEMail() const {\n return email;\n};\n\nvoid PlayerInfo::cleanEMail() {\n \/\/ strip leading whitespace from email\n char *sp = email;\n char *tp = sp;\n while (isspace(*sp))\n sp++;\n\n \/\/ strip any non-printable characters and ' and \" from email\n do {\n if (isprint(*sp) && (*sp != '\\'') && (*sp != '\"')) {\n *tp++ = *sp;\n }\n } while (*++sp);\n *tp = *sp;\n\n \/\/ strip trailing whitespace from email\n while (isspace(*--tp)) {\n *tp=0;\n }\n};\n\nbool PlayerInfo::isEMailReadable() {\n \/\/ email\/\"team\" readability filter, make sure there are more\n \/\/ alphanum than non\n int emailAlnumCount = 0;\n char *sp = email;\n do {\n if (isalnum(*sp)) {\n emailAlnumCount++;\n }\n } while (*++sp);\n int emaillen = (int)strlen(email);\n return (emaillen <= 4) || (((float)emailAlnumCount \/ (float)emaillen) > 0.5);\n};\n\nconst char *PlayerInfo::getToken() const {\n return token;\n};\n\nvoid PlayerInfo::clearToken() {\n token[0] = '\\0';\n};\n\nvoid *PlayerInfo::packVirtualFlagCapture(void *buf) {\n buf = nboPackUShort(buf, uint16_t(int(team) - 1));\n buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4)));\n return buf;\n};\n\nbool PlayerInfo::isTeam(TeamColor _team) const {\n return team == _team;\n};\n\nbool PlayerInfo::isObserver() const {\n return team == ObserverTeam;\n};\n\nTeamColor PlayerInfo::getTeam() {\n return team;\n};\n\nvoid PlayerInfo::setTeam(TeamColor _team) {\n team = _team;\n};\n\nvoid PlayerInfo::wasARabbit() {\n team = RogueTeam;\n wasRabbit = true;\n};\n\nvoid PlayerInfo::wasNotARabbit() {\n wasRabbit = false;\n};\n\nvoid PlayerInfo::resetFlag() {\n flag = -1;\n lastFlagDropTime = now;\n};\n\nvoid PlayerInfo::setFlag(int _flag) {\n flag = _flag;\n};\n\nbool PlayerInfo::isFlagTransitSafe() {\n return now - lastFlagDropTime >= 2.0f;\n};\n\nconst char *PlayerInfo::getClientVersion() {\n return clientVersion;\n};\n\nstd::string PlayerInfo::getIdleStat() {\n std::string reply;\n if ((state > PlayerInLimbo) && (team != ObserverTeam)) {\n reply = TextUtils::format(\"%s\\t: %4ds\", callSign,\n\t\t\t\tint(now - lastupdate));\n if (paused) {\n reply += TextUtils::format(\" paused %4ds\", int(now - pausedSince));\n }\n }\n return reply;\n};\n\nbool PlayerInfo::canBeRabbit(bool relaxing) {\n if (paused || notResponding || (team == ObserverTeam))\n return false;\n return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive);\n};\n\nvoid PlayerInfo::setPaused(bool _paused) {\n paused = _paused;\n pausedSince = now;\n};\n\nvoid PlayerInfo::setAutoPilot(bool _autopilot) {\n autopilot = _autopilot;\n};\n\nbool PlayerInfo::isTooMuchIdling(float kickThresh) {\n bool idling = false;\n if ((state > PlayerInLimbo) && (team != ObserverTeam)) {\n int idletime = (int)(now - lastupdate);\n int pausetime = 0;\n if (paused && now - pausedSince > idletime)\n pausetime = (int)(now - pausedSince);\n idletime = idletime > pausetime ? idletime : pausetime;\n if (idletime\n\t> (now - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) {\n DEBUG1(\"Kicking player %s [%d] idle %d\\n\", callSign, playerIndex,\n\t idletime);\n idling = true;\n }\n }\n return idling;\n};\n\nbool PlayerInfo::hasStartedToNotRespond() {\n float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME);\n bool startingToNotRespond = false;\n if (state > PlayerInLimbo) {\n bool oldnr = notResponding;\n notResponding = (now - lastupdate) > notRespondingTime;\n if (!oldnr && notResponding)\n startingToNotRespond = true;\n }\n return startingToNotRespond;\n}\n\nvoid PlayerInfo::hasSent(char message[]) {\n lastmsg = now;\n DEBUG1(\"Player %s [%d]: %s\\n\", callSign, playerIndex, message);\n};\n\nbool PlayerInfo::hasPlayedEarly() {\n bool returnValue = playedEarly;\n playedEarly = false;\n return returnValue;\n};\n\nvoid PlayerInfo::setPlayedEarly(bool early) {\n playedEarly = early;\n};\n\nvoid PlayerInfo::updateIdleTime() {\n lastupdate = now;\n};\n\nvoid\tPlayerInfo::setReplayState(PlayerReplayState state) {\n replayState = state;\n}\n\nPlayerReplayState PlayerInfo::getReplayState()\n{\n return replayState;\n}\n\n\nvoid PlayerInfo::setTrackerID(unsigned short int t)\n{\n tracker = t;\n}\n\n\nunsigned short int PlayerInfo::trackerID()\n{\n return tracker;\n}\n\nvoid PlayerInfo::setCurrentTime(TimeKeeper tm)\n{\n now = tm;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ CustomAudioUnit.cpp\n\/\/ Demo\n\/\/\n\/\/ Created by Philadelphia Game Lab on 6\/11\/14.\n\/\/ Copyright (c) 2014 Philadelphia Game Lab. All rights reserved.\n\/\/\n\n#include \"CustomAudioUnit.h\"\n\n\nstatic OSStatus recordingCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {\n \n \/\/Please dont remove the following commented code\n \/\/The following code will be used if we use recording callback\n \n \/\/TODO: Use inRefCon to access our interface object to do stuff\n \/\/Then use inNumberFrames to figure out how much data is available and make that much space available in buffers in AudioBufferList\n \n \/\/AudioBufferList list;\n \/\/list.mNumberBuffers = 1;\n \/\/list.mBuffers[0].mData = sampleBuffer;\n \/\/list.mBuffers[0].mDataByteSize = 2* inNumberFrames;\n \/\/list.mBuffers[0].mNumberChannels = 1;\n \/\/AudioUnitRender([audioInterface audioUnitInstance], ioActionFlags, inTimeStamp, 1, inNumberFrames, &list);\n \n return noErr;\n}\n\nstatic OSStatus playbackCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {\n \n \/\/Please dont remove the following commented code\n \/\/The following code will be used for immediate debugging\n \n \/\/Notes: ioData contains buffers (may be more than one)\n \/\/Fill them up as much as you can. Remember to set the size value in each buffer to match how much data is in each buffer.\n \n \/\/ioData->mBuffers[i].mNumberChannels is no. of channels per buffer\n \/\/*ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;\n \/\/for (UInt32 i=0; i<ioData->mNumberBuffers; ++i) {\n \/\/ memset(ioData->mBuffers[i].mData, 10000, ioData->mBuffers[i].mDataByteSize);\n \/\/ std::cout<<\"\\naksjdhka \" << ioData->mBuffers[i].mDataByteSize <<\" i=\" << i <<\" \"<<inBusNumber;\n \/\/\n \/\/}\n \n \/\/clock_t t1, t2;\n \/\/t1 = clock();\n mixer3D->performMix((short *)ioData->mBuffers[0].mData, (short *) ioData->mBuffers[1].mData);\n \/\/t2 = clock();\n \/\/cout<<\"The time consumption is \"<<((double)(t2-t1))\/CLOCKS_PER_SEC<<endl;\n\n return noErr;\n}\n\nvoid CustomAudioUnit::init () {\n mixer3D = new Mixer3D(BUF_SIZE, SAMPLE_RATE, BIT_DEPTH, myWorld);\n \n AudioComponentDescription desc;\n \n desc.componentType = kAudioUnitType_Output;\n desc.componentSubType = kAudioUnitSubType_RemoteIO;\n desc.componentFlags = 0;\n desc.componentFlagsMask = 0;\n desc.componentManufacturer = kAudioUnitManufacturer_Apple;\n \n AudioComponent component = AudioComponentFindNext(NULL, &desc);\n AudioComponentInstanceNew(component, &audioUnitInstance);\n \n UInt32 enableIO;\n AudioUnitElement inputBus = 1;\n AudioUnitElement outputBus = 0;\n \n \/\/Disabling IO for recording\n enableIO = 0;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enableIO, sizeof(enableIO));\n \n \/\/Enabling IO for playback\n enableIO = 1;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &enableIO, sizeof(enableIO));\n \n \n UInt32 bytesPerSample = sizeof(short) ; \/\/sizeof(AudioUnitSampleType);\n AudioStreamBasicDescription stereoStreamFormat = {0};\n stereoStreamFormat.mBitsPerChannel = 8 * bytesPerSample;\n stereoStreamFormat.mBytesPerFrame = bytesPerSample;\n stereoStreamFormat.mBytesPerPacket = bytesPerSample;\n stereoStreamFormat.mChannelsPerFrame = 2; \/\/ 2 incdicates stereo\n stereoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger |\n kAudioFormatFlagsNativeEndian |\n kAudioFormatFlagIsPacked |\n kAudioFormatFlagIsNonInterleaved;\n stereoStreamFormat.mFormatID = kAudioFormatLinearPCM;\n stereoStreamFormat.mFramesPerPacket = 1;\n stereoStreamFormat.mReserved = 0;\n stereoStreamFormat.mSampleRate = SAMPLE_RATE;\n \n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));\n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, outputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));\n \n \/\/Setting input callback\n AURenderCallbackStruct callbackStruct;\n callbackStruct.inputProc = &recordingCallback; \/\/\/\/\/\/Should there be an ampersand\n callbackStruct.inputProcRefCon = audioUnitInstance;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, inputBus, &callbackStruct, sizeof(callbackStruct)); \/\/\/\/\/Not sure of scope and bus\/element\n \n \/\/Setting output callback\n callbackStruct.inputProc = &playbackCallback;\n callbackStruct.inputProcRefCon = audioUnitInstance;\n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, outputBus, &callbackStruct, sizeof(callbackStruct));\n \n AudioUnitInitialize(audioUnitInstance);\n\n}\n \nCustomAudioUnit::CustomAudioUnit() {\n myWorld = new World;\n init();\n std::cout<<\"\\nConstructor\";\n}\n\nCustomAudioUnit::~CustomAudioUnit() {\n AudioUnitUninitialize(audioUnitInstance);\n AudioComponentInstanceDispose(audioUnitInstance);\n std::cout<<\"\\nDestructor\";\n}\n\nvoid CustomAudioUnit::play() {\n \/\/init();\n myWorld->createWriteThread();\n AudioOutputUnitStart(audioUnitInstance);\n std::cout<<\"\\nPlay\";\n}\n\nvoid CustomAudioUnit::stop() {\n AudioOutputUnitStop(audioUnitInstance);\n \/\/AudioUnitUninitialize(audioUnitInstance);\n \/\/AudioComponentInstanceDispose(audioUnitInstance);\n std::cout<<\"\\nStop\";\n}\n\nAudioObj* CustomAudioUnit::addAudioObjectInWorld(string wavFile, VariableForLocation x, VariableForLocation y, VariableForLocation z)\n{\n if(myWorld != nullptr)\n {\n Location loc = Location(x, y, z);\n Velocity vel = Velocity();\n return myWorld->addAudioObj(loc,vel,wavFile);\n }\n else\n {\n throw(\"World has to be created before adding audio objects\");\n return nullptr;\n }\n \n}\n\nvoid CustomAudioUnit::setPlayerPosition(VariableForLocation x, VariableForLocation y, VariableForLocation z)\n{\n myWorld->setPlayerPosition(x, y, z);\n}\n\nvoid CustomAudioUnit::setPlayerBearing(float bearing)\n{\n myWorld->setPlayerBearing(bearing);\n}\n\n\n\n\n\n\n<commit_msg>moved #defines to .h file<commit_after>\/\/\n\/\/ CustomAudioUnit.cpp\n\/\/ Demo\n\/\/\n\/\/ Created by Philadelphia Game Lab on 6\/11\/14.\n\/\/ Copyright (c) 2014 Philadelphia Game Lab. All rights reserved.\n\/\/\n\n#include \"CustomAudioUnit.h\"\n\nstatic OSStatus recordingCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {\n \n \/\/Please dont remove the following commented code\n \/\/The following code will be used if we use recording callback\n \n \/\/TODO: Use inRefCon to access our interface object to do stuff\n \/\/Then use inNumberFrames to figure out how much data is available and make that much space available in buffers in AudioBufferList\n \n \/\/AudioBufferList list;\n \/\/list.mNumberBuffers = 1;\n \/\/list.mBuffers[0].mData = sampleBuffer;\n \/\/list.mBuffers[0].mDataByteSize = 2* inNumberFrames;\n \/\/list.mBuffers[0].mNumberChannels = 1;\n \/\/AudioUnitRender([audioInterface audioUnitInstance], ioActionFlags, inTimeStamp, 1, inNumberFrames, &list);\n \n return noErr;\n}\n\nstatic OSStatus playbackCallback (void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {\n \n \/\/Please dont remove the following commented code\n \/\/The following code will be used for immediate debugging\n \n \/\/Notes: ioData contains buffers (may be more than one)\n \/\/Fill them up as much as you can. Remember to set the size value in each buffer to match how much data is in each buffer.\n \n \/\/ioData->mBuffers[i].mNumberChannels is no. of channels per buffer\n \/\/*ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;\n \/\/for (UInt32 i=0; i<ioData->mNumberBuffers; ++i) {\n \/\/ memset(ioData->mBuffers[i].mData, 10000, ioData->mBuffers[i].mDataByteSize);\n \/\/ std::cout<<\"\\naksjdhka \" << ioData->mBuffers[i].mDataByteSize <<\" i=\" << i <<\" \"<<inBusNumber;\n \/\/\n \/\/}\n \n \/\/clock_t t1, t2;\n \/\/t1 = clock();\n mixer3D->performMix((short *)ioData->mBuffers[0].mData, (short *) ioData->mBuffers[1].mData);\n \/\/t2 = clock();\n \/\/cout<<\"The time consumption is \"<<((double)(t2-t1))\/CLOCKS_PER_SEC<<endl;\n\n return noErr;\n}\n\nvoid CustomAudioUnit::init () {\n mixer3D = new Mixer3D(BUF_SIZE, SAMPLE_RATE, BIT_DEPTH, myWorld);\n \n AudioComponentDescription desc;\n \n desc.componentType = kAudioUnitType_Output;\n desc.componentSubType = kAudioUnitSubType_RemoteIO;\n desc.componentFlags = 0;\n desc.componentFlagsMask = 0;\n desc.componentManufacturer = kAudioUnitManufacturer_Apple;\n \n AudioComponent component = AudioComponentFindNext(NULL, &desc);\n AudioComponentInstanceNew(component, &audioUnitInstance);\n \n UInt32 enableIO;\n AudioUnitElement inputBus = 1;\n AudioUnitElement outputBus = 0;\n \n \/\/Disabling IO for recording\n enableIO = 0;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enableIO, sizeof(enableIO));\n \n \/\/Enabling IO for playback\n enableIO = 1;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &enableIO, sizeof(enableIO));\n \n \n UInt32 bytesPerSample = sizeof(short) ; \/\/sizeof(AudioUnitSampleType);\n AudioStreamBasicDescription stereoStreamFormat = {0};\n stereoStreamFormat.mBitsPerChannel = 8 * bytesPerSample;\n stereoStreamFormat.mBytesPerFrame = bytesPerSample;\n stereoStreamFormat.mBytesPerPacket = bytesPerSample;\n stereoStreamFormat.mChannelsPerFrame = 2; \/\/ 2 incdicates stereo\n stereoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger |\n kAudioFormatFlagsNativeEndian |\n kAudioFormatFlagIsPacked |\n kAudioFormatFlagIsNonInterleaved;\n stereoStreamFormat.mFormatID = kAudioFormatLinearPCM;\n stereoStreamFormat.mFramesPerPacket = 1;\n stereoStreamFormat.mReserved = 0;\n stereoStreamFormat.mSampleRate = SAMPLE_RATE;\n \n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));\n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, outputBus, &stereoStreamFormat, sizeof(AudioStreamBasicDescription));\n \n \/\/Setting input callback\n AURenderCallbackStruct callbackStruct;\n callbackStruct.inputProc = &recordingCallback; \/\/\/\/\/\/Should there be an ampersand\n callbackStruct.inputProcRefCon = audioUnitInstance;\n AudioUnitSetProperty(audioUnitInstance, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Output, inputBus, &callbackStruct, sizeof(callbackStruct)); \/\/\/\/\/Not sure of scope and bus\/element\n \n \/\/Setting output callback\n callbackStruct.inputProc = &playbackCallback;\n callbackStruct.inputProcRefCon = audioUnitInstance;\n AudioUnitSetProperty(audioUnitInstance, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, outputBus, &callbackStruct, sizeof(callbackStruct));\n \n AudioUnitInitialize(audioUnitInstance);\n\n}\n \nCustomAudioUnit::CustomAudioUnit() {\n myWorld = new World;\n init();\n std::cout<<\"\\nConstructor\";\n}\n\nCustomAudioUnit::~CustomAudioUnit() {\n AudioUnitUninitialize(audioUnitInstance);\n AudioComponentInstanceDispose(audioUnitInstance);\n std::cout<<\"\\nDestructor\";\n}\n\nvoid CustomAudioUnit::play() {\n \/\/init();\n myWorld->createWriteThread();\n AudioOutputUnitStart(audioUnitInstance);\n std::cout<<\"\\nPlay\";\n}\n\nvoid CustomAudioUnit::stop() {\n AudioOutputUnitStop(audioUnitInstance);\n \/\/AudioUnitUninitialize(audioUnitInstance);\n \/\/AudioComponentInstanceDispose(audioUnitInstance);\n std::cout<<\"\\nStop\";\n}\n\nAudioObj* CustomAudioUnit::addAudioObjectInWorld(string wavFile, VariableForLocation x, VariableForLocation y, VariableForLocation z)\n{\n if(myWorld != nullptr)\n {\n Location loc = Location(x, y, z);\n Velocity vel = Velocity();\n return myWorld->addAudioObj(loc,vel,wavFile);\n }\n else\n {\n throw(\"World has to be created before adding audio objects\");\n return nullptr;\n }\n \n}\n\nvoid CustomAudioUnit::setPlayerPosition(VariableForLocation x, VariableForLocation y, VariableForLocation z)\n{\n myWorld->setPlayerPosition(x, y, z);\n}\n\nvoid CustomAudioUnit::setPlayerBearing(float bearing)\n{\n myWorld->setPlayerBearing(bearing);\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2006 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#endif\n\n\/* interface header *\/\n#include \"TextChunkManager.h\"\n\n\/* system implementation headers *\/\n#include <fstream>\n\n\/* common implementation headers *\/\n#include \"global.h\"\n\n\n\/******************************************************************************\/\n\nTextChunk::TextChunk()\n{\n \/\/ for the <map>[] operator\n}\n\n\nTextChunk::TextChunk(const std::string& _fileName)\n{\n fileName = _fileName;\n theVector = parse();\n return;\n}\n\n\nTextChunk::TextChunk(const TextChunk& tc)\n{\n fileName = tc.fileName;\n theVector = tc.theVector;\n return;\n}\n\n\nStringVector TextChunk::parse()\n{\n StringVector strings;\n char buffer[MessageLen];\n std::ifstream in(fileName.c_str());\n if (in) {\n for(int i = 0; (i < 20) && in.good(); i++) {\n in.getline(buffer, MessageLen);\n if(!in.fail()){ \/\/ really read something\n\tstrings.push_back(buffer);\n }\n }\n }\n return strings;\n}\n\n\nbool TextChunk::reload()\n{\n StringVector newVec = parse();\n if (newVec.size() > 0) {\n theVector = newVec;\n }\n return (theVector.size() > 0);\n}\n\n\nsize_t TextChunk::size() const\n{\n return theVector.size();\n}\n\n\nconst StringVector& TextChunk::getVector() const\n{\n return theVector;\n}\n\n\n\/******************************************************************************\/\n\nbool TextChunkManager::parseFile(const std::string &fileName,\n\t\t\t\t const std::string &chunkName)\n{\n TextChunk textChunk(fileName);\n\n if (textChunk.size() <= 0) {\n return false;\n }\n\n \/\/ add a new chunk name if it isn't already listed\n if (theChunks.find(chunkName) == theChunks.end()) {\n chunkNames.push_back(chunkName);\n }\n\n \/\/ add or replace the chunk\n theChunks[chunkName] = textChunk;\n\n return true;\n}\n\n\nconst StringVector* TextChunkManager::getTextChunk(const std::string &chunkName) const\n{\n TextChunkMap::const_iterator it;\n it = theChunks.find(chunkName);\n if (it != theChunks.end()){\n return &it->second.getVector();\n } else {\n return NULL;\n }\n}\n\n\nconst StringVector& TextChunkManager::getChunkNames() const\n{\n return chunkNames;\n}\n\n\nvoid TextChunkManager::reload()\n{\n TextChunkMap::iterator it;\n for (it = theChunks.begin(); it != theChunks.end(); it++) {\n it->second.reload();\n }\n return;\n}\n\n\n\/******************************************************************************\/\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>allow for longer help files (50 lines)<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2006 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#endif\n\n\/* interface header *\/\n#include \"TextChunkManager.h\"\n\n\/* system implementation headers *\/\n#include <fstream>\n\n\/* common implementation headers *\/\n#include \"global.h\"\n\n\n\/******************************************************************************\/\n\nTextChunk::TextChunk()\n{\n \/\/ for the <map>[] operator\n}\n\n\nTextChunk::TextChunk(const std::string& _fileName)\n{\n fileName = _fileName;\n theVector = parse();\n return;\n}\n\n\nTextChunk::TextChunk(const TextChunk& tc)\n{\n fileName = tc.fileName;\n theVector = tc.theVector;\n return;\n}\n\n\nStringVector TextChunk::parse()\n{\n StringVector strings;\n char buffer[MessageLen];\n std::ifstream in(fileName.c_str());\n if (in) {\n for(int i = 0; (i < 50) && in.good(); i++) {\n in.getline(buffer, MessageLen);\n if(!in.fail()){ \/\/ really read something\n\tstrings.push_back(buffer);\n }\n }\n }\n return strings;\n}\n\n\nbool TextChunk::reload()\n{\n StringVector newVec = parse();\n if (newVec.size() > 0) {\n theVector = newVec;\n }\n return (theVector.size() > 0);\n}\n\n\nsize_t TextChunk::size() const\n{\n return theVector.size();\n}\n\n\nconst StringVector& TextChunk::getVector() const\n{\n return theVector;\n}\n\n\n\/******************************************************************************\/\n\nbool TextChunkManager::parseFile(const std::string &fileName,\n\t\t\t\t const std::string &chunkName)\n{\n TextChunk textChunk(fileName);\n\n if (textChunk.size() <= 0) {\n return false;\n }\n\n \/\/ add a new chunk name if it isn't already listed\n if (theChunks.find(chunkName) == theChunks.end()) {\n chunkNames.push_back(chunkName);\n }\n\n \/\/ add or replace the chunk\n theChunks[chunkName] = textChunk;\n\n return true;\n}\n\n\nconst StringVector* TextChunkManager::getTextChunk(const std::string &chunkName) const\n{\n TextChunkMap::const_iterator it;\n it = theChunks.find(chunkName);\n if (it != theChunks.end()){\n return &it->second.getVector();\n } else {\n return NULL;\n }\n}\n\n\nconst StringVector& TextChunkManager::getChunkNames() const\n{\n return chunkNames;\n}\n\n\nvoid TextChunkManager::reload()\n{\n TextChunkMap::iterator it;\n for (it = theChunks.begin(); it != theChunks.end(); it++) {\n it->second.reload();\n }\n return;\n}\n\n\n\/******************************************************************************\/\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>#define SPICA_TRIMESH_EXPORT\n#include \"trimesh.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n\n#include \"..\/utils\/common.h\"\n\nnamespace spica {\n\n Trimesh::Trimesh()\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n }\n\n Trimesh::Trimesh(const std::string& filename)\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n load(filename);\n }\n\n Trimesh::Trimesh(const Trimesh& trimesh)\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n operator=(trimesh);\n }\n\n Trimesh::~Trimesh()\n {\n release();\n }\n\n void Trimesh::release() {\n delete[] _vertices;\n delete[] _faces;\n delete[] _normals;\n delete _accel;\n _numVerts = 0;\n _numFaces = 0;\n _vertices = NULL;\n _faces = NULL;\n _normals = NULL;\n _accel = NULL;\n }\n\n Trimesh& Trimesh::operator=(const Trimesh& trimesh) {\n release();\n\n _numVerts = trimesh._numVerts;\n _numFaces = trimesh._numFaces;\n _vertices = new Vector3[trimesh._numVerts];\n _faces = new int[trimesh._numFaces * 3];\n _normals = new Vector3[trimesh._numFaces];\n _accel = NULL;\n _accelType = trimesh._accelType;\n \n memcpy(_vertices, trimesh._vertices, sizeof(Vector3) * _numVerts);\n memcpy(_faces, trimesh._faces, sizeof(int) * (_numFaces * 3));\n memcpy(_normals, trimesh._normals, sizeof(Vector3) * _numFaces);\n\n buildAccel();\n\n return *this;\n }\n\n bool Trimesh::intersect(const Ray& ray, Hitpoint* hitpoint) const {\n msg_assert(_accel != NULL, \"Accelerator is not constructed\");\n hitpoint->setDistance(INFTY);\n return _accel->intersect(ray, hitpoint);\n }\n\n double Trimesh::area() const {\n double ret = 0.0;\n for (int i = 0; i < _numFaces; i++) {\n Triangle tri = this->getTriangle(i);\n ret += tri.area();\n }\n return ret;\n }\n\n void Trimesh::setAccelType(AccelType accelType, bool doBuild) {\n this->_accelType = accelType;\n if (doBuild) {\n buildAccel();\n }\n }\n\n void Trimesh::buildAccel() {\n std::vector<Triangle> triangles(_numFaces);\n for (int i = 0; i < _numFaces; i++) {\n Vector3& p0 = _vertices[_faces[i * 3 + 0]];\n Vector3& p1 = _vertices[_faces[i * 3 + 1]];\n Vector3& p2 = _vertices[_faces[i * 3 + 2]];\n triangles[i] = Triangle(p0, p1, p2);\n }\n\n switch(_accelType) {\n case KD_TREE_ACCEL:\n printf(\"Accelerator: K-D tree\\n\");\n _accel = new KdTreeAccel();\n break;\n case QBVH_ACCEL:\n printf(\"Accelerator: QBVH\\n\");\n _accel = new QBVHAccel();\n break;\n default:\n msg_assert(false, \"Unknown accelerator type!!\");\n break;\n }\n _accel->construct(triangles);\n }\n\n void Trimesh::load(const std::string& filename) {\n release();\n\n int dotPos = filename.find_last_of(\".\");\n std::string ext = filename.substr(dotPos);\n \n if (ext == \".ply\") {\n this->loadPly(filename);\n } else if (ext == \".obj\") {\n this->loadObj(filename);\n } else {\n msg_assert(ext == \".ply\" || ext == \".obj\", \"Mesh loader only accepts .ply and .obj file format\");\n }\n }\n\n void Trimesh::loadPly(const std::string& filename) {\n std::ifstream in(filename.c_str(), std::ios::in);\n msg_assert(in.is_open(), \"Failed to open mesh file\");\n\n std::string format, key, name, val;\n int numVerts = -1;\n int numFaces = -1;\n\n in >> format;\n msg_assert(format == \"ply\", \"Invalid format identifier\");\n\n bool isBody = false;\n while(!in.eof()) {\n if (!isBody) {\n in >> key;\n if (key == \"format\" || key == \"property\") {\n in >> name >> val;\n \/\/ std::cout << key << \" \" << name << \" \" << val << std::endl;\n } else if (key == \"element\") {\n in >> name;\n if (name == \"vertex\") {\n in >> numVerts;\n } else if (name == \"face\") {\n in >> numFaces;\n } else {\n msg_assert(false, \"Invalid element indentifier\");\n }\n } else if (key == \"end_header\") {\n isBody = true;\n continue;\n } else {\n continue;\n }\n } else {\n std::string line;\n std::stringstream ss;\n double vx, vy, vz;\n int nv, p0, p1, p2;\n\n msg_assert(numVerts > 0 && numFaces > 0, \"numVerts and numFaces must be positive\");\n\n _numVerts = numVerts;\n _numFaces = numFaces;\n _vertices = new Vector3[numVerts];\n _faces = new int[numFaces * 3];\n _normals = new Vector3[numFaces];\n\n std::getline(in, line); \/\/ skip end_header line\n\n int cnt = 0;\n for (int i = 0; i < numVerts; i++) {\n std::getline(in, line);\n ss.str(\"\");\n ss.clear(std::stringstream::goodbit);\n ss << line;\n ss >> vx >> vy >> vz;\n _vertices[i] = Vector3(vx, vy, vz);\n }\n\n for (int i = 0; i < numFaces; i++) {\n std::getline(in, line);\n ss.str(\"\");\n ss.clear(std::stringstream::goodbit);\n ss << line;\n ss >> nv >> p0 >> p1 >> p2;\n _faces[i * 3 + 0] = p0;\n _faces[i * 3 + 1] = p1;\n _faces[i * 3 + 2] = p2;\n\n _normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]).normalized();\n }\n break;\n }\n }\n }\n\n void Trimesh::loadObj(const std::string& filename) {\n std::ifstream in(filename.c_str(), std::ios::in);\n msg_assert(in.is_open(), \"Failed to open mesh file\");\n\n std::string typ;\n this->_numVerts = 0;\n this->_numFaces = 0;\n std::vector<Vector3> verts;\n std::vector<int> faces;\n while (!in.eof()) {\n in >> typ;\n if (typ == \"v\") {\n _numVerts++;\n \n double x, y, z;\n in >> x >> y >> z;\n verts.emplace_back(x, y, z);\n } else if (typ == \"f\") {\n _numFaces++;\n\n int v0, v1, v2;\n in >> v0 >> v1 >> v2;\n faces.push_back(v0);\n faces.push_back(v1);\n faces.push_back(v2);\n } else {\n msg_assert(false, \"Unknown type is found while reading .obj file!!\");\n }\n }\n\n _vertices = new Vector3[_numVerts];\n _faces = new int[_numFaces * 3];\n _normals = new Vector3[_numFaces];\n memcpy(_vertices, &verts[0], sizeof(Vector3) * _numVerts);\n memcpy(_faces, &faces[0], sizeof(int) * _numFaces * 3);\n for (int i = 0; i < _numFaces; i++) {\n int p0 = _faces[i * 3 + 0];\n int p1 = _faces[i * 3 + 1];\n int p2 = _faces[i * 3 + 2];\n _normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]);\n }\n }\n\n void Trimesh::translate(const Vector3& move) {\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i] += move;\n }\n }\n\n void Trimesh::scale(const double scaleX, const double scaleY, const double scaleZ) {\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i].setX(_vertices[i].x() * scaleX);\n _vertices[i].setY(_vertices[i].y() * scaleY);\n _vertices[i].setZ(_vertices[i].z() * scaleZ);\n }\n }\n\n void Trimesh::putOnPlane(const Plane& plane) {\n \/\/ Find nearest point\n double minval = INFTY;\n for (int i = 0; i < _numVerts; i++) {\n minval = std::min(minval, Vector3::dot(plane.normal(), _vertices[i]));\n }\n\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i] -= (minval + plane.distance()) * plane.normal();\n }\n }\n\n Vector3 Trimesh::getNormal(int id) const {\n msg_assert(id >= 0 && id < _numFaces, \"Triangle index out of bounds\");\n return _normals[id];\n }\n\n Triangle Trimesh::getTriangle(int id) const {\n msg_assert(id >= 0 && id < _numFaces, \"Triangle index out of bounds\");\n const Vector3& p0 = _vertices[_faces[id * 3 + 0]];\n const Vector3& p1 = _vertices[_faces[id * 3 + 1]];\n const Vector3& p2 = _vertices[_faces[id * 3 + 2]];\n return Triangle(p0, p1, p2);\n }\n\n} \/\/ namesapce spica\n<commit_msg>Fix function to load .obj file format.<commit_after>#define SPICA_TRIMESH_EXPORT\n#include \"trimesh.h\"\n\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n\n#include \"..\/utils\/common.h\"\n\nnamespace spica {\n\n Trimesh::Trimesh()\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n }\n\n Trimesh::Trimesh(const std::string& filename)\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n load(filename);\n }\n\n Trimesh::Trimesh(const Trimesh& trimesh)\n : _numVerts(0)\n , _numFaces(0)\n , _vertices(NULL)\n , _faces(NULL)\n , _normals(NULL)\n , _accel(NULL)\n , _accelType(QBVH_ACCEL)\n {\n operator=(trimesh);\n }\n\n Trimesh::~Trimesh()\n {\n release();\n }\n\n void Trimesh::release() {\n delete[] _vertices;\n delete[] _faces;\n delete[] _normals;\n delete _accel;\n _numVerts = 0;\n _numFaces = 0;\n _vertices = NULL;\n _faces = NULL;\n _normals = NULL;\n _accel = NULL;\n }\n\n Trimesh& Trimesh::operator=(const Trimesh& trimesh) {\n release();\n\n _numVerts = trimesh._numVerts;\n _numFaces = trimesh._numFaces;\n _vertices = new Vector3[trimesh._numVerts];\n _faces = new int[trimesh._numFaces * 3];\n _normals = new Vector3[trimesh._numFaces];\n _accel = NULL;\n _accelType = trimesh._accelType;\n \n memcpy(_vertices, trimesh._vertices, sizeof(Vector3) * _numVerts);\n memcpy(_faces, trimesh._faces, sizeof(int) * (_numFaces * 3));\n memcpy(_normals, trimesh._normals, sizeof(Vector3) * _numFaces);\n\n buildAccel();\n\n return *this;\n }\n\n bool Trimesh::intersect(const Ray& ray, Hitpoint* hitpoint) const {\n msg_assert(_accel != NULL, \"Accelerator is not constructed\");\n hitpoint->setDistance(INFTY);\n return _accel->intersect(ray, hitpoint);\n }\n\n double Trimesh::area() const {\n double ret = 0.0;\n for (int i = 0; i < _numFaces; i++) {\n Triangle tri = this->getTriangle(i);\n ret += tri.area();\n }\n return ret;\n }\n\n void Trimesh::setAccelType(AccelType accelType, bool doBuild) {\n this->_accelType = accelType;\n if (doBuild) {\n buildAccel();\n }\n }\n\n void Trimesh::buildAccel() {\n std::vector<Triangle> triangles(_numFaces);\n for (int i = 0; i < _numFaces; i++) {\n Vector3& p0 = _vertices[_faces[i * 3 + 0]];\n Vector3& p1 = _vertices[_faces[i * 3 + 1]];\n Vector3& p2 = _vertices[_faces[i * 3 + 2]];\n triangles[i] = Triangle(p0, p1, p2);\n }\n\n switch(_accelType) {\n case KD_TREE_ACCEL:\n printf(\"Accelerator: K-D tree\\n\");\n _accel = new KdTreeAccel();\n break;\n case QBVH_ACCEL:\n printf(\"Accelerator: QBVH\\n\");\n _accel = new QBVHAccel();\n break;\n default:\n msg_assert(false, \"Unknown accelerator type!!\");\n break;\n }\n _accel->construct(triangles);\n }\n\n void Trimesh::load(const std::string& filename) {\n release();\n\n int dotPos = filename.find_last_of(\".\");\n std::string ext = filename.substr(dotPos);\n \n if (ext == \".ply\") {\n this->loadPly(filename);\n } else if (ext == \".obj\") {\n this->loadObj(filename);\n } else {\n msg_assert(ext == \".ply\" || ext == \".obj\", \"Mesh loader only accepts .ply and .obj file format\");\n }\n }\n\n void Trimesh::loadPly(const std::string& filename) {\n std::ifstream in(filename.c_str(), std::ios::in);\n msg_assert(in.is_open(), \"Failed to open mesh file\");\n\n std::string format, key, name, val;\n int numVerts = -1;\n int numFaces = -1;\n\n in >> format;\n msg_assert(format == \"ply\", \"Invalid format identifier\");\n\n bool isBody = false;\n while(!in.eof()) {\n if (!isBody) {\n in >> key;\n if (key == \"format\" || key == \"property\") {\n in >> name >> val;\n \/\/ std::cout << key << \" \" << name << \" \" << val << std::endl;\n } else if (key == \"element\") {\n in >> name;\n if (name == \"vertex\") {\n in >> numVerts;\n } else if (name == \"face\") {\n in >> numFaces;\n } else {\n msg_assert(false, \"Invalid element indentifier\");\n }\n } else if (key == \"end_header\") {\n isBody = true;\n continue;\n } else {\n continue;\n }\n } else {\n std::string line;\n std::stringstream ss;\n double vx, vy, vz;\n int nv, p0, p1, p2;\n\n msg_assert(numVerts > 0 && numFaces > 0, \"numVerts and numFaces must be positive\");\n\n _numVerts = numVerts;\n _numFaces = numFaces;\n _vertices = new Vector3[numVerts];\n _faces = new int[numFaces * 3];\n _normals = new Vector3[numFaces];\n\n std::getline(in, line); \/\/ skip end_header line\n\n int cnt = 0;\n for (int i = 0; i < numVerts; i++) {\n std::getline(in, line);\n ss.str(\"\");\n ss.clear(std::stringstream::goodbit);\n ss << line;\n ss >> vx >> vy >> vz;\n _vertices[i] = Vector3(vx, vy, vz);\n }\n\n for (int i = 0; i < numFaces; i++) {\n std::getline(in, line);\n ss.str(\"\");\n ss.clear(std::stringstream::goodbit);\n ss << line;\n ss >> nv >> p0 >> p1 >> p2;\n _faces[i * 3 + 0] = p0 - 1;\n _faces[i * 3 + 1] = p1 - 1;\n _faces[i * 3 + 2] = p2 - 1;\n\n _normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]).normalized();\n }\n break;\n }\n }\n }\n\n void Trimesh::loadObj(const std::string& filename) {\n std::ifstream in(filename.c_str(), std::ios::in);\n msg_assert(in.is_open(), \"Failed to open mesh file\");\n\n std::string typ;\n this->_numVerts = 0;\n this->_numFaces = 0;\n std::vector<Vector3> verts;\n std::vector<int> faces;\n while (!in.eof()) {\n in >> typ;\n if (typ == \"v\") {\n _numVerts++;\n \n double x, y, z;\n in >> x >> y >> z;\n verts.emplace_back(x, y, z);\n } else if (typ == \"f\") {\n _numFaces++;\n\n int v0, v1, v2;\n in >> v0 >> v1 >> v2;\n faces.push_back(v0);\n faces.push_back(v1);\n faces.push_back(v2);\n } else {\n msg_assert(false, \"Unknown type is found while reading .obj file!!\");\n }\n }\n\n _vertices = new Vector3[_numVerts];\n _faces = new int[_numFaces * 3];\n _normals = new Vector3[_numFaces];\n memcpy(_vertices, &verts[0], sizeof(Vector3) * _numVerts);\n memcpy(_faces, &faces[0], sizeof(int) * _numFaces * 3);\n for (int i = 0; i < _numFaces; i++) {\n int p0 = _faces[i * 3 + 0];\n int p1 = _faces[i * 3 + 1];\n int p2 = _faces[i * 3 + 2];\n _normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]);\n }\n }\n\n void Trimesh::translate(const Vector3& move) {\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i] += move;\n }\n }\n\n void Trimesh::scale(const double scaleX, const double scaleY, const double scaleZ) {\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i].setX(_vertices[i].x() * scaleX);\n _vertices[i].setY(_vertices[i].y() * scaleY);\n _vertices[i].setZ(_vertices[i].z() * scaleZ);\n }\n }\n\n void Trimesh::putOnPlane(const Plane& plane) {\n \/\/ Find nearest point\n double minval = INFTY;\n for (int i = 0; i < _numVerts; i++) {\n minval = std::min(minval, Vector3::dot(plane.normal(), _vertices[i]));\n }\n\n for (int i = 0; i < _numVerts; i++) {\n _vertices[i] -= (minval + plane.distance()) * plane.normal();\n }\n }\n\n Vector3 Trimesh::getNormal(int id) const {\n msg_assert(id >= 0 && id < _numFaces, \"Triangle index out of bounds\");\n return _normals[id];\n }\n\n Triangle Trimesh::getTriangle(int id) const {\n msg_assert(id >= 0 && id < _numFaces, \"Triangle index out of bounds\");\n const Vector3& p0 = _vertices[_faces[id * 3 + 0]];\n const Vector3& p1 = _vertices[_faces[id * 3 + 1]];\n const Vector3& p2 = _vertices[_faces[id * 3 + 2]];\n return Triangle(p0, p1, p2);\n }\n\n} \/\/ namesapce spica\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost\n\/\/ Software License, Version 1.0. (See accompanying file\n\/\/ LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ See http:\/\/www.boost.org\/libs\/interprocess for documentation.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n#define BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n\n#ifndef BOOST_CONFIG_HPP\n# include <boost\/config.hpp>\n#endif\n#\n#if defined(BOOST_HAS_PRAGMA_ONCE)\n# pragma once\n#endif\n\n#include <boost\/interprocess\/detail\/config_begin.hpp>\n#include <boost\/interprocess\/detail\/workaround.hpp>\n#include <boost\/interprocess\/creation_tags.hpp>\n#include <boost\/interprocess\/exceptions.hpp>\n#include <boost\/move\/utility_core.hpp>\n#include <boost\/interprocess\/interprocess_fwd.hpp>\n#include <boost\/interprocess\/exceptions.hpp>\n#include <boost\/interprocess\/detail\/os_file_functions.hpp>\n#include <boost\/interprocess\/detail\/shared_dir_helpers.hpp>\n#include <boost\/interprocess\/permissions.hpp>\n#include <boost\/move\/adl_move_swap.hpp>\n#include <cstddef>\n#include <string>\n\n#if defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n# include <fcntl.h> \/\/O_CREAT, O_*...\n# include <sys\/mman.h> \/\/shm_xxx\n# include <unistd.h> \/\/ftruncate, close\n# include <sys\/stat.h> \/\/mode_t, S_IRWXG, S_IRWXO, S_IRWXU,\n# if defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n# if defined(__FreeBSD__)\n# include <sys\/sysctl.h>\n# endif\n# endif\n#else\n\/\/\n#endif\n\n\/\/!\\file\n\/\/!Describes a shared memory object management class.\n\nnamespace boost {\nnamespace interprocess {\n\n\/\/!A class that wraps a shared memory mapping that can be used to\n\/\/!create mapped regions from the mapped files\nclass shared_memory_object\n{\n #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n \/\/Non-copyable and non-assignable\n BOOST_MOVABLE_BUT_NOT_COPYABLE(shared_memory_object)\n #endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n\n public:\n \/\/!Default constructor. Represents an empty shared_memory_object.\n shared_memory_object();\n\n \/\/!Creates a shared memory object with name \"name\" and mode \"mode\", with the access mode \"mode\"\n \/\/!If the file previously exists, throws an error.*\/\n shared_memory_object(create_only_t, const char *name, mode_t mode, const permissions &perm = permissions())\n { this->priv_open_or_create(ipcdetail::DoCreate, name, mode, perm); }\n\n \/\/!Tries to create a shared memory object with name \"name\" and mode \"mode\", with the\n \/\/!access mode \"mode\". If the file previously exists, it tries to open it with mode \"mode\".\n \/\/!Otherwise throws an error.\n shared_memory_object(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions())\n { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, perm); }\n\n \/\/!Tries to open a shared memory object with name \"name\", with the access mode \"mode\".\n \/\/!If the file does not previously exist, it throws an error.\n shared_memory_object(open_only_t, const char *name, mode_t mode)\n { this->priv_open_or_create(ipcdetail::DoOpen, name, mode, permissions()); }\n\n \/\/!Moves the ownership of \"moved\"'s shared memory object to *this.\n \/\/!After the call, \"moved\" does not represent any shared memory object.\n \/\/!Does not throw\n shared_memory_object(BOOST_RV_REF(shared_memory_object) moved)\n : m_handle(file_handle_t(ipcdetail::invalid_file()))\n , m_mode(read_only)\n { this->swap(moved); }\n\n \/\/!Moves the ownership of \"moved\"'s shared memory to *this.\n \/\/!After the call, \"moved\" does not represent any shared memory.\n \/\/!Does not throw\n shared_memory_object &operator=(BOOST_RV_REF(shared_memory_object) moved)\n {\n shared_memory_object tmp(boost::move(moved));\n this->swap(tmp);\n return *this;\n }\n\n \/\/!Swaps the shared_memory_objects. Does not throw\n void swap(shared_memory_object &moved);\n\n \/\/!Erases a shared memory object from the system.\n \/\/!Returns false on error. Never throws\n static bool remove(const char *name);\n\n \/\/!Sets the size of the shared memory mapping\n void truncate(offset_t length);\n\n \/\/!Destroys *this and indicates that the calling process is finished using\n \/\/!the resource. All mapped regions are still\n \/\/!valid after destruction. The destructor function will deallocate\n \/\/!any system resources allocated by the system for use by this process for\n \/\/!this resource. The resource can still be opened again calling\n \/\/!the open constructor overload. To erase the resource from the system\n \/\/!use remove().\n ~shared_memory_object();\n\n \/\/!Returns the name of the shared memory object.\n const char *get_name() const;\n\n \/\/!Returns true if the size of the shared memory object\n \/\/!can be obtained and writes the size in the passed reference\n bool get_size(offset_t &size) const;\n\n \/\/!Returns access mode\n mode_t get_mode() const;\n\n \/\/!Returns mapping handle. Never throws.\n mapping_handle_t get_mapping_handle() const;\n\n #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n private:\n\n \/\/!Closes a previously opened file mapping. Never throws.\n void priv_close();\n\n \/\/!Opens or creates a shared memory object.\n bool priv_open_or_create(ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm);\n\n file_handle_t m_handle;\n mode_t m_mode;\n std::string m_filename;\n #endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n};\n\n#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n\ninline shared_memory_object::shared_memory_object()\n : m_handle(file_handle_t(ipcdetail::invalid_file()))\n , m_mode(read_only)\n{}\n\ninline shared_memory_object::~shared_memory_object()\n{ this->priv_close(); }\n\n\ninline const char *shared_memory_object::get_name() const\n{ return m_filename.c_str(); }\n\ninline bool shared_memory_object::get_size(offset_t &size) const\n{ return ipcdetail::get_file_size((file_handle_t)m_handle, size); }\n\ninline void shared_memory_object::swap(shared_memory_object &other)\n{\n boost::adl_move_swap(m_handle, other.m_handle);\n boost::adl_move_swap(m_mode, other.m_mode);\n m_filename.swap(other.m_filename);\n}\n\ninline mapping_handle_t shared_memory_object::get_mapping_handle() const\n{\n return ipcdetail::mapping_handle_from_file_handle(m_handle);\n}\n\ninline mode_t shared_memory_object::get_mode() const\n{ return m_mode; }\n\n#if !defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n\ninline bool shared_memory_object::priv_open_or_create\n (ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm)\n{\n m_filename = filename;\n std::string shmfile;\n ipcdetail::create_shared_dir_cleaning_old_and_get_filepath(filename, shmfile);\n\n \/\/Set accesses\n if (mode != read_write && mode != read_only){\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n\n switch(type){\n case ipcdetail::DoOpen:\n m_handle = ipcdetail::open_existing_file(shmfile.c_str(), mode, true);\n break;\n case ipcdetail::DoCreate:\n m_handle = ipcdetail::create_new_file(shmfile.c_str(), mode, perm, true);\n break;\n case ipcdetail::DoOpenOrCreate:\n m_handle = ipcdetail::create_or_open_file(shmfile.c_str(), mode, perm, true);\n break;\n default:\n {\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n }\n\n \/\/Check for error\n if(m_handle == ipcdetail::invalid_file()){\n error_info err = system_error_code();\n this->priv_close();\n throw interprocess_exception(err);\n }\n\n m_mode = mode;\n return true;\n}\n\ninline bool shared_memory_object::remove(const char *filename)\n{\n try{\n \/\/Make sure a temporary path is created for shared memory\n std::string shmfile;\n ipcdetail::shared_filepath(filename, shmfile);\n return ipcdetail::delete_file(shmfile.c_str());\n }\n catch(...){\n return false;\n }\n}\n\ninline void shared_memory_object::truncate(offset_t length)\n{\n if(!ipcdetail::truncate_file(m_handle, length)){\n error_info err = system_error_code();\n throw interprocess_exception(err);\n }\n}\n\ninline void shared_memory_object::priv_close()\n{\n if(m_handle != ipcdetail::invalid_file()){\n ipcdetail::close_file(m_handle);\n m_handle = ipcdetail::invalid_file();\n }\n}\n\n#else \/\/!defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n\nnamespace shared_memory_object_detail {\n\n#ifdef BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY\n\n#if defined(__FreeBSD__)\n\ninline bool use_filesystem_based_posix()\n{\n int jailed = 0;\n std::size_t len = sizeof(jailed);\n ::sysctlbyname(\"security.jail.jailed\", &jailed, &len, NULL, 0);\n return jailed != 0;\n}\n\n#else\n#error \"Not supported platform for BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY\"\n#endif\n\n#endif\n\n} \/\/shared_memory_object_detail\n\ninline bool shared_memory_object::priv_open_or_create\n (ipcdetail::create_enum_t type,\n const char *filename,\n mode_t mode, const permissions &perm)\n{\n #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = false;\n #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix();\n #else\n const bool add_leading_slash = true;\n #endif\n if(add_leading_slash){\n ipcdetail::add_leading_slash(filename, m_filename);\n }\n else{\n ipcdetail::create_shared_dir_cleaning_old_and_get_filepath(filename, m_filename);\n }\n\n \/\/Create new mapping\n int oflag = 0;\n if(mode == read_only){\n oflag |= O_RDONLY;\n }\n else if(mode == read_write){\n oflag |= O_RDWR;\n }\n else{\n error_info err(mode_error);\n throw interprocess_exception(err);\n }\n int unix_perm = perm.get_permissions();\n\n switch(type){\n case ipcdetail::DoOpen:\n {\n \/\/No oflag addition\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n }\n break;\n case ipcdetail::DoCreate:\n {\n oflag |= (O_CREAT | O_EXCL);\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n if(m_handle >= 0){\n ::fchmod(m_handle, unix_perm);\n }\n }\n break;\n case ipcdetail::DoOpenOrCreate:\n {\n \/\/We need a create\/open loop to change permissions correctly using fchmod, since\n \/\/with \"O_CREAT\" only we don't know if we've created or opened the shm.\n while(1){\n \/\/Try to create shared memory\n m_handle = shm_open(m_filename.c_str(), oflag | (O_CREAT | O_EXCL), unix_perm);\n \/\/If successful change real permissions\n if(m_handle >= 0){\n ::fchmod(m_handle, unix_perm);\n }\n \/\/If already exists, try to open\n else if(errno == EEXIST){\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n \/\/If open fails and errno tells the file does not exist\n \/\/(shm was removed between creation and opening tries), just retry\n if(m_handle < 0 && errno == ENOENT){\n continue;\n }\n }\n \/\/Exit retries\n break;\n }\n }\n break;\n default:\n {\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n }\n\n \/\/Check for error\n if(m_handle < 0){\n error_info err = errno;\n this->priv_close();\n throw interprocess_exception(err);\n }\n\n m_filename = filename;\n m_mode = mode;\n return true;\n}\n\ninline bool shared_memory_object::remove(const char *filename)\n{\n try{\n std::string filepath;\n #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = false;\n #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix();\n #else\n const bool add_leading_slash = true;\n #endif\n if(add_leading_slash){\n ipcdetail::add_leading_slash(filename, filepath);\n }\n else{\n ipcdetail::shared_filepath(filename, filepath);\n }\n return 0 == shm_unlink(filepath.c_str());\n }\n catch(...){\n return false;\n }\n}\n\ninline void shared_memory_object::truncate(offset_t length)\n{\n#ifdef BOOST_FASTDDS_PATCHES\n\n if (0 != fallocate(m_handle, 0, 0, length))\n {\n error_info err(system_error_code());\n throw interprocess_exception(err);\n }\n\n#else \/\/ Original BOOST code\n\n if(0 != ftruncate(m_handle, length)){\n error_info err(system_error_code());\n throw interprocess_exception(err);\n }\n\n#endif\n}\n\ninline void shared_memory_object::priv_close()\n{\n if(m_handle != -1){\n ::close(m_handle);\n m_handle = -1;\n }\n}\n\n#endif\n\n\/\/!A class that stores the name of a shared memory\n\/\/!and calls shared_memory_object::remove(name) in its destructor\n\/\/!Useful to remove temporary shared memory objects in the presence\n\/\/!of exceptions\nclass remove_shared_memory_on_destroy\n{\n const char * m_name;\n public:\n remove_shared_memory_on_destroy(const char *name)\n : m_name(name)\n {}\n\n ~remove_shared_memory_on_destroy()\n { shared_memory_object::remove(m_name); }\n};\n\n#endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n\n} \/\/namespace interprocess {\n} \/\/namespace boost {\n\n#include <boost\/interprocess\/detail\/config_end.hpp>\n\n#endif \/\/BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n<commit_msg>Use posix_fallocate. (#1465)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost\n\/\/ Software License, Version 1.0. (See accompanying file\n\/\/ LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ See http:\/\/www.boost.org\/libs\/interprocess for documentation.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n#define BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n\n#ifndef BOOST_CONFIG_HPP\n# include <boost\/config.hpp>\n#endif\n#\n#if defined(BOOST_HAS_PRAGMA_ONCE)\n# pragma once\n#endif\n\n#include <boost\/interprocess\/detail\/config_begin.hpp>\n#include <boost\/interprocess\/detail\/workaround.hpp>\n#include <boost\/interprocess\/creation_tags.hpp>\n#include <boost\/interprocess\/exceptions.hpp>\n#include <boost\/move\/utility_core.hpp>\n#include <boost\/interprocess\/interprocess_fwd.hpp>\n#include <boost\/interprocess\/exceptions.hpp>\n#include <boost\/interprocess\/detail\/os_file_functions.hpp>\n#include <boost\/interprocess\/detail\/shared_dir_helpers.hpp>\n#include <boost\/interprocess\/permissions.hpp>\n#include <boost\/move\/adl_move_swap.hpp>\n#include <cstddef>\n#include <string>\n\n#if defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n# include <fcntl.h> \/\/O_CREAT, O_*...\n# include <sys\/mman.h> \/\/shm_xxx\n# include <unistd.h> \/\/ftruncate, close\n# include <sys\/stat.h> \/\/mode_t, S_IRWXG, S_IRWXO, S_IRWXU,\n# if defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n# if defined(__FreeBSD__)\n# include <sys\/sysctl.h>\n# endif\n# endif\n#else\n\/\/\n#endif\n\n\/\/!\\file\n\/\/!Describes a shared memory object management class.\n\nnamespace boost {\nnamespace interprocess {\n\n\/\/!A class that wraps a shared memory mapping that can be used to\n\/\/!create mapped regions from the mapped files\nclass shared_memory_object\n{\n #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n \/\/Non-copyable and non-assignable\n BOOST_MOVABLE_BUT_NOT_COPYABLE(shared_memory_object)\n #endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n\n public:\n \/\/!Default constructor. Represents an empty shared_memory_object.\n shared_memory_object();\n\n \/\/!Creates a shared memory object with name \"name\" and mode \"mode\", with the access mode \"mode\"\n \/\/!If the file previously exists, throws an error.*\/\n shared_memory_object(create_only_t, const char *name, mode_t mode, const permissions &perm = permissions())\n { this->priv_open_or_create(ipcdetail::DoCreate, name, mode, perm); }\n\n \/\/!Tries to create a shared memory object with name \"name\" and mode \"mode\", with the\n \/\/!access mode \"mode\". If the file previously exists, it tries to open it with mode \"mode\".\n \/\/!Otherwise throws an error.\n shared_memory_object(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions())\n { this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, perm); }\n\n \/\/!Tries to open a shared memory object with name \"name\", with the access mode \"mode\".\n \/\/!If the file does not previously exist, it throws an error.\n shared_memory_object(open_only_t, const char *name, mode_t mode)\n { this->priv_open_or_create(ipcdetail::DoOpen, name, mode, permissions()); }\n\n \/\/!Moves the ownership of \"moved\"'s shared memory object to *this.\n \/\/!After the call, \"moved\" does not represent any shared memory object.\n \/\/!Does not throw\n shared_memory_object(BOOST_RV_REF(shared_memory_object) moved)\n : m_handle(file_handle_t(ipcdetail::invalid_file()))\n , m_mode(read_only)\n { this->swap(moved); }\n\n \/\/!Moves the ownership of \"moved\"'s shared memory to *this.\n \/\/!After the call, \"moved\" does not represent any shared memory.\n \/\/!Does not throw\n shared_memory_object &operator=(BOOST_RV_REF(shared_memory_object) moved)\n {\n shared_memory_object tmp(boost::move(moved));\n this->swap(tmp);\n return *this;\n }\n\n \/\/!Swaps the shared_memory_objects. Does not throw\n void swap(shared_memory_object &moved);\n\n \/\/!Erases a shared memory object from the system.\n \/\/!Returns false on error. Never throws\n static bool remove(const char *name);\n\n \/\/!Sets the size of the shared memory mapping\n void truncate(offset_t length);\n\n \/\/!Destroys *this and indicates that the calling process is finished using\n \/\/!the resource. All mapped regions are still\n \/\/!valid after destruction. The destructor function will deallocate\n \/\/!any system resources allocated by the system for use by this process for\n \/\/!this resource. The resource can still be opened again calling\n \/\/!the open constructor overload. To erase the resource from the system\n \/\/!use remove().\n ~shared_memory_object();\n\n \/\/!Returns the name of the shared memory object.\n const char *get_name() const;\n\n \/\/!Returns true if the size of the shared memory object\n \/\/!can be obtained and writes the size in the passed reference\n bool get_size(offset_t &size) const;\n\n \/\/!Returns access mode\n mode_t get_mode() const;\n\n \/\/!Returns mapping handle. Never throws.\n mapping_handle_t get_mapping_handle() const;\n\n #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n private:\n\n \/\/!Closes a previously opened file mapping. Never throws.\n void priv_close();\n\n \/\/!Opens or creates a shared memory object.\n bool priv_open_or_create(ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm);\n\n file_handle_t m_handle;\n mode_t m_mode;\n std::string m_filename;\n #endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n};\n\n#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)\n\ninline shared_memory_object::shared_memory_object()\n : m_handle(file_handle_t(ipcdetail::invalid_file()))\n , m_mode(read_only)\n{}\n\ninline shared_memory_object::~shared_memory_object()\n{ this->priv_close(); }\n\n\ninline const char *shared_memory_object::get_name() const\n{ return m_filename.c_str(); }\n\ninline bool shared_memory_object::get_size(offset_t &size) const\n{ return ipcdetail::get_file_size((file_handle_t)m_handle, size); }\n\ninline void shared_memory_object::swap(shared_memory_object &other)\n{\n boost::adl_move_swap(m_handle, other.m_handle);\n boost::adl_move_swap(m_mode, other.m_mode);\n m_filename.swap(other.m_filename);\n}\n\ninline mapping_handle_t shared_memory_object::get_mapping_handle() const\n{\n return ipcdetail::mapping_handle_from_file_handle(m_handle);\n}\n\ninline mode_t shared_memory_object::get_mode() const\n{ return m_mode; }\n\n#if !defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n\ninline bool shared_memory_object::priv_open_or_create\n (ipcdetail::create_enum_t type, const char *filename, mode_t mode, const permissions &perm)\n{\n m_filename = filename;\n std::string shmfile;\n ipcdetail::create_shared_dir_cleaning_old_and_get_filepath(filename, shmfile);\n\n \/\/Set accesses\n if (mode != read_write && mode != read_only){\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n\n switch(type){\n case ipcdetail::DoOpen:\n m_handle = ipcdetail::open_existing_file(shmfile.c_str(), mode, true);\n break;\n case ipcdetail::DoCreate:\n m_handle = ipcdetail::create_new_file(shmfile.c_str(), mode, perm, true);\n break;\n case ipcdetail::DoOpenOrCreate:\n m_handle = ipcdetail::create_or_open_file(shmfile.c_str(), mode, perm, true);\n break;\n default:\n {\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n }\n\n \/\/Check for error\n if(m_handle == ipcdetail::invalid_file()){\n error_info err = system_error_code();\n this->priv_close();\n throw interprocess_exception(err);\n }\n\n m_mode = mode;\n return true;\n}\n\ninline bool shared_memory_object::remove(const char *filename)\n{\n try{\n \/\/Make sure a temporary path is created for shared memory\n std::string shmfile;\n ipcdetail::shared_filepath(filename, shmfile);\n return ipcdetail::delete_file(shmfile.c_str());\n }\n catch(...){\n return false;\n }\n}\n\ninline void shared_memory_object::truncate(offset_t length)\n{\n if(!ipcdetail::truncate_file(m_handle, length)){\n error_info err = system_error_code();\n throw interprocess_exception(err);\n }\n}\n\ninline void shared_memory_object::priv_close()\n{\n if(m_handle != ipcdetail::invalid_file()){\n ipcdetail::close_file(m_handle);\n m_handle = ipcdetail::invalid_file();\n }\n}\n\n#else \/\/!defined(BOOST_INTERPROCESS_POSIX_SHARED_MEMORY_OBJECTS)\n\nnamespace shared_memory_object_detail {\n\n#ifdef BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY\n\n#if defined(__FreeBSD__)\n\ninline bool use_filesystem_based_posix()\n{\n int jailed = 0;\n std::size_t len = sizeof(jailed);\n ::sysctlbyname(\"security.jail.jailed\", &jailed, &len, NULL, 0);\n return jailed != 0;\n}\n\n#else\n#error \"Not supported platform for BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY\"\n#endif\n\n#endif\n\n} \/\/shared_memory_object_detail\n\ninline bool shared_memory_object::priv_open_or_create\n (ipcdetail::create_enum_t type,\n const char *filename,\n mode_t mode, const permissions &perm)\n{\n #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = false;\n #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix();\n #else\n const bool add_leading_slash = true;\n #endif\n if(add_leading_slash){\n ipcdetail::add_leading_slash(filename, m_filename);\n }\n else{\n ipcdetail::create_shared_dir_cleaning_old_and_get_filepath(filename, m_filename);\n }\n\n \/\/Create new mapping\n int oflag = 0;\n if(mode == read_only){\n oflag |= O_RDONLY;\n }\n else if(mode == read_write){\n oflag |= O_RDWR;\n }\n else{\n error_info err(mode_error);\n throw interprocess_exception(err);\n }\n int unix_perm = perm.get_permissions();\n\n switch(type){\n case ipcdetail::DoOpen:\n {\n \/\/No oflag addition\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n }\n break;\n case ipcdetail::DoCreate:\n {\n oflag |= (O_CREAT | O_EXCL);\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n if(m_handle >= 0){\n ::fchmod(m_handle, unix_perm);\n }\n }\n break;\n case ipcdetail::DoOpenOrCreate:\n {\n \/\/We need a create\/open loop to change permissions correctly using fchmod, since\n \/\/with \"O_CREAT\" only we don't know if we've created or opened the shm.\n while(1){\n \/\/Try to create shared memory\n m_handle = shm_open(m_filename.c_str(), oflag | (O_CREAT | O_EXCL), unix_perm);\n \/\/If successful change real permissions\n if(m_handle >= 0){\n ::fchmod(m_handle, unix_perm);\n }\n \/\/If already exists, try to open\n else if(errno == EEXIST){\n m_handle = shm_open(m_filename.c_str(), oflag, unix_perm);\n \/\/If open fails and errno tells the file does not exist\n \/\/(shm was removed between creation and opening tries), just retry\n if(m_handle < 0 && errno == ENOENT){\n continue;\n }\n }\n \/\/Exit retries\n break;\n }\n }\n break;\n default:\n {\n error_info err = other_error;\n throw interprocess_exception(err);\n }\n }\n\n \/\/Check for error\n if(m_handle < 0){\n error_info err = errno;\n this->priv_close();\n throw interprocess_exception(err);\n }\n\n m_filename = filename;\n m_mode = mode;\n return true;\n}\n\ninline bool shared_memory_object::remove(const char *filename)\n{\n try{\n std::string filepath;\n #if defined(BOOST_INTERPROCESS_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = false;\n #elif defined(BOOST_INTERPROCESS_RUNTIME_FILESYSTEM_BASED_POSIX_SHARED_MEMORY)\n const bool add_leading_slash = !shared_memory_object_detail::use_filesystem_based_posix();\n #else\n const bool add_leading_slash = true;\n #endif\n if(add_leading_slash){\n ipcdetail::add_leading_slash(filename, filepath);\n }\n else{\n ipcdetail::shared_filepath(filename, filepath);\n }\n return 0 == shm_unlink(filepath.c_str());\n }\n catch(...){\n return false;\n }\n}\n\ninline void shared_memory_object::truncate(offset_t length)\n{\n#ifdef BOOST_FASTDDS_PATCHES\n\n if (0 != posix_fallocate(m_handle, 0, length))\n {\n error_info err(system_error_code());\n throw interprocess_exception(err);\n }\n\n#else \/\/ Original BOOST code\n\n if(0 != ftruncate(m_handle, length)){\n error_info err(system_error_code());\n throw interprocess_exception(err);\n }\n\n#endif\n}\n\ninline void shared_memory_object::priv_close()\n{\n if(m_handle != -1){\n ::close(m_handle);\n m_handle = -1;\n }\n}\n\n#endif\n\n\/\/!A class that stores the name of a shared memory\n\/\/!and calls shared_memory_object::remove(name) in its destructor\n\/\/!Useful to remove temporary shared memory objects in the presence\n\/\/!of exceptions\nclass remove_shared_memory_on_destroy\n{\n const char * m_name;\n public:\n remove_shared_memory_on_destroy(const char *name)\n : m_name(name)\n {}\n\n ~remove_shared_memory_on_destroy()\n { shared_memory_object::remove(m_name); }\n};\n\n#endif \/\/#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED\n\n} \/\/namespace interprocess {\n} \/\/namespace boost {\n\n#include <boost\/interprocess\/detail\/config_end.hpp>\n\n#endif \/\/BOOST_INTERPROCESS_SHARED_MEMORY_OBJECT_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- sanitizer_stacktrace_libcdep.cc -----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is shared between AddressSanitizer and ThreadSanitizer\n\/\/ run-time libraries.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common.h\"\n#include \"sanitizer_placement_new.h\"\n#include \"sanitizer_stacktrace.h\"\n#include \"sanitizer_stacktrace_printer.h\"\n#include \"sanitizer_symbolizer.h\"\n\nnamespace __sanitizer {\n\nvoid StackTrace::Print() const {\n if (trace == nullptr || size == 0) {\n Printf(\" <empty stack>\\n\\n\");\n return;\n }\n InternalScopedString frame_desc(GetPageSizeCached() * 2);\n InternalScopedString dedup_token(GetPageSizeCached());\n int dedup_frames = common_flags()->dedup_token_length;\n uptr frame_num = 0;\n for (uptr i = 0; i < size && trace[i]; i++) {\n \/\/ PCs in stack traces are actually the return addresses, that is,\n \/\/ addresses of the next instructions after the call.\n uptr pc = GetPreviousInstructionPc(trace[i]);\n SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(pc);\n CHECK(frames);\n for (SymbolizedStack *cur = frames; cur; cur = cur->next) {\n frame_desc.clear();\n RenderFrame(&frame_desc, common_flags()->stack_trace_format, frame_num++,\n cur->info, common_flags()->symbolize_vs_style,\n common_flags()->strip_path_prefix);\n Printf(\"%s\\n\", frame_desc.data());\n if (dedup_frames-- > 0) {\n if (dedup_token.length())\n dedup_token.append(\"--\");\n dedup_token.append(cur->info.function);\n }\n }\n frames->ClearAll();\n }\n \/\/ Always print a trailing empty line after stack trace.\n Printf(\"\\n\");\n if (dedup_token.length())\n Printf(\"DEDUP_TOKEN: %s\\n\", dedup_token.data());\n}\n\nvoid BufferedStackTrace::Unwind(u32 max_depth, uptr pc, uptr bp, void *context,\n uptr stack_top, uptr stack_bottom,\n bool request_fast_unwind) {\n top_frame_bp = (max_depth > 0) ? bp : 0;\n \/\/ Avoid doing any work for small max_depth.\n if (max_depth == 0) {\n size = 0;\n return;\n }\n if (max_depth == 1) {\n size = 1;\n trace_buffer[0] = pc;\n return;\n }\n if (!WillUseFastUnwind(request_fast_unwind)) {\n#if SANITIZER_CAN_SLOW_UNWIND\n if (context)\n SlowUnwindStackWithContext(pc, context, max_depth);\n else\n SlowUnwindStack(pc, max_depth);\n#else\n UNREACHABLE(\"slow unwind requested but not available\");\n#endif\n } else {\n FastUnwindStack(pc, bp, stack_top, stack_bottom, max_depth);\n }\n}\n\nstatic int GetModuleAndOffsetForPc(uptr pc, char *module_name,\n uptr module_name_len, uptr *pc_offset) {\n const char *found_module_name = nullptr;\n bool ok = Symbolizer::GetOrInit()->GetModuleNameAndOffsetForPC(\n pc, &found_module_name, pc_offset);\n\n if (!ok) return false;\n\n if (module_name && module_name_len) {\n internal_strncpy(module_name, found_module_name, module_name_len);\n module_name[module_name_len - 1] = '\\x00';\n }\n return true;\n}\n\n} \/\/ namespace __sanitizer\nusing namespace __sanitizer;\n\nextern \"C\" {\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid __sanitizer_symbolize_pc(uptr pc, const char *fmt, char *out_buf,\n uptr out_buf_size) {\n if (!out_buf_size) return;\n pc = StackTrace::GetPreviousInstructionPc(pc);\n SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);\n if (!frame) {\n internal_strncpy(out_buf, \"<can't symbolize>\", out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n return;\n }\n InternalScopedString frame_desc(GetPageSizeCached());\n RenderFrame(&frame_desc, fmt, 0, frame->info,\n common_flags()->symbolize_vs_style,\n common_flags()->strip_path_prefix);\n internal_strncpy(out_buf, frame_desc.data(), out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid __sanitizer_symbolize_global(uptr data_addr, const char *fmt,\n char *out_buf, uptr out_buf_size) {\n if (!out_buf_size) return;\n out_buf[0] = 0;\n DataInfo DI;\n if (!Symbolizer::GetOrInit()->SymbolizeData(data_addr, &DI)) return;\n InternalScopedString data_desc(GetPageSizeCached());\n RenderData(&data_desc, fmt, &DI, common_flags()->strip_path_prefix);\n internal_strncpy(out_buf, data_desc.data(), out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nint __sanitizer_get_module_and_offset_for_pc( \/\/ NOLINT\n uptr pc, char *module_name, uptr module_name_len, uptr *pc_offset) {\n return __sanitizer::GetModuleAndOffsetForPc(pc, module_name, module_name_len,\n pc_offset);\n}\n} \/\/ extern \"C\"\n<commit_msg>Do not crash with missing symbolication when running in DEDUP mode<commit_after>\/\/===-- sanitizer_stacktrace_libcdep.cc -----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is shared between AddressSanitizer and ThreadSanitizer\n\/\/ run-time libraries.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common.h\"\n#include \"sanitizer_placement_new.h\"\n#include \"sanitizer_stacktrace.h\"\n#include \"sanitizer_stacktrace_printer.h\"\n#include \"sanitizer_symbolizer.h\"\n\nnamespace __sanitizer {\n\nvoid StackTrace::Print() const {\n if (trace == nullptr || size == 0) {\n Printf(\" <empty stack>\\n\\n\");\n return;\n }\n InternalScopedString frame_desc(GetPageSizeCached() * 2);\n InternalScopedString dedup_token(GetPageSizeCached());\n int dedup_frames = common_flags()->dedup_token_length;\n uptr frame_num = 0;\n for (uptr i = 0; i < size && trace[i]; i++) {\n \/\/ PCs in stack traces are actually the return addresses, that is,\n \/\/ addresses of the next instructions after the call.\n uptr pc = GetPreviousInstructionPc(trace[i]);\n SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(pc);\n CHECK(frames);\n for (SymbolizedStack *cur = frames; cur; cur = cur->next) {\n frame_desc.clear();\n RenderFrame(&frame_desc, common_flags()->stack_trace_format, frame_num++,\n cur->info, common_flags()->symbolize_vs_style,\n common_flags()->strip_path_prefix);\n Printf(\"%s\\n\", frame_desc.data());\n if (dedup_frames-- > 0) {\n if (dedup_token.length())\n dedup_token.append(\"--\");\n if (cur->info.function != nullptr)\n dedup_token.append(cur->info.function);\n }\n }\n frames->ClearAll();\n }\n \/\/ Always print a trailing empty line after stack trace.\n Printf(\"\\n\");\n if (dedup_token.length())\n Printf(\"DEDUP_TOKEN: %s\\n\", dedup_token.data());\n}\n\nvoid BufferedStackTrace::Unwind(u32 max_depth, uptr pc, uptr bp, void *context,\n uptr stack_top, uptr stack_bottom,\n bool request_fast_unwind) {\n top_frame_bp = (max_depth > 0) ? bp : 0;\n \/\/ Avoid doing any work for small max_depth.\n if (max_depth == 0) {\n size = 0;\n return;\n }\n if (max_depth == 1) {\n size = 1;\n trace_buffer[0] = pc;\n return;\n }\n if (!WillUseFastUnwind(request_fast_unwind)) {\n#if SANITIZER_CAN_SLOW_UNWIND\n if (context)\n SlowUnwindStackWithContext(pc, context, max_depth);\n else\n SlowUnwindStack(pc, max_depth);\n#else\n UNREACHABLE(\"slow unwind requested but not available\");\n#endif\n } else {\n FastUnwindStack(pc, bp, stack_top, stack_bottom, max_depth);\n }\n}\n\nstatic int GetModuleAndOffsetForPc(uptr pc, char *module_name,\n uptr module_name_len, uptr *pc_offset) {\n const char *found_module_name = nullptr;\n bool ok = Symbolizer::GetOrInit()->GetModuleNameAndOffsetForPC(\n pc, &found_module_name, pc_offset);\n\n if (!ok) return false;\n\n if (module_name && module_name_len) {\n internal_strncpy(module_name, found_module_name, module_name_len);\n module_name[module_name_len - 1] = '\\x00';\n }\n return true;\n}\n\n} \/\/ namespace __sanitizer\nusing namespace __sanitizer;\n\nextern \"C\" {\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid __sanitizer_symbolize_pc(uptr pc, const char *fmt, char *out_buf,\n uptr out_buf_size) {\n if (!out_buf_size) return;\n pc = StackTrace::GetPreviousInstructionPc(pc);\n SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);\n if (!frame) {\n internal_strncpy(out_buf, \"<can't symbolize>\", out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n return;\n }\n InternalScopedString frame_desc(GetPageSizeCached());\n RenderFrame(&frame_desc, fmt, 0, frame->info,\n common_flags()->symbolize_vs_style,\n common_flags()->strip_path_prefix);\n internal_strncpy(out_buf, frame_desc.data(), out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid __sanitizer_symbolize_global(uptr data_addr, const char *fmt,\n char *out_buf, uptr out_buf_size) {\n if (!out_buf_size) return;\n out_buf[0] = 0;\n DataInfo DI;\n if (!Symbolizer::GetOrInit()->SymbolizeData(data_addr, &DI)) return;\n InternalScopedString data_desc(GetPageSizeCached());\n RenderData(&data_desc, fmt, &DI, common_flags()->strip_path_prefix);\n internal_strncpy(out_buf, data_desc.data(), out_buf_size);\n out_buf[out_buf_size - 1] = 0;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nint __sanitizer_get_module_and_offset_for_pc( \/\/ NOLINT\n uptr pc, char *module_name, uptr module_name_len, uptr *pc_offset) {\n return __sanitizer::GetModuleAndOffsetForPc(pc, module_name, module_name_len,\n pc_offset);\n}\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>BUG: Now handles any number of datasets.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <array>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <map>\n#include <SDL\/SDL.h>\n#include <SDL\/SDL_image.h>\n#include <SDL\/SDL_mixer.h>\n#include <SDL\/SDL_ttf.h>\n#include \"Vipper\/Vipper.h\"\n#include \"CSDLRenderer.h\"\n\n\nnamespace RunTheWorld {\n \n Vipper::IRenderer::BitmapId CSDLRenderer::loadBitmap( std::string path ) {\n auto id = mSprites.size() + 1;\n mSprites[ id ] = IMG_Load( path.c_str() );\n return id;\n }\n \n Vipper::IRenderer::SoundId CSDLRenderer::loadSound( std::string path ) {\n auto id = mSounds.size() + 1;\n mSounds[ id ] = Mix_LoadWAV(path.c_str() );\n return id;\n }\n \n Vipper::IRenderer::FontId CSDLRenderer::loadFont( std::string path, int sizeInPt ) {\n auto id = mFonts.size() + 1;\n mFonts[ id ] = TTF_OpenFont(path.c_str(), sizeInPt );\n\n return id;\n }\n\n void CSDLRenderer::fill(float x0, float x1, float y0, float x2, float x3, float y1, int shade[3]) {\n float fromY = std::min( y0, y1 );\n float toY = std::max( y0, y1 );\n SDL_Rect rect;\n float deltaY = toY - fromY;\n\n float ratiox0x2 = 1.0f;\n float ratiox1x3 = 1.0f;\n\n if ( toY - fromY > 0.0f ) {\n ratiox0x2 = ( x0 - x2 ) \/ deltaY;\n ratiox1x3 = ( x1 - x3 ) \/ deltaY;\n }\n\n float x = x0;\n float fx = x1;\n\n for ( int line = toY; line >= fromY; line--) {\n\n rect.x = x;\n rect.y = line;\n rect.w = ( fx - x);\n rect.h = 1;\n\n x -= ratiox0x2;\n fx -= ratiox1x3;\n\n SDL_FillRect(video, &rect, SDL_MapRGB(video->format, shade[0], shade[1], shade[2] ));\n }\n }\n\n void CSDLRenderer::drawSquare( int x, int y, int x2, int y2, std::array<int,4> colour ) {\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = ( x2 - x );\n rect.h = ( y2 - y );\n int colourMerged = SDL_MapRGBA( video->format, colour[ 0 ], colour[ 1 ], colour[ 2 ], colour[ 3 ] );\n SDL_FillRect( video, &rect, colourMerged );\n };\n \n void CSDLRenderer::drawTextAt( int x, int y, std::string text, std::array<int, 4> colour, Vipper::IRenderer::FontId id ) {\n if ( id == 0 ) {\n return;\n }\n\n SDL_Color color = { (Uint8)colour[ 0 ], (Uint8)colour[ 1 ], (Uint8)colour[ 2 ], (Uint8)colour[ 3 ] };\n auto font = mFonts[ id ];\n auto result = TTF_RenderText_Solid( font, text.c_str(), color );\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = result->w;\n rect.h = result->h;\n SDL_BlitSurface( result, nullptr, video, &rect );\n SDL_FreeSurface( result );\n };\n\n void CSDLRenderer::drawBitmapAt( int x, int y, int w, int h, const IRenderer::BitmapId id ) {\n\n if ( id == 0 ) {\n return;\n }\n\n auto bitmap = mSprites[ id ];\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = w;\n rect.h = h;\n SDL_BlitSurface( bitmap, nullptr, video, &rect );\n };\n\n void CSDLRenderer::playSound( const IRenderer::SoundId& id ) {\n if ( id == 0 ) {\n return;\n }\n\n auto sound = mSounds[ id ];\n\n Mix_PlayChannel( -1, sound, 0 );\n }; \n \n CSDLRenderer::CSDLRenderer() {\n \n \/\/REFACTOR! \n SDL_Init( SDL_INIT_EVERYTHING );\n TTF_Init();\n video = SDL_SetVideoMode( 640, 480, 32, 0 );\n\n if ( Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1 ) {\n std::cout << \"coudlnt init mixer\" << std::endl;\n }\n }\n\n void CSDLRenderer::shutdown() {\n SDL_Quit();\n }\n\n void CSDLRenderer::update() {\n SDL_Event event;\n\n\n if ( SDL_PollEvent( &event ) ) {\n\n if( event.type == SDL_QUIT ) {\n exit(0);\n }\n \n if ( event.type == SDL_MOUSEBUTTONDOWN ) {\n dispatchClickToListeners( std::pair<int, int>( event.button.x, event.button.y ) );\n }\n\n if (event.type == SDL_KEYUP) {\n switch (event.key.keysym.sym) {\n case SDLK_q:\n#ifndef __EMSCRIPTEN__\n exit(0);\n#endif\n case SDLK_LEFT:\n dispatchKeyUpToListeners(Vipper::ECommand::kLeft);\n break;\n\n case SDLK_RIGHT:\n dispatchKeyUpToListeners(Vipper::ECommand::kRight);\n break;\n\n case SDLK_UP:\n dispatchKeyUpToListeners(Vipper::ECommand::kUp);\n break;\n\n case SDLK_DOWN:\n dispatchKeyUpToListeners(Vipper::ECommand::kDown);\n break;\n case SDLK_SPACE:\n dispatchKeyUpToListeners(Vipper::ECommand::kFire1);\n break;\n default:\n break;\n }\n }\n\n if (event.type == SDL_KEYDOWN) {\n switch (event.key.keysym.sym) {\n case SDLK_LEFT:\n dispatchKeyDownToListeners(Vipper::ECommand::kLeft);\n break;\n case SDLK_RIGHT:\n dispatchKeyDownToListeners(Vipper::ECommand::kRight);\n break;\n\n case SDLK_UP:\n dispatchKeyDownToListeners(Vipper::ECommand::kUp);\n break;\n\n case SDLK_DOWN:\n dispatchKeyDownToListeners(Vipper::ECommand::kDown);\n break;\n case SDLK_SPACE:\n dispatchKeyDownToListeners(Vipper::ECommand::kFire1);\n break;\n default:\n break;\n }\n }\n }\n }\n\n void CSDLRenderer::render() {\n SDL_Flip(video);\n }\n}\n<commit_msg>Free up the video surface before quitting<commit_after>#include <array>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <map>\n#include <SDL\/SDL.h>\n#include <SDL\/SDL_image.h>\n#include <SDL\/SDL_mixer.h>\n#include <SDL\/SDL_ttf.h>\n#include \"Vipper\/Vipper.h\"\n#include \"CSDLRenderer.h\"\n\n\nnamespace RunTheWorld {\n \n Vipper::IRenderer::BitmapId CSDLRenderer::loadBitmap( std::string path ) {\n auto id = mSprites.size() + 1;\n mSprites[ id ] = IMG_Load( path.c_str() );\n return id;\n }\n \n Vipper::IRenderer::SoundId CSDLRenderer::loadSound( std::string path ) {\n auto id = mSounds.size() + 1;\n mSounds[ id ] = Mix_LoadWAV(path.c_str() );\n return id;\n }\n \n Vipper::IRenderer::FontId CSDLRenderer::loadFont( std::string path, int sizeInPt ) {\n auto id = mFonts.size() + 1;\n mFonts[ id ] = TTF_OpenFont(path.c_str(), sizeInPt );\n\n return id;\n }\n\n void CSDLRenderer::fill(float x0, float x1, float y0, float x2, float x3, float y1, int shade[3]) {\n float fromY = std::min( y0, y1 );\n float toY = std::max( y0, y1 );\n SDL_Rect rect;\n float deltaY = toY - fromY;\n\n float ratiox0x2 = 1.0f;\n float ratiox1x3 = 1.0f;\n\n if ( toY - fromY > 0.0f ) {\n ratiox0x2 = ( x0 - x2 ) \/ deltaY;\n ratiox1x3 = ( x1 - x3 ) \/ deltaY;\n }\n\n float x = x0;\n float fx = x1;\n\n for ( int line = toY; line >= fromY; line--) {\n\n rect.x = x;\n rect.y = line;\n rect.w = ( fx - x);\n rect.h = 1;\n\n x -= ratiox0x2;\n fx -= ratiox1x3;\n\n SDL_FillRect(video, &rect, SDL_MapRGB(video->format, shade[0], shade[1], shade[2] ));\n }\n }\n\n void CSDLRenderer::drawSquare( int x, int y, int x2, int y2, std::array<int,4> colour ) {\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = ( x2 - x );\n rect.h = ( y2 - y );\n int colourMerged = SDL_MapRGBA( video->format, colour[ 0 ], colour[ 1 ], colour[ 2 ], colour[ 3 ] );\n SDL_FillRect( video, &rect, colourMerged );\n };\n \n void CSDLRenderer::drawTextAt( int x, int y, std::string text, std::array<int, 4> colour, Vipper::IRenderer::FontId id ) {\n if ( id == 0 ) {\n return;\n }\n\n SDL_Color color = { (Uint8)colour[ 0 ], (Uint8)colour[ 1 ], (Uint8)colour[ 2 ], (Uint8)colour[ 3 ] };\n auto font = mFonts[ id ];\n auto result = TTF_RenderText_Solid( font, text.c_str(), color );\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = result->w;\n rect.h = result->h;\n SDL_BlitSurface( result, nullptr, video, &rect );\n SDL_FreeSurface( result );\n };\n\n void CSDLRenderer::drawBitmapAt( int x, int y, int w, int h, const IRenderer::BitmapId id ) {\n\n if ( id == 0 ) {\n return;\n }\n\n auto bitmap = mSprites[ id ];\n SDL_Rect rect;\n rect.x = x;\n rect.y = y;\n rect.w = w;\n rect.h = h;\n SDL_BlitSurface( bitmap, nullptr, video, &rect );\n };\n\n void CSDLRenderer::playSound( const IRenderer::SoundId& id ) {\n if ( id == 0 ) {\n return;\n }\n\n auto sound = mSounds[ id ];\n\n Mix_PlayChannel( -1, sound, 0 );\n }; \n \n CSDLRenderer::CSDLRenderer() {\n \n \/\/REFACTOR! \n SDL_Init( SDL_INIT_EVERYTHING );\n TTF_Init();\n video = SDL_SetVideoMode( 640, 480, 32, 0 );\n\n if ( Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1 ) {\n std::cout << \"coudlnt init mixer\" << std::endl;\n }\n }\n\n void CSDLRenderer::shutdown() {\n SDL_FreeSurface(video);\n SDL_Quit();\n }\n\n void CSDLRenderer::update() {\n SDL_Event event;\n\n\n if ( SDL_PollEvent( &event ) ) {\n\n if( event.type == SDL_QUIT ) {\n exit(0);\n }\n \n if ( event.type == SDL_MOUSEBUTTONDOWN ) {\n dispatchClickToListeners( std::pair<int, int>( event.button.x, event.button.y ) );\n }\n\n if (event.type == SDL_KEYUP) {\n switch (event.key.keysym.sym) {\n case SDLK_q:\n#ifndef __EMSCRIPTEN__\n exit(0);\n#endif\n case SDLK_LEFT:\n dispatchKeyUpToListeners(Vipper::ECommand::kLeft);\n break;\n\n case SDLK_RIGHT:\n dispatchKeyUpToListeners(Vipper::ECommand::kRight);\n break;\n\n case SDLK_UP:\n dispatchKeyUpToListeners(Vipper::ECommand::kUp);\n break;\n\n case SDLK_DOWN:\n dispatchKeyUpToListeners(Vipper::ECommand::kDown);\n break;\n case SDLK_SPACE:\n dispatchKeyUpToListeners(Vipper::ECommand::kFire1);\n break;\n default:\n break;\n }\n }\n\n if (event.type == SDL_KEYDOWN) {\n switch (event.key.keysym.sym) {\n case SDLK_LEFT:\n dispatchKeyDownToListeners(Vipper::ECommand::kLeft);\n break;\n case SDLK_RIGHT:\n dispatchKeyDownToListeners(Vipper::ECommand::kRight);\n break;\n\n case SDLK_UP:\n dispatchKeyDownToListeners(Vipper::ECommand::kUp);\n break;\n\n case SDLK_DOWN:\n dispatchKeyDownToListeners(Vipper::ECommand::kDown);\n break;\n case SDLK_SPACE:\n dispatchKeyDownToListeners(Vipper::ECommand::kFire1);\n break;\n default:\n break;\n }\n }\n }\n }\n\n void CSDLRenderer::render() {\n SDL_Flip(video);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ************************************************************************************\n *\n * ftFluidFlow\n *\n * Created by Matthias Oostrik on 03\/16.14.\n * Copyright 2014 http:\/\/www.MatthiasOostrik.com All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the author nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\tThe Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones:\n *\t\t* Mark J Harris: Various online sources\n *\t\t* Patricio Gonzalez Vivo (http:\/\/www.patriciogonzalezvivo.com): ofxFluid\n * \n * ************************************************************************************ *\/\n\n#include \"ftFluidFlow.h\"\n\nnamespace flowTools {\n\t\n\tftFluidFlow::ftFluidFlow(){\n\t\tparameters.setName(\"fluid\");\n\t\tparameters.add(speed.set(\"speed\", .5, 0, 1));\n\t\tparameters.add(numJacobiIterations.set(\"iterations\", 40, 1, 100));\n\t\tparameters.add(viscosity.set(\"viscosity\", 0.0, 0, 1));\n\t\tparameters.add(vorticity.set(\"vorticity\", 0.0, 0.0, 1));\n\t\tdissipationParameters.setName(\"dissipation\");\n\t\tdissipationParameters.add(dissipationVel.set(\"velocity\",0.0015, 0, 0.01));\n\t\tdissipationParameters.add(dissipationDen.set(\"density\", 0.0015, 0, 0.01));\n\t\tdissipationParameters.add(dissipationPrs.set(\"pressure\",0.025, 0, 0.1));\n\t\tparameters.add(dissipationParameters);\n\t\tsmokeBuoyancyParameters.setName(\"smoke buoyancy\");\n\t\tsmokeBuoyancyParameters.add(smokeSigma.set(\"buoyancy\", 0.5, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(smokeWeight.set(\"weight\", 0.05, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(ambientTemperature.set(\"ambient temperature\", 0.75, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(gravity.set(\"gravity\", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1)));\n\t\tparameters.add(smokeBuoyancyParameters);\n\/\/\t\tparameters.add(wrap.set(\"wrap\", false));\n\/\/\t\twrap.addListener(this, &ftFluidFlow::wrapListener);\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {\n\t\tallocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F);\n\/\/\t\tif(wrap.get()) { advectShader = &advectWrapShader; } else { advectShader = &advectNoWrapShader; }\n\t\tadvectShader = &advectNoWrapShader;\n\t}\n\t\n\tvoid ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) {\n\t\tsimulationWidth = _simulationWidth;\n\t\tsimulationHeight = _simulationHeight;\n\t\tdensityWidth = _densityWidth;\n\t\tdensityHeight = _densityHeight;\n\t\t\n\t\tftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat);\n\t\t\n\t\tvisualizationField.setup(simulationWidth, simulationHeight);\n\t\t\n\t\ttemperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F);\n\t\tftUtil::zero(temperatureFbo);\n\t\tpressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F);\n\t\tftUtil::zero(pressureFbo);\n\t\tobstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8);\n\t\tftUtil::zero(obstacleFbo);\n\t\tobstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGBA32F);\n\t\tftUtil::zero(obstacleOffsetFbo);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tdivergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F);\n\t\tftUtil::zero(divergenceFbo);\n\t\tsmokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\tvorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(pressureFbo);\n\t\tvorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(pressureFbo);\n\t\t\n\t\tinitObstacle();\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::update(float _deltaTime){\n\t\tfloat timeStep = _deltaTime * speed.get() * simulationWidth;\n\t\t\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\n\t\tftPingPongFbo& velocityFbo = inputFbo;\n\t\tftPingPongFbo& densityFbo = outputFbo;\n\t\t\n\t\t\/\/ ADVECT\n\t\tvelocityFbo.swap();\n\t\tadvectShader->update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get());\n\t\tvelocityFbo.swap();\n\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ ADD FORCES: DIFFUSE\n\t\tif (viscosity.get() > 0.0) {\n\t\t\tfor (int i = 0; i < numJacobiIterations.get(); i++) {\n\t\t\t\tvelocityFbo.swap();\n\t\t\t\tdiffuseShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), viscosity.get());\n\t\t\t}\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\t\n\t\t\/\/ ADD FORCES: VORTEX CONFINEMENT\n\t\tif (vorticity.get() > 0.0) {\n\t\t\tvorticityVelocityShader.update(vorticityVelocityFbo.get(), velocityFbo.getTexture());\n\t\t\tvorticityVelocityFbo.swap();\n\t\t\tapplyObstacleZeroShader.update(vorticityVelocityFbo.get(), vorticityVelocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\tvorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get());\n\t\t\taddVelocity(vorticityConfinementFbo.getTexture());\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\t\n\t\t\/\/ ADD FORCES: SMOKE BUOYANCY\n\t\tif (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) {\n\t\t\ttemperatureFbo.swap();\n\t\t\tadvectShader->update(temperatureFbo.get(), temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get());\n\/\/\t\t\ttemperatureFbo.swap();\n\/\/\t\t\tclampLengthShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), 2.0, 1.0);\n\t\t\ttemperatureFbo.swap();\n\t\t\tapplyObstacleNegShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\t\tsmokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get());\n\t\t\taddVelocity(smokeBuoyancyFbo.getTexture());\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\telse {\n\t\t\tftUtil::zero(temperatureFbo);\n\t\t}\n\t\t\n\t\t\/\/ PRESSURE: DIVERGENCE\n\/\/\t\tftUtil::zero(divergenceFbo);\n\t\tdivergenceShader.update(divergenceFbo, velocityFbo.getTexture());\n\t\t\n\t\t\/\/ PRESSURE: JACOBI\n\/\/\t\tftUtil::zero(pressureFbo);\n\t\tpressureFbo.swap();\n\t\tmultiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get());\n\t\tfor (int i = 0; i < numJacobiIterations.get(); i++) {\n\t\t\tpressureFbo.swap();\n\t\t\tjacobiObstacleShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\tpressureFbo.swap();\n\t\tapplyObstaclePosShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ PRESSURE: SUBSTRACT GRADIENT\n\t\tvelocityFbo.swap();\n\t\tsubstractGradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture());\n\t\tvelocityFbo.swap();\n\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ DENSITY:\n\t\tdensityFbo.swap();\n\t\tadvectShader->update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get());\n\/\/\t\tdensityFbo.swap();\n\/\/\t\tclampLengthShader.update(densityFbo.get(), densityFbo.getBackTexture(), sqrt(3), 1.0);\n\t\tdensityFbo.swap();\n\t\tapplyObstacleDensityShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture());\n\t\t\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) {\n\t\tswitch (_type) {\n\t\t\tcase FT_VELOCITY:\t\tsetVelocity(_tex);\t\tbreak;\n\t\t\tcase FT_DENSITY:\t\tsetDensity(_tex);\t\tbreak;\n\t\t\tcase FT_TEMPERATURE:\tsetTemperature(_tex);\tbreak;\n\t\t\tcase FT_PRESSURE:\t\tsetPressure(_tex);\t\tbreak;\n\t\t\tcase FT_OBSTACLE:\t\tsetObstacle(_tex);\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tofLogWarning(\"ftFluidFlow: addFlow\") << \"no method to add flow of type \" << _type;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) {\n\t\tswitch (_type) {\n\t\t\tcase FT_VELOCITY:\t\taddVelocity(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_DENSITY:\t\taddDensity(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_TEMPERATURE:\taddTemperature(_tex, _strength);\tbreak;\n\t\t\tcase FT_PRESSURE:\t\taddPressure(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_OBSTACLE:\t\taddObstacle(_tex);\t\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tofLogWarning(\"ftFluidFlow: addFlow\") << \"no method to add flow of type \" << _type;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::initObstacle(){\n\/\/\t\tif (wrap.get()) {\n\/\/\t\t\tftUtil::zero(obstacleFbo);\n\/\/\t\t}\n\/\/\t\telse { \/\/ create edge\n\t\t\tofPushStyle();\n\t\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\t\tftUtil::one(obstacleFbo);\n\t\t\tobstacleFbo.begin();\n\t\t\tofSetColor(0,0,0,255);\n\t\t\tint borderSize = 1;\n\t\t\tofDrawRectangle(borderSize, borderSize, obstacleFbo.getWidth()-borderSize*2, obstacleFbo.getHeight()-borderSize*2);\n\t\t\tobstacleFbo.end();\n\t\t\tofPopStyle();\n\/\/\t\t}\n\t\t\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setObstacle(ofTexture & _tex){\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\tinitObstacle();\n\t\taddBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex);\n\t\tftUtil::zero(obstacleOffsetFbo);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::addObstacle(ofTexture & _tex){\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\tobstacleFbo.swap();\n\t\taddBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::reset() {\n\t\t\n\t\tftFlow::reset();\n\t\tftUtil::zero(pressureFbo);\n\t\tftUtil::zero(temperatureFbo);\n\t\tftUtil::zero(divergenceFbo);\n\t\tftUtil::zero(vorticityVelocityFbo);\n\t\tftUtil::zero(vorticityConfinementFbo);\n\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\t\n\t\tinitObstacle();\n\t\t\n\t\tjacobiObstacleShader = ftJacobiObstacleShader();\n\t}\n}\n<commit_msg>optimized obstacle<commit_after>\/* ************************************************************************************\n *\n * ftFluidFlow\n *\n * Created by Matthias Oostrik on 03\/16.14.\n * Copyright 2014 http:\/\/www.MatthiasOostrik.com All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the author nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\tThe Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones:\n *\t\t* Mark J Harris: Various online sources\n *\t\t* Patricio Gonzalez Vivo (http:\/\/www.patriciogonzalezvivo.com): ofxFluid\n * \n * ************************************************************************************ *\/\n\n#include \"ftFluidFlow.h\"\n\nnamespace flowTools {\n\t\n\tftFluidFlow::ftFluidFlow(){\n\t\tparameters.setName(\"fluid\");\n\t\tparameters.add(speed.set(\"speed\", .5, 0, 1));\n\t\tparameters.add(numJacobiIterations.set(\"iterations\", 40, 1, 100));\n\t\tparameters.add(viscosity.set(\"viscosity\", 0.0, 0, 1));\n\t\tparameters.add(vorticity.set(\"vorticity\", 0.0, 0.0, 1));\n\t\tdissipationParameters.setName(\"dissipation\");\n\t\tdissipationParameters.add(dissipationVel.set(\"velocity\",0.0015, 0, 0.01));\n\t\tdissipationParameters.add(dissipationDen.set(\"density\", 0.0015, 0, 0.01));\n\t\tdissipationParameters.add(dissipationPrs.set(\"pressure\",0.025, 0, 0.1));\n\t\tparameters.add(dissipationParameters);\n\t\tsmokeBuoyancyParameters.setName(\"smoke buoyancy\");\n\t\tsmokeBuoyancyParameters.add(smokeSigma.set(\"buoyancy\", 0.5, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(smokeWeight.set(\"weight\", 0.05, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(ambientTemperature.set(\"ambient temperature\", 0.75, 0.0, 1.0));\n\t\tsmokeBuoyancyParameters.add(gravity.set(\"gravity\", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1)));\n\t\tparameters.add(smokeBuoyancyParameters);\n\/\/\t\tparameters.add(wrap.set(\"wrap\", false));\n\/\/\t\twrap.addListener(this, &ftFluidFlow::wrapListener);\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {\n\t\tallocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F);\n\/\/\t\tif(wrap.get()) { advectShader = &advectWrapShader; } else { advectShader = &advectNoWrapShader; }\n\t\tadvectShader = &advectNoWrapShader;\n\t}\n\t\n\tvoid ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) {\n\t\tsimulationWidth = _simulationWidth;\n\t\tsimulationHeight = _simulationHeight;\n\t\tdensityWidth = _densityWidth;\n\t\tdensityHeight = _densityHeight;\n\t\t\n\t\tftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat);\n\t\t\n\t\tvisualizationField.setup(simulationWidth, simulationHeight);\n\t\t\n\t\ttemperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F);\n\t\tftUtil::zero(temperatureFbo);\n\t\tpressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F);\n\t\tftUtil::zero(pressureFbo);\n\t\tobstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8);\n\t\tftUtil::zero(obstacleFbo);\n\t\tobstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGB32F);\n\t\tftUtil::zero(obstacleOffsetFbo);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tdivergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F);\n\t\tftUtil::zero(divergenceFbo);\n\t\tsmokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\tvorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(pressureFbo);\n\t\tvorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F);\n\t\tftUtil::zero(pressureFbo);\n\t\t\n\t\tinitObstacle();\n\t\t\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::update(float _deltaTime){\n\t\tfloat timeStep = _deltaTime * speed.get() * simulationWidth;\n\t\t\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\n\t\tftPingPongFbo& velocityFbo = inputFbo;\n\t\tftPingPongFbo& densityFbo = outputFbo;\n\t\t\n\t\t\/\/ ADVECT\n\t\tvelocityFbo.swap();\n\t\tadvectShader->update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get());\n\t\tvelocityFbo.swap();\n\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ ADD FORCES: DIFFUSE\n\t\tif (viscosity.get() > 0.0) {\n\t\t\tfor (int i = 0; i < numJacobiIterations.get(); i++) {\n\t\t\t\tvelocityFbo.swap();\n\t\t\t\tdiffuseShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), viscosity.get());\n\t\t\t}\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\t\n\t\t\/\/ ADD FORCES: VORTEX CONFINEMENT\n\t\tif (vorticity.get() > 0.0) {\n\t\t\tvorticityVelocityShader.update(vorticityVelocityFbo.get(), velocityFbo.getTexture());\n\t\t\tvorticityVelocityFbo.swap();\n\t\t\tapplyObstacleZeroShader.update(vorticityVelocityFbo.get(), vorticityVelocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\tvorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get());\n\t\t\taddVelocity(vorticityConfinementFbo.getTexture());\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\t\n\t\t\/\/ ADD FORCES: SMOKE BUOYANCY\n\t\tif (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) {\n\t\t\ttemperatureFbo.swap();\n\t\t\tadvectShader->update(temperatureFbo.get(), temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get());\n\/\/\t\t\ttemperatureFbo.swap();\n\/\/\t\t\tclampLengthShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), 2.0, 1.0);\n\t\t\ttemperatureFbo.swap();\n\t\t\tapplyObstacleNegShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\t\tsmokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get());\n\t\t\taddVelocity(smokeBuoyancyFbo.getTexture());\n\t\t\tvelocityFbo.swap();\n\t\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\telse {\n\t\t\tftUtil::zero(temperatureFbo);\n\t\t}\n\t\t\n\t\t\/\/ PRESSURE: DIVERGENCE\n\/\/\t\tftUtil::zero(divergenceFbo);\n\t\tdivergenceShader.update(divergenceFbo, velocityFbo.getTexture());\n\t\t\n\t\t\/\/ PRESSURE: JACOBI\n\/\/\t\tftUtil::zero(pressureFbo);\n\t\tpressureFbo.swap();\n\t\tmultiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get());\n\t\tfor (int i = 0; i < numJacobiIterations.get(); i++) {\n\t\t\tpressureFbo.swap();\n\t\t\tjacobiObstacleShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture(), obstacleOffsetFbo.getTexture());\n\t\t}\n\t\tpressureFbo.swap();\n\t\tapplyObstaclePosShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ PRESSURE: SUBSTRACT GRADIENT\n\t\tvelocityFbo.swap();\n\t\tsubstractGradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture());\n\t\tvelocityFbo.swap();\n\t\tapplyObstacleNegShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture());\n\t\t\n\t\t\/\/ DENSITY:\n\t\tdensityFbo.swap();\n\t\tadvectShader->update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get());\n\/\/\t\tdensityFbo.swap();\n\/\/\t\tclampLengthShader.update(densityFbo.get(), densityFbo.getBackTexture(), sqrt(3), 1.0);\n\t\tdensityFbo.swap();\n\t\tapplyObstacleDensityShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture());\n\t\t\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) {\n\t\tswitch (_type) {\n\t\t\tcase FT_VELOCITY:\t\tsetVelocity(_tex);\t\tbreak;\n\t\t\tcase FT_DENSITY:\t\tsetDensity(_tex);\t\tbreak;\n\t\t\tcase FT_TEMPERATURE:\tsetTemperature(_tex);\tbreak;\n\t\t\tcase FT_PRESSURE:\t\tsetPressure(_tex);\t\tbreak;\n\t\t\tcase FT_OBSTACLE:\t\tsetObstacle(_tex);\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tofLogWarning(\"ftFluidFlow: addFlow\") << \"no method to add flow of type \" << _type;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) {\n\t\tswitch (_type) {\n\t\t\tcase FT_VELOCITY:\t\taddVelocity(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_DENSITY:\t\taddDensity(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_TEMPERATURE:\taddTemperature(_tex, _strength);\tbreak;\n\t\t\tcase FT_PRESSURE:\t\taddPressure(_tex, _strength);\t\tbreak;\n\t\t\tcase FT_OBSTACLE:\t\taddObstacle(_tex);\t\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tofLogWarning(\"ftFluidFlow: addFlow\") << \"no method to add flow of type \" << _type;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::initObstacle(){\n\/\/\t\tif (wrap.get()) {\n\/\/\t\t\tftUtil::zero(obstacleFbo);\n\/\/\t\t}\n\/\/\t\telse { \/\/ create edge\n\t\t\tofPushStyle();\n\t\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\t\tftUtil::one(obstacleFbo);\n\t\t\tobstacleFbo.begin();\n\t\t\tofSetColor(0,0,0,255);\n\t\t\tint borderSize = 1;\n\t\t\tofDrawRectangle(borderSize, borderSize, obstacleFbo.getWidth()-borderSize*2, obstacleFbo.getHeight()-borderSize*2);\n\t\t\tobstacleFbo.end();\n\t\t\tofPopStyle();\n\/\/\t\t}\n\t\t\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::setObstacle(ofTexture & _tex){\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\tinitObstacle();\n\t\taddBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex);\n\t\tftUtil::zero(obstacleOffsetFbo);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::addObstacle(ofTexture & _tex){\n\t\tofPushStyle();\n\t\tofEnableBlendMode(OF_BLENDMODE_DISABLED);\n\t\tobstacleFbo.swap();\n\t\taddBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex);\n\t\tobstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture());\n\t\tofPopStyle();\n\t}\n\t\n\t\/\/--------------------------------------------------------------\n\tvoid ftFluidFlow::reset() {\n\t\t\n\t\tftFlow::reset();\n\t\tftUtil::zero(pressureFbo);\n\t\tftUtil::zero(temperatureFbo);\n\t\tftUtil::zero(divergenceFbo);\n\t\tftUtil::zero(vorticityVelocityFbo);\n\t\tftUtil::zero(vorticityConfinementFbo);\n\t\tftUtil::zero(smokeBuoyancyFbo);\n\t\t\n\t\tinitObstacle();\n\t\t\n\t\tjacobiObstacleShader = ftJacobiObstacleShader();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n ofxTableGestures (formerly OF-TangibleFramework)\n Developed for Taller de Sistemes Interactius I\n Universitat Pompeu Fabra\n\n Copyright (c) 2011 Carles F. Julià <carles.fernandez@upf.edu>\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\n#ifndef FIGUREGRAPHIC_HPP_INCLUDED\n#define FIGUREGRAPHIC_HPP_INCLUDED\n\n#include \"ofVectorMath.h\"\n#include \"Graphic.hpp\"\n#include \"Figure.h\"\n\ninline void ofMultMatrix(ofMatrix4x4 &m) {\n float a[] = {m(0,0),m(0,1),m(0,2),m(0,3),\n m(1,0),m(1,1),m(1,2),m(1,3),\n m(2,0),m(2,1),m(2,2),m(2,3),\n m(3,0),m(3,1),m(3,2),m(3,3)};\n glMultMatrixf(a);\n}\n\nclass FigureGraphic: public Graphic\n{\n Figures::Figure * figure;\n bool testCollide;\n bool hasalpha;\n bool fill;\n bool hidden;\n public:\n ofColor color;\n ofMatrix4x4 transformation;\n FigureGraphic(Figures::Figure * f):figure(f),testCollide(true),hasalpha(false),fill(true),hidden(false){}\n ~FigureGraphic(){}\n inline bool Collide(ofPoint const & point)\n {\n return testCollide && figure->Collide(point);\n }\n void draw()\n {\n if(hidden)\n {\n ofPushMatrix();\n ofMultMatrix(transformation);\n glGetDoublev(GL_MODELVIEW_MATRIX,figure->getMatrix().data);\n ofPopMatrix();\n }\n else\n {\n ofPushStyle();\n ofPushMatrix();\n ofMultMatrix(transformation);\n if(hasalpha)\n {\n ofEnableAlphaBlending();\n ofSetColor(color.r,color.g,color.b,color.a);\n }\n else\n {\n ofSetColor(color.r,color.g,color.b);\n }\n if(fill)\n {figure->Draw();}\n else\n {figure->DrawStroke();}\n if(hasalpha)\n {\n ofDisableAlphaBlending();\n }\n ofPopMatrix();\n ofPopStyle();\n }\n }\n void canCollide(bool can){testCollide = can;}\n bool canCollide(){return testCollide;}\n void hasAlpha(bool has){hasalpha = has;}\n bool hasAlpha(){return hasalpha;}\n bool getFill(){return fill;}\n void setFill(bool Fill){fill = Fill;}\n Figures::Figure * getFigure(){return figure;}\n void setFigure(Figures::Figure * f){figure = f;}\n bool isHidden() {return hidden;}\n void isHidden(bool is){hidden = is;}\n};\n\n\n#endif \/\/ FIGUREGRAPHIC_HPP_INCLUDED\n<commit_msg>adding layer specification on figuregraphic<commit_after>\/*\n\n ofxTableGestures (formerly OF-TangibleFramework)\n Developed for Taller de Sistemes Interactius I\n Universitat Pompeu Fabra\n\n Copyright (c) 2011 Carles F. Julià <carles.fernandez@upf.edu>\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the \"Software\"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\n#ifndef FIGUREGRAPHIC_HPP_INCLUDED\n#define FIGUREGRAPHIC_HPP_INCLUDED\n\n#include \"ofVectorMath.h\"\n#include \"Graphic.hpp\"\n#include \"Figure.h\"\n\ninline void ofMultMatrix(ofMatrix4x4 &m) {\n float a[] = {m(0,0),m(0,1),m(0,2),m(0,3),\n m(1,0),m(1,1),m(1,2),m(1,3),\n m(2,0),m(2,1),m(2,2),m(2,3),\n m(3,0),m(3,1),m(3,2),m(3,3)};\n glMultMatrixf(a);\n}\n\nclass FigureGraphic: public Graphic\n{\n Figures::Figure * figure;\n bool testCollide;\n bool hasalpha;\n bool fill;\n bool hidden;\n public:\n ofColor color;\n ofMatrix4x4 transformation;\n FigureGraphic(Figures::Figure * f, int layer=APP_LAYER):Graphic(layer),figure(f),testCollide(true),hasalpha(false),fill(true),hidden(false){}\n ~FigureGraphic(){}\n inline bool Collide(ofPoint const & point)\n {\n return testCollide && figure->Collide(point);\n }\n void draw()\n {\n if(hidden)\n {\n ofPushMatrix();\n ofMultMatrix(transformation);\n glGetDoublev(GL_MODELVIEW_MATRIX,figure->getMatrix().data);\n ofPopMatrix();\n }\n else\n {\n ofPushStyle();\n ofPushMatrix();\n ofMultMatrix(transformation);\n if(hasalpha)\n {\n ofEnableAlphaBlending();\n ofSetColor(color.r,color.g,color.b,color.a);\n }\n else\n {\n ofSetColor(color.r,color.g,color.b);\n }\n if(fill)\n {figure->Draw();}\n else\n {figure->DrawStroke();}\n if(hasalpha)\n {\n ofDisableAlphaBlending();\n }\n ofPopMatrix();\n ofPopStyle();\n }\n }\n void canCollide(bool can){testCollide = can;}\n bool canCollide(){return testCollide;}\n void hasAlpha(bool has){hasalpha = has;}\n bool hasAlpha(){return hasalpha;}\n bool getFill(){return fill;}\n void setFill(bool Fill){fill = Fill;}\n Figures::Figure * getFigure(){return figure;}\n void setFigure(Figures::Figure * f){figure = f;}\n bool isHidden() {return hidden;}\n void isHidden(bool is){hidden = is;}\n};\n\n\n#endif \/\/ FIGUREGRAPHIC_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>#include <QtNetwork\/QTcpSocket>\n#include <QFileInfo>\n#include <QFile>\n#include <QStringList>\n#include <QDir>\n\n#include \"httpthread.h\"\n\nHTTPThread::HTTPThread(const int socketDescriptor, const QString &docRoot,\n QObject *parent) :\n QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot),\n responseStatusLine(\"HTTP\/1.0 %1\\r\\n\")\n{\n}\n\nvoid HTTPThread::run()\n{\n QTcpSocket socket;\n\n if(!socket.setSocketDescriptor(socketDescriptor)){\n qDebug() << \"Setting the sd has failed: \" << socket.errorString();\n emit error(socket.error());\n\n return;\n }\n\n QString request = readRequest(&socket);\n qDebug() << request;\n\n QByteArray response = processRequestData(parseHTTPRequest(request));\n\n \/\/TODO: construct the response in a nice data structure and put it toghether here\n \/\/also be good and send a Content-Length field (bytes)\n socket.write(response, response.size());\n\n if(!socket.waitForBytesWritten()){\n qDebug() << \"Could not write byts to socket: \" << socket.errorString();\n emit error(socket.error());\n }\n\n socket.close();\n}\n\nQString HTTPThread::readRequest(QTcpSocket *socket){\n QString request;\n\n \/\/TODO: what if is a POST?\n\n do{\n if(!socket->waitForReadyRead()){\n qDebug() << \"Error while waiting for client data: \"\n << socket->errorString();\n emit error(socket->error());\n\n return request;\n }\n\n request.append(QString(socket->readAll()));\n }while(-1 == request.lastIndexOf(\"\\n\\n\") &&\n -1 == request.lastIndexOf(\"\\r\\n\\r\\n\"));\n\n return request;\n}\n\nRequestData HTTPThread::parseHTTPRequest(QString request)\n{\n RequestData requestData;\n requestData.valid = false;\n\n \/\/TODO: what if I encounter \\r\\n in the URL or in the POST data?\n \/\/TODO: be tolerant and replace \"\\r\" with \"\" and then work with \"\\n\"\n QStringList parts = request.split(\"\\r\\n\\r\\n\", QString::SkipEmptyParts);\n\n if(parts.isEmpty()){\n return requestData;\n }\n\n QStringList fields = parts[0].split(\"\\r\\n\", QString::SkipEmptyParts);\n\n QStringList statusLine = fields[0].split(\" \");\n\n if(3 != statusLine.size()){\n return requestData;\n }\n\n QStringList protocol = statusLine[2].split(\"\/\");\n bool ok;\n\n if(2 != protocol.size()){\n return requestData;\n }\n\n double ver = protocol[1].toDouble(&ok);\n\n if(\"HTTP\" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){\n return requestData;\n }\n\n requestData.method = statusLine[0];\n requestData.url.setUrl(statusLine[1]);\n requestData.protocol = protocol[0];\n requestData.protocolVersion = ver;\n\n fields.removeAt(0);\n int spacePos;\n foreach(QString line, fields){\n spacePos = line.indexOf(\" \");\n\n requestData.fields.insert(line.left(spacePos-1),\n QStringList(line.right(line.size()-spacePos-1)));\n }\n\n if(requestData.fields.contains(\"Host\")){\n requestData.fields[\"Host\"] = requestData.fields[\"Host\"][0].split(\":\");\n }\n\n\n if(\"POST\" == requestData.method && 2 == parts.size() &&\n !parts[1].isEmpty()){\n requestData.postData = parsePostBody(parts[1]);\n \/\/TODO: if it's empty error out\n }\n\n qDebug() << \"Request data:\\n\\tStatusLine:\\n\\t\\tMethod: \"\n << requestData.method << \"\\n\\t\\tUrl: \"\n << requestData.url << \"\\n\\t\\tProtocol: \"\n << requestData.protocol << \"\\n\\t\\tVer: \"\n <<requestData.protocolVersion\n << \"\\n\\tFields: \" << requestData.fields\n << \"\\n\\tpost: \" << requestData.postData;\n\n requestData.valid = true;\n return requestData;\n}\n\nQHash<QString, QString> HTTPThread::parsePostBody(QString postBody)\n{\n \/\/ what if a radiobox is checked and sent?\n \/\/ what if: \"option_set\", with no \"=\" sign, is it possible?\n \/\/ what if the data contains \"&\"?\n QHash<QString, QString> retval;\n\n QStringList pairs = postBody.split(\"&\", QString::SkipEmptyParts); \/\/TODO: ???\n\n foreach(QString pair, pairs){\n QStringList keyVal = pair.split(\"=\"); \/\/TODO: ???\n retval.insert(keyVal[0], keyVal[1]); \/\/TODO: ???\n }\n\n return retval;\n}\n\nQByteArray HTTPThread::processRequestData(const RequestData &requestData)\n{\n \/\/TODO: add support for different Host values\n \/\/TODO: URL rewriting?\n\n QByteArray response = responseStatusLine.arg(\"200 OK\").toUtf8();\n\n if(!requestData.valid){\n return responseStatusLine.arg(\"400 Bad request\\r\\n\").toAscii();\n }\n\n if(\"GET\" == requestData.method || \"POST\" == requestData.method){\n \/\/serve static files\n\n QString fullPath = docRoot + requestData.url.path();\n QFileInfo f(fullPath);\n\n qDebug() << requestData.method << \" \" << fullPath;\n\n if(f.exists() && f.isReadable()){\n if(f.isDir()){\n response = serveStaticDir(response, f.absoluteFilePath());\n }\n else{\n response = serveStaticFile(response, f.absoluteFilePath());\n\n if(response.isEmpty()){\n response = responseStatusLine.arg(\n \"500 Internal Server Error\\r\\n\").toAscii();\n }\n }\n }\n\n \/* TODO: load HTTPSCripts via HTTPScriptLoader (.so and .dll files) ?\n * -> evolve this into FastCGI? read more\n *\n * or at least create a mapping of path -> method\n *\n *What's below isn't good because I have to modify the daemon every\n *time I want new functionality and the \"login\", \"check\", etc. methods are not a semantic part of HTTPThread\n *\/\n else if(\"\/patrat\" == requestData.url.path()){\n response = square(response, requestData);\n }\n else if(\"\/login\" == requestData.url.path()){\n response = login(response, requestData);\n }\n else if(\"\/verifica\" == requestData.url.path()){\n response = check(response, requestData);\n }\n else if(!f.exists()){\n response = responseStatusLine.arg(\"404 Not Found\\r\\n\").toAscii();\n }\n else if(!f.isReadable()){\n qDebug() << \"Not readable!\";\n response = responseStatusLine.arg(\"403 Forbidden\\r\\n\").toAscii() +\n \"Permission denied\\n\";\n }\n }\n else{\n response = responseStatusLine.arg(\"501 Not Implemented\\r\\n\").toAscii();\n qDebug() << \"Unsupported HTTP method!\";\n }\n\n return response;\n return responseStatusLine.arg(\"200 OK\\r\\n\").toAscii();\n}\n\nQByteArray HTTPThread::serveStaticFile(const QByteArray &partialResponse,\n const QString &filePath)\n{\n \/\/TODO: set the mime type\n QFile file(filePath);\n\n if(!file.open( QIODevice::ReadOnly)){\n qDebug() << \"Cannot open\";\n return \"\";\n }\n\n return partialResponse + \"\\r\\n\" + file.readAll();\n}\n\nQByteArray HTTPThread::serveStaticDir(const QByteArray &partialResponse,\n const QString &dirPath)\n{\n QDir dir(dirPath);\n QStringList dirList = dir.entryList();\n\n if(dirList.isEmpty()){\n return responseStatusLine.arg(\"404 Not Found\\r\\n\").toAscii();\n }\n\n \/\/TODO: format as HTML\n return partialResponse + \"Content-Type: text\/plain\\r\\n\\r\\n\" +\n dirList.join(\"\\n\").toUtf8();\n}\n\nQByteArray HTTPThread::square(const QByteArray &partialResponse,\n const RequestData &requestData)\n{\n if(\"GET\" != requestData.method || !requestData.url.hasQueryItem(\"a\")){\n return responseStatusLine.arg(\"400 Bad Request\\r\\n\").toAscii();\n }\n\n QString numToSquare = requestData.url.queryItemValue(\"a\");\n QString body;\n\n bool ok;\n double n = numToSquare.toDouble(&ok);\n\n if(!ok){\n body = \"a-ul trebuie sa fie numar!\\n\";\n }\n else{\n body = numToSquare + \"^2 = \" + QString::number(n*n) + \"\\n\";\n }\n\n return partialResponse + \"\\r\\n\" + body.toAscii();\n}\n\nQByteArray HTTPThread::login(const QByteArray &partialResponse,\n const RequestData &requestData)\n{\n return partialResponse + \"\\r\\n<html><body>\"\n \"<form method=\\\"POST\\\">\"\n \"Username: <input type=\\\"text\\\" name=\\\"username\\\">\"\n \"Password: <input type=\\\"password\\\" name=\\\"pass\\\">\"\n \"<INPUT type=\\\"submit\\\" value=\\\"Auth\\\">\"\n \"<\/form><\/body><\/html>\";\n}\n\nQByteArray HTTPThread::check(const QByteArray &partialResponse,\n const QHash<QString, QStringList> &requestData)\n{\n return partialResponse + \"\\r\\n\";\n}\n<commit_msg>finished the test methods HTTPThread::login() and HTTPThread::check()<commit_after>#include <QtNetwork\/QTcpSocket>\n#include <QFileInfo>\n#include <QFile>\n#include <QStringList>\n#include <QDir>\n\n#include \"httpthread.h\"\n\nHTTPThread::HTTPThread(const int socketDescriptor, const QString &docRoot,\n QObject *parent) :\n QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot),\n responseStatusLine(\"HTTP\/1.0 %1\\r\\n\")\n{\n}\n\nvoid HTTPThread::run()\n{\n QTcpSocket socket;\n\n if(!socket.setSocketDescriptor(socketDescriptor)){\n qDebug() << \"Setting the sd has failed: \" << socket.errorString();\n emit error(socket.error());\n\n return;\n }\n\n QString request = readRequest(&socket);\n qDebug() << request;\n\n QByteArray response = processRequestData(parseHTTPRequest(request));\n\n \/\/TODO: construct the response in a nice data structure and put it toghether here\n \/\/also be good and send a Content-Length field (bytes)\n socket.write(response, response.size());\n\n if(!socket.waitForBytesWritten()){\n qDebug() << \"Could not write byts to socket: \" << socket.errorString();\n emit error(socket.error());\n }\n\n socket.close();\n}\n\nQString HTTPThread::readRequest(QTcpSocket *socket){\n QString request;\n\n \/\/TODO: what if is a POST?\n\n do{\n if(!socket->waitForReadyRead()){\n qDebug() << \"Error while waiting for client data: \"\n << socket->errorString();\n emit error(socket->error());\n\n return request;\n }\n\n request.append(QString(socket->readAll()));\n }while(-1 == request.lastIndexOf(\"\\n\\n\") &&\n -1 == request.lastIndexOf(\"\\r\\n\\r\\n\"));\n\n return request;\n}\n\nRequestData HTTPThread::parseHTTPRequest(QString request)\n{\n RequestData requestData;\n requestData.valid = false;\n\n \/\/TODO: what if I encounter \\r\\n in the URL or in the POST data?\n \/\/TODO: be tolerant and replace \"\\r\" with \"\" and then work with \"\\n\"\n QStringList parts = request.split(\"\\r\\n\\r\\n\", QString::SkipEmptyParts);\n\n if(parts.isEmpty()){\n return requestData;\n }\n\n QStringList fields = parts[0].split(\"\\r\\n\", QString::SkipEmptyParts);\n\n QStringList statusLine = fields[0].split(\" \");\n\n if(3 != statusLine.size()){\n return requestData;\n }\n\n QStringList protocol = statusLine[2].split(\"\/\");\n bool ok;\n\n if(2 != protocol.size()){\n return requestData;\n }\n\n double ver = protocol[1].toDouble(&ok);\n\n if(\"HTTP\" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){\n return requestData;\n }\n\n requestData.method = statusLine[0];\n requestData.url.setUrl(statusLine[1]);\n requestData.protocol = protocol[0];\n requestData.protocolVersion = ver;\n\n fields.removeAt(0);\n int spacePos;\n foreach(QString line, fields){\n spacePos = line.indexOf(\" \");\n\n requestData.fields.insert(line.left(spacePos-1),\n QStringList(line.right(line.size()-spacePos-1)));\n }\n\n if(requestData.fields.contains(\"Host\")){\n requestData.fields[\"Host\"] = requestData.fields[\"Host\"][0].split(\":\");\n }\n\n\n if(\"POST\" == requestData.method && 2 == parts.size() &&\n !parts[1].isEmpty()){\n requestData.postData = parsePostBody(parts[1]);\n \/\/TODO: if it's empty error out\n }\n\n qDebug() << \"Request data:\\n\\tStatusLine:\\n\\t\\tMethod: \"\n << requestData.method << \"\\n\\t\\tUrl: \"\n << requestData.url << \"\\n\\t\\tProtocol: \"\n << requestData.protocol << \"\\n\\t\\tVer: \"\n <<requestData.protocolVersion\n << \"\\n\\tFields: \" << requestData.fields\n << \"\\n\\tpost: \" << requestData.postData;\n\n requestData.valid = true;\n return requestData;\n}\n\nQHash<QString, QString> HTTPThread::parsePostBody(QString postBody)\n{\n \/\/ what if a radiobox is checked and sent?\n \/\/ what if: \"option_set\", with no \"=\" sign, is it possible?\n \/\/ what if the data contains \"&\"?\n QHash<QString, QString> retval;\n\n QStringList pairs = postBody.split(\"&\", QString::SkipEmptyParts); \/\/TODO: ???\n\n foreach(QString pair, pairs){\n QStringList keyVal = pair.split(\"=\"); \/\/TODO: ???\n retval.insert(keyVal[0], keyVal[1]); \/\/TODO: ???\n }\n\n return retval;\n}\n\nQByteArray HTTPThread::processRequestData(const RequestData &requestData)\n{\n \/\/TODO: add support for different Host values\n \/\/TODO: URL rewriting?\n\n QByteArray response = responseStatusLine.arg(\"200 OK\").toUtf8();\n\n if(!requestData.valid){\n return responseStatusLine.arg(\"400 Bad request\\r\\n\").toAscii();\n }\n\n if(\"GET\" == requestData.method || \"POST\" == requestData.method){\n \/\/serve static files\n\n QString fullPath = docRoot + requestData.url.path();\n QFileInfo f(fullPath);\n\n qDebug() << requestData.method << \" \" << fullPath;\n\n if(f.exists() && f.isReadable()){\n if(f.isDir()){\n response = serveStaticDir(response, f.absoluteFilePath());\n }\n else{\n response = serveStaticFile(response, f.absoluteFilePath());\n\n if(response.isEmpty()){\n response = responseStatusLine.arg(\n \"500 Internal Server Error\\r\\n\").toAscii();\n }\n }\n }\n\n \/* TODO: load HTTPSCripts via HTTPScriptLoader (.so and .dll files) ?\n * -> evolve this into FastCGI? read more\n *\n * or at least create a mapping of path -> method\n *\n *What's below isn't good because I have to modify the daemon every\n *time I want new functionality and the \"login\", \"check\", etc. methods are not a semantic part of HTTPThread\n *\/\n else if(\"\/patrat\" == requestData.url.path()){\n response = square(response, requestData);\n }\n else if(\"\/login\" == requestData.url.path()){\n response = login(response, requestData);\n }\n else if(\"\/verifica\" == requestData.url.path()){\n response = check(response, requestData);\n }\n else if(!f.exists()){\n response = responseStatusLine.arg(\"404 Not Found\\r\\n\").toAscii();\n }\n else if(!f.isReadable()){\n qDebug() << \"Not readable!\";\n response = responseStatusLine.arg(\"403 Forbidden\\r\\n\").toAscii() +\n \"Permission denied\\n\";\n }\n }\n else{\n response = responseStatusLine.arg(\"501 Not Implemented\\r\\n\").toAscii();\n qDebug() << \"Unsupported HTTP method!\";\n }\n\n return response;\n return responseStatusLine.arg(\"200 OK\\r\\n\").toAscii();\n}\n\nQByteArray HTTPThread::serveStaticFile(const QByteArray &partialResponse,\n const QString &filePath)\n{\n \/\/TODO: set the mime type\n QFile file(filePath);\n\n if(!file.open( QIODevice::ReadOnly)){\n qDebug() << \"Cannot open\";\n return \"\";\n }\n\n return partialResponse + \"\\r\\n\" + file.readAll();\n}\n\nQByteArray HTTPThread::serveStaticDir(const QByteArray &partialResponse,\n const QString &dirPath)\n{\n QDir dir(dirPath);\n QStringList dirList = dir.entryList();\n\n if(dirList.isEmpty()){\n return responseStatusLine.arg(\"404 Not Found\\r\\n\").toAscii();\n }\n\n \/\/TODO: format as HTML\n return partialResponse + \"Content-Type: text\/plain\\r\\n\\r\\n\" +\n dirList.join(\"\\n\").toUtf8();\n}\n\nQByteArray HTTPThread::square(const QByteArray &partialResponse,\n const RequestData &requestData)\n{\n if(\"GET\" != requestData.method || !requestData.url.hasQueryItem(\"a\")){\n return responseStatusLine.arg(\"400 Bad Request\\r\\n\").toAscii();\n }\n\n QString numToSquare = requestData.url.queryItemValue(\"a\");\n QString body;\n\n bool ok;\n double n = numToSquare.toDouble(&ok);\n\n if(!ok){\n body = \"a-ul trebuie sa fie numar!\\n\";\n }\n else{\n body = numToSquare + \"^2 = \" + QString::number(n*n) + \"\\n\";\n }\n\n return partialResponse + \"\\r\\n\" + body.toAscii();\n}\n\nQByteArray HTTPThread::login(const QByteArray &partialResponse,\n const RequestData &requestData)\n{\n QString page = \"\\r\\n<html><body>\"\n \"<form method=\\\"POST\\\">\"\n \"%1\"\n \"Username: <input type=\\\"text\\\" name=\\\"username\\\">\"\n \"Password: <input type=\\\"password\\\" name=\\\"pass\\\">\"\n \"<INPUT type=\\\"submit\\\" value=\\\"Auth\\\">\"\n \"<\/form><\/body><\/html>\";\n\n if(\"GET\" == requestData.method){\n return partialResponse + page.arg(\"\").toAscii();\n }\n\n if(\"POST\" == requestData.method && !requestData.postData.isEmpty()){\n if(requestData.postData.contains(\"username\") &&\n \"Ion\" == requestData.postData[\"username\"] &&\n requestData.postData.contains(\"pass\") &&\n \"1234\" == requestData.postData[\"pass\"]){\n\n return partialResponse + \"Set-Cookie: loggedin=1\\r\\n\\r\\nYou're logged in!\";\n }\n\n return partialResponse +\n page.arg(\"Login failed, try again!<br>\").toAscii();\n }\n\n return responseStatusLine.arg(\"400 Bad request\\r\\n\").toAscii();\n}\n\nQByteArray HTTPThread::check(const QByteArray &partialResponse,\n const RequestData &requestData)\n{\n if(\"GET\" != requestData.method){\n return responseStatusLine.arg(\"400 Bad request\\r\\n\").toAscii();\n }\n\n if(requestData.fields.contains(\"Cookie\") &&\n \"loggedin=1\" == requestData.fields[\"Cookie\"][0]){\n\n return partialResponse + \"\\r\\nYou're logged in!\";\n }\n\n return partialResponse + \"\\r\\nYou're not logged in!\";;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/base\/assert.hpp\"\n#include \"..\/base\/base.hpp\"\n#include \"..\/base\/math.hpp\"\n#include \"..\/base\/stl_add.hpp\"\n\n#include \"..\/std\/iterator.hpp\"\n\n\ntemplate <typename IsVisibleF>\nbool FindSingleStripForIndex(size_t i, size_t n, IsVisibleF isVisible)\n{\n \/\/ Searching for a strip only in a single direction, because the opposite direction\n \/\/ is traversed from the last vertex of the possible strip.\n size_t a = my::PrevModN(i, n);\n size_t b = my::NextModN(i, n);\n for (size_t j = 2; j < n; ++j)\n {\n ASSERT_NOT_EQUAL ( a, b, () );\n if (!isVisible(a, b))\n return false;\n if (j & 1)\n a = my::PrevModN(a, n);\n else\n b = my::NextModN(b, n);\n }\n\n ASSERT_EQUAL ( a, b, () );\n return true;\n}\n\n\/\/ If polygon with n vertices is a single strip, return the start index of the strip or n otherwise.\ntemplate <typename IsVisibleF>\nsize_t FindSingleStrip(size_t n, IsVisibleF isVisible)\n{\n for (size_t i = 0; i < n; ++i)\n {\n if (FindSingleStripForIndex(i, n, isVisible))\n return i;\n }\n\n return n;\n}\n\n#ifdef DEBUG\ntemplate <typename IterT> bool TestPolygonPreconditions(IterT beg, IterT end)\n{\n ASSERT_GREATER ( distance(beg, end), 2, () );\n ASSERT ( !AlmostEqual(*beg, *(--end)), () );\n return true;\n}\n#endif\n\n\/\/\/ Is polygon [beg, end) has CCW orientation.\ntemplate <typename IterT> bool IsPolygonCCW(IterT beg, IterT end)\n{\n ASSERT ( TestPolygonPreconditions(beg, end), () );\n\n \/\/ find the most down (left) point\n double minY = numeric_limits<double>::max();\n IterT iRes;\n for (IterT i = beg; i != end; ++i)\n {\n if ((*i).y < minY || ((*i).y == minY && (*i).x < (*iRes).x))\n {\n iRes = i;\n minY = (*i).y;\n }\n }\n\n double cp = CrossProduct(*iRes - *PrevIterInCycle(iRes, beg, end),\n *NextIterInCycle(iRes, beg, end) - *iRes);\n if (cp != 0.0)\n return (cp > 0.0);\n\n \/\/ fid the most up (left) point\n double maxY = numeric_limits<double>::min();\n for (IterT i = beg; i != end; ++i)\n {\n if ((*i).y > maxY || ((*i).y == maxY && (*i).x < (*iRes).x))\n {\n iRes = i;\n maxY = (*i).y;\n }\n }\n\n cp = CrossProduct(*iRes - *PrevIterInCycle(iRes, beg, end),\n *NextIterInCycle(iRes, beg, end) - *iRes);\n ASSERT_NOT_EQUAL ( cp, 0.0, () );\n return (cp > 0.0);\n}\n\n\/\/\/ Is segment (v, v1) in cone (vPrev, v, vNext)?\n\/\/\/ @precondition Orientation CCW!!!\ntemplate <typename PointT> bool IsSegmentInCone(PointT v, PointT v1, PointT vPrev, PointT vNext)\n{\n PointT const diff = v1 - v;\n PointT const edgeL = vPrev - v;\n PointT const edgeR = vNext - v;\n double const cpLR = CrossProduct(edgeR, edgeL);\n\n if (my::AlmostEqual(cpLR, 0.0))\n {\n \/\/ Points vPrev, v, vNext placed on one line;\n \/\/ use property that polygon has CCW orientation.\n return CrossProduct(vNext - vPrev, v1 - vPrev) > 0.0;\n }\n\n if (cpLR > 0)\n {\n \/\/ vertex is convex\n return CrossProduct(diff, edgeR) < 0 && CrossProduct(diff, edgeL) > 0.0;\n }\n else\n {\n \/\/ vertex is reflex\n return CrossProduct(diff, edgeR) < 0 || CrossProduct(diff, edgeL) > 0.0;\n }\n}\n\n\/\/\/ Is diagonal (i0, i1) visible in polygon [beg, end).\n\/\/\/ @precondition Orientation CCW!!\ntemplate <typename IterT>\nbool IsDiagonalVisible(IterT beg, IterT end, IterT i0, IterT i1)\n{\n ASSERT ( IsPolygonCCW(beg, end), () );\n ASSERT ( TestPolygonPreconditions(beg, end), () );\n ASSERT ( i0 != i1, () );\n\n IterT const prev = PrevIterInCycle(i0, beg, end);\n IterT const next = NextIterInCycle(i0, beg, end);\n if (prev == i1 || next == i1)\n return true;\n\n if (!IsSegmentInCone(*i0, *i1, *prev, *next))\n return false;\n\n for (IterT j0 = beg, j1 = PrevIterInCycle(beg, beg, end); j0 != end; j1 = j0++)\n if (j0 != i0 && j0 != i1 && j1 != i0 && j1 != i1 && SegmentsIntersect(*i0, *i1, *j0, *j1))\n return false;\n\n return true;\n}\n\ntemplate <typename IterT> class IsDiagonalVisibleFunctor\n{\n IterT m_Beg, m_End;\npublic:\n IsDiagonalVisibleFunctor(IterT beg, IterT end) : m_Beg(beg), m_End(end) {}\n\n bool operator () (size_t a, size_t b) const\n {\n return IsDiagonalVisible(m_Beg, m_End, m_Beg + a, m_Beg + b);\n }\n};\n\nnamespace detail\n{\n template <typename F> class StripEmitter\n {\n F & m_f;\n int m_order;\n\n public:\n StripEmitter(F & f) : m_f(f), m_order(0) {}\n\n bool operator () (size_t a, size_t b)\n {\n if (m_order == 0)\n {\n m_f(b);\n m_f(a);\n m_order = 1;\n }\n else\n {\n m_f(m_order == 1 ? b : a);\n m_order = -m_order;\n }\n return true;\n }\n };\n}\n\n\/\/\/ Make single strip for the range of points [beg, end), started with index = i.\ntemplate <typename F> \nvoid MakeSingleStripFromIndex(size_t i, size_t n, F f)\n{\n ASSERT_LESS ( i, n, () );\n f(i);\n FindSingleStripForIndex(i, n, detail::StripEmitter<F>(f));\n}\n<commit_msg>Add extended assert in IsPolygonCCW.<commit_after>#pragma once\n\n#include \"..\/base\/assert.hpp\"\n#include \"..\/base\/base.hpp\"\n#include \"..\/base\/math.hpp\"\n#include \"..\/base\/stl_add.hpp\"\n\n#include \"..\/std\/iterator.hpp\"\n\n\ntemplate <typename IsVisibleF>\nbool FindSingleStripForIndex(size_t i, size_t n, IsVisibleF isVisible)\n{\n \/\/ Searching for a strip only in a single direction, because the opposite direction\n \/\/ is traversed from the last vertex of the possible strip.\n size_t a = my::PrevModN(i, n);\n size_t b = my::NextModN(i, n);\n for (size_t j = 2; j < n; ++j)\n {\n ASSERT_NOT_EQUAL ( a, b, () );\n if (!isVisible(a, b))\n return false;\n if (j & 1)\n a = my::PrevModN(a, n);\n else\n b = my::NextModN(b, n);\n }\n\n ASSERT_EQUAL ( a, b, () );\n return true;\n}\n\n\/\/ If polygon with n vertices is a single strip, return the start index of the strip or n otherwise.\ntemplate <typename IsVisibleF>\nsize_t FindSingleStrip(size_t n, IsVisibleF isVisible)\n{\n for (size_t i = 0; i < n; ++i)\n {\n if (FindSingleStripForIndex(i, n, isVisible))\n return i;\n }\n\n return n;\n}\n\n#ifdef DEBUG\ntemplate <typename IterT> bool TestPolygonPreconditions(IterT beg, IterT end)\n{\n ASSERT_GREATER ( distance(beg, end), 2, () );\n ASSERT ( !AlmostEqual(*beg, *(--end)), () );\n return true;\n}\n#endif\n\n\/\/\/ Is polygon [beg, end) has CCW orientation.\ntemplate <typename IterT> bool IsPolygonCCW(IterT beg, IterT end)\n{\n ASSERT ( TestPolygonPreconditions(beg, end), () );\n\n \/\/ find the most down (left) point\n double minY = numeric_limits<double>::max();\n IterT iRes;\n for (IterT i = beg; i != end; ++i)\n {\n if ((*i).y < minY || ((*i).y == minY && (*i).x < (*iRes).x))\n {\n iRes = i;\n minY = (*i).y;\n }\n }\n\n double cp = CrossProduct(*iRes - *PrevIterInCycle(iRes, beg, end),\n *NextIterInCycle(iRes, beg, end) - *iRes);\n if (cp != 0.0)\n return (cp > 0.0);\n\n \/\/ find the most up (left) point\n double maxY = numeric_limits<double>::min();\n for (IterT i = beg; i != end; ++i)\n {\n if ((*i).y > maxY || ((*i).y == maxY && (*i).x < (*iRes).x))\n {\n iRes = i;\n maxY = (*i).y;\n }\n }\n\n IterT iPrev = PrevIterInCycle(iRes, beg, end);\n IterT iNext = NextIterInCycle(iRes, beg, end);\n cp = CrossProduct(*iRes - *iPrev, *iNext - *iRes);\n\n ASSERT_NOT_EQUAL ( cp, 0.0, (*iPrev, *iRes, *iNext) );\n return (cp > 0.0);\n}\n\n\/\/\/ Is segment (v, v1) in cone (vPrev, v, vNext)?\n\/\/\/ @precondition Orientation CCW!!!\ntemplate <typename PointT> bool IsSegmentInCone(PointT v, PointT v1, PointT vPrev, PointT vNext)\n{\n PointT const diff = v1 - v;\n PointT const edgeL = vPrev - v;\n PointT const edgeR = vNext - v;\n double const cpLR = CrossProduct(edgeR, edgeL);\n\n if (my::AlmostEqual(cpLR, 0.0))\n {\n \/\/ Points vPrev, v, vNext placed on one line;\n \/\/ use property that polygon has CCW orientation.\n return CrossProduct(vNext - vPrev, v1 - vPrev) > 0.0;\n }\n\n if (cpLR > 0)\n {\n \/\/ vertex is convex\n return CrossProduct(diff, edgeR) < 0 && CrossProduct(diff, edgeL) > 0.0;\n }\n else\n {\n \/\/ vertex is reflex\n return CrossProduct(diff, edgeR) < 0 || CrossProduct(diff, edgeL) > 0.0;\n }\n}\n\n\/\/\/ Is diagonal (i0, i1) visible in polygon [beg, end).\n\/\/\/ @precondition Orientation CCW!!\ntemplate <typename IterT>\nbool IsDiagonalVisible(IterT beg, IterT end, IterT i0, IterT i1)\n{\n ASSERT ( IsPolygonCCW(beg, end), () );\n ASSERT ( TestPolygonPreconditions(beg, end), () );\n ASSERT ( i0 != i1, () );\n\n IterT const prev = PrevIterInCycle(i0, beg, end);\n IterT const next = NextIterInCycle(i0, beg, end);\n if (prev == i1 || next == i1)\n return true;\n\n if (!IsSegmentInCone(*i0, *i1, *prev, *next))\n return false;\n\n for (IterT j0 = beg, j1 = PrevIterInCycle(beg, beg, end); j0 != end; j1 = j0++)\n if (j0 != i0 && j0 != i1 && j1 != i0 && j1 != i1 && SegmentsIntersect(*i0, *i1, *j0, *j1))\n return false;\n\n return true;\n}\n\ntemplate <typename IterT> class IsDiagonalVisibleFunctor\n{\n IterT m_Beg, m_End;\npublic:\n IsDiagonalVisibleFunctor(IterT beg, IterT end) : m_Beg(beg), m_End(end) {}\n\n bool operator () (size_t a, size_t b) const\n {\n return IsDiagonalVisible(m_Beg, m_End, m_Beg + a, m_Beg + b);\n }\n};\n\nnamespace detail\n{\n template <typename F> class StripEmitter\n {\n F & m_f;\n int m_order;\n\n public:\n StripEmitter(F & f) : m_f(f), m_order(0) {}\n\n bool operator () (size_t a, size_t b)\n {\n if (m_order == 0)\n {\n m_f(b);\n m_f(a);\n m_order = 1;\n }\n else\n {\n m_f(m_order == 1 ? b : a);\n m_order = -m_order;\n }\n return true;\n }\n };\n}\n\n\/\/\/ Make single strip for the range of points [beg, end), started with index = i.\ntemplate <typename F> \nvoid MakeSingleStripFromIndex(size_t i, size_t n, F f)\n{\n ASSERT_LESS ( i, n, () );\n f(i);\n FindSingleStripForIndex(i, n, detail::StripEmitter<F>(f));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/scoped_ptr.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/mock_ffmpeg.h\"\n#include \"media\/base\/mock_task.h\"\n#include \"media\/filters\/ffmpeg_video_decode_engine.h\"\n#include \"media\/filters\/ffmpeg_video_decoder.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::testing::_;\nusing ::testing::DoAll;\nusing ::testing::Return;\nusing ::testing::ReturnNull;\nusing ::testing::SetArgumentPointee;\nusing ::testing::StrictMock;\n\nnamespace media {\n\nstatic const int kWidth = 320;\nstatic const int kHeight = 240;\nstatic const AVRational kTimeBase = { 1, 100 };\n\nACTION_P(SaveInitializeResult, engine) {\n engine->info_ = arg0;\n}\n\nclass FFmpegVideoDecodeEngineTest : public testing::Test,\n public VideoDecodeEngine::EventHandler {\n protected:\n FFmpegVideoDecodeEngineTest() {\n \/\/ Setup FFmpeg structures.\n frame_buffer_.reset(new uint8[kWidth * kHeight]);\n memset(&yuv_frame_, 0, sizeof(yuv_frame_));\n\n \/\/ DecodeFrame will check these pointers as non-NULL value.\n yuv_frame_.data[0] = yuv_frame_.data[1] = yuv_frame_.data[2]\n = frame_buffer_.get();\n yuv_frame_.linesize[0] = kWidth;\n yuv_frame_.linesize[1] = yuv_frame_.linesize[2] = kWidth >> 1;\n\n memset(&codec_context_, 0, sizeof(codec_context_));\n codec_context_.width = kWidth;\n codec_context_.height = kHeight;\n codec_context_.time_base = kTimeBase;\n\n memset(&codec_, 0, sizeof(codec_));\n memset(&stream_, 0, sizeof(stream_));\n stream_.codec = &codec_context_;\n stream_.r_frame_rate.num = kTimeBase.den;\n stream_.r_frame_rate.den = kTimeBase.num;\n\n buffer_ = new DataBuffer(1);\n\n \/\/ Initialize MockFFmpeg.\n MockFFmpeg::set(&mock_ffmpeg_);\n\n test_engine_ = new FFmpegVideoDecodeEngine();\n test_engine_->SetCodecContextForTest(&codec_context_);\n\n VideoFrame::CreateFrame(VideoFrame::YV12,\n kWidth,\n kHeight,\n StreamSample::kInvalidTimestamp,\n StreamSample::kInvalidTimestamp,\n &video_frame_);\n }\n\n ~FFmpegVideoDecodeEngineTest() {\n test_engine_ = NULL;\n MockFFmpeg::set(NULL);\n }\n\n void Initialize() {\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_TRUE(info_.success_);\n }\n\n public:\n MOCK_METHOD1(OnFillBufferCallback,\n void(scoped_refptr<VideoFrame> video_frame));\n MOCK_METHOD1(OnEmptyBufferCallback,\n void(scoped_refptr<Buffer> buffer));\n MOCK_METHOD1(OnInitializeComplete,\n void(const VideoCodecInfo& info));\n MOCK_METHOD0(OnUninitializeComplete, void());\n MOCK_METHOD0(OnFlushComplete, void());\n MOCK_METHOD0(OnSeekComplete, void());\n MOCK_METHOD0(OnError, void());\n MOCK_METHOD1(OnFormatChange, void(VideoStreamInfo stream_info));\n\n scoped_refptr<VideoFrame> video_frame_;\n VideoCodecConfig config_;\n VideoCodecInfo info_;\n protected:\n scoped_refptr<FFmpegVideoDecodeEngine> test_engine_;\n scoped_array<uint8_t> frame_buffer_;\n StrictMock<MockFFmpeg> mock_ffmpeg_;\n\n AVFrame yuv_frame_;\n AVCodecContext codec_context_;\n AVStream stream_;\n AVCodec codec_;\n scoped_refptr<DataBuffer> buffer_;\n\n};\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_Normal) {\n Initialize();\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_FindDecoderFails) {\n \/\/ Test avcodec_find_decoder() returning NULL.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(ReturnNull());\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_InitThreadFails) {\n \/\/ Test avcodec_thread_init() failing.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(-1));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_OpenDecoderFails) {\n \/\/ Test avcodec_open() failing.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))\n .WillOnce(Return(-1));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\nACTION_P2(DemuxComplete, engine, buffer) {\n engine->EmptyThisBuffer(buffer);\n}\n\nACTION_P(DecodeComplete, decoder) {\n decoder->video_frame_ = arg0;\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_Normal) {\n Initialize();\n\n \/\/ We rely on FFmpeg for timestamp and duration reporting. The one tricky\n \/\/ bit is calculating the duration when |repeat_pict| > 0.\n const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(123);\n const base::TimeDelta kDuration = base::TimeDelta::FromMicroseconds(15000);\n yuv_frame_.repeat_pict = 1;\n yuv_frame_.reordered_opaque = kTimestamp.InMicroseconds();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(1), \/\/ Simulate 1 byte frame.\n Return(0)));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n \/\/ |video_frame_| timestamp is 0 because we set the timestamp based off\n \/\/ the buffer timestamp.\n EXPECT_EQ(0, video_frame_->GetTimestamp().ToInternalValue());\n EXPECT_EQ(kDuration.ToInternalValue(),\n video_frame_->GetDuration().ToInternalValue());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_0ByteFrame) {\n Initialize();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_))\n .Times(2);\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(0), \/\/ Simulate 0 byte frame.\n Return(0)))\n .WillOnce(DoAll(SetArgumentPointee<2>(1), \/\/ Simulate 1 byte frame.\n Return(0)));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n EXPECT_TRUE(video_frame_.get());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_DecodeError) {\n Initialize();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(Return(-1));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n EXPECT_FALSE(video_frame_.get());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, GetSurfaceFormat) {\n \/\/ YV12 formats.\n codec_context_.pix_fmt = PIX_FMT_YUV420P;\n EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());\n codec_context_.pix_fmt = PIX_FMT_YUVJ420P;\n EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());\n\n \/\/ YV16 formats.\n codec_context_.pix_fmt = PIX_FMT_YUV422P;\n EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());\n codec_context_.pix_fmt = PIX_FMT_YUVJ422P;\n EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());\n\n \/\/ Invalid value.\n codec_context_.pix_fmt = PIX_FMT_NONE;\n EXPECT_EQ(VideoFrame::INVALID, test_engine_->GetSurfaceFormat());\n}\n\n} \/\/ namespace media\n<commit_msg>there are 2 threads for AVCodecThreadInit BUG=NONE TEST=NONE<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/scoped_ptr.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"media\/base\/mock_ffmpeg.h\"\n#include \"media\/base\/mock_task.h\"\n#include \"media\/filters\/ffmpeg_video_decode_engine.h\"\n#include \"media\/filters\/ffmpeg_video_decoder.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::testing::_;\nusing ::testing::DoAll;\nusing ::testing::Return;\nusing ::testing::ReturnNull;\nusing ::testing::SetArgumentPointee;\nusing ::testing::StrictMock;\n\nnamespace media {\n\nstatic const int kWidth = 320;\nstatic const int kHeight = 240;\nstatic const AVRational kTimeBase = { 1, 100 };\n\nACTION_P(SaveInitializeResult, engine) {\n engine->info_ = arg0;\n}\n\nclass FFmpegVideoDecodeEngineTest : public testing::Test,\n public VideoDecodeEngine::EventHandler {\n protected:\n FFmpegVideoDecodeEngineTest() {\n \/\/ Setup FFmpeg structures.\n frame_buffer_.reset(new uint8[kWidth * kHeight]);\n memset(&yuv_frame_, 0, sizeof(yuv_frame_));\n\n \/\/ DecodeFrame will check these pointers as non-NULL value.\n yuv_frame_.data[0] = yuv_frame_.data[1] = yuv_frame_.data[2]\n = frame_buffer_.get();\n yuv_frame_.linesize[0] = kWidth;\n yuv_frame_.linesize[1] = yuv_frame_.linesize[2] = kWidth >> 1;\n\n memset(&codec_context_, 0, sizeof(codec_context_));\n codec_context_.width = kWidth;\n codec_context_.height = kHeight;\n codec_context_.time_base = kTimeBase;\n\n memset(&codec_, 0, sizeof(codec_));\n memset(&stream_, 0, sizeof(stream_));\n stream_.codec = &codec_context_;\n stream_.r_frame_rate.num = kTimeBase.den;\n stream_.r_frame_rate.den = kTimeBase.num;\n\n buffer_ = new DataBuffer(1);\n\n \/\/ Initialize MockFFmpeg.\n MockFFmpeg::set(&mock_ffmpeg_);\n\n test_engine_ = new FFmpegVideoDecodeEngine();\n test_engine_->SetCodecContextForTest(&codec_context_);\n\n VideoFrame::CreateFrame(VideoFrame::YV12,\n kWidth,\n kHeight,\n StreamSample::kInvalidTimestamp,\n StreamSample::kInvalidTimestamp,\n &video_frame_);\n }\n\n ~FFmpegVideoDecodeEngineTest() {\n test_engine_ = NULL;\n MockFFmpeg::set(NULL);\n }\n\n void Initialize() {\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_TRUE(info_.success_);\n }\n\n public:\n MOCK_METHOD1(OnFillBufferCallback,\n void(scoped_refptr<VideoFrame> video_frame));\n MOCK_METHOD1(OnEmptyBufferCallback,\n void(scoped_refptr<Buffer> buffer));\n MOCK_METHOD1(OnInitializeComplete,\n void(const VideoCodecInfo& info));\n MOCK_METHOD0(OnUninitializeComplete, void());\n MOCK_METHOD0(OnFlushComplete, void());\n MOCK_METHOD0(OnSeekComplete, void());\n MOCK_METHOD0(OnError, void());\n MOCK_METHOD1(OnFormatChange, void(VideoStreamInfo stream_info));\n\n scoped_refptr<VideoFrame> video_frame_;\n VideoCodecConfig config_;\n VideoCodecInfo info_;\n protected:\n scoped_refptr<FFmpegVideoDecodeEngine> test_engine_;\n scoped_array<uint8_t> frame_buffer_;\n StrictMock<MockFFmpeg> mock_ffmpeg_;\n\n AVFrame yuv_frame_;\n AVCodecContext codec_context_;\n AVStream stream_;\n AVCodec codec_;\n scoped_refptr<DataBuffer> buffer_;\n\n};\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_Normal) {\n Initialize();\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_FindDecoderFails) {\n \/\/ Test avcodec_find_decoder() returning NULL.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(ReturnNull());\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\n\/\/ Note There are 2 threads for FFmpeg-mt.\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_InitThreadFails) {\n \/\/ Test avcodec_thread_init() failing.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(-1));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, Initialize_OpenDecoderFails) {\n \/\/ Test avcodec_open() failing.\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))\n .WillOnce(Return(&codec_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())\n .WillOnce(Return(&yuv_frame_));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))\n .WillOnce(Return(0));\n EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))\n .WillOnce(Return(-1));\n EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))\n .Times(1);\n\n config_.codec_ = kCodecH264;\n config_.opaque_context_ = &stream_;\n config_.width_ = kWidth;\n config_.height_ = kHeight;\n EXPECT_CALL(*this, OnInitializeComplete(_))\n .WillOnce(SaveInitializeResult(this));\n test_engine_->Initialize(MessageLoop::current(), this, config_);\n EXPECT_FALSE(info_.success_);\n}\n\nACTION_P2(DemuxComplete, engine, buffer) {\n engine->EmptyThisBuffer(buffer);\n}\n\nACTION_P(DecodeComplete, decoder) {\n decoder->video_frame_ = arg0;\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_Normal) {\n Initialize();\n\n \/\/ We rely on FFmpeg for timestamp and duration reporting. The one tricky\n \/\/ bit is calculating the duration when |repeat_pict| > 0.\n const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(123);\n const base::TimeDelta kDuration = base::TimeDelta::FromMicroseconds(15000);\n yuv_frame_.repeat_pict = 1;\n yuv_frame_.reordered_opaque = kTimestamp.InMicroseconds();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(1), \/\/ Simulate 1 byte frame.\n Return(0)));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n \/\/ |video_frame_| timestamp is 0 because we set the timestamp based off\n \/\/ the buffer timestamp.\n EXPECT_EQ(0, video_frame_->GetTimestamp().ToInternalValue());\n EXPECT_EQ(kDuration.ToInternalValue(),\n video_frame_->GetDuration().ToInternalValue());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_0ByteFrame) {\n Initialize();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_))\n .Times(2);\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(0), \/\/ Simulate 0 byte frame.\n Return(0)))\n .WillOnce(DoAll(SetArgumentPointee<2>(1), \/\/ Simulate 1 byte frame.\n Return(0)));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n EXPECT_TRUE(video_frame_.get());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_DecodeError) {\n Initialize();\n\n \/\/ Expect a bunch of avcodec calls.\n EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));\n EXPECT_CALL(mock_ffmpeg_,\n AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))\n .WillOnce(Return(-1));\n\n EXPECT_CALL(*this, OnEmptyBufferCallback(_))\n .WillOnce(DemuxComplete(test_engine_.get(), buffer_));\n EXPECT_CALL(*this, OnFillBufferCallback(_))\n .WillOnce(DecodeComplete(this));\n test_engine_->FillThisBuffer(video_frame_);\n\n EXPECT_FALSE(video_frame_.get());\n}\n\nTEST_F(FFmpegVideoDecodeEngineTest, GetSurfaceFormat) {\n \/\/ YV12 formats.\n codec_context_.pix_fmt = PIX_FMT_YUV420P;\n EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());\n codec_context_.pix_fmt = PIX_FMT_YUVJ420P;\n EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());\n\n \/\/ YV16 formats.\n codec_context_.pix_fmt = PIX_FMT_YUV422P;\n EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());\n codec_context_.pix_fmt = PIX_FMT_YUVJ422P;\n EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());\n\n \/\/ Invalid value.\n codec_context_.pix_fmt = PIX_FMT_NONE;\n EXPECT_EQ(VideoFrame::INVALID, test_engine_->GetSurfaceFormat());\n}\n\n} \/\/ namespace media\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************\n * Source Code for the Original Compiler for the\n * Programming Language Wake\n *\n * OtherStatement.cpp\n *\n * Licensed under the MIT license\n * See LICENSE.TXT for details\n *\n * Author: Michael Fairhurst\n * Revised By:\n *\n **************************************************\/\n\n#include \"type.h\"\n#include \"TypeAnalyzer.h\"\n#include \"TypeParameterizer.h\"\n#include \"ClassSpaceSymbolTable.h\"\n#include \"ast\/StatementNode.h\"\n#include \"ast\/OtherStatement.h\"\n\nvoid wake::ast::OtherStatement::typeCheck() {\n\tswitch(tree->node_type) {\n\t\t\/\/ Ignoring these for now\n\t\tcase NT_SWITCH:\n\t\tcase NT_CURRIED:\n\t\tcase NT_INCREMENT:\n\t\tcase NT_DECREMENT:\n\t\t\/\/ These require a common-ancestor function\n\t\tcase NT_TYPE_ARRAY:\n\t\tcase NT_VALUES:\n\t\t\tthrow string(\"Not supported yet\");\n\n\t\t\/\/ These have tests so can't throw, but won't compile anyway as long as switch throws\n\t\tcase NT_DEFAULTCASE:\n\t\tcase NT_CASE:\n\n\t\t\/\/ these don't have types\n\t\tcase NT_BLOCK:\n\t\tcase NT_TRY:\n\t\t\tscopesymtable->pushScope();\n\t\t\t\/\/ FALL THROUGH!\n\t\tcase NT_RETRIEVALS_STATEMENTS:\n\t\tcase NT_BREAK:\n\t\tcase NT_CONTINUE:\n\t\t\ttry {\n\t\t\t\tfor(boost::ptr_vector<StatementNode>::iterator it = children.begin(); it != children.end(); ++it) {\n\t\t\t\t\tit->typeCheck();\n\t\t\t\t}\n\t\t\t\tif(tree->node_type == NT_BLOCK || tree->node_type == NT_TRY) scopesymtable->popScope();\n\t\t\t} catch(SemanticError *e) {\n\t\t\t\tif(tree->node_type == NT_BLOCK || tree->node_type == NT_TRY) scopesymtable->popScope();\n\t\t\t\tthrow e;\n\t\t\t}\n\t}\n}\n<commit_msg>Typecheck the expressions in a for loop incr<commit_after>\/**************************************************\n * Source Code for the Original Compiler for the\n * Programming Language Wake\n *\n * OtherStatement.cpp\n *\n * Licensed under the MIT license\n * See LICENSE.TXT for details\n *\n * Author: Michael Fairhurst\n * Revised By:\n *\n **************************************************\/\n\n#include \"type.h\"\n#include \"TypeAnalyzer.h\"\n#include \"TypeParameterizer.h\"\n#include \"ClassSpaceSymbolTable.h\"\n#include \"ast\/StatementNode.h\"\n#include \"ast\/OtherStatement.h\"\n\nvoid wake::ast::OtherStatement::typeCheck() {\n\tswitch(tree->node_type) {\n\t\t\/\/ Ignoring these for now\n\t\tcase NT_SWITCH:\n\t\tcase NT_CURRIED:\n\t\tcase NT_INCREMENT:\n\t\tcase NT_DECREMENT:\n\t\t\/\/ These require a common-ancestor function\n\t\tcase NT_TYPE_ARRAY:\n\t\tcase NT_VALUES:\n\t\t\tthrow string(\"Not supported yet\");\n\n\t\t\/\/ These have tests so can't throw, but won't compile anyway as long as switch throws\n\t\tcase NT_DEFAULTCASE:\n\t\tcase NT_CASE:\n\n\t\t\/\/ these don't have types\n\t\tcase NT_BLOCK:\n\t\tcase NT_TRY:\n\t\t\tscopesymtable->pushScope();\n\t\t\t\/\/ FALL THROUGH!\n\t\tcase NT_RETRIEVALS_STATEMENTS:\n\t\tcase NT_EXPRESSIONS:\n\t\tcase NT_BREAK:\n\t\tcase NT_CONTINUE:\n\t\t\ttry {\n\t\t\t\tfor(boost::ptr_vector<StatementNode>::iterator it = children.begin(); it != children.end(); ++it) {\n\t\t\t\t\tit->typeCheck();\n\t\t\t\t}\n\t\t\t\tif(tree->node_type == NT_BLOCK || tree->node_type == NT_TRY) scopesymtable->popScope();\n\t\t\t} catch(SemanticError *e) {\n\t\t\t\tif(tree->node_type == NT_BLOCK || tree->node_type == NT_TRY) scopesymtable->popScope();\n\t\t\t\tthrow e;\n\t\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <map>\n#include <vector>\n#include <fstream>\n\n#include <Observation.hpp>\n#include <utils.hpp>\n\n#ifndef INTEGRATION_HPP\n#define INTEGRATION_HPP\n\nnamespace PulsarSearch {\n\nclass integrationSamplesDMsConf {\npublic:\n integrationSamplesDMsConf();\n ~integrationSamplesDMsConf();\n \/\/ Get\n unsigned int getNrSamplesPerBlock() const;\n unsigned int getNrSamplesPerThread() const;\n \/\/ Set\n void setNrSamplesPerBlock(unsigned int samples);\n void setNrSamplesPerThread(unsigned int samples);\n \/\/ utils\n std::string print() const;\nprivate:\n unsigned int nrSamplesPerBlock;\n unsigned int nrSamplesPerThread;\n};\n\ntypedef std::map< std::string, std::map < unsigned int, std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > > > tunedIntegrationSamplesDMsConf;\n\n\/\/ Sequential\ntemplate< typename T > void integrationSamplesDMs(const AstroData::Observation & observation, const unsigned int integration, const unsigned int padding, const std::vector< T > & input, std::vector< T > & output);\n\/\/ OpenCL\ntemplate< typename T > std::string * getIntegrationSamplesDMsOpenCL(const integrationSamplesDMsConf & conf, const AstroData::Observation & observation, const std::string & inputDataName, const unsigned int integration, const unsigned int padding);\n\/\/ Read configuration files\nvoid readTunedIntegrationSamplesDMsConf(tunedIntegrationSamplesDMsConf & tunedConf, const std::string & confFilename);\n\n\n\/\/ Implementations\ninline unsigned int integrationSamplesDMsConf::getNrSamplesPerBlock() const {\n return nrSamplesPerBlock;\n}\n\ninline unsigned int integrationSamplesDMsConf::getNrSamplesPerThread() const {\n return nrSamplesPerThread;\n}\n\ninline void integrationSamplesDMsConf::setNrSamplesPerBlock(unsigned int samples) {\n nrSamplesPerBlock = samples;\n}\n\ninline void integrationSamplesDMsConf::setNrSamplesPerThread(unsigned int samples) {\n nrSamplesPerThread = samples;\n}\n\ntemplate< typename T > void integrationSamplesDMs(const AstroData::Observation & observation, const unsigned int integration, const unsigned int padding, const std::vector< T > & input, std::vector< T > & output) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample += integration ) {\n T integratedSample = 0;\n\n for ( unsigned int i = 0; i < integration; i++ ) {\n integratedSample += input[(dm * observation.getNrSamplesPerPaddedSecond(padding \/ sizeof(T))) + (sample + i)];\n }\n output[(dm * isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + (sample \/ integration)] = integratedSample \/ integration;\n }\n }\n}\n\ntemplate< typename T > std::string * getIntegrationSamplesDMsOpenCL(const integrationSamplesDMsConf & conf, const AstroData::Observation & observation, const std::string & dataName, const unsigned int integration, const unsigned int padding) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void integrationSamplesDMs\" + isa::utils::toString(integration) + \"(__global const \" + dataName + \" * const restrict input, __global \" + dataName + \" * const restrict output) {\\n\"\n \"unsigned int dm = get_group_id(1);\\n\"\n \"__local \" + dataName + \" buffer[\" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \"];\\n\"\n \"<%DEFS%>\"\n \"\\n\"\n \"\/\/ Load local memory\\n\"\n \"unsigned int inLocalMemory = get_local_id(0);\\n\"\n \"unsigned int inGlobalMemory = get_local_id(0) + (get_group_id(0) * \" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \");\\n\"\n \"while ( inLocalMemory < \" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \" ) {\\n\"\n \"buffer[inLocalMemory] = input[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond(padding \/ sizeof(T))) + \") + inGlobalMemory];\\n\"\n \"inGlobalMemory += \" + isa::utils::toString(conf.getNrSamplesPerBlock()) + \";\\n\"\n \"inLocalMemory += \" + isa::utils::toString(conf.getNrSamplesPerBlock()) + \";\\n\"\n \"}\\n\"\n \"<%LOAD%>\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"\/\/ Reduce\\n\"\n \"unsigned int threshold = \" + isa::utils::toString(integration \/ 2) + \";\\n\"\n \"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n \"if ( sample < threshold ) {\\n\"\n \"<%REDUCE%>\"\n \"}\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"}\\n\"\n \"if ( get_local_id(0) < \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \" ) {\\n\";\n if ( dataName == \"float\" ) {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] * \" + isa::utils::toString(1.0f \/ integration) + \"f;\\n\";\n } else if ( dataName == \"double\" ) {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] * \" + isa::utils::toString(1.0 \/ integration) + \";\\n\";\n } else {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] \/ \" + isa::utils::toString(integration) + \";\\n\";\n }\n *code += \"}\\n\"\n \"}\\n\";\n std::string defs_sTemplate = dataName + \" integratedSample<%NUM%> = 0;\\n\";\n std::string load_sTemplate = \"integratedSample<%NUM%> = buffer[get_local_id(0) + <%OFFSET%>];\\n\"\n std::string reduce_sTemplate = \"integratedSample<%NUM%> += buffer[(sample + <%OFFSET%>) + threshold];\\n\"\n \"buffer[sample + <%OFFSET%>] = integratedSample<%NUM%>;\\n\";\n \/\/ End kernel's template\n\n std::string * defs_s = new std::string();\n std::string * load_s = new std::string();\n std::string * reduce_s = new std::string();\n\n for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {\n std::string sample_s = isa::utils::toString(sample);\n std::string offset_s = isa::utils::toString(sample * integration);\n std::string * temp = 0;\n\n temp = isa::utils::replace(&defs_sTemplate, \"<%NUM%>\", sample_s);\n defs_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&load_sTemplate, \"<%NUM%>\", sample_s);\n if ( sample == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n load_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&reduce_sTemplate, \"<%NUM%>\", sample_s);\n if ( sample == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n reduce_s->append(*temp);\n delete temp;\n }\n code = isa::utils::replace(code, \"<%DEFS%>\", *defs_s, true);\n code = isa::utils::replace(code, \"<%LOAD%>\", *load_s, true);\n code = isa::utils::replace(code, \"<%REDUCE%>\", *reduce_s, true);\n delete defs_s;\n delete reduce_s;\n\n return code;\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ INTEGRATION_HPP\n\n<commit_msg>Typo.<commit_after>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <map>\n#include <vector>\n#include <fstream>\n\n#include <Observation.hpp>\n#include <utils.hpp>\n\n#ifndef INTEGRATION_HPP\n#define INTEGRATION_HPP\n\nnamespace PulsarSearch {\n\nclass integrationSamplesDMsConf {\npublic:\n integrationSamplesDMsConf();\n ~integrationSamplesDMsConf();\n \/\/ Get\n unsigned int getNrSamplesPerBlock() const;\n unsigned int getNrSamplesPerThread() const;\n \/\/ Set\n void setNrSamplesPerBlock(unsigned int samples);\n void setNrSamplesPerThread(unsigned int samples);\n \/\/ utils\n std::string print() const;\nprivate:\n unsigned int nrSamplesPerBlock;\n unsigned int nrSamplesPerThread;\n};\n\ntypedef std::map< std::string, std::map < unsigned int, std::map< unsigned int, PulsarSearch::integrationSamplesDMsConf > > > tunedIntegrationSamplesDMsConf;\n\n\/\/ Sequential\ntemplate< typename T > void integrationSamplesDMs(const AstroData::Observation & observation, const unsigned int integration, const unsigned int padding, const std::vector< T > & input, std::vector< T > & output);\n\/\/ OpenCL\ntemplate< typename T > std::string * getIntegrationSamplesDMsOpenCL(const integrationSamplesDMsConf & conf, const AstroData::Observation & observation, const std::string & inputDataName, const unsigned int integration, const unsigned int padding);\n\/\/ Read configuration files\nvoid readTunedIntegrationSamplesDMsConf(tunedIntegrationSamplesDMsConf & tunedConf, const std::string & confFilename);\n\n\n\/\/ Implementations\ninline unsigned int integrationSamplesDMsConf::getNrSamplesPerBlock() const {\n return nrSamplesPerBlock;\n}\n\ninline unsigned int integrationSamplesDMsConf::getNrSamplesPerThread() const {\n return nrSamplesPerThread;\n}\n\ninline void integrationSamplesDMsConf::setNrSamplesPerBlock(unsigned int samples) {\n nrSamplesPerBlock = samples;\n}\n\ninline void integrationSamplesDMsConf::setNrSamplesPerThread(unsigned int samples) {\n nrSamplesPerThread = samples;\n}\n\ntemplate< typename T > void integrationSamplesDMs(const AstroData::Observation & observation, const unsigned int integration, const unsigned int padding, const std::vector< T > & input, std::vector< T > & output) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample += integration ) {\n T integratedSample = 0;\n\n for ( unsigned int i = 0; i < integration; i++ ) {\n integratedSample += input[(dm * observation.getNrSamplesPerPaddedSecond(padding \/ sizeof(T))) + (sample + i)];\n }\n output[(dm * isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + (sample \/ integration)] = integratedSample \/ integration;\n }\n }\n}\n\ntemplate< typename T > std::string * getIntegrationSamplesDMsOpenCL(const integrationSamplesDMsConf & conf, const AstroData::Observation & observation, const std::string & dataName, const unsigned int integration, const unsigned int padding) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n *code = \"__kernel void integrationSamplesDMs\" + isa::utils::toString(integration) + \"(__global const \" + dataName + \" * const restrict input, __global \" + dataName + \" * const restrict output) {\\n\"\n \"unsigned int dm = get_group_id(1);\\n\"\n \"__local \" + dataName + \" buffer[\" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \"];\\n\"\n \"<%DEFS%>\"\n \"\\n\"\n \"\/\/ Load local memory\\n\"\n \"unsigned int inLocalMemory = get_local_id(0);\\n\"\n \"unsigned int inGlobalMemory = get_local_id(0) + (get_group_id(0) * \" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \");\\n\"\n \"while ( inLocalMemory < \" + isa::utils::toString(integration * conf.getNrSamplesPerThread()) + \" ) {\\n\"\n \"buffer[inLocalMemory] = input[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond(padding \/ sizeof(T))) + \") + inGlobalMemory];\\n\"\n \"inGlobalMemory += \" + isa::utils::toString(conf.getNrSamplesPerBlock()) + \";\\n\"\n \"inLocalMemory += \" + isa::utils::toString(conf.getNrSamplesPerBlock()) + \";\\n\"\n \"}\\n\"\n \"<%LOAD%>\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"\/\/ Reduce\\n\"\n \"unsigned int threshold = \" + isa::utils::toString(integration \/ 2) + \";\\n\"\n \"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n \"if ( sample < threshold ) {\\n\"\n \"<%REDUCE%>\"\n \"}\\n\"\n \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n \"}\\n\"\n \"if ( get_local_id(0) < \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \" ) {\\n\";\n if ( dataName == \"float\" ) {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] * \" + isa::utils::toString(1.0f \/ integration) + \"f;\\n\";\n } else if ( dataName == \"double\" ) {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] * \" + isa::utils::toString(1.0 \/ integration) + \";\\n\";\n } else {\n *code += \"output[(dm * \" + isa::utils::toString(isa::utils::pad(observation.getNrSamplesPerSecond() \/ integration, padding \/ sizeof(T))) + \") + ((get_group_id(0) * \" + isa::utils::toString(conf.getNrSamplesPerThread()) + \") + get_local_id(0))] = buffer[get_local_id(0) * \" + isa::utils::toString(integration) + \"] \/ \" + isa::utils::toString(integration) + \";\\n\";\n }\n *code += \"}\\n\"\n \"}\\n\";\n std::string defs_sTemplate = dataName + \" integratedSample<%NUM%> = 0;\\n\";\n std::string load_sTemplate = \"integratedSample<%NUM%> = buffer[get_local_id(0) + <%OFFSET%>];\\n\";\n std::string reduce_sTemplate = \"integratedSample<%NUM%> += buffer[(sample + <%OFFSET%>) + threshold];\\n\"\n \"buffer[sample + <%OFFSET%>] = integratedSample<%NUM%>;\\n\";\n \/\/ End kernel's template\n\n std::string * defs_s = new std::string();\n std::string * load_s = new std::string();\n std::string * reduce_s = new std::string();\n\n for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {\n std::string sample_s = isa::utils::toString(sample);\n std::string offset_s = isa::utils::toString(sample * integration);\n std::string * temp = 0;\n\n temp = isa::utils::replace(&defs_sTemplate, \"<%NUM%>\", sample_s);\n defs_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&load_sTemplate, \"<%NUM%>\", sample_s);\n if ( sample == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n load_s->append(*temp);\n delete temp;\n temp = isa::utils::replace(&reduce_sTemplate, \"<%NUM%>\", sample_s);\n if ( sample == 0 ) {\n std::string empty_s(\"\");\n temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n } else {\n temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n }\n reduce_s->append(*temp);\n delete temp;\n }\n code = isa::utils::replace(code, \"<%DEFS%>\", *defs_s, true);\n code = isa::utils::replace(code, \"<%LOAD%>\", *load_s, true);\n code = isa::utils::replace(code, \"<%REDUCE%>\", *reduce_s, true);\n delete defs_s;\n delete reduce_s;\n\n return code;\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ INTEGRATION_HPP\n\n<|endoftext|>"} {"text":"<commit_before>#include \"AlignmentOffsets.hpp\"\n\n#include <iostream>\n\nvoid AlignmentOffsets::update_offset(int32_t const& opcode, uint32_t const& oplen) {\n \/\/This code from SAMBLASTER\n if (opcode == BAM_CMATCH || opcode == BAM_CEQUAL || opcode == BAM_CDIFF) {\n raLen += oplen;\n qaLen += oplen;\n first = false;\n }\n else if (opcode == BAM_CSOFT_CLIP || opcode == BAM_CHARD_CLIP) {\n if (first) {\n sclip += oplen;\n }\n else {\n eclip += oplen;\n }\n } \n else if (opcode == BAM_CDEL || opcode == BAM_CREF_SKIP) {\n raLen += oplen;\n }\n else if (opcode == BAM_CINS)\n {\n qaLen += oplen;\n }\n else\n {\n \/\/ XXX This should be an exception\n std::cerr << \"Unknown opcode '\" << opcode << \"%c'\\n\";\n }\n}\n<commit_msg>throw exception<commit_after>#include \"AlignmentOffsets.hpp\"\n\n#include <boost\/format.hpp>\n\n#include <iostream>\n#include <stdexcept>\n#include <string.h>\n\nusing boost::format;\n\nvoid AlignmentOffsets::update_offset(int32_t const& opcode, uint32_t const& oplen) {\n \/\/This code from SAMBLASTER\n if (opcode == BAM_CMATCH || opcode == BAM_CEQUAL || opcode == BAM_CDIFF) {\n raLen += oplen;\n qaLen += oplen;\n first = false;\n }\n else if (opcode == BAM_CSOFT_CLIP || opcode == BAM_CHARD_CLIP) {\n if (first) {\n sclip += oplen;\n }\n else {\n eclip += oplen;\n }\n } \n else if (opcode == BAM_CDEL || opcode == BAM_CREF_SKIP) {\n raLen += oplen;\n }\n else if (opcode == BAM_CINS)\n {\n qaLen += oplen;\n }\n else\n {\n throw std::runtime_error(str(format(\n \"Unknown opcode %1%\") % bam_cigar_opchr(opcode)));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file was automatically generated on 03 Feb 2016 at 00:06:56\n\n\/*\n\tNazara Engine - Core module\n\n\tCopyright (C) 2015 Jérôme \"Lynix\" Leclercq (Lynix680@gmail.com)\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy of\n\tthis software and associated documentation files (the \"Software\"), to deal in\n\tthe Software without restriction, including without limitation the rights to\n\tuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n\tof the Software, and to permit persons to whom the Software is furnished to do\n\tso, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in all\n\tcopies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\tSOFTWARE.\n*\/\n\n#pragma once\n\n#ifndef NAZARA_GLOBAL_CORE_HPP\n#define NAZARA_GLOBAL_CORE_HPP\n\n#include <Nazara\/Core\/AbstractHash.hpp>\n#include <Nazara\/Core\/AbstractLogger.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Core\/Bitset.hpp>\n#include <Nazara\/Core\/ByteArray.hpp>\n#include <Nazara\/Core\/ByteStream.hpp>\n#include <Nazara\/Core\/CallOnExit.hpp>\n#include <Nazara\/Core\/Clock.hpp>\n#include <Nazara\/Core\/Color.hpp>\n#include <Nazara\/Core\/ConditionVariable.hpp>\n#include <Nazara\/Core\/Config.hpp>\n#include <Nazara\/Core\/Core.hpp>\n#include <Nazara\/Core\/Directory.hpp>\n#include <Nazara\/Core\/DynLib.hpp>\n#include <Nazara\/Core\/Endianness.hpp>\n#include <Nazara\/Core\/Enums.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/ErrorFlags.hpp>\n#include <Nazara\/Core\/File.hpp>\n#include <Nazara\/Core\/FileLogger.hpp>\n#include <Nazara\/Core\/Functor.hpp>\n#include <Nazara\/Core\/GuillotineBinPack.hpp>\n#include <Nazara\/Core\/HardwareInfo.hpp>\n#include <Nazara\/Core\/Initializer.hpp>\n#include <Nazara\/Core\/LockGuard.hpp>\n#include <Nazara\/Core\/Log.hpp>\n#include <Nazara\/Core\/MemoryHelper.hpp>\n#include <Nazara\/Core\/MemoryManager.hpp>\n#include <Nazara\/Core\/MemoryPool.hpp>\n#include <Nazara\/Core\/MemoryStream.hpp>\n#include <Nazara\/Core\/MemoryView.hpp>\n#include <Nazara\/Core\/Mutex.hpp>\n#include <Nazara\/Core\/ObjectLibrary.hpp>\n#include <Nazara\/Core\/ObjectRef.hpp>\n#include <Nazara\/Core\/OffsetOf.hpp>\n#include <Nazara\/Core\/ParameterList.hpp>\n#include <Nazara\/Core\/PluginManager.hpp>\n#include <Nazara\/Core\/Primitive.hpp>\n#include <Nazara\/Core\/PrimitiveList.hpp>\n#include <Nazara\/Core\/RefCounted.hpp>\n#include <Nazara\/Core\/Resource.hpp>\n#include <Nazara\/Core\/ResourceLoader.hpp>\n#include <Nazara\/Core\/ResourceManager.hpp>\n#include <Nazara\/Core\/Semaphore.hpp>\n#include <Nazara\/Core\/SerializationContext.hpp>\n#include <Nazara\/Core\/Signal.hpp>\n#include <Nazara\/Core\/SparsePtr.hpp>\n#include <Nazara\/Core\/StdLogger.hpp>\n#include <Nazara\/Core\/Stream.hpp>\n#include <Nazara\/Core\/String.hpp>\n#include <Nazara\/Core\/StringStream.hpp>\n#include <Nazara\/Core\/TaskScheduler.hpp>\n#include <Nazara\/Core\/Thread.hpp>\n#include <Nazara\/Core\/Unicode.hpp>\n#include <Nazara\/Core\/Updatable.hpp>\n\n#endif \/\/ NAZARA_GLOBAL_CORE_HPP\n<commit_msg>Core: Update global include<commit_after>\/\/ This file was automatically generated on 09 May 2016 at 17:07:09\n\n\/*\n\tNazara Engine - Core module\n\n\tCopyright (C) 2015 Jérôme \"Lynix\" Leclercq (Lynix680@gmail.com)\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy of\n\tthis software and associated documentation files (the \"Software\"), to deal in\n\tthe Software without restriction, including without limitation the rights to\n\tuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n\tof the Software, and to permit persons to whom the Software is furnished to do\n\tso, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in all\n\tcopies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\tSOFTWARE.\n*\/\n\n#pragma once\n\n#ifndef NAZARA_GLOBAL_CORE_HPP\n#define NAZARA_GLOBAL_CORE_HPP\n\n#include <Nazara\/Core\/AbstractHash.hpp>\n#include <Nazara\/Core\/AbstractLogger.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Core\/Bitset.hpp>\n#include <Nazara\/Core\/ByteArray.hpp>\n#include <Nazara\/Core\/ByteStream.hpp>\n#include <Nazara\/Core\/CallOnExit.hpp>\n#include <Nazara\/Core\/Clock.hpp>\n#include <Nazara\/Core\/Color.hpp>\n#include <Nazara\/Core\/ConditionVariable.hpp>\n#include <Nazara\/Core\/Config.hpp>\n#include <Nazara\/Core\/Core.hpp>\n#include <Nazara\/Core\/Directory.hpp>\n#include <Nazara\/Core\/DynLib.hpp>\n#include <Nazara\/Core\/Endianness.hpp>\n#include <Nazara\/Core\/Enums.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/ErrorFlags.hpp>\n#include <Nazara\/Core\/File.hpp>\n#include <Nazara\/Core\/FileLogger.hpp>\n#include <Nazara\/Core\/Functor.hpp>\n#include <Nazara\/Core\/GuillotineBinPack.hpp>\n#include <Nazara\/Core\/HandledObject.hpp>\n#include <Nazara\/Core\/HardwareInfo.hpp>\n#include <Nazara\/Core\/Initializer.hpp>\n#include <Nazara\/Core\/LockGuard.hpp>\n#include <Nazara\/Core\/Log.hpp>\n#include <Nazara\/Core\/MemoryHelper.hpp>\n#include <Nazara\/Core\/MemoryManager.hpp>\n#include <Nazara\/Core\/MemoryPool.hpp>\n#include <Nazara\/Core\/MemoryStream.hpp>\n#include <Nazara\/Core\/MemoryView.hpp>\n#include <Nazara\/Core\/Mutex.hpp>\n#include <Nazara\/Core\/ObjectHandle.hpp>\n#include <Nazara\/Core\/ObjectLibrary.hpp>\n#include <Nazara\/Core\/ObjectRef.hpp>\n#include <Nazara\/Core\/OffsetOf.hpp>\n#include <Nazara\/Core\/ParameterList.hpp>\n#include <Nazara\/Core\/PluginManager.hpp>\n#include <Nazara\/Core\/Primitive.hpp>\n#include <Nazara\/Core\/PrimitiveList.hpp>\n#include <Nazara\/Core\/RefCounted.hpp>\n#include <Nazara\/Core\/Resource.hpp>\n#include <Nazara\/Core\/ResourceLoader.hpp>\n#include <Nazara\/Core\/ResourceManager.hpp>\n#include <Nazara\/Core\/ResourceParameters.hpp>\n#include <Nazara\/Core\/ResourceSaver.hpp>\n#include <Nazara\/Core\/Semaphore.hpp>\n#include <Nazara\/Core\/SerializationContext.hpp>\n#include <Nazara\/Core\/Signal.hpp>\n#include <Nazara\/Core\/SparsePtr.hpp>\n#include <Nazara\/Core\/StdLogger.hpp>\n#include <Nazara\/Core\/Stream.hpp>\n#include <Nazara\/Core\/String.hpp>\n#include <Nazara\/Core\/StringStream.hpp>\n#include <Nazara\/Core\/TaskScheduler.hpp>\n#include <Nazara\/Core\/Thread.hpp>\n#include <Nazara\/Core\/Unicode.hpp>\n#include <Nazara\/Core\/Updatable.hpp>\n\n#endif \/\/ NAZARA_GLOBAL_CORE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <limits>\n\n#include <utils.hpp>\n\n\n#ifndef OBSERVATION_HPP\n#define OBSERVATION_HPP\n\nnamespace AstroData {\n\nclass Observation {\npublic:\n Observation();\n ~Observation();\n\n \/\/ Getters\n \/\/ General observation parameters\n unsigned int getNrSeconds() const;\n unsigned int getNrStations() const;\n unsigned int getNrPaddedStations(unsigned int padding) const;\n unsigned int getNrBeams() const;\n unsigned int getNrPaddedBeams(unsigned int padding) const;\n unsigned int getNrSyntheticBeams() const;\n unsigned int getNrPaddedSyntheticBeams(const unsigned int padding) const;\n float getSamplingRate() const;\n unsigned int getNrSamplesPerBatch() const;\n unsigned int getNrSamplesPerPaddedBatch(unsigned int padding) const;\n\t\/\/ Frequency parameters\n unsigned int getNrSubbands() const;\n unsigned int getNrChannels() const;\n unsigned int getNrChannelsPerSubband() const;\n unsigned int getNrPaddedSubbands(unsigned int padding) const;\n unsigned int getNrPaddedChannels(unsigned int padding) const;\n unsigned int getNrZappedChannels() const;\n float getSubbandMinFreq() const;\n float getSubbandMaxFreq() const;\n float getSubbandBandwidth() const;\n float getMinFreq() const;\n float getMaxFreq() const;\n float getChannelBandwidth() const;\n\t\/\/ Dispersion measures\n unsigned int getNrSamplesPerBatchSubbanding() const;\n unsigned int getNrSamplesPerPaddedBatchSubbanding(unsigned int padding) const;\n unsigned int getNrDelaySecondsSubbanding() const;\n unsigned int getNrDelaySeconds() const;\n unsigned int getNrDMsSubbanding() const;\n unsigned int getNrDMs() const;\n unsigned int getNrPaddedDMsSubbanding(unsigned int padding) const;\n unsigned int getNrPaddedDMs(unsigned int padding) const;\n unsigned int getNrSamplesPerSubbandingDispersedChannel() const;\n unsigned int getNrSamplesPerDispersedChannel() const;\n unsigned int getNrSamplesPerPaddedSubbandingDispersedChannel(unsigned int padding) const;\n unsigned int getNrSamplesPerPaddedDispersedChannel(unsigned int padding) const;\n float getFirstDMSubbanding() const;\n float getFirstDM() const;\n float getLastDMSubbanding() const;\n float getLastDM() const;\n float getDMSubbandingStep() const;\n float getDMStep() const;\n\t\/\/ Periods\n unsigned int getNrPeriods() const;\n unsigned int getNrPaddedPeriods(unsigned int padding) const;\n unsigned int getFirstPeriod() const;\n unsigned int getLastPeriod() const;\n unsigned int getPeriodStep() const;\n unsigned int getNrBins() const;\n unsigned int getNrPaddedBins(unsigned int padding) const;\n\n \/\/ Setters\n \/\/ General observation parameters\n void setNrSeconds(const unsigned int seconds);\n void setNrStations(const unsigned int stations);\n void setNrBeams(const unsigned int beams);\n void setNrSyntheticBeams(const unsigned int beams);\n void setSamplingRate(const float sampling);\n void setNrSamplesPerBatch(const unsigned int samples);\n \/\/ Frequency parameters\n void setFrequencyRange(const unsigned int subbands, const unsigned int channels, const float baseFrequency, const float bandwidth);\n void setNrZappedChannels(const unsigned int zappedChannels);\n \/\/ Dispersion measures\n void setNrSamplesPerBatchSubbanding(const unsigned int samples);\n void setNrDelaySecondsSubbanding(const unsigned int seconds);\n void setNrDelaySeconds(const unsigned int seconds);\n void setNrSamplesPerSubbandingDispersedChannel(const unsigned int samples);\n void setNrSamplesPerDispersedChannel(const unsigned int samples);\n void setDMSubbandingRange(const unsigned int dms, const float baseDM, const float step);\n void setDMRange(const unsigned int dms, const float baseDM, const float step);\n \/\/ Periods\n void setPeriodRange(const unsigned int periods, const unsigned int basePeriod, const unsigned int step);\n void setNrBins(const unsigned int bins);\n\nprivate:\n unsigned int nrSeconds;\n unsigned int nrStations;\n unsigned int nrBeams;\n unsigned int nrSyntheticBeams;\n float samplingRate;\n unsigned int nrSamplesPerBatch;\n unsigned int nrSamplesPerDispersedChannel;\n\n unsigned int nrSubbands;\n unsigned int nrChannels;\n unsigned int nrChannelsPerSubband;\n unsigned int nrZappedChannels;\n float subbandMinFreq;\n float subbandMaxFreq;\n float subbandBandwidth;\n float minFreq;\n float maxFreq;\n float channelBandwidth;\n\n unsigned int nrSamplesPerBatchSubbanding;\n unsigned int nrDelaySecondsSubbanding;\n unsigned int nrDelaySeconds;\n unsigned int nrDMsSubbanding;\n unsigned int nrDMs;\n float firstDMSubbanding;\n float firstDM;\n float lastDMSubbanding;\n float lastDM;\n float DMSubbandingStep;\n float DMStep;\n\n unsigned int nrPeriods;\n unsigned int firstPeriod;\n unsigned int lastPeriod;\n unsigned int periodStep;\n unsigned int nrBins;\n};\n\n\/\/ Implementations\ninline unsigned int Observation::getNrSeconds() const {\n\treturn nrSeconds;\n}\n\ninline unsigned int Observation::getNrStations() const {\n\treturn nrStations;\n}\n\ninline unsigned int Observation::getNrPaddedStations(unsigned int padding) const {\n\treturn isa::utils::pad(nrStations, padding);\n}\n\ninline unsigned int Observation::getNrBeams() const {\n\treturn nrBeams;\n}\n\ninline unsigned int Observation::getNrPaddedBeams(unsigned int padding) const {\n\treturn isa::utils::pad(nrBeams, padding);\n}\n\ninline unsigned int Observation::getNrSyntheticBeams() const {\n return nrSyntheticBeams;\n}\n\ninline unsigned int Observation::getNrPaddedSyntheticBeams(unsigned int padding) const {\n return isa::utils::pad(nrSyntheticBeams, padding);\n}\n\ninline unsigned int Observation::getNrSamplesPerBatch() const {\n\treturn nrSamplesPerBatch;\n}\n\ninline float Observation::getSamplingRate() const {\n\treturn samplingRate;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedBatch(unsigned int padding) const {\n\treturn isa::utils::pad(nrSamplesPerBatch, padding);\n}\n\ninline unsigned int Observation::getNrSubbands() const {\n return nrSubbands;\n}\n\ninline unsigned int Observation::getNrChannels() const {\n\treturn nrChannels;\n}\n\ninline unsigned int Observation::getNrPaddedSubbands(unsigned int padding) const {\n\treturn isa::utils::pad(nrSubbands, padding);\n}\n\ninline unsigned int Observation::getNrPaddedChannels(unsigned int padding) const {\n\treturn isa::utils::pad(nrChannels, padding);\n}\n\ninline unsigned int Observation::getNrZappedChannels() const {\n return nrZappedChannels;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedDispersedChannel(unsigned int padding) const {\n return isa::utils::pad(nrSamplesPerDispersedChannel, padding);\n}\n\ninline float Observation::getSubbandMinFreq() const {\n return subbandMinFreq;\n}\n\ninline float Observation::getSubbandMaxFreq() const {\n return subbandMaxFreq;\n}\n\ninline float Observation::getSubbandBandwidth() const {\n return subbandBandwidth;\n}\n\ninline float Observation::getMinFreq() const {\n\treturn minFreq;\n}\n\ninline float Observation::getMaxFreq() const {\n\treturn maxFreq;\n}\n\ninline float Observation::getChannelBandwidth() const {\n\treturn channelBandwidth;\n}\n\ninline unsigned int Observation::getNrSamplesPerDispersedChannel() const {\n return nrSamplesPerDispersedChannel;\n}\n\ninline unsigned int Observation::getNrSamplesPerBatchSubbanding() const {\n return nrSamplesPerBatchSubbanding;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedBatchSubbanding(unsigned int padding) const {\n\treturn isa::utils::pad(nrSamplesPerBatchSubbanding, padding);\n}\n\ninline unsigned int Observation::getNrDelaySecondsSubbanding() const {\n return nrDelaySecondsSubbanding;\n}\n\ninline unsigned int Observation::getNrDelaySeconds() const {\n return nrDelaySeconds;\n}\n\ninline unsigned int Observation::getNrDMsSubbanding() const {\n\treturn nrDMsSubbanding;\n}\n\ninline unsigned int Observation::getNrDMs() const {\n\treturn nrDMs;\n}\n\ninline unsigned int Observation::getNrPaddedDMsSubbanding(unsigned int padding) const {\n\treturn isa::utils::pad(nrDMsSubbanding, padding);\n}\n\ninline unsigned int Observation::getNrPaddedDMs(unsigned int padding) const {\n\treturn isa::utils::pad(nrDMs, padding);\n}\n\ninline float Observation::getFirstDMSubbanding() const {\n\treturn firstDMSubbanding;\n}\n\ninline float Observation::getFirstDM() const {\n\treturn firstDM;\n}\n\ninline float Observation::getLastDMSubbanding() const {\n return lastDMSubbanding;\n}\n\ninline float Observation::getLastDM() const {\n return lastDM;\n}\n\ninline float Observation::getDMSubbandingStep() const {\n\treturn DMSubbandingStep;\n}\n\ninline float Observation::getDMStep() const {\n\treturn DMStep;\n}\n\ninline unsigned int Observation::getNrPeriods() const {\n\treturn nrPeriods;\n}\n\ninline unsigned int Observation::getNrPaddedPeriods(unsigned int padding) const {\n\treturn isa::utils::pad(nrPeriods, padding);\n}\n\ninline unsigned int Observation::getNrBins() const {\n\treturn nrBins;\n}\n\ninline unsigned int Observation::getNrPaddedBins(unsigned int padding) const {\n\treturn isa::utils::pad(nrBins, padding);\n}\n\ninline unsigned int Observation::getFirstPeriod() const {\n\treturn firstPeriod;\n}\n\ninline unsigned int Observation::getLastPeriod() const {\n return lastPeriod;\n}\n\ninline unsigned int Observation::getPeriodStep() const {\n\treturn periodStep;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ OBSERVATION_HPP\n\n<commit_msg>Missing variable.<commit_after>\/\/ Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <limits>\n\n#include <utils.hpp>\n\n\n#ifndef OBSERVATION_HPP\n#define OBSERVATION_HPP\n\nnamespace AstroData {\n\nclass Observation {\npublic:\n Observation();\n ~Observation();\n\n \/\/ Getters\n \/\/ General observation parameters\n unsigned int getNrSeconds() const;\n unsigned int getNrStations() const;\n unsigned int getNrPaddedStations(unsigned int padding) const;\n unsigned int getNrBeams() const;\n unsigned int getNrPaddedBeams(unsigned int padding) const;\n unsigned int getNrSyntheticBeams() const;\n unsigned int getNrPaddedSyntheticBeams(const unsigned int padding) const;\n float getSamplingRate() const;\n unsigned int getNrSamplesPerBatch() const;\n unsigned int getNrSamplesPerPaddedBatch(unsigned int padding) const;\n\t\/\/ Frequency parameters\n unsigned int getNrSubbands() const;\n unsigned int getNrChannels() const;\n unsigned int getNrChannelsPerSubband() const;\n unsigned int getNrPaddedSubbands(unsigned int padding) const;\n unsigned int getNrPaddedChannels(unsigned int padding) const;\n unsigned int getNrZappedChannels() const;\n float getSubbandMinFreq() const;\n float getSubbandMaxFreq() const;\n float getSubbandBandwidth() const;\n float getMinFreq() const;\n float getMaxFreq() const;\n float getChannelBandwidth() const;\n\t\/\/ Dispersion measures\n unsigned int getNrSamplesPerBatchSubbanding() const;\n unsigned int getNrSamplesPerPaddedBatchSubbanding(unsigned int padding) const;\n unsigned int getNrDelaySecondsSubbanding() const;\n unsigned int getNrDelaySeconds() const;\n unsigned int getNrDMsSubbanding() const;\n unsigned int getNrDMs() const;\n unsigned int getNrPaddedDMsSubbanding(unsigned int padding) const;\n unsigned int getNrPaddedDMs(unsigned int padding) const;\n unsigned int getNrSamplesPerSubbandingDispersedChannel() const;\n unsigned int getNrSamplesPerDispersedChannel() const;\n unsigned int getNrSamplesPerPaddedSubbandingDispersedChannel(unsigned int padding) const;\n unsigned int getNrSamplesPerPaddedDispersedChannel(unsigned int padding) const;\n float getFirstDMSubbanding() const;\n float getFirstDM() const;\n float getLastDMSubbanding() const;\n float getLastDM() const;\n float getDMSubbandingStep() const;\n float getDMStep() const;\n\t\/\/ Periods\n unsigned int getNrPeriods() const;\n unsigned int getNrPaddedPeriods(unsigned int padding) const;\n unsigned int getFirstPeriod() const;\n unsigned int getLastPeriod() const;\n unsigned int getPeriodStep() const;\n unsigned int getNrBins() const;\n unsigned int getNrPaddedBins(unsigned int padding) const;\n\n \/\/ Setters\n \/\/ General observation parameters\n void setNrSeconds(const unsigned int seconds);\n void setNrStations(const unsigned int stations);\n void setNrBeams(const unsigned int beams);\n void setNrSyntheticBeams(const unsigned int beams);\n void setSamplingRate(const float sampling);\n void setNrSamplesPerBatch(const unsigned int samples);\n \/\/ Frequency parameters\n void setFrequencyRange(const unsigned int subbands, const unsigned int channels, const float baseFrequency, const float bandwidth);\n void setNrZappedChannels(const unsigned int zappedChannels);\n \/\/ Dispersion measures\n void setNrSamplesPerBatchSubbanding(const unsigned int samples);\n void setNrDelaySecondsSubbanding(const unsigned int seconds);\n void setNrDelaySeconds(const unsigned int seconds);\n void setNrSamplesPerSubbandingDispersedChannel(const unsigned int samples);\n void setNrSamplesPerDispersedChannel(const unsigned int samples);\n void setDMSubbandingRange(const unsigned int dms, const float baseDM, const float step);\n void setDMRange(const unsigned int dms, const float baseDM, const float step);\n \/\/ Periods\n void setPeriodRange(const unsigned int periods, const unsigned int basePeriod, const unsigned int step);\n void setNrBins(const unsigned int bins);\n\nprivate:\n unsigned int nrSeconds;\n unsigned int nrStations;\n unsigned int nrBeams;\n unsigned int nrSyntheticBeams;\n float samplingRate;\n unsigned int nrSamplesPerBatchSubbanding;\n unsigned int nrSamplesPerBatch;\n unsigned int nrSamplesPerDispersedChannel;\n unsigned int nrSamplesPerSubbandingDispersedChannel;\n\n unsigned int nrSubbands;\n unsigned int nrChannels;\n unsigned int nrChannelsPerSubband;\n unsigned int nrZappedChannels;\n float subbandMinFreq;\n float subbandMaxFreq;\n float subbandBandwidth;\n float minFreq;\n float maxFreq;\n float channelBandwidth;\n\n unsigned int nrDelaySecondsSubbanding;\n unsigned int nrDelaySeconds;\n unsigned int nrDMsSubbanding;\n unsigned int nrDMs;\n float firstDMSubbanding;\n float firstDM;\n float lastDMSubbanding;\n float lastDM;\n float DMSubbandingStep;\n float DMStep;\n\n unsigned int nrPeriods;\n unsigned int firstPeriod;\n unsigned int lastPeriod;\n unsigned int periodStep;\n unsigned int nrBins;\n};\n\n\/\/ Implementations\ninline unsigned int Observation::getNrSeconds() const {\n\treturn nrSeconds;\n}\n\ninline unsigned int Observation::getNrStations() const {\n\treturn nrStations;\n}\n\ninline unsigned int Observation::getNrPaddedStations(unsigned int padding) const {\n\treturn isa::utils::pad(nrStations, padding);\n}\n\ninline unsigned int Observation::getNrBeams() const {\n\treturn nrBeams;\n}\n\ninline unsigned int Observation::getNrPaddedBeams(unsigned int padding) const {\n\treturn isa::utils::pad(nrBeams, padding);\n}\n\ninline unsigned int Observation::getNrSyntheticBeams() const {\n return nrSyntheticBeams;\n}\n\ninline unsigned int Observation::getNrPaddedSyntheticBeams(unsigned int padding) const {\n return isa::utils::pad(nrSyntheticBeams, padding);\n}\n\ninline unsigned int Observation::getNrSamplesPerBatch() const {\n\treturn nrSamplesPerBatch;\n}\n\ninline float Observation::getSamplingRate() const {\n\treturn samplingRate;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedBatch(unsigned int padding) const {\n\treturn isa::utils::pad(nrSamplesPerBatch, padding);\n}\n\ninline unsigned int Observation::getNrSubbands() const {\n return nrSubbands;\n}\n\ninline unsigned int Observation::getNrChannels() const {\n\treturn nrChannels;\n}\n\ninline unsigned int Observation::getNrPaddedSubbands(unsigned int padding) const {\n\treturn isa::utils::pad(nrSubbands, padding);\n}\n\ninline unsigned int Observation::getNrPaddedChannels(unsigned int padding) const {\n\treturn isa::utils::pad(nrChannels, padding);\n}\n\ninline unsigned int Observation::getNrZappedChannels() const {\n return nrZappedChannels;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedDispersedChannel(unsigned int padding) const {\n return isa::utils::pad(nrSamplesPerDispersedChannel, padding);\n}\n\ninline float Observation::getSubbandMinFreq() const {\n return subbandMinFreq;\n}\n\ninline float Observation::getSubbandMaxFreq() const {\n return subbandMaxFreq;\n}\n\ninline float Observation::getSubbandBandwidth() const {\n return subbandBandwidth;\n}\n\ninline float Observation::getMinFreq() const {\n\treturn minFreq;\n}\n\ninline float Observation::getMaxFreq() const {\n\treturn maxFreq;\n}\n\ninline float Observation::getChannelBandwidth() const {\n\treturn channelBandwidth;\n}\n\ninline unsigned int Observation::getNrSamplesPerDispersedChannel() const {\n return nrSamplesPerDispersedChannel;\n}\n\ninline unsigned int Observation::getNrSamplesPerBatchSubbanding() const {\n return nrSamplesPerBatchSubbanding;\n}\n\ninline unsigned int Observation::getNrSamplesPerPaddedBatchSubbanding(unsigned int padding) const {\n\treturn isa::utils::pad(nrSamplesPerBatchSubbanding, padding);\n}\n\ninline unsigned int Observation::getNrDelaySecondsSubbanding() const {\n return nrDelaySecondsSubbanding;\n}\n\ninline unsigned int Observation::getNrDelaySeconds() const {\n return nrDelaySeconds;\n}\n\ninline unsigned int Observation::getNrDMsSubbanding() const {\n\treturn nrDMsSubbanding;\n}\n\ninline unsigned int Observation::getNrDMs() const {\n\treturn nrDMs;\n}\n\ninline unsigned int Observation::getNrPaddedDMsSubbanding(unsigned int padding) const {\n\treturn isa::utils::pad(nrDMsSubbanding, padding);\n}\n\ninline unsigned int Observation::getNrPaddedDMs(unsigned int padding) const {\n\treturn isa::utils::pad(nrDMs, padding);\n}\n\ninline float Observation::getFirstDMSubbanding() const {\n\treturn firstDMSubbanding;\n}\n\ninline float Observation::getFirstDM() const {\n\treturn firstDM;\n}\n\ninline float Observation::getLastDMSubbanding() const {\n return lastDMSubbanding;\n}\n\ninline float Observation::getLastDM() const {\n return lastDM;\n}\n\ninline float Observation::getDMSubbandingStep() const {\n\treturn DMSubbandingStep;\n}\n\ninline float Observation::getDMStep() const {\n\treturn DMStep;\n}\n\ninline unsigned int Observation::getNrPeriods() const {\n\treturn nrPeriods;\n}\n\ninline unsigned int Observation::getNrPaddedPeriods(unsigned int padding) const {\n\treturn isa::utils::pad(nrPeriods, padding);\n}\n\ninline unsigned int Observation::getNrBins() const {\n\treturn nrBins;\n}\n\ninline unsigned int Observation::getNrPaddedBins(unsigned int padding) const {\n\treturn isa::utils::pad(nrBins, padding);\n}\n\ninline unsigned int Observation::getFirstPeriod() const {\n\treturn firstPeriod;\n}\n\ninline unsigned int Observation::getLastPeriod() const {\n return lastPeriod;\n}\n\ninline unsigned int Observation::getPeriodStep() const {\n\treturn periodStep;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ OBSERVATION_HPP\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2013 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"tutorial\/tutorial.h\"\n#include \"tutorial\/obj_loader.h\"\n#include \"tutorial\/hair_loader.h\"\n#include \"sys\/taskscheduler.h\"\n#include \"image\/image.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"tutorial07\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static size_t g_numThreads = 0;\n\n static int tessellation_segments = -1;\n static int tessellation_strips = -1;\n\n \/* scene *\/\n OBJScene g_obj_scene;\n static FileName objFilename = \"\";\n static FileName hairFilename = \"\";\n static FileName outFilename = \"\";\n Vec3fa offset = 0.0f;\n\n static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model *\/\n else if (tag == \"-i\") {\n objFilename = path + cin->getFileName();\n }\n\n \/* load hair model *\/\n else if (tag == \"--hair\") {\n hairFilename = path + cin->getFileName();\n }\n\n \/* scene offset *\/\n else if (tag == \"--offset\") {\n offset = cin->getVec3fa();\n }\n\n \/* tessellation flags *\/\n else if (tag == \"--tessellate\") {\n tessellation_segments = cin->getInt();\n tessellation_strips = cin->getInt();\n }\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n \n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore = cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n \/* render image using ISPC *\/\n double t0 = getSeconds();\n render(0.0f,\n pixel2world.l.vx,\n pixel2world.l.vy,\n pixel2world.l.vz,\n pixel2world.p);\n double dt0 = getSeconds()-t0;\n\n void* ptr = map();\n Ref<Image> image = new Image4c(g_width, g_height, (Col4c*)ptr);\n storeImage(image, fileName);\n unmap();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* create stream for parsing *\/\n Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n if (g_numThreads) \n g_rtcore += \",threads=\" + std::stringOf(g_numThreads);\n\n \/* initialize task scheduler *\/\n#if !defined(__EXPORT_ALL_SYMBOLS__)\n TaskScheduler::create(g_numThreads);\n#endif\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n\n \/* load scene *\/\n if (objFilename.str() != \"\")\n loadOBJ(objFilename,g_obj_scene,offset);\n\n \/* load hair *\/\n if (hairFilename.str() != \"\")\n loadHair(hairFilename,g_obj_scene,offset);\n\n \/* send model *\/\n if (objFilename.str() != \"\" && hairFilename.str() != \"\")\n set_scene(&g_obj_scene);\n\n \/* render to disk *\/\n if (outFilename.str() != \"\") {\n renderToFile(outFilename);\n return 0;\n } \n\n \/* initialize GLUT *\/\n initGlut(tutorialName,g_width,g_height,g_fullscreen,true);\n \n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\n<commit_msg>started writing tessellation code for hair<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2013 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"tutorial\/tutorial.h\"\n#include \"tutorial\/obj_loader.h\"\n#include \"tutorial\/hair_loader.h\"\n#include \"sys\/taskscheduler.h\"\n#include \"image\/image.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"tutorial07\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static size_t g_numThreads = 0;\n\n static int tessellation_subdivisions = -1;\n static int tessellation_strips = -1;\n\n \/* scene *\/\n OBJScene g_obj_scene;\n static FileName objFilename = \"\";\n static FileName hairFilename = \"\";\n static FileName outFilename = \"\";\n Vec3fa offset = 0.0f;\n\n static void tessellateHair(OBJScene &scene);\n\n static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model *\/\n else if (tag == \"-i\") {\n objFilename = path + cin->getFileName();\n }\n\n \/* load hair model *\/\n else if (tag == \"--hair\") {\n hairFilename = path + cin->getFileName();\n }\n\n \/* scene offset *\/\n else if (tag == \"--offset\") {\n offset = cin->getVec3fa();\n }\n\n \/* tessellation flags *\/\n else if (tag == \"--tessellate\") {\n tessellation_subdivisions = cin->getInt();\n tessellation_strips = cin->getInt();\n }\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n \n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore = cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n\n void addHairSegment(OBJScene &scene, \n const vec3f &p00,\n const vec3f &p01)\n {\n \/* todo *\/\n }\n void tessellateHair(OBJScene &scene, \n const vec3f &p00,\n const vec3f &p01,\n const vec3f &p02,\n const vec3f &p03,\n int subdivisions)\n {\n vec3f p00 = hairSet.v[hair.vertex+0];\n vec3f p01 = hairSet.v[hair.vertex+1];\n vec3f p02 = hairSet.v[hair.vertex+2];\n vec3f p03 = hairSet.v[hair.vertex+3];\n if (subdivisions > 0) {\n const vec3f p10 = 0.5f*(p00+p01);\n const vec3f p11 = 0.5f*(p01+p02);\n const vec3f p12 = 0.5f*(p02+p03);\n\n const vec3f p20 = 0.5f*(p10+p11);\n const vec3f p21 = 0.5f*(p11+p12);\n\n const vec3f p30 = 0.5f*(p20+p21);\n \n tessellateHair(scene,p00,p10,p20,p30,subdivisions-1);\n tessellateHair(scene,p30,p21,p12,p03,subdivisions-1);\n } else {\n addHairSegment(scene,p00,p01);\n addHairSegment(scene,p01,p02);\n addHairSegment(scene,p02,p03);\n }\n }\n void tessellateHair(OBJScene &scene, \n OBJScene::HairSet &hairSet)\n {\n for (int i=0;i<hairSet.hair.size();i++) {\n OBJScene::Hair hair = hairSet.hairs[i];\n vec3f p00 = hairSet.v[hair.vertex+0];\n vec3f p01 = hairSet.v[hair.vertex+1];\n vec3f p02 = hairSet.v[hair.vertex+2];\n vec3f p03 = hairSet.v[hair.vertex+3];\n tessellateHair(scene,p00,p01,p02,p03,tessellate_subdivisions);\n }\n }\n void tessellateHair(OBJScene &scene)\n {\n for (int i=0;i<scene.hairsets.size();i++) \n tessellateHair(scene,scene.hairsets[i]);\n scene.hairsets.clear();\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n \/* render image using ISPC *\/\n double t0 = getSeconds();\n render(0.0f,\n pixel2world.l.vx,\n pixel2world.l.vy,\n pixel2world.l.vz,\n pixel2world.p);\n double dt0 = getSeconds()-t0;\n\n void* ptr = map();\n Ref<Image> image = new Image4c(g_width, g_height, (Col4c*)ptr);\n storeImage(image, fileName);\n unmap();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* create stream for parsing *\/\n Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n if (g_numThreads) \n g_rtcore += \",threads=\" + std::stringOf(g_numThreads);\n\n \/* initialize task scheduler *\/\n#if !defined(__EXPORT_ALL_SYMBOLS__)\n TaskScheduler::create(g_numThreads);\n#endif\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n\n \/* load scene *\/\n if (objFilename.str() != \"\")\n loadOBJ(objFilename,g_obj_scene,offset);\n\n \/* load hair *\/\n if (hairFilename.str() != \"\") {\n loadHair(hairFilename,g_obj_scene,offset);\n if (tessellate_subdivisions > 0 && tessellate_strips > 0)\n tessellateHair(g_obj_scene);\n }\n\n \/* send model *\/\n if (objFilename.str() != \"\" && hairFilename.str() != \"\")\n set_scene(&g_obj_scene);\n\n \/* render to disk *\/\n if (outFilename.str() != \"\") {\n renderToFile(outFilename);\n return 0;\n } \n\n \/* initialize GLUT *\/\n initGlut(tutorialName,g_width,g_height,g_fullscreen,true);\n \n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2009, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"OpenEXR\/ImathFun.h\"\n\n#include \"IECore\/CurvesPrimitiveEvaluator.h\"\n#include \"IECore\/CurvesPrimitive.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/FastFloat.h\"\n\nusing namespace IECore;\nusing namespace Imath;\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of Result\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCurvesPrimitiveEvaluator::Result::Result()\n{\n}\n\ntemplate<class T>\nT CurvesPrimitiveEvaluator::Result::primVar( const PrimitiveVariable &primVar, const float *coefficients ) const\n{\n\tswitch( primVar.interpolation )\n\t{\n\t\tcase PrimitiveVariable::Constant :\n\t\t\t{\n\t\t\t\tconst TypedData<T> *d = static_cast<TypedData<T> *>( primVar.data.get() );\n\t\t\t\treturn d->readable();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PrimitiveVariable::Uniform :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn d[m_curveIndex];\n\t\t\t}\n\t\tcase PrimitiveVariable::Vertex :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn\t(T)( coefficients[0] * d[m_vertexDataIndices[0]] +\n\t\t\t\t\t\tcoefficients[1] * d[m_vertexDataIndices[1]] +\n\t\t\t\t\t\tcoefficients[2] * d[m_vertexDataIndices[2]] +\n\t\t\t\t\t\tcoefficients[3] * d[m_vertexDataIndices[3]] );\n\t\t\t}\n\t\tcase PrimitiveVariable::Varying :\n\t\tcase PrimitiveVariable::FaceVarying :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn lerp( d[0], d[1], m_segmentV );\n\t\t\t}\n\t\tdefault :\n\t\t\tthrow InvalidArgumentException( \"PrimitiveVariable has invalid interpolation\" );\n\t}\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::point() const\n{\n\treturn primVar<V3f>( m_p, m_coefficients );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::normal() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V2f CurvesPrimitiveEvaluator::Result::uv() const\n{\n\treturn V2f( 0, m_v );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::uTangent() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::vTangent() const\n{\n\treturn primVar<V3f>( m_p, m_derivativeCoefficients );\n}\n\nunsigned CurvesPrimitiveEvaluator::Result::curveIndex() const\n{\n\treturn m_curveIndex;\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::vectorPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<V3f>( pv, m_coefficients );\n}\n\nfloat CurvesPrimitiveEvaluator::Result::floatPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<float>( pv, m_coefficients );\n}\n\nint CurvesPrimitiveEvaluator::Result::intPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<int>( pv, m_coefficients );\n}\n\nconst std::string &CurvesPrimitiveEvaluator::Result::stringPrimVar( const PrimitiveVariable &pv ) const\n{\n\tswitch( pv.interpolation )\n\t{\n\t\tcase PrimitiveVariable::Constant :\n\t\t\t{\n\t\t\t\tconst TypedData<string> *d = static_cast<TypedData<string> *>( pv.data.get() );\n\t\t\t\treturn d->readable();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PrimitiveVariable::Uniform :\n\t\t\t{\n\t\t\t\tconst vector<string> &d = static_cast<TypedData<vector<string> > *>( pv.data.get() )->readable();\n\t\t\t\treturn d[m_curveIndex];\n\t\t\t}\n\t\tdefault :\n\t\t\t{\n\t\t\t\tthrow InvalidArgumentException( \"Can only evaluate string PrimitiveVariables with Constant or Uniform interpolation.\" );\n\t\t\t}\n\t}\n}\n\nImath::Color3f CurvesPrimitiveEvaluator::Result::colorPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<Color3f>( pv, m_coefficients );\n}\n\nhalf CurvesPrimitiveEvaluator::Result::halfPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<half>( pv, m_coefficients );\n}\n\nvoid CurvesPrimitiveEvaluator::Result::init( unsigned curveIndex, float v, const CurvesPrimitiveEvaluator *evaluator )\n{\n\tm_curveIndex = curveIndex;\n\tm_v = v;\n\n\tunsigned numSegments = evaluator->m_curvesPrimitive->numSegments( m_curveIndex );\n\tfloat vv = v * numSegments;\n\tunsigned segment = min( (unsigned)fastFloatFloor( vv ), numSegments - 1 );\n\tm_segmentV = vv - segment;\n\t\n\tconst CubicBasisf &basis = evaluator->m_curvesPrimitive->basis();\n\tbasis.coefficients( m_segmentV, m_coefficients );\n\tbasis.derivativeCoefficients( m_segmentV, m_derivativeCoefficients );\n\t\n\tif( evaluator->m_curvesPrimitive->periodic() )\n\t{\n\t\tint numVertices = evaluator->m_verticesPerCurve[curveIndex];\n\t\tunsigned o = evaluator->m_vertexDataOffsets[m_curveIndex];\n\t\tunsigned i = segment * basis.step;\n\t\tm_vertexDataIndices[0] = o + i;\n\t\tm_vertexDataIndices[1] = o + ( ( i + 1 ) % numVertices );\n\t\tm_vertexDataIndices[2] = o + ( ( i + 2 ) % numVertices );\n\t\tm_vertexDataIndices[3] = o + ( ( i + 3 ) % numVertices );\n\t\t\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + segment;\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + ( segment % numSegments );\n\t}\n\telse\n\t{\n\t\tm_vertexDataIndices[0] = evaluator->m_vertexDataOffsets[m_curveIndex] + segment * basis.step;\n\t\tm_vertexDataIndices[1] = m_vertexDataIndices[0] + 1;\n\t\tm_vertexDataIndices[2] = m_vertexDataIndices[1] + 1;\n\t\tm_vertexDataIndices[3] = m_vertexDataIndices[2] + 1;\n\t\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + segment;\n\t\tm_varyingDataIndices[1] = m_varyingDataIndices[0] + 1;\n\t}\n}\n\t\t\t\t\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of Evaluator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCurvesPrimitiveEvaluator::CurvesPrimitiveEvaluator( ConstCurvesPrimitivePtr curves )\n\t:\tm_curvesPrimitive( curves->copy() ), m_verticesPerCurve( m_curvesPrimitive->verticesPerCurve()->readable() )\n{\n\tm_vertexDataOffsets.reserve( m_verticesPerCurve.size() );\n\tm_varyingDataOffsets.reserve( m_verticesPerCurve.size() );\n\tint vertexDataOffset = 0;\n\tint varyingDataOffset = 0;\n\tfor( unsigned i=0; i<m_verticesPerCurve.size(); i++ )\n\t{\n\t\tm_vertexDataOffsets.push_back( vertexDataOffset );\n\t\tvertexDataOffset += m_verticesPerCurve[i];\n\t\t\n\t\tm_varyingDataOffsets.push_back( varyingDataOffset );\n\t\tvaryingDataOffset += m_curvesPrimitive->variableSize( PrimitiveVariable::Varying, i );\n\t}\n\t\n\tPrimitiveVariableMap::iterator pIt = m_curvesPrimitive->variables.find( \"P\" );\n\tif( pIt==m_curvesPrimitive->variables.end() )\n\t{\n\t\tthrow InvalidArgumentException( \"No PrimitiveVariable named P on CurvesPrimitive.\" );\n\t}\n\tm_p = pIt->second;\n}\n\nCurvesPrimitiveEvaluator::~CurvesPrimitiveEvaluator()\n{\n}\n\nConstPrimitivePtr CurvesPrimitiveEvaluator::primitive() const\n{\n\treturn m_curvesPrimitive;\n}\n\nPrimitiveEvaluator::ResultPtr CurvesPrimitiveEvaluator::createResult() const\n{\n\tResult *result = new Result;\n\tresult->m_p = m_p;\n\treturn result;\n}\n\nvoid CurvesPrimitiveEvaluator::validateResult( const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tif( ! boost::dynamic_pointer_cast<CurvesPrimitiveEvaluator::Result>( result ) )\n\t{\n\t\tthrow InvalidArgumentException( \"CurvesPrimitiveEvaluator: Invalid result type\" );\n\t}\n}\n\nfloat CurvesPrimitiveEvaluator::surfaceArea() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nfloat CurvesPrimitiveEvaluator::volume() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::centerOfGravity() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::closestPoint( const Imath::V3f &p, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::pointAtUV( const Imath::V2f &uv, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\treturn pointAtV( 0, uv[1], result );\n}\n\nbool CurvesPrimitiveEvaluator::intersectionPoint( const Imath::V3f &origin, const Imath::V3f &direction,\n\tconst PrimitiveEvaluator::ResultPtr &result, float maxDistance ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nint CurvesPrimitiveEvaluator::intersectionPoints( const Imath::V3f &origin, const Imath::V3f &direction,\n\tstd::vector<PrimitiveEvaluator::ResultPtr> &results, float maxDistance ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::pointAtV( unsigned curveIndex, float v, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tif( curveIndex > m_verticesPerCurve.size() || v < 0.0f || v > 1.0f )\n\t{\n\t\treturn false;\n\t}\n\tResult *typedResult = static_cast<Result *>( result.get() );\n\ttypedResult->init( curveIndex, v, this );\n\treturn true;\n}\n<commit_msg>Fixed test failure caused by not registering the CurvesPrimitiveEvaluator with the RunTimeTyped base class.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2009, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"OpenEXR\/ImathFun.h\"\n\n#include \"IECore\/CurvesPrimitiveEvaluator.h\"\n#include \"IECore\/CurvesPrimitive.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/FastFloat.h\"\n\nusing namespace IECore;\nusing namespace Imath;\nusing namespace std;\n\nIE_CORE_DEFINERUNTIMETYPED( CurvesPrimitiveEvaluator );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of Result\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCurvesPrimitiveEvaluator::Result::Result()\n{\n}\n\ntemplate<class T>\nT CurvesPrimitiveEvaluator::Result::primVar( const PrimitiveVariable &primVar, const float *coefficients ) const\n{\n\tswitch( primVar.interpolation )\n\t{\n\t\tcase PrimitiveVariable::Constant :\n\t\t\t{\n\t\t\t\tconst TypedData<T> *d = static_cast<TypedData<T> *>( primVar.data.get() );\n\t\t\t\treturn d->readable();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PrimitiveVariable::Uniform :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn d[m_curveIndex];\n\t\t\t}\n\t\tcase PrimitiveVariable::Vertex :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn\t(T)( coefficients[0] * d[m_vertexDataIndices[0]] +\n\t\t\t\t\t\tcoefficients[1] * d[m_vertexDataIndices[1]] +\n\t\t\t\t\t\tcoefficients[2] * d[m_vertexDataIndices[2]] +\n\t\t\t\t\t\tcoefficients[3] * d[m_vertexDataIndices[3]] );\n\t\t\t}\n\t\tcase PrimitiveVariable::Varying :\n\t\tcase PrimitiveVariable::FaceVarying :\n\t\t\t{\n\t\t\t\tconst vector<T> &d = static_cast<TypedData<vector<T> > *>( primVar.data.get() )->readable();\n\t\t\t\treturn lerp( d[0], d[1], m_segmentV );\n\t\t\t}\n\t\tdefault :\n\t\t\tthrow InvalidArgumentException( \"PrimitiveVariable has invalid interpolation\" );\n\t}\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::point() const\n{\n\treturn primVar<V3f>( m_p, m_coefficients );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::normal() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V2f CurvesPrimitiveEvaluator::Result::uv() const\n{\n\treturn V2f( 0, m_v );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::uTangent() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::vTangent() const\n{\n\treturn primVar<V3f>( m_p, m_derivativeCoefficients );\n}\n\nunsigned CurvesPrimitiveEvaluator::Result::curveIndex() const\n{\n\treturn m_curveIndex;\n}\n\nImath::V3f CurvesPrimitiveEvaluator::Result::vectorPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<V3f>( pv, m_coefficients );\n}\n\nfloat CurvesPrimitiveEvaluator::Result::floatPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<float>( pv, m_coefficients );\n}\n\nint CurvesPrimitiveEvaluator::Result::intPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<int>( pv, m_coefficients );\n}\n\nconst std::string &CurvesPrimitiveEvaluator::Result::stringPrimVar( const PrimitiveVariable &pv ) const\n{\n\tswitch( pv.interpolation )\n\t{\n\t\tcase PrimitiveVariable::Constant :\n\t\t\t{\n\t\t\t\tconst TypedData<string> *d = static_cast<TypedData<string> *>( pv.data.get() );\n\t\t\t\treturn d->readable();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PrimitiveVariable::Uniform :\n\t\t\t{\n\t\t\t\tconst vector<string> &d = static_cast<TypedData<vector<string> > *>( pv.data.get() )->readable();\n\t\t\t\treturn d[m_curveIndex];\n\t\t\t}\n\t\tdefault :\n\t\t\t{\n\t\t\t\tthrow InvalidArgumentException( \"Can only evaluate string PrimitiveVariables with Constant or Uniform interpolation.\" );\n\t\t\t}\n\t}\n}\n\nImath::Color3f CurvesPrimitiveEvaluator::Result::colorPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<Color3f>( pv, m_coefficients );\n}\n\nhalf CurvesPrimitiveEvaluator::Result::halfPrimVar( const PrimitiveVariable &pv ) const\n{\n\treturn primVar<half>( pv, m_coefficients );\n}\n\nvoid CurvesPrimitiveEvaluator::Result::init( unsigned curveIndex, float v, const CurvesPrimitiveEvaluator *evaluator )\n{\n\tm_curveIndex = curveIndex;\n\tm_v = v;\n\n\tunsigned numSegments = evaluator->m_curvesPrimitive->numSegments( m_curveIndex );\n\tfloat vv = v * numSegments;\n\tunsigned segment = min( (unsigned)fastFloatFloor( vv ), numSegments - 1 );\n\tm_segmentV = vv - segment;\n\t\n\tconst CubicBasisf &basis = evaluator->m_curvesPrimitive->basis();\n\tbasis.coefficients( m_segmentV, m_coefficients );\n\tbasis.derivativeCoefficients( m_segmentV, m_derivativeCoefficients );\n\t\n\tif( evaluator->m_curvesPrimitive->periodic() )\n\t{\n\t\tint numVertices = evaluator->m_verticesPerCurve[curveIndex];\n\t\tunsigned o = evaluator->m_vertexDataOffsets[m_curveIndex];\n\t\tunsigned i = segment * basis.step;\n\t\tm_vertexDataIndices[0] = o + i;\n\t\tm_vertexDataIndices[1] = o + ( ( i + 1 ) % numVertices );\n\t\tm_vertexDataIndices[2] = o + ( ( i + 2 ) % numVertices );\n\t\tm_vertexDataIndices[3] = o + ( ( i + 3 ) % numVertices );\n\t\t\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + segment;\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + ( segment % numSegments );\n\t}\n\telse\n\t{\n\t\tm_vertexDataIndices[0] = evaluator->m_vertexDataOffsets[m_curveIndex] + segment * basis.step;\n\t\tm_vertexDataIndices[1] = m_vertexDataIndices[0] + 1;\n\t\tm_vertexDataIndices[2] = m_vertexDataIndices[1] + 1;\n\t\tm_vertexDataIndices[3] = m_vertexDataIndices[2] + 1;\n\t\n\t\tm_varyingDataIndices[0] = evaluator->m_varyingDataOffsets[m_curveIndex] + segment;\n\t\tm_varyingDataIndices[1] = m_varyingDataIndices[0] + 1;\n\t}\n}\n\t\t\t\t\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of Evaluator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCurvesPrimitiveEvaluator::CurvesPrimitiveEvaluator( ConstCurvesPrimitivePtr curves )\n\t:\tm_curvesPrimitive( curves->copy() ), m_verticesPerCurve( m_curvesPrimitive->verticesPerCurve()->readable() )\n{\n\tm_vertexDataOffsets.reserve( m_verticesPerCurve.size() );\n\tm_varyingDataOffsets.reserve( m_verticesPerCurve.size() );\n\tint vertexDataOffset = 0;\n\tint varyingDataOffset = 0;\n\tfor( unsigned i=0; i<m_verticesPerCurve.size(); i++ )\n\t{\n\t\tm_vertexDataOffsets.push_back( vertexDataOffset );\n\t\tvertexDataOffset += m_verticesPerCurve[i];\n\t\t\n\t\tm_varyingDataOffsets.push_back( varyingDataOffset );\n\t\tvaryingDataOffset += m_curvesPrimitive->variableSize( PrimitiveVariable::Varying, i );\n\t}\n\t\n\tPrimitiveVariableMap::iterator pIt = m_curvesPrimitive->variables.find( \"P\" );\n\tif( pIt==m_curvesPrimitive->variables.end() )\n\t{\n\t\tthrow InvalidArgumentException( \"No PrimitiveVariable named P on CurvesPrimitive.\" );\n\t}\n\tm_p = pIt->second;\n}\n\nCurvesPrimitiveEvaluator::~CurvesPrimitiveEvaluator()\n{\n}\n\nConstPrimitivePtr CurvesPrimitiveEvaluator::primitive() const\n{\n\treturn m_curvesPrimitive;\n}\n\nPrimitiveEvaluator::ResultPtr CurvesPrimitiveEvaluator::createResult() const\n{\n\tResult *result = new Result;\n\tresult->m_p = m_p;\n\treturn result;\n}\n\nvoid CurvesPrimitiveEvaluator::validateResult( const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tif( ! boost::dynamic_pointer_cast<CurvesPrimitiveEvaluator::Result>( result ) )\n\t{\n\t\tthrow InvalidArgumentException( \"CurvesPrimitiveEvaluator: Invalid result type\" );\n\t}\n}\n\nfloat CurvesPrimitiveEvaluator::surfaceArea() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nfloat CurvesPrimitiveEvaluator::volume() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nImath::V3f CurvesPrimitiveEvaluator::centerOfGravity() const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::closestPoint( const Imath::V3f &p, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::pointAtUV( const Imath::V2f &uv, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\treturn pointAtV( 0, uv[1], result );\n}\n\nbool CurvesPrimitiveEvaluator::intersectionPoint( const Imath::V3f &origin, const Imath::V3f &direction,\n\tconst PrimitiveEvaluator::ResultPtr &result, float maxDistance ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nint CurvesPrimitiveEvaluator::intersectionPoints( const Imath::V3f &origin, const Imath::V3f &direction,\n\tstd::vector<PrimitiveEvaluator::ResultPtr> &results, float maxDistance ) const\n{\n\tthrow NotImplementedException( __PRETTY_FUNCTION__ );\n}\n\nbool CurvesPrimitiveEvaluator::pointAtV( unsigned curveIndex, float v, const PrimitiveEvaluator::ResultPtr &result ) const\n{\n\tif( curveIndex > m_verticesPerCurve.size() || v < 0.0f || v > 1.0f )\n\t{\n\t\treturn false;\n\t}\n\tResult *typedResult = static_cast<Result *>( result.get() );\n\ttypedResult->init( curveIndex, v, this );\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FuseGPUThreadLoops.h\"\n#include \"CodeGen_GPU_Dev.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Bounds.h\"\n#include \"Substitute.h\"\n#include \"IREquality.h\"\n#include \"Simplify.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::vector;\nusing std::string;\nusing std::set;\n\nnamespace {\nstring thread_names[] = {\"threadidx\", \"threadidy\", \"threadidz\", \"threadidw\"};\nstring shared_mem_name = \"__shared__\";\n}\n\nclass InjectThreadBarriers : public IRMutator {\n bool in_threads;\n\n using IRMutator::visit;\n\n void visit(const For *op) {\n bool old_in_threads = in_threads;\n\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n in_threads = true;\n }\n\n IRMutator::visit(op);\n\n in_threads = old_in_threads;\n }\n\n Stmt barrier() {\n return Evaluate::make(Call::make(Int(32), Call::gpu_thread_barrier, vector<Expr>(), Call::Intrinsic));\n }\n\n void visit(const Pipeline *op) {\n if (!in_threads) {\n Stmt produce = mutate(op->produce);\n produce = Block::make(produce, barrier());\n\n Stmt update;\n if (op->update.defined()) {\n update = mutate(op->update);\n update = Block::make(update, barrier());\n }\n\n Stmt consume = mutate(op->consume);\n\n stmt = Pipeline::make(op->name, produce, update, consume);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Block *op) {\n if (!in_threads && op->rest.defined()) {\n Stmt first = mutate(op->first);\n Stmt rest = mutate(op->rest);\n stmt = Block::make(Block::make(first, barrier()), rest);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n InjectThreadBarriers() : in_threads(false) {}\n};\n\n\nclass ExtractBlockSize : public IRVisitor {\n Expr block_extent[4];\n\n using IRVisitor::visit;\n\n void found_for(int dim, Expr extent) {\n internal_assert(dim >= 0 && dim < 4);\n if (!block_extent[dim].defined()) {\n block_extent[dim] = extent;\n } else {\n block_extent[dim] = simplify(Max::make(extent, block_extent[dim]));\n }\n }\n\n void visit(const For *op) {\n for (int i = 0; i < 4; i++) {\n if (ends_with(op->name, thread_names[i])) {\n found_for(i, op->extent);\n }\n }\n\n IRVisitor::visit(op);\n }\n\npublic:\n int dimensions() const {\n for (int i = 0; i < 4; i++) {\n if (!block_extent[i].defined()) {\n return i;\n }\n }\n return 4;\n }\n\n Expr extent(int d) const {\n return block_extent[d];\n }\n};\n\nclass NormalizeDimensionality : public IRMutator {\n using IRMutator::visit;\n\n const ExtractBlockSize &block_size;\n\n int depth;\n int max_depth;\n\n bool should_wrap;\n\n\n Stmt wrap(Stmt s) {\n if (depth != 0 || !should_wrap) {\n return s;\n }\n max_depth = 0;\n should_wrap = false;\n s = mutate(s);\n while (max_depth < block_size.dimensions()) {\n string name = thread_names[max_depth];\n s = For::make(name, 0, 1, For::Parallel, s);\n max_depth++;\n }\n should_wrap = true;\n return s;\n }\n\n void visit(const Pipeline *op) {\n Stmt produce = wrap(op->produce);\n Stmt update;\n if (op->update.defined()) {\n update = wrap(op->update);\n }\n Stmt consume = wrap(op->consume);\n\n if (produce.same_as(op->produce) &&\n update.same_as(op->update) &&\n consume.same_as(op->consume)) {\n stmt = op;\n } else {\n stmt = Pipeline::make(op->name, produce, update, consume);\n }\n }\n\n void visit(const Block *op) {\n Stmt first = wrap(op->first);\n\n Stmt rest;\n if (op->rest.defined()) {\n rest = wrap(op->rest);\n }\n\n if (first.same_as(op->first) &&\n rest.same_as(op->rest)) {\n stmt = op;\n } else {\n stmt = Block::make(first, rest);\n }\n }\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n depth++;\n if (depth > max_depth) {\n max_depth = depth;\n }\n if (!is_zero(op->min)) {\n \/\/ Shift them all to be zero-based.\n Expr var = Variable::make(Int(32), op->name);\n Stmt body = substitute(op->name, var + op->min, op->body);\n body = mutate(body);\n stmt = For::make(op->name, 0, op->extent, For::Parallel, body);\n } else {\n IRMutator::visit(op);\n }\n depth--;\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n NormalizeDimensionality(const ExtractBlockSize &e) : block_size(e), depth(0), max_depth(0), should_wrap(true) {}\n};\n\nclass ReplaceForWithIf : public IRMutator {\n using IRMutator::visit;\n\n const ExtractBlockSize &block_size;\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n int dim;\n for (dim = 0; dim < 4; dim++) {\n if (ends_with(op->name, thread_names[dim])) {\n break;\n }\n }\n\n internal_assert(dim >= 0 && dim < block_size.dimensions());\n\n Expr var = Variable::make(Int(32), \".\" + thread_names[dim]);\n internal_assert(is_zero(op->min));\n Stmt body = mutate(op->body);\n\n body = substitute(op->name, var, body);\n\n if (equal(op->extent, block_size.extent(dim))) {\n stmt = body;\n } else {\n Expr cond = var < op->extent;\n stmt = IfThenElse::make(cond, body, Stmt());\n }\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceForWithIf(const ExtractBlockSize &e) : block_size(e) {}\n};\n\nclass ExtractSharedAllocations : public IRMutator {\n\n using IRMutator::visit;\n\n struct SharedAllocation {\n string name;\n Type type;\n Expr size;\n };\n vector<SharedAllocation> allocations;\n\n Scope<Interval> scope;\n\n set<string> shared;\n\n bool in_threads;\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n bool old = in_threads;\n in_threads = true;\n IRMutator::visit(op);\n in_threads = old;\n } else {\n Interval min_bounds = bounds_of_expr_in_scope(op->min, scope);\n Interval extent_bounds = bounds_of_expr_in_scope(op->extent, scope);\n Interval bounds(min_bounds.min, min_bounds.max + extent_bounds.max - 1);\n scope.push(op->name, bounds);\n IRMutator::visit(op);\n scope.pop(op->name);\n }\n }\n\n void visit(const Allocate *op) {\n if (in_threads) {\n IRMutator::visit(op);\n return;\n }\n\n shared.insert(op->name);\n IRMutator::visit(op);\n shared.erase(op->name);\n op = stmt.as<Allocate>();\n internal_assert(op);\n\n SharedAllocation alloc;\n alloc.name = op->name;\n alloc.type = op->type;\n alloc.size = 1;\n for (size_t i = 0; i < op->extents.size(); i++) {\n alloc.size *= bounds_of_expr_in_scope(op->extents[i], scope).max;\n }\n allocations.push_back(alloc);\n stmt = op->body;\n\n }\n\n void visit(const Load *op) {\n if (shared.count(op->name)) {\n Expr base = Variable::make(Int(32), op->name + \".shared_offset\");\n Expr index = mutate(op->index);\n expr = Load::make(op->type, shared_mem_name, base + index, op->image, op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n if (shared.count(op->name)) {\n Expr base = Variable::make(Int(32), op->name + \".shared_offset\");\n Expr index = mutate(op->index);\n Expr value = mutate(op->value);\n stmt = Store::make(shared_mem_name, value, base + index);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *op) {\n if (in_threads) {\n IRMutator::visit(op);\n return;\n }\n\n Expr value = mutate(op->value);\n Interval bounds = bounds_of_expr_in_scope(value, scope);\n scope.push(op->name, bounds);\n Stmt body = mutate(op->body);\n scope.pop(op->name);\n\n if (op->body.same_as(body) && op->value.same_as(value)) {\n stmt = op;\n } else {\n stmt = LetStmt::make(op->name, value, body);\n }\n }\n\npublic:\n Stmt rewrap(Stmt s) {\n \/\/ Sort the allocations by size in bytes of the primitive\n \/\/ type. Use reverse insertion sort.\n for (size_t i = 1; i < allocations.size(); i++) {\n for (size_t j = i; j > 0; j--) {\n if (allocations[j].type.bytes() > allocations[j - 1].type.bytes()) {\n std::swap(allocations[j], allocations[j - 1]);\n }\n }\n }\n\n \/\/ Add a dummy allocation at the end to get the total size\n SharedAllocation sentinel;\n sentinel.name = \"sentinel\";\n sentinel.type = UInt(8);\n sentinel.size = 0;\n allocations.push_back(sentinel);\n\n Expr total_size = Variable::make(Int(32), allocations.back().name + \".shared_offset\");\n s = Allocate::make(shared_mem_name, UInt(8), vec(total_size), s);\n\n \/\/ Define an offset for each allocation. The offsets are in\n \/\/ elements, not bytes, so that the stores and loads can use\n \/\/ them directly.\n for (int i = (int)(allocations.size()) - 1; i >= 0; i--) {\n Expr offset = 0;\n if (i > 0) {\n offset = Variable::make(Int(32), allocations[i-1].name + \".shared_offset\");\n offset += allocations[i-1].size;\n int old_elem_size = allocations[i-1].type.bytes();\n int new_elem_size = allocations[i].type.bytes();\n internal_assert(old_elem_size >= new_elem_size);\n if (old_elem_size != new_elem_size) {\n \/\/ We only have power-of-two sized types.\n internal_assert(old_elem_size % new_elem_size == 0);\n offset *= (old_elem_size \/ new_elem_size);\n }\n }\n\n s = LetStmt::make(allocations[i].name + \".shared_offset\", offset, s);\n }\n\n return s;\n }\n\n ExtractSharedAllocations() : in_threads(false) {}\n};\n\nclass FuseGPUThreadLoops : public IRMutator {\n using IRMutator::visit;\n\n void visit(const For *op) {\n if (ends_with(op->name, \".blockidx\")) {\n\n Stmt body = op->body;\n\n ExtractBlockSize e;\n body.accept(&e);\n\n debug(3) << \"Fusing thread block:\\n\" << body << \"\\n\\n\";\n\n NormalizeDimensionality n(e);\n body = n.mutate(body);\n\n debug(3) << \"Normalized dimensionality:\\n\" << body << \"\\n\\n\";\n\n ExtractSharedAllocations h;\n body = h.mutate(body);\n\n debug(3) << \"Pulled out shared allocations:\\n\" << body << \"\\n\\n\";\n\n InjectThreadBarriers i;\n body = i.mutate(body);\n\n debug(3) << \"Injected synchronization:\\n\" << body << \"\\n\\n\";\n\n ReplaceForWithIf f(e);\n body = f.mutate(body);\n\n debug(3) << \"Replaced for with if:\\n\" << body << \"\\n\\n\";\n\n \/\/ Rewrap the whole thing in the loop over threads\n for (int i = 0; i < e.dimensions(); i++) {\n body = For::make(\".\" + thread_names[i], 0, e.extent(i), For::Parallel, body);\n }\n\n \/\/ There at least needs to be a loop over threadidx as a marker for codegen\n if (e.dimensions() == 0) {\n body = For::make(\".threadidx\", 0, 1, For::Parallel, body);\n }\n\n debug(3) << \"Rewrapped in for loops:\\n\" << body << \"\\n\\n\";\n\n \/\/ Add back in the shared allocations\n body = h.rewrap(body);\n\n debug(3) << \"Add back in shared allocations:\\n\" << body << \"\\n\\n\";\n\n if (body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, body);\n }\n } else {\n IRMutator::visit(op);\n }\n\n \/\/ Shift the min to be zero\n if (CodeGen_GPU_Dev::is_gpu_var(op->name) && !is_zero(op->min)) {\n op = stmt.as<For>();\n internal_assert(op);\n Expr adjusted = Variable::make(Int(32), op->name) + op->min;\n Stmt body = substitute(op->name, adjusted, op->body);\n stmt = For::make(op->name, 0, op->extent, op->for_type, body);\n }\n }\n};\n\n\nStmt fuse_gpu_thread_loops(Stmt s) {\n FuseGPUThreadLoops f;\n return f.mutate(s);\n}\n\n}\n}\n\n\n<commit_msg>Fix bug in dimensionality normalization for gpu loops<commit_after>#include \"FuseGPUThreadLoops.h\"\n#include \"CodeGen_GPU_Dev.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Bounds.h\"\n#include \"Substitute.h\"\n#include \"IREquality.h\"\n#include \"Simplify.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::vector;\nusing std::string;\nusing std::set;\n\nnamespace {\nstring thread_names[] = {\"threadidx\", \"threadidy\", \"threadidz\", \"threadidw\"};\nstring shared_mem_name = \"__shared__\";\n}\n\nclass InjectThreadBarriers : public IRMutator {\n bool in_threads;\n\n using IRMutator::visit;\n\n void visit(const For *op) {\n bool old_in_threads = in_threads;\n\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n in_threads = true;\n }\n\n IRMutator::visit(op);\n\n in_threads = old_in_threads;\n }\n\n Stmt barrier() {\n return Evaluate::make(Call::make(Int(32), Call::gpu_thread_barrier, vector<Expr>(), Call::Intrinsic));\n }\n\n void visit(const Pipeline *op) {\n if (!in_threads) {\n Stmt produce = mutate(op->produce);\n produce = Block::make(produce, barrier());\n\n Stmt update;\n if (op->update.defined()) {\n update = mutate(op->update);\n update = Block::make(update, barrier());\n }\n\n Stmt consume = mutate(op->consume);\n\n stmt = Pipeline::make(op->name, produce, update, consume);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Block *op) {\n if (!in_threads && op->rest.defined()) {\n Stmt first = mutate(op->first);\n Stmt rest = mutate(op->rest);\n stmt = Block::make(Block::make(first, barrier()), rest);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n InjectThreadBarriers() : in_threads(false) {}\n};\n\n\nclass ExtractBlockSize : public IRVisitor {\n Expr block_extent[4];\n\n using IRVisitor::visit;\n\n void found_for(int dim, Expr extent) {\n internal_assert(dim >= 0 && dim < 4);\n if (!block_extent[dim].defined()) {\n block_extent[dim] = extent;\n } else {\n block_extent[dim] = simplify(Max::make(extent, block_extent[dim]));\n }\n }\n\n void visit(const For *op) {\n for (int i = 0; i < 4; i++) {\n if (ends_with(op->name, thread_names[i])) {\n found_for(i, op->extent);\n }\n }\n\n IRVisitor::visit(op);\n }\n\npublic:\n int dimensions() const {\n for (int i = 0; i < 4; i++) {\n if (!block_extent[i].defined()) {\n return i;\n }\n }\n return 4;\n }\n\n Expr extent(int d) const {\n return block_extent[d];\n }\n};\n\nclass NormalizeDimensionality : public IRMutator {\n using IRMutator::visit;\n\n const ExtractBlockSize &block_size;\n\n int depth;\n int max_depth;\n\n Stmt wrap(Stmt s) {\n if (depth != 0) {\n return mutate(s);\n }\n max_depth = 0;\n s = mutate(s);\n while (max_depth < block_size.dimensions()) {\n string name = thread_names[max_depth];\n s = For::make(name, 0, 1, For::Parallel, s);\n max_depth++;\n }\n return s;\n }\n\n void visit(const Pipeline *op) {\n Stmt produce = wrap(op->produce);\n Stmt update;\n if (op->update.defined()) {\n update = wrap(op->update);\n }\n Stmt consume = wrap(op->consume);\n\n if (produce.same_as(op->produce) &&\n update.same_as(op->update) &&\n consume.same_as(op->consume)) {\n stmt = op;\n } else {\n stmt = Pipeline::make(op->name, produce, update, consume);\n }\n }\n\n void visit(const Block *op) {\n Stmt first = wrap(op->first);\n\n Stmt rest;\n if (op->rest.defined()) {\n rest = wrap(op->rest);\n }\n\n if (first.same_as(op->first) &&\n rest.same_as(op->rest)) {\n stmt = op;\n } else {\n stmt = Block::make(first, rest);\n }\n }\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n depth++;\n if (depth > max_depth) {\n max_depth = depth;\n }\n if (!is_zero(op->min)) {\n \/\/ Shift them all to be zero-based.\n Expr var = Variable::make(Int(32), op->name);\n Stmt body = substitute(op->name, var + op->min, op->body);\n body = mutate(body);\n stmt = For::make(op->name, 0, op->extent, For::Parallel, body);\n } else {\n IRMutator::visit(op);\n }\n depth--;\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n NormalizeDimensionality(const ExtractBlockSize &e) : block_size(e), depth(0), max_depth(0) {}\n};\n\nclass ReplaceForWithIf : public IRMutator {\n using IRMutator::visit;\n\n const ExtractBlockSize &block_size;\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n int dim;\n for (dim = 0; dim < 4; dim++) {\n if (ends_with(op->name, thread_names[dim])) {\n break;\n }\n }\n\n internal_assert(dim >= 0 && dim < block_size.dimensions());\n\n Expr var = Variable::make(Int(32), \".\" + thread_names[dim]);\n internal_assert(is_zero(op->min));\n Stmt body = mutate(op->body);\n\n body = substitute(op->name, var, body);\n\n if (equal(op->extent, block_size.extent(dim))) {\n stmt = body;\n } else {\n Expr cond = var < op->extent;\n stmt = IfThenElse::make(cond, body, Stmt());\n }\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceForWithIf(const ExtractBlockSize &e) : block_size(e) {}\n};\n\nclass ExtractSharedAllocations : public IRMutator {\n\n using IRMutator::visit;\n\n struct SharedAllocation {\n string name;\n Type type;\n Expr size;\n };\n vector<SharedAllocation> allocations;\n\n Scope<Interval> scope;\n\n set<string> shared;\n\n bool in_threads;\n\n void visit(const For *op) {\n if (CodeGen_GPU_Dev::is_gpu_thread_var(op->name)) {\n bool old = in_threads;\n in_threads = true;\n IRMutator::visit(op);\n in_threads = old;\n } else {\n Interval min_bounds = bounds_of_expr_in_scope(op->min, scope);\n Interval extent_bounds = bounds_of_expr_in_scope(op->extent, scope);\n Interval bounds(min_bounds.min, min_bounds.max + extent_bounds.max - 1);\n scope.push(op->name, bounds);\n IRMutator::visit(op);\n scope.pop(op->name);\n }\n }\n\n void visit(const Allocate *op) {\n if (in_threads) {\n IRMutator::visit(op);\n return;\n }\n\n shared.insert(op->name);\n IRMutator::visit(op);\n shared.erase(op->name);\n op = stmt.as<Allocate>();\n internal_assert(op);\n\n SharedAllocation alloc;\n alloc.name = op->name;\n alloc.type = op->type;\n alloc.size = 1;\n for (size_t i = 0; i < op->extents.size(); i++) {\n alloc.size *= bounds_of_expr_in_scope(op->extents[i], scope).max;\n }\n allocations.push_back(alloc);\n stmt = op->body;\n\n }\n\n void visit(const Load *op) {\n if (shared.count(op->name)) {\n Expr base = Variable::make(Int(32), op->name + \".shared_offset\");\n Expr index = mutate(op->index);\n expr = Load::make(op->type, shared_mem_name, base + index, op->image, op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n if (shared.count(op->name)) {\n Expr base = Variable::make(Int(32), op->name + \".shared_offset\");\n Expr index = mutate(op->index);\n Expr value = mutate(op->value);\n stmt = Store::make(shared_mem_name, value, base + index);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *op) {\n if (in_threads) {\n IRMutator::visit(op);\n return;\n }\n\n Expr value = mutate(op->value);\n Interval bounds = bounds_of_expr_in_scope(value, scope);\n scope.push(op->name, bounds);\n Stmt body = mutate(op->body);\n scope.pop(op->name);\n\n if (op->body.same_as(body) && op->value.same_as(value)) {\n stmt = op;\n } else {\n stmt = LetStmt::make(op->name, value, body);\n }\n }\n\npublic:\n Stmt rewrap(Stmt s) {\n \/\/ Sort the allocations by size in bytes of the primitive\n \/\/ type. Use reverse insertion sort.\n for (size_t i = 1; i < allocations.size(); i++) {\n for (size_t j = i; j > 0; j--) {\n if (allocations[j].type.bytes() > allocations[j - 1].type.bytes()) {\n std::swap(allocations[j], allocations[j - 1]);\n }\n }\n }\n\n \/\/ Add a dummy allocation at the end to get the total size\n SharedAllocation sentinel;\n sentinel.name = \"sentinel\";\n sentinel.type = UInt(8);\n sentinel.size = 0;\n allocations.push_back(sentinel);\n\n Expr total_size = Variable::make(Int(32), allocations.back().name + \".shared_offset\");\n s = Allocate::make(shared_mem_name, UInt(8), vec(total_size), s);\n\n \/\/ Define an offset for each allocation. The offsets are in\n \/\/ elements, not bytes, so that the stores and loads can use\n \/\/ them directly.\n for (int i = (int)(allocations.size()) - 1; i >= 0; i--) {\n Expr offset = 0;\n if (i > 0) {\n offset = Variable::make(Int(32), allocations[i-1].name + \".shared_offset\");\n offset += allocations[i-1].size;\n int old_elem_size = allocations[i-1].type.bytes();\n int new_elem_size = allocations[i].type.bytes();\n internal_assert(old_elem_size >= new_elem_size);\n if (old_elem_size != new_elem_size) {\n \/\/ We only have power-of-two sized types.\n internal_assert(old_elem_size % new_elem_size == 0);\n offset *= (old_elem_size \/ new_elem_size);\n }\n }\n\n s = LetStmt::make(allocations[i].name + \".shared_offset\", offset, s);\n }\n\n return s;\n }\n\n ExtractSharedAllocations() : in_threads(false) {}\n};\n\nclass FuseGPUThreadLoops : public IRMutator {\n using IRMutator::visit;\n\n void visit(const For *op) {\n if (ends_with(op->name, \".blockidx\")) {\n\n Stmt body = op->body;\n\n ExtractBlockSize e;\n body.accept(&e);\n\n debug(3) << \"Fusing thread block:\\n\" << body << \"\\n\\n\";\n\n NormalizeDimensionality n(e);\n body = n.mutate(body);\n\n debug(3) << \"Normalized dimensionality:\\n\" << body << \"\\n\\n\";\n\n ExtractSharedAllocations h;\n body = h.mutate(body);\n\n debug(3) << \"Pulled out shared allocations:\\n\" << body << \"\\n\\n\";\n\n InjectThreadBarriers i;\n body = i.mutate(body);\n\n debug(3) << \"Injected synchronization:\\n\" << body << \"\\n\\n\";\n\n ReplaceForWithIf f(e);\n body = f.mutate(body);\n\n debug(3) << \"Replaced for with if:\\n\" << body << \"\\n\\n\";\n\n \/\/ Rewrap the whole thing in the loop over threads\n for (int i = 0; i < e.dimensions(); i++) {\n body = For::make(\".\" + thread_names[i], 0, e.extent(i), For::Parallel, body);\n }\n\n \/\/ There at least needs to be a loop over threadidx as a marker for codegen\n if (e.dimensions() == 0) {\n body = For::make(\".threadidx\", 0, 1, For::Parallel, body);\n }\n\n debug(3) << \"Rewrapped in for loops:\\n\" << body << \"\\n\\n\";\n\n \/\/ Add back in the shared allocations\n body = h.rewrap(body);\n\n debug(3) << \"Add back in shared allocations:\\n\" << body << \"\\n\\n\";\n\n if (body.same_as(op->body)) {\n stmt = op;\n } else {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, body);\n }\n } else {\n IRMutator::visit(op);\n }\n\n \/\/ Shift the min to be zero\n if (CodeGen_GPU_Dev::is_gpu_var(op->name) && !is_zero(op->min)) {\n op = stmt.as<For>();\n internal_assert(op);\n Expr adjusted = Variable::make(Int(32), op->name) + op->min;\n Stmt body = substitute(op->name, adjusted, op->body);\n stmt = For::make(op->name, 0, op->extent, op->for_type, body);\n }\n }\n};\n\n\nStmt fuse_gpu_thread_loops(Stmt s) {\n FuseGPUThreadLoops f;\n return f.mutate(s);\n}\n\n}\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input;\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n char c = (char) getchar();\n if (c == '\\n') {\n *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n\n memset(&input, 0, SAY_MAX + 1);;\n strncpy(input, stdin_buffer, sizeof(stdin_buffer));\n memset(&stdin_buffer, 0, SAY_MAX + 1);\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input);\n }\n\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n *stdin_buffer_position++ = c;\n printf(\"%c\", c);\n\/\/ std::cout << c << std::endl;\n fflush(stdout);\n }\n } \/\/ end of if STDIN_FILENO\n\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << stdin_buffer << std::flush;\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<commit_msg>remove all that<commit_after>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input;\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n char c = (char) getchar();\n if (c == '\\n') {\n *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n\n\/\/ memset(&input, 0, SAY_MAX + 1);;\n\/\/ strncpy(input, stdin_buffer, sizeof(stdin_buffer));\n\/\/ memset(&stdin_buffer, 0, SAY_MAX + 1);\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input);\n }\n\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n *stdin_buffer_position++ = c;\n printf(\"%c\", c);\n\/\/ std::cout << c << std::endl;\n fflush(stdout);\n }\n } \/\/ end of if STDIN_FILENO\n\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << stdin_buffer << std::flush;\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkImage.h\"\n#include \"include\/core\/SkStream.h\"\n#include \"src\/core\/SkCompressedDataUtils.h\"\n#include \"src\/core\/SkMipMap.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/gl\/GrGLDefines.h\"\n#include \"src\/image\/SkImage_Base.h\"\n\n#include \"tools\/Resources.h\"\n\n\/\/-------------------------------------------------------------------------------------------------\nstruct ImageInfo {\n SkISize fDim;\n GrMipMapped fMipMapped;\n SkImage::CompressionType fCompressionType;\n};\n\n\/*\n * Get an int from a buffer\n * This method is unsafe, the caller is responsible for performing a check\n *\/\nstatic inline uint32_t get_uint(uint8_t* buffer, uint32_t i) {\n uint32_t result;\n memcpy(&result, &(buffer[i]), 4);\n return result;\n}\n\n\/\/ This KTX loader is barely sufficient to load the specific files this GM requires. Use\n\/\/ at your own peril.\nstatic sk_sp<SkData> load_ktx(const char* filename, ImageInfo* imageInfo) {\n SkFILEStream input(filename);\n if (!input.isValid()) {\n return nullptr;\n }\n\n constexpr int kKTXIdentifierSize = 12;\n constexpr int kKTXHeaderSize = kKTXIdentifierSize + 13 * sizeof(uint32_t);\n uint8_t header[kKTXHeaderSize];\n\n if (input.read(header, kKTXHeaderSize) != kKTXHeaderSize) {\n return nullptr;\n }\n\n static const uint8_t kExpectedIdentifier[kKTXIdentifierSize] = {\n 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A\n };\n\n if (memcmp(header, kExpectedIdentifier, kKTXIdentifierSize)) {\n return nullptr;\n }\n\n uint32_t endianness = get_uint(header, 12);\n if (endianness != 0x04030201) {\n \/\/ TODO: need to swap rest of header and, if glTypeSize is > 1, all\n \/\/ the texture data.\n return nullptr;\n }\n\n uint32_t glType = get_uint(header, 16);\n SkDEBUGCODE(uint32_t glTypeSize = get_uint(header, 20);)\n uint32_t glFormat = get_uint(header, 24);\n uint32_t glInternalFormat = get_uint(header, 28);\n \/\/uint32_t glBaseInternalFormat = get_uint(header, 32);\n uint32_t pixelWidth = get_uint(header, 36);\n uint32_t pixelHeight = get_uint(header, 40);\n uint32_t pixelDepth = get_uint(header, 44);\n \/\/uint32_t numberOfArrayElements = get_uint(header, 48);\n uint32_t numberOfFaces = get_uint(header, 52);\n int numberOfMipmapLevels = get_uint(header, 56);\n uint32_t bytesOfKeyValueData = get_uint(header, 60);\n\n if (glType != 0 || glFormat != 0) { \/\/ only care about compressed data for now\n return nullptr;\n }\n SkASSERT(glTypeSize == 1); \/\/ required for compressed data\n\n \/\/ We only handle these four formats right now\n switch (glInternalFormat) {\n case GR_GL_COMPRESSED_ETC1_RGB8:\n case GR_GL_COMPRESSED_RGB8_ETC2:\n imageInfo->fCompressionType = SkImage::CompressionType::kETC2_RGB8_UNORM;\n break;\n case GR_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGB8_UNORM;\n break;\n case GR_GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGBA8_UNORM;\n break;\n default:\n return nullptr;\n }\n\n imageInfo->fDim.fWidth = pixelWidth;\n imageInfo->fDim.fHeight = pixelHeight;\n\n if (pixelDepth != 0) {\n return nullptr; \/\/ pixel depth is always zero for 2D textures\n }\n\n if (numberOfFaces != 1) {\n return nullptr; \/\/ we don't support cube maps right now\n }\n\n if (numberOfMipmapLevels == 1) {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n } else {\n int numRequiredMipLevels = SkMipMap::ComputeLevelCount(pixelWidth, pixelHeight)+1;\n if (numberOfMipmapLevels != numRequiredMipLevels) {\n return nullptr;\n }\n imageInfo->fMipMapped = GrMipMapped::kYes;\n }\n\n if (bytesOfKeyValueData != 0) {\n return nullptr;\n }\n\n SkTArray<size_t> individualMipOffsets(numberOfMipmapLevels);\n\n size_t dataSize = SkCompressedDataSize(imageInfo->fCompressionType,\n { (int) pixelWidth, (int) pixelHeight },\n &individualMipOffsets,\n imageInfo->fMipMapped == GrMipMapped::kYes);\n SkASSERT(individualMipOffsets.size() == (size_t) numberOfMipmapLevels);\n\n sk_sp<SkData> data = SkData::MakeUninitialized(dataSize);\n\n uint8_t* dest = (uint8_t*) data->writable_data();\n\n size_t offset = 0;\n for (int i = 0; i < numberOfMipmapLevels; ++i) {\n uint32_t imageSize;\n\n if (input.read(&imageSize, 4) != 4) {\n return nullptr;\n }\n\n SkASSERT(offset + imageSize <= dataSize);\n SkASSERT(offset == individualMipOffsets[i]);\n\n if (input.read(&dest[offset], imageSize) != imageSize) {\n return nullptr;\n }\n\n offset += imageSize;\n }\n\n return data;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\ntypedef uint32_t DWORD;\n\n\/\/ Values for the DDS_PIXELFORMAT 'dwFlags' field\nconstexpr unsigned int kDDPF_FOURCC = 0x4;\n\nstruct DDS_PIXELFORMAT {\n DWORD dwSize;\n DWORD dwFlags;\n DWORD dwFourCC;\n DWORD dwRGBBitCount;\n DWORD dwRBitMask;\n DWORD dwGBitMask;\n DWORD dwBBitMask;\n DWORD dwABitMask;\n};\n\n\/\/ Values for the DDS_HEADER 'dwFlags' field\nconstexpr unsigned int kDDSD_CAPS = 0x1; \/\/ required\nconstexpr unsigned int kDDSD_HEIGHT = 0x2; \/\/ required\nconstexpr unsigned int kDDSD_WIDTH = 0x4; \/\/ required\nconstexpr unsigned int kDDSD_PITCH = 0x8;\nconstexpr unsigned int kDDSD_PIXELFORMAT = 0x001000; \/\/ required\nconstexpr unsigned int kDDSD_MIPMAPCOUNT = 0x020000;\nconstexpr unsigned int kDDSD_LINEARSIZE = 0x080000;\nconstexpr unsigned int kDDSD_DEPTH = 0x800000;\n\nconstexpr unsigned int kDDSD_REQUIRED = kDDSD_CAPS | kDDSD_HEIGHT | kDDSD_WIDTH | kDDSD_PIXELFORMAT;\n\ntypedef struct {\n DWORD dwSize;\n DWORD dwFlags;\n DWORD dwHeight;\n DWORD dwWidth;\n DWORD dwPitchOrLinearSize;\n DWORD dwDepth;\n DWORD dwMipMapCount;\n DWORD dwReserved1[11];\n DDS_PIXELFORMAT ddspf;\n DWORD dwCaps;\n DWORD dwCaps2;\n DWORD dwCaps3;\n DWORD dwCaps4;\n DWORD dwReserved2;\n} DDS_HEADER;\n\n\/\/ This DDS loader is barely sufficient to load the specific files this GM requires. Use\n\/\/ at your own peril.\nstatic sk_sp<SkData> load_dds(const char* filename, ImageInfo* imageInfo) {\n SkFILEStream input(filename);\n if (!input.isValid()) {\n return nullptr;\n }\n\n constexpr uint32_t kMagic = 0x20534444;\n uint32_t magic;\n\n if (input.read(&magic, 4) != 4) {\n return nullptr;\n }\n\n if (magic != kMagic) {\n return nullptr;\n }\n\n constexpr size_t kDDSHeaderSize = sizeof(DDS_HEADER);\n static_assert(kDDSHeaderSize == 124);\n constexpr size_t kDDSPixelFormatSize = sizeof(DDS_PIXELFORMAT);\n static_assert(kDDSPixelFormatSize == 32);\n\n DDS_HEADER header;\n\n if (input.read(&header, kDDSHeaderSize) != kDDSHeaderSize) {\n return nullptr;\n }\n\n if (header.dwSize != kDDSHeaderSize ||\n header.ddspf.dwSize != kDDSPixelFormatSize) {\n return nullptr;\n }\n\n if ((header.dwFlags & kDDSD_REQUIRED) != kDDSD_REQUIRED) {\n return nullptr;\n }\n\n if (header.dwFlags & (kDDSD_PITCH | kDDSD_LINEARSIZE | kDDSD_DEPTH)) {\n \/\/ TODO: support these features\n }\n\n imageInfo->fDim.fWidth = header.dwWidth;\n imageInfo->fDim.fHeight = header.dwHeight;\n\n int numberOfMipmapLevels = 1;\n if (header.dwFlags & kDDSD_MIPMAPCOUNT) {\n if (header.dwMipMapCount == 1) {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n } else {\n int numRequiredLevels = SkMipMap::ComputeLevelCount(header.dwWidth, header.dwHeight)+1;\n if (header.dwMipMapCount != (unsigned) numRequiredLevels) {\n return nullptr;\n }\n imageInfo->fMipMapped = GrMipMapped::kYes;\n numberOfMipmapLevels = numRequiredLevels;\n }\n } else {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n }\n\n if (!(header.ddspf.dwFlags & kDDPF_FOURCC)) {\n return nullptr;\n }\n\n \/\/ We only handle these one format right now\n switch (header.ddspf.dwFourCC) {\n case 0x31545844: \/\/ DXT1\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGB8_UNORM;\n break;\n default:\n return nullptr;\n }\n\n SkTArray<size_t> individualMipOffsets(numberOfMipmapLevels);\n\n size_t dataSize = SkCompressedDataSize(imageInfo->fCompressionType,\n { (int) header.dwWidth, (int) header.dwHeight },\n &individualMipOffsets,\n imageInfo->fMipMapped == GrMipMapped::kYes);\n SkASSERT(individualMipOffsets.size() == (size_t) numberOfMipmapLevels);\n\n sk_sp<SkData> data = SkData::MakeUninitialized(dataSize);\n\n uint8_t* dest = (uint8_t*) data->writable_data();\n\n size_t amountRead = input.read(dest, dataSize);\n if (amountRead != dataSize) {\n return nullptr;\n }\n\n return data;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\nstatic sk_sp<SkImage> data_to_img(GrContext *context, sk_sp<SkData> data, const ImageInfo& info) {\n if (context) {\n return SkImage::MakeTextureFromCompressed(context, std::move(data),\n info.fDim.fWidth,\n info.fDim.fHeight,\n info.fCompressionType,\n info.fMipMapped);\n } else {\n return SkImage::MakeRasterFromCompressed(std::move(data),\n info.fDim.fWidth,\n info.fDim.fHeight,\n info.fCompressionType);\n }\n}\n\nnamespace skiagm {\n\n\/\/ This GM exercises our handling of some of the more exotic formats using externally\n\/\/ generated content. Right now it only tests ETC1 and BC1.\nclass ExoticFormatsGM : public GM {\npublic:\n ExoticFormatsGM() {\n this->setBGColor(0xFFCCCCCC);\n }\n\nprotected:\n SkString onShortName() override {\n return SkString(\"exoticformats\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(2*kImgWidthHeight, kImgWidthHeight);\n }\n\n void loadImages(GrContext *context) {\n\n if (!fETC1Image) {\n ImageInfo info;\n sk_sp<SkData> data = load_ktx(GetResourcePath(\"images\/flower-etc1.ktx\").c_str(), &info);\n if (data) {\n SkASSERT(info.fDim.equals(kImgWidthHeight, kImgWidthHeight));\n SkASSERT(info.fMipMapped == GrMipMapped::kNo);\n SkASSERT(info.fCompressionType == SkImage::CompressionType::kETC2_RGB8_UNORM);\n\n fETC1Image = data_to_img(context, std::move(data), info);\n } else {\n SkDebugf(\"failed to load flower-etc1.ktx\\n\");\n }\n }\n\n if (!fBC1Image) {\n ImageInfo info;\n sk_sp<SkData> data = load_dds(GetResourcePath(\"images\/flower-bc1.dds\").c_str(), &info);\n if (data) {\n SkASSERT(info.fDim.equals(kImgWidthHeight, kImgWidthHeight));\n SkASSERT(info.fMipMapped == GrMipMapped::kNo);\n SkASSERT(info.fCompressionType == SkImage::CompressionType::kBC1_RGB8_UNORM);\n\n fBC1Image = data_to_img(context, std::move(data), info);\n } else {\n SkDebugf(\"failed to load flower-bc1.dds\\n\");\n }\n }\n\n }\n\n void drawImage(GrContext* context, SkCanvas* canvas, SkImage* image, int x, int y) {\n if (!image) {\n return;\n }\n\n bool isCompressed = false;\n if (image->isTextureBacked()) {\n const GrCaps* caps = context->priv().caps();\n\n GrTextureProxy* proxy = as_IB(image)->peekProxy();\n isCompressed = caps->isFormatCompressed(proxy->backendFormat());\n }\n\n canvas->drawImage(image, x, y);\n\n if (!isCompressed) {\n \/\/ Make it obvious which drawImages used decompressed images\n SkRect r = SkRect::MakeXYWH(x, y, kImgWidthHeight, kImgWidthHeight);\n SkPaint paint;\n paint.setColor(SK_ColorRED);\n paint.setStyle(SkPaint::kStroke_Style);\n canvas->drawRect(r, paint);\n }\n }\n\n void onDraw(SkCanvas* canvas) override {\n GrContext* context = canvas->getGrContext();\n\n this->loadImages(context);\n\n this->drawImage(context, canvas, fETC1Image.get(), 0, 0);\n this->drawImage(context, canvas, fBC1Image.get(), kImgWidthHeight, 0);\n }\n\nprivate:\n static const int kImgWidthHeight = 128;\n\n sk_sp<SkImage> fETC1Image;\n sk_sp<SkImage> fBC1Image;\n\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDEF_GM(return new ExoticFormatsGM;)\n}\n<commit_msg>Make exoticformats GM a bit easier to triage<commit_after>\/*\n * Copyright 2020 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkImage.h\"\n#include \"include\/core\/SkStream.h\"\n#include \"src\/core\/SkCompressedDataUtils.h\"\n#include \"src\/core\/SkMipMap.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/gl\/GrGLDefines.h\"\n#include \"src\/image\/SkImage_Base.h\"\n\n#include \"tools\/Resources.h\"\n\n\/\/-------------------------------------------------------------------------------------------------\nstruct ImageInfo {\n SkISize fDim;\n GrMipMapped fMipMapped;\n SkImage::CompressionType fCompressionType;\n};\n\n\/*\n * Get an int from a buffer\n * This method is unsafe, the caller is responsible for performing a check\n *\/\nstatic inline uint32_t get_uint(uint8_t* buffer, uint32_t i) {\n uint32_t result;\n memcpy(&result, &(buffer[i]), 4);\n return result;\n}\n\n\/\/ This KTX loader is barely sufficient to load the specific files this GM requires. Use\n\/\/ at your own peril.\nstatic sk_sp<SkData> load_ktx(const char* filename, ImageInfo* imageInfo) {\n SkFILEStream input(filename);\n if (!input.isValid()) {\n return nullptr;\n }\n\n constexpr int kKTXIdentifierSize = 12;\n constexpr int kKTXHeaderSize = kKTXIdentifierSize + 13 * sizeof(uint32_t);\n uint8_t header[kKTXHeaderSize];\n\n if (input.read(header, kKTXHeaderSize) != kKTXHeaderSize) {\n return nullptr;\n }\n\n static const uint8_t kExpectedIdentifier[kKTXIdentifierSize] = {\n 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A\n };\n\n if (memcmp(header, kExpectedIdentifier, kKTXIdentifierSize)) {\n return nullptr;\n }\n\n uint32_t endianness = get_uint(header, 12);\n if (endianness != 0x04030201) {\n \/\/ TODO: need to swap rest of header and, if glTypeSize is > 1, all\n \/\/ the texture data.\n return nullptr;\n }\n\n uint32_t glType = get_uint(header, 16);\n SkDEBUGCODE(uint32_t glTypeSize = get_uint(header, 20);)\n uint32_t glFormat = get_uint(header, 24);\n uint32_t glInternalFormat = get_uint(header, 28);\n \/\/uint32_t glBaseInternalFormat = get_uint(header, 32);\n uint32_t pixelWidth = get_uint(header, 36);\n uint32_t pixelHeight = get_uint(header, 40);\n uint32_t pixelDepth = get_uint(header, 44);\n \/\/uint32_t numberOfArrayElements = get_uint(header, 48);\n uint32_t numberOfFaces = get_uint(header, 52);\n int numberOfMipmapLevels = get_uint(header, 56);\n uint32_t bytesOfKeyValueData = get_uint(header, 60);\n\n if (glType != 0 || glFormat != 0) { \/\/ only care about compressed data for now\n return nullptr;\n }\n SkASSERT(glTypeSize == 1); \/\/ required for compressed data\n\n \/\/ We only handle these four formats right now\n switch (glInternalFormat) {\n case GR_GL_COMPRESSED_ETC1_RGB8:\n case GR_GL_COMPRESSED_RGB8_ETC2:\n imageInfo->fCompressionType = SkImage::CompressionType::kETC2_RGB8_UNORM;\n break;\n case GR_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGB8_UNORM;\n break;\n case GR_GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGBA8_UNORM;\n break;\n default:\n return nullptr;\n }\n\n imageInfo->fDim.fWidth = pixelWidth;\n imageInfo->fDim.fHeight = pixelHeight;\n\n if (pixelDepth != 0) {\n return nullptr; \/\/ pixel depth is always zero for 2D textures\n }\n\n if (numberOfFaces != 1) {\n return nullptr; \/\/ we don't support cube maps right now\n }\n\n if (numberOfMipmapLevels == 1) {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n } else {\n int numRequiredMipLevels = SkMipMap::ComputeLevelCount(pixelWidth, pixelHeight)+1;\n if (numberOfMipmapLevels != numRequiredMipLevels) {\n return nullptr;\n }\n imageInfo->fMipMapped = GrMipMapped::kYes;\n }\n\n if (bytesOfKeyValueData != 0) {\n return nullptr;\n }\n\n SkTArray<size_t> individualMipOffsets(numberOfMipmapLevels);\n\n size_t dataSize = SkCompressedDataSize(imageInfo->fCompressionType,\n { (int) pixelWidth, (int) pixelHeight },\n &individualMipOffsets,\n imageInfo->fMipMapped == GrMipMapped::kYes);\n SkASSERT(individualMipOffsets.size() == (size_t) numberOfMipmapLevels);\n\n sk_sp<SkData> data = SkData::MakeUninitialized(dataSize);\n\n uint8_t* dest = (uint8_t*) data->writable_data();\n\n size_t offset = 0;\n for (int i = 0; i < numberOfMipmapLevels; ++i) {\n uint32_t imageSize;\n\n if (input.read(&imageSize, 4) != 4) {\n return nullptr;\n }\n\n SkASSERT(offset + imageSize <= dataSize);\n SkASSERT(offset == individualMipOffsets[i]);\n\n if (input.read(&dest[offset], imageSize) != imageSize) {\n return nullptr;\n }\n\n offset += imageSize;\n }\n\n return data;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\ntypedef uint32_t DWORD;\n\n\/\/ Values for the DDS_PIXELFORMAT 'dwFlags' field\nconstexpr unsigned int kDDPF_FOURCC = 0x4;\n\nstruct DDS_PIXELFORMAT {\n DWORD dwSize;\n DWORD dwFlags;\n DWORD dwFourCC;\n DWORD dwRGBBitCount;\n DWORD dwRBitMask;\n DWORD dwGBitMask;\n DWORD dwBBitMask;\n DWORD dwABitMask;\n};\n\n\/\/ Values for the DDS_HEADER 'dwFlags' field\nconstexpr unsigned int kDDSD_CAPS = 0x1; \/\/ required\nconstexpr unsigned int kDDSD_HEIGHT = 0x2; \/\/ required\nconstexpr unsigned int kDDSD_WIDTH = 0x4; \/\/ required\nconstexpr unsigned int kDDSD_PITCH = 0x8;\nconstexpr unsigned int kDDSD_PIXELFORMAT = 0x001000; \/\/ required\nconstexpr unsigned int kDDSD_MIPMAPCOUNT = 0x020000;\nconstexpr unsigned int kDDSD_LINEARSIZE = 0x080000;\nconstexpr unsigned int kDDSD_DEPTH = 0x800000;\n\nconstexpr unsigned int kDDSD_REQUIRED = kDDSD_CAPS | kDDSD_HEIGHT | kDDSD_WIDTH | kDDSD_PIXELFORMAT;\n\ntypedef struct {\n DWORD dwSize;\n DWORD dwFlags;\n DWORD dwHeight;\n DWORD dwWidth;\n DWORD dwPitchOrLinearSize;\n DWORD dwDepth;\n DWORD dwMipMapCount;\n DWORD dwReserved1[11];\n DDS_PIXELFORMAT ddspf;\n DWORD dwCaps;\n DWORD dwCaps2;\n DWORD dwCaps3;\n DWORD dwCaps4;\n DWORD dwReserved2;\n} DDS_HEADER;\n\n\/\/ This DDS loader is barely sufficient to load the specific files this GM requires. Use\n\/\/ at your own peril.\nstatic sk_sp<SkData> load_dds(const char* filename, ImageInfo* imageInfo) {\n SkFILEStream input(filename);\n if (!input.isValid()) {\n return nullptr;\n }\n\n constexpr uint32_t kMagic = 0x20534444;\n uint32_t magic;\n\n if (input.read(&magic, 4) != 4) {\n return nullptr;\n }\n\n if (magic != kMagic) {\n return nullptr;\n }\n\n constexpr size_t kDDSHeaderSize = sizeof(DDS_HEADER);\n static_assert(kDDSHeaderSize == 124);\n constexpr size_t kDDSPixelFormatSize = sizeof(DDS_PIXELFORMAT);\n static_assert(kDDSPixelFormatSize == 32);\n\n DDS_HEADER header;\n\n if (input.read(&header, kDDSHeaderSize) != kDDSHeaderSize) {\n return nullptr;\n }\n\n if (header.dwSize != kDDSHeaderSize ||\n header.ddspf.dwSize != kDDSPixelFormatSize) {\n return nullptr;\n }\n\n if ((header.dwFlags & kDDSD_REQUIRED) != kDDSD_REQUIRED) {\n return nullptr;\n }\n\n if (header.dwFlags & (kDDSD_PITCH | kDDSD_LINEARSIZE | kDDSD_DEPTH)) {\n \/\/ TODO: support these features\n }\n\n imageInfo->fDim.fWidth = header.dwWidth;\n imageInfo->fDim.fHeight = header.dwHeight;\n\n int numberOfMipmapLevels = 1;\n if (header.dwFlags & kDDSD_MIPMAPCOUNT) {\n if (header.dwMipMapCount == 1) {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n } else {\n int numRequiredLevels = SkMipMap::ComputeLevelCount(header.dwWidth, header.dwHeight)+1;\n if (header.dwMipMapCount != (unsigned) numRequiredLevels) {\n return nullptr;\n }\n imageInfo->fMipMapped = GrMipMapped::kYes;\n numberOfMipmapLevels = numRequiredLevels;\n }\n } else {\n imageInfo->fMipMapped = GrMipMapped::kNo;\n }\n\n if (!(header.ddspf.dwFlags & kDDPF_FOURCC)) {\n return nullptr;\n }\n\n \/\/ We only handle these one format right now\n switch (header.ddspf.dwFourCC) {\n case 0x31545844: \/\/ DXT1\n imageInfo->fCompressionType = SkImage::CompressionType::kBC1_RGB8_UNORM;\n break;\n default:\n return nullptr;\n }\n\n SkTArray<size_t> individualMipOffsets(numberOfMipmapLevels);\n\n size_t dataSize = SkCompressedDataSize(imageInfo->fCompressionType,\n { (int) header.dwWidth, (int) header.dwHeight },\n &individualMipOffsets,\n imageInfo->fMipMapped == GrMipMapped::kYes);\n SkASSERT(individualMipOffsets.size() == (size_t) numberOfMipmapLevels);\n\n sk_sp<SkData> data = SkData::MakeUninitialized(dataSize);\n\n uint8_t* dest = (uint8_t*) data->writable_data();\n\n size_t amountRead = input.read(dest, dataSize);\n if (amountRead != dataSize) {\n return nullptr;\n }\n\n return data;\n}\n\n\/\/-------------------------------------------------------------------------------------------------\nstatic sk_sp<SkImage> data_to_img(GrContext *context, sk_sp<SkData> data, const ImageInfo& info) {\n if (context) {\n return SkImage::MakeTextureFromCompressed(context, std::move(data),\n info.fDim.fWidth,\n info.fDim.fHeight,\n info.fCompressionType,\n info.fMipMapped);\n } else {\n return SkImage::MakeRasterFromCompressed(std::move(data),\n info.fDim.fWidth,\n info.fDim.fHeight,\n info.fCompressionType);\n }\n}\n\nnamespace skiagm {\n\n\/\/ This GM exercises our handling of some of the more exotic formats using externally\n\/\/ generated content. Right now it only tests ETC1 and BC1.\nclass ExoticFormatsGM : public GM {\npublic:\n ExoticFormatsGM() {\n this->setBGColor(SK_ColorBLACK);\n }\n\nprotected:\n SkString onShortName() override {\n return SkString(\"exoticformats\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(2*kImgWidthHeight + 3 * kPad, kImgWidthHeight + 2 * kPad);\n }\n\n void loadImages(GrContext *context) {\n\n if (!fETC1Image) {\n ImageInfo info;\n sk_sp<SkData> data = load_ktx(GetResourcePath(\"images\/flower-etc1.ktx\").c_str(), &info);\n if (data) {\n SkASSERT(info.fDim.equals(kImgWidthHeight, kImgWidthHeight));\n SkASSERT(info.fMipMapped == GrMipMapped::kNo);\n SkASSERT(info.fCompressionType == SkImage::CompressionType::kETC2_RGB8_UNORM);\n\n fETC1Image = data_to_img(context, std::move(data), info);\n } else {\n SkDebugf(\"failed to load flower-etc1.ktx\\n\");\n }\n }\n\n if (!fBC1Image) {\n ImageInfo info;\n sk_sp<SkData> data = load_dds(GetResourcePath(\"images\/flower-bc1.dds\").c_str(), &info);\n if (data) {\n SkASSERT(info.fDim.equals(kImgWidthHeight, kImgWidthHeight));\n SkASSERT(info.fMipMapped == GrMipMapped::kNo);\n SkASSERT(info.fCompressionType == SkImage::CompressionType::kBC1_RGB8_UNORM);\n\n fBC1Image = data_to_img(context, std::move(data), info);\n } else {\n SkDebugf(\"failed to load flower-bc1.dds\\n\");\n }\n }\n\n }\n\n void drawImage(GrContext* context, SkCanvas* canvas, SkImage* image, int x, int y) {\n if (!image) {\n return;\n }\n\n bool isCompressed = false;\n if (image->isTextureBacked()) {\n const GrCaps* caps = context->priv().caps();\n\n GrTextureProxy* proxy = as_IB(image)->peekProxy();\n isCompressed = caps->isFormatCompressed(proxy->backendFormat());\n }\n\n canvas->drawImage(image, x, y);\n\n if (!isCompressed) {\n \/\/ Make it obvious which drawImages used decompressed images\n SkRect r = SkRect::MakeXYWH(x, y, kImgWidthHeight, kImgWidthHeight);\n SkPaint paint;\n paint.setColor(SK_ColorRED);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(2.0f);\n canvas->drawRect(r, paint);\n }\n }\n\n void onDraw(SkCanvas* canvas) override {\n GrContext* context = canvas->getGrContext();\n\n this->loadImages(context);\n\n this->drawImage(context, canvas, fETC1Image.get(), kPad, kPad);\n this->drawImage(context, canvas, fBC1Image.get(), kImgWidthHeight + 2 * kPad, kPad);\n }\n\nprivate:\n static const int kImgWidthHeight = 128;\n static const int kPad = 4;\n\n sk_sp<SkImage> fETC1Image;\n sk_sp<SkImage> fBC1Image;\n\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDEF_GM(return new ExoticFormatsGM;)\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __scripting_function_hpp__\n#define __scripting_function_hpp__\n\n\n#include \"scripting_object.hpp\"\n\n#include <string>\n#include <boost\/function.hpp>\n#include <boost\/bind.hpp>\n#include <stdexcept>\n#include <vector>\n\n\n\/\/ handle_return implementations\ntemplate<typename Ret>\nstruct Handle_Return\n{\n Scripting_Object operator()(const boost::function<Ret ()> &f)\n {\n return Scripting_Object(f());\n }\n};\n\ntemplate<typename Ret>\nstruct Handle_Return<Ret &>\n{\n Scripting_Object operator()(const boost::function<Ret &()> &f)\n {\n return Scripting_Object(boost::ref(f()));\n }\n};\n\ntemplate<>\nstruct Handle_Return<void>\n{\n Scripting_Object operator()(const boost::function<void ()> &f)\n {\n f();\n return Scripting_Object();\n }\n};\n\n\n\n\/\/ call_func implementations todo: handle reference return types\n\/\/ to be made variadic\ntemplate<typename Ret, typename Param1, typename Param2>\nScripting_Object call_func(const boost::function<Ret (Param1, Param2)> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 2)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(boost::bind(f, Cast_Helper<Param1>()(params[0]), Cast_Helper<Param2>()(params[1])));\n }\n}\n\ntemplate<typename Ret, typename Param1>\nScripting_Object call_func(const boost::function<Ret (Param1)> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 1)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(boost::bind(f, Cast_Helper<Param1>()(params[0])));\n }\n}\n\ntemplate<typename Ret>\nScripting_Object call_func(const boost::function<Ret ()> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 0)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(f);\n }\n}\n\n\n\nclass Function_Handler\n{\n public:\n virtual Scripting_Object operator()(const std::vector<Scripting_Object> ¶ms) = 0;\n};\n\ntemplate<typename Func>\nclass Function_Handler_Impl : public Function_Handler\n{\n public:\n Function_Handler_Impl(const Func &f)\n : m_f(f)\n {\n }\n\n virtual Scripting_Object operator()(const std::vector<Scripting_Object> ¶ms)\n {\n return call_func(m_f, params);\n }\n\n private:\n Func m_f;\n};\n\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so);\n return sos;\n}\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so1, const Scripting_Object &so2)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so1);\n sos.push_back(so2);\n return sos;\n}\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so1, const Scripting_Object &so2, const Scripting_Object &so3)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so1);\n sos.push_back(so2);\n sos.push_back(so3);\n return sos;\n}\n\n\n\n#endif\n\n<commit_msg>Add support for getting command argument types as a vector<commit_after>#ifndef __scripting_function_hpp__\n#define __scripting_function_hpp__\n\n\n#include \"scripting_object.hpp\"\n#include \"scripting_type_info.hpp\"\n#include <string>\n#include <boost\/function.hpp>\n#include <boost\/bind.hpp>\n#include <stdexcept>\n#include <vector>\n\ntemplate<typename Ret>\nstd::vector<Type_Info> build_param_type_list(const boost::function<Ret ()> &f)\n{\n return std::vector<Type_Info>();\n}\n\ntemplate<typename Ret, typename Param1>\nstd::vector<Type_Info> build_param_type_list(const boost::function<Ret (Param1)> &f)\n{\n std::vector<Type_Info> ti;\n ti.push_back(Get_Type_Info<Param1>()());\n return ti;\n}\n\ntemplate<typename Ret, typename Param1, typename Param2>\nstd::vector<Type_Info> build_param_type_list(const boost::function<Ret (Param1, Param2)> &f)\n{\n std::vector<Type_Info> ti;\n ti.push_back(Get_Type_Info<Param1>()());\n ti.push_back(Get_Type_Info<Param2>()());\n return ti;\n}\n\n\/\/ handle_return implementations\ntemplate<typename Ret>\nstruct Handle_Return\n{\n Scripting_Object operator()(const boost::function<Ret ()> &f)\n {\n return Scripting_Object(f());\n }\n};\n\ntemplate<typename Ret>\nstruct Handle_Return<Ret &>\n{\n Scripting_Object operator()(const boost::function<Ret &()> &f)\n {\n return Scripting_Object(boost::ref(f()));\n }\n};\n\ntemplate<>\nstruct Handle_Return<void>\n{\n Scripting_Object operator()(const boost::function<void ()> &f)\n {\n f();\n return Scripting_Object();\n }\n};\n\n\n\n\/\/ call_func implementations todo: handle reference return types\n\/\/ to be made variadic\ntemplate<typename Ret, typename Param1, typename Param2>\nScripting_Object call_func(const boost::function<Ret (Param1, Param2)> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 2)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(boost::bind(f, Cast_Helper<Param1>()(params[0]), Cast_Helper<Param2>()(params[1])));\n }\n}\n\ntemplate<typename Ret, typename Param1>\nScripting_Object call_func(const boost::function<Ret (Param1)> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 1)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(boost::bind(f, Cast_Helper<Param1>()(params[0])));\n }\n}\n\ntemplate<typename Ret>\nScripting_Object call_func(const boost::function<Ret ()> &f, const std::vector<Scripting_Object> ¶ms)\n{\n if (params.size() != 0)\n {\n throw std::range_error(\"Incorrect number of parameters\");\n } else {\n return Handle_Return<Ret>()(f);\n }\n}\n\n\n\nclass Function_Handler\n{\n public:\n virtual Scripting_Object operator()(const std::vector<Scripting_Object> ¶ms) = 0;\n virtual std::vector<Type_Info> get_param_types() = 0;\n\n};\n\ntemplate<typename Func>\nclass Function_Handler_Impl : public Function_Handler\n{\n public:\n Function_Handler_Impl(const Func &f)\n : m_f(f)\n {\n }\n\n virtual Scripting_Object operator()(const std::vector<Scripting_Object> ¶ms)\n {\n return call_func(m_f, params);\n }\n\n virtual std::vector<Type_Info> get_param_types()\n {\n return build_param_type_list(m_f);\n }\n\n private:\n Func m_f;\n};\n\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so);\n return sos;\n}\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so1, const Scripting_Object &so2)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so1);\n sos.push_back(so2);\n return sos;\n}\nstd::vector<Scripting_Object> build_param_list(const Scripting_Object &so1, const Scripting_Object &so2, const Scripting_Object &so3)\n{\n std::vector<Scripting_Object> sos;\n sos.push_back(so1);\n sos.push_back(so2);\n sos.push_back(so3);\n return sos;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Context.h\"\r\n#include \"InputEvents.h\"\r\n#include \"Log.h\"\r\n#include \"Slider.h\"\r\n#include \"UIEvents.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\nnamespace Urho3D\r\n{\r\n\r\nconst char* orientations[] =\r\n{\r\n \"Horizontal\",\r\n \"Vertical\",\r\n 0\r\n};\r\n\r\ntemplate<> Orientation Variant::Get<Orientation>() const\r\n{\r\n return (Orientation)GetInt();\r\n}\r\n\r\nextern const char* UI_CATEGORY;\r\n\r\nSlider::Slider(Context* context) :\r\n BorderImage(context),\r\n orientation_(O_HORIZONTAL),\r\n range_(1.0f),\r\n value_(0.0f),\r\n dragSlider_(false),\r\n repeatRate_(0.0f)\r\n{\r\n enabled_ = true;\r\n knob_ = CreateChild<BorderImage>(\"S_Knob\");\r\n knob_->SetInternal(true);\r\n\r\n UpdateSlider();\r\n}\r\n\r\nSlider::~Slider()\r\n{\r\n}\r\n\r\nvoid Slider::RegisterObject(Context* context)\r\n{\r\n context->RegisterFactory<Slider>(UI_CATEGORY);\r\n\r\n COPY_BASE_ATTRIBUTES(Slider, BorderImage);\r\n UPDATE_ATTRIBUTE_DEFAULT_VALUE(Slider, \"Is Enabled\", true);\r\n ENUM_ACCESSOR_ATTRIBUTE(Slider, \"Orientation\", GetOrientation, SetOrientation, Orientation, orientations, O_HORIZONTAL, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Range\", GetRange, SetRange, float, 1.0f, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Value\", GetValue, SetValue, float, 0.0f, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Repeat Rate\", GetRepeatRate, SetRepeatRate, float, 0.0f, AM_FILE);\r\n}\r\n\r\nvoid Slider::Update(float timeStep)\r\n{\r\n if (dragSlider_)\r\n hovering_ = true;\r\n\r\n \/\/ Propagate hover effect to the slider knob\r\n knob_->SetHovering(hovering_);\r\n knob_->SetSelected(hovering_);\r\n}\r\n\r\nvoid Slider::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n BorderImage::OnHover(position, screenPosition, buttons, qualifiers, cursor);\r\n\r\n \/\/ Show hover effect if inside the slider knob\r\n hovering_ = knob_->IsInside(screenPosition, true);\r\n\r\n \/\/ If not hovering on the knob, send it as page event\r\n if (!hovering_)\r\n Page(position, 0, buttons, qualifiers);\r\n}\r\n\r\nvoid Slider::OnClickBegin(const IntVector2& position, const IntVector2& screenPosition, int button, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n selected_ = true;\r\n hovering_ = knob_->IsInside(screenPosition, true);\r\n if (!hovering_)\r\n Page(position, button, buttons, qualifiers);\r\n}\r\n\r\nvoid Slider::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n dragBeginCursor_ = position;\r\n dragBeginPosition_ = knob_->GetPosition();\r\n dragSlider_ = knob_->IsInside(screenPosition, true);\r\n}\r\n\r\nvoid Slider::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n if (!dragSlider_ || GetSize() == knob_->GetSize())\r\n return;\r\n\r\n float newValue = value_;\r\n IntVector2 delta = position - dragBeginCursor_;\r\n\r\n if (orientation_ == O_HORIZONTAL)\r\n {\r\n int newX = Clamp(dragBeginPosition_.x_ + delta.x_, 0, GetWidth() - knob_->GetWidth());\r\n knob_->SetPosition(newX, 0);\r\n newValue = (float)newX * range_ \/ (float)(GetWidth() - knob_->GetWidth());\r\n }\r\n else\r\n {\r\n int newY = Clamp(dragBeginPosition_.y_ + delta.y_, 0, GetHeight() - knob_->GetHeight());\r\n knob_->SetPosition(0, newY);\r\n newValue = (float)newY * range_ \/ (float)(GetHeight() - knob_->GetHeight());\r\n }\r\n\r\n SetValue(newValue);\r\n}\r\n\r\nvoid Slider::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)\r\n{\r\n dragSlider_ = false;\r\n selected_ = false;\r\n}\r\n\r\nvoid Slider::OnResize()\r\n{\r\n UpdateSlider();\r\n}\r\n\r\nvoid Slider::SetOrientation(Orientation type)\r\n{\r\n orientation_ = type;\r\n UpdateSlider();\r\n}\r\n\r\nvoid Slider::SetRange(float range)\r\n{\r\n range = Max(range, 0.0f);\r\n if (range != range_)\r\n {\r\n range_ = range;\r\n UpdateSlider();\r\n }\r\n}\r\n\r\nvoid Slider::SetValue(float value)\r\n{\r\n value = Clamp(value, 0.0f, range_);\r\n if (value != value_)\r\n {\r\n value_ = value;\r\n UpdateSlider();\r\n\r\n using namespace SliderChanged;\r\n\r\n VariantMap eventData;\r\n eventData[P_ELEMENT] = (void*)this;\r\n eventData[P_VALUE] = value_;\r\n SendEvent(E_SLIDERCHANGED, eventData);\r\n }\r\n}\r\n\r\nvoid Slider::ChangeValue(float delta)\r\n{\r\n SetValue(value_ + delta);\r\n}\r\n\r\nvoid Slider::SetRepeatRate(float rate)\r\n{\r\n repeatRate_ = Max(rate, 0.0f);\r\n}\r\n\r\nbool Slider::FilterImplicitAttributes(XMLElement& dest) const\r\n{\r\n if (!BorderImage::FilterImplicitAttributes(dest))\r\n return false;\r\n\r\n XMLElement childElem = dest.GetChild(\"element\");\r\n if (!childElem)\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Name\", \"S_Knob\"))\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Position\"))\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Size\"))\r\n return false;\r\n\r\n return true;\r\n}\r\n\r\nvoid Slider::UpdateSlider()\r\n{\r\n const IntRect& border = knob_->GetBorder();\r\n\r\n if (range_ > 0.0f)\r\n {\r\n if (orientation_ == O_HORIZONTAL)\r\n {\r\n int sliderLength = (int)Max((float)GetWidth() \/ (range_ + 1.0f), (float)(border.left_ + border.right_));\r\n float sliderPos = (float)(GetWidth() - sliderLength) * value_ \/ range_;\r\n knob_->SetSize(sliderLength, GetHeight());\r\n knob_->SetPosition(Clamp((int)(sliderPos + 0.5f), 0, GetWidth() - knob_->GetWidth()), 0);\r\n }\r\n else\r\n {\r\n int sliderLength = (int)Max((float)GetHeight() \/ (range_ + 1.0f), (float)(border.top_ + border.bottom_));\r\n float sliderPos = (float)(GetHeight() - sliderLength) * value_ \/ range_;\r\n knob_->SetSize(GetWidth(), sliderLength);\r\n knob_->SetPosition(0, Clamp((int)(sliderPos + 0.5f), 0, GetHeight() - knob_->GetHeight()));\r\n }\r\n }\r\n else\r\n {\r\n knob_->SetSize(GetSize());\r\n knob_->SetPosition(0, 0);\r\n }\r\n}\r\n\r\nvoid Slider::Page(const IntVector2& position, int button, int buttons, int qualifiers)\r\n{\r\n IntVector2 offsetXY = position - knob_->GetPosition() - knob_->GetSize() \/ 2;\r\n int offset = orientation_ == O_HORIZONTAL ? offsetXY.x_ : offsetXY.y_;\r\n float length = (float)(orientation_ == O_HORIZONTAL ? GetWidth() : GetHeight());\r\n\r\n using namespace SliderPaged;\r\n\r\n VariantMap eventData;\r\n eventData[P_ELEMENT] = (void*)this;\r\n eventData[P_OFFSET] = offset;\r\n \/\/ Only generate the 'click' variant of the event when the slider is selected\r\n \/\/ i.e. when it has received the first initial click.\r\n if (selected_ && repeatRate_ > 0.0f && repeatTimer_.GetMSec(false) >= Lerp(1000.0f \/ repeatRate_, 0, Abs(offset) \/ length))\r\n {\r\n repeatTimer_.Reset();\r\n eventData[P_BUTTON] = button;\r\n eventData[P_BUTTONS] = buttons;\r\n eventData[P_QUALIFIERS] = qualifiers;\r\n }\r\n \/\/ When without buttons & qualifiers parameters, the receiver should interpret\r\n \/\/ this event as just mouse hovering on slider's 'paging' area instead\r\n SendEvent(E_SLIDERPAGED, eventData);\r\n}\r\n\r\n}\r\n<commit_msg>Fixed repeat paging of the slider.<commit_after>\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Context.h\"\r\n#include \"InputEvents.h\"\r\n#include \"Log.h\"\r\n#include \"Slider.h\"\r\n#include \"UIEvents.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\nnamespace Urho3D\r\n{\r\n\r\nconst char* orientations[] =\r\n{\r\n \"Horizontal\",\r\n \"Vertical\",\r\n 0\r\n};\r\n\r\ntemplate<> Orientation Variant::Get<Orientation>() const\r\n{\r\n return (Orientation)GetInt();\r\n}\r\n\r\nextern const char* UI_CATEGORY;\r\n\r\nSlider::Slider(Context* context) :\r\n BorderImage(context),\r\n orientation_(O_HORIZONTAL),\r\n range_(1.0f),\r\n value_(0.0f),\r\n dragSlider_(false),\r\n repeatRate_(0.0f)\r\n{\r\n enabled_ = true;\r\n knob_ = CreateChild<BorderImage>(\"S_Knob\");\r\n knob_->SetInternal(true);\r\n\r\n UpdateSlider();\r\n}\r\n\r\nSlider::~Slider()\r\n{\r\n}\r\n\r\nvoid Slider::RegisterObject(Context* context)\r\n{\r\n context->RegisterFactory<Slider>(UI_CATEGORY);\r\n\r\n COPY_BASE_ATTRIBUTES(Slider, BorderImage);\r\n UPDATE_ATTRIBUTE_DEFAULT_VALUE(Slider, \"Is Enabled\", true);\r\n ENUM_ACCESSOR_ATTRIBUTE(Slider, \"Orientation\", GetOrientation, SetOrientation, Orientation, orientations, O_HORIZONTAL, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Range\", GetRange, SetRange, float, 1.0f, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Value\", GetValue, SetValue, float, 0.0f, AM_FILE);\r\n ACCESSOR_ATTRIBUTE(Slider, VAR_FLOAT, \"Repeat Rate\", GetRepeatRate, SetRepeatRate, float, 0.0f, AM_FILE);\r\n}\r\n\r\nvoid Slider::Update(float timeStep)\r\n{\r\n if (dragSlider_)\r\n hovering_ = true;\r\n\r\n \/\/ Propagate hover effect to the slider knob\r\n knob_->SetHovering(hovering_);\r\n knob_->SetSelected(hovering_);\r\n}\r\n\r\nvoid Slider::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n BorderImage::OnHover(position, screenPosition, buttons, qualifiers, cursor);\r\n\r\n \/\/ Show hover effect if inside the slider knob\r\n hovering_ = knob_->IsInside(screenPosition, true);\r\n\r\n \/\/ If not hovering on the knob, send it as page event\r\n if (!hovering_)\r\n Page(position, 0, buttons, qualifiers);\r\n}\r\n\r\nvoid Slider::OnClickBegin(const IntVector2& position, const IntVector2& screenPosition, int button, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n selected_ = true;\r\n hovering_ = knob_->IsInside(screenPosition, true);\r\n if (!hovering_)\r\n Page(position, button, buttons, qualifiers);\r\n}\r\n\r\nvoid Slider::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n dragBeginCursor_ = position;\r\n dragBeginPosition_ = knob_->GetPosition();\r\n dragSlider_ = knob_->IsInside(screenPosition, true);\r\n}\r\n\r\nvoid Slider::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)\r\n{\r\n if (!dragSlider_ || GetSize() == knob_->GetSize())\r\n return;\r\n\r\n float newValue = value_;\r\n IntVector2 delta = position - dragBeginCursor_;\r\n\r\n if (orientation_ == O_HORIZONTAL)\r\n {\r\n int newX = Clamp(dragBeginPosition_.x_ + delta.x_, 0, GetWidth() - knob_->GetWidth());\r\n knob_->SetPosition(newX, 0);\r\n newValue = (float)newX * range_ \/ (float)(GetWidth() - knob_->GetWidth());\r\n }\r\n else\r\n {\r\n int newY = Clamp(dragBeginPosition_.y_ + delta.y_, 0, GetHeight() - knob_->GetHeight());\r\n knob_->SetPosition(0, newY);\r\n newValue = (float)newY * range_ \/ (float)(GetHeight() - knob_->GetHeight());\r\n }\r\n\r\n SetValue(newValue);\r\n}\r\n\r\nvoid Slider::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)\r\n{\r\n dragSlider_ = false;\r\n selected_ = false;\r\n}\r\n\r\nvoid Slider::OnResize()\r\n{\r\n UpdateSlider();\r\n}\r\n\r\nvoid Slider::SetOrientation(Orientation type)\r\n{\r\n orientation_ = type;\r\n UpdateSlider();\r\n}\r\n\r\nvoid Slider::SetRange(float range)\r\n{\r\n range = Max(range, 0.0f);\r\n if (range != range_)\r\n {\r\n range_ = range;\r\n UpdateSlider();\r\n }\r\n}\r\n\r\nvoid Slider::SetValue(float value)\r\n{\r\n value = Clamp(value, 0.0f, range_);\r\n if (value != value_)\r\n {\r\n value_ = value;\r\n UpdateSlider();\r\n\r\n using namespace SliderChanged;\r\n\r\n VariantMap eventData;\r\n eventData[P_ELEMENT] = (void*)this;\r\n eventData[P_VALUE] = value_;\r\n SendEvent(E_SLIDERCHANGED, eventData);\r\n }\r\n}\r\n\r\nvoid Slider::ChangeValue(float delta)\r\n{\r\n SetValue(value_ + delta);\r\n}\r\n\r\nvoid Slider::SetRepeatRate(float rate)\r\n{\r\n repeatRate_ = Max(rate, 0.0f);\r\n}\r\n\r\nbool Slider::FilterImplicitAttributes(XMLElement& dest) const\r\n{\r\n if (!BorderImage::FilterImplicitAttributes(dest))\r\n return false;\r\n\r\n XMLElement childElem = dest.GetChild(\"element\");\r\n if (!childElem)\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Name\", \"S_Knob\"))\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Position\"))\r\n return false;\r\n if (!RemoveChildXML(childElem, \"Size\"))\r\n return false;\r\n\r\n return true;\r\n}\r\n\r\nvoid Slider::UpdateSlider()\r\n{\r\n const IntRect& border = knob_->GetBorder();\r\n\r\n if (range_ > 0.0f)\r\n {\r\n if (orientation_ == O_HORIZONTAL)\r\n {\r\n int sliderLength = (int)Max((float)GetWidth() \/ (range_ + 1.0f), (float)(border.left_ + border.right_));\r\n float sliderPos = (float)(GetWidth() - sliderLength) * value_ \/ range_;\r\n knob_->SetSize(sliderLength, GetHeight());\r\n knob_->SetPosition(Clamp((int)(sliderPos + 0.5f), 0, GetWidth() - knob_->GetWidth()), 0);\r\n }\r\n else\r\n {\r\n int sliderLength = (int)Max((float)GetHeight() \/ (range_ + 1.0f), (float)(border.top_ + border.bottom_));\r\n float sliderPos = (float)(GetHeight() - sliderLength) * value_ \/ range_;\r\n knob_->SetSize(GetWidth(), sliderLength);\r\n knob_->SetPosition(0, Clamp((int)(sliderPos + 0.5f), 0, GetHeight() - knob_->GetHeight()));\r\n }\r\n }\r\n else\r\n {\r\n knob_->SetSize(GetSize());\r\n knob_->SetPosition(0, 0);\r\n }\r\n}\r\n\r\nvoid Slider::Page(const IntVector2& position, int button, int buttons, int qualifiers)\r\n{\r\n IntVector2 offsetXY = position - knob_->GetPosition() - knob_->GetSize() \/ 2;\r\n int offset = orientation_ == O_HORIZONTAL ? offsetXY.x_ : offsetXY.y_;\r\n float length = (float)(orientation_ == O_HORIZONTAL ? GetWidth() : GetHeight());\r\n\r\n using namespace SliderPaged;\r\n \r\n \/\/ If button is 0 (passed from hover event) assume it's the lowest pressed bit in buttons\r\n if (!button && buttons)\r\n {\r\n if (buttons & MOUSEB_LEFT)\r\n button = MOUSEB_LEFT;\r\n else if (buttons & MOUSEB_MIDDLE)\r\n button = MOUSEB_MIDDLE;\r\n else if (buttons & MOUSEB_RIGHT)\r\n button = MOUSEB_RIGHT;\r\n }\r\n \r\n VariantMap eventData;\r\n eventData[P_ELEMENT] = (void*)this;\r\n eventData[P_OFFSET] = offset;\r\n \/\/ Only generate the 'click' variant of the event when the slider is selected\r\n \/\/ i.e. when it has received the first initial click.\r\n if (selected_ && repeatRate_ > 0.0f && repeatTimer_.GetMSec(false) >= Lerp(1000.0f \/ repeatRate_, 0, Abs(offset) \/ length))\r\n {\r\n repeatTimer_.Reset();\r\n eventData[P_BUTTON] = button;\r\n eventData[P_BUTTONS] = buttons;\r\n eventData[P_QUALIFIERS] = qualifiers;\r\n }\r\n \/\/ When without buttons & qualifiers parameters, the receiver should interpret\r\n \/\/ this event as just mouse hovering on slider's 'paging' area instead\r\n SendEvent(E_SLIDERPAGED, eventData);\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief zlib compressor and decompressor class\n\n\tCopyright (C) 2009 Cybozu Labs, Inc., all rights reserved.\n*\/\n\n#include <cybozu\/exception.hpp>\n#include <cybozu\/endian.hpp>\n#include <cybozu\/stream_fwd.hpp>\n#include <assert.h>\n#include <stdio.h>\n#include <zlib.h>\n\n#ifdef _MSC_VER\n\t#ifdef _DLL_CPPLIB\n\t\t#pragma comment(lib, \"zlib_md.lib\")\n\t#else\n\t\t#pragma comment(lib, \"zlib_mt.lib\")\n\t#endif\n#endif\n\nnamespace cybozu {\n\nnamespace zlib_local {\n\nconst int DEF_MEM_LEVEL = 8;\n\n} \/\/ zlib_local\n\n\/**\n\tzlib compressor class\n\tOutputStream must have size_t write(const char *buf, size_t size);\n*\/\ntemplate<class OutputStream, size_t maxBufSize = 2048>\nclass ZlibCompressorT {\n\tOutputStream& os_;\n\tunsigned int crc_;\n\tunsigned int totalSize_; \/* mod 2^32 *\/\n\tz_stream z_;\n\tchar buf_[maxBufSize];\n\tbool isFlushCalled_;\n\tconst bool useGzip_;\n\tZlibCompressorT(const ZlibCompressorT&);\n\tvoid operator=(const ZlibCompressorT&);\npublic:\n\t\/**\n\t\t@param os [in] output stream\n\t\t@param useGzip [in] useGzip if true, use deflate if false\n\t\t@note useGzip option is not fully tested, so default off\n\t*\/\n\tZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION)\n\t\t: os_(os)\n\t\t, crc_(crc32(0L, Z_NULL, 0))\n\t\t, totalSize_(0)\n\t\t, isFlushCalled_(false)\n\t\t, useGzip_(useGzip)\n\t{\n\t\tz_.zalloc = Z_NULL;\n\t\tz_.zfree = Z_NULL;\n\t\tz_.opaque = Z_NULL;\n\t\tif (useGzip_) {\n\t\t\tif (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressorT:deflateInit2\") << std::string(z_.msg);\n\t\t\t}\n\t\t\tchar header[] = \"\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\"; \/* OS_CODE = 0x03(Unix) *\/\n\t\t\twrite_os(header, 10);\n\t\t} else {\n\t\t\tif (deflateInit(&z_, compressionLevel) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressorT:deflateInit\") << std::string(z_.msg);\n\t\t\t}\n\t\t}\n\t}\n\t~ZlibCompressorT()\n\t{\n\t\tif (!isFlushCalled_) {\n\t\t\ttry {\n\t\t\t\tflush();\n\t\t\t} catch (std::exception& e) {\n\t\t\t\tfprintf(stderr, \"zlib:ZlibCompressor:flush:exception:%s\\n\", e.what());\n\t\t\t} catch (...) {\n\t\t\t\tfprintf(stderr, \"zlib:ZlibCompressor:flush:unknown exception\\n\");\n\t\t\t}\n\t\t}\n\t\tdeflateEnd(&z_);\n\t}\n\t\/*\n\t\tcompress buf\n\t\t@param buf [in] input data\n\t\t@param size [in] input data size\n\t*\/\n\tvoid write(const void *buf, size_t _size)\n\t{\n\t\tif (_size >= (1u << 31)) throw cybozu::Exception(\"zlib:ZlibCompressor:write:too large size\") << _size;\n\t\tuint32_t size = (uint32_t)_size;\n\t\tif (useGzip_) {\n\t\t\tcrc_ = crc32(crc_, (const Bytef *)buf, size);\n\t\t\ttotalSize_ += (unsigned int)size;\n\t\t}\n\t\tz_.next_in = (Bytef*)const_cast<char*>((const char*)buf);\n\t\tz_.avail_in = size;\n\t\twhile (z_.avail_in > 0) {\n\t\t\tz_.next_out = (Bytef*)buf_;\n\t\t\tz_.avail_out = maxBufSize;\n\n\t\t\tint ret = deflate(&z_, Z_NO_FLUSH);\n\t\t\tif (ret != Z_STREAM_END && ret != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressor:exec:compress\") << std::string(z_.msg);\n\t\t\t}\n\t\t\twrite_os(buf_, maxBufSize - z_.avail_out);\n\t\t\tif (ret == Z_STREAM_END) break;\n\t\t}\n\t}\n\tvoid flush()\n\t{\n\t\tisFlushCalled_ = true;\n\t\tz_.next_in = 0;\n\t\tz_.avail_in = 0;\n\n\t\tfor (;;) {\n\t\t\tz_.next_out = (Bytef*)buf_;\n\t\t\tz_.avail_out = maxBufSize;\n\n\t\t\tint ret = deflate(&z_, Z_FINISH);\n\t\t\tif (ret != Z_STREAM_END && ret != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressor:flush\") << std::string(z_.msg);\n\t\t\t}\n\t\t\twrite_os(buf_, sizeof(buf_) - z_.avail_out);\n\t\t\tif (ret == Z_STREAM_END) break;\n\t\t}\n\t\tif (useGzip_) {\n\t\t\tchar tail[8];\n\t\t\tcybozu::Set32bitAsLE(&tail[0], crc_);\n\t\t\tcybozu::Set32bitAsLE(&tail[4], totalSize_);\n\t\t\twrite_os(tail, sizeof(tail));\n\t\t}\n\t}\nprivate:\n\tvoid write_os(const char *buf, size_t size)\n\t{\n\t\tcybozu::OutputStreamTag<OutputStream>::write(os_, buf, size);\n\t}\n};\n\n\/**\n\tzlib decompressor class\n\tInputStream must have size_t read(char *str, size_t size);\n*\/\ntemplate<class InputStream, size_t maxBufSize = 2048>\nclass ZlibDecompressorT {\n\ttypedef cybozu::InputStreamTag<InputStream> In;\n\tInputStream& is_;\n\tunsigned int crc_;\n\tunsigned int totalSize_; \/* mod 2^32 *\/\n\tz_stream z_;\n\tint ret_;\n\tchar buf_[maxBufSize];\n\tconst bool useGzip_;\n\tbool readGzipHeader_;\n\tvoid readAll(char *buf, size_t size)\n\t{\n\t\tIn::read(is_, buf, size);\n\t}\n\tvoid skipToZero()\n\t{\n\t\tfor (;;) {\n\t\t\tchar buf[1];\n\t\t\treadAll(buf, 1);\n\t\t\tif (buf[0] == '\\0') break;\n\t\t}\n\t}\n\tvoid skip(int size)\n\t{\n\t\tfor (int i = 0 ; i < size; i++) {\n\t\t\tchar buf[1];\n\t\t\treadAll(buf, 1);\n\t\t}\n\t}\n\tvoid readGzipHeader()\n\t{\n\t\tchar header[10];\n\t\treadAll(header, sizeof(header));\n\t\tenum {\n\t\t\tFHCRC = 1 << 1,\n\t\t\tFEXTRA = 1 << 2,\n\t\t\tFNAME = 1 << 3,\n\t\t\tFCOMMENT = 1 << 4,\n\t\t\tRESERVED = 7 << 5,\n\t\t};\n\t\tchar flg = header[3];\n\t\tif (header[0] == '\\x1f'\n\t\t\t&& header[1] == '\\x8b'\n\t\t\t&& header[2] == Z_DEFLATED\n\t\t\t&& !(flg & RESERVED)) {\n\t\t\tif (flg & FEXTRA) {\n\t\t\t\tchar xlen[2];\n\t\t\t\treadAll(xlen, sizeof(xlen));\n\t\t\t\tint size = cybozu::Get16bitAsLE(xlen);\n\t\t\t\tskip(size);\n\t\t\t}\n\t\t\tif (flg & FNAME) {\n\t\t\t\tskipToZero();\n\t\t\t}\n\t\t\tif (flg & FCOMMENT) {\n\t\t\t\tskipToZero();\n\t\t\t}\n\t\t\tif (flg & FHCRC) {\n\t\t\t\tskip(2);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:readGzipHeader:bad gzip header\") << std::string(header, 10);\n\t}\n\tZlibDecompressorT(const ZlibDecompressorT&);\n\tvoid operator=(const ZlibDecompressorT&);\npublic:\n\t\/**\n\t\t@param os [in] input stream\n\t\t@param useGzip [in] useGzip if true, use deflate if false\n\t\t@note useGzip option is not fully tested, so default off\n\t*\/\n\tZlibDecompressorT(InputStream& is, bool useGzip = false)\n\t\t: is_(is)\n\t\t, crc_(crc32(0L, Z_NULL, 0))\n\t\t, totalSize_(0)\n\t\t, ret_(Z_OK)\n\t\t, useGzip_(useGzip)\n\t\t, readGzipHeader_(false)\n\t{\n\t\tz_.zalloc = Z_NULL;\n\t\tz_.zfree = Z_NULL;\n\t\tz_.opaque = Z_NULL;\n\t\tz_.next_in = 0;\n\t\tz_.avail_in = 0;\n\t\tif (useGzip_) {\n\t\t\tif (inflateInit2(&z_, -MAX_WBITS) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:inflateInit2\") << std::string(z_.msg);\n\t\t\t}\n\t\t} else {\n\t\t\tif (inflateInit(&z_) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:inflateInit\") << std::string(z_.msg);\n\t\t\t}\n\t\t}\n\t}\n\t~ZlibDecompressorT()\n\t{\n\t\tinflateEnd(&z_);\n\t}\n\t\/*\n\t\tdecompress is\n\t\t@param str [out] decompressed data\n\t\t@param str [out] max buf size\n\t\t@return read size\n\t*\/\n\tsize_t readSome(void *buf, size_t _size)\n\t{\n\t\tif (_size == 0) return 0;\n\t\tif (_size >= (1u << 31)) throw cybozu::Exception(\"zlib:ZlibDecompressorT:readSome:too large size\") << _size;\n\t\tuint32_t size = (uint32_t)_size;\n\t\tif (useGzip_ && !readGzipHeader_) {\n\t\t\treadGzipHeader();\n\t\t\treadGzipHeader_ = true;\n\t\t}\n\t\tz_.next_out = (Bytef*)buf;\n\t\tz_.avail_out = size;\n\t\tdo {\n\t\t\tif (z_.avail_in == 0) {\n\t\t\t\tz_.avail_in = (uint32_t)In::readSome(is_, buf_, maxBufSize);\n\t\t\t\tif (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0;\n\t\t\t\tz_.next_in = (Bytef*)buf_;\n\t\t\t}\n\t\t\tret_ = inflate(&z_, Z_NO_FLUSH);\n\t\t\tif (ret_ == Z_STREAM_END) break;\n\t\t\tif (ret_ != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:readSome:inflate\") << std::string(z_.msg);\n\t\t\t}\n\t\t} while (size == z_.avail_out);\n\n\t\treturn size - z_.avail_out;\n\t}\n\tvoid read(void *buf, size_t size)\n\t{\n\t\tchar *p = (char *)buf;\n\t\twhile (size > 0) {\n\t\t\tsize_t readSize = readSome(p, size);\n\t\t\tif (readSize == 0) throw cybozu::Exception(\"zlib:ZlibDecompressorT:read\");\n\t\t\tp += readSize;\n\t\t\tsize -= readSize;\n\t\t}\n\t}\n};\n\n} \/\/ cybozu\n\n<commit_msg>add isEmpty() to verify whether data is empty or not<commit_after>#pragma once\n\/**\n\t@file\n\t@brief zlib compressor and decompressor class\n\n\tCopyright (C) 2009 Cybozu Labs, Inc., all rights reserved.\n*\/\n\n#include <cybozu\/exception.hpp>\n#include <cybozu\/endian.hpp>\n#include <cybozu\/stream_fwd.hpp>\n#include <assert.h>\n#include <stdio.h>\n#include <zlib.h>\n\n#ifdef _MSC_VER\n\t#ifdef _DLL_CPPLIB\n\t\t#pragma comment(lib, \"zlib_md.lib\")\n\t#else\n\t\t#pragma comment(lib, \"zlib_mt.lib\")\n\t#endif\n#endif\n\nnamespace cybozu {\n\nnamespace zlib_local {\n\nconst int DEF_MEM_LEVEL = 8;\n\n} \/\/ zlib_local\n\n\/**\n\tzlib compressor class\n\tOutputStream must have size_t write(const char *buf, size_t size);\n*\/\ntemplate<class OutputStream, size_t maxBufSize = 2048>\nclass ZlibCompressorT {\n\tOutputStream& os_;\n\tunsigned int crc_;\n\tunsigned int totalSize_; \/* mod 2^32 *\/\n\tz_stream z_;\n\tchar buf_[maxBufSize];\n\tbool isFlushCalled_;\n\tconst bool useGzip_;\n\tZlibCompressorT(const ZlibCompressorT&);\n\tvoid operator=(const ZlibCompressorT&);\npublic:\n\t\/**\n\t\t@param os [in] output stream\n\t\t@param useGzip [in] useGzip if true, use deflate if false\n\t\t@note useGzip option is not fully tested, so default off\n\t*\/\n\tZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION)\n\t\t: os_(os)\n\t\t, crc_(crc32(0L, Z_NULL, 0))\n\t\t, totalSize_(0)\n\t\t, isFlushCalled_(false)\n\t\t, useGzip_(useGzip)\n\t{\n\t\tz_.zalloc = Z_NULL;\n\t\tz_.zfree = Z_NULL;\n\t\tz_.opaque = Z_NULL;\n\t\tif (useGzip_) {\n\t\t\tif (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressorT:deflateInit2\") << std::string(z_.msg);\n\t\t\t}\n\t\t\tchar header[] = \"\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\"; \/* OS_CODE = 0x03(Unix) *\/\n\t\t\twrite_os(header, 10);\n\t\t} else {\n\t\t\tif (deflateInit(&z_, compressionLevel) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressorT:deflateInit\") << std::string(z_.msg);\n\t\t\t}\n\t\t}\n\t}\n\t~ZlibCompressorT()\n\t{\n\t\tif (!isFlushCalled_) {\n\t\t\ttry {\n\t\t\t\tflush();\n\t\t\t} catch (std::exception& e) {\n\t\t\t\tfprintf(stderr, \"zlib:ZlibCompressor:flush:exception:%s\\n\", e.what());\n\t\t\t} catch (...) {\n\t\t\t\tfprintf(stderr, \"zlib:ZlibCompressor:flush:unknown exception\\n\");\n\t\t\t}\n\t\t}\n\t\tdeflateEnd(&z_);\n\t}\n\t\/*\n\t\tcompress buf\n\t\t@param buf [in] input data\n\t\t@param size [in] input data size\n\t*\/\n\tvoid write(const void *buf, size_t _size)\n\t{\n\t\tif (_size >= (1u << 31)) throw cybozu::Exception(\"zlib:ZlibCompressor:write:too large size\") << _size;\n\t\tuint32_t size = (uint32_t)_size;\n\t\tif (useGzip_) {\n\t\t\tcrc_ = crc32(crc_, (const Bytef *)buf, size);\n\t\t\ttotalSize_ += (unsigned int)size;\n\t\t}\n\t\tz_.next_in = (Bytef*)const_cast<char*>((const char*)buf);\n\t\tz_.avail_in = size;\n\t\twhile (z_.avail_in > 0) {\n\t\t\tz_.next_out = (Bytef*)buf_;\n\t\t\tz_.avail_out = maxBufSize;\n\n\t\t\tint ret = deflate(&z_, Z_NO_FLUSH);\n\t\t\tif (ret != Z_STREAM_END && ret != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressor:exec:compress\") << std::string(z_.msg);\n\t\t\t}\n\t\t\twrite_os(buf_, maxBufSize - z_.avail_out);\n\t\t\tif (ret == Z_STREAM_END) break;\n\t\t}\n\t}\n\tvoid flush()\n\t{\n\t\tisFlushCalled_ = true;\n\t\tz_.next_in = 0;\n\t\tz_.avail_in = 0;\n\n\t\tfor (;;) {\n\t\t\tz_.next_out = (Bytef*)buf_;\n\t\t\tz_.avail_out = maxBufSize;\n\n\t\t\tint ret = deflate(&z_, Z_FINISH);\n\t\t\tif (ret != Z_STREAM_END && ret != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibCompressor:flush\") << std::string(z_.msg);\n\t\t\t}\n\t\t\twrite_os(buf_, sizeof(buf_) - z_.avail_out);\n\t\t\tif (ret == Z_STREAM_END) break;\n\t\t}\n\t\tif (useGzip_) {\n\t\t\tchar tail[8];\n\t\t\tcybozu::Set32bitAsLE(&tail[0], crc_);\n\t\t\tcybozu::Set32bitAsLE(&tail[4], totalSize_);\n\t\t\twrite_os(tail, sizeof(tail));\n\t\t}\n\t}\nprivate:\n\tvoid write_os(const char *buf, size_t size)\n\t{\n\t\tcybozu::OutputStreamTag<OutputStream>::write(os_, buf, size);\n\t}\n};\n\n\/**\n\tzlib decompressor class\n\tInputStream must have size_t read(char *str, size_t size);\n*\/\ntemplate<class InputStream, size_t maxBufSize = 2048>\nclass ZlibDecompressorT {\n\ttypedef cybozu::InputStreamTag<InputStream> In;\n\tInputStream& is_;\n\tunsigned int crc_;\n\tunsigned int totalSize_; \/* mod 2^32 *\/\n\tz_stream z_;\n\tint ret_;\n\tchar buf_[maxBufSize];\n\tconst bool useGzip_;\n\tbool readGzipHeader_;\n\tvoid readAll(char *buf, size_t size)\n\t{\n\t\tIn::read(is_, buf, size);\n\t}\n\tvoid skipToZero()\n\t{\n\t\tfor (;;) {\n\t\t\tchar buf[1];\n\t\t\treadAll(buf, 1);\n\t\t\tif (buf[0] == '\\0') break;\n\t\t}\n\t}\n\tvoid skip(int size)\n\t{\n\t\tfor (int i = 0 ; i < size; i++) {\n\t\t\tchar buf[1];\n\t\t\treadAll(buf, 1);\n\t\t}\n\t}\n\tvoid readGzipHeader()\n\t{\n\t\tchar header[10];\n\t\treadAll(header, sizeof(header));\n\t\tenum {\n\t\t\tFHCRC = 1 << 1,\n\t\t\tFEXTRA = 1 << 2,\n\t\t\tFNAME = 1 << 3,\n\t\t\tFCOMMENT = 1 << 4,\n\t\t\tRESERVED = 7 << 5,\n\t\t};\n\t\tchar flg = header[3];\n\t\tif (header[0] == '\\x1f'\n\t\t\t&& header[1] == '\\x8b'\n\t\t\t&& header[2] == Z_DEFLATED\n\t\t\t&& !(flg & RESERVED)) {\n\t\t\tif (flg & FEXTRA) {\n\t\t\t\tchar xlen[2];\n\t\t\t\treadAll(xlen, sizeof(xlen));\n\t\t\t\tint size = cybozu::Get16bitAsLE(xlen);\n\t\t\t\tskip(size);\n\t\t\t}\n\t\t\tif (flg & FNAME) {\n\t\t\t\tskipToZero();\n\t\t\t}\n\t\t\tif (flg & FCOMMENT) {\n\t\t\t\tskipToZero();\n\t\t\t}\n\t\t\tif (flg & FHCRC) {\n\t\t\t\tskip(2);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:readGzipHeader:bad gzip header\") << std::string(header, 10);\n\t}\n\tZlibDecompressorT(const ZlibDecompressorT&);\n\tvoid operator=(const ZlibDecompressorT&);\npublic:\n\t\/**\n\t\t@param os [in] input stream\n\t\t@param useGzip [in] useGzip if true, use deflate if false\n\t\t@note useGzip option is not fully tested, so default off\n\t*\/\n\tZlibDecompressorT(InputStream& is, bool useGzip = false)\n\t\t: is_(is)\n\t\t, crc_(crc32(0L, Z_NULL, 0))\n\t\t, totalSize_(0)\n\t\t, ret_(Z_OK)\n\t\t, useGzip_(useGzip)\n\t\t, readGzipHeader_(false)\n\t{\n\t\tz_.zalloc = Z_NULL;\n\t\tz_.zfree = Z_NULL;\n\t\tz_.opaque = Z_NULL;\n\t\tz_.next_in = 0;\n\t\tz_.avail_in = 0;\n\t\tif (useGzip_) {\n\t\t\tif (inflateInit2(&z_, -MAX_WBITS) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:inflateInit2\") << std::string(z_.msg);\n\t\t\t}\n\t\t} else {\n\t\t\tif (inflateInit(&z_) != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:inflateInit\") << std::string(z_.msg);\n\t\t\t}\n\t\t}\n\t}\n\t~ZlibDecompressorT()\n\t{\n\t\tinflateEnd(&z_);\n\t}\n\t\/*\n\t\tdecompress is\n\t\t@param str [out] decompressed data\n\t\t@param str [out] max buf size\n\t\t@return read size\n\t*\/\n\tsize_t readSome(void *buf, size_t _size)\n\t{\n\t\tif (_size == 0) return 0;\n\t\tif (_size >= (1u << 31)) throw cybozu::Exception(\"zlib:ZlibDecompressorT:readSome:too large size\") << _size;\n\t\tuint32_t size = (uint32_t)_size;\n\t\tif (useGzip_ && !readGzipHeader_) {\n\t\t\treadGzipHeader();\n\t\t\treadGzipHeader_ = true;\n\t\t}\n\t\tz_.next_out = (Bytef*)buf;\n\t\tz_.avail_out = size;\n\t\tdo {\n\t\t\tif (z_.avail_in == 0) {\n\t\t\t\tz_.avail_in = (uint32_t)In::readSome(is_, buf_, maxBufSize);\n\t\t\t\tif (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0;\n\t\t\t\tz_.next_in = (Bytef*)buf_;\n\t\t\t}\n\t\t\tret_ = inflate(&z_, Z_NO_FLUSH);\n\t\t\tif (ret_ == Z_STREAM_END) break;\n\t\t\tif (ret_ != Z_OK) {\n\t\t\t\tthrow cybozu::Exception(\"zlib:ZlibDecompressorT:readSome:inflate\") << std::string(z_.msg);\n\t\t\t}\n\t\t} while (size == z_.avail_out);\n\n\t\treturn size - z_.avail_out;\n\t}\n\tbool isEmpty() const { return ret_ == Z_STREAM_END; }\n\tvoid read(void *buf, size_t size)\n\t{\n\t\tchar *p = (char *)buf;\n\t\twhile (size > 0) {\n\t\t\tsize_t readSize = readSome(p, size);\n\t\t\tif (readSize == 0) throw cybozu::Exception(\"zlib:ZlibDecompressorT:read\");\n\t\t\tp += readSize;\n\t\t\tsize -= readSize;\n\t\t}\n\t}\n};\n\n} \/\/ cybozu\n\n<|endoftext|>"} {"text":"<commit_before>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n\/\/ std::string input;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n char stdin_buffer[kBufferSize];\n memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\";\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n }\n\n\n\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize);\n\n if (read_stdin_size != 0) {\n if (stdin_buffer[0] == '\/') {\n ProcessInput(stdin_buffer);\n } else {\n \/\/ Send chat messages\n StripChar(stdin_buffer, '\\n');\n RequestSay(stdin_buffer);\n }\n }\n\n memset(&stdin_buffer, 0, kBufferSize);\n } \/\/ end of if STDIN\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<commit_msg>add std::end<commit_after>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n\/\/ std::string input;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n char stdin_buffer[kBufferSize];\n memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << std::endl;\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n }\n\n\n\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize);\n\n if (read_stdin_size != 0) {\n if (stdin_buffer[0] == '\/') {\n ProcessInput(stdin_buffer);\n } else {\n \/\/ Send chat messages\n StripChar(stdin_buffer, '\\n');\n RequestSay(stdin_buffer);\n }\n }\n\n memset(&stdin_buffer, 0, kBufferSize);\n } \/\/ end of if STDIN\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- llvm\/Transforms\/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ DecomposeMultiDimRefs - Convert multi-dimensional references consisting of\n\/\/ any combination of 2 or more array and structure indices into a sequence of\n\/\/ instructions (using getelementpr and cast) so that each instruction has at\n\/\/ most one index (except structure references, which need an extra leading\n\/\/ index of [0]).\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumAdded(\"lowerrefs\", \"# of getelementptr instructions added\");\n\n struct DecomposePass : public BasicBlockPass {\n virtual bool runOnBasicBlock(BasicBlock &BB);\n };\n RegisterOpt<DecomposePass> X(\"lowerrefs\", \"Decompose multi-dimensional \"\n \"structure\/array references\");\n}\n\n\/\/ runOnBasicBlock - Entry point for array or structure references with multiple\n\/\/ indices.\n\/\/\nbool DecomposePass::runOnBasicBlock(BasicBlock &BB) {\n bool changed = false;\n for (BasicBlock::iterator II = BB.begin(); II != BB.end(); )\n if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(II++)) \/\/ pre-inc\n if (gep->getNumIndices() >= 2)\n changed |= DecomposeArrayRef(gep); \/\/ always modifies II\n return changed;\n}\n\nFunctionPass *llvm::createDecomposeMultiDimRefsPass() {\n return new DecomposePass();\n}\n\n\/\/ Function: DecomposeArrayRef()\n\/\/ \n\/\/ For any GetElementPtrInst with 2 or more array and structure indices:\n\/\/ \n\/\/ opCode CompositeType* P, [uint|ubyte] idx1, ..., [uint|ubyte] idxN\n\/\/ \n\/\/ this function generates the foll sequence:\n\/\/ \n\/\/ ptr1 = getElementPtr P, idx1\n\/\/ ptr2 = getElementPtr ptr1, 0, idx2\n\/\/ ...\n\/\/ ptrN-1 = getElementPtr ptrN-2, 0, idxN-1\n\/\/ opCode ptrN-1, 0, idxN \/\/ New-MAI\n\/\/ \n\/\/ Then it replaces the original instruction with this sequence,\n\/\/ and replaces all uses of the original instruction with New-MAI.\n\/\/ If idx1 is 0, we simply omit the first getElementPtr instruction.\n\/\/ \n\/\/ On return: BBI points to the instruction after the current one\n\/\/ (whether or not *BBI was replaced).\n\/\/ \n\/\/ Return value: true if the instruction was replaced; false otherwise.\n\/\/ \nbool llvm::DecomposeArrayRef(GetElementPtrInst* GEP) {\n if (GEP->getNumIndices() < 2)\n return false;\n\n BasicBlock *BB = GEP->getParent();\n Value *LastPtr = GEP->getPointerOperand();\n Instruction *InsertPoint = GEP->getNext(); \/\/ Insert before the next insn\n\n \/\/ The vector of new instructions to be created\n std::vector<Instruction*> NewInsts;\n\n \/\/ Process each index except the last one.\n User::const_op_iterator OI = GEP->idx_begin(), OE = GEP->idx_end();\n for (; OI+1 != OE; ++OI) {\n std::vector<Value*> Indices;\n \n \/\/ If this is the first index and is 0, skip it and move on!\n if (OI == GEP->idx_begin()) {\n if (*OI == ConstantInt::getNullValue((*OI)->getType()))\n continue;\n }\n else \/\/ Not the first index: include initial [0] to deref the last ptr\n Indices.push_back(Constant::getNullValue(Type::LongTy));\n\n Indices.push_back(*OI);\n\n \/\/ New Instruction: nextPtr1 = GetElementPtr LastPtr, Indices\n LastPtr = new GetElementPtrInst(LastPtr, Indices, \"ptr1\", InsertPoint);\n ++NumAdded;\n }\n\n \/\/ Now create a new instruction to replace the original one\n \/\/\n const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());\n\n \/\/ Get the final index vector, including an initial [0] as before.\n std::vector<Value*> Indices;\n Indices.push_back(Constant::getNullValue(Type::LongTy));\n Indices.push_back(*OI);\n\n Value *NewVal = new GetElementPtrInst(LastPtr, Indices, GEP->getName(),\n InsertPoint);\n\n \/\/ Replace all uses of the old instruction with the new\n GEP->replaceAllUsesWith(NewVal);\n\n \/\/ Now remove and delete the old instruction...\n BB->getInstList().erase(GEP);\n\n return true;\n}\n\n<commit_msg>Get rid of a dead variable, and fix a typo in a comment.<commit_after>\/\/===- llvm\/Transforms\/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ DecomposeMultiDimRefs - Convert multi-dimensional references consisting of\n\/\/ any combination of 2 or more array and structure indices into a sequence of\n\/\/ instructions (using getelementpr and cast) so that each instruction has at\n\/\/ most one index (except structure references, which need an extra leading\n\/\/ index of [0]).\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumAdded(\"lowerrefs\", \"# of getelementptr instructions added\");\n\n struct DecomposePass : public BasicBlockPass {\n virtual bool runOnBasicBlock(BasicBlock &BB);\n };\n RegisterOpt<DecomposePass> X(\"lowerrefs\", \"Decompose multi-dimensional \"\n \"structure\/array references\");\n}\n\n\/\/ runOnBasicBlock - Entry point for array or structure references with multiple\n\/\/ indices.\n\/\/\nbool DecomposePass::runOnBasicBlock(BasicBlock &BB) {\n bool changed = false;\n for (BasicBlock::iterator II = BB.begin(); II != BB.end(); )\n if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(II++)) \/\/ pre-inc\n if (gep->getNumIndices() >= 2)\n changed |= DecomposeArrayRef(gep); \/\/ always modifies II\n return changed;\n}\n\nFunctionPass *llvm::createDecomposeMultiDimRefsPass() {\n return new DecomposePass();\n}\n\n\/\/ Function: DecomposeArrayRef()\n\/\/ \n\/\/ For any GetElementPtrInst with 2 or more array and structure indices:\n\/\/ \n\/\/ opCode CompositeType* P, [uint|ubyte] idx1, ..., [uint|ubyte] idxN\n\/\/ \n\/\/ this function generates the following sequence:\n\/\/ \n\/\/ ptr1 = getElementPtr P, idx1\n\/\/ ptr2 = getElementPtr ptr1, 0, idx2\n\/\/ ...\n\/\/ ptrN-1 = getElementPtr ptrN-2, 0, idxN-1\n\/\/ opCode ptrN-1, 0, idxN \/\/ New-MAI\n\/\/ \n\/\/ Then it replaces the original instruction with this sequence,\n\/\/ and replaces all uses of the original instruction with New-MAI.\n\/\/ If idx1 is 0, we simply omit the first getElementPtr instruction.\n\/\/ \n\/\/ On return: BBI points to the instruction after the current one\n\/\/ (whether or not *BBI was replaced).\n\/\/ \n\/\/ Return value: true if the instruction was replaced; false otherwise.\n\/\/ \nbool llvm::DecomposeArrayRef(GetElementPtrInst* GEP) {\n if (GEP->getNumIndices() < 2)\n return false;\n\n BasicBlock *BB = GEP->getParent();\n Value *LastPtr = GEP->getPointerOperand();\n Instruction *InsertPoint = GEP->getNext(); \/\/ Insert before the next insn\n\n \/\/ Process each index except the last one.\n User::const_op_iterator OI = GEP->idx_begin(), OE = GEP->idx_end();\n for (; OI+1 != OE; ++OI) {\n std::vector<Value*> Indices;\n \n \/\/ If this is the first index and is 0, skip it and move on!\n if (OI == GEP->idx_begin()) {\n if (*OI == ConstantInt::getNullValue((*OI)->getType()))\n continue;\n }\n else \/\/ Not the first index: include initial [0] to deref the last ptr\n Indices.push_back(Constant::getNullValue(Type::LongTy));\n\n Indices.push_back(*OI);\n\n \/\/ New Instruction: nextPtr1 = GetElementPtr LastPtr, Indices\n LastPtr = new GetElementPtrInst(LastPtr, Indices, \"ptr1\", InsertPoint);\n ++NumAdded;\n }\n\n \/\/ Now create a new instruction to replace the original one\n \/\/\n const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());\n\n \/\/ Get the final index vector, including an initial [0] as before.\n std::vector<Value*> Indices;\n Indices.push_back(Constant::getNullValue(Type::LongTy));\n Indices.push_back(*OI);\n\n Value *NewVal = new GetElementPtrInst(LastPtr, Indices, GEP->getName(),\n InsertPoint);\n\n \/\/ Replace all uses of the old instruction with the new\n GEP->replaceAllUsesWith(NewVal);\n\n \/\/ Now remove and delete the old instruction...\n BB->getInstList().erase(GEP);\n\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <decaf\/internal\/util\/concurrent\/Atomics.h>\n\n#ifndef HAVE_ATOMIC_BUILTINS\n#if defined(SOLARIS2) && SOLARIS2 >= 10\n#include <atomic.h>\n#endif\n#endif\n\nusing namespace decaf::internal;\nusing namespace decaf::internal::util;\nusing namespace decaf::internal::util::concurrent;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef HAVE_ATOMIC_BUILTINS\n\n#include <decaf\/internal\/util\/concurrent\/PlatformThread.h>\n\nnamespace {\n decaf_mutex_t atomicMutex;\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Atomics::initialize() {\n#ifndef HAVE_ATOMIC_BUILTINS\n PlatformThread::createMutex(&atomicMutex);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Atomics::shutdown() {\n#ifndef HAVE_ATOMIC_BUILTINS\n PlatformThread::destroyMutex(atomicMutex);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {\n\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_val_compare_and_swap(target, expect, update) == (unsigned int)expect;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_cas_32((volatile unsigned int*)target, expect, update);\n#else\n bool result = false;\n PlatformThread::lockMutex(atomicMutex);\n\n if (*target == expect) {\n *target = update;\n result = true;\n }\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return result;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_val_compare_and_swap(target, (void*)expect, (void*)update) == (void*)expect;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_cas_ptr(target, expect, update);\n#else\n bool result = false;\n PlatformThread::lockMutex(atomicMutex);\n\n if (*target == expect) {\n *target = update;\n result = true;\n }\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return result;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndSet(volatile int* target, int newValue) {\n#ifdef HAVE_ATOMIC_BUILTINS\n __sync_synchronize();\n return __sync_lock_test_and_set(target, newValue);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_swap_32(target, newValue);\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n *target = newValue;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid* Atomics::getAndSet(volatile void** target, void* newValue) {\n#ifdef HAVE_ATOMIC_BUILTINS\n __sync_synchronize();\n return (void*) __sync_lock_test_and_set(target, newValue);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_swap_ptr(target, newValue);\n#elif defined(__APPLE__)\n return atomic_swap_32(target, newValue);\n#else\n void* oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *(void **)target;\n *target = newValue;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndIncrement(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 1);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(mem, 1) - 1;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n (*target)++;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndDecrement(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 0xFFFFFFFF);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(target, 0xFFFFFFFF) + 1;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n (*target)--;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndAdd(volatile int* target, int delta) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, delta);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(target, delta) - delta;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n *target += delta;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::addAndGet(volatile int* target, int delta) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, delta) + delta;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(target, delta);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n *target += delta;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::incrementAndGet(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 1) + 1;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(target, 1);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n (*target)++;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::decrementAndGet(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 0xFFFFFFFF) - 1;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv(target, 0xFFFFFFFF);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n (*target)--;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n<commit_msg>fix for: https:\/\/issues.apache.org\/jira\/browse\/AMQCPP-475<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <decaf\/internal\/util\/concurrent\/Atomics.h>\n\n#ifndef HAVE_ATOMIC_BUILTINS\n#if defined(SOLARIS2) && SOLARIS2 >= 10\n#include <atomic.h>\n#endif\n#endif\n\nusing namespace decaf::internal;\nusing namespace decaf::internal::util;\nusing namespace decaf::internal::util::concurrent;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef HAVE_ATOMIC_BUILTINS\n\n#include <decaf\/internal\/util\/concurrent\/PlatformThread.h>\n\nnamespace {\n decaf_mutex_t atomicMutex;\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Atomics::initialize() {\n#ifndef HAVE_ATOMIC_BUILTINS\n PlatformThread::createMutex(&atomicMutex);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Atomics::shutdown() {\n#ifndef HAVE_ATOMIC_BUILTINS\n PlatformThread::destroyMutex(atomicMutex);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {\n\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_val_compare_and_swap(target, expect, update) == expect;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_cas_32((volatile unsigned int*)target, expect, update) == expect;\n#else\n bool result = false;\n PlatformThread::lockMutex(atomicMutex);\n\n if (*target == expect) {\n *target = update;\n result = true;\n }\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return result;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_val_compare_and_swap(target, (void*)expect, (void*)update) == (void*)expect;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_cas_ptr(target, expect, update) == expect;\n#else\n bool result = false;\n PlatformThread::lockMutex(atomicMutex);\n\n if (*target == expect) {\n *target = update;\n result = true;\n }\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return result;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndSet(volatile int* target, int newValue) {\n#ifdef HAVE_ATOMIC_BUILTINS\n __sync_synchronize();\n return __sync_lock_test_and_set(target, newValue);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_swap_32((volatile unsigned int*)target, newValue);\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n *target = newValue;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid* Atomics::getAndSet(volatile void** target, void* newValue) {\n#ifdef HAVE_ATOMIC_BUILTINS\n __sync_synchronize();\n return (void*) __sync_lock_test_and_set(target, newValue);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_swap_ptr(target, newValue);\n#elif defined(__APPLE__)\n return atomic_swap_32(target, newValue);\n#else\n void* oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *(void **)target;\n *target = newValue;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndIncrement(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 1);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, 1) - 1;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n (*target)++;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndDecrement(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 0xFFFFFFFF);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, 0xFFFFFFFF) + 1;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n (*target)--;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::getAndAdd(volatile int* target, int delta) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, delta);\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, delta) - delta;\n#else\n int oldValue;\n PlatformThread::lockMutex(atomicMutex);\n\n oldValue = *target;\n *target += delta;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return oldValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::addAndGet(volatile int* target, int delta) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, delta) + delta;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, delta);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n *target += delta;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::incrementAndGet(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 1) + 1;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, 1);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n (*target)++;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint Atomics::decrementAndGet(volatile int* target) {\n#ifdef HAVE_ATOMIC_BUILTINS\n return __sync_fetch_and_add(target, 0xFFFFFFFF) - 1;\n#elif defined(SOLARIS2) && SOLARIS2 >= 10\n return atomic_add_32_nv((volatile unsigned int*)target, 0xFFFFFFFF);\n#else\n int newValue;\n PlatformThread::lockMutex(atomicMutex);\n\n (*target)--;\n newValue = *target;\n\n PlatformThread::unlockMutex(atomicMutex);\n\n return newValue;\n#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"ui_SimpleViewUI.h\"\n#include \"SimpleViewUI.h\"\n\n#include <QFileDialog>\n#include <vtkCamera.h>\n\n#include \"vtkKWImage.h\"\n#include \"vtkKWImageIO.h\"\n\n\/\/ Constructor\nSimpleView::SimpleView()\n{\n this->ui = new Ui_SimpleView;\n this->ui->setupUi(this);\n\n renderer = vtkSmartPointer<vtkRenderer>::New();\n\n this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(renderer);\n\n vtkRenderWindowInteractor * renderInteractor = this->ui->qvtkWidget->GetInteractor();\n\n planeWidget1 = vtkSmartPointer<vtkImagePlaneWidget>::New();\n planeWidget2 = vtkSmartPointer<vtkImagePlaneWidget>::New();\n\n planeWidget1->SetInteractor( renderInteractor );\n planeWidget2->SetInteractor( renderInteractor );\n\n double origin[3] = {0,1,0};\n\n planeWidget1->SetOrigin(origin);\n planeWidget1->UpdatePlacement();\n\n planeWidget2->SetOrigin(origin);\n planeWidget2->UpdatePlacement();\n\n picker1 = vtkSmartPointer< vtkCellPicker >::New();\n picker2 = vtkSmartPointer< vtkCellPicker >::New();\n\n picker1->SetTolerance(0.005);\n picker2->SetTolerance(0.005);\n\n property1 = vtkSmartPointer< vtkProperty >::New();\n property2 = vtkSmartPointer< vtkProperty >::New();\n\n renderer->SetBackground(0.329,0.349,0.427);\n renderer->SetBackground2(0.658,0.698,0.855);\n renderer->GradientBackgroundOn();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n\n \/\/ Set up action signals and slots\n connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit()));\n connect(this->ui->pushButton1, SIGNAL(pressed()), this, SLOT(slotLoadImage1()));\n connect(this->ui->pushButton2, SIGNAL(pressed()), this, SLOT(slotLoadImage2()));\n};\n\nvoid SimpleView::slotExit()\n{\n qApp->exit();\n}\n\nstd::string SimpleView::GetFileName()\n{\n QFileDialog fileDialog(this);\n\n fileDialog.setViewMode( QFileDialog::Detail );\n\n QStringList filters;\n filters << \"Image files (*.*)\";\n\n fileDialog.setFilters( filters );\n fileDialog.setLabelText( QFileDialog::LookIn,\"Select Input\");\n\n fileDialog.exec();\n\n QStringList listOfFiles = fileDialog.selectedFiles();\n\n std::string inputFilename = listOfFiles[0].toStdString();\n\n return inputFilename;\n}\n\nvoid SimpleView::slotLoadImage1()\n{\n std::string inputFilename = this->GetFileName();\n\n vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();\n\n kwreader->SetFileName( inputFilename );\n kwreader->ReadImage();\n\n vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();\n\n vtkImageData * vtkimage1 = kwimage->GetVTKImage();\n\n planeWidget1->SetInput( vtkimage1 );\n\n int x0, x1, y0, y1, z0, z1;\n\n vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );\n\n int middleSliceNumber = ( z1 + z0 ) \/ 2;\n\n planeWidget1->SetPlaneOrientationToZAxes();\n planeWidget1->SetSlicePosition( middleSliceNumber );\n planeWidget1->SetPicker(picker1);\n planeWidget1->RestrictPlaneToVolumeOn();\n planeWidget1->SetKeyPressActivationValue('z');\n planeWidget1->SetTexturePlaneProperty(property1);\n planeWidget1->On();\n\n planeWidget2->SetPlaneOrientationToZAxes();\n planeWidget2->SetSlicePosition( middleSliceNumber );\n planeWidget2->SetPicker(picker2);\n planeWidget2->RestrictPlaneToVolumeOn();\n planeWidget2->SetKeyPressActivationValue('z');\n planeWidget2->SetTexturePlaneProperty(property2);\n planeWidget2->On();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n}\n\nvoid SimpleView::slotLoadImage2()\n{\n std::string inputFilename = this->GetFileName();\n\n vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();\n\n kwreader->SetFileName( inputFilename );\n kwreader->ReadImage();\n\n vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();\n\n vtkImageData * vtkimage1 = kwimage->GetVTKImage();\n\n planeWidget1->SetInput( vtkimage1 );\n\n int x0, x1, y0, y1, z0, z1;\n\n vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );\n\n int middleSliceNumber = ( z1 + z0 ) \/ 2;\n\n planeWidget1->SetPlaneOrientationToZAxes();\n planeWidget1->SetSlicePosition( middleSliceNumber );\n planeWidget1->SetPicker(picker1);\n planeWidget1->RestrictPlaneToVolumeOn();\n planeWidget1->SetKeyPressActivationValue('z');\n planeWidget1->SetTexturePlaneProperty(property1);\n planeWidget1->On();\n\n planeWidget2->SetPlaneOrientationToZAxes();\n planeWidget2->SetSlicePosition( middleSliceNumber );\n planeWidget2->SetPicker(picker2);\n planeWidget2->RestrictPlaneToVolumeOn();\n planeWidget2->SetKeyPressActivationValue('z');\n planeWidget2->SetTexturePlaneProperty(property2);\n planeWidget2->On();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n}\n<commit_msg>ENH: Connected two image planes.<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"ui_SimpleViewUI.h\"\n#include \"SimpleViewUI.h\"\n\n#include <QFileDialog>\n#include <vtkCamera.h>\n\n#include \"vtkKWImage.h\"\n#include \"vtkKWImageIO.h\"\n\n\/\/ Constructor\nSimpleView::SimpleView()\n{\n this->ui = new Ui_SimpleView;\n this->ui->setupUi(this);\n\n renderer = vtkSmartPointer<vtkRenderer>::New();\n\n this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(renderer);\n\n vtkRenderWindowInteractor * renderInteractor = this->ui->qvtkWidget->GetInteractor();\n\n planeWidget1 = vtkSmartPointer<vtkImagePlaneWidget>::New();\n planeWidget2 = vtkSmartPointer<vtkImagePlaneWidget>::New();\n\n planeWidget1->SetInteractor( renderInteractor );\n planeWidget2->SetInteractor( renderInteractor );\n\n double origin[3] = {0,1,0};\n\n planeWidget1->SetOrigin(origin);\n planeWidget1->UpdatePlacement();\n\n planeWidget2->SetOrigin(origin);\n planeWidget2->UpdatePlacement();\n\n picker1 = vtkSmartPointer< vtkCellPicker >::New();\n picker2 = vtkSmartPointer< vtkCellPicker >::New();\n\n picker1->SetTolerance(0.005);\n picker2->SetTolerance(0.005);\n\n property1 = vtkSmartPointer< vtkProperty >::New();\n property2 = vtkSmartPointer< vtkProperty >::New();\n\n renderer->SetBackground(0.329,0.349,0.427);\n renderer->SetBackground2(0.658,0.698,0.855);\n renderer->GradientBackgroundOn();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n\n \/\/ Set up action signals and slots\n connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit()));\n connect(this->ui->pushButton1, SIGNAL(pressed()), this, SLOT(slotLoadImage1()));\n connect(this->ui->pushButton2, SIGNAL(pressed()), this, SLOT(slotLoadImage2()));\n};\n\nvoid SimpleView::slotExit()\n{\n qApp->exit();\n}\n\nstd::string SimpleView::GetFileName()\n{\n QFileDialog fileDialog(this);\n\n fileDialog.setViewMode( QFileDialog::Detail );\n\n QStringList filters;\n filters << \"Image files (*.*)\";\n\n fileDialog.setFilters( filters );\n fileDialog.setLabelText( QFileDialog::LookIn,\"Select Input\");\n\n fileDialog.exec();\n\n QStringList listOfFiles = fileDialog.selectedFiles();\n\n std::string inputFilename = listOfFiles[0].toStdString();\n\n return inputFilename;\n}\n\nvoid SimpleView::slotLoadImage1()\n{\n std::string inputFilename = this->GetFileName();\n\n vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();\n\n kwreader->SetFileName( inputFilename );\n kwreader->ReadImage();\n\n vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();\n\n vtkImageData * vtkimage1 = kwimage->GetVTKImage();\n\n planeWidget1->SetInput( vtkimage1 );\n\n int x0, x1, y0, y1, z0, z1;\n\n vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );\n\n int middleSliceNumber = ( z1 + z0 ) \/ 2;\n\n planeWidget1->SetPlaneOrientationToZAxes();\n planeWidget1->SetSlicePosition( middleSliceNumber );\n planeWidget1->SetPicker(picker1);\n planeWidget1->RestrictPlaneToVolumeOn();\n planeWidget1->SetKeyPressActivationValue('z');\n planeWidget1->SetTexturePlaneProperty(property1);\n planeWidget1->On();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n}\n\nvoid SimpleView::slotLoadImage2()\n{\n std::string inputFilename = this->GetFileName();\n\n vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();\n\n kwreader->SetFileName( inputFilename );\n kwreader->ReadImage();\n\n vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();\n\n vtkImageData * vtkimage2 = kwimage->GetVTKImage();\n\n planeWidget2->SetInput( vtkimage2 );\n\n int x0, x1, y0, y1, z0, z1;\n\n vtkimage2->GetExtent( x0, x1, y0, y1, z0, z1 );\n\n int middleSliceNumber = ( z1 + z0 ) \/ 2;\n\n planeWidget2->SetPlaneOrientationToZAxes();\n planeWidget2->SetSlicePosition( middleSliceNumber );\n planeWidget2->SetPicker(picker2);\n planeWidget2->RestrictPlaneToVolumeOn();\n planeWidget2->SetKeyPressActivationValue('z');\n planeWidget2->SetTexturePlaneProperty(property2);\n planeWidget2->On();\n\n vtkCamera * camera = renderer->GetActiveCamera();\n\n camera->SetPosition ( 0.5, 0.5, -1 );\n camera->SetViewUp( 0, -1, 0 );\n\n renderer->ResetCamera();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ T0 Tender supply \/\/\n\/\/ \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <AliESDEvent.h>\n#include <AliESDtrack.h>\n\n#include <AliTender.h>\n#include <AliT0TenderSupply.h>\n#include <AliCDBManager.h>\n#include <AliCDBEntry.h>\n#include <AliT0CalibSeasonTimeShift.h>\n\n\nClassImp(AliT0TenderSupply)\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::AliT0TenderSupply():\n AliTenderSupply(),\n fCorrectMeanTime(kFALSE),\n fCorrectStartTimeOnAmplSatur(kFALSE),\n fAmplitudeThreshold(100), \n fPass4LHC11aCorrection(kFALSE)\n{\n \/\/\n \/\/ default constructor\n \/\/\n for(int i=0; i<4; i++) fTimeOffset[i]=0;\n}\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::AliT0TenderSupply(const char *name, const AliTender *tender):\n AliTenderSupply(name,tender),\n fCorrectMeanTime(kFALSE),\n fCorrectStartTimeOnAmplSatur(kFALSE),\n fAmplitudeThreshold(100),\n fPass4LHC11aCorrection(kFALSE)\n{\n \/\/\n \/\/ constructor\n \/\/\n for(int i=0; i<3; i++) fTimeOffset[i]=0;\n}\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::~AliT0TenderSupply(){\n \/\/\n \/\/ destructor\n \/\/\n \n}\n\n\/\/________________________________________________________________________\nvoid AliT0TenderSupply::Init(){\n \/\/\n \/\/ Init\n \/\/\n Int_t run = fTender->GetRun();\n if (run == 0) return; \/\/ to skip first init, when we don't have yet a run number\n\n fCorrectMeanTime = kFALSE; \/\/reset\n for(int i=0; i<4; i++) fTimeOffset[i]=0;\n\n\n fCorrectStartTimeOnAmplSatur = kFALSE;\n fAmplitudeThreshold = 100; \/\/in mips\n \n if(167693<= run && run<=170593){ \/\/ LHC11h\n fCorrectStartTimeOnAmplSatur = kTRUE;\n fAmplitudeThreshold = 50; \/\/in mips\n }\n\n}\n\n\/\/________________________________________________________________________\nvoid AliT0TenderSupply::ProcessEvent(){\n \/\/\n \/\/ loop over all online T0 candidates and flag\n \/\/ selected daughter tracks using the status bis of the TObject\n \/\/\n\n AliESDEvent *event=fTender->GetEvent();\n if (!event) return;\n\n \/\/Do something when the run number changed, like loading OCDB entries etc.\n if(fTender->RunChanged()){\n Init();\n }\n\n if(fPass4LHC11aCorrection) {\n const Double32_t* mean = event->GetT0TOF();\n event->SetT0TOF(0, (mean[1]+mean[2])\/2.);\n\n }\n if(fCorrectStartTimeOnAmplSatur){\n \/\/correct A side ORA on amplitude saturation\n const Double32_t* time = event->GetT0time();\n const Double32_t* amplitude = event->GetT0amplitude();\n\n Int_t idxOfFirstPmtA = -1;\n Double32_t timeOrA = 99999;\n for(int ipmt=12; ipmt<24; ipmt++){ \/\/loop over A side\n if( amplitude[ipmt] < fAmplitudeThreshold){\n if( time[ipmt] > -200 && time[ipmt]!=0 && time[ipmt] < timeOrA ){ \n timeOrA = time[ipmt];\n idxOfFirstPmtA = ipmt;\n }\n }\n }\n\n if(idxOfFirstPmtA>-1){ \/\/a hit in aside with less than 40 mips\n const Double32_t* mean = event->GetT0TOF();\n Double32_t timeOrC = mean[2];\n Double32_t timeOrAplusOrC = (timeOrA+timeOrC)\/2;\n\n event->SetT0TOF(0, timeOrAplusOrC);\n event->SetT0TOF(1, timeOrA);\n }\n }\n\n \/\/...........................................\n Float_t *t0means=0x0;\n if(fCorrectMeanTime){\n AliCDBManager* ocdbMan = AliCDBManager::Instance();\n ocdbMan->SetRun(fTender->GetRun()); \n AliCDBEntry *entry = ocdbMan->Get(\"T0\/Calib\/TimeAdjust\/\");\n if(entry) {\n\tAliT0CalibSeasonTimeShift *clb = (AliT0CalibSeasonTimeShift*) entry->GetObject();\n\tt0means= clb->GetT0Means();\n } else {\n\tfor (Int_t i=0;i<4;i++) t0means[i]=0;\n\tAliWarning(\"T0Tender no T0 entry found T0shift set to 0\");\n }\n } else {\n for (Int_t i=0;i<4;i++) t0means=0;\n }\n \/\/ correct mean time offsets \n const Double32_t* mean = event->GetT0TOF();\n for(int it0=0; it0<3; it0++){\n if(-2000 < mean[it0]){\n\t event->SetT0TOF(it0, mean[it0] - t0means[it0]); \n }\n }\n}\n\n\n<commit_msg>o automatic detection of 11a pass4 (Alla)<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ T0 Tender supply \/\/\n\/\/ \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <AliESDEvent.h>\n#include <AliESDtrack.h>\n\n#include <AliTender.h>\n#include <AliT0TenderSupply.h>\n#include <AliCDBManager.h>\n#include <AliCDBEntry.h>\n#include <AliT0CalibSeasonTimeShift.h>\n#include <AliESDInputHandler.h>\n\nClassImp(AliT0TenderSupply)\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::AliT0TenderSupply():\n AliTenderSupply(),\n fCorrectMeanTime(kFALSE),\n fCorrectStartTimeOnAmplSatur(kFALSE),\n fAmplitudeThreshold(100), \n fPass4LHC11aCorrection(kFALSE)\n{\n \/\/\n \/\/ default constructor\n \/\/\n for(int i=0; i<4; i++) fTimeOffset[i]=0;\n}\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::AliT0TenderSupply(const char *name, const AliTender *tender):\n AliTenderSupply(name,tender),\n fCorrectMeanTime(kFALSE),\n fCorrectStartTimeOnAmplSatur(kFALSE),\n fAmplitudeThreshold(100),\n fPass4LHC11aCorrection(kFALSE)\n{\n \/\/\n \/\/ constructor\n \/\/\n for(int i=0; i<3; i++) fTimeOffset[i]=0;\n}\n\n\/\/________________________________________________________________________\nAliT0TenderSupply::~AliT0TenderSupply(){\n \/\/\n \/\/ destructor\n \/\/\n \n}\n\n\/\/________________________________________________________________________\nvoid AliT0TenderSupply::Init(){\n \/\/ Init\n \/\/\n Int_t run = fTender->GetRun();\n if (run == 0) return; \/\/ to skip first init, when we don't have yet a run number\n fPass4LHC11aCorrection=kFALSE;\n \n\n fCorrectMeanTime = kFALSE; \/\/reset\n for(int i=0; i<4; i++) fTimeOffset[i]=0;\n\n\n fCorrectStartTimeOnAmplSatur = kFALSE;\n fAmplitudeThreshold = 100; \/\/in mips\n \n if(167693<= run && run<=170593){ \/\/ LHC11h\n fCorrectStartTimeOnAmplSatur = kTRUE;\n fAmplitudeThreshold = 50; \/\/in mips\n }\n\n}\n\n\/\/________________________________________________________________________\nvoid AliT0TenderSupply::ProcessEvent(){\n \/\/\n \/\/ loop over all online T0 candidates and flag\n \/\/ selected daughter tracks using the status bis of the TObject\n \/\/\n\n AliESDEvent *event=fTender->GetEvent();\n if (!event) return;\n\n \/\/Do something when the run number changed, like loading OCDB entries etc.\n fPass4LHC11aCorrection=kFALSE;\n if(fTender->RunChanged()){\n Init();\n if (fTender->GetRun()>=139699&& fTender->GetRun()<=146860){\n AliESDInputHandler *esdIH = dynamic_cast<AliESDInputHandler*> (fTender->GetESDhandler());\n if (esdIH) {\n TTree *tree= (TTree*)esdIH->GetTree();\n TFile *file= (TFile*)tree->GetCurrentFile();\n if (file){\n TString fileName(file->GetName());\n if (fileName.Contains(\"pass4\") ) fPass4LHC11aCorrection=kTRUE;\n\t }\n\t}\n }\n }\n\n if(fPass4LHC11aCorrection) {\n const Double32_t* mean = event->GetT0TOF();\n event->SetT0TOF(0, (mean[1]+mean[2])\/2.);\n\n }\n if(fCorrectStartTimeOnAmplSatur){\n \/\/correct A side ORA on amplitude saturation\n const Double32_t* time = event->GetT0time();\n const Double32_t* amplitude = event->GetT0amplitude();\n\n Int_t idxOfFirstPmtA = -1;\n Double32_t timeOrA = 99999;\n for(int ipmt=12; ipmt<24; ipmt++){ \/\/loop over A side\n if( amplitude[ipmt] < fAmplitudeThreshold){\n if( time[ipmt] > -200 && time[ipmt]!=0 && time[ipmt] < timeOrA ){ \n timeOrA = time[ipmt];\n idxOfFirstPmtA = ipmt;\n }\n }\n }\n\n if(idxOfFirstPmtA>-1){ \/\/a hit in aside with less than 40 mips\n const Double32_t* mean = event->GetT0TOF();\n Double32_t timeOrC = mean[2];\n Double32_t timeOrAplusOrC = (timeOrA+timeOrC)\/2;\n\n event->SetT0TOF(0, timeOrAplusOrC);\n event->SetT0TOF(1, timeOrA);\n }\n }\n\n \/\/...........................................\n Float_t *t0means=0x0;\n if(fCorrectMeanTime){\n AliCDBManager* ocdbMan = AliCDBManager::Instance();\n ocdbMan->SetRun(fTender->GetRun()); \n AliCDBEntry *entry = ocdbMan->Get(\"T0\/Calib\/TimeAdjust\/\");\n if(entry) {\n\tAliT0CalibSeasonTimeShift *clb = (AliT0CalibSeasonTimeShift*) entry->GetObject();\n\tt0means= clb->GetT0Means();\n } else {\n\tfor (Int_t i=0;i<4;i++) t0means[i]=0;\n\tAliWarning(\"T0Tender no T0 entry found T0shift set to 0\");\n }\n } else {\n for (Int_t i=0;i<4;i++) t0means=0;\n }\n \/\/ correct mean time offsets \n const Double32_t* mean = event->GetT0TOF();\n for(int it0=0; it0<3; it0++){\n if(-2000 < mean[it0]){\n\t event->SetT0TOF(it0, mean[it0] - t0means[it0]); \n }\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <Hord\/Rule\/Defs.hpp>\n#include <Hord\/Error.hpp>\n#include <Hord\/System\/Driver.hpp>\n\n#include <type_traits>\n#include <algorithm>\n#include <utility>\n#include <chrono>\n\nnamespace Hord {\nnamespace System {\n\n\/\/ class Driver implementation\n\n#define HORD_SCOPE_CLASS_IDENT__ System::Driver\n\nDriver::Driver(\n\tSystem::IDGenerator& id_generator\n) noexcept\n\t: m_id_generator(id_generator)\n{\n\tstatic_assert(\n\t\tstd::is_same<\n\t\t\tint64_t,\n\t\t\tstd::chrono::steady_clock::rep\n\t\t>::value,\n\t\t\"steady_clock representation is not 64 bits!\"\n\t);\n\n\t\/\/ Initialize generator\n\tm_id_generator.seed(\n\t\tstd::chrono::steady_clock::now().time_since_epoch().count()\n\t);\n\t\/\/ TODO: Register standard rule types.\n}\n\nDriver::Driver(Driver&&) = default;\nDriver::~Driver() noexcept = default;\n\n#define HORD_SCOPE_FUNC_IDENT__ register_rule_type\nvoid\nDriver::register_rule_type(\n\tRule::type_info const& type_info\n) {\n\tif (\n\t\tstatic_cast<Rule::Type>(Rule::StandardTypes::ReservedLast)\n\t\t>= type_info.type\n\t) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_reserved,\n\t\t\t\"type is within range reserved for standard rules\"\n\t\t);\n\t} else if (0u == type_info.permitted_types) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_zero_permitted_types,\n\t\t\t\"permitted_types property must be a nonzero combination\"\n\t\t\t\" of FieldTypes\"\n\t\t);\n\t} else if (m_rule_types.cend() != m_rule_types.find(type_info.type)) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_shared,\n\t\t\t\"type has already been registered\"\n\t\t);\n\t}\n\tm_rule_types.insert(std::move(std::make_pair(\n\t\ttype_info.type,\n\t\ttype_info\n\t)));\n}\n#undef HORD_SCOPE_FUNC_IDENT__\n\n#define HORD_SCOPE_FUNC_IDENT__ placehold_hive\nHive::Unit const&\nDriver::placehold_hive(\n\tIO::Datastore::type_info const& type_info,\n\tString root_path\n) {\n\tif (root_path.empty()) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_hive_root_empty,\n\t\t\t\"cannot placehold hive with empty root path\"\n\t\t);\n\t} else if (\n\t\t\/\/ FIXME: This is rank.\n\t\tm_datastores.cend()\n\t\t!= std::find_if(m_datastores.cbegin(), m_datastores.cend(),\n\t\t\t[&root_path](datastore_map_type::value_type const& pair) -> bool {\n\t\t\t\treturn 0 == root_path.compare(pair.second->get_root_path());\n\t\t\t}\n\t\t)\n\t) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_hive_root_shared,\n\t\t\t\"cannot placehold hive with non-unique root path\"\n\t\t);\n\t}\n\n\t\/\/ Phew. Now let's try to construct and insert this guy\n\tObject::ID const\n\t\tid = m_id_generator.generate_unique(m_datastores);\n\tIO::Datastore* const\n\t\tdatastore_ptr = type_info.construct(std::move(root_path), id);\n\tif (nullptr == datastore_ptr) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_datastore_construct_failed,\n\t\t\t\"failed to construct datastore for root path\"\n\t\t);\n\t}\n\tauto result_pair = m_datastores.emplace(\n\t\tid,\n\t\tstd::move(std::unique_ptr<IO::Datastore>{\n\t\t\tdatastore_ptr\n\t\t})\n\t);\n\tm_hive_order.emplace_back(id);\n\treturn result_pair.first->second->get_hive();\n}\n#undef HORD_SCOPE_FUNC_IDENT__\n\n#undef HORD_SCOPE_CLASS_IDENT__\n\n} \/\/ namespace System\n} \/\/ namespace Hord\n<commit_msg>System::Driver: report root path with non-unique error message.<commit_after>\n#include <Hord\/Rule\/Defs.hpp>\n#include <Hord\/Error.hpp>\n#include <Hord\/System\/Driver.hpp>\n\n#include <ceformat\/print.hpp>\n\n#include <type_traits>\n#include <algorithm>\n#include <utility>\n#include <chrono>\n\nnamespace Hord {\nnamespace System {\n\n\/\/ class Driver implementation\n\n#define HORD_SCOPE_CLASS_IDENT__ System::Driver\n\nDriver::Driver(\n\tSystem::IDGenerator& id_generator\n) noexcept\n\t: m_id_generator(id_generator)\n{\n\tstatic_assert(\n\t\tstd::is_same<\n\t\t\tint64_t,\n\t\t\tstd::chrono::steady_clock::rep\n\t\t>::value,\n\t\t\"steady_clock representation is not 64 bits!\"\n\t);\n\n\t\/\/ Initialize generator\n\tm_id_generator.seed(\n\t\tstd::chrono::steady_clock::now().time_since_epoch().count()\n\t);\n\t\/\/ TODO: Register standard rule types.\n}\n\nDriver::Driver(Driver&&) = default;\nDriver::~Driver() noexcept = default;\n\n#define HORD_SCOPE_FUNC_IDENT__ register_rule_type\nvoid\nDriver::register_rule_type(\n\tRule::type_info const& type_info\n) {\n\tif (\n\t\tstatic_cast<Rule::Type>(Rule::StandardTypes::ReservedLast)\n\t\t>= type_info.type\n\t) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_reserved,\n\t\t\t\"type is within range reserved for standard rules\"\n\t\t);\n\t} else if (0u == type_info.permitted_types) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_zero_permitted_types,\n\t\t\t\"permitted_types property must be a nonzero combination\"\n\t\t\t\" of FieldTypes\"\n\t\t);\n\t} else if (m_rule_types.cend() != m_rule_types.find(type_info.type)) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_rule_type_shared,\n\t\t\t\"type has already been registered\"\n\t\t);\n\t}\n\tm_rule_types.insert(std::move(std::make_pair(\n\t\ttype_info.type,\n\t\ttype_info\n\t)));\n}\n#undef HORD_SCOPE_FUNC_IDENT__\n\n#define HORD_SCOPE_FUNC_IDENT__ placehold_hive\n\nHORD_FMT_SCOPED_FQN(\n\ts_err_root_shared,\n\t\"cannot placehold hive with non-unique root path `%s`\"\n);\n\nHive::Unit const&\nDriver::placehold_hive(\n\tIO::Datastore::type_info const& type_info,\n\tString root_path\n) {\n\tif (root_path.empty()) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_hive_root_empty,\n\t\t\t\"cannot placehold hive with empty root path\"\n\t\t);\n\t} else if (\n\t\t\/\/ FIXME: This is rank.\n\t\tm_datastores.cend()\n\t\t!= std::find_if(m_datastores.cbegin(), m_datastores.cend(),\n\t\t\t[&root_path](datastore_map_type::value_type const& pair) -> bool {\n\t\t\t\treturn 0 == root_path.compare(pair.second->get_root_path());\n\t\t\t}\n\t\t)\n\t) {\n\t\tHORD_THROW_ERROR_F(\n\t\t\tErrorCode::driver_hive_root_shared,\n\t\t\ts_err_root_shared,\n\t\t\troot_path\n\t\t);\n\t}\n\n\t\/\/ Phew. Now let's try to construct and insert this guy\n\tObject::ID const\n\t\tid = m_id_generator.generate_unique(m_datastores);\n\tIO::Datastore* const\n\t\tdatastore_ptr = type_info.construct(std::move(root_path), id);\n\tif (nullptr == datastore_ptr) {\n\t\tHORD_THROW_ERROR_SCOPED_FQN(\n\t\t\tErrorCode::driver_datastore_construct_failed,\n\t\t\t\"failed to construct datastore for root path\"\n\t\t);\n\t}\n\tauto result_pair = m_datastores.emplace(\n\t\tid,\n\t\tstd::move(std::unique_ptr<IO::Datastore>{\n\t\t\tdatastore_ptr\n\t\t})\n\t);\n\tm_hive_order.emplace_back(id);\n\treturn result_pair.first->second->get_hive();\n}\n#undef HORD_SCOPE_FUNC_IDENT__\n\n#undef HORD_SCOPE_CLASS_IDENT__\n\n} \/\/ namespace System\n} \/\/ namespace Hord\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECoreRI\/SLOReader.h\"\n\n#include \"IECore\/Shader.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/ObjectParameter.h\"\n#include \"IECore\/NullObject.h\"\n#include \"IECore\/CompoundObject.h\"\n\n#include \"slo.h\"\n\nusing namespace IECore;\nusing namespace IECoreRI;\nusing namespace boost;\nusing namespace std;\nusing namespace Imath;\n\nconst Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( \"sdl\" );\n\nSLOReader::SLOReader()\n\t:\tReader( \"SLOReader\", \"Reads compiled renderman shaders.\", new ObjectParameter( \"result\", \"The loaded shader\", new NullObject, Shader::staticTypeId() ) )\n{\t\n}\n\nSLOReader::SLOReader( const std::string &fileName )\n\t:\tReader( \"SLOReader\", \"Reads compiled renderman shaders.\", new ObjectParameter( \"result\", \"The loaded shader\", new NullObject, Shader::staticTypeId() ) )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nSLOReader::~SLOReader()\n{\n}\n\nbool SLOReader::canRead( const std::string &fileName )\n{\n\tif( Slo_SetShader( fileName.c_str() ) )\n\t{\n\t\treturn false;\n\t}\n\tSlo_EndShader();\n\treturn true;\n}\n\nObjectPtr SLOReader::doOperation( ConstCompoundObjectPtr operands )\n{\n\tif( Slo_SetShader( fileName().c_str() ) )\n\t{\n\t\treturn 0;\n\t}\n\n\tstring name = Slo_GetName();\n\tstring type = Slo_TypetoStr( Slo_GetType() );\n\tShaderPtr result = new Shader( name, type );\n\t\n\tCompoundDataPtr typeHints = new CompoundData;\n\tresult->blindData()->writable().insert( pair<string, DataPtr>( \"ri:parameterTypeHints\", typeHints ) );\n\t\n\tint numArgs = Slo_GetNArgs();\n\tfor( int i=1; i<=numArgs; i++ )\n\t{\n\t\tDataPtr data = 0;\n\t\t\n\t\tSLO_VISSYMDEF *arg = Slo_GetArgById( i );\n\t\tswitch( arg->svd_type )\n\t\t{\n\t\t\tcase SLO_TYPE_POINT :\n\t\t\tcase SLO_TYPE_VECTOR :\n\t\t\tcase SLO_TYPE_NORMAL :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst SLO_POINT *p = arg->svd_default.pointval;\n\t\t\t\t\t\tdata = new V3fData( V3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tV3fVectorDataPtr vData = new V3fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst SLO_POINT *p = a->svd_default.pointval;\n\t\t\t\t\t\t\tvData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttypeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\tcase SLO_TYPE_COLOR :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst SLO_POINT *p = arg->svd_default.pointval;\n\t\t\t\t\t\tdata = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tColor3fVectorDataPtr vData = new Color3fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst SLO_POINT *p = a->svd_default.pointval;\n\t\t\t\t\t\t\tvData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase SLO_TYPE_SCALAR :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = new FloatData( *(arg->svd_default.scalarval) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tFloatVectorDataPtr vData = new FloatVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tvData->writable().push_back( *(a->svd_default.scalarval) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t\tbreak;\n\t\t\n\t\t\tcase SLO_TYPE_STRING :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = new StringData( arg->svd_default.stringval );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tStringVectorDataPtr vData = new StringVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tvData->writable().push_back( a->svd_default.stringval );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase SLO_TYPE_MATRIX :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst float *m = arg->svd_default.matrixval;\n\t\t\t\t\t\tM44f mm(\tm[0], m[1], m[2], m[3],\n\t\t\t\t\t\t\t\t\tm[4], m[5], m[6], m[7],\n\t\t\t\t\t\t\t\t\tm[8], m[9], m[10], m[11],\n\t\t\t\t\t\t\t\t\tm[12], m[13], m[14], m[15] \t);\n\t\t\t\t\t\tdata = new M44fData( mm );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tM44fVectorDataPtr vData = new M44fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst float *m = a->svd_default.matrixval;\n\t\t\t\t\t\t\tM44f mm(\tm[0], m[1], m[2], m[3],\n\t\t\t\t\t\t\t\t\t\tm[4], m[5], m[6], m[7],\n\t\t\t\t\t\t\t\t\t\tm[8], m[9], m[10], m[11],\n\t\t\t\t\t\t\t\t\t\tm[12], m[13], m[14], m[15] \t);\n\t\t\t\t\t\t\tvData->writable().push_back( mm );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\n\t\t\tdefault :\n\t\t\t\n\t\t\t\tmsg( Msg::Warning, \"SLOReader::read\", format( \"Parameter \\\"%s\\\" has unsupported type.\" ) % arg->svd_name );\n\t\t}\n\t\t\n\t\tif( data )\n\t\t{\n\t\t\tresult->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );\n\t\t}\n\t\n\t}\n\n\treturn result;\n}\n\n<commit_msg>Can now handle null default values in string arrays.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECoreRI\/SLOReader.h\"\n\n#include \"IECore\/Shader.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/ObjectParameter.h\"\n#include \"IECore\/NullObject.h\"\n#include \"IECore\/CompoundObject.h\"\n\n#include \"slo.h\"\n\nusing namespace IECore;\nusing namespace IECoreRI;\nusing namespace boost;\nusing namespace std;\nusing namespace Imath;\n\nconst Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( \"sdl\" );\n\nSLOReader::SLOReader()\n\t:\tReader( \"SLOReader\", \"Reads compiled renderman shaders.\", new ObjectParameter( \"result\", \"The loaded shader\", new NullObject, Shader::staticTypeId() ) )\n{\t\n}\n\nSLOReader::SLOReader( const std::string &fileName )\n\t:\tReader( \"SLOReader\", \"Reads compiled renderman shaders.\", new ObjectParameter( \"result\", \"The loaded shader\", new NullObject, Shader::staticTypeId() ) )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nSLOReader::~SLOReader()\n{\n}\n\nbool SLOReader::canRead( const std::string &fileName )\n{\n\tif( Slo_SetShader( fileName.c_str() ) )\n\t{\n\t\treturn false;\n\t}\n\tSlo_EndShader();\n\treturn true;\n}\n\nObjectPtr SLOReader::doOperation( ConstCompoundObjectPtr operands )\n{\n\tif( Slo_SetShader( fileName().c_str() ) )\n\t{\n\t\treturn 0;\n\t}\n\n\tstring name = Slo_GetName();\n\tstring type = Slo_TypetoStr( Slo_GetType() );\n\tShaderPtr result = new Shader( name, type );\n\t\n\tCompoundDataPtr typeHints = new CompoundData;\n\tresult->blindData()->writable().insert( pair<string, DataPtr>( \"ri:parameterTypeHints\", typeHints ) );\n\t\n\tint numArgs = Slo_GetNArgs();\n\tfor( int i=1; i<=numArgs; i++ )\n\t{\n\t\tDataPtr data = 0;\n\t\t\n\t\tSLO_VISSYMDEF *arg = Slo_GetArgById( i );\n\t\tswitch( arg->svd_type )\n\t\t{\n\t\t\tcase SLO_TYPE_POINT :\n\t\t\tcase SLO_TYPE_VECTOR :\n\t\t\tcase SLO_TYPE_NORMAL :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst SLO_POINT *p = arg->svd_default.pointval;\n\t\t\t\t\t\tdata = new V3fData( V3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tV3fVectorDataPtr vData = new V3fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst SLO_POINT *p = a->svd_default.pointval;\n\t\t\t\t\t\t\tvData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttypeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\tcase SLO_TYPE_COLOR :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst SLO_POINT *p = arg->svd_default.pointval;\n\t\t\t\t\t\tdata = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tColor3fVectorDataPtr vData = new Color3fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst SLO_POINT *p = a->svd_default.pointval;\n\t\t\t\t\t\t\tvData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase SLO_TYPE_SCALAR :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = new FloatData( *(arg->svd_default.scalarval) );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tFloatVectorDataPtr vData = new FloatVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tvData->writable().push_back( *(a->svd_default.scalarval) );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t\tbreak;\n\t\t\n\t\t\tcase SLO_TYPE_STRING :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tdata = new StringData( arg->svd_default.stringval );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tStringVectorDataPtr vData = new StringVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\t\/\/ sometimes the default value for an element of a string array can be a null pointer.\n\t\t\t\t\t\t\t\/\/ i'm not sure what the meaning of this is. the 3delight shaderinfo utility reports such values\n\t\t\t\t\t\t\t\/\/ as \"(null)\", so that's what we do too.\n\t\t\t\t\t\t\tconst char *defaultValue = a->svd_default.stringval;\n\t\t\t\t\t\t\tvData->writable().push_back( defaultValue ? defaultValue : \"(null)\" );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase SLO_TYPE_MATRIX :\n\t\t\t\t{\n\t\t\t\t\tif( arg->svd_arraylen==0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst float *m = arg->svd_default.matrixval;\n\t\t\t\t\t\tM44f mm(\tm[0], m[1], m[2], m[3],\n\t\t\t\t\t\t\t\t\tm[4], m[5], m[6], m[7],\n\t\t\t\t\t\t\t\t\tm[8], m[9], m[10], m[11],\n\t\t\t\t\t\t\t\t\tm[12], m[13], m[14], m[15] \t);\n\t\t\t\t\t\tdata = new M44fData( mm );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tM44fVectorDataPtr vData = new M44fVectorData();\n\t\t\t\t\t\tdata = vData;\n\t\t\t\t\t\tfor( int j=0; j<arg->svd_arraylen; j++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );\n\t\t\t\t\t\t\tconst float *m = a->svd_default.matrixval;\n\t\t\t\t\t\t\tM44f mm(\tm[0], m[1], m[2], m[3],\n\t\t\t\t\t\t\t\t\t\tm[4], m[5], m[6], m[7],\n\t\t\t\t\t\t\t\t\t\tm[8], m[9], m[10], m[11],\n\t\t\t\t\t\t\t\t\t\tm[12], m[13], m[14], m[15] \t);\n\t\t\t\t\t\t\tvData->writable().push_back( mm );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\n\t\t\tdefault :\n\t\t\t\n\t\t\t\tmsg( Msg::Warning, \"SLOReader::read\", format( \"Parameter \\\"%s\\\" has unsupported type.\" ) % arg->svd_name );\n\t\t}\n\t\t\n\t\tif( data )\n\t\t{\n\t\t\tresult->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );\n\t\t}\n\t\n\t}\n\n\treturn result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Created on: 2012-07-18\n\/\/ Created by: Kirill GAVRILOV\n\/\/ Copyright (c) 2012 OPEN CASCADE SAS\n\/\/\n\/\/ The content of this file is subject to the Open CASCADE Technology Public\n\/\/ License Version 6.5 (the \"License\"). You may not use the content of this file\n\/\/ except in compliance with the License. Please obtain a copy of the License\n\/\/ at http:\/\/www.opencascade.org and read it completely before using this file.\n\/\/\n\/\/ The Initial Developer of the Original Code is Open CASCADE S.A.S., having its\n\/\/ main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.\n\/\/\n\/\/ The Original Code and all software distributed under the License is\n\/\/ distributed on an \"AS IS\" basis, without warranty of any kind, and the\n\/\/ Initial Developer hereby disclaims all such warranties, including without\n\/\/ limitation, any warranties of merchantability, fitness for a particular\n\/\/ purpose or non-infringement. Please see the License for the specific terms\n\/\/ and conditions governing the rights and limitations under the License.\n\n#include <Image_PixMap.hxx>\n\n#ifdef _MSC_VER\n #include <malloc.h>\n#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)\n #include <mm_malloc.h>\n#else\n extern \"C\" int posix_memalign (void** thePtr, size_t theAlign, size_t theBytesCount);\n#endif\n\ntemplate<typename TypePtr>\ninline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,\n const Standard_Size& theAlign = 16)\n{\n#if defined(_MSC_VER)\n return (TypePtr )_aligned_malloc (theBytesCount, theAlign);\n#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)\n return (TypePtr ) _mm_malloc (theBytesCount, theAlign);\n#else\n void* aPtr;\n if (posix_memalign (&aPtr, theAlign, theBytesCount))\n {\n aPtr = NULL;\n }\n return (TypePtr )aPtr;\n#endif\n}\n\ninline void MemFreeAligned (void* thePtrAligned)\n{\n#if defined(_MSC_VER)\n _aligned_free (thePtrAligned);\n#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)\n _mm_free (thePtrAligned);\n#else\n free (thePtrAligned);\n#endif\n}\n\nIMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)\nIMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)\n\n\/\/ =======================================================================\n\/\/ function : Image_PixMap\n\/\/ purpose :\n\/\/ =======================================================================\nImage_PixMap::Image_PixMap()\n: myImgFormat (Image_PixMap::ImgGray),\n myIsOwnPointer (true)\n{\n memset (&myData, 0, sizeof(myData));\n myData.mySizeBPP = 1;\n myData.myTopToDown = 1;\n setFormat (Image_PixMap::ImgGray);\n}\n\n\/\/ =======================================================================\n\/\/ function : ~Image_PixMap\n\/\/ purpose :\n\/\/ =======================================================================\nImage_PixMap::~Image_PixMap()\n{\n Clear();\n}\n\nStandard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)\n{\n switch (thePixelFormat)\n {\n case ImgGrayF:\n return sizeof(float);\n case ImgRGBAF:\n case ImgBGRAF:\n return sizeof(float) * 4;\n case ImgRGBF:\n case ImgBGRF:\n return sizeof(float) * 3;\n case ImgRGBA:\n case ImgBGRA:\n return 4;\n case ImgRGB32:\n case ImgBGR32:\n return 4;\n case ImgRGB:\n case ImgBGR:\n return 3;\n case ImgGray:\n default:\n return 1;\n }\n}\n\n\/\/ =======================================================================\n\/\/ function : setFormat\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)\n{\n myImgFormat = thePixelFormat;\n myData.mySizeBPP = SizePixelBytes (myImgFormat);\n}\n\n\/\/ =======================================================================\n\/\/ function : setTopDown\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::setTopDown()\n{\n myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)\n ? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));\n}\n\n\/\/ =======================================================================\n\/\/ function : InitWrapper\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,\n Standard_Byte* theDataPtr,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes)\n{\n Clear (thePixelFormat);\n if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))\n {\n return false;\n }\n myData.mySizeX = theSizeX;\n myData.mySizeY = theSizeY;\n myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);\n myData.myDataPtr = theDataPtr;\n myIsOwnPointer = false;\n setTopDown();\n return true;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitTrash\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes)\n{\n Clear (thePixelFormat);\n if ((theSizeX == 0) || (theSizeY == 0))\n {\n return false;\n }\n myData.mySizeX = theSizeX;\n myData.mySizeY = theSizeY;\n myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;\n if (theSizeRowBytes > myData.mySizeRowBytes)\n {\n \/\/ use argument only if it greater\n myData.mySizeRowBytes = theSizeRowBytes;\n }\n myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());\n myIsOwnPointer = true;\n setTopDown();\n return myData.myDataPtr != NULL;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitZero\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes,\n const Standard_Byte theValue)\n{\n if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))\n {\n return false;\n }\n memset (myData.myDataPtr, (int )theValue, SizeBytes());\n return true;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitCopy\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitCopy (const Image_PixMap& theCopy)\n{\n if (&theCopy == this)\n {\n \/\/ self-copying disallowed\n return false;\n }\n if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))\n {\n memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());\n return true;\n }\n return false;\n}\n\n\/\/ =======================================================================\n\/\/ function : Clear\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)\n{\n if (myIsOwnPointer && (myData.myDataPtr != NULL))\n {\n MemFreeAligned (myData.myDataPtr);\n }\n myData.myDataPtr = myData.myTopRowPtr = NULL;\n myIsOwnPointer = true;\n myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;\n setFormat (thePixelFormat);\n myData.myTopToDown = 1;\n}\n\n\/\/ =======================================================================\n\/\/ function : PixelColor\n\/\/ purpose :\n\/\/ =======================================================================\nQuantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,\n const Standard_Integer theY,\n Quantity_Parameter& theAlpha) const\n{\n if (IsEmpty() ||\n theX < 0 || (Standard_Size )theX >= myData.mySizeX ||\n theY < 0 || (Standard_Size )theY >= myData.mySizeY)\n {\n theAlpha = 0.0; \/\/ transparent\n return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);\n }\n\n switch (myImgFormat)\n {\n case ImgGrayF:\n {\n const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_TOC_RGB);\n break;\n }\n case ImgRGBAF:\n {\n const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);\n theAlpha = aPixel.a();\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgBGRAF:\n { \n const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);\n theAlpha = aPixel.a();\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgRGBF:\n {\n const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgBGRF:\n {\n const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgRGBA:\n {\n const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);\n theAlpha = Standard_Real (aPixel.a()) \/ 255.0;\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGRA:\n {\n const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);\n theAlpha = Standard_Real (aPixel.a()) \/ 255.0;\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgRGB32:\n {\n const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGR32:\n {\n const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgRGB:\n {\n const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGR:\n {\n const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgGray:\n {\n const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_TOC_RGB);\n }\n default:\n {\n \/\/ not supported image type\n theAlpha = 0.0; \/\/ transparent\n return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);\n }\n }\n}\n<commit_msg>Fix build failure on Mac OSX 10.5, posix_memalign was introduced in 10.6<commit_after>\/\/ Created on: 2012-07-18\n\/\/ Created by: Kirill GAVRILOV\n\/\/ Copyright (c) 2012 OPEN CASCADE SAS\n\/\/\n\/\/ The content of this file is subject to the Open CASCADE Technology Public\n\/\/ License Version 6.5 (the \"License\"). You may not use the content of this file\n\/\/ except in compliance with the License. Please obtain a copy of the License\n\/\/ at http:\/\/www.opencascade.org and read it completely before using this file.\n\/\/\n\/\/ The Initial Developer of the Original Code is Open CASCADE S.A.S., having its\n\/\/ main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.\n\/\/\n\/\/ The Original Code and all software distributed under the License is\n\/\/ distributed on an \"AS IS\" basis, without warranty of any kind, and the\n\/\/ Initial Developer hereby disclaims all such warranties, including without\n\/\/ limitation, any warranties of merchantability, fitness for a particular\n\/\/ purpose or non-infringement. Please see the License for the specific terms\n\/\/ and conditions governing the rights and limitations under the License.\n\n#include <Image_PixMap.hxx>\n\n#ifdef _MSC_VER\n #include <malloc.h>\n#elif defined(HAVE_MM_MALLOC_H)\n #include <mm_malloc.h>\n#else\n #include <stdlib.h>\n#endif\n\ntemplate<typename TypePtr>\ninline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,\n const Standard_Size& theAlign = 16)\n{\n#if defined(_MSC_VER)\n return (TypePtr )_aligned_malloc (theBytesCount, theAlign);\n#elif defined(HAVE_MM_MALLOC_H)\n return (TypePtr ) _mm_malloc (theBytesCount, theAlign);\n#elif defined(HAVE_POSIX_MEMALIGN)\n void* aPtr;\n if (posix_memalign (&aPtr, theAlign, theBytesCount))\n {\n aPtr = NULL;\n }\n return (TypePtr )aPtr;\n#else\n return (TypePtr ) malloc (theBytesCount);\n#endif\n}\n\ninline void MemFreeAligned (void* thePtrAligned)\n{\n#if defined(_MSC_VER)\n _aligned_free (thePtrAligned);\n#elif defined(HAVE_MM_MALLOC_H)\n _mm_free (thePtrAligned);\n#else\n free (thePtrAligned);\n#endif\n}\n\nIMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)\nIMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)\n\n\/\/ =======================================================================\n\/\/ function : Image_PixMap\n\/\/ purpose :\n\/\/ =======================================================================\nImage_PixMap::Image_PixMap()\n: myImgFormat (Image_PixMap::ImgGray),\n myIsOwnPointer (true)\n{\n memset (&myData, 0, sizeof(myData));\n myData.mySizeBPP = 1;\n myData.myTopToDown = 1;\n setFormat (Image_PixMap::ImgGray);\n}\n\n\/\/ =======================================================================\n\/\/ function : ~Image_PixMap\n\/\/ purpose :\n\/\/ =======================================================================\nImage_PixMap::~Image_PixMap()\n{\n Clear();\n}\n\nStandard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)\n{\n switch (thePixelFormat)\n {\n case ImgGrayF:\n return sizeof(float);\n case ImgRGBAF:\n case ImgBGRAF:\n return sizeof(float) * 4;\n case ImgRGBF:\n case ImgBGRF:\n return sizeof(float) * 3;\n case ImgRGBA:\n case ImgBGRA:\n return 4;\n case ImgRGB32:\n case ImgBGR32:\n return 4;\n case ImgRGB:\n case ImgBGR:\n return 3;\n case ImgGray:\n default:\n return 1;\n }\n}\n\n\/\/ =======================================================================\n\/\/ function : setFormat\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)\n{\n myImgFormat = thePixelFormat;\n myData.mySizeBPP = SizePixelBytes (myImgFormat);\n}\n\n\/\/ =======================================================================\n\/\/ function : setTopDown\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::setTopDown()\n{\n myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)\n ? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));\n}\n\n\/\/ =======================================================================\n\/\/ function : InitWrapper\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,\n Standard_Byte* theDataPtr,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes)\n{\n Clear (thePixelFormat);\n if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))\n {\n return false;\n }\n myData.mySizeX = theSizeX;\n myData.mySizeY = theSizeY;\n myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);\n myData.myDataPtr = theDataPtr;\n myIsOwnPointer = false;\n setTopDown();\n return true;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitTrash\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes)\n{\n Clear (thePixelFormat);\n if ((theSizeX == 0) || (theSizeY == 0))\n {\n return false;\n }\n myData.mySizeX = theSizeX;\n myData.mySizeY = theSizeY;\n myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;\n if (theSizeRowBytes > myData.mySizeRowBytes)\n {\n \/\/ use argument only if it greater\n myData.mySizeRowBytes = theSizeRowBytes;\n }\n myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());\n myIsOwnPointer = true;\n setTopDown();\n return myData.myDataPtr != NULL;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitZero\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,\n const Standard_Size theSizeX,\n const Standard_Size theSizeY,\n const Standard_Size theSizeRowBytes,\n const Standard_Byte theValue)\n{\n if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))\n {\n return false;\n }\n memset (myData.myDataPtr, (int )theValue, SizeBytes());\n return true;\n}\n\n\/\/ =======================================================================\n\/\/ function : InitCopy\n\/\/ purpose :\n\/\/ =======================================================================\nbool Image_PixMap::InitCopy (const Image_PixMap& theCopy)\n{\n if (&theCopy == this)\n {\n \/\/ self-copying disallowed\n return false;\n }\n if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))\n {\n memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());\n return true;\n }\n return false;\n}\n\n\/\/ =======================================================================\n\/\/ function : Clear\n\/\/ purpose :\n\/\/ =======================================================================\nvoid Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)\n{\n if (myIsOwnPointer && (myData.myDataPtr != NULL))\n {\n MemFreeAligned (myData.myDataPtr);\n }\n myData.myDataPtr = myData.myTopRowPtr = NULL;\n myIsOwnPointer = true;\n myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;\n setFormat (thePixelFormat);\n myData.myTopToDown = 1;\n}\n\n\/\/ =======================================================================\n\/\/ function : PixelColor\n\/\/ purpose :\n\/\/ =======================================================================\nQuantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,\n const Standard_Integer theY,\n Quantity_Parameter& theAlpha) const\n{\n if (IsEmpty() ||\n theX < 0 || (Standard_Size )theX >= myData.mySizeX ||\n theY < 0 || (Standard_Size )theY >= myData.mySizeY)\n {\n theAlpha = 0.0; \/\/ transparent\n return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);\n }\n\n switch (myImgFormat)\n {\n case ImgGrayF:\n {\n const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_Parameter (Standard_Real (aPixel)),\n Quantity_TOC_RGB);\n break;\n }\n case ImgRGBAF:\n {\n const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);\n theAlpha = aPixel.a();\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgBGRAF:\n { \n const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);\n theAlpha = aPixel.a();\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgRGBF:\n {\n const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgBGRF:\n {\n const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (aPixel.r()),\n Quantity_Parameter (aPixel.g()),\n Quantity_Parameter (aPixel.b()),\n Quantity_TOC_RGB);\n }\n case ImgRGBA:\n {\n const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);\n theAlpha = Standard_Real (aPixel.a()) \/ 255.0;\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGRA:\n {\n const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);\n theAlpha = Standard_Real (aPixel.a()) \/ 255.0;\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgRGB32:\n {\n const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGR32:\n {\n const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgRGB:\n {\n const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgBGR:\n {\n const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.g()) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel.b()) \/ 255.0),\n Quantity_TOC_RGB);\n }\n case ImgGray:\n {\n const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);\n theAlpha = 1.0; \/\/ opaque\n return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_Parameter (Standard_Real (aPixel) \/ 255.0),\n Quantity_TOC_RGB);\n }\n default:\n {\n \/\/ not supported image type\n theAlpha = 0.0; \/\/ transparent\n return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>PartDesign: Mild code cleanup of Helix<commit_after><|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright 2016 otris software AG\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ This project is hosted at https:\/\/github.com\/otris\n\n#pragma once\n\n#include <string>\n\n#ifdef EWS_HAS_NOEXCEPT_SPECIFIER\n#define EWS_NOEXCEPT noexcept\n#else\n#define EWS_NOEXCEPT\n#endif\n\n\/\/ Forward declarations\nnamespace ews\n{\nclass and_;\nclass attachment;\nclass attachment_id;\nclass attendee;\nclass basic_credentials;\nclass body;\nclass calendar_item;\nclass connecting_sid;\nclass contact;\nclass contains;\nclass date_time;\nclass delegate_user;\nclass directory_id;\nclass distinguished_folder_id;\nclass duration;\nclass exception;\nclass exchange_error;\nclass folder_id;\nclass http_error;\nclass indexed_property_path;\nclass internet_message_header;\nclass is_equal_to;\nclass is_greater_than;\nclass is_greater_than_or_equal_to;\nclass is_less_than;\nclass is_less_than_or_equal_to;\nclass is_not_equal_to;\nclass item;\nclass item_id;\nclass mailbox;\nclass message;\nclass mime_content;\nclass not_;\nclass ntlm_credentials;\nclass or_;\nclass paging_view;\nclass parse_error;\nclass property;\nclass property_path;\nclass schema_validation_error;\nclass search_expression;\nclass soap_fault;\nclass task;\nclass update;\nclass user_id;\nstruct autodiscover_result;\nstruct autodiscover_hints;\nstruct resolution;\nstruct resolution_set;\ntemplate <typename T> class basic_service;\nbool operator==(const date_time&, const date_time&);\nbool operator==(const property_path&, const property_path&);\nvoid set_up() EWS_NOEXCEPT;\nvoid tear_down() EWS_NOEXCEPT;\nstd::string version();\ntemplate <typename T>\nautodiscover_result get_exchange_web_services_url(const std::string&,\n const basic_credentials&);\ntemplate <typename T>\nautodiscover_result get_exchange_web_services_url(const std::string&,\n const basic_credentials&,\n const autodiscover_hints&);\n}\n\n\/\/ vim:et ts=4 sw=4\n<commit_msg>Fix wrong forward declaration<commit_after>\n\/\/ Copyright 2016 otris software AG\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ This project is hosted at https:\/\/github.com\/otris\n\n#pragma once\n\n#include <string>\n\n#ifdef EWS_HAS_NOEXCEPT_SPECIFIER\n#define EWS_NOEXCEPT noexcept\n#else\n#define EWS_NOEXCEPT\n#endif\n\n\/\/ Forward declarations\nnamespace ews\n{\nclass and_;\nclass attachment;\nclass attachment_id;\nclass attendee;\nclass basic_credentials;\nclass body;\nclass calendar_item;\nclass connecting_sid;\nclass contact;\nclass contains;\nclass date_time;\nclass delegate_user;\nclass directory_id;\nclass distinguished_folder_id;\nclass duration;\nclass exception;\nclass exchange_error;\nclass folder_id;\nclass http_error;\nclass indexed_property_path;\nclass internet_message_header;\nclass is_equal_to;\nclass is_greater_than;\nclass is_greater_than_or_equal_to;\nclass is_less_than;\nclass is_less_than_or_equal_to;\nclass is_not_equal_to;\nclass item;\nclass item_id;\nclass mailbox;\nclass message;\nclass mime_content;\nclass not_;\nclass ntlm_credentials;\nclass or_;\nclass paging_view;\nclass property;\nclass property_path;\nclass schema_validation_error;\nclass search_expression;\nclass soap_fault;\nclass task;\nclass update;\nclass user_id;\nclass xml_parse_error;\nstruct autodiscover_hints;\nstruct autodiscover_result;\nstruct resolution;\nstruct resolution_set;\ntemplate <typename T> class basic_service;\nbool operator==(const date_time&, const date_time&);\nbool operator==(const property_path&, const property_path&);\nvoid set_up() EWS_NOEXCEPT;\nvoid tear_down() EWS_NOEXCEPT;\nstd::string version();\ntemplate <typename T>\nautodiscover_result get_exchange_web_services_url(const std::string&,\n const basic_credentials&);\ntemplate <typename T>\nautodiscover_result get_exchange_web_services_url(const std::string&,\n const basic_credentials&,\n const autodiscover_hints&);\n}\n\n\/\/ vim:et ts=4 sw=4\n<|endoftext|>"} {"text":"<commit_before>\n#include \"python_plugin.hh\"\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define CHK(bad, fmt, ...)\t\t\t\t\t \\\n do {\t\t\t\t\t\t\t \\\n\tif (bad) {\t\t\t\t\t\t \\\n\t fprintf(stderr,fmt, ## __VA_ARGS__);\t\t \\\n\t exit(1);\t\t\t\t\t\t \\\n\t}\t\t\t\t\t\t\t \\\n } while(0)\n\nvoid gdb_in_window(int sig) {}\n\nvoid analyze(const char *what,bp::object retval)\n{\n PyObject *res_str = PyObject_Str(retval.ptr());\n Py_XDECREF(res_str);\n printf(\"analyze: %s returned '%s' - '%s'\\n\",what,\n\t PyString_AsString(res_str),\n\t retval.ptr()->ob_type->tp_name);\n}\n\nvoid exercise(PythonPlugin *pp,const char *mod, const char*func, bp::tuple tupleargs, bp::dict kwargs)\n{\n\n bp::object r;\n\n bool callable = pp->is_callable(mod,func);\n printf(\"callable(%s.%s) = %s\\n\",mod,func,callable ? \"TRUE\": \"FALSE\");\n\n\n int status = pp->call(mod,func, tupleargs,kwargs,r);\n switch (status) {\n case PLUGIN_EXCEPTION:\n\tprintf(\"call(%s.%s): exception='%s' status = %d\\n\",\n\t mod,func,pp->last_exception().c_str(), status);\n\tbreak;\n case PLUGIN_OK:\n\tprintf(\"call(%s.%s): OK\\n\", mod,func);\n\tanalyze( func,r);\n\tbreak;\n default:\n\tprintf(\"call(%s.%s): status = %d\\n\", mod,func,status);\n }\n}\n\nvoid run(PythonPlugin *pp,const char *cmd, bool as_file)\n{\n bp::object r;\n int status = pp->run_string(cmd,r, as_file);\n printf(\"run_string(%s): status = %d\\n\", cmd,status);\n analyze(cmd,r);\n}\n\nvoid foo_init()\n{\n printf(\"foo init\\n\");\n}\nvoid bar_init()\n{\n printf(\"bar init\\n\");\n}\n\nconst char *inifile = \"test.ini\";\nconst char *section = \"PYTHON\";\nstruct _inittab builtin_modules[] = {\n { (char *) \"foo\", foo_init },\n { (char *) \"bar\", bar_init },\n \/\/ any others...\n { NULL, NULL }\n};\n\nint builtins;\nbool as_file = false;\nint\nmain (int argc, char **argv)\n{\n\n int index;\n int c;\n bp::object retval;\n char *callablefunc = NULL;\n char *callablemod = NULL;\n char *xcallable = NULL;\n\n opterr = 0;\n\n while ((c = getopt (argc, argv, \"fbi:C:c:x:\")) != -1) {\n\tswitch (c) {\n\tcase 'f':\n\t as_file = true;\n\t break;\n\tcase 'b':\n\t builtins++;\n\t break;\n\tcase 'i':\n\t inifile = optarg;\n\t break;\n\tcase 'C':\n\t callablemod = optarg;\n\t break;\n\tcase 'c':\n\t callablefunc = optarg;\n\t break;\n\tcase 'x':\n\t xcallable = optarg;\n\t break;\n\tcase '?':\n\t if (optopt == 'c')\n\t\tfprintf (stderr, \"Option -%c requires an argument.\\n\", optopt);\n\t else if (isprint (optopt))\n\t\tfprintf (stderr, \"Unknown option `-%c'.\\n\", optopt);\n\t else\n\t\tfprintf (stderr,\n\t\t\t \"Unknown option character `\\\\x%x'.\\n\",\n\t\t\t optopt);\n\t return 1;\n\tdefault:\n\t abort ();\n\t}\n }\n \/\/ creates the singleton instance\n PythonPlugin *pp = PythonPlugin::configure(inifile,\n\t\t\t\t\t\t section,\n\t\t\t\t\t\t builtins ? builtin_modules : NULL);\n \/\/ PythonPlugin two = pp; \/\/ this fails since copy constructor is private.\n \/\/ PythonPlugin &second = PythonPlugin::getInstance(); \/\/ returns the singleton instance\n\n printf(\"status = %d\\n\", pp->plugin_status());\n bp::tuple tupleargs,nulltupleargs;\n bp::dict kwargs,nullkwargs;\n kwargs['x'] = 10;\n kwargs['y'] = 20;\n tupleargs = bp::make_tuple(3,2,1,\"foo\");\n\n exercise(pp,NULL,\"func\",nulltupleargs, nullkwargs);\n\n system(\"\/usr\/bin\/touch testmod.py\");\n\n exercise(pp,NULL,\"badfunc\",tupleargs,kwargs);\n exercise(pp,NULL,\"retstring\",tupleargs,kwargs);\n exercise(pp,NULL,\"retdouble\",tupleargs,kwargs);\n \/\/ exercise(pp,\"submod\",\"subfunc\");\n\n for (index = optind; index < argc; index++) {\n\trun(pp, argv[index], as_file);\n }\n return 0;\n}\n<commit_msg>testpp: use strdup for strstore<commit_after>\n#include \"python_plugin.hh\"\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define CHK(bad, fmt, ...)\t\t\t\t\t \\\n do {\t\t\t\t\t\t\t \\\n\tif (bad) {\t\t\t\t\t\t \\\n\t fprintf(stderr,fmt, ## __VA_ARGS__);\t\t \\\n\t exit(1);\t\t\t\t\t\t \\\n\t}\t\t\t\t\t\t\t \\\n } while(0)\n\nconst char *strstore(const char *s) { return strdup(s); }\n\nvoid analyze(const char *what,bp::object retval)\n{\n PyObject *res_str = PyObject_Str(retval.ptr());\n Py_XDECREF(res_str);\n printf(\"analyze: %s returned '%s' - '%s'\\n\",what,\n\t PyString_AsString(res_str),\n\t retval.ptr()->ob_type->tp_name);\n}\n\nvoid exercise(PythonPlugin *pp,const char *mod, const char*func, bp::tuple tupleargs, bp::dict kwargs)\n{\n\n bp::object r;\n\n bool callable = pp->is_callable(mod,func);\n printf(\"callable(%s.%s) = %s\\n\",mod,func,callable ? \"TRUE\": \"FALSE\");\n\n\n int status = pp->call(mod,func, tupleargs,kwargs,r);\n switch (status) {\n case PLUGIN_EXCEPTION:\n\tprintf(\"call(%s.%s): exception='%s' status = %d\\n\",\n\t mod,func,pp->last_exception().c_str(), status);\n\tbreak;\n case PLUGIN_OK:\n\tprintf(\"call(%s.%s): OK\\n\", mod,func);\n\tanalyze( func,r);\n\tbreak;\n default:\n\tprintf(\"call(%s.%s): status = %d\\n\", mod,func,status);\n }\n}\n\nvoid run(PythonPlugin *pp,const char *cmd, bool as_file)\n{\n bp::object r;\n int status = pp->run_string(cmd,r, as_file);\n printf(\"run_string(%s): status = %d\\n\", cmd,status);\n analyze(cmd,r);\n}\n\nvoid foo_init()\n{\n printf(\"foo init\\n\");\n}\nvoid bar_init()\n{\n printf(\"bar init\\n\");\n}\n\nconst char *inifile = \"test.ini\";\nconst char *section = \"PYTHON\";\nstruct _inittab builtin_modules[] = {\n { (char *) \"foo\", foo_init },\n { (char *) \"bar\", bar_init },\n \/\/ any others...\n { NULL, NULL }\n};\n\nint builtins;\nbool as_file = false;\nint\nmain (int argc, char **argv)\n{\n\n int index;\n int c;\n bp::object retval;\n char *callablefunc = NULL;\n char *callablemod = NULL;\n char *xcallable = NULL;\n\n opterr = 0;\n\n while ((c = getopt (argc, argv, \"fbi:C:c:x:\")) != -1) {\n\tswitch (c) {\n\tcase 'f':\n\t as_file = true;\n\t break;\n\tcase 'b':\n\t builtins++;\n\t break;\n\tcase 'i':\n\t inifile = optarg;\n\t break;\n\tcase 'C':\n\t callablemod = optarg;\n\t break;\n\tcase 'c':\n\t callablefunc = optarg;\n\t break;\n\tcase 'x':\n\t xcallable = optarg;\n\t break;\n\tcase '?':\n\t if (optopt == 'c')\n\t\tfprintf (stderr, \"Option -%c requires an argument.\\n\", optopt);\n\t else if (isprint (optopt))\n\t\tfprintf (stderr, \"Unknown option `-%c'.\\n\", optopt);\n\t else\n\t\tfprintf (stderr,\n\t\t\t \"Unknown option character `\\\\x%x'.\\n\",\n\t\t\t optopt);\n\t return 1;\n\tdefault:\n\t abort ();\n\t}\n }\n \/\/ creates the singleton instance\n PythonPlugin *pp = PythonPlugin::configure(inifile,\n\t\t\t\t\t\t section,\n\t\t\t\t\t\t builtins ? builtin_modules : NULL);\n \/\/ PythonPlugin two = pp; \/\/ this fails since copy constructor is private.\n \/\/ PythonPlugin &second = PythonPlugin::getInstance(); \/\/ returns the singleton instance\n\n printf(\"status = %d\\n\", pp->plugin_status());\n bp::tuple tupleargs,nulltupleargs;\n bp::dict kwargs,nullkwargs;\n kwargs['x'] = 10;\n kwargs['y'] = 20;\n tupleargs = bp::make_tuple(3,2,1,\"foo\");\n\n exercise(pp,NULL,\"func\",nulltupleargs, nullkwargs);\n\n system(\"\/usr\/bin\/touch testmod.py\");\n\n exercise(pp,NULL,\"badfunc\",tupleargs,kwargs);\n exercise(pp,NULL,\"retstring\",tupleargs,kwargs);\n exercise(pp,NULL,\"retdouble\",tupleargs,kwargs);\n \/\/ exercise(pp,\"submod\",\"subfunc\");\n\n for (index = optind; index < argc; index++) {\n\trun(pp, argv[index], as_file);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RULE_HPP\n#define MAPNIK_RULE_HPP\n\n\/\/ mapnik\n#include <mapnik\/line_symbolizer.hpp>\n#include <mapnik\/line_pattern_symbolizer.hpp>\n#include <mapnik\/polygon_symbolizer.hpp>\n#include <mapnik\/polygon_pattern_symbolizer.hpp>\n#include <mapnik\/point_symbolizer.hpp>\n#include <mapnik\/raster_symbolizer.hpp>\n#include <mapnik\/shield_symbolizer.hpp>\n#include <mapnik\/text_symbolizer.hpp>\n#include <mapnik\/markers_symbolizer.hpp>\n#include <mapnik\/glyph_symbolizer.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/expression_string.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n#include <boost\/variant.hpp>\n\n\/\/ stl\n#include <string>\n#include <vector>\n\nnamespace mapnik\n{\ninline bool operator==(point_symbolizer const& lhs,\n point_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ninline bool operator==(line_symbolizer const& lhs,\n line_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ninline bool operator==(line_pattern_symbolizer const& lhs,\n line_pattern_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n\ninline bool operator==(polygon_symbolizer const& lhs,\n polygon_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(polygon_pattern_symbolizer const& lhs,\n polygon_pattern_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(raster_symbolizer const& lhs,\n raster_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(text_symbolizer const& lhs,\n text_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(shield_symbolizer const& lhs,\n shield_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(building_symbolizer const& lhs,\n building_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(markers_symbolizer const& lhs,\n markers_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n\ninline bool operator==(glyph_symbolizer const& lhs,\n glyph_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ntypedef boost::variant<point_symbolizer,\n line_symbolizer,\n line_pattern_symbolizer,\n polygon_symbolizer,\n polygon_pattern_symbolizer,\n raster_symbolizer,\n shield_symbolizer,\n text_symbolizer,\n building_symbolizer,\n markers_symbolizer,\n glyph_symbolizer> symbolizer;\n \n \nclass rule\n{ \npublic:\n typedef std::vector<symbolizer> symbolizers;\nprivate:\n \n std::string name_;\n std::string title_;\n std::string abstract_;\n double min_scale_;\n double max_scale_;\n symbolizers syms_;\n expression_ptr filter_;\n bool else_filter_;\n bool also_filter_;\npublic:\n rule()\n : name_(),\n title_(),\n abstract_(),\n min_scale_(0),\n max_scale_(std::numeric_limits<double>::infinity()),\n syms_(),\n filter_(boost::make_shared<mapnik::expr_node>(true)),\n else_filter_(false), \n also_filter_(false) {}\n \n rule(const std::string& name,\n const std::string& title=\"\",\n double min_scale_denominator=0,\n double max_scale_denominator=std::numeric_limits<double>::infinity())\n : name_(name),\n title_(title),\n min_scale_(min_scale_denominator),\n max_scale_(max_scale_denominator),\n syms_(),\n filter_(boost::make_shared<mapnik::expr_node>(true)),\n else_filter_(false), \n also_filter_(false) {}\n \n rule(const rule& rhs, bool deep_copy = false)\n : name_(rhs.name_),\n title_(rhs.title_),\n abstract_(rhs.abstract_),\n min_scale_(rhs.min_scale_),\n max_scale_(rhs.max_scale_),\n syms_(rhs.syms_),\n filter_(rhs.filter_),\n else_filter_(rhs.else_filter_), \n also_filter_(rhs.also_filter_) \n {\n if (deep_copy) {\n \/\/std::string expr = to_expression_string(rhs.filter_);\n \/\/filter_ = parse_expression(expr,\"utf8\");\n \n symbolizers::iterator it = syms_.begin(),\n end = syms_.end();\n \n \/\/ FIXME - metawriter_ptr?\n \n for(; it != end; ++it) {\n \n \/*if (polygon_symbolizer *sym = boost::get<polygon_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n } else if (line_symbolizer *sym = boost::get<line_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n } else if (building_symbolizer *sym = boost::get<building_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n }*\/\n \n if (markers_symbolizer *sym = boost::get<markers_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (point_symbolizer *sym = boost::get<point_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (polygon_pattern_symbolizer *sym = boost::get<polygon_pattern_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (line_pattern_symbolizer *sym = boost::get<line_pattern_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (raster_symbolizer *sym = boost::get<raster_symbolizer>(&(*it))) {\n raster_colorizer_ptr old_colorizer = sym->get_colorizer(),\n new_colorizer = raster_colorizer_ptr();\n \n new_colorizer->set_stops( old_colorizer->get_stops());\n new_colorizer->set_default_mode( old_colorizer->get_default_mode() );\n new_colorizer->set_default_color( old_colorizer->get_default_color() );\n new_colorizer->set_epsilon( old_colorizer->get_epsilon() );\n \n sym->set_colorizer(new_colorizer);\n } else if (shield_symbolizer *sym = boost::get<shield_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n copy_text_ptr(sym);\n } else if (text_symbolizer *sym = boost::get<text_symbolizer>(&(*it))) {\n copy_text_ptr(sym);\n }\n }\n }\n }\n \n rule& operator=(rule const& rhs) \n {\n rule tmp(rhs);\n swap(tmp);\n return *this;\n }\n bool operator==(rule const& other)\n {\n return (this == &other); \n }\n \n void set_max_scale(double scale)\n {\n max_scale_=scale;\n }\n \n double get_max_scale() const\n {\n return max_scale_;\n }\n \n void set_min_scale(double scale)\n {\n min_scale_=scale;\n }\n \n double get_min_scale() const\n {\n return min_scale_;\n }\n \n void set_name(std::string const& name)\n {\n name_=name;\n }\n \n std::string const& get_name() const\n {\n return name_;\n }\n \n std::string const& get_title() const\n {\n return title_;\n }\n \n void set_title(std::string const& title)\n {\n title_=title;\n }\n \n void set_abstract(std::string const& abstract)\n {\n abstract_=abstract;\n }\n \n std::string const& get_abstract() const\n {\n return abstract_;\n }\n \n void append(const symbolizer& sym)\n {\n syms_.push_back(sym);\n }\n \n void remove_at(size_t index)\n {\n if (index < syms_.size())\n {\n syms_.erase(syms_.begin()+index);\n }\n }\n \n const symbolizers& get_symbolizers() const\n {\n return syms_;\n }\n \n symbolizers::const_iterator begin() const\n {\n return syms_.begin();\n }\n \n symbolizers::const_iterator end() const\n {\n return syms_.end();\n }\n \n symbolizers::iterator begin()\n {\n return syms_.begin();\n }\n \n symbolizers::iterator end()\n {\n return syms_.end();\n }\n \n void set_filter(const expression_ptr& filter)\n {\n filter_=filter;\n }\n \n expression_ptr const& get_filter() const\n {\n return filter_;\n }\n \n void set_else(bool else_filter)\n {\n else_filter_=else_filter;\n }\n \n bool has_else_filter() const\n {\n return else_filter_;\n }\n \n void set_also(bool also_filter)\n {\n also_filter_=also_filter;\n }\n \n bool has_also_filter() const\n {\n return also_filter_;\n }\n \n bool active(double scale) const\n {\n return ( scale >= min_scale_ - 1e-6 && scale < max_scale_ + 1e-6);\n }\n \nprivate:\n \n void swap(rule& rhs) throw()\n {\n name_=rhs.name_;\n title_=rhs.title_;\n abstract_=rhs.abstract_;\n min_scale_=rhs.min_scale_;\n max_scale_=rhs.max_scale_;\n syms_=rhs.syms_;\n filter_=rhs.filter_;\n else_filter_=rhs.else_filter_;\n also_filter_=rhs.also_filter_;\n }\n \n template <class T>\n void copy_path_ptr(T* sym)\n {\n std::string path = path_processor_type::to_string(*sym->get_filename());\n sym->set_filename( parse_path(path) );\n }\n \n template <class T>\n void copy_text_ptr(T* sym)\n {\n std::string name = to_expression_string(*sym->get_name());\n sym->set_name( parse_expression(name) );\n \n \/\/ FIXME - orientation doesn't appear to be initialized in constructor?\n \/\/std::string orientation = to_expression_string(*sym->get_orientation());\n \/\/sym->set_orientation( parse_expression(orientation) );\n \n unsigned text_size = sym->get_text_size();\n position displace = sym->get_displacement();\n vertical_alignment_e valign = sym->get_vertical_alignment();\n horizontal_alignment_e halign = sym->get_horizontal_alignment();\n justify_alignment_e jalign = sym->get_justify_alignment();\n \n text_placements_ptr placements = text_placements_ptr(boost::make_shared<text_placements_dummy>());\n sym->set_placement_options( placements );\n \n sym->set_text_size(text_size);\n sym->set_displacement(displace);\n sym->set_vertical_alignment(valign);\n sym->set_horizontal_alignment(halign);\n sym->set_justify_alignment(jalign);\n }\n};\n\n}\n\n#endif \/\/ MAPNIK_RULE_HPP\n<commit_msg>keep proper type in text sym deep copy - refs #946<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RULE_HPP\n#define MAPNIK_RULE_HPP\n\n\/\/ mapnik\n#include <mapnik\/line_symbolizer.hpp>\n#include <mapnik\/line_pattern_symbolizer.hpp>\n#include <mapnik\/polygon_symbolizer.hpp>\n#include <mapnik\/polygon_pattern_symbolizer.hpp>\n#include <mapnik\/point_symbolizer.hpp>\n#include <mapnik\/raster_symbolizer.hpp>\n#include <mapnik\/shield_symbolizer.hpp>\n#include <mapnik\/text_symbolizer.hpp>\n#include <mapnik\/markers_symbolizer.hpp>\n#include <mapnik\/glyph_symbolizer.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/expression_string.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n#include <boost\/variant.hpp>\n\n\/\/ stl\n#include <string>\n#include <vector>\n\nnamespace mapnik\n{\ninline bool operator==(point_symbolizer const& lhs,\n point_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ninline bool operator==(line_symbolizer const& lhs,\n line_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ninline bool operator==(line_pattern_symbolizer const& lhs,\n line_pattern_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n\ninline bool operator==(polygon_symbolizer const& lhs,\n polygon_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(polygon_pattern_symbolizer const& lhs,\n polygon_pattern_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(raster_symbolizer const& lhs,\n raster_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(text_symbolizer const& lhs,\n text_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(shield_symbolizer const& lhs,\n shield_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(building_symbolizer const& lhs,\n building_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n \ninline bool operator==(markers_symbolizer const& lhs,\n markers_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\n\ninline bool operator==(glyph_symbolizer const& lhs,\n glyph_symbolizer const& rhs)\n{\n return (&lhs == &rhs); \n}\ntypedef boost::variant<point_symbolizer,\n line_symbolizer,\n line_pattern_symbolizer,\n polygon_symbolizer,\n polygon_pattern_symbolizer,\n raster_symbolizer,\n shield_symbolizer,\n text_symbolizer,\n building_symbolizer,\n markers_symbolizer,\n glyph_symbolizer> symbolizer;\n \n \nclass rule\n{ \npublic:\n typedef std::vector<symbolizer> symbolizers;\nprivate:\n \n std::string name_;\n std::string title_;\n std::string abstract_;\n double min_scale_;\n double max_scale_;\n symbolizers syms_;\n expression_ptr filter_;\n bool else_filter_;\n bool also_filter_;\npublic:\n rule()\n : name_(),\n title_(),\n abstract_(),\n min_scale_(0),\n max_scale_(std::numeric_limits<double>::infinity()),\n syms_(),\n filter_(boost::make_shared<mapnik::expr_node>(true)),\n else_filter_(false), \n also_filter_(false) {}\n \n rule(const std::string& name,\n const std::string& title=\"\",\n double min_scale_denominator=0,\n double max_scale_denominator=std::numeric_limits<double>::infinity())\n : name_(name),\n title_(title),\n min_scale_(min_scale_denominator),\n max_scale_(max_scale_denominator),\n syms_(),\n filter_(boost::make_shared<mapnik::expr_node>(true)),\n else_filter_(false), \n also_filter_(false) {}\n \n rule(const rule& rhs, bool deep_copy = false)\n : name_(rhs.name_),\n title_(rhs.title_),\n abstract_(rhs.abstract_),\n min_scale_(rhs.min_scale_),\n max_scale_(rhs.max_scale_),\n syms_(rhs.syms_),\n filter_(rhs.filter_),\n else_filter_(rhs.else_filter_), \n also_filter_(rhs.also_filter_) \n {\n if (deep_copy) {\n \/\/std::string expr = to_expression_string(rhs.filter_);\n \/\/filter_ = parse_expression(expr,\"utf8\");\n \n symbolizers::iterator it = syms_.begin(),\n end = syms_.end();\n \n \/\/ FIXME - metawriter_ptr?\n \n for(; it != end; ++it) {\n \n \/*if (polygon_symbolizer *sym = boost::get<polygon_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n } else if (line_symbolizer *sym = boost::get<line_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n } else if (building_symbolizer *sym = boost::get<building_symbolizer>(&(*it))) {\n \/\/ no shared pointers\n }*\/\n \n if (markers_symbolizer *sym = boost::get<markers_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (point_symbolizer *sym = boost::get<point_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (polygon_pattern_symbolizer *sym = boost::get<polygon_pattern_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (line_pattern_symbolizer *sym = boost::get<line_pattern_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n } else if (raster_symbolizer *sym = boost::get<raster_symbolizer>(&(*it))) {\n raster_colorizer_ptr old_colorizer = sym->get_colorizer(),\n new_colorizer = raster_colorizer_ptr();\n \n new_colorizer->set_stops( old_colorizer->get_stops());\n new_colorizer->set_default_mode( old_colorizer->get_default_mode() );\n new_colorizer->set_default_color( old_colorizer->get_default_color() );\n new_colorizer->set_epsilon( old_colorizer->get_epsilon() );\n \n sym->set_colorizer(new_colorizer);\n } else if (shield_symbolizer *sym = boost::get<shield_symbolizer>(&(*it))) {\n copy_path_ptr(sym);\n copy_text_ptr(sym);\n } else if (text_symbolizer *sym = boost::get<text_symbolizer>(&(*it))) {\n copy_text_ptr(sym);\n }\n }\n }\n }\n \n rule& operator=(rule const& rhs) \n {\n rule tmp(rhs);\n swap(tmp);\n return *this;\n }\n bool operator==(rule const& other)\n {\n return (this == &other); \n }\n \n void set_max_scale(double scale)\n {\n max_scale_=scale;\n }\n \n double get_max_scale() const\n {\n return max_scale_;\n }\n \n void set_min_scale(double scale)\n {\n min_scale_=scale;\n }\n \n double get_min_scale() const\n {\n return min_scale_;\n }\n \n void set_name(std::string const& name)\n {\n name_=name;\n }\n \n std::string const& get_name() const\n {\n return name_;\n }\n \n std::string const& get_title() const\n {\n return title_;\n }\n \n void set_title(std::string const& title)\n {\n title_=title;\n }\n \n void set_abstract(std::string const& abstract)\n {\n abstract_=abstract;\n }\n \n std::string const& get_abstract() const\n {\n return abstract_;\n }\n \n void append(const symbolizer& sym)\n {\n syms_.push_back(sym);\n }\n \n void remove_at(size_t index)\n {\n if (index < syms_.size())\n {\n syms_.erase(syms_.begin()+index);\n }\n }\n \n const symbolizers& get_symbolizers() const\n {\n return syms_;\n }\n \n symbolizers::const_iterator begin() const\n {\n return syms_.begin();\n }\n \n symbolizers::const_iterator end() const\n {\n return syms_.end();\n }\n \n symbolizers::iterator begin()\n {\n return syms_.begin();\n }\n \n symbolizers::iterator end()\n {\n return syms_.end();\n }\n \n void set_filter(const expression_ptr& filter)\n {\n filter_=filter;\n }\n \n expression_ptr const& get_filter() const\n {\n return filter_;\n }\n \n void set_else(bool else_filter)\n {\n else_filter_=else_filter;\n }\n \n bool has_else_filter() const\n {\n return else_filter_;\n }\n \n void set_also(bool also_filter)\n {\n also_filter_=also_filter;\n }\n \n bool has_also_filter() const\n {\n return also_filter_;\n }\n \n bool active(double scale) const\n {\n return ( scale >= min_scale_ - 1e-6 && scale < max_scale_ + 1e-6);\n }\n \nprivate:\n \n void swap(rule& rhs) throw()\n {\n name_=rhs.name_;\n title_=rhs.title_;\n abstract_=rhs.abstract_;\n min_scale_=rhs.min_scale_;\n max_scale_=rhs.max_scale_;\n syms_=rhs.syms_;\n filter_=rhs.filter_;\n else_filter_=rhs.else_filter_;\n also_filter_=rhs.also_filter_;\n }\n \n template <class T>\n void copy_path_ptr(T* sym)\n {\n std::string path = path_processor_type::to_string(*sym->get_filename());\n sym->set_filename( parse_path(path) );\n }\n \n template <class T>\n void copy_text_ptr(T* sym)\n {\n std::string name = to_expression_string(*sym->get_name());\n sym->set_name( parse_expression(name) );\n \n \/\/ FIXME - orientation doesn't appear to be initialized in constructor?\n \/\/std::string orientation = to_expression_string(*sym->get_orientation());\n \/\/sym->set_orientation( parse_expression(orientation) );\n \n float text_size = sym->get_text_size();\n position displace = sym->get_displacement();\n vertical_alignment_e valign = sym->get_vertical_alignment();\n horizontal_alignment_e halign = sym->get_horizontal_alignment();\n justify_alignment_e jalign = sym->get_justify_alignment();\n \n text_placements_ptr placements = text_placements_ptr(boost::make_shared<text_placements_dummy>());\n sym->set_placement_options( placements );\n \n sym->set_text_size(text_size);\n sym->set_displacement(displace);\n sym->set_vertical_alignment(valign);\n sym->set_horizontal_alignment(halign);\n sym->set_justify_alignment(jalign);\n }\n};\n\n}\n\n#endif \/\/ MAPNIK_RULE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * OpenSim: testContext.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2017 Stanford University and the Authors *\n * Author(s): Ayman Habib *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include \"..\/OpenSimContext.h\"\n#include <OpenSim\/Common\/Function.h>\n#include <OpenSim\/Common\/MarkerData.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/Body.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/Coordinate.h>\n#include <OpenSim\/Simulation\/Model\/Marker.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Simulation\/Model\/BodySet.h>\n#include <OpenSim\/Simulation\/Model\/MovingPathPoint.h>\n#include <OpenSim\/Simulation\/Model\/Muscle.h>\n#include <OpenSim\/Simulation\/Model\/PathPoint.h>\n#include <OpenSim\/Simulation\/Wrap\/PathWrap.h>\n#include <OpenSim\/Simulation\/Model\/ConditionalPathPoint.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/SimbodyEngine.h>\n#include <OpenSim\/Simulation\/Wrap\/WrapObject.h>\n#include <OpenSim\/Simulation\/Model\/Analysis.h>\n#include <OpenSim\/Simulation\/Model\/MarkerSet.h>\n#include <OpenSim\/Tools\/AnalyzeTool.h>\n#include <OpenSim\/Tools\/ModelScaler.h>\n#include <OpenSim\/Tools\/Measurement.h>\n#include <OpenSim\/Tools\/MarkerPlacer.h>\n#include <OpenSim\/Simulation\/Model\/ForceSet.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Actuators\/Thelen2003Muscle.h>\n\nusing namespace OpenSim;\nusing namespace SimTK;\nusing namespace std;\n\n#define ASSERT_EQUAL(expected, found, tolerance) { \\\ndouble tol = std::max((tolerance), std::abs((expected)*(tolerance))); \\\nif ((found)<(expected)-(tol) || (found)>(expected)+(tol)) throw(exception());}\n\nint main()\n{\n try {\n int status = 0;\n\n \/\/ To Retrace the steps taken by the GUI this test case follows the same call sequence:\n \/\/ new Model(file)\n \/\/ new OpenSimContext(model.initSystem(), model);\n \/\/ context.updateDisplayer(muscle) \/\/ to display muscles\n \/\/ context.getCurrentPath(muscle)\n \/\/ context.getTransform(body)\n \/\/ context.transformPosition(body, loc, global) \/\/ to display markers\n \/\/ context.getLocked(Coordinate)\n \/\/ context.getValue(cooridnate)\n LoadOpenSimLibrary(\"osimActuators\");\n LoadOpenSimLibrary(\"osimSimulation\");\n LoadOpenSimLibrary(\"osimJavaJNI\");\n\n Model *model = new Model(\"wrist.osim\");\n OpenSimContext* context = new OpenSimContext(&model->initSystem(), model);\n const ForceSet& fs = model->getForceSet();\n int n1 = fs.getNumGroups();\n const ObjectGroup* grp = fs.getGroup(\"wrist\");\n assert(grp);\n const Array<const Object*>& members = grp->getMembers();\n int sz = members.getSize();\n ASSERT_EQUAL(sz,5,0);\n assert(members.get(0)->getName()==\"ECRB\");\n delete model;\n delete context;\n model = new Model(\"arm26_20.osim\");\n context = new OpenSimContext(&model->initSystem(), model);\n \/\/ Make a copy of state contained in context ad make sure content match \n SimTK::State stateCopy = context->getCurrentStateCopy();\n assert(context->getCurrentStateRef().toString()==stateCopy.toString());\n\n Array<std::string> stateNames = model->getStateVariableNames();\n OpenSim::Force* dForce=&(model->updForceSet().get(\"TRIlong\"));\n Muscle* dTRIlong = dynamic_cast<Muscle*>(dForce);\n assert(dTRIlong);\n context->setPropertiesFromState();\n OpenSim::Thelen2003Muscle* thelenMsl = dynamic_cast<Thelen2003Muscle*>(dTRIlong);\n AbstractProperty& dProp = thelenMsl->updPropertyByName(\"ignore_tendon_compliance\");\n \n PropertyHelper::setValueBool(true, dProp);\n cout << \"Prop after is \" << dProp.toString() << endl;\n\n bool exceptionThrown = false;\n try{\/\/ adding to the system should cause Muscle that do not handle\n \/\/ ignore_tendon_compliance to throw an exception\n context->recreateSystemKeepStage();\n } \n catch (const std::exception& e) {\n cout << e.what() << endl;\n exceptionThrown = true;\n PropertyHelper::setValueBool(false, dProp);\n cout << \"Prop reset to \" << dProp.toString() << endl;\n \/\/ recreate the system so test can continue\n context->recreateSystemKeepStage();\n }\n\n SimTK_ASSERT_ALWAYS(exceptionThrown, \"Setting ignore_tendon_compliance must throw an exception.\");\n\n\n AbstractProperty& dProp2 = thelenMsl->updPropertyByName(\"ignore_tendon_compliance\");\n cout << \"Prop after create system is \" << dProp2.toString() << endl;\n bool after = PropertyHelper::getValueBool(dProp);\n SimTK_ASSERT_ALWAYS(!after, \"Property has wrong value!!\");\n dTRIlong->updGeometryPath().updateGeometry(context->getCurrentStateRef());\n const OpenSim::Array<AbstractPathPoint*>& path = context->getCurrentPath(*dTRIlong);\n cout << \"Muscle Path\" << endl;\n cout << path.getSize() << endl;\n for(int i=0; i< path.getSize(); i++)\n cout << path[i]->getParentFrame().getName()\n << path[i]->getLocation(stateCopy) << endl;\n \/\/ Compare to known path \n const OpenSim::Body& dBody = model->getBodySet().get(\"r_ulna_radius_hand\");\n Transform xform = context->getTransform(dBody);\n cout << xform << endl;\n double flat[16];\n context->getTransformAsDouble16(xform, flat);\n \/\/ Compare to known xform\n double markerPosition[] = {.005000000000, -0.290400000000, 0.030000000000};\n double markerPositionInGround[3];\n context->transformPosition(dBody, markerPosition, markerPositionInGround); \/\/ to display markers\n cout << \"Global frame position = \" << markerPositionInGround[0] << \n markerPositionInGround[1] << markerPositionInGround[2]<< endl;\n \/\/ Check xformed point against known position\n const Coordinate& dr_elbow_flex = model->getCoordinateSet().get(\"r_elbow_flex\");\n bool isLocked = context->getLocked(dr_elbow_flex);\n assert(!isLocked);\n double startValue = context->getValue(dr_elbow_flex);\n cout << \"Coordinate start value = \" << startValue << endl;\n double length1 = context->getMuscleLength(*dTRIlong);\n cout << length1 << endl;\n ASSERT_EQUAL(.277609, length1, 1e-5);\n \/\/ Coordinate Slider\n context->setValue(dr_elbow_flex, 100*SimTK_PI\/180.);\n \/\/ Get body transform, marker position and muscle path (tests wrapping as well)\n xform = context->getTransform(dBody);\n cout << \"After setting coordinate to 100 deg.\" << endl;\n cout << xform << endl;\n \/\/ Compare to known xform\n dTRIlong->updGeometryPath().updateGeometry(context->getCurrentStateRef());\n const OpenSim::Array<AbstractPathPoint*>& newPath = context->getCurrentPath(*dTRIlong);\n \/\/ Compare to known path \n cout << \"New Muscle Path\" << endl;\n cout << path.getSize() << endl;\n for(int i=0; i< path.getSize(); i++)\n cout << path[i]->getParentFrame().getName() \n << path[i]->getLocation(stateCopy) << endl;\n double length2 = context->getMuscleLength(*dTRIlong);\n cout << length2 << endl;\n ASSERT_EQUAL(.315748, length2, 1e-5);\n \/\/ Test that we can lock coordinates to specific value and make this persistant.\n Coordinate& dr_elbow_flex_mod = model->updCoordinateSet().get(\"r_elbow_flex\");\n \/\/dr_elbow_flex_mod.setDefaultValue(0.5);\n dr_elbow_flex_mod.setDefaultLocked(true);\n context->setValue(dr_elbow_flex_mod, 0.5);\n \/\/model->print(\"wrist_locked_elbow.osim\");\n context->recreateSystemKeepStage();\n const Coordinate& dr_elbow_flexNew = model->getCoordinateSet().get(\"r_elbow_flex\");\n assert(context->getLocked(dr_elbow_flexNew));\n ASSERT_EQUAL(0.5, context->getValue(dr_elbow_flexNew), 0.000001);\n\n \/\/ Exercise Editing workflow\n \/\/ These are the same calls done from GUI code base through Property edits\n OpenSim::Body& bdy = model->updBodySet().get(\"r_humerus\");\n AbstractProperty& massProp = bdy.updPropertyByName(\"mass\");\n double oldValue = PropertyHelper::getValueDouble(massProp);\n double v = oldValue + 1.0;\n context->cacheModelAndState();\n PropertyHelper::setValueDouble(v, massProp);\n context->restoreStateFromCachedModel();\n\n \/\/ Exercise PathPoint operations used to edit Path in GUI\n PathPointSet& pathPoints = dTRIlong->updGeometryPath().updPathPointSet();\n std::string pathBeforeInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathBeforeInXML << endl;\n int origSize = pathPoints.getSize();\n AbstractPathPoint& savePoint = pathPoints.get(\"TRIlong-P2\");\n const std::string& saveFrameName = savePoint.getParentFrame().getName();\n AbstractPathPoint* clonedPoint = savePoint.clone();\n\n \/\/ Test delete second PathPoint from TRIlong muscle\n context->deletePathPoint(dTRIlong->updGeometryPath(), 2); \n assert(pathPoints.getSize() == origSize - 1);\n std::string pathAfterDeletionInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterDeletionInXML << endl;\n \n \/\/ Test adding PathPoint to TRIlong muscle (Stationary)\n Component& frame = model->updComponent(saveFrameName);\n PhysicalFrame* physFrame = PhysicalFrame::safeDownCast(&frame);\n context->addPathPoint(dTRIlong->updGeometryPath(), 3, *physFrame);\n assert(pathPoints.getSize() == origSize);\n std::string pathAfterReinsertionInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterReinsertionInXML << endl;\n\n \/\/ Test changing type to ConditionalPathPoint\n ConditionalPathPoint* newPoint = new ConditionalPathPoint();\n AbstractPathPoint& oldPoint = pathPoints.get(2);\n newPoint->setCoordinate(model->getCoordinateSet().get(0));\n newPoint->setParentFrame(oldPoint.getParentFrame());\n context->replacePathPoint(dTRIlong->updGeometryPath(), oldPoint, *newPoint);\n assert(pathPoints.getSize() == origSize);\n\n std::string pathAfterTypeChangeToViaInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterTypeChangeToViaInXML << endl;\n \n \/\/ Make a change to a socket that is invalid and verify that we can recover\n \/\/ from that invalid change by restoring from a cached model and state.\n context->cacheModelAndState();\n Joint& shoulder = model->updComponent<Joint>(\"r_shoulder\");\n AbstractSocket& socket = shoulder.updSocket(\"child_frame\");\n const std::string originalConnecteeName = socket.getConnecteeName();\n try {\n \/\/ create an invalid model where joint connects two frames on ground\n context->setConnecteeName(shoulder, socket, \"ground\");\n }\n catch (const std::exception& e) {\n \/\/ Expect meaningful error message rather than a crash\n cout << \"Exception: \" << e.what() << endl;\n }\n AbstractSocket& psocket = shoulder.updSocket(\"parent_frame\");\n const std::string poriginalConnecteeName = psocket.getConnecteeName();\n try {\n \/\/ create an invalid model\n psocket.setConnecteeName(\"r_ulna_radius_hand\"); \n context->restoreStateFromCachedModel();\n }\n catch (...) {\n \/\/ undo the change\n socket.setConnecteeName(originalConnecteeName);\n context->restoreStateFromCachedModel();\n }\n\n return status;\n } catch (const std::exception& e) {\n cout << \"Exception: \" << e.what() << endl;\n return 1;\n }\n}\n\n<commit_msg>Update test case<commit_after>\/* -------------------------------------------------------------------------- *\n * OpenSim: testContext.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2017 Stanford University and the Authors *\n * Author(s): Ayman Habib *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include \"..\/OpenSimContext.h\"\n#include <OpenSim\/Common\/Function.h>\n#include <OpenSim\/Common\/MarkerData.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/Body.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/Coordinate.h>\n#include <OpenSim\/Simulation\/Model\/Marker.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Simulation\/Model\/BodySet.h>\n#include <OpenSim\/Simulation\/Model\/MovingPathPoint.h>\n#include <OpenSim\/Simulation\/Model\/Muscle.h>\n#include <OpenSim\/Simulation\/Model\/PathPoint.h>\n#include <OpenSim\/Simulation\/Wrap\/PathWrap.h>\n#include <OpenSim\/Simulation\/Model\/ConditionalPathPoint.h>\n#include <OpenSim\/Simulation\/SimbodyEngine\/SimbodyEngine.h>\n#include <OpenSim\/Simulation\/Wrap\/WrapObject.h>\n#include <OpenSim\/Simulation\/Model\/Analysis.h>\n#include <OpenSim\/Simulation\/Model\/MarkerSet.h>\n#include <OpenSim\/Tools\/AnalyzeTool.h>\n#include <OpenSim\/Tools\/ModelScaler.h>\n#include <OpenSim\/Tools\/Measurement.h>\n#include <OpenSim\/Tools\/MarkerPlacer.h>\n#include <OpenSim\/Simulation\/Model\/ForceSet.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Actuators\/Thelen2003Muscle.h>\n\nusing namespace OpenSim;\nusing namespace SimTK;\nusing namespace std;\n\n#define ASSERT_EQUAL(expected, found, tolerance) { \\\ndouble tol = std::max((tolerance), std::abs((expected)*(tolerance))); \\\nif ((found)<(expected)-(tol) || (found)>(expected)+(tol)) throw(exception());}\n\nint main()\n{\n try {\n int status = 0;\n\n \/\/ To Retrace the steps taken by the GUI this test case follows the same call sequence:\n \/\/ new Model(file)\n \/\/ new OpenSimContext(model.initSystem(), model);\n \/\/ context.updateDisplayer(muscle) \/\/ to display muscles\n \/\/ context.getCurrentPath(muscle)\n \/\/ context.getTransform(body)\n \/\/ context.transformPosition(body, loc, global) \/\/ to display markers\n \/\/ context.getLocked(Coordinate)\n \/\/ context.getValue(cooridnate)\n LoadOpenSimLibrary(\"osimActuators\");\n LoadOpenSimLibrary(\"osimSimulation\");\n LoadOpenSimLibrary(\"osimJavaJNI\");\n\n Model *model = new Model(\"wrist.osim\");\n OpenSimContext* context = new OpenSimContext(&model->initSystem(), model);\n const ForceSet& fs = model->getForceSet();\n int n1 = fs.getNumGroups();\n const ObjectGroup* grp = fs.getGroup(\"wrist\");\n assert(grp);\n const Array<const Object*>& members = grp->getMembers();\n int sz = members.getSize();\n ASSERT_EQUAL(sz,5,0);\n assert(members.get(0)->getName()==\"ECRB\");\n delete model;\n delete context;\n model = new Model(\"arm26_20.osim\");\n context = new OpenSimContext(&model->initSystem(), model);\n \/\/ Make a copy of state contained in context ad make sure content match \n SimTK::State stateCopy = context->getCurrentStateCopy();\n assert(context->getCurrentStateRef().toString()==stateCopy.toString());\n\n Array<std::string> stateNames = model->getStateVariableNames();\n OpenSim::Force* dForce=&(model->updForceSet().get(\"TRIlong\"));\n Muscle* dTRIlong = dynamic_cast<Muscle*>(dForce);\n assert(dTRIlong);\n context->setPropertiesFromState();\n OpenSim::Thelen2003Muscle* thelenMsl = dynamic_cast<Thelen2003Muscle*>(dTRIlong);\n AbstractProperty& dProp = thelenMsl->updPropertyByName(\"ignore_tendon_compliance\");\n \n PropertyHelper::setValueBool(true, dProp);\n cout << \"Prop after is \" << dProp.toString() << endl;\n\n bool exceptionThrown = false;\n try{\/\/ adding to the system should cause Muscle that do not handle\n \/\/ ignore_tendon_compliance to throw an exception\n context->recreateSystemKeepStage();\n } \n catch (const std::exception& e) {\n cout << e.what() << endl;\n exceptionThrown = true;\n PropertyHelper::setValueBool(false, dProp);\n cout << \"Prop reset to \" << dProp.toString() << endl;\n \/\/ recreate the system so test can continue\n context->recreateSystemKeepStage();\n }\n\n SimTK_ASSERT_ALWAYS(exceptionThrown, \"Setting ignore_tendon_compliance must throw an exception.\");\n\n\n AbstractProperty& dProp2 = thelenMsl->updPropertyByName(\"ignore_tendon_compliance\");\n cout << \"Prop after create system is \" << dProp2.toString() << endl;\n bool after = PropertyHelper::getValueBool(dProp);\n SimTK_ASSERT_ALWAYS(!after, \"Property has wrong value!!\");\n dTRIlong->updGeometryPath().updateGeometry(context->getCurrentStateRef());\n const OpenSim::Array<AbstractPathPoint*>& path = context->getCurrentPath(*dTRIlong);\n cout << \"Muscle Path\" << endl;\n cout << path.getSize() << endl;\n for(int i=0; i< path.getSize(); i++)\n cout << path[i]->getParentFrame().getName()\n << path[i]->getLocation(stateCopy) << endl;\n \/\/ Compare to known path \n const OpenSim::Body& dBody = model->getBodySet().get(\"r_ulna_radius_hand\");\n Transform xform = context->getTransform(dBody);\n cout << xform << endl;\n double flat[16];\n context->getTransformAsDouble16(xform, flat);\n \/\/ Compare to known xform\n double markerPosition[] = {.005000000000, -0.290400000000, 0.030000000000};\n double markerPositionInGround[3];\n context->transformPosition(dBody, markerPosition, markerPositionInGround); \/\/ to display markers\n cout << \"Global frame position = \" << markerPositionInGround[0] << \n markerPositionInGround[1] << markerPositionInGround[2]<< endl;\n \/\/ Check xformed point against known position\n const Coordinate& dr_elbow_flex = model->getCoordinateSet().get(\"r_elbow_flex\");\n bool isLocked = context->getLocked(dr_elbow_flex);\n assert(!isLocked);\n double startValue = context->getValue(dr_elbow_flex);\n cout << \"Coordinate start value = \" << startValue << endl;\n double length1 = context->getMuscleLength(*dTRIlong);\n cout << length1 << endl;\n ASSERT_EQUAL(.277609, length1, 1e-5);\n \/\/ Coordinate Slider\n context->setValue(dr_elbow_flex, 100*SimTK_PI\/180.);\n \/\/ Get body transform, marker position and muscle path (tests wrapping as well)\n xform = context->getTransform(dBody);\n cout << \"After setting coordinate to 100 deg.\" << endl;\n cout << xform << endl;\n \/\/ Compare to known xform\n dTRIlong->updGeometryPath().updateGeometry(context->getCurrentStateRef());\n const OpenSim::Array<AbstractPathPoint*>& newPath = context->getCurrentPath(*dTRIlong);\n \/\/ Compare to known path \n cout << \"New Muscle Path\" << endl;\n cout << path.getSize() << endl;\n for(int i=0; i< path.getSize(); i++)\n cout << path[i]->getParentFrame().getName() \n << path[i]->getLocation(stateCopy) << endl;\n double length2 = context->getMuscleLength(*dTRIlong);\n cout << length2 << endl;\n ASSERT_EQUAL(.315748, length2, 1e-5);\n \/\/ Test that we can lock coordinates to specific value and make this persistant.\n Coordinate& dr_elbow_flex_mod = model->updCoordinateSet().get(\"r_elbow_flex\");\n \/\/dr_elbow_flex_mod.setDefaultValue(0.5);\n dr_elbow_flex_mod.setDefaultLocked(true);\n context->setValue(dr_elbow_flex_mod, 0.5);\n \/\/model->print(\"wrist_locked_elbow.osim\");\n context->recreateSystemKeepStage();\n const Coordinate& dr_elbow_flexNew = model->getCoordinateSet().get(\"r_elbow_flex\");\n assert(context->getLocked(dr_elbow_flexNew));\n ASSERT_EQUAL(0.5, context->getValue(dr_elbow_flexNew), 0.000001);\n\n \/\/ Exercise Editing workflow\n \/\/ These are the same calls done from GUI code base through Property edits\n OpenSim::Body& bdy = model->updBodySet().get(\"r_humerus\");\n AbstractProperty& massProp = bdy.updPropertyByName(\"mass\");\n double oldValue = PropertyHelper::getValueDouble(massProp);\n double v = oldValue + 1.0;\n context->cacheModelAndState();\n PropertyHelper::setValueDouble(v, massProp);\n context->restoreStateFromCachedModel();\n\n \/\/ Exercise PathPoint operations used to edit Path in GUI\n PathPointSet& pathPoints = dTRIlong->updGeometryPath().updPathPointSet();\n std::string pathBeforeInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathBeforeInXML << endl;\n int origSize = pathPoints.getSize();\n AbstractPathPoint& savePoint = pathPoints.get(\"TRIlong-P2\");\n const std::string& saveFrameName = savePoint.getParentFrame().getName();\n AbstractPathPoint* clonedPoint = savePoint.clone();\n\n \/\/ Test delete second PathPoint from TRIlong muscle\n context->deletePathPoint(dTRIlong->updGeometryPath(), 2); \n assert(pathPoints.getSize() == origSize - 1);\n std::string pathAfterDeletionInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterDeletionInXML << endl;\n \n \/\/ Test adding PathPoint to TRIlong muscle (Stationary)\n Component& frame = model->updComponent(saveFrameName);\n PhysicalFrame* physFrame = PhysicalFrame::safeDownCast(&frame);\n context->addPathPoint(dTRIlong->updGeometryPath(), 3, *physFrame);\n assert(pathPoints.getSize() == origSize);\n std::string pathAfterReinsertionInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterReinsertionInXML << endl;\n\n \/\/ Test changing type to ConditionalPathPoint\n ConditionalPathPoint* newPoint = new ConditionalPathPoint();\n AbstractPathPoint& oldPoint = pathPoints.get(2);\n newPoint->setCoordinate(model->getCoordinateSet().get(0));\n newPoint->setParentFrame(oldPoint.getParentFrame());\n context->replacePathPoint(dTRIlong->updGeometryPath(), oldPoint, *newPoint);\n assert(pathPoints.getSize() == origSize);\n\n std::string pathAfterTypeChangeToViaInXML = dTRIlong->updGeometryPath().dump();\n std::cout << pathAfterTypeChangeToViaInXML << endl;\n \n \/\/ Make a change to a socket that is invalid and verify that we can recover\n \/\/ from that invalid change by restoring from a cached model and state.\n context->cacheModelAndState();\n Joint& shoulder = model->updComponent<Joint>(\"r_shoulder\");\n AbstractSocket& socket = shoulder.updSocket(\"child_frame\");\n const std::string originalConnecteeName = socket.getConnecteeName();\n try {\n \/\/ create an invalid model where joint connects two frames on ground\n context->setConnecteeName(shoulder, socket, \"ground\");\n }\n catch (const std::exception& e) {\n \/\/ Expect meaningful error message rather than a crash\n cout << \"Exception: \" << e.what() << endl;\n }\n AbstractSocket& psocket = shoulder.updSocket(\"parent_frame\");\n const std::string poriginalConnecteeName = psocket.getConnecteeName();\n try {\n \/\/ create an invalid model\n context->setConnecteeName(shoulder, psocket, \"r_ulna_radius_hand\");\n }\n catch (const std::exception& e) {\n \/\/ undo the change\n cout << \"Exception: \" << e.what() << endl;\n }\n\n return status;\n } catch (const std::exception& e) {\n cout << \"Exception: \" << e.what() << endl;\n return 1;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ Unit tests for DelayManager class.\n\n#include \"webrtc\/modules\/audio_coding\/neteq\/delay_manager.h\"\n\n#include <math.h>\n\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/audio_coding\/neteq\/mock\/mock_delay_peak_detector.h\"\n\nnamespace webrtc {\n\nusing ::testing::Return;\nusing ::testing::_;\n\nclass DelayManagerTest : public ::testing::Test {\n protected:\n static const int kMaxNumberOfPackets = 240;\n static const int kTimeStepMs = 10;\n static const int kFs = 8000;\n static const int kFrameSizeMs = 20;\n static const int kTsIncrement = kFrameSizeMs * kFs \/ 1000;\n\n DelayManagerTest();\n virtual void SetUp();\n virtual void TearDown();\n void SetPacketAudioLength(int lengt_ms);\n void InsertNextPacket();\n void IncreaseTime(int inc_ms);\n\n DelayManager* dm_;\n MockDelayPeakDetector detector_;\n uint16_t seq_no_;\n uint32_t ts_;\n};\n\nDelayManagerTest::DelayManagerTest()\n : dm_(NULL),\n seq_no_(0x1234),\n ts_(0x12345678) {\n}\n\nvoid DelayManagerTest::SetUp() {\n EXPECT_CALL(detector_, Reset())\n .Times(1);\n dm_ = new DelayManager(kMaxNumberOfPackets, &detector_);\n}\n\nvoid DelayManagerTest::SetPacketAudioLength(int lengt_ms) {\n EXPECT_CALL(detector_, SetPacketAudioLength(lengt_ms));\n dm_->SetPacketAudioLength(lengt_ms);\n}\n\nvoid DelayManagerTest::InsertNextPacket() {\n EXPECT_EQ(0, dm_->Update(seq_no_, ts_, kFs));\n seq_no_ += 1;\n ts_ += kTsIncrement;\n}\n\nvoid DelayManagerTest::IncreaseTime(int inc_ms) {\n for (int t = 0; t < inc_ms; t += kTimeStepMs) {\n EXPECT_CALL(detector_, IncrementCounter(kTimeStepMs))\n .Times(1);\n dm_->UpdateCounters(kTimeStepMs);\n }\n}\nvoid DelayManagerTest::TearDown() {\n EXPECT_CALL(detector_, Die());\n delete dm_;\n}\n\nTEST_F(DelayManagerTest, CreateAndDestroy) {\n \/\/ Nothing to do here. The test fixture creates and destroys the DelayManager\n \/\/ object.\n}\n\nTEST_F(DelayManagerTest, VectorInitialization) {\n const DelayManager::IATVector& vec = dm_->iat_vector();\n double sum = 0.0;\n for (size_t i = 0; i < vec.size(); i++) {\n EXPECT_NEAR(ldexp(pow(0.5, static_cast<int>(i + 1)), 30), vec[i], 65536);\n \/\/ Tolerance 65536 in Q30 corresponds to a delta of approximately 0.00006.\n sum += vec[i];\n }\n EXPECT_EQ(1 << 30, static_cast<int>(sum)); \/\/ Should be 1 in Q30.\n}\n\nTEST_F(DelayManagerTest, SetPacketAudioLength) {\n const int kLengthMs = 30;\n \/\/ Expect DelayManager to pass on the new length to the detector object.\n EXPECT_CALL(detector_, SetPacketAudioLength(kLengthMs))\n .Times(1);\n EXPECT_EQ(0, dm_->SetPacketAudioLength(kLengthMs));\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(-1)); \/\/ Illegal parameter value.\n}\n\nTEST_F(DelayManagerTest, PeakFound) {\n \/\/ Expect DelayManager to pass on the question to the detector.\n \/\/ Call twice, and let the detector return true the first time and false the\n \/\/ second time.\n EXPECT_CALL(detector_, peak_found())\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n EXPECT_TRUE(dm_->PeakFound());\n EXPECT_FALSE(dm_->PeakFound());\n}\n\nTEST_F(DelayManagerTest, UpdateCounters) {\n \/\/ Expect DelayManager to pass on the counter update to the detector.\n EXPECT_CALL(detector_, IncrementCounter(kTimeStepMs))\n .Times(1);\n dm_->UpdateCounters(kTimeStepMs);\n}\n\nTEST_F(DelayManagerTest, UpdateNormal) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(false));\n InsertNextPacket();\n EXPECT_EQ(1 << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(1, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level,\n \/\/ but also at least 20 ms higher than |lower|, which is the limiting case\n \/\/ here.\n EXPECT_EQ((1 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, UpdateLongInterArrivalTime) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by two frame size.\n IncreaseTime(2 * kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(2, 2))\n .WillOnce(Return(false));\n InsertNextPacket();\n EXPECT_EQ(2 << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(2, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level,\n \/\/ but also at least 20 ms higher than |lower|, which is the limiting case\n \/\/ here.\n EXPECT_EQ((2 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, UpdatePeakFound) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return true to indicate that peaks are found. Let the peak height be 5.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillOnce(Return(5));\n InsertNextPacket();\n EXPECT_EQ(5 << 8, dm_->TargetLevel());\n EXPECT_EQ(1, dm_->base_target_level()); \/\/ Base target level is w\/o peaks.\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level.\n EXPECT_EQ((5 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(5 << 8, higher);\n}\n\nTEST_F(DelayManagerTest, TargetDelay) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(false));\n InsertNextPacket();\n const int kExpectedTarget = 1;\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(1, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of base target level, and |higher| to be\n \/\/ lower + 20 ms headroom.\n EXPECT_EQ((1 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, MaxAndRequiredDelay) {\n const int kExpectedTarget = 5;\n const int kTimeIncrement = kExpectedTarget * kFrameSizeMs;\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to |kExpectedTarget| packet. Return true to indicate peaks found.\n EXPECT_CALL(detector_, Update(kExpectedTarget, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillRepeatedly(Return(kExpectedTarget));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n\n \/\/ No limit is set.\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel());\n\n int kMaxDelayPackets = kExpectedTarget - 2;\n int kMaxDelayMs = kMaxDelayPackets * kFrameSizeMs;\n EXPECT_TRUE(dm_->SetMaximumDelay(kMaxDelayMs));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n EXPECT_EQ(kExpectedTarget * kFrameSizeMs, dm_->least_required_delay_ms());\n EXPECT_EQ(kMaxDelayPackets << 8, dm_->TargetLevel());\n\n \/\/ Target level at least should be one packet.\n EXPECT_FALSE(dm_->SetMaximumDelay(kFrameSizeMs - 1));\n}\n\nTEST_F(DelayManagerTest, MinAndRequiredDelay) {\n const int kExpectedTarget = 5;\n const int kTimeIncrement = kExpectedTarget * kFrameSizeMs;\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to |kExpectedTarget| packet. Return true to indicate peaks found.\n EXPECT_CALL(detector_, Update(kExpectedTarget, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillRepeatedly(Return(kExpectedTarget));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n\n \/\/ No limit is applied.\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel());\n\n int kMinDelayPackets = kExpectedTarget + 2;\n int kMinDelayMs = kMinDelayPackets * kFrameSizeMs;\n dm_->SetMinimumDelay(kMinDelayMs);\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n EXPECT_EQ(kExpectedTarget * kFrameSizeMs, dm_->least_required_delay_ms());\n EXPECT_EQ(kMinDelayPackets << 8, dm_->TargetLevel());\n}\n\nTEST_F(DelayManagerTest, Failures) {\n \/\/ Wrong sample rate.\n EXPECT_EQ(-1, dm_->Update(0, 0, -1));\n \/\/ Wrong packet size.\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(0));\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(-1));\n\n \/\/ Minimum delay higher than a maximum delay is not accepted.\n EXPECT_TRUE(dm_->SetMaximumDelay(10));\n EXPECT_FALSE(dm_->SetMinimumDelay(20));\n\n \/\/ Maximum delay less than minimum delay is not accepted.\n EXPECT_TRUE(dm_->SetMaximumDelay(100));\n EXPECT_TRUE(dm_->SetMinimumDelay(80));\n EXPECT_FALSE(dm_->SetMaximumDelay(60));\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Increase the tolerance in NetEq's DelayManagerTest a notch<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ Unit tests for DelayManager class.\n\n#include \"webrtc\/modules\/audio_coding\/neteq\/delay_manager.h\"\n\n#include <math.h>\n\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/audio_coding\/neteq\/mock\/mock_delay_peak_detector.h\"\n\nnamespace webrtc {\n\nusing ::testing::Return;\nusing ::testing::_;\n\nclass DelayManagerTest : public ::testing::Test {\n protected:\n static const int kMaxNumberOfPackets = 240;\n static const int kTimeStepMs = 10;\n static const int kFs = 8000;\n static const int kFrameSizeMs = 20;\n static const int kTsIncrement = kFrameSizeMs * kFs \/ 1000;\n\n DelayManagerTest();\n virtual void SetUp();\n virtual void TearDown();\n void SetPacketAudioLength(int lengt_ms);\n void InsertNextPacket();\n void IncreaseTime(int inc_ms);\n\n DelayManager* dm_;\n MockDelayPeakDetector detector_;\n uint16_t seq_no_;\n uint32_t ts_;\n};\n\nDelayManagerTest::DelayManagerTest()\n : dm_(NULL),\n seq_no_(0x1234),\n ts_(0x12345678) {\n}\n\nvoid DelayManagerTest::SetUp() {\n EXPECT_CALL(detector_, Reset())\n .Times(1);\n dm_ = new DelayManager(kMaxNumberOfPackets, &detector_);\n}\n\nvoid DelayManagerTest::SetPacketAudioLength(int lengt_ms) {\n EXPECT_CALL(detector_, SetPacketAudioLength(lengt_ms));\n dm_->SetPacketAudioLength(lengt_ms);\n}\n\nvoid DelayManagerTest::InsertNextPacket() {\n EXPECT_EQ(0, dm_->Update(seq_no_, ts_, kFs));\n seq_no_ += 1;\n ts_ += kTsIncrement;\n}\n\nvoid DelayManagerTest::IncreaseTime(int inc_ms) {\n for (int t = 0; t < inc_ms; t += kTimeStepMs) {\n EXPECT_CALL(detector_, IncrementCounter(kTimeStepMs))\n .Times(1);\n dm_->UpdateCounters(kTimeStepMs);\n }\n}\nvoid DelayManagerTest::TearDown() {\n EXPECT_CALL(detector_, Die());\n delete dm_;\n}\n\nTEST_F(DelayManagerTest, CreateAndDestroy) {\n \/\/ Nothing to do here. The test fixture creates and destroys the DelayManager\n \/\/ object.\n}\n\nTEST_F(DelayManagerTest, VectorInitialization) {\n const DelayManager::IATVector& vec = dm_->iat_vector();\n double sum = 0.0;\n for (size_t i = 0; i < vec.size(); i++) {\n EXPECT_NEAR(ldexp(pow(0.5, static_cast<int>(i + 1)), 30), vec[i], 65537);\n \/\/ Tolerance 65537 in Q30 corresponds to a delta of approximately 0.00006.\n sum += vec[i];\n }\n EXPECT_EQ(1 << 30, static_cast<int>(sum)); \/\/ Should be 1 in Q30.\n}\n\nTEST_F(DelayManagerTest, SetPacketAudioLength) {\n const int kLengthMs = 30;\n \/\/ Expect DelayManager to pass on the new length to the detector object.\n EXPECT_CALL(detector_, SetPacketAudioLength(kLengthMs))\n .Times(1);\n EXPECT_EQ(0, dm_->SetPacketAudioLength(kLengthMs));\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(-1)); \/\/ Illegal parameter value.\n}\n\nTEST_F(DelayManagerTest, PeakFound) {\n \/\/ Expect DelayManager to pass on the question to the detector.\n \/\/ Call twice, and let the detector return true the first time and false the\n \/\/ second time.\n EXPECT_CALL(detector_, peak_found())\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n EXPECT_TRUE(dm_->PeakFound());\n EXPECT_FALSE(dm_->PeakFound());\n}\n\nTEST_F(DelayManagerTest, UpdateCounters) {\n \/\/ Expect DelayManager to pass on the counter update to the detector.\n EXPECT_CALL(detector_, IncrementCounter(kTimeStepMs))\n .Times(1);\n dm_->UpdateCounters(kTimeStepMs);\n}\n\nTEST_F(DelayManagerTest, UpdateNormal) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(false));\n InsertNextPacket();\n EXPECT_EQ(1 << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(1, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level,\n \/\/ but also at least 20 ms higher than |lower|, which is the limiting case\n \/\/ here.\n EXPECT_EQ((1 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, UpdateLongInterArrivalTime) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by two frame size.\n IncreaseTime(2 * kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(2, 2))\n .WillOnce(Return(false));\n InsertNextPacket();\n EXPECT_EQ(2 << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(2, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level,\n \/\/ but also at least 20 ms higher than |lower|, which is the limiting case\n \/\/ here.\n EXPECT_EQ((2 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, UpdatePeakFound) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return true to indicate that peaks are found. Let the peak height be 5.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillOnce(Return(5));\n InsertNextPacket();\n EXPECT_EQ(5 << 8, dm_->TargetLevel());\n EXPECT_EQ(1, dm_->base_target_level()); \/\/ Base target level is w\/o peaks.\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of target level, and |higher| to be target level.\n EXPECT_EQ((5 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(5 << 8, higher);\n}\n\nTEST_F(DelayManagerTest, TargetDelay) {\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Advance time by one frame size.\n IncreaseTime(kFrameSizeMs);\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to 1 packet, and (base) target level equal to 1 as well.\n \/\/ Return false to indicate no peaks found.\n EXPECT_CALL(detector_, Update(1, 1))\n .WillOnce(Return(false));\n InsertNextPacket();\n const int kExpectedTarget = 1;\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel()); \/\/ In Q8.\n EXPECT_EQ(1, dm_->base_target_level());\n int lower, higher;\n dm_->BufferLimits(&lower, &higher);\n \/\/ Expect |lower| to be 75% of base target level, and |higher| to be\n \/\/ lower + 20 ms headroom.\n EXPECT_EQ((1 << 8) * 3 \/ 4, lower);\n EXPECT_EQ(lower + (20 << 8) \/ kFrameSizeMs, higher);\n}\n\nTEST_F(DelayManagerTest, MaxAndRequiredDelay) {\n const int kExpectedTarget = 5;\n const int kTimeIncrement = kExpectedTarget * kFrameSizeMs;\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to |kExpectedTarget| packet. Return true to indicate peaks found.\n EXPECT_CALL(detector_, Update(kExpectedTarget, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillRepeatedly(Return(kExpectedTarget));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n\n \/\/ No limit is set.\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel());\n\n int kMaxDelayPackets = kExpectedTarget - 2;\n int kMaxDelayMs = kMaxDelayPackets * kFrameSizeMs;\n EXPECT_TRUE(dm_->SetMaximumDelay(kMaxDelayMs));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n EXPECT_EQ(kExpectedTarget * kFrameSizeMs, dm_->least_required_delay_ms());\n EXPECT_EQ(kMaxDelayPackets << 8, dm_->TargetLevel());\n\n \/\/ Target level at least should be one packet.\n EXPECT_FALSE(dm_->SetMaximumDelay(kFrameSizeMs - 1));\n}\n\nTEST_F(DelayManagerTest, MinAndRequiredDelay) {\n const int kExpectedTarget = 5;\n const int kTimeIncrement = kExpectedTarget * kFrameSizeMs;\n SetPacketAudioLength(kFrameSizeMs);\n \/\/ First packet arrival.\n InsertNextPacket();\n \/\/ Second packet arrival.\n \/\/ Expect detector update method to be called once with inter-arrival time\n \/\/ equal to |kExpectedTarget| packet. Return true to indicate peaks found.\n EXPECT_CALL(detector_, Update(kExpectedTarget, _))\n .WillRepeatedly(Return(true));\n EXPECT_CALL(detector_, MaxPeakHeight())\n .WillRepeatedly(Return(kExpectedTarget));\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n\n \/\/ No limit is applied.\n EXPECT_EQ(kExpectedTarget << 8, dm_->TargetLevel());\n\n int kMinDelayPackets = kExpectedTarget + 2;\n int kMinDelayMs = kMinDelayPackets * kFrameSizeMs;\n dm_->SetMinimumDelay(kMinDelayMs);\n IncreaseTime(kTimeIncrement);\n InsertNextPacket();\n EXPECT_EQ(kExpectedTarget * kFrameSizeMs, dm_->least_required_delay_ms());\n EXPECT_EQ(kMinDelayPackets << 8, dm_->TargetLevel());\n}\n\nTEST_F(DelayManagerTest, Failures) {\n \/\/ Wrong sample rate.\n EXPECT_EQ(-1, dm_->Update(0, 0, -1));\n \/\/ Wrong packet size.\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(0));\n EXPECT_EQ(-1, dm_->SetPacketAudioLength(-1));\n\n \/\/ Minimum delay higher than a maximum delay is not accepted.\n EXPECT_TRUE(dm_->SetMaximumDelay(10));\n EXPECT_FALSE(dm_->SetMinimumDelay(20));\n\n \/\/ Maximum delay less than minimum delay is not accepted.\n EXPECT_TRUE(dm_->SetMaximumDelay(100));\n EXPECT_TRUE(dm_->SetMinimumDelay(80));\n EXPECT_FALSE(dm_->SetMaximumDelay(60));\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\nusing namespace std;\n<commit_msg>amend maint<commit_after>#include <iostream>\nusing namespace std;\n\/**\n * This is maint branch \n **\/\n\nint main() {\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2019-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <ivwdataframe\/pydataframe.h>\n\n#include <warn\/push>\n#include <warn\/ignore\/shadow>\n#include <pybind11\/functional.h>\n#include <pybind11\/stl.h>\n#include <pybind11\/stl_bind.h>\n#include <warn\/pop>\n\n#include <inviwo\/dataframe\/datastructures\/column.h>\n#include <inviwo\/dataframe\/datastructures\/dataframe.h>\n#include <inviwo\/dataframe\/datastructures\/datapoint.h>\n#include <inviwo\/dataframe\/util\/dataframeutil.h>\n\n#include <inviwo\/core\/util\/defaultvalues.h>\n#include <inviwo\/core\/util\/safecstr.h>\n#include <inviwo\/core\/datastructures\/buffer\/buffer.h>\n#include <modules\/python3\/pyportutils.h>\n\n#include <fmt\/format.h>\n\nnamespace py = pybind11;\n\nnamespace inviwo {\n\nnamespace {\n\nstruct DataFrameAddColumnReg {\n template <typename T>\n auto operator()(py::class_<DataFrame, std::shared_ptr<DataFrame>>& d) {\n auto classname = Defaultvalues<T>::getName();\n\n d.def(\n fmt::format(\"add{}Column\", classname).c_str(),\n [](DataFrame& d, const std::string& header, const size_t size = 0) {\n return d.addColumn<T>(header, size);\n },\n py::arg(\"header\"), py::arg(\"size\") = 0);\n\n d.def(\n fmt::format(\"add{}Column\", classname).c_str(),\n [](DataFrame& d, std::string header, std::vector<T> data) {\n return d.addColumn(std::move(header), std::move(data));\n },\n py::arg(\"header\"), py::arg(\"data\"));\n }\n};\n\nstruct DataPointReg {\n template <typename T>\n auto operator()(pybind11::module& m) {\n using D = DataPoint<T>;\n auto classname = Defaultvalues<T>::getName() + \"DataPoint\";\n\n py::class_<D, DataPointBase, std::shared_ptr<D>> data(m, classname.c_str());\n data.def_property_readonly(\"data\", &D::getData)\n .def_property_readonly(\"str\", &D::toString)\n .def(\"__repr__\",\n [classname](D& p) { return fmt::format(\"<{}: '{}'>\", classname, p.toString()); });\n }\n};\n\nstruct TemplateColumnReg {\n template <typename T>\n auto operator()(pybind11::module& m) {\n using C = TemplateColumn<T>;\n auto classname = Defaultvalues<T>::getName() + \"Column\";\n\n py::class_<C, Column, std::shared_ptr<C>> col(m, classname.c_str());\n col.def_property_readonly(\"buffer\", [](C& c) { return c.getTypedBuffer(); })\n .def(py::init<const std::string&>())\n .def(\"add\", py::overload_cast<const T&>(&C::add))\n .def(\"add\", py::overload_cast<std::string_view>(&C::add))\n .def(\"append\", [](C& c, C& src) { c.append(src); })\n .def(\"set\", &C::set)\n .def(\n \"get\",\n [](const C& c, size_t i) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i);\n },\n py::arg(\"i\"))\n .def(\n \"get\",\n [](const C& c, size_t i, bool asString) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i, asString);\n },\n py::arg(\"i\"), py::arg(\"asString\"))\n .def(\"__repr__\", [classname](C& c) {\n return fmt::format(\"<{}: '{}', {}, {}>\", classname, c.getHeader(), c.getSize(),\n c.getBuffer()->getDataFormat()->getString());\n });\n }\n};\n\n} \/\/ namespace\n\nvoid exposeDataFrame(pybind11::module& m) {\n py::class_<DataPointBase, std::shared_ptr<DataPointBase>>(m, \"DataPointBase\")\n .def(\"__repr__\",\n [](DataPointBase& p) { return fmt::format(\"<DataPoint: '{}'>\", p.toString()); });\n\n py::class_<Column, std::shared_ptr<Column>>(m, \"Column\")\n .def_property(\"header\", &Column::getHeader, &Column::setHeader)\n .def_property_readonly(\"buffer\", [](Column& self) { return self.getBuffer(); })\n .def_property_readonly(\"size\", &Column::getSize)\n .def(\"__repr__\", [](Column& c) {\n return fmt::format(\"<Column: '{}', {}, {}>\", c.getHeader(), c.getSize(),\n c.getBuffer()->getDataFormat()->getString());\n });\n\n using Scalars = std::tuple<float, double, int, glm::i64, size_t, std::uint32_t>;\n util::for_each_type<Scalars>{}(DataPointReg{}, m);\n util::for_each_type<Scalars>{}(TemplateColumnReg{}, m);\n\n py::class_<CategoricalColumn, TemplateColumn<std::uint32_t>,\n std::shared_ptr<CategoricalColumn>>(m, \"CategoricalColumn\")\n .def(py::init<const std::string&>())\n .def_property_readonly(\"categories\", &CategoricalColumn::getCategories,\n py::return_value_policy::copy)\n .def(\"add\", [](CategoricalColumn& c, const std::string& str) { c.add(str); })\n .def(\"append\", [](CategoricalColumn& c, CategoricalColumn& src) { c.append(src); })\n .def(\"set\", [](CategoricalColumn& c, size_t idx, const std::uint32_t& v) { c.set(idx, v); })\n .def(\"set\", py::overload_cast<size_t, const std::string&>(&CategoricalColumn::set))\n .def(\n \"get\",\n [](const CategoricalColumn& c, size_t i, bool asString) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i, asString);\n },\n py::arg(\"i\"), py::arg(\"asString\") = true)\n .def(\"__repr__\", [](CategoricalColumn& c) {\n return fmt::format(\"<CategoricalColumn: '{}', {}, {} categories>\", c.getHeader(),\n c.getSize(), c.getCategories().size());\n });\n\n py::class_<DataFrame, std::shared_ptr<DataFrame>> dataframe(m, \"DataFrame\");\n dataframe.def(py::init<std::uint32_t>(), py::arg(\"size\") = 0)\n .def_property_readonly(\"cols\", &DataFrame::getNumberOfColumns)\n .def_property_readonly(\"rows\", &DataFrame::getNumberOfRows)\n .def(\"indexcol\", [](DataFrame& d) { return d.getIndexColumn(); })\n .def(\"column\", [](DataFrame& self, size_t index) { return self.getColumn(index); })\n .def(\"addColumnFromBuffer\", &DataFrame::addColumnFromBuffer)\n .def(\"addCategoricalColumn\",\n py::overload_cast<std::string_view, size_t>(&DataFrame::addCategoricalColumn),\n py::arg(\"header\"), py::arg(\"size\") = 0)\n .def(\"addCategoricalColumn\",\n py::overload_cast<std::string_view, const std::vector<std::string>&>(\n &DataFrame::addCategoricalColumn),\n py::arg(\"header\"), py::arg(\"values\"))\n .def(\"getRow\", &DataFrame::getDataItem, py::arg(\"index\"), py::arg(\"asString\") = false)\n\n .def(\"updateIndex\", [](DataFrame& d) { d.updateIndexBuffer(); })\n\n \/\/ interface for operator[]\n .def(\n \"__getitem__\",\n [](const DataFrame& d, size_t i) {\n if (i >= d.getNumberOfColumns()) throw py::index_error();\n return *(d.begin() + i);\n },\n py::return_value_policy::reference_internal)\n \/\/ sequence protocol operations\n .def(\n \"__iter__\", [](const DataFrame& d) { return py::make_iterator(d.begin(), d.end()); },\n py::keep_alive<0, 1>() \/* Essential: keep object alive while iterator exists *\/)\n\n .def(\"__repr__\", [](const DataFrame& d) {\n std::string str = fmt::format(\"<DataFrame: {} column(s), {} rows\",\n d.getNumberOfColumns(), d.getNumberOfRows());\n size_t i = 0;\n for (auto c : d) {\n ++i;\n str += fmt::format(\"\\n {:>3}: '{}', {}, {}\", i, c->getHeader(), c->getSize(),\n c->getBuffer()->getDataFormat()->getString());\n }\n return str + \">\";\n });\n\n util::for_each_type<Scalars>{}(DataFrameAddColumnReg{}, dataframe);\n\n m.def(\"createDataFrame\", createDataFrame, py::arg(\"exampleRows\"),\n py::arg(\"colheaders\") = std::vector<std::string>{}, py::arg(\"doubleprecision\") = false,\n R\"delim(\nCreate a new DataFrame by guessing the column types from a number of rows.\n\nParameters\n----------\nexampleRows Rows for guessing data type of each column.\ncolHeaders Name of each column. If none are given, \"Column 1\", \"Column 2\", ... is used\ndoubleprecision If true, columns with floating point values will use double for storage\n)delim\")\n .def(\"appendColumns\", dataframe::appendColumns, py::arg(\"left\"), py::arg(\"right\"),\n py::arg(\"ignoreduplicates\") = false, py::arg(\"fillmissingrows\") = false,\n R\"delim(\nCreate a new DataFrame by appending the columns of DataFrame right to DataFrame left\n\nParameters\n----------\nignoreduplicates duplicate columns, i.e. same column header, are ignored if true\nfillmissingrows if true, missing rows in either DataFrame are filled with 0 or\n \"undefined\" (for categorical columns)\n)delim\")\n .def(\"appendRows\", dataframe::appendRows, py::arg(\"top\"), py::arg(\"bottom\"),\n py::arg(\"matchbyname\") = false,\n R\"delim(\nCreate a new DataFrame by appending the rows of DataFrame bottom to DataFrame top\n\nParameters\n----------\nmatchByName if true, column headers are used for matching columns. Otherwise columns\n are matched by order (default)\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::string&>(\n dataframe::innerJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumn\") = \"index\",\n R\"delim(\nCreate a new DataFrame by using an inner join of DataFrame left and DataFrame right.\nThat is only rows with matching keys are kept.\n\nIt is assumed that the entries in the key columns are unique. Otherwise results are undefined.\n\nParameters\n----------\nkeycolumn header of the column used as key for the join operation (default: index column)\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::vector<std::string>&>(\n dataframe::innerJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumns\"),\n R\"delim(\nCreate a new DataFrame by using an inner join of DataFrame left and DataFrame right.\nThat is only rows with matching all keys are kept.\n\nIt is assumed that the entries in the key columns are unique. Otherwise results are undefined.\n\nParameters\n----------\nkeycolumns list of headers of the columns used as key for the join operation\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::string&>(\n dataframe::leftJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumn\") = \"index\",\n R\"delim(\nCreate a new DataFrame by using an outer left join of DataFrame left and DataFrame right.\nThat is all rows of left are augmented with matching rows from right.\n\nIt is assumed that the entries in the key columns of right are unique. Otherwise results\nare undefined.\n\nParameters\n----------\nkeycolumn header of the column used as key for the join operation (default: index column)\n)delim\")\n .def(\"leftJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::vector<std::string>&>(\n dataframe::leftJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumns\"),\n R\"delim(\nCreate a new DataFrame by using an outer left join of DataFrame left and DataFrame right.\nThat is all rows of left are augmented with matching rows from right.\n\nIt is assumed that the entries in the key columns of right are unique. Otherwise results\nare undefined.\n\nParameters\n----------\nkeycolumns list of headers of the columns used as key for the join operation\n)delim\");\n\n exposeStandardDataPorts<DataFrame>(m, \"DataFrame\");\n}\n\n} \/\/ namespace inviwo\n<commit_msg>DataFramePython: updated python interface<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2019-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <ivwdataframe\/pydataframe.h>\n\n#include <warn\/push>\n#include <warn\/ignore\/shadow>\n#include <pybind11\/functional.h>\n#include <pybind11\/stl.h>\n#include <pybind11\/stl_bind.h>\n#include <warn\/pop>\n\n#include <inviwo\/dataframe\/datastructures\/column.h>\n#include <inviwo\/dataframe\/datastructures\/dataframe.h>\n#include <inviwo\/dataframe\/datastructures\/datapoint.h>\n#include <inviwo\/dataframe\/util\/dataframeutil.h>\n\n#include <inviwo\/core\/util\/defaultvalues.h>\n#include <inviwo\/core\/util\/safecstr.h>\n#include <inviwo\/core\/datastructures\/buffer\/buffer.h>\n#include <modules\/python3\/pyportutils.h>\n\n#include <fmt\/format.h>\n\nnamespace py = pybind11;\n\nnamespace inviwo {\n\nnamespace {\n\nstruct DataFrameAddColumnReg {\n template <typename T>\n auto operator()(py::class_<DataFrame, std::shared_ptr<DataFrame>>& d) {\n auto classname = Defaultvalues<T>::getName();\n\n d.def(\n fmt::format(\"add{}Column\", classname).c_str(),\n [](DataFrame& d, const std::string& header, const size_t size = 0) {\n return d.addColumn<T>(header, size);\n },\n py::arg(\"header\"), py::arg(\"size\") = 0);\n\n d.def(\n fmt::format(\"add{}Column\", classname).c_str(),\n [](DataFrame& d, std::string header, std::vector<T> data) {\n return d.addColumn(std::move(header), std::move(data));\n },\n py::arg(\"header\"), py::arg(\"data\"));\n }\n};\n\nstruct DataPointReg {\n template <typename T>\n auto operator()(pybind11::module& m) {\n using D = DataPoint<T>;\n auto classname = Defaultvalues<T>::getName() + \"DataPoint\";\n\n py::class_<D, DataPointBase, std::shared_ptr<D>> data(m, classname.c_str());\n data.def_property_readonly(\"data\", &D::getData)\n .def_property_readonly(\"str\", &D::toString)\n .def(\"__repr__\",\n [classname](D& p) { return fmt::format(\"<{}: '{}'>\", classname, p.toString()); });\n }\n};\n\nstruct TemplateColumnReg {\n template <typename T>\n auto operator()(pybind11::module& m) {\n using C = TemplateColumn<T>;\n auto classname = Defaultvalues<T>::getName() + \"Column\";\n\n py::class_<C, Column, std::shared_ptr<C>> col(m, classname.c_str());\n col.def_property_readonly(\"buffer\", [](C& c) { return c.getTypedBuffer(); })\n .def(py::init<std::string_view>())\n .def(\"add\", py::overload_cast<const T&>(&C::add))\n .def(\"add\", py::overload_cast<std::string_view>(&C::add))\n .def(\"append\", [](C& c, C& src) { c.append(src); })\n .def(\"set\", &C::set)\n .def(\n \"get\",\n [](const C& c, size_t i) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i);\n },\n py::arg(\"i\"))\n .def(\n \"get\",\n [](const C& c, size_t i, bool asString) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i, asString);\n },\n py::arg(\"i\"), py::arg(\"asString\"))\n .def(\"__repr__\", [classname](C& c) {\n return fmt::format(\"<{}: '{}', {}, {}>\", classname, c.getHeader(), c.getSize(),\n c.getBuffer()->getDataFormat()->getString());\n });\n }\n};\n\n} \/\/ namespace\n\nvoid exposeDataFrame(pybind11::module& m) {\n py::class_<DataPointBase, std::shared_ptr<DataPointBase>>(m, \"DataPointBase\")\n .def(\"__repr__\",\n [](DataPointBase& p) { return fmt::format(\"<DataPoint: '{}'>\", p.toString()); });\n\n py::enum_<ColumnType>(m, \"ColumnType\")\n .value(\"Index\", ColumnType::Index)\n .value(\"Ordinal\", ColumnType::Ordinal)\n .value(\"Categorical\", ColumnType::Categorical);\n\n py::class_<Column, std::shared_ptr<Column>>(m, \"Column\")\n .def_property(\"header\", &Column::getHeader, &Column::setHeader)\n .def_property_readonly(\"buffer\", [](Column& self) { return self.getBuffer(); })\n .def_property_readonly(\"size\", &Column::getSize)\n .def_property_readonly(\"type\", &Column::getColumnType)\n .def(\n \"setRange\",\n [](Column& c, std::optional<dvec2> range) {\n if (range) {\n c.setRange(*range);\n } else {\n c.unsetRange();\n }\n },\n py::arg(\"range\"))\n .def_property_readonly(\"range\", &Column::getRange)\n .def(\"__repr__\", [](Column& c) {\n return fmt::format(\"<Column: '{}', {}, {}>\", c.getHeader(), c.getSize(),\n c.getBuffer()->getDataFormat()->getString());\n });\n\n using Scalars = std::tuple<float, double, int, glm::i64, size_t, std::uint32_t>;\n util::for_each_type<Scalars>{}(DataPointReg{}, m);\n util::for_each_type<Scalars>{}(TemplateColumnReg{}, m);\n\n py::class_<CategoricalColumn, TemplateColumn<std::uint32_t>,\n std::shared_ptr<CategoricalColumn>>(m, \"CategoricalColumn\")\n .def(py::init<std::string_view>())\n .def_property_readonly(\"categories\", &CategoricalColumn::getCategories,\n py::return_value_policy::copy)\n .def(\"add\", [](CategoricalColumn& c, const std::string& str) { c.add(str); })\n .def(\"append\", [](CategoricalColumn& c, CategoricalColumn& src) { c.append(src); })\n .def(\"set\", [](CategoricalColumn& c, size_t idx, const std::uint32_t& v) { c.set(idx, v); })\n .def(\"set\", py::overload_cast<size_t, const std::string&>(&CategoricalColumn::set))\n .def(\n \"get\",\n [](const CategoricalColumn& c, size_t i, bool asString) {\n if (i >= c.getSize()) throw py::index_error();\n return c.get(i, asString);\n },\n py::arg(\"i\"), py::arg(\"asString\") = true)\n .def(\"__repr__\", [](CategoricalColumn& c) {\n return fmt::format(\"<CategoricalColumn: '{}', {}, {} categories>\", c.getHeader(),\n c.getSize(), c.getCategories().size());\n });\n\n py::class_<IndexColumn, TemplateColumn<std::uint32_t>, std::shared_ptr<IndexColumn>>(\n m, \"IndexColumn\")\n .def(py::init<std::string_view>());\n\n py::class_<DataFrame, std::shared_ptr<DataFrame>> dataframe(m, \"DataFrame\");\n dataframe.def(py::init<std::uint32_t>(), py::arg(\"size\") = 0)\n .def_property_readonly(\"cols\", &DataFrame::getNumberOfColumns)\n .def_property_readonly(\"rows\", &DataFrame::getNumberOfRows)\n .def(\"indexcol\", [](DataFrame& d) { return d.getIndexColumn(); })\n .def(\"column\", [](DataFrame& self, size_t index) { return self.getColumn(index); })\n .def(\"addColumnFromBuffer\", &DataFrame::addColumnFromBuffer)\n .def(\"addCategoricalColumn\",\n py::overload_cast<std::string_view, size_t>(&DataFrame::addCategoricalColumn),\n py::arg(\"header\"), py::arg(\"size\") = 0)\n .def(\"addCategoricalColumn\",\n py::overload_cast<std::string_view, const std::vector<std::string>&>(\n &DataFrame::addCategoricalColumn),\n py::arg(\"header\"), py::arg(\"values\"))\n .def(\"getRow\", &DataFrame::getDataItem, py::arg(\"index\"), py::arg(\"asString\") = false)\n\n .def(\"updateIndex\", [](DataFrame& d) { d.updateIndexBuffer(); })\n\n \/\/ interface for operator[]\n .def(\n \"__getitem__\",\n [](const DataFrame& d, size_t i) {\n if (i >= d.getNumberOfColumns()) throw py::index_error();\n return *(d.begin() + i);\n },\n py::return_value_policy::reference_internal)\n \/\/ sequence protocol operations\n .def(\n \"__iter__\", [](const DataFrame& d) { return py::make_iterator(d.begin(), d.end()); },\n py::keep_alive<0, 1>() \/* Essential: keep object alive while iterator exists *\/)\n\n .def(\"__repr__\", [](const DataFrame& d) {\n std::string str = fmt::format(\"<DataFrame: {} column(s), {} rows\",\n d.getNumberOfColumns(), d.getNumberOfRows());\n size_t i = 0;\n for (auto c : d) {\n ++i;\n str += fmt::format(\"\\n {:>3}: '{}', {}, {}\", i, c->getHeader(), c->getSize(),\n c->getBuffer()->getDataFormat()->getString());\n }\n return str + \">\";\n });\n\n util::for_each_type<Scalars>{}(DataFrameAddColumnReg{}, dataframe);\n\n m.def(\"createDataFrame\", createDataFrame, py::arg(\"exampleRows\"),\n py::arg(\"colheaders\") = std::vector<std::string>{}, py::arg(\"doubleprecision\") = false,\n R\"delim(\nCreate a new DataFrame by guessing the column types from a number of rows.\n\nParameters\n----------\nexampleRows Rows for guessing data type of each column.\ncolHeaders Name of each column. If none are given, \"Column 1\", \"Column 2\", ... is used\ndoubleprecision If true, columns with floating point values will use double for storage\n)delim\")\n .def(\"appendColumns\", dataframe::appendColumns, py::arg(\"left\"), py::arg(\"right\"),\n py::arg(\"ignoreduplicates\") = false, py::arg(\"fillmissingrows\") = false,\n R\"delim(\nCreate a new DataFrame by appending the columns of DataFrame right to DataFrame left\n\nParameters\n----------\nignoreduplicates duplicate columns, i.e. same column header, are ignored if true\nfillmissingrows if true, missing rows in either DataFrame are filled with 0 or\n \"undefined\" (for categorical columns)\n)delim\")\n .def(\"appendRows\", dataframe::appendRows, py::arg(\"top\"), py::arg(\"bottom\"),\n py::arg(\"matchbyname\") = false,\n R\"delim(\nCreate a new DataFrame by appending the rows of DataFrame bottom to DataFrame top\n\nParameters\n----------\nmatchByName if true, column headers are used for matching columns. Otherwise columns\n are matched by order (default)\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::string&>(\n dataframe::innerJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumn\") = \"index\",\n R\"delim(\nCreate a new DataFrame by using an inner join of DataFrame left and DataFrame right.\nThat is only rows with matching keys are kept.\n\nIt is assumed that the entries in the key columns are unique. Otherwise results are undefined.\n\nParameters\n----------\nkeycolumn header of the column used as key for the join operation (default: index column)\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::vector<std::string>&>(\n dataframe::innerJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumns\"),\n R\"delim(\nCreate a new DataFrame by using an inner join of DataFrame left and DataFrame right.\nThat is only rows with matching all keys are kept.\n\nIt is assumed that the entries in the key columns are unique. Otherwise results are undefined.\n\nParameters\n----------\nkeycolumns list of headers of the columns used as key for the join operation\n)delim\")\n .def(\"innerJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::string&>(\n dataframe::leftJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumn\") = \"index\",\n R\"delim(\nCreate a new DataFrame by using an outer left join of DataFrame left and DataFrame right.\nThat is all rows of left are augmented with matching rows from right.\n\nIt is assumed that the entries in the key columns of right are unique. Otherwise results\nare undefined.\n\nParameters\n----------\nkeycolumn header of the column used as key for the join operation (default: index column)\n)delim\")\n .def(\"leftJoin\",\n py::overload_cast<const DataFrame&, const DataFrame&, const std::vector<std::string>&>(\n dataframe::leftJoin),\n py::arg(\"left\"), py::arg(\"right\"), py::arg(\"keycolumns\"),\n R\"delim(\nCreate a new DataFrame by using an outer left join of DataFrame left and DataFrame right.\nThat is all rows of left are augmented with matching rows from right.\n\nIt is assumed that the entries in the key columns of right are unique. Otherwise results\nare undefined.\n\nParameters\n----------\nkeycolumns list of headers of the columns used as key for the join operation\n)delim\");\n\n exposeStandardDataPorts<DataFrame>(m, \"DataFrame\");\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <vector>\n#include <map>\n#include <string>\n#include <memory>\n\n#include <boost\/variant.hpp>\n\nnamespace mstch {\nnamespace internal {\n\ntemplate<class N>\nclass object_t {\n public:\n const N& at(const std::string& name) const {\n cache[name] = (methods.at(name))();\n return cache[name];\n }\n\n bool has(const std::string name) const {\n return methods.count(name);\n }\n\n protected:\n template<class S>\n void register_methods(S* s, std::map<std::string,N(S::*)()> methods) {\n for(auto& item: methods)\n this->methods.insert({item.first, std::bind(item.second, s)});\n }\n\n private:\n std::map<std::string, std::function<N()>> methods;\n mutable std::map<std::string, N> cache;\n};\n\n}\n\nusing renderer = std::function<std::string(const std::string&)>;\n\nclass lambda {\n public:\n lambda(std::function<std::string()> fun):\n fun([fun](const std::string&, renderer){return fun();})\n {\n }\n\n lambda(std::function<std::string(const std::string&, renderer)> fun):\n fun(fun)\n {\n }\n\n std::string operator()(\n const std::string& text = \"\",\n renderer renderer = renderer()) const\n {\n return fun(text, renderer);\n }\n\n private:\n std::function<std::string(const std::string&, renderer)> fun;\n};\n\nusing node = boost::make_recursive_variant<\n boost::blank, std::string, int, bool, lambda,\n std::shared_ptr<internal::object_t<boost::recursive_variant_>>,\n std::map<const std::string, boost::recursive_variant_>,\n std::vector<boost::recursive_variant_>>::type;\nusing object = internal::object_t<node>;\nusing map = std::map<const std::string, node>;\nusing array = std::vector<node>;\n\nstd::string render(\n const std::string& tmplt,\n const node& root,\n const std::map<std::string,std::string>& partials =\n std::map<std::string,std::string>());\n\n}\n<commit_msg>TMP magic to support gcc 4.7<commit_after>#pragma once\n\n#include <vector>\n#include <map>\n#include <string>\n#include <memory>\n\n#include <boost\/variant.hpp>\n\nnamespace mstch {\n\nusing renderer = std::function<std::string(const std::string&)>;\n\nnamespace internal {\n\ntemplate<class N>\nclass object_t {\n public:\n const N& at(const std::string& name) const {\n cache[name] = (methods.at(name))();\n return cache[name];\n }\n\n bool has(const std::string name) const {\n return methods.count(name);\n }\n\n protected:\n template<class S>\n void register_methods(S* s, std::map<std::string,N(S::*)()> methods) {\n for(auto& item: methods)\n this->methods.insert({item.first, std::bind(item.second, s)});\n }\n\n private:\n std::map<std::string, std::function<N()>> methods;\n mutable std::map<std::string, N> cache;\n};\n\ntemplate <typename T>\nclass is_fun {\n private:\n using not_fun = char;\n using fun_without_args = char[2];\n using fun_with_args = char[3];\n template <typename U, U> struct really_has;\n template <typename C> static fun_without_args& test(\n really_has<std::string(C::*)() const, &C::operator()>*);\n template <typename C> static fun_with_args& test(\n really_has<std::string(C::*)(const std::string&,renderer) const,\n &C::operator()>*);\n template <typename> static not_fun& test(...);\n\n public:\n static bool const no_args = sizeof(test<T>(0)) == sizeof(fun_without_args);\n static bool const has_args = sizeof(test<T>(0)) == sizeof(fun_with_args);\n};\n\n}\n\nclass lambda {\n public:\n template<class F>\n lambda(F f, typename std::enable_if<internal::is_fun<F>::no_args>::type* =0):\n fun([f](const std::string&,renderer){return f();})\n {\n }\n\n template<class F>\n lambda(F f, typename std::enable_if<internal::is_fun<F>::has_args>::type* =0):\n fun(f)\n {\n }\n\n std::string operator()(\n const std::string& text = \"\",\n renderer renderer = renderer()) const\n {\n return fun(text, renderer);\n }\n\n private:\n std::function<std::string(const std::string&, renderer)> fun;\n};\n\nusing node = boost::make_recursive_variant<\n boost::blank, std::string, int, bool, lambda,\n std::shared_ptr<internal::object_t<boost::recursive_variant_>>,\n std::map<const std::string, boost::recursive_variant_>,\n std::vector<boost::recursive_variant_>>::type;\nusing object = internal::object_t<node>;\nusing map = std::map<const std::string, node>;\nusing array = std::vector<node>;\n\nstd::string render(\n const std::string& tmplt,\n const node& root,\n const std::map<std::string,std::string>& partials =\n std::map<std::string,std::string>());\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"interpreterCore\/managers\/saveConvertionManager.h\"\n\nusing namespace interpreterCore;\nusing namespace qReal;\n\nQString SaveConvertionManager::editor()\n{\n\treturn \"RobotsMetamodel\";\n}\n\nQList<ProjectConverter> SaveConvertionManager::converters()\n{\n\treturn { before300Alpha1Converter()\n\t\t, from300Alpha4to300Alpha5Converter()\n\t\t, from300Beta2to300rc1Converter()\n\t\t, from300to301Converter()\n\t};\n}\n\nProjectConverter SaveConvertionManager::before300Alpha1Converter()\n{\n\treturn ProjectConverter(editor(), Version(), Version::fromString(\"3.0.0-a1\")\n\t\t\t, [=](const GraphicalModelAssistInterface &graphicalApi, LogicalModelAssistInterface &logicalApi)\n\t{\n\t\tQ_UNUSED(graphicalApi)\n\t\tQ_UNUSED(logicalApi)\n\t\treturn ProjectConverter::VersionTooOld;\n\t});\n}\n\nProjectConverter SaveConvertionManager::from300Alpha4to300Alpha5Converter()\n{\n\treturn constructConverter(\"3.0.0-a4\", \"3.0.0-a5\"\n\t\t\t, {\n\t\t\t\treplace({\n\t\t\t\t\t\t{\"JA1\", \"A1\"}\n\t\t\t\t\t\t, {\"JA2\", \"A2\"}\n\t\t\t\t\t\t, {\"JA3\", \"A3\"}\n\t\t\t\t\t\t, {\"JA4\", \"A4\"}\n\t\t\t\t\t\t, {\"JA5\", \"A5\"}\n\t\t\t\t\t\t, {\"JA6\", \"A6\"}\n\n\t\t\t\t\t\t, {\"JD1\", \"D1\"}\n\t\t\t\t\t\t, {\"JD2\", \"D2\"}\n\n\t\t\t\t\t\t, {\"JF1\", \"F1\"}\n\n\t\t\t\t\t\t, {\"JM1\", \"M1\"}\n\t\t\t\t\t\t, {\"JM2\", \"M2\"}\n\t\t\t\t\t\t, {\"JM3\", \"M3\"}\n\t\t\t\t\t\t, {\"JM4\", \"M4\"}\n\n\t\t\t\t\t\t, {\"JB1\", \"B1\"}\n\t\t\t\t\t\t, {\"JB2\", \"B2\"}\n\t\t\t\t\t\t, {\"JB3\", \"B3\"}\n\t\t\t\t\t\t, {\"JB4\", \"B4\"}\n\n\t\t\t\t\t\t, {\"JE1\", \"E1\"}\n\t\t\t\t\t\t, {\"JE2\", \"E2\"}\n\t\t\t\t\t\t, {\"JE3\", \"E3\"}\n\t\t\t\t\t\t, {\"JE4\", \"E4\"}\n\n\t\t\t\t\t\t, {\"JC1\", \"C1\"}\n\t\t\t\t\t\t, {\"JC2\", \"C2\"}\n\t\t\t\t\t\t, {\"JC3\", \"C3\"}\n\n\t\t\t\t\t\t, {\"sensor1\", \"sensorA1\"}\n\t\t\t\t\t\t, {\"sensor2\", \"sensorA2\"}\n\t\t\t\t\t\t, {\"sensor3\", \"sensorA3\"}\n\t\t\t\t\t\t, {\"sensor4\", \"sensorA4\"}\n\t\t\t\t\t\t, {\"sensor5\", \"sensorA5\"}\n\t\t\t\t\t\t, {\"sensor6\", \"sensorA6\"}\n\n\t\t\t\t\t\t, {\"digitSensor1\", \"sensorD1\"}\n\t\t\t\t\t\t, {\"digitSensor2\", \"sensorD2\"}\n\t\t\t\t})\n\t\t\t}\n\t\t\t, [] (const Id &block) { return block.element().startsWith(\"Trik\"); }\n\t\t\t);\n\n}\n\nProjectConverter SaveConvertionManager::from300Beta2to300rc1Converter()\n{\n\treturn constructConverter(\"3.0.0-b2\", \"3.0.0-rc1\"\n\t\t\t, { quote(\"TrikSay\", \"Text\"), quote(\"PrintText\", \"PrintText\") }\n\t\t\t);\n}\n\nqReal::ProjectConverter SaveConvertionManager::from300to301Converter()\n{\n\treturn constructConverter(\"3.0.0\", \"3.0.1\"\n\t\t\t, {\n\t\t\t\treplace({\n\t\t\t\t\t\t{\"enterButton\", \"buttonEnter\"}\n\t\t\t\t\t\t, {\"escapeButton\", \"buttonEscape\"}\n\t\t\t\t\t\t, {\"leftButton\", \"buttonLeft\"}\n\t\t\t\t\t\t, {\"rightButton\", \"buttonRight\"}\n\t\t\t\t\t\t, {\"backButton\", \"buttonBack\"}\n\t\t\t\t\t\t, {\"downButton\", \"buttonDown\"}\n\t\t\t\t\t\t, {\"enterButton\", \"buttonEnter\"}\n\t\t\t\t\t\t, {\"upButton\", \"buttonUp\"}\n\t\t\t\t\t\t, {\"powerButton\", \"buttonEsc\"}\n\t\t\t\t })\n\t\t\t\t, [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\t\t\t\t\tif (block.element().startsWith(\"Trik\")) {\n\t\t\t\t\t\t\treturn replace({{\"buttonEscape\", \"buttonEsc\"}})(block, logicalApi);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t, deleteBlocks({\"Ev3WaitForUp\"\n\t\t\t\t\t\t, \"Ev3WaitForEnter\"\n\t\t\t\t\t\t, \"Ev3WaitForDown\"\n\t\t\t\t\t\t, \"Ev3WaitForRight\"\n\t\t\t\t\t\t, \"Ev3WaitForLeft\"\n\t\t\t\t\t\t, \"Ev3WaitForBack\"\n\n\t\t\t\t\t\t, \"NxtWaitForEnter\"\n\t\t\t\t\t\t, \"NxtWaitForEscape\"\n\t\t\t\t\t\t, \"NxtWaitForLeft\"\n\t\t\t\t\t\t, \"NxtWaitForRight\"\n\n\t\t\t\t\t\t, \"TrikWaitForEnter\"\n\t\t\t\t\t\t, \"TrikWaitForLeft\"\n\t\t\t\t\t\t, \"TrikWaitForRight\"\n\t\t\t\t\t\t, \"TrikWaitForDown\"\n\t\t\t\t\t\t, \"TrikWaitForUp\"\n\t\t\t\t\t\t, \"TrikWaitForPower\"\n\t\t\t\t\t\t})\n\t\t\t}\n\t\t\t);\n}\n\nqReal::ProjectConverter SaveConvertionManager::from301to302Converter()\n{\n\treturn constructConverter(\"3.0.1\", \"3.0.2\", { quote(\"TrikSystem\", \"Command\") } );\n}\n\nbool SaveConvertionManager::isRobotsDiagram(const Id &diagram)\n{\n\tconst QStringList robotsDiagrams = { \"RobotsDiagram\", \"SubprogramDiagram\" };\n\treturn diagram.editor() == editor() && robotsDiagrams.contains(diagram.diagram());\n}\n\nIdList SaveConvertionManager::elementsOfRobotsDiagrams(const LogicalModelAssistInterface &logicalApi)\n{\n\tIdList result;\n\tfor (const Id &diagramId : logicalApi.children(Id::rootId())) {\n\t\tif (isRobotsDiagram(diagramId)) {\n\t\t\tresult += logicalApi.children(diagramId);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nqReal::ProjectConverter SaveConvertionManager::constructConverter(const QString &oldVersion\n\t\t, const QString &newVersion\n\t\t, const QList<std::function<bool(const Id &, LogicalModelAssistInterface &)>> &filters\n\t\t, const std::function<bool(const qReal::Id &)> &condition\n\t\t)\n{\n\treturn ProjectConverter(editor(), Version::fromString(oldVersion), Version::fromString(newVersion)\n\t\t\t, [=](const GraphicalModelAssistInterface &graphicalApi, LogicalModelAssistInterface &logicalApi)\n\t{\n\t\tQ_UNUSED(graphicalApi);\n\n\t\tbool modificationsMade = false;\n\n\t\tfor (const Id &graphicalBlock : elementsOfRobotsDiagrams(logicalApi)) {\n\t\t\tconst Id block = graphicalApi.logicalId(graphicalBlock);\n\n\t\t\tif (!condition(block)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const auto &filter : filters) {\n\t\t\t\tmodificationsMade |= filter(block, logicalApi);\n\t\t\t}\n\t\t}\n\n\t\treturn modificationsMade ? ProjectConverter::Success : ProjectConverter::NoModificationsMade;\n\t});\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)> SaveConvertionManager::replace(\n\t\tconst QMap<QString, QString> &replacementRules)\n{\n\treturn [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\tbool modificationsMade = false;\n\t\tQMapIterator<QString, QVariant> iterator = logicalApi.logicalRepoApi().propertiesIterator(block);\n\t\tfor (iterator.next(); iterator.hasNext(); iterator.next()) {\n\t\t\tconst QString name = iterator.key();\n\t\t\tQString value = iterator.value().toString();\n\t\t\tbool replacementOccured = false;\n\t\t\tfor (const QString &toReplace : replacementRules.keys()) {\n\t\t\t\tif (value.contains(toReplace)) {\n\t\t\t\t\treplacementOccured = true;\n\t\t\t\t\tmodificationsMade = true;\n\n\t\t\t\t\tvalue.replace(toReplace, replacementRules[toReplace]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (replacementOccured) {\n\t\t\t\tlogicalApi.setPropertyByRoleName(block, value, name);\n\t\t\t}\n\t\t}\n\n\t\t return modificationsMade;\n\t};\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)>\n\t\tSaveConvertionManager::deleteBlocks(const QStringList &blocks)\n{\n\treturn [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\tif (blocks.contains(block.element())) {\n\t\t\tlogicalApi.removeElement(block);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)> SaveConvertionManager::quote(\n\t\tconst QString &blockType, const QString &property)\n{\n\treturn [blockType, property] (const qReal::Id &block, qReal::LogicalModelAssistInterface &logicalApi) {\n\t\tif (block.element() == blockType) {\n\t\t\tconst QString oldValue = logicalApi.logicalRepoApi().property(block, property).toString();\n\t\t\tif (!oldValue.startsWith(\"\\\"\")) {\n\t\t\t\tlogicalApi.mutableLogicalRepoApi().setProperty(block, property, \"\\\"\" + oldValue + \"\\\"\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t};\n}\n<commit_msg>added save converter to a list of converters<commit_after>#include \"interpreterCore\/managers\/saveConvertionManager.h\"\n\nusing namespace interpreterCore;\nusing namespace qReal;\n\nQString SaveConvertionManager::editor()\n{\n\treturn \"RobotsMetamodel\";\n}\n\nQList<ProjectConverter> SaveConvertionManager::converters()\n{\n\treturn { before300Alpha1Converter()\n\t\t, from300Alpha4to300Alpha5Converter()\n\t\t, from300Beta2to300rc1Converter()\n\t\t, from300to301Converter()\n\t\t, from301to302Converter()\n\t};\n}\n\nProjectConverter SaveConvertionManager::before300Alpha1Converter()\n{\n\treturn ProjectConverter(editor(), Version(), Version::fromString(\"3.0.0-a1\")\n\t\t\t, [=](const GraphicalModelAssistInterface &graphicalApi, LogicalModelAssistInterface &logicalApi)\n\t{\n\t\tQ_UNUSED(graphicalApi)\n\t\tQ_UNUSED(logicalApi)\n\t\treturn ProjectConverter::VersionTooOld;\n\t});\n}\n\nProjectConverter SaveConvertionManager::from300Alpha4to300Alpha5Converter()\n{\n\treturn constructConverter(\"3.0.0-a4\", \"3.0.0-a5\"\n\t\t\t, {\n\t\t\t\treplace({\n\t\t\t\t\t\t{\"JA1\", \"A1\"}\n\t\t\t\t\t\t, {\"JA2\", \"A2\"}\n\t\t\t\t\t\t, {\"JA3\", \"A3\"}\n\t\t\t\t\t\t, {\"JA4\", \"A4\"}\n\t\t\t\t\t\t, {\"JA5\", \"A5\"}\n\t\t\t\t\t\t, {\"JA6\", \"A6\"}\n\n\t\t\t\t\t\t, {\"JD1\", \"D1\"}\n\t\t\t\t\t\t, {\"JD2\", \"D2\"}\n\n\t\t\t\t\t\t, {\"JF1\", \"F1\"}\n\n\t\t\t\t\t\t, {\"JM1\", \"M1\"}\n\t\t\t\t\t\t, {\"JM2\", \"M2\"}\n\t\t\t\t\t\t, {\"JM3\", \"M3\"}\n\t\t\t\t\t\t, {\"JM4\", \"M4\"}\n\n\t\t\t\t\t\t, {\"JB1\", \"B1\"}\n\t\t\t\t\t\t, {\"JB2\", \"B2\"}\n\t\t\t\t\t\t, {\"JB3\", \"B3\"}\n\t\t\t\t\t\t, {\"JB4\", \"B4\"}\n\n\t\t\t\t\t\t, {\"JE1\", \"E1\"}\n\t\t\t\t\t\t, {\"JE2\", \"E2\"}\n\t\t\t\t\t\t, {\"JE3\", \"E3\"}\n\t\t\t\t\t\t, {\"JE4\", \"E4\"}\n\n\t\t\t\t\t\t, {\"JC1\", \"C1\"}\n\t\t\t\t\t\t, {\"JC2\", \"C2\"}\n\t\t\t\t\t\t, {\"JC3\", \"C3\"}\n\n\t\t\t\t\t\t, {\"sensor1\", \"sensorA1\"}\n\t\t\t\t\t\t, {\"sensor2\", \"sensorA2\"}\n\t\t\t\t\t\t, {\"sensor3\", \"sensorA3\"}\n\t\t\t\t\t\t, {\"sensor4\", \"sensorA4\"}\n\t\t\t\t\t\t, {\"sensor5\", \"sensorA5\"}\n\t\t\t\t\t\t, {\"sensor6\", \"sensorA6\"}\n\n\t\t\t\t\t\t, {\"digitSensor1\", \"sensorD1\"}\n\t\t\t\t\t\t, {\"digitSensor2\", \"sensorD2\"}\n\t\t\t\t})\n\t\t\t}\n\t\t\t, [] (const Id &block) { return block.element().startsWith(\"Trik\"); }\n\t\t\t);\n\n}\n\nProjectConverter SaveConvertionManager::from300Beta2to300rc1Converter()\n{\n\treturn constructConverter(\"3.0.0-b2\", \"3.0.0-rc1\"\n\t\t\t, { quote(\"TrikSay\", \"Text\"), quote(\"PrintText\", \"PrintText\") }\n\t\t\t);\n}\n\nqReal::ProjectConverter SaveConvertionManager::from300to301Converter()\n{\n\treturn constructConverter(\"3.0.0\", \"3.0.1\"\n\t\t\t, {\n\t\t\t\treplace({\n\t\t\t\t\t\t{\"enterButton\", \"buttonEnter\"}\n\t\t\t\t\t\t, {\"escapeButton\", \"buttonEscape\"}\n\t\t\t\t\t\t, {\"leftButton\", \"buttonLeft\"}\n\t\t\t\t\t\t, {\"rightButton\", \"buttonRight\"}\n\t\t\t\t\t\t, {\"backButton\", \"buttonBack\"}\n\t\t\t\t\t\t, {\"downButton\", \"buttonDown\"}\n\t\t\t\t\t\t, {\"enterButton\", \"buttonEnter\"}\n\t\t\t\t\t\t, {\"upButton\", \"buttonUp\"}\n\t\t\t\t\t\t, {\"powerButton\", \"buttonEsc\"}\n\t\t\t\t })\n\t\t\t\t, [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\t\t\t\t\tif (block.element().startsWith(\"Trik\")) {\n\t\t\t\t\t\t\treturn replace({{\"buttonEscape\", \"buttonEsc\"}})(block, logicalApi);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t, deleteBlocks({\"Ev3WaitForUp\"\n\t\t\t\t\t\t, \"Ev3WaitForEnter\"\n\t\t\t\t\t\t, \"Ev3WaitForDown\"\n\t\t\t\t\t\t, \"Ev3WaitForRight\"\n\t\t\t\t\t\t, \"Ev3WaitForLeft\"\n\t\t\t\t\t\t, \"Ev3WaitForBack\"\n\n\t\t\t\t\t\t, \"NxtWaitForEnter\"\n\t\t\t\t\t\t, \"NxtWaitForEscape\"\n\t\t\t\t\t\t, \"NxtWaitForLeft\"\n\t\t\t\t\t\t, \"NxtWaitForRight\"\n\n\t\t\t\t\t\t, \"TrikWaitForEnter\"\n\t\t\t\t\t\t, \"TrikWaitForLeft\"\n\t\t\t\t\t\t, \"TrikWaitForRight\"\n\t\t\t\t\t\t, \"TrikWaitForDown\"\n\t\t\t\t\t\t, \"TrikWaitForUp\"\n\t\t\t\t\t\t, \"TrikWaitForPower\"\n\t\t\t\t\t\t})\n\t\t\t}\n\t\t\t);\n}\n\nqReal::ProjectConverter SaveConvertionManager::from301to302Converter()\n{\n\treturn constructConverter(\"3.0.1\", \"3.0.2\", { quote(\"TrikSystem\", \"Command\") } );\n}\n\nbool SaveConvertionManager::isRobotsDiagram(const Id &diagram)\n{\n\tconst QStringList robotsDiagrams = { \"RobotsDiagram\", \"SubprogramDiagram\" };\n\treturn diagram.editor() == editor() && robotsDiagrams.contains(diagram.diagram());\n}\n\nIdList SaveConvertionManager::elementsOfRobotsDiagrams(const LogicalModelAssistInterface &logicalApi)\n{\n\tIdList result;\n\tfor (const Id &diagramId : logicalApi.children(Id::rootId())) {\n\t\tif (isRobotsDiagram(diagramId)) {\n\t\t\tresult += logicalApi.children(diagramId);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nqReal::ProjectConverter SaveConvertionManager::constructConverter(const QString &oldVersion\n\t\t, const QString &newVersion\n\t\t, const QList<std::function<bool(const Id &, LogicalModelAssistInterface &)>> &filters\n\t\t, const std::function<bool(const qReal::Id &)> &condition\n\t\t)\n{\n\treturn ProjectConverter(editor(), Version::fromString(oldVersion), Version::fromString(newVersion)\n\t\t\t, [=](const GraphicalModelAssistInterface &graphicalApi, LogicalModelAssistInterface &logicalApi)\n\t{\n\t\tQ_UNUSED(graphicalApi);\n\n\t\tbool modificationsMade = false;\n\n\t\tfor (const Id &graphicalBlock : elementsOfRobotsDiagrams(logicalApi)) {\n\t\t\tconst Id block = graphicalApi.logicalId(graphicalBlock);\n\n\t\t\tif (!condition(block)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const auto &filter : filters) {\n\t\t\t\tmodificationsMade |= filter(block, logicalApi);\n\t\t\t}\n\t\t}\n\n\t\treturn modificationsMade ? ProjectConverter::Success : ProjectConverter::NoModificationsMade;\n\t});\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)> SaveConvertionManager::replace(\n\t\tconst QMap<QString, QString> &replacementRules)\n{\n\treturn [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\tbool modificationsMade = false;\n\t\tQMapIterator<QString, QVariant> iterator = logicalApi.logicalRepoApi().propertiesIterator(block);\n\t\tfor (iterator.next(); iterator.hasNext(); iterator.next()) {\n\t\t\tconst QString name = iterator.key();\n\t\t\tQString value = iterator.value().toString();\n\t\t\tbool replacementOccured = false;\n\t\t\tfor (const QString &toReplace : replacementRules.keys()) {\n\t\t\t\tif (value.contains(toReplace)) {\n\t\t\t\t\treplacementOccured = true;\n\t\t\t\t\tmodificationsMade = true;\n\n\t\t\t\t\tvalue.replace(toReplace, replacementRules[toReplace]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (replacementOccured) {\n\t\t\t\tlogicalApi.setPropertyByRoleName(block, value, name);\n\t\t\t}\n\t\t}\n\n\t\t return modificationsMade;\n\t};\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)>\n\t\tSaveConvertionManager::deleteBlocks(const QStringList &blocks)\n{\n\treturn [=] (const Id &block, LogicalModelAssistInterface &logicalApi) {\n\t\tif (blocks.contains(block.element())) {\n\t\t\tlogicalApi.removeElement(block);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n}\n\nstd::function<bool(const qReal::Id &, qReal::LogicalModelAssistInterface &)> SaveConvertionManager::quote(\n\t\tconst QString &blockType, const QString &property)\n{\n\treturn [blockType, property] (const qReal::Id &block, qReal::LogicalModelAssistInterface &logicalApi) {\n\t\tif (block.element() == blockType) {\n\t\t\tconst QString oldValue = logicalApi.logicalRepoApi().property(block, property).toString();\n\t\t\tif (!oldValue.startsWith(\"\\\"\")) {\n\t\t\t\tlogicalApi.mutableLogicalRepoApi().setProperty(block, property, \"\\\"\" + oldValue + \"\\\"\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n#include <event2\/event.h>\n#include <event2\/bufferevent.h>\n#include <event2\/thread.h>\n\n#include <boost\/thread.hpp>\n\n#include <qi\/log.hpp>\n#include <qi\/application.hpp>\n\n#include <qi\/eventloop.hpp>\n\n#include \"eventloop_p.hpp\"\n\nnamespace qi {\n\n EventLoopPrivate::EventLoopPrivate()\n : _destroyMe(false)\n , _running(false)\n , _threaded(false)\n {\n static bool libevent_init = false;\n\n\n #ifdef _WIN32\n \/\/ libevent does not call WSAStartup\n WSADATA WSAData;\n \/\/ TODO: handle return code\n ::WSAStartup(MAKEWORD(1, 0), &WSAData);\n #endif\n\n if (!libevent_init)\n {\n #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED\n evthread_use_windows_threads();\n #endif\n #ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED\n evthread_use_pthreads();\n #endif\n libevent_init = !libevent_init;\n }\n\n if (!(_base = event_base_new()))\n return;\n }\n\n\n void EventLoopPrivate::start()\n {\n if (_running || _threaded)\n return;\n _threaded = true;\n _thd = boost::thread(&EventLoopPrivate::run, this);\n while (!_running)\n qi::os::msleep(0);\n }\n\n EventLoopPrivate::~EventLoopPrivate()\n {\n if (_running && boost::this_thread::get_id() != _id)\n qiLogError(\"Destroying EventLoopPrivate from itself while running\");\n stop();\n join();\n\n #ifdef _WIN32\n \/\/ TODO handle return code\n ::WSACleanup();\n #endif\n }\n\n void EventLoopPrivate::destroy(bool join)\n {\n bool needJoin;\n bool needDelete;\n {\n boost::recursive_mutex::scoped_lock sl(_mutex);\n needJoin = join && _running && (boost::this_thread::get_id() != _id);\n needDelete = needJoin || !_running;\n _destroyMe = !needDelete;\n }\n stop(); \/\/ Deadlock if called within the scoped_lock\n if (needJoin)\n this->join();\n\n if (needDelete)\n delete this;\n }\n\n void EventLoopPrivate::run()\n {\n qiLogDebug(\"qi.EventLoop\") << this << \"run starting\";\n _running = true;\n _id = boost::this_thread::get_id();\n \/\/ stop will set _base to 0 to delect usage attempts after stop\n \/\/ so use a local copy.\n event_base* base = _base;\n \/\/ libevent needs a dummy op to perform otherwise dispatch exits immediately\n struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n \/\/bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n\n event_base_dispatch(base);\n qiLogDebug(\"qi.EventLoop\") << this << \"run ending\";\n bufferevent_free(bev);\n event_base_free(base);\n _base = 0;\n {\n boost::recursive_mutex::scoped_lock sl(_mutex);\n _running = false;\n if (_destroyMe)\n delete this;\n }\n }\n\n bool EventLoopPrivate::isInEventLoopThread()\n {\n return boost::this_thread::get_id() == _id;\n }\n\n void EventLoopPrivate::stop()\n {\n qiLogDebug(\"qi.EventLoop\") << this << \"stopping\";\n event_base* base = 0;\n { \/\/ Ensure no multipe calls are made.\n boost::recursive_mutex::scoped_lock sl(_mutex);\n if (_base && _running)\n {\n base = _base;\n _base = 0;\n }\n }\n if (base)\n if (event_base_loopexit(base, NULL) != 0)\n qiLogError(\"networkThread\") << \"Can't stop the EventLoopPrivate\";\n\n }\n\n void EventLoopPrivate::join()\n {\n if (_base)\n qiLogError(\"EventLoop\") << \"join() called before stop()\";\n if (boost::this_thread::get_id() == _id)\n return;\n if (_threaded)\n _thd.join();\n else\n while (_running)\n qi::os::msleep(0);\n }\n\n static void async_call(evutil_socket_t,\n short what,\n void *context)\n {\n EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;\n if (!handle->_p->cancelled)\n handle->_p->callback();\n event_del(handle->_p->ev);\n event_free(handle->_p->ev);\n delete handle;\n }\n\n static void fduse_call(evutil_socket_t socket,\n short what,\n void *context)\n {\n EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;\n if (!handle->_p->cancelled) {\n if (what & EV_READ)\n handle->_p->fdcallback(socket, EventLoop::FileOperation_Read);\n else if (what & EV_WRITE)\n handle->_p->fdcallback(socket, EventLoop::FileOperation_Write);\n \/\/\/ If this event is persistant and was not cancelled, do not delete.\n if (handle->_p->persistant)\n return;\n }\n event_del(handle->_p->ev);\n event_free(handle->_p->ev);\n delete handle;\n }\n\n EventLoop::AsyncCallHandle EventLoopPrivate::asyncCall(uint64_t usDelay, boost::function<void ()> cb)\n {\n EventLoop::AsyncCallHandle res;\n if (!_base) {\n qiLogDebug(\"eventloop\") << \"Discarding asyncCall after loop destruction.\";\n return res;\n }\n struct timeval period;\n period.tv_sec = static_cast<long>(usDelay \/ 1000000ULL);\n period.tv_usec = usDelay % 1000000ULL;\n struct event *ev = event_new(_base, -1, 0, async_call,\n new EventLoop::AsyncCallHandle(res));\n \/\/ Order is important.\n res._p->ev = ev;\n res._p->cancelled = false;\n std::swap(res._p->callback,cb);\n event_add(ev, &period);\n return res;\n }\n\n EventLoop::AsyncCallHandle EventLoopPrivate::notifyFd(evutil_socket_t fd, EventLoop::NotifyFdCallbackFunction cb, short evflags, bool persistant)\n {\n EventLoop::AsyncCallHandle res;\n if (!_base) {\n qiLogDebug(\"eventloop\") << \"Discarding notifyChange after loop destruction.\";\n return res;\n }\n if (persistant)\n evflags |= EV_PERSIST;\n struct event *ev = event_new(_base,\n fd,\n evflags,\n fduse_call,\n new EventLoop::AsyncCallHandle(res));\n res._p->ev = ev;\n res._p->cancelled = false;\n res._p->persistant = persistant;\n std::swap(res._p->fdcallback,cb);\n event_add(ev, NULL);\n return res;\n }\n\n \/\/ Basic pimpl bouncers.\n EventLoop::AsyncCallHandle::AsyncCallHandle()\n {\n _p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());\n }\n\n EventLoop::AsyncCallHandle::~AsyncCallHandle()\n {\n }\n\n void EventLoop::AsyncCallHandle::cancel()\n {\n _p->cancel();\n }\n\n EventLoop::EventLoop()\n {\n _p = new EventLoopPrivate();\n }\n\n EventLoop::~EventLoop()\n {\n _p->destroy(false);\n _p = 0;\n }\n\n bool EventLoop::isInEventLoopThread()\n {\n return _p->isInEventLoopThread();\n }\n\n void EventLoop::join()\n {\n _p->join();\n }\n\n void EventLoop::start()\n {\n _p->start();\n }\n\n void EventLoop::stop()\n {\n _p->stop();\n }\n\n void EventLoop::run()\n {\n _p->run();\n }\n\n void *EventLoop::nativeHandle() {\n return static_cast<void *>(_p->getEventBase());\n }\n\n EventLoop::AsyncCallHandle\n EventLoop::asyncCall(\n uint64_t usDelay,\n boost::function<void ()> callback)\n {\n return _p->asyncCall(usDelay, callback);\n }\n\n EventLoop::AsyncCallHandle\n EventLoop::notifyFd(int fileDescriptor,\n NotifyFdCallbackFunction callback,\n FileOperation fdUsage)\n {\n switch (fdUsage)\n {\n case FileOperation_Read:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ, true);\n case FileOperation_Write:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_WRITE, true);\n case FileOperation_ReadOrWrite:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ|EV_WRITE, true);\n }\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ|EV_WRITE, true);\n }\n\n static void eventloop_stop(EventLoop* ctx)\n {\n ctx->stop();\n ctx->join();\n delete ctx;\n }\n\n static EventLoop* _get(EventLoop* &ctx)\n {\n if (!ctx)\n {\n if (! qi::Application::initialized())\n {\n qiLogError(\"EventLoop\") << \"EventLoop created before qi::Application()\";\n }\n ctx = new EventLoop();\n ctx->start();\n Application::atExit(boost::bind(&eventloop_stop, ctx));\n }\n return ctx;\n }\n\n static EventLoop* _netEventLoop = 0;\n static EventLoop* _objEventLoop = 0;\n EventLoop* getDefaultNetworkEventLoop()\n {\n return _get(_netEventLoop);\n }\n\n EventLoop* getDefaultObjectEventLoop()\n {\n return _get(_objEventLoop);\n }\n\n}\n<commit_msg>Change log for event loop creation before qi::application initialization<commit_after>\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n#include <event2\/event.h>\n#include <event2\/bufferevent.h>\n#include <event2\/thread.h>\n\n#include <boost\/thread.hpp>\n\n#include <qi\/log.hpp>\n#include <qi\/application.hpp>\n\n#include <qi\/eventloop.hpp>\n\n#include \"eventloop_p.hpp\"\n\nnamespace qi {\n\n EventLoopPrivate::EventLoopPrivate()\n : _destroyMe(false)\n , _running(false)\n , _threaded(false)\n {\n static bool libevent_init = false;\n\n\n #ifdef _WIN32\n \/\/ libevent does not call WSAStartup\n WSADATA WSAData;\n \/\/ TODO: handle return code\n ::WSAStartup(MAKEWORD(1, 0), &WSAData);\n #endif\n\n if (!libevent_init)\n {\n #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED\n evthread_use_windows_threads();\n #endif\n #ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED\n evthread_use_pthreads();\n #endif\n libevent_init = !libevent_init;\n }\n\n if (!(_base = event_base_new()))\n return;\n }\n\n\n void EventLoopPrivate::start()\n {\n if (_running || _threaded)\n return;\n _threaded = true;\n _thd = boost::thread(&EventLoopPrivate::run, this);\n while (!_running)\n qi::os::msleep(0);\n }\n\n EventLoopPrivate::~EventLoopPrivate()\n {\n if (_running && boost::this_thread::get_id() != _id)\n qiLogError(\"Destroying EventLoopPrivate from itself while running\");\n stop();\n join();\n\n #ifdef _WIN32\n \/\/ TODO handle return code\n ::WSACleanup();\n #endif\n }\n\n void EventLoopPrivate::destroy(bool join)\n {\n bool needJoin;\n bool needDelete;\n {\n boost::recursive_mutex::scoped_lock sl(_mutex);\n needJoin = join && _running && (boost::this_thread::get_id() != _id);\n needDelete = needJoin || !_running;\n _destroyMe = !needDelete;\n }\n stop(); \/\/ Deadlock if called within the scoped_lock\n if (needJoin)\n this->join();\n\n if (needDelete)\n delete this;\n }\n\n void EventLoopPrivate::run()\n {\n qiLogDebug(\"qi.EventLoop\") << this << \"run starting\";\n _running = true;\n _id = boost::this_thread::get_id();\n \/\/ stop will set _base to 0 to delect usage attempts after stop\n \/\/ so use a local copy.\n event_base* base = _base;\n \/\/ libevent needs a dummy op to perform otherwise dispatch exits immediately\n struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);\n \/\/bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);\n bufferevent_enable(bev, EV_READ|EV_WRITE);\n\n event_base_dispatch(base);\n qiLogDebug(\"qi.EventLoop\") << this << \"run ending\";\n bufferevent_free(bev);\n event_base_free(base);\n _base = 0;\n {\n boost::recursive_mutex::scoped_lock sl(_mutex);\n _running = false;\n if (_destroyMe)\n delete this;\n }\n }\n\n bool EventLoopPrivate::isInEventLoopThread()\n {\n return boost::this_thread::get_id() == _id;\n }\n\n void EventLoopPrivate::stop()\n {\n qiLogDebug(\"qi.EventLoop\") << this << \"stopping\";\n event_base* base = 0;\n { \/\/ Ensure no multipe calls are made.\n boost::recursive_mutex::scoped_lock sl(_mutex);\n if (_base && _running)\n {\n base = _base;\n _base = 0;\n }\n }\n if (base)\n if (event_base_loopexit(base, NULL) != 0)\n qiLogError(\"networkThread\") << \"Can't stop the EventLoopPrivate\";\n\n }\n\n void EventLoopPrivate::join()\n {\n if (_base)\n qiLogError(\"EventLoop\") << \"join() called before stop()\";\n if (boost::this_thread::get_id() == _id)\n return;\n if (_threaded)\n _thd.join();\n else\n while (_running)\n qi::os::msleep(0);\n }\n\n static void async_call(evutil_socket_t,\n short what,\n void *context)\n {\n EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;\n if (!handle->_p->cancelled)\n handle->_p->callback();\n event_del(handle->_p->ev);\n event_free(handle->_p->ev);\n delete handle;\n }\n\n static void fduse_call(evutil_socket_t socket,\n short what,\n void *context)\n {\n EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;\n if (!handle->_p->cancelled) {\n if (what & EV_READ)\n handle->_p->fdcallback(socket, EventLoop::FileOperation_Read);\n else if (what & EV_WRITE)\n handle->_p->fdcallback(socket, EventLoop::FileOperation_Write);\n \/\/\/ If this event is persistant and was not cancelled, do not delete.\n if (handle->_p->persistant)\n return;\n }\n event_del(handle->_p->ev);\n event_free(handle->_p->ev);\n delete handle;\n }\n\n EventLoop::AsyncCallHandle EventLoopPrivate::asyncCall(uint64_t usDelay, boost::function<void ()> cb)\n {\n EventLoop::AsyncCallHandle res;\n if (!_base) {\n qiLogDebug(\"eventloop\") << \"Discarding asyncCall after loop destruction.\";\n return res;\n }\n struct timeval period;\n period.tv_sec = static_cast<long>(usDelay \/ 1000000ULL);\n period.tv_usec = usDelay % 1000000ULL;\n struct event *ev = event_new(_base, -1, 0, async_call,\n new EventLoop::AsyncCallHandle(res));\n \/\/ Order is important.\n res._p->ev = ev;\n res._p->cancelled = false;\n std::swap(res._p->callback,cb);\n event_add(ev, &period);\n return res;\n }\n\n EventLoop::AsyncCallHandle EventLoopPrivate::notifyFd(evutil_socket_t fd, EventLoop::NotifyFdCallbackFunction cb, short evflags, bool persistant)\n {\n EventLoop::AsyncCallHandle res;\n if (!_base) {\n qiLogDebug(\"eventloop\") << \"Discarding notifyChange after loop destruction.\";\n return res;\n }\n if (persistant)\n evflags |= EV_PERSIST;\n struct event *ev = event_new(_base,\n fd,\n evflags,\n fduse_call,\n new EventLoop::AsyncCallHandle(res));\n res._p->ev = ev;\n res._p->cancelled = false;\n res._p->persistant = persistant;\n std::swap(res._p->fdcallback,cb);\n event_add(ev, NULL);\n return res;\n }\n\n \/\/ Basic pimpl bouncers.\n EventLoop::AsyncCallHandle::AsyncCallHandle()\n {\n _p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());\n }\n\n EventLoop::AsyncCallHandle::~AsyncCallHandle()\n {\n }\n\n void EventLoop::AsyncCallHandle::cancel()\n {\n _p->cancel();\n }\n\n EventLoop::EventLoop()\n {\n _p = new EventLoopPrivate();\n }\n\n EventLoop::~EventLoop()\n {\n _p->destroy(false);\n _p = 0;\n }\n\n bool EventLoop::isInEventLoopThread()\n {\n return _p->isInEventLoopThread();\n }\n\n void EventLoop::join()\n {\n _p->join();\n }\n\n void EventLoop::start()\n {\n _p->start();\n }\n\n void EventLoop::stop()\n {\n _p->stop();\n }\n\n void EventLoop::run()\n {\n _p->run();\n }\n\n void *EventLoop::nativeHandle() {\n return static_cast<void *>(_p->getEventBase());\n }\n\n EventLoop::AsyncCallHandle\n EventLoop::asyncCall(\n uint64_t usDelay,\n boost::function<void ()> callback)\n {\n return _p->asyncCall(usDelay, callback);\n }\n\n EventLoop::AsyncCallHandle\n EventLoop::notifyFd(int fileDescriptor,\n NotifyFdCallbackFunction callback,\n FileOperation fdUsage)\n {\n switch (fdUsage)\n {\n case FileOperation_Read:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ, true);\n case FileOperation_Write:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_WRITE, true);\n case FileOperation_ReadOrWrite:\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ|EV_WRITE, true);\n }\n return _p->notifyFd(static_cast<evutil_socket_t>(fileDescriptor), callback, EV_READ|EV_WRITE, true);\n }\n\n static void eventloop_stop(EventLoop* ctx)\n {\n ctx->stop();\n ctx->join();\n delete ctx;\n }\n\n static EventLoop* _get(EventLoop* &ctx)\n {\n if (!ctx)\n {\n if (! qi::Application::initialized())\n {\n qiLogInfo(\"EventLoop\") << \"Creating event loop while no qi::Application() is running\";\n }\n ctx = new EventLoop();\n ctx->start();\n Application::atExit(boost::bind(&eventloop_stop, ctx));\n }\n return ctx;\n }\n\n static EventLoop* _netEventLoop = 0;\n static EventLoop* _objEventLoop = 0;\n EventLoop* getDefaultNetworkEventLoop()\n {\n return _get(_netEventLoop);\n }\n\n EventLoop* getDefaultObjectEventLoop()\n {\n return _get(_objEventLoop);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ TargetPlatforms.h\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 27\/08\/2017.\n\/\/ Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef TargetPlatforms_hpp\n#define TargetPlatforms_hpp\n\nnamespace TargetPlatform {\n\ntypedef int IntType;\n\n\/\/ The below is somehwat overspecified because some of the file formats already supported by this\n\/\/ emulator can self-specify platforms beyond those the emulator otherwise implements.\nenum Type: IntType {\n\tAmstradCPC\t\t=\t1 << 0,\n\tAppleII\t\t\t=\t1 << 1,\n\tAppleIIgs\t\t=\t1 << 2,\n\tAtari2600\t\t=\t1 << 3,\n\tAtariST\t\t\t=\t1 << 4,\n\tAcornAtom\t\t=\t1 << 5,\n\tAcornElectron\t=\t1 << 6,\n\tBBCMaster\t\t=\t1 << 7,\n\tBBCModelA\t\t=\t1 << 8,\n\tBBCModelB\t\t=\t1 << 9,\n\tColeco\t\t\t=\t1 << 10,\n\tCommodore\t\t=\t1 << 11,\n\tDiskII\t\t\t=\t1 << 12,\n\tSega\t\t\t=\t1 << 13,\n\tMacintosh\t\t=\t1 << 14,\n\tMSX\t\t\t\t=\t1 << 15,\n\tOric\t\t\t=\t1 << 16,\n\tZX80\t\t\t=\t1 << 17,\n\tZX81\t\t\t=\t1 << 18,\n\tZXSpectrum\t\t=\t1 << 19,\n\n\tAcorn\t\t\t=\tAcornAtom | AcornElectron | BBCMaster | BBCModelA | BBCModelB,\n\tZX8081\t\t\t=\tZX80 | ZX81,\n\tAllCartridge\t=\tAtari2600 | AcornElectron | Coleco | MSX,\n\tAllDisk\t\t\t=\tAcorn | AmstradCPC | Commodore | Oric | MSX,\t\/\/ TODO: | AtariST\n\tAllTape\t\t\t=\tAcorn | AmstradCPC | Commodore | Oric | ZX80 | ZX81 | MSX | ZXSpectrum,\n};\n\nclass TypeDistinguisher {\n\tpublic:\n\t\tvirtual Type target_platform_type() = 0;\n};\n\n}\n\n#endif \/* TargetPlatforms_h *\/\n<commit_msg>Update AllDisk and AllTape.<commit_after>\/\/\n\/\/ TargetPlatforms.h\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 27\/08\/2017.\n\/\/ Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef TargetPlatforms_hpp\n#define TargetPlatforms_hpp\n\nnamespace TargetPlatform {\n\ntypedef int IntType;\n\n\/\/ The below is somehwat overspecified because some of the file formats already supported by this\n\/\/ emulator can self-specify platforms beyond those the emulator otherwise implements.\nenum Type: IntType {\n\tAmstradCPC\t\t=\t1 << 0,\n\tAppleII\t\t\t=\t1 << 1,\n\tAppleIIgs\t\t=\t1 << 2,\n\tAtari2600\t\t=\t1 << 3,\n\tAtariST\t\t\t=\t1 << 4,\n\tAcornAtom\t\t=\t1 << 5,\n\tAcornElectron\t=\t1 << 6,\n\tBBCMaster\t\t=\t1 << 7,\n\tBBCModelA\t\t=\t1 << 8,\n\tBBCModelB\t\t=\t1 << 9,\n\tColeco\t\t\t=\t1 << 10,\n\tCommodore\t\t=\t1 << 11,\n\tDiskII\t\t\t=\t1 << 12,\n\tSega\t\t\t=\t1 << 13,\n\tMacintosh\t\t=\t1 << 14,\n\tMSX\t\t\t\t=\t1 << 15,\n\tOric\t\t\t=\t1 << 16,\n\tZX80\t\t\t=\t1 << 17,\n\tZX81\t\t\t=\t1 << 18,\n\tZXSpectrum\t\t=\t1 << 19,\n\n\tAcorn\t\t\t=\tAcornAtom | AcornElectron | BBCMaster | BBCModelA | BBCModelB,\n\tZX8081\t\t\t=\tZX80 | ZX81,\n\tAllCartridge\t=\tAtari2600 | AcornElectron | Coleco | MSX,\n\tAllDisk\t\t\t=\tAcorn | AmstradCPC | Commodore | Oric | MSX | ZXSpectrum | Macintosh | AtariST | DiskII,\n\tAllTape\t\t\t=\tAcorn | AmstradCPC | Commodore | Oric | ZX8081 | MSX | ZXSpectrum,\n};\n\nclass TypeDistinguisher {\n\tpublic:\n\t\tvirtual Type target_platform_type() = 0;\n};\n\n}\n\n#endif \/* TargetPlatforms_h *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ exchanger.cpp\n\/\/ integral\n\/\/\n\/\/ Copyright (C) 2013, 2014, 2016 André Pereira Henriques\n\/\/ aphenriques (at) outlook (dot) com\n\/\/\n\/\/ This file is part of integral.\n\/\/\n\/\/ integral is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ integral is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with integral. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"exchanger.h\"\n\nnamespace integral {\n namespace detail {\n namespace exchanger {\n const char * Exchanger<const char *>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n const char * const string = lua_tostring(luaState, index);\n if (string == nullptr) {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n return string;\n } else {\n const char **userData = type_manager::getConvertibleType<const char *>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n }\n }\n \n std::string Exchanger<std::string>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n const char * const string = lua_tostring(luaState, index);\n if (string != nullptr) {\n return string;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n } else {\n std::string *userData = type_manager::getConvertibleType<std::string>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n }\n }\n \n bool Exchanger<bool>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n return lua_toboolean(luaState, index);\n } else {\n bool *userData = type_manager::getConvertibleType<bool>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TBOOLEAN));\n }\n }\n }\n }\n }\n}\n<commit_msg>most frequent code placed first<commit_after>\/\/\n\/\/ exchanger.cpp\n\/\/ integral\n\/\/\n\/\/ Copyright (C) 2013, 2014, 2016 André Pereira Henriques\n\/\/ aphenriques (at) outlook (dot) com\n\/\/\n\/\/ This file is part of integral.\n\/\/\n\/\/ integral is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ integral is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with integral. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"exchanger.h\"\n\nnamespace integral {\n namespace detail {\n namespace exchanger {\n const char * Exchanger<const char *>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n const char * const string = lua_tostring(luaState, index);\n if (string != nullptr) {\n return string;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n } else {\n const char **userData = type_manager::getConvertibleType<const char *>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n }\n }\n \n std::string Exchanger<std::string>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n const char * const string = lua_tostring(luaState, index);\n if (string != nullptr) {\n return string;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n } else {\n std::string *userData = type_manager::getConvertibleType<std::string>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TSTRING));\n }\n }\n }\n \n bool Exchanger<bool>::get(lua_State *luaState, int index) {\n if (lua_isuserdata(luaState, index) == 0) {\n return lua_toboolean(luaState, index);\n } else {\n bool *userData = type_manager::getConvertibleType<bool>(luaState, index);\n if (userData != nullptr) {\n return *userData;\n } else {\n throw ArgumentException::createTypeErrorException(luaState, index, lua_typename(luaState, LUA_TBOOLEAN));\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtGui module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtgroupbox.h\"\n\n#include <QChildEvent>\n\nclass QxtGroupBoxPrivate : public QxtPrivate<QxtGroupBox>\n{\npublic:\n QXT_DECLARE_PUBLIC(QxtGroupBox);\n\n QxtGroupBoxPrivate();\n bool collapsive;\n bool flat; \/\/ so we can restore it when expanding\n};\n\nQxtGroupBoxPrivate::QxtGroupBoxPrivate() : collapsive(true), flat(false)\n{}\n\n\n\/*!\n \\class QxtGroupBox\n \\inmodule QxtGui\n \\brief The QxtGroupBox widget is a collapsive and checkable QGroupBox.\n\n QxtGroupBox is a checkable group box automatically expanding\/collapsing\n its content according to the check state. QxtGroupBox shows its children\n when checked and hides its children when unchecked.\n\n \\image qxtgroupbox.png \"Two QxtGroupBoxes - an expanded and a collapsed - on top of each other.\"\n *\/\n\n\/*!\n Constructs a new QxtGroupBox with \\a parent.\n *\/\nQxtGroupBox::QxtGroupBox(QWidget* parent)\n : QGroupBox(parent)\n{\n QXT_INIT_PRIVATE(QxtGroupBox);\n setCheckable(true);\n setChecked(true);\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n\n}\n\n\/*!\n Constructs a new QxtGroupBox with \\a title and \\a parent.\n *\/\nQxtGroupBox::QxtGroupBox(const QString& title, QWidget* parent)\n : QGroupBox(title, parent)\n{\n QXT_INIT_PRIVATE(QxtGroupBox);\n setCheckable(true);\n setChecked(true);\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n}\n\n\/*!\n Destructs the group box.\n *\/\nQxtGroupBox::~QxtGroupBox()\n{}\n\n\/*!\n \\property QxtGroupBox::collapsive\n \\brief whether the group box is collapsive\n *\/\nbool QxtGroupBox::isCollapsive() const\n{\n return qxt_d().collapsive;\n}\n\nvoid QxtGroupBox::setCollapsive(bool enable)\n{\n if (qxt_d().collapsive != enable)\n {\n qxt_d().collapsive = enable;\n if (!enable)\n setExpanded(true);\n else if (!isChecked())\n setExpanded(false);\n }\n}\n\n\/*!\n Sets the group box \\a collapsed.\n\n A collapsed group box hides its children.\n\n \\sa setExpanded(), QGroupBox::toggled()\n *\/\nvoid QxtGroupBox::setCollapsed(bool collapsed)\n{\n setExpanded(!collapsed);\n}\n\n\/*!\n Sets the group box \\a expanded.\n\n An expanded group box shows its children.\n\n \\sa setCollapsed(), QGroupBox::toggled()\n *\/\nvoid QxtGroupBox::setExpanded(bool expanded)\n{\n if (qxt_d().collapsive || expanded)\n {\n \/\/ show\/hide direct children\n foreach(QObject* child, children())\n {\n if (child->isWidgetType())\n static_cast<QWidget*>(child)->setVisible(expanded);\n }\n if (expanded) {\n setFlat(qxt_d().flat);\n } else {\n qxt_d().flat = isFlat();\n setFlat(true);\n }\n }\n}\n\n\/*!\n \\reimp\n *\/\nvoid QxtGroupBox::childEvent(QChildEvent* event)\n{\n QObject* child = event->child();\n if (event->added() && child->isWidgetType())\n {\n QWidget* widget = static_cast<QWidget*>(child);\n if (qxt_d().collapsive && !isChecked())\n widget->hide();\n }\n}\n<commit_msg>Revised QxtGroupBox docs.<commit_after>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtGui module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtgroupbox.h\"\n\n#include <QChildEvent>\n\nclass QxtGroupBoxPrivate : public QxtPrivate<QxtGroupBox>\n{\npublic:\n QXT_DECLARE_PUBLIC(QxtGroupBox);\n\n QxtGroupBoxPrivate();\n bool collapsive;\n bool flat; \/\/ so we can restore it when expanding\n};\n\nQxtGroupBoxPrivate::QxtGroupBoxPrivate() : collapsive(true), flat(false)\n{}\n\n\n\/*!\n \\class QxtGroupBox\n \\inmodule QxtGui\n \\brief The QxtGroupBox widget is a collapsive and checkable QGroupBox.\n\n QxtGroupBox is a checkable group box automatically expanding\/collapsing\n its content according to the check state. QxtGroupBox shows its children\n when checked and hides its children when unchecked.\n\n \\image qxtgroupbox.png \"Two QxtGroupBoxes - an expanded and a collapsed - on top of each other.\"\n *\/\n\n\/*!\n Constructs a new QxtGroupBox with \\a parent.\n *\/\nQxtGroupBox::QxtGroupBox(QWidget* parent)\n : QGroupBox(parent)\n{\n QXT_INIT_PRIVATE(QxtGroupBox);\n setCheckable(true);\n setChecked(true);\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n\n}\n\n\/*!\n Constructs a new QxtGroupBox with \\a title and \\a parent.\n *\/\nQxtGroupBox::QxtGroupBox(const QString& title, QWidget* parent)\n : QGroupBox(title, parent)\n{\n QXT_INIT_PRIVATE(QxtGroupBox);\n setCheckable(true);\n setChecked(true);\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n}\n\n\/*!\n Destructs the group box.\n *\/\nQxtGroupBox::~QxtGroupBox()\n{}\n\n\/*!\n \\property QxtGroupBox::collapsive\n \\brief whether the group box is collapsive\n\n The default value is \\c true.\n *\/\nbool QxtGroupBox::isCollapsive() const\n{\n return qxt_d().collapsive;\n}\n\nvoid QxtGroupBox::setCollapsive(bool enable)\n{\n if (qxt_d().collapsive != enable)\n {\n qxt_d().collapsive = enable;\n if (!enable)\n setExpanded(true);\n else if (!isChecked())\n setExpanded(false);\n }\n}\n\n\/*!\n Sets the group box \\a collapsed.\n\n A collapsed group box hides its children.\n\n \\sa setExpanded(), QGroupBox::toggled()\n *\/\nvoid QxtGroupBox::setCollapsed(bool collapsed)\n{\n setExpanded(!collapsed);\n}\n\n\/*!\n Sets the group box \\a expanded.\n\n An expanded group box shows its children.\n\n \\sa setCollapsed(), QGroupBox::toggled()\n *\/\nvoid QxtGroupBox::setExpanded(bool expanded)\n{\n if (qxt_d().collapsive || expanded)\n {\n \/\/ show\/hide direct children\n foreach(QObject* child, children())\n {\n if (child->isWidgetType())\n static_cast<QWidget*>(child)->setVisible(expanded);\n }\n if (expanded) {\n setFlat(qxt_d().flat);\n } else {\n qxt_d().flat = isFlat();\n setFlat(true);\n }\n }\n}\n\n\/*!\n \\reimp\n *\/\nvoid QxtGroupBox::childEvent(QChildEvent* event)\n{\n QObject* child = event->child();\n if (event->added() && child->isWidgetType())\n {\n QWidget* widget = static_cast<QWidget*>(child);\n if (qxt_d().collapsive && !isChecked())\n widget->hide();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cnn\/cnn.h\"\n#include \"cnn\/training.h\"\n#include \"cnn\/expr.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/shm.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <utility>\n#include <sstream>\n#include <random>\n\/*\nTODO:\n- Can we move the data vector into shared memory so that we can shuffle it\n between iterations and not have to send huge vectors of integers around?\n- Can we use some sort of shared memory queue to allow threads to spread\n work more evenly?\n- The shadow params in the trainers need to be shared.\n*\/\n\nusing namespace std;\nusing namespace cnn;\nusing namespace cnn::expr;\n\ntypedef pair<cnn::real, cnn::real> Datum;\nconst unsigned num_children = 8;\n\n\/\/ This shared object\/shared memory stuff is junk now\n\/\/ It used to be useful, but now I'm just leaving it here\n\/\/ so that I don't have to look up how to do all tis stuff\n\/\/ in case I ever need to use it again.\nstruct SharedObject {\n cnn::real fake;\n};\nSharedObject* shared_memory = nullptr;\nSharedObject* GetSharedMemory() {\n unsigned shm_size = 1024;\n assert (sizeof(SharedObject) < shm_size);\n key_t shm_key = ftok(\"\/Users\/austinma\/shared2\", 'R');\n if (shm_key == -1) {\n cerr << \"Unable to get shared memory key\" << endl;\n return NULL;\n }\n int shm_id = shmget(shm_key, shm_size, 0644 | IPC_CREAT);\n if (shm_id == -1) {\n cerr << \"Unable to create shared memory\" << endl;\n return NULL;\n }\n void* shm_p = shmat(shm_id, nullptr, 0);\n if (shm_p == (void*)-1) {\n cerr << \"Unable to get shared memory pointer\";\n return NULL;\n }\n return (SharedObject*)shm_p;\n}\n\n\/\/ Some simple functions that do IO to\/from pipes.\n\/\/ These are used to send data from child processes\n\/\/ to the parent process or vice\/versa.\ncnn::real ReadReal(int pipe) {\n cnn::real v;\n read(pipe, &v, sizeof(cnn::real));\n return v;\n}\n\nvoid WriteReal(int pipe, cnn::real v) {\n write(pipe, &v, sizeof(cnn::real));\n}\n\ntemplate <typename T>\nvoid WriteIntVector(int pipe, const vector<T>& vec) {\n unsigned length = vec.size();\n write(pipe, &length, sizeof(unsigned));\n for (T v : vec) {\n write(pipe, &v, sizeof(T));\n }\n}\n\ntemplate<typename T>\nvector<T> ReadIntVector(int pipe) {\n unsigned length;\n read(pipe, &length, sizeof(unsigned));\n vector<T> vec(length);\n for (unsigned i = 0; i < length; ++i) {\n read(pipe, &vec[i], sizeof(T));\n }\n return vec;\n}\n\ncnn::real SumValues(const vector<cnn::real>& values) {\n return accumulate(values.begin(), values.end(), 0.0);\n}\n\ncnn::real Mean(const vector<cnn::real>& values) {\n return SumValues(values) \/ values.size();\n}\n\nstruct Workload {\n pid_t pid;\n int c2p[2]; \/\/ Child to parent pipe\n int p2c[2]; \/\/ Parent to child pipe\n};\n\nstruct ModelParameters {\n Parameters* m;\n Parameters* b;\n};\n\nvoid BuildComputationGraph(ComputationGraph& cg, ModelParameters& model_parameters, cnn::real* x_value, cnn::real* y_value) {\n Expression m = parameter(cg, model_parameters.m);\n Expression b = parameter(cg, model_parameters.b);\n\n Expression x = input(cg, x_value);\n Expression y_star = input(cg, y_value);\n Expression y = m * x + b;\n Expression loss = squared_distance(y, y_star);\n}\n\nvector<Datum> ReadData(string filename) {\n vector<Datum> data;\n ifstream fs(filename);\n if (!fs.is_open()) {\n cerr << \"ERROR: Unable to open \" << filename << endl;\n exit(1);\n }\n string line;\n while (getline(fs, line)) {\n if (line.size() > 0 && line[0] == '#') {\n continue;\n }\n vector<string> parts;\n boost::split(parts, line, boost::is_any_of(\"\\t\"));\n data.push_back(make_pair(atof(parts[0].c_str()), atof(parts[1].c_str())));\n }\n return data;\n}\n\nunsigned SpawnChildren(vector<Workload>& workloads) {\n assert (workloads.size() == num_children);\n pid_t pid;\n unsigned cid;\n for (cid = 0; cid < num_children; ++cid) {\n pid = fork();\n if (pid == -1) {\n cerr << \"Fork failed. Exiting ...\";\n return 1;\n }\n else if (pid == 0) {\n \/\/ children shouldn't continue looping\n break;\n }\n workloads[cid].pid = pid;\n }\n return cid;\n}\n\nint RunChild(unsigned cid, ComputationGraph& cg, Trainer* trainer, vector<Workload>& workloads,\n const vector<Datum>& data, cnn::real& x_value, cnn::real& y_value, ModelParameters& model_params) {\n assert (cid >= 0 && cid < num_children);\n while (true) {\n \/\/ Check if the parent wants us to exit\n bool cont = false;\n read(workloads[cid].p2c[0], &cont, sizeof(bool));\n if (!cont) {\n break;\n }\n\n \/\/ Read in our workload and update our local model\n vector<unsigned> indices = ReadIntVector<unsigned>(workloads[cid].p2c[0]);\n\n \/\/ Run the actual training loop\n cnn::real loss = 0;\n for (unsigned i : indices) {\n assert (i < data.size());\n auto p = data[i];\n x_value = get<0>(p);\n y_value = get<1>(p);\n loss += as_scalar(cg.forward());\n cg.backward();\n trainer->update(1.0);\n }\n trainer->update_epoch();\n\n cnn::real m = as_scalar(model_params.m->values);\n cnn::real b = as_scalar(model_params.b->values);\n\n \/\/ Let the parent know that we're done and return the loss value\n WriteReal(workloads[cid].c2p[1], m);\n WriteReal(workloads[cid].c2p[1], b);\n WriteReal(workloads[cid].c2p[1], loss);\n }\n return 0;\n}\n\nvoid RunParent(vector<Datum>& data, unsigned num_iterations, vector<Workload>& workloads, ModelParameters& model_params, Trainer* trainer) {\n for (unsigned iter = 0; iter < num_iterations; ++iter) {\n vector<cnn::real> ms(num_children);\n vector<cnn::real> bs(num_children);\n vector<cnn::real> losses(num_children);\n vector<unsigned> indices(data.size());\n for (unsigned i = 0; i < data.size(); ++i) {\n indices[i] = i;\n }\n random_shuffle(indices.begin(), indices.end());\n\n for(unsigned cid = 0; cid < num_children; ++cid) {\n \/\/ work out the indices of the data points we want this child to consider\n unsigned start = (unsigned)(1.0 * cid \/ num_children * data.size() + 0.5);\n unsigned end = (unsigned)(1.0 * (cid + 1) \/ num_children * data.size() + 0.5);\n vector<unsigned> child_indices;\n child_indices.reserve(end - start);\n for (unsigned i = start; i < end; ++i) {\n child_indices.push_back(indices[i]);\n }\n \/\/ Tell the child it's not time to quit yet\n bool cont = true;\n write(workloads[cid].p2c[1], &cont, sizeof(bool)); \n WriteIntVector(workloads[cid].p2c[1], child_indices);\n }\n\n \/\/ Wait for each child to finish training its load\n for(unsigned cid = 0; cid < num_children; ++cid) {\n ms[cid] = ReadReal(workloads[cid].c2p[0]);\n bs[cid] = ReadReal(workloads[cid].c2p[0]);\n losses[cid] = ReadReal(workloads[cid].c2p[0]);\n }\n\n cerr << \"ID\\tm\\tb\\tloss\" << endl;\n cerr << \"============================\" << endl;\n for (unsigned cid = 0; cid < num_children; ++cid) {\n cerr << cid << \"\\t\" << ms[cid] << \"\\t\" << bs[cid] << \"\\t\" << losses[cid] << endl;\n }\n\n \/\/ TODO: This is currently uneffective because it doesn't affect the Trainers on the child processes\n trainer->update_epoch();\n\n cnn::real loss = SumValues(losses) \/ data.size();\n cerr << iter << \"\\t\" << \"loss = \" << loss << endl; \n }\n\n \/\/ Kill all children one by one and wait for them to exit\n for (unsigned cid = 0; cid < num_children; ++cid) {\n bool cont = false;\n write(workloads[cid].p2c[1], &cont, sizeof(cont));\n wait(NULL);\n }\n\n cnn::Cleanup();\n}\n\nint main(int argc, char** argv) {\n cnn::Initialize(argc, argv, 0, true);\n\n if (argc < 2) {\n cerr << \"Usage: \" << argv[0] << \" data.txt\" << endl;\n cerr << \"Where data.txt contains tab-delimited pairs of floats.\" << endl;\n return 1;\n }\n unsigned num_iterations = (argc >= 3) ? atoi(argv[2]) : 10;\n vector<Datum> data = ReadData(argv[1]);\n vector<Workload> workloads(num_children);\n\n Model model; \n \/\/SimpleSGDTrainer sgd(&model, 0.0, 0.001);\n AdamTrainer sgd(&model, 0.0);\n\n ComputationGraph cg;\n cnn::real x_value, y_value;\n Parameters* m_param = model.add_parameters({1, 1});\n Parameters* b_param = model.add_parameters({1});\n ModelParameters model_params = {m_param, b_param};\n BuildComputationGraph(cg, model_params, &x_value, &y_value);\n\n shared_memory = GetSharedMemory();\n\n for (unsigned cid = 0; cid < num_children; cid++) {\n pipe(workloads[cid].p2c);\n pipe(workloads[cid].c2p);\n }\n\n unsigned cid = SpawnChildren(workloads);\n if (cid < num_children) {\n return RunChild(cid, cg, &sgd, workloads, data, x_value, y_value, model_params);\n }\n else {\n RunParent(data, num_iterations, workloads, model_params, &sgd);\n }\n}\n<commit_msg>mp example now trains an RNN language model<commit_after>#include \"cnn\/cnn.h\"\n#include \"cnn\/training.h\"\n#include \"cnn\/expr.h\"\n#include \"cnn\/dict.h\"\n#include \"cnn\/lstm.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/shm.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <utility>\n#include <sstream>\n#include <random>\n\/*\nTODO:\n- Can we move the data vector into shared memory so that we can shuffle it\n between iterations and not have to send huge vectors of integers around?\n- Can we use some sort of shared memory queue to allow threads to spread\n work more evenly?\n- The shadow params in the trainers need to be shared.\n*\/\n\nusing namespace std;\nusing namespace cnn;\nusing namespace cnn::expr;\n\ntypedef vector<int> Datum;\nunsigned num_children = 1;\n\n\/\/ Some simple functions that do IO to\/from pipes.\n\/\/ These are used to send data from child processes\n\/\/ to the parent process or vice\/versa.\ncnn::real ReadReal(int pipe) {\n cnn::real v;\n read(pipe, &v, sizeof(cnn::real));\n return v;\n}\n\nvoid WriteReal(int pipe, cnn::real v) {\n write(pipe, &v, sizeof(cnn::real));\n}\n\ntemplate <typename T>\nvoid WriteIntVector(int pipe, const vector<T>& vec) {\n unsigned length = vec.size();\n write(pipe, &length, sizeof(unsigned));\n for (T v : vec) {\n write(pipe, &v, sizeof(T));\n }\n}\n\ntemplate<typename T>\nvector<T> ReadIntVector(int pipe) {\n unsigned length;\n read(pipe, &length, sizeof(unsigned));\n vector<T> vec(length);\n for (unsigned i = 0; i < length; ++i) {\n read(pipe, &vec[i], sizeof(T));\n }\n return vec;\n}\n\ncnn::real SumValues(const vector<cnn::real>& values) {\n return accumulate(values.begin(), values.end(), 0.0);\n}\n\ncnn::real Mean(const vector<cnn::real>& values) {\n return SumValues(values) \/ values.size();\n}\n\nstruct Workload {\n pid_t pid;\n int c2p[2]; \/\/ Child to parent pipe\n int p2c[2]; \/\/ Parent to child pipe\n};\n\nunsigned LAYERS = 2;\nunsigned INPUT_DIM = 8; \/\/256\nunsigned HIDDEN_DIM = 24; \/\/ 1024\nunsigned VOCAB_SIZE = 5500;\n\ncnn::Dict d;\nint kSOS;\nint kEOS;\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n LookupParameters* p_c;\n Parameters* p_R;\n Parameters* p_bias;\n Builder builder;\n explicit RNNLanguageModel(Model& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model) {\n p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});\n p_bias = model.add_parameters({VOCAB_SIZE});\n }\n\n \/\/ return Expression of total loss\n Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg) {\n const unsigned slen = sent.size() - 1;\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n Expression i_R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n Expression i_bias = parameter(cg, p_bias); \/\/ word bias\n vector<Expression> errs;\n for (unsigned t = 0; t < slen; ++t) {\n Expression i_x_t = lookup(cg, p_c, sent[t]);\n \/\/ y_t = RNN(x_t)\n Expression i_y_t = builder.add_input(i_x_t);\n Expression i_r_t = i_bias + i_R * i_y_t;\n \n \/\/ LogSoftmax followed by PickElement can be written in one step\n \/\/ using PickNegLogSoftmax\n Expression i_err = pickneglogsoftmax(i_r_t, sent[t+1]);\n errs.push_back(i_err);\n }\n Expression i_nerr = sum(errs);\n return i_nerr;\n }\n\n \/\/ return Expression for total loss\n void RandomSample(int max_len = 150) {\n cerr << endl;\n ComputationGraph cg;\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n \n Expression i_R = parameter(cg, p_R);\n Expression i_bias = parameter(cg, p_bias);\n vector<Expression> errs;\n int len = 0;\n int cur = kSOS;\n while(len < max_len && cur != kEOS) {\n ++len;\n Expression i_x_t = lookup(cg, p_c, cur);\n \/\/ y_t = RNN(x_t)\n Expression i_y_t = builder.add_input(i_x_t);\n Expression i_r_t = i_bias + i_R * i_y_t;\n \n Expression ydist = softmax(i_r_t);\n \n unsigned w = 0;\n while (w == 0 || (int)w == kSOS) {\n auto dist = as_vector(cg.incremental_forward());\n double p = rand01();\n for (; w < dist.size(); ++w) {\n p -= dist[w];\n if (p < 0.0) { break; }\n }\n if (w == dist.size()) w = kEOS;\n }\n cerr << (len == 1 ? \"\" : \" \") << d.Convert(w);\n cur = w;\n }\n cerr << endl;\n }\n};\n\nvector<Datum> ReadData(string filename) {\n vector<Datum> data;\n ifstream fs(filename);\n if (!fs.is_open()) {\n cerr << \"ERROR: Unable to open \" << filename << endl;\n exit(1);\n }\n string line;\n while (getline(fs, line)) {\n data.push_back(ReadSentence(line, &d));\n }\n return data;\n}\n\nunsigned SpawnChildren(vector<Workload>& workloads) {\n assert (workloads.size() == num_children);\n pid_t pid;\n unsigned cid;\n for (cid = 0; cid < num_children; ++cid) {\n pid = fork();\n if (pid == -1) {\n cerr << \"Fork failed. Exiting ...\";\n return 1;\n }\n else if (pid == 0) {\n \/\/ children shouldn't continue looping\n break;\n }\n workloads[cid].pid = pid;\n }\n return cid;\n}\n\ntemplate <class T>\nint RunChild(unsigned cid, RNNLanguageModel<T>& rnnlm, Trainer* trainer, vector<Workload>& workloads,\n const vector<Datum>& data) {\n assert (cid >= 0 && cid < num_children);\n while (true) {\n \/\/ Check if the parent wants us to exit\n bool cont = false;\n read(workloads[cid].p2c[0], &cont, sizeof(bool));\n if (!cont) {\n break;\n }\n\n \/\/ Read in our workload and update our local model\n vector<unsigned> indices = ReadIntVector<unsigned>(workloads[cid].p2c[0]);\n\n \/\/ Run the actual training loop\n cnn::real loss = 0;\n for (unsigned i : indices) {\n assert (i < data.size());\n const Datum& datum = data[i];\n ComputationGraph cg;\n rnnlm.BuildLMGraph(datum, cg);\n loss += as_scalar(cg.forward());\n cg.backward();\n trainer->update(1.0);\n }\n trainer->update_epoch();\n\n \/\/ Let the parent know that we're done and return the loss value\n WriteReal(workloads[cid].c2p[1], loss);\n }\n return 0;\n}\n\nvoid RunParent(vector<Datum>& data, vector<Datum>& dev_data, vector<Workload>& workloads) {\n for (unsigned iter = 0; iter < 0; ++iter) {\n vector<unsigned> indices(data.size());\n for (unsigned i = 0; i < data.size(); ++i) {\n indices[i] = i;\n }\n random_shuffle(indices.begin(), indices.end());\n\n for(unsigned cid = 0; cid < num_children; ++cid) {\n \/\/ work out the indices of the data points we want this child to consider\n unsigned start = (unsigned)(1.0 * cid \/ num_children * data.size() + 0.5);\n unsigned end = (unsigned)(1.0 * (cid + 1) \/ num_children * data.size() + 0.5);\n vector<unsigned> child_indices;\n child_indices.reserve(end - start);\n for (unsigned i = start; i < end; ++i) {\n child_indices.push_back(indices[i]);\n }\n \/\/ Tell the child it's not time to quit yet\n bool cont = true;\n write(workloads[cid].p2c[1], &cont, sizeof(bool)); \n WriteIntVector(workloads[cid].p2c[1], child_indices);\n }\n\n \/\/ Wait for each child to finish training its load\n vector<cnn::real> losses(num_children);\n for(unsigned cid = 0; cid < num_children; ++cid) {\n losses[cid] = ReadReal(workloads[cid].c2p[0]);\n }\n\n cnn::real loss = SumValues(losses) \/ data.size();\n cerr << iter << \"\\t\" << \"loss = \" << loss << endl; \n }\n\n \/\/ Kill all children one by one and wait for them to exit\n for (unsigned cid = 0; cid < num_children; ++cid) {\n bool cont = false;\n write(workloads[cid].p2c[1], &cont, sizeof(cont));\n wait(NULL);\n }\n\n cnn::Cleanup();\n}\n\nint main(int argc, char** argv) {\n cnn::Initialize(argc, argv, 0, true);\n\n if (argc < 4) {\n cerr << \"Usage: \" << argv[0] << \" cores corpus.txt dev.txt\" << endl;\n return 1;\n }\n num_children = atoi(argv[1]);\n kSOS = d.Convert(\"<s>\");\n kEOS = d.Convert(\"<\/s>\");\n assert (num_children > 0 && num_children <= 64);\n\n vector<Datum> data = ReadData(argv[2]);\n vector<Datum> dev_data = ReadData(argv[3]);\n vector<Workload> workloads(num_children);\n\n Model model; \n SimpleSGDTrainer sgd(&model, 0.0);\n \/\/AdamTrainer sgd(&model, 0.0);\n\n RNNLanguageModel<LSTMBuilder> rnnlm(model);\n\n for (unsigned cid = 0; cid < num_children; cid++) {\n pipe(workloads[cid].p2c);\n pipe(workloads[cid].c2p);\n }\n\n unsigned cid = SpawnChildren(workloads);\n if (cid < num_children) {\n return RunChild(cid, rnnlm, &sgd, workloads, data);\n }\n else {\n RunParent(data, dev_data, workloads);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017-2018 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"enginerequest.h\"\n\n#include \"common.h\"\n\n#include <Cutelyst\/response_p.h>\n#include <Cutelyst\/Context>\n\n#include <QLoggingCategory>\nQ_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, \"cutelyst.engine_request\", QtWarningMsg)\n\nusing namespace Cutelyst;\n\nEngineRequest::EngineRequest()\n{\n\n}\n\nEngineRequest::~EngineRequest()\n{\n delete body;\n delete context;\n}\n\nvoid EngineRequest::finalizeBody()\n{\n if (!(status & EngineRequest::Chunked)) {\n Response *response = context->response();\n QIODevice *body = response->bodyDevice();\n\n if (body) {\n body->seek(0);\n char block[64 * 1024];\n while (!body->atEnd()) {\n qint64 in = body->read(block, sizeof(block));\n if (in <= 0) {\n break;\n }\n\n if (write(block, in) != in) {\n qCWarning(CUTELYST_ENGINEREQUEST) << \"Failed to write body\";\n break;\n }\n }\n } else {\n const QByteArray bodyByteArray = response->body();\n write(bodyByteArray.constData(), bodyByteArray.size());\n }\n } else if (!(status & EngineRequest::ChunkedDone)) {\n \/\/ Write the final '0' chunk\n doWrite(\"0\\r\\n\\r\\n\", 5);\n }\n}\n\nvoid EngineRequest::finalizeError()\n{\n Response *res = context->response();\n\n res->setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n QByteArray body;\n\n \/\/ Trick IE. Old versions of IE would display their own error page instead\n \/\/ of ours if we'd give it less than 512 bytes.\n body.reserve(512);\n\n body.append(context->errors().join(QLatin1Char('\\n')).toUtf8());\n\n res->setBody(body);\n\n \/\/ Return 500\n res->setStatus(Response::InternalServerError);\n}\n\nvoid EngineRequest::finalize()\n{\n if (context->error()) {\n finalizeError();\n }\n\n if (!(status & EngineRequest::FinalizedHeaders) && !finalizeHeaders()) {\n return;\n }\n\n finalizeBody();\n}\n\nvoid EngineRequest::finalizeCookies()\n{\n Response *res = context->response();\n Headers &headers = res->headers();\n const auto cookies = res->cookies();\n for (const QNetworkCookie &cookie : cookies) {\n headers.pushHeader(QStringLiteral(\"SET_COOKIE\"), QString::fromLatin1(cookie.toRawForm()));\n }\n}\n\nbool EngineRequest::finalizeHeaders()\n{\n Response *response = context->response();\n Headers &headers = response->headers();\n\n \/\/ Fix missing content length\n if (headers.contentLength() < 0) {\n qint64 size = response->size();\n if (size >= 0) {\n headers.setContentLength(size);\n }\n }\n\n finalizeCookies();\n\n \/\/ Done\n status |= EngineRequest::FinalizedHeaders;\n return writeHeaders(response->status(), headers);\n}\n\nqint64 EngineRequest::write(const char *data, qint64 len)\n{\n if (!(status & EngineRequest::Chunked)) {\n return doWrite(data, len);\n } else if (!(status & EngineRequest::ChunkedDone)) {\n const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();\n QByteArray chunk;\n chunk.reserve(len + chunkSize.size() + 4);\n chunk.append(chunkSize).append(\"\\r\\n\", 2)\n .append(data, len).append(\"\\r\\n\", 2);\n\n qint64 retWrite = doWrite(chunk.data(), chunk.size());\n\n \/\/ Flag if we wrote an empty chunk\n if (!len) {\n status |= EngineRequest::ChunkedDone;\n }\n\n return retWrite == chunk.size() ? len : -1;\n }\n return -1;\n}\n\nbool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)\n{\n if (status & EngineRequest::FinalizedHeaders) {\n return false;\n }\n\n if (webSocketHandshakeDo(key, origin, protocol)) {\n status |= EngineRequest::FinalizedHeaders;\n return true;\n }\n\n return false;\n}\n\nbool EngineRequest::webSocketSendTextMessage(const QString &message)\n{\n Q_UNUSED(message)\n return false;\n}\n\nbool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)\n{\n Q_UNUSED(message)\n return false;\n}\n\nbool EngineRequest::webSocketSendPing(const QByteArray &payload)\n{\n Q_UNUSED(payload)\n return false;\n}\n\nbool EngineRequest::webSocketClose(quint16 code, const QString &reason)\n{\n Q_UNUSED(code)\n Q_UNUSED(reason)\n return false;\n}\n\nvoid EngineRequest::processingFinished()\n{\n}\n\nbool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)\n{\n Q_UNUSED(key)\n Q_UNUSED(origin)\n Q_UNUSED(protocol)\n return false;\n}\n\nvoid EngineRequest::setPath(char *rawPath, const int len)\n{\n qDebug() << \"PATH\" << QByteArray(rawPath, len);\n if (len == 0) {\n return;\n }\n\n char *data = rawPath;\n const char *inputPtr = data;\n\n bool skipUtf8 = true;\n int outlen = 0;\n for (int i = 0; i < len; ++i, ++outlen) {\n const char c = inputPtr[i];\n if (c == '%' && i + 2 < len) {\n int a = inputPtr[++i];\n int b = inputPtr[++i];\n\n if (a >= '0' && a <= '9') a -= '0';\n else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;\n else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;\n\n if (b >= '0' && b <= '9') b -= '0';\n else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;\n else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;\n\n *data++ = (char)((a << 4) | b);\n skipUtf8 = false;\n } else if (c == '+') {\n *data++ = ' ';\n } else {\n *data++ = c;\n }\n }\n\n if (skipUtf8) {\n path = QString::fromLatin1(rawPath, outlen);\n } else {\n path = QString::fromUtf8(rawPath, outlen);\n }\n}\n\n#include \"moc_enginerequest.cpp\"\n<commit_msg>remove debug info<commit_after>\/*\n * Copyright (C) 2017-2018 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"enginerequest.h\"\n\n#include \"common.h\"\n\n#include <Cutelyst\/response_p.h>\n#include <Cutelyst\/Context>\n\n#include <QLoggingCategory>\nQ_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, \"cutelyst.engine_request\", QtWarningMsg)\n\nusing namespace Cutelyst;\n\nEngineRequest::EngineRequest()\n{\n\n}\n\nEngineRequest::~EngineRequest()\n{\n delete body;\n delete context;\n}\n\nvoid EngineRequest::finalizeBody()\n{\n if (!(status & EngineRequest::Chunked)) {\n Response *response = context->response();\n QIODevice *body = response->bodyDevice();\n\n if (body) {\n body->seek(0);\n char block[64 * 1024];\n while (!body->atEnd()) {\n qint64 in = body->read(block, sizeof(block));\n if (in <= 0) {\n break;\n }\n\n if (write(block, in) != in) {\n qCWarning(CUTELYST_ENGINEREQUEST) << \"Failed to write body\";\n break;\n }\n }\n } else {\n const QByteArray bodyByteArray = response->body();\n write(bodyByteArray.constData(), bodyByteArray.size());\n }\n } else if (!(status & EngineRequest::ChunkedDone)) {\n \/\/ Write the final '0' chunk\n doWrite(\"0\\r\\n\\r\\n\", 5);\n }\n}\n\nvoid EngineRequest::finalizeError()\n{\n Response *res = context->response();\n\n res->setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n QByteArray body;\n\n \/\/ Trick IE. Old versions of IE would display their own error page instead\n \/\/ of ours if we'd give it less than 512 bytes.\n body.reserve(512);\n\n body.append(context->errors().join(QLatin1Char('\\n')).toUtf8());\n\n res->setBody(body);\n\n \/\/ Return 500\n res->setStatus(Response::InternalServerError);\n}\n\nvoid EngineRequest::finalize()\n{\n if (context->error()) {\n finalizeError();\n }\n\n if (!(status & EngineRequest::FinalizedHeaders) && !finalizeHeaders()) {\n return;\n }\n\n finalizeBody();\n}\n\nvoid EngineRequest::finalizeCookies()\n{\n Response *res = context->response();\n Headers &headers = res->headers();\n const auto cookies = res->cookies();\n for (const QNetworkCookie &cookie : cookies) {\n headers.pushHeader(QStringLiteral(\"SET_COOKIE\"), QString::fromLatin1(cookie.toRawForm()));\n }\n}\n\nbool EngineRequest::finalizeHeaders()\n{\n Response *response = context->response();\n Headers &headers = response->headers();\n\n \/\/ Fix missing content length\n if (headers.contentLength() < 0) {\n qint64 size = response->size();\n if (size >= 0) {\n headers.setContentLength(size);\n }\n }\n\n finalizeCookies();\n\n \/\/ Done\n status |= EngineRequest::FinalizedHeaders;\n return writeHeaders(response->status(), headers);\n}\n\nqint64 EngineRequest::write(const char *data, qint64 len)\n{\n if (!(status & EngineRequest::Chunked)) {\n return doWrite(data, len);\n } else if (!(status & EngineRequest::ChunkedDone)) {\n const QByteArray chunkSize = QByteArray::number(len, 16).toUpper();\n QByteArray chunk;\n chunk.reserve(len + chunkSize.size() + 4);\n chunk.append(chunkSize).append(\"\\r\\n\", 2)\n .append(data, len).append(\"\\r\\n\", 2);\n\n qint64 retWrite = doWrite(chunk.data(), chunk.size());\n\n \/\/ Flag if we wrote an empty chunk\n if (!len) {\n status |= EngineRequest::ChunkedDone;\n }\n\n return retWrite == chunk.size() ? len : -1;\n }\n return -1;\n}\n\nbool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)\n{\n if (status & EngineRequest::FinalizedHeaders) {\n return false;\n }\n\n if (webSocketHandshakeDo(key, origin, protocol)) {\n status |= EngineRequest::FinalizedHeaders;\n return true;\n }\n\n return false;\n}\n\nbool EngineRequest::webSocketSendTextMessage(const QString &message)\n{\n Q_UNUSED(message)\n return false;\n}\n\nbool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message)\n{\n Q_UNUSED(message)\n return false;\n}\n\nbool EngineRequest::webSocketSendPing(const QByteArray &payload)\n{\n Q_UNUSED(payload)\n return false;\n}\n\nbool EngineRequest::webSocketClose(quint16 code, const QString &reason)\n{\n Q_UNUSED(code)\n Q_UNUSED(reason)\n return false;\n}\n\nvoid EngineRequest::processingFinished()\n{\n}\n\nbool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol)\n{\n Q_UNUSED(key)\n Q_UNUSED(origin)\n Q_UNUSED(protocol)\n return false;\n}\n\nvoid EngineRequest::setPath(char *rawPath, const int len)\n{\n if (len == 0) {\n return;\n }\n\n char *data = rawPath;\n const char *inputPtr = data;\n\n bool skipUtf8 = true;\n int outlen = 0;\n for (int i = 0; i < len; ++i, ++outlen) {\n const char c = inputPtr[i];\n if (c == '%' && i + 2 < len) {\n int a = inputPtr[++i];\n int b = inputPtr[++i];\n\n if (a >= '0' && a <= '9') a -= '0';\n else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;\n else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;\n\n if (b >= '0' && b <= '9') b -= '0';\n else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;\n else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;\n\n *data++ = (char)((a << 4) | b);\n skipUtf8 = false;\n } else if (c == '+') {\n *data++ = ' ';\n } else {\n *data++ = c;\n }\n }\n\n if (skipUtf8) {\n path = QString::fromLatin1(rawPath, outlen);\n } else {\n path = QString::fromUtf8(rawPath, outlen);\n }\n}\n\n#include \"moc_enginerequest.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-grid-multiscale project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-grid-multiscale\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GRID_PART_ITERATOR_CODIM0_HH\n#define DUNE_GRID_PART_ITERATOR_CODIM0_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n\/\/ system\n#include <map>\n\n\/\/ dune-common\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n\n\/\/ dune-geometry\n#include <dune\/geometry\/type.hh>\n\n\/\/ dune-grid\n#include <dune\/grid\/common\/grid.hh>\n\nnamespace Dune {\nnamespace grid {\nnamespace Part {\nnamespace Iterator {\nnamespace Local {\n\n\n\/**\n * \\brief Iterates over those entities of a grid part, the indices of which match predefined ones.\n * \\todo Replace GlobalGridPartImp with Interface< GlobalGridPartTraitsImp >!\n * \\todo Document!\n *\/\ntemplate< class GlobalGridPartImp, int codim, Dune::PartitionIteratorType pitype >\nclass IndexBased\n : public GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType\n{\npublic:\n typedef GlobalGridPartImp GlobalGridPartType;\n\n typedef IndexBased< GlobalGridPartType, codim, pitype > ThisType;\n\n typedef typename GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType BaseType;\n\n typedef typename GlobalGridPartType::IndexSetType::IndexType IndexType;\n\n typedef Dune::GeometryType GeometryType;\n\nprivate:\n typedef std::map< IndexType, IndexType > IndexMapType;\n\npublic:\n typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType;\n\n typedef typename BaseType::Entity Entity;\n\n IndexBased(const GlobalGridPartType& globalGridPart,\n const Dune::shared_ptr< const IndexContainerType > indexContainer,\n const bool end = false)\n : BaseType(end ? globalGridPart.template end< codim, pitype >() : globalGridPart.template begin< codim, pitype >()),\n globalGridPart_(globalGridPart),\n indexContainer_(indexContainer),\n workAtAll_(0)\n {\n if (!end) {\n \/\/ loop over all GeometryTypes\n for (typename IndexContainerType::const_iterator iterator = indexContainer_->begin();\n iterator != indexContainer_->end();\n ++iterator) {\n \/\/ treat only the codim 0 ones\n if (iterator->first.dim() == (GlobalGridPartType::GridType::dimension - codim)) {\n ++workAtAll_;\n last_.insert(std::make_pair(iterator->first, iterator->second.rbegin()->first));\n end_.insert(std::make_pair(iterator->first, iterator->second.end()));\n } \/\/ treat only the codim 0 ones\n } \/\/ loop over all GeometryTypes\n forward();\n } \/\/ if (!end)\n } \/\/ IndexBased\n\n ThisType& operator++()\n {\n if (workAtAll_ > 0) {\n BaseType::operator++();\n forward();\n } else\n BaseType::operator=(globalGridPart_.template end< codim, pitype >());\n return *this;\n } \/\/ ThisType& operator++()\n\nprivate:\n \/\/! iterates forward until we find the next entity that belongs to the local grid part\n void forward()\n {\n bool found = false;\n while (!found && (workAtAll_ > 0)) {\n const Entity& entity = BaseType::operator*();\n const IndexType& index = globalGridPart_.indexSet().index(entity);\n const GeometryType& geometryType = entity.type();\n typename IndexContainerType::const_iterator indexMap = indexContainer_->find(geometryType);\n if (indexMap != indexContainer_->end()) {\n const typename IndexMapType::const_iterator result = indexMap->second.find(index);\n if ((result != end_.find(geometryType)->second)) {\n found = true;\n if (result->first == last_.find(geometryType)->second)\n --workAtAll_;\n } else\n BaseType::operator++();\n } else\n BaseType::operator++();\n }\n } \/\/ void forward()\n\n const GlobalGridPartType& globalGridPart_;\n const Dune::shared_ptr< const IndexContainerType > indexContainer_;\n unsigned int workAtAll_;\n std::map< GeometryType, IndexType > last_;\n std::map< GeometryType, typename IndexMapType::const_iterator > end_;\n}; \/\/ class IndexBased\n\n\n} \/\/ namespace Local\n} \/\/ namespace Iterator\n} \/\/ namespace Part\n} \/\/ namespace grid\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GRID_PART_ITERATOR_CODIM0_HH\n<commit_msg>[grid.part] drop config.h include<commit_after>\/\/ This file is part of the dune-grid-multiscale project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-grid-multiscale\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GRID_PART_ITERATOR_CODIM0_HH\n#define DUNE_GRID_PART_ITERATOR_CODIM0_HH\n\n\/\/ system\n#include <map>\n\n\/\/ dune-common\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n\n\/\/ dune-geometry\n#include <dune\/geometry\/type.hh>\n\n\/\/ dune-grid\n#include <dune\/grid\/common\/grid.hh>\n\nnamespace Dune {\nnamespace grid {\nnamespace Part {\nnamespace Iterator {\nnamespace Local {\n\n\n\/**\n * \\brief Iterates over those entities of a grid part, the indices of which match predefined ones.\n * \\todo Replace GlobalGridPartImp with Interface< GlobalGridPartTraitsImp >!\n * \\todo Document!\n *\/\ntemplate< class GlobalGridPartImp, int codim, Dune::PartitionIteratorType pitype >\nclass IndexBased\n : public GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType\n{\npublic:\n typedef GlobalGridPartImp GlobalGridPartType;\n\n typedef IndexBased< GlobalGridPartType, codim, pitype > ThisType;\n\n typedef typename GlobalGridPartImp::template Codim< codim >::template Partition< pitype >::IteratorType BaseType;\n\n typedef typename GlobalGridPartType::IndexSetType::IndexType IndexType;\n\n typedef Dune::GeometryType GeometryType;\n\nprivate:\n typedef std::map< IndexType, IndexType > IndexMapType;\n\npublic:\n typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType;\n\n typedef typename BaseType::Entity Entity;\n\n IndexBased(const GlobalGridPartType& globalGridPart,\n const Dune::shared_ptr< const IndexContainerType > indexContainer,\n const bool end = false)\n : BaseType(end ? globalGridPart.template end< codim, pitype >() : globalGridPart.template begin< codim, pitype >()),\n globalGridPart_(globalGridPart),\n indexContainer_(indexContainer),\n workAtAll_(0)\n {\n if (!end) {\n \/\/ loop over all GeometryTypes\n for (typename IndexContainerType::const_iterator iterator = indexContainer_->begin();\n iterator != indexContainer_->end();\n ++iterator) {\n \/\/ treat only the codim 0 ones\n if (iterator->first.dim() == (GlobalGridPartType::GridType::dimension - codim)) {\n ++workAtAll_;\n last_.insert(std::make_pair(iterator->first, iterator->second.rbegin()->first));\n end_.insert(std::make_pair(iterator->first, iterator->second.end()));\n } \/\/ treat only the codim 0 ones\n } \/\/ loop over all GeometryTypes\n forward();\n } \/\/ if (!end)\n } \/\/ IndexBased\n\n ThisType& operator++()\n {\n if (workAtAll_ > 0) {\n BaseType::operator++();\n forward();\n } else\n BaseType::operator=(globalGridPart_.template end< codim, pitype >());\n return *this;\n } \/\/ ThisType& operator++()\n\nprivate:\n \/\/! iterates forward until we find the next entity that belongs to the local grid part\n void forward()\n {\n bool found = false;\n while (!found && (workAtAll_ > 0)) {\n const Entity& entity = BaseType::operator*();\n const IndexType& index = globalGridPart_.indexSet().index(entity);\n const GeometryType& geometryType = entity.type();\n typename IndexContainerType::const_iterator indexMap = indexContainer_->find(geometryType);\n if (indexMap != indexContainer_->end()) {\n const typename IndexMapType::const_iterator result = indexMap->second.find(index);\n if ((result != end_.find(geometryType)->second)) {\n found = true;\n if (result->first == last_.find(geometryType)->second)\n --workAtAll_;\n } else\n BaseType::operator++();\n } else\n BaseType::operator++();\n }\n } \/\/ void forward()\n\n const GlobalGridPartType& globalGridPart_;\n const Dune::shared_ptr< const IndexContainerType > indexContainer_;\n unsigned int workAtAll_;\n std::map< GeometryType, IndexType > last_;\n std::map< GeometryType, typename IndexMapType::const_iterator > end_;\n}; \/\/ class IndexBased\n\n\n} \/\/ namespace Local\n} \/\/ namespace Iterator\n} \/\/ namespace Part\n} \/\/ namespace grid\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GRID_PART_ITERATOR_CODIM0_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * (c) Copyright Ascensio System SIA 2010-2019\r\n *\r\n * This program is a free software product. You can redistribute it and\/or\r\n * modify it under the terms of the GNU Affero General Public License (AGPL)\r\n * version 3 as published by the Free Software Foundation. In accordance with\r\n * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect\r\n * that Ascensio System SIA expressly excludes the warranty of non-infringement\r\n * of any third-party rights.\r\n *\r\n * This program is distributed WITHOUT ANY WARRANTY; without even the implied\r\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For\r\n * details, see the GNU AGPL at: http:\/\/www.gnu.org\/licenses\/agpl-3.0.html\r\n *\r\n * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha\r\n * street, Riga, Latvia, EU, LV-1050.\r\n *\r\n * The interactive user interfaces in modified source and object code versions\r\n * of the Program must display Appropriate Legal Notices, as required under\r\n * Section 5 of the GNU AGPL version 3.\r\n *\r\n * Pursuant to Section 7(b) of the License you must retain the original Product\r\n * logo when distributing the program. Pursuant to Section 7(e) we decline to\r\n * grant you any rights under trademark law for use of our trademarks.\r\n *\r\n * All the Product's GUI elements, including illustrations and icon sets, as\r\n * well as technical writing content are licensed under the terms of the\r\n * Creative Commons Attribution-ShareAlike 4.0 International. See the License\r\n * terms at http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/legalcode\r\n *\r\n *\/\r\n#include \"FileDownloader_private.h\"\r\n\r\n#include <iostream>\r\n#include <unistd.h>\r\n#include \"..\/..\/DesktopEditor\/common\/Directory.h\"\r\n\r\n#ifndef USE_EXTERNAL_DOWNLOAD\r\n\r\n#include <fcntl.h>\r\n#include <curl\/curl.h>\r\n#include <curl\/easy.h>\r\n#include <stdio.h>\r\n\r\n#else\r\n\r\n#include <unistd.h>\r\n#include <sys\/wait.h>\r\n\r\nstd::string wget_url_validate(const std::string& url)\r\n{\r\n std::string::size_type pos = 0;\r\n const char* url_ptr = url.c_str();\r\n while ('-' == *url_ptr++) \/\/ '\\0' => break\r\n ++pos;\r\n if (*url_ptr == '\\0')\r\n return \"\";\r\n\r\n return url.substr(pos);\r\n}\r\n\r\nint download_external(const std::wstring& sUrl, const std::wstring& sOutput)\r\n{\r\n int nReturnCode = -1;\r\n\r\n std::string sUrlA = U_TO_UTF8(sUrl);\r\n \/\/sUrlA =(\"\\\"\" + sUrlA + \"\\\"\");\r\n std::string sOutputA = U_TO_UTF8(sOutput);\r\n \/\/sOutputA =(\"\\\"\" + sOutputA + \"\\\"\");\r\n\r\n if (0 != nReturnCode && NSFile::CFileBinary::Exists(L\"\/usr\/bin\/curl\"))\r\n {\r\n pid_t pid = fork(); \/\/ create child process\r\n int status;\r\n\r\n switch (pid)\r\n {\r\n case -1: \/\/ error\r\n break;\r\n\r\n case 0: \/\/ child process\r\n {\r\n const char* nargs[8];\r\n nargs[0] = \"\/usr\/bin\/curl\";\r\n nargs[1] = \"--url\";\r\n nargs[2] = sUrlA.c_str();\r\n nargs[3] = \"--output\";\r\n nargs[4] = sOutputA.c_str();\r\n nargs[5] = \"--silent\";\r\n nargs[6] = \"-L\";\r\n nargs[7] = NULL;\r\n\r\n const char* nenv[3];\r\n nenv[0] = \"LD_PRELOAD=\";\r\n nenv[1] = \"LD_LIBRARY_PATH=\";\r\n nenv[2] = NULL;\r\n\r\n execve(\"\/usr\/bin\/curl\", (char * const *)nargs, (char * const *)nenv);\r\n exit(EXIT_SUCCESS);\r\n break;\r\n }\r\n default: \/\/ parent process, pid now contains the child pid\r\n while (-1 == waitpid(pid, &status, 0)); \/\/ wait for child to complete\r\n if (WIFEXITED(status))\r\n {\r\n nReturnCode = WEXITSTATUS(status);\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (0 != nReturnCode && NSFile::CFileBinary::Exists(L\"\/usr\/bin\/wget\"))\r\n {\r\n std::string sUrlValidateA = wget_url_validate(sUrlA);\r\n\r\n pid_t pid = fork(); \/\/ create child process\r\n int status;\r\n\r\n switch (pid)\r\n {\r\n case -1: \/\/ error\r\n break;\r\n\r\n case 0: \/\/ child process\r\n {\r\n const char* nargs[6];\r\n nargs[0] = \"\/usr\/bin\/wget\";\r\n nargs[1] = sUrlValidateA.c_str();\r\n nargs[2] = \"-O\";\r\n nargs[3] = sOutputA.c_str();\r\n nargs[4] = \"-q\";\r\n nargs[5] = NULL;\r\n\r\n const char* nenv[2];\r\n nenv[0] = \"LD_PRELOAD=\";\r\n nenv[1] = NULL;\r\n\r\n execve(\"\/usr\/bin\/wget\", (char * const *)nargs, (char * const *)nenv);\r\n exit(EXIT_SUCCESS);\r\n break;\r\n }\r\n default: \/\/ parent process, pid now contains the child pid\r\n while (-1 == waitpid(pid, &status, 0)); \/\/ wait for child to complete\r\n if (WIFEXITED(status))\r\n {\r\n nReturnCode = WEXITSTATUS(status);\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (0 == nReturnCode)\r\n {\r\n if (!NSFile::CFileBinary::Exists(sOutput))\r\n nReturnCode = -1;\r\n }\r\n\r\n return nReturnCode;\r\n}\r\n\r\n#endif\r\n\r\nclass CFileDownloaderBaseCURL : public CFileDownloaderBase\r\n{\r\npublic :\r\n CFileDownloaderBaseCURL(std::wstring sFileUrl, bool bDelete = true)\r\n : CFileDownloaderBase(sFileUrl, bDelete)\r\n {\r\n }\r\n virtual ~CFileDownloaderBaseCURL()\r\n {\r\n if (m_bDelete && !m_sFilePath.empty())\r\n {\r\n std::string sFilePath = U_TO_UTF8(m_sFilePath);\r\n unlink(sFilePath.c_str());\r\n }\r\n }\r\n\r\n#ifndef USE_EXTERNAL_DOWNLOAD\r\n static size_t write_data(void *ptr, size_t size, size_t nmemb, int fd) {\r\n size_t written = write(fd, ptr, size * nmemb);\r\n return written;\r\n }\r\n\r\n virtual int DownloadFile()\r\n {\r\n CURL *curl;\r\n int fp;\r\n CURLcode res;\r\n std::string sUrl = U_TO_UTF8(m_sFileUrl);\r\n std::string sOut;\r\n const char *url = sUrl.c_str();\r\n curl = curl_easy_init();\r\n if (curl)\r\n {\r\n fp = createUniqueTempFile(sOut);\r\n curl_easy_setopt(curl, CURLOPT_URL, url);\r\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\r\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\r\n#if defined(__linux__)\r\n \/\/в linux нет встроенных в систему корневых сертификатов, поэтому отключаем проверку\r\n \/\/http:\/\/curl.haxx.se\/docs\/sslcerts.html\r\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);\r\n#endif\r\n \/* tell libcurl to follow redirection(default false) *\/\r\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);\r\n \/* some servers don't like requests that are made without a user-agent field, so we provide one *\/\r\n curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Mozilla\/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko\/20100101 Firefox\/38.0\");\r\n res = curl_easy_perform(curl);\r\n \/* always cleanup *\/\r\n curl_easy_cleanup(curl);\r\n close(fp);\r\n }\r\n\r\n m_bComplete = (CURLE_OK == res);\r\n if (m_bComplete)\r\n {\r\n if (m_sFilePath.empty())\r\n m_sFilePath = NSFile::CUtf8Converter::GetUnicodeStringFromUTF8((BYTE*)sOut.c_str(), sOut.length());\r\n else\r\n NSFile::CFileBinary::Move(UTF8_TO_U(sOut), m_sFilePath);\r\n }\r\n \/\/int nRes = execl(\"\/usr\/bin\/wget\", stringWstingToUtf8String (m_sFileUrl).c_str(), \"-P\", stringWstingToUtf8String (m_sFilePath).c_str(), (char *)NULL);\r\n \/\/m_bComplete = nRes >= 0;\r\n\r\n return m_bComplete ? 0 : 1;\r\n }\r\n\r\nprotected:\r\n int createUniqueTempFile (std::string &filename)\r\n {\r\n std::string sTempPath = NSFile::CUtf8Converter::GetUtf8StringFromUnicode(NSDirectory::GetTempPath());\r\n sTempPath += \"\/fileXXXXXX\";\r\n int fd = mkstemp(const_cast <char *> (sTempPath.c_str()));\r\n if (-1 != fd)\r\n filename = sTempPath;\r\n return fd;\r\n }\r\n#else\r\n virtual int DownloadFile()\r\n {\r\n if (m_sFilePath.empty())\r\n {\r\n m_sFilePath = NSFile::CFileBinary::CreateTempFileWithUniqueName(NSDirectory::GetTempPath(), L\"DW\");\r\n if (NSFile::CFileBinary::Exists(m_sFilePath))\r\n NSFile::CFileBinary::Remove(m_sFilePath);\r\n }\r\n return download_external(m_sFileUrl, m_sFilePath);\r\n }\r\n\r\n#endif\r\n};\r\n\r\nCFileDownloader_private::CFileDownloader_private(std::wstring sFileUrl, bool bDelete)\r\n{\r\n m_pInternal = new CFileDownloaderBaseCURL(sFileUrl, bDelete);\r\n}\r\n<commit_msg>Add timeout to curl\/wget<commit_after>\/*\r\n * (c) Copyright Ascensio System SIA 2010-2019\r\n *\r\n * This program is a free software product. You can redistribute it and\/or\r\n * modify it under the terms of the GNU Affero General Public License (AGPL)\r\n * version 3 as published by the Free Software Foundation. In accordance with\r\n * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect\r\n * that Ascensio System SIA expressly excludes the warranty of non-infringement\r\n * of any third-party rights.\r\n *\r\n * This program is distributed WITHOUT ANY WARRANTY; without even the implied\r\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For\r\n * details, see the GNU AGPL at: http:\/\/www.gnu.org\/licenses\/agpl-3.0.html\r\n *\r\n * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha\r\n * street, Riga, Latvia, EU, LV-1050.\r\n *\r\n * The interactive user interfaces in modified source and object code versions\r\n * of the Program must display Appropriate Legal Notices, as required under\r\n * Section 5 of the GNU AGPL version 3.\r\n *\r\n * Pursuant to Section 7(b) of the License you must retain the original Product\r\n * logo when distributing the program. Pursuant to Section 7(e) we decline to\r\n * grant you any rights under trademark law for use of our trademarks.\r\n *\r\n * All the Product's GUI elements, including illustrations and icon sets, as\r\n * well as technical writing content are licensed under the terms of the\r\n * Creative Commons Attribution-ShareAlike 4.0 International. See the License\r\n * terms at http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/legalcode\r\n *\r\n *\/\r\n#include \"FileDownloader_private.h\"\r\n\r\n#include <iostream>\r\n#include <unistd.h>\r\n#include \"..\/..\/DesktopEditor\/common\/Directory.h\"\r\n\r\n#ifndef USE_EXTERNAL_DOWNLOAD\r\n\r\n#include <fcntl.h>\r\n#include <curl\/curl.h>\r\n#include <curl\/easy.h>\r\n#include <stdio.h>\r\n\r\n#else\r\n\r\n#include <unistd.h>\r\n#include <sys\/wait.h>\r\n\r\nstd::string wget_url_validate(const std::string& url)\r\n{\r\n std::string::size_type pos = 0;\r\n const char* url_ptr = url.c_str();\r\n while ('-' == *url_ptr++) \/\/ '\\0' => break\r\n ++pos;\r\n if (*url_ptr == '\\0')\r\n return \"\";\r\n\r\n return url.substr(pos);\r\n}\r\n\r\nint download_external(const std::wstring& sUrl, const std::wstring& sOutput)\r\n{\r\n int nReturnCode = -1;\r\n\r\n std::string sUrlA = U_TO_UTF8(sUrl);\r\n \/\/sUrlA =(\"\\\"\" + sUrlA + \"\\\"\");\r\n std::string sOutputA = U_TO_UTF8(sOutput);\r\n \/\/sOutputA =(\"\\\"\" + sOutputA + \"\\\"\");\r\n\r\n if (0 != nReturnCode && NSFile::CFileBinary::Exists(L\"\/usr\/bin\/curl\"))\r\n {\r\n pid_t pid = fork(); \/\/ create child process\r\n int status;\r\n\r\n switch (pid)\r\n {\r\n case -1: \/\/ error\r\n break;\r\n\r\n case 0: \/\/ child process\r\n {\r\n const char* nargs[10];\r\n nargs[0] = \"\/usr\/bin\/curl\";\r\n nargs[1] = \"--url\";\r\n nargs[2] = sUrlA.c_str();\r\n nargs[3] = \"--output\";\r\n nargs[4] = sOutputA.c_str();\r\n nargs[5] = \"--silent\";\r\n nargs[6] = \"-L\";\r\n nargs[7] = \"--connect-timeout\";\r\n nargs[8] = \"10\";\r\n nargs[9] = NULL;\r\n\r\n const char* nenv[3];\r\n nenv[0] = \"LD_PRELOAD=\";\r\n nenv[1] = \"LD_LIBRARY_PATH=\";\r\n nenv[2] = NULL;\r\n\r\n execve(\"\/usr\/bin\/curl\", (char * const *)nargs, (char * const *)nenv);\r\n exit(EXIT_SUCCESS);\r\n break;\r\n }\r\n default: \/\/ parent process, pid now contains the child pid\r\n while (-1 == waitpid(pid, &status, 0)); \/\/ wait for child to complete\r\n if (WIFEXITED(status))\r\n {\r\n nReturnCode = WEXITSTATUS(status);\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (0 != nReturnCode && NSFile::CFileBinary::Exists(L\"\/usr\/bin\/wget\"))\r\n {\r\n std::string sUrlValidateA = wget_url_validate(sUrlA);\r\n\r\n pid_t pid = fork(); \/\/ create child process\r\n int status;\r\n\r\n switch (pid)\r\n {\r\n case -1: \/\/ error\r\n break;\r\n\r\n case 0: \/\/ child process\r\n {\r\n const char* nargs[8];\r\n nargs[0] = \"\/usr\/bin\/wget\";\r\n nargs[1] = sUrlValidateA.c_str();\r\n nargs[2] = \"-O\";\r\n nargs[3] = sOutputA.c_str();\r\n nargs[4] = \"-q\";\r\n nargs[5] = \"--connect-timeout=10\";\r\n nargs[6] = \"--tries=2\";\r\n nargs[7] = NULL;\r\n\r\n const char* nenv[2];\r\n nenv[0] = \"LD_PRELOAD=\";\r\n nenv[1] = NULL;\r\n\r\n execve(\"\/usr\/bin\/wget\", (char * const *)nargs, (char * const *)nenv);\r\n exit(EXIT_SUCCESS);\r\n break;\r\n }\r\n default: \/\/ parent process, pid now contains the child pid\r\n while (-1 == waitpid(pid, &status, 0)); \/\/ wait for child to complete\r\n if (WIFEXITED(status))\r\n {\r\n nReturnCode = WEXITSTATUS(status);\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (0 == nReturnCode)\r\n {\r\n if (!NSFile::CFileBinary::Exists(sOutput))\r\n nReturnCode = -1;\r\n }\r\n\r\n return nReturnCode;\r\n}\r\n\r\n#endif\r\n\r\nclass CFileDownloaderBaseCURL : public CFileDownloaderBase\r\n{\r\npublic :\r\n CFileDownloaderBaseCURL(std::wstring sFileUrl, bool bDelete = true)\r\n : CFileDownloaderBase(sFileUrl, bDelete)\r\n {\r\n }\r\n virtual ~CFileDownloaderBaseCURL()\r\n {\r\n if (m_bDelete && !m_sFilePath.empty())\r\n {\r\n std::string sFilePath = U_TO_UTF8(m_sFilePath);\r\n unlink(sFilePath.c_str());\r\n }\r\n }\r\n\r\n#ifndef USE_EXTERNAL_DOWNLOAD\r\n static size_t write_data(void *ptr, size_t size, size_t nmemb, int fd) {\r\n size_t written = write(fd, ptr, size * nmemb);\r\n return written;\r\n }\r\n\r\n virtual int DownloadFile()\r\n {\r\n CURL *curl;\r\n int fp;\r\n CURLcode res;\r\n std::string sUrl = U_TO_UTF8(m_sFileUrl);\r\n std::string sOut;\r\n const char *url = sUrl.c_str();\r\n curl = curl_easy_init();\r\n if (curl)\r\n {\r\n fp = createUniqueTempFile(sOut);\r\n curl_easy_setopt(curl, CURLOPT_URL, url);\r\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\r\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);\r\n#if defined(__linux__)\r\n \/\/в linux нет встроенных в систему корневых сертификатов, поэтому отключаем проверку\r\n \/\/http:\/\/curl.haxx.se\/docs\/sslcerts.html\r\n curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);\r\n#endif\r\n \/* tell libcurl to follow redirection(default false) *\/\r\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);\r\n \/* some servers don't like requests that are made without a user-agent field, so we provide one *\/\r\n curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Mozilla\/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko\/20100101 Firefox\/38.0\");\r\n res = curl_easy_perform(curl);\r\n \/* always cleanup *\/\r\n curl_easy_cleanup(curl);\r\n close(fp);\r\n }\r\n\r\n m_bComplete = (CURLE_OK == res);\r\n if (m_bComplete)\r\n {\r\n if (m_sFilePath.empty())\r\n m_sFilePath = NSFile::CUtf8Converter::GetUnicodeStringFromUTF8((BYTE*)sOut.c_str(), sOut.length());\r\n else\r\n NSFile::CFileBinary::Move(UTF8_TO_U(sOut), m_sFilePath);\r\n }\r\n \/\/int nRes = execl(\"\/usr\/bin\/wget\", stringWstingToUtf8String (m_sFileUrl).c_str(), \"-P\", stringWstingToUtf8String (m_sFilePath).c_str(), (char *)NULL);\r\n \/\/m_bComplete = nRes >= 0;\r\n\r\n return m_bComplete ? 0 : 1;\r\n }\r\n\r\nprotected:\r\n int createUniqueTempFile (std::string &filename)\r\n {\r\n std::string sTempPath = NSFile::CUtf8Converter::GetUtf8StringFromUnicode(NSDirectory::GetTempPath());\r\n sTempPath += \"\/fileXXXXXX\";\r\n int fd = mkstemp(const_cast <char *> (sTempPath.c_str()));\r\n if (-1 != fd)\r\n filename = sTempPath;\r\n return fd;\r\n }\r\n#else\r\n virtual int DownloadFile()\r\n {\r\n if (m_sFilePath.empty())\r\n {\r\n m_sFilePath = NSFile::CFileBinary::CreateTempFileWithUniqueName(NSDirectory::GetTempPath(), L\"DW\");\r\n if (NSFile::CFileBinary::Exists(m_sFilePath))\r\n NSFile::CFileBinary::Remove(m_sFilePath);\r\n }\r\n return download_external(m_sFileUrl, m_sFilePath);\r\n }\r\n\r\n#endif\r\n};\r\n\r\nCFileDownloader_private::CFileDownloader_private(std::wstring sFileUrl, bool bDelete)\r\n{\r\n m_pInternal = new CFileDownloaderBaseCURL(sFileUrl, bDelete);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <tiramisu\/auto_scheduler\/search_method.h>\n#include <random>\n\nnamespace tiramisu::auto_scheduler\n{\n\nvoid beam_search::search(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n\n child->print_previous_optims();\n std::cout << \"-----------\" << std::endl;\n child->print_new_optims();\n child->print_ast();\n std::cout << \"Evaluation : \" << child->evaluation << std::endl << std::endl;\n \n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n \n nb_explored_schedules++;\n }\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ keep the top 'beam_size' children and delete the rest\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n \/\/ Search recursively on the best children\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\nvoid beam_search::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n\n std::vector<syntax_tree*> children;\n\n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n\n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n\n nb_explored_optims++;\n nb_optims_tried++;\n }\n\n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n\n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n\n child->evaluation = eval_func->evaluate(*child);\n\n std::string schedule_annot = evaluate_by_learning_model::get_schedule_json(*child);\n\n \/\/remove the last two characters }\\n\n schedule_annot.pop_back();\n schedule_annot.pop_back();\n\n if (std::isfinite(child->evaluation)) \/\/ the evaluation is not finite mean that the schedule didn't run\n schedule_annot += \", \\n\\\"execution_time\\\" : \" + std::to_string(child->evaluation) + \"\\n}\\n\";\n else\n schedule_annot += \", \\n\\\"execution_time\\\" : null\\n}\\n\";\n\n schedules_annotations->push_back(schedule_annot);\n\n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n\n nb_explored_schedules++;\n }\n\n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n\n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ keep the top 'beam_size' children and delete the rest\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n\n children.resize(std::min(beam_size, (int)children.size()));\n\n \/\/ Search recursively on the best children\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1;\n search_save(*child, schedules_annotations);\n }\n}\n\nvoid mcts::search(syntax_tree& ast)\n{\n std::default_random_engine rand_generator;\n \n std::vector<syntax_tree*> samples;\n std::vector<syntax_tree*> children;\n std::vector<double> children_evals;\n \n for (int epoch = 0; epoch < nb_samples; ++epoch)\n {\n \/\/ Starting from the initial ast, generate optimizations until reaching max_depth\n syntax_tree *ast_sample = *\n for (int depth = 0; depth < max_depth; ++depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(*ast_sample, optim_type);\n \n if (children.empty())\n continue;\n \n children_evals.clear();\n \n for (syntax_tree *child : children)\n {\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n children_evals.push_back(child->evaluation);\n \n nb_explored_schedules++;\n }\n \n \/\/ Add the current AST to the list of children\n children.push_back(ast_sample->copy_ast());\n children_evals.push_back(ast_sample->evaluation);\n \n \/\/ Sample an AST\n std::discrete_distribution<int> dist(children_evals.begin(), children_evals.end());\n ast_sample = children[dist(rand_generator)];\n \n samples.push_back(ast_sample);\n }\n }\n \n if (samples.empty())\n return ;\n \n \/\/ Sort schedules with respect to evaluations\n std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n \/\/ Execute top-k schedules and return the best\n for (int i = 0; i < topk; ++i)\n {\n float exec_time = exec_eval->evaluate(*samples[i]);\n if (exec_time < best_evaluation)\n {\n best_evaluation = exec_time;\n best_ast = samples[i];\n }\n }\n}\n\nvoid mcts::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n std::cerr<< \"mcts::search_save not yet implemented\" << std::endl;\n exit(1);\n}\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\nvoid beam_search_topk::search(syntax_tree& ast)\n{\n \/\/ Do a beam search\n beam_search_subroutine(ast);\n \n \/\/ Sort schedules found\n std::sort(schedules.begin(), schedules.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n \/\/ Execute top-k schedules to find the best\n for (int i = 0; i < topk; ++i)\n {\n float exec_time = exec_eval->evaluate(*schedules[i]);\n if (exec_time < best_evaluation)\n {\n best_evaluation = exec_time;\n best_ast = schedules[i];\n }\n }\n}\n\nvoid beam_search_topk::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n std::cerr<< \"beam_search_topk::search_save not yet implemented\" << std::endl;\n exit(1);\n}\n\nvoid beam_search_topk::beam_search_subroutine(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n \n nb_explored_schedules++;\n }\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n for (int i = 0; i < beam_size; ++i)\n schedules.push_back(children[i]);\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n\n \/\/ Search recursively on the best children\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\nvoid beam_search_accuracy_evaluator::search(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n \n \/\/ We evaluate both by the model and by execution\n model_evals_list.push_back(child->evaluation);\n exec_evals_list.push_back(exec_eval->evaluate(*child));\n \n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n \n nb_explored_schedules++;\n }\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ Search recursively on the best children\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\n}\n<commit_msg>Added a verbose option for search space sampling<commit_after>#include <tiramisu\/auto_scheduler\/search_method.h>\n#include <random>\n\nnamespace tiramisu::auto_scheduler\n{\n\nvoid beam_search::search(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n\n child->print_previous_optims();\n std::cout << \"-----------\" << std::endl;\n child->print_new_optims();\n child->print_ast();\n std::cout << \"Evaluation : \" << child->evaluation << std::endl << std::endl;\n \n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n \n nb_explored_schedules++;\n }\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ keep the top 'beam_size' children and delete the rest\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n \/\/ Search recursively on the best children\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\nvoid beam_search::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n\n std::vector<syntax_tree*> children;\n\n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n\n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n\n nb_explored_optims++;\n nb_optims_tried++;\n }\n\n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n\n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n\n if (std::getenv(\"AS_VERBOSE\")!=NULL)\n if (std::stoi(std::getenv(\"AS_VERBOSE\"))==1){\n child->print_previous_optims();\n std::cout << \"-----------\" << std::endl;\n child->print_new_optims();\n child->print_ast();\n }\n\n child->evaluation = eval_func->evaluate(*child);\n\n std::string schedule_annot = evaluate_by_learning_model::get_schedule_json(*child);\n\n \/\/remove the last two characters }\\n\n schedule_annot.pop_back();\n schedule_annot.pop_back();\n\n if (std::isfinite(child->evaluation)) \/\/ the evaluation is not finite mean that the schedule didn't run\n schedule_annot += \", \\n\\\"execution_time\\\" : \" + std::to_string(child->evaluation) + \"\\n}\\n\";\n else\n schedule_annot += \", \\n\\\"execution_time\\\" : null\\n}\\n\";\n\n schedules_annotations->push_back(schedule_annot);\n\n if (std::getenv(\"AS_VERBOSE\")!=NULL)\n if (std::stoi(std::getenv(\"AS_VERBOSE\"))==1){\n std::cout << \"Schedule number \"<< schedules_annotations->size() << std::endl;\n std::cout << \"Evaluation : \" << child->evaluation << std::endl << std::endl;\n }\n\n if (std::isinf(child->evaluation))\n std::cerr<< \"Evaluation of schedule \"<< schedules_annotations->size() <<\" failed \"<< std::endl;\n\n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n\n nb_explored_schedules++;\n }\n\n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n\n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ keep the top 'beam_size' children and delete the rest\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n\n children.resize(std::min(beam_size, (int)children.size()));\n\n \/\/ Search recursively on the best children\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1;\n search_save(*child, schedules_annotations);\n }\n}\n\nvoid mcts::search(syntax_tree& ast)\n{\n std::default_random_engine rand_generator;\n \n std::vector<syntax_tree*> samples;\n std::vector<syntax_tree*> children;\n std::vector<double> children_evals;\n \n for (int epoch = 0; epoch < nb_samples; ++epoch)\n {\n \/\/ Starting from the initial ast, generate optimizations until reaching max_depth\n syntax_tree *ast_sample = *\n for (int depth = 0; depth < max_depth; ++depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(*ast_sample, optim_type);\n \n if (children.empty())\n continue;\n \n children_evals.clear();\n \n for (syntax_tree *child : children)\n {\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n children_evals.push_back(child->evaluation);\n \n nb_explored_schedules++;\n }\n \n \/\/ Add the current AST to the list of children\n children.push_back(ast_sample->copy_ast());\n children_evals.push_back(ast_sample->evaluation);\n \n \/\/ Sample an AST\n std::discrete_distribution<int> dist(children_evals.begin(), children_evals.end());\n ast_sample = children[dist(rand_generator)];\n \n samples.push_back(ast_sample);\n }\n }\n \n if (samples.empty())\n return ;\n \n \/\/ Sort schedules with respect to evaluations\n std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n \/\/ Execute top-k schedules and return the best\n for (int i = 0; i < topk; ++i)\n {\n float exec_time = exec_eval->evaluate(*samples[i]);\n if (exec_time < best_evaluation)\n {\n best_evaluation = exec_time;\n best_ast = samples[i];\n }\n }\n}\n\nvoid mcts::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n std::cerr<< \"mcts::search_save not yet implemented\" << std::endl;\n exit(1);\n}\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\nvoid beam_search_topk::search(syntax_tree& ast)\n{\n \/\/ Do a beam search\n beam_search_subroutine(ast);\n \n \/\/ Sort schedules found\n std::sort(schedules.begin(), schedules.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n \/\/ Execute top-k schedules to find the best\n for (int i = 0; i < topk; ++i)\n {\n float exec_time = exec_eval->evaluate(*schedules[i]);\n if (exec_time < best_evaluation)\n {\n best_evaluation = exec_time;\n best_ast = schedules[i];\n }\n }\n}\n\nvoid beam_search_topk::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)\n{\n std::cerr<< \"beam_search_topk::search_save not yet implemented\" << std::endl;\n exit(1);\n}\n\nvoid beam_search_topk::beam_search_subroutine(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n \n nb_explored_schedules++;\n }\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n \n for (int i = 0; i < beam_size; ++i)\n schedules.push_back(children[i]);\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n\n \/\/ Search recursively on the best children\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\nvoid beam_search_accuracy_evaluator::search(syntax_tree& ast)\n{\n if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)\n ast.clear_new_optimizations();\n \n std::vector<syntax_tree*> children;\n \n \/\/ Look for an optimization that can be applied\n int nb_optims_tried = 0;\n int nb_explored_optims = ast.nb_explored_optims;\n \n while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)\n {\n optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];\n children = scheds_gen->generate_schedules(ast, optim_type);\n \n nb_explored_optims++;\n nb_optims_tried++;\n }\n \n \/\/ Stop if no more optimizations can be applied\n if (children.size() == 0)\n return ;\n \n \/\/ Evaluate children and sort them from smallest to highest evaluation\n for (syntax_tree *child : children)\n {\n child->nb_explored_optims = nb_explored_optims;\n child->transform_ast();\n \n child->evaluation = eval_func->evaluate(*child);\n \n \/\/ We evaluate both by the model and by execution\n model_evals_list.push_back(child->evaluation);\n exec_evals_list.push_back(exec_eval->evaluate(*child));\n \n if (child->evaluation < best_evaluation)\n {\n best_evaluation = child->evaluation;\n best_ast = child;\n }\n \n nb_explored_schedules++;\n }\n \n \/\/ Stop if we reached the maximum depth\n if (nb_explored_optims >= max_depth)\n return ;\n \n \/\/ Add the current AST to the list of children\n syntax_tree *ast_copy = ast.copy_ast();\n ast_copy->nb_explored_optims = nb_explored_optims;\n children.push_back(ast_copy);\n\n \/\/ Sort children from smallest evaluation to largest\n std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {\n return a->evaluation < b->evaluation;\n });\n\n \/\/ Search recursively on the best children\n for (int i = beam_size; i < children.size(); ++i)\n delete children[i];\n \n children.resize(std::min(beam_size, (int)children.size()));\n\n for (syntax_tree *child : children)\n {\n child->search_depth = ast.search_depth + 1; \n search(*child);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***\nDEVSIM\nCopyright 2021 Devsim LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***\/\n#include \"GaussFermi.hh\"\n#include \"BoostConstants.hh\"\n#include \"MiscMathFunc.hh\"\n#ifdef DEVSIM_EXTENDED_PRECISION\n#include \"Float128.hh\"\n#endif\n#include <utility>\n#include <cmath>\nusing std::abs;\n\n#ifdef DEVSIM_UNIT_TEST\n#include <iostream>\n#include <iomanip>\n#endif\n\n\/*\nImplementation of:\nhttps:\/\/doi.org\/10.1063\/1.3374475\n@article{doi:10.1063\/1.3374475,\nauthor = {Paasch,Gernot and Scheinert,Susanne },\ntitle = {Charge carrier density of organics with Gaussian density of states: Analytical approximation for the Gauss–Fermi integral},\njournal = {Journal of Applied Physics},\nvolume = {107},\nnumber = {10},\npages = {104501},\nyear = {2010},\ndoi = {10.1063\/1.3374475},\nURL = { https:\/\/doi.org\/10.1063\/1.3374475 },\neprint = { https:\/\/doi.org\/10.1063\/1.3374475 }\n}\n*\/\n\nnamespace {\ntemplate <typename T>\nstruct MC {\n static constexpr T sqrt2 = boost::math::constants::root_two<T>();\n static constexpr T sqrt2_pi = boost::math::constants::root_two<T>() * boost::math::constants::one_div_root_pi<T>();\n static constexpr T one_div_root_two_pi = boost::math::constants::one_div_root_two_pi<T>();\n};\n\ntemplate <typename T>\ninline T calcH_Impl(const T &s, const T &S)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n\n T H = sqrt2 \/ s * erfc_inv(exp(-0.5 * S));\n return H;\n}\n\ntemplate <typename T>\ninline T calcH(const T &s, const T &S)\n{\n thread_local auto p = std::make_pair(s, calcH_Impl(s, S));\n\n \/\/ Assume that s is constant across the same call in the same region\n if (p.first != s)\n {\n p = std::make_pair(s, calcH_Impl(s, S));\n }\n\n return p.second;\n}\n\ntemplate <typename T>\ninline T calcK(const T &s, const T &S, const T &H)\n{\n const T &sqrt2_pi = MC<T>::sqrt2_pi;\n\n T K = 2 * (1. - H \/ s * sqrt2_pi * exp(0.5 * S * (1. - H * H)));\n return K;\n}\n\n}\n\ntemplate <typename T>\nT gfi(T zeta, T s)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n const T S = s * s;\n\n T H = calcH(s, S);\n\n T value;\n if (zeta < -S)\n {\n const T K = calcK(s, S, H);\n value = exp(0.5 * S + zeta) \/ (exp(K*(zeta+S)) + 1);\n }\n else\n {\n value = 0.5 * erfc(-zeta \/ (s*sqrt2) * H);\n }\n\n return value;\n}\n\ntemplate <typename T>\nT dgfidx(T zeta, T s)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n const T &sqrt2_pi = MC<T>::sqrt2_pi;\n\n const T S = s * s;\n\n T H = calcH(s, S);\n\n T dvalue;\n if (zeta < -S)\n {\n const T K = calcK(s, S, H);\n const T den_inv = 1. \/ (exp(K * (S + zeta)) + 1.);\n dvalue = exp(0.5 * S + zeta) * den_inv * (1. - K*exp(K * (S+zeta)) * den_inv);\n }\n else\n {\n const T &one_div_root_two_pi = MC<T>::one_div_root_two_pi;\n dvalue = one_div_root_two_pi * H \/ s * exp(-0.5 * pow(H*zeta,2)\/S);\n }\n\n return dvalue;\n}\n\n\/\/### inverse function for Gaussian Fermi Integral\n\nnamespace {\ntemplate <typename T>\nT good_relerror();\n\ntemplate <>\ndouble good_relerror()\n{\n return 1e-12;\n}\n\n#ifdef DEVSIM_EXTENDED_PRECISION\ntemplate <>\nfloat128 good_relerror()\n{\n return 1e-31;\n}\n#endif\n}\n\ntemplate <typename T>\nT igfi(T g, T s)\n{\n \/\/ using the Newton method\n \/\/ The initial guess\n \/\/ perhaps the degenerate approximation\n \/\/ or provided from the last call\n \/\/ improves speed\n T x = 0.0;\n \/\/printf(\"%d %1.15e %1.15e\\n\", -1, x, rerr);\n#ifdef DEVSIM_UNIT_TEST\n std::cout << std::setprecision(std::numeric_limits<T>::max_digits10);\n#endif\n T arg = 1. - 2. * g;\n\n static constexpr T bound = 1.0 - std::numeric_limits<T>::epsilon();\n\n \/\/ prevent infinite results\n if (arg <= -1.0)\n {\n arg = -bound;\n }\n else if (arg >= 1.0)\n {\n arg = bound;\n }\n\n const T &sqrt2 = MC<T>::sqrt2;\n \/\/ using the degenerate approximation\n const T S = s*s;\n const T H = calcH(s, S);\n x = -s * sqrt2 * erf_inv(arg) \/ H;\n\n#if 0\n \/\/ slightly less accuracy, best to use iteration\n if ((x >= -S) && (abs(arg) != bound))\n {\n return x;\n }\n#endif\n\n T rerr = 0.0;\n size_t i = 0;\n T f;\n T fp;\n T upd;\n\n do\n {\n f = gfi(x, s) - g;\n fp = dgfidx(x, s);\n upd = -f \/ fp;\n x += upd;\n rerr = abs(upd)\/(abs(x) + good_relerror<T>());\n#ifdef DEVSIM_UNIT_TEST\n std::cout << i << \" \" << x << \" \" << rerr << \"\\n\";\n#endif\n ++i;\n } while ((rerr > good_relerror<T>()) && (i < 200));\n return x;\n}\n\n\ntemplate <typename T>\nT digfidx(T g, T s)\n{\n return 1.0 \/ dgfidx(igfi(g,s), s);\n}\n\ntemplate double gfi<double>(double, double);\ntemplate double dgfidx<double>(double, double);\ntemplate double igfi<double>(double, double);\ntemplate double digfidx<double>(double, double);\n\n#ifdef DEVSIM_EXTENDED_PRECISION\ntemplate float128 gfi<float128>(float128, float128);\ntemplate float128 dgfidx<float128>(float128, float128);\ntemplate float128 igfi<float128>(float128, float128);\ntemplate float128 digfidx<float128>(float128, float128);\n#endif\n\n#ifdef DEVSIM_UNIT_TEST\ntemplate <typename DoubleType>\nvoid unit()\n{\n DoubleType k_B = 1.380649e-23;\n DoubleType e = 1.602176634e-19;\n DoubleType T = 300;\n DoubleType sigma = 0.10;\n DoubleType s = (sigma*e)\/(k_B*T);\n DoubleType S = s*s;\n DoubleType V_0 = 0;\n DoubleType V_f = V_0-S*k_B*T\/e;\/\/ # (-0.65372119-1.2) ;\n DoubleType zeta = (V_f*e-V_0*e)\/(k_B*T);\n \/\/ zeta =-0.5\n DoubleType zeta_1 = (V_f*e-V_0*e-pow(sigma*e, 2)\/k_B*T)\/(k_B*T);\n\n DoubleType g= gfi(zeta,s);\n DoubleType dg= dgfidx(zeta,s);\n DoubleType ginv= igfi(g,s);\n DoubleType dginv= digfidx(g,s);\n\/\/ print(g,dg,ginv)\n std::cout << std::setprecision(std::numeric_limits<DoubleType>::max_digits10);\n std::cout\n << \" zeta\\t\" << zeta << \"\\n\"\n << \" gfi\\t\" << g << \"\\n\"\n << \" dgfidx\\t\" << dg << \"\\n\"\n << \" igfi\\t\" << ginv << \"\\n\"\n << \" digfidx\\t\" << dginv << \" \" << 1.0\/dginv << \"\\n\";\n\n}\n\nint main()\n{\n unit<double>();\n#ifdef DEVSIM_EXTENDED_PRECISION\n unit<float128>();\n#endif\n}\n#endif\n<commit_msg>update test<commit_after>\/***\nDEVSIM\nCopyright 2021 Devsim LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n***\/\n#include \"GaussFermi.hh\"\n#include \"BoostConstants.hh\"\n#include \"MiscMathFunc.hh\"\n#ifdef DEVSIM_EXTENDED_PRECISION\n#include \"Float128.hh\"\n#endif\n#include <utility>\n#include <cmath>\nusing std::abs;\n\n#ifdef DEVSIM_UNIT_TEST\n#include <iostream>\n#include <iomanip>\n#endif\n\n\/*\nImplementation of:\nhttps:\/\/doi.org\/10.1063\/1.3374475\n@article{doi:10.1063\/1.3374475,\nauthor = {Paasch,Gernot and Scheinert,Susanne },\ntitle = {Charge carrier density of organics with Gaussian density of states: Analytical approximation for the Gauss–Fermi integral},\njournal = {Journal of Applied Physics},\nvolume = {107},\nnumber = {10},\npages = {104501},\nyear = {2010},\ndoi = {10.1063\/1.3374475},\nURL = { https:\/\/doi.org\/10.1063\/1.3374475 },\neprint = { https:\/\/doi.org\/10.1063\/1.3374475 }\n}\n*\/\n\nnamespace {\ntemplate <typename T>\nstruct MC {\n static constexpr T sqrt2 = boost::math::constants::root_two<T>();\n static constexpr T sqrt2_pi = boost::math::constants::root_two<T>() * boost::math::constants::one_div_root_pi<T>();\n static constexpr T one_div_root_two_pi = boost::math::constants::one_div_root_two_pi<T>();\n};\n\ntemplate <typename T>\ninline T calcH_Impl(const T &s, const T &S)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n\n T H = sqrt2 \/ s * erfc_inv(exp(-0.5 * S));\n#ifdef DEVSIM_UNIT_TEST\n std::cout << std::setprecision(std::numeric_limits<T>::max_digits10);\n std::cout << \"DEBUG NEW H \" << s << \" \" << H << \"\\n\";\n#endif\n return H;\n}\n\ntemplate <typename T>\ninline T calcH(const T &s, const T &S)\n{\n thread_local auto p = std::make_pair(s, calcH_Impl(s, S));\n\n \/\/ Assume that s is constant across the same call in the same region\n if (p.first != s)\n {\n p = std::make_pair(s, calcH_Impl(s, S));\n }\n#if 0\n else\n {\n std::cout << \"DEBUG REUSE H\\n\";\n }\n#endif\n\n return p.second;\n}\n\ntemplate <typename T>\ninline T calcK(const T &s, const T &S, const T &H)\n{\n const T &sqrt2_pi = MC<T>::sqrt2_pi;\n\n T K = 2 * (1. - H \/ s * sqrt2_pi * exp(0.5 * S * (1. - H * H)));\n return K;\n}\n\n}\n\ntemplate <typename T>\nT gfi(T zeta, T s)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n const T S = s * s;\n\n T H = calcH(s, S);\n\n T value;\n if (zeta < -S)\n {\n const T K = calcK(s, S, H);\n value = exp(0.5 * S + zeta) \/ (exp(K*(zeta+S)) + 1);\n }\n else\n {\n value = 0.5 * erfc(-zeta \/ (s*sqrt2) * H);\n }\n\n return value;\n}\n\ntemplate <typename T>\nT dgfidx(T zeta, T s)\n{\n const T &sqrt2 = MC<T>::sqrt2;\n const T &sqrt2_pi = MC<T>::sqrt2_pi;\n\n const T S = s * s;\n\n T H = calcH(s, S);\n\n T dvalue;\n if (zeta < -S)\n {\n const T K = calcK(s, S, H);\n const T den_inv = 1. \/ (exp(K * (S + zeta)) + 1.);\n dvalue = exp(0.5 * S + zeta) * den_inv * (1. - K*exp(K * (S+zeta)) * den_inv);\n }\n else\n {\n const T &one_div_root_two_pi = MC<T>::one_div_root_two_pi;\n dvalue = one_div_root_two_pi * H \/ s * exp(-0.5 * pow(H*zeta,2)\/S);\n }\n\n return dvalue;\n}\n\n\/\/### inverse function for Gaussian Fermi Integral\n\nnamespace {\ntemplate <typename T>\nT good_relerror();\n\ntemplate <>\ndouble good_relerror()\n{\n return 1e-12;\n}\n\n#ifdef DEVSIM_EXTENDED_PRECISION\ntemplate <>\nfloat128 good_relerror()\n{\n return 1e-31;\n}\n#endif\n}\n\ntemplate <typename T>\nT igfi(T g, T s)\n{\n \/\/ using the Newton method\n \/\/ The initial guess\n \/\/ perhaps the degenerate approximation\n \/\/ or provided from the last call\n \/\/ improves speed\n T x = 0.0;\n \/\/printf(\"%d %1.15e %1.15e\\n\", -1, x, rerr);\n#ifdef DEVSIM_UNIT_TEST\n std::cout << std::setprecision(std::numeric_limits<T>::max_digits10);\n#endif\n T arg = 1. - 2. * g;\n\n static constexpr T bound = 1.0 - std::numeric_limits<T>::epsilon();\n\n \/\/ prevent infinite results\n if (arg <= -1.0)\n {\n arg = -bound;\n }\n else if (arg >= 1.0)\n {\n arg = bound;\n }\n\n const T &sqrt2 = MC<T>::sqrt2;\n \/\/ using the degenerate approximation\n const T S = s*s;\n const T H = calcH(s, S);\n x = -s * sqrt2 * erf_inv(arg) \/ H;\n\n#if 0\n \/\/ slightly less accuracy, best to use iteration\n if ((x >= -S) && (abs(arg) != bound))\n {\n return x;\n }\n#endif\n\n T rerr = 0.0;\n size_t i = 0;\n T f;\n T fp;\n T upd;\n\n do\n {\n f = gfi(x, s) - g;\n fp = dgfidx(x, s);\n upd = -f \/ fp;\n x += upd;\n rerr = abs(upd)\/(abs(x) + good_relerror<T>());\n#ifdef DEVSIM_UNIT_TEST\n std::cout << i << \" \" << x << \" \" << rerr << \"\\n\";\n#endif\n ++i;\n } while ((rerr > good_relerror<T>()) && (i < 200));\n return x;\n}\n\n\ntemplate <typename T>\nT digfidx(T g, T s)\n{\n return 1.0 \/ dgfidx(igfi(g,s), s);\n}\n\ntemplate double gfi<double>(double, double);\ntemplate double dgfidx<double>(double, double);\ntemplate double igfi<double>(double, double);\ntemplate double digfidx<double>(double, double);\n\n#ifdef DEVSIM_EXTENDED_PRECISION\ntemplate float128 gfi<float128>(float128, float128);\ntemplate float128 dgfidx<float128>(float128, float128);\ntemplate float128 igfi<float128>(float128, float128);\ntemplate float128 digfidx<float128>(float128, float128);\n#endif\n\n#ifdef DEVSIM_UNIT_TEST\ntemplate <typename DoubleType>\nvoid unit()\n{\n for (size_t j = 2; j <= 8; j += 2)\n {\n DoubleType s = static_cast<DoubleType>(j);\n for (size_t i = 0; i <= 10; ++i)\n {\n DoubleType zeta = 7 * i - 70.;\n DoubleType g= gfi(zeta,s);\n DoubleType dg= dgfidx(zeta,s);\n DoubleType ginv= igfi(g,s);\n DoubleType dginv= digfidx(g,s);\n std::cout\n << zeta << \" \"\n << g << \" \"\n << dg << \" \"\n << ginv << \" \"\n << dginv << \" \" << 1.0\/dginv << \"\\n\";\n }\n }\n#if 0\n DoubleType k_B = 1.380649e-23;\n DoubleType e = 1.602176634e-19;\n DoubleType T = 300;\n DoubleType sigma = 0.10;\n DoubleType s = (sigma*e)\/(k_B*T);\n DoubleType S = s*s;\n DoubleType V_0 = 0;\n DoubleType V_f = V_0-S*k_B*T\/e;\/\/ # (-0.65372119-1.2) ;\n DoubleType zeta = (V_f*e-V_0*e)\/(k_B*T);\n \/\/ zeta =-0.5\n DoubleType zeta_1 = (V_f*e-V_0*e-pow(sigma*e, 2)\/k_B*T)\/(k_B*T);\n\n DoubleType g= gfi(zeta,s);\n DoubleType dg= dgfidx(zeta,s);\n DoubleType ginv= igfi(g,s);\n DoubleType dginv= digfidx(g,s);\n\/\/ print(g,dg,ginv)\n std::cout << std::setprecision(std::numeric_limits<DoubleType>::max_digits10);\n std::cout\n << \" zeta\\t\" << zeta << \"\\n\"\n << \" gfi\\t\" << g << \"\\n\"\n << \" dgfidx\\t\" << dg << \"\\n\"\n << \" igfi\\t\" << ginv << \"\\n\"\n << \" digfidx\\t\" << dginv << \" \" << 1.0\/dginv << \"\\n\";\n#endif\n}\n\nint main()\n{\n unit<double>();\n#ifdef DEVSIM_EXTENDED_PRECISION\n unit<float128>();\n#endif\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <MemoryManager.hh>\n\n#include <Memory.hh>\n#include <Debug.hh>\n\n#include <cstdio>\n\nMemoryManager* MemoryManager::self = 0;\n\nMemoryManager::MemoryManager()\n : freeList()\n{\n \/\/ empty!\n}\n\nvoid*\nMemoryManager::operator new(std::size_t \/*size*\/, void *placement)\n{\n return placement;\n}\n\nMemoryManager::Segment*\nMemoryManager::headerOf(void* data)\n{\n return reinterpret_cast<Segment*>(uintptr_t(data) - sizeof(Segment));\n}\n\nvoid\nMemoryManager::init()\n{\n printf(\"Intializing Memory Manager\\n\");\n void* object = allocateBackend(sizeof(MemoryManager));\n\n MemoryManager::self = new (object) MemoryManager();\n\n printf(\"Memory Manager at %p\\n\", (void* )MemoryManager::self);\n}\n\nMemoryManager&\nMemoryManager::get()\n{\n return *self;\n}\n\nvoid*\nMemoryManager::allocateBackend(std::size_t size)\n{\n std::size_t rsize = roundTo(size, PageSize);\n void* data = reinterpret_cast<void*>(Memory::sbrk(rsize));\n\n KASSERT(data != 0);\n\n return data;\n}\n\nvoid*\nMemoryManager::allocate(std::size_t size)\n{\n for (auto& s : freeList)\n {\n if (s.getSize() >= size)\n {\n\t freeList.remove(&s);\n\t s.markAllocated();\n#ifdef DEBUG\n\t printf(\"Debug: allocating from freelist\\n\");\n#endif\n\t return reinterpret_cast<void*>(s.getAddress());\n }\n }\n\n#ifdef DEBUG\n printf(\"Debug: allocating from heap\\n\");\n#endif\n\n std::size_t rsize = roundTo(size + sizeof(Segment), PageSize);\n\/\/ Segment* segment = reinterpret_cast<Segment*>(allocateBackend(rsize));\n Segment* segment = new (reinterpret_cast<void*>(allocateBackend(rsize))) Segment;\n\n segment->setSize(rsize - sizeof(Segment));\n segment->setAddress(reinterpret_cast<uintptr_t>(segment + 1));\n segment->markAllocated();\n\n return reinterpret_cast<void*>(segment->getAddress());\n}\n\nvoid\nMemoryManager::deallocate(void *data)\n{\n Segment* segment = headerOf(data);\n\n KASSERT(segment->isAllocated());\n segment->markAllocated();\n\n#ifdef DEBUG\n printf(\"Putting to freelist\\n\");\n#endif\n\n freeList.insertLast(segment);\n}\n\nvoid\nMemoryManager::printStatistics()\n{\n printf(\"Allocator statistics:\\n\");\n printf(\"Free segments: %zu\\n\", freeList.getCount());\n\n for (auto& s : freeList)\n {\n printf(\"Segment %p: size: %zu, address: %p\\n\", &s, s.getSize(), (void* )s.getAddress());\n }\n}\n\n<commit_msg>use memory mapped backend<commit_after>#include <MemoryManager.hh>\n\n#include <Memory.hh>\n#include <Debug.hh>\n\n#include <cstdio>\n\nMemoryManager* MemoryManager::self = 0;\n\nMemoryManager::MemoryManager()\n : freeList()\n{\n \/\/ empty!\n}\n\nvoid*\nMemoryManager::operator new(std::size_t \/*size*\/, void *placement)\n{\n return placement;\n}\n\nMemoryManager::Segment*\nMemoryManager::headerOf(void* data)\n{\n return reinterpret_cast<Segment*>(uintptr_t(data) - sizeof(Segment));\n}\n\nvoid\nMemoryManager::init()\n{\n printf(\"Intializing Memory Manager\\n\");\n void* object = allocateBackend(sizeof(MemoryManager));\n\n MemoryManager::self = new (object) MemoryManager();\n\n printf(\"Memory Manager at %p\\n\", (void* )MemoryManager::self);\n}\n\nMemoryManager&\nMemoryManager::get()\n{\n return *self;\n}\n\nvoid*\nMemoryManager::allocateBackend(std::size_t size)\n{\n std::size_t rsize = roundTo(size, PageSize);\n\n void* data = reinterpret_cast<void*>(Memory::mapAnonymousRegion(rsize));\n\n KASSERT(data != 0);\n\n return data;\n}\n\nvoid*\nMemoryManager::allocate(std::size_t size)\n{\n for (auto& s : freeList)\n {\n if (s.getSize() >= size)\n {\n\t freeList.remove(&s);\n\t s.markAllocated();\n#ifdef DEBUG\n\t printf(\"Debug: allocating from freelist\\n\");\n#endif\n\t return reinterpret_cast<void*>(s.getAddress());\n }\n }\n\n#ifdef DEBUG\n printf(\"Debug: allocating from heap\\n\");\n#endif\n\n std::size_t rsize = roundTo(size + sizeof(Segment), PageSize);\n\/\/ Segment* segment = reinterpret_cast<Segment*>(allocateBackend(rsize));\n Segment* segment = new (reinterpret_cast<void*>(allocateBackend(rsize))) Segment;\n\n segment->setSize(rsize - sizeof(Segment));\n segment->setAddress(reinterpret_cast<uintptr_t>(segment + 1));\n segment->markAllocated();\n\n return reinterpret_cast<void*>(segment->getAddress());\n}\n\nvoid\nMemoryManager::deallocate(void *data)\n{\n Segment* segment = headerOf(data);\n\n KASSERT(segment->isAllocated());\n segment->markAllocated();\n\n#ifdef DEBUG\n printf(\"Putting to freelist\\n\");\n#endif\n\n freeList.insertLast(segment);\n}\n\nvoid\nMemoryManager::printStatistics()\n{\n printf(\"Allocator statistics:\\n\");\n printf(\"Free segments: %zu\\n\", freeList.getCount());\n\n for (auto& s : freeList)\n {\n printf(\"Segment %p: size: %zu, address: %p\\n\", &s, s.getSize(), (void* )s.getAddress());\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include <autowiring\/CoreThread.h>\n#include CHRONO_HEADER\n#include THREAD_HEADER\n\nclass AutoPacketFactoryTest:\n public testing::Test\n{};\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has not yet been started should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, StopReallyStops) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->ShouldStop()) << \"Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory\";\n}\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has already been stopped should throw an exception\";\n}\n\nclass IssuesPacketWaitsThenQuits:\n public CoreThread\n{\npublic:\n IssuesPacketWaitsThenQuits(void) :\n m_hasQuit(false)\n {\n \/\/ Note: Don't do this in practice. This only works because we only inject this type\n \/\/ into a context that's already running; normally, creating a packet from our ctor can\n \/\/ cause an exception if we are being injected before Initiate is called.\n AutoRequired<AutoPacketFactory> factory;\n m_packet = factory->NewPacket();\n }\n\n bool m_hasQuit;\n std::shared_ptr<AutoPacket> m_packet;\n\n void Run(void) override {\n \/\/ Move shared pointer locally:\n std::shared_ptr<AutoPacket> packet;\n std::swap(packet, m_packet);\n\n \/\/ Just wait a bit, then return, just like we said we would\n this->ThreadSleep(std::chrono::milliseconds(50));\n\n \/\/ Update our variable and then return out:\n m_hasQuit = true;\n }\n};\n\n\nTEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {\n AutoCurrentContext()->Initiate();\n\n \/\/ Create a factory in our context, factory had better be started:\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->IsRunning()) << \"Factory was not started even though it was a member of an initiated context\";\n\n \/\/ Make the thread create and hold a packet, and then return\n AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;\n \n \/\/ Shutdown context\n AutoCurrentContext()->SignalShutdown();\n\n \/\/ Now we're going to try to run down the factory:\n factory->Wait();\n\n \/\/ Verify that the thread has quit:\n ASSERT_TRUE(ipwtq->m_hasQuit) << \"AutoPacketFactory::Wait returned prematurely\";\n}\n\nclass HoldsAutoPacketFactoryReference {\npublic:\n HoldsAutoPacketFactoryReference(void):\n m_value(0)\n {}\n\n AutoRequired<AutoPacketFactory> m_factory;\n int m_value;\n\n \/\/ Just a dummy AutoFilter method so that this class is recognized as an AutoFilter\n void AutoFilter(int value) {\n m_value = value;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {\n std::weak_ptr<CoreContext> ctxtWeak;\n std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;\n std::shared_ptr<AutoPacket> packet;\n\n {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);\n ctxt->Initiate();\n \n \/\/ A weak pointer is used to detect object destruction\n ctxtWeak = ctxt;\n hapfrWeak = hapfr;\n\n \/\/ Trivial validation-of-reciept:\n AutoRequired<AutoPacketFactory> factory;\n {\n auto trivial = factory->NewPacket();\n trivial->Decorate((int) 54);\n ASSERT_EQ(54, hapfr->m_value) << \"A simple packet was not received as expected by an AutoFilter\";\n }\n\n \/\/ Create a packet which will force in a back-reference:\n packet = factory->NewPacket();\n\n \/\/ Terminate the context:\n ctxt->SignalShutdown();\n\n \/\/ Verify that we can still decorate the packet and also that the packet is delivered to the factory:\n packet->Decorate((int) 55);\n\n \/\/ Relock, verify the value was received by the hapfr:\n ASSERT_EQ(55, hapfr->m_value) << \"AutoFilter did not receive a packet as expected\";\n }\n\n \/\/ The context cannot go out of socpe until all packets in the context are out of scope\n ASSERT_FALSE(ctxtWeak.expired()) << \"Context went out of scope before all packets were finished being processed\";\n\n \/\/ Now we can release the packet and verify that everything gets cleaned up:\n packet.reset();\n ASSERT_TRUE(ctxtWeak.expired()) << \"AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down\";\n ASSERT_TRUE(hapfrWeak.expired()) << \"The last packet from a factory was released; this should have resulted in teardown, but it did not\";\n}\n\nclass DelaysAutoPacketsOneMS {\npublic:\n DelaysAutoPacketsOneMS(void) {}\n\n void AutoFilter(int value) {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketStatistics) {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<DelaysAutoPacketsOneMS> dapoms(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n int numPackets = 20;\n\n \/\/ Send 20 packets which should all be delayed 1ms\n for (int i = 0; i < numPackets; ++i) {\n auto packet = factory->NewPacket();\n packet->Decorate(i);\n }\n\n \/\/ Shutdown our context, and rundown our factory\n ctxt->SignalShutdown();\n factory->Wait();\n\n \/\/ Ensure that the statistics are not too wrong\n \/\/ We delayed each packet by one ms, and our statistics are given in nanoseconds\n double packetDelay = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(1)).count();\n ASSERT_EQ(numPackets, factory->GetTotalPacketCount()) << \"The factory did not get enough packets\";\n\n ASSERT_LE(packetDelay, factory->GetMeanPacketLifetime()) << \"The mean packet lifetime was less than the delay on each packet\";\n}\n\nTEST_F(AutoPacketFactoryTest, AddSubscriberTest) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n bool first_called = false;\n bool second_called = false;\n\n factory->AddSubscriber(AutoFilterDescriptor([&first_called] (int) {first_called = true;}));\n *factory += [&second_called] (int) {second_called = true;};\n\n auto packet = factory->NewPacket();\n\n ASSERT_FALSE(first_called) << \"Normal subscriber called too early\";\n ASSERT_FALSE(second_called) << \"Subscriber added with operator+= called too early\";\n\n packet->DecorateImmediate(int(0));\n\n ASSERT_TRUE(first_called) << \"Normal subscriber never called\";\n ASSERT_TRUE(second_called) << \"Subscriber added with operator+= never called\";\n}\n\nTEST_F(AutoPacketFactoryTest, MultiDecorateTest) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n int called = 0;\n\n *factory += [&called] (int& out) { out = called++; };\n *factory += [&called] (int& out) { out = called++; };\n *factory += [&called] (const int* vals[]) {\n ASSERT_NE(nullptr, vals);\n called++;\n int i;\n for (i = 0; vals[i] != nullptr; i++) {\n EXPECT_EQ(i, *(vals[i])) << \"Incorrect values were added to the packet\";\n }\n EXPECT_EQ(2, i) << \"The wrong number of values were added to the packet\";\n };\n ASSERT_EQ(0, called);\n\n auto packet = factory->NewPacket();\n\n ASSERT_EQ(3, called);\n}\n<commit_msg>Adding a small test to verify extraction on a multi-in type<commit_after>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include <autowiring\/CoreThread.h>\n#include CHRONO_HEADER\n#include THREAD_HEADER\n\nclass AutoPacketFactoryTest:\n public testing::Test\n{};\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has not yet been started should throw an exception\";\n}\n\nTEST_F(AutoPacketFactoryTest, StopReallyStops) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->ShouldStop()) << \"Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory\";\n}\n\nTEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {\n AutoCurrentContext()->SignalShutdown();\n\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_THROW(factory->NewPacket(), autowiring_error) << \"Issuing a packet in a context that has already been stopped should throw an exception\";\n}\n\nclass IssuesPacketWaitsThenQuits:\n public CoreThread\n{\npublic:\n IssuesPacketWaitsThenQuits(void) :\n m_hasQuit(false)\n {\n \/\/ Note: Don't do this in practice. This only works because we only inject this type\n \/\/ into a context that's already running; normally, creating a packet from our ctor can\n \/\/ cause an exception if we are being injected before Initiate is called.\n AutoRequired<AutoPacketFactory> factory;\n m_packet = factory->NewPacket();\n }\n\n bool m_hasQuit;\n std::shared_ptr<AutoPacket> m_packet;\n\n void Run(void) override {\n \/\/ Move shared pointer locally:\n std::shared_ptr<AutoPacket> packet;\n std::swap(packet, m_packet);\n\n \/\/ Just wait a bit, then return, just like we said we would\n this->ThreadSleep(std::chrono::milliseconds(50));\n\n \/\/ Update our variable and then return out:\n m_hasQuit = true;\n }\n};\n\n\nTEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {\n AutoCurrentContext()->Initiate();\n\n \/\/ Create a factory in our context, factory had better be started:\n AutoRequired<AutoPacketFactory> factory;\n ASSERT_TRUE(factory->IsRunning()) << \"Factory was not started even though it was a member of an initiated context\";\n\n \/\/ Make the thread create and hold a packet, and then return\n AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;\n \n \/\/ Shutdown context\n AutoCurrentContext()->SignalShutdown();\n\n \/\/ Now we're going to try to run down the factory:\n factory->Wait();\n\n \/\/ Verify that the thread has quit:\n ASSERT_TRUE(ipwtq->m_hasQuit) << \"AutoPacketFactory::Wait returned prematurely\";\n}\n\nclass HoldsAutoPacketFactoryReference {\npublic:\n HoldsAutoPacketFactoryReference(void):\n m_value(0)\n {}\n\n AutoRequired<AutoPacketFactory> m_factory;\n int m_value;\n\n \/\/ Just a dummy AutoFilter method so that this class is recognized as an AutoFilter\n void AutoFilter(int value) {\n m_value = value;\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {\n std::weak_ptr<CoreContext> ctxtWeak;\n std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;\n std::shared_ptr<AutoPacket> packet;\n\n {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);\n ctxt->Initiate();\n \n \/\/ A weak pointer is used to detect object destruction\n ctxtWeak = ctxt;\n hapfrWeak = hapfr;\n\n \/\/ Trivial validation-of-reciept:\n AutoRequired<AutoPacketFactory> factory;\n {\n auto trivial = factory->NewPacket();\n trivial->Decorate((int) 54);\n ASSERT_EQ(54, hapfr->m_value) << \"A simple packet was not received as expected by an AutoFilter\";\n }\n\n \/\/ Create a packet which will force in a back-reference:\n packet = factory->NewPacket();\n\n \/\/ Terminate the context:\n ctxt->SignalShutdown();\n\n \/\/ Verify that we can still decorate the packet and also that the packet is delivered to the factory:\n packet->Decorate((int) 55);\n\n \/\/ Relock, verify the value was received by the hapfr:\n ASSERT_EQ(55, hapfr->m_value) << \"AutoFilter did not receive a packet as expected\";\n }\n\n \/\/ The context cannot go out of socpe until all packets in the context are out of scope\n ASSERT_FALSE(ctxtWeak.expired()) << \"Context went out of scope before all packets were finished being processed\";\n\n \/\/ Now we can release the packet and verify that everything gets cleaned up:\n packet.reset();\n ASSERT_TRUE(ctxtWeak.expired()) << \"AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down\";\n ASSERT_TRUE(hapfrWeak.expired()) << \"The last packet from a factory was released; this should have resulted in teardown, but it did not\";\n}\n\nclass DelaysAutoPacketsOneMS {\npublic:\n DelaysAutoPacketsOneMS(void) {}\n\n void AutoFilter(int value) {\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n }\n};\n\nTEST_F(AutoPacketFactoryTest, AutoPacketStatistics) {\n \/\/ Create a context, fill it up, kick it off:\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<DelaysAutoPacketsOneMS> dapoms(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n int numPackets = 20;\n\n \/\/ Send 20 packets which should all be delayed 1ms\n for (int i = 0; i < numPackets; ++i) {\n auto packet = factory->NewPacket();\n packet->Decorate(i);\n }\n\n \/\/ Shutdown our context, and rundown our factory\n ctxt->SignalShutdown();\n factory->Wait();\n\n \/\/ Ensure that the statistics are not too wrong\n \/\/ We delayed each packet by one ms, and our statistics are given in nanoseconds\n double packetDelay = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(1)).count();\n ASSERT_EQ(numPackets, factory->GetTotalPacketCount()) << \"The factory did not get enough packets\";\n\n ASSERT_LE(packetDelay, factory->GetMeanPacketLifetime()) << \"The mean packet lifetime was less than the delay on each packet\";\n}\n\nTEST_F(AutoPacketFactoryTest, AddSubscriberTest) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n bool first_called = false;\n bool second_called = false;\n\n factory->AddSubscriber(AutoFilterDescriptor([&first_called] (int) {first_called = true;}));\n *factory += [&second_called] (int) {second_called = true;};\n\n auto packet = factory->NewPacket();\n\n ASSERT_FALSE(first_called) << \"Normal subscriber called too early\";\n ASSERT_FALSE(second_called) << \"Subscriber added with operator+= called too early\";\n\n packet->DecorateImmediate(int(0));\n\n ASSERT_TRUE(first_called) << \"Normal subscriber never called\";\n ASSERT_TRUE(second_called) << \"Subscriber added with operator+= never called\";\n}\n\nTEST_F(AutoPacketFactoryTest, EnumerateDecorationsTest) {\n auto sample = [](const int* vals []) {};\n AutoFilterDescriptor desc(sample);\n\n size_t i = 0;\n for (auto* pCur = desc.GetAutoFilterInput(); *pCur; pCur++)\n i++;\n\n ASSERT_EQ(1, i) << \"AutoFilterDescriptor parsed an incorrect number of arguments from a lambda\";\n}\n\nTEST_F(AutoPacketFactoryTest, MultiDecorateTest) {\n AutoCreateContext ctxt;\n CurrentContextPusher pshr(ctxt);\n AutoRequired<AutoPacketFactory> factory(ctxt);\n ctxt->Initiate();\n\n int called = 0;\n\n *factory += [&called] (int& out) { out = called++; };\n *factory += [&called] (int& out) { out = called++; };\n *factory += [&called] (const int* vals[]) {\n ASSERT_NE(nullptr, vals);\n called++;\n int i;\n for (i = 0; vals[i] != nullptr; i++) {\n EXPECT_EQ(i, *(vals[i])) << \"Incorrect values were added to the packet\";\n }\n EXPECT_EQ(2, i) << \"The wrong number of values were added to the packet\";\n };\n ASSERT_EQ(0, called);\n\n auto packet = factory->NewPacket();\n\n ASSERT_EQ(3, called);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file quintic_spiral_path.cpp\n **\/\n\n#include \"modules\/planning\/math\/curve1d\/quintic_spiral_path.h\"\n\n#include \"glog\/logging.h\"\n\nnamespace apollo {\nnamespace planning {\n\nQuinticSpiralPath::QuinticSpiralPath(\n const double x0, const double dx0, const double ddx0, const double x1,\n const double dx1, const double ddx1, const double p)\n : QuinticPolynomialCurve1d(x0, dx0, ddx0, x1, dx1, ddx1, p) {\n CHECK(p > 0.0);\n\n double p2 = p * p;\n double p3 = p2 * p;\n double p4 = p3 * p;\n double p5 = p2 * p3;\n double p6 = p3 * p3;\n\n \/\/ derive a\n \/\/ double a = -6.0 * x0 \/ p5 - 3.0 * dx0 \/ p4 - 0.5 * ddx0 \/ p3 + 6.0 * x1 \/\n \/\/ p5 - 3.0 * dx1 \/ p4 + 0.5 * ddx1 \/ p3;\n coef_deriv_[0][0] = -6.0 \/ p5;\n\n coef_deriv_[0][1] = -3.0 \/ p4;\n\n coef_deriv_[0][2] = -0.5 \/ p3;\n\n coef_deriv_[0][3] = 6.0 \/ p5;\n\n coef_deriv_[0][4] = -3.0 \/ p4;\n\n coef_deriv_[0][5] = 0.5 \/ p3;\n\n coef_deriv_[0][6] = 30.0 * x0 \/ p6 + 12.0 * dx0 \/ p5 + 1.5 * ddx0 \/ p4 -\n 30.0 * x1 \/ p6 + 12.0 * dx1 \/ p5 - 1.5 * ddx1 \/ p4;\n\n \/\/ derive b\n \/\/ double b = 15.0 * x0 \/ p4 + 8.0 * dx0 \/ p3 + 1.5 * ddx0 \/ p2 - 15.0 * x1 \/\n \/\/ p4 + 7.0 * dx1 \/ p3 - ddx1 \/ p2;\n coef_deriv_[1][0] = 15.0 \/ p4;\n\n coef_deriv_[1][1] = 8.0 \/ p3;\n\n coef_deriv_[1][2] = 1.5 \/ p2;\n\n coef_deriv_[1][3] = -15.0 \/ p4;\n\n coef_deriv_[1][4] = 7.0 \/ p3;\n\n coef_deriv_[1][5] = -1.0 \/ p2;\n\n coef_deriv_[1][6] = -60.0 * x0 \/ p5 - 24.0 * dx0 \/ p4 - 3.0 * ddx0 \/ p3 +\n 60.0 * x1 \/ p5 - 21.0 * dx1 \/ p4 + 2.0 * ddx1 \/ p3;\n\n \/\/ derive c\n \/\/ double c = -10.0 * x0 \/ p3 - 6.0 * dx0 \/ p2 - 1.5 * ddx0 \/ p + 10.0 * x1 \/\n \/\/ p3 - 4.0 * dx1 \/ p2 + 0.5 * ddx1 \/ p;\n coef_deriv_[2][0] = -10.0 \/ p3;\n\n coef_deriv_[2][1] = -6.0 \/ p2;\n\n coef_deriv_[2][2] = -1.5 \/ p;\n\n coef_deriv_[2][3] = 10.0 \/ p3;\n\n coef_deriv_[2][4] = -4.0 \/ p2;\n\n coef_deriv_[2][5] = 0.5 \/ p;\n\n coef_deriv_[2][6] = 30.0 * x0 \/ p4 + 12.0 * dx0 \/ p3 + 1.5 * ddx0 \/ p2 -\n 30.0 * x1 \/ p4 + 8.0 * dx1 \/ p3 - 0.5 * ddx1 \/ p2;\n\n \/\/ derive d\n \/\/ double d = 0.5 * ddx0;\n coef_deriv_[3][0] = 0.0;\n\n coef_deriv_[3][1] = 0.0;\n\n coef_deriv_[3][2] = 0.5;\n\n coef_deriv_[3][3] = 0.0;\n\n coef_deriv_[3][4] = 0.0;\n\n coef_deriv_[3][5] = 0.0;\n\n coef_deriv_[3][6] = 0.0;\n\n \/\/ derive e\n \/\/ double e = dx0;\n coef_deriv_[4][0] = 0.0;\n\n coef_deriv_[4][1] = 1.0;\n\n coef_deriv_[4][2] = 0.0;\n\n coef_deriv_[4][3] = 0.0;\n\n coef_deriv_[4][4] = 0.0;\n\n coef_deriv_[4][5] = 0.0;\n\n coef_deriv_[4][6] = 0.0;\n\n \/\/ derive f\n \/\/ double f = x0;\n coef_deriv_[5][0] = 1.0;\n\n coef_deriv_[5][1] = 0.0;\n\n coef_deriv_[5][2] = 0.0;\n\n coef_deriv_[5][3] = 0.0;\n\n coef_deriv_[5][4] = 0.0;\n\n coef_deriv_[5][5] = 0.0;\n\n coef_deriv_[5][6] = 0.0;\n}\n\nQuinticSpiralPath::QuinticSpiralPath(\n const std::array<double, 3>& start, const std::array<double, 3>& end,\n const double delta_s)\n : QuinticSpiralPath(start[0], start[1], start[2], end[0], end[1],\n end[2], delta_s) {}\n\ndouble QuinticSpiralPath::DeriveTheta(const std::size_t param_index,\n const double r) const {\n double s = param_ * r;\n double s2 = s * s;\n double s3 = s2 * s;\n double s4 = s2 * s2;\n double s5 = s3 * s2;\n\n double derivative =\n coef_deriv_[0][param_index] * s5 + coef_deriv_[1][param_index] * s4 +\n coef_deriv_[2][param_index] * s3 + coef_deriv_[3][param_index] * s2 +\n coef_deriv_[4][param_index] * s + coef_deriv_[5][param_index];\n\n if (param_index == DELTA_S) {\n derivative += coef_[0] * 5.0 * s4 * r + coef_[1] * 4.0 * s3 * r +\n coef_[2] * 3.0 * s2 * r + coef_[3] * 2.0 * s * r +\n coef_[4] * r;\n }\n return derivative;\n}\n\ndouble QuinticSpiralPath::DeriveKappaDerivative(\n const std::size_t param_index, const double r) const {\n double s = param_ * r;\n double s2 = s * s;\n double s3 = s2 * s;\n\n double derivative = 20.0 * coef_deriv_[0][param_index] * s3 +\n 12.0 * coef_deriv_[1][param_index] * s2 +\n 6.0 * coef_deriv_[2][param_index] * s +\n 2.0 * coef_deriv_[3][param_index];\n\n if (param_index == DELTA_S) {\n derivative += 20.0 * coef_[0] * 3.0 * s2 * r +\n 12.0 * coef_[1] * 2.0 * s * r + 6.0 * coef_[2] * r;\n }\n return derivative;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: fixed unmatched indices in quintic spiral path<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file quintic_spiral_path.cpp\n **\/\n\n#include \"modules\/planning\/math\/curve1d\/quintic_spiral_path.h\"\n\n#include \"glog\/logging.h\"\n\nnamespace apollo {\nnamespace planning {\n\nQuinticSpiralPath::QuinticSpiralPath(\n const double x0, const double dx0, const double ddx0, const double x1,\n const double dx1, const double ddx1, const double p)\n : QuinticPolynomialCurve1d(x0, dx0, ddx0, x1, dx1, ddx1, p) {\n CHECK(p > 0.0);\n\n double p2 = p * p;\n double p3 = p2 * p;\n double p4 = p3 * p;\n double p5 = p2 * p3;\n double p6 = p3 * p3;\n\n \/\/ derive a\n \/\/ double a = -6.0 * x0 \/ p5 - 3.0 * dx0 \/ p4 - 0.5 * ddx0 \/ p3 + 6.0 * x1 \/\n \/\/ p5 - 3.0 * dx1 \/ p4 + 0.5 * ddx1 \/ p3;\n coef_deriv_[5][0] = -6.0 \/ p5;\n\n coef_deriv_[5][1] = -3.0 \/ p4;\n\n coef_deriv_[5][2] = -0.5 \/ p3;\n\n coef_deriv_[5][3] = 6.0 \/ p5;\n\n coef_deriv_[5][4] = -3.0 \/ p4;\n\n coef_deriv_[5][5] = 0.5 \/ p3;\n\n coef_deriv_[5][6] = 30.0 * x0 \/ p6 + 12.0 * dx0 \/ p5 + 1.5 * ddx0 \/ p4 -\n 30.0 * x1 \/ p6 + 12.0 * dx1 \/ p5 - 1.5 * ddx1 \/ p4;\n\n \/\/ derive b\n \/\/ double b = 15.0 * x0 \/ p4 + 8.0 * dx0 \/ p3 + 1.5 * ddx0 \/ p2 - 15.0 * x1 \/\n \/\/ p4 + 7.0 * dx1 \/ p3 - ddx1 \/ p2;\n coef_deriv_[4][0] = 15.0 \/ p4;\n\n coef_deriv_[4][1] = 8.0 \/ p3;\n\n coef_deriv_[4][2] = 1.5 \/ p2;\n\n coef_deriv_[4][3] = -15.0 \/ p4;\n\n coef_deriv_[4][4] = 7.0 \/ p3;\n\n coef_deriv_[4][5] = -1.0 \/ p2;\n\n coef_deriv_[4][6] = -60.0 * x0 \/ p5 - 24.0 * dx0 \/ p4 - 3.0 * ddx0 \/ p3 +\n 60.0 * x1 \/ p5 - 21.0 * dx1 \/ p4 + 2.0 * ddx1 \/ p3;\n\n \/\/ derive c\n \/\/ double c = -10.0 * x0 \/ p3 - 6.0 * dx0 \/ p2 - 1.5 * ddx0 \/ p + 10.0 * x1 \/\n \/\/ p3 - 4.0 * dx1 \/ p2 + 0.5 * ddx1 \/ p;\n coef_deriv_[3][0] = -10.0 \/ p3;\n\n coef_deriv_[3][1] = -6.0 \/ p2;\n\n coef_deriv_[3][2] = -1.5 \/ p;\n\n coef_deriv_[3][3] = 10.0 \/ p3;\n\n coef_deriv_[3][4] = -4.0 \/ p2;\n\n coef_deriv_[3][5] = 0.5 \/ p;\n\n coef_deriv_[3][6] = 30.0 * x0 \/ p4 + 12.0 * dx0 \/ p3 + 1.5 * ddx0 \/ p2 -\n 30.0 * x1 \/ p4 + 8.0 * dx1 \/ p3 - 0.5 * ddx1 \/ p2;\n\n \/\/ derive d\n \/\/ double d = 0.5 * ddx0;\n coef_deriv_[2][0] = 0.0;\n\n coef_deriv_[2][1] = 0.0;\n\n coef_deriv_[2][2] = 0.5;\n\n coef_deriv_[2][3] = 0.0;\n\n coef_deriv_[2][4] = 0.0;\n\n coef_deriv_[2][5] = 0.0;\n\n coef_deriv_[2][6] = 0.0;\n\n \/\/ derive e\n \/\/ double e = dx0;\n coef_deriv_[1][0] = 0.0;\n\n coef_deriv_[1][1] = 1.0;\n\n coef_deriv_[1][2] = 0.0;\n\n coef_deriv_[1][3] = 0.0;\n\n coef_deriv_[1][4] = 0.0;\n\n coef_deriv_[1][5] = 0.0;\n\n coef_deriv_[1][6] = 0.0;\n\n \/\/ derive f\n \/\/ double f = x0;\n coef_deriv_[0][0] = 1.0;\n\n coef_deriv_[0][1] = 0.0;\n\n coef_deriv_[0][2] = 0.0;\n\n coef_deriv_[0][3] = 0.0;\n\n coef_deriv_[0][4] = 0.0;\n\n coef_deriv_[0][5] = 0.0;\n\n coef_deriv_[0][6] = 0.0;\n}\n\nQuinticSpiralPath::QuinticSpiralPath(\n const std::array<double, 3>& start, const std::array<double, 3>& end,\n const double delta_s)\n : QuinticSpiralPath(start[0], start[1], start[2], end[0], end[1],\n end[2], delta_s) {}\n\ndouble QuinticSpiralPath::DeriveTheta(const std::size_t param_index,\n const double r) const {\n double s = param_ * r;\n double s2 = s * s;\n double s3 = s2 * s;\n double s4 = s2 * s2;\n double s5 = s3 * s2;\n\n double derivative =\n coef_deriv_[5][param_index] * s5 + coef_deriv_[4][param_index] * s4 +\n coef_deriv_[3][param_index] * s3 + coef_deriv_[2][param_index] * s2 +\n coef_deriv_[1][param_index] * s + coef_deriv_[0][param_index];\n\n if (param_index == DELTA_S) {\n derivative += coef_[5] * 5.0 * s4 * r + coef_[4] * 4.0 * s3 * r +\n coef_[3] * 3.0 * s2 * r + coef_[2] * 2.0 * s * r +\n coef_[1] * r;\n }\n return derivative;\n}\n\ndouble QuinticSpiralPath::DeriveKappaDerivative(\n const std::size_t param_index, const double r) const {\n double s = param_ * r;\n double s2 = s * s;\n double s3 = s2 * s;\n\n double derivative = 20.0 * coef_deriv_[5][param_index] * s3 +\n 12.0 * coef_deriv_[4][param_index] * s2 +\n 6.0 * coef_deriv_[3][param_index] * s +\n 2.0 * coef_deriv_[2][param_index];\n\n if (param_index == DELTA_S) {\n derivative += 20.0 * coef_[5] * 3.0 * s2 * r +\n 12.0 * coef_[4] * 2.0 * s * r + 6.0 * coef_[3] * r;\n }\n return derivative;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Framework\/Assert.h\"\n#include \"SurgSim\/Framework\/Timer.h\"\n\nnamespace SurgSim {\nnamespace Framework {\n\nTimer::Timer() :\n\tm_stopped(true), m_maxNumberOfFrames(100), m_clockFails(0)\n{\n\tstart();\n}\n\nvoid Timer::start()\n{\n\tm_frameDurations.clear();\n\tm_clockFails = 0;\n\tbeginFrame();\n}\n\nvoid Timer::beginFrame()\n{\n\tm_lastTime = now();\n}\n\nvoid Timer::endFrame()\n{\n\tTimerTimePoint currentTime = now();\n\tm_frameDurations.push_back(currentTime - m_lastTime);\n\tif (m_frameDurations.size() > m_maxNumberOfFrames)\n\t{\n\t\tm_frameDurations.pop_front();\n\t}\n\tm_lastTime = currentTime;\n}\n\ndouble Timer::getAverageFramePeriod() const\n{\n\tSURGSIM_ASSERT(m_frameDurations.size() > 0) <<\n\t\t\"Attempted to access the last frame period for a Timer with no frames.\\n\";\n\tTimerDuration cumulativeTime;\n\tfor (auto it = m_frameDurations.begin(); it != m_frameDurations.end(); ++it)\n\t{\n\t\tcumulativeTime += *it;\n\t}\n\treturn cumulativeTime.count() \/ m_frameDurations.size();\n}\n\ndouble Timer::getAverageFrameRate() const\n{\n\treturn 1.0 \/ getAverageFramePeriod();\n}\n\ndouble Timer::getLastFramePeriod() const\n{\n\tSURGSIM_ASSERT(m_frameDurations.size() > 0) <<\n\t\t\"Attempted to access the last frame period for a Timer with no frames.\\n\";\n\treturn m_frameDurations.back().count();\n}\n\ndouble Timer::getLastFrameRate() const\n{\n\treturn 1.0 \/ getLastFramePeriod();\n}\n\nvoid Timer::setNumberOfFrames(size_t maxNumberOfFrames)\n{\n\tm_maxNumberOfFrames = (maxNumberOfFrames > 0) ? maxNumberOfFrames : 1;\n\twhile (m_frameDurations.size() > m_maxNumberOfFrames)\n\t{\n\t\tm_frameDurations.pop_front();\n\t}\n}\n\nsize_t Timer::getCurrentNumberOfFrames() const\n{\n\treturn m_frameDurations.size();\n}\n\nsize_t Timer::getNumberOfClockFails() const\n{\n\treturn m_clockFails;\n}\n\nTimer::TimerTimePoint Timer::now()\n{\n\tboost::system::error_code ec;\n\tTimerTimePoint currentTime = m_clock.now(ec);\n\tif (ec.value() != 0)\n\t{\n\t\t++ m_clockFails;\n\t}\n\treturn currentTime;\n}\n\n}; \/\/ namespace Framework\n}; \/\/ namespace SurgSim\n<commit_msg>Fix copy\/paste error in assert message about Timer not having frames.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Framework\/Assert.h\"\n#include \"SurgSim\/Framework\/Timer.h\"\n\nnamespace SurgSim {\nnamespace Framework {\n\nTimer::Timer() :\n\tm_stopped(true), m_maxNumberOfFrames(100), m_clockFails(0)\n{\n\tstart();\n}\n\nvoid Timer::start()\n{\n\tm_frameDurations.clear();\n\tm_clockFails = 0;\n\tbeginFrame();\n}\n\nvoid Timer::beginFrame()\n{\n\tm_lastTime = now();\n}\n\nvoid Timer::endFrame()\n{\n\tTimerTimePoint currentTime = now();\n\tm_frameDurations.push_back(currentTime - m_lastTime);\n\tif (m_frameDurations.size() > m_maxNumberOfFrames)\n\t{\n\t\tm_frameDurations.pop_front();\n\t}\n\tm_lastTime = currentTime;\n}\n\ndouble Timer::getAverageFramePeriod() const\n{\n\tSURGSIM_ASSERT(m_frameDurations.size() > 0) <<\n\t\t\"Attempted to access the frames for a Timer with no frames.\\n\";\n\tTimerDuration cumulativeTime;\n\tfor (auto it = m_frameDurations.begin(); it != m_frameDurations.end(); ++it)\n\t{\n\t\tcumulativeTime += *it;\n\t}\n\treturn cumulativeTime.count() \/ m_frameDurations.size();\n}\n\ndouble Timer::getAverageFrameRate() const\n{\n\treturn 1.0 \/ getAverageFramePeriod();\n}\n\ndouble Timer::getLastFramePeriod() const\n{\n\tSURGSIM_ASSERT(m_frameDurations.size() > 0) <<\n\t\t\"Attempted to access the last frame period for a Timer with no frames.\\n\";\n\treturn m_frameDurations.back().count();\n}\n\ndouble Timer::getLastFrameRate() const\n{\n\treturn 1.0 \/ getLastFramePeriod();\n}\n\nvoid Timer::setNumberOfFrames(size_t maxNumberOfFrames)\n{\n\tm_maxNumberOfFrames = (maxNumberOfFrames > 0) ? maxNumberOfFrames : 1;\n\twhile (m_frameDurations.size() > m_maxNumberOfFrames)\n\t{\n\t\tm_frameDurations.pop_front();\n\t}\n}\n\nsize_t Timer::getCurrentNumberOfFrames() const\n{\n\treturn m_frameDurations.size();\n}\n\nsize_t Timer::getNumberOfClockFails() const\n{\n\treturn m_clockFails;\n}\n\nTimer::TimerTimePoint Timer::now()\n{\n\tboost::system::error_code ec;\n\tTimerTimePoint currentTime = m_clock.now(ec);\n\tif (ec.value() != 0)\n\t{\n\t\t++ m_clockFails;\n\t}\n\treturn currentTime;\n}\n\n}; \/\/ namespace Framework\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2005-2009 Jay Berkenbilt\n\/\/\n\/\/ This file is part of qpdf. This software may be distributed under\n\/\/ the terms of version 2 of the Artistic License which may be found\n\/\/ in the source distribution. It is provided \"as is\" without express\n\/\/ or implied warranty.\n\n#ifndef __QPDFEXC_HH__\n#define __QPDFEXC_HH__\n\n#include <qpdf\/DLL.h>\n#include <qpdf\/Constants.h>\n#include <stdexcept>\n#include <fcntl.h>\n\nclass DLL_EXPORT QPDFExc: public std::runtime_error\n{\n public:\n QPDFExc(qpdf_error_code_e error_code,\n\t std::string const& filename,\n\t std::string const& object,\n\t off_t offset,\n\t std::string const& message);\n virtual ~QPDFExc() throw ();\n\n \/\/ To get a complete error string, call what(), provided by\n \/\/ std::exception. The accessors below return the original values\n \/\/ used to create the exception. Only the error code and message\n \/\/ are guaranteed to have non-zero\/empty values.\n\n \/\/ There is no lookup code that maps numeric error codes into\n \/\/ strings. The numeric error code is just another way to get at\n \/\/ the underlying issue, but it is more programmer-friendly than\n \/\/ trying to parse a string that is subject to change.\n\n qpdf_error_code_e getErrorCode() const;\n std::string const& getFilename() const;\n std::string const& getObject() const;\n off_t getFilePosition() const;\n std::string const& getMessageDetail() const;\n\n private:\n static std::string createWhat(std::string const& filename,\n\t\t\t\t std::string const& object,\n\t\t\t\t off_t offset,\n\t\t\t\t std::string const& message);\n\n qpdf_error_code_e error_code;\n std::string filename;\n std::string object;\n off_t offset;\n std::string message;\n};\n\n#endif \/\/ __QPDFEXC_HH__\n<commit_msg>try stdlib.h<commit_after>\/\/ Copyright (c) 2005-2009 Jay Berkenbilt\n\/\/\n\/\/ This file is part of qpdf. This software may be distributed under\n\/\/ the terms of version 2 of the Artistic License which may be found\n\/\/ in the source distribution. It is provided \"as is\" without express\n\/\/ or implied warranty.\n\n#ifndef __QPDFEXC_HH__\n#define __QPDFEXC_HH__\n\n#include <qpdf\/DLL.h>\n#include <qpdf\/Constants.h>\n#include <stdexcept>\n#include <fcntl.h>\n#include <stdlib.h>\n\nclass DLL_EXPORT QPDFExc: public std::runtime_error\n{\n public:\n QPDFExc(qpdf_error_code_e error_code,\n\t std::string const& filename,\n\t std::string const& object,\n\t off_t offset,\n\t std::string const& message);\n virtual ~QPDFExc() throw ();\n\n \/\/ To get a complete error string, call what(), provided by\n \/\/ std::exception. The accessors below return the original values\n \/\/ used to create the exception. Only the error code and message\n \/\/ are guaranteed to have non-zero\/empty values.\n\n \/\/ There is no lookup code that maps numeric error codes into\n \/\/ strings. The numeric error code is just another way to get at\n \/\/ the underlying issue, but it is more programmer-friendly than\n \/\/ trying to parse a string that is subject to change.\n\n qpdf_error_code_e getErrorCode() const;\n std::string const& getFilename() const;\n std::string const& getObject() const;\n off_t getFilePosition() const;\n std::string const& getMessageDetail() const;\n\n private:\n static std::string createWhat(std::string const& filename,\n\t\t\t\t std::string const& object,\n\t\t\t\t off_t offset,\n\t\t\t\t std::string const& message);\n\n qpdf_error_code_e error_code;\n std::string filename;\n std::string object;\n off_t offset;\n std::string message;\n};\n\n#endif \/\/ __QPDFEXC_HH__\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Planning: support simple pull over in dp_road_graph.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2010 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Author: jmarantz@google.com (Joshua Marantz)\n\/\/\n\/\/ Contains implementation of CssCombineFilter, which concatenates multiple\n\/\/ CSS files into one. Implemented in part via delegating to\n\/\/ CssCombineFilter::CssCombiner, a ResourceCombiner subclass.\n\n#include \"net\/instaweb\/rewriter\/public\/css_combine_filter.h\"\n\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"net\/instaweb\/htmlparse\/public\/doctype.h\"\n#include \"net\/instaweb\/htmlparse\/public\/html_element.h\"\n#include \"net\/instaweb\/htmlparse\/public\/html_name.h\"\n#include \"net\/instaweb\/http\/public\/content_type.h\"\n#include \"net\/instaweb\/rewriter\/cached_result.pb.h\"\n#include \"net\/instaweb\/rewriter\/public\/css_tag_scanner.h\"\n#include \"net\/instaweb\/rewriter\/public\/output_resource.h\"\n#include \"net\/instaweb\/rewriter\/public\/output_resource_kind.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_combiner.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_manager.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_slot.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_context.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_driver.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_filter.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_result.h\"\n#include \"net\/instaweb\/util\/public\/charset_util.h\"\n#include \"net\/instaweb\/util\/public\/google_url.h\"\n#include \"net\/instaweb\/util\/public\/message_handler.h\"\n#include \"net\/instaweb\/util\/public\/proto_util.h\"\n#include \"net\/instaweb\/util\/public\/ref_counted_ptr.h\"\n#include \"net\/instaweb\/util\/public\/statistics.h\"\n#include \"net\/instaweb\/util\/public\/string.h\"\n#include \"net\/instaweb\/util\/public\/string_util.h\"\n#include \"net\/instaweb\/util\/public\/writer.h\"\n#include \"webutil\/css\/parser.h\"\n\nnamespace net_instaweb {\n\nclass HtmlIEDirectiveNode;\nclass UrlSegmentEncoder;\n\n\/\/ names for Statistics variables.\nconst char CssCombineFilter::kCssFileCountReduction[] =\n \"css_file_count_reduction\";\n\n\/\/ Combining helper. Takes care of checking that media matches, that we do not\n\/\/ produce @import's in the middle and of URL absolutification.\nclass CssCombineFilter::CssCombiner : public ResourceCombiner {\n public:\n CssCombiner(RewriteDriver* driver,\n CssTagScanner* css_tag_scanner,\n CssCombineFilter* filter)\n : ResourceCombiner(driver, kContentTypeCss.file_extension() + 1, filter),\n css_tag_scanner_(css_tag_scanner) {\n Statistics* stats = resource_manager_->statistics();\n css_file_count_reduction_ = stats->GetVariable(kCssFileCountReduction);\n }\n\n bool CleanParse(const StringPiece& contents) {\n Css::Parser parser(contents);\n \/\/ Note: We do not turn on preservation_mode because that could pass through\n \/\/ verbatim text that will break other CSS files combined with this one.\n \/\/ TODO(sligocki): Be less conservative here and actually scan verbatim\n \/\/ text for bad constructs (Ex: contains \"{\").\n \/\/ TODO(sligocki): Do parsing on low-priority worker thread.\n scoped_ptr<Css::Stylesheet> stylesheet(parser.ParseRawStylesheet());\n return (parser.errors_seen_mask() == Css::Parser::kNoError);\n }\n\n virtual bool ResourceCombinable(Resource* resource, MessageHandler* handler) {\n \/\/ If this CSS file is not parseable it may have errors that will break\n \/\/ the rest of the files combined with this one. So we should not include\n \/\/ it in the combination.\n \/\/ TODO(sligocki): Just do the CSS parsing and rewriting here.\n if (!CleanParse(resource->contents())) {\n handler->Message(kInfo, \"Failed to combine %s because of parse error.\",\n resource->url().c_str());\n \/\/ TODO(sligocki): All parse failures are repeated twice because we will\n \/\/ try to combine them in the normal combination, then we'll try again\n \/\/ with this as the first of a new combination.\n return false;\n }\n\n \/\/ styles containing @import cannot be appended to others, as any\n \/\/ @import in the middle will be ignored.\n \/\/ TODO(sligocki): Do CSS parsing and rewriting here so that we can\n \/\/ git rid of this restriction.\n return ((num_urls() == 0)\n || !CssTagScanner::HasImport(resource->contents(), handler));\n }\n\n OutputResourcePtr MakeOutput() {\n return Combine(rewrite_driver_->message_handler());\n }\n\n bool Write(const ResourceVector& in, const OutputResourcePtr& out) {\n return WriteCombination(in, out, rewrite_driver_->message_handler());\n }\n\n void set_media(const char* media) { media_ = media; }\n const GoogleString& media() const { return media_; }\n\n void AddFileCountReduction(int num_files) {\n css_file_count_reduction_->Add(num_files);\n }\n\n private:\n virtual const ContentType* CombinationContentType() {\n return &kContentTypeCss;\n }\n\n virtual bool WritePiece(int index, const Resource* input,\n OutputResource* combination, Writer* writer,\n MessageHandler* handler);\n\n GoogleString media_;\n CssTagScanner* css_tag_scanner_;\n Variable* css_file_count_reduction_;\n};\n\nclass CssCombineFilter::Context : public RewriteContext {\n public:\n Context(RewriteDriver* driver, CssTagScanner* scanner,\n CssCombineFilter* filter)\n : RewriteContext(driver, NULL, NULL),\n filter_(filter),\n combiner_(driver, scanner, filter),\n new_combination_(true) {\n }\n\n CssCombiner* combiner() { return &combiner_; }\n\n bool AddElement(HtmlElement* element, HtmlElement::Attribute* href) {\n bool ret = false;\n ResourcePtr resource(filter_->CreateInputResource(\n href->DecodedValueOrNull()));\n if (resource.get() != NULL) {\n ResourceSlotPtr slot(Driver()->GetSlot(resource, element, href));\n AddSlot(slot);\n elements_.push_back(element);\n ret = true;\n }\n return ret;\n }\n\n bool empty() const { return elements_.empty(); }\n bool new_combination() const { return new_combination_; }\n\n void Reset() {\n combiner_.Reset();\n combiner_.set_media(\"\");\n new_combination_ = true;\n }\n\n void SetMedia(const char* media) {\n combiner_.set_media(media);\n new_combination_ = false;\n }\n\n protected:\n virtual bool Partition(OutputPartitions* partitions,\n OutputResourceVector* outputs) {\n MessageHandler* handler = Driver()->message_handler();\n CachedResult* partition = NULL;\n CHECK_EQ(static_cast<int>(elements_.size()), num_slots());\n for (int i = 0, n = num_slots(); i < n; ++i) {\n bool add_input = false;\n ResourcePtr resource(slot(i)->resource());\n\n if (resource->IsValidAndCacheable()) {\n if (combiner_.AddResourceNoFetch(resource, handler).value) {\n \/\/ This new element works in the existing partition.\n add_input = true;\n } else {\n \/\/ This new element does not work in the existing partition,\n \/\/ so close out that partition if it's non-empty.\n if (partition != NULL) {\n FinalizePartition(partitions, partition, outputs);\n partition = NULL;\n if (combiner_.AddResourceNoFetch(resource, handler).value) {\n add_input = true;\n }\n }\n }\n } else {\n \/\/ A failed resource-fetch tells us to finalize any partition that\n \/\/ we've already started. We don't want to combine across a CSS file\n \/\/ that our server sees as a 404 because the browser might successfully\n \/\/ fetch that file, and thus we'd mangle the ordering if we combined\n \/\/ across it.\n FinalizePartition(partitions, partition, outputs);\n partition = NULL;\n }\n if (add_input) {\n if (partition == NULL) {\n partition = partitions->add_partition();\n }\n resource->AddInputInfoToPartition(\n Resource::kIncludeInputHash, i, partition);\n }\n }\n FinalizePartition(partitions, partition, outputs);\n return (partitions->partition_size() != 0);\n }\n\n virtual void Rewrite(int partition_index,\n CachedResult* partition,\n const OutputResourcePtr& output) {\n \/\/ resource_combiner.cc calls WriteCombination as part\n \/\/ of Combine. But if we are being called on behalf of a\n \/\/ fetch then the resource still needs to be written.\n RewriteResult result = kRewriteOk;\n \/\/ OutputResource CHECK-fails if you try to Write twice, which\n \/\/ would happen in the html-rewrite phase without this check.\n if (!output->IsWritten()) {\n ResourceVector resources;\n for (int i = 0, n = num_slots(); i < n; ++i) {\n ResourcePtr resource(slot(i)->resource());\n resources.push_back(resource);\n }\n if (!combiner_.Write(resources, output)) {\n result = kRewriteFailed;\n }\n }\n RewriteDone(result, partition_index);\n }\n\n virtual void Render() {\n \/\/ Slot 0 will be replaced by the combined resource as part of\n \/\/ rewrite_context.cc. But we still need to delete slots 1-N.\n for (int p = 0, np = num_output_partitions(); p < np; ++p) {\n CachedResult* partition = output_partition(p);\n if (partition->input_size() == 0) {\n continue;\n }\n\n if (filter_->driver()->doctype().IsXhtml()) {\n int first_element_index = partition->input(0).index();\n HtmlElement* first_element = elements_[first_element_index];\n first_element->set_close_style(HtmlElement::BRIEF_CLOSE);\n }\n for (int i = 1; i < partition->input_size(); ++i) {\n int slot_index = partition->input(i).index();\n slot(slot_index)->set_should_delete_element(true);\n }\n combiner_.AddFileCountReduction(partition->input_size() - 1);\n }\n }\n\n virtual const UrlSegmentEncoder* encoder() const {\n return filter_->encoder();\n }\n virtual const char* id() const { return filter_->id(); }\n virtual OutputResourceKind kind() const { return kRewrittenResource; }\n\n private:\n void FinalizePartition(OutputPartitions* partitions,\n CachedResult* partition,\n OutputResourceVector* outputs) {\n if (partition != NULL) {\n OutputResourcePtr combination_output(combiner_.MakeOutput());\n if (combination_output.get() == NULL) {\n partitions->mutable_partition()->RemoveLast();\n } else {\n combination_output->UpdateCachedResultPreservingInputInfo(partition);\n outputs->push_back(combination_output);\n }\n Reset();\n }\n }\n\n std::vector<HtmlElement*> elements_;\n RewriteFilter* filter_;\n CssCombineFilter::CssCombiner combiner_;\n bool new_combination_;\n DISALLOW_COPY_AND_ASSIGN(Context);\n};\n\n\/\/ TODO(jmarantz) We exhibit zero intelligence about which css files to\n\/\/ combine; we combine whatever is possible. This can reduce performance\n\/\/ by combining highly cacheable shared resources with transient ones.\n\/\/\n\/\/ TODO(jmarantz): We do not recognize IE directives as spriting boundaries.\n\/\/ We should supply a meaningful IEDirective method as a boundary.\n\/\/\n\/\/ TODO(jmarantz): allow combining of CSS elements found in the body, whether\n\/\/ or not the head has already been flushed.\n\/\/\n\/\/ TODO(jmaessen): The addition of 1 below avoids the leading \".\";\n\/\/ make this convention consistent and fix all code.\nCssCombineFilter::CssCombineFilter(RewriteDriver* driver)\n : RewriteFilter(driver),\n css_tag_scanner_(driver_) {\n}\n\nCssCombineFilter::~CssCombineFilter() {\n}\n\nvoid CssCombineFilter::Initialize(Statistics* statistics) {\n statistics->AddVariable(kCssFileCountReduction);\n}\n\nvoid CssCombineFilter::StartDocumentImpl() {\n context_.reset(MakeContext());\n}\n\nvoid CssCombineFilter::StartElementImpl(HtmlElement* element) {\n HtmlElement::Attribute* href;\n const char* media;\n if (!driver_->HasChildrenInFlushWindow(element) &&\n css_tag_scanner_.ParseCssElement(element, &href, &media)) {\n \/\/ We cannot combine with a link in <noscript> tag and we cannot combine\n \/\/ over a link in a <noscript> tag, so this is a barrier.\n if (noscript_element() != NULL) {\n NextCombination();\n } else {\n if (context_->new_combination()) {\n context_->SetMedia(media);\n } else if (combiner()->media() != media) {\n \/\/ After the first CSS file, subsequent CSS files must have matching\n \/\/ media.\n \/\/ TODO(jmarantz): do media='' and media='display mean the same\n \/\/ thing? sligocki thinks mdsteele looked into this and it\n \/\/ depended on HTML version. In one display was default, in the\n \/\/ other screen was IIRC.\n NextCombination();\n context_->SetMedia(media);\n }\n if (!context_->AddElement(element, href)) {\n NextCombination();\n }\n }\n } else if (element->keyword() == HtmlName::kStyle) {\n \/\/ We can't reorder styles on a page, so if we are only combining <link>\n \/\/ tags, we can't combine them across a <style> tag.\n \/\/ TODO(sligocki): Maybe we should just combine <style>s too?\n \/\/ We can run outline_css first for now to make all <style>s into <link>s.\n NextCombination();\n }\n}\n\nvoid CssCombineFilter::NextCombination() {\n if (!context_->empty()) {\n driver_->InitiateRewrite(context_.release());\n context_.reset(MakeContext());\n }\n context_->Reset();\n}\n\n\/\/ An IE directive that includes any stylesheet info should be a barrier\n\/\/ for css combining. It's OK to emit the combination we've seen so far.\nvoid CssCombineFilter::IEDirective(HtmlIEDirectiveNode* directive) {\n \/\/ TODO(sligocki): Figure out how to safely parse IEDirectives, for now we\n \/\/ just consider them black boxes \/ solid barriers.\n NextCombination();\n}\n\nvoid CssCombineFilter::Flush() {\n NextCombination();\n}\n\nbool CssCombineFilter::CssCombiner::WritePiece(\n int index, const Resource* input, OutputResource* combination,\n Writer* writer, MessageHandler* handler) {\n StringPiece contents = input->contents();\n GoogleUrl input_url(input->url());\n StringPiece input_dir = input_url.AllExceptLeaf();\n \/\/ Strip the BOM off of the contents (if it's there) if this is not the\n \/\/ first resource.\n if (index != 0) {\n StripUtf8Bom(&contents);\n }\n bool ret = false;\n switch (rewrite_driver_->ResolveCssUrls(\n input_url, combination->resolved_base(), contents, writer, handler)) {\n case RewriteDriver::kNoResolutionNeeded:\n ret = writer->Write(contents, handler);\n break;\n case RewriteDriver::kWriteFailed:\n break;\n case RewriteDriver::kSuccess:\n ret = true;\n break;\n }\n return ret;\n}\n\nCssCombineFilter::CssCombiner* CssCombineFilter::combiner() {\n return context_->combiner();\n}\n\nCssCombineFilter::Context* CssCombineFilter::MakeContext() {\n return new Context(driver_, &css_tag_scanner_, this);\n}\n\nRewriteContext* CssCombineFilter::MakeRewriteContext() {\n return MakeContext();\n}\n\n} \/\/ namespace net_instaweb\n<commit_msg>remove unused temp variable.<commit_after>\/*\n * Copyright 2010 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Author: jmarantz@google.com (Joshua Marantz)\n\/\/\n\/\/ Contains implementation of CssCombineFilter, which concatenates multiple\n\/\/ CSS files into one. Implemented in part via delegating to\n\/\/ CssCombineFilter::CssCombiner, a ResourceCombiner subclass.\n\n#include \"net\/instaweb\/rewriter\/public\/css_combine_filter.h\"\n\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"net\/instaweb\/htmlparse\/public\/doctype.h\"\n#include \"net\/instaweb\/htmlparse\/public\/html_element.h\"\n#include \"net\/instaweb\/htmlparse\/public\/html_name.h\"\n#include \"net\/instaweb\/http\/public\/content_type.h\"\n#include \"net\/instaweb\/rewriter\/cached_result.pb.h\"\n#include \"net\/instaweb\/rewriter\/public\/css_tag_scanner.h\"\n#include \"net\/instaweb\/rewriter\/public\/output_resource.h\"\n#include \"net\/instaweb\/rewriter\/public\/output_resource_kind.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_combiner.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_manager.h\"\n#include \"net\/instaweb\/rewriter\/public\/resource_slot.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_context.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_driver.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_filter.h\"\n#include \"net\/instaweb\/rewriter\/public\/rewrite_result.h\"\n#include \"net\/instaweb\/util\/public\/charset_util.h\"\n#include \"net\/instaweb\/util\/public\/google_url.h\"\n#include \"net\/instaweb\/util\/public\/message_handler.h\"\n#include \"net\/instaweb\/util\/public\/proto_util.h\"\n#include \"net\/instaweb\/util\/public\/ref_counted_ptr.h\"\n#include \"net\/instaweb\/util\/public\/statistics.h\"\n#include \"net\/instaweb\/util\/public\/string.h\"\n#include \"net\/instaweb\/util\/public\/string_util.h\"\n#include \"net\/instaweb\/util\/public\/writer.h\"\n#include \"webutil\/css\/parser.h\"\n\nnamespace net_instaweb {\n\nclass HtmlIEDirectiveNode;\nclass UrlSegmentEncoder;\n\n\/\/ names for Statistics variables.\nconst char CssCombineFilter::kCssFileCountReduction[] =\n \"css_file_count_reduction\";\n\n\/\/ Combining helper. Takes care of checking that media matches, that we do not\n\/\/ produce @import's in the middle and of URL absolutification.\nclass CssCombineFilter::CssCombiner : public ResourceCombiner {\n public:\n CssCombiner(RewriteDriver* driver,\n CssTagScanner* css_tag_scanner,\n CssCombineFilter* filter)\n : ResourceCombiner(driver, kContentTypeCss.file_extension() + 1, filter),\n css_tag_scanner_(css_tag_scanner) {\n Statistics* stats = resource_manager_->statistics();\n css_file_count_reduction_ = stats->GetVariable(kCssFileCountReduction);\n }\n\n bool CleanParse(const StringPiece& contents) {\n Css::Parser parser(contents);\n \/\/ Note: We do not turn on preservation_mode because that could pass through\n \/\/ verbatim text that will break other CSS files combined with this one.\n \/\/ TODO(sligocki): Be less conservative here and actually scan verbatim\n \/\/ text for bad constructs (Ex: contains \"{\").\n \/\/ TODO(sligocki): Do parsing on low-priority worker thread.\n scoped_ptr<Css::Stylesheet> stylesheet(parser.ParseRawStylesheet());\n return (parser.errors_seen_mask() == Css::Parser::kNoError);\n }\n\n virtual bool ResourceCombinable(Resource* resource, MessageHandler* handler) {\n \/\/ If this CSS file is not parseable it may have errors that will break\n \/\/ the rest of the files combined with this one. So we should not include\n \/\/ it in the combination.\n \/\/ TODO(sligocki): Just do the CSS parsing and rewriting here.\n if (!CleanParse(resource->contents())) {\n handler->Message(kInfo, \"Failed to combine %s because of parse error.\",\n resource->url().c_str());\n \/\/ TODO(sligocki): All parse failures are repeated twice because we will\n \/\/ try to combine them in the normal combination, then we'll try again\n \/\/ with this as the first of a new combination.\n return false;\n }\n\n \/\/ styles containing @import cannot be appended to others, as any\n \/\/ @import in the middle will be ignored.\n \/\/ TODO(sligocki): Do CSS parsing and rewriting here so that we can\n \/\/ git rid of this restriction.\n return ((num_urls() == 0)\n || !CssTagScanner::HasImport(resource->contents(), handler));\n }\n\n OutputResourcePtr MakeOutput() {\n return Combine(rewrite_driver_->message_handler());\n }\n\n bool Write(const ResourceVector& in, const OutputResourcePtr& out) {\n return WriteCombination(in, out, rewrite_driver_->message_handler());\n }\n\n void set_media(const char* media) { media_ = media; }\n const GoogleString& media() const { return media_; }\n\n void AddFileCountReduction(int num_files) {\n css_file_count_reduction_->Add(num_files);\n }\n\n private:\n virtual const ContentType* CombinationContentType() {\n return &kContentTypeCss;\n }\n\n virtual bool WritePiece(int index, const Resource* input,\n OutputResource* combination, Writer* writer,\n MessageHandler* handler);\n\n GoogleString media_;\n CssTagScanner* css_tag_scanner_;\n Variable* css_file_count_reduction_;\n};\n\nclass CssCombineFilter::Context : public RewriteContext {\n public:\n Context(RewriteDriver* driver, CssTagScanner* scanner,\n CssCombineFilter* filter)\n : RewriteContext(driver, NULL, NULL),\n filter_(filter),\n combiner_(driver, scanner, filter),\n new_combination_(true) {\n }\n\n CssCombiner* combiner() { return &combiner_; }\n\n bool AddElement(HtmlElement* element, HtmlElement::Attribute* href) {\n bool ret = false;\n ResourcePtr resource(filter_->CreateInputResource(\n href->DecodedValueOrNull()));\n if (resource.get() != NULL) {\n ResourceSlotPtr slot(Driver()->GetSlot(resource, element, href));\n AddSlot(slot);\n elements_.push_back(element);\n ret = true;\n }\n return ret;\n }\n\n bool empty() const { return elements_.empty(); }\n bool new_combination() const { return new_combination_; }\n\n void Reset() {\n combiner_.Reset();\n combiner_.set_media(\"\");\n new_combination_ = true;\n }\n\n void SetMedia(const char* media) {\n combiner_.set_media(media);\n new_combination_ = false;\n }\n\n protected:\n virtual bool Partition(OutputPartitions* partitions,\n OutputResourceVector* outputs) {\n MessageHandler* handler = Driver()->message_handler();\n CachedResult* partition = NULL;\n CHECK_EQ(static_cast<int>(elements_.size()), num_slots());\n for (int i = 0, n = num_slots(); i < n; ++i) {\n bool add_input = false;\n ResourcePtr resource(slot(i)->resource());\n\n if (resource->IsValidAndCacheable()) {\n if (combiner_.AddResourceNoFetch(resource, handler).value) {\n \/\/ This new element works in the existing partition.\n add_input = true;\n } else {\n \/\/ This new element does not work in the existing partition,\n \/\/ so close out that partition if it's non-empty.\n if (partition != NULL) {\n FinalizePartition(partitions, partition, outputs);\n partition = NULL;\n if (combiner_.AddResourceNoFetch(resource, handler).value) {\n add_input = true;\n }\n }\n }\n } else {\n \/\/ A failed resource-fetch tells us to finalize any partition that\n \/\/ we've already started. We don't want to combine across a CSS file\n \/\/ that our server sees as a 404 because the browser might successfully\n \/\/ fetch that file, and thus we'd mangle the ordering if we combined\n \/\/ across it.\n FinalizePartition(partitions, partition, outputs);\n partition = NULL;\n }\n if (add_input) {\n if (partition == NULL) {\n partition = partitions->add_partition();\n }\n resource->AddInputInfoToPartition(\n Resource::kIncludeInputHash, i, partition);\n }\n }\n FinalizePartition(partitions, partition, outputs);\n return (partitions->partition_size() != 0);\n }\n\n virtual void Rewrite(int partition_index,\n CachedResult* partition,\n const OutputResourcePtr& output) {\n \/\/ resource_combiner.cc calls WriteCombination as part\n \/\/ of Combine. But if we are being called on behalf of a\n \/\/ fetch then the resource still needs to be written.\n RewriteResult result = kRewriteOk;\n \/\/ OutputResource CHECK-fails if you try to Write twice, which\n \/\/ would happen in the html-rewrite phase without this check.\n if (!output->IsWritten()) {\n ResourceVector resources;\n for (int i = 0, n = num_slots(); i < n; ++i) {\n ResourcePtr resource(slot(i)->resource());\n resources.push_back(resource);\n }\n if (!combiner_.Write(resources, output)) {\n result = kRewriteFailed;\n }\n }\n RewriteDone(result, partition_index);\n }\n\n virtual void Render() {\n \/\/ Slot 0 will be replaced by the combined resource as part of\n \/\/ rewrite_context.cc. But we still need to delete slots 1-N.\n for (int p = 0, np = num_output_partitions(); p < np; ++p) {\n CachedResult* partition = output_partition(p);\n if (partition->input_size() == 0) {\n continue;\n }\n\n if (filter_->driver()->doctype().IsXhtml()) {\n int first_element_index = partition->input(0).index();\n HtmlElement* first_element = elements_[first_element_index];\n first_element->set_close_style(HtmlElement::BRIEF_CLOSE);\n }\n for (int i = 1; i < partition->input_size(); ++i) {\n int slot_index = partition->input(i).index();\n slot(slot_index)->set_should_delete_element(true);\n }\n combiner_.AddFileCountReduction(partition->input_size() - 1);\n }\n }\n\n virtual const UrlSegmentEncoder* encoder() const {\n return filter_->encoder();\n }\n virtual const char* id() const { return filter_->id(); }\n virtual OutputResourceKind kind() const { return kRewrittenResource; }\n\n private:\n void FinalizePartition(OutputPartitions* partitions,\n CachedResult* partition,\n OutputResourceVector* outputs) {\n if (partition != NULL) {\n OutputResourcePtr combination_output(combiner_.MakeOutput());\n if (combination_output.get() == NULL) {\n partitions->mutable_partition()->RemoveLast();\n } else {\n combination_output->UpdateCachedResultPreservingInputInfo(partition);\n outputs->push_back(combination_output);\n }\n Reset();\n }\n }\n\n std::vector<HtmlElement*> elements_;\n RewriteFilter* filter_;\n CssCombineFilter::CssCombiner combiner_;\n bool new_combination_;\n DISALLOW_COPY_AND_ASSIGN(Context);\n};\n\n\/\/ TODO(jmarantz) We exhibit zero intelligence about which css files to\n\/\/ combine; we combine whatever is possible. This can reduce performance\n\/\/ by combining highly cacheable shared resources with transient ones.\n\/\/\n\/\/ TODO(jmarantz): We do not recognize IE directives as spriting boundaries.\n\/\/ We should supply a meaningful IEDirective method as a boundary.\n\/\/\n\/\/ TODO(jmarantz): allow combining of CSS elements found in the body, whether\n\/\/ or not the head has already been flushed.\n\/\/\n\/\/ TODO(jmaessen): The addition of 1 below avoids the leading \".\";\n\/\/ make this convention consistent and fix all code.\nCssCombineFilter::CssCombineFilter(RewriteDriver* driver)\n : RewriteFilter(driver),\n css_tag_scanner_(driver_) {\n}\n\nCssCombineFilter::~CssCombineFilter() {\n}\n\nvoid CssCombineFilter::Initialize(Statistics* statistics) {\n statistics->AddVariable(kCssFileCountReduction);\n}\n\nvoid CssCombineFilter::StartDocumentImpl() {\n context_.reset(MakeContext());\n}\n\nvoid CssCombineFilter::StartElementImpl(HtmlElement* element) {\n HtmlElement::Attribute* href;\n const char* media;\n if (!driver_->HasChildrenInFlushWindow(element) &&\n css_tag_scanner_.ParseCssElement(element, &href, &media)) {\n \/\/ We cannot combine with a link in <noscript> tag and we cannot combine\n \/\/ over a link in a <noscript> tag, so this is a barrier.\n if (noscript_element() != NULL) {\n NextCombination();\n } else {\n if (context_->new_combination()) {\n context_->SetMedia(media);\n } else if (combiner()->media() != media) {\n \/\/ After the first CSS file, subsequent CSS files must have matching\n \/\/ media.\n \/\/ TODO(jmarantz): do media='' and media='display mean the same\n \/\/ thing? sligocki thinks mdsteele looked into this and it\n \/\/ depended on HTML version. In one display was default, in the\n \/\/ other screen was IIRC.\n NextCombination();\n context_->SetMedia(media);\n }\n if (!context_->AddElement(element, href)) {\n NextCombination();\n }\n }\n } else if (element->keyword() == HtmlName::kStyle) {\n \/\/ We can't reorder styles on a page, so if we are only combining <link>\n \/\/ tags, we can't combine them across a <style> tag.\n \/\/ TODO(sligocki): Maybe we should just combine <style>s too?\n \/\/ We can run outline_css first for now to make all <style>s into <link>s.\n NextCombination();\n }\n}\n\nvoid CssCombineFilter::NextCombination() {\n if (!context_->empty()) {\n driver_->InitiateRewrite(context_.release());\n context_.reset(MakeContext());\n }\n context_->Reset();\n}\n\n\/\/ An IE directive that includes any stylesheet info should be a barrier\n\/\/ for css combining. It's OK to emit the combination we've seen so far.\nvoid CssCombineFilter::IEDirective(HtmlIEDirectiveNode* directive) {\n \/\/ TODO(sligocki): Figure out how to safely parse IEDirectives, for now we\n \/\/ just consider them black boxes \/ solid barriers.\n NextCombination();\n}\n\nvoid CssCombineFilter::Flush() {\n NextCombination();\n}\n\nbool CssCombineFilter::CssCombiner::WritePiece(\n int index, const Resource* input, OutputResource* combination,\n Writer* writer, MessageHandler* handler) {\n StringPiece contents = input->contents();\n GoogleUrl input_url(input->url());\n \/\/ Strip the BOM off of the contents (if it's there) if this is not the\n \/\/ first resource.\n if (index != 0) {\n StripUtf8Bom(&contents);\n }\n bool ret = false;\n switch (rewrite_driver_->ResolveCssUrls(\n input_url, combination->resolved_base(), contents, writer, handler)) {\n case RewriteDriver::kNoResolutionNeeded:\n ret = writer->Write(contents, handler);\n break;\n case RewriteDriver::kWriteFailed:\n break;\n case RewriteDriver::kSuccess:\n ret = true;\n break;\n }\n return ret;\n}\n\nCssCombineFilter::CssCombiner* CssCombineFilter::combiner() {\n return context_->combiner();\n}\n\nCssCombineFilter::Context* CssCombineFilter::MakeContext() {\n return new Context(driver_, &css_tag_scanner_, this);\n}\n\nRewriteContext* CssCombineFilter::MakeRewriteContext() {\n return MakeContext();\n}\n\n} \/\/ namespace net_instaweb\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstdint>\n#include <iomanip>\n#include <sstream>\n#include <string>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"blackhole\/sink\/files\/rotation\/naming.hpp\"\n\nnamespace blackhole {\n\nnamespace sink {\n\nnamespace rotation {\n\nstruct counter_t {\n std::string prefix;\n std::string suffix;\n uint width;\n\n counter_t(const std::string& prefix, const std::string& suffix, uint width) :\n prefix(std::move(prefix)),\n suffix(std::move(suffix)),\n width(width)\n {}\n\n counter_t(std::string&& prefix, std::string&& suffix, uint width) :\n prefix(std::move(prefix)),\n suffix(std::move(suffix)),\n width(width)\n {}\n\n bool operator ==(const counter_t& other) const {\n return prefix == other.prefix && suffix == other.suffix && width == other.width;\n }\n\n friend std::ostream& operator <<(std::ostream& stream, const counter_t& counter) {\n stream << \"counter_t('\" << counter.prefix << \"', '\" << counter.suffix << \"', \" << counter.width << \")\";\n return stream;\n }\n\n bool valid() const {\n return width != 0;\n }\n\n \/\/! I just leave these examples as mini documentation.\n \/\/! pattern: test.log.%Y%m%d.%N %(filename).%N %(filename).%Y%m%d.%N\n \/\/! basename: test.log.%Y%m%d.%N test.log.%N test.log.%Y%m%d.%N\n \/\/! current: test.log.20140130.1 test.log.1 test.log.20140130.1\n \/\/! newname: test.log.20140130.2 test.log.2 test.log.20140130.2\n std::string next(const std::string& filename) const {\n BOOST_ASSERT(filename.size() - prefix.size() - suffix.size() >= 0);\n const std::string& counter = filename.substr(prefix.size(),\n filename.size() - prefix.size() - suffix.size());\n uint value = 0;\n try {\n value = boost::lexical_cast<uint>(counter);\n } catch (const boost::bad_lexical_cast&) {\n \/\/ Eat this.\n }\n\n std::ostringstream stream;\n stream << std::string(filename.begin(), filename.begin() + prefix.size())\n << std::setfill('0') << std::setw(width) << (value + 1)\n << std::string(filename.begin() + prefix.size() + std::max(width, matching::digits(value)), filename.end());\n return stream.str();\n }\n\n static counter_t from_string(const std::string& pattern) {\n std::string prefix;\n std::string suffix;\n int width = 0;\n bool found = false;\n for (auto it = pattern.begin(); it != pattern.end(); ++it) {\n if (found) {\n suffix.push_back(*it);\n } else if (*it == '%') {\n it++;\n std::string value;\n\n for (; it != pattern.end(); ++it) {\n if (*it == 'N') {\n found = true;\n break;\n }\n\n value.push_back(*it);\n if (!std::isdigit(*it)) {\n break;\n }\n }\n\n if (found) {\n width = value.empty() ? 1 : boost::lexical_cast<uint>(value);\n } else {\n prefix.push_back('%');\n prefix.append(value);\n }\n } else {\n prefix.push_back(*it);\n }\n }\n\n boost::replace_all(prefix, \"%Y\", \"YYYY\");\n boost::replace_all(prefix, \"%m\", \"mm\");\n boost::replace_all(prefix, \"%d\", \"dd\");\n boost::replace_all(prefix, \"%H\", \"HH\");\n boost::replace_all(prefix, \"%M\", \"MM\");\n boost::replace_all(prefix, \"%s\", \"ss\");\n\n boost::replace_all(suffix, \"%Y\", \"YYYY\");\n boost::replace_all(suffix, \"%m\", \"mm\");\n boost::replace_all(suffix, \"%d\", \"dd\");\n boost::replace_all(suffix, \"%H\", \"HH\");\n boost::replace_all(suffix, \"%M\", \"MM\");\n boost::replace_all(suffix, \"%s\", \"ss\");\n\n return counter_t(std::move(prefix), std::move(suffix), width);\n }\n\n int count(const std::string& str, const std::string& obj ) {\n int n = 0;\n std::string::size_type pos = 0;\n while ((pos = obj.find(str, pos)) != std::string::npos) {\n n++;\n pos += str.size();\n }\n\n return n;\n }\n};\n\n} \/\/ namespace rotation\n\n} \/\/ namespace sink\n\n} \/\/ namespace blackhole\n<commit_msg>Tiny comment fix.<commit_after>#pragma once\n\n#include <cstdint>\n#include <iomanip>\n#include <sstream>\n#include <string>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"blackhole\/sink\/files\/rotation\/naming.hpp\"\n\nnamespace blackhole {\n\nnamespace sink {\n\nnamespace rotation {\n\nstruct counter_t {\n std::string prefix;\n std::string suffix;\n uint width;\n\n counter_t(const std::string& prefix, const std::string& suffix, uint width) :\n prefix(std::move(prefix)),\n suffix(std::move(suffix)),\n width(width)\n {}\n\n counter_t(std::string&& prefix, std::string&& suffix, uint width) :\n prefix(std::move(prefix)),\n suffix(std::move(suffix)),\n width(width)\n {}\n\n bool operator ==(const counter_t& other) const {\n return prefix == other.prefix && suffix == other.suffix && width == other.width;\n }\n\n friend std::ostream& operator <<(std::ostream& stream, const counter_t& counter) {\n stream << \"counter_t('\" << counter.prefix << \"', '\" << counter.suffix << \"', \" << counter.width << \")\";\n return stream;\n }\n\n bool valid() const {\n return width != 0;\n }\n\n \/\/! I just leave these examples as mini documentation.\n \/*!\n * pattern: test.log.%Y%m%d.%N %(filename)s.%N %(filename)s.%Y%m%d.%N\n * basename: test.log.%Y%m%d.%N test.log.%N test.log.%Y%m%d.%N\n * current: test.log.20140130.1 test.log.1 test.log.20140130.1\n * newname: test.log.20140130.2 test.log.2 test.log.20140130.2\n *\/\n std::string next(const std::string& filename) const {\n BOOST_ASSERT(filename.size() - prefix.size() - suffix.size() >= 0);\n const std::string& counter = filename.substr(prefix.size(),\n filename.size() - prefix.size() - suffix.size());\n uint value = 0;\n try {\n value = boost::lexical_cast<uint>(counter);\n } catch (const boost::bad_lexical_cast&) {\n \/\/ Eat this.\n }\n\n std::ostringstream stream;\n stream << std::string(filename.begin(), filename.begin() + prefix.size())\n << std::setfill('0') << std::setw(width) << (value + 1)\n << std::string(filename.begin() + prefix.size() + std::max(width, matching::digits(value)), filename.end());\n return stream.str();\n }\n\n static counter_t from_string(const std::string& pattern) {\n std::string prefix;\n std::string suffix;\n int width = 0;\n bool found = false;\n for (auto it = pattern.begin(); it != pattern.end(); ++it) {\n if (found) {\n suffix.push_back(*it);\n } else if (*it == '%') {\n it++;\n std::string value;\n\n for (; it != pattern.end(); ++it) {\n if (*it == 'N') {\n found = true;\n break;\n }\n\n value.push_back(*it);\n if (!std::isdigit(*it)) {\n break;\n }\n }\n\n if (found) {\n width = value.empty() ? 1 : boost::lexical_cast<uint>(value);\n } else {\n prefix.push_back('%');\n prefix.append(value);\n }\n } else {\n prefix.push_back(*it);\n }\n }\n\n boost::replace_all(prefix, \"%Y\", \"YYYY\");\n boost::replace_all(prefix, \"%m\", \"mm\");\n boost::replace_all(prefix, \"%d\", \"dd\");\n boost::replace_all(prefix, \"%H\", \"HH\");\n boost::replace_all(prefix, \"%M\", \"MM\");\n boost::replace_all(prefix, \"%s\", \"ss\");\n\n boost::replace_all(suffix, \"%Y\", \"YYYY\");\n boost::replace_all(suffix, \"%m\", \"mm\");\n boost::replace_all(suffix, \"%d\", \"dd\");\n boost::replace_all(suffix, \"%H\", \"HH\");\n boost::replace_all(suffix, \"%M\", \"MM\");\n boost::replace_all(suffix, \"%s\", \"ss\");\n\n return counter_t(std::move(prefix), std::move(suffix), width);\n }\n\n int count(const std::string& str, const std::string& obj ) {\n int n = 0;\n std::string::size_type pos = 0;\n while ((pos = obj.find(str, pos)) != std::string::npos) {\n n++;\n pos += str.size();\n }\n\n return n;\n }\n};\n\n} \/\/ namespace rotation\n\n} \/\/ namespace sink\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>#include \"TMC2130Stepper.h\"\n\n#define REG_CHOPCONF 0x6C\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ REG_CHOPCONF\n\nuint32_t TMC2130Stepper::CHOPCONF() {\n\tuint32_t data = 0x0;\n\tsend2130(READ|REG_CHOPCONF, &data, 0x0, 0x0);\n\treturn data;\n}\n\nvoid TMC2130Stepper::CHOPCONF(uint32_t value) {\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xFFFFFFFF);\n}\n\nuint8_t TMC2130Stepper::off_time() {return val_toff;}\n\nvoid TMC2130Stepper::off_time(uint8_t value) {\n\tif (value > 15) value = 15;\n\tval_toff = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xF);\n}\n\nuint8_t TMC2130Stepper::hysterisis_start() {return val_hstrt;}\n\nvoid TMC2130Stepper::hysterisis_start(uint8_t value) {\n\tif (val_chm\t== 0) {\n\t\tif (value < 1) value = 1;\n\t\telse if (value > 8) value = 8;\n\t\tval_hstrt = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value-1) << 4, 0x70);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 1 -> fast_decay_time is in use. No change made.\");}\n#endif\t\n}\n\nuint8_t TMC2130Stepper::fast_decay_time() {return val_tfd;}\n\nvoid TMC2130Stepper::fast_decay_time(uint8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value > 15) value = 15;\n\t\tval_tfd = value;\n\t\tvalue = ((uint32_t)value << 4) | (value & 0b111); \/\/ Create space between MSB and the bits 0..2\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 4, 0x870);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> hysterisis_start is in use. No change made.\");}\n#endif\t\n}\n\nint8_t TMC2130Stepper::hysterisis_low() {return val_hend;}\n\nvoid TMC2130Stepper::hysterisis_low(int8_t value) {\n\tif (val_chm == 0) {\n\t\tif (value < -3) value = -3;\n\t\tif (value > 12) value = 12;\n\t\tval_hend = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 1 -> sine_offset is in use. No change made.\");}\n#endif\t\n}\n\nint8_t TMC2130Stepper::sine_offset() {return val_offset;}\n\nvoid TMC2130Stepper::sine_offset(int8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value < -3) value = -3;\n\t\tif (value > 12) value = 12;\n\t\tval_hend = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> hysterisis_low is in use. No change made.\");}\n#endif\t\n}\n\nuint8_t TMC2130Stepper::disable_I_comparator() {return val_disfdcc;}\n\nvoid TMC2130Stepper::disable_I_comparator(uint8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value > 1) value = 1;\n\t\tval_disfdcc = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 12, (uint32_t)0b1 << 12);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> No change made.\");}\n#endif\n}\n\nuint8_t TMC2130Stepper::random_off_time() {return val_rndtf;}\n\nvoid TMC2130Stepper::random_off_time(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_rndtf = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 13, (uint32_t)0b1 << 13);\n}\n\nuint8_t TMC2130Stepper::chopper_mode() {return val_chm;}\n\nvoid TMC2130Stepper::chopper_mode(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_chm = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 14, (uint32_t)0b1 << 14);\n}\n\nuint8_t TMC2130Stepper::blank_time() {return val_tbl;}\n\nvoid TMC2130Stepper::blank_time(uint8_t value) {\n\tuint8_t valid[] = {54, 36, 24, 16};\n\n\tif (value < valid[3]) value = valid[3]; \/\/ Make sure we find a match for low values\n\tfor (int i = 0; i<4; i++) {\n\t\tif (value >= valid[i]) {\n\t\t\tvalue = valid[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tval_tbl = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 15, 0x18000);\n}\n\nuint8_t TMC2130Stepper::high_sense_R() {return val_vsense;}\n\nvoid TMC2130Stepper::high_sense_R(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vsense = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 17, (uint32_t)0b1 << 17);\n}\n\nuint8_t TMC2130Stepper::fullstep_threshold() {return val_vhighfs;}\n\nvoid TMC2130Stepper::fullstep_threshold(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vhighfs = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 18, (uint32_t)0b1 << 18);\n}\n\nuint8_t TMC2130Stepper::high_speed_mode() {return val_vhighchm;}\n\nvoid TMC2130Stepper::high_speed_mode(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vhighchm = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 19, (uint32_t)0b1 << 19);\n}\n\nuint8_t TMC2130Stepper::sync_phases() {return val_sync;}\n\nvoid TMC2130Stepper::sync_phases(uint8_t value) {\n\tif (value > 15) value = 15;\n\tval_sync = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 20, 0xF00000);\n}\n\nuint8_t TMC2130Stepper::microsteps() {return val_mres;}\n\nvoid TMC2130Stepper::microsteps(uint8_t value) {\n\tint valid[] \t= {\t\t256, \t128, \t 64, \t 32, \t 16, \t 8, \t 4, \t 2, \t 0 };\n\tuint32_t _hex[] = { 0b0000, 0b0001, 0b0010, 0b0011, 0b0100, 0b0101, 0b0110, 0b0111, 0b1000 };\n\n\tfor (int i = 0; i<9; i++) {\n\t\tif (value >= valid[i]) {\n\t\t\tval_mres = valid[i];\n\t\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, _hex[i] << 24, 0xF000000);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nuint8_t TMC2130Stepper::interpolate() {return val_intpol;}\n\nvoid TMC2130Stepper::interpolate(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_intpol = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 28, (uint32_t)0b1 << 28);\n}\n\nuint8_t TMC2130Stepper::double_edge_step() {return val_dedge;}\n\nvoid TMC2130Stepper::double_edge_step(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_dedge = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 29, (uint32_t)0b1 << 29);\n}\n\nuint8_t TMC2130Stepper::disable_short_protection() {return val_diss2g;}\n\nvoid TMC2130Stepper::disable_short_protection(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_diss2g = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)(uint32_t)value << 30, (uint32_t)0b1 << 30);\n}<commit_msg>Fixed double casts<commit_after>#include \"TMC2130Stepper.h\"\n\n#define REG_CHOPCONF 0x6C\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ REG_CHOPCONF\n\nuint32_t TMC2130Stepper::CHOPCONF() {\n\tuint32_t data = 0x0;\n\tsend2130(READ|REG_CHOPCONF, &data, 0x0, 0x0);\n\treturn data;\n}\n\nvoid TMC2130Stepper::CHOPCONF(uint32_t value) {\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xFFFFFFFF);\n}\n\nuint8_t TMC2130Stepper::off_time() {return val_toff;}\n\nvoid TMC2130Stepper::off_time(uint8_t value) {\n\tif (value > 15) value = 15;\n\tval_toff = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xF);\n}\n\nuint8_t TMC2130Stepper::hysterisis_start() {return val_hstrt;}\n\nvoid TMC2130Stepper::hysterisis_start(uint8_t value) {\n\tif (val_chm\t== 0) {\n\t\tif (value < 1) value = 1;\n\t\telse if (value > 8) value = 8;\n\t\tval_hstrt = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value-1) << 4, 0x70);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 1 -> fast_decay_time is in use. No change made.\");}\n#endif\t\n}\n\nuint8_t TMC2130Stepper::fast_decay_time() {return val_tfd;}\n\nvoid TMC2130Stepper::fast_decay_time(uint8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value > 15) value = 15;\n\t\tval_tfd = value;\n\t\tvalue = ((uint32_t)value << 4) | (value & 0b111); \/\/ Create space between MSB and the bits 0..2\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 4, 0x870);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> hysterisis_start is in use. No change made.\");}\n#endif\t\n}\n\nint8_t TMC2130Stepper::hysterisis_low() {return val_hend;}\n\nvoid TMC2130Stepper::hysterisis_low(int8_t value) {\n\tif (val_chm == 0) {\n\t\tif (value < -3) value = -3;\n\t\tif (value > 12) value = 12;\n\t\tval_hend = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 1 -> sine_offset is in use. No change made.\");}\n#endif\t\n}\n\nint8_t TMC2130Stepper::sine_offset() {return val_offset;}\n\nvoid TMC2130Stepper::sine_offset(int8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value < -3) value = -3;\n\t\tif (value > 12) value = 12;\n\t\tval_hend = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> hysterisis_low is in use. No change made.\");}\n#endif\t\n}\n\nuint8_t TMC2130Stepper::disable_I_comparator() {return val_disfdcc;}\n\nvoid TMC2130Stepper::disable_I_comparator(uint8_t value) {\n\tif (val_chm == 1) {\n\t\tif (value > 1) value = 1;\n\t\tval_disfdcc = value;\n\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 12, (uint32_t)0b1 << 12);\n\t}\n#ifdef TMC2130DEBUG\n\telse {Serial.println(\"chopper_mode bit is set to 0 -> No change made.\");}\n#endif\n}\n\nuint8_t TMC2130Stepper::random_off_time() {return val_rndtf;}\n\nvoid TMC2130Stepper::random_off_time(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_rndtf = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 13, (uint32_t)0b1 << 13);\n}\n\nuint8_t TMC2130Stepper::chopper_mode() {return val_chm;}\n\nvoid TMC2130Stepper::chopper_mode(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_chm = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 14, (uint32_t)0b1 << 14);\n}\n\nuint8_t TMC2130Stepper::blank_time() {return val_tbl;}\n\nvoid TMC2130Stepper::blank_time(uint8_t value) {\n\tuint8_t valid[] = {54, 36, 24, 16};\n\n\tif (value < valid[3]) value = valid[3]; \/\/ Make sure we find a match for low values\n\tfor (int i = 0; i<4; i++) {\n\t\tif (value >= valid[i]) {\n\t\t\tvalue = valid[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tval_tbl = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 15, 0x18000);\n}\n\nuint8_t TMC2130Stepper::high_sense_R() {return val_vsense;}\n\nvoid TMC2130Stepper::high_sense_R(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vsense = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 17, (uint32_t)0b1 << 17);\n}\n\nuint8_t TMC2130Stepper::fullstep_threshold() {return val_vhighfs;}\n\nvoid TMC2130Stepper::fullstep_threshold(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vhighfs = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 18, (uint32_t)0b1 << 18);\n}\n\nuint8_t TMC2130Stepper::high_speed_mode() {return val_vhighchm;}\n\nvoid TMC2130Stepper::high_speed_mode(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_vhighchm = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 19, (uint32_t)0b1 << 19);\n}\n\nuint8_t TMC2130Stepper::sync_phases() {return val_sync;}\n\nvoid TMC2130Stepper::sync_phases(uint8_t value) {\n\tif (value > 15) value = 15;\n\tval_sync = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 20, 0xF00000);\n}\n\nuint8_t TMC2130Stepper::microsteps() {return val_mres;}\n\nvoid TMC2130Stepper::microsteps(uint8_t value) {\n\tint valid[] \t= {\t\t256, \t128, \t 64, \t 32, \t 16, \t 8, \t 4, \t 2, \t 0 };\n\tuint32_t _hex[] = { 0b0000, 0b0001, 0b0010, 0b0011, 0b0100, 0b0101, 0b0110, 0b0111, 0b1000 };\n\n\tfor (int i = 0; i<9; i++) {\n\t\tif (value >= valid[i]) {\n\t\t\tval_mres = valid[i];\n\t\t\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, _hex[i] << 24, 0xF000000);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nuint8_t TMC2130Stepper::interpolate() {return val_intpol;}\n\nvoid TMC2130Stepper::interpolate(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_intpol = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 28, (uint32_t)0b1 << 28);\n}\n\nuint8_t TMC2130Stepper::double_edge_step() {return val_dedge;}\n\nvoid TMC2130Stepper::double_edge_step(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_dedge = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 29, (uint32_t)0b1 << 29);\n}\n\nuint8_t TMC2130Stepper::disable_short_protection() {return val_diss2g;}\n\nvoid TMC2130Stepper::disable_short_protection(uint8_t value) {\n\tif (value > 1) value = 1;\n\tval_diss2g = value;\n\tsend2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 30, (uint32_t)0b1 << 30);\n}<|endoftext|>"} {"text":"<commit_before>#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include <deque>\n#include <cassert>\n#include <functional>\n#include <iostream>\n#include <iterator>\n\n#include <boost\/array.hpp>\n#include <boost\/container\/set.hpp>\n#include <boost\/container\/node_allocator.hpp>\n#include <boost\/math\/special_functions\/round.hpp>\n#include <boost\/static_assert.hpp>\n#include <boost\/type_traits.hpp>\n\n\nnamespace rank_filter\n{\n\ntemplate<class I1,\n class I2>\ninline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,\n I2& dest_begin, I2& dest_end,\n size_t half_length, double rank)\n{\n \/\/ Types in use.\n typedef typename std::iterator_traits<I1>::value_type T1;\n typedef typename std::iterator_traits<I2>::value_type T2;\n typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;\n typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;\n\n \/\/ Establish common types to work with source and destination values.\n BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));\n typedef T1 T;\n typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;\n\n \/\/ Define container types that will be used.\n typedef boost::container::multiset< T,\n std::less<T>,\n boost::container::node_allocator<T>,\n boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;\n typedef std::deque< typename multiset::iterator > deque;\n\n \/\/ Lengths.\n const I_diff_t src_size = std::distance(src_begin, src_end);\n const I_diff_t dest_size = std::distance(dest_begin, dest_end);\n\n \/\/ Ensure the result will fit.\n assert(src_size <= dest_size);\n\n \/\/ Window length cannot exceed input data with reflection.\n assert((half_length + 1) <= src_size);\n\n \/\/ Rank must be in the range 0 to 1.\n assert((0 <= rank) && (rank <= 1));\n\n \/\/ The position of the window.\n I_diff_t window_begin = 0;\n\n \/\/ Window position corresponding to this rank.\n const I_diff_t rank_pos;\n typename multiset::iterator rank_point;\n\n \/\/ Track values in window both in sorted and sequential order.\n multiset sorted_window;\n deque window_iters(2 * half_length + 1);\n\n \/\/ Get the initial sorted window.\n \/\/ Include the reflection.\n for (I_diff_t j = 0; j < half_length; j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);\n }\n for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);\n }\n\n rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length)));\n rank_point = sorted_window.begin();\n for (I_diff_t i = 0; i < rank_pos; i++)\n {\n rank_point++;\n }\n\n typename multiset::iterator prev_iter;\n T prev_value;\n T next_value;\n while ( window_begin < src_size )\n {\n dest_begin[window_begin] = *rank_point;\n\n prev_iter = window_iters.front();\n prev_value = *prev_iter;\n window_iters.pop_front();\n\n window_begin++;\n\n if ( window_begin == src_size )\n {\n next_value = prev_value;\n }\n else if ( window_begin < (src_size - half_length) )\n {\n next_value = src_begin[window_begin + half_length];\n }\n else\n {\n next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);\n }\n\n if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )\n {\n if ( rank_point == prev_iter )\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point--;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n }\n else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point--;\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )\n {\n if (rank_point == prev_iter)\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point++;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point++;\n }\n }\n }\n}\n\n}\n\n\nnamespace std\n{\n template <class T, size_t N>\n ostream& operator<<(ostream& out, const boost::array<T, N>& that)\n {\n out << \"{ \";\n for (unsigned int i = 0; i < (N - 1); i++)\n {\n out << that[i] << \", \";\n }\n out << that[N - 1] << \" }\";\n\n return(out);\n }\n}\n\n\n#endif \/\/__RANK_FILTER__\n<commit_msg>Explain initialization of `rank_point`<commit_after>#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include <deque>\n#include <cassert>\n#include <functional>\n#include <iostream>\n#include <iterator>\n\n#include <boost\/array.hpp>\n#include <boost\/container\/set.hpp>\n#include <boost\/container\/node_allocator.hpp>\n#include <boost\/math\/special_functions\/round.hpp>\n#include <boost\/static_assert.hpp>\n#include <boost\/type_traits.hpp>\n\n\nnamespace rank_filter\n{\n\ntemplate<class I1,\n class I2>\ninline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,\n I2& dest_begin, I2& dest_end,\n size_t half_length, double rank)\n{\n \/\/ Types in use.\n typedef typename std::iterator_traits<I1>::value_type T1;\n typedef typename std::iterator_traits<I2>::value_type T2;\n typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;\n typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;\n\n \/\/ Establish common types to work with source and destination values.\n BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));\n typedef T1 T;\n typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;\n\n \/\/ Define container types that will be used.\n typedef boost::container::multiset< T,\n std::less<T>,\n boost::container::node_allocator<T>,\n boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;\n typedef std::deque< typename multiset::iterator > deque;\n\n \/\/ Lengths.\n const I_diff_t src_size = std::distance(src_begin, src_end);\n const I_diff_t dest_size = std::distance(dest_begin, dest_end);\n\n \/\/ Ensure the result will fit.\n assert(src_size <= dest_size);\n\n \/\/ Window length cannot exceed input data with reflection.\n assert((half_length + 1) <= src_size);\n\n \/\/ Rank must be in the range 0 to 1.\n assert((0 <= rank) && (rank <= 1));\n\n \/\/ The position of the window.\n I_diff_t window_begin = 0;\n\n \/\/ Window position corresponding to this rank.\n const I_diff_t rank_pos;\n typename multiset::iterator rank_point;\n\n \/\/ Track values in window both in sorted and sequential order.\n multiset sorted_window;\n deque window_iters(2 * half_length + 1);\n\n \/\/ Get the initial sorted window.\n \/\/ Include the reflection.\n for (I_diff_t j = 0; j < half_length; j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);\n }\n for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);\n }\n\n \/\/ Move our selection point to the corresponding rank.\n rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length)));\n rank_point = sorted_window.begin();\n for (I_diff_t i = 0; i < rank_pos; i++)\n {\n rank_point++;\n }\n\n typename multiset::iterator prev_iter;\n T prev_value;\n T next_value;\n while ( window_begin < src_size )\n {\n dest_begin[window_begin] = *rank_point;\n\n prev_iter = window_iters.front();\n prev_value = *prev_iter;\n window_iters.pop_front();\n\n window_begin++;\n\n if ( window_begin == src_size )\n {\n next_value = prev_value;\n }\n else if ( window_begin < (src_size - half_length) )\n {\n next_value = src_begin[window_begin + half_length];\n }\n else\n {\n next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);\n }\n\n if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )\n {\n if ( rank_point == prev_iter )\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point--;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n }\n else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point--;\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )\n {\n if (rank_point == prev_iter)\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point++;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point++;\n }\n }\n }\n}\n\n}\n\n\nnamespace std\n{\n template <class T, size_t N>\n ostream& operator<<(ostream& out, const boost::array<T, N>& that)\n {\n out << \"{ \";\n for (unsigned int i = 0; i < (N - 1); i++)\n {\n out << that[i] << \", \";\n }\n out << that[N - 1] << \" }\";\n\n return(out);\n }\n}\n\n\n#endif \/\/__RANK_FILTER__\n<|endoftext|>"} {"text":"<commit_before>\/\/ cg.cpp: multi-precision, preconditioned Conjugate Gradient iterative solver\n\/\/\n\/\/ Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n\/\/ Authors: Theodore Omtzigt\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#ifdef _MSC_VER\n#pragma warning(disable : 4514) \/\/ unreferenced inline function has been removed\n#pragma warning(disable : 4710) \/\/ 'int sprintf_s(char *const ,const size_t,const char *const ,...)': function not inlined\n#pragma warning(disable : 4820) \/\/ 'sw::unum::value<23>': '3' bytes padding added after data member 'sw::unum::value<23>::_sign'\n#pragma warning(disable : 5045) \/\/ Compiler will insert Spectre mitigation for memory load if \/Qspectre switch specified\n#endif\n\n\/\/ standard library\n#include <limits>\n\/\/ Configure the posit library with arithmetic exceptions\n\/\/ enable posit arithmetic exceptions\n#define POSIT_THROW_ARITHMETIC_EXCEPTION 1\n#include <universal\/posit\/posit>\n#include <universal\/blas\/blas.hpp>\n#include <universal\/blas\/generators.hpp>\n\n\/\/ cg: Solution of x in Ax=b using preconditioned Conjugate Gradient algorithm \n\/\/ with different precision for matrix-vector multiply and residual calculation\n\/\/ Input: \n\/\/ preconditioner M\n\/\/ system matrix A\n\/\/ right hand side b\n\/\/ accuracy tolerance for target solution\n\/\/ Output:\n\/\/ number of iterations to reach required accuracy\ntemplate<typename Matrix, typename Vector, size_t MAX_ITERATIONS = 10>\nsize_t cg(const Matrix& M, const Matrix& A, Vector& b, typename Matrix::value_type tolerance = typename Matrix::value_type(0.00001)) {\n\tusing Scalar = typename Matrix::value_type;\n\tScalar residual = Scalar(std::numeric_limits<Scalar>::max());\n\t\/\/size_t m = num_rows(A);\n\t\/\/size_t n = num_cols(A);\n\tVector x(size(b));\n\tVector rho(size(b));\n\tVector zeta(size(b));\n\tVector p(size(b));\n\tVector q(size(b));\n\tScalar sigma_1{ 0 }, sigma_2{ 0 }, alpha{ 0 }, beta{ 0 };\n\trho = b; \/\/ term is b - A * x, but if we use x(0) = 0 vector, rho = b is equivalent\n\tsize_t itr = 0;\n\tbool firstIteration = true;\n\twhile (residual > tolerance && itr < MAX_ITERATIONS) {\n\t\tzeta = sw::unum::blas::solve(M, rho);\n\t\tsigma_2 = sigma_1;\n\t\tsigma_1 = dot(zeta, rho); \/\/ dot product, fused dot product if Scalar is a posit type\n\t\tif (firstIteration) {\n\t\t\tfirstIteration = false;\n\t\t\tp = zeta;\n\t\t}\n\t\telse {\n\t\t\tbeta = sigma_1 \/ sigma_2;\n\t\t\tp = zeta + beta * p;\n\t\t}\n\t\tq = A * p;\n\t\talpha = sigma_1 \/ dot(p, q);\n\t\tVector x_1(x);\n\t\tx = x + alpha * p;\n\t\trho = rho - alpha * q;\n\t\t\/\/ check for convergence of the system\n\t\tresidual = norm1(x_1 - x);\n\t\tstd::cout << '[' << itr << \"] \" << x << \" residual \" << residual << std::endl;\n\t\t++itr;\n\t}\n\tstd::cout << \"solution in \" << itr << \" iterations\\n\";\n\tstd::cout << \"solution is \" << x << '\\n';\n\tstd::cout << \"final residual is \" << residual << '\\n';\n\tstd::cout << \"validation\\n\" << A * x << \" = \" << b << std::endl;\n\treturn itr;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tusing namespace sw::unum::blas;\n\n\tconstexpr size_t nbits = 32;\n\tconstexpr size_t es = 2;\n\tusing Scalar = posit<nbits, es>;\n\/\/\tusing Scalar = float;\n\tusing Matrix = sw::unum::blas::matrix<Scalar>;\n\tusing Vector = sw::unum::blas::vector<Scalar>;\n\n\tif (argc == 1) cout << argv[0] << '\\n';\n\tint nrOfFailedTestCases = 0;\n\n\t\/\/ Initialize 'A', preconditioner 'M', 'b' & intial guess 'x' * _\n\tconstexpr size_t DoF = 8;\n\tMatrix A;\n\ttridiag(A, DoF); \/\/ this does a resize of A\n\tMatrix M = eye<Scalar>(DoF);\n\tVector b(DoF);\n\tVector x(DoF);\n\tx = Scalar(1);\n\tb = A * x;\n\n\tcout << A << endl;\n\tcout << M << endl;\n\tcout << b << endl;\n\tconstexpr size_t MAX_ITERATIONS = 10;\n\tsize_t itr = cg<Matrix, Vector, MAX_ITERATIONS>(M, A, b);\n\n\tif (itr == MAX_ITERATIONS) {\n\t\tstd::cerr << \"Solution failed to converge\\n\";\n\t\t++nrOfFailedTestCases;\n\t}\n\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const std::runtime_error& err) {\n\tstd::cerr << \"Uncaught runtime exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n<commit_msg>adding an LU preconditioner to the mix: and results get worse....<commit_after>\/\/ cg.cpp: multi-precision, preconditioned Conjugate Gradient iterative solver\n\/\/\n\/\/ Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n\/\/ Authors: Theodore Omtzigt\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#ifdef _MSC_VER\n#pragma warning(disable : 4514) \/\/ unreferenced inline function has been removed\n#pragma warning(disable : 4710) \/\/ 'int sprintf_s(char *const ,const size_t,const char *const ,...)': function not inlined\n#pragma warning(disable : 4820) \/\/ 'sw::unum::value<23>': '3' bytes padding added after data member 'sw::unum::value<23>::_sign'\n#pragma warning(disable : 5045) \/\/ Compiler will insert Spectre mitigation for memory load if \/Qspectre switch specified\n#endif\n\n\/\/ standard library\n#include <limits>\n\/\/ Configure the posit library with arithmetic exceptions\n\/\/ enable posit arithmetic exceptions\n#define POSIT_THROW_ARITHMETIC_EXCEPTION 1\n#include <universal\/posit\/posit>\n#include <universal\/blas\/blas.hpp>\n#include <universal\/blas\/generators.hpp>\n\n\/\/ cg: Solution of x in Ax=b using preconditioned Conjugate Gradient algorithm \n\/\/ with different precision for matrix-vector multiply and residual calculation\n\/\/ Input: \n\/\/ preconditioner M\n\/\/ system matrix A\n\/\/ right hand side b\n\/\/ accuracy tolerance for target solution\n\/\/ Output:\n\/\/ number of iterations to reach required accuracy\ntemplate<typename Matrix, typename Vector, size_t MAX_ITERATIONS = 10>\nsize_t cg(const Matrix& M, const Matrix& A, Vector& b, typename Matrix::value_type tolerance = typename Matrix::value_type(0.00001)) {\n\tusing Scalar = typename Matrix::value_type;\n\tScalar residual = Scalar(std::numeric_limits<Scalar>::max());\n\t\/\/size_t m = num_rows(A);\n\t\/\/size_t n = num_cols(A);\n\tVector x(size(b));\n\tVector rho(size(b));\n\tVector zeta(size(b));\n\tVector p(size(b));\n\tVector q(size(b));\n\tScalar sigma_1{ 0 }, sigma_2{ 0 }, alpha{ 0 }, beta{ 0 };\n\trho = b; \/\/ term is b - A * x, but if we use x(0) = 0 vector, rho = b is equivalent\n\tsize_t itr = 0;\n\tbool firstIteration = true;\n\twhile (residual > tolerance && itr < MAX_ITERATIONS) {\n\t\tzeta = sw::unum::blas::solve(M, rho);\n\t\tsigma_2 = sigma_1;\n\t\tsigma_1 = dot(zeta, rho); \/\/ dot product, fused dot product if Scalar is a posit type\n\t\tif (firstIteration) {\n\t\t\tfirstIteration = false;\n\t\t\tp = zeta;\n\t\t}\n\t\telse {\n\t\t\tbeta = sigma_1 \/ sigma_2;\n\t\t\tp = zeta + beta * p;\n\t\t}\n\t\tq = A * p;\n\t\talpha = sigma_1 \/ dot(p, q);\n\t\tVector x_1(x);\n\t\tx = x + alpha * p;\n\t\trho = rho - alpha * q;\n\t\t\/\/ check for convergence of the system\n\t\tresidual = norm1(x_1 - x);\n\t\tstd::cout << '[' << itr << \"] \" << std::setw(12) << x << \" residual \" << residual << std::endl;\n\t\t++itr;\n\t}\n\tstd::cout << \"solution in \" << itr << \" iterations\\n\";\n\tstd::cout << \"solution is \" << x << '\\n';\n\tstd::cout << \"final residual is \" << residual << '\\n';\n\tstd::cout << \"validation\\n\" << A * x << \" = \" << b << std::endl;\n\treturn itr;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tusing namespace sw::unum::blas;\n\n\tconstexpr size_t nbits = 32;\n\tconstexpr size_t es = 2;\n\tusing Scalar = posit<nbits, es>;\n\/\/\tusing Scalar = float;\n\tusing Matrix = sw::unum::blas::matrix<Scalar>;\n\tusing Vector = sw::unum::blas::vector<Scalar>;\n\n\tif (argc == 1) cout << argv[0] << '\\n';\n\tint nrOfFailedTestCases = 0;\n\n\t\/\/ Initialize 'A', preconditioner 'M', 'b' & intial guess 'x' * _\n\tconstexpr size_t DoF = 8;\n\tMatrix A;\n\ttridiag(A, DoF); \/\/ this does a resize of A\n\tMatrix M = eye<Scalar>(DoF);\n\tVector b(DoF);\n\tVector x(DoF);\n\tx = Scalar(1);\n\tb = A * x;\n\n\tcout << A << endl;\n\tcout << M << endl;\n\tcout << b << endl;\n\tconstexpr size_t MAX_ITERATIONS = 10;\n\tsize_t itr = cg<Matrix, Vector, MAX_ITERATIONS>(M, A, b);\n\n\tif (itr == MAX_ITERATIONS) {\n\t\tstd::cerr << \"Solution failed to converge\\n\";\n\t\t++nrOfFailedTestCases;\n\t}\n\n\tM = sw::unum::blas::inv(A);\n\titr = cg<Matrix, Vector, MAX_ITERATIONS>(M, A, b);\n\n\tif (itr == MAX_ITERATIONS) {\n\t\tstd::cerr << \"Solution failed to converge\\n\";\n\t\t++nrOfFailedTestCases;\n\t}\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const std::runtime_error& err) {\n\tstd::cerr << \"Uncaught runtime exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FloatProperty.h\"\r\n#include \"ExposureProperty.h\"\r\n#include \"CallBackManager.h\"\r\n#include <cmath>\r\n#include <iomanip>\r\n\r\nusing namespace andor;\r\nusing namespace std;\r\n\r\nTExposureProperty::TExposureProperty(const string & MM_name, IFloat * float_feature, ICallBackManager* callback,\r\n bool readOnly, bool needsCallBack)\r\n: MM_name_(MM_name),\r\n float_feature_(float_feature),\r\n callback_(callback),\r\n callbackRegistered_(needsCallBack)\r\n{\r\n if (float_feature->IsImplemented())\r\n {\r\n CPropertyAction * pAct = new CPropertyAction (this, &TExposureProperty::OnFloat);\r\n callback->CPCCreateProperty(MM_name.c_str(), \"\", MM::Float, readOnly, pAct);\r\n\r\n try \r\n {\r\n if (needsCallBack)\r\n {\r\n float_feature_->Attach(this);\r\n }\r\n }\r\n catch (exception & e)\r\n {\r\n \/\/ SDK3 Callback not implemented for this feature\r\n callback->CPCLog(e.what());\r\n }\r\n }\r\n else\r\n {\r\n callbackRegistered_ = false;\r\n }\r\n}\r\n\r\nTExposureProperty::~TExposureProperty()\r\n{\r\n if (callbackRegistered_)\r\n {\r\n try \r\n {\r\n float_feature_->Detach(this);\r\n }\r\n catch (exception & e)\r\n {\r\n \/\/ SDK3 Callback not implemented for this feature\r\n callback_->CPCLog(e.what());\r\n }\r\n }\r\n \/\/Clean up memory, created as passed in\r\n callback_->GetCameraDevice()->Release(float_feature_);\r\n}\r\n\r\nvoid TExposureProperty::Update(ISubject * Subject)\r\n{\r\n \/\/if NOT Poised,... (Snapshot sets this first, then changes trigger silently\r\n \/\/ so once updates get applied, and repoise, snapshot sets true, so no erroneous updates get applied\r\n if ( !callback_->IsSSCPoised() )\r\n {\r\n IFloat * featureSubject = dynamic_cast<IFloat *>(Subject);\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache && featureSubject)\r\n {\r\n cache->SetCache(featureSubject->Get());\r\n }\r\n }\r\n}\r\n\r\nvoid TExposureProperty::setFeatureWithinLimits(double new_value)\r\n{\r\n try\r\n {\r\n if (new_value < float_feature_->Min())\r\n {\r\n new_value = float_feature_->Min();\r\n }\r\n else if (new_value > float_feature_->Max())\r\n {\r\n new_value = float_feature_->Max();\r\n }\r\n float_feature_->Set(new_value);\r\n }\r\n catch (exception & e)\r\n {\r\n callback_->CPCLog(e.what());\r\n }\r\n}\r\n\r\nbool TExposureProperty::valueIsWithinLimits(double new_value)\r\n{\r\n try\r\n {\r\n return new_value > float_feature_->Min() && new_value < float_feature_->Max();\r\n }\r\n catch (exception & e)\r\n {\r\n callback_->CPCLog(e.what());\r\n return false;\r\n }\r\n}\r\n\r\n\r\n\r\ninline bool almostEqual(double val1, double val2, int precisionFactor)\r\n{\r\n const double base = 10.0;\r\n double precisionError = 1.0 \/ pow(base, precisionFactor);\r\n \/\/ Check if val1 and val2 are within precision decimal places\r\n return ( val1 > (val2 - precisionError) && val1 < (val2 + precisionError)) ? true : false;\r\n}\r\n\r\nint TExposureProperty::OnFloat(MM::PropertyBase * pProp, MM::ActionType eAct)\r\n{\r\n if (eAct == MM::BeforeGet)\r\n {\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache)\r\n {\r\n pProp->Set(cache->Get(callback_->IsSSCPoised()));\r\n }\r\n else\r\n {\r\n pProp->Set(float_feature_->Get());\r\n }\r\n\r\n }\r\n else if (eAct == MM::AfterSet)\r\n {\r\n double new_value = 0.0, current_value = float_feature_->Get();\r\n pProp->Get(new_value);\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache)\r\n {\r\n current_value = cache->Get(callback_->IsSSCPoised());\r\n }\r\n if (!almostEqual(new_value, current_value, DEC_PLACES_ERROR))\r\n {\r\n if(valueIsWithinLimits(new_value))\r\n {\r\n setFeatureWithinLimits(new_value);\r\n }\r\n else\r\n {\r\n bool wasPoised = callback_->IsSSCPoised();\r\n\r\n if(wasPoised)\r\n callback_->SSCLeavePoised();\r\n \r\n setFeatureWithinLimits(new_value);\r\n \r\n if(wasPoised)\r\n callback_->SSCEnterPoised();\r\n }\r\n }\r\n }\r\n\r\n return DEVICE_OK;\r\n}\r\n\r\n\r\n<commit_msg>Fix for fast exposure switching - it did not check iswritable, so sometimes the user's value would not be set. Now, if the exposureTime is not writable the current acquisition will be stopped, and restarted after the change. The problem was only re-created using a 4.2 10-tap Zyla with overlap off.<commit_after>#include \"FloatProperty.h\"\r\n#include \"ExposureProperty.h\"\r\n#include \"CallBackManager.h\"\r\n#include <cmath>\r\n#include <iomanip>\r\n\r\nusing namespace andor;\r\nusing namespace std;\r\n\r\nTExposureProperty::TExposureProperty(const string & MM_name, IFloat * float_feature, ICallBackManager* callback,\r\n bool readOnly, bool needsCallBack)\r\n: MM_name_(MM_name),\r\n float_feature_(float_feature),\r\n callback_(callback),\r\n callbackRegistered_(needsCallBack)\r\n{\r\n if (float_feature->IsImplemented())\r\n {\r\n CPropertyAction * pAct = new CPropertyAction (this, &TExposureProperty::OnFloat);\r\n callback->CPCCreateProperty(MM_name.c_str(), \"\", MM::Float, readOnly, pAct);\r\n\r\n try \r\n {\r\n if (needsCallBack)\r\n {\r\n float_feature_->Attach(this);\r\n }\r\n }\r\n catch (exception & e)\r\n {\r\n \/\/ SDK3 Callback not implemented for this feature\r\n callback->CPCLog(e.what());\r\n }\r\n }\r\n else\r\n {\r\n callbackRegistered_ = false;\r\n }\r\n}\r\n\r\nTExposureProperty::~TExposureProperty()\r\n{\r\n if (callbackRegistered_)\r\n {\r\n try \r\n {\r\n float_feature_->Detach(this);\r\n }\r\n catch (exception & e)\r\n {\r\n \/\/ SDK3 Callback not implemented for this feature\r\n callback_->CPCLog(e.what());\r\n }\r\n }\r\n \/\/Clean up memory, created as passed in\r\n callback_->GetCameraDevice()->Release(float_feature_);\r\n}\r\n\r\nvoid TExposureProperty::Update(ISubject * Subject)\r\n{\r\n \/\/if NOT Poised,... (Snapshot sets this first, then changes trigger silently\r\n \/\/ so once updates get applied, and repoise, snapshot sets true, so no erroneous updates get applied\r\n if ( !callback_->IsSSCPoised() )\r\n {\r\n IFloat * featureSubject = dynamic_cast<IFloat *>(Subject);\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache && featureSubject)\r\n {\r\n cache->SetCache(featureSubject->Get());\r\n }\r\n }\r\n}\r\n\r\nvoid TExposureProperty::setFeatureWithinLimits(double new_value)\r\n{\r\n try\r\n {\r\n if (new_value < float_feature_->Min())\r\n {\r\n new_value = float_feature_->Min();\r\n }\r\n else if (new_value > float_feature_->Max())\r\n {\r\n new_value = float_feature_->Max();\r\n }\r\n float_feature_->Set(new_value);\r\n }\r\n catch (exception & e)\r\n {\r\n callback_->CPCLog(e.what());\r\n }\r\n}\r\n\r\nbool TExposureProperty::valueIsWithinLimits(double new_value)\r\n{\r\n try\r\n {\r\n return new_value > float_feature_->Min() && new_value < float_feature_->Max();\r\n }\r\n catch (exception & e)\r\n {\r\n callback_->CPCLog(e.what());\r\n return false;\r\n }\r\n}\r\n\r\n\r\n\r\ninline bool almostEqual(double val1, double val2, int precisionFactor)\r\n{\r\n const double base = 10.0;\r\n double precisionError = 1.0 \/ pow(base, precisionFactor);\r\n \/\/ Check if val1 and val2 are within precision decimal places\r\n return ( val1 > (val2 - precisionError) && val1 < (val2 + precisionError)) ? true : false;\r\n}\r\n\r\nint TExposureProperty::OnFloat(MM::PropertyBase * pProp, MM::ActionType eAct)\r\n{\r\n if (eAct == MM::BeforeGet)\r\n {\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache)\r\n {\r\n pProp->Set(cache->Get(callback_->IsSSCPoised()));\r\n }\r\n else\r\n {\r\n pProp->Set(float_feature_->Get());\r\n }\r\n\r\n }\r\n else if (eAct == MM::AfterSet)\r\n {\r\n double new_value = 0.0, current_value = float_feature_->Get();\r\n pProp->Get(new_value);\r\n TAndorFloatCache * cache = dynamic_cast<TAndorFloatCache *>(float_feature_);\r\n if (cache)\r\n {\r\n current_value = cache->Get(callback_->IsSSCPoised());\r\n }\r\n if (!almostEqual(new_value, current_value, DEC_PLACES_ERROR))\r\n {\r\n if(valueIsWithinLimits(new_value) && float_feature_->IsWritable())\r\n {\r\n setFeatureWithinLimits(new_value);\r\n }\r\n else\r\n {\r\n bool wasPoised = callback_->IsSSCPoised();\r\n\r\n if(wasPoised)\r\n callback_->SSCLeavePoised();\r\n \r\n setFeatureWithinLimits(new_value);\r\n \r\n if(wasPoised)\r\n callback_->SSCEnterPoised();\r\n }\r\n }\r\n }\r\n\r\n return DEVICE_OK;\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2011, Rice University\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Rice University nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Authors: Alejandro Perez, Sertac Karaman, Ryan Luna, Ioan Sucan *\/\n\n#include \"ompl\/geometric\/planners\/rrt\/RRTstar.h\"\n#include \"ompl\/base\/goals\/GoalSampleableRegion.h\"\n#include \"ompl\/tools\/config\/SelfConfig.h\"\n#include \"ompl\/tools\/config\/MagicConstants.h\"\n#include <algorithm>\n#include <limits>\n#include <map>\n#include <boost\/math\/constants\/constants.hpp>\n\nompl::geometric::RRTstar::RRTstar(const base::SpaceInformationPtr &si) : base::Planner(si, \"RRTstar\")\n{\n specs_.approximateSolutions = true;\n specs_.optimizingPaths = true;\n\n goalBias_ = 0.05;\n maxDistance_ = 0.0;\n delayCC_ = true;\n iterations_ = 0;\n lastGoalMotion_ = NULL;\n\n Planner::declareParam<double>(\"range\", this, &RRTstar::setRange, &RRTstar::getRange, \"0.:1.:10000.\");\n Planner::declareParam<double>(\"goal_bias\", this, &RRTstar::setGoalBias, &RRTstar::getGoalBias, \"0.:.05:1.\");\n Planner::declareParam<bool>(\"delay_collision_checking\", this, &RRTstar::setDelayCC, &RRTstar::getDelayCC, \"0,1\");\n}\n\nompl::geometric::RRTstar::~RRTstar(void)\n{\n freeMemory();\n}\n\nvoid ompl::geometric::RRTstar::setup(void)\n{\n Planner::setup();\n tools::SelfConfig sc(si_, getName());\n sc.configurePlannerRange(maxDistance_);\n\n if (!nn_)\n nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(si_->getStateSpace()));\n nn_->setDistanceFunction(boost::bind(&RRTstar::distanceFunction, this, _1, _2));\n}\n\nvoid ompl::geometric::RRTstar::clear(void)\n{\n Planner::clear();\n sampler_.reset();\n freeMemory();\n if (nn_)\n nn_->clear();\n iterations_ = 0;\n lastGoalMotion_ = NULL;\n goalMotions_.clear();\n}\n\nompl::base::PlannerStatus ompl::geometric::RRTstar::solve(const base::PlannerTerminationCondition &ptc)\n{\n checkValidity();\n base::Goal *goal = pdef_->getGoal().get();\n base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion*>(goal);\n base::OptimizationObjective *opt = pdef_->getOptimizationObjective().get();\n\n \/\/ when no optimization objective is specified, we create a temporary one (we should not modify the ProblemDefinition)\n boost::scoped_ptr<base::OptimizationObjective> temporaryOptimizationObjective;\n\n if (opt && !dynamic_cast<base::PathLengthOptimizationObjective*>(opt))\n {\n opt = NULL;\n OMPL_WARN(\"Optimization objective '%s' specified, but such an objective is not appropriate for %s. Only path length can be optimized.\", getName().c_str(), opt->getDescription().c_str());\n }\n\n if (!opt)\n {\n \/\/ by default, optimize path length and run until completion\n opt = new base::PathLengthOptimizationObjective(si_, std::numeric_limits<double>::epsilon());\n temporaryOptimizationObjective.reset(opt);\n OMPL_INFORM(\"No optimization objective specified. Defaulting to optimization of path length for the allowed planning time.\");\n }\n\n if (!goal)\n {\n OMPL_ERROR(\"Goal undefined\");\n return base::PlannerStatus::INVALID_GOAL;\n }\n\n while (const base::State *st = pis_.nextStart())\n {\n Motion *motion = new Motion(si_);\n si_->copyState(motion->state, st);\n nn_->add(motion);\n }\n\n if (nn_->size() == 0)\n {\n OMPL_ERROR(\"There are no valid initial states!\");\n return base::PlannerStatus::INVALID_START;\n }\n\n if (!sampler_)\n sampler_ = si_->allocStateSampler();\n\n OMPL_INFORM(\"Starting with %u states\", nn_->size());\n\n Motion *solution = lastGoalMotion_;\n Motion *approximation = NULL;\n double approximatedist = std::numeric_limits<double>::infinity();\n bool sufficientlyShort = false;\n\n Motion *rmotion = new Motion(si_);\n base::State *rstate = rmotion->state;\n base::State *xstate = si_->allocState();\n\n \/\/ e+e\/d. K-nearest RRT*\n double k_rrg = boost::math::constants::e<double>() + (boost::math::constants::e<double>()\/(double)si_->getStateSpace()->getDimension());\n\n std::vector<Motion*> nbh;\n std::vector<double> dists;\n std::vector<std::size_t> sortedDistIndices;\n std::vector<int> valid;\n unsigned int rewireTest = 0;\n unsigned int statesGenerated = 0;\n\n if(solution)\n OMPL_INFORM(\"Starting with existing solution of cost %.5f\", solution->cost);\n OMPL_INFORM(\"Initial k-nearest value of %u\", (unsigned int)std::ceil(k_rrg * log((double)nn_->size()+1)));\n\n NeighborIndexCompare compareFn(nbh);\n\n while (ptc == false)\n {\n iterations_++;\n \/\/ sample random state (with goal biasing)\n \/\/ Goal samples are only sampled until maxSampleCount() goals are in the tree, to prohibit duplicate goal states.\n if (goal_s && goalMotions_.size() < goal_s->maxSampleCount() && rng_.uniform01() < goalBias_ && goal_s->canSample())\n goal_s->sampleGoal(rstate);\n else\n sampler_->sampleUniform(rstate);\n\n \/\/ find closest state in the tree\n Motion *nmotion = nn_->nearest(rmotion);\n\n base::State *dstate = rstate;\n\n \/\/ find state to add to the tree\n double d = si_->distance(nmotion->state, rstate);\n if (d > maxDistance_)\n {\n si_->getStateSpace()->interpolate(nmotion->state, rstate, maxDistance_ \/ d, xstate);\n dstate = xstate;\n }\n\n \/\/ Check if the motion between the nearest state and the state to add is valid\n if (si_->checkMotion(nmotion->state, dstate))\n {\n \/\/ Duplicate the sampled motion\n double distN = si_->distance(dstate, nmotion->state);\n Motion *motion = new Motion(si_);\n si_->copyState(motion->state, dstate);\n motion->parent = nmotion;\n\n \/\/ Find nearby neighbors of the new motion - k-nearest RRT*\n unsigned int k = std::ceil(k_rrg * log((double)nn_->size()+1));\n nn_->nearestK(motion, k, nbh);\n rewireTest += nbh.size();\n statesGenerated++;\n\n \/\/ cache for distance computations\n dists.resize(nbh.size());\n sortedDistIndices.resize(nbh.size());\n for (std::size_t i = 0; i < sortedDistIndices.size(); ++i)\n sortedDistIndices[i] = i;\n \/\/ cache for motion validity\n valid.resize(nbh.size());\n std::fill(valid.begin(), valid.end(), 0);\n\n \/\/ Finding the nearest neighbor to connect to\n \/\/ By default, neighborhood states are sorted by distance, and collision checking\n \/\/ is performed in increasing order of distance\n if (delayCC_)\n {\n \/\/ calculate all costs and distances\n for (unsigned int i = 0; i < nbh.size(); ++i)\n {\n double d = si_->distance(nbh[i]->state, motion->state);\n dists[i] = d;\n nbh[i]->cost += d;\n }\n\n \/\/ sort the nodes\n std::sort(sortedDistIndices.begin(), sortedDistIndices.end(), compareFn);\n\n for (unsigned int i = 0; i < nbh.size(); ++i)\n nbh[i]->cost -= dists[i];\n\n \/\/ Collision check until a valid motion is found\n \/\/ The first one found is the min, since the neighbors are sorted\n for (std::vector<std::size_t>::const_iterator i = sortedDistIndices.begin();\n i != sortedDistIndices.end();\n ++i)\n {\n if (nbh[*i] == nmotion || si_->checkMotion(nbh[*i]->state, motion->state))\n {\n motion->cost = nbh[*i]->cost + dists[*i];\n motion->parent = nbh[*i];\n valid[*i] = 1;\n break;\n }\n else\n valid[*i] = -1;\n }\n }\n else\n {\n motion->cost = distN;\n \/\/ find which one we connect the new state to\n for (unsigned int i = 0 ; i < nbh.size() ; ++i)\n {\n if (nbh[i] != nmotion)\n {\n double d = si_->distance(nbh[i]->state, dstate);\n dists[i] = d;\n double c = nbh[i]->cost + d;\n if (c < motion->cost)\n {\n if (si_->checkMotion(nbh[i]->state, motion->state))\n {\n motion->cost = c;\n motion->parent = nbh[i];\n valid[i] = 1;\n }\n else\n valid[i] = -1;\n }\n }\n else\n {\n valid[i] = 1;\n dists[i] = distN;\n }\n }\n }\n\n \/\/ add motion to the tree\n nn_->add(motion);\n motion->parent->children.push_back(motion);\n\n \/\/ rewire tree if needed\n bool checkForSolution = false;\n for (unsigned int i = 0; i < nbh.size(); ++i)\n {\n if (nbh[i] == motion->parent) continue;\n\n double newcost = motion->cost + dists[i];\n if (newcost < nbh[i]->cost)\n {\n \/\/ Check if the motion to the neighbor is valid\n bool v = (valid[i] == 0 ? si_->checkMotion(nbh[i]->state, motion->state) : valid[i] == 1);\n if (v)\n {\n \/\/ Need to subtract the difference in cost from all of the node's in the neighbor's subtree\n double delta = newcost - nbh[i]->cost;\n \/\/ Remove the neighbor node from it's parent's child list\n removeFromParent(nbh[i]);\n\n \/\/ Add the neighbor node as a child of motion\n nbh[i]->parent = motion;\n nbh[i]->cost = newcost;\n motion->children.push_back(nbh[i]);\n\n updateChildCosts(nbh[i], delta);\n checkForSolution = true;\n }\n }\n }\n\n \/\/ Add the new motion to the goalMotion_ list, if it satisfies the goal\n double distanceFromGoal;\n if (goal->isSatisfied(motion->state, &distanceFromGoal))\n {\n goalMotions_.push_back(motion);\n checkForSolution = true;\n }\n\n \/\/ Checking for solution or iterative improvement\n for (size_t i = 0; i < goalMotions_.size() && checkForSolution; ++i)\n {\n sufficientlyShort = opt->isSatisfied(goalMotions_[i]->cost);\n if (sufficientlyShort)\n {\n solution = goalMotions_[i];\n break;\n }\n else if (!solution || goalMotions_[i]->cost < solution->cost)\n {\n solution = goalMotions_[i];\n }\n }\n\n \/\/ Checking for approximate solution (closest state found to the goal)\n if (goalMotions_.size() == 0 && distanceFromGoal < approximatedist)\n {\n approximation = motion;\n approximatedist = distanceFromGoal;\n }\n }\n\n \/\/ terminate if a sufficient solution is found\n if (solution && sufficientlyShort)\n break;\n }\n\n bool approximate = (solution == NULL);\n bool addedSolution = false;\n if (approximate)\n solution = approximation;\n else\n lastGoalMotion_ = solution;\n\n if (solution != NULL)\n {\n \/\/ construct the solution path\n std::vector<Motion*> mpath;\n while (solution != NULL)\n {\n mpath.push_back(solution);\n solution = solution->parent;\n }\n\n \/\/ set the solution path\n PathGeometric *geopath = new PathGeometric(si_);\n for (int i = mpath.size() - 1 ; i >= 0 ; --i)\n geopath->append(mpath[i]->state);\n\n base::PathPtr path(geopath);\n \/\/ Add the solution path, whether it is approximate (not reaching the goal), and the\n \/\/ distance from the end of the path to the goal (-1 if satisfying the goal).\n base::PlannerSolution psol(path, approximate, approximate ? approximatedist : -1.0);\n \/\/ Does the solution satisfy the optimization objective?\n psol.optimized_ = sufficientlyShort;\n\n pdef_->addSolutionPath (psol);\n\n addedSolution = true;\n }\n\n si_->freeState(xstate);\n if (rmotion->state)\n si_->freeState(rmotion->state);\n delete rmotion;\n\n OMPL_INFORM(\"Created %u new states. Checked %lu rewire options. %u goal states in tree.\", statesGenerated, rewireTest, goalMotions_.size());\n\n return base::PlannerStatus(addedSolution, approximate);\n}\n\nvoid ompl::geometric::RRTstar::removeFromParent(Motion *m)\n{\n std::vector<Motion*>::iterator it = m->parent->children.begin ();\n while (it != m->parent->children.end ())\n {\n if (*it == m)\n {\n it = m->parent->children.erase(it);\n it = m->parent->children.end ();\n }\n else\n ++it;\n }\n}\n\nvoid ompl::geometric::RRTstar::updateChildCosts(Motion *m, double delta)\n{\n for (size_t i = 0; i < m->children.size(); ++i)\n {\n m->children[i]->cost += delta;\n updateChildCosts(m->children[i], delta);\n }\n}\n\nvoid ompl::geometric::RRTstar::freeMemory(void)\n{\n if (nn_)\n {\n std::vector<Motion*> motions;\n nn_->list(motions);\n for (unsigned int i = 0 ; i < motions.size() ; ++i)\n {\n if (motions[i]->state)\n si_->freeState(motions[i]->state);\n delete motions[i];\n }\n }\n}\n\nvoid ompl::geometric::RRTstar::getPlannerData(base::PlannerData &data) const\n{\n Planner::getPlannerData(data);\n\n std::vector<Motion*> motions;\n if (nn_)\n nn_->list(motions);\n\n if (lastGoalMotion_)\n data.addGoalVertex(base::PlannerDataVertex(lastGoalMotion_->state));\n\n for (unsigned int i = 0 ; i < motions.size() ; ++i)\n {\n if (motions[i]->parent == NULL)\n data.addStartVertex(base::PlannerDataVertex(motions[i]->state));\n else\n data.addEdge(base::PlannerDataVertex(motions[i]->parent->state),\n base::PlannerDataVertex(motions[i]->state));\n }\n\n data.properties[\"iterations INTEGER\"] = boost::lexical_cast<std::string>(iterations_);\n}\n<commit_msg>Fixed bug in RRTstar when it runs with delayCC_ OFF<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2011, Rice University\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Rice University nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Authors: Alejandro Perez, Sertac Karaman, Ryan Luna, Ioan Sucan *\/\n\n#include \"ompl\/geometric\/planners\/rrt\/RRTstar.h\"\n#include \"ompl\/base\/goals\/GoalSampleableRegion.h\"\n#include \"ompl\/tools\/config\/SelfConfig.h\"\n#include \"ompl\/tools\/config\/MagicConstants.h\"\n#include <algorithm>\n#include <limits>\n#include <map>\n#include <boost\/math\/constants\/constants.hpp>\n\nompl::geometric::RRTstar::RRTstar(const base::SpaceInformationPtr &si) : base::Planner(si, \"RRTstar\")\n{\n specs_.approximateSolutions = true;\n specs_.optimizingPaths = true;\n\n goalBias_ = 0.05;\n maxDistance_ = 0.0;\n delayCC_ = true;\n iterations_ = 0;\n lastGoalMotion_ = NULL;\n\n Planner::declareParam<double>(\"range\", this, &RRTstar::setRange, &RRTstar::getRange, \"0.:1.:10000.\");\n Planner::declareParam<double>(\"goal_bias\", this, &RRTstar::setGoalBias, &RRTstar::getGoalBias, \"0.:.05:1.\");\n Planner::declareParam<bool>(\"delay_collision_checking\", this, &RRTstar::setDelayCC, &RRTstar::getDelayCC, \"0,1\");\n}\n\nompl::geometric::RRTstar::~RRTstar(void)\n{\n freeMemory();\n}\n\nvoid ompl::geometric::RRTstar::setup(void)\n{\n Planner::setup();\n tools::SelfConfig sc(si_, getName());\n sc.configurePlannerRange(maxDistance_);\n\n if (!nn_)\n nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Motion*>(si_->getStateSpace()));\n nn_->setDistanceFunction(boost::bind(&RRTstar::distanceFunction, this, _1, _2));\n}\n\nvoid ompl::geometric::RRTstar::clear(void)\n{\n Planner::clear();\n sampler_.reset();\n freeMemory();\n if (nn_)\n nn_->clear();\n iterations_ = 0;\n lastGoalMotion_ = NULL;\n goalMotions_.clear();\n}\n\nompl::base::PlannerStatus ompl::geometric::RRTstar::solve(const base::PlannerTerminationCondition &ptc)\n{\n checkValidity();\n base::Goal *goal = pdef_->getGoal().get();\n base::GoalSampleableRegion *goal_s = dynamic_cast<base::GoalSampleableRegion*>(goal);\n base::OptimizationObjective *opt = pdef_->getOptimizationObjective().get();\n\n \/\/ when no optimization objective is specified, we create a temporary one (we should not modify the ProblemDefinition)\n boost::scoped_ptr<base::OptimizationObjective> temporaryOptimizationObjective;\n\n if (opt && !dynamic_cast<base::PathLengthOptimizationObjective*>(opt))\n {\n opt = NULL;\n OMPL_WARN(\"Optimization objective '%s' specified, but such an objective is not appropriate for %s. Only path length can be optimized.\", getName().c_str(), opt->getDescription().c_str());\n }\n\n if (!opt)\n {\n \/\/ by default, optimize path length and run until completion\n opt = new base::PathLengthOptimizationObjective(si_, std::numeric_limits<double>::epsilon());\n temporaryOptimizationObjective.reset(opt);\n OMPL_INFORM(\"No optimization objective specified. Defaulting to optimization of path length for the allowed planning time.\");\n }\n\n if (!goal)\n {\n OMPL_ERROR(\"Goal undefined\");\n return base::PlannerStatus::INVALID_GOAL;\n }\n\n while (const base::State *st = pis_.nextStart())\n {\n Motion *motion = new Motion(si_);\n si_->copyState(motion->state, st);\n nn_->add(motion);\n }\n\n if (nn_->size() == 0)\n {\n OMPL_ERROR(\"There are no valid initial states!\");\n return base::PlannerStatus::INVALID_START;\n }\n\n if (!sampler_)\n sampler_ = si_->allocStateSampler();\n\n OMPL_INFORM(\"Starting with %u states\", nn_->size());\n\n Motion *solution = lastGoalMotion_;\n Motion *approximation = NULL;\n double approximatedist = std::numeric_limits<double>::infinity();\n bool sufficientlyShort = false;\n\n Motion *rmotion = new Motion(si_);\n base::State *rstate = rmotion->state;\n base::State *xstate = si_->allocState();\n\n \/\/ e+e\/d. K-nearest RRT*\n double k_rrg = boost::math::constants::e<double>() + (boost::math::constants::e<double>()\/(double)si_->getStateSpace()->getDimension());\n\n std::vector<Motion*> nbh;\n std::vector<double> dists;\n std::vector<std::size_t> sortedDistIndices;\n std::vector<int> valid;\n unsigned int rewireTest = 0;\n unsigned int statesGenerated = 0;\n\n if(solution)\n OMPL_INFORM(\"Starting with existing solution of cost %.5f\", solution->cost);\n OMPL_INFORM(\"Initial k-nearest value of %u\", (unsigned int)std::ceil(k_rrg * log((double)nn_->size()+1)));\n\n NeighborIndexCompare compareFn(nbh);\n\n while (ptc == false)\n {\n iterations_++;\n \/\/ sample random state (with goal biasing)\n \/\/ Goal samples are only sampled until maxSampleCount() goals are in the tree, to prohibit duplicate goal states.\n if (goal_s && goalMotions_.size() < goal_s->maxSampleCount() && rng_.uniform01() < goalBias_ && goal_s->canSample())\n goal_s->sampleGoal(rstate);\n else\n sampler_->sampleUniform(rstate);\n\n \/\/ find closest state in the tree\n Motion *nmotion = nn_->nearest(rmotion);\n\n base::State *dstate = rstate;\n\n \/\/ find state to add to the tree\n double d = si_->distance(nmotion->state, rstate);\n if (d > maxDistance_)\n {\n si_->getStateSpace()->interpolate(nmotion->state, rstate, maxDistance_ \/ d, xstate);\n dstate = xstate;\n }\n\n \/\/ Check if the motion between the nearest state and the state to add is valid\n if (si_->checkMotion(nmotion->state, dstate))\n {\n \/\/ Duplicate the sampled motion\n double distN = si_->distance(dstate, nmotion->state);\n Motion *motion = new Motion(si_);\n si_->copyState(motion->state, dstate);\n motion->parent = nmotion;\n\n \/\/ Find nearby neighbors of the new motion - k-nearest RRT*\n unsigned int k = std::ceil(k_rrg * log((double)nn_->size()+1));\n nn_->nearestK(motion, k, nbh);\n rewireTest += nbh.size();\n statesGenerated++;\n\n \/\/ cache for distance computations\n dists.resize(nbh.size());\n sortedDistIndices.resize(nbh.size());\n for (std::size_t i = 0; i < sortedDistIndices.size(); ++i)\n sortedDistIndices[i] = i;\n \/\/ cache for motion validity\n valid.resize(nbh.size());\n std::fill(valid.begin(), valid.end(), 0);\n\n \/\/ Finding the nearest neighbor to connect to\n \/\/ By default, neighborhood states are sorted by distance, and collision checking\n \/\/ is performed in increasing order of distance\n if (delayCC_)\n {\n \/\/ calculate all costs and distances\n for (unsigned int i = 0; i < nbh.size(); ++i)\n {\n double d = si_->distance(nbh[i]->state, motion->state);\n dists[i] = d;\n nbh[i]->cost += d;\n }\n\n \/\/ sort the nodes\n std::sort(sortedDistIndices.begin(), sortedDistIndices.end(), compareFn);\n\n for (unsigned int i = 0; i < nbh.size(); ++i)\n nbh[i]->cost -= dists[i];\n\n \/\/ Collision check until a valid motion is found\n \/\/ The first one found is the min, since the neighbors are sorted\n for (std::vector<std::size_t>::const_iterator i = sortedDistIndices.begin();\n i != sortedDistIndices.end();\n ++i)\n {\n if (nbh[*i] == nmotion || si_->checkMotion(nbh[*i]->state, motion->state))\n {\n motion->cost = nbh[*i]->cost + dists[*i];\n motion->parent = nbh[*i];\n valid[*i] = 1;\n break;\n }\n else\n valid[*i] = -1;\n }\n }\n else\n {\n motion->cost = nmotion->cost + distN;\n \/\/ find which one we connect the new state to\n for (unsigned int i = 0 ; i < nbh.size() ; ++i)\n {\n if (nbh[i] != nmotion)\n {\n double d = si_->distance(nbh[i]->state, dstate);\n dists[i] = d;\n double c = nbh[i]->cost + d;\n if (c < motion->cost)\n {\n if (si_->checkMotion(nbh[i]->state, motion->state))\n {\n motion->cost = c;\n motion->parent = nbh[i];\n valid[i] = 1;\n }\n else\n valid[i] = -1;\n }\n }\n else\n {\n valid[i] = 1;\n dists[i] = distN;\n }\n }\n }\n\n \/\/ add motion to the tree\n nn_->add(motion);\n motion->parent->children.push_back(motion);\n\n \/\/ rewire tree if needed\n bool checkForSolution = false;\n for (unsigned int i = 0; i < nbh.size(); ++i)\n {\n if (nbh[i] == motion->parent) continue;\n\n double newcost = motion->cost + dists[i];\n if (newcost < nbh[i]->cost)\n {\n \/\/ Check if the motion to the neighbor is valid\n bool v = (valid[i] == 0 ? si_->checkMotion(nbh[i]->state, motion->state) : valid[i] == 1);\n if (v)\n {\n \/\/ Need to subtract the difference in cost from all of the node's in the neighbor's subtree\n double delta = newcost - nbh[i]->cost;\n \/\/ Remove the neighbor node from it's parent's child list\n removeFromParent(nbh[i]);\n\n \/\/ Add the neighbor node as a child of motion\n nbh[i]->parent = motion;\n nbh[i]->cost = newcost;\n motion->children.push_back(nbh[i]);\n\n updateChildCosts(nbh[i], delta);\n checkForSolution = true;\n }\n }\n }\n\n \/\/ Add the new motion to the goalMotion_ list, if it satisfies the goal\n double distanceFromGoal;\n if (goal->isSatisfied(motion->state, &distanceFromGoal))\n {\n goalMotions_.push_back(motion);\n checkForSolution = true;\n }\n\n \/\/ Checking for solution or iterative improvement\n for (size_t i = 0; i < goalMotions_.size() && checkForSolution; ++i)\n {\n sufficientlyShort = opt->isSatisfied(goalMotions_[i]->cost);\n if (sufficientlyShort)\n {\n solution = goalMotions_[i];\n break;\n }\n else if (!solution || goalMotions_[i]->cost < solution->cost)\n {\n solution = goalMotions_[i];\n }\n }\n\n \/\/ Checking for approximate solution (closest state found to the goal)\n if (goalMotions_.size() == 0 && distanceFromGoal < approximatedist)\n {\n approximation = motion;\n approximatedist = distanceFromGoal;\n }\n }\n\n \/\/ terminate if a sufficient solution is found\n if (solution && sufficientlyShort)\n break;\n }\n\n bool approximate = (solution == NULL);\n bool addedSolution = false;\n if (approximate)\n solution = approximation;\n else\n lastGoalMotion_ = solution;\n\n if (solution != NULL)\n {\n \/\/ construct the solution path\n std::vector<Motion*> mpath;\n while (solution != NULL)\n {\n mpath.push_back(solution);\n solution = solution->parent;\n }\n\n \/\/ set the solution path\n PathGeometric *geopath = new PathGeometric(si_);\n for (int i = mpath.size() - 1 ; i >= 0 ; --i)\n geopath->append(mpath[i]->state);\n\n base::PathPtr path(geopath);\n \/\/ Add the solution path, whether it is approximate (not reaching the goal), and the\n \/\/ distance from the end of the path to the goal (-1 if satisfying the goal).\n base::PlannerSolution psol(path, approximate, approximate ? approximatedist : -1.0);\n \/\/ Does the solution satisfy the optimization objective?\n psol.optimized_ = sufficientlyShort;\n\n pdef_->addSolutionPath (psol);\n\n addedSolution = true;\n }\n\n si_->freeState(xstate);\n if (rmotion->state)\n si_->freeState(rmotion->state);\n delete rmotion;\n\n OMPL_INFORM(\"Created %u new states. Checked %lu rewire options. %u goal states in tree.\", statesGenerated, rewireTest, goalMotions_.size());\n\n return base::PlannerStatus(addedSolution, approximate);\n}\n\nvoid ompl::geometric::RRTstar::removeFromParent(Motion *m)\n{\n std::vector<Motion*>::iterator it = m->parent->children.begin ();\n while (it != m->parent->children.end ())\n {\n if (*it == m)\n {\n it = m->parent->children.erase(it);\n it = m->parent->children.end ();\n }\n else\n ++it;\n }\n}\n\nvoid ompl::geometric::RRTstar::updateChildCosts(Motion *m, double delta)\n{\n for (size_t i = 0; i < m->children.size(); ++i)\n {\n m->children[i]->cost += delta;\n updateChildCosts(m->children[i], delta);\n }\n}\n\nvoid ompl::geometric::RRTstar::freeMemory(void)\n{\n if (nn_)\n {\n std::vector<Motion*> motions;\n nn_->list(motions);\n for (unsigned int i = 0 ; i < motions.size() ; ++i)\n {\n if (motions[i]->state)\n si_->freeState(motions[i]->state);\n delete motions[i];\n }\n }\n}\n\nvoid ompl::geometric::RRTstar::getPlannerData(base::PlannerData &data) const\n{\n Planner::getPlannerData(data);\n\n std::vector<Motion*> motions;\n if (nn_)\n nn_->list(motions);\n\n if (lastGoalMotion_)\n data.addGoalVertex(base::PlannerDataVertex(lastGoalMotion_->state));\n\n for (unsigned int i = 0 ; i < motions.size() ; ++i)\n {\n if (motions[i]->parent == NULL)\n data.addStartVertex(base::PlannerDataVertex(motions[i]->state));\n else\n data.addEdge(base::PlannerDataVertex(motions[i]->parent->state),\n base::PlannerDataVertex(motions[i]->state));\n }\n\n data.properties[\"iterations INTEGER\"] = boost::lexical_cast<std::string>(iterations_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"BatchGUI.h\"\n#include <sofa\/simulation\/Simulation.h>\n#include <sofa\/simulation\/UpdateContextVisitor.h>\n#ifdef SOFA_SMP\n#include <athapascan-1>\n#endif\n#include <sofa\/helper\/system\/thread\/CTime.h>\n#include <iostream>\n#include <sstream>\n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nconst unsigned int BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS = 1000;\nunsigned int BatchGUI::nbIter = BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS;\n\nBatchGUI::BatchGUI()\n : groot(NULL)\n{\n}\n\nBatchGUI::~BatchGUI()\n{\n}\n\nint BatchGUI::mainLoop()\n{\n if (groot)\n {\n\n sofa::simulation::getSimulation()->animate(groot.get());\n \/\/As no visualization is done by the Batch GUI, these two lines are not necessary.\n sofa::simulation::getSimulation()->updateVisual(groot.get());\n std::cout << \"Computing \"<<nbIter<<\" iterations.\" << std::endl;\n sofa::simulation::Visitor::ctime_t rtfreq = sofa::helper::system::thread::CTime::getRefTicksPerSec();\n sofa::simulation::Visitor::ctime_t tfreq = sofa::helper::system::thread::CTime::getTicksPerSec();\n sofa::simulation::Visitor::ctime_t rt = sofa::helper::system::thread::CTime::getRefTime();\n sofa::simulation::Visitor::ctime_t t = sofa::helper::system::thread::CTime::getFastTime();\n for (unsigned int i=0; i<nbIter; i++)\n {\n sofa::simulation::getSimulation()->animate(groot.get());\n \/\/As no visualization is done by the Batch GUI, these two lines are not necessary.\n sofa::simulation::getSimulation()->updateVisual(groot.get());\n }\n t = sofa::helper::system::thread::CTime::getFastTime()-t;\n rt = sofa::helper::system::thread::CTime::getRefTime()-rt;\n\n std::cout << nbIter << \" iterations done in \"<< ((double)t)\/((double)tfreq) << \" s ( \" << (((double)tfreq)*nbIter)\/((double)t) << \" FPS).\" << std::endl;\n std::cout << nbIter << \" iterations done in \"<< ((double)rt)\/((double)rtfreq) << \" s ( \" << (((double)rtfreq)*nbIter)\/((double)rt) << \" FPS).\" << std::endl;\n }\n return 0;\n}\n\nvoid BatchGUI::redraw()\n{\n}\n\nint BatchGUI::closeGUI()\n{\n delete this;\n return 0;\n}\n\nvoid BatchGUI::setScene(sofa::simulation::Node::SPtr groot, const char* filename, bool )\n{\n this->groot = groot;\n this->filename = (filename?filename:\"\");\n\n resetScene();\n}\n\n\nvoid BatchGUI::resetScene()\n{\n sofa::simulation::Node* root = currentSimulation();\n\n if ( root )\n {\n root->setTime(0.);\n simulation::getSimulation()->reset ( root );\n\n sofa::simulation::UpdateSimulationContextVisitor(sofa::core::ExecParams::defaultInstance()).execute(root);\n }\n}\n\nvoid BatchGUI::startDumpVisitor()\n{\n#ifdef SOFA_DUMP_VISITOR_INFO\n sofa::simulation::Node* root = currentSimulation();\n if (root)\n {\n m_dumpVisitorStream.str(\"\");\n sofa::simulation::Visitor::startDumpVisitor(&m_dumpVisitorStream, root->getTime());\n }\n#endif\n}\n\nvoid BatchGUI::stopDumpVisitor()\n{\n#ifdef SOFA_DUMP_VISITOR_INFO\n sofa::simulation::Visitor::stopDumpVisitor();\n m_dumpVisitorStream.flush();\n m_dumpVisitorStream.str(\"\");\n#endif\n}\n\nsofa::simulation::Node* BatchGUI::currentSimulation()\n{\n return groot.get();\n}\n\n\nint BatchGUI::InitGUI(const char* \/*name*\/, const std::vector<std::string>& options)\n{\n setNumIterations(DEFAULT_NUMBER_OF_ITERATIONS);\n\n \/\/parse options\n for (unsigned int i=0 ; i<options.size() ; i++)\n {\n size_t cursor = 0;\n std::string opt = options[i];\n \/\/Set number of iterations\n \/\/(option = \"nbIterations=N where N is the number of iterations)\n if ( (cursor = opt.find(\"nbIterations=\")) != std::string::npos )\n {\n unsigned int nbIterations;\n std::istringstream iss;\n iss.str(opt.substr(cursor+std::string(\"nbIterations=\").length(), std::string::npos));\n iss >> nbIterations;\n setNumIterations(nbIterations);\n }\n }\n return 0;\n}\n\nBaseGUI* BatchGUI::CreateGUI(const char* name, const std::vector<std::string>& \/*options*\/, sofa::simulation::Node::SPtr groot, const char* filename)\n{\n BatchGUI::mGuiName = name;\n BatchGUI* gui = new BatchGUI();\n gui->setScene(groot, filename);\n return gui;\n}\n\n} \/\/ namespace gui\n\n} \/\/ namespace sofa\n<commit_msg>[Advanced Timer] in batch mode<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"BatchGUI.h\"\n#include <sofa\/simulation\/Simulation.h>\n#include <sofa\/simulation\/UpdateContextVisitor.h>\n#ifdef SOFA_SMP\n#include <athapascan-1>\n#endif\n#include <sofa\/helper\/system\/thread\/CTime.h>\n#include <iostream>\n#include <sstream>\n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nconst unsigned int BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS = 1000;\nunsigned int BatchGUI::nbIter = BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS;\n\nBatchGUI::BatchGUI()\n : groot(NULL)\n{\n}\n\nBatchGUI::~BatchGUI()\n{\n}\n\nint BatchGUI::mainLoop()\n{\n if (groot)\n {\n\n sofa::helper::AdvancedTimer::begin(\"Animate\");\n sofa::simulation::getSimulation()->animate(groot.get());\n sofa::helper::AdvancedTimer::end(\"Animate\");\n \/\/As no visualization is done by the Batch GUI, these two lines are not necessary.\n sofa::simulation::getSimulation()->updateVisual(groot.get());\n std::cout << \"Computing \"<<nbIter<<\" iterations.\" << std::endl;\n sofa::simulation::Visitor::ctime_t rtfreq = sofa::helper::system::thread::CTime::getRefTicksPerSec();\n sofa::simulation::Visitor::ctime_t tfreq = sofa::helper::system::thread::CTime::getTicksPerSec();\n sofa::simulation::Visitor::ctime_t rt = sofa::helper::system::thread::CTime::getRefTime();\n sofa::simulation::Visitor::ctime_t t = sofa::helper::system::thread::CTime::getFastTime();\n for (unsigned int i=0; i<nbIter; i++)\n {\n sofa::helper::AdvancedTimer::begin(\"Animate\");\n sofa::simulation::getSimulation()->animate(groot.get());\n sofa::helper::AdvancedTimer::end(\"Animate\");\n \/\/As no visualization is done by the Batch GUI, these two lines are not necessary.\n sofa::simulation::getSimulation()->updateVisual(groot.get());\n }\n t = sofa::helper::system::thread::CTime::getFastTime()-t;\n rt = sofa::helper::system::thread::CTime::getRefTime()-rt;\n\n std::cout << nbIter << \" iterations done in \"<< ((double)t)\/((double)tfreq) << \" s ( \" << (((double)tfreq)*nbIter)\/((double)t) << \" FPS).\" << std::endl;\n std::cout << nbIter << \" iterations done in \"<< ((double)rt)\/((double)rtfreq) << \" s ( \" << (((double)rtfreq)*nbIter)\/((double)rt) << \" FPS).\" << std::endl;\n }\n return 0;\n}\n\nvoid BatchGUI::redraw()\n{\n}\n\nint BatchGUI::closeGUI()\n{\n delete this;\n return 0;\n}\n\nvoid BatchGUI::setScene(sofa::simulation::Node::SPtr groot, const char* filename, bool )\n{\n this->groot = groot;\n this->filename = (filename?filename:\"\");\n\n resetScene();\n}\n\n\nvoid BatchGUI::resetScene()\n{\n sofa::simulation::Node* root = currentSimulation();\n\n if ( root )\n {\n root->setTime(0.);\n simulation::getSimulation()->reset ( root );\n\n sofa::simulation::UpdateSimulationContextVisitor(sofa::core::ExecParams::defaultInstance()).execute(root);\n }\n}\n\nvoid BatchGUI::startDumpVisitor()\n{\n#ifdef SOFA_DUMP_VISITOR_INFO\n sofa::simulation::Node* root = currentSimulation();\n if (root)\n {\n m_dumpVisitorStream.str(\"\");\n sofa::simulation::Visitor::startDumpVisitor(&m_dumpVisitorStream, root->getTime());\n }\n#endif\n}\n\nvoid BatchGUI::stopDumpVisitor()\n{\n#ifdef SOFA_DUMP_VISITOR_INFO\n sofa::simulation::Visitor::stopDumpVisitor();\n m_dumpVisitorStream.flush();\n m_dumpVisitorStream.str(\"\");\n#endif\n}\n\nsofa::simulation::Node* BatchGUI::currentSimulation()\n{\n return groot.get();\n}\n\n\nint BatchGUI::InitGUI(const char* \/*name*\/, const std::vector<std::string>& options)\n{\n setNumIterations(DEFAULT_NUMBER_OF_ITERATIONS);\n\n \/\/parse options\n for (unsigned int i=0 ; i<options.size() ; i++)\n {\n size_t cursor = 0;\n std::string opt = options[i];\n \/\/Set number of iterations\n \/\/(option = \"nbIterations=N where N is the number of iterations)\n if ( (cursor = opt.find(\"nbIterations=\")) != std::string::npos )\n {\n unsigned int nbIterations;\n std::istringstream iss;\n iss.str(opt.substr(cursor+std::string(\"nbIterations=\").length(), std::string::npos));\n iss >> nbIterations;\n setNumIterations(nbIterations);\n }\n }\n return 0;\n}\n\nBaseGUI* BatchGUI::CreateGUI(const char* name, const std::vector<std::string>& \/*options*\/, sofa::simulation::Node::SPtr groot, const char* filename)\n{\n BatchGUI::mGuiName = name;\n BatchGUI* gui = new BatchGUI();\n gui->setScene(groot, filename);\n return gui;\n}\n\n} \/\/ namespace gui\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"<commit_before>\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright 2016 Marco Biasini\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ -----------------------------------------------------------------------------\n\n#ifndef TYPUS_RESULT_HH\n#define TYPUS_RESULT_HH\n\n#include <memory>\n#include <cassert>\n#include <type_traits>\n\n\nnamespace typus {\n\ntemplate <typename E>\nstruct error_traits {\n \/**\n * Whether the result is OK.\n *\/\n static bool is_ok(const E& value);\n\n \/**\n * Error value to be used to indicate that result is OK, e.g. contains a \n * constructed value of type T.\n *\/\n constexpr static E ok_value();\n\n \/**\n * May be provided for an error type as the default error status, so \n * \\code result<T,E>::fail() \\endcode can be called without arguments. For \n * types where there is no clear default failed value, this can be omitted.\n *\/\n constexpr static E default_fail_value();\n};\n\n\/**\n * Default error traits for boolean errors.\n *\/\ntemplate <>\nstruct error_traits<bool> {\n static bool is_ok(const bool& error) {\n return !error;\n }\n constexpr static bool ok_value() { return false; }\n constexpr static bool default_fail_value() { return true; }\n};\n\n\nnamespace detail {\n\n\/\/ Tag type for failed result construction. \nstruct failed_tag_t {};\n\n\/\/ holder class for the actual result. This class is required, because we want \n\/\/ to have separate implementations for trivially destructible value types and \n\/\/ types that require the destructor to be invoked.\ntemplate <typename T, typename E, \n bool =std::is_trivially_destructible<T>::value>\nclass result_storage {\npublic:\n using value_type = T;\n using error_type = E;\nprotected:\n result_storage(): value_(), error_(error_traits<E>::ok_value()) {\n }\n \n result_storage(const result_storage &rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(rhs.value_);\n }\n }\n\n result_storage(const result_storage &&rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) T(std::move(rhs.value_));\n }\n }\n\n result_storage(const value_type &rhs): \n value_(rhs), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(const value_type &&rhs): \n value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(failed_tag_t, E error): nul_state_('\\0'), error_(error) {\n }\n\n ~result_storage() {\n if (error_traits<E>::is_ok(error_)) {\n value_.~T();\n }\n }\n union {\n char nul_state_;\n T value_;\n };\n E error_;\n};\n\ntemplate <typename T, typename E>\nclass result_storage<T, E, true> {\npublic:\n using value_type = T;\n using error_type = E;\nprotected:\n result_storage(): value_(), error_(error_traits<E>::ok_value()) {\n }\n \n result_storage(const result_storage &rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(rhs.value_);\n }\n }\n\n result_storage(const result_storage &&rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(std::move(rhs.value_));\n }\n }\n\n result_storage(const value_type &rhs): \n value_(rhs), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(const value_type &&rhs): \n value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(failed_tag_t, E error): nul_state_('\\0'), error_(error) {\n }\n\n \/\/ nothing to be done, value_type is trivially destructible\n ~result_storage() { }\n union {\n char nul_state_;\n T value_;\n };\n E error_;\n};\n\n} \/\/ namespace detail\n\n\/**\n * \\brief class holding a value of type T or an error of type E.\n *\n * Typical uses of this class include as a return type for a function\/method \n * that can fail. The result acts as a replacement for exception-based error \n * handling.\n *\/\ntemplate <typename T, typename E=bool>\nclass result : public detail::result_storage<T, E> {\npublic:\n typedef T value_type;\n typedef E error_type;\n\n \/**\n * \\brief construct a failed result using the provided error value\n *\/\n static result<T, E> fail(E error) {\n return result<T,E>(detail::failed_tag_t{}, error);\n }\n \/**\n * \\brief construct a failed result using the default fail value.\n *\n * This is probably only useful when using a boolean error type as \n * for all others there is not meaningful default error value.\n *\/\n static result<T, E> fail() {\n return result<T,E>(detail::failed_tag_t{}, \n error_traits<E>::default_fail_value());\n }\n\n \/**\n * \\brief whether the result contains a valid value.\n *\/\n bool ok() const {\n return error_traits<E>::is_ok(this->error_);\n }\n\n \/**\n * \\brief whether the result contains a valid value.\n *\n * Identical to calling \\ref ok.\n *\/\n operator bool() const {\n return this->ok();\n }\n\n\n \/**\n * \\brief access the value in-place.\n *\n * Aborts if the result does not hold a valid value.\n *\/\n const T& value() const { \n assert(this->ok());\n return this->value_; \n }\n \/**\n * \\brief access the value in-place.\n *\n * Aborts if the result does not hold a valid value.\n *\/\n T& value() { \n assert(this->ok());\n return this->value_; \n }\n\n \/**\n * \\brief extract the value out of the result.\n *\/\n T && extract() {\n assert(this->ok());\n return std::move(this->value_);\n }\npublic:\n \/**\n * \\brief create a result containing a default-constructed value.\n *\/\n result() = default;\n \/**\n * \\brief copy-construct a result.\n *\/\n result(const result& rhs) = default;\n \/**\n * \\brief construct a new result holding a value by copy-constructor.\n *\/\n result(const value_type &rhs): detail::result_storage<T, E>(rhs) {}\n \/**\n * \\brief construct a new result holding a value through move construction.\n *\/\n result(value_type &&rhs): detail::result_storage<T, E>(std::move(rhs)) {}\n\n template <typename T2, typename E2>\n friend class result;\n\n \/**\n * Allow for implicit conversion from one failed result type to another. \n * Only supported if error types are the same. aborts if the value is\n * ok. \n *\/\n template<typename U>\n result(const result<U, E> &other): \n detail::result_storage<T,E>(detail::failed_tag_t{}, other.error_) {\n assert(!other.ok());\n }\n\n \/**\n * \\brief The error state of the result.\n *\/\n E error() const { return this->error_; }\nprivate:\n result(detail::failed_tag_t, const error_type &e): \n detail::result_storage<T, E>(detail::failed_tag_t{}, e) {\n }\n};\n\n\/**\n * macro for Rust-style function return value checking. Note that is is\n * not standard C++ and is only supported in clang and gcc, since it relies\n * on statement expressions. So if you want to be portable, don't use it.\n *\n * Typical usage:\n * \\code\n * result<std::string> may_fail() { ... }\n *\n * result<std::string> foo() {\n * std::string value = TRY(may_fail());\n * return do_stuff(value);\n * \n * }\n * \\endcode\n *\/\n#define TRY(expr) ({ \\\n auto v = expr; \\\n if (!v.ok()) { \\\n return v; \\\n }; \\\n v.extract(); \\\n })\n\n\n} \/\/ namespace typus\n\n#endif \/\/ TYPUS_RESULT_HH\n\n<commit_msg>fix typo<commit_after>\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright 2016 Marco Biasini\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ -----------------------------------------------------------------------------\n\n#ifndef TYPUS_RESULT_HH\n#define TYPUS_RESULT_HH\n\n#include <memory>\n#include <cassert>\n#include <type_traits>\n\n\nnamespace typus {\n\ntemplate <typename E>\nstruct error_traits {\n \/**\n * Whether the result is OK.\n *\/\n static bool is_ok(const E& value);\n\n \/**\n * Error value to be used to indicate that result is OK, e.g. contains a \n * constructed value of type T.\n *\/\n constexpr static E ok_value();\n\n \/**\n * May be provided for an error type as the default error status, so \n * \\code result<T,E>::fail() \\endcode can be called without arguments. For \n * types where there is no clear default failed value, this can be omitted.\n *\/\n constexpr static E default_fail_value();\n};\n\n\/**\n * Default error traits for boolean errors.\n *\/\ntemplate <>\nstruct error_traits<bool> {\n static bool is_ok(const bool& error) {\n return !error;\n }\n constexpr static bool ok_value() { return false; }\n constexpr static bool default_fail_value() { return true; }\n};\n\n\nnamespace detail {\n\n\/\/ Tag type for failed result construction. \nstruct failed_tag_t {};\n\n\/\/ holder class for the actual result. This class is required, because we want \n\/\/ to have separate implementations for trivially destructible value types and \n\/\/ types that require the destructor to be invoked.\ntemplate <typename T, typename E, \n bool =std::is_trivially_destructible<T>::value>\nclass result_storage {\npublic:\n using value_type = T;\n using error_type = E;\nprotected:\n result_storage(): value_(), error_(error_traits<E>::ok_value()) {\n }\n \n result_storage(const result_storage &rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(rhs.value_);\n }\n }\n\n result_storage(const result_storage &&rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) T(std::move(rhs.value_));\n }\n }\n\n result_storage(const value_type &rhs): \n value_(rhs), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(const value_type &&rhs): \n value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(failed_tag_t, E error): nul_state_('\\0'), error_(error) {\n }\n\n ~result_storage() {\n if (error_traits<E>::is_ok(error_)) {\n value_.~T();\n }\n }\n union {\n char nul_state_;\n T value_;\n };\n E error_;\n};\n\ntemplate <typename T, typename E>\nclass result_storage<T, E, true> {\npublic:\n using value_type = T;\n using error_type = E;\nprotected:\n result_storage(): value_(), error_(error_traits<E>::ok_value()) {\n }\n \n result_storage(const result_storage &rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(rhs.value_);\n }\n }\n\n result_storage(const result_storage &&rhs): error_(rhs.error_) {\n if (error_traits<E>::is_ok(error_)) {\n \/\/ in-place new\n ::new (std::addressof(value_)) value_type(std::move(rhs.value_));\n }\n }\n\n result_storage(const value_type &rhs): \n value_(rhs), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(const value_type &&rhs): \n value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {\n }\n\n result_storage(failed_tag_t, E error): nul_state_('\\0'), error_(error) {\n }\n\n \/\/ nothing to be done, value_type is trivially destructible\n ~result_storage() { }\n union {\n char nul_state_;\n T value_;\n };\n E error_;\n};\n\n} \/\/ namespace detail\n\n\/**\n * \\brief class holding a value of type T or an error of type E.\n *\n * Typical uses of this class include as a return type for a function\/method \n * that can fail. The result acts as a replacement for exception-based error \n * handling.\n *\/\ntemplate <typename T, typename E=bool>\nclass result : public detail::result_storage<T, E> {\npublic:\n typedef T value_type;\n typedef E error_type;\n\n \/**\n * \\brief construct a failed result using the provided error value\n *\/\n static result<T, E> fail(E error) {\n return result<T,E>(detail::failed_tag_t{}, error);\n }\n \/**\n * \\brief construct a failed result using the default fail value.\n *\n * This is probably only useful when using a boolean error type as \n * for all others there is no meaningful default error value.\n *\/\n static result<T, E> fail() {\n return result<T,E>(detail::failed_tag_t{}, \n error_traits<E>::default_fail_value());\n }\n\n \/**\n * \\brief whether the result contains a valid value.\n *\/\n bool ok() const {\n return error_traits<E>::is_ok(this->error_);\n }\n\n \/**\n * \\brief whether the result contains a valid value.\n *\n * Identical to calling \\ref ok.\n *\/\n operator bool() const {\n return this->ok();\n }\n\n\n \/**\n * \\brief access the value in-place.\n *\n * Aborts if the result does not hold a valid value.\n *\/\n const T& value() const { \n assert(this->ok());\n return this->value_; \n }\n \/**\n * \\brief access the value in-place.\n *\n * Aborts if the result does not hold a valid value.\n *\/\n T& value() { \n assert(this->ok());\n return this->value_; \n }\n\n \/**\n * \\brief extract the value out of the result.\n *\/\n T && extract() {\n assert(this->ok());\n return std::move(this->value_);\n }\npublic:\n \/**\n * \\brief create a result containing a default-constructed value.\n *\/\n result() = default;\n \/**\n * \\brief copy-construct a result.\n *\/\n result(const result& rhs) = default;\n \/**\n * \\brief construct a new result holding a value by copy-constructor.\n *\/\n result(const value_type &rhs): detail::result_storage<T, E>(rhs) {}\n \/**\n * \\brief construct a new result holding a value through move construction.\n *\/\n result(value_type &&rhs): detail::result_storage<T, E>(std::move(rhs)) {}\n\n template <typename T2, typename E2>\n friend class result;\n\n \/**\n * Allow for implicit conversion from one failed result type to another. \n * Only supported if error types are the same. aborts if the value is\n * ok. \n *\/\n template<typename U>\n result(const result<U, E> &other): \n detail::result_storage<T,E>(detail::failed_tag_t{}, other.error_) {\n assert(!other.ok());\n }\n\n \/**\n * \\brief The error state of the result.\n *\/\n E error() const { return this->error_; }\nprivate:\n result(detail::failed_tag_t, const error_type &e): \n detail::result_storage<T, E>(detail::failed_tag_t{}, e) {\n }\n};\n\n\/**\n * macro for Rust-style function return value checking. Note that is is\n * not standard C++ and is only supported in clang and gcc, since it relies\n * on statement expressions. So if you want to be portable, don't use it.\n *\n * Typical usage:\n * \\code\n * result<std::string> may_fail() { ... }\n *\n * result<std::string> foo() {\n * std::string value = TRY(may_fail());\n * return do_stuff(value);\n * \n * }\n * \\endcode\n *\/\n#define TRY(expr) ({ \\\n auto v = expr; \\\n if (!v.ok()) { \\\n return v; \\\n }; \\\n v.extract(); \\\n })\n\n\n} \/\/ namespace typus\n\n#endif \/\/ TYPUS_RESULT_HH\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef NEWARRAYS_H_INCLUDED\r\n#define NEWARRAYS_H_INCLUDED\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\/\/\/ #define ARRAYS_DEBUG\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n#include <wiz\/global.h>\r\n#include <wiz\/wizardError.h>\r\n\r\nnamespace wiz{\r\ntemplate <class T>\r\nclass Array{\r\nprivate:\r\n T* p; \/\/ array\r\n int N; \/\/ array \r\nprivate:\r\n static T sBegin; \/\/\/ static -> s, \/\/\/ to not static?\r\n static T sEnd;\r\n\r\nprivate:\r\n void resetP( const T* p )\r\n {\r\n if( nullptr != this->p && nullptr != p )\r\n {\r\n for( int i=0;i< N;i++ ){\r\n this->p[i] = p[i];\r\n }\r\n }\r\n }\r\n\/\/\/for c++11\r\npublic:\r\n class Iter \/\/\r\n {\r\n private:\r\n T* _pt;\/\/\r\n \/\/\/ following constant values..\r\n T* p;\r\n int N;\r\n T* pBegin;\r\n T* pEnd;\r\n public:\r\n explicit Iter( T* _pt, T* p, int N, T* pBegin, T* pEnd ) : _pt(_pt),\r\n p(p), N(N), pBegin(pBegin), pEnd(pEnd)\r\n {\r\n if( nullptr == _pt ) { throw wiz::Error( \"nullptr == _pt in Iter\" ); }\r\n }\r\n \/\/\r\n void left() {\r\n \/\/ p == nullptr -> err.\r\n if( p == _pt ) { _pt = pBegin; }\r\n else if( _pt == pBegin ) { throw wiz::Error( \" _pt == pBegin in left \" ); }\r\n else if( _pt == pEnd ) { _pt = p+N-1; }\r\n else {\r\n _pt--;\r\n }\r\n }\r\n void right() {\r\n \/\/ p == nullptr -> err.\r\n if( p+N-1 == _pt ) { _pt = pEnd; }\r\n else if( _pt == pEnd ) { throw wiz::Error( \" _pt == pEnd in right \" ); }\r\n else if( _pt == pBegin ) { _pt = p; }\r\n else {\r\n _pt++;\r\n }\r\n }\r\n T data()const { return *_pt; }\r\n bool isnullptr()const { return nullptr == _pt; }\r\n bool operator!=( const Iter& x ) const\r\n {\r\n return x._pt != this->_pt;\r\n }\r\n void operator++() { right(); }\r\n void operator--() { left(); }\r\n \/\/\/ TO DO\r\n \/\/\/ T* operator->()\r\n \/\/\/ const T* operator->()const\r\n T* operator->() { return _pt; }\r\n const T* operator->()const { return _pt; }\r\n T& operator*() { return *_pt; }\r\n const T& operator*()const { return *_pt; }\r\n };\r\n class ConstIter \/\/\r\n {\r\n private:\r\n T* _pt;\/\/\r\n \/\/\/ following constant values..\r\n T* p;\r\n int N;\r\n T* pBegin;\r\n T* pEnd;\r\n public:\r\n explicit ConstIter( T* _pt, T* p, int N, T* pBegin, T* pEnd ) : _pt(_pt),\r\n p(p), N(N), pBegin(pBegin), pEnd(pEnd)\r\n {\r\n if( nullptr == _pt ) { throw wiz::Error( \"nullptr == _pt in ConstIter\" ); }\r\n }\r\n \/\/\r\n void left() {\r\n \/\/ p == nullptr -> err.\r\n if( p == _pt ) { _pt = pBegin; }\r\n else if( _pt == pBegin ) { throw wiz::Error( \" _pt == pBegin in left \" ); }\r\n else if( _pt == pEnd ) { _pt = p+N-1; }\r\n else {\r\n _pt--;\r\n }\r\n }\r\n void right() {\r\n \/\/ p == nullptr -> err.\r\n if( p+N-1 == _pt ) { _pt = pEnd; }\r\n else if( _pt == pEnd ) { throw wiz::Error( \" _pt == pEnd in right \" ); }\r\n else if( _pt == pBegin ) { _pt = p; }\r\n else {\r\n _pt++;\r\n }\r\n }\r\n T data()const { return *_pt; }\r\n bool isnullptr()const { return nullptr == _pt; }\r\n bool operator!=( const ConstIter& x ) const\r\n {\r\n return x._pt != this->_pt;\r\n }\r\n void operator++() { right(); }\r\n void operator--() { left(); }\r\n\r\n const T* operator->()const { return _pt; }\r\n const T& operator*()const { return *_pt; }\r\n };\r\n Iter begin() { if( empty() ) { return end(); }\r\n return Iter( p, p, N, &sBegin, &sEnd );\r\n }\r\n Iter end() { return Iter( &sEnd, p, N, &sBegin, &sEnd ); }\r\n Iter rbegin() { if( empty() ){ return rend(); }\r\n return Iter( p+N-1, p, N, &sBegin, &sEnd );\r\n }\r\n\r\n Iter rend() { return Iter( &sBegin, p, N, &sBegin, &sEnd ); }\r\n \/\/\/ Check....\r\n ConstIter crend() const { return ConstIter( &sBegin, p, N, &sBegin, &sEnd ); }\r\n ConstIter cbegin() const { if( empty() ) { return cend(); }\r\n return ConstIter( p, p, N, &sBegin, &sEnd );\r\n }\r\n ConstIter cend() const { return ConstIter( &sEnd, p, N, &sBegin, &sEnd ); }\r\n ConstIter crbegin() const { if( empty() ){ return crend(); }\r\n return ConstIter( p+N-1, p, N, &sBegin, &sEnd );\r\n }\r\n\r\n\r\n explicit Array( initializer_list<T> args )\r\n {\r\n N = args.size();\r\n\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkUnderError( 1, N, 0 );\r\n #endif\r\n\r\n if( 0 == N ) { p = nullptr; return; }\r\n p = new T[N];\r\n\r\n int count = 0;\r\n for( auto iter = args.begin(); iter != args.end(); ++iter )\r\n {\r\n p[count] = *iter;\r\n count++;\r\n }\r\n\r\n }\r\n\r\n Array<T>& operator=( Array<T>&& arr )\r\n {\r\n if( p == arr.p ) { return *this; }\r\n\r\n if( p ) { delete[] p; }\r\n p = arr.p; arr.p = nullptr;\r\n N = arr.N; arr.N = 0;\r\n\r\n return *this;\r\n }\r\n Array( Array<T>&& arr )\r\n {\r\n p = arr.p; arr.p = nullptr;\r\n N = arr.N; arr.N = 0;\r\n }\r\n\r\n\/\/\r\npublic:\r\n\texplicit Array(const int _N, const T reset_val = T()) : N(_N)\r\n\t{\r\n#ifdef ARRAYS_DEBUG\r\n\t\twiz::checkUnderError(2, N, 1);\r\n#endif\r\n\t\tp = new T[_N];\r\n\r\n\t\t\/\/reset( reset_val );\r\n\t\tif (!std::is_class<T>::value)\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\t\tp[i] = reset_val;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n Array( const Array<T>& _arr )\r\n : p(nullptr), N(0)\r\n {\r\n *this = _arr;\r\n }\r\n explicit Array() : p(nullptr), N(0)\r\n { }\r\n\r\n virtual ~Array()\r\n {\r\n if( p )\r\n delete[] p;\r\n }\r\n\r\n void reset( const T& resetValue )\r\n {\r\n for( int i=0;i< N;i++ )\/\/\r\n p[i] = resetValue;\r\n }\r\n bool operator==( const Array<T>& arr ) const \/\/\/ ..\r\n {\r\n return this->p == arr.p;\r\n }\r\n bool operator!=( const Array<T>& arr ) const\r\n {\r\n return this->p != arr.p;\r\n }\r\n \/\/\/ cf) isSameValues?\r\n template<class IS_SAME_VALUE=EQ<T>> \/\/\/ need more thinking..\r\n bool isSameValue( const Array<T>& arr ) const\r\n {\r\n if( arr.size() != size() ) { return false; }\r\n for( int i=0; i < arr.size(); i++ )\r\n {\r\n if( !( IS_SAME_VALUE()( arr[i], p[i] ) ) ) { return false; }\r\n }\r\n return true;\r\n }\r\n \/\/ ũ\r\n int size()const{ return N; }\r\n int length()const{ return N; }\r\n \/\/\r\n T& operator[]( const int index )\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( index, N );\r\n #endif\r\n\t\treturn p[index];\r\n }\r\n const T& operator[]( const int index )const\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( index, N );\r\n #endif\r\n\t\treturn p[index];\r\n }\r\n \/\/\r\n Array<T>& operator=( const Array<T>& _p )\r\n {\r\n if( _p.p == p ) { return *this; }\r\n\r\n if( nullptr != p && size() != _p.size() )\r\n {\r\n delete[] p;\r\n p = nullptr;\r\n }\r\n\r\n\t\tif( nullptr == p && nullptr != _p.p )\r\n {\r\n p = new T[_p.N];\r\n }\r\n\r\n \/\/reset\r\n N = _p.N;\r\n resetP( _p.p );\r\n\r\n return *this;\r\n }\r\n\r\n bool empty()const\r\n {\r\n \treturn nullptr == p;\r\n }\r\n bool isValid()const\r\n {\r\n return !empty();\r\n }\r\n void DoEmpty()\r\n {\r\n if( p ) delete[] p;\r\n p = nullptr;\r\n N = 0;\r\n }\r\npublic:\r\n\tvoid expand()\r\n\t{\r\n\t\tif( nullptr != p )\r\n\t\t{\r\n\t\t \/\/ 2012.5.8\r\n\t\t\tconst int newN = 2 * N;\r\n T* temp = new T[2*N]; \/\/ new Array!\r\n\r\n \/\/ data copy!\r\n\t\t for( int i=0; i < N; i++ )\r\n\t\t\t{\r\n\t\t\t\ttemp[i] = std::move( p[i] ); \/\/ cf) Ѱ p[i] ???\r\n\t\t\t}\r\n\r\n\t\t\tif (!std::is_class<T>::value)\r\n\t\t\t{\r\n\t\t\t\tfor (int i = N; i < newN; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\ttemp[i] = T();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n \/\/\/\r\n delete[] p;\r\n p = temp; N = newN;\r\n\t\t}\r\n\t}\r\n\r\npublic: \/\/\/ Done-swap..\r\n void swap( Array<T>& arr )\r\n {\r\n wiz::Swap( this->p, arr.p );\r\n wiz::Swap( this->N, arr.N );\r\n }\r\n};\/\/ end class array\r\ntemplate <class T>\r\nT Array<T>::sBegin = T();\r\ntemplate <class T>\r\nT Array<T>::sEnd = T();\r\n\/\/ not use debug() and use below!\r\ntemplate <class T>\r\ninline ostream& operator<<( ostream& stream, const Array<T>& arr )\r\n{\r\n if( arr.empty() ) { return stream; }\r\n\r\n for( int index=0; index < arr.length()-1; index++ )\r\n stream << arr[index] << \" \";\r\n stream << arr[arr.length()-1]; \/\/ chk 2012.7.30\r\n\r\n return stream;\r\n}\r\ntemplate <class T>\r\ninline istream& operator>>( istream& stream, Array<T>& arr )\r\n{\r\n for( int i=0; i < arr.size(); ++i )\r\n {\r\n stream >> arr[i];\r\n }\r\n\r\n return stream;\r\n}\r\ntemplate <class T>\r\nclass SecondArray{ \/\/\/ To Do Add bool isSameValue?\r\nprivate:\r\n Array<T>** p;\r\n int row_N; \/\/ array \r\n int column_N;\r\n\r\nprivate:\r\n void Delete() \/\/\/ to public??\r\n {\r\n\t\tif( nullptr != p )\r\n {\r\n\t\t\tfor( int i=0;i< row_N;i++ )\r\n\t\t\t{\r\n\t\t\t\tif( p[i] ){ delete p[i]; p[i] = nullptr; }\r\n\t\t\t}\r\n\t\t\tdelete[] p;\/\/\r\n p = nullptr;\r\n }\r\n row_N = 0; column_N = 0;\r\n }\r\n\r\n void reset( const int row_N, const int column_N )\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n checkUnderError( 4, row_N, 0 );\r\n checkUnderError( 5, column_N, 0 );\r\n #endif\r\n\r\n this->row_N = row_N;\r\n this->column_N = column_N;\r\n }\r\n\r\npublic:\r\n explicit SecondArray()\r\n\t: p( nullptr ), row_N( 0 ), column_N( 0 )\r\n\t{\r\n \/\/\r\n\t}\r\n explicit SecondArray( const int _row_N, const int _column_N, const T _resetValue=T() )\r\n : row_N(_row_N), column_N(_column_N)\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkUnderError( 6, row_N, 1 );\r\n wiz::checkUnderError( 7, column_N, 1 );\r\n #endif\r\n\r\n p = new Array<T>*[row_N];\r\n for( int i=0;i< row_N;i++ )\r\n {\r\n p[i] = new Array<T>( column_N, _resetValue );\r\n }\r\n }\r\n\r\n virtual ~SecondArray()\r\n {\r\n Delete();\r\n }\r\n \/\/ ִ ũ⸦ ޴´.\r\n SecondArray( const SecondArray<T>& dap )\r\n : p( nullptr ), row_N( 0 ), column_N( 0 )\r\n {\r\n *this = dap;\r\n }\r\n\r\n SecondArray<T>& operator=( const SecondArray<T>& dap ) \/\/\/ need more thinking...\r\n {\r\n if( dap.p == p ) { return *this; }\r\n\r\n \/\/\/ nullptr != p && nullptr == dap.p -> ( nullptr!=p && other size ) is true.\r\n if( nullptr != p && ( row_N != dap.row_N || column_N != dap.column_N ) )\r\n \/\/\/ nullptr != p && nullptr == dap.p\r\n \/\/\/ nullptr != p && nullptr != dap.p && ( different row_size or different col_size )\r\n {\r\n for( int i=0; i < this->row_N; ++i )\r\n {\r\n delete p[i];\r\n }\r\n delete[] p;\r\n p = nullptr;\r\n }\r\n\r\n \tif( nullptr == p && nullptr != dap.p )\r\n {\r\n p = new Array<T>*[dap.row_N];\r\n for( int i=0;i< dap.row_N;i++ )\r\n {\r\n p[i] = new Array<T>( *(dap.p[i]) );\r\n }\r\n }\r\n else \/\/\/ else if( nullptr != p && nullptr != dap.p && same row_size && same col_size )\r\n \/\/\/ else if( nullptr == p && nullptr == dap.p ) -> dap.row_N == 0.\r\n {\r\n for( int i=0; i < dap.row_N; i++ )\r\n {\r\n (*p[i]) = (*dap.p[i]);\r\n }\r\n }\r\n\r\n reset( dap.row_N, dap.column_N );\r\n \/\/\r\n return *this;\r\n }\r\n\r\n \/\/\/ DONE 2014.3.7 - ̵, ̵Կ ߰.\r\n SecondArray<T>& operator=( SecondArray<T>&& arr )\r\n {\r\n if( p == arr.p ) { return *this; }\r\n if( p ) { Delete(); }\r\n p = arr.p;\r\n row_N = arr.row_N;\r\n column_N = arr.column_N;\r\n\r\n arr.p = nullptr;\r\n arr.row_N = 0;\r\n arr.column_N = 0;\r\n return *this;\r\n }\r\n SecondArray( SecondArray<T>&& arr )\r\n {\r\n p = arr.p; arr.p = nullptr;\r\n row_N = arr.row_N; arr.row_N = 0;\r\n column_N = arr.column_N; arr.column_N = 0;\r\n }\r\n\r\n \/\/\/ chk [i].size() == column_N ??\r\n T getValue( const int i, const int j )const\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( i, row_N );\r\n wiz::checkIndexError( j, column_N );\r\n #endif\r\n return (*p[i])[j]; \/\/\r\n }\r\n\r\n void setValue( const int i, const int j, const T& set )\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( i, row_N );\r\n wiz::checkIndexError( j, column_N );\r\n #endif\r\n (*p[i])[j] = set;\r\n }\r\n\r\n \/\/ get size\r\n int getRowN()const{ return row_N; }\r\n int getColumnN()const{ return column_N; }\r\n\r\n void reset( const T& val )\r\n {\r\n for( int i=0;i< row_N;i++ ){\r\n for( int j=0;j< column_N;j++ ){\r\n (*p[i])[j] = val;\r\n }\r\n }\r\n }\r\n\r\n \/\/\/ chk [i].size() == column_N ??\r\n Array<T>& operator[]( const int index )\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( index, row_N );\r\n wiz::assertEquals( p[index]->size(), column_N );\r\n #endif\r\n return *(p[index]);\r\n }\r\n\r\n const Array<T>& operator[]( const int index )const\r\n {\r\n #ifdef ARRAYS_DEBUG\r\n wiz::checkIndexError( index, row_N );\r\n #endif\r\n return *(p[index]);\r\n }\r\n\r\n bool empty() const\r\n {\r\n return nullptr == p;\r\n }\r\n\tbool isValid()const\r\n {\r\n \treturn nullptr != p;\r\n }\r\n \/\/Array<T> getColumnArray( const int columnNo );\r\n \/\/Array<T> getRowArray( const int rowNo );\r\npublic:\r\n virtual bool isSquareSecondArray(){ return false; }\r\n \/\/\/ ToDo swap\r\n void swap( SecondArray<T>& sarr )\r\n {\r\n wiz::Swap( this->p, sarr.p );\r\n wiz::Swap( this->row_N, sarr.row_N );\r\n wiz::Swap( this->column_N, sarr.column_N );\r\n }\r\n\r\n \/\/\/ ToDO row_expand, col_expand, row_col_expand. - *2, *2, *4.\r\n void row_expand()\r\n {\r\n if( isSquareSecondArray() ) { return; } \/\/\/ throw err.?\r\n if( nullptr != p ) {\r\n const int new_row_size = 2 * row_N;\r\n Array<T>** temp = new Array<T>*[new_row_size];\r\n\r\n for( int i=0; i < row_N; i++ ) {\r\n temp[i] = p[i];\r\n }\r\n for( int i=row_N; i < new_row_size; i++ ) {\r\n temp[i] = new Array<T>( column_N, T() );\r\n }\r\n delete[] p;\r\n p = temp;\r\n row_N = new_row_size;\r\n }\r\n }\r\n};\/\/ end double array\r\ntemplate <typename T>\r\nclass SquareSecondArray : public SecondArray<T> \/\/\/ row_expand -> err. ???\r\n{\r\npublic:\r\n virtual bool isSquareSecondArray(){ return true; }\r\npublic:\r\n SquareSecondArray() : SecondArray<T>() { }\r\n virtual ~SquareSecondArray() { }\r\n SquareSecondArray( const SquareSecondArray& sda ) : SecondArray<T>( sda ) { }\r\n SquareSecondArray( const int N, const T init=T() ):SecondArray<T>( N, N, init ){\r\n \/\/\r\n }\r\n\r\n int getN()const{ return SecondArray<T>::getColumnN(); }\r\n\r\n void Transpose() \/\/ only n*n!\/\/ cf) return transposed Square Double Array?\r\n { \/\/\r\n const int N = SecondArray<T>::getRowN();\r\n\r\n for( int i=0;i < N; i++ ){\r\n for( int j=i+1;j < N; j++ ){\r\n \/\/ swap [i][j] and [j][i];\r\n wiz::Swap( (*this)[i][j], (*this)[j][i] );\r\n }\r\n }\r\n }\r\n};\r\n\/\/ not use debug() and use below!\r\ntemplate <class T>\r\ninline ostream& operator<<( ostream& stream, const SecondArray<T>& arr )\r\n{\r\n for( int i=0; i < arr.getRowN(); i++ )\r\n {\r\n stream << arr[i];\r\n stream << \"\\n\";\r\n }\r\n\r\n return stream;\r\n}\r\n\r\ntemplate <class T>\r\ninline istream& operator>>( istream& stream, SecondArray<T>& arr )\r\n{\r\n for( int i=0; i < arr.getRowN(); ++i )\r\n {\r\n stream >> arr[i];\r\n }\r\n\r\n return stream;\r\n}\r\n}\r\n#endif \/\/ NEWARRAYS_H_INCLUDED\r\n<commit_msg>Delete NEWARRAYS.H<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Siconos-sample version 3.1.0, Copyright INRIA 2005-2009.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\n *\/\n\n#ifndef BodiesViewer_hpp\n#define BodiesViewer_hpp\n\n\/* Siconos *\/\n#include <SiconosKernel.hpp>\n\n#include <Disk.hpp>\n#include <DiskDiskR.hpp>\n#include <DiskPlanR.hpp>\n#include <DiskMovingPlanR.hpp>\n#include <Circle.hpp>\n#include <CircleCircleR.hpp>\n#include <SphereLDS.hpp>\n#include <SphereLDSPlanR.hpp>\n#include <SphereLDSSphereLDSR.hpp>\n#include <SphereNEDS.hpp>\n#include <SphereNEDSPlanR.hpp>\n#include <SphereNEDSSphereNEDSR.hpp>\n\n#if WITH_BULLET\n#include <BulletDS.hpp>\n#include <BulletR.hpp>\n#define IFBULLET(X) X\n#else\n#define IFBULLET(X)\n#endif\n\n#include \"SiconosBodies.hpp\"\n\n\/* QGLViewer *\/\n#include <qglviewer.h>\n#include <qapplication.h>\n\n#include <qevent.h>\n#include <qmessagebox.h>\n\n#ifdef QT_INTERFACE\n#include \"ui_viewerInterface.Qt4.h\"\nclass ViewerInterface : public QDialog, public Ui::Dialog\n{\npublic:\n ViewerInterface()\n {\n setupUi(this);\n }\n};\n#endif\n\n\/* convenient macros *\/\n\n\n#define GETALLDS(M) M->model()->nonSmoothDynamicalSystem()->topology()->dSG(0)\n#define GETNDS(M) GETALLDS(M)->size()\n\nstruct ForNdof : public Question<unsigned int>\n{\n ANSWER_V(Disk, 3);\n ANSWER_V(Circle, 3);\n ANSWER_V(SphereLDS, 6);\n ANSWER_V(SphereNEDS, 6);\n IFBULLET(ANSWER_V(BulletDS, 6));\n};\n\n\nstruct ForFExt : public Question<SP::SiconosVector>\n{\n\n ANSWER(Disk, fExt());\n ANSWER(Circle, fExt());\n ANSWER(SphereLDS, fExt());\n ANSWER(SphereNEDS, fExt());\n IFBULLET(ANSWER(BulletDS, fExt()));\n};\n\n\nstruct ForPosition : public Question<SP::SiconosVector>\n{\n\n ANSWER(Disk, q());\n ANSWER(Circle, q());\n ANSWER(SphereLDS, q());\n ANSWER(SphereNEDS, q());\n IFBULLET(ANSWER(BulletDS, q()));\n};\n\nstruct ForRadius : public Question<double>\n{\n\n ANSWER(Disk, getRadius());\n ANSWER(Circle, getRadius());\n ANSWER(SphereLDS, getRadius());\n ANSWER(SphereNEDS, getRadius());\n IFBULLET(ANSWER_V(BulletDS, 0.)); \/\/ fix\n};\n\nstruct ForMassValue : public Question<double>\n{\n ANSWER(Disk, mass()->getValue(0, 0));\n ANSWER(Circle, mass()->getValue(0, 0));\n ANSWER(SphereLDS, mass()->getValue(0, 0));\n ANSWER(SphereNEDS, massValue());\n IFBULLET(ANSWER(BulletDS, massValue()));\n};\n\nstruct ForJachq : public Question<SP::SiconosMatrix>\n{\n ANSWER(LagrangianR, jachq());\n ANSWER(NewtonEulerR, jachq());\n ANSWER(DiskDiskR, jachq());\n ANSWER(DiskPlanR, jachq());\n ANSWER(DiskMovingPlanR, jachq());\n ANSWER(SphereLDSPlanR, jachq());\n ANSWER(SphereNEDSPlanR, jachq());\n ANSWER(SphereLDSSphereLDSR, jachq());\n ANSWER(SphereNEDSSphereNEDSR, jachq());\n IFBULLET(ANSWER(BulletR, jachq()));\n};\n\nstruct ForContactForce : public Question<SP::SiconosVector>\n{\n IFBULLET(ANSWER(BulletR, contactForce()));\n};\n\n\n\n\n#define GETX(C) ask<ForPosition>(*C)->getValue(0)\n#define GETY(C) ask<ForPosition>(*C)->getValue(1)\n#define GETZ(C) ask<ForPosition>(*C)->getValue(2)\n#define GETA1(C) ask<ForPosition>(*C)->getValue(3)\n#define GETA2(C) ask<ForPosition>(*C)->getValue(4)\n#define GETA3(C) ask<ForPosition>(*C)->getValue(5)\n#define GETA4(C) ask<ForPosition>(*C)->getValue(6)\n#define GETXFE(C) ask<ForFExt>(*C)->getValue(0)\n#define GETYFE(C) ask<ForFExt>(*C)->getValue(1)\n#define GETZFE(C) ask<ForFExt>(*C)->getValue(2)\n\n#define GETVX(C) ask<ForVelocity>(*C)->getValue(0)\n#define GETVY(C) ask<ForVelocity>(*C)->getValue(1)\n#define GETVZ(C) ask<ForVelocity>(*C)->getValue(2)\n\n#define GETVA1(C) ask<ForVelocity>(*C)->getValue(3)\n#define GETVA2(C) ask<ForVelocity>(*C)->getValue(4)\n#define GETVA3(C) ask<ForVelocity>(*C)->getValue(5)\n\n#define GETRADIUS(C) ask<ForRadius>(*C)\n\n\nenum SHAPE\n{\n DISK,\n CIRCLE,\n SPHERE,\n IFBULLET(BULLET)\n};\n\nstruct ForShape : public Question<SHAPE>\n{\n ANSWER_V(Disk, DISK);\n ANSWER_V(Circle, CIRCLE);\n ANSWER_V(SphereLDS, SPHERE);\n ANSWER_V(SphereNEDS, SPHERE);\n IFBULLET(ANSWER_V(BulletDS, BULLET));\n};\n\n\/* dynamical system \/ figure association *\/\nclass QGLShape\n{\n\npublic:\n\n \/* construction from a LagrangianDS *\/\n QGLShape(SHAPE f, SP::DynamicalSystem D, const qglviewer::Frame* ref)\n {\n assert(D);\n\n figure_ = f;\n DS_ = D;\n frame_.reset(new qglviewer::ManipulatedFrame());\n frame_->setReferenceFrame(ref);\n savedFExt_ = ask<ForFExt>(*DS());\n selected_ = false;\n saved_ = true;\n type_ = Type::value(*DS());\n\n };\n\n ~QGLShape() {};\n\n \/* pointer to DS *\/\n SP::DynamicalSystem DS() const\n {\n return DS_;\n };\n\n \/* selection with mouse *\/\n bool selected()\n {\n return selected_ ;\n };\n void setSelection(bool v)\n {\n selected_ = v ;\n };\n\n \/* identifiant *\/\n int getD()\n {\n return id_ ;\n };\n void setID(int i)\n {\n id_ = i;\n };\n\n\n \/* External force set from mouse and restore *\/\n void saveFExt()\n {\n savedFExt_ = ask<ForFExt>(*DS());\n };\n void restoreFExt()\n {\n switch (Type::value(*DS()))\n {\n case Type::NewtonEulerDS :\n {\n std11::static_pointer_cast<NewtonEulerDS>(DS())\n ->setFExtPtr(std11::static_pointer_cast<SiconosVector>(savedFExt_));\n break;\n }\n case Type::LagrangianDS :\n {\n std11::static_pointer_cast<LagrangianDS>(DS())\n ->setFExtPtr(std11::static_pointer_cast<SiconosVector>(savedFExt_));\n break;\n };\n default:\n {};\n }\n };\n\n \/* DS frame *\/\n qglviewer::ManipulatedFrame * frame()\n {\n return frame_.get();\n };\n\n SHAPE shape() const\n {\n return figure_;\n }\n\n Type::Siconos type() const\n {\n return type_;\n }\n\nprotected:\n int id_;\n bool selected_;\n bool saved_;\n SP::SiconosVector savedFExt_;\n boost::shared_ptr<qglviewer::ManipulatedFrame> frame_;\n\n SHAPE figure_;\n SP::DynamicalSystem DS_;\n int positionSize_;\n\n Type::Siconos type_;\n\n};\n\nTYPEDEF_SPTR(QGLShape);\n\n\/* QGLViewer main object *\/\nclass BodiesViewer : public QGLViewer\n{\n\npublic:\n\n#ifdef QT_INTERFACE\n Viewer(QWidget *parent);\n#endif\n\npublic:\n virtual void draw() = 0;\n void drawWithNames();\n void initUCircle();\n void drawUCircle();\n void drawUDisk();\n void drawUCircleTicks(float a);\n void drawUDiskTicks(float a) ;\n void drawUTriangle(float depth = 0.) ;\n void drawVec(float x1, float y1, float x2, float y2) ;\n void drawRec(float x1, float y1, float x2, float y2, float w, float z = 0.);\n void drawArrow(float x1, float y1, float x2, float y2, float w);\n void drawPar(float x1, float y1, float z1, float x2, float y2, float z2, float w);\n void drawArrow(float x1, float y1, float z1, float x2, float y2, float z2, float w);\n void drawCircleTicks(float x, float y, float a, float r);\n void drawDiskTicks(float x, float y, float a, float r, float *c);\n void drawSimpleCircle(float x, float y, float r);\n void drawCircle(float x, float y, float a, float r, float *c);\n void drawDisk(float x, float y, float a, float r, float *c);\n void rotate(const float R[12]);\n void drawSphere(float x, float y, float z, float theta, float phi, float psi, float r, float *c);\n void drawSphere(float x, float y, float z, float a, float b, float c, float d, float r, float *color);\n void drawPolyg(unsigned int n, double* coor, float *c);\n\n virtual void drawQGLShape(const QGLShape&);\n virtual void drawSelectedQGLShape(const QGLShape&);\n void insertQGLShape(SHAPE, SP::DynamicalSystem);\n\n\nprotected :\n\n void postSelection(const QPoint& point);\n virtual void init();\n virtual void animate();\n virtual void mousePressEvent(QMouseEvent *);\n virtual void mouseMoveEvent(QMouseEvent *);\n virtual void mouseReleaseEvent(QMouseEvent *);\n virtual void keyPressEvent(QKeyEvent *);\n\n virtual QString helpString() const;\n boost::shared_ptr<qglviewer::WorldConstraint> constraint_;\n\n SP::SiconosBodies Siconos_;\n\n qglviewer::Frame* referenceFrame_;\n\n std::vector<SP::QGLShape> shapes_;\n\n void print(float x, float y, const char *s, int size);\n\n int NDS_;\n\n qglviewer::Vec selectedPoint_;\n\n int lastSelected_;\n\n bool myMouseBehavior_;\n\n bool stepSimulation_;\n bool stepNow_;\n\n long timeSiconos_;\n\n long timeGlob_;\n\n float _transparency;\n\n};\n\n\n\n#endif\n<commit_msg>using SiconosVisitor::visit<commit_after>\/* Siconos-sample version 3.1.0, Copyright INRIA 2005-2009.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY vincent.acary@inrialpes.fr\n *\n *\/\n\n#ifndef BodiesViewer_hpp\n#define BodiesViewer_hpp\n\n\/* Siconos *\/\n#include <SiconosKernel.hpp>\n\n#include <Disk.hpp>\n#include <DiskDiskR.hpp>\n#include <DiskPlanR.hpp>\n#include <DiskMovingPlanR.hpp>\n#include <Circle.hpp>\n#include <CircleCircleR.hpp>\n#include <SphereLDS.hpp>\n#include <SphereLDSPlanR.hpp>\n#include <SphereLDSSphereLDSR.hpp>\n#include <SphereNEDS.hpp>\n#include <SphereNEDSPlanR.hpp>\n#include <SphereNEDSSphereNEDSR.hpp>\n\n#if WITH_BULLET\n#include <BulletDS.hpp>\n#include <BulletR.hpp>\n#define IFBULLET(X) X\n#else\n#define IFBULLET(X)\n#endif\n\n#include \"SiconosBodies.hpp\"\n\n\/* QGLViewer *\/\n#include <qglviewer.h>\n#include <qapplication.h>\n\n#include <qevent.h>\n#include <qmessagebox.h>\n\n#ifdef QT_INTERFACE\n#include \"ui_viewerInterface.Qt4.h\"\nclass ViewerInterface : public QDialog, public Ui::Dialog\n{\npublic:\n ViewerInterface()\n {\n setupUi(this);\n }\n};\n#endif\n\n\/* convenient macros *\/\n\n\n#define GETALLDS(M) M->model()->nonSmoothDynamicalSystem()->topology()->dSG(0)\n#define GETNDS(M) GETALLDS(M)->size()\n\nstruct ForNdof : public Question<unsigned int>\n{\n using SiconosVisitor::visit;\n\n ANSWER_V(Disk, 3);\n ANSWER_V(Circle, 3);\n ANSWER_V(SphereLDS, 6);\n ANSWER_V(SphereNEDS, 6);\n IFBULLET(ANSWER_V(BulletDS, 6));\n};\n\n\nstruct ForFExt : public Question<SP::SiconosVector>\n{\n using SiconosVisitor::visit;\n\n ANSWER(Disk, fExt());\n ANSWER(Circle, fExt());\n ANSWER(SphereLDS, fExt());\n ANSWER(SphereNEDS, fExt());\n IFBULLET(ANSWER(BulletDS, fExt()));\n};\n\n\nstruct ForPosition : public Question<SP::SiconosVector>\n{\n using SiconosVisitor::visit;\n\n ANSWER(Disk, q());\n ANSWER(Circle, q());\n ANSWER(SphereLDS, q());\n ANSWER(SphereNEDS, q());\n IFBULLET(ANSWER(BulletDS, q()));\n};\n\nstruct ForRadius : public Question<double>\n{\n using SiconosVisitor::visit;\n\n ANSWER(Disk, getRadius());\n ANSWER(Circle, getRadius());\n ANSWER(SphereLDS, getRadius());\n ANSWER(SphereNEDS, getRadius());\n IFBULLET(ANSWER_V(BulletDS, 0.)); \/\/ fix\n};\n\nstruct ForMassValue : public Question<double>\n{\n using SiconosVisitor::visit;\n\n ANSWER(Disk, mass()->getValue(0, 0));\n ANSWER(Circle, mass()->getValue(0, 0));\n ANSWER(SphereLDS, mass()->getValue(0, 0));\n ANSWER(SphereNEDS, massValue());\n IFBULLET(ANSWER(BulletDS, massValue()));\n};\n\nstruct ForJachq : public Question<SP::SiconosMatrix>\n{\n using SiconosVisitor::visit;\n\n ANSWER(LagrangianR, jachq());\n ANSWER(NewtonEulerR, jachq());\n ANSWER(DiskDiskR, jachq());\n ANSWER(DiskPlanR, jachq());\n ANSWER(DiskMovingPlanR, jachq());\n ANSWER(SphereLDSPlanR, jachq());\n ANSWER(SphereNEDSPlanR, jachq());\n ANSWER(SphereLDSSphereLDSR, jachq());\n ANSWER(SphereNEDSSphereNEDSR, jachq());\n IFBULLET(ANSWER(BulletR, jachq()));\n};\n\nstruct ForContactForce : public Question<SP::SiconosVector>\n{\n using SiconosVisitor::visit;\n\n IFBULLET(ANSWER(BulletR, contactForce()));\n};\n\n\n\n\n#define GETX(C) ask<ForPosition>(*C)->getValue(0)\n#define GETY(C) ask<ForPosition>(*C)->getValue(1)\n#define GETZ(C) ask<ForPosition>(*C)->getValue(2)\n#define GETA1(C) ask<ForPosition>(*C)->getValue(3)\n#define GETA2(C) ask<ForPosition>(*C)->getValue(4)\n#define GETA3(C) ask<ForPosition>(*C)->getValue(5)\n#define GETA4(C) ask<ForPosition>(*C)->getValue(6)\n#define GETXFE(C) ask<ForFExt>(*C)->getValue(0)\n#define GETYFE(C) ask<ForFExt>(*C)->getValue(1)\n#define GETZFE(C) ask<ForFExt>(*C)->getValue(2)\n\n#define GETVX(C) ask<ForVelocity>(*C)->getValue(0)\n#define GETVY(C) ask<ForVelocity>(*C)->getValue(1)\n#define GETVZ(C) ask<ForVelocity>(*C)->getValue(2)\n\n#define GETVA1(C) ask<ForVelocity>(*C)->getValue(3)\n#define GETVA2(C) ask<ForVelocity>(*C)->getValue(4)\n#define GETVA3(C) ask<ForVelocity>(*C)->getValue(5)\n\n#define GETRADIUS(C) ask<ForRadius>(*C)\n\n\nenum SHAPE\n{\n DISK,\n CIRCLE,\n SPHERE,\n IFBULLET(BULLET)\n};\n\nstruct ForShape : public Question<SHAPE>\n{\n using SiconosVisitor::visit;\n\n ANSWER_V(Disk, DISK);\n ANSWER_V(Circle, CIRCLE);\n ANSWER_V(SphereLDS, SPHERE);\n ANSWER_V(SphereNEDS, SPHERE);\n IFBULLET(ANSWER_V(BulletDS, BULLET));\n};\n\n\/* dynamical system \/ figure association *\/\nclass QGLShape\n{\n\npublic:\n\n \/* construction from a LagrangianDS *\/\n QGLShape(SHAPE f, SP::DynamicalSystem D, const qglviewer::Frame* ref)\n {\n assert(D);\n\n figure_ = f;\n DS_ = D;\n frame_.reset(new qglviewer::ManipulatedFrame());\n frame_->setReferenceFrame(ref);\n savedFExt_ = ask<ForFExt>(*DS());\n selected_ = false;\n saved_ = true;\n type_ = Type::value(*DS());\n\n };\n\n ~QGLShape() {};\n\n \/* pointer to DS *\/\n SP::DynamicalSystem DS() const\n {\n return DS_;\n };\n\n \/* selection with mouse *\/\n bool selected()\n {\n return selected_ ;\n };\n void setSelection(bool v)\n {\n selected_ = v ;\n };\n\n \/* identifiant *\/\n int getD()\n {\n return id_ ;\n };\n void setID(int i)\n {\n id_ = i;\n };\n\n\n \/* External force set from mouse and restore *\/\n void saveFExt()\n {\n savedFExt_ = ask<ForFExt>(*DS());\n };\n void restoreFExt()\n {\n switch (Type::value(*DS()))\n {\n case Type::NewtonEulerDS :\n {\n std11::static_pointer_cast<NewtonEulerDS>(DS())\n ->setFExtPtr(std11::static_pointer_cast<SiconosVector>(savedFExt_));\n break;\n }\n case Type::LagrangianDS :\n {\n std11::static_pointer_cast<LagrangianDS>(DS())\n ->setFExtPtr(std11::static_pointer_cast<SiconosVector>(savedFExt_));\n break;\n };\n default:\n {};\n }\n };\n\n \/* DS frame *\/\n qglviewer::ManipulatedFrame * frame()\n {\n return frame_.get();\n };\n\n SHAPE shape() const\n {\n return figure_;\n }\n\n Type::Siconos type() const\n {\n return type_;\n }\n\nprotected:\n int id_;\n bool selected_;\n bool saved_;\n SP::SiconosVector savedFExt_;\n boost::shared_ptr<qglviewer::ManipulatedFrame> frame_;\n\n SHAPE figure_;\n SP::DynamicalSystem DS_;\n int positionSize_;\n\n Type::Siconos type_;\n\n};\n\nTYPEDEF_SPTR(QGLShape);\n\n\/* QGLViewer main object *\/\nclass BodiesViewer : public QGLViewer\n{\n\npublic:\n\n#ifdef QT_INTERFACE\n Viewer(QWidget *parent);\n#endif\n\npublic:\n virtual void draw() = 0;\n void drawWithNames();\n void initUCircle();\n void drawUCircle();\n void drawUDisk();\n void drawUCircleTicks(float a);\n void drawUDiskTicks(float a) ;\n void drawUTriangle(float depth = 0.) ;\n void drawVec(float x1, float y1, float x2, float y2) ;\n void drawRec(float x1, float y1, float x2, float y2, float w, float z = 0.);\n void drawArrow(float x1, float y1, float x2, float y2, float w);\n void drawPar(float x1, float y1, float z1, float x2, float y2, float z2, float w);\n void drawArrow(float x1, float y1, float z1, float x2, float y2, float z2, float w);\n void drawCircleTicks(float x, float y, float a, float r);\n void drawDiskTicks(float x, float y, float a, float r, float *c);\n void drawSimpleCircle(float x, float y, float r);\n void drawCircle(float x, float y, float a, float r, float *c);\n void drawDisk(float x, float y, float a, float r, float *c);\n void rotate(const float R[12]);\n void drawSphere(float x, float y, float z, float theta, float phi, float psi, float r, float *c);\n void drawSphere(float x, float y, float z, float a, float b, float c, float d, float r, float *color);\n void drawPolyg(unsigned int n, double* coor, float *c);\n\n virtual void drawQGLShape(const QGLShape&);\n virtual void drawSelectedQGLShape(const QGLShape&);\n void insertQGLShape(SHAPE, SP::DynamicalSystem);\n\n\nprotected :\n\n void postSelection(const QPoint& point);\n virtual void init();\n virtual void animate();\n virtual void mousePressEvent(QMouseEvent *);\n virtual void mouseMoveEvent(QMouseEvent *);\n virtual void mouseReleaseEvent(QMouseEvent *);\n virtual void keyPressEvent(QKeyEvent *);\n\n virtual QString helpString() const;\n boost::shared_ptr<qglviewer::WorldConstraint> constraint_;\n\n SP::SiconosBodies Siconos_;\n\n qglviewer::Frame* referenceFrame_;\n\n std::vector<SP::QGLShape> shapes_;\n\n void print(float x, float y, const char *s, int size);\n\n int NDS_;\n\n qglviewer::Vec selectedPoint_;\n\n int lastSelected_;\n\n bool myMouseBehavior_;\n\n bool stepSimulation_;\n bool stepNow_;\n\n long timeSiconos_;\n\n long timeGlob_;\n\n float _transparency;\n\n};\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ImageRegistration11.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates how to combine the MutualInformation metric with an\n\/\/ Evolutionary algorithm for optimization. Evolutionary algorithms are\n\/\/ naturally well-suited for optimizing the Mutual Information metric given its\n\/\/ randomic and noisy behavior.\n\/\/\n\/\/ The structure of the example is almost identical o the one illustrated in\n\/\/ ImageRegistration4. Therefore we will focus here on the setup that is\n\/\/ specifically required for the evolutionary optimizer.\n\/\/\n\/\/\n\/\/ \\index{itk::ImageRegistrationMethod!Multi-Modality}\n\/\/ \\index{itk::OnePlusOneEvolutionaryOptimizer!Multi-Modality}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkOnePlusOneEvolutionaryOptimizer.h\"\n#include \"itkNormalVariateGenerator.h\" \n#include \"itkImage.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ used to monitor the evolution of the registration process.\n\/\/\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() { m_LastMetricValue = 0.0; };\npublic:\n typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n double currentValue = optimizer->GetValue();\n \/\/ Only print out when the Metric value changes\n if( fabs( m_LastMetricValue - currentValue ) > 1e-7 )\n { \n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << currentValue << \" \";\n std::cout << optimizer->GetCurrentPosition() << std::endl;\n m_LastMetricValue = currentValue;\n }\n }\nprivate:\n double m_LastMetricValue;\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 3 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \"outputImagefile [differenceImage]\" << std::endl;\n return 1;\n }\n \n const unsigned int Dimension = 2;\n typedef unsigned short PixelType;\n \n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n\n typedef itk::TranslationTransform< double, Dimension > TransformType;\n typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType;\n typedef itk::LinearInterpolateImageFunction< \n MovingImageType,\n double > InterpolatorType;\n typedef itk::ImageRegistrationMethod< \n FixedImageType, \n MovingImageType > RegistrationType;\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ In this example the image types and all registration components,\n \/\/ except the metric, are declared as in Section \n \/\/ \\ref{sec:IntroductionImageRegistration}.\n \/\/ The Mattes mutual information metric type is \n \/\/ instantiated using the image types.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::MattesMutualInformationImageToImageMetric< \n FixedImageType, \n MovingImageType > MetricType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n TransformType::Pointer transform = TransformType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n\n registration->SetOptimizer( optimizer );\n registration->SetTransform( transform );\n registration->SetInterpolator( interpolator );\n \n MetricType::Pointer metric = MetricType::New();\n registration->SetMetric( metric );\n\n metric->SetNumberOfHistogramBins( 20 );\n metric->SetNumberOfSpatialSamples( 10000 );\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n registration->SetFixedImage( fixedImageReader->GetOutput() );\n registration->SetMovingImage( movingImageReader->GetOutput() );\n\n fixedImageReader->Update();\n\n registration->SetFixedImageRegion( \n fixedImageReader->GetOutput()->GetBufferedRegion() );\n\n\n typedef RegistrationType::ParametersType ParametersType;\n ParametersType initialParameters( transform->GetNumberOfParameters() );\n\n initialParameters[0] = 0.0; \/\/ Initial offset in mm along X\n initialParameters[1] = 0.0; \/\/ Initial offset in mm along Y\n \n registration->SetInitialTransformParameters( initialParameters );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Evolutionary algorithms are based on testing random variations\n \/\/ of parameters. In order to support the computation of random values,\n \/\/ ITK provides a family of random number generators. In this example, we\n \/\/ use the \\doxygen{NormalVariateGenerator} which generates values with a\n \/\/ normal distribution.\n \/\/\n \/\/ \\index{itk::NormalVariateGenerator!New()}\n \/\/ \\index{itk::NormalVariateGenerator!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Statistics::NormalVariateGenerator GeneratorType;\n\n GeneratorType::Pointer generator = GeneratorType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The random number generator must be initialized with a seed.\n \/\/\n \/\/ \\index{itk::NormalVariateGenerator!Initialize()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n generator->Initialize(12345);\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Another significant difference in the metric is that it\n \/\/ computes the negative mutual information and hence we\n \/\/ need to minimize the cost function in this case. In this\n \/\/ example we will use the same optimization parameters as in\n \/\/ Section \\ref{sec:IntroductionImageRegistration}.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n optimizer->MaximizeOn();\n\n optimizer->SetNormalVariateGenerator( generator );\n optimizer->Initialize( 10 );\n optimizer->SetEpsilon( 1.0 );\n optimizer->SetMaximumIteration( 4000 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Create the Command observer and register it with the optimizer.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n try \n { \n registration->StartRegistration(); \n } \n catch( itk::ExceptionObject & err ) \n { \n std::cout << \"ExceptionObject caught !\" << std::endl; \n std::cout << err << std::endl; \n return -1;\n } \n\n ParametersType finalParameters = registration->GetLastTransformParameters();\n \n double TranslationAlongX = finalParameters[0];\n double TranslationAlongY = finalParameters[1];\n \n unsigned int numberOfIterations = optimizer->GetCurrentIteration();\n \n double bestValue = optimizer->GetValue();\n\n\n \/\/ Print out results\n \/\/\n std::cout << \"Result = \" << std::endl;\n std::cout << \" Translation X = \" << TranslationAlongX << std::endl;\n std::cout << \" Translation Y = \" << TranslationAlongY << std::endl;\n std::cout << \" Iterations = \" << numberOfIterations << std::endl;\n std::cout << \" Metric value = \" << bestValue << std::endl;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ This example is executed using the same multi-modality images as\n \/\/ in the previous one. The registration converges after $24$ iterations and produces\n \/\/ the following results:\n \/\/\n \/\/ \\begin{verbatim}\n \/\/ Translation X = 13.1719\n \/\/ Translation Y = 16.9006\n \/\/ \\end{verbatim}\n \/\/ These values are a very close match to \n \/\/ the true misaligment introduced in the moving image.\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n TransformType::Pointer finalTransform = TransformType::New();\n\n finalTransform->SetParameters( finalParameters );\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( finalTransform );\n resample->SetInput( movingImageReader->GetOutput() );\n\n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n\n\n typedef unsigned char OutputPixelType;\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n writer->SetFileName( argv[3] );\n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n return 0;\n}\n\n<commit_msg>FIX: MattesMI is optimal for a minimal value. The optimizer should be set to MaximizeOff().<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ImageRegistration11.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates how to combine the MutualInformation metric with an\n\/\/ Evolutionary algorithm for optimization. Evolutionary algorithms are\n\/\/ naturally well-suited for optimizing the Mutual Information metric given its\n\/\/ randomic and noisy behavior.\n\/\/\n\/\/ The structure of the example is almost identical o the one illustrated in\n\/\/ ImageRegistration4. Therefore we will focus here on the setup that is\n\/\/ specifically required for the evolutionary optimizer.\n\/\/\n\/\/\n\/\/ \\index{itk::ImageRegistrationMethod!Multi-Modality}\n\/\/ \\index{itk::OnePlusOneEvolutionaryOptimizer!Multi-Modality}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkOnePlusOneEvolutionaryOptimizer.h\"\n#include \"itkNormalVariateGenerator.h\" \n#include \"itkImage.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ used to monitor the evolution of the registration process.\n\/\/\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() { m_LastMetricValue = 0.0; };\npublic:\n typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n double currentValue = optimizer->GetValue();\n \/\/ Only print out when the Metric value changes\n if( fabs( m_LastMetricValue - currentValue ) > 1e-7 )\n { \n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << currentValue << \" \";\n std::cout << optimizer->GetCurrentPosition() << std::endl;\n m_LastMetricValue = currentValue;\n }\n }\nprivate:\n double m_LastMetricValue;\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 3 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \"outputImagefile [differenceImage]\" << std::endl;\n return 1;\n }\n \n const unsigned int Dimension = 2;\n typedef unsigned short PixelType;\n \n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n\n typedef itk::TranslationTransform< double, Dimension > TransformType;\n typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType;\n typedef itk::LinearInterpolateImageFunction< \n MovingImageType,\n double > InterpolatorType;\n typedef itk::ImageRegistrationMethod< \n FixedImageType, \n MovingImageType > RegistrationType;\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ In this example the image types and all registration components,\n \/\/ except the metric, are declared as in Section \n \/\/ \\ref{sec:IntroductionImageRegistration}.\n \/\/ The Mattes mutual information metric type is \n \/\/ instantiated using the image types.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::MattesMutualInformationImageToImageMetric< \n FixedImageType, \n MovingImageType > MetricType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n TransformType::Pointer transform = TransformType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n\n registration->SetOptimizer( optimizer );\n registration->SetTransform( transform );\n registration->SetInterpolator( interpolator );\n \n MetricType::Pointer metric = MetricType::New();\n registration->SetMetric( metric );\n\n metric->SetNumberOfHistogramBins( 20 );\n metric->SetNumberOfSpatialSamples( 10000 );\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n registration->SetFixedImage( fixedImageReader->GetOutput() );\n registration->SetMovingImage( movingImageReader->GetOutput() );\n\n fixedImageReader->Update();\n\n registration->SetFixedImageRegion( \n fixedImageReader->GetOutput()->GetBufferedRegion() );\n\n\n typedef RegistrationType::ParametersType ParametersType;\n ParametersType initialParameters( transform->GetNumberOfParameters() );\n\n initialParameters[0] = 0.0; \/\/ Initial offset in mm along X\n initialParameters[1] = 0.0; \/\/ Initial offset in mm along Y\n \n registration->SetInitialTransformParameters( initialParameters );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Evolutionary algorithms are based on testing random variations\n \/\/ of parameters. In order to support the computation of random values,\n \/\/ ITK provides a family of random number generators. In this example, we\n \/\/ use the \\doxygen{NormalVariateGenerator} which generates values with a\n \/\/ normal distribution.\n \/\/\n \/\/ \\index{itk::NormalVariateGenerator!New()}\n \/\/ \\index{itk::NormalVariateGenerator!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Statistics::NormalVariateGenerator GeneratorType;\n\n GeneratorType::Pointer generator = GeneratorType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The random number generator must be initialized with a seed.\n \/\/\n \/\/ \\index{itk::NormalVariateGenerator!Initialize()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n generator->Initialize(12345);\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Another significant difference in the metric is that it\n \/\/ computes the negative mutual information and hence we\n \/\/ need to minimize the cost function in this case. In this\n \/\/ example we will use the same optimization parameters as in\n \/\/ Section \\ref{sec:IntroductionImageRegistration}.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n optimizer->MaximizeOff();\n\n optimizer->SetNormalVariateGenerator( generator );\n optimizer->Initialize( 10 );\n optimizer->SetEpsilon( 1.0 );\n optimizer->SetMaximumIteration( 4000 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Create the Command observer and register it with the optimizer.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n try \n { \n registration->StartRegistration(); \n } \n catch( itk::ExceptionObject & err ) \n { \n std::cout << \"ExceptionObject caught !\" << std::endl; \n std::cout << err << std::endl; \n return -1;\n } \n\n ParametersType finalParameters = registration->GetLastTransformParameters();\n \n double TranslationAlongX = finalParameters[0];\n double TranslationAlongY = finalParameters[1];\n \n unsigned int numberOfIterations = optimizer->GetCurrentIteration();\n \n double bestValue = optimizer->GetValue();\n\n\n \/\/ Print out results\n \/\/\n std::cout << \"Result = \" << std::endl;\n std::cout << \" Translation X = \" << TranslationAlongX << std::endl;\n std::cout << \" Translation Y = \" << TranslationAlongY << std::endl;\n std::cout << \" Iterations = \" << numberOfIterations << std::endl;\n std::cout << \" Metric value = \" << bestValue << std::endl;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ This example is executed using the same multi-modality images as\n \/\/ in the previous one. The registration converges after $24$ iterations and produces\n \/\/ the following results:\n \/\/\n \/\/ \\begin{verbatim}\n \/\/ Translation X = 13.1719\n \/\/ Translation Y = 16.9006\n \/\/ \\end{verbatim}\n \/\/ These values are a very close match to \n \/\/ the true misaligment introduced in the moving image.\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n TransformType::Pointer finalTransform = TransformType::New();\n\n finalTransform->SetParameters( finalParameters );\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( finalTransform );\n resample->SetInput( movingImageReader->GetOutput() );\n\n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n\n\n typedef unsigned char OutputPixelType;\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n writer->SetFileName( argv[3] );\n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Pixie\n\/\/\n\/\/ Copyright 1999 - 2003, Okan Arikan\n\/\/\n\/\/ Contact: okan@cs.utexas.edu\n\/\/\n\/\/\tThis library is free software; you can redistribute it and\/or\n\/\/\tmodify it under the terms of the GNU Lesser General Public\n\/\/\tLicense as published by the Free Software Foundation; either\n\/\/\tversion 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/\tThis library is distributed in the hope that it will be useful,\n\/\/\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/\tLesser General Public License for more details.\n\/\/\n\/\/\tYou should have received a copy of the GNU Lesser General Public\n\/\/\tLicense along with this library; if not, write to the Free Software\n\/\/\tFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File\t\t\t\t:\tfile.cpp\n\/\/ Classes\t\t\t\t:\n\/\/ Description\t\t\t:\tThis file implements the default output device\n\/\/\t\t\t\t\t\t\tthat sends the image into a file\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"common\/global.h\"\n#include \"common\/algebra.h\"\n#include \"common\/os.h\"\n#include \"ri\/dsply.h\"\t\t\t\t\t\t\t\/\/ The display driver interface\n\n#include <stdlib.h>\t\t\t\t\t\t\t\t\/\/ Ensure we have NULL defined before libtiff\n#include <tiffio.h>\t\t\t\t\t\t\t\t\/\/ Libtiff is required\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Class\t\t\t\t:\tCRendererbuffer\n\/\/ Description\t\t\t:\tHolds the framebuffer\n\/\/ Comments\t\t\t\t:\nclass\tCFileFramebuffer {\npublic:\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Description\t\t\t:\tCtor\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\t\t\t\tCFileFramebuffer(const char *name,int width,int height,int numSamples,const char *samples,TDisplayParameterFunction findParameter) {\n\t\t\t\t\tint\t\t\ti;\n\t\t\t\t\tfloat\t\t*tmp;\n\t\t\t\t\tfloat\t\tworldToNDC[16];\n\t\t\t\t\tfloat\t\tworldToCamera[16];\n\t\t\t\t\tchar\t\t*software;\n\t\t\t\t\tconst char\t*compression\t=\tNULL;\n\n\t\t\t\t\t\/\/ Open the image file\n\t\t\t\t\timage\t\t\t\t=\tTIFFOpen(name,\"w\");\n\n\t\t\t\t\t\/\/ If we could not open the file, there's nothing to do\n\t\t\t\t\tif (image == NULL)\treturn;\n\n\t\t\t\t\t\/\/ Copy the quantization data\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"quantize\",FLOAT_PARAMETER,4))) {\n\t\t\t\t\t\tqzero\t\t\t=\ttmp[0];\n\t\t\t\t\t\tqone\t\t\t=\ttmp[1];\n\t\t\t\t\t\tqmin\t\t\t=\ttmp[2];\n\t\t\t\t\t\tqmax\t\t\t=\ttmp[3];\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Get the gamma correction stuff (only if we're not depth)\n\t\t\t\t\tif (strcmp(samples,\"z\") != 0) {\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"dither\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tqamp\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"gamma\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tgamma\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"gain\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tgain\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ If we're saving the z channel, we must be HDR\n\t\t\t\t\t\tqmin\t\t\t=\t0;\n\t\t\t\t\t\tqmax\t\t\t=\t0;\n\t\t\t\t\t\tqzero\t\t\t=\t0;\n\t\t\t\t\t\tqone\t\t\t=\t0;\n\t\t\t\t\t\tqamp\t\t\t=\t0;\n\t\t\t\t\t\tgamma\t\t\t=\t1;\n\t\t\t\t\t\tgain\t\t\t=\t1;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Camera to world matrix\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"NP\",FLOAT_PARAMETER,16))) {\n\t\t\t\t\t\tint\ti;\n\n\t\t\t\t\t\tfor (i=0;i<16;i++) {\n\t\t\t\t\t\t\tworldToNDC[i]\t=\ttmp[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Camera to world matrix\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"Nl\",FLOAT_PARAMETER,16))) {\n\t\t\t\t\t\tint\ti;\n\n\t\t\t\t\t\tfor (i=0;i<16;i++) {\n\t\t\t\t\t\t\tworldToCamera[i]\t=\ttmp[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsoftware\t=\t(char *) findParameter(\"Software\",STRING_PARAMETER,1);\n\n\t\t\t\t\tcompression\t=\t(char *) findParameter(\"compression\",STRING_PARAMETER,1);\n\n\t\t\t\t\tif (qmax == 0) {\n\t\t\t\t\t\tbitspersample\t=\t32;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_IEEEFP;\n\t\t\t\t\t} else if (qmax > 65535) {\n\t\t\t\t\t\tbitspersample\t=\t32;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t} else if (qmax > 255) {\n\t\t\t\t\t\tbitspersample\t=\t16;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbitspersample\t=\t8;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Set the tiff fields\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_IMAGEWIDTH,\t\t\t(unsigned long) width);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_IMAGELENGTH,\t\t(unsigned long) height);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_ORIENTATION,\t\tORIENTATION_TOPLEFT);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PLANARCONFIG,\t\tPLANARCONFIG_CONTIG);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_RESOLUTIONUNIT,\t\tRESUNIT_NONE);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_XRESOLUTION,\t\t(float) 1.0);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_YRESOLUTION,\t\t(float) 1.0);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_BITSPERSAMPLE,\t\t(unsigned short) bitspersample);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_SAMPLEFORMAT,\t\t(unsigned short) sampleformat);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL,\t(unsigned short) numSamples);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN,\tworldToNDC);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA,\tworldToCamera);\n\n\t\t\t\t\t\/\/ Compute the size of a pixel\n\t\t\t\t\tpixelSize\t=\tnumSamples*bitspersample \/ 8;\n\n\t\t\t\t\t\/\/ The default compression is LZW\n\t\t\t\t\tif (compression != NULL) {\n\t\t\t\t\t\tif (strcmp(compression,\"LZW\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_LZW);\n\t\t\t\t\t\t} else if (strcmp(compression,\"JPEG\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_JPEG);\n\t\t\t\t\t\t} else if (strcmp(compression,\"Deflate\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_DEFLATE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (numSamples == 1)\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_PHOTOMETRIC,\tPHOTOMETRIC_MINISBLACK);\n\t\t\t\t\telse\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_PHOTOMETRIC,\tPHOTOMETRIC_RGB);\n\n\t\t\t\t\tif (numSamples == 4) {\n\t\t\t\t\t\tunsigned short sampleinfo = EXTRASAMPLE_ASSOCALPHA;\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1, &sampleinfo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (software != NULL)\tTIFFSetField(image, TIFFTAG_SOFTWARE,\t\tsoftware);\n\n\t\t\t\t\tlastSavedLine\t=\t0;\n\t\t\t\t\tscanlines\t\t=\tnew unsigned char*[height];\n\t\t\t\t\tscanlineUsage\t=\tnew int[height];\n\n\t\t\t\t\tfor (i=0;i<height;i++) {\n\t\t\t\t\t\tscanlines[i]\t\t=\tNULL;\n\t\t\t\t\t\tscanlineUsage[i]\t=\twidth;\n\t\t\t\t\t}\n\n\t\t\t\t\tthis->width\t\t\t=\twidth;\n\t\t\t\t\tthis->height\t\t=\theight;\n\t\t\t\t\tthis->numSamples\t=\tnumSamples;\n\n\t\t\t\t\tosCreateMutex(fileMutex);\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\t~CRendererbuffer\n\t\t\t\t\/\/ Description\t\t\t:\tDtor\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\t\t\t\t~CFileFramebuffer() {\n\t\t\t\t\tint\ti;\n\n\t\t\t\t\tif (image != NULL)\tTIFFClose(image);\n\t\t\t\t\telse\treturn;\n\n\t\t\t\t\tosDeleteMutex(fileMutex);\n\n\t\t\t\t\tfor (i=0;i<height;i++) {\n\t\t\t\t\t\tif (scanlines[i] != NULL)\tdelete [] (unsigned char *) scanlines[i];\n\t\t\t\t\t}\n\n\n\t\t\t\t\tdelete [] scanlines;\n\t\t\t\t\tdelete [] scanlineUsage;\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\twrite\n\t\t\t\t\/\/ Description\t\t\t:\tSwrite some data to the out file\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\tvoid\t\twrite(int x,int y,int w,int h,float *data) {\n\t\t\t\t\tint\t\t\t\ti,j;\n\t\t\t\t\tint\t\t\t\tcheck\t\t=\tFALSE;\n\t\t\t\t\tint\t\t\t\tnumChannels\t=\tw*h*numSamples;\n\n\t\t\t\t\tif (image == NULL)\treturn;\n\n\t\t\t\t\t\/\/ Apply the gamma correction if applicable\n\t\t\t\t\tif ((gamma != 1) || (gain != 1)) {\n\t\t\t\t\t\tfloat\tinvGamma\t=\t1 \/ gamma;\n\n\t\t\t\t\t\tfor (i=0;i<numChannels;i++) {\n\t\t\t\t\t\t\tdata[i]\t=\tpowf(gain*data[i],invGamma);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Apply the quantization if applicable\n\t\t\t\t\tif (qmax > 0) {\n\t\t\t\t\t\tfor (i=0;i<numChannels;i++) {\n\t\t\t\t\t\t\tfloat\tdither\t=\tqamp*(2*(rand() \/ (float) RAND_MAX)-1);\n\t\t\t\t\t\t\tdata[i]\t\t\t=\tqzero + (qone - qzero)*data[i] + dither;\n\t\t\t\t\t\t\tif (data[i] < qmin)\t\t\tdata[i]\t=\tqmin;\n\t\t\t\t\t\t\telse if (data[i] > qmax)\tdata[i]\t=\tqmax;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Lock the file\n\t\t\t\t\tosLock(fileMutex);\n\n\t\t\t\t\t\/\/ Record the data\n\t\t\t\t\tfor (i=0;i<h;i++) {\n\t\t\t\t\t\tunsigned char\t*scan;\n\n\t\t\t\t\t\tif (scanlines[i+y] == NULL) {\n\t\t\t\t\t\t\tscanlines[i+y]\t=\tscan\t=\tnew unsigned char[width*pixelSize];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan\t\t\t=\t(unsigned char *) scanlines[i+y];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch(bitspersample) {\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned char\t*dest\t=\t&((unsigned char *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned char) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 16:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned short\t*dest\t=\t&((unsigned short *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned short) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 32:\n\t\t\t\t\t\t\tif (sampleformat == SAMPLEFORMAT_IEEEFP) {\n\t\t\t\t\t\t\t\tconst float\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tfloat\t\t*dest\t=\t&((float *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t*src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned int\t*dest\t=\t&((unsigned int *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned int) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tscanlineUsage[i+y]\t-=\tw;\n\t\t\t\t\t\tif (scanlineUsage[i+y] <= 0)\tcheck\t=\tTRUE;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (check) {\n\t\t\t\t\t\tfor (;lastSavedLine<height;lastSavedLine++) {\n\t\t\t\t\t\t\tif (scanlineUsage[lastSavedLine] == 0) {\n\t\t\t\t\t\t\t\tif (scanlines[lastSavedLine] != NULL) {\n\t\t\t\t\t\t\t\t\tTIFFWriteScanline(image,scanlines[lastSavedLine],lastSavedLine,0);\n\t\t\t\t\t\t\t\t\tdelete [] scanlines[lastSavedLine];\n\t\t\t\t\t\t\t\t\tscanlines[lastSavedLine]\t=\tNULL;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Release the file\n\t\t\t\t\tosUnlock(fileMutex);\n\t\t\t\t}\n\n\tunsigned char\t**scanlines;\n\tint\t\t\t\t*scanlineUsage;\n\tint\t\t\t\twidth,height;\n\tTIFF\t\t\t*image;\n\tint\t\t\t\tpixelSize;\n\tint\t\t\t\tnumSamples;\n\tint\t\t\t\tlastSavedLine;\n\tTMutex\t\t\tfileMutex;\n\n\tfloat\t\t\tqmin,qmax,qone,qzero,qamp;\n\tfloat\t\t\tgamma,gain;\n\tint\t\t\t\tbitspersample,sampleformat;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayStart\n\/\/ Description\t\t\t:\tBegin receiving an image\n\/\/ Return Value\t\t\t:\tThe handle to the image on success, NULL othervise\n\/\/ Comments\t\t\t\t:\nvoid\t*displayStart(const char *name,int width,int height,int numSamples,const char *samples,TDisplayParameterFunction findParameter) {\n\tCFileFramebuffer\t*fb\t=\tnew CFileFramebuffer(name,width,height,numSamples,samples,findParameter);\n\t\n\tif (fb->image == NULL) {\t\/\/ If we could not open the image, return NULL\n\t\tdelete fb;\n\t\treturn NULL;\n\t}\n\n\treturn fb;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayData\n\/\/ Description\t\t\t:\tReceive image data\n\/\/ Return Value\t\t\t:\tTRUE on success, FALSE otherwise\n\/\/ Comments\t\t\t\t:\nint\t\tdisplayData(void *im,int x,int y,int w,int h,float *data) {\n\tCFileFramebuffer\t*fb\t=\t(CFileFramebuffer *) im;\n\t\n\tassert(fb != NULL);\n\n\tfb->write(x,y,w,h,data);\n\n\treturn TRUE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayFinish\n\/\/ Description\t\t\t:\tFinish receiving an image\n\/\/ Return Value\t\t\t:\tTRUE on success, FALSE othervise\n\/\/ Comments\t\t\t\t:\nvoid\tdisplayFinish(void *im) {\n\tCFileFramebuffer\t*fb\t=\t(CFileFramebuffer *) im;\n\n\tassert(fb != NULL);\n\n\tdelete fb;\n}\n\n<commit_msg>cleanup quantize for depth<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Pixie\n\/\/\n\/\/ Copyright 1999 - 2003, Okan Arikan\n\/\/\n\/\/ Contact: okan@cs.utexas.edu\n\/\/\n\/\/\tThis library is free software; you can redistribute it and\/or\n\/\/\tmodify it under the terms of the GNU Lesser General Public\n\/\/\tLicense as published by the Free Software Foundation; either\n\/\/\tversion 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/\tThis library is distributed in the hope that it will be useful,\n\/\/\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/\tLesser General Public License for more details.\n\/\/\n\/\/\tYou should have received a copy of the GNU Lesser General Public\n\/\/\tLicense along with this library; if not, write to the Free Software\n\/\/\tFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File\t\t\t\t:\tfile.cpp\n\/\/ Classes\t\t\t\t:\n\/\/ Description\t\t\t:\tThis file implements the default output device\n\/\/\t\t\t\t\t\t\tthat sends the image into a file\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"common\/global.h\"\n#include \"common\/algebra.h\"\n#include \"common\/os.h\"\n#include \"ri\/dsply.h\"\t\t\t\t\t\t\t\/\/ The display driver interface\n\n#include <stdlib.h>\t\t\t\t\t\t\t\t\/\/ Ensure we have NULL defined before libtiff\n#include <tiffio.h>\t\t\t\t\t\t\t\t\/\/ Libtiff is required\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Class\t\t\t\t:\tCRendererbuffer\n\/\/ Description\t\t\t:\tHolds the framebuffer\n\/\/ Comments\t\t\t\t:\nclass\tCFileFramebuffer {\npublic:\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Description\t\t\t:\tCtor\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\t\t\t\tCFileFramebuffer(const char *name,int width,int height,int numSamples,const char *samples,TDisplayParameterFunction findParameter) {\n\t\t\t\t\tint\t\t\ti;\n\t\t\t\t\tfloat\t\t*tmp;\n\t\t\t\t\tfloat\t\tworldToNDC[16];\n\t\t\t\t\tfloat\t\tworldToCamera[16];\n\t\t\t\t\tchar\t\t*software;\n\t\t\t\t\tconst char\t*compression\t=\tNULL;\n\n\t\t\t\t\t\/\/ Open the image file\n\t\t\t\t\timage\t\t\t\t=\tTIFFOpen(name,\"w\");\n\n\t\t\t\t\t\/\/ If we could not open the file, there's nothing to do\n\t\t\t\t\tif (image == NULL)\treturn;\n\n\t\t\t\t\t\/\/ Copy the quantization data\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"quantize\",FLOAT_PARAMETER,4))) {\n\t\t\t\t\t\tqzero\t\t\t=\ttmp[0];\n\t\t\t\t\t\tqone\t\t\t=\ttmp[1];\n\t\t\t\t\t\tqmin\t\t\t=\ttmp[2];\n\t\t\t\t\t\tqmax\t\t\t=\ttmp[3];\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Get the gamma correction stuff (only if we're not depth)\n\t\t\t\t\tif (strcmp(samples,\"z\") != 0) {\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"dither\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tqamp\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"gamma\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tgamma\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((tmp = (float *) findParameter(\"gain\",FLOAT_PARAMETER,1))) {\n\t\t\t\t\t\t\tgain\t\t\t=\ttmp[0];\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ If we're saving the z channel, we must be HDR\n\t\t\t\t\t\tqamp\t\t\t=\t0;\n\t\t\t\t\t\tgamma\t\t\t=\t1;\n\t\t\t\t\t\tgain\t\t\t=\t1;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Camera to world matrix\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"NP\",FLOAT_PARAMETER,16))) {\n\t\t\t\t\t\tint\ti;\n\n\t\t\t\t\t\tfor (i=0;i<16;i++) {\n\t\t\t\t\t\t\tworldToNDC[i]\t=\ttmp[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Camera to world matrix\n\t\t\t\t\tif ((tmp = (float *) findParameter(\"Nl\",FLOAT_PARAMETER,16))) {\n\t\t\t\t\t\tint\ti;\n\n\t\t\t\t\t\tfor (i=0;i<16;i++) {\n\t\t\t\t\t\t\tworldToCamera[i]\t=\ttmp[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsoftware\t=\t(char *) findParameter(\"Software\",STRING_PARAMETER,1);\n\n\t\t\t\t\tcompression\t=\t(char *) findParameter(\"compression\",STRING_PARAMETER,1);\n\n\t\t\t\t\tif (qmax == 0) {\n\t\t\t\t\t\tbitspersample\t=\t32;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_IEEEFP;\n\t\t\t\t\t} else if (qmax > 65535) {\n\t\t\t\t\t\tbitspersample\t=\t32;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t} else if (qmax > 255) {\n\t\t\t\t\t\tbitspersample\t=\t16;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbitspersample\t=\t8;\n\t\t\t\t\t\tsampleformat\t=\tSAMPLEFORMAT_UINT;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Set the tiff fields\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_IMAGEWIDTH,\t\t\t(unsigned long) width);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_IMAGELENGTH,\t\t(unsigned long) height);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_ORIENTATION,\t\tORIENTATION_TOPLEFT);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PLANARCONFIG,\t\tPLANARCONFIG_CONTIG);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_RESOLUTIONUNIT,\t\tRESUNIT_NONE);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_XRESOLUTION,\t\t(float) 1.0);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_YRESOLUTION,\t\t(float) 1.0);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_BITSPERSAMPLE,\t\t(unsigned short) bitspersample);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_SAMPLEFORMAT,\t\t(unsigned short) sampleformat);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL,\t(unsigned short) numSamples);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN,\tworldToNDC);\n\t\t\t\t\tTIFFSetField(image, TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA,\tworldToCamera);\n\n\t\t\t\t\t\/\/ Compute the size of a pixel\n\t\t\t\t\tpixelSize\t=\tnumSamples*bitspersample \/ 8;\n\n\t\t\t\t\t\/\/ The default compression is LZW\n\t\t\t\t\tif (compression != NULL) {\n\t\t\t\t\t\tif (strcmp(compression,\"LZW\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_LZW);\n\t\t\t\t\t\t} else if (strcmp(compression,\"JPEG\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_JPEG);\n\t\t\t\t\t\t} else if (strcmp(compression,\"Deflate\") == 0) {\n\t\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_COMPRESSION,\tCOMPRESSION_DEFLATE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (numSamples == 1)\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_PHOTOMETRIC,\tPHOTOMETRIC_MINISBLACK);\n\t\t\t\t\telse\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_PHOTOMETRIC,\tPHOTOMETRIC_RGB);\n\n\t\t\t\t\tif (numSamples == 4) {\n\t\t\t\t\t\tunsigned short sampleinfo = EXTRASAMPLE_ASSOCALPHA;\n\t\t\t\t\t\tTIFFSetField(image, TIFFTAG_EXTRASAMPLES, 1, &sampleinfo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (software != NULL)\tTIFFSetField(image, TIFFTAG_SOFTWARE,\t\tsoftware);\n\n\t\t\t\t\tlastSavedLine\t=\t0;\n\t\t\t\t\tscanlines\t\t=\tnew unsigned char*[height];\n\t\t\t\t\tscanlineUsage\t=\tnew int[height];\n\n\t\t\t\t\tfor (i=0;i<height;i++) {\n\t\t\t\t\t\tscanlines[i]\t\t=\tNULL;\n\t\t\t\t\t\tscanlineUsage[i]\t=\twidth;\n\t\t\t\t\t}\n\n\t\t\t\t\tthis->width\t\t\t=\twidth;\n\t\t\t\t\tthis->height\t\t=\theight;\n\t\t\t\t\tthis->numSamples\t=\tnumSamples;\n\n\t\t\t\t\tosCreateMutex(fileMutex);\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\t~CRendererbuffer\n\t\t\t\t\/\/ Description\t\t\t:\tDtor\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\t\t\t\t~CFileFramebuffer() {\n\t\t\t\t\tint\ti;\n\n\t\t\t\t\tif (image != NULL)\tTIFFClose(image);\n\t\t\t\t\telse\treturn;\n\n\t\t\t\t\tosDeleteMutex(fileMutex);\n\n\t\t\t\t\tfor (i=0;i<height;i++) {\n\t\t\t\t\t\tif (scanlines[i] != NULL)\tdelete [] (unsigned char *) scanlines[i];\n\t\t\t\t\t}\n\n\n\t\t\t\t\tdelete [] scanlines;\n\t\t\t\t\tdelete [] scanlineUsage;\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ Class\t\t\t\t:\tCRendererbuffer\n\t\t\t\t\/\/ Method\t\t\t\t:\twrite\n\t\t\t\t\/\/ Description\t\t\t:\tSwrite some data to the out file\n\t\t\t\t\/\/ Return Value\t\t\t:\t-\n\t\t\t\t\/\/ Comments\t\t\t\t:\n\tvoid\t\twrite(int x,int y,int w,int h,float *data) {\n\t\t\t\t\tint\t\t\t\ti,j;\n\t\t\t\t\tint\t\t\t\tcheck\t\t=\tFALSE;\n\t\t\t\t\tint\t\t\t\tnumChannels\t=\tw*h*numSamples;\n\n\t\t\t\t\tif (image == NULL)\treturn;\n\n\t\t\t\t\t\/\/ Apply the gamma correction if applicable\n\t\t\t\t\tif ((gamma != 1) || (gain != 1)) {\n\t\t\t\t\t\tfloat\tinvGamma\t=\t1 \/ gamma;\n\n\t\t\t\t\t\tfor (i=0;i<numChannels;i++) {\n\t\t\t\t\t\t\tdata[i]\t=\tpowf(gain*data[i],invGamma);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Apply the quantization if applicable\n\t\t\t\t\tif (qmax > 0) {\n\t\t\t\t\t\tfor (i=0;i<numChannels;i++) {\n\t\t\t\t\t\t\tfloat\tdither\t=\tqamp*(2*(rand() \/ (float) RAND_MAX)-1);\n\t\t\t\t\t\t\tdata[i]\t\t\t=\tqzero + (qone - qzero)*data[i] + dither;\n\t\t\t\t\t\t\tif (data[i] < qmin)\t\t\tdata[i]\t=\tqmin;\n\t\t\t\t\t\t\telse if (data[i] > qmax)\tdata[i]\t=\tqmax;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Lock the file\n\t\t\t\t\tosLock(fileMutex);\n\n\t\t\t\t\t\/\/ Record the data\n\t\t\t\t\tfor (i=0;i<h;i++) {\n\t\t\t\t\t\tunsigned char\t*scan;\n\n\t\t\t\t\t\tif (scanlines[i+y] == NULL) {\n\t\t\t\t\t\t\tscanlines[i+y]\t=\tscan\t=\tnew unsigned char[width*pixelSize];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan\t\t\t=\t(unsigned char *) scanlines[i+y];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch(bitspersample) {\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned char\t*dest\t=\t&((unsigned char *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned char) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 16:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned short\t*dest\t=\t&((unsigned short *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned short) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 32:\n\t\t\t\t\t\t\tif (sampleformat == SAMPLEFORMAT_IEEEFP) {\n\t\t\t\t\t\t\t\tconst float\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tfloat\t\t*dest\t=\t&((float *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t*src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst float\t\t*src\t=\t&data[i*w*numSamples];\n\t\t\t\t\t\t\t\tunsigned int\t*dest\t=\t&((unsigned int *) scan)[x*numSamples];\n\n\t\t\t\t\t\t\t\tfor (j=0;j<w*numSamples;j++) {\n\t\t\t\t\t\t\t\t\t*dest++\t\t=\t(unsigned int) *src++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tscanlineUsage[i+y]\t-=\tw;\n\t\t\t\t\t\tif (scanlineUsage[i+y] <= 0)\tcheck\t=\tTRUE;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (check) {\n\t\t\t\t\t\tfor (;lastSavedLine<height;lastSavedLine++) {\n\t\t\t\t\t\t\tif (scanlineUsage[lastSavedLine] == 0) {\n\t\t\t\t\t\t\t\tif (scanlines[lastSavedLine] != NULL) {\n\t\t\t\t\t\t\t\t\tTIFFWriteScanline(image,scanlines[lastSavedLine],lastSavedLine,0);\n\t\t\t\t\t\t\t\t\tdelete [] scanlines[lastSavedLine];\n\t\t\t\t\t\t\t\t\tscanlines[lastSavedLine]\t=\tNULL;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Release the file\n\t\t\t\t\tosUnlock(fileMutex);\n\t\t\t\t}\n\n\tunsigned char\t**scanlines;\n\tint\t\t\t\t*scanlineUsage;\n\tint\t\t\t\twidth,height;\n\tTIFF\t\t\t*image;\n\tint\t\t\t\tpixelSize;\n\tint\t\t\t\tnumSamples;\n\tint\t\t\t\tlastSavedLine;\n\tTMutex\t\t\tfileMutex;\n\n\tfloat\t\t\tqmin,qmax,qone,qzero,qamp;\n\tfloat\t\t\tgamma,gain;\n\tint\t\t\t\tbitspersample,sampleformat;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayStart\n\/\/ Description\t\t\t:\tBegin receiving an image\n\/\/ Return Value\t\t\t:\tThe handle to the image on success, NULL othervise\n\/\/ Comments\t\t\t\t:\nvoid\t*displayStart(const char *name,int width,int height,int numSamples,const char *samples,TDisplayParameterFunction findParameter) {\n\tCFileFramebuffer\t*fb\t=\tnew CFileFramebuffer(name,width,height,numSamples,samples,findParameter);\n\t\n\tif (fb->image == NULL) {\t\/\/ If we could not open the image, return NULL\n\t\tdelete fb;\n\t\treturn NULL;\n\t}\n\n\treturn fb;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayData\n\/\/ Description\t\t\t:\tReceive image data\n\/\/ Return Value\t\t\t:\tTRUE on success, FALSE otherwise\n\/\/ Comments\t\t\t\t:\nint\t\tdisplayData(void *im,int x,int y,int w,int h,float *data) {\n\tCFileFramebuffer\t*fb\t=\t(CFileFramebuffer *) im;\n\t\n\tassert(fb != NULL);\n\n\tfb->write(x,y,w,h,data);\n\n\treturn TRUE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function\t\t\t\t:\tdisplayFinish\n\/\/ Description\t\t\t:\tFinish receiving an image\n\/\/ Return Value\t\t\t:\tTRUE on success, FALSE othervise\n\/\/ Comments\t\t\t\t:\nvoid\tdisplayFinish(void *im) {\n\tCFileFramebuffer\t*fb\t=\t(CFileFramebuffer *) im;\n\n\tassert(fb != NULL);\n\n\tdelete fb;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <UnitTest++\/src\/UnitTest++.h>\r\n#include \"rdestl\/fixed_substring.h\"\r\n\r\nnamespace\r\n{\r\n\tTEST(DefaultCtorGivesEmptyString)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str;\r\n\t\tCHECK(str.empty());\r\n\t}\r\n\tTEST(FromCStrNotEmpty)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\tCHECK(!str.empty());\r\n\t}\r\n\tTEST(FromCStrCopiesContents)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\tCHECK_EQUAL(0, rde::strcompare(str.data(), \"Hello world\"));\r\n\t}\r\n\tTEST(CopyCtorGivesEqualStrings)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\trde::fixed_substring<char, 16> str2(str);\r\n\t\tCHECK(!str2.empty());\r\n\t\tCHECK(str == str2);\r\n\t}\r\n}\r\n\r\n<commit_msg>append() test<commit_after>#include <UnitTest++\/src\/UnitTest++.h>\r\n#include \"rdestl\/fixed_substring.h\"\r\n\r\nnamespace\r\n{\r\n\tTEST(DefaultCtorGivesEmptyString)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str;\r\n\t\tCHECK(str.empty());\r\n\t}\r\n\tTEST(FromCStrNotEmpty)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\tCHECK(!str.empty());\r\n\t}\r\n\tTEST(FromCStrCopiesContents)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\tCHECK_EQUAL(0, rde::strcompare(str.data(), \"Hello world\"));\r\n\t}\r\n\tTEST(CopyCtorGivesEqualStrings)\r\n\t{\r\n\t\trde::fixed_substring<char, 16> str(\"Hello world\");\r\n\t\trde::fixed_substring<char, 16> str2(str);\r\n\t\tCHECK(!str2.empty());\r\n\t\tCHECK(str == str2);\r\n\t}\r\n\tTEST(Append)\r\n\t{\r\n\t\trde::fixed_substring<char, 9> str(\"Hello \");\r\n\t\tstr.append(\"world\");\r\n\t\tCHECK_EQUAL(0, rde::strcompare(str.data(), \"Hello wor\"));\r\n\t}\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"amd64.h\"\n#ifdef XV6_KERNEL\n#include \"atomic.hh\"\n#else\n#include <atomic>\n#endif\n\n\/**\n * A seqcount is a synchronization primitive that, in conjunction with\n * some form of mutual exclusion, provides write-free optimistic reads\n * of shared data.\n *\/\ntemplate<typename T = unsigned>\nclass seqcount\n{\n std::atomic<T> seq_;\n\npublic:\n constexpr seqcount() : seq_(0) { }\n\n \/**\n * An RAII object representing a read section protected by a\n * seqcount.\n *\/\n class reader\n {\n seqcount * const sc_;\n T init_;\n\n public:\n constexpr reader(seqcount *sc, T init) : sc_(sc), init_(init) { }\n\n \/**\n * Return true if this read section needs to be retried because of\n * an intervening write section.\n *\/\n bool need_retry() const\n {\n \/\/ The release fence prevents code (specifically, reads) from\n \/\/ sinking below the check.\n std::atomic_thread_fence(std::memory_order_release);\n return sc_->seq_.load(std::memory_order_relaxed) != init_;\n }\n };\n\n \/**\n * Signal the beginning of a read of the shared data protected by\n * this seqcount. This read is opportunistic, so after reading the\n * data, the caller must call #reader::need_retry() on the returned\n * object and, if it returns true, restart the read (including the\n * read_begin()). Note that the reader must assume that any data\n * returned before need_retry() returns false may be garbage (for\n * example, it's not safe to follow pointers without additional\n * protection from something like RCU).\n *\/\n reader read_begin()\n {\n retry:\n \/\/ Acquire order disables code hoisting so that reads in the\n \/\/ caller don't move before our counter snapshot. Furthermore,\n \/\/ this synchronizes with the release store in writer::done such\n \/\/ that, if we observe its write, we will observe all writes\n \/\/ before it.\n auto s = seq_.load(std::memory_order_acquire);\n if (s & 1) {\n nop_pause();\n goto retry;\n }\n return reader(this, s);\n }\n\n \/**\n * An RAII section representing a write section that may conflict\n * with read sections managed by a seqcount.\n *\/\n class writer\n {\n seqcount *sc_;\n T val_;\n\n public:\n constexpr writer(seqcount *sc, T val) : sc_(sc), val_(val) { }\n\n \/**\n * End the write section.\n *\/\n ~writer()\n {\n done();\n }\n\n \/**\n * End the write section.\n *\/\n void done() __attribute__((always_inline))\n {\n if (sc_) {\n \/\/ This is the mirror of write_begin: writes are not allowed\n \/\/ to move after this, but reads are.\n sc_->seq_.store(val_ + 1, std::memory_order_release);\n sc_ = nullptr;\n }\n }\n };\n\n \/**\n * Begin a write section. This alone does not synchronize write\n * sections; the caller is responsible for acquiring some other form\n * of mutual exclusion before this and releasing it after ending the\n * write section.\n *\n * Another thread attempting to start a reads will spin until this\n * write section ends. If another thread is currently in a read\n * section, it will be forced to retry.\n *\/\n writer write_begin()\n {\n \/\/ Writes are not allowed to move before this because they may be\n \/\/ observed by a reader that thinks the value is stable. Reads\n \/\/ are allowed to move before this because they cannot affect the\n \/\/ value observed by readers (and the caller is required to\n \/\/ precede this with a lock acquire, which is a stronger barrier).\n \/\/ Furthermore, because the caller provides mutual exclusion, we\n \/\/ don't have to worry about competing writes, so we don't need an\n \/\/ interlocked increment.\n \/\/\n \/\/ Because of the surrounding synchronization, we use relaxed\n \/\/ ordering for the load and store (the stronger barrier of the\n \/\/ lock will prevent even these from hoisting). To ensure nothing\n \/\/ after the store hoists, we follow it with an acquire fence.\n T val = seq_.load(std::memory_order_relaxed);\n seq_.store(val + 1, std::memory_order_relaxed);\n std::atomic_thread_fence(std::memory_order_acquire);\n return writer(this, val + 1);\n }\n};\n<commit_msg>export count from seqcount::reader<commit_after>#pragma once\n\n#include \"amd64.h\"\n#ifdef XV6_KERNEL\n#include \"atomic.hh\"\n#else\n#include <atomic>\n#endif\n\n\/**\n * A seqcount is a synchronization primitive that, in conjunction with\n * some form of mutual exclusion, provides write-free optimistic reads\n * of shared data.\n *\/\ntemplate<typename T = unsigned>\nclass seqcount\n{\n std::atomic<T> seq_;\n\npublic:\n constexpr seqcount() : seq_(0) { }\n\n \/**\n * An RAII object representing a read section protected by a\n * seqcount.\n *\/\n class reader\n {\n seqcount * const sc_;\n T init_;\n\n public:\n constexpr reader(seqcount *sc, T init) : sc_(sc), init_(init) { }\n\n \/**\n * Return true if this read section needs to be retried because of\n * an intervening write section.\n *\/\n bool need_retry() const\n {\n \/\/ The release fence prevents code (specifically, reads) from\n \/\/ sinking below the check.\n std::atomic_thread_fence(std::memory_order_release);\n return sc_->seq_.load(std::memory_order_relaxed) != init_;\n }\n\n T count() const\n {\n return init_;\n }\n };\n\n \/**\n * Signal the beginning of a read of the shared data protected by\n * this seqcount. This read is opportunistic, so after reading the\n * data, the caller must call #reader::need_retry() on the returned\n * object and, if it returns true, restart the read (including the\n * read_begin()). Note that the reader must assume that any data\n * returned before need_retry() returns false may be garbage (for\n * example, it's not safe to follow pointers without additional\n * protection from something like RCU).\n *\/\n reader read_begin()\n {\n retry:\n \/\/ Acquire order disables code hoisting so that reads in the\n \/\/ caller don't move before our counter snapshot. Furthermore,\n \/\/ this synchronizes with the release store in writer::done such\n \/\/ that, if we observe its write, we will observe all writes\n \/\/ before it.\n auto s = seq_.load(std::memory_order_acquire);\n if (s & 1) {\n nop_pause();\n goto retry;\n }\n return reader(this, s);\n }\n\n \/**\n * An RAII section representing a write section that may conflict\n * with read sections managed by a seqcount.\n *\/\n class writer\n {\n seqcount *sc_;\n T val_;\n\n public:\n constexpr writer(seqcount *sc, T val) : sc_(sc), val_(val) { }\n\n \/**\n * End the write section.\n *\/\n ~writer()\n {\n done();\n }\n\n \/**\n * End the write section.\n *\/\n void done() __attribute__((always_inline))\n {\n if (sc_) {\n \/\/ This is the mirror of write_begin: writes are not allowed\n \/\/ to move after this, but reads are.\n sc_->seq_.store(val_ + 1, std::memory_order_release);\n sc_ = nullptr;\n }\n }\n };\n\n \/**\n * Begin a write section. This alone does not synchronize write\n * sections; the caller is responsible for acquiring some other form\n * of mutual exclusion before this and releasing it after ending the\n * write section.\n *\n * Another thread attempting to start a reads will spin until this\n * write section ends. If another thread is currently in a read\n * section, it will be forced to retry.\n *\/\n writer write_begin()\n {\n \/\/ Writes are not allowed to move before this because they may be\n \/\/ observed by a reader that thinks the value is stable. Reads\n \/\/ are allowed to move before this because they cannot affect the\n \/\/ value observed by readers (and the caller is required to\n \/\/ precede this with a lock acquire, which is a stronger barrier).\n \/\/ Furthermore, because the caller provides mutual exclusion, we\n \/\/ don't have to worry about competing writes, so we don't need an\n \/\/ interlocked increment.\n \/\/\n \/\/ Because of the surrounding synchronization, we use relaxed\n \/\/ ordering for the load and store (the stronger barrier of the\n \/\/ lock will prevent even these from hoisting). To ensure nothing\n \/\/ after the store hoists, we follow it with an acquire fence.\n T val = seq_.load(std::memory_order_relaxed);\n seq_.store(val + 1, std::memory_order_relaxed);\n std::atomic_thread_fence(std::memory_order_acquire);\n return writer(this, val + 1);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ language_bootstrap.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 30\/05\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n#include \"language_bootstrap.h\"\n#include \"Language\/bootstrap.h\"\n#include \"Language\/formatter.h\"\n#include \"Lr\/conflict.h\"\n\nusing namespace std;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace language;\nusing namespace lr;\n\n\/\/ Checks that a given phrase is lexed as gthe specified symbol\nstatic bool test_lex(string phrase, const lexer& lex, int expectedSymbol, const terminal_dictionary& terms) {\n \/\/ Create a lexeme stream\n stringstream source(phrase);\n lexeme_stream* lxs = lex.create_stream_from(source);\n \n \/\/ Get the next lexeme\n lexeme* match;\n (*lxs) >> match;\n \n bool result = true;\n if (match->content().size() != phrase.size()) {\n for (int x=0; x<match->content().size(); x++) {\n cerr << (char)match->content()[x];\n }\n cerr << endl;\n result = false;\n }\n if (match->matched() != expectedSymbol) {\n wcerr << terms.name_for_symbol(match->matched()) << endl;\n result = false;\n }\n \n \/\/ Finished with the stream\n delete match;\n delete lxs;\n \n return result;\n}\n\nvoid test_language_bootstrap::run_tests() {\n \/\/ Create a bootstrap object\n bootstrap bs;\n \n \/\/ Write out the language to test things\n wcerr << formatter::to_string(bs.get_builder(), bs.get_grammar(), bs.get_terminals()) << endl;\n \n \/\/ Verify that the weak symbols have a higher priority than the strong symbols\n report(\"WeakSymbols1\", bs.get_terminal_items().identifier->symbol() > bs.get_terminal_items().language->symbol());\n \n \/\/ Verify that the lexer looks like a DFA\n ndfa* bsDfa = bs.create_dfa();\n\n report(\"DfaIsDfa\", bsDfa->is_dfa());\n report(\"DfaVerifyDfa\", bsDfa->verify_is_dfa());\n report(\"DfaNoOverlap\", bsDfa->verify_no_symbol_overlap());\n \n \/\/ The 'identifier' symbol should share its actions with some of the weak symbols in the language\n const item_container& icIdentifier = bs.get_terminal_items().identifier;\n const item_container& icLanguage = bs.get_terminal_items().language;\n const item_container& icLexer = bs.get_terminal_items().lexer;\n const item_container& icEquals = bs.get_terminal_items().equals;\n \n bool anyIds = false;\n bool anyLanguage = false;\n bool anyLexer = false;\n bool idAndLanguage = false;\n bool idAndLexer = false;\n bool idAndAnything = false;\n bool idAndEquals = false;\n \n for (int stateId = 0; stateId < bsDfa->count_states(); stateId++) {\n typedef ndfa::accept_action_list aal;\n \n const aal& actions = bsDfa->actions_for_state(stateId);\n if (actions.empty()) continue;\n \n bool hasId = false;\n bool hasLanguage = false;\n bool hasLexer = false;\n bool hasEquals = false;\n \n for (aal::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {\n if ((*nextAction)->symbol() == icIdentifier->symbol()) hasId = true;\n if ((*nextAction)->symbol() == icLanguage->symbol()) hasLanguage = true;\n if ((*nextAction)->symbol() == icLexer->symbol()) hasLexer = true;\n if ((*nextAction)->symbol() == icEquals->symbol()) hasEquals = true;\n }\n \n if (hasLanguage) {\n anyLanguage = true;\n if (!idAndLanguage) idAndLanguage = hasId;\n }\n \n if (hasLexer) {\n anyLexer = true;\n if (!idAndLexer) idAndLexer = hasId;\n }\n \n if (hasEquals) {\n if (!idAndEquals) idAndEquals = hasId;\n }\n \n if (hasId) {\n anyIds = true;\n if (actions.size() > 1) {\n idAndAnything = true;\n }\n }\n }\n \n report(\"AnyIdentifiers\", anyIds);\n report(\"AnyLanguage\", anyLanguage);\n report(\"AnyLexer\", anyLexer);\n report(\"IdentifierAndAnything\", idAndAnything);\n report(\"IdentifierAndLanguage\", idAndLanguage);\n report(\"IdentifierAndLexer\", idAndLexer);\n report(\"IdentifierAndNotEquals\", !idAndEquals);\n \n \/\/ Finished looking at the DFA\n delete bsDfa;\n \n \/\/ Test that the lexer can match some particular symbols\n report(\"MatchIdentifier1\", test_lex(\"fdsu\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier2\", test_lex(\"some-identifier\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier3\", test_lex(\"id128\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier4\", test_lex(\"identifier\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchNonterminal1\", test_lex(\"<nonterminal>\", bs.get_lexer(), bs.get_terminal_items().nonterminal->symbol(), bs.get_terminals()));\n report(\"MatchRegex1\", test_lex(\"\/regex\/\", bs.get_lexer(), bs.get_terminal_items().regex->symbol(), bs.get_terminals()));\n report(\"MatchString1\", test_lex(\"\\\"string\\\"\", bs.get_lexer(), bs.get_terminal_items().string->symbol(), bs.get_terminals()));\n report(\"MatchCharacter1\", test_lex(\"'c'\", bs.get_lexer(), bs.get_terminal_items().character->symbol(), bs.get_terminals()));\n \n report(\"MatchLanguage\", test_lex(\"language\", bs.get_lexer(), bs.get_terminal_items().language->symbol(), bs.get_terminals()));\n report(\"MatchGrammar\", test_lex(\"grammar\", bs.get_lexer(), bs.get_terminal_items().grammar->symbol(), bs.get_terminals()));\n report(\"MatchLexer\", test_lex(\"lexer\", bs.get_lexer(), bs.get_terminal_items().lexer->symbol(), bs.get_terminals()));\n report(\"MatchLexerSymbols\", test_lex(\"lexer-symbols\", bs.get_lexer(), bs.get_terminal_items().lexersymbols->symbol(), bs.get_terminals()));\n report(\"MatchWeakLexer\", test_lex(\"weaklexer\", bs.get_lexer(), bs.get_terminal_items().weaklexer->symbol(), bs.get_terminals()));\n report(\"MatchIgnore\", test_lex(\"ignore\", bs.get_lexer(), bs.get_terminal_items().ignore->symbol(), bs.get_terminals()));\n report(\"MatchKeywords\", test_lex(\"keywords\", bs.get_lexer(), bs.get_terminal_items().keywords->symbol(), bs.get_terminals()));\n report(\"MatchWhitespace\", test_lex(\" \", bs.get_lexer(), bs.get_terminal_items().whitespace->symbol(), bs.get_terminals()));\n report(\"MatchNewline\", test_lex(\"\\n\", bs.get_lexer(), bs.get_terminal_items().newline->symbol(), bs.get_terminals()));\n report(\"MatchComment\", test_lex(\"\/\/ Comment\", bs.get_lexer(), bs.get_terminal_items().comment->symbol(), bs.get_terminals()));\n \n \/\/ Get the conflicts in the grammar\n conflict_list conflicts;\n conflict::find_conflicts(bs.get_builder(), conflicts);\n \n report(\"NoConflicts\", conflicts.size() == 0);\n \n \/\/ Write out the conflicts to the standard I\/O if there were any\n if (conflicts.size() > 0) {\n for (conflict_list::const_iterator it = conflicts.begin(); it != conflicts.end(); it++) {\n wcerr << endl << L\"===\" << endl << formatter::to_string(**it, bs.get_grammar(), bs.get_terminals()) << endl << L\"===\" << endl;\n }\n }\n}\n<commit_msg>Added tests for the quoted form of the character terminal<commit_after>\/\/\n\/\/ language_bootstrap.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 30\/05\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include <string>\n#include <sstream>\n#include <iostream>\n\n#include \"language_bootstrap.h\"\n#include \"Language\/bootstrap.h\"\n#include \"Language\/formatter.h\"\n#include \"Lr\/conflict.h\"\n\nusing namespace std;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace language;\nusing namespace lr;\n\n\/\/ Checks that a given phrase is lexed as gthe specified symbol\nstatic bool test_lex(string phrase, const lexer& lex, int expectedSymbol, const terminal_dictionary& terms) {\n \/\/ Create a lexeme stream\n stringstream source(phrase);\n lexeme_stream* lxs = lex.create_stream_from(source);\n \n \/\/ Get the next lexeme\n lexeme* match;\n (*lxs) >> match;\n \n bool result = true;\n if (match->content().size() != phrase.size()) {\n for (int x=0; x<match->content().size(); x++) {\n cerr << (char)match->content()[x];\n }\n cerr << endl;\n result = false;\n }\n if (match->matched() != expectedSymbol) {\n wcerr << terms.name_for_symbol(match->matched()) << endl;\n result = false;\n }\n \n \/\/ Finished with the stream\n delete match;\n delete lxs;\n \n return result;\n}\n\nvoid test_language_bootstrap::run_tests() {\n \/\/ Create a bootstrap object\n bootstrap bs;\n \n \/\/ Write out the language to test things\n wcerr << formatter::to_string(bs.get_builder(), bs.get_grammar(), bs.get_terminals()) << endl;\n \n \/\/ Verify that the weak symbols have a higher priority than the strong symbols\n report(\"WeakSymbols1\", bs.get_terminal_items().identifier->symbol() > bs.get_terminal_items().language->symbol());\n \n \/\/ Verify that the lexer looks like a DFA\n ndfa* bsDfa = bs.create_dfa();\n\n report(\"DfaIsDfa\", bsDfa->is_dfa());\n report(\"DfaVerifyDfa\", bsDfa->verify_is_dfa());\n report(\"DfaNoOverlap\", bsDfa->verify_no_symbol_overlap());\n \n \/\/ The 'identifier' symbol should share its actions with some of the weak symbols in the language\n const item_container& icIdentifier = bs.get_terminal_items().identifier;\n const item_container& icLanguage = bs.get_terminal_items().language;\n const item_container& icLexer = bs.get_terminal_items().lexer;\n const item_container& icEquals = bs.get_terminal_items().equals;\n \n bool anyIds = false;\n bool anyLanguage = false;\n bool anyLexer = false;\n bool idAndLanguage = false;\n bool idAndLexer = false;\n bool idAndAnything = false;\n bool idAndEquals = false;\n \n for (int stateId = 0; stateId < bsDfa->count_states(); stateId++) {\n typedef ndfa::accept_action_list aal;\n \n const aal& actions = bsDfa->actions_for_state(stateId);\n if (actions.empty()) continue;\n \n bool hasId = false;\n bool hasLanguage = false;\n bool hasLexer = false;\n bool hasEquals = false;\n \n for (aal::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {\n if ((*nextAction)->symbol() == icIdentifier->symbol()) hasId = true;\n if ((*nextAction)->symbol() == icLanguage->symbol()) hasLanguage = true;\n if ((*nextAction)->symbol() == icLexer->symbol()) hasLexer = true;\n if ((*nextAction)->symbol() == icEquals->symbol()) hasEquals = true;\n }\n \n if (hasLanguage) {\n anyLanguage = true;\n if (!idAndLanguage) idAndLanguage = hasId;\n }\n \n if (hasLexer) {\n anyLexer = true;\n if (!idAndLexer) idAndLexer = hasId;\n }\n \n if (hasEquals) {\n if (!idAndEquals) idAndEquals = hasId;\n }\n \n if (hasId) {\n anyIds = true;\n if (actions.size() > 1) {\n idAndAnything = true;\n }\n }\n }\n \n report(\"AnyIdentifiers\", anyIds);\n report(\"AnyLanguage\", anyLanguage);\n report(\"AnyLexer\", anyLexer);\n report(\"IdentifierAndAnything\", idAndAnything);\n report(\"IdentifierAndLanguage\", idAndLanguage);\n report(\"IdentifierAndLexer\", idAndLexer);\n report(\"IdentifierAndNotEquals\", !idAndEquals);\n \n \/\/ Finished looking at the DFA\n delete bsDfa;\n \n \/\/ Test that the lexer can match some particular symbols\n report(\"MatchIdentifier1\", test_lex(\"fdsu\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier2\", test_lex(\"some-identifier\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier3\", test_lex(\"id128\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchIdentifier4\", test_lex(\"identifier\", bs.get_lexer(), bs.get_terminal_items().identifier->symbol(), bs.get_terminals()));\n report(\"MatchNonterminal1\", test_lex(\"<nonterminal>\", bs.get_lexer(), bs.get_terminal_items().nonterminal->symbol(), bs.get_terminals()));\n report(\"MatchRegex1\", test_lex(\"\/regex\/\", bs.get_lexer(), bs.get_terminal_items().regex->symbol(), bs.get_terminals()));\n report(\"MatchString1\", test_lex(\"\\\"string\\\"\", bs.get_lexer(), bs.get_terminal_items().string->symbol(), bs.get_terminals()));\n report(\"MatchCharacter1\", test_lex(\"'c'\", bs.get_lexer(), bs.get_terminal_items().character->symbol(), bs.get_terminals()));\n report(\"MatchCharacter2\", test_lex(\"'\\n'\", bs.get_lexer(), bs.get_terminal_items().character->symbol(), bs.get_terminals()));\n \n report(\"MatchLanguage\", test_lex(\"language\", bs.get_lexer(), bs.get_terminal_items().language->symbol(), bs.get_terminals()));\n report(\"MatchGrammar\", test_lex(\"grammar\", bs.get_lexer(), bs.get_terminal_items().grammar->symbol(), bs.get_terminals()));\n report(\"MatchLexer\", test_lex(\"lexer\", bs.get_lexer(), bs.get_terminal_items().lexer->symbol(), bs.get_terminals()));\n report(\"MatchLexerSymbols\", test_lex(\"lexer-symbols\", bs.get_lexer(), bs.get_terminal_items().lexersymbols->symbol(), bs.get_terminals()));\n report(\"MatchWeakLexer\", test_lex(\"weaklexer\", bs.get_lexer(), bs.get_terminal_items().weaklexer->symbol(), bs.get_terminals()));\n report(\"MatchIgnore\", test_lex(\"ignore\", bs.get_lexer(), bs.get_terminal_items().ignore->symbol(), bs.get_terminals()));\n report(\"MatchKeywords\", test_lex(\"keywords\", bs.get_lexer(), bs.get_terminal_items().keywords->symbol(), bs.get_terminals()));\n report(\"MatchWhitespace\", test_lex(\" \", bs.get_lexer(), bs.get_terminal_items().whitespace->symbol(), bs.get_terminals()));\n report(\"MatchNewline\", test_lex(\"\\n\", bs.get_lexer(), bs.get_terminal_items().newline->symbol(), bs.get_terminals()));\n report(\"MatchComment\", test_lex(\"\/\/ Comment\", bs.get_lexer(), bs.get_terminal_items().comment->symbol(), bs.get_terminals()));\n \n \/\/ Get the conflicts in the grammar\n conflict_list conflicts;\n conflict::find_conflicts(bs.get_builder(), conflicts);\n \n report(\"NoConflicts\", conflicts.size() == 0);\n \n \/\/ Write out the conflicts to the standard I\/O if there were any\n if (conflicts.size() > 0) {\n for (conflict_list::const_iterator it = conflicts.begin(); it != conflicts.end(); it++) {\n wcerr << endl << L\"===\" << endl << formatter::to_string(**it, bs.get_grammar(), bs.get_terminals()) << endl << L\"===\" << endl;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"attributeconstraints.h\"\n\n#include <model\/devisertypes.h>\n\n#include <util.h>\n\nAttributeConstraints::AttributeConstraints(DeviserValidator* validator)\n : DeviserConstraint(validator)\n , mKnownElementTypes()\n , mKnownTypes(Util::getKnownTypes())\n{\n\n mKnownElementTypes << \"enum\"\n << \"array\"\n << \"element\"\n << \"lo_element\"\n << \"inline_lo_element\"\n << \"vector\"\n ;\n\n}\n\nint AttributeConstraints::analyzePackage(DeviserPackage *package)\n{\n if (package == NULL) return 0;\n\n int count = 0;\n\n foreach (DeviserVersion* version, package->getVersions())\n {\n foreach (DeviserClass* element, version->getElements())\n {\n if (element->getName().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"There is an unnamed class in version '\"\n << version->toString()\n << \"', this is a required attribute\");\n ++count;\n }\n\n foreach(DeviserAttribute* attribute, element->getAttributes())\n {\n if (checkAttribute(attribute, element->getName()))\n ++count;\n }\n\n foreach (DeviserListOfAttribute* attribute, element->getListOfAttributes()) {\n if (checkAttribute(attribute, element->getName()))\n ++count;\n }\n\n }\n\n foreach (DeviserPlugin* element, version->getPlugins())\n {\n if (element->getExtensionPoint().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"There is a plugin without extensionpoint in version '\"\n << version->toString()\n << \"', this is a required attribute\");\n ++count;\n }\n\n foreach(DeviserAttribute* attribute, element->getAttributes())\n {\n if (checkAttribute(attribute, element->getExtensionPoint()))\n ++count;\n }\n }\n }\n\n return count;\n\n}\n\nbool AttributeConstraints::checkAttribute(DeviserAttribute *attribute,\n const QString& name)\n{\n bool result = false;\n\n if (attribute->getName().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The element '\"\n << name\n << \"' has an unnamed attribute. This is a required attribute.\");\n\n result = true;\n }\n else if (attribute->getName() == \"level\" || attribute->getName() == \"version\")\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The attribute '\"\n << attribute->getName()\n << \"' of element '\"\n << name\n << \"' uses the name 'level' or 'version' which will cause compilation issues.\");\n\n }\n\n if (attribute->getType() == \"SIdRef\" && attribute->getElement().isEmpty())\n {\n\n ADD_MESSAGE(\"The attribute '\"\n << attribute->getName()\n << \"' of element '\"\n << name\n << \"' is of type SIdRef, but has no element set. This is needed for validation purposes.\");\n\n return true;\n }\n else if (attribute->getType() == \"SIdRef\")\n return false;\n\n if (attribute->getType().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"The attribute '\"\n << attribute->getName()\n << \"' has no type defined, this is a required attribute.\");\n return true;\n }\n\n if (mKnownElementTypes.contains(attribute->getType().toLower(), Qt::CaseInsensitive))\n {\n if (attribute->getElement().isEmpty())\n {\n\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"' but has no element defined, this is a required attribute.\");\n result = true;\n\n }\n }\n else if (!attribute->getElement().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_WARNING,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"' but has an element '\"\n << attribute->getElement()\n << \"' defined, this attribute will not be used.\");\n result = true;\n }\n\n if (!mKnownTypes.contains(attribute->getType().toLower(), Qt::CaseInsensitive))\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_WARNING,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"', this type is not known by DEVISER and will have to be changed manually in the generated code.\");\n result = true;\n }\n\n return result;\n}\n\n<commit_msg>restrict attribute names to avoid any SBase clashes<commit_after>#include \"attributeconstraints.h\"\n\n#include <model\/devisertypes.h>\n\n#include <util.h>\n\nAttributeConstraints::AttributeConstraints(DeviserValidator* validator)\n : DeviserConstraint(validator)\n , mKnownElementTypes()\n , mKnownTypes(Util::getKnownTypes())\n{\n\n mKnownElementTypes << \"enum\"\n << \"array\"\n << \"element\"\n << \"lo_element\"\n << \"inline_lo_element\"\n << \"vector\"\n ;\n\n}\n\nint AttributeConstraints::analyzePackage(DeviserPackage *package)\n{\n if (package == NULL) return 0;\n\n int count = 0;\n\n foreach (DeviserVersion* version, package->getVersions())\n {\n foreach (DeviserClass* element, version->getElements())\n {\n if (element->getName().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"There is an unnamed class in version '\"\n << version->toString()\n << \"', this is a required attribute\");\n ++count;\n }\n\n foreach(DeviserAttribute* attribute, element->getAttributes())\n {\n if (checkAttribute(attribute, element->getName()))\n ++count;\n }\n\n foreach (DeviserListOfAttribute* attribute, element->getListOfAttributes()) {\n if (checkAttribute(attribute, element->getName()))\n ++count;\n }\n\n }\n\n foreach (DeviserPlugin* element, version->getPlugins())\n {\n if (element->getExtensionPoint().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"There is a plugin without extensionpoint in version '\"\n << version->toString()\n << \"', this is a required attribute\");\n ++count;\n }\n\n foreach(DeviserAttribute* attribute, element->getAttributes())\n {\n if (checkAttribute(attribute, element->getExtensionPoint()))\n ++count;\n }\n }\n }\n\n return count;\n\n}\n\nbool AttributeConstraints::checkAttribute(DeviserAttribute *attribute,\n const QString& name)\n{\n bool result = false;\n QString lowerName = attribute->getName().toLower();\n\n if (attribute->getName().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The element '\"\n << name\n << \"' has an unnamed attribute. This is a required attribute.\");\n\n result = true;\n }\n else if (lowerName == \"level\" || lowerName == \"version\" \n || lowerName == \"packageversion\" || lowerName == \"metaid\"\n || lowerName == \"notes\" || lowerName == \"annotation\"\n || lowerName == \"sboterm\" || lowerName == \"line\"\n || lowerName == \"column\" || lowerName == \"model\"\n || lowerName == \"modelhistory\" || lowerName == \"cvterms\"\n || lowerName == \"attribute\" || lowerName == \"uri\" || lowerName == \"prefix\")\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The attribute '\"\n << attribute->getName()\n << \"' of element '\"\n << name\n << \"' uses a restricted name which will cause compilation issues.\");\n\n }\n\n if (attribute->getType() == \"SIdRef\" && attribute->getElement().isEmpty())\n {\n\n ADD_MESSAGE(\"The attribute '\"\n << attribute->getName()\n << \"' of element '\"\n << name\n << \"' is of type SIdRef, but has no element set. This is needed for validation purposes.\");\n\n return true;\n }\n else if (attribute->getType() == \"SIdRef\")\n return false;\n\n if (attribute->getType().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"The attribute '\"\n << attribute->getName()\n << \"' has no type defined, this is a required attribute.\");\n return true;\n }\n\n if (mKnownElementTypes.contains(attribute->getType().toLower(), Qt::CaseInsensitive))\n {\n if (attribute->getElement().isEmpty())\n {\n\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"' but has no element defined, this is a required attribute.\");\n result = true;\n\n }\n }\n else if (!attribute->getElement().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_WARNING,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"' but has an element '\"\n << attribute->getElement()\n << \"' defined, this attribute will not be used.\");\n result = true;\n }\n\n if (!mKnownTypes.contains(attribute->getType().toLower(), Qt::CaseInsensitive))\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_WARNING,\n \"The attribute '\"\n << attribute->getName()\n << \"' is of type '\"\n << attribute->getType()\n << \"', this type is not known by DEVISER and will have to be changed manually in the generated code.\");\n result = true;\n }\n\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef UNIT_CONFIG_HPP_\n#define UNIT_CONFIG_HPP_\n\nnamespace unit_config {\n\nconst float DT = 0.001;\n\nconst double PI = 3.14159265358979323846;\n\n\/\/ Maximum angular position in the roll and pitch axes (rad)\nconst float MAX_PITCH_ROLL_POS = 30.0 * PI \/ 180.0;\n\n\/\/ Maximum angular velocity in the roll and pitch axes (rad\/s)\nconst float MAX_PITCH_ROLL_VEL = 100.0 * PI \/ 180.0;\n\n\/\/ Maximum angular acceleration (rad\/s^2)\nconst float MAX_PITCH_ROLL_ACC = 4.0; \/\/ TODO: calculate properly\n\n\/\/ Sensor offsets\nconst float GYR_X_OFFSET = -0.033;\nconst float GYR_Y_OFFSET = 0.011;\nconst float GYR_Z_OFFSET = 0.023;\nconst float ACC_X_OFFSET = 0.026;\nconst float ACC_Y_OFFSET = -0.005;\nconst float ACC_Z_OFFSET = 0.025;\n\n\/\/ Initial angular position controller gains\nconst float ANGPOS_X_KP = 1.0;\nconst float ANGPOS_X_KI = 0.0;\nconst float ANGPOS_X_KD = 0.0;\nconst float ANGPOS_Y_KP = 1.0;\nconst float ANGPOS_Y_KI = 0.0;\nconst float ANGPOS_Y_KD = 0.0;\nconst float ANGPOS_Z_KP = 1.0;\nconst float ANGPOS_Z_KI = 0.0;\nconst float ANGPOS_Z_KD = 0.0;\n\n\/\/ Initial angular velocity controller gains\nconst float ANGVEL_X_KP = 1.0;\nconst float ANGVEL_X_KI = 0.0;\nconst float ANGVEL_X_KD = 0.0;\nconst float ANGVEL_Y_KP = 1.0;\nconst float ANGVEL_Y_KI = 0.0;\nconst float ANGVEL_Y_KD = 0.0;\nconst float ANGVEL_Z_KP = 1.0;\nconst float ANGVEL_Z_KI = 0.0;\nconst float ANGVEL_Z_KD = 0.0;\n\n\/\/ Initial angular acceleration controller gains\nconst float ANGACC_X_KP = 1.0;\nconst float ANGACC_X_KI = 0.0;\nconst float ANGACC_X_KD = 0.0;\nconst float ANGACC_Y_KP = 1.0;\nconst float ANGACC_Y_KI = 0.0;\nconst float ANGACC_Y_KD = 0.0;\nconst float ANGACC_Z_KP = 1.0;\nconst float ANGACC_Z_KI = 0.0;\nconst float ANGACC_Z_KD = 0.0;\n\n\/\/ Pin configuration\nconst uint8_t PIN_MAIN_CH = 1; \/\/ PA5\nconst uint8_t PIN_DROGUE_CH = 2; \/\/ PC4\nconst uint8_t PIN_EXT_TEMP_THERM_CH = 1; \/\/ PC1\n\n}\n\n#endif \/\/ UNIT_CONFIG_HPP_\n<commit_msg>Add payload pin configs to hera.<commit_after>#ifndef UNIT_CONFIG_HPP_\n#define UNIT_CONFIG_HPP_\n\nnamespace unit_config {\n\nconst float DT = 0.001;\n\nconst double PI = 3.14159265358979323846;\n\n\/\/ Maximum angular position in the roll and pitch axes (rad)\nconst float MAX_PITCH_ROLL_POS = 30.0 * PI \/ 180.0;\n\n\/\/ Maximum angular velocity in the roll and pitch axes (rad\/s)\nconst float MAX_PITCH_ROLL_VEL = 100.0 * PI \/ 180.0;\n\n\/\/ Maximum angular acceleration (rad\/s^2)\nconst float MAX_PITCH_ROLL_ACC = 4.0; \/\/ TODO: calculate properly\n\n\/\/ Sensor offsets\nconst float GYR_X_OFFSET = -0.033;\nconst float GYR_Y_OFFSET = 0.011;\nconst float GYR_Z_OFFSET = 0.023;\nconst float ACC_X_OFFSET = 0.026;\nconst float ACC_Y_OFFSET = -0.005;\nconst float ACC_Z_OFFSET = 0.025;\n\n\/\/ Initial angular position controller gains\nconst float ANGPOS_X_KP = 1.0;\nconst float ANGPOS_X_KI = 0.0;\nconst float ANGPOS_X_KD = 0.0;\nconst float ANGPOS_Y_KP = 1.0;\nconst float ANGPOS_Y_KI = 0.0;\nconst float ANGPOS_Y_KD = 0.0;\nconst float ANGPOS_Z_KP = 1.0;\nconst float ANGPOS_Z_KI = 0.0;\nconst float ANGPOS_Z_KD = 0.0;\n\n\/\/ Initial angular velocity controller gains\nconst float ANGVEL_X_KP = 1.0;\nconst float ANGVEL_X_KI = 0.0;\nconst float ANGVEL_X_KD = 0.0;\nconst float ANGVEL_Y_KP = 1.0;\nconst float ANGVEL_Y_KI = 0.0;\nconst float ANGVEL_Y_KD = 0.0;\nconst float ANGVEL_Z_KP = 1.0;\nconst float ANGVEL_Z_KI = 0.0;\nconst float ANGVEL_Z_KD = 0.0;\n\n\/\/ Initial angular acceleration controller gains\nconst float ANGACC_X_KP = 1.0;\nconst float ANGACC_X_KI = 0.0;\nconst float ANGACC_X_KD = 0.0;\nconst float ANGACC_Y_KP = 1.0;\nconst float ANGACC_Y_KI = 0.0;\nconst float ANGACC_Y_KD = 0.0;\nconst float ANGACC_Z_KP = 1.0;\nconst float ANGACC_Z_KI = 0.0;\nconst float ANGACC_Z_KD = 0.0;\n\n\/\/ PWM pin config\nconst uint8_t PIN_FIN_SWITCH_CH = 5; \/\/ PB7\nconst uint8_t PIN_MOTOR_CH = 7; \/\/ PB9\n\n\/\/ ADC pin config\nconst uint8_t PIN_ESC_TEMP_THERM_CH = 0; \/\/ PC0\n\n\/\/ Digital pin config\nconst uint8_t PIN_SHUTTLE2_CH = 0; \/\/ PA4\nconst uint8_t PIN_DROGUE_CH = 1; \/\/ PA5\nconst uint8_t PIN_SHUTTLE1_CH = 3; \/\/ PC5\n\n\/\/ Unused config\n\/\/ TODO(yoos): This is a hack to make rocket and payload build.\nconst uint8_t PIN_MAIN_CH = 255;\n\n}\n\n#endif \/\/ UNIT_CONFIG_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <cmath>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <signal.h>\n#include <unistd.h>\n#include <assert.h>\n#include <math.h>\n#include <poll.h>\n#include <sys\/mman.h>\n\n#include \"common\/util.h\"\n#include \"common\/swaglog.h\"\n#include \"common\/visionimg.h\"\n#include \"common\/utilpp.h\"\n#include \"ui.hpp\"\n#include \"paint.hpp\"\n\nextern volatile sig_atomic_t do_exit;\n\nint write_param_float(float param, const char* param_name, bool persistent_param) {\n char s[16];\n int size = snprintf(s, sizeof(s), \"%f\", param);\n return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s));\n}\n\nvoid ui_init(UIState *s) {\n s->sm = new SubMaster({\"modelV2\", \"controlsState\", \"uiLayoutState\", \"liveCalibration\", \"radarState\", \"thermal\", \"frame\",\n \"health\", \"carParams\", \"ubloxGnss\", \"driverState\", \"dMonitoringState\", \"sensorEvents\"});\n\n s->started = false;\n s->status = STATUS_OFFROAD;\n s->scene.satelliteCount = -1;\n read_param(&s->is_metric, \"IsMetric\");\n\n s->fb = framebuffer_init(\"ui\", 0, true, &s->fb_w, &s->fb_h);\n assert(s->fb);\n\n ui_nvg_init(s);\n}\n\nstatic void ui_init_vision(UIState *s) {\n \/\/ Invisible until we receive a calibration message.\n s->scene.world_objects_visible = false;\n\n for (int i = 0; i < UI_BUF_COUNT; i++) {\n if (s->khr[i] != 0) {\n visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]);\n glDeleteTextures(1, &s->frame_texs[i]);\n }\n\n VisionImg img = {\n .fd = s->stream.bufs[i].fd,\n .format = VISIONIMG_FORMAT_RGB24,\n .width = s->stream.bufs_info.width,\n .height = s->stream.bufs_info.height,\n .stride = s->stream.bufs_info.stride,\n .bpp = 3,\n .size = s->stream.bufs_info.buf_len,\n };\n#ifndef QCOM\n s->priv_hnds[i] = s->stream.bufs[i].addr;\n#endif\n s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]);\n\n glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n \/\/ BGR\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);\n }\n assert(glGetError() == GL_NO_ERROR);\n}\n\nvoid ui_update_vision(UIState *s) {\n\n if (!s->vision_connected && s->started) {\n const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK;\n int err = visionstream_init(&s->stream, type, true, nullptr);\n if (err == 0) {\n ui_init_vision(s);\n s->vision_connected = true;\n }\n }\n\n if (s->vision_connected) {\n if (!s->started) goto destroy;\n\n \/\/ poll for a new frame\n struct pollfd fds[1] = {{\n .fd = s->stream.ipc_fd,\n .events = POLLOUT,\n }};\n int ret = poll(fds, 1, 100);\n if (ret > 0) {\n if (!visionstream_get(&s->stream, nullptr)) goto destroy;\n }\n }\n\n return;\n\ndestroy:\n visionstream_destroy(&s->stream);\n s->vision_connected = false;\n}\n\nvoid update_sockets(UIState *s) {\n\n UIScene &scene = s->scene;\n SubMaster &sm = *(s->sm);\n\n if (sm.update(0) == 0){\n return;\n }\n\n if (s->started && sm.updated(\"controlsState\")) {\n auto event = sm[\"controlsState\"];\n scene.controls_state = event.getControlsState();\n\n \/\/ TODO: the alert stuff shouldn't be handled here\n auto alert_sound = scene.controls_state.getAlertSound();\n if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) {\n if (alert_sound == AudibleAlert::NONE) {\n s->sound->stop();\n } else {\n s->sound->play(alert_sound);\n }\n }\n scene.alert_text1 = scene.controls_state.getAlertText1();\n scene.alert_text2 = scene.controls_state.getAlertText2();\n scene.alert_size = scene.controls_state.getAlertSize();\n scene.alert_type = scene.controls_state.getAlertType();\n auto alertStatus = scene.controls_state.getAlertStatus();\n if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) {\n s->status = STATUS_WARNING;\n } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) {\n s->status = STATUS_ALERT;\n } else {\n s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;\n }\n\n float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate();\n if (alert_blinkingrate > 0.) {\n if (s->alert_blinked) {\n if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) {\n s->alert_blinking_alpha += (0.05*alert_blinkingrate);\n } else {\n s->alert_blinked = false;\n }\n } else {\n if (s->alert_blinking_alpha > 0.25) {\n s->alert_blinking_alpha -= (0.05*alert_blinkingrate);\n } else {\n s->alert_blinking_alpha += 0.25;\n s->alert_blinked = true;\n }\n }\n }\n }\n if (sm.updated(\"radarState\")) {\n auto data = sm[\"radarState\"].getRadarState();\n scene.lead_data[0] = data.getLeadOne();\n scene.lead_data[1] = data.getLeadTwo();\n }\n if (sm.updated(\"liveCalibration\")) {\n scene.world_objects_visible = true;\n auto extrinsicl = sm[\"liveCalibration\"].getLiveCalibration().getExtrinsicMatrix();\n for (int i = 0; i < 3 * 4; i++) {\n scene.extrinsic_matrix.v[i] = extrinsicl[i];\n }\n }\n if (sm.updated(\"modelV2\")) {\n scene.model = sm[\"modelV2\"].getModelV2();\n scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE);\n for (int ll_idx = 0; ll_idx < 4; ll_idx++) {\n if (scene.model.getLaneLineProbs().size() > ll_idx) {\n scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx];\n } else {\n scene.lane_line_probs[ll_idx] = 0.0;\n }\n }\n\n for (int re_idx = 0; re_idx < 2; re_idx++) {\n if (scene.model.getRoadEdgeStds().size() > re_idx) {\n scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx];\n } else {\n scene.road_edge_stds[re_idx] = 1.0;\n }\n }\n }\n if (sm.updated(\"uiLayoutState\")) {\n auto data = sm[\"uiLayoutState\"].getUiLayoutState();\n s->active_app = data.getActiveApp();\n scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed();\n }\n if (sm.updated(\"thermal\")) {\n scene.thermal = sm[\"thermal\"].getThermal();\n }\n if (sm.updated(\"ubloxGnss\")) {\n auto data = sm[\"ubloxGnss\"].getUbloxGnss();\n if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) {\n scene.satelliteCount = data.getMeasurementReport().getNumMeas();\n }\n }\n if (sm.updated(\"health\")) {\n auto health = sm[\"health\"].getHealth();\n scene.hwType = health.getHwType();\n s->ignition = health.getIgnitionLine() || health.getIgnitionCan();\n } else if ((s->sm->frame - s->sm->rcv_frame(\"health\")) > 5*UI_FREQ) {\n scene.hwType = cereal::HealthData::HwType::UNKNOWN;\n }\n if (sm.updated(\"carParams\")) {\n s->longitudinal_control = sm[\"carParams\"].getCarParams().getOpenpilotLongitudinalControl();\n }\n if (sm.updated(\"driverState\")) {\n scene.driver_state = sm[\"driverState\"].getDriverState();\n }\n if (sm.updated(\"dMonitoringState\")) {\n scene.dmonitoring_state = sm[\"dMonitoringState\"].getDMonitoringState();\n scene.is_rhd = scene.dmonitoring_state.getIsRHD();\n scene.frontview = scene.dmonitoring_state.getIsPreview();\n } else if ((sm.frame - sm.rcv_frame(\"dMonitoringState\")) > UI_FREQ\/2) {\n scene.frontview = false;\n }\n if (sm.updated(\"sensorEvents\")) {\n for (auto sensor : sm[\"sensorEvents\"].getSensorEvents()) {\n if (sensor.which() == cereal::SensorEventData::LIGHT) {\n s->light_sensor = sensor.getLight();\n } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) {\n s->accel_sensor = sensor.getAcceleration().getV()[2];\n } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {\n s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1];\n }\n }\n }\n\n s->started = scene.thermal.getStarted() || scene.frontview;\n}\n\nvoid ui_update(UIState *s) {\n\n update_sockets(s);\n ui_update_vision(s);\n\n \/\/ Handle onroad\/offroad transition\n if (!s->started && s->status != STATUS_OFFROAD) {\n s->status = STATUS_OFFROAD;\n s->active_app = cereal::UiLayoutState::App::HOME;\n s->scene.uilayout_sidebarcollapsed = false;\n s->sound->stop();\n } else if (s->started && s->status == STATUS_OFFROAD) {\n s->status = STATUS_DISENGAGED;\n s->started_frame = s->sm->frame;\n\n s->active_app = cereal::UiLayoutState::App::NONE;\n s->scene.uilayout_sidebarcollapsed = true;\n s->alert_blinked = false;\n s->alert_blinking_alpha = 1.0;\n s->scene.alert_size = cereal::ControlsState::AlertSize::NONE;\n }\n\n \/\/ Handle controls\/fcamera timeout\n if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 10*UI_FREQ) {\n if ((s->sm)->rcv_frame(\"controlsState\") < s->started_frame) {\n \/\/ car is started, but controlsState hasn't been seen at all\n s->scene.alert_text1 = \"openpilot Unavailable\";\n s->scene.alert_text2 = \"Waiting for controls to start\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::MID;\n } else if (((s->sm)->frame - (s->sm)->rcv_frame(\"controlsState\")) > 5*UI_FREQ) {\n \/\/ car is started, but controls is lagging or died\n if (s->scene.alert_text2 != \"Controls Unresponsive\" &&\n s->scene.alert_text1 != \"Camera Malfunction\") {\n s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT);\n LOGE(\"Controls unresponsive\");\n }\n\n s->scene.alert_text1 = \"TAKE CONTROL IMMEDIATELY\";\n s->scene.alert_text2 = \"Controls Unresponsive\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;\n s->status = STATUS_ALERT;\n }\n\n const uint64_t frame_pkt = (s->sm)->rcv_frame(\"frame\");\n const uint64_t frame_delayed = (s->sm)->frame - frame_pkt;\n const uint64_t since_started = (s->sm)->frame - s->started_frame;\n if ((frame_pkt > s->started_frame || since_started > 15*UI_FREQ) && frame_delayed > 5*UI_FREQ) {\n \/\/ controls is fine, but rear camera is lagging or died\n s->scene.alert_text1 = \"Camera Malfunction\";\n s->scene.alert_text2 = \"Contact Support\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;\n s->status = STATUS_DISENGAGED;\n s->sound->stop();\n }\n }\n\n \/\/ Read params\n if ((s->sm)->frame % (5*UI_FREQ) == 0) {\n read_param(&s->is_metric, \"IsMetric\");\n } else if ((s->sm)->frame % (6*UI_FREQ) == 0) {\n int param_read = read_param(&s->last_athena_ping, \"LastAthenaPingTime\");\n if (param_read != 0) { \/\/ Failed to read param\n s->scene.athenaStatus = NET_DISCONNECTED;\n } else if (nanos_since_boot() - s->last_athena_ping < 70e9) {\n s->scene.athenaStatus = NET_CONNECTED;\n } else {\n s->scene.athenaStatus = NET_ERROR;\n }\n }\n}\n<commit_msg>ui: delete the variable do_exit that is no longer used (#19551)<commit_after>#include <stdio.h>\n#include <cmath>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <signal.h>\n#include <unistd.h>\n#include <assert.h>\n#include <math.h>\n#include <poll.h>\n#include <sys\/mman.h>\n\n#include \"common\/util.h\"\n#include \"common\/swaglog.h\"\n#include \"common\/visionimg.h\"\n#include \"common\/utilpp.h\"\n#include \"ui.hpp\"\n#include \"paint.hpp\"\n\nint write_param_float(float param, const char* param_name, bool persistent_param) {\n char s[16];\n int size = snprintf(s, sizeof(s), \"%f\", param);\n return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s));\n}\n\nvoid ui_init(UIState *s) {\n s->sm = new SubMaster({\"modelV2\", \"controlsState\", \"uiLayoutState\", \"liveCalibration\", \"radarState\", \"thermal\", \"frame\",\n \"health\", \"carParams\", \"ubloxGnss\", \"driverState\", \"dMonitoringState\", \"sensorEvents\"});\n\n s->started = false;\n s->status = STATUS_OFFROAD;\n s->scene.satelliteCount = -1;\n read_param(&s->is_metric, \"IsMetric\");\n\n s->fb = framebuffer_init(\"ui\", 0, true, &s->fb_w, &s->fb_h);\n assert(s->fb);\n\n ui_nvg_init(s);\n}\n\nstatic void ui_init_vision(UIState *s) {\n \/\/ Invisible until we receive a calibration message.\n s->scene.world_objects_visible = false;\n\n for (int i = 0; i < UI_BUF_COUNT; i++) {\n if (s->khr[i] != 0) {\n visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]);\n glDeleteTextures(1, &s->frame_texs[i]);\n }\n\n VisionImg img = {\n .fd = s->stream.bufs[i].fd,\n .format = VISIONIMG_FORMAT_RGB24,\n .width = s->stream.bufs_info.width,\n .height = s->stream.bufs_info.height,\n .stride = s->stream.bufs_info.stride,\n .bpp = 3,\n .size = s->stream.bufs_info.buf_len,\n };\n#ifndef QCOM\n s->priv_hnds[i] = s->stream.bufs[i].addr;\n#endif\n s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]);\n\n glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n \/\/ BGR\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);\n }\n assert(glGetError() == GL_NO_ERROR);\n}\n\nvoid ui_update_vision(UIState *s) {\n\n if (!s->vision_connected && s->started) {\n const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK;\n int err = visionstream_init(&s->stream, type, true, nullptr);\n if (err == 0) {\n ui_init_vision(s);\n s->vision_connected = true;\n }\n }\n\n if (s->vision_connected) {\n if (!s->started) goto destroy;\n\n \/\/ poll for a new frame\n struct pollfd fds[1] = {{\n .fd = s->stream.ipc_fd,\n .events = POLLOUT,\n }};\n int ret = poll(fds, 1, 100);\n if (ret > 0) {\n if (!visionstream_get(&s->stream, nullptr)) goto destroy;\n }\n }\n\n return;\n\ndestroy:\n visionstream_destroy(&s->stream);\n s->vision_connected = false;\n}\n\nvoid update_sockets(UIState *s) {\n\n UIScene &scene = s->scene;\n SubMaster &sm = *(s->sm);\n\n if (sm.update(0) == 0){\n return;\n }\n\n if (s->started && sm.updated(\"controlsState\")) {\n auto event = sm[\"controlsState\"];\n scene.controls_state = event.getControlsState();\n\n \/\/ TODO: the alert stuff shouldn't be handled here\n auto alert_sound = scene.controls_state.getAlertSound();\n if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) {\n if (alert_sound == AudibleAlert::NONE) {\n s->sound->stop();\n } else {\n s->sound->play(alert_sound);\n }\n }\n scene.alert_text1 = scene.controls_state.getAlertText1();\n scene.alert_text2 = scene.controls_state.getAlertText2();\n scene.alert_size = scene.controls_state.getAlertSize();\n scene.alert_type = scene.controls_state.getAlertType();\n auto alertStatus = scene.controls_state.getAlertStatus();\n if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) {\n s->status = STATUS_WARNING;\n } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) {\n s->status = STATUS_ALERT;\n } else {\n s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED;\n }\n\n float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate();\n if (alert_blinkingrate > 0.) {\n if (s->alert_blinked) {\n if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) {\n s->alert_blinking_alpha += (0.05*alert_blinkingrate);\n } else {\n s->alert_blinked = false;\n }\n } else {\n if (s->alert_blinking_alpha > 0.25) {\n s->alert_blinking_alpha -= (0.05*alert_blinkingrate);\n } else {\n s->alert_blinking_alpha += 0.25;\n s->alert_blinked = true;\n }\n }\n }\n }\n if (sm.updated(\"radarState\")) {\n auto data = sm[\"radarState\"].getRadarState();\n scene.lead_data[0] = data.getLeadOne();\n scene.lead_data[1] = data.getLeadTwo();\n }\n if (sm.updated(\"liveCalibration\")) {\n scene.world_objects_visible = true;\n auto extrinsicl = sm[\"liveCalibration\"].getLiveCalibration().getExtrinsicMatrix();\n for (int i = 0; i < 3 * 4; i++) {\n scene.extrinsic_matrix.v[i] = extrinsicl[i];\n }\n }\n if (sm.updated(\"modelV2\")) {\n scene.model = sm[\"modelV2\"].getModelV2();\n scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE);\n for (int ll_idx = 0; ll_idx < 4; ll_idx++) {\n if (scene.model.getLaneLineProbs().size() > ll_idx) {\n scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx];\n } else {\n scene.lane_line_probs[ll_idx] = 0.0;\n }\n }\n\n for (int re_idx = 0; re_idx < 2; re_idx++) {\n if (scene.model.getRoadEdgeStds().size() > re_idx) {\n scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx];\n } else {\n scene.road_edge_stds[re_idx] = 1.0;\n }\n }\n }\n if (sm.updated(\"uiLayoutState\")) {\n auto data = sm[\"uiLayoutState\"].getUiLayoutState();\n s->active_app = data.getActiveApp();\n scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed();\n }\n if (sm.updated(\"thermal\")) {\n scene.thermal = sm[\"thermal\"].getThermal();\n }\n if (sm.updated(\"ubloxGnss\")) {\n auto data = sm[\"ubloxGnss\"].getUbloxGnss();\n if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) {\n scene.satelliteCount = data.getMeasurementReport().getNumMeas();\n }\n }\n if (sm.updated(\"health\")) {\n auto health = sm[\"health\"].getHealth();\n scene.hwType = health.getHwType();\n s->ignition = health.getIgnitionLine() || health.getIgnitionCan();\n } else if ((s->sm->frame - s->sm->rcv_frame(\"health\")) > 5*UI_FREQ) {\n scene.hwType = cereal::HealthData::HwType::UNKNOWN;\n }\n if (sm.updated(\"carParams\")) {\n s->longitudinal_control = sm[\"carParams\"].getCarParams().getOpenpilotLongitudinalControl();\n }\n if (sm.updated(\"driverState\")) {\n scene.driver_state = sm[\"driverState\"].getDriverState();\n }\n if (sm.updated(\"dMonitoringState\")) {\n scene.dmonitoring_state = sm[\"dMonitoringState\"].getDMonitoringState();\n scene.is_rhd = scene.dmonitoring_state.getIsRHD();\n scene.frontview = scene.dmonitoring_state.getIsPreview();\n } else if ((sm.frame - sm.rcv_frame(\"dMonitoringState\")) > UI_FREQ\/2) {\n scene.frontview = false;\n }\n if (sm.updated(\"sensorEvents\")) {\n for (auto sensor : sm[\"sensorEvents\"].getSensorEvents()) {\n if (sensor.which() == cereal::SensorEventData::LIGHT) {\n s->light_sensor = sensor.getLight();\n } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) {\n s->accel_sensor = sensor.getAcceleration().getV()[2];\n } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) {\n s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1];\n }\n }\n }\n\n s->started = scene.thermal.getStarted() || scene.frontview;\n}\n\nvoid ui_update(UIState *s) {\n\n update_sockets(s);\n ui_update_vision(s);\n\n \/\/ Handle onroad\/offroad transition\n if (!s->started && s->status != STATUS_OFFROAD) {\n s->status = STATUS_OFFROAD;\n s->active_app = cereal::UiLayoutState::App::HOME;\n s->scene.uilayout_sidebarcollapsed = false;\n s->sound->stop();\n } else if (s->started && s->status == STATUS_OFFROAD) {\n s->status = STATUS_DISENGAGED;\n s->started_frame = s->sm->frame;\n\n s->active_app = cereal::UiLayoutState::App::NONE;\n s->scene.uilayout_sidebarcollapsed = true;\n s->alert_blinked = false;\n s->alert_blinking_alpha = 1.0;\n s->scene.alert_size = cereal::ControlsState::AlertSize::NONE;\n }\n\n \/\/ Handle controls\/fcamera timeout\n if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 10*UI_FREQ) {\n if ((s->sm)->rcv_frame(\"controlsState\") < s->started_frame) {\n \/\/ car is started, but controlsState hasn't been seen at all\n s->scene.alert_text1 = \"openpilot Unavailable\";\n s->scene.alert_text2 = \"Waiting for controls to start\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::MID;\n } else if (((s->sm)->frame - (s->sm)->rcv_frame(\"controlsState\")) > 5*UI_FREQ) {\n \/\/ car is started, but controls is lagging or died\n if (s->scene.alert_text2 != \"Controls Unresponsive\" &&\n s->scene.alert_text1 != \"Camera Malfunction\") {\n s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT);\n LOGE(\"Controls unresponsive\");\n }\n\n s->scene.alert_text1 = \"TAKE CONTROL IMMEDIATELY\";\n s->scene.alert_text2 = \"Controls Unresponsive\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;\n s->status = STATUS_ALERT;\n }\n\n const uint64_t frame_pkt = (s->sm)->rcv_frame(\"frame\");\n const uint64_t frame_delayed = (s->sm)->frame - frame_pkt;\n const uint64_t since_started = (s->sm)->frame - s->started_frame;\n if ((frame_pkt > s->started_frame || since_started > 15*UI_FREQ) && frame_delayed > 5*UI_FREQ) {\n \/\/ controls is fine, but rear camera is lagging or died\n s->scene.alert_text1 = \"Camera Malfunction\";\n s->scene.alert_text2 = \"Contact Support\";\n s->scene.alert_size = cereal::ControlsState::AlertSize::FULL;\n s->status = STATUS_DISENGAGED;\n s->sound->stop();\n }\n }\n\n \/\/ Read params\n if ((s->sm)->frame % (5*UI_FREQ) == 0) {\n read_param(&s->is_metric, \"IsMetric\");\n } else if ((s->sm)->frame % (6*UI_FREQ) == 0) {\n int param_read = read_param(&s->last_athena_ping, \"LastAthenaPingTime\");\n if (param_read != 0) { \/\/ Failed to read param\n s->scene.athenaStatus = NET_DISCONNECTED;\n } else if (nanos_since_boot() - s->last_athena_ping < 70e9) {\n s->scene.athenaStatus = NET_CONNECTED;\n } else {\n s->scene.athenaStatus = NET_ERROR;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\tstruct map_entry\n\t{\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\t{\"A\", \"ABC\"}\n\t\t, {\"AG\", \"Ares\"}\n\t\t, {\"AR\", \"Arctic Torrent\"}\n\t\t, {\"AV\", \"Avicora\"}\n\t\t, {\"AX\", \"BitPump\"}\n\t\t, {\"AZ\", \"Azureus\"}\n\t\t, {\"A~\", \"Ares\"}\n\t\t, {\"BB\", \"BitBuddy\"}\n\t\t, {\"BC\", \"BitComet\"}\n\t\t, {\"BF\", \"Bitflu\"}\n\t\t, {\"BG\", \"BTG\"}\n\t\t, {\"BR\", \"BitRocket\"}\n\t\t, {\"BS\", \"BTSlave\"}\n\t\t, {\"BX\", \"BittorrentX\"}\n\t\t, {\"CD\", \"Enhanced CTorrent\"}\n\t\t, {\"CT\", \"CTorrent\"}\n\t\t, {\"DE\", \"Deluge Torrent\"}\n\t\t, {\"EB\", \"EBit\"}\n\t\t, {\"ES\", \"electric sheep\"}\n\t\t, {\"HL\", \"Halite\"}\n\t\t, {\"HN\", \"Hydranode\"}\n\t\t, {\"KT\", \"KTorrent\"}\n\t\t, {\"LK\", \"Linkage\"}\n\t\t, {\"LP\", \"lphant\"}\n\t\t, {\"LT\", \"libtorrent\"}\n\t\t, {\"M\", \"Mainline\"}\n\t\t, {\"ML\", \"MLDonkey\"}\n\t\t, {\"MO\", \"Mono Torrent\"}\n\t\t, {\"MP\", \"MooPolice\"}\n\t\t, {\"MR\", \"Miro\"}\n\t\t, {\"MT\", \"Moonlight Torrent\"}\n\t\t, {\"O\", \"Osprey Permaseed\"}\n\t\t, {\"PD\", \"Pando\"}\n\t\t, {\"Q\", \"BTQueue\"}\n\t\t, {\"QT\", \"Qt 4\"}\n\t\t, {\"R\", \"Tribler\"}\n\t\t, {\"S\", \"Shadow\"}\n\t\t, {\"SB\", \"Swiftbit\"}\n\t\t, {\"SN\", \"ShareNet\"}\n\t\t, {\"SS\", \"SwarmScope\"}\n\t\t, {\"ST\", \"SymTorrent\"}\n\t\t, {\"SZ\", \"Shareaza\"}\n\t\t, {\"S~\", \"Shareaza (beta)\"}\n\t\t, {\"T\", \"BitTornado\"}\n\t\t, {\"TN\", \"Torrent.NET\"}\n\t\t, {\"TR\", \"Transmission\"}\n\t\t, {\"TS\", \"TorrentStorm\"}\n\t\t, {\"TT\", \"TuoTu\"}\n\t\t, {\"U\", \"UPnP\"}\n\t\t, {\"UL\", \"uLeecher\"}\n\t\t, {\"UT\", \"uTorrent\"}\n\t\t, {\"XL\", \"Xunlei\"}\n\t\t, {\"XT\", \"XanTorrent\"}\n\t\t, {\"XX\", \"Xtorrent\"}\n\t\t, {\"ZT\", \"ZipTorrent\"}\n\t\t, {\"lt\", \"rTorrent\"}\n\t\t, {\"pX\", \"pHoeniX\"}\n\t\t, {\"qB\", \"qBittorrent\"}\n\t\t, {\"st\", \"SharkTorrent\"}\n\t};\n\n\tstruct generic_map_entry\n\t{\n\t\tint offset;\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\t\/\/ non-standard names\n\tgeneric_map_entry generic_mappings[] =\n\t{\n\t\t{0, \"Deadman Walking-\", \"Deadman\"}\n\t\t, {5, \"Azureus\", \"Azureus 2.0.3.2\"}\n\t\t, {0, \"DansClient\", \"XanTorrent\"}\n\t\t, {4, \"btfans\", \"SimpleBT\"}\n\t\t, {0, \"PRC.P---\", \"Bittorrent Plus! II\"}\n\t\t, {0, \"P87.P---\", \"Bittorrent Plus!\"}\n\t\t, {0, \"S587Plus\", \"Bittorrent Plus!\"}\n\t\t, {0, \"martini\", \"Martini Man\"}\n\t\t, {0, \"Plus---\", \"Bittorrent Plus\"}\n\t\t, {0, \"turbobt\", \"TurboBT\"}\n\t\t, {0, \"a00---0\", \"Swarmy\"}\n\t\t, {0, \"a02---0\", \"Swarmy\"}\n\t\t, {0, \"T00---0\", \"Teeweety\"}\n\t\t, {0, \"BTDWV-\", \"Deadman Walking\"}\n\t\t, {2, \"BS\", \"BitSpirit\"}\n\t\t, {0, \"Pando-\", \"Pando\"}\n\t\t, {0, \"LIME\", \"LimeWire\"}\n\t\t, {0, \"btuga\", \"BTugaXP\"}\n\t\t, {0, \"oernu\", \"BTugaXP\"}\n\t\t, {0, \"Mbrst\", \"Burst!\"}\n\t\t, {0, \"PEERAPP\", \"PeerApp\"}\n\t\t, {0, \"Plus\", \"Plus!\"}\n\t\t, {0, \"-Qt-\", \"Qt\"}\n\t\t, {0, \"exbc\", \"BitComet\"}\n\t\t, {0, \"DNA\", \"BitTorrent DNA\"}\n\t\t, {0, \"-G3\", \"G3 Torrent\"}\n\t\t, {0, \"-FG\", \"FlashGet\"}\n\t\t, {0, \"-ML\", \"MLdonkey\"}\n\t\t, {0, \"XBT\", \"XBT\"}\n\t\t, {0, \"OP\", \"Opera\"}\n\t\t, {2, \"RS\", \"Rufus\"}\n\t\t, {0, \"AZ2500BT\", \"BitTyrant\"}\n\t};\n\n\tbool compare_id(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.id[0] < rhs.id[0]\n\t\t\t|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry tmp = {f.name, \"\"};\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, tmp, &compare_id);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(compare_id(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->id))\n\t\t\tidentity << i->name;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tint num_generic_mappings = sizeof(generic_mappings) \/ sizeof(generic_mappings[0]);\n\n\t\tfor (int i = 0; i < num_generic_mappings; ++i)\n\t\t{\n\t\t\tgeneric_map_entry const& e = generic_mappings[i];\n\t\t\tif (find_string(PID + e.offset, e.id)) return e.name;\n\t\t}\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>added LeechCraft to identify client<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\tstruct map_entry\n\t{\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\t{\"A\", \"ABC\"}\n\t\t, {\"AG\", \"Ares\"}\n\t\t, {\"AR\", \"Arctic Torrent\"}\n\t\t, {\"AV\", \"Avicora\"}\n\t\t, {\"AX\", \"BitPump\"}\n\t\t, {\"AZ\", \"Azureus\"}\n\t\t, {\"A~\", \"Ares\"}\n\t\t, {\"BB\", \"BitBuddy\"}\n\t\t, {\"BC\", \"BitComet\"}\n\t\t, {\"BF\", \"Bitflu\"}\n\t\t, {\"BG\", \"BTG\"}\n\t\t, {\"BR\", \"BitRocket\"}\n\t\t, {\"BS\", \"BTSlave\"}\n\t\t, {\"BX\", \"BittorrentX\"}\n\t\t, {\"CD\", \"Enhanced CTorrent\"}\n\t\t, {\"CT\", \"CTorrent\"}\n\t\t, {\"DE\", \"Deluge Torrent\"}\n\t\t, {\"EB\", \"EBit\"}\n\t\t, {\"ES\", \"electric sheep\"}\n\t\t, {\"HL\", \"Halite\"}\n\t\t, {\"HN\", \"Hydranode\"}\n\t\t, {\"KT\", \"KTorrent\"}\n\t\t, {\"LC\", \"LeechCraft\"}\n\t\t, {\"LK\", \"Linkage\"}\n\t\t, {\"LP\", \"lphant\"}\n\t\t, {\"LT\", \"libtorrent\"}\n\t\t, {\"M\", \"Mainline\"}\n\t\t, {\"ML\", \"MLDonkey\"}\n\t\t, {\"MO\", \"Mono Torrent\"}\n\t\t, {\"MP\", \"MooPolice\"}\n\t\t, {\"MR\", \"Miro\"}\n\t\t, {\"MT\", \"Moonlight Torrent\"}\n\t\t, {\"O\", \"Osprey Permaseed\"}\n\t\t, {\"PD\", \"Pando\"}\n\t\t, {\"Q\", \"BTQueue\"}\n\t\t, {\"QT\", \"Qt 4\"}\n\t\t, {\"R\", \"Tribler\"}\n\t\t, {\"S\", \"Shadow\"}\n\t\t, {\"SB\", \"Swiftbit\"}\n\t\t, {\"SN\", \"ShareNet\"}\n\t\t, {\"SS\", \"SwarmScope\"}\n\t\t, {\"ST\", \"SymTorrent\"}\n\t\t, {\"SZ\", \"Shareaza\"}\n\t\t, {\"S~\", \"Shareaza (beta)\"}\n\t\t, {\"T\", \"BitTornado\"}\n\t\t, {\"TN\", \"Torrent.NET\"}\n\t\t, {\"TR\", \"Transmission\"}\n\t\t, {\"TS\", \"TorrentStorm\"}\n\t\t, {\"TT\", \"TuoTu\"}\n\t\t, {\"U\", \"UPnP\"}\n\t\t, {\"UL\", \"uLeecher\"}\n\t\t, {\"UT\", \"uTorrent\"}\n\t\t, {\"XL\", \"Xunlei\"}\n\t\t, {\"XT\", \"XanTorrent\"}\n\t\t, {\"XX\", \"Xtorrent\"}\n\t\t, {\"ZT\", \"ZipTorrent\"}\n\t\t, {\"lt\", \"rTorrent\"}\n\t\t, {\"pX\", \"pHoeniX\"}\n\t\t, {\"qB\", \"qBittorrent\"}\n\t\t, {\"st\", \"SharkTorrent\"}\n\t};\n\n\tstruct generic_map_entry\n\t{\n\t\tint offset;\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\t\/\/ non-standard names\n\tgeneric_map_entry generic_mappings[] =\n\t{\n\t\t{0, \"Deadman Walking-\", \"Deadman\"}\n\t\t, {5, \"Azureus\", \"Azureus 2.0.3.2\"}\n\t\t, {0, \"DansClient\", \"XanTorrent\"}\n\t\t, {4, \"btfans\", \"SimpleBT\"}\n\t\t, {0, \"PRC.P---\", \"Bittorrent Plus! II\"}\n\t\t, {0, \"P87.P---\", \"Bittorrent Plus!\"}\n\t\t, {0, \"S587Plus\", \"Bittorrent Plus!\"}\n\t\t, {0, \"martini\", \"Martini Man\"}\n\t\t, {0, \"Plus---\", \"Bittorrent Plus\"}\n\t\t, {0, \"turbobt\", \"TurboBT\"}\n\t\t, {0, \"a00---0\", \"Swarmy\"}\n\t\t, {0, \"a02---0\", \"Swarmy\"}\n\t\t, {0, \"T00---0\", \"Teeweety\"}\n\t\t, {0, \"BTDWV-\", \"Deadman Walking\"}\n\t\t, {2, \"BS\", \"BitSpirit\"}\n\t\t, {0, \"Pando-\", \"Pando\"}\n\t\t, {0, \"LIME\", \"LimeWire\"}\n\t\t, {0, \"btuga\", \"BTugaXP\"}\n\t\t, {0, \"oernu\", \"BTugaXP\"}\n\t\t, {0, \"Mbrst\", \"Burst!\"}\n\t\t, {0, \"PEERAPP\", \"PeerApp\"}\n\t\t, {0, \"Plus\", \"Plus!\"}\n\t\t, {0, \"-Qt-\", \"Qt\"}\n\t\t, {0, \"exbc\", \"BitComet\"}\n\t\t, {0, \"DNA\", \"BitTorrent DNA\"}\n\t\t, {0, \"-G3\", \"G3 Torrent\"}\n\t\t, {0, \"-FG\", \"FlashGet\"}\n\t\t, {0, \"-ML\", \"MLdonkey\"}\n\t\t, {0, \"XBT\", \"XBT\"}\n\t\t, {0, \"OP\", \"Opera\"}\n\t\t, {2, \"RS\", \"Rufus\"}\n\t\t, {0, \"AZ2500BT\", \"BitTyrant\"}\n\t};\n\n\tbool compare_id(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.id[0] < rhs.id[0]\n\t\t\t|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry tmp = {f.name, \"\"};\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, tmp, &compare_id);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(compare_id(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->id))\n\t\t\tidentity << i->name;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tint num_generic_mappings = sizeof(generic_mappings) \/ sizeof(generic_mappings[0]);\n\n\t\tfor (int i = 0; i < num_generic_mappings; ++i)\n\t\t{\n\t\t\tgeneric_map_entry const& e = generic_mappings[i];\n\t\t\tif (find_string(PID + e.offset, e.id)) return e.name;\n\t\t}\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t. map_emtry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n if (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>*** empty log message ***<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i].first));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AX\", \"BitPump\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BC\", \"BitComet\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CD\", \"Enhanced CTorrent\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"ES\", \"electric sheep\")\n\t\t, map_entry(\"KT\", \"KTorrent\")\n\t\t, map_entry(\"LP\", \"lphant\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"O\", \"Osprey Permaseed\")\n\t\t, map_entry(\"R\", \"Tribler\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SB\", \"Swiftbit\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"SZ\", \"Shareaza\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TR\", \"Transmission\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"UL\", \"uLeecher\")\n\t\t, map_entry(\"UT\", \"MicroTorrent\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t\t, map_entry(\"lt\", \"libTorrent (libtorrent.rakshasa.no\/)\")\n\t\t, map_entry(\"pX\", \"pHoeniX\")\n\t\t, map_entry(\"qB\", \"qBittorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.first[0] < rhs.first[0]\n\t\t\t|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, map_entry(f.name, \"\"), &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"-Qt-\")) return \"Qt\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\t\tif (find_string(PID, \"OP\")) return \"Opera\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>added Deluge client id<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AX\", \"BitPump\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BC\", \"BitComet\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CD\", \"Enhanced CTorrent\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"DE\", \"Deluge\")\n\t\t, map_entry(\"ES\", \"electric sheep\")\n\t\t, map_entry(\"KT\", \"KTorrent\")\n\t\t, map_entry(\"LP\", \"lphant\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"O\", \"Osprey Permaseed\")\n\t\t, map_entry(\"R\", \"Tribler\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SB\", \"Swiftbit\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"SZ\", \"Shareaza\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TR\", \"Transmission\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"UL\", \"uLeecher\")\n\t\t, map_entry(\"UT\", \"MicroTorrent\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t\t, map_entry(\"lt\", \"libTorrent (libtorrent.rakshasa.no\/)\")\n\t\t, map_entry(\"pX\", \"pHoeniX\")\n\t\t, map_entry(\"qB\", \"qBittorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.first[0] < rhs.first[0]\n\t\t\t|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, map_entry(f.name, \"\"), &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"-Qt-\")) return \"Qt\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\t\tif (find_string(PID, \"OP\")) return \"Opera\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BC\", \"BitComet\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"O\", \"Osprey Permaseed\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SB\", \"Swiftbit\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t\t, map_entry(\"lt\", \"libTorrent (libtorrent.rakshasa.no\/)\")\n\t\t, map_entry(\"pX\", \"pHoeniX\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i].first));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"-Qt-\")) return \"Qt\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"OP\")) return \"Opera\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>updated client identification<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\", \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BC\", \"BitComet\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"KT\", \"KTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\", \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"O\", \"Osprey Permaseed\")\n\t\t, map_entry(\"S\", \"Shadow\")\n\t\t, map_entry(\"SB\", \"Swiftbit\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"SZ\", \"Shareaza\")\n\t\t, map_entry(\"T\", \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\", \"UPnP\")\n\t\t, map_entry(\"UT\", \"MicroTorrent\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t\t, map_entry(\"lt\", \"libTorrent (libtorrent.rakshasa.no\/)\")\n\t\t, map_entry(\"pX\", \"pHoeniX\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i].first));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"-Qt-\")) return \"Qt\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\t\tif (find_string(PID, \"OP\")) return \"Opera\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\tstruct map_entry\n\t{\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\t{\"A\", \"ABC\"}\n\t\t, {\"AG\", \"Ares\"}\n\t\t, {\"AR\", \"Arctic Torrent\"}\n\t\t, {\"AV\", \"Avicora\"}\n\t\t, {\"AX\", \"BitPump\"}\n\t\t, {\"AZ\", \"Azureus\"}\n\t\t, {\"A~\", \"Ares\"}\n\t\t, {\"BB\", \"BitBuddy\"}\n\t\t, {\"BC\", \"BitComet\"}\n\t\t, {\"BF\", \"Bitflu\"}\n\t\t, {\"BG\", \"BTG\"}\n\t\t, {\"BR\", \"BitRocket\"}\n\t\t, {\"BS\", \"BTSlave\"}\n\t\t, {\"BX\", \"BittorrentX\"}\n\t\t, {\"CD\", \"Enhanced CTorrent\"}\n\t\t, {\"CT\", \"CTorrent\"}\n\t\t, {\"DE\", \"Deluge Torrent\"}\n\t\t, {\"EB\", \"EBit\"}\n\t\t, {\"ES\", \"electric sheep\"}\n\t\t, {\"HL\", \"Halite\"}\n\t\t, {\"HN\", \"Hydranode\"}\n\t\t, {\"KT\", \"KTorrent\"}\n\t\t, {\"LK\", \"Linkage\"}\n\t\t, {\"LP\", \"lphant\"}\n\t\t, {\"LT\", \"libtorrent\"}\n\t\t, {\"M\", \"Mainline\"}\n\t\t, {\"ML\", \"MLDonkey\"}\n\t\t, {\"MO\", \"Mono Torrent\"}\n\t\t, {\"MP\", \"MooPolice\"}\n\t\t, {\"MT\", \"Moonlight Torrent\"}\n\t\t, {\"O\", \"Osprey Permaseed\"}\n\t\t, {\"PD\", \"Pando\"}\n\t\t, {\"Q\", \"BTQueue\"}\n\t\t, {\"QT\", \"Qt 4\"}\n\t\t, {\"R\", \"Tribler\"}\n\t\t, {\"S\", \"Shadow\"}\n\t\t, {\"SB\", \"Swiftbit\"}\n\t\t, {\"SN\", \"ShareNet\"}\n\t\t, {\"SS\", \"SwarmScope\"}\n\t\t, {\"ST\", \"SymTorrent\"}\n\t\t, {\"SZ\", \"Shareaza\"}\n\t\t, {\"S~\", \"Shareaza (beta)\"}\n\t\t, {\"T\", \"BitTornado\"}\n\t\t, {\"TN\", \"Torrent.NET\"}\n\t\t, {\"TR\", \"Transmission\"}\n\t\t, {\"TS\", \"TorrentStorm\"}\n\t\t, {\"TT\", \"TuoTu\"}\n\t\t, {\"U\", \"UPnP\"}\n\t\t, {\"UL\", \"uLeecher\"}\n\t\t, {\"UT\", \"uTorrent\"}\n\t\t, {\"XL\", \"Xunlei\"}\n\t\t, {\"XT\", \"XanTorrent\"}\n\t\t, {\"XX\", \"Xtorrent\"}\n\t\t, {\"ZT\", \"ZipTorrent\"}\n\t\t, {\"lt\", \"rTorrent\"}\n\t\t, {\"pX\", \"pHoeniX\"}\n\t\t, {\"qB\", \"qBittorrent\"}\n\t\t, {\"st\", \"SharkTorrent\"}\n\t};\n\n\tstruct generic_map_entry\n\t{\n\t\tint offset;\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\t\/\/ non-standard names\n\tgeneric_map_entry generic_mappings[] =\n\t{\n\t\t{0, \"Deadman Walking-\", \"Deadman\"}\n\t\t, {5, \"Azureus\", \"Azureus 2.0.3.2\"}\n\t\t, {0, \"DansClient\", \"XanTorrent\"}\n\t\t, {4, \"btfans\", \"SimpleBT\"}\n\t\t, {0, \"PRC.P---\", \"Bittorrent Plus! II\"}\n\t\t, {0, \"P87.P---\", \"Bittorrent Plus!\"}\n\t\t, {0, \"S587Plus\", \"Bittorrent Plus!\"}\n\t\t, {0, \"martini\", \"Martini Man\"}\n\t\t, {0, \"Plus---\", \"Bittorrent Plus\"}\n\t\t, {0, \"turbobt\", \"TurboBT\"}\n\t\t, {0, \"a00---0\", \"Swarmy\"}\n\t\t, {0, \"a02---0\", \"Swarmy\"}\n\t\t, {0, \"T00---0\", \"Teeweety\"}\n\t\t, {0, \"BTDWV-\", \"Deadman Walking\"}\n\t\t, {2, \"BS\", \"BitSpirit\"}\n\t\t, {0, \"Pando-\", \"Pando\"}\n\t\t, {0, \"LIME\", \"LimeWire\"}\n\t\t, {0, \"btuga\", \"BTugaXP\"}\n\t\t, {0, \"oernu\", \"BTugaXP\"}\n\t\t, {0, \"Mbrst\", \"Burst!\"}\n\t\t, {0, \"PEERAPP\", \"PeerApp\"}\n\t\t, {0, \"Plus\", \"Plus!\"}\n\t\t, {0, \"-Qt-\", \"Qt\"}\n\t\t, {0, \"exbc\", \"BitComet\"}\n\t\t, {0, \"DNA\", \"BitTorrent DNA\"}\n\t\t, {0, \"-G3\", \"G3 Torrent\"}\n\t\t, {0, \"-FG\", \"FlashGet\"}\n\t\t, {0, \"-ML\", \"MLdonkey\"}\n\t\t, {0, \"XBT\", \"XBT\"}\n\t\t, {0, \"OP\", \"Opera\"}\n\t\t, {2, \"RS\", \"Rufus\"}\n\t\t, {0, \"AZ2500BT\", \"BitTyrant\"}\n\t};\n\n\tbool compare_id(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.id[0] < rhs.id[0]\n\t\t\t|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry tmp = {f.name, \"\"};\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, tmp, &compare_id);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(compare_id(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->id))\n\t\t\tidentity << i->name;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tint num_generic_mappings = sizeof(generic_mappings) \/ sizeof(generic_mappings[0]);\n\n\t\tfor (int i = 0; i < num_generic_mappings; ++i)\n\t\t{\n\t\t\tgeneric_map_entry const& e = generic_mappings[i];\n\t\t\tif (find_string(PID + e.offset, e.id)) return e.name;\n\t\t}\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>added Miro to the identifiable clients<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn unsigned(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')\n\t\t\t|| (id[3] < '0') || (id[4] < '0')\n\t\t\t|| (id[5] < '0') || (id[6] < '0')\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.name[0] = id[1];\n\t\tret.name[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+6, \"--\"))\n\t\t{\n\t\t\tif ((id[1] < '0') || (id[2] < '0')\n\t\t\t\t|| (id[3] < '0'))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.name[0] = id[0];\n\t\tret.name[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tchar ids[21];\n\t\tstd::copy(id.begin(), id.end(), ids);\n\t\tids[20] = 0;\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tret.name[1] = 0;\n\t\tret.tag_version = 0;\n\t\tif (sscanf(ids, \"%c%d-%d-%d--\", &ret.name[0], &ret.major_version, &ret.minor_version\n\t\t\t, &ret.revision_version) != 4\n\t\t\t|| !std::isprint(ret.name[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\tstruct map_entry\n\t{\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\t{\"A\", \"ABC\"}\n\t\t, {\"AG\", \"Ares\"}\n\t\t, {\"AR\", \"Arctic Torrent\"}\n\t\t, {\"AV\", \"Avicora\"}\n\t\t, {\"AX\", \"BitPump\"}\n\t\t, {\"AZ\", \"Azureus\"}\n\t\t, {\"A~\", \"Ares\"}\n\t\t, {\"BB\", \"BitBuddy\"}\n\t\t, {\"BC\", \"BitComet\"}\n\t\t, {\"BF\", \"Bitflu\"}\n\t\t, {\"BG\", \"BTG\"}\n\t\t, {\"BR\", \"BitRocket\"}\n\t\t, {\"BS\", \"BTSlave\"}\n\t\t, {\"BX\", \"BittorrentX\"}\n\t\t, {\"CD\", \"Enhanced CTorrent\"}\n\t\t, {\"CT\", \"CTorrent\"}\n\t\t, {\"DE\", \"Deluge Torrent\"}\n\t\t, {\"EB\", \"EBit\"}\n\t\t, {\"ES\", \"electric sheep\"}\n\t\t, {\"HL\", \"Halite\"}\n\t\t, {\"HN\", \"Hydranode\"}\n\t\t, {\"KT\", \"KTorrent\"}\n\t\t, {\"LK\", \"Linkage\"}\n\t\t, {\"LP\", \"lphant\"}\n\t\t, {\"LT\", \"libtorrent\"}\n\t\t, {\"M\", \"Mainline\"}\n\t\t, {\"ML\", \"MLDonkey\"}\n\t\t, {\"MO\", \"Mono Torrent\"}\n\t\t, {\"MP\", \"MooPolice\"}\n\t\t, {\"MR\", \"Miro\"}\n\t\t, {\"MT\", \"Moonlight Torrent\"}\n\t\t, {\"O\", \"Osprey Permaseed\"}\n\t\t, {\"PD\", \"Pando\"}\n\t\t, {\"Q\", \"BTQueue\"}\n\t\t, {\"QT\", \"Qt 4\"}\n\t\t, {\"R\", \"Tribler\"}\n\t\t, {\"S\", \"Shadow\"}\n\t\t, {\"SB\", \"Swiftbit\"}\n\t\t, {\"SN\", \"ShareNet\"}\n\t\t, {\"SS\", \"SwarmScope\"}\n\t\t, {\"ST\", \"SymTorrent\"}\n\t\t, {\"SZ\", \"Shareaza\"}\n\t\t, {\"S~\", \"Shareaza (beta)\"}\n\t\t, {\"T\", \"BitTornado\"}\n\t\t, {\"TN\", \"Torrent.NET\"}\n\t\t, {\"TR\", \"Transmission\"}\n\t\t, {\"TS\", \"TorrentStorm\"}\n\t\t, {\"TT\", \"TuoTu\"}\n\t\t, {\"U\", \"UPnP\"}\n\t\t, {\"UL\", \"uLeecher\"}\n\t\t, {\"UT\", \"uTorrent\"}\n\t\t, {\"XL\", \"Xunlei\"}\n\t\t, {\"XT\", \"XanTorrent\"}\n\t\t, {\"XX\", \"Xtorrent\"}\n\t\t, {\"ZT\", \"ZipTorrent\"}\n\t\t, {\"lt\", \"rTorrent\"}\n\t\t, {\"pX\", \"pHoeniX\"}\n\t\t, {\"qB\", \"qBittorrent\"}\n\t\t, {\"st\", \"SharkTorrent\"}\n\t};\n\n\tstruct generic_map_entry\n\t{\n\t\tint offset;\n\t\tchar const* id;\n\t\tchar const* name;\n\t};\n\t\/\/ non-standard names\n\tgeneric_map_entry generic_mappings[] =\n\t{\n\t\t{0, \"Deadman Walking-\", \"Deadman\"}\n\t\t, {5, \"Azureus\", \"Azureus 2.0.3.2\"}\n\t\t, {0, \"DansClient\", \"XanTorrent\"}\n\t\t, {4, \"btfans\", \"SimpleBT\"}\n\t\t, {0, \"PRC.P---\", \"Bittorrent Plus! II\"}\n\t\t, {0, \"P87.P---\", \"Bittorrent Plus!\"}\n\t\t, {0, \"S587Plus\", \"Bittorrent Plus!\"}\n\t\t, {0, \"martini\", \"Martini Man\"}\n\t\t, {0, \"Plus---\", \"Bittorrent Plus\"}\n\t\t, {0, \"turbobt\", \"TurboBT\"}\n\t\t, {0, \"a00---0\", \"Swarmy\"}\n\t\t, {0, \"a02---0\", \"Swarmy\"}\n\t\t, {0, \"T00---0\", \"Teeweety\"}\n\t\t, {0, \"BTDWV-\", \"Deadman Walking\"}\n\t\t, {2, \"BS\", \"BitSpirit\"}\n\t\t, {0, \"Pando-\", \"Pando\"}\n\t\t, {0, \"LIME\", \"LimeWire\"}\n\t\t, {0, \"btuga\", \"BTugaXP\"}\n\t\t, {0, \"oernu\", \"BTugaXP\"}\n\t\t, {0, \"Mbrst\", \"Burst!\"}\n\t\t, {0, \"PEERAPP\", \"PeerApp\"}\n\t\t, {0, \"Plus\", \"Plus!\"}\n\t\t, {0, \"-Qt-\", \"Qt\"}\n\t\t, {0, \"exbc\", \"BitComet\"}\n\t\t, {0, \"DNA\", \"BitTorrent DNA\"}\n\t\t, {0, \"-G3\", \"G3 Torrent\"}\n\t\t, {0, \"-FG\", \"FlashGet\"}\n\t\t, {0, \"-ML\", \"MLdonkey\"}\n\t\t, {0, \"XBT\", \"XBT\"}\n\t\t, {0, \"OP\", \"Opera\"}\n\t\t, {2, \"RS\", \"Rufus\"}\n\t\t, {0, \"AZ2500BT\", \"BitTyrant\"}\n\t};\n\n\tbool compare_id(map_entry const& lhs, map_entry const& rhs)\n\t{\n\t\treturn lhs.id[0] < rhs.id[0]\n\t\t\t|| ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry tmp = {f.name, \"\"};\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, tmp, &compare_id);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(compare_id(name_map[i-1]\n\t\t\t\t, name_map[i]));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.name, f.name + 2, i->id))\n\t\t\tidentity << i->name;\n\t\telse\n\t\t{\n\t\t\tidentity << f.name[0];\n\t\t\tif (f.name[1] != 0) identity << f.name[1];\n\t\t}\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version;\n\n\t\tif (f.name[1] != 0)\n\t\t\tidentity << \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tboost::optional<fingerprint> client_fingerprint(peer_id const& p)\n\t{\n\t\t\/\/ look for azureus style id\n\t\tboost::optional<fingerprint> f;\n\t\tf = parse_az_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return f;\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return f;\n\t\treturn f;\n\t}\n\n\tstd::string identify_client(peer_id const& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tint num_generic_mappings = sizeof(generic_mappings) \/ sizeof(generic_mappings[0]);\n\n\t\tfor (int i = 0; i < num_generic_mappings; ++i)\n\t\t{\n\t\t\tgeneric_map_entry const& e = generic_mappings[i];\n\t\t\tif (find_string(PID + e.offset, e.id)) return e.name;\n\t\t}\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2002 by Gunnar Kedenburg *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de or *\/\n\/* vigra@kogs1.informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/ \n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_BYTEORDER_HXX\n#define VIGRA_BYTEORDER_HXX\n\n#include <vector>\n#include <memory>\n#include <string>\n#include <fstream>\n#include <algorithm>\n#include \"vigra\/sized_int.hxx\"\n\nnamespace vigra\n{\n class byteorder\n {\n class host\n {\n std::string m_string;\n\n public:\n \n \/\/ ctor, dtor\n\n host();\n\n \/\/ methods\n\n const std::string & get() const;\n };\n\n \/\/ attributes\n\n static const host m_host;\n\n \/\/ data byte order, can be changed\n\n std::string m_string;\n bool native;\n\n \/\/ delegation methods\n\n template< class T >\n void reversebytes( T & x ) const\n {\n const unsigned int n = sizeof(T);\n UInt8 t[n];\n UInt8 * c = reinterpret_cast< UInt8 * >(&x);\n unsigned int i;\n for( i = 0; i < n; ++i )\n t[i] = c[ n - 1 - i ];\n for( i = 0; i < n; ++i )\n c[i] = t[i];\n }\n\n public:\n\n \/\/ ctor, dtor\n\n byteorder(); \/\/ uses the host byteorder\n byteorder( const std::string & );\n\n \/\/ methods\n\n void set( const std::string & );\n const std::string & get() const;\n const std::string & get_host_byteorder() const;\n\n template< class T >\n void convert_to_host( T & x ) const\n {\n if (!native)\n reversebytes(x);\n }\n\n template< class T >\n void convert_to_host( T * x, unsigned int num ) const\n {\n if (!native)\n for( unsigned int i = 0; i < num; ++i )\n reversebytes(x[i]);\n }\n\n template< class T >\n void convert_from_host( T & x ) const\n {\n if (!native)\n reversebytes(x);\n }\n\n template< class T >\n void convert_from_host( T * x, unsigned int num ) const\n {\n if (!native)\n for( unsigned int i = 0; i < num; ++i )\n reversebytes(x[i]);\n }\n\n void convert_to_host( char & x ) const {}\n void convert_to_host( Int8 & x ) const {}\n void convert_to_host( UInt8 & x ) const {}\n\n void convert_to_host( char * x , unsigned int) const {}\n void convert_to_host( Int8 * x, unsigned int) const {}\n void convert_to_host( UInt8 * x, unsigned int) const {}\n\n void convert_from_host( char & x ) const {}\n void convert_from_host( Int8 & x ) const {}\n void convert_from_host( UInt8 & x ) const {}\n\n void convert_from_host( char * x , unsigned int) const {}\n void convert_from_host( Int8 * x, unsigned int) const {}\n void convert_from_host( UInt8 * x, unsigned int) const {}\n };\n\n template< class T >\n void read_field( std::ifstream & stream, const byteorder & bo, T & x )\n {\n stream.read( reinterpret_cast< char * >(&x), sizeof(T) );\n bo.convert_to_host(x);\n }\n\n template< class T >\n void read_array( std::ifstream & stream, const byteorder & bo, T * x,\n unsigned int num )\n {\n stream.read( reinterpret_cast< char * >(x), sizeof(T) * num );\n bo.convert_to_host( x, num );\n }\n\n template< class T >\n void write_field( std::ofstream & stream, const byteorder & bo, T t )\n {\n bo.convert_from_host(t);\n stream.write( reinterpret_cast< char * >(&t), sizeof(T) );\n }\n\n template< class T >\n void write_array( std::ofstream & stream, const byteorder & bo,\n const T * x, unsigned int num )\n {\n for( unsigned int i = 0; i < num; ++i )\n write_field( stream, bo, x[i] );\n }\n\n} \/\/ namespace vigra\n\n#endif \/\/ VIGRA_BYTEORDER_HXX\n<commit_msg>changed unsigned int => size_t<commit_after>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2002 by Gunnar Kedenburg *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de or *\/\n\/* vigra@kogs1.informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/ \n\/* *\/\n\/************************************************************************\/\n\n#ifndef VIGRA_BYTEORDER_HXX\n#define VIGRA_BYTEORDER_HXX\n\n#include <vector>\n#include <memory>\n#include <string>\n#include <fstream>\n#include <algorithm>\n#include \"vigra\/sized_int.hxx\"\n\nnamespace vigra\n{\n class byteorder\n {\n class host\n {\n std::string m_string;\n\n public:\n \n \/\/ ctor, dtor\n\n host();\n\n \/\/ methods\n\n const std::string & get() const;\n };\n\n \/\/ attributes\n\n static const host m_host;\n\n \/\/ data byte order, can be changed\n\n std::string m_string;\n bool native;\n\n \/\/ delegation methods\n\n template< class T >\n void reversebytes( T & x ) const\n {\n const size_t n = sizeof(T);\n UInt8 t[n];\n UInt8 * c = reinterpret_cast< UInt8 * >(&x);\n size_t i;\n for( i = 0; i < n; ++i )\n t[i] = c[ n - 1 - i ];\n for( i = 0; i < n; ++i )\n c[i] = t[i];\n }\n\n public:\n\n \/\/ ctor, dtor\n\n byteorder(); \/\/ uses the host byteorder\n byteorder( const std::string & );\n\n \/\/ methods\n\n void set( const std::string & );\n const std::string & get() const;\n const std::string & get_host_byteorder() const;\n\n template< class T >\n void convert_to_host( T & x ) const\n {\n if (!native)\n reversebytes(x);\n }\n\n template< class T >\n void convert_to_host( T * x, size_t num ) const\n {\n if (!native)\n for( size_t i = 0; i < num; ++i )\n reversebytes(x[i]);\n }\n\n template< class T >\n void convert_from_host( T & x ) const\n {\n if (!native)\n reversebytes(x);\n }\n\n template< class T >\n void convert_from_host( T * x, size_t num ) const\n {\n if (!native)\n for( size_t i = 0; i < num; ++i )\n reversebytes(x[i]);\n }\n\n void convert_to_host( char & x ) const {}\n void convert_to_host( Int8 & x ) const {}\n void convert_to_host( UInt8 & x ) const {}\n\n void convert_to_host( char * x , size_t) const {}\n void convert_to_host( Int8 * x, size_t) const {}\n void convert_to_host( UInt8 * x, size_t) const {}\n\n void convert_from_host( char & x ) const {}\n void convert_from_host( Int8 & x ) const {}\n void convert_from_host( UInt8 & x ) const {}\n\n void convert_from_host( char * x , size_t) const {}\n void convert_from_host( Int8 * x, size_t) const {}\n void convert_from_host( UInt8 * x, size_t) const {}\n };\n\n template< class T >\n void read_field( std::ifstream & stream, const byteorder & bo, T & x )\n {\n stream.read( reinterpret_cast< char * >(&x), sizeof(T) );\n bo.convert_to_host(x);\n }\n\n template< class T >\n void read_array( std::ifstream & stream, const byteorder & bo, T * x,\n size_t num )\n {\n stream.read( reinterpret_cast< char * >(x), static_cast<std::streamsize>(sizeof(T) * num) );\n bo.convert_to_host( x, num );\n }\n\n template< class T >\n void write_field( std::ofstream & stream, const byteorder & bo, T t )\n {\n bo.convert_from_host(t);\n stream.write( reinterpret_cast< char * >(&t), sizeof(T) );\n }\n\n template< class T >\n void write_array( std::ofstream & stream, const byteorder & bo,\n const T * x, size_t num )\n {\n for( size_t i = 0; i < num; ++i )\n write_field( stream, bo, x[i] );\n }\n\n} \/\/ namespace vigra\n\n#endif \/\/ VIGRA_BYTEORDER_HXX\n<|endoftext|>"} {"text":"<commit_before>\/**\n * PWM.cpp\n *\n * This implementation file contains the function implementation for the PWM\n * class in libbbbpwm. This class encapsulates the fileops needed to activate\n * the PWM interface on the BeagleBone Black running the 3.8 kernel.\n *\n * Copyright (C) 2014 Nathan Hui <ntlhui@gmail.com> (408.838.5393)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the license, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n * USA\n *\/\n\n\/\/ Includes\n#include \"PWM.hpp\"\n\nusing namespace std;\n\n\/\/ Internal Defines\n\n\nPWM::PWM(const uint8_t pin, const uint32_t frequency){\n\t_pin = pin;\n\n\t_ocpDir = \"\/sys\/devices\/ocp.3\";\n\n\tswitch(pin){\n\t\tcase 0:\n\t\t\t_ocpDir += \"\/pwm_test_P8_13.11\";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\t_ocpDir += \"\/pwm_test_P8_19.14\";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t_ocpDir += \"\/pwm_test_P8_34.12\";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\t_ocpDir += \"\/pwm_test_P8_36.15\";\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\t_ocpDir += \"\/pwm_test_P8_45.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\t_ocpDir += \"\/pwm_test_P8_46.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\t_ocpDir += \"\/pwm_test_P9_14.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\t_ocpDir += \"\/pwm_test_P9_16.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\t_ocpDir += \"\/pwm_test_P9_21.16\";\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\t_ocpDir += \"\/pwm_test_P9_22.17\";\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\t_ocpDir += \"\/pwm_test_P9_28.18\";\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\t_ocpDir += \"\/pwm_test_P9_29.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 12:\n\t\t\t_ocpDir += \"\/pwm_test_P9_31.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\t_ocpDir += \"\/pwm_Test_P9_42.19\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(pin <= 13);\n\t}\n\t\n\t\/\/ Set initial frequency\n\tfstream freqFile (_ocpDir + \"\/period\", fstream::out | fstream :: app);\n\tcout << _ocpDir << endl;\n\tassert(freqFile.good());\n\n\t_period = 1e9 \/ frequency;\n\tfreqFile << _period;\n\tfreqFile.close();\n}\n\nPWM::~PWM(){\n\n}\n\nvoid PWM::setDuty(const float dutyPercentage){\n\tassert(!_period);\n\tassert(dutyPercentage >= 1);\n\n\t_pulseWidth = dutyPercentage * _period;\n\tfstream file (_ocpDir + \"\/duty\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/duty!\");\n\t}\n\tfile << _pulseWidth << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/duty!\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setPeriod(const uint32_t period){\n\tassert(period >= 1000000000);\n\t_period = period;\n\n\tfstream file (_ocpDir + \"\/period\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/period!\");\n\t}\n\tfile << _period << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/period!\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setOnTime(const uint32_t onTime){\n\tcout << _period << endl;\n\tassert(_period > 0);\n\tassert(onTime < _period);\n\n\t_pulseWidth = onTime;\n\tfstream file(_ocpDir + \"\/duty\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/duty\");\n\t}\n\tfile << _pulseWidth << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/duty\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setPolarity(const bool polarity){\n\t_polarity = polarity;\n\n\tfstream file(_ocpDir + \"\/polarity\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/polarity\");\n\t}\n\tfile << _polarity << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/polarity\");\n\t}\n\tfile.close();\n}\n<commit_msg>Implemented setState<commit_after>\/**\n * PWM.cpp\n *\n * This implementation file contains the function implementation for the PWM\n * class in libbbbpwm. This class encapsulates the fileops needed to activate\n * the PWM interface on the BeagleBone Black running the 3.8 kernel.\n *\n * Copyright (C) 2014 Nathan Hui <ntlhui@gmail.com> (408.838.5393)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the license, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n * USA\n *\/\n\n\/\/ Includes\n#include \"PWM.hpp\"\n\nusing namespace std;\n\n\/\/ Internal Defines\n\n\nPWM::PWM(const uint8_t pin, const uint32_t frequency){\n\t_pin = pin;\n\n\t_ocpDir = \"\/sys\/devices\/ocp.3\";\n\n\tswitch(pin){\n\t\tcase 0:\n\t\t\t_ocpDir += \"\/pwm_test_P8_13.11\";\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\t_ocpDir += \"\/pwm_test_P8_19.14\";\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t_ocpDir += \"\/pwm_test_P8_34.12\";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\t_ocpDir += \"\/pwm_test_P8_36.15\";\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\t_ocpDir += \"\/pwm_test_P8_45.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\t_ocpDir += \"\/pwm_test_P8_46.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\t_ocpDir += \"\/pwm_test_P9_14.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\t_ocpDir += \"\/pwm_test_P9_16.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\t_ocpDir += \"\/pwm_test_P9_21.16\";\n\t\t\tbreak;\n\t\tcase 9:\n\t\t\t_ocpDir += \"\/pwm_test_P9_22.17\";\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\t_ocpDir += \"\/pwm_test_P9_28.18\";\n\t\t\tbreak;\n\t\tcase 11:\n\t\t\t_ocpDir += \"\/pwm_test_P9_29.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 12:\n\t\t\t_ocpDir += \"\/pwm_test_P9_31.\";\t\/\/ TODO add suffix\n\t\t\tbreak;\n\t\tcase 13:\n\t\t\t_ocpDir += \"\/pwm_Test_P9_42.19\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(pin <= 13);\n\t}\n\t\n\t\/\/ Set initial frequency\n\tfstream freqFile (_ocpDir + \"\/period\", fstream::out | fstream :: app);\n\tcout << _ocpDir << endl;\n\tassert(freqFile.good());\n\n\t_period = 1e9 \/ frequency;\n\tfreqFile << _period;\n\tfreqFile.close();\n}\n\nPWM::~PWM(){\n\n}\n\nvoid PWM::setDuty(const float dutyPercentage){\n\tassert(!_period);\n\tassert(dutyPercentage >= 1);\n\n\t_pulseWidth = dutyPercentage * _period;\n\tfstream file (_ocpDir + \"\/duty\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/duty!\");\n\t}\n\tfile << _pulseWidth << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/duty!\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setPeriod(const uint32_t period){\n\tassert(period >= 1000000000);\n\t_period = period;\n\n\tfstream file (_ocpDir + \"\/period\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/period!\");\n\t}\n\tfile << _period << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/period!\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setOnTime(const uint32_t onTime){\n\tcout << _period << endl;\n\tassert(_period > 0);\n\tassert(onTime < _period);\n\n\t_pulseWidth = onTime;\n\tfstream file(_ocpDir + \"\/duty\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/duty\");\n\t}\n\tfile << _pulseWidth << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/duty\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setPolarity(const bool polarity){\n\t_polarity = polarity;\n\n\tfstream file(_ocpDir + \"\/polarity\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/polarity\");\n\t}\n\tfile << _polarity << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/polarity\");\n\t}\n\tfile.close();\n}\n\nvoid PWM::setState(const bool running){\n\t_running = running;\n\n\tfstream file(_ocpDir + \"\/run\", fstream::out | fstream::app);\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to open \" + _ocpDir + \"\/run\");\n\t}\n\tfile << _running << flush;\n\tif(file.bad()){\n\t\tthrow runtime_error(\"Failed to write to \" + _ocpDir + \"\/run\");\n\t}\n\tfile.close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Siconos-Kernel, Copyright INRIA 2005-2010.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\n\n#include \"NewtonEulerRFC3D.hpp\"\n#include \"NewtonEulerDS.hpp\"\n#include <boost\/math\/quaternion.hpp>\nusing namespace std;\n\/\/#define NEFC3D_DEBUG\n\/*\n See devNotes.pdf for details.\n *\/\nvoid NewtonEulerRFC3D::initComponents()\n{\n NewtonEulerRImpact::initComponents();\n \/*keep only the distance.*\/\n \/*Warning, in current version, user of FC3D has to set _y and _yProj in the computeh *\/\n _yProj.reset(new SimpleVector(1));\n _Mabs_C.reset(new SimpleMatrix(3, 3));\n _AUX2.reset(new SimpleMatrix(3, 3));\n}\nvoid NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts(SP::NewtonEulerDS d1)\n{\n\n double Nx = _Nc->getValue(0);\n double Ny = _Nc->getValue(1);\n double Nz = _Nc->getValue(2);\n double Px = _Pc1->getValue(0);\n double Py = _Pc1->getValue(1);\n double Pz = _Pc1->getValue(2);\n double G1x = d1->q()->getValue(0);\n double G1y = d1->q()->getValue(1);\n double G1z = d1->q()->getValue(2);\n#ifdef NEFC3D_DEBUG\n printf(\"contact normal:\\n\");\n _Nc->display();\n printf(\"point de contact :\\n\");\n _Pc1->display();\n printf(\"center of masse :\\n\");\n d1->q()->display();\n#endif\n double t[6];\n double * pt = t;\n orthoBaseFromVector(&Nx, &Ny, &Nz, pt, pt + 1, pt + 2, pt + 3, pt + 4, pt + 5);\n pt = t;\n _Mabs_C->setValue(0, 0, Nx);\n _Mabs_C->setValue(1, 0, *pt);\n _Mabs_C->setValue(2, 0, *(pt + 3));\n _Mabs_C->setValue(0, 1, Ny);\n _Mabs_C->setValue(1, 1, *(pt + 1));\n _Mabs_C->setValue(2, 1, *(pt + 4));\n _Mabs_C->setValue(0, 2, Nz);\n _Mabs_C->setValue(1, 2, *(pt + 2));\n _Mabs_C->setValue(2, 2, *(pt + 5));\n#ifdef NEFC3D_DEBUG\n printf(\"_Mabs_C:\\n\");\n _Mabs_C->display();\n#endif\n _NPG1->zero();\n\n (*_NPG1)(0, 0) = 0;\n (*_NPG1)(0, 1) = -(G1z - Pz);\n (*_NPG1)(0, 2) = (G1y - Py);\n (*_NPG1)(1, 0) = (G1z - Pz);\n (*_NPG1)(1, 1) = 0;\n (*_NPG1)(1, 2) = -(G1x - Px);\n (*_NPG1)(2, 0) = -(G1y - Py);\n (*_NPG1)(2, 1) = (G1x - Px);\n (*_NPG1)(2, 2) = 0;\n\n d1->updateMObjToAbs();\n SP::SimpleMatrix Mobj1_abs = d1->MObjToAbs();\n\n\n\n#ifdef NEFC3D_DEBUG\n printf(\"NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts, Mobj1_abs:\");\n Mobj1_abs->display();\n#endif\n\n\n prod(*_NPG1, *Mobj1_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj, _Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj, _AUX2->getValue(ii, jj - 3));\n#ifdef NEFC3D_DEBUG\n printf(\"NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts, jhqT:\\n\");\n _jachqT->display();\n SP::SimpleMatrix jaux(new SimpleMatrix(*jhqT));\n jaux->trans();\n SP::SimpleVector v(new SimpleVector(3));\n SP::SimpleVector vRes(new SimpleVector(6));\n v->zero();\n v->setValue(0, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n v->zero();\n v->setValue(1, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n v->zero();\n v->setValue(2, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n#endif\n}\n\nvoid NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2)\n{\n double Nx = _Nc->getValue(0);\n double Ny = _Nc->getValue(1);\n double Nz = _Nc->getValue(2);\n double Px = _Pc1->getValue(0);\n double Py = _Pc1->getValue(1);\n double Pz = _Pc1->getValue(2);\n double G1x = d1->q()->getValue(0);\n double G1y = d1->q()->getValue(1);\n double G1z = d1->q()->getValue(2);\n\n double t[6];\n double * pt = t;\n orthoBaseFromVector(&Nx, &Ny, &Nz, pt, pt + 1, pt + 2, pt + 3, pt + 4, pt + 5);\n pt = t;\n _Mabs_C->setValue(0, 0, Nx);\n _Mabs_C->setValue(1, 0, *pt);\n _Mabs_C->setValue(2, 0, *(pt + 3));\n _Mabs_C->setValue(0, 1, Ny);\n _Mabs_C->setValue(1, 1, *(pt + 1));\n _Mabs_C->setValue(2, 1, *(pt + 4));\n _Mabs_C->setValue(0, 2, Nz);\n _Mabs_C->setValue(1, 2, *(pt + 2));\n _Mabs_C->setValue(2, 2, *(pt + 5));\n\n _NPG1->zero();\n\n (*_NPG1)(0, 0) = 0;\n (*_NPG1)(0, 1) = -(G1z - Pz);\n (*_NPG1)(0, 2) = (G1y - Py);\n (*_NPG1)(1, 0) = (G1z - Pz);\n (*_NPG1)(1, 1) = 0;\n (*_NPG1)(1, 2) = -(G1x - Px);\n (*_NPG1)(2, 0) = -(G1y - Py);\n (*_NPG1)(2, 1) = (G1x - Px);\n (*_NPG1)(2, 2) = 0;\n\n\n d1->updateMObjToAbs();\n SP::SimpleMatrix Mobj1_abs = d1->MObjToAbs();\n\n\n prod(*_NPG1, *Mobj1_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj, _Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj, _AUX2->getValue(ii, jj - 3));\n\n d2->updateMObjToAbs();\n SP::SimpleMatrix Mobj2_abs = d1->MObjToAbs();\n\n\n prod(*_NPG2, *Mobj2_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj + 6, -_Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj + 6, -_AUX2->getValue(ii, jj - 3));\n\n}\nvoid NewtonEulerRFC3D::computeJachqT()\n{\n DSIterator itDS = interaction()->dynamicalSystemsBegin();\n SP::NewtonEulerDS d1 = boost::static_pointer_cast<NewtonEulerDS> (*itDS);\n itDS++;\n if (itDS != interaction()->dynamicalSystemsEnd())\n {\n SP::NewtonEulerDS d2 = boost::static_pointer_cast<NewtonEulerDS> (*itDS);\n FC3DcomputeJachqTFromContacts(d1, d2);\n }\n else\n {\n FC3DcomputeJachqTFromContacts(d1);\n }\n}\n<commit_msg>Fix a Bug: missing a part of nablaqT when two bodies collide<commit_after>\/* Siconos-Kernel, Copyright INRIA 2005-2010.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n *\/\n\n\n#include \"NewtonEulerRFC3D.hpp\"\n#include \"NewtonEulerDS.hpp\"\n#include <boost\/math\/quaternion.hpp>\nusing namespace std;\n\/\/#define NEFC3D_DEBUG\n\/*\n See devNotes.pdf for details.\n *\/\nvoid NewtonEulerRFC3D::initComponents()\n{\n NewtonEulerRImpact::initComponents();\n \/*keep only the distance.*\/\n \/*Warning, in current version, user of FC3D has to set _y and _yProj in the computeh *\/\n _yProj.reset(new SimpleVector(1));\n _Mabs_C.reset(new SimpleMatrix(3, 3));\n _AUX2.reset(new SimpleMatrix(3, 3));\n}\nvoid NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts(SP::NewtonEulerDS d1)\n{\n\n double Nx = _Nc->getValue(0);\n double Ny = _Nc->getValue(1);\n double Nz = _Nc->getValue(2);\n double Px = _Pc1->getValue(0);\n double Py = _Pc1->getValue(1);\n double Pz = _Pc1->getValue(2);\n double G1x = d1->q()->getValue(0);\n double G1y = d1->q()->getValue(1);\n double G1z = d1->q()->getValue(2);\n#ifdef NEFC3D_DEBUG\n printf(\"contact normal:\\n\");\n _Nc->display();\n printf(\"point de contact :\\n\");\n _Pc1->display();\n printf(\"center of masse :\\n\");\n d1->q()->display();\n#endif\n double t[6];\n double * pt = t;\n orthoBaseFromVector(&Nx, &Ny, &Nz, pt, pt + 1, pt + 2, pt + 3, pt + 4, pt + 5);\n pt = t;\n _Mabs_C->setValue(0, 0, Nx);\n _Mabs_C->setValue(1, 0, *pt);\n _Mabs_C->setValue(2, 0, *(pt + 3));\n _Mabs_C->setValue(0, 1, Ny);\n _Mabs_C->setValue(1, 1, *(pt + 1));\n _Mabs_C->setValue(2, 1, *(pt + 4));\n _Mabs_C->setValue(0, 2, Nz);\n _Mabs_C->setValue(1, 2, *(pt + 2));\n _Mabs_C->setValue(2, 2, *(pt + 5));\n#ifdef NEFC3D_DEBUG\n printf(\"_Mabs_C:\\n\");\n _Mabs_C->display();\n#endif\n _NPG1->zero();\n\n (*_NPG1)(0, 0) = 0;\n (*_NPG1)(0, 1) = -(G1z - Pz);\n (*_NPG1)(0, 2) = (G1y - Py);\n (*_NPG1)(1, 0) = (G1z - Pz);\n (*_NPG1)(1, 1) = 0;\n (*_NPG1)(1, 2) = -(G1x - Px);\n (*_NPG1)(2, 0) = -(G1y - Py);\n (*_NPG1)(2, 1) = (G1x - Px);\n (*_NPG1)(2, 2) = 0;\n\n d1->updateMObjToAbs();\n SP::SimpleMatrix Mobj1_abs = d1->MObjToAbs();\n\n\n\n#ifdef NEFC3D_DEBUG\n printf(\"NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts, Mobj1_abs:\");\n Mobj1_abs->display();\n#endif\n\n\n prod(*_NPG1, *Mobj1_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj, _Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj, _AUX2->getValue(ii, jj - 3));\n#ifdef NEFC3D_DEBUG\n printf(\"NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts, jhqT:\\n\");\n _jachqT->display();\n SP::SimpleMatrix jaux(new SimpleMatrix(*jhqT));\n jaux->trans();\n SP::SimpleVector v(new SimpleVector(3));\n SP::SimpleVector vRes(new SimpleVector(6));\n v->zero();\n v->setValue(0, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n v->zero();\n v->setValue(1, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n v->zero();\n v->setValue(2, 1);\n prod(*jaux, *v, *vRes, true);\n vRes->display();\n#endif\n}\n\nvoid NewtonEulerRFC3D::FC3DcomputeJachqTFromContacts(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2)\n{\n double Nx = _Nc->getValue(0);\n double Ny = _Nc->getValue(1);\n double Nz = _Nc->getValue(2);\n double Px = _Pc1->getValue(0);\n double Py = _Pc1->getValue(1);\n double Pz = _Pc1->getValue(2);\n double G1x = d1->q()->getValue(0);\n double G1y = d1->q()->getValue(1);\n double G1z = d1->q()->getValue(2);\n double G2x = d2->q()->getValue(0);\n double G2y = d2->q()->getValue(1);\n double G2z = d2->q()->getValue(2);\n\n double t[6];\n double * pt = t;\n orthoBaseFromVector(&Nx, &Ny, &Nz, pt, pt + 1, pt + 2, pt + 3, pt + 4, pt + 5);\n pt = t;\n _Mabs_C->setValue(0, 0, Nx);\n _Mabs_C->setValue(1, 0, *pt);\n _Mabs_C->setValue(2, 0, *(pt + 3));\n _Mabs_C->setValue(0, 1, Ny);\n _Mabs_C->setValue(1, 1, *(pt + 1));\n _Mabs_C->setValue(2, 1, *(pt + 4));\n _Mabs_C->setValue(0, 2, Nz);\n _Mabs_C->setValue(1, 2, *(pt + 2));\n _Mabs_C->setValue(2, 2, *(pt + 5));\n\n _NPG1->zero();\n\n (*_NPG1)(0, 0) = 0;\n (*_NPG1)(0, 1) = -(G1z - Pz);\n (*_NPG1)(0, 2) = (G1y - Py);\n (*_NPG1)(1, 0) = (G1z - Pz);\n (*_NPG1)(1, 1) = 0;\n (*_NPG1)(1, 2) = -(G1x - Px);\n (*_NPG1)(2, 0) = -(G1y - Py);\n (*_NPG1)(2, 1) = (G1x - Px);\n (*_NPG1)(2, 2) = 0;\n\n _NPG2->zero();\n\n (*_NPG2)(0, 0) = 0;\n (*_NPG2)(0, 1) = -(G2z - Pz);\n (*_NPG2)(0, 2) = (G2y - Py);\n (*_NPG2)(1, 0) = (G2z - Pz);\n (*_NPG2)(1, 1) = 0;\n (*_NPG2)(1, 2) = -(G2x - Px);\n (*_NPG2)(2, 0) = -(G2y - Py);\n (*_NPG2)(2, 1) = (G2x - Px);\n (*_NPG2)(2, 2) = 0;\n\n\n d1->updateMObjToAbs();\n SP::SimpleMatrix Mobj1_abs = d1->MObjToAbs();\n\n\n prod(*_NPG1, *Mobj1_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj, _Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj, _AUX2->getValue(ii, jj - 3));\n\n d2->updateMObjToAbs();\n SP::SimpleMatrix Mobj2_abs = d1->MObjToAbs();\n\n\n prod(*_NPG2, *Mobj2_abs, *_AUX1, true);\n prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 0; jj < 3; jj++)\n _jachqT->setValue(ii, jj + 6, -_Mabs_C->getValue(ii, jj));\n\n for (unsigned int ii = 0; ii < 3; ii++)\n for (unsigned int jj = 3; jj < 6; jj++)\n _jachqT->setValue(ii, jj + 6, -_AUX2->getValue(ii, jj - 3));\n\n}\nvoid NewtonEulerRFC3D::computeJachqT()\n{\n DSIterator itDS = interaction()->dynamicalSystemsBegin();\n SP::NewtonEulerDS d1 = boost::static_pointer_cast<NewtonEulerDS> (*itDS);\n itDS++;\n if (itDS != interaction()->dynamicalSystemsEnd())\n {\n SP::NewtonEulerDS d2 = boost::static_pointer_cast<NewtonEulerDS> (*itDS);\n FC3DcomputeJachqTFromContacts(d1, d2);\n }\n else\n {\n FC3DcomputeJachqTFromContacts(d1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\nclass Solution {\npublic:\n bool isSymmetricBFS(TreeNode* root) {\n if (root == nullptr) return true;\n std::queue<TreeNode*> q1, q2;\n q1.push(root->left);\n q2.push(root->right);\n while (!q1.empty() && !q2.empty()) {\n TreeNode *n1 = q1.front(), *n2 = q2.front();\n q1.pop();\n q2.pop();\n if (n1 == nullptr && n2 == nullptr)\n continue;\n if (n1 == nullptr || n2 == nullptr)\n return false;\n if (n1->val != n2->val)\n return false;\n q1.push(n1->left);\n q1.push(n1->right);\n q2.push(n2->right);\n q2.push(n2->left);\n }\n return true;\n }\n};<commit_msg>101 added DFS<commit_after>\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\nclass Solution {\npublic:\n bool isSymmetricBFS(TreeNode* root) {\n if (root == nullptr) return true;\n std::queue<TreeNode*> q1, q2;\n q1.push(root->left);\n q2.push(root->right);\n while (!q1.empty() && !q2.empty()) {\n TreeNode *n1 = q1.front(), *n2 = q2.front();\n q1.pop();\n q2.pop();\n if (n1 == nullptr && n2 == nullptr)\n continue;\n if (n1 == nullptr || n2 == nullptr)\n return false;\n if (n1->val != n2->val)\n return false;\n q1.push(n1->left);\n q1.push(n1->right);\n q2.push(n2->right);\n q2.push(n2->left);\n }\n return true;\n }\n bool isSymmetric(TreeNode* root) {\n return DFS(root, root);\n }\n \n bool DFS(TreeNode* a, TreeNode* b) {\n if (a == nullptr && b == nullptr)\n return true;\n if (a == nullptr || b == nullptr)\n return false;\n if (a->val != b->val)\n return false;\n return DFS(a->left, b->right) && DFS(a->right, b->left);\n }\n};<|endoftext|>"} {"text":"<commit_before>#include \"board\/Board.h\"\n#include \"board\/common\/indicators\/Variables.h\"\n#include \"Constants.h\"\n\n\/\/\/\n\/\/\/ \\brief Buffer in which outgoing data is stored.\n\/\/\/\nstatic RingBuff_t txBuffer;\n\n\/\/\/\n\/\/\/ \\brief Buffer in which incoming data is stored.\n\/\/\/\nstatic RingBuff_t rxBuffer;\n\n\/\/\/\n\/\/\/ \\brief Flag determining whether or not UART loopback functionality is enabled.\n\/\/\/ When enabled, all incoming UART traffic is immediately passed on to UART TX.\n\/\/\/\nstatic bool loopbackEnabled;\n\n\/\/\/\n\/\/\/ \\brief Flag determining whether or not OpenDeck UART format is configured.\n\/\/\/\nstatic bool odUARTconfigured;\n\n\/\/\/\n\/\/\/ \\brief ISR used to store incoming data from UART to buffer.\n\/\/\/\nISR(USART_RX_vect)\n{\n uint8_t data = UDR;\n\n if (!loopbackEnabled)\n {\n if (!RingBuffer_IsFull(&rxBuffer))\n {\n RingBuffer_Insert(&rxBuffer, data);\n }\n }\n else\n {\n if (!RingBuffer_IsFull(&txBuffer))\n {\n RingBuffer_Insert(&txBuffer, data);\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n MIDIreceived = true;\n #endif\n }\n}\n}\n\n\/\/\/\n\/\/\/ \\brief ISR used to write outgoing data in buffer to UART.\n\/\/\/\nISR(USART_UDRE_vect)\n{\n if (RingBuffer_IsEmpty(&txBuffer))\n {\n \/\/buffer is empty, disable transmit interrupt\n UCSRB &= ~(1<<UDRIE);\n }\n else\n {\n uint8_t data = RingBuffer_Remove(&txBuffer);\n UDR = data;\n }\n}\n\nvoid Board::initMIDI_UART()\n{\n int32_t baud_count = ((F_CPU \/ 8) + (MIDI_BAUD_RATE \/ 2)) \/ MIDI_BAUD_RATE;\n\n \/\/clear registers first\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n {\n UCSRA = 0;\n UCSRB = 0;\n UCSRC = 0;\n UBRR = 0;\n }\n\n if ((baud_count & 1) && baud_count <= 4096)\n {\n UCSRA = (1<<U2X); \/\/double speed uart\n UBRR = baud_count - 1;\n }\n else\n {\n UCSRA = 0;\n UBRR = (baud_count >> 1) - 1;\n }\n\n \/\/8 bit, no parity, 1 stop bit\n UCSRC = (1<<UCSZ1) | (1<<UCSZ0);\n\n \/\/enable receiver, transmitter and receive interrupt\n UCSRB = (1<<RXEN) | (1<<TXEN) | (1<<RXCIE);\n\n RingBuffer_InitBuffer(&rxBuffer);\n RingBuffer_InitBuffer(&txBuffer);\n\n #ifndef BOARD_A_xu2\n #if defined(BOARD_A_MEGA) || defined(BOARD_A_UNO)\n \/\/enable od format immediately for these boards\n setOD_UART();\n #else\n midi.handleUARTread(board.MIDIread_UART);\n midi.handleUARTwrite(board.MIDIwrite_UART);\n #endif\n #endif\n}\n\nint16_t Board::MIDIread_UART()\n{\n if (RingBuffer_IsEmpty(&rxBuffer))\n {\n return -1;\n }\n\n uint8_t data = RingBuffer_Remove(&rxBuffer);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO) && !defined(BOARD_A_xu2)\n MIDIreceived = true;\n #endif\n return data;\n}\n\nint8_t Board::MIDIwrite_UART(uint8_t data)\n{\n \/\/if both the outgoing buffer and the UART data register are empty\n \/\/write the byte to the data register directly\n if (RingBuffer_IsEmpty(&txBuffer) && (UCSRA & (1<<UDRE)))\n {\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n {\n UDR = data;\n }\n\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n #endif\n\n return 1;\n }\n\n while (RingBuffer_IsFull(&txBuffer));\n RingBuffer_Insert(&txBuffer, data);\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n #endif\n\n return 1;\n}\n\nbool Board::MIDIwrite_UART_OD(USBMIDIpacket_t& USBMIDIpacket)\n{\n RingBuffer_Insert(&txBuffer, 0xF1);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Event);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data1);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data2);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data3);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Event ^ USBMIDIpacket.Data1 ^ USBMIDIpacket.Data2 ^ USBMIDIpacket.Data3);\n\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO) && !defined(BOARD_A_xu2)\n MIDIsent = true;\n #endif\n\n return true;\n}\n\nbool Board::MIDIread_UART_OD()\n{\n if (RingBuffer_GetCount(&rxBuffer) >= 6)\n {\n int16_t data = MIDIread_UART();\n\n if (data == 0xF1)\n {\n \/\/start of frame, read rest of the packet\n for (int i=0; i<5; i++)\n {\n data = MIDIread_UART();\n\n switch(i)\n {\n case 0:\n usbMIDIpacket.Event = data;\n break;\n\n case 1:\n usbMIDIpacket.Data1 = data;\n break;\n\n case 2:\n usbMIDIpacket.Data2 = data;\n break;\n\n case 3:\n usbMIDIpacket.Data3 = data;\n break;\n\n case 4:\n \/\/xor byte, do nothing\n break;\n }\n }\n\n \/\/everything fine so far\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO) && !defined(BOARD_A_xu2)\n MIDIreceived = true;\n #endif\n\n \/\/error check\n uint8_t dataXOR = usbMIDIpacket.Event ^ usbMIDIpacket.Data1 ^ usbMIDIpacket.Data2 ^ usbMIDIpacket.Data3;\n\n return (dataXOR == data);\n }\n }\n\n return false;\n}\n\nbool usbRead_od(USBMIDIpacket_t& USBMIDIpacket)\n{\n return board.MIDIread_UART_OD();\n}\n\nvoid Board::setUARTloopbackState(bool state)\n{\n loopbackEnabled = state;\n}\n\nbool Board::getUARTloopbackState()\n{\n return loopbackEnabled;\n}\n\nbool Board::isRXempty()\n{\n return RingBuffer_IsEmpty(&rxBuffer);\n}\n\nbool Board::isTXempty()\n{\n return RingBuffer_IsEmpty(&txBuffer);\n}\n\nvoid Board::setOD_UART()\n{\n #ifdef BOARD_OPEN_DECK\n if (isUSBconnected())\n {\n \/\/master board\n midi.handleUSBread(board.MIDIread_USB_write_UART_OD);\n midi.handleUSBwrite(board.MIDIwrite_USB);\n midi.handleUARTread(NULL); \/\/parsed internally\n midi.handleUARTwrite(NULL);\n }\n else\n {\n \/\/slave\n midi.handleUSBread(usbRead_od); \/\/loopback used on inner slaves\n midi.handleUSBwrite(board.MIDIwrite_UART_OD);\n midi.handleUARTread(NULL);\n midi.handleUARTwrite(NULL);\n }\n\n odUARTconfigured = true;\n #elif defined(BOARD_A_MEGA) || defined(BOARD_A_UNO)\n midi.handleUSBread(usbRead_od);\n midi.handleUSBwrite(board.MIDIwrite_UART_OD);\n midi.handleUARTread(NULL);\n midi.handleUARTwrite(NULL);\n odUARTconfigured = true;\n #endif\n}\n\nbool Board::getOD_UART()\n{\n return odUARTconfigured;\n}\n<commit_msg>remove duplicate functionality<commit_after>#include \"board\/Board.h\"\n#include \"board\/common\/indicators\/Variables.h\"\n#include \"Constants.h\"\n\n\/\/\/\n\/\/\/ \\brief Buffer in which outgoing data is stored.\n\/\/\/\nstatic RingBuff_t txBuffer;\n\n\/\/\/\n\/\/\/ \\brief Buffer in which incoming data is stored.\n\/\/\/\nstatic RingBuff_t rxBuffer;\n\n\/\/\/\n\/\/\/ \\brief Flag determining whether or not UART loopback functionality is enabled.\n\/\/\/ When enabled, all incoming UART traffic is immediately passed on to UART TX.\n\/\/\/\nstatic bool loopbackEnabled;\n\n\/\/\/\n\/\/\/ \\brief Flag determining whether or not OpenDeck UART format is configured.\n\/\/\/\nstatic bool odUARTconfigured;\n\n\/\/\/\n\/\/\/ \\brief ISR used to store incoming data from UART to buffer.\n\/\/\/\nISR(USART_RX_vect)\n{\n uint8_t data = UDR;\n\n if (!loopbackEnabled)\n {\n if (!RingBuffer_IsFull(&rxBuffer))\n {\n RingBuffer_Insert(&rxBuffer, data);\n }\n }\n else\n {\n if (!RingBuffer_IsFull(&txBuffer))\n {\n RingBuffer_Insert(&txBuffer, data);\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n MIDIreceived = true;\n #endif\n }\n}\n}\n\n\/\/\/\n\/\/\/ \\brief ISR used to write outgoing data in buffer to UART.\n\/\/\/\nISR(USART_UDRE_vect)\n{\n if (RingBuffer_IsEmpty(&txBuffer))\n {\n \/\/buffer is empty, disable transmit interrupt\n UCSRB &= ~(1<<UDRIE);\n }\n else\n {\n uint8_t data = RingBuffer_Remove(&txBuffer);\n UDR = data;\n }\n}\n\nvoid Board::initMIDI_UART()\n{\n int32_t baud_count = ((F_CPU \/ 8) + (MIDI_BAUD_RATE \/ 2)) \/ MIDI_BAUD_RATE;\n\n \/\/clear registers first\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n {\n UCSRA = 0;\n UCSRB = 0;\n UCSRC = 0;\n UBRR = 0;\n }\n\n if ((baud_count & 1) && baud_count <= 4096)\n {\n UCSRA = (1<<U2X); \/\/double speed uart\n UBRR = baud_count - 1;\n }\n else\n {\n UCSRA = 0;\n UBRR = (baud_count >> 1) - 1;\n }\n\n \/\/8 bit, no parity, 1 stop bit\n UCSRC = (1<<UCSZ1) | (1<<UCSZ0);\n\n \/\/enable receiver, transmitter and receive interrupt\n UCSRB = (1<<RXEN) | (1<<TXEN) | (1<<RXCIE);\n\n RingBuffer_InitBuffer(&rxBuffer);\n RingBuffer_InitBuffer(&txBuffer);\n\n #ifndef BOARD_A_xu2\n #if defined(BOARD_A_MEGA) || defined(BOARD_A_UNO)\n \/\/enable od format immediately for these boards\n setOD_UART();\n #else\n midi.handleUARTread(board.MIDIread_UART);\n midi.handleUARTwrite(board.MIDIwrite_UART);\n #endif\n #endif\n}\n\nint16_t Board::MIDIread_UART()\n{\n if (RingBuffer_IsEmpty(&rxBuffer))\n {\n return -1;\n }\n\n uint8_t data = RingBuffer_Remove(&rxBuffer);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO) && !defined(BOARD_A_xu2)\n MIDIreceived = true;\n #endif\n return data;\n}\n\nint8_t Board::MIDIwrite_UART(uint8_t data)\n{\n \/\/if both the outgoing buffer and the UART data register are empty\n \/\/write the byte to the data register directly\n if (RingBuffer_IsEmpty(&txBuffer) && (UCSRA & (1<<UDRE)))\n {\n ATOMIC_BLOCK(ATOMIC_RESTORESTATE)\n {\n UDR = data;\n }\n\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n #endif\n\n return 1;\n }\n\n while (RingBuffer_IsFull(&txBuffer));\n RingBuffer_Insert(&txBuffer, data);\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO)\n MIDIsent = true;\n #endif\n\n return 1;\n}\n\nbool Board::MIDIwrite_UART_OD(USBMIDIpacket_t& USBMIDIpacket)\n{\n RingBuffer_Insert(&txBuffer, 0xF1);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Event);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data1);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data2);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Data3);\n RingBuffer_Insert(&txBuffer, USBMIDIpacket.Event ^ USBMIDIpacket.Data1 ^ USBMIDIpacket.Data2 ^ USBMIDIpacket.Data3);\n\n UCSRB |= (1<<UDRIE);\n #if !defined(BOARD_A_MEGA) && !defined(BOARD_A_UNO) && !defined(BOARD_A_xu2)\n MIDIsent = true;\n #endif\n\n return true;\n}\n\nbool Board::MIDIread_UART_OD()\n{\n if (RingBuffer_GetCount(&rxBuffer) >= 6)\n {\n int16_t data = MIDIread_UART();\n\n if (data == 0xF1)\n {\n \/\/start of frame, read rest of the packet\n for (int i=0; i<5; i++)\n {\n data = MIDIread_UART();\n\n switch(i)\n {\n case 0:\n usbMIDIpacket.Event = data;\n break;\n\n case 1:\n usbMIDIpacket.Data1 = data;\n break;\n\n case 2:\n usbMIDIpacket.Data2 = data;\n break;\n\n case 3:\n usbMIDIpacket.Data3 = data;\n break;\n\n case 4:\n \/\/xor byte, do nothing\n break;\n }\n }\n\n \/\/error check\n uint8_t dataXOR = usbMIDIpacket.Event ^ usbMIDIpacket.Data1 ^ usbMIDIpacket.Data2 ^ usbMIDIpacket.Data3;\n\n return (dataXOR == data);\n }\n }\n\n return false;\n}\n\nbool usbRead_od(USBMIDIpacket_t& USBMIDIpacket)\n{\n return board.MIDIread_UART_OD();\n}\n\nvoid Board::setUARTloopbackState(bool state)\n{\n loopbackEnabled = state;\n}\n\nbool Board::getUARTloopbackState()\n{\n return loopbackEnabled;\n}\n\nbool Board::isRXempty()\n{\n return RingBuffer_IsEmpty(&rxBuffer);\n}\n\nbool Board::isTXempty()\n{\n return RingBuffer_IsEmpty(&txBuffer);\n}\n\nvoid Board::setOD_UART()\n{\n #ifdef BOARD_OPEN_DECK\n if (isUSBconnected())\n {\n \/\/master board\n midi.handleUSBread(board.MIDIread_USB_write_UART_OD);\n midi.handleUSBwrite(board.MIDIwrite_USB);\n midi.handleUARTread(NULL); \/\/parsed internally\n midi.handleUARTwrite(NULL);\n }\n else\n {\n \/\/slave\n midi.handleUSBread(usbRead_od); \/\/loopback used on inner slaves\n midi.handleUSBwrite(board.MIDIwrite_UART_OD);\n midi.handleUARTread(NULL);\n midi.handleUARTwrite(NULL);\n }\n\n odUARTconfigured = true;\n #elif defined(BOARD_A_MEGA) || defined(BOARD_A_UNO)\n midi.handleUSBread(usbRead_od);\n midi.handleUSBwrite(board.MIDIwrite_UART_OD);\n midi.handleUARTread(NULL);\n midi.handleUARTwrite(NULL);\n odUARTconfigured = true;\n #endif\n}\n\nbool Board::getOD_UART()\n{\n return odUARTconfigured;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _MATH_VECTOR_HPP\n#define _MATH_VECTOR_HPP\n\n#include <cmath>\n#include <numeric>\n#include <iterator>\n#include <algorithm>\n#include <type_traits>\n#include <iosfwd>\n\nnamespace math {\n\n\tnamespace internal {\n\t\ttemplate <typename _T, std::size_t _N>\n\t\tstruct vector_base {\n\t\tprivate:\n\t\t\t_T _data[_N];\n\n\t\tpublic:\n\t\t\t_T& operator [](std::size_t index) noexcept { return _data[index]; }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return _data[index]; }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 2> {\n\t\t\t_T x, y;\n\n\t\t\tvector_base(_T x, _T y) : x(x), y(y) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 3> {\n\t\t\t_T x, y, z;\n\n\t\t\tvector_base(_T x, _T y, _T z = static_cast<_T>(1))\n\t\t\t\t: x(x), y(y), z(z) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 4> {\n\t\t\t_T x, y, z, w;\n\n\t\t\tvector_base(_T x, _T y, _T z, _T w = static_cast<_T>(1))\n\t\t\t\t: x(x), y(y), z(z), w(w) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\t}\n\n\ttemplate <typename _T, std::size_t _N>\n\tstruct vector : public internal::vector_base<_T, _N> {\n\t\tstatic_assert(std::is_arithmetic<_T>::value, \"vector<_T> requires arithmetic type.\");\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ type definitions.\n\n\t\ttypedef _T value_type;\n\t\ttypedef _T* pointer;\n\t\ttypedef _T& reference;\n\t\ttypedef _T const* const_pointer;\n\t\ttypedef _T const& const_reference;\n\t\ttypedef std::size_t size_type;\n\n\t\ttypedef _T* iterator;\n\t\ttypedef _T const* const_iterator;\n\t\ttypedef std::reverse_iterator<iterator> reverse_iterator;\n\t\ttypedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ construction.\n\n\t\tusing internal::vector_base<_T, _N>::vector_base;\n\n\t\tconstexpr vector operator -() const noexcept { return *this; }\n\t\tconstexpr vector operator +() const noexcept { return *this; }\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ compound arithmetic operators.\n\n\t\tvector& operator += (vector const& other) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), other.begin(),\n\t\t\t\tthis->begin(), std::plus<_T>());\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator -= (vector const& other) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), other.begin(),\n\t\t\t\tthis->begin(), std::minus<_T>());\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator *= (value_type scalar) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), this->begin(),\n\t\t\t\tstd::bind(std::multiplies<_T>(), std::placeholders::_1, scalar));\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator \/= (value_type scalar) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), this->begin(),\n\t\t\t\tstd::bind(std::divides<_T>(), std::placeholders::_1, scalar));\n\t\t\treturn *this;\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ methods.\n\n\t\ttypename std::common_type<_T, float>::type length() const noexcept{\n\t\t\treturn std::sqrt(this->length_sqr());\n\t\t}\n\n\t\ttypename std::common_type<_T, float>::type length_sqr() const noexcept {\n\t\t\treturn dot_product(*this, *this);\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ iteration.\n\n\t\titerator begin() noexcept { return std::addressof((*this)[0]); }\n\t\titerator end() noexcept { return std::addressof((*this)[_N]); }\n\n\t\tconst_iterator begin() const noexcept { return std::addressof((*this)[0]); }\n\t\tconst_iterator end() const noexcept { return std::addressof((*this)[_N]); }\n\n\t\tconst_iterator cbegin() const noexcept { return std::addressof((*this)[0]); }\n\t\tconst_iterator cend() const noexcept { return std::addressof((*this)[_N]); }\n\n\t\treverse_iterator rbegin() noexcept { return this->end(); }\n\t\treverse_iterator rend() noexcept { return this->begin(); }\n\n\t\tconst_reverse_iterator rbegin() const noexcept { return this->end(); }\n\t\tconst_reverse_iterator rend() const noexcept { return this->begin(); }\n\n\t\tconst_reverse_iterator crbegin() const noexcept { return this->cend(); }\n\t\tconst_reverse_iterator crend() const noexcept { return this->cbegin(); }\n\t};\n\n\ttemplate <typename _T> using vector2 = vector<_T, 2>;\n\ttemplate <typename _T> using vector3 = vector<_T, 3>;\n\ttemplate <typename _T> using vector4 = vector<_T, 4>;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tbool operator == (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tbool operator != (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator + (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(lhs) += rhs;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator - (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(lhs) -= rhs;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator * (vector<_T, _N> const& vec, _U scalar) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) *= scalar;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator * (_T scalar, vector<_U, _N> const& vec) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) *= scalar;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator \/ (vector<_T, _N> const& vec, _U scalar) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) \/= scalar;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\ttypename std::common_type<_T, _U, float>::type dot_product(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U, float>::type common_t;\n\t\treturn std::inner_product(lhs.begin(), lhs.end(), rhs.begin(), static_cast<common_t>(0));\n\t}\n\n \ttemplate <typename _T, typename _U, std::size_t _N>\n \tvector<typename std::common_type<_T, _U, float>::type, _N> projection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {\n\t\treturn dot_product(vec, n) \/ dot_product(n, n) * n;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n \tvector<typename std::common_type<_T, _U, float>::type, _N> reflection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {\n\t\ttypedef typename std::common_type<_T, _U, float>::type common_t;\n\t\treturn vec - static_cast<common_t>(2) * projection(vec, n);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _Elem, typename _Traits, typename _T, std::size_t _N>\n\tstd::basic_ostream<_Elem, _Traits>& operator << (std::basic_ostream<_Elem, _Traits>& os, vector<_T, _N> const& vec) {\n\t\tstd::copy(vec.begin(), vec.end(), std::ostream_iterator<_T, _Elem, _Traits>(os, \" \"));\n\t\treturn os << '\\b';\n\t}\n}\n\n\n#endif \/\/ _MATH_VECTOR_HPP<commit_msg>Add comma seperator when outputing vector with stream operator<commit_after>#ifndef _MATH_VECTOR_HPP\n#define _MATH_VECTOR_HPP\n\n#include <cmath>\n#include <numeric>\n#include <iterator>\n#include <algorithm>\n#include <type_traits>\n#include <iosfwd>\n\nnamespace math {\n\n\tnamespace internal {\n\t\ttemplate <typename _T, std::size_t _N>\n\t\tstruct vector_base {\n\t\tprivate:\n\t\t\t_T _data[_N];\n\n\t\tpublic:\n\t\t\t_T& operator [](std::size_t index) noexcept { return _data[index]; }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return _data[index]; }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 2> {\n\t\t\t_T x, y;\n\n\t\t\tvector_base(_T x, _T y) : x(x), y(y) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 3> {\n\t\t\t_T x, y, z;\n\n\t\t\tvector_base(_T x, _T y, _T z = static_cast<_T>(1))\n\t\t\t\t: x(x), y(y), z(z) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\n\t\ttemplate <typename _T>\n\t\tstruct vector_base<_T, 4> {\n\t\t\t_T x, y, z, w;\n\n\t\t\tvector_base(_T x, _T y, _T z, _T w = static_cast<_T>(1))\n\t\t\t\t: x(x), y(y), z(z), w(w) {}\n\n\t\t\t_T& operator [](std::size_t index) noexcept { return *(reinterpret_cast<_T*>(this) + index); }\n\t\t\t_T const& operator [](std::size_t index) const noexcept { return *(reinterpret_cast<_T const*>(this) + index); }\n\t\t};\n\t}\n\n\ttemplate <typename _T, std::size_t _N>\n\tstruct vector : public internal::vector_base<_T, _N> {\n\t\tstatic_assert(std::is_arithmetic<_T>::value, \"vector<_T> requires arithmetic type.\");\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ type definitions.\n\n\t\ttypedef _T value_type;\n\t\ttypedef _T* pointer;\n\t\ttypedef _T& reference;\n\t\ttypedef _T const* const_pointer;\n\t\ttypedef _T const& const_reference;\n\t\ttypedef std::size_t size_type;\n\n\t\ttypedef _T* iterator;\n\t\ttypedef _T const* const_iterator;\n\t\ttypedef std::reverse_iterator<iterator> reverse_iterator;\n\t\ttypedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ construction.\n\n\t\tusing internal::vector_base<_T, _N>::vector_base;\n\n\t\tconstexpr vector operator -() const noexcept { return *this; }\n\t\tconstexpr vector operator +() const noexcept { return *this; }\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ compound arithmetic operators.\n\n\t\tvector& operator += (vector const& other) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), other.begin(),\n\t\t\t\tthis->begin(), std::plus<_T>());\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator -= (vector const& other) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), other.begin(),\n\t\t\t\tthis->begin(), std::minus<_T>());\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator *= (value_type scalar) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), this->begin(),\n\t\t\t\tstd::bind(std::multiplies<_T>(), std::placeholders::_1, scalar));\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector& operator \/= (value_type scalar) noexcept {\n\t\t\tstd::transform(this->begin(), this->end(), this->begin(),\n\t\t\t\tstd::bind(std::divides<_T>(), std::placeholders::_1, scalar));\n\t\t\treturn *this;\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ methods.\n\n\t\ttypename std::common_type<_T, float>::type length() const noexcept{\n\t\t\treturn std::sqrt(this->length_sqr());\n\t\t}\n\n\t\ttypename std::common_type<_T, float>::type length_sqr() const noexcept {\n\t\t\treturn dot_product(*this, *this);\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ iteration.\n\n\t\titerator begin() noexcept { return std::addressof((*this)[0]); }\n\t\titerator end() noexcept { return std::addressof((*this)[_N]); }\n\n\t\tconst_iterator begin() const noexcept { return std::addressof((*this)[0]); }\n\t\tconst_iterator end() const noexcept { return std::addressof((*this)[_N]); }\n\n\t\tconst_iterator cbegin() const noexcept { return std::addressof((*this)[0]); }\n\t\tconst_iterator cend() const noexcept { return std::addressof((*this)[_N]); }\n\n\t\treverse_iterator rbegin() noexcept { return this->end(); }\n\t\treverse_iterator rend() noexcept { return this->begin(); }\n\n\t\tconst_reverse_iterator rbegin() const noexcept { return this->end(); }\n\t\tconst_reverse_iterator rend() const noexcept { return this->begin(); }\n\n\t\tconst_reverse_iterator crbegin() const noexcept { return this->cend(); }\n\t\tconst_reverse_iterator crend() const noexcept { return this->cbegin(); }\n\t};\n\n\ttemplate <typename _T> using vector2 = vector<_T, 2>;\n\ttemplate <typename _T> using vector3 = vector<_T, 3>;\n\ttemplate <typename _T> using vector4 = vector<_T, 4>;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tbool operator == (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tbool operator != (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator + (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(lhs) += rhs;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator - (vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(lhs) -= rhs;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator * (vector<_T, _N> const& vec, _U scalar) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) *= scalar;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator * (_T scalar, vector<_U, _N> const& vec) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) *= scalar;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\tvector<typename std::common_type<_T, _U>::type, _N> operator \/ (vector<_T, _N> const& vec, _U scalar) {\n\t\ttypedef typename std::common_type<_T, _U>::type common_t;\n\t\treturn vector<common_t, _N>(vec) \/= scalar;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n\ttypename std::common_type<_T, _U, float>::type dot_product(vector<_T, _N> const& lhs, vector<_U, _N> const& rhs) {\n\t\ttypedef typename std::common_type<_T, _U, float>::type common_t;\n\t\treturn std::inner_product(lhs.begin(), lhs.end(), rhs.begin(), static_cast<common_t>(0));\n\t}\n\n \ttemplate <typename _T, typename _U, std::size_t _N>\n \tvector<typename std::common_type<_T, _U, float>::type, _N> projection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {\n\t\treturn dot_product(vec, n) \/ dot_product(n, n) * n;\n\t}\n\n\ttemplate <typename _T, typename _U, std::size_t _N>\n \tvector<typename std::common_type<_T, _U, float>::type, _N> reflection(vector<_T, _N> const& vec, vector<_U, _N> const& n) {\n\t\ttypedef typename std::common_type<_T, _U, float>::type common_t;\n\t\treturn vec - static_cast<common_t>(2) * projection(vec, n);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ttemplate <typename _Elem, typename _Traits, typename _T, std::size_t _N>\n\tstd::basic_ostream<_Elem, _Traits>& operator << (std::basic_ostream<_Elem, _Traits>& os, vector<_T, _N> const& vec) {\n\t\tstd::copy(vec.begin(), vec.end(), std::ostream_iterator<_T, _Elem, _Traits>(os, \", \"));\n\t\treturn os << \"\\b\\b \\b\";\n\t}\n}\n\n\n#endif \/\/ _MATH_VECTOR_HPP<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions\n * \n * This file is part of WATCHER.\n * \n * WATCHER is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * WATCHER is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n * \n * You should have received a copy of the GNU Affero General Public License\n * along with Watcher. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <libwatcher\/messageStream.h>\n#include <libwatcher\/dataPointMessage.h>\n#include <libwatcher\/playbackTimeRange.h>\n#include <libwatcher\/speedWatcherMessage.h>\n#include <libwatcher\/seekWatcherMessage.h>\n#include <libwatcher\/messageTypesAndVersions.h>\n#include <libwatcher\/listStreamsMessage.h>\n\n#include <logger.h>\n\n#include \"watcherMainWindow.h\"\n#include \"watcherConfig.h\"\n#include \"seriesGraphDialog.h\"\n#include \"watcherStreamListDialog.h\"\n\nnamespace watcher {\n\nnamespace config {\n extern int StreamUid;\n} \/\/ namespace\n\nnamespace ui {\n\nINIT_LOGGER(MainWindow, \"MainWindow\");\n\nTimestamp EpochTS; \/\/ the timestamp of the first message in the event stream\nTimestamp MaxTS; \/\/ the timestamp of the last event in the stream\nTimestamp CurrentTS;\nMessageStreamPtr MsgStream;\n\nMainWindow::MainWindow() : checkIOThread(0), streamsDialog(0)\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nvoid MainWindow::dataPointHandler(const QString& dataName, const QString& fromID, const QString& \/*layer*\/, qlonglong when, double value)\n{\n TRACE_ENTER();\n\n SeriesGraphDialog *series;\n SeriesMap::iterator it = seriesMap.find(dataName);\n if (it == seriesMap.end()) {\n\tLOG_INFO(\"found new data series \" << dataName.toStdString());\n\t\/* not found, create a new menu item *\/\n\tseries = new SeriesGraphDialog(dataName);\n\tseriesMap[dataName] = series;\n\tmenuSeries->addAction(dataName, series, SLOT(show()));\n\tQObject::connect(this, SIGNAL(clockTick(qlonglong)), series, SLOT(handleClock(qlonglong)));\n\tQObject::connect(series, SIGNAL(seekStream(qlonglong)), this, SLOT(seekStream(qlonglong)));\n } else {\n\tseries = it->second;\n }\n series->dataPoint(fromID, when, value);\n\n TRACE_EXIT();\n}\n\nvoid MainWindow::checkIO()\n{\n TRACE_ENTER();\n\n MsgStream = MessageStreamPtr(new MessageStream(watcher::config::Server));\n MsgStream->connect(true);\n MsgStream->getMessageTimeRange();\n if (watcher::config::StreamUid == -1) {\n\tMsgStream->setDescription(\"data Watcher\");\n\tMsgStream->startStream();\n } else {\n\tMsgStream->subscribeToStream(watcher::config::StreamUid);\n }\n\n \/\/ We only care about data point (and (some) control) messages. \n MessageStreamFilterPtr f(new MessageStreamFilter); \n unsigned int ourMessageTypes[] = { DATA_POINT_MESSAGE_TYPE, PLAYBACK_TIME_RANGE_MESSAGE_TYPE, \n SPEED_MESSAGE_TYPE, SEEK_MESSAGE_TYPE, LIST_STREAMS_MESSAGE_TYPE }; \n for (size_t t=0; t<(sizeof(ourMessageTypes)\/sizeof(ourMessageTypes[0])); t++) \n f->addMessageType(ourMessageTypes[t]); \n MsgStream->addMessageFilter(f);\n\n MessagePtr msg;\n QString layer;\n while (MsgStream->getNextMessage(msg)) {\n if (watcher::event::isFeederEvent(msg->type))\n LOG_DEBUG(\"Got feeder message of type: \" << msg->type); \n\tif (msg->type == DATA_POINT_MESSAGE_TYPE) {\n\t LOG_DEBUG(\"got DataPointMessage\");\n\t CurrentTS = msg->timestamp;\n\t if (CurrentTS > MaxTS)\n\t\tMaxTS = CurrentTS;\n\t emit clockTick(msg->timestamp);\n\t watcher::event::DataPointMessagePtr dp = boost::dynamic_pointer_cast<DataPointMessage>(msg);\n\t \/\/ TODO:\n\t \/\/ - add layer when DataPointMessage supports its\n\t \/\/ - support data point messages for edges as well\n\t emit dataPointReceived(QString::fromStdString(dp->dataName),\n\t\t QString::fromStdString(dp->fromNodeID.to_string()),\n\t\t layer, dp->timestamp, dp->dataPoints.front());\n\t} else if (msg->type == PLAYBACK_TIME_RANGE_MESSAGE_TYPE) {\n\t LOG_DEBUG(\"got playback time range\");\n\t watcher::event::PlaybackTimeRangeMessagePtr m = boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(msg);\n\t EpochTS = m->min_;\n\t MaxTS = m->max_;\n\t LOG_INFO(\"epoch TS = \" << EpochTS << \", max TS = \" << MaxTS);\n\t} else if (msg->type == SPEED_MESSAGE_TYPE) {\n\t watcher::event::SpeedMessagePtr sm = boost::dynamic_pointer_cast<SpeedMessage>(msg);\n\t} else if (msg->type == SEEK_MESSAGE_TYPE) {\n\t watcher::event::SeekMessagePtr sm = boost::dynamic_pointer_cast<SeekMessage>(msg);\n\t} else if (msg->type == LIST_STREAMS_MESSAGE_TYPE) {\n\t watcher::event::ListStreamsMessagePtr lsm = boost::dynamic_pointer_cast<ListStreamsMessage>(msg);\n\t for (size_t i = 0; i < lsm->evstreams.size(); ++i) {\n\t\tEventStreamInfoPtr ev ( lsm->evstreams[i] );\n\t\tstreamsDialog->addStream(ev->uid, ev->description);\n\t }\n\t} else {\n \/\/ GTL - should not happen except at start as we're filtering by message type.\n LOG_WARN(\"Recv'd unwanted message type\"); \n\t}\n }\n\n TRACE_EXIT();\n}\n\nvoid MainWindow::setup()\n{\n TRACE_ENTER();\n\n setupUi(this);\n QObject::connect(this,\n\tSIGNAL(dataPointReceived(const QString& , const QString& , const QString& , qlonglong , double )),\n \tthis,\n\tSLOT(dataPointHandler(const QString& , const QString& , const QString& , qlonglong , double )));\n\n QObject::connect(actionChange_Stream, SIGNAL(triggered()), this, SLOT(listStreams()));\n\n LOG_INFO(\"spawning checkIO thread\");\n checkIOThread = new boost::thread(&MainWindow::checkIO, this);\n\n TRACE_EXIT();\n}\n\n\/** Slot for receiving seek requests\n * @param t the watcher::Timestamp value to seek to (milliseconds)\n *\/\nvoid MainWindow::seekStream(qlonglong t)\n{\n TRACE_ENTER();\n LOG_INFO(\"seeking to \" << t);\n MsgStream->setStreamTimeStart(t);\n TRACE_EXIT();\n}\n\n\/** Slot to open the change stream dialog. *\/\nvoid MainWindow::listStreams()\n{\n TRACE_ENTER();\n if (!streamsDialog) {\n\tstreamsDialog = new WatcherStreamListDialog;\n\tconnect(streamsDialog, SIGNAL(streamChanged(unsigned long)), this, SLOT(selectStream(unsigned long)));\n\tconnect(streamsDialog->refreshButton, SIGNAL(clicked()), this, SLOT(listStreams()));\n\tconnect(streamsDialog, SIGNAL(reconnect()), this, SLOT(reconnect()));\n }\n streamsDialog->treeWidget->clear();\n streamsDialog->show();\n\n MsgStream->listStreams();\n TRACE_EXIT();\n}\n\n\/** Slot to select a new stream. *\/\nvoid MainWindow::selectStream(unsigned long uid)\n{\n TRACE_ENTER();\n LOG_INFO(\"subscribing to new stream uid \" << uid);\n MsgStream->clearMessageCache();\n MsgStream->subscribeToStream(uid);\n closeAllGraphs();\n TRACE_EXIT();\n}\n\n\/** Slot for receiving the reconnect stream signal from the change stream dialog. *\/\nvoid MainWindow::reconnect()\n{\n TRACE_ENTER();\n LOG_INFO(\"reconnecting to server upon user request\");\n MsgStream->clearMessageCache();\n MsgStream->reconnect();\n closeAllGraphs();\n TRACE_EXIT();\n}\n\nvoid MainWindow::closeAllGraphs()\n{\n TRACE_ENTER();\n for (SeriesMap::iterator it = seriesMap.begin(); it != seriesMap.end(); ++it)\n\tit->second->close();\n seriesMap.clear();\n menuSeries->clear();\n TRACE_EXIT();\n}\n\n} \/\/ ui\n} \/\/ watcher\n\n\/\/ vim:sw=4\n<commit_msg>Ensure the connection to watcherd is active before opening the list streams dialog in order to avoid locking up.<commit_after>\/* Copyright 2010 SPARTA, Inc., dba Cobham Analytic Solutions\n * \n * This file is part of WATCHER.\n * \n * WATCHER is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * WATCHER is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n * \n * You should have received a copy of the GNU Affero General Public License\n * along with Watcher. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <libwatcher\/messageStream.h>\n#include <libwatcher\/dataPointMessage.h>\n#include <libwatcher\/playbackTimeRange.h>\n#include <libwatcher\/speedWatcherMessage.h>\n#include <libwatcher\/seekWatcherMessage.h>\n#include <libwatcher\/messageTypesAndVersions.h>\n#include <libwatcher\/listStreamsMessage.h>\n\n#include <logger.h>\n\n#include \"watcherMainWindow.h\"\n#include \"watcherConfig.h\"\n#include \"seriesGraphDialog.h\"\n#include \"watcherStreamListDialog.h\"\n\nnamespace watcher {\n\nnamespace config {\n extern int StreamUid;\n} \/\/ namespace\n\nnamespace ui {\n\nINIT_LOGGER(MainWindow, \"MainWindow\");\n\nTimestamp EpochTS; \/\/ the timestamp of the first message in the event stream\nTimestamp MaxTS; \/\/ the timestamp of the last event in the stream\nTimestamp CurrentTS;\nMessageStreamPtr MsgStream;\n\nMainWindow::MainWindow() : checkIOThread(0), streamsDialog(0)\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nvoid MainWindow::dataPointHandler(const QString& dataName, const QString& fromID, const QString& \/*layer*\/, qlonglong when, double value)\n{\n TRACE_ENTER();\n\n SeriesGraphDialog *series;\n SeriesMap::iterator it = seriesMap.find(dataName);\n if (it == seriesMap.end()) {\n\tLOG_INFO(\"found new data series \" << dataName.toStdString());\n\t\/* not found, create a new menu item *\/\n\tseries = new SeriesGraphDialog(dataName);\n\tseriesMap[dataName] = series;\n\tmenuSeries->addAction(dataName, series, SLOT(show()));\n\tQObject::connect(this, SIGNAL(clockTick(qlonglong)), series, SLOT(handleClock(qlonglong)));\n\tQObject::connect(series, SIGNAL(seekStream(qlonglong)), this, SLOT(seekStream(qlonglong)));\n } else {\n\tseries = it->second;\n }\n series->dataPoint(fromID, when, value);\n\n TRACE_EXIT();\n}\n\nvoid MainWindow::checkIO()\n{\n TRACE_ENTER();\n\n MsgStream = MessageStreamPtr(new MessageStream(watcher::config::Server));\n MsgStream->connect(true);\n MsgStream->getMessageTimeRange();\n if (watcher::config::StreamUid == -1) {\n\tMsgStream->setDescription(\"data Watcher\");\n\tMsgStream->startStream();\n } else {\n\tMsgStream->subscribeToStream(watcher::config::StreamUid);\n }\n\n \/\/ We only care about data point (and (some) control) messages. \n MessageStreamFilterPtr f(new MessageStreamFilter); \n unsigned int ourMessageTypes[] = { DATA_POINT_MESSAGE_TYPE, PLAYBACK_TIME_RANGE_MESSAGE_TYPE, \n SPEED_MESSAGE_TYPE, SEEK_MESSAGE_TYPE, LIST_STREAMS_MESSAGE_TYPE }; \n for (size_t t=0; t<(sizeof(ourMessageTypes)\/sizeof(ourMessageTypes[0])); t++) \n f->addMessageType(ourMessageTypes[t]); \n MsgStream->addMessageFilter(f);\n\n MessagePtr msg;\n QString layer;\n while (MsgStream->getNextMessage(msg)) {\n if (watcher::event::isFeederEvent(msg->type))\n LOG_DEBUG(\"Got feeder message of type: \" << msg->type); \n\tif (msg->type == DATA_POINT_MESSAGE_TYPE) {\n\t LOG_DEBUG(\"got DataPointMessage\");\n\t CurrentTS = msg->timestamp;\n\t if (CurrentTS > MaxTS)\n\t\tMaxTS = CurrentTS;\n\t emit clockTick(msg->timestamp);\n\t watcher::event::DataPointMessagePtr dp = boost::dynamic_pointer_cast<DataPointMessage>(msg);\n\t \/\/ TODO:\n\t \/\/ - add layer when DataPointMessage supports its\n\t \/\/ - support data point messages for edges as well\n\t emit dataPointReceived(QString::fromStdString(dp->dataName),\n\t\t QString::fromStdString(dp->fromNodeID.to_string()),\n\t\t layer, dp->timestamp, dp->dataPoints.front());\n\t} else if (msg->type == PLAYBACK_TIME_RANGE_MESSAGE_TYPE) {\n\t LOG_DEBUG(\"got playback time range\");\n\t watcher::event::PlaybackTimeRangeMessagePtr m = boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(msg);\n\t EpochTS = m->min_;\n\t MaxTS = m->max_;\n\t LOG_INFO(\"epoch TS = \" << EpochTS << \", max TS = \" << MaxTS);\n\t} else if (msg->type == SPEED_MESSAGE_TYPE) {\n\t watcher::event::SpeedMessagePtr sm = boost::dynamic_pointer_cast<SpeedMessage>(msg);\n\t} else if (msg->type == SEEK_MESSAGE_TYPE) {\n\t watcher::event::SeekMessagePtr sm = boost::dynamic_pointer_cast<SeekMessage>(msg);\n\t} else if (msg->type == LIST_STREAMS_MESSAGE_TYPE) {\n\t watcher::event::ListStreamsMessagePtr lsm = boost::dynamic_pointer_cast<ListStreamsMessage>(msg);\n\t for (size_t i = 0; i < lsm->evstreams.size(); ++i) {\n\t\tEventStreamInfoPtr ev ( lsm->evstreams[i] );\n\t\tstreamsDialog->addStream(ev->uid, ev->description);\n\t }\n\t} else {\n \/\/ GTL - should not happen except at start as we're filtering by message type.\n LOG_WARN(\"Recv'd unwanted message type\"); \n\t}\n }\n\n TRACE_EXIT();\n}\n\nvoid MainWindow::setup()\n{\n TRACE_ENTER();\n\n setupUi(this);\n QObject::connect(this,\n\tSIGNAL(dataPointReceived(const QString& , const QString& , const QString& , qlonglong , double )),\n \tthis,\n\tSLOT(dataPointHandler(const QString& , const QString& , const QString& , qlonglong , double )));\n\n QObject::connect(actionChange_Stream, SIGNAL(triggered()), this, SLOT(listStreams()));\n\n LOG_INFO(\"spawning checkIO thread\");\n checkIOThread = new boost::thread(&MainWindow::checkIO, this);\n\n TRACE_EXIT();\n}\n\n\/** Slot for receiving seek requests\n * @param t the watcher::Timestamp value to seek to (milliseconds)\n *\/\nvoid MainWindow::seekStream(qlonglong t)\n{\n TRACE_ENTER();\n LOG_INFO(\"seeking to \" << t);\n MsgStream->setStreamTimeStart(t);\n TRACE_EXIT();\n}\n\n\/** Slot to open the change stream dialog. *\/\nvoid MainWindow::listStreams()\n{\n TRACE_ENTER();\n if (MsgStream->connected()) {\n\tif (!streamsDialog) {\n\t streamsDialog = new WatcherStreamListDialog;\n\t connect(streamsDialog, SIGNAL(streamChanged(unsigned long)), this, SLOT(selectStream(unsigned long)));\n\t connect(streamsDialog->refreshButton, SIGNAL(clicked()), this, SLOT(listStreams()));\n\t connect(streamsDialog, SIGNAL(reconnect()), this, SLOT(reconnect()));\n\t}\n\tstreamsDialog->treeWidget->clear();\n\tstreamsDialog->show();\n\n\tMsgStream->listStreams();\n } else {\n\tLOG_WARN(\"unable to list streams; not connected to watcherd\");\n }\n TRACE_EXIT();\n}\n\n\/** Slot to select a new stream. *\/\nvoid MainWindow::selectStream(unsigned long uid)\n{\n TRACE_ENTER();\n LOG_INFO(\"subscribing to new stream uid \" << uid);\n if (MsgStream->connected()) {\n\tMsgStream->clearMessageCache();\n\tMsgStream->subscribeToStream(uid);\n\tcloseAllGraphs();\n } else {\n\tLOG_WARN(\"unable to select stream; not connected to watcherd\");\n }\n TRACE_EXIT();\n}\n\n\/** Slot for receiving the reconnect stream signal from the change stream dialog. *\/\nvoid MainWindow::reconnect()\n{\n TRACE_ENTER();\n LOG_INFO(\"reconnecting to server upon user request\");\n MsgStream->clearMessageCache();\n MsgStream->reconnect();\n closeAllGraphs();\n TRACE_EXIT();\n}\n\nvoid MainWindow::closeAllGraphs()\n{\n TRACE_ENTER();\n for (SeriesMap::iterator it = seriesMap.begin(); it != seriesMap.end(); ++it)\n\tit->second->close();\n seriesMap.clear();\n menuSeries->clear();\n TRACE_EXIT();\n}\n\n} \/\/ ui\n} \/\/ watcher\n\n\/\/ vim:sw=4\n<|endoftext|>"} {"text":"<commit_before>#include <osgGA\/KeySwitchCameraManipulator>\n#include <osg\/Notify>\n\nusing namespace osgGA;\n\nvoid KeySwitchCameraManipulator::addCameraManipulator(int key, std::string name, CameraManipulator *cm)\n{\n if(!cm) return;\n\n _manips[key]=std::make_pair(name,osg::ref_ptr<CameraManipulator>(cm));\n if(!_current.valid()){\n _current=cm;\n }\n}\n\nbool KeySwitchCameraManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)\n{\n if(ea.getEventType()==GUIEventAdapter::KEYBOARD){\n\n KeyManipMap::iterator it=_manips.find(ea.getKey());\n if(it != _manips.end()){\n osg::notify(osg::INFO)<<\"Switching to manipulator: \"<<(*it).second.first<<std::endl;\n cout<<\"***Switching to manipulator: \"<<(*it).second.first<<std::endl;\n it->second.second->setNode(_current->getNode());\n it->second.second->setCamera(_current->getCamera());\n it->second.second->init(ea,aa);\n _current = it->second.second;\n\n \/\/_cameraManipChangeCallbacks.notify(this);\n\n }\n }\n\n return _current->handle(ea,aa);\n}\n\n\/\/ void KeySwitchCameraManipulator::addCallback(Callback* c)\n\/\/ {\n\/\/ _cameraManipChangeCallbacks.addCallback(c);\n\/\/ }\n\/\/ \n\/\/ void KeySwitchCameraManipulator::removeCallback(Callback* c)\n\/\/ {\n\/\/ _cameraManipChangeCallbacks.removeCallback(c);\n\/\/ }\n<commit_msg>Small std::cout fix<commit_after>#include <osgGA\/KeySwitchCameraManipulator>\n#include <osg\/Notify>\n\nusing namespace osgGA;\n\nvoid KeySwitchCameraManipulator::addCameraManipulator(int key, std::string name, CameraManipulator *cm)\n{\n if(!cm) return;\n\n _manips[key]=std::make_pair(name,osg::ref_ptr<CameraManipulator>(cm));\n if(!_current.valid()){\n _current=cm;\n }\n}\n\nbool KeySwitchCameraManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& aa)\n{\n if(ea.getEventType()==GUIEventAdapter::KEYBOARD){\n\n KeyManipMap::iterator it=_manips.find(ea.getKey());\n if(it != _manips.end()){\n osg::notify(osg::INFO)<<\"Switching to manipulator: \"<<(*it).second.first<<std::endl;\n std::cout<<\"***Switching to manipulator: \"<<(*it).second.first<<std::endl;\n it->second.second->setNode(_current->getNode());\n it->second.second->setCamera(_current->getCamera());\n it->second.second->init(ea,aa);\n _current = it->second.second;\n\n \/\/_cameraManipChangeCallbacks.notify(this);\n\n }\n }\n\n return _current->handle(ea,aa);\n}\n\n\/\/ void KeySwitchCameraManipulator::addCallback(Callback* c)\n\/\/ {\n\/\/ _cameraManipChangeCallbacks.addCallback(c);\n\/\/ }\n\/\/ \n\/\/ void KeySwitchCameraManipulator::removeCallback(Callback* c)\n\/\/ {\n\/\/ _cameraManipChangeCallbacks.removeCallback(c);\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before>#include<cstdlib>\n#include<cstring>\n#include<fstream>\n#include<vector>\n\n#include\"global.h\"\n#include\"config.h\"\n\nstd::string Config::upackage_root;\nstd::string Config::ubuild_path;\nstd::string Config::tarball_path;\nstd::string Config::source_path;\nstd::string Config::tracker_path;\nstd::string Config::cflags;\nstd::string Config::cxxflags;\n\nvoid Config::init()\n{\n upackage_root = \"\/var\/upackage\";\n \n \/* +--------------------------------------------+\n * |Here we are checking to see if the user has |\n * |set the UPACKAGE_ROOT environment variable |\n * |and if the value set is not \"\" |\n * +--------------------------------------------+\n *\/\n if(getenv(\"UPACKAGE_ROOT\") && strcmp(getenv(\"UPACKAGE_ROOT\"), \"\"))\n {\n std::string env(getenv(\"UPACKAGE_ROOT\"));\n \n \/* +-----------------------------------------+\n * |Check to see if the user set environment |\n * |variable is correctly terminated by a '\/'|\n * +-----------------------------------------+\n *\/\n if(env[env.size() - 1] == '\/')\n {\n upackage_root = env;\n }\n else\n {\n \/* +----------------------------------------------+\n * |The environment variable must not be correctly|\n * |terminated, lets fix that and move on. |\n * +----------------------------------------------+\n *\/t\n upackage_root = env + \"\/\";\n }\n }\n\n \/* +----------------------------------------------------------+\n * |All of the directories in upackage are under upackage_root|\n * +----------------------------------------------------------+\n *\/\n \/* +-------------------+\n * |These are defaults |\n * +-------------------+\n *\/\n ubuild_path = upackage_root + \"ubuild\/\";\n tarball_path = upackage_root + \"tarballs\/\";\n source_path = upackage_root + \"sources\/\";\n tracker_path = upackage_root + \"packages\/\";\n\n cflags = \"\";\n cxxflags = \"\";\n\n \/* +--------------------------------------------------+\n * |Now we read in the global config file for upackage|\n * +--------------------------------------------------+\n *\/\n std::vector<std::string> file = read(\"\/etc\/upackage.conf\");\n\n \/* +----------------------------------------------------+\n * |If the file size is <= 0 then the file must be empty|\n * +----------------------------------------------------+\n *\/\n if(file.size() <= 0)\n {\n return;\n }\n \n \/* If we are here, then the file size is > 0, now lets parse it *\/\n\n \/* +------------------------------------------+\n * |An integer vector for storing line numbers|\n * +------------------------------------------+\n *\/\n std::vector<int> line;\n \n \/* +------------------------------------------------------+\n * |An integer vector for storing the position of each ':'|\n * +------------------------------------------------------+\n *\/\n std::vector<int> pos;\n \n for(int i = 0; i < file.size(); i++)\n {\n \/* +---------------------+\n * |Locate all of the ':'|\n * +---------------------+\n *\/\n if(file[i].find_first_of(\":\") + 1 > 0)\n {\n \/* +----------------------------------------------+\n * |Store the position and line number of each ':'|\n * +----------------------------------------------+\n *\/\n pos.push_back(file[i].find_first_of(\":\"));\n line.push_back(i);\n }\n }\n \n \/* +--------------------------------------------+\n * |A string for storing the data before the ':'|\n * +--------------------------------------------+\n *\/\n std::string key;\n \n \/* +-------------------------------------------+\n * |A string for storing the data after the ':'|\n * +-------------------------------------------+\n *\/\n std::string value;\n\n line.push_back(file.size());\n\n for(int i = 0; i < pos.size(); i++)\n {\n \/* +----------------------------------+\n * |The key is the data before the ':'|\n * +----------------------------------+\n *\/\n key = file[line[i]].substr(0, pos[i]);\n \n \/* +-----------------------------------+\n * |The value is the data after the ':'|\n * +-----------------------------------+\n *\/\n value = file[line[i]].substr(pos[i] + 1);\n\n for(int j = line[i] + 1; j < line[i + 1]; j++)\n {\n if(file[j].length() > 0)\n {\n value = value + \"\\n\" + file[j];\n }\n }\n if(!strcmp(key.c_str(), \"CFLAGS\")\n || !strcmp(key.c_str(), \"cflags\"))\n {\n cflags = value;\n }\n if(!strcmp(key.c_str(), \"CXXFLAGS\")\n || !strcmp(key.c_str(), \"cxxflags\"))\n {\n cxxflags = value;\n }\n }\n}\n\n<commit_msg>added do nothting for commented lines in config<commit_after>#include<cstdlib>\n#include<cstring>\n#include<fstream>\n#include<vector>\n\n#include\"global.h\"\n#include\"config.h\"\n\nstd::string Config::upackage_root;\nstd::string Config::ubuild_path;\nstd::string Config::tarball_path;\nstd::string Config::source_path;\nstd::string Config::tracker_path;\nstd::string Config::cflags;\nstd::string Config::cxxflags;\n\nvoid Config::init()\n{\n upackage_root = \"\/var\/upackage\/\";\n \n \/* +--------------------------------------------+\n * |Here we are checking to see if the user has |\n * |set the UPACKAGE_ROOT environment variable |\n * |and if the value set is not \"\" |\n * +--------------------------------------------+\n *\/\n if(getenv(\"UPACKAGE_ROOT\") && strcmp(getenv(\"UPACKAGE_ROOT\"), \"\"))\n {\n std::string env(getenv(\"UPACKAGE_ROOT\"));\n \n \/* +-----------------------------------------+\n * |Check to see if the user set environment |\n * |variable is correctly terminated by a '\/'|\n * +-----------------------------------------+\n *\/\n if(env[env.size() - 1] == '\/')\n {\n upackage_root = env;\n }\n else\n {\n \/* +----------------------------------------------+\n * |The environment variable must not be correctly|\n * |terminated, lets fix that and move on. |\n * +----------------------------------------------+\n *\/\n upackage_root = env + \"\/\";\n }\n }\n\n \/* +----------------------------------------------------------+\n * |All of the directories in upackage are under upackage_root|\n * +----------------------------------------------------------+\n *\/\n \/* +-------------------+\n * |These are defaults |\n * +-------------------+\n *\/\n ubuild_path = upackage_root + \"ubuild\/\";\n tarball_path = upackage_root + \"tarballs\/\";\n source_path = upackage_root + \"sources\/\";\n tracker_path = upackage_root + \"packages\/\";\n\n cflags = \"\";\n cxxflags = \"\";\n\n \/* +--------------------------------------------------+\n * |Now we read in the global config file for upackage|\n * +--------------------------------------------------+\n *\/\n std::vector<std::string> file = read(\"upackage.conf\");\n\n \/* +----------------------------------------------------+\n * |If the file size is <= 0 then the file must be empty|\n * +----------------------------------------------------+\n *\/\n if(file.size() <= 0)\n {\n return;\n }\n \n \/* If we are here, then the file size is > 0, now lets parse it *\/\n\n \/* +------------------------------------------+\n * |An integer vector for storing line numbers|\n * +------------------------------------------+\n *\/\n std::vector<int> line;\n \n \/* +------------------------------------------------------+\n * |An integer vector for storing the position of each ':'|\n * +------------------------------------------------------+\n *\/\n std::vector<int> pos;\n \n for(int i = 0; i < file.size(); i++)\n {\n \/* +----------------------------+\n * |Do nothing with line[0] == # |\n * +----------------------------+\n *\/\n file[i] = file[i].substr(0, file[i].find_first_of(\"#\"));\n\n \/* +---------------------+\n * |Locate all of the ':'|\n * +---------------------+\n *\/\n if(file[i].find_first_of(\":\") + 1 > 0)\n {\n \/* +----------------------------------------------+\n * |Store the position and line number of each ':'|\n * +----------------------------------------------+\n *\/\n pos.push_back(file[i].find_first_of(\":\"));\n line.push_back(i);\n }\n }\n \n \/* +--------------------------------------------+\n * |A string for storing the data before the ':'|\n * +--------------------------------------------+\n *\/\n std::string key;\n \n \/* +-------------------------------------------+\n * |A string for storing the data after the ':'|\n * +-------------------------------------------+\n *\/\n std::string value;\n\n line.push_back(file.size());\n\n for(int i = 0; i < pos.size(); i++)\n {\n \/* +----------------------------------+\n * |The key is the data before the ':'|\n * +----------------------------------+\n *\/\n key = file[line[i]].substr(0, pos[i]);\n \n \/* +-----------------------------------+\n * |The value is the data after the ':'|\n * +-----------------------------------+\n *\/\n value = file[line[i]].substr(pos[i] + 1);\n\n for(int j = line[i] + 1; j < line[i + 1]; j++)\n {\n if(file[j].length() > 0)\n {\n value = value + \"\\n\" + file[j];\n }\n }\n if(!strcmp(key.c_str(), \"CFLAGS\")\n || !strcmp(key.c_str(), \"cflags\"))\n {\n cflags = value;\n }\n if(!strcmp(key.c_str(), \"CXXFLAGS\")\n || !strcmp(key.c_str(), \"cxxflags\"))\n {\n cxxflags = value;\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <vector>\n\n#include \"Scorpio\/parse-option.hpp\"\n\n#include \"board.hpp\"\n#include \"config.hpp\"\n\nnamespace roadagain\n{\n\nConfig::Config() : color_(true), automatic_(false), player_(BLACK), level_(EASY)\n{\n}\n\nConfig& Config::instance()\n{\n static Config instance_;\n return (instance_);\n}\n\nbool Config::init(int argc, char** argv)\n{\n scorpio::OptionParser parser(argc, argv);\n\n parser.add_option(AUTOMATIC_STR);\n parser.add_option(COLOR_STR, true);\n parser.add_option(LEVEL_STR, true);\n parser.add_option(LOG_STR, true);\n parser.add_option(HELP_STR);\n parser.add_option(BLACK_STR);\n parser.add_option(WHITE_STR);\n\n std::vector<scorpio::Option> options = parser.parse();\n int size = options.size();\n for (int i = 0; i < size; i++){\n if (!options[i].available){\n continue;\n }\n if (options[i].name == HELP_STR){\n help();\n }\n else if (options[i].name == AUTOMATIC_STR){\n automatic_ = true;\n }\n else if (options[i].name == COLOR_STR){\n if (options[i].value == ALWAYS_STR || options[i].value == AUTO_STR){\n color_ = true;\n }\n else if (options[i].value == NEVER_STR){\n color_ = false;\n }\n else {\n std::puts(\"color option can be only 1 of 3 values: always, auto, never\");\n return (false);\n }\n }\n else if (options[i].name == LEVEL_STR){\n if (options[i].value == EASY_STR){\n level_ = EASY;\n }\n else if (options[i].value == HARD_STR){\n level_ = HARD;\n }\n else {\n std::puts(\"level option cna be only 1 of 2 values: easy, hard\");\n return (false);\n }\n }\n else if (options[i].name == LOG_STR){\n if (options[i].value.empty()){\n std::puts(\"log option needs filename\");\n return (false);\n }\n else {\n log_file_ = options[i].value;\n }\n }\n else if (options[i].name == BLACK_STR){\n player_ = BLACK;\n }\n else if (options[i].name == WHITE_STR){\n player_ = WHITE;\n }\n else {\n std::printf(\"Unknown option: %s\\n\", options[i].name.c_str());\n return (false);\n }\n }\n\n return (true);\n}\n\nvoid Config::help()\n{\n std::puts(\"Usage: reversi [options] [color]\");\n std::puts(\"Reversi game for one person's play.\");\n std::puts(\"Options:\");\n std::puts(\" --automatic Play automatically.\");\n std::puts(\" --color[=WHEN] Colorize the output; \");\n std::puts(\" WHEN can be 'always' (default if omitted), 'auto', or 'never'.\");\n std::puts(\" --help Print this help and exit successfully.\");\n std::puts(\"\");\n std::puts(\"Color must be 'black' or 'white'.\");\n std::puts(\"Default color is black.\");\n\n std::exit(0);\n}\n\nbool Config::color() const\n{\n return (color_);\n}\n\nbool Config::automatic() const\n{\n return (automatic_);\n}\n\nBoardState Config::player() const\n{\n if (automatic_){\n return (EMPTY);\n }\n else {\n return (player_);\n }\n}\n\nLevel Config::level() const\n{\n return (level_);\n}\n\nconst std::string Config::BLACK_STR(\"black\");\nconst std::string Config::WHITE_STR(\"white\");\nconst std::string Config::AUTOMATIC_STR(\"--automatic\");\nconst std::string Config::COLOR_STR(\"--color\");\nconst std::string Config::ALWAYS_STR(\"always\");\nconst std::string Config::AUTO_STR(\"auto\");\nconst std::string Config::NEVER_STR(\"never\");\nconst std::string Config::LEVEL_STR(\"--level\");\nconst std::string Config::EASY_STR(\"easy\");\nconst std::string Config::HARD_STR(\"hard\");\nconst std::string Config::LOG_STR(\"--log\");\nconst std::string Config::HELP_STR(\"--help\");\n\n}\n<commit_msg>Fixed typo in level error message<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <vector>\n\n#include \"Scorpio\/parse-option.hpp\"\n\n#include \"board.hpp\"\n#include \"config.hpp\"\n\nnamespace roadagain\n{\n\nConfig::Config() : color_(true), automatic_(false), player_(BLACK), level_(EASY)\n{\n}\n\nConfig& Config::instance()\n{\n static Config instance_;\n return (instance_);\n}\n\nbool Config::init(int argc, char** argv)\n{\n scorpio::OptionParser parser(argc, argv);\n\n parser.add_option(AUTOMATIC_STR);\n parser.add_option(COLOR_STR, true);\n parser.add_option(LEVEL_STR, true);\n parser.add_option(LOG_STR, true);\n parser.add_option(HELP_STR);\n parser.add_option(BLACK_STR);\n parser.add_option(WHITE_STR);\n\n std::vector<scorpio::Option> options = parser.parse();\n int size = options.size();\n for (int i = 0; i < size; i++){\n if (!options[i].available){\n continue;\n }\n if (options[i].name == HELP_STR){\n help();\n }\n else if (options[i].name == AUTOMATIC_STR){\n automatic_ = true;\n }\n else if (options[i].name == COLOR_STR){\n if (options[i].value == ALWAYS_STR || options[i].value == AUTO_STR){\n color_ = true;\n }\n else if (options[i].value == NEVER_STR){\n color_ = false;\n }\n else {\n std::puts(\"color option can be only 1 of 3 values: always, auto, never\");\n return (false);\n }\n }\n else if (options[i].name == LEVEL_STR){\n if (options[i].value == EASY_STR){\n level_ = EASY;\n }\n else if (options[i].value == HARD_STR){\n level_ = HARD;\n }\n else {\n std::puts(\"level option can be only 1 of 2 values: easy, hard\");\n return (false);\n }\n }\n else if (options[i].name == LOG_STR){\n if (options[i].value.empty()){\n std::puts(\"log option needs filename\");\n return (false);\n }\n else {\n log_file_ = options[i].value;\n }\n }\n else if (options[i].name == BLACK_STR){\n player_ = BLACK;\n }\n else if (options[i].name == WHITE_STR){\n player_ = WHITE;\n }\n else {\n std::printf(\"Unknown option: %s\\n\", options[i].name.c_str());\n return (false);\n }\n }\n\n return (true);\n}\n\nvoid Config::help()\n{\n std::puts(\"Usage: reversi [options] [color]\");\n std::puts(\"Reversi game for one person's play.\");\n std::puts(\"Options:\");\n std::puts(\" --automatic Play automatically.\");\n std::puts(\" --color[=WHEN] Colorize the output; \");\n std::puts(\" WHEN can be 'always' (default if omitted), 'auto', or 'never'.\");\n std::puts(\" --help Print this help and exit successfully.\");\n std::puts(\"\");\n std::puts(\"Color must be 'black' or 'white'.\");\n std::puts(\"Default color is black.\");\n\n std::exit(0);\n}\n\nbool Config::color() const\n{\n return (color_);\n}\n\nbool Config::automatic() const\n{\n return (automatic_);\n}\n\nBoardState Config::player() const\n{\n if (automatic_){\n return (EMPTY);\n }\n else {\n return (player_);\n }\n}\n\nLevel Config::level() const\n{\n return (level_);\n}\n\nconst std::string Config::BLACK_STR(\"black\");\nconst std::string Config::WHITE_STR(\"white\");\nconst std::string Config::AUTOMATIC_STR(\"--automatic\");\nconst std::string Config::COLOR_STR(\"--color\");\nconst std::string Config::ALWAYS_STR(\"always\");\nconst std::string Config::AUTO_STR(\"auto\");\nconst std::string Config::NEVER_STR(\"never\");\nconst std::string Config::LEVEL_STR(\"--level\");\nconst std::string Config::EASY_STR(\"easy\");\nconst std::string Config::HARD_STR(\"hard\");\nconst std::string Config::LOG_STR(\"--log\");\nconst std::string Config::HELP_STR(\"--help\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018-2022 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <avalanche\/voterecord.h>\n\n#include <test\/util\/setup_common.h>\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace avalanche;\n\nNodeId nextNodeId(NodeId &nodeid) {\n nodeid++;\n if (nodeid >= 8) {\n nodeid = 0;\n }\n return nodeid;\n}\n\nBOOST_FIXTURE_TEST_SUITE(voterecord_tests, TestingSetup)\n\n#define REGISTER_VOTE_AND_CHECK(vr, vote, state, finalized, stale, confidence) \\\n vr.registerVote(nextNodeId(nodeid), vote); \\\n BOOST_CHECK_EQUAL(vr.isAccepted(), state); \\\n BOOST_CHECK_EQUAL(vr.hasFinalized(), finalized); \\\n BOOST_CHECK_EQUAL(vr.isStale(), stale); \\\n BOOST_CHECK_EQUAL(vr.getConfidence(), confidence);\n\nBOOST_AUTO_TEST_CASE(vote_record) {\n NodeId nodeid = -1;\n VoteRecord vraccepted(true);\n\n \/\/ Check initial state.\n BOOST_CHECK_EQUAL(vraccepted.isAccepted(), true);\n BOOST_CHECK_EQUAL(vraccepted.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vraccepted.isStale(), false);\n BOOST_CHECK_EQUAL(vraccepted.getConfidence(), 0);\n\n VoteRecord vr(false);\n\n \/\/ Check initial state.\n BOOST_CHECK_EQUAL(vr.isAccepted(), false);\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n BOOST_CHECK_EQUAL(vr.getConfidence(), 0);\n\n \/\/ We need to register 6 positive votes before we start counting.\n for (int i = 0; i < 6; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, false, false, false, 0);\n }\n\n \/\/ Next vote will flip state, and confidence will increase as long as we\n \/\/ vote yes.\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 0);\n\n \/\/ A single neutral vote do not change anything.\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 1);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);\n }\n\n \/\/ Two neutral votes will stall progress.\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 7);\n }\n\n \/\/ Now confidence will increase as long as we vote yes.\n for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);\n }\n\n \/\/ The next vote will finalize the decision.\n REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n\n \/\/ Now that we have two no votes, confidence stop increasing.\n for (int i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n }\n\n \/\/ Next vote will flip state, and confidence will increase as long as we\n \/\/ vote no.\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 0);\n\n \/\/ A single neutral vote do not change anything.\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);\n }\n\n \/\/ Two neutral votes will stall progress.\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 7);\n }\n\n \/\/ Now confidence will increase as long as we vote no.\n for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);\n }\n\n \/\/ The next vote will finalize the decision.\n REGISTER_VOTE_AND_CHECK(vr, 0, false, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n\n \/\/ Check that inflight accounting work as expected.\n VoteRecord vrinflight(false);\n for (int i = 0; i < 2 * AVALANCHE_MAX_INFLIGHT_POLL; i++) {\n bool shouldPoll = vrinflight.shouldPoll();\n BOOST_CHECK_EQUAL(shouldPoll, i < AVALANCHE_MAX_INFLIGHT_POLL);\n BOOST_CHECK_EQUAL(vrinflight.registerPoll(), shouldPoll);\n }\n\n \/\/ Clear various number of inflight requests and check everything behaves as\n \/\/ expected.\n for (int i = 1; i < AVALANCHE_MAX_INFLIGHT_POLL; i++) {\n vrinflight.clearInflightRequest(i);\n BOOST_CHECK(vrinflight.shouldPoll());\n\n for (int j = 1; j < i; j++) {\n BOOST_CHECK(vrinflight.registerPoll());\n BOOST_CHECK(vrinflight.shouldPoll());\n }\n\n BOOST_CHECK(vrinflight.registerPoll());\n BOOST_CHECK(!vrinflight.shouldPoll());\n }\n}\n\n\/\/ Test some cases where confidence never advances\nBOOST_AUTO_TEST_CASE(stale_vote_always_inconclusive) {\n NodeId nodeid = -1;\n \/\/ Setup a record that is inconclusive so far\n VoteRecord vr(false);\n\n for (uint32_t i = 0; i < AVALANCHE_VOTE_STALE_THRESHOLD \/ 8; i++) {\n \/\/ Vote randomly, but such that there's always enough neutral votes to\n \/\/ not gain confidence.\n for (auto j = 0; j < 6; j++) {\n REGISTER_VOTE_AND_CHECK(vr, InsecureRand32(), false, false, false,\n 0);\n }\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);\n }\n\n \/\/ Vote record becomes stale after too many rounds of inconclusive voting\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 0);\n}\n\n\/\/ Test all cases where records reach a specific confidence level and then go\n\/\/ stale.\nBOOST_AUTO_TEST_CASE(stale_vote_at_all_confidence_levels) {\n NodeId nodeid = -1;\n\n for (uint32_t vote = 0; vote <= 1; vote++) {\n for (uint32_t confidence = 0; confidence < AVALANCHE_FINALIZATION_SCORE;\n confidence++) {\n VoteRecord vr(!vote);\n\n \/\/ Prepare to increase confidence with some votes\n for (auto i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);\n }\n\n \/\/ Increase to target confidence\n for (uint32_t i = 0; i < confidence; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);\n }\n\n uint32_t remainingVotes =\n AVALANCHE_VOTE_STALE_THRESHOLD - confidence - 5;\n\n \/\/ Special case where staying at confidence of 1 requires a\n \/\/ different vote between agreeing votes\n if (confidence == 1) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 1);\n remainingVotes -= 2;\n }\n\n \/\/ Vote neutral until stale\n if (confidence >\n AVALANCHE_VOTE_STALE_THRESHOLD \/ AVALANCHE_VOTE_STALE_FACTOR) {\n remainingVotes =\n confidence * AVALANCHE_VOTE_STALE_FACTOR - confidence - 5;\n }\n for (uint32_t i = 0; i < remainingVotes; i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false,\n confidence);\n }\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, true, confidence);\n }\n }\n}\n\n\/\/ Test some cases where confidence may flip flop and then goes stale.\nBOOST_AUTO_TEST_CASE(stale_vote_random_then_inconclusive) {\n NodeId nodeid = -1;\n VoteRecord vr(false);\n\n for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 14; i++) {\n \/\/ Vote randomly. Confidence changes are ok.\n vr.registerVote(nextNodeId(nodeid), InsecureRand32());\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n }\n\n \/\/ Reset confidence, no matter what it is right now\n for (uint32_t i = 0; i < 7; i++) {\n vr.registerVote(nextNodeId(nodeid), 0);\n }\n for (uint32_t i = 0; i < 7; i++) {\n vr.registerVote(nextNodeId(nodeid), 1);\n }\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n\n \/\/ Remainder of votes are neutral\n for (uint32_t i = 0;\n i < AVALANCHE_VOTE_STALE_THRESHOLD - AVALANCHE_FINALIZATION_SCORE;\n i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);\n }\n\n \/\/ Vote record becomes stale after too many rounds of voting\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 1);\n}\n\n\/\/ Test all cases where confidence flips as much as possible, ending at all\n\/\/ possible confidence levels.\nBOOST_AUTO_TEST_CASE(stale_vote_with_confidence_flips) {\n NodeId nodeid = -1;\n\n \/\/ Start testing with yes or no votes\n for (uint32_t voteInit = 0; voteInit <= 1; voteInit++) {\n \/\/ Test stalling at all confidence levels\n for (auto offset = 0; offset < AVALANCHE_FINALIZATION_SCORE; offset++) {\n uint32_t vote = voteInit;\n VoteRecord vr(!vote);\n uint32_t count = 0;\n\n \/\/ Offset with neutral votes\n for (auto i = 0; i < offset; i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);\n count++;\n }\n\n \/\/ Prepare to increase confidence with some votes\n for (auto i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);\n count++;\n }\n\n while (true) {\n \/\/ Increase confidence as fast as possible\n for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 1;\n i++) {\n if (i <= AVALANCHE_VOTE_STALE_THRESHOLD \/\n AVALANCHE_VOTE_STALE_FACTOR &&\n count >= AVALANCHE_VOTE_STALE_THRESHOLD) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,\n i);\n goto finalsanitycheck;\n }\n if (i > AVALANCHE_VOTE_STALE_THRESHOLD \/\n AVALANCHE_VOTE_STALE_FACTOR &&\n count >= i * AVALANCHE_VOTE_STALE_FACTOR) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,\n i);\n goto finalsanitycheck;\n }\n\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);\n count++;\n }\n\n \/\/ Flip the vote\n if (vote++ >= 1) {\n vote = 0;\n }\n\n \/\/ Reset confidence\n for (auto i = 0; i < 6; i++) {\n if (count >= (AVALANCHE_FINALIZATION_SCORE - 1) *\n AVALANCHE_VOTE_STALE_FACTOR) {\n REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, true,\n AVALANCHE_FINALIZATION_SCORE);\n goto finalsanitycheck;\n }\n\n REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, false,\n AVALANCHE_FINALIZATION_SCORE - 1);\n count++;\n }\n\n \/\/ If this fails, we are probably infinite looping for some\n \/\/ reason\n BOOST_CHECK(count <= AVALANCHE_FINALIZATION_SCORE *\n AVALANCHE_VOTE_STALE_FACTOR);\n }\n\n finalsanitycheck:\n BOOST_CHECK(vr.isStale());\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(duplicate_votes) {\n VoteRecord vr(true);\n NodeId nodeid = -1;\n\n \/\/ Register some votes, expecting confidence to increase\n for (auto i = 0; i < 7; i++) {\n BOOST_CHECK_EQUAL(vr.getConfidence(), 0);\n BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));\n }\n BOOST_CHECK_EQUAL(vr.getConfidence(), 1);\n\n \/\/ Multiple duplicate votes do not advance confidence\n for (auto i = 0; i < 8; i++) {\n BOOST_CHECK(!vr.registerVote(nodeid, 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), 1);\n }\n\n \/\/ Register more votes with duplicates mixed in. Confidence should only\n \/\/ increase when duplicates are not used.\n auto expectedConfidence = 1;\n for (auto i = 0; i < 8; i++) {\n BOOST_CHECK(!vr.registerVote(nodeid, 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), expectedConfidence);\n for (auto j = i; j < 8; j++) {\n BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);\n }\n }\n\n \/\/ Register enough votes to get just before finalization\n for (auto i = 0; i < 90; i++) {\n BOOST_CHECK(!vr.registerVote(nextNodeId(nodeid), 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);\n }\n\n \/\/ Sanity check that finalization occurs on the expected vote\n BOOST_CHECK(vr.registerVote(nextNodeId(nodeid), 0));\n BOOST_CHECK(vr.hasFinalized());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>[avalanche] Set voterecord_tests node ID using a fixture<commit_after>\/\/ Copyright (c) 2018-2022 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <avalanche\/voterecord.h>\n\n#include <test\/util\/setup_common.h>\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace avalanche;\n\nstruct VoteRecordFixture {\n NodeId currentNodeId = -1;\n\n NodeId nextNodeId() {\n currentNodeId++;\n if (currentNodeId >= 8) {\n currentNodeId = 0;\n }\n return currentNodeId;\n }\n};\n\nBOOST_FIXTURE_TEST_SUITE(voterecord_tests, VoteRecordFixture)\n\n#define REGISTER_VOTE_AND_CHECK(vr, vote, state, finalized, stale, confidence) \\\n vr.registerVote(nextNodeId(), vote); \\\n BOOST_CHECK_EQUAL(vr.isAccepted(), state); \\\n BOOST_CHECK_EQUAL(vr.hasFinalized(), finalized); \\\n BOOST_CHECK_EQUAL(vr.isStale(), stale); \\\n BOOST_CHECK_EQUAL(vr.getConfidence(), confidence);\n\nBOOST_AUTO_TEST_CASE(vote_record) {\n VoteRecord vraccepted(true);\n\n \/\/ Check initial state.\n BOOST_CHECK_EQUAL(vraccepted.isAccepted(), true);\n BOOST_CHECK_EQUAL(vraccepted.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vraccepted.isStale(), false);\n BOOST_CHECK_EQUAL(vraccepted.getConfidence(), 0);\n\n VoteRecord vr(false);\n\n \/\/ Check initial state.\n BOOST_CHECK_EQUAL(vr.isAccepted(), false);\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n BOOST_CHECK_EQUAL(vr.getConfidence(), 0);\n\n \/\/ We need to register 6 positive votes before we start counting.\n for (int i = 0; i < 6; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, false, false, false, 0);\n }\n\n \/\/ Next vote will flip state, and confidence will increase as long as we\n \/\/ vote yes.\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 0);\n\n \/\/ A single neutral vote do not change anything.\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 1);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);\n }\n\n \/\/ Two neutral votes will stall progress.\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);\n REGISTER_VOTE_AND_CHECK(vr, -1, true, false, false, 7);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, 7);\n }\n\n \/\/ Now confidence will increase as long as we vote yes.\n for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 0, true, false, false, i);\n }\n\n \/\/ The next vote will finalize the decision.\n REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n\n \/\/ Now that we have two no votes, confidence stop increasing.\n for (int i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, true, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n }\n\n \/\/ Next vote will flip state, and confidence will increase as long as we\n \/\/ vote no.\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 0);\n\n \/\/ A single neutral vote do not change anything.\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);\n }\n\n \/\/ Two neutral votes will stall progress.\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 7);\n for (int i = 2; i < 8; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, 7);\n }\n\n \/\/ Now confidence will increase as long as we vote no.\n for (int i = 8; i < AVALANCHE_FINALIZATION_SCORE; i++) {\n REGISTER_VOTE_AND_CHECK(vr, 1, false, false, false, i);\n }\n\n \/\/ The next vote will finalize the decision.\n REGISTER_VOTE_AND_CHECK(vr, 0, false, true, false,\n AVALANCHE_FINALIZATION_SCORE);\n\n \/\/ Check that inflight accounting work as expected.\n VoteRecord vrinflight(false);\n for (int i = 0; i < 2 * AVALANCHE_MAX_INFLIGHT_POLL; i++) {\n bool shouldPoll = vrinflight.shouldPoll();\n BOOST_CHECK_EQUAL(shouldPoll, i < AVALANCHE_MAX_INFLIGHT_POLL);\n BOOST_CHECK_EQUAL(vrinflight.registerPoll(), shouldPoll);\n }\n\n \/\/ Clear various number of inflight requests and check everything behaves as\n \/\/ expected.\n for (int i = 1; i < AVALANCHE_MAX_INFLIGHT_POLL; i++) {\n vrinflight.clearInflightRequest(i);\n BOOST_CHECK(vrinflight.shouldPoll());\n\n for (int j = 1; j < i; j++) {\n BOOST_CHECK(vrinflight.registerPoll());\n BOOST_CHECK(vrinflight.shouldPoll());\n }\n\n BOOST_CHECK(vrinflight.registerPoll());\n BOOST_CHECK(!vrinflight.shouldPoll());\n }\n}\n\n\/\/ Test some cases where confidence never advances\nBOOST_AUTO_TEST_CASE(stale_vote_always_inconclusive) {\n \/\/ Setup a record that is inconclusive so far\n VoteRecord vr(false);\n\n for (uint32_t i = 0; i < AVALANCHE_VOTE_STALE_THRESHOLD \/ 8; i++) {\n \/\/ Vote randomly, but such that there's always enough neutral votes to\n \/\/ not gain confidence.\n for (auto j = 0; j < 6; j++) {\n REGISTER_VOTE_AND_CHECK(vr, InsecureRand32(), false, false, false,\n 0);\n }\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 0);\n }\n\n \/\/ Vote record becomes stale after too many rounds of inconclusive voting\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 0);\n}\n\n\/\/ Test all cases where records reach a specific confidence level and then go\n\/\/ stale.\nBOOST_AUTO_TEST_CASE(stale_vote_at_all_confidence_levels) {\n for (uint32_t vote = 0; vote <= 1; vote++) {\n for (uint32_t confidence = 0; confidence < AVALANCHE_FINALIZATION_SCORE;\n confidence++) {\n VoteRecord vr(!vote);\n\n \/\/ Prepare to increase confidence with some votes\n for (auto i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);\n }\n\n \/\/ Increase to target confidence\n for (uint32_t i = 0; i < confidence; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);\n }\n\n uint32_t remainingVotes =\n AVALANCHE_VOTE_STALE_THRESHOLD - confidence - 5;\n\n \/\/ Special case where staying at confidence of 1 requires a\n \/\/ different vote between agreeing votes\n if (confidence == 1) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 1);\n remainingVotes -= 2;\n }\n\n \/\/ Vote neutral until stale\n if (confidence >\n AVALANCHE_VOTE_STALE_THRESHOLD \/ AVALANCHE_VOTE_STALE_FACTOR) {\n remainingVotes =\n confidence * AVALANCHE_VOTE_STALE_FACTOR - confidence - 5;\n }\n for (uint32_t i = 0; i < remainingVotes; i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false,\n confidence);\n }\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, true, confidence);\n }\n }\n}\n\n\/\/ Test some cases where confidence may flip flop and then goes stale.\nBOOST_AUTO_TEST_CASE(stale_vote_random_then_inconclusive) {\n VoteRecord vr(false);\n\n for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 14; i++) {\n \/\/ Vote randomly. Confidence changes are ok.\n vr.registerVote(nextNodeId(), InsecureRand32());\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n }\n\n \/\/ Reset confidence, no matter what it is right now\n for (uint32_t i = 0; i < 7; i++) {\n vr.registerVote(nextNodeId(), 0);\n }\n for (uint32_t i = 0; i < 7; i++) {\n vr.registerVote(nextNodeId(), 1);\n }\n BOOST_CHECK_EQUAL(vr.hasFinalized(), false);\n BOOST_CHECK_EQUAL(vr.isStale(), false);\n\n \/\/ Remainder of votes are neutral\n for (uint32_t i = 0;\n i < AVALANCHE_VOTE_STALE_THRESHOLD - AVALANCHE_FINALIZATION_SCORE;\n i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, false, 1);\n }\n\n \/\/ Vote record becomes stale after too many rounds of voting\n REGISTER_VOTE_AND_CHECK(vr, -1, false, false, true, 1);\n}\n\n\/\/ Test all cases where confidence flips as much as possible, ending at all\n\/\/ possible confidence levels.\nBOOST_AUTO_TEST_CASE(stale_vote_with_confidence_flips) {\n \/\/ Start testing with yes or no votes\n for (uint32_t voteInit = 0; voteInit <= 1; voteInit++) {\n \/\/ Test stalling at all confidence levels\n for (auto offset = 0; offset < AVALANCHE_FINALIZATION_SCORE; offset++) {\n uint32_t vote = voteInit;\n VoteRecord vr(!vote);\n uint32_t count = 0;\n\n \/\/ Offset with neutral votes\n for (auto i = 0; i < offset; i++) {\n REGISTER_VOTE_AND_CHECK(vr, -1, !vote, false, false, 0);\n count++;\n }\n\n \/\/ Prepare to increase confidence with some votes\n for (auto i = 0; i < 5; i++) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, 0);\n count++;\n }\n\n while (true) {\n \/\/ Increase confidence as fast as possible\n for (uint32_t i = 0; i < AVALANCHE_FINALIZATION_SCORE - 1;\n i++) {\n if (i <= AVALANCHE_VOTE_STALE_THRESHOLD \/\n AVALANCHE_VOTE_STALE_FACTOR &&\n count >= AVALANCHE_VOTE_STALE_THRESHOLD) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,\n i);\n goto finalsanitycheck;\n }\n if (i > AVALANCHE_VOTE_STALE_THRESHOLD \/\n AVALANCHE_VOTE_STALE_FACTOR &&\n count >= i * AVALANCHE_VOTE_STALE_FACTOR) {\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, true,\n i);\n goto finalsanitycheck;\n }\n\n REGISTER_VOTE_AND_CHECK(vr, vote, !vote, false, false, i);\n count++;\n }\n\n \/\/ Flip the vote\n if (vote++ >= 1) {\n vote = 0;\n }\n\n \/\/ Reset confidence\n for (auto i = 0; i < 6; i++) {\n if (count >= (AVALANCHE_FINALIZATION_SCORE - 1) *\n AVALANCHE_VOTE_STALE_FACTOR) {\n REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, true,\n AVALANCHE_FINALIZATION_SCORE);\n goto finalsanitycheck;\n }\n\n REGISTER_VOTE_AND_CHECK(vr, vote, vote, false, false,\n AVALANCHE_FINALIZATION_SCORE - 1);\n count++;\n }\n\n \/\/ If this fails, we are probably infinite looping for some\n \/\/ reason\n BOOST_CHECK(count <= AVALANCHE_FINALIZATION_SCORE *\n AVALANCHE_VOTE_STALE_FACTOR);\n }\n\n finalsanitycheck:\n BOOST_CHECK(vr.isStale());\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(duplicate_votes) {\n VoteRecord vr(true);\n\n \/\/ Register some votes, expecting confidence to increase\n for (auto i = 0; i < 7; i++) {\n BOOST_CHECK_EQUAL(vr.getConfidence(), 0);\n BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));\n }\n BOOST_CHECK_EQUAL(vr.getConfidence(), 1);\n\n \/\/ Multiple duplicate votes do not advance confidence\n for (auto i = 0; i < 8; i++) {\n BOOST_CHECK(!vr.registerVote(currentNodeId, 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), 1);\n }\n\n \/\/ Register more votes with duplicates mixed in. Confidence should only\n \/\/ increase when duplicates are not used.\n auto expectedConfidence = 1;\n for (auto i = 0; i < 8; i++) {\n BOOST_CHECK(!vr.registerVote(currentNodeId, 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), expectedConfidence);\n for (auto j = i; j < 8; j++) {\n BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);\n }\n }\n\n \/\/ Register enough votes to get just before finalization\n for (auto i = 0; i < 90; i++) {\n BOOST_CHECK(!vr.registerVote(nextNodeId(), 0));\n BOOST_CHECK_EQUAL(vr.getConfidence(), ++expectedConfidence);\n }\n\n \/\/ Sanity check that finalization occurs on the expected vote\n BOOST_CHECK(vr.registerVote(nextNodeId(), 0));\n BOOST_CHECK(vr.hasFinalized());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************************\n * Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann *\n * Permission is hereby granted, free of charge, to any person obtaining a copy *\n * of this software and associated documentation files (the \"Software\"), to deal *\n * in the Software without restriction, including without limitation the rights *\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell *\n * copies of the Software, and to permit persons to whom the Software is * \n * furnished to do so, subject to the following conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in *\n * all copies or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *\n * THE SOFTWARE. *\n *********************************************************************************\/\n\n#include <GL\/glfw.h>\n#include \"GameWorld.hpp\"\n#include \"PlayerShip.hpp\"\n#include \"..\/math\/vector.hpp\"\n#include <ctime>\n#include <cstdlib>\n#include <GL\/glu.h>\n\n\nint main()\n{\n glfwInit();\n glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);\n glfwOpenWindow(800, 800, 8, 8, 8, 8, 24, 8, GLFW_WINDOW);\n\n using hstefan::game::GameWorld;\n using hstefan::game::PlayerShip;\n using namespace hstefan::math;\n\n GameWorld* world = GameWorld::getInstance();\n PlayerShip* ship = new PlayerShip(makeVec(400,400,1), 800, 800);\n world->addObject(ship);\n bool running = true;\n\n double last_render = 0;\n double last_update = 0;\n\n double frame_interval = 1.f\/60.f;\n double update_interval = 1.f\/90.f;\n\n double cur_time = 0;\n glClearColor(0.f, 0.f, 0.f, 1.f);\n glMatrixMode(GL_PROJECTION);\n \/\/glPushMatrix();\n glLoadIdentity();\n \/\/float proj[16] = {2\/800, 0, 0, 0, 0, 2\/800, 0, 0, 0, 0, 1, 0, -400, -400, 0, 1};\n \/\/glLoadMatrixf(proj);\n gluOrtho2D(0, 800, 0, 800);\n while(running) \n {\n cur_time = glfwGetTime();\n \n if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) \n break;\n if(cur_time - last_render > frame_interval) \n {\n last_render = glfwGetTime();\n glClear(GL_COLOR_BUFFER_BIT); \n world->render();\n glfwSwapBuffers();\n }\n \n if(cur_time - last_update > update_interval)\n {\n world->update();\n last_update = glfwGetTime();\n }\n glfwSleep(update_interval - (cur_time + glfwGetTime()));\n running = glfwGetWindowParam(GLFW_OPENED) != 0;\n }\n\n glfwTerminate();\n}\n<commit_msg>last version<commit_after>\/**********************************************************************************\n * Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann *\n * Permission is hereby granted, free of charge, to any person obtaining a copy *\n * of this software and associated documentation files (the \"Software\"), to deal *\n * in the Software without restriction, including without limitation the rights *\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell *\n * copies of the Software, and to permit persons to whom the Software is * \n * furnished to do so, subject to the following conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in *\n * all copies or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *\n * THE SOFTWARE. *\n *********************************************************************************\/\n\n#include <GL\/glfw.h>\n#include \"GameWorld.hpp\"\n#include \"PlayerShip.hpp\"\n#include \"..\/math\/vector.hpp\"\n#include <ctime>\n#include <cstdlib>\n\/\/#include <GL\/glu.h>\n\nint main()\n{\n glfwInit();\n glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);\n glfwOpenWindow(800, 800, 8, 8, 8, 8, 24, 8, GLFW_WINDOW);\n\n using hstefan::game::GameWorld;\n using hstefan::game::PlayerShip;\n using namespace hstefan::math;\n\n GameWorld* world = GameWorld::getInstance();\n PlayerShip* ship = new PlayerShip(makeVec(400,400,1), 800, 800);\n world->addObject(ship);\n bool running = true;\n\n double last_render = 0;\n double last_update = 0;\n\n double frame_interval = 1.f\/60.f;\n double update_interval = 1.f\/90.f;\n\n double cur_time = 0;\n glClearColor(0.f, 0.f, 0.f, 1.f);\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n float proj[16] = {2\/800, 0, 0, 0, 0, 2\/800, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1};\n glLoadMatrixf(proj);\n \/\/gluOrtho2D(0, 800, 0, 800);\n while(running) \n {\n cur_time = glfwGetTime();\n \n if(glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) \n break;\n if(cur_time - last_render > frame_interval) \n {\n last_render = glfwGetTime();\n glClear(GL_COLOR_BUFFER_BIT); \n world->render();\n glfwSwapBuffers();\n }\n \n if(cur_time - last_update > update_interval)\n {\n world->update();\n last_update = glfwGetTime();\n }\n glfwSleep(update_interval - (cur_time + glfwGetTime()));\n running = glfwGetWindowParam(GLFW_OPENED) != 0;\n }\n\n glfwTerminate();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n* Copyright (C) 2015 3D Repo Ltd\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as\r\n* published by the Free Software Foundation, either version 3 of the\r\n* License, or (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n*\/\r\n\r\n#include \"repo_settings_credentials.h\"\r\n\r\n\/\/------------------------------------------------------------------------------\r\nusing namespace repo::settings;\r\n\/\/------------------------------------------------------------------------------\r\n\r\nQString CREDENTIALS = \"token\";\r\nQString CREDENTIALS_ARRAY = \"tokens\";\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nRepoSettingsCredentials::RepoSettingsCredentials() : QSettings()\r\n{\r\n qRegisterMetaType<repo::RepoCredentials>();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid RepoSettingsCredentials::writeCredentials(QList<repo::RepoCredentials> &credentials)\r\n{\r\n beginWriteArray(CREDENTIALS_ARRAY);\r\n for (int i = 0; i < credentials.size(); ++i)\r\n {\r\n setArrayIndex(i);\r\n QVariant var;\r\n var.setValue(credentials.at(i));\r\n setValue(CREDENTIALS, var);\r\n }\r\n endArray();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nQList<repo::RepoCredentials> RepoSettingsCredentials::readCredentials()\r\n{ \r\n int size = beginReadArray(CREDENTIALS_ARRAY);\r\n QList<repo::RepoCredentials> credentialsList;\r\n for (int i = 0; i < size; ++i) {\r\n setArrayIndex(i);\r\n repo::RepoCredentials credentials = value(CREDENTIALS).value<repo::RepoCredentials>();\r\n credentialsList.append(credentials);\r\n emit credentialsAt(i, credentials);\r\n }\r\n endArray();\r\n return credentialsList;\r\n}\r\n<commit_msg>#51 Fixed compilation errors.<commit_after>\/**\r\n* Copyright (C) 2015 3D Repo Ltd\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as\r\n* published by the Free Software Foundation, either version 3 of the\r\n* License, or (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n*\/\r\n\r\n#include \"repo_settings_credentials.h\"\r\n\r\n\/\/------------------------------------------------------------------------------\r\nusing namespace repo::settings;\r\n\/\/------------------------------------------------------------------------------\r\n\r\nconst QString RepoSettingsCredentials::CREDENTIALS = \"credentials\";\r\nconst QString RepoSettingsCredentials::CREDENTIALS_ARRAY = \"credentials_array\";\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nRepoSettingsCredentials::RepoSettingsCredentials() : QSettings()\r\n{\r\n qRegisterMetaType<repo::RepoCredentials>();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid RepoSettingsCredentials::writeCredentials(QList<repo::RepoCredentials> &credentials)\r\n{\r\n beginWriteArray(CREDENTIALS_ARRAY);\r\n for (int i = 0; i < credentials.size(); ++i)\r\n {\r\n setArrayIndex(i);\r\n QVariant var;\r\n var.setValue(credentials.at(i));\r\n setValue(CREDENTIALS, var);\r\n }\r\n endArray();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nQList<repo::RepoCredentials> RepoSettingsCredentials::readCredentials()\r\n{ \r\n int size = beginReadArray(CREDENTIALS_ARRAY);\r\n QList<repo::RepoCredentials> credentialsList;\r\n for (int i = 0; i < size; ++i) {\r\n setArrayIndex(i);\r\n repo::RepoCredentials credentials = value(CREDENTIALS).value<repo::RepoCredentials>();\r\n credentialsList.append(credentials);\r\n\/\/ emit credentialsAt(i, credentials);\r\n }\r\n endArray();\r\n return credentialsList;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include \"controller.h\"\n#include \"fpshandler.h\"\n\n#include <stdlib.h>\n\n\nController::Controller()\n{\n running = true;\n window = new Window();\n model = new Model;\n}\n\nController::~Controller()\n{\n delete window;\n delete model;\n delete current_view;\n\tif (player != nullptr)\n\t{\n\t\tdelete player;\n\t\tplayer=nullptr;\n\t}\n}\n\nvoid Controller::run()\n{\n Controller &controller = getController();\n controller.setView(\"mainmenu\");\n FpsHandler clock;\n while (controller.running)\n {\n clock.start();\n controller.window->eventLoop();\n controller.window->renderFrame();\n clock.delay();\n }\n}\n\nvoid Controller::event(std::string event_name)\n{\n Controller &controller = getController();\n if (controller.current_view_name == \"mainmenu\")\n {\n controller.mainMenuEvent(event_name);\n }\n else if (controller.current_view_name == \"new_game\")\n {\n controller.newGameEvent(event_name);\n }\n else if (controller.current_view_name == \"settings\")\n {\n controller.settingsEvent(event_name);\n }\n else\n {\n std::cout << \"error, view \\\"\" << controller.current_view_name << \"\\\" is invalid\\n\";\n }\n}\n\nvoid Controller::mainMenuEvent(std::string event_name)\n{\n if (event_name == \"NEW_GAME\")\n {\n startNewGame();\n player = new Character();\n\t\tloadStats(player);\n }\n else if (event_name == \"SETTINGS\")\n {\n setView(\"settings\");\n }\n else if (event_name == \"EXIT_GAME\")\n {\n setDone();\n }\n else\n {\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::newGameEvent(std::string event_name)\n{\n\tif (event_name == \"BACK\")\n\t{\n delete player;\n\t\tplayer = nullptr;\n\t\tsetView(\"mainmenu\");\n\t}\n\telse if (event_name == \"DEC_STRENGTH\")\n\t{\n player->decStrength();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n\t\tcurrent_view->setText(\"{strength_value}\", asText(player->getStrength()));\n\t}\n\telse if (event_name == \"INC_STRENGTH\")\n\t{\n player->incStrength();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n\t\tcurrent_view->setText(\"{strength_value}\", asText(player->getStrength()));\n\t}\n else if (event_name == \"DEC_DEXTERITY\")\n {\n player->decDexterity();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{dexterity_value}\", asText(player->getDexterity()));\n }\n else if (event_name == \"INC_DEXTERITY\")\n {\n player->incDexterity();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{dexterity_value}\", asText(player->getDexterity()));\n }\n else if (event_name == \"DEC_AGILITY\")\n {\n player->decAgility();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{agility_value}\", asText(player->getAgility()));\n }\n else if (event_name == \"INC_AGILITY\")\n {\n player->incAgility();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{agility_value}\", asText(player->getAgility()));\n }\n else if (event_name == \"DEC_WISDOM\")\n {\n player->decWisdom();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{wisdom_value}\", asText(player->getWisdom()));\n }\n else if (event_name == \"INC_WISDOM\")\n {\n player->incWisdom();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{wisdom_value}\", asText(player->getWisdom()));\n }\n else if (event_name == \"DEC_INTELIGENCE\")\n {\n player->decInteligence();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{inteligence_value}\", asText(player->getInteligence()));\n }\n else if (event_name == \"INC_INTELIGENCE\")\n {\n player->incInteligence();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{inteligence_value}\", asText(player->getInteligence()));\n }\n else if (event_name == \"DEC_CHARISMA\")\n {\n player->decCharisma();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{charisma_value}\", asText(player->getCharisma()));\n }\n else if (event_name == \"INC_CHARISMA\")\n {\n player->incCharisma();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{charisma_value}\", asText(player->getCharisma()));\n }\n\telse if (event_name == \"START_GAME\")\n\t{\n\t\tsetView(\"mainmenu\");\n\t\taddView(\"player_card\", true);\n\t}\n\telse\n {\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::settingsEvent(std::string event_name)\n{\n if (event_name == \"BACK\")\n {\n setView(\"mainmenu\");\n }\n else if (event_name.substr(0, 9) == \"LANGUAGE_\")\n {\n std::cout << \"new language: \" << event_name.substr(9) << std::endl;\n model->setLanguage(event_name.substr(9));\n setView(\"settings\");\n }\n else\n {\n std::cout << \"cut: \" << event_name.substr(0, 8) << std::endl;\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::startNewGame()\n{\n std::cout << \"new game starting\\n\";\n setView(\"new_game\");\n}\n\nvoid Controller::setView(std::string view)\n{\n std::cout << \"changed view to: \" << std::setw(10) << view << std::endl;\n current_view_name = view;\n current_view = model->getXml(\"view_\" + view);\n window->setView(current_view);\n}\n\nvoid Controller::addView(std::string view, bool deactivation)\n{\n\tView* v;\n\tif (deactivation)\n\t{\n\t\tv = model->getXml(\"view_blockade\");\n\t\tcurrent_view->extendView(v);\n\t}\n\tv = model->getXml(\"view_\" + view);\n\tcurrent_view->extendView(v);\n\twindow->updateClickmap();\n}\n\nvoid Controller::delView()\n{\n\tcurrent_view->removeLastView();\n\twindow->updateClickmap();\n}\n\nvoid Controller::setDone()\n{\n getController().running = false;\n}\n\nController &Controller::getController()\n{\n static Controller controller;\n return controller;\n}\n\nstd::string Controller::asText(int number)\n{\n char buff[3];\n snprintf(buff, sizeof(buff), \"%d\", number);\n return buff;\n}\n\nvoid Controller::loadStats(Character *character)\n{\n\tcurrent_view->setText(\"{points_value}\", asText(character->getPoints()));\n current_view->setText(\"{strength_value}\", asText(character->getStrength()));\n current_view->setText(\"{dexterity_value}\", asText(character->getDexterity()));\n current_view->setText(\"{agility_value}\", asText(character->getAgility()));\n current_view->setText(\"{wisdom_value}\", asText(character->getWisdom()));\n current_view->setText(\"{inteligence_value}\", asText(character->getInteligence()));\n current_view->setText(\"{charisma_value}\", asText(character->getCharisma()));\n}\n\n\n\n\n<commit_msg>bugfix<commit_after>#include <iostream>\n#include <iomanip>\n#include \"controller.h\"\n#include \"fpshandler.h\"\n\n#include <stdlib.h>\n\n\nController::Controller()\n{\n running = true;\n window = new Window();\n model = new Model;\n}\n\nController::~Controller()\n{\n delete window;\n delete model;\n delete current_view;\n\tif (player != nullptr)\n\t{\n\t\tdelete player;\n\t\tplayer=nullptr;\n\t}\n}\n\nvoid Controller::run()\n{\n Controller &controller = getController();\n controller.setView(\"mainmenu\");\n FpsHandler clock;\n while (controller.running)\n {\n clock.start();\n controller.window->eventLoop();\n controller.window->renderFrame();\n clock.delay();\n }\n}\n\nvoid Controller::event(std::string event_name)\n{\n Controller &controller = getController();\n if (controller.current_view_name == \"mainmenu\")\n {\n controller.mainMenuEvent(event_name);\n }\n else if (controller.current_view_name == \"new_game\")\n {\n controller.newGameEvent(event_name);\n }\n else if (controller.current_view_name == \"settings\")\n {\n controller.settingsEvent(event_name);\n }\n else\n {\n std::cout << \"error, view \\\"\" << controller.current_view_name << \"\\\" is invalid\\n\";\n }\n}\n\nvoid Controller::mainMenuEvent(std::string event_name)\n{\n if (event_name == \"NEW_GAME\")\n {\n startNewGame();\n player = new Character();\n\t\tloadStats(player);\n }\n else if (event_name == \"SETTINGS\")\n {\n setView(\"settings\");\n }\n else if (event_name == \"EXIT_GAME\")\n {\n setDone();\n }\n else\n {\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::newGameEvent(std::string event_name)\n{\n\tif (event_name == \"BACK\")\n\t{\n delete player;\n\t\tplayer = nullptr;\n\t\tsetView(\"mainmenu\");\n\t}\n\telse if (event_name == \"DEC_STRENGTH\")\n\t{\n player->decStrength();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n\t\tcurrent_view->setText(\"{strength_value}\", asText(player->getStrength()));\n\t}\n\telse if (event_name == \"INC_STRENGTH\")\n\t{\n player->incStrength();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n\t\tcurrent_view->setText(\"{strength_value}\", asText(player->getStrength()));\n\t}\n else if (event_name == \"DEC_DEXTERITY\")\n {\n player->decDexterity();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{dexterity_value}\", asText(player->getDexterity()));\n }\n else if (event_name == \"INC_DEXTERITY\")\n {\n player->incDexterity();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{dexterity_value}\", asText(player->getDexterity()));\n }\n else if (event_name == \"DEC_AGILITY\")\n {\n player->decAgility();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{agility_value}\", asText(player->getAgility()));\n }\n else if (event_name == \"INC_AGILITY\")\n {\n player->incAgility();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{agility_value}\", asText(player->getAgility()));\n }\n else if (event_name == \"DEC_WISDOM\")\n {\n player->decWisdom();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{wisdom_value}\", asText(player->getWisdom()));\n }\n else if (event_name == \"INC_WISDOM\")\n {\n player->incWisdom();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{wisdom_value}\", asText(player->getWisdom()));\n }\n else if (event_name == \"DEC_INTELIGENCE\")\n {\n player->decInteligence();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{inteligence_value}\", asText(player->getInteligence()));\n }\n else if (event_name == \"INC_INTELIGENCE\")\n {\n player->incInteligence();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{inteligence_value}\", asText(player->getInteligence()));\n }\n else if (event_name == \"DEC_CHARISMA\")\n {\n player->decCharisma();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{charisma_value}\", asText(player->getCharisma()));\n }\n else if (event_name == \"INC_CHARISMA\")\n {\n player->incCharisma();\n\t\tcurrent_view->setText(\"{points_value}\", asText(player->getPoints()));\n current_view->setText(\"{charisma_value}\", asText(player->getCharisma()));\n }\n\telse if (event_name == \"START_GAME\")\n\t{\n\t\tsetView(\"mainmenu\");\n\t\taddView(\"player_card\", false);\n\t}\n\telse\n {\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::settingsEvent(std::string event_name)\n{\n if (event_name == \"BACK\")\n {\n setView(\"mainmenu\");\n }\n else if (event_name.substr(0, 9) == \"LANGUAGE_\")\n {\n std::cout << \"new language: \" << event_name.substr(9) << std::endl;\n model->setLanguage(event_name.substr(9));\n setView(\"settings\");\n }\n else\n {\n std::cout << \"cut: \" << event_name.substr(0, 8) << std::endl;\n std::cout << \"error, unexpected command:\" << std::setw(10) << event_name << std::endl;\n }\n}\n\nvoid Controller::startNewGame()\n{\n std::cout << \"new game starting\\n\";\n setView(\"new_game\");\n}\n\nvoid Controller::setView(std::string view)\n{\n std::cout << \"changed view to: \" << std::setw(10) << view << std::endl;\n current_view_name = view;\n current_view = model->getXml(\"view_\" + view);\n window->setView(current_view);\n}\n\nvoid Controller::addView(std::string view, bool deactivation)\n{\n\tView* v;\n\tif (deactivation)\n\t{\n\t\tv = model->getXml(\"view_blockade\");\n\t\tcurrent_view->extendView(v);\n\t}\n\tv = model->getXml(\"view_\" + view);\n\tcurrent_view->extendView(v);\n\twindow->updateClickmap();\n}\n\nvoid Controller::delView()\n{\n\tcurrent_view->removeLastView();\n\twindow->updateClickmap();\n}\n\nvoid Controller::setDone()\n{\n getController().running = false;\n}\n\nController &Controller::getController()\n{\n static Controller controller;\n return controller;\n}\n\nstd::string Controller::asText(int number)\n{\n char buff[3];\n snprintf(buff, sizeof(buff), \"%d\", number);\n return buff;\n}\n\nvoid Controller::loadStats(Character *character)\n{\n\tcurrent_view->setText(\"{points_value}\", asText(character->getPoints()));\n current_view->setText(\"{strength_value}\", asText(character->getStrength()));\n current_view->setText(\"{dexterity_value}\", asText(character->getDexterity()));\n current_view->setText(\"{agility_value}\", asText(character->getAgility()));\n current_view->setText(\"{wisdom_value}\", asText(character->getWisdom()));\n current_view->setText(\"{inteligence_value}\", asText(character->getInteligence()));\n current_view->setText(\"{charisma_value}\", asText(character->getCharisma()));\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix of the initial locale set.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nfarrtl.cpp\n\n८। 㭪権 ࠡ : new\/delete\/malloc\/realloc\/free\n*\/\n\n\/* Revision: 1.02 05.07.2000 $ *\/\n\n\/*\nModify:\n 03.07.2000 IS\n ! 祭 ᥣ 䠩 ஥\n 04.07.2000 SVS\n ! 뤥 ⢥ ᠬ筮 !\n 05.07.2000 IS\n ! ஢ப, ᠫ , ࠢ\n , ᫨ ८। new\/delete :-(((\n*\/\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\ntypedef unsigned size_t;\n\nvoid *malloc(size_t size);\nvoid *realloc(void *block, size_t size);\nvoid free(void *block);\n\n#ifdef __cplusplus\n}\n#endif\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\nstatic HANDLE FARHeapForNew=NULL;\n\nvoid *malloc(size_t size)\n{\n void *p;\n if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();\n if(FARHeapForNew) p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,size);\n\/\/ if(p==NULL)MessageBox(NULL,\"NULL\",\"p\",0);\n return p;\n}\n\nvoid *realloc(void *block, size_t size)\n{\n void *p;\n if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();\n if(FARHeapForNew)\n {\n if (block) p=HeapReAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,block,size);\n else p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY, size);\n }\n\/\/ if(p==NULL)MessageBox(NULL,\"NULL\",\"p\",0);\n return p;\n}\n\nvoid free(void *block)\n{\n if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();\n if(FARHeapForNew) HeapFree(FARHeapForNew,0,block);\n}\n\n#if 0 \/\/ ⮣ ࠡ⠥, 稭\nvoid *operator new(size_t sz)\n {\n extern new_handler _new_handler;\n void *p;\n sz=sz?sz:1;\n while((p=malloc(sz))==NULL)\n {\n if(_new_handler!=NULL)_new_handler();\n else break;\n }\n return p;\n }\nvoid operator delete(void *v)\n {\n if(v)free(v);\n }\nvoid *operator new[](size_t sz)\n {\n extern new_handler _new_handler;\n void *p;\n sz=sz?sz:1;\n while((p=malloc(sz))==NULL)\n {\n if(_new_handler!=NULL)_new_handler();\n else break;\n }\n return p;\n }\nvoid operator delete[](void *v)\n {\n if(v)free(v);\n }\n#endif\n<commit_msg>FAR patch 00047.farrtl.cpp Дата : 11.07.2000 Сделал : Valentin Skirdin Описание : Более разумное (с запасом) распределение памяти. Измененные файлы : farrtl.cpp Состав : farrtl.cpp.47.diff 47.farrtl.cpp.txt Основан на патче : 46 Дополнение :<commit_after>\/*\nfarrtl.cpp\n\n८। 㭪権 ࠡ : new\/delete\/malloc\/realloc\/free\n*\/\n\n\/* Revision: 1.03 11.07.2000 $ *\/\n\n\/*\nModify:\n 03.07.2000 IS\n ! 祭 ᥣ 䠩 ஥\n 04.07.2000 SVS\n ! 뤥 ⢥ ᠬ筮 !\n 05.07.2000 IS\n ! ஢ப, ᠫ , ࠢ\n , ᫨ ८। new\/delete :-(((\n 11.07.2000 SVS\n\n*\/\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\ntypedef unsigned size_t;\n\nvoid *malloc(size_t size);\nvoid *realloc(void *block, size_t size);\nvoid free(void *block);\n\n#ifdef __cplusplus\n}\n#endif\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\n#define MEM_DELTA\t1023\n\nstatic HANDLE FARHeapForNew=NULL;\n\nvoid *malloc(size_t size)\n{\n return realloc(NULL,size);\n}\n\n\nvoid *realloc(void *block, size_t size)\n{\n void *p=NULL;\n int size2;\n\n if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();\n\n if(FARHeapForNew)\n {\n if(!size)\n HeapFree(FARHeapForNew,0,block);\n else if (!block) \/\/ ࠧ ⮫쪮, ᪮쪮\n \/\/ . - 뫮 譥 室 筮 맮\n p=HeapAlloc(FARHeapForNew,HEAP_ZERO_MEMORY, size);\n else\n {\n p=block;\n \/\/ Required size, alligned to MEM_DELTA\n size = (size + MEM_DELTA) & (~MEM_DELTA);\n \/\/ Current allocated size\n size2 = HeapSize(FARHeapForNew,0,block);\n if (size > size2 || \/\/ ᨫ , 祬 ॠ쭮 뤥\n size2 - size > MEM_DELTA) \/\/ ᢮ ࠧ஬ MEM_DELTA \n p=HeapReAlloc(FARHeapForNew,HEAP_ZERO_MEMORY,block,size);\n \/\/ else\n \/*\n 祣. 娯 㦥 뤥 ࠧ ண .\n ணࠬ ⠥, ந諨 ...\n *\/\n }\n }\n return p;\n}\n\nvoid free(void *block)\n{\n if(!FARHeapForNew) FARHeapForNew=GetProcessHeap();\n if(FARHeapForNew) HeapFree(FARHeapForNew,0,block);\n}\n\n#if 0 \/\/ ⮣ ࠡ⠥, 稭\nvoid *operator new(size_t sz)\n {\n extern new_handler _new_handler;\n void *p;\n sz=sz?sz:1;\n while((p=malloc(sz))==NULL)\n {\n if(_new_handler!=NULL)_new_handler();\n else break;\n }\n return p;\n }\nvoid operator delete(void *v)\n {\n if(v)free(v);\n }\nvoid *operator new[](size_t sz)\n {\n extern new_handler _new_handler;\n void *p;\n sz=sz?sz:1;\n while((p=malloc(sz))==NULL)\n {\n if(_new_handler!=NULL)_new_handler();\n else break;\n }\n return p;\n }\nvoid operator delete[](void *v)\n {\n if(v)free(v);\n }\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2015 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <cassert>\n#include <cstdlib>\n#include <string>\n#include <subhook.h>\n#include \"jithandler.h\"\n#include \"logprintf.h\"\n#include \"os.h\"\n#include \"plugin.h\"\n#include \"version.h\"\n\ntypedef int (AMXAPI *AMX_EXEC)(AMX *amx, cell *retval, int index);\n\nextern void *pAMXFunctions;\nstatic subhook::Hook exec_hook;\n\n#ifdef LINUX\n static cell *opcode_table = NULL;\n#endif\n\nnamespace {\n\nvoid *GetAmxFunction(int index) {\n return static_cast<void**>(pAMXFunctions)[index];\n}\n\nstd::string GetFileName(const std::string &path) {\n std::string::size_type pos = path.find_last_of(\"\/\\\\\");\n if (pos != std::string::npos) {\n return path.substr(pos + 1);\n }\n return path;\n}\n\nint AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {\n #ifdef LINUX\n if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {\n assert(::opcode_table != 0);\n *retval = reinterpret_cast<cell>(::opcode_table);\n return AMX_ERR_NONE;\n }\n #endif\n int error = JITHandler::GetHandler(amx)->Exec(retval, index);\n if (error == AMX_ERR_INIT_JIT) {\n AMX_EXEC exec = (AMX_EXEC)exec_hook.GetTrampoline();\n return exec(amx, retval, index);\n }\n return error;\n}\n\ncell AMX_NATIVE_CALL n_JITSleep(AMX *amx, cell *params) {\n amx->error = AMX_ERR_SLEEP;\n return 0;\n}\n\n} \/\/ anonymous namespace\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n\n void *exec_start = GetAmxFunction(PLUGIN_AMX_EXPORT_Exec);\n void *other_guy = subhook::Hook::ReadDst(exec_start);\n\n if (other_guy != 0) {\n std::string module = GetFileName(os::GetModuleName(other_guy));\n if (!module.empty()) {\n logprintf(\" JIT plugin must be loaded before '%s'\", module.c_str());\n } else {\n logprintf(\" Sorry, your server is messed up\");\n }\n return false;\n }\n\n #ifdef LINUX\n \/\/ Get the opcode table before we hook amx_Exec().\n AMX amx = {0};\n amx.flags |= AMX_FLAG_BROWSE;\n amx_Exec(&amx, reinterpret_cast<cell*>(&::opcode_table), 0);\n amx.flags &= ~AMX_FLAG_BROWSE;\n #endif\n exec_hook.Install(exec_start, (void *)amx_Exec_JIT);\n\n logprintf(\" JIT plugin %s\", PROJECT_VERSION_STRING);\n return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n if (std::getenv(\"JIT_TEST\") != NULL) {\n const AMX_NATIVE_INFO natives[] = {\n {\"JITSleep\", n_JITSleep}\n };\n amx_Register(amx, natives, sizeof(natives) \/ sizeof(natives[0]));\n }\n return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n JITHandler::DestroyHandler(amx);\n return AMX_ERR_NONE;\n}\n<commit_msg>Remove JITSleep native<commit_after>\/\/ Copyright (c) 2012-2015 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <cassert>\n#include <cstdlib>\n#include <string>\n#include <subhook.h>\n#include \"jithandler.h\"\n#include \"logprintf.h\"\n#include \"os.h\"\n#include \"plugin.h\"\n#include \"version.h\"\n\ntypedef int (AMXAPI *AMX_EXEC)(AMX *amx, cell *retval, int index);\n\nextern void *pAMXFunctions;\nstatic subhook::Hook exec_hook;\n\n#ifdef LINUX\n static cell *opcode_table = NULL;\n#endif\n\nnamespace {\n\nvoid *GetAmxFunction(int index) {\n return static_cast<void**>(pAMXFunctions)[index];\n}\n\nstd::string GetFileName(const std::string &path) {\n std::string::size_type pos = path.find_last_of(\"\/\\\\\");\n if (pos != std::string::npos) {\n return path.substr(pos + 1);\n }\n return path;\n}\n\nint AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {\n #ifdef LINUX\n if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {\n assert(::opcode_table != 0);\n *retval = reinterpret_cast<cell>(::opcode_table);\n return AMX_ERR_NONE;\n }\n #endif\n int error = JITHandler::GetHandler(amx)->Exec(retval, index);\n if (error == AMX_ERR_INIT_JIT) {\n AMX_EXEC exec = (AMX_EXEC)exec_hook.GetTrampoline();\n return exec(amx, retval, index);\n }\n return error;\n}\n\n} \/\/ anonymous namespace\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n\n void *exec_start = GetAmxFunction(PLUGIN_AMX_EXPORT_Exec);\n void *other_guy = subhook::Hook::ReadDst(exec_start);\n\n if (other_guy != 0) {\n std::string module = GetFileName(os::GetModuleName(other_guy));\n if (!module.empty()) {\n logprintf(\" JIT plugin must be loaded before '%s'\", module.c_str());\n } else {\n logprintf(\" Sorry, your server is messed up\");\n }\n return false;\n }\n\n #ifdef LINUX\n \/\/ Get the opcode table before we hook amx_Exec().\n AMX amx = {0};\n amx.flags |= AMX_FLAG_BROWSE;\n amx_Exec(&amx, reinterpret_cast<cell*>(&::opcode_table), 0);\n amx.flags &= ~AMX_FLAG_BROWSE;\n #endif\n exec_hook.Install(exec_start, (void *)amx_Exec_JIT);\n\n logprintf(\" JIT plugin %s\", PROJECT_VERSION_STRING);\n return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n JITHandler::DestroyHandler(amx);\n return AMX_ERR_NONE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * KQOAuth - An OAuth authentication library for Qt.\n *\n * Author: Johan Paul (johan.paul@gmail.com)\n * http:\/\/www.johanpaul.com\n *\n * KQOAuth is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * KQOAuth is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with KQOAuth. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <QByteArray>\n#include <QDateTime>\n#include <QCryptographicHash>\n#include <QPair>\n#include <QStringList>\n\n#include <QtDebug>\n#include <QtAlgorithms>\n\n#include \"kqoauthrequest.h\"\n#include \"kqoauthrequest_p.h\"\n#include \"kqoauthutils.h\"\n#include \"kqoauthglobals.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/ Private d_ptr implementation \/\/\/\/\/\/\/\/\/\n\nKQOAuthRequestPrivate::KQOAuthRequestPrivate()\n{\n\n}\n\nKQOAuthRequestPrivate::~KQOAuthRequestPrivate()\n{\n\n}\n\n\/\/ This method will not include the \"oauthSignature\" paramater, since it is calculated from these parameters.\nvoid KQOAuthRequestPrivate::prepareRequest() {\n\n \/\/ If parameter list is not empty, we don't want to insert these values by\n \/\/ accident a second time. So giving up.\n if( !requestParameters.isEmpty() ) {\n return;\n }\n\n switch ( requestType ) {\n case KQOAuthRequest::TemporaryCredentials:\n requestParameters.append( qMakePair( OAUTH_KEY_CALLBACK, QString(QUrl::toPercentEncoding( oauthCallbackUrl.toString()) ))); \/\/ This is so ugly that it is almost beautiful.\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n insertAdditionalParams(requestParameters);\n break;\n\n case KQOAuthRequest::AccessToken:\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERIFIER, oauthVerifier ));\n requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));\n insertAdditionalParams(requestParameters);\n break;\n\n case KQOAuthRequest::AuthorizedRequest:\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));\n insertAdditionalParams(requestParameters);\n break;\n\n default:\n break;\n }\n}\n\nvoid KQOAuthRequestPrivate::insertAdditionalParams(QList< QPair<QString, QString> > &requestParams) {\n QList<QString> additionalKeys = this->additionalParams.keys();\n QList<QString> additionalValues = this->additionalParams.values();\n\n for(int i=0; i<additionalKeys.size(); i++) {\n requestParams.append( qMakePair(QString(QUrl::toPercentEncoding(additionalKeys.at(i))),\n QString(QUrl::toPercentEncoding(additionalValues.at(i))))\n );\n }\n\n if (oauthHttpMethod == KQOAuthRequest::POST) {\n insertPostBody();\n }\n}\n\nvoid KQOAuthRequestPrivate::insertPostBody() {\n QList<QString> postBodyKeys = this->additionalParams.keys();\n QList<QString> postBodyValues = this->additionalParams.values();\n\n postBodyContent.clear();\n bool first = true;\n for(int i=0; i<postBodyKeys.size(); i++) {\n if(!first) {\n postBodyContent.append(\"&\");\n } else {\n first = false;\n }\n\n QString key = postBodyKeys.at(i);\n QString value = postBodyValues.at(i);\n\n postBodyContent.append(QUrl::toPercentEncoding(key) + QString(\"=\").toUtf8() +\n QUrl::toPercentEncoding(value));\n }\n\n}\n\nvoid KQOAuthRequestPrivate::signRequest() {\n QString signature = this->oauthSignature();\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE, signature) );\n}\n\nQString KQOAuthRequestPrivate::oauthSignature() {\n QByteArray baseString = this->requestBaseString();\n\n QString signature = KQOAuthUtils::hmac_sha1(baseString, oauthConsumerSecretKey + \"&\" + oauthTokenSecret);\n return QString( QUrl::toPercentEncoding( signature ) );\n}\n\nbool normalizedParameterSort(const QPair<QString, QString> &left, const QPair<QString, QString> &right) {\n QString keyLeft = left.first;\n QString valueLeft = left.second;\n QString keyRight = right.first;\n QString valueRight = right.second;\n\n if(keyLeft == keyRight) {\n return (valueLeft < valueRight);\n } else {\n return (keyLeft < keyRight);\n }\n}\nQByteArray KQOAuthRequestPrivate::requestBaseString() {\n QByteArray baseString;\n\n \/\/ Every request has these as the commont parameters.\n baseString.append( oauthHttpMethodString.toUtf8() + \"&\"); \/\/ HTTP method\n baseString.append( QUrl::toPercentEncoding( oauthRequestEndpoint.toString(QUrl::RemoveQuery) ) + \"&\" ); \/\/ The path and query components\n\n QList< QPair<QString, QString> > baseStringParameters;\n baseStringParameters.append(requestParameters);\n\n \/\/ Sort the request parameters. These parameters have been\n \/\/ initialized earlier.\n qSort(baseStringParameters.begin(),\n baseStringParameters.end(),\n normalizedParameterSort\n );\n\n \/\/ Last append the request parameters correctly encoded.\n baseString.append( encodedParamaterList(baseStringParameters) );\n\n return baseString;\n}\n\nQByteArray KQOAuthRequestPrivate::encodedParamaterList(const QList< QPair<QString, QString> > ¶meters) {\n QByteArray resultList;\n\n bool first = true;\n QPair<QString, QString> parameter;\n foreach (parameter, parameters) {\n if(!first) {\n resultList.append( \"%26\" );\n } else {\n first = false;\n }\n\n \/\/ Here we don't need to explicitely encode the strings to UTF-8 since\n \/\/ QUrl::toPercentEncoding() takes care of that for us.\n resultList.append( QUrl::toPercentEncoding(parameter.first) \/\/ Parameter key\n + \"%3D\" \/\/ '=' encoded\n + QUrl::toPercentEncoding(parameter.second) \/\/ Parameter value\n );\n }\n\n return resultList;\n}\n\nQString KQOAuthRequestPrivate::oauthTimestamp() const {\n \/\/ This is basically for unit tests only. In most cases we don't set the nonce beforehand.\n if (!oauthTimestamp_.isEmpty()) {\n return oauthTimestamp_;\n }\n\n#if QT_VERSION >= 0x040700\n return QString::number(QDateTime::currentDateTimeUtc().toTime_t());\n#else\n return QString::number(QDateTime::currentDateTime().toUTC().toTime_t());\n#endif\n\n}\n\nQString KQOAuthRequestPrivate::oauthNonce() const {\n \/\/ This is basically for unit tests only. In most cases we don't set the nonce beforehand.\n if (!oauthNonce_.isEmpty()) {\n return oauthNonce_;\n }\n\n QString nonceTimestamp = oauthTimestamp_;\n\n if (nonceTimestamp.isEmpty()) {\n nonceTimestamp = oauthTimestamp();\n }\n\n return QCryptographicHash::hash(nonceTimestamp.toAscii(), QCryptographicHash::Md5).toHex();\n}\n\nbool KQOAuthRequestPrivate::validateRequest() const { \n switch ( requestType ) {\n case KQOAuthRequest::TemporaryCredentials:\n if (oauthRequestEndpoint.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n case KQOAuthRequest::AccessToken:\n if (oauthRequestEndpoint.isEmpty()\n || oauthVerifier.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthToken.isEmpty()\n || oauthTokenSecret.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n case KQOAuthRequest::AuthorizedRequest:\n if (oauthRequestEndpoint.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthToken.isEmpty()\n || oauthTokenSecret.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n default:\n return false;\n }\n\n \/\/ We should not come here.\n return false;\n}\n\nQByteArray KQOAuthRequestPrivate::requestBody() const {\n return postBodyContent;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/ Public implementation \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nKQOAuthRequest::KQOAuthRequest(QObject *parent) :\n QObject(parent),\n d_ptr(new KQOAuthRequestPrivate)\n{\n}\n\nKQOAuthRequest::~KQOAuthRequest()\n{\n delete d_ptr;\n}\n\nvoid KQOAuthRequest::initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint) {\n Q_D(KQOAuthRequest);\n\n if (!requestEndpoint.isValid()) {\n qWarning() << \"Endpoint URL is not valid. Ignoring. This request might not work.\";\n return;\n }\n\n if (type < 0 || type > KQOAuthRequest::AuthorizedRequest) {\n qWarning() << \"Invalid request type. Ignoring. This request might not work.\";\n return;\n }\n\n \/\/ Set smart defaults.\n d->requestType = type;\n d->oauthRequestEndpoint = requestEndpoint;\n d->oauthTimestamp_ = d->oauthTimestamp();\n d->oauthNonce_ = d->oauthNonce();\n this->setSignatureMethod(KQOAuthRequest::HMAC_SHA1);\n this->setHttpMethod(KQOAuthRequest::POST);\n d->oauthVersion = \"1.0\"; \/\/ Currently supports only version 1.0\n}\n\nvoid KQOAuthRequest::setConsumerKey(const QString &consumerKey) {\n Q_D(KQOAuthRequest);\n d->oauthConsumerKey = consumerKey;\n}\n\nvoid KQOAuthRequest::setConsumerSecretKey(const QString &consumerSecretKey) {\n Q_D(KQOAuthRequest);\n d->oauthConsumerSecretKey = consumerSecretKey;\n}\n\nvoid KQOAuthRequest::setCallbackUrl(const QUrl &callbackUrl) {\n Q_D(KQOAuthRequest);\n\n d->oauthCallbackUrl = callbackUrl;\n}\n\nvoid KQOAuthRequest::setSignatureMethod(KQOAuthRequest::RequestSignatureMethod requestMethod) {\n Q_D(KQOAuthRequest);\n QString requestMethodString;\n\n switch (requestMethod) {\n case KQOAuthRequest::PLAINTEXT:\n requestMethodString = \"PLAINTEXT\";\n break;\n case KQOAuthRequest::HMAC_SHA1:\n requestMethodString = \"HMAC-SHA1\";\n break;\n case KQOAuthRequest::RSA_SHA1:\n requestMethodString = \"RSA-SHA1\";\n break;\n default:\n \/\/ We should not come here\n qWarning() << \"Invalid signature method set.\";\n break;\n }\n\n d->oauthSignatureMethod = requestMethodString;\n}\n\nvoid KQOAuthRequest::setTokenSecret(const QString &tokenSecret) {\n Q_D(KQOAuthRequest);\n\n d->oauthTokenSecret = tokenSecret;\n}\n\nvoid KQOAuthRequest::setToken(const QString &token) {\n Q_D(KQOAuthRequest);\n\n d->oauthToken = token;\n}\n\nvoid KQOAuthRequest::setVerifier(const QString &verifier) {\n Q_D(KQOAuthRequest);\n\n d->oauthVerifier = verifier;\n}\n\n\nvoid KQOAuthRequest::setHttpMethod(KQOAuthRequest::RequestHttpMethod httpMethod) {\n Q_D(KQOAuthRequest);\n\n QString requestHttpMethodString;\n\n switch (httpMethod) {\n case KQOAuthRequest::GET:\n requestHttpMethodString = \"GET\";\n break;\n case KQOAuthRequest::POST:\n requestHttpMethodString = \"POST\";\n break;\n default:\n qWarning() << \"Invalid HTTP method set.\";\n break;\n }\n\n d->oauthHttpMethod = httpMethod;\n d->oauthHttpMethodString = requestHttpMethodString;\n}\n\nKQOAuthRequest::RequestHttpMethod KQOAuthRequest::httpMethod() const {\n Q_D(const KQOAuthRequest);\n\n return d->oauthHttpMethod;\n}\n\nvoid KQOAuthRequest::setAdditionalParameters(const KQOAuthParameters &additionalParams) {\n Q_D(KQOAuthRequest);\n\n d->additionalParams = additionalParams;\n}\n\nKQOAuthParameters KQOAuthRequest::additionalParameters() const {\n Q_D(const KQOAuthRequest);\n\n return d->additionalParams;\n}\n\nKQOAuthRequest::RequestType KQOAuthRequest::requestType() const {\n Q_D(const KQOAuthRequest);\n\n return d->requestType;\n}\n\nQUrl KQOAuthRequest::requestEndpoint() const {\n Q_D(const KQOAuthRequest);\n\n return d->oauthRequestEndpoint;\n}\n\nQList<QByteArray> KQOAuthRequest::requestParameters() {\n Q_D(KQOAuthRequest);\n\n QList<QByteArray> requestParamList;\n\n d->prepareRequest();\n if (!d->validateRequest() ) {\n qWarning() << \"Request is not valid! I will still sign it, but it will probably not work.\";\n }\n d->signRequest();\n\n QPair<QString, QString> requestParam;\n QString param;\n QString value;\n foreach (requestParam, d->requestParameters) {\n param = requestParam.first;\n value = requestParam.second;\n requestParamList.append(QString(param + \"=\\\"\" + value +\"\\\"\").toUtf8());\n }\n\n return requestParamList;\n}\n\nbool KQOAuthRequest::isValid() const {\n Q_D(const KQOAuthRequest);\n\n return d->validateRequest();\n}\n\nvoid KQOAuthRequest::clearRequest() {\n Q_D(KQOAuthRequest);\n\n d->oauthRequestEndpoint = \"\";\n d->oauthHttpMethodString = \"\";\n d->oauthConsumerKey = \"\";\n d->oauthConsumerSecretKey = \"\";\n d->oauthToken = \"\";\n d->oauthTokenSecret = \"\";\n d->oauthSignatureMethod = \"\";\n d->oauthCallbackUrl = \"\";\n d->oauthVerifier = \"\";\n d->oauthTimestamp_ = \"\";\n d->oauthNonce_ = \"\";\n d->requestParameters.clear();\n d->additionalParams.clear();\n}\n\n\n<commit_msg>When initing the request, we should clear old data too.<commit_after>\/**\n * KQOAuth - An OAuth authentication library for Qt.\n *\n * Author: Johan Paul (johan.paul@gmail.com)\n * http:\/\/www.johanpaul.com\n *\n * KQOAuth is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * KQOAuth is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with KQOAuth. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <QByteArray>\n#include <QDateTime>\n#include <QCryptographicHash>\n#include <QPair>\n#include <QStringList>\n\n#include <QtDebug>\n#include <QtAlgorithms>\n\n#include \"kqoauthrequest.h\"\n#include \"kqoauthrequest_p.h\"\n#include \"kqoauthutils.h\"\n#include \"kqoauthglobals.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/ Private d_ptr implementation \/\/\/\/\/\/\/\/\/\n\nKQOAuthRequestPrivate::KQOAuthRequestPrivate()\n{\n\n}\n\nKQOAuthRequestPrivate::~KQOAuthRequestPrivate()\n{\n\n}\n\n\/\/ This method will not include the \"oauthSignature\" paramater, since it is calculated from these parameters.\nvoid KQOAuthRequestPrivate::prepareRequest() {\n\n \/\/ If parameter list is not empty, we don't want to insert these values by\n \/\/ accident a second time. So giving up.\n if( !requestParameters.isEmpty() ) {\n return;\n }\n\n switch ( requestType ) {\n case KQOAuthRequest::TemporaryCredentials:\n requestParameters.append( qMakePair( OAUTH_KEY_CALLBACK, QString(QUrl::toPercentEncoding( oauthCallbackUrl.toString()) ))); \/\/ This is so ugly that it is almost beautiful.\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n insertAdditionalParams(requestParameters);\n break;\n\n case KQOAuthRequest::AccessToken:\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERIFIER, oauthVerifier ));\n requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));\n insertAdditionalParams(requestParameters);\n break;\n\n case KQOAuthRequest::AuthorizedRequest:\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod ));\n requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey ));\n requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion ));\n requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() ));\n requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() ));\n requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken ));\n insertAdditionalParams(requestParameters);\n break;\n\n default:\n break;\n }\n}\n\nvoid KQOAuthRequestPrivate::insertAdditionalParams(QList< QPair<QString, QString> > &requestParams) {\n QList<QString> additionalKeys = this->additionalParams.keys();\n QList<QString> additionalValues = this->additionalParams.values();\n\n for(int i=0; i<additionalKeys.size(); i++) {\n requestParams.append( qMakePair(QString(QUrl::toPercentEncoding(additionalKeys.at(i))),\n QString(QUrl::toPercentEncoding(additionalValues.at(i))))\n );\n }\n\n if (oauthHttpMethod == KQOAuthRequest::POST) {\n insertPostBody();\n }\n}\n\nvoid KQOAuthRequestPrivate::insertPostBody() {\n QList<QString> postBodyKeys = this->additionalParams.keys();\n QList<QString> postBodyValues = this->additionalParams.values();\n\n postBodyContent.clear();\n bool first = true;\n for(int i=0; i<postBodyKeys.size(); i++) {\n if(!first) {\n postBodyContent.append(\"&\");\n } else {\n first = false;\n }\n\n QString key = postBodyKeys.at(i);\n QString value = postBodyValues.at(i);\n\n postBodyContent.append(QUrl::toPercentEncoding(key) + QString(\"=\").toUtf8() +\n QUrl::toPercentEncoding(value));\n }\n\n}\n\nvoid KQOAuthRequestPrivate::signRequest() {\n QString signature = this->oauthSignature();\n requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE, signature) );\n}\n\nQString KQOAuthRequestPrivate::oauthSignature() {\n QByteArray baseString = this->requestBaseString();\n\n QString signature = KQOAuthUtils::hmac_sha1(baseString, oauthConsumerSecretKey + \"&\" + oauthTokenSecret);\n return QString( QUrl::toPercentEncoding( signature ) );\n}\n\nbool normalizedParameterSort(const QPair<QString, QString> &left, const QPair<QString, QString> &right) {\n QString keyLeft = left.first;\n QString valueLeft = left.second;\n QString keyRight = right.first;\n QString valueRight = right.second;\n\n if(keyLeft == keyRight) {\n return (valueLeft < valueRight);\n } else {\n return (keyLeft < keyRight);\n }\n}\nQByteArray KQOAuthRequestPrivate::requestBaseString() {\n QByteArray baseString;\n\n \/\/ Every request has these as the commont parameters.\n baseString.append( oauthHttpMethodString.toUtf8() + \"&\"); \/\/ HTTP method\n baseString.append( QUrl::toPercentEncoding( oauthRequestEndpoint.toString(QUrl::RemoveQuery) ) + \"&\" ); \/\/ The path and query components\n\n QList< QPair<QString, QString> > baseStringParameters;\n baseStringParameters.append(requestParameters);\n\n \/\/ Sort the request parameters. These parameters have been\n \/\/ initialized earlier.\n qSort(baseStringParameters.begin(),\n baseStringParameters.end(),\n normalizedParameterSort\n );\n\n \/\/ Last append the request parameters correctly encoded.\n baseString.append( encodedParamaterList(baseStringParameters) );\n\n return baseString;\n}\n\nQByteArray KQOAuthRequestPrivate::encodedParamaterList(const QList< QPair<QString, QString> > ¶meters) {\n QByteArray resultList;\n\n bool first = true;\n QPair<QString, QString> parameter;\n foreach (parameter, parameters) {\n if(!first) {\n resultList.append( \"%26\" );\n } else {\n first = false;\n }\n\n \/\/ Here we don't need to explicitely encode the strings to UTF-8 since\n \/\/ QUrl::toPercentEncoding() takes care of that for us.\n resultList.append( QUrl::toPercentEncoding(parameter.first) \/\/ Parameter key\n + \"%3D\" \/\/ '=' encoded\n + QUrl::toPercentEncoding(parameter.second) \/\/ Parameter value\n );\n }\n\n return resultList;\n}\n\nQString KQOAuthRequestPrivate::oauthTimestamp() const {\n \/\/ This is basically for unit tests only. In most cases we don't set the nonce beforehand.\n if (!oauthTimestamp_.isEmpty()) {\n return oauthTimestamp_;\n }\n\n#if QT_VERSION >= 0x040700\n return QString::number(QDateTime::currentDateTimeUtc().toTime_t());\n#else\n return QString::number(QDateTime::currentDateTime().toUTC().toTime_t());\n#endif\n\n}\n\nQString KQOAuthRequestPrivate::oauthNonce() const {\n \/\/ This is basically for unit tests only. In most cases we don't set the nonce beforehand.\n if (!oauthNonce_.isEmpty()) {\n return oauthNonce_;\n }\n\n QString nonceTimestamp = oauthTimestamp_;\n\n if (nonceTimestamp.isEmpty()) {\n nonceTimestamp = oauthTimestamp();\n }\n\n return QCryptographicHash::hash(nonceTimestamp.toAscii(), QCryptographicHash::Md5).toHex();\n}\n\nbool KQOAuthRequestPrivate::validateRequest() const { \n switch ( requestType ) {\n case KQOAuthRequest::TemporaryCredentials:\n if (oauthRequestEndpoint.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n case KQOAuthRequest::AccessToken:\n if (oauthRequestEndpoint.isEmpty()\n || oauthVerifier.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthToken.isEmpty()\n || oauthTokenSecret.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n case KQOAuthRequest::AuthorizedRequest:\n if (oauthRequestEndpoint.isEmpty()\n || oauthConsumerKey.isEmpty()\n || oauthNonce_.isEmpty()\n || oauthSignatureMethod.isEmpty()\n || oauthTimestamp_.isEmpty()\n || oauthToken.isEmpty()\n || oauthTokenSecret.isEmpty()\n || oauthVersion.isEmpty())\n {\n return false;\n }\n return true;\n\n default:\n return false;\n }\n\n \/\/ We should not come here.\n return false;\n}\n\nQByteArray KQOAuthRequestPrivate::requestBody() const {\n return postBodyContent;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/ Public implementation \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nKQOAuthRequest::KQOAuthRequest(QObject *parent) :\n QObject(parent),\n d_ptr(new KQOAuthRequestPrivate)\n{\n}\n\nKQOAuthRequest::~KQOAuthRequest()\n{\n delete d_ptr;\n}\n\nvoid KQOAuthRequest::initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint) {\n Q_D(KQOAuthRequest);\n\n if (!requestEndpoint.isValid()) {\n qWarning() << \"Endpoint URL is not valid. Ignoring. This request might not work.\";\n return;\n }\n\n if (type < 0 || type > KQOAuthRequest::AuthorizedRequest) {\n qWarning() << \"Invalid request type. Ignoring. This request might not work.\";\n return;\n }\n\n \/\/ Clear the request\n clearRequest();\n\n \/\/ Set smart defaults.\n d->requestType = type;\n d->oauthRequestEndpoint = requestEndpoint;\n d->oauthTimestamp_ = d->oauthTimestamp();\n d->oauthNonce_ = d->oauthNonce();\n this->setSignatureMethod(KQOAuthRequest::HMAC_SHA1);\n this->setHttpMethod(KQOAuthRequest::POST);\n d->oauthVersion = \"1.0\"; \/\/ Currently supports only version 1.0\n}\n\nvoid KQOAuthRequest::setConsumerKey(const QString &consumerKey) {\n Q_D(KQOAuthRequest);\n d->oauthConsumerKey = consumerKey;\n}\n\nvoid KQOAuthRequest::setConsumerSecretKey(const QString &consumerSecretKey) {\n Q_D(KQOAuthRequest);\n d->oauthConsumerSecretKey = consumerSecretKey;\n}\n\nvoid KQOAuthRequest::setCallbackUrl(const QUrl &callbackUrl) {\n Q_D(KQOAuthRequest);\n\n d->oauthCallbackUrl = callbackUrl;\n}\n\nvoid KQOAuthRequest::setSignatureMethod(KQOAuthRequest::RequestSignatureMethod requestMethod) {\n Q_D(KQOAuthRequest);\n QString requestMethodString;\n\n switch (requestMethod) {\n case KQOAuthRequest::PLAINTEXT:\n requestMethodString = \"PLAINTEXT\";\n break;\n case KQOAuthRequest::HMAC_SHA1:\n requestMethodString = \"HMAC-SHA1\";\n break;\n case KQOAuthRequest::RSA_SHA1:\n requestMethodString = \"RSA-SHA1\";\n break;\n default:\n \/\/ We should not come here\n qWarning() << \"Invalid signature method set.\";\n break;\n }\n\n d->oauthSignatureMethod = requestMethodString;\n}\n\nvoid KQOAuthRequest::setTokenSecret(const QString &tokenSecret) {\n Q_D(KQOAuthRequest);\n\n d->oauthTokenSecret = tokenSecret;\n}\n\nvoid KQOAuthRequest::setToken(const QString &token) {\n Q_D(KQOAuthRequest);\n\n d->oauthToken = token;\n}\n\nvoid KQOAuthRequest::setVerifier(const QString &verifier) {\n Q_D(KQOAuthRequest);\n\n d->oauthVerifier = verifier;\n}\n\n\nvoid KQOAuthRequest::setHttpMethod(KQOAuthRequest::RequestHttpMethod httpMethod) {\n Q_D(KQOAuthRequest);\n\n QString requestHttpMethodString;\n\n switch (httpMethod) {\n case KQOAuthRequest::GET:\n requestHttpMethodString = \"GET\";\n break;\n case KQOAuthRequest::POST:\n requestHttpMethodString = \"POST\";\n break;\n default:\n qWarning() << \"Invalid HTTP method set.\";\n break;\n }\n\n d->oauthHttpMethod = httpMethod;\n d->oauthHttpMethodString = requestHttpMethodString;\n}\n\nKQOAuthRequest::RequestHttpMethod KQOAuthRequest::httpMethod() const {\n Q_D(const KQOAuthRequest);\n\n return d->oauthHttpMethod;\n}\n\nvoid KQOAuthRequest::setAdditionalParameters(const KQOAuthParameters &additionalParams) {\n Q_D(KQOAuthRequest);\n\n d->additionalParams = additionalParams;\n}\n\nKQOAuthParameters KQOAuthRequest::additionalParameters() const {\n Q_D(const KQOAuthRequest);\n\n return d->additionalParams;\n}\n\nKQOAuthRequest::RequestType KQOAuthRequest::requestType() const {\n Q_D(const KQOAuthRequest);\n\n return d->requestType;\n}\n\nQUrl KQOAuthRequest::requestEndpoint() const {\n Q_D(const KQOAuthRequest);\n\n return d->oauthRequestEndpoint;\n}\n\nQList<QByteArray> KQOAuthRequest::requestParameters() {\n Q_D(KQOAuthRequest);\n\n QList<QByteArray> requestParamList;\n\n d->prepareRequest();\n if (!d->validateRequest() ) {\n qWarning() << \"Request is not valid! I will still sign it, but it will probably not work.\";\n }\n d->signRequest();\n\n QPair<QString, QString> requestParam;\n QString param;\n QString value;\n foreach (requestParam, d->requestParameters) {\n param = requestParam.first;\n value = requestParam.second;\n requestParamList.append(QString(param + \"=\\\"\" + value +\"\\\"\").toUtf8());\n }\n\n return requestParamList;\n}\n\nbool KQOAuthRequest::isValid() const {\n Q_D(const KQOAuthRequest);\n\n return d->validateRequest();\n}\n\nvoid KQOAuthRequest::clearRequest() {\n Q_D(KQOAuthRequest);\n\n d->oauthRequestEndpoint = \"\";\n d->oauthHttpMethodString = \"\";\n d->oauthConsumerKey = \"\";\n d->oauthConsumerSecretKey = \"\";\n d->oauthToken = \"\";\n d->oauthTokenSecret = \"\";\n d->oauthSignatureMethod = \"\";\n d->oauthCallbackUrl = \"\";\n d->oauthVerifier = \"\";\n d->oauthTimestamp_ = \"\";\n d->oauthNonce_ = \"\";\n d->requestParameters.clear();\n d->additionalParams.clear();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"XalanNode.hpp\"\n\n\n#define XALAN_NODE_SPECIAL_DEBUG\n\n#if !defined(NDEBUG)\nunsigned long\tXalanNode::s_instanceCount = 0;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n#include <iostream>\n#include <set>\n\n#if defined(XALAN_NO_NAMESPACES)\n\ntypedef set<XalanNode*>\t\t\tInstanceSetType;\n\n#else\n\ntypedef std::set<XalanNode*>\tInstanceSetType;\nusing std::cerr;\nusing std::endl;\n\n#endif\n\nstatic InstanceSetType\ts_instanceSet;\n\n#endif\n\n#endif\n\n\n\nXalanNode::XalanNode()\n{\n#if !defined(NDEBUG)\n\ts_instanceCount++;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\ts_instanceSet.insert(this);\n\n#endif\n\n#endif\n\n}\n\n\n\nXalanNode::~XalanNode()\n{\n#if !defined(NDEBUG)\n\n\ts_instanceCount--;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\ts_instanceSet.erase(this);\n\n#endif\n\n#endif\n}\n\n\n\nXalanNode::XalanNode(const XalanNode&\t\/* theSource *\/)\n{\n#if !defined(NDEBUG)\n\n\ts_instanceCount++;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\ts_instanceSet.insert(this);\n\n#endif\n\n#endif\n}\n\n\n\nXalanNode&\nXalanNode::operator=(const XalanNode&\t\/* theSource *\/)\n{\n\treturn *this;\n}\n\n\n\nbool\nXalanNode::operator==(const XalanNode&\t\/* theRHS *\/) const\n{\n\treturn false;\n}\n\n\n\n#if !defined(NDEBUG)\n\nvoid\nXalanNode::getLiveInstances(XalanNode*\ttheNodes[])\n{\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\tInstanceSetType::const_iterator\t\ti =\n\t\ts_instanceSet.begin();\n\n\tInstanceSetType::const_iterator\t\tend =\n\t\ts_instanceSet.end();\n\n\tfor(size_t j = 0; i != end; ++i, ++j)\n\t{\n\t\ttheNodes[j] = *i;\n\t}\n#endif\n}\n\n#endif\n\n<commit_msg>Removed extraneous debug code.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"XalanNode.hpp\"\n\n\n\n#if !defined(NDEBUG)\nunsigned long\tXalanNode::s_instanceCount = 0;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n#include <set>\n\n#if defined(XALAN_NO_NAMESPACES)\n\ntypedef set<XalanNode*>\t\t\tInstanceSetType;\n\n#else\n\ntypedef std::set<XalanNode*>\tInstanceSetType;\n\n#endif\n\nstatic InstanceSetType\ts_instanceSet;\n\n#endif\n\n#endif\n\n\n\nXalanNode::XalanNode()\n{\n#if !defined(NDEBUG)\n\ts_instanceCount++;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\ts_instanceSet.insert(this);\n\n#endif\n\n#endif\n\n}\n\n\n\nXalanNode::~XalanNode()\n{\n#if !defined(NDEBUG)\n\n\ts_instanceCount--;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\ts_instanceSet.erase(this);\n\n#endif\n\n#endif\n}\n\n\n\nXalanNode::XalanNode(const XalanNode&\t\/* theSource *\/)\n{\n#if !defined(NDEBUG)\n\n\ts_instanceCount++;\n\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\ts_instanceSet.insert(this);\n\n#endif\n\n#endif\n}\n\n\n\nXalanNode&\nXalanNode::operator=(const XalanNode&\t\/* theSource *\/)\n{\n\treturn *this;\n}\n\n\n\nbool\nXalanNode::operator==(const XalanNode&\t\/* theRHS *\/) const\n{\n\treturn false;\n}\n\n\n\n#if !defined(NDEBUG)\n\nvoid\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\nXalanNode::getLiveInstances(XalanNode*\ttheNodes[])\n#else\nXalanNode::getLiveInstances(XalanNode*\t\/* theNodes*\/ [])\n#endif\n{\n#if defined(XALAN_NODE_SPECIAL_DEBUG)\n\n\tInstanceSetType::const_iterator\t\ti =\n\t\ts_instanceSet.begin();\n\n\tInstanceSetType::const_iterator\t\tend =\n\t\ts_instanceSet.end();\n\n\tfor(size_t j = 0; i != end; ++i, ++j)\n\t{\n\t\ttheNodes[j] = *i;\n\t}\n#endif\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"NL_Scheduler.h\"\n#include \"NL_SysManager.h\"\n#include \"tbb\/tbb.h\"\n#include \"NL_System.h\"\n#include \"NL_SysTask.h\"\n#include \"NL_StateManager.h\"\n\nnamespace NLE\n{\n\tnamespace Core\n\t{\n\t\tScheduler::Scheduler() :\n\t\t\t_syncSystems(),\n\t\t\t_asyncSystems(),\n\t\t\t_numCores()\n\t\t{\n\t\t}\n\n\t\tScheduler::~Scheduler()\n\t\t{\n\n\t\t}\n\n\t\tbool Scheduler::initialize()\n\t\t{\n\t\t\t_numCores = tbb::task_scheduler_init::default_num_threads();\n\t\t\t_taskSchedulerInit = new tbb::task_scheduler_init(_numCores + 1);\n\t\t\tprintf(\"Running on %i threads.\\n\", _numCores + 1);\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid Scheduler::release()\n\t\t{\n\t\t\tif (_taskSchedulerInit)\n\t\t\t\tdelete _taskSchedulerInit;\n\t\t}\n\n\t\tuint_fast8_t Scheduler::getNumCores()\n\t\t{\n\t\t\treturn _numCores;\n\t\t}\n\n\t\tvoid Scheduler::scheduleExecution(ExecutionDesc execDesc)\n\t\t{\n\t\t\tprintf(\"Scheduling system %i\\n\", execDesc.getSysId());\n\t\t\tif (execDesc.getExecutionType() == ExecutionType::SYNC)\n\t\t\t\t_syncSystems.push(execDesc);\n\t\t\telse \n\t\t\t\t_asyncSystems.push(execDesc);\n\t\t}\n\n\t\tvoid Scheduler::executeSystems(\n\t\t\tstd::unique_ptr<SysManager> const& sysManager,\n\t\t\tstd::unique_ptr<StateManager> const& stateManager)\n\t\t{\n\t\t\tExecutionDesc execDesc;\n\t\t\tstd::function<void()> procedure;\n\n\t\t\tsize_t size = _syncSystems.size();\n\t\t\tif (size > 0 && size == sysManager->getNumSyncSystems())\n\t\t\t{\n\t\t\t\tstateManager->distributeData();\n\t\t\t\twhile (_syncSystems.try_pop(execDesc))\n\t\t\t\t{\n\t\t\t\t\tprocedure = sysManager->getSystemById(execDesc.getSysId()).get()->getExecutionProcedure();\n\t\t\t\t\ttbb::task::enqueue(*new (tbb::task::allocate_root())NLE::Core::SysTask(this, execDesc, procedure));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!_asyncSystems.empty())\n\t\t\t{\n\t\t\t\twhile (_asyncSystems.try_pop(execDesc))\n\t\t\t\t{\n\t\t\t\t\tprocedure = sysManager->getSystemById(execDesc.getSysId()).get()->getExecutionProcedure();\n\t\t\t\t\ttbb::task::enqueue(*new (tbb::task::allocate_root())NLE::Core::SysTask(this, execDesc, procedure));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>Data is distributed after synchronization<commit_after>#include \"NL_Scheduler.h\"\n#include \"NL_SysManager.h\"\n#include \"tbb\/tbb.h\"\n#include \"NL_System.h\"\n#include \"NL_SysTask.h\"\n#include \"NL_StateManager.h\"\n\nnamespace NLE\n{\n\tnamespace Core\n\t{\n\t\tScheduler::Scheduler() :\n\t\t\t_syncSystems(),\n\t\t\t_asyncSystems(),\n\t\t\t_numCores()\n\t\t{\n\t\t}\n\n\t\tScheduler::~Scheduler()\n\t\t{\n\n\t\t}\n\n\t\tbool Scheduler::initialize()\n\t\t{\n\t\t\t_numCores = tbb::task_scheduler_init::default_num_threads();\n\t\t\t_taskSchedulerInit = new tbb::task_scheduler_init(_numCores + 1);\n\t\t\tprintf(\"Running on %i threads.\\n\", _numCores + 1);\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid Scheduler::release()\n\t\t{\n\t\t\tif (_taskSchedulerInit)\n\t\t\t\tdelete _taskSchedulerInit;\n\t\t}\n\n\t\tuint_fast8_t Scheduler::getNumCores()\n\t\t{\n\t\t\treturn _numCores;\n\t\t}\n\n\t\tvoid Scheduler::scheduleExecution(ExecutionDesc execDesc)\n\t\t{\n\t\t\tprintf(\"Scheduling system %i\\n\", execDesc.getSysId());\n\t\t\tif (execDesc.getExecutionType() == ExecutionType::SYNC)\n\t\t\t\t_syncSystems.push(execDesc);\n\t\t\telse \n\t\t\t\t_asyncSystems.push(execDesc);\n\t\t}\n\n\t\tvoid Scheduler::executeSystems(\n\t\t\tstd::unique_ptr<SysManager> const& sysManager,\n\t\t\tstd::unique_ptr<StateManager> const& stateManager)\n\t\t{\n\t\t\tExecutionDesc execDesc;\n\t\t\tstd::function<void()> procedure;\n\n\t\t\tsize_t size = _syncSystems.size();\n\t\t\tif (size > 0 && size == sysManager->getNumSyncSystems())\n\t\t\t{\n\t\t\t\twhile (_syncSystems.try_pop(execDesc))\n\t\t\t\t{\n\t\t\t\t\tprocedure = sysManager->getSystemById(execDesc.getSysId()).get()->getExecutionProcedure();\n\t\t\t\t\ttbb::task::enqueue(*new (tbb::task::allocate_root())NLE::Core::SysTask(this, execDesc, procedure));\n\t\t\t\t}\n\t\t\t\tstateManager->distributeData();\n\t\t\t}\n\n\t\t\tif (!_asyncSystems.empty())\n\t\t\t{\n\t\t\t\twhile (_asyncSystems.try_pop(execDesc))\n\t\t\t\t{\n\t\t\t\t\tprocedure = sysManager->getSystemById(execDesc.getSysId()).get()->getExecutionProcedure();\n\t\t\t\t\ttbb::task::enqueue(*new (tbb::task::allocate_root())NLE::Core::SysTask(this, execDesc, procedure));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"fft2d.pb.h\"\n#include <thrust\/device_vector.h>\n\nnamespace cujak {\nnamespace fft2d {\n\ninline int calc_stride(int Ny) { return (Ny % 2 ? Ny \/ 2 + 1 : Ny \/ 2); }\n\ntemplate <typename Container> class wrapper_base {\nprotected:\n const int Nx, Ny, stride, N;\n Container &u;\n wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_)\n : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {}\n\npublic:\n typedef typename Container::value_type value_type;\n\n pb::Property property;\n\n value_type *get() const { return u.data().get(); }\n Container &data() const { return u; }\n\n value_type operator()(int i, int j) const { return u[stride * i + j]; }\n void set(int i, int j, value_type v) { u[stride * i + j] = v; }\n\n int size_x() const { return Nx; }\n int size_y() const { return Ny; }\n int size() const { return N; }\n int get_stride() const { return stride; }\n};\n\ntemplate <typename Float>\nclass Field_wrapper : public wrapper_base<rdVector<Float> > {\npublic:\n typedef rdVector<Float> Container;\n Field_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {}\n virtual ~Field_wrapper() = default;\n};\n\ntemplate <typename Float>\nclass Coefficient_wrapper : public wrapper_base<cdVector<Float> > {\n\npublic:\n typedef cdVector<Float> Container;\n Coefficient_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny),\n u) {}\n virtual ~Coefficient_wrapper() = default;\n};\n\ntemplate <typename Float> class Field : public Field_wrapper<Float> {\n typename Field_wrapper<Float>::Container data_;\n\npublic:\n Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {}\n};\n\ntemplate <typename Float>\nclass Coefficient : public Coefficient_wrapper<Float> {\n typedef Coefficient_wrapper<Float> Inhereted;\n typedef typename Inhereted::Container Container;\n std::unique_ptr<Container> p;\n\npublic:\n Coefficient(int Nx, int Ny)\n : p(new Container(Nx * calc_stride(Ny))),\n Coefficient_wrapper<Float>(Nx, Ny, *p) {}\n};\n\n} \/\/ namespace fft2d\n} \/\/ namespace Kolmogorov2D\n<commit_msg>Use Container directly<commit_after>#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"fft2d.pb.h\"\n#include <thrust\/device_vector.h>\n\nnamespace cujak {\nnamespace fft2d {\n\ninline int calc_stride(int Ny) { return (Ny % 2 ? Ny \/ 2 + 1 : Ny \/ 2); }\n\ntemplate <typename Container> class wrapper_base {\nprotected:\n const int Nx, Ny, stride, N;\n Container &u;\n wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_)\n : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {}\n\npublic:\n typedef typename Container::value_type value_type;\n\n pb::Property property;\n\n value_type *get() const { return u.data().get(); }\n Container &data() const { return u; }\n\n value_type operator()(int i, int j) const { return u[stride * i + j]; }\n void set(int i, int j, value_type v) { u[stride * i + j] = v; }\n\n int size_x() const { return Nx; }\n int size_y() const { return Ny; }\n int size() const { return N; }\n int get_stride() const { return stride; }\n};\n\ntemplate <typename Float>\nclass Field_wrapper : public wrapper_base<rdVector<Float> > {\npublic:\n typedef rdVector<Float> Container;\n Field_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {}\n virtual ~Field_wrapper() = default;\n};\n\ntemplate <typename Float>\nclass Coefficient_wrapper : public wrapper_base<cdVector<Float> > {\n\npublic:\n typedef cdVector<Float> Container;\n Coefficient_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny),\n u) {}\n virtual ~Coefficient_wrapper() = default;\n};\n\ntemplate <typename Float> class Field : public Field_wrapper<Float> {\n typename Field_wrapper<Float>::Container data_;\n\npublic:\n Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {}\n};\n\ntemplate <typename Float>\nclass Coefficient : public Coefficient_wrapper<Float> {\n typename Coefficient<Float>::Container data_;\n\npublic:\n Coefficient(int Nx, int Ny)\n : data_(Nx * calc_stride(Ny)), Coefficient_wrapper<Float>(Nx, Ny, data_) {\n }\n};\n\n} \/\/ namespace fft2d\n} \/\/ namespace Kolmogorov2D\n<|endoftext|>"} {"text":"<commit_before>#ifndef FILE_UTILS_INCLUDED__\n#define FILE_UTILS_INCLUDED__\n\n#include <fstream>\n#include <string>\n#include <vector>\n\n\ninline std::string file_slurp (const std::string & filename)\n{\n std::string retval;\n\n std::ifstream ifs(filename);\n ifs.seekg(0, std::ifstream::end);\n if (0 < ifs.tellg())\n retval.resize(ifs.tellg());\n ifs.seekg(0);\n\n const std::streamsize read_size = 64 * 1024; \/\/ 64k per read\n char* retval_pos = &retval[0];\n std::streamsize bytes_read = 0;\n do {\n ifs.read(retval_pos, read_size);\n bytes_read = ifs.gcount();\n retval_pos += bytes_read;\n } while (bytes_read == read_size);\n\n return retval;\n}\n\ninline std::vector<std::string> line_break (const std::string & file)\n{\n std::vector<std::string> retval;\n\n std::string::size_type prev_pos = 0;\n while (true) {\n std::string::size_type pos_1 = file.find(\"\\r\\n\", prev_pos);\n std::string::size_type pos_2 = file.find_first_of(\"\\r\\n\", prev_pos);\n std::string::size_type pos = pos_2;\n std::string::size_type match_size = 1;\n if (pos_1 != std::string::npos) {\n pos = pos_1;\n match_size = 2;\n } else if (pos_2 == std::string::npos) {\n\t break;\n }\n retval.push_back(file.substr(prev_pos, pos - prev_pos));\n prev_pos = pos + match_size;\n }\n\n retval.push_back(file.substr(prev_pos));\n\n return retval;\n}\n\n#endif\n<commit_msg>Simplify file_slurp() to eliminate stray null characters in generated code on Windows.<commit_after>#ifndef FILE_UTILS_INCLUDED__\n#define FILE_UTILS_INCLUDED__\n\n#include <fstream>\n#include <string>\n#include <vector>\n\n\ninline std::string file_slurp (const std::string & filename)\n{\n std::string retval;\n std::ifstream ifs(filename);\n std::getline(ifs, retval, '\\0');\n return retval;\n}\n\ninline std::vector<std::string> line_break (const std::string & file)\n{\n std::vector<std::string> retval;\n\n std::string::size_type prev_pos = 0;\n while (true) {\n std::string::size_type pos_1 = file.find(\"\\r\\n\", prev_pos);\n std::string::size_type pos_2 = file.find_first_of(\"\\r\\n\", prev_pos);\n std::string::size_type pos = pos_2;\n std::string::size_type match_size = 1;\n if (pos_1 != std::string::npos) {\n pos = pos_1;\n match_size = 2;\n } else if (pos_2 == std::string::npos) {\n\t break;\n }\n retval.push_back(file.substr(prev_pos, pos - prev_pos));\n prev_pos = pos + match_size;\n }\n\n retval.push_back(file.substr(prev_pos));\n\n return retval;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircchannelmodel.h\"\n#include \"ircmessagefilter.h\"\n#include \"ircsessioninfo.h\"\n#include \"ircchannel_p.h\"\n#include \"ircmessage.h\"\n#include \"ircsession.h\"\n#include <qpointer.h>\n\n\/*!\n \\file ircchannelmodel.h\n \\brief #include <IrcChannelModel>\n *\/\n\n\/*!\n \\class IrcChannelModel ircchannelmodel.h <IrcChannelModel>\n \\ingroup models\n \\brief Keeps track of channels.\n\n IrcChannelModel automatically keeps track of channels\n and manages IrcChannel instances for them.\n\n \\sa models\n *\/\n\n\/*!\n \\fn void IrcChannelModel::channelAdded(IrcChannel* channel)\n\n This signal is emitted when a \\a channel is added to the list of channels.\n *\/\n\n\/*!\n \\fn void IrcChannelModel::channelRemoved(IrcChannel* channel)\n\n This signal is emitted when a \\a channel is removed from the list of channels.\n *\/\n\n\/*!\n \\fn void IrcChannelModel::messageIgnored(IrcMessage* message)\n\n This signal is emitted when a message was ignored.\n\n IrcChannelModel handles only channel specific messages and delivers\n them to the appropriate IrcChannel instances. When applications decide\n to handle IrcChannel::messageReceived(), this signal makes it easy to\n implement handling for the rest, non-channel specific messages.\n\n \\sa IrcSession::messageReceived(), IrcChannel::messageReceived()\n *\/\n\nclass IrcChannelModelPrivate : public IrcMessageFilter\n{\n Q_DECLARE_PUBLIC(IrcChannelModel)\n\npublic:\n IrcChannelModelPrivate(IrcChannelModel* q);\n\n bool messageFilter(IrcMessage* message);\n\n void addChannel(const QString& title);\n void removeChannel(const QString& title);\n bool processMessage(const QString& title, IrcMessage* message);\n\n void _irc_channelDestroyed(IrcChannel* channel);\n\n IrcChannelModel* q_ptr;\n Irc::ItemDataRole role;\n QPointer<IrcSession> session;\n QList<IrcChannel*> channelList;\n QMap<QString, IrcChannel*> channelMap;\n};\n\nIrcChannelModelPrivate::IrcChannelModelPrivate(IrcChannelModel* q) :\n q_ptr(q), role(Irc::TitleRole)\n{\n}\n\nbool IrcChannelModelPrivate::messageFilter(IrcMessage* msg)\n{\n Q_Q(IrcChannelModel);\n if (msg->type() == IrcMessage::Join && msg->flags() & IrcMessage::Own)\n addChannel(static_cast<IrcJoinMessage*>(msg)->channel().toLower());\n\n switch (msg->type()) {\n case IrcMessage::Nick:\n case IrcMessage::Quit:\n foreach (IrcChannel* channel, channelList)\n channel->d_func()->processMessage(msg);\n break;\n\n case IrcMessage::Join:\n case IrcMessage::Part:\n case IrcMessage::Kick:\n case IrcMessage::Names:\n case IrcMessage::Topic:\n if (!processMessage(msg->property(\"channel\").toString().toLower(), msg))\n emit q->messageIgnored(msg);\n break;\n\n case IrcMessage::Mode:\n case IrcMessage::Notice:\n case IrcMessage::Private:\n if (!processMessage(msg->property(\"target\").toString().toLower(), msg))\n emit q->messageIgnored(msg);\n break;\n\n default:\n emit q->messageIgnored(msg);\n break;\n }\n\n if (msg->type() == IrcMessage::Part && msg->flags() & IrcMessage::Own) {\n removeChannel(static_cast<IrcPartMessage*>(msg)->channel().toLower());\n } else if (msg->type() == IrcMessage::Quit && msg->flags() & IrcMessage::Own) {\n foreach (const QString& channel, channelMap.keys())\n removeChannel(channel);\n } else if (msg->type() == IrcMessage::Kick) {\n const IrcKickMessage* kickMsg = static_cast<IrcKickMessage*>(msg);\n if (!kickMsg->user().compare(msg->session()->nickName(), Qt::CaseInsensitive))\n removeChannel(kickMsg->channel().toLower());\n }\n\n return false;\n}\n\nstatic QString channelPrefix(const QString& channel, const QStringList& prefixes)\n{\n int i = 0;\n while (i < channel.length() && prefixes.contains(channel.at(i)))\n ++i;\n return channel.left(i);\n}\n\nstatic QString unprefixedChannel(const QString& channel, const QStringList& prefixes)\n{\n int i = 0;\n while (i < channel.length() && prefixes.contains(channel.at(i)))\n ++i;\n return channel.mid(i);\n}\n\nvoid IrcChannelModelPrivate::addChannel(const QString& title)\n{\n Q_Q(IrcChannelModel);\n if (!channelMap.contains(title)) {\n IrcChannel* channel = q->createChannel(title);\n if (channel) {\n const QStringList prefixes = IrcSessionInfo(session).channelTypes();\n channel->d_func()->init(channelPrefix(title, prefixes), unprefixedChannel(title, prefixes));\n\n q->beginInsertRows(QModelIndex(), 0, 0);\n channelList.append(channel);\n channelMap.insert(title, channel);\n q->connect(channel, SIGNAL(destroyed(IrcChannel*)), SLOT(_irc_channelDestroyed(IrcChannel*)));\n q->endInsertRows();\n emit q->channelAdded(channel);\n emit q->channelsChanged(channelList);\n emit q->countChanged(channelList.count());\n }\n }\n}\n\nvoid IrcChannelModelPrivate::removeChannel(const QString& title)\n{\n Q_Q(IrcChannelModel);\n IrcChannel* channel = channelMap.value(title);\n if (channel)\n q->destroyChannel(channel);\n}\n\nbool IrcChannelModelPrivate::processMessage(const QString& title, IrcMessage* message)\n{\n IrcChannel* channel = channelMap.value(title);\n if (channel)\n return channel->d_func()->processMessage(message);\n return false;\n}\n\nvoid IrcChannelModelPrivate::_irc_channelDestroyed(IrcChannel* channel)\n{\n Q_Q(IrcChannelModel);\n int idx = channelList.indexOf(channel);\n if (idx != -1) {\n q->beginRemoveRows(QModelIndex(), idx, idx);\n channelList.removeAt(idx);\n channelMap.remove(channel->title());\n q->endRemoveRows();\n emit q->channelRemoved(channel);\n emit q->channelsChanged(channelList);\n emit q->countChanged(channelList.count());\n }\n}\n\nQ_DECLARE_METATYPE(IrcChannel*)\nQ_DECLARE_METATYPE(QList<IrcChannel*>)\n\n\/*!\n Constructs a new model with \\a parent.\n\n \\note If \\a parent is an instance of IrcSession, it will be\n automatically assigned to \\ref IrcChannelModel::session \"session\".\n *\/\nIrcChannelModel::IrcChannelModel(QObject* parent)\n : QAbstractListModel(parent), d_ptr(new IrcChannelModelPrivate(this))\n{\n setSession(qobject_cast<IrcSession*>(parent));\n\n qRegisterMetaType<IrcChannel*>();\n qRegisterMetaType<QList<IrcChannel*> >();\n}\n\n\/*!\n Destructs the model.\n *\/\nIrcChannelModel::~IrcChannelModel()\n{\n Q_D(IrcChannelModel);\n foreach (IrcChannel* channel, d->channelList) {\n channel->blockSignals(true);\n delete channel;\n }\n d->channelList.clear();\n d->channelMap.clear();\n}\n\n\/*!\n This property holds the session.\n\n \\par Access functions:\n \\li \\ref IrcSession* <b>session<\/b>() const\n \\li void <b>setSession<\/b>(\\ref IrcSession* session)\n\n \\warning Changing the session on the fly is not supported.\n *\/\nIrcSession* IrcChannelModel::session() const\n{\n Q_D(const IrcChannelModel);\n return d->session;\n}\n\nvoid IrcChannelModel::setSession(IrcSession* session)\n{\n Q_D(IrcChannelModel);\n if (d->session != session) {\n if (d->session)\n qFatal(\"IrcChannelModel::setSession(): changing the session on the fly is not supported.\");\n d->session = session;\n d->session->installMessageFilter(d);\n emit sessionChanged(session);\n }\n}\n\n\/*!\n This property holds the number of channels.\n\n \\par Access function:\n \\li int <b>count<\/b>() const\n\n \\par Notifier signal:\n \\li void <b>countChanged<\/b>(int count)\n *\/\nint IrcChannelModel::count() const\n{\n return rowCount();\n}\n\n\/*!\n This property holds the list of channels.\n\n \\par Access function:\n \\li QList<\\ref IrcChannel*> <b>channels<\/b>() const\n\n \\par Notifier signal:\n \\li void <b>channelsChanged<\/b>(const QList<\\ref IrcChannel*>& channels)\n *\/\nQList<IrcChannel*> IrcChannelModel::channels() const\n{\n Q_D(const IrcChannelModel);\n return d->channelList;\n}\n\n\/*!\n Returns the channel object at \\a index.\n *\/\nIrcChannel* IrcChannelModel::get(int index) const\n{\n Q_D(const IrcChannelModel);\n return d->channelList.value(index);\n}\n\n\/*!\n Returns the channel object for \\a title.\n *\/\nIrcChannel* IrcChannelModel::channel(const QString& title) const\n{\n Q_D(const IrcChannelModel);\n return d->channelMap.value(title);\n}\n\n\/*!\n Returns \\c true if the model contains \\a title.\n *\/\nbool IrcChannelModel::contains(const QString& title) const\n{\n Q_D(const IrcChannelModel);\n return d->channelMap.contains(title);\n}\n\n\/*!\n This property holds the display role.\n\n The specified data role is returned for Qt::DisplayRole.\n\n The default value is \\ref Irc::TitleRole.\n\n \\par Access functions:\n \\li \\ref Irc::ItemDataRole <b>displayRole<\/b>() const\n \\li void <b>setDisplayRole<\/b>(\\ref Irc::ItemDataRole role)\n *\/\nIrc::ItemDataRole IrcChannelModel::displayRole() const\n{\n Q_D(const IrcChannelModel);\n return d->role;\n}\n\nvoid IrcChannelModel::setDisplayRole(Irc::ItemDataRole role)\n{\n Q_D(IrcChannelModel);\n d->role = role;\n}\n\n\/*!\n Clears the model.\n *\/\nvoid IrcChannelModel::clear()\n{\n Q_D(IrcChannelModel);\n if (!d->channelList.isEmpty()) {\n beginResetModel();\n qDeleteAll(d->channelList);\n d->channelList.clear();\n d->channelMap.clear();\n endResetModel();\n }\n}\n\n\/*!\n Creates a channel object for channel \\a title.\n\n IrcChannelModel will automatically call this factory method when a\n need for the channel object occurs ie. the channel is being joined.\n\n The default implementation creates a new instance of IrcChannel.\n Reimplement this function in order to alter the default behavior,\n for example to provide a custom IrcChannel subclass.\n *\/\nIrcChannel* IrcChannelModel::createChannel(const QString& title)\n{\n Q_UNUSED(title);\n return new IrcChannel(this);\n}\n\n\/*!\n Destroys the channel \\a model.\n\n IrcChannelModel will automatically call this method when the channel\n object is no longer needed ie. the user quit, the channel was parted,\n or the user was kicked from the channel.\n\n The default implementation deletes the channel object.\n Reimplement this function in order to alter the default behavior,\n for example to keep the channel object alive.\n *\/\nvoid IrcChannelModel::destroyChannel(IrcChannel* channel)\n{\n delete channel;\n}\n\n\/*!\n The following role names are provided by default:\n\n Role | Name | Type | Example\n -----------------|-----------|-------------|--------\n Qt::DisplayRole | \"display\" | 1) | -\n Irc::ChannelRole | \"channel\" | IrcChannel* | <object>\n Irc::NameRole | \"name\" | QString | \"communi\"\n Irc::PrefixRole | \"prefix\" | QString | \"#\"\n Irc::TitleRole | \"title\" | QString | \"#communi\"\n\n 1) The type depends on \\ref displayRole.\n *\/\nQHash<int, QByteArray> IrcChannelModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[Qt::DisplayRole] = \"display\";\n roles[Irc::ChannelRole] = \"channel\";\n roles[Irc::NameRole] = \"name\";\n roles[Irc::PrefixRole] = \"prefix\";\n roles[Irc::TitleRole] = \"title\";\n return roles;\n}\n\n\/*!\n Returns the number of channels.\n *\/\nint IrcChannelModel::rowCount(const QModelIndex& parent) const\n{\n if (parent.isValid())\n return 0;\n\n Q_D(const IrcChannelModel);\n return d->channelList.count();\n}\n\n\/*!\n Returns the data for specified \\a role and user referred to by by the \\a index.\n *\/\nQVariant IrcChannelModel::data(const QModelIndex& index, int role) const\n{\n Q_D(const IrcChannelModel);\n if (!hasIndex(index.row(), index.column()))\n return QVariant();\n\n switch (role) {\n case Qt::DisplayRole:\n return data(index, d->role);\n case Irc::ChannelRole:\n return QVariant::fromValue(d->channelList.at(index.row()));\n case Irc::NameRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->name();\n break;\n case Irc::PrefixRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->prefix();\n break;\n case Irc::TitleRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->title();\n break;\n }\n\n return QVariant();\n}\n\n#include \"moc_ircchannelmodel.cpp\"\n<commit_msg>Fix IrcChannelModelPrivate::addChannel()<commit_after>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This library is free software; you can redistribute it and\/or modify it\n* under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or (at your\n* option) any later version.\n*\n* This library is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n* License for more details.\n*\/\n\n#include \"ircchannelmodel.h\"\n#include \"ircmessagefilter.h\"\n#include \"ircsessioninfo.h\"\n#include \"ircchannel_p.h\"\n#include \"ircmessage.h\"\n#include \"ircsession.h\"\n#include <qpointer.h>\n\n\/*!\n \\file ircchannelmodel.h\n \\brief #include <IrcChannelModel>\n *\/\n\n\/*!\n \\class IrcChannelModel ircchannelmodel.h <IrcChannelModel>\n \\ingroup models\n \\brief Keeps track of channels.\n\n IrcChannelModel automatically keeps track of channels\n and manages IrcChannel instances for them.\n\n \\sa models\n *\/\n\n\/*!\n \\fn void IrcChannelModel::channelAdded(IrcChannel* channel)\n\n This signal is emitted when a \\a channel is added to the list of channels.\n *\/\n\n\/*!\n \\fn void IrcChannelModel::channelRemoved(IrcChannel* channel)\n\n This signal is emitted when a \\a channel is removed from the list of channels.\n *\/\n\n\/*!\n \\fn void IrcChannelModel::messageIgnored(IrcMessage* message)\n\n This signal is emitted when a message was ignored.\n\n IrcChannelModel handles only channel specific messages and delivers\n them to the appropriate IrcChannel instances. When applications decide\n to handle IrcChannel::messageReceived(), this signal makes it easy to\n implement handling for the rest, non-channel specific messages.\n\n \\sa IrcSession::messageReceived(), IrcChannel::messageReceived()\n *\/\n\nclass IrcChannelModelPrivate : public IrcMessageFilter\n{\n Q_DECLARE_PUBLIC(IrcChannelModel)\n\npublic:\n IrcChannelModelPrivate(IrcChannelModel* q);\n\n bool messageFilter(IrcMessage* message);\n\n void addChannel(const QString& title);\n void removeChannel(const QString& title);\n bool processMessage(const QString& title, IrcMessage* message);\n\n void _irc_channelDestroyed(IrcChannel* channel);\n\n IrcChannelModel* q_ptr;\n Irc::ItemDataRole role;\n QPointer<IrcSession> session;\n QList<IrcChannel*> channelList;\n QMap<QString, IrcChannel*> channelMap;\n};\n\nIrcChannelModelPrivate::IrcChannelModelPrivate(IrcChannelModel* q) :\n q_ptr(q), role(Irc::TitleRole)\n{\n}\n\nbool IrcChannelModelPrivate::messageFilter(IrcMessage* msg)\n{\n Q_Q(IrcChannelModel);\n if (msg->type() == IrcMessage::Join && msg->flags() & IrcMessage::Own)\n addChannel(static_cast<IrcJoinMessage*>(msg)->channel().toLower());\n\n switch (msg->type()) {\n case IrcMessage::Nick:\n case IrcMessage::Quit:\n foreach (IrcChannel* channel, channelList)\n channel->d_func()->processMessage(msg);\n break;\n\n case IrcMessage::Join:\n case IrcMessage::Part:\n case IrcMessage::Kick:\n case IrcMessage::Names:\n case IrcMessage::Topic:\n if (!processMessage(msg->property(\"channel\").toString().toLower(), msg))\n emit q->messageIgnored(msg);\n break;\n\n case IrcMessage::Mode:\n case IrcMessage::Notice:\n case IrcMessage::Private:\n if (!processMessage(msg->property(\"target\").toString().toLower(), msg))\n emit q->messageIgnored(msg);\n break;\n\n default:\n emit q->messageIgnored(msg);\n break;\n }\n\n if (msg->type() == IrcMessage::Part && msg->flags() & IrcMessage::Own) {\n removeChannel(static_cast<IrcPartMessage*>(msg)->channel().toLower());\n } else if (msg->type() == IrcMessage::Quit && msg->flags() & IrcMessage::Own) {\n foreach (const QString& channel, channelMap.keys())\n removeChannel(channel);\n } else if (msg->type() == IrcMessage::Kick) {\n const IrcKickMessage* kickMsg = static_cast<IrcKickMessage*>(msg);\n if (!kickMsg->user().compare(msg->session()->nickName(), Qt::CaseInsensitive))\n removeChannel(kickMsg->channel().toLower());\n }\n\n return false;\n}\n\nstatic QString channelPrefix(const QString& channel, const QStringList& prefixes)\n{\n int i = 0;\n while (i < channel.length() && prefixes.contains(channel.at(i)))\n ++i;\n return channel.left(i);\n}\n\nstatic QString unprefixedChannel(const QString& channel, const QStringList& prefixes)\n{\n int i = 0;\n while (i < channel.length() && prefixes.contains(channel.at(i)))\n ++i;\n return channel.mid(i);\n}\n\nvoid IrcChannelModelPrivate::addChannel(const QString& title)\n{\n Q_Q(IrcChannelModel);\n if (!channelMap.contains(title)) {\n IrcChannel* channel = q->createChannel(title);\n if (channel) {\n const QStringList prefixes = IrcSessionInfo(session).channelTypes();\n channel->d_func()->init(channelPrefix(title, prefixes), unprefixedChannel(title, prefixes));\n\n q->beginInsertRows(QModelIndex(), channelList.count(), channelList.count());\n channelList.append(channel);\n channelMap.insert(title, channel);\n q->connect(channel, SIGNAL(destroyed(IrcChannel*)), SLOT(_irc_channelDestroyed(IrcChannel*)));\n q->endInsertRows();\n emit q->channelAdded(channel);\n emit q->channelsChanged(channelList);\n emit q->countChanged(channelList.count());\n }\n }\n}\n\nvoid IrcChannelModelPrivate::removeChannel(const QString& title)\n{\n Q_Q(IrcChannelModel);\n IrcChannel* channel = channelMap.value(title);\n if (channel)\n q->destroyChannel(channel);\n}\n\nbool IrcChannelModelPrivate::processMessage(const QString& title, IrcMessage* message)\n{\n IrcChannel* channel = channelMap.value(title);\n if (channel)\n return channel->d_func()->processMessage(message);\n return false;\n}\n\nvoid IrcChannelModelPrivate::_irc_channelDestroyed(IrcChannel* channel)\n{\n Q_Q(IrcChannelModel);\n int idx = channelList.indexOf(channel);\n if (idx != -1) {\n q->beginRemoveRows(QModelIndex(), idx, idx);\n channelList.removeAt(idx);\n channelMap.remove(channel->title());\n q->endRemoveRows();\n emit q->channelRemoved(channel);\n emit q->channelsChanged(channelList);\n emit q->countChanged(channelList.count());\n }\n}\n\nQ_DECLARE_METATYPE(IrcChannel*)\nQ_DECLARE_METATYPE(QList<IrcChannel*>)\n\n\/*!\n Constructs a new model with \\a parent.\n\n \\note If \\a parent is an instance of IrcSession, it will be\n automatically assigned to \\ref IrcChannelModel::session \"session\".\n *\/\nIrcChannelModel::IrcChannelModel(QObject* parent)\n : QAbstractListModel(parent), d_ptr(new IrcChannelModelPrivate(this))\n{\n setSession(qobject_cast<IrcSession*>(parent));\n\n qRegisterMetaType<IrcChannel*>();\n qRegisterMetaType<QList<IrcChannel*> >();\n}\n\n\/*!\n Destructs the model.\n *\/\nIrcChannelModel::~IrcChannelModel()\n{\n Q_D(IrcChannelModel);\n foreach (IrcChannel* channel, d->channelList) {\n channel->blockSignals(true);\n delete channel;\n }\n d->channelList.clear();\n d->channelMap.clear();\n}\n\n\/*!\n This property holds the session.\n\n \\par Access functions:\n \\li \\ref IrcSession* <b>session<\/b>() const\n \\li void <b>setSession<\/b>(\\ref IrcSession* session)\n\n \\warning Changing the session on the fly is not supported.\n *\/\nIrcSession* IrcChannelModel::session() const\n{\n Q_D(const IrcChannelModel);\n return d->session;\n}\n\nvoid IrcChannelModel::setSession(IrcSession* session)\n{\n Q_D(IrcChannelModel);\n if (d->session != session) {\n if (d->session)\n qFatal(\"IrcChannelModel::setSession(): changing the session on the fly is not supported.\");\n d->session = session;\n d->session->installMessageFilter(d);\n emit sessionChanged(session);\n }\n}\n\n\/*!\n This property holds the number of channels.\n\n \\par Access function:\n \\li int <b>count<\/b>() const\n\n \\par Notifier signal:\n \\li void <b>countChanged<\/b>(int count)\n *\/\nint IrcChannelModel::count() const\n{\n return rowCount();\n}\n\n\/*!\n This property holds the list of channels.\n\n \\par Access function:\n \\li QList<\\ref IrcChannel*> <b>channels<\/b>() const\n\n \\par Notifier signal:\n \\li void <b>channelsChanged<\/b>(const QList<\\ref IrcChannel*>& channels)\n *\/\nQList<IrcChannel*> IrcChannelModel::channels() const\n{\n Q_D(const IrcChannelModel);\n return d->channelList;\n}\n\n\/*!\n Returns the channel object at \\a index.\n *\/\nIrcChannel* IrcChannelModel::get(int index) const\n{\n Q_D(const IrcChannelModel);\n return d->channelList.value(index);\n}\n\n\/*!\n Returns the channel object for \\a title.\n *\/\nIrcChannel* IrcChannelModel::channel(const QString& title) const\n{\n Q_D(const IrcChannelModel);\n return d->channelMap.value(title);\n}\n\n\/*!\n Returns \\c true if the model contains \\a title.\n *\/\nbool IrcChannelModel::contains(const QString& title) const\n{\n Q_D(const IrcChannelModel);\n return d->channelMap.contains(title);\n}\n\n\/*!\n This property holds the display role.\n\n The specified data role is returned for Qt::DisplayRole.\n\n The default value is \\ref Irc::TitleRole.\n\n \\par Access functions:\n \\li \\ref Irc::ItemDataRole <b>displayRole<\/b>() const\n \\li void <b>setDisplayRole<\/b>(\\ref Irc::ItemDataRole role)\n *\/\nIrc::ItemDataRole IrcChannelModel::displayRole() const\n{\n Q_D(const IrcChannelModel);\n return d->role;\n}\n\nvoid IrcChannelModel::setDisplayRole(Irc::ItemDataRole role)\n{\n Q_D(IrcChannelModel);\n d->role = role;\n}\n\n\/*!\n Clears the model.\n *\/\nvoid IrcChannelModel::clear()\n{\n Q_D(IrcChannelModel);\n if (!d->channelList.isEmpty()) {\n beginResetModel();\n qDeleteAll(d->channelList);\n d->channelList.clear();\n d->channelMap.clear();\n endResetModel();\n }\n}\n\n\/*!\n Creates a channel object for channel \\a title.\n\n IrcChannelModel will automatically call this factory method when a\n need for the channel object occurs ie. the channel is being joined.\n\n The default implementation creates a new instance of IrcChannel.\n Reimplement this function in order to alter the default behavior,\n for example to provide a custom IrcChannel subclass.\n *\/\nIrcChannel* IrcChannelModel::createChannel(const QString& title)\n{\n Q_UNUSED(title);\n return new IrcChannel(this);\n}\n\n\/*!\n Destroys the channel \\a model.\n\n IrcChannelModel will automatically call this method when the channel\n object is no longer needed ie. the user quit, the channel was parted,\n or the user was kicked from the channel.\n\n The default implementation deletes the channel object.\n Reimplement this function in order to alter the default behavior,\n for example to keep the channel object alive.\n *\/\nvoid IrcChannelModel::destroyChannel(IrcChannel* channel)\n{\n delete channel;\n}\n\n\/*!\n The following role names are provided by default:\n\n Role | Name | Type | Example\n -----------------|-----------|-------------|--------\n Qt::DisplayRole | \"display\" | 1) | -\n Irc::ChannelRole | \"channel\" | IrcChannel* | <object>\n Irc::NameRole | \"name\" | QString | \"communi\"\n Irc::PrefixRole | \"prefix\" | QString | \"#\"\n Irc::TitleRole | \"title\" | QString | \"#communi\"\n\n 1) The type depends on \\ref displayRole.\n *\/\nQHash<int, QByteArray> IrcChannelModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[Qt::DisplayRole] = \"display\";\n roles[Irc::ChannelRole] = \"channel\";\n roles[Irc::NameRole] = \"name\";\n roles[Irc::PrefixRole] = \"prefix\";\n roles[Irc::TitleRole] = \"title\";\n return roles;\n}\n\n\/*!\n Returns the number of channels.\n *\/\nint IrcChannelModel::rowCount(const QModelIndex& parent) const\n{\n if (parent.isValid())\n return 0;\n\n Q_D(const IrcChannelModel);\n return d->channelList.count();\n}\n\n\/*!\n Returns the data for specified \\a role and user referred to by by the \\a index.\n *\/\nQVariant IrcChannelModel::data(const QModelIndex& index, int role) const\n{\n Q_D(const IrcChannelModel);\n if (!hasIndex(index.row(), index.column()))\n return QVariant();\n\n switch (role) {\n case Qt::DisplayRole:\n return data(index, d->role);\n case Irc::ChannelRole:\n return QVariant::fromValue(d->channelList.at(index.row()));\n case Irc::NameRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->name();\n break;\n case Irc::PrefixRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->prefix();\n break;\n case Irc::TitleRole:\n if (IrcChannel* channel = d->channelList.at(index.row()))\n return channel->title();\n break;\n }\n\n return QVariant();\n}\n\n#include \"moc_ircchannelmodel.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ResourceAllocator.h\"\n\n#include \"private\/backend\/DriverApi.h\"\n\n#include \"details\/Texture.h\"\n\n#include <utils\/Log.h>\n\nusing namespace utils;\n\nnamespace filament {\n\nusing namespace backend;\nusing namespace details;\n\nnamespace fg {\n\n\/\/ ------------------------------------------------------------------------------------------------\n\ntemplate<typename K, typename V, typename H>\nUTILS_NOINLINE\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::iterator\nResourceAllocator::AssociativeContainer<K, V, H>::erase(iterator it) {\n return mContainer.erase(it);\n}\n\ntemplate<typename K, typename V, typename H>\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::const_iterator\nResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) const {\n return const_cast<AssociativeContainer*>(this)->find(key);\n}\n\ntemplate<typename K, typename V, typename H>\nUTILS_NOINLINE\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::iterator\nResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) {\n return std::find_if(mContainer.begin(), mContainer.end(), [&key](auto const& v) {\n return v.first == key;\n });\n}\n\ntemplate<typename K, typename V, typename H>\ntemplate<typename... ARGS>\nUTILS_NOINLINE\nvoid ResourceAllocator::AssociativeContainer<K, V, H>::emplace(ARGS&& ... args) {\n mContainer.emplace_back(std::forward<ARGS>(args)...);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\n\nsize_t ResourceAllocator::TextureKey::getSize() const noexcept {\n size_t pixelCount = width * height * depth;\n size_t size = pixelCount * FTexture::getFormatSize(format);\n if (levels > 1) {\n \/\/ if we have mip-maps we assume the full pyramid\n size += size \/ 3;\n }\n size_t s = std::max(uint8_t(1), samples);\n if (s > 1) {\n \/\/ if we have MSAA, we assume 8 bit extra per pixel\n size += pixelCount;\n }\n return size;\n}\n\nResourceAllocator::ResourceAllocator(DriverApi& driverApi) noexcept\n : mBackend(driverApi) {\n}\n\nResourceAllocator::~ResourceAllocator() noexcept {\n assert(!mTextureCache.size());\n assert(!mInUseTextures.size());\n}\n\nvoid ResourceAllocator::terminate() noexcept {\n assert(!mInUseTextures.size());\n auto& textureCache = mTextureCache;\n for (auto it = textureCache.begin(); it != textureCache.end();) {\n mBackend.destroyTexture(it->second.handle);\n it = textureCache.erase(it);\n }\n}\n\nRenderTargetHandle ResourceAllocator::createRenderTarget(const char* name,\n TargetBufferFlags targetBufferFlags, uint32_t width, uint32_t height,\n uint8_t samples, TargetBufferInfo color, TargetBufferInfo depth,\n TargetBufferInfo stencil) noexcept {\n return mBackend.createRenderTarget(targetBufferFlags,\n width, height, samples ? samples : 1u, color, depth, stencil);\n}\n\nvoid ResourceAllocator::destroyRenderTarget(RenderTargetHandle h) noexcept {\n return mBackend.destroyRenderTarget(h);\n}\n\nbackend::TextureHandle ResourceAllocator::createTexture(const char* name,\n backend::SamplerType target, uint8_t levels,\n backend::TextureFormat format, uint8_t samples, uint32_t width, uint32_t height,\n uint32_t depth, backend::TextureUsage usage) noexcept {\n\n \/\/ Some WebGL implementations complain about an incomplete framebuffer when the attachment sizes\n \/\/ are heterogeneous. This merits further investigation.\n#if defined(__EMSCRIPTEN__)\n if (!(usage & TextureUsage::SAMPLEABLE)) {\n \/\/ If this texture is not going to be sampled, we can round its size up\n \/\/ this helps prevent many reallocations for small size changes.\n \/\/ We round to 16 pixels, which works for 720p btw.\n width = (width + 15u) & ~15u;\n height = (height + 15u) & ~15u;\n }\n#endif\n\n \/\/ do we have a suitable texture in the cache?\n TextureHandle handle;\n if (mEnabled) {\n auto& textureCache = mTextureCache;\n const TextureKey key{ name, target, levels, format, samples, width, height, depth, usage };\n auto it = textureCache.find(key);\n if (UTILS_LIKELY(it != textureCache.end())) {\n \/\/ we do, move the entry to the in-use list, and remove from the cache\n handle = it->second.handle;\n mCacheSize -= it->second.size;\n textureCache.erase(it);\n } else {\n \/\/ we don't, allocate a new texture and populate the in-use list\n handle = mBackend.createTexture(\n target, levels, format, samples, width, height, depth, usage);\n }\n mInUseTextures.emplace(handle, key);\n } else {\n handle = mBackend.createTexture(\n target, levels, format, samples, width, height, depth, usage);\n }\n return handle;\n}\n\nvoid ResourceAllocator::destroyTexture(TextureHandle h) noexcept {\n if (mEnabled) {\n \/\/ find the texture in the in-use list (it must be there!)\n auto it = mInUseTextures.find(h);\n assert(it != mInUseTextures.end());\n\n \/\/ move it to the cache\n const TextureKey key = it->second;\n uint32_t size = key.getSize();\n\n mTextureCache.emplace(key, TextureCachePayload{ h, mAge, size });\n mCacheSize += size;\n\n \/\/ remove it from the in-use list\n mInUseTextures.erase(it);\n } else {\n mBackend.destroyTexture(h);\n }\n}\n\nvoid ResourceAllocator::gc() noexcept {\n \/\/ this is called regularly -- usually once per frame of each Renderer\n\n \/\/ increase our age\n const size_t age = mAge++;\n\n \/\/ Purging strategy:\n \/\/ + remove entries that are older than a certain age\n \/\/ - remove only one entry per gc(), unless we're at capacity\n\n auto& textureCache = mTextureCache;\n for (auto it = textureCache.begin(); it != textureCache.end();) {\n const size_t ageDiff = age - it->second.age;\n if (ageDiff >= CACHE_MAX_AGE) {\n mBackend.destroyTexture(it->second.handle);\n mCacheSize -= it->second.size;\n \/\/slog.d << \"purging \" << it->second.handle.getId() << io::endl;\n it = textureCache.erase(it);\n if (mCacheSize < CACHE_CAPACITY) {\n \/\/ if we're not at capacity, only purge a single entry per gc, trying to\n \/\/ avoid a burst of work.\n break;\n }\n } else {\n ++it;\n }\n }\n\n \/\/if (mAge % 60 == 0) dump();\n \/\/ TODO: maybe purge LRU entries if we have more than a certain number\n \/\/ TODO: maybe purge LRU entries if the size of the cache is too large\n}\n\nUTILS_NOINLINE\nvoid ResourceAllocator::dump() const noexcept {\n slog.d << \"# entries=\" << mTextureCache.size() << \", sz=\" << mCacheSize \/ float(1u << 20u)\n << \" MiB\" << io::endl;\n for (auto const & it : mTextureCache) {\n auto w = it.first.width;\n auto h = it.first.height;\n auto f = FTexture::getFormatSize(it.first.format);\n slog.d << it.first.name << \": w=\" << w << \", h=\" << h << \", f=\" << f << \", sz=\"\n << it.second.size \/ float(1u << 20u) << io::endl;\n }\n}\n\n} \/\/ namespace fg\n} \/\/ namespace filament\n<commit_msg>Repair web samples by fixing typo in previous fix.<commit_after>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ResourceAllocator.h\"\n\n#include \"private\/backend\/DriverApi.h\"\n\n#include \"details\/Texture.h\"\n\n#include <utils\/Log.h>\n\nusing namespace utils;\n\nnamespace filament {\n\nusing namespace backend;\nusing namespace details;\n\nnamespace fg {\n\n\/\/ ------------------------------------------------------------------------------------------------\n\ntemplate<typename K, typename V, typename H>\nUTILS_NOINLINE\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::iterator\nResourceAllocator::AssociativeContainer<K, V, H>::erase(iterator it) {\n return mContainer.erase(it);\n}\n\ntemplate<typename K, typename V, typename H>\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::const_iterator\nResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) const {\n return const_cast<AssociativeContainer*>(this)->find(key);\n}\n\ntemplate<typename K, typename V, typename H>\nUTILS_NOINLINE\ntypename ResourceAllocator::AssociativeContainer<K, V, H>::iterator\nResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) {\n return std::find_if(mContainer.begin(), mContainer.end(), [&key](auto const& v) {\n return v.first == key;\n });\n}\n\ntemplate<typename K, typename V, typename H>\ntemplate<typename... ARGS>\nUTILS_NOINLINE\nvoid ResourceAllocator::AssociativeContainer<K, V, H>::emplace(ARGS&& ... args) {\n mContainer.emplace_back(std::forward<ARGS>(args)...);\n}\n\n\/\/ ------------------------------------------------------------------------------------------------\n\nsize_t ResourceAllocator::TextureKey::getSize() const noexcept {\n size_t pixelCount = width * height * depth;\n size_t size = pixelCount * FTexture::getFormatSize(format);\n if (levels > 1) {\n \/\/ if we have mip-maps we assume the full pyramid\n size += size \/ 3;\n }\n size_t s = std::max(uint8_t(1), samples);\n if (s > 1) {\n \/\/ if we have MSAA, we assume 8 bit extra per pixel\n size += pixelCount;\n }\n return size;\n}\n\nResourceAllocator::ResourceAllocator(DriverApi& driverApi) noexcept\n : mBackend(driverApi) {\n}\n\nResourceAllocator::~ResourceAllocator() noexcept {\n assert(!mTextureCache.size());\n assert(!mInUseTextures.size());\n}\n\nvoid ResourceAllocator::terminate() noexcept {\n assert(!mInUseTextures.size());\n auto& textureCache = mTextureCache;\n for (auto it = textureCache.begin(); it != textureCache.end();) {\n mBackend.destroyTexture(it->second.handle);\n it = textureCache.erase(it);\n }\n}\n\nRenderTargetHandle ResourceAllocator::createRenderTarget(const char* name,\n TargetBufferFlags targetBufferFlags, uint32_t width, uint32_t height,\n uint8_t samples, TargetBufferInfo color, TargetBufferInfo depth,\n TargetBufferInfo stencil) noexcept {\n return mBackend.createRenderTarget(targetBufferFlags,\n width, height, samples ? samples : 1u, color, depth, stencil);\n}\n\nvoid ResourceAllocator::destroyRenderTarget(RenderTargetHandle h) noexcept {\n return mBackend.destroyRenderTarget(h);\n}\n\nbackend::TextureHandle ResourceAllocator::createTexture(const char* name,\n backend::SamplerType target, uint8_t levels,\n backend::TextureFormat format, uint8_t samples, uint32_t width, uint32_t height,\n uint32_t depth, backend::TextureUsage usage) noexcept {\n\n \/\/ Some WebGL implementations complain about an incomplete framebuffer when the attachment sizes\n \/\/ are heterogeneous. This merits further investigation.\n#if !defined(__EMSCRIPTEN__)\n if (!(usage & TextureUsage::SAMPLEABLE)) {\n \/\/ If this texture is not going to be sampled, we can round its size up\n \/\/ this helps prevent many reallocations for small size changes.\n \/\/ We round to 16 pixels, which works for 720p btw.\n width = (width + 15u) & ~15u;\n height = (height + 15u) & ~15u;\n }\n#endif\n\n \/\/ do we have a suitable texture in the cache?\n TextureHandle handle;\n if (mEnabled) {\n auto& textureCache = mTextureCache;\n const TextureKey key{ name, target, levels, format, samples, width, height, depth, usage };\n auto it = textureCache.find(key);\n if (UTILS_LIKELY(it != textureCache.end())) {\n \/\/ we do, move the entry to the in-use list, and remove from the cache\n handle = it->second.handle;\n mCacheSize -= it->second.size;\n textureCache.erase(it);\n } else {\n \/\/ we don't, allocate a new texture and populate the in-use list\n handle = mBackend.createTexture(\n target, levels, format, samples, width, height, depth, usage);\n }\n mInUseTextures.emplace(handle, key);\n } else {\n handle = mBackend.createTexture(\n target, levels, format, samples, width, height, depth, usage);\n }\n return handle;\n}\n\nvoid ResourceAllocator::destroyTexture(TextureHandle h) noexcept {\n if (mEnabled) {\n \/\/ find the texture in the in-use list (it must be there!)\n auto it = mInUseTextures.find(h);\n assert(it != mInUseTextures.end());\n\n \/\/ move it to the cache\n const TextureKey key = it->second;\n uint32_t size = key.getSize();\n\n mTextureCache.emplace(key, TextureCachePayload{ h, mAge, size });\n mCacheSize += size;\n\n \/\/ remove it from the in-use list\n mInUseTextures.erase(it);\n } else {\n mBackend.destroyTexture(h);\n }\n}\n\nvoid ResourceAllocator::gc() noexcept {\n \/\/ this is called regularly -- usually once per frame of each Renderer\n\n \/\/ increase our age\n const size_t age = mAge++;\n\n \/\/ Purging strategy:\n \/\/ + remove entries that are older than a certain age\n \/\/ - remove only one entry per gc(), unless we're at capacity\n\n auto& textureCache = mTextureCache;\n for (auto it = textureCache.begin(); it != textureCache.end();) {\n const size_t ageDiff = age - it->second.age;\n if (ageDiff >= CACHE_MAX_AGE) {\n mBackend.destroyTexture(it->second.handle);\n mCacheSize -= it->second.size;\n \/\/slog.d << \"purging \" << it->second.handle.getId() << io::endl;\n it = textureCache.erase(it);\n if (mCacheSize < CACHE_CAPACITY) {\n \/\/ if we're not at capacity, only purge a single entry per gc, trying to\n \/\/ avoid a burst of work.\n break;\n }\n } else {\n ++it;\n }\n }\n\n \/\/if (mAge % 60 == 0) dump();\n \/\/ TODO: maybe purge LRU entries if we have more than a certain number\n \/\/ TODO: maybe purge LRU entries if the size of the cache is too large\n}\n\nUTILS_NOINLINE\nvoid ResourceAllocator::dump() const noexcept {\n slog.d << \"# entries=\" << mTextureCache.size() << \", sz=\" << mCacheSize \/ float(1u << 20u)\n << \" MiB\" << io::endl;\n for (auto const & it : mTextureCache) {\n auto w = it.first.width;\n auto h = it.first.height;\n auto f = FTexture::getFormatSize(it.first.format);\n slog.d << it.first.name << \": w=\" << w << \", h=\" << h << \", f=\" << f << \", sz=\"\n << it.second.size \/ float(1u << 20u) << io::endl;\n }\n}\n\n} \/\/ namespace fg\n} \/\/ namespace filament\n<|endoftext|>"} {"text":"<commit_before>\n#include <Rcpp.h>\n#include <ncbi-vdb\/NGS.hpp>\n#include <ngs-bam\/ngs-bam.hpp>\n#include <ngs\/ErrorMsg.hpp>\n#include <ngs\/ReadCollection.hpp>\n#include <ngs\/ReadIterator.hpp>\n#include <ngs\/Read.hpp>\n\n#include <ngs\/Reference.hpp>\n#include <ngs\/Alignment.hpp>\n#include <ngs\/PileupIterator.hpp>\n\n#include <math.h>\n#include <iostream>\n\nusing namespace ngs;\nusing namespace std;\nusing namespace Rcpp;\n\n\/\/ This is a simple example of exporting a C++ function to R. You can\n\/\/ source this function into an R session using the Rcpp::sourceCpp \n\/\/ function (or via the Source button on the editor toolbar). Learn\n\/\/ more about Rcpp at:\n\/\/\n\/\/ http:\/\/www.rcpp.org\/\n\/\/ http:\/\/adv-r.had.co.nz\/Rcpp.html\n\/\/ http:\/\/gallery.rcpp.org\/\n\/\/s\n\n\/\/' The readCount in the read collection.\n\/\/'\n\/\/' This simply returns the full read count.\n\/\/'\n\/\/' @param acc An accession or a path to an actual SRA file (with .sra suffix)\n\/\/' @param refname Reference name for pile up\n\/\/' @param start An in for position of start of pileup\n\/\/' @param stop An in for position of stop of pileup\n\/\/' @param MinPileUpDepth Coverage required\n\/\/' @return the number of reads in the collection\n\/\/' @export\n\/\/' @examples\n\/\/' getPileUp('SRR390728')\n\/\/ [[Rcpp::export]]\nDataFrame getPileUp(Rcpp::String acc, Rcpp::String refname, int start = 1, int stop = 0, int MinPileUpDepth = 0 ) {\n \n \/\/ open requested accession using SRA implementation of the API\n ReadCollection run = ncbi::NGS::openReadCollection ( acc );\n\n\n \/\/ get requested reference\n ngs::Reference ref = run.getReference ( refname );\n if ( start == 1 && stop == 0 ){\n stop = ref.getLength();\n }\n \n \n \/\/ start iterator on requested range\n long count = stop - start + 1;\n PileupIterator it = ref.getPileupSlice ( start-1 \/*0-based*\/, count);\n \n vector<std::string> RefSpec;\n vector<long> RefPos;\n vector<char> RefBase;\n vector<long> PileDepth;\n\n while ( it.nextPileup ())\n {\n if ( it.getPileupDepth () >= MinPileUpDepth ) { \n RefSpec.push_back(it.getReferenceSpec ());\n RefPos.push_back( it.getReferencePosition () + 1 );\n RefBase.push_back( it.getReferenceBase () );\n PileDepth.push_back(it.getPileupDepth ( ) );\n\n } \n }\n \n return DataFrame::create (\n _[\"ReferenceSpec\"] = RefSpec, _[\"ReferencePosition\"] = RefPos, _[\"ReferenceBase\"] = RefBase, _[\"PileupDepth\"] = PileDepth\n \n );\n \n}\n\n<commit_msg>aligned quality bases<commit_after>\n#include <Rcpp.h>\n#include <ncbi-vdb\/NGS.hpp>\n#include <ngs-bam\/ngs-bam.hpp>\n#include <ngs\/ErrorMsg.hpp>\n#include <ngs\/ReadCollection.hpp>\n#include <ngs\/ReadIterator.hpp>\n#include <ngs\/Read.hpp>\n\n#include <ngs\/Reference.hpp>\n#include <ngs\/Alignment.hpp>\n#include <ngs\/PileupIterator.hpp>\n\n#include <math.h>\n#include <iostream>\n#include <string>\n\nusing namespace ngs;\nusing namespace std;\nusing namespace Rcpp;\n\n\/\/ This is a simple example of exporting a C++ function to R. You can\n\/\/ source this function into an R session using the Rcpp::sourceCpp \n\/\/ function (or via the Source button on the editor toolbar). Learn\n\/\/ more about Rcpp at:\n\/\/\n\/\/ http:\/\/www.rcpp.org\/\n\/\/ http:\/\/adv-r.had.co.nz\/Rcpp.html\n\/\/ http:\/\/gallery.rcpp.org\/\n\/\/s\n\n\/\/' The readCount in the read collection.\n\/\/'\n\/\/' This simply returns the full read count.\n\/\/'\n\/\/' @param acc An accession or a path to an actual SRA file (with .sra suffix)\n\/\/' @param refname Reference name for pile up\n\/\/' @param start An in for position of start of pileup\n\/\/' @param stop An in for position of stop of pileup\n\/\/' @param MinPileUpDepth Coverage required\n\/\/' @return the number of reads in the collection\n\/\/' @export\n\/\/' @examples\n\/\/' getPileUp('SRR390728')\n\/\/ [[Rcpp::export]]\nDataFrame getPileUp(Rcpp::String acc, Rcpp::String refname, int start = 1, int stop = 0, int MinPileUpDepth = 0 ) {\n \n \/\/ open requested accession using SRA implementation of the API\n ReadCollection run = ncbi::NGS::openReadCollection ( acc );\n\n\n \/\/ get requested reference\n ngs::Reference ref = run.getReference ( refname );\n if ( start == 1 && stop == 0 ){\n stop = ref.getLength();\n }\n \n \n \/\/ start iterator on requested range\n long count = stop - start + 1;\n PileupIterator it = ref.getPileupSlice ( start-1 \/*0-based*\/, count);\n \n vector<std::string> RefSpec;\n vector<long> RefPos;\n vector<char> RefBase;\n vector<long> PileDepth;\n vector<char> AlignedQuality;\n vector<std::string> AllAlignedQuality;\n \n while ( it.nextPileup ())\n {\n if ( it.getPileupDepth () >= MinPileUpDepth ) { \n RefSpec.push_back(it.getReferenceSpec ());\n RefPos.push_back( it.getReferencePosition () + 1 );\n RefBase.push_back( it.getReferenceBase () );\n PileDepth.push_back(it.getPileupDepth ( ) );\n AlignedQuality.clear();\n \n while ( it.nextPileupEvent() ){\n \n AlignedQuality.push_back( it.getAlignmentQuality() );\n \n }\n std::string str(AlignedQuality.begin(),AlignedQuality.end());\n AllAlignedQuality.push_back( str ); \n \n }\n \n \n } \n \n \n return DataFrame::create (\n _[\"ReferenceSpec\"] = RefSpec, _[\"ReferencePosition\"] = RefPos, _[\"ReferenceBase\"] = RefBase, _[\"PileupDepth\"] = PileDepth, _[\"AllAlignedQuality\"] = AllAlignedQuality\n \n );\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/coroutine.hxx>\n\n#if ABC_HOST_API_POSIX\n #include <errno.h> \/\/ EINTR errno\n #if ABC_HOST_API_BSD\n #include <sys\/event.h>\n #include <sys\/time.h>\n #include <sys\/types.h>\n #elif ABC_HOST_API_LINUX\n #include <sys\/epoll.h>\n #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n context(std::function<void ()> fnMain) :\n m_fnInnerMain(std::move(fnMain)) {\n }\n\n void reset(::ucontext_t * puctxReturn) {\n if (::getcontext(&m_uctx) < 0) {\n exception::throw_os_error();\n }\n m_uctx.uc_stack.ss_sp = &m_aiStack;\n m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n m_uctx.uc_link = puctxReturn;\n ::makecontext(&m_uctx, reinterpret_cast<void (*)()>(&outer_main), 1, this);\n }\n\nprivate:\n static void outer_main(void * p) {\n context * pctx = static_cast<context *>(p);\n try {\n pctx->m_fnInnerMain();\n } catch (std::exception const & x) {\n exception::write_with_scope_trace(nullptr, &x);\n \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n } catch (...) {\n exception::write_with_scope_trace();\n \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n }\n }\n\npublic:\n ::ucontext_t m_uctx;\nprivate:\n std::function<void ()> m_fnInnerMain;\n \/\/ TODO: use MINSIGSTKSZ.\n abc::max_align_t m_aiStack[1024];\n};\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function<void ()> fnMain) :\n m_pctx(std::make_shared<coroutine::context>(std::move(fnMain))) {\n}\n\ncoroutine::~coroutine() {\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine_scheduler\n\nnamespace abc {\n\nthread_local_value<std::shared_ptr<coroutine_scheduler>> coroutine_scheduler::sm_pcorosched;\n\ncoroutine_scheduler::coroutine_scheduler() :\n m_pcoroctxActive(nullptr),\n m_fdEpoll(::epoll_create1(EPOLL_CLOEXEC)) {\n if (!m_fdEpoll) {\n exception::throw_os_error();\n }\n}\n\ncoroutine_scheduler::~coroutine_scheduler() {\n \/\/ TODO: verify that m_listStartingCoros and m_mapBlockedCoros are empty.\n}\n\n\/*static*\/ coroutine_scheduler & coroutine_scheduler::attach_to_current_thread(\n std::shared_ptr<coroutine_scheduler> pcorosched \/*= nullptr*\/\n) {\n if (sm_pcorosched.operator std::shared_ptr<coroutine_scheduler> const &()) {\n \/\/ The current thread already has a coroutine scheduler.\n \/\/ TODO: use a better exception class.\n ABC_THROW(generic_error, ());\n }\n if (!pcorosched) {\n pcorosched = std::make_shared<coroutine_scheduler>();\n }\n return *(\n sm_pcorosched = std::move(pcorosched)\n ).operator std::shared_ptr<coroutine_scheduler> const &();\n}\n\nstd::shared_ptr<coroutine::context> coroutine_scheduler::find_coroutine_to_activate() {\n \/\/ This loop will only repeat in case of EINTR during ::epoll_wait().\n for (;;) {\n if (m_listStartingCoros) {\n \/\/ There are coroutines that haven’t had a chance to run; remove and schedule the first.\n auto pcoroctx(m_listStartingCoros.pop_front());\n \/\/ TODO: verify how this behaves in a multithreaded scenario.\n pcoroctx->reset(&m_uctxReturn);\n return std::move(pcoroctx);\n } else if (m_mapBlockedCoros) {\n \/\/ There are blocked coroutines; wait for the first one to become ready again.\n ::epoll_event eeReady;\n int cReadyFds = ::epoll_wait(m_fdEpoll.get(), &eeReady, 1, -1);\n \/\/ 0 won’t really be returned; possible values are either 1 or -1.\n if (cReadyFds < 0) {\n int iErr = errno;\n if (iErr == EINTR) {\n continue;\n }\n exception::throw_os_error(iErr);\n }\n \/* Remove this event source from the epoll. Ignore errors, since we wouldn’t know what to\n do aobut them. *\/\n ::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_DEL, eeReady.data.fd, nullptr);\n \/\/ Find which coroutine was waiting for eeReady and remove it from m_mapBlockedCoros.\n \/\/ TODO: need map::pop().\n auto itBlockedCoro(m_mapBlockedCoros.find(eeReady.data.fd));\n std::shared_ptr<coroutine::context> pcoroctxToActivate(std::move(itBlockedCoro->value));\n m_mapBlockedCoros.remove(itBlockedCoro);\n return std::move(pcoroctxToActivate);\n } else {\n return nullptr;\n }\n }\n}\n\nvoid coroutine_scheduler::run() {\n while ((m_pcoroctxActive = find_coroutine_to_activate())) {\n if (::swapcontext(&m_uctxReturn, &m_pcoroctxActive->m_uctx) < 0) {\n \/* TODO: in case of errors, which should never happen here since all coroutines have the\n same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n }\n }\n \/\/ Release the last coroutine.\n m_pcoroctxActive.reset();\n}\n\nvoid coroutine_scheduler::yield_while_async_pending(io::filedesc const & fd, bool bWrite) {\n \/\/ Add fd to the epoll as a new event source.\n ::epoll_event ee;\n ee.data.fd = fd.get();\n \/* Use EPOLLONESHOT to avoid waking up multiple threads for the same fd becoming ready. This\n means we’d need to then rearm it in find_coroutine_to_activate() when it becomes ready, but we’ll\n remove it instead. *\/\n ee.events = EPOLLONESHOT | (bWrite ? EPOLLOUT : EPOLLIN) | EPOLLPRI;\n if (::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_ADD, ee.data.fd, &ee) < 0) {\n exception::throw_os_error();\n }\n \/\/ Deactivate the current coroutine and find one to activate instead.\n ::ucontext_t * puctxActive = &m_pcoroctxActive->m_uctx;\n auto itBlockedCoro(\n m_mapBlockedCoros.add_or_assign(ee.data.fd, std::move(m_pcoroctxActive)).first\n );\n try {\n m_pcoroctxActive = find_coroutine_to_activate();\n } catch (...) {\n \/\/ If anything went wrong, restore the coroutine that was active.\n \/\/ TODO: need map::pop().\n m_pcoroctxActive = std::move(itBlockedCoro->value);\n m_mapBlockedCoros.remove(itBlockedCoro);\n throw;\n }\n \/* If the context changed, i.e. the coroutine that’s ready to run is not the one that was active,\n switch to it. *\/\n if (&m_pcoroctxActive->m_uctx != puctxActive) {\n if (::swapcontext(puctxActive, &m_pcoroctxActive->m_uctx) < 0) {\n \/* TODO: in case of errors, which should never happen here since all coroutines have the\n same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n }\n }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Compare abc::coroutine::context pointers, not ::ucontext_t pointers<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/coroutine.hxx>\n\n#if ABC_HOST_API_POSIX\n #include <errno.h> \/\/ EINTR errno\n #if ABC_HOST_API_BSD\n #include <sys\/event.h>\n #include <sys\/time.h>\n #include <sys\/types.h>\n #elif ABC_HOST_API_LINUX\n #include <sys\/epoll.h>\n #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n context(std::function<void ()> fnMain) :\n m_fnInnerMain(std::move(fnMain)) {\n }\n\n void reset(::ucontext_t * puctxReturn) {\n if (::getcontext(&m_uctx) < 0) {\n exception::throw_os_error();\n }\n m_uctx.uc_stack.ss_sp = &m_aiStack;\n m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n m_uctx.uc_link = puctxReturn;\n ::makecontext(&m_uctx, reinterpret_cast<void (*)()>(&outer_main), 1, this);\n }\n\nprivate:\n static void outer_main(void * p) {\n context * pctx = static_cast<context *>(p);\n try {\n pctx->m_fnInnerMain();\n } catch (std::exception const & x) {\n exception::write_with_scope_trace(nullptr, &x);\n \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n } catch (...) {\n exception::write_with_scope_trace();\n \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n }\n }\n\npublic:\n ::ucontext_t m_uctx;\nprivate:\n std::function<void ()> m_fnInnerMain;\n \/\/ TODO: use MINSIGSTKSZ.\n abc::max_align_t m_aiStack[1024];\n};\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function<void ()> fnMain) :\n m_pctx(std::make_shared<coroutine::context>(std::move(fnMain))) {\n}\n\ncoroutine::~coroutine() {\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine_scheduler\n\nnamespace abc {\n\nthread_local_value<std::shared_ptr<coroutine_scheduler>> coroutine_scheduler::sm_pcorosched;\n\ncoroutine_scheduler::coroutine_scheduler() :\n m_pcoroctxActive(nullptr),\n m_fdEpoll(::epoll_create1(EPOLL_CLOEXEC)) {\n if (!m_fdEpoll) {\n exception::throw_os_error();\n }\n}\n\ncoroutine_scheduler::~coroutine_scheduler() {\n \/\/ TODO: verify that m_listStartingCoros and m_mapBlockedCoros are empty.\n}\n\n\/*static*\/ coroutine_scheduler & coroutine_scheduler::attach_to_current_thread(\n std::shared_ptr<coroutine_scheduler> pcorosched \/*= nullptr*\/\n) {\n if (sm_pcorosched.operator std::shared_ptr<coroutine_scheduler> const &()) {\n \/\/ The current thread already has a coroutine scheduler.\n \/\/ TODO: use a better exception class.\n ABC_THROW(generic_error, ());\n }\n if (!pcorosched) {\n pcorosched = std::make_shared<coroutine_scheduler>();\n }\n return *(\n sm_pcorosched = std::move(pcorosched)\n ).operator std::shared_ptr<coroutine_scheduler> const &();\n}\n\nstd::shared_ptr<coroutine::context> coroutine_scheduler::find_coroutine_to_activate() {\n \/\/ This loop will only repeat in case of EINTR during ::epoll_wait().\n for (;;) {\n if (m_listStartingCoros) {\n \/\/ There are coroutines that haven’t had a chance to run; remove and schedule the first.\n auto pcoroctx(m_listStartingCoros.pop_front());\n \/\/ TODO: verify how this behaves in a multithreaded scenario.\n pcoroctx->reset(&m_uctxReturn);\n return std::move(pcoroctx);\n } else if (m_mapBlockedCoros) {\n \/\/ There are blocked coroutines; wait for the first one to become ready again.\n ::epoll_event eeReady;\n int cReadyFds = ::epoll_wait(m_fdEpoll.get(), &eeReady, 1, -1);\n \/\/ 0 won’t really be returned; possible values are either 1 or -1.\n if (cReadyFds < 0) {\n int iErr = errno;\n if (iErr == EINTR) {\n continue;\n }\n exception::throw_os_error(iErr);\n }\n \/* Remove this event source from the epoll. Ignore errors, since we wouldn’t know what to\n do aobut them. *\/\n ::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_DEL, eeReady.data.fd, nullptr);\n \/\/ Find which coroutine was waiting for eeReady and remove it from m_mapBlockedCoros.\n \/\/ TODO: need map::pop().\n auto itBlockedCoro(m_mapBlockedCoros.find(eeReady.data.fd));\n std::shared_ptr<coroutine::context> pcoroctxToActivate(std::move(itBlockedCoro->value));\n m_mapBlockedCoros.remove(itBlockedCoro);\n return std::move(pcoroctxToActivate);\n } else {\n return nullptr;\n }\n }\n}\n\nvoid coroutine_scheduler::run() {\n while ((m_pcoroctxActive = find_coroutine_to_activate())) {\n if (::swapcontext(&m_uctxReturn, &m_pcoroctxActive->m_uctx) < 0) {\n \/* TODO: in case of errors, which should never happen here since all coroutines have the\n same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n }\n }\n \/\/ Release the last coroutine.\n m_pcoroctxActive.reset();\n}\n\nvoid coroutine_scheduler::yield_while_async_pending(io::filedesc const & fd, bool bWrite) {\n \/\/ Add fd to the epoll as a new event source.\n ::epoll_event ee;\n ee.data.fd = fd.get();\n \/* Use EPOLLONESHOT to avoid waking up multiple threads for the same fd becoming ready. This\n means we’d need to then rearm it in find_coroutine_to_activate() when it becomes ready, but we’ll\n remove it instead. *\/\n ee.events = EPOLLONESHOT | (bWrite ? EPOLLOUT : EPOLLIN) | EPOLLPRI;\n if (::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_ADD, ee.data.fd, &ee) < 0) {\n exception::throw_os_error();\n }\n \/\/ Deactivate the current coroutine and find one to activate instead.\n coroutine::context * pcoroctxActive = m_pcoroctxActive.get();\n auto itBlockedCoro(\n m_mapBlockedCoros.add_or_assign(ee.data.fd, std::move(m_pcoroctxActive)).first\n );\n try {\n m_pcoroctxActive = find_coroutine_to_activate();\n } catch (...) {\n \/\/ If anything went wrong, restore the coroutine that was active.\n \/\/ TODO: need map::pop().\n m_pcoroctxActive = std::move(itBlockedCoro->value);\n m_mapBlockedCoros.remove(itBlockedCoro);\n throw;\n }\n \/* If the context changed, i.e. the coroutine that’s ready to run is not the one that was active,\n switch to it. *\/\n if (m_pcoroctxActive.get() != pcoroctxActive) {\n if (::swapcontext(&pcoroctxActive->m_uctx, &m_pcoroctxActive->m_uctx) < 0) {\n \/* TODO: in case of errors, which should never happen here since all coroutines have the\n same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n }\n }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/ui\/views\/root_view.h\"\n\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/ui\/views\/menu_bar.h\"\n#include \"content\/public\/browser\/native_web_keyboard_event.h\"\n\nnamespace atom {\n\nnamespace {\n\n\/\/ The menu bar height in pixels.\n#if defined(OS_WIN)\nconst int kMenuBarHeight = 20;\n#else\nconst int kMenuBarHeight = 25;\n#endif\n\nbool IsAltKey(const content::NativeWebKeyboardEvent& event) {\n return event.windows_key_code == ui::VKEY_MENU;\n}\n\nbool IsAltModifier(const content::NativeWebKeyboardEvent& event) {\n typedef content::NativeWebKeyboardEvent::Modifiers Modifiers;\n int modifiers = event.GetModifiers();\n modifiers &= ~Modifiers::kNumLockOn;\n modifiers &= ~Modifiers::kCapsLockOn;\n return (modifiers == Modifiers::kAltKey) ||\n (modifiers == (Modifiers::kAltKey | Modifiers::kIsLeft)) ||\n (modifiers == (Modifiers::kAltKey | Modifiers::kIsRight));\n}\n\n} \/\/ namespace\n\nRootView::RootView(NativeWindow* window)\n : window_(window),\n last_focused_view_tracker_(std::make_unique<views::ViewTracker>()) {\n set_owned_by_client();\n}\n\nRootView::~RootView() {}\n\nvoid RootView::SetMenu(AtomMenuModel* menu_model) {\n if (menu_model == nullptr) {\n \/\/ Remove accelerators\n UnregisterAcceleratorsWithFocusManager();\n \/\/ and menu bar.\n SetMenuBarVisibility(false);\n menu_bar_.reset();\n return;\n }\n\n RegisterAcceleratorsWithFocusManager(menu_model);\n\n \/\/ Do not show menu bar in frameless window.\n if (!window_->has_frame())\n return;\n\n if (!menu_bar_) {\n menu_bar_.reset(new MenuBar(this));\n menu_bar_->set_owned_by_client();\n if (!menu_bar_autohide_)\n SetMenuBarVisibility(true);\n }\n\n menu_bar_->SetMenu(menu_model);\n Layout();\n}\n\nbool RootView::HasMenu() const {\n return !!menu_bar_;\n}\n\nint RootView::GetMenuBarHeight() const {\n return kMenuBarHeight;\n}\n\nvoid RootView::SetAutoHideMenuBar(bool auto_hide) {\n menu_bar_autohide_ = auto_hide;\n}\n\nbool RootView::IsMenuBarAutoHide() const {\n return menu_bar_autohide_;\n}\n\nvoid RootView::SetMenuBarVisibility(bool visible) {\n if (!window_->content_view() || !menu_bar_ || menu_bar_visible_ == visible)\n return;\n\n menu_bar_visible_ = visible;\n if (visible) {\n DCHECK_EQ(child_count(), 1);\n AddChildView(menu_bar_.get());\n } else {\n DCHECK_EQ(child_count(), 2);\n RemoveChildView(menu_bar_.get());\n }\n\n Layout();\n}\n\nbool RootView::IsMenuBarVisible() const {\n return menu_bar_visible_;\n}\n\nvoid RootView::HandleKeyEvent(const content::NativeWebKeyboardEvent& event) {\n if (!menu_bar_)\n return;\n\n \/\/ Show accelerator when \"Alt\" is pressed.\n if (menu_bar_visible_ && IsAltKey(event))\n menu_bar_->SetAcceleratorVisibility(event.GetType() ==\n blink::WebInputEvent::kRawKeyDown);\n\n \/\/ Show the submenu when \"Alt+Key\" is pressed.\n if (event.GetType() == blink::WebInputEvent::kRawKeyDown &&\n !IsAltKey(event) && IsAltModifier(event)) {\n if (menu_bar_->HasAccelerator(event.windows_key_code)) {\n if (!menu_bar_visible_) {\n SetMenuBarVisibility(true);\n\n View* focused_view = GetFocusManager()->GetFocusedView();\n last_focused_view_tracker_->SetView(focused_view);\n menu_bar_->RequestFocus();\n }\n\n menu_bar_->ActivateAccelerator(event.windows_key_code);\n }\n return;\n }\n\n \/\/ Toggle the menu bar only when a single Alt is released.\n if (event.GetType() == blink::WebInputEvent::kRawKeyDown && IsAltKey(event)) {\n \/\/ When a single Alt is pressed:\n menu_bar_alt_pressed_ = true;\n } else if (event.GetType() == blink::WebInputEvent::kKeyUp &&\n IsAltKey(event) && menu_bar_alt_pressed_) {\n \/\/ When a single Alt is released right after a Alt is pressed:\n menu_bar_alt_pressed_ = false;\n if (menu_bar_autohide_)\n SetMenuBarVisibility(!menu_bar_visible_);\n\n View* focused_view = GetFocusManager()->GetFocusedView();\n last_focused_view_tracker_->SetView(focused_view);\n menu_bar_->RequestFocus();\n \/\/ Show accelerators when menu bar is focused\n menu_bar_->SetAcceleratorVisibility(true);\n } else {\n \/\/ When any other keys except single Alt have been pressed\/released:\n menu_bar_alt_pressed_ = false;\n }\n}\n\nvoid RootView::RestoreFocus() {\n View* last_focused_view = last_focused_view_tracker_->view();\n if (last_focused_view) {\n GetFocusManager()->SetFocusedViewWithReason(\n last_focused_view, views::FocusManager::kReasonFocusRestore);\n }\n if (menu_bar_autohide_)\n SetMenuBarVisibility(false);\n}\n\nvoid RootView::ResetAltState() {\n menu_bar_alt_pressed_ = false;\n}\n\nvoid RootView::Layout() {\n if (!window_->content_view()) \/\/ Not ready yet.\n return;\n\n const auto menu_bar_bounds =\n menu_bar_visible_\n ? gfx::Rect(insets_.left(), insets_.top(),\n size().width() - insets_.width(), kMenuBarHeight)\n : gfx::Rect();\n if (menu_bar_)\n menu_bar_->SetBoundsRect(menu_bar_bounds);\n\n window_->content_view()->SetBoundsRect(\n gfx::Rect(insets_.left(),\n menu_bar_visible_ ? menu_bar_bounds.bottom() : insets_.top(),\n size().width() - insets_.width(),\n size().height() - menu_bar_bounds.height() - insets_.height()));\n}\n\ngfx::Size RootView::GetMinimumSize() const {\n return window_->GetMinimumSize();\n}\n\ngfx::Size RootView::GetMaximumSize() const {\n return window_->GetMaximumSize();\n}\n\nbool RootView::AcceleratorPressed(const ui::Accelerator& accelerator) {\n return accelerator_util::TriggerAcceleratorTableCommand(&accelerator_table_,\n accelerator);\n}\n\nvoid RootView::RegisterAcceleratorsWithFocusManager(AtomMenuModel* menu_model) {\n if (!menu_model)\n return;\n \/\/ Clear previous accelerators.\n UnregisterAcceleratorsWithFocusManager();\n\n views::FocusManager* focus_manager = GetFocusManager();\n \/\/ Register accelerators with focus manager.\n accelerator_util::GenerateAcceleratorTable(&accelerator_table_, menu_model);\n for (const auto& iter : accelerator_table_) {\n focus_manager->RegisterAccelerator(\n iter.first, ui::AcceleratorManager::kNormalPriority, this);\n }\n}\n\nvoid RootView::UnregisterAcceleratorsWithFocusManager() {\n views::FocusManager* focus_manager = GetFocusManager();\n accelerator_table_.clear();\n focus_manager->UnregisterAccelerators(this);\n}\n\nvoid RootView::SetInsets(const gfx::Insets& insets) {\n if (insets != insets_) {\n insets_ = insets;\n Layout();\n }\n}\n\n} \/\/ namespace atom\n<commit_msg>fix: crash when alt key pressed with falsy menu bar visiblity (#17766)<commit_after>\/\/ Copyright (c) 2018 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/ui\/views\/root_view.h\"\n\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/ui\/views\/menu_bar.h\"\n#include \"content\/public\/browser\/native_web_keyboard_event.h\"\n\nnamespace atom {\n\nnamespace {\n\n\/\/ The menu bar height in pixels.\n#if defined(OS_WIN)\nconst int kMenuBarHeight = 20;\n#else\nconst int kMenuBarHeight = 25;\n#endif\n\nbool IsAltKey(const content::NativeWebKeyboardEvent& event) {\n return event.windows_key_code == ui::VKEY_MENU;\n}\n\nbool IsAltModifier(const content::NativeWebKeyboardEvent& event) {\n typedef content::NativeWebKeyboardEvent::Modifiers Modifiers;\n int modifiers = event.GetModifiers();\n modifiers &= ~Modifiers::kNumLockOn;\n modifiers &= ~Modifiers::kCapsLockOn;\n return (modifiers == Modifiers::kAltKey) ||\n (modifiers == (Modifiers::kAltKey | Modifiers::kIsLeft)) ||\n (modifiers == (Modifiers::kAltKey | Modifiers::kIsRight));\n}\n\n} \/\/ namespace\n\nRootView::RootView(NativeWindow* window)\n : window_(window),\n last_focused_view_tracker_(std::make_unique<views::ViewTracker>()) {\n set_owned_by_client();\n}\n\nRootView::~RootView() {}\n\nvoid RootView::SetMenu(AtomMenuModel* menu_model) {\n if (menu_model == nullptr) {\n \/\/ Remove accelerators\n UnregisterAcceleratorsWithFocusManager();\n \/\/ and menu bar.\n SetMenuBarVisibility(false);\n menu_bar_.reset();\n return;\n }\n\n RegisterAcceleratorsWithFocusManager(menu_model);\n\n \/\/ Do not show menu bar in frameless window.\n if (!window_->has_frame())\n return;\n\n if (!menu_bar_) {\n menu_bar_.reset(new MenuBar(this));\n menu_bar_->set_owned_by_client();\n if (!menu_bar_autohide_)\n SetMenuBarVisibility(true);\n }\n\n menu_bar_->SetMenu(menu_model);\n Layout();\n}\n\nbool RootView::HasMenu() const {\n return !!menu_bar_;\n}\n\nint RootView::GetMenuBarHeight() const {\n return kMenuBarHeight;\n}\n\nvoid RootView::SetAutoHideMenuBar(bool auto_hide) {\n menu_bar_autohide_ = auto_hide;\n}\n\nbool RootView::IsMenuBarAutoHide() const {\n return menu_bar_autohide_;\n}\n\nvoid RootView::SetMenuBarVisibility(bool visible) {\n if (!window_->content_view() || !menu_bar_ || menu_bar_visible_ == visible)\n return;\n\n menu_bar_visible_ = visible;\n if (visible) {\n DCHECK_EQ(child_count(), 1);\n AddChildView(menu_bar_.get());\n } else {\n DCHECK_EQ(child_count(), 2);\n RemoveChildView(menu_bar_.get());\n }\n\n Layout();\n}\n\nbool RootView::IsMenuBarVisible() const {\n return menu_bar_visible_;\n}\n\nvoid RootView::HandleKeyEvent(const content::NativeWebKeyboardEvent& event) {\n if (!menu_bar_)\n return;\n\n \/\/ Show accelerator when \"Alt\" is pressed.\n if (menu_bar_visible_ && IsAltKey(event))\n menu_bar_->SetAcceleratorVisibility(event.GetType() ==\n blink::WebInputEvent::kRawKeyDown);\n\n \/\/ Show the submenu when \"Alt+Key\" is pressed.\n if (event.GetType() == blink::WebInputEvent::kRawKeyDown &&\n !IsAltKey(event) && IsAltModifier(event)) {\n if (menu_bar_->HasAccelerator(event.windows_key_code)) {\n if (!menu_bar_visible_) {\n SetMenuBarVisibility(true);\n\n View* focused_view = GetFocusManager()->GetFocusedView();\n last_focused_view_tracker_->SetView(focused_view);\n menu_bar_->RequestFocus();\n }\n\n menu_bar_->ActivateAccelerator(event.windows_key_code);\n }\n return;\n }\n\n \/\/ Toggle the menu bar only when a single Alt is released.\n if (event.GetType() == blink::WebInputEvent::kRawKeyDown && IsAltKey(event)) {\n \/\/ When a single Alt is pressed:\n menu_bar_alt_pressed_ = true;\n } else if (event.GetType() == blink::WebInputEvent::kKeyUp &&\n IsAltKey(event) && menu_bar_alt_pressed_) {\n \/\/ When a single Alt is released right after a Alt is pressed:\n menu_bar_alt_pressed_ = false;\n if (menu_bar_autohide_)\n SetMenuBarVisibility(!menu_bar_visible_);\n\n View* focused_view = GetFocusManager()->GetFocusedView();\n last_focused_view_tracker_->SetView(focused_view);\n if (menu_bar_visible_) {\n menu_bar_->RequestFocus();\n \/\/ Show accelerators when menu bar is focused\n menu_bar_->SetAcceleratorVisibility(true);\n }\n } else {\n \/\/ When any other keys except single Alt have been pressed\/released:\n menu_bar_alt_pressed_ = false;\n }\n}\n\nvoid RootView::RestoreFocus() {\n View* last_focused_view = last_focused_view_tracker_->view();\n if (last_focused_view) {\n GetFocusManager()->SetFocusedViewWithReason(\n last_focused_view, views::FocusManager::kReasonFocusRestore);\n }\n if (menu_bar_autohide_)\n SetMenuBarVisibility(false);\n}\n\nvoid RootView::ResetAltState() {\n menu_bar_alt_pressed_ = false;\n}\n\nvoid RootView::Layout() {\n if (!window_->content_view()) \/\/ Not ready yet.\n return;\n\n const auto menu_bar_bounds =\n menu_bar_visible_\n ? gfx::Rect(insets_.left(), insets_.top(),\n size().width() - insets_.width(), kMenuBarHeight)\n : gfx::Rect();\n if (menu_bar_)\n menu_bar_->SetBoundsRect(menu_bar_bounds);\n\n window_->content_view()->SetBoundsRect(\n gfx::Rect(insets_.left(),\n menu_bar_visible_ ? menu_bar_bounds.bottom() : insets_.top(),\n size().width() - insets_.width(),\n size().height() - menu_bar_bounds.height() - insets_.height()));\n}\n\ngfx::Size RootView::GetMinimumSize() const {\n return window_->GetMinimumSize();\n}\n\ngfx::Size RootView::GetMaximumSize() const {\n return window_->GetMaximumSize();\n}\n\nbool RootView::AcceleratorPressed(const ui::Accelerator& accelerator) {\n return accelerator_util::TriggerAcceleratorTableCommand(&accelerator_table_,\n accelerator);\n}\n\nvoid RootView::RegisterAcceleratorsWithFocusManager(AtomMenuModel* menu_model) {\n if (!menu_model)\n return;\n \/\/ Clear previous accelerators.\n UnregisterAcceleratorsWithFocusManager();\n\n views::FocusManager* focus_manager = GetFocusManager();\n \/\/ Register accelerators with focus manager.\n accelerator_util::GenerateAcceleratorTable(&accelerator_table_, menu_model);\n for (const auto& iter : accelerator_table_) {\n focus_manager->RegisterAccelerator(\n iter.first, ui::AcceleratorManager::kNormalPriority, this);\n }\n}\n\nvoid RootView::UnregisterAcceleratorsWithFocusManager() {\n views::FocusManager* focus_manager = GetFocusManager();\n accelerator_table_.clear();\n focus_manager->UnregisterAccelerators(this);\n}\n\nvoid RootView::SetInsets(const gfx::Insets& insets) {\n if (insets != insets_) {\n insets_ = insets;\n Layout();\n }\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before>#if defined(__cplusplus) && (__cplusplus >= 201103L)\n\n#include <iostream>\n#include <iomanip>\n\n#include <atomic>\n\n#include <chrono>\n\n#ifdef SEQUENTIAL_CONSISTENCY\nauto update_model = std::memory_order_seq_cst;\n#else\nauto update_model = std::memory_order_relaxed;\n#endif\n\n#ifdef _OPENMP\n# include <omp.h>\n#define OMP_PARALLEL _Pragma(\"omp parallel\")\n#define OMP_BARRIER _Pragma(\"omp barrier\")\n#define OMP_CRITICAL _Pragma(\"omp critical\")\n#ifdef SEQUENTIAL_CONSISTENCY\n#define OMP_ATOMIC _Pragma(\"omp atomic seq_cst\")\n#define OMP_ATOMIC_CAPTURE _Pragma(\"omp atomic capture seq_cst\")\n#else\n#define OMP_ATOMIC _Pragma(\"omp atomic\")\n#define OMP_ATOMIC_CAPTURE _Pragma(\"omp atomic capture\")\n#endif\n#else\n# error No OpenMP support!\n#endif\n\nint main(int argc, char * argv[])\n{\n int iterations = (argc>1) ? atoi(argv[1]) : 10000000;\n\n std::cout << \"thread counter benchmark\\n\";\n std::cout << \"num threads = \" << omp_get_max_threads() << \"\\n\";\n std::cout << \"iterations = \" << iterations << \"\\n\";\n#ifdef SEQUENTIAL_CONSISTENCY\n std::cout << \"memory model = \" << \"seq_cst\";\n#else\n std::cout << \"memory model = \" << \"relaxed\";\n#endif\n std::cout << std::endl;\n\n std::cout << \"1) std::atomic_fetch_add(&counter, 1)\\n\";\n\n std::atomic<int> counter = {0};\n int omp_counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n std::atomic_fetch_add(&counter, 1);\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"2) ++counter\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n ++counter;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"3) counter++\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"4) output = counter++\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n output = counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n std::cout << \"5) output = std::atomic_fetch_add(&counter, 1)\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n output = std::atomic_fetch_add(&counter, 1);\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n std::cout << \"6) #pragma omp atomic\\n\";\n\n omp_counter = 0;\n\n OMP_PARALLEL\n {\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n OMP_ATOMIC\n omp_counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"7) #pragma omp atomic capture\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n OMP_ATOMIC_CAPTURE\n output = omp_counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n return 0;\n}\n\n#else \/\/ C++11\n#error You need C++11 for this test!\n#endif \/\/ C++11\n<commit_msg>bugfix in printout (omp_counter)<commit_after>#if defined(__cplusplus) && (__cplusplus >= 201103L)\n\n#include <iostream>\n#include <iomanip>\n\n#include <atomic>\n\n#include <chrono>\n\n#ifdef SEQUENTIAL_CONSISTENCY\nauto update_model = std::memory_order_seq_cst;\n#else\nauto update_model = std::memory_order_relaxed;\n#endif\n\n#ifdef _OPENMP\n# include <omp.h>\n#define OMP_PARALLEL _Pragma(\"omp parallel\")\n#define OMP_BARRIER _Pragma(\"omp barrier\")\n#define OMP_CRITICAL _Pragma(\"omp critical\")\n#ifdef SEQUENTIAL_CONSISTENCY\n#define OMP_ATOMIC _Pragma(\"omp atomic seq_cst\")\n#define OMP_ATOMIC_CAPTURE _Pragma(\"omp atomic capture seq_cst\")\n#else\n#define OMP_ATOMIC _Pragma(\"omp atomic\")\n#define OMP_ATOMIC_CAPTURE _Pragma(\"omp atomic capture\")\n#endif\n#else\n# error No OpenMP support!\n#endif\n\nint main(int argc, char * argv[])\n{\n int iterations = (argc>1) ? atoi(argv[1]) : 10000000;\n\n std::cout << \"thread counter benchmark\\n\";\n std::cout << \"num threads = \" << omp_get_max_threads() << \"\\n\";\n std::cout << \"iterations = \" << iterations << \"\\n\";\n#ifdef SEQUENTIAL_CONSISTENCY\n std::cout << \"memory model = \" << \"seq_cst\";\n#else\n std::cout << \"memory model = \" << \"relaxed\";\n#endif\n std::cout << std::endl;\n\n std::cout << \"1) std::atomic_fetch_add(&counter, 1)\\n\";\n\n std::atomic<int> counter = {0};\n int omp_counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n std::atomic_fetch_add(&counter, 1);\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"2) ++counter\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n ++counter;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"3) counter++\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n }\n }\n\n std::cout << \"4) output = counter++\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n output = counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n std::cout << \"5) output = std::atomic_fetch_add(&counter, 1)\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n output = std::atomic_fetch_add(&counter, 1);\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n std::atomic_thread_fence(std::memory_order_seq_cst);\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n std::cout << \"6) #pragma omp atomic\\n\";\n\n omp_counter = 0;\n\n OMP_PARALLEL\n {\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n OMP_ATOMIC\n omp_counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << omp_counter << std::endl;\n }\n }\n\n std::cout << \"7) #pragma omp atomic capture\\n\";\n\n counter = 0;\n\n OMP_PARALLEL\n {\n int output = -1;\n\n \/\/\/ START TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();\n\n for (int i=0; i<iterations; ++i) {\n OMP_ATOMIC_CAPTURE\n output = omp_counter++;\n }\n\n \/\/\/ STOP TIME\n OMP_BARRIER\n std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n \/\/\/ PRINT TIME\n std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);\n OMP_CRITICAL\n {\n std::cout << \"total time elapsed = \" << dt.count() << \"\\n\";\n std::cout << \"time per iteration = \" << dt.count()\/iterations << \"\\n\";\n std::cout << omp_counter << std::endl;\n std::cout << output << std::endl;\n }\n }\n\n return 0;\n}\n\n#else \/\/ C++11\n#error You need C++11 for this test!\n#endif \/\/ C++11\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"Device.h\"\n#include \"Directory.h\"\n#include \"utils\/Filename.h\"\n#include \"logging\/Logger.h\"\n\n#include <algorithm>\n#include <cstring>\n#include <cstdio>\n#include <dirent.h>\n#include <limits.h>\n#include <mntent.h>\n#include <unistd.h>\n#include <sys\/types.h>\n\nnamespace\n{\n \/\/ Allow private ctors to be used from make_shared\n struct DeviceBuilder : public fs::Device\n {\n template <typename... Args>\n DeviceBuilder( Args&&... args ) : Device( std::forward<Args>( args )... ) {}\n };\n}\n\nnamespace fs\n{\n\nDevice::DeviceMap Device::Devices;\nDevice::MountpointMap Device::Mountpoints;\nDevice::DeviceCacheMap Device::DeviceCache;\n\nDevice::Device( const std::string& uuid, const std::string& mountpoint, bool isRemovable )\n : m_uuid( uuid )\n , m_mountpoint( mountpoint )\n , m_present( true )\n , m_removable( isRemovable )\n{\n if ( *m_mountpoint.crbegin() != '\/' )\n m_mountpoint += '\/';\n}\n\nconst std::string& Device::uuid() const\n{\n return m_uuid;\n}\n\nbool Device::isRemovable() const\n{\n return m_removable;\n}\n\nbool Device::isPresent() const\n{\n return m_present;\n}\n\nconst std::string&Device::mountpoint() const\n{\n return m_mountpoint;\n}\n\nstd::shared_ptr<IDevice> Device::fromPath( const std::string& path )\n{\n std::shared_ptr<IDevice> res;\n for ( const auto& p : DeviceCache )\n {\n if ( path.find( p.second->mountpoint() ) == 0 )\n {\n if ( res == nullptr || res->mountpoint().length() < p.second->mountpoint().length() )\n res = p.second;\n }\n }\n return res;\n}\n\nstd::shared_ptr<IDevice> Device::fromUuid( const std::string& uuid )\n{\n auto it = DeviceCache.find( uuid );\n if ( it != end( DeviceCache ) )\n return it->second;\n return nullptr;\n}\n\nbool Device::populateCache()\n{\n Devices = listDevices();\n Mountpoints = listMountpoints();\n DeviceCache = populateDeviceCache();\n return true;\n}\n\nDevice::DeviceMap Device::listDevices()\n{\n\n static const std::vector<std::string> deviceBlacklist = { \"loop\", \"dm-\" };\n const std::string devPath = \"\/dev\/disk\/by-uuid\/\";\n \/\/ Don't use fs::Directory to iterate, as it resolves the symbolic links automatically.\n \/\/ We need the link name & what it points to.\n std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( devPath.c_str() ), &closedir );\n if ( dir == nullptr )\n {\n std::stringstream err;\n err << \"Failed to open \/dev\/disk\/by-uuid: \" << strerror(errno);\n throw std::runtime_error( err.str() );\n }\n DeviceMap res;\n dirent* result = nullptr;\n\n while ( ( result = readdir( dir.get() ) ) != nullptr )\n {\n if ( strcmp( result->d_name, \".\" ) == 0 ||\n strcmp( result->d_name, \"..\" ) == 0 )\n {\n continue;\n }\n std::string path = devPath + result->d_name;\n char linkPath[PATH_MAX] = {};\n if ( readlink( path.c_str(), linkPath, PATH_MAX ) < 0 )\n {\n std::stringstream err;\n err << \"Failed to resolve uuid -> device link: \"\n << result->d_name << \" (\" << strerror(errno) << ')';\n throw std::runtime_error( err.str() );\n }\n auto deviceName = utils::file::fileName( linkPath );\n if ( std::find_if( begin( deviceBlacklist ), end( deviceBlacklist ), [&deviceName]( const std::string& pattern ) {\n return deviceName.length() >= pattern.length() && deviceName.find( pattern ) == 0;\n }) != end( deviceBlacklist ) )\n continue;\n auto uuid = result->d_name;\n LOG_INFO( \"Discovered device \", deviceName, \" -> {\", uuid, '}' );\n res[deviceName] = uuid;\n }\n return res;\n}\n\nDevice::MountpointMap Device::listMountpoints()\n{\n static const std::vector<std::string> allowedFsType = { \"vfat\", \"exfat\", \"sdcardfs\", \"fuse\",\n \"ntfs\", \"fat32\", \"ext3\", \"ext4\", \"esdfs\" };\n MountpointMap res;\n char buff[512];\n errno = 0;\n mntent* s;\n#ifndef __ANDROID__\n mntent smnt;\n FILE* f = setmntent(\"\/etc\/mtab\", \"r\");\n if ( f == nullptr )\n throw std::runtime_error( \"Failed to read \/etc\/mtab\" );\n std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &endmntent );\n while ( getmntent_r( f, &smnt, buff, sizeof(buff) ) != nullptr )\n {\n s = &smnt;\n#else\n FILE* f = fopen( \"\/proc\/mounts\", \"r\" );\n std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &fclose );\n while ( s = getmntent( f ) )\n {\n#endif\n if ( std::find( begin( allowedFsType ), end( allowedFsType ), s->mnt_type ) == end( allowedFsType ) )\n continue;\n auto deviceName = s->mnt_fsname;\n LOG_INFO( \"Discovered mountpoint \", deviceName, \" mounted on \", s->mnt_dir, \" (\", s->mnt_type, ')' );\n res[deviceName] = s->mnt_dir;\n errno = 0;\n }\n if ( errno != 0 )\n {\n LOG_ERROR( \"Failed to read mountpoints: \", strerror( errno ) );\n }\n return res;\n}\n\nDevice::DeviceCacheMap Device::populateDeviceCache()\n{\n Device::DeviceCacheMap res;\n for ( const auto& p : Mountpoints )\n {\n const auto& devicePath = p.first;\n auto deviceName = utils::file::fileName( devicePath );\n const auto& mountpoint = p.second;\n auto it = Devices.find( deviceName );\n std::string uuid;\n if ( it != end( Devices ) )\n uuid = it->second;\n else\n {\n deviceName = deviceFromDeviceMapper( devicePath );\n it = Devices.find( deviceName );\n if ( it != end( Devices ) )\n uuid = it->second;\n else\n {\n LOG_ERROR( \"Failed to resolve mountpoint \", mountpoint, \" to any known device\" );\n continue;\n }\n }\n auto removable = isRemovable( deviceName, mountpoint );\n LOG_INFO( \"Adding device to cache: {\", uuid, \"} mounted on \", mountpoint, \" Removable: \", removable );\n res[uuid] = std::make_shared<DeviceBuilder>( uuid, mountpoint, removable );\n }\n return res;\n}\n\nstd::string Device::deviceFromDeviceMapper( const std::string& devicePath )\n{\n if ( devicePath.find( \"\/dev\/mapper\" ) != 0 )\n return {};\n char linkPath[PATH_MAX];\n if ( readlink( devicePath.c_str(), linkPath, PATH_MAX ) < 0 )\n {\n std::stringstream err;\n err << \"Failed to resolve device -> mapper link: \"\n << devicePath << \" (\" << strerror(errno) << ')';\n throw std::runtime_error( err.str() );\n }\n const auto dmName = utils::file::fileName( linkPath );\n std::string dmSlavePath = \"\/sys\/block\/\" + dmName + \"\/slaves\";\n std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( dmSlavePath.c_str() ), &closedir );\n std::string res;\n if ( dir == nullptr )\n return {};\n dirent* result;\n while ( ( result = readdir( dir.get() ) ) != nullptr )\n {\n if ( strcmp( result->d_name, \".\" ) == 0 ||\n strcmp( result->d_name, \"..\" ) == 0 )\n {\n continue;\n }\n if ( res.empty() == true )\n res = result->d_name;\n else\n LOG_WARN( \"More than one slave for device mapper \", linkPath );\n }\n LOG_INFO( \"Device mapper \", dmName, \" maps to \", res );\n return res;\n}\n\nbool Device::isRemovable( const std::string& deviceName, const std::string& mountpoint )\n{\n#ifndef TIZEN\n (void)mountpoint;\n std::stringstream removableFilePath;\n removableFilePath << \"\/sys\/block\/\" << deviceName << \"\/removable\";\n std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), \"r\" ), &fclose );\n \/\/ Assume the file isn't removable by default\n if ( removableFile != nullptr )\n {\n char buff;\n if ( fread(&buff, sizeof(buff), 1, removableFile.get() ) != 1 )\n return buff == '1';\n return false;\n }\n#else\n (void)deviceName;\n static const std::vector<std::string> SDMountpoints = { \"\/opt\/storage\/sdcard\" };\n auto it = std::find_if( begin( SDMountpoints ), end( SDMountpoints ), [mountpoint]( const std::string& pattern ) {\n return mountpoint.length() >= pattern.length() && mountpoint.find( pattern ) == 0;\n });\n if ( it != end( SDMountpoints ) )\n {\n LOG_INFO( \"Considering mountpoint \", mountpoint, \" a removable SDCard\" );\n return true;\n }\n#endif\n return false;\n}\n\n}\n<commit_msg>fs: Device: Fix warning<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"Device.h\"\n#include \"Directory.h\"\n#include \"utils\/Filename.h\"\n#include \"logging\/Logger.h\"\n\n#include <algorithm>\n#include <cstring>\n#include <cstdio>\n#include <dirent.h>\n#include <limits.h>\n#include <mntent.h>\n#include <unistd.h>\n#include <sys\/types.h>\n\nnamespace\n{\n \/\/ Allow private ctors to be used from make_shared\n struct DeviceBuilder : public fs::Device\n {\n template <typename... Args>\n DeviceBuilder( Args&&... args ) : Device( std::forward<Args>( args )... ) {}\n };\n}\n\nnamespace fs\n{\n\nDevice::DeviceMap Device::Devices;\nDevice::MountpointMap Device::Mountpoints;\nDevice::DeviceCacheMap Device::DeviceCache;\n\nDevice::Device( const std::string& uuid, const std::string& mountpoint, bool isRemovable )\n : m_uuid( uuid )\n , m_mountpoint( mountpoint )\n , m_present( true )\n , m_removable( isRemovable )\n{\n if ( *m_mountpoint.crbegin() != '\/' )\n m_mountpoint += '\/';\n}\n\nconst std::string& Device::uuid() const\n{\n return m_uuid;\n}\n\nbool Device::isRemovable() const\n{\n return m_removable;\n}\n\nbool Device::isPresent() const\n{\n return m_present;\n}\n\nconst std::string&Device::mountpoint() const\n{\n return m_mountpoint;\n}\n\nstd::shared_ptr<IDevice> Device::fromPath( const std::string& path )\n{\n std::shared_ptr<IDevice> res;\n for ( const auto& p : DeviceCache )\n {\n if ( path.find( p.second->mountpoint() ) == 0 )\n {\n if ( res == nullptr || res->mountpoint().length() < p.second->mountpoint().length() )\n res = p.second;\n }\n }\n return res;\n}\n\nstd::shared_ptr<IDevice> Device::fromUuid( const std::string& uuid )\n{\n auto it = DeviceCache.find( uuid );\n if ( it != end( DeviceCache ) )\n return it->second;\n return nullptr;\n}\n\nbool Device::populateCache()\n{\n Devices = listDevices();\n Mountpoints = listMountpoints();\n DeviceCache = populateDeviceCache();\n return true;\n}\n\nDevice::DeviceMap Device::listDevices()\n{\n\n static const std::vector<std::string> deviceBlacklist = { \"loop\", \"dm-\" };\n const std::string devPath = \"\/dev\/disk\/by-uuid\/\";\n \/\/ Don't use fs::Directory to iterate, as it resolves the symbolic links automatically.\n \/\/ We need the link name & what it points to.\n std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( devPath.c_str() ), &closedir );\n if ( dir == nullptr )\n {\n std::stringstream err;\n err << \"Failed to open \/dev\/disk\/by-uuid: \" << strerror(errno);\n throw std::runtime_error( err.str() );\n }\n DeviceMap res;\n dirent* result = nullptr;\n\n while ( ( result = readdir( dir.get() ) ) != nullptr )\n {\n if ( strcmp( result->d_name, \".\" ) == 0 ||\n strcmp( result->d_name, \"..\" ) == 0 )\n {\n continue;\n }\n std::string path = devPath + result->d_name;\n char linkPath[PATH_MAX] = {};\n if ( readlink( path.c_str(), linkPath, PATH_MAX ) < 0 )\n {\n std::stringstream err;\n err << \"Failed to resolve uuid -> device link: \"\n << result->d_name << \" (\" << strerror(errno) << ')';\n throw std::runtime_error( err.str() );\n }\n auto deviceName = utils::file::fileName( linkPath );\n if ( std::find_if( begin( deviceBlacklist ), end( deviceBlacklist ), [&deviceName]( const std::string& pattern ) {\n return deviceName.length() >= pattern.length() && deviceName.find( pattern ) == 0;\n }) != end( deviceBlacklist ) )\n continue;\n auto uuid = result->d_name;\n LOG_INFO( \"Discovered device \", deviceName, \" -> {\", uuid, '}' );\n res[deviceName] = uuid;\n }\n return res;\n}\n\nDevice::MountpointMap Device::listMountpoints()\n{\n static const std::vector<std::string> allowedFsType = { \"vfat\", \"exfat\", \"sdcardfs\", \"fuse\",\n \"ntfs\", \"fat32\", \"ext3\", \"ext4\", \"esdfs\" };\n MountpointMap res;\n char buff[512];\n errno = 0;\n mntent* s;\n#ifndef __ANDROID__\n mntent smnt;\n FILE* f = setmntent(\"\/etc\/mtab\", \"r\");\n if ( f == nullptr )\n throw std::runtime_error( \"Failed to read \/etc\/mtab\" );\n std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &endmntent );\n while ( getmntent_r( f, &smnt, buff, sizeof(buff) ) != nullptr )\n {\n s = &smnt;\n#else\n FILE* f = fopen( \"\/proc\/mounts\", \"r\" );\n std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &fclose );\n while ( ( s = getmntent( f ) ) )\n {\n#endif\n if ( std::find( begin( allowedFsType ), end( allowedFsType ), s->mnt_type ) == end( allowedFsType ) )\n continue;\n auto deviceName = s->mnt_fsname;\n LOG_INFO( \"Discovered mountpoint \", deviceName, \" mounted on \", s->mnt_dir, \" (\", s->mnt_type, ')' );\n res[deviceName] = s->mnt_dir;\n errno = 0;\n }\n if ( errno != 0 )\n {\n LOG_ERROR( \"Failed to read mountpoints: \", strerror( errno ) );\n }\n return res;\n}\n\nDevice::DeviceCacheMap Device::populateDeviceCache()\n{\n Device::DeviceCacheMap res;\n for ( const auto& p : Mountpoints )\n {\n const auto& devicePath = p.first;\n auto deviceName = utils::file::fileName( devicePath );\n const auto& mountpoint = p.second;\n auto it = Devices.find( deviceName );\n std::string uuid;\n if ( it != end( Devices ) )\n uuid = it->second;\n else\n {\n deviceName = deviceFromDeviceMapper( devicePath );\n it = Devices.find( deviceName );\n if ( it != end( Devices ) )\n uuid = it->second;\n else\n {\n LOG_ERROR( \"Failed to resolve mountpoint \", mountpoint, \" to any known device\" );\n continue;\n }\n }\n auto removable = isRemovable( deviceName, mountpoint );\n LOG_INFO( \"Adding device to cache: {\", uuid, \"} mounted on \", mountpoint, \" Removable: \", removable );\n res[uuid] = std::make_shared<DeviceBuilder>( uuid, mountpoint, removable );\n }\n return res;\n}\n\nstd::string Device::deviceFromDeviceMapper( const std::string& devicePath )\n{\n if ( devicePath.find( \"\/dev\/mapper\" ) != 0 )\n return {};\n char linkPath[PATH_MAX];\n if ( readlink( devicePath.c_str(), linkPath, PATH_MAX ) < 0 )\n {\n std::stringstream err;\n err << \"Failed to resolve device -> mapper link: \"\n << devicePath << \" (\" << strerror(errno) << ')';\n throw std::runtime_error( err.str() );\n }\n const auto dmName = utils::file::fileName( linkPath );\n std::string dmSlavePath = \"\/sys\/block\/\" + dmName + \"\/slaves\";\n std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( dmSlavePath.c_str() ), &closedir );\n std::string res;\n if ( dir == nullptr )\n return {};\n dirent* result;\n while ( ( result = readdir( dir.get() ) ) != nullptr )\n {\n if ( strcmp( result->d_name, \".\" ) == 0 ||\n strcmp( result->d_name, \"..\" ) == 0 )\n {\n continue;\n }\n if ( res.empty() == true )\n res = result->d_name;\n else\n LOG_WARN( \"More than one slave for device mapper \", linkPath );\n }\n LOG_INFO( \"Device mapper \", dmName, \" maps to \", res );\n return res;\n}\n\nbool Device::isRemovable( const std::string& deviceName, const std::string& mountpoint )\n{\n#ifndef TIZEN\n (void)mountpoint;\n std::stringstream removableFilePath;\n removableFilePath << \"\/sys\/block\/\" << deviceName << \"\/removable\";\n std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), \"r\" ), &fclose );\n \/\/ Assume the file isn't removable by default\n if ( removableFile != nullptr )\n {\n char buff;\n if ( fread(&buff, sizeof(buff), 1, removableFile.get() ) != 1 )\n return buff == '1';\n return false;\n }\n#else\n (void)deviceName;\n static const std::vector<std::string> SDMountpoints = { \"\/opt\/storage\/sdcard\" };\n auto it = std::find_if( begin( SDMountpoints ), end( SDMountpoints ), [mountpoint]( const std::string& pattern ) {\n return mountpoint.length() >= pattern.length() && mountpoint.find( pattern ) == 0;\n });\n if ( it != end( SDMountpoints ) )\n {\n LOG_INFO( \"Considering mountpoint \", mountpoint, \" a removable SDCard\" );\n return true;\n }\n#endif\n return false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n#include <set>\n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"base\/common.h\"\n#include \"base\/random.h\"\n\nusing namespace testing;\n\n\/\/ Dependency injection\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Dependency_injection\n\nclass UdpChannel {\n public:\n virtual void Send(const char *buffer, size_t size) = 0;\n virtual bool Receive(char *buffer, size_t *size) = 0;\n};\n\nclass MockUdpChannel : public UdpChannel {\n public:\n MOCK_METHOD2(Send, void(const char *buffer, size_t size));\n MOCK_METHOD2(Receive, bool(char *buffer, size_t *size));\n};\n\nclass ReliableUdpChannel {\n public:\n ReliableUdpChannel(UdpChannel *chan) : channel_(chan), next_receive_(0) { }\n\n void Heartbeat() {\n const size_t MAX_BUFFER = 1024;\n\n char local_buffer[MAX_BUFFER];\n size_t local_size = MAX_BUFFER;\n\n if (!retry_ids_.empty()) {\n \/\/ TODO(timurrrr): throttle to avoid excessive traffic\n local_buffer[0] = 'R';\n local_buffer[1] = '0' + *retry_ids_.begin();\n local_buffer[2] = '\\0';\n channel_->Send(local_buffer, 3);\n }\n\n \/\/ TODO(timurrrr): check return value\n channel_->Receive(local_buffer, &local_size);\n\n \/\/ TODO(timurrrr): the header should be int or larger...\n CHECK(*local_buffer >= '0' && *local_buffer <= '9');\n size_t index = *local_buffer - '0';\n if (received_.find(index) != received_.end() || index < next_receive_) {\n \/\/ Hm, packet received twice?.. Drop it.\n return;\n }\n\n \/\/ TODO(timurrrr): drop packets if received_.size() is too large.\n\n char * payload = new char[local_size - 1];\n memcpy(payload, local_buffer + 1, local_size - 1);\n\n received_[index] = std::pair<size_t,char*>(local_size - 1, payload);\n }\n\n void Send(const char *buffer, size_t size) { NOT_IMPLEMENTED; }\n\n bool Receive(char *buffer, size_t *size) {\n if (received_.find(next_receive_) == received_.end())\n Heartbeat();\n\n if (received_.find(next_receive_) == received_.end()) {\n if (!received_.empty()) {\n retry_ids_.insert(next_receive_);\n }\n return false;\n }\n\n size_t data_size = received_[next_receive_].first;\n char *data = received_[next_receive_].second;\n\n if (*size < data_size)\n return false;\n\n *size = data_size;\n memcpy(buffer, data, data_size);\n next_receive_++;\n return true;\n }\n\n private:\n UdpChannel *channel_;\n size_t next_receive_;\n std::map<size_t, std::pair<size_t, char*> > received_;\n std::set<size_t> retry_ids_;\n};\n\nACTION_P(MockReceive, str) {\n size_t required_len = strlen(str) + 1;\n if (required_len > *arg1)\n return false;\n strcpy(arg0, str);\n *arg1 = required_len;\n return true;\n}\n\nTEST(ReliableUdpChannel, SimpleSequence) {\n MockUdpChannel mock;\n EXPECT_CALL(mock, Receive(_,_))\n .WillOnce(MockReceive(\"0H\"))\n .WillOnce(MockReceive(\"1E\"))\n .WillOnce(MockReceive(\"2L\"))\n .WillOnce(MockReceive(\"3L\"))\n .WillOnce(MockReceive(\"4O\"));\n\n char buff[10] = {};\n size_t size;\n ReliableUdpChannel channel(&mock);\n\n const char *expectations[] = {\"H\", \"E\", \"L\", \"L\", \"O\"};\n for (size_t i = 0; i < ARRAY_SIZE(expectations); i++) {\n size = sizeof(buff);\n ASSERT_TRUE(channel.Receive(buff, &size));\n ASSERT_STREQ(expectations[i], buff);\n }\n}\n\nTEST(ReliableUdpChannel, OnePacketLost) {\n MockUdpChannel mock;\n \/\/ Default action. See\n \/\/ http:\/\/code.google.com\/p\/googlemock\/wiki\/ForDummies#All_Expectations_Are_Sticky_(Unless_Said_Otherwise)\n EXPECT_CALL(mock, Send(StrEq(\"R1\"), Eq(3u))).Times(AnyNumber());\n\n \/\/ http:\/\/code.google.com\/p\/googlemock\/wiki\/CheatSheet#Sequences\n Sequence main, retries \/* and before retries *\/;\n EXPECT_CALL(mock, Receive(_,_))\n .InSequence(main, retries)\n .WillOnce(MockReceive(\"0H\"))\n \/\/ .WillOnce(MockReceive(\"1E\")) <-- lost!\n .WillOnce(MockReceive(\"2L\"));\n EXPECT_CALL(mock, Send(StrEq(\"R1\"), Eq(3u)))\n .InSequence(retries)\n .RetiresOnSaturation();\n EXPECT_CALL(mock, Receive(_,_))\n .InSequence(main)\n .WillOnce(MockReceive(\"3L\"))\n .WillOnce(MockReceive(\"1E\")) \/\/ <-- answer to R1\n .WillOnce(MockReceive(\"4O\"));\n\n char buff[10] = {};\n size_t size;\n ReliableUdpChannel channel(&mock);\n\n const char *expectations[] = {\"H\", \"E\", \"L\", \"L\", \"O\"};\n for (size_t i = 0; i < ARRAY_SIZE(expectations); i++) {\n size = sizeof(buff);\n int attempts = 20;\n\n while(!channel.Receive(buff, &size) && --attempts > 0)\n ;\n ASSERT_GT(attempts, 0) << \"Too many Receive attempts, aborting\";\n ASSERT_STREQ(expectations[i], buff);\n }\n}\n\n\/\/ TODO(timurrrr): random Receive==false tests\n\/\/ TODO(timurrrr): packets reordered test\n\n\/\/ TODO(timurrrr): Tests for Send()\n\nclass FakeUdpChannel : public UdpChannel {\n public:\n virtual void Send(const char *buffer, size_t size) {\n \/\/ TODO: make packet loss adjustable\n if (random_.Generate<int>() % 6 == 0)\n return;\n NOT_IMPLEMENTED;\n }\n virtual bool Receive(char *buffer, size_t *size) {\n NOT_IMPLEMENTED;\n }\n\n private:\n RandomGenerator random_;\n \/* TODO:\n std::queue<> \n *\/\n};\n\n\/\/ TODO: write a test sending 100K of data over a lossy FakeUdpChannel\n\/\/ and make sure the other end receives it all.\n<commit_msg>Plug a memory leak found by Valgrind<commit_after>\/\/ Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n#include <set>\n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"base\/common.h\"\n#include \"base\/random.h\"\n\nusing namespace testing;\n\n\/\/ Dependency injection\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Dependency_injection\n\nclass UdpChannel {\n public:\n virtual void Send(const char *buffer, size_t size) = 0;\n virtual bool Receive(char *buffer, size_t *size) = 0;\n};\n\nclass MockUdpChannel : public UdpChannel {\n public:\n MOCK_METHOD2(Send, void(const char *buffer, size_t size));\n MOCK_METHOD2(Receive, bool(char *buffer, size_t *size));\n};\n\nclass ReliableUdpChannel {\n public:\n ReliableUdpChannel(UdpChannel *chan) : channel_(chan), next_receive_(0) { }\n\n ~ReliableUdpChannel() {\n \/\/ TODO(timurrrr): free messages not taken from received_.\n }\n\n void Heartbeat() {\n const size_t MAX_BUFFER = 1024;\n\n char local_buffer[MAX_BUFFER];\n size_t local_size = MAX_BUFFER;\n\n if (!retry_ids_.empty()) {\n \/\/ TODO(timurrrr): throttle to avoid excessive traffic\n local_buffer[0] = 'R';\n local_buffer[1] = '0' + *retry_ids_.begin();\n local_buffer[2] = '\\0';\n channel_->Send(local_buffer, 3);\n }\n\n \/\/ TODO(timurrrr): check return value\n channel_->Receive(local_buffer, &local_size);\n\n \/\/ TODO(timurrrr): the header should be int or larger...\n CHECK(*local_buffer >= '0' && *local_buffer <= '9');\n size_t index = *local_buffer - '0';\n if (received_.find(index) != received_.end() || index < next_receive_) {\n \/\/ Hm, packet received twice?.. Drop it.\n return;\n }\n\n \/\/ TODO(timurrrr): drop packets if received_.size() is too large.\n\n char * payload = new char[local_size - 1];\n memcpy(payload, local_buffer + 1, local_size - 1);\n\n received_[index] = std::pair<size_t,char*>(local_size - 1, payload);\n }\n\n void Send(const char *buffer, size_t size) { NOT_IMPLEMENTED; }\n\n bool Receive(char *buffer, size_t *size) {\n if (received_.find(next_receive_) == received_.end())\n Heartbeat();\n\n if (received_.find(next_receive_) == received_.end()) {\n if (!received_.empty()) {\n retry_ids_.insert(next_receive_);\n }\n return false;\n }\n\n size_t data_size = received_[next_receive_].first;\n char *data = received_[next_receive_].second;\n\n if (*size < data_size)\n return false;\n\n *size = data_size;\n memcpy(buffer, data, data_size);\n delete [] data;\n next_receive_++;\n return true;\n }\n\n private:\n UdpChannel *channel_;\n size_t next_receive_;\n std::map<size_t, std::pair<size_t, char*> > received_;\n std::set<size_t> retry_ids_;\n};\n\nACTION_P(MockReceive, str) {\n size_t required_len = strlen(str) + 1;\n if (required_len > *arg1)\n return false;\n strcpy(arg0, str);\n *arg1 = required_len;\n return true;\n}\n\nTEST(ReliableUdpChannel, SimpleSequence) {\n MockUdpChannel mock;\n EXPECT_CALL(mock, Receive(_,_))\n .WillOnce(MockReceive(\"0H\"))\n .WillOnce(MockReceive(\"1E\"))\n .WillOnce(MockReceive(\"2L\"))\n .WillOnce(MockReceive(\"3L\"))\n .WillOnce(MockReceive(\"4O\"));\n\n char buff[10] = {};\n size_t size;\n ReliableUdpChannel channel(&mock);\n\n const char *expectations[] = {\"H\", \"E\", \"L\", \"L\", \"O\"};\n for (size_t i = 0; i < ARRAY_SIZE(expectations); i++) {\n size = sizeof(buff);\n ASSERT_TRUE(channel.Receive(buff, &size));\n ASSERT_STREQ(expectations[i], buff);\n }\n}\n\nTEST(ReliableUdpChannel, OnePacketLost) {\n MockUdpChannel mock;\n \/\/ Default action. See\n \/\/ http:\/\/code.google.com\/p\/googlemock\/wiki\/ForDummies#All_Expectations_Are_Sticky_(Unless_Said_Otherwise)\n EXPECT_CALL(mock, Send(StrEq(\"R1\"), Eq(3u))).Times(AnyNumber());\n\n \/\/ http:\/\/code.google.com\/p\/googlemock\/wiki\/CheatSheet#Sequences\n Sequence main, retries \/* and before retries *\/;\n EXPECT_CALL(mock, Receive(_,_))\n .InSequence(main, retries)\n .WillOnce(MockReceive(\"0H\"))\n \/\/ .WillOnce(MockReceive(\"1E\")) <-- lost!\n .WillOnce(MockReceive(\"2L\"));\n EXPECT_CALL(mock, Send(StrEq(\"R1\"), Eq(3u)))\n .InSequence(retries)\n .RetiresOnSaturation();\n EXPECT_CALL(mock, Receive(_,_))\n .InSequence(main)\n .WillOnce(MockReceive(\"3L\"))\n .WillOnce(MockReceive(\"1E\")) \/\/ <-- answer to R1\n .WillOnce(MockReceive(\"4O\"));\n\n char buff[10] = {};\n size_t size;\n ReliableUdpChannel channel(&mock);\n\n const char *expectations[] = {\"H\", \"E\", \"L\", \"L\", \"O\"};\n for (size_t i = 0; i < ARRAY_SIZE(expectations); i++) {\n size = sizeof(buff);\n int attempts = 20;\n\n while(!channel.Receive(buff, &size) && --attempts > 0)\n ;\n ASSERT_GT(attempts, 0) << \"Too many Receive attempts, aborting\";\n ASSERT_STREQ(expectations[i], buff);\n }\n}\n\n\/\/ TODO(timurrrr): random Receive==false tests\n\/\/ TODO(timurrrr): packets reordered test\n\n\/\/ TODO(timurrrr): Tests for Send()\n\nclass FakeUdpChannel : public UdpChannel {\n public:\n virtual void Send(const char *buffer, size_t size) {\n \/\/ TODO: make packet loss adjustable\n if (random_.Generate<int>() % 6 == 0)\n return;\n NOT_IMPLEMENTED;\n }\n virtual bool Receive(char *buffer, size_t *size) {\n NOT_IMPLEMENTED;\n }\n\n private:\n RandomGenerator random_;\n \/* TODO:\n std::queue<> \n *\/\n};\n\n\/\/ TODO: write a test sending 100K of data over a lossy FakeUdpChannel\n\/\/ and make sure the other end receives it all.\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"tabprotection.hxx\"\n#include \"tools\/debug.hxx\"\n#include \"svl\/PasswordHelper.hxx\"\n#include \"document.hxx\"\n\n#define DEBUG_TAB_PROTECTION 0\n\nusing namespace ::com::sun::star;\nusing ::com::sun::star::uno::Sequence;\nusing ::rtl::OUString;\n\n\/\/ ============================================================================\n\nbool ScPassHashHelper::needsPassHashRegen(const ScDocument& rDoc, ScPasswordHash eHash)\n{\n if (rDoc.IsDocProtected())\n {\n const ScDocProtection* p = rDoc.GetDocProtection();\n if (!p->isPasswordEmpty() && !p->hasPasswordHash(eHash))\n return true;\n }\n\n SCTAB nTabCount = rDoc.GetTableCount();\n for (SCTAB i = 0; i < nTabCount; ++i)\n {\n const ScTableProtection* p = rDoc.GetTabProtection(i);\n if (!p || !p->isProtected())\n \/\/ Sheet not protected. Skip it.\n continue;\n\n if (!p->isPasswordEmpty() && !p->hasPasswordHash(eHash))\n return true;\n }\n\n return false;\n}\n\n\/\/ ============================================================================\n\nScPassHashProtectable::~ScPassHashProtectable()\n{\n}\n\n\/\/ ============================================================================\n\nstatic sal_uInt16 lcl_getXLHashFromChar(const sal_Char* szPassword)\n{\n sal_uInt16 cchPassword = static_cast< sal_uInt16 >( strlen(szPassword) );\n sal_uInt16 wPasswordHash = 0;\n if (!cchPassword)\n return wPasswordHash;\n\n const char* pch = &szPassword[cchPassword];\n while (pch-- != szPassword)\n {\n wPasswordHash = ((wPasswordHash >> 14) & 0x01) |\n ((wPasswordHash << 1) & 0x7fff);\n wPasswordHash ^= *pch;\n }\n\n wPasswordHash = ((wPasswordHash >> 14) & 0x01) |\n ((wPasswordHash << 1) & 0x7fff);\n\n wPasswordHash ^= (0x8000 | ('N' << 8) | 'K');\n wPasswordHash ^= cchPassword;\n\n return wPasswordHash;\n}\n\nstatic Sequence<sal_Int8> lcl_getXLHash(const String& aPassText)\n{\n const sal_Char* szBuf = OUStringToOString(OUString(aPassText), RTL_TEXTENCODING_UTF8).getStr();\n sal_uInt16 nHash = lcl_getXLHashFromChar(szBuf);\n Sequence<sal_Int8> aHash(2);\n aHash[0] = (nHash >> 8) & 0xFF;\n aHash[1] = nHash & 0xFF;\n return aHash;\n}\n\nclass ScTableProtectionImpl\n{\npublic:\n static ::com::sun::star::uno::Sequence<sal_Int8> hashPassword(const String& aPassText, ScPasswordHash eHash = PASSHASH_OOO);\n\n explicit ScTableProtectionImpl(SCSIZE nOptSize);\n explicit ScTableProtectionImpl(const ScTableProtectionImpl& r);\n\n bool isProtected() const;\n bool isProtectedWithPass() const;\n void setProtected(bool bProtected);\n\n bool isPasswordEmpty() const;\n bool hasPasswordHash(ScPasswordHash eHash) const;\n void setPassword(const String& aPassText);\n ::com::sun::star::uno::Sequence<sal_Int8> getPasswordHash(ScPasswordHash eHash) const;\n void setPasswordHash(const ::com::sun::star::uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash = PASSHASH_OOO);\n bool verifyPassword(const String& aPassText) const;\n\n bool isOptionEnabled(SCSIZE nOptId) const;\n void setOption(SCSIZE nOptId, bool bEnabled);\n\nprivate:\n String maPassText;\n ::com::sun::star::uno::Sequence<sal_Int8> maPassHash;\n ::std::vector<bool> maOptions;\n bool mbEmptyPass;\n bool mbProtected;\n ScPasswordHash meHash;\n};\n\nSequence<sal_Int8> ScTableProtectionImpl::hashPassword(const String& aPassText, ScPasswordHash eHash)\n{\n Sequence<sal_Int8> aHash;\n switch (eHash)\n {\n case PASSHASH_XL:\n aHash = lcl_getXLHash(aPassText);\n break;\n case PASSHASH_OOO:\n default:\n SvPasswordHelper::GetHashPassword(aHash, aPassText);\n break;\n }\n return aHash;\n}\n\nScTableProtectionImpl::ScTableProtectionImpl(SCSIZE nOptSize) :\n maOptions(nOptSize),\n mbEmptyPass(true),\n mbProtected(false),\n meHash(PASSHASH_OOO)\n{\n}\n\nScTableProtectionImpl::ScTableProtectionImpl(const ScTableProtectionImpl& r) :\n maPassText(r.maPassText),\n maPassHash(r.maPassHash),\n maOptions(r.maOptions),\n mbEmptyPass(r.mbEmptyPass),\n mbProtected(r.mbProtected),\n meHash(r.meHash)\n{\n}\n\nbool ScTableProtectionImpl::isProtected() const\n{\n return mbProtected;\n}\n\nbool ScTableProtectionImpl::isProtectedWithPass() const\n{\n if (!mbProtected)\n return false;\n\n return maPassText.Len() || maPassHash.getLength();\n}\n\nvoid ScTableProtectionImpl::setProtected(bool bProtected)\n{\n mbProtected = bProtected;\n \/\/ We need to keep the old password even when the protection is off. So,\n \/\/ don't erase the password data here.\n}\n\nvoid ScTableProtectionImpl::setPassword(const String& aPassText)\n{\n \/\/ We can't hash it here because we don't know whether this document will\n \/\/ get saved to Excel or ODF, depending on which we will need to use a\n \/\/ different hashing algorithm. One alternative is to hash it using all\n \/\/ hash algorithms that we support, and store them all.\n\n maPassText = aPassText;\n mbEmptyPass = aPassText.Len() == 0;\n if (mbEmptyPass)\n {\n maPassHash = Sequence<sal_Int8>();\n }\n}\n\nbool ScTableProtectionImpl::isPasswordEmpty() const\n{\n return mbEmptyPass;\n}\n\nbool ScTableProtectionImpl::hasPasswordHash(ScPasswordHash eHash) const\n{\n if (mbEmptyPass)\n return true;\n\n if (maPassText.Len())\n return true;\n\n if (meHash == eHash)\n return true;\n\n return false;\n}\n\nSequence<sal_Int8> ScTableProtectionImpl::getPasswordHash(ScPasswordHash eHash) const\n{\n if (mbEmptyPass)\n \/\/ Flaged as empty.\n return Sequence<sal_Int8>();\n\n if (maPassText.Len())\n \/\/ Cleartext password exists. Hash it.\n return hashPassword(maPassText, eHash);\n\n if (meHash == eHash)\n \/\/ Stored hash exists.\n return maPassHash;\n\n \/\/ Failed to find a matching hash.\n return Sequence<sal_Int8>();\n}\n\nvoid ScTableProtectionImpl::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n sal_Int32 nLen = aPassword.getLength();\n mbEmptyPass = nLen <= 0 ? true : false;\n meHash = eHash;\n maPassHash = aPassword;\n\n#if DEBUG_TAB_PROTECTION\n for (sal_Int32 i = 0; i < nLen; ++i)\n printf(\"%2.2X \", static_cast<sal_uInt8>(aPassword[i]));\n printf(\"\\n\");\n#endif\n}\n\nbool ScTableProtectionImpl::verifyPassword(const String& aPassText) const\n{\n#if DEBUG_TAB_PROTECTION\n fprintf(stdout, \"ScTableProtectionImpl::verifyPassword: input = '%s'\\n\",\n OUStringToOString(rtl::OUString(aPassText), RTL_TEXTENCODING_UTF8).getStr());\n#endif\n\n if (mbEmptyPass)\n return aPassText.Len() == 0;\n\n if (maPassText.Len())\n \/\/ Clear text password exists, and this one takes precedence.\n return aPassText.Equals(maPassText);\n\n Sequence<sal_Int8> aHash = hashPassword(aPassText, meHash);\n\n#if DEBUG_TAB_PROTECTION\n fprintf(stdout, \"ScTableProtectionImpl::verifyPassword: hash = \");\n for (sal_Int32 i = 0; i < aHash.getLength(); ++i)\n printf(\"%2.2X \", static_cast<sal_uInt8>(aHash[i]));\n printf(\"\\n\");\n#endif\n\n return aHash == maPassHash;\n}\n\nbool ScTableProtectionImpl::isOptionEnabled(SCSIZE nOptId) const\n{\n if ( maOptions.size() <= static_cast<size_t>(nOptId) )\n {\n DBG_ERROR(\"ScTableProtectionImpl::isOptionEnabled: wrong size\");\n return false;\n }\n\n return maOptions[nOptId];\n}\n\nvoid ScTableProtectionImpl::setOption(SCSIZE nOptId, bool bEnabled)\n{\n if ( maOptions.size() <= static_cast<size_t>(nOptId) )\n {\n DBG_ERROR(\"ScTableProtectionImpl::setOption: wrong size\");\n return;\n }\n\n maOptions[nOptId] = bEnabled;\n}\n\n\/\/ ============================================================================\n\nScDocProtection::ScDocProtection() :\n mpImpl(new ScTableProtectionImpl(static_cast<SCSIZE>(ScDocProtection::NONE)))\n{\n}\n\nScDocProtection::ScDocProtection(const ScDocProtection& r) :\n ScPassHashProtectable(),\n mpImpl(new ScTableProtectionImpl(*r.mpImpl))\n{\n}\n\nScDocProtection::~ScDocProtection()\n{\n}\n\nbool ScDocProtection::isProtected() const\n{\n return mpImpl->isProtected();\n}\n\nbool ScDocProtection::isProtectedWithPass() const\n{\n return mpImpl->isProtectedWithPass();\n}\n\nvoid ScDocProtection::setProtected(bool bProtected)\n{\n mpImpl->setProtected(bProtected);\n\n \/\/ Currently Calc doesn't support document protection options. So, let's\n \/\/ assume that when the document is protected, its structure is protected.\n \/\/ We need to do this for Excel export.\n mpImpl->setOption(ScDocProtection::STRUCTURE, bProtected);\n}\n\nbool ScDocProtection::isPasswordEmpty() const\n{\n return mpImpl->isPasswordEmpty();\n}\n\nbool ScDocProtection::hasPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->hasPasswordHash(eHash);\n}\n\nvoid ScDocProtection::setPassword(const String& aPassText)\n{\n mpImpl->setPassword(aPassText);\n}\n\nuno::Sequence<sal_Int8> ScDocProtection::getPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->getPasswordHash(eHash);\n}\n\nvoid ScDocProtection::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n mpImpl->setPasswordHash(aPassword, eHash);\n}\n\nbool ScDocProtection::verifyPassword(const String& aPassText) const\n{\n return mpImpl->verifyPassword(aPassText);\n}\n\nbool ScDocProtection::isOptionEnabled(Option eOption) const\n{\n return mpImpl->isOptionEnabled(eOption);\n}\n\nvoid ScDocProtection::setOption(Option eOption, bool bEnabled)\n{\n mpImpl->setOption(eOption, bEnabled);\n}\n\n\/\/ ============================================================================\n\nScTableProtection::ScTableProtection() :\n mpImpl(new ScTableProtectionImpl(static_cast<SCSIZE>(ScTableProtection::NONE)))\n{\n \/\/ Set default values for the options.\n mpImpl->setOption(SELECT_LOCKED_CELLS, true);\n mpImpl->setOption(SELECT_UNLOCKED_CELLS, true);\n}\n\nScTableProtection::ScTableProtection(const ScTableProtection& r) :\n ScPassHashProtectable(),\n mpImpl(new ScTableProtectionImpl(*r.mpImpl))\n{\n}\n\nScTableProtection::~ScTableProtection()\n{\n}\n\nbool ScTableProtection::isProtected() const\n{\n return mpImpl->isProtected();\n}\n\nbool ScTableProtection::isProtectedWithPass() const\n{\n return mpImpl->isProtectedWithPass();\n}\n\nvoid ScTableProtection::setProtected(bool bProtected)\n{\n mpImpl->setProtected(bProtected);\n}\n\nbool ScTableProtection::isPasswordEmpty() const\n{\n return mpImpl->isPasswordEmpty();\n}\n\nbool ScTableProtection::hasPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->hasPasswordHash(eHash);\n}\n\nvoid ScTableProtection::setPassword(const String& aPassText)\n{\n mpImpl->setPassword(aPassText);\n}\n\nSequence<sal_Int8> ScTableProtection::getPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->getPasswordHash(eHash);\n}\n\nvoid ScTableProtection::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n mpImpl->setPasswordHash(aPassword, eHash);\n}\n\nbool ScTableProtection::verifyPassword(const String& aPassText) const\n{\n return mpImpl->verifyPassword(aPassText);\n}\n\nbool ScTableProtection::isOptionEnabled(Option eOption) const\n{\n return mpImpl->isOptionEnabled(eOption);\n}\n\nvoid ScTableProtection::setOption(Option eOption, bool bEnabled)\n{\n mpImpl->setOption(eOption, bEnabled);\n}\n\n<commit_msg>tl78: #i110383# support password to modify<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"tabprotection.hxx\"\n#include \"tools\/debug.hxx\"\n#include \"svl\/PasswordHelper.hxx\"\n#include <comphelper\/docpasswordhelper.hxx>\n#include \"document.hxx\"\n\n#define DEBUG_TAB_PROTECTION 0\n\nusing namespace ::com::sun::star;\nusing ::com::sun::star::uno::Sequence;\nusing ::rtl::OUString;\n\n\/\/ ============================================================================\n\nbool ScPassHashHelper::needsPassHashRegen(const ScDocument& rDoc, ScPasswordHash eHash)\n{\n if (rDoc.IsDocProtected())\n {\n const ScDocProtection* p = rDoc.GetDocProtection();\n if (!p->isPasswordEmpty() && !p->hasPasswordHash(eHash))\n return true;\n }\n\n SCTAB nTabCount = rDoc.GetTableCount();\n for (SCTAB i = 0; i < nTabCount; ++i)\n {\n const ScTableProtection* p = rDoc.GetTabProtection(i);\n if (!p || !p->isProtected())\n \/\/ Sheet not protected. Skip it.\n continue;\n\n if (!p->isPasswordEmpty() && !p->hasPasswordHash(eHash))\n return true;\n }\n\n return false;\n}\n\n\/\/ ============================================================================\n\nScPassHashProtectable::~ScPassHashProtectable()\n{\n}\n\n\/\/ ============================================================================\n\nclass ScTableProtectionImpl\n{\npublic:\n static ::com::sun::star::uno::Sequence<sal_Int8> hashPassword(const String& aPassText, ScPasswordHash eHash = PASSHASH_OOO);\n\n explicit ScTableProtectionImpl(SCSIZE nOptSize);\n explicit ScTableProtectionImpl(const ScTableProtectionImpl& r);\n\n bool isProtected() const;\n bool isProtectedWithPass() const;\n void setProtected(bool bProtected);\n\n bool isPasswordEmpty() const;\n bool hasPasswordHash(ScPasswordHash eHash) const;\n void setPassword(const String& aPassText);\n ::com::sun::star::uno::Sequence<sal_Int8> getPasswordHash(ScPasswordHash eHash) const;\n void setPasswordHash(const ::com::sun::star::uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash = PASSHASH_OOO);\n bool verifyPassword(const String& aPassText) const;\n\n bool isOptionEnabled(SCSIZE nOptId) const;\n void setOption(SCSIZE nOptId, bool bEnabled);\n\nprivate:\n String maPassText;\n ::com::sun::star::uno::Sequence<sal_Int8> maPassHash;\n ::std::vector<bool> maOptions;\n bool mbEmptyPass;\n bool mbProtected;\n ScPasswordHash meHash;\n};\n\nSequence<sal_Int8> ScTableProtectionImpl::hashPassword(const String& aPassText, ScPasswordHash eHash)\n{\n Sequence<sal_Int8> aHash;\n switch (eHash)\n {\n case PASSHASH_XL:\n aHash = ::comphelper::DocPasswordHelper::GetXLHashAsSequence( aPassText, RTL_TEXTENCODING_UTF8 );\n break;\n case PASSHASH_OOO:\n default:\n SvPasswordHelper::GetHashPassword(aHash, aPassText);\n break;\n }\n return aHash;\n}\n\nScTableProtectionImpl::ScTableProtectionImpl(SCSIZE nOptSize) :\n maOptions(nOptSize),\n mbEmptyPass(true),\n mbProtected(false),\n meHash(PASSHASH_OOO)\n{\n}\n\nScTableProtectionImpl::ScTableProtectionImpl(const ScTableProtectionImpl& r) :\n maPassText(r.maPassText),\n maPassHash(r.maPassHash),\n maOptions(r.maOptions),\n mbEmptyPass(r.mbEmptyPass),\n mbProtected(r.mbProtected),\n meHash(r.meHash)\n{\n}\n\nbool ScTableProtectionImpl::isProtected() const\n{\n return mbProtected;\n}\n\nbool ScTableProtectionImpl::isProtectedWithPass() const\n{\n if (!mbProtected)\n return false;\n\n return maPassText.Len() || maPassHash.getLength();\n}\n\nvoid ScTableProtectionImpl::setProtected(bool bProtected)\n{\n mbProtected = bProtected;\n \/\/ We need to keep the old password even when the protection is off. So,\n \/\/ don't erase the password data here.\n}\n\nvoid ScTableProtectionImpl::setPassword(const String& aPassText)\n{\n \/\/ We can't hash it here because we don't know whether this document will\n \/\/ get saved to Excel or ODF, depending on which we will need to use a\n \/\/ different hashing algorithm. One alternative is to hash it using all\n \/\/ hash algorithms that we support, and store them all.\n\n maPassText = aPassText;\n mbEmptyPass = aPassText.Len() == 0;\n if (mbEmptyPass)\n {\n maPassHash = Sequence<sal_Int8>();\n }\n}\n\nbool ScTableProtectionImpl::isPasswordEmpty() const\n{\n return mbEmptyPass;\n}\n\nbool ScTableProtectionImpl::hasPasswordHash(ScPasswordHash eHash) const\n{\n if (mbEmptyPass)\n return true;\n\n if (maPassText.Len())\n return true;\n\n if (meHash == eHash)\n return true;\n\n return false;\n}\n\nSequence<sal_Int8> ScTableProtectionImpl::getPasswordHash(ScPasswordHash eHash) const\n{\n if (mbEmptyPass)\n \/\/ Flaged as empty.\n return Sequence<sal_Int8>();\n\n if (maPassText.Len())\n \/\/ Cleartext password exists. Hash it.\n return hashPassword(maPassText, eHash);\n\n if (meHash == eHash)\n \/\/ Stored hash exists.\n return maPassHash;\n\n \/\/ Failed to find a matching hash.\n return Sequence<sal_Int8>();\n}\n\nvoid ScTableProtectionImpl::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n sal_Int32 nLen = aPassword.getLength();\n mbEmptyPass = nLen <= 0 ? true : false;\n meHash = eHash;\n maPassHash = aPassword;\n\n#if DEBUG_TAB_PROTECTION\n for (sal_Int32 i = 0; i < nLen; ++i)\n printf(\"%2.2X \", static_cast<sal_uInt8>(aPassword[i]));\n printf(\"\\n\");\n#endif\n}\n\nbool ScTableProtectionImpl::verifyPassword(const String& aPassText) const\n{\n#if DEBUG_TAB_PROTECTION\n fprintf(stdout, \"ScTableProtectionImpl::verifyPassword: input = '%s'\\n\",\n OUStringToOString(rtl::OUString(aPassText), RTL_TEXTENCODING_UTF8).getStr());\n#endif\n\n if (mbEmptyPass)\n return aPassText.Len() == 0;\n\n if (maPassText.Len())\n \/\/ Clear text password exists, and this one takes precedence.\n return aPassText.Equals(maPassText);\n\n Sequence<sal_Int8> aHash = hashPassword(aPassText, meHash);\n\n#if DEBUG_TAB_PROTECTION\n fprintf(stdout, \"ScTableProtectionImpl::verifyPassword: hash = \");\n for (sal_Int32 i = 0; i < aHash.getLength(); ++i)\n printf(\"%2.2X \", static_cast<sal_uInt8>(aHash[i]));\n printf(\"\\n\");\n#endif\n\n return aHash == maPassHash;\n}\n\nbool ScTableProtectionImpl::isOptionEnabled(SCSIZE nOptId) const\n{\n if ( maOptions.size() <= static_cast<size_t>(nOptId) )\n {\n DBG_ERROR(\"ScTableProtectionImpl::isOptionEnabled: wrong size\");\n return false;\n }\n\n return maOptions[nOptId];\n}\n\nvoid ScTableProtectionImpl::setOption(SCSIZE nOptId, bool bEnabled)\n{\n if ( maOptions.size() <= static_cast<size_t>(nOptId) )\n {\n DBG_ERROR(\"ScTableProtectionImpl::setOption: wrong size\");\n return;\n }\n\n maOptions[nOptId] = bEnabled;\n}\n\n\/\/ ============================================================================\n\nScDocProtection::ScDocProtection() :\n mpImpl(new ScTableProtectionImpl(static_cast<SCSIZE>(ScDocProtection::NONE)))\n{\n}\n\nScDocProtection::ScDocProtection(const ScDocProtection& r) :\n ScPassHashProtectable(),\n mpImpl(new ScTableProtectionImpl(*r.mpImpl))\n{\n}\n\nScDocProtection::~ScDocProtection()\n{\n}\n\nbool ScDocProtection::isProtected() const\n{\n return mpImpl->isProtected();\n}\n\nbool ScDocProtection::isProtectedWithPass() const\n{\n return mpImpl->isProtectedWithPass();\n}\n\nvoid ScDocProtection::setProtected(bool bProtected)\n{\n mpImpl->setProtected(bProtected);\n\n \/\/ Currently Calc doesn't support document protection options. So, let's\n \/\/ assume that when the document is protected, its structure is protected.\n \/\/ We need to do this for Excel export.\n mpImpl->setOption(ScDocProtection::STRUCTURE, bProtected);\n}\n\nbool ScDocProtection::isPasswordEmpty() const\n{\n return mpImpl->isPasswordEmpty();\n}\n\nbool ScDocProtection::hasPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->hasPasswordHash(eHash);\n}\n\nvoid ScDocProtection::setPassword(const String& aPassText)\n{\n mpImpl->setPassword(aPassText);\n}\n\nuno::Sequence<sal_Int8> ScDocProtection::getPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->getPasswordHash(eHash);\n}\n\nvoid ScDocProtection::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n mpImpl->setPasswordHash(aPassword, eHash);\n}\n\nbool ScDocProtection::verifyPassword(const String& aPassText) const\n{\n return mpImpl->verifyPassword(aPassText);\n}\n\nbool ScDocProtection::isOptionEnabled(Option eOption) const\n{\n return mpImpl->isOptionEnabled(eOption);\n}\n\nvoid ScDocProtection::setOption(Option eOption, bool bEnabled)\n{\n mpImpl->setOption(eOption, bEnabled);\n}\n\n\/\/ ============================================================================\n\nScTableProtection::ScTableProtection() :\n mpImpl(new ScTableProtectionImpl(static_cast<SCSIZE>(ScTableProtection::NONE)))\n{\n \/\/ Set default values for the options.\n mpImpl->setOption(SELECT_LOCKED_CELLS, true);\n mpImpl->setOption(SELECT_UNLOCKED_CELLS, true);\n}\n\nScTableProtection::ScTableProtection(const ScTableProtection& r) :\n ScPassHashProtectable(),\n mpImpl(new ScTableProtectionImpl(*r.mpImpl))\n{\n}\n\nScTableProtection::~ScTableProtection()\n{\n}\n\nbool ScTableProtection::isProtected() const\n{\n return mpImpl->isProtected();\n}\n\nbool ScTableProtection::isProtectedWithPass() const\n{\n return mpImpl->isProtectedWithPass();\n}\n\nvoid ScTableProtection::setProtected(bool bProtected)\n{\n mpImpl->setProtected(bProtected);\n}\n\nbool ScTableProtection::isPasswordEmpty() const\n{\n return mpImpl->isPasswordEmpty();\n}\n\nbool ScTableProtection::hasPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->hasPasswordHash(eHash);\n}\n\nvoid ScTableProtection::setPassword(const String& aPassText)\n{\n mpImpl->setPassword(aPassText);\n}\n\nSequence<sal_Int8> ScTableProtection::getPasswordHash(ScPasswordHash eHash) const\n{\n return mpImpl->getPasswordHash(eHash);\n}\n\nvoid ScTableProtection::setPasswordHash(const uno::Sequence<sal_Int8>& aPassword, ScPasswordHash eHash)\n{\n mpImpl->setPasswordHash(aPassword, eHash);\n}\n\nbool ScTableProtection::verifyPassword(const String& aPassText) const\n{\n return mpImpl->verifyPassword(aPassText);\n}\n\nbool ScTableProtection::isOptionEnabled(Option eOption) const\n{\n return mpImpl->isOptionEnabled(eOption);\n}\n\nvoid ScTableProtection::setOption(Option eOption, bool bEnabled)\n{\n mpImpl->setOption(eOption, bEnabled);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkTestingMacros.h>\n#include <mitkTestFixture.h>\n#include \"mitkIOUtil.h\"\n#include <cmath>\n\n#include <mitkGIFLocalIntensity.h>\n\nclass mitkGIFLocalIntensityTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFLocalIntensityTestSuite);\n\n MITK_TEST(ImageDescription_PhantomTest);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\tmitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n\tmitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n\tmitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n\tmitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest()\n {\n mitk::GIFLocalIntensity::Pointer featureCalculator = mitk::GIFLocalIntensity::New();\n\n featureCalculator->SetUseBinsize(true);\n featureCalculator->SetBinsize(3);\n featureCalculator->SetUseMinimumIntensity(true);\n featureCalculator->SetUseMaximumIntensity(true);\n featureCalculator->SetMinimumIntensity(1);\n featureCalculator->SetMaximumIntensity(6);\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 44 features.\", std::size_t(2), featureList.size());\n\n \/\/ These values are obtained by a run of the filter.\n \/\/ The might be wrong!\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Local Intensity Peak with Large IBSI Phantom Image\", 2.6, results[\"Local Intensity::Local Intensity Peak\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Global Intensity Peak with Large IBSI Phantom Image\", 3.1, results[\"Local Intensity::Global Intensity Peak\"], 0.1);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFLocalIntensity )<commit_msg>Added additional test with Large Phantom and change of Range.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkTestingMacros.h>\n#include <mitkTestFixture.h>\n#include \"mitkIOUtil.h\"\n#include <cmath>\n\n#include <mitkGIFLocalIntensity.h>\n\nclass mitkGIFLocalIntensityTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFLocalIntensityTestSuite);\n\n MITK_TEST(ImageDescription_PhantomTest_Small);\n MITK_TEST(ImageDescription_PhantomTest_Large);\n MITK_TEST(ImageDescription_PhantomTest_Large_RangeChanged);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\tmitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n\tmitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n\tmitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n\tmitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest_Small()\n {\n mitk::GIFLocalIntensity::Pointer featureCalculator = mitk::GIFLocalIntensity::New();\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Small, m_IBSI_Phantom_Mask_Small);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 2 features.\", std::size_t(2), featureList.size());\n\n \/\/ These values are obtained in cooperation with IBSI\n \/\/ Reported with an accuracy of 0.1\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Local Intensity Peak with Large IBSI Phantom Image\", 2.6, results[\"Local Intensity::Local Intensity Peak\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Global Intensity Peak with Large IBSI Phantom Image\", 3.1, results[\"Local Intensity::Global Intensity Peak\"], 0.1);\n }\n\n void ImageDescription_PhantomTest_Large()\n {\n mitk::GIFLocalIntensity::Pointer featureCalculator = mitk::GIFLocalIntensity::New();\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 2 features.\", std::size_t(2), featureList.size());\n\n \/\/ These values are obtained by running the tool\n \/\/ They might be wrong\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Local Intensity Peak with Large IBSI Phantom Image\", 1.43, results[\"Local Intensity::Local Intensity Peak\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Global Intensity Peak with Large IBSI Phantom Image\", 1.43, results[\"Local Intensity::Global Intensity Peak\"], 0.01);\n }\n\n void ImageDescription_PhantomTest_Large_RangeChanged()\n {\n mitk::GIFLocalIntensity::Pointer featureCalculator = mitk::GIFLocalIntensity::New();\n\n featureCalculator->SetRange(1);\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 2 features.\", std::size_t(2), featureList.size());\n\n \/\/ These values are obtained by running the tool\n \/\/ They might be wrong\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Local Intensity Peak with Large IBSI Phantom Image\", 2.81, results[\"Local Intensity::Local Intensity Peak\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Local Intensity::Global Intensity Peak with Large IBSI Phantom Image\", 3.15, results[\"Local Intensity::Global Intensity Peak\"], 0.01);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFLocalIntensity )<|endoftext|>"} {"text":"<commit_before>#include \"HCUBE_Defines.h\"\n\n#include \"Experiments\/HCUBE_AtariExperiment.h\"\n#include <boost\/foreach.hpp>\n\nusing namespace NEAT;\n\nenum GamePositionValue {\n EMPTY,\n CHICKEN,\n VEHICLE\n};\n\nnamespace HCUBE\n{\n AtariExperiment::AtariExperiment(string _experimentName,int _threadID):\n Experiment(_experimentName,_threadID),\n screen_width(5), screen_height(19)\n {\n layerInfo = NEAT::LayeredSubstrateInfo();\n layerInfo.layerSizes.push_back(Vector2<int>(screen_width,screen_height));\n layerInfo.layerIsInput.push_back(true);\n layerInfo.layerLocations.push_back(Vector3<float>(0,0,0));\n layerInfo.layerNames.push_back(\"Input\");\n\n layerInfo.layerSizes.push_back(Vector2<int>(screen_width,screen_height));\n layerInfo.layerIsInput.push_back(false);\n layerInfo.layerLocations.push_back(Vector3<float>(0,4,0));\n layerInfo.layerNames.push_back(\"Output\");\n\n layerInfo.layerAdjacencyList.push_back(std::pair<string,string>(\"Input\",\"Output\"));\n\n layerInfo.normalize = true;\n layerInfo.useOldOutputNames = false;\n layerInfo.layerValidSizes = layerInfo.layerSizes;\n\n substrate = NEAT::LayeredSubstrate<float>();\n substrate.setLayerInfo(layerInfo);\n }\n\n NEAT::GeneticPopulation* AtariExperiment::createInitialPopulation(int populationSize) {\n GeneticPopulation *population = new GeneticPopulation();\n vector<GeneticNodeGene> genes;\n\n genes.push_back(GeneticNodeGene(\"Bias\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"X1\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"X2\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Y1\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Y2\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Output_Input_Output\",\"NetworkOutputNode\",1,false,ACTIVATION_FUNCTION_SIGMOID));\n\n for (int a=0;a<populationSize;a++) {\n shared_ptr<GeneticIndividual> individual(new GeneticIndividual(genes,true,1.0));\n for (int b=0;b<10;b++) {\n individual->testMutate();\n }\n population->addIndividual(individual);\n }\n\n cout << \"Finished creating population\\n\";\n return population;\n }\n\n void AtariExperiment::populateSubstrate(shared_ptr<NEAT::GeneticIndividual> individual) {\n if (currentSubstrateIndividual == individual)\n return;\n\n currentSubstrateIndividual = individual;\n substrate.populateSubstrate(individual);\n }\n\n void AtariExperiment::processGroup(shared_ptr<NEAT::GeneticGeneration> generation)\n {\n static int i=0;\n \n shared_ptr<NEAT::GeneticIndividual> individual = group.front();\n individual->setFitness(10);\n\n \/\/ Print the individual\n \/\/individual->print();\n\n populateSubstrate(individual);\n\n runAtariEpisode(individual);\n }\n\n void AtariExperiment::runAtariEpisode(shared_ptr<NEAT::GeneticIndividual> individual) {\n GamePositionValue gameState[screen_width][screen_height];\n\n int chic_x = screen_width\/2, chic_y = screen_height-1;\n float total_reward = 0.0;\n \n \/\/ Initialize Game\n for (int x=0;x<screen_width;x++) {\n for (int y=0;y<screen_height;y++) {\n gameState[x][y] = EMPTY;\n }\n }\n\n \/\/ Initialize Chicken\n gameState[chic_x][chic_y] = CHICKEN;\n\n \/\/ Initialize Cars\n for (int y=2; y<=screen_height-2; y+=2) {\n if (y < screen_height\/2)\n gameState[screen_width-1][y] = VEHICLE;\n else\n gameState[0][y] = VEHICLE;\n }\n\n \/\/ Run simulation for t timesteps\n int num_timesteps = 10000;\n for (int t=0; t<num_timesteps; t++) {\n substrate.getNetwork()->reinitialize();\n substrate.getNetwork()->dummyActivation();\n\n \/\/ Print Game Screen\n \/\/ if (threadID == 0) {\n \/\/ printf(\"Timestep %d Individual Species ID %d\\n\",t,individual->getSpeciesID());\n \/\/ for (int x=0; x<screen_width+2; ++x)\n \/\/ printf(\"-\");\n \/\/ printf(\"\\n\");\n \/\/ for (int y=0; y<screen_height; ++y) {\n \/\/ for (int x=0; x<screen_width; ++x) {\n \/\/ if (x==0) printf(\"|\");\n \/\/ if (gameState[x][y] == CHICKEN) {\n \/\/ printf(\"x\");\n \/\/ } else if (gameState[x][y] == VEHICLE) {\n \/\/ printf(\"o\");\n \/\/ } else {\n \/\/ printf(\" \");\n \/\/ }\n \/\/ }\n \/\/ printf(\"|\\n\");\n \/\/ }\n \/\/ for (int x=0; x<screen_width+2; ++x)\n \/\/ printf(\"-\");\n \/\/ printf(\"\\n\");\n \/\/ cin.get();\n \/\/ }\n\n \/\/ Set substrate values\n for (int x=0; x<screen_width; ++x) {\n for (int y=0; y<screen_height; ++y) {\n if (gameState[x][y] == CHICKEN) {\n substrate.setValue((Node(x,y,0)), 1.0);\n } else if (gameState[x][y] == VEHICLE) {\n \/\/ Highlight regions that the car is going to move into\n \/\/ for (int x2=max(0,x-2); x2<min(screen_width,x+3); x2++) {\n \/\/ if (gameState[x2][y] == CHICKEN) continue;\n \/\/ substrate.setValue((Node(x2,y,0)), -.5);\n \/\/ }\n substrate.setValue((Node(x,y,0)), -1.0);\n } else {\n substrate.setValue((Node(x,y,0)), 0.0); \n }\n }\n }\n\n substrate.getNetwork()->update();\n\n float chicken_val = substrate.getValue((Node(chic_x,chic_y,1)));\n float down_val = (chic_y >= screen_height-1) ? chicken_val : substrate.getValue((Node(chic_x,chic_y+1,1)));\n float up_val = (chic_y <= 0) ? chicken_val : substrate.getValue((Node(chic_x,chic_y-1,1)));\n\n int action;\n if (chicken_val >= up_val) {\n if (chicken_val >= down_val) {\n action = 0;\n } else {\n action = 1;\n }\n } else {\n if (up_val >= down_val) {\n action = -1;\n } else {\n action = 1;\n }\n }\n \/\/action = -1;\n \n \/\/ Update game state with action\n bool collision = false;\n\n \/\/ Move cars\n for (int y=0; y<screen_height; ++y) {\n for (int x=0; x<screen_width; ++x) {\n if (gameState[x][y] == VEHICLE) {\n int velocity = rand()%2;\n int carx;\n if (y < screen_height\/2) { \/\/ Top half cars go left\n if (x == 0) \/\/ reset car if it has reached the end\n carx = screen_width-1; \n else\n carx = max(0, x-velocity);\n } else {\n if (x == screen_width-1)\n carx = 0;\n else\n carx = min(screen_width-1, x+velocity);\n }\n gameState[x][y] = EMPTY;\n gameState[carx][y] = VEHICLE;\n break;\n }\n }\n }\n\n \/\/ Move chicken\n if (gameState[chic_x][chic_y] != VEHICLE) gameState[chic_x][chic_y] = EMPTY;\n if (gameState[chic_x][chic_y+action] != VEHICLE) gameState[chic_x][chic_y+action] = CHICKEN;\n else collision = true;\n chic_y += action;\n\n \/\/ Compute reward\n if (chic_y == 0 || collision) {\n if (collision)\n total_reward = max(0.0f,total_reward-1.0f);\n if (chic_y == 0)\n total_reward += 100.0;\n \/\/ Reset the sim\n if (gameState[chic_x][chic_y] != VEHICLE) gameState[chic_x][chic_y] = EMPTY;\n gameState[chic_x][screen_height-1] = CHICKEN;\n chic_y = screen_height-1;\n }\n }\n \/\/cout << \"Got total reward: \" << total_reward << endl;\n individual->reward(total_reward);\n }\n\n void AtariExperiment::preprocessIndividual(shared_ptr<NEAT::GeneticGeneration> generation,\n shared_ptr<NEAT::GeneticIndividual> individual) {\n if (individual->getNode(\"X1\") == NULL) {\n printf(\"Got blank individual\\n\");\n }\n }\n\n void AtariExperiment::processIndividualPostHoc(shared_ptr<NEAT::GeneticIndividual> individual)\n {\n \/\/ NEAT::FastNetwork<float> network = individual->spawnFastPhenotypeStack<float>();\n\n \/\/ \/\/TODO Put in userdata\n\n \/\/ double fitness = 10.0;\n \/\/ double maxFitness = 10.0;\n\n \/\/ for (int x1=0;x1<2;x1++)\n \/\/ {\n \/\/ for (int x2=0;x2<2;x2++)\n \/\/ {\n \/\/ network.reinitialize();\n\n \/\/ network.setValue(\"X1\",x1);\n \/\/ network.setValue(\"X2\",x2);\n \/\/ network.setValue(\"Bias\",0.3f);\n\n \/\/ network.update();\n\n \/\/ double value = network.getValue(\"Output\");\n\n \/\/ double expectedValue = (double)(x1 ^ x2);\n\n \/\/ fitness += (5000*(2-fabs(value-expectedValue)));\n \/\/ maxFitness += 5000*2;\n \/\/ }\n \/\/ }\n\n \/\/ cout << \"POST HOC ANALYSIS: \" << fitness << \"\/\" << maxFitness << endl;\n }\n\n Experiment* AtariExperiment::clone()\n {\n AtariExperiment* experiment = new AtariExperiment(*this);\n\n return experiment;\n }\n}\n<commit_msg>Changed to episodic view.<commit_after>#include \"HCUBE_Defines.h\"\n\n#include \"Experiments\/HCUBE_AtariExperiment.h\"\n#include <boost\/foreach.hpp>\n\nusing namespace NEAT;\n\nenum GamePositionValue {\n EMPTY,\n CHICKEN,\n VEHICLE\n};\n\nnamespace HCUBE\n{\n AtariExperiment::AtariExperiment(string _experimentName,int _threadID):\n Experiment(_experimentName,_threadID),\n screen_width(5), screen_height(19)\n {\n layerInfo = NEAT::LayeredSubstrateInfo();\n layerInfo.layerSizes.push_back(Vector2<int>(screen_width,screen_height));\n layerInfo.layerIsInput.push_back(true);\n layerInfo.layerLocations.push_back(Vector3<float>(0,0,0));\n layerInfo.layerNames.push_back(\"Input\");\n\n layerInfo.layerSizes.push_back(Vector2<int>(screen_width,screen_height));\n layerInfo.layerIsInput.push_back(false);\n layerInfo.layerLocations.push_back(Vector3<float>(0,4,0));\n layerInfo.layerNames.push_back(\"Output\");\n\n layerInfo.layerAdjacencyList.push_back(std::pair<string,string>(\"Input\",\"Output\"));\n\n layerInfo.normalize = true;\n layerInfo.useOldOutputNames = false;\n layerInfo.layerValidSizes = layerInfo.layerSizes;\n\n substrate = NEAT::LayeredSubstrate<float>();\n substrate.setLayerInfo(layerInfo);\n }\n\n NEAT::GeneticPopulation* AtariExperiment::createInitialPopulation(int populationSize) {\n GeneticPopulation *population = new GeneticPopulation();\n vector<GeneticNodeGene> genes;\n\n genes.push_back(GeneticNodeGene(\"Bias\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"X1\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"X2\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Y1\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Y2\",\"NetworkSensor\",0,false));\n genes.push_back(GeneticNodeGene(\"Output_Input_Output\",\"NetworkOutputNode\",1,false,ACTIVATION_FUNCTION_SIGMOID));\n\n for (int a=0;a<populationSize;a++) {\n shared_ptr<GeneticIndividual> individual(new GeneticIndividual(genes,true,1.0));\n for (int b=0;b<10;b++) {\n individual->testMutate();\n }\n population->addIndividual(individual);\n }\n\n cout << \"Finished creating population\\n\";\n return population;\n }\n\n void AtariExperiment::populateSubstrate(shared_ptr<NEAT::GeneticIndividual> individual) {\n if (currentSubstrateIndividual == individual)\n return;\n\n currentSubstrateIndividual = individual;\n substrate.populateSubstrate(individual);\n }\n\n void AtariExperiment::processGroup(shared_ptr<NEAT::GeneticGeneration> generation)\n {\n static int i=0;\n \n shared_ptr<NEAT::GeneticIndividual> individual = group.front();\n individual->setFitness(10);\n\n \/\/ Print the individual\n \/\/individual->print();\n\n populateSubstrate(individual);\n\n runAtariEpisode(individual);\n }\n\n void AtariExperiment::runAtariEpisode(shared_ptr<NEAT::GeneticIndividual> individual) {\n GamePositionValue gameState[screen_width][screen_height];\n\n int chic_x = screen_width\/2, chic_y = screen_height-1;\n float total_reward = 0.0;\n \n \/\/ Initialize Game\n for (int x=0;x<screen_width;x++) {\n for (int y=0;y<screen_height;y++) {\n gameState[x][y] = EMPTY;\n }\n }\n\n \/\/ Initialize Chicken\n gameState[chic_x][chic_y] = CHICKEN;\n\n \/\/ Initialize Cars\n for (int y=2; y<=screen_height-2; y+=2) {\n if (y < screen_height\/2)\n gameState[screen_width-1][y] = VEHICLE;\n else\n gameState[0][y] = VEHICLE;\n }\n\n \/\/ Run simulation for t timesteps\n int max_num_episodes = 100;\n int episode = 0;\n int curr_time = 0, max_timesteps = 100;\n while (episode < max_num_episodes) {\n curr_time++;\n substrate.getNetwork()->reinitialize();\n substrate.getNetwork()->dummyActivation();\n\n \/\/ Print Game Screen\n \/\/ if (threadID == 0) {\n \/\/ printf(\"Timestep %d Individual Species ID %d\\n\",t,individual->getSpeciesID());\n \/\/ for (int x=0; x<screen_width+2; ++x)\n \/\/ printf(\"-\");\n \/\/ printf(\"\\n\");\n \/\/ for (int y=0; y<screen_height; ++y) {\n \/\/ for (int x=0; x<screen_width; ++x) {\n \/\/ if (x==0) printf(\"|\");\n \/\/ if (gameState[x][y] == CHICKEN) {\n \/\/ printf(\"x\");\n \/\/ } else if (gameState[x][y] == VEHICLE) {\n \/\/ printf(\"o\");\n \/\/ } else {\n \/\/ printf(\" \");\n \/\/ }\n \/\/ }\n \/\/ printf(\"|\\n\");\n \/\/ }\n \/\/ for (int x=0; x<screen_width+2; ++x)\n \/\/ printf(\"-\");\n \/\/ printf(\"\\n\");\n \/\/ cin.get();\n \/\/ }\n\n \/\/ Set substrate values\n for (int x=0; x<screen_width; ++x) {\n for (int y=0; y<screen_height; ++y) {\n if (gameState[x][y] == CHICKEN) {\n substrate.setValue((Node(x,y,0)), 1.0);\n } else if (gameState[x][y] == VEHICLE) {\n \/\/ Highlight regions that the car is going to move into\n \/\/ for (int x2=max(0,x-2); x2<min(screen_width,x+3); x2++) {\n \/\/ if (gameState[x2][y] == CHICKEN) continue;\n \/\/ substrate.setValue((Node(x2,y,0)), -.5);\n \/\/ }\n substrate.setValue((Node(x,y,0)), -1.0);\n } else {\n substrate.setValue((Node(x,y,0)), 0.0); \n }\n }\n }\n\n substrate.getNetwork()->update();\n\n float chicken_val = substrate.getValue((Node(chic_x,chic_y,1)));\n float down_val = (chic_y >= screen_height-1) ? chicken_val : substrate.getValue((Node(chic_x,chic_y+1,1)));\n float up_val = (chic_y <= 0) ? chicken_val : substrate.getValue((Node(chic_x,chic_y-1,1)));\n\n int action;\n if (chicken_val >= up_val) {\n if (chicken_val >= down_val) {\n action = 0;\n } else {\n action = 1;\n }\n } else {\n if (up_val >= down_val) {\n action = -1;\n } else {\n action = 1;\n }\n }\n \/\/action = -1;\n \n \/\/ Update game state with action\n bool collision = false;\n\n \/\/ Move cars\n for (int y=0; y<screen_height; ++y) {\n for (int x=0; x<screen_width; ++x) {\n if (gameState[x][y] == VEHICLE) {\n int velocity = rand()%2;\n int carx;\n if (y < screen_height\/2) { \/\/ Top half cars go left\n if (x == 0) \/\/ reset car if it has reached the end\n carx = screen_width-1; \n else\n carx = max(0, x-velocity);\n } else {\n if (x == screen_width-1)\n carx = 0;\n else\n carx = min(screen_width-1, x+velocity);\n }\n gameState[x][y] = EMPTY;\n gameState[carx][y] = VEHICLE;\n break;\n }\n }\n }\n\n \/\/ Move chicken\n if (gameState[chic_x][chic_y] != VEHICLE) gameState[chic_x][chic_y] = EMPTY;\n if (gameState[chic_x][chic_y+action] != VEHICLE) gameState[chic_x][chic_y+action] = CHICKEN;\n else collision = true;\n chic_y += action;\n\n \/\/ Compute reward\n if (chic_y == 0 || collision || curr_time >= max_timesteps) {\n episode++;\n \n if (chic_y == 0) {\n total_reward += 50;\n } else if (collision) {\n total_reward += screen_height - chic_y;\n }\n \n curr_time = 0;\n \/\/ Reset the sim\n if (gameState[chic_x][chic_y] != VEHICLE) gameState[chic_x][chic_y] = EMPTY;\n gameState[chic_x][screen_height-1] = CHICKEN;\n chic_y = screen_height-1;\n }\n }\n float avg_reward = total_reward \/ max_num_episodes;\n \/\/cout << \"Got total reward: \" << total_reward << endl;\n individual->reward(avg_reward);\n }\n\n void AtariExperiment::preprocessIndividual(shared_ptr<NEAT::GeneticGeneration> generation,\n shared_ptr<NEAT::GeneticIndividual> individual) {\n if (individual->getNode(\"X1\") == NULL) {\n printf(\"Got blank individual\\n\");\n }\n }\n\n void AtariExperiment::processIndividualPostHoc(shared_ptr<NEAT::GeneticIndividual> individual)\n {\n \/\/ NEAT::FastNetwork<float> network = individual->spawnFastPhenotypeStack<float>();\n\n \/\/ \/\/TODO Put in userdata\n\n \/\/ double fitness = 10.0;\n \/\/ double maxFitness = 10.0;\n\n \/\/ for (int x1=0;x1<2;x1++)\n \/\/ {\n \/\/ for (int x2=0;x2<2;x2++)\n \/\/ {\n \/\/ network.reinitialize();\n\n \/\/ network.setValue(\"X1\",x1);\n \/\/ network.setValue(\"X2\",x2);\n \/\/ network.setValue(\"Bias\",0.3f);\n\n \/\/ network.update();\n\n \/\/ double value = network.getValue(\"Output\");\n\n \/\/ double expectedValue = (double)(x1 ^ x2);\n\n \/\/ fitness += (5000*(2-fabs(value-expectedValue)));\n \/\/ maxFitness += 5000*2;\n \/\/ }\n \/\/ }\n\n \/\/ cout << \"POST HOC ANALYSIS: \" << fitness << \"\/\" << maxFitness << endl;\n }\n\n Experiment* AtariExperiment::clone()\n {\n AtariExperiment* experiment = new AtariExperiment(*this);\n\n return experiment;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"cpphighlighter.h\"\n#include <cpptools\/cppdoxygen.h>\n\n#include <Token.h>\n#include <cplusplus\/SimpleLexer.h>\n#include <texteditor\/basetextdocumentlayout.h>\n\n#include <QtGui\/QTextDocument>\n#include <QtCore\/QDebug>\n\nusing namespace CppEditor::Internal;\nusing namespace TextEditor;\nusing namespace CPlusPlus;\n\nCppHighlighter::CppHighlighter(QTextDocument *document) :\n QSyntaxHighlighter(document)\n{\n}\n\nvoid CppHighlighter::highlightBlock(const QString &text)\n{\n const int previousState = previousBlockState();\n int state = 0, initialBraceDepth = 0;\n if (previousState != -1) {\n state = previousState & 0xff;\n initialBraceDepth = previousState >> 8;\n }\n\n int braceDepth = initialBraceDepth;\n\n SimpleLexer tokenize;\n tokenize.setQtMocRunEnabled(false);\n tokenize.setObjCEnabled(false);\n\n int initialState = state;\n const QList<SimpleToken> tokens = tokenize(text, initialState);\n state = tokenize.state(); \/\/ refresh the state\n\n int foldingIndent = initialBraceDepth;\n if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(currentBlock())) {\n userData->setFoldingIndent(0);\n userData->setFoldingStartIncluded(false);\n userData->setFoldingEndIncluded(false);\n }\n\n if (tokens.isEmpty()) {\n setCurrentBlockState(previousState);\n BaseTextDocumentLayout::clearParentheses(currentBlock());\n if (text.length()) \/\/ the empty line can still contain whitespace\n setFormat(0, text.length(), m_formats[CppVisualWhitespace]);\n BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);\n return;\n }\n\n const int firstNonSpace = tokens.first().position();\n\n Parentheses parentheses;\n parentheses.reserve(20); \/\/ assume wizard level ;-)\n\n bool highlightAsPreprocessor = false;\n\n for (int i = 0; i < tokens.size(); ++i) {\n const SimpleToken &tk = tokens.at(i);\n\n int previousTokenEnd = 0;\n if (i != 0) {\n \/\/ mark the whitespaces\n previousTokenEnd = tokens.at(i - 1).position() +\n tokens.at(i - 1).length();\n }\n\n if (previousTokenEnd != tk.position()) {\n setFormat(previousTokenEnd, tk.position() - previousTokenEnd,\n m_formats[CppVisualWhitespace]);\n }\n\n if (tk.is(T_LPAREN) || tk.is(T_LBRACE) || tk.is(T_LBRACKET)) {\n const QChar c(tk.text().at(0));\n parentheses.append(Parenthesis(Parenthesis::Opened, c, tk.position()));\n if (tk.is(T_LBRACE)) {\n ++braceDepth;\n\n \/\/ if a folding block opens at the beginning of a line, treat the entire line\n \/\/ as if it were inside the folding block\n if (tk.position() == firstNonSpace) {\n ++foldingIndent;\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingStartIncluded(true);\n }\n }\n } else if (tk.is(T_RPAREN) || tk.is(T_RBRACE) || tk.is(T_RBRACKET)) {\n const QChar c(tk.text().at(0));\n parentheses.append(Parenthesis(Parenthesis::Closed, c, tk.position()));\n if (tk.is(T_RBRACE)) {\n --braceDepth;\n if (braceDepth < foldingIndent) {\n \/\/ unless we are at the end of the block, we reduce the folding indent\n if (i == tokens.size()-1 || tokens.at(i+1).is(T_SEMICOLON))\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true);\n else\n foldingIndent = qMin(braceDepth, foldingIndent);\n }\n }\n }\n\n bool highlightCurrentWordAsPreprocessor = highlightAsPreprocessor;\n\n if (highlightAsPreprocessor)\n highlightAsPreprocessor = false;\n\n if (i == 0 && tk.is(T_POUND)) {\n highlightLine(text, tk.position(), tk.length(), m_formats[CppPreprocessorFormat]);\n highlightAsPreprocessor = true;\n\n } else if (highlightCurrentWordAsPreprocessor &&\n (tk.isKeyword() || tk.is(T_IDENTIFIER)) && isPPKeyword(tk.text()))\n setFormat(tk.position(), tk.length(), m_formats[CppPreprocessorFormat]);\n\n else if (tk.is(T_NUMERIC_LITERAL))\n setFormat(tk.position(), tk.length(), m_formats[CppNumberFormat]);\n\n else if (tk.is(T_STRING_LITERAL) || tk.is(T_CHAR_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL) ||\n tk.is(T_AT_STRING_LITERAL))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppStringFormat]);\n\n else if (tk.is(T_WIDE_STRING_LITERAL) || tk.is(T_WIDE_CHAR_LITERAL))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppStringFormat]);\n\n else if (tk.isComment()) {\n\n if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppCommentFormat]);\n\n else \/\/ a doxygen comment\n highlightDoxygenComment(text, tk.position(), tk.length());\n\n \/\/ we need to insert a close comment parenthesis, if\n \/\/ - the line starts in a C Comment (initalState != 0)\n \/\/ - the first token of the line is a T_COMMENT (i == 0 && tk.is(T_COMMENT))\n \/\/ - is not a continuation line (tokens.size() > 1 || ! state)\n if (initialState && i == 0 && (tokens.size() > 1 || ! state)) {\n --braceDepth;\n \/\/ unless we are at the end of the block, we reduce the folding indent\n if (i == tokens.size()-1)\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true);\n else\n foldingIndent = qMin(braceDepth, foldingIndent);\n const int tokenEnd = tk.position() + tk.length() - 1;\n parentheses.append(Parenthesis(Parenthesis::Closed, QLatin1Char('-'), tokenEnd));\n\n \/\/ clear the initial state.\n initialState = 0;\n }\n\n } else if (tk.isKeyword() || isQtKeyword(tk.text()) || tk.isObjCAtKeyword() || tk.isObjCTypeQualifier())\n setFormat(tk.position(), tk.length(), m_formats[CppKeywordFormat]);\n\n else if (tk.isOperator())\n setFormat(tk.position(), tk.length(), m_formats[CppOperatorFormat]);\n\n else if (i == 0 && tokens.size() > 1 && tk.is(T_IDENTIFIER) && tokens.at(1).is(T_COLON))\n setFormat(tk.position(), tk.length(), m_formats[CppLabelFormat]);\n\n else if (tk.is(T_IDENTIFIER))\n highlightWord(tk.text(), tk.position(), tk.length());\n\n }\n\n \/\/ mark the trailing white spaces\n {\n const SimpleToken tk = tokens.last();\n const int lastTokenEnd = tk.position() + tk.length();\n if (text.length() > lastTokenEnd)\n highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, QTextCharFormat());\n }\n\n if (! initialState && state && ! tokens.isEmpty()) {\n parentheses.append(Parenthesis(Parenthesis::Opened, QLatin1Char('+'),\n tokens.last().position()));\n ++braceDepth;\n }\n\n BaseTextDocumentLayout::setParentheses(currentBlock(), parentheses);\n\n \/\/ if the block is ifdefed out, we only store the parentheses, but\n\n \/\/ do not adjust the brace depth.\n if (BaseTextDocumentLayout::ifdefedOut(currentBlock())) {\n braceDepth = initialBraceDepth;\n foldingIndent = initialBraceDepth;\n }\n\n BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);\n\n \/\/ optimization: if only the brace depth changes, we adjust subsequent blocks\n \/\/ to have QSyntaxHighlighter stop the rehighlighting\n int currentState = currentBlockState();\n if (currentState != -1) {\n int oldState = currentState & 0xff;\n int oldBraceDepth = currentState >> 8;\n if (oldState == tokenize.state() && oldBraceDepth != braceDepth) {\n int delta = braceDepth - oldBraceDepth;\n QTextBlock block = currentBlock().next();\n while (block.isValid() && block.userState() != -1) {\n BaseTextDocumentLayout::changeBraceDepth(block, delta);\n BaseTextDocumentLayout::changeFoldingIndent(block, delta);\n block = block.next();\n }\n }\n }\n\n setCurrentBlockState((braceDepth << 8) | tokenize.state());\n}\n\n\nbool CppHighlighter::isPPKeyword(const QStringRef &text) const\n{\n switch (text.length())\n {\n case 2:\n if (text.at(0) == 'i' && text.at(1) == 'f')\n return true;\n break;\n\n case 4:\n if (text.at(0) == 'e' && text == QLatin1String(\"elif\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"else\"))\n return true;\n break;\n\n case 5:\n if (text.at(0) == 'i' && text == QLatin1String(\"ifdef\"))\n return true;\n else if (text.at(0) == 'u' && text == QLatin1String(\"undef\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"endif\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"error\"))\n return true;\n break;\n\n case 6:\n if (text.at(0) == 'i' && text == QLatin1String(\"ifndef\"))\n return true;\n if (text.at(0) == 'i' && text == QLatin1String(\"import\"))\n return true;\n else if (text.at(0) == 'd' && text == QLatin1String(\"define\"))\n return true;\n else if (text.at(0) == 'p' && text == QLatin1String(\"pragma\"))\n return true;\n break;\n\n case 7:\n if (text.at(0) == 'i' && text == QLatin1String(\"include\"))\n return true;\n else if (text.at(0) == 'w' && text == QLatin1String(\"warning\"))\n return true;\n break;\n\n case 12:\n if (text.at(0) == 'i' && text == QLatin1String(\"include_next\"))\n return true;\n break;\n\n default:\n break;\n }\n\n return false;\n}\n\nbool CppHighlighter::isQtKeyword(const QStringRef &text) const\n{\n switch (text.length()) {\n case 4:\n if (text.at(0) == 'e' && text == QLatin1String(\"emit\"))\n return true;\n else if (text.at(0) == 'S' && text == QLatin1String(\"SLOT\"))\n return true;\n break;\n\n case 5:\n if (text.at(0) == 's' && text == QLatin1String(\"slots\"))\n return true;\n break;\n\n case 6:\n if (text.at(0) == 'S' && text == QLatin1String(\"SIGNAL\"))\n return true;\n break;\n\n case 7:\n if (text.at(0) == 's' && text == QLatin1String(\"signals\"))\n return true;\n else if (text.at(0) == 'f' && text == QLatin1String(\"foreach\"))\n return true;\n else if (text.at(0) == 'f' && text == QLatin1String(\"forever\"))\n return true;\n break;\n\n default:\n break;\n }\n return false;\n}\n\nvoid CppHighlighter::highlightLine(const QString &text, int position, int length,\n const QTextCharFormat &format)\n{\n const QTextCharFormat visualSpaceFormat = m_formats[CppVisualWhitespace];\n\n const int end = position + length;\n int index = position;\n\n while (index != end) {\n const bool isSpace = text.at(index).isSpace();\n const int start = index;\n\n do { ++index; }\n while (index != end && text.at(index).isSpace() == isSpace);\n\n const int tokenLength = index - start;\n if (isSpace)\n setFormat(start, tokenLength, visualSpaceFormat);\n else if (format.isValid())\n setFormat(start, tokenLength, format);\n }\n}\n\nvoid CppHighlighter::highlightWord(QStringRef word, int position, int length)\n{\n \/\/ try to highlight Qt 'identifiers' like QObject and Q_PROPERTY\n \/\/ but don't highlight words like 'Query'\n\n if (word.length() > 1 && word.at(0) == QLatin1Char('Q')) {\n for (int i = 1; i < word.length(); ++i) {\n const QChar &ch = word.at(i);\n if (! (ch.isUpper() || ch == QLatin1Char('_')))\n return;\n }\n\n setFormat(position, length, m_formats[CppTypeFormat]);\n }\n}\n\nvoid CppHighlighter::highlightDoxygenComment(const QString &text, int position, int)\n{\n int initial = position;\n\n const QChar *uc = text.unicode();\n const QChar *it = uc + position;\n\n const QTextCharFormat &format = m_formats[CppDoxygenCommentFormat];\n const QTextCharFormat &kwFormat = m_formats[CppDoxygenTagFormat];\n\n while (! it->isNull()) {\n if (it->unicode() == QLatin1Char('\\\\') ||\n it->unicode() == QLatin1Char('@')) {\n ++it;\n\n const QChar *start = it;\n while (it->isLetterOrNumber() || it->unicode() == '_')\n ++it;\n\n int k = CppTools::classifyDoxygenTag(start, it - start);\n if (k != CppTools::T_DOXY_IDENTIFIER) {\n highlightLine(text, initial, start - uc - initial, format);\n setFormat(start - uc - 1, it - start + 1, kwFormat);\n initial = it - uc;\n }\n } else\n ++it;\n }\n\n highlightLine(text, initial, it - uc - initial, format);\n}\n\n<commit_msg>Recognize Q_* and QT_* as reserved keywords.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"cpphighlighter.h\"\n#include <cpptools\/cppdoxygen.h>\n\n#include <Token.h>\n#include <cplusplus\/SimpleLexer.h>\n#include <texteditor\/basetextdocumentlayout.h>\n\n#include <QtGui\/QTextDocument>\n#include <QtCore\/QDebug>\n\nusing namespace CppEditor::Internal;\nusing namespace TextEditor;\nusing namespace CPlusPlus;\n\nCppHighlighter::CppHighlighter(QTextDocument *document) :\n QSyntaxHighlighter(document)\n{\n}\n\nvoid CppHighlighter::highlightBlock(const QString &text)\n{\n const int previousState = previousBlockState();\n int state = 0, initialBraceDepth = 0;\n if (previousState != -1) {\n state = previousState & 0xff;\n initialBraceDepth = previousState >> 8;\n }\n\n int braceDepth = initialBraceDepth;\n\n SimpleLexer tokenize;\n tokenize.setQtMocRunEnabled(false);\n tokenize.setObjCEnabled(false);\n\n int initialState = state;\n const QList<SimpleToken> tokens = tokenize(text, initialState);\n state = tokenize.state(); \/\/ refresh the state\n\n int foldingIndent = initialBraceDepth;\n if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(currentBlock())) {\n userData->setFoldingIndent(0);\n userData->setFoldingStartIncluded(false);\n userData->setFoldingEndIncluded(false);\n }\n\n if (tokens.isEmpty()) {\n setCurrentBlockState(previousState);\n BaseTextDocumentLayout::clearParentheses(currentBlock());\n if (text.length()) \/\/ the empty line can still contain whitespace\n setFormat(0, text.length(), m_formats[CppVisualWhitespace]);\n BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);\n return;\n }\n\n const int firstNonSpace = tokens.first().position();\n\n Parentheses parentheses;\n parentheses.reserve(20); \/\/ assume wizard level ;-)\n\n bool highlightAsPreprocessor = false;\n\n for (int i = 0; i < tokens.size(); ++i) {\n const SimpleToken &tk = tokens.at(i);\n\n int previousTokenEnd = 0;\n if (i != 0) {\n \/\/ mark the whitespaces\n previousTokenEnd = tokens.at(i - 1).position() +\n tokens.at(i - 1).length();\n }\n\n if (previousTokenEnd != tk.position()) {\n setFormat(previousTokenEnd, tk.position() - previousTokenEnd,\n m_formats[CppVisualWhitespace]);\n }\n\n if (tk.is(T_LPAREN) || tk.is(T_LBRACE) || tk.is(T_LBRACKET)) {\n const QChar c(tk.text().at(0));\n parentheses.append(Parenthesis(Parenthesis::Opened, c, tk.position()));\n if (tk.is(T_LBRACE)) {\n ++braceDepth;\n\n \/\/ if a folding block opens at the beginning of a line, treat the entire line\n \/\/ as if it were inside the folding block\n if (tk.position() == firstNonSpace) {\n ++foldingIndent;\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingStartIncluded(true);\n }\n }\n } else if (tk.is(T_RPAREN) || tk.is(T_RBRACE) || tk.is(T_RBRACKET)) {\n const QChar c(tk.text().at(0));\n parentheses.append(Parenthesis(Parenthesis::Closed, c, tk.position()));\n if (tk.is(T_RBRACE)) {\n --braceDepth;\n if (braceDepth < foldingIndent) {\n \/\/ unless we are at the end of the block, we reduce the folding indent\n if (i == tokens.size()-1 || tokens.at(i+1).is(T_SEMICOLON))\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true);\n else\n foldingIndent = qMin(braceDepth, foldingIndent);\n }\n }\n }\n\n bool highlightCurrentWordAsPreprocessor = highlightAsPreprocessor;\n\n if (highlightAsPreprocessor)\n highlightAsPreprocessor = false;\n\n if (i == 0 && tk.is(T_POUND)) {\n highlightLine(text, tk.position(), tk.length(), m_formats[CppPreprocessorFormat]);\n highlightAsPreprocessor = true;\n\n } else if (highlightCurrentWordAsPreprocessor &&\n (tk.isKeyword() || tk.is(T_IDENTIFIER)) && isPPKeyword(tk.text()))\n setFormat(tk.position(), tk.length(), m_formats[CppPreprocessorFormat]);\n\n else if (tk.is(T_NUMERIC_LITERAL))\n setFormat(tk.position(), tk.length(), m_formats[CppNumberFormat]);\n\n else if (tk.is(T_STRING_LITERAL) || tk.is(T_CHAR_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL) ||\n tk.is(T_AT_STRING_LITERAL))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppStringFormat]);\n\n else if (tk.is(T_WIDE_STRING_LITERAL) || tk.is(T_WIDE_CHAR_LITERAL))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppStringFormat]);\n\n else if (tk.isComment()) {\n\n if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT))\n highlightLine(text, tk.position(), tk.length(), m_formats[CppCommentFormat]);\n\n else \/\/ a doxygen comment\n highlightDoxygenComment(text, tk.position(), tk.length());\n\n \/\/ we need to insert a close comment parenthesis, if\n \/\/ - the line starts in a C Comment (initalState != 0)\n \/\/ - the first token of the line is a T_COMMENT (i == 0 && tk.is(T_COMMENT))\n \/\/ - is not a continuation line (tokens.size() > 1 || ! state)\n if (initialState && i == 0 && (tokens.size() > 1 || ! state)) {\n --braceDepth;\n \/\/ unless we are at the end of the block, we reduce the folding indent\n if (i == tokens.size()-1)\n BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true);\n else\n foldingIndent = qMin(braceDepth, foldingIndent);\n const int tokenEnd = tk.position() + tk.length() - 1;\n parentheses.append(Parenthesis(Parenthesis::Closed, QLatin1Char('-'), tokenEnd));\n\n \/\/ clear the initial state.\n initialState = 0;\n }\n\n } else if (tk.isKeyword() || isQtKeyword(tk.text()) || tk.isObjCAtKeyword() || tk.isObjCTypeQualifier())\n setFormat(tk.position(), tk.length(), m_formats[CppKeywordFormat]);\n\n else if (tk.isOperator())\n setFormat(tk.position(), tk.length(), m_formats[CppOperatorFormat]);\n\n else if (i == 0 && tokens.size() > 1 && tk.is(T_IDENTIFIER) && tokens.at(1).is(T_COLON))\n setFormat(tk.position(), tk.length(), m_formats[CppLabelFormat]);\n\n else if (tk.is(T_IDENTIFIER))\n highlightWord(tk.text(), tk.position(), tk.length());\n\n }\n\n \/\/ mark the trailing white spaces\n {\n const SimpleToken tk = tokens.last();\n const int lastTokenEnd = tk.position() + tk.length();\n if (text.length() > lastTokenEnd)\n highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, QTextCharFormat());\n }\n\n if (! initialState && state && ! tokens.isEmpty()) {\n parentheses.append(Parenthesis(Parenthesis::Opened, QLatin1Char('+'),\n tokens.last().position()));\n ++braceDepth;\n }\n\n BaseTextDocumentLayout::setParentheses(currentBlock(), parentheses);\n\n \/\/ if the block is ifdefed out, we only store the parentheses, but\n\n \/\/ do not adjust the brace depth.\n if (BaseTextDocumentLayout::ifdefedOut(currentBlock())) {\n braceDepth = initialBraceDepth;\n foldingIndent = initialBraceDepth;\n }\n\n BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);\n\n \/\/ optimization: if only the brace depth changes, we adjust subsequent blocks\n \/\/ to have QSyntaxHighlighter stop the rehighlighting\n int currentState = currentBlockState();\n if (currentState != -1) {\n int oldState = currentState & 0xff;\n int oldBraceDepth = currentState >> 8;\n if (oldState == tokenize.state() && oldBraceDepth != braceDepth) {\n int delta = braceDepth - oldBraceDepth;\n QTextBlock block = currentBlock().next();\n while (block.isValid() && block.userState() != -1) {\n BaseTextDocumentLayout::changeBraceDepth(block, delta);\n BaseTextDocumentLayout::changeFoldingIndent(block, delta);\n block = block.next();\n }\n }\n }\n\n setCurrentBlockState((braceDepth << 8) | tokenize.state());\n}\n\n\nbool CppHighlighter::isPPKeyword(const QStringRef &text) const\n{\n switch (text.length())\n {\n case 2:\n if (text.at(0) == 'i' && text.at(1) == 'f')\n return true;\n break;\n\n case 4:\n if (text.at(0) == 'e' && text == QLatin1String(\"elif\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"else\"))\n return true;\n break;\n\n case 5:\n if (text.at(0) == 'i' && text == QLatin1String(\"ifdef\"))\n return true;\n else if (text.at(0) == 'u' && text == QLatin1String(\"undef\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"endif\"))\n return true;\n else if (text.at(0) == 'e' && text == QLatin1String(\"error\"))\n return true;\n break;\n\n case 6:\n if (text.at(0) == 'i' && text == QLatin1String(\"ifndef\"))\n return true;\n if (text.at(0) == 'i' && text == QLatin1String(\"import\"))\n return true;\n else if (text.at(0) == 'd' && text == QLatin1String(\"define\"))\n return true;\n else if (text.at(0) == 'p' && text == QLatin1String(\"pragma\"))\n return true;\n break;\n\n case 7:\n if (text.at(0) == 'i' && text == QLatin1String(\"include\"))\n return true;\n else if (text.at(0) == 'w' && text == QLatin1String(\"warning\"))\n return true;\n break;\n\n case 12:\n if (text.at(0) == 'i' && text == QLatin1String(\"include_next\"))\n return true;\n break;\n\n default:\n break;\n }\n\n return false;\n}\n\nbool CppHighlighter::isQtKeyword(const QStringRef &text) const\n{\n switch (text.length()) {\n case 4:\n if (text.at(0) == 'e' && text == QLatin1String(\"emit\"))\n return true;\n else if (text.at(0) == 'S' && text == QLatin1String(\"SLOT\"))\n return true;\n break;\n\n case 5:\n if (text.at(0) == 's' && text == QLatin1String(\"slots\"))\n return true;\n break;\n\n case 6:\n if (text.at(0) == 'S' && text == QLatin1String(\"SIGNAL\"))\n return true;\n break;\n\n case 7:\n if (text.at(0) == 's' && text == QLatin1String(\"signals\"))\n return true;\n else if (text.at(0) == 'f' && text == QLatin1String(\"foreach\"))\n return true;\n else if (text.at(0) == 'f' && text == QLatin1String(\"forever\"))\n return true;\n break;\n\n default:\n break;\n }\n return false;\n}\n\nvoid CppHighlighter::highlightLine(const QString &text, int position, int length,\n const QTextCharFormat &format)\n{\n const QTextCharFormat visualSpaceFormat = m_formats[CppVisualWhitespace];\n\n const int end = position + length;\n int index = position;\n\n while (index != end) {\n const bool isSpace = text.at(index).isSpace();\n const int start = index;\n\n do { ++index; }\n while (index != end && text.at(index).isSpace() == isSpace);\n\n const int tokenLength = index - start;\n if (isSpace)\n setFormat(start, tokenLength, visualSpaceFormat);\n else if (format.isValid())\n setFormat(start, tokenLength, format);\n }\n}\n\nvoid CppHighlighter::highlightWord(QStringRef word, int position, int length)\n{\n \/\/ try to highlight Qt 'identifiers' like QObject and Q_PROPERTY\n\n if (word.length() > 2 && word.at(0) == QLatin1Char('Q')) {\n if (word.at(1) == QLatin1Char('_') \/\/ Q_\n || word.at(1) == QLatin1Char('T') && word.at(2) == QLatin1Char('_')) { \/\/ QT_\n for (int i = 1; i < word.length(); ++i) {\n const QChar &ch = word.at(i);\n if (! (ch.isUpper() || ch == QLatin1Char('_')))\n return;\n }\n\n setFormat(position, length, m_formats[CppTypeFormat]);\n }\n }\n}\n\nvoid CppHighlighter::highlightDoxygenComment(const QString &text, int position, int)\n{\n int initial = position;\n\n const QChar *uc = text.unicode();\n const QChar *it = uc + position;\n\n const QTextCharFormat &format = m_formats[CppDoxygenCommentFormat];\n const QTextCharFormat &kwFormat = m_formats[CppDoxygenTagFormat];\n\n while (! it->isNull()) {\n if (it->unicode() == QLatin1Char('\\\\') ||\n it->unicode() == QLatin1Char('@')) {\n ++it;\n\n const QChar *start = it;\n while (it->isLetterOrNumber() || it->unicode() == '_')\n ++it;\n\n int k = CppTools::classifyDoxygenTag(start, it - start);\n if (k != CppTools::T_DOXY_IDENTIFIER) {\n highlightLine(text, initial, start - uc - initial, format);\n setFormat(start - uc - 1, it - start + 1, kwFormat);\n initial = it - uc;\n }\n } else\n ++it;\n }\n\n highlightLine(text, initial, it - uc - initial, format);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file airspeed_calibration.cpp\n * Airspeed sensor calibration routine\n *\/\n\n#include \"airspeed_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n#include \"commander_helper.h\"\n\n#include <px4_posix.h>\n#include <px4_time.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <cmath>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/drv_airspeed.h>\n#include <uORB\/topics\/sensor_combined.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/err.h>\n#include <systemlib\/airspeed.h>\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nstatic const int ERROR = -1;\n\nstatic const char *sensor_name = \"dpress\";\n\nstatic void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)\n{\n\tsleep(5);\n\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);\n}\n\nint do_airspeed_calibration(orb_advert_t *mavlink_log_pub)\n{\n\tint result = OK;\n\tunsigned calibration_counter = 0;\n\tconst unsigned maxcount = 2400;\n\n\t\/* give directions *\/\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);\n\n\tconst unsigned calibration_count = (maxcount * 2) \/ 3;\n\n\tint diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));\n\tstruct differential_pressure_s diff_pres;\n\n\tfloat diff_pres_offset = 0.0f;\n\n\t\/* Reset sensor parameters *\/\n\tstruct airspeed_scale airscale = {\n\t\tdiff_pres_offset,\n\t\t1.0f,\n\t};\n\n\tbool paramreset_successful = false;\n\tint fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\n\tif (fd > 0) {\n\t\tif (OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\tparamreset_successful = true;\n\n\t\t} else {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset zero failed\");\n\t\t}\n\n\t\tpx4_close(fd);\n\t}\n\n\tint cancel_sub = calibrate_cancel_subscribe();\n\n\tif (!paramreset_successful) {\n\n\t\t\/* only warn if analog scaling is zero *\/\n\t\tfloat analog_scaling = 0.0f;\n\t\tparam_get(param_find(\"SENS_DPRES_ANSC\"), &(analog_scaling));\n\t\tif (fabsf(analog_scaling) < 0.1f) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] No airspeed sensor, see http:\/\/px4.io\/help\/aspd\");\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* set scaling offset parameter *\/\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Ensure sensor is not measuring wind\");\n\tusleep(500 * 1000);\n\n\twhile (calibration_counter < calibration_count) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tdiff_pres_offset += diff_pres.differential_pressure_raw_pa;\n\t\t\tcalibration_counter++;\n\n\t\t\tif (calibration_counter % (calibration_count \/ 20) == 0) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) \/ calibration_count);\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tdiff_pres_offset = diff_pres_offset \/ calibration_count;\n\n\tif (PX4_ISFINITE(diff_pres_offset)) {\n\n\t\tint fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\t\tairscale.offset_pa = diff_pres_offset;\n\t\tif (fd_scale > 0) {\n\t\t\tif (OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset update failed\");\n\t\t\t}\n\n\t\t\tpx4_close(fd_scale);\n\t\t}\n\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* auto-save to EEPROM *\/\n\t\tint save_ret = param_save_default();\n\n\t\tif (save_ret != 0) {\n\t\t\twarn(\"WARNING: auto-save of params to storage failed\");\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SAVE_PARAMS_MSG);\n\t\t\tgoto error_return;\n\t\t}\n\n\t} else {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Offset of %d Pascal\", (int)diff_pres_offset);\n\n\t\/* wait 500 ms to ensure parameter propagated through the system *\/\n\tusleep(500 * 1000);\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Blow across front of pitot without touching\");\n\n\tcalibration_counter = 0;\n\n\t\/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds *\/\n\twhile (calibration_counter < maxcount) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tcalibration_counter++;\n\n\t\t\tif (fabsf(diff_pres.differential_pressure_raw_pa) < 50.0f) {\n\t\t\t\tif (calibration_counter % 500 == 0) {\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Create air pressure! (got %d, wanted: 50 Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/* do not allow negative values *\/\n\t\t\tif (diff_pres.differential_pressure_raw_pa < 0.0f) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Negative pressure difference detected (%d Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Swap static and dynamic ports!\");\n\n\t\t\t\t\/* the user setup is wrong, wipe the calibration to force a proper re-calibration *\/\n\n\t\t\t\tdiff_pres_offset = 0.0f;\n\t\t\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t\/* save *\/\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);\n\t\t\t\t(void)param_save_default();\n\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\t\t\t} else {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Positive pressure: OK (%d Pa)\",\n\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tif (calibration_counter == maxcount) {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);\n\ttune_neutral(true);\n\nnormal_return:\n\tcalibrate_cancel_unsubscribe(cancel_sub);\n\tpx4_close(diff_pres_sub);\n\n\t\/\/ This give a chance for the log messages to go out of the queue before someone else stomps on then\n\tsleep(1);\n\n\treturn result;\n\nerror_return:\n\tresult = ERROR;\n\tgoto normal_return;\n}\n<commit_msg>airspeed_calibration: remove unused include<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file airspeed_calibration.cpp\n * Airspeed sensor calibration routine\n *\/\n\n#include \"airspeed_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n#include \"commander_helper.h\"\n\n#include <px4_posix.h>\n#include <px4_time.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <cmath>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/drv_airspeed.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/err.h>\n#include <systemlib\/airspeed.h>\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nstatic const int ERROR = -1;\n\nstatic const char *sensor_name = \"dpress\";\n\nstatic void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)\n{\n\tsleep(5);\n\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);\n}\n\nint do_airspeed_calibration(orb_advert_t *mavlink_log_pub)\n{\n\tint result = OK;\n\tunsigned calibration_counter = 0;\n\tconst unsigned maxcount = 2400;\n\n\t\/* give directions *\/\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);\n\n\tconst unsigned calibration_count = (maxcount * 2) \/ 3;\n\n\tint diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));\n\tstruct differential_pressure_s diff_pres;\n\n\tfloat diff_pres_offset = 0.0f;\n\n\t\/* Reset sensor parameters *\/\n\tstruct airspeed_scale airscale = {\n\t\tdiff_pres_offset,\n\t\t1.0f,\n\t};\n\n\tbool paramreset_successful = false;\n\tint fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\n\tif (fd > 0) {\n\t\tif (OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\tparamreset_successful = true;\n\n\t\t} else {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset zero failed\");\n\t\t}\n\n\t\tpx4_close(fd);\n\t}\n\n\tint cancel_sub = calibrate_cancel_subscribe();\n\n\tif (!paramreset_successful) {\n\n\t\t\/* only warn if analog scaling is zero *\/\n\t\tfloat analog_scaling = 0.0f;\n\t\tparam_get(param_find(\"SENS_DPRES_ANSC\"), &(analog_scaling));\n\t\tif (fabsf(analog_scaling) < 0.1f) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] No airspeed sensor, see http:\/\/px4.io\/help\/aspd\");\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* set scaling offset parameter *\/\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Ensure sensor is not measuring wind\");\n\tusleep(500 * 1000);\n\n\twhile (calibration_counter < calibration_count) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tdiff_pres_offset += diff_pres.differential_pressure_raw_pa;\n\t\t\tcalibration_counter++;\n\n\t\t\tif (calibration_counter % (calibration_count \/ 20) == 0) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) \/ calibration_count);\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tdiff_pres_offset = diff_pres_offset \/ calibration_count;\n\n\tif (PX4_ISFINITE(diff_pres_offset)) {\n\n\t\tint fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\t\tairscale.offset_pa = diff_pres_offset;\n\t\tif (fd_scale > 0) {\n\t\t\tif (OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset update failed\");\n\t\t\t}\n\n\t\t\tpx4_close(fd_scale);\n\t\t}\n\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* auto-save to EEPROM *\/\n\t\tint save_ret = param_save_default();\n\n\t\tif (save_ret != 0) {\n\t\t\twarn(\"WARNING: auto-save of params to storage failed\");\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SAVE_PARAMS_MSG);\n\t\t\tgoto error_return;\n\t\t}\n\n\t} else {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Offset of %d Pascal\", (int)diff_pres_offset);\n\n\t\/* wait 500 ms to ensure parameter propagated through the system *\/\n\tusleep(500 * 1000);\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Blow across front of pitot without touching\");\n\n\tcalibration_counter = 0;\n\n\t\/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds *\/\n\twhile (calibration_counter < maxcount) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tcalibration_counter++;\n\n\t\t\tif (fabsf(diff_pres.differential_pressure_raw_pa) < 50.0f) {\n\t\t\t\tif (calibration_counter % 500 == 0) {\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Create air pressure! (got %d, wanted: 50 Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/* do not allow negative values *\/\n\t\t\tif (diff_pres.differential_pressure_raw_pa < 0.0f) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Negative pressure difference detected (%d Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Swap static and dynamic ports!\");\n\n\t\t\t\t\/* the user setup is wrong, wipe the calibration to force a proper re-calibration *\/\n\n\t\t\t\tdiff_pres_offset = 0.0f;\n\t\t\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t\/* save *\/\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);\n\t\t\t\t(void)param_save_default();\n\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\t\t\t} else {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Positive pressure: OK (%d Pa)\",\n\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tif (calibration_counter == maxcount) {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);\n\ttune_neutral(true);\n\nnormal_return:\n\tcalibrate_cancel_unsubscribe(cancel_sub);\n\tpx4_close(diff_pres_sub);\n\n\t\/\/ This give a chance for the log messages to go out of the queue before someone else stomps on then\n\tsleep(1);\n\n\treturn result;\n\nerror_return:\n\tresult = ERROR;\n\tgoto normal_return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file airspeed_calibration.cpp\n * Airspeed sensor calibration routine\n *\/\n\n#include \"airspeed_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n#include \"commander_helper.h\"\n\n#include <px4_defines.h>\n#include <px4_posix.h>\n#include <px4_time.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <cmath>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/drv_airspeed.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/err.h>\n#include <systemlib\/airspeed.h>\n\nstatic const char *sensor_name = \"dpress\";\n\nstatic void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)\n{\n\tsleep(5);\n\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);\n}\n\nint do_airspeed_calibration(orb_advert_t *mavlink_log_pub)\n{\n\tint result = PX4_OK;\n\tunsigned calibration_counter = 0;\n\tconst unsigned maxcount = 2400;\n\n\t\/* give directions *\/\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);\n\n\tconst unsigned calibration_count = (maxcount * 2) \/ 3;\n\n\tint diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));\n\tstruct differential_pressure_s diff_pres;\n\n\tfloat diff_pres_offset = 0.0f;\n\n\t\/* Reset sensor parameters *\/\n\tstruct airspeed_scale airscale = {\n\t\tdiff_pres_offset,\n\t\t1.0f,\n\t};\n\n\tbool paramreset_successful = false;\n\tint fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\n\tif (fd > 0) {\n\t\tif (PX4_OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\tparamreset_successful = true;\n\n\t\t} else {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset zero failed\");\n\t\t}\n\n\t\tpx4_close(fd);\n\t}\n\n\tint cancel_sub = calibrate_cancel_subscribe();\n\n\tif (!paramreset_successful) {\n\n\t\t\/* only warn if analog scaling is zero *\/\n\t\tfloat analog_scaling = 0.0f;\n\t\tparam_get(param_find(\"SENS_DPRES_ANSC\"), &(analog_scaling));\n\t\tif (fabsf(analog_scaling) < 0.1f) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] No airspeed sensor, see http:\/\/px4.io\/help\/aspd\");\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* set scaling offset parameter *\/\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Ensure sensor is not measuring wind\");\n\tusleep(500 * 1000);\n\n\twhile (calibration_counter < calibration_count) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tdiff_pres_offset += diff_pres.differential_pressure_raw_pa;\n\t\t\tcalibration_counter++;\n\n\t\t\t\/* any differential pressure failure a reason to abort *\/\n\t\t\tif (diff_pres.error_count != 0) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed error count non zero\");\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\t\t\t}\n\n\t\t\tif (calibration_counter % (calibration_count \/ 20) == 0) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) \/ calibration_count);\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tdiff_pres_offset = diff_pres_offset \/ calibration_count;\n\n\tif (PX4_ISFINITE(diff_pres_offset)) {\n\n\t\tint fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\t\tairscale.offset_pa = diff_pres_offset;\n\t\tif (fd_scale > 0) {\n\t\t\tif (PX4_OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset update failed\");\n\t\t\t}\n\n\t\t\tpx4_close(fd_scale);\n\t\t}\n\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* auto-save to EEPROM *\/\n\t\tint save_ret = param_save_default();\n\n\t\tif (save_ret != 0) {\n\t\t\twarn(\"WARNING: auto-save of params to storage failed\");\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SAVE_PARAMS_MSG);\n\t\t\tgoto error_return;\n\t\t}\n\n\t} else {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Offset of %d Pascal\", (int)diff_pres_offset);\n\n\t\/* wait 500 ms to ensure parameter propagated through the system *\/\n\tusleep(500 * 1000);\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Blow across front of pitot without touching\");\n\n\tcalibration_counter = 0;\n\n\t\/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds *\/\n\twhile (calibration_counter < maxcount) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tcalibration_counter++;\n\n\t\t\tif (fabsf(diff_pres.differential_pressure_raw_pa) < 50.0f) {\n\t\t\t\tif (calibration_counter % 500 == 0) {\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Create air pressure! (got %d, wanted: 50 Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/* do not allow negative values *\/\n\t\t\tif (diff_pres.differential_pressure_raw_pa < 0.0f) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Negative pressure difference detected (%d Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Swap static and dynamic ports!\");\n\n\t\t\t\t\/* the user setup is wrong, wipe the calibration to force a proper re-calibration *\/\n\n\t\t\t\tdiff_pres_offset = 0.0f;\n\t\t\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t\/* save *\/\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);\n\t\t\t\t(void)param_save_default();\n\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\n\t\t\t} else {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Positive pressure: OK (%d Pa)\",\n\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tif (calibration_counter == maxcount) {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);\n\ttune_neutral(true);\n\n\t\/* Wait 2sec for the airflow to stop and ensure the driver filter has caught up, otherwise\n\t * the followup preflight checks might fail. *\/\n\tusleep(2e6);\n\nnormal_return:\n\tcalibrate_cancel_unsubscribe(cancel_sub);\n\tpx4_close(diff_pres_sub);\n\n\t\/\/ This give a chance for the log messages to go out of the queue before someone else stomps on then\n\tsleep(1);\n\n\treturn result;\n\nerror_return:\n\tresult = PX4_ERROR;\n\tgoto normal_return;\n}\n<commit_msg>airspeed cal more descriptive error message (#6324)<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file airspeed_calibration.cpp\n * Airspeed sensor calibration routine\n *\/\n\n#include \"airspeed_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n#include \"commander_helper.h\"\n\n#include <px4_defines.h>\n#include <px4_posix.h>\n#include <px4_time.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <cmath>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/drv_airspeed.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/err.h>\n#include <systemlib\/airspeed.h>\n\nstatic const char *sensor_name = \"airspeed\";\n\nstatic void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)\n{\n\tsleep(5);\n\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);\n}\n\nint do_airspeed_calibration(orb_advert_t *mavlink_log_pub)\n{\n\tint result = PX4_OK;\n\tunsigned calibration_counter = 0;\n\tconst unsigned maxcount = 2400;\n\n\t\/* give directions *\/\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);\n\n\tconst unsigned calibration_count = (maxcount * 2) \/ 3;\n\n\tint diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));\n\tstruct differential_pressure_s diff_pres;\n\n\tfloat diff_pres_offset = 0.0f;\n\n\t\/* Reset sensor parameters *\/\n\tstruct airspeed_scale airscale = {\n\t\tdiff_pres_offset,\n\t\t1.0f,\n\t};\n\n\tbool paramreset_successful = false;\n\tint fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\n\tif (fd > 0) {\n\t\tif (PX4_OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\tparamreset_successful = true;\n\n\t\t} else {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset zero failed\");\n\t\t}\n\n\t\tpx4_close(fd);\n\t}\n\n\tint cancel_sub = calibrate_cancel_subscribe();\n\n\tif (!paramreset_successful) {\n\n\t\t\/* only warn if analog scaling is zero *\/\n\t\tfloat analog_scaling = 0.0f;\n\t\tparam_get(param_find(\"SENS_DPRES_ANSC\"), &(analog_scaling));\n\t\tif (fabsf(analog_scaling) < 0.1f) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] No airspeed sensor, see http:\/\/px4.io\/help\/aspd\");\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* set scaling offset parameter *\/\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Ensure sensor is not measuring wind\");\n\tusleep(500 * 1000);\n\n\twhile (calibration_counter < calibration_count) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tdiff_pres_offset += diff_pres.differential_pressure_raw_pa;\n\t\t\tcalibration_counter++;\n\n\t\t\t\/* any differential pressure failure a reason to abort *\/\n\t\t\tif (diff_pres.error_count != 0) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] Airspeed sensor is reporting errors (%d)\", diff_pres.error_count);\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] Check your wiring before trying again\");\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\t\t\t}\n\n\t\t\tif (calibration_counter % (calibration_count \/ 20) == 0) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) \/ calibration_count);\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tdiff_pres_offset = diff_pres_offset \/ calibration_count;\n\n\tif (PX4_ISFINITE(diff_pres_offset)) {\n\n\t\tint fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);\n\t\tairscale.offset_pa = diff_pres_offset;\n\t\tif (fd_scale > 0) {\n\t\t\tif (PX4_OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, \"[cal] airspeed offset update failed\");\n\t\t\t}\n\n\t\t\tpx4_close(fd_scale);\n\t\t}\n\n\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* auto-save to EEPROM *\/\n\t\tint save_ret = param_save_default();\n\n\t\tif (save_ret != 0) {\n\t\t\twarn(\"WARNING: auto-save of params to storage failed\");\n\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SAVE_PARAMS_MSG);\n\t\t\tgoto error_return;\n\t\t}\n\n\t} else {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Offset of %d Pascal\", (int)diff_pres_offset);\n\n\t\/* wait 500 ms to ensure parameter propagated through the system *\/\n\tusleep(500 * 1000);\n\n\tcalibration_log_critical(mavlink_log_pub, \"[cal] Blow across front of pitot without touching\");\n\n\tcalibration_counter = 0;\n\n\t\/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds *\/\n\twhile (calibration_counter < maxcount) {\n\n\t\tif (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {\n\t\t\tgoto error_return;\n\t\t}\n\n\t\t\/* wait blocking for new data *\/\n\t\tpx4_pollfd_struct_t fds[1];\n\t\tfds[0].fd = diff_pres_sub;\n\t\tfds[0].events = POLLIN;\n\n\t\tint poll_ret = px4_poll(fds, 1, 1000);\n\n\t\tif (poll_ret) {\n\t\t\torb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);\n\n\t\t\tcalibration_counter++;\n\n\t\t\tif (fabsf(diff_pres.differential_pressure_raw_pa) < 50.0f) {\n\t\t\t\tif (calibration_counter % 500 == 0) {\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Create air pressure! (got %d, wanted: 50 Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/* do not allow negative values *\/\n\t\t\tif (diff_pres.differential_pressure_raw_pa < 0.0f) {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Negative pressure difference detected (%d Pa)\",\n\t\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Swap static and dynamic ports!\");\n\n\t\t\t\t\/* the user setup is wrong, wipe the calibration to force a proper re-calibration *\/\n\n\t\t\t\tdiff_pres_offset = 0.0f;\n\t\t\t\tif (param_set(param_find(\"SENS_DPRES_OFF\"), &(diff_pres_offset))) {\n\t\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG, 1);\n\t\t\t\t\tgoto error_return;\n\t\t\t\t}\n\n\t\t\t\t\/* save *\/\n\t\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);\n\t\t\t\t(void)param_save_default();\n\n\t\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\t\tgoto error_return;\n\n\t\t\t} else {\n\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Positive pressure: OK (%d Pa)\",\n\t\t\t\t\t(int)diff_pres.differential_pressure_raw_pa);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (poll_ret == 0) {\n\t\t\t\/* any poll failure for 1s is a reason to abort *\/\n\t\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\t\tgoto error_return;\n\t\t}\n\t}\n\n\tif (calibration_counter == maxcount) {\n\t\tfeedback_calibration_failed(mavlink_log_pub);\n\t\tgoto error_return;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);\n\ttune_neutral(true);\n\n\t\/* Wait 2sec for the airflow to stop and ensure the driver filter has caught up, otherwise\n\t * the followup preflight checks might fail. *\/\n\tusleep(2e6);\n\nnormal_return:\n\tcalibrate_cancel_unsubscribe(cancel_sub);\n\tpx4_close(diff_pres_sub);\n\n\t\/\/ This give a chance for the log messages to go out of the queue before someone else stomps on then\n\tsleep(1);\n\n\treturn result;\n\nerror_return:\n\tresult = PX4_ERROR;\n\tgoto normal_return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: eth_linux.cc,v 1.20 2004\/10\/07 17:38:03 vruppert Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/ Peter Grehan (grehan@iprg.nokia.com) coded all of this\n\/\/ NE2000\/ether stuff.\n\n\/\/ eth_linux.cc - A Linux socket filter adaptation of the FreeBSD BPF driver\n\/\/ <splite@purdue.edu> 21 June 2001\n\/\/\n\/\/ Problems and limitations:\n\/\/ - packets cannot be sent from BOCHS to the host\n\/\/ - Linux kernel sometimes gets network watchdog timeouts under emulation\n\/\/ - author doesn't know C++\n\/\/\n\/\/ The config line in .bochsrc should look something like:\n\/\/\n\/\/ ne2k: ioaddr=0x280, irq=10, mac=00:a:b:c:1:2, ethmod=linux, ethdev=eth0\n\/\/\n\n\/\/ Define BX_PLUGGABLE in files that can be compiled into plugins. For\n\/\/ platforms that require a special tag on exported symbols, BX_PLUGGABLE \n\/\/ is used to know when we are exporting symbols and when we are importing.\n#define BX_PLUGGABLE\n \n#include \"iodev.h\"\n#if BX_NETWORKING && defined (ETH_LINUX)\n\n#include \"eth.h\"\n\n#define LOG_THIS bx_devices.pluginNE2kDevice->\n\nextern \"C\" {\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <netpacket\/packet.h>\n#include <netinet\/in.h>\n#include <net\/ethernet.h>\n#include <net\/if.h>\n#include <linux\/types.h>\n#include <linux\/filter.h>\n};\n\n#define BX_PACKET_POLL 1000 \/\/ Poll for a frame every 1000 usecs\n\n\/\/ template filter for a unicast mac address and all\n\/\/ multicast\/broadcast frames\nstatic const struct sock_filter macfilter[] = {\n BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2),\n BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xaaaaaaaa, 0, 2),\n BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 0),\n BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x0000aaaa, 2, 0),\n BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0),\n BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x01, 0, 1),\n BPF_STMT(BPF_RET, 1514),\n BPF_STMT(BPF_RET, 0),\n};\n#define BX_LSF_ICNT 8 \/\/ number of lsf instructions in macfilter\n\n#if 0\n\/\/ template filter for all frames\nstatic const struct sock_filter promiscfilter[] = {\n BPF_STMT(BPF_RET, 1514)\n};\n#endif\n\n\/\/\n\/\/ Define the class. This is private to this module\n\/\/\nclass bx_linux_pktmover_c : public eth_pktmover_c {\npublic:\n bx_linux_pktmover_c(const char *netif, \n\t\t const char *macaddr,\n\t\t eth_rx_handler_t rxh,\n\t\t void *rxarg,\n\t\t char *script);\n void sendpkt(void *buf, unsigned io_len);\n\nprivate:\n unsigned char *linux_macaddr[6];\n int fd;\n int ifindex;\n static void rx_timer_handler(void *);\n void rx_timer(void);\n int rx_timer_index;\n struct sock_filter filter[BX_LSF_ICNT];\n};\n\n\n\/\/\n\/\/ Define the static class that registers the derived pktmover class,\n\/\/ and allocates one on request.\n\/\/\nclass bx_linux_locator_c : public eth_locator_c {\npublic:\n bx_linux_locator_c(void) : eth_locator_c(\"linux\") {}\nprotected:\n eth_pktmover_c *allocate(const char *netif, \n\t\t\t const char *macaddr,\n\t\t\t eth_rx_handler_t rxh,\n\t\t\t void *rxarg, char *script) {\n return (new bx_linux_pktmover_c(netif, macaddr, rxh, rxarg, script));\n }\n} bx_linux_match;\n\n\n\/\/\n\/\/ Define the methods for the bx_linux_pktmover derived class\n\/\/\n\n\/\/ the constructor\n\/\/\nbx_linux_pktmover_c::bx_linux_pktmover_c(const char *netif, \n\t\t\t\t const char *macaddr,\n\t\t\t\t eth_rx_handler_t rxh,\n\t\t\t\t void *rxarg,\n\t\t\t\t char *script)\n{\n struct sockaddr_ll sll;\n struct packet_mreq mr;\n struct ifreq ifr;\n struct sock_fprog fp;\n\n memcpy(linux_macaddr, macaddr, 6);\n\n \/\/ Open packet socket\n \/\/\n if ((this->fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {\n if (errno == EACCES)\n BX_PANIC((\"eth_linux: must be root or have CAP_NET_RAW capability to open socket\"));\n else\n BX_PANIC((\"eth_linux: could not open socket: %s\", strerror(errno)));\n this->fd = -1;\n return;\n }\n \n \/\/ Translate interface name to index\n \/\/\n memset(&ifr, 0, sizeof(ifr));\n strcpy(ifr.ifr_name, netif);\n if (ioctl(this->fd, SIOCGIFINDEX, &ifr) == -1) {\n BX_PANIC((\"eth_linux: could not get index for interface '%s'\\n\", netif));\n close(fd);\n this->fd = -1;\n return;\n }\n this->ifindex = ifr.ifr_ifindex;\n\n\n \/\/ Bind to given interface\n \/\/\n memset(&sll, 0, sizeof(sll));\n sll.sll_family = AF_PACKET;\n sll.sll_ifindex = this->ifindex;\n if (bind(fd, (struct sockaddr *)&sll, (socklen_t)sizeof(sll)) == -1) {\n BX_PANIC((\"eth_linux: could not bind to interface '%s': %s\\n\", netif, strerror(errno)));\n close(fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Put the device into promisc mode.\n \/\/\n memset(&mr, 0, sizeof(mr));\n mr.mr_ifindex = this->ifindex;\n mr.mr_type = PACKET_MR_PROMISC;\n if (setsockopt(this->fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, (void *)&mr, (socklen_t)sizeof(mr)) == -1) {\n BX_PANIC((\"eth_linux: could not enable promisc mode: %s\\n\", strerror(errno)));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Set up non-blocking i\/o\n if (fcntl(this->fd, F_SETFL, O_NONBLOCK) == -1) {\n BX_PANIC((\"eth_linux: could not set non-blocking i\/o on socket\"));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Install a filter\n#ifdef notdef\n memcpy(&this->filter, promiscfilter, sizeof(promiscfilter));\n fp.len = 1;\n#endif\n memcpy(&this->filter, macfilter, sizeof(macfilter));\n this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 |\n (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff);\n this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff);\n fp.len = BX_LSF_ICNT;\n fp.filter = this->filter;\n BX_INFO((\"eth_linux: fp.len=%d fp.filter=%x\", fp.len, (unsigned) fp.filter));\n if (setsockopt(this->fd, SOL_SOCKET, SO_ATTACH_FILTER, &fp, sizeof(fp)) < 0) {\n BX_PANIC((\"eth_linux: could not set socket filter: %s\", strerror(errno)));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Start the rx poll \n this->rx_timer_index = \n bx_pc_system.register_timer(this, this->rx_timer_handler, BX_PACKET_POLL,\n\t\t\t\t1, 1, \"eth_linux\"); \/\/ continuous, active\n\n this->rxh = rxh;\n this->rxarg = rxarg;\n BX_INFO((\"eth_linux: enabled NE2K emulation on interface %s\", netif));\n}\n\n\/\/ the output routine - called with pre-formatted ethernet frame.\nvoid\nbx_linux_pktmover_c::sendpkt(void *buf, unsigned io_len)\n{\n int status;\n\n if (this->fd != -1) {\n status = write(this->fd, buf, io_len);\n if (status == -1)\n BX_INFO((\"eth_linux: write failed: %s\", strerror(errno)));\n }\n}\n\n\/\/ The receive poll process\nvoid\nbx_linux_pktmover_c::rx_timer_handler(void *this_ptr)\n{\n bx_linux_pktmover_c *class_ptr = (bx_linux_pktmover_c *) this_ptr;\n\n class_ptr->rx_timer();\n}\n\nvoid\nbx_linux_pktmover_c::rx_timer(void)\n{\n int nbytes = 0;\n Bit8u rxbuf[BX_PACKET_BUFSIZE]; \n struct sockaddr_ll sll;\n socklen_t fromlen;\n\n if (this->fd == -1)\n return;\n\n fromlen = sizeof(sll);\n nbytes = recvfrom(this->fd, rxbuf, sizeof(rxbuf), 0, (struct sockaddr *)&sll, &fromlen);\n\n if (nbytes == -1) {\n if (errno != EAGAIN)\n BX_INFO((\"eth_linux: error receiving packet: %s\\n\", strerror(errno)));\n return;\n }\n\n \/\/ this should be done with LSF someday\n \/\/ filter out packets sourced by us\n if (memcmp(sll.sll_addr, this->linux_macaddr, 6) == 0)\n return;\n \/\/ let through broadcast, multicast, and our mac address\n\/\/ if ((memcmp(rxbuf, broadcast_macaddr, 6) == 0) || (memcmp(rxbuf, this->linux_macaddr, 6) == 0) || rxbuf[0] & 0x01) {\n BX_DEBUG((\"eth_linux: got packet: %d bytes, dst=%x:%x:%x:%x:%x:%x, src=%x:%x:%x:%x:%x:%x\\n\", nbytes, rxbuf[0], rxbuf[1], rxbuf[2], rxbuf[3], rxbuf[4], rxbuf[5], rxbuf[6], rxbuf[7], rxbuf[8], rxbuf[9], rxbuf[10], rxbuf[11]));\n (*rxh)(rxarg, rxbuf, nbytes);\n\/\/ }\n}\n#endif \/* if BX_NETWORKING && defined ETH_LINUX *\/\n<commit_msg>- fixed compilation with x86_64 and gcc4 (SF patch #1211525 by scop)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: eth_linux.cc,v 1.21 2005\/06\/05 07:24:43 vruppert Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/ Peter Grehan (grehan@iprg.nokia.com) coded all of this\n\/\/ NE2000\/ether stuff.\n\n\/\/ eth_linux.cc - A Linux socket filter adaptation of the FreeBSD BPF driver\n\/\/ <splite@purdue.edu> 21 June 2001\n\/\/\n\/\/ Problems and limitations:\n\/\/ - packets cannot be sent from BOCHS to the host\n\/\/ - Linux kernel sometimes gets network watchdog timeouts under emulation\n\/\/ - author doesn't know C++\n\/\/\n\/\/ The config line in .bochsrc should look something like:\n\/\/\n\/\/ ne2k: ioaddr=0x280, irq=10, mac=00:a:b:c:1:2, ethmod=linux, ethdev=eth0\n\/\/\n\n\/\/ Define BX_PLUGGABLE in files that can be compiled into plugins. For\n\/\/ platforms that require a special tag on exported symbols, BX_PLUGGABLE \n\/\/ is used to know when we are exporting symbols and when we are importing.\n#define BX_PLUGGABLE\n \n#include \"iodev.h\"\n#if BX_NETWORKING && defined (ETH_LINUX)\n\n#include \"eth.h\"\n\n#define LOG_THIS bx_devices.pluginNE2kDevice->\n\nextern \"C\" {\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <netpacket\/packet.h>\n#include <netinet\/in.h>\n#include <net\/ethernet.h>\n#include <net\/if.h>\n#include <linux\/types.h>\n#include <linux\/filter.h>\n};\n\n#define BX_PACKET_POLL 1000 \/\/ Poll for a frame every 1000 usecs\n\n\/\/ template filter for a unicast mac address and all\n\/\/ multicast\/broadcast frames\nstatic const struct sock_filter macfilter[] = {\n BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2),\n BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xaaaaaaaa, 0, 2),\n BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 0),\n BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x0000aaaa, 2, 0),\n BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0),\n BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x01, 0, 1),\n BPF_STMT(BPF_RET, 1514),\n BPF_STMT(BPF_RET, 0),\n};\n#define BX_LSF_ICNT 8 \/\/ number of lsf instructions in macfilter\n\n#if 0\n\/\/ template filter for all frames\nstatic const struct sock_filter promiscfilter[] = {\n BPF_STMT(BPF_RET, 1514)\n};\n#endif\n\n\/\/\n\/\/ Define the class. This is private to this module\n\/\/\nclass bx_linux_pktmover_c : public eth_pktmover_c {\npublic:\n bx_linux_pktmover_c(const char *netif, \n\t\t const char *macaddr,\n\t\t eth_rx_handler_t rxh,\n\t\t void *rxarg,\n\t\t char *script);\n void sendpkt(void *buf, unsigned io_len);\n\nprivate:\n unsigned char *linux_macaddr[6];\n int fd;\n int ifindex;\n static void rx_timer_handler(void *);\n void rx_timer(void);\n int rx_timer_index;\n struct sock_filter filter[BX_LSF_ICNT];\n};\n\n\n\/\/\n\/\/ Define the static class that registers the derived pktmover class,\n\/\/ and allocates one on request.\n\/\/\nclass bx_linux_locator_c : public eth_locator_c {\npublic:\n bx_linux_locator_c(void) : eth_locator_c(\"linux\") {}\nprotected:\n eth_pktmover_c *allocate(const char *netif, \n\t\t\t const char *macaddr,\n\t\t\t eth_rx_handler_t rxh,\n\t\t\t void *rxarg, char *script) {\n return (new bx_linux_pktmover_c(netif, macaddr, rxh, rxarg, script));\n }\n} bx_linux_match;\n\n\n\/\/\n\/\/ Define the methods for the bx_linux_pktmover derived class\n\/\/\n\n\/\/ the constructor\n\/\/\nbx_linux_pktmover_c::bx_linux_pktmover_c(const char *netif, \n\t\t\t\t const char *macaddr,\n\t\t\t\t eth_rx_handler_t rxh,\n\t\t\t\t void *rxarg,\n\t\t\t\t char *script)\n{\n struct sockaddr_ll sll;\n struct packet_mreq mr;\n struct ifreq ifr;\n struct sock_fprog fp;\n\n memcpy(linux_macaddr, macaddr, 6);\n\n \/\/ Open packet socket\n \/\/\n if ((this->fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {\n if (errno == EACCES)\n BX_PANIC((\"eth_linux: must be root or have CAP_NET_RAW capability to open socket\"));\n else\n BX_PANIC((\"eth_linux: could not open socket: %s\", strerror(errno)));\n this->fd = -1;\n return;\n }\n \n \/\/ Translate interface name to index\n \/\/\n memset(&ifr, 0, sizeof(ifr));\n strcpy(ifr.ifr_name, netif);\n if (ioctl(this->fd, SIOCGIFINDEX, &ifr) == -1) {\n BX_PANIC((\"eth_linux: could not get index for interface '%s'\\n\", netif));\n close(fd);\n this->fd = -1;\n return;\n }\n this->ifindex = ifr.ifr_ifindex;\n\n\n \/\/ Bind to given interface\n \/\/\n memset(&sll, 0, sizeof(sll));\n sll.sll_family = AF_PACKET;\n sll.sll_ifindex = this->ifindex;\n if (bind(fd, (struct sockaddr *)&sll, (socklen_t)sizeof(sll)) == -1) {\n BX_PANIC((\"eth_linux: could not bind to interface '%s': %s\\n\", netif, strerror(errno)));\n close(fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Put the device into promisc mode.\n \/\/\n memset(&mr, 0, sizeof(mr));\n mr.mr_ifindex = this->ifindex;\n mr.mr_type = PACKET_MR_PROMISC;\n if (setsockopt(this->fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, (void *)&mr, (socklen_t)sizeof(mr)) == -1) {\n BX_PANIC((\"eth_linux: could not enable promisc mode: %s\\n\", strerror(errno)));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Set up non-blocking i\/o\n if (fcntl(this->fd, F_SETFL, O_NONBLOCK) == -1) {\n BX_PANIC((\"eth_linux: could not set non-blocking i\/o on socket\"));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Install a filter\n#ifdef notdef\n memcpy(&this->filter, promiscfilter, sizeof(promiscfilter));\n fp.len = 1;\n#endif\n memcpy(&this->filter, macfilter, sizeof(macfilter));\n this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 |\n (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff);\n this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff);\n fp.len = BX_LSF_ICNT;\n fp.filter = this->filter;\n BX_INFO((\"eth_linux: fp.len=%d fp.filter=%lx\", fp.len, (unsigned long) fp.filter));\n if (setsockopt(this->fd, SOL_SOCKET, SO_ATTACH_FILTER, &fp, sizeof(fp)) < 0) {\n BX_PANIC((\"eth_linux: could not set socket filter: %s\", strerror(errno)));\n close(this->fd);\n this->fd = -1;\n return;\n }\n\n \/\/ Start the rx poll \n this->rx_timer_index = \n bx_pc_system.register_timer(this, this->rx_timer_handler, BX_PACKET_POLL,\n\t\t\t\t1, 1, \"eth_linux\"); \/\/ continuous, active\n\n this->rxh = rxh;\n this->rxarg = rxarg;\n BX_INFO((\"eth_linux: enabled NE2K emulation on interface %s\", netif));\n}\n\n\/\/ the output routine - called with pre-formatted ethernet frame.\nvoid\nbx_linux_pktmover_c::sendpkt(void *buf, unsigned io_len)\n{\n int status;\n\n if (this->fd != -1) {\n status = write(this->fd, buf, io_len);\n if (status == -1)\n BX_INFO((\"eth_linux: write failed: %s\", strerror(errno)));\n }\n}\n\n\/\/ The receive poll process\nvoid\nbx_linux_pktmover_c::rx_timer_handler(void *this_ptr)\n{\n bx_linux_pktmover_c *class_ptr = (bx_linux_pktmover_c *) this_ptr;\n\n class_ptr->rx_timer();\n}\n\nvoid\nbx_linux_pktmover_c::rx_timer(void)\n{\n int nbytes = 0;\n Bit8u rxbuf[BX_PACKET_BUFSIZE]; \n struct sockaddr_ll sll;\n socklen_t fromlen;\n\n if (this->fd == -1)\n return;\n\n fromlen = sizeof(sll);\n nbytes = recvfrom(this->fd, rxbuf, sizeof(rxbuf), 0, (struct sockaddr *)&sll, &fromlen);\n\n if (nbytes == -1) {\n if (errno != EAGAIN)\n BX_INFO((\"eth_linux: error receiving packet: %s\\n\", strerror(errno)));\n return;\n }\n\n \/\/ this should be done with LSF someday\n \/\/ filter out packets sourced by us\n if (memcmp(sll.sll_addr, this->linux_macaddr, 6) == 0)\n return;\n \/\/ let through broadcast, multicast, and our mac address\n\/\/ if ((memcmp(rxbuf, broadcast_macaddr, 6) == 0) || (memcmp(rxbuf, this->linux_macaddr, 6) == 0) || rxbuf[0] & 0x01) {\n BX_DEBUG((\"eth_linux: got packet: %d bytes, dst=%x:%x:%x:%x:%x:%x, src=%x:%x:%x:%x:%x:%x\\n\", nbytes, rxbuf[0], rxbuf[1], rxbuf[2], rxbuf[3], rxbuf[4], rxbuf[5], rxbuf[6], rxbuf[7], rxbuf[8], rxbuf[9], rxbuf[10], rxbuf[11]));\n (*rxh)(rxarg, rxbuf, nbytes);\n\/\/ }\n}\n#endif \/* if BX_NETWORKING && defined ETH_LINUX *\/\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n\n\/\/Mitk\n#include <mitkDataNode.h>\n#include <mitkNodePredicateNot.h>\n#include <mitkNodePredicateProperty.h>\n#include <mitkIRenderingManager.h>\n\n\/\/ Qmitk\n#include \"UltrasoundSupport.h\"\n#include <QTimer>\n\n\/\/ Qt\n#include <QMessageBox>\n\n\/\/ Ultrasound\n#include \"mitkUSDevice.h\"\n#include \"QmitkUSAbstractCustomWidget.h\"\n\n#include <usModuleContext.h>\n#include <usGetModuleContext.h>\n#include \"usServiceReference.h\"\n#include \"internal\/org_mitk_gui_qt_ultrasound_Activator.h\"\n\nconst std::string UltrasoundSupport::VIEW_ID = \"org.mitk.views.ultrasoundsupport\";\n\nvoid UltrasoundSupport::SetFocus()\n{\n}\n\nvoid UltrasoundSupport::CreateQtPartControl( QWidget *parent )\n{\n m_Timer = new QTimer(this);\n\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls.setupUi( parent );\n\n connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); \/\/ Change Widget Visibilities\n connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); \/\/ Init NewDeviceWidget\n connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); \/\/ After NewDeviceWidget finished editing\n connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );\n connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );\n connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );\n connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));\n\n \/\/ Initializations\n m_Controls.m_NewVideoDeviceWidget->setVisible(false);\n std::string filter = \"(&(\" + us::ServiceConstants::OBJECTCLASS() + \"=\"\n + \"org.mitk.services.UltrasoundDevice)(\"\n + mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + \"=true))\";\n m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(\n mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter);\n\n m_Node = this->GetDataStorage()->GetNamedNode(\"US Image Stream\");\n if (m_Node.IsNull())\n {\n \/\/ Create Node for US Stream\n m_Node = mitk::DataNode::New();\n m_Node->SetName(\"US Image Stream\");\n this->GetDataStorage()->Add(m_Node);\n }\n\n m_Controls.tabWidget->setTabEnabled(1, false);\n}\n\nvoid UltrasoundSupport::OnClickedAddNewDevice()\n{\n m_Controls.m_NewVideoDeviceWidget->setVisible(true);\n m_Controls.m_DeviceManagerWidget->setVisible(false);\n m_Controls.m_Headline->setText(\"Add New Video Device:\");\n m_Controls.m_WidgetActiveDevices->setVisible(false);\n}\n\nvoid UltrasoundSupport::DisplayImage()\n{\n m_Device->Modified();\n m_Device->Update();\n\n mitk::Image::Pointer curOutput = m_Device->GetOutput();\n if (! m_ImageAlreadySetToNode && curOutput.IsNotNull() && curOutput->IsInitialized())\n {\n m_Node->SetData(curOutput);\n m_ImageAlreadySetToNode = true;\n }\n\n if ( curOutput.GetPointer() != m_Node->GetData() )\n {\n MITK_INFO << \"Data Node of the ultrasound image stream was changed by another plugin. Stop viewing.\";\n this->StopViewing();\n return;\n }\n\n this->RequestRenderWindowUpdate();\n\n if ( curOutput->GetDimension() > 1\n && (curOutput->GetDimension(0) != m_CurrentImageWidth\n || curOutput->GetDimension(1) != m_CurrentImageHeight) )\n {\n \/\/ make a reinit on the ultrasound image\n mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();\n if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() )\n {\n renderWindow->GetRenderingManager()->InitializeViews(\n curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );\n renderWindow->GetRenderingManager()->RequestUpdateAll();\n }\n\n m_CurrentImageWidth = curOutput->GetDimension(0);\n m_CurrentImageHeight = curOutput->GetDimension(1);\n }\n\n m_FrameCounter ++;\n if (m_FrameCounter == 10)\n {\n int nMilliseconds = m_Clock.restart();\n int fps = 10000.0f \/ (nMilliseconds );\n m_Controls.m_FramerateLabel->setText(\"Current Framerate: \"+ QString::number(fps) +\" FPS\");\n m_FrameCounter = 0;\n }\n}\n\nvoid UltrasoundSupport::OnClickedViewDevice()\n{\n m_FrameCounter = 0;\n \/\/ We use the activity state of the timer to determine whether we are currently viewing images\n if ( ! m_Timer->isActive() ) \/\/ Activate Imaging\n {\n this->StartViewing();\n }\n else \/\/deactivate imaging\n {\n this->StopViewing();\n }\n}\n\nvoid UltrasoundSupport::OnChangedFramerateLimit(int value)\n{\n m_Timer->setInterval(1000 \/ value);\n}\n\nvoid UltrasoundSupport::OnClickedFreezeButton()\n{\n if ( m_Device->GetIsFreezed() )\n {\n m_Device->SetIsFreezed(false);\n m_Controls.m_FreezeButton->setText(\"Freeze\");\n }\n else\n {\n m_Device->SetIsFreezed(true);\n m_Controls.m_FreezeButton->setText(\"Start Viewing Again\");\n }\n}\n\nvoid UltrasoundSupport::OnNewDeviceWidgetDone()\n{\n m_Controls.m_NewVideoDeviceWidget->setVisible(false);\n m_Controls.m_DeviceManagerWidget->setVisible(true);\n m_Controls.m_Headline->setText(\"Ultrasound Devices:\");\n m_Controls.m_WidgetActiveDevices->setVisible(true);\n}\n\nvoid UltrasoundSupport::StartViewing()\n{\n m_ImageAlreadySetToNode = false;\n\n m_Controls.tabWidget->setTabEnabled(1, true);\n m_Controls.tabWidget->setCurrentIndex(1);\n\n \/\/get device & set data node\n m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();\n if (m_Device.IsNull())\n {\n m_Timer->stop();\n return;\n }\n\n \/\/start timer\n int interval = (1000 \/ m_Controls.m_FrameRate->value());\n m_Timer->setInterval(interval);\n m_Timer->start();\n\n \/\/change UI elements\n m_Controls.m_BtnView->setText(\"Stop Viewing\");\n\n this->CreateControlWidgets();\n}\n\nvoid UltrasoundSupport::StopViewing()\n{\n m_Controls.tabWidget->setTabEnabled(1, false);\n\n this->RemoveControlWidgets();\n\n \/\/stop timer & release data\n m_Timer->stop();\n m_Node->ReleaseData();\n this->RequestRenderWindowUpdate();\n\n \/\/change UI elements\n m_Controls.m_BtnView->setText(\"Start Viewing\");\n}\n\nvoid UltrasoundSupport::CreateControlWidgets()\n{\n m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);\n\n \/\/ create b mode widget for current device\n m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, \"B Mode Controls\");\n if ( ! m_Device->GetControlInterfaceBMode() )\n {\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n\n \/\/ create doppler widget for current device\n m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, \"Doppler Controls\");\n if ( ! m_Device->GetControlInterfaceDoppler() )\n {\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n if ( pluginContext )\n {\n std::string filter = \"(ork.mitk.services.UltrasoundCustomWidget.deviceClass=\" + m_Device->GetDeviceClass() + \")\";\n\n QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );\n m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));\n\n if (m_CustomWidgetServiceReference.size() > 0)\n {\n m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>\n (m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);\n m_ControlCustomWidget->SetDevice(m_Device);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, \"Custom Controls\");\n }\n else\n {\n m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), \"Custom Controls\");\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n }\n\n \/\/ select first enabled control widget\n for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)\n {\n if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )\n {\n m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);\n break;\n }\n }\n}\n\nvoid UltrasoundSupport::RemoveControlWidgets()\n{\n \/\/ remove all control widgets from the tool box widget\n while (m_Controls.m_ToolBoxControlWidgets->count() > 0)\n {\n m_Controls.m_ToolBoxControlWidgets->removeItem(0);\n }\n\n \/\/ remove probes widget (which is not part of the tool box widget)\n m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);\n delete m_ControlProbesWidget;\n m_ControlProbesWidget = 0;\n\n delete m_ControlBModeWidget;\n m_ControlBModeWidget = 0;\n\n delete m_ControlDopplerWidget;\n m_ControlDopplerWidget = 0;\n\n \/\/ delete custom widget if it is present\n if ( m_ControlCustomWidget )\n {\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n delete m_ControlCustomWidget; m_ControlCustomWidget = 0;\n\n if ( m_CustomWidgetServiceReference.size() > 0 )\n {\n pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));\n }\n }\n}\n\nvoid UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)\n{\n if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; }\n\n ctkServiceReference service = event.getServiceReference();\n\n if ( m_Device->GetDeviceManufacturer() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MANUFACTURER).toString().toStdString()\n && m_Device->GetDeviceModel() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MODEL).toString().toStdString() )\n {\n return;\n }\n\n if ( ! m_Device->GetIsActive() && m_Timer->isActive() )\n {\n this->StopViewing();\n }\n}\n\nUltrasoundSupport::UltrasoundSupport()\n: m_ControlCustomWidget(0), m_ControlBModeWidget(0),\n m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false),\n m_CurrentImageWidth(0), m_CurrentImageHeight(0)\n{\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n\n if ( pluginContext )\n {\n \/\/ to be notified about service event of an USDevice\n pluginContext->connectServiceListener(this, \"OnDeciveServiceEvent\",\n QString::fromStdString(\"(\" + us::ServiceConstants::OBJECTCLASS() + \"=\" + us_service_interface_iid<mitk::USDevice>() + \")\"));\n }\n}\n\nUltrasoundSupport::~UltrasoundSupport()\n{\n}\n<commit_msg>Removed usage of USImageMetadata from the UltrasoundSupport plugin.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n\n\/\/Mitk\n#include <mitkDataNode.h>\n#include <mitkNodePredicateNot.h>\n#include <mitkNodePredicateProperty.h>\n#include <mitkIRenderingManager.h>\n\n\/\/ Qmitk\n#include \"UltrasoundSupport.h\"\n#include <QTimer>\n\n\/\/ Qt\n#include <QMessageBox>\n\n\/\/ Ultrasound\n#include \"mitkUSDevice.h\"\n#include \"QmitkUSAbstractCustomWidget.h\"\n\n#include <usModuleContext.h>\n#include <usGetModuleContext.h>\n#include \"usServiceReference.h\"\n#include \"internal\/org_mitk_gui_qt_ultrasound_Activator.h\"\n\nconst std::string UltrasoundSupport::VIEW_ID = \"org.mitk.views.ultrasoundsupport\";\n\nvoid UltrasoundSupport::SetFocus()\n{\n}\n\nvoid UltrasoundSupport::CreateQtPartControl( QWidget *parent )\n{\n m_Timer = new QTimer(this);\n\n \/\/ create GUI widgets from the Qt Designer's .ui file\n m_Controls.setupUi( parent );\n\n connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); \/\/ Change Widget Visibilities\n connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); \/\/ Init NewDeviceWidget\n connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); \/\/ After NewDeviceWidget finished editing\n connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );\n connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );\n connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );\n connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));\n\n \/\/ Initializations\n m_Controls.m_NewVideoDeviceWidget->setVisible(false);\n std::string filter = \"(&(\" + us::ServiceConstants::OBJECTCLASS() + \"=\"\n + \"org.mitk.services.UltrasoundDevice)(\"\n + mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + \"=true))\";\n m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(\n mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter);\n\n m_Node = this->GetDataStorage()->GetNamedNode(\"US Image Stream\");\n if (m_Node.IsNull())\n {\n \/\/ Create Node for US Stream\n m_Node = mitk::DataNode::New();\n m_Node->SetName(\"US Image Stream\");\n this->GetDataStorage()->Add(m_Node);\n }\n\n m_Controls.tabWidget->setTabEnabled(1, false);\n}\n\nvoid UltrasoundSupport::OnClickedAddNewDevice()\n{\n m_Controls.m_NewVideoDeviceWidget->setVisible(true);\n m_Controls.m_DeviceManagerWidget->setVisible(false);\n m_Controls.m_Headline->setText(\"Add New Video Device:\");\n m_Controls.m_WidgetActiveDevices->setVisible(false);\n}\n\nvoid UltrasoundSupport::DisplayImage()\n{\n m_Device->Modified();\n m_Device->Update();\n\n mitk::Image::Pointer curOutput = m_Device->GetOutput();\n if (! m_ImageAlreadySetToNode && curOutput.IsNotNull() && curOutput->IsInitialized())\n {\n m_Node->SetData(curOutput);\n m_ImageAlreadySetToNode = true;\n }\n\n if ( curOutput.GetPointer() != m_Node->GetData() )\n {\n MITK_INFO << \"Data Node of the ultrasound image stream was changed by another plugin. Stop viewing.\";\n this->StopViewing();\n return;\n }\n\n this->RequestRenderWindowUpdate();\n\n if ( curOutput->GetDimension() > 1\n && (curOutput->GetDimension(0) != m_CurrentImageWidth\n || curOutput->GetDimension(1) != m_CurrentImageHeight) )\n {\n \/\/ make a reinit on the ultrasound image\n mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();\n if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() )\n {\n renderWindow->GetRenderingManager()->InitializeViews(\n curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );\n renderWindow->GetRenderingManager()->RequestUpdateAll();\n }\n\n m_CurrentImageWidth = curOutput->GetDimension(0);\n m_CurrentImageHeight = curOutput->GetDimension(1);\n }\n\n m_FrameCounter ++;\n if (m_FrameCounter == 10)\n {\n int nMilliseconds = m_Clock.restart();\n int fps = 10000.0f \/ (nMilliseconds );\n m_Controls.m_FramerateLabel->setText(\"Current Framerate: \"+ QString::number(fps) +\" FPS\");\n m_FrameCounter = 0;\n }\n}\n\nvoid UltrasoundSupport::OnClickedViewDevice()\n{\n m_FrameCounter = 0;\n \/\/ We use the activity state of the timer to determine whether we are currently viewing images\n if ( ! m_Timer->isActive() ) \/\/ Activate Imaging\n {\n this->StartViewing();\n }\n else \/\/deactivate imaging\n {\n this->StopViewing();\n }\n}\n\nvoid UltrasoundSupport::OnChangedFramerateLimit(int value)\n{\n m_Timer->setInterval(1000 \/ value);\n}\n\nvoid UltrasoundSupport::OnClickedFreezeButton()\n{\n if ( m_Device->GetIsFreezed() )\n {\n m_Device->SetIsFreezed(false);\n m_Controls.m_FreezeButton->setText(\"Freeze\");\n }\n else\n {\n m_Device->SetIsFreezed(true);\n m_Controls.m_FreezeButton->setText(\"Start Viewing Again\");\n }\n}\n\nvoid UltrasoundSupport::OnNewDeviceWidgetDone()\n{\n m_Controls.m_NewVideoDeviceWidget->setVisible(false);\n m_Controls.m_DeviceManagerWidget->setVisible(true);\n m_Controls.m_Headline->setText(\"Ultrasound Devices:\");\n m_Controls.m_WidgetActiveDevices->setVisible(true);\n}\n\nvoid UltrasoundSupport::StartViewing()\n{\n m_ImageAlreadySetToNode = false;\n\n m_Controls.tabWidget->setTabEnabled(1, true);\n m_Controls.tabWidget->setCurrentIndex(1);\n\n \/\/get device & set data node\n m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();\n if (m_Device.IsNull())\n {\n m_Timer->stop();\n return;\n }\n\n \/\/start timer\n int interval = (1000 \/ m_Controls.m_FrameRate->value());\n m_Timer->setInterval(interval);\n m_Timer->start();\n\n \/\/change UI elements\n m_Controls.m_BtnView->setText(\"Stop Viewing\");\n\n this->CreateControlWidgets();\n}\n\nvoid UltrasoundSupport::StopViewing()\n{\n m_Controls.tabWidget->setTabEnabled(1, false);\n\n this->RemoveControlWidgets();\n\n \/\/stop timer & release data\n m_Timer->stop();\n m_Node->ReleaseData();\n this->RequestRenderWindowUpdate();\n\n \/\/change UI elements\n m_Controls.m_BtnView->setText(\"Start Viewing\");\n}\n\nvoid UltrasoundSupport::CreateControlWidgets()\n{\n m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);\n\n \/\/ create b mode widget for current device\n m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, \"B Mode Controls\");\n if ( ! m_Device->GetControlInterfaceBMode() )\n {\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n\n \/\/ create doppler widget for current device\n m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, \"Doppler Controls\");\n if ( ! m_Device->GetControlInterfaceDoppler() )\n {\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n if ( pluginContext )\n {\n std::string filter = \"(ork.mitk.services.UltrasoundCustomWidget.deviceClass=\" + m_Device->GetDeviceClass() + \")\";\n\n QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );\n m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));\n\n if (m_CustomWidgetServiceReference.size() > 0)\n {\n m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>\n (m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);\n m_ControlCustomWidget->SetDevice(m_Device);\n m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, \"Custom Controls\");\n }\n else\n {\n m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), \"Custom Controls\");\n m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);\n }\n }\n\n \/\/ select first enabled control widget\n for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)\n {\n if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )\n {\n m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);\n break;\n }\n }\n}\n\nvoid UltrasoundSupport::RemoveControlWidgets()\n{\n \/\/ remove all control widgets from the tool box widget\n while (m_Controls.m_ToolBoxControlWidgets->count() > 0)\n {\n m_Controls.m_ToolBoxControlWidgets->removeItem(0);\n }\n\n \/\/ remove probes widget (which is not part of the tool box widget)\n m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);\n delete m_ControlProbesWidget;\n m_ControlProbesWidget = 0;\n\n delete m_ControlBModeWidget;\n m_ControlBModeWidget = 0;\n\n delete m_ControlDopplerWidget;\n m_ControlDopplerWidget = 0;\n\n \/\/ delete custom widget if it is present\n if ( m_ControlCustomWidget )\n {\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n delete m_ControlCustomWidget; m_ControlCustomWidget = 0;\n\n if ( m_CustomWidgetServiceReference.size() > 0 )\n {\n pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));\n }\n }\n}\n\nvoid UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)\n{\n if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; }\n\n ctkServiceReference service = event.getServiceReference();\n\n if ( m_Device->GetManufacturer() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_MANUFACTURER)).toString().toStdString()\n && m_Device->GetName() != service.getProperty(QString::fromStdString(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME)).toString().toStdString() )\n {\n return;\n }\n\n if ( ! m_Device->GetIsActive() && m_Timer->isActive() )\n {\n this->StopViewing();\n }\n}\n\nUltrasoundSupport::UltrasoundSupport()\n: m_ControlCustomWidget(0), m_ControlBModeWidget(0),\n m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false),\n m_CurrentImageWidth(0), m_CurrentImageHeight(0)\n{\n ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();\n\n if ( pluginContext )\n {\n \/\/ to be notified about service event of an USDevice\n pluginContext->connectServiceListener(this, \"OnDeciveServiceEvent\",\n QString::fromStdString(\"(\" + us::ServiceConstants::OBJECTCLASS() + \"=\" + us_service_interface_iid<mitk::USDevice>() + \")\"));\n }\n}\n\nUltrasoundSupport::~UltrasoundSupport()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/________________________________\n\/\/ my own includes\n#include <jobs\/jobexecutor.hxx>\n#include <jobs\/job.hxx>\n#include <jobs\/joburl.hxx>\n\n#include <classes\/converter.hxx>\n#include <threadhelp\/transactionguard.hxx>\n#include <threadhelp\/readguard.hxx>\n#include <threadhelp\/writeguard.hxx>\n#include <general.h>\n#include <services.h>\n\n#include \"helper\/mischelper.hxx\"\n\n\/\/________________________________\n\/\/ interface includes\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/container\/XContainer.hpp>\n\n\/\/________________________________\n\/\/ includes of other projects\n#include <unotools\/configpathes.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <vcl\/svapp.hxx>\n\n#include <rtl\/logfile.hxx>\n\n\/\/________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/________________________________\n\/\/ non exported const\n\n\/\/________________________________\n\/\/ non exported definitions\n\n\/\/________________________________\n\/\/ declarations\n\nDEFINE_XINTERFACE_6( JobExecutor ,\n OWeakObject ,\n DIRECT_INTERFACE(css::lang::XTypeProvider ),\n DIRECT_INTERFACE(css::lang::XServiceInfo ),\n DIRECT_INTERFACE(css::task::XJobExecutor ),\n DIRECT_INTERFACE(css::container::XContainerListener ),\n DIRECT_INTERFACE(css::document::XEventListener ),\n DERIVED_INTERFACE(css::lang::XEventListener,css::document::XEventListener)\n )\n\nDEFINE_XTYPEPROVIDER_6( JobExecutor ,\n css::lang::XTypeProvider ,\n css::lang::XServiceInfo ,\n css::task::XJobExecutor ,\n css::container::XContainerListener,\n css::document::XEventListener ,\n css::lang::XEventListener\n )\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE( JobExecutor ,\n ::cppu::OWeakObject ,\n SERVICENAME_JOBEXECUTOR ,\n IMPLEMENTATIONNAME_JOBEXECUTOR\n )\n\nDEFINE_INIT_SERVICE( JobExecutor,\n {\n m_xModuleManager = css::uno::Reference< css::frame::XModuleManager >(\n m_xSMGR->createInstance(\n SERVICENAME_MODULEMANAGER ),\n css::uno::UNO_QUERY_THROW );\n\n \/*Attention\n I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()\n to create a new instance of this class by our own supported service factory.\n see macro DEFINE_XSERVICEINFO_MULTISERVICE and \"impl_initService()\" for further informations!\n *\/\n \/\/ read the list of all currently registered events inside configuration.\n \/\/ e.g. \"\/org.openoffice.Office.Jobs\/Events\/<event name>\"\n \/\/ We need it later to check if an incoming event request can be executed successfully\n \/\/ or must be rejected. It's an optimization! Of course we must implement updating of this\n \/\/ list too ... Be listener at the configuration.\n\n m_aConfig.open(ConfigAccess::E_READONLY);\n if (m_aConfig.getMode() == ConfigAccess::E_READONLY)\n {\n css::uno::Reference< css::container::XNameAccess > xRegistry(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xRegistry.is())\n m_lEvents = Converter::convert_seqOUString2OUStringList(xRegistry->getElementNames());\n\n css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xNotifier.is())\n {\n m_xConfigListener = new WeakContainerListener(this);\n xNotifier->addContainerListener(m_xConfigListener);\n }\n\n \/\/ don't close cfg here!\n \/\/ It will be done inside disposing ...\n }\n }\n )\n\n\/\/________________________________\n\n\/**\n @short standard ctor\n @descr It initialize this new instance.\n\n @param xSMGR\n reference to the uno service manager\n *\/\nJobExecutor::JobExecutor( \/*IN*\/ const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )\n : ThreadHelpBase (&Application::GetSolarMutex() )\n , ::cppu::OWeakObject ( )\n , m_xSMGR (xSMGR )\n , m_xModuleManager ( )\n , m_aConfig (xSMGR, ::rtl::OUString::createFromAscii(JobData::EVENTCFG_ROOT) )\n{\n \/\/ Don't do any reference related code here! Do it inside special\n \/\/ impl_ method() ... see DEFINE_INIT_SERVICE() macro for further informations.\n}\n\nJobExecutor::~JobExecutor()\n{\n css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xNotifier.is())\n xNotifier->removeContainerListener(m_xConfigListener);\n LOG_ASSERT(m_aConfig.getMode() == ConfigAccess::E_CLOSED, \"JobExecutor::~JobExecutor()\\nConfiguration don't send dispoing() message!\\n\")\n}\n\n\/\/________________________________\n\n\/**\n @short implementation of XJobExecutor interface\n @descr We use the given event to locate any registered job inside our configuration\n and execute it. Further we control the lifetime of it and supress\n shutdown of the office till all jobs was finished.\n\n @param sEvent\n is used to locate registered jobs\n *\/\nvoid SAL_CALL JobExecutor::trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException)\n{\n RTL_LOGFILE_CONTEXT(aLog, \"fwk (as96863) JobExecutor::trigger()\");\n\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n\n \/\/ Optimization!\n \/\/ Check if the given event name exist inside configuration and reject wrong requests.\n \/\/ This optimization supress using of the cfg api for getting event and job descriptions ...\n if (m_lEvents.find(sEvent) == m_lEvents.end())\n return;\n\n \/\/ get list of all enabled jobs\n \/\/ The called static helper methods read it from the configuration and\n \/\/ filter disabled jobs using it's time stamp values.\n css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, sEvent);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n \/\/ step over all enabled jobs and execute it\n sal_Int32 c = lJobs.getLength();\n for (sal_Int32 j=0; j<c; ++j)\n {\n \/* SAFE { *\/\n aReadLock.lock();\n\n JobData aCfg(m_xSMGR);\n aCfg.setEvent(sEvent, lJobs[j]);\n aCfg.setEnvironment(JobData::E_EXECUTION);\n\n \/*Attention!\n Jobs implements interfaces and dies by ref count!\n And freeing of such uno object is done by uno itself.\n So we have to use dynamic memory everytimes.\n *\/\n Job* pJob = new Job(m_xSMGR, css::uno::Reference< css::frame::XFrame >());\n css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY);\n pJob->setJobData(aCfg);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n pJob->execute(css::uno::Sequence< css::beans::NamedValue >());\n }\n}\n\n\/\/________________________________\n\nvoid SAL_CALL JobExecutor::notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException)\n{\n static ::rtl::OUString EVENT_ON_NEW = DECLARE_ASCII(\"OnNew\" ); \/\/ Doc UI event\n static ::rtl::OUString EVENT_ON_LOAD = DECLARE_ASCII(\"OnLoad\" ); \/\/ Doc UI event\n static ::rtl::OUString EVENT_ON_CREATE = DECLARE_ASCII(\"OnCreate\" ); \/\/ Doc API event\n static ::rtl::OUString EVENT_ON_LOAD_FINISHED = DECLARE_ASCII(\"OnLoadFinished\" ); \/\/ Doc API event\n static ::rtl::OUString EVENT_ON_DOCUMENT_OPENED = DECLARE_ASCII(\"onDocumentOpened\" ); \/\/ Job UI event : OnNew or OnLoad\n static ::rtl::OUString EVENT_ON_DOCUMENT_ADDED = DECLARE_ASCII(\"onDocumentAdded\" ); \/\/ Job API event : OnCreate or OnLoadFinished\n\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n\n ::comphelper::SequenceAsVector< JobData::TJob2DocEventBinding > lJobs;\n\n \/\/ Optimization!\n \/\/ Check if the given event name exist inside configuration and reject wrong requests.\n \/\/ This optimization supress using of the cfg api for getting event and job descriptions.\n \/\/ see using of m_lEvents.find() below ...\n\n \/\/ retrieve event context from event source\n rtl::OUString aModuleIdentifier;\n try\n {\n aModuleIdentifier = m_xModuleManager->identify( aEvent.Source );\n }\n catch( css::uno::Exception& )\n {}\n\n \/\/ Special feature: If the events \"OnNew\" or \"OnLoad\" occures - we generate our own event \"onDocumentOpened\".\n if (\n (aEvent.EventName.equals(EVENT_ON_NEW )) ||\n (aEvent.EventName.equals(EVENT_ON_LOAD))\n )\n {\n if (m_lEvents.find(EVENT_ON_DOCUMENT_OPENED) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, EVENT_ON_DOCUMENT_OPENED, lJobs);\n }\n\n \/\/ Special feature: If the events \"OnCreate\" or \"OnLoadFinished\" occures - we generate our own event \"onDocumentAdded\".\n if (\n (aEvent.EventName.equals(EVENT_ON_CREATE )) ||\n (aEvent.EventName.equals(EVENT_ON_LOAD_FINISHED))\n )\n {\n if (m_lEvents.find(EVENT_ON_DOCUMENT_ADDED) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, EVENT_ON_DOCUMENT_ADDED, lJobs);\n }\n\n \/\/ Add all jobs for \"real\" notified event too .-)\n if (m_lEvents.find(aEvent.EventName) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, aEvent.EventName, lJobs);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n \/\/ step over all enabled jobs and execute it\n ::comphelper::SequenceAsVector< JobData::TJob2DocEventBinding >::const_iterator pIt;\n for ( pIt = lJobs.begin();\n pIt != lJobs.end() ;\n ++pIt )\n {\n \/* SAFE { *\/\n aReadLock.lock();\n\n const JobData::TJob2DocEventBinding& rBinding = *pIt;\n\n JobData aCfg(m_xSMGR);\n aCfg.setEvent(rBinding.m_sDocEvent, rBinding.m_sJobName);\n aCfg.setEnvironment(JobData::E_DOCUMENTEVENT);\n\n if (!aCfg.hasCorrectContext(aModuleIdentifier))\n continue;\n\n \/*Attention!\n Jobs implements interfaces and dies by ref count!\n And freeing of such uno object is done by uno itself.\n So we have to use dynamic memory everytimes.\n *\/\n css::uno::Reference< css::frame::XModel > xModel(aEvent.Source, css::uno::UNO_QUERY);\n Job* pJob = new Job(m_xSMGR, xModel);\n css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY);\n pJob->setJobData(aCfg);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n pJob->execute(css::uno::Sequence< css::beans::NamedValue >());\n }\n}\n\n\/\/________________________________\n\nvoid SAL_CALL JobExecutor::elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException)\n{\n ::rtl::OUString sValue;\n if (aEvent.Accessor >>= sValue)\n {\n ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue);\n if (sEvent.getLength() > 0)\n {\n OUStringList::iterator pEvent = m_lEvents.find(sEvent);\n if (pEvent == m_lEvents.end())\n m_lEvents.push_back(sEvent);\n }\n }\n}\n\nvoid SAL_CALL JobExecutor::elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException)\n{\n ::rtl::OUString sValue;\n if (aEvent.Accessor >>= sValue)\n {\n ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue);\n if (sEvent.getLength() > 0)\n {\n OUStringList::iterator pEvent = m_lEvents.find(sEvent);\n if (pEvent != m_lEvents.end())\n m_lEvents.erase(pEvent);\n }\n }\n}\n\nvoid SAL_CALL JobExecutor::elementReplaced( const css::container::ContainerEvent& ) throw(css::uno::RuntimeException)\n{\n \/\/ I'm not interested on changed items :-)\n}\n\n\/\/________________________________\n\n\/** @short the used cfg changes notifier wish to be released in its reference.\n\n @descr We close our internal used configuration instance to\n free this reference.\n\n @attention For the special feature \"bind global document event broadcaster to job execution\"\n this job executor instance was registered from outside code as\n css.document.XEventListener. So it can be, that this disposing call comes from\n the global event broadcaster service. But we don't hold any reference to this service\n which can or must be released. Because this broadcaster itself is an one instance service\n too, we can ignore this request. On the other side we must relase our internal CFG\n reference ... SOLUTION => check the given event source and react only, if it's our internal\n hold configuration object!\n *\/\nvoid SAL_CALL JobExecutor::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)\n{\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n css::uno::Reference< css::uno::XInterface > xCFG(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (\n (xCFG == aEvent.Source ) &&\n (m_aConfig.getMode() != ConfigAccess::E_CLOSED)\n )\n {\n m_aConfig.close();\n }\n aReadLock.unlock();\n \/* } SAFE *\/\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>don't annoy us<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/________________________________\n\/\/ my own includes\n#include <jobs\/jobexecutor.hxx>\n#include <jobs\/job.hxx>\n#include <jobs\/joburl.hxx>\n\n#include <classes\/converter.hxx>\n#include <threadhelp\/transactionguard.hxx>\n#include <threadhelp\/readguard.hxx>\n#include <threadhelp\/writeguard.hxx>\n#include <general.h>\n#include <services.h>\n\n#include \"helper\/mischelper.hxx\"\n\n\/\/________________________________\n\/\/ interface includes\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/container\/XContainer.hpp>\n\n\/\/________________________________\n\/\/ includes of other projects\n#include <unotools\/configpathes.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <vcl\/svapp.hxx>\n\n#include <rtl\/logfile.hxx>\n\n\/\/________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/________________________________\n\/\/ non exported const\n\n\/\/________________________________\n\/\/ non exported definitions\n\n\/\/________________________________\n\/\/ declarations\n\nDEFINE_XINTERFACE_6( JobExecutor ,\n OWeakObject ,\n DIRECT_INTERFACE(css::lang::XTypeProvider ),\n DIRECT_INTERFACE(css::lang::XServiceInfo ),\n DIRECT_INTERFACE(css::task::XJobExecutor ),\n DIRECT_INTERFACE(css::container::XContainerListener ),\n DIRECT_INTERFACE(css::document::XEventListener ),\n DERIVED_INTERFACE(css::lang::XEventListener,css::document::XEventListener)\n )\n\nDEFINE_XTYPEPROVIDER_6( JobExecutor ,\n css::lang::XTypeProvider ,\n css::lang::XServiceInfo ,\n css::task::XJobExecutor ,\n css::container::XContainerListener,\n css::document::XEventListener ,\n css::lang::XEventListener\n )\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE( JobExecutor ,\n ::cppu::OWeakObject ,\n SERVICENAME_JOBEXECUTOR ,\n IMPLEMENTATIONNAME_JOBEXECUTOR\n )\n\nDEFINE_INIT_SERVICE( JobExecutor,\n {\n m_xModuleManager = css::uno::Reference< css::frame::XModuleManager >(\n m_xSMGR->createInstance(\n SERVICENAME_MODULEMANAGER ),\n css::uno::UNO_QUERY_THROW );\n\n \/*Attention\n I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()\n to create a new instance of this class by our own supported service factory.\n see macro DEFINE_XSERVICEINFO_MULTISERVICE and \"impl_initService()\" for further informations!\n *\/\n \/\/ read the list of all currently registered events inside configuration.\n \/\/ e.g. \"\/org.openoffice.Office.Jobs\/Events\/<event name>\"\n \/\/ We need it later to check if an incoming event request can be executed successfully\n \/\/ or must be rejected. It's an optimization! Of course we must implement updating of this\n \/\/ list too ... Be listener at the configuration.\n\n m_aConfig.open(ConfigAccess::E_READONLY);\n if (m_aConfig.getMode() == ConfigAccess::E_READONLY)\n {\n css::uno::Reference< css::container::XNameAccess > xRegistry(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xRegistry.is())\n m_lEvents = Converter::convert_seqOUString2OUStringList(xRegistry->getElementNames());\n\n css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xNotifier.is())\n {\n m_xConfigListener = new WeakContainerListener(this);\n xNotifier->addContainerListener(m_xConfigListener);\n }\n\n \/\/ don't close cfg here!\n \/\/ It will be done inside disposing ...\n }\n }\n )\n\n\/\/________________________________\n\n\/**\n @short standard ctor\n @descr It initialize this new instance.\n\n @param xSMGR\n reference to the uno service manager\n *\/\nJobExecutor::JobExecutor( \/*IN*\/ const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )\n : ThreadHelpBase (&Application::GetSolarMutex() )\n , ::cppu::OWeakObject ( )\n , m_xSMGR (xSMGR )\n , m_xModuleManager ( )\n , m_aConfig (xSMGR, ::rtl::OUString::createFromAscii(JobData::EVENTCFG_ROOT) )\n{\n \/\/ Don't do any reference related code here! Do it inside special\n \/\/ impl_ method() ... see DEFINE_INIT_SERVICE() macro for further informations.\n}\n\nJobExecutor::~JobExecutor()\n{\n css::uno::Reference< css::container::XContainer > xNotifier(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (xNotifier.is())\n xNotifier->removeContainerListener(m_xConfigListener);\n}\n\n\/\/________________________________\n\n\/**\n @short implementation of XJobExecutor interface\n @descr We use the given event to locate any registered job inside our configuration\n and execute it. Further we control the lifetime of it and supress\n shutdown of the office till all jobs was finished.\n\n @param sEvent\n is used to locate registered jobs\n *\/\nvoid SAL_CALL JobExecutor::trigger( const ::rtl::OUString& sEvent ) throw(css::uno::RuntimeException)\n{\n RTL_LOGFILE_CONTEXT(aLog, \"fwk (as96863) JobExecutor::trigger()\");\n\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n\n \/\/ Optimization!\n \/\/ Check if the given event name exist inside configuration and reject wrong requests.\n \/\/ This optimization supress using of the cfg api for getting event and job descriptions ...\n if (m_lEvents.find(sEvent) == m_lEvents.end())\n return;\n\n \/\/ get list of all enabled jobs\n \/\/ The called static helper methods read it from the configuration and\n \/\/ filter disabled jobs using it's time stamp values.\n css::uno::Sequence< ::rtl::OUString > lJobs = JobData::getEnabledJobsForEvent(m_xSMGR, sEvent);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n \/\/ step over all enabled jobs and execute it\n sal_Int32 c = lJobs.getLength();\n for (sal_Int32 j=0; j<c; ++j)\n {\n \/* SAFE { *\/\n aReadLock.lock();\n\n JobData aCfg(m_xSMGR);\n aCfg.setEvent(sEvent, lJobs[j]);\n aCfg.setEnvironment(JobData::E_EXECUTION);\n\n \/*Attention!\n Jobs implements interfaces and dies by ref count!\n And freeing of such uno object is done by uno itself.\n So we have to use dynamic memory everytimes.\n *\/\n Job* pJob = new Job(m_xSMGR, css::uno::Reference< css::frame::XFrame >());\n css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY);\n pJob->setJobData(aCfg);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n pJob->execute(css::uno::Sequence< css::beans::NamedValue >());\n }\n}\n\n\/\/________________________________\n\nvoid SAL_CALL JobExecutor::notifyEvent( const css::document::EventObject& aEvent ) throw(css::uno::RuntimeException)\n{\n static ::rtl::OUString EVENT_ON_NEW = DECLARE_ASCII(\"OnNew\" ); \/\/ Doc UI event\n static ::rtl::OUString EVENT_ON_LOAD = DECLARE_ASCII(\"OnLoad\" ); \/\/ Doc UI event\n static ::rtl::OUString EVENT_ON_CREATE = DECLARE_ASCII(\"OnCreate\" ); \/\/ Doc API event\n static ::rtl::OUString EVENT_ON_LOAD_FINISHED = DECLARE_ASCII(\"OnLoadFinished\" ); \/\/ Doc API event\n static ::rtl::OUString EVENT_ON_DOCUMENT_OPENED = DECLARE_ASCII(\"onDocumentOpened\" ); \/\/ Job UI event : OnNew or OnLoad\n static ::rtl::OUString EVENT_ON_DOCUMENT_ADDED = DECLARE_ASCII(\"onDocumentAdded\" ); \/\/ Job API event : OnCreate or OnLoadFinished\n\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n\n ::comphelper::SequenceAsVector< JobData::TJob2DocEventBinding > lJobs;\n\n \/\/ Optimization!\n \/\/ Check if the given event name exist inside configuration and reject wrong requests.\n \/\/ This optimization supress using of the cfg api for getting event and job descriptions.\n \/\/ see using of m_lEvents.find() below ...\n\n \/\/ retrieve event context from event source\n rtl::OUString aModuleIdentifier;\n try\n {\n aModuleIdentifier = m_xModuleManager->identify( aEvent.Source );\n }\n catch( css::uno::Exception& )\n {}\n\n \/\/ Special feature: If the events \"OnNew\" or \"OnLoad\" occures - we generate our own event \"onDocumentOpened\".\n if (\n (aEvent.EventName.equals(EVENT_ON_NEW )) ||\n (aEvent.EventName.equals(EVENT_ON_LOAD))\n )\n {\n if (m_lEvents.find(EVENT_ON_DOCUMENT_OPENED) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, EVENT_ON_DOCUMENT_OPENED, lJobs);\n }\n\n \/\/ Special feature: If the events \"OnCreate\" or \"OnLoadFinished\" occures - we generate our own event \"onDocumentAdded\".\n if (\n (aEvent.EventName.equals(EVENT_ON_CREATE )) ||\n (aEvent.EventName.equals(EVENT_ON_LOAD_FINISHED))\n )\n {\n if (m_lEvents.find(EVENT_ON_DOCUMENT_ADDED) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, EVENT_ON_DOCUMENT_ADDED, lJobs);\n }\n\n \/\/ Add all jobs for \"real\" notified event too .-)\n if (m_lEvents.find(aEvent.EventName) != m_lEvents.end())\n JobData::appendEnabledJobsForEvent(m_xSMGR, aEvent.EventName, lJobs);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n \/\/ step over all enabled jobs and execute it\n ::comphelper::SequenceAsVector< JobData::TJob2DocEventBinding >::const_iterator pIt;\n for ( pIt = lJobs.begin();\n pIt != lJobs.end() ;\n ++pIt )\n {\n \/* SAFE { *\/\n aReadLock.lock();\n\n const JobData::TJob2DocEventBinding& rBinding = *pIt;\n\n JobData aCfg(m_xSMGR);\n aCfg.setEvent(rBinding.m_sDocEvent, rBinding.m_sJobName);\n aCfg.setEnvironment(JobData::E_DOCUMENTEVENT);\n\n if (!aCfg.hasCorrectContext(aModuleIdentifier))\n continue;\n\n \/*Attention!\n Jobs implements interfaces and dies by ref count!\n And freeing of such uno object is done by uno itself.\n So we have to use dynamic memory everytimes.\n *\/\n css::uno::Reference< css::frame::XModel > xModel(aEvent.Source, css::uno::UNO_QUERY);\n Job* pJob = new Job(m_xSMGR, xModel);\n css::uno::Reference< css::uno::XInterface > xJob(static_cast< ::cppu::OWeakObject* >(pJob), css::uno::UNO_QUERY);\n pJob->setJobData(aCfg);\n\n aReadLock.unlock();\n \/* } SAFE *\/\n\n pJob->execute(css::uno::Sequence< css::beans::NamedValue >());\n }\n}\n\n\/\/________________________________\n\nvoid SAL_CALL JobExecutor::elementInserted( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException)\n{\n ::rtl::OUString sValue;\n if (aEvent.Accessor >>= sValue)\n {\n ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue);\n if (sEvent.getLength() > 0)\n {\n OUStringList::iterator pEvent = m_lEvents.find(sEvent);\n if (pEvent == m_lEvents.end())\n m_lEvents.push_back(sEvent);\n }\n }\n}\n\nvoid SAL_CALL JobExecutor::elementRemoved ( const css::container::ContainerEvent& aEvent ) throw(css::uno::RuntimeException)\n{\n ::rtl::OUString sValue;\n if (aEvent.Accessor >>= sValue)\n {\n ::rtl::OUString sEvent = ::utl::extractFirstFromConfigurationPath(sValue);\n if (sEvent.getLength() > 0)\n {\n OUStringList::iterator pEvent = m_lEvents.find(sEvent);\n if (pEvent != m_lEvents.end())\n m_lEvents.erase(pEvent);\n }\n }\n}\n\nvoid SAL_CALL JobExecutor::elementReplaced( const css::container::ContainerEvent& ) throw(css::uno::RuntimeException)\n{\n \/\/ I'm not interested on changed items :-)\n}\n\n\/\/________________________________\n\n\/** @short the used cfg changes notifier wish to be released in its reference.\n\n @descr We close our internal used configuration instance to\n free this reference.\n\n @attention For the special feature \"bind global document event broadcaster to job execution\"\n this job executor instance was registered from outside code as\n css.document.XEventListener. So it can be, that this disposing call comes from\n the global event broadcaster service. But we don't hold any reference to this service\n which can or must be released. Because this broadcaster itself is an one instance service\n too, we can ignore this request. On the other side we must relase our internal CFG\n reference ... SOLUTION => check the given event source and react only, if it's our internal\n hold configuration object!\n *\/\nvoid SAL_CALL JobExecutor::disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException)\n{\n \/* SAFE { *\/\n ReadGuard aReadLock(m_aLock);\n css::uno::Reference< css::uno::XInterface > xCFG(m_aConfig.cfg(), css::uno::UNO_QUERY);\n if (\n (xCFG == aEvent.Source ) &&\n (m_aConfig.getMode() != ConfigAccess::E_CLOSED)\n )\n {\n m_aConfig.close();\n }\n aReadLock.unlock();\n \/* } SAFE *\/\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_OPENCL_KERNELS_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_OPENCL_KERNELS_CHOLESKY_DECOMPOSE_HPP\n#ifdef STAN_OPENCL\n\n#include <stan\/math\/opencl\/kernel_cl.hpp>\n#include <stan\/math\/opencl\/buffer_types.hpp>\n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\/\/ \\cond\nstatic const char *cholesky_decompose_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/**\n * Calculates the Cholesky Decomposition of a matrix on an OpenCL\n *\n * This kernel is run with threads organized in one dimension and\n * in a single thread block. The kernel is best suited for\n * small input matrices as it only utilizes a single streaming\n * multiprocessor. The kernels is used as a part of a blocked\n * cholesky decompose.\n *\n * @param[in, out] A The input matrix and the result of the cholesky\n * decompisition\n * @param rows The number of rows for A and B.\n * @note Code is a <code>const char*<\/code> held in\n * <code>cholesky_decompose_kernel_code.<\/code>\n * Used in math\/opencl\/cholesky_decompose.hpp.\n * This kernel uses the helper macros available in helpers.cl.\n *\n *\/\n __kernel void cholesky_decompose(__global double *A, int rows) {\n const int local_index = get_local_id(0);\n \/\/ The following code is the sequential version of the inplace\n \/\/ cholesky decomposition. Only the innermost loops are parallelized. The\n \/\/ rows are processed sequentially. This loop process all the rows:\n for (int j = 0; j < rows; j++) {\n if (local_index == 0) {\n double sum = 0.0;\n for (int k = 0; k < j; k++) {\n sum = sum + A(j, k) * A(j, k);\n }\n A(j, j) = sqrt(A(j, j) - sum);\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n if (local_index < j) {\n A(local_index, j) = 0.0;\n } else if (local_index > j) {\n double sum = 0.0;\n for (int k = 0; k < j; k++)\n sum = sum + A(local_index, k) * A(j, k);\n A(local_index, j) = (A(local_index, j) - sum) \/ A(j, j);\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/cholesky_decompose.hpp cholesky_decompose()\n * \\endlink\n *\/\nconst kernel_cl<out_buffer, int> cholesky_decompose(\n \"cholesky_decompose\", {indexing_helpers, cholesky_decompose_kernel_code});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n#endif\n<commit_msg>Fix typo<commit_after>#ifndef STAN_MATH_OPENCL_KERNELS_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_OPENCL_KERNELS_CHOLESKY_DECOMPOSE_HPP\n#ifdef STAN_OPENCL\n\n#include <stan\/math\/opencl\/kernel_cl.hpp>\n#include <stan\/math\/opencl\/buffer_types.hpp>\n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\/\/ \\cond\nstatic const char *cholesky_decompose_kernel_code = STRINGIFY(\n \/\/ \\endcond\n \/**\n * Calculates the Cholesky Decomposition of a matrix on an OpenCL\n *\n * This kernel is run with threads organized in one dimension and\n * in a single thread block. The kernel is best suited for\n * small input matrices as it only utilizes a single streaming\n * multiprocessor. The kernels is used as a part of a blocked\n * cholesky decompose.\n *\n * @param[in, out] A The input matrix and the result of the cholesky\n * decomposition\n * @param rows The number of rows for A and B.\n * @note Code is a <code>const char*<\/code> held in\n * <code>cholesky_decompose_kernel_code.<\/code>\n * Used in math\/opencl\/cholesky_decompose.hpp.\n * This kernel uses the helper macros available in helpers.cl.\n *\n *\/\n __kernel void cholesky_decompose(__global double *A, int rows) {\n const int local_index = get_local_id(0);\n \/\/ The following code is the sequential version of the inplace\n \/\/ cholesky decomposition. Only the innermost loops are parallelized. The\n \/\/ rows are processed sequentially. This loop process all the rows:\n for (int j = 0; j < rows; j++) {\n if (local_index == 0) {\n double sum = 0.0;\n for (int k = 0; k < j; k++) {\n sum = sum + A(j, k) * A(j, k);\n }\n A(j, j) = sqrt(A(j, j) - sum);\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n if (local_index < j) {\n A(local_index, j) = 0.0;\n } else if (local_index > j) {\n double sum = 0.0;\n for (int k = 0; k < j; k++)\n sum = sum + A(local_index, k) * A(j, k);\n A(local_index, j) = (A(local_index, j) - sum) \/ A(j, j);\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/cholesky_decompose.hpp cholesky_decompose()\n * \\endlink\n *\/\nconst kernel_cl<out_buffer, int> cholesky_decompose(\n \"cholesky_decompose\", {indexing_helpers, cholesky_decompose_kernel_code});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"mmu.h\"\n#include \"atomic.hh\"\n#ifndef XV6_USER\n\/\/ XXX(Austin) lib\/wqalloc.c includes percpu, which includes cpu.hh.\n\/\/ I don't understand at all how percpu works in user space, but\n\/\/ spinlock definitely doesn't work in user space.\n#include \"spinlock.h\"\n#endif\n\nusing std::atomic;\n\n\/\/ Per-CPU state\nstruct cpu {\n cpuid_t id; \/\/ Index into cpus[] below\n int ncli; \/\/ Depth of pushcli nesting.\n int intena; \/\/ Were interrupts enabled before pushcli?\n struct segdesc gdt[NSEGS]; \/\/ x86 global descriptor table\n struct taskstate ts; \/\/ Used by x86 to find stack for interrupt\n struct context *scheduler; \/\/ swtch() here to enter scheduler\n\n int timer_printpc;\n atomic<u64> tlbflush_done; \/\/ last tlb flush req done on this cpu\n struct proc *prev; \/\/ The previously-running process\n atomic<struct proc*> fpu_owner; \/\/ The proc with the current FPU state\n\n#ifndef XV6_USER\n \/\/ The list of IPI calls to this CPU\n atomic<struct ipi_call *> ipi __mpalign__;\n atomic<struct ipi_call *> *ipi_tail;\n \/\/ The lock protecting updates to ipi and ipi_tail.\n spinlock ipi_lock;\n#endif\n\n hwid_t hwid __mpalign__; \/\/ Local APIC ID, accessed by other CPUs\n\n \/\/ Cpu-local storage variables; see below\n struct cpu *cpu;\n struct proc *proc; \/\/ The currently-running process.\n struct cpu_mem *mem; \/\/ The per-core memory metadata\n u64 syscallno; \/\/ Temporary used by sysentry\n struct kstats *kstats;\n} __mpalign__;\n\nextern struct cpu cpus[NCPU];\n\n\/\/ Per-CPU variables, holding pointers to the\n\/\/ current cpu and to the current process.\n\/\/ XXX(sbw) asm labels default to RIP-relative and\n\/\/ I don't know how to force absolute addressing.\nstatic inline struct cpu *\nmycpu(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:0, %0\" : \"=r\" (val));\n return (struct cpu *)val;\n}\n\nstatic inline struct proc *\nmyproc(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:8, %0\" : \"=r\" (val));\n return (struct proc *)val;\n}\n\nstatic inline struct kmem *\nmykmem(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:16, %0\" : \"=r\" (val));\n return (struct kmem *)val;\n}\n\nstatic inline struct kstats *\nmykstats(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:(8*4), %0\" : \"=r\" (val));\n return (struct kstats *)val;\n}\n\nstatic inline cpuid_t\nmyid(void)\n{\n return mycpu()->id;\n}\n<commit_msg>cpu: Remove now unnecessary hacks<commit_after>#pragma once\n\n#include \"mmu.h\"\n#include \"atomic.hh\"\n#include \"spinlock.h\"\n\nusing std::atomic;\n\n\/\/ Per-CPU state\nstruct cpu {\n cpuid_t id; \/\/ Index into cpus[] below\n int ncli; \/\/ Depth of pushcli nesting.\n int intena; \/\/ Were interrupts enabled before pushcli?\n struct segdesc gdt[NSEGS]; \/\/ x86 global descriptor table\n struct taskstate ts; \/\/ Used by x86 to find stack for interrupt\n struct context *scheduler; \/\/ swtch() here to enter scheduler\n\n int timer_printpc;\n atomic<u64> tlbflush_done; \/\/ last tlb flush req done on this cpu\n struct proc *prev; \/\/ The previously-running process\n atomic<struct proc*> fpu_owner; \/\/ The proc with the current FPU state\n\n \/\/ The list of IPI calls to this CPU\n atomic<struct ipi_call *> ipi __mpalign__;\n atomic<struct ipi_call *> *ipi_tail;\n \/\/ The lock protecting updates to ipi and ipi_tail.\n spinlock ipi_lock;\n\n hwid_t hwid __mpalign__; \/\/ Local APIC ID, accessed by other CPUs\n\n \/\/ Cpu-local storage variables; see below\n struct cpu *cpu;\n struct proc *proc; \/\/ The currently-running process.\n struct cpu_mem *mem; \/\/ The per-core memory metadata\n u64 syscallno; \/\/ Temporary used by sysentry\n struct kstats *kstats;\n} __mpalign__;\n\nextern struct cpu cpus[NCPU];\n\n\/\/ Per-CPU variables, holding pointers to the\n\/\/ current cpu and to the current process.\n\/\/ XXX(sbw) asm labels default to RIP-relative and\n\/\/ I don't know how to force absolute addressing.\nstatic inline struct cpu *\nmycpu(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:0, %0\" : \"=r\" (val));\n return (struct cpu *)val;\n}\n\nstatic inline struct proc *\nmyproc(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:8, %0\" : \"=r\" (val));\n return (struct proc *)val;\n}\n\nstatic inline struct kmem *\nmykmem(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:16, %0\" : \"=r\" (val));\n return (struct kmem *)val;\n}\n\nstatic inline struct kstats *\nmykstats(void)\n{\n u64 val;\n __asm volatile(\"movq %%gs:(8*4), %0\" : \"=r\" (val));\n return (struct kstats *)val;\n}\n\nstatic inline cpuid_t\nmyid(void)\n{\n return mycpu()->id;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2013 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file opt_flip_matrices.cpp\n *\n * Convert (matrix * vector) operations to (vector * matrixTranspose),\n * which can be done using dot products rather than multiplies and adds.\n * On some hardware, this is more efficient.\n *\n * This currently only does the conversion for built-in matrices which\n * already have transposed equivalents. Namely, gl_ModelViewProjectionMatrix\n * and gl_TextureMatrix.\n *\/\n#include \"ir.h\"\n#include \"ir_optimization.h\"\n#include \"main\/macros.h\"\n\nnamespace {\nclass matrix_flipper : public ir_hierarchical_visitor {\npublic:\n matrix_flipper(exec_list *instructions)\n {\n progress = false;\n mvp_transpose = NULL;\n texmat_transpose = NULL;\n\n foreach_list(n, instructions) {\n ir_instruction *ir = (ir_instruction *) n;\n ir_variable *var = ir->as_variable();\n if (!var)\n continue;\n if (strcmp(var->name, \"gl_ModelViewProjectionMatrixTranspose\") == 0)\n mvp_transpose = var;\n if (strcmp(var->name, \"gl_TextureMatrixTranspose\") == 0)\n texmat_transpose = var;\n }\n }\n\n ir_visitor_status visit_enter(ir_expression *ir);\n\n bool progress;\n\nprivate:\n ir_variable *mvp_transpose;\n ir_variable *texmat_transpose;\n};\n}\n\nir_visitor_status\nmatrix_flipper::visit_enter(ir_expression *ir)\n{\n if (ir->operation != ir_binop_mul ||\n !ir->operands[0]->type->is_matrix() ||\n !ir->operands[1]->type->is_vector())\n return visit_continue;\n\n ir_variable *mat_var = ir->operands[0]->variable_referenced();\n if (!mat_var)\n return visit_continue;\n\n if (mvp_transpose &&\n strcmp(mat_var->name, \"gl_ModelViewProjectionMatrix\") == 0) {\n ir_dereference_variable *deref = ir->operands[0]->as_dereference_variable();\n assert(deref && deref->var == mat_var);\n\n void *mem_ctx = ralloc_parent(ir);\n\n ir->operands[0] = ir->operands[1];\n ir->operands[1] = new(mem_ctx) ir_dereference_variable(mvp_transpose);\n\n progress = true;\n } else if (texmat_transpose &&\n strcmp(mat_var->name, \"gl_TextureMatrix\") == 0) {\n ir_dereference_array *array_ref = ir->operands[0]->as_dereference_array();\n assert(array_ref != NULL);\n ir_dereference_variable *var_ref = array_ref->array->as_dereference_variable();\n assert(var_ref && var_ref->var == mat_var);\n\n ir->operands[0] = ir->operands[1];\n ir->operands[1] = array_ref;\n\n var_ref->var = texmat_transpose;\n\n texmat_transpose->max_array_access =\n MAX2(texmat_transpose->max_array_access, mat_var->max_array_access);\n\n progress = true;\n }\n\n return visit_continue;\n}\n\nbool\nopt_flip_matrices(struct exec_list *instructions)\n{\n matrix_flipper v(instructions);\n\n visit_list_elements(&v, instructions);\n\n return v.progress;\n}\n<commit_msg>glsl: Silence unused variable warning in the release build<commit_after>\/*\n * Copyright © 2013 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file opt_flip_matrices.cpp\n *\n * Convert (matrix * vector) operations to (vector * matrixTranspose),\n * which can be done using dot products rather than multiplies and adds.\n * On some hardware, this is more efficient.\n *\n * This currently only does the conversion for built-in matrices which\n * already have transposed equivalents. Namely, gl_ModelViewProjectionMatrix\n * and gl_TextureMatrix.\n *\/\n#include \"ir.h\"\n#include \"ir_optimization.h\"\n#include \"main\/macros.h\"\n\nnamespace {\nclass matrix_flipper : public ir_hierarchical_visitor {\npublic:\n matrix_flipper(exec_list *instructions)\n {\n progress = false;\n mvp_transpose = NULL;\n texmat_transpose = NULL;\n\n foreach_list(n, instructions) {\n ir_instruction *ir = (ir_instruction *) n;\n ir_variable *var = ir->as_variable();\n if (!var)\n continue;\n if (strcmp(var->name, \"gl_ModelViewProjectionMatrixTranspose\") == 0)\n mvp_transpose = var;\n if (strcmp(var->name, \"gl_TextureMatrixTranspose\") == 0)\n texmat_transpose = var;\n }\n }\n\n ir_visitor_status visit_enter(ir_expression *ir);\n\n bool progress;\n\nprivate:\n ir_variable *mvp_transpose;\n ir_variable *texmat_transpose;\n};\n}\n\nir_visitor_status\nmatrix_flipper::visit_enter(ir_expression *ir)\n{\n if (ir->operation != ir_binop_mul ||\n !ir->operands[0]->type->is_matrix() ||\n !ir->operands[1]->type->is_vector())\n return visit_continue;\n\n ir_variable *mat_var = ir->operands[0]->variable_referenced();\n if (!mat_var)\n return visit_continue;\n\n if (mvp_transpose &&\n strcmp(mat_var->name, \"gl_ModelViewProjectionMatrix\") == 0) {\n#ifndef NDEBUG\n ir_dereference_variable *deref = ir->operands[0]->as_dereference_variable();\n assert(deref && deref->var == mat_var);\n#endif\n\n void *mem_ctx = ralloc_parent(ir);\n\n ir->operands[0] = ir->operands[1];\n ir->operands[1] = new(mem_ctx) ir_dereference_variable(mvp_transpose);\n\n progress = true;\n } else if (texmat_transpose &&\n strcmp(mat_var->name, \"gl_TextureMatrix\") == 0) {\n ir_dereference_array *array_ref = ir->operands[0]->as_dereference_array();\n assert(array_ref != NULL);\n ir_dereference_variable *var_ref = array_ref->array->as_dereference_variable();\n assert(var_ref && var_ref->var == mat_var);\n\n ir->operands[0] = ir->operands[1];\n ir->operands[1] = array_ref;\n\n var_ref->var = texmat_transpose;\n\n texmat_transpose->max_array_access =\n MAX2(texmat_transpose->max_array_access, mat_var->max_array_access);\n\n progress = true;\n }\n\n return visit_continue;\n}\n\nbool\nopt_flip_matrices(struct exec_list *instructions)\n{\n matrix_flipper v(instructions);\n\n visit_list_elements(&v, instructions);\n\n return v.progress;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/fun\/lbeta.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/err\/check_nonnegative.hpp>\n#include <stan\/math\/prim\/err\/check_greater_or_equal.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the log of the binomial coefficient for the specified\n * arguments.\n *\n * The binomial coefficient, \\f${N \\choose n}\\f$, read \"N choose n\", is\n * defined for \\f$0 \\leq n \\leq N\\f$ by\n *\n * \\f${N \\choose n} = \\frac{N!}{n! (N-n)!}\\f$.\n *\n * This function uses Gamma functions to define the log\n * and generalize the arguments to continuous N and n.\n *\n * \\f$ \\log {N \\choose n}\n * = \\log \\ \\Gamma(N+1) - \\log \\Gamma(n+1) - \\log \\Gamma(N-n+1)\\f$.\n *\n *\n \\f[\n \\mbox{binomial\\_coefficient\\_log}(x, y) =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n \\ln\\Gamma(x+1) & \\mbox{if } -1 < y < x + 1 \\\\\n \\quad -\\ln\\Gamma(y+1)& \\\\\n \\quad -\\ln\\Gamma(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial x} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n \\Psi(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad -\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial y} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n -\\Psi(y+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad +\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n *\n * This function is numerically more stable than naive evaluation via lgamma.\n *\n * @param N total number of objects.\n * @param n number of objects chosen.\n * @return log (N choose n).\n *\/\n\ntemplate <typename T_N, typename T_n>\ninline return_type_t<T_N, T_n> binomial_coefficient_log(const T_N N,\n const T_n n) {\n if (is_nan(value_of_rec(N)) || is_nan(value_of_rec(n))) {\n return std::numeric_limits<double>::quiet_NaN();\n }\n\n \/\/ For some uses it is important this works even when N < 0 and therefore\n \/\/ it is before checks\n if (n == 0) {\n return 0;\n }\n const T_N N_plus_1 = N + 1;\n\n static const char* function = \"binomial_coefficient_log\";\n check_greater_or_equal(function, \"first argument\", N, -1);\n check_greater_or_equal(function, \"second argument\", n, -1);\n check_greater_or_equal(function, \"(first argument - second argument + 1)\",\n N - n + 1, 0.0);\n\n if (N \/ 2 < n) {\n return binomial_coefficient_log(N, N - n);\n } else if (N_plus_1 < lgamma_stirling_diff_useful) {\n return lgamma(N_plus_1) - lgamma(n + 1) - lgamma(N_plus_1 - n);\n } else {\n return -lbeta(N - n + 1, n + 1) - log(N_plus_1);\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>Mismatched define<commit_after>#ifndef STAN_MATH_PRIM_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_PRIM_FUN_BINOMIAL_COEFFICIENT_LOG_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/fun\/lbeta.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/err\/check_nonnegative.hpp>\n#include <stan\/math\/prim\/err\/check_greater_or_equal.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the log of the binomial coefficient for the specified\n * arguments.\n *\n * The binomial coefficient, \\f${N \\choose n}\\f$, read \"N choose n\", is\n * defined for \\f$0 \\leq n \\leq N\\f$ by\n *\n * \\f${N \\choose n} = \\frac{N!}{n! (N-n)!}\\f$.\n *\n * This function uses Gamma functions to define the log\n * and generalize the arguments to continuous N and n.\n *\n * \\f$ \\log {N \\choose n}\n * = \\log \\ \\Gamma(N+1) - \\log \\Gamma(n+1) - \\log \\Gamma(N-n+1)\\f$.\n *\n *\n \\f[\n \\mbox{binomial\\_coefficient\\_log}(x, y) =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n \\ln\\Gamma(x+1) & \\mbox{if } -1 < y < x + 1 \\\\\n \\quad -\\ln\\Gamma(y+1)& \\\\\n \\quad -\\ln\\Gamma(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial x} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n \\Psi(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad -\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial y} =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1 \\textrm{ or } x\n < -1\\\\\n -\\Psi(y+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad +\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n *\n * This function is numerically more stable than naive evaluation via lgamma.\n *\n * @param N total number of objects.\n * @param n number of objects chosen.\n * @return log (N choose n).\n *\/\n\ntemplate <typename T_N, typename T_n>\ninline return_type_t<T_N, T_n> binomial_coefficient_log(const T_N N,\n const T_n n) {\n if (is_nan(value_of_rec(N)) || is_nan(value_of_rec(n))) {\n return std::numeric_limits<double>::quiet_NaN();\n }\n\n \/\/ For some uses it is important this works even when N < 0 and therefore\n \/\/ it is before checks\n if (n == 0) {\n return 0;\n }\n const T_N N_plus_1 = N + 1;\n\n static const char* function = \"binomial_coefficient_log\";\n check_greater_or_equal(function, \"first argument\", N, -1);\n check_greater_or_equal(function, \"second argument\", n, -1);\n check_greater_or_equal(function, \"(first argument - second argument + 1)\",\n N - n + 1, 0.0);\n\n if (N \/ 2 < n) {\n return binomial_coefficient_log(N, N - n);\n } else if (N_plus_1 < lgamma_stirling_diff_useful) {\n return lgamma(N_plus_1) - lgamma(n + 1) - lgamma(N_plus_1 - n);\n } else {\n return -lbeta(N - n + 1, n + 1) - log(N_plus_1);\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cstring>\n#include \"halley\/support\/exception.h\"\n#include \"halley\/support\/console.h\"\n#include \"shader_opengl.h\"\n#include \"halley\/core\/graphics\/material\/material_definition.h\"\n#include \"gl_utils.h\"\n#include \"halley_gl.h\"\n\nusing namespace Halley;\n\nstatic ShaderOpenGL* currentShader = nullptr;\n\n#ifdef _MSC_VER\n#pragma warning(disable: 4996)\n#endif\n\nShaderOpenGL::ShaderOpenGL(const ShaderDefinition& definition)\n{\n\tid = glCreateProgram();\n\tglCheckError();\t\n\n\tname = definition.name;\n\tsetAttributes(definition.vertexAttributes);\n\tloadShaders(definition.shaders);\n\tcompile();\n}\n\nShaderOpenGL::~ShaderOpenGL()\n{\n\tdestroy();\n}\n\nvoid ShaderOpenGL::bind()\n{\n\tif (this != currentShader) {\n\t\tif (!ready) {\n\t\t\tcompile();\n\t\t}\n\t\tglUseProgram(id);\n\t\tglCheckError();\n\t\tcurrentShader = this;\n\t}\n}\n\nvoid ShaderOpenGL::unbind()\n{\n\tcurrentShader = nullptr;\n\tglUseProgram(0);\n\tglCheckError();\n}\n\nstatic GLuint loadShader(const Bytes& src, GLenum type, String name)\n{\n\t\/\/ Create shader\n\tGLuint shader = glCreateShader(type);\n\tglCheckError();\n\n\t\/\/ Load source\n#ifdef WITH_OPENGL_ES3\n size_t startPos = 0;\n if (src.size() >= 13 && memcmp(src.data(), \"#version 330\", 12) == 0) {\n startPos = 12;\n }\n size_t len = src.size() + 15 - startPos;\n GLchar* buffer = new GLchar[len + 1];\n memcpy(buffer, \"#version 300 es\", 15);\n memcpy(buffer + 15, src.data() + startPos, len - 15);\n buffer[len] = 0;\n#else\n\tsize_t len = src.size();\n\tGLchar* buffer = new GLchar[len + 1];\n\tmemcpy(buffer, src.data(), src.size());\n\tbuffer[len] = 0;\n#endif\n\n\t\/\/ Set source\n const char* cbuf = buffer;\n\tglShaderSource(shader, 1, &cbuf, nullptr);\n\tglCheckError();\n\n\t\/\/ Compile source\n\tglCompileShader(shader);\n\tglCheckError();\n\n\tdelete[] buffer;\n\n\t\/\/ Check result\n\t\/\/ Seriously, GL? All this crap to retrieve an info log?\n\tint result;\n\tglGetShaderiv(shader, GL_COMPILE_STATUS, &result);\n\tglCheckError();\n\tif (result == GL_FALSE) {\n\t\tint infolen;\n\t\tglGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infolen);\n\t\tglCheckError();\n\t\tchar* log = new char[infolen];\n\t\tglGetShaderInfoLog(shader, infolen, &infolen, log);\n\t\tString msg = String(\"Error compiling shader \\\"\" + name + \"\\\":\\n\") + log;\n\t\tdelete[] log;\n\t\tglCheckError();\n\t\tthrow Exception(msg, HalleyExceptions::VideoPlugin);\n\t}\n\n\treturn shader;\n}\n\nvoid ShaderOpenGL::loadShaders(const std::map<ShaderType, Bytes>& sources)\n{\n\tfor (auto& s: sources) {\n\t\tauto type = s.first;\n\t\tint glType = 0;\n\t\tswitch (type) {\n\t\tcase ShaderType::Vertex:\n\t\t\tglType = GL_VERTEX_SHADER;\n\t\t\tbreak;\n\t\tcase ShaderType::Pixel:\n\t\t\tglType = GL_FRAGMENT_SHADER;\n\t\t\tbreak;\n#ifdef WITH_OPENGL\n\t\tcase ShaderType::Geometry:\n\t\t\tglType = GL_GEOMETRY_SHADER;\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\t\tthrow Exception(\"Unsupported shader type: \" + toString(type), HalleyExceptions::VideoPlugin);\n\t\t}\n\n\t\tshaders.push_back(loadShader(s.second, glType, name + \"\/\" + toString(type)));\n\t}\n}\n\nvoid ShaderOpenGL::compile()\n{\n\tif (!ready) {\n\t\t\/\/ Create program\n\t\tfor (size_t i = 0; i<shaders.size(); i++) {\n\t\t\tglAttachShader(id, shaders[i]);\n\t\t\tglCheckError();\n\t\t}\n\t\tglLinkProgram(id);\n\t\tglCheckError();\n\n\t\t\/\/ Collect log\n\t\tint infolen;\n\t\tglGetProgramiv(id, GL_INFO_LOG_LENGTH, &infolen);\n\t\tglCheckError();\n\t\tchar* logRaw = new char[infolen + 1];\n\t\tglGetProgramInfoLog(id, infolen, &infolen, logRaw);\n\t\tlogRaw[infolen] = 0;\n\t\tString log = logRaw;\n\t\tdelete[] logRaw;\n\t\tglCheckError();\n\n\t\t\/\/ Verify result\n\t\tint result;\n\t\tglGetProgramiv(id, GL_LINK_STATUS, &result);\n\t\tglCheckError();\n\t\tif (result == GL_FALSE) {\n\t\t\tthrow Exception(\"Error loading shader: \" + log, HalleyExceptions::VideoPlugin);\n\t\t} else if (infolen > 0) {\n\t\t\tstd::cout << ConsoleColour(Console::YELLOW) << \"\\nIn shader \\\"\" << name << \"\\\":\\n==========\\n\" << log << \"\\n==========\" << ConsoleColour() << std::endl;\n\t\t}\n\n\t\tuniformLocations.clear();\n\t\tattributeLocations.clear();\n\t\tready = true;\n\t}\n}\n\nvoid ShaderOpenGL::destroy()\n{\n\tif (ready) {\n\t\tglCheckError();\n\t\tunbind();\n\t\tready = false;\n\n\t\tfor (size_t i = 0; i < shaders.size(); i++) {\n\t\t\tglDetachShader(id, shaders[i]);\n\t\t\tglCheckError();\n\t\t\tglDeleteShader(shaders[i]);\n\t\t\tglCheckError();\n\t\t}\n\t}\n\n\tif (id != 0) {\n\t\tglDeleteProgram(id);\n\t\tglCheckError();\n\t\tid = 0;\n\t}\n}\n\nvoid ShaderOpenGL::setUniformBlockBinding(unsigned int blockIndex, unsigned int binding)\n{\n\tglUniformBlockBinding(id, blockIndex, binding);\n\tglCheckError();\n}\n\nint ShaderOpenGL::getUniformLocation(const String& name, ShaderType stage)\n{\n\tif (stage != ShaderType::Combined) {\n\t\t\/\/ OpenGL doesn't support per-stage bindings\n\t\treturn -1;\n\t}\n\n\tauto i = uniformLocations.find(name);\n\tif (i != uniformLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetUniformLocation(id, name.c_str());\n\tglCheckError();\n\n\tuniformLocations[name] = result;\n\treturn int(result);\n}\n\nint ShaderOpenGL::getBlockLocation(const String& name, ShaderType stage)\n{\n\tif (stage != ShaderType::Combined) {\n\t\t\/\/ OpenGL doesn't support per-stage bindings\n\t\treturn -1;\n\t}\n\n\tauto i = blockLocations.find(name);\n\tif (i != blockLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetUniformBlockIndex(id, name.c_str());\n\tglCheckError();\n\n\tblockLocations[name] = result;\n\treturn int(result);\n}\n\nint ShaderOpenGL::getAttributeLocation(const String& name)\n{\n\tauto i = attributeLocations.find(name);\n\tif (i != attributeLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetAttribLocation(id, name.c_str());\n\tglCheckError();\n\n\tattributeLocations[name] = result;\n\treturn int(result);\n}\n\nvoid ShaderOpenGL::setAttributes(const Vector<MaterialAttribute>& attributes)\n{\n\tfor (auto& attribute : attributes) {\n\t\tglBindAttribLocation(id, attribute.location, attribute.name.c_str());\n\t\tglCheckError();\n\t}\n}\n<commit_msg>Disable attribute binding to name<commit_after>#include <cstring>\n#include \"halley\/support\/exception.h\"\n#include \"halley\/support\/console.h\"\n#include \"shader_opengl.h\"\n#include \"halley\/core\/graphics\/material\/material_definition.h\"\n#include \"gl_utils.h\"\n#include \"halley_gl.h\"\n\nusing namespace Halley;\n\nstatic ShaderOpenGL* currentShader = nullptr;\n\n#ifdef _MSC_VER\n#pragma warning(disable: 4996)\n#endif\n\nShaderOpenGL::ShaderOpenGL(const ShaderDefinition& definition)\n{\n\tid = glCreateProgram();\n\tglCheckError();\t\n\n\tname = definition.name;\n\t\/\/setAttributes(definition.vertexAttributes);\n\tloadShaders(definition.shaders);\n\tcompile();\n}\n\nShaderOpenGL::~ShaderOpenGL()\n{\n\tdestroy();\n}\n\nvoid ShaderOpenGL::bind()\n{\n\tif (this != currentShader) {\n\t\tif (!ready) {\n\t\t\tcompile();\n\t\t}\n\t\tglUseProgram(id);\n\t\tglCheckError();\n\t\tcurrentShader = this;\n\t}\n}\n\nvoid ShaderOpenGL::unbind()\n{\n\tcurrentShader = nullptr;\n\tglUseProgram(0);\n\tglCheckError();\n}\n\nstatic GLuint loadShader(const Bytes& src, GLenum type, String name)\n{\n\t\/\/ Create shader\n\tGLuint shader = glCreateShader(type);\n\tglCheckError();\n\n\t\/\/ Load source\n#ifdef WITH_OPENGL_ES3\n size_t startPos = 0;\n if (src.size() >= 13 && memcmp(src.data(), \"#version 330\", 12) == 0) {\n startPos = 12;\n }\n size_t len = src.size() + 15 - startPos;\n GLchar* buffer = new GLchar[len + 1];\n memcpy(buffer, \"#version 300 es\", 15);\n memcpy(buffer + 15, src.data() + startPos, len - 15);\n buffer[len] = 0;\n#else\n\tsize_t len = src.size();\n\tGLchar* buffer = new GLchar[len + 1];\n\tmemcpy(buffer, src.data(), src.size());\n\tbuffer[len] = 0;\n#endif\n\n\t\/\/ Set source\n const char* cbuf = buffer;\n\tglShaderSource(shader, 1, &cbuf, nullptr);\n\tglCheckError();\n\n\t\/\/ Compile source\n\tglCompileShader(shader);\n\tglCheckError();\n\n\tdelete[] buffer;\n\n\t\/\/ Check result\n\t\/\/ Seriously, GL? All this crap to retrieve an info log?\n\tint result;\n\tglGetShaderiv(shader, GL_COMPILE_STATUS, &result);\n\tglCheckError();\n\tif (result == GL_FALSE) {\n\t\tint infolen;\n\t\tglGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infolen);\n\t\tglCheckError();\n\t\tchar* log = new char[infolen];\n\t\tglGetShaderInfoLog(shader, infolen, &infolen, log);\n\t\tString msg = String(\"Error compiling shader \\\"\" + name + \"\\\":\\n\") + log;\n\t\tdelete[] log;\n\t\tglCheckError();\n\t\tthrow Exception(msg, HalleyExceptions::VideoPlugin);\n\t}\n\n\treturn shader;\n}\n\nvoid ShaderOpenGL::loadShaders(const std::map<ShaderType, Bytes>& sources)\n{\n\tfor (auto& s: sources) {\n\t\tauto type = s.first;\n\t\tint glType = 0;\n\t\tswitch (type) {\n\t\tcase ShaderType::Vertex:\n\t\t\tglType = GL_VERTEX_SHADER;\n\t\t\tbreak;\n\t\tcase ShaderType::Pixel:\n\t\t\tglType = GL_FRAGMENT_SHADER;\n\t\t\tbreak;\n#ifdef WITH_OPENGL\n\t\tcase ShaderType::Geometry:\n\t\t\tglType = GL_GEOMETRY_SHADER;\n\t\t\tbreak;\n#endif\n\t\tdefault:\n\t\t\tthrow Exception(\"Unsupported shader type: \" + toString(type), HalleyExceptions::VideoPlugin);\n\t\t}\n\n\t\tshaders.push_back(loadShader(s.second, glType, name + \"\/\" + toString(type)));\n\t}\n}\n\nvoid ShaderOpenGL::compile()\n{\n\tif (!ready) {\n\t\t\/\/ Create program\n\t\tfor (size_t i = 0; i<shaders.size(); i++) {\n\t\t\tglAttachShader(id, shaders[i]);\n\t\t\tglCheckError();\n\t\t}\n\t\tglLinkProgram(id);\n\t\tglCheckError();\n\n\t\t\/\/ Collect log\n\t\tint infolen;\n\t\tglGetProgramiv(id, GL_INFO_LOG_LENGTH, &infolen);\n\t\tglCheckError();\n\t\tchar* logRaw = new char[infolen + 1];\n\t\tglGetProgramInfoLog(id, infolen, &infolen, logRaw);\n\t\tlogRaw[infolen] = 0;\n\t\tString log = logRaw;\n\t\tdelete[] logRaw;\n\t\tglCheckError();\n\n\t\t\/\/ Verify result\n\t\tint result;\n\t\tglGetProgramiv(id, GL_LINK_STATUS, &result);\n\t\tglCheckError();\n\t\tif (result == GL_FALSE) {\n\t\t\tthrow Exception(\"Error loading shader: \" + log, HalleyExceptions::VideoPlugin);\n\t\t} else if (infolen > 0) {\n\t\t\tstd::cout << ConsoleColour(Console::YELLOW) << \"\\nIn shader \\\"\" << name << \"\\\":\\n==========\\n\" << log << \"\\n==========\" << ConsoleColour() << std::endl;\n\t\t}\n\n\t\tuniformLocations.clear();\n\t\tattributeLocations.clear();\n\t\tready = true;\n\t}\n}\n\nvoid ShaderOpenGL::destroy()\n{\n\tif (ready) {\n\t\tglCheckError();\n\t\tunbind();\n\t\tready = false;\n\n\t\tfor (size_t i = 0; i < shaders.size(); i++) {\n\t\t\tglDetachShader(id, shaders[i]);\n\t\t\tglCheckError();\n\t\t\tglDeleteShader(shaders[i]);\n\t\t\tglCheckError();\n\t\t}\n\t}\n\n\tif (id != 0) {\n\t\tglDeleteProgram(id);\n\t\tglCheckError();\n\t\tid = 0;\n\t}\n}\n\nvoid ShaderOpenGL::setUniformBlockBinding(unsigned int blockIndex, unsigned int binding)\n{\n\tglUniformBlockBinding(id, blockIndex, binding);\n\tglCheckError();\n}\n\nint ShaderOpenGL::getUniformLocation(const String& name, ShaderType stage)\n{\n\tif (stage != ShaderType::Combined) {\n\t\t\/\/ OpenGL doesn't support per-stage bindings\n\t\treturn -1;\n\t}\n\n\tauto i = uniformLocations.find(name);\n\tif (i != uniformLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetUniformLocation(id, name.c_str());\n\tglCheckError();\n\n\tuniformLocations[name] = result;\n\treturn int(result);\n}\n\nint ShaderOpenGL::getBlockLocation(const String& name, ShaderType stage)\n{\n\tif (stage != ShaderType::Combined) {\n\t\t\/\/ OpenGL doesn't support per-stage bindings\n\t\treturn -1;\n\t}\n\n\tauto i = blockLocations.find(name);\n\tif (i != blockLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetUniformBlockIndex(id, name.c_str());\n\tglCheckError();\n\n\tblockLocations[name] = result;\n\treturn int(result);\n}\n\nint ShaderOpenGL::getAttributeLocation(const String& name)\n{\n\tauto i = attributeLocations.find(name);\n\tif (i != attributeLocations.end()) {\n\t\treturn int(i->second);\n\t}\n\n\tunsigned int result = glGetAttribLocation(id, name.c_str());\n\tglCheckError();\n\n\tattributeLocations[name] = result;\n\treturn int(result);\n}\n\nvoid ShaderOpenGL::setAttributes(const Vector<MaterialAttribute>& attributes)\n{\n\tfor (auto& attribute : attributes) {\n\t\tglBindAttribLocation(id, attribute.location, attribute.name.c_str());\n\t\tglCheckError();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/hist:$Name: $:$Id: THStack.cxx,v 1.5 2001\/12\/10 15:03:18 rdm Exp $\n\/\/ Author: Rene Brun 10\/12\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TROOT.h\"\n#include \"THStack.h\"\n#include \"TVirtualPad.h\"\n#include \"TH2.h\"\n\n#include <fstream.h>\n#include <iostream.h>\n\nClassImp(THStack)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ A THStack is a collection of TH1 (or derived) objects\n\/\/ Use THStack::Add to add a new histogram to the list.\n\/\/ The THStack owns the objects in the list.\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n\/\/ Example;\n\/\/ THStack hs(\"hs\",\"test stacked histograms\");\n\/\/ TH1F *h1 = new TH1F(\"h1\",\"test hstack\",100,-4,4);\n\/\/ h1->FillRandom(\"gaus\",20000);\n\/\/ h1->SetFillColor(kRed);\n\/\/ hs.Add(h1);\n\/\/ TH1F *h2 = new TH1F(\"h2\",\"test hstack\",100,-4,4);\n\/\/ h2->FillRandom(\"gaus\",15000);\n\/\/ h2->SetFillColor(kBlue);\n\/\/ hs.Add(h2);\n\/\/ TH1F *h3 = new TH1F(\"h3\",\"test hstack\",100,-4,4);\n\/\/ h3->FillRandom(\"gaus\",10000);\n\/\/ h3->SetFillColor(kGreen);\n\/\/ hs.Add(h3);\n\/\/ TCanvas c1(\"c1\",\"stacked hists\",10,10,700,900);\n\/\/ c1.Divide(1,2);\n\/\/ c1.cd(1);\n\/\/ hs.Draw();\n\/\/ c1.cd(2);\n\/\/ hs->Draw(\"nostack\");\n\/\/\n\/\/ See a more complex example in $ROOTSYS\/tutorials\/hstack.C\n\/\/\n\/\/ Note that picking is supported for all drawing modes.\n\n\/\/______________________________________________________________________________\nTHStack::THStack(): TNamed()\n{\n\/\/ THStack default constructor\n\n fHists = 0;\n fStack = 0;\n fHistogram = 0;\n fMaximum = -1111;\n fMinimum = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::THStack(const char *name, const char *title)\n : TNamed(name,title)\n{\n\/\/ constructor with name and title\n fHists = 0;\n fStack = 0;\n fHistogram = 0;\n fMaximum = -1111;\n fMinimum = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::~THStack()\n{\n\/\/ THStack destructor\n\n\n if (!fHists) return;\n fHists->Delete();\n delete fHists;\n fHists = 0;\n if (fStack) {fStack->Delete(); delete fStack;}\n delete fHistogram;\n fHistogram = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Add(TH1 *h1)\n{\n \/\/ add a new histogram to the list\n \/\/ Only 1-d histograms currently supported.\n \/\/ Note that all histograms in the list must have the same number\n \/\/ of channels and the same X axis.\n\n if (!h1) return;\n if (h1->GetDimension() > 2) {\n Error(\"Add\",\"THStack supports only 1-d and 2-d histograms\");\n return;\n }\n if (!fHists) fHists = new TObjArray();\n fHists->Add(h1);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Browse(TBrowser *)\n{\n Draw();\n gPad->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::BuildStack()\n{\n\/\/ build sum of all histograms\n\/\/ Build a separate list fStack containing the running sum of all histograms\n\n if (fStack) return;\n Int_t nhists = fHists->GetEntriesFast();\n fStack = new TObjArray(nhists);\n Bool_t add = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n TH1 *h = (TH1*)fHists->At(0)->Clone();\n fStack->Add(h);\n for (Int_t i=1;i<nhists;i++) {\n h = (TH1*)fHists->At(i)->Clone();\n h->Add((TH1*)fStack->At(i-1));\n fStack->AddAt(h,i);\n }\n TH1::AddDirectory(add);\n}\n\n\/\/______________________________________________________________________________\nInt_t THStack::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/ Compute distance from point px,py to each graph\n\/\/\n\n\/\/*-*- Are we on the axis?\n const Int_t kMaxDiff = 10;\n Int_t distance = 9999;\n if (fHistogram) {\n distance = fHistogram->DistancetoPrimitive(px,py);\n if (distance <= 0) {return distance;}\n if (distance <= 1) {gPad->SetSelected(fHistogram);return distance;}\n }\n\n\n\/\/*-*- Loop on the list of histograms\n if (!fHists) return distance;\n TH1 *h = 0;\n const char *doption = GetDrawOption();\n Int_t nhists = fHists->GetEntriesFast();\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n if (fStack && !strstr(doption,\"nostack\")) h = (TH1*)fStack->At(i);\n Int_t dist = h->DistancetoPrimitive(px,py);\n if (dist < kMaxDiff) {\n gPad->SetSelected(fHists->At(i));\n gPad->SetCursor(kPointer);\n return dist;\n }\n }\n return distance;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this multihist with its current attributes*-*-*-*-*-*-*\n\/\/*-* ==========================================\n\/\/\n\/\/ Options to draw histograms are described in THistPainter::Paint\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n\n TString opt = option;\n opt.ToLower();\n if (gPad) {\n if (!gPad->IsEditable()) (gROOT->GetMakeDefCanvas())();\n if (!opt.Contains(\"same\")) {\n \/\/the following statement is necessary in case one attempts to draw\n \/\/a temporary histogram already in the current pad\n if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);\n gPad->Clear();\n }\n }\n AppendPad(opt.Data());\n}\n\n\/\/______________________________________________________________________________\nTH1 *THStack::GetHistogram() const\n{\n\/\/ Returns a pointer to the histogram used to draw the axis\n\/\/ Takes into account the two following cases.\n\/\/ 1- option 'A' was specified in THStack::Draw. Return fHistogram\n\/\/ 2- user had called TPad::DrawFrame. return pointer to hframe histogram\n\n if (fHistogram) return fHistogram;\n if (!gPad) return 0;\n gPad->Modified();\n gPad->Update();\n if (fHistogram) return fHistogram;\n TH1 *h1 = (TH1*)gPad->FindObject(\"hframe\");\n return h1;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMaximum(Option_t *option)\n{\n\/\/ returns the maximum of all added histograms\n\/\/ returns the maximum of all histograms if option \"nostack\".\n\n TString opt = option;\n opt.ToLower();\n Double_t them=0, themax = -1e300;\n Int_t nhists = fHists->GetEntriesFast();\n TH1 *h;\n if (!opt.Contains(\"nostack\")) {\n BuildStack();\n h = (TH1*)fStack->At(nhists-1);\n themax = h->GetMaximum();\n if (strstr(opt.Data(),\"e1\")) themax += TMath::Sqrt(TMath::Abs(themax));\n } else {\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n them = h->GetMaximum();\n if (strstr(opt.Data(),\"e1\")) them += TMath::Sqrt(TMath::Abs(them));\n if (them > themax) themax = them;\n }\n }\n return themax;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMinimum(Option_t *option)\n{\n\/\/ returns the minimum of all added histograms\n\/\/ returns the minimum of all histograms if option \"nostack\".\n\n TString opt = option;\n opt.ToLower();\n Double_t them=0, themin = 1e300;\n Int_t nhists = fHists->GetEntriesFast();\n TH1 *h;\n if (!opt.Contains(\"nostack\")) {\n BuildStack();\n h = (TH1*)fStack->At(nhists-1);\n themin = h->GetMinimum();\n } else {\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n them = h->GetMinimum();\n if (them < themin) themin = them;\n }\n }\n return themin;\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetXaxis() const\n{\n \/\/ Get x axis of the graph.\n\n if (!gPad) return 0;\n return GetHistogram()->GetXaxis();\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetYaxis() const\n{\n \/\/ Get y axis of the graph.\n\n if (!gPad) return 0;\n return GetHistogram()->GetYaxis();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::ls(Option_t *option) const\n{\n \/\/ List histograms in the stack\n\n TROOT::IndentLevel();\n cout <<IsA()->GetName()\n <<\" Name= \"<<GetName()<<\" Title= \"<<GetTitle()<<\" Option=\"<<option<<endl;\n TROOT::IncreaseDirLevel();\n if (fHists) fHists->ls(option);\n TROOT::DecreaseDirLevel();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Modified()\n{\n\/\/ invalidate sum of histograms\n\n if (!fStack) return;\n fStack->Delete();\n delete fStack;\n fStack = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Paint(Option_t *option)\n{\n\/\/ paint the list of histograms\n\/\/ By default, histograms are shown stacked.\n\/\/ -the first histogram is paint\n\/\/ -then the sum of the first and second, etc\n\/\/ If option \"nostack\" is specified, histograms are all paint in the same pad\n\/\/ as if the option \"same\" had been specified.\n\/\/\n\/\/ See THistPainter::Paint for a list of valid options.\n\n TString opt = option;\n opt.ToLower();\n char loption[32];\n sprintf(loption,\"%s\",opt.Data());\n char *nostack = strstr(loption,\"nostack\");\n \/\/ do not delete the stack. Another pad may contain the same object\n \/\/ drawn in stack mode!\n \/\/if (nostack && fStack) {fStack->Delete(); delete fStack; fStack = 0;}\n\n if (!opt.Contains(\"nostack\")) BuildStack();\n \n Double_t themax,themin;\n if (fMaximum == -1111) themax = GetMaximum(option);\n else themax = fMaximum;\n if (fMinimum == -1111) themin = GetMinimum(option);\n else themin = fMinimum;\n if (!fHistogram) {\n Bool_t add = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n TH1 *h = (TH1*)fHists->At(0);\n TAxis *xaxis = h->GetXaxis();\n TAxis *yaxis = h->GetYaxis();\n if (h->GetDimension() > 1) {\n if (strlen(option) == 0) strcpy(loption,\"lego1\");\n fHistogram = new TH2F(GetName(),GetTitle(),\n xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax(),\n yaxis->GetNbins(),yaxis->GetXmin(),yaxis->GetXmax());\n } else {\n fHistogram = new TH1F(GetName(),GetTitle(),xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax());\n }\n fHistogram->SetStats(0);\n TH1::AddDirectory(add);\n }\n\n if (nostack) {*nostack = 0; strcat(nostack,nostack+7);}\n else fHistogram->GetPainter()->SetStack(fHists);\n\n fHistogram->SetMaximum(1.05*themax);\n fHistogram->SetMinimum(themin);\n fHistogram->Paint(loption);\n\n if (fHistogram->GetDimension() > 1) SetDrawOption(loption);\n if (strstr(loption,\"lego\")) return;\n\n Int_t nhists = fHists->GetEntriesFast();\n strcat(loption,\"same\");\n for (Int_t i=0;i<nhists;i++) {\n if (nostack) fHists->At(i)->Paint(loption);\n else fStack->At(nhists-i-1)->Paint(loption);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Print(Option_t *option) const\n{\n\/\/ Print the list of histograms\n\n TH1 *h;\n if (fHists) {\n TIter next(fHists);\n while ((h = (TH1*) next())) {\n h->Print(option);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save primitive as a C++ statement(s) on output stream out\n\n char quote = '\"';\n out<<\" \"<<endl;\n if (gROOT->ClassSaved(THStack::Class())) {\n out<<\" \";\n } else {\n out<<\" THStack *\";\n }\n out<<\"hstack = new THStack();\"<<endl;\n out<<\" hstack->SetName(\"<<quote<<GetName()<<quote<<\");\"<<endl;\n out<<\" hstack->SetTitle(\"<<quote<<GetTitle()<<quote<<\");\"<<endl;\n\n TH1 *h;\n if (fHists) {\n TIter next(fHists);\n while ((h = (TH1*) next())) {\n h->SavePrimitive(out,\"nodraw\");\n out<<\" hstack->Add(\"<<h->GetName()<<\");\"<<endl;\n }\n }\n out<<\" hstack->Draw(\"\n <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMaximum(Double_t maximum)\n{\n fMaximum = maximum;\n if (fHistogram) fHistogram->SetMaximum(maximum);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMinimum(Double_t minimum)\n{\n fMinimum = minimum;\n if (fHistogram) fHistogram->SetMinimum(minimum);\n}\n<commit_msg>In THStack::Paint, Use a default minimum=0 if the minimum is positive.<commit_after>\/\/ @(#)root\/hist:$Name: $:$Id: THStack.cxx,v 1.6 2001\/12\/21 13:41:09 brun Exp $\n\/\/ Author: Rene Brun 10\/12\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TROOT.h\"\n#include \"THStack.h\"\n#include \"TVirtualPad.h\"\n#include \"TH2.h\"\n\n#include <fstream.h>\n#include <iostream.h>\n\nClassImp(THStack)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ A THStack is a collection of TH1 (or derived) objects\n\/\/ Use THStack::Add to add a new histogram to the list.\n\/\/ The THStack owns the objects in the list.\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n\/\/ Example;\n\/\/ THStack hs(\"hs\",\"test stacked histograms\");\n\/\/ TH1F *h1 = new TH1F(\"h1\",\"test hstack\",100,-4,4);\n\/\/ h1->FillRandom(\"gaus\",20000);\n\/\/ h1->SetFillColor(kRed);\n\/\/ hs.Add(h1);\n\/\/ TH1F *h2 = new TH1F(\"h2\",\"test hstack\",100,-4,4);\n\/\/ h2->FillRandom(\"gaus\",15000);\n\/\/ h2->SetFillColor(kBlue);\n\/\/ hs.Add(h2);\n\/\/ TH1F *h3 = new TH1F(\"h3\",\"test hstack\",100,-4,4);\n\/\/ h3->FillRandom(\"gaus\",10000);\n\/\/ h3->SetFillColor(kGreen);\n\/\/ hs.Add(h3);\n\/\/ TCanvas c1(\"c1\",\"stacked hists\",10,10,700,900);\n\/\/ c1.Divide(1,2);\n\/\/ c1.cd(1);\n\/\/ hs.Draw();\n\/\/ c1.cd(2);\n\/\/ hs->Draw(\"nostack\");\n\/\/\n\/\/ See a more complex example in $ROOTSYS\/tutorials\/hstack.C\n\/\/\n\/\/ Note that picking is supported for all drawing modes.\n\n\/\/______________________________________________________________________________\nTHStack::THStack(): TNamed()\n{\n\/\/ THStack default constructor\n\n fHists = 0;\n fStack = 0;\n fHistogram = 0;\n fMaximum = -1111;\n fMinimum = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::THStack(const char *name, const char *title)\n : TNamed(name,title)\n{\n\/\/ constructor with name and title\n fHists = 0;\n fStack = 0;\n fHistogram = 0;\n fMaximum = -1111;\n fMinimum = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::~THStack()\n{\n\/\/ THStack destructor\n\n\n if (!fHists) return;\n fHists->Delete();\n delete fHists;\n fHists = 0;\n if (fStack) {fStack->Delete(); delete fStack;}\n delete fHistogram;\n fHistogram = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Add(TH1 *h1)\n{\n \/\/ add a new histogram to the list\n \/\/ Only 1-d histograms currently supported.\n \/\/ Note that all histograms in the list must have the same number\n \/\/ of channels and the same X axis.\n\n if (!h1) return;\n if (h1->GetDimension() > 2) {\n Error(\"Add\",\"THStack supports only 1-d and 2-d histograms\");\n return;\n }\n if (!fHists) fHists = new TObjArray();\n fHists->Add(h1);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Browse(TBrowser *)\n{\n Draw();\n gPad->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::BuildStack()\n{\n\/\/ build sum of all histograms\n\/\/ Build a separate list fStack containing the running sum of all histograms\n\n if (fStack) return;\n Int_t nhists = fHists->GetEntriesFast();\n fStack = new TObjArray(nhists);\n Bool_t add = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n TH1 *h = (TH1*)fHists->At(0)->Clone();\n fStack->Add(h);\n for (Int_t i=1;i<nhists;i++) {\n h = (TH1*)fHists->At(i)->Clone();\n h->Add((TH1*)fStack->At(i-1));\n fStack->AddAt(h,i);\n }\n TH1::AddDirectory(add);\n}\n\n\/\/______________________________________________________________________________\nInt_t THStack::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/ Compute distance from point px,py to each graph\n\/\/\n\n\/\/*-*- Are we on the axis?\n const Int_t kMaxDiff = 10;\n Int_t distance = 9999;\n if (fHistogram) {\n distance = fHistogram->DistancetoPrimitive(px,py);\n if (distance <= 0) {return distance;}\n if (distance <= 1) {gPad->SetSelected(fHistogram);return distance;}\n }\n\n\n\/\/*-*- Loop on the list of histograms\n if (!fHists) return distance;\n TH1 *h = 0;\n const char *doption = GetDrawOption();\n Int_t nhists = fHists->GetEntriesFast();\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n if (fStack && !strstr(doption,\"nostack\")) h = (TH1*)fStack->At(i);\n Int_t dist = h->DistancetoPrimitive(px,py);\n if (dist < kMaxDiff) {\n gPad->SetSelected(fHists->At(i));\n gPad->SetCursor(kPointer);\n return dist;\n }\n }\n return distance;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this multihist with its current attributes*-*-*-*-*-*-*\n\/\/*-* ==========================================\n\/\/\n\/\/ Options to draw histograms are described in THistPainter::Paint\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n\n TString opt = option;\n opt.ToLower();\n if (gPad) {\n if (!gPad->IsEditable()) (gROOT->GetMakeDefCanvas())();\n if (!opt.Contains(\"same\")) {\n \/\/the following statement is necessary in case one attempts to draw\n \/\/a temporary histogram already in the current pad\n if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);\n gPad->Clear();\n }\n }\n AppendPad(opt.Data());\n}\n\n\/\/______________________________________________________________________________\nTH1 *THStack::GetHistogram() const\n{\n\/\/ Returns a pointer to the histogram used to draw the axis\n\/\/ Takes into account the two following cases.\n\/\/ 1- option 'A' was specified in THStack::Draw. Return fHistogram\n\/\/ 2- user had called TPad::DrawFrame. return pointer to hframe histogram\n\n if (fHistogram) return fHistogram;\n if (!gPad) return 0;\n gPad->Modified();\n gPad->Update();\n if (fHistogram) return fHistogram;\n TH1 *h1 = (TH1*)gPad->FindObject(\"hframe\");\n return h1;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMaximum(Option_t *option)\n{\n\/\/ returns the maximum of all added histograms\n\/\/ returns the maximum of all histograms if option \"nostack\".\n\n TString opt = option;\n opt.ToLower();\n Double_t them=0, themax = -1e300;\n Int_t nhists = fHists->GetEntriesFast();\n TH1 *h;\n if (!opt.Contains(\"nostack\")) {\n BuildStack();\n h = (TH1*)fStack->At(nhists-1);\n themax = h->GetMaximum();\n if (strstr(opt.Data(),\"e1\")) themax += TMath::Sqrt(TMath::Abs(themax));\n } else {\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n them = h->GetMaximum();\n if (strstr(opt.Data(),\"e1\")) them += TMath::Sqrt(TMath::Abs(them));\n if (them > themax) themax = them;\n }\n }\n return themax;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMinimum(Option_t *option)\n{\n\/\/ returns the minimum of all added histograms\n\/\/ returns the minimum of all histograms if option \"nostack\".\n\n TString opt = option;\n opt.ToLower();\n Double_t them=0, themin = 1e300;\n Int_t nhists = fHists->GetEntriesFast();\n TH1 *h;\n if (!opt.Contains(\"nostack\")) {\n BuildStack();\n h = (TH1*)fStack->At(nhists-1);\n themin = h->GetMinimum();\n } else {\n for (Int_t i=0;i<nhists;i++) {\n h = (TH1*)fHists->At(i);\n them = h->GetMinimum();\n if (them < themin) themin = them;\n }\n }\n return themin;\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetXaxis() const\n{\n \/\/ Get x axis of the graph.\n\n if (!gPad) return 0;\n return GetHistogram()->GetXaxis();\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetYaxis() const\n{\n \/\/ Get y axis of the graph.\n\n if (!gPad) return 0;\n return GetHistogram()->GetYaxis();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::ls(Option_t *option) const\n{\n \/\/ List histograms in the stack\n\n TROOT::IndentLevel();\n cout <<IsA()->GetName()\n <<\" Name= \"<<GetName()<<\" Title= \"<<GetTitle()<<\" Option=\"<<option<<endl;\n TROOT::IncreaseDirLevel();\n if (fHists) fHists->ls(option);\n TROOT::DecreaseDirLevel();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Modified()\n{\n\/\/ invalidate sum of histograms\n\n if (!fStack) return;\n fStack->Delete();\n delete fStack;\n fStack = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Paint(Option_t *option)\n{\n\/\/ paint the list of histograms\n\/\/ By default, histograms are shown stacked.\n\/\/ -the first histogram is paint\n\/\/ -then the sum of the first and second, etc\n\/\/ If option \"nostack\" is specified, histograms are all paint in the same pad\n\/\/ as if the option \"same\" had been specified.\n\/\/\n\/\/ See THistPainter::Paint for a list of valid options.\n\n TString opt = option;\n opt.ToLower();\n char loption[32];\n sprintf(loption,\"%s\",opt.Data());\n char *nostack = strstr(loption,\"nostack\");\n \/\/ do not delete the stack. Another pad may contain the same object\n \/\/ drawn in stack mode!\n \/\/if (nostack && fStack) {fStack->Delete(); delete fStack; fStack = 0;}\n\n if (!opt.Contains(\"nostack\")) BuildStack();\n \n Double_t themax,themin;\n if (fMaximum == -1111) themax = GetMaximum(option);\n else themax = fMaximum;\n if (fMinimum == -1111) {themin = GetMinimum(option); if (themin > 0) themin = 0;}\n else themin = fMinimum;\n if (!fHistogram) {\n Bool_t add = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n TH1 *h = (TH1*)fHists->At(0);\n TAxis *xaxis = h->GetXaxis();\n TAxis *yaxis = h->GetYaxis();\n if (h->GetDimension() > 1) {\n if (strlen(option) == 0) strcpy(loption,\"lego1\");\n fHistogram = new TH2F(GetName(),GetTitle(),\n xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax(),\n yaxis->GetNbins(),yaxis->GetXmin(),yaxis->GetXmax());\n } else {\n fHistogram = new TH1F(GetName(),GetTitle(),xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax());\n }\n fHistogram->SetStats(0);\n TH1::AddDirectory(add);\n }\n\n if (nostack) {*nostack = 0; strcat(nostack,nostack+7);}\n else fHistogram->GetPainter()->SetStack(fHists);\n\n fHistogram->SetMaximum(1.05*themax);\n fHistogram->SetMinimum(themin);\n fHistogram->Paint(loption);\n\n if (fHistogram->GetDimension() > 1) SetDrawOption(loption);\n if (strstr(loption,\"lego\")) return;\n\n Int_t nhists = fHists->GetEntriesFast();\n strcat(loption,\"same\");\n for (Int_t i=0;i<nhists;i++) {\n if (nostack) fHists->At(i)->Paint(loption);\n else fStack->At(nhists-i-1)->Paint(loption);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Print(Option_t *option) const\n{\n\/\/ Print the list of histograms\n\n TH1 *h;\n if (fHists) {\n TIter next(fHists);\n while ((h = (TH1*) next())) {\n h->Print(option);\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save primitive as a C++ statement(s) on output stream out\n\n char quote = '\"';\n out<<\" \"<<endl;\n if (gROOT->ClassSaved(THStack::Class())) {\n out<<\" \";\n } else {\n out<<\" THStack *\";\n }\n out<<\"hstack = new THStack();\"<<endl;\n out<<\" hstack->SetName(\"<<quote<<GetName()<<quote<<\");\"<<endl;\n out<<\" hstack->SetTitle(\"<<quote<<GetTitle()<<quote<<\");\"<<endl;\n\n TH1 *h;\n if (fHists) {\n TIter next(fHists);\n while ((h = (TH1*) next())) {\n h->SavePrimitive(out,\"nodraw\");\n out<<\" hstack->Add(\"<<h->GetName()<<\");\"<<endl;\n }\n }\n out<<\" hstack->Draw(\"\n <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMaximum(Double_t maximum)\n{\n fMaximum = maximum;\n if (fHistogram) fHistogram->SetMaximum(maximum);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMinimum(Double_t minimum)\n{\n fMinimum = minimum;\n if (fHistogram) fHistogram->SetMinimum(minimum);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) 2015 Augustin Cavalier\n * All rights reserved. Distributed under the terms of the MIT license.\n *\/\n#include \"Stack.h\"\n\n#include <iostream>\n\n#include \"util\/StringUtil.h\"\n\nusing std::cout;\nusing std::string;\nusing std::vector;\n\nnamespace Language {\n\nstd::map<std::string, Function> GlobalFunctions;\n\nStack::Stack()\n{\n\tpush();\n}\n\nvoid Stack::push()\n{\n\tfStack.push_back(ObjectMap());\n}\n\nvoid Stack::pop()\n{\n\tfStack.pop_back();\n}\n\nstd::vector<ObjectMap>::size_type Stack::getPos(std::string variable)\n{\n\tstd::vector<ObjectMap>::size_type size = fStack.size() - 1;\n\tfor (std::vector<ObjectMap>::size_type i = 0; i <= size; i++) {\n\t\tif (fStack[size - i].get_ptr(variable) != nullptr)\n\t\t\treturn i;\n\t}\n\treturn fStack.size() - 1;\n}\n\nObject Stack::get(const vector<string> variable)\n{\n\tObject* ret = nullptr;\n\tif (variable[0][0] == '$') {\n\t\t\/\/ it's a superglobal\n\t\tstring var = variable[0];\n\t\tvar = var.substr(1);\n\t\tret = fSuperglobalScope.get_ptr(var);\n\t} else\n\t\tret = fStack[getPos(variable[0])].get_ptr(variable[0]);\n\tfor (vector<string>::size_type i = 1; i < variable.size(); i++) {\n\t\tstd::string what = string(\"referenced variable '\")\n\t\t\t.append(StringUtil::join(variable, \".\")).append(\"'\");\n\t\tCoerceOrThrowPtr(what, ret, Type::Map);\n\t\tret = ret->map->get_ptr(variable[i]);\n\t}\n\n\tif (ret != nullptr)\n\t\treturn *ret;\n\treturn Object();\n}\n\nvoid Stack::set(vector<string> variable, Object value)\n{\n\tif (variable[0][0] == '$') {\n\t\t\/\/ it's a superglobal\n\t\tthrow Exception(Exception::AccessViolation, \"superglobals are read-only\");\n\t}\n\tvector<ObjectMap>::size_type loc = getPos(variable[0]);\n\tif (variable.size() == 1) {\n\t\tfStack[loc].set(variable[0], value);\n\t\treturn;\n\t}\n\n\tObject* res = fStack[loc].get_ptr(variable[0]);\n\tCoerceOrThrowPtr(\"referenced variable\", res, Type::Map);\n\tfor (vector<string>::size_type i = 1; i < variable.size() - 1; i++) {\n\t\tres = res->map->get_ptr(variable[i]);\n\t\tCoerceOrThrowPtr(\"referenced variable\", res, Type::Map);\n\t}\n\tres->map->set(variable[variable.size() - 1], value);\n}\n\nvoid Stack::addSuperglobal(string variableName, Object value)\n{\n\tfSuperglobalScope.set(variableName, value);\n}\n\nvoid Stack::print()\n{\n\tcout << \"-- VM STACK DUMP --\" << std::endl;\n\tint tabs = 1;\n\tfor (const ObjectMap& m : fStack) {\n\t\tfor (ObjectMap::const_iterator it = m.begin(); it != m.end(); it++) {\n\t\t\tfor (int i = 0; i < tabs; i++)\n\t\t\t\tcout << \" \";\n\t\t\tcout << it->first << \": \" << it->second->asString() << std::endl;\n\t\t}\n\t\ttabs++;\n\t}\n}\n\n}\n<commit_msg>Stack: Properly print referenced variable error.<commit_after>\/*\n * (C) 2015 Augustin Cavalier\n * All rights reserved. Distributed under the terms of the MIT license.\n *\/\n#include \"Stack.h\"\n\n#include <iostream>\n\n#include \"util\/StringUtil.h\"\n\nusing std::cout;\nusing std::string;\nusing std::vector;\n\nnamespace Language {\n\nstd::map<std::string, Function> GlobalFunctions;\n\nStack::Stack()\n{\n\tpush();\n}\n\nvoid Stack::push()\n{\n\tfStack.push_back(ObjectMap());\n}\n\nvoid Stack::pop()\n{\n\tfStack.pop_back();\n}\n\nstd::vector<ObjectMap>::size_type Stack::getPos(std::string variable)\n{\n\tstd::vector<ObjectMap>::size_type size = fStack.size() - 1;\n\tfor (std::vector<ObjectMap>::size_type i = 0; i <= size; i++) {\n\t\tif (fStack[size - i].get_ptr(variable) != nullptr)\n\t\t\treturn i;\n\t}\n\treturn fStack.size() - 1;\n}\n\nObject Stack::get(const vector<string> variable)\n{\n\tObject* ret = nullptr;\n\tif (variable[0][0] == '$') {\n\t\t\/\/ it's a superglobal\n\t\tstring var = variable[0];\n\t\tvar = var.substr(1);\n\t\tret = fSuperglobalScope.get_ptr(var);\n\t} else\n\t\tret = fStack[getPos(variable[0])].get_ptr(variable[0]);\n\tfor (vector<string>::size_type i = 1; i < variable.size(); i++) {\n\t\tCoerceOrThrowPtr(string(\"referenced variable '\")\n\t\t\t.append(variable[i - 1]).append(\"'\"), ret, Type::Map);\n\t\tret = ret->map->get_ptr(variable[i]);\n\t}\n\n\tif (ret != nullptr)\n\t\treturn *ret;\n\treturn Object();\n}\n\nvoid Stack::set(vector<string> variable, Object value)\n{\n\tif (variable[0][0] == '$') {\n\t\t\/\/ it's a superglobal\n\t\tthrow Exception(Exception::AccessViolation, \"superglobals are read-only\");\n\t}\n\tvector<ObjectMap>::size_type loc = getPos(variable[0]);\n\tif (variable.size() == 1) {\n\t\tfStack[loc].set(variable[0], value);\n\t\treturn;\n\t}\n\n\tObject* res = fStack[loc].get_ptr(variable[0]);\n\tCoerceOrThrowPtr(\"referenced variable\", res, Type::Map);\n\tfor (vector<string>::size_type i = 1; i < variable.size() - 1; i++) {\n\t\tres = res->map->get_ptr(variable[i]);\n\t\tCoerceOrThrowPtr(\"referenced variable\", res, Type::Map);\n\t}\n\tres->map->set(variable[variable.size() - 1], value);\n}\n\nvoid Stack::addSuperglobal(string variableName, Object value)\n{\n\tfSuperglobalScope.set(variableName, value);\n}\n\nvoid Stack::print()\n{\n\tcout << \"-- VM STACK DUMP --\" << std::endl;\n\tint tabs = 1;\n\tfor (const ObjectMap& m : fStack) {\n\t\tfor (ObjectMap::const_iterator it = m.begin(); it != m.end(); it++) {\n\t\t\tfor (int i = 0; i < tabs; i++)\n\t\t\t\tcout << \" \";\n\t\t\tcout << it->first << \": \" << it->second->asString() << std::endl;\n\t\t}\n\t\ttabs++;\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TwitchIrcServer.hpp\"\n\n#include \"Application.hpp\"\n#include \"common\/Common.hpp\"\n#include \"controllers\/accounts\/AccountController.hpp\"\n#include \"controllers\/highlights\/HighlightController.hpp\"\n#include \"messages\/Message.hpp\"\n#include \"messages\/MessageBuilder.hpp\"\n#include \"providers\/twitch\/ChatroomChannel.hpp\"\n#include \"providers\/twitch\/IrcMessageHandler.hpp\"\n#include \"providers\/twitch\/PubsubClient.hpp\"\n#include \"providers\/twitch\/TwitchAccount.hpp\"\n#include \"providers\/twitch\/TwitchChannel.hpp\"\n#include \"providers\/twitch\/TwitchHelpers.hpp\"\n#include \"providers\/twitch\/TwitchMessageBuilder.hpp\"\n#include \"util\/PostToThread.hpp\"\n\n#include <IrcCommand>\n#include <cassert>\n\n\/\/ using namespace Communi;\nusing namespace std::chrono_literals;\n\nnamespace chatterino {\n\nnamespace {\n bool isChatroom(const QString &channel)\n {\n if (channel.left(10) == \"chatrooms:\")\n {\n auto reflist = channel.splitRef(':');\n if (reflist.size() == 3)\n {\n return true;\n }\n }\n return false;\n }\n} \/\/ namespace\n\nTwitchIrcServer::TwitchIrcServer()\n : whispersChannel(new Channel(\"\/whispers\", Channel::Type::TwitchWhispers))\n , mentionsChannel(new Channel(\"\/mentions\", Channel::Type::TwitchMentions))\n , watchingChannel(Channel::getEmpty(), Channel::Type::TwitchWatching)\n{\n this->pubsub = new PubSub;\n\n \/\/ getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) {\n \/\/ this->connect(); },\n \/\/ this->signalHolder_,\n \/\/ false);\n}\n\nvoid TwitchIrcServer::initialize(Settings &settings, Paths &paths)\n{\n getApp()->accounts->twitch.currentUserChanged.connect(\n [this]() { postToThread([this] { this->connect(); }); });\n\n this->twitchBadges.loadTwitchBadges();\n this->bttv.loadEmotes();\n this->ffz.loadEmotes();\n}\n\nvoid TwitchIrcServer::initializeConnection(IrcConnection *connection,\n ConnectionType type)\n{\n std::shared_ptr<TwitchAccount> account =\n getApp()->accounts->twitch.getCurrent();\n\n qDebug() << \"logging in as\" << account->getUserName();\n\n QString username = account->getUserName();\n QString oauthToken = account->getOAuthToken();\n\n if (!oauthToken.startsWith(\"oauth:\"))\n {\n oauthToken.prepend(\"oauth:\");\n }\n\n connection->setUserName(username);\n connection->setNickName(username);\n connection->setRealName(username);\n\n if (!account->isAnon())\n {\n connection->setPassword(oauthToken);\n }\n\n connection->setSecure(true);\n\n \/\/ https:\/\/dev.twitch.tv\/docs\/irc\/guide\/#connecting-to-twitch-irc\n \/\/ SSL disabled: irc:\/\/irc.chat.twitch.tv:6667\n \/\/ SSL enabled: irc:\/\/irc.chat.twitch.tv:6697\n connection->setHost(\"irc.chat.twitch.tv\");\n connection->setPort(6697);\n\n this->open(type);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::createChannel(\n const QString &channelName)\n{\n std::shared_ptr<TwitchChannel> channel;\n if (isChatroom(channelName))\n {\n channel = std::static_pointer_cast<TwitchChannel>(\n std::shared_ptr<ChatroomChannel>(new ChatroomChannel(\n channelName, this->twitchBadges, this->bttv, this->ffz)));\n }\n else\n {\n channel = std::shared_ptr<TwitchChannel>(new TwitchChannel(\n channelName, this->twitchBadges, this->bttv, this->ffz));\n }\n channel->initialize();\n\n channel->sendMessageSignal.connect(\n [this, channel = channel.get()](auto &chan, auto &msg, bool &sent) {\n this->onMessageSendRequested(channel, msg, sent);\n });\n\n return std::shared_ptr<Channel>(channel);\n}\n\nvoid TwitchIrcServer::privateMessageReceived(\n Communi::IrcPrivateMessage *message)\n{\n IrcMessageHandler::getInstance().handlePrivMessage(message, *this);\n}\n\nvoid TwitchIrcServer::readConnectionMessageReceived(\n Communi::IrcMessage *message)\n{\n AbstractIrcServer::readConnectionMessageReceived(message);\n\n if (message->type() == Communi::IrcMessage::Type::Private)\n {\n \/\/ We already have a handler for private messages\n return;\n }\n\n const QString &command = message->command();\n\n auto &handler = IrcMessageHandler::getInstance();\n\n \/\/ Below commands enabled through the twitch.tv\/membership CAP REQ\n if (command == \"MODE\")\n {\n handler.handleModeMessage(message);\n }\n else if (command == \"JOIN\")\n {\n handler.handleJoinMessage(message);\n }\n else if (command == \"PART\")\n {\n handler.handlePartMessage(message);\n }\n else if (command == \"USERSTATE\")\n {\n \/\/ Received USERSTATE upon JOINing a channel\n handler.handleUserStateMessage(message);\n }\n}\n\nvoid TwitchIrcServer::writeConnectionMessageReceived(\n Communi::IrcMessage *message)\n{\n const QString &command = message->command();\n\n auto &handler = IrcMessageHandler::getInstance();\n\n \/\/ Below commands enabled through the twitch.tv\/commands CAP REQ\n if (command == \"USERSTATE\")\n {\n \/\/ Received USERSTATE upon PRIVMSGing\n handler.handleUserStateMessage(message);\n }\n else if (command == \"WHISPER\")\n {\n handler.handleWhisperMessage(message);\n }\n else if (command == \"USERNOTICE\")\n {\n handler.handleUserNoticeMessage(message, *this);\n }\n else if (command == \"ROOMSTATE\")\n {\n handler.handleRoomStateMessage(message);\n }\n else if (command == \"CLEARCHAT\")\n {\n handler.handleClearChatMessage(message);\n }\n else if (command == \"CLEARMSG\")\n {\n handler.handleClearMessageMessage(message);\n }\n else if (command == \"NOTICE\")\n {\n handler.handleNoticeMessage(\n static_cast<Communi::IrcNoticeMessage *>(message));\n }\n}\n\nvoid TwitchIrcServer::onReadConnected(IrcConnection *connection)\n{\n \/\/ twitch.tv\/tags enables IRCv3 tags on messages. See https:\/\/dev.twitch.tv\/docs\/irc\/tags\/\n \/\/ twitch.tv\/membership enables the JOIN\/PART\/MODE\/NAMES commands. See https:\/\/dev.twitch.tv\/docs\/irc\/membership\/\n \/\/ twitch.tv\/commands enables a bunch of miscellaneous command capabilities. See https:\/\/dev.twitch.tv\/docs\/irc\/commands\/\n \/\/ This is enabled here so we receive USERSTATE messages when joining channels\n connection->sendRaw(\n \"CAP REQ :twitch.tv\/tags twitch.tv\/membership twitch.tv\/commands\");\n\n AbstractIrcServer::onReadConnected(connection);\n}\n\nvoid TwitchIrcServer::onWriteConnected(IrcConnection *connection)\n{\n \/\/ twitch.tv\/tags enables IRCv3 tags on messages. See https:\/\/dev.twitch.tv\/docs\/irc\/tags\/\n \/\/ twitch.tv\/commands enables a bunch of miscellaneous command capabilities. See https:\/\/dev.twitch.tv\/docs\/irc\/commands\/\n \/\/ This is enabled here so we receive USERSTATE messages when typing messages, along with the other command capabilities\n connection->sendRaw(\"CAP REQ :twitch.tv\/tags twitch.tv\/commands\");\n\n AbstractIrcServer::onWriteConnected(connection);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::getCustomChannel(\n const QString &channelName)\n{\n if (channelName == \"\/whispers\")\n {\n return this->whispersChannel;\n }\n\n if (channelName == \"\/mentions\")\n {\n return this->mentionsChannel;\n }\n\n if (channelName == \"$$$\")\n {\n static auto channel =\n std::make_shared<Channel>(\"$$$\", chatterino::Channel::Type::Misc);\n static auto getTimer = [&] {\n for (auto i = 0; i < 1000; i++)\n {\n channel->addMessage(makeSystemMessage(QString::number(i + 1)));\n }\n\n auto timer = new QTimer;\n QObject::connect(timer, &QTimer::timeout, [] {\n channel->addMessage(\n makeSystemMessage(QTime::currentTime().toString()));\n });\n timer->start(500);\n return timer;\n }();\n\n return channel;\n }\n\n return nullptr;\n}\n\nvoid TwitchIrcServer::forEachChannelAndSpecialChannels(\n std::function<void(ChannelPtr)> func)\n{\n this->forEachChannel(func);\n\n func(this->whispersChannel);\n func(this->mentionsChannel);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::getChannelOrEmptyByID(\n const QString &channelId)\n{\n std::lock_guard<std::mutex> lock(this->channelMutex);\n\n for (const auto &weakChannel : this->channels)\n {\n auto channel = weakChannel.lock();\n if (!channel)\n continue;\n\n auto twitchChannel = std::dynamic_pointer_cast<TwitchChannel>(channel);\n if (!twitchChannel)\n continue;\n\n if (twitchChannel->roomId() == channelId &&\n twitchChannel->getName().splitRef(\":\").size() < 3)\n {\n return twitchChannel;\n }\n }\n\n return Channel::getEmpty();\n}\n\nQString TwitchIrcServer::cleanChannelName(const QString &dirtyChannelName)\n{\n if (dirtyChannelName.startsWith('#'))\n return dirtyChannelName.mid(1).toLower();\n else\n return dirtyChannelName.toLower();\n}\n\nbool TwitchIrcServer::hasSeparateWriteConnection() const\n{\n return true;\n \/\/ return getSettings()->twitchSeperateWriteConnection;\n}\n\nvoid TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel,\n const QString &message, bool &sent)\n{\n sent = false;\n\n {\n std::lock_guard<std::mutex> guard(this->lastMessageMutex_);\n\n \/\/ std::queue<std::chrono::steady_clock::time_point>\n auto &lastMessage = channel->hasHighRateLimit()\n ? this->lastMessageMod_\n : this->lastMessagePleb_;\n size_t maxMessageCount = channel->hasHighRateLimit() ? 99 : 19;\n auto minMessageOffset = (channel->hasHighRateLimit() ? 100ms : 1100ms);\n\n auto now = std::chrono::steady_clock::now();\n\n \/\/ check if you are sending messages too fast\n if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now)\n {\n if (this->lastErrorTimeSpeed_ + 30s < now)\n {\n auto errorMessage =\n makeSystemMessage(\"sending messages too fast\");\n\n channel->addMessage(errorMessage);\n\n this->lastErrorTimeSpeed_ = now;\n }\n return;\n }\n\n \/\/ remove messages older than 30 seconds\n while (!lastMessage.empty() && lastMessage.front() + 32s < now)\n {\n lastMessage.pop();\n }\n\n \/\/ check if you are sending too many messages\n if (lastMessage.size() >= maxMessageCount)\n {\n if (this->lastErrorTimeAmount_ + 30s < now)\n {\n auto errorMessage =\n makeSystemMessage(\"sending too many messages\");\n\n channel->addMessage(errorMessage);\n\n this->lastErrorTimeAmount_ = now;\n }\n return;\n }\n\n lastMessage.push(now);\n }\n\n this->sendMessage(channel->getName(), message);\n sent = true;\n}\n\nconst BttvEmotes &TwitchIrcServer::getBttvEmotes() const\n{\n return this->bttv;\n}\nconst FfzEmotes &TwitchIrcServer::getFfzEmotes() const\n{\n return this->ffz;\n}\n\n} \/\/ namespace chatterino\n<commit_msg>handle ROOMSTATE in read connection too<commit_after>#include \"TwitchIrcServer.hpp\"\n\n#include \"Application.hpp\"\n#include \"common\/Common.hpp\"\n#include \"controllers\/accounts\/AccountController.hpp\"\n#include \"controllers\/highlights\/HighlightController.hpp\"\n#include \"messages\/Message.hpp\"\n#include \"messages\/MessageBuilder.hpp\"\n#include \"providers\/twitch\/ChatroomChannel.hpp\"\n#include \"providers\/twitch\/IrcMessageHandler.hpp\"\n#include \"providers\/twitch\/PubsubClient.hpp\"\n#include \"providers\/twitch\/TwitchAccount.hpp\"\n#include \"providers\/twitch\/TwitchChannel.hpp\"\n#include \"providers\/twitch\/TwitchHelpers.hpp\"\n#include \"providers\/twitch\/TwitchMessageBuilder.hpp\"\n#include \"util\/PostToThread.hpp\"\n\n#include <IrcCommand>\n#include <cassert>\n\n\/\/ using namespace Communi;\nusing namespace std::chrono_literals;\n\nnamespace chatterino {\n\nnamespace {\n bool isChatroom(const QString &channel)\n {\n if (channel.left(10) == \"chatrooms:\")\n {\n auto reflist = channel.splitRef(':');\n if (reflist.size() == 3)\n {\n return true;\n }\n }\n return false;\n }\n} \/\/ namespace\n\nTwitchIrcServer::TwitchIrcServer()\n : whispersChannel(new Channel(\"\/whispers\", Channel::Type::TwitchWhispers))\n , mentionsChannel(new Channel(\"\/mentions\", Channel::Type::TwitchMentions))\n , watchingChannel(Channel::getEmpty(), Channel::Type::TwitchWatching)\n{\n this->pubsub = new PubSub;\n\n \/\/ getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) {\n \/\/ this->connect(); },\n \/\/ this->signalHolder_,\n \/\/ false);\n}\n\nvoid TwitchIrcServer::initialize(Settings &settings, Paths &paths)\n{\n getApp()->accounts->twitch.currentUserChanged.connect(\n [this]() { postToThread([this] { this->connect(); }); });\n\n this->twitchBadges.loadTwitchBadges();\n this->bttv.loadEmotes();\n this->ffz.loadEmotes();\n}\n\nvoid TwitchIrcServer::initializeConnection(IrcConnection *connection,\n ConnectionType type)\n{\n std::shared_ptr<TwitchAccount> account =\n getApp()->accounts->twitch.getCurrent();\n\n qDebug() << \"logging in as\" << account->getUserName();\n\n QString username = account->getUserName();\n QString oauthToken = account->getOAuthToken();\n\n if (!oauthToken.startsWith(\"oauth:\"))\n {\n oauthToken.prepend(\"oauth:\");\n }\n\n connection->setUserName(username);\n connection->setNickName(username);\n connection->setRealName(username);\n\n if (!account->isAnon())\n {\n connection->setPassword(oauthToken);\n }\n\n connection->setSecure(true);\n\n \/\/ https:\/\/dev.twitch.tv\/docs\/irc\/guide\/#connecting-to-twitch-irc\n \/\/ SSL disabled: irc:\/\/irc.chat.twitch.tv:6667\n \/\/ SSL enabled: irc:\/\/irc.chat.twitch.tv:6697\n connection->setHost(\"irc.chat.twitch.tv\");\n connection->setPort(6697);\n\n this->open(type);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::createChannel(\n const QString &channelName)\n{\n std::shared_ptr<TwitchChannel> channel;\n if (isChatroom(channelName))\n {\n channel = std::static_pointer_cast<TwitchChannel>(\n std::shared_ptr<ChatroomChannel>(new ChatroomChannel(\n channelName, this->twitchBadges, this->bttv, this->ffz)));\n }\n else\n {\n channel = std::shared_ptr<TwitchChannel>(new TwitchChannel(\n channelName, this->twitchBadges, this->bttv, this->ffz));\n }\n channel->initialize();\n\n channel->sendMessageSignal.connect(\n [this, channel = channel.get()](auto &chan, auto &msg, bool &sent) {\n this->onMessageSendRequested(channel, msg, sent);\n });\n\n return std::shared_ptr<Channel>(channel);\n}\n\nvoid TwitchIrcServer::privateMessageReceived(\n Communi::IrcPrivateMessage *message)\n{\n IrcMessageHandler::getInstance().handlePrivMessage(message, *this);\n}\n\nvoid TwitchIrcServer::readConnectionMessageReceived(\n Communi::IrcMessage *message)\n{\n AbstractIrcServer::readConnectionMessageReceived(message);\n\n if (message->type() == Communi::IrcMessage::Type::Private)\n {\n \/\/ We already have a handler for private messages\n return;\n }\n\n const QString &command = message->command();\n\n auto &handler = IrcMessageHandler::getInstance();\n\n \/\/ Below commands enabled through the twitch.tv\/membership CAP REQ\n if (command == \"MODE\")\n {\n handler.handleModeMessage(message);\n }\n else if (command == \"JOIN\")\n {\n handler.handleJoinMessage(message);\n }\n else if (command == \"PART\")\n {\n handler.handlePartMessage(message);\n }\n else if (command == \"USERSTATE\")\n {\n \/\/ Received USERSTATE upon JOINing a channel\n handler.handleUserStateMessage(message);\n }\n else if (command == \"ROOMSTATE\")\n {\n \/\/ Received ROOMSTATE upon JOINing a channel\n handler.handleRoomStateMessage(message);\n }\n}\n\nvoid TwitchIrcServer::writeConnectionMessageReceived(\n Communi::IrcMessage *message)\n{\n const QString &command = message->command();\n\n auto &handler = IrcMessageHandler::getInstance();\n\n \/\/ Below commands enabled through the twitch.tv\/commands CAP REQ\n if (command == \"USERSTATE\")\n {\n \/\/ Received USERSTATE upon PRIVMSGing\n handler.handleUserStateMessage(message);\n }\n else if (command == \"WHISPER\")\n {\n handler.handleWhisperMessage(message);\n }\n else if (command == \"USERNOTICE\")\n {\n handler.handleUserNoticeMessage(message, *this);\n }\n else if (command == \"ROOMSTATE\")\n {\n handler.handleRoomStateMessage(message);\n }\n else if (command == \"CLEARCHAT\")\n {\n handler.handleClearChatMessage(message);\n }\n else if (command == \"CLEARMSG\")\n {\n handler.handleClearMessageMessage(message);\n }\n else if (command == \"NOTICE\")\n {\n handler.handleNoticeMessage(\n static_cast<Communi::IrcNoticeMessage *>(message));\n }\n}\n\nvoid TwitchIrcServer::onReadConnected(IrcConnection *connection)\n{\n \/\/ twitch.tv\/tags enables IRCv3 tags on messages. See https:\/\/dev.twitch.tv\/docs\/irc\/tags\/\n \/\/ twitch.tv\/membership enables the JOIN\/PART\/MODE\/NAMES commands. See https:\/\/dev.twitch.tv\/docs\/irc\/membership\/\n \/\/ twitch.tv\/commands enables a bunch of miscellaneous command capabilities. See https:\/\/dev.twitch.tv\/docs\/irc\/commands\/\n \/\/ This is enabled here so we receive USERSTATE messages when joining channels\n connection->sendRaw(\n \"CAP REQ :twitch.tv\/tags twitch.tv\/membership twitch.tv\/commands\");\n\n AbstractIrcServer::onReadConnected(connection);\n}\n\nvoid TwitchIrcServer::onWriteConnected(IrcConnection *connection)\n{\n \/\/ twitch.tv\/tags enables IRCv3 tags on messages. See https:\/\/dev.twitch.tv\/docs\/irc\/tags\/\n \/\/ twitch.tv\/commands enables a bunch of miscellaneous command capabilities. See https:\/\/dev.twitch.tv\/docs\/irc\/commands\/\n \/\/ This is enabled here so we receive USERSTATE messages when typing messages, along with the other command capabilities\n connection->sendRaw(\"CAP REQ :twitch.tv\/tags twitch.tv\/commands\");\n\n AbstractIrcServer::onWriteConnected(connection);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::getCustomChannel(\n const QString &channelName)\n{\n if (channelName == \"\/whispers\")\n {\n return this->whispersChannel;\n }\n\n if (channelName == \"\/mentions\")\n {\n return this->mentionsChannel;\n }\n\n if (channelName == \"$$$\")\n {\n static auto channel =\n std::make_shared<Channel>(\"$$$\", chatterino::Channel::Type::Misc);\n static auto getTimer = [&] {\n for (auto i = 0; i < 1000; i++)\n {\n channel->addMessage(makeSystemMessage(QString::number(i + 1)));\n }\n\n auto timer = new QTimer;\n QObject::connect(timer, &QTimer::timeout, [] {\n channel->addMessage(\n makeSystemMessage(QTime::currentTime().toString()));\n });\n timer->start(500);\n return timer;\n }();\n\n return channel;\n }\n\n return nullptr;\n}\n\nvoid TwitchIrcServer::forEachChannelAndSpecialChannels(\n std::function<void(ChannelPtr)> func)\n{\n this->forEachChannel(func);\n\n func(this->whispersChannel);\n func(this->mentionsChannel);\n}\n\nstd::shared_ptr<Channel> TwitchIrcServer::getChannelOrEmptyByID(\n const QString &channelId)\n{\n std::lock_guard<std::mutex> lock(this->channelMutex);\n\n for (const auto &weakChannel : this->channels)\n {\n auto channel = weakChannel.lock();\n if (!channel)\n continue;\n\n auto twitchChannel = std::dynamic_pointer_cast<TwitchChannel>(channel);\n if (!twitchChannel)\n continue;\n\n if (twitchChannel->roomId() == channelId &&\n twitchChannel->getName().splitRef(\":\").size() < 3)\n {\n return twitchChannel;\n }\n }\n\n return Channel::getEmpty();\n}\n\nQString TwitchIrcServer::cleanChannelName(const QString &dirtyChannelName)\n{\n if (dirtyChannelName.startsWith('#'))\n return dirtyChannelName.mid(1).toLower();\n else\n return dirtyChannelName.toLower();\n}\n\nbool TwitchIrcServer::hasSeparateWriteConnection() const\n{\n return true;\n \/\/ return getSettings()->twitchSeperateWriteConnection;\n}\n\nvoid TwitchIrcServer::onMessageSendRequested(TwitchChannel *channel,\n const QString &message, bool &sent)\n{\n sent = false;\n\n {\n std::lock_guard<std::mutex> guard(this->lastMessageMutex_);\n\n \/\/ std::queue<std::chrono::steady_clock::time_point>\n auto &lastMessage = channel->hasHighRateLimit()\n ? this->lastMessageMod_\n : this->lastMessagePleb_;\n size_t maxMessageCount = channel->hasHighRateLimit() ? 99 : 19;\n auto minMessageOffset = (channel->hasHighRateLimit() ? 100ms : 1100ms);\n\n auto now = std::chrono::steady_clock::now();\n\n \/\/ check if you are sending messages too fast\n if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now)\n {\n if (this->lastErrorTimeSpeed_ + 30s < now)\n {\n auto errorMessage =\n makeSystemMessage(\"sending messages too fast\");\n\n channel->addMessage(errorMessage);\n\n this->lastErrorTimeSpeed_ = now;\n }\n return;\n }\n\n \/\/ remove messages older than 30 seconds\n while (!lastMessage.empty() && lastMessage.front() + 32s < now)\n {\n lastMessage.pop();\n }\n\n \/\/ check if you are sending too many messages\n if (lastMessage.size() >= maxMessageCount)\n {\n if (this->lastErrorTimeAmount_ + 30s < now)\n {\n auto errorMessage =\n makeSystemMessage(\"sending too many messages\");\n\n channel->addMessage(errorMessage);\n\n this->lastErrorTimeAmount_ = now;\n }\n return;\n }\n\n lastMessage.push(now);\n }\n\n this->sendMessage(channel->getName(), message);\n sent = true;\n}\n\nconst BttvEmotes &TwitchIrcServer::getBttvEmotes() const\n{\n return this->bttv;\n}\nconst FfzEmotes &TwitchIrcServer::getFfzEmotes() const\n{\n return this->ffz;\n}\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreRenderSystemCapabilities.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreException.h\"\n\nnamespace Ogre {\n\n\t\/\/-----------------------------------------------------------------------\n\tRenderSystemCapabilities::RenderSystemCapabilities()\n\t\t: mVendor(GPU_UNKNOWN)\n\t\t, mNumWorldMatrices(0)\n\t\t, mNumTextureUnits(0)\n\t\t, mStencilBufferBitDepth(0)\n\t\t, mNumVertexBlendMatrices(0)\n\t\t, mNumMultiRenderTargets(1)\n\t\t, mNonPOW2TexturesLimited(false)\n\t{\n\n\t\tfor(int i = 0; i < CAPS_CATEGORY_COUNT; i++)\n\t\t{\n\t\t\tmCapabilities[i] = 0;\n\t\t}\n\t\tmCategoryRelevant[CAPS_CATEGORY_COMMON] = true;\n\t\tmCategoryRelevant[CAPS_CATEGORY_COMMON_2] = true;\n\t\t\/\/ each rendersystem should enable these\n\t\tmCategoryRelevant[CAPS_CATEGORY_D3D9] = false;\n\t\tmCategoryRelevant[CAPS_CATEGORY_GL] = false;\n\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n\tRenderSystemCapabilities::~RenderSystemCapabilities()\n\t{\n\t}\n\t\/\/-----------------------------------------------------------------------\n\tvoid RenderSystemCapabilities::log(Log* pLog)\n\t{\n\t\tpLog->logMessage(\"RenderSystem capabilities\");\n\t\tpLog->logMessage(\"-------------------------\");\n\t\tpLog->logMessage(\"RenderSystem Name: \" + getRenderSystemName());\n\t\tpLog->logMessage(\"GPU Vendor: \" + vendorToString(getVendor()));\n\t\tpLog->logMessage(\"Device Name: \" + getDeviceName());\n\t\tpLog->logMessage(\"Driver Version: \" + getDriverVersion().toString());\n\t\tpLog->logMessage(\" * Fixed function pipeline: \" \n\t\t\t+ StringConverter::toString(hasCapability(RSC_FIXED_FUNCTION), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware generation of mipmaps: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_AUTOMIPMAP), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Texture blending: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_BLENDING), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Anisotropic texture filtering: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_ANISOTROPY), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Dot product texture operation: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_DOT3), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Cube mapping: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_CUBEMAPPING), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware stencil buffer: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWSTENCIL), true));\n\t\tif (hasCapability(RSC_HWSTENCIL))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Stencil depth: \"\n\t\t\t\t+ StringConverter::toString(getStencilBufferBitDepth()));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Two sided stencil support: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TWO_SIDED_STENCIL), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Wrap stencil values: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_STENCIL_WRAP), true));\n\t\t}\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware vertex \/ index buffers: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VBO), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Vertex programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantBoolCount));\n\t\tpLog->logMessage(\n\t\t\t\" * Fragment programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_FRAGMENT_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantBoolCount));\n\t\tpLog->logMessage(\n\t\t\t\" * Geometry programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_GEOMETRY_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantBoolCount));\n\t\tString profileList = \"\";\n\t\tfor(ShaderProfiles::iterator iter = mSupportedShaderProfiles.begin(), end = mSupportedShaderProfiles.end();\n\t\t\titer != end; ++iter)\n\t\t{\n\t\t\tprofileList += \" \" + *iter;\n\t\t}\n\t\tpLog->logMessage(\" * Supported Shader Profiles:\" + profileList);\n\n\t\tpLog->logMessage(\n\t\t\t\" * Texture Compression: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION), true));\n\t\tif (hasCapability(RSC_TEXTURE_COMPRESSION))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - DXT: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_DXT), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - VTC: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_VTC), true));\n\t\t\tpLog->logMessage(\n \" - PVRTC: \"\n + StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC), true));\n\t\t}\n\n\t\tpLog->logMessage(\n\t\t\t\" * Scissor Rectangle: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_SCISSOR_TEST), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware Occlusion Query: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWOCCLUSION), true));\n\t\tpLog->logMessage(\n\t\t\t\" * User clip planes: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_USER_CLIP_PLANES), true));\n\t\tpLog->logMessage(\n\t\t\t\" * VET_UBYTE4 vertex element type: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_FORMAT_UBYTE4), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Infinite far plane projection: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_INFINITE_FAR_PLANE), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware render-to-texture: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWRENDER_TO_TEXTURE), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Floating point textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_FLOAT), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Non-power-of-two textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_NON_POWER_OF_2_TEXTURES), true)\n\t\t\t+ (mNonPOW2TexturesLimited ? \" (limited)\" : \"\"));\n\t\tpLog->logMessage(\n\t\t\t\" * Volume textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_3D), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Multiple Render Targets: \"\n\t\t\t+ StringConverter::toString(mNumMultiRenderTargets));\n\t\tpLog->logMessage(\n\t\t\t\" - With different bit depths: \" + StringConverter::toString(hasCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Point Sprites: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_POINT_SPRITES), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Extended point parameters: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_POINT_EXTENDED_PARAMETERS), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Max Point Size: \"\n\t\t\t+ StringConverter::toString(mMaxPointSize));\n\t\tpLog->logMessage(\n\t\t\t\" * Vertex texture fetch: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_TEXTURE_FETCH), true));\n\t\tpLog->logMessage(\n \" * Number of world matrices: \"\n + StringConverter::toString(mNumWorldMatrices));\n\t\tpLog->logMessage(\n \" * Number of texture units: \"\n + StringConverter::toString(mNumTextureUnits));\n\t\tpLog->logMessage(\n \" * Stencil buffer depth: \"\n + StringConverter::toString(mStencilBufferBitDepth));\n\t\tpLog->logMessage(\n \" * Number of vertex blend matrices: \"\n + StringConverter::toString(mNumVertexBlendMatrices));\n\t\tif (hasCapability(RSC_VERTEX_TEXTURE_FETCH))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Max vertex textures: \"\n\t\t\t\t+ StringConverter::toString(mNumVertexTextureUnits));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Vertex textures shared: \"\n\t\t\t\t+ StringConverter::toString(mVertexTextureUnitsShared, true));\n\n\t\t}\n\t\tpLog->logMessage(\n\t\t\t\" * Render to Vertex Buffer : \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWRENDER_TO_VERTEX_BUFFER), true));\n\n\t\tif (mCategoryRelevant[CAPS_CATEGORY_GL])\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * GL 1.5 without VBO workaround: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_GL1_5_NOVBO), true));\n\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects (ARB extension): \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO_ARB), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects (ATI extension): \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO_ATI), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * PBuffer support: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_PBUFFER), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * GL 1.5 without HW-occlusion workaround: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_GL1_5_NOHWOCCLUSION), true));\n\t\t}\n\n\t\tif (mCategoryRelevant[CAPS_CATEGORY_D3D9])\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * DirectX per stage constants: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_PERSTAGECONSTANT), true));\n\t\t}\n\n\t}\n\t\/\/---------------------------------------------------------------------\n\tStringVector RenderSystemCapabilities::msGPUVendorStrings;\n\t\/\/---------------------------------------------------------------------\n\tGPUVendor RenderSystemCapabilities::vendorFromString(const String& vendorString)\n\t{\n\t\tinitVendorStrings();\n\t\tGPUVendor ret = GPU_UNKNOWN;\n\t\tString cmpString = vendorString;\n\t\tStringUtil::toLowerCase(cmpString);\n\t\tfor (int i = 0; i < GPU_VENDOR_COUNT; ++i)\n\t\t{\n\t\t\t\/\/ case insensitive (lower case)\n\t\t\tif (msGPUVendorStrings[i] == cmpString)\n\t\t\t{\n\t\t\t\tret = static_cast<GPUVendor>(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t\t\n\t}\n\t\/\/---------------------------------------------------------------------\n\tString RenderSystemCapabilities::vendorToString(GPUVendor v)\n\t{\n\t\tinitVendorStrings();\n\t\treturn msGPUVendorStrings[v];\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid RenderSystemCapabilities::initVendorStrings()\n\t{\n\t\tif (msGPUVendorStrings.empty())\n\t\t{\n\t\t\t\/\/ Always lower case!\n\t\t\tmsGPUVendorStrings.resize(GPU_VENDOR_COUNT);\n\t\t\tmsGPUVendorStrings[GPU_UNKNOWN] = \"unknown\";\n\t\t\tmsGPUVendorStrings[GPU_NVIDIA] = \"nvidia\";\n\t\t\tmsGPUVendorStrings[GPU_ATI] = \"ati\";\n\t\t\tmsGPUVendorStrings[GPU_INTEL] = \"intel\";\n\t\t\tmsGPUVendorStrings[GPU_3DLABS] = \"3dlabs\";\n\t\t\tmsGPUVendorStrings[GPU_S3] = \"s3\";\n\t\t\tmsGPUVendorStrings[GPU_MATROX] = \"matrox\";\n\t\t\tmsGPUVendorStrings[GPU_SIS] = \"sis\";\n\t\t\tmsGPUVendorStrings[GPU_IMAGINATION_TECHNOLOGIES] = \"imagination technologies\";\n\t\t\tmsGPUVendorStrings[GPU_APPLE] = \"apple\"; \/\/ iPhone Simulator\n\t\t}\n\t}\n\n};\n<commit_msg>Side-stepped a strange runtime crash on Android.<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreStableHeaders.h\"\n\n#include \"OgreRenderSystemCapabilities.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreException.h\"\n\nnamespace Ogre {\n\n\t\/\/-----------------------------------------------------------------------\n\tRenderSystemCapabilities::RenderSystemCapabilities()\n\t\t: mVendor(GPU_UNKNOWN)\n\t\t, mNumWorldMatrices(0)\n\t\t, mNumTextureUnits(0)\n\t\t, mStencilBufferBitDepth(0)\n\t\t, mNumVertexBlendMatrices(0)\n\t\t, mNumMultiRenderTargets(1)\n\t\t, mNonPOW2TexturesLimited(false)\n\t{\n\n\t\tfor(int i = 0; i < CAPS_CATEGORY_COUNT; i++)\n\t\t{\n\t\t\tmCapabilities[i] = 0;\n\t\t}\n\t\tmCategoryRelevant[CAPS_CATEGORY_COMMON] = true;\n\t\tmCategoryRelevant[CAPS_CATEGORY_COMMON_2] = true;\n\t\t\/\/ each rendersystem should enable these\n\t\tmCategoryRelevant[CAPS_CATEGORY_D3D9] = false;\n\t\tmCategoryRelevant[CAPS_CATEGORY_GL] = false;\n\n\n\t}\n\t\/\/-----------------------------------------------------------------------\n\tRenderSystemCapabilities::~RenderSystemCapabilities()\n\t{\n\t}\n\t\/\/-----------------------------------------------------------------------\n\tvoid RenderSystemCapabilities::log(Log* pLog)\n\t{\n\t\tpLog->logMessage(\"RenderSystem capabilities\");\n\t\tpLog->logMessage(\"-------------------------\");\n\t\tpLog->logMessage(\"RenderSystem Name: \" + getRenderSystemName());\n\t\tpLog->logMessage(\"GPU Vendor: \" + vendorToString(getVendor()));\n\t\tpLog->logMessage(\"Device Name: \" + getDeviceName());\n\t\tpLog->logMessage(\"Driver Version: \" + getDriverVersion().toString());\n\t\tpLog->logMessage(\" * Fixed function pipeline: \" \n\t\t\t+ StringConverter::toString(hasCapability(RSC_FIXED_FUNCTION), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware generation of mipmaps: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_AUTOMIPMAP), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Texture blending: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_BLENDING), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Anisotropic texture filtering: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_ANISOTROPY), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Dot product texture operation: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_DOT3), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Cube mapping: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_CUBEMAPPING), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware stencil buffer: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWSTENCIL), true));\n\t\tif (hasCapability(RSC_HWSTENCIL))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Stencil depth: \"\n\t\t\t\t+ StringConverter::toString(getStencilBufferBitDepth()));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Two sided stencil support: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TWO_SIDED_STENCIL), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Wrap stencil values: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_STENCIL_WRAP), true));\n\t\t}\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware vertex \/ index buffers: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VBO), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Vertex programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for vertex programs: \"\n + StringConverter::toString(mVertexProgramConstantBoolCount));\n\t\tpLog->logMessage(\n\t\t\t\" * Fragment programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_FRAGMENT_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for fragment programs: \"\n + StringConverter::toString(mFragmentProgramConstantBoolCount));\n\t\tpLog->logMessage(\n\t\t\t\" * Geometry programs: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_GEOMETRY_PROGRAM), true));\n\t\tpLog->logMessage(\n \" * Number of floating-point constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantFloatCount));\n\t\tpLog->logMessage(\n \" * Number of integer constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantIntCount));\n\t\tpLog->logMessage(\n \" * Number of boolean constants for geometry programs: \"\n + StringConverter::toString(mGeometryProgramConstantBoolCount));\n\t\tString profileList = \"\";\n\t\tfor(ShaderProfiles::iterator iter = mSupportedShaderProfiles.begin(), end = mSupportedShaderProfiles.end();\n\t\t\titer != end; ++iter)\n\t\t{\n\t\t\tprofileList += \" \" + *iter;\n\t\t}\n\t\tpLog->logMessage(\" * Supported Shader Profiles:\" + profileList);\n\n\t\tpLog->logMessage(\n\t\t\t\" * Texture Compression: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION), true));\n\t\tif (hasCapability(RSC_TEXTURE_COMPRESSION))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - DXT: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_DXT), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - VTC: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_VTC), true));\n\t\t\tpLog->logMessage(\n \" - PVRTC: \"\n + StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC), true));\n\t\t}\n\n\t\tpLog->logMessage(\n\t\t\t\" * Scissor Rectangle: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_SCISSOR_TEST), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware Occlusion Query: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWOCCLUSION), true));\n\t\tpLog->logMessage(\n\t\t\t\" * User clip planes: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_USER_CLIP_PLANES), true));\n\t\tpLog->logMessage(\n\t\t\t\" * VET_UBYTE4 vertex element type: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_FORMAT_UBYTE4), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Infinite far plane projection: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_INFINITE_FAR_PLANE), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Hardware render-to-texture: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWRENDER_TO_TEXTURE), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Floating point textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_FLOAT), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Non-power-of-two textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_NON_POWER_OF_2_TEXTURES), true)\n\t\t\t+ (mNonPOW2TexturesLimited ? \" (limited)\" : \"\"));\n\t\tpLog->logMessage(\n\t\t\t\" * Volume textures: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_TEXTURE_3D), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Multiple Render Targets: \"\n\t\t\t+ StringConverter::toString(mNumMultiRenderTargets));\n\t\tpLog->logMessage(\n\t\t\t\" - With different bit depths: \" + StringConverter::toString(hasCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Point Sprites: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_POINT_SPRITES), true));\n\t\tpLog->logMessage(\n\t\t\t\" * Extended point parameters: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_POINT_EXTENDED_PARAMETERS), true));\n\t\tif(hasCapability(RSC_POINT_SPRITES))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Max Point Size: \"\n\t\t\t\t+ StringConverter::toString(mMaxPointSize));\n\t\t}\n\t\tpLog->logMessage(\n\t\t\t\" * Vertex texture fetch: \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_VERTEX_TEXTURE_FETCH), true));\n\t\tpLog->logMessage(\n \" * Number of world matrices: \"\n + StringConverter::toString(mNumWorldMatrices));\n\t\tpLog->logMessage(\n \" * Number of texture units: \"\n + StringConverter::toString(mNumTextureUnits));\n\t\tpLog->logMessage(\n \" * Stencil buffer depth: \"\n + StringConverter::toString(mStencilBufferBitDepth));\n\t\tpLog->logMessage(\n \" * Number of vertex blend matrices: \"\n + StringConverter::toString(mNumVertexBlendMatrices));\n\t\tif (hasCapability(RSC_VERTEX_TEXTURE_FETCH))\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Max vertex textures: \"\n\t\t\t\t+ StringConverter::toString(mNumVertexTextureUnits));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" - Vertex textures shared: \"\n\t\t\t\t+ StringConverter::toString(mVertexTextureUnitsShared, true));\n\n\t\t}\n\t\tpLog->logMessage(\n\t\t\t\" * Render to Vertex Buffer : \"\n\t\t\t+ StringConverter::toString(hasCapability(RSC_HWRENDER_TO_VERTEX_BUFFER), true));\n\n\t\tif (mCategoryRelevant[CAPS_CATEGORY_GL])\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * GL 1.5 without VBO workaround: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_GL1_5_NOVBO), true));\n\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects (ARB extension): \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO_ARB), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * Frame Buffer objects (ATI extension): \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_FBO_ATI), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * PBuffer support: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_PBUFFER), true));\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * GL 1.5 without HW-occlusion workaround: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_GL1_5_NOHWOCCLUSION), true));\n\t\t}\n\n\t\tif (mCategoryRelevant[CAPS_CATEGORY_D3D9])\n\t\t{\n\t\t\tpLog->logMessage(\n\t\t\t\t\" * DirectX per stage constants: \"\n\t\t\t\t+ StringConverter::toString(hasCapability(RSC_PERSTAGECONSTANT), true));\n\t\t}\n\n\t}\n\t\/\/---------------------------------------------------------------------\n\tStringVector RenderSystemCapabilities::msGPUVendorStrings;\n\t\/\/---------------------------------------------------------------------\n\tGPUVendor RenderSystemCapabilities::vendorFromString(const String& vendorString)\n\t{\n\t\tinitVendorStrings();\n\t\tGPUVendor ret = GPU_UNKNOWN;\n\t\tString cmpString = vendorString;\n\t\tStringUtil::toLowerCase(cmpString);\n\t\tfor (int i = 0; i < GPU_VENDOR_COUNT; ++i)\n\t\t{\n\t\t\t\/\/ case insensitive (lower case)\n\t\t\tif (msGPUVendorStrings[i] == cmpString)\n\t\t\t{\n\t\t\t\tret = static_cast<GPUVendor>(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t\t\n\t}\n\t\/\/---------------------------------------------------------------------\n\tString RenderSystemCapabilities::vendorToString(GPUVendor v)\n\t{\n\t\tinitVendorStrings();\n\t\treturn msGPUVendorStrings[v];\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid RenderSystemCapabilities::initVendorStrings()\n\t{\n\t\tif (msGPUVendorStrings.empty())\n\t\t{\n\t\t\t\/\/ Always lower case!\n\t\t\tmsGPUVendorStrings.resize(GPU_VENDOR_COUNT);\n\t\t\tmsGPUVendorStrings[GPU_UNKNOWN] = \"unknown\";\n\t\t\tmsGPUVendorStrings[GPU_NVIDIA] = \"nvidia\";\n\t\t\tmsGPUVendorStrings[GPU_ATI] = \"ati\";\n\t\t\tmsGPUVendorStrings[GPU_INTEL] = \"intel\";\n\t\t\tmsGPUVendorStrings[GPU_3DLABS] = \"3dlabs\";\n\t\t\tmsGPUVendorStrings[GPU_S3] = \"s3\";\n\t\t\tmsGPUVendorStrings[GPU_MATROX] = \"matrox\";\n\t\t\tmsGPUVendorStrings[GPU_SIS] = \"sis\";\n\t\t\tmsGPUVendorStrings[GPU_IMAGINATION_TECHNOLOGIES] = \"imagination technologies\";\n\t\t\tmsGPUVendorStrings[GPU_APPLE] = \"apple\"; \/\/ iPhone Simulator\n\t\t}\n\t}\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Kevin Lim\n *\/\n\n#include \"arch\/types.hh\"\n#include \"arch\/isa_traits.hh\"\n#include \"base\/trace.hh\"\n#include \"base\/traceflags.hh\"\n#include \"cpu\/o3\/bpred_unit.hh\"\n\ntemplate<class Impl>\nBPredUnit<Impl>::BPredUnit(Params *params)\n : BTB(params->BTBEntries,\n params->BTBTagSize,\n params->instShiftAmt)\n{\n \/\/ Setup the selected predictor.\n if (params->predType == \"local\") {\n localBP = new LocalBP(params->localPredictorSize,\n params->localCtrBits,\n params->instShiftAmt);\n predictor = Local;\n } else if (params->predType == \"tournament\") {\n tournamentBP = new TournamentBP(params->localPredictorSize,\n params->localCtrBits,\n params->localHistoryTableSize,\n params->localHistoryBits,\n params->globalPredictorSize,\n params->globalHistoryBits,\n params->globalCtrBits,\n params->choicePredictorSize,\n params->choiceCtrBits,\n params->instShiftAmt);\n predictor = Tournament;\n } else {\n fatal(\"Invalid BP selected!\");\n }\n\n for (int i=0; i < Impl::MaxThreads; i++)\n RAS[i].init(params->RASSize);\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::regStats()\n{\n lookups\n .name(name() + \".BPredUnit.lookups\")\n .desc(\"Number of BP lookups\")\n ;\n\n condPredicted\n .name(name() + \".BPredUnit.condPredicted\")\n .desc(\"Number of conditional branches predicted\")\n ;\n\n condIncorrect\n .name(name() + \".BPredUnit.condIncorrect\")\n .desc(\"Number of conditional branches incorrect\")\n ;\n\n BTBLookups\n .name(name() + \".BPredUnit.BTBLookups\")\n .desc(\"Number of BTB lookups\")\n ;\n\n BTBHits\n .name(name() + \".BPredUnit.BTBHits\")\n .desc(\"Number of BTB hits\")\n ;\n\n BTBCorrect\n .name(name() + \".BPredUnit.BTBCorrect\")\n .desc(\"Number of correct BTB predictions (this stat may not \"\n \"work properly.\")\n ;\n\n usedRAS\n .name(name() + \".BPredUnit.usedRAS\")\n .desc(\"Number of times the RAS was used to get a target.\")\n ;\n\n RASIncorrect\n .name(name() + \".BPredUnit.RASInCorrect\")\n .desc(\"Number of incorrect RAS predictions.\")\n ;\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::switchOut()\n{\n \/\/ Clear any state upon switch out.\n for (int i = 0; i < Impl::MaxThreads; ++i) {\n squash(0, i);\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::takeOverFrom()\n{\n \/\/ Can reset all predictor state, but it's not necessarily better\n \/\/ than leaving it be.\n\/*\n for (int i = 0; i < Impl::MaxThreads; ++i)\n RAS[i].reset();\n\n BP.reset();\n BTB.reset();\n*\/\n}\n\ntemplate <class Impl>\nbool\nBPredUnit<Impl>::predict(DynInstPtr &inst, Addr &PC, unsigned tid)\n{\n \/\/ See if branch predictor predicts taken.\n \/\/ If so, get its target addr either from the BTB or the RAS.\n \/\/ Save off record of branch stuff so the RAS can be fixed\n \/\/ up once it's done.\n\n using TheISA::MachInst;\n\n bool pred_taken = false;\n Addr target;\n\n ++lookups;\n\n void *bp_history = NULL;\n\n if (inst->isUncondCtrl()) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Unconditional control.\\n\", tid);\n pred_taken = true;\n \/\/ Tell the BP there was an unconditional branch.\n BPUncond(bp_history);\n } else {\n ++condPredicted;\n\n pred_taken = BPLookup(PC, bp_history);\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Branch predictor predicted %i \"\n \"for PC %#x\\n\",\n tid, pred_taken, inst->readPC());\n }\n\n PredictorHistory predict_record(inst->seqNum, PC, pred_taken,\n bp_history, tid);\n\n \/\/ Now lookup in the BTB or RAS.\n if (pred_taken) {\n if (inst->isReturn()) {\n ++usedRAS;\n\n \/\/ If it's a function return call, then look up the address\n \/\/ in the RAS.\n target = RAS[tid].top();\n\n \/\/ Record the top entry of the RAS, and its index.\n predict_record.usedRAS = true;\n predict_record.RASIndex = RAS[tid].topIdx();\n predict_record.RASTarget = target;\n\n assert(predict_record.RASIndex < 16);\n\n RAS[tid].pop();\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x is a return, \"\n \"RAS predicted target: %#x, RAS index: %i.\\n\",\n tid, inst->readPC(), target, predict_record.RASIndex);\n } else {\n ++BTBLookups;\n\n if (inst->isCall()) {\n#if ISA_HAS_DELAY_SLOT\n Addr ras_pc = PC + (2 * sizeof(MachInst)); \/\/ Next Next PC\n#else\n Addr ras_pc = PC + sizeof(MachInst); \/\/ Next PC\n#endif\n RAS[tid].push(ras_pc);\n\n \/\/ Record that it was a call so that the top RAS entry can\n \/\/ be popped off if the speculation is incorrect.\n predict_record.wasCall = true;\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x was a call\"\n \", adding %#x to the RAS index: %i.\\n\",\n tid, inst->readPC(), ras_pc, RAS[tid].topIdx());\n }\n\n if (BTB.valid(PC, tid)) {\n ++BTBHits;\n\n \/\/ If it's not a return, use the BTB to get the target addr.\n target = BTB.lookup(PC, tid);\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x predicted\"\n \" target is %#x.\\n\",\n tid, inst->readPC(), target);\n\n } else {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: BTB doesn't have a \"\n \"valid entry.\\n\",tid);\n pred_taken = false;\n }\n\n }\n }\n\n if (pred_taken) {\n \/\/ Set the PC and the instruction's predicted target.\n PC = target;\n inst->setPredTarg(target);\n } else {\n PC = PC + sizeof(MachInst);\n inst->setPredTarg(PC);\n }\n\n predHist[tid].push_front(predict_record);\n\n DPRINTF(Fetch, \"[tid:%i]: predHist.size(): %i\\n\", tid, predHist[tid].size());\n\n return pred_taken;\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::update(const InstSeqNum &done_sn, unsigned tid)\n{\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Commiting branches until \"\n \"[sn:%lli].\\n\", tid, done_sn);\n\n while (!predHist[tid].empty() &&\n predHist[tid].back().seqNum <= done_sn) {\n \/\/ Update the branch predictor with the correct results.\n BPUpdate(predHist[tid].back().PC,\n predHist[tid].back().predTaken,\n predHist[tid].back().bpHistory);\n\n predHist[tid].pop_back();\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::squash(const InstSeqNum &squashed_sn, unsigned tid)\n{\n History &pred_hist = predHist[tid];\n\n while (!pred_hist.empty() &&\n pred_hist.front().seqNum > squashed_sn) {\n if (pred_hist.front().usedRAS) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Restoring top of RAS to: %i,\"\n \" target: %#x.\\n\",\n tid,\n pred_hist.front().RASIndex,\n pred_hist.front().RASTarget);\n\n RAS[tid].restore(pred_hist.front().RASIndex,\n pred_hist.front().RASTarget);\n } else if (pred_hist.front().wasCall) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Removing speculative entry \"\n \"added to the RAS.\\n\",tid);\n\n RAS[tid].pop();\n }\n\n \/\/ This call should delete the bpHistory.\n BPSquash(pred_hist.front().bpHistory);\n\n pred_hist.pop_front();\n }\n\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::squash(const InstSeqNum &squashed_sn,\n const Addr &corr_target,\n const bool actually_taken,\n unsigned tid)\n{\n \/\/ Now that we know that a branch was mispredicted, we need to undo\n \/\/ all the branches that have been seen up until this branch and\n \/\/ fix up everything.\n\n History &pred_hist = predHist[tid];\n\n ++condIncorrect;\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Squashing from sequence number %i, \"\n \"setting target to %#x.\\n\",\n tid, squashed_sn, corr_target);\n\n squash(squashed_sn, tid);\n\n \/\/ If there's a squash due to a syscall, there may not be an entry\n \/\/ corresponding to the squash. In that case, don't bother trying to\n \/\/ fix up the entry.\n if (!pred_hist.empty()) {\n assert(pred_hist.front().seqNum == squashed_sn);\n if (pred_hist.front().usedRAS) {\n ++RASIncorrect;\n }\n\n BPUpdate(pred_hist.front().PC, actually_taken,\n pred_hist.front().bpHistory);\n\n BTB.update(pred_hist.front().PC, corr_target, tid);\n pred_hist.pop_front();\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPUncond(void * &bp_history)\n{\n \/\/ Only the tournament predictor cares about unconditional branches.\n if (predictor == Tournament) {\n tournamentBP->uncondBr(bp_history);\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPSquash(void *bp_history)\n{\n if (predictor == Local) {\n localBP->squash(bp_history);\n } else if (predictor == Tournament) {\n tournamentBP->squash(bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nbool\nBPredUnit<Impl>::BPLookup(Addr &inst_PC, void * &bp_history)\n{\n if (predictor == Local) {\n return localBP->lookup(inst_PC, bp_history);\n } else if (predictor == Tournament) {\n return tournamentBP->lookup(inst_PC, bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPUpdate(Addr &inst_PC, bool taken, void *bp_history)\n{\n if (predictor == Local) {\n localBP->update(inst_PC, taken, bp_history);\n } else if (predictor == Tournament) {\n tournamentBP->update(inst_PC, taken, bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::dump()\n{\n typename History::iterator pred_hist_it;\n\n for (int i = 0; i < Impl::MaxThreads; ++i) {\n if (!predHist[i].empty()) {\n pred_hist_it = predHist[i].begin();\n\n cprintf(\"predHist[%i].size(): %i\\n\", i, predHist[i].size());\n\n while (pred_hist_it != predHist[i].end()) {\n cprintf(\"[sn:%lli], PC:%#x, tid:%i, predTaken:%i, \"\n \"bpHistory:%#x\\n\",\n (*pred_hist_it).seqNum, (*pred_hist_it).PC,\n (*pred_hist_it).tid, (*pred_hist_it).predTaken,\n (*pred_hist_it).bpHistory);\n pred_hist_it++;\n }\n\n cprintf(\"\\n\");\n }\n }\n}\n<commit_msg>Don't have \"predict\" set the predicted target of the instruction. Do that explicitly when you use predict.<commit_after>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Kevin Lim\n *\/\n\n#include \"arch\/types.hh\"\n#include \"arch\/isa_traits.hh\"\n#include \"base\/trace.hh\"\n#include \"base\/traceflags.hh\"\n#include \"cpu\/o3\/bpred_unit.hh\"\n\ntemplate<class Impl>\nBPredUnit<Impl>::BPredUnit(Params *params)\n : BTB(params->BTBEntries,\n params->BTBTagSize,\n params->instShiftAmt)\n{\n \/\/ Setup the selected predictor.\n if (params->predType == \"local\") {\n localBP = new LocalBP(params->localPredictorSize,\n params->localCtrBits,\n params->instShiftAmt);\n predictor = Local;\n } else if (params->predType == \"tournament\") {\n tournamentBP = new TournamentBP(params->localPredictorSize,\n params->localCtrBits,\n params->localHistoryTableSize,\n params->localHistoryBits,\n params->globalPredictorSize,\n params->globalHistoryBits,\n params->globalCtrBits,\n params->choicePredictorSize,\n params->choiceCtrBits,\n params->instShiftAmt);\n predictor = Tournament;\n } else {\n fatal(\"Invalid BP selected!\");\n }\n\n for (int i=0; i < Impl::MaxThreads; i++)\n RAS[i].init(params->RASSize);\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::regStats()\n{\n lookups\n .name(name() + \".BPredUnit.lookups\")\n .desc(\"Number of BP lookups\")\n ;\n\n condPredicted\n .name(name() + \".BPredUnit.condPredicted\")\n .desc(\"Number of conditional branches predicted\")\n ;\n\n condIncorrect\n .name(name() + \".BPredUnit.condIncorrect\")\n .desc(\"Number of conditional branches incorrect\")\n ;\n\n BTBLookups\n .name(name() + \".BPredUnit.BTBLookups\")\n .desc(\"Number of BTB lookups\")\n ;\n\n BTBHits\n .name(name() + \".BPredUnit.BTBHits\")\n .desc(\"Number of BTB hits\")\n ;\n\n BTBCorrect\n .name(name() + \".BPredUnit.BTBCorrect\")\n .desc(\"Number of correct BTB predictions (this stat may not \"\n \"work properly.\")\n ;\n\n usedRAS\n .name(name() + \".BPredUnit.usedRAS\")\n .desc(\"Number of times the RAS was used to get a target.\")\n ;\n\n RASIncorrect\n .name(name() + \".BPredUnit.RASInCorrect\")\n .desc(\"Number of incorrect RAS predictions.\")\n ;\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::switchOut()\n{\n \/\/ Clear any state upon switch out.\n for (int i = 0; i < Impl::MaxThreads; ++i) {\n squash(0, i);\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::takeOverFrom()\n{\n \/\/ Can reset all predictor state, but it's not necessarily better\n \/\/ than leaving it be.\n\/*\n for (int i = 0; i < Impl::MaxThreads; ++i)\n RAS[i].reset();\n\n BP.reset();\n BTB.reset();\n*\/\n}\n\ntemplate <class Impl>\nbool\nBPredUnit<Impl>::predict(DynInstPtr &inst, Addr &PC, unsigned tid)\n{\n \/\/ See if branch predictor predicts taken.\n \/\/ If so, get its target addr either from the BTB or the RAS.\n \/\/ Save off record of branch stuff so the RAS can be fixed\n \/\/ up once it's done.\n\n using TheISA::MachInst;\n\n bool pred_taken = false;\n Addr target;\n\n ++lookups;\n\n void *bp_history = NULL;\n\n if (inst->isUncondCtrl()) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Unconditional control.\\n\", tid);\n pred_taken = true;\n \/\/ Tell the BP there was an unconditional branch.\n BPUncond(bp_history);\n } else {\n ++condPredicted;\n\n pred_taken = BPLookup(PC, bp_history);\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Branch predictor predicted %i \"\n \"for PC %#x\\n\",\n tid, pred_taken, inst->readPC());\n }\n\n PredictorHistory predict_record(inst->seqNum, PC, pred_taken,\n bp_history, tid);\n\n \/\/ Now lookup in the BTB or RAS.\n if (pred_taken) {\n if (inst->isReturn()) {\n ++usedRAS;\n\n \/\/ If it's a function return call, then look up the address\n \/\/ in the RAS.\n target = RAS[tid].top();\n\n \/\/ Record the top entry of the RAS, and its index.\n predict_record.usedRAS = true;\n predict_record.RASIndex = RAS[tid].topIdx();\n predict_record.RASTarget = target;\n\n assert(predict_record.RASIndex < 16);\n\n RAS[tid].pop();\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x is a return, \"\n \"RAS predicted target: %#x, RAS index: %i.\\n\",\n tid, inst->readPC(), target, predict_record.RASIndex);\n } else {\n ++BTBLookups;\n\n if (inst->isCall()) {\n#if ISA_HAS_DELAY_SLOT\n Addr ras_pc = PC + (2 * sizeof(MachInst)); \/\/ Next Next PC\n#else\n Addr ras_pc = PC + sizeof(MachInst); \/\/ Next PC\n#endif\n RAS[tid].push(ras_pc);\n\n \/\/ Record that it was a call so that the top RAS entry can\n \/\/ be popped off if the speculation is incorrect.\n predict_record.wasCall = true;\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x was a call\"\n \", adding %#x to the RAS index: %i.\\n\",\n tid, inst->readPC(), ras_pc, RAS[tid].topIdx());\n }\n\n if (BTB.valid(PC, tid)) {\n ++BTBHits;\n\n \/\/ If it's not a return, use the BTB to get the target addr.\n target = BTB.lookup(PC, tid);\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Instruction %#x predicted\"\n \" target is %#x.\\n\",\n tid, inst->readPC(), target);\n\n } else {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: BTB doesn't have a \"\n \"valid entry.\\n\",tid);\n pred_taken = false;\n }\n\n }\n }\n\n predHist[tid].push_front(predict_record);\n\n DPRINTF(Fetch, \"[tid:%i]: predHist.size(): %i\\n\", tid, predHist[tid].size());\n\n return pred_taken;\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::update(const InstSeqNum &done_sn, unsigned tid)\n{\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Commiting branches until \"\n \"[sn:%lli].\\n\", tid, done_sn);\n\n while (!predHist[tid].empty() &&\n predHist[tid].back().seqNum <= done_sn) {\n \/\/ Update the branch predictor with the correct results.\n BPUpdate(predHist[tid].back().PC,\n predHist[tid].back().predTaken,\n predHist[tid].back().bpHistory);\n\n predHist[tid].pop_back();\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::squash(const InstSeqNum &squashed_sn, unsigned tid)\n{\n History &pred_hist = predHist[tid];\n\n while (!pred_hist.empty() &&\n pred_hist.front().seqNum > squashed_sn) {\n if (pred_hist.front().usedRAS) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Restoring top of RAS to: %i,\"\n \" target: %#x.\\n\",\n tid,\n pred_hist.front().RASIndex,\n pred_hist.front().RASTarget);\n\n RAS[tid].restore(pred_hist.front().RASIndex,\n pred_hist.front().RASTarget);\n } else if (pred_hist.front().wasCall) {\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Removing speculative entry \"\n \"added to the RAS.\\n\",tid);\n\n RAS[tid].pop();\n }\n\n \/\/ This call should delete the bpHistory.\n BPSquash(pred_hist.front().bpHistory);\n\n pred_hist.pop_front();\n }\n\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::squash(const InstSeqNum &squashed_sn,\n const Addr &corr_target,\n const bool actually_taken,\n unsigned tid)\n{\n \/\/ Now that we know that a branch was mispredicted, we need to undo\n \/\/ all the branches that have been seen up until this branch and\n \/\/ fix up everything.\n\n History &pred_hist = predHist[tid];\n\n ++condIncorrect;\n\n DPRINTF(Fetch, \"BranchPred: [tid:%i]: Squashing from sequence number %i, \"\n \"setting target to %#x.\\n\",\n tid, squashed_sn, corr_target);\n\n squash(squashed_sn, tid);\n\n \/\/ If there's a squash due to a syscall, there may not be an entry\n \/\/ corresponding to the squash. In that case, don't bother trying to\n \/\/ fix up the entry.\n if (!pred_hist.empty()) {\n assert(pred_hist.front().seqNum == squashed_sn);\n if (pred_hist.front().usedRAS) {\n ++RASIncorrect;\n }\n\n BPUpdate(pred_hist.front().PC, actually_taken,\n pred_hist.front().bpHistory);\n\n BTB.update(pred_hist.front().PC, corr_target, tid);\n pred_hist.pop_front();\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPUncond(void * &bp_history)\n{\n \/\/ Only the tournament predictor cares about unconditional branches.\n if (predictor == Tournament) {\n tournamentBP->uncondBr(bp_history);\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPSquash(void *bp_history)\n{\n if (predictor == Local) {\n localBP->squash(bp_history);\n } else if (predictor == Tournament) {\n tournamentBP->squash(bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nbool\nBPredUnit<Impl>::BPLookup(Addr &inst_PC, void * &bp_history)\n{\n if (predictor == Local) {\n return localBP->lookup(inst_PC, bp_history);\n } else if (predictor == Tournament) {\n return tournamentBP->lookup(inst_PC, bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::BPUpdate(Addr &inst_PC, bool taken, void *bp_history)\n{\n if (predictor == Local) {\n localBP->update(inst_PC, taken, bp_history);\n } else if (predictor == Tournament) {\n tournamentBP->update(inst_PC, taken, bp_history);\n } else {\n panic(\"Predictor type is unexpected value!\");\n }\n}\n\ntemplate <class Impl>\nvoid\nBPredUnit<Impl>::dump()\n{\n typename History::iterator pred_hist_it;\n\n for (int i = 0; i < Impl::MaxThreads; ++i) {\n if (!predHist[i].empty()) {\n pred_hist_it = predHist[i].begin();\n\n cprintf(\"predHist[%i].size(): %i\\n\", i, predHist[i].size());\n\n while (pred_hist_it != predHist[i].end()) {\n cprintf(\"[sn:%lli], PC:%#x, tid:%i, predTaken:%i, \"\n \"bpHistory:%#x\\n\",\n (*pred_hist_it).seqNum, (*pred_hist_it).PC,\n (*pred_hist_it).tid, (*pred_hist_it).predTaken,\n (*pred_hist_it).bpHistory);\n pred_hist_it++;\n }\n\n cprintf(\"\\n\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * simple_providers_cpp.cpp: C++ providers for SVN_AUTH_CRED_SIMPLE\n *\n * ====================================================================\n * Copyright (c) 2008 CollabNet. All rights reserved.\n *\n * This software is licensed as described in the file COPYING, which\n * you should have received as part of this distribution. The terms\n * are also available at http:\/\/subversion.tigris.org\/license-1.html.\n * If newer versions of this license are posted there, you may use a\n * newer version instead, at your option.\n *\n * This software consists of voluntary contributions made by many\n * individuals. For exact contribution history, see the revision\n * history and logs, available at http:\/\/subversion.tigris.org\/.\n * ====================================================================\n *\/\n\n\/* ==================================================================== *\/\n\n\n\f\n\/*** Includes. ***\/\n\n#include <apr_pools.h>\n#include \"svn_auth.h\"\n#include \"svn_error.h\"\n\n#include \"simple_providers.h\"\n\n#include \"svn_private_config.h\"\n\n#define SVN_AUTH__KWALLET_PASSWORD_TYPE \"kwallet\"\n\f\n\/*-----------------------------------------------------------------------*\/\n\/* KWallet simple provider, puts passwords in KWallet *\/\n\/*-----------------------------------------------------------------------*\/\n\n#ifdef SVN_HAVE_KWALLET\n#include <QtCore\/QString>\n#include <QtGui\/QWidget>\n\n#include <kwallet.h>\n\n\/* Implementation of password_get_t that retrieves the password\n from the KWallet. *\/\nstatic svn_boolean_t\nkwallet_password_get(const char **password,\n apr_hash_t *creds,\n const char *realmstring,\n const char *username,\n svn_boolean_t non_interactive,\n apr_pool_t *pool)\n{\n}\n\n\/* Implementation of password_set_t that stores the password in the\n KWallet. *\/\nstatic svn_boolean_t\nkwallet_password_set(apr_hash_t *creds,\n const char *realmstring,\n const char *username,\n const char *password,\n svn_boolean_t non_interactive,\n apr_pool_t *pool)\n{\n}\n\n\/* Get cached encrypted credentials from the simple provider's cache. *\/\nstatic svn_error_t *\nkwallet_simple_first_creds(void **credentials,\n void **iter_baton,\n void *provider_baton,\n apr_hash_t *parameters,\n const char *realmstring,\n apr_pool_t *pool)\n{\n return simple_first_creds_helper(credentials,\n iter_baton, provider_baton,\n parameters, realmstring,\n kwallet_password_get,\n SVN_AUTH__KWALLET_PASSWORD_TYPE,\n pool);\n}\n\n\/* Save encrypted credentials to the simple provider's cache. *\/\nstatic svn_error_t *\nkwallet_simple_save_creds(svn_boolean_t *saved,\n void *credentials,\n void *provider_baton,\n apr_hash_t *parameters,\n const char *realmstring,\n apr_pool_t *pool)\n{\n return simple_save_creds_helper(saved, credentials, provider_baton,\n parameters, realmstring,\n kwallet_password_set,\n SVN_AUTH__KWALLET_PASSWORD_TYPE,\n pool);\n}\n\nstatic const svn_auth_provider_t kwallet_simple_provider = {\n SVN_AUTH_CRED_SIMPLE,\n kwallet_simple_first_creds,\n NULL,\n kwallet_simple_save_creds\n};\n#endif \/* SVN_HAVE_KWALLET *\/\n\n\/* Public API *\/\nextern \"C\" svn_error_t *\nsvn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider,\n apr_pool_t *pool)\n{\n#ifdef SVN_HAVE_KWALLET\n svn_auth_provider_object_t *po =\n static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po)));\n\n po->vtable = &kwallet_simple_provider;\n *provider = po;\n return SVN_NO_ERROR;\n#else\n return svn_error_create(APR_ENOTIMPL, NULL,\n _(\"Support for KWallet not implemented\"));\n#endif \/* SVN_HAVE_KWALLET *\/\n}\n<commit_msg>On the 'kwallet' branch: Implement support for KWallet.<commit_after>\/*\n * simple_providers_cpp.cpp: C++ providers for SVN_AUTH_CRED_SIMPLE\n *\n * ====================================================================\n * Copyright (c) 2008 CollabNet. All rights reserved.\n *\n * This software is licensed as described in the file COPYING, which\n * you should have received as part of this distribution. The terms\n * are also available at http:\/\/subversion.tigris.org\/license-1.html.\n * If newer versions of this license are posted there, you may use a\n * newer version instead, at your option.\n *\n * This software consists of voluntary contributions made by many\n * individuals. For exact contribution history, see the revision\n * history and logs, available at http:\/\/subversion.tigris.org\/.\n * ====================================================================\n *\/\n\n\/* ==================================================================== *\/\n\n\n\f\n\/*** Includes. ***\/\n\n#include <apr_pools.h>\n#include \"svn_auth.h\"\n#include \"svn_error.h\"\n#include \"svn_version.h\"\n\n#include \"simple_providers.h\"\n\n#include \"svn_private_config.h\"\n\n#define SVN_AUTH__KWALLET_PASSWORD_TYPE \"kwallet\"\n\f\n\/*-----------------------------------------------------------------------*\/\n\/* KWallet simple provider, puts passwords in KWallet *\/\n\/*-----------------------------------------------------------------------*\/\n\n#ifdef SVN_HAVE_KWALLET\n#include <QtCore\/QString>\n#include <QtGui\/QWidget>\n\n#include <kapplication.h>\n#include <kcmdlineargs.h>\n#include <kwallet.h>\n\n\/* Implementation of password_get_t that retrieves the password\n from the KWallet. *\/\nstatic svn_boolean_t\nkwallet_password_get(const char **password,\n apr_hash_t *creds,\n const char *realmstring,\n const char *username,\n svn_boolean_t non_interactive,\n apr_pool_t *pool)\n{\n if (! KWallet::Wallet::isEnabled())\n {\n return FALSE;\n }\n\n KCmdLineArgs::init(1,\n (char *[1]) { \"svn\\0\" },\n \"Subversion\",\n \"subversion\",\n ki18n(\"Subversion\"),\n SVN_VER_NUMBER,\n ki18n(\"Version control system\"),\n KCmdLineArgs::CmdLineArgKDE);\n KApplication *application = new KApplication;\n QWidget *widget = new QWidget;\n WId *wid = new WId;\n *wid = widget->winId();\n svn_boolean_t ret = FALSE;\n QString wallet_name = KWallet::Wallet::NetworkWallet();\n QString folder = QString::fromUtf8(\"Subversion\");\n QString key = QString::fromUtf8(username) + \"@\" + QString::fromUtf8(realmstring);\n if (! KWallet::Wallet::keyDoesNotExist(wallet_name, folder, key))\n {\n KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, *wid, KWallet::Wallet::Synchronous);\n if (wallet)\n {\n if (wallet->hasFolder(folder))\n {\n if (wallet->setFolder(folder))\n {\n QString q_password;\n wallet->readPassword(key, q_password);\n if (q_password.size() > 0)\n {\n *password = apr_pstrmemdup(pool, q_password.toUtf8().data(), q_password.size());\n ret = TRUE;\n }\n }\n }\n }\n }\n KWallet::Wallet::closeWallet(wallet_name, false);\n return ret;\n}\n\n\/* Implementation of password_set_t that stores the password in the\n KWallet. *\/\nstatic svn_boolean_t\nkwallet_password_set(apr_hash_t *creds,\n const char *realmstring,\n const char *username,\n const char *password,\n svn_boolean_t non_interactive,\n apr_pool_t *pool)\n{\n if (! KWallet::Wallet::isEnabled())\n {\n return FALSE;\n }\n\n KCmdLineArgs::init(1,\n (char *[1]) { \"svn\\0\" },\n \"Subversion\",\n \"subversion\",\n ki18n(\"Subversion\"),\n SVN_VER_NUMBER,\n ki18n(\"Version control system\"),\n KCmdLineArgs::CmdLineArgKDE);\n KApplication *application = new KApplication;\n QWidget *widget = new QWidget;\n WId *wid = new WId;\n *wid = widget->winId();\n svn_boolean_t ret = FALSE;\n QString q_password = QString::fromUtf8(password);\n if (q_password.size() > 0)\n {\n QString wallet_name = KWallet::Wallet::NetworkWallet();\n QString folder = QString::fromUtf8(\"Subversion\");\n KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, *wid, KWallet::Wallet::Synchronous);\n if (wallet)\n {\n if (! wallet->hasFolder(folder))\n {\n wallet->createFolder(folder);\n }\n if (wallet->hasFolder(folder))\n {\n if (wallet->setFolder(folder))\n {\n QString key = QString::fromUtf8(username) + \"@\" + QString::fromUtf8(realmstring);\n if (wallet->writePassword(key, q_password))\n {\n ret = TRUE;\n }\n }\n }\n }\n KWallet::Wallet::closeWallet(wallet_name, false);\n }\n else\n {\n ret = TRUE;\n }\n return ret;\n}\n\n\/* Get cached encrypted credentials from the simple provider's cache. *\/\nstatic svn_error_t *\nkwallet_simple_first_creds(void **credentials,\n void **iter_baton,\n void *provider_baton,\n apr_hash_t *parameters,\n const char *realmstring,\n apr_pool_t *pool)\n{\n return simple_first_creds_helper(credentials,\n iter_baton, provider_baton,\n parameters, realmstring,\n kwallet_password_get,\n SVN_AUTH__KWALLET_PASSWORD_TYPE,\n pool);\n}\n\n\/* Save encrypted credentials to the simple provider's cache. *\/\nstatic svn_error_t *\nkwallet_simple_save_creds(svn_boolean_t *saved,\n void *credentials,\n void *provider_baton,\n apr_hash_t *parameters,\n const char *realmstring,\n apr_pool_t *pool)\n{\n return simple_save_creds_helper(saved, credentials, provider_baton,\n parameters, realmstring,\n kwallet_password_set,\n SVN_AUTH__KWALLET_PASSWORD_TYPE,\n pool);\n}\n\nstatic const svn_auth_provider_t kwallet_simple_provider = {\n SVN_AUTH_CRED_SIMPLE,\n kwallet_simple_first_creds,\n NULL,\n kwallet_simple_save_creds\n};\n#endif \/* SVN_HAVE_KWALLET *\/\n\n\/* Public API *\/\nextern \"C\" svn_error_t *\nsvn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider,\n apr_pool_t *pool)\n{\n#ifdef SVN_HAVE_KWALLET\n svn_auth_provider_object_t *po =\n static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po)));\n\n po->vtable = &kwallet_simple_provider;\n *provider = po;\n return SVN_NO_ERROR;\n#else\n return svn_error_create(APR_ENOTIMPL, NULL,\n _(\"Support for KWallet not available\"));\n#endif \/* SVN_HAVE_KWALLET *\/\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"ScriptEditor.h\"\n#include \"Resource.h\"\n#include <Commctrl.h>\n\n#define fileNameSize 256\n#define startCode L\"def OnClick(): \\r\\n\\t#put your code here \\r\\ndef OnTick():\\r\\n\\t#put your code here\"\n\nLRESULT __stdcall CScriptEditor::windowProc( HWND handle, UINT msg, WPARAM wParam, LPARAM lParam )\n{\t\n\tCScriptEditor* window;\n\tif( msg == WM_NCCREATE ) {\n\t\twindow = reinterpret_cast< CScriptEditor*>(\treinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);\n\t\tif( window ) {\n\t\t\tSetWindowLongPtr( handle, 0, reinterpret_cast<LONG_PTR>(window) );\n\t\t\twindow->OnNCCreate( handle );\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t} else {\n\t\twindow = reinterpret_cast<CScriptEditor*>(GetWindowLongPtr( handle, 0 ));\n\t\tswitch( msg ) {\n\t\t\tcase WM_CREATE:\n\t\t\t\twindow->OnCreate( handle );\n\t\t\t\treturn 1;\n\t\t\tcase WM_CLOSE:\n\t\t\t\twindow->OnClose();\n\t\t\t\treturn 0;\n\t\t\tcase WM_COMMAND:\n\t\t\t\twindow->OnCommand( wParam);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\treturn DefWindowProc( handle, msg, wParam, lParam );\n\t\t}\n\t}\n}\n\nbool CScriptEditor::RegisterClass()\n{\n\tHMODULE instance = GetModuleHandleW( nullptr );\n\tWNDCLASSEX windowClass;\n\tZeroMemory( &windowClass, sizeof( windowClass ) );\n\twindowClass.cbSize = sizeof( WNDCLASSEX );\n\twindowClass.lpfnWndProc = windowProc;\n\twindowClass.hInstance = instance;\n\twindowClass.lpszClassName = L\"ScriptEditor\";\n\treturn (RegisterClassEx( &windowClass ) != 0);\n}\n\nCScriptEditor::CScriptEditor() {\n\t\n}\n\nCScriptEditor::~CScriptEditor()\n{\n\tif( handle ) {\n\t\tDestroyWindow( handle );\n\t}\n}\n\nvoid CScriptEditor::OnNCCreate( HWND _handle )\n{\n\thandle = _handle;\n}\n\nbool CScriptEditor::Create()\n{\n\tHINSTANCE hInstance = GetModuleHandle( nullptr );\n\t\n\thandle = CreateWindowEx( 0, L\"ScriptEditor\", L\"ScriptEditor\",\n\t\tWS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,\n\t\tCW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr,\n\t\thInstance, this );\t\n\taddToolbar();\n\treturn (handle != 0);\n}\n\nvoid CScriptEditor::addToolbar()\n{\n\tHWND toolbar = CreateToolbarEx( handle, 0, 0,\n\t\t0, HINST_COMMCTRL, NULL, NULL, 0, 0, 0, 0, 0, sizeof( TBBUTTON ) );\n\tTBBUTTON tbb_buildin[] = {\n\t\t{ STD_FILENEW, ID_FILE_NEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t\t{ STD_FILEOPEN, ID_FILE_OPEN, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t\t{ STD_FILESAVE, ID_FILE_SAVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t};\n\tSendMessage( toolbar, (UINT)TB_ADDBUTTONS, _countof( tbb_buildin ), (LPARAM)&tbb_buildin );\n\tShowWindow( toolbar, TRUE );\n}\n\nHWND CScriptEditor::GetHandle() const\n{\n\treturn handle;\n}\n\nvoid CScriptEditor::OnCreate( HWND hwnd )\n{\n\tRECT windowRect;\t\n\tGetClientRect( hwnd, &windowRect );\t\n\tHWND editBox = CreateWindowEx(0, L\"EDIT\", NULL,\n\t\tWS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | WS_BORDER,\n\t\twindowRect.left, windowRect.top + 30,\n\t\twindowRect.right - windowRect.left,\n\t\twindowRect.bottom - windowRect.top,\n\t\thwnd, NULL, GetModuleHandle( 0 ), NULL );\t\n\tSetWindowText( editBox, startCode );\n}\n\nvoid CScriptEditor::OnClose()\n{\n\tif( handle ) {\n\t\tDestroyWindow( handle );\n\t}\n}\n\nvoid CScriptEditor::OnDestroy()\n{\n\tPostQuitMessage( 0 );\n}\n\nvoid CScriptEditor::Show( int cmdShow )\n{\n\tShowWindow( handle, cmdShow );\n}\n\nvoid CScriptEditor::OnCommand( WPARAM wParam)\n{\n\tswitch( LOWORD( wParam ) ) {\n\t\tcase ID_FILE_SAVE:\n\t\t{\n\t\t\tOnFileSave();\n\t\t\tbreak;\n\t\t}\n\t\tcase ID_FILE_NEW:\n\t\t{\n\t\t\tOnFileNew();\n\t\t\tbreak;\n\t\t}\n\t\tcase ID_FILE_OPEN:\n\t\t{\n\t\t\tOnFileOpen();\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nvoid CScriptEditor::OnFileSave()\n{\n\t\/\/ fix after resolving the problem with creating edit control\n\n\t\/*int len = GetWindowTextLength( editBox );\n\tTCHAR* buffer;\n\tbuffer = (TCHAR*)calloc( len + 1, sizeof( TCHAR ) );\n\tGetWindowText( editBox, buffer, len + 1 );*\/\n\n\tint len = 5;\n\tLPWSTR buffer = L\"12345\";\n\n\t\/\/MessageBox( NULL, L\"FILE\", L\"SAVE\", NULL );\n\twchar_t fileName[fileNameSize];\n\tOPENFILENAME ofn;\n\tmemset( &ofn, 0, sizeof( OPENFILENAME ) );\n\tofn.lStructSize = sizeof( OPENFILENAME );\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = fileName;\n\tofn.nMaxFile = sizeof( fileName );\n\tofn.lpstrFilter = L\"Python script(*.py)\\0*.py\\0\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrTitle = L\"Save as\";\n\tofn.lpstrInitialDir = L\"c:\\\\\";\n\tofn.lpstrDefExt = ofn.lpstrFilter;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n\n\tint result = GetSaveFileName( &ofn );\n\tif( result ) {\n\t\tDWORD writtenBytes;\n\t\tHANDLE file = CreateFile( ofn.lpstrFile, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 );\n\t\tWORD uCode = 0xFEFF;\n\t\tWriteFile( file, &uCode, 2, &writtenBytes, NULL );\n\t\tWriteFile( file, buffer, 2 * len, &writtenBytes, NULL );\n\t\tCloseHandle( file );\n\t}\n}\n\nvoid CScriptEditor::OnFileNew()\n{\n\tMessageBox( NULL, L\"FILE\", L\"NEW\", NULL );\n}\n\nvoid CScriptEditor::OnFileOpen()\n{\n\tMessageBox( NULL, L\"FILE\", L\"OPEN\", NULL );\n}<commit_msg>Added File oppenning to ScriptEditor<commit_after>#include \"stdafx.h\"\n#include \"ScriptEditor.h\"\n#include \"Resource.h\"\n#include <Commctrl.h>\n\n#define startCode L\"def OnClick(): \\r\\n\\t#put your code here \\r\\ndef OnTick():\\r\\n\\t#put your code here\"\n\nLRESULT __stdcall CScriptEditor::windowProc( HWND handle, UINT msg, WPARAM wParam, LPARAM lParam )\n{\t\n\tCScriptEditor* window;\n\tif( msg == WM_NCCREATE ) {\n\t\twindow = reinterpret_cast< CScriptEditor*>(\treinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);\n\t\tif( window ) {\n\t\t\tSetWindowLongPtr( handle, 0, reinterpret_cast<LONG_PTR>(window) );\n\t\t\twindow->OnNCCreate( handle );\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t} else {\n\t\twindow = reinterpret_cast<CScriptEditor*>(GetWindowLongPtr( handle, 0 ));\n\t\tswitch( msg ) {\n\t\t\tcase WM_CREATE:\n\t\t\t\twindow->OnCreate( handle );\n\t\t\t\treturn 1;\n\t\t\tcase WM_CLOSE:\n\t\t\t\twindow->OnClose();\n\t\t\t\treturn 0;\n\t\t\tcase WM_COMMAND:\n\t\t\t\twindow->OnCommand( wParam);\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\treturn DefWindowProc( handle, msg, wParam, lParam );\n\t\t}\n\t}\n}\n\nbool CScriptEditor::RegisterClass()\n{\n\tHMODULE instance = GetModuleHandleW( nullptr );\n\tWNDCLASSEX windowClass;\n\tZeroMemory( &windowClass, sizeof( windowClass ) );\n\twindowClass.cbSize = sizeof( WNDCLASSEX );\n\twindowClass.lpfnWndProc = windowProc;\n\twindowClass.hInstance = instance;\n\twindowClass.lpszClassName = L\"ScriptEditor\";\n\treturn (RegisterClassEx( &windowClass ) != 0);\n}\n\nCScriptEditor::CScriptEditor() {\n\t\n}\n\nCScriptEditor::~CScriptEditor()\n{\n\tif( handle ) {\n\t\tDestroyWindow( handle );\n\t}\n}\n\nvoid CScriptEditor::OnNCCreate( HWND _handle )\n{\n\thandle = _handle;\n}\n\nbool CScriptEditor::Create()\n{\n\tHINSTANCE hInstance = GetModuleHandle( nullptr );\n\t\n\thandle = CreateWindowEx( 0, L\"ScriptEditor\", L\"ScriptEditor\",\n\t\tWS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,\n\t\tCW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr,\n\t\thInstance, this );\t\n\taddToolbar();\n\treturn (handle != 0);\n}\n\nvoid CScriptEditor::addToolbar()\n{\n\tHWND toolbar = CreateToolbarEx( handle, 0, 0,\n\t\t0, HINST_COMMCTRL, NULL, NULL, 0, 0, 0, 0, 0, sizeof( TBBUTTON ) );\n\tTBBUTTON tbb_buildin[] = {\n\t\t{ STD_FILENEW, ID_FILE_NEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t\t{ STD_FILEOPEN, ID_FILE_OPEN, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t\t{ STD_FILESAVE, ID_FILE_SAVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0, 0, 0, 0 },\n\t};\n\tSendMessage( toolbar, (UINT)TB_ADDBUTTONS, _countof( tbb_buildin ), (LPARAM)&tbb_buildin );\n\tShowWindow( toolbar, TRUE );\n}\n\nHWND CScriptEditor::GetHandle() const\n{\n\treturn handle;\n}\n\nvoid CScriptEditor::OnCreate( HWND hwnd )\n{\n\tRECT windowRect;\t\n\tGetClientRect( hwnd, &windowRect );\t\n\t\/\/ can't asign to class member, this problem should be resolved\n\tHWND editBox = CreateWindowEx(0, L\"EDIT\", NULL,\n\t\tWS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | WS_BORDER,\n\t\twindowRect.left, windowRect.top + 30,\n\t\twindowRect.right - windowRect.left,\n\t\twindowRect.bottom - windowRect.top,\n\t\thwnd, NULL, GetModuleHandle( 0 ), NULL );\t\n\tSetWindowText( editBox, startCode );\n}\n\nvoid CScriptEditor::OnClose()\n{\n\tif( handle ) {\n\t\tDestroyWindow( handle );\n\t}\n}\n\nvoid CScriptEditor::OnDestroy()\n{\n\tPostQuitMessage( 0 );\n}\n\nvoid CScriptEditor::Show( int cmdShow )\n{\n\tShowWindow( handle, cmdShow );\n}\n\nvoid CScriptEditor::OnCommand( WPARAM wParam)\n{\n\tswitch( LOWORD( wParam ) ) {\n\t\tcase ID_FILE_SAVE:\n\t\t{\n\t\t\tOnFileSave();\n\t\t\tbreak;\n\t\t}\n\t\tcase ID_FILE_NEW:\n\t\t{\n\t\t\tOnFileNew();\n\t\t\tbreak;\n\t\t}\n\t\tcase ID_FILE_OPEN:\n\t\t{\n\t\t\tOnFileOpen();\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nvoid CScriptEditor::OnFileSave()\n{\n\t\/\/ fix after resolving the problem with creating edit control\n\n\t\/*int len = GetWindowTextLength( editBox );\n\tTCHAR* buffer;\n\tbuffer = (TCHAR*)calloc( len + 1, sizeof( TCHAR ) );\n\tGetWindowText( editBox, buffer, len + 1 );*\/\n\n\tint len = 5;\n\tLPWSTR buffer = L\"12345\";\n\t\n\twchar_t fileName[MAX_PATH];\n\tOPENFILENAME ofn;\n\tmemset( &ofn, 0, sizeof( OPENFILENAME ) );\n\tofn.lStructSize = sizeof( OPENFILENAME );\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = fileName;\n\tofn.nMaxFile = sizeof( fileName );\n\tofn.lpstrFilter = L\"Python script(*.py)\\0*.py\\0\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrTitle = L\"Save as\";\n\tofn.lpstrInitialDir = L\"c:\\\\\";\n\tofn.lpstrDefExt = ofn.lpstrFilter;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n\n\tint result = GetSaveFileName( &ofn );\n\tif( result ) {\n\t\tDWORD writtenBytes;\n\t\tHANDLE file = CreateFile( ofn.lpstrFile, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 );\n\t\tWORD uCode = 0xFEFF;\n\t\tWriteFile( file, &uCode, 2, &writtenBytes, NULL );\n\t\tWriteFile( file, buffer, 2 * len, &writtenBytes, NULL );\n\t\tCloseHandle( file );\n\t}\n}\n\nvoid CScriptEditor::OnFileNew()\n{\n\tMessageBox( NULL, L\"FILE\", L\"NEW\", NULL );\n\t\/\/SetWindowText( editBox, L\" \" ); fix after resolving problems\n}\n\nvoid CScriptEditor::OnFileOpen()\n{\n\tOPENFILENAME ofn;\n\tTCHAR fileName[MAX_PATH];\n\tmemset( &ofn, 0, sizeof( OPENFILENAME ) );\n\tofn.lStructSize = sizeof( OPENFILENAME );\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = fileName;\n\tofn.nMaxFile = sizeof( fileName );\n\tofn.lpstrFilter = L\"Python script(*.py)\\0*.py\\0\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrTitle = L\"Open\";\n\tofn.lpstrInitialDir = L\"c:\\\\\";\n\tofn.lpstrDefExt = ofn.lpstrFilter;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;\n\n\tint result = GetOpenFileName( &ofn );\n\tif( result ) {\n\t\tHANDLE file = CreateFile( ofn.lpstrFile, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );\n\t\twchar_t* buffer;\n\t\tauto fileSize = GetFileSize( file, NULL );\n\t\tDWORD newsize = 0;\t\t\n\t\tbuffer = (wchar_t*)malloc( fileSize );\n\t\tReadFile( file, buffer, fileSize, &newsize, NULL ); \n\n\t\tMessageBox( NULL, buffer, L\" \", NULL );\n\t\t\/\/SetWindowText( editBox, buffer ); fix after resolving problems\n\n\t\tCloseHandle( file );\n\t}\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"..\/interface\/MuonsFiller.h\"\n\n#include \"DataFormats\/VertexReco\/interface\/Vertex.h\"\n#include \"DataFormats\/MuonReco\/interface\/MuonSelectors.h\"\n#include \"DataFormats\/Math\/interface\/deltaR.h\"\n#include \"DataFormats\/PatCandidates\/interface\/Muon.h\"\n#include \"DataFormats\/PatCandidates\/interface\/TriggerObjectStandAlone.h\"\n#include \"DataFormats\/PatCandidates\/interface\/PackedCandidate.h\"\n#include \"DataFormats\/Common\/interface\/RefToPtr.h\"\n\nMuonsFiller::MuonsFiller(std::string const& _name, edm::ParameterSet const& _cfg, edm::ConsumesCollector& _coll) :\n FillerBase(_name, _cfg),\n minPt_(getParameter_<double>(_cfg, \"minPt\", -1.)),\n maxEta_(getParameter_<double>(_cfg, \"maxEta\", 10.))\n{\n getToken_(muonsToken_, _cfg, _coll, \"muons\");\n getToken_(verticesToken_, _cfg, _coll, \"common\", \"vertices\");\n\n if (useTrigger_) {\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n std::string name(panda::Muon::TriggerObjectName[iT]); \/\/ \"f<trigger filter name>\"\n auto filters(getParameter_<VString>(_cfg, \"triggerObjects.\" + name.substr(1)));\n triggerObjects_[iT].insert(filters.begin(), filters.end());\n }\n }\n}\n\nvoid\nMuonsFiller::addOutput(TFile& _outputFile)\n{\n TDirectory::TContext context(&_outputFile);\n auto* t(panda::utils::makeDocTree(\"MuonTriggerObject\", panda::Muon::TriggerObjectName, panda::Muon::nTriggerObjects));\n t->Write();\n delete t;\n}\n\nvoid\nMuonsFiller::branchNames(panda::utils::BranchList& _eventBranches, panda::utils::BranchList&) const\n{\n _eventBranches.emplace_back(\"muons\");\n\n if (isRealData_)\n _eventBranches.emplace_back(\"!muons.matchedGen_\");\n if (!useTrigger_)\n _eventBranches.emplace_back(\"!muons.triggerMatch\");\n}\n\nvoid\nMuonsFiller::fill(panda::Event& _outEvent, edm::Event const& _inEvent, edm::EventSetup const& _setup)\n{\n auto& inMuons(getProduct_(_inEvent, muonsToken_));\n auto& vertices(getProduct_(_inEvent, verticesToken_));\n\n auto& outMuons(_outEvent.muons);\n\n std::vector<edm::Ptr<reco::Muon>> ptrList;\n\n unsigned iMu(-1);\n for (auto& inMuon : inMuons) {\n ++iMu;\n\n if (inMuon.pt() < minPt_)\n continue;\n if (std::abs(inMuon.eta()) > maxEta_)\n continue;\n\n auto& outMuon(outMuons.create_back());\n\n fillP4(outMuon, inMuon);\n\n outMuon.charge = inMuon.charge();\n\n auto& pfIso(inMuon.pfIsolationR04());\n\n outMuon.chIso = pfIso.sumChargedHadronPt;\n outMuon.nhIso = pfIso.sumNeutralHadronEt;\n outMuon.phIso = pfIso.sumPhotonEt;\n outMuon.puIso = pfIso.sumPUPt;\n\n if (dynamic_cast<pat::Muon const*>(&inMuon)) {\n auto& patMuon(static_cast<pat::Muon const&>(inMuon));\n\n outMuon.loose = patMuon.isLooseMuon();\n outMuon.medium = patMuon.isMediumMuon();\n \/\/ Following the \"short-term instruction for Moriond 2017\" given in https:\/\/twiki.cern.ch\/twiki\/bin\/viewauth\/CMS\/SWGuideMuonIdRun2#MediumID2016_to_be_used_with_Run\n \/\/ Valid only for runs B-F\n outMuon.mediumBtoF = outMuon.loose && inMuon.innerTrack()->validFraction() > 0.49 &&\n ((inMuon.isGlobalMuon() &&\n inMuon.globalTrack()->normalizedChi2() < 3. &&\n inMuon.combinedQuality().chi2LocalPosition < 12. &&\n inMuon.combinedQuality().trkKink < 20. &&\n muon::segmentCompatibility(inMuon) > 0.303) ||\n muon::segmentCompatibility(inMuon) > 0.451);\n \n if (vertices.size() == 0)\n outMuon.tight = false;\n else\n outMuon.tight = patMuon.isTightMuon(vertices.at(0));\n }\n else {\n outMuon.loose = muon::isLooseMuon(inMuon);\n outMuon.medium = muon::isMediumMuon(inMuon);\n if (vertices.size() == 0)\n outMuon.tight = false;\n else\n outMuon.tight = muon::isTightMuon(inMuon, vertices.at(0));\n }\n\n outMuon.pfPt = inMuon.pfP4().pt();\n\n ptrList.push_back(inMuons.ptrAt(iMu));\n }\n \n auto originalIndices(outMuons.sort(panda::Particle::PtGreater));\n\n \/\/ export panda <-> reco mapping\n\n auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>());\n auto& pfMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"pf\"));\n auto& vtxMuMap(objectMap_->get<reco::Vertex, panda::Muon>());\n auto& genMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"gen\"));\n\n for (unsigned iP(0); iP != outMuons.size(); ++iP) {\n auto& outMuon(outMuons[iP]);\n unsigned idx(originalIndices[iP]);\n muMuMap.add(ptrList[idx], outMuon);\n\n auto sourcePtr(ptrList[idx]->sourceCandidatePtr(0));\n if (sourcePtr.isNonnull()) {\n pfMuMap.add(sourcePtr, outMuon);\n if (dynamic_cast<pat::PackedCandidate const*>(sourcePtr.get())) {\n auto vtxRef(static_cast<pat::PackedCandidate const&>(*sourcePtr).vertexRef());\n if (vtxRef.isNonnull())\n vtxMuMap.add(edm::refToPtr(vtxRef), outMuon);\n }\n }\n\n if (!isRealData_) {\n auto& inMuon(*ptrList[idx]);\n\n if (dynamic_cast<pat::Muon const*>(&inMuon)) {\n auto& patMuon(static_cast<pat::Muon const&>(inMuon));\n auto ref(patMuon.genParticleRef());\n if (ref.isNonnull())\n genMuMap.add(edm::refToPtr(ref), outMuon);\n }\n }\n }\n}\n\nvoid\nMuonsFiller::setRefs(ObjectMapStore const& _objectMaps)\n{\n auto& pfMuMap(objectMap_->get<reco::Candidate, panda::Muon>());\n auto& vtxMuMap(objectMap_->get<reco::Vertex, panda::Muon>());\n\n auto& pfMap(_objectMaps.at(\"pfCandidates\").get<reco::Candidate, panda::PFCand>().fwdMap);\n auto& vtxMap(_objectMaps.at(\"vertices\").get<reco::Vertex, panda::RecoVertex>().fwdMap);\n\n for (auto& link : pfMuMap.bwdMap) { \/\/ panda -> edm\n auto& outMuon(*link.first);\n auto& pfPtr(link.second);\n\n \/\/ muon sourceCandidatePtr can point to the AOD pfCandidates in some cases\n auto pfItr(pfMap.find(pfPtr));\n if (pfItr == pfMap.end())\n continue;\n\n outMuon.matchedPF.setRef(pfItr->second);\n }\n\n for (auto& link : vtxMuMap.bwdMap) { \/\/ panda -> edm\n auto& outMuon(*link.first);\n auto& vtxPtr(link.second);\n\n outMuon.vertex.setRef(vtxMap.at(vtxPtr));\n }\n\n if (!isRealData_) {\n auto& genMuMap(objectMap_->get<reco::Candidate, panda::Muon>());\n\n auto& genMap(_objectMaps.at(\"genParticles\").get<reco::Candidate, panda::GenParticle>().fwdMap);\n\n for (auto& link : genMuMap.bwdMap) {\n auto& genPtr(link.second);\n if (genMap.find(genPtr) == genMap.end())\n continue;\n\n auto& outMuon(*link.first);\n outMuon.matchedGen.setRef(genMap.at(genPtr));\n }\n }\n\n if (useTrigger_) {\n auto& objMap(_objectMaps.at(\"global\").get<pat::TriggerObjectStandAlone, VString>().fwdMap);\n\n std::vector<pat::TriggerObjectStandAlone const*> triggerObjects[panda::Muon::nTriggerObjects];\n\n \/\/ loop over the trigger filters we are interested in\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n \/\/ loop over all trigger objects (and their associated filter names)\n for (auto& objAndNames : objMap) { \/\/ (TO ptr, VString)\n VString const& names(*objAndNames.second);\n \/\/ loop over the associated filter names\n for (auto& name : names) {\n if (triggerObjects_[iT].find(name) != triggerObjects_[iT].end()) {\n triggerObjects[iT].push_back(&*objAndNames.first);\n break;\n }\n }\n }\n }\n\n auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>().fwdMap);\n\n for (auto& link : muMuMap) { \/\/ edm -> panda\n auto& inMuon(*link.first);\n auto& outMuon(*link.second);\n\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n for (auto* obj : triggerObjects[iT]) {\n if (reco::deltaR(inMuon, *obj) < 0.3) {\n outMuon.triggerMatch[iT] = true;\n break;\n }\n }\n }\n }\n }\n}\n\nDEFINE_TREEFILLER(MuonsFiller);\n<commit_msg>forgot to fix muon<commit_after>#include \"..\/interface\/MuonsFiller.h\"\n\n#include \"DataFormats\/VertexReco\/interface\/Vertex.h\"\n#include \"DataFormats\/MuonReco\/interface\/MuonSelectors.h\"\n#include \"DataFormats\/Math\/interface\/deltaR.h\"\n#include \"DataFormats\/PatCandidates\/interface\/Muon.h\"\n#include \"DataFormats\/PatCandidates\/interface\/TriggerObjectStandAlone.h\"\n#include \"DataFormats\/PatCandidates\/interface\/PackedCandidate.h\"\n#include \"DataFormats\/Common\/interface\/RefToPtr.h\"\n\nMuonsFiller::MuonsFiller(std::string const& _name, edm::ParameterSet const& _cfg, edm::ConsumesCollector& _coll) :\n FillerBase(_name, _cfg),\n minPt_(getParameter_<double>(_cfg, \"minPt\", -1.)),\n maxEta_(getParameter_<double>(_cfg, \"maxEta\", 10.))\n{\n getToken_(muonsToken_, _cfg, _coll, \"muons\");\n getToken_(verticesToken_, _cfg, _coll, \"common\", \"vertices\");\n\n if (useTrigger_) {\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n std::string name(panda::Muon::TriggerObjectName[iT]); \/\/ \"f<trigger filter name>\"\n auto filters(getParameter_<VString>(_cfg, \"triggerObjects.\" + name.substr(1)));\n triggerObjects_[iT].insert(filters.begin(), filters.end());\n }\n }\n}\n\nvoid\nMuonsFiller::addOutput(TFile& _outputFile)\n{\n TDirectory::TContext context(&_outputFile);\n auto* t(panda::utils::makeDocTree(\"MuonTriggerObject\", panda::Muon::TriggerObjectName, panda::Muon::nTriggerObjects));\n t->Write();\n delete t;\n}\n\nvoid\nMuonsFiller::branchNames(panda::utils::BranchList& _eventBranches, panda::utils::BranchList&) const\n{\n _eventBranches.emplace_back(\"muons\");\n\n if (isRealData_)\n _eventBranches.emplace_back(\"!muons.matchedGen_\");\n if (!useTrigger_)\n _eventBranches.emplace_back(\"!muons.triggerMatch\");\n}\n\nvoid\nMuonsFiller::fill(panda::Event& _outEvent, edm::Event const& _inEvent, edm::EventSetup const& _setup)\n{\n auto& inMuons(getProduct_(_inEvent, muonsToken_));\n auto& vertices(getProduct_(_inEvent, verticesToken_));\n\n auto& outMuons(_outEvent.muons);\n\n std::vector<edm::Ptr<reco::Muon>> ptrList;\n\n unsigned iMu(-1);\n for (auto& inMuon : inMuons) {\n ++iMu;\n\n if (inMuon.pt() < minPt_)\n continue;\n if (std::abs(inMuon.eta()) > maxEta_)\n continue;\n\n auto& outMuon(outMuons.create_back());\n\n fillP4(outMuon, inMuon);\n\n outMuon.charge = inMuon.charge();\n\n auto& pfIso(inMuon.pfIsolationR04());\n\n outMuon.chIso = pfIso.sumChargedHadronPt;\n outMuon.nhIso = pfIso.sumNeutralHadronEt;\n outMuon.phIso = pfIso.sumPhotonEt;\n outMuon.puIso = pfIso.sumPUPt;\n\n if (dynamic_cast<pat::Muon const*>(&inMuon)) {\n auto& patMuon(static_cast<pat::Muon const&>(inMuon));\n\n outMuon.loose = patMuon.isLooseMuon();\n outMuon.medium = patMuon.isMediumMuon();\n \/\/ Following the \"short-term instruction for Moriond 2017\" given in https:\/\/twiki.cern.ch\/twiki\/bin\/viewauth\/CMS\/SWGuideMuonIdRun2#MediumID2016_to_be_used_with_Run\n \/\/ Valid only for runs B-F\n outMuon.mediumBtoF = outMuon.loose && inMuon.innerTrack()->validFraction() > 0.49 &&\n ((inMuon.isGlobalMuon() &&\n inMuon.globalTrack()->normalizedChi2() < 3. &&\n inMuon.combinedQuality().chi2LocalPosition < 12. &&\n inMuon.combinedQuality().trkKink < 20. &&\n muon::segmentCompatibility(inMuon) > 0.303) ||\n muon::segmentCompatibility(inMuon) > 0.451);\n \n if (vertices.size() == 0)\n outMuon.tight = false;\n else\n outMuon.tight = patMuon.isTightMuon(vertices.at(0));\n }\n else {\n outMuon.loose = muon::isLooseMuon(inMuon);\n outMuon.medium = muon::isMediumMuon(inMuon);\n if (vertices.size() == 0)\n outMuon.tight = false;\n else\n outMuon.tight = muon::isTightMuon(inMuon, vertices.at(0));\n }\n\n outMuon.pfPt = inMuon.pfP4().pt();\n\n ptrList.push_back(inMuons.ptrAt(iMu));\n }\n \n auto originalIndices(outMuons.sort(panda::Particle::PtGreater));\n\n \/\/ export panda <-> reco mapping\n\n auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>());\n auto& pfMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"pf\"));\n auto& vtxMuMap(objectMap_->get<reco::Vertex, panda::Muon>());\n auto& genMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"gen\"));\n\n for (unsigned iP(0); iP != outMuons.size(); ++iP) {\n auto& outMuon(outMuons[iP]);\n unsigned idx(originalIndices[iP]);\n muMuMap.add(ptrList[idx], outMuon);\n\n auto sourcePtr(ptrList[idx]->sourceCandidatePtr(0));\n if (sourcePtr.isNonnull()) {\n pfMuMap.add(sourcePtr, outMuon);\n if (dynamic_cast<pat::PackedCandidate const*>(sourcePtr.get())) {\n auto vtxRef(static_cast<pat::PackedCandidate const&>(*sourcePtr).vertexRef());\n if (vtxRef.isNonnull())\n vtxMuMap.add(edm::refToPtr(vtxRef), outMuon);\n }\n }\n\n if (!isRealData_) {\n auto& inMuon(*ptrList[idx]);\n\n if (dynamic_cast<pat::Muon const*>(&inMuon)) {\n auto& patMuon(static_cast<pat::Muon const&>(inMuon));\n auto ref(patMuon.genParticleRef());\n if (ref.isNonnull())\n genMuMap.add(edm::refToPtr(ref), outMuon);\n }\n }\n }\n}\n\nvoid\nMuonsFiller::setRefs(ObjectMapStore const& _objectMaps)\n{\n auto& pfMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"pf\"));\n auto& vtxMuMap(objectMap_->get<reco::Vertex, panda::Muon>());\n\n auto& pfMap(_objectMaps.at(\"pfCandidates\").get<reco::Candidate, panda::PFCand>().fwdMap);\n auto& vtxMap(_objectMaps.at(\"vertices\").get<reco::Vertex, panda::RecoVertex>().fwdMap);\n\n for (auto& link : pfMuMap.bwdMap) { \/\/ panda -> edm\n auto& outMuon(*link.first);\n auto& pfPtr(link.second);\n\n \/\/ muon sourceCandidatePtr can point to the AOD pfCandidates in some cases\n auto pfItr(pfMap.find(pfPtr));\n if (pfItr == pfMap.end())\n continue;\n\n outMuon.matchedPF.setRef(pfItr->second);\n }\n\n for (auto& link : vtxMuMap.bwdMap) { \/\/ panda -> edm\n auto& outMuon(*link.first);\n auto& vtxPtr(link.second);\n\n outMuon.vertex.setRef(vtxMap.at(vtxPtr));\n }\n\n if (!isRealData_) {\n auto& genMuMap(objectMap_->get<reco::Candidate, panda::Muon>(\"gen\"));\n\n auto& genMap(_objectMaps.at(\"genParticles\").get<reco::Candidate, panda::GenParticle>().fwdMap);\n\n for (auto& link : genMuMap.bwdMap) {\n auto& genPtr(link.second);\n if (genMap.find(genPtr) == genMap.end())\n continue;\n\n auto& outMuon(*link.first);\n outMuon.matchedGen.setRef(genMap.at(genPtr));\n }\n }\n\n if (useTrigger_) {\n auto& objMap(_objectMaps.at(\"global\").get<pat::TriggerObjectStandAlone, VString>().fwdMap);\n\n std::vector<pat::TriggerObjectStandAlone const*> triggerObjects[panda::Muon::nTriggerObjects];\n\n \/\/ loop over the trigger filters we are interested in\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n \/\/ loop over all trigger objects (and their associated filter names)\n for (auto& objAndNames : objMap) { \/\/ (TO ptr, VString)\n VString const& names(*objAndNames.second);\n \/\/ loop over the associated filter names\n for (auto& name : names) {\n if (triggerObjects_[iT].find(name) != triggerObjects_[iT].end()) {\n triggerObjects[iT].push_back(&*objAndNames.first);\n break;\n }\n }\n }\n }\n\n auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>().fwdMap);\n\n for (auto& link : muMuMap) { \/\/ edm -> panda\n auto& inMuon(*link.first);\n auto& outMuon(*link.second);\n\n for (unsigned iT(0); iT != panda::Muon::nTriggerObjects; ++iT) {\n for (auto* obj : triggerObjects[iT]) {\n if (reco::deltaR(inMuon, *obj) < 0.3) {\n outMuon.triggerMatch[iT] = true;\n break;\n }\n }\n }\n }\n }\n}\n\nDEFINE_TREEFILLER(MuonsFiller);\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCarbonRenderWindowInteractor.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include \"vtkActor.h\"\n#include \"vtkCarbonRenderWindow.h\"\n#include \"vtkCarbonRenderWindowInteractor.h\"\n#include \"vtkCommand.h\"\n#include \"vtkInteractorStyle.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkCarbonRenderWindowInteractor, \"1.23\");\nvtkStandardNewMacro(vtkCarbonRenderWindowInteractor);\n\nvoid (*vtkCarbonRenderWindowInteractor::ClassExitMethod)(void *) \n = (void (*)(void *))NULL;\nvoid *vtkCarbonRenderWindowInteractor::ClassExitMethodArg = (void *)NULL;\nvoid (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)(void *) \n = (void (*)(void *))NULL;\n\n\/\/--------------------------------------------------------------------------\n\/\/ callback routine to handle all window-related events\n\/\/ The WindowPtr of the associated window is passed in userData\nstatic pascal OSStatus myWinEvtHndlr(EventHandlerCallRef,\n EventRef event, void* userData)\n{\n OSStatus result = eventNotHandledErr;\n HIPoint mouseLoc;\n vtkCarbonRenderWindow *ren;\n vtkCarbonRenderWindowInteractor *me;\n UInt32 eventClass = GetEventClass(event);\n UInt32 eventKind = GetEventKind (event);\n\n ren = (vtkCarbonRenderWindow *)userData;\n\n if (NULL == ren)\n {\n return 0;\n }\n\n me = (vtkCarbonRenderWindowInteractor *)ren->GetInteractor();\n if (NULL == me)\n {\n return 0;\n }\n\n UInt32 modifierKeys;\n GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,\n sizeof(modifierKeys), NULL, &modifierKeys);\n int controlDown = (modifierKeys & controlKey);\n int shiftDown = (modifierKeys & shiftKey);\n \n \/\/ Even though the option key is the one with a small 'alt' label on top\n \/\/ of it, VNC (as well as some Mac users) uses the command key as 'alt'.\n \/\/ Let's use both then. \n UInt32 altKey = cmdKey | optionKey;\n int altDown = (modifierKeys & altKey);\n \n switch (eventClass)\n {\n case kEventClassControl:\n {\n switch (eventKind)\n {\n case kEventControlDraw:\n {\n ren->Render();\n result = noErr;\n break;\n }\n case kEventControlBoundsChanged:\n {\n if(ren->GetWindowId())\n {\n HIRect viewBounds;\n HIViewGetBounds(ren->GetWindowId(), &viewBounds);\n me->UpdateSize((int)viewBounds.size.width, (int)viewBounds.size.height);\n if (me->GetEnabled())\n {\n me->InvokeEvent(vtkCommand::ConfigureEvent,NULL);\n }\n result = noErr;\n }\n break;\n }\n }\n break;\n }\n\n case kEventClassKeyboard:\n {\n SInt8 charCode;\n GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar,NULL,\n sizeof(charCode),NULL,&charCode);\n switch (GetEventKind(event))\n {\n case kEventRawKeyDown:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);\n me->InvokeEvent(vtkCommand::CharEvent, NULL);\n result = noErr;\n break;\n }\n case kEventRawKeyRepeat:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);\n me->InvokeEvent(vtkCommand::CharEvent, NULL);\n result = noErr;\n break;\n }\n case kEventRawKeyUp:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);\n result = noErr;\n break;\n }\n }\n break;\n }\n\n case kEventClassMouse:\n {\n \/\/ see if the event is for this view\n HIViewRef view_for_mouse;\n HIViewRef root_window = HIViewGetRoot(ren->GetRootWindow());\n HIViewGetViewForMouseEvent(root_window, event, &view_for_mouse);\n if(view_for_mouse != ren->GetWindowId())\n return eventNotHandledErr;\n\n GetEventParameter(event, kEventParamMouseLocation, typeHIPoint,\n NULL, sizeof(HIPoint), NULL, &mouseLoc);\n \n HIViewConvertPoint(&mouseLoc, root_window, ren->GetWindowId());\n\n GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,\n sizeof(modifierKeys), NULL, &modifierKeys);\n UInt16 buttonNumber;\n GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL,\n sizeof(buttonNumber), NULL, &buttonNumber);\n \n me->SetEventInformationFlipY((int)mouseLoc.x, (int)mouseLoc.y,\n (modifierKeys & controlKey),\n (modifierKeys & shiftKey));\n me->SetAltKey(modifierKeys & altKey);\n switch (GetEventKind(event))\n {\n case kEventMouseDown:\n {\n switch (buttonNumber)\n {\n case 1:\n {\n me->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);\n break;\n }\n case 2:\n {\n me->InvokeEvent(vtkCommand::RightButtonPressEvent,NULL);\n break;\n }\n case 3:\n {\n me->InvokeEvent(vtkCommand::MiddleButtonPressEvent,NULL);\n break;\n }\n }\n result = noErr;\n break;\n }\n case kEventMouseUp:\n {\n switch (buttonNumber)\n {\n case 1:\n {\n me->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);\n break;\n }\n case 2:\n {\n me->InvokeEvent(vtkCommand::RightButtonReleaseEvent,NULL);\n break;\n }\n case 3:\n {\n me->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent,NULL);\n break;\n }\n }\n result = noErr;\n break;\n }\n case kEventMouseMoved:\n {\n me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n result = noErr;\n break;\n }\n case kEventMouseDragged:\n {\n me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n result = noErr;\n break;\n }\n case kEventMouseWheelMoved:\n {\n EventMouseWheelAxis axis;\n SInt32 delta;\n GetEventParameter( event, kEventParamMouseWheelAxis, \n typeMouseWheelAxis, NULL, sizeof(axis), NULL, &axis );\n GetEventParameter( event, kEventParamMouseWheelDelta, \n typeLongInteger, NULL, sizeof(delta), NULL, &delta );\n if ( axis == kEventMouseWheelAxisY )\n {\n if( delta > 0)\n {\n me->InvokeEvent(vtkCommand::MouseWheelForwardEvent, NULL);\n }\n else\n {\n me->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, NULL);\n }\n }\n result = noErr;\n break;\n }\n default:\n {\n }\n }\n }\n }\n \n return result;\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Construct object so that light follows camera motion.\nvtkCarbonRenderWindowInteractor::vtkCarbonRenderWindowInteractor()\n{\n this->InstallMessageProc = 1;\n this->ViewProcUPP = NULL;\n this->WindowProcUPP = NULL;\n}\n\n\/\/--------------------------------------------------------------------------\nvtkCarbonRenderWindowInteractor::~vtkCarbonRenderWindowInteractor()\n{\n this->Enabled = 0;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Start()\n{\n \/\/ Let the compositing handle the event loop if it wants to.\n if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)\n {\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n return;\n }\n\n \/\/ No need to do anything if this is a 'mapped' interactor\n if (!this->Enabled || !this->InstallMessageProc)\n {\n return;\n }\n RunApplicationEventLoop();\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Fill in some local variables (most of this routine could probably go)\nvoid vtkCarbonRenderWindowInteractor::Initialize()\n{\n vtkCarbonRenderWindow *ren;\n int *size;\n\n \/\/ make sure we have a RenderWindow and camera\n if ( ! this->RenderWindow)\n {\n vtkErrorMacro(<<\"No renderer defined!\");\n return;\n }\n if (this->Initialized)\n {\n return;\n }\n this->Initialized = 1;\n \/\/ get the info we need from the RenderingWindow\n ren = (vtkCarbonRenderWindow *)(this->RenderWindow);\n\n ren->Start();\n size = ren->GetSize();\n ren->GetPosition();\n this->Enable();\n this->Size[0] = size[0];\n this->Size[1] = size[1];\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Enable()\n{\n if (this->Enabled)\n {\n return;\n }\n\n \n if (this->InstallMessageProc)\n {\n \/\/ set up the event handling\n \/\/ specify which events we want to hear about\n OSStatus err = noErr;\n EventTypeSpec view_event_list[] = {{ kEventClassControl, kEventControlDraw },\n { kEventClassControl, kEventControlBoundsChanged }};\n \n EventTypeSpec window_event_list[] ={{ kEventClassMouse, kEventMouseDown },\n { kEventClassMouse, kEventMouseUp },\n { kEventClassMouse, kEventMouseMoved },\n { kEventClassMouse, kEventMouseDragged },\n { kEventClassMouse, kEventMouseWheelMoved },\n { kEventClassKeyboard, kEventRawKeyDown },\n { kEventClassKeyboard, kEventRawKeyRepeat },\n { kEventClassKeyboard, kEventRawKeyUp }};\n \n this->WindowProcUPP = NewEventHandlerUPP(myWinEvtHndlr);\n this->ViewProcUPP = NewEventHandlerUPP(myWinEvtHndlr);\n if(!this->WindowProcUPP || !ViewProcUPP)\n err = memFullErr;\n\n if(!err)\n {\n vtkCarbonRenderWindow* ren = static_cast<vtkCarbonRenderWindow*>(this->RenderWindow);\n err = InstallControlEventHandler(ren->GetWindowId(), this->ViewProcUPP,\n GetEventTypeCount(view_event_list), view_event_list, ren, NULL);\n err = InstallWindowEventHandler(ren->GetRootWindow(), this->WindowProcUPP,\n GetEventTypeCount(window_event_list), window_event_list, ren, NULL);\n }\n }\n this->Enabled = 1;\n this->Modified();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Disable()\n{\n if (!this->Enabled)\n {\n return;\n }\n this->Enabled = 0;\n this->Modified();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::TerminateApp(void)\n{\n QuitApplicationEventLoop();\n}\n\n\/\/--------------------------------------------------------------------------\npascal void TimerAction(EventLoopTimerRef platformTimerId, void* userData)\n{\n if (NULL != userData)\n {\n vtkCarbonRenderWindowInteractor *rwi =\n static_cast<vtkCarbonRenderWindowInteractor *>(userData);\n int vtkTimerId = rwi->GetVTKTimerId((int) platformTimerId);\n rwi->InvokeEvent(vtkCommand::TimerEvent, (void *) &vtkTimerId);\n }\n}\n\n\/\/--------------------------------------------------------------------------\nint vtkCarbonRenderWindowInteractor::InternalCreateTimer(\n int vtkNotUsed(timerId), int timerType, unsigned long duration)\n{\n EventLoopTimerRef platformTimerId;\n EventLoopRef mainLoop = GetMainEventLoop();\n EventLoopTimerUPP timerUPP = NewEventLoopTimerUPP(TimerAction);\n EventTimerInterval interval = 0;\n\n \/\/ Carbon's InstallEventLoopTimer can create either one-shot or repeating\n \/\/ timers... interval == 0 indicates a one-shot timer.\n\n if (RepeatingTimer == timerType)\n {\n interval = duration*kEventDurationMillisecond;\n }\n\n InstallEventLoopTimer(mainLoop,\n duration*kEventDurationMillisecond,\n interval,\n timerUPP,\n this,\n &platformTimerId);\n\n return (int) platformTimerId;\n}\n\n\/\/--------------------------------------------------------------------------\nint vtkCarbonRenderWindowInteractor::InternalDestroyTimer(int platformTimerId)\n{\n RemoveEventLoopTimer((EventLoopTimerRef) platformTimerId);\n return 1;\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Specify the default function to be called when an interactor needs to exit.\n\/\/ This callback is overridden by an instance ExitMethod that is defined.\nvoid vtkCarbonRenderWindowInteractor::SetClassExitMethod(void (*f)(void *),\n void *arg)\n{\n if (f != vtkCarbonRenderWindowInteractor::ClassExitMethod\n || arg != vtkCarbonRenderWindowInteractor::ClassExitMethodArg)\n {\n \/\/ delete the current arg if there is a delete method\n if ((vtkCarbonRenderWindowInteractor::ClassExitMethodArg) &&\n (vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete))\n {\n (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)\n (vtkCarbonRenderWindowInteractor::ClassExitMethodArg);\n }\n vtkCarbonRenderWindowInteractor::ClassExitMethod = f;\n vtkCarbonRenderWindowInteractor::ClassExitMethodArg = arg;\n \n \/\/ no call to this->Modified() since this is a class member function\n }\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid\nvtkCarbonRenderWindowInteractor::SetClassExitMethodArgDelete(void (*f)(void *))\n{\n if (f != vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)\n {\n vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete = f;\n\n \/\/ no call to this->Modified() since this is a class member function\n }\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkRenderWindowInteractor::PrintSelf(os,indent);\n os << indent << \"InstallMessageProc: \" << this->InstallMessageProc << endl;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::ExitCallback()\n{\n if (this->HasObserver(vtkCommand::ExitEvent)) \n {\n this->InvokeEvent(vtkCommand::ExitEvent,NULL);\n }\n else if (this->ClassExitMethod)\n {\n (*this->ClassExitMethod)(this->ClassExitMethodArg);\n }\n this->TerminateApp();\n}\n<commit_msg><commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCarbonRenderWindowInteractor.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include \"vtkActor.h\"\n#include \"vtkCarbonRenderWindow.h\"\n#include \"vtkCarbonRenderWindowInteractor.h\"\n#include \"vtkCommand.h\"\n#include \"vtkInteractorStyle.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkCarbonRenderWindowInteractor, \"1.24\");\nvtkStandardNewMacro(vtkCarbonRenderWindowInteractor);\n\nvoid (*vtkCarbonRenderWindowInteractor::ClassExitMethod)(void *) \n = (void (*)(void *))NULL;\nvoid *vtkCarbonRenderWindowInteractor::ClassExitMethodArg = (void *)NULL;\nvoid (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)(void *) \n = (void (*)(void *))NULL;\n\n\/\/--------------------------------------------------------------------------\n\/\/ callback routine to handle all window-related events\n\/\/ The WindowPtr of the associated window is passed in userData\nstatic pascal OSStatus myWinEvtHndlr(EventHandlerCallRef,\n EventRef event, void* userData)\n{\n OSStatus result = eventNotHandledErr;\n HIPoint mouseLoc;\n vtkCarbonRenderWindow *ren;\n vtkCarbonRenderWindowInteractor *me;\n UInt32 eventClass = GetEventClass(event);\n UInt32 eventKind = GetEventKind (event);\n\n ren = (vtkCarbonRenderWindow *)userData;\n\n if (NULL == ren)\n {\n return 0;\n }\n\n me = (vtkCarbonRenderWindowInteractor *)ren->GetInteractor();\n if (NULL == me)\n {\n return 0;\n }\n\n UInt32 modifierKeys;\n GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,\n sizeof(modifierKeys), NULL, &modifierKeys);\n int controlDown = (modifierKeys & controlKey);\n int shiftDown = (modifierKeys & shiftKey);\n \n \/\/ Even though the option key is the one with a small 'alt' label on top\n \/\/ of it, VNC (as well as some Mac users) uses the command key as 'alt'.\n \/\/ Let's use both then. \n UInt32 altKey = cmdKey | optionKey;\n int altDown = (modifierKeys & altKey);\n \n switch (eventClass)\n {\n case kEventClassControl:\n {\n switch (eventKind)\n {\n case kEventControlDraw:\n {\n ren->Render();\n result = noErr;\n break;\n }\n case kEventControlBoundsChanged:\n {\n if(ren->GetWindowId())\n {\n HIRect viewBounds;\n HIViewGetBounds(ren->GetWindowId(), &viewBounds);\n me->UpdateSize((int)viewBounds.size.width, (int)viewBounds.size.height);\n if (me->GetEnabled())\n {\n me->InvokeEvent(vtkCommand::ConfigureEvent,NULL);\n }\n result = noErr;\n }\n break;\n }\n }\n break;\n }\n\n case kEventClassKeyboard:\n {\n SInt8 charCode;\n GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar,NULL,\n sizeof(charCode),NULL,&charCode);\n switch (GetEventKind(event))\n {\n case kEventRawKeyDown:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);\n me->InvokeEvent(vtkCommand::CharEvent, NULL);\n result = noErr;\n break;\n }\n case kEventRawKeyRepeat:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);\n me->InvokeEvent(vtkCommand::CharEvent, NULL);\n result = noErr;\n break;\n }\n case kEventRawKeyUp:\n {\n me->SetKeyEventInformation(controlDown, shiftDown,\n (int)charCode,1,(char*)&charCode);\n me->SetAltKey(altDown);\n me->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);\n result = noErr;\n break;\n }\n }\n break;\n }\n\n case kEventClassMouse:\n {\n \/\/ see if the event is for this view\n HIViewRef view_for_mouse;\n HIViewRef root_window = HIViewGetRoot(ren->GetRootWindow());\n HIViewGetViewForMouseEvent(root_window, event, &view_for_mouse);\n if(view_for_mouse != ren->GetWindowId())\n return eventNotHandledErr;\n\n GetEventParameter(event, kEventParamWindowMouseLocation, typeHIPoint,\n NULL, sizeof(HIPoint), NULL, &mouseLoc);\n \n HIViewConvertPoint(&mouseLoc, root_window, ren->GetWindowId());\n\n GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,\n sizeof(modifierKeys), NULL, &modifierKeys);\n UInt16 buttonNumber;\n GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL,\n sizeof(buttonNumber), NULL, &buttonNumber);\n \n me->SetEventInformationFlipY((int)mouseLoc.x, (int)mouseLoc.y,\n (modifierKeys & controlKey),\n (modifierKeys & shiftKey));\n me->SetAltKey(modifierKeys & altKey);\n switch (GetEventKind(event))\n {\n case kEventMouseDown:\n {\n switch (buttonNumber)\n {\n case 1:\n {\n me->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);\n break;\n }\n case 2:\n {\n me->InvokeEvent(vtkCommand::RightButtonPressEvent,NULL);\n break;\n }\n case 3:\n {\n me->InvokeEvent(vtkCommand::MiddleButtonPressEvent,NULL);\n break;\n }\n }\n result = noErr;\n break;\n }\n case kEventMouseUp:\n {\n switch (buttonNumber)\n {\n case 1:\n {\n me->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);\n break;\n }\n case 2:\n {\n me->InvokeEvent(vtkCommand::RightButtonReleaseEvent,NULL);\n break;\n }\n case 3:\n {\n me->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent,NULL);\n break;\n }\n }\n result = noErr;\n break;\n }\n case kEventMouseMoved:\n {\n me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n result = noErr;\n break;\n }\n case kEventMouseDragged:\n {\n me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);\n result = noErr;\n break;\n }\n case kEventMouseWheelMoved:\n {\n EventMouseWheelAxis axis;\n SInt32 delta;\n GetEventParameter( event, kEventParamMouseWheelAxis, \n typeMouseWheelAxis, NULL, sizeof(axis), NULL, &axis );\n GetEventParameter( event, kEventParamMouseWheelDelta, \n typeLongInteger, NULL, sizeof(delta), NULL, &delta );\n if ( axis == kEventMouseWheelAxisY )\n {\n if( delta > 0)\n {\n me->InvokeEvent(vtkCommand::MouseWheelForwardEvent, NULL);\n }\n else\n {\n me->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, NULL);\n }\n }\n result = noErr;\n break;\n }\n default:\n {\n }\n }\n }\n }\n \n return result;\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Construct object so that light follows camera motion.\nvtkCarbonRenderWindowInteractor::vtkCarbonRenderWindowInteractor()\n{\n this->InstallMessageProc = 1;\n this->ViewProcUPP = NULL;\n this->WindowProcUPP = NULL;\n}\n\n\/\/--------------------------------------------------------------------------\nvtkCarbonRenderWindowInteractor::~vtkCarbonRenderWindowInteractor()\n{\n this->Enabled = 0;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Start()\n{\n \/\/ Let the compositing handle the event loop if it wants to.\n if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)\n {\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n return;\n }\n\n \/\/ No need to do anything if this is a 'mapped' interactor\n if (!this->Enabled || !this->InstallMessageProc)\n {\n return;\n }\n RunApplicationEventLoop();\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Fill in some local variables (most of this routine could probably go)\nvoid vtkCarbonRenderWindowInteractor::Initialize()\n{\n vtkCarbonRenderWindow *ren;\n int *size;\n\n \/\/ make sure we have a RenderWindow and camera\n if ( ! this->RenderWindow)\n {\n vtkErrorMacro(<<\"No renderer defined!\");\n return;\n }\n if (this->Initialized)\n {\n return;\n }\n this->Initialized = 1;\n \/\/ get the info we need from the RenderingWindow\n ren = (vtkCarbonRenderWindow *)(this->RenderWindow);\n\n ren->Start();\n size = ren->GetSize();\n ren->GetPosition();\n this->Enable();\n this->Size[0] = size[0];\n this->Size[1] = size[1];\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Enable()\n{\n if (this->Enabled)\n {\n return;\n }\n\n \n if (this->InstallMessageProc)\n {\n \/\/ set up the event handling\n \/\/ specify which events we want to hear about\n OSStatus err = noErr;\n EventTypeSpec view_event_list[] = {{ kEventClassControl, kEventControlDraw },\n { kEventClassControl, kEventControlBoundsChanged }};\n \n EventTypeSpec window_event_list[] ={{ kEventClassMouse, kEventMouseDown },\n { kEventClassMouse, kEventMouseUp },\n { kEventClassMouse, kEventMouseMoved },\n { kEventClassMouse, kEventMouseDragged },\n { kEventClassMouse, kEventMouseWheelMoved },\n { kEventClassKeyboard, kEventRawKeyDown },\n { kEventClassKeyboard, kEventRawKeyRepeat },\n { kEventClassKeyboard, kEventRawKeyUp }};\n \n this->WindowProcUPP = NewEventHandlerUPP(myWinEvtHndlr);\n this->ViewProcUPP = NewEventHandlerUPP(myWinEvtHndlr);\n if(!this->WindowProcUPP || !ViewProcUPP)\n err = memFullErr;\n\n if(!err)\n {\n vtkCarbonRenderWindow* ren = static_cast<vtkCarbonRenderWindow*>(this->RenderWindow);\n err = InstallControlEventHandler(ren->GetWindowId(), this->ViewProcUPP,\n GetEventTypeCount(view_event_list), view_event_list, ren, NULL);\n err = InstallWindowEventHandler(ren->GetRootWindow(), this->WindowProcUPP,\n GetEventTypeCount(window_event_list), window_event_list, ren, NULL);\n }\n }\n this->Enabled = 1;\n this->Modified();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::Disable()\n{\n if (!this->Enabled)\n {\n return;\n }\n this->Enabled = 0;\n this->Modified();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::TerminateApp(void)\n{\n QuitApplicationEventLoop();\n}\n\n\/\/--------------------------------------------------------------------------\npascal void TimerAction(EventLoopTimerRef platformTimerId, void* userData)\n{\n if (NULL != userData)\n {\n vtkCarbonRenderWindowInteractor *rwi =\n static_cast<vtkCarbonRenderWindowInteractor *>(userData);\n int vtkTimerId = rwi->GetVTKTimerId((int) platformTimerId);\n rwi->InvokeEvent(vtkCommand::TimerEvent, (void *) &vtkTimerId);\n }\n}\n\n\/\/--------------------------------------------------------------------------\nint vtkCarbonRenderWindowInteractor::InternalCreateTimer(\n int vtkNotUsed(timerId), int timerType, unsigned long duration)\n{\n EventLoopTimerRef platformTimerId;\n EventLoopRef mainLoop = GetMainEventLoop();\n EventLoopTimerUPP timerUPP = NewEventLoopTimerUPP(TimerAction);\n EventTimerInterval interval = 0;\n\n \/\/ Carbon's InstallEventLoopTimer can create either one-shot or repeating\n \/\/ timers... interval == 0 indicates a one-shot timer.\n\n if (RepeatingTimer == timerType)\n {\n interval = duration*kEventDurationMillisecond;\n }\n\n InstallEventLoopTimer(mainLoop,\n duration*kEventDurationMillisecond,\n interval,\n timerUPP,\n this,\n &platformTimerId);\n\n return (int) platformTimerId;\n}\n\n\/\/--------------------------------------------------------------------------\nint vtkCarbonRenderWindowInteractor::InternalDestroyTimer(int platformTimerId)\n{\n RemoveEventLoopTimer((EventLoopTimerRef) platformTimerId);\n return 1;\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Specify the default function to be called when an interactor needs to exit.\n\/\/ This callback is overridden by an instance ExitMethod that is defined.\nvoid vtkCarbonRenderWindowInteractor::SetClassExitMethod(void (*f)(void *),\n void *arg)\n{\n if (f != vtkCarbonRenderWindowInteractor::ClassExitMethod\n || arg != vtkCarbonRenderWindowInteractor::ClassExitMethodArg)\n {\n \/\/ delete the current arg if there is a delete method\n if ((vtkCarbonRenderWindowInteractor::ClassExitMethodArg) &&\n (vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete))\n {\n (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)\n (vtkCarbonRenderWindowInteractor::ClassExitMethodArg);\n }\n vtkCarbonRenderWindowInteractor::ClassExitMethod = f;\n vtkCarbonRenderWindowInteractor::ClassExitMethodArg = arg;\n \n \/\/ no call to this->Modified() since this is a class member function\n }\n}\n\n\/\/--------------------------------------------------------------------------\n\/\/ Set the arg delete method. This is used to free user memory.\nvoid\nvtkCarbonRenderWindowInteractor::SetClassExitMethodArgDelete(void (*f)(void *))\n{\n if (f != vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)\n {\n vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete = f;\n\n \/\/ no call to this->Modified() since this is a class member function\n }\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkRenderWindowInteractor::PrintSelf(os,indent);\n os << indent << \"InstallMessageProc: \" << this->InstallMessageProc << endl;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid vtkCarbonRenderWindowInteractor::ExitCallback()\n{\n if (this->HasObserver(vtkCommand::ExitEvent)) \n {\n this->InvokeEvent(vtkCommand::ExitEvent,NULL);\n }\n else if (this->ClassExitMethod)\n {\n (*this->ClassExitMethod)(this->ClassExitMethodArg);\n }\n this->TerminateApp();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>use C++11 iteration<commit_after><|endoftext|>"} {"text":"<commit_before>\n#include \"rutil\/Log.hxx\"\n#include \"rutil\/Logger.hxx\"\n#include \"rutil\/Subsystem.hxx\"\n#include \"resip\/dum\/ClientAuthManager.hxx\"\n#include \"resip\/dum\/ClientRegistration.hxx\"\n#include \"resip\/dum\/DialogUsageManager.hxx\"\n#include \"resip\/dum\/InviteSessionHandler.hxx\"\n#include \"resip\/dum\/MasterProfile.hxx\"\n#include \"resip\/dum\/Profile.hxx\"\n#include \"resip\/dum\/UserProfile.hxx\"\n#include \"resip\/dum\/RegistrationHandler.hxx\"\n#include \"resip\/dum\/ClientPagerMessage.hxx\"\n#include \"resip\/dum\/ServerPagerMessage.hxx\"\n\n#include \"resip\/dum\/DialogUsageManager.hxx\"\n#include \"resip\/dum\/AppDialogSet.hxx\"\n#include \"resip\/dum\/AppDialog.hxx\"\n#include \"resip\/dum\/RegistrationHandler.hxx\"\n#include \"resip\/dum\/PagerMessageHandler.hxx\"\n#include \"resip\/stack\/PlainContents.hxx\"\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\n#include \"org_resiprocate_android_basicmessage_MessageSender.h\"\n\nusing namespace std;\nusing namespace resip;\n\n#define RESIPROCATE_SUBSYSTEM Subsystem::TEST\n\nclass ClientMessageHandler : public ClientPagerMessageHandler {\npublic:\n ClientMessageHandler()\n : finished(false),\n successful(false)\n {\n };\n\n virtual void onSuccess(ClientPagerMessageHandle, const SipMessage& status)\n {\n InfoLog(<<\"ClientMessageHandler::onSuccess\\n\");\n successful = true;\n finished = true;\n }\n\n virtual void onFailure(ClientPagerMessageHandle, const SipMessage& status, std::auto_ptr<Contents> contents)\n {\n ErrLog(<<\"ClientMessageHandler::onFailure\\n\");\n successful = false;\n finished = true;\n }\n\n bool isFinished() { return finished; };\n bool isSuccessful() { return successful; };\n\nprivate:\n bool finished;\n bool successful;\n};\n\nint send_message(int argc, const char *argv[], const char* body)\n{\n Log::initialize(Log::Cout, Log::Info, argv[0]);\n\n if( (argc < 6) || (argc > 7) ) {\n ErrLog(<< \"usage: \" << argv[0] << \" sip:from user passwd realm sip:to [port]\\n\");\n return 1;\n }\n\n string from(argv[1]);\n string user(argv[2]);\n string passwd(argv[3]);\n string realm(argv[4]);\n string to(argv[5]);\n int port = 5060;\n if(argc == 7)\n {\n string temp(argv[6]);\n istringstream src(temp);\n src >> port;\n }\n\n InfoLog(<< \"log: from: \" << from << \", to: \" << to << \", port: \" << port << \"\\n\");\n InfoLog(<< \"user: \" << user << \", passwd: \" << passwd << \", realm: \" << realm << \"\\n\");\n\n SharedPtr<MasterProfile> profile(new MasterProfile);\n auto_ptr<ClientAuthManager> clientAuth(new ClientAuthManager());\n\n SipStack clientStack;\n DialogUsageManager clientDum(clientStack);\n clientDum.addTransport(UDP, port);\n clientDum.setMasterProfile(profile);\n\n clientDum.setClientAuthManager(clientAuth);\n clientDum.getMasterProfile()->setDefaultRegistrationTime(70);\n clientDum.getMasterProfile()->addSupportedMethod(MESSAGE);\n clientDum.getMasterProfile()->addSupportedMimeType(MESSAGE, Mime(\"text\", \"plain\"));\n ClientMessageHandler *cmh = new ClientMessageHandler();\n clientDum.setClientPagerMessageHandler(cmh);\n\n NameAddr naFrom(from.c_str());\n profile->setDefaultFrom(naFrom);\n profile->setDigestCredential(realm.c_str(), user.c_str(), passwd.c_str());\n\n InfoLog(<< \"Sending MESSAGE\\n\");\n NameAddr naTo(to.c_str());\n ClientPagerMessageHandle cpmh = clientDum.makePagerMessage(naTo);\n\n Data messageBody(body);\n auto_ptr<Contents> content(new PlainContents(messageBody));\n cpmh.get()->page(content);\n\n \/\/ Event loop - stack will invoke callbacks in our app\n while(!cmh->isFinished())\n {\n clientStack.process(100);\n while(clientDum.process());\n }\n\n if(!cmh->isSuccessful())\n {\n ErrLog(<< \"Message delivery failed, aborting\");\n return 1;\n }\n\n return 0;\n}\n\n\/\/ Note: this is very crude, it will create a new SIP stack and DUM each\n\/\/ time a message needs to be sent\n\n\/\/ A proper implementation must keep the SIP stack active as long as the\n\/\/ app is running.\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void JNICALL Java_org_resiprocate_android_basicmessage_MessageSender_sendMessage\n (JNIEnv *env, jobject jthis, jstring recipient, jstring body)\n{\n const char *_recipient = env->GetStringUTFChars(recipient, 0);\n const char *_body = env->GetStringUTFChars(body, 0);\n \n \/\/ These should be configured through Android preferences:\n \n const char *argv[8];\n argv[0] = \"BasicMessage (JNI)\";\n argv[1] = \"sip:anonymous@example.org\";\n argv[2] = \"anonymous\";\n argv[3] = \"password\";\n argv[4] = \"realm\";\n argv[5] = _recipient;\n \n \/\/ we don't use 5060 in case it clashes with some other app on the phone\n argv[6] = \"5067\";\n \n try {\n \tint rc = send_message(7, argv, _body);\n } catch (exception& e)\n {\n cout << e.what() << endl;\n }\n catch(...)\n {\n cout << \"some exception!\" << endl;\n }\n \n env->ReleaseStringUTFChars(recipient, _recipient);\n env->ReleaseStringUTFChars(body, _body);\n}\n#ifdef __cplusplus\n}\n#endif\n<commit_msg>Use the new AndroidLogger mechanism for logcat output<commit_after>\n#include \"rutil\/AndroidLogger.hxx\"\n#include \"rutil\/Log.hxx\"\n#include \"rutil\/Logger.hxx\"\n#include \"rutil\/Subsystem.hxx\"\n#include \"resip\/dum\/ClientAuthManager.hxx\"\n#include \"resip\/dum\/ClientRegistration.hxx\"\n#include \"resip\/dum\/DialogUsageManager.hxx\"\n#include \"resip\/dum\/InviteSessionHandler.hxx\"\n#include \"resip\/dum\/MasterProfile.hxx\"\n#include \"resip\/dum\/Profile.hxx\"\n#include \"resip\/dum\/UserProfile.hxx\"\n#include \"resip\/dum\/RegistrationHandler.hxx\"\n#include \"resip\/dum\/ClientPagerMessage.hxx\"\n#include \"resip\/dum\/ServerPagerMessage.hxx\"\n\n#include \"resip\/dum\/DialogUsageManager.hxx\"\n#include \"resip\/dum\/AppDialogSet.hxx\"\n#include \"resip\/dum\/AppDialog.hxx\"\n#include \"resip\/dum\/RegistrationHandler.hxx\"\n#include \"resip\/dum\/PagerMessageHandler.hxx\"\n#include \"resip\/stack\/PlainContents.hxx\"\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\n#include \"org_resiprocate_android_basicmessage_MessageSender.h\"\n\nusing namespace std;\nusing namespace resip;\n\n#define RESIPROCATE_SUBSYSTEM Subsystem::TEST\n\nclass ClientMessageHandler : public ClientPagerMessageHandler {\npublic:\n ClientMessageHandler()\n : finished(false),\n successful(false)\n {\n };\n\n virtual void onSuccess(ClientPagerMessageHandle, const SipMessage& status)\n {\n InfoLog(<<\"ClientMessageHandler::onSuccess\\n\");\n successful = true;\n finished = true;\n }\n\n virtual void onFailure(ClientPagerMessageHandle, const SipMessage& status, std::auto_ptr<Contents> contents)\n {\n ErrLog(<<\"ClientMessageHandler::onFailure\\n\");\n successful = false;\n finished = true;\n }\n\n bool isFinished() { return finished; };\n bool isSuccessful() { return successful; };\n\nprivate:\n bool finished;\n bool successful;\n};\n\nint send_message(int argc, const char *argv[], const char* body)\n{\n AndroidLogger alog;\n Log::initialize(Log::Cout, Log::Stack, argv[0], alog);\n\n if( (argc < 6) || (argc > 7) ) {\n ErrLog(<< \"usage: \" << argv[0] << \" sip:from user passwd realm sip:to [port]\\n\");\n return 1;\n }\n\n string from(argv[1]);\n string user(argv[2]);\n string passwd(argv[3]);\n string realm(argv[4]);\n string to(argv[5]);\n int port = 5060;\n if(argc == 7)\n {\n string temp(argv[6]);\n istringstream src(temp);\n src >> port;\n }\n\n InfoLog(<< \"log: from: \" << from << \", to: \" << to << \", port: \" << port << \"\\n\");\n InfoLog(<< \"user: \" << user << \", passwd: \" << passwd << \", realm: \" << realm << \"\\n\");\n\n SharedPtr<MasterProfile> profile(new MasterProfile);\n auto_ptr<ClientAuthManager> clientAuth(new ClientAuthManager());\n\n SipStack clientStack;\n DialogUsageManager clientDum(clientStack);\n clientDum.addTransport(UDP, port);\n clientDum.setMasterProfile(profile);\n\n clientDum.setClientAuthManager(clientAuth);\n clientDum.getMasterProfile()->setDefaultRegistrationTime(70);\n clientDum.getMasterProfile()->addSupportedMethod(MESSAGE);\n clientDum.getMasterProfile()->addSupportedMimeType(MESSAGE, Mime(\"text\", \"plain\"));\n ClientMessageHandler *cmh = new ClientMessageHandler();\n clientDum.setClientPagerMessageHandler(cmh);\n\n NameAddr naFrom(from.c_str());\n profile->setDefaultFrom(naFrom);\n profile->setDigestCredential(realm.c_str(), user.c_str(), passwd.c_str());\n\n InfoLog(<< \"Sending MESSAGE\\n\");\n NameAddr naTo(to.c_str());\n ClientPagerMessageHandle cpmh = clientDum.makePagerMessage(naTo);\n\n Data messageBody(body);\n auto_ptr<Contents> content(new PlainContents(messageBody));\n cpmh.get()->page(content);\n\n \/\/ Event loop - stack will invoke callbacks in our app\n while(!cmh->isFinished())\n {\n clientStack.process(100);\n while(clientDum.process());\n }\n\n if(!cmh->isSuccessful())\n {\n ErrLog(<< \"Message delivery failed, aborting\");\n return 1;\n }\n\n return 0;\n}\n\n\/\/ Note: this is very crude, it will create a new SIP stack and DUM each\n\/\/ time a message needs to be sent\n\n\/\/ A proper implementation must keep the SIP stack active as long as the\n\/\/ app is running.\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void JNICALL Java_org_resiprocate_android_basicmessage_MessageSender_sendMessage\n (JNIEnv *env, jobject jthis, jstring recipient, jstring body)\n{\n const char *_recipient = env->GetStringUTFChars(recipient, 0);\n const char *_body = env->GetStringUTFChars(body, 0);\n \n \/\/ These should be configured through Android preferences:\n \n const char *argv[8];\n argv[0] = \"BasicMessage (JNI)\";\n argv[1] = \"sip:anonymous@example.org\";\n argv[2] = \"anonymous\";\n argv[3] = \"password\";\n argv[4] = \"realm\";\n argv[5] = _recipient;\n \n \/\/ we don't use 5060 in case it clashes with some other app on the phone\n argv[6] = \"5067\";\n \n try {\n \tint rc = send_message(7, argv, _body);\n } catch (exception& e)\n {\n cout << e.what() << endl;\n }\n catch(...)\n {\n cout << \"some exception!\" << endl;\n }\n \n env->ReleaseStringUTFChars(recipient, _recipient);\n env->ReleaseStringUTFChars(body, _body);\n}\n#ifdef __cplusplus\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2005-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n * Copyright 2008,2009 Jens-Michael Hoffmann <jensmh@gmx.de>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n#include \"TileLoader.h\"\n\n#include \"global.h\"\n#include \"GeoSceneLayer.h\"\n#include \"GeoSceneTexture.h\"\n#include \"HttpDownloadManager.h\"\n#include \"DatasetProvider.h\"\n#include \"TextureTile.h\"\n#include \"MarbleDirs.h\"\n#include \"MarbleModel.h\"\n#include \"TileLoaderHelper.h\"\n\n#include <QtCore\/QCache>\n#include <QtCore\/QDebug>\n#include <QtCore\/QHash>\n#include <QtGui\/QImage>\n\n\n#ifdef Q_CC_MSVC\n# ifndef KDEWIN_MATH_H\n long double log(int i) { return log((long double)i); }\n# endif\n#endif\n\nnamespace Marble\n{\n\nclass TileLoaderPrivate\n{\n public:\n TileLoaderPrivate()\n : m_datasetProvider( 0 ),\n m_downloadManager( 0 ),\n m_layer( 0 ),\n m_tileWidth( 0 ),\n m_tileHeight( 0 )\n {\n m_tileCache.setMaxCost( 20000 * 1024 ); \/\/ Cache size measured in bytes\n }\n\n DatasetProvider *m_datasetProvider;\n HttpDownloadManager *m_downloadManager;\n GeoSceneLayer *m_layer;\n QHash <TileId, TextureTile*> m_tilesOnDisplay;\n int m_tileWidth;\n int m_tileHeight;\n QCache <TileId, TextureTile> m_tileCache;\n};\n\n\n\nTileLoader::TileLoader( HttpDownloadManager *downloadManager, MarbleModel* parent)\n : d( new TileLoaderPrivate() ),\n m_parent(parent)\n{\n setDownloadManager( downloadManager );\n}\n\nTileLoader::~TileLoader()\n{\n flush();\n d->m_tileCache.clear();\n if ( d->m_downloadManager != 0 )\n d->m_downloadManager->disconnect( this );\n\n delete d;\n}\n\nvoid TileLoader::setDownloadManager( HttpDownloadManager *downloadManager )\n{\n if ( d->m_downloadManager != 0 ) {\n d->m_downloadManager->disconnect( this );\n d->m_downloadManager = 0;\n }\n\n d->m_downloadManager = downloadManager;\n if ( d->m_downloadManager != 0 ) {\n connect( d->m_downloadManager, SIGNAL( downloadComplete( QString, QString ) ),\n this, SLOT( reloadTile( QString, QString ) ) );\n }\n}\n\nvoid TileLoader::setLayer( GeoSceneLayer * layer )\n{\n \/\/ Initialize map theme.\n flush();\n d->m_tileCache.clear();\n\n if ( !layer ) {\n qDebug() << \"No layer specified! (GeoSceneLayer * layer = 0)\";\n return;\n }\n\n d->m_layer = layer;\n\n TileId id;\n TextureTile tile( id );\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n tile.loadDataset( texture, 0, 0, 0 );\n\n \/\/ We assume that all tiles have the same size. TODO: check to be safe\n d->m_tileWidth = tile.rawtile().width();\n d->m_tileHeight = tile.rawtile().height();\n}\n\nvoid TileLoader::resetTilehash()\n{\n QHash<TileId, TextureTile*>::const_iterator it = d->m_tilesOnDisplay.constBegin();\n while ( it != d->m_tilesOnDisplay.constEnd() ) {\n it.value()->setUsed( false );\n ++it;\n }\n}\n\nvoid TileLoader::cleanupTilehash()\n{\n \/\/ Make sure that tiles which haven't been used during the last\n \/\/ rendering of the map at all get removed from the tile hash.\n\n QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );\n while ( it.hasNext() ) {\n it.next();\n if ( !it.value()->used() ) {\n \/\/ If insert call result is false then the cache is too small to store the tile \n \/\/ but the item will get deleted nevertheless and the pointer we have \n \/\/ doesn't get set to zero (so don't delete it in this case or it will crash!)\n d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );\n d->m_tilesOnDisplay.remove( it.key() );\n }\n }\n}\n\nvoid TileLoader::flush()\n{\n \/\/ Remove all tiles from m_tilesOnDisplay\n QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );\n while ( it.hasNext() ) {\n it.next();\n \/\/ If insert call result is false then the cache is too small to store the tile \n \/\/ but the item will get deleted nevertheless and the pointer we have \n \/\/ doesn't get set to zero (so don't delete it in this case or it will crash!)\n d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );\n d->m_tilesOnDisplay.remove( it.key() );\n }\n\n d->m_tilesOnDisplay.clear();\n}\n\nint TileLoader::tileWidth() const\n{\n return d->m_tileWidth;\n}\n\nint TileLoader::tileHeight() const\n{\n return d->m_tileHeight;\n}\n\nint TileLoader::globalWidth( int level ) const\n{\n if ( !d->m_layer ) return 0;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n return d->m_tileWidth * TileLoaderHelper::levelToColumn( \n texture->levelZeroColumns(), level );\n}\n\nint TileLoader::globalHeight( int level ) const\n{\n if ( !d->m_layer ) return 0;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n return d->m_tileHeight * TileLoaderHelper::levelToRow( \n texture->levelZeroRows(), level );\n}\n\nTextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel )\n{\n if ( !d->m_layer ) return 0;\n\n TileId tileId( tileLevel, tilx, tily );\n\n \/\/ check if the tile is in the hash\n TextureTile * tile = d->m_tilesOnDisplay.value( tileId, 0 );\n if ( tile ) {\n tile->setUsed( true );\n return tile;\n }\n \/\/ here ends the performance critical section of this method\n\n \/\/ the tile was not in the hash or has been removed because of expiration\n \/\/ so check if it is in the cache\n tile = d->m_tileCache.take( tileId );\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n if ( tile ) {\n \/\/ the tile was in the cache, but is it up to date?\n const QDateTime now = QDateTime::currentDateTime();\n\n if ( tile->created().secsTo( now ) < texture->expire()) {\n d->m_tilesOnDisplay[tileId] = tile;\n tile->setUsed( true );\n return tile;\n } else {\n delete tile;\n tile = 0;\n }\n }\n\n \/\/ tile (valid) has not been found in hash or cache, so load it from disk\n \/\/ and place it in the hash from where it will get transfered to the cache\n\n \/\/ qDebug() << \"load Tile from Disk: \" << tileId.toString();\n tile = new TextureTile( tileId );\n d->m_tilesOnDisplay[tileId] = tile;\n\n \/\/ FIXME: Implement asynchronous tile loading\n \/\/ d->m_datasetProvider->loadDatasets( tile );\n\n if ( d->m_downloadManager != 0 ) {\n connect( tile, SIGNAL( downloadTile( QUrl, QString, QString ) ),\n d->m_downloadManager, SLOT( addJob( QUrl, QString, QString ) ) );\n }\n connect( tile, SIGNAL( tileUpdateDone() ),\n this, SIGNAL( tileUpdateAvailable() ) );\n\n tile->loadDataset( texture, tileLevel, tilx, tily, &( d->m_tileCache ) );\n tile->initJumpTables( false );\n\n \/\/ TODO should emit signal rather than directly calling paintTile\n \/\/ emit paintTile( tile, tilx, tily, tileLevel, d->m_theme, false );\n m_parent->paintTile( tile, tilx, tily, tileLevel, texture, false );\n\n return tile;\n}\n\nGeoSceneLayer * TileLoader::layer() const\n{\n return d->m_layer;\n}\n\nquint64 TileLoader::volatileCacheLimit() const\n{\n return d->m_tileCache.maxCost() \/ 1024;\n}\n\nQList<TileId> TileLoader::tilesOnDisplay() const\n{\n QList<TileId> result;\n QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();\n QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();\n for (; pos != end; ++pos ) {\n if ( pos.value()->used() ) {\n result.append( pos.key() );\n }\n }\n return result;\n}\n\nint TileLoader::maxPartialTileLevel( GeoSceneLayer * layer )\n{\n int maxtilelevel = -1;\n\n if ( !layer ) return maxtilelevel;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n\n if ( !texture ) return maxtilelevel;\n\n QString tilepath = MarbleDirs::path( TileLoaderHelper::themeStr( texture ) );\n\/\/ qDebug() << \"TileLoader::maxPartialTileLevel tilepath\" << tilepath;\n QStringList leveldirs = ( QDir( tilepath ) ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );\n\n bool ok = true;\n\n QStringList::const_iterator constIterator = leveldirs.constBegin();\n for (; constIterator != leveldirs.constEnd(); ++constIterator )\n {\n int value = (*constIterator).toInt( &ok, 10 );\n if ( ok && value > maxtilelevel )\n maxtilelevel = value;\n }\n\n\/\/ qDebug() << \"Detected maximum tile level that contains data: \"\n\/\/ << maxtilelevel;\n\n return maxtilelevel;\n}\n\n\nbool TileLoader::baseTilesAvailable( GeoSceneLayer * layer )\n{\n if ( !layer ) return false;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n\n const int levelZeroColumns = texture->levelZeroColumns();\n const int levelZeroRows = texture->levelZeroRows();\n\n bool noerr = true; \n\n \/\/ Check whether the tiles from the lowest texture level are available\n \/\/\n for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {\n for ( int row = 0; noerr && row < levelZeroRows; ++row ) {\n\n const QString tilepath = MarbleDirs::path( TileLoaderHelper::relativeTileFileName(\n texture, 0, column, row ));\n noerr = QFile::exists( tilepath );\n }\n }\n\n return noerr;\n}\n\nvoid TileLoader::setVolatileCacheLimit( quint64 kiloBytes )\n{\n qDebug() << QString(\"Setting tile cache to %1 kilobytes.\").arg( kiloBytes );\n d->m_tileCache.setMaxCost( kiloBytes * 1024 );\n}\n\nvoid TileLoader::reloadTile( const QString &idStr )\n{\n if ( !d->m_layer ) return;\n\n\/\/ qDebug() << \"TileLoader::reloadTile:\" << idStr;\n \n const TileId id = TileId::fromString( idStr );\n if ( d->m_tilesOnDisplay.contains( id ) ) {\n int level = id.zoomLevel();\n int y = id.y();\n int x = id.x();\n\n \/\/ TODO should emit signal rather than directly calling paintTile\n\/\/ emit paintTile( d->m_tilesOnDisplay[id], x, y, level, d->m_theme, true );\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n (d->m_tilesOnDisplay[id])->loadDataset( texture, level, x, y, &( d->m_tileCache ) ); \n m_parent->paintTile( d->m_tilesOnDisplay[id], x, y, level, texture, true );\n\/\/ (d->m_tilesOnDisplay[id])->reloadTile( x, y, level, d->m_theme );\n } else {\n \/\/ Remove \"false\" tile from cache so it doesn't get loaded anymore\n d->m_tileCache.remove( id );\n qDebug() << \"No such ID:\" << idStr;\n }\n}\n\nvoid TileLoader::reloadTile( const QString &relativeUrlString, const QString &_id )\n{\n Q_UNUSED( relativeUrlString );\n \/\/ qDebug() << \"Reloading Tile\" << relativeUrlString << \"id:\" << _id;\n\n reloadTile( _id );\n}\n\nvoid TileLoader::reloadTile( const QString& serverUrlString, const QString &relativeUrlString,\n const QString &_id )\n{\n Q_UNUSED( serverUrlString );\n Q_UNUSED( relativeUrlString );\n \/\/ qDebug() << \"Reloading Tile\" << serverUrlString << relativeUrlString << \"id:\" << _id;\n\n reloadTile( _id );\n}\n\nvoid TileLoader::update()\n{\n qDebug() << \"TileLoader::update()\";\n flush(); \/\/ trigger a reload of all tiles that are currently in use\n d->m_tileCache.clear(); \/\/ clear the tile cache in physical memory\n emit tileUpdateAvailable();\n}\n\n}\n\n#include \"TileLoader.moc\"\n<commit_msg>Cache end iterators.<commit_after>\/**\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2005-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n * Copyright 2008,2009 Jens-Michael Hoffmann <jensmh@gmx.de>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n#include \"TileLoader.h\"\n\n#include \"global.h\"\n#include \"GeoSceneLayer.h\"\n#include \"GeoSceneTexture.h\"\n#include \"HttpDownloadManager.h\"\n#include \"DatasetProvider.h\"\n#include \"TextureTile.h\"\n#include \"MarbleDirs.h\"\n#include \"MarbleModel.h\"\n#include \"TileLoaderHelper.h\"\n\n#include <QtCore\/QCache>\n#include <QtCore\/QDebug>\n#include <QtCore\/QHash>\n#include <QtGui\/QImage>\n\n\n#ifdef Q_CC_MSVC\n# ifndef KDEWIN_MATH_H\n long double log(int i) { return log((long double)i); }\n# endif\n#endif\n\nnamespace Marble\n{\n\nclass TileLoaderPrivate\n{\n public:\n TileLoaderPrivate()\n : m_datasetProvider( 0 ),\n m_downloadManager( 0 ),\n m_layer( 0 ),\n m_tileWidth( 0 ),\n m_tileHeight( 0 )\n {\n m_tileCache.setMaxCost( 20000 * 1024 ); \/\/ Cache size measured in bytes\n }\n\n DatasetProvider *m_datasetProvider;\n HttpDownloadManager *m_downloadManager;\n GeoSceneLayer *m_layer;\n QHash <TileId, TextureTile*> m_tilesOnDisplay;\n int m_tileWidth;\n int m_tileHeight;\n QCache <TileId, TextureTile> m_tileCache;\n};\n\n\n\nTileLoader::TileLoader( HttpDownloadManager *downloadManager, MarbleModel* parent)\n : d( new TileLoaderPrivate() ),\n m_parent(parent)\n{\n setDownloadManager( downloadManager );\n}\n\nTileLoader::~TileLoader()\n{\n flush();\n d->m_tileCache.clear();\n if ( d->m_downloadManager != 0 )\n d->m_downloadManager->disconnect( this );\n\n delete d;\n}\n\nvoid TileLoader::setDownloadManager( HttpDownloadManager *downloadManager )\n{\n if ( d->m_downloadManager != 0 ) {\n d->m_downloadManager->disconnect( this );\n d->m_downloadManager = 0;\n }\n\n d->m_downloadManager = downloadManager;\n if ( d->m_downloadManager != 0 ) {\n connect( d->m_downloadManager, SIGNAL( downloadComplete( QString, QString ) ),\n this, SLOT( reloadTile( QString, QString ) ) );\n }\n}\n\nvoid TileLoader::setLayer( GeoSceneLayer * layer )\n{\n \/\/ Initialize map theme.\n flush();\n d->m_tileCache.clear();\n\n if ( !layer ) {\n qDebug() << \"No layer specified! (GeoSceneLayer * layer = 0)\";\n return;\n }\n\n d->m_layer = layer;\n\n TileId id;\n TextureTile tile( id );\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n tile.loadDataset( texture, 0, 0, 0 );\n\n \/\/ We assume that all tiles have the same size. TODO: check to be safe\n d->m_tileWidth = tile.rawtile().width();\n d->m_tileHeight = tile.rawtile().height();\n}\n\nvoid TileLoader::resetTilehash()\n{\n QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();\n QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();\n for (; pos != end; ++pos ) {\n pos.value()->setUsed( false );\n }\n}\n\nvoid TileLoader::cleanupTilehash()\n{\n \/\/ Make sure that tiles which haven't been used during the last\n \/\/ rendering of the map at all get removed from the tile hash.\n\n QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );\n while ( it.hasNext() ) {\n it.next();\n if ( !it.value()->used() ) {\n \/\/ If insert call result is false then the cache is too small to store the tile \n \/\/ but the item will get deleted nevertheless and the pointer we have \n \/\/ doesn't get set to zero (so don't delete it in this case or it will crash!)\n d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );\n d->m_tilesOnDisplay.remove( it.key() );\n }\n }\n}\n\nvoid TileLoader::flush()\n{\n \/\/ Remove all tiles from m_tilesOnDisplay\n QHashIterator<TileId, TextureTile*> it( d->m_tilesOnDisplay );\n while ( it.hasNext() ) {\n it.next();\n \/\/ If insert call result is false then the cache is too small to store the tile \n \/\/ but the item will get deleted nevertheless and the pointer we have \n \/\/ doesn't get set to zero (so don't delete it in this case or it will crash!)\n d->m_tileCache.insert( it.key(), it.value(), it.value()->numBytes() );\n d->m_tilesOnDisplay.remove( it.key() );\n }\n\n d->m_tilesOnDisplay.clear();\n}\n\nint TileLoader::tileWidth() const\n{\n return d->m_tileWidth;\n}\n\nint TileLoader::tileHeight() const\n{\n return d->m_tileHeight;\n}\n\nint TileLoader::globalWidth( int level ) const\n{\n if ( !d->m_layer ) return 0;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n return d->m_tileWidth * TileLoaderHelper::levelToColumn( \n texture->levelZeroColumns(), level );\n}\n\nint TileLoader::globalHeight( int level ) const\n{\n if ( !d->m_layer ) return 0;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n return d->m_tileHeight * TileLoaderHelper::levelToRow( \n texture->levelZeroRows(), level );\n}\n\nTextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel )\n{\n if ( !d->m_layer ) return 0;\n\n TileId tileId( tileLevel, tilx, tily );\n\n \/\/ check if the tile is in the hash\n TextureTile * tile = d->m_tilesOnDisplay.value( tileId, 0 );\n if ( tile ) {\n tile->setUsed( true );\n return tile;\n }\n \/\/ here ends the performance critical section of this method\n\n \/\/ the tile was not in the hash or has been removed because of expiration\n \/\/ so check if it is in the cache\n tile = d->m_tileCache.take( tileId );\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n if ( tile ) {\n \/\/ the tile was in the cache, but is it up to date?\n const QDateTime now = QDateTime::currentDateTime();\n\n if ( tile->created().secsTo( now ) < texture->expire()) {\n d->m_tilesOnDisplay[tileId] = tile;\n tile->setUsed( true );\n return tile;\n } else {\n delete tile;\n tile = 0;\n }\n }\n\n \/\/ tile (valid) has not been found in hash or cache, so load it from disk\n \/\/ and place it in the hash from where it will get transfered to the cache\n\n \/\/ qDebug() << \"load Tile from Disk: \" << tileId.toString();\n tile = new TextureTile( tileId );\n d->m_tilesOnDisplay[tileId] = tile;\n\n \/\/ FIXME: Implement asynchronous tile loading\n \/\/ d->m_datasetProvider->loadDatasets( tile );\n\n if ( d->m_downloadManager != 0 ) {\n connect( tile, SIGNAL( downloadTile( QUrl, QString, QString ) ),\n d->m_downloadManager, SLOT( addJob( QUrl, QString, QString ) ) );\n }\n connect( tile, SIGNAL( tileUpdateDone() ),\n this, SIGNAL( tileUpdateAvailable() ) );\n\n tile->loadDataset( texture, tileLevel, tilx, tily, &( d->m_tileCache ) );\n tile->initJumpTables( false );\n\n \/\/ TODO should emit signal rather than directly calling paintTile\n \/\/ emit paintTile( tile, tilx, tily, tileLevel, d->m_theme, false );\n m_parent->paintTile( tile, tilx, tily, tileLevel, texture, false );\n\n return tile;\n}\n\nGeoSceneLayer * TileLoader::layer() const\n{\n return d->m_layer;\n}\n\nquint64 TileLoader::volatileCacheLimit() const\n{\n return d->m_tileCache.maxCost() \/ 1024;\n}\n\nQList<TileId> TileLoader::tilesOnDisplay() const\n{\n QList<TileId> result;\n QHash<TileId, TextureTile*>::const_iterator pos = d->m_tilesOnDisplay.constBegin();\n QHash<TileId, TextureTile*>::const_iterator const end = d->m_tilesOnDisplay.constEnd();\n for (; pos != end; ++pos ) {\n if ( pos.value()->used() ) {\n result.append( pos.key() );\n }\n }\n return result;\n}\n\nint TileLoader::maxPartialTileLevel( GeoSceneLayer * layer )\n{\n int maxtilelevel = -1;\n\n if ( !layer ) return maxtilelevel;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n\n if ( !texture ) return maxtilelevel;\n\n QString tilepath = MarbleDirs::path( TileLoaderHelper::themeStr( texture ) );\n\/\/ qDebug() << \"TileLoader::maxPartialTileLevel tilepath\" << tilepath;\n QStringList leveldirs = ( QDir( tilepath ) ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );\n\n bool ok = true;\n\n QStringList::const_iterator pos = leveldirs.constBegin();\n QStringList::const_iterator const end = leveldirs.constEnd();\n for (; pos != end; ++pos ) {\n int value = (*pos).toInt( &ok, 10 );\n if ( ok && value > maxtilelevel )\n maxtilelevel = value;\n }\n\n\/\/ qDebug() << \"Detected maximum tile level that contains data: \"\n\/\/ << maxtilelevel;\n\n return maxtilelevel;\n}\n\n\nbool TileLoader::baseTilesAvailable( GeoSceneLayer * layer )\n{\n if ( !layer ) return false;\n\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n\n const int levelZeroColumns = texture->levelZeroColumns();\n const int levelZeroRows = texture->levelZeroRows();\n\n bool noerr = true; \n\n \/\/ Check whether the tiles from the lowest texture level are available\n \/\/\n for ( int column = 0; noerr && column < levelZeroColumns; ++column ) {\n for ( int row = 0; noerr && row < levelZeroRows; ++row ) {\n\n const QString tilepath = MarbleDirs::path( TileLoaderHelper::relativeTileFileName(\n texture, 0, column, row ));\n noerr = QFile::exists( tilepath );\n }\n }\n\n return noerr;\n}\n\nvoid TileLoader::setVolatileCacheLimit( quint64 kiloBytes )\n{\n qDebug() << QString(\"Setting tile cache to %1 kilobytes.\").arg( kiloBytes );\n d->m_tileCache.setMaxCost( kiloBytes * 1024 );\n}\n\nvoid TileLoader::reloadTile( const QString &idStr )\n{\n if ( !d->m_layer ) return;\n\n\/\/ qDebug() << \"TileLoader::reloadTile:\" << idStr;\n \n const TileId id = TileId::fromString( idStr );\n if ( d->m_tilesOnDisplay.contains( id ) ) {\n int level = id.zoomLevel();\n int y = id.y();\n int x = id.x();\n\n \/\/ TODO should emit signal rather than directly calling paintTile\n\/\/ emit paintTile( d->m_tilesOnDisplay[id], x, y, level, d->m_theme, true );\n GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( d->m_layer->groundDataset() );\n\n (d->m_tilesOnDisplay[id])->loadDataset( texture, level, x, y, &( d->m_tileCache ) ); \n m_parent->paintTile( d->m_tilesOnDisplay[id], x, y, level, texture, true );\n\/\/ (d->m_tilesOnDisplay[id])->reloadTile( x, y, level, d->m_theme );\n } else {\n \/\/ Remove \"false\" tile from cache so it doesn't get loaded anymore\n d->m_tileCache.remove( id );\n qDebug() << \"No such ID:\" << idStr;\n }\n}\n\nvoid TileLoader::reloadTile( const QString &relativeUrlString, const QString &_id )\n{\n Q_UNUSED( relativeUrlString );\n \/\/ qDebug() << \"Reloading Tile\" << relativeUrlString << \"id:\" << _id;\n\n reloadTile( _id );\n}\n\nvoid TileLoader::reloadTile( const QString& serverUrlString, const QString &relativeUrlString,\n const QString &_id )\n{\n Q_UNUSED( serverUrlString );\n Q_UNUSED( relativeUrlString );\n \/\/ qDebug() << \"Reloading Tile\" << serverUrlString << relativeUrlString << \"id:\" << _id;\n\n reloadTile( _id );\n}\n\nvoid TileLoader::update()\n{\n qDebug() << \"TileLoader::update()\";\n flush(); \/\/ trigger a reload of all tiles that are currently in use\n d->m_tileCache.clear(); \/\/ clear the tile cache in physical memory\n emit tileUpdateAvailable();\n}\n\n}\n\n#include \"TileLoader.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Jens-Michael Hoffmann <jmho@c-xx.com>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"TileLoader.h\"\n\n#include <QtCore\/QDateTime>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QMetaType>\n#include <QtGui\/QImage>\n\n#include \"GeoSceneTexture.h\"\n#include \"HttpDownloadManager.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"TileLoaderHelper.h\"\n\nQ_DECLARE_METATYPE( Marble::DownloadUsage )\n\nnamespace Marble\n{\n\nTileLoader::TileLoader( HttpDownloadManager * const downloadManager )\n{\n qRegisterMetaType<DownloadUsage>( \"DownloadUsage\" );\n connect( this, SIGNAL( downloadTile( QUrl, QString, QString, DownloadUsage )),\n downloadManager, SLOT( addJob( QUrl, QString, QString, DownloadUsage )));\n connect( downloadManager, SIGNAL( downloadComplete( QByteArray, QString )),\n SLOT( updateTile( QByteArray, QString )));\n}\n\n\/\/ If the tile is locally available:\n\/\/ - if not expired: create TextureTile, set state to \"uptodate\", return it => done\n\/\/ - if expired: create TextureTile, state is set to Expired by default, trigger dl,\n\nQImage TileLoader::loadTile( GeoSceneTexture const *textureLayer, TileId const & tileId, DownloadUsage const usage )\n{\n QString const fileName = tileFileName( textureLayer, tileId );\n TileStatus status = tileStatus( textureLayer, tileId );\n if ( status != Missing ) {\n \/\/ check if an update should be triggered\n\n if ( status == Available ) {\n mDebug() << Q_FUNC_INFO << tileId << \"StateUptodate\";\n } else {\n Q_ASSERT( status == Expired );\n mDebug() << Q_FUNC_INFO << tileId << \"StateExpired\";\n triggerDownload( textureLayer, tileId, usage );\n }\n\n QImage const image( fileName );\n if ( !image.isNull() ) {\n \/\/ file is there, so create and return a tile object in any case\n return image;\n }\n }\n\n \/\/ tile was not locally available => trigger download and look for tiles in other levels\n \/\/ for scaling\n QImage replacementTile = scaledLowerLevelTile( textureLayer, tileId );\n Q_ASSERT( !replacementTile.isNull() );\n\n triggerDownload( textureLayer, tileId, usage );\n\n return replacementTile;\n}\n\n\/\/ This method triggers a download of the given tile (without checking\n\/\/ expiration). It is called by upper layer (StackedTileLoader) when the tile\n\/\/ that should be reloaded is currently loaded in memory.\n\/\/\n\/\/ post condition\n\/\/ - download is triggered\nvoid TileLoader::downloadTile( GeoSceneTexture const *textureLayer, TileId const &tileId, DownloadUsage const usage )\n{\n triggerDownload( textureLayer, tileId, usage );\n}\n\nint TileLoader::maximumTileLevel( GeoSceneTexture const & texture )\n{\n \/\/ if maximum tile level is configured in the DGML files,\n \/\/ then use it, otherwise use old detection code.\n if ( texture.maximumTileLevel() >= 0 ) {\n return texture.maximumTileLevel();\n }\n\n int maximumTileLevel = -1;\n const QFileInfo themeStr( texture.themeStr() );\n const QString tilepath = themeStr.isAbsolute() ? themeStr.absoluteFilePath() : MarbleDirs::path( texture.themeStr() );\n \/\/ mDebug() << \"StackedTileLoader::maxPartialTileLevel tilepath\" << tilepath;\n QStringList leveldirs = QDir( tilepath ).entryList( QDir::AllDirs | QDir::NoSymLinks\n | QDir::NoDotAndDotDot );\n\n QStringList::const_iterator it = leveldirs.constBegin();\n QStringList::const_iterator const end = leveldirs.constEnd();\n for (; it != end; ++it ) {\n bool ok = true;\n const int value = (*it).toInt( &ok, 10 );\n\n if ( ok && value > maximumTileLevel )\n maximumTileLevel = value;\n }\n\n \/\/ mDebug() << \"Detected maximum tile level that contains data: \"\n \/\/ << maxtilelevel;\n return maximumTileLevel + 1;\n}\n\nbool TileLoader::baseTilesAvailable( GeoSceneTexture const & texture )\n{\n const int levelZeroColumns = texture.levelZeroColumns();\n const int levelZeroRows = texture.levelZeroRows();\n\n bool result = true;\n\n \/\/ Check whether the tiles from the lowest texture level are available\n \/\/\n for ( int column = 0; result && column < levelZeroColumns; ++column ) {\n for ( int row = 0; result && row < levelZeroRows; ++row ) {\n const TileId id( texture.sourceDir(), 0, column, row );\n const QString tilepath = tileFileName( &texture, id );\n result &= QFile::exists( tilepath );\n }\n }\n\n return result;\n}\n\nTileLoader::TileStatus TileLoader::tileStatus( GeoSceneTexture const *textureLayer, const TileId &tileId )\n{\n QString const fileName = tileFileName( textureLayer, tileId );\n QFileInfo fileInfo( fileName );\n if ( !fileInfo.exists() ) {\n return Missing;\n }\n\n const QDateTime lastModified = fileInfo.lastModified();\n const int expireSecs = textureLayer->expire();\n const bool isExpired = lastModified.secsTo( QDateTime::currentDateTime() ) >= expireSecs;\n return isExpired ? Expired : Available;\n}\n\nvoid TileLoader::updateTile( QByteArray const & data, QString const & tileId )\n{\n TileId const id = TileId::fromString( tileId );\n\n QImage const tileImage = QImage::fromData( data );\n if ( tileImage.isNull() )\n return;\n\n emit tileCompleted( id, tileImage );\n}\n\nQString TileLoader::tileFileName( GeoSceneTexture const * textureLayer, TileId const & tileId )\n{\n QString const fileName = textureLayer->relativeTileFileName( tileId );\n QFileInfo const dirInfo( fileName );\n return dirInfo.isAbsolute() ? fileName : MarbleDirs::path( fileName );\n}\n\nvoid TileLoader::triggerDownload( GeoSceneTexture const *textureLayer, TileId const &id, DownloadUsage const usage )\n{\n QUrl const sourceUrl = textureLayer->downloadUrl( id );\n QString const destFileName = textureLayer->relativeTileFileName( id );\n emit downloadTile( sourceUrl, destFileName, id.toString(), usage );\n}\n\nQImage TileLoader::scaledLowerLevelTile( GeoSceneTexture const *textureLayer, TileId const & id ) const\n{\n mDebug() << Q_FUNC_INFO << id;\n\n for ( int level = qMax<int>( 0, id.zoomLevel() - 1 ); level >= 0; --level ) {\n int const deltaLevel = id.zoomLevel() - level;\n TileId const replacementTileId( id.mapThemeIdHash(), level,\n id.x() >> deltaLevel, id.y() >> deltaLevel );\n QString const fileName = tileFileName( textureLayer, replacementTileId );\n mDebug() << \"TileLoader::scaledLowerLevelTile\" << \"trying\" << fileName;\n QImage toScale( fileName );\n\n if ( level == 0 && toScale.isNull() ) {\n mDebug() << \"No level zero tile installed in map theme dir. Falling back to a transparent image for now.\";\n QSize tileSize = textureLayer->tileSize();\n Q_ASSERT( !tileSize.isEmpty() ); \/\/ assured by textureLayer\n toScale = QImage( tileSize, QImage::Format_ARGB32_Premultiplied );\n toScale.fill( qRgba( 0, 0, 0, 0 ) );\n }\n\n if ( !toScale.isNull() ) {\n \/\/ which rect to scale?\n int const restTileX = id.x() % ( 1 << deltaLevel );\n int const restTileY = id.y() % ( 1 << deltaLevel );\n int const partWidth = toScale.width() >> deltaLevel;\n int const partHeight = toScale.height() >> deltaLevel;\n int const startX = restTileX * partWidth;\n int const startY = restTileY * partHeight;\n mDebug() << \"QImage::copy:\" << startX << startY << partWidth << partHeight;\n QImage const part = toScale.copy( startX, startY, partWidth, partHeight );\n mDebug() << \"QImage::scaled:\" << toScale.size();\n return part.scaled( toScale.size() );\n }\n }\n\n Q_ASSERT_X( false, \"scaled image\", \"level zero image missing\" ); \/\/ not reached\n return QImage();\n}\n\n}\n\n#include \"TileLoader.moc\"\n<commit_msg>More detailed debug info when a base tile is missing.<commit_after>\/\/ Copyright 2010 Jens-Michael Hoffmann <jmho@c-xx.com>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"TileLoader.h\"\n\n#include <QtCore\/QDateTime>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QMetaType>\n#include <QtGui\/QImage>\n\n#include \"GeoSceneTexture.h\"\n#include \"HttpDownloadManager.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"TileLoaderHelper.h\"\n\nQ_DECLARE_METATYPE( Marble::DownloadUsage )\n\nnamespace Marble\n{\n\nTileLoader::TileLoader( HttpDownloadManager * const downloadManager )\n{\n qRegisterMetaType<DownloadUsage>( \"DownloadUsage\" );\n connect( this, SIGNAL( downloadTile( QUrl, QString, QString, DownloadUsage )),\n downloadManager, SLOT( addJob( QUrl, QString, QString, DownloadUsage )));\n connect( downloadManager, SIGNAL( downloadComplete( QByteArray, QString )),\n SLOT( updateTile( QByteArray, QString )));\n}\n\n\/\/ If the tile is locally available:\n\/\/ - if not expired: create TextureTile, set state to \"uptodate\", return it => done\n\/\/ - if expired: create TextureTile, state is set to Expired by default, trigger dl,\n\nQImage TileLoader::loadTile( GeoSceneTexture const *textureLayer, TileId const & tileId, DownloadUsage const usage )\n{\n QString const fileName = tileFileName( textureLayer, tileId );\n TileStatus status = tileStatus( textureLayer, tileId );\n if ( status != Missing ) {\n \/\/ check if an update should be triggered\n\n if ( status == Available ) {\n mDebug() << Q_FUNC_INFO << tileId << \"StateUptodate\";\n } else {\n Q_ASSERT( status == Expired );\n mDebug() << Q_FUNC_INFO << tileId << \"StateExpired\";\n triggerDownload( textureLayer, tileId, usage );\n }\n\n QImage const image( fileName );\n if ( !image.isNull() ) {\n \/\/ file is there, so create and return a tile object in any case\n return image;\n }\n }\n\n \/\/ tile was not locally available => trigger download and look for tiles in other levels\n \/\/ for scaling\n QImage replacementTile = scaledLowerLevelTile( textureLayer, tileId );\n Q_ASSERT( !replacementTile.isNull() );\n\n triggerDownload( textureLayer, tileId, usage );\n\n return replacementTile;\n}\n\n\/\/ This method triggers a download of the given tile (without checking\n\/\/ expiration). It is called by upper layer (StackedTileLoader) when the tile\n\/\/ that should be reloaded is currently loaded in memory.\n\/\/\n\/\/ post condition\n\/\/ - download is triggered\nvoid TileLoader::downloadTile( GeoSceneTexture const *textureLayer, TileId const &tileId, DownloadUsage const usage )\n{\n triggerDownload( textureLayer, tileId, usage );\n}\n\nint TileLoader::maximumTileLevel( GeoSceneTexture const & texture )\n{\n \/\/ if maximum tile level is configured in the DGML files,\n \/\/ then use it, otherwise use old detection code.\n if ( texture.maximumTileLevel() >= 0 ) {\n return texture.maximumTileLevel();\n }\n\n int maximumTileLevel = -1;\n const QFileInfo themeStr( texture.themeStr() );\n const QString tilepath = themeStr.isAbsolute() ? themeStr.absoluteFilePath() : MarbleDirs::path( texture.themeStr() );\n \/\/ mDebug() << \"StackedTileLoader::maxPartialTileLevel tilepath\" << tilepath;\n QStringList leveldirs = QDir( tilepath ).entryList( QDir::AllDirs | QDir::NoSymLinks\n | QDir::NoDotAndDotDot );\n\n QStringList::const_iterator it = leveldirs.constBegin();\n QStringList::const_iterator const end = leveldirs.constEnd();\n for (; it != end; ++it ) {\n bool ok = true;\n const int value = (*it).toInt( &ok, 10 );\n\n if ( ok && value > maximumTileLevel )\n maximumTileLevel = value;\n }\n\n \/\/ mDebug() << \"Detected maximum tile level that contains data: \"\n \/\/ << maxtilelevel;\n return maximumTileLevel + 1;\n}\n\nbool TileLoader::baseTilesAvailable( GeoSceneTexture const & texture )\n{\n const int levelZeroColumns = texture.levelZeroColumns();\n const int levelZeroRows = texture.levelZeroRows();\n\n bool result = true;\n\n \/\/ Check whether the tiles from the lowest texture level are available\n \/\/\n for ( int column = 0; result && column < levelZeroColumns; ++column ) {\n for ( int row = 0; result && row < levelZeroRows; ++row ) {\n const TileId id( texture.sourceDir(), 0, column, row );\n const QString tilepath = tileFileName( &texture, id );\n result &= QFile::exists( tilepath );\n if (!result) {\n mDebug() << \"Base tile \" << texture.relativeTileFileName( id ) << \" is missing for source dir \" << texture.sourceDir();\n }\n }\n }\n\n return result;\n}\n\nTileLoader::TileStatus TileLoader::tileStatus( GeoSceneTexture const *textureLayer, const TileId &tileId )\n{\n QString const fileName = tileFileName( textureLayer, tileId );\n QFileInfo fileInfo( fileName );\n if ( !fileInfo.exists() ) {\n return Missing;\n }\n\n const QDateTime lastModified = fileInfo.lastModified();\n const int expireSecs = textureLayer->expire();\n const bool isExpired = lastModified.secsTo( QDateTime::currentDateTime() ) >= expireSecs;\n return isExpired ? Expired : Available;\n}\n\nvoid TileLoader::updateTile( QByteArray const & data, QString const & tileId )\n{\n TileId const id = TileId::fromString( tileId );\n\n QImage const tileImage = QImage::fromData( data );\n if ( tileImage.isNull() )\n return;\n\n emit tileCompleted( id, tileImage );\n}\n\nQString TileLoader::tileFileName( GeoSceneTexture const * textureLayer, TileId const & tileId )\n{\n QString const fileName = textureLayer->relativeTileFileName( tileId );\n QFileInfo const dirInfo( fileName );\n return dirInfo.isAbsolute() ? fileName : MarbleDirs::path( fileName );\n}\n\nvoid TileLoader::triggerDownload( GeoSceneTexture const *textureLayer, TileId const &id, DownloadUsage const usage )\n{\n QUrl const sourceUrl = textureLayer->downloadUrl( id );\n QString const destFileName = textureLayer->relativeTileFileName( id );\n emit downloadTile( sourceUrl, destFileName, id.toString(), usage );\n}\n\nQImage TileLoader::scaledLowerLevelTile( GeoSceneTexture const *textureLayer, TileId const & id ) const\n{\n mDebug() << Q_FUNC_INFO << id;\n\n for ( int level = qMax<int>( 0, id.zoomLevel() - 1 ); level >= 0; --level ) {\n int const deltaLevel = id.zoomLevel() - level;\n TileId const replacementTileId( id.mapThemeIdHash(), level,\n id.x() >> deltaLevel, id.y() >> deltaLevel );\n QString const fileName = tileFileName( textureLayer, replacementTileId );\n mDebug() << \"TileLoader::scaledLowerLevelTile\" << \"trying\" << fileName;\n QImage toScale( fileName );\n\n if ( level == 0 && toScale.isNull() ) {\n mDebug() << \"No level zero tile installed in map theme dir. Falling back to a transparent image for now.\";\n QSize tileSize = textureLayer->tileSize();\n Q_ASSERT( !tileSize.isEmpty() ); \/\/ assured by textureLayer\n toScale = QImage( tileSize, QImage::Format_ARGB32_Premultiplied );\n toScale.fill( qRgba( 0, 0, 0, 0 ) );\n }\n\n if ( !toScale.isNull() ) {\n \/\/ which rect to scale?\n int const restTileX = id.x() % ( 1 << deltaLevel );\n int const restTileY = id.y() % ( 1 << deltaLevel );\n int const partWidth = toScale.width() >> deltaLevel;\n int const partHeight = toScale.height() >> deltaLevel;\n int const startX = restTileX * partWidth;\n int const startY = restTileY * partHeight;\n mDebug() << \"QImage::copy:\" << startX << startY << partWidth << partHeight;\n QImage const part = toScale.copy( startX, startY, partWidth, partHeight );\n mDebug() << \"QImage::scaled:\" << toScale.size();\n return part.scaled( toScale.size() );\n }\n }\n\n Q_ASSERT_X( false, \"scaled image\", \"level zero image missing\" ); \/\/ not reached\n return QImage();\n}\n\n}\n\n#include \"TileLoader.moc\"\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"histoBook.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n\n\/\/ constructor sets the name of the file for saving\nhistoBook::histoBook( string name, string input, string inDir ){\n\n\tif (name.find( \".root\") != std::string::npos){\n\t\tfilename = name;\t\n\t} else\n\t\tfilename = name + \".root\";\n\n\tcurrentDir = \"\/\";\n\n\tfile = new TFile( filename.c_str(), \"recreate\" );\n\tfile->cd();\n\n\t\n\t\/\/ make the legend and draw it once to apply styles etc. \n\t\/\/ for some reason needed to make styling work on the first draw\n\tlegend = new TLegend( 0.65, 0.65, 0.9, 0.9);\n\tlegend->SetFillColor( kWhite );\n\tlegend->Draw();\n\tlegend->Clear();\n\n\tglobalStyle();\n\n\t\/\/ if an input was given merge it into the live record\n\tif ( input.length() >= 5 ){\n\t\tTFile * fin = new TFile( input.c_str() );\n\t\tcd ( inDir );\n\t\tfin->cd( inDir.c_str() );\n\t\tloadRootDir( gDirectory, inDir );\n\t}\n\n\n\n}\n\/\/ destructor\nhistoBook::~histoBook(){\n\n\tdelete legend;\n\n\tsave();\n\tfile->Close();\n}\nvoid histoBook::save() {\n\n\tfile->Write();\n}\n\nvoid histoBook::loadRootDir( TDirectory* tDir, string path ){\n\n\t\/\/cout << \"histoBook.loadRootDir] Path : \" << path << endl;\n\n\tTList* list;\n\n\tif ( tDir ){\n\t\tlist = tDir->GetListOfKeys(); \n\t} else {\n\t\tcout << \"[histoBook.loadRootDir] Bad Directory Given \" << endl;\n\t\treturn;\n\t}\n\n\tTIter next(list); \n\tTKey* key; \n\tTObject* obj; \n\t\n\twhile ( (key = (TKey*)next()) ) { \n\t\t\n\t\tobj = key->ReadObj() ; \n\t\t\n\t\tif ( 0 == strcmp(obj->IsA()->GetName(),\"TDirectoryFile\") ){\n\t\t\tTDirectoryFile* dir = (TDirectoryFile*)obj;\n\t\t\t\n\t\t\tstring nPath = path + dir->GetName();\n\t\t\tif ( path == (string) \"\" )\n\t\t\t\tnPath = path + dir->GetName();\n\t\t\telse \n\t\t\t\tnPath = path + \"\/\" + dir->GetName();\n\n\t\t\tcd( nPath );\n\t\t\tloadRootDir( dir, nPath );\n\t\t} else if ( obj ){\n\t\t\tif ( (strcmp(obj->IsA()->GetName(),\"TProfile\")!=0) && (!obj->InheritsFrom(\"TH2\") && (!obj->InheritsFrom(\"TH1\"))) ) { \n\t\t\t\t\/\/ not a 1d or 2d histogram\n\t\t\t} else {\n\t\t\t\t\/\/ add it to the book\n\t\t\t\t\/\/cout << \"Adding : \" << obj->GetName() << endl;\n\t\t\t\tadd( obj->GetName(), (TH1*)obj->Clone( obj->GetName() ) );\n\t\t\t} \n\t\t\t\n\t\t}\n\t}\t\n\n}\n\n\nvoid histoBook::add( string name, TH1* h ){\n\n\tstring oName = name;\n\tif ( name.length() <= 1 || !h )\n\t\treturn;\n\n\tname = currentDir + name;\n\t\n\t\/\/ dont allow duplicated name overites\n\tif ( book[ name ] ){\n\t\tcout << \"[histoBook.add] Duplicate histogram name in this directory \" << currentDir << \" \/ \" << oName << endl;\n\t\treturn;\n\t}\n\n\t\/\/ save the histo to the map\n\tbook[ name ] = h;\n\n}\n\/*\n*\n* TODO:: add support for full subdirectory trees\n*\/\nstring histoBook::cd( string sdir ){\n\n\tstring old = currentDir;\n\n\tchar* csdir = (char*)sdir.c_str();\n\tfile->cd();\n\n\tif ( file->GetDirectory( csdir ) ){\n\t\tfile->cd( csdir );\n\t} else {\n\t\tcout << \"[histoBook.cd] creating directory \" << sdir << endl;\n\t\tfile->mkdir( csdir );\n\t\tfile->cd( csdir );\n\t}\n\n\tcurrentDir = sdir;\n\n\treturn old;\n}\n\nvoid histoBook::make( xmlConfig * config, string nodeName ){\n\n\tif ( config && config->nodeExists( nodeName ) ){\n\t\t\n\t\tstring hName = config->tagName( nodeName );\n\t\tif ( \"\" == hName )\n\t\t\thName = nodeName;\n\n\t\tstring type = config->getString( nodeName + \":type\", \"1D\" );\n\n\t\tif ( \"1D\" == type ){\n\t\t\tmake1D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ) );\n\n\t\t} else if ( \"2D\" == type ){\n\t\t\tmake2D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ),\n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsY\", 1 ), config->getDouble( nodeName + \":y1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":y2\", 1 ) );\n\t\t} else if ( \"1F\" == type ){\n\t\t\t\n\t\t}\n\t}\n\n}\n\nvoid histoBook::make1F( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1F* h;\n\th = new TH1F( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\n\nvoid histoBook::make1D( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make1D( string name, string title, uint nBins, const Double_t* bins ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, bins );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make2D( string name, string title, uint nBinsX, double lowX, double hiX, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, lowX, hiX, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\nvoid histoBook::make2D( string name, string title, uint nBinsX, const Double_t* xBins, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, xBins, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\n\n\nTH1* histoBook::get( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn book[ ( sdir + name ) ];\n}\nTH2* histoBook::get2D( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn (TH2*)book[ ( sdir + name ) ];\n}\n\nvoid histoBook::fill( string name, double bin, double weight ){ \n\tif ( get( name ) != 0)\n\t\tget( name )->Fill( bin, weight );\n}\n\n\nvoid histoBook::globalStyle(){\n\n\tgStyle->SetCanvasColor(kWhite); \/\/ background is no longer mouse-dropping white\n \tgStyle->SetPalette(1,0); \/\/ blue to red false color palette. Use 9 for b\/w\n \tgStyle->SetCanvasBorderMode(0); \/\/ turn off canvas borders\n \tgStyle->SetPadBorderMode(0);\n \tgStyle->SetPaintTextFormat(\"5.2f\"); \/\/ What precision to put numbers if plotted with \"TEXT\"\n\n\n \t\/\/ For publishing:\n \tgStyle->SetLineWidth(2.);\n \tgStyle->SetTextSize(0.7);\n \tgStyle->SetLabelSize(0.05,\"xy\");\n \tgStyle->SetTitleSize(0.05,\"xy\");\n \tgStyle->SetTitleOffset(1.0,\"x\");\n \tgStyle->SetTitleOffset(1.5,\"y\");\n \tgStyle->SetPadTopMargin(0.1);\n \tgStyle->SetPadRightMargin(0.1);\n \tgStyle->SetPadBottomMargin(0.16);\n \tgStyle->SetPadLeftMargin(0.2);\n\n \tgStyle->SetFillColor(-1); \n\tgStyle->SetFillStyle(4000); \n\n\n\t\n}\n\n\nhistoBook* histoBook::style( string histName ){\n\tstyling = histName;\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, string p1, string p2, string p3, string p4 ){\n\t\n\t\/\/ force the param name to lowercase\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"title\" == param ){\n\t \th->SetTitle( p1.c_str() );\n\t } else if ( \"x\" == param ){\n\t \th->GetXaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"y\" == param ){\n\t \th->GetYaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"legend\" == param ){\n\t \tif ( p2 == \"\")\n\t \t\tp2=\"lpf\";\n\t \tlegend->AddEntry( h, p1.c_str(), p2.c_str() );\n\t\t\tlegend->Draw();\n\t } else if ( \"draw\" == param ){\n\t \tdrawOption = p1;\n\t }\n\t}\n\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, double p1, double p2, double p3, double p4 ){\n\n\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"linecolor\" == param ){\n\n\t \th->SetLineColor( (int) p1 );\n\t } else if ( \"domain\" == param ){\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t\t h->GetXaxis()->SetRangeUser( min, max );\n\t } else if ( \"dynamicdomain\" == param ){\n\t \tdouble thresh = p1;\n\t \tint min = (int)p2;\n\t \tint max = (int)p3;\n\t \tint axis = (int)p4;\t\t\/\/ 1 = x, 2 = y\n\n\t \tif ( 1 != axis && 2 != axis )\n\t \t\taxis = 1;\n\t \t\n\t \tif ( thresh >= 0) {\n\t \t\tif ( -1 >= min )\n\t \t\t\tmin = h->FindFirstBinAbove( thresh, axis );\n\t \t\tif ( -1 >= max )\n\t \t\t\tmax = h->FindLastBinAbove( thresh, axis );\n\t \t}\n\t \t\n\t \tif ( 1 == axis )\n\t\t \t h->GetXaxis()->SetRange( min, max );\n\t\t \telse if ( 2 == axis )\n\t\t \t\th->GetYaxis()->SetRange( min, max );\n\n\t } else if ( \"range\" == param ){\n\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t \t\n\t \th->GetYaxis()->SetRangeUser( min, max );\n\t } else if ( \"markercolor\" == param ) {\n\t \th->SetMarkerColor( (int)p1 );\n\t } else if ( \"markerstyle\" == param ) {\n\t \th->SetMarkerStyle( (int)p1 );\n\t } else if ( \"legend\" == param ){\n\t \t\/\/ p1 - alignmentX\n\t \t\/\/ p2 - alignmentY\n\t \t\/\/ p3 - width\n\t \t\/\/ p4 - height\n\n\t \t\/\/ make sure option is valid\n\t \tif ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )\n\t \t\tp1 = legendAlignment::best;\n\t \tif ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )\n\t \t\tp2 = legendAlignment::best;\n\t \tplaceLegend( p1, p2, p3, p4 );\n\t } else if ( \"numberofticks\" == param ){\n\t \t\/\/ p1 - # of primary divisions\n\t \t\/\/ p2 - # of secondary divisions\n\t \t\/\/ p3 - axis : 0 or 1 = x, 2 = y\n\t \t\n\t \tif ( p2 == -1 )\n\t \t\tp2 = 0;\n\n\t\t if ( 2 == (int)p3 )\n\t\t \th->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t\t else \n\t\t \th->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t }\n\n }\n \n \n \n\n\n\treturn this;\n}\n\n\nhistoBook* histoBook::draw(string name, Option_t* opt ){\n\n\t\/\/ no parameters\n\tif ( name == \"\"){\n\t\tTH1* h = get( styling );\n\t\tif ( h ){\n\t\t\t\/\/ use the draw option set in its styling\n\t\t\th->Draw( drawOption.c_str() );\n\t\t\tdrawOption = \"\";\n\t\t}\t\n\t} else {\n\t\tTH1* h = get( name );\n\t\tif ( h ){\n\t\t\th->Draw( opt );\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\n\nhistoBook* histoBook::placeLegend( int alignmentX, int alignmentY, double width, double height ){\n\n\tdouble mR = 1 - gPad->GetRightMargin();\n\tdouble mL = gPad->GetLeftMargin();\n\tdouble mT = 1- gPad->GetTopMargin();\n\tdouble mB = gPad->GetBottomMargin();\n\n\tdouble x1, x2, y1, y2;\n\n\tif ( width <= 0 || width > 1 )\n\t\twidth = .2;\n\tif ( height <= 0 || height > 1 )\n\t\theight = .2;\n\n\t\/\/ alignment best needs a current histo\n\tif ( !(get( styling )) ){\n\t\tif ( legendAlignment::best == alignmentX )\n\t\t\talignmentX = legendAlignment::right;\n\t\tif ( legendAlignment::best == alignmentY )\n\t\t\talignmentY = legendAlignment::top;\n\t} else {\n\n\t\t\/\/TODO\n\n\t}\n\n\n\tif ( \tlegendAlignment::left == alignmentX ){\n\t\tx1 = mL ;\n\t\tx2 = mL + width;\n\t}\n\tif ( \tlegendAlignment::right == alignmentX ){\n\t\tx1 = mR - width;\n\t\tx2 = mR ;\n\t}\n\tif ( \tlegendAlignment::center == alignmentX ){\n\t\tx1 = 0.55 - width\/2.0;\n\t\tx2 = 0.55 + width\/2.0;\n\t}\n\tif ( \tlegendAlignment::top == alignmentY ){\n\t\ty1 = mT - height;\n\t\ty2 = mT ;\n\t}\n\tif ( \tlegendAlignment::bottom == alignmentY ){\n\t\ty1 = mB ;\n\t\ty2 = mB + height;\n\t}\n\tif ( \tlegendAlignment::center == alignmentY ){\n\t\ty1 = 0.55 - height\/2.0;\n\t\ty2 = 0.55 + height\/2.0;\n\t}\n\tlegend->SetX1NDC( x1 );\n\tlegend->SetX2NDC( x2 );\n\tlegend->SetY1NDC( y1 );\n\tlegend->SetY2NDC( y2 );\n\n\treturn this;\n}<commit_msg>test upstream<commit_after>\n\n#include \"histoBook.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n\n\/\/ constructor sets the name of the file for saving\nhistoBook::histoBook( string name, string input, string inDir ){\n\n\tif (name.find( \".root\") != std::string::npos){\n\t\tfilename = name;\t\n\t} else\n\t\tfilename = name + \".root\";\n\n\tcurrentDir = \"\/\";\n\n\tfile = new TFile( filename.c_str(), \"recreate\" );\n\tfile->cd();\n\n\t\n\t\/\/ make the legend and draw it once to apply styles etc. \n\t\/\/ for some reason needed to make styling work on the first draw\n\tlegend = new TLegend( 0.65, 0.65, 0.9, 0.9);\n\tlegend->SetFillColor( kWhite );\n\tlegend->Draw();\n\tlegend->Clear();\n\n\tglobalStyle();\n\n\t\/\/ if an input was given merge it into the live record\n\tif ( input.length() >= 5 ){\n\t\tTFile * fin = new TFile( input.c_str() );\n\t\tcd ( inDir );\n\t\tfin->cd( inDir.c_str() );\n\t\tloadRootDir( gDirectory, inDir );\n\t}\n\n\n\n}\n\/\/ destructor\nhistoBook::~histoBook(){\n\n\tdelete legend;\n\n\tsave();\n\tfile->Close();\n}\nvoid histoBook::save() {\n\n\tfile->Write();\n}\n\nvoid histoBook::loadRootDir( TDirectory* tDir, string path ){\n\n\t\/\/cout << \"histoBook.loadRootDir] Path : \" << path << endl;\n\n\tTList* list;\n\n\tif ( tDir ){\n\t\tlist = tDir->GetListOfKeys(); \n\t} else {\n\t\tcout << \"[histoBook.loadRootDir] Bad Directory Given \" << endl;\n\t\treturn;\n\t}\n\n\tTIter next(list); \n\tTKey* key; \n\tTObject* obj; \n\t\n\twhile ( (key = (TKey*)next()) ) { \n\t\t\n\t\tobj = key->ReadObj() ; \n\t\t\n\t\tif ( 0 == strcmp(obj->IsA()->GetName(),\"TDirectoryFile\") ){\n\t\t\tTDirectoryFile* dir = (TDirectoryFile*)obj;\n\t\t\t\n\t\t\tstring nPath = path + dir->GetName();\n\t\t\tif ( path == (string) \"\" )\n\t\t\t\tnPath = path + dir->GetName();\n\t\t\telse \n\t\t\t\tnPath = path + \"\/\" + dir->GetName();\n\n\t\t\tcd( nPath );\n\t\t\tloadRootDir( dir, nPath );\n\t\t} else if ( obj ){\n\t\t\tif ( (strcmp(obj->IsA()->GetName(),\"TProfile\")!=0) && (!obj->InheritsFrom(\"TH2\") && (!obj->InheritsFrom(\"TH1\"))) ) { \n\t\t\t\t\/\/ not a 1d or 2d histogram\n\t\t\t} else {\n\t\t\t\t\/\/ add it to the book\n\t\t\t\t\/\/cout << \"Adding : \" << obj->GetName() << endl;\n\t\t\t\tadd( obj->GetName(), (TH1*)obj->Clone( obj->GetName() ) );\n\t\t\t} \n\t\t\t\n\t\t}\n\t}\t\n\n}\n\n\nvoid histoBook::add( string name, TH1* h ){\n\n\tstring oName = name;\n\tif ( name.length() <= 1 || !h )\n\t\treturn;\n\n\tname = currentDir + name;\n\t\n\t\/\/ dont allow duplicated name overites\n\tif ( book[ name ] ){\n\t\tcout << \"[histoBook.add] Duplicate histogram name in this directory \" << currentDir << \" \/ \" << oName << endl;\n\t\treturn;\n\t}\n\n\t\/\/ save the histo to the map\n\tbook[ name ] = h;\n\n}\n\/*\n*\n* TODO:: add support for full subdirectory trees\n*\/\nstring histoBook::cd( string sdir ){\n\n\tstring old = currentDir;\n\n\tchar* csdir = (char*)sdir.c_str();\n\tfile->cd();\n\n\tif ( file->GetDirectory( csdir ) ){\n\t\tfile->cd( csdir );\n\t} else {\n\t\tcout << \"[histoBook.cd] creating directory \" << sdir << endl;\n\t\tfile->mkdir( csdir );\n\t\tfile->cd( csdir );\n\t}\n\n\tcurrentDir = sdir;\n\n\treturn old;\n}\n\nvoid histoBook::make( xmlConfig * config, string nodeName ){\n\n\tif ( config && config->nodeExists( nodeName ) ){\n\t\t\n\t\tstring hName = config->tagName( nodeName );\n\t\tif ( \"\" == hName )\n\t\t\thName = nodeName;\n\n\t\tstring type = config->getString( nodeName + \":type\", \"1D\" );\n\n\t\tif ( \"1D\" == type ){\n\t\t\tmake1D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ) );\n\n\t\t} else if ( \"2D\" == type ){\n\t\t\tmake2D( hName, config->getString( nodeName + \":title\", hName ), \n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsX\", 1 ), config->getDouble( nodeName + \":x1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":x2\", 1 ),\n\t\t\t\t\tconfig->getInt( nodeName + \":nBinsY\", 1 ), config->getDouble( nodeName + \":y1\", 0 ),\n\t\t\t\t\tconfig->getDouble( nodeName + \":y2\", 1 ) );\n\t\t} else if ( \"1F\" == type ){\n\t\t\t\/\/ test comment\n\t\t}\n\t}\n\n}\n\nvoid histoBook::make1F( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1F* h;\n\th = new TH1F( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\n\nvoid histoBook::make1D( string name, string title, uint nBins, double low, double hi ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, low, hi );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make1D( string name, string title, uint nBins, const Double_t* bins ){\n\n\tTH1D* h;\n\th = new TH1D( name.c_str(), title.c_str(), nBins, bins );\n\n\tthis->add( name, h );\n}\n\nvoid histoBook::make2D( string name, string title, uint nBinsX, double lowX, double hiX, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, lowX, hiX, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\nvoid histoBook::make2D( string name, string title, uint nBinsX, const Double_t* xBins, uint nBinsY, double lowY, double hiY ){\n\n\tTH2D* h;\n\th = new TH2D( name.c_str(), title.c_str(), nBinsX, xBins, nBinsY, lowY, hiY );\n\n\tthis->add( name, h );\n}\n\n\nTH1* histoBook::get( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn book[ ( sdir + name ) ];\n}\nTH2* histoBook::get2D( string name, string sdir ){\n\tif ( sdir.compare(\"\") == 0)\n\t\tsdir = currentDir;\n\treturn (TH2*)book[ ( sdir + name ) ];\n}\n\nvoid histoBook::fill( string name, double bin, double weight ){ \n\tif ( get( name ) != 0)\n\t\tget( name )->Fill( bin, weight );\n}\n\n\nvoid histoBook::globalStyle(){\n\n\tgStyle->SetCanvasColor(kWhite); \/\/ background is no longer mouse-dropping white\n \tgStyle->SetPalette(1,0); \/\/ blue to red false color palette. Use 9 for b\/w\n \tgStyle->SetCanvasBorderMode(0); \/\/ turn off canvas borders\n \tgStyle->SetPadBorderMode(0);\n \tgStyle->SetPaintTextFormat(\"5.2f\"); \/\/ What precision to put numbers if plotted with \"TEXT\"\n\n\n \t\/\/ For publishing:\n \tgStyle->SetLineWidth(2.);\n \tgStyle->SetTextSize(0.7);\n \tgStyle->SetLabelSize(0.05,\"xy\");\n \tgStyle->SetTitleSize(0.05,\"xy\");\n \tgStyle->SetTitleOffset(1.0,\"x\");\n \tgStyle->SetTitleOffset(1.5,\"y\");\n \tgStyle->SetPadTopMargin(0.1);\n \tgStyle->SetPadRightMargin(0.1);\n \tgStyle->SetPadBottomMargin(0.16);\n \tgStyle->SetPadLeftMargin(0.2);\n\n \tgStyle->SetFillColor(-1); \n\tgStyle->SetFillStyle(4000); \n\n\n\t\n}\n\n\nhistoBook* histoBook::style( string histName ){\n\tstyling = histName;\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, string p1, string p2, string p3, string p4 ){\n\t\n\t\/\/ force the param name to lowercase\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"title\" == param ){\n\t \th->SetTitle( p1.c_str() );\n\t } else if ( \"x\" == param ){\n\t \th->GetXaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"y\" == param ){\n\t \th->GetYaxis()->SetTitle( p1.c_str() );\n\t } else if ( \"legend\" == param ){\n\t \tif ( p2 == \"\")\n\t \t\tp2=\"lpf\";\n\t \tlegend->AddEntry( h, p1.c_str(), p2.c_str() );\n\t\t\tlegend->Draw();\n\t } else if ( \"draw\" == param ){\n\t \tdrawOption = p1;\n\t }\n\t}\n\n\treturn this;\n}\n\nhistoBook* histoBook::set( string param, double p1, double p2, double p3, double p4 ){\n\n\n\ttransform(param.begin(), param.end(), param.begin(), ::tolower);\n\n TH1* h = get( styling );\n if ( h ){\n\n\t if ( \"linecolor\" == param ){\n\n\t \th->SetLineColor( (int) p1 );\n\t } else if ( \"domain\" == param ){\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t\t h->GetXaxis()->SetRangeUser( min, max );\n\t } else if ( \"dynamicdomain\" == param ){\n\t \tdouble thresh = p1;\n\t \tint min = (int)p2;\n\t \tint max = (int)p3;\n\t \tint axis = (int)p4;\t\t\/\/ 1 = x, 2 = y\n\n\t \tif ( 1 != axis && 2 != axis )\n\t \t\taxis = 1;\n\t \t\n\t \tif ( thresh >= 0) {\n\t \t\tif ( -1 >= min )\n\t \t\t\tmin = h->FindFirstBinAbove( thresh, axis );\n\t \t\tif ( -1 >= max )\n\t \t\t\tmax = h->FindLastBinAbove( thresh, axis );\n\t \t}\n\t \t\n\t \tif ( 1 == axis )\n\t\t \t h->GetXaxis()->SetRange( min, max );\n\t\t \telse if ( 2 == axis )\n\t\t \t\th->GetYaxis()->SetRange( min, max );\n\n\t } else if ( \"range\" == param ){\n\n\t \tdouble min = p1;\n\t \tdouble max = p2;\n\t \t\n\t \th->GetYaxis()->SetRangeUser( min, max );\n\t } else if ( \"markercolor\" == param ) {\n\t \th->SetMarkerColor( (int)p1 );\n\t } else if ( \"markerstyle\" == param ) {\n\t \th->SetMarkerStyle( (int)p1 );\n\t } else if ( \"legend\" == param ){\n\t \t\/\/ p1 - alignmentX\n\t \t\/\/ p2 - alignmentY\n\t \t\/\/ p3 - width\n\t \t\/\/ p4 - height\n\n\t \t\/\/ make sure option is valid\n\t \tif ( !(legendAlignment::center == p1 || legendAlignment::left == p1 || legendAlignment::right == p1) )\n\t \t\tp1 = legendAlignment::best;\n\t \tif ( !(legendAlignment::center == p2 || legendAlignment::top == p2 || legendAlignment::bottom == p2) )\n\t \t\tp2 = legendAlignment::best;\n\t \tplaceLegend( p1, p2, p3, p4 );\n\t } else if ( \"numberofticks\" == param ){\n\t \t\/\/ p1 - # of primary divisions\n\t \t\/\/ p2 - # of secondary divisions\n\t \t\/\/ p3 - axis : 0 or 1 = x, 2 = y\n\t \t\n\t \tif ( p2 == -1 )\n\t \t\tp2 = 0;\n\n\t\t if ( 2 == (int)p3 )\n\t\t \th->GetYaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t\t else \n\t\t \th->GetXaxis()->SetNdivisions( (int) p1, (int) p2, 0, true );\n\t }\n\n }\n \n \n \n\n\n\treturn this;\n}\n\n\nhistoBook* histoBook::draw(string name, Option_t* opt ){\n\n\t\/\/ no parameters\n\tif ( name == \"\"){\n\t\tTH1* h = get( styling );\n\t\tif ( h ){\n\t\t\t\/\/ use the draw option set in its styling\n\t\t\th->Draw( drawOption.c_str() );\n\t\t\tdrawOption = \"\";\n\t\t}\t\n\t} else {\n\t\tTH1* h = get( name );\n\t\tif ( h ){\n\t\t\th->Draw( opt );\n\t\t}\n\t}\n\t\n\treturn this;\n}\n\n\nhistoBook* histoBook::placeLegend( int alignmentX, int alignmentY, double width, double height ){\n\n\tdouble mR = 1 - gPad->GetRightMargin();\n\tdouble mL = gPad->GetLeftMargin();\n\tdouble mT = 1- gPad->GetTopMargin();\n\tdouble mB = gPad->GetBottomMargin();\n\n\tdouble x1, x2, y1, y2;\n\n\tif ( width <= 0 || width > 1 )\n\t\twidth = .2;\n\tif ( height <= 0 || height > 1 )\n\t\theight = .2;\n\n\t\/\/ alignment best needs a current histo\n\tif ( !(get( styling )) ){\n\t\tif ( legendAlignment::best == alignmentX )\n\t\t\talignmentX = legendAlignment::right;\n\t\tif ( legendAlignment::best == alignmentY )\n\t\t\talignmentY = legendAlignment::top;\n\t} else {\n\n\t\t\/\/TODO\n\n\t}\n\n\n\tif ( \tlegendAlignment::left == alignmentX ){\n\t\tx1 = mL ;\n\t\tx2 = mL + width;\n\t}\n\tif ( \tlegendAlignment::right == alignmentX ){\n\t\tx1 = mR - width;\n\t\tx2 = mR ;\n\t}\n\tif ( \tlegendAlignment::center == alignmentX ){\n\t\tx1 = 0.55 - width\/2.0;\n\t\tx2 = 0.55 + width\/2.0;\n\t}\n\tif ( \tlegendAlignment::top == alignmentY ){\n\t\ty1 = mT - height;\n\t\ty2 = mT ;\n\t}\n\tif ( \tlegendAlignment::bottom == alignmentY ){\n\t\ty1 = mB ;\n\t\ty2 = mB + height;\n\t}\n\tif ( \tlegendAlignment::center == alignmentY ){\n\t\ty1 = 0.55 - height\/2.0;\n\t\ty2 = 0.55 + height\/2.0;\n\t}\n\tlegend->SetX1NDC( x1 );\n\tlegend->SetX2NDC( x2 );\n\tlegend->SetY1NDC( y1 );\n\tlegend->SetY2NDC( y2 );\n\n\treturn this;\n}<|endoftext|>"} {"text":"<commit_before>#include \"TargetCorpus.h\"\n#include <string>\n#include <stdlib.h>\n#include <cstring>\n\nvoid TargetCorpus::Create( string fileName )\n{\n ifstream textFile;\n char line[LINE_MAX_LENGTH];\n\n \/\/ count the number of words first;\n textFile.open(fileName.c_str());\n istream *fileP = &textFile;\n m_size = 0;\n m_sentenceCount = 0;\n while(!fileP->eof()) {\n SAFE_GETLINE((*fileP), line, LINE_MAX_LENGTH, '\\n');\n if (fileP->eof()) break;\n vector< WORD_ID > words = m_vcb.Tokenize( line );\n m_size += words.size();\n m_sentenceCount++;\n }\n textFile.close();\n cerr << m_size << \" words\" << endl;\n\n \/\/ allocate memory\n m_array = (WORD_ID*) calloc( sizeof( WORD_ID ), m_size );\n m_sentenceEnd = (INDEX*) calloc( sizeof( INDEX ), m_sentenceCount );\n\n \/\/ fill the array\n int wordIndex = 0;\n int sentenceId = 0;\n textFile.open(fileName.c_str());\n fileP = &textFile;\n while(!fileP->eof()) {\n SAFE_GETLINE((*fileP), line, LINE_MAX_LENGTH, '\\n');\n if (fileP->eof()) break;\n vector< WORD_ID > words = m_vcb.Tokenize( line );\n vector< WORD_ID >::const_iterator i;\n\n for( i=words.begin(); i!=words.end(); i++) {\n m_array[ wordIndex++ ] = *i;\n }\n m_sentenceEnd[ sentenceId++ ] = wordIndex-1;\n }\n textFile.close();\n cerr << \"done reading \" << wordIndex << \" words, \" << sentenceId << \" sentences.\" << endl;\n}\n\nTargetCorpus::~TargetCorpus()\n{\n free(m_array);\n free(m_sentenceEnd);\n}\n\nWORD TargetCorpus::GetWordFromId( const WORD_ID id ) const\n{\n return m_vcb.GetWord( id );\n}\n\nWORD TargetCorpus::GetWord( INDEX sentence, char word )\n{\n return m_vcb.GetWord( GetWordId( sentence, word ) );\n}\n\nWORD_ID TargetCorpus::GetWordId( INDEX sentence, char word )\n{\n if (sentence == 0) {\n return m_array[ word ];\n }\n return m_array[ m_sentenceEnd[ sentence-1 ] + 1 + word ] ;\n}\n\nchar TargetCorpus::GetSentenceLength( INDEX sentence )\n{\n if (sentence == 0) {\n return (char) m_sentenceEnd[ 0 ]+1;\n }\n return (char) ( m_sentenceEnd[ sentence ] - m_sentenceEnd[ sentence-1 ] );\n}\n\nvoid TargetCorpus::Save( string fileName )\n{\n FILE *pFile = fopen ( (fileName + \".tgt\").c_str() , \"w\" );\n\n fwrite( &m_size, sizeof(INDEX), 1, pFile );\n fwrite( m_array, sizeof(WORD_ID), m_size, pFile ); \/\/ corpus\n\n fwrite( &m_sentenceCount, sizeof(INDEX), 1, pFile );\n fwrite( m_sentenceEnd, sizeof(INDEX), m_sentenceCount, pFile); \/\/ sentence index\n fclose( pFile );\n\n m_vcb.Save( fileName + \".tgt-vcb\" );\n}\n\nvoid TargetCorpus::Load( string fileName )\n{\n FILE *pFile = fopen ( (fileName + \".tgt\").c_str() , \"r\" );\n cerr << \"loading from \" << fileName << \".tgt\" << endl;\n\n fread( &m_size, sizeof(INDEX), 1, pFile );\n cerr << \"words in corpus: \" << m_size << endl;\n m_array = (WORD_ID*) calloc( sizeof(WORD_ID), m_size );\n fread( m_array, sizeof(WORD_ID), m_size, pFile ); \/\/ corpus\n\n fread( &m_sentenceCount, sizeof(INDEX), 1, pFile );\n cerr << \"sentences in corpus: \" << m_sentenceCount << endl;\n m_sentenceEnd = (INDEX*) calloc( sizeof(INDEX), m_sentenceCount );\n fread( m_sentenceEnd, sizeof(INDEX), m_sentenceCount, pFile); \/\/ sentence index\n fclose( pFile );\n m_vcb.Load( fileName + \".tgt-vcb\" );\n}<commit_msg>minor warning<commit_after>#include \"TargetCorpus.h\"\n#include <string>\n#include <stdlib.h>\n#include <cstring>\n\nvoid TargetCorpus::Create( string fileName )\n{\n ifstream textFile;\n char line[LINE_MAX_LENGTH];\n\n \/\/ count the number of words first;\n textFile.open(fileName.c_str());\n istream *fileP = &textFile;\n m_size = 0;\n m_sentenceCount = 0;\n while(!fileP->eof()) {\n SAFE_GETLINE((*fileP), line, LINE_MAX_LENGTH, '\\n');\n if (fileP->eof()) break;\n vector< WORD_ID > words = m_vcb.Tokenize( line );\n m_size += words.size();\n m_sentenceCount++;\n }\n textFile.close();\n cerr << m_size << \" words\" << endl;\n\n \/\/ allocate memory\n m_array = (WORD_ID*) calloc( sizeof( WORD_ID ), m_size );\n m_sentenceEnd = (INDEX*) calloc( sizeof( INDEX ), m_sentenceCount );\n\n \/\/ fill the array\n int wordIndex = 0;\n int sentenceId = 0;\n textFile.open(fileName.c_str());\n fileP = &textFile;\n while(!fileP->eof()) {\n SAFE_GETLINE((*fileP), line, LINE_MAX_LENGTH, '\\n');\n if (fileP->eof()) break;\n vector< WORD_ID > words = m_vcb.Tokenize( line );\n vector< WORD_ID >::const_iterator i;\n\n for( i=words.begin(); i!=words.end(); i++) {\n m_array[ wordIndex++ ] = *i;\n }\n m_sentenceEnd[ sentenceId++ ] = wordIndex-1;\n }\n textFile.close();\n cerr << \"done reading \" << wordIndex << \" words, \" << sentenceId << \" sentences.\" << endl;\n}\n\nTargetCorpus::~TargetCorpus()\n{\n free(m_array);\n free(m_sentenceEnd);\n}\n\nWORD TargetCorpus::GetWordFromId( const WORD_ID id ) const\n{\n return m_vcb.GetWord( id );\n}\n\nWORD TargetCorpus::GetWord( INDEX sentence, char word )\n{\n return m_vcb.GetWord( GetWordId( sentence, word ) );\n}\n\nWORD_ID TargetCorpus::GetWordId( INDEX sentence, char word )\n{\n if (sentence == 0) {\n return m_array[ word ];\n }\n return m_array[ m_sentenceEnd[ sentence-1 ] + 1 + word ] ;\n}\n\nchar TargetCorpus::GetSentenceLength( INDEX sentence )\n{\n if (sentence == 0) {\n return (char) m_sentenceEnd[ 0 ]+1;\n }\n return (char) ( m_sentenceEnd[ sentence ] - m_sentenceEnd[ sentence-1 ] );\n}\n\nvoid TargetCorpus::Save( string fileName )\n{\n FILE *pFile = fopen ( (fileName + \".tgt\").c_str() , \"w\" );\n\n fwrite( &m_size, sizeof(INDEX), 1, pFile );\n fwrite( m_array, sizeof(WORD_ID), m_size, pFile ); \/\/ corpus\n\n fwrite( &m_sentenceCount, sizeof(INDEX), 1, pFile );\n fwrite( m_sentenceEnd, sizeof(INDEX), m_sentenceCount, pFile); \/\/ sentence index\n fclose( pFile );\n\n m_vcb.Save( fileName + \".tgt-vcb\" );\n}\n\nvoid TargetCorpus::Load( string fileName )\n{\n FILE *pFile = fopen ( (fileName + \".tgt\").c_str() , \"r\" );\n cerr << \"loading from \" << fileName << \".tgt\" << endl;\n\n fread( &m_size, sizeof(INDEX), 1, pFile );\n cerr << \"words in corpus: \" << m_size << endl;\n m_array = (WORD_ID*) calloc( sizeof(WORD_ID), m_size );\n fread( m_array, sizeof(WORD_ID), m_size, pFile ); \/\/ corpus\n\n fread( &m_sentenceCount, sizeof(INDEX), 1, pFile );\n cerr << \"sentences in corpus: \" << m_sentenceCount << endl;\n m_sentenceEnd = (INDEX*) calloc( sizeof(INDEX), m_sentenceCount );\n fread( m_sentenceEnd, sizeof(INDEX), m_sentenceCount, pFile); \/\/ sentence index\n fclose( pFile );\n m_vcb.Load( fileName + \".tgt-vcb\" );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n *\n * Author(s): Christopher Dyken <christopher.dyken@sintef.no>\n *\n *\n * Copyright (C) 2012 by SINTEF. All rights reserved.\n *\n ******************************************************************************\/\n#include <atomic>\n#include \"utils\/Logger.hpp\"\n#include \"ASyncReader.hpp\"\n#include \"cornerpoint\/Tessellator.hpp\"\n#include \"eclipse\/EclipseReader.hpp\"\n#include \"utils\/PerfTimer.hpp\"\n\nstatic const std::string package = \"ASyncReader\";\n\nASyncReader::ASyncReader( boost::shared_ptr<tinia::model::ExposedModel> model )\n : m_ticket_counter(1),\n m_model( model ),\n m_worker( worker, this )\n{\n Logger log = getLogger( package + \".ASyncReader\" );\n m_model->addElement<bool>( \"asyncreader_working\", false, \"Loading and preprocessing\" );\n m_model->addElement<std::string>( \"asyncreader_what\", \"Idle\" );\n m_model->addConstrainedElement<int>( \"asyncreader_progress\", 0, 0, 100, \"Progress\" );\n m_model->addElement<int>( \"asyncreader_ticket\", 0 );\n}\n\nbool\nASyncReader::issueReadProject( const std::string& file,\n const int refine_i,\n const int refine_j,\n const int refine_k,\n const bool triangulate)\n{\n Logger log = getLogger( package + \".read\" );\n Command cmd;\n cmd.m_type = Command::READ_PROJECT;\n cmd.m_project_file = file;\n cmd.m_refine_i = refine_i;\n cmd.m_refine_j = refine_j;\n cmd.m_refine_k = refine_k;\n cmd.m_triangulate = triangulate;\n postCommand( cmd );\n return true;\n}\n\nbool\nASyncReader::issueReadSolution( const dataset::Project<float>::Solution& solution_location )\n{\n Command cmd;\n cmd.m_type = Command::READ_SOLUTION;\n cmd.m_solution_location = solution_location;\n postCommand( cmd );\n return true;\n}\n\n\nbool\nASyncReader::getProject( boost::shared_ptr< dataset::Project<float> >& project,\n boost::shared_ptr< render::GridTessBridge>& tess_bridge )\n{\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n for(auto it = m_rsp_queue.begin(); it!=m_rsp_queue.end(); ++it ) {\n if( it->m_type == Response::PROJECT ) {\n project = it->m_project;\n tess_bridge = it->m_project_grid;\n m_rsp_queue.erase( it );\n return true;\n }\n }\n return false;\n}\n\nbool\nASyncReader::getSolution( boost::shared_ptr< render::GridFieldBridge >& field_bridge )\n{\n \/\/ We kill of all but the latest request of correct type\n bool found_any = false;\n std::list<Response> keep;\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n for(auto it = m_rsp_queue.begin(); it!=m_rsp_queue.end(); ++it ) {\n if( it->m_type == Response::SOLUTION ) {\n field_bridge = it->m_solution;\n found_any = true;\n }\n else {\n keep.push_back( *it );\n }\n }\n if( found_any ) {\n m_rsp_queue.swap( keep );\n return true;\n }\n else {\n return false;\n }\n}\n\n\n\nbool\nASyncReader::getCommand( Command& cmd )\n{\n std::unique_lock< std::mutex > lock( m_cmd_queue_lock );\n while( m_cmd_queue.empty() ) {\n m_cmd_queue_wait.wait( lock );\n }\n cmd = m_cmd_queue.front();\n m_cmd_queue.pop_front();\n return true;\n}\n\nvoid\nASyncReader::handleReadProject( const Command& cmd )\n{\n Logger log = getLogger( package + \".handleReadProject\" );\n m_model->updateElement<bool>( \"asyncreader_working\", true );\n try {\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Indexing files...\" );\n m_model->updateElement<int>( \"asyncreader_progress\", 0 );\n\n boost::shared_ptr< dataset::Project<float> > project( new dataset::Project<float>( cmd.m_project_file,\n cmd.m_refine_i,\n cmd.m_refine_j,\n cmd.m_refine_k ) );\n if( project->geometryType() == dataset::Project<float>::GEOMETRY_CORNERPOINT_GRID ) {\n\n boost::shared_ptr< render::GridTessBridge > tess_bridge( new render::GridTessBridge( cmd.m_triangulate ) );\n\n m_field_remap = project->fieldRemap();\n\n\n cornerpoint::Tessellator< render::GridTessBridge > tess( *tess_bridge );\n tess.tessellate( m_model,\n \"asyncreader_what\",\n \"asyncreader_progress\",\n project->nx(),\n project->ny(),\n project->nz(),\n project->nr(),\n project->cornerPointCoord(),\n project->cornerPointZCorn(),\n project->cornerPointActNum() );\n\n \/\/ organize data\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Organizing data...\" );\n m_model->updateElement<int>( \"asyncreader_progress\", 0 );\n tess_bridge->process();\n\n Response rsp;\n rsp.m_type = Response::PROJECT;\n rsp.m_project = project;\n rsp.m_project_grid = tess_bridge;\n postResponse( cmd, rsp );\n }\n else {\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Unsupported geometry type\" );\n sleep(2);\n }\n }\n catch( std::runtime_error& e ) {\n m_model->updateElement<std::string>( \"asyncreader_what\", e.what() );\n sleep(2);\n }\n m_model->updateElement<bool>( \"asyncreader_working\", false );\n}\n\nvoid\nASyncReader::handleReadSolution( const Command& cmd )\n{\n Logger log = getLogger( package + \".handleReadSolution\" );\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Reading solution...\" );\n\n Response rsp;\n rsp.m_type = Response::SOLUTION;\n if( cmd.m_solution_location.m_reader == dataset::Project<float>::READER_UNFORMATTED_ECLIPSE ) {\n\n if( !m_field_remap.empty() ) {\n rsp.m_solution.reset( new render::GridFieldBridge( m_field_remap.size() ) );\n\n std::vector<float> tmp( cmd.m_solution_location.m_location.m_unformatted_eclipse.m_size );\n eclipse::Reader reader( cmd.m_solution_location.m_path );\n reader.blockContent( tmp.data(),\n rsp.m_solution->minimum(),\n rsp.m_solution->maximum(),\n cmd.m_solution_location.m_location.m_unformatted_eclipse );\n for(size_t i=0; i<m_field_remap.size(); i++ ) {\n rsp.m_solution->values()[i] = tmp[ m_field_remap[i] ];\n }\n\n }\n else {\n rsp.m_solution.reset( new render::GridFieldBridge( cmd.m_solution_location.m_location.m_unformatted_eclipse.m_size ) );\n\n eclipse::Reader reader( cmd.m_solution_location.m_path );\n reader.blockContent( rsp.m_solution->values(),\n rsp.m_solution->minimum(),\n rsp.m_solution->maximum(),\n cmd.m_solution_location.m_location.m_unformatted_eclipse );\n }\n\n }\n else {\n LOGGER_ERROR( log, \"Unsupported solution format\" );\n }\n postResponse( cmd, rsp );\n}\n\n\nvoid\nASyncReader::worker( ASyncReader* that )\n{\n Logger log = getLogger( package + \".worker\" );\n\n bool keep_going = true;\n while( keep_going ) {\n Command cmd;\n if( that->getCommand( cmd ) ) {\n switch( cmd.m_type ) {\n case Command::READ_PROJECT:\n that->handleReadProject( cmd );\n break;\n case Command::READ_SOLUTION:\n that->handleReadSolution( cmd );\n break;\n case Command::DIE:\n keep_going = false;\n break;\n }\n }\n }\n LOGGER_DEBUG( log, \"weee!\" );\n}\n\nvoid\nASyncReader::postCommand( Command& cmd , bool wipe)\n{\n Logger log = getLogger( package + \".postCommand\" );\n std::unique_lock<std::mutex> lock( m_cmd_queue_lock );\n cmd.m_ticket = m_ticket_counter++;\n if( wipe ) {\n for(auto it=m_cmd_queue.begin(); it!=m_cmd_queue.end(); ++it ) {\n if( it->m_type == cmd.m_type ) {\n LOGGER_DEBUG( log, \"Wiped old command\" );\n *it = cmd;\n return;\n }\n }\n }\n m_cmd_queue.push_back( cmd );\n m_cmd_queue_wait.notify_one();\n}\n\nvoid\nASyncReader::postResponse( const Command& cmd, const Response& rsp )\n{\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n m_rsp_queue.push_back( rsp );\n lock.unlock();\n\n \/\/ Signal that a response is ready\n m_model->updateElement<int>( \"asyncreader_ticket\", cmd.m_ticket );\n}\n<commit_msg>Removed unused (and C++11-dependent) include<commit_after>\/******************************************************************************\n *\n * Author(s): Christopher Dyken <christopher.dyken@sintef.no>\n *\n *\n * Copyright (C) 2012 by SINTEF. All rights reserved.\n *\n ******************************************************************************\/\n#include \"utils\/Logger.hpp\"\n#include \"ASyncReader.hpp\"\n#include \"cornerpoint\/Tessellator.hpp\"\n#include \"eclipse\/EclipseReader.hpp\"\n#include \"utils\/PerfTimer.hpp\"\n\nstatic const std::string package = \"ASyncReader\";\n\nASyncReader::ASyncReader( boost::shared_ptr<tinia::model::ExposedModel> model )\n : m_ticket_counter(1),\n m_model( model ),\n m_worker( worker, this )\n{\n Logger log = getLogger( package + \".ASyncReader\" );\n m_model->addElement<bool>( \"asyncreader_working\", false, \"Loading and preprocessing\" );\n m_model->addElement<std::string>( \"asyncreader_what\", \"Idle\" );\n m_model->addConstrainedElement<int>( \"asyncreader_progress\", 0, 0, 100, \"Progress\" );\n m_model->addElement<int>( \"asyncreader_ticket\", 0 );\n}\n\nbool\nASyncReader::issueReadProject( const std::string& file,\n const int refine_i,\n const int refine_j,\n const int refine_k,\n const bool triangulate)\n{\n Logger log = getLogger( package + \".read\" );\n Command cmd;\n cmd.m_type = Command::READ_PROJECT;\n cmd.m_project_file = file;\n cmd.m_refine_i = refine_i;\n cmd.m_refine_j = refine_j;\n cmd.m_refine_k = refine_k;\n cmd.m_triangulate = triangulate;\n postCommand( cmd );\n return true;\n}\n\nbool\nASyncReader::issueReadSolution( const dataset::Project<float>::Solution& solution_location )\n{\n Command cmd;\n cmd.m_type = Command::READ_SOLUTION;\n cmd.m_solution_location = solution_location;\n postCommand( cmd );\n return true;\n}\n\n\nbool\nASyncReader::getProject( boost::shared_ptr< dataset::Project<float> >& project,\n boost::shared_ptr< render::GridTessBridge>& tess_bridge )\n{\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n for(auto it = m_rsp_queue.begin(); it!=m_rsp_queue.end(); ++it ) {\n if( it->m_type == Response::PROJECT ) {\n project = it->m_project;\n tess_bridge = it->m_project_grid;\n m_rsp_queue.erase( it );\n return true;\n }\n }\n return false;\n}\n\nbool\nASyncReader::getSolution( boost::shared_ptr< render::GridFieldBridge >& field_bridge )\n{\n \/\/ We kill of all but the latest request of correct type\n bool found_any = false;\n std::list<Response> keep;\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n for(auto it = m_rsp_queue.begin(); it!=m_rsp_queue.end(); ++it ) {\n if( it->m_type == Response::SOLUTION ) {\n field_bridge = it->m_solution;\n found_any = true;\n }\n else {\n keep.push_back( *it );\n }\n }\n if( found_any ) {\n m_rsp_queue.swap( keep );\n return true;\n }\n else {\n return false;\n }\n}\n\n\n\nbool\nASyncReader::getCommand( Command& cmd )\n{\n std::unique_lock< std::mutex > lock( m_cmd_queue_lock );\n while( m_cmd_queue.empty() ) {\n m_cmd_queue_wait.wait( lock );\n }\n cmd = m_cmd_queue.front();\n m_cmd_queue.pop_front();\n return true;\n}\n\nvoid\nASyncReader::handleReadProject( const Command& cmd )\n{\n Logger log = getLogger( package + \".handleReadProject\" );\n m_model->updateElement<bool>( \"asyncreader_working\", true );\n try {\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Indexing files...\" );\n m_model->updateElement<int>( \"asyncreader_progress\", 0 );\n\n boost::shared_ptr< dataset::Project<float> > project( new dataset::Project<float>( cmd.m_project_file,\n cmd.m_refine_i,\n cmd.m_refine_j,\n cmd.m_refine_k ) );\n if( project->geometryType() == dataset::Project<float>::GEOMETRY_CORNERPOINT_GRID ) {\n\n boost::shared_ptr< render::GridTessBridge > tess_bridge( new render::GridTessBridge( cmd.m_triangulate ) );\n\n m_field_remap = project->fieldRemap();\n\n\n cornerpoint::Tessellator< render::GridTessBridge > tess( *tess_bridge );\n tess.tessellate( m_model,\n \"asyncreader_what\",\n \"asyncreader_progress\",\n project->nx(),\n project->ny(),\n project->nz(),\n project->nr(),\n project->cornerPointCoord(),\n project->cornerPointZCorn(),\n project->cornerPointActNum() );\n\n \/\/ organize data\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Organizing data...\" );\n m_model->updateElement<int>( \"asyncreader_progress\", 0 );\n tess_bridge->process();\n\n Response rsp;\n rsp.m_type = Response::PROJECT;\n rsp.m_project = project;\n rsp.m_project_grid = tess_bridge;\n postResponse( cmd, rsp );\n }\n else {\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Unsupported geometry type\" );\n sleep(2);\n }\n }\n catch( std::runtime_error& e ) {\n m_model->updateElement<std::string>( \"asyncreader_what\", e.what() );\n sleep(2);\n }\n m_model->updateElement<bool>( \"asyncreader_working\", false );\n}\n\nvoid\nASyncReader::handleReadSolution( const Command& cmd )\n{\n Logger log = getLogger( package + \".handleReadSolution\" );\n m_model->updateElement<std::string>( \"asyncreader_what\", \"Reading solution...\" );\n\n Response rsp;\n rsp.m_type = Response::SOLUTION;\n if( cmd.m_solution_location.m_reader == dataset::Project<float>::READER_UNFORMATTED_ECLIPSE ) {\n\n if( !m_field_remap.empty() ) {\n rsp.m_solution.reset( new render::GridFieldBridge( m_field_remap.size() ) );\n\n std::vector<float> tmp( cmd.m_solution_location.m_location.m_unformatted_eclipse.m_size );\n eclipse::Reader reader( cmd.m_solution_location.m_path );\n reader.blockContent( tmp.data(),\n rsp.m_solution->minimum(),\n rsp.m_solution->maximum(),\n cmd.m_solution_location.m_location.m_unformatted_eclipse );\n for(size_t i=0; i<m_field_remap.size(); i++ ) {\n rsp.m_solution->values()[i] = tmp[ m_field_remap[i] ];\n }\n\n }\n else {\n rsp.m_solution.reset( new render::GridFieldBridge( cmd.m_solution_location.m_location.m_unformatted_eclipse.m_size ) );\n\n eclipse::Reader reader( cmd.m_solution_location.m_path );\n reader.blockContent( rsp.m_solution->values(),\n rsp.m_solution->minimum(),\n rsp.m_solution->maximum(),\n cmd.m_solution_location.m_location.m_unformatted_eclipse );\n }\n\n }\n else {\n LOGGER_ERROR( log, \"Unsupported solution format\" );\n }\n postResponse( cmd, rsp );\n}\n\n\nvoid\nASyncReader::worker( ASyncReader* that )\n{\n Logger log = getLogger( package + \".worker\" );\n\n bool keep_going = true;\n while( keep_going ) {\n Command cmd;\n if( that->getCommand( cmd ) ) {\n switch( cmd.m_type ) {\n case Command::READ_PROJECT:\n that->handleReadProject( cmd );\n break;\n case Command::READ_SOLUTION:\n that->handleReadSolution( cmd );\n break;\n case Command::DIE:\n keep_going = false;\n break;\n }\n }\n }\n LOGGER_DEBUG( log, \"weee!\" );\n}\n\nvoid\nASyncReader::postCommand( Command& cmd , bool wipe)\n{\n Logger log = getLogger( package + \".postCommand\" );\n std::unique_lock<std::mutex> lock( m_cmd_queue_lock );\n cmd.m_ticket = m_ticket_counter++;\n if( wipe ) {\n for(auto it=m_cmd_queue.begin(); it!=m_cmd_queue.end(); ++it ) {\n if( it->m_type == cmd.m_type ) {\n LOGGER_DEBUG( log, \"Wiped old command\" );\n *it = cmd;\n return;\n }\n }\n }\n m_cmd_queue.push_back( cmd );\n m_cmd_queue_wait.notify_one();\n}\n\nvoid\nASyncReader::postResponse( const Command& cmd, const Response& rsp )\n{\n std::unique_lock<std::mutex> lock( m_rsp_queue_lock );\n m_rsp_queue.push_back( rsp );\n lock.unlock();\n\n \/\/ Signal that a response is ready\n m_model->updateElement<int>( \"asyncreader_ticket\", cmd.m_ticket );\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SSL_CONNECTION_H\n#define _SSL_CONNECTION_H\n\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n\n#include <string>\n\n#include <openssl\/ssl.h>\n#include <openssl\/err.h>\n\n#include \".\/plain_connection.hpp\"\n\nnamespace SSLWrapper {\n\n\tclass SSLConnection : public PlainConnection {\n\n\t\tclass _ssl_init_object {\n\t\t public:\n\t\t\t_ssl_init_object() {\n\t\t\t\tSSL_load_error_strings();\n\t\t\t\tSSL_library_init();\n\t\t\t}\n\t\t\t~_ssl_init_object() {\n\t\t\t\tERR_remove_thread_state(nullptr);\n\t\t\t\tERR_free_strings();\n\t\t\t\tEVP_cleanup();\n\t\t\t\tCRYPTO_cleanup_all_ex_data();\n\t\t\t\tsk_SSL_COMP_free(SSL_COMP_get_compression_methods());\n\t\t\t}\n\t\t};\n\n\t\tSSL_CTX *ssl_context;\n\t\tSSL *ssl_handle;\n\n\tpublic:\n\n\t\tSSLConnection(const std::string& host , const int& port);\n\t\t~SSLConnection();\n\n\t\tbool do_connect(void);\n\t\tvoid disconnect(void);\n\n\t\tstd::string receive(void);\n\t\tint send(const std::string& msg);\n\n\t\tbool is_connected(void) {\n\t\t\treturn PlainConnection::is_connected();\n\t\t}\n\n\t\tbool is_secure(void) {\n\t\t\treturn true;\n\t\t}\n\n\t\tbool operator==(SSLConnection& other) const {\n\t\t\treturn false;\n\t\t}\n\n\t};\n\n};\n\n#endif\n<commit_msg>document connections<commit_after>#ifndef _SSL_CONNECTION_H\n#define _SSL_CONNECTION_H\n\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n\n#include <string>\n\n#include <openssl\/ssl.h>\n#include <openssl\/err.h>\n\n#include \".\/plain_connection.hpp\"\n\n\/*\n\tIf you're reading this, get ready for headaches. This is OpenSSL stuff.\n*\/\n\nnamespace SSLWrapper {\n\n\tclass SSLConnection : public PlainConnection {\n\n\t\tclass _ssl_init_object {\n\t\t public:\n\t\t\t_ssl_init_object() {\n\t\t\t\tSSL_load_error_strings();\n\t\t\t\tSSL_library_init();\n\t\t\t}\n\t\t\t~_ssl_init_object() {\n\t\t\t\tERR_remove_thread_state(nullptr);\n\t\t\t\tERR_free_strings();\n\t\t\t\tEVP_cleanup();\n\t\t\t\tCRYPTO_cleanup_all_ex_data();\n\t\t\t\tsk_SSL_COMP_free(SSL_COMP_get_compression_methods());\n\t\t\t}\n\t\t};\n\n\t\tSSL_CTX *ssl_context;\n\t\tSSL *ssl_handle;\n\n\tpublic:\n\n\t\tSSLConnection(const std::string& host , const int& port);\n\t\t~SSLConnection();\n\n\t\tbool do_connect(void);\n\t\tvoid disconnect(void);\n\n\t\tstd::string receive(void);\n\t\tint send(const std::string& msg);\n\n\t\tbool is_connected(void) {\n\t\t\treturn PlainConnection::is_connected();\n\t\t}\n\n\t\tbool is_secure(void) {\n\t\t\treturn true;\n\t\t}\n\n\t\t\/* since copy-constructors are deleted, symmetry is the only measure of equality. *\/\n\t\tbool operator==(SSLConnection& other) const {\n\t\t\treturn this == &other;\n\t\t}\n\n\t};\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ DiskCopy42.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 02\/06\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"DiskCopy42.hpp\"\n\n#include \"..\/..\/Track\/PCMTrack.hpp\"\n#include \"..\/..\/Encodings\/AppleGCR\/Encoder.hpp\"\n\n\/*\n\tFile format specifications as referenced below are largely\n\tsourced from the documentation at\n\thttps:\/\/wiki.68kmla.org\/DiskCopy_4.2_format_specification\n*\/\n\nusing namespace Storage::Disk;\n\nDiskCopy42::DiskCopy42(const std::string &file_name) :\n\tfile_(file_name) {\n\n\t\/\/ File format starts with 64 bytes dedicated to the disk name;\n\t\/\/ this is a Pascal-style string though there is apparently a\n\t\/\/ bug in one version of Disk Copy that can cause the length to\n\t\/\/ be one too high.\n\t\/\/\n\t\/\/ Validate the length, then skip the rest of the string.\n\tconst auto name_length = file_.get8();\n\tif(name_length > 64)\n\t\tthrow Error::InvalidFormat;\n\n\t\/\/ Get the length of the data and tag blocks.\n\tfile_.seek(64, SEEK_SET);\n\tconst auto data_block_length = file_.get32be();\n\tconst auto tag_block_length = file_.get32be();\n\tconst auto data_checksum = file_.get32be();\n\tconst auto tag_checksum = file_.get32be();\n\n\t\/\/ Don't continue with no data.\n\tif(!data_block_length)\n\t\tthrow Error::InvalidFormat;\n\n\t\/\/ Check that this is a comprehensible disk encoding.\n\tconst auto encoding = file_.get8();\n\tswitch(encoding) {\n\t\tdefault: throw Error::InvalidFormat;\n\n\t\tcase 0:\tencoding_ = Encoding::GCR400;\tbreak;\n\t\tcase 1:\tencoding_ = Encoding::GCR800;\tbreak;\n\t\tcase 2:\tencoding_ = Encoding::MFM720;\tbreak;\n\t\tcase 3:\tencoding_ = Encoding::MFM1440;\tbreak;\n\t}\n\tformat_ = file_.get8();\n\n\t\/\/ Check the magic number.\n\tconst auto magic_number = file_.get16be();\n\tif(magic_number != 0x0100)\n\t\tthrow Error::InvalidFormat;\n\n\t\/\/ Read the data and tags, and verify that enough data\n\t\/\/ was present.\n\tdata_ = file_.read(data_block_length);\n\ttags_ = file_.read(tag_block_length);\n\n\tif(data_.size() != data_block_length || tags_.size() != tag_block_length)\n\t\tthrow Error::InvalidFormat;\n\n\t\/\/ Verify the two checksums.\n\tconst auto computed_data_checksum = checksum(data_);\n\tconst auto computed_tag_checksum = checksum(tags_, 12);\n\n\tif(computed_tag_checksum != tag_checksum || computed_data_checksum != data_checksum)\n\t\tthrow Error::InvalidFormat;\n}\n\nuint32_t DiskCopy42::checksum(const std::vector<uint8_t> &data, size_t bytes_to_skip) {\n\tuint32_t result = 0;\n\n\t\/\/ Checksum algorith is: take each two bytes as a big-endian word; add that to a\n\t\/\/ 32-bit accumulator and then rotate the accumulator right one position.\n\tfor(size_t c = bytes_to_skip; c < data.size(); c += 2) {\n\t\tconst uint16_t next_word = uint16_t((data[c] << 8) | data[c+1]);\n\t\tresult += next_word;\n\t\tresult = (result >> 1) | (result << 31);\n\t}\n\n\treturn result;\n}\n\nHeadPosition DiskCopy42::get_maximum_head_position() {\n\treturn HeadPosition(80);\n}\n\nint DiskCopy42::get_head_count() {\n\t\/\/ Bit 5 in the format field indicates whether this disk is double\n\t\/\/ sided, regardless of whether it is GCR or MFM.\n\treturn 1 + ((format_ & 0x20) >> 5);\n}\n\nbool DiskCopy42::get_is_read_only() {\n\treturn true;\n}\n\nstd::shared_ptr<::Storage::Disk::Track> DiskCopy42::get_track_at_position(::Storage::Disk::Track::Address address) {\n\t\/*\n\t\tThe format_ byte has the following meanings:\n\n\t\tGCR:\n\t\t\tThis byte appears on disk as the GCR format nibble in every sector tag.\n\t\t\tThe low five bits are an interleave factor, either:\n\n\t\t\t\t'2' for 0 8 1 9 2 10 3 11 4 12 5 13 6 14 7 15; or\n\t\t\t\t'4' for 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15.\n\n\t\t\tBit 5 indicates double sided or not.\n\n\t\tMFM:\n\t\t\tThe low five bits provide sector size as a multiple of 256 bytes.\n\t\t\tBit 5 indicates double sided or not.\n\t*\/\n\n\tif(encoding_ == Encoding::GCR400 || encoding_ == Encoding::GCR800) {\n\t\t\/\/ Perform a GCR encoding.\n\t\tconst auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(address.position.as_int());\n\t\tconst size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * address.head);\n\n\t\tif(start_sector*512 >= data_.size()) return nullptr;\n\n\t\tuint8_t *sector = &data_[512 * start_sector];\n\t\tuint8_t *tags = tags_.size() ? nullptr : &tags_[12 * start_sector];\n\n\t\tStorage::Disk::PCMSegment segment;\n\t\tsegment += Encodings::AppleGCR::six_and_two_sync(24);\n\n\t\tfor(int c = 0; c < included_sectors.length; ++c) {\n\/\/\t\t\tconst int interleave_scale = ((format_ & 0x1f) == 4) ? 8 : 4;\n\t\t\tuint8_t sector_id = uint8_t(c);\/\/uint8_t((c == included_sectors.length - 1) ? c : (c * interleave_scale)%included_sectors.length);\n\n\t\t\tuint8_t sector_plus_tags[524];\n\n\t\t\t\/\/ Copy in the tags, if provided; otherwise generate them.\n\t\t\tif(tags) {\n\t\t\t\tmemcpy(sector_plus_tags, tags, 12);\n\t\t\t\ttags += 12;\n\t\t\t} else {\n\t\t\t\t\/\/ TODO: fill in tags properly.\n\t\t\t\tmemset(sector_plus_tags, 0, 12);\n\t\t\t}\n\n\t\t\t\/\/ Copy in the sector body.\n\t\t\tmemcpy(§or_plus_tags[12], sector, 512);\n\t\t\tsector += 512;\n\n\t\t\t\/\/ NB: sync lengths below are identical to those for\n\t\t\t\/\/ the Apple II, as I have no idea whatsoever what they\n\t\t\t\/\/ should be.\n\n\t\t\tsegment += Encodings::AppleGCR::Macintosh::header(\n\t\t\t\tformat_,\n\t\t\t\tuint8_t(address.position.as_int()),\n\t\t\t\tsector_id,\n\t\t\t\t!!address.head\n\t\t\t);\n\t\t\tsegment += Encodings::AppleGCR::six_and_two_sync(7);\n\t\t\tsegment += Encodings::AppleGCR::Macintosh::data(sector_id, sector_plus_tags);\n\t\t\tsegment += Encodings::AppleGCR::six_and_two_sync(20);\n\t\t}\n\n\t\t\/\/ TODO: is there inter-track skew?\n\n\t\treturn std::make_shared<PCMTrack>(segment);\n\t}\n\n\treturn nullptr;\n}\n<commit_msg>Adds support for raw sector dumps.<commit_after>\/\/\n\/\/ DiskCopy42.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 02\/06\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"DiskCopy42.hpp\"\n\n#include \"..\/..\/Track\/PCMTrack.hpp\"\n#include \"..\/..\/Encodings\/AppleGCR\/Encoder.hpp\"\n\n\/*\n\tFile format specifications as referenced below are largely\n\tsourced from the documentation at\n\thttps:\/\/wiki.68kmla.org\/DiskCopy_4.2_format_specification\n*\/\n\nusing namespace Storage::Disk;\n\nDiskCopy42::DiskCopy42(const std::string &file_name) :\n\tfile_(file_name) {\n\n\t\/\/ Test 1: is this a raw secctor dump? If so it'll start with\n\t\/\/ the magic word 0x4C4B6000 (big endian) and be exactly\n\t\/\/ 819,200 bytes long if double sided, or 409,600 bytes if\n\t\/\/ single sided.\n\t\/\/\n\t\/\/ Luckily, 0x4c is an invalid string length for the proper\n\t\/\/ DiskCopy 4.2 format, so there's no ambiguity here.\n\n\t\/\/ File format starts with 64 bytes dedicated to the disk name;\n\t\/\/ this is a Pascal-style string though there is apparently a\n\t\/\/ bug in one version of Disk Copy that can cause the length to\n\t\/\/ be one too high.\n\t\/\/\n\t\/\/ Validate the length, then skip the rest of the string.\n\tconst auto name_length = file_.get8();\n\tif(name_length == 0x4c) {\n\t\tif(file_.stats().st_size != 819200 && file_.stats().st_size != 409600)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\tuint32_t magic_word = file_.get24be();\n\t\tif(magic_word != 0x4b6000)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\tfile_.seek(0, SEEK_SET);\n\t\tif(file_.stats().st_size == 819200) {\n\t\t\tencoding_ = Encoding::GCR800;\n\t\t\tformat_ = 0x22;\n\t\t\tdata_ = file_.read(819200);\n\t\t} else {\n\t\t\tencoding_ = Encoding::GCR400;\n\t\t\tformat_ = 0x2;\n\t\t\tdata_ = file_.read(409600);\n\t\t}\n\t} else {\n\t\tif(name_length > 64)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\t\/\/ Get the length of the data and tag blocks.\n\t\tfile_.seek(64, SEEK_SET);\n\t\tconst auto data_block_length = file_.get32be();\n\t\tconst auto tag_block_length = file_.get32be();\n\t\tconst auto data_checksum = file_.get32be();\n\t\tconst auto tag_checksum = file_.get32be();\n\n\t\t\/\/ Don't continue with no data.\n\t\tif(!data_block_length)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\t\/\/ Check that this is a comprehensible disk encoding.\n\t\tconst auto encoding = file_.get8();\n\t\tswitch(encoding) {\n\t\t\tdefault: throw Error::InvalidFormat;\n\n\t\t\tcase 0:\tencoding_ = Encoding::GCR400;\tbreak;\n\t\t\tcase 1:\tencoding_ = Encoding::GCR800;\tbreak;\n\t\t\tcase 2:\tencoding_ = Encoding::MFM720;\tbreak;\n\t\t\tcase 3:\tencoding_ = Encoding::MFM1440;\tbreak;\n\t\t}\n\t\tformat_ = file_.get8();\n\n\t\t\/\/ Check the magic number.\n\t\tconst auto magic_number = file_.get16be();\n\t\tif(magic_number != 0x0100)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\t\/\/ Read the data and tags, and verify that enough data\n\t\t\/\/ was present.\n\t\tdata_ = file_.read(data_block_length);\n\t\ttags_ = file_.read(tag_block_length);\n\n\t\tif(data_.size() != data_block_length || tags_.size() != tag_block_length)\n\t\t\tthrow Error::InvalidFormat;\n\n\t\t\/\/ Verify the two checksums.\n\t\tconst auto computed_data_checksum = checksum(data_);\n\t\tconst auto computed_tag_checksum = checksum(tags_, 12);\n\n\t\tif(computed_tag_checksum != tag_checksum || computed_data_checksum != data_checksum)\n\t\t\tthrow Error::InvalidFormat;\n\t}\n}\n\nuint32_t DiskCopy42::checksum(const std::vector<uint8_t> &data, size_t bytes_to_skip) {\n\tuint32_t result = 0;\n\n\t\/\/ Checksum algorith is: take each two bytes as a big-endian word; add that to a\n\t\/\/ 32-bit accumulator and then rotate the accumulator right one position.\n\tfor(size_t c = bytes_to_skip; c < data.size(); c += 2) {\n\t\tconst uint16_t next_word = uint16_t((data[c] << 8) | data[c+1]);\n\t\tresult += next_word;\n\t\tresult = (result >> 1) | (result << 31);\n\t}\n\n\treturn result;\n}\n\nHeadPosition DiskCopy42::get_maximum_head_position() {\n\treturn HeadPosition(80);\n}\n\nint DiskCopy42::get_head_count() {\n\t\/\/ Bit 5 in the format field indicates whether this disk is double\n\t\/\/ sided, regardless of whether it is GCR or MFM.\n\treturn 1 + ((format_ & 0x20) >> 5);\n}\n\nbool DiskCopy42::get_is_read_only() {\n\treturn true;\n}\n\nstd::shared_ptr<::Storage::Disk::Track> DiskCopy42::get_track_at_position(::Storage::Disk::Track::Address address) {\n\t\/*\n\t\tThe format_ byte has the following meanings:\n\n\t\tGCR:\n\t\t\tThis byte appears on disk as the GCR format nibble in every sector tag.\n\t\t\tThe low five bits are an interleave factor, either:\n\n\t\t\t\t'2' for 0 8 1 9 2 10 3 11 4 12 5 13 6 14 7 15; or\n\t\t\t\t'4' for 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15.\n\n\t\t\tBit 5 indicates double sided or not.\n\n\t\tMFM:\n\t\t\tThe low five bits provide sector size as a multiple of 256 bytes.\n\t\t\tBit 5 indicates double sided or not.\n\t*\/\n\n\tif(encoding_ == Encoding::GCR400 || encoding_ == Encoding::GCR800) {\n\t\t\/\/ Perform a GCR encoding.\n\t\tconst auto included_sectors = Storage::Encodings::AppleGCR::Macintosh::sectors_in_track(address.position.as_int());\n\t\tconst size_t start_sector = size_t(included_sectors.start * get_head_count() + included_sectors.length * address.head);\n\n\t\tif(start_sector*512 >= data_.size()) return nullptr;\n\n\t\tuint8_t *sector = &data_[512 * start_sector];\n\t\tuint8_t *tags = tags_.size() ? &tags_[12 * start_sector] : nullptr;\n\n\t\tStorage::Disk::PCMSegment segment;\n\t\tsegment += Encodings::AppleGCR::six_and_two_sync(24);\n\n\t\tfor(int c = 0; c < included_sectors.length; ++c) {\n\/\/\t\t\tconst int interleave_scale = ((format_ & 0x1f) == 4) ? 8 : 4;\n\t\t\tuint8_t sector_id = uint8_t(c);\/\/uint8_t((c == included_sectors.length - 1) ? c : (c * interleave_scale)%included_sectors.length);\n\n\t\t\tuint8_t sector_plus_tags[524];\n\n\t\t\t\/\/ Copy in the tags, if provided; otherwise generate them.\n\t\t\tif(tags) {\n\t\t\t\tmemcpy(sector_plus_tags, tags, 12);\n\t\t\t\ttags += 12;\n\t\t\t} else {\n\t\t\t\t\/\/ TODO: fill in tags properly.\n\t\t\t\tmemset(sector_plus_tags, 0, 12);\n\t\t\t}\n\n\t\t\t\/\/ Copy in the sector body.\n\t\t\tmemcpy(§or_plus_tags[12], sector, 512);\n\t\t\tsector += 512;\n\n\t\t\t\/\/ NB: sync lengths below are identical to those for\n\t\t\t\/\/ the Apple II, as I have no idea whatsoever what they\n\t\t\t\/\/ should be.\n\n\t\t\tsegment += Encodings::AppleGCR::Macintosh::header(\n\t\t\t\tformat_,\n\t\t\t\tuint8_t(address.position.as_int()),\n\t\t\t\tsector_id,\n\t\t\t\t!!address.head\n\t\t\t);\n\t\t\tsegment += Encodings::AppleGCR::six_and_two_sync(7);\n\t\t\tsegment += Encodings::AppleGCR::Macintosh::data(sector_id, sector_plus_tags);\n\t\t\tsegment += Encodings::AppleGCR::six_and_two_sync(20);\n\t\t}\n\n\t\t\/\/ TODO: is there inter-track skew?\n\n\t\treturn std::make_shared<PCMTrack>(segment);\n\t}\n\n\treturn nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ guaranteed_minimum_withdrawal_benefit.cpp\n\/\/ -----------------------------------------\n\/\/\n\/\/ Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an\n\/\/ implicit, impulse control formulation.\n\/\/\n\/\/ Author: Parsiad Azimzadeh\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <QuantPDE\/Core>\n#include <QuantPDE\/Modules\/Lambdas>\n#include <QuantPDE\/Modules\/Operators>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <algorithm> \/\/ max, min\n#include <iostream> \/\/ cout\n#include <numeric> \/\/ accumulate\n#include <tuple> \/\/ get\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace QuantPDE;\nusing namespace QuantPDE::Modules;\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Withdrawal final : public ControlledLinearSystem2 {\n\n\tstatic constexpr Real epsilon = 1e-12;\n\n\tRectilinearGrid2 &grid;\n\tNoncontrollable2 contractRate, kappa;\n\n\tControllable2 control;\n\npublic:\n\n\ttemplate <typename G, typename F1, typename F2>\n\tWithdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :\n\t\tgrid(grid),\n\t\tcontractRate(contractRate),\n\t\tkappa(kappa),\n\t\tcontrol( Control2(grid) )\n\t{\n\t\tregisterControl( control );\n\t}\n\n\tvirtual Matrix A(Real t) {\n\t\tMatrix M(grid.size(), grid.size());\n\t\tM.reserve(IntegerVector::Constant(grid.size(), 4));\n\n\t\tIndex i = 0;\n\t\tfor(auto node : grid) {\n\t\t\tconst Real S = node[0]; \/\/ Investment\n\t\t\tconst Real W = node[1]; \/\/ Withdrawal\n\n\t\t\tconst Real lambda = control(t, S, W); \/\/ Control\n\n\t\t\t\/\/ Interpolation data\n\t\t\tauto data = interpolationData<2>(\n\t\t\t\tgrid,\n\t\t\t\t{\n\t\t\t\t\tmax(S - lambda * W, 0.),\n\t\t\t\t\t(1 - lambda) * W\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tconst Index i0 = get<0>( data[0] );\n\t\t\tconst Index i1 = get<0>( data[1] );\n\t\t\tconst Real w0 = get<1>( data[0] );\n\t\t\tconst Real w1 = get<1>( data[1] );\n\n\t\t\tconst Index j = grid.index(i0, i1);\n\n\t\t\tM.insert(i, j ) = w0 * w1 ;\n\t\t\tM.insert(i, j + grid[0].size()) = w0 * (1-w1);\n\t\t\tM.insert(i, j + 1 ) = (1-w0) * w1 ;\n\t\t\tM.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);\n\n\t\t\t++i;\n\t\t}\n\n\t\tM.makeCompressed();\n\t\treturn grid.identity() - M;\n\t}\n\n\tvirtual Vector b(Real t) {\n\t\tVector b( grid.vector() );\n\t\tfor(auto node : accessor(grid, b)) {\n\t\t\tconst Real S = (&node)[0]; \/\/ Investment\n\t\t\tconst Real W = (&node)[1]; \/\/ Withdrawal\n\n\t\t\t\/\/std::cout << S << \", \" << W << \": \";\n\n\t\t\t\/\/ You have no money :(\n\t\t\tif(W <= epsilon) {\n\t\t\t\t*node = 0. - epsilon;\n\t\t\t\t\/\/std::cout << \"cashflow=\" << *node << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Control\n\t\t\tconst Real lambda = control(t, S, W);\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\tconst Real lambdaW = lambda * W;\n\n\t\t\t\/\/ Withdrawal at no penalty\n\t\t\tif( lambda < min(Gdt \/ W, 1.) ) {\n\t\t\t\t*node = lambdaW - epsilon;\n\t\t\t\t\/\/std::cout << \"cashflow=\" << *node << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at a penalty\n\t\t\t*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt)\n\t\t\t\t\t- epsilon;\n\t\t\t\/\/std::cout << \"cashflow=\" << *node << std::endl;\n\n\t\t}\n\n\t\treturn b;\n\t}\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main() {\n\n\tint n = 10; \/\/ Optimal control partition size\n\tint N = 100; \/\/ Number of timesteps\n\n\tReal T = 10.;\n\tReal r = .05;\n\tReal v = .20;\n\n\tReal alpha = 0.; \/\/ Hedging fee\n\n\tReal G = 10.; \/\/ Contract rate\n\tReal kappa = 0.1; \/\/ Penalty rate\n\n\tint refinement = 2;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Solution grid\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tRectilinearGrid2 grid(\n\t\tAxis {\n\t\t\t0., 5., 10., 15., 20., 25.,\n\t\t\t30., 35., 40., 45.,\n\t\t\t50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,\n\t\t\t86., 88., 90., 91., 92., 93., 94., 95.,\n\t\t\t96., 97., 98., 99., 100.,\n\t\t\t101., 102., 103., 104., 105., 106.,\n\t\t\t107., 108., 109., 110., 112., 114.,\n\t\t\t116., 118., 120., 123., 126.,\n\t\t\t130., 135., 140., 145., 150., 160., 175., 200., 225.,\n\t\t\t250., 300., 500., 750., 1000.\n\t\t},\n\t\tAxis::range(0., 2., 200.)\n\t);\n\n\tunsigned pow2l = 1; \/\/ 2^l\n\tfor(int l = 0; l < refinement; ++l) {\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Control grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/ Control partition 0 : 1\/n : 1 (MATLAB notation)\n\t\tRectilinearGrid1 controls( Axis::range(0, 1. \/ (n * pow2l), 1) );\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Iteration tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tReverseConstantStepper stepper(\n\t\t\t0., \/\/ Initial time\n\t\t\tT, \/\/ Expiry time\n\t\t\tT \/ (N * pow2l) \/\/ Timestep size\n\t\t);\n\t\tToleranceIteration tolerance;\n\t\tstepper.setInnerIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Linear system tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBlackScholes<2, 0> bs(grid, r, v, alpha);\n\t\tReverseLinearBDFTwo bdf(grid, bs);\n\t\tbdf.setIteration(stepper);\n\n\t\tWithdrawal impulse(grid, G * T \/ (N * pow2l), kappa);\n\t\tMinPolicyIteration2_1 policy(grid, controls, impulse);\n\n\t\tPenaltyMethod penalty(grid, bdf, policy);\n\n\t\t\/\/ TODO: It currently matters what order each linear system is\n\t\t\/\/ associated with an iteration; fix this.\n\n\t\tpenalty.setIteration(tolerance);\n\t\tpolicy.setIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Payoff\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tFunction2 payoff = [=] (Real S, Real W) {\n\t\t\treturn max(S, (1 - kappa) * W);\n\t\t};\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Running\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBiCGSTABSolver solver;\n\n\t\tauto V = stepper.solve(\n\t\t\tgrid, \/\/ Domain\n\t\t\tpayoff, \/\/ Initial condition\n\t\t\tpenalty, \/\/ Root of linear system tree\n\t\t\tsolver \/\/ Linear system solver\n\t\t);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Print solution\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tRectilinearGrid2 printGrid(\n\t\t\tAxis::range(0., 25., 200.),\n\t\t\tAxis::range(0., 25., 200.)\n\t\t);\n\t\tcout << accessor( printGrid, V );\n\n\t\tcout << endl;\n\n\t\tauto its = tolerance.iterations();\n\t\tReal inner = accumulate(its.begin(), its.end(), 0.)\/its.size();\n\n\t\tcout << \"average number of inner iterations: \" << inner << endl;\n\n\t\tcout << endl;\n\n\t\tpow2l *= 2;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Refine Solution grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tgrid.refine( RectilinearGrid2::NewTickBetweenEachPair() );\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>Control discretization now has the same number of nodes under the contract withdrawal amount and above it.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ guaranteed_minimum_withdrawal_benefit.cpp\n\/\/ -----------------------------------------\n\/\/\n\/\/ Computes the price of a Guaranteed Minimum Withdrawal Benefit (GMWB) using an\n\/\/ implicit, impulse control formulation.\n\/\/\n\/\/ Author: Parsiad Azimzadeh\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <QuantPDE\/Core>\n#include <QuantPDE\/Modules\/Lambdas>\n#include <QuantPDE\/Modules\/Operators>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <algorithm> \/\/ max, min\n#include <iostream> \/\/ cout\n#include <numeric> \/\/ accumulate\n#include <tuple> \/\/ get\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace QuantPDE;\nusing namespace QuantPDE::Modules;\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Withdrawal final : public ControlledLinearSystem2 {\n\n\tstatic constexpr Real epsilon = 1e-12;\n\n\tRectilinearGrid2 &grid;\n\tNoncontrollable2 contractRate, kappa;\n\n\tControllable2 control;\n\npublic:\n\n\ttemplate <typename G, typename F1, typename F2>\n\tWithdrawal(G &grid, F1 &&contractRate, F2 &&kappa) noexcept :\n\t\tgrid(grid),\n\t\tcontractRate(contractRate),\n\t\tkappa(kappa),\n\t\tcontrol( Control2(grid) )\n\t{\n\t\tregisterControl( control );\n\t}\n\n\tvirtual Matrix A(Real t) {\n\t\tMatrix M(grid.size(), grid.size());\n\t\tM.reserve(IntegerVector::Constant(grid.size(), 4));\n\n\t\tIndex i = 0;\n\t\tfor(auto node : grid) {\n\t\t\tconst Real S = node[0]; \/\/ Investment\n\t\t\tconst Real W = node[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\tconst Real lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);\n\n\t\t\t\/\/ Interpolation data\n\t\t\tauto data = interpolationData<2>(\n\t\t\t\tgrid,\n\t\t\t\t{\n\t\t\t\t\tmax(S - lambdaW, 0.),\n\t\t\t\t\tW - lambdaW\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tconst Index i0 = get<0>( data[0] );\n\t\t\tconst Index i1 = get<0>( data[1] );\n\t\t\tconst Real w0 = get<1>( data[0] );\n\t\t\tconst Real w1 = get<1>( data[1] );\n\n\t\t\tconst Index j = grid.index(i0, i1);\n\n\t\t\tM.insert(i, j ) = w0 * w1 ;\n\t\t\tM.insert(i, j + grid[0].size()) = w0 * (1-w1);\n\t\t\tM.insert(i, j + 1 ) = (1-w0) * w1 ;\n\t\t\tM.insert(i, j + 1 + grid[0].size()) = (1-w0) * (1-w1);\n\n\t\t\t++i;\n\t\t}\n\n\t\tM.makeCompressed();\n\t\treturn grid.identity() - M;\n\t}\n\n\tvirtual Vector b(Real t) {\n\t\tVector b( grid.vector() );\n\t\tfor(auto node : accessor(grid, b)) {\n\t\t\tconst Real S = (&node)[0]; \/\/ Investment\n\t\t\tconst Real W = (&node)[1]; \/\/ Withdrawal\n\n\t\t\t\/\/ You have no money :(\n\t\t\tif(W <= epsilon) {\n\t\t\t\t*node = 0.;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Contract rate of withdrawal\n\t\t\tconst Real Gdt = contractRate(t, S, W);\n\n\t\t\t\/\/ Control\n\t\t\tconst Real q = control(t, S, W);\n\n\t\t\t\/\/ Amount withdrawn, pre-penalty\n\t\t\tconst Real lambdaW = (q<=1.) ? (q*Gdt) : ((q-1.)*(W - Gdt) + Gdt);\n\n\t\t\t\/\/ Withdrawal at no penalty\n\t\t\tif(lambdaW < Gdt) {\n\t\t\t\t*node = lambdaW;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ Withdrawal at a penalty\n\t\t\t*node = lambdaW - kappa(t, S, W) * (lambdaW - Gdt);\n\t\t}\n\n\t\treturn b;\n\t}\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main() {\n\n\tint n = 10; \/\/ Optimal control partition size\n\tint N = 100; \/\/ Number of timesteps\n\n\tReal T = 10.;\n\tReal r = .05;\n\tReal v = .20;\n\n\tReal alpha = 0.; \/\/ Hedging fee\n\n\tReal G = 10.; \/\/ Contract rate\n\tReal kappa = 0.1; \/\/ Penalty rate\n\n\tint refinement = 1;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Solution grid\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tRectilinearGrid2 grid(\n\t\tAxis {\n\t\t\t0., 5., 10., 15., 20., 25.,\n\t\t\t30., 35., 40., 45.,\n\t\t\t50., 55., 60., 65., 70., 72.5, 75., 77.5, 80., 82., 84.,\n\t\t\t86., 88., 90., 91., 92., 93., 94., 95.,\n\t\t\t96., 97., 98., 99., 100.,\n\t\t\t101., 102., 103., 104., 105., 106.,\n\t\t\t107., 108., 109., 110., 112., 114.,\n\t\t\t116., 118., 120., 123., 126.,\n\t\t\t130., 135., 140., 145., 150., 160., 175., 200., 225.,\n\t\t\t250., 300., 500., 750., 1000.\n\t\t},\n\t\tAxis::range(0., 2., 200.)\n\t);\n\n\tunsigned pow2l = 1; \/\/ 2^l\n\tfor(int l = 0; l < refinement; ++l) {\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Control grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\/\/ Control partition 0 : 1\/n : 1 (MATLAB notation)\n\t\tRectilinearGrid1 controls( Axis::range(0., 1. \/ (n * pow2l), 2.) );\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Iteration tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tReverseConstantStepper stepper(\n\t\t\t0., \/\/ Initial time\n\t\t\tT, \/\/ Expiry time\n\t\t\tT \/ (N * pow2l) \/\/ Timestep size\n\t\t);\n\t\tToleranceIteration tolerance;\n\t\tstepper.setInnerIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Linear system tree\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBlackScholes<2, 0> bs(grid, r, v, alpha);\n\t\tReverseLinearBDFTwo bdf(grid, bs);\n\t\tbdf.setIteration(stepper);\n\n\t\tWithdrawal impulse(grid, G * T \/ (N * pow2l), kappa);\n\t\tMinPolicyIteration2_1 policy(grid, controls, impulse);\n\n\t\tPenaltyMethod penalty(grid, bdf, policy);\n\n\t\t\/\/ TODO: It currently matters what order each linear system is\n\t\t\/\/ associated with an iteration; fix this.\n\n\t\tpenalty.setIteration(tolerance);\n\t\tpolicy.setIteration(tolerance);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Payoff\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tFunction2 payoff = [=] (Real S, Real W) {\n\t\t\treturn max(S, (1 - kappa) * W);\n\t\t};\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Running\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tBiCGSTABSolver solver;\n\n\t\tauto V = stepper.solve(\n\t\t\tgrid, \/\/ Domain\n\t\t\tpayoff, \/\/ Initial condition\n\t\t\tpenalty, \/\/ Root of linear system tree\n\t\t\tsolver \/\/ Linear system solver\n\t\t);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Print solution\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tRectilinearGrid2 printGrid(\n\t\t\tAxis::range(0., 25., 200.),\n\t\t\tAxis::range(0., 25., 200.)\n\t\t);\n\t\tcout << accessor( printGrid, V );\n\n\t\tcout << endl;\n\n\t\tauto its = tolerance.iterations();\n\t\tReal inner = accumulate(its.begin(), its.end(), 0.)\/its.size();\n\n\t\tcout << \"average number of inner iterations: \" << inner << endl;\n\n\t\tcout << endl;\n\n\t\tpow2l *= 2;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ Refine Solution grid\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tgrid.refine( RectilinearGrid2::NewTickBetweenEachPair() );\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_ISATRAITS_HH__\n#define __ARCH_X86_ISATRAITS_HH__\n\n#include \"arch\/x86\/intregs.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"arch\/x86\/x86_traits.hh\"\n#include \"sim\/host.hh\"\n\nclass StaticInstPtr;\n\nnamespace LittleEndianGuest {}\n\nnamespace X86ISA\n{\n \/\/This makes sure the little endian version of certain functions\n \/\/are used.\n using namespace LittleEndianGuest;\n\n \/\/ X86 does not have a delay slot\n#define ISA_HAS_DELAY_SLOT 0\n\n \/\/ X86 NOP (XCHG rAX, rAX)\n \/\/XXX This needs to be set to an intermediate instruction struct\n \/\/which encodes this instruction\n\n \/\/ These enumerate all the registers for dependence tracking.\n enum DependenceTags {\n \/\/There are 16 microcode registers at the moment. This is an\n \/\/unusually large constant to make sure there isn't overflow.\n FP_Base_DepTag = 128,\n Ctrl_Base_DepTag =\n FP_Base_DepTag +\n \/\/mmx\/x87 registers\n 8 +\n \/\/xmm registers\n 16 * 2 +\n \/\/The microcode fp registers\n 8 +\n \/\/The indices that are mapped over the fp stack\n 8\n };\n\n \/\/ semantically meaningful register indices\n \/\/There is no such register in X86\n const int ZeroReg = NUM_INTREGS;\n const int StackPointerReg = INTREG_RSP;\n \/\/X86 doesn't seem to have a link register\n const int ReturnAddressReg = 0;\n const int ReturnValueReg = INTREG_RAX;\n const int FramePointerReg = INTREG_RBP;\n const int ArgumentReg[] = {\n INTREG_RDI,\n INTREG_RSI,\n INTREG_RDX,\n \/\/This argument register is r10 for syscalls and rcx for C.\n INTREG_R10W,\n \/\/INTREG_RCX,\n INTREG_R8W,\n INTREG_R9W\n };\n const int NumArgumentRegs = sizeof(ArgumentReg) \/ sizeof(const int);\n\n \/\/ Some OS syscalls use a second register (rdx) to return a second\n \/\/ value\n const int SyscallPseudoReturnReg = INTREG_RDX;\n\n \/\/XXX These numbers are bogus\n const int MaxInstSrcRegs = 10;\n const int MaxInstDestRegs = 10;\n\n \/\/4k. This value is not constant on x86.\n const int LogVMPageSize = 12;\n const int VMPageSize = (1 << LogVMPageSize);\n\n const int PageShift = 13;\n const int PageBytes = 1ULL << PageShift;\n\n const int BranchPredAddrShiftAmt = 0;\n\n StaticInstPtr decodeInst(ExtMachInst);\n\n const Addr LoadAddrMask = ULL(0xffffffffff);\n};\n\n#endif \/\/ __ARCH_X86_ISATRAITS_HH__\n<commit_msg>X86: Fix the PageShift constant in isa_traits.hh (I thought I alread did this?)<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_ISATRAITS_HH__\n#define __ARCH_X86_ISATRAITS_HH__\n\n#include \"arch\/x86\/intregs.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"arch\/x86\/x86_traits.hh\"\n#include \"sim\/host.hh\"\n\nclass StaticInstPtr;\n\nnamespace LittleEndianGuest {}\n\nnamespace X86ISA\n{\n \/\/This makes sure the little endian version of certain functions\n \/\/are used.\n using namespace LittleEndianGuest;\n\n \/\/ X86 does not have a delay slot\n#define ISA_HAS_DELAY_SLOT 0\n\n \/\/ X86 NOP (XCHG rAX, rAX)\n \/\/XXX This needs to be set to an intermediate instruction struct\n \/\/which encodes this instruction\n\n \/\/ These enumerate all the registers for dependence tracking.\n enum DependenceTags {\n \/\/There are 16 microcode registers at the moment. This is an\n \/\/unusually large constant to make sure there isn't overflow.\n FP_Base_DepTag = 128,\n Ctrl_Base_DepTag =\n FP_Base_DepTag +\n \/\/mmx\/x87 registers\n 8 +\n \/\/xmm registers\n 16 * 2 +\n \/\/The microcode fp registers\n 8 +\n \/\/The indices that are mapped over the fp stack\n 8\n };\n\n \/\/ semantically meaningful register indices\n \/\/There is no such register in X86\n const int ZeroReg = NUM_INTREGS;\n const int StackPointerReg = INTREG_RSP;\n \/\/X86 doesn't seem to have a link register\n const int ReturnAddressReg = 0;\n const int ReturnValueReg = INTREG_RAX;\n const int FramePointerReg = INTREG_RBP;\n const int ArgumentReg[] = {\n INTREG_RDI,\n INTREG_RSI,\n INTREG_RDX,\n \/\/This argument register is r10 for syscalls and rcx for C.\n INTREG_R10W,\n \/\/INTREG_RCX,\n INTREG_R8W,\n INTREG_R9W\n };\n const int NumArgumentRegs = sizeof(ArgumentReg) \/ sizeof(const int);\n\n \/\/ Some OS syscalls use a second register (rdx) to return a second\n \/\/ value\n const int SyscallPseudoReturnReg = INTREG_RDX;\n\n \/\/XXX These numbers are bogus\n const int MaxInstSrcRegs = 10;\n const int MaxInstDestRegs = 10;\n\n \/\/4k. This value is not constant on x86.\n const int LogVMPageSize = 12;\n const int VMPageSize = (1 << LogVMPageSize);\n\n const int PageShift = 12;\n const int PageBytes = 1ULL << PageShift;\n\n const int BranchPredAddrShiftAmt = 0;\n\n StaticInstPtr decodeInst(ExtMachInst);\n\n const Addr LoadAddrMask = ULL(0xffffffffff);\n};\n\n#endif \/\/ __ARCH_X86_ISATRAITS_HH__\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include <string>\n\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"arch\/x86\/stacktrace.hh\"\n#include \"arch\/x86\/vtophys.hh\"\n#include \"base\/bitfield.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nnamespace X86ISA\n{\n ProcessInfo::ProcessInfo(ThreadContext *_tc)\n : tc(_tc)\n {\n Addr addr = 0;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"thread_info_size\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n thread_info_size = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_size\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n task_struct_size = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"thread_info_task\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n task_off = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_pid\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n pid_off = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_comm\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n name_off = vp->readGtoH<int32_t>(addr);\n\n tc->delVirtPort(vp);\n }\n\n Addr\n ProcessInfo::task(Addr ksp) const\n {\n Addr base = ksp & ~0x3fff;\n if (base == ULL(0xfffffc0000000000))\n return 0;\n\n Addr tsk;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n tsk = vp->readGtoH<Addr>(base + task_off);\n tc->delVirtPort(vp);\n\n return tsk;\n }\n\n int\n ProcessInfo::pid(Addr ksp) const\n {\n Addr task = this->task(ksp);\n if (!task)\n return -1;\n\n uint16_t pd;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n pd = vp->readGtoH<uint16_t>(task + pid_off);\n tc->delVirtPort(vp);\n\n return pd;\n }\n\n string\n ProcessInfo::name(Addr ksp) const\n {\n Addr task = this->task(ksp);\n if (!task)\n return \"console\";\n\n char comm[256];\n CopyStringOut(tc, comm, task + name_off, sizeof(comm));\n if (!comm[0])\n return \"startup\";\n\n return comm;\n }\n\n StackTrace::StackTrace()\n : tc(0), stack(64)\n {\n }\n\n StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst)\n : tc(0), stack(64)\n {\n trace(_tc, inst);\n }\n\n StackTrace::~StackTrace()\n {\n }\n\n void\n StackTrace::trace(ThreadContext *_tc, bool is_call)\n {\n }\n\n bool\n StackTrace::isEntry(Addr addr)\n {\n return false;\n }\n\n bool\n StackTrace::decodeStack(MachInst inst, int &disp)\n {\n return true;\n }\n\n bool\n StackTrace::decodeSave(MachInst inst, int ®, int &disp)\n {\n return true;\n }\n\n \/*\n * Decode the function prologue for the function we're in, and note\n * which registers are stored where, and how large the stack frame is.\n *\/\n bool\n StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func,\n int &size, Addr &ra)\n {\n size = 0;\n ra = 0;\n\n for (Addr pc = func; pc < callpc; pc += sizeof(MachInst)) {\n MachInst inst;\n CopyOut(tc, (uint8_t *)&inst, pc, sizeof(MachInst));\n\n int reg, disp;\n if (decodeStack(inst, disp)) {\n if (size) {\n \/\/ panic(\"decoding frame size again\");\n return true;\n }\n size += disp;\n } else if (decodeSave(inst, reg, disp)) {\n if (!ra && reg == ReturnAddressReg) {\n CopyOut(tc, (uint8_t *)&ra, sp + disp, sizeof(Addr));\n if (!ra) {\n \/\/ panic(\"no return address value pc=%#x\\n\", pc);\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n#if TRACING_ON\n void\n StackTrace::dump()\n {\n StringWrap name(tc->getCpuPtr()->name());\n SymbolTable *symtab = tc->getSystemPtr()->kernelSymtab;\n\n DPRINTFN(\"------ Stack ------\\n\");\n\n string symbol;\n for (int i = 0, size = stack.size(); i < size; ++i) {\n Addr addr = stack[size - i - 1];\n if (addr == user)\n symbol = \"user\";\n else if (addr == console)\n symbol = \"console\";\n else if (addr == unknown)\n symbol = \"unknown\";\n else\n symtab->findSymbol(addr, symbol);\n\n DPRINTFN(\"%#x: %s\\n\", addr, symbol);\n }\n }\n#endif\n}\n<commit_msg>X86: Fix for uninitialized variables in stacktrace code.<commit_after>\/*\n * Copyright (c) 2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include <string>\n\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"arch\/x86\/stacktrace.hh\"\n#include \"arch\/x86\/vtophys.hh\"\n#include \"base\/bitfield.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nnamespace X86ISA\n{\n ProcessInfo::ProcessInfo(ThreadContext *_tc)\n : tc(_tc)\n {\n Addr addr = 0;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"thread_info_size\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n thread_info_size = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_size\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n task_struct_size = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"thread_info_task\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n task_off = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_pid\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n pid_off = vp->readGtoH<int32_t>(addr);\n\n if (!tc->getSystemPtr()->kernelSymtab->findAddress(\"task_struct_comm\", addr))\n panic(\"thread info not compiled into kernel\\n\");\n name_off = vp->readGtoH<int32_t>(addr);\n\n tc->delVirtPort(vp);\n }\n\n Addr\n ProcessInfo::task(Addr ksp) const\n {\n Addr base = ksp & ~0x3fff;\n if (base == ULL(0xfffffc0000000000))\n return 0;\n\n Addr tsk;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n tsk = vp->readGtoH<Addr>(base + task_off);\n tc->delVirtPort(vp);\n\n return tsk;\n }\n\n int\n ProcessInfo::pid(Addr ksp) const\n {\n Addr task = this->task(ksp);\n if (!task)\n return -1;\n\n uint16_t pd;\n\n VirtualPort *vp;\n\n vp = tc->getVirtPort();\n pd = vp->readGtoH<uint16_t>(task + pid_off);\n tc->delVirtPort(vp);\n\n return pd;\n }\n\n string\n ProcessInfo::name(Addr ksp) const\n {\n Addr task = this->task(ksp);\n if (!task)\n return \"console\";\n\n char comm[256];\n CopyStringOut(tc, comm, task + name_off, sizeof(comm));\n if (!comm[0])\n return \"startup\";\n\n return comm;\n }\n\n StackTrace::StackTrace()\n : tc(0), stack(64)\n {\n }\n\n StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst)\n : tc(0), stack(64)\n {\n trace(_tc, inst);\n }\n\n StackTrace::~StackTrace()\n {\n }\n\n void\n StackTrace::trace(ThreadContext *_tc, bool is_call)\n {\n }\n\n bool\n StackTrace::isEntry(Addr addr)\n {\n return false;\n }\n\n bool\n StackTrace::decodeStack(MachInst inst, int &disp)\n {\n disp = 0;\n return true;\n }\n\n bool\n StackTrace::decodeSave(MachInst inst, int ®, int &disp)\n {\n reg = 0;\n disp = 0;\n return true;\n }\n\n \/*\n * Decode the function prologue for the function we're in, and note\n * which registers are stored where, and how large the stack frame is.\n *\/\n bool\n StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func,\n int &size, Addr &ra)\n {\n size = 0;\n ra = 0;\n\n for (Addr pc = func; pc < callpc; pc += sizeof(MachInst)) {\n MachInst inst;\n CopyOut(tc, (uint8_t *)&inst, pc, sizeof(MachInst));\n\n int reg, disp;\n if (decodeStack(inst, disp)) {\n if (size) {\n \/\/ panic(\"decoding frame size again\");\n return true;\n }\n size += disp;\n } else if (decodeSave(inst, reg, disp)) {\n if (!ra && reg == ReturnAddressReg) {\n CopyOut(tc, (uint8_t *)&ra, sp + disp, sizeof(Addr));\n if (!ra) {\n \/\/ panic(\"no return address value pc=%#x\\n\", pc);\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n#if TRACING_ON\n void\n StackTrace::dump()\n {\n StringWrap name(tc->getCpuPtr()->name());\n SymbolTable *symtab = tc->getSystemPtr()->kernelSymtab;\n\n DPRINTFN(\"------ Stack ------\\n\");\n\n string symbol;\n for (int i = 0, size = stack.size(); i < size; ++i) {\n Addr addr = stack[size - i - 1];\n if (addr == user)\n symbol = \"user\";\n else if (addr == console)\n symbol = \"console\";\n else if (addr == unknown)\n symbol = \"unknown\";\n else\n symtab->findSymbol(addr, symbol);\n\n DPRINTFN(\"%#x: %s\\n\", addr, symbol);\n }\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nusing namespace std;\n\n#include \"mo\/SmellFinder.h\"\n#include \"mo\/exception\/MOException.h\"\n\nint main(int argc, char* argv[]) {\n try {\n SmellFinder smellFinder;\n if (smellFinder.hasSmell(argv, argc)) {\n cout << smellFinder.smellToString() << endl;\n }\n else {\n cout << \"No Smell Detected!\" << endl;\n }\n }\n catch (MOException& ex) {\n cout << \"Exception: \" << ex.message << endl;\n }\n return 0;\n}\n<commit_msg>fix the linker warming as what we do right now is syntax only<commit_after>#include <iostream>\n\nusing namespace std;\n\n#include \"mo\/SmellFinder.h\"\n#include \"mo\/exception\/MOException.h\"\n\nint main(int argc, char* argv[]) {\n try {\n SmellFinder smellFinder;\n if (smellFinder.hasSmell(argv + 1, argc - 1)) {\n cout << smellFinder.smellToString() << endl;\n }\n else {\n cout << \"No Smell Detected!\" << endl;\n }\n }\n catch (MOException& ex) {\n cout << \"Exception: \" << ex.message << endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* author: @gwzz\n * \n *\/\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <iterator>\n#include \"graph.h\"\n#include \"support.h\"\n#include \"sctfile.h\"\n\nusing namespace std;\n\n\/\/ Pre-define hierarchy array\n\/\/ CUI: array of top nodes concept id of each hierarchy\n\/\/ ConName: array of the name of each hierarchy\nconst long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};\nconst string ConName[19] = {\"Body_structure\", \"Clinical_finding\", \"Environment_or_geographical_location\", \"Event\", \"Observable_entity\", \"Organism\", \"Pharmaceutical_biologic_product\", \"Physical_force\", \"Physical_object\", \"Procedure\", \"Qualifier_value\", \"Record_artifact\", \"Situation_with_explicit_context\", \"SNOMED_CT_Model_Component\", \"Social_context\", \"Special_Concept\", \"Specimen\", \"Staging_and_scales\", \"Substance\"};\n\n \nint main(int argc, char* argv[])\n{ \n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" SNOMED_CT_FILE_PATH\" << std::endl;\n return 1;\n }\n \/\/ string out_put_folder = \"\/Users\/zhuwei\/Desktop\/sct_nodes_within_hierarchy\/\";\n string out_put_folder = \"\/Users\/zhuwei\/Desktop\/tc\/\";\n SctFile sf(argv[1]);\n long long top_node;\n std::map<long long, int> node_map;\n std::map<int, long long> reversed_node_map;\n std::vector<long long> output_vector;\n std::string sline;\n std::vector<std::string> relation = sf.relations();\n std::vector<std::string> nodes = sf.nodes();\n\n \/\/ Read in node file\n \/\/ (concept, index)\n \/\/ (index, concept) reversed\n for (int i = 0; i < nodes.size(); ++i){\n node_map[std::stoll(nodes[i])] = i;\n }\n for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)\n reversed_node_map[i->second] = i->first;\n\n int nodeSize = node_map.size();\n \/\/ initialize graph g\n int rnodeSize = reversed_node_map.size();\n std::cout << nodeSize << \" \" << rnodeSize << endl;\n Graph g(nodeSize);\n std::vector<long long> is_a_relationship;\n for (auto i : relation){\n is_a_relationship.clear();\n is_a_relationship = Split(i, ',');\n \/\/ g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);\n g.addEdge(node_map[is_a_relationship[0]],node_map[is_a_relationship[1]]);\n }\n\n \/\/ string out_put_file;\n \/\/ for (int i = 0; i < 19; ++i){\n \/\/ output_vector.clear();\n \/\/ out_put_file.clear();\n \/\/ out_put_file = out_put_folder + ConName[i];\n \/\/ top_node = CUI[i];\n \/\/ output_vector = g.DFS(node_map[top_node]);\n \/\/ fstream fout;\n \/\/ fout.open(out_put_file,ios::app);\n \/\/ for (auto o : output_vector){\n \/\/ fout << reversed_node_map[o] << endl;\n \/\/ }\n \/\/ fout.close();\n \/\/ }\n fstream fout;\n string out_put_file = out_put_folder + \"test\";\n fout.open(out_put_file,ios::app);\n int tc_index = 0;\n for(std::map<long long, int>::iterator it = node_map.begin(); it != node_map.end(); ++it) {\n std::cout << it->first << endl;\n output_vector = g.DFS(it->second);\n fout << reversed_node_map[it->first] << '|';\n for (auto o : output_vector){\n fout << reversed_node_map[o] << ',';\n }\n fout << std::endl;\n std::cout << tc_index++ << endl;\n }\n fout.close();\n \n return 0;\n}<commit_msg>tc test<commit_after>\/* author: @gwzz\n * \n *\/\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <iterator>\n#include \"graph.h\"\n#include \"support.h\"\n#include \"sctfile.h\"\n\nusing namespace std;\n\n\/\/ Pre-define hierarchy array\n\/\/ CUI: array of top nodes concept id of each hierarchy\n\/\/ ConName: array of the name of each hierarchy\nconst long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};\nconst string ConName[19] = {\"Body_structure\", \"Clinical_finding\", \"Environment_or_geographical_location\", \"Event\", \"Observable_entity\", \"Organism\", \"Pharmaceutical_biologic_product\", \"Physical_force\", \"Physical_object\", \"Procedure\", \"Qualifier_value\", \"Record_artifact\", \"Situation_with_explicit_context\", \"SNOMED_CT_Model_Component\", \"Social_context\", \"Special_Concept\", \"Specimen\", \"Staging_and_scales\", \"Substance\"};\n\n \nint main(int argc, char* argv[])\n{ \n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" SNOMED_CT_FILE_PATH\" << std::endl;\n return 1;\n }\n \/\/ string out_put_folder = \"\/Users\/zhuwei\/Desktop\/sct_nodes_within_hierarchy\/\";\n string out_put_folder = \"\/Users\/zhuwei\/Desktop\/tc\/\";\n SctFile sf(argv[1]);\n long long top_node;\n std::map<long long, int> node_map;\n std::map<int, long long> reversed_node_map;\n std::vector<long long> output_vector;\n std::string sline;\n std::vector<std::string> relation = sf.relations();\n std::vector<std::string> nodes = sf.nodes();\n\n \/\/ Read in node file\n \/\/ (concept, index)\n \/\/ (index, concept) reversed\n for (int i = 0; i < nodes.size(); ++i){\n node_map[std::stoll(nodes[i])] = i;\n }\n for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)\n reversed_node_map[i->second] = i->first;\n\n int nodeSize = node_map.size();\n \/\/ initialize graph g\n int rnodeSize = reversed_node_map.size();\n std::cout << nodeSize << \" \" << rnodeSize << endl;\n Graph g(nodeSize);\n std::vector<long long> is_a_relationship;\n for (auto i : relation){\n is_a_relationship.clear();\n is_a_relationship = Split(i, ',');\n \/\/ g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);\n g.addEdge(node_map[is_a_relationship[0]],node_map[is_a_relationship[1]]);\n }\n\n \/\/ string out_put_file;\n \/\/ for (int i = 0; i < 19; ++i){\n \/\/ output_vector.clear();\n \/\/ out_put_file.clear();\n \/\/ out_put_file = out_put_folder + ConName[i];\n \/\/ top_node = CUI[i];\n \/\/ output_vector = g.DFS(node_map[top_node]);\n \/\/ fstream fout;\n \/\/ fout.open(out_put_file,ios::app);\n \/\/ for (auto o : output_vector){\n \/\/ fout << reversed_node_map[o] << endl;\n \/\/ }\n \/\/ fout.close();\n \/\/ }\n fstream fout;\n string out_put_file = out_put_folder + \"test\";\n fout.open(out_put_file,ios::app);\n int tc_index = 0;\n \/\/ debug begin\n \/\/ output_vector = g.DFS(node_map[300591002]);\n \/\/ for (auto o : output_vector){\n \/\/ cout << reversed_node_map[o] << ',';\n \/\/ }\n \/\/ debug end\n std::map<long long, int>::iterator it = node_map.begin();\n \/\/ std::advance( it, 149999 );\n for(it; it != node_map.end(); ++it) {\n std::cout << it->first << endl;\n output_vector = g.DFS(it->second);\n fout << it->first << '|';\n for (auto o : output_vector){\n fout << reversed_node_map[o] << ',';\n }\n fout << std::endl;\n std::cout << tc_index++ << endl;\n }\n fout.close();\n \n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <iostream>\n#include <fstream>\n\n#include <deal.II\/base\/parameter_handler.h>\n#include <deal.II\/base\/mpi.h>\n\n#include \"framework\/builder\/cfem_framework_builder.h\"\n#include \"problem\/parameters_dealii_handler.h\"\n\nint main(int argc, char* argv[]) {\n try {\n if (argc != 2) {\n std::cerr\n << \"Call the program as mpirun -np num_proc bart input_file_name\"\n << std::endl;\n return 1;\n }\n\n std::cout << \"BAY AREA RADIATION TRANSPORT\\n\"\n << \"Developed at the University of California, Berkeley\"\n << std::endl;\n\n bart::problem::ParametersDealiiHandler prm;\n dealii::ParameterHandler d2_prm;\n const std::string filename{argv[1]};\n\n prm.SetUp(d2_prm);\n d2_prm.parse_input(filename, \"\");\n prm.Parse(d2_prm);\n\n dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n double k_eff_final;\n\n std::ofstream output_stream((prm.OutputFilenameBase() + \".vtu\").c_str());\n\n switch(prm.SpatialDimension()) {\n case 1: {\n bart::framework::builder::CFEM_FrameworkBuilder<1> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n case 2: {\n bart::framework::builder::CFEM_FrameworkBuilder<2> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n case 3: {\n bart::framework::builder::CFEM_FrameworkBuilder<3> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n }\n\n std::cout << \"Final k_effective: \" << k_eff_final << std::endl;\n\n } catch (std::exception &exc) {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n } catch (...) {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n return 0;\n}\n<commit_msg>added mpi filename extension using process number<commit_after>#include <memory>\n#include <iostream>\n#include <fstream>\n\n#include <deal.II\/base\/parameter_handler.h>\n#include <deal.II\/base\/mpi.h>\n\n#include \"framework\/builder\/cfem_framework_builder.h\"\n#include \"problem\/parameters_dealii_handler.h\"\n\nint main(int argc, char* argv[]) {\n try {\n if (argc != 2) {\n std::cerr\n << \"Call the program as mpirun -np num_proc bart input_file_name\"\n << std::endl;\n return 1;\n }\n\n std::cout << \"BAY AREA RADIATION TRANSPORT\\n\"\n << \"Developed at the University of California, Berkeley\"\n << std::endl;\n\n bart::problem::ParametersDealiiHandler prm;\n dealii::ParameterHandler d2_prm;\n const std::string filename{argv[1]};\n\n prm.SetUp(d2_prm);\n d2_prm.parse_input(filename, \"\");\n prm.Parse(d2_prm);\n\n dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n double k_eff_final;\n\n const int n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n const int process_id = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n\n std::ofstream output_stream;\n const std::string output_filename_base{prm.OutputFilenameBase()};\n if (n_processes > 1) {\n const std::string full_filename = output_filename_base + dealii::Utilities::int_to_string(process_id, 4);\n output_stream.open((full_filename + \".vtu\").c_str());\n } else {\n output_stream.open((output_filename_base + \".vtu\").c_str());\n }\n\n switch(prm.SpatialDimension()) {\n case 1: {\n bart::framework::builder::CFEM_FrameworkBuilder<1> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n case 2: {\n bart::framework::builder::CFEM_FrameworkBuilder<2> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n case 3: {\n bart::framework::builder::CFEM_FrameworkBuilder<3> builder;\n auto framework_ptr = builder.BuildFramework(prm, d2_prm);\n framework_ptr->SolveSystem();\n framework_ptr->OutputResults(output_stream);\n k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n break;\n }\n }\n\n std::cout << \"Final k_effective: \" << k_eff_final << std::endl;\n\n } catch (std::exception &exc) {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n } catch (...) {\n std::cerr << std::endl << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include \"NTClient.h\"\nusing namespace std;\n\nvoid initBot() {\n\tNTClient nclient = NTClient(220, 0.98);\n\tnclient.login(\"utpp_bot2\", \"123asd123\"); \/\/ Throw-away account\n\tnclient.connect();\n}\nint main(int argc, char** argv) {\n\tsrand(static_cast<unsigned int>(time(0)));\n\tinitBot();\n\treturn 0;\n}<commit_msg>Lower base accuracy<commit_after>#include <iostream>\n#include <cstdlib>\n#include \"NTClient.h\"\nusing namespace std;\n\nvoid initBot() {\n\tNTClient nclient = NTClient(220, 0.92);\n\tnclient.login(\"utpp_bot2\", \"123asd123\"); \/\/ Throw-away account\n\tnclient.connect();\n}\nint main(int argc, char** argv) {\n\tsrand(static_cast<unsigned int>(time(0)));\n\tinitBot();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\nusing namespace std;\n\nextern \"C\" {\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <curl\/curl.h>\n#include <errno.h>\n#include <sqlite3.h>\n#include <getopt.h>\n#include <libxml\/xmlmemory.h>\n#include \"help.h\"\n#include \"logger.h\"\n}\n\n#include \"localFileList.h\"\n#include \"fileListStorage.h\"\n#include \"amazonCredentials.h\"\n#include \"remoteListOfFiles.h\"\n#include \"upload.h\"\n#include \"filePattern.h\"\n\nstatic char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) \"s3.amazonaws.com\",\n\t*source=NULL, *databasePath=NULL, *databaseFilename= (char *)\".files.sqlite3\";\nstatic int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0;\n\nFilePattern *excludeFilePattern;\n\nFILE *logStream;\nint logLevel = LOG_ERR;\n\n\nint rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {\n\tint res = remoteListOfFiles->downloadList();\n\tif (res==LIST_FAILED) { \n\t\treturn LIST_FAILED;\n\t}\n\n LOG(LOG_INFO, \"[MetaUpdate] Got %d files, updating meta information\", remoteListOfFiles->count);\n\n\tres = remoteListOfFiles->resolveMtimes();\n\tif (res==LIST_FAILED) { \n\t\treturn LIST_FAILED;\n\t}\n\n\tif (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {\n LOG(LOG_FATAL, \"[MetaUpdate] Failed to store list of files\");\n\t\treturn LIST_FAILED;\n\t} else { \n\t\treturn LIST_SUCCESS;\n\t}\n}\n\nstatic char *endPoints[] = {\n\t(char *) \"s3.amazonaws.com\",\n\t(char *) \"s3-us-west-2.amazonaws.com\",\n\t(char *) \"s3-us-west-1.amazonaws.com\",\n\t(char *) \"s3-eu-west-1.amazonaws.com\",\n\t(char *) \"s3-ap-southeast-1.amazonaws.com\",\n\t(char *) \"s3-ap-northeast-1.amazonaws.com\",\n\t(char *) \"s3-sa-east-1.amazonaws.com\",\n\n#ifdef TEST\n\t(char *) \"test.dev\",\n#endif\n\t\n\tNULL\n};\n\nint validateEndpoint(char *endPoint) {\n\tint i=0;\n\twhile (char *e=endPoints[i++]) {\n\t\tif (e && strcmp(e, endPoint)==0) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n \tprintf(\"--endPoint %s not valid, use one of:\\n\", endPoint);\n\n \ti=0;\n\twhile (char *e=endPoints[i++]) {\n\t\tprintf(\"\\t%s\\n\", e);\n\t}\n\n\treturn 0;\n}\n\nchar *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {\n\tuint64_t len = strlen(databasePath)+strlen(databaseFilename)+1;\n\tchar *databaseFilePath = (char *) malloc(len);\n\tbzero(databaseFilePath, len);\n\tstrcat(databaseFilePath, databasePath);\n\tstrcat(databaseFilePath, \"\/\");\n\tstrcat(databaseFilePath, databaseFilename);\n\treturn databaseFilePath;\n}\n\nvoid showVersion() {\n\tprintf(\"clarc version \" VERSION \" (c) 2012 Egor Egorov <me@egorfine.com>\\nMIT License | http:\/\/egorfine.com\/clarc\/\\n\");\n}\n\nint parseCommandline(int argc, char *argv[]) {\n\tif (argc==1) {\n\t\tshowVersion();\n\t\tprintf(\"Perhaps, ask --help?\\n\");\n\t\texit(0);\t\n\t}\n\n static struct option longOpts[] = {\n { \"accessKeyId\", required_argument, NULL, 0 },\n { \"secretAccessKey\", required_argument, NULL, 0 },\n { \"bucket\", required_argument, NULL, 0 },\n { \"endPoint\", required_argument, NULL, 0 },\n { \"public\", no_argument, NULL, 0 },\n { \"rrs\", no_argument, NULL, 0 },\n { \"rss\", no_argument, NULL, 0 }, \/\/ common typo\n { \"skipSsl\", no_argument, NULL, 0 },\n\n { \"source\", required_argument, NULL, 0 },\n { \"ddbPath\", required_argument, NULL, 0 },\n { \"dbFilename\", required_argument, NULL, 0 },\n\n { \"exclude\", required_argument, NULL, 0 },\n { \"excludeFromFile\", required_argument, NULL, 0 },\n\n { \"progress\", no_argument, NULL, 0 },\n { \"logLevel\", required_argument, NULL, 0 },\n\n { \"dryRun\", no_argument, NULL, 0 },\n\n { \"rebuild\", no_argument, NULL, 0 },\n { \"upload\", no_argument, NULL, 0 },\n\n { \"version\", no_argument, NULL, 'V' },\n { \"help\", no_argument, NULL, 'h' },\n\n { NULL, 0, NULL, 0 }\n };\n\n\tint ch, longIndex;\n while ((ch = getopt_long(argc, argv, \"Vh\", longOpts, &longIndex)) != -1) {\n \tif (ch=='V') {\n \t\tshowVersion();\n \t\texit(0);\n \t} else if (ch=='h') {\n \t\tshowHelp();\n \t\texit(0);\n \t}\n\n \tif (ch!=0) {\n \t\tcontinue;\n \t}\n\n \tconst char *longName = longOpts[longIndex].name;\n\n \tif (strcmp(longName, \"accessKeyId\")==0) {\n \t\taccessKeyId = strdup(optarg);\n\n \t} else if (strcmp(longName, \"secretAccessKey\")==0) {\n \t\tsecretAccessKey = strdup(optarg);\n\n \t} else if (strcmp(longName, \"bucket\")==0) {\n \t\tbucket = strdup(optarg);\n\n \t} else if (strcmp(longName, \"endPoint\")==0) {\n \t\tendPoint = strdup(optarg);\n\n \t} else if (strcmp(longName, \"public\")==0) {\n \t\tmakeAllPublic = 1;\n\n } else if (strcmp(longName, \"skipSsl\")==0) {\n skipSsl = 1;\n\n \t} else if (strcmp(longName, \"rrs\")==0) {\n \t\tuseRrs = 1;\n\n \t} else if (strcmp(longName, \"rss\")==0) {\n \t\tprintf(\"Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\\n\");\n \t\tuseRrs = 1;\n\n } else if (strcmp(longName, \"dryRun\")==0) {\n dryRun = 1;\n\n } else if (strcmp(longName, \"progress\")==0) {\n showProgress = 1;\n\n } else if (strcmp(longName, \"logLevel\")==0) {\n logLevel = atoi(optarg);\n if (logLevel <= 0 || logLevel > 5) {\n printf(\"--logLevel must be 1..5\\n\");\n exit(1);\n }\n\n \t} else if (strcmp(longName, \"source\")==0) {\n \t\tsource = strdup(optarg);\n\n \t} else if (strcmp(longName, \"dbPath\")==0) {\n \t\tdatabasePath = strdup(optarg);\n\n \t} else if (strcmp(longName, \"dbFilename\")==0) {\n \t\tdatabaseFilename = strdup(optarg);\n\n \t} else if (strcmp(longName, \"rebuild\")==0) {\n \t\tperformRebuild=1;\n\n \t} else if (strcmp(longName, \"upload\")==0) {\n \t\tperformUpload=1;\n\n \t} else if (strcmp(longName, \"exclude\")==0) {\n \t\tif (!excludeFilePattern->add(optarg)) {\n \t\t\tprintf(\"Pattern `%s' is not valid.\\n\", optarg);\n \t\t\texit(1);\n \t\t}\n \t} else if (strcmp(longName, \"excludeFromFile\")==0) {\n \t\tif (!excludeFilePattern->readFile(optarg)) {\n \t\t\tprintf(\"Cannot read or parse patterns in %s\\n\", optarg);\n \t\t\texit(1);\n \t\t}\n \t}\n }\n\n int failed = 0;\n\n if (!source) {\n \tprintf(\"Specify --source.\\n\"); \n \tfailed = 1;\n }\n\n if (source && source[0]!='\/') {\n \tprintf(\"--source must be absolute path.\\n\");\n\t\tfailed=1;\n }\n\n if (!accessKeyId) {\n \tprintf(\"Specify --accessKeyId.\\n\"); \n \tfailed = 1;\n }\n\n if (!secretAccessKey) {\n \tprintf(\"Specify --secretAccessKey.\\n\"); \n \tfailed = 1;\n }\n\n if (!bucket) {\n \tprintf(\"Specify --bucket.\\n\"); \n \tfailed = 1;\n }\n\n if (!validateEndpoint(endPoint)) {\n \tfailed = 1;\n }\n\n if (!performRebuild && !performUpload) {\n \tprintf(\"What shall I do? Say --rebuild and\/or --upload!\\n\");\n \tfailed = 1;\n }\n\n if (failed) {\n \treturn 0;\n }\n\n while (source[strlen(source)-1]=='\/') {\n \tsource[strlen(source)-1]=0;\n }\n\n if (!databasePath) {\n \tdatabasePath = source;\n } else { \n\t while (databasePath[strlen(databasePath)-1]=='\/') {\n\t \tdatabasePath[strlen(databasePath)-1]=0;\n\t }\n\t}\n\n\treturn 1;\n}\n\nint verifySource(char *source) {\n\tstruct stat fileInfo;\n\tif (lstat(source, &fileInfo)<0) {\n\t\tprintf(\"%s doesn't exists.\\n\", source);\n\t\treturn 0;\n\t}\n\n\tif (!(fileInfo.st_mode & S_IFDIR)) {\n\t\tprintf(\"%s isn't a directory.\\n\", source);\n\t\treturn 0;\n\t}\n\n\treturn 1;\n}\n\nint main(int argc, char *argv[]) {\n\tint res;\n curl_global_init(CURL_GLOBAL_ALL);\n xmlInitParser();\n\n logStream = stdout;\n logLevel = LOG_DBG;\n\n\texcludeFilePattern = new FilePattern();\n\n if (!parseCommandline(argc, argv)) {\n \texit(1);\n }\n\n if (!verifySource(source)) {\n \texit(1);\n }\n\n AmazonCredentials *amazonCredentials = new AmazonCredentials(\n \taccessKeyId, \n \tsecretAccessKey,\n \tbucket, endPoint\n );\n\n\tRemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);\n remoteListOfFiles->showProgress = showProgress;\n if (skipSsl) {\n remoteListOfFiles->useSsl=0;\n }\n\n\tres = remoteListOfFiles->checkAuth();\n\tif (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {\n LOG(LOG_FATAL, \"[Auth] Failed: bucket doesn't exists, exit\");\n\t\texit(1);\t\t\n\t} else if (res == AUTH_FAILED) {\n\t\tLOG(LOG_FATAL, \"[Auth] FAIL, exit\");\n\t\texit(1);\t\t\n\t}\n LOG(LOG_INFO, \"[Auth] Success\");\n\n\tchar *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);\n\tLOG(LOG_DBG, \"[Storage] Database path = %s\", databaseFilePath);\n\n\tchar errorResult[1024*100];\n\tFileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);\n\tif (strlen(errorResult)>0) {\n\t\tLOG(LOG_FATAL, \"[Storage] FAIL: %s, exit\", errorResult);\n\t\texit(1);\n\t}\n\n\tif (performRebuild) {\n\t\tif (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (performUpload) {\n\t\tif (excludeFilePattern->count==0) {\n\t\t\tdelete excludeFilePattern;\n\t\t\texcludeFilePattern=NULL;\n\t\t}\n\n\t\tUploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);\n\t\tuploader->useRrs = useRrs;\n\t\tuploader->makeAllPublic = makeAllPublic;\n uploader->showProgress = showProgress;\n if (skipSsl) {\n uploader->useSsl=0;\n }\n uploader->dryRun = dryRun;\n\n\t\tres = uploader->uploadFiles(fileListStorage, source);\n\n\t\tif (res==UPLOAD_FAILED) {\n\t\t\texit(1);\n\t\t}\n\n\t\tres = uploader->uploadDatabase(databaseFilePath, databaseFilename);\n\t\tif (res==UPLOAD_FAILED) {\n\t\t\texit(1);\n\t\t}\n\n\t\tdelete uploader;\n\t}\n\n\tfree(databaseFilePath);\n\tdelete fileListStorage;\n\tdelete amazonCredentials;\n\n\texit(0);\n}\n<commit_msg>dryRun<commit_after>#include <iostream>\nusing namespace std;\n\nextern \"C\" {\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <curl\/curl.h>\n#include <errno.h>\n#include <sqlite3.h>\n#include <getopt.h>\n#include <libxml\/xmlmemory.h>\n#include \"help.h\"\n#include \"logger.h\"\n}\n\n#include \"localFileList.h\"\n#include \"fileListStorage.h\"\n#include \"amazonCredentials.h\"\n#include \"remoteListOfFiles.h\"\n#include \"upload.h\"\n#include \"filePattern.h\"\n\nstatic char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) \"s3.amazonaws.com\",\n\t*source=NULL, *databasePath=NULL, *databaseFilename= (char *)\".files.sqlite3\";\nstatic int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0;\n\nFilePattern *excludeFilePattern;\n\nFILE *logStream;\nint logLevel = LOG_ERR;\n\n\nint rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {\n\tint res = remoteListOfFiles->downloadList();\n\tif (res==LIST_FAILED) { \n\t\treturn LIST_FAILED;\n\t}\n\n LOG(LOG_INFO, \"[MetaUpdate] Got %d files, updating meta information\", remoteListOfFiles->count);\n\n\tres = remoteListOfFiles->resolveMtimes();\n\tif (res==LIST_FAILED) { \n\t\treturn LIST_FAILED;\n\t}\n\n if (dryRun) {\n LOG(LOG_INFO, \"[MetaUpdate] [dry] Skipped storing list of files\");\n return LIST_SUCCESS;\n }\n \n\tif (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {\n LOG(LOG_FATAL, \"[MetaUpdate] Failed to store list of files\");\n\t\treturn LIST_FAILED;\n\t} else { \n\t\treturn LIST_SUCCESS;\n\t}\n}\n\nstatic char *endPoints[] = {\n\t(char *) \"s3.amazonaws.com\",\n\t(char *) \"s3-us-west-2.amazonaws.com\",\n\t(char *) \"s3-us-west-1.amazonaws.com\",\n\t(char *) \"s3-eu-west-1.amazonaws.com\",\n\t(char *) \"s3-ap-southeast-1.amazonaws.com\",\n\t(char *) \"s3-ap-northeast-1.amazonaws.com\",\n\t(char *) \"s3-sa-east-1.amazonaws.com\",\n\n#ifdef TEST\n\t(char *) \"test.dev\",\n#endif\n\t\n\tNULL\n};\n\nint validateEndpoint(char *endPoint) {\n\tint i=0;\n\twhile (char *e=endPoints[i++]) {\n\t\tif (e && strcmp(e, endPoint)==0) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n \tprintf(\"--endPoint %s not valid, use one of:\\n\", endPoint);\n\n \ti=0;\n\twhile (char *e=endPoints[i++]) {\n\t\tprintf(\"\\t%s\\n\", e);\n\t}\n\n\treturn 0;\n}\n\nchar *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {\n\tuint64_t len = strlen(databasePath)+strlen(databaseFilename)+1;\n\tchar *databaseFilePath = (char *) malloc(len);\n\tbzero(databaseFilePath, len);\n\tstrcat(databaseFilePath, databasePath);\n\tstrcat(databaseFilePath, \"\/\");\n\tstrcat(databaseFilePath, databaseFilename);\n\treturn databaseFilePath;\n}\n\nvoid showVersion() {\n\tprintf(\"clarc version \" VERSION \" (c) 2012 Egor Egorov <me@egorfine.com>\\nMIT License | http:\/\/egorfine.com\/clarc\/\\n\");\n}\n\nint parseCommandline(int argc, char *argv[]) {\n\tif (argc==1) {\n\t\tshowVersion();\n\t\tprintf(\"Perhaps, ask --help?\\n\");\n\t\texit(0);\t\n\t}\n\n static struct option longOpts[] = {\n { \"accessKeyId\", required_argument, NULL, 0 },\n { \"secretAccessKey\", required_argument, NULL, 0 },\n { \"bucket\", required_argument, NULL, 0 },\n { \"endPoint\", required_argument, NULL, 0 },\n { \"public\", no_argument, NULL, 0 },\n { \"rrs\", no_argument, NULL, 0 },\n { \"rss\", no_argument, NULL, 0 }, \/\/ common typo\n { \"skipSsl\", no_argument, NULL, 0 },\n\n { \"source\", required_argument, NULL, 0 },\n { \"ddbPath\", required_argument, NULL, 0 },\n { \"dbFilename\", required_argument, NULL, 0 },\n\n { \"exclude\", required_argument, NULL, 0 },\n { \"excludeFromFile\", required_argument, NULL, 0 },\n\n { \"progress\", no_argument, NULL, 0 },\n { \"logLevel\", required_argument, NULL, 0 },\n\n { \"dryRun\", no_argument, NULL, 0 },\n\n { \"rebuild\", no_argument, NULL, 0 },\n { \"upload\", no_argument, NULL, 0 },\n\n { \"version\", no_argument, NULL, 'V' },\n { \"help\", no_argument, NULL, 'h' },\n\n { NULL, 0, NULL, 0 }\n };\n\n\tint ch, longIndex;\n while ((ch = getopt_long(argc, argv, \"Vh\", longOpts, &longIndex)) != -1) {\n \tif (ch=='V') {\n \t\tshowVersion();\n \t\texit(0);\n \t} else if (ch=='h') {\n \t\tshowHelp();\n \t\texit(0);\n \t}\n\n \tif (ch!=0) {\n \t\tcontinue;\n \t}\n\n \tconst char *longName = longOpts[longIndex].name;\n\n \tif (strcmp(longName, \"accessKeyId\")==0) {\n \t\taccessKeyId = strdup(optarg);\n\n \t} else if (strcmp(longName, \"secretAccessKey\")==0) {\n \t\tsecretAccessKey = strdup(optarg);\n\n \t} else if (strcmp(longName, \"bucket\")==0) {\n \t\tbucket = strdup(optarg);\n\n \t} else if (strcmp(longName, \"endPoint\")==0) {\n \t\tendPoint = strdup(optarg);\n\n \t} else if (strcmp(longName, \"public\")==0) {\n \t\tmakeAllPublic = 1;\n\n } else if (strcmp(longName, \"skipSsl\")==0) {\n skipSsl = 1;\n\n \t} else if (strcmp(longName, \"rrs\")==0) {\n \t\tuseRrs = 1;\n\n \t} else if (strcmp(longName, \"rss\")==0) {\n \t\tprintf(\"Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\\n\");\n \t\tuseRrs = 1;\n\n } else if (strcmp(longName, \"dryRun\")==0) {\n dryRun = 1;\n\n } else if (strcmp(longName, \"progress\")==0) {\n showProgress = 1;\n\n } else if (strcmp(longName, \"logLevel\")==0) {\n logLevel = atoi(optarg);\n if (logLevel <= 0 || logLevel > 5) {\n printf(\"--logLevel must be 1..5\\n\");\n exit(1);\n }\n\n \t} else if (strcmp(longName, \"source\")==0) {\n \t\tsource = strdup(optarg);\n\n \t} else if (strcmp(longName, \"dbPath\")==0) {\n \t\tdatabasePath = strdup(optarg);\n\n \t} else if (strcmp(longName, \"dbFilename\")==0) {\n \t\tdatabaseFilename = strdup(optarg);\n\n \t} else if (strcmp(longName, \"rebuild\")==0) {\n \t\tperformRebuild=1;\n\n \t} else if (strcmp(longName, \"upload\")==0) {\n \t\tperformUpload=1;\n\n \t} else if (strcmp(longName, \"exclude\")==0) {\n \t\tif (!excludeFilePattern->add(optarg)) {\n \t\t\tprintf(\"Pattern `%s' is not valid.\\n\", optarg);\n \t\t\texit(1);\n \t\t}\n \t} else if (strcmp(longName, \"excludeFromFile\")==0) {\n \t\tif (!excludeFilePattern->readFile(optarg)) {\n \t\t\tprintf(\"Cannot read or parse patterns in %s\\n\", optarg);\n \t\t\texit(1);\n \t\t}\n \t}\n }\n\n int failed = 0;\n\n if (!source) {\n \tprintf(\"Specify --source.\\n\"); \n \tfailed = 1;\n }\n\n if (source && source[0]!='\/') {\n \tprintf(\"--source must be absolute path.\\n\");\n\t\tfailed=1;\n }\n\n if (!accessKeyId) {\n \tprintf(\"Specify --accessKeyId.\\n\"); \n \tfailed = 1;\n }\n\n if (!secretAccessKey) {\n \tprintf(\"Specify --secretAccessKey.\\n\"); \n \tfailed = 1;\n }\n\n if (!bucket) {\n \tprintf(\"Specify --bucket.\\n\"); \n \tfailed = 1;\n }\n\n if (!validateEndpoint(endPoint)) {\n \tfailed = 1;\n }\n\n if (!performRebuild && !performUpload) {\n \tprintf(\"What shall I do? Say --rebuild and\/or --upload!\\n\");\n \tfailed = 1;\n }\n\n if (failed) {\n \treturn 0;\n }\n\n while (source[strlen(source)-1]=='\/') {\n \tsource[strlen(source)-1]=0;\n }\n\n if (!databasePath) {\n \tdatabasePath = source;\n } else { \n\t while (databasePath[strlen(databasePath)-1]=='\/') {\n\t \tdatabasePath[strlen(databasePath)-1]=0;\n\t }\n\t}\n\n\treturn 1;\n}\n\nint verifySource(char *source) {\n\tstruct stat fileInfo;\n\tif (lstat(source, &fileInfo)<0) {\n\t\tprintf(\"%s doesn't exists.\\n\", source);\n\t\treturn 0;\n\t}\n\n\tif (!(fileInfo.st_mode & S_IFDIR)) {\n\t\tprintf(\"%s isn't a directory.\\n\", source);\n\t\treturn 0;\n\t}\n\n\treturn 1;\n}\n\nint main(int argc, char *argv[]) {\n\tint res;\n curl_global_init(CURL_GLOBAL_ALL);\n xmlInitParser();\n\n logStream = stdout;\n logLevel = LOG_DBG;\n\n\texcludeFilePattern = new FilePattern();\n\n if (!parseCommandline(argc, argv)) {\n \texit(1);\n }\n\n if (!verifySource(source)) {\n \texit(1);\n }\n\n AmazonCredentials *amazonCredentials = new AmazonCredentials(\n \taccessKeyId, \n \tsecretAccessKey,\n \tbucket, endPoint\n );\n\n\tRemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);\n remoteListOfFiles->showProgress = showProgress;\n if (skipSsl) {\n remoteListOfFiles->useSsl=0;\n }\n\n\tres = remoteListOfFiles->checkAuth();\n\tif (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {\n LOG(LOG_FATAL, \"[Auth] Failed: bucket doesn't exists, exit\");\n\t\texit(1);\t\t\n\t} else if (res == AUTH_FAILED) {\n\t\tLOG(LOG_FATAL, \"[Auth] FAIL, exit\");\n\t\texit(1);\t\t\n\t}\n LOG(LOG_INFO, \"[Auth] Success\");\n\n\tchar *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);\n\tLOG(LOG_DBG, \"[Storage] Database path = %s\", databaseFilePath);\n\n\tchar errorResult[1024*100];\n\tFileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);\n\tif (strlen(errorResult)>0) {\n\t\tLOG(LOG_FATAL, \"[Storage] FAIL: %s, exit\", errorResult);\n\t\texit(1);\n\t}\n\n\tif (performRebuild) {\n\t\tif (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (performUpload) {\n\t\tif (excludeFilePattern->count==0) {\n\t\t\tdelete excludeFilePattern;\n\t\t\texcludeFilePattern=NULL;\n\t\t}\n\n\t\tUploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);\n\t\tuploader->useRrs = useRrs;\n\t\tuploader->makeAllPublic = makeAllPublic;\n uploader->showProgress = showProgress;\n if (skipSsl) {\n uploader->useSsl=0;\n }\n uploader->dryRun = dryRun;\n\n\t\tres = uploader->uploadFiles(fileListStorage, source);\n\n\t\tif (res==UPLOAD_FAILED) {\n\t\t\texit(1);\n\t\t}\n\n\t\tres = uploader->uploadDatabase(databaseFilePath, databaseFilename);\n\t\tif (res==UPLOAD_FAILED) {\n\t\t\texit(1);\n\t\t}\n\n\t\tdelete uploader;\n\t}\n\n\tfree(databaseFilePath);\n\tdelete fileListStorage;\n\tdelete amazonCredentials;\n\n\texit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ncurses.h>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include \"key_listeners.hh\"\n#include \"file_contents.hh\"\n#include \"configuration.hh\"\n\nint main(int argc, char**argv) {\n argc--;argv++;\n\n initscr();\n noecho();\n raw();\n\n if(use_colors()) {\n start_color();\n }\n\n init_conf();\n\n std::vector<std::string> lines = std::vector<std::string>();\n if(argc) {\n std::string line;\n std::ifstream myfile(argv[0]);\n if(!myfile.good())\n lines.push_back(\"[Invalid file]\");\n else while(std::getline(myfile,line))\n lines.push_back(line);\n } else {\n lines.push_back(\"\");\n }\n\n init(lines);\n loop();\n\n endwin();\n return 0;\n}\n<commit_msg>Don't insert ``invalid file`` when new file.<commit_after>#include <ncurses.h>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include \"key_listeners.hh\"\n#include \"file_contents.hh\"\n#include \"configuration.hh\"\n\nint main(int argc, char**argv) {\n argc--;argv++;\n\n initscr();\n noecho();\n raw();\n\n if(use_colors()) {\n start_color();\n }\n\n init_conf();\n\n std::vector<std::string> lines = std::vector<std::string>();\n if(argc) {\n std::string line;\n std::ifstream myfile(argv[0]);\n if(!myfile.good())\n lines.push_back(\"\");\n else while(std::getline(myfile,line))\n lines.push_back(line);\n } else {\n lines.push_back(\"\");\n }\n\n init(lines);\n loop();\n\n endwin();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"pixeliterator.h\"\n#include \"assignment.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nAssignment::Assignment()\n{\n}\n\n\nAssignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nbool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {\n PixelIterator iterIn(_inputGC, box);\n PixelIterator iterOut(_outputGC, box);\n\n double v_in = 0;\n for_each(iterOut, iterOut.end(), [&](double& v){\n v_in = *iterIn;\n if ( v_in != rUNDEF) {\n v = v_in;\n }\n ++iterIn;\n ++iterOut;\n });\n return true;\n };\n\n bool res = OperationHelper::execute(Assign, _outputGC);\n\n if ( res && ctx != 0) {\n QVariant value;\n value.setValue<IGridCoverage>(_outputGC);\n ctx->_results.push_back(_outputGC->name());\n symTable.addSymbol(_outputGC->name(),0, itGRIDCOVERAGE,value);\n }\n return res;\n}\n\nIlwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new Assignment(metaid, expr);\n}\n\nIlwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)\n{\n if ( _expression.parameterCount() != 1) {\n ERROR3(ERR_ILLEGAL_NUM_PARM3,\"rasvalue\",\"1\",QString::number(_expression.parameterCount()));\n return sPREPAREFAILED;\n }\n\n QString gc = _expression.parm(0).value();\n if (!_inputGC.prepare(gc)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,gc,\"\");\n return sPREPAREFAILED;\n }\n OperationHelper helper;\n helper.initialize(_inputGC, _outputGC, _expression.parm(0),\n itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);\n return sPREPARED;\n}\n\nquint64 Assignment::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/assignment\");\n Resource res(QUrl(url), itOPERATIONMETADATA);\n res.addProperty(\"namespace\",\"ilwis\");\n res.addProperty(\"longname\",\"assignment\");\n res.addProperty(\"syntax\",\"assignment(gridcoverage)\");\n res.addProperty(\"inparameters\",\"1\");\n res.addProperty(\"pin_1_type\", itGRIDCOVERAGE);\n res.addProperty(\"pin_1_name\", TR(\"input gridcoverage\"));\n res.addProperty(\"pin_1_desc\",TR(\"input gridcoverage with any domain\"));\n res.addProperty(\"pout_1_type\", itGRIDCOVERAGE);\n res.addProperty(\"pout_1_name\", TR(\"copied object\"));\n res.addProperty(\"pout_1_desc\",TR(\"\"));\n res.prepare();\n url += \"=\" + QString::number(res.id());\n res.setUrl(url);\n\n mastercatalog()->addItems({res});\n return res.id();\n\n}\n<commit_msg>using alternate initialize function<commit_after>#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"pixeliterator.h\"\n#include \"mastercatalog.h\"\n#include \"assignment.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nAssignment::Assignment()\n{\n}\n\n\nAssignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nbool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {\n PixelIterator iterIn(_inputGC, box);\n PixelIterator iterOut(_outputGC, box);\n\n double v_in = 0;\n for_each(iterOut, iterOut.end(), [&](double& v){\n v_in = *iterIn;\n if ( v_in != rUNDEF) {\n v = v_in;\n }\n ++iterIn;\n ++iterOut;\n });\n return true;\n };\n\n bool res = OperationHelper::execute(Assign, _outputGC);\n\n if ( res && ctx != 0) {\n QVariant value;\n value.setValue<IGridCoverage>(_outputGC);\n ctx->_results.push_back(_outputGC->name());\n symTable.addSymbol(_outputGC->name(),0, itGRIDCOVERAGE,value);\n }\n return res;\n}\n\nIlwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new Assignment(metaid, expr);\n}\n\nIlwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)\n{\n if ( _expression.parameterCount() != 1) {\n ERROR3(ERR_ILLEGAL_NUM_PARM3,\"rasvalue\",\"1\",QString::number(_expression.parameterCount()));\n return sPREPAREFAILED;\n }\n\n QString coverage = _expression.parm(0).value();\n Resource res = mastercatalog()->name2Resource(coverage);\n if ( !res.isValid()) {\n ERROR1(ERR_COULD_NOT_OPEN_READING_1,coverage);\n return sPREPAREFAILED;\n }\n\/\/ if ( res.ilwisType() == itGRIDCOVERAGE) {\n\/\/ if (!_inputGC.prepare(coverage)) {\n\/\/ ERROR2(ERR_COULD_NOT_LOAD_2,coverage,\"\");\n\/\/ return sPREPAREFAILED;\n\/\/ }\n\/\/ } else if ( res.ilwisType() == itPOLYGONCOVERAGE) {\n\/\/ IIlwisObject ob;\n\/\/ ob.prepare(coverage, res.ilwisType());\n\/\/ }\n IIlwisObject objIn;\n objIn.prepare(coverage, res.ilwisType());\n OperationHelper helper;\n helper.initialize(objIn, res.ilwisType(), _expression.parm(0),\n itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);\n return sPREPARED;\n}\n\nquint64 Assignment::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/assignment\");\n Resource res(QUrl(url), itOPERATIONMETADATA);\n res.addProperty(\"namespace\",\"ilwis\");\n res.addProperty(\"longname\",\"assignment\");\n res.addProperty(\"syntax\",\"assignment(gridcoverage)\");\n res.addProperty(\"inparameters\",\"1\");\n res.addProperty(\"pin_1_type\", itGRIDCOVERAGE);\n res.addProperty(\"pin_1_name\", TR(\"input gridcoverage\"));\n res.addProperty(\"pin_1_desc\",TR(\"input gridcoverage with any domain\"));\n res.addProperty(\"pout_1_type\", itGRIDCOVERAGE);\n res.addProperty(\"pout_1_name\", TR(\"copied object\"));\n res.addProperty(\"pout_1_desc\",TR(\"\"));\n res.prepare();\n url += \"=\" + QString::number(res.id());\n res.setUrl(url);\n\n mastercatalog()->addItems({res});\n return res.id();\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files(the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions :\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n**\/\n\n#ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE\n\n#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS\n#include <exception>\n#endif \/\/ CONTINUABLE_WITH_NO_EXCEPTIONS\n\n#include <tuple>\n\n#include <test-continuable.hpp>\n\nnamespace std {\nnamespace experimental {\ntemplate <class... T>\nstruct coroutine_traits<void, T...> {\n struct promise_type {\n void get_return_object() {\n }\n\n void set_exception(exception_ptr const&) noexcept {\n }\n\n \/\/ FIXME This throws errors in MSVC but is required in clang\n#ifndef _MSC_VER\n void unhandled_exception() {\n GTEST_FATAL_FAILURE_(\"Unhandled async exception!\");\n }\n#endif \/\/ _MSC_VER\n\n suspend_never initial_suspend() noexcept {\n return {};\n }\n\n suspend_never final_suspend() noexcept {\n return {};\n }\n\n void return_void() noexcept {\n }\n };\n};\n} \/\/ namespace experimental\n} \/\/ namespace std\n\n\/\/\/ Resolves the given promise asynchonously\ntemplate <typename S, typename T>\nvoid resolve_async(S&& supplier, T&& promise) {\n \/\/ 0 args\n co_await supplier();\n\n \/\/ 1 args\n int a1 = co_await supplier(1);\n EXPECT_EQ(a1, 1);\n\n \/\/ 2-n args\n std::tuple<int, int> a2 = co_await supplier(1, 2);\n EXPECT_EQ(a2, std::make_tuple(1, 2));\n\n promise.set_value();\n co_return;\n}\n\nTYPED_TEST(single_dimension_tests, are_awaitable) {\n auto const& supply = [&](auto&&... args) {\n \/\/ Supplies the current tested continuable\n return this->supply(std::forward<decltype(args)>(args)...);\n };\n\n EXPECT_ASYNC_RESULT(\n this->supply().then(cti::make_continuable<void>([&](auto&& promise) {\n \/\/ Resolve the cotinuable through a coroutine\n resolve_async(supply, std::forward<decltype(promise)>(promise));\n })));\n}\n\n#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS\n\nstruct await_exception : std::exception {\n char const* what() const noexcept override {\n return \"await_exception\";\n }\n\n bool operator==(await_exception const&) const noexcept {\n return true;\n }\n};\n\n\/\/\/ Resolves the given promise asynchonously through an exception\ntemplate <typename S, typename T>\nvoid resolve_async_exceptional(S&& supplier, T&& promise) {\n \/\/ 0 args\n co_await supplier();\n\n \/\/ 1 args\n int a1 = co_await supplier(1);\n EXPECT_EQ(a1, 1);\n\n \/\/ 2-n args\n std::tuple<int, int> a2 = co_await supplier(1, 2);\n EXPECT_EQ(a2, std::make_tuple(1, 2));\n\n \/\/ GTest ASSERT_THROW isn't co_await friendly yet:\n \/\/ clang: 'return statement not allowed in coroutine; did you mean\n \/\/ 'co_return'?'\n EXPECT_THROW(co_await supplier().then([] { throw await_exception{}; }),\n await_exception);\n\n promise.set_value();\n co_return;\n}\n\nTYPED_TEST(single_dimension_tests, are_awaitable_with_exceptions) {\n auto const& supply = [&](auto&&... args) {\n \/\/ Supplies the current tested continuable\n return this->supply(std::forward<decltype(args)>(args)...);\n };\n\n ASSERT_ASYNC_COMPLETION(\n this->supply().then(cti::make_continuable<void>([&](auto&& promise) {\n \/\/ Resolve the cotinuable through a coroutine\n resolve_async_exceptional(supply,\n std::forward<decltype(promise)>(promise));\n })));\n}\n\n\/\/ TODO Implement this later\n\/\/\n\/\/ static cti::continuable<int> async_await() {\n\/\/ co_await cti::make_continuable<void>([](auto&& promise) {\n\/\/ \/\/ ...\n\/\/ promise.set_value();\n\/\/ });\n\/\/\n\/\/ co_return 1;\n\/\/ }\n\n#endif \/\/ CONTINUABLE_WITH_NO_EXCEPTIONS\n\n#endif \/\/ CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE\n<commit_msg>Address a MSVC compiler bug which prevents collapsing references in coroutines * Closes #2<commit_after>\n\/*\n Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files(the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions :\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n**\/\n\n#ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE\n\n#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS\n#include <exception>\n#endif \/\/ CONTINUABLE_WITH_NO_EXCEPTIONS\n\n#include <tuple>\n\n#include <test-continuable.hpp>\n\nnamespace std {\nnamespace experimental {\ntemplate <class... T>\nstruct coroutine_traits<void, T...> {\n struct promise_type {\n void get_return_object() {\n }\n\n void set_exception(exception_ptr const&) noexcept {\n }\n\n \/\/ FIXME This throws errors in MSVC but is required in clang\n#ifndef _MSC_VER\n void unhandled_exception() {\n GTEST_FATAL_FAILURE_(\"Unhandled async exception!\");\n }\n#endif \/\/ _MSC_VER\n\n suspend_never initial_suspend() noexcept {\n return {};\n }\n\n suspend_never final_suspend() noexcept {\n return {};\n }\n\n void return_void() noexcept {\n }\n };\n};\n} \/\/ namespace experimental\n} \/\/ namespace std\n\n\/\/\/ Resolves the given promise asynchonously\ntemplate <typename S, typename T>\nvoid resolve_async(S&& supplier, T promise) {\n \/\/ 0 args\n co_await supplier();\n\n \/\/ 1 args\n int a1 = co_await supplier(1);\n EXPECT_EQ(a1, 1);\n\n \/\/ 2-n args\n std::tuple<int, int> a2 = co_await supplier(1, 2);\n EXPECT_EQ(a2, std::make_tuple(1, 2));\n\n promise.set_value();\n co_return;\n}\n\nTYPED_TEST(single_dimension_tests, are_awaitable) {\n auto const& supply = [&](auto&&... args) {\n \/\/ Supplies the current tested continuable\n return this->supply(std::forward<decltype(args)>(args)...);\n };\n\n EXPECT_ASYNC_RESULT(\n this->supply().then(cti::make_continuable<void>([&](auto promise) {\n \/\/ Resolve the cotinuable through a coroutine\n resolve_async(supply, std::move(promise));\n })));\n}\n\n#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS\n\nstruct await_exception : std::exception {\n char const* what() const noexcept override {\n return \"await_exception\";\n }\n\n bool operator==(await_exception const&) const noexcept {\n return true;\n }\n};\n\n\/\/\/ Resolves the given promise asynchonously through an exception\ntemplate <typename S, typename T>\nvoid resolve_async_exceptional(S&& supplier, T promise) {\n \/\/ 0 args\n co_await supplier();\n\n \/\/ 1 args\n int a1 = co_await supplier(1);\n EXPECT_EQ(a1, 1);\n\n \/\/ 2-n args\n std::tuple<int, int> a2 = co_await supplier(1, 2);\n EXPECT_EQ(a2, std::make_tuple(1, 2));\n\n \/\/ GTest ASSERT_THROW isn't co_await friendly yet:\n \/\/ clang: 'return statement not allowed in coroutine; did you mean\n \/\/ 'co_return'?'\n EXPECT_THROW(co_await supplier().then([] { throw await_exception{}; }),\n await_exception);\n\n promise.set_value();\n co_return;\n}\n\nTYPED_TEST(single_dimension_tests, are_awaitable_with_exceptions) {\n auto const& supply = [&](auto&&... args) {\n \/\/ Supplies the current tested continuable\n return this->supply(std::forward<decltype(args)>(args)...);\n };\n\n ASSERT_ASYNC_COMPLETION(\n this->supply().then(cti::make_continuable<void>([&](auto promise) {\n \/\/ Resolve the cotinuable through a coroutine\n resolve_async_exceptional(supply, std::move(promise));\n })));\n}\n\n\/\/ TODO Implement this later\n\/\/\n\/\/ static cti::continuable<int> async_await() {\n\/\/ co_await cti::make_continuable<void>([](auto&& promise) {\n\/\/ \/\/ ...\n\/\/ promise.set_value();\n\/\/ });\n\/\/\n\/\/ co_return 1;\n\/\/ }\n\n#endif \/\/ CONTINUABLE_WITH_NO_EXCEPTIONS\n\n#endif \/\/ CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE\n<|endoftext|>"} {"text":"<commit_before>#include \"SDL.hh\"\r\n#include \"Logger.hh\"\r\nusing namespace RAGE;\r\nusing namespace RAGE::SDL;\r\n\r\nLogger Log(\"Test Events\");\r\n\r\nclass Console\r\n{\r\n\r\n\tfriend class MyEngine;\r\n\r\n\t\/\/if member embedded (object not reference), error when destructing Font...\r\n\t\/\/to debug -> copy \/ deletion problem\r\n\tconst Font _font;\r\n\r\n\tColor _bgColor;\r\n\r\n\tRGBSurface * surf;\r\n\r\n\tstd::string text;\r\n\r\npublic :\r\n\tConsole(const Font & fnt = Font(),Color c = Color(0,0,0)) :_font(fnt),_bgColor(c),surf(NULL),text(\">\")\r\n\t{\r\n\t\t\/\/init();\r\n\t\t\/\/draw();\r\n\t}\r\n\r\n\tbool init(int width, int height)\r\n\t{\r\n\t\tsurf = new RGBSurface(_bgColor,width,height,8); \/\/8 as magic number for minimum bpp.\r\n\t\tif (surf == NULL) return false;\r\n\t\tsurf->optimise(); \/\/ Doesnt matter anyway we match the display one here.\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/WARNING : BUG here if trying to set to fullscreen using F6, then error, then trying to resize -> crash\r\n\tbool resize(int width, int height,bool keepcontent = true)\r\n\t{\r\n\t\tbool res = surf->resize(width,height,false);\r\n\t\tdraw();\r\n\t\treturn res;\r\n\t}\r\n\r\n\tvoid print(const std::string & newtext)\r\n\t{\r\n\t\ttext += newtext;\r\n\t\tdraw();\r\n\t}\r\n\r\n\tvoid add(char newchar)\r\n\t{\r\n\t\tif (newchar != '\\0')\r\n\t\t\ttext += newchar;\r\n\t\tdraw();\r\n\t}\r\n\r\n\tvoid draw()\r\n\t{\r\n\t\tstd::auto_ptr<RGBSurface> textsurf = _font.render(text,Color(255,255,255),Font::Solid);\r\n\t\tassert(textsurf.get());\r\n\t\tsurf->fill(_bgColor);\r\n\t\tsurf->blit(*textsurf);\r\n\t}\r\n\r\n\t~Console()\r\n\t{\r\n\t\tif (surf != NULL)\r\n\t\t\tdelete surf,surf = NULL;\r\n\t}\r\n\r\n\r\n};\r\n\r\n\/\/Defining general EventHandler\r\nclass MyGeneralHandler : public GeneralHandler\r\n{\r\n\tfriend class EventManager;\r\n bool _quitRequested;\r\n\r\n public:\r\n\r\n GeneralHandler() : _quitRequested(false)\r\n {}\r\n virtual ~GeneralHandler()\r\n {}\r\n\r\n \/\/Callbacks on Window \/ Display events\r\n virtual bool handleActiveEvent(bool gain, bool active, bool inputfocus, bool mousefocus)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n virtual bool handleResizeEvent(int w, int h)\r\n\t\t{\r\n\t\t\tApp::getInstance().getWindow().resizeDisplay(w,h);\r\n \t\treturn true;\r\n\t\t}\r\n virtual bool handleExposeEvent()\r\n\t\t{\r\n\t\t\t return false;\r\n\t\t}\r\n \/\/callback on platform-dependent windows manager event\r\n virtual bool handleSysWMEvent(void)\r\n {\r\n return false;\r\n }\r\n\r\n \/\/Callback on other Events\r\n\t virtual bool handleUserEvent(Event::Type type, int code, void* data1, void* data2)\r\n {\r\n return false;\r\n }\r\n\r\n\r\n \/\/Callback on Quit Event\r\n virtual bool handleQuitEvent(void)\r\n\t\t{\r\n \t\t_quitRequested=true;\r\n \t\treturn true;\r\n\t\t}\r\n \/\/Catch-all callback\r\n virtual bool handleEvent(Event &event)\r\n\t\t{\r\n#if (DEBUG ==2)\r\n \/\/Getting the details of the Event\r\n Log << nl << \"Last chance handler : \" << cevent.getType() << std::endl;\r\n return true;\r\n#else\r\n\r\n return false;\r\n#endif\r\n\t\t}\r\n\r\n};\r\n\r\n\/\/Defining UserInput\r\nclass MyUserInput : public TextInput\r\n{\r\npublic:\r\n\r\n\tConsole *cons;\r\n\r\n\tMyUserInput() : TextInput(), cons(NULL) {}\r\n\r\n\tvoid setConsole (Console * newcons)\r\n\t{\r\n\t\tcons = newcons;\r\n\t}\r\n\r\n virtual bool handleKeyEvent (const Sym &s, bool pressed)\r\n {\r\n bool res = false;\r\n switch( s.getKey() )\r\n {\r\n case KEscape:\r\n if (pressed==false)\r\n {\r\n#ifdef DEBUG\r\n Log << nl << \"Quit requested !\" << std::endl;\r\n#endif\r\n\r\n _quitRequested=true;\r\n res=true;\r\n }\r\n break;\r\n case KF5:\r\n if (pressed==true)\r\n App::getInstance().getWindow().iconify();\r\n res = true;\r\n break;\r\n\t\t\t\tcase KF6:\r\n if (pressed==true)\r\n App::getInstance().getWindow().setFullscreen(!App::getInstance().getWindow().isFullscreen());\r\n res = true;\r\n break;\r\n\t\t\t\tdefault: if (pressed == true) cons->add(s.getChar());\r\n res = true;\r\n }\r\n return res;\r\n }\r\n};\r\n\r\nclass MyEngine : public DefaultEngine\r\n{\r\n\r\npublic:\r\n\r\n\tPoint consolePos;\r\n\tConsole * console;\r\n\tstd::auto_ptr<RGBSurface> HelpMsg;\r\n\t\t\r\n\tMyEngine() : consolePos(0,0), console (NULL), HelpMsg(0)\r\n\t{}\r\n\r\n\tvoid setConsole( Console * cons ) { console = cons;}\r\n\r\n virtual ~MyEngine()\r\n\t{\r\n\t}\r\n\r\n\tbool init(int width, int height)\r\n\t{\r\n\t\tDefaultEngine::init(width,height);\r\n\t\tconsole->init(width,height - 2 * DefaultEngine::_logo.getHeight());\r\n\t\tconsolePos.sety(DefaultEngine::_logo.getHeight());\r\n\t\tHelpMsg = console->_font.render(\"Plz Use Keyboard To Write Text Down\", Color(0xFF, 0xFF, 0xFF), Font::Shaded, Color(0, 0, 0));\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool resize(int width, int height)\r\n\t{\r\n\t\tDefaultEngine::resize(width,height);\r\n\t\tconsole->resize(width,height - 2 * DefaultEngine::_logo.getHeight());\r\n\t\tconsolePos.sety(DefaultEngine::_logo.getHeight());\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvoid prerender()\r\n\t{\r\n\t\t\/\/nothing for now\r\n\t}\r\n\r\n\tvoid render(VideoSurface & screen) const\r\n {\r\n\t\tDefaultEngine::render(screen);\r\n\r\n\t\tif (HelpMsg.get()) \r\n\t\t\tscreen.blit( *HelpMsg, Point::Point(5, 5) );\r\n\r\n\t\tif (console !=NULL)\r\n\t\t\tscreen.blit(*(console->surf),consolePos);\r\n }\r\n\r\n\tvoid postrender()\r\n\t{\r\n\t\t\/\/nothing for now\r\n\t}\r\n};\r\n\r\n\r\n\/\/Main Program\r\nint main(int argc, char** argv)\r\n{\r\n\r\n Logger testlog(\"Test Log\");\r\n\r\n \/\/Setup example\r\n\r\n testlog << nl << \" Enabling SDL Video... \" << std::endl;\r\n\tApp::getInstance().setName (\"RAGE::SDL test - Font\");\r\n App::getInstance().initVideo(false,false,false,false);\r\n\tApp::getInstance().initText();\r\n\r\n testlog << nl << \" Creating the User Interface... \" << std::endl;\r\n \r\n App::getInstance().getWindow().setBGColor(Color (64,0,0));\r\n\r\n Font font;\r\n \r\n if (argc > 1)\r\n {\r\n\t\/\/specific font\r\n\tfont.setTTF(argv[1],24);\r\n }\r\n\r\n\tConsole cons(font);\r\n\tMyEngine engine;\r\n\tengine.setConsole(&cons);\r\n\t\r\n \/\/UI Creation\r\n MyUserInput ui;\r\n\tui.setConsole(&cons);\r\n MyGeneralHandler gh;\r\n App::getInstance().getWindow().getEventManager().setKeyboard(&ui);\r\n App::getInstance().getWindow().getEventManager().setGeneralHandler(&gh);\r\n\r\n\r\n\t\/\/without this line the default engine is used\r\n App::getInstance().getWindow().setEngine(&engine);\r\n\r\n\r\n if (! (App::getInstance().getWindow().resetDisplay()))\r\n {\r\n testlog << nl << \"Display Creation FAILED !\"<< std::endl;\r\n exit(0);\r\n }\r\n else\r\n {\r\n App::getInstance().getWindow().mainLoop();\r\n }\r\n \r\n return 0;\r\n}\r\n\r\n\r\n<commit_msg>fix to build...<commit_after>#include \"SDL.hh\"\r\n#include \"Logger.hh\"\r\nusing namespace RAGE;\r\nusing namespace RAGE::SDL;\r\n\r\nLogger Log(\"Test Events\");\r\n\r\nclass Console\r\n{\r\n\r\n\tfriend class MyEngine;\r\n\r\n\t\/\/if member embedded (object not reference), error when destructing Font...\r\n\t\/\/to debug -> copy \/ deletion problem\r\n\tconst Font _font;\r\n\r\n\tColor _bgColor;\r\n\r\n\tRGBSurface * surf;\r\n\r\n\tstd::string text;\r\n\r\npublic :\r\n\tConsole(const Font & fnt = Font(),Color c = Color(0,0,0)) :_font(fnt),_bgColor(c),surf(NULL),text(\">\")\r\n\t{\r\n\t\t\/\/init();\r\n\t\t\/\/draw();\r\n\t}\r\n\r\n\tbool init(int width, int height)\r\n\t{\r\n\t\tsurf = new RGBSurface(_bgColor,width,height,8); \/\/8 as magic number for minimum bpp.\r\n\t\tif (surf == NULL) return false;\r\n\t\tsurf->optimise(); \/\/ Doesnt matter anyway we match the display one here.\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/WARNING : BUG here if trying to set to fullscreen using F6, then error, then trying to resize -> crash\r\n\tbool resize(int width, int height,bool keepcontent = true)\r\n\t{\r\n\t\tbool res = surf->resize(width,height,false);\r\n\t\tdraw();\r\n\t\treturn res;\r\n\t}\r\n\r\n\tvoid print(const std::string & newtext)\r\n\t{\r\n\t\ttext += newtext;\r\n\t\tdraw();\r\n\t}\r\n\r\n\tvoid add(char newchar)\r\n\t{\r\n\t\tif (newchar != '\\0')\r\n\t\t\ttext += newchar;\r\n\t\tdraw();\r\n\t}\r\n\r\n\tvoid draw()\r\n\t{\r\n\t\tstd::auto_ptr<RGBSurface> textsurf = _font.render(text,Color(255,255,255),Font::Solid);\r\n\t\tassert(textsurf.get());\r\n\t\tsurf->fill(_bgColor);\r\n\t\tsurf->blit(*textsurf);\r\n\t}\r\n\r\n\t~Console()\r\n\t{\r\n\t\tif (surf != NULL)\r\n\t\t\tdelete surf,surf = NULL;\r\n\t}\r\n\r\n\r\n};\r\n\r\n\/\/Defining general EventHandler\r\nclass MyGeneralHandler : public GeneralHandler\r\n{\r\n\tfriend class EventManager;\r\n bool _quitRequested;\r\n\r\n public:\r\n\r\n\t\t\t\/\/Callbacks on Window \/ Display events\r\n virtual bool handleActiveEvent(bool gain, bool active, bool inputfocus, bool mousefocus)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n virtual bool handleResizeEvent(int w, int h)\r\n\t\t{\r\n\t\t\tApp::getInstance().getWindow().resizeDisplay(w,h);\r\n \t\treturn true;\r\n\t\t}\r\n virtual bool handleExposeEvent()\r\n\t\t{\r\n\t\t\t return false;\r\n\t\t}\r\n \/\/callback on platform-dependent windows manager event\r\n virtual bool handleSysWMEvent(void)\r\n {\r\n return false;\r\n }\r\n\r\n \/\/Callback on other Events\r\n\t virtual bool handleUserEvent(Event::Type type, int code, void* data1, void* data2)\r\n {\r\n return false;\r\n }\r\n\r\n\r\n \/\/Callback on Quit Event\r\n virtual bool handleQuitEvent(void)\r\n\t\t{\r\n \t\t_quitRequested=true;\r\n \t\treturn true;\r\n\t\t}\r\n \/\/Catch-all callback\r\n virtual bool handleEvent(Event &event)\r\n\t\t{\r\n#if (DEBUG ==2)\r\n \/\/Getting the details of the Event\r\n Log << nl << \"Last chance handler : \" << cevent.getType() << std::endl;\r\n return true;\r\n#else\r\n\r\n return false;\r\n#endif\r\n\t\t}\r\n\r\n};\r\n\r\n\/\/Defining UserInput\r\nclass MyUserInput : public TextInput\r\n{\r\npublic:\r\n\r\n\tConsole *cons;\r\n\r\n\tMyUserInput() : TextInput(), cons(NULL) {}\r\n\r\n\tvoid setConsole (Console * newcons)\r\n\t{\r\n\t\tcons = newcons;\r\n\t}\r\n\r\n virtual bool handleKeyEvent (const Sym &s, bool pressed)\r\n {\r\n bool res = false;\r\n switch( s.getKey() )\r\n {\r\n case KEscape:\r\n if (pressed==false)\r\n {\r\n#ifdef DEBUG\r\n Log << nl << \"Quit requested !\" << std::endl;\r\n#endif\r\n\r\n _quitRequested=true;\r\n res=true;\r\n }\r\n break;\r\n case KF5:\r\n if (pressed==true)\r\n App::getInstance().getWindow().iconify();\r\n res = true;\r\n break;\r\n\t\t\t\tcase KF6:\r\n if (pressed==true)\r\n App::getInstance().getWindow().setFullscreen(!App::getInstance().getWindow().isFullscreen());\r\n res = true;\r\n break;\r\n\t\t\t\tdefault: if (pressed == true) cons->add(s.getChar());\r\n res = true;\r\n }\r\n return res;\r\n }\r\n};\r\n\r\nclass MyEngine : public DefaultEngine\r\n{\r\n\r\npublic:\r\n\r\n\tPoint consolePos;\r\n\tConsole * console;\r\n\tstd::auto_ptr<RGBSurface> HelpMsg;\r\n\t\t\r\n\tMyEngine() : consolePos(0,0), console (NULL), HelpMsg(0)\r\n\t{}\r\n\r\n\tvoid setConsole( Console * cons ) { console = cons;}\r\n\r\n virtual ~MyEngine()\r\n\t{\r\n\t}\r\n\r\n\tbool init(int width, int height)\r\n\t{\r\n\t\tDefaultEngine::init(width,height);\r\n\t\tconsole->init(width,height - 2 * DefaultEngine::_logo.getHeight());\r\n\t\tconsolePos.sety(DefaultEngine::_logo.getHeight());\r\n\t\tHelpMsg = console->_font.render(\"Plz Use Keyboard To Write Text Down\", Color(0xFF, 0xFF, 0xFF), Font::Shaded, Color(0, 0, 0));\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool resize(int width, int height)\r\n\t{\r\n\t\tDefaultEngine::resize(width,height);\r\n\t\tconsole->resize(width,height - 2 * DefaultEngine::_logo.getHeight());\r\n\t\tconsolePos.sety(DefaultEngine::_logo.getHeight());\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvoid prerender()\r\n\t{\r\n\t\t\/\/nothing for now\r\n\t}\r\n\r\n\tvoid render(VideoSurface & screen) const\r\n {\r\n\t\tDefaultEngine::render(screen);\r\n\r\n\t\tif (HelpMsg.get()) \r\n\t\t\tscreen.blit( *HelpMsg, Point::Point(5, 5) );\r\n\r\n\t\tif (console !=NULL)\r\n\t\t\tscreen.blit(*(console->surf),consolePos);\r\n }\r\n\r\n\tvoid postrender()\r\n\t{\r\n\t\t\/\/nothing for now\r\n\t}\r\n};\r\n\r\n\r\n\/\/Main Program\r\nint main(int argc, char** argv)\r\n{\r\n\r\n Logger testlog(\"Test Log\");\r\n\r\n \/\/Setup example\r\n\r\n testlog << nl << \" Enabling SDL Video... \" << std::endl;\r\n\tApp::getInstance().setName (\"RAGE::SDL test - Font\");\r\n App::getInstance().initVideo(false,false,false,false);\r\n\tApp::getInstance().initText();\r\n\r\n testlog << nl << \" Creating the User Interface... \" << std::endl;\r\n \r\n App::getInstance().getWindow().setBGColor(Color (64,0,0));\r\n\r\n Font font;\r\n \r\n if (argc > 1)\r\n {\r\n\t\/\/specific font\r\n\tfont.setTTF(argv[1],24);\r\n }\r\n\r\n\tConsole cons(font);\r\n\tMyEngine engine;\r\n\tengine.setConsole(&cons);\r\n\t\r\n \/\/UI Creation\r\n MyUserInput ui;\r\n\tui.setConsole(&cons);\r\n MyGeneralHandler gh;\r\n App::getInstance().getWindow().getEventManager().setKeyboard(&ui);\r\n App::getInstance().getWindow().getEventManager().setGeneralHandler(&gh);\r\n\r\n\r\n\t\/\/without this line the default engine is used\r\n App::getInstance().getWindow().setEngine(&engine);\r\n\r\n\r\n if (! (App::getInstance().getWindow().resetDisplay()))\r\n {\r\n testlog << nl << \"Display Creation FAILED !\"<< std::endl;\r\n exit(0);\r\n }\r\n else\r\n {\r\n App::getInstance().getWindow().mainLoop();\r\n }\r\n \r\n return 0;\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/image\/image.hpp\"\n#include \"openMVG\/features\/features.hpp\"\n\n\/\/\/ Generic Image Collection image matching\n#include \"software\/SfM\/ImageCollectionMatcher_AllInMemory.hpp\"\n#include \"software\/SfM\/ImageCollectionGeometricFilter.hpp\"\n#include \"software\/SfM\/ImageCollection_F_ACRobust.hpp\"\n#include \"software\/SfM\/pairwiseAdjacencyDisplay.hpp\"\n#include \"software\/SfM\/SfMIOHelper.hpp\"\n#include \"openMVG\/matching\/matcher_brute_force.hpp\"\n#include \"openMVG\/matching\/matcher_kdtree_flann.hpp\"\n#include \"openMVG\/matching\/indMatch_utils.hpp\"\n\n\/\/\/ Generic Image Collection image matching\n#include \"software\/SfM\/ImageCollectionMatcher_AllInMemory.hpp\"\n#include \"software\/SfM\/ImageCollectionGeometricFilter.hpp\"\n#include \"software\/SfM\/ImageCollection_F_ACRobust.hpp\"\n#include \"software\/SfM\/pairwiseAdjacencyDisplay.hpp\"\n\n\/\/\/ Feature detector and descriptor interface\n#include \"patented\/sift\/SIFT.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n#include \"third_party\/progress\/progress.hpp\"\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n\nusing namespace openMVG;\nusing namespace openMVG::matching;\nusing namespace openMVG::robust;\nusing namespace std;\n\nint main(int argc, char **argv)\n{\n CmdLine cmd;\n\n std::string sImaDirectory;\n std::string sOutDir = \"\";\n float fDistRatio = .6f;\n bool bOctMinus1 = false;\n size_t coefZoom = 1;\n float dPeakThreshold = 0.04f;\n\n cmd.add( make_option('i', sImaDirectory, \"imadir\") );\n cmd.add( make_option('o', sOutDir, \"outdir\") );\n cmd.add( make_option('r', fDistRatio, \"distratio\") );\n cmd.add( make_option('s', bOctMinus1, \"octminus1\") );\n cmd.add( make_option('p', dPeakThreshold, \"peakThreshold\") );\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << ' '\n << \"[-i|--imadir path] \"\n << \"[-o|--outdir path] \"\n << \"[-r|--distratio 0.6] \"\n << \"[-s|--octminus1 0 or 1] \"\n << \"[-p|--peakThreshold 0.04 -> 0.01] \"\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \" You called : \" <<std::endl\n << argv[0] << std::endl\n << \"--imadir \" << sImaDirectory << std::endl\n << \"--outdir \" << sOutDir << std::endl\n << \"--distratio \" << fDistRatio << std::endl\n << \"--octminus1 \" << bOctMinus1 << std::endl\n << \"--peakThreshold \" << dPeakThreshold << std::endl;\n\n if (sOutDir.empty()) {\n std::cerr << \"\\nIt is an invalid output directory\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ -----------------------------\n \/\/ a. List images\n \/\/ b. Compute features and descriptor\n \/\/ c. Compute putatives descriptor matches\n \/\/ d. Geometric filtering of putatives matches\n \/\/ e. Export some statistics\n \/\/ -----------------------------\n\n \/\/ Create output dir\n if (!stlplus::folder_exists(sOutDir))\n stlplus::folder_create( sOutDir );\n\n \/\/---------------------------------------\n \/\/ a. List images\n \/\/---------------------------------------\n std::string sListsFile = stlplus::create_filespec( sOutDir,\n \"lists.txt\" ).c_str();\n if (!stlplus::is_file(sListsFile) )\n {\n std::cerr << std::endl\n << \"The input matching\/lists.txt is missing\" << std::endl;\n return false;\n }\n\n std::vector<openMVG::SfMIO::CameraInfo> vec_camImageName;\n std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;\n if (!openMVG::SfMIO::loadImageList( vec_camImageName,\n vec_focalGroup,\n sListsFile) )\n {\n std::cerr << \"\\nEmpty image list.\" << std::endl;\n return false;\n }\n\n std::vector<std::string> vec_fileNames;\n std::vector<std::pair<size_t, size_t> > vec_imagesSize;\n for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator iter_camInfo = vec_camImageName.begin();\n iter_camInfo != vec_camImageName.end();\n iter_camInfo++ )\n {\n vec_imagesSize.push_back( std::make_pair( vec_focalGroup[iter_camInfo->m_intrinsicId].m_w,\n vec_focalGroup[iter_camInfo->m_intrinsicId].m_h ) );\n vec_fileNames.push_back( stlplus::create_filespec( sImaDirectory, iter_camInfo->m_sImageName) );\n }\n\n \/\/---------------------------------------\n \/\/ b. Compute features and descriptor\n \/\/ - extract sift features and descriptor\n \/\/ - if keypoints already computed, re-load them\n \/\/ - else save features and descriptors on disk\n \/\/---------------------------------------\n\n typedef Descriptor<float, 128> DescriptorT;\n typedef SIOPointFeature FeatureT;\n typedef std::vector<FeatureT> FeatsT;\n typedef vector<DescriptorT > DescsT;\n typedef KeypointSet<FeatsT, DescsT > KeypointSetT;\n\n {\n std::cout << \"\\n\\nEXTRACT FEATURES\" << std::endl;\n vec_imagesSize.resize(vec_fileNames.size());\n\n Image<RGBColor> imageRGB;\n Image<unsigned char> imageGray;\n\n C_Progress_display my_progress_bar( vec_fileNames.size() );\n for(size_t i=0; i < vec_fileNames.size(); ++i) {\n KeypointSetT kpSet;\n\n std::string sFeat = stlplus::create_filespec(sOutDir,\n stlplus::basename_part(vec_fileNames[i]), \"feat\");\n std::string sDesc = stlplus::create_filespec(sOutDir,\n stlplus::basename_part(vec_fileNames[i]), \"desc\");\n\n \/\/Test if descriptor and feature was already computed\n if (stlplus::file_exists(sFeat) && stlplus::file_exists(sDesc)) {\n\n if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {\n vec_imagesSize[i] = make_pair(imageRGB.Width(), imageRGB.Height());\n }\n else {\n ReadImage(vec_fileNames[i].c_str(), &imageGray);\n vec_imagesSize[i] = make_pair(imageGray.Width(), imageGray.Height());\n }\n }\n else { \/\/Not already computed, so compute and save\n\n if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {\n Rgb2Gray(imageRGB, &imageGray);\n }\n else{\n ReadImage(vec_fileNames[i].c_str(), &imageGray);\n }\n\n \/\/ Compute features and descriptors and export them to file\n SIFTDetector(imageGray,\n kpSet.features(), kpSet.descriptors(),\n bOctMinus1, true, dPeakThreshold);\n \n kpSet.saveToBinFile(sFeat, sDesc);\n vec_imagesSize[i] = make_pair(imageGray.Width(), imageRGB.Height());\n }\n ++my_progress_bar;\n }\n }\n\n\n\n \/\/---------------------------------------\n \/\/ c. Compute putatives descriptor matches\n \/\/ - L2 descriptor matching\n \/\/ - Keep correspondences only if NearestNeighbor ratio is ok\n \/\/---------------------------------------\n IndexedMatchPerPair map_PutativesMatches;\n \/\/ Define the matcher and the used metric (Squared L2)\n \/\/ ANN matcher could be defined as follow:\n typedef flann::L2<DescriptorT::bin_type> MetricT;\n typedef ArrayMatcher_Kdtree_Flann<DescriptorT::bin_type, MetricT> MatcherT;\n \/\/ Brute force matcher is defined as following:\n \/\/typedef L2_Vectorized<DescriptorT::bin_type> MetricT;\n \/\/typedef ArrayMatcherBruteForce<DescriptorT::bin_type, MetricT> MatcherT;\n\n \/\/ If the matches already exists, reload them\n if (stlplus::file_exists(sOutDir + \"\/matches.putative.txt\"))\n {\n PairedIndMatchImport(sOutDir + \"\/matches.putative.txt\", map_PutativesMatches);\n std::cout << std::endl << \"PUTATIVE MATCHES -- PREVIOUS RESULTS LOADED\" << std::endl;\n }\n else \/\/ Compute the putatives matches\n {\n ImageCollectionMatcher_AllInMemory<KeypointSetT, MatcherT> collectionMatcher(fDistRatio);\n if (collectionMatcher.loadData(vec_fileNames, sOutDir))\n {\n std::cout << std::endl << \"PUTATIVE MATCHES\" << std::endl;\n collectionMatcher.Match(vec_fileNames, map_PutativesMatches);\n \/\/---------------------------------------\n \/\/-- Export putative matches\n \/\/---------------------------------------\n std::ofstream file (std::string(sOutDir + \"\/matches.putative.txt\").c_str());\n if (file.is_open())\n PairedIndMatchToStream(map_PutativesMatches, file);\n file.close();\n }\n }\n \/\/-- export putative matches Adjacency matrix\n PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),\n map_PutativesMatches,\n stlplus::create_filespec(sOutDir, \"PutativeAdjacencyMatrix\", \"svg\"));\n\n\n \/\/---------------------------------------\n \/\/ d. Geometric filtering of putatives matches\n \/\/ - AContrario Estimation of the Fundamental matrix\n \/\/ - Use a upper bound for the plausible F matrix\n \/\/ acontrario estimated threshold\n \/\/---------------------------------------\n IndexedMatchPerPair map_GeometricMatches_F;\n\n GeometricFilter_FMatrix_AC geomFilter_F_AC(4.0);\n ImageCollectionGeometricFilter<FeatureT, GeometricFilter_FMatrix_AC> collectionGeomFilter;\n if (collectionGeomFilter.loadData(vec_fileNames, sOutDir))\n {\n std::cout << std::endl << \" - GEOMETRIC FILTERING - \" << std::endl;\n collectionGeomFilter.Filter(\n geomFilter_F_AC,\n map_PutativesMatches,\n map_GeometricMatches_F,\n vec_imagesSize);\n\n \/\/---------------------------------------\n \/\/-- Export geometric filtered matches\n \/\/---------------------------------------\n std::ofstream file (string(sOutDir + \"\/matches.f.txt\").c_str());\n if (file.is_open())\n PairedIndMatchToStream(map_GeometricMatches_F, file);\n file.close();\n\n \/\/-- export Adjacency matrix\n std::cout << \"\\n Export Adjacency Matrix of the pairwise's Epipolar matches\"\n << std::endl;\n PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),\n map_GeometricMatches_F,\n stlplus::create_filespec(sOutDir, \"EpipolarAdjacencyMatrix\", \"svg\"));\n }\n return EXIT_SUCCESS;\n}\n\n\n<commit_msg>Fix hardcoded path in error message<commit_after>\n\/\/ Copyright (c) 2012, 2013 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/image\/image.hpp\"\n#include \"openMVG\/features\/features.hpp\"\n\n\/\/\/ Generic Image Collection image matching\n#include \"software\/SfM\/ImageCollectionMatcher_AllInMemory.hpp\"\n#include \"software\/SfM\/ImageCollectionGeometricFilter.hpp\"\n#include \"software\/SfM\/ImageCollection_F_ACRobust.hpp\"\n#include \"software\/SfM\/pairwiseAdjacencyDisplay.hpp\"\n#include \"software\/SfM\/SfMIOHelper.hpp\"\n#include \"openMVG\/matching\/matcher_brute_force.hpp\"\n#include \"openMVG\/matching\/matcher_kdtree_flann.hpp\"\n#include \"openMVG\/matching\/indMatch_utils.hpp\"\n\n\/\/\/ Generic Image Collection image matching\n#include \"software\/SfM\/ImageCollectionMatcher_AllInMemory.hpp\"\n#include \"software\/SfM\/ImageCollectionGeometricFilter.hpp\"\n#include \"software\/SfM\/ImageCollection_F_ACRobust.hpp\"\n#include \"software\/SfM\/pairwiseAdjacencyDisplay.hpp\"\n\n\/\/\/ Feature detector and descriptor interface\n#include \"patented\/sift\/SIFT.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n#include \"third_party\/progress\/progress.hpp\"\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n\nusing namespace openMVG;\nusing namespace openMVG::matching;\nusing namespace openMVG::robust;\nusing namespace std;\n\nint main(int argc, char **argv)\n{\n CmdLine cmd;\n\n std::string sImaDirectory;\n std::string sOutDir = \"\";\n float fDistRatio = .6f;\n bool bOctMinus1 = false;\n size_t coefZoom = 1;\n float dPeakThreshold = 0.04f;\n\n cmd.add( make_option('i', sImaDirectory, \"imadir\") );\n cmd.add( make_option('o', sOutDir, \"outdir\") );\n cmd.add( make_option('r', fDistRatio, \"distratio\") );\n cmd.add( make_option('s', bOctMinus1, \"octminus1\") );\n cmd.add( make_option('p', dPeakThreshold, \"peakThreshold\") );\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << ' '\n << \"[-i|--imadir path] \"\n << \"[-o|--outdir path] \"\n << \"[-r|--distratio 0.6] \"\n << \"[-s|--octminus1 0 or 1] \"\n << \"[-p|--peakThreshold 0.04 -> 0.01] \"\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \" You called : \" <<std::endl\n << argv[0] << std::endl\n << \"--imadir \" << sImaDirectory << std::endl\n << \"--outdir \" << sOutDir << std::endl\n << \"--distratio \" << fDistRatio << std::endl\n << \"--octminus1 \" << bOctMinus1 << std::endl\n << \"--peakThreshold \" << dPeakThreshold << std::endl;\n\n if (sOutDir.empty()) {\n std::cerr << \"\\nIt is an invalid output directory\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ -----------------------------\n \/\/ a. List images\n \/\/ b. Compute features and descriptor\n \/\/ c. Compute putatives descriptor matches\n \/\/ d. Geometric filtering of putatives matches\n \/\/ e. Export some statistics\n \/\/ -----------------------------\n\n \/\/ Create output dir\n if (!stlplus::folder_exists(sOutDir))\n stlplus::folder_create( sOutDir );\n\n \/\/---------------------------------------\n \/\/ a. List images\n \/\/---------------------------------------\n std::string sListsFile = stlplus::create_filespec( sOutDir,\n \"lists.txt\" ).c_str();\n if (!stlplus::is_file(sListsFile) )\n {\n std::cerr << std::endl\n << \"The input file \\\"\"<< sListsFile << \"\\\" is missing\" << std::endl;\n return false;\n }\n\n std::vector<openMVG::SfMIO::CameraInfo> vec_camImageName;\n std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;\n if (!openMVG::SfMIO::loadImageList( vec_camImageName,\n vec_focalGroup,\n sListsFile) )\n {\n std::cerr << \"\\nEmpty image list.\" << std::endl;\n return false;\n }\n\n std::vector<std::string> vec_fileNames;\n std::vector<std::pair<size_t, size_t> > vec_imagesSize;\n for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator iter_camInfo = vec_camImageName.begin();\n iter_camInfo != vec_camImageName.end();\n iter_camInfo++ )\n {\n vec_imagesSize.push_back( std::make_pair( vec_focalGroup[iter_camInfo->m_intrinsicId].m_w,\n vec_focalGroup[iter_camInfo->m_intrinsicId].m_h ) );\n vec_fileNames.push_back( stlplus::create_filespec( sImaDirectory, iter_camInfo->m_sImageName) );\n }\n\n \/\/---------------------------------------\n \/\/ b. Compute features and descriptor\n \/\/ - extract sift features and descriptor\n \/\/ - if keypoints already computed, re-load them\n \/\/ - else save features and descriptors on disk\n \/\/---------------------------------------\n\n typedef Descriptor<float, 128> DescriptorT;\n typedef SIOPointFeature FeatureT;\n typedef std::vector<FeatureT> FeatsT;\n typedef vector<DescriptorT > DescsT;\n typedef KeypointSet<FeatsT, DescsT > KeypointSetT;\n\n {\n std::cout << \"\\n\\nEXTRACT FEATURES\" << std::endl;\n vec_imagesSize.resize(vec_fileNames.size());\n\n Image<RGBColor> imageRGB;\n Image<unsigned char> imageGray;\n\n C_Progress_display my_progress_bar( vec_fileNames.size() );\n for(size_t i=0; i < vec_fileNames.size(); ++i) {\n KeypointSetT kpSet;\n\n std::string sFeat = stlplus::create_filespec(sOutDir,\n stlplus::basename_part(vec_fileNames[i]), \"feat\");\n std::string sDesc = stlplus::create_filespec(sOutDir,\n stlplus::basename_part(vec_fileNames[i]), \"desc\");\n\n \/\/Test if descriptor and feature was already computed\n if (stlplus::file_exists(sFeat) && stlplus::file_exists(sDesc)) {\n\n if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {\n vec_imagesSize[i] = make_pair(imageRGB.Width(), imageRGB.Height());\n }\n else {\n ReadImage(vec_fileNames[i].c_str(), &imageGray);\n vec_imagesSize[i] = make_pair(imageGray.Width(), imageGray.Height());\n }\n }\n else { \/\/Not already computed, so compute and save\n\n if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {\n Rgb2Gray(imageRGB, &imageGray);\n }\n else{\n ReadImage(vec_fileNames[i].c_str(), &imageGray);\n }\n\n \/\/ Compute features and descriptors and export them to file\n SIFTDetector(imageGray,\n kpSet.features(), kpSet.descriptors(),\n bOctMinus1, true, dPeakThreshold);\n\n kpSet.saveToBinFile(sFeat, sDesc);\n vec_imagesSize[i] = make_pair(imageGray.Width(), imageRGB.Height());\n }\n ++my_progress_bar;\n }\n }\n\n\n\n \/\/---------------------------------------\n \/\/ c. Compute putatives descriptor matches\n \/\/ - L2 descriptor matching\n \/\/ - Keep correspondences only if NearestNeighbor ratio is ok\n \/\/---------------------------------------\n IndexedMatchPerPair map_PutativesMatches;\n \/\/ Define the matcher and the used metric (Squared L2)\n \/\/ ANN matcher could be defined as follow:\n typedef flann::L2<DescriptorT::bin_type> MetricT;\n typedef ArrayMatcher_Kdtree_Flann<DescriptorT::bin_type, MetricT> MatcherT;\n \/\/ Brute force matcher is defined as following:\n \/\/typedef L2_Vectorized<DescriptorT::bin_type> MetricT;\n \/\/typedef ArrayMatcherBruteForce<DescriptorT::bin_type, MetricT> MatcherT;\n\n \/\/ If the matches already exists, reload them\n if (stlplus::file_exists(sOutDir + \"\/matches.putative.txt\"))\n {\n PairedIndMatchImport(sOutDir + \"\/matches.putative.txt\", map_PutativesMatches);\n std::cout << std::endl << \"PUTATIVE MATCHES -- PREVIOUS RESULTS LOADED\" << std::endl;\n }\n else \/\/ Compute the putatives matches\n {\n ImageCollectionMatcher_AllInMemory<KeypointSetT, MatcherT> collectionMatcher(fDistRatio);\n if (collectionMatcher.loadData(vec_fileNames, sOutDir))\n {\n std::cout << std::endl << \"PUTATIVE MATCHES\" << std::endl;\n collectionMatcher.Match(vec_fileNames, map_PutativesMatches);\n \/\/---------------------------------------\n \/\/-- Export putative matches\n \/\/---------------------------------------\n std::ofstream file (std::string(sOutDir + \"\/matches.putative.txt\").c_str());\n if (file.is_open())\n PairedIndMatchToStream(map_PutativesMatches, file);\n file.close();\n }\n }\n \/\/-- export putative matches Adjacency matrix\n PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),\n map_PutativesMatches,\n stlplus::create_filespec(sOutDir, \"PutativeAdjacencyMatrix\", \"svg\"));\n\n\n \/\/---------------------------------------\n \/\/ d. Geometric filtering of putatives matches\n \/\/ - AContrario Estimation of the Fundamental matrix\n \/\/ - Use a upper bound for the plausible F matrix\n \/\/ acontrario estimated threshold\n \/\/---------------------------------------\n IndexedMatchPerPair map_GeometricMatches_F;\n\n GeometricFilter_FMatrix_AC geomFilter_F_AC(4.0);\n ImageCollectionGeometricFilter<FeatureT, GeometricFilter_FMatrix_AC> collectionGeomFilter;\n if (collectionGeomFilter.loadData(vec_fileNames, sOutDir))\n {\n std::cout << std::endl << \" - GEOMETRIC FILTERING - \" << std::endl;\n collectionGeomFilter.Filter(\n geomFilter_F_AC,\n map_PutativesMatches,\n map_GeometricMatches_F,\n vec_imagesSize);\n\n \/\/---------------------------------------\n \/\/-- Export geometric filtered matches\n \/\/---------------------------------------\n std::ofstream file (string(sOutDir + \"\/matches.f.txt\").c_str());\n if (file.is_open())\n PairedIndMatchToStream(map_GeometricMatches_F, file);\n file.close();\n\n \/\/-- export Adjacency matrix\n std::cout << \"\\n Export Adjacency Matrix of the pairwise's Epipolar matches\"\n << std::endl;\n PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),\n map_GeometricMatches_F,\n stlplus::create_filespec(sOutDir, \"EpipolarAdjacencyMatrix\", \"svg\"));\n }\n return EXIT_SUCCESS;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n This class calculates the space charge kicks for bunch using 2.5D approach in transverse direction\n and Rick Baartman's approach (RB) to the longitudinal kicks. There is a hope that will be simular to\n the true 3D discription of space charge. \n*\/\n\n#ifndef SC_SPACECHARGE_CALC_2P5D_RB_H\n#define SC_SPACECHARGE_CALC_2P5D_RB_H\n\n\/\/MPI Function Wrappers\n#include \"orbit_mpi.hh\"\n#include \"wrap_mpi_comm.hh\"\n\n#include <cstdlib>\n#include <cmath>\n\n\/\/ORBIT bunch\n#include \"Bunch.hh\"\n\n\/\/pyORBIT utils\n#include \"CppPyWrapper.hh\"\n#include \"BunchExtremaCalculator.hh\"\n\n#include \"Grid1D.hh\"\n#include \"Grid2D.hh\"\n#include \"PoissonSolverFFT2D.hh\"\n\nusing namespace std;\n\nclass SpaceChargeCalc2p5Drb: public OrbitUtils::CppPyWrapper\n{\npublic:\n\t\n\t\/** Constructor with the \"x to y ratio\" parameter. *\/\n\tSpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize, double xy_ratio_in);\n\n\t\/** Constructor with \"ratio\" parameter equals 1. *\/\n\tSpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize);\n\t\n\t\/** Destructor *\/\n\tvirtual ~SpaceChargeCalc2p5Drb();\n\t\n\t\/** Calculates space charge and applies the transverse and \n\t longitudinal SC kicks to the macro-particles in the bunch. *\/\n\tvoid trackBunch(Bunch* bunch, double length, double pipe_radius);\n\t\t\n\t\/** Returns the 2D rho grid with a transverse density distribution. **\/\n\tGrid2D* getRhoGrid();\n\n\t\/** Returns the 2D phi grid with a transverse potential. **\/\n\tGrid2D* getPhiGrid();\n\n\t\/** Returns the 1D grid with a longitudinal density. **\/\n\tGrid1D* getLongGrid();\n\t\n\t\/** Returns the 1D grid with a derivative of the longitudinal density. **\/\n\tGrid1D* getLongDerivativeGrid();\n\t\n\t\/** Sets the number of smoothing points to calculate the derivative of the longitudinal density. *\/\n\tvoid setLongAveragingPointsN(int n_points);\n\t\n\t\/** Returns the number of smoothing points to calculate the derivative of the longitudinal density. *\/\n\tint getLongAveragingPointsN();\n\t\nprivate:\n\t\n\t\/** Analyses the bunch and does bining. *\/\n double bunchAnalysis(Bunch* bunch, double& totalMacrosize, double& x_c, double& y_c, double& a_bunch);\t\n \n \/** Calculates the derivative of the longitudinal density by using Quadratic Curve Fitting *\/\n void calculateLongDerivative();\n\t\nprotected:\n\tPoissonSolverFFT2D* poissonSolver;\n\tGrid2D* rhoGrid;\n\tGrid2D* phiGrid;\n\tGrid1D* zGrid;\n\tGrid1D* zDerivGrid;\n\tOrbitUtils::BunchExtremaCalculator* bunchExtremaCalc;\n\t\n\tdouble xy_ratio;\n\tint n_long_avg;\n\t\n\t\/\/auxiliary 5x2 array for Quadratic Curve Fitting\n\tdouble** S_arr;\n};\n\/\/end of SC_SPACECHARGE_CALC_2P5D_RB_H\n#endif\n<commit_msg>The comment about \"hope\" removed. There is no hope that this algorithm will work for linac bunches<commit_after>\/**\n This class calculates the space charge kicks for bunch using 2.5D approach in transverse direction\n and Rick Baartman's approach (RB) to the longitudinal kicks. It is not sutable for short bunches, but can be used in \n rings. \n*\/\n\n#ifndef SC_SPACECHARGE_CALC_2P5D_RB_H\n#define SC_SPACECHARGE_CALC_2P5D_RB_H\n\n\/\/MPI Function Wrappers\n#include \"orbit_mpi.hh\"\n#include \"wrap_mpi_comm.hh\"\n\n#include <cstdlib>\n#include <cmath>\n\n\/\/ORBIT bunch\n#include \"Bunch.hh\"\n\n\/\/pyORBIT utils\n#include \"CppPyWrapper.hh\"\n#include \"BunchExtremaCalculator.hh\"\n\n#include \"Grid1D.hh\"\n#include \"Grid2D.hh\"\n#include \"PoissonSolverFFT2D.hh\"\n\nusing namespace std;\n\nclass SpaceChargeCalc2p5Drb: public OrbitUtils::CppPyWrapper\n{\npublic:\n\t\n\t\/** Constructor with the \"x to y ratio\" parameter. *\/\n\tSpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize, double xy_ratio_in);\n\n\t\/** Constructor with \"ratio\" parameter equals 1. *\/\n\tSpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize);\n\t\n\t\/** Destructor *\/\n\tvirtual ~SpaceChargeCalc2p5Drb();\n\t\n\t\/** Calculates space charge and applies the transverse and \n\t longitudinal SC kicks to the macro-particles in the bunch. *\/\n\tvoid trackBunch(Bunch* bunch, double length, double pipe_radius);\n\t\t\n\t\/** Returns the 2D rho grid with a transverse density distribution. **\/\n\tGrid2D* getRhoGrid();\n\n\t\/** Returns the 2D phi grid with a transverse potential. **\/\n\tGrid2D* getPhiGrid();\n\n\t\/** Returns the 1D grid with a longitudinal density. **\/\n\tGrid1D* getLongGrid();\n\t\n\t\/** Returns the 1D grid with a derivative of the longitudinal density. **\/\n\tGrid1D* getLongDerivativeGrid();\n\t\n\t\/** Sets the number of smoothing points to calculate the derivative of the longitudinal density. *\/\n\tvoid setLongAveragingPointsN(int n_points);\n\t\n\t\/** Returns the number of smoothing points to calculate the derivative of the longitudinal density. *\/\n\tint getLongAveragingPointsN();\n\t\nprivate:\n\t\n\t\/** Analyses the bunch and does bining. *\/\n double bunchAnalysis(Bunch* bunch, double& totalMacrosize, double& x_c, double& y_c, double& a_bunch);\t\n \n \/** Calculates the derivative of the longitudinal density by using Quadratic Curve Fitting *\/\n void calculateLongDerivative();\n\t\nprotected:\n\tPoissonSolverFFT2D* poissonSolver;\n\tGrid2D* rhoGrid;\n\tGrid2D* phiGrid;\n\tGrid1D* zGrid;\n\tGrid1D* zDerivGrid;\n\tOrbitUtils::BunchExtremaCalculator* bunchExtremaCalc;\n\t\n\tdouble xy_ratio;\n\tint n_long_avg;\n\t\n\t\/\/auxiliary 5x2 array for Quadratic Curve Fitting\n\tdouble** S_arr;\n};\n\/\/end of SC_SPACECHARGE_CALC_2P5D_RB_H\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nYou may use this sample code for anything you like, it is not covered by the\nsame license as the rest of the engine.\n-----------------------------------------------------------------------------\n*\/\n#include \"SdkSample.h\"\n#include \"SamplePlugin.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\n\nSamplePlugin* sp;\nSample* s;\n\nclass _OgreSampleClassExport Sample_Basic : public SdkSample\n{\n Entity* mOgreEnt;\n\n TexturePtr mImage;\n HardwarePixelBufferSharedPtr mPixelBuffer;\n\n \/\/HardwareCounterBufferSharedPtr mBuffer;\n\n public:\n \n Sample_Basic() \n { \n mInfo[\"Title\"] = \"Basic\";\n mInfo[\"Description\"] = \"A basic example using every available shader type.\";\n mInfo[\"Thumbnail\"] = \"thumb_basic.png\";\n mInfo[\"Category\"] = \"Tests\";\n }\n\n void testCapabilities(const RenderSystemCapabilities* caps)\n {\n if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM))\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your render system \/ hardware does not support geometry programs, \"\n \"so you cannot run this sample. Sorry!\", \n \"Sample_Basic::testCapabilities\");\n }\n \/\/TODO check for tessellation shaders and compute shaders too\n }\n\n \/\/ Just override the mandatory create scene method\n void setupContent(void)\n {\n mCamera->setPosition(0, 0, -40);\n mCamera->lookAt(0,0,0);\n \/\/ mCamera->setNearClipDistance(0.1);\n \/\/ mCamera->setFarClipDistance(100);\n \n mOgreEnt = mSceneMgr->createEntity(\"PlainHead\", \"ogrehead.mesh\");\n mOgreEnt->setMaterialName(\"JAJ\/Basic\");\n \/\/mOgreEnt->setMaterialName(\"BaseWhiteNoLighting\");\n SceneNode* ogre = mSceneMgr->getRootSceneNode()->createChildSceneNode();\n ogre->setPosition(50, -50, 140);\n ogre->setDirection(0,0,1);\n ogre->attachObject(mOgreEnt);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Image Load\/Store\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n mImage = TextureManager::getSingleton().createManual(\n \"ImageData\", \/\/ Name of texture\n \"General\", \/\/ Name of resource group in which the texture should be created\n TEX_TYPE_2D, \/\/ Texture type\n 256, 256, 1, \/\/ Width, Height, Depth\n 0, \/\/ Number of mipmaps\n PF_X8R8G8B8 \/\/ Pixel format \/\/TODO support formats from GL3+\n \/\/TU_DYNAMIC \/\/ usage\n );\n\n mImage->createShaderAccessPoint(0);\n\n mPixelBuffer = mImage->getBuffer(0,0);\n\n \/\/ Lock the buffer so we can write to it.\n mPixelBuffer->lock(HardwareBuffer::HBL_DISCARD);\n const PixelBox &pb = mPixelBuffer->getCurrentLock();\n\n \/\/ Update the contents of pb here\n \/\/ Image data starts at pb.data and has format pb.format\n \/\/ Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32.\n uint *data = static_cast<uint*>(pb.data);\n size_t height = pb.getHeight();\n size_t width = pb.getWidth();\n size_t pitch = pb.rowPitch; \/\/ Skip between rows of image\n for (size_t y = 0; y < height; ++y)\n {\n for(size_t x = 0; x < width; ++x)\n {\n \/\/ 0xXXRRGGBB -> fill the buffer with yellow pixels\n \/\/ data[pitch * y + x] = 0x00FFFF00;\n data[pitch * y + x] = 0x0087CEEB;\n }\n }\n\n \/\/ Unlock the buffer again (frees it for use by the GPU)\n mPixelBuffer->unlock();\n }\n\n void cleanupContent()\n {\n \/\/ Read image load\/store data.\n mPixelBuffer->lock(HardwareBuffer::HBL_READ_ONLY);\n const PixelBox &pb = mPixelBuffer->getCurrentLock();\n uint *data = static_cast<uint*>(pb.data);\n size_t height = pb.getHeight();\n size_t width = pb.getWidth();\n size_t pitch = pb.rowPitch; \/\/ Skip between rows of image\n printf(\"Buffer values.\\n\");\n \/\/ for (size_t y = 0; y < height; ++y)\n \/\/ {\n \/\/ for(size_t x = 0; x < width; ++x)\n \/\/ {\n \/\/ std::cout << \" \" << std::hex << data[pitch * y + x];\n \/\/ }\n \/\/ std::cout << std::endl;\n \/\/ }\n std::cout << std::hex << data[0];\n std::cout << \" \" << data[1] << std::endl;\n mPixelBuffer->unlock();\n\n \/\/MeshManager::getSingleton().remove(mTetrahedraMesh->getName());\n }\n\n bool frameRenderingQueued(const FrameEvent& evt)\n {\n Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) \/ 1000.0;\n Pass* renderPass = mOgreEnt->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0);\n if (renderPass->hasFragmentProgram())\n {\n Ogre::GpuProgramParametersSharedPtr pParams = renderPass->getFragmentProgramParameters();\n if ( pParams.isNull() )\n {\n \/\/printf(\"SAD PANDA!\");\n }\n else\n { \n if ( pParams->_findNamedConstantDefinition( \"ColourMe[0]\" ) )\n {\n Vector4 constParam = Ogre::Vector4(0.5, 0.1, 0.0, 1.0);\n renderPass->getFragmentProgramParameters()->setNamedConstant(\"ColourMe[0]\", constParam);\n \n Vector4 timeParam = Ogre::Vector4(\n Ogre::Math::Sin(seconds)*0.5, 0.0, Ogre::Math::Cos(seconds)*0.5, 0.0);\n renderPass->getFragmentProgramParameters()->setNamedConstant(\"ColourMe[1]\", timeParam);\n }\n const Ogre::GpuConstantDefinition* atom_counter_def;\n if ( (atom_counter_def = &pParams->getConstantDefinition(\"atom_counter\")) )\n {\n \/\/TODO lock buffer, retrieve counter value similar to compute above\n \/\/const uint* counter = pParams->getUnsignedIntPointer(atom_counter_def->physicalIndex);\n \/\/const uint* counter2 = ;\n \/\/std::cout << \"FOUND THE ATOMS: \" << *counter << \" \" << std::endl; \/\/<< *counter2 << std::endl;\n }\n }\n }\n\n \/\/ renderPass->getFragmentProgramParameters()->getConstantDefinition(\"atom_counter\").getValue();\n return SdkSample::frameRenderingQueued(evt); \n }\n};\n\n#ifndef OGRE_STATIC_LIB\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n s = new Sample_Basic;\n sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n sp->addSample(s);\n Root::getSingleton().installPlugin(sp);\n}\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n Root::getSingleton().uninstallPlugin(sp); \n OGRE_DELETE sp;\n delete s;\n}\n\n#endif\n<commit_msg>Add capabilities check to basic sample<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nAlso see acknowledgements in Readme.html\n\nYou may use this sample code for anything you like, it is not covered by the\nsame license as the rest of the engine.\n-----------------------------------------------------------------------------\n*\/\n#include \"SdkSample.h\"\n#include \"SamplePlugin.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\n\nSamplePlugin* sp;\nSample* s;\n\nclass _OgreSampleClassExport Sample_Basic : public SdkSample\n{\n Entity* mOgreEnt;\n\n TexturePtr mImage;\n HardwarePixelBufferSharedPtr mPixelBuffer;\n\n \/\/HardwareCounterBufferSharedPtr mBuffer;\n\n public:\n \n Sample_Basic() \n { \n mInfo[\"Title\"] = \"Basic\";\n mInfo[\"Description\"] = \"A basic example using every available shader type.\";\n mInfo[\"Thumbnail\"] = \"thumb_basic.png\";\n mInfo[\"Category\"] = \"Tests\";\n }\n\n void testCapabilities(const RenderSystemCapabilities* caps)\n {\n if (!caps->hasCapability(RSC_ATOMIC_COUNTERS))\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your render system \/ hardware does not support atomic counters, \"\n \"so you cannot run this sample. Sorry!\",\n \"Sample_Basic::testCapabilities\");\n }\n\n if (!caps->hasCapability(RSC_COMPUTE_PROGRAM))\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your render system \/ hardware does not support compute programs, \"\n \"so you cannot run this sample. Sorry!\",\n \"Sample_Basic::testCapabilities\");\n }\n\n if (!caps->hasCapability(RSC_TESSELATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELATION_DOMAIN_PROGRAM))\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your render system \/ hardware does not support tesselation programs, \"\n \"so you cannot run this sample. Sorry!\",\n \"Sample_Basic::testCapabilities\");\n }\n\n if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM))\n {\n OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, \"Your render system \/ hardware does not support geometry programs, \"\n \"so you cannot run this sample. Sorry!\", \n \"Sample_Basic::testCapabilities\");\n }\n }\n\n \/\/ Just override the mandatory create scene method\n void setupContent(void)\n {\n mCamera->setPosition(0, 0, -40);\n mCamera->lookAt(0,0,0);\n \/\/ mCamera->setNearClipDistance(0.1);\n \/\/ mCamera->setFarClipDistance(100);\n \n mOgreEnt = mSceneMgr->createEntity(\"PlainHead\", \"ogrehead.mesh\");\n mOgreEnt->setMaterialName(\"JAJ\/Basic\");\n \/\/mOgreEnt->setMaterialName(\"BaseWhiteNoLighting\");\n SceneNode* ogre = mSceneMgr->getRootSceneNode()->createChildSceneNode();\n ogre->setPosition(50, -50, 140);\n ogre->setDirection(0,0,1);\n ogre->attachObject(mOgreEnt);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Image Load\/Store\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n mImage = TextureManager::getSingleton().createManual(\n \"ImageData\", \/\/ Name of texture\n \"General\", \/\/ Name of resource group in which the texture should be created\n TEX_TYPE_2D, \/\/ Texture type\n 256, 256, 1, \/\/ Width, Height, Depth\n 0, \/\/ Number of mipmaps\n PF_X8R8G8B8 \/\/ Pixel format \/\/TODO support formats from GL3+\n \/\/TU_DYNAMIC \/\/ usage\n );\n\n mImage->createShaderAccessPoint(0);\n\n mPixelBuffer = mImage->getBuffer(0,0);\n\n \/\/ Lock the buffer so we can write to it.\n mPixelBuffer->lock(HardwareBuffer::HBL_DISCARD);\n const PixelBox &pb = mPixelBuffer->getCurrentLock();\n\n \/\/ Update the contents of pb here\n \/\/ Image data starts at pb.data and has format pb.format\n \/\/ Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32.\n uint *data = static_cast<uint*>(pb.data);\n size_t height = pb.getHeight();\n size_t width = pb.getWidth();\n size_t pitch = pb.rowPitch; \/\/ Skip between rows of image\n for (size_t y = 0; y < height; ++y)\n {\n for(size_t x = 0; x < width; ++x)\n {\n \/\/ 0xXXRRGGBB -> fill the buffer with yellow pixels\n \/\/ data[pitch * y + x] = 0x00FFFF00;\n data[pitch * y + x] = 0x0087CEEB;\n }\n }\n\n \/\/ Unlock the buffer again (frees it for use by the GPU)\n mPixelBuffer->unlock();\n }\n\n void cleanupContent()\n {\n \/\/ Read image load\/store data.\n mPixelBuffer->lock(HardwareBuffer::HBL_READ_ONLY);\n const PixelBox &pb = mPixelBuffer->getCurrentLock();\n uint *data = static_cast<uint*>(pb.data);\n size_t height = pb.getHeight();\n size_t width = pb.getWidth();\n size_t pitch = pb.rowPitch; \/\/ Skip between rows of image\n printf(\"Buffer values.\\n\");\n \/\/ for (size_t y = 0; y < height; ++y)\n \/\/ {\n \/\/ for(size_t x = 0; x < width; ++x)\n \/\/ {\n \/\/ std::cout << \" \" << std::hex << data[pitch * y + x];\n \/\/ }\n \/\/ std::cout << std::endl;\n \/\/ }\n std::cout << std::hex << data[0];\n std::cout << \" \" << data[1] << std::endl;\n mPixelBuffer->unlock();\n\n \/\/MeshManager::getSingleton().remove(mTetrahedraMesh->getName());\n }\n\n bool frameRenderingQueued(const FrameEvent& evt)\n {\n Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) \/ 1000.0;\n Pass* renderPass = mOgreEnt->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0);\n if (renderPass->hasFragmentProgram())\n {\n Ogre::GpuProgramParametersSharedPtr pParams = renderPass->getFragmentProgramParameters();\n if ( pParams.isNull() )\n {\n \/\/printf(\"SAD PANDA!\");\n }\n else\n { \n if ( pParams->_findNamedConstantDefinition( \"ColourMe[0]\" ) )\n {\n Vector4 constParam = Ogre::Vector4(0.5, 0.1, 0.0, 1.0);\n renderPass->getFragmentProgramParameters()->setNamedConstant(\"ColourMe[0]\", constParam);\n \n Vector4 timeParam = Ogre::Vector4(\n Ogre::Math::Sin(seconds)*0.5, 0.0, Ogre::Math::Cos(seconds)*0.5, 0.0);\n renderPass->getFragmentProgramParameters()->setNamedConstant(\"ColourMe[1]\", timeParam);\n }\n const Ogre::GpuConstantDefinition* atom_counter_def;\n if ( (atom_counter_def = &pParams->getConstantDefinition(\"atom_counter\")) )\n {\n \/\/TODO lock buffer, retrieve counter value similar to compute above\n \/\/const uint* counter = pParams->getUnsignedIntPointer(atom_counter_def->physicalIndex);\n \/\/const uint* counter2 = ;\n \/\/std::cout << \"FOUND THE ATOMS: \" << *counter << \" \" << std::endl; \/\/<< *counter2 << std::endl;\n }\n }\n }\n\n \/\/ renderPass->getFragmentProgramParameters()->getConstantDefinition(\"atom_counter\").getValue();\n return SdkSample::frameRenderingQueued(evt); \n }\n};\n\n#ifndef OGRE_STATIC_LIB\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n s = new Sample_Basic;\n sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n sp->addSample(s);\n Root::getSingleton().installPlugin(sp);\n}\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n Root::getSingleton().uninstallPlugin(sp); \n OGRE_DELETE sp;\n delete s;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: OutlineViewShell.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-01-11 12:12:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#define SD_OUTLINE_VIEW_SHELL_HXX\n\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n\nclass SdPage;\nclass TransferableDataHelper;\nclass TransferableClipboardListener;\n\nnamespace sd {\n\nclass SdUnoOutlineView;\n\n\/** Show a textual overview of the text contents of all slides.\n*\/\nclass OutlineViewShell\n : public ViewShell\n{\npublic:\n TYPEINFO();\n\n SFX_DECL_VIEWFACTORY(OutlineViewShell);\n SFX_DECL_INTERFACE(SD_IF_SDOUTLINEVIEWSHELL);\n\n \/\/ The previous macros change access mode. To be sure switch back\n \/\/ to public access.\npublic:\n \/** Create a new view shell for the outline mode.\n @param rViewShellBase\n The new object will be stacked on this view shell base.\n @param pFrameView\n The frame view that makes it possible to pass information from\n one view shell to the next.\n *\/\n OutlineViewShell (\n SfxViewFrame* pFrame,\n ViewShellBase& rViewShellBase,\n ::Window* pParentWindow,\n FrameView* pFrameView = NULL);\n\n OutlineViewShell (\n SfxViewFrame* pFrame,\n ::Window* pParentWindow,\n const OutlineViewShell& rShell);\n\n virtual ~OutlineViewShell (void);\n\n virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);\n\n \/** Arrange and resize the GUI elements like rulers, sliders, and\n buttons as well as the actual document view according to the size of\n the enclosing window and current sizes of buttons, rulers, and\n sliders.\n *\/\n virtual void ArrangeGUIElements (void);\n\n virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );\n\n virtual long VirtHScrollHdl(ScrollBar* pHScroll);\n virtual long VirtVScrollHdl(ScrollBar* pVHScroll);\n\n virtual void AddWindow(::sd::Window* pWin);\n virtual void RemoveWindow(::sd::Window* pWin);\n\n virtual void Activate( BOOL IsMDIActivate );\n virtual void Deactivate( BOOL IsMDIActivate );\n\n virtual SdPage* GetActualPage();\n \/** Return a string that describes the currently selected pages.\n *\/\n String GetPageRangeString (void);\n\n void ExecCtrl(SfxRequest &rReq);\n void GetCtrlState(SfxItemSet &rSet);\n void GetMenuState(SfxItemSet &rSet);\n void GetAttrState(SfxItemSet &rSet);\n void GetState (SfxItemSet& rSet);\n\n void ExecStatusBar(SfxRequest& rReq);\n void GetStatusBarState(SfxItemSet& rSet);\n\n void FuTemporary(SfxRequest &rReq);\n void FuPermanent(SfxRequest &rReq);\n void FuSupport(SfxRequest &rReq);\n\n virtual void SetZoom(long nZoom);\n virtual void SetZoomRect(const Rectangle& rZoomRect);\n virtual String GetSelectionText( BOOL bCompleteWords = FALSE );\n virtual BOOL HasSelection( BOOL bText = TRUE ) const;\n\n void Execute(SfxRequest& rReq);\n\n virtual void ReadFrameViewData(FrameView* pView);\n virtual void WriteFrameViewData();\n\n virtual void Command( const CommandEvent& rCEvt, ::sd::Window* pWin );\n virtual BOOL KeyInput(const KeyEvent& rKEvt, ::sd::Window* pWin);\n virtual void MouseButtonUp(const MouseEvent& rMEvt, ::sd::Window* pWin);\n\n ULONG Read(SvStream& rInput, const String& rBaseURL, USHORT eFormat);\n\n virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );\n virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );\n\n \/** this method is called when the visible area of the view from this viewshell is changed *\/\n virtual void VisAreaChanged(const Rectangle& rRect);\n\n \/** Create an accessible object representing the specified window.\n @param pWindow\n The returned object makes the document displayed in this window\n accessible.\n @return\n Returns an <type>AccessibleDrawDocumentView<\/type> object.\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>\n CreateAccessibleDocumentView (::sd::Window* pWindow);\n\n \/** Update the preview to show the specified page.\n *\/\n virtual void UpdatePreview (SdPage* pPage, BOOL bInit = FALSE);\n\n virtual DrawController* GetController (void);\n\nprotected:\n virtual Size GetOptimalSizePixel() const;\n\n \/\/ Methoden, die fuer die Preview gebraucht werden\n BOOL UpdateTitleObject( SdPage* pPage, Paragraph* pPara );\n BOOL UpdateLayoutObject( SdPage* pPage, Paragraph* pPara );\n\n \/** Make the given page the new current page. This method\n notifies the controller and adapts the selection of the\n model.\n @param pPage\n The new current page. Pass NULL when there is no current page.\n *\/\n void SetCurrentPage (SdPage* pPage);\n\nprivate:\n OutlineView* pOlView;\n SdPage* pLastPage; \/\/ Zur performanten Aufbereitung der Preview\n TransferableClipboardListener* pClipEvtLstnr;\n BOOL bPastePossible;\n\n void Construct (DrawDocShell* pDocSh);\n DECL_LINK( ClipboardChanged, TransferableDataHelper* );\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS impress31 (1.6.24); FILE MERGED 2005\/01\/28 09:13:04 cl 1.6.24.1: #i32920# reworked FuPage to work with master pages without a slide<commit_after>\/*************************************************************************\n *\n * $RCSfile: OutlineViewShell.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2005-02-17 09:42:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#define SD_OUTLINE_VIEW_SHELL_HXX\n\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n\nclass SdPage;\nclass TransferableDataHelper;\nclass TransferableClipboardListener;\n\nnamespace sd {\n\nclass SdUnoOutlineView;\n\n\/** Show a textual overview of the text contents of all slides.\n*\/\nclass OutlineViewShell\n : public ViewShell\n{\npublic:\n TYPEINFO();\n\n SFX_DECL_VIEWFACTORY(OutlineViewShell);\n SFX_DECL_INTERFACE(SD_IF_SDOUTLINEVIEWSHELL);\n\n \/\/ The previous macros change access mode. To be sure switch back\n \/\/ to public access.\npublic:\n \/** Create a new view shell for the outline mode.\n @param rViewShellBase\n The new object will be stacked on this view shell base.\n @param pFrameView\n The frame view that makes it possible to pass information from\n one view shell to the next.\n *\/\n OutlineViewShell (\n SfxViewFrame* pFrame,\n ViewShellBase& rViewShellBase,\n ::Window* pParentWindow,\n FrameView* pFrameView = NULL);\n\n OutlineViewShell (\n SfxViewFrame* pFrame,\n ::Window* pParentWindow,\n const OutlineViewShell& rShell);\n\n virtual ~OutlineViewShell (void);\n\n virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);\n\n \/** Arrange and resize the GUI elements like rulers, sliders, and\n buttons as well as the actual document view according to the size of\n the enclosing window and current sizes of buttons, rulers, and\n sliders.\n *\/\n virtual void ArrangeGUIElements (void);\n\n virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );\n\n virtual long VirtHScrollHdl(ScrollBar* pHScroll);\n virtual long VirtVScrollHdl(ScrollBar* pVHScroll);\n\n virtual void AddWindow(::sd::Window* pWin);\n virtual void RemoveWindow(::sd::Window* pWin);\n\n virtual void Activate( BOOL IsMDIActivate );\n virtual void Deactivate( BOOL IsMDIActivate );\n\n virtual SdPage* GetActualPage();\n\n \/\/\/ inherited from sd::ViewShell\n virtual SdPage* getCurrentPage() const;\n\n \/** Return a string that describes the currently selected pages.\n *\/\n String GetPageRangeString (void);\n\n void ExecCtrl(SfxRequest &rReq);\n void GetCtrlState(SfxItemSet &rSet);\n void GetMenuState(SfxItemSet &rSet);\n void GetAttrState(SfxItemSet &rSet);\n void GetState (SfxItemSet& rSet);\n\n void ExecStatusBar(SfxRequest& rReq);\n void GetStatusBarState(SfxItemSet& rSet);\n\n void FuTemporary(SfxRequest &rReq);\n void FuPermanent(SfxRequest &rReq);\n void FuSupport(SfxRequest &rReq);\n\n virtual void SetZoom(long nZoom);\n virtual void SetZoomRect(const Rectangle& rZoomRect);\n virtual String GetSelectionText( BOOL bCompleteWords = FALSE );\n virtual BOOL HasSelection( BOOL bText = TRUE ) const;\n\n void Execute(SfxRequest& rReq);\n\n virtual void ReadFrameViewData(FrameView* pView);\n virtual void WriteFrameViewData();\n\n virtual void Command( const CommandEvent& rCEvt, ::sd::Window* pWin );\n virtual BOOL KeyInput(const KeyEvent& rKEvt, ::sd::Window* pWin);\n virtual void MouseButtonUp(const MouseEvent& rMEvt, ::sd::Window* pWin);\n\n ULONG Read(SvStream& rInput, const String& rBaseURL, USHORT eFormat);\n\n virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );\n virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );\n\n \/** this method is called when the visible area of the view from this viewshell is changed *\/\n virtual void VisAreaChanged(const Rectangle& rRect);\n\n \/** Create an accessible object representing the specified window.\n @param pWindow\n The returned object makes the document displayed in this window\n accessible.\n @return\n Returns an <type>AccessibleDrawDocumentView<\/type> object.\n *\/\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>\n CreateAccessibleDocumentView (::sd::Window* pWindow);\n\n \/** Update the preview to show the specified page.\n *\/\n virtual void UpdatePreview (SdPage* pPage, BOOL bInit = FALSE);\n\n virtual DrawController* GetController (void);\n\nprotected:\n virtual Size GetOptimalSizePixel() const;\n\n \/\/ Methoden, die fuer die Preview gebraucht werden\n BOOL UpdateTitleObject( SdPage* pPage, Paragraph* pPara );\n BOOL UpdateLayoutObject( SdPage* pPage, Paragraph* pPara );\n\n \/** Make the given page the new current page. This method\n notifies the controller and adapts the selection of the\n model.\n @param pPage\n The new current page. Pass NULL when there is no current page.\n *\/\n void SetCurrentPage (SdPage* pPage);\n\nprivate:\n OutlineView* pOlView;\n SdPage* pLastPage; \/\/ Zur performanten Aufbereitung der Preview\n TransferableClipboardListener* pClipEvtLstnr;\n BOOL bPastePossible;\n\n void Construct (DrawDocShell* pDocSh);\n DECL_LINK( ClipboardChanged, TransferableDataHelper* );\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"startremotedialog.h\"\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/id.h>\n#include <projectexplorer\/kitchooser.h>\n#include <projectexplorer\/kitinformation.h>\n#include <ssh\/sshconnection.h>\n#include <utils\/pathchooser.h>\n\n#include <QDialogButtonBox>\n#include <QFormLayout>\n#include <QLabel>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QSpinBox>\n\nusing namespace ProjectExplorer;\nusing namespace Utils;\n\nnamespace Analyzer {\nnamespace Internal {\n\nclass StartRemoteDialogPrivate\n{\npublic:\n KitChooser *kitChooser;\n QLineEdit *executable;\n QLineEdit *arguments;\n QLineEdit *workingDirectory;\n QDialogButtonBox *buttonBox;\n};\n\n} \/\/ namespace Internal\n\nStartRemoteDialog::StartRemoteDialog(QWidget *parent)\n : QDialog(parent)\n , d(new Internal::StartRemoteDialogPrivate)\n{\n setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n setWindowTitle(tr(\"Start Remote Analysis\"));\n\n d->kitChooser = new KitChooser(this);\n d->executable = new QLineEdit(this);\n d->arguments = new QLineEdit(this);\n d->workingDirectory = new QLineEdit(this);\n\n d->buttonBox = new QDialogButtonBox(this);\n d->buttonBox->setOrientation(Qt::Horizontal);\n d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n\n QFormLayout *formLayout = new QFormLayout;\n formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);\n formLayout->addRow(tr(\"Kit:\"), d->kitChooser);\n formLayout->addRow(tr(\"Executable:\"), d->executable);\n formLayout->addRow(tr(\"Arguments:\"), d->arguments);\n formLayout->addRow(tr(\"Working directory:\"), d->workingDirectory);\n\n QVBoxLayout *verticalLayout = new QVBoxLayout(this);\n verticalLayout->addLayout(formLayout);\n verticalLayout->addWidget(d->buttonBox);\n\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(QLatin1String(\"AnalyzerStartRemoteDialog\"));\n QString kit = settings->value(QLatin1String(\"profile\")).toString();\n d->kitChooser->setCurrentKitId(Core::Id(kit));\n d->executable->setText(settings->value(QLatin1String(\"executable\")).toString());\n d->workingDirectory->setText(settings->value(QLatin1String(\"workingDirectory\")).toString());\n d->arguments->setText(settings->value(QLatin1String(\"arguments\")).toString());\n settings->endGroup();\n\n connect(d->kitChooser, SIGNAL(activated(int)), SLOT(validate()));\n connect(d->executable, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->workingDirectory, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->arguments, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));\n connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));\n\n validate();\n}\n\nStartRemoteDialog::~StartRemoteDialog()\n{\n delete d;\n}\n\nvoid StartRemoteDialog::accept()\n{\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(QLatin1String(\"AnalyzerStartRemoteDialog\"));\n settings->setValue(QLatin1String(\"profile\"), d->kitChooser->currentKitId().toString());\n settings->setValue(QLatin1String(\"executable\"), d->executable->text());\n settings->setValue(QLatin1String(\"workingDirectory\"), d->workingDirectory->text());\n settings->setValue(QLatin1String(\"arguments\"), d->arguments->text());\n settings->endGroup();\n\n QDialog::accept();\n}\n\nvoid StartRemoteDialog::validate()\n{\n bool valid = !d->executable->text().isEmpty();\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);\n}\n\nQSsh::SshConnectionParameters StartRemoteDialog::sshParams() const\n{\n Kit *kit = d->kitChooser->currentKit();\n IDevice::ConstPtr device = DeviceKitInformation::device(kit);\n return device->sshParameters();\n}\n\nQString StartRemoteDialog::executable() const\n{\n return d->executable->text();\n}\n\nQString StartRemoteDialog::arguments() const\n{\n return d->arguments->text();\n}\n\nQString StartRemoteDialog::workingDirectory() const\n{\n return d->workingDirectory->text();\n}\n\n} \/\/ namespace Analyzer\n<commit_msg>Populate Kit Chooser in Analyzer dialog.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"startremotedialog.h\"\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/id.h>\n#include <projectexplorer\/kitchooser.h>\n#include <projectexplorer\/kitinformation.h>\n#include <ssh\/sshconnection.h>\n#include <utils\/pathchooser.h>\n\n#include <QDialogButtonBox>\n#include <QFormLayout>\n#include <QLabel>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QSpinBox>\n\nusing namespace ProjectExplorer;\nusing namespace Utils;\n\nnamespace Analyzer {\nnamespace Internal {\n\nclass StartRemoteDialogPrivate\n{\npublic:\n KitChooser *kitChooser;\n QLineEdit *executable;\n QLineEdit *arguments;\n QLineEdit *workingDirectory;\n QDialogButtonBox *buttonBox;\n};\n\n} \/\/ namespace Internal\n\nStartRemoteDialog::StartRemoteDialog(QWidget *parent)\n : QDialog(parent)\n , d(new Internal::StartRemoteDialogPrivate)\n{\n setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n setWindowTitle(tr(\"Start Remote Analysis\"));\n\n d->kitChooser = new KitChooser(this);\n d->executable = new QLineEdit(this);\n d->arguments = new QLineEdit(this);\n d->workingDirectory = new QLineEdit(this);\n\n d->buttonBox = new QDialogButtonBox(this);\n d->buttonBox->setOrientation(Qt::Horizontal);\n d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n\n QFormLayout *formLayout = new QFormLayout;\n formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);\n formLayout->addRow(tr(\"Kit:\"), d->kitChooser);\n formLayout->addRow(tr(\"Executable:\"), d->executable);\n formLayout->addRow(tr(\"Arguments:\"), d->arguments);\n formLayout->addRow(tr(\"Working directory:\"), d->workingDirectory);\n\n QVBoxLayout *verticalLayout = new QVBoxLayout(this);\n verticalLayout->addLayout(formLayout);\n verticalLayout->addWidget(d->buttonBox);\n\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(QLatin1String(\"AnalyzerStartRemoteDialog\"));\n QString kit = settings->value(QLatin1String(\"profile\")).toString();\n d->kitChooser->populate();\n d->kitChooser->setCurrentKitId(Core::Id(kit));\n d->executable->setText(settings->value(QLatin1String(\"executable\")).toString());\n d->workingDirectory->setText(settings->value(QLatin1String(\"workingDirectory\")).toString());\n d->arguments->setText(settings->value(QLatin1String(\"arguments\")).toString());\n settings->endGroup();\n\n connect(d->kitChooser, SIGNAL(activated(int)), SLOT(validate()));\n connect(d->executable, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->workingDirectory, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->arguments, SIGNAL(textChanged(QString)), SLOT(validate()));\n connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));\n connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));\n\n validate();\n}\n\nStartRemoteDialog::~StartRemoteDialog()\n{\n delete d;\n}\n\nvoid StartRemoteDialog::accept()\n{\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(QLatin1String(\"AnalyzerStartRemoteDialog\"));\n settings->setValue(QLatin1String(\"profile\"), d->kitChooser->currentKitId().toString());\n settings->setValue(QLatin1String(\"executable\"), d->executable->text());\n settings->setValue(QLatin1String(\"workingDirectory\"), d->workingDirectory->text());\n settings->setValue(QLatin1String(\"arguments\"), d->arguments->text());\n settings->endGroup();\n\n QDialog::accept();\n}\n\nvoid StartRemoteDialog::validate()\n{\n bool valid = !d->executable->text().isEmpty();\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);\n}\n\nQSsh::SshConnectionParameters StartRemoteDialog::sshParams() const\n{\n Kit *kit = d->kitChooser->currentKit();\n IDevice::ConstPtr device = DeviceKitInformation::device(kit);\n return device->sshParameters();\n}\n\nQString StartRemoteDialog::executable() const\n{\n return d->executable->text();\n}\n\nQString StartRemoteDialog::arguments() const\n{\n return d->arguments->text();\n}\n\nQString StartRemoteDialog::workingDirectory() const\n{\n return d->workingDirectory->text();\n}\n\n} \/\/ namespace Analyzer\n<|endoftext|>"} {"text":"<commit_before>#include \"generator\/regions\/regions_builder.hpp\"\n\n#include \"generator\/regions\/admin_suburbs_marker.hpp\"\n#include \"generator\/regions\/country_specifier_builder.hpp\"\n#include \"generator\/regions\/place_points_integrator.hpp\"\n#include \"generator\/regions\/specs\/rus.hpp\"\n\n#include \"base\/assert.hpp\"\n#include \"base\/thread_pool_computational.hpp\"\n#include \"base\/stl_helpers.hpp\"\n#include \"base\/thread_pool_computational.hpp\"\n\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <functional>\n#include <numeric>\n#include <queue>\n#include <thread>\n#include <unordered_set>\n\nnamespace generator\n{\nnamespace regions\n{\nRegionsBuilder::RegionsBuilder(Regions && regions, PlacePointsMap && placePointsMap,\n size_t threadsCount)\n : m_threadsCount(threadsCount)\n{\n ASSERT(m_threadsCount != 0, ());\n\n MoveLabelPlacePoints(placePointsMap, regions);\n\n m_regionsInAreaOrder = FormRegionsInAreaOrder(std::move(regions));\n m_countriesOuters = ExtractCountriesOuters(m_regionsInAreaOrder);\n m_placePointsMap = std::move(placePointsMap);\n}\n\nvoid RegionsBuilder::MoveLabelPlacePoints(PlacePointsMap & placePointsMap, Regions & regions)\n{\n for (auto & region : regions)\n {\n if (auto labelOsmId = region.GetLabelOsmId())\n {\n auto label = placePointsMap.find(*labelOsmId);\n if (label != placePointsMap.end())\n {\n region.SetLabel(label->second);\n placePointsMap.erase(label);\n }\n }\n }\n}\n\nRegionsBuilder::Regions RegionsBuilder::FormRegionsInAreaOrder(Regions && regions)\n{\n auto const cmp = [](Region const & l, Region const & r) { return l.GetArea() > r.GetArea(); };\n std::sort(std::begin(regions), std::end(regions), cmp);\n return std::move(regions);\n}\n\nRegionsBuilder::Regions RegionsBuilder::ExtractCountriesOuters(Regions & regions)\n{\n Regions countriesOuters;\n\n auto const isCountry = [](Region const & region) {\n auto const placeType = region.GetPlaceType();\n if (placeType == PlaceType::Country)\n return true;\n\n auto const adminLevel = region.GetAdminLevel();\n return adminLevel == AdminLevel::Two && placeType == PlaceType::Unknown;\n };\n std::copy_if(std::begin(regions), std::end(regions), std::back_inserter(countriesOuters),\n isCountry);\n\n base::EraseIf(regions, isCountry);\n\n return countriesOuters;\n}\n\nRegionsBuilder::Regions const & RegionsBuilder::GetCountriesOuters() const\n{\n return m_countriesOuters;\n}\n\nRegionsBuilder::StringsList RegionsBuilder::GetCountryNames() const\n{\n StringsList result;\n std::unordered_set<std::string> set;\n for (auto const & c : GetCountriesOuters())\n {\n auto const & name = c.GetName();\n if (set.insert(name).second)\n result.emplace_back(std::move(name));\n }\n\n return result;\n}\n\nNode::Ptr RegionsBuilder::BuildCountryRegionTree(\n Region const & outer, CountrySpecifier const & countrySpecifier) const\n{\n auto nodes = MakeCountryNodesInAreaOrder(outer, m_regionsInAreaOrder, countrySpecifier);\n\n for (auto i = std::crbegin(nodes), end = std::crend(nodes); i != end; ++i)\n {\n if (auto parent = ChooseParent(nodes, i, countrySpecifier))\n {\n (*i)->SetParent(parent);\n parent->AddChild(*i);\n }\n }\n\n return nodes.front();\n}\n\nstd::vector<Node::Ptr> RegionsBuilder::MakeCountryNodesInAreaOrder(\n Region const & countryOuter, Regions const & regionsInAreaOrder,\n CountrySpecifier const & countrySpecifier) const\n{\n std::vector<Node::Ptr> nodes{std::make_shared<Node>(LevelRegion{PlaceLevel::Country,\n countryOuter})};\n for (auto const & region : regionsInAreaOrder)\n {\n if (countryOuter.ContainsRect(region))\n {\n auto level = countrySpecifier.GetLevel(region);\n auto node = std::make_shared<Node>(LevelRegion{level, region});\n nodes.emplace_back(std::move(node));\n }\n }\n\n return nodes;\n}\n\nNode::Ptr RegionsBuilder::ChooseParent(\n std::vector<Node::Ptr> const & nodesInAreaOrder,\n std::vector<Node::Ptr>::const_reverse_iterator forItem,\n CountrySpecifier const & countrySpecifier) const\n{\n auto const & node = *forItem;\n auto const & region = node->GetData();\n\n auto const from = FindAreaLowerBoundRely(nodesInAreaOrder, forItem);\n CHECK(from <= forItem, ());\n\n Node::Ptr parent;\n for (auto i = from, end = std::crend(nodesInAreaOrder); i != end; ++i)\n {\n auto const & candidate = *i;\n auto const & candidateRegion = candidate->GetData();\n\n if (parent)\n {\n auto const & parentRegion = parent->GetData();\n if (IsAreaLessRely(parentRegion, candidateRegion))\n break;\n }\n\n if (!candidateRegion.ContainsRect(region) && !candidateRegion.Contains(region.GetCenter()))\n continue;\n\n if (i == forItem)\n continue;\n\n auto const c = CompareAffiliation(candidateRegion, region, countrySpecifier);\n if (c == 1)\n {\n if (parent && 0 <= CompareAffiliation(candidateRegion, parent->GetData(), countrySpecifier))\n continue;\n\n parent = candidate;\n }\n }\n\n return parent;\n}\n\nstd::vector<Node::Ptr>::const_reverse_iterator RegionsBuilder::FindAreaLowerBoundRely(\n std::vector<Node::Ptr> const & nodesInAreaOrder,\n std::vector<Node::Ptr>::const_reverse_iterator forItem) const\n{\n auto const & region = (*forItem)->GetData();\n\n auto areaLessRely = [](Node::Ptr const & element, Region const & region) {\n auto const & elementRegion = element->GetData();\n return IsAreaLessRely(elementRegion, region);\n };\n\n return std::lower_bound(std::crbegin(nodesInAreaOrder), forItem, region, areaLessRely);\n}\n\n\/\/ static\nvoid RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, LevelRegion && region,\n CountrySpecifier const & countrySpecifier)\n{\n auto newNode = std::make_shared<Node>(std::move(region));\n InsertIntoSubtree(subtree, std::move(newNode), countrySpecifier);\n}\n\n\/\/ static\nvoid RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, Node::Ptr && newNode,\n CountrySpecifier const & countrySpecifier)\n{\n CHECK(0 < CompareAffiliation(subtree->GetData(), newNode->GetData(), countrySpecifier), ());\n\n auto & children = subtree->GetChildren();\n auto childIt = children.begin();\n while (childIt != children.end())\n {\n auto & child = *childIt;\n auto const c = CompareAffiliation(child->GetData(), newNode->GetData(), countrySpecifier);\n if (c > 0)\n return InsertIntoSubtree(child, std::move(newNode), countrySpecifier);\n\n if (c < 0)\n {\n child->SetParent(newNode);\n newNode->AddChild(child);\n childIt = children.erase(childIt);\n continue;\n }\n\n ASSERT(c == 0, ());\n ++childIt;\n }\n\n newNode->SetParent(subtree);\n subtree->AddChild(newNode);\n}\n\n\/\/ static\nint RegionsBuilder::CompareAffiliation(LevelRegion const & l, LevelRegion const & r,\n CountrySpecifier const & countrySpecifier)\n{\n if (IsAreaLessRely(r, l) && l.Contains(r))\n return 1;\n if (IsAreaLessRely(l, r) && r.Contains(l))\n return -1;\n\n if (l.CalculateOverlapPercentage(r) < 50.0)\n return 0;\n\n auto const lArea = l.GetArea();\n auto const rArea = r.GetArea();\n if (0.5 * lArea >= rArea)\n {\n LOG(LDEBUG, (\"Region\", l.GetId(), GetRegionNotation(l), \"contains partly\",\n r.GetId(), GetRegionNotation(r)));\n return 1;\n }\n if (0.5 * rArea >= lArea)\n {\n LOG(LDEBUG, (\"Region\", r.GetId(), GetRegionNotation(r), \"contains partly\",\n l.GetId(), GetRegionNotation(l)));\n return -1;\n }\n\n return countrySpecifier.RelateByWeight(l, r);\n}\n\n\/\/ static\nbool RegionsBuilder::IsAreaLessRely(Region const & l, Region const & r)\n{\n constexpr auto lAreaRation = 1. + kAreaRelativeErrorPercent \/ 100.;\n return lAreaRation * l.GetArea() < r.GetArea();\n}\n\nvoid RegionsBuilder::ForEachCountry(CountryFn fn)\n{\n std::vector<std::future<Node::PtrList>> buildingTasks;\n\n {\n base::thread_pool::computational::ThreadPool threadPool(m_threadsCount);\n\n for (auto const & countryName : GetCountryNames())\n {\n auto result = threadPool.Submit([this, countryName]() { return BuildCountry(countryName); });\n buildingTasks.emplace_back(std::move(result));\n }\n }\n\n for (auto && task : buildingTasks)\n {\n auto countryTrees = task.get();\n CHECK(!countryTrees.empty(), ());\n auto && countryName = countryTrees.front()->GetData().GetName();\n fn(countryName, countryTrees);\n }\n}\n\nNode::PtrList RegionsBuilder::BuildCountry(std::string const & countryName) const\n{\n Regions outers;\n auto const & countries = GetCountriesOuters();\n auto const pred = [&](Region const & country) { return countryName == country.GetName(); };\n std::copy_if(std::begin(countries), std::end(countries), std::back_inserter(outers), pred);\n\n auto countrySpecifier = GetCountrySpecifier(countryName);\n auto countryTrees = BuildCountryRegionTrees(outers, *countrySpecifier);\n\n PlacePointsIntegrator pointsIntegrator{m_placePointsMap, *countrySpecifier};\n LOG(LINFO, (\"Start integrate place points for\", countryName));\n pointsIntegrator.ApplyTo(countryTrees);\n LOG(LINFO, (\"Finish integrate place points for\", countryName));\n\n AdminSuburbsMarker suburbsMarker;\n LOG(LINFO, (\"Start mark admin suburbs for\", countryName));\n for (auto & tree : countryTrees)\n suburbsMarker.MarkSuburbs(tree);\n LOG(LINFO, (\"Finish mark admin suburbs for\", countryName));\n\n countrySpecifier->AdjustRegionsLevel(countryTrees);\n\n return countryTrees;\n}\n\nNode::PtrList RegionsBuilder::BuildCountryRegionTrees(\n Regions const & outers, CountrySpecifier const & countrySpecifier) const\n{\n Node::PtrList trees;\n for (auto const & outer : outers)\n {\n auto tree = BuildCountryRegionTree(outer, countrySpecifier);\n trees.push_back(std::move(tree));\n }\n\n return trees;\n}\n} \/\/ namespace regions\n} \/\/ namespace generator\n<commit_msg>[generator] style<commit_after>#include \"generator\/regions\/regions_builder.hpp\"\n\n#include \"generator\/regions\/admin_suburbs_marker.hpp\"\n#include \"generator\/regions\/country_specifier_builder.hpp\"\n#include \"generator\/regions\/place_points_integrator.hpp\"\n#include \"generator\/regions\/specs\/rus.hpp\"\n\n#include \"base\/assert.hpp\"\n#include \"base\/stl_helpers.hpp\"\n#include \"base\/thread_pool_computational.hpp\"\n\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <functional>\n#include <numeric>\n#include <queue>\n#include <thread>\n#include <unordered_set>\n\nnamespace generator\n{\nnamespace regions\n{\nRegionsBuilder::RegionsBuilder(Regions && regions, PlacePointsMap && placePointsMap,\n size_t threadsCount)\n : m_threadsCount(threadsCount)\n{\n ASSERT(m_threadsCount != 0, ());\n\n MoveLabelPlacePoints(placePointsMap, regions);\n\n m_regionsInAreaOrder = FormRegionsInAreaOrder(std::move(regions));\n m_countriesOuters = ExtractCountriesOuters(m_regionsInAreaOrder);\n m_placePointsMap = std::move(placePointsMap);\n}\n\nvoid RegionsBuilder::MoveLabelPlacePoints(PlacePointsMap & placePointsMap, Regions & regions)\n{\n for (auto & region : regions)\n {\n if (auto labelOsmId = region.GetLabelOsmId())\n {\n auto label = placePointsMap.find(*labelOsmId);\n if (label != placePointsMap.end())\n {\n region.SetLabel(label->second);\n placePointsMap.erase(label);\n }\n }\n }\n}\n\nRegionsBuilder::Regions RegionsBuilder::FormRegionsInAreaOrder(Regions && regions)\n{\n auto const cmp = [](Region const & l, Region const & r) { return l.GetArea() > r.GetArea(); };\n std::sort(std::begin(regions), std::end(regions), cmp);\n return std::move(regions);\n}\n\nRegionsBuilder::Regions RegionsBuilder::ExtractCountriesOuters(Regions & regions)\n{\n Regions countriesOuters;\n\n auto const isCountry = [](Region const & region) {\n auto const placeType = region.GetPlaceType();\n if (placeType == PlaceType::Country)\n return true;\n\n auto const adminLevel = region.GetAdminLevel();\n return adminLevel == AdminLevel::Two && placeType == PlaceType::Unknown;\n };\n std::copy_if(std::begin(regions), std::end(regions), std::back_inserter(countriesOuters),\n isCountry);\n\n base::EraseIf(regions, isCountry);\n\n return countriesOuters;\n}\n\nRegionsBuilder::Regions const & RegionsBuilder::GetCountriesOuters() const\n{\n return m_countriesOuters;\n}\n\nRegionsBuilder::StringsList RegionsBuilder::GetCountryNames() const\n{\n StringsList result;\n std::unordered_set<std::string> set;\n for (auto const & c : GetCountriesOuters())\n {\n auto const & name = c.GetName();\n if (set.insert(name).second)\n result.emplace_back(std::move(name));\n }\n\n return result;\n}\n\nNode::Ptr RegionsBuilder::BuildCountryRegionTree(Region const & outer,\n CountrySpecifier const & countrySpecifier) const\n{\n auto nodes = MakeCountryNodesInAreaOrder(outer, m_regionsInAreaOrder, countrySpecifier);\n\n for (auto i = std::crbegin(nodes), end = std::crend(nodes); i != end; ++i)\n {\n if (auto parent = ChooseParent(nodes, i, countrySpecifier))\n {\n (*i)->SetParent(parent);\n parent->AddChild(*i);\n }\n }\n\n return nodes.front();\n}\n\nstd::vector<Node::Ptr> RegionsBuilder::MakeCountryNodesInAreaOrder(\n Region const & countryOuter, Regions const & regionsInAreaOrder,\n CountrySpecifier const & countrySpecifier) const\n{\n std::vector<Node::Ptr> nodes{\n std::make_shared<Node>(LevelRegion{PlaceLevel::Country, countryOuter})};\n for (auto const & region : regionsInAreaOrder)\n {\n if (countryOuter.ContainsRect(region))\n {\n auto level = countrySpecifier.GetLevel(region);\n auto node = std::make_shared<Node>(LevelRegion{level, region});\n nodes.emplace_back(std::move(node));\n }\n }\n\n return nodes;\n}\n\nNode::Ptr RegionsBuilder::ChooseParent(std::vector<Node::Ptr> const & nodesInAreaOrder,\n std::vector<Node::Ptr>::const_reverse_iterator forItem,\n CountrySpecifier const & countrySpecifier) const\n{\n auto const & node = *forItem;\n auto const & region = node->GetData();\n\n auto const from = FindAreaLowerBoundRely(nodesInAreaOrder, forItem);\n CHECK(from <= forItem, ());\n\n Node::Ptr parent;\n for (auto i = from, end = std::crend(nodesInAreaOrder); i != end; ++i)\n {\n auto const & candidate = *i;\n auto const & candidateRegion = candidate->GetData();\n\n if (parent)\n {\n auto const & parentRegion = parent->GetData();\n if (IsAreaLessRely(parentRegion, candidateRegion))\n break;\n }\n\n if (!candidateRegion.ContainsRect(region) && !candidateRegion.Contains(region.GetCenter()))\n continue;\n\n if (i == forItem)\n continue;\n\n auto const c = CompareAffiliation(candidateRegion, region, countrySpecifier);\n if (c == 1)\n {\n if (parent && 0 <= CompareAffiliation(candidateRegion, parent->GetData(), countrySpecifier))\n continue;\n\n parent = candidate;\n }\n }\n\n return parent;\n}\n\nstd::vector<Node::Ptr>::const_reverse_iterator RegionsBuilder::FindAreaLowerBoundRely(\n std::vector<Node::Ptr> const & nodesInAreaOrder,\n std::vector<Node::Ptr>::const_reverse_iterator forItem) const\n{\n auto const & region = (*forItem)->GetData();\n\n auto areaLessRely = [](Node::Ptr const & element, Region const & region) {\n auto const & elementRegion = element->GetData();\n return IsAreaLessRely(elementRegion, region);\n };\n\n return std::lower_bound(std::crbegin(nodesInAreaOrder), forItem, region, areaLessRely);\n}\n\n\/\/ static\nvoid RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, LevelRegion && region,\n CountrySpecifier const & countrySpecifier)\n{\n auto newNode = std::make_shared<Node>(std::move(region));\n InsertIntoSubtree(subtree, std::move(newNode), countrySpecifier);\n}\n\n\/\/ static\nvoid RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, Node::Ptr && newNode,\n CountrySpecifier const & countrySpecifier)\n{\n CHECK(0 < CompareAffiliation(subtree->GetData(), newNode->GetData(), countrySpecifier), ());\n\n auto & children = subtree->GetChildren();\n auto childIt = children.begin();\n while (childIt != children.end())\n {\n auto & child = *childIt;\n auto const c = CompareAffiliation(child->GetData(), newNode->GetData(), countrySpecifier);\n if (c > 0)\n return InsertIntoSubtree(child, std::move(newNode), countrySpecifier);\n\n if (c < 0)\n {\n child->SetParent(newNode);\n newNode->AddChild(child);\n childIt = children.erase(childIt);\n continue;\n }\n\n ASSERT(c == 0, ());\n ++childIt;\n }\n\n newNode->SetParent(subtree);\n subtree->AddChild(newNode);\n}\n\n\/\/ static\nint RegionsBuilder::CompareAffiliation(LevelRegion const & l, LevelRegion const & r,\n CountrySpecifier const & countrySpecifier)\n{\n if (IsAreaLessRely(r, l) && l.Contains(r))\n return 1;\n if (IsAreaLessRely(l, r) && r.Contains(l))\n return -1;\n\n if (l.CalculateOverlapPercentage(r) < 50.0)\n return 0;\n\n auto const lArea = l.GetArea();\n auto const rArea = r.GetArea();\n if (0.5 * lArea >= rArea)\n {\n LOG(LDEBUG, (\"Region\", l.GetId(), GetRegionNotation(l), \"contains partly\", r.GetId(),\n GetRegionNotation(r)));\n return 1;\n }\n if (0.5 * rArea >= lArea)\n {\n LOG(LDEBUG, (\"Region\", r.GetId(), GetRegionNotation(r), \"contains partly\", l.GetId(),\n GetRegionNotation(l)));\n return -1;\n }\n\n return countrySpecifier.RelateByWeight(l, r);\n}\n\n\/\/ static\nbool RegionsBuilder::IsAreaLessRely(Region const & l, Region const & r)\n{\n constexpr auto lAreaRation = 1. + kAreaRelativeErrorPercent \/ 100.;\n return lAreaRation * l.GetArea() < r.GetArea();\n}\n\nvoid RegionsBuilder::ForEachCountry(CountryFn fn)\n{\n std::vector<std::future<Node::PtrList>> buildingTasks;\n\n {\n base::thread_pool::computational::ThreadPool threadPool(m_threadsCount);\n\n for (auto const & countryName : GetCountryNames())\n {\n auto result = threadPool.Submit([this, countryName]() { return BuildCountry(countryName); });\n buildingTasks.emplace_back(std::move(result));\n }\n }\n\n for (auto && task : buildingTasks)\n {\n auto countryTrees = task.get();\n CHECK(!countryTrees.empty(), ());\n auto && countryName = countryTrees.front()->GetData().GetName();\n fn(countryName, countryTrees);\n }\n}\n\nNode::PtrList RegionsBuilder::BuildCountry(std::string const & countryName) const\n{\n Regions outers;\n auto const & countries = GetCountriesOuters();\n auto const pred = [&](Region const & country) { return countryName == country.GetName(); };\n std::copy_if(std::begin(countries), std::end(countries), std::back_inserter(outers), pred);\n\n auto countrySpecifier = GetCountrySpecifier(countryName);\n auto countryTrees = BuildCountryRegionTrees(outers, *countrySpecifier);\n\n PlacePointsIntegrator pointsIntegrator{m_placePointsMap, *countrySpecifier};\n LOG(LINFO, (\"Start integrate place points for\", countryName));\n pointsIntegrator.ApplyTo(countryTrees);\n LOG(LINFO, (\"Finish integrate place points for\", countryName));\n\n AdminSuburbsMarker suburbsMarker;\n LOG(LINFO, (\"Start mark admin suburbs for\", countryName));\n for (auto & tree : countryTrees)\n suburbsMarker.MarkSuburbs(tree);\n LOG(LINFO, (\"Finish mark admin suburbs for\", countryName));\n\n countrySpecifier->AdjustRegionsLevel(countryTrees);\n\n return countryTrees;\n}\n\nNode::PtrList RegionsBuilder::BuildCountryRegionTrees(\n Regions const & outers, CountrySpecifier const & countrySpecifier) const\n{\n Node::PtrList trees;\n for (auto const & outer : outers)\n {\n auto tree = BuildCountryRegionTree(outer, countrySpecifier);\n trees.push_back(std::move(tree));\n }\n\n return trees;\n}\n} \/\/ namespace regions\n} \/\/ namespace generator\n<|endoftext|>"} {"text":"<commit_before>\/**\n * PermutationWT.cpp\n * Copyright (C) 2011 Francisco Claude F.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include<PermutationWT.h>\n\nnamespace cds_static {\n\nPermutationWT::PermutationWT(uint *perm, size_t len) {\n uint b = bits(len-1);\n uint * seq = new uint[len];\n uint * marker = new uint[uint_len(len,1)];\n for(size_t i=0;i<uint_len(len,1);i++)\n marker[i] = 0;\n\n runs = 0;\n uint last = get_field(perm,b,0);\n seq[get_field(perm,b,0)] = 0;\n bitset(marker,0);\n\n for(size_t i=1;i<len;i++) {\n if(last > get_field(perm,b,i)) {\n runs++;\n bitset(marker,i);\n }\n seq[get_field(perm,b,i)] = runs;\n last = get_field(perm,b,i);\n }\n\n wt = new WaveletTree(seq, len, new wt_coder_huff(seq, len, new MapperNone()), new BitSequenceBuilderRG(20), new MapperNone());\n marks = new BitSequenceRG(marker, len, 20);\n delete [] seq;\n}\n\nPermutationWT::~PermutationWT(){ \n delete wt;\n}\n\nuint PermutationWT::pi(uint k) const {\n uint v = (uint)marks->rank1(k);\n return (uint)wt->select(v-1, k - marks->select1(v) + 1);\n}\n\nuint PermutationWT::revpi(uint k) const {\n size_t val = 0;\n uint s = wt->access(k, val);\n return marks->select1(s+1) + val - 1;\n}\n\nsize_t PermutationWT::getSize() const {\n return marks->getSize()+wt->getSize()+sizeof(PermutationWT);\n}\n\n void PermutationWT::save(ofstream & out) const {\n saveValue(out,WTPERM);\n saveValue(out, length);\n wt->save(out);\n marks->save(out);\n }\n\n PermutationWT * PermutationWT::load(ifstream &in) {\n uint rd = loadValue<uint>(in);\n if(rd!=WTPERM) return NULL;\n PermutationWT * ret = new PermutationWT();\n ret->length = loadValue<size_t>(in);\n ret->wt = Sequence::load(in);\n ret->marks = BitSequence::load(in);\n return ret;\n }\n};\n<commit_msg>pointers break everything<commit_after>\/**\n * PermutationWT.cpp\n * Copyright (C) 2011 Francisco Claude F.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include<PermutationWT.h>\n\nnamespace cds_static {\n\nPermutationWT::PermutationWT(uint *perm, size_t len) {\n uint b = bits(len-1);\n uint * seq = new uint[len];\n uint * marker = new uint[uint_len(len,1)];\n for(size_t i=0;i<uint_len(len,1);i++)\n marker[i] = 0;\n\n runs = 0;\n uint last = get_field(perm,b,0);\n seq[get_field(perm,b,0)] = 0;\n bitset(marker,0);\n\n for(size_t i=1;i<len;i++) {\n if(last > get_field(perm,b,i)) {\n runs++;\n bitset(marker,i);\n }\n seq[get_field(perm,b,i)] = runs;\n last = get_field(perm,b,i);\n }\n\n wt = new WaveletTreeNoptrs(seq, len, new BitSequenceBuilderRRR(40), new MapperNone());\n marks = new BitSequenceRG(marker, len, 20);\n delete [] seq;\n}\n\nPermutationWT::~PermutationWT(){ \n delete wt;\n}\n\nuint PermutationWT::pi(uint k) const {\n uint v = (uint)marks->rank1(k);\n return (uint)wt->select(v-1, k - marks->select1(v) + 1);\n}\n\nuint PermutationWT::revpi(uint k) const {\n size_t val = 0;\n uint s = wt->access(k, val);\n return marks->select1(s+1) + val - 1;\n}\n\nsize_t PermutationWT::getSize() const {\n return marks->getSize()+wt->getSize()+sizeof(PermutationWT);\n}\n\n void PermutationWT::save(ofstream & out) const {\n saveValue(out,WTPERM);\n saveValue(out, length);\n wt->save(out);\n marks->save(out);\n }\n\n PermutationWT * PermutationWT::load(ifstream &in) {\n uint rd = loadValue<uint>(in);\n if(rd!=WTPERM) return NULL;\n PermutationWT * ret = new PermutationWT();\n ret->length = loadValue<size_t>(in);\n ret->wt = Sequence::load(in);\n ret->marks = BitSequence::load(in);\n return ret;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>template <int num_rotors>\nvoid MultirotorVehicleSystem<num_rotors>::init() {\n}\n\ntemplate <int num_rotors>\nvoid MultirotorVehicleSystem<num_rotors>::update() {\n \/\/ Poll the accelerometer and gyroscope\n accelerometer_reading_t accel_reading = getAccelerometer()->read();\n gyroscope_reading_t gyro_reading = getGyroscope()->read();\n\n \/\/ Update the attitude estimate\n attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);\n\n \/\/ Poll for controller input\n controller_input_t input = getInputSource()->read();\n\n \/\/ Run the controllers\n angular_position_setpoint_t angular_setpoint = {\n .pitch_pos_sp = input.pitch_sp,\n .roll_pos_sp = input.roll_sp,\n .yaw_pos_sp = input.yaw_sp,\n .throttle_sp = input.throttle_sp\n };\n\n actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);\n\n \/\/ TODO: Update motor outputs\n getMotorMapper()->run(actuator_setpoint);\n}\n<commit_msg>Remove finished TODO.<commit_after>template <int num_rotors>\nvoid MultirotorVehicleSystem<num_rotors>::init() {\n}\n\ntemplate <int num_rotors>\nvoid MultirotorVehicleSystem<num_rotors>::update() {\n \/\/ Poll the accelerometer and gyroscope\n accelerometer_reading_t accel_reading = getAccelerometer()->read();\n gyroscope_reading_t gyro_reading = getGyroscope()->read();\n\n \/\/ Update the attitude estimate\n attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);\n\n \/\/ Poll for controller input\n controller_input_t input = getInputSource()->read();\n\n \/\/ Run the controllers\n angular_position_setpoint_t angular_setpoint = {\n .pitch_pos_sp = input.pitch_sp,\n .roll_pos_sp = input.roll_sp,\n .yaw_pos_sp = input.yaw_sp,\n .throttle_sp = input.throttle_sp\n };\n\n actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);\n\n \/\/ Update motor outputs\n getMotorMapper()->run(actuator_setpoint);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/gadgetConfig.h>\n#include <typeinfo>\n#include <vpr\/vpr.h>\n#include <jccl\/Config\/ConfigElement.h>\n#include <gadget\/Type\/DeviceFactory.h>\n#include <gadget\/Type\/DeviceConstructor.h>\n\n\/\/ Sims\n#include <gadget\/Devices\/Sim\/SimAnalog.h>\n#include <gadget\/Devices\/Sim\/SimDigital.h>\n#include <gadget\/Devices\/Sim\/SimPosition.h>\n#include <gadget\/Devices\/Sim\/SimGloveGesture.h>\n\/\/#include <gadget\/Devices\/Sim\/SimKeyboardDigital.h>\n#include <gadget\/Devices\/Sim\/SimRelativePosition.h>\n#include <gadget\/Devices\/Sim\/SimSetablePosition.h>\n#include <gadget\/Devices\/Sim\/SimDigitalGlove.h>\n\n#if defined(VPR_OS_Win32)\n# include <gadget\/Devices\/EventWindow\/EventWindowWin32.h>\n#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)\n# include <gadget\/Devices\/EventWindow\/EventWindowOSX.h>\n#else\n# include <gadget\/Devices\/EventWindow\/EventWindowXWin.h>\n# include <gadget\/Devices\/EventWindow\/EventWindowDepCheckerXWin.h>\n#endif\n\n\/* Physical devices *\/\n#ifdef STATIC_DRIVERS\n\n\/* PThread Dependant Driver *\/\n#ifdef GADGET_HAVE_DTK\n# include <gadget\/Devices\/Open\/DTK\/DTK.h>\n#endif\n\n#endif \/* STATIC_DRIVERS *\/\n\n#include <gadget\/Util\/Debug.h>\n\nnamespace gadget\n{\n\n\/\/ Initialize the singleton ptr\n\/\/vjDeviceFactory* DeviceFactory::mInstance = NULL;\n\/\/vjSingletonImp( DeviceFactory ); \/\/kevin\nvprSingletonImpWithInitFunc(DeviceFactory, loadKnownDevices);\n\n\/**\n * Registers all the devices that I know about.\n *\/\nvoid DeviceFactory::loadKnownDevices()\n{\n gadget::InputManager* input_mgr = gadget::InputManager::instance();\n\n#ifdef STATIC_DRIVERS\n\n#ifdef GADGET_HAVE_DTK\n DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;\n if( (NULL == dtk_wrapper))\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\" << vprDEBUG_FLUSH;\n }\n#endif\n\n#endif \/* STATIC_DRIVERS *\/\n\n DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>(input_mgr);\n DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>(input_mgr);\n DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>(input_mgr);\n \/\/DeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>(input_mgr);\n DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>(input_mgr);\n DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>(input_mgr);\n\n DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>(input_mgr);\n DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>(input_mgr);\n\n if( (NULL == sim_analog) ||\n (NULL == sim_digital) ||\n (NULL == sim_position) ||\n (NULL == sim_glove) ||\n (NULL == simpinch_glove) ||\n (NULL == sim_setable) ||\n (NULL == sim_relative) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\" << vprDEBUG_FLUSH;\n }\n\n#if defined(VPR_OS_Win32)\n DeviceConstructor<EventWindowWin32>* key_win32 =\n new DeviceConstructor<EventWindowWin32>(input_mgr);\n if( (NULL == key_win32))\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)\n DeviceConstructor<EventWindowOSX>* osx_keyboard =\n new DeviceConstructor<EventWindowOSX>(input_mgr);\n if( (NULL == osx_keyboard) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#else\n DeviceConstructor<EventWindowXWin>* xwin_key =\n new DeviceConstructor<EventWindowXWin>(input_mgr);\n jccl::DependencyManager::instance()->registerChecker(new EventWindowDepCheckerXWin());\n if( (NULL == xwin_key) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#endif\n\n}\n\nvoid DeviceFactory::registerDevice(DeviceConstructorBase* constructor)\n{\n vprASSERT(constructor != NULL);\n mConstructors.push_back(constructor); \/\/ Add the constructor to the list\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)\n << \"gadget::DeviceFactory: Registered: \"\n << std::setiosflags(std::ios::right) << std::setw(25)\n << std::setfill(' ') << constructor->getElementType()\n << std::setiosflags(std::ios::right)\n \/\/<< \" :\" << (void*)constructor\n << \" type: \" << typeid(*constructor).name() << std::endl\n << vprDEBUG_FLUSH;\n}\n\n\/\/ Simply query all device constructors registered looking\n\/\/ for one that knows how to load the device\nbool DeviceFactory::recognizeDevice(jccl::ConfigElementPtr element)\n{\n return ! (findConstructor(element) == -1);\n}\n\n\/**\n * Loads the specified device.\n *\/\nInput* DeviceFactory::loadDevice(jccl::ConfigElementPtr element)\n{\n vprASSERT(recognizeDevice(element));\n\n int index(findConstructor(element));\n\n Input* new_dev;\n DeviceConstructorBase* constructor = mConstructors[index];\n\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)\n << \"gadget::DeviceFactory::loadDevice: Loading device: \"\n << element->getID() << \" with: \" << typeid(*constructor).name()\n << std::endl << vprDEBUG_FLUSH;\n\n new_dev = constructor->createDevice(element);\n return new_dev;\n}\n\nint DeviceFactory::findConstructor(jccl::ConfigElementPtr element)\n{\n const std::string element_type(element->getID());\n\n for ( unsigned int i = 0; i < mConstructors.size(); ++i )\n {\n \/\/ Get next constructor\n DeviceConstructorBase* construct = mConstructors[i];\n vprASSERT(construct != NULL);\n\n if(construct->getElementType() == element_type)\n {\n return i;\n }\n }\n\n return -1;\n}\n\n\nvoid DeviceFactory::debugDump()\n{\n vprDEBUG_OutputGuard(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL,\n std::string(\"gadget::DeviceFactory::debugDump\\n\"),\n std::string(\"------ END DUMP ------\\n\"));\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL) << \"num constructors:\"\n << mConstructors.size() << \"\\n\"\n << vprDEBUG_FLUSH;\n\n for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)\n {\n DeviceConstructorBase* dev_constr = mConstructors[cNum];\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)\n << cNum << \": Constructor:\" << (void*)dev_constr\n << \" type:\" << typeid(*dev_constr).name() << \"\\n\" << vprDEBUG_FLUSH;\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)\n << \" recog:\" << dev_constr->getElementType() << \"\\n\"\n << vprDEBUG_FLUSH;\n }\n}\n\n} \/\/ End of gadget namespace\n<commit_msg>Added a missing #include.<commit_after>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/gadgetConfig.h>\n#include <typeinfo>\n#include <vpr\/vpr.h>\n#include <jccl\/Config\/ConfigElement.h>\n#include <gadget\/Type\/DeviceFactory.h>\n#include <gadget\/Type\/DeviceConstructor.h>\n\n\/\/ Sims\n#include <gadget\/Devices\/Sim\/SimAnalog.h>\n#include <gadget\/Devices\/Sim\/SimDigital.h>\n#include <gadget\/Devices\/Sim\/SimPosition.h>\n#include <gadget\/Devices\/Sim\/SimGloveGesture.h>\n\/\/#include <gadget\/Devices\/Sim\/SimKeyboardDigital.h>\n#include <gadget\/Devices\/Sim\/SimRelativePosition.h>\n#include <gadget\/Devices\/Sim\/SimSetablePosition.h>\n#include <gadget\/Devices\/Sim\/SimDigitalGlove.h>\n\n#if defined(VPR_OS_Win32)\n# include <gadget\/Devices\/EventWindow\/EventWindowWin32.h>\n#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)\n# include <gadget\/Devices\/EventWindow\/EventWindowOSX.h>\n#else\n# include <jccl\/RTRC\/DependencyManager.h>\n# include <gadget\/Devices\/EventWindow\/EventWindowXWin.h>\n# include <gadget\/Devices\/EventWindow\/EventWindowDepCheckerXWin.h>\n#endif\n\n\/* Physical devices *\/\n#ifdef STATIC_DRIVERS\n\n\/* PThread Dependant Driver *\/\n#ifdef GADGET_HAVE_DTK\n# include <gadget\/Devices\/Open\/DTK\/DTK.h>\n#endif\n\n#endif \/* STATIC_DRIVERS *\/\n\n#include <gadget\/Util\/Debug.h>\n\nnamespace gadget\n{\n\n\/\/ Initialize the singleton ptr\n\/\/vjDeviceFactory* DeviceFactory::mInstance = NULL;\n\/\/vjSingletonImp( DeviceFactory ); \/\/kevin\nvprSingletonImpWithInitFunc(DeviceFactory, loadKnownDevices);\n\n\/**\n * Registers all the devices that I know about.\n *\/\nvoid DeviceFactory::loadKnownDevices()\n{\n gadget::InputManager* input_mgr = gadget::InputManager::instance();\n\n#ifdef STATIC_DRIVERS\n\n#ifdef GADGET_HAVE_DTK\n DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;\n if( (NULL == dtk_wrapper))\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\" << vprDEBUG_FLUSH;\n }\n#endif\n\n#endif \/* STATIC_DRIVERS *\/\n\n DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>(input_mgr);\n DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>(input_mgr);\n DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>(input_mgr);\n \/\/DeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>(input_mgr);\n DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>(input_mgr);\n DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>(input_mgr);\n\n DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>(input_mgr);\n DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>(input_mgr);\n\n if( (NULL == sim_analog) ||\n (NULL == sim_digital) ||\n (NULL == sim_position) ||\n (NULL == sim_glove) ||\n (NULL == simpinch_glove) ||\n (NULL == sim_setable) ||\n (NULL == sim_relative) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\" << vprDEBUG_FLUSH;\n }\n\n#if defined(VPR_OS_Win32)\n DeviceConstructor<EventWindowWin32>* key_win32 =\n new DeviceConstructor<EventWindowWin32>(input_mgr);\n if( (NULL == key_win32))\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)\n DeviceConstructor<EventWindowOSX>* osx_keyboard =\n new DeviceConstructor<EventWindowOSX>(input_mgr);\n if( (NULL == osx_keyboard) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#else\n DeviceConstructor<EventWindowXWin>* xwin_key =\n new DeviceConstructor<EventWindowXWin>(input_mgr);\n jccl::DependencyManager::instance()->registerChecker(new EventWindowDepCheckerXWin());\n if( (NULL == xwin_key) )\n {\n vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)\n << clrOutBOLD(clrRED,\"ERROR:\") << \"Failed to load a known device\\n\"\n << vprDEBUG_FLUSH;\n }\n#endif\n\n}\n\nvoid DeviceFactory::registerDevice(DeviceConstructorBase* constructor)\n{\n vprASSERT(constructor != NULL);\n mConstructors.push_back(constructor); \/\/ Add the constructor to the list\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)\n << \"gadget::DeviceFactory: Registered: \"\n << std::setiosflags(std::ios::right) << std::setw(25)\n << std::setfill(' ') << constructor->getElementType()\n << std::setiosflags(std::ios::right)\n \/\/<< \" :\" << (void*)constructor\n << \" type: \" << typeid(*constructor).name() << std::endl\n << vprDEBUG_FLUSH;\n}\n\n\/\/ Simply query all device constructors registered looking\n\/\/ for one that knows how to load the device\nbool DeviceFactory::recognizeDevice(jccl::ConfigElementPtr element)\n{\n return ! (findConstructor(element) == -1);\n}\n\n\/**\n * Loads the specified device.\n *\/\nInput* DeviceFactory::loadDevice(jccl::ConfigElementPtr element)\n{\n vprASSERT(recognizeDevice(element));\n\n int index(findConstructor(element));\n\n Input* new_dev;\n DeviceConstructorBase* constructor = mConstructors[index];\n\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)\n << \"gadget::DeviceFactory::loadDevice: Loading device: \"\n << element->getID() << \" with: \" << typeid(*constructor).name()\n << std::endl << vprDEBUG_FLUSH;\n\n new_dev = constructor->createDevice(element);\n return new_dev;\n}\n\nint DeviceFactory::findConstructor(jccl::ConfigElementPtr element)\n{\n const std::string element_type(element->getID());\n\n for ( unsigned int i = 0; i < mConstructors.size(); ++i )\n {\n \/\/ Get next constructor\n DeviceConstructorBase* construct = mConstructors[i];\n vprASSERT(construct != NULL);\n\n if(construct->getElementType() == element_type)\n {\n return i;\n }\n }\n\n return -1;\n}\n\n\nvoid DeviceFactory::debugDump()\n{\n vprDEBUG_OutputGuard(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL,\n std::string(\"gadget::DeviceFactory::debugDump\\n\"),\n std::string(\"------ END DUMP ------\\n\"));\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL) << \"num constructors:\"\n << mConstructors.size() << \"\\n\"\n << vprDEBUG_FLUSH;\n\n for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)\n {\n DeviceConstructorBase* dev_constr = mConstructors[cNum];\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)\n << cNum << \": Constructor:\" << (void*)dev_constr\n << \" type:\" << typeid(*dev_constr).name() << \"\\n\" << vprDEBUG_FLUSH;\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)\n << \" recog:\" << dev_constr->getElementType() << \"\\n\"\n << vprDEBUG_FLUSH;\n }\n}\n\n} \/\/ End of gadget namespace\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"profilemanager.h\"\n\n#include \"profile.h\"\n#include \"profileconfigwidget.h\"\n#include \"profilemanagerconfigwidget.h\"\n#include \"project.h\"\n\n#include <coreplugin\/icore.h>\n\n#include <extensionsystem\/pluginmanager.h>\n\n#include <utils\/persistentsettings.h>\n#include <utils\/environment.h>\n\n#include <QCoreApplication>\n#include <QDir>\n#include <QSettings>\n\n#include <QFormLayout>\n#include <QLabel>\n#include <QMainWindow>\n\nstatic const char PROFILE_DATA_KEY[] = \"Profile.\";\nstatic const char PROFILE_COUNT_KEY[] = \"Profile.Count\";\nstatic const char PROFILE_FILE_VERSION_KEY[] = \"Version\";\nstatic const char PROFILE_DEFAULT_KEY[] = \"Profile.Default\";\nstatic const char PROFILE_FILENAME[] = \"\/qtcreator\/profiles.xml\";\n\nusing Utils::PersistentSettingsWriter;\nusing Utils::PersistentSettingsReader;\n\nstatic QString settingsFileName()\n{\n ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();\n QFileInfo settingsLocation(pm->settings()->fileName());\n return settingsLocation.absolutePath() + QLatin1String(PROFILE_FILENAME);\n}\n\nnamespace ProjectExplorer {\n\nProfileManager *ProfileManager::m_instance = 0;\n\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ProfileManagerPrivate:\n\/\/ --------------------------------------------------------------------------\n\nclass ProfileManagerPrivate\n{\npublic:\n ProfileManagerPrivate();\n ~ProfileManagerPrivate();\n QList<Task> validateProfile(Profile *p) const;\n\n Profile *m_defaultProfile;\n bool m_initialized;\n QList<ProfileInformation *> m_informationList;\n QList<Profile *> m_profileList;\n};\n\nProfileManagerPrivate::ProfileManagerPrivate()\n : m_defaultProfile(0), m_initialized(false)\n{ }\n\nProfileManagerPrivate::~ProfileManagerPrivate()\n{\n}\n\nQList<Task> ProfileManagerPrivate::validateProfile(Profile *p) const\n{\n Q_ASSERT(p);\n QList<Task> result;\n bool hasError = false;\n foreach (ProfileInformation *pi, m_informationList) {\n QList<Task> tmp = pi->validate(p);\n foreach (const Task &t, tmp)\n if (t.type == Task::Error)\n hasError = true;\n result << tmp;\n }\n p->setValid(!hasError);\n return result;\n}\n\n} \/\/ namespace Internal\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ProfileManager:\n\/\/ --------------------------------------------------------------------------\n\nProfileManager *ProfileManager::instance()\n{\n return m_instance;\n}\n\nProfileManager::ProfileManager(QObject *parent) :\n QObject(parent),\n d(new Internal::ProfileManagerPrivate())\n{\n Q_ASSERT(!m_instance);\n m_instance = this;\n\n connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),\n this, SLOT(saveProfiles()));\n\n connect(this, SIGNAL(profileAdded(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n connect(this, SIGNAL(profileRemoved(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n connect(this, SIGNAL(profileUpdated(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n}\n\nvoid ProfileManager::restoreProfiles()\n{\n QList<Profile *> stsToRegister;\n QList<Profile *> stsToCheck;\n\n \/\/ read all profiles from SDK\n QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());\n ProfileList system = restoreProfiles(systemSettingsFile.absolutePath() + QLatin1String(PROFILE_FILENAME));\n QList<Profile *> readSts = system.profiles;\n \/\/ make sure we mark these as autodetected!\n foreach (Profile *p, readSts)\n p->setAutoDetected(true);\n\n stsToRegister = readSts; \/\/ SDK profiles are always considered to be up-to-date, so no need to\n \/\/ recheck them.\n\n \/\/ read all profile chains from user file\n ProfileList userProfiles = restoreProfiles(settingsFileName());\n readSts = userProfiles.profiles;\n\n foreach (Profile *p, readSts) {\n if (p->isAutoDetected())\n stsToCheck.append(p);\n else\n stsToRegister.append(p);\n }\n readSts.clear();\n\n \/\/ Then auto create profiles:\n QList<Profile *> detectedSts;\n Profile *defaultProfile = new Profile; \/\/ One profile using default values\n defaultProfile->setDisplayName(tr(\"Desktop\"));\n defaultProfile->setAutoDetected(true);\n defaultProfile->setIconPath(QLatin1String(\":\/\/\/DESKTOP\/\/\/\"));\n\n detectedSts << defaultProfile;\n\n \/\/ Find\/update autodetected profiles:\n Profile *toStore = 0;\n foreach (Profile *currentDetected, detectedSts) {\n toStore = currentDetected;\n\n \/\/ Check whether we had this profile stored and prefer the old one with the old id:\n for (int i = 0; i < stsToCheck.count(); ++i) {\n if (*(stsToCheck.at(i)) == *currentDetected) {\n toStore = stsToCheck.at(i);\n stsToCheck.removeAt(i);\n delete currentDetected;\n break;\n }\n }\n addProfile(toStore);\n }\n\n \/\/ Delete all loaded autodetected profiles that were not rediscovered:\n qDeleteAll(stsToCheck);\n\n \/\/ Store manual tool chains\n foreach (Profile *p, stsToRegister)\n addProfile(p);\n\n Profile *p = find(userProfiles.defaultProfile);\n if (p)\n setDefaultProfile(p);\n}\n\nProfileManager::~ProfileManager()\n{\n \/\/ Clean out profile information to avoid calling them during deregistration:\n qDeleteAll(d->m_informationList);\n qDeleteAll(d->m_profileList);\n delete d;\n m_instance = 0;\n}\n\nvoid ProfileManager::saveProfiles()\n{\n PersistentSettingsWriter writer;\n writer.saveValue(QLatin1String(PROFILE_FILE_VERSION_KEY), 1);\n\n int count = 0;\n foreach (Profile *p, profiles()) {\n QVariantMap tmp = p->toMap();\n if (tmp.isEmpty())\n continue;\n writer.saveValue(QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(count), tmp);\n ++count;\n }\n writer.saveValue(QLatin1String(PROFILE_COUNT_KEY), count);\n writer.saveValue(QLatin1String(PROFILE_DEFAULT_KEY),\n d->m_defaultProfile ? QString::fromLatin1(d->m_defaultProfile->id().name()) : QString());\n writer.save(settingsFileName(), QLatin1String(\"QtCreatorProfiles\"), Core::ICore::mainWindow());\n}\n\nbool greaterPriority(ProfileInformation *a, ProfileInformation *b)\n{\n return a->priority() > b->priority();\n}\n\nvoid ProfileManager::registerProfileInformation(ProfileInformation *pi)\n{\n QList<ProfileInformation *>::iterator it\n = qLowerBound(d->m_informationList.begin(), d->m_informationList.end(), pi, greaterPriority);\n d->m_informationList.insert(it, pi);\n\n connect(pi, SIGNAL(validationNeeded()), this, SLOT(validateProfiles()));\n\n if (!d->m_initialized)\n return;\n\n foreach (Profile *p, profiles()) {\n if (!p->hasValue(pi->dataId()))\n p->setValue(pi->dataId(), pi->defaultValue(p));\n }\n\n return;\n}\n\nvoid ProfileManager::deregisterProfileInformation(ProfileInformation *pi)\n{\n Q_ASSERT(d->m_informationList.contains(pi));\n d->m_informationList.removeAll(pi);\n delete pi;\n}\n\nProfileManager::ProfileList ProfileManager::restoreProfiles(const QString &fileName)\n{\n ProfileList result;\n\n PersistentSettingsReader reader;\n if (!reader.load(fileName))\n return result;\n QVariantMap data = reader.restoreValues();\n\n \/\/ Check version:\n int version = data.value(QLatin1String(PROFILE_FILE_VERSION_KEY), 0).toInt();\n if (version < 1)\n return result;\n\n const int count = data.value(QLatin1String(PROFILE_COUNT_KEY), 0).toInt();\n for (int i = 0; i < count; ++i) {\n const QString key = QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(i);\n if (!data.contains(key))\n break;\n\n const QVariantMap stMap = data.value(key).toMap();\n\n Profile *p = new Profile;\n if (p->fromMap(stMap)) {\n result.profiles.append(p);\n } else {\n delete p;\n qWarning(\"Warning: Unable to restore profiles stored in %s at position %d.\",\n qPrintable(QDir::toNativeSeparators(fileName)), i);\n }\n }\n const QString defaultId = data.value(QLatin1String(PROFILE_DEFAULT_KEY)).toString();\n if (defaultId.isEmpty())\n return result;\n\n const Core::Id id = Core::Id(defaultId);\n foreach (Profile *i, result.profiles) {\n if (i->id() == id) {\n result.defaultProfile = id;\n break;\n }\n }\n return result;\n}\n\nQList<Profile *> ProfileManager::profiles(const ProfileMatcher *m) const\n{\n if (!d->m_initialized) {\n d->m_initialized = true;\n const_cast<ProfileManager *>(this)->restoreProfiles();\n }\n\n QList<Profile *> result;\n foreach (Profile *p, d->m_profileList) {\n if (!m || m->matches(p))\n result.append(p);\n }\n return result;\n}\n\nProfile *ProfileManager::find(const Core::Id &id) const\n{\n if (!id.isValid())\n return 0;\n\n foreach (Profile *p, profiles()) {\n if (p->id() == id)\n return p;\n }\n return 0;\n}\n\nProfile *ProfileManager::find(const ProfileMatcher *m) const\n{\n QList<Profile *> matched = profiles(m);\n return matched.isEmpty() ? 0 : matched.first();\n}\n\nProfile *ProfileManager::defaultProfile()\n{\n if (!d->m_initialized) {\n d->m_initialized = true;\n restoreProfiles();\n }\n return d->m_defaultProfile;\n}\n\nQList<ProfileInformation *> ProfileManager::profileInformation() const\n{\n return d->m_informationList;\n}\n\nProfileConfigWidget *ProfileManager::createConfigWidget(Profile *p) const\n{\n if (!p)\n return 0;\n\n Internal::ProfileManagerConfigWidget *result = new Internal::ProfileManagerConfigWidget(p);\n foreach (ProfileInformation *pi, d->m_informationList)\n result->addConfigWidget(pi->createConfigWidget(p));\n\n return result;\n}\n\nvoid ProfileManager::notifyAboutUpdate(ProjectExplorer::Profile *p)\n{\n if (!p || !profiles().contains(p))\n return;\n d->validateProfile(p);\n emit profileUpdated(p);\n}\n\nbool ProfileManager::registerProfile(ProjectExplorer::Profile *p)\n{\n if (!p)\n return true;\n foreach (Profile *current, profiles()) {\n if (p == current)\n return false;\n }\n\n \/\/ Make name unique:\n QStringList names;\n foreach (Profile *tmp, profiles())\n names << tmp->displayName();\n p->setDisplayName(Project::makeUnique(p->displayName(), names));\n\n \/\/ make sure we have all the information in our profiles:\n foreach (ProfileInformation *pi, d->m_informationList) {\n if (!p->hasValue(pi->dataId()))\n p->setValue(pi->dataId(), pi->defaultValue(p));\n }\n\n addProfile(p);\n emit profileAdded(p);\n return true;\n}\n\nvoid ProfileManager::deregisterProfile(Profile *p)\n{\n if (!p || !profiles().contains(p))\n return;\n d->m_profileList.removeOne(p);\n if (d->m_defaultProfile == p) {\n QList<Profile *> stList = profiles();\n Profile *newDefault = 0;\n foreach (Profile *cur, stList) {\n if (cur->isValid()) {\n newDefault = cur;\n break;\n }\n }\n setDefaultProfile(newDefault);\n }\n emit profileRemoved(p);\n delete p;\n}\n\nQList<Task> ProfileManager::validateProfile(Profile *p)\n{\n QList<Task> result = d->validateProfile(p);\n qSort(result);\n return result;\n}\n\nvoid ProfileManager::setDefaultProfile(Profile *p)\n{\n if (d->m_defaultProfile == p)\n return;\n if (p && !profiles().contains(p))\n return;\n d->m_defaultProfile = p;\n emit defaultProfileChanged();\n}\n\nvoid ProfileManager::validateProfiles()\n{\n foreach (Profile *p, profiles())\n d->validateProfile(p);\n}\n\nvoid ProfileManager::addProfile(Profile *p)\n{\n if (!p)\n return;\n d->validateProfile(p);\n d->m_profileList.append(p);\n if (!d->m_defaultProfile ||\n (!d->m_defaultProfile->isValid() && p->isValid()))\n setDefaultProfile(p);\n}\n\n\nvoid ProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const\n{\n Q_UNUSED(p);\n Q_UNUSED(env);\n}\n\n} \/\/ namespace ProjectExplorer\n<commit_msg>ProfileManager: Create the desktop profile as manual<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"profilemanager.h\"\n\n#include \"profile.h\"\n#include \"profileconfigwidget.h\"\n#include \"profilemanagerconfigwidget.h\"\n#include \"project.h\"\n\n#include <coreplugin\/icore.h>\n\n#include <extensionsystem\/pluginmanager.h>\n\n#include <utils\/persistentsettings.h>\n#include <utils\/environment.h>\n\n#include <QCoreApplication>\n#include <QDir>\n#include <QSettings>\n\n#include <QFormLayout>\n#include <QLabel>\n#include <QMainWindow>\n\nstatic const char PROFILE_DATA_KEY[] = \"Profile.\";\nstatic const char PROFILE_COUNT_KEY[] = \"Profile.Count\";\nstatic const char PROFILE_FILE_VERSION_KEY[] = \"Version\";\nstatic const char PROFILE_DEFAULT_KEY[] = \"Profile.Default\";\nstatic const char PROFILE_FILENAME[] = \"\/qtcreator\/profiles.xml\";\n\nusing Utils::PersistentSettingsWriter;\nusing Utils::PersistentSettingsReader;\n\nstatic QString settingsFileName()\n{\n ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();\n QFileInfo settingsLocation(pm->settings()->fileName());\n return settingsLocation.absolutePath() + QLatin1String(PROFILE_FILENAME);\n}\n\nnamespace ProjectExplorer {\n\nProfileManager *ProfileManager::m_instance = 0;\n\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ProfileManagerPrivate:\n\/\/ --------------------------------------------------------------------------\n\nclass ProfileManagerPrivate\n{\npublic:\n ProfileManagerPrivate();\n ~ProfileManagerPrivate();\n QList<Task> validateProfile(Profile *p) const;\n\n Profile *m_defaultProfile;\n bool m_initialized;\n QList<ProfileInformation *> m_informationList;\n QList<Profile *> m_profileList;\n};\n\nProfileManagerPrivate::ProfileManagerPrivate()\n : m_defaultProfile(0), m_initialized(false)\n{ }\n\nProfileManagerPrivate::~ProfileManagerPrivate()\n{\n}\n\nQList<Task> ProfileManagerPrivate::validateProfile(Profile *p) const\n{\n Q_ASSERT(p);\n QList<Task> result;\n bool hasError = false;\n foreach (ProfileInformation *pi, m_informationList) {\n QList<Task> tmp = pi->validate(p);\n foreach (const Task &t, tmp)\n if (t.type == Task::Error)\n hasError = true;\n result << tmp;\n }\n p->setValid(!hasError);\n return result;\n}\n\n} \/\/ namespace Internal\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ProfileManager:\n\/\/ --------------------------------------------------------------------------\n\nProfileManager *ProfileManager::instance()\n{\n return m_instance;\n}\n\nProfileManager::ProfileManager(QObject *parent) :\n QObject(parent),\n d(new Internal::ProfileManagerPrivate())\n{\n Q_ASSERT(!m_instance);\n m_instance = this;\n\n connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),\n this, SLOT(saveProfiles()));\n\n connect(this, SIGNAL(profileAdded(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n connect(this, SIGNAL(profileRemoved(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n connect(this, SIGNAL(profileUpdated(ProjectExplorer::Profile*)),\n this, SIGNAL(profilesChanged()));\n}\n\nvoid ProfileManager::restoreProfiles()\n{\n QList<Profile *> stsToRegister;\n QList<Profile *> stsToCheck;\n\n \/\/ read all profiles from SDK\n QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());\n ProfileList system = restoreProfiles(systemSettingsFile.absolutePath() + QLatin1String(PROFILE_FILENAME));\n QList<Profile *> readSts = system.profiles;\n \/\/ make sure we mark these as autodetected!\n foreach (Profile *p, readSts)\n p->setAutoDetected(true);\n\n stsToRegister = readSts; \/\/ SDK profiles are always considered to be up-to-date, so no need to\n \/\/ recheck them.\n\n \/\/ read all profile chains from user file\n ProfileList userProfiles = restoreProfiles(settingsFileName());\n readSts = userProfiles.profiles;\n\n foreach (Profile *p, readSts) {\n if (p->isAutoDetected())\n stsToCheck.append(p);\n else\n stsToRegister.append(p);\n }\n readSts.clear();\n\n \/\/ Then auto create profiles:\n QList<Profile *> detectedSts;\n\n \/\/ Find\/update autodetected profiles:\n Profile *toStore = 0;\n foreach (Profile *currentDetected, detectedSts) {\n toStore = currentDetected;\n\n \/\/ Check whether we had this profile stored and prefer the old one with the old id:\n for (int i = 0; i < stsToCheck.count(); ++i) {\n if (*(stsToCheck.at(i)) == *currentDetected) {\n toStore = stsToCheck.at(i);\n stsToCheck.removeAt(i);\n delete currentDetected;\n break;\n }\n }\n addProfile(toStore);\n }\n\n \/\/ Delete all loaded autodetected profiles that were not rediscovered:\n qDeleteAll(stsToCheck);\n\n \/\/ Store manual profiles\n foreach (Profile *p, stsToRegister)\n addProfile(p);\n\n if (profiles().isEmpty()) {\n Profile *defaultProfile = new Profile; \/\/ One profile using default values\n defaultProfile->setDisplayName(tr(\"Desktop\"));\n defaultProfile->setAutoDetected(false);\n defaultProfile->setIconPath(QLatin1String(\":\/\/\/DESKTOP\/\/\/\"));\n\n addProfile(defaultProfile);\n }\n\n Profile *p = find(userProfiles.defaultProfile);\n if (p)\n setDefaultProfile(p);\n}\n\nProfileManager::~ProfileManager()\n{\n \/\/ Clean out profile information to avoid calling them during deregistration:\n qDeleteAll(d->m_informationList);\n qDeleteAll(d->m_profileList);\n delete d;\n m_instance = 0;\n}\n\nvoid ProfileManager::saveProfiles()\n{\n PersistentSettingsWriter writer;\n writer.saveValue(QLatin1String(PROFILE_FILE_VERSION_KEY), 1);\n\n int count = 0;\n foreach (Profile *p, profiles()) {\n QVariantMap tmp = p->toMap();\n if (tmp.isEmpty())\n continue;\n writer.saveValue(QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(count), tmp);\n ++count;\n }\n writer.saveValue(QLatin1String(PROFILE_COUNT_KEY), count);\n writer.saveValue(QLatin1String(PROFILE_DEFAULT_KEY),\n d->m_defaultProfile ? QString::fromLatin1(d->m_defaultProfile->id().name()) : QString());\n writer.save(settingsFileName(), QLatin1String(\"QtCreatorProfiles\"), Core::ICore::mainWindow());\n}\n\nbool greaterPriority(ProfileInformation *a, ProfileInformation *b)\n{\n return a->priority() > b->priority();\n}\n\nvoid ProfileManager::registerProfileInformation(ProfileInformation *pi)\n{\n QList<ProfileInformation *>::iterator it\n = qLowerBound(d->m_informationList.begin(), d->m_informationList.end(), pi, greaterPriority);\n d->m_informationList.insert(it, pi);\n\n connect(pi, SIGNAL(validationNeeded()), this, SLOT(validateProfiles()));\n\n if (!d->m_initialized)\n return;\n\n foreach (Profile *p, profiles()) {\n if (!p->hasValue(pi->dataId()))\n p->setValue(pi->dataId(), pi->defaultValue(p));\n }\n\n return;\n}\n\nvoid ProfileManager::deregisterProfileInformation(ProfileInformation *pi)\n{\n Q_ASSERT(d->m_informationList.contains(pi));\n d->m_informationList.removeAll(pi);\n delete pi;\n}\n\nProfileManager::ProfileList ProfileManager::restoreProfiles(const QString &fileName)\n{\n ProfileList result;\n\n PersistentSettingsReader reader;\n if (!reader.load(fileName))\n return result;\n QVariantMap data = reader.restoreValues();\n\n \/\/ Check version:\n int version = data.value(QLatin1String(PROFILE_FILE_VERSION_KEY), 0).toInt();\n if (version < 1)\n return result;\n\n const int count = data.value(QLatin1String(PROFILE_COUNT_KEY), 0).toInt();\n for (int i = 0; i < count; ++i) {\n const QString key = QString::fromLatin1(PROFILE_DATA_KEY) + QString::number(i);\n if (!data.contains(key))\n break;\n\n const QVariantMap stMap = data.value(key).toMap();\n\n Profile *p = new Profile;\n if (p->fromMap(stMap)) {\n result.profiles.append(p);\n } else {\n delete p;\n qWarning(\"Warning: Unable to restore profiles stored in %s at position %d.\",\n qPrintable(QDir::toNativeSeparators(fileName)), i);\n }\n }\n const QString defaultId = data.value(QLatin1String(PROFILE_DEFAULT_KEY)).toString();\n if (defaultId.isEmpty())\n return result;\n\n const Core::Id id = Core::Id(defaultId);\n foreach (Profile *i, result.profiles) {\n if (i->id() == id) {\n result.defaultProfile = id;\n break;\n }\n }\n return result;\n}\n\nQList<Profile *> ProfileManager::profiles(const ProfileMatcher *m) const\n{\n if (!d->m_initialized) {\n d->m_initialized = true;\n const_cast<ProfileManager *>(this)->restoreProfiles();\n }\n\n QList<Profile *> result;\n foreach (Profile *p, d->m_profileList) {\n if (!m || m->matches(p))\n result.append(p);\n }\n return result;\n}\n\nProfile *ProfileManager::find(const Core::Id &id) const\n{\n if (!id.isValid())\n return 0;\n\n foreach (Profile *p, profiles()) {\n if (p->id() == id)\n return p;\n }\n return 0;\n}\n\nProfile *ProfileManager::find(const ProfileMatcher *m) const\n{\n QList<Profile *> matched = profiles(m);\n return matched.isEmpty() ? 0 : matched.first();\n}\n\nProfile *ProfileManager::defaultProfile()\n{\n if (!d->m_initialized) {\n d->m_initialized = true;\n restoreProfiles();\n }\n return d->m_defaultProfile;\n}\n\nQList<ProfileInformation *> ProfileManager::profileInformation() const\n{\n return d->m_informationList;\n}\n\nProfileConfigWidget *ProfileManager::createConfigWidget(Profile *p) const\n{\n if (!p)\n return 0;\n\n Internal::ProfileManagerConfigWidget *result = new Internal::ProfileManagerConfigWidget(p);\n foreach (ProfileInformation *pi, d->m_informationList)\n result->addConfigWidget(pi->createConfigWidget(p));\n\n return result;\n}\n\nvoid ProfileManager::notifyAboutUpdate(ProjectExplorer::Profile *p)\n{\n if (!p || !profiles().contains(p))\n return;\n d->validateProfile(p);\n emit profileUpdated(p);\n}\n\nbool ProfileManager::registerProfile(ProjectExplorer::Profile *p)\n{\n if (!p)\n return true;\n foreach (Profile *current, profiles()) {\n if (p == current)\n return false;\n }\n\n \/\/ Make name unique:\n QStringList names;\n foreach (Profile *tmp, profiles())\n names << tmp->displayName();\n p->setDisplayName(Project::makeUnique(p->displayName(), names));\n\n \/\/ make sure we have all the information in our profiles:\n foreach (ProfileInformation *pi, d->m_informationList) {\n if (!p->hasValue(pi->dataId()))\n p->setValue(pi->dataId(), pi->defaultValue(p));\n }\n\n addProfile(p);\n emit profileAdded(p);\n return true;\n}\n\nvoid ProfileManager::deregisterProfile(Profile *p)\n{\n if (!p || !profiles().contains(p))\n return;\n d->m_profileList.removeOne(p);\n if (d->m_defaultProfile == p) {\n QList<Profile *> stList = profiles();\n Profile *newDefault = 0;\n foreach (Profile *cur, stList) {\n if (cur->isValid()) {\n newDefault = cur;\n break;\n }\n }\n setDefaultProfile(newDefault);\n }\n emit profileRemoved(p);\n delete p;\n}\n\nQList<Task> ProfileManager::validateProfile(Profile *p)\n{\n QList<Task> result = d->validateProfile(p);\n qSort(result);\n return result;\n}\n\nvoid ProfileManager::setDefaultProfile(Profile *p)\n{\n if (d->m_defaultProfile == p)\n return;\n if (p && !profiles().contains(p))\n return;\n d->m_defaultProfile = p;\n emit defaultProfileChanged();\n}\n\nvoid ProfileManager::validateProfiles()\n{\n foreach (Profile *p, profiles())\n d->validateProfile(p);\n}\n\nvoid ProfileManager::addProfile(Profile *p)\n{\n if (!p)\n return;\n d->validateProfile(p);\n d->m_profileList.append(p);\n if (!d->m_defaultProfile ||\n (!d->m_defaultProfile->isValid() && p->isValid()))\n setDefaultProfile(p);\n}\n\n\nvoid ProfileInformation::addToEnvironment(const Profile *p, Utils::Environment &env) const\n{\n Q_UNUSED(p);\n Q_UNUSED(env);\n}\n\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"MapQuestRunner.h\"\n\n#include \"MarbleAbstractRunner.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleLocale.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataExtendedData.h\"\n#include \"TinyWebBrowser.h\"\n#include \"routing\/Maneuver.h\"\n\n#include <QtCore\/QString>\n#include <QtCore\/QVector>\n#include <QtCore\/QUrl>\n#include <QtCore\/QTime>\n#include <QtCore\/QTimer>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkReply>\n#include <QtXml\/QDomDocument>\n\nnamespace Marble\n{\n\nMapQuestRunner::MapQuestRunner( QObject *parent ) :\n MarbleAbstractRunner( parent ),\n m_networkAccessManager( new QNetworkAccessManager( this ) )\n{\n connect( m_networkAccessManager, SIGNAL( finished( QNetworkReply * ) ),\n this, SLOT( retrieveData( QNetworkReply * ) ) );\n}\n\nMapQuestRunner::~MapQuestRunner()\n{\n \/\/ nothing to do\n}\n\nGeoDataFeature::GeoDataVisualCategory MapQuestRunner::category() const\n{\n return GeoDataFeature::OsmSite;\n}\n\nvoid MapQuestRunner::retrieveRoute( const RouteRequest *route )\n{\n if ( route->size() < 2 ) {\n return;\n }\n\n QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()[\"mapquest\"];\n\n QString url = \"http:\/\/open.mapquestapi.com\/directions\/v0\/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0\";\n GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;\n append( &url, \"from\", QString::number( route->source().latitude( degree ), 'f', 6 ) + \",\" + QString::number( route->source().longitude( degree ), 'f', 6 ) );\n for ( int i=1; i<route->size(); ++i ) {\n append( &url, \"to\", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + \",\" + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );\n }\n\n QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == QLocale::MetricSystem ? \"k\" : \"m\";\n append( &url, \"units\", unit );\n\n if ( settings[\"noMotorways\"].toInt() ) {\n append( &url, \"avoids\", \"Limited Access\" );\n }\n if ( settings[\"noTollroads\"].toInt() ) {\n append( &url, \"avoids\", \"Toll road\" );\n }\n if ( settings[\"noFerries\"].toInt() ) {\n append( &url, \"avoids\", \"Ferry\" );\n }\n\n if ( !settings[\"preference\"].toString().isEmpty() ) {\n append( &url, \"routeType\", settings[\"preference\"].toString() );\n }\n\n QNetworkReply *reply = m_networkAccessManager->get( QNetworkRequest( QUrl( url ) ) );\n connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),\n this, SLOT( handleError( QNetworkReply::NetworkError ) ) );\n\n QEventLoop eventLoop;\n\n connect( this, SIGNAL( routeCalculated( GeoDataDocument* ) ),\n &eventLoop, SLOT( quit() ) );\n\n eventLoop.exec();\n}\n\nvoid MapQuestRunner::retrieveData( QNetworkReply *reply )\n{\n if ( reply->isFinished() ) {\n QByteArray data = reply->readAll();\n reply->deleteLater();\n \/\/mDebug() << \"Download completed: \" << data;\n GeoDataDocument* document = parse( data );\n\n if ( !document ) {\n mDebug() << \"Failed to parse the downloaded route data\" << data;\n }\n\n emit routeCalculated( document );\n }\n}\n\nvoid MapQuestRunner::handleError( QNetworkReply::NetworkError error )\n{\n mDebug() << \" Error when retrieving mapquest.org route: \" << error;\n}\n\nvoid MapQuestRunner::append(QString *input, const QString &key, const QString &value)\n{\n *input += \"&\" + key + \"=\" + value;\n}\n\nint MapQuestRunner::maneuverType( int mapQuestId ) const\n{\n \/** @todo FIXME: review 10, 11 *\/\n switch( mapQuestId ) {\n case 0: return Maneuver::Straight ; \/\/ straight\n case 1: return Maneuver::SlightRight ; \/\/ slight right\n case 2: return Maneuver::Right ; \/\/ right\n case 3: return Maneuver::SharpRight ; \/\/ sharp right\n case 4: return Maneuver::TurnAround ; \/\/ reverse\n case 5: return Maneuver::SharpLeft ; \/\/ sharp left\n case 6: return Maneuver::Left ; \/\/ left\n case 7: return Maneuver::SlightLeft ; \/\/ slight left\n case 8: return Maneuver::TurnAround ; \/\/ right u-turn\n case 9: return Maneuver::TurnAround ; \/\/ left u-turn\n case 10: return Maneuver::Merge ; \/\/ right merge\n case 11: return Maneuver::Merge ; \/\/ left merge\n case 12: return Maneuver::Merge ; \/\/ right on ramp\n case 13: return Maneuver::Merge ; \/\/ left on ramp\n case 14: return Maneuver::ExitRight ; \/\/ right off ramp\n case 15: return Maneuver::ExitLeft ; \/\/ left off ramp\n case 16: return Maneuver::Right ; \/\/ right fork\n case 17: return Maneuver::Left ; \/\/ left fork\n case 18: return Maneuver::Continue ; \/\/ straight fork\n }\n\n return Maneuver::Unknown;\n}\n\nGeoDataDocument* MapQuestRunner::parse( const QByteArray &content ) const\n{\n QDomDocument xml;\n if ( !xml.setContent( content ) ) {\n mDebug() << \"Cannot parse xml file with routing instructions.\";\n return 0;\n }\n\n \/\/ mDebug() << xml.toString(2);\n QDomElement root = xml.documentElement();\n\n GeoDataDocument* result = new GeoDataDocument();\n result->setName( \"MapQuest\" );\n GeoDataPlacemark* routePlacemark = new GeoDataPlacemark;\n routePlacemark->setName( \"Route\" );\n\n GeoDataLineString* routeWaypoints = new GeoDataLineString;\n QDomNodeList shapePoints = root.elementsByTagName( \"shapePoints\" );\n if ( shapePoints.size() == 1 ) {\n QDomNodeList geometry = shapePoints.at( 0 ).toElement().elementsByTagName( \"latLng\" );\n for ( int i=0; i<geometry.size(); ++i ) {\n double const lat = geometry.item( i ).namedItem( \"lat\" ).toElement().text().toDouble();\n double const lon = geometry.item( i ).namedItem( \"lng\" ).toElement().text().toDouble();\n GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree );\n routeWaypoints->append( position );\n }\n }\n routePlacemark->setGeometry( routeWaypoints );\n\n QString name = \"%1 %2 (MapQuest)\";\n QString unit = \"m\";\n qreal length = routeWaypoints->length( EARTH_RADIUS );\n if (length >= 1000) {\n length \/= 1000.0;\n unit = \"km\";\n }\n result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) );\n result->append( routePlacemark );\n\n QMap<int,int> mapping;\n QDomNodeList maneuvers = root.elementsByTagName( \"maneuverIndexes\" );\n if ( maneuvers.size() == 1 ) {\n maneuvers = maneuvers.at( 0 ).childNodes();\n for ( int i=0; i<maneuvers.size(); ++i ) {\n mapping[i] = maneuvers.at( i ).toElement().text().toInt();\n if ( mapping[i] == routeWaypoints->size() ) {\n --mapping[i];\n }\n }\n }\n\n QDomNodeList instructions = root.elementsByTagName( \"maneuver\" );\n unsigned int const lastInstruction = qMax<int>( 0, instructions.length()-1 ); \/\/ ignore the last 'Welcome to xy' instruction\n for ( unsigned int i = 0; i < lastInstruction; ++i ) {\n QDomElement node = instructions.item( i ).toElement();\n\n QDomNodeList maneuver = node.elementsByTagName( \"turnType\" );\n QDomNodeList textNodes = node.elementsByTagName( \"narrative\" );\n QDomNodeList points = node.elementsByTagName( \"startPoint\" );\n QDomNodeList streets = node.elementsByTagName( \"streets\" );\n\n Q_ASSERT( mapping.contains( i ) );\n if ( textNodes.size() == 1 && maneuver.size() == 1 && points.size() == 1 && mapping.contains( i ) ) {\n GeoDataPlacemark* instruction = new GeoDataPlacemark;\n instruction->setName( textNodes.at( 0 ).toElement().text() );\n\n GeoDataExtendedData extendedData;\n GeoDataData turnType;\n turnType.setName( \"turnType\" );\n turnType.setValue( maneuverType( maneuver.at( 0 ).toElement().text().toInt() ) );\n extendedData.addValue( turnType );\n if ( streets.size() == 1 ) {\n GeoDataData roadName;\n roadName.setName( \"roadName\" );\n roadName.setValue( streets.at( 0 ).toElement().text() );\n extendedData.addValue( roadName );\n }\n instruction->setExtendedData( extendedData );\n\n int const start = mapping[i];\n int const end = mapping.contains(i+1) ? mapping[i+1] : routeWaypoints->size()-1;\n if ( start >= 0 && start < routeWaypoints->size() && end < routeWaypoints->size() ) {\n instruction->setName( textNodes.item( 0 ).toElement().text() );\n GeoDataLineString *lineString = new GeoDataLineString;\n for ( int j=start; j<=end; ++j ) {\n *lineString << GeoDataCoordinates( routeWaypoints->at( j ).longitude(), routeWaypoints->at( j ).latitude() );\n }\n\n if ( !lineString->isEmpty() ) {\n instruction->setGeometry( lineString );\n result->append( instruction );\n }\n }\n }\n }\n\n return result;\n}\n\n\n} \/\/ namespace Marble\n\n#include \"MapQuestRunner.moc\"\n<commit_msg>delete routing document when it is empty<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"MapQuestRunner.h\"\n\n#include \"MarbleAbstractRunner.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleLocale.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataExtendedData.h\"\n#include \"TinyWebBrowser.h\"\n#include \"routing\/Maneuver.h\"\n\n#include <QtCore\/QString>\n#include <QtCore\/QVector>\n#include <QtCore\/QUrl>\n#include <QtCore\/QTime>\n#include <QtCore\/QTimer>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkReply>\n#include <QtXml\/QDomDocument>\n\nnamespace Marble\n{\n\nMapQuestRunner::MapQuestRunner( QObject *parent ) :\n MarbleAbstractRunner( parent ),\n m_networkAccessManager( new QNetworkAccessManager( this ) )\n{\n connect( m_networkAccessManager, SIGNAL( finished( QNetworkReply * ) ),\n this, SLOT( retrieveData( QNetworkReply * ) ) );\n}\n\nMapQuestRunner::~MapQuestRunner()\n{\n \/\/ nothing to do\n}\n\nGeoDataFeature::GeoDataVisualCategory MapQuestRunner::category() const\n{\n return GeoDataFeature::OsmSite;\n}\n\nvoid MapQuestRunner::retrieveRoute( const RouteRequest *route )\n{\n if ( route->size() < 2 ) {\n return;\n }\n\n QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()[\"mapquest\"];\n\n QString url = \"http:\/\/open.mapquestapi.com\/directions\/v0\/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0\";\n GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;\n append( &url, \"from\", QString::number( route->source().latitude( degree ), 'f', 6 ) + \",\" + QString::number( route->source().longitude( degree ), 'f', 6 ) );\n for ( int i=1; i<route->size(); ++i ) {\n append( &url, \"to\", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + \",\" + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );\n }\n\n QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == QLocale::MetricSystem ? \"k\" : \"m\";\n append( &url, \"units\", unit );\n\n if ( settings[\"noMotorways\"].toInt() ) {\n append( &url, \"avoids\", \"Limited Access\" );\n }\n if ( settings[\"noTollroads\"].toInt() ) {\n append( &url, \"avoids\", \"Toll road\" );\n }\n if ( settings[\"noFerries\"].toInt() ) {\n append( &url, \"avoids\", \"Ferry\" );\n }\n\n if ( !settings[\"preference\"].toString().isEmpty() ) {\n append( &url, \"routeType\", settings[\"preference\"].toString() );\n }\n\n QNetworkReply *reply = m_networkAccessManager->get( QNetworkRequest( QUrl( url ) ) );\n connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),\n this, SLOT( handleError( QNetworkReply::NetworkError ) ) );\n\n QEventLoop eventLoop;\n\n connect( this, SIGNAL( routeCalculated( GeoDataDocument* ) ),\n &eventLoop, SLOT( quit() ) );\n\n eventLoop.exec();\n}\n\nvoid MapQuestRunner::retrieveData( QNetworkReply *reply )\n{\n if ( reply->isFinished() ) {\n QByteArray data = reply->readAll();\n reply->deleteLater();\n \/\/mDebug() << \"Download completed: \" << data;\n GeoDataDocument* document = parse( data );\n\n if ( !document ) {\n mDebug() << \"Failed to parse the downloaded route data\" << data;\n }\n\n emit routeCalculated( document );\n }\n}\n\nvoid MapQuestRunner::handleError( QNetworkReply::NetworkError error )\n{\n mDebug() << \" Error when retrieving mapquest.org route: \" << error;\n}\n\nvoid MapQuestRunner::append(QString *input, const QString &key, const QString &value)\n{\n *input += \"&\" + key + \"=\" + value;\n}\n\nint MapQuestRunner::maneuverType( int mapQuestId ) const\n{\n \/** @todo FIXME: review 10, 11 *\/\n switch( mapQuestId ) {\n case 0: return Maneuver::Straight ; \/\/ straight\n case 1: return Maneuver::SlightRight ; \/\/ slight right\n case 2: return Maneuver::Right ; \/\/ right\n case 3: return Maneuver::SharpRight ; \/\/ sharp right\n case 4: return Maneuver::TurnAround ; \/\/ reverse\n case 5: return Maneuver::SharpLeft ; \/\/ sharp left\n case 6: return Maneuver::Left ; \/\/ left\n case 7: return Maneuver::SlightLeft ; \/\/ slight left\n case 8: return Maneuver::TurnAround ; \/\/ right u-turn\n case 9: return Maneuver::TurnAround ; \/\/ left u-turn\n case 10: return Maneuver::Merge ; \/\/ right merge\n case 11: return Maneuver::Merge ; \/\/ left merge\n case 12: return Maneuver::Merge ; \/\/ right on ramp\n case 13: return Maneuver::Merge ; \/\/ left on ramp\n case 14: return Maneuver::ExitRight ; \/\/ right off ramp\n case 15: return Maneuver::ExitLeft ; \/\/ left off ramp\n case 16: return Maneuver::Right ; \/\/ right fork\n case 17: return Maneuver::Left ; \/\/ left fork\n case 18: return Maneuver::Continue ; \/\/ straight fork\n }\n\n return Maneuver::Unknown;\n}\n\nGeoDataDocument* MapQuestRunner::parse( const QByteArray &content ) const\n{\n QDomDocument xml;\n if ( !xml.setContent( content ) ) {\n mDebug() << \"Cannot parse xml file with routing instructions.\";\n return 0;\n }\n\n \/\/ mDebug() << xml.toString(2);\n QDomElement root = xml.documentElement();\n\n GeoDataDocument* result = new GeoDataDocument();\n result->setName( \"MapQuest\" );\n GeoDataPlacemark* routePlacemark = new GeoDataPlacemark;\n routePlacemark->setName( \"Route\" );\n\n GeoDataLineString* routeWaypoints = new GeoDataLineString;\n QDomNodeList shapePoints = root.elementsByTagName( \"shapePoints\" );\n if ( shapePoints.size() == 1 ) {\n QDomNodeList geometry = shapePoints.at( 0 ).toElement().elementsByTagName( \"latLng\" );\n for ( int i=0; i<geometry.size(); ++i ) {\n double const lat = geometry.item( i ).namedItem( \"lat\" ).toElement().text().toDouble();\n double const lon = geometry.item( i ).namedItem( \"lng\" ).toElement().text().toDouble();\n GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree );\n routeWaypoints->append( position );\n }\n }\n routePlacemark->setGeometry( routeWaypoints );\n\n QString name = \"%1 %2 (MapQuest)\";\n QString unit = \"m\";\n qreal length = routeWaypoints->length( EARTH_RADIUS );\n if (length >= 1000) {\n length \/= 1000.0;\n unit = \"km\";\n }\n result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) );\n result->append( routePlacemark );\n\n QMap<int,int> mapping;\n QDomNodeList maneuvers = root.elementsByTagName( \"maneuverIndexes\" );\n if ( maneuvers.size() == 1 ) {\n maneuvers = maneuvers.at( 0 ).childNodes();\n for ( int i=0; i<maneuvers.size(); ++i ) {\n mapping[i] = maneuvers.at( i ).toElement().text().toInt();\n if ( mapping[i] == routeWaypoints->size() ) {\n --mapping[i];\n }\n }\n }\n\n QDomNodeList instructions = root.elementsByTagName( \"maneuver\" );\n unsigned int const lastInstruction = qMax<int>( 0, instructions.length()-1 ); \/\/ ignore the last 'Welcome to xy' instruction\n for ( unsigned int i = 0; i < lastInstruction; ++i ) {\n QDomElement node = instructions.item( i ).toElement();\n\n QDomNodeList maneuver = node.elementsByTagName( \"turnType\" );\n QDomNodeList textNodes = node.elementsByTagName( \"narrative\" );\n QDomNodeList points = node.elementsByTagName( \"startPoint\" );\n QDomNodeList streets = node.elementsByTagName( \"streets\" );\n\n Q_ASSERT( mapping.contains( i ) );\n if ( textNodes.size() == 1 && maneuver.size() == 1 && points.size() == 1 && mapping.contains( i ) ) {\n GeoDataPlacemark* instruction = new GeoDataPlacemark;\n instruction->setName( textNodes.at( 0 ).toElement().text() );\n\n GeoDataExtendedData extendedData;\n GeoDataData turnType;\n turnType.setName( \"turnType\" );\n turnType.setValue( maneuverType( maneuver.at( 0 ).toElement().text().toInt() ) );\n extendedData.addValue( turnType );\n if ( streets.size() == 1 ) {\n GeoDataData roadName;\n roadName.setName( \"roadName\" );\n roadName.setValue( streets.at( 0 ).toElement().text() );\n extendedData.addValue( roadName );\n }\n instruction->setExtendedData( extendedData );\n\n int const start = mapping[i];\n int const end = mapping.contains(i+1) ? mapping[i+1] : routeWaypoints->size()-1;\n if ( start >= 0 && start < routeWaypoints->size() && end < routeWaypoints->size() ) {\n instruction->setName( textNodes.item( 0 ).toElement().text() );\n GeoDataLineString *lineString = new GeoDataLineString;\n for ( int j=start; j<=end; ++j ) {\n *lineString << GeoDataCoordinates( routeWaypoints->at( j ).longitude(), routeWaypoints->at( j ).latitude() );\n }\n\n if ( !lineString->isEmpty() ) {\n instruction->setGeometry( lineString );\n result->append( instruction );\n }\n }\n }\n }\n\n if ( routeWaypoints->size() < 1 ) {\n delete result;\n result = 0;\n }\n\n return result;\n}\n\n\n} \/\/ namespace Marble\n\n#include \"MapQuestRunner.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\nTidyEngine\nCopyright (C) 2016 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\nContact the author at: jakob.sinclair99@gmail.com\n*\/\n\n#include \"audio.hpp\"\n#include <cstdio>\n#include <al.h>\n\nAudioSystem::AudioSystem(bool create)\n{\n\tif (create == true)\n\t\tCreateSystem();\n}\n\nAudioSystem::~AudioSystem()\n{\n\tDestroySystem();\n}\n\nvoid AudioSystem::CreateSystem()\n{\n\tm_Device = alcOpenDevice(nullptr);\n\tm_Context = alcCreateContext(m_Device, nullptr);\n\talcMakeContextCurrent(m_Context);\n\n\tint error = alcGetError(m_Device);\n\tif (error != ALC_NO_ERROR) {\n\t\tprintf(\"OpenAL error: %d\\n\", error);\n\t\talcDestroyContext(m_Context);\n\t\talcCloseDevice(m_Device);\n\t\tm_Context = nullptr;\n\t\tm_Device = nullptr;\n\t}\n\talListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f);\n\talListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f);\n}\n\nvoid AudioSystem::DestroySystem()\n{\n\tif (m_Context != nullptr)\n\t\talcDestroyContext(m_Context);\n\tif (m_Device != nullptr)\n\t\talcCloseDevice(m_Device);\n\n\talcMakeContextCurrent(nullptr);\n\n\tm_Context = nullptr;\n\tm_Device = nullptr;\n}\n\nconst ALCdevice *AudioSystem::GetDevice() const\n{\n\treturn m_Device;\n}\n<commit_msg>libTidyEngine: close audio device<commit_after>\/*\nTidyEngine\nCopyright (C) 2016 Jakob Sinclair\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\nContact the author at: jakob.sinclair99@gmail.com\n*\/\n\n#include \"audio.hpp\"\n#include <cstdio>\n#include <al.h>\n\nAudioSystem::AudioSystem(bool create)\n{\n\tif (create == true)\n\t\tCreateSystem();\n}\n\nAudioSystem::~AudioSystem()\n{\n\tDestroySystem();\n}\n\nvoid AudioSystem::CreateSystem()\n{\n\tm_Device = alcOpenDevice(nullptr);\n\tm_Context = alcCreateContext(m_Device, nullptr);\n\talcMakeContextCurrent(m_Context);\n\n\tint error = alcGetError(m_Device);\n\tif (error != ALC_NO_ERROR) {\n\t\tprintf(\"Error: OpenAL %d\\n\", error);\n\t\talcDestroyContext(m_Context);\n\t\talcCloseDevice(m_Device);\n\t\tm_Context = nullptr;\n\t\tm_Device = nullptr;\n\t}\n\talListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f);\n\talListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f);\n}\n\nvoid AudioSystem::DestroySystem()\n{\t\n\talcDestroyContext(m_Context);\t\n\talcCloseDevice(m_Device);\n\n\tm_Context = nullptr;\n\tm_Device = nullptr;\n}\n\nconst ALCdevice *AudioSystem::GetDevice() const\n{\n\treturn m_Device;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"BlobRegistryImpl.h\"\n\n#include \"BlobResourceHandle.h\"\n#include \"ResourceError.h\"\n#include \"ResourceHandle.h\"\n#include \"ResourceLoader.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include <wtf\/MainThread.h>\n#include <wtf\/StdLibExtras.h>\n\nnamespace WebCore {\n\n#if !PLATFORM(CHROMIUM)\nBlobRegistry& blobRegistry()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(BlobRegistryImpl, instance, ());\n return instance;\n}\n#endif\n\nbool BlobRegistryImpl::shouldLoadResource(const ResourceRequest& request) const\n{\n \/\/ If the resource is not fetched using the GET method, bail out.\n if (!equalIgnoringCase(request.httpMethod(), \"GET\"))\n return false;\n\n return true;\n}\n\nPassRefPtr<ResourceHandle> BlobRegistryImpl::createResourceHandle(const ResourceRequest& request, ResourceHandleClient* client)\n{\n if (!shouldLoadResource(request))\n return 0;\n\n return BlobResourceHandle::create(m_blobs.get(request.url().string()), request, client);\n}\n\nbool BlobRegistryImpl::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data)\n{\n if (!shouldLoadResource(request))\n return false;\n\n BlobResourceHandle::loadResourceSynchronously(m_blobs.get(request.url().string()), request, error, response, data);\n return true;\n}\n\nvoid BlobRegistryImpl::appendStorageItems(BlobStorageData* blobStorageData, const BlobDataItemList& items)\n{\n for (BlobDataItemList::const_iterator iter = items.begin(); iter != items.end(); ++iter) {\n if (iter->type == BlobDataItem::Data)\n blobStorageData->m_data.appendData(iter->data, iter->offset, iter->length);\n else {\n ASSERT(iter->type == BlobDataItem::File);\n blobStorageData->m_data.appendFile(iter->path, iter->offset, iter->length, iter->expectedModificationTime);\n }\n }\n}\n\nvoid BlobRegistryImpl::appendStorageItems(BlobStorageData* blobStorageData, const BlobDataItemList& items, long long offset, long long length)\n{\n ASSERT(length != BlobDataItem::toEndOfFile);\n\n BlobDataItemList::const_iterator iter = items.begin();\n if (offset) {\n for (; iter != items.end(); ++iter) {\n if (offset >= iter->length)\n offset -= iter->length;\n else\n break;\n }\n }\n\n for (; iter != items.end() && length > 0; ++iter) {\n long long currentLength = iter->length - offset;\n long long newLength = currentLength > length ? length : currentLength;\n if (iter->type == BlobDataItem::Data)\n blobStorageData->m_data.appendData(iter->data, iter->offset + offset, newLength);\n else {\n ASSERT(iter->type == BlobDataItem::File);\n blobStorageData->m_data.appendFile(iter->path, iter->offset + offset, newLength, iter->expectedModificationTime);\n }\n length -= newLength;\n offset = 0;\n }\n}\n\nvoid BlobRegistryImpl::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)\n{\n ASSERT(isMainThread());\n\n RefPtr<BlobStorageData> blobStorageData = BlobStorageData::create(blobData->contentType(), blobData->contentDisposition());\n\n \/\/ The blob data is stored in the \"canonical\" way. That is, it only contains a list of Data and File items.\n \/\/ 1) The Data item is denoted by the raw data and the range.\n \/\/ 2) The File item is denoted by the file path, the range and the expected modification time.\n \/\/ All the Blob items in the passing blob data are resolved and expanded into a set of Data and File items.\n\n for (BlobDataItemList::const_iterator iter = blobData->items().begin(); iter != blobData->items().end(); ++iter) {\n switch (iter->type) {\n case BlobDataItem::Data:\n blobStorageData->m_data.appendData(iter->data, 0, iter->data.length());\n break;\n case BlobDataItem::File:\n blobStorageData->m_data.appendFile(iter->path, iter->offset, iter->length, iter->expectedModificationTime);\n break;\n case BlobDataItem::Blob:\n if (m_blobs.contains(iter->url.string()))\n appendStorageItems(blobStorageData.get(), m_blobs.get(iter->url.string())->items(), iter->offset, iter->length);\n break;\n }\n }\n\n m_blobs.set(url.string(), blobStorageData);\n}\n\nvoid BlobRegistryImpl::registerBlobURL(const KURL& url, const KURL& srcURL)\n{\n ASSERT(isMainThread());\n\n RefPtr<BlobStorageData> src = m_blobs.get(srcURL.string());\n ASSERT(src);\n if (!src)\n return;\n\n RefPtr<BlobStorageData> blobStorageData = BlobStorageData::create(src->contentType(), src->contentDisposition());\n appendStorageItems(blobStorageData.get(), src->items());\n \n m_blobs.set(url.string(), blobStorageData);\n}\n\nvoid BlobRegistryImpl::unregisterBlobURL(const KURL& url)\n{\n ASSERT(isMainThread());\n m_blobs.remove(url.string());\n}\n\nPassRefPtr<BlobStorageData> BlobRegistryImpl::getBlobDataFromURL(const KURL& url) const\n{\n ASSERT(isMainThread());\n return m_blobs.get(url.string());\n}\n\n} \/\/ namespace WebCore\n<commit_msg>2010-08-30 Jian Li <jianli@chromium.org><commit_after>\/*\n * Copyright (C) 2010 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#if ENABLE(BLOB)\n\n#include \"BlobRegistryImpl.h\"\n\n#include \"BlobResourceHandle.h\"\n#include \"ResourceError.h\"\n#include \"ResourceHandle.h\"\n#include \"ResourceLoader.h\"\n#include \"ResourceRequest.h\"\n#include \"ResourceResponse.h\"\n#include <wtf\/MainThread.h>\n#include <wtf\/StdLibExtras.h>\n\nnamespace WebCore {\n\n#if !PLATFORM(CHROMIUM)\nBlobRegistry& blobRegistry()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(BlobRegistryImpl, instance, ());\n return instance;\n}\n#endif\n\nbool BlobRegistryImpl::shouldLoadResource(const ResourceRequest& request) const\n{\n \/\/ If the resource is not fetched using the GET method, bail out.\n if (!equalIgnoringCase(request.httpMethod(), \"GET\"))\n return false;\n\n return true;\n}\n\nPassRefPtr<ResourceHandle> BlobRegistryImpl::createResourceHandle(const ResourceRequest& request, ResourceHandleClient* client)\n{\n if (!shouldLoadResource(request))\n return 0;\n\n return BlobResourceHandle::create(m_blobs.get(request.url().string()), request, client);\n}\n\nbool BlobRegistryImpl::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data)\n{\n if (!shouldLoadResource(request))\n return false;\n\n BlobResourceHandle::loadResourceSynchronously(m_blobs.get(request.url().string()), request, error, response, data);\n return true;\n}\n\nvoid BlobRegistryImpl::appendStorageItems(BlobStorageData* blobStorageData, const BlobDataItemList& items)\n{\n for (BlobDataItemList::const_iterator iter = items.begin(); iter != items.end(); ++iter) {\n if (iter->type == BlobDataItem::Data)\n blobStorageData->m_data.appendData(iter->data, iter->offset, iter->length);\n else {\n ASSERT(iter->type == BlobDataItem::File);\n blobStorageData->m_data.appendFile(iter->path, iter->offset, iter->length, iter->expectedModificationTime);\n }\n }\n}\n\nvoid BlobRegistryImpl::appendStorageItems(BlobStorageData* blobStorageData, const BlobDataItemList& items, long long offset, long long length)\n{\n ASSERT(length != BlobDataItem::toEndOfFile);\n\n BlobDataItemList::const_iterator iter = items.begin();\n if (offset) {\n for (; iter != items.end(); ++iter) {\n if (offset >= iter->length)\n offset -= iter->length;\n else\n break;\n }\n }\n\n for (; iter != items.end() && length > 0; ++iter) {\n long long currentLength = iter->length - offset;\n long long newLength = currentLength > length ? length : currentLength;\n if (iter->type == BlobDataItem::Data)\n blobStorageData->m_data.appendData(iter->data, iter->offset + offset, newLength);\n else {\n ASSERT(iter->type == BlobDataItem::File);\n blobStorageData->m_data.appendFile(iter->path, iter->offset + offset, newLength, iter->expectedModificationTime);\n }\n length -= newLength;\n offset = 0;\n }\n}\n\nvoid BlobRegistryImpl::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)\n{\n ASSERT(isMainThread());\n\n RefPtr<BlobStorageData> blobStorageData = BlobStorageData::create(blobData->contentType(), blobData->contentDisposition());\n\n \/\/ The blob data is stored in the \"canonical\" way. That is, it only contains a list of Data and File items.\n \/\/ 1) The Data item is denoted by the raw data and the range.\n \/\/ 2) The File item is denoted by the file path, the range and the expected modification time.\n \/\/ All the Blob items in the passing blob data are resolved and expanded into a set of Data and File items.\n\n for (BlobDataItemList::const_iterator iter = blobData->items().begin(); iter != blobData->items().end(); ++iter) {\n switch (iter->type) {\n case BlobDataItem::Data:\n blobStorageData->m_data.appendData(iter->data, 0, iter->data.length());\n break;\n case BlobDataItem::File:\n blobStorageData->m_data.appendFile(iter->path, iter->offset, iter->length, iter->expectedModificationTime);\n break;\n case BlobDataItem::Blob:\n if (m_blobs.contains(iter->url.string()))\n appendStorageItems(blobStorageData.get(), m_blobs.get(iter->url.string())->items(), iter->offset, iter->length);\n break;\n }\n }\n\n m_blobs.set(url.string(), blobStorageData);\n}\n\nvoid BlobRegistryImpl::registerBlobURL(const KURL& url, const KURL& srcURL)\n{\n ASSERT(isMainThread());\n\n RefPtr<BlobStorageData> src = m_blobs.get(srcURL.string());\n ASSERT(src);\n if (!src)\n return;\n\n RefPtr<BlobStorageData> blobStorageData = BlobStorageData::create(src->contentType(), src->contentDisposition());\n appendStorageItems(blobStorageData.get(), src->items());\n \n m_blobs.set(url.string(), blobStorageData);\n}\n\nvoid BlobRegistryImpl::unregisterBlobURL(const KURL& url)\n{\n ASSERT(isMainThread());\n m_blobs.remove(url.string());\n}\n\nPassRefPtr<BlobStorageData> BlobRegistryImpl::getBlobDataFromURL(const KURL& url) const\n{\n ASSERT(isMainThread());\n return m_blobs.get(url.string());\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(BLOB)\n<|endoftext|>"} {"text":"<commit_before>#include \"minimal_scene.h\"\n\n#include \"augs\/templates\/algorithm_templates.h\"\n\n#include \"game\/enums\/party_category.h\"\n\n#include \"test_scenes\/test_scene_flavours.h\"\n#include \"test_scenes\/ingredients\/ingredients.h\"\n#include \"test_scenes\/test_scenes_content.h\"\n\n#include \"game\/transcendental\/cosmos.h\"\n#include \"game\/organization\/all_component_includes.h\"\n#include \"game\/organization\/all_messages_includes.h\"\n#include \"game\/transcendental\/logic_step.h\"\n\n#include \"game\/detail\/inventory\/perform_transfer.h\"\n#include \"view\/viewables\/image_cache.h\"\n\nnamespace test_scenes {\n\tentity_id minimal_scene::populate(const loaded_image_caches_map&, const logic_step step) const {\n\t\tconst int num_characters = 1;\n\n\t\tstd::vector<entity_id> new_characters;\n\t\tnew_characters.resize(num_characters);\n\n\t\tfor (int i = 0; i < num_characters; ++i) {\n\t\t\ttransformr transform;\n\n\t\t\tif (i == 0) {\n\t\t\t}\n\t\t\telse if (i == 1) {\n\t\t\t\ttransform.pos.x += 200;\n\t\t\t}\n\n\t\t\tconst auto new_character = prefabs::create_metropolis_soldier(step, transform, typesafe_sprintf(\"player%x\", i));\n\n\t\t\tnew_characters[i] = new_character;\n\n\t\t\tif (i == 0) {\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_value(100);\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_maximum_value(100);\n\t\t\t\tnew_character.get<components::attitude>().parties = party_category::RESISTANCE_CITIZEN;\n\t\t\t\tnew_character.get<components::attitude>().hostile_parties = party_category::METROPOLIS_CITIZEN;\n\t\t\t}\n\t\t\telse if (i == 1) {\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_value(100);\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_maximum_value(100);\n\t\t\t\tnew_character.get<components::attitude>().parties = party_category::METROPOLIS_CITIZEN;\n\t\t\t\tnew_character.get<components::attitude>().hostile_parties = party_category::RESISTANCE_CITIZEN;\n\t\t\t}\n\n\t\t\tauto& sentience = new_character.get<components::sentience>();\n\n\n\t\t\tfill_range(sentience.learned_spells, true);\n\t\t}\n\n\t\tprefabs::create_sample_rifle(step, vec2(100, -500 + 50),\n\t\t\tprefabs::create_sample_magazine(step, vec2(100, -650),\n\t\t\t\tprefabs::create_cyan_charge(step, vec2(0, 0))));\n\n\t\tprefabs::create_force_grenade(step, { 100, 100 });\n\t\tprefabs::create_force_grenade(step, { 200, 100 });\n\t\tprefabs::create_force_grenade(step, { 300, 100});\n\n\t\t\/* Test: create cyan charges first, only then magazine, and reinfer. *\/\n\t\tconst auto charge = prefabs::create_cyan_charge(step, vec2(0, 0));\n\t\tprefabs::create_sample_magazine(step, vec2(100, -650), charge);\n\n\t\tcosmic::reinfer_all_entities(step.get_cosmos());\n\n\t\t\/\/ _controlfp(0, _EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID | _EM_DENORMAL);\n\t\treturn new_characters[0];\n\t}\n}\n<commit_msg>added aligner to minimal test scene<commit_after>#include \"minimal_scene.h\"\n\n#include \"augs\/templates\/algorithm_templates.h\"\n\n#include \"game\/enums\/party_category.h\"\n\n#include \"test_scenes\/test_scene_flavours.h\"\n#include \"test_scenes\/ingredients\/ingredients.h\"\n#include \"test_scenes\/test_scenes_content.h\"\n\n#include \"game\/transcendental\/cosmos.h\"\n#include \"game\/organization\/all_component_includes.h\"\n#include \"game\/organization\/all_messages_includes.h\"\n#include \"game\/transcendental\/logic_step.h\"\n\n#include \"game\/detail\/inventory\/perform_transfer.h\"\n#include \"view\/viewables\/image_cache.h\"\n\n#include \"test_scenes\/scenes\/test_scene_node.h\"\n#include \"augs\/math\/cascade_aligner.h\"\n\nnamespace test_scenes {\n\tentity_id minimal_scene::populate(const loaded_image_caches_map& caches, const logic_step step) const {\n\t\tauto& world = step.get_cosmos();\n\n#if 0\n\t\tauto create = [&](auto&&... args) {\n\t\t\treturn create_test_scene_entity(world, std::forward<decltype(args)>(args)...);\n\t\t};\n#endif\n\n\t\tauto get_size_of = [&caches](const auto id) {\n\t\t\treturn vec2i(caches.at(to_image_id(id)).get_original_size());\n\t\t};\n\n\t\tconst int num_characters = 1;\n\n\t\tstd::vector<entity_id> new_characters;\n\t\tnew_characters.resize(num_characters);\n\n\t\tfor (int i = 0; i < num_characters; ++i) {\n\t\t\ttransformr transform;\n\n\t\t\tif (i == 0) {\n\t\t\t}\n\t\t\telse if (i == 1) {\n\t\t\t\ttransform.pos.x += 200;\n\t\t\t}\n\n\t\t\tconst auto new_character = prefabs::create_metropolis_soldier(step, transform, typesafe_sprintf(\"player%x\", i));\n\n\t\t\tnew_characters[i] = new_character;\n\n\t\t\tif (i == 0) {\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_value(100);\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_maximum_value(100);\n\t\t\t\tnew_character.get<components::attitude>().parties = party_category::RESISTANCE_CITIZEN;\n\t\t\t\tnew_character.get<components::attitude>().hostile_parties = party_category::METROPOLIS_CITIZEN;\n\t\t\t}\n\t\t\telse if (i == 1) {\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_value(100);\n\t\t\t\tnew_character.get<components::sentience>().get<health_meter_instance>().set_maximum_value(100);\n\t\t\t\tnew_character.get<components::attitude>().parties = party_category::METROPOLIS_CITIZEN;\n\t\t\t\tnew_character.get<components::attitude>().hostile_parties = party_category::RESISTANCE_CITIZEN;\n\t\t\t}\n\n\t\t\tauto& sentience = new_character.get<components::sentience>();\n\n\n\t\t\tfill_range(sentience.learned_spells, true);\n\t\t}\n\n#if 0\n\t\tprefabs::create_sample_rifle(step, vec2(100, -500 + 50),\n\t\t\tprefabs::create_sample_magazine(step, vec2(100, -650),\n\t\t\t\tprefabs::create_cyan_charge(step, vec2(0, 0))));\n\n\t\tprefabs::create_force_grenade(step, { 100, 100 });\n\t\tprefabs::create_force_grenade(step, { 200, 100 });\n\t\tprefabs::create_force_grenade(step, { 300, 100});\n\n\t\t\/* Test: create cyan charges first, only then magazine, and reinfer. *\/\n\t\tconst auto charge = prefabs::create_cyan_charge(step, vec2(0, 0));\n\t\tprefabs::create_sample_magazine(step, vec2(100, -650), charge);\n#endif\n\n\t\t{\n\t\t\tconst vec2 floor_size = get_size_of(test_scene_image_id::FLOOR);\n\t\t\tconst auto total_floor_size = floor_size * 10;\n\t\t\tconst auto floor_origin = vec2(512, -768);\n\n\t\t\tauto floor_align = [&](const auto flavour_id) {\n\t\t\t\treturn make_cascade_aligner(\n\t\t\t\t\tfloor_origin,\n\t\t\t\t\ttotal_floor_size, \n\t\t\t\t\ttest_scene_node { world, flavour_id }\n\t\t\t\t);\n\t\t\t};\n\n\t\t\tfloor_align(test_sprite_decorations::FLOOR).set_size(total_floor_size);\n\t\t}\n\n\t\tcosmic::reinfer_all_entities(world);\n\n\t\t\/\/ _controlfp(0, _EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID | _EM_DENORMAL);\n\t\treturn new_characters[0];\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"libs\/array\/sort.h\"\n#include \"object\/array.h\"\n#include \"object\/argument.h\"\n#include \"object\/function.h\"\n\n#include <algorithm>\n\nnamespace grok {\nnamespace libs {\nusing namespace grok::vm;\nusing namespace grok::obj;\n\nbool MyPred(std::shared_ptr<Object> A, std::shared_ptr<Object> B)\n{\n auto strA = A->as<JSObject>()->ToString();\n auto strB = B->as<JSObject>()->ToString();\n\n return strA < strB;\n}\n\nvoid SortArrayWithDefaultPredicate(std::shared_ptr<JSArray> arr)\n{\n std::sort(arr->begin(), arr->end(), MyPred);\n}\n\nvoid SortStringWithDefaultPredicate(std::shared_ptr<JSString> str)\n{\n auto &S = str->GetString();\n std::sort(S.begin(), S.end());\n}\n\nvoid SortWithDefaultPredicate(std::shared_ptr<Object> A)\n{\n if (IsJSArray(A)) {\n SortArrayWithDefaultPredicate(A->as<JSArray>());\n } else if (IsJSString(A)) {\n SortStringWithDefaultPredicate(A->as<JSString>());\n } else {\n return;\n }\n}\n\nvoid SortWithPredicate(std::shared_ptr<Object> obj,\n std::shared_ptr<Function> func)\n{\n if (!IsJSArray(obj))\n return;\n\n auto A = obj->as<JSArray>();\n std::sort(A->begin(), A->end(),\n [&func](auto a, auto b) {\n auto Args = CreateArgumentObject()->as<Argument>();\n Args->Push(a);\n Args->Push(b);\n auto vm = GetGlobalVMContext()->GetVM();\n\n auto R = CallJSFunction(func, Args, vm);\n\n int n = 0;\n if (IsJSNumber(R)) {\n n = (int)R->as<JSNumber>()->GetNumber();\n return n < 0 ? true : false;\n }\n return false;\n });\n}\n\nvoid SortInternal(std::shared_ptr<Object> A,\n std::shared_ptr<Object> pred, bool use_default_pred)\n{\n if (use_default_pred) {\n SortWithDefaultPredicate(A);\n } else {\n if (!IsFunction(pred))\n SortWithDefaultPredicate(A);\n else \n SortWithPredicate(A, pred->as<Function>());\n }\n}\n\n\/\/ this is a very generic sort function and can be applied to strings\n\/\/ and arrays or any other object having property length\nstd::shared_ptr<Object> ArraySort(std::shared_ptr<Argument> Args)\n{\n bool use_default_pred = false;\n\n \/\/ object on which we are applying sort\n auto Obj = Args->GetProperty(\"this\");\n auto O = Obj->as<JSObject>();\n\n \/\/ predicate\n auto Pred = Args->GetProperty(\"pred\");\n\n if (IsUndefined(Pred)) {\n use_default_pred = true;\n }\n\n SortInternal(Obj, Pred, use_default_pred);\n return Obj;\n}\n\n\n}\n} \/\/ grok\n<commit_msg>Fix: Use JSDouble over JSNumber<commit_after>#include \"libs\/array\/sort.h\"\n#include \"object\/array.h\"\n#include \"object\/argument.h\"\n#include \"object\/function.h\"\n\n#include <algorithm>\n\nnamespace grok {\nnamespace libs {\nusing namespace grok::vm;\nusing namespace grok::obj;\n\nbool MyPred(std::shared_ptr<Object> A, std::shared_ptr<Object> B)\n{\n auto strA = A->as<JSObject>()->ToString();\n auto strB = B->as<JSObject>()->ToString();\n\n return strA < strB;\n}\n\nvoid SortArrayWithDefaultPredicate(std::shared_ptr<JSArray> arr)\n{\n std::sort(arr->begin(), arr->end(), MyPred);\n}\n\nvoid SortStringWithDefaultPredicate(std::shared_ptr<JSString> str)\n{\n auto &S = str->GetString();\n std::sort(S.begin(), S.end());\n}\n\nvoid SortWithDefaultPredicate(std::shared_ptr<Object> A)\n{\n if (IsJSArray(A)) {\n SortArrayWithDefaultPredicate(A->as<JSArray>());\n } else if (IsJSString(A)) {\n SortStringWithDefaultPredicate(A->as<JSString>());\n } else {\n return;\n }\n}\n\nvoid SortWithPredicate(std::shared_ptr<Object> obj,\n std::shared_ptr<Function> func)\n{\n if (!IsJSArray(obj))\n return;\n\n auto A = obj->as<JSArray>();\n std::sort(A->begin(), A->end(),\n [&func](auto a, auto b) {\n auto Args = CreateArgumentObject()->as<Argument>();\n Args->Push(a);\n Args->Push(b);\n auto vm = GetGlobalVMContext()->GetVM();\n\n auto R = CallJSFunction(func, Args, vm);\n\n int n = 0;\n if (IsJSNumber(R)) {\n n = (int)R->as<JSDouble>()->GetNumber();\n return n < 0 ? true : false;\n }\n return false;\n });\n}\n\nvoid SortInternal(std::shared_ptr<Object> A,\n std::shared_ptr<Object> pred, bool use_default_pred)\n{\n if (use_default_pred) {\n SortWithDefaultPredicate(A);\n } else {\n if (!IsFunction(pred))\n SortWithDefaultPredicate(A);\n else \n SortWithPredicate(A, pred->as<Function>());\n }\n}\n\n\/\/ this is a very generic sort function and can be applied to strings\n\/\/ and arrays or any other object having property length\nstd::shared_ptr<Object> ArraySort(std::shared_ptr<Argument> Args)\n{\n bool use_default_pred = false;\n\n \/\/ object on which we are applying sort\n auto Obj = Args->GetProperty(\"this\");\n auto O = Obj->as<JSObject>();\n\n \/\/ predicate\n auto Pred = Args->GetProperty(\"pred\");\n\n if (IsUndefined(Pred)) {\n use_default_pred = true;\n }\n\n SortInternal(Obj, Pred, use_default_pred);\n return Obj;\n}\n\n\n}\n} \/\/ grok\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/component\/loader\/MeshOffLoader.h>\n#include <sofa\/helper\/system\/SetDirectory.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace loader\n{\n\nusing namespace sofa::defaulttype;\n\nSOFA_DECL_CLASS(MeshOffLoader)\n\nint MeshOffLoaderClass = core::RegisterObject(\"Specific mesh loader for Off file format.\")\n .add< MeshOffLoader >()\n ;\n\nbool MeshOffLoader::load()\n{\n sout << \"Loading OFF file: \" << m_filename << sendl;\n\n bool fileRead = false;\n\n \/\/ -- Loading file\n const char* filename = m_filename.getFullPath().c_str();\n std::string cmd;\n std::ifstream file(filename);\n\n if (!file.good())\n {\n serr << \"Error: MeshOffLoader: Cannot read file '\" << m_filename << \"'.\" << sendl;\n return false;\n }\n\n file >> cmd;\n if (cmd != \"OFF\")\n {\n serr << \"Error: MeshOffLoader: Not a OFF file (header problem) '\" << m_filename << \"'.\" << sendl;\n return false;\n }\n\n \/\/ -- Reading file\n fileRead = this->readOFF (file,filename);\n file.close();\n\n return fileRead;\n}\n\n\n\nbool MeshOffLoader::readOFF (std::ifstream &file, const char* \/* filename *\/ )\n{\n sout << \"MeshOffLoader::readOFF\" << sendl;\n\n helper::vector<sofa::defaulttype::Vector3>& my_positions = *(positions.beginEdit());\n\n helper::vector<helper::fixed_array <unsigned int,3> >& my_triangles = *(triangles.beginEdit());\n helper::vector<helper::fixed_array <unsigned int,4> >& my_quads = *(quads.beginEdit());\n\n unsigned int numberOfVertices, numberOfFaces, numberOfEdges;\n unsigned int currentNumberOfVertices, currentNumberOfFaces;\n Vec3d vertex;\n helper::fixed_array <unsigned int,3> triangle;\n helper::fixed_array <unsigned int,4> quad;\n std::string line;\n\n while( !file.eof() && (numberOfVertices == 0) )\n {\n std::getline(file,line);\n\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n values >> numberOfVertices >> numberOfFaces >> numberOfEdges;\n }\n currentNumberOfVertices = 0;\n\n \/\/Vertices\n while( !file.eof() && currentNumberOfVertices < numberOfVertices)\n {\n std::getline(file,line);\n\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n\n values >> vertex[0] >> vertex[1] >> vertex[2];\n my_positions.push_back(Vector3(vertex[0],vertex[1], vertex[2]));\n\n currentNumberOfVertices++;\n }\n currentNumberOfFaces = 0;\n \/\/Faces\n while( !file.eof() && currentNumberOfFaces < numberOfFaces)\n {\n std::getline(file,line);\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n unsigned int numberOfVerticesPerFace = 0;\n\n values >> numberOfVerticesPerFace;\n if (numberOfVerticesPerFace < 3 || numberOfVerticesPerFace > 4)\n continue;\n\n if (numberOfVerticesPerFace == 3)\n {\n values >> triangle[0] >> triangle[1] >> triangle[2];\n addTriangle(&my_triangles, triangle);\n }\n if (numberOfVerticesPerFace == 4)\n {\n values >> quad[0] >> quad[1] >> quad[2] >> quad[3];\n addQuad(&my_quads, quad);\n }\n currentNumberOfFaces++;\n }\n\n positions.endEdit();\n triangles.endEdit();\n quads.endEdit();\n\n return true;\n}\n} \/\/ namespace loader\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<commit_msg>r5862\/sofa-dev : FIX: MeshOffLoader<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/component\/loader\/MeshOffLoader.h>\n#include <sofa\/helper\/system\/SetDirectory.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace loader\n{\n\nusing namespace sofa::defaulttype;\n\nSOFA_DECL_CLASS(MeshOffLoader)\n\nint MeshOffLoaderClass = core::RegisterObject(\"Specific mesh loader for Off file format.\")\n .add< MeshOffLoader >()\n ;\n\nbool MeshOffLoader::load()\n{\n sout << \"Loading OFF file: \" << m_filename << sendl;\n\n bool fileRead = false;\n\n \/\/ -- Loading file\n const char* filename = m_filename.getFullPath().c_str();\n std::string cmd;\n std::ifstream file(filename);\n\n if (!file.good())\n {\n serr << \"Error: MeshOffLoader: Cannot read file '\" << m_filename << \"'.\" << sendl;\n return false;\n }\n\n file >> cmd;\n if (cmd != \"OFF\")\n {\n serr << \"Error: MeshOffLoader: Not a OFF file (header problem) '\" << m_filename << \"'.\" << sendl;\n return false;\n }\n\n \/\/ -- Reading file\n fileRead = this->readOFF (file,filename);\n file.close();\n\n return fileRead;\n}\n\n\n\nbool MeshOffLoader::readOFF (std::ifstream &file, const char* \/* filename *\/ )\n{\n sout << \"MeshOffLoader::readOFF\" << sendl;\n\n helper::vector<sofa::defaulttype::Vector3>& my_positions = *(positions.beginEdit());\n\n helper::vector<helper::fixed_array <unsigned int,3> >& my_triangles = *(triangles.beginEdit());\n helper::vector<helper::fixed_array <unsigned int,4> >& my_quads = *(quads.beginEdit());\n\n unsigned int numberOfVertices = 0, numberOfFaces = 0, numberOfEdges = 0;\n unsigned int currentNumberOfVertices = 0, currentNumberOfFaces = 0;\n Vec3d vertex;\n helper::fixed_array <unsigned int,3> triangle;\n helper::fixed_array <unsigned int,4> quad;\n std::string line;\n\n while( !file.eof() && (numberOfVertices == 0) )\n {\n std::getline(file,line);\n\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n values >> numberOfVertices >> numberOfFaces >> numberOfEdges;\n }\n sout << \"vertices = \"<< numberOfVertices << sendl;\n sout << \"faces = \"<< numberOfFaces << sendl;\n sout << \"edges = \"<< numberOfEdges << sendl;\n\n currentNumberOfVertices = 0;\n\n \/\/Vertices\n while( !file.eof() && currentNumberOfVertices < numberOfVertices)\n {\n std::getline(file,line);\n\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n\n values >> vertex[0] >> vertex[1] >> vertex[2];\n my_positions.push_back(Vector3(vertex[0],vertex[1], vertex[2]));\n\n currentNumberOfVertices++;\n }\n currentNumberOfFaces = 0;\n \/\/Faces\n while( !file.eof() && currentNumberOfFaces < numberOfFaces)\n {\n std::getline(file,line);\n if (line.empty()) continue;\n if (line[0] == '#') continue;\n\n std::istringstream values(line);\n unsigned int numberOfVerticesPerFace = 0;\n\n values >> numberOfVerticesPerFace;\n if (numberOfVerticesPerFace < 3 || numberOfVerticesPerFace > 4)\n continue;\n\n if (numberOfVerticesPerFace == 3)\n {\n values >> triangle[0] >> triangle[1] >> triangle[2];\n addTriangle(&my_triangles, triangle);\n }\n if (numberOfVerticesPerFace == 4)\n {\n values >> quad[0] >> quad[1] >> quad[2] >> quad[3];\n addQuad(&my_quads, quad);\n }\n currentNumberOfFaces++;\n }\n\n positions.endEdit();\n triangles.endEdit();\n quads.endEdit();\n\n return true;\n}\n} \/\/ namespace loader\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file CommonIO.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"CommonIO.h\"\n\n#include <fstream>\n#include \"Exceptions.h\"\nusing namespace std;\nusing namespace dev;\n\nstring dev::memDump(bytes const& _bytes, unsigned _width, bool _html)\n{\n\tstringstream ret;\n\tif (_html)\n\t\tret << \"<pre style=\\\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\\\">\";\n\tfor (unsigned i = 0; i < _bytes.size(); i += _width)\n\t{\n\t\tret << hex << setw(4) << setfill('0') << i << \" \";\n\t\tfor (unsigned j = i; j < i + _width; ++j)\n\t\t\tif (j < _bytes.size())\n\t\t\t\tif (_bytes[j] >= 32 && _bytes[j] < 127)\n\t\t\t\t\tif ((char)_bytes[j] == '<' && _html)\n\t\t\t\t\t\tret << \"<\";\n\t\t\t\t\telse if ((char)_bytes[j] == '&' && _html)\n\t\t\t\t\t\tret << \"&\";\n\t\t\t\t\telse\n\t\t\t\t\t\tret << (char)_bytes[j];\n\t\t\t\telse\n\t\t\t\t\tret << '?';\n\t\t\telse\n\t\t\t\tret << ' ';\n\t\tret << \" \";\n\t\tfor (unsigned j = i; j < i + _width && j < _bytes.size(); ++j)\n\t\t\tret << setfill('0') << setw(2) << hex << (unsigned)_bytes[j] << \" \";\n\t\tret << \"\\n\";\n\t}\n\tif (_html)\n\t\tret << \"<\/pre>\";\n\treturn ret.str();\n}\n\n\/\/ Don't forget to delete[] later.\nbytesRef dev::contentsNew(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn bytesRef();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn bytesRef();\n\tis.seekg (0, is.beg);\n\tbytesRef ret(new byte[length], length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nbytes dev::contents(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn bytes();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn bytes();\n\tis.seekg (0, is.beg);\n\tbytes ret(length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nstring dev::contentsString(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn string();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn string();\n\tis.seekg (0, is.beg);\n\tstring ret;\n\tret.resize(length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nvoid dev::writeFile(std::string const& _file, bytesConstRef _data)\n{\n\tofstream(_file, ios::trunc).write((char const*)_data.data(), _data.size());\n}\n\n<commit_msg>Win32\/MSVC requires ios::binary flag on ofstream to correctly write dag file<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file CommonIO.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"CommonIO.h\"\n\n#include <fstream>\n#include \"Exceptions.h\"\nusing namespace std;\nusing namespace dev;\n\nstring dev::memDump(bytes const& _bytes, unsigned _width, bool _html)\n{\n\tstringstream ret;\n\tif (_html)\n\t\tret << \"<pre style=\\\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\\\">\";\n\tfor (unsigned i = 0; i < _bytes.size(); i += _width)\n\t{\n\t\tret << hex << setw(4) << setfill('0') << i << \" \";\n\t\tfor (unsigned j = i; j < i + _width; ++j)\n\t\t\tif (j < _bytes.size())\n\t\t\t\tif (_bytes[j] >= 32 && _bytes[j] < 127)\n\t\t\t\t\tif ((char)_bytes[j] == '<' && _html)\n\t\t\t\t\t\tret << \"<\";\n\t\t\t\t\telse if ((char)_bytes[j] == '&' && _html)\n\t\t\t\t\t\tret << \"&\";\n\t\t\t\t\telse\n\t\t\t\t\t\tret << (char)_bytes[j];\n\t\t\t\telse\n\t\t\t\t\tret << '?';\n\t\t\telse\n\t\t\t\tret << ' ';\n\t\tret << \" \";\n\t\tfor (unsigned j = i; j < i + _width && j < _bytes.size(); ++j)\n\t\t\tret << setfill('0') << setw(2) << hex << (unsigned)_bytes[j] << \" \";\n\t\tret << \"\\n\";\n\t}\n\tif (_html)\n\t\tret << \"<\/pre>\";\n\treturn ret.str();\n}\n\n\/\/ Don't forget to delete[] later.\nbytesRef dev::contentsNew(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn bytesRef();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn bytesRef();\n\tis.seekg (0, is.beg);\n\tbytesRef ret(new byte[length], length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nbytes dev::contents(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn bytes();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn bytes();\n\tis.seekg (0, is.beg);\n\tbytes ret(length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nstring dev::contentsString(std::string const& _file)\n{\n\tstd::ifstream is(_file, std::ifstream::binary);\n\tif (!is)\n\t\treturn string();\n\t\/\/ get length of file:\n\tis.seekg (0, is.end);\n\tstreamoff length = is.tellg();\n\tif (length == 0) \/\/ return early, MSVC does not like reading 0 bytes\n\t\treturn string();\n\tis.seekg (0, is.beg);\n\tstring ret;\n\tret.resize(length);\n\tis.read((char*)ret.data(), length);\n\tis.close();\n\treturn ret;\n}\n\nvoid dev::writeFile(std::string const& _file, bytesConstRef _data)\n{\n\tofstream(_file, ios::trunc|ios::binary).write((char const*)_data.data(), _data.size());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 The MUSCET Development Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\n#include <votca\/xtp\/gyration.h>\n#include <boost\/format.hpp>\n#include <votca\/tools\/elements.h>\n\n\nusing namespace votca::tools;\n\nnamespace votca { namespace xtp {\n\nvoid Density2Gyration::Initialize( tools::Property& options) {\n string key = Identify();\n\n std::string statestring=options.ifExistsReturnElseThrowRuntimeError<string>(key + \".state\");\n _state.FromString(statestring);\n _dostateonly = options.ifExistsReturnElseReturnDefault<bool>(key + \".difference_to_groundstate\",false);\n _gridsize = options.ifExistsReturnElseReturnDefault<string>(key+\".gridsize\",\"medium\");\n _openmp_threads = options.ifExistsReturnElseReturnDefault<int>(key + \".openmp\",1);\n \n \/\/ get the path to the shared folders with xml files\n char *votca_share = getenv(\"VOTCASHARE\"); \n if(votca_share == NULL) throw std::runtime_error(\"VOTCASHARE not set, cannot open help files.\"); \n }\n\n\n void Density2Gyration::AnalyzeDensity(const Orbitals & orbitals) {\n int threads = 1;\n#ifdef _OPENMP\n if (_openmp_threads > 0) omp_set_num_threads(_openmp_threads);\n threads = omp_get_max_threads();\n#endif\n XTP_LOG(logDEBUG, *_log) << \"===== Running on \" << threads << \" threads ===== \" << flush;\n\n const QMMolecule& Atomlist = orbitals.QMAtoms();\n Eigen::MatrixXd DMAT_tot;\n BasisSet bs;\n bs.LoadBasisSet(orbitals.getDFTbasis());\n AOBasis basis;\n basis.AOBasisFill(bs, Atomlist);\n AnalyzeGeometry(Atomlist);\n std::vector<Eigen::MatrixXd > DMAT;\n\n \/\/ setup numerical integration grid\n NumericalIntegration numway;\n numway.GridSetup(_gridsize, Atomlist, basis);\n\n if (!_dostateonly) {\n Eigen::MatrixXd DMATGS = orbitals.DensityMatrixFull(_state);\n Gyrationtensor gyro = numway.IntegrateGyrationTensor(DMAT_tot);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n es.computeDirect(gyro.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(_state.ToLongString(), gyro,es);\n\n } else{\n \/\/ hole density first\n std::vector<Eigen::MatrixXd > DMAT=orbitals.DensityMatrixExcitedState(_state);\n Gyrationtensor gyro_hole = numway.IntegrateGyrationTensor(DMAT[0]);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_h;\n es_h.computeDirect(gyro_hole.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(\"hole\", gyro_hole,es_h);\n \n \/\/ electron density\n Gyrationtensor gyro_electron = numway.IntegrateGyrationTensor(DMAT[1]);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_e;\n es_e.computeDirect(gyro_electron.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(\"electron\", gyro_electron,es_e);\n }\n return;\n }\n\n\n void Density2Gyration::AnalyzeGeometry(const QMMolecule& atoms){\n \n tools::Elements elements; \n double mass=0.0;\n Eigen::Vector3d centroid = Eigen::Vector3d::Zero();\n Eigen::Matrix3d gyration = Eigen::Matrix3d::Zero();\n for (const QMAtom& atom:atoms){\n double m = elements.getMass(atom.getElement());\n const Eigen::Vector3d & pos =atom.getPos();\n mass+= m;\n centroid+=m*pos;\n gyration+=m*pos*pos.transpose();\n }\n centroid\/=mass;\n gyration\/=mass;\n gyration-=centroid*centroid.transpose();\n Gyrationtensor gyro;\n gyro.mass=mass;\n gyro.centroid=centroid;\n gyro.gyration=gyration;\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n es.computeDirect(gyro.gyration);\n ReportAnalysis( \"geometry\", gyro,es );\n }\n\n void Density2Gyration::ReportAnalysis(string label,const Gyrationtensor& gyro, const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>& es){\n \n XTP_LOG(logINFO, *_log) << \"---------------- \" << label << \" ----------------\" << flush;\n XTP_LOG(logINFO, *_log) << (boost::format(\" Norm = %1$9.4f \") % (gyro.mass) ) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid x = %1$9.4f Ang\") % (gyro.centroid.x()*tools::conv::bohr2ang) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid y = %1$9.4f Ang\") % (gyro.centroid.y()*tools::conv::bohr2ang) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid y = %1$9.4f Ang\") % (gyro.centroid.z()*tools::conv::bohr2ang) ) << flush;\n \n double RA2 = tools::conv::bohr2ang *tools::conv::bohr2ang;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xx = %1$9.4f Ang^2\") % (gyro.gyration(0,0)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xy = %1$9.4f Ang^2\") % (gyro.gyration(0,1)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xz = %1$9.4f Ang^2\") % (gyro.gyration(0,2)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor yy = %1$9.4f Ang^2\") % (gyro.gyration(1,1)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor yz = %1$9.4f Ang^2\") % (gyro.gyration(1,2)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor zz = %1$9.4f Ang^2\") % (gyro.gyration(2,2)*RA2) ) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D1 = %1$9.4f Ang^2\") % (es.eigenvalues()[0]*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D2 = %1$9.4f Ang^2\") % (es.eigenvalues()[1]*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D3 = %1$9.4f Ang^2\") % (es.eigenvalues()[2]*RA2) ) << flush;\n\n XTP_LOG(logINFO,*_log) << (boost::format(\" Radius of Gyration = %1$9.4f Ang\") % (std::sqrt(es.eigenvalues().sum())*tools::conv::bohr2ang )) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 1 = %1$9.4f \") % es.eigenvectors().col(0).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 2 = %1$9.4f \") % es.eigenvectors().col(0).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 3 = %1$9.4f \") % es.eigenvectors().col(0).z() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 1 = %1$9.4f \") % es.eigenvectors().col(1).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 2 = %1$9.4f \") % es.eigenvectors().col(1).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 3 = %1$9.4f \") % es.eigenvectors().col(1).z() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 1 = %1$9.4f \") % es.eigenvectors().col(2).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 2 = %1$9.4f \") % es.eigenvectors().col(2).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 3 = %1$9.4f \") % es.eigenvectors().col(2).z() ) << flush;\n return;\n }\n\n \n \n\n}}\n\n\n<commit_msg>Added using namespace std to gyration.cc<commit_after>\/*\n * Copyright 2016 The MUSCET Development Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\n#include <votca\/xtp\/gyration.h>\n#include <boost\/format.hpp>\n#include <votca\/tools\/elements.h>\n\nusing namespace std;\nusing namespace votca::tools;\n\nnamespace votca { namespace xtp {\n\nvoid Density2Gyration::Initialize( tools::Property& options) {\n string key = Identify();\n\n std::string statestring=options.ifExistsReturnElseThrowRuntimeError<string>(key + \".state\");\n _state.FromString(statestring);\n _dostateonly = options.ifExistsReturnElseReturnDefault<bool>(key + \".difference_to_groundstate\",false);\n _gridsize = options.ifExistsReturnElseReturnDefault<string>(key+\".gridsize\",\"medium\");\n _openmp_threads = options.ifExistsReturnElseReturnDefault<int>(key + \".openmp\",1);\n \n \/\/ get the path to the shared folders with xml files\n char *votca_share = getenv(\"VOTCASHARE\"); \n if(votca_share == NULL) throw std::runtime_error(\"VOTCASHARE not set, cannot open help files.\"); \n }\n\n\n void Density2Gyration::AnalyzeDensity(const Orbitals & orbitals) {\n int threads = 1;\n#ifdef _OPENMP\n if (_openmp_threads > 0) omp_set_num_threads(_openmp_threads);\n threads = omp_get_max_threads();\n#endif\n XTP_LOG(logDEBUG, *_log) << \"===== Running on \" << threads << \" threads ===== \" << flush;\n\n const QMMolecule& Atomlist = orbitals.QMAtoms();\n Eigen::MatrixXd DMAT_tot;\n BasisSet bs;\n bs.LoadBasisSet(orbitals.getDFTbasis());\n AOBasis basis;\n basis.AOBasisFill(bs, Atomlist);\n AnalyzeGeometry(Atomlist);\n std::vector<Eigen::MatrixXd > DMAT;\n\n \/\/ setup numerical integration grid\n NumericalIntegration numway;\n numway.GridSetup(_gridsize, Atomlist, basis);\n\n if (!_dostateonly) {\n Eigen::MatrixXd DMATGS = orbitals.DensityMatrixFull(_state);\n Gyrationtensor gyro = numway.IntegrateGyrationTensor(DMAT_tot);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n es.computeDirect(gyro.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(_state.ToLongString(), gyro,es);\n\n } else{\n \/\/ hole density first\n std::vector<Eigen::MatrixXd > DMAT=orbitals.DensityMatrixExcitedState(_state);\n Gyrationtensor gyro_hole = numway.IntegrateGyrationTensor(DMAT[0]);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_h;\n es_h.computeDirect(gyro_hole.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(\"hole\", gyro_hole,es_h);\n \n \/\/ electron density\n Gyrationtensor gyro_electron = numway.IntegrateGyrationTensor(DMAT[1]);\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_e;\n es_e.computeDirect(gyro_electron.gyration);\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Converting to Eigenframe \" << flush;\n XTP_LOG(logDEBUG, *_log) << TimeStamp() << \" Reporting \" << flush;\n ReportAnalysis(\"electron\", gyro_electron,es_e);\n }\n return;\n }\n\n\n void Density2Gyration::AnalyzeGeometry(const QMMolecule& atoms){\n \n tools::Elements elements; \n double mass=0.0;\n Eigen::Vector3d centroid = Eigen::Vector3d::Zero();\n Eigen::Matrix3d gyration = Eigen::Matrix3d::Zero();\n for (const QMAtom& atom:atoms){\n double m = elements.getMass(atom.getElement());\n const Eigen::Vector3d & pos =atom.getPos();\n mass+= m;\n centroid+=m*pos;\n gyration+=m*pos*pos.transpose();\n }\n centroid\/=mass;\n gyration\/=mass;\n gyration-=centroid*centroid.transpose();\n Gyrationtensor gyro;\n gyro.mass=mass;\n gyro.centroid=centroid;\n gyro.gyration=gyration;\n Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n es.computeDirect(gyro.gyration);\n ReportAnalysis( \"geometry\", gyro,es );\n }\n\n void Density2Gyration::ReportAnalysis(string label,const Gyrationtensor& gyro, const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>& es){\n \n XTP_LOG(logINFO, *_log) << \"---------------- \" << label << \" ----------------\" << flush;\n XTP_LOG(logINFO, *_log) << (boost::format(\" Norm = %1$9.4f \") % (gyro.mass) ) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid x = %1$9.4f Ang\") % (gyro.centroid.x()*tools::conv::bohr2ang) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid y = %1$9.4f Ang\") % (gyro.centroid.y()*tools::conv::bohr2ang) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Centroid y = %1$9.4f Ang\") % (gyro.centroid.z()*tools::conv::bohr2ang) ) << flush;\n \n double RA2 = tools::conv::bohr2ang *tools::conv::bohr2ang;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xx = %1$9.4f Ang^2\") % (gyro.gyration(0,0)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xy = %1$9.4f Ang^2\") % (gyro.gyration(0,1)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor xz = %1$9.4f Ang^2\") % (gyro.gyration(0,2)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor yy = %1$9.4f Ang^2\") % (gyro.gyration(1,1)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor yz = %1$9.4f Ang^2\") % (gyro.gyration(1,2)*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor zz = %1$9.4f Ang^2\") % (gyro.gyration(2,2)*RA2) ) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D1 = %1$9.4f Ang^2\") % (es.eigenvalues()[0]*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D2 = %1$9.4f Ang^2\") % (es.eigenvalues()[1]*RA2) ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Gyration Tensor D3 = %1$9.4f Ang^2\") % (es.eigenvalues()[2]*RA2) ) << flush;\n\n XTP_LOG(logINFO,*_log) << (boost::format(\" Radius of Gyration = %1$9.4f Ang\") % (std::sqrt(es.eigenvalues().sum())*tools::conv::bohr2ang )) << flush;\n \n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 1 = %1$9.4f \") % es.eigenvectors().col(0).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 2 = %1$9.4f \") % es.eigenvectors().col(0).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 1 3 = %1$9.4f \") % es.eigenvectors().col(0).z() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 1 = %1$9.4f \") % es.eigenvectors().col(1).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 2 = %1$9.4f \") % es.eigenvectors().col(1).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 2 3 = %1$9.4f \") % es.eigenvectors().col(1).z() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 1 = %1$9.4f \") % es.eigenvectors().col(2).x() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 2 = %1$9.4f \") % es.eigenvectors().col(2).y() ) << flush;\n XTP_LOG(logINFO,*_log) << (boost::format(\" Tensor EF Axis 3 3 = %1$9.4f \") % es.eigenvectors().col(2).z() ) << flush;\n return;\n }\n\n \n \n\n}}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include <gst\/gst.h>\n\n#include \"logging.hpp\"\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == NULL) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (\n object) ) : \"''\") % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR:\n return error;\n\n case GST_LEVEL_WARNING:\n return warning;\n\n case GST_LEVEL_FIXME:\n return fixme;\n\n case GST_LEVEL_INFO:\n return info;\n\n case GST_LEVEL_DEBUG:\n return debug;\n\n case GST_LEVEL_LOG:\n return log;\n\n case GST_LEVEL_TRACE:\n return trace;\n\n default:\n return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path,\n int fileSize,\n int fileNumber)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,\n keywords::min_free_space = fileSize * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \" error\",\n \"warning\",\n \" fixme\",\n \" info\",\n \" debug\",\n \" log\",\n \" trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%d %H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << logging::extract< attrs::current_process_id::value_type > (\"ProcessID\",\n rec) << \" \";\n strm << \"[\" <<\n logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \"] \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging (const std::string &path, int fileSize, int fileNumber)\n{\n gst_debug_remove_log_function_by_data (NULL);\n gst_debug_add_log_function (kms_log_function, NULL, NULL);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"media-server_%Y-%m-%d_%H-%M-%S.%5N.pid\" +\n std::to_string (getpid() ) + \".log\",\n keywords::rotation_size = fileSize * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path + \"\/logs\", fileSize, fileNumber);\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n} \/* kurento *\/\n<commit_msg>logging: Do not print gstreamer logs when boost file log is active<commit_after>\/*\n * (C) Copyright 2014 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include <gst\/gst.h>\n\n#include \"logging.hpp\"\n\n#include <boost\/format.hpp>\n#include <boost\/log\/sinks\/text_file_backend.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/sources\/channel_feature.hpp>\n#include <boost\/log\/sources\/channel_logger.hpp>\n#include <boost\/log\/support\/date_time.hpp>\n#include <boost\/log\/utility\/manipulators\/add_value.hpp>\n\nnamespace logging = boost::log;\nnamespace attrs = boost::log::attributes;\nnamespace src = boost::log::sources;\nnamespace sinks = boost::log::sinks;\nnamespace expr = boost::log::expressions;\nnamespace keywords = boost::log::keywords;\n\ntypedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;\n\nnamespace kurento\n{\n\n\/* kurento logging sinks *\/\nboost::shared_ptr< sink_t > system_sink;\n\nstatic std::string\ndebug_object (GObject *object)\n{\n if (object == NULL) {\n return \"\";\n }\n\n if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s:%s> \");\n fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (\n object) ) : \"''\") % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {\n boost::format fmt (\"<%s> \");\n fmt % GST_OBJECT_NAME (object);\n return fmt.str();\n }\n\n if (G_IS_OBJECT (object) ) {\n boost::format fmt (\"<%s@%p> \");\n fmt % G_OBJECT_TYPE_NAME (object) % object;\n return fmt.str();\n }\n\n boost::format fmt (\"<%p> \");\n fmt % object;\n return fmt.str();\n}\n\nstatic std::string\nexpand_string (std::string str, int len)\n{\n std::string ret = str;\n int sp = len - str.size ();\n\n for (int i = sp; i > 0; i--) {\n str.append (\" \");\n }\n\n return str;\n}\n\nstatic severity_level\ngst_debug_level_to_severity_level (GstDebugLevel level)\n{\n switch (level) {\n case GST_LEVEL_ERROR:\n return error;\n\n case GST_LEVEL_WARNING:\n return warning;\n\n case GST_LEVEL_FIXME:\n return fixme;\n\n case GST_LEVEL_INFO:\n return info;\n\n case GST_LEVEL_DEBUG:\n return debug;\n\n case GST_LEVEL_LOG:\n return log;\n\n case GST_LEVEL_TRACE:\n return trace;\n\n default:\n return undefined;\n }\n}\n\nstatic void\nkms_log_function (GstDebugCategory *category, GstDebugLevel level,\n const gchar *file,\n const gchar *function, gint line, GObject *object,\n GstDebugMessage *message, gpointer user_data)\n{\n if (level > gst_debug_category_get_threshold (category) ) {\n return;\n }\n\n severity_level severity = gst_debug_level_to_severity_level (level);\n\n if (severity == undefined) {\n return;\n }\n\n BOOST_LOG_SEV (system_logger::get(), severity) <<\n logging::add_value (\"Category\", expand_string (category->name, 25) ) <<\n logging::add_value (\"FileName\",\n boost::filesystem::path (file).filename().string() ) <<\n logging::add_value (\"Line\", line) <<\n logging::add_value (\"Function\", function) <<\n logging::add_value (\"GObject\", debug_object (object) ) <<\n gst_debug_message_get (message);\n}\n\nvoid init_file_collecting (boost::shared_ptr< sink_t > sink,\n const std::string &path,\n int fileSize,\n int fileNumber)\n{\n sink->locked_backend()->set_file_collector (sinks::file::make_collector (\n keywords::target = path,\n keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,\n keywords::min_free_space = fileSize * 1024 * 1024\n ) );\n}\n\n\/* The formatting logic for the severity level *\/\ntemplate< typename CharT, typename TraitsT >\ninline std::basic_ostream< CharT, TraitsT > &operator<< (\n std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)\n{\n static const char *const str[] = {\n \" error\",\n \"warning\",\n \" fixme\",\n \" info\",\n \" debug\",\n \" log\",\n \" trace\",\n \"unknown\"\n };\n\n if (static_cast< std::size_t > (lvl) < (sizeof (str) \/ sizeof (*str) ) ) {\n strm << str[lvl];\n } else {\n strm << static_cast< int > (lvl);\n }\n\n return strm;\n}\n\nstatic void\nsystem_formatter (logging::record_view const &rec,\n logging::formatting_ostream &strm)\n{\n auto date_time_formatter = expr::stream\n << expr::format_date_time< boost::posix_time::ptime > (\"TimeStamp\",\n \"%Y-%m-%d %H:%M:%S,%f\");\n date_time_formatter (rec, strm) << \" \";\n strm << logging::extract< attrs::current_process_id::value_type > (\"ProcessID\",\n rec) << \" \";\n strm << \"[\" <<\n logging::extract< attrs::current_thread_id::value_type > (\"ThreadID\",\n rec) << \"] \";\n strm << logging::extract< severity_level > (\"Severity\", rec) << \" \";\n strm << logging::extract< std::string > (\"Category\", rec) << \" \";\n strm << logging::extract< std::string > (\"FileName\", rec) << \":\";\n strm << logging::extract< int > (\"Line\", rec) << \" \";\n strm << logging::extract< std::string > (\"Function\", rec) << \"() \";\n strm << logging::extract< std::string > (\"GObject\", rec) << \" \";\n strm << rec[expr::smessage];\n}\n\nbool\nkms_init_logging (const std::string &path, int fileSize, int fileNumber)\n{\n gst_debug_remove_log_function (gst_debug_log_default);\n gst_debug_add_log_function (kms_log_function, NULL, NULL);\n\n boost::shared_ptr< logging::core > core = logging::core::get();\n\n boost::shared_ptr< sinks::text_file_backend > backend =\n boost::make_shared< sinks::text_file_backend > (\n keywords::file_name = path + \"\/\" + \"media-server_%Y-%m-%d_%H-%M-%S.%5N.pid\" +\n std::to_string (getpid() ) + \".log\",\n keywords::rotation_size = fileSize * 1024 * 1024,\n keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)\n );\n\n \/* Enable auto-flushing after each log record written *\/\n backend->auto_flush (true);\n\n \/* Wrap it into the frontend and register in the core. *\/\n \/* The backend requires synchronization in the frontend. *\/\n system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );\n\n \/*Set up filter to pass only records that have the necessary attributes *\/\n system_sink->set_filter (\n expr::has_attr< std::string > (\"Channel\") &&\n expr::attr< std::string > (\"Channel\") == \"system\"\n );\n\n \/* Set up where the rotated files will be stored *\/\n init_file_collecting (system_sink, path + \"\/logs\", fileSize, fileNumber);\n\n \/* Upon restart, scan the directory for files matching the file_name pattern *\/\n system_sink->locked_backend()->scan_for_files();\n\n core->add_sink (system_sink);\n\n system_sink->set_formatter (&system_formatter);\n\n return true;\n}\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of libkdepim.\n\n Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n Copyright (c) 2002 David Jarvie <software@astrojar.org.uk>\n Copyright (c) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\/\/krazy:excludeall=qclasses as we want to subclass from QComboBox, not KComboBox\n\n#include \"kdateedit.h\"\n\n#include <KCalendarSystem>\n#include <KDebug>\n#include <KGlobal>\n#include <KGlobalSettings>\n#include <KLocale>\n\n#include <QAbstractItemView>\n#include <QApplication>\n#include <QEvent>\n#include <QKeyEvent>\n#include <QLineEdit>\n#include <QMouseEvent>\n#include <QValidator>\n\nusing namespace KPIM;\n\nclass DateValidator : public QValidator\n{\n public:\n DateValidator( const QStringList &keywords, QWidget *parent )\n : QValidator( parent ), mKeywords( keywords )\n {}\n\n virtual State validate( QString &str, int & ) const\n {\n int length = str.length();\n\n \/\/ empty string is intermediate so one can clear the edit line and start from scratch\n if ( length <= 0 ) {\n return Intermediate;\n }\n\n if ( mKeywords.contains( str.toLower() ) ) {\n return Acceptable;\n }\n\n bool ok = false;\n KGlobal::locale()->readDate( str, &ok );\n if ( ok ) {\n return Acceptable;\n } else {\n return Intermediate;\n }\n }\n\n private:\n QStringList mKeywords;\n};\n\nKDateEdit::KDateEdit( QWidget *parent, const char *name )\n : QComboBox( parent ), mReadOnly( false ), mDiscardNextMousePress( false )\n{\n setObjectName( name );\n \/\/ need at least one entry for popup to work\n setMaxCount( 1 );\n setEditable( true );\n\n mDate = QDate::currentDate();\n QString today = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );\n\n addItem( today );\n setCurrentIndex( 0 );\n setSizeAdjustPolicy( AdjustToContents );\n\n connect( lineEdit(), SIGNAL( returnPressed() ),\n this, SLOT( lineEnterPressed() ) );\n connect( this, SIGNAL( textChanged( const QString& ) ),\n SLOT( slotTextChanged( const QString& ) ) );\n\n mPopup = new KDatePickerPopup( KDatePickerPopup::DatePicker | KDatePickerPopup::Words,\n QDate::currentDate(), this );\n mPopup->hide();\n mPopup->installEventFilter( this );\n\n connect( mPopup, SIGNAL( dateChanged( const QDate& ) ),\n SLOT( dateSelected( const QDate& ) ) );\n\n \/\/ handle keyword entry\n setupKeywords();\n lineEdit()->installEventFilter( this );\n\n setValidator( new DateValidator( mKeywordMap.keys(), this ) );\n\n mTextChanged = false;\n}\n\nKDateEdit::~KDateEdit()\n{\n}\n\nvoid KDateEdit::setDate( const QDate &date )\n{\n assignDate( date );\n updateView();\n}\n\nQDate KDateEdit::date() const\n{\n return mDate;\n}\n\nvoid KDateEdit::setReadOnly( bool readOnly )\n{\n mReadOnly = readOnly;\n lineEdit()->setReadOnly( readOnly );\n}\n\nbool KDateEdit::isReadOnly() const\n{\n return mReadOnly;\n}\n\nvoid KDateEdit::showPopup()\n{\n if ( mReadOnly ) {\n return;\n }\n\n QRect desk = KGlobalSettings::desktopGeometry( this );\n\n QPoint popupPoint = mapToGlobal( QPoint( 0, 0 ) );\n\n int dateFrameHeight = mPopup->sizeHint().height();\n if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {\n popupPoint.setY( popupPoint.y() - dateFrameHeight );\n } else {\n popupPoint.setY( popupPoint.y() + height() );\n }\n\n int dateFrameWidth = mPopup->sizeHint().width();\n if ( popupPoint.x() + dateFrameWidth > desk.right() ) {\n popupPoint.setX( desk.right() - dateFrameWidth );\n }\n\n if ( popupPoint.x() < desk.left() ) {\n popupPoint.setX( desk.left() );\n }\n\n if ( popupPoint.y() < desk.top() ) {\n popupPoint.setY( desk.top() );\n }\n\n if ( mDate.isValid() ) {\n mPopup->setDate( mDate );\n } else {\n mPopup->setDate( QDate::currentDate() );\n }\n\n mPopup->popup( popupPoint );\n\n \/\/ The combo box is now shown pressed. Make it show not pressed again\n \/\/ by causing its (invisible) list box to emit a 'selected' signal.\n \/\/ First, ensure that the list box contains the date currently displayed.\n QDate date = parseDate();\n assignDate( date );\n updateView();\n\n \/\/ Now, simulate an Enter to unpress it\n QAbstractItemView *lb = view();\n if ( lb ) {\n lb->setCurrentIndex( lb->model()->index( 0, 0 ) );\n QKeyEvent *keyEvent =\n new QKeyEvent( QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier );\n QApplication::postEvent( lb, keyEvent );\n }\n}\n\nvoid KDateEdit::dateSelected( const QDate &date )\n{\n if ( assignDate( date ) ) {\n updateView();\n emit dateChanged( date );\n emit dateEntered( date );\n\n if ( date.isValid() ) {\n mPopup->hide();\n }\n }\n}\n\nvoid KDateEdit::lineEnterPressed()\n{\n bool replaced = false;\n\n QDate date = parseDate( &replaced );\n\n if ( assignDate( date ) ) {\n if ( replaced ) {\n updateView();\n }\n\n emit dateChanged( date );\n emit dateEntered( date );\n }\n}\n\nQDate KDateEdit::parseDate( bool *replaced ) const\n{\n QString text = currentText();\n QDate result;\n\n if ( replaced ) {\n (*replaced) = false;\n }\n\n if ( text.isEmpty() ) {\n result = QDate();\n } else if ( mKeywordMap.contains( text.toLower() ) ) {\n QDate today = QDate::currentDate();\n int i = mKeywordMap[ text.toLower() ];\n if ( i >= 100 ) {\n \/* A day name has been entered. Convert to offset from today.\n * This uses some math tricks to figure out the offset in days\n * to the next date the given day of the week occurs. There\n * are two cases, that the new day is >= the current day, which means\n * the new day has not occurred yet or that the new day < the current day,\n * which means the new day is already passed (so we need to find the\n * day in the next week).\n *\/\n i -= 100;\n int currentDay = today.dayOfWeek();\n if ( i >= currentDay ) {\n i -= currentDay;\n } else {\n i += 7 - currentDay;\n }\n }\n\n result = today.addDays( i );\n if ( replaced ) {\n (*replaced) = true;\n }\n } else {\n result = KGlobal::locale()->readDate( text );\n }\n\n return result;\n}\n\nvoid KDateEdit::focusOutEvent( QFocusEvent *e )\n{\n if ( mTextChanged ) {\n lineEnterPressed();\n mTextChanged = false;\n }\n QComboBox::focusOutEvent( e );\n}\n\nvoid KDateEdit::keyPressEvent(QKeyEvent* e)\n{\n int step = 0;\n if ( e->key() == Qt::Key_Up ) {\n step = 1;\n } else if ( e->key() == Qt::Key_Down ) {\n step = -1;\n }\n if ( step && !mReadOnly ) {\n QDate date = parseDate();\n if ( date.isValid() ) {\n date = date.addDays( step );\n if ( assignDate( date ) ) {\n updateView();\n emit dateChanged( date );\n emit dateEntered( date );\n }\n }\n }\n}\n\nbool KDateEdit::eventFilter( QObject *object, QEvent *event )\n{\n if ( object == lineEdit() ) {\n \/\/ We only process the focus out event if the text has changed\n \/\/ since we got focus\n if ( ( event->type() == QEvent::FocusOut ) && mTextChanged ) {\n lineEnterPressed();\n mTextChanged = false;\n } else if ( event->type() == QEvent::KeyPress ) {\n \/\/ Up and down arrow keys step the date\n QKeyEvent *keyEvent = (QKeyEvent *)event;\n\n if ( keyEvent->key() == Qt::Key_Return ) {\n lineEnterPressed();\n return true;\n }\n }\n } else {\n \/\/ It's a date picker event\n switch ( event->type() ) {\n case QEvent::MouseButtonDblClick:\n case QEvent::MouseButtonPress:\n {\n QMouseEvent *mouseEvent = (QMouseEvent*)event;\n if ( !mPopup->rect().contains( mouseEvent->pos() ) ) {\n QPoint globalPos = mPopup->mapToGlobal( mouseEvent->pos() );\n if ( QApplication::widgetAt( globalPos ) == this ) {\n \/\/ The date picker is being closed by a click on the\n \/\/ KDateEdit widget. Avoid popping it up again immediately.\n mDiscardNextMousePress = true;\n }\n }\n\n break;\n }\n default:\n break;\n }\n }\n\n return false;\n}\n\nvoid KDateEdit::mousePressEvent( QMouseEvent *event )\n{\n if ( event->button() == Qt::LeftButton && mDiscardNextMousePress ) {\n mDiscardNextMousePress = false;\n return;\n }\n\n QComboBox::mousePressEvent( event );\n}\n\nvoid KDateEdit::slotTextChanged( const QString & )\n{\n QDate date = parseDate();\n\n if ( assignDate( date ) ) {\n emit dateChanged( date );\n }\n\n mTextChanged = true;\n}\n\nvoid KDateEdit::setupKeywords()\n{\n \/\/ Create the keyword list. This will be used to match against when the user\n \/\/ enters information.\n mKeywordMap.insert( i18nc( \"the day after today\", \"tomorrow\" ), 1 );\n mKeywordMap.insert( i18nc( \"this day\", \"today\" ), 0 );\n mKeywordMap.insert( i18nc( \"the day before today\", \"yesterday\" ), -1 );\n\n QString dayName;\n for ( int i = 1; i <= 7; ++i ) {\n dayName = KGlobal::locale()->calendar()->weekDayName( i ).toLower();\n mKeywordMap.insert( dayName, i + 100 );\n }\n}\n\nbool KDateEdit::assignDate( const QDate &date )\n{\n mDate = date;\n mTextChanged = false;\n return true;\n}\n\nvoid KDateEdit::updateView()\n{\n QString dateString;\n if ( mDate.isValid() ) {\n dateString = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );\n }\n\n \/\/ We do not want to generate a signal here,\n \/\/ since we explicitly setting the date\n bool blocked = signalsBlocked();\n blockSignals( true );\n removeItem( 0 );\n insertItem( 0, dateString );\n blockSignals( blocked );\n}\n\n#include \"kdateedit.moc\"\n<commit_msg>Let's allow people to type in the KDateEdit. Okay? :-)<commit_after>\/*\n This file is part of libkdepim.\n\n Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n Copyright (c) 2002 David Jarvie <software@astrojar.org.uk>\n Copyright (c) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\/\/krazy:excludeall=qclasses as we want to subclass from QComboBox, not KComboBox\n\n#include \"kdateedit.h\"\n\n#include <KCalendarSystem>\n#include <KDebug>\n#include <KGlobal>\n#include <KGlobalSettings>\n#include <KLocale>\n\n#include <QAbstractItemView>\n#include <QApplication>\n#include <QEvent>\n#include <QKeyEvent>\n#include <QLineEdit>\n#include <QMouseEvent>\n#include <QValidator>\n\nusing namespace KPIM;\n\nclass DateValidator : public QValidator\n{\n public:\n DateValidator( const QStringList &keywords, QWidget *parent )\n : QValidator( parent ), mKeywords( keywords )\n {}\n\n virtual State validate( QString &str, int & ) const\n {\n int length = str.length();\n\n \/\/ empty string is intermediate so one can clear the edit line and start from scratch\n if ( length <= 0 ) {\n return Intermediate;\n }\n\n if ( mKeywords.contains( str.toLower() ) ) {\n return Acceptable;\n }\n\n bool ok = false;\n KGlobal::locale()->readDate( str, &ok );\n if ( ok ) {\n return Acceptable;\n } else {\n return Intermediate;\n }\n }\n\n private:\n QStringList mKeywords;\n};\n\nKDateEdit::KDateEdit( QWidget *parent, const char *name )\n : QComboBox( parent ), mReadOnly( false ), mDiscardNextMousePress( false )\n{\n setObjectName( name );\n \/\/ need at least one entry for popup to work\n setMaxCount( 1 );\n setEditable( true );\n\n mDate = QDate::currentDate();\n QString today = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );\n\n addItem( today );\n setCurrentIndex( 0 );\n setSizeAdjustPolicy( AdjustToContents );\n\n connect( lineEdit(), SIGNAL( returnPressed() ),\n this, SLOT( lineEnterPressed() ) );\n connect( this, SIGNAL( textChanged( const QString& ) ),\n SLOT( slotTextChanged( const QString& ) ) );\n\n mPopup = new KDatePickerPopup( KDatePickerPopup::DatePicker | KDatePickerPopup::Words,\n QDate::currentDate(), this );\n mPopup->hide();\n mPopup->installEventFilter( this );\n\n connect( mPopup, SIGNAL( dateChanged( const QDate& ) ),\n SLOT( dateSelected( const QDate& ) ) );\n\n \/\/ handle keyword entry\n setupKeywords();\n lineEdit()->installEventFilter( this );\n\n setValidator( new DateValidator( mKeywordMap.keys(), this ) );\n\n mTextChanged = false;\n}\n\nKDateEdit::~KDateEdit()\n{\n}\n\nvoid KDateEdit::setDate( const QDate &date )\n{\n assignDate( date );\n updateView();\n}\n\nQDate KDateEdit::date() const\n{\n return mDate;\n}\n\nvoid KDateEdit::setReadOnly( bool readOnly )\n{\n mReadOnly = readOnly;\n lineEdit()->setReadOnly( readOnly );\n}\n\nbool KDateEdit::isReadOnly() const\n{\n return mReadOnly;\n}\n\nvoid KDateEdit::showPopup()\n{\n if ( mReadOnly ) {\n return;\n }\n\n QRect desk = KGlobalSettings::desktopGeometry( this );\n\n QPoint popupPoint = mapToGlobal( QPoint( 0, 0 ) );\n\n int dateFrameHeight = mPopup->sizeHint().height();\n if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {\n popupPoint.setY( popupPoint.y() - dateFrameHeight );\n } else {\n popupPoint.setY( popupPoint.y() + height() );\n }\n\n int dateFrameWidth = mPopup->sizeHint().width();\n if ( popupPoint.x() + dateFrameWidth > desk.right() ) {\n popupPoint.setX( desk.right() - dateFrameWidth );\n }\n\n if ( popupPoint.x() < desk.left() ) {\n popupPoint.setX( desk.left() );\n }\n\n if ( popupPoint.y() < desk.top() ) {\n popupPoint.setY( desk.top() );\n }\n\n if ( mDate.isValid() ) {\n mPopup->setDate( mDate );\n } else {\n mPopup->setDate( QDate::currentDate() );\n }\n\n mPopup->popup( popupPoint );\n\n \/\/ The combo box is now shown pressed. Make it show not pressed again\n \/\/ by causing its (invisible) list box to emit a 'selected' signal.\n \/\/ First, ensure that the list box contains the date currently displayed.\n QDate date = parseDate();\n assignDate( date );\n updateView();\n\n \/\/ Now, simulate an Enter to unpress it\n QAbstractItemView *lb = view();\n if ( lb ) {\n lb->setCurrentIndex( lb->model()->index( 0, 0 ) );\n QKeyEvent *keyEvent =\n new QKeyEvent( QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier );\n QApplication::postEvent( lb, keyEvent );\n }\n}\n\nvoid KDateEdit::dateSelected( const QDate &date )\n{\n if ( assignDate( date ) ) {\n updateView();\n emit dateChanged( date );\n emit dateEntered( date );\n\n if ( date.isValid() ) {\n mPopup->hide();\n }\n }\n}\n\nvoid KDateEdit::lineEnterPressed()\n{\n bool replaced = false;\n\n QDate date = parseDate( &replaced );\n\n if ( assignDate( date ) ) {\n if ( replaced ) {\n updateView();\n }\n\n emit dateChanged( date );\n emit dateEntered( date );\n }\n}\n\nQDate KDateEdit::parseDate( bool *replaced ) const\n{\n QString text = currentText();\n QDate result;\n\n if ( replaced ) {\n (*replaced) = false;\n }\n\n if ( text.isEmpty() ) {\n result = QDate();\n } else if ( mKeywordMap.contains( text.toLower() ) ) {\n QDate today = QDate::currentDate();\n int i = mKeywordMap[ text.toLower() ];\n if ( i >= 100 ) {\n \/* A day name has been entered. Convert to offset from today.\n * This uses some math tricks to figure out the offset in days\n * to the next date the given day of the week occurs. There\n * are two cases, that the new day is >= the current day, which means\n * the new day has not occurred yet or that the new day < the current day,\n * which means the new day is already passed (so we need to find the\n * day in the next week).\n *\/\n i -= 100;\n int currentDay = today.dayOfWeek();\n if ( i >= currentDay ) {\n i -= currentDay;\n } else {\n i += 7 - currentDay;\n }\n }\n\n result = today.addDays( i );\n if ( replaced ) {\n (*replaced) = true;\n }\n } else {\n result = KGlobal::locale()->readDate( text );\n }\n\n return result;\n}\n\nvoid KDateEdit::focusOutEvent( QFocusEvent *e )\n{\n if ( mTextChanged ) {\n lineEnterPressed();\n mTextChanged = false;\n }\n QComboBox::focusOutEvent( e );\n}\n\nvoid KDateEdit::keyPressEvent(QKeyEvent* e)\n{\n int step = 0;\n if ( e->key() == Qt::Key_Up ) {\n step = 1;\n } else if ( e->key() == Qt::Key_Down ) {\n step = -1;\n }\n if ( step && !mReadOnly ) {\n QDate date = parseDate();\n if ( date.isValid() ) {\n date = date.addDays( step );\n if ( assignDate( date ) ) {\n updateView();\n emit dateChanged( date );\n emit dateEntered( date );\n }\n }\n }\n QComboBox::keyPressEvent( e );\n}\n\nbool KDateEdit::eventFilter( QObject *object, QEvent *event )\n{\n if ( object == lineEdit() ) {\n \/\/ We only process the focus out event if the text has changed\n \/\/ since we got focus\n if ( ( event->type() == QEvent::FocusOut ) && mTextChanged ) {\n lineEnterPressed();\n mTextChanged = false;\n } else if ( event->type() == QEvent::KeyPress ) {\n \/\/ Up and down arrow keys step the date\n QKeyEvent *keyEvent = (QKeyEvent *)event;\n\n if ( keyEvent->key() == Qt::Key_Return ) {\n lineEnterPressed();\n return true;\n }\n }\n } else {\n \/\/ It's a date picker event\n switch ( event->type() ) {\n case QEvent::MouseButtonDblClick:\n case QEvent::MouseButtonPress:\n {\n QMouseEvent *mouseEvent = (QMouseEvent*)event;\n if ( !mPopup->rect().contains( mouseEvent->pos() ) ) {\n QPoint globalPos = mPopup->mapToGlobal( mouseEvent->pos() );\n if ( QApplication::widgetAt( globalPos ) == this ) {\n \/\/ The date picker is being closed by a click on the\n \/\/ KDateEdit widget. Avoid popping it up again immediately.\n mDiscardNextMousePress = true;\n }\n }\n\n break;\n }\n default:\n break;\n }\n }\n\n return false;\n}\n\nvoid KDateEdit::mousePressEvent( QMouseEvent *event )\n{\n if ( event->button() == Qt::LeftButton && mDiscardNextMousePress ) {\n mDiscardNextMousePress = false;\n return;\n }\n\n QComboBox::mousePressEvent( event );\n}\n\nvoid KDateEdit::slotTextChanged( const QString & )\n{\n QDate date = parseDate();\n\n if ( assignDate( date ) ) {\n emit dateChanged( date );\n }\n\n mTextChanged = true;\n}\n\nvoid KDateEdit::setupKeywords()\n{\n \/\/ Create the keyword list. This will be used to match against when the user\n \/\/ enters information.\n mKeywordMap.insert( i18nc( \"the day after today\", \"tomorrow\" ), 1 );\n mKeywordMap.insert( i18nc( \"this day\", \"today\" ), 0 );\n mKeywordMap.insert( i18nc( \"the day before today\", \"yesterday\" ), -1 );\n\n QString dayName;\n for ( int i = 1; i <= 7; ++i ) {\n dayName = KGlobal::locale()->calendar()->weekDayName( i ).toLower();\n mKeywordMap.insert( dayName, i + 100 );\n }\n}\n\nbool KDateEdit::assignDate( const QDate &date )\n{\n mDate = date;\n mTextChanged = false;\n return true;\n}\n\nvoid KDateEdit::updateView()\n{\n QString dateString;\n if ( mDate.isValid() ) {\n dateString = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );\n }\n\n \/\/ We do not want to generate a signal here,\n \/\/ since we explicitly setting the date\n bool blocked = signalsBlocked();\n blockSignals( true );\n removeItem( 0 );\n insertItem( 0, dateString );\n blockSignals( blocked );\n}\n\n#include \"kdateedit.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/Actions\/Draw.hpp>\n#include <hspp\/Actions\/Generic.hpp>\n#include <hspp\/Cards\/Cards.hpp>\n#include <hspp\/Games\/Game.hpp>\n#include <hspp\/Games\/GameManager.hpp>\n\n#include <effolkronium\/random.hpp>\n\n#include <algorithm>\n\nusing Random = effolkronium::random_static;\n\nnamespace Hearthstonepp\n{\nGame::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)\n{\n \/\/ Add hero and hero power\n GetPlayer1().AddHeroAndPower(\n Cards::GetInstance().GetHeroCard(gameConfig.player1Class),\n Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));\n GetPlayer2().AddHeroAndPower(\n Cards::GetInstance().GetHeroCard(gameConfig.player2Class),\n Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));\n\n \/\/ Set opponent player\n GetPlayer1().SetOpponent(&GetPlayer2());\n GetPlayer2().SetOpponent(&GetPlayer1());\n}\n\nPlayer& Game::GetPlayer1()\n{\n return m_players[0];\n}\n\nPlayer& Game::GetPlayer2()\n{\n return m_players[1];\n}\n\nPlayer& Game::GetCurrentPlayer()\n{\n return *m_currentPlayer;\n}\n\nPlayer& Game::GetOpponentPlayer()\n{\n return m_currentPlayer->GetOpponent();\n}\n\nvoid Game::BeginFirst()\n{\n \/\/ Set next step\n nextStep = Step::BEGIN_SHUFFLE;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginShuffle()\n{\n \/\/ Shuffle cards in deck\n if (m_gameConfig.doShuffle)\n {\n GetPlayer1().GetDeck().Shuffle();\n GetPlayer2().GetDeck().Shuffle();\n }\n\n \/\/ Set next step\n nextStep = Step::BEGIN_DRAW;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginDraw()\n{\n for (auto& p : m_players)\n {\n \/\/ Draw 3 cards\n Generic::Draw(p);\n Generic::Draw(p);\n Generic::Draw(p);\n\n if (&p != m_firstPlayer)\n {\n \/\/ Draw 4th card for second player\n Generic::Draw(p);\n\n \/\/ Give \"The Coin\" card to second player\n Card coin = Cards::GetInstance().FindCardByID(\"GAME_005\");\n p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));\n }\n }\n\n \/\/ Set next step\n nextStep =\n m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginMulligan()\n{\n \/\/ Do nothing\n}\n\nvoid Game::MainBegin()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_READY;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainReady()\n{\n \/\/ Reset the number of attacked\n for (auto& p : m_players)\n {\n \/\/ Hero\n p.GetHero()->numAttacked = 0;\n \/\/ Field\n for (auto& m : p.GetField().GetAllMinions())\n {\n m->numAttacked = 0;\n }\n }\n\n \/\/ Reset exhaust for current player\n auto& curPlayer = GetCurrentPlayer();\n \/\/ Hero\n curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);\n \/\/ Weapon\n if (curPlayer.GetHero()->weapon != nullptr)\n {\n curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);\n }\n \/\/ Hero power\n curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);\n \/\/ Field\n for (auto& m : curPlayer.GetField().GetAllMinions())\n {\n m->SetGameTag(GameTag::EXHAUSTED, 0);\n }\n\n \/\/ Set next step\n nextStep = Step::MAIN_START_TRIGGERS;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStartTriggers()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_RESOURCE;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainResource()\n{\n auto& curPlayer = GetCurrentPlayer();\n\n \/\/ Add mana crystal to current player\n Generic::ChangeManaCrystal(curPlayer, 1, false);\n\n \/\/ Reset current mana\n curPlayer.currentMana = curPlayer.maximumMana;\n\n \/\/ Set next step\n nextStep = Step::MAIN_DRAW;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainDraw()\n{\n \/\/ Draw a card for current player\n Generic::Draw(GetCurrentPlayer());\n\n \/\/ Set next step\n nextStep = Step::MAIN_START;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStart()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_ACTION;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainEnd()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_CLEANUP;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainCleanUp()\n{\n auto& curPlayer = GetCurrentPlayer();\n\n \/\/ Unfreeze all characters they control that are Frozen, don't have\n \/\/ summoning sickness (or do have Charge) and have not attacked that turn\n \/\/ Hero\n if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&\n curPlayer.GetHero()->numAttacked == 0)\n {\n curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);\n }\n \/\/ Field\n for (auto& m : curPlayer.GetField().GetAllMinions())\n {\n if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&\n m->GetGameTag(GameTag::EXHAUSTED) == 0)\n {\n m->SetGameTag(GameTag::FROZEN, 0);\n }\n }\n\n \/\/ Set next step\n nextStep = Step::MAIN_NEXT;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainNext()\n{\n \/\/ Set player for next turn\n m_currentPlayer = &m_currentPlayer->GetOpponent();\n\n \/\/ Count next turn\n m_turn++;\n\n \/\/ Set next step\n nextStep = Step::MAIN_READY;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalWrapUp()\n{\n \/\/ Do nothing\n}\n\nvoid Game::FinalGameOver()\n{\n \/\/ Do nothing\n}\n\nvoid Game::StartGame()\n{\n \/\/ Reverse card order in deck\n if (!m_gameConfig.doShuffle)\n {\n std::reverse(m_gameConfig.player1Deck.begin(),\n m_gameConfig.player1Deck.end());\n std::reverse(m_gameConfig.player2Deck.begin(),\n m_gameConfig.player2Deck.end());\n }\n\n \/\/ Set up decks\n for (auto& card : m_gameConfig.player1Deck)\n {\n Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));\n GetPlayer1().GetDeck().AddCard(*entity);\n }\n for (auto& card : m_gameConfig.player2Deck)\n {\n Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));\n GetPlayer2().GetDeck().AddCard(*entity);\n }\n\n \/\/ Determine first player\n switch (m_gameConfig.startPlayer)\n {\n case PlayerType::RANDOM:\n {\n auto val = Random::get(0, 1);\n m_firstPlayer = &m_players[val];\n break;\n }\n case PlayerType::PLAYER1:\n m_firstPlayer = &m_players[0];\n break;\n case PlayerType::PLAYER2:\n m_firstPlayer = &m_players[1];\n break;\n }\n m_currentPlayer = m_firstPlayer;\n\n \/\/ Set first turn\n m_turn = 1;\n\n \/\/ Set next step\n nextStep = Step::BEGIN_FIRST;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n} \/\/ namespace Hearthstonepp<commit_msg>[ci skip] feat(game-state): Add code to set game states<commit_after>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/Actions\/Draw.hpp>\n#include <hspp\/Actions\/Generic.hpp>\n#include <hspp\/Cards\/Cards.hpp>\n#include <hspp\/Games\/Game.hpp>\n#include <hspp\/Games\/GameManager.hpp>\n\n#include <effolkronium\/random.hpp>\n\n#include <algorithm>\n\nusing Random = effolkronium::random_static;\n\nnamespace Hearthstonepp\n{\nGame::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)\n{\n \/\/ Add hero and hero power\n GetPlayer1().AddHeroAndPower(\n Cards::GetInstance().GetHeroCard(gameConfig.player1Class),\n Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));\n GetPlayer2().AddHeroAndPower(\n Cards::GetInstance().GetHeroCard(gameConfig.player2Class),\n Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));\n\n \/\/ Set opponent player\n GetPlayer1().SetOpponent(&GetPlayer2());\n GetPlayer2().SetOpponent(&GetPlayer1());\n}\n\nPlayer& Game::GetPlayer1()\n{\n return m_players[0];\n}\n\nPlayer& Game::GetPlayer2()\n{\n return m_players[1];\n}\n\nPlayer& Game::GetCurrentPlayer()\n{\n return *m_currentPlayer;\n}\n\nPlayer& Game::GetOpponentPlayer()\n{\n return m_currentPlayer->GetOpponent();\n}\n\nvoid Game::BeginFirst()\n{\n \/\/ Set next step\n nextStep = Step::BEGIN_SHUFFLE;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginShuffle()\n{\n \/\/ Shuffle cards in deck\n if (m_gameConfig.doShuffle)\n {\n GetPlayer1().GetDeck().Shuffle();\n GetPlayer2().GetDeck().Shuffle();\n }\n\n \/\/ Set next step\n nextStep = Step::BEGIN_DRAW;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginDraw()\n{\n for (auto& p : m_players)\n {\n \/\/ Draw 3 cards\n Generic::Draw(p);\n Generic::Draw(p);\n Generic::Draw(p);\n\n if (&p != m_firstPlayer)\n {\n \/\/ Draw 4th card for second player\n Generic::Draw(p);\n\n \/\/ Give \"The Coin\" card to second player\n Card coin = Cards::GetInstance().FindCardByID(\"GAME_005\");\n p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));\n }\n }\n\n \/\/ Set next step\n nextStep =\n m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginMulligan()\n{\n \/\/ Do nothing\n}\n\nvoid Game::MainBegin()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_READY;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainReady()\n{\n \/\/ Reset the number of attacked\n for (auto& p : m_players)\n {\n \/\/ Hero\n p.GetHero()->numAttacked = 0;\n \/\/ Field\n for (auto& m : p.GetField().GetAllMinions())\n {\n m->numAttacked = 0;\n }\n }\n\n \/\/ Reset exhaust for current player\n auto& curPlayer = GetCurrentPlayer();\n \/\/ Hero\n curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);\n \/\/ Weapon\n if (curPlayer.GetHero()->weapon != nullptr)\n {\n curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);\n }\n \/\/ Hero power\n curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);\n \/\/ Field\n for (auto& m : curPlayer.GetField().GetAllMinions())\n {\n m->SetGameTag(GameTag::EXHAUSTED, 0);\n }\n\n \/\/ Set next step\n nextStep = Step::MAIN_START_TRIGGERS;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStartTriggers()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_RESOURCE;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainResource()\n{\n auto& curPlayer = GetCurrentPlayer();\n\n \/\/ Add mana crystal to current player\n Generic::ChangeManaCrystal(curPlayer, 1, false);\n\n \/\/ Reset current mana\n curPlayer.currentMana = curPlayer.maximumMana;\n\n \/\/ Set next step\n nextStep = Step::MAIN_DRAW;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainDraw()\n{\n \/\/ Draw a card for current player\n Generic::Draw(GetCurrentPlayer());\n\n \/\/ Set next step\n nextStep = Step::MAIN_START;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStart()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_ACTION;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainEnd()\n{\n \/\/ Set next step\n nextStep = Step::MAIN_CLEANUP;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainCleanUp()\n{\n auto& curPlayer = GetCurrentPlayer();\n\n \/\/ Unfreeze all characters they control that are Frozen, don't have\n \/\/ summoning sickness (or do have Charge) and have not attacked that turn\n \/\/ Hero\n if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&\n curPlayer.GetHero()->numAttacked == 0)\n {\n curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);\n }\n \/\/ Field\n for (auto& m : curPlayer.GetField().GetAllMinions())\n {\n if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&\n m->GetGameTag(GameTag::EXHAUSTED) == 0)\n {\n m->SetGameTag(GameTag::FROZEN, 0);\n }\n }\n\n \/\/ Set next step\n nextStep = Step::MAIN_NEXT;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainNext()\n{\n \/\/ Set player for next turn\n m_currentPlayer = &m_currentPlayer->GetOpponent();\n\n \/\/ Count next turn\n m_turn++;\n\n \/\/ Set next step\n nextStep = Step::MAIN_READY;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalWrapUp()\n{\n \/\/ Do nothing\n}\n\nvoid Game::FinalGameOver()\n{\n \/\/ Do nothing\n}\n\nvoid Game::StartGame()\n{\n \/\/ Reverse card order in deck\n if (!m_gameConfig.doShuffle)\n {\n std::reverse(m_gameConfig.player1Deck.begin(),\n m_gameConfig.player1Deck.end());\n std::reverse(m_gameConfig.player2Deck.begin(),\n m_gameConfig.player2Deck.end());\n }\n\n \/\/ Set up decks\n for (auto& card : m_gameConfig.player1Deck)\n {\n Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));\n GetPlayer1().GetDeck().AddCard(*entity);\n }\n for (auto& card : m_gameConfig.player2Deck)\n {\n Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));\n GetPlayer2().GetDeck().AddCard(*entity);\n }\n\n \/\/ Set game states\n state = State::RUNNING;\n for (auto& p : m_players)\n {\n p.playState = PlayState::PLAYING;\n }\n\n \/\/ Determine first player\n switch (m_gameConfig.startPlayer)\n {\n case PlayerType::RANDOM:\n {\n auto val = Random::get(0, 1);\n m_firstPlayer = &m_players[val];\n break;\n }\n case PlayerType::PLAYER1:\n m_firstPlayer = &m_players[0];\n break;\n case PlayerType::PLAYER2:\n m_firstPlayer = &m_players[1];\n break;\n }\n m_currentPlayer = m_firstPlayer;\n\n \/\/ Set first turn\n m_turn = 1;\n\n \/\/ Set next step\n nextStep = Step::BEGIN_FIRST;\n GameManager::ProcessNextStep(*this, nextStep);\n}\n} \/\/ namespace Hearthstonepp<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of libkdepim.\n\n Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include <time.h>\n#include <unistd.h>\n\n#include <qstring.h>\n\n#include <kstandarddirs.h>\n#include <kglobal.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kdebug.h>\n\n#include \"kpimprefs.h\"\n\nKPimPrefs::KPimPrefs( const QString &name )\n : KConfigSkeleton( name )\n{\n}\n\nKPimPrefs::~KPimPrefs()\n{\n}\n\nvoid KPimPrefs::usrSetDefaults()\n{\n setCategoryDefaults();\n}\n\nvoid KPimPrefs::usrReadConfig()\n{\n kdDebug(5300) << \"KPimPrefs::usrReadConfig()\" << endl;\n\n config()->setGroup(\"General\");\n mCustomCategories = config()->readListEntry(\"Custom Categories\");\n if (mCustomCategories.isEmpty()) setCategoryDefaults();\n}\n\nconst QString KPimPrefs::timezone()\n{\n QString zone = \"\";\n\n \/\/ Read TimeZoneId from korganizerrc.\n KConfig korgcfg( locate( \"config\", QString::fromLatin1(\"korganizerrc\") ) );\n korgcfg.setGroup( \"Time & Date\" );\n QString tz(korgcfg.readEntry( \"TimeZoneId\" ) );\n if ( ! tz.isEmpty() ) \n {\n zone = tz;\n kdDebug(5300) << \"timezone from korganizerrc is \" << zone << endl;\n }\n\n \/\/ If timezone not found in KOrg, use the system's default timezone.\n if ( zone.isEmpty() )\n {\n char zonefilebuf[PATH_MAX];\n\n \/\/ readlink does not return a null-terminated string.\n memset(zonefilebuf, '\\0', PATH_MAX);\n int len = readlink(\"\/etc\/localtime\", zonefilebuf, PATH_MAX);\n if ( len > 0 && len < PATH_MAX ) \n {\n zone = QString::fromLocal8Bit(zonefilebuf);\n zone = zone.mid(zone.find(\"zoneinfo\/\") + 9);\n kdDebug(5300) << \"system timezone from \/etc\/localtime is \" << zone << endl;\n } \n else \n {\n tzset();\n zone = tzname[0];\n kdDebug(5300) << \"system timezone from tzset() is \" << zone << endl;\n }\n }\n\n return( zone );\n\n}\n\nvoid KPimPrefs::usrWriteConfig()\n{\n config()->setGroup(\"General\");\n config()->writeEntry(\"Custom Categories\",mCustomCategories);\n}\n<commit_msg>No QT_NO_CAST_ASCII in libkdepim, so don't need fromLatin1.<commit_after>\/*\n This file is part of libkdepim.\n\n Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include <time.h>\n#include <unistd.h>\n\n#include <qstring.h>\n\n#include <kstandarddirs.h>\n#include <kglobal.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kdebug.h>\n\n#include \"kpimprefs.h\"\n\nKPimPrefs::KPimPrefs( const QString &name )\n : KConfigSkeleton( name )\n{\n}\n\nKPimPrefs::~KPimPrefs()\n{\n}\n\nvoid KPimPrefs::usrSetDefaults()\n{\n setCategoryDefaults();\n}\n\nvoid KPimPrefs::usrReadConfig()\n{\n kdDebug(5300) << \"KPimPrefs::usrReadConfig()\" << endl;\n\n config()->setGroup(\"General\");\n mCustomCategories = config()->readListEntry(\"Custom Categories\");\n if (mCustomCategories.isEmpty()) setCategoryDefaults();\n}\n\nconst QString KPimPrefs::timezone()\n{\n QString zone = \"\";\n\n \/\/ Read TimeZoneId from korganizerrc.\n KConfig korgcfg( locate( \"config\", \"korganizerrc\" ) );\n korgcfg.setGroup( \"Time & Date\" );\n QString tz(korgcfg.readEntry( \"TimeZoneId\" ) );\n if ( ! tz.isEmpty() ) \n {\n zone = tz;\n kdDebug(5300) << \"timezone from korganizerrc is \" << zone << endl;\n }\n\n \/\/ If timezone not found in KOrg, use the system's default timezone.\n if ( zone.isEmpty() )\n {\n char zonefilebuf[PATH_MAX];\n\n int len = readlink(\"\/etc\/localtime\", zonefilebuf, PATH_MAX);\n if ( len > 0 && len < PATH_MAX ) \n {\n zone = QString::fromLocal8Bit(zonefilebuf, len);\n zone = zone.mid(zone.find(\"zoneinfo\/\") + 9);\n kdDebug(5300) << \"system timezone from \/etc\/localtime is \" << zone << endl;\n } \n else \n {\n tzset();\n zone = tzname[0];\n kdDebug(5300) << \"system timezone from tzset() is \" << zone << endl;\n }\n }\n\n return( zone );\n\n}\n\nvoid KPimPrefs::usrWriteConfig()\n{\n config()->setGroup(\"General\");\n config()->writeEntry(\"Custom Categories\",mCustomCategories);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <zombye\/core\/game.hpp>\n#include <zombye\/ecs\/entity.hpp>\n#include <zombye\/gameplay\/gameplay_system.hpp>\n#include <zombye\/gameplay\/state_component.hpp>\n#include <zombye\/scripting\/scripting_system.hpp>\n\nnamespace zombye {\n state_component::state_component(game& game, entity& owner)\n : reflective{game, owner}, scripting_system_{game_.scripting_system()}, current_state_{nullptr} {\n game_.gameplay()->register_component(this);\n }\n\n state_component::~state_component() {\n game_.gameplay()->unregister_component(this);\n }\n\n void state_component::emplace(const std::string& state_name, const std::string& file_name) {\n auto it = states_.find(state_name);\n if (it != states_.end()) {\n throw std::runtime_error(\"state \" + state_name + \" already exists in \" + std::to_string(owner_.id()));\n }\n\n static auto state_prefix = std::to_string(owner_.id()) + \"_\";\n auto module_name = state_prefix + state_name;\n\n scripting_system_.begin_module(module_name);\n scripting_system_.load_script(file_name);\n scripting_system_.end_module();\n\n auto module = scripting_system_.script_engine().GetModule(module_name.c_str());\n if (!module) {\n throw std::runtime_error(\"no module named \" + module_name);\n }\n\n auto enter_ptr = module->GetFunctionByName(\"enter\");\n if (!enter_ptr) {\n throw std::runtime_error(\"no function callback for enter state in \" + file_name);\n }\n\n auto update_ptr = module->GetFunctionByName(\"update\");\n if (!update_ptr) {\n throw std::runtime_error(\"no function callback for update state in \" + file_name);\n }\n\n auto leave_ptr = module->GetFunctionByName(\"leave\");\n if (!leave_ptr) {\n throw std::runtime_error(\"no function callback for leave state in \" + file_name);\n }\n\n states_.insert(std::make_pair(state_name, character_state{enter_ptr, update_ptr, leave_ptr}));\n }\n\n void state_component::change_state(const std::string& state_name) {\n auto it = states_.find(state_name);\n if (it == states_.end()) {\n throw std::runtime_error(\"entity \" + std::to_string(owner_.id()) + \" has no state \" + state_name);\n }\n\n if (current_state_) {\n scripting_system_.prepare(*current_state_->leave);\n scripting_system_.argument(0, &owner_);\n scripting_system_.exec();\n }\n\n current_state_ = &(it->second);\n scripting_system_.prepare(*current_state_->enter);\n scripting_system_.argument(0, &owner_);\n scripting_system_.exec();\n }\n\n void state_component::update(float delta_time) {\n if (current_state_) {\n scripting_system_.prepare(*current_state_->update);\n scripting_system_.argument(0, delta_time);\n scripting_system_.argument(1, &owner_);\n scripting_system_.exec();\n }\n }\n\n void state_component::register_at_script_engine(game& game) {\n auto& scripting_system = game.scripting_system();\n\n scripting_system.register_type<state_component>(\"state_component\");\n\n scripting_system.register_member_function(\"state_component\", \"void emplace(const string& in, const string& in)\",\n +[](state_component& component, const std::string& state_name, const std::string& file_name) {\n component.emplace(state_name, file_name);\n });\n scripting_system.register_member_function(\"state_component\", \"void change_state(const string& in)\",\n +[](state_component& component, const std::string& state_name) { component.change_state(state_name); });\n\n scripting_system.register_member_function(\"entity_impl\",\n \"state_component& add_state_component()\",\n +[](entity& owner) -> state_component& {\n return owner.emplace<state_component>();\n });\n scripting_system.register_member_function(\"entity_impl\", \"state_component@ get_state_component()\",\n +[](entity& owner) { return owner.component<state_component>(); });\n }\n}\n<commit_msg>fix wrong argument pass to scripting_system::argument<commit_after>#include <zombye\/core\/game.hpp>\n#include <zombye\/ecs\/entity.hpp>\n#include <zombye\/gameplay\/gameplay_system.hpp>\n#include <zombye\/gameplay\/state_component.hpp>\n#include <zombye\/scripting\/scripting_system.hpp>\n\nnamespace zombye {\n state_component::state_component(game& game, entity& owner)\n : reflective{game, owner}, scripting_system_{game_.scripting_system()}, current_state_{nullptr} {\n game_.gameplay()->register_component(this);\n }\n\n state_component::~state_component() {\n game_.gameplay()->unregister_component(this);\n }\n\n void state_component::emplace(const std::string& state_name, const std::string& file_name) {\n auto it = states_.find(state_name);\n if (it != states_.end()) {\n throw std::runtime_error(\"state \" + state_name + \" already exists in \" + std::to_string(owner_.id()));\n }\n\n static auto state_prefix = std::to_string(owner_.id()) + \"_\";\n auto module_name = state_prefix + state_name;\n\n scripting_system_.begin_module(module_name);\n scripting_system_.load_script(file_name);\n scripting_system_.end_module();\n\n auto module = scripting_system_.script_engine().GetModule(module_name.c_str());\n if (!module) {\n throw std::runtime_error(\"no module named \" + module_name);\n }\n\n auto enter_ptr = module->GetFunctionByName(\"enter\");\n if (!enter_ptr) {\n throw std::runtime_error(\"no function callback for enter state in \" + file_name);\n }\n\n auto update_ptr = module->GetFunctionByName(\"update\");\n if (!update_ptr) {\n throw std::runtime_error(\"no function callback for update state in \" + file_name);\n }\n\n auto leave_ptr = module->GetFunctionByName(\"leave\");\n if (!leave_ptr) {\n throw std::runtime_error(\"no function callback for leave state in \" + file_name);\n }\n\n states_.insert(std::make_pair(state_name, character_state{enter_ptr, update_ptr, leave_ptr}));\n }\n\n void state_component::change_state(const std::string& state_name) {\n auto it = states_.find(state_name);\n if (it == states_.end()) {\n throw std::runtime_error(\"entity \" + std::to_string(owner_.id()) + \" has no state \" + state_name);\n }\n\n if (current_state_) {\n scripting_system_.prepare(*current_state_->leave);\n scripting_system_.argument(0, owner_);\n scripting_system_.exec();\n }\n\n current_state_ = &(it->second);\n scripting_system_.prepare(*current_state_->enter);\n scripting_system_.argument(0, owner_);\n scripting_system_.exec();\n }\n\n void state_component::update(float delta_time) {\n if (current_state_) {\n scripting_system_.prepare(*current_state_->update);\n scripting_system_.argument(0, delta_time);\n scripting_system_.argument(1, owner_);\n scripting_system_.exec();\n }\n }\n\n void state_component::register_at_script_engine(game& game) {\n auto& scripting_system = game.scripting_system();\n\n scripting_system.register_type<state_component>(\"state_component\");\n\n scripting_system.register_member_function(\"state_component\", \"void emplace(const string& in, const string& in)\",\n +[](state_component& component, const std::string& state_name, const std::string& file_name) {\n component.emplace(state_name, file_name);\n });\n scripting_system.register_member_function(\"state_component\", \"void change_state(const string& in)\",\n +[](state_component& component, const std::string& state_name) { component.change_state(state_name); });\n\n scripting_system.register_member_function(\"entity_impl\",\n \"state_component& add_state_component()\",\n +[](entity& owner) -> state_component& {\n return owner.emplace<state_component>();\n });\n scripting_system.register_member_function(\"entity_impl\", \"state_component@ get_state_component()\",\n +[](entity& owner) { return owner.component<state_component>(); });\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP\n#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP\n\n#include <vector>\n#include <boost\/math\/tools\/promotion.hpp>\n\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n\n#include <stan\/math\/prim\/scal\/err\/check_equal.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive.hpp>\n\nnamespace stan {\n\n namespace math {\n\n \/** Return the multiplication of the sparse matrix spefcified by\n * by values and indexing by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * row index of each value), the integer array u (containing\n * one-based indexes of where each column starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each column of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Rows in matrix.\n * @param n Columns in matrix.\n * @param v One-based row index of each value.\n * @param u one-based index of where each column starts in w.\n * @param z number of non-zer entries in each column of w.\n * @return dense vector for the product.\n * @throw ... explain error conditions briefly ...\n *\/\n \/** Return the multiplication of the sparse matrix (specified by\n * by values and indexing) by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * row index of each value), the integer array u (containing\n * one-based indexes of where each column starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each column of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Number of rows in matrix.\n * @param n Number of columns in matrix.\n\t\t * @param w Vector of non-zero values in matrix.\n * @param v One-based row index of each non-zero value, same\n\t\t * length as w.\n * @param u one-based index of where each column starts in w, equal to\n\t\t * the number of columns plus one.\n * @param z number of non-zero entries in each column of w, equal to\n\t\t * the number of columns..\n * @return dense vector for the product.\n * @throw std::domain_error if m and n are not positive or are nan.\n\t\t * @throw std::domain_error if the implied sparse matrix and b are \n\t\t * not multiplicable.\n\t\t * @throw std::domain_error if m\/n\/w\/v\/u\/z are not internally\n\t\t * consistent, as defined by the indexing scheme. Extractors are\n\t\t * defined in Stan which guarantee a consistent set of m\/n\/w\/v\/u\/z\n\t\t * for a given sparse matrix. \n *\/\n template <typename T1, typename T2>\n inline\n Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>\n sparse_multiply_csc(const int& m,\n const int& n,\n const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,\n const std::vector<int>& v,\n const std::vector<int>& u,\n const std::vector<int>& z,\n const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {\n\n\t\t\tstan::math::check_positive(\"sparse_multiply_csr\",\"m\",m);\n\t\t\tstan::math::check_positive(\"sparse_multiply_csr\",\"n\",n);\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"n\/b\", n, b.size());\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"n\/u\", n, u.size()-1);\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"n\/z\", n, z.size() );\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"w\/v\", w.size(), v.size());\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"u\/z\/v\", u[n-1]+z[n-1]-1, v.size());\n\n typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;\n Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);\n for (int j = 0; j < n; ++j) {\n int end = u[j] + z[j] - 1;\n for (int q = u[j] - 1; q < end; ++q)\n y(v[q]-1) += w[q] * b(j);\n }\n return y;\n }\n\n \/** Return the multiplication of the sparse matrix (specified by\n * by values and indexing) by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * column index of each value), the integer array u (containing\n * one-based indexes of where each row starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each row of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Number of rows in matrix.\n * @param n Number of columns in matrix.\n\t\t * @param w Vector of non-zero values in matrix.\n * @param v One-based column index of each non-zero value, same\n\t\t * length as w.\n * @param u one-based index of where each row starts in w, equal to\n\t\t * the number of rows plus one.\n * @param z number of non-zero entries in each row of w, equal to\n\t\t * the number of rows..\n * @return dense vector for the product.\n * @throw std::domain_error if m and n are not positive or are nan.\n\t\t * @throw std::domain_error if the implied sparse matrix and b are \n\t\t * not multiplicable.\n\t\t * @throw std::domain_error if m\/n\/w\/v\/u\/z are not internally\n\t\t * consistent, as defined by the indexing scheme. Extractors are\n\t\t * defined in Stan which guarantee a consistent set of m\/n\/w\/v\/u\/z\n\t\t * for a given sparse matrix. \n *\/\n template <typename T1, typename T2>\n inline\n Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>\n sparse_multiply_csr(const int& m,\n const int& n,\n const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,\n const std::vector<int>& v,\n const std::vector<int>& u,\n const std::vector<int>& z,\n const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {\n\n\t\t\tstan::math::check_positive(\"sparse_multiply_csr\",\"m\",m);\n\t\t\tstan::math::check_positive(\"sparse_multiply_csr\",\"n\",n);\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"n\/b\", n, b.size());\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"m\/u\", m, u.size()-1);\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"m\/z\", m, z.size() );\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"w\/v\", w.size(), v.size());\n\t\t\tstan::math::check_equal(\"sparse_multiply_csr\",\"u\/z\/v\", u[m-1]+z[m-1]-1, v.size());\n\n typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;\n Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);\n for (int i = 0; i < m; ++i) {\n int end = u[i] + z[i] - 1;\n int p = 0;\n Eigen::Matrix<T2,Eigen::Dynamic,1> b_sub(z[i]);\n for (int q = u[i]-1; q < end; ++q) {\n b_sub(p) = b(v[q]-1); \n ++p;\n }\n Eigen::Matrix<T2,Eigen::Dynamic,1> w_sub = w.segment(u[i]-1,z[i]);\n y(i) = stan::math::dot_product(w_sub,b_sub);\n }\n return y;\n }\n\n }\n\n}\n\n#endif\n\n\n<commit_msg>Fixed tabs.<commit_after>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP\n#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP\n\n#include <vector>\n#include <boost\/math\/tools\/promotion.hpp>\n\n#include <stan\/math\/prim\/mat\/fun\/Eigen.hpp>\n\n#include <stan\/math\/prim\/scal\/err\/check_equal.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive.hpp>\n\nnamespace stan {\n\n namespace math {\n\n \/** Return the multiplication of the sparse matrix spefcified by\n * by values and indexing by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * row index of each value), the integer array u (containing\n * one-based indexes of where each column starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each column of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Rows in matrix.\n * @param n Columns in matrix.\n * @param v One-based row index of each value.\n * @param u one-based index of where each column starts in w.\n * @param z number of non-zer entries in each column of w.\n * @return dense vector for the product.\n * @throw ... explain error conditions briefly ...\n *\/\n \/** Return the multiplication of the sparse matrix (specified by\n * by values and indexing) by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * row index of each value), the integer array u (containing\n * one-based indexes of where each column starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each column of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Number of rows in matrix.\n * @param n Number of columns in matrix.\n * @param w Vector of non-zero values in matrix.\n * @param v One-based row index of each non-zero value, same\n * length as w.\n * @param u one-based index of where each column starts in w, equal to\n * the number of columns plus one.\n * @param z number of non-zero entries in each column of w, equal to\n * the number of columns..\n * @return dense vector for the product.\n * @throw std::domain_error if m and n are not positive or are nan.\n * @throw std::domain_error if the implied sparse matrix and b are \n * not multiplicable.\n * @throw std::domain_error if m\/n\/w\/v\/u\/z are not internally\n * consistent, as defined by the indexing scheme. Extractors are\n * defined in Stan which guarantee a consistent set of m\/n\/w\/v\/u\/z\n * for a given sparse matrix. \n *\/\n template <typename T1, typename T2>\n inline\n Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>\n sparse_multiply_csc(const int& m,\n const int& n,\n const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,\n const std::vector<int>& v,\n const std::vector<int>& u,\n const std::vector<int>& z,\n const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {\n\n stan::math::check_positive(\"sparse_multiply_csr\",\"m\",m);\n stan::math::check_positive(\"sparse_multiply_csr\",\"n\",n);\n stan::math::check_equal(\"sparse_multiply_csr\",\"n\/b\", n, b.size());\n stan::math::check_equal(\"sparse_multiply_csr\",\"n\/u\", n, u.size()-1);\n stan::math::check_equal(\"sparse_multiply_csr\",\"n\/z\", n, z.size() );\n stan::math::check_equal(\"sparse_multiply_csr\",\"w\/v\", w.size(), v.size());\n stan::math::check_equal(\"sparse_multiply_csr\",\"u\/z\/v\", u[n-1]+z[n-1]-1, v.size());\n\n typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;\n Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);\n for (int j = 0; j < n; ++j) {\n int end = u[j] + z[j] - 1;\n for (int q = u[j] - 1; q < end; ++q)\n y(v[q]-1) += w[q] * b(j);\n }\n return y;\n }\n\n \/** Return the multiplication of the sparse matrix (specified by\n * by values and indexing) by the specified dense vector.\n *\n * The sparse matrix X of dimension m by n is represented by the\n * vector w (of values), the integer array v (containing one-based\n * column index of each value), the integer array u (containing\n * one-based indexes of where each row starts in w), and the\n * integer array z (containing the number of non-zero entries in\n * each row of w).\n *\n * @tparam T1 Type of sparse matrix entries.\n * @tparam T2 Type of dense vector entries.\n * @param m Number of rows in matrix.\n * @param n Number of columns in matrix.\n * @param w Vector of non-zero values in matrix.\n * @param v One-based column index of each non-zero value, same\n * length as w.\n * @param u one-based index of where each row starts in w, equal to\n * the number of rows plus one.\n * @param z number of non-zero entries in each row of w, equal to\n * the number of rows..\n * @return dense vector for the product.\n * @throw std::domain_error if m and n are not positive or are nan.\n * @throw std::domain_error if the implied sparse matrix and b are \n * not multiplicable.\n * @throw std::domain_error if m\/n\/w\/v\/u\/z are not internally\n * consistent, as defined by the indexing scheme. Extractors are\n * defined in Stan which guarantee a consistent set of m\/n\/w\/v\/u\/z\n * for a given sparse matrix. \n *\/\n template <typename T1, typename T2>\n inline\n Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>\n sparse_multiply_csr(const int& m,\n const int& n,\n const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,\n const std::vector<int>& v,\n const std::vector<int>& u,\n const std::vector<int>& z,\n const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {\n\n stan::math::check_positive(\"sparse_multiply_csr\",\"m\",m);\n stan::math::check_positive(\"sparse_multiply_csr\",\"n\",n);\n stan::math::check_equal(\"sparse_multiply_csr\",\"n\/b\", n, b.size());\n stan::math::check_equal(\"sparse_multiply_csr\",\"m\/u\", m, u.size()-1);\n stan::math::check_equal(\"sparse_multiply_csr\",\"m\/z\", m, z.size() );\n stan::math::check_equal(\"sparse_multiply_csr\",\"w\/v\", w.size(), v.size());\n stan::math::check_equal(\"sparse_multiply_csr\",\"u\/z\/v\", u[m-1]+z[m-1]-1, v.size());\n\n typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;\n Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1> y(m);\n for (int i = 0; i < m; ++i) {\n int end = u[i] + z[i] - 1;\n int p = 0;\n Eigen::Matrix<T2,Eigen::Dynamic,1> b_sub(z[i]);\n for (int q = u[i]-1; q < end; ++q) {\n b_sub(p) = b(v[q]-1); \n ++p;\n }\n Eigen::Matrix<T2,Eigen::Dynamic,1> w_sub = w.segment(u[i]-1,z[i]);\n y(i) = stan::math::dot_product(w_sub,b_sub);\n }\n return y;\n }\n\n }\n\n}\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ircmanager.h\"\n#include \"asyncexec.h\"\n#include \"channel.h\"\n#include \"channels.h\"\n\n#include <irccommand.h>\n#include <ircconnection.h>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <future>\n\nnamespace chatterino {\n\nAccount *IrcManager::account = nullptr;\nstd::shared_ptr<IrcConnection> IrcManager::connection;\nQMutex IrcManager::connectionMutex;\nlong IrcManager::connectionGeneration = 0;\nconst QString IrcManager::defaultClientId = \"7ue61iz46fz11y3cugd0l3tawb4taal\";\nQNetworkAccessManager IrcManager::accessManager;\n\nQMap<QString, bool> IrcManager::twitchBlockedUsers;\nQMutex IrcManager::twitchBlockedUsersMutex;\n\nIrcManager::IrcManager()\n{\n}\n\nvoid\nIrcManager::connect()\n{\n disconnect();\n\n async_exec([] { beginConnecting(); });\n}\n\nvoid\nIrcManager::beginConnecting()\n{\n IrcManager::account = const_cast<Account *>(Account::getAnon());\n\n int generation = ++IrcManager::connectionGeneration;\n\n auto c = new IrcConnection();\n\n QObject::connect(c, &IrcConnection::messageReceived, &messageReceived);\n QObject::connect(c, &IrcConnection::privateMessageReceived,\n &privateMessageReceived);\n\n if (account->isAnon()) {\n \/\/ fetch ignored users\n QString username = account->getUsername();\n QString oauthClient = account->getOauthClient();\n QString oauthToken = account->getOauthToken();\n\n {\n QString nextLink = \"https:\/\/api.twitch.tv\/kraken\/users\/\" +\n username + \"\/blocks?limit=\" + 100 +\n \"&client_id=\" + oauthClient;\n\n QNetworkAccessManager *manager = new QNetworkAccessManager();\n QNetworkRequest req(QUrl(nextLink + \"&oauth_token=\" + oauthToken));\n QNetworkReply *reply = manager->get(req);\n\n QObject::connect(reply, &QNetworkReply::finished, [=] {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.clear();\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n QByteArray data = reply->readAll();\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n QJsonObject root = jsonDoc.object();\n\n \/\/ nextLink =\n \/\/ root.value(\"_links\").toObject().value(\"next\").toString();\n\n auto blocks = root.value(\"blocks\").toArray();\n\n IrcManager::twitchBlockedUsersMutex.lock();\n for (QJsonValue block : blocks) {\n QJsonObject user =\n block.toObject().value(\"user\").toObject();\n \/\/ display_name\n IrcManager::twitchBlockedUsers.insert(\n user.value(\"name\").toString().toLower(), true);\n }\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n manager->deleteLater();\n });\n }\n\n \/\/ fetch available twitch emtoes\n {\n QNetworkRequest req(QUrl(\"https:\/\/api.twitch.tv\/kraken\/users\/\" +\n username + \"\/emotes?oauth_token=\" +\n oauthToken + \"&client_id=\" + oauthClient));\n QNetworkReply *reply = IrcManager::accessManager.get(req);\n\n QObject::connect(reply, &QNetworkReply::finished, [=] {\n QByteArray data = reply->readAll();\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n QJsonObject root = jsonDoc.object();\n\n \/\/ nextLink =\n \/\/ root.value(\"_links\").toObject().value(\"next\").toString();\n\n auto blocks = root.value(\"blocks\").toArray();\n\n IrcManager::twitchBlockedUsersMutex.lock();\n for (QJsonValue block : blocks) {\n QJsonObject user =\n block.toObject().value(\"user\").toObject();\n \/\/ display_name\n IrcManager::twitchBlockedUsers.insert(\n user.value(\"name\").toString().toLower(), true);\n }\n IrcManager::twitchBlockedUsersMutex.unlock();\n });\n }\n }\n\n c->setHost(\"irc.chat.twitch.tv\");\n c->setPort(6667);\n\n c->setUserName(\"justinfan123\");\n c->setNickName(\"justinfan123\");\n c->setRealName(\"justinfan123\");\n\n c->sendCommand(IrcCommand::createCapability(\"REQ\", \"twitch.tv\/commands\"));\n c->sendCommand(IrcCommand::createCapability(\"REQ\", \"twitch.tv\/tags\"));\n\n c->open();\n\n IrcManager::connectionMutex.lock();\n if (generation == IrcManager::connectionGeneration) {\n c->moveToThread(QCoreApplication::instance()->thread());\n IrcManager::connection = std::shared_ptr<IrcConnection>(c);\n\n auto channels = Channels::getItems();\n\n for (auto &channel : channels) {\n IrcManager::sendJoin(channel.get()->getName());\n }\n } else {\n delete c;\n }\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::disconnect()\n{\n IrcManager::connectionMutex.lock();\n\n if (IrcManager::connection.get() != NULL) {\n IrcManager::connection = std::shared_ptr<IrcConnection>();\n }\n\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::send(QString raw)\n{\n IrcManager::connectionMutex.lock();\n IrcManager::connection->sendRaw(raw);\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::sendJoin(const QString &channel)\n{\n IrcManager::connectionMutex.lock();\n if (IrcManager::connection != NULL) {\n IrcManager::connection->sendRaw(\"JOIN #\" + channel);\n }\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::partChannel(const QString &channel)\n{\n IrcManager::connectionMutex.lock();\n if (IrcManager::connection != NULL) {\n IrcManager::connection->sendRaw(\"PART #\" + channel);\n }\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::messageReceived(IrcMessage *message)\n{\n \/\/ qInfo(message->command().toStdString().c_str());\n\n const QString &command = message->command();\n\n \/\/ if (command == \"CLEARCHAT\") {\n \/\/ message->\n \/\/ } else if (command == \"ROOMSTATE\") {\n \/\/ } else if (command == \"USERSTATE\") {\n \/\/ } else if (command == \"WHISPER\") {\n \/\/ } else if (command == \"USERNOTICE\") {\n \/\/ }\n}\n\nvoid\nIrcManager::privateMessageReceived(IrcPrivateMessage *message)\n{\n \/\/ qInfo(message->content().toStdString().c_str());\n\n auto c = Channels::getChannel(message->target().mid(1));\n\n if (c != NULL) {\n c->addMessage(std::shared_ptr<messages::Message>(\n new messages::Message(*message, *c)));\n }\n}\n\nbool\nIrcManager::isTwitchBlockedUser(QString const &username)\n{\n IrcManager::twitchBlockedUsersMutex.lock();\n\n auto iterator = IrcManager::twitchBlockedUsers.find(username);\n\n if (iterator == IrcManager::twitchBlockedUsers.end()) {\n IrcManager::twitchBlockedUsersMutex.unlock();\n return false;\n }\n\n IrcManager::twitchBlockedUsersMutex.unlock();\n return true;\n}\n\nbool\nIrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)\n{\n QUrl url(\"https:\/\/api.twitch.tv\/kraken\/users\/\" + account->getUsername() +\n \"\/blocks\/\" + username +\n \"?oauth_token=\" + account->getOauthToken() +\n \"&client_id=\" + account->getOauthClient());\n\n QNetworkRequest request(url);\n auto reply = IrcManager::accessManager.put(request, QByteArray());\n reply->waitForReadyRead(10000);\n\n if (reply->error() == QNetworkReply::NoError) {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.insert(username, true);\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n delete reply;\n return true;\n }\n\n errorMessage = \"Error while ignoring user \\\"\" + username +\n \"\\\": \" + reply->errorString();\n return false;\n}\n\nvoid\nIrcManager::addIgnoredUser(QString const &username)\n{\n QString errorMessage;\n if (!tryAddIgnoredUser(username, errorMessage)) {\n \/\/ TODO: Implement IrcManager::addIgnoredUser\n }\n}\n\nbool\nIrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)\n{\n QUrl url(\"https:\/\/api.twitch.tv\/kraken\/users\/\" + account->getUsername() +\n \"\/blocks\/\" + username +\n \"?oauth_token=\" + account->getOauthToken() +\n \"&client_id=\" + account->getOauthClient());\n\n QNetworkRequest request(url);\n auto reply = IrcManager::accessManager.deleteResource(request);\n reply->waitForReadyRead(10000);\n\n if (reply->error() == QNetworkReply::NoError) {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.remove(username);\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n delete reply;\n return true;\n }\n\n errorMessage = \"Error while unignoring user \\\"\" + username +\n \"\\\": \" + reply->errorString();\n return false;\n}\n\nvoid\nIrcManager::removeIgnoredUser(QString const &username)\n{\n QString errorMessage;\n if (!tryRemoveIgnoredUser(username, errorMessage)) {\n \/\/ TODO: Implement IrcManager::removeIgnoredUser\n }\n}\n}\n<commit_msg>join channels when IrcChonnection started<commit_after>#include \"ircmanager.h\"\n#include \"asyncexec.h\"\n#include \"channel.h\"\n#include \"channels.h\"\n\n#include <irccommand.h>\n#include <ircconnection.h>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <future>\n\nnamespace chatterino {\n\nAccount *IrcManager::account = nullptr;\nstd::shared_ptr<IrcConnection> IrcManager::connection;\nQMutex IrcManager::connectionMutex;\nlong IrcManager::connectionGeneration = 0;\nconst QString IrcManager::defaultClientId = \"7ue61iz46fz11y3cugd0l3tawb4taal\";\nQNetworkAccessManager IrcManager::accessManager;\n\nQMap<QString, bool> IrcManager::twitchBlockedUsers;\nQMutex IrcManager::twitchBlockedUsersMutex;\n\nIrcManager::IrcManager()\n{\n}\n\nvoid\nIrcManager::connect()\n{\n disconnect();\n\n async_exec([] { beginConnecting(); });\n}\n\nvoid\nIrcManager::beginConnecting()\n{\n IrcManager::account = const_cast<Account *>(Account::getAnon());\n\n int generation = ++IrcManager::connectionGeneration;\n\n auto c = new IrcConnection();\n\n QObject::connect(c, &IrcConnection::messageReceived, &messageReceived);\n QObject::connect(c, &IrcConnection::privateMessageReceived,\n &privateMessageReceived);\n\n if (account->isAnon()) {\n \/\/ fetch ignored users\n QString username = account->getUsername();\n QString oauthClient = account->getOauthClient();\n QString oauthToken = account->getOauthToken();\n\n {\n QString nextLink = \"https:\/\/api.twitch.tv\/kraken\/users\/\" +\n username + \"\/blocks?limit=\" + 100 +\n \"&client_id=\" + oauthClient;\n\n QNetworkAccessManager *manager = new QNetworkAccessManager();\n QNetworkRequest req(QUrl(nextLink + \"&oauth_token=\" + oauthToken));\n QNetworkReply *reply = manager->get(req);\n\n QObject::connect(reply, &QNetworkReply::finished, [=] {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.clear();\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n QByteArray data = reply->readAll();\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n QJsonObject root = jsonDoc.object();\n\n \/\/ nextLink =\n \/\/ root.value(\"_links\").toObject().value(\"next\").toString();\n\n auto blocks = root.value(\"blocks\").toArray();\n\n IrcManager::twitchBlockedUsersMutex.lock();\n for (QJsonValue block : blocks) {\n QJsonObject user =\n block.toObject().value(\"user\").toObject();\n \/\/ display_name\n IrcManager::twitchBlockedUsers.insert(\n user.value(\"name\").toString().toLower(), true);\n }\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n manager->deleteLater();\n });\n }\n\n \/\/ fetch available twitch emtoes\n {\n QNetworkRequest req(QUrl(\"https:\/\/api.twitch.tv\/kraken\/users\/\" +\n username + \"\/emotes?oauth_token=\" +\n oauthToken + \"&client_id=\" + oauthClient));\n QNetworkReply *reply = IrcManager::accessManager.get(req);\n\n QObject::connect(reply, &QNetworkReply::finished, [=] {\n QByteArray data = reply->readAll();\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n QJsonObject root = jsonDoc.object();\n\n \/\/ nextLink =\n \/\/ root.value(\"_links\").toObject().value(\"next\").toString();\n\n auto blocks = root.value(\"blocks\").toArray();\n\n IrcManager::twitchBlockedUsersMutex.lock();\n for (QJsonValue block : blocks) {\n QJsonObject user =\n block.toObject().value(\"user\").toObject();\n \/\/ display_name\n IrcManager::twitchBlockedUsers.insert(\n user.value(\"name\").toString().toLower(), true);\n }\n IrcManager::twitchBlockedUsersMutex.unlock();\n });\n }\n }\n\n c->setHost(\"irc.chat.twitch.tv\");\n c->setPort(6667);\n\n c->setUserName(\"justinfan123\");\n c->setNickName(\"justinfan123\");\n c->setRealName(\"justinfan123\");\n\n c->sendCommand(IrcCommand::createCapability(\"REQ\", \"twitch.tv\/commands\"));\n c->sendCommand(IrcCommand::createCapability(\"REQ\", \"twitch.tv\/tags\"));\n\n QMutexLocker locker(&IrcManager::connectionMutex);\n\n if (generation == IrcManager::connectionGeneration) {\n c->moveToThread(QCoreApplication::instance()->thread());\n IrcManager::connection = std::shared_ptr<IrcConnection>(c);\n\n auto channels = Channels::getItems();\n\n for (auto &channel : channels) {\n c->sendRaw(\"JOIN #\" + channel.get()->getName());\n }\n\n c->open();\n } else {\n delete c;\n }\n}\n\nvoid\nIrcManager::disconnect()\n{\n IrcManager::connectionMutex.lock();\n\n auto c = IrcManager::connection;\n if (IrcManager::connection.get() != NULL) {\n IrcManager::connection = std::shared_ptr<IrcConnection>();\n }\n\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::send(QString raw)\n{\n IrcManager::connectionMutex.lock();\n IrcManager::connection->sendRaw(raw);\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::sendJoin(const QString &channel)\n{\n IrcManager::connectionMutex.lock();\n\n if (IrcManager::connection.get() != NULL) {\n IrcManager::connection.get()->sendRaw(\"JOIN #\" + channel);\n }\n\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::partChannel(const QString &channel)\n{\n IrcManager::connectionMutex.lock();\n\n if (IrcManager::connection.get() != NULL) {\n IrcManager::connection.get()->sendRaw(\"PART #\" + channel);\n }\n\n IrcManager::connectionMutex.unlock();\n}\n\nvoid\nIrcManager::messageReceived(IrcMessage *message)\n{\n \/\/ qInfo(message->command().toStdString().c_str());\n\n const QString &command = message->command();\n\n \/\/ if (command == \"CLEARCHAT\") {\n \/\/ message->\n \/\/ } else if (command == \"ROOMSTATE\") {\n \/\/ } else if (command == \"USERSTATE\") {\n \/\/ } else if (command == \"WHISPER\") {\n \/\/ } else if (command == \"USERNOTICE\") {\n \/\/ }\n}\n\nvoid\nIrcManager::privateMessageReceived(IrcPrivateMessage *message)\n{\n \/\/ qInfo(message->content().toStdString().c_str());\n\n auto c = Channels::getChannel(message->target().mid(1));\n\n if (c != NULL) {\n c->addMessage(std::shared_ptr<messages::Message>(\n new messages::Message(*message, *c)));\n }\n}\n\nbool\nIrcManager::isTwitchBlockedUser(QString const &username)\n{\n IrcManager::twitchBlockedUsersMutex.lock();\n\n auto iterator = IrcManager::twitchBlockedUsers.find(username);\n\n if (iterator == IrcManager::twitchBlockedUsers.end()) {\n IrcManager::twitchBlockedUsersMutex.unlock();\n return false;\n }\n\n IrcManager::twitchBlockedUsersMutex.unlock();\n return true;\n}\n\nbool\nIrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)\n{\n QUrl url(\"https:\/\/api.twitch.tv\/kraken\/users\/\" + account->getUsername() +\n \"\/blocks\/\" + username +\n \"?oauth_token=\" + account->getOauthToken() +\n \"&client_id=\" + account->getOauthClient());\n\n QNetworkRequest request(url);\n auto reply = IrcManager::accessManager.put(request, QByteArray());\n reply->waitForReadyRead(10000);\n\n if (reply->error() == QNetworkReply::NoError) {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.insert(username, true);\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n delete reply;\n return true;\n }\n\n errorMessage = \"Error while ignoring user \\\"\" + username +\n \"\\\": \" + reply->errorString();\n return false;\n}\n\nvoid\nIrcManager::addIgnoredUser(QString const &username)\n{\n QString errorMessage;\n if (!tryAddIgnoredUser(username, errorMessage)) {\n \/\/ TODO: Implement IrcManager::addIgnoredUser\n }\n}\n\nbool\nIrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)\n{\n QUrl url(\"https:\/\/api.twitch.tv\/kraken\/users\/\" + account->getUsername() +\n \"\/blocks\/\" + username +\n \"?oauth_token=\" + account->getOauthToken() +\n \"&client_id=\" + account->getOauthClient());\n\n QNetworkRequest request(url);\n auto reply = IrcManager::accessManager.deleteResource(request);\n reply->waitForReadyRead(10000);\n\n if (reply->error() == QNetworkReply::NoError) {\n IrcManager::twitchBlockedUsersMutex.lock();\n IrcManager::twitchBlockedUsers.remove(username);\n IrcManager::twitchBlockedUsersMutex.unlock();\n\n delete reply;\n return true;\n }\n\n errorMessage = \"Error while unignoring user \\\"\" + username +\n \"\\\": \" + reply->errorString();\n return false;\n}\n\nvoid\nIrcManager::removeIgnoredUser(QString const &username)\n{\n QString errorMessage;\n if (!tryRemoveIgnoredUser(username, errorMessage)) {\n \/\/ TODO: Implement IrcManager::removeIgnoredUser\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2018 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskOrbit.cpp\n *\/\n\n#include \"FlightTaskOrbit.hpp\"\n#include <mathlib\/mathlib.h>\n\nusing namespace matrix;\n\nFlightTaskOrbit::FlightTaskOrbit()\n{\n\t_sticks_data_required = false;\n}\n\nbool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command)\n{\n\tconst float &r = command.param3; \/\/ commanded radius\n\tconst float &v = command.param4; \/\/ commanded velocity\n\n\tif (setRadius(r) && setVelocity(v)) {\n\t\treturn FlightTaskManual::applyCommandParameters(command);\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::setRadius(const float r)\n{\n\tif (math::isInRange(r, radius_min, radius_max)) {\n\t\t\/\/ radius is more important than velocity for safety\n\t\tif (!checkAcceleration(r, _v, acceleration_max)) {\n\t\t\t_v = sqrtf(acceleration_max * r);\n\t\t}\n\n\t\t_r = r;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::setVelocity(const float v)\n{\n\tif (fabs(v) < velocity_max &&\n\t checkAcceleration(_r, v, acceleration_max)) {\n\t\t_v = v;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::checkAcceleration(float r, float v, float a)\n{\n\treturn v * v < a * r;\n}\n\nbool FlightTaskOrbit::activate()\n{\n\tbool ret = FlightTaskManual::activate();\n\t_r = 1.f;\n\t_v = 0.5f;\n\t_z = _position(2);\n\t_center = Vector2f(_position.data());\n\t_center(0) -= _r;\n\n\t\/\/ need a valid position and velocity\n\tret = ret && PX4_ISFINITE(_position(0))\n\t && PX4_ISFINITE(_position(1))\n\t && PX4_ISFINITE(_position(2))\n\t && PX4_ISFINITE(_velocity(0))\n\t && PX4_ISFINITE(_velocity(1))\n\t && PX4_ISFINITE(_velocity(2));\n\n\treturn ret;\n}\n\nbool FlightTaskOrbit::update()\n{\n\t\/\/ stick input adjusts parameters\n\tconst float r = _r + _sticks_expo(0) * _deltatime;\n\tconst float v = _v - _sticks_expo(1) * _deltatime;\n\t_z += _sticks_expo(2) * _deltatime;\n\n\tsetRadius(r);\n\tsetVelocity(v);\n\n\t_position_setpoint = Vector3f(NAN, NAN, _z);\n\n\t\/\/ xy velocity to go around in a circle\n\tVector2f center_to_position = Vector2f(_position.data()) - _center;\n\tVector2f velocity_xy = Vector2f(center_to_position(1), -center_to_position(0));\n\tvelocity_xy = velocity_xy.unit_or_zero();\n\tvelocity_xy *= _v;\n\n\t\/\/ xy velocity adjustment to stay on the radius distance\n\tvelocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero();\n\n\t_velocity_setpoint = Vector3f(velocity_xy(0), velocity_xy(1), 0.f);\n\n\t\/\/ make vehicle front always point towards the center\n\t_yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F;\n\treturn true;\n}\n<commit_msg>FlightTaskOrbit: improve yaw tracking with feed-forward<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2018 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskOrbit.cpp\n *\/\n\n#include \"FlightTaskOrbit.hpp\"\n#include <mathlib\/mathlib.h>\n\nusing namespace matrix;\n\nFlightTaskOrbit::FlightTaskOrbit()\n{\n\t_sticks_data_required = false;\n}\n\nbool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command)\n{\n\tconst float &r = command.param3; \/\/ commanded radius\n\tconst float &v = command.param4; \/\/ commanded velocity\n\n\tif (setRadius(r) && setVelocity(v)) {\n\t\treturn FlightTaskManual::applyCommandParameters(command);\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::setRadius(const float r)\n{\n\tif (math::isInRange(r, radius_min, radius_max)) {\n\t\t\/\/ radius is more important than velocity for safety\n\t\tif (!checkAcceleration(r, _v, acceleration_max)) {\n\t\t\t_v = sqrtf(acceleration_max * r);\n\t\t}\n\n\t\t_r = r;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::setVelocity(const float v)\n{\n\tif (fabs(v) < velocity_max &&\n\t checkAcceleration(_r, v, acceleration_max)) {\n\t\t_v = v;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool FlightTaskOrbit::checkAcceleration(float r, float v, float a)\n{\n\treturn v * v < a * r;\n}\n\nbool FlightTaskOrbit::activate()\n{\n\tbool ret = FlightTaskManual::activate();\n\t_r = 1.f;\n\t_v = 0.5f;\n\t_z = _position(2);\n\t_center = Vector2f(_position.data());\n\t_center(0) -= _r;\n\n\t\/\/ need a valid position and velocity\n\tret = ret && PX4_ISFINITE(_position(0))\n\t && PX4_ISFINITE(_position(1))\n\t && PX4_ISFINITE(_position(2))\n\t && PX4_ISFINITE(_velocity(0))\n\t && PX4_ISFINITE(_velocity(1))\n\t && PX4_ISFINITE(_velocity(2));\n\n\treturn ret;\n}\n\nbool FlightTaskOrbit::update()\n{\n\t\/\/ stick input adjusts parameters\n\tconst float r = _r + _sticks_expo(0) * _deltatime;\n\tconst float v = _v - _sticks_expo(1) * _deltatime;\n\t_z += _sticks_expo(2) * _deltatime;\n\n\tsetRadius(r);\n\tsetVelocity(v);\n\n\t_position_setpoint = Vector3f(NAN, NAN, _z);\n\n\t\/\/ xy velocity to go around in a circle\n\tVector2f center_to_position = Vector2f(_position.data()) - _center;\n\tVector2f velocity_xy = Vector2f(center_to_position(1), -center_to_position(0));\n\tvelocity_xy = velocity_xy.unit_or_zero();\n\tvelocity_xy *= _v;\n\n\t\/\/ xy velocity adjustment to stay on the radius distance\n\tvelocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero();\n\n\t_velocity_setpoint = Vector3f(velocity_xy(0), velocity_xy(1), 0.f);\n\n\t\/\/ make vehicle front always point towards the center\n\t_yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F;\n\t\/\/ yawspeed feed-forward because we know the necessary angular rate\n\t_yawspeed_setpoint = -_v \/ _r;\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the License);\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an AS IS BASIS, \/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\n#include \"src\/validator\/error.h\"\n#include \"src\/validator\/handlers\/simple_handler.h\"\n\nusing namespace std;\nusing namespace stoke;\nusing namespace x64asm;\n\nvoid SimpleHandler::add_all() {\n\n add_opcode({\"andb\", \"andw\", \"andl\", \"andq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a & b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a & b);\n });\n\n add_opcode({\"decb\", \"decw\", \"decl\", \"decq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n SymBitVector one = SymBitVector::constant(dst.size(), 1);\n\n ss.set(dst, a - one);\n ss.set(eflags_of, a[dst.size() - 1] &\n a[dst.size() - 2][0] == SymBitVector::constant(dst.size() - 1, 0));\n ss.set(eflags_af, a[3][0] == SymBitVector::constant(4, 0x0));\n ss.set_szp_flags(a - one, dst.size());\n\n });\n\n add_opcode({\"incb\", \"incw\", \"incl\", \"incq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n SymBitVector one = SymBitVector::constant(dst.size(), 1);\n\n ss.set(dst, a + one);\n ss.set(eflags_of, !a[dst.size() - 1] &\n a[dst.size()-2][0] == SymBitVector::constant(dst.size() - 1, -1));\n ss.set(eflags_af, a[3][0] == SymBitVector::constant(4, 0xf));\n ss.set_szp_flags(a + one, dst.size());\n\n });\n\n add_opcode({\"negb\", \"negw\", \"negl\", \"negq\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, -a);\n ss.set(eflags_cf, a != SymBitVector::constant(dst.size(), 0));\n ss.set(eflags_of, a[dst.size()-1] & (-a)[dst.size()-1]);\n ss.set(eflags_af, a[3] & (-a)[3]);\n ss.set_szp_flags(-a);\n });\n\n add_opcode({\"nop\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {});\n\n add_opcode({\"notb\", \"notw\", \"notl\", \"notq\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, !a);\n });\n\n add_opcode({\"orb\", \"orw\", \"orl\", \"orq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a | b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a | b);\n });\n\n add_opcode({\"testb\", \"testw\", \"testl\", \"testq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a & b);\n });\n\n add_opcode({\"xchgb\", \"xchgw\", \"xchgl\", \"xchgq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, b);\n ss.set(src, a);\n });\n\n add_opcode({\"xorb\", \"xorw\", \"xorl\", \"xorq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a ^ b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a ^ b);\n });\n\n\n\n}\n\nHandler::SupportLevel SimpleHandler::get_support(const x64asm::Instruction& instr) {\n\n auto opcode = get_opcode(instr);\n\n if(!operator_.count(opcode))\n return Handler::NONE;\n\n for(size_t i = 0; i < instr.arity(); ++i) {\n Operand o = instr.get_operand<Operand>(i);\n if(!o.is_gp_register() && !o.is_typical_memory() &&\n !o.is_sse_register() && !o.is_immediate())\n return Handler::NONE;\n }\n\n return (Handler::SupportLevel)(Handler::BASIC | Handler::CEG | Handler::ANALYSIS);\n\n}\n\nvoid SimpleHandler::build_circuit(const x64asm::Instruction& instr, SymState& state) {\n\n auto opcode = get_opcode(instr);\n\n error_ = \"\";\n if(!get_support(instr)) {\n error_ = \"No support for this instruction.\";\n return;\n }\n\n \/\/ Figure out the arguments\n Operand dst = instr.get_operand<Operand>(0);\n Operand src = instr.get_operand<Operand>(0);\n\n size_t arity = instr.arity();\n\n if(arity == 2) {\n src = instr.get_operand<Operand>(1);\n } else if (arity > 2) {\n throw VALIDATOR_ERROR(\"Only arity 0\/1\/2 instructions supported by SimpleHandler\");\n }\n\n \/\/ Run the real handler\n auto f = operator_[opcode];\n\n if(arity > 0)\n f(dst, src, state[dst], state[src], state);\n else\n f(dst, src, SymBitVector::constant(1, 0), SymBitVector::constant(1,0), state);\n\n}\n\nvoid SimpleHandler::add_opcode(vector<string> opcodes, BinaryOperator op) {\n for(auto it : opcodes) {\n operator_[it] = op;\n }\n}\n\n\n\n<commit_msg>implemented popcnt<commit_after>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the License);\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an AS IS BASIS, \/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\n#include \"src\/validator\/error.h\"\n#include \"src\/validator\/handlers\/simple_handler.h\"\n\nusing namespace std;\nusing namespace stoke;\nusing namespace x64asm;\n\nvoid SimpleHandler::add_all() {\n\n add_opcode({\"andb\", \"andw\", \"andl\", \"andq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a & b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a & b);\n });\n\n add_opcode({\"decb\", \"decw\", \"decl\", \"decq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n SymBitVector one = SymBitVector::constant(dst.size(), 1);\n\n ss.set(dst, a - one);\n ss.set(eflags_of, a[dst.size() - 1] &\n a[dst.size() - 2][0] == SymBitVector::constant(dst.size() - 1, 0));\n ss.set(eflags_af, a[3][0] == SymBitVector::constant(4, 0x0));\n ss.set_szp_flags(a - one, dst.size());\n\n });\n\n add_opcode({\"incb\", \"incw\", \"incl\", \"incq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n SymBitVector one = SymBitVector::constant(dst.size(), 1);\n\n ss.set(dst, a + one);\n ss.set(eflags_of, !a[dst.size() - 1] &\n a[dst.size()-2][0] == SymBitVector::constant(dst.size() - 1, -1));\n ss.set(eflags_af, a[3][0] == SymBitVector::constant(4, 0xf));\n ss.set_szp_flags(a + one, dst.size());\n\n });\n\n add_opcode({\"negb\", \"negw\", \"negl\", \"negq\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, -a);\n ss.set(eflags_cf, a != SymBitVector::constant(dst.size(), 0));\n ss.set(eflags_of, a[dst.size()-1] & (-a)[dst.size()-1]);\n ss.set(eflags_af, a[3] & (-a)[3]);\n ss.set_szp_flags(-a);\n });\n\n add_opcode({\"nop\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {});\n\n add_opcode({\"notb\", \"notw\", \"notl\", \"notq\"},\n [] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, !a);\n });\n\n add_opcode({\"orb\", \"orw\", \"orl\", \"orq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a | b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a | b);\n });\n\n add_opcode({\"popcntw\", \"popcntl\", \"popcntq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n\n std::function<SymBitVector (SymBitVector, uint16_t)> helper =\n [&] (SymBitVector src, uint16_t size) {\n if(size == 1) {\n return src;\n } else {\n uint16_t half = size\/2;\n SymBitVector zeros = SymBitVector::constant(half, 0);\n SymBitVector left = src[size-1][half];\n SymBitVector right = src[half-1][0];\n return (zeros || helper(left, half)) + (zeros || helper(right, half));\n }\n };\n\n uint16_t size = dst.size();\n\n ss.set(dst, helper(b, size));\n ss.set(eflags_zf, b == SymBitVector::constant(size, 0));\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_pf, SymBool::_false());\n ss.set(eflags_sf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::_false());\n });\n\n add_opcode({\"testb\", \"testw\", \"testl\", \"testq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a & b);\n });\n\n add_opcode({\"xchgb\", \"xchgw\", \"xchgl\", \"xchgq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n ss.set(dst, b);\n ss.set(src, a);\n });\n\n add_opcode({\"xorb\", \"xorw\", \"xorl\", \"xorq\"},\n [this] (Operand dst, Operand src, SymBitVector a, SymBitVector b, SymState& ss) {\n if(src.size() < dst.size())\n b = b.extend(dst.size());\n\n ss.set(dst, a ^ b);\n ss.set(eflags_cf, SymBool::_false());\n ss.set(eflags_of, SymBool::_false());\n ss.set(eflags_af, SymBool::var(\"AF_\" + to_string(temp())));\n ss.set_szp_flags(a ^ b);\n });\n\n\n\n}\n\nHandler::SupportLevel SimpleHandler::get_support(const x64asm::Instruction& instr) {\n\n auto opcode = get_opcode(instr);\n\n if(!operator_.count(opcode))\n return Handler::NONE;\n\n for(size_t i = 0; i < instr.arity(); ++i) {\n Operand o = instr.get_operand<Operand>(i);\n if(!o.is_gp_register() && !o.is_typical_memory() &&\n !o.is_sse_register() && !o.is_immediate())\n return Handler::NONE;\n }\n\n return (Handler::SupportLevel)(Handler::BASIC | Handler::CEG | Handler::ANALYSIS);\n\n}\n\nvoid SimpleHandler::build_circuit(const x64asm::Instruction& instr, SymState& state) {\n\n auto opcode = get_opcode(instr);\n\n error_ = \"\";\n if(!get_support(instr)) {\n error_ = \"No support for this instruction.\";\n return;\n }\n\n \/\/ Figure out the arguments\n Operand dst = instr.get_operand<Operand>(0);\n Operand src = instr.get_operand<Operand>(0);\n\n size_t arity = instr.arity();\n\n if(arity == 2) {\n src = instr.get_operand<Operand>(1);\n } else if (arity > 2) {\n throw VALIDATOR_ERROR(\"Only arity 0\/1\/2 instructions supported by SimpleHandler\");\n }\n\n \/\/ Run the real handler\n auto f = operator_[opcode];\n\n if(arity > 0)\n f(dst, src, state[dst], state[src], state);\n else\n f(dst, src, SymBitVector::constant(1, 0), SymBitVector::constant(1,0), state);\n\n}\n\nvoid SimpleHandler::add_opcode(vector<string> opcodes, BinaryOperator op) {\n for(auto it : opcodes) {\n operator_[it] = op;\n }\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ gltut-glfw\n\/\/\n\/\/ Copyright (C) 2010-2012 by Jason L. McKesson\n\/\/ Xcode and glfw adaptation: Ricardo Sánchez-Sáez.\n\/\/\n\/\/ This file is licensed under the MIT License.\n\/\/\n\n#include <iostream>\n\n#include \"GLFW\/glfw3.h\"\n\n#include \"Scene.h\"\n\nconst char* gltutglfwName = \"gltut-glfw\";\n\nstatic void onError(int error, const char* description)\n{\n std::cout << \"Error: \" << description << std::endl;\n}\n\nGLFWwindow* createWindow()\n{\n if (!glfwInit())\n return NULL;\n \n glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );\n glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 2 );\n glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );\n glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );\n \n return glfwCreateWindow(1024, 640, gltutglfwName, NULL, NULL);\n}\n\nScene scene = Scene();\n\nvoid onFramebufferResize(GLFWwindow* window, int width, int height)\n{\n scene.reshape(width, height);\n glfwSwapBuffers(window);\n\n}\n\nint main(int argc, const char * argv[])\n{\n glfwSetErrorCallback(onError);\n \n GLFWwindow* window = createWindow();\n if (!window)\n return 0;\n\n glfwMakeContextCurrent(window);\n\n scene.init();\n \n int windowWidth = 0;\n int windowHeight = 0;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n onFramebufferResize(window, windowWidth, windowHeight);\n glfwSetFramebufferSizeCallback(window, &onFramebufferResize);\n \n while (!glfwWindowShouldClose(window))\n {\n scene.draw();\n \n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n \n glfwTerminate();\n \n return 0;\n}\n\n<commit_msg>Fixed window size being used as framebuffer size.<commit_after>\/\/\n\/\/ main.cpp\n\/\/ gltut-glfw\n\/\/\n\/\/ Copyright (C) 2010-2012 by Jason L. McKesson\n\/\/ Xcode and glfw adaptation: Ricardo Sánchez-Sáez.\n\/\/\n\/\/ This file is licensed under the MIT License.\n\/\/\n\n#include <iostream>\n\n#include \"GLFW\/glfw3.h\"\n\n#include \"Scene.h\"\n\nconst char* gltutglfwName = \"gltut-glfw\";\n\nstatic void onError(int error, const char* description)\n{\n std::cout << \"Error: \" << description << std::endl;\n}\n\nGLFWwindow* createWindow()\n{\n if (!glfwInit())\n return NULL;\n \n glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );\n glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 2 );\n glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );\n glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );\n \n return glfwCreateWindow(1024, 640, gltutglfwName, NULL, NULL);\n}\n\nScene scene = Scene();\n\nvoid onFramebufferResize(GLFWwindow* window, int width, int height)\n{\n scene.reshape(width, height);\n glfwSwapBuffers(window);\n\n}\n\nint main(int argc, const char * argv[])\n{\n glfwSetErrorCallback(onError);\n \n GLFWwindow* window = createWindow();\n if (!window)\n return 0;\n\n glfwMakeContextCurrent(window);\n\n scene.init();\n \n int windowWidth = 0;\n int windowHeight = 0;\n glfwGetFramebufferSize(window, &windowWidth, &windowHeight);\n onFramebufferResize(window, windowWidth, windowHeight);\n glfwSetFramebufferSizeCallback(window, &onFramebufferResize);\n \n while (!glfwWindowShouldClose(window))\n {\n scene.draw();\n \n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n \n glfwTerminate();\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Title: Address scanner\n\n Copyright (c) 2006-8, 2012 David C.J. Matthews\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n*\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#elif defined(_WIN32)\n#include \"winconfig.h\"\n#else\n#error \"No configuration file\"\n#endif\n\n#ifdef HAVE_ASSERT_H\n#include <assert.h>\n#define ASSERT(x) assert(x)\n#else\n#define ASSERT(x) 0\n#endif\n\n#include <new>\n\n#include \"globals.h\"\n#include \"scanaddrs.h\"\n#include \"machine_dep.h\"\n#include \"diagnostics.h\"\n#include \"memmgr.h\"\n\n\/\/ Process the value at a given location and update it as necessary.\nPOLYUNSIGNED ScanAddress::ScanAddressAt(PolyWord *pt)\n{\n PolyWord val = *pt;\n PolyWord newVal = val;\n if (IS_INT(val) || val == PolyWord::FromUnsigned(0))\n {\n \/\/ We can get zeros in the constant area if we garbage collect\n \/\/ while compiling some code. *\/\n }\n else\n {\n ASSERT(OBJ_IS_DATAPTR(val));\n \/\/ Any sort of address\n newVal = ScanObjectAddress(val.AsObjPtr());\n }\n if (newVal != val) \/\/ Only update if we need to.\n *pt = newVal;\n return 0;\n}\n\n\/\/ General purpose object processor, Processes all the addresses in an object.\n\/\/ Handles the various kinds of object that may contain addresses.\nvoid ScanAddress::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)\n{\n do\n {\n ASSERT (OBJ_IS_LENGTH(lengthWord));\n \n if (OBJ_IS_BYTE_OBJECT(lengthWord))\n return; \/* Nothing more to do *\/\n \n POLYUNSIGNED length = OBJ_OBJECT_LENGTH(lengthWord);\n PolyWord *baseAddr = (PolyWord*)obj;\n \n if (OBJ_IS_CODE_OBJECT(lengthWord))\n {\n \/\/ Scan constants within the code.\n machineDependent->ScanConstantsWithinCode(obj, obj, length, this);\n \n \/\/ Skip to the constants and get ready to scan them.\n obj->GetConstSegmentForCode(length, baseAddr, length);\n\n } \/\/ else it's a normal object,\n\n PolyWord *endWord = baseAddr + length;\n\n \/\/ We want to minimise the actual recursion we perform so we try to\n \/\/ use tail recursion if we can. We first scan from the end and\n \/\/ remove any words that don't need recursion.\n POLYUNSIGNED lastLengthWord = 0;\n while (endWord != baseAddr)\n {\n PolyWord wordAt = endWord[-1];\n if (IS_INT(wordAt) || wordAt == PolyWord::FromUnsigned(0))\n endWord--; \/\/ Don't need to look at this.\n else if ((lastLengthWord = ScanAddressAt(endWord-1)) != 0)\n \/\/ We need to process this one\n break;\n else endWord--; \/\/ We're not interested in this.\n }\n\n if (endWord == baseAddr)\n return; \/\/ We've done everything.\n\n \/\/ There is at least one word that needs to be processed, the\n \/\/ one at endWord-1.\n \/\/ Now process from the beginning forward to see if there are\n \/\/ any words before this that need to be handled. This way we are more\n \/\/ likely to handle the head of a list by recursion and the\n \/\/ tail by looping (tail recursion).\n while (baseAddr < endWord-1)\n {\n PolyWord wordAt = *baseAddr;\n if (IS_INT(wordAt) || wordAt == PolyWord::FromUnsigned(0))\n baseAddr++; \/\/ Don't need to look at this.\n else\n {\n POLYUNSIGNED lengthWord = ScanAddressAt(baseAddr);\n if (lengthWord != 0)\n {\n wordAt = *baseAddr; \/\/ Reload because it may have been side-effected\n \/\/ We really have to process this recursively.\n ASSERT(wordAt.IsDataPtr());\n ScanAddressesInObject(wordAt.AsObjPtr(), lengthWord);\n baseAddr++;\n }\n else baseAddr++;\n }\n }\n\n \/\/ Finally process the last word we found that has to be processed.\n \/\/ Do this by looping rather than recursion.\n PolyWord wordAt = *baseAddr; \/\/ Last word to do.\n \/\/ This must be an address \n ASSERT(wordAt.IsDataPtr());\n obj = wordAt.AsObjPtr();\n\n lengthWord = lastLengthWord;\n\n } while(1);\n}\n\nvoid ScanAddress::ScanAddressesInRegion(PolyWord *region, PolyWord *end)\n{\n PolyWord *pt = region;\n while (pt < end)\n {\n pt++; \/\/ Skip length word.\n \/\/ pt actually points AT the object here.\n PolyObject *obj = (PolyObject*)pt;\n if (obj->ContainsForwardingPtr()) \/* skip over moved object *\/\n {\n \/\/ We can now get multiple forwarding pointers as a result\n \/\/ of applying ShareData repeatedly. Perhaps we should\n \/\/ turn the forwarding pointers back into normal words in\n \/\/ an extra pass.\n obj = obj->FollowForwardingChain();\n ASSERT(obj->ContainsNormalLengthWord());\n pt += obj->Length();\n }\n else\n {\n ASSERT(obj->ContainsNormalLengthWord());\n POLYUNSIGNED length = obj->Length();\n if (pt+length > end)\n Crash(\"Malformed object at %p - length %lu\\n\", pt, length);\n if (length != 0)\n ScanAddressesInObject(obj);\n pt += length;\n }\n }\n}\n\n\/\/ Extract a constant from the code.\nPolyWord ScanAddress::GetConstantValue(byte *addressOfConstant, ScanRelocationKind code)\n{\n switch (code)\n {\n case PROCESS_RELOC_DIRECT: \/\/ 32 or 64 bit address of target\n {\n POLYUNSIGNED valu;\n unsigned i;\n byte *pt = addressOfConstant;\n if (pt[3] & 0x80) valu = 0-1; else valu = 0;\n for (i = sizeof(PolyWord); i > 0; i--)\n valu = (valu << 8) | pt[i-1];\n\n return PolyWord::FromUnsigned(valu);\n }\n case PROCESS_RELOC_I386RELATIVE: \/\/ 32 bit relative address\n {\n POLYSIGNED disp;\n byte *pt = addressOfConstant;\n \/\/ Get the displacement. This is signed.\n if (pt[3] & 0x80) disp = -1; else disp = 0; \/\/ Set the sign just in case.\n for(unsigned i = 4; i > 0; i--) disp = (disp << 8) | pt[i-1];\n\n byte *absAddr = pt + disp + 4; \/\/ The address is relative to AFTER the constant\n\n return PolyWord::FromCodePtr(absAddr);\n }\n default:\n ASSERT(false);\n return TAGGED(0);\n }\n}\n\n\/\/ Store a constant value. Also used with a patch table when importing a saved heap which has\n\/\/ been exported using the C exporter.\nvoid ScanAddress::SetConstantValue(byte *addressOfConstant, PolyWord p, ScanRelocationKind code)\n{\n\n switch (code)\n {\n case PROCESS_RELOC_DIRECT: \/\/ 32 or 64 bit address of target\n {\n POLYUNSIGNED valu = p.AsUnsigned();\n for (unsigned i = 0; i < sizeof(PolyWord); i++)\n {\n addressOfConstant[i] = (byte)(valu & 255); \n valu >>= 8;\n }\n }\n break;\n case PROCESS_RELOC_I386RELATIVE: \/\/ 32 bit relative address\n {\n POLYSIGNED newDisp = p.AsCodePtr() - addressOfConstant - 4;\n#if (SIZEOF_VOIDP != 4)\n ASSERT(newDisp < 0x80000000 && newDisp >= -(POLYSIGNED)0x80000000);\n#endif\n for (unsigned i = 0; i < 4; i++) {\n addressOfConstant[i] = (byte)(newDisp & 0xff);\n newDisp >>= 8;\n }\n }\n break;\n }\n}\n\n\/\/ The default action is to call the DEFAULT ScanAddressAt NOT the virtual which means that it calls\n\/\/ ScanObjectAddress for the base address of the object referred to.\nvoid ScanAddress::ScanConstant(PolyObject *base, byte *addressOfConstant, ScanRelocationKind code)\n{\n PolyWord p = GetConstantValue(addressOfConstant, code);\n\n if (! IS_INT(p))\n {\n PolyWord oldValue = p;\n ScanAddress::ScanAddressAt(&p);\n if (p != oldValue) \/\/ Update it if it has changed.\n SetConstantValue(addressOfConstant, p, code);\n }\n}\n\nvoid ScanAddress::ScanRuntimeWord(PolyWord *w)\n{\n if (w->IsTagged()) {} \/\/ Don't need to do anything\n else {\n ASSERT(w->IsDataPtr());\n *w = ScanObjectAddress(w->AsObjPtr()); \n }\n}\n\n\/\/ This gets called in two circumstances. It may be called for the roots\n\/\/ in which case the stack will be empty and we want to process it completely\n\/\/ or it is called for a constant address in which case it will have been\n\/\/ called from RecursiveScan::ScanAddressesInObject and that can process\n\/\/ any addresses.\nPolyObject *RecursiveScan::ScanObjectAddress(PolyObject *obj)\n{\n PolyWord pWord = obj;\n \/\/ Test to see if this needs to be scanned.\n \/\/ It may update the word.\n bool test = TestForScan(&pWord);\n obj = pWord.AsObjPtr();\n\n if (test)\n {\n MarkAsScanning(obj);\n if (obj->IsByteObject())\n Completed(obj); \/\/ Don't need to put it on the stack\n \/\/ If we already have something on the stack we must being called\n \/\/ recursively to process a constant in a code segment. Just push\n \/\/ it on the stack and let the caller deal with it.\n else if (StackIsEmpty())\n RecursiveScan::ScanAddressesInObject(obj, obj->LengthWord());\n else\n PushToStack(obj, (PolyWord*)obj);\n }\n\n return obj;\n}\n\n\/\/ This is called via ScanAddressesInRegion to process the permanent mutables. It is\n\/\/ also called from ScanObjectAddress to process root addresses.\n\/\/ It processes all the addresses reachable from the object.\nvoid RecursiveScan::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)\n{\n if (OBJ_IS_BYTE_OBJECT(lengthWord))\n return; \/\/ Ignore byte cells and don't call Completed on them\n\n PolyWord *baseAddr = (PolyWord*)obj;\n\n while (true)\n {\n ASSERT (OBJ_IS_LENGTH(lengthWord));\n\n \/\/ Get the length and base address. N.B. If this is a code segment\n \/\/ these will be side-effected by GetConstSegmentForCode.\n POLYUNSIGNED length = OBJ_OBJECT_LENGTH(lengthWord);\n\n if (OBJ_IS_CODE_OBJECT(lengthWord))\n {\n \/\/ It's better to process the whole code object in one go.\n ScanAddress::ScanAddressesInObject(obj, lengthWord);\n length = 0; \/\/ Finished\n }\n\n \/\/ else it's a normal object,\n\n \/\/ If there are only two addresses in this cell that need to be\n \/\/ followed we follow them immediately and treat this cell as done.\n \/\/ If there are more than two we push the address of this cell on\n \/\/ the stack, follow the first address and then rescan it. That way\n \/\/ list cells are processed once only but we don't overflow the\n \/\/ stack by pushing all the addresses in a very large vector.\n PolyWord *endWord = (PolyWord*)obj + length;\n PolyObject *firstWord = 0;\n PolyObject *secondWord = 0;\n\n while (baseAddr != endWord)\n {\n PolyWord wordAt = *baseAddr;\n\n if (wordAt.IsDataPtr() && wordAt != PolyWord::FromUnsigned(0))\n {\n \/\/ Normal address. We can have words of all zeros at least in the\n \/\/ situation where we have a partially constructed code segment where\n \/\/ the constants at the end of the code have not yet been filled in.\n if (TestForScan(baseAddr)) \/\/ Test value at baseAddr (may side-effect it)\n {\n PolyObject *wObj = (*baseAddr).AsObjPtr();\n if (wObj->IsByteObject())\n {\n \/\/ Can do this now - don't need to push it\n MarkAsScanning(wObj);\n Completed(wObj);\n }\n else if (firstWord == 0)\n {\n firstWord = wObj;\n \/\/ We mark the word immediately. We can have\n \/\/ two words in an object that are the same\n \/\/ and we don't want to process it again.\n MarkAsScanning(firstWord);\n }\n else if (secondWord == 0)\n secondWord = wObj;\n else break; \/\/ More than two words.\n }\n }\n baseAddr++;\n }\n\n if (baseAddr == endWord)\n {\n \/\/ We have done everything except possibly firstWord and secondWord.\n Completed(obj);\n if (secondWord != 0)\n {\n MarkAsScanning(secondWord);\n \/\/ Put this on the stack. If this is a list node we will be\n \/\/ pushing the tail.\n PushToStack(secondWord, (PolyWord*)secondWord);\n }\n }\n else \/\/ Put this back on the stack while we process the first word\n PushToStack(obj, baseAddr);\n\n if (firstWord != 0)\n {\n \/\/ Process it immediately.\n obj = firstWord;\n baseAddr = (PolyWord*)obj;\n }\n else if (StackIsEmpty())\n return;\n else\n PopFromStack(obj, baseAddr);\n\n lengthWord = obj->LengthWord();\n }\n}\n\n\/\/ The stack is allocated as a series of blocks chained together.\n#define RSTACK_SEGMENT_SIZE 1000\n\nclass RScanStack {\npublic:\n RScanStack(): nextStack(0), lastStack(0), sp(0) {}\n ~RScanStack() { delete(nextStack); }\n\n RScanStack *nextStack;\n RScanStack *lastStack;\n unsigned sp;\n struct { PolyObject *obj; PolyWord *base; } stack[RSTACK_SEGMENT_SIZE];\n};\n\nRecursiveScanWithStack::~RecursiveScanWithStack()\n{\n delete(stack);\n}\n\nbool RecursiveScanWithStack::StackIsEmpty(void)\n{\n return stack == 0 || (stack->sp == 0 && stack->lastStack == 0);\n}\n\nvoid RecursiveScanWithStack::PushToStack(PolyObject *obj, PolyWord *base)\n{\n if (stack == 0 || stack->sp == RSTACK_SEGMENT_SIZE)\n {\n if (stack != 0 && stack->nextStack != 0)\n stack = stack->nextStack;\n else\n {\n \/\/ Need a new segment\n try {\n RScanStack *s = new RScanStack;\n s->lastStack = stack;\n if (stack != 0)\n stack->nextStack = s;\n stack = s;\n }\n catch (std::bad_alloc &) {\n StackOverflow();\n return;\n }\n }\n }\n stack->stack[stack->sp].obj = obj;\n stack->stack[stack->sp].base = base;\n stack->sp++;\n}\n\nvoid RecursiveScanWithStack::PopFromStack(PolyObject *&obj, PolyWord *&base)\n{\n if (stack->sp == 0)\n {\n \/\/ Chain to the previous stack if any\n ASSERT(stack->lastStack != 0);\n \/\/ Before we do, delete any further one to free some memory\n delete(stack->nextStack);\n stack->nextStack = 0;\n stack = stack->lastStack;\n ASSERT(stack->sp == RSTACK_SEGMENT_SIZE);\n }\n --stack->sp;\n obj = stack->stack[stack->sp].obj;\n base = stack->stack[stack->sp].base;\n}\n<commit_msg>Fix bug in last commit to GC sharer. This was meant to avoid rescanning large vectors from the start but had a bug that meant that it omitted some words from the scan.<commit_after>\/*\n Title: Address scanner\n\n Copyright (c) 2006-8, 2012 David C.J. Matthews\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n*\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#elif defined(_WIN32)\n#include \"winconfig.h\"\n#else\n#error \"No configuration file\"\n#endif\n\n#ifdef HAVE_ASSERT_H\n#include <assert.h>\n#define ASSERT(x) assert(x)\n#else\n#define ASSERT(x) 0\n#endif\n\n#include <new>\n\n#include \"globals.h\"\n#include \"scanaddrs.h\"\n#include \"machine_dep.h\"\n#include \"diagnostics.h\"\n#include \"memmgr.h\"\n\n\/\/ Process the value at a given location and update it as necessary.\nPOLYUNSIGNED ScanAddress::ScanAddressAt(PolyWord *pt)\n{\n PolyWord val = *pt;\n PolyWord newVal = val;\n if (IS_INT(val) || val == PolyWord::FromUnsigned(0))\n {\n \/\/ We can get zeros in the constant area if we garbage collect\n \/\/ while compiling some code. *\/\n }\n else\n {\n ASSERT(OBJ_IS_DATAPTR(val));\n \/\/ Any sort of address\n newVal = ScanObjectAddress(val.AsObjPtr());\n }\n if (newVal != val) \/\/ Only update if we need to.\n *pt = newVal;\n return 0;\n}\n\n\/\/ General purpose object processor, Processes all the addresses in an object.\n\/\/ Handles the various kinds of object that may contain addresses.\nvoid ScanAddress::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)\n{\n do\n {\n ASSERT (OBJ_IS_LENGTH(lengthWord));\n \n if (OBJ_IS_BYTE_OBJECT(lengthWord))\n return; \/* Nothing more to do *\/\n \n POLYUNSIGNED length = OBJ_OBJECT_LENGTH(lengthWord);\n PolyWord *baseAddr = (PolyWord*)obj;\n \n if (OBJ_IS_CODE_OBJECT(lengthWord))\n {\n \/\/ Scan constants within the code.\n machineDependent->ScanConstantsWithinCode(obj, obj, length, this);\n \n \/\/ Skip to the constants and get ready to scan them.\n obj->GetConstSegmentForCode(length, baseAddr, length);\n\n } \/\/ else it's a normal object,\n\n PolyWord *endWord = baseAddr + length;\n\n \/\/ We want to minimise the actual recursion we perform so we try to\n \/\/ use tail recursion if we can. We first scan from the end and\n \/\/ remove any words that don't need recursion.\n POLYUNSIGNED lastLengthWord = 0;\n while (endWord != baseAddr)\n {\n PolyWord wordAt = endWord[-1];\n if (IS_INT(wordAt) || wordAt == PolyWord::FromUnsigned(0))\n endWord--; \/\/ Don't need to look at this.\n else if ((lastLengthWord = ScanAddressAt(endWord-1)) != 0)\n \/\/ We need to process this one\n break;\n else endWord--; \/\/ We're not interested in this.\n }\n\n if (endWord == baseAddr)\n return; \/\/ We've done everything.\n\n \/\/ There is at least one word that needs to be processed, the\n \/\/ one at endWord-1.\n \/\/ Now process from the beginning forward to see if there are\n \/\/ any words before this that need to be handled. This way we are more\n \/\/ likely to handle the head of a list by recursion and the\n \/\/ tail by looping (tail recursion).\n while (baseAddr < endWord-1)\n {\n PolyWord wordAt = *baseAddr;\n if (IS_INT(wordAt) || wordAt == PolyWord::FromUnsigned(0))\n baseAddr++; \/\/ Don't need to look at this.\n else\n {\n POLYUNSIGNED lengthWord = ScanAddressAt(baseAddr);\n if (lengthWord != 0)\n {\n wordAt = *baseAddr; \/\/ Reload because it may have been side-effected\n \/\/ We really have to process this recursively.\n ASSERT(wordAt.IsDataPtr());\n ScanAddressesInObject(wordAt.AsObjPtr(), lengthWord);\n baseAddr++;\n }\n else baseAddr++;\n }\n }\n\n \/\/ Finally process the last word we found that has to be processed.\n \/\/ Do this by looping rather than recursion.\n PolyWord wordAt = *baseAddr; \/\/ Last word to do.\n \/\/ This must be an address \n ASSERT(wordAt.IsDataPtr());\n obj = wordAt.AsObjPtr();\n\n lengthWord = lastLengthWord;\n\n } while(1);\n}\n\nvoid ScanAddress::ScanAddressesInRegion(PolyWord *region, PolyWord *end)\n{\n PolyWord *pt = region;\n while (pt < end)\n {\n pt++; \/\/ Skip length word.\n \/\/ pt actually points AT the object here.\n PolyObject *obj = (PolyObject*)pt;\n if (obj->ContainsForwardingPtr()) \/* skip over moved object *\/\n {\n \/\/ We can now get multiple forwarding pointers as a result\n \/\/ of applying ShareData repeatedly. Perhaps we should\n \/\/ turn the forwarding pointers back into normal words in\n \/\/ an extra pass.\n obj = obj->FollowForwardingChain();\n ASSERT(obj->ContainsNormalLengthWord());\n pt += obj->Length();\n }\n else\n {\n ASSERT(obj->ContainsNormalLengthWord());\n POLYUNSIGNED length = obj->Length();\n if (pt+length > end)\n Crash(\"Malformed object at %p - length %lu\\n\", pt, length);\n if (length != 0)\n ScanAddressesInObject(obj);\n pt += length;\n }\n }\n}\n\n\/\/ Extract a constant from the code.\nPolyWord ScanAddress::GetConstantValue(byte *addressOfConstant, ScanRelocationKind code)\n{\n switch (code)\n {\n case PROCESS_RELOC_DIRECT: \/\/ 32 or 64 bit address of target\n {\n POLYUNSIGNED valu;\n unsigned i;\n byte *pt = addressOfConstant;\n if (pt[3] & 0x80) valu = 0-1; else valu = 0;\n for (i = sizeof(PolyWord); i > 0; i--)\n valu = (valu << 8) | pt[i-1];\n\n return PolyWord::FromUnsigned(valu);\n }\n case PROCESS_RELOC_I386RELATIVE: \/\/ 32 bit relative address\n {\n POLYSIGNED disp;\n byte *pt = addressOfConstant;\n \/\/ Get the displacement. This is signed.\n if (pt[3] & 0x80) disp = -1; else disp = 0; \/\/ Set the sign just in case.\n for(unsigned i = 4; i > 0; i--) disp = (disp << 8) | pt[i-1];\n\n byte *absAddr = pt + disp + 4; \/\/ The address is relative to AFTER the constant\n\n return PolyWord::FromCodePtr(absAddr);\n }\n default:\n ASSERT(false);\n return TAGGED(0);\n }\n}\n\n\/\/ Store a constant value. Also used with a patch table when importing a saved heap which has\n\/\/ been exported using the C exporter.\nvoid ScanAddress::SetConstantValue(byte *addressOfConstant, PolyWord p, ScanRelocationKind code)\n{\n\n switch (code)\n {\n case PROCESS_RELOC_DIRECT: \/\/ 32 or 64 bit address of target\n {\n POLYUNSIGNED valu = p.AsUnsigned();\n for (unsigned i = 0; i < sizeof(PolyWord); i++)\n {\n addressOfConstant[i] = (byte)(valu & 255); \n valu >>= 8;\n }\n }\n break;\n case PROCESS_RELOC_I386RELATIVE: \/\/ 32 bit relative address\n {\n POLYSIGNED newDisp = p.AsCodePtr() - addressOfConstant - 4;\n#if (SIZEOF_VOIDP != 4)\n ASSERT(newDisp < 0x80000000 && newDisp >= -(POLYSIGNED)0x80000000);\n#endif\n for (unsigned i = 0; i < 4; i++) {\n addressOfConstant[i] = (byte)(newDisp & 0xff);\n newDisp >>= 8;\n }\n }\n break;\n }\n}\n\n\/\/ The default action is to call the DEFAULT ScanAddressAt NOT the virtual which means that it calls\n\/\/ ScanObjectAddress for the base address of the object referred to.\nvoid ScanAddress::ScanConstant(PolyObject *base, byte *addressOfConstant, ScanRelocationKind code)\n{\n PolyWord p = GetConstantValue(addressOfConstant, code);\n\n if (! IS_INT(p))\n {\n PolyWord oldValue = p;\n ScanAddress::ScanAddressAt(&p);\n if (p != oldValue) \/\/ Update it if it has changed.\n SetConstantValue(addressOfConstant, p, code);\n }\n}\n\nvoid ScanAddress::ScanRuntimeWord(PolyWord *w)\n{\n if (w->IsTagged()) {} \/\/ Don't need to do anything\n else {\n ASSERT(w->IsDataPtr());\n *w = ScanObjectAddress(w->AsObjPtr()); \n }\n}\n\n\/\/ This gets called in two circumstances. It may be called for the roots\n\/\/ in which case the stack will be empty and we want to process it completely\n\/\/ or it is called for a constant address in which case it will have been\n\/\/ called from RecursiveScan::ScanAddressesInObject and that can process\n\/\/ any addresses.\nPolyObject *RecursiveScan::ScanObjectAddress(PolyObject *obj)\n{\n PolyWord pWord = obj;\n \/\/ Test to see if this needs to be scanned.\n \/\/ It may update the word.\n bool test = TestForScan(&pWord);\n obj = pWord.AsObjPtr();\n\n if (test)\n {\n MarkAsScanning(obj);\n if (obj->IsByteObject())\n Completed(obj); \/\/ Don't need to put it on the stack\n \/\/ If we already have something on the stack we must being called\n \/\/ recursively to process a constant in a code segment. Just push\n \/\/ it on the stack and let the caller deal with it.\n else if (StackIsEmpty())\n RecursiveScan::ScanAddressesInObject(obj, obj->LengthWord());\n else\n PushToStack(obj, (PolyWord*)obj);\n }\n\n return obj;\n}\n\n\/\/ This is called via ScanAddressesInRegion to process the permanent mutables. It is\n\/\/ also called from ScanObjectAddress to process root addresses.\n\/\/ It processes all the addresses reachable from the object.\nvoid RecursiveScan::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord)\n{\n if (OBJ_IS_BYTE_OBJECT(lengthWord))\n return; \/\/ Ignore byte cells and don't call Completed on them\n\n PolyWord *baseAddr = (PolyWord*)obj;\n\n while (true)\n {\n ASSERT (OBJ_IS_LENGTH(lengthWord));\n\n \/\/ Get the length and base address. N.B. If this is a code segment\n \/\/ these will be side-effected by GetConstSegmentForCode.\n POLYUNSIGNED length = OBJ_OBJECT_LENGTH(lengthWord);\n\n if (OBJ_IS_CODE_OBJECT(lengthWord))\n {\n \/\/ It's better to process the whole code object in one go.\n ScanAddress::ScanAddressesInObject(obj, lengthWord);\n length = 0; \/\/ Finished\n }\n\n \/\/ else it's a normal object,\n\n \/\/ If there are only two addresses in this cell that need to be\n \/\/ followed we follow them immediately and treat this cell as done.\n \/\/ If there are more than two we push the address of this cell on\n \/\/ the stack, follow the first address and then rescan it. That way\n \/\/ list cells are processed once only but we don't overflow the\n \/\/ stack by pushing all the addresses in a very large vector.\n PolyWord *endWord = (PolyWord*)obj + length;\n PolyObject *firstWord = 0;\n PolyObject *secondWord = 0;\n PolyWord *restartFrom = baseAddr;\n\n while (baseAddr != endWord)\n {\n PolyWord wordAt = *baseAddr;\n\n if (wordAt.IsDataPtr() && wordAt != PolyWord::FromUnsigned(0))\n {\n \/\/ Normal address. We can have words of all zeros at least in the\n \/\/ situation where we have a partially constructed code segment where\n \/\/ the constants at the end of the code have not yet been filled in.\n if (TestForScan(baseAddr)) \/\/ Test value at baseAddr (may side-effect it)\n {\n PolyObject *wObj = (*baseAddr).AsObjPtr();\n if (wObj->IsByteObject())\n {\n \/\/ Can do this now - don't need to push it\n MarkAsScanning(wObj);\n Completed(wObj);\n }\n else if (firstWord == 0)\n {\n firstWord = wObj;\n \/\/ We mark the word immediately. We can have\n \/\/ two words in an object that are the same\n \/\/ and we don't want to process it again.\n MarkAsScanning(firstWord);\n }\n else if (secondWord == 0)\n {\n secondWord = wObj;\n restartFrom = baseAddr;\n }\n else break; \/\/ More than two words.\n }\n }\n baseAddr++;\n }\n\n if (baseAddr == endWord)\n {\n \/\/ We have done everything except possibly firstWord and secondWord.\n Completed(obj);\n if (secondWord != 0)\n {\n MarkAsScanning(secondWord);\n \/\/ Put this on the stack. If this is a list node we will be\n \/\/ pushing the tail.\n PushToStack(secondWord, (PolyWord*)secondWord);\n }\n }\n else \/\/ Put this back on the stack while we process the first word\n PushToStack(obj, restartFrom);\n\n if (firstWord != 0)\n {\n \/\/ Process it immediately.\n obj = firstWord;\n baseAddr = (PolyWord*)obj;\n }\n else if (StackIsEmpty())\n return;\n else\n PopFromStack(obj, baseAddr);\n\n lengthWord = obj->LengthWord();\n }\n}\n\n\/\/ The stack is allocated as a series of blocks chained together.\n#define RSTACK_SEGMENT_SIZE 1000\n\nclass RScanStack {\npublic:\n RScanStack(): nextStack(0), lastStack(0), sp(0) {}\n ~RScanStack() { delete(nextStack); }\n\n RScanStack *nextStack;\n RScanStack *lastStack;\n unsigned sp;\n struct { PolyObject *obj; PolyWord *base; } stack[RSTACK_SEGMENT_SIZE];\n};\n\nRecursiveScanWithStack::~RecursiveScanWithStack()\n{\n delete(stack);\n}\n\nbool RecursiveScanWithStack::StackIsEmpty(void)\n{\n return stack == 0 || (stack->sp == 0 && stack->lastStack == 0);\n}\n\nvoid RecursiveScanWithStack::PushToStack(PolyObject *obj, PolyWord *base)\n{\n if (stack == 0 || stack->sp == RSTACK_SEGMENT_SIZE)\n {\n if (stack != 0 && stack->nextStack != 0)\n stack = stack->nextStack;\n else\n {\n \/\/ Need a new segment\n try {\n RScanStack *s = new RScanStack;\n s->lastStack = stack;\n if (stack != 0)\n stack->nextStack = s;\n stack = s;\n }\n catch (std::bad_alloc &) {\n StackOverflow();\n return;\n }\n }\n }\n stack->stack[stack->sp].obj = obj;\n stack->stack[stack->sp].base = base;\n stack->sp++;\n}\n\nvoid RecursiveScanWithStack::PopFromStack(PolyObject *&obj, PolyWord *&base)\n{\n if (stack->sp == 0)\n {\n \/\/ Chain to the previous stack if any\n ASSERT(stack->lastStack != 0);\n \/\/ Before we do, delete any further one to free some memory\n delete(stack->nextStack);\n stack->nextStack = 0;\n stack = stack->lastStack;\n ASSERT(stack->sp == RSTACK_SEGMENT_SIZE);\n }\n --stack->sp;\n obj = stack->stack[stack->sp].obj;\n base = stack->stack[stack->sp].base;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (c) 2014-2021 AscEmu Team <http:\/\/www.ascemu.org>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n#include \"Management\/EquipmentSetMgr.h\"\n#include \"Server\/MainServerDefines.h\"\n#include \"Database\/Field.hpp\"\n#include \"Database\/Database.h\"\n#include \"WoWGuid.h\"\n#include \"WorldPacket.h\"\n#include \"Logging\/Logger.hpp\"\n\nnamespace Arcemu\n{\n\n EquipmentSetMgr::~EquipmentSetMgr()\n {\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n delete itr->second;\n\n EquipmentSets.clear();\n }\n\n EquipmentSet* EquipmentSetMgr::GetEquipmentSet(uint32 id)\n {\n EquipmentSetStorage::iterator itr;\n\n itr = EquipmentSets.find(id);\n\n if (itr != EquipmentSets.end())\n return itr->second;\n else\n return NULL;\n }\n\n bool EquipmentSetMgr::AddEquipmentSet(uint32 setGUID, EquipmentSet* set)\n {\n std::pair< EquipmentSetStorage::iterator, bool > retval;\n\n retval = EquipmentSets.insert(std::pair< uint32, EquipmentSet* >(setGUID, set));\n\n return retval.second;\n }\n\n bool EquipmentSetMgr::DeleteEquipmentSet(uint32 setGUID)\n {\n EquipmentSetStorage::iterator itr;\n\n itr = EquipmentSets.find(setGUID);\n\n if (itr != EquipmentSets.end())\n {\n EquipmentSet* set = itr->second;\n\n EquipmentSets.erase(itr);\n delete set;\n set = NULL;\n\n return true;\n }\n else\n return false;\n }\n\n bool EquipmentSetMgr::LoadfromDB(QueryResult* result)\n {\n if (result == NULL)\n return false;\n\n uint32 setcount = 0;\n EquipmentSet* set = NULL;\n Field* fields = NULL;\n\n do\n {\n if (setcount >= 10)\n {\n sLogger.failure(\"There were more than 10 equipment sets for GUID: %u\", ownerGUID);\n return true;\n }\n\n fields = result->Fetch();\n\n set = new EquipmentSet();\n if (set == NULL)\n return false;\n\n set->SetGUID = fields[1].GetUInt32();\n set->SetID = fields[2].GetUInt32();\n set->SetName = fields[3].GetString();\n set->IconName = fields[4].GetString();\n\n for (uint32 i = 0; i < set->ItemGUID.size(); ++i)\n set->ItemGUID[i] = fields[5 + i].GetUInt32();\n\n EquipmentSets.insert(std::pair< uint32, EquipmentSet* >(set->SetGUID, set));\n set = NULL;\n setcount++;\n\n }\n while (result->NextRow());\n\n return true;\n }\n\n bool EquipmentSetMgr::SavetoDB(QueryBuffer* buf)\n {\n if (buf == NULL)\n return false;\n\n std::stringstream ds;\n ds << \"DELETE FROM equipmentsets WHERE ownerguid = \";\n ds << ownerGUID;\n\n buf->AddQueryNA(ds.str().c_str());\n\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n {\n EquipmentSet* set = itr->second;\n\n std::stringstream ss;\n\n ss << \"INSERT INTO equipmentsets VALUES('\";\n ss << ownerGUID << \"','\";\n ss << set->SetGUID << \"','\";\n ss << set->SetID << \"','\";\n ss << CharacterDatabase.EscapeString(set->SetName) << \"','\";\n ss << set->IconName << \"'\";\n\n for (uint32 j = 0; j < set->ItemGUID.size(); ++j)\n {\n ss << \",'\";\n ss << set->ItemGUID[j];\n ss << \"'\";\n }\n\n ss << \")\";\n\n buf->AddQueryNA(ss.str().c_str());\n }\n\n return true;\n }\n\n void EquipmentSetMgr::FillEquipmentSetListPacket(WorldPacket& data)\n {\n data << uint32(EquipmentSets.size());\n\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n {\n EquipmentSet* set = itr->second;\n\n data << WoWGuid(uint64(set->SetGUID));\n data << uint32(set->SetID);\n data << std::string(set->SetName);\n data << std::string(set->IconName);\n\n for (uint32 i = 0; i < set->ItemGUID.size(); ++i)\n {\n data << WoWGuid(uint64(WoWGuid::createItemGuid(set->ItemGUID[i])));\n }\n }\n }\n}\n<commit_msg>V823 Decreased performance. Object may be created in-place in the 'EquipmentSets' container. Consider replacing methods: 'insert' -> 'emplace'. world EquipmentSetMgr.cpp 57<commit_after>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (c) 2014-2021 AscEmu Team <http:\/\/www.ascemu.org>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n#include \"Management\/EquipmentSetMgr.h\"\n#include \"Server\/MainServerDefines.h\"\n#include \"Database\/Field.hpp\"\n#include \"Database\/Database.h\"\n#include \"WoWGuid.h\"\n#include \"WorldPacket.h\"\n#include \"Logging\/Logger.hpp\"\n\nnamespace Arcemu\n{\n\n EquipmentSetMgr::~EquipmentSetMgr()\n {\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n delete itr->second;\n\n EquipmentSets.clear();\n }\n\n EquipmentSet* EquipmentSetMgr::GetEquipmentSet(uint32 id)\n {\n EquipmentSetStorage::iterator itr;\n\n itr = EquipmentSets.find(id);\n\n if (itr != EquipmentSets.end())\n return itr->second;\n else\n return NULL;\n }\n\n bool EquipmentSetMgr::AddEquipmentSet(uint32 setGUID, EquipmentSet* set)\n {\n std::pair< EquipmentSetStorage::iterator, bool > retval;\n\n retval = EquipmentSets.emplace(std::pair< uint32, EquipmentSet* >(setGUID, set));\n\n return retval.second;\n }\n\n bool EquipmentSetMgr::DeleteEquipmentSet(uint32 setGUID)\n {\n EquipmentSetStorage::iterator itr;\n\n itr = EquipmentSets.find(setGUID);\n\n if (itr != EquipmentSets.end())\n {\n EquipmentSet* set = itr->second;\n\n EquipmentSets.erase(itr);\n delete set;\n set = NULL;\n\n return true;\n }\n else\n return false;\n }\n\n bool EquipmentSetMgr::LoadfromDB(QueryResult* result)\n {\n if (result == NULL)\n return false;\n\n uint32 setcount = 0;\n EquipmentSet* set = NULL;\n Field* fields = NULL;\n\n do\n {\n if (setcount >= 10)\n {\n sLogger.failure(\"There were more than 10 equipment sets for GUID: %u\", ownerGUID);\n return true;\n }\n\n fields = result->Fetch();\n\n set = new EquipmentSet();\n if (set == NULL)\n return false;\n\n set->SetGUID = fields[1].GetUInt32();\n set->SetID = fields[2].GetUInt32();\n set->SetName = fields[3].GetString();\n set->IconName = fields[4].GetString();\n\n for (uint32 i = 0; i < set->ItemGUID.size(); ++i)\n set->ItemGUID[i] = fields[5 + i].GetUInt32();\n\n EquipmentSets.insert(std::pair< uint32, EquipmentSet* >(set->SetGUID, set));\n set = NULL;\n setcount++;\n\n }\n while (result->NextRow());\n\n return true;\n }\n\n bool EquipmentSetMgr::SavetoDB(QueryBuffer* buf)\n {\n if (buf == NULL)\n return false;\n\n std::stringstream ds;\n ds << \"DELETE FROM equipmentsets WHERE ownerguid = \";\n ds << ownerGUID;\n\n buf->AddQueryNA(ds.str().c_str());\n\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n {\n EquipmentSet* set = itr->second;\n\n std::stringstream ss;\n\n ss << \"INSERT INTO equipmentsets VALUES('\";\n ss << ownerGUID << \"','\";\n ss << set->SetGUID << \"','\";\n ss << set->SetID << \"','\";\n ss << CharacterDatabase.EscapeString(set->SetName) << \"','\";\n ss << set->IconName << \"'\";\n\n for (uint32 j = 0; j < set->ItemGUID.size(); ++j)\n {\n ss << \",'\";\n ss << set->ItemGUID[j];\n ss << \"'\";\n }\n\n ss << \")\";\n\n buf->AddQueryNA(ss.str().c_str());\n }\n\n return true;\n }\n\n void EquipmentSetMgr::FillEquipmentSetListPacket(WorldPacket& data)\n {\n data << uint32(EquipmentSets.size());\n\n for (EquipmentSetStorage::iterator itr = EquipmentSets.begin(); itr != EquipmentSets.end(); ++itr)\n {\n EquipmentSet* set = itr->second;\n\n data << WoWGuid(uint64(set->SetGUID));\n data << uint32(set->SetID);\n data << std::string(set->SetName);\n data << std::string(set->IconName);\n\n for (uint32 i = 0; i < set->ItemGUID.size(); ++i)\n {\n data << WoWGuid(uint64(WoWGuid::createItemGuid(set->ItemGUID[i])));\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkStepper.h\"\n#include \"mitkMultiStepper.h\"\n\nint mitkStepperTest(int argc, char* argv[])\n{\n mitk::Stepper::Pointer stepperA;\n std::cout << \"Testing mitk::Stepper::New(): \";\n stepperA = mitk::Stepper::New();\n if (stepperA.IsNull()) {\n std::cout<<\"[FAILED]\"<<std::endl;\n return EXIT_FAILURE;\n }\n else {\n std::cout<<\"[PASSED]\"<<std::endl;\n }\n \n mitk::Stepper::Pointer stepperB = mitk::Stepper::New();\n stepperA->SetSteps(4);\n \/\/stepperA->PingPongOn();\n tepperB->SetSteps(6);\n \/\/ stepperB->PingPongOn();\n \/* for (int i=0 ; i<10; i++) {\n std::cout << i << \": A: \" << stepperA->GetPos() << \" B:\" << stepperB->GetPos() << std::endl; \n stepperA->Next();\n stepperB->Next();\n }*\/\n std::cout << \"Multi Stepper Test\" << std::endl;\n mitk::MultiStepper::Pointer multiStepper = mitk::MultiStepper::New();\n\n multiStepper->AddStepper(stepperA,2);\n multiStepper->AddStepper(stepperB);\n \n for (int i=0 ; i<10; i++) {\n std::cout << i << \": A: \" << stepperA->GetPos() << \" B:\" << stepperB->GetPos() << std::endl; \n multiStepper->Next();\n }\n \n return EXIT_SUCCESS;\n}\n<commit_msg>FIX: typo<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkStepper.h\"\n#include \"mitkMultiStepper.h\"\n\nint mitkStepperTest(int argc, char* argv[])\n{\n mitk::Stepper::Pointer stepperA;\n std::cout << \"Testing mitk::Stepper::New(): \";\n stepperA = mitk::Stepper::New();\n if (stepperA.IsNull()) {\n std::cout<<\"[FAILED]\"<<std::endl;\n return EXIT_FAILURE;\n }\n else {\n std::cout<<\"[PASSED]\"<<std::endl;\n }\n \n mitk::Stepper::Pointer stepperB = mitk::Stepper::New();\n stepperA->SetSteps(4);\n \/\/stepperA->PingPongOn();\n stepperB->SetSteps(6);\n \/\/ stepperB->PingPongOn();\n \/* for (int i=0 ; i<10; i++) {\n std::cout << i << \": A: \" << stepperA->GetPos() << \" B:\" << stepperB->GetPos() << std::endl; \n stepperA->Next();\n stepperB->Next();\n }*\/\n std::cout << \"Multi Stepper Test\" << std::endl;\n mitk::MultiStepper::Pointer multiStepper = mitk::MultiStepper::New();\n\n multiStepper->AddStepper(stepperA,2);\n multiStepper->AddStepper(stepperB);\n \n for (int i=0 ; i<10; i++) {\n std::cout << i << \": A: \" << stepperA->GetPos() << \" B:\" << stepperB->GetPos() << std::endl; \n multiStepper->Next();\n }\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/tracing\/core\/trace_writer_impl.h\"\n\n#include <gtest\/gtest.h>\n#include \"perfetto\/ext\/base\/utils.h\"\n#include \"perfetto\/ext\/tracing\/core\/commit_data_request.h\"\n#include \"perfetto\/ext\/tracing\/core\/trace_writer.h\"\n#include \"perfetto\/ext\/tracing\/core\/tracing_service.h\"\n#include \"src\/base\/test\/gtest_test_suite.h\"\n#include \"src\/base\/test\/test_task_runner.h\"\n#include \"src\/tracing\/core\/shared_memory_arbiter_impl.h\"\n#include \"src\/tracing\/test\/aligned_buffer_test.h\"\n#include \"src\/tracing\/test\/fake_producer_endpoint.h\"\n\n#include \"perfetto\/trace\/test_event.pbzero.h\"\n#include \"perfetto\/trace\/trace_packet.pbzero.h\"\n\nnamespace perfetto {\nnamespace {\n\nclass TraceWriterImplTest : public AlignedBufferTest {\n public:\n void SetUp() override {\n SharedMemoryArbiterImpl::set_default_layout_for_testing(\n SharedMemoryABI::PageLayout::kPageDiv4);\n AlignedBufferTest::SetUp();\n task_runner_.reset(new base::TestTaskRunner());\n arbiter_.reset(new SharedMemoryArbiterImpl(buf(), buf_size(), page_size(),\n &fake_producer_endpoint_,\n task_runner_.get()));\n }\n\n void TearDown() override {\n arbiter_.reset();\n task_runner_.reset();\n }\n\n FakeProducerEndpoint fake_producer_endpoint_;\n std::unique_ptr<base::TestTaskRunner> task_runner_;\n std::unique_ptr<SharedMemoryArbiterImpl> arbiter_;\n std::function<void(const std::vector<uint32_t>&)> on_pages_complete_;\n};\n\nsize_t const kPageSizes[] = {4096, 65536};\nINSTANTIATE_TEST_SUITE_P(PageSize,\n TraceWriterImplTest,\n ::testing::ValuesIn(kPageSizes));\n\nTEST_P(TraceWriterImplTest, SingleWriter) {\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(kBufId);\n const size_t kNumPackets = 32;\n for (size_t i = 0; i < kNumPackets; i++) {\n auto packet = writer->NewTracePacket();\n char str[16];\n sprintf(str, \"foobar %zu\", i);\n packet->set_for_testing()->set_str(str);\n }\n\n \/\/ Destroying the TraceWriteImpl should cause the last packet to be finalized\n \/\/ and the chunk to be put back in the kChunkComplete state.\n writer.reset();\n\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n size_t packets_count = 0;\n for (size_t page_idx = 0; page_idx < kNumPages; page_idx++) {\n uint32_t page_layout = abi->GetPageLayout(page_idx);\n size_t num_chunks = SharedMemoryABI::GetNumChunksForLayout(page_layout);\n for (size_t chunk_idx = 0; chunk_idx < num_chunks; chunk_idx++) {\n auto chunk_state = abi->GetChunkState(page_idx, chunk_idx);\n ASSERT_TRUE(chunk_state == SharedMemoryABI::kChunkFree ||\n chunk_state == SharedMemoryABI::kChunkComplete);\n auto chunk = abi->TryAcquireChunkForReading(page_idx, chunk_idx);\n if (!chunk.is_valid())\n continue;\n packets_count += chunk.header()->packets.load().count;\n }\n }\n EXPECT_EQ(kNumPackets, packets_count);\n \/\/ TODO(primiano): check also the content of the packets decoding the protos.\n}\n\nTEST_P(TraceWriterImplTest, FragmentingPacket) {\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(kBufId);\n\n \/\/ Write a packet that's guaranteed to span more than a single chunk.\n auto packet = writer->NewTracePacket();\n size_t chunk_size = page_size() \/ 4;\n std::stringstream large_string_writer;\n for (size_t pos = 0; pos < chunk_size; pos++)\n large_string_writer << \"x\";\n std::string large_string = large_string_writer.str();\n packet->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n \/\/ First chunk should be committed.\n arbiter_->FlushPendingCommitDataRequests();\n const auto& last_commit = fake_producer_endpoint_.last_commit_data_request;\n ASSERT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n EXPECT_EQ(kBufId, last_commit.chunks_to_move()[0].target_buffer());\n EXPECT_EQ(0, last_commit.chunks_to_patch_size());\n\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n\n \/\/ The first allocated chunk should be complete but need patching, since the\n \/\/ packet extended past the chunk and no patches for the packet size or string\n \/\/ field size were applied yet.\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n auto chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(1, chunk.header()->packets.load().count);\n ASSERT_TRUE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_TRUE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n\n \/\/ Starting a new packet should cause patches to be applied.\n packet->Finalize();\n auto packet2 = writer->NewTracePacket();\n arbiter_->FlushPendingCommitDataRequests();\n EXPECT_EQ(0, last_commit.chunks_to_move_size());\n ASSERT_EQ(1, last_commit.chunks_to_patch_size());\n EXPECT_EQ(writer->writer_id(), last_commit.chunks_to_patch()[0].writer_id());\n EXPECT_EQ(kBufId, last_commit.chunks_to_patch()[0].target_buffer());\n EXPECT_EQ(chunk.header()->chunk_id.load(),\n last_commit.chunks_to_patch()[0].chunk_id());\n EXPECT_FALSE(last_commit.chunks_to_patch()[0].has_more_patches());\n ASSERT_EQ(1, last_commit.chunks_to_patch()[0].patches_size());\n}\n\n\/\/ Sets up a scenario in which the SMB is exhausted and TraceWriter fails to get\n\/\/ a new chunk while fragmenting a packet. Verifies that data is dropped until\n\/\/ the SMB is freed up and TraceWriter can get a new chunk.\nTEST_P(TraceWriterImplTest, FragmentingPacketWhileBufferExhaused) {\n arbiter_.reset(new SharedMemoryArbiterImpl(buf(), buf_size(), page_size(),\n &fake_producer_endpoint_,\n task_runner_.get()));\n\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(\n kBufId, SharedMemoryArbiter::BufferExhaustedPolicy::kDrop);\n\n \/\/ Write a small first packet, so that |writer| owns a chunk.\n auto packet = writer->NewTracePacket();\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n EXPECT_EQ(packet->Finalize(), 0);\n\n \/\/ Grab all the remaining chunks in the SMB in new writers.\n std::array<std::unique_ptr<TraceWriter>, kNumPages * 4 - 1> other_writers;\n for (size_t i = 0; i < other_writers.size(); i++) {\n other_writers[i] = arbiter_->CreateTraceWriter(\n kBufId, SharedMemoryArbiter::BufferExhaustedPolicy::kDrop);\n auto other_writer_packet = other_writers[i]->NewTracePacket();\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(other_writers[i].get())\n ->drop_packets_for_testing());\n }\n\n \/\/ Write a packet that's guaranteed to span more than a single chunk, causing\n \/\/ |writer| to attempt to acquire a new chunk but fail to do so.\n auto packet2 = writer->NewTracePacket();\n size_t chunk_size = page_size() \/ 4;\n std::stringstream large_string_writer;\n for (size_t pos = 0; pos < chunk_size; pos++)\n large_string_writer << \"x\";\n std::string large_string = large_string_writer.str();\n packet2->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n EXPECT_TRUE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n\n \/\/ First chunk should be committed.\n arbiter_->FlushPendingCommitDataRequests();\n const auto& last_commit = fake_producer_endpoint_.last_commit_data_request;\n ASSERT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n EXPECT_EQ(kBufId, last_commit.chunks_to_move()[0].target_buffer());\n EXPECT_EQ(0, last_commit.chunks_to_patch_size());\n\n \/\/ It should not need patching and not have the continuation flag set.\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n auto chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(2, chunk.header()->packets.load().count);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n\n \/\/ Writing more data while in garbage mode succeeds. This data is dropped.\n packet2->Finalize();\n auto packet3 = writer->NewTracePacket();\n packet3->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n \/\/ Release the |writer|'s first chunk as free, so that it can grab it again.\n abi->ReleaseChunkAsFree(std::move(chunk));\n\n \/\/ Starting a new packet should cause TraceWriter to attempt to grab a new\n \/\/ chunk again, because we wrote enough data to wrap the garbage chunk.\n packet3->Finalize();\n auto packet4 = writer->NewTracePacket();\n\n \/\/ Grabbing the chunk should have succeeded.\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n\n \/\/ The first packet in the chunk should have the previous_packet_dropped flag\n \/\/ set, so shouldn't be empty.\n EXPECT_GT(packet4->Finalize(), 0);\n\n \/\/ Flushing the writer causes the chunk to be released again.\n writer->Flush();\n EXPECT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n ASSERT_EQ(0, last_commit.chunks_to_patch_size());\n\n \/\/ Chunk should contain only |packet4| and not have any continuation flag set.\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(1, chunk.header()->packets.load().count);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_FALSE(\n chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kFirstPacketContinuesFromPrevChunk);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n}\n\n\/\/ TODO(primiano): add multi-writer test.\n\/\/ TODO(primiano): add Flush() test.\n\n} \/\/ namespace\n} \/\/ namespace perfetto\n<commit_msg>build: Attempt to fix chrometto roll am: ee85c6fe18 am: c39efa40d4 am: 4cf4d9ebec am: cd378ed793<commit_after>\/*\n * Copyright (C) 2017 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/tracing\/core\/trace_writer_impl.h\"\n\n#include <gtest\/gtest.h>\n#include \"perfetto\/ext\/base\/utils.h\"\n#include \"perfetto\/ext\/tracing\/core\/commit_data_request.h\"\n#include \"perfetto\/ext\/tracing\/core\/trace_writer.h\"\n#include \"perfetto\/ext\/tracing\/core\/tracing_service.h\"\n#include \"src\/base\/test\/gtest_test_suite.h\"\n#include \"src\/base\/test\/test_task_runner.h\"\n#include \"src\/tracing\/core\/shared_memory_arbiter_impl.h\"\n#include \"src\/tracing\/test\/aligned_buffer_test.h\"\n#include \"src\/tracing\/test\/fake_producer_endpoint.h\"\n\n#include \"perfetto\/trace\/test_event.pbzero.h\"\n#include \"perfetto\/trace\/trace_packet.pbzero.h\"\n\nnamespace perfetto {\nnamespace {\n\nclass TraceWriterImplTest : public AlignedBufferTest {\n public:\n void SetUp() override {\n SharedMemoryArbiterImpl::set_default_layout_for_testing(\n SharedMemoryABI::PageLayout::kPageDiv4);\n AlignedBufferTest::SetUp();\n task_runner_.reset(new base::TestTaskRunner());\n arbiter_.reset(new SharedMemoryArbiterImpl(buf(), buf_size(), page_size(),\n &fake_producer_endpoint_,\n task_runner_.get()));\n }\n\n void TearDown() override {\n arbiter_.reset();\n task_runner_.reset();\n }\n\n FakeProducerEndpoint fake_producer_endpoint_;\n std::unique_ptr<base::TestTaskRunner> task_runner_;\n std::unique_ptr<SharedMemoryArbiterImpl> arbiter_;\n std::function<void(const std::vector<uint32_t>&)> on_pages_complete_;\n};\n\nsize_t const kPageSizes[] = {4096, 65536};\nINSTANTIATE_TEST_SUITE_P(PageSize,\n TraceWriterImplTest,\n ::testing::ValuesIn(kPageSizes));\n\nTEST_P(TraceWriterImplTest, SingleWriter) {\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(kBufId);\n const size_t kNumPackets = 32;\n for (size_t i = 0; i < kNumPackets; i++) {\n auto packet = writer->NewTracePacket();\n char str[16];\n sprintf(str, \"foobar %zu\", i);\n packet->set_for_testing()->set_str(str);\n }\n\n \/\/ Destroying the TraceWriteImpl should cause the last packet to be finalized\n \/\/ and the chunk to be put back in the kChunkComplete state.\n writer.reset();\n\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n size_t packets_count = 0;\n for (size_t page_idx = 0; page_idx < kNumPages; page_idx++) {\n uint32_t page_layout = abi->GetPageLayout(page_idx);\n size_t num_chunks = SharedMemoryABI::GetNumChunksForLayout(page_layout);\n for (size_t chunk_idx = 0; chunk_idx < num_chunks; chunk_idx++) {\n auto chunk_state = abi->GetChunkState(page_idx, chunk_idx);\n ASSERT_TRUE(chunk_state == SharedMemoryABI::kChunkFree ||\n chunk_state == SharedMemoryABI::kChunkComplete);\n auto chunk = abi->TryAcquireChunkForReading(page_idx, chunk_idx);\n if (!chunk.is_valid())\n continue;\n packets_count += chunk.header()->packets.load().count;\n }\n }\n EXPECT_EQ(kNumPackets, packets_count);\n \/\/ TODO(primiano): check also the content of the packets decoding the protos.\n}\n\nTEST_P(TraceWriterImplTest, FragmentingPacket) {\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(kBufId);\n\n \/\/ Write a packet that's guaranteed to span more than a single chunk.\n auto packet = writer->NewTracePacket();\n size_t chunk_size = page_size() \/ 4;\n std::stringstream large_string_writer;\n for (size_t pos = 0; pos < chunk_size; pos++)\n large_string_writer << \"x\";\n std::string large_string = large_string_writer.str();\n packet->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n \/\/ First chunk should be committed.\n arbiter_->FlushPendingCommitDataRequests();\n const auto& last_commit = fake_producer_endpoint_.last_commit_data_request;\n ASSERT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n EXPECT_EQ(kBufId, last_commit.chunks_to_move()[0].target_buffer());\n EXPECT_EQ(0, last_commit.chunks_to_patch_size());\n\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n\n \/\/ The first allocated chunk should be complete but need patching, since the\n \/\/ packet extended past the chunk and no patches for the packet size or string\n \/\/ field size were applied yet.\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n auto chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(1, chunk.header()->packets.load().count);\n ASSERT_TRUE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_TRUE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n\n \/\/ Starting a new packet should cause patches to be applied.\n packet->Finalize();\n auto packet2 = writer->NewTracePacket();\n arbiter_->FlushPendingCommitDataRequests();\n EXPECT_EQ(0, last_commit.chunks_to_move_size());\n ASSERT_EQ(1, last_commit.chunks_to_patch_size());\n EXPECT_EQ(writer->writer_id(), last_commit.chunks_to_patch()[0].writer_id());\n EXPECT_EQ(kBufId, last_commit.chunks_to_patch()[0].target_buffer());\n EXPECT_EQ(chunk.header()->chunk_id.load(),\n last_commit.chunks_to_patch()[0].chunk_id());\n EXPECT_FALSE(last_commit.chunks_to_patch()[0].has_more_patches());\n ASSERT_EQ(1, last_commit.chunks_to_patch()[0].patches_size());\n}\n\n\/\/ Sets up a scenario in which the SMB is exhausted and TraceWriter fails to get\n\/\/ a new chunk while fragmenting a packet. Verifies that data is dropped until\n\/\/ the SMB is freed up and TraceWriter can get a new chunk.\nTEST_P(TraceWriterImplTest, FragmentingPacketWhileBufferExhausted) {\n arbiter_.reset(new SharedMemoryArbiterImpl(buf(), buf_size(), page_size(),\n &fake_producer_endpoint_,\n task_runner_.get()));\n\n const BufferID kBufId = 42;\n std::unique_ptr<TraceWriter> writer = arbiter_->CreateTraceWriter(\n kBufId, SharedMemoryArbiter::BufferExhaustedPolicy::kDrop);\n\n \/\/ Write a small first packet, so that |writer| owns a chunk.\n auto packet = writer->NewTracePacket();\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n EXPECT_EQ(packet->Finalize(), 0u);\n\n \/\/ Grab all the remaining chunks in the SMB in new writers.\n std::array<std::unique_ptr<TraceWriter>, kNumPages * 4 - 1> other_writers;\n for (size_t i = 0; i < other_writers.size(); i++) {\n other_writers[i] = arbiter_->CreateTraceWriter(\n kBufId, SharedMemoryArbiter::BufferExhaustedPolicy::kDrop);\n auto other_writer_packet = other_writers[i]->NewTracePacket();\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(other_writers[i].get())\n ->drop_packets_for_testing());\n }\n\n \/\/ Write a packet that's guaranteed to span more than a single chunk, causing\n \/\/ |writer| to attempt to acquire a new chunk but fail to do so.\n auto packet2 = writer->NewTracePacket();\n size_t chunk_size = page_size() \/ 4;\n std::stringstream large_string_writer;\n for (size_t pos = 0; pos < chunk_size; pos++)\n large_string_writer << \"x\";\n std::string large_string = large_string_writer.str();\n packet2->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n EXPECT_TRUE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n\n \/\/ First chunk should be committed.\n arbiter_->FlushPendingCommitDataRequests();\n const auto& last_commit = fake_producer_endpoint_.last_commit_data_request;\n ASSERT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n EXPECT_EQ(kBufId, last_commit.chunks_to_move()[0].target_buffer());\n EXPECT_EQ(0, last_commit.chunks_to_patch_size());\n\n \/\/ It should not need patching and not have the continuation flag set.\n SharedMemoryABI* abi = arbiter_->shmem_abi_for_testing();\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n auto chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(2, chunk.header()->packets.load().count);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n\n \/\/ Writing more data while in garbage mode succeeds. This data is dropped.\n packet2->Finalize();\n auto packet3 = writer->NewTracePacket();\n packet3->set_for_testing()->set_str(large_string.data(), large_string.size());\n\n \/\/ Release the |writer|'s first chunk as free, so that it can grab it again.\n abi->ReleaseChunkAsFree(std::move(chunk));\n\n \/\/ Starting a new packet should cause TraceWriter to attempt to grab a new\n \/\/ chunk again, because we wrote enough data to wrap the garbage chunk.\n packet3->Finalize();\n auto packet4 = writer->NewTracePacket();\n\n \/\/ Grabbing the chunk should have succeeded.\n EXPECT_FALSE(reinterpret_cast<TraceWriterImpl*>(writer.get())\n ->drop_packets_for_testing());\n\n \/\/ The first packet in the chunk should have the previous_packet_dropped flag\n \/\/ set, so shouldn't be empty.\n EXPECT_GT(packet4->Finalize(), 0u);\n\n \/\/ Flushing the writer causes the chunk to be released again.\n writer->Flush();\n EXPECT_EQ(1, last_commit.chunks_to_move_size());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].page());\n EXPECT_EQ(0u, last_commit.chunks_to_move()[0].chunk());\n ASSERT_EQ(0, last_commit.chunks_to_patch_size());\n\n \/\/ Chunk should contain only |packet4| and not have any continuation flag set.\n ASSERT_EQ(SharedMemoryABI::kChunkComplete, abi->GetChunkState(0u, 0u));\n chunk = abi->TryAcquireChunkForReading(0u, 0u);\n ASSERT_TRUE(chunk.is_valid());\n ASSERT_EQ(1, chunk.header()->packets.load().count);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kChunkNeedsPatching);\n ASSERT_FALSE(\n chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kFirstPacketContinuesFromPrevChunk);\n ASSERT_FALSE(chunk.header()->packets.load().flags &\n SharedMemoryABI::ChunkHeader::kLastPacketContinuesOnNextChunk);\n}\n\n\/\/ TODO(primiano): add multi-writer test.\n\/\/ TODO(primiano): add Flush() test.\n\n} \/\/ namespace\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"<commit_before>#define WIN32_LEAN_AND_MEAN\n\n#include <windows.h>\n#include <uv.h>\n#include <string>\n#include <sstream>\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"..\/worker_platform.h\"\n#include \"..\/worker_thread.h\"\n#include \"..\/..\/message.h\"\n#include \"..\/..\/log.h\"\n#include \"..\/..\/lock.h\"\n\nusing std::string;\nusing std::wstring;\nusing std::ostringstream;\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::default_delete;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::vector;\nusing std::move;\nusing std::endl;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nstatic void CALLBACK command_perform_helper(__in ULONG_PTR payload);\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);\n\nstatic Result<string> to_utf8(const wstring &in);\n\ntemplate < class V = void* >\nstatic Result<V> windows_error_result(const string &prefix);\n\ntemplate < class V = void* >\nstatic Result<V> windows_error_result(const string &prefix, DWORD error_code);\n\nclass WindowsWorkerPlatform;\n\nclass Subscription {\npublic:\n Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n {\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n }\n\n ~Subscription()\n {\n CloseHandle(root);\n }\n\n Result<> schedule()\n {\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n &event_helper \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n }\n\n Result<> use_network_size()\n {\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n }\n\n ChannelID get_channel() const {\n return channel;\n }\n\n WindowsWorkerPlatform* get_platform() const {\n return platform;\n }\n\n BYTE *get_written(DWORD written_size) {\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n }\n\n string make_absolute(const string &sub_path)\n {\n ostringstream out;\n\n out << path;\n if (path.back() != '\\\\' && sub_path.front() != '\\\\') {\n out << '\\\\';\n }\n out << sub_path;\n\n return out.str();\n }\n\nprivate:\n ChannelID channel;\n WindowsWorkerPlatform *platform;\n\n string path;\n HANDLE root;\n OVERLAPPED overlapped;\n\n DWORD buffer_size;\n unique_ptr<BYTE[]> buffer;\n unique_ptr<BYTE[]> written;\n};\n\nclass WindowsWorkerPlatform : public WorkerPlatform {\npublic:\n WindowsWorkerPlatform(WorkerThread *thread) :\n WorkerPlatform(thread),\n thread_handle{0}\n {\n int err;\n\n err = uv_mutex_init(&thread_handle_mutex);\n if (err) {\n report_uv_error(err);\n }\n };\n\n ~WindowsWorkerPlatform() override\n {\n uv_mutex_destroy(&thread_handle_mutex);\n }\n\n Result<> wake() override\n {\n Lock lock(thread_handle_mutex);\n\n if (!thread_handle) {\n return ok_result();\n }\n\n BOOL success = QueueUserAPC(\n command_perform_helper,\n thread_handle,\n reinterpret_cast<ULONG_PTR>(this)\n );\n if (!success) {\n return windows_error_result<>(\"Unable to queue APC\");\n }\n\n return ok_result();\n }\n\n Result<> listen() override\n {\n {\n Lock lock(thread_handle_mutex);\n\n HANDLE pseudo_handle = GetCurrentThread();\n BOOL success = DuplicateHandle(\n GetCurrentProcess(), \/\/ Source process\n pseudo_handle, \/\/ Source handle\n GetCurrentProcess(), \/\/ Destination process\n &thread_handle, \/\/ Destination handle\n 0, \/\/ Desired access\n FALSE, \/\/ Inheritable by new processes\n DUPLICATE_SAME_ACCESS \/\/ options\n );\n if (!success) {\n Result<> r = windows_error_result<>(\"Unable to duplicate thread handle\");\n report_error(\"Unable to acquire thread handle\");\n return r;\n }\n }\n\n while (true) {\n SleepEx(INFINITE, true);\n }\n\n report_error(\"listen loop ended unexpectedly\");\n return health_err_result();\n }\n\n Result<> handle_add_command(const ChannelID channel, const string &root_path)\n {\n LOGGER << \"Watching: \" << root_path << endl;\n\n \/\/ Convert the path to a wide-character array\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result<>(\"Unable to measure UTF-16 buffer\");\n }\n unique_ptr<WCHAR[]> root_path_w{new WCHAR[wlen]};\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n root_path_w.get(), \/\/ output buffer\n wlen \/\/ output buffer size\n );\n if (!conv_success) {\n return windows_error_result<>(\"Unable to convert root path to UTF-16\");\n }\n\n \/\/ Open a directory handle\n HANDLE root = CreateFileW(\n root_path_w.get(), \/\/ file name\n FILE_LIST_DIRECTORY, \/\/ desired access\n FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, \/\/ share mode\n NULL, \/\/ security attributes\n OPEN_EXISTING, \/\/ creation disposition\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, \/\/ flags and attributes\n NULL \/\/ template file\n );\n if (root == INVALID_HANDLE_VALUE) {\n return windows_error_result<>(\"Unable to open directory handle\");\n }\n\n \/\/ Allocate and persist the subscription\n Subscription *sub = new Subscription(channel, root, root_path, this);\n auto insert_result = subscriptions.insert(make_pair(channel, sub));\n if (!insert_result.second) {\n delete sub;\n\n ostringstream msg(\"Channel collision: \");\n msg << channel;\n return error_result(msg.str());\n }\n\n LOGGER << \"Now watching directory \" << root_path << \".\" << endl;\n\n return sub->schedule();\n }\n\n Result<> handle_remove_command(const ChannelID channel)\n {\n return ok_result();\n }\n\n Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)\n {\n \/\/ Ensure that the subscription is valid.\n ChannelID channel = sub->get_channel();\n auto it = subscriptions.find(channel);\n if (it == subscriptions.end() || it->second != sub) {\n return ok_result();\n }\n\n \/\/ Handle errors.\n if (error_code == ERROR_OPERATION_ABORTED) {\n LOGGER << \"Operation aborted.\" << endl;\n\n subscriptions.erase(it);\n delete sub;\n\n return ok_result();\n }\n\n if (error_code == ERROR_INVALID_PARAMETER) {\n Result<> resize = sub->use_network_size();\n if (resize.is_error()) return resize;\n\n return sub->schedule();\n }\n\n if (error_code == ERROR_NOTIFY_ENUM_DIR) {\n LOGGER << \"Change buffer overflow. Some events may have been lost.\" << endl;\n return sub->schedule();\n }\n\n if (error_code != ERROR_SUCCESS) {\n return windows_error_result<>(\"Completion callback error\", error_code);\n }\n\n \/\/ Schedule the next completion callback.\n BYTE *base = sub->get_written(num_bytes);\n Result<> next = sub->schedule();\n if (next.is_error()) {\n report_error(string(next.get_error()));\n }\n\n \/\/ Process received events.\n vector<Message> messages;\n bool old_path_seen = false;\n string old_path;\n\n while (true) {\n PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);\n\n wstring wpath{info->FileName, info->FileNameLength};\n Result<string> u8r = to_utf8(wpath);\n if (u8r.is_error()) {\n LOGGER << \"Skipping path: \" << u8r << \".\" << endl;\n } else {\n string path = sub->make_absolute(u8r.get_value());\n\n switch (info->Action) {\n case FILE_ACTION_ADDED:\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_MODIFIED:\n {\n FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_REMOVED:\n {\n FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_RENAMED_OLD_NAME:\n old_path_seen = true;\n old_path = move(path);\n break;\n case FILE_ACTION_RENAMED_NEW_NAME:\n if (old_path_seen) {\n \/\/ Old name received first\n {\n FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n\n old_path_seen = false;\n } else {\n \/\/ No old name. Treat it as a creation\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n }\n break;\n default:\n LOGGER << \"Skipping unexpected action \" << info->Action << \".\" << endl;\n break;\n }\n }\n\n if (info->NextEntryOffset == 0) {\n break;\n }\n base += info->NextEntryOffset;\n }\n\n if (!messages.empty()) {\n Result<> er = emit_all(messages.begin(), messages.end());\n if (er.is_error()) {\n LOGGER << \"Unable to emit messages: \" << er << \".\" << endl;\n }\n }\n\n return next;\n }\n\nprivate:\n uv_mutex_t thread_handle_mutex;\n HANDLE thread_handle;\n\n map<ChannelID, Subscription*> subscriptions;\n};\n\nunique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)\n{\n return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));\n}\n\nvoid CALLBACK command_perform_helper(__in ULONG_PTR payload)\n{\n WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);\n platform->handle_commands();\n}\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)\n{\n Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);\n Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);\n if (r.is_error()) {\n LOGGER << \"Unable to handle filesystem events: \" << r << \".\" << endl;\n }\n}\n\nResult<string> to_utf8(const wstring &in)\n{\n size_t len = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size() \/ sizeof(WCHAR), \/\/ source string length\n nullptr, \/\/ destination string, null to measure\n 0, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!len) {\n return windows_error_result<string>(\"Unable to measure path as UTF-8\");\n }\n\n char *out = new char[len];\n size_t copied = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size() \/ sizeof(WCHAR), \/\/ source string length\n out, \/\/ destination string\n len, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!copied) {\n delete [] out;\n return windows_error_result<string>(\"Unable to convert path to UTF-8\");\n }\n\n return ok_result(string{out, len});\n}\n\ntemplate < class V >\nResult<V> windows_error_result(const string &prefix)\n{\n return windows_error_result<V>(prefix, GetLastError());\n}\n\ntemplate < class V >\nResult<V> windows_error_result(const string &prefix, DWORD error_code)\n{\n LPVOID msg_buffer;\n\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, \/\/ source\n error_code, \/\/ message ID\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ language ID\n (LPSTR) &msg_buffer, \/\/ output buffer\n 0, \/\/ size\n NULL \/\/ arguments\n );\n\n ostringstream msg;\n msg << prefix << \"\\n (\" << error_code << \") \" << (char*) msg_buffer;\n LocalFree(msg_buffer);\n\n return Result<V>::make_error(msg.str());\n}\n<commit_msg>Extract to_wchar() as a counterpoint to to_utf8()<commit_after>#define WIN32_LEAN_AND_MEAN\n\n#include <windows.h>\n#include <uv.h>\n#include <string>\n#include <sstream>\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"..\/worker_platform.h\"\n#include \"..\/worker_thread.h\"\n#include \"..\/..\/message.h\"\n#include \"..\/..\/log.h\"\n#include \"..\/..\/lock.h\"\n\nusing std::string;\nusing std::wstring;\nusing std::ostringstream;\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::default_delete;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::vector;\nusing std::move;\nusing std::endl;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nstatic void CALLBACK command_perform_helper(__in ULONG_PTR payload);\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);\n\nstatic Result<string> to_utf8(const wstring &in);\n\nstatic Result<wstring> to_wchar(const string &in);\n\ntemplate < class V = void* >\nstatic Result<V> windows_error_result(const string &prefix);\n\ntemplate < class V = void* >\nstatic Result<V> windows_error_result(const string &prefix, DWORD error_code);\n\nclass WindowsWorkerPlatform;\n\nclass Subscription {\npublic:\n Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n {\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n }\n\n ~Subscription()\n {\n CloseHandle(root);\n }\n\n Result<> schedule()\n {\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n &event_helper \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n }\n\n Result<> use_network_size()\n {\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n }\n\n ChannelID get_channel() const {\n return channel;\n }\n\n WindowsWorkerPlatform* get_platform() const {\n return platform;\n }\n\n BYTE *get_written(DWORD written_size) {\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n }\n\n string make_absolute(const string &sub_path)\n {\n ostringstream out;\n\n out << path;\n if (path.back() != '\\\\' && sub_path.front() != '\\\\') {\n out << '\\\\';\n }\n out << sub_path;\n\n return out.str();\n }\n\nprivate:\n ChannelID channel;\n WindowsWorkerPlatform *platform;\n\n string path;\n HANDLE root;\n OVERLAPPED overlapped;\n\n DWORD buffer_size;\n unique_ptr<BYTE[]> buffer;\n unique_ptr<BYTE[]> written;\n};\n\nclass WindowsWorkerPlatform : public WorkerPlatform {\npublic:\n WindowsWorkerPlatform(WorkerThread *thread) :\n WorkerPlatform(thread),\n thread_handle{0}\n {\n int err;\n\n err = uv_mutex_init(&thread_handle_mutex);\n if (err) {\n report_uv_error(err);\n }\n };\n\n ~WindowsWorkerPlatform() override\n {\n uv_mutex_destroy(&thread_handle_mutex);\n }\n\n Result<> wake() override\n {\n Lock lock(thread_handle_mutex);\n\n if (!thread_handle) {\n return ok_result();\n }\n\n BOOL success = QueueUserAPC(\n command_perform_helper,\n thread_handle,\n reinterpret_cast<ULONG_PTR>(this)\n );\n if (!success) {\n return windows_error_result<>(\"Unable to queue APC\");\n }\n\n return ok_result();\n }\n\n Result<> listen() override\n {\n {\n Lock lock(thread_handle_mutex);\n\n HANDLE pseudo_handle = GetCurrentThread();\n BOOL success = DuplicateHandle(\n GetCurrentProcess(), \/\/ Source process\n pseudo_handle, \/\/ Source handle\n GetCurrentProcess(), \/\/ Destination process\n &thread_handle, \/\/ Destination handle\n 0, \/\/ Desired access\n FALSE, \/\/ Inheritable by new processes\n DUPLICATE_SAME_ACCESS \/\/ options\n );\n if (!success) {\n Result<> r = windows_error_result<>(\"Unable to duplicate thread handle\");\n report_error(\"Unable to acquire thread handle\");\n return r;\n }\n }\n\n while (true) {\n SleepEx(INFINITE, true);\n }\n\n report_error(\"listen loop ended unexpectedly\");\n return health_err_result();\n }\n\n Result<> handle_add_command(const ChannelID channel, const string &root_path)\n {\n LOGGER << \"Watching: \" << root_path << endl;\n\n \/\/ Convert the path to a wide-character array\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result<>(\"Unable to measure UTF-16 buffer\");\n }\n unique_ptr<WCHAR[]> root_path_w{new WCHAR[wlen]};\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n root_path_w.get(), \/\/ output buffer\n wlen \/\/ output buffer size\n );\n if (!conv_success) {\n return windows_error_result<>(\"Unable to convert root path to UTF-16\");\n }\n\n \/\/ Open a directory handle\n HANDLE root = CreateFileW(\n root_path_w.get(), \/\/ file name\n FILE_LIST_DIRECTORY, \/\/ desired access\n FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, \/\/ share mode\n NULL, \/\/ security attributes\n OPEN_EXISTING, \/\/ creation disposition\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, \/\/ flags and attributes\n NULL \/\/ template file\n );\n if (root == INVALID_HANDLE_VALUE) {\n return windows_error_result<>(\"Unable to open directory handle\");\n }\n\n \/\/ Allocate and persist the subscription\n Subscription *sub = new Subscription(channel, root, root_path, this);\n auto insert_result = subscriptions.insert(make_pair(channel, sub));\n if (!insert_result.second) {\n delete sub;\n\n ostringstream msg(\"Channel collision: \");\n msg << channel;\n return error_result(msg.str());\n }\n\n LOGGER << \"Now watching directory \" << root_path << \".\" << endl;\n\n return sub->schedule();\n }\n\n Result<> handle_remove_command(const ChannelID channel)\n {\n return ok_result();\n }\n\n Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)\n {\n \/\/ Ensure that the subscription is valid.\n ChannelID channel = sub->get_channel();\n auto it = subscriptions.find(channel);\n if (it == subscriptions.end() || it->second != sub) {\n return ok_result();\n }\n\n \/\/ Handle errors.\n if (error_code == ERROR_OPERATION_ABORTED) {\n LOGGER << \"Operation aborted.\" << endl;\n\n subscriptions.erase(it);\n delete sub;\n\n return ok_result();\n }\n\n if (error_code == ERROR_INVALID_PARAMETER) {\n Result<> resize = sub->use_network_size();\n if (resize.is_error()) return resize;\n\n return sub->schedule();\n }\n\n if (error_code == ERROR_NOTIFY_ENUM_DIR) {\n LOGGER << \"Change buffer overflow. Some events may have been lost.\" << endl;\n return sub->schedule();\n }\n\n if (error_code != ERROR_SUCCESS) {\n return windows_error_result<>(\"Completion callback error\", error_code);\n }\n\n \/\/ Schedule the next completion callback.\n BYTE *base = sub->get_written(num_bytes);\n Result<> next = sub->schedule();\n if (next.is_error()) {\n report_error(string(next.get_error()));\n }\n\n \/\/ Process received events.\n vector<Message> messages;\n bool old_path_seen = false;\n string old_path;\n\n while (true) {\n PFILE_NOTIFY_INFORMATION info = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(base);\n\n wstring wpath{info->FileName, info->FileNameLength};\n Result<string> u8r = to_utf8(wpath);\n if (u8r.is_error()) {\n LOGGER << \"Skipping path: \" << u8r << \".\" << endl;\n } else {\n string path = sub->make_absolute(u8r.get_value());\n\n switch (info->Action) {\n case FILE_ACTION_ADDED:\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_MODIFIED:\n {\n FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_REMOVED:\n {\n FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_RENAMED_OLD_NAME:\n old_path_seen = true;\n old_path = move(path);\n break;\n case FILE_ACTION_RENAMED_NEW_NAME:\n if (old_path_seen) {\n \/\/ Old name received first\n {\n FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n\n old_path_seen = false;\n } else {\n \/\/ No old name. Treat it as a creation\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n }\n break;\n default:\n LOGGER << \"Skipping unexpected action \" << info->Action << \".\" << endl;\n break;\n }\n }\n\n if (info->NextEntryOffset == 0) {\n break;\n }\n base += info->NextEntryOffset;\n }\n\n if (!messages.empty()) {\n Result<> er = emit_all(messages.begin(), messages.end());\n if (er.is_error()) {\n LOGGER << \"Unable to emit messages: \" << er << \".\" << endl;\n }\n }\n\n return next;\n }\n\nprivate:\n uv_mutex_t thread_handle_mutex;\n HANDLE thread_handle;\n\n map<ChannelID, Subscription*> subscriptions;\n};\n\nunique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread)\n{\n return unique_ptr<WorkerPlatform>(new WindowsWorkerPlatform(thread));\n}\n\nvoid CALLBACK command_perform_helper(__in ULONG_PTR payload)\n{\n WindowsWorkerPlatform *platform = reinterpret_cast<WindowsWorkerPlatform*>(payload);\n platform->handle_commands();\n}\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)\n{\n Subscription *sub = static_cast<Subscription*>(overlapped->hEvent);\n Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);\n if (r.is_error()) {\n LOGGER << \"Unable to handle filesystem events: \" << r << \".\" << endl;\n }\n}\n\nResult<string> to_utf8(const wstring &in)\n{\n size_t len = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n nullptr, \/\/ destination string, null to measure\n 0, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!len) {\n return windows_error_result<string>(\"Unable to measure string as UTF-8\");\n }\n\n unique_ptr<char[]> payload(new char[len]);\n size_t copied = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n payload.get(), \/\/ destination string\n len, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!copied) {\n return windows_error_result<string>(\"Unable to convert string to UTF-8\");\n }\n\n return ok_result(string(payload.get(), len));\n}\n\nResult<wstring> to_wchar(const string &in)\n{\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result<wstring>(\"Unable to measure string as wide string\");\n }\n\n unique_ptr<WCHAR[]> payload(new WCHAR[wlen]);\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n payload.get(), \/\/ output buffer\n wlen \/\/ output buffer size (in bytes)\n );\n if (!conv_success) {\n return windows_error_result<wstring>(\"Unable to convert string to wide string\");\n }\n\n return ok_result(wstring(payload.get(), wlen - 1));\n}\n\ntemplate < class V >\nResult<V> windows_error_result(const string &prefix)\n{\n return windows_error_result<V>(prefix, GetLastError());\n}\n\ntemplate < class V >\nResult<V> windows_error_result(const string &prefix, DWORD error_code)\n{\n LPVOID msg_buffer;\n\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, \/\/ source\n error_code, \/\/ message ID\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ language ID\n (LPSTR) &msg_buffer, \/\/ output buffer\n 0, \/\/ size\n NULL \/\/ arguments\n );\n\n ostringstream msg;\n msg << prefix << \"\\n (\" << error_code << \") \" << (char*) msg_buffer;\n LocalFree(msg_buffer);\n\n return Result<V>::make_error(msg.str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/kernel\/fs\/devices\/host_path_entry.h\"\n\n#include \"poly\/mapped_memory.h\"\n#include \"xenia\/kernel\/fs\/devices\/host_path_file.h\"\n\nnamespace xe {\nnamespace kernel {\nnamespace fs {\n\nclass HostPathMemoryMapping : public MemoryMapping {\n public:\n HostPathMemoryMapping(std::unique_ptr<poly::MappedMemory> mmap)\n : MemoryMapping(mmap->data(), mmap->size()), mmap_(std::move(mmap)) {}\n\n private:\n std::unique_ptr<poly::MappedMemory> mmap_;\n};\n\nHostPathEntry::HostPathEntry(Device* device, const char* path,\n const std::wstring& local_path)\n : Entry(device, path),\n local_path_(local_path),\n find_file_(INVALID_HANDLE_VALUE) {}\n\nHostPathEntry::~HostPathEntry() {\n if (find_file_ != INVALID_HANDLE_VALUE) {\n FindClose(find_file_);\n }\n}\n\n#define COMBINE_TIME(t) (((uint64_t)t.dwHighDateTime << 32) | t.dwLowDateTime)\n\nX_STATUS HostPathEntry::QueryInfo(XFileInfo* out_info) {\n assert_not_null(out_info);\n\n WIN32_FILE_ATTRIBUTE_DATA data;\n if (!GetFileAttributesEx(local_path_.c_str(), GetFileExInfoStandard, &data)) {\n return X_STATUS_ACCESS_DENIED;\n }\n\n out_info->creation_time = COMBINE_TIME(data.ftCreationTime);\n out_info->last_access_time = COMBINE_TIME(data.ftLastAccessTime);\n out_info->last_write_time = COMBINE_TIME(data.ftLastWriteTime);\n out_info->change_time = COMBINE_TIME(data.ftLastWriteTime);\n out_info->allocation_size = 4096;\n out_info->file_length =\n ((uint64_t)data.nFileSizeHigh << 32) | data.nFileSizeLow;\n out_info->attributes = (X_FILE_ATTRIBUTES)data.dwFileAttributes;\n return X_STATUS_SUCCESS;\n}\n\nX_STATUS HostPathEntry::QueryDirectory(XDirectoryInfo* out_info, size_t length,\n const char* file_name, bool restart) {\n assert_not_null(out_info);\n\n WIN32_FIND_DATA ffd;\n\n HANDLE handle = find_file_;\n\n if (restart == true && handle != INVALID_HANDLE_VALUE) {\n FindClose(find_file_);\n handle = find_file_ = INVALID_HANDLE_VALUE;\n }\n\n if (handle == INVALID_HANDLE_VALUE) {\n std::wstring target_path = local_path_;\n if (!file_name) {\n target_path = poly::join_paths(target_path, L\"*\");\n } else {\n target_path = poly::join_paths(target_path, poly::to_wstring(file_name));\n }\n handle = find_file_ = FindFirstFile(target_path.c_str(), &ffd);\n if (handle == INVALID_HANDLE_VALUE) {\n if (GetLastError() == ERROR_FILE_NOT_FOUND) {\n return X_STATUS_NO_MORE_FILES;\n }\n return X_STATUS_UNSUCCESSFUL;\n }\n } else {\n if (FindNextFile(handle, &ffd) == FALSE) {\n FindClose(handle);\n find_file_ = INVALID_HANDLE_VALUE;\n return X_STATUS_NO_MORE_FILES;\n }\n }\n\n auto end = (uint8_t*)out_info + length;\n size_t entry_name_length = wcslen(ffd.cFileName);\n if (((uint8_t*)&out_info->file_name[0]) + entry_name_length > end) {\n FindClose(handle);\n find_file_ = INVALID_HANDLE_VALUE;\n return X_STATUS_BUFFER_OVERFLOW;\n }\n\n out_info->next_entry_offset = 0;\n out_info->file_index = 0xCDCDCDCD;\n out_info->creation_time = COMBINE_TIME(ffd.ftCreationTime);\n out_info->last_access_time = COMBINE_TIME(ffd.ftLastAccessTime);\n out_info->last_write_time = COMBINE_TIME(ffd.ftLastWriteTime);\n out_info->change_time = COMBINE_TIME(ffd.ftLastWriteTime);\n out_info->end_of_file =\n ((uint64_t)ffd.nFileSizeHigh << 32) | ffd.nFileSizeLow;\n out_info->allocation_size = 4096;\n out_info->attributes = (X_FILE_ATTRIBUTES)ffd.dwFileAttributes;\n\n out_info->file_name_length = (uint32_t)entry_name_length;\n for (size_t i = 0; i < entry_name_length; ++i) {\n out_info->file_name[i] =\n ffd.cFileName[i] < 256 ? (char)ffd.cFileName[i] : '?';\n }\n\n return X_STATUS_SUCCESS;\n}\n\nstd::unique_ptr<MemoryMapping> HostPathEntry::CreateMemoryMapping(\n Mode map_mode, const size_t offset, const size_t length) {\n auto mmap = poly::MappedMemory::Open(\n local_path_,\n map_mode == Mode::READ ? poly::MappedMemory::Mode::kRead\n : poly::MappedMemory::Mode::kReadWrite,\n offset, length);\n if (!mmap) {\n return nullptr;\n }\n\n return std::make_unique<HostPathMemoryMapping>(std::move(mmap));\n}\n\nX_STATUS HostPathEntry::Open(KernelState* kernel_state, Mode mode, bool async,\n XFile** out_file) {\n DWORD desired_access =\n mode == Mode::READ ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);\n DWORD share_mode = FILE_SHARE_READ;\n DWORD creation_disposition = mode == Mode::READ ? OPEN_EXISTING : OPEN_ALWAYS;\n DWORD flags_and_attributes = async ? FILE_FLAG_OVERLAPPED : 0;\n HANDLE file =\n CreateFile(local_path_.c_str(), desired_access, share_mode, NULL,\n creation_disposition,\n flags_and_attributes | FILE_FLAG_BACKUP_SEMANTICS, NULL);\n if (file == INVALID_HANDLE_VALUE) {\n \/\/ TODO(benvanik): pick correct response.\n return X_STATUS_ACCESS_DENIED;\n }\n\n *out_file = new HostPathFile(kernel_state, mode, this, file);\n return X_STATUS_SUCCESS;\n}\n\n} \/\/ namespace fs\n} \/\/ namespace kernel\n} \/\/ namespace xe\n<commit_msg>Somewhere the file access mode is messed up...<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/kernel\/fs\/devices\/host_path_entry.h\"\n\n#include \"poly\/mapped_memory.h\"\n#include \"xenia\/kernel\/fs\/devices\/host_path_file.h\"\n\nnamespace xe {\nnamespace kernel {\nnamespace fs {\n\nclass HostPathMemoryMapping : public MemoryMapping {\n public:\n HostPathMemoryMapping(std::unique_ptr<poly::MappedMemory> mmap)\n : MemoryMapping(mmap->data(), mmap->size()), mmap_(std::move(mmap)) {}\n\n private:\n std::unique_ptr<poly::MappedMemory> mmap_;\n};\n\nHostPathEntry::HostPathEntry(Device* device, const char* path,\n const std::wstring& local_path)\n : Entry(device, path),\n local_path_(local_path),\n find_file_(INVALID_HANDLE_VALUE) {}\n\nHostPathEntry::~HostPathEntry() {\n if (find_file_ != INVALID_HANDLE_VALUE) {\n FindClose(find_file_);\n }\n}\n\n#define COMBINE_TIME(t) (((uint64_t)t.dwHighDateTime << 32) | t.dwLowDateTime)\n\nX_STATUS HostPathEntry::QueryInfo(XFileInfo* out_info) {\n assert_not_null(out_info);\n\n WIN32_FILE_ATTRIBUTE_DATA data;\n if (!GetFileAttributesEx(local_path_.c_str(), GetFileExInfoStandard, &data)) {\n return X_STATUS_ACCESS_DENIED;\n }\n\n out_info->creation_time = COMBINE_TIME(data.ftCreationTime);\n out_info->last_access_time = COMBINE_TIME(data.ftLastAccessTime);\n out_info->last_write_time = COMBINE_TIME(data.ftLastWriteTime);\n out_info->change_time = COMBINE_TIME(data.ftLastWriteTime);\n out_info->allocation_size = 4096;\n out_info->file_length =\n ((uint64_t)data.nFileSizeHigh << 32) | data.nFileSizeLow;\n out_info->attributes = (X_FILE_ATTRIBUTES)data.dwFileAttributes;\n return X_STATUS_SUCCESS;\n}\n\nX_STATUS HostPathEntry::QueryDirectory(XDirectoryInfo* out_info, size_t length,\n const char* file_name, bool restart) {\n assert_not_null(out_info);\n\n WIN32_FIND_DATA ffd;\n\n HANDLE handle = find_file_;\n\n if (restart == true && handle != INVALID_HANDLE_VALUE) {\n FindClose(find_file_);\n handle = find_file_ = INVALID_HANDLE_VALUE;\n }\n\n if (handle == INVALID_HANDLE_VALUE) {\n std::wstring target_path = local_path_;\n if (!file_name) {\n target_path = poly::join_paths(target_path, L\"*\");\n } else {\n target_path = poly::join_paths(target_path, poly::to_wstring(file_name));\n }\n handle = find_file_ = FindFirstFile(target_path.c_str(), &ffd);\n if (handle == INVALID_HANDLE_VALUE) {\n if (GetLastError() == ERROR_FILE_NOT_FOUND) {\n return X_STATUS_NO_MORE_FILES;\n }\n return X_STATUS_UNSUCCESSFUL;\n }\n } else {\n if (FindNextFile(handle, &ffd) == FALSE) {\n FindClose(handle);\n find_file_ = INVALID_HANDLE_VALUE;\n return X_STATUS_NO_MORE_FILES;\n }\n }\n\n auto end = (uint8_t*)out_info + length;\n size_t entry_name_length = wcslen(ffd.cFileName);\n if (((uint8_t*)&out_info->file_name[0]) + entry_name_length > end) {\n FindClose(handle);\n find_file_ = INVALID_HANDLE_VALUE;\n return X_STATUS_BUFFER_OVERFLOW;\n }\n\n out_info->next_entry_offset = 0;\n out_info->file_index = 0xCDCDCDCD;\n out_info->creation_time = COMBINE_TIME(ffd.ftCreationTime);\n out_info->last_access_time = COMBINE_TIME(ffd.ftLastAccessTime);\n out_info->last_write_time = COMBINE_TIME(ffd.ftLastWriteTime);\n out_info->change_time = COMBINE_TIME(ffd.ftLastWriteTime);\n out_info->end_of_file =\n ((uint64_t)ffd.nFileSizeHigh << 32) | ffd.nFileSizeLow;\n out_info->allocation_size = 4096;\n out_info->attributes = (X_FILE_ATTRIBUTES)ffd.dwFileAttributes;\n\n out_info->file_name_length = (uint32_t)entry_name_length;\n for (size_t i = 0; i < entry_name_length; ++i) {\n out_info->file_name[i] =\n ffd.cFileName[i] < 256 ? (char)ffd.cFileName[i] : '?';\n }\n\n return X_STATUS_SUCCESS;\n}\n\nstd::unique_ptr<MemoryMapping> HostPathEntry::CreateMemoryMapping(\n Mode map_mode, const size_t offset, const size_t length) {\n auto mmap = poly::MappedMemory::Open(\n local_path_,\n map_mode == Mode::READ ? poly::MappedMemory::Mode::kRead\n : poly::MappedMemory::Mode::kReadWrite,\n offset, length);\n if (!mmap) {\n return nullptr;\n }\n\n return std::make_unique<HostPathMemoryMapping>(std::move(mmap));\n}\n\nX_STATUS HostPathEntry::Open(KernelState* kernel_state, Mode mode, bool async,\n XFile** out_file) {\n \/\/ TODO(benvanik): plumb through proper disposition\/access mode.\n DWORD desired_access =\n is_read_only() ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);\n \/\/ mode == Mode::READ ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);\n DWORD share_mode = FILE_SHARE_READ;\n DWORD creation_disposition = mode == Mode::READ ? OPEN_EXISTING : OPEN_ALWAYS;\n DWORD flags_and_attributes = async ? FILE_FLAG_OVERLAPPED : 0;\n HANDLE file =\n CreateFile(local_path_.c_str(), desired_access, share_mode, NULL,\n creation_disposition,\n flags_and_attributes | FILE_FLAG_BACKUP_SEMANTICS, NULL);\n if (file == INVALID_HANDLE_VALUE) {\n \/\/ TODO(benvanik): pick correct response.\n return X_STATUS_ACCESS_DENIED;\n }\n\n *out_file = new HostPathFile(kernel_state, mode, this, file);\n return X_STATUS_SUCCESS;\n}\n\n} \/\/ namespace fs\n} \/\/ namespace kernel\n} \/\/ namespace xe\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_GPU_BASIC_MATRIX_KERNELS_HPP\n#define STAN_MATH_GPU_BASIC_MATRIX_KERNELS_HPP\n\n#include <string>\n\n\/**\n * @file stan\/math\/gpu\/basic_matrix_kernels.hpp\n * @brief Kernel sources for basic matrix operations on the gpu:\n * copy, copy lower\/upper triangular, copy triangular transposed,\n * copy submatrix, init to zeros, init to identity,\n * add, subtract, transpose\n *\/\n\nnamespace stan {\nnamespace math {\n\nstd::string copy_matrix_kernel\n = \"#define A(i,j) A[j*rows+i] \\n\"\n \"#define B(i,j) B[j*rows+i] \\n\"\n \" __kernel void copy( \\n\"\n \" __global double *A, \\n\"\n \" __global double *B, \\n\"\n \" unsigned int rows, \\n\"\n \" unsigned int cols) { \\n\"\n \" int i = get_global_id(0); \\n\"\n \" int j = get_global_id(1); \\n\"\n \" if ( i < rows && j < cols ) { \\n\"\n \" B(i,j) = A(i,j); \\n\"\n \" }\\n\"\n \"}\\n\";\n}\n} \/\/ namespace stan\n#endif\n<commit_msg>Add ifdef STAN_OPENCL to basic_matrix_kernels<commit_after>#ifndef STAN_MATH_GPU_BASIC_MATRIX_KERNELS_HPP\n#define STAN_MATH_GPU_BASIC_MATRIX_KERNELS_HPP\n#ifdef STAN_OPENCL\n#include <string>\n\n\/**\n * @file stan\/math\/gpu\/basic_matrix_kernels.hpp\n * @brief Kernel sources for basic matrix operations on the gpu:\n * copy, copy lower\/upper triangular, copy triangular transposed,\n * copy submatrix, init to zeros, init to identity,\n * add, subtract, transpose\n *\/\n\nnamespace stan {\nnamespace math {\n\nstd::string copy_matrix_kernel\n = \"#define A(i,j) A[j*rows+i] \\n\"\n \"#define B(i,j) B[j*rows+i] \\n\"\n \" __kernel void copy( \\n\"\n \" __global double *A, \\n\"\n \" __global double *B, \\n\"\n \" unsigned int rows, \\n\"\n \" unsigned int cols) { \\n\"\n \" int i = get_global_id(0); \\n\"\n \" int j = get_global_id(1); \\n\"\n \" if ( i < rows && j < cols ) { \\n\"\n \" B(i,j) = A(i,j); \\n\"\n \" }\\n\"\n \"}\\n\";\n}\n} \/\/ namespace stan\n#endif\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 H4314, MIT License *\/\n#include <iostream>\n#include <string>\n\n#define OPT_TRANSFORM \"-o\"\n#define OPT_PRINT \"-p\"\n#define OPT_STATIC \"-a\"\n#define OPT_EXEC \"-e\"\n\nusing std::string;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nint main(int argc, char* argv[]) {\n bool transformEnabled = false;\n bool printEnabled = false;\n bool staticEnabled = false;\n bool execEnabled = false;\n string* fileName = NULL;\n\n for (int i = 1; i < argc; i++) {\n string* arg = new string(argv[i]);\n if (arg->compare(OPT_TRANSFORM) == 0) {\n transformEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_PRINT) == 0) {\n printEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_STATIC) == 0) {\n staticEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_EXEC) == 0) {\n execEnabled = true;\n delete arg;\n } else {\n fileName = arg;\n }\n }\n\n if (fileName == NULL) {\n string errorMessage = \"Erreur, veuillez specifier des arguments\\n\\\n Utilisation :\\n\\\n ..\/lut [-p] [-a] [-e] [-o] source.lt\\n\\\n [-p] affiche le code source reconnu\\n\\\n [-a] analyse le programme de maniere statique\\n\\\n [-e] execute interactivement le programme\\n\\\n [-o] optimise les expressions et instructions\\n\";\n \n cerr << errorMessage << endl;\n return 1;\n }\n\n \/\/ LEXER\n \/\/ PARSER\n if (transformEnabled) {\n cout << \"Transform (optimize) input\" << endl;\n \/\/ TRANSFORM\n }\n if (printEnabled) {\n cout << \"Print (transformed?) input\" << endl;\n \/\/ PRINT\n }\n if (staticEnabled) {\n cout << \"Analyze statically\" << endl;\n \/\/ STATIC\n }\n if (execEnabled) {\n cout << \"Execute\" << endl;\n \/\/ EXEC\n }\n\n return 0;\n}\n<commit_msg>cpplint errors fixed<commit_after>\/* Copyright 2015 H4314, MIT License *\/\n#include <iostream>\n#include <string>\n\n#define OPT_TRANSFORM \"-o\"\n#define OPT_PRINT \"-p\"\n#define OPT_STATIC \"-a\"\n#define OPT_EXEC \"-e\"\n\nusing std::string;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nint main(int argc, char* argv[]) {\n bool transformEnabled = false;\n bool printEnabled = false;\n bool staticEnabled = false;\n bool execEnabled = false;\n string* fileName = NULL;\n\n for (int i = 1; i < argc; i++) {\n string* arg = new string(argv[i]);\n if (arg->compare(OPT_TRANSFORM) == 0) {\n transformEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_PRINT) == 0) {\n printEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_STATIC) == 0) {\n staticEnabled = true;\n delete arg;\n } else if (arg->compare(OPT_EXEC) == 0) {\n execEnabled = true;\n delete arg;\n } else {\n fileName = arg;\n }\n }\n\n if (fileName == NULL) {\n string errorMessage = \"Erreur, veuillez specifier des arguments\\n\"\n \" Utilisation :\\n\"\n \" ..\/lut [-p] [-a] [-e] [-o] source.lt\\n\"\n \" [-p] affiche le code source reconnu\\n\"\n \" [-a] analyse le programme de maniere statique\\n\"\n \" [-e] execute interactivement le programme\\n\"\n \" [-o] optimise les expressions et instructions\\n\";\n\n cerr << errorMessage << endl;\n return 1;\n }\n\n \/\/ LEXER\n \/\/ PARSER\n if (transformEnabled) {\n cout << \"Transform (optimize) input\" << endl;\n \/\/ TRANSFORM\n }\n if (printEnabled) {\n cout << \"Print (transformed?) input\" << endl;\n \/\/ PRINT\n }\n if (staticEnabled) {\n cout << \"Analyze statically\" << endl;\n \/\/ STATIC\n }\n if (execEnabled) {\n cout << \"Execute\" << endl;\n \/\/ EXEC\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ncurses.h>\n\n\/\/ Erase characters which would be left behind\nvoid erase(int row, int col)\n{\n\tmvaddch(row, col, ' ');\n}\n\nvoid move_actor(int row, int col, char symbol)\n{\n\tfor(;;)\n\t{\n\t\tint ch = getch();\n\n\t\tif (ch == 'h' || ch == 'H' || ch == KEY_LEFT || ch == '4')\n\t\t{\n\t\t\terase(row, col);\n\t\t\tcol = col - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'l' || ch == 'L' || ch == KEY_RIGHT || ch == '6')\n\t\t{\n\t\t\terase(row, col);\n\t\t\tcol = col + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'k' || ch == 'K' || ch == KEY_UP || ch == '8')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'j' || ch == 'J' || ch == KEY_DOWN || ch == '2')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\telse if(ch == 'q' || ch == 'Q')\n\t\t\tbreak;\n\t}\n}\n\nvoid game_loop(int ch)\n{\n\t\/\/ Check if our user wants to play\n\tif(ch == 'q' || ch =='Q') return;\n\n\t\/\/ Slap an actor on the screen at (10,10)\n\tint row = 10, col = 10;\n\tchar player_symbol = '@';\n\n\tmvaddch(row, col, player_symbol);\n\n\t\/\/ Allow movement!\n\tmove_actor(row, col, player_symbol);\n}\n\nvoid new_game()\n{\n\t\/\/ Greet the user\n\tprintw(\"Welcome.\\nPress the any key to play.\\nPress [q] to quit!\\n\");\n\n\t\/\/ Wait for user input then scrub\n\tint ch = getch();\n\tclear();\n\n\t\/\/ Run the game loop\n\tgame_loop(ch);\n}\n\nvoid init_ncurses()\n{\n\tinitscr();\n\tclear();\n\tnoecho();\n\tcbreak();\n\tkeypad(stdscr, TRUE);\n\tcurs_set(0);\n}\n\nint main()\n{\n\t\/\/ Initialize the ncurses display\n\tinit_ncurses();\n\n\t\/\/ Start a new game\n\tnew_game();\n\n\t\/\/ Abolish ncurses\n\tendwin();\n\n\treturn 0;\n}\n<commit_msg>Allow diagonal movement.<commit_after>#include <ncurses.h>\n\n\/\/ Erase characters which would be left behind\nvoid erase(int row, int col)\n{\n\tmvaddch(row, col, ' ');\n}\n\nvoid move_actor(int row, int col, char symbol)\n{\n\tfor(;;)\n\t{\n\t\tint ch = getch();\n\n\t\tif (ch == 'h' || ch == 'H' || ch == KEY_LEFT || ch == '4')\n\t\t{\n\t\t\terase(row, col);\n\t\t\tcol = col - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'l' || ch == 'L' || ch == KEY_RIGHT || ch == '6')\n\t\t{\n\t\t\terase(row, col);\n\t\t\tcol = col + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'k' || ch == 'K' || ch == KEY_UP || ch == '8')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'j' || ch == 'J' || ch == KEY_DOWN || ch == '2')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'y' || ch == 'Y' || ch == '7')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row - 1;\n\t\t\tcol = col - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'u' || ch == 'U' || ch == '9')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row - 1;\n\t\t\tcol = col + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'b' || ch == 'B' || ch == '1')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row + 1;\n\t\t\tcol = col - 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\tif (ch == 'n' || ch == 'N' || ch == '3')\n\t\t{\n\t\t\terase(row, col);\n\t\t\trow = row + 1;\n\t\t\tcol = col + 1;\n\t\t\tmvaddch(row, col, symbol);\n\t\t\trefresh();\n\t\t}\n\t\telse if(ch == 'q' || ch == 'Q')\n\t\t\tbreak;\n\t}\n}\n\nvoid game_loop(int ch)\n{\n\t\/\/ Check if our user wants to play\n\tif(ch == 'q' || ch =='Q') return;\n\n\t\/\/ Slap an actor on the screen at (10,10)\n\tint row = 10, col = 10;\n\tchar player_symbol = '@';\n\n\tmvaddch(row, col, player_symbol);\n\n\t\/\/ Allow movement!\n\tmove_actor(row, col, player_symbol);\n}\n\nvoid new_game()\n{\n\t\/\/ Greet the user\n\tprintw(\"Welcome.\\nPress the any key to play.\\nPress [q] to quit!\\n\");\n\n\t\/\/ Wait for user input then scrub\n\tint ch = getch();\n\tclear();\n\n\t\/\/ Run the game loop\n\tgame_loop(ch);\n}\n\nvoid init_ncurses()\n{\n\tinitscr();\n\tclear();\n\tnoecho();\n\tcbreak();\n\tkeypad(stdscr, TRUE);\n\tcurs_set(0);\n}\n\nint main()\n{\n\t\/\/ Initialize the ncurses display\n\tinit_ncurses();\n\n\t\/\/ Start a new game\n\tnew_game();\n\n\t\/\/ Abolish ncurses\n\tendwin();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ForwardChainer.cc\n *\n * Copyright (C) 2014,2015 Misgana Bayetta\n *\n * Author: Misgana Bayetta <misgana.bayetta@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/util\/Logger.h>\n#include <opencog\/atoms\/bind\/PatternLink.h>\n#include <opencog\/atomutils\/AtomUtils.h>\n#include <opencog\/query\/DefaultImplicator.h>\n#include <opencog\/rule-engine\/Rule.h>\n#include <opencog\/atoms\/bind\/BindLink.h>\n#include \"ForwardChainer.h\"\n#include \"ForwardChainerCallBack.h\"\n\nusing namespace opencog;\n\nForwardChainer::ForwardChainer(AtomSpace& as, Handle rbs) :\n\t_as(as), _rec(_as), _rbs(rbs), _configReader(as, rbs), _fcmem(&as)\n{\n init();\n}\n\nvoid ForwardChainer::init()\n{\n _fcmem.set_search_in_af(_configReader.get_attention_allocation());\n _fcmem.set_rules(_configReader.get_rules());\n _fcmem.set_cur_rule(nullptr);\n\n \/\/ Provide a logger\n _log = NULL;\n setLogger(new opencog::Logger(\"forward_chainer.log\", Logger::FINE, true));\n}\n\nvoid ForwardChainer::setLogger(Logger* log)\n{\n if (_log)\n delete _log;\n _log = log;\n}\n\nLogger* ForwardChainer::getLogger()\n{\n return _log;\n}\n\n\/**\n * Does one step forward chaining\n *\n * @param fcb a concrete implementation of of ForwardChainerCallBack class \n *\/\nUnorderedHandleSet ForwardChainer::do_step(bool search_focus_set\/* = false*\/)\n{\n\n Handle hsource = choose_next_source(_fcmem);\n\n _log->debug(\"[ForwardChainer] Next source %s\", hsource->toString().c_str());\n\n _fcmem.set_source(hsource);\n\n HandleSeq derived_rhandles;\n\n \/\/choose a rule that source unifies with one of its premises.\n Rule *rule = choose_rule(hsource, false);\n if (rule) {\n _fcmem.set_cur_rule(rule);\n derived_rhandles = derive_rules(hsource, rule);\n\n } else {\n \/\/choose rule that unifies that source unifies with sub-atoms of its premises.\n rule = choose_rule(hsource, true);\n\n if (rule) {\n _fcmem.set_cur_rule(rule);\n derived_rhandles = derive_rules(hsource, rule,\n true);\n }\n }\n\n _log->debug( \"Derived rule size = %d\", derived_rhandles.size());\n\n UnorderedHandleSet products;\n\n for (Handle rhandle : derived_rhandles) {\n HandleSeq temp_result = apply_rule(rhandle,search_focus_set);\n\n std::copy(temp_result.begin(), temp_result.end(),\n std::inserter(products, products.end()));\n }\n\n return products;\n}\n\nvoid ForwardChainer::do_chain(Handle hsource, HandleSeq focus_set)\n{\n\n validate(hsource,focus_set);\n\n _fcmem.set_focus_set(focus_set);\n\n HandleSeq init_sources;\n \/\/Accept set of initial sources wrapped in a SET_LINK\n if(LinkCast(hsource) and hsource->getType() == SET_LINK)\n {\n init_sources = _as.get_outgoing(hsource);\n\n \/\/Relex2Logic uses this.TODO make a separate class\n \/\/to handle this robustly.\n if(init_sources.empty())\n {\n bool search_in_af = not focus_set.empty();\n apply_all_rules(search_in_af);\n return;\n }\n\n }\n else\n {\n init_sources.push_back(hsource);\n }\n\n \/\/ Variable fulfillment query.\n UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,\n { VARIABLE_NODE });\n if (not var_nodes.empty())\n return do_pm(hsource, var_nodes);\n\n \/\/ Default forward chaining\n _fcmem.update_potential_sources(init_sources);\n\n auto max_iter = _configReader.get_maximum_iterations();\n\n while (_iteration < max_iter \/*OR other termination criteria*\/) {\n\n _log->debug(\"Iteration %d\", _iteration);\n\n UnorderedHandleSet products;\n\n if (focus_set.empty())\n products = do_step(false);\n else\n products = do_step(true);\n\n _fcmem.add_rules_product(_iteration,\n HandleSeq(products.begin(), products.end()));\n _fcmem.update_potential_sources(\n HandleSeq(products.begin(), products.end()));\n\n _iteration++;\n }\n\n _log->debug(\"[ForwardChainer] finished forwarch chaining.\");\n}\n\n\/**\n * Does pattern matching for a variable containing query.\n * @param source a variable containing handle passed as an input to the pattern matcher\n * @param var_nodes the VariableNodes in @param hsource\n * @param fcb a forward chainer callback implementation used here only for choosing rules\n * that contain @param hsource in their implicant\n *\/\nvoid ForwardChainer::do_pm(const Handle& hsource,\n const UnorderedHandleSet& var_nodes,\n ForwardChainerCallBack& fcb)\n{\n DefaultImplicator impl(&_as);\n impl.implicand = hsource;\n HandleSeq vars;\n for (auto h : var_nodes)\n vars.push_back(h);\n _fcmem.set_source(hsource);\n Handle hvar_list = _as.add_link(VARIABLE_LIST, vars);\n Handle hclause = _as.add_link(AND_LINK, hsource);\n\n \/\/ Run the pattern matcher, find all patterns that satisfy the\n \/\/ the clause, with the given variables in it.\n PatternLinkPtr sl(createPatternLink(hvar_list, hclause));\n sl->satisfy(impl);\n\n \/\/ Update result\n _fcmem.add_rules_product(0, impl.get_result_list());\n\n \/\/ Delete the AND_LINK and LIST_LINK\n _as.remove_atom(hvar_list);\n _as.remove_atom(hclause);\n\n \/\/!Additionally, find applicable rules and apply.\n vector<Rule*> rules = fcb.choose_rules(_fcmem);\n for (Rule* rule : rules) {\n BindLinkPtr bl(BindLinkCast(rule->get_handle()));\n DefaultImplicator impl(&_as);\n impl.implicand = bl->get_implicand();\n bl->imply(impl);\n _fcmem.set_cur_rule(rule);\n _fcmem.add_rules_product(0, impl.get_result_list());\n }\n}\n\/**\n * Invokes pattern matcher using each rule declared in the configuration file.\n *\/\nvoid ForwardChainer::do_pm()\n{\n \/\/! Do pattern matching using the rules declared in the declaration file\n _log->info(\"Forward chaining on the rule-based system %s \"\n \"declared in %s\", _rbs->toString().c_str());\n vector<Rule*> rules = _fcmem.get_rules();\n for (Rule* rule : rules) {\n _log->info(\"Applying rule %s on \", rule->get_name().c_str());\n BindLinkPtr bl(BindLinkCast(rule->get_handle()));\n DefaultImplicator impl(&_as);\n impl.implicand = bl->get_implicand();\n bl->imply(impl);\n _fcmem.set_cur_rule(rule);\n\n _log->info(\"OUTPUTS\");\n for (auto h : impl.get_result_list())\n _log->info(\"%s\", h->toString().c_str());\n\n _fcmem.add_rules_product(0, impl.get_result_list());\n }\n\n}\n\nHandleSeq ForwardChainer::get_chaining_result()\n{\n return _fcmem.get_result();\n}\n\nRule* ForwardChainer::choose_rule(Handle hsource, bool subatom_match)\n{\n \/\/TODO move this somewhere else\n std::map<Rule*, float> rule_weight;\n for (Rule* r : _fcmem.get_rules())\n rule_weight[r] = r->get_weight();\n\n _log->debug(\"[ForwardChainer] %d rules to be searched\",rule_weight.size());\n\n \/\/Select a rule among the admissible rules in the rule-base via stochastic\n \/\/selection,based on the weights of the rules in the current context.\n Rule* rule = nullptr;\n bool unifiable = false;\n\n if (subatom_match) {\n _log->debug(\"[ForwardChainer] Subatom-unifying. %s\",(hsource->toShortString()).c_str());\n\n while (!unifiable and !rule_weight.empty()) {\n Rule* temp = _rec.tournament_select(rule_weight);\n\n if (subatom_unify(hsource, temp)) {\n unifiable = true;\n rule = temp;\n break;\n }\n rule_weight.erase(temp);\n }\n\n } else {\n _log->debug(\"[ForwardChainer] Unifying. %s\",(hsource->toShortString()).c_str());\n\n while (!unifiable and !rule_weight.empty()) {\n Rule *temp = _rec.tournament_select(rule_weight);\n HandleSeq hs = temp->get_implicant_seq();\n\n for (Handle target : hs) {\n if (unify(hsource, target, temp)) {\n unifiable = true;\n rule = temp;\n break;\n }\n }\n rule_weight.erase(temp);\n }\n }\n\n if(nullptr != rule)\n _log->debug(\"[ForwardChainer] Selected rule is %s\",\n (rule->get_handle())->toShortString().c_str());\n else\n _log->debug(\"[ForwardChainer] No match found.\");\n\n return rule;\n};\nHandleSeq ForwardChainer::apply_rule(Handle rhandle,bool search_in_focus_set \/*=false*\/)\n{\n HandleSeq result;\n\n if (search_in_focus_set) {\n \/\/This restricts PM to look only in the focus set\n AtomSpace focus_set_as;\n\n \/\/Add focus set atoms to focus_set atomspace\n HandleSeq focus_set_atoms = _fcmem.get_focus_set();\n for (Handle h : focus_set_atoms)\n focus_set_as.add_atom(h);\n\n \/\/Add source atoms to focus_set atomspace\n HandleSeq sources = _fcmem.get_potential_sources();\n for (Handle h : sources)\n focus_set_as.add_atom(h);\n\n \/\/rhandle may introduce a new atoms that satisfies condition for the output\n \/\/In order to prevent this undesirable effect, lets store rhandle in a child\n \/\/atomspace of parent focus_set_as so that PM will never be able to find this\n \/\/new undesired atom created from partial grounding.\n AtomSpace derived_rule_as(&focus_set_as);\n Handle rhcpy = derived_rule_as.add_atom(rhandle);\n\n BindLinkPtr bl = BindLinkCast(rhcpy);\n\n FocusSetPMCB fs_pmcb(&derived_rule_as, &_as);\n fs_pmcb.implicand = bl->get_implicand();\n\n _log->debug(\"Applying rule in focus set %s \",(rhcpy->toShortString()).c_str());\n\n std::cout << \"ATOMSPACE:\" << derived_rule_as << std::endl;\n bl->imply(fs_pmcb);\n\n result = fs_pmcb.get_result_list();\n\n _log->debug(\n \"Result is %s \",\n ((_as.add_link(SET_LINK, result))->toShortString()).c_str());\n\n }\n \/\/Search the whole atomspace\n else {\n AtomSpace derived_rule_as(&_as);\n\n Handle rhcpy = derived_rule_as.add_atom(rhandle);\n\n _log->debug(\"Applying rule on atomspace %s \",(rhcpy->toShortString()).c_str());\n\n Handle h = bindlink(&derived_rule_as,rhcpy);\n\n _log->debug(\"Result is %s \",(h->toShortString()).c_str());\n\n result = derived_rule_as.get_outgoing(h);\n }\n\n \/\/add the results back to main atomspace\n for(Handle h:result) _as.add_atom(h);\n\n return result;\n}\n<commit_msg>Used for R2L case<commit_after>\/*\n * ForwardChainer.cc\n *\n * Copyright (C) 2014,2015 Misgana Bayetta\n *\n * Author: Misgana Bayetta <misgana.bayetta@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/util\/Logger.h>\n#include <opencog\/atoms\/bind\/PatternLink.h>\n#include <opencog\/atomutils\/AtomUtils.h>\n#include <opencog\/query\/DefaultImplicator.h>\n#include <opencog\/rule-engine\/Rule.h>\n#include <opencog\/atoms\/bind\/BindLink.h>\n#include \"ForwardChainer.h\"\n#include \"ForwardChainerCallBack.h\"\n\nusing namespace opencog;\n\nForwardChainer::ForwardChainer(AtomSpace& as, Handle rbs) :\n\t_as(as), _rec(_as), _rbs(rbs), _configReader(as, rbs), _fcmem(&as)\n{\n init();\n}\n\nvoid ForwardChainer::init()\n{\n _fcmem.set_search_in_af(_configReader.get_attention_allocation());\n _fcmem.set_rules(_configReader.get_rules());\n _fcmem.set_cur_rule(nullptr);\n\n \/\/ Provide a logger\n _log = NULL;\n setLogger(new opencog::Logger(\"forward_chainer.log\", Logger::FINE, true));\n}\n\nvoid ForwardChainer::setLogger(Logger* log)\n{\n if (_log)\n delete _log;\n _log = log;\n}\n\nLogger* ForwardChainer::getLogger()\n{\n return _log;\n}\n\n\/**\n * Does one step forward chaining\n *\n * @param fcb a concrete implementation of of ForwardChainerCallBack class \n *\/\nUnorderedHandleSet ForwardChainer::do_step(bool search_focus_set\/* = false*\/)\n{\n\n Handle hsource = choose_next_source(_fcmem);\n\n _log->debug(\"[ForwardChainer] Next source %s\", hsource->toString().c_str());\n\n _fcmem.set_source(hsource);\n\n HandleSeq derived_rhandles;\n\n \/\/choose a rule that source unifies with one of its premises.\n Rule *rule = choose_rule(hsource, false);\n if (rule) {\n _fcmem.set_cur_rule(rule);\n derived_rhandles = derive_rules(hsource, rule);\n\n } else {\n \/\/choose rule that unifies that source unifies with sub-atoms of its premises.\n rule = choose_rule(hsource, true);\n\n if (rule) {\n _fcmem.set_cur_rule(rule);\n derived_rhandles = derive_rules(hsource, rule,\n true);\n }\n }\n\n _log->debug( \"Derived rule size = %d\", derived_rhandles.size());\n\n UnorderedHandleSet products;\n\n for (Handle rhandle : derived_rhandles) {\n HandleSeq temp_result = apply_rule(rhandle,search_focus_set);\n\n std::copy(temp_result.begin(), temp_result.end(),\n std::inserter(products, products.end()));\n }\n\n return products;\n}\n\nvoid ForwardChainer::do_chain(Handle hsource, HandleSeq focus_set)\n{\n\n validate(hsource,focus_set);\n\n _fcmem.set_focus_set(focus_set);\n\n HandleSeq init_sources;\n \/\/Accept set of initial sources wrapped in a SET_LINK\n if(LinkCast(hsource) and hsource->getType() == SET_LINK)\n {\n init_sources = _as.get_outgoing(hsource);\n\n \/\/Relex2Logic uses this.TODO make a separate class\n \/\/to handle this robustly.\n if(init_sources.empty())\n {\n bool search_in_af = not focus_set.empty();\n apply_all_rules(search_in_af);\n return;\n }\n\n }\n else\n {\n init_sources.push_back(hsource);\n }\n\n \/\/ Variable fulfillment query.\n UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource,\n { VARIABLE_NODE });\n if (not var_nodes.empty())\n return do_pm(hsource, var_nodes);\n\n \/\/ Default forward chaining\n _fcmem.update_potential_sources(init_sources);\n\n auto max_iter = _configReader.get_maximum_iterations();\n\n while (_iteration < max_iter \/*OR other termination criteria*\/) {\n\n _log->debug(\"Iteration %d\", _iteration);\n\n UnorderedHandleSet products;\n\n if (focus_set.empty())\n products = do_step(false);\n else\n products = do_step(true);\n\n _fcmem.add_rules_product(_iteration,\n HandleSeq(products.begin(), products.end()));\n _fcmem.update_potential_sources(\n HandleSeq(products.begin(), products.end()));\n\n _iteration++;\n }\n\n _log->debug(\"[ForwardChainer] finished forwarch chaining.\");\n}\n\n\/**\n * Does pattern matching for a variable containing query.\n * @param source a variable containing handle passed as an input to the pattern matcher\n * @param var_nodes the VariableNodes in @param hsource\n * @param fcb a forward chainer callback implementation used here only for choosing rules\n * that contain @param hsource in their implicant\n *\/\nvoid ForwardChainer::do_pm(const Handle& hsource,\n const UnorderedHandleSet& var_nodes,\n ForwardChainerCallBack& fcb)\n{\n DefaultImplicator impl(&_as);\n impl.implicand = hsource;\n HandleSeq vars;\n for (auto h : var_nodes)\n vars.push_back(h);\n _fcmem.set_source(hsource);\n Handle hvar_list = _as.add_link(VARIABLE_LIST, vars);\n Handle hclause = _as.add_link(AND_LINK, hsource);\n\n \/\/ Run the pattern matcher, find all patterns that satisfy the\n \/\/ the clause, with the given variables in it.\n PatternLinkPtr sl(createPatternLink(hvar_list, hclause));\n sl->satisfy(impl);\n\n \/\/ Update result\n _fcmem.add_rules_product(0, impl.get_result_list());\n\n \/\/ Delete the AND_LINK and LIST_LINK\n _as.remove_atom(hvar_list);\n _as.remove_atom(hclause);\n\n \/\/!Additionally, find applicable rules and apply.\n vector<Rule*> rules = fcb.choose_rules(_fcmem);\n for (Rule* rule : rules) {\n BindLinkPtr bl(BindLinkCast(rule->get_handle()));\n DefaultImplicator impl(&_as);\n impl.implicand = bl->get_implicand();\n bl->imply(impl);\n _fcmem.set_cur_rule(rule);\n _fcmem.add_rules_product(0, impl.get_result_list());\n }\n}\n\n\/**\n * Applies all rules in the rule base.\n *\n * @param search_focus_set flag for searching focus set.\n *\/\nvoid ForwardChainer::apply_all_rules(bool search_focus_set \/*= false*\/)\n{\n vector<Rule*> rules = _fcmem.get_rules();\n\n for (Rule* rule : rules) {\n _fcmem.set_cur_rule(rule);\n HandleSeq hs = apply_rule(rule->get_handle(), search_focus_set);\n\n \/\/Update\n _fcmem.add_rules_product(0, hs);\n _fcmem.update_potential_sources(hs);\n }\n\n}\n\nHandleSeq ForwardChainer::get_chaining_result()\n{\n return _fcmem.get_result();\n}\n\nRule* ForwardChainer::choose_rule(Handle hsource, bool subatom_match)\n{\n \/\/TODO move this somewhere else\n std::map<Rule*, float> rule_weight;\n for (Rule* r : _fcmem.get_rules())\n rule_weight[r] = r->get_weight();\n\n _log->debug(\"[ForwardChainer] %d rules to be searched\",rule_weight.size());\n\n \/\/Select a rule among the admissible rules in the rule-base via stochastic\n \/\/selection,based on the weights of the rules in the current context.\n Rule* rule = nullptr;\n bool unifiable = false;\n\n if (subatom_match) {\n _log->debug(\"[ForwardChainer] Subatom-unifying. %s\",(hsource->toShortString()).c_str());\n\n while (!unifiable and !rule_weight.empty()) {\n Rule* temp = _rec.tournament_select(rule_weight);\n\n if (subatom_unify(hsource, temp)) {\n unifiable = true;\n rule = temp;\n break;\n }\n rule_weight.erase(temp);\n }\n\n } else {\n _log->debug(\"[ForwardChainer] Unifying. %s\",(hsource->toShortString()).c_str());\n\n while (!unifiable and !rule_weight.empty()) {\n Rule *temp = _rec.tournament_select(rule_weight);\n HandleSeq hs = temp->get_implicant_seq();\n\n for (Handle target : hs) {\n if (unify(hsource, target, temp)) {\n unifiable = true;\n rule = temp;\n break;\n }\n }\n rule_weight.erase(temp);\n }\n }\n\n if(nullptr != rule)\n _log->debug(\"[ForwardChainer] Selected rule is %s\",\n (rule->get_handle())->toShortString().c_str());\n else\n _log->debug(\"[ForwardChainer] No match found.\");\n\n return rule;\n};\nHandleSeq ForwardChainer::apply_rule(Handle rhandle,bool search_in_focus_set \/*=false*\/)\n{\n HandleSeq result;\n\n if (search_in_focus_set) {\n \/\/This restricts PM to look only in the focus set\n AtomSpace focus_set_as;\n\n \/\/Add focus set atoms to focus_set atomspace\n HandleSeq focus_set_atoms = _fcmem.get_focus_set();\n for (Handle h : focus_set_atoms)\n focus_set_as.add_atom(h);\n\n \/\/Add source atoms to focus_set atomspace\n HandleSeq sources = _fcmem.get_potential_sources();\n for (Handle h : sources)\n focus_set_as.add_atom(h);\n\n \/\/rhandle may introduce a new atoms that satisfies condition for the output\n \/\/In order to prevent this undesirable effect, lets store rhandle in a child\n \/\/atomspace of parent focus_set_as so that PM will never be able to find this\n \/\/new undesired atom created from partial grounding.\n AtomSpace derived_rule_as(&focus_set_as);\n Handle rhcpy = derived_rule_as.add_atom(rhandle);\n\n BindLinkPtr bl = BindLinkCast(rhcpy);\n\n FocusSetPMCB fs_pmcb(&derived_rule_as, &_as);\n fs_pmcb.implicand = bl->get_implicand();\n\n _log->debug(\"Applying rule in focus set %s \",(rhcpy->toShortString()).c_str());\n\n std::cout << \"ATOMSPACE:\" << derived_rule_as << std::endl;\n bl->imply(fs_pmcb);\n\n result = fs_pmcb.get_result_list();\n\n _log->debug(\n \"Result is %s \",\n ((_as.add_link(SET_LINK, result))->toShortString()).c_str());\n\n }\n \/\/Search the whole atomspace\n else {\n AtomSpace derived_rule_as(&_as);\n\n Handle rhcpy = derived_rule_as.add_atom(rhandle);\n\n _log->debug(\"Applying rule on atomspace %s \",(rhcpy->toShortString()).c_str());\n\n Handle h = bindlink(&derived_rule_as,rhcpy);\n\n _log->debug(\"Result is %s \",(h->toShortString()).c_str());\n\n result = derived_rule_as.get_outgoing(h);\n }\n\n \/\/add the results back to main atomspace\n for(Handle h:result) _as.add_atom(h);\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ Licensed under the MIT License.\n\n#include \"core\/optimizer\/initializer.h\"\n#include \"core\/optimizer\/matmul_add_fusion.h\"\n#include \"core\/graph\/graph_utils.h\"\n#include <deque>\n\nusing namespace ONNX_NAMESPACE;\nusing namespace ::onnxruntime::common;\nnamespace onnxruntime {\n\nStatus MatMulAddFusion::ApplyImpl(Graph& graph, bool& modified, int graph_level) const {\n GraphViewer graph_viewer(graph);\n const auto& node_topology_list = graph_viewer.GetNodesInTopologicalOrder();\n std::deque<onnxruntime::NodeIndex> removed_nodes;\n\n for (auto node_index : node_topology_list) {\n auto& node = *graph.GetNode(node_index);\n ORT_RETURN_IF_ERROR(Recurse(node, modified, graph_level));\n\n if (!graph_utils::IsSupportedOptypeVersionAndDomain(node, \"MatMul\", {1, 9}) ||\n !graph_utils::IsSupportedProvider(node, GetCompatibleExecutionProviders()) ||\n node.GetOutputEdgesCount() != 1) {\n continue;\n }\n\n auto next_node_itr = node.OutputNodesBegin();\n if (next_node_itr == node.OutputNodesEnd()) {\n continue;\n }\n\n const Node& next_node = (*next_node_itr);\n if (!graph_utils::IsSupportedOptypeVersionAndDomain(next_node, \"Add\", {7}) ||\n next_node.GetExecutionProviderType() != node.GetExecutionProviderType()) {\n continue;\n }\n\n Node& matmul_node = node;\n Node& add_node = const_cast<Node&>(next_node);\n std::vector<NodeArg> input_args;\n std::vector<NodeArg> output_args;\n auto matmul_input_defs = matmul_node.MutableInputDefs();\n auto add_input_defs = add_node.MutableInputDefs();\n\n \/\/ Gemm only support float, so the inputs of MatMul\n auto matmul_type = matmul_input_defs[0]->Type();\n auto add_type = add_input_defs[0]->Type();\n if ((*matmul_type) != \"tensor(float)\" || (*add_type) != \"tensor(float)\") {\n continue;\n }\n\n \/\/ Gemm only support Matrix, need to check the shape of MatMul and Add\n auto matmul_a_shape = matmul_input_defs[0]->Shape();\n auto matmul_b_shape = matmul_input_defs[1]->Shape();\n if (nullptr == matmul_a_shape || nullptr == matmul_b_shape) {\n continue;\n }\n if (1 == matmul_a_shape->dim_size() && 2 == matmul_b_shape->dim_size()) {\n \/\/ MatMul has shape [K] * [K, N], reset it to [1, K] * [K, N], so that it can work for Gemm\n auto mutable_matmul_a_shape = const_cast<ONNX_NAMESPACE::TensorShapeProto*>(matmul_a_shape);\n auto dim_0 = mutable_matmul_a_shape->mutable_dim(0);\n auto dim_1 = (const_cast<ONNX_NAMESPACE::TensorShapeProto*>(matmul_a_shape))->add_dim();\n (*dim_1) = (*dim_0);\n dim_0->set_dim_value(1);\n }\n if (2 != matmul_a_shape->dim_size() || 2 != matmul_b_shape->dim_size()) {\n \/\/ Gemm only support Matrix\n continue;\n }\n\n auto matmul_output_name = matmul_node.OutputDefs()[0]->Name();\n auto gemm_input_defs = matmul_input_defs;\n if (matmul_output_name == add_input_defs[0]->Name()) {\n \/\/ matmul output as Add_A, should use Add_B as input C for gemm\n \/\/ Gemm only support unidirectional broadcast on C\n if (add_input_defs[1]->Shape()->dim_size() > 2) {\n continue;\n }\n gemm_input_defs.push_back(add_input_defs[1]);\n } else {\n \/\/ matmul output as Add_B, should use Add_A as input C for gemm\n \/\/ Gemm only support unidirectional broadcast on C\n if (add_input_defs[0]->Shape()->dim_size() > 2) {\n continue;\n }\n gemm_input_defs.push_back(add_input_defs[0]);\n }\n\n Node& gemm_node = graph.AddNode(graph.GenerateNodeName(\"gemm\"),\n \"Gemm\",\n \"fused Matmul and Add \" + add_node.OpType(),\n gemm_input_defs,\n add_node.MutableOutputDefs());\n\n \/\/ Assign provider to this new node. Provider should be same as the provider for old node.\n gemm_node.SetExecutionProviderType(matmul_node.GetExecutionProviderType());\n\n removed_nodes.push_front(matmul_node.Index());\n removed_nodes.push_front(add_node.Index());\n }\n\n \/\/ Have to remove node in reversed order for now to walk around the issue in RemoveNode\n for (onnxruntime::NodeIndex removed_node : removed_nodes) {\n graph.RemoveNode(removed_node);\n }\n\n if (!removed_nodes.empty()) {\n modified = true;\n }\n\n return Status::OK();\n}\n} \/\/ namespace onnxruntime\n<commit_msg>Enable float16 MatMul+Add -> GEMM fusion for performance boost (#1506)<commit_after>\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ Licensed under the MIT License.\n\n#include \"core\/optimizer\/initializer.h\"\n#include \"core\/optimizer\/matmul_add_fusion.h\"\n#include \"core\/graph\/graph_utils.h\"\n#include <deque>\n\nusing namespace ONNX_NAMESPACE;\nusing namespace ::onnxruntime::common;\nnamespace onnxruntime {\n\nStatus MatMulAddFusion::ApplyImpl(Graph& graph, bool& modified, int graph_level) const {\n GraphViewer graph_viewer(graph);\n const auto& node_topology_list = graph_viewer.GetNodesInTopologicalOrder();\n std::deque<onnxruntime::NodeIndex> removed_nodes;\n\n for (auto node_index : node_topology_list) {\n auto& node = *graph.GetNode(node_index);\n ORT_RETURN_IF_ERROR(Recurse(node, modified, graph_level));\n\n if (!graph_utils::IsSupportedOptypeVersionAndDomain(node, \"MatMul\", {1, 9}) ||\n !graph_utils::IsSupportedProvider(node, GetCompatibleExecutionProviders()) ||\n node.GetOutputEdgesCount() != 1) {\n continue;\n }\n\n auto next_node_itr = node.OutputNodesBegin();\n if (next_node_itr == node.OutputNodesEnd()) {\n continue;\n }\n\n const Node& next_node = (*next_node_itr);\n if (!graph_utils::IsSupportedOptypeVersionAndDomain(next_node, \"Add\", {7}) ||\n next_node.GetExecutionProviderType() != node.GetExecutionProviderType()) {\n continue;\n }\n\n Node& matmul_node = node;\n Node& add_node = const_cast<Node&>(next_node);\n std::vector<NodeArg> input_args;\n std::vector<NodeArg> output_args;\n auto matmul_input_defs = matmul_node.MutableInputDefs();\n auto add_input_defs = add_node.MutableInputDefs();\n\n \/\/ Gemm requires that inputs be the same data type and both floating point (float32\/float16).\n auto matmul_type = matmul_input_defs[0]->Type();\n auto add_type = add_input_defs[0]->Type();\n if ((*matmul_type) != (*add_type)) {\n continue;\n }\n if ((*matmul_type) != \"tensor(float)\" && (*matmul_type) != \"tensor(float16)\") {\n continue;\n }\n\n \/\/ Gemm only support Matrix, need to check the shape of MatMul and Add\n auto matmul_a_shape = matmul_input_defs[0]->Shape();\n auto matmul_b_shape = matmul_input_defs[1]->Shape();\n if (nullptr == matmul_a_shape || nullptr == matmul_b_shape) {\n continue;\n }\n if (1 == matmul_a_shape->dim_size() && 2 == matmul_b_shape->dim_size()) {\n \/\/ MatMul has shape [K] * [K, N], reset it to [1, K] * [K, N], so that it can work for Gemm\n auto mutable_matmul_a_shape = const_cast<ONNX_NAMESPACE::TensorShapeProto*>(matmul_a_shape);\n auto dim_0 = mutable_matmul_a_shape->mutable_dim(0);\n auto dim_1 = (const_cast<ONNX_NAMESPACE::TensorShapeProto*>(matmul_a_shape))->add_dim();\n (*dim_1) = (*dim_0);\n dim_0->set_dim_value(1);\n }\n if (2 != matmul_a_shape->dim_size() || 2 != matmul_b_shape->dim_size()) {\n \/\/ Gemm only support Matrix\n continue;\n }\n\n auto matmul_output_name = matmul_node.OutputDefs()[0]->Name();\n auto gemm_input_defs = matmul_input_defs;\n if (matmul_output_name == add_input_defs[0]->Name()) {\n \/\/ matmul output as Add_A, should use Add_B as input C for gemm\n \/\/ Gemm only support unidirectional broadcast on C\n if (add_input_defs[1]->Shape()->dim_size() > 2) {\n continue;\n }\n gemm_input_defs.push_back(add_input_defs[1]);\n } else {\n \/\/ matmul output as Add_B, should use Add_A as input C for gemm\n \/\/ Gemm only support unidirectional broadcast on C\n if (add_input_defs[0]->Shape()->dim_size() > 2) {\n continue;\n }\n gemm_input_defs.push_back(add_input_defs[0]);\n }\n\n Node& gemm_node = graph.AddNode(graph.GenerateNodeName(\"gemm\"),\n \"Gemm\",\n \"fused Matmul and Add \" + add_node.OpType(),\n gemm_input_defs,\n add_node.MutableOutputDefs());\n\n \/\/ Assign provider to this new node. Provider should be same as the provider for old node.\n gemm_node.SetExecutionProviderType(matmul_node.GetExecutionProviderType());\n\n removed_nodes.push_front(matmul_node.Index());\n removed_nodes.push_front(add_node.Index());\n }\n\n \/\/ Have to remove node in reversed order for now to walk around the issue in RemoveNode\n for (onnxruntime::NodeIndex removed_node : removed_nodes) {\n graph.RemoveNode(removed_node);\n }\n\n if (!removed_nodes.empty()) {\n modified = true;\n }\n\n return Status::OK();\n}\n} \/\/ namespace onnxruntime\n<|endoftext|>"} {"text":"<commit_before>\/** @mainpage TraceMiner 2\n *\n * @author Norman Dunbar\n * @copyright MIT Licence\n *\n * @tableofcontents\n *\n * @section Introduction\n *\n * TraceMiner 2 is a new improved version of the old TraceMiner utility. It has\n * been completely rewritten in C++ rather than the old style vanilla C. This has made\n * things surprisingly easier to do in the new versions and has got around a whole pile\n * of crud and hacks in the previous version. There's no manual configuration required\n * before compiling for example.\n *\n * @section sec-free-source-code Free Source Code\n *\n * The source code for TraceMiner2 lives in GitHub at\n * https:\/\/github.com\/NormanDunbar\/TraceMiner2\/.\n *\n * Feel free to clone the repository and make any desired changes you wish.\n *\n * You may, if you just want to compile and use the code, download the source as a\n * zip file from https:\/\/github.com\/NormanDunbar\/TraceMiner2\/archive\/master.zip.\n *\n * @section sec-compiling Compiling\n *\n * The source should be downloaded. Then simply compile all the *.cpp files using a C++\n * compiler that knows about the Standard Template Library (aka STL). This is the only\n * \"weird\" thing used by TraceMiner2. No other special libraries such as Boost, for\n * example, are required.\n *\n * @subsection sub-sec-with-codeblocks With CodeBlocks\n *\n * There's a CodeBlocks project file, `TraceMiner2.cbp`, located in the main source folder.\n * You may need to change some paths etc to use it. In my own setup, I have configured the\n * free Borland\/Embarcadero C++ compiler, version 10.1, to be used. Get yours at\n * https:\/\/www.embarcadero.com\/free-tools\/ccompiler\/start-for-free. CodeBlocks itself is\n * available at https:\/\/www.codeblocks.org.\n *\n * Once compiled, look here for your executable:\n *\n * @code\n * TraceMiner2-master\\TraceMiner2\\bin\\release\n * @endcode\n *\n * @subsection sub-sec-with-borland With Borland\/Embarcadero C++ 10.1\n *\n * Unzip the download zip file, then:\n *\n * @code\n * cd TraceMiner2-master\\TraceMiner2\n * mkdir bin\n * bcc32c -o bin\\TraceMiner2.exe *.cpp\n * @endcode\n *\n * Once compiled, look your executable will be:\n *\n * @code\n * TraceMiner2-master\\TraceMiner2\\bin\\TraceMiner2.exe\n * @endcode\n *\n * Get a free copy of the compiler at https:\/\/www.embarcadero.com\/free-tools\/ccompiler\/start-for-free.\n *\n * @subsection sub-sec-with-gpp With G++\n *\n * You can use the supplied Makefile.gnu, or just compile all the *.cpp files, as follows:\n *\n * @code\n * cd TraceMiner2-master\/TraceMiner2\n * mkdir bin\n * g++ -o bin\/TraceMiner2 *.cpp\n * @endcode\n *\n * The executable will be wherever you pointed it to be created with the '-o' option.\n *\n * @subsection sec-makefile With a Makefile\n *\n * @code\n * cd TraceMiner2-master\n * make -f makefile.gnu\n * @endcode\n *\n * Once compiled, look here for your executable:\n *\n * @code\n * TraceMiner2-master\/TraceMiner2\/bin\n * @endcode\n *\n * @section sec-execution Execution\n *\n * There is one mandatory parameter required, the trace file name. This must have the extension\n * \".trc\" as generated by Oracle. The report file will have the \".trc\" changed to \".txt\" or\n * \".html\" depending on whether you have requested a plain text or HTML report format.\n *\n * The report file will be created in the same location as the trace file and defaults to HTML format. This\n * is simply because the textual format is pretty dire with wide lines in many cases.\n *\n * If you choose to run in verbose mode, and you probably shouldn't, the output file for that\n * detail will be the same as the trace file name, but with the \".trc\" extension replaced by\n * \".dbg\". Once again, the output file will be in the same location as the trace file.\n *\n * The optional parameters are as follows:\n *\n * @li --verbose or -v - indicates that you wish to generate lots of output for debugging purposes.\n * @li --quiet or -q - indicates that you do not wish to see \"Cursor: #cccc created at line: nnnn\" messages.\n * on the screen while parsing is taking place. Any ERRORs or PARSE ERRORS will still be displayed.\n * @li --help -h or -? - indicates that you want help. The program will exit after displaying the\n * usage details.\n * @li --text or -t - indicates that you wish to have the report formatted in plain text as opposed to\n * HTML text. Good luck with that option! ;-)\n * @li --depth=n or -d=n - indicates the maximum depth of recursive cursors that you wish to report on\n * which is useful when a PL\/SQL calls is at depth=0, you wouold be interested in depth=1, for example.\n * @li --pagesize=nn or -p=nn - indicates how many EXEC statements you wish to display in each HTML table\n * in the report. This meakes scrolling to the headings in long report files a lot easier!\n * @li --feedback=nn or -f=nn - indicates how often you want feedback on progress reading the trace file. Zero\n * disables feedback. The default is every 100,000 lines read. Useful on larger trace files.\n *\n * @section sec-mit-licence MIT Licence\n *\n * MIT License\n *\n * Copyright (c) 2017 Norman Dunbar\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n\/** @file TraceMiner2.cpp\n * @brief This is where it all starts. The main() function lives here.\n *\/\n\n\n#include \"TraceMiner2.h\"\n#include \"utilities.h\"\n#include \"favicon.h\"\n\n\/\/ Version number.\nconst float version = 0.07;\n\n\/\/ Various flags set according to the passed parameters.\ntmOptions options;\n\nint main(int argc, char *argv[])\n{\n \/\/ Make sure that cout\/cerr gets comma\/dot separated thousands etc.\n cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));\n cerr.imbue(locale(cerr.getloc(), new ThousandsSeparator<char>(',')));\n\n \/\/ Parse command line args and bale if problems detected.\n bool allOk = options.parseArgs(argc, argv);\n if (!allOk) {\n return 1;\n }\n\n \/\/ Show help and exit requested?\n if (options.help()) {\n return 0;\n }\n\n if (options.html()) {\n \/\/ Create a (new) CSS file, if HTML requested and\n \/\/ there isn't one already.\n string cssFile = options.cssFileName();\n if (fileExists(cssFile)) {\n cout << \"File exists: \" << cssFile << endl;\n } else {\n allOk = createCSSFile(cssFile);\n if (!allOk) {\n return 1;\n }\n }\n\n \/\/ Likewise, a 'favicon.ico' icon file too.\n string favIconFile = filePath(cssFile) + directorySeparator + \"favicon.ico\";\n if (fileExists(favIconFile)) {\n cout << \"File exists: \" << favIconFile << endl;\n } else {\n allOk = createFaviconFile(favIconFile);\n if (allOk) {\n cout << \"TraceMiner2: 'favicon' file [\" << favIconFile << \"] created ok.\" << endl;\n } else {\n cout << \"TraceMiner2: 'favicon' file [\" << favIconFile << \"] creation failed.\" << endl;\n return 1;\n }\n }\n }\n\n\n\n \/\/ This is it, here is where we hit the big time! :)\n tmTraceFile *traceFile = new tmTraceFile(&options);\n allOk = traceFile->parse();\n\n \/\/ All done.\n if (traceFile) {\n delete traceFile;\n }\n\n return allOk ? 0 : 1;\n}\n<commit_msg>Version upgraded to 0.08.<commit_after>\/** @mainpage TraceMiner 2\n *\n * @author Norman Dunbar\n * @copyright MIT Licence\n *\n * @tableofcontents\n *\n * @section Introduction\n *\n * TraceMiner 2 is a new improved version of the old TraceMiner utility. It has\n * been completely rewritten in C++ rather than the old style vanilla C. This has made\n * things surprisingly easier to do in the new versions and has got around a whole pile\n * of crud and hacks in the previous version. There's no manual configuration required\n * before compiling for example.\n *\n * @section sec-free-source-code Free Source Code\n *\n * The source code for TraceMiner2 lives in GitHub at\n * https:\/\/github.com\/NormanDunbar\/TraceMiner2\/.\n *\n * Feel free to clone the repository and make any desired changes you wish.\n *\n * You may, if you just want to compile and use the code, download the source as a\n * zip file from https:\/\/github.com\/NormanDunbar\/TraceMiner2\/archive\/master.zip.\n *\n * @section sec-compiling Compiling\n *\n * The source should be downloaded. Then simply compile all the *.cpp files using a C++\n * compiler that knows about the Standard Template Library (aka STL). This is the only\n * \"weird\" thing used by TraceMiner2. No other special libraries such as Boost, for\n * example, are required.\n *\n * @subsection sub-sec-with-codeblocks With CodeBlocks\n *\n * There's a CodeBlocks project file, `TraceMiner2.cbp`, located in the main source folder.\n * You may need to change some paths etc to use it. In my own setup, I have configured the\n * free Borland\/Embarcadero C++ compiler, version 10.1, to be used. Get yours at\n * https:\/\/www.embarcadero.com\/free-tools\/ccompiler\/start-for-free. CodeBlocks itself is\n * available at https:\/\/www.codeblocks.org.\n *\n * Once compiled, look here for your executable:\n *\n * @code\n * TraceMiner2-master\\TraceMiner2\\bin\\release\n * @endcode\n *\n * @subsection sub-sec-with-borland With Borland\/Embarcadero C++ 10.1\n *\n * Unzip the download zip file, then:\n *\n * @code\n * cd TraceMiner2-master\\TraceMiner2\n * mkdir bin\n * bcc32c -o bin\\TraceMiner2.exe *.cpp\n * @endcode\n *\n * Once compiled, look your executable will be:\n *\n * @code\n * TraceMiner2-master\\TraceMiner2\\bin\\TraceMiner2.exe\n * @endcode\n *\n * Get a free copy of the compiler at https:\/\/www.embarcadero.com\/free-tools\/ccompiler\/start-for-free.\n *\n * @subsection sub-sec-with-gpp With G++\n *\n * You can use the supplied Makefile.gnu, or just compile all the *.cpp files, as follows:\n *\n * @code\n * cd TraceMiner2-master\/TraceMiner2\n * mkdir bin\n * g++ -o bin\/TraceMiner2 *.cpp\n * @endcode\n *\n * The executable will be wherever you pointed it to be created with the '-o' option.\n *\n * @subsection sec-makefile With a Makefile\n *\n * @code\n * cd TraceMiner2-master\n * make -f makefile.gnu\n * @endcode\n *\n * Once compiled, look here for your executable:\n *\n * @code\n * TraceMiner2-master\/TraceMiner2\/bin\n * @endcode\n *\n * @section sec-execution Execution\n *\n * There is one mandatory parameter required, the trace file name. This must have the extension\n * \".trc\" as generated by Oracle. The report file will have the \".trc\" changed to \".txt\" or\n * \".html\" depending on whether you have requested a plain text or HTML report format.\n *\n * The report file will be created in the same location as the trace file and defaults to HTML format. This\n * is simply because the textual format is pretty dire with wide lines in many cases.\n *\n * If you choose to run in verbose mode, and you probably shouldn't, the output file for that\n * detail will be the same as the trace file name, but with the \".trc\" extension replaced by\n * \".dbg\". Once again, the output file will be in the same location as the trace file.\n *\n * The optional parameters are as follows:\n *\n * @li --verbose or -v - indicates that you wish to generate lots of output for debugging purposes.\n * @li --quiet or -q - indicates that you do not wish to see \"Cursor: #cccc created at line: nnnn\" messages.\n * on the screen while parsing is taking place. Any ERRORs or PARSE ERRORS will still be displayed.\n * @li --help -h or -? - indicates that you want help. The program will exit after displaying the\n * usage details.\n * @li --text or -t - indicates that you wish to have the report formatted in plain text as opposed to\n * HTML text. Good luck with that option! ;-)\n * @li --depth=n or -d=n - indicates the maximum depth of recursive cursors that you wish to report on\n * which is useful when a PL\/SQL calls is at depth=0, you wouold be interested in depth=1, for example.\n * @li --pagesize=nn or -p=nn - indicates how many EXEC statements you wish to display in each HTML table\n * in the report. This meakes scrolling to the headings in long report files a lot easier!\n * @li --feedback=nn or -f=nn - indicates how often you want feedback on progress reading the trace file. Zero\n * disables feedback. The default is every 100,000 lines read. Useful on larger trace files.\n *\n * @section sec-mit-licence MIT Licence\n *\n * MIT License\n *\n * Copyright (c) 2017 Norman Dunbar\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n\/** @file TraceMiner2.cpp\n * @brief This is where it all starts. The main() function lives here.\n *\/\n\n\n#include \"TraceMiner2.h\"\n#include \"utilities.h\"\n#include \"favicon.h\"\n\n\/\/ Version number.\nconst float version = 0.08;\n\n\/\/ Various flags set according to the passed parameters.\ntmOptions options;\n\nint main(int argc, char *argv[])\n{\n \/\/ Make sure that cout\/cerr gets comma\/dot separated thousands etc.\n cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));\n cerr.imbue(locale(cerr.getloc(), new ThousandsSeparator<char>(',')));\n\n \/\/ Parse command line args and bale if problems detected.\n bool allOk = options.parseArgs(argc, argv);\n if (!allOk) {\n return 1;\n }\n\n \/\/ Show help and exit requested?\n if (options.help()) {\n return 0;\n }\n\n if (options.html()) {\n \/\/ Create a (new) CSS file, if HTML requested and\n \/\/ there isn't one already.\n string cssFile = options.cssFileName();\n if (fileExists(cssFile)) {\n cout << \"File exists: \" << cssFile << endl;\n } else {\n allOk = createCSSFile(cssFile);\n if (!allOk) {\n return 1;\n }\n }\n\n \/\/ Likewise, a 'favicon.ico' icon file too.\n string favIconFile = filePath(cssFile) + directorySeparator + \"favicon.ico\";\n if (fileExists(favIconFile)) {\n cout << \"File exists: \" << favIconFile << endl;\n } else {\n allOk = createFaviconFile(favIconFile);\n if (allOk) {\n cout << \"TraceMiner2: 'favicon' file [\" << favIconFile << \"] created ok.\" << endl;\n } else {\n cout << \"TraceMiner2: 'favicon' file [\" << favIconFile << \"] creation failed.\" << endl;\n return 1;\n }\n }\n }\n\n\n\n \/\/ This is it, here is where we hit the big time! :)\n tmTraceFile *traceFile = new tmTraceFile(&options);\n allOk = traceFile->parse();\n\n \/\/ All done.\n if (traceFile) {\n delete traceFile;\n }\n\n return allOk ? 0 : 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************\/\n\/* onleftclick.cpp *\/\n\/*******************\/\n\n#include \"fctsys.h\"\n#include \"common.h\"\n#include \"eeschema_id.h\"\n#include \"class_drawpanel.h\"\n#include \"confirm.h\"\n#include \"class_sch_screen.h\"\n#include \"wxEeschemaStruct.h\"\n\n#include \"general.h\"\n#include \"protos.h\"\n#include \"sch_bus_entry.h\"\n#include \"sch_text.h\"\n#include \"sch_marker.h\"\n#include \"sch_junction.h\"\n#include \"sch_line.h\"\n#include \"sch_no_connect.h\"\n#include \"sch_component.h\"\n#include \"sch_sheet.h\"\n\n\nstatic wxArrayString s_CmpNameList;\nstatic wxArrayString s_PowerNameList;\n\n\nvoid SCH_EDIT_FRAME::OnLeftClick( wxDC* aDC, const wxPoint& aPosition )\n{\n SCH_ITEM* item = GetScreen()->GetCurItem();\n wxPoint gridPosition = GetGridPosition( aPosition );\n\n if( ( m_ID_current_state == ID_SCH_NO_TOOL )\n || ( m_ID_current_state == 0 )\n || ( item && item->m_Flags ) )\n {\n DrawPanel->m_AutoPAN_Request = false;\n m_itemToRepeat = NULL;\n\n if( item && item->m_Flags )\n {\n switch( item->Type() )\n {\n case SCH_LABEL_T:\n case SCH_GLOBAL_LABEL_T:\n case SCH_HIERARCHICAL_LABEL_T:\n case SCH_TEXT_T:\n case SCH_SHEET_LABEL_T:\n case SCH_SHEET_T:\n case SCH_BUS_ENTRY_T:\n case SCH_JUNCTION_T:\n case SCH_COMPONENT_T:\n case SCH_FIELD_T:\n item->Place( this, aDC );\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n return;\n\n case SCH_SCREEN_T:\n DisplayError( this, wxT( \"OnLeftClick err: unexpected type for Place\" ) );\n item->m_Flags = 0;\n break;\n\n case SCH_LINE_T: \/\/ May already be drawing segment.\n break;\n\n default:\n {\n wxString msg;\n msg.Printf( wxT( \"SCH_EDIT_FRAME::OnLeftClick err: m_Flags != 0, itmetype %d\" ),\n item->Type());\n DisplayError( this, msg );\n item->m_Flags = 0;\n break;\n }\n }\n }\n else\n {\n item = LocateAndShowItem( aPosition );\n }\n }\n\n switch( m_ID_current_state )\n {\n case 0:\n case ID_SCH_NO_TOOL:\n break;\n\n case ID_HIERARCHY_PUSH_POP_BUTT:\n if( ( item && item->m_Flags ) || ( g_RootSheet->CountSheets() == 0 ) )\n break;\n\n item = LocateAndShowItem( aPosition );\n\n if( item && ( item->Type() == SCH_SHEET_T ) )\n {\n m_CurrentSheet->Push( (SCH_SHEET*) item );\n DisplayCurrentSheet();\n }\n else\n {\n wxCHECK_RET( m_CurrentSheet->Last() != g_RootSheet,\n wxT( \"Cannot leave root sheet. Bad Programmer!\" ) );\n\n m_CurrentSheet->Pop();\n DisplayCurrentSheet();\n }\n\n break;\n\n case ID_NOCONN_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n m_itemToRepeat = AddNoConnect( aDC, gridPosition );\n GetScreen()->SetCurItem( m_itemToRepeat );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_JUNCTION_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n m_itemToRepeat = AddJunction( aDC, gridPosition, true );\n GetScreen()->SetCurItem( m_itemToRepeat );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_WIRETOBUS_ENTRY_BUTT:\n case ID_BUSTOBUS_ENTRY_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n item = CreateBusEntry( aDC, ( m_ID_current_state == ID_WIRETOBUS_ENTRY_BUTT ) ?\n WIRE_TO_BUS : BUS_TO_BUS );\n GetScreen()->SetCurItem( item );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n DrawPanel->m_AutoPAN_Request = false;\n }\n break;\n\n case ID_SCHEMATIC_DELETE_ITEM_BUTT:\n LocateAndDeleteItem( this, aDC );\n OnModify();\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_WIRE_BUTT:\n BeginSegment( aDC, LAYER_WIRE );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_BUS_BUTT:\n BeginSegment( aDC, LAYER_BUS );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_LINE_COMMENT_BUTT:\n BeginSegment( aDC, LAYER_NOTES );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_TEXT_COMMENT_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_NOTES ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n break;\n\n case ID_LABEL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_LOCLABEL ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_GLABEL_BUTT:\n case ID_HIERLABEL_BUTT:\n if( (item == NULL) || (item->m_Flags == 0) )\n {\n if(m_ID_current_state == ID_GLABEL_BUTT)\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_GLOBLABEL ) );\n\n if(m_ID_current_state == ID_HIERLABEL_BUTT)\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_HIERLABEL ) );\n\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_SHEET_SYMBOL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateSheet( aDC ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_IMPORT_HLABEL_BUTT:\n case ID_SHEET_LABEL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n item = LocateAndShowItem( aPosition );\n\n if( item == NULL )\n break;\n\n if( (item->Type() == SCH_SHEET_T) && (item->m_Flags == 0) )\n {\n if( m_ID_current_state == ID_IMPORT_HLABEL_BUTT )\n GetScreen()->SetCurItem( Import_PinSheet( (SCH_SHEET*) item, aDC ) );\n else\n GetScreen()->SetCurItem( Create_PinSheet( (SCH_SHEET*) item, aDC ) );\n }\n else if( (item->Type() == SCH_SHEET_LABEL_T) && (item->m_Flags != 0) )\n {\n item->Place( this, aDC );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_SCH_PLACE_COMPONENT:\n if( (item == NULL) || (item->m_Flags == 0) )\n {\n GetScreen()->SetCurItem( Load_Component( aDC, wxEmptyString, s_CmpNameList, true ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_PLACE_POWER_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( Load_Component( aDC, wxT( \"power\" ),\n s_PowerNameList, false ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n default:\n {\n SetToolID( 0, wxCURSOR_ARROW, wxEmptyString );\n wxString msg( wxT( \"SCH_EDIT_FRAME::OnLeftClick error state \" ) );\n\n msg << m_ID_current_state;\n DisplayError( this, msg );\n break;\n }\n }\n}\n\n\n\/**\n * Function OnLeftDClick\n * called on a double click event from the drawpanel mouse handler\n * if an editable item is found (text, component)\n * Call the suitable dialog editor.\n * Id a create command is in progress:\n * validate and finish the command\n *\/\nvoid SCH_EDIT_FRAME::OnLeftDClick( wxDC* aDC, const wxPoint& aPosition )\n\n{\n EDA_ITEM* item = GetScreen()->GetCurItem();\n wxPoint pos = aPosition;\n\n switch( m_ID_current_state )\n {\n case ID_SCH_NO_TOOL:\n case 0:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n item = LocateAndShowItem( aPosition );\n }\n\n if( ( item == NULL ) || ( item->m_Flags != 0 ) )\n break;\n\n switch( item->Type() )\n {\n case SCH_SHEET_T:\n m_CurrentSheet->Push( (SCH_SHEET*) item );\n DisplayCurrentSheet();\n break;\n\n case SCH_COMPONENT_T:\n InstallCmpeditFrame( this, (SCH_COMPONENT*) item );\n DrawPanel->MoveCursorToCrossHair();\n break;\n\n case SCH_TEXT_T:\n case SCH_LABEL_T:\n case SCH_GLOBAL_LABEL_T:\n case SCH_HIERARCHICAL_LABEL_T:\n EditSchematicText( (SCH_TEXT*) item );\n break;\n\n case SCH_FIELD_T:\n EditCmpFieldText( (SCH_FIELD*) item, aDC );\n DrawPanel->MoveCursorToCrossHair();\n break;\n\n case SCH_MARKER_T:\n ( (SCH_MARKER*) item )->DisplayMarkerInfo( this );\n break;\n\n default:\n break;\n }\n\n break;\n\n case ID_BUS_BUTT:\n case ID_WIRE_BUTT:\n case ID_LINE_COMMENT_BUTT:\n if( item && item->IsNew() )\n EndSegment( aDC );\n\n break;\n }\n}\n<commit_msg>Fix developer warning message to only show on debug build. Fixes lp:624926<commit_after>\/*******************\/\n\/* onleftclick.cpp *\/\n\/*******************\/\n\n#include \"fctsys.h\"\n#include \"common.h\"\n#include \"eeschema_id.h\"\n#include \"class_drawpanel.h\"\n#include \"confirm.h\"\n#include \"class_sch_screen.h\"\n#include \"wxEeschemaStruct.h\"\n\n#include \"general.h\"\n#include \"protos.h\"\n#include \"sch_bus_entry.h\"\n#include \"sch_text.h\"\n#include \"sch_marker.h\"\n#include \"sch_junction.h\"\n#include \"sch_line.h\"\n#include \"sch_no_connect.h\"\n#include \"sch_component.h\"\n#include \"sch_sheet.h\"\n\n\nstatic wxArrayString s_CmpNameList;\nstatic wxArrayString s_PowerNameList;\n\n\nvoid SCH_EDIT_FRAME::OnLeftClick( wxDC* aDC, const wxPoint& aPosition )\n{\n SCH_ITEM* item = GetScreen()->GetCurItem();\n wxPoint gridPosition = GetGridPosition( aPosition );\n\n if( ( m_ID_current_state == ID_SCH_NO_TOOL )\n || ( m_ID_current_state == 0 )\n || ( item && item->m_Flags ) )\n {\n DrawPanel->m_AutoPAN_Request = false;\n m_itemToRepeat = NULL;\n\n if( item && item->m_Flags )\n {\n switch( item->Type() )\n {\n case SCH_LABEL_T:\n case SCH_GLOBAL_LABEL_T:\n case SCH_HIERARCHICAL_LABEL_T:\n case SCH_TEXT_T:\n case SCH_SHEET_LABEL_T:\n case SCH_SHEET_T:\n case SCH_BUS_ENTRY_T:\n case SCH_JUNCTION_T:\n case SCH_COMPONENT_T:\n case SCH_FIELD_T:\n item->Place( this, aDC );\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n return;\n\n case SCH_LINE_T: \/\/ May already be drawing segment.\n break;\n\n default:\n wxFAIL_MSG( wxT( \"SCH_EDIT_FRAME::OnLeftClick error. Item type <\" ) +\n item->GetClass() + wxT( \"> is already being edited.\" ) );\n item->SetFlags( 0 );\n }\n }\n else\n {\n item = LocateAndShowItem( aPosition );\n }\n }\n\n switch( m_ID_current_state )\n {\n case 0:\n case ID_SCH_NO_TOOL:\n break;\n\n case ID_HIERARCHY_PUSH_POP_BUTT:\n if( ( item && item->m_Flags ) || ( g_RootSheet->CountSheets() == 0 ) )\n break;\n\n item = LocateAndShowItem( aPosition );\n\n if( item && ( item->Type() == SCH_SHEET_T ) )\n {\n m_CurrentSheet->Push( (SCH_SHEET*) item );\n DisplayCurrentSheet();\n }\n else\n {\n wxCHECK_RET( m_CurrentSheet->Last() != g_RootSheet,\n wxT( \"Cannot leave root sheet. Bad Programmer!\" ) );\n\n m_CurrentSheet->Pop();\n DisplayCurrentSheet();\n }\n\n break;\n\n case ID_NOCONN_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n m_itemToRepeat = AddNoConnect( aDC, gridPosition );\n GetScreen()->SetCurItem( m_itemToRepeat );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_JUNCTION_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n m_itemToRepeat = AddJunction( aDC, gridPosition, true );\n GetScreen()->SetCurItem( m_itemToRepeat );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_WIRETOBUS_ENTRY_BUTT:\n case ID_BUSTOBUS_ENTRY_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n item = CreateBusEntry( aDC, ( m_ID_current_state == ID_WIRETOBUS_ENTRY_BUTT ) ?\n WIRE_TO_BUS : BUS_TO_BUS );\n GetScreen()->SetCurItem( item );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n DrawPanel->m_AutoPAN_Request = false;\n }\n break;\n\n case ID_SCHEMATIC_DELETE_ITEM_BUTT:\n LocateAndDeleteItem( this, aDC );\n OnModify();\n GetScreen()->SetCurItem( NULL );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n break;\n\n case ID_WIRE_BUTT:\n BeginSegment( aDC, LAYER_WIRE );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_BUS_BUTT:\n BeginSegment( aDC, LAYER_BUS );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_LINE_COMMENT_BUTT:\n BeginSegment( aDC, LAYER_NOTES );\n DrawPanel->m_AutoPAN_Request = true;\n break;\n\n case ID_TEXT_COMMENT_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_NOTES ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n }\n break;\n\n case ID_LABEL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_LOCLABEL ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_GLABEL_BUTT:\n case ID_HIERLABEL_BUTT:\n if( (item == NULL) || (item->m_Flags == 0) )\n {\n if(m_ID_current_state == ID_GLABEL_BUTT)\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_GLOBLABEL ) );\n\n if(m_ID_current_state == ID_HIERLABEL_BUTT)\n GetScreen()->SetCurItem( CreateNewText( aDC, LAYER_HIERLABEL ) );\n\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_SHEET_SYMBOL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( CreateSheet( aDC ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_IMPORT_HLABEL_BUTT:\n case ID_SHEET_LABEL_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n item = LocateAndShowItem( aPosition );\n\n if( item == NULL )\n break;\n\n if( (item->Type() == SCH_SHEET_T) && (item->m_Flags == 0) )\n {\n if( m_ID_current_state == ID_IMPORT_HLABEL_BUTT )\n GetScreen()->SetCurItem( Import_PinSheet( (SCH_SHEET*) item, aDC ) );\n else\n GetScreen()->SetCurItem( Create_PinSheet( (SCH_SHEET*) item, aDC ) );\n }\n else if( (item->Type() == SCH_SHEET_LABEL_T) && (item->m_Flags != 0) )\n {\n item->Place( this, aDC );\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_SCH_PLACE_COMPONENT:\n if( (item == NULL) || (item->m_Flags == 0) )\n {\n GetScreen()->SetCurItem( Load_Component( aDC, wxEmptyString, s_CmpNameList, true ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n case ID_PLACE_POWER_BUTT:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n GetScreen()->SetCurItem( Load_Component( aDC, wxT( \"power\" ),\n s_PowerNameList, false ) );\n DrawPanel->m_AutoPAN_Request = true;\n }\n else\n {\n item->Place( this, aDC );\n DrawPanel->m_AutoPAN_Request = false;\n GetScreen()->TestDanglingEnds();\n DrawPanel->Refresh( true );\n }\n break;\n\n default:\n SetToolID( ID_SCH_NO_TOOL, DrawPanel->GetDefaultCursor(), wxEmptyString );\n wxFAIL_MSG( wxT( \"SCH_EDIT_FRAME::OnLeftClick invalid tool ID <\" ) +\n wxString::Format( wxT( \"%d> selected.\" ), m_ID_current_state ) );\n }\n}\n\n\n\/**\n * Function OnLeftDClick\n * called on a double click event from the drawpanel mouse handler\n * if an editable item is found (text, component)\n * Call the suitable dialog editor.\n * Id a create command is in progress:\n * validate and finish the command\n *\/\nvoid SCH_EDIT_FRAME::OnLeftDClick( wxDC* aDC, const wxPoint& aPosition )\n\n{\n EDA_ITEM* item = GetScreen()->GetCurItem();\n wxPoint pos = aPosition;\n\n switch( m_ID_current_state )\n {\n case ID_SCH_NO_TOOL:\n case 0:\n if( ( item == NULL ) || ( item->m_Flags == 0 ) )\n {\n item = LocateAndShowItem( aPosition );\n }\n\n if( ( item == NULL ) || ( item->m_Flags != 0 ) )\n break;\n\n switch( item->Type() )\n {\n case SCH_SHEET_T:\n m_CurrentSheet->Push( (SCH_SHEET*) item );\n DisplayCurrentSheet();\n break;\n\n case SCH_COMPONENT_T:\n InstallCmpeditFrame( this, (SCH_COMPONENT*) item );\n DrawPanel->MoveCursorToCrossHair();\n break;\n\n case SCH_TEXT_T:\n case SCH_LABEL_T:\n case SCH_GLOBAL_LABEL_T:\n case SCH_HIERARCHICAL_LABEL_T:\n EditSchematicText( (SCH_TEXT*) item );\n break;\n\n case SCH_FIELD_T:\n EditCmpFieldText( (SCH_FIELD*) item, aDC );\n DrawPanel->MoveCursorToCrossHair();\n break;\n\n case SCH_MARKER_T:\n ( (SCH_MARKER*) item )->DisplayMarkerInfo( this );\n break;\n\n default:\n break;\n }\n\n break;\n\n case ID_BUS_BUTT:\n case ID_WIRE_BUTT:\n case ID_LINE_COMMENT_BUTT:\n if( item && item->IsNew() )\n EndSegment( aDC );\n\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ComponentCamera.h\"\n#include \"Application.h\"\n\n\nComponentCamera::ComponentCamera(Object* obj_parent)\n{\n\tparent = obj_parent;\n\tcomp_type = ComponentType::camera;\n\tcam_frustum.SetViewPlaneDistances(1, 15);\n\n\t\/\/Set frustum looking to GameObject Z axis\n\tComponentTransform* parent_transform = parent->GetTransform();\n\n\tcam_frustum.SetPos(parent_transform->translation);\n\tcam_frustum.SetFront(parent_transform->GetMatrix().Col3(2));\n\tcam_frustum.SetUp(parent_transform->GetMatrix().Col3(1));\n\n\n\tcam_frustum.SetVerticalFovAndAspectRatio(90 * DEGTORAD, App->window->GetAspectRatio());\n\tcam_frustum.SetHorizontalFovAndAspectRatio(2 * math::Atan(math::Tan(cam_frustum.VerticalFov()\/ 2) * App->window->GetAspectRatio()),App->window->GetAspectRatio());\n\n\t\n}\n\n\nComponentCamera::~ComponentCamera()\n{\n}\n\nvoid ComponentCamera::UpdateComponent()\n{\n\tComponentTransform* parent_transform = parent->GetTransform();\n\tcam_frustum.SetPos(parent_transform->translation);\n\n\tfloat color[4] = { 0.7f, 0.7f, 0.7f, 1 };\n\tcam_frustum.Draw(3.0f,color );\n\n}\n\n\n<commit_msg>frustum can rotate<commit_after>#include \"ComponentCamera.h\"\n#include \"Application.h\"\n\n\nComponentCamera::ComponentCamera(Object* obj_parent)\n{\n\tparent = obj_parent;\n\tcomp_type = ComponentType::camera;\n\tcam_frustum.SetViewPlaneDistances(1, 15);\n\n\t\/\/Set frustum looking to GameObject Z axis\n\tComponentTransform* parent_transform = parent->GetTransform();\n\n\tcam_frustum.SetPos(parent_transform->translation);\n\tcam_frustum.SetFront(parent_transform->GetMatrix().Col3(2));\n\tcam_frustum.SetUp(parent_transform->GetMatrix().Col3(1));\n\n\n\tcam_frustum.SetVerticalFovAndAspectRatio(90 * DEGTORAD, App->window->GetAspectRatio());\n\tcam_frustum.SetHorizontalFovAndAspectRatio(2 * math::Atan(math::Tan(cam_frustum.VerticalFov()\/ 2) * App->window->GetAspectRatio()),App->window->GetAspectRatio());\n\n\t\n}\n\n\nComponentCamera::~ComponentCamera()\n{\n}\n\nvoid ComponentCamera::UpdateComponent()\n{\n\tComponentTransform* parent_transform = parent->GetTransform();\n\tcam_frustum.SetPos(parent_transform->translation);\n\n\tcam_frustum.SetFront(parent_transform->GetMatrix().Col3(2));\n\t\/\/cam_frustum.SetUp(parent_transform->GetMatrix().Col3(1));\n\n\tfloat color[4] = { 0.7f, 0.7f, 0.7f, 1 };\n\tcam_frustum.Draw(3.0f,color );\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"transmissionquickfilter.h\"\n\nTransmissionQuickFilter::TransmissionQuickFilter(int AnalysisId) : QuickFilterBlockInterface()\n{\n \/\/ Dominant - ref\/alt\n mFilters[0] = \"[\\\"==\\\", [\\\"field\\\", \\\"b33e172643f14920cee93d25daaa3c7b\\\"], [\\\"value\\\", \\\"2\\\"]]\";\n mActiveFilters[0] = false;\n \/\/ Recessif - alt\/alt\n mFilters[1] = \"[\\\"==\\\", [\\\"field\\\", \\\"b33e172643f14920cee93d25daaa3c7b\\\"], [\\\"value\\\", \\\"1\\\"]]\";\n mActiveFilters[1] = false;\n \/\/ Composite - alt1\/alt2\n mFilters[2] = \"[\\\"==\\\", [\\\"field\\\", \\\"b33e172643f14920cee93d25daaa3c7b\\\"], [\\\"value\\\", \\\"3\\\"]]\";\n mActiveFilters[2] = false;\n}\n\n\nbool TransmissionQuickFilter::isVisible()\n{\n \/\/ This filter is always availble in the UI\n return true;\n}\n\n\nQString TransmissionQuickFilter::getFilter()\n{\n QStringList filter;\n for (int idx=0; idx < mActiveFilters.count(); idx++)\n {\n if (mActiveFilters[idx])\n {\n filter << mFilters[idx];\n }\n }\n\n if (filter.count() > 1)\n return QString(\"[\\\"OR\\\", [%1]]\").arg(filter.join(\",\"));\n else if (filter.count() == 1)\n return filter[0];\n return \"\";\n}\n\n\n\nvoid TransmissionQuickFilter::setFilter(int id, QVariant value)\n{\n mActiveFilters[id] = value.toBool();\n}\n\nvoid TransmissionQuickFilter::clear()\n{\n mActiveFilters[0] = false;\n mActiveFilters[1] = false;\n mActiveFilters[2] = false;\n}\n<commit_msg>fix htz composite filter (solo sample)<commit_after>#include \"transmissionquickfilter.h\"\n\nTransmissionQuickFilter::TransmissionQuickFilter(int AnalysisId) : QuickFilterBlockInterface()\n{\n \/\/ Dominant - ref\/alt\n mFilters[0] = \"[\\\"==\\\", [\\\"field\\\", \\\"b33e172643f14920cee93d25daaa3c7b\\\"], [\\\"value\\\", \\\"2\\\"]]\";\n mActiveFilters[0] = false;\n \/\/ Recessif - alt\/alt\n mFilters[1] = \"[\\\"==\\\", [\\\"field\\\", \\\"b33e172643f14920cee93d25daaa3c7b\\\"], [\\\"value\\\", \\\"1\\\"]]\";\n mActiveFilters[1] = false;\n \/\/ Composite - alt1\/alt2\n mFilters[2] = \"[\\\"==\\\", [\\\"field\\\", \\\"212a9e5be0a47eea6ed028af9992e1bb\\\"], [\\\"value\\\", true]]\";\n mActiveFilters[2] = false;\n}\n\n\nbool TransmissionQuickFilter::isVisible()\n{\n \/\/ This filter is always availble in the UI\n return true;\n}\n\n\nQString TransmissionQuickFilter::getFilter()\n{\n QStringList filter;\n for (int idx=0; idx < mActiveFilters.count(); idx++)\n {\n if (mActiveFilters[idx])\n {\n filter << mFilters[idx];\n }\n }\n\n if (filter.count() > 1)\n return QString(\"[\\\"OR\\\", [%1]]\").arg(filter.join(\",\"));\n else if (filter.count() == 1)\n return filter[0];\n return \"\";\n}\n\n\n\nvoid TransmissionQuickFilter::setFilter(int id, QVariant value)\n{\n mActiveFilters[id] = value.toBool();\n}\n\nvoid TransmissionQuickFilter::clear()\n{\n mActiveFilters[0] = false;\n mActiveFilters[1] = false;\n mActiveFilters[2] = false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/meta\/MetaPopulationFactory.hpp\"\n#include \"core\/PopulationNode.hpp\"\n#include \"core\/Apportionment.hpp\"\n#include \"core\/ObjectiveFunction.hpp\"\n#include \"core\/meta\/MetaPopulationObjective.hpp\"\n#include \"core\/meta\/MetaPopulationApportionment.hpp\"\n#include \"core\/meta\/MetaPopulationToString.hpp\"\n#include \"loci\/PopulationLocus.hpp\"\n#include \"exception\/InvalidBlanketException.hpp\"\n\n#include <set>\n\nstd::vector<PopulationNode*> MetaPopulationFactory::getAllHierarchicalNodes(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::set<Locus*> constructiveLoci;\n\tstd::vector<PopulationNode*> unmatchedNodes;\n\tfor (unsigned int i = 0; i < nodes.size(); i++) {\n\t\tconstructiveLoci = nodes[i]->getConstructiveLoci();\n\t\tfor (auto k : constructiveLoci)\n\t\t\tunmatchedNodes.push_back(\n\t\t\t\t((PopulationLocus*)k)->getNode()\n\t\t\t);\n\t}\n\n\treturn unmatchedNodes;\n}\n\nbool MetaPopulationFactory::isCompleteBlanket(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::vector<PopulationNode*> unmatchedNodes =\n\t\tMetaPopulationFactory::getAllHierarchicalNodes(nodes);\n\n\tfor (unsigned int i = 0; i < unmatchedNodes.size(); i++)\n\t\tfor (unsigned int k = 0; k < nodes.size(); k++)\n\t\t\tif (unmatchedNodes[i] == nodes[k])\n\t\t\t\tunmatchedNodes.erase(\n\t\t\t\t\tunmatchedNodes.begin() + i--\n\t\t\t\t);\n\n\treturn unmatchedNodes.empty();\n}\n\nbool MetaPopulationFactory::isSingleBlanket(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::vector<PopulationNode*> unmatchedNodes =\n\t\tMetaPopulationFactory::getAllHierarchicalNodes(nodes);\n\tunsigned int rootNodes = 0;\n\n\tfor (unsigned int i = 0; i < nodes.size(); i++) {\n\t\tbool matched = false;\n\t\tfor (unsigned int k = 0; k < unmatchedNodes.size(); k++)\n\t\t\tif (nodes[i] == unmatchedNodes[k]) {\n\t\t\t\tmatched = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (matched) rootNodes++;\n\t}\n\n\treturn rootNodes == 1;\n}\n\nbool MetaPopulationFactory::isValidBlanket(\n\tPopulationNode * topNode,\n\tstd::vector<PopulationNode*> secondaryNodes\n) {\n\tstd::vector<PopulationNode*> nodes = secondaryNodes;\n\tnodes.push_back(topNode);\n\n\tif (!MetaPopulationFactory::isCompleteBlanket(nodes)) return false;\n\tif (!MetaPopulationFactory::isSingleBlanket(nodes)) return false;\n\n\treturn true;\n}\n\nPopulationNode * MetaPopulationFactory::createMeta(\n\tPopulationNode * metaNode,\n\tstd::vector<ObjectiveFunction *> flattenedObjectives,\n\tToStringFunction * flattenedToString,\n\tPopulationNode * topNode,\n\tstd::tuple<\n\t\tApportionmentFunction *,\n\t\tAggregationFunction *\n\t> topNodeApportionment,\n\tstd::vector<std::tuple<\n\t\tPopulationNode *,\n\t\tApportionmentFunction *,\n\t\tAggregationFunction *\n\t>> secondaryNodes\n) {\n\tstd::vector<PopulationNode*> secondaryPopNodes;\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tsecondaryPopNodes.push_back(std::get<0>(secondaryNodes[i]));\n\tif (!MetaPopulationFactory::isValidBlanket(topNode, secondaryPopNodes))\n\t\tthrow InvalidBlanketException();\n\n\tstd::vector<Locus*> newLoci;\n\tnewLoci.push_back(new PopulationLocus(topNode));\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tnewLoci.push_back(new PopulationLocus(\n\t\t\tstd::get<0>(secondaryNodes[i])\n\t\t));\n\n\tmetaNode->setLoci(newLoci);\n\n\t\/\/ The normal varieties won't work on a meta-population anyways\n\tmetaNode->setObjectives({});\n\tmetaNode->setToString(new MetaPopulationToString(flattenedToString));\n\n\tfor (unsigned int i = 0; i < flattenedObjectives.size(); i++)\n\t\tmetaNode->addObjective((ObjectiveFunction*)\n\t\t\tnew MetaPopulationObjective(flattenedObjectives[i])\n\t\t);\n\n\ttopNode->addObjective(new MetaPopulationApportionment(\n\t\tmetaNode,\n\t\tstd::get<0>(topNodeApportionment),\n\t\tstd::get<1>(topNodeApportionment)\n\t));\n\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tstd::get<0>(secondaryNodes[i])->addObjective(\n\t\t\t(ObjectiveFunction*)new MetaPopulationApportionment(\n\t\t\t\tmetaNode,\n\t\t\t\tstd::get<1>(secondaryNodes[i]),\n\t\t\t\tstd::get<2>(secondaryNodes[i])\n\t\t\t)\n\t\t);\n\n\treturn metaNode;\n}\n<commit_msg>[MetaPopulationFactory]: Fixed logic error in root counter<commit_after>#include \"core\/meta\/MetaPopulationFactory.hpp\"\n#include \"core\/PopulationNode.hpp\"\n#include \"core\/Apportionment.hpp\"\n#include \"core\/ObjectiveFunction.hpp\"\n#include \"core\/meta\/MetaPopulationObjective.hpp\"\n#include \"core\/meta\/MetaPopulationApportionment.hpp\"\n#include \"core\/meta\/MetaPopulationToString.hpp\"\n#include \"loci\/PopulationLocus.hpp\"\n#include \"exception\/InvalidBlanketException.hpp\"\n\n#include <set>\n\nstd::vector<PopulationNode*> MetaPopulationFactory::getAllHierarchicalNodes(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::set<Locus*> constructiveLoci;\n\tstd::vector<PopulationNode*> unmatchedNodes;\n\tfor (unsigned int i = 0; i < nodes.size(); i++) {\n\t\tconstructiveLoci = nodes[i]->getConstructiveLoci();\n\t\tfor (auto k : constructiveLoci)\n\t\t\tunmatchedNodes.push_back(\n\t\t\t\t((PopulationLocus*)k)->getNode()\n\t\t\t);\n\t}\n\n\treturn unmatchedNodes;\n}\n\nbool MetaPopulationFactory::isCompleteBlanket(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::vector<PopulationNode*> unmatchedNodes =\n\t\tMetaPopulationFactory::getAllHierarchicalNodes(nodes);\n\n\tfor (unsigned int i = 0; i < unmatchedNodes.size(); i++)\n\t\tfor (unsigned int k = 0; k < nodes.size(); k++)\n\t\t\tif (unmatchedNodes[i] == nodes[k])\n\t\t\t\tunmatchedNodes.erase(\n\t\t\t\t\tunmatchedNodes.begin() + i--\n\t\t\t\t);\n\n\treturn unmatchedNodes.empty();\n}\n\nbool MetaPopulationFactory::isSingleBlanket(\n\tstd::vector<PopulationNode*> nodes\n) {\n\tstd::vector<PopulationNode*> unmatchedNodes =\n\t\tMetaPopulationFactory::getAllHierarchicalNodes(nodes);\n\tunsigned int rootNodes = 0;\n\n\tfor (unsigned int i = 0; i < nodes.size(); i++) {\n\t\tbool matched = false;\n\t\tfor (unsigned int k = 0; k < unmatchedNodes.size(); k++)\n\t\t\tif (nodes[i] == unmatchedNodes[k]) {\n\t\t\t\tmatched = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (!matched) rootNodes++;\n\t}\n\n\treturn rootNodes == 1;\n}\n\nbool MetaPopulationFactory::isValidBlanket(\n\tPopulationNode * topNode,\n\tstd::vector<PopulationNode*> secondaryNodes\n) {\n\tstd::vector<PopulationNode*> nodes = secondaryNodes;\n\tnodes.push_back(topNode);\n\n\tif (!MetaPopulationFactory::isCompleteBlanket(nodes)) return false;\n\tif (!MetaPopulationFactory::isSingleBlanket(nodes)) return false;\n\n\treturn true;\n}\n\nPopulationNode * MetaPopulationFactory::createMeta(\n\tPopulationNode * metaNode,\n\tstd::vector<ObjectiveFunction *> flattenedObjectives,\n\tToStringFunction * flattenedToString,\n\tPopulationNode * topNode,\n\tstd::tuple<\n\t\tApportionmentFunction *,\n\t\tAggregationFunction *\n\t> topNodeApportionment,\n\tstd::vector<std::tuple<\n\t\tPopulationNode *,\n\t\tApportionmentFunction *,\n\t\tAggregationFunction *\n\t>> secondaryNodes\n) {\n\tstd::vector<PopulationNode*> secondaryPopNodes;\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tsecondaryPopNodes.push_back(std::get<0>(secondaryNodes[i]));\n\tif (!MetaPopulationFactory::isValidBlanket(topNode, secondaryPopNodes))\n\t\tthrow InvalidBlanketException();\n\n\tstd::vector<Locus*> newLoci;\n\tnewLoci.push_back(new PopulationLocus(topNode));\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tnewLoci.push_back(new PopulationLocus(\n\t\t\tstd::get<0>(secondaryNodes[i])\n\t\t));\n\n\tmetaNode->setLoci(newLoci);\n\n\t\/\/ The normal varieties won't work on a meta-population anyways\n\tmetaNode->setObjectives({});\n\tmetaNode->setToString(new MetaPopulationToString(flattenedToString));\n\n\tfor (unsigned int i = 0; i < flattenedObjectives.size(); i++)\n\t\tmetaNode->addObjective((ObjectiveFunction*)\n\t\t\tnew MetaPopulationObjective(flattenedObjectives[i])\n\t\t);\n\n\ttopNode->addObjective(new MetaPopulationApportionment(\n\t\tmetaNode,\n\t\tstd::get<0>(topNodeApportionment),\n\t\tstd::get<1>(topNodeApportionment)\n\t));\n\n\tfor (unsigned int i = 0; i < secondaryNodes.size(); i++)\n\t\tstd::get<0>(secondaryNodes[i])->addObjective(\n\t\t\t(ObjectiveFunction*)new MetaPopulationApportionment(\n\t\t\t\tmetaNode,\n\t\t\t\tstd::get<1>(secondaryNodes[i]),\n\t\t\t\tstd::get<2>(secondaryNodes[i])\n\t\t\t)\n\t\t);\n\n\treturn metaNode;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 1998-2001 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define CS_SYSDEF_PROVIDE_ALLOCA\n#include \"cssysdef.h\"\n#include \"csutil\/scf.h\"\n#include \"csutil\/plugldr.h\"\n#include \"csutil\/csvector.h\"\n#include \"csutil\/util.h\"\n#include \"csutil\/snprintf.h\"\n#include \"ivaria\/reporter.h\"\n#include \"iutil\/objreg.h\"\n#include \"iutil\/cmdline.h\"\n#include \"iutil\/cfgmgr.h\"\n#include \"iutil\/plugin.h\"\n#include \"iutil\/vfs.h\"\n\n\/**\n * Since every plugin can depend on another one, the plugin loader should be\n * able to sort them by their preferences. Thus, if some plugin A wants some\n * other plugins B and C to be loaded before him, the plugin loader should\n * sort the list of loaded plugins such that plugin A comes after B and C.\n * <p>\n * Of course it is possible that some plugin A depends on B and B depends on A,\n * or even worse A on B, B on C and C on A. The sort algorithm should detect\n * this case and type an error message if it is detected.\n * <p>\n * The algorithm works as follows. First, a dependency matrix is built. Here\n * is a example of a simple dependency matrix:\n * <pre>\n * iEngine iVFS iGraphics3D iGraphics2D\n * +-----------+-----------+-----------+-----------+\n * iEngine | | X | X | X |\n * +-----------+-----------+-----------+-----------+\n * iVFS | | | | |\n * +-----------+-----------+-----------+-----------+\n * iGraphics3D | | X | | X |\n * +-----------+-----------+-----------+-----------+\n * iGraphics2D | | X | | |\n * +-----------+-----------+-----------+-----------+\n * <\/pre>\n * Thus, we see that the iEngine plugin depends on iVFS, iGraphics3D and\n * iGraphics2D plugins (this is an abstract example, in reality the\n * things are simpler), iVFS does not depend on anything, iGraphics3D\n * wants the iVFS and the iGraphics2D plugins, and finally iGraphics2D\n * wants just the iVFS.\n * <p>\n * The sort algorithm works as follows: we take each plugin, one by one\n * starting from first (iEngine) and examine each of them. If some plugin\n * depends on others, we recursively launch this algorithm on those plugins.\n * If we don't have any more dependencies, we put the plugin into the\n * load list and return to the previous recursion level. To detect loops\n * we need to maintain an \"recurse list\", thus if we found that iEngine\n * depends on iGraphics3D, iGraphics3D depends on iGraphics2D and we're\n * examining iGraphics2D for dependencies, we have the following\n * loop-detection array: iEngine, iGraphics3D, iGraphics2D. If we find that\n * iGraphics2D depends on anyone that is in the loop array, we found a loop.\n * If we find that the plugin depends on anyone that is already in the load\n * list, its not a loop but just an already-fullfilled dependency.\n * Thus, the above table will be traversed this way (to the left is the\n * load list, to the right is the loop detection list):\n * <pre><ol>\n * <li> [] [iEngine]\n * <li> [] [iEngine,iVFS]\n * <li> [iVFS] [iEngine]\n * <li> [iVFS] [iEngine,iGraphics3D]\n * <li> [iVFS] [iEngine,iGraphics3D,iGraphics2D]\n * <li> [iVFS,iGraphics2D] [iEngine,iGraphics3D]\n * <li> [iVFS,iGraphics2D,iGraphics3D] [iEngine]\n * <li> [iVFS,iGraphics2D,iGraphics3D,iEngine] []\n * <\/ol><\/pre>\n * In this example we traversed all plugins in one go. If we didn't, we\n * just take the next one (iEngine, iVFS, iGraphics3D, iGraphics2D) and if\n * it is not already in the load list, recursively traverse it.\n *\/\nbool csPluginList::Sort (iObjectRegistry* object_reg)\n{\n int row, col, len = Length ();\n\n \/\/ Build the dependency matrix\n bool *matrix = (bool *)alloca (len * len * sizeof (bool));\n memset (matrix, 0, len * len * sizeof (bool));\n for (row = 0; row < len; row++)\n {\n const char *dep = iSCF::SCF->GetClassDependencies (Get (row).ClassID);\n while (dep && *dep)\n {\n char tmp [100];\n const char *comma = strchr (dep, ',');\n if (!comma)\n comma = strchr (dep, 0);\n size_t sl = comma - dep;\n if (sl >= sizeof (tmp))\n sl = sizeof (tmp) - 1;\n memcpy (tmp, dep, sl);\n while (sl && ((tmp [sl - 1] == ' ') || (tmp [sl - 1] == '\\t')))\n sl--;\n tmp [sl] = 0;\n if (!sl)\n break;\n bool wildcard = tmp [sl - 1] == '.';\n for (col = 0; col < len; col++)\n if ((col != row)\n && (wildcard ? strncmp (tmp, Get (col).ClassID, sl) :\n strcmp (tmp, Get (col).ClassID)) == 0)\n matrix [row * len + col] = true;\n dep = comma;\n while (*dep == ',' || *dep == ' ' || *dep == '\\t')\n dep++;\n }\n }\n\n \/\/ Go through dependency matrix and put all plugins into an array\n bool error = false;\n int *order = (int *)alloca (sizeof (int) * (len + 1));\n *order = 0;\n int *loop = (int *)alloca (sizeof (int) * (len + 1));\n *loop = 0;\n\n for (row = 0; row < len; row++)\n if (!RecurseSort (object_reg, row, order, loop, matrix))\n error = true;\n\n \/\/ Reorder plugin list according to \"order\" array\n csSome *newroot = (csSome *)malloc (len * sizeof (csSome));\n for (row = 0; row < len; row++)\n newroot [row] = root [order [row] - 1];\n free (root); root = newroot;\n\n return !error;\n}\n\nstatic int* strchr_int (int* str, int fnd)\n{\n while (*str != fnd)\n {\n if (!*str) return NULL;\n str++;\n }\n return str;\n}\n\nbool csPluginList::RecurseSort (iObjectRegistry *object_reg,\n\tint row, int *order, int *loop, bool *matrix)\n{\n \/\/ If the plugin is already in the load list, skip it\n if (strchr_int (order, row + 1))\n return true;\n\n int len = Length ();\n bool *dep = matrix + row * len;\n bool error = false;\n int *loopp = strchr_int (loop, 0);\n *loopp++ = row + 1; *loopp = 0;\n int col, x;\n for (col = 0; col < len; col++)\n if (*dep++)\n {\n \/\/ If the plugin is already loaded, skip\n if (strchr_int (order, col + 1))\n continue;\n\n int *already = strchr_int (loop, col + 1);\n if (already)\n {\n\tcsReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n\t \"crystalspace.pluginloader.recursesort\",\n\t \"Cyclic dependency detected!\");\n int startx = int (already - loop);\n for (x = startx; loop [x]; x++)\n\t{\n\t csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n\t \"crystalspace.pluginloader.recursesort\",\n \" %s %s\",\n x == startx ? \"+->\" : loop [x + 1] ? \"| |\" : \"<-+\",\n Get (loop [x] - 1).ClassID);\n\t}\n error = true;\n break;\n }\n\n bool recurse_error = !RecurseSort (object_reg, col, order, loop, matrix);\n\n \/\/ Drop recursive loop dependency since it has already been ordered.\n *loopp = 0;\n\n if (recurse_error)\n {\n error = true;\n break;\n }\n }\n\n \/\/ Put current plugin into the list\n int *orderp = strchr_int (order, 0);\n *orderp++ = row + 1; *orderp = 0;\n\n return !error;\n}\n\n\/\/--------------------------------------------------- The plugin loader -----\/\/\n\ncsPluginLoader::csPluginLoader (iObjectRegistry* object_reg)\n{\n csPluginLoader::object_reg = object_reg;\n}\n\ncsPluginLoader::~csPluginLoader ()\n{\n}\n\nbool csPluginLoader::LoadPlugins ()\n{\n \/\/ Collect all options from command line\n iCommandLineParser* CommandLine = CS_QUERY_REGISTRY (object_reg,\n \tiCommandLineParser);\n CS_ASSERT (CommandLine != NULL);\n\n \/\/ The list of plugins\n csPluginList PluginList;\n\n \/\/ Now eat all common-for-plugins command-line switches\n bool g3d_override = false;\n\n const char *val;\n if ((val = CommandLine->GetOption (\"video\")))\n {\n \/\/ Alternate videodriver\n char temp [100];\n cs_snprintf (temp, sizeof(temp), \"crystalspace.graphics3d.%s\", val);\n \/\/sprintf (temp, \"crystalspace.graphics3d.%s\", val);\n csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,\n \t\"crystalspace.pluginloader.loadplugins\",\n \t\"Using alternative 3D driver: %s\", temp);\n PluginList.Push (new csPluginLoadRec (\"iGraphics3D\", temp));\n g3d_override = true;\n }\n if ((val = CommandLine->GetOption (\"canvas\")))\n {\n if (!strchr (val, '.'))\n {\n char temp [100];\n cs_snprintf (temp, sizeof(temp), \"crystalspace.graphics2d.%s\", val);\n \/\/sprintf (temp, \"crystalspace.graphics2d.%s\", val);\n CommandLine->ReplaceOption (\"canvas\", temp);\n }\n }\n\n \/\/ Eat all --plugin switches specified on the command line\n int n = 0;\n while ((val = CommandLine->GetOption (\"plugin\", n++)))\n {\n size_t sl = strlen (val);\n char temp [100];\n if (sl >= sizeof (temp)) sl = sizeof (temp) - 1;\n memcpy (temp, val, sl); temp [sl] = 0;\n char *tag = strchr (temp, ':');\n if (tag) *tag++ = 0;\n if (g3d_override && !strcmp (\"iGraphics3D\", tag)) continue;\n PluginList.Push (new csPluginLoadRec (tag, temp));\n }\n\n CommandLine->DecRef (); CommandLine = NULL;\n\n \/\/ Now load and initialize all plugins\n iConfigManager* Config = CS_QUERY_REGISTRY (object_reg, iConfigManager);\n iConfigIterator *plugin_list = Config->Enumerate (\"System.Plugins.\");\n if (plugin_list)\n {\n while (plugin_list->Next ())\n {\n const char *tag = plugin_list->GetKey (true);\n \/\/ If -video was used to override 3D driver, then respect it.\n if (g3d_override && strcmp (tag, \"iGraphics3D\") == 0)\n continue;\n const char *classID = plugin_list->GetStr ();\n if (classID)\n PluginList.Push (new csPluginLoadRec (tag, classID));\n }\n plugin_list->DecRef ();\n }\n\n iVFS* VFS = CS_QUERY_REGISTRY (object_reg, iVFS);\n\n \/\/ Check all requested plugins and see if there is already\n \/\/ a plugin with that tag present. If not we add it.\n int i;\n for (i = 0 ; i < requested_plugins.Length () ; i++)\n {\n csPluginLoadRec& req_plugin = requested_plugins.Get (i);\n int j;\n bool present = false;\n for (j = 0 ; j < PluginList.Length () ; j++)\n {\n csPluginLoadRec& plugin = PluginList.Get (j);\n if (plugin.Tag && !strcmp (plugin.Tag, req_plugin.Tag))\n {\n present = true;\n\tbreak;\n }\n }\n if (!present)\n {\n PluginList.Push (new csPluginLoadRec (req_plugin.Tag,\n \treq_plugin.ClassID));\n }\n }\n\n \/\/ Sort all plugins by their dependency lists\n if (!PluginList.Sort (object_reg))\n {\n Config->DecRef ();\n if (VFS) VFS->DecRef ();\n return false;\n }\n\n iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);\n\n \/\/ Load all plugins\n for (n = 0; n < PluginList.Length (); n++)\n {\n const csPluginLoadRec& r = PluginList.Get(n);\n \/\/ If plugin is VFS then skip if already loaded earlier.\n if (VFS && r.Tag && strcmp (r.Tag, \"iVFS\") == 0)\n continue;\n iBase *plg = plugin_mgr->LoadPlugin (r.ClassID, NULL, 0);\n if (plg)\n {\n if (!object_reg->Register (plg, r.Tag))\n {\n Config->DecRef ();\n plugin_mgr->DecRef ();\n if (VFS) VFS->DecRef ();\n if (r.Tag)\n csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n \t \"crystalspace.pluginloader.loadplugins\",\n \t \"Duplicate tag '%s' found for plugin '%s'!\", r.Tag, r.ClassID);\n else\n csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n \t \"crystalspace.pluginloader.loadplugins\",\n \t \"Could not register plugin '%s'!\", r.ClassID);\n return false;\n }\n plg->DecRef ();\n }\n }\n\n \/\/ flush all removed config files\n Config->FlushRemoved();\n\n Config->DecRef ();\n plugin_mgr->DecRef ();\n if (VFS) VFS->DecRef ();\n return true;\n}\n\nvoid csPluginLoader::RequestPlugin (const char *pluginName,\n\tconst char* tagName)\n{\n requested_plugins.Push (new csPluginLoadRec (tagName, pluginName));\n}\n\n<commit_msg>small fix<commit_after>\/*\n Copyright (C) 1998-2001 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define CS_SYSDEF_PROVIDE_ALLOCA\n#include \"cssysdef.h\"\n#include \"csutil\/scf.h\"\n#include \"csutil\/plugldr.h\"\n#include \"csutil\/csvector.h\"\n#include \"csutil\/util.h\"\n#include \"csutil\/snprintf.h\"\n#include \"ivaria\/reporter.h\"\n#include \"iutil\/objreg.h\"\n#include \"iutil\/cmdline.h\"\n#include \"iutil\/cfgmgr.h\"\n#include \"iutil\/plugin.h\"\n#include \"iutil\/vfs.h\"\n\n\/**\n * Since every plugin can depend on another one, the plugin loader should be\n * able to sort them by their preferences. Thus, if some plugin A wants some\n * other plugins B and C to be loaded before him, the plugin loader should\n * sort the list of loaded plugins such that plugin A comes after B and C.\n * <p>\n * Of course it is possible that some plugin A depends on B and B depends on A,\n * or even worse A on B, B on C and C on A. The sort algorithm should detect\n * this case and type an error message if it is detected.\n * <p>\n * The algorithm works as follows. First, a dependency matrix is built. Here\n * is a example of a simple dependency matrix:\n * <pre>\n * iEngine iVFS iGraphics3D iGraphics2D\n * +-----------+-----------+-----------+-----------+\n * iEngine | | X | X | X |\n * +-----------+-----------+-----------+-----------+\n * iVFS | | | | |\n * +-----------+-----------+-----------+-----------+\n * iGraphics3D | | X | | X |\n * +-----------+-----------+-----------+-----------+\n * iGraphics2D | | X | | |\n * +-----------+-----------+-----------+-----------+\n * <\/pre>\n * Thus, we see that the iEngine plugin depends on iVFS, iGraphics3D and\n * iGraphics2D plugins (this is an abstract example, in reality the\n * things are simpler), iVFS does not depend on anything, iGraphics3D\n * wants the iVFS and the iGraphics2D plugins, and finally iGraphics2D\n * wants just the iVFS.\n * <p>\n * The sort algorithm works as follows: we take each plugin, one by one\n * starting from first (iEngine) and examine each of them. If some plugin\n * depends on others, we recursively launch this algorithm on those plugins.\n * If we don't have any more dependencies, we put the plugin into the\n * load list and return to the previous recursion level. To detect loops\n * we need to maintain an \"recurse list\", thus if we found that iEngine\n * depends on iGraphics3D, iGraphics3D depends on iGraphics2D and we're\n * examining iGraphics2D for dependencies, we have the following\n * loop-detection array: iEngine, iGraphics3D, iGraphics2D. If we find that\n * iGraphics2D depends on anyone that is in the loop array, we found a loop.\n * If we find that the plugin depends on anyone that is already in the load\n * list, its not a loop but just an already-fullfilled dependency.\n * Thus, the above table will be traversed this way (to the left is the\n * load list, to the right is the loop detection list):\n * <pre><ol>\n * <li> [] [iEngine]\n * <li> [] [iEngine,iVFS]\n * <li> [iVFS] [iEngine]\n * <li> [iVFS] [iEngine,iGraphics3D]\n * <li> [iVFS] [iEngine,iGraphics3D,iGraphics2D]\n * <li> [iVFS,iGraphics2D] [iEngine,iGraphics3D]\n * <li> [iVFS,iGraphics2D,iGraphics3D] [iEngine]\n * <li> [iVFS,iGraphics2D,iGraphics3D,iEngine] []\n * <\/ol><\/pre>\n * In this example we traversed all plugins in one go. If we didn't, we\n * just take the next one (iEngine, iVFS, iGraphics3D, iGraphics2D) and if\n * it is not already in the load list, recursively traverse it.\n *\/\nbool csPluginList::Sort (iObjectRegistry* object_reg)\n{\n int row, col, len = Length ();\n\n \/\/ Build the dependency matrix\n bool *matrix = (bool *)alloca (len * len * sizeof (bool));\n memset (matrix, 0, len * len * sizeof (bool));\n for (row = 0; row < len; row++)\n {\n const char *dep = iSCF::SCF->GetClassDependencies (Get (row).ClassID);\n while (dep && *dep)\n {\n char tmp [100];\n const char *comma = strchr (dep, ',');\n if (!comma)\n comma = strchr (dep, 0);\n size_t sl = comma - dep;\n if (sl >= sizeof (tmp))\n sl = sizeof (tmp) - 1;\n memcpy (tmp, dep, sl);\n while (sl && ((tmp [sl - 1] == ' ') || (tmp [sl - 1] == '\\t')))\n sl--;\n tmp [sl] = 0;\n if (!sl)\n break;\n bool wildcard = tmp [sl - 1] == '.';\n for (col = 0; col < len; col++)\n if ((col != row)\n && (wildcard ? strncmp (tmp, Get (col).ClassID, sl) :\n strcmp (tmp, Get (col).ClassID)) == 0)\n matrix [row * len + col] = true;\n dep = comma;\n while (*dep == ',' || *dep == ' ' || *dep == '\\t')\n dep++;\n }\n }\n\n \/\/ Go through dependency matrix and put all plugins into an array\n bool error = false;\n int *order = (int *)alloca (sizeof (int) * (len + 1));\n *order = 0;\n int *loop = (int *)alloca (sizeof (int) * (len + 1));\n *loop = 0;\n\n for (row = 0; row < len; row++)\n if (!RecurseSort (object_reg, row, order, loop, matrix))\n error = true;\n\n \/\/ Reorder plugin list according to \"order\" array\n csSome *newroot = (csSome *)malloc (len * sizeof (csSome));\n for (row = 0; row < len; row++)\n newroot [row] = root [order [row] - 1];\n free (root); root = newroot;\n\n return !error;\n}\n\nstatic int* strchr_int (int* str, int fnd)\n{\n while (*str != fnd)\n {\n if (!*str) return NULL;\n str++;\n }\n return str;\n}\n\nbool csPluginList::RecurseSort (iObjectRegistry *object_reg,\n\tint row, int *order, int *loop, bool *matrix)\n{\n \/\/ If the plugin is already in the load list, skip it\n if (strchr_int (order, row + 1))\n return true;\n\n int len = Length ();\n bool *dep = matrix + row * len;\n bool error = false;\n int *loopp = strchr_int (loop, 0);\n *loopp++ = row + 1; *loopp = 0;\n int col, x;\n for (col = 0; col < len; col++)\n if (*dep++)\n {\n \/\/ If the plugin is already loaded, skip\n if (strchr_int (order, col + 1))\n continue;\n\n int *already = strchr_int (loop, col + 1);\n if (already)\n {\n\tcsReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n\t \"crystalspace.pluginloader.recursesort\",\n\t \"Cyclic dependency detected!\");\n int startx = int (already - loop);\n for (x = startx; loop [x]; x++)\n\t{\n\t csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n\t \"crystalspace.pluginloader.recursesort\",\n \" %s %s\",\n x == startx ? \"+->\" : loop [x + 1] ? \"| |\" : \"<-+\",\n Get (loop [x] - 1).ClassID);\n\t}\n error = true;\n break;\n }\n\n bool recurse_error = !RecurseSort (object_reg, col, order, loop, matrix);\n\n \/\/ Drop recursive loop dependency since it has already been ordered.\n *loopp = 0;\n\n if (recurse_error)\n {\n error = true;\n break;\n }\n }\n\n \/\/ Put current plugin into the list\n int *orderp = strchr_int (order, 0);\n *orderp++ = row + 1; *orderp = 0;\n\n return !error;\n}\n\n\/\/--------------------------------------------------- The plugin loader -----\/\/\n\ncsPluginLoader::csPluginLoader (iObjectRegistry* object_reg)\n{\n csPluginLoader::object_reg = object_reg;\n}\n\ncsPluginLoader::~csPluginLoader ()\n{\n}\n\nbool csPluginLoader::LoadPlugins ()\n{\n \/\/ Collect all options from command line\n iCommandLineParser* CommandLine = CS_QUERY_REGISTRY (object_reg,\n \tiCommandLineParser);\n CS_ASSERT (CommandLine != NULL);\n\n \/\/ The list of plugins\n csPluginList PluginList;\n\n \/\/ Now eat all common-for-plugins command-line switches\n bool g3d_override = false;\n\n const char *val;\n if ((val = CommandLine->GetOption (\"video\")))\n {\n \/\/ Alternate videodriver\n char temp [100];\n cs_snprintf (temp, sizeof(temp), \"crystalspace.graphics3d.%s\", val);\n \/\/sprintf (temp, \"crystalspace.graphics3d.%s\", val);\n csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,\n \t\"crystalspace.pluginloader.loadplugins\",\n \t\"Using alternative 3D driver: %s\", temp);\n PluginList.Push (new csPluginLoadRec (\"iGraphics3D\", temp));\n g3d_override = true;\n }\n if ((val = CommandLine->GetOption (\"canvas\")))\n {\n if (!strchr (val, '.'))\n {\n char temp [100];\n cs_snprintf (temp, sizeof(temp), \"crystalspace.graphics2d.%s\", val);\n \/\/sprintf (temp, \"crystalspace.graphics2d.%s\", val);\n CommandLine->ReplaceOption (\"canvas\", temp);\n }\n }\n\n \/\/ Eat all --plugin switches specified on the command line\n int n = 0;\n while ((val = CommandLine->GetOption (\"plugin\", n++)))\n {\n size_t sl = strlen (val);\n char temp [100];\n if (sl >= sizeof (temp)) sl = sizeof (temp) - 1;\n memcpy (temp, val, sl); temp [sl] = 0;\n char *tag = strchr (temp, ':');\n if (tag) *tag++ = 0;\n if (g3d_override && tag && !strcmp (\"iGraphics3D\", tag)) continue;\n PluginList.Push (new csPluginLoadRec (tag, temp));\n }\n\n CommandLine->DecRef (); CommandLine = NULL;\n\n \/\/ Now load and initialize all plugins\n iConfigManager* Config = CS_QUERY_REGISTRY (object_reg, iConfigManager);\n iConfigIterator *plugin_list = Config->Enumerate (\"System.Plugins.\");\n if (plugin_list)\n {\n while (plugin_list->Next ())\n {\n const char *tag = plugin_list->GetKey (true);\n \/\/ If -video was used to override 3D driver, then respect it.\n if (g3d_override && strcmp (tag, \"iGraphics3D\") == 0)\n continue;\n const char *classID = plugin_list->GetStr ();\n if (classID)\n PluginList.Push (new csPluginLoadRec (tag, classID));\n }\n plugin_list->DecRef ();\n }\n\n iVFS* VFS = CS_QUERY_REGISTRY (object_reg, iVFS);\n\n \/\/ Check all requested plugins and see if there is already\n \/\/ a plugin with that tag present. If not we add it.\n int i;\n for (i = 0 ; i < requested_plugins.Length () ; i++)\n {\n csPluginLoadRec& req_plugin = requested_plugins.Get (i);\n int j;\n bool present = false;\n for (j = 0 ; j < PluginList.Length () ; j++)\n {\n csPluginLoadRec& plugin = PluginList.Get (j);\n if (plugin.Tag && !strcmp (plugin.Tag, req_plugin.Tag))\n {\n present = true;\n\tbreak;\n }\n }\n if (!present)\n {\n PluginList.Push (new csPluginLoadRec (req_plugin.Tag,\n \treq_plugin.ClassID));\n }\n }\n\n \/\/ Sort all plugins by their dependency lists\n if (!PluginList.Sort (object_reg))\n {\n Config->DecRef ();\n if (VFS) VFS->DecRef ();\n return false;\n }\n\n iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);\n\n \/\/ Load all plugins\n for (n = 0; n < PluginList.Length (); n++)\n {\n const csPluginLoadRec& r = PluginList.Get(n);\n \/\/ If plugin is VFS then skip if already loaded earlier.\n if (VFS && r.Tag && strcmp (r.Tag, \"iVFS\") == 0)\n continue;\n iBase *plg = plugin_mgr->LoadPlugin (r.ClassID, NULL, 0);\n if (plg)\n {\n if (!object_reg->Register (plg, r.Tag))\n {\n Config->DecRef ();\n plugin_mgr->DecRef ();\n if (VFS) VFS->DecRef ();\n if (r.Tag)\n csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n \t \"crystalspace.pluginloader.loadplugins\",\n \t \"Duplicate tag '%s' found for plugin '%s'!\", r.Tag, r.ClassID);\n else\n csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,\n \t \"crystalspace.pluginloader.loadplugins\",\n \t \"Could not register plugin '%s'!\", r.ClassID);\n return false;\n }\n plg->DecRef ();\n }\n }\n\n \/\/ flush all removed config files\n Config->FlushRemoved();\n\n Config->DecRef ();\n plugin_mgr->DecRef ();\n if (VFS) VFS->DecRef ();\n return true;\n}\n\nvoid csPluginLoader::RequestPlugin (const char *pluginName,\n\tconst char* tagName)\n{\n requested_plugins.Push (new csPluginLoadRec (tagName, pluginName));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n#include <vector>\n\n#include \"ash\/desktop_background\/desktop_background_controller.h\"\n#include \"ash\/desktop_background\/desktop_background_controller_observer.h\"\n#include \"ash\/shell.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_manager_test.h\"\n#include \"chrome\/browser\/chromeos\/login\/startup_utils.h\"\n#include \"chrome\/browser\/chromeos\/login\/user.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/chromeos\/login\/wallpaper_manager.h\"\n#include \"chrome\/browser\/chromeos\/policy\/cloud_external_data_manager_base_test_util.h\"\n#include \"chrome\/browser\/chromeos\/policy\/user_cloud_policy_manager_chromeos.h\"\n#include \"chrome\/browser\/chromeos\/policy\/user_cloud_policy_manager_factory_chromeos.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chromeos\/chromeos_paths.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"chromeos\/dbus\/cryptohome_client.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/fake_dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/fake_session_manager_client.h\"\n#include \"chromeos\/dbus\/session_manager_client.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_core.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_store.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_validator.h\"\n#include \"components\/policy\/core\/common\/cloud\/policy_builder.h\"\n#include \"crypto\/rsa_private_key.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n#include \"policy\/proto\/cloud_policy.pb.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/skia\/include\/core\/SkColor.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"url\/gurl.h\"\n\nnamespace chromeos {\n\nnamespace {\n\nconst char kTestUsers[2][19] = { \"test-0@example.com\", \"test-1@example.com\" };\n\nconst char kRedImageFileName[] = \"chromeos\/wallpapers\/red.jpg\";\nconst char kGreenImageFileName[] = \"chromeos\/wallpapers\/green.jpg\";\nconst char kBlueImageFileName[] = \"chromeos\/wallpapers\/blue.jpg\";\n\nconst SkColor kRedImageColor = SkColorSetARGB(255, 199, 6, 7);\nconst SkColor kGreenImageColor = SkColorSetARGB(255, 38, 196, 15);\n\npolicy::CloudPolicyStore* GetStoreForUser(const User* user) {\n Profile* profile = UserManager::Get()->GetProfileByUser(user);\n if (!profile) {\n ADD_FAILURE();\n return NULL;\n }\n policy::UserCloudPolicyManagerChromeOS* policy_manager =\n policy::UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile);\n if (!policy_manager) {\n ADD_FAILURE();\n return NULL;\n }\n return policy_manager->core()->store();\n}\n\n\/\/ Compute the average ARGB color of |bitmap|.\nSkColor ComputeAverageColor(const SkBitmap& bitmap) {\n if (bitmap.empty() || bitmap.width() < 1 || bitmap.height() < 1) {\n ADD_FAILURE() << \"Empty or invalid bitmap.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n if (bitmap.isNull()) {\n ADD_FAILURE() << \"Bitmap has no pixelref.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n if (bitmap.config() == SkBitmap::kNo_Config) {\n ADD_FAILURE() << \"Bitmap has not been configured.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n uint64 a = 0, r = 0, g = 0, b = 0;\n bitmap.lockPixels();\n for (int x = 0; x < bitmap.width(); ++x) {\n for (int y = 0; y < bitmap.height(); ++y) {\n const SkColor color = bitmap.getColor(x, y);\n a += SkColorGetA(color);\n r += SkColorGetR(color);\n g += SkColorGetG(color);\n b += SkColorGetB(color);\n }\n }\n bitmap.unlockPixels();\n uint64 pixel_number = bitmap.width() * bitmap.height();\n return SkColorSetARGB((a + pixel_number \/ 2) \/ pixel_number,\n (r + pixel_number \/ 2) \/ pixel_number,\n (g + pixel_number \/ 2) \/ pixel_number,\n (b + pixel_number \/ 2) \/ pixel_number);\n}\n\n\/\/ Obtain background image and return its average ARGB color.\nSkColor GetAverageBackgroundColor() {\n const gfx::ImageSkia image =\n ash::Shell::GetInstance()->desktop_background_controller()->\n GetWallpaper();\n\n const gfx::ImageSkiaRep& representation = image.GetRepresentation(1.);\n if (representation.is_null()) {\n ADD_FAILURE() << \"No image representation.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n\n const SkBitmap& bitmap = representation.sk_bitmap();\n return ComputeAverageColor(bitmap);\n}\n\n} \/\/ namespace\n\nclass WallpaperManagerPolicyTest\n : public LoginManagerTest,\n public ash::DesktopBackgroundControllerObserver,\n public testing::WithParamInterface<bool> {\n protected:\n WallpaperManagerPolicyTest()\n : LoginManagerTest(true),\n wallpaper_change_count_(0),\n fake_dbus_thread_manager_(new FakeDBusThreadManager),\n fake_session_manager_client_(new FakeSessionManagerClient) {\n fake_dbus_thread_manager_->SetFakeClients();\n fake_dbus_thread_manager_->SetSessionManagerClient(\n scoped_ptr<SessionManagerClient>(fake_session_manager_client_));\n }\n\n scoped_ptr<policy::UserPolicyBuilder> GetUserPolicyBuilder(\n const std::string& user_id) {\n scoped_ptr<policy::UserPolicyBuilder>\n user_policy_builder(new policy::UserPolicyBuilder());\n base::FilePath user_keys_dir;\n EXPECT_TRUE(PathService::Get(DIR_USER_POLICY_KEYS, &user_keys_dir));\n const std::string sanitized_user_id =\n CryptohomeClient::GetStubSanitizedUsername(user_id);\n const base::FilePath user_key_file =\n user_keys_dir.AppendASCII(sanitized_user_id)\n .AppendASCII(\"policy.pub\");\n std::vector<uint8> user_key_bits;\n EXPECT_TRUE(user_policy_builder->GetSigningKey()->\n ExportPublicKey(&user_key_bits));\n EXPECT_TRUE(base::CreateDirectory(user_key_file.DirName()));\n EXPECT_EQ(base::WriteFile(\n user_key_file,\n reinterpret_cast<const char*>(user_key_bits.data()),\n user_key_bits.size()),\n static_cast<int>(user_key_bits.size()));\n user_policy_builder->policy_data().set_username(user_id);\n return user_policy_builder.Pass();\n }\n\n \/\/ LoginManagerTest:\n virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {\n DBusThreadManager::SetInstanceForTesting(fake_dbus_thread_manager_);\n LoginManagerTest::SetUpInProcessBrowserTestFixture();\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n \/\/ Set the same switches as LoginManagerTest, except that kMultiProfiles is\n \/\/ only set when GetParam() is true and except that kLoginProfile is set\n \/\/ when GetParam() is false. The latter seems to be required for the sane\n \/\/ start-up of user profiles.\n command_line->AppendSwitch(switches::kLoginManager);\n command_line->AppendSwitch(switches::kForceLoginManagerInTests);\n if (GetParam())\n command_line->AppendSwitch(::switches::kMultiProfiles);\n else\n command_line->AppendSwitchASCII(switches::kLoginProfile, kTestUsers[0]);\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n LoginManagerTest::SetUpOnMainThread();\n ash::Shell::GetInstance()->\n desktop_background_controller()->AddObserver(this);\n\n \/\/ Set up policy signing.\n user_policy_builders_[0] = GetUserPolicyBuilder(kTestUsers[0]);\n user_policy_builders_[1] = GetUserPolicyBuilder(kTestUsers[1]);\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n }\n\n virtual void TearDownOnMainThread() OVERRIDE {\n ash::Shell::GetInstance()->\n desktop_background_controller()->RemoveObserver(this);\n LoginManagerTest::TearDownOnMainThread();\n }\n\n \/\/ ash::DesktopBackgroundControllerObserver:\n virtual void OnWallpaperDataChanged() OVERRIDE {\n ++wallpaper_change_count_;\n if (run_loop_)\n run_loop_->Quit();\n }\n\n void StartLoop() {\n run_loop_.reset(new base::RunLoop);\n run_loop_->Run();\n }\n\n std::string ConstructPolicy(const std::string& relative_path) const {\n std::string image_data;\n if (!base::ReadFileToString(test_data_dir_.Append(relative_path),\n &image_data)) {\n ADD_FAILURE();\n }\n std::string policy;\n base::JSONWriter::Write(policy::test::ConstructExternalDataReference(\n embedded_test_server()->GetURL(std::string(\"\/\") + relative_path).spec(),\n image_data).get(),\n &policy);\n return policy;\n }\n\n \/\/ Inject |filename| as wallpaper policy for test user |user_number|. Set\n \/\/ empty |filename| to clear policy.\n void InjectPolicy(int user_number, const std::string& filename) {\n ASSERT_TRUE(user_number == 0 || user_number == 1);\n const std::string user_id = kTestUsers[user_number];\n policy::UserPolicyBuilder* builder =\n user_policy_builders_[user_number].get();\n if (filename != \"\") {\n builder->payload().\n mutable_wallpaperimage()->set_value(ConstructPolicy(filename));\n } else {\n builder->payload().Clear();\n }\n builder->Build();\n fake_session_manager_client_->set_user_policy(user_id, builder->GetBlob());\n const User* user = UserManager::Get()->FindUser(user_id);\n ASSERT_TRUE(user);\n policy::CloudPolicyStore* store = GetStoreForUser(user);\n ASSERT_TRUE(store);\n store->Load();\n ASSERT_EQ(policy::CloudPolicyStore::STATUS_OK, store->status());\n ASSERT_EQ(policy::CloudPolicyValidatorBase::VALIDATION_OK,\n store->validation_status());\n }\n\n \/\/ Obtain WallpaperInfo for |user_number| from WallpaperManager.\n void GetUserWallpaperInfo(int user_number, WallpaperInfo* wallpaper_info) {\n WallpaperManager::Get()->\n GetUserWallpaperInfo(kTestUsers[user_number], wallpaper_info);\n }\n\n base::FilePath test_data_dir_;\n scoped_ptr<base::RunLoop> run_loop_;\n int wallpaper_change_count_;\n scoped_ptr<policy::UserPolicyBuilder> user_policy_builders_[2];\n FakeDBusThreadManager* fake_dbus_thread_manager_;\n FakeSessionManagerClient* fake_session_manager_client_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WallpaperManagerPolicyTest);\n};\n\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_SetResetClear) {\n RegisterUser(kTestUsers[0]);\n RegisterUser(kTestUsers[1]);\n StartupUtils::MarkOobeCompleted();\n}\n\n\/\/ Verifies that the wallpaper can be set and re-set through policy and that\n\/\/ setting policy for a user that is not logged in doesn't affect the current\n\/\/ user. Also verifies that after the policy has been cleared, the wallpaper\n\/\/ reverts to default.\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, SetResetClear) {\n WallpaperInfo info;\n LoginUser(kTestUsers[0]);\n base::RunLoop().RunUntilIdle();\n\n \/\/ First user: Wait until default wallpaper has been loaded (happens\n \/\/ automatically) and store color to recognize it later.\n if (wallpaper_change_count_ == 0) {\n LOG(INFO) << \"No wallpaper change observed, yet. Starting loop.\";\n StartLoop();\n } else {\n LOG(INFO) << \"Wallpaper changed already \" << wallpaper_change_count_\n << \" time(s). Not starting loop.\";\n }\n const SkColor original_background_color = GetAverageBackgroundColor();\n\n \/\/ Second user: Set wallpaper policy to blue image. This should not result in\n \/\/ a wallpaper change, which is checked at the very end of this test.\n InjectPolicy(1, kBlueImageFileName);\n\n \/\/ First user: Set wallpaper policy to red image and verify average color.\n InjectPolicy(0, kRedImageFileName);\n StartLoop();\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::POLICY, info.type);\n ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());\n\n \/\/ First user: Set wallpaper policy to green image and verify average color.\n InjectPolicy(0, kGreenImageFileName);\n StartLoop();\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::POLICY, info.type);\n ASSERT_EQ(kGreenImageColor, GetAverageBackgroundColor());\n\n \/\/ First user: Clear wallpaper policy and verify that the default wallpaper is\n \/\/ set again.\n InjectPolicy(0, \"\");\n StartLoop();\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::DEFAULT, info.type);\n ASSERT_EQ(original_background_color, GetAverageBackgroundColor());\n\n \/\/ Check wallpaper change count to ensure that setting the second user's\n \/\/ wallpaper didn't have any effect.\n ASSERT_EQ(4, wallpaper_change_count_);\n}\n\nINSTANTIATE_TEST_CASE_P(WallpaperManagerPolicyTestInstantiation,\n WallpaperManagerPolicyTest, testing::Bool());\n\n} \/\/ namespace chromeos\n<commit_msg>Add wallpaper policy browsertest for login screen.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n#include <vector>\n\n#include \"ash\/desktop_background\/desktop_background_controller.h\"\n#include \"ash\/desktop_background\/desktop_background_controller_observer.h\"\n#include \"ash\/shell.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_manager_test.h\"\n#include \"chrome\/browser\/chromeos\/login\/startup_utils.h\"\n#include \"chrome\/browser\/chromeos\/login\/user.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/chromeos\/login\/wallpaper_manager.h\"\n#include \"chrome\/browser\/chromeos\/policy\/cloud_external_data_manager_base_test_util.h\"\n#include \"chrome\/browser\/chromeos\/policy\/user_cloud_policy_manager_chromeos.h\"\n#include \"chrome\/browser\/chromeos\/policy\/user_cloud_policy_manager_factory_chromeos.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chromeos\/chromeos_paths.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"chromeos\/dbus\/cryptohome_client.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/fake_dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/fake_session_manager_client.h\"\n#include \"chromeos\/dbus\/session_manager_client.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_core.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_store.h\"\n#include \"components\/policy\/core\/common\/cloud\/cloud_policy_validator.h\"\n#include \"components\/policy\/core\/common\/cloud\/policy_builder.h\"\n#include \"crypto\/rsa_private_key.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n#include \"policy\/proto\/cloud_policy.pb.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/skia\/include\/core\/SkColor.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"url\/gurl.h\"\n\nnamespace chromeos {\n\nnamespace {\n\nconst char kTestUsers[2][19] = { \"test-0@example.com\", \"test-1@example.com\" };\n\nconst char kRedImageFileName[] = \"chromeos\/wallpapers\/red.jpg\";\nconst char kGreenImageFileName[] = \"chromeos\/wallpapers\/green.jpg\";\nconst char kBlueImageFileName[] = \"chromeos\/wallpapers\/blue.jpg\";\n\nconst SkColor kRedImageColor = SkColorSetARGB(255, 199, 6, 7);\nconst SkColor kGreenImageColor = SkColorSetARGB(255, 38, 196, 15);\n\npolicy::CloudPolicyStore* GetStoreForUser(const User* user) {\n Profile* profile = UserManager::Get()->GetProfileByUser(user);\n if (!profile) {\n ADD_FAILURE();\n return NULL;\n }\n policy::UserCloudPolicyManagerChromeOS* policy_manager =\n policy::UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile);\n if (!policy_manager) {\n ADD_FAILURE();\n return NULL;\n }\n return policy_manager->core()->store();\n}\n\n\/\/ Compute the average ARGB color of |bitmap|.\nSkColor ComputeAverageColor(const SkBitmap& bitmap) {\n if (bitmap.empty() || bitmap.width() < 1 || bitmap.height() < 1) {\n ADD_FAILURE() << \"Empty or invalid bitmap.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n if (bitmap.isNull()) {\n ADD_FAILURE() << \"Bitmap has no pixelref.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n if (bitmap.config() == SkBitmap::kNo_Config) {\n ADD_FAILURE() << \"Bitmap has not been configured.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n uint64 a = 0, r = 0, g = 0, b = 0;\n bitmap.lockPixels();\n for (int x = 0; x < bitmap.width(); ++x) {\n for (int y = 0; y < bitmap.height(); ++y) {\n const SkColor color = bitmap.getColor(x, y);\n a += SkColorGetA(color);\n r += SkColorGetR(color);\n g += SkColorGetG(color);\n b += SkColorGetB(color);\n }\n }\n bitmap.unlockPixels();\n uint64 pixel_number = bitmap.width() * bitmap.height();\n return SkColorSetARGB((a + pixel_number \/ 2) \/ pixel_number,\n (r + pixel_number \/ 2) \/ pixel_number,\n (g + pixel_number \/ 2) \/ pixel_number,\n (b + pixel_number \/ 2) \/ pixel_number);\n}\n\n\/\/ Obtain background image and return its average ARGB color.\nSkColor GetAverageBackgroundColor() {\n const gfx::ImageSkia image =\n ash::Shell::GetInstance()->desktop_background_controller()->\n GetWallpaper();\n\n const gfx::ImageSkiaRep& representation = image.GetRepresentation(1.);\n if (representation.is_null()) {\n ADD_FAILURE() << \"No image representation.\";\n return SkColorSetARGB(0, 0, 0, 0);\n }\n\n const SkBitmap& bitmap = representation.sk_bitmap();\n return ComputeAverageColor(bitmap);\n}\n\n} \/\/ namespace\n\nclass WallpaperManagerPolicyTest\n : public LoginManagerTest,\n public ash::DesktopBackgroundControllerObserver,\n public testing::WithParamInterface<bool> {\n protected:\n WallpaperManagerPolicyTest()\n : LoginManagerTest(true),\n wallpaper_change_count_(0),\n fake_dbus_thread_manager_(new FakeDBusThreadManager),\n fake_session_manager_client_(new FakeSessionManagerClient) {\n fake_dbus_thread_manager_->SetFakeClients();\n fake_dbus_thread_manager_->SetSessionManagerClient(\n scoped_ptr<SessionManagerClient>(fake_session_manager_client_));\n }\n\n scoped_ptr<policy::UserPolicyBuilder> GetUserPolicyBuilder(\n const std::string& user_id) {\n scoped_ptr<policy::UserPolicyBuilder>\n user_policy_builder(new policy::UserPolicyBuilder());\n base::FilePath user_keys_dir;\n EXPECT_TRUE(PathService::Get(DIR_USER_POLICY_KEYS, &user_keys_dir));\n const std::string sanitized_user_id =\n CryptohomeClient::GetStubSanitizedUsername(user_id);\n const base::FilePath user_key_file =\n user_keys_dir.AppendASCII(sanitized_user_id)\n .AppendASCII(\"policy.pub\");\n std::vector<uint8> user_key_bits;\n EXPECT_TRUE(user_policy_builder->GetSigningKey()->\n ExportPublicKey(&user_key_bits));\n EXPECT_TRUE(base::CreateDirectory(user_key_file.DirName()));\n EXPECT_EQ(base::WriteFile(\n user_key_file,\n reinterpret_cast<const char*>(user_key_bits.data()),\n user_key_bits.size()),\n static_cast<int>(user_key_bits.size()));\n user_policy_builder->policy_data().set_username(user_id);\n return user_policy_builder.Pass();\n }\n\n \/\/ LoginManagerTest:\n virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {\n DBusThreadManager::SetInstanceForTesting(fake_dbus_thread_manager_);\n LoginManagerTest::SetUpInProcessBrowserTestFixture();\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n \/\/ Set the same switches as LoginManagerTest, except that kMultiProfiles is\n \/\/ only set when GetParam() is true and except that kLoginProfile is set\n \/\/ when GetParam() is false. The latter seems to be required for the sane\n \/\/ start-up of user profiles.\n command_line->AppendSwitch(switches::kLoginManager);\n command_line->AppendSwitch(switches::kForceLoginManagerInTests);\n if (GetParam())\n command_line->AppendSwitch(::switches::kMultiProfiles);\n else\n command_line->AppendSwitchASCII(switches::kLoginProfile, kTestUsers[0]);\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n LoginManagerTest::SetUpOnMainThread();\n ash::Shell::GetInstance()->\n desktop_background_controller()->AddObserver(this);\n\n \/\/ Set up policy signing.\n user_policy_builders_[0] = GetUserPolicyBuilder(kTestUsers[0]);\n user_policy_builders_[1] = GetUserPolicyBuilder(kTestUsers[1]);\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n }\n\n virtual void TearDownOnMainThread() OVERRIDE {\n ash::Shell::GetInstance()->\n desktop_background_controller()->RemoveObserver(this);\n LoginManagerTest::TearDownOnMainThread();\n }\n\n \/\/ ash::DesktopBackgroundControllerObserver:\n virtual void OnWallpaperDataChanged() OVERRIDE {\n ++wallpaper_change_count_;\n if (run_loop_)\n run_loop_->Quit();\n }\n\n \/\/ Runs the loop until wallpaper has changed at least |count| times in total.\n void RunUntilWallpaperChangeCount(int count) {\n while (wallpaper_change_count_ < count) {\n run_loop_.reset(new base::RunLoop);\n run_loop_->Run();\n }\n }\n\n std::string ConstructPolicy(const std::string& relative_path) const {\n std::string image_data;\n if (!base::ReadFileToString(test_data_dir_.Append(relative_path),\n &image_data)) {\n ADD_FAILURE();\n }\n std::string policy;\n base::JSONWriter::Write(policy::test::ConstructExternalDataReference(\n embedded_test_server()->GetURL(std::string(\"\/\") + relative_path).spec(),\n image_data).get(),\n &policy);\n return policy;\n }\n\n \/\/ Inject |filename| as wallpaper policy for test user |user_number|. Set\n \/\/ empty |filename| to clear policy.\n void InjectPolicy(int user_number, const std::string& filename) {\n ASSERT_TRUE(user_number == 0 || user_number == 1);\n const std::string user_id = kTestUsers[user_number];\n policy::UserPolicyBuilder* builder =\n user_policy_builders_[user_number].get();\n if (filename != \"\") {\n builder->payload().\n mutable_wallpaperimage()->set_value(ConstructPolicy(filename));\n } else {\n builder->payload().Clear();\n }\n builder->Build();\n fake_session_manager_client_->set_user_policy(user_id, builder->GetBlob());\n const User* user = UserManager::Get()->FindUser(user_id);\n ASSERT_TRUE(user);\n policy::CloudPolicyStore* store = GetStoreForUser(user);\n ASSERT_TRUE(store);\n store->Load();\n ASSERT_EQ(policy::CloudPolicyStore::STATUS_OK, store->status());\n ASSERT_EQ(policy::CloudPolicyValidatorBase::VALIDATION_OK,\n store->validation_status());\n }\n\n \/\/ Obtain WallpaperInfo for |user_number| from WallpaperManager.\n void GetUserWallpaperInfo(int user_number, WallpaperInfo* wallpaper_info) {\n WallpaperManager::Get()->\n GetUserWallpaperInfo(kTestUsers[user_number], wallpaper_info);\n }\n\n base::FilePath test_data_dir_;\n scoped_ptr<base::RunLoop> run_loop_;\n int wallpaper_change_count_;\n scoped_ptr<policy::UserPolicyBuilder> user_policy_builders_[2];\n FakeDBusThreadManager* fake_dbus_thread_manager_;\n FakeSessionManagerClient* fake_session_manager_client_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WallpaperManagerPolicyTest);\n};\n\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_SetResetClear) {\n RegisterUser(kTestUsers[0]);\n RegisterUser(kTestUsers[1]);\n StartupUtils::MarkOobeCompleted();\n}\n\n\/\/ Verifies that the wallpaper can be set and re-set through policy and that\n\/\/ setting policy for a user that is not logged in doesn't affect the current\n\/\/ user. Also verifies that after the policy has been cleared, the wallpaper\n\/\/ reverts to default.\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, SetResetClear) {\n WallpaperInfo info;\n LoginUser(kTestUsers[0]);\n base::RunLoop().RunUntilIdle();\n\n \/\/ First user: Wait until default wallpaper has been loaded (happens\n \/\/ automatically) and store color to recognize it later.\n RunUntilWallpaperChangeCount(1);\n const SkColor original_background_color = GetAverageBackgroundColor();\n\n \/\/ Second user: Set wallpaper policy to blue image. This should not result in\n \/\/ a wallpaper change, which is checked at the very end of this test.\n InjectPolicy(1, kBlueImageFileName);\n\n \/\/ First user: Set wallpaper policy to red image and verify average color.\n InjectPolicy(0, kRedImageFileName);\n RunUntilWallpaperChangeCount(2);\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::POLICY, info.type);\n ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());\n\n \/\/ First user: Set wallpaper policy to green image and verify average color.\n InjectPolicy(0, kGreenImageFileName);\n RunUntilWallpaperChangeCount(3);\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::POLICY, info.type);\n ASSERT_EQ(kGreenImageColor, GetAverageBackgroundColor());\n\n \/\/ First user: Clear wallpaper policy and verify that the default wallpaper is\n \/\/ set again.\n InjectPolicy(0, \"\");\n RunUntilWallpaperChangeCount(4);\n GetUserWallpaperInfo(0, &info);\n ASSERT_EQ(User::DEFAULT, info.type);\n ASSERT_EQ(original_background_color, GetAverageBackgroundColor());\n\n \/\/ Check wallpaper change count to ensure that setting the second user's\n \/\/ wallpaper didn't have any effect.\n ASSERT_EQ(4, wallpaper_change_count_);\n}\n\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest,\n PRE_PRE_WallpaperOnLoginScreen) {\n RegisterUser(kTestUsers[0]);\n StartupUtils::MarkOobeCompleted();\n}\n\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_WallpaperOnLoginScreen) {\n LoginUser(kTestUsers[0]);\n\n \/\/ Wait until default wallpaper has been loaded.\n RunUntilWallpaperChangeCount(1);\n\n \/\/ Set wallpaper policy to red image.\n InjectPolicy(0, kRedImageFileName);\n\n \/\/ Run until wallpaper has changed.\n RunUntilWallpaperChangeCount(2);\n}\n\nIN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, WallpaperOnLoginScreen) {\n \/\/ Wait for active pod's wallpaper to be loaded.\n RunUntilWallpaperChangeCount(1);\n ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());\n}\n\nINSTANTIATE_TEST_CASE_P(WallpaperManagerPolicyTestInstantiation,\n WallpaperManagerPolicyTest, testing::Bool());\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2016. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"CameraServer.h\"\n#include \"WPIErrors.h\"\n#include \"Utility.h\"\n\n#include <iostream>\n#include <chrono>\n#include <cstring>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netdb.h>\n\nconstexpr uint8_t CameraServer::kMagicNumber[];\n\nCameraServer* CameraServer::GetInstance() {\n static CameraServer instance;\n return &instance;\n}\n\nCameraServer::CameraServer()\n : m_camera(),\n m_serverThread(&CameraServer::Serve, this),\n m_captureThread(),\n m_imageMutex(),\n m_newImageVariable(),\n m_dataPool(3),\n m_quality(50),\n m_autoCaptureStarted(false),\n m_hwClient(true),\n m_imageData(nullptr, 0, 0, false) {\n for (int i = 0; i < 3; i++) m_dataPool.push_back(new uint8_t[kMaxImageSize]);\n}\n\nvoid CameraServer::FreeImageData(\n std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData) {\n if (std::get<3>(imageData))\n imaqDispose(std::get<0>(imageData));\n else if (std::get<0>(imageData) != nullptr) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n m_dataPool.push_back(std::get<0>(imageData));\n }\n}\n\nvoid CameraServer::SetImageData(uint8_t* data, unsigned int size,\n unsigned int start, bool imaqData) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n FreeImageData(m_imageData);\n m_imageData = std::make_tuple(data, size, start, imaqData);\n m_newImageVariable.notify_all();\n}\n\nvoid CameraServer::SetImage(Image const* image) {\n unsigned int dataSize = 0;\n uint8_t* data =\n (uint8_t*)imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG,\n 10 * m_quality, &dataSize);\n\n \/\/ If we're using a HW camera, then find the start of the data\n bool hwClient;\n {\n \/\/ Make a local copy of the hwClient variable so that we can safely use it.\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n hwClient = m_hwClient;\n }\n unsigned int start = 0;\n if (hwClient) {\n while (start < dataSize - 1) {\n if (data[start] == 0xFF && data[start + 1] == 0xD8)\n break;\n else\n start++;\n }\n }\n dataSize -= start;\n\n wpi_assert(dataSize > 2);\n SetImageData(data, dataSize, start, true);\n}\n\nvoid CameraServer::AutoCapture() {\n Image* frame = imaqCreateImage(IMAQ_IMAGE_RGB, 0);\n\n while (true) {\n bool hwClient;\n uint8_t* data = nullptr;\n {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n hwClient = m_hwClient;\n if (hwClient) {\n data = m_dataPool.back();\n m_dataPool.pop_back();\n }\n }\n\n if (hwClient) {\n unsigned int size = m_camera->GetImageData(data, kMaxImageSize);\n SetImageData(data, size);\n } else {\n m_camera->GetImage(frame);\n SetImage(frame);\n }\n }\n}\n\nvoid CameraServer::StartAutomaticCapture(char const* cameraName) {\n std::shared_ptr<USBCamera> camera =\n std::make_shared<USBCamera>(cameraName, true);\n camera->OpenCamera();\n StartAutomaticCapture(camera);\n}\n\nvoid CameraServer::StartAutomaticCapture(std::shared_ptr<USBCamera> camera) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n if (m_autoCaptureStarted) return;\n\n m_camera = camera;\n m_camera->StartCapture();\n\n m_captureThread = std::thread(&CameraServer::AutoCapture, this);\n m_captureThread.detach();\n m_autoCaptureStarted = true;\n}\n\nbool CameraServer::IsAutoCaptureStarted() {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n return m_autoCaptureStarted;\n}\n\nvoid CameraServer::SetSize(unsigned int size) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n if (!m_camera) return;\n if (size == kSize160x120)\n m_camera->SetSize(160, 120);\n else if (size == kSize320x240)\n m_camera->SetSize(320, 240);\n else if (size == kSize640x480)\n m_camera->SetSize(640, 480);\n}\n\nvoid CameraServer::SetQuality(unsigned int quality) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n m_quality = quality > 100 ? 100 : quality;\n}\n\nunsigned int CameraServer::GetQuality() {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n return m_quality;\n}\n\nvoid CameraServer::Serve() {\n int sock = socket(AF_INET, SOCK_STREAM, 0);\n\n if (sock == -1) {\n wpi_setErrnoError();\n return;\n }\n\n int reuseAddr = 1;\n if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr,\n sizeof(reuseAddr)) == -1)\n wpi_setErrnoError();\n\n sockaddr_in address, clientAddress;\n\n memset(&address, 0, sizeof(address));\n address.sin_family = AF_INET;\n address.sin_addr.s_addr = htonl(INADDR_ANY);\n address.sin_port = htons(kPort);\n\n if (bind(sock, (struct sockaddr*)&address, sizeof(address)) == -1)\n wpi_setErrnoError();\n\n if (listen(sock, 10) == -1) wpi_setErrnoError();\n\n while (true) {\n socklen_t clientAddressLen = sizeof(clientAddress);\n\n int conn =\n accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen);\n if (conn == -1) {\n wpi_setErrnoError();\n continue;\n }\n\n Request req;\n if (read(conn, &req, sizeof(req)) == -1) {\n wpi_setErrnoError();\n close(conn);\n continue;\n } else {\n req.fps = ntohl(req.fps);\n req.compression = ntohl(req.compression);\n req.size = ntohl(req.size);\n }\n\n \/\/ TODO: Support the SW Compression. The rest of the code below will work as\n \/\/ though this\n \/\/ check isn't here\n if (req.compression != kHardwareCompression) {\n wpi_setWPIErrorWithContext(IncompatibleState,\n \"Choose \\\"USB Camera HW\\\" on the dashboard\");\n close(conn);\n continue;\n }\n\n {\n \/\/ Wait for the camera to be setw\n std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);\n if (!m_camera) {\n std::cout << \"Camera not yet ready, awaiting first image\" << std::endl;\n m_newImageVariable.wait(lock);\n }\n m_hwClient = req.compression == kHardwareCompression;\n if (!m_hwClient)\n SetQuality(100 - req.compression);\n else if (m_camera)\n m_camera->SetFPS(req.fps);\n SetSize(req.size);\n }\n\n auto period = std::chrono::microseconds(1000000) \/ req.fps;\n while (true) {\n auto startTime = std::chrono::steady_clock::now();\n std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData;\n {\n std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);\n m_newImageVariable.wait(lock);\n imageData = m_imageData;\n m_imageData = std::make_tuple<uint8_t*>(nullptr, 0, 0, false);\n }\n\n unsigned int size = std::get<1>(imageData);\n unsigned int netSize = htonl(size);\n unsigned int start = std::get<2>(imageData);\n uint8_t* data = std::get<0>(imageData);\n\n if (data == nullptr) continue;\n\n if (write(conn, kMagicNumber, sizeof(kMagicNumber)) == -1) {\n wpi_setErrnoErrorWithContext(\n \"[CameraServer] Error sending magic number\");\n FreeImageData(imageData);\n break;\n }\n if (write(conn, &netSize, sizeof(netSize)) == -1) {\n wpi_setErrnoErrorWithContext(\"[CameraServer] Error sending image size\");\n FreeImageData(imageData);\n break;\n }\n if (write(conn, &data[start], sizeof(uint8_t) * size) == -1) {\n wpi_setErrnoErrorWithContext(\"[CameraServer] Error sending image data\");\n FreeImageData(imageData);\n break;\n }\n FreeImageData(imageData);\n std::this_thread::sleep_until(startTime + period);\n }\n close(conn);\n }\n close(sock);\n}\n<commit_msg>Fix C++ CameraServer request handling.<commit_after>\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2016. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"CameraServer.h\"\n#include \"WPIErrors.h\"\n#include \"Utility.h\"\n\n#include <iostream>\n#include <chrono>\n#include <cstring>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netdb.h>\n\nconstexpr uint8_t CameraServer::kMagicNumber[];\n\nCameraServer* CameraServer::GetInstance() {\n static CameraServer instance;\n return &instance;\n}\n\nCameraServer::CameraServer()\n : m_camera(),\n m_serverThread(&CameraServer::Serve, this),\n m_captureThread(),\n m_imageMutex(),\n m_newImageVariable(),\n m_dataPool(3),\n m_quality(50),\n m_autoCaptureStarted(false),\n m_hwClient(true),\n m_imageData(nullptr, 0, 0, false) {\n for (int i = 0; i < 3; i++) m_dataPool.push_back(new uint8_t[kMaxImageSize]);\n}\n\nvoid CameraServer::FreeImageData(\n std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData) {\n if (std::get<3>(imageData))\n imaqDispose(std::get<0>(imageData));\n else if (std::get<0>(imageData) != nullptr) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n m_dataPool.push_back(std::get<0>(imageData));\n }\n}\n\nvoid CameraServer::SetImageData(uint8_t* data, unsigned int size,\n unsigned int start, bool imaqData) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n FreeImageData(m_imageData);\n m_imageData = std::make_tuple(data, size, start, imaqData);\n m_newImageVariable.notify_all();\n}\n\nvoid CameraServer::SetImage(Image const* image) {\n unsigned int dataSize = 0;\n uint8_t* data =\n (uint8_t*)imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG,\n 10 * m_quality, &dataSize);\n\n \/\/ If we're using a HW camera, then find the start of the data\n bool hwClient;\n {\n \/\/ Make a local copy of the hwClient variable so that we can safely use it.\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n hwClient = m_hwClient;\n }\n unsigned int start = 0;\n if (hwClient) {\n while (start < dataSize - 1) {\n if (data[start] == 0xFF && data[start + 1] == 0xD8)\n break;\n else\n start++;\n }\n }\n dataSize -= start;\n\n wpi_assert(dataSize > 2);\n SetImageData(data, dataSize, start, true);\n}\n\nvoid CameraServer::AutoCapture() {\n Image* frame = imaqCreateImage(IMAQ_IMAGE_RGB, 0);\n\n while (true) {\n bool hwClient;\n uint8_t* data = nullptr;\n {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n hwClient = m_hwClient;\n if (hwClient) {\n data = m_dataPool.back();\n m_dataPool.pop_back();\n }\n }\n\n if (hwClient) {\n unsigned int size = m_camera->GetImageData(data, kMaxImageSize);\n SetImageData(data, size);\n } else {\n m_camera->GetImage(frame);\n SetImage(frame);\n }\n }\n}\n\nvoid CameraServer::StartAutomaticCapture(char const* cameraName) {\n std::shared_ptr<USBCamera> camera =\n std::make_shared<USBCamera>(cameraName, true);\n camera->OpenCamera();\n StartAutomaticCapture(camera);\n}\n\nvoid CameraServer::StartAutomaticCapture(std::shared_ptr<USBCamera> camera) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n if (m_autoCaptureStarted) return;\n\n m_camera = camera;\n m_camera->StartCapture();\n\n m_captureThread = std::thread(&CameraServer::AutoCapture, this);\n m_captureThread.detach();\n m_autoCaptureStarted = true;\n}\n\nbool CameraServer::IsAutoCaptureStarted() {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n return m_autoCaptureStarted;\n}\n\nvoid CameraServer::SetSize(unsigned int size) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n if (!m_camera) return;\n if (size == kSize160x120)\n m_camera->SetSize(160, 120);\n else if (size == kSize320x240)\n m_camera->SetSize(320, 240);\n else if (size == kSize640x480)\n m_camera->SetSize(640, 480);\n}\n\nvoid CameraServer::SetQuality(unsigned int quality) {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n m_quality = quality > 100 ? 100 : quality;\n}\n\nunsigned int CameraServer::GetQuality() {\n std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);\n return m_quality;\n}\n\nvoid CameraServer::Serve() {\n int sock = socket(AF_INET, SOCK_STREAM, 0);\n\n if (sock == -1) {\n wpi_setErrnoError();\n return;\n }\n\n int reuseAddr = 1;\n if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr,\n sizeof(reuseAddr)) == -1)\n wpi_setErrnoError();\n\n sockaddr_in address, clientAddress;\n\n memset(&address, 0, sizeof(address));\n address.sin_family = AF_INET;\n address.sin_addr.s_addr = htonl(INADDR_ANY);\n address.sin_port = htons(kPort);\n\n if (bind(sock, (struct sockaddr*)&address, sizeof(address)) == -1)\n wpi_setErrnoError();\n\n if (listen(sock, 10) == -1) wpi_setErrnoError();\n\n while (true) {\n socklen_t clientAddressLen = sizeof(clientAddress);\n\n int conn =\n accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen);\n if (conn == -1) {\n wpi_setErrnoError();\n continue;\n }\n\n Request req;\n char reqBuf[sizeof(req)];\n size_t reqPos = 0;\n\n while (reqPos < sizeof(req)) {\n ssize_t sizeRead = read(conn, &reqBuf[reqPos], sizeof(req) - reqPos);\n if (sizeRead < 0) break;\n reqPos += sizeRead;\n }\n\n if (reqPos < sizeof(req)) {\n wpi_setErrnoError();\n close(conn);\n continue;\n }\n\n memcpy(&req, reqBuf, sizeof(req));\n req.fps = ntohl(req.fps);\n req.compression = ntohl(req.compression);\n req.size = ntohl(req.size);\n\n \/\/ TODO: Support the SW Compression. The rest of the code below will work as\n \/\/ though this\n \/\/ check isn't here\n if (req.compression != kHardwareCompression) {\n wpi_setWPIErrorWithContext(IncompatibleState,\n \"Choose \\\"USB Camera HW\\\" on the dashboard\");\n close(conn);\n continue;\n }\n\n {\n \/\/ Wait for the camera to be setw\n std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);\n if (!m_camera) {\n std::cout << \"Camera not yet ready, awaiting first image\" << std::endl;\n m_newImageVariable.wait(lock);\n }\n m_hwClient = req.compression == kHardwareCompression;\n if (!m_hwClient)\n SetQuality(100 - req.compression);\n else if (m_camera)\n m_camera->SetFPS(req.fps);\n SetSize(req.size);\n }\n\n auto period = std::chrono::microseconds(1000000) \/ req.fps;\n while (true) {\n auto startTime = std::chrono::steady_clock::now();\n std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData;\n {\n std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);\n m_newImageVariable.wait(lock);\n imageData = m_imageData;\n m_imageData = std::make_tuple<uint8_t*>(nullptr, 0, 0, false);\n }\n\n unsigned int size = std::get<1>(imageData);\n unsigned int netSize = htonl(size);\n unsigned int start = std::get<2>(imageData);\n uint8_t* data = std::get<0>(imageData);\n\n if (data == nullptr) continue;\n\n if (write(conn, kMagicNumber, sizeof(kMagicNumber)) == -1) {\n wpi_setErrnoErrorWithContext(\n \"[CameraServer] Error sending magic number\");\n FreeImageData(imageData);\n break;\n }\n if (write(conn, &netSize, sizeof(netSize)) == -1) {\n wpi_setErrnoErrorWithContext(\"[CameraServer] Error sending image size\");\n FreeImageData(imageData);\n break;\n }\n if (write(conn, &data[start], sizeof(uint8_t) * size) == -1) {\n wpi_setErrnoErrorWithContext(\"[CameraServer] Error sending image data\");\n FreeImageData(imageData);\n break;\n }\n FreeImageData(imageData);\n std::this_thread::sleep_until(startTime + period);\n }\n close(conn);\n }\n close(sock);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#include <hdfs.h>\n#include \"THDFSFileTransport.h\"\n\nusing namespace std;\nusing std::shared_ptr;\n\nnamespace apache { namespace thrift { namespace transport {\n\nvoid THDFSFileTransport::open() {\n \/\/ THDFSFileTransport does not handle resource alloc\/release.\n \/\/ An open HDFSFile handle must exist by now\n if (!isOpen()) {\n throw TTransportException(TTransportException::NOT_OPEN,\n \"THDFSFileTransport::open()\");\n }\n}\n\nvoid THDFSFileTransport::close() {\n \/\/ THDFSFileTransport does not handle resource alloc\/release\n return;\n}\n\nuint32_t THDFSFileTransport::read(uint8_t* buf, uint32_t len) {\n tSize rv = hdfsRead(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);\n if (rv < 0) {\n int errno_copy = errno;\n throw TTransportException(TTransportException::UNKNOWN,\n \"THDFSFileTransport::read()\",\n errno_copy);\n } else if (rv == 0) {\n throw TTransportException(TTransportException::END_OF_FILE,\n \"THDFSFileTransport::read()\");\n }\n return rv;\n}\n\nvoid THDFSFileTransport::write(const uint8_t* buf, uint32_t len) {\n tSize rv = hdfsWrite(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);\n if (rv < 0) {\n int errno_copy = errno;\n throw TTransportException(TTransportException::UNKNOWN,\n \"THDFSFileTransport::write()\",\n errno_copy);\n } else if (rv != len) {\n throw TTransportException(TTransportException::INTERRUPTED,\n \"THDFSFileTransport::write()\");\n }\n}\n\n}}} \/\/ apache::thrift::transport\n<commit_msg>Fix header ordering lint failures<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#include \"THDFSFileTransport.h\"\n#include <hdfs.h>\n\nusing namespace std;\nusing std::shared_ptr;\n\nnamespace apache { namespace thrift { namespace transport {\n\nvoid THDFSFileTransport::open() {\n \/\/ THDFSFileTransport does not handle resource alloc\/release.\n \/\/ An open HDFSFile handle must exist by now\n if (!isOpen()) {\n throw TTransportException(TTransportException::NOT_OPEN,\n \"THDFSFileTransport::open()\");\n }\n}\n\nvoid THDFSFileTransport::close() {\n \/\/ THDFSFileTransport does not handle resource alloc\/release\n return;\n}\n\nuint32_t THDFSFileTransport::read(uint8_t* buf, uint32_t len) {\n tSize rv = hdfsRead(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);\n if (rv < 0) {\n int errno_copy = errno;\n throw TTransportException(TTransportException::UNKNOWN,\n \"THDFSFileTransport::read()\",\n errno_copy);\n } else if (rv == 0) {\n throw TTransportException(TTransportException::END_OF_FILE,\n \"THDFSFileTransport::read()\");\n }\n return rv;\n}\n\nvoid THDFSFileTransport::write(const uint8_t* buf, uint32_t len) {\n tSize rv = hdfsWrite(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);\n if (rv < 0) {\n int errno_copy = errno;\n throw TTransportException(TTransportException::UNKNOWN,\n \"THDFSFileTransport::write()\",\n errno_copy);\n } else if (rv != len) {\n throw TTransportException(TTransportException::INTERRUPTED,\n \"THDFSFileTransport::write()\");\n }\n}\n\n}}} \/\/ apache::thrift::transport\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const deUint32 knownDriverIds[] =\n{\n\t\/\/ Specified in the Vulkan registry (vk.xml)\n\t1,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD proprietary driver\"\n\t2,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD open-source driver\"\n\t3,\t\/\/ author = \"Mesa open source project\" comment = \"Mesa RADV driver\"\n\t4,\t\/\/ author = \"NVIDIA Corporation\" comment = \"NVIDIA proprietary driver\"\n\t5,\t\/\/ author = \"Intel Corporation\" comment = \"Intel proprietary Windows driver\"\n\t6,\t\/\/ author = \"Intel Corporation\" comment = \"Intel open-source Mesa driver\"\n\t7,\t\/\/ author = \"Imagination Technologies\" comment = \"Imagination proprietary driver\"\n\t8,\t\/\/ author = \"Qualcomm Technologies, Inc.\" comment = \"Qualcomm proprietary driver\"\n\t9,\t\/\/ author = \"Arm Limited\" comment = \"Arm proprietary driver\"\n\t10,\t\/\/ <enum value=\"10\" name=\"VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR\" comment=\"Google LLC\"\/>\n\t11,\t\/\/ <enum value=\"11\" name=\"VK_DRIVER_ID_GGP_PROPRIETARY_KHR\" comment=\"Google LLC\"\/>\n\t12,\t\/\/ <enum value=\"12\" name=\"VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR\" comment=\"Broadcom Inc.\"\/>\n};\n\nstatic const VkConformanceVersionKHR knownConformanceVersions[] =\n{\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n\tmakeConformanceVersion(1, 1, 2, 3),\n\tmakeConformanceVersion(1, 1, 2, 2),\n\tmakeConformanceVersion(1, 1, 2, 1),\n\tmakeConformanceVersion(1, 1, 2, 0),\n\tmakeConformanceVersion(1, 1, 1, 3),\n\tmakeConformanceVersion(1, 1, 1, 2),\n\tmakeConformanceVersion(1, 1, 1, 1),\n\tmakeConformanceVersion(1, 1, 1, 0),\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tfor (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)\n\t{\n\t\tif (deviceDriverProperties.driverID == *pDriverId)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<commit_msg>Whitelist Vulkan CTS 1.2.1.0<commit_after>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const deUint32 knownDriverIds[] =\n{\n\t\/\/ Specified in the Vulkan registry (vk.xml)\n\t1,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD proprietary driver\"\n\t2,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD open-source driver\"\n\t3,\t\/\/ author = \"Mesa open source project\" comment = \"Mesa RADV driver\"\n\t4,\t\/\/ author = \"NVIDIA Corporation\" comment = \"NVIDIA proprietary driver\"\n\t5,\t\/\/ author = \"Intel Corporation\" comment = \"Intel proprietary Windows driver\"\n\t6,\t\/\/ author = \"Intel Corporation\" comment = \"Intel open-source Mesa driver\"\n\t7,\t\/\/ author = \"Imagination Technologies\" comment = \"Imagination proprietary driver\"\n\t8,\t\/\/ author = \"Qualcomm Technologies, Inc.\" comment = \"Qualcomm proprietary driver\"\n\t9,\t\/\/ author = \"Arm Limited\" comment = \"Arm proprietary driver\"\n\t10,\t\/\/ <enum value=\"10\" name=\"VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR\" comment=\"Google LLC\"\/>\n\t11,\t\/\/ <enum value=\"11\" name=\"VK_DRIVER_ID_GGP_PROPRIETARY_KHR\" comment=\"Google LLC\"\/>\n\t12,\t\/\/ <enum value=\"12\" name=\"VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR\" comment=\"Broadcom Inc.\"\/>\n};\n\nstatic const VkConformanceVersionKHR knownConformanceVersions[] =\n{\n\tmakeConformanceVersion(1, 2, 1, 0),\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n\tmakeConformanceVersion(1, 1, 2, 3),\n\tmakeConformanceVersion(1, 1, 2, 2),\n\tmakeConformanceVersion(1, 1, 2, 1),\n\tmakeConformanceVersion(1, 1, 2, 0),\n\tmakeConformanceVersion(1, 1, 1, 3),\n\tmakeConformanceVersion(1, 1, 1, 2),\n\tmakeConformanceVersion(1, 1, 1, 1),\n\tmakeConformanceVersion(1, 1, 1, 0),\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tfor (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)\n\t{\n\t\tif (deviceDriverProperties.driverID == *pDriverId)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<|endoftext|>"} {"text":"<commit_before>#include \"gamestates\/introstate.hpp\"\n\n#include <SFML\/Window\/Event.hpp>\n#include <SFML\/Graphics\/Texture.hpp>\n#include <SFML\/Graphics\/Sprite.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n\n#include <iostream>\n\nnamespace qrw\n{\n\nIntroState::IntroState(sf::RenderWindow* renderWindow)\n\t: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)\n{\n}\n\nIntroState::~IntroState()\n{\n}\n\nvoid IntroState::init(GameState* previousState)\n{\n\t\/\/ Create render window\n\t_renderWindow->create(\n\t\tsf::VideoMode(640, 240),\n\t\t\"Quad-Ruled War - Loading...\",\n\t\tsf::Style::None\n\t);\n\n\t_advanceToNextState = false;\n\n\t_splashTexture = new sf::Texture();\n\t_splashTexture->loadFromFile(\".\/res\/img\/splash.png\");\n\t_splashSprite = new sf::Sprite();\n\t_splashSprite->setTexture(*_splashTexture);\n}\n\nEGameStateId IntroState::update()\n{\n\tif(_advanceToNextState)\n\t{\n\t\tdelete _splashTexture;\n\t\tdelete _splashSprite;\n\n\t\treturn EGameStateId::EGSID_MAIN_MENU_STATE;\n\t}\n\n\treturn EGameStateId::EGSID_NO_CHANGE;\n}\n\nvoid IntroState::draw()\n{\n\t_renderWindow->draw(*_splashSprite);\n}\n\nvoid IntroState::handleEvent(sf::Event& event)\n{\n\tstd::cout << \"Handle event\\n\";\n\n\tif(event.type == sf::Event::KeyPressed)\n\t\t_advanceToNextState = true;\n}\n\n} \/\/ namespace qrw\n<commit_msg>Intro state loads resources.<commit_after>#include \"gamestates\/introstate.hpp\"\n\n#include <SFML\/Window\/Event.hpp>\n#include <SFML\/Graphics\/Texture.hpp>\n#include <SFML\/Graphics\/Sprite.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n\n#include <iostream>\n\n#include \"config\/settings.hpp\"\n#include \"config\/tilesetprocessor.hpp\"\n#include \"gui\/imagemanager.hpp\"\n#include \"gui\/texturemanager.hpp\"\n\n\nnamespace qrw\n{\n\nIntroState::IntroState(sf::RenderWindow* renderWindow)\n\t: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)\n{\n}\n\nIntroState::~IntroState()\n{\n}\n\nvoid IntroState::init(GameState* previousState)\n{\n\t\/\/ Create render window\n\t_renderWindow->create(\n\t\tsf::VideoMode(640, 240),\n\t\t\"Quad-Ruled War - Loading...\",\n\t\tsf::Style::None\n\t);\n\n\t_advanceToNextState = false;\n\n\t_splashTexture = new sf::Texture();\n\t_splashTexture->loadFromFile(\".\/res\/img\/splash.png\");\n\t_splashSprite = new sf::Sprite();\n\t_splashSprite->setTexture(*_splashTexture);\n}\n\nEGameStateId IntroState::update()\n{\n\tif(_advanceToNextState)\n\t{\n\t\tdelete _splashTexture;\n\t\tdelete _splashSprite;\n\n\t\treturn EGameStateId::EGSID_MAIN_MENU_STATE;\n\t}\n\n\treturn EGameStateId::EGSID_NO_CHANGE;\n}\n\nvoid IntroState::draw()\n{\n\t_renderWindow->draw(*_splashSprite);\n\t_renderWindow->display();\n\n\t\/\/ Start initialization of qrw...\n\t\/\/ Load Settings\n\tqrw::Settings* settings = qrw::Settings::getInstance();\n\tsettings->loadFromFile();\n\n\t\/\/ Preload image resources\n\tqrw::ImageManager* imgmgr = qrw::ImageManager::getInstance();\n\timgmgr->loadImage(\"p1swordman\", \".\/res\/img\/units\/p1swordman.png\");\n\timgmgr->loadImage(\"p1archer\", \".\/res\/img\/units\/p1archer.png\");\n\timgmgr->loadImage(\"p1spearman\", \".\/res\/img\/units\/p1spearman.png\");\n\timgmgr->loadImage(\"p2swordman\", \".\/res\/img\/units\/p2swordman.png\");\n\timgmgr->loadImage(\"p2archer\", \".\/res\/img\/units\/p2archer.png\");\n\timgmgr->loadImage(\"p2spearman\", \".\/res\/img\/units\/p2spearman.png\");\n\timgmgr->loadImage(\"plainsquare\", \".\/res\/img\/plainsquare.png\");\n\n\tTextureManager::getInstance()->loadTexture(\"mainmenubackground\", \".\/res\/img\/mainmenubackground.png\");\n\n\t\/\/ Loading tilesets\n\tqrw::TilesetProcessor tilesetprocessor;\n\ttilesetprocessor.loadTileset(settings->getEntityTilesetPath());\n\ttilesetprocessor.loadTileset(settings->getGuiTilesetPath());\n}\n\nvoid IntroState::handleEvent(sf::Event& event)\n{\n\tstd::cout << \"Handle event\\n\";\n\n\tif(event.type == sf::Event::KeyPressed)\n\t\t_advanceToNextState = true;\n}\n\n} \/\/ namespace qrw\n<|endoftext|>"} {"text":"<commit_before>\/* dtkComposerNodeFile.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Thu Jul 8 13:28:18 2010 (+0200)\n * Version: $Id$\n * Last-Updated: Tue Aug 30 10:52:37 2011 (+0200)\n * By: Thibaud Kloczko\n * Update #: 94\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerNodeFile.h\"\n#include \"dtkComposerNodeProperty.h\"\n\n#include <dtkCore\/dtkGlobal.h>\n#include <dtkCore\/dtkLog.h>\n\n#include <dtkGui\/dtkTextEditor.h>\n\n#include <QtGui\/QFileDialog>\n\nclass dtkComposerNodeFilePrivate\n{\npublic:\n dtkComposerNodeProperty *property_output_file_name;\n dtkComposerNodeProperty *property_output_file_text;\n\npublic:\n QString file;\n};\n\ndtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)\n{\n d->property_output_file_name = new dtkComposerNodeProperty(\"name\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);\n d->property_output_file_text = new dtkComposerNodeProperty(\"text\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);\n\n this->setTitle(\"File\");\n this->setKind(dtkComposerNode::Atomic);\n this->setType(\"dtkComposerFile\");\n\n this->addOutputProperty(d->property_output_file_name);\n this->addOutputProperty(d->property_output_file_text);\n \n this->addAction(\"Choose file\", this, SLOT(getFileName()));\n this->addAction(\"Edit file\", this, SLOT(editFile()));\n\n d->file = QString();\n}\n\ndtkComposerNodeFile::~dtkComposerNodeFile(void)\n{\n delete d;\n\n d = NULL;\n}\n\nQVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)\n{\n if(property == d->property_output_file_name) {\n emit elapsed(\"00:00::000.001\");\n emit progressed(QString(\"File name: %1\").arg(d->file));\n emit progressed(100);\n return QVariant(d->file);\n }\n\n return QVariant();\n}\n\nvoid dtkComposerNodeFile::editFile(void)\n{\n dtkTextEditor *editor = new dtkTextEditor;\n editor->open(d->file);\n editor->show();\n\n connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));\n}\n\nvoid dtkComposerNodeFile::getFileName(void)\n{\n QFileDialog dialog(0, tr(\"Choose file\"));\n dialog.setFileMode(QFileDialog::ExistingFile);\n if (dialog.exec())\n d->file = dialog.selectedFiles().first(); \n\n \/\/d->file = QFileDialog::getOpenFileName(0, tr(\"Choose file\"));\n}\n\nvoid dtkComposerNodeFile::setFileName(const QString& file)\n{\n d->file = file;\n}\n\nvoid dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)\n{\n Q_UNUSED(edge);\n Q_UNUSED(property); \n}\n\nvoid dtkComposerNodeFile::run(void)\n{\n if (d->file.isEmpty())\n dtkDebug() << \"File has not been initialized.\";\n\n return;\n}\n\nvoid dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)\n{\n Q_UNUSED(edge);\n Q_UNUSED(property); \n}\n<commit_msg>Setting default stylesheet for node file when opening filedialog box.<commit_after>\/* dtkComposerNodeFile.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Thu Jul 8 13:28:18 2010 (+0200)\n * Version: $Id$\n * Last-Updated: Wed Sep 28 17:26:00 2011 (+0200)\n * By: Thibaud Kloczko\n * Update #: 97\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerNodeFile.h\"\n#include \"dtkComposerNodeProperty.h\"\n\n#include <dtkCore\/dtkGlobal.h>\n#include <dtkCore\/dtkLog.h>\n\n#include <dtkGui\/dtkTextEditor.h>\n\n#include <QtGui\/QFileDialog>\n\nclass dtkComposerNodeFilePrivate\n{\npublic:\n dtkComposerNodeProperty *property_output_file_name;\n dtkComposerNodeProperty *property_output_file_text;\n\npublic:\n QString file;\n};\n\ndtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)\n{\n d->property_output_file_name = new dtkComposerNodeProperty(\"name\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);\n d->property_output_file_text = new dtkComposerNodeProperty(\"text\", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);\n\n this->setTitle(\"File\");\n this->setKind(dtkComposerNode::Atomic);\n this->setType(\"dtkComposerFile\");\n\n this->addOutputProperty(d->property_output_file_name);\n this->addOutputProperty(d->property_output_file_text);\n \n this->addAction(\"Choose file\", this, SLOT(getFileName()));\n this->addAction(\"Edit file\", this, SLOT(editFile()));\n\n d->file = QString();\n}\n\ndtkComposerNodeFile::~dtkComposerNodeFile(void)\n{\n delete d;\n\n d = NULL;\n}\n\nQVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)\n{\n if(property == d->property_output_file_name) {\n emit elapsed(\"00:00::000.001\");\n emit progressed(QString(\"File name: %1\").arg(d->file));\n emit progressed(100);\n return QVariant(d->file);\n }\n\n return QVariant();\n}\n\nvoid dtkComposerNodeFile::editFile(void)\n{\n dtkTextEditor *editor = new dtkTextEditor;\n editor->open(d->file);\n editor->show();\n\n connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));\n}\n\nvoid dtkComposerNodeFile::getFileName(void)\n{\n QFileDialog dialog(0, tr(\"Choose file\"));\n dialog.setStyleSheet(\"background-color: none ; color: none;\");\n dialog.setFileMode(QFileDialog::ExistingFile);\n if (dialog.exec())\n d->file = dialog.selectedFiles().first(); \n\n \/\/ d->file = QFileDialog::getOpenFileName(0, tr(\"Choose file\"));\n}\n\nvoid dtkComposerNodeFile::setFileName(const QString& file)\n{\n d->file = file;\n}\n\nvoid dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)\n{\n Q_UNUSED(edge);\n Q_UNUSED(property); \n}\n\nvoid dtkComposerNodeFile::run(void)\n{\n if (d->file.isEmpty())\n dtkDebug() << \"File has not been initialized.\";\n\n return;\n}\n\nvoid dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)\n{\n Q_UNUSED(edge);\n Q_UNUSED(property); \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRectShaderImageFilter.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkDevice.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkShader.h\"\n\nSkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {\n SkASSERT(s);\n return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));\n}\n\nSkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)\n : INHERITED(NULL)\n , fShader(s)\n , fRect(rect) {\n SkASSERT(s);\n s->ref();\n}\n\nSkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n fShader = buffer.readFlattenableT<SkShader>();\n buffer.readRect(&fRect);\n}\n\nvoid SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.writeFlattenable(fShader);\n buffer.writeRect(fRect);\n}\n\nSkRectShaderImageFilter::~SkRectShaderImageFilter() {\n SkSafeUnref(fShader);\n}\n\nbool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,\n const SkBitmap& source,\n const SkMatrix& matrix,\n SkBitmap* result,\n SkIPoint* loc) {\n SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(fRect.width()),\n SkScalarCeilToInt(fRect.height())));\n SkCanvas canvas(device.get());\n SkPaint paint;\n paint.setShader(fShader);\n canvas.drawRect(fRect, paint);\n *result = device.get()->accessBitmap(false);\n return true;\n}\n<commit_msg>Adding a bit of rebustness to SkRectShaderImageFilter<commit_after>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRectShaderImageFilter.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkDevice.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkShader.h\"\n\nSkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {\n SkASSERT(s);\n return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));\n}\n\nSkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)\n : INHERITED(NULL)\n , fShader(s)\n , fRect(rect) {\n SkASSERT(s);\n s->ref();\n}\n\nSkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n fShader = buffer.readFlattenableT<SkShader>();\n buffer.readRect(&fRect);\n}\n\nvoid SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.writeFlattenable(fShader);\n buffer.writeRect(fRect);\n}\n\nSkRectShaderImageFilter::~SkRectShaderImageFilter() {\n SkSafeUnref(fShader);\n}\n\nbool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,\n const SkBitmap& source,\n const SkMatrix&,\n SkBitmap* result,\n SkIPoint*) {\n SkRect rect(fRect);\n if (rect.isEmpty()) {\n rect = SkRect::MakeWH(source.width(), source.height());\n }\n\n if (rect.isEmpty()) {\n return false;\n }\n\n SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(rect.width()),\n SkScalarCeilToInt(rect.height())));\n SkCanvas canvas(device.get());\n SkPaint paint;\n paint.setShader(fShader);\n canvas.drawRect(rect, paint);\n *result = device.get()->accessBitmap(false);\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: misc.hxx,v $\n * $Revision: 1.14 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_MISC_HXX_\n#define _LINGUISTIC_MISC_HXX_\n\n\n#include <com\/sun\/star\/uno\/Sequence.h>\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/linguistic2\/XDictionaryEntry.hpp>\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <svtools\/pathoptions.hxx>\n#include <i18npool\/lang.h>\n#include <tools\/string.hxx>\n#include <unotools\/charclass.hxx>\n#include <osl\/thread.h>\n#include <osl\/mutex.hxx>\n#include <vcl\/svapp.hxx>\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n class XFastPropertySet;\n}}}}\n\nnamespace com { namespace sun { namespace star { namespace frame {\n class XDesktop;\n}}}}\n\nclass LocaleDataWrapper;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define SN_SPELLCHECKER \"com.sun.star.linguistic2.SpellChecker\"\n#define SN_HYPHENATOR \"com.sun.star.linguistic2.Hyphenator\"\n#define SN_THESAURUS \"com.sun.star.linguistic2.Thesaurus\"\n#define SN_LINGU_SERVCICE_MANAGER \"com.sun.star.linguistic2.LinguServiceManager\"\n#define SN_LINGU_PROPERTIES \"com.sun.star.linguistic2.LinguProperties\"\n#define SN_DICTIONARY_LIST \"com.sun.star.linguistic2.DictionaryList\"\n#define SN_OTHER_LINGU \"com.sun.star.linguistic2.OtherLingu\"\n#define SN_DESKTOP \"com.sun.star.frame.Desktop\"\n\n\nnamespace linguistic\n{\n\n\/\/ ascii to OUString conversion\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n\/\/\/ Flags to be used with the multi-path related functions\n\/\/\/ @see GetDictionaryPaths, GetLinguisticPaths\n#define PATH_FLAG_INTERNAL 0x01\n#define PATH_FLAG_USER 0x02\n#define PATH_FLAG_WRITABLE 0x04\n#define PATH_FLAG_ALL (PATH_FLAG_INTERNAL | PATH_FLAG_USER | PATH_FLAG_WRITABLE)\n\n\n\/\/ AddEntryToDic return values\n#define DIC_ERR_NONE 0\n#define DIC_ERR_FULL 1\n#define DIC_ERR_READONLY 2\n#define DIC_ERR_UNKNOWN 3\n#define DIC_ERR_NOT_EXISTS 4\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::osl::Mutex & GetLinguMutex();\n\nLocaleDataWrapper & GetLocaleDataWrapper( INT16 nLang );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrtl_TextEncoding GetTextEncoding( INT16 nLanguage );\n\ninline ::rtl::OUString BS2OU(const ByteString &rText, rtl_TextEncoding nEnc)\n{\n return ::rtl::OUString( rText.GetBuffer(), rText.Len(), nEnc );\n}\n\ninline ByteString OU2BS(const ::rtl::OUString &rText, rtl_TextEncoding nEnc)\n{\n return ByteString( rText.getStr(), nEnc );\n}\n\nrtl::OUString StripTrailingChars( rtl::OUString &rTxt, sal_Unicode cChar );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsal_Int32 LevDistance( const rtl::OUString &rTxt1, const rtl::OUString &rTxt2 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::lang::Locale\n CreateLocale( LanguageType eLang );\n\nLanguageType\n LocaleToLanguage( const ::com::sun::star::lang::Locale& rLocale );\n\n::com::sun::star::lang::Locale&\n LanguageToLocale( ::com::sun::star::lang::Locale& rLocale, LanguageType eLang );\n\n::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale >\n LangSeqToLocaleSeq( const ::com::sun::star::uno::Sequence< INT16 > &rLangSeq );\n\n::com::sun::star::uno::Sequence< INT16 >\n LocaleSeqToLangSeq( ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > &rLocaleSeq );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ checks if file pointed to by rURL is readonly\n\/\/ and may also check return if such a file exists or not\nBOOL IsReadOnly( const String &rURL, BOOL *pbExist = 0 );\n\n\/\/ checks if a file with the given URL exists\nBOOL FileExists( const String &rURL );\n\n#ifdef TL_OUTDATED\n\/\/ returns complete file URL for given filename that is to be searched in\n\/\/ the specified path\nString GetFileURL( SvtPathOptions::Pathes ePath, const String &rFileName );\n\nString GetModulePath( SvtPathOptions::Pathes ePath, BOOL bAddAccessDelim = TRUE );\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::rtl::OUString GetDictionaryWriteablePath();\n::com::sun::star::uno::Sequence< ::rtl::OUString > GetDictionaryPaths( sal_Int16 nPathFlags = PATH_FLAG_ALL );\n::com::sun::star::uno::Sequence< ::rtl::OUString > GetLinguisticPaths( sal_Int16 nPathFlags = PATH_FLAG_ALL );\n\n\/\/\/ @returns an URL for a new and writable dictionary rDicName.\n\/\/\/ The URL will point to the path given by 'GetDictionaryWriteablePath'\nString GetWritableDictionaryURL( const String &rDicName );\n\n\/\/ looks for the specified file in the list of paths.\n\/\/ In case of multiple occurences only the first found is returned.\nString SearchFileInPaths( const String &rFile, const ::com::sun::star::uno::Sequence< ::rtl::OUString > &rPaths );\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nINT32 GetPosInWordToCheck( const rtl::OUString &rTxt, INT32 nPos );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord >\n RebuildHyphensAndControlChars( const rtl::OUString &rOrigWord,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord > &rxHyphWord );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUpper( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\nBOOL IsLower( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\n\ninline BOOL IsUpper( const String &rText, INT16 nLanguage ) { return IsUpper( rText, 0, rText.Len(), nLanguage ); }\ninline BOOL IsLower( const String &rText, INT16 nLanguage ) { return IsLower( rText, 0, rText.Len(), nLanguage ); }\n\nString ToLower( const String &rText, INT16 nLanguage );\nString ToUpper( const String &rText, INT16 nLanguage );\nString ToTitle( const String &rText, INT16 nLanguage );\nsal_Unicode ToLower( const sal_Unicode cChar, INT16 nLanguage );\nsal_Unicode ToUpper( const sal_Unicode cChar, INT16 nLanguage );\nBOOL HasDigits( const String &rText );\nBOOL IsNumeric( const String &rText );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface >\n GetOneInstanceService( const char *pServiceName );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetLinguProperties();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XSearchableDictionaryList >\n GetSearchableDictionaryList();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >\n GetDictionaryList();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUseDicList( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\nBOOL IsIgnoreControlChars( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >\n SearchDicList(\n const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryList >& rDicList,\n const ::rtl::OUString& rWord, INT16 nLanguage,\n BOOL bSearchPosDics, BOOL bSearchSpellEntry );\n\nsal_uInt8 AddEntryToDic(\n ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary > &rxDic,\n const ::rtl::OUString &rWord, sal_Bool bIsNeg,\n const ::rtl::OUString &rRplcTxt, sal_Int16 nRplcLang,\n sal_Bool bStripDot = sal_True );\n\nsal_Bool SaveDictionaries( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryList > &xDicList );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AppExitLstnr:\n\/\/ virtual base class that calls it AtExit function when the application\n\/\/ (ie the Desktop) is about to terminate\n\/\/\n\nclass AppExitListener :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::frame::XTerminateListener\n >\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::frame::XDesktop > xDesktop;\n\npublic:\n AppExitListener();\n virtual ~AppExitListener();\n\n virtual void AtExit() = 0;\n\n void Activate();\n void Deactivate();\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace linguistic\n\n#endif\n\n<commit_msg>INTEGRATION: CWS tl55 (1.14.8); FILE MERGED 2008\/05\/21 09:59:51 tl 1.14.8.1: #158047# customer specific extension<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: misc.hxx,v $\n * $Revision: 1.15 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_MISC_HXX_\n#define _LINGUISTIC_MISC_HXX_\n\n\n#include <com\/sun\/star\/uno\/Sequence.h>\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/linguistic2\/XDictionaryEntry.hpp>\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <svtools\/pathoptions.hxx>\n#include <i18npool\/lang.h>\n#include <tools\/string.hxx>\n#include <unotools\/charclass.hxx>\n#include <osl\/thread.h>\n#include <osl\/mutex.hxx>\n#include <vcl\/svapp.hxx>\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n class XFastPropertySet;\n}}}}\n\nnamespace com { namespace sun { namespace star { namespace frame {\n class XDesktop;\n}}}}\n\nclass LocaleDataWrapper;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define SN_GRAMMARCHECKER \"com.sun.star.linguistic2.GrammarChecker\"\n#define SN_SPELLCHECKER \"com.sun.star.linguistic2.SpellChecker\"\n#define SN_HYPHENATOR \"com.sun.star.linguistic2.Hyphenator\"\n#define SN_THESAURUS \"com.sun.star.linguistic2.Thesaurus\"\n#define SN_LINGU_SERVCICE_MANAGER \"com.sun.star.linguistic2.LinguServiceManager\"\n#define SN_LINGU_PROPERTIES \"com.sun.star.linguistic2.LinguProperties\"\n#define SN_DICTIONARY_LIST \"com.sun.star.linguistic2.DictionaryList\"\n#define SN_OTHER_LINGU \"com.sun.star.linguistic2.OtherLingu\"\n#define SN_DESKTOP \"com.sun.star.frame.Desktop\"\n\n\nnamespace linguistic\n{\n\n\/\/ ascii to OUString conversion\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n\/\/\/ Flags to be used with the multi-path related functions\n\/\/\/ @see GetDictionaryPaths, GetLinguisticPaths\n#define PATH_FLAG_INTERNAL 0x01\n#define PATH_FLAG_USER 0x02\n#define PATH_FLAG_WRITABLE 0x04\n#define PATH_FLAG_ALL (PATH_FLAG_INTERNAL | PATH_FLAG_USER | PATH_FLAG_WRITABLE)\n\n\n\/\/ AddEntryToDic return values\n#define DIC_ERR_NONE 0\n#define DIC_ERR_FULL 1\n#define DIC_ERR_READONLY 2\n#define DIC_ERR_UNKNOWN 3\n#define DIC_ERR_NOT_EXISTS 4\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::osl::Mutex & GetLinguMutex();\n\nLocaleDataWrapper & GetLocaleDataWrapper( INT16 nLang );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrtl_TextEncoding GetTextEncoding( INT16 nLanguage );\n\ninline ::rtl::OUString BS2OU(const ByteString &rText, rtl_TextEncoding nEnc)\n{\n return ::rtl::OUString( rText.GetBuffer(), rText.Len(), nEnc );\n}\n\ninline ByteString OU2BS(const ::rtl::OUString &rText, rtl_TextEncoding nEnc)\n{\n return ByteString( rText.getStr(), nEnc );\n}\n\nrtl::OUString StripTrailingChars( rtl::OUString &rTxt, sal_Unicode cChar );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsal_Int32 LevDistance( const rtl::OUString &rTxt1, const rtl::OUString &rTxt2 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::lang::Locale\n CreateLocale( LanguageType eLang );\n\nLanguageType\n LocaleToLanguage( const ::com::sun::star::lang::Locale& rLocale );\n\n::com::sun::star::lang::Locale&\n LanguageToLocale( ::com::sun::star::lang::Locale& rLocale, LanguageType eLang );\n\n::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale >\n LangSeqToLocaleSeq( const ::com::sun::star::uno::Sequence< INT16 > &rLangSeq );\n\n::com::sun::star::uno::Sequence< INT16 >\n LocaleSeqToLangSeq( ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > &rLocaleSeq );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ checks if file pointed to by rURL is readonly\n\/\/ and may also check return if such a file exists or not\nBOOL IsReadOnly( const String &rURL, BOOL *pbExist = 0 );\n\n\/\/ checks if a file with the given URL exists\nBOOL FileExists( const String &rURL );\n\n#ifdef TL_OUTDATED\n\/\/ returns complete file URL for given filename that is to be searched in\n\/\/ the specified path\nString GetFileURL( SvtPathOptions::Pathes ePath, const String &rFileName );\n\nString GetModulePath( SvtPathOptions::Pathes ePath, BOOL bAddAccessDelim = TRUE );\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::rtl::OUString GetDictionaryWriteablePath();\n::com::sun::star::uno::Sequence< ::rtl::OUString > GetDictionaryPaths( sal_Int16 nPathFlags = PATH_FLAG_ALL );\n::com::sun::star::uno::Sequence< ::rtl::OUString > GetLinguisticPaths( sal_Int16 nPathFlags = PATH_FLAG_ALL );\n\n\/\/\/ @returns an URL for a new and writable dictionary rDicName.\n\/\/\/ The URL will point to the path given by 'GetDictionaryWriteablePath'\nString GetWritableDictionaryURL( const String &rDicName );\n\n\/\/ looks for the specified file in the list of paths.\n\/\/ In case of multiple occurences only the first found is returned.\nString SearchFileInPaths( const String &rFile, const ::com::sun::star::uno::Sequence< ::rtl::OUString > &rPaths );\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nINT32 GetPosInWordToCheck( const rtl::OUString &rTxt, INT32 nPos );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord >\n RebuildHyphensAndControlChars( const rtl::OUString &rOrigWord,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord > &rxHyphWord );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUpper( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\nBOOL IsLower( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\n\ninline BOOL IsUpper( const String &rText, INT16 nLanguage ) { return IsUpper( rText, 0, rText.Len(), nLanguage ); }\ninline BOOL IsLower( const String &rText, INT16 nLanguage ) { return IsLower( rText, 0, rText.Len(), nLanguage ); }\n\nString ToLower( const String &rText, INT16 nLanguage );\nString ToUpper( const String &rText, INT16 nLanguage );\nString ToTitle( const String &rText, INT16 nLanguage );\nsal_Unicode ToLower( const sal_Unicode cChar, INT16 nLanguage );\nsal_Unicode ToUpper( const sal_Unicode cChar, INT16 nLanguage );\nBOOL HasDigits( const String &rText );\nBOOL IsNumeric( const String &rText );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface >\n GetOneInstanceService( const char *pServiceName );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetLinguProperties();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XSearchableDictionaryList >\n GetSearchableDictionaryList();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >\n GetDictionaryList();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUseDicList( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\nBOOL IsIgnoreControlChars( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >\n SearchDicList(\n const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryList >& rDicList,\n const ::rtl::OUString& rWord, INT16 nLanguage,\n BOOL bSearchPosDics, BOOL bSearchSpellEntry );\n\nsal_uInt8 AddEntryToDic(\n ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary > &rxDic,\n const ::rtl::OUString &rWord, sal_Bool bIsNeg,\n const ::rtl::OUString &rRplcTxt, sal_Int16 nRplcLang,\n sal_Bool bStripDot = sal_True );\n\nsal_Bool SaveDictionaries( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryList > &xDicList );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AppExitLstnr:\n\/\/ virtual base class that calls it AtExit function when the application\n\/\/ (ie the Desktop) is about to terminate\n\/\/\n\nclass AppExitListener :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::frame::XTerminateListener\n >\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::frame::XDesktop > xDesktop;\n\npublic:\n AppExitListener();\n virtual ~AppExitListener();\n\n virtual void AtExit() = 0;\n\n void Activate();\n void Deactivate();\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace linguistic\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: misc.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:46:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_MISC_HXX_\n#define _LINGUISTIC_MISC_HXX_\n\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/Sequence.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUES_HPP_\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XDICTIONARYENTRY_HPP_\n#include <com\/sun\/star\/linguistic2\/XDictionaryEntry.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XSEARCHABLEDICTIONARYLIST_HPP_\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n#endif\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef _ISOLANG_HXX\n#include <tools\/isolang.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _TOOLS_INTN_HXX\n#include <tools\/intn.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _OSL_THREAD_H_\n#include <osl\/thread.h>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n class XFastPropertySet;\n}}}};\n\nnamespace com { namespace sun { namespace star { namespace frame {\n class XDesktop;\n}}}};\n\nclass LocaleDataWrapper;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define SN_SPELLCHECKER \"com.sun.star.linguistic2.SpellChecker\"\n#define SN_HYPHENATOR \"com.sun.star.linguistic2.Hyphenator\"\n#define SN_THESAURUS \"com.sun.star.linguistic2.Thesaurus\"\n#define SN_LINGU_SERVCICE_MANAGER \"com.sun.star.linguistic2.LinguServiceManager\"\n#define SN_LINGU_PROPERTIES \"com.sun.star.linguistic2.LinguProperties\"\n#define SN_DICTIONARY_LIST \"com.sun.star.linguistic2.DictionaryList\"\n#define SN_OTHER_LINGU \"com.sun.star.linguistic2.OtherLingu\"\n#define SN_DESKTOP \"com.sun.star.frame.Desktop\"\n\n\nnamespace linguistic\n{\n\n\/\/ ascii to OUString conversion\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::osl::Mutex & GetLinguMutex();\n\nLocaleDataWrapper & GetLocaleDataWrapper( INT16 nLang );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrtl_TextEncoding GetTextEncoding( INT16 nLanguage );\n\ninline ::rtl::OUString BS2OU(const ByteString &rText, rtl_TextEncoding nEnc)\n{\n return ::rtl::OUString( rText.GetBuffer(), rText.Len(), nEnc );\n}\n\ninline ByteString OU2BS(const ::rtl::OUString &rText, rtl_TextEncoding nEnc)\n{\n return ByteString( rText.getStr(), nEnc );\n}\n\nrtl::OUString StripTrailingChars( rtl::OUString &rTxt, sal_Unicode cChar );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsal_Int32 LevDistance( const rtl::OUString &rTxt1, const rtl::OUString &rTxt2 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::lang::Locale\n CreateLocale( LanguageType eLang );\n\nLanguageType\n LocaleToLanguage( const ::com::sun::star::lang::Locale& rLocale );\n\n::com::sun::star::lang::Locale&\n LanguageToLocale( ::com::sun::star::lang::Locale& rLocale, LanguageType eLang );\n\n::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale >\n LangSeqToLocaleSeq( const ::com::sun::star::uno::Sequence< INT16 > &rLangSeq );\n\n::com::sun::star::uno::Sequence< INT16 >\n LocaleSeqToLangSeq( ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > &rLocaleSeq );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ checks if file pointed to by rURL is readonly\n\/\/ and may also check return if such a file exists or not\nBOOL IsReadOnly( const String &rURL, BOOL *pbExist = 0 );\n\n\/\/ checks if a file with the given URL exists\nBOOL FileExists( const String &rURL );\n\n\/\/ returns complete file URL for given filename that is to be searched in\n\/\/ the specified path\nString GetFileURL( SvtPathOptions::Pathes ePath, const String &rFileName );\n\nString GetModulePath( SvtPathOptions::Pathes ePath, BOOL bAddAccessDelim = TRUE );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nINT32 GetPosInWordToCheck( const rtl::OUString &rTxt, INT32 nPos );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord >\n RebuildHyphensAndControlChars( const rtl::OUString &rOrigWord,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord > &rxHyphWord );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUpper( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\nBOOL IsLower( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\n\ninline BOOL IsUpper( const String &rText, INT16 nLanguage ) { return IsUpper( rText, 0, rText.Len(), nLanguage ); }\ninline BOOL IsLower( const String &rText, INT16 nLanguage ) { return IsLower( rText, 0, rText.Len(), nLanguage ); }\n\nString ToLower( const String &rText, INT16 nLanguage );\nString ToUpper( const String &rText, INT16 nLanguage );\nString ToTitle( const String &rText, INT16 nLanguage );\nsal_Unicode ToLower( const sal_Unicode cChar, INT16 nLanguage );\nsal_Unicode ToUpper( const sal_Unicode cChar, INT16 nLanguage );\nBOOL HasDigits( const String &rText );\nBOOL IsNumeric( const String &rText );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface >\n GetOneInstanceService( const char *pServiceName );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetLinguProperties();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XSearchableDictionaryList >\n GetSearchableDictionaryList();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >\n GetDictionaryList();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUseDicList( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\nBOOL IsIgnoreControlChars( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >\n SearchDicList(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >& rDicList,\n const ::rtl::OUString& rWord, INT16 nLanguage,\n BOOL bSearchPosDics, BOOL bSearchSpellEntry );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AppExitLstnr:\n\/\/ virtual base class that calls it AtExit function when the application\n\/\/ (ie the Desktop) is about to terminate\n\/\/\n\nclass AppExitListener :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::frame::XTerminateListener\n >\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::frame::XDesktop > xDesktop;\n\npublic:\n AppExitListener();\n virtual ~AppExitListener();\n\n virtual void AtExit() = 0;\n\n void Activate();\n void Deactivate();\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace linguistic\n\n#endif\n\n<commit_msg>INTEGRATION: CWS internatiodel (1.9.12); FILE MERGED 2006\/02\/10 19:27:20 er 1.9.12.3: #i52115# move LangIDs and ISO conversion from tools to i18npool; introduce class MsLangId and libi18nisolang 2006\/01\/21 15:14:38 er 1.9.12.2: RESYNC: (1.9-1.10); FILE MERGED 2005\/06\/24 13:08:58 er 1.9.12.1: #i50205# get rid of class International<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: misc.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: vg $ $Date: 2006-04-07 13:45:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_MISC_HXX_\n#define _LINGUISTIC_MISC_HXX_\n\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/Sequence.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUES_HPP_\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XDICTIONARYENTRY_HPP_\n#include <com\/sun\/star\/linguistic2\/XDictionaryEntry.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XSEARCHABLEDICTIONARYLIST_HPP_\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n#endif\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef INCLUDED_I18NPOOL_LANG_H\n#include <i18npool\/lang.h>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _OSL_THREAD_H_\n#include <osl\/thread.h>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n class XFastPropertySet;\n}}}};\n\nnamespace com { namespace sun { namespace star { namespace frame {\n class XDesktop;\n}}}};\n\nclass LocaleDataWrapper;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define SN_SPELLCHECKER \"com.sun.star.linguistic2.SpellChecker\"\n#define SN_HYPHENATOR \"com.sun.star.linguistic2.Hyphenator\"\n#define SN_THESAURUS \"com.sun.star.linguistic2.Thesaurus\"\n#define SN_LINGU_SERVCICE_MANAGER \"com.sun.star.linguistic2.LinguServiceManager\"\n#define SN_LINGU_PROPERTIES \"com.sun.star.linguistic2.LinguProperties\"\n#define SN_DICTIONARY_LIST \"com.sun.star.linguistic2.DictionaryList\"\n#define SN_OTHER_LINGU \"com.sun.star.linguistic2.OtherLingu\"\n#define SN_DESKTOP \"com.sun.star.frame.Desktop\"\n\n\nnamespace linguistic\n{\n\n\/\/ ascii to OUString conversion\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::osl::Mutex & GetLinguMutex();\n\nLocaleDataWrapper & GetLocaleDataWrapper( INT16 nLang );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrtl_TextEncoding GetTextEncoding( INT16 nLanguage );\n\ninline ::rtl::OUString BS2OU(const ByteString &rText, rtl_TextEncoding nEnc)\n{\n return ::rtl::OUString( rText.GetBuffer(), rText.Len(), nEnc );\n}\n\ninline ByteString OU2BS(const ::rtl::OUString &rText, rtl_TextEncoding nEnc)\n{\n return ByteString( rText.getStr(), nEnc );\n}\n\nrtl::OUString StripTrailingChars( rtl::OUString &rTxt, sal_Unicode cChar );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsal_Int32 LevDistance( const rtl::OUString &rTxt1, const rtl::OUString &rTxt2 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::lang::Locale\n CreateLocale( LanguageType eLang );\n\nLanguageType\n LocaleToLanguage( const ::com::sun::star::lang::Locale& rLocale );\n\n::com::sun::star::lang::Locale&\n LanguageToLocale( ::com::sun::star::lang::Locale& rLocale, LanguageType eLang );\n\n::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale >\n LangSeqToLocaleSeq( const ::com::sun::star::uno::Sequence< INT16 > &rLangSeq );\n\n::com::sun::star::uno::Sequence< INT16 >\n LocaleSeqToLangSeq( ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > &rLocaleSeq );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ checks if file pointed to by rURL is readonly\n\/\/ and may also check return if such a file exists or not\nBOOL IsReadOnly( const String &rURL, BOOL *pbExist = 0 );\n\n\/\/ checks if a file with the given URL exists\nBOOL FileExists( const String &rURL );\n\n\/\/ returns complete file URL for given filename that is to be searched in\n\/\/ the specified path\nString GetFileURL( SvtPathOptions::Pathes ePath, const String &rFileName );\n\nString GetModulePath( SvtPathOptions::Pathes ePath, BOOL bAddAccessDelim = TRUE );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nINT32 GetPosInWordToCheck( const rtl::OUString &rTxt, INT32 nPos );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord >\n RebuildHyphensAndControlChars( const rtl::OUString &rOrigWord,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XHyphenatedWord > &rxHyphWord );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUpper( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\nBOOL IsLower( const String &rText, xub_StrLen nPos, xub_StrLen nLen, INT16 nLanguage );\n\ninline BOOL IsUpper( const String &rText, INT16 nLanguage ) { return IsUpper( rText, 0, rText.Len(), nLanguage ); }\ninline BOOL IsLower( const String &rText, INT16 nLanguage ) { return IsLower( rText, 0, rText.Len(), nLanguage ); }\n\nString ToLower( const String &rText, INT16 nLanguage );\nString ToUpper( const String &rText, INT16 nLanguage );\nString ToTitle( const String &rText, INT16 nLanguage );\nsal_Unicode ToLower( const sal_Unicode cChar, INT16 nLanguage );\nsal_Unicode ToUpper( const sal_Unicode cChar, INT16 nLanguage );\nBOOL HasDigits( const String &rText );\nBOOL IsNumeric( const String &rText );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface >\n GetOneInstanceService( const char *pServiceName );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetLinguProperties();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XSearchableDictionaryList >\n GetSearchableDictionaryList();\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >\n GetDictionaryList();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOL IsUseDicList( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\nBOOL IsIgnoreControlChars( const ::com::sun::star::beans::PropertyValues &rProperties,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > &rxPropSet );\n\n::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >\n SearchDicList(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryList >& rDicList,\n const ::rtl::OUString& rWord, INT16 nLanguage,\n BOOL bSearchPosDics, BOOL bSearchSpellEntry );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AppExitLstnr:\n\/\/ virtual base class that calls it AtExit function when the application\n\/\/ (ie the Desktop) is about to terminate\n\/\/\n\nclass AppExitListener :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::frame::XTerminateListener\n >\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::frame::XDesktop > xDesktop;\n\npublic:\n AppExitListener();\n virtual ~AppExitListener();\n\n virtual void AtExit() = 0;\n\n void Activate();\n void Deactivate();\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace linguistic\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Rest\/Version.h\"\n\n#ifdef _WIN32\n#include \"Basics\/win-utils.h\"\n#endif\n\n#include <sstream>\n\n#include <curl\/curl.h>\n#include <openssl\/ssl.h>\n\n#include <rocksdb\/convenience.h>\n#include <rocksdb\/version.h>\n\n#include <velocypack\/Builder.h>\n#include <velocypack\/Version.h>\n#include <velocypack\/velocypack-aliases.h>\n\n#include \"Basics\/StringUtils.h\"\n#include \"Basics\/Utf8Helper.h\"\n#include \"Basics\/asio_ns.h\"\n#include \"Basics\/build-date.h\"\n#include \"Basics\/build-repository.h\"\n#include \"Basics\/conversions.h\"\n\n#include \"3rdParty\/iresearch\/core\/utils\/version_defines.hpp\"\n\nusing namespace arangodb::rest;\n\nstd::map<std::string, std::string> Version::Values;\n\n\/\/\/ @brief parse a version string into major, minor\n\/\/\/ returns -1, -1 when the version string has an invalid format\n\/\/\/ returns major, -1 when only the major version can be determined\nstd::pair<int, int> Version::parseVersionString(std::string const& str) {\n std::pair<int, int> result{-1, -1};\n\n if (!str.empty()) {\n char const* p = str.c_str();\n char const* q = p;\n while (*q >= '0' && *q <= '9') {\n ++q;\n }\n if (p != q) {\n result.first = std::stoi(std::string(p, q - p));\n result.second = 0;\n\n if (*q == '.') {\n ++q;\n }\n p = q;\n while (*q >= '0' && *q <= '9') {\n ++q;\n }\n if (p != q) {\n result.second = std::stoi(std::string(p, q - p));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/ @brief initialize\nvoid Version::initialize() {\n if (!Values.empty()) {\n return;\n }\n\n Values[\"architecture\"] =\n (sizeof(void*) == 4 ? \"32\" : \"64\") + std::string(\"bit\");\n#ifdef __arm__\n Values[\"arm\"] = \"true\";\n#else\n Values[\"arm\"] = \"false\";\n#endif\n Values[\"asm-crc32\"] = (ENABLE_ASM_CRC32) ? \"true\" : \"false\";\n Values[\"boost-version\"] = getBoostVersion();\n Values[\"build-date\"] = getBuildDate();\n Values[\"compiler\"] = getCompiler();\n#ifdef _DEBUG\n Values[\"debug\"] = \"true\";\n#else\n Values[\"debug\"] = \"false\";\n#endif\n#ifdef NDEBUG\n Values[\"ndebug\"] = \"true\";\n#else\n Values[\"ndebug\"] = \"false\";\n#endif\n#if defined(ARCHITECTURE_OPTIMIZATIONS)\n Values[\"optimization-flags\"] = std::string(ARCHITECTURE_OPTIMIZATIONS);\n#endif\n Values[\"endianness\"] = getEndianness();\n Values[\"fd-setsize\"] = arangodb::basics::StringUtils::itoa(FD_SETSIZE);\n Values[\"full-version-string\"] = getVerboseVersionString();\n Values[\"icu-version\"] = getICUVersion();\n Values[\"openssl-version-compile-time\"] = getOpenSSLVersion(true);\n Values[\"openssl-version-run-time\"] = getOpenSSLVersion(false);\n#ifdef __pie__\n Values[\"pie\"] = std::to_string(__pie__);\n#else \n Values[\"pie\"] = \"none\";\n#endif\n Values[\"platform\"] = TRI_PLATFORM;\n Values[\"reactor-type\"] = getBoostReactorType();\n Values[\"server-version\"] = getServerVersion();\n Values[\"sizeof int\"] = arangodb::basics::StringUtils::itoa(sizeof(int));\n Values[\"sizeof long\"] = arangodb::basics::StringUtils::itoa(sizeof(long));\n Values[\"sizeof void*\"] = arangodb::basics::StringUtils::itoa(sizeof(void*));\n#ifdef TRI_UNALIGNED_ACCESS\n Values[\"unaligned-access\"] = \"true\";\n#else\n Values[\"unaligned-access\"] = \"false\";\n#endif\n Values[\"v8-version\"] = getV8Version();\n Values[\"vpack-version\"] = getVPackVersion();\n Values[\"zlib-version\"] = getZLibVersion();\n\n#if USE_ENTERPRISE\n Values[\"enterprise-version\"] = ARANGODB_ENTERPRISE_VERSION;\n Values[\"license\"] = \"enterprise\";\n#else\n Values[\"license\"] = \"community\";\n#endif\n\n#if HAVE_ARANGODB_BUILD_REPOSITORY\n Values[\"build-repository\"] = getBuildRepository();\n#endif\n\n Values[\"curl-version\"] = curl_version();\n\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n Values[\"assertions\"] = \"true\";\n#else\n Values[\"assertions\"] = \"false\";\n#endif\n\n Values[\"rocksdb-version\"] = getRocksDBVersion();\n\n#ifdef __cplusplus\n Values[\"cplusplus\"] = std::to_string(__cplusplus);\n#else\n Values[\"cplusplus\"] = \"unknown\";\n#endif\n\n#if defined(__SANITIZE_ADDRESS__) || \\\n (defined(__has_feature) && __has_feature(address_sanitizer))\n Values[\"asan\"] = \"true\";\n#else\n Values[\"asan\"] = \"false\";\n#if defined(__has_feature)\n#if __has_feature(address_sanitizer)\n Values[\"asan\"] = \"true\";\n#endif\n#endif\n#endif\n\n#if defined(__SSE4_2__) && !defined(NO_SSE42)\n Values[\"sse42\"] = \"true\";\n#else\n Values[\"sse42\"] = \"false\";\n#endif\n\n#ifdef __AVX2__\n Values[\"avx2\"] = \"true\";\n#else\n Values[\"avx2\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n Values[\"maintainer-mode\"] = \"true\";\n#else\n Values[\"maintainer-mode\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_ENABLE_FAILURE_TESTS\n Values[\"failure-tests\"] = \"true\";\n#else\n Values[\"failure-tests\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_HAVE_JEMALLOC\n Values[\"jemalloc\"] = \"true\";\n#else\n Values[\"jemalloc\"] = \"false\";\n#endif\n\n#ifdef TRI_HAVE_POLL_H\n Values[\"fd-client-event-handler\"] = \"poll\";\n#else\n Values[\"fd-client-event-handler\"] = \"select\";\n#endif\n\n Values[\"iresearch-version\"] = getIResearchVersion();\n\n for (auto& it : Values) {\n arangodb::basics::StringUtils::trimInPlace(it.second);\n }\n}\n\n\/\/\/ @brief get numeric server version\nint32_t Version::getNumericServerVersion() {\n char const* apiVersion = ARANGODB_VERSION;\n char const* p = apiVersion;\n\n \/\/ read major version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n TRI_ASSERT(*p == '.');\n int32_t major = TRI_Int32String(apiVersion, (p - apiVersion));\n\n apiVersion = ++p;\n\n \/\/ read minor version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n TRI_ASSERT((*p == '.' || *p == '-' || *p == '\\0') && p != apiVersion);\n int32_t minor = TRI_Int32String(apiVersion, (p - apiVersion));\n\n int32_t patch = 0;\n if (*p == '.') {\n apiVersion = ++p;\n\n \/\/ read minor version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n if (p != apiVersion) {\n patch = TRI_Int32String(apiVersion, (p - apiVersion));\n }\n }\n\n return (int32_t)(patch + minor * 100L + major * 10000L);\n}\n\n\/\/\/ @brief get server version\nstd::string Version::getServerVersion() {\n return std::string(ARANGODB_VERSION);\n}\n\n\/\/\/ @brief get BOOST version\nstd::string Version::getBoostVersion() {\n#ifdef ARANGODB_BOOST_VERSION\n return std::string(ARANGODB_BOOST_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get boost reactor type\nstd::string Version::getBoostReactorType() {\n#if defined(BOOST_ASIO_HAS_IOCP)\n return std::string(\"iocp\");\n#elif defined(BOOST_ASIO_HAS_EPOLL)\n return std::string(\"epoll\");\n#elif defined(BOOST_ASIO_HAS_KQUEUE)\n return std::string(\"kqueue\");\n#elif defined(BOOST_ASIO_HAS_DEV_POLL)\n return std::string(\"\/dev\/poll\");\n#else\n return std::string(\"select\");\n#endif\n}\n\n\/\/\/ @brief get RocksDB version\nstd::string Version::getRocksDBVersion() {\n return std::to_string(ROCKSDB_MAJOR) + \".\" + std::to_string(ROCKSDB_MINOR) +\n \".\" + std::to_string(ROCKSDB_PATCH);\n}\n\n\/\/\/ @brief get V8 version\nstd::string Version::getV8Version() {\n#ifdef ARANGODB_V8_VERSION\n return std::string(ARANGODB_V8_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get OpenSSL version\nstd::string Version::getOpenSSLVersion(bool compileTime) {\n if (compileTime) {\n#ifdef OPENSSL_VERSION_TEXT\n return std::string(OPENSSL_VERSION_TEXT);\n#elif defined(ARANGODB_OPENSSL_VERSION)\n return std::string(ARANGODB_OPENSSL_VERSION);\n#else\n return std::string(\"openssl (unknown version)\");\n#endif\n } else {\n char const* v = SSLeay_version(SSLEAY_VERSION);\n\n if (v == nullptr) {\n return std::string(\"openssl (unknown version)\");\n }\n\n return std::string(v);\n }\n}\n\n\/\/\/ @brief get vpack version\nstd::string Version::getVPackVersion() {\n return arangodb::velocypack::Version::BuildVersion.toString();\n}\n\n\/\/\/ @brief get zlib version\nstd::string Version::getZLibVersion() {\n#ifdef ARANGODB_ZLIB_VERSION\n return std::string(ARANGODB_ZLIB_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get ICU version\nstd::string Version::getICUVersion() {\n UVersionInfo icuVersion;\n char icuVersionString[U_MAX_VERSION_STRING_LENGTH];\n u_getVersion(icuVersion);\n u_versionToString(icuVersion, icuVersionString);\n\n return icuVersionString;\n}\n\n\/\/\/ @brief get IResearch version\nstd::string Version::getIResearchVersion() { return IResearch_version; }\n\n\/\/\/ @brief get compiler\nstd::string Version::getCompiler() {\n#if defined(__clang__)\n return \"clang [\" + std::string(__VERSION__) + \"]\";\n#elif defined(__GNUC__) || defined(__GNUG__)\n return \"gcc [\" + std::string(__VERSION__) + \"]\";\n#elif defined(_MSC_VER)\n return \"msvc [\" + std::to_string(_MSC_VER) + \"]\";\n#else\n return \"unknown\";\n#endif\n}\n\n\/\/\/ @brief get endianness\nstd::string Version::getEndianness() {\n uint64_t value = 0x12345678abcdef99;\n static_assert(sizeof(value) == 8, \"unexpected uint64_t size\");\n\n unsigned char const* p = reinterpret_cast<unsigned char const*>(&value);\n if (p[0] == 0x12 && p[1] == 0x34 && p[2] == 0x56 && p[3] == 0x78 &&\n p[4] == 0xab && p[5] == 0xcd && p[6] == 0xef && p[7] == 0x99) {\n return \"big\";\n }\n\n if (p[0] == 0x99 && p[1] == 0xef && p[2] == 0xcd && p[3] == 0xab &&\n p[4] == 0x78 && p[5] == 0x56 && p[6] == 0x34 && p[7] == 0x12) {\n return \"little\";\n }\n return \"unknown\";\n}\n\n\/\/\/ @brief get build date\nstd::string Version::getBuildDate() {\n\/\/ the OpenSuSE build system does not like it, if __DATE__ is used\n#ifdef ARANGODB_BUILD_DATE\n return std::string(ARANGODB_BUILD_DATE);\n#else\n return std::string(__DATE__).append(\" \").append(__TIME__);\n#endif\n}\n\n\/\/\/ @brief get build repository\nstd::string Version::getBuildRepository() {\n#ifdef HAVE_ARANGODB_BUILD_REPOSITORY\n return std::string(ARANGODB_BUILD_REPOSITORY);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief return a server version string\nstd::string Version::getVerboseVersionString() {\n std::ostringstream version;\n\n version << \"ArangoDB \" << ARANGODB_VERSION_FULL << \" \"\n << (sizeof(void*) == 4 ? \"32\" : \"64\") << \"bit\"\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n << \" maintainer mode\"\n#endif\n#if defined(__SANITIZE_ADDRESS__) || \\\n (defined(__has_feature) && __has_feature(address_sanitizer))\n << \" with ASAN\"\n#endif\n << \", using \"\n#ifdef ARANGODB_HAVE_JEMALLOC\n << \"jemalloc, \"\n#endif\n#ifdef HAVE_ARANGODB_BUILD_REPOSITORY\n << \"build \" << getBuildRepository() << \", \"\n#endif\n << \"VPack \" << getVPackVersion() << \", \"\n << \"RocksDB \" << getRocksDBVersion() << \", \"\n << \"ICU \" << getICUVersion() << \", \"\n << \"V8 \" << getV8Version() << \", \" << getOpenSSLVersion(false);\n\n return version.str();\n}\n\n\/\/\/ @brief get detailed version information as a (multi-line) string\nstd::string Version::getDetailed() {\n std::string result;\n\n for (auto const& it : Values) {\n std::string const& value = it.second;\n\n if (!value.empty()) {\n result.append(it.first);\n result.append(\": \");\n result.append(it.second);\n#ifdef _WIN32\n result += \"\\r\\n\";\n#else\n result += \"\\n\";\n#endif\n }\n }\n\n return result;\n}\n\n\/\/\/ @brief VelocyPack all data\nvoid Version::getVPack(VPackBuilder& dst) {\n TRI_ASSERT(!dst.isClosed());\n\n for (auto const& it : Values) {\n std::string const& value = it.second;\n\n if (!value.empty()) {\n dst.add(it.first, VPackValue(value));\n }\n }\n}\n<commit_msg>added pic<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Rest\/Version.h\"\n\n#ifdef _WIN32\n#include \"Basics\/win-utils.h\"\n#endif\n\n#include <sstream>\n\n#include <curl\/curl.h>\n#include <openssl\/ssl.h>\n\n#include <rocksdb\/convenience.h>\n#include <rocksdb\/version.h>\n\n#include <velocypack\/Builder.h>\n#include <velocypack\/Version.h>\n#include <velocypack\/velocypack-aliases.h>\n\n#include \"Basics\/StringUtils.h\"\n#include \"Basics\/Utf8Helper.h\"\n#include \"Basics\/asio_ns.h\"\n#include \"Basics\/build-date.h\"\n#include \"Basics\/build-repository.h\"\n#include \"Basics\/conversions.h\"\n\n#include \"3rdParty\/iresearch\/core\/utils\/version_defines.hpp\"\n\nusing namespace arangodb::rest;\n\nstd::map<std::string, std::string> Version::Values;\n\n\/\/\/ @brief parse a version string into major, minor\n\/\/\/ returns -1, -1 when the version string has an invalid format\n\/\/\/ returns major, -1 when only the major version can be determined\nstd::pair<int, int> Version::parseVersionString(std::string const& str) {\n std::pair<int, int> result{-1, -1};\n\n if (!str.empty()) {\n char const* p = str.c_str();\n char const* q = p;\n while (*q >= '0' && *q <= '9') {\n ++q;\n }\n if (p != q) {\n result.first = std::stoi(std::string(p, q - p));\n result.second = 0;\n\n if (*q == '.') {\n ++q;\n }\n p = q;\n while (*q >= '0' && *q <= '9') {\n ++q;\n }\n if (p != q) {\n result.second = std::stoi(std::string(p, q - p));\n }\n }\n }\n\n return result;\n}\n\n\/\/\/ @brief initialize\nvoid Version::initialize() {\n if (!Values.empty()) {\n return;\n }\n\n Values[\"architecture\"] =\n (sizeof(void*) == 4 ? \"32\" : \"64\") + std::string(\"bit\");\n#ifdef __arm__\n Values[\"arm\"] = \"true\";\n#else\n Values[\"arm\"] = \"false\";\n#endif\n Values[\"asm-crc32\"] = (ENABLE_ASM_CRC32) ? \"true\" : \"false\";\n Values[\"boost-version\"] = getBoostVersion();\n Values[\"build-date\"] = getBuildDate();\n Values[\"compiler\"] = getCompiler();\n#ifdef _DEBUG\n Values[\"debug\"] = \"true\";\n#else\n Values[\"debug\"] = \"false\";\n#endif\n#ifdef NDEBUG\n Values[\"ndebug\"] = \"true\";\n#else\n Values[\"ndebug\"] = \"false\";\n#endif\n#if defined(ARCHITECTURE_OPTIMIZATIONS)\n Values[\"optimization-flags\"] = std::string(ARCHITECTURE_OPTIMIZATIONS);\n#endif\n Values[\"endianness\"] = getEndianness();\n Values[\"fd-setsize\"] = arangodb::basics::StringUtils::itoa(FD_SETSIZE);\n Values[\"full-version-string\"] = getVerboseVersionString();\n Values[\"icu-version\"] = getICUVersion();\n Values[\"openssl-version-compile-time\"] = getOpenSSLVersion(true);\n Values[\"openssl-version-run-time\"] = getOpenSSLVersion(false);\n#ifdef __pic__\n Values[\"pic\"] = std::to_string(__pic__);\n#else\n Values[\"pic\"] = \"none\";\n#endif\n#ifdef __pie__\n Values[\"pie\"] = std::to_string(__pie__);\n#else\n Values[\"pie\"] = \"none\";\n#endif\n Values[\"platform\"] = TRI_PLATFORM;\n Values[\"reactor-type\"] = getBoostReactorType();\n Values[\"server-version\"] = getServerVersion();\n Values[\"sizeof int\"] = arangodb::basics::StringUtils::itoa(sizeof(int));\n Values[\"sizeof long\"] = arangodb::basics::StringUtils::itoa(sizeof(long));\n Values[\"sizeof void*\"] = arangodb::basics::StringUtils::itoa(sizeof(void*));\n#ifdef TRI_UNALIGNED_ACCESS\n Values[\"unaligned-access\"] = \"true\";\n#else\n Values[\"unaligned-access\"] = \"false\";\n#endif\n Values[\"v8-version\"] = getV8Version();\n Values[\"vpack-version\"] = getVPackVersion();\n Values[\"zlib-version\"] = getZLibVersion();\n\n#if USE_ENTERPRISE\n Values[\"enterprise-version\"] = ARANGODB_ENTERPRISE_VERSION;\n Values[\"license\"] = \"enterprise\";\n#else\n Values[\"license\"] = \"community\";\n#endif\n\n#if HAVE_ARANGODB_BUILD_REPOSITORY\n Values[\"build-repository\"] = getBuildRepository();\n#endif\n\n Values[\"curl-version\"] = curl_version();\n\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n Values[\"assertions\"] = \"true\";\n#else\n Values[\"assertions\"] = \"false\";\n#endif\n\n Values[\"rocksdb-version\"] = getRocksDBVersion();\n\n#ifdef __cplusplus\n Values[\"cplusplus\"] = std::to_string(__cplusplus);\n#else\n Values[\"cplusplus\"] = \"unknown\";\n#endif\n\n#if defined(__SANITIZE_ADDRESS__) || \\\n (defined(__has_feature) && __has_feature(address_sanitizer))\n Values[\"asan\"] = \"true\";\n#else\n Values[\"asan\"] = \"false\";\n#if defined(__has_feature)\n#if __has_feature(address_sanitizer)\n Values[\"asan\"] = \"true\";\n#endif\n#endif\n#endif\n\n#if defined(__SSE4_2__) && !defined(NO_SSE42)\n Values[\"sse42\"] = \"true\";\n#else\n Values[\"sse42\"] = \"false\";\n#endif\n\n#ifdef __AVX2__\n Values[\"avx2\"] = \"true\";\n#else\n Values[\"avx2\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n Values[\"maintainer-mode\"] = \"true\";\n#else\n Values[\"maintainer-mode\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_ENABLE_FAILURE_TESTS\n Values[\"failure-tests\"] = \"true\";\n#else\n Values[\"failure-tests\"] = \"false\";\n#endif\n\n#ifdef ARANGODB_HAVE_JEMALLOC\n Values[\"jemalloc\"] = \"true\";\n#else\n Values[\"jemalloc\"] = \"false\";\n#endif\n\n#ifdef TRI_HAVE_POLL_H\n Values[\"fd-client-event-handler\"] = \"poll\";\n#else\n Values[\"fd-client-event-handler\"] = \"select\";\n#endif\n\n Values[\"iresearch-version\"] = getIResearchVersion();\n\n for (auto& it : Values) {\n arangodb::basics::StringUtils::trimInPlace(it.second);\n }\n}\n\n\/\/\/ @brief get numeric server version\nint32_t Version::getNumericServerVersion() {\n char const* apiVersion = ARANGODB_VERSION;\n char const* p = apiVersion;\n\n \/\/ read major version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n TRI_ASSERT(*p == '.');\n int32_t major = TRI_Int32String(apiVersion, (p - apiVersion));\n\n apiVersion = ++p;\n\n \/\/ read minor version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n TRI_ASSERT((*p == '.' || *p == '-' || *p == '\\0') && p != apiVersion);\n int32_t minor = TRI_Int32String(apiVersion, (p - apiVersion));\n\n int32_t patch = 0;\n if (*p == '.') {\n apiVersion = ++p;\n\n \/\/ read minor version\n while (*p >= '0' && *p <= '9') {\n ++p;\n }\n\n if (p != apiVersion) {\n patch = TRI_Int32String(apiVersion, (p - apiVersion));\n }\n }\n\n return (int32_t)(patch + minor * 100L + major * 10000L);\n}\n\n\/\/\/ @brief get server version\nstd::string Version::getServerVersion() {\n return std::string(ARANGODB_VERSION);\n}\n\n\/\/\/ @brief get BOOST version\nstd::string Version::getBoostVersion() {\n#ifdef ARANGODB_BOOST_VERSION\n return std::string(ARANGODB_BOOST_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get boost reactor type\nstd::string Version::getBoostReactorType() {\n#if defined(BOOST_ASIO_HAS_IOCP)\n return std::string(\"iocp\");\n#elif defined(BOOST_ASIO_HAS_EPOLL)\n return std::string(\"epoll\");\n#elif defined(BOOST_ASIO_HAS_KQUEUE)\n return std::string(\"kqueue\");\n#elif defined(BOOST_ASIO_HAS_DEV_POLL)\n return std::string(\"\/dev\/poll\");\n#else\n return std::string(\"select\");\n#endif\n}\n\n\/\/\/ @brief get RocksDB version\nstd::string Version::getRocksDBVersion() {\n return std::to_string(ROCKSDB_MAJOR) + \".\" + std::to_string(ROCKSDB_MINOR) +\n \".\" + std::to_string(ROCKSDB_PATCH);\n}\n\n\/\/\/ @brief get V8 version\nstd::string Version::getV8Version() {\n#ifdef ARANGODB_V8_VERSION\n return std::string(ARANGODB_V8_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get OpenSSL version\nstd::string Version::getOpenSSLVersion(bool compileTime) {\n if (compileTime) {\n#ifdef OPENSSL_VERSION_TEXT\n return std::string(OPENSSL_VERSION_TEXT);\n#elif defined(ARANGODB_OPENSSL_VERSION)\n return std::string(ARANGODB_OPENSSL_VERSION);\n#else\n return std::string(\"openssl (unknown version)\");\n#endif\n } else {\n char const* v = SSLeay_version(SSLEAY_VERSION);\n\n if (v == nullptr) {\n return std::string(\"openssl (unknown version)\");\n }\n\n return std::string(v);\n }\n}\n\n\/\/\/ @brief get vpack version\nstd::string Version::getVPackVersion() {\n return arangodb::velocypack::Version::BuildVersion.toString();\n}\n\n\/\/\/ @brief get zlib version\nstd::string Version::getZLibVersion() {\n#ifdef ARANGODB_ZLIB_VERSION\n return std::string(ARANGODB_ZLIB_VERSION);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief get ICU version\nstd::string Version::getICUVersion() {\n UVersionInfo icuVersion;\n char icuVersionString[U_MAX_VERSION_STRING_LENGTH];\n u_getVersion(icuVersion);\n u_versionToString(icuVersion, icuVersionString);\n\n return icuVersionString;\n}\n\n\/\/\/ @brief get IResearch version\nstd::string Version::getIResearchVersion() { return IResearch_version; }\n\n\/\/\/ @brief get compiler\nstd::string Version::getCompiler() {\n#if defined(__clang__)\n return \"clang [\" + std::string(__VERSION__) + \"]\";\n#elif defined(__GNUC__) || defined(__GNUG__)\n return \"gcc [\" + std::string(__VERSION__) + \"]\";\n#elif defined(_MSC_VER)\n return \"msvc [\" + std::to_string(_MSC_VER) + \"]\";\n#else\n return \"unknown\";\n#endif\n}\n\n\/\/\/ @brief get endianness\nstd::string Version::getEndianness() {\n uint64_t value = 0x12345678abcdef99;\n static_assert(sizeof(value) == 8, \"unexpected uint64_t size\");\n\n unsigned char const* p = reinterpret_cast<unsigned char const*>(&value);\n if (p[0] == 0x12 && p[1] == 0x34 && p[2] == 0x56 && p[3] == 0x78 &&\n p[4] == 0xab && p[5] == 0xcd && p[6] == 0xef && p[7] == 0x99) {\n return \"big\";\n }\n\n if (p[0] == 0x99 && p[1] == 0xef && p[2] == 0xcd && p[3] == 0xab &&\n p[4] == 0x78 && p[5] == 0x56 && p[6] == 0x34 && p[7] == 0x12) {\n return \"little\";\n }\n return \"unknown\";\n}\n\n\/\/\/ @brief get build date\nstd::string Version::getBuildDate() {\n\/\/ the OpenSuSE build system does not like it, if __DATE__ is used\n#ifdef ARANGODB_BUILD_DATE\n return std::string(ARANGODB_BUILD_DATE);\n#else\n return std::string(__DATE__).append(\" \").append(__TIME__);\n#endif\n}\n\n\/\/\/ @brief get build repository\nstd::string Version::getBuildRepository() {\n#ifdef HAVE_ARANGODB_BUILD_REPOSITORY\n return std::string(ARANGODB_BUILD_REPOSITORY);\n#else\n return std::string();\n#endif\n}\n\n\/\/\/ @brief return a server version string\nstd::string Version::getVerboseVersionString() {\n std::ostringstream version;\n\n version << \"ArangoDB \" << ARANGODB_VERSION_FULL << \" \"\n << (sizeof(void*) == 4 ? \"32\" : \"64\") << \"bit\"\n#ifdef ARANGODB_ENABLE_MAINTAINER_MODE\n << \" maintainer mode\"\n#endif\n#if defined(__SANITIZE_ADDRESS__) || \\\n (defined(__has_feature) && __has_feature(address_sanitizer))\n << \" with ASAN\"\n#endif\n << \", using \"\n#ifdef ARANGODB_HAVE_JEMALLOC\n << \"jemalloc, \"\n#endif\n#ifdef HAVE_ARANGODB_BUILD_REPOSITORY\n << \"build \" << getBuildRepository() << \", \"\n#endif\n << \"VPack \" << getVPackVersion() << \", \"\n << \"RocksDB \" << getRocksDBVersion() << \", \"\n << \"ICU \" << getICUVersion() << \", \"\n << \"V8 \" << getV8Version() << \", \" << getOpenSSLVersion(false);\n\n return version.str();\n}\n\n\/\/\/ @brief get detailed version information as a (multi-line) string\nstd::string Version::getDetailed() {\n std::string result;\n\n for (auto const& it : Values) {\n std::string const& value = it.second;\n\n if (!value.empty()) {\n result.append(it.first);\n result.append(\": \");\n result.append(it.second);\n#ifdef _WIN32\n result += \"\\r\\n\";\n#else\n result += \"\\n\";\n#endif\n }\n }\n\n return result;\n}\n\n\/\/\/ @brief VelocyPack all data\nvoid Version::getVPack(VPackBuilder& dst) {\n TRI_ASSERT(!dst.isClosed());\n\n for (auto const& it : Values) {\n std::string const& value = it.second;\n\n if (!value.empty()) {\n dst.add(it.first, VPackValue(value));\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n printf(\"hello world!\\n\");\n printf(\"show me the code\\n\");\n printf(\"Talk is cheap\\n\");\n sleep(100); \n \/\/ this is first branch.\n\n \/\/ this is the second line.\n return 0;\n}\n\n<commit_msg>delete talk is cheap<commit_after>#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n printf(\"hello world!\\n\");\n printf(\"show me the code\\n\");\n printf(\"##Tommy##\\n\");\n sleep(100); \n \/\/ this is first branch.\n\n \/\/ this is the second line.\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n : Name(name), Ty(checkType(ty), this) {\n VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as \n \/\/ a <badref>\n \/\/\n if (Uses.begin() != Uses.end()) {\n std::cerr << \"While deleting: \" << Ty << \"%\" << Name << \"\\n\";\n for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)\n std::cerr << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(Uses.begin() == Uses.end());\n\n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\nvoid Value::replaceAllUsesWith(Value *D) {\n assert(D && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(D != this && \"V->replaceAllUsesWith(V) is NOT valid!\");\n assert(D->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n while (!Uses.empty()) {\n User *Use = Uses.back();\n#ifndef NDEBUG\n unsigned NumUses = Uses.size();\n#endif\n Use->replaceUsesOfWith(this, D);\n\n#ifndef NDEBUG \/\/ only in -g mode...\n if (Uses.size() == NumUses)\n std::cerr << \"Use: \" << *Use << \"replace with: \" << *D;\n#endif\n assert(Uses.size() != NumUses && \"Didn't remove definition!\");\n }\n}\n\n\/\/ refineAbstractType - This function is implemented because we use\n\/\/ potentially abstract types, and these types may be resolved to more\n\/\/ concrete types after we are constructed. For the value class, we simply\n\/\/ change Ty to point to the right type. :)\n\/\/\nvoid Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {\n assert(Ty.get() == OldTy && \"Can't refine anything but my type!\");\n if (OldTy == NewTy && !OldTy->isAbstract())\n Ty.removeUserFromConcrete();\n Ty = NewTy;\n}\n\nvoid Value::killUse(User *i) {\n if (i == 0) return;\n use_iterator I = find(Uses.begin(), Uses.end(), i);\n\n assert(I != Uses.end() && \"Use not in uses list!!\");\n Uses.erase(I);\n}\n\nUser *Value::use_remove(use_iterator &I) {\n assert(I != Uses.end() && \"Trying to remove the end of the use list!!!\");\n User *i = *I;\n I = Uses.erase(I);\n return i;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n\n\n<commit_msg>Fix NASTY N^2 behavior that was causing the gzip benchmark to take forever to assemble. Now we scan the use-list from the back when removing users instead of from the front.<commit_after>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n : Name(name), Ty(checkType(ty), this) {\n VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as \n \/\/ a <badref>\n \/\/\n if (Uses.begin() != Uses.end()) {\n std::cerr << \"While deleting: \" << Ty << \"%\" << Name << \"\\n\";\n for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)\n std::cerr << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(Uses.begin() == Uses.end());\n\n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\nvoid Value::replaceAllUsesWith(Value *D) {\n assert(D && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(D != this && \"V->replaceAllUsesWith(V) is NOT valid!\");\n assert(D->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n while (!Uses.empty()) {\n User *Use = Uses.back();\n#ifndef NDEBUG\n unsigned NumUses = Uses.size();\n#endif\n Use->replaceUsesOfWith(this, D);\n\n#ifndef NDEBUG \/\/ only in -g mode...\n if (Uses.size() == NumUses)\n std::cerr << \"Use: \" << *Use << \"replace with: \" << *D;\n#endif\n assert(Uses.size() != NumUses && \"Didn't remove definition!\");\n }\n}\n\n\/\/ refineAbstractType - This function is implemented because we use\n\/\/ potentially abstract types, and these types may be resolved to more\n\/\/ concrete types after we are constructed. For the value class, we simply\n\/\/ change Ty to point to the right type. :)\n\/\/\nvoid Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {\n assert(Ty.get() == OldTy && \"Can't refine anything but my type!\");\n if (OldTy == NewTy && !OldTy->isAbstract())\n Ty.removeUserFromConcrete();\n Ty = NewTy;\n}\n\nvoid Value::killUse(User *U) {\n if (U == 0) return;\n unsigned i;\n\n \/\/ Scan backwards through the uses list looking for the user. We do this\n \/\/ because vectors like to be accessed on the end. This is incredibly\n \/\/ important from a performance perspective.\n for (i = Uses.size()-1; Uses[i] != U; --i)\n \/* empty *\/;\n\n assert(i < Uses.size() && \"Use not in uses list!!\");\n Uses.erase(Uses.begin()+i);\n}\n\nUser *Value::use_remove(use_iterator &I) {\n assert(I != Uses.end() && \"Trying to remove the end of the use list!!!\");\n User *i = *I;\n I = Uses.erase(I);\n return i;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constant.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ValueSymbolTable.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include <algorithm>\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, unsigned scid)\n : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),\n UseList(0), Name(0) {\n if (isa<CallInst>(this) || isa<InvokeInst>(this))\n assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||\n isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&\n \"invalid CallInst type!\");\n else if (!isa<Constant>(this) && !isa<BasicBlock>(this))\n assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||\n isa<OpaqueType>(ty)) &&\n \"Cannot create non-first-class values except for constants!\");\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as\n \/\/ a <badref>\n \/\/\n if (!use_empty()) {\n DOUT << \"While deleting: \" << *Ty << \" %\" << getNameStr() << \"\\n\";\n for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)\n DOUT << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(use_empty() && \"Uses remain when a value is destroyed!\");\n\n \/\/ If this value is named, destroy the name. This should not be in a symtab\n \/\/ at this point.\n if (Name)\n Name->Destroy();\n \n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\n\/\/\/ hasNUses - Return true if this Value has exactly N users.\n\/\/\/\nbool Value::hasNUses(unsigned N) const {\n use_const_iterator UI = use_begin(), E = use_end();\n\n for (; N; --N, ++UI)\n if (UI == E) return false; \/\/ Too few.\n return UI == E;\n}\n\n\/\/\/ hasNUsesOrMore - Return true if this value has N users or more. This is\n\/\/\/ logically equivalent to getNumUses() >= N.\n\/\/\/\nbool Value::hasNUsesOrMore(unsigned N) const {\n use_const_iterator UI = use_begin(), E = use_end();\n\n for (; N; --N, ++UI)\n if (UI == E) return false; \/\/ Too few.\n\n return true;\n}\n\n\n\/\/\/ getNumUses - This method computes the number of uses of this Value. This\n\/\/\/ is a linear time operation. Use hasOneUse or hasNUses to check for specific\n\/\/\/ values.\nunsigned Value::getNumUses() const {\n return (unsigned)std::distance(use_begin(), use_end());\n}\n\nstatic bool getSymTab(Value *V, ValueSymbolTable *&ST) {\n ST = 0;\n if (Instruction *I = dyn_cast<Instruction>(V)) {\n if (BasicBlock *P = I->getParent())\n if (Function *PP = P->getParent())\n ST = &PP->getValueSymbolTable();\n } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {\n if (Function *P = BB->getParent()) \n ST = &P->getValueSymbolTable();\n } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {\n if (Module *P = GV->getParent()) \n ST = &P->getValueSymbolTable();\n } else if (Argument *A = dyn_cast<Argument>(V)) {\n if (Function *P = A->getParent()) \n ST = &P->getValueSymbolTable();\n } else {\n assert(isa<Constant>(V) && \"Unknown value type!\");\n return true; \/\/ no name is setable for this.\n }\n return false;\n}\n\n\/\/\/ getNameStart - Return a pointer to a null terminated string for this name.\n\/\/\/ Note that names can have null characters within the string as well as at\n\/\/\/ their end. This always returns a non-null pointer.\nconst char *Value::getNameStart() const {\n if (Name == 0) return \"\";\n return Name->getKeyData();\n}\n\n\/\/\/ getNameLen - Return the length of the string, correctly handling nul\n\/\/\/ characters embedded into them.\nunsigned Value::getNameLen() const {\n return Name ? Name->getKeyLength() : 0;\n}\n\n\/\/\/ isName - Return true if this value has the name specified by the provided\n\/\/\/ nul terminated string.\nbool Value::isName(const char *N) const {\n unsigned InLen = strlen(N);\n return InLen = getNameLen() && memcmp(getNameStart(), N, InLen) == 0;\n}\n\n\nstd::string Value::getNameStr() const {\n if (Name == 0) return \"\";\n return std::string(Name->getKeyData(),\n Name->getKeyData()+Name->getKeyLength());\n}\n\nvoid Value::setName(const std::string &name) {\n setName(&name[0], name.size());\n}\n\nvoid Value::setName(const char *Name) {\n setName(Name, Name ? strlen(Name) : 0);\n}\n\nvoid Value::setName(const char *NameStr, unsigned NameLen) {\n if (NameLen == 0 && !hasName()) return;\n assert(getType() != Type::VoidTy && \"Cannot assign a name to void values!\");\n \n \/\/ Get the symbol table to update for this object.\n ValueSymbolTable *ST;\n if (getSymTab(this, ST))\n return; \/\/ Cannot set a name on this value (e.g. constant).\n\n if (!ST) { \/\/ No symbol table to update? Just do the change.\n if (NameLen == 0) {\n \/\/ Free the name for this value.\n Name->Destroy();\n Name = 0;\n return;\n }\n \n if (Name) {\n \/\/ Name isn't changing?\n if (NameLen == Name->getKeyLength() &&\n !memcmp(Name->getKeyData(), NameStr, NameLen))\n return;\n Name->Destroy();\n }\n \n \/\/ NOTE: Could optimize for the case the name is shrinking to not deallocate\n \/\/ then reallocated.\n \n \/\/ Create the new name.\n Name = ValueName::Create(NameStr, NameStr+NameLen);\n Name->setValue(this);\n return;\n }\n \n \/\/ NOTE: Could optimize for the case the name is shrinking to not deallocate\n \/\/ then reallocated.\n if (hasName()) {\n \/\/ Name isn't changing?\n if (NameLen == Name->getKeyLength() &&\n !memcmp(Name->getKeyData(), NameStr, NameLen))\n return;\n\n \/\/ Remove old name.\n ST->removeValueName(Name);\n Name->Destroy();\n Name = 0;\n\n if (NameLen == 0)\n return;\n }\n\n \/\/ Name is changing to something new.\n Name = ST->createValueName(NameStr, NameLen, this);\n}\n\n\n\/\/\/ takeName - transfer the name from V to this value, setting V's name to\n\/\/\/ empty. It is an error to call V->takeName(V). \nvoid Value::takeName(Value *V) {\n ValueSymbolTable *ST = 0;\n \/\/ If this value has a name, drop it.\n if (hasName()) {\n \/\/ Get the symtab this is in.\n if (getSymTab(this, ST)) {\n \/\/ We can't set a name on this value, but we need to clear V's name if\n \/\/ it has one.\n if (V->hasName()) V->setName(0, 0);\n return; \/\/ Cannot set a name on this value (e.g. constant).\n }\n \n \/\/ Remove old name.\n if (ST)\n ST->removeValueName(Name);\n Name->Destroy();\n Name = 0;\n } \n \n \/\/ Now we know that this has no name.\n \n \/\/ If V has no name either, we're done.\n if (!V->hasName()) return;\n \n \/\/ Get this's symtab if we didn't before.\n if (!ST) {\n if (getSymTab(this, ST)) {\n \/\/ Clear V's name.\n V->setName(0, 0);\n return; \/\/ Cannot set a name on this value (e.g. constant).\n }\n }\n \n \/\/ Get V's ST, this should always succed, because V has a name.\n ValueSymbolTable *VST;\n bool Failure = getSymTab(V, VST);\n assert(!Failure && \"V has a name, so it should have a ST!\");\n \n \/\/ If these values are both in the same symtab, we can do this very fast.\n \/\/ This works even if both values have no symtab yet.\n if (ST == VST) {\n \/\/ Take the name!\n Name = V->Name;\n V->Name = 0;\n Name->setValue(this);\n return;\n }\n \n \/\/ Otherwise, things are slightly more complex. Remove V's name from VST and\n \/\/ then reinsert it into ST.\n \n if (VST)\n VST->removeValueName(V->Name);\n Name = V->Name;\n V->Name = 0;\n Name->setValue(this);\n \n if (ST)\n ST->reinsertValue(this);\n}\n\n\n\/\/ uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,\n\/\/ except that it doesn't have all of the asserts. The asserts fail because we\n\/\/ are half-way done resolving types, which causes some types to exist as two\n\/\/ different Type*'s at the same time. This is a sledgehammer to work around\n\/\/ this problem.\n\/\/\nvoid Value::uncheckedReplaceAllUsesWith(Value *New) {\n while (!use_empty()) {\n Use &U = *UseList;\n \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n \/\/ constant because they are uniqued.\n if (Constant *C = dyn_cast<Constant>(U.getUser())) {\n if (!isa<GlobalValue>(C)) {\n C->replaceUsesOfWithOnConstant(this, New, &U);\n continue;\n }\n }\n \n U.set(New);\n }\n}\n\nvoid Value::replaceAllUsesWith(Value *New) {\n assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n assert(New->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n\n uncheckedReplaceAllUsesWith(New);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&\n \"Cannot call User::replaceUsesofWith on a constant!\");\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n\n<commit_msg>fix a bug in my previous patch, a classic =\/== bug.<commit_after>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constant.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ValueSymbolTable.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include <algorithm>\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, unsigned scid)\n : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),\n UseList(0), Name(0) {\n if (isa<CallInst>(this) || isa<InvokeInst>(this))\n assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||\n isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&\n \"invalid CallInst type!\");\n else if (!isa<Constant>(this) && !isa<BasicBlock>(this))\n assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||\n isa<OpaqueType>(ty)) &&\n \"Cannot create non-first-class values except for constants!\");\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as\n \/\/ a <badref>\n \/\/\n if (!use_empty()) {\n DOUT << \"While deleting: \" << *Ty << \" %\" << getNameStr() << \"\\n\";\n for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)\n DOUT << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(use_empty() && \"Uses remain when a value is destroyed!\");\n\n \/\/ If this value is named, destroy the name. This should not be in a symtab\n \/\/ at this point.\n if (Name)\n Name->Destroy();\n \n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\n\/\/\/ hasNUses - Return true if this Value has exactly N users.\n\/\/\/\nbool Value::hasNUses(unsigned N) const {\n use_const_iterator UI = use_begin(), E = use_end();\n\n for (; N; --N, ++UI)\n if (UI == E) return false; \/\/ Too few.\n return UI == E;\n}\n\n\/\/\/ hasNUsesOrMore - Return true if this value has N users or more. This is\n\/\/\/ logically equivalent to getNumUses() >= N.\n\/\/\/\nbool Value::hasNUsesOrMore(unsigned N) const {\n use_const_iterator UI = use_begin(), E = use_end();\n\n for (; N; --N, ++UI)\n if (UI == E) return false; \/\/ Too few.\n\n return true;\n}\n\n\n\/\/\/ getNumUses - This method computes the number of uses of this Value. This\n\/\/\/ is a linear time operation. Use hasOneUse or hasNUses to check for specific\n\/\/\/ values.\nunsigned Value::getNumUses() const {\n return (unsigned)std::distance(use_begin(), use_end());\n}\n\nstatic bool getSymTab(Value *V, ValueSymbolTable *&ST) {\n ST = 0;\n if (Instruction *I = dyn_cast<Instruction>(V)) {\n if (BasicBlock *P = I->getParent())\n if (Function *PP = P->getParent())\n ST = &PP->getValueSymbolTable();\n } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {\n if (Function *P = BB->getParent()) \n ST = &P->getValueSymbolTable();\n } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {\n if (Module *P = GV->getParent()) \n ST = &P->getValueSymbolTable();\n } else if (Argument *A = dyn_cast<Argument>(V)) {\n if (Function *P = A->getParent()) \n ST = &P->getValueSymbolTable();\n } else {\n assert(isa<Constant>(V) && \"Unknown value type!\");\n return true; \/\/ no name is setable for this.\n }\n return false;\n}\n\n\/\/\/ getNameStart - Return a pointer to a null terminated string for this name.\n\/\/\/ Note that names can have null characters within the string as well as at\n\/\/\/ their end. This always returns a non-null pointer.\nconst char *Value::getNameStart() const {\n if (Name == 0) return \"\";\n return Name->getKeyData();\n}\n\n\/\/\/ getNameLen - Return the length of the string, correctly handling nul\n\/\/\/ characters embedded into them.\nunsigned Value::getNameLen() const {\n return Name ? Name->getKeyLength() : 0;\n}\n\n\/\/\/ isName - Return true if this value has the name specified by the provided\n\/\/\/ nul terminated string.\nbool Value::isName(const char *N) const {\n unsigned InLen = strlen(N);\n return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;\n}\n\n\nstd::string Value::getNameStr() const {\n if (Name == 0) return \"\";\n return std::string(Name->getKeyData(),\n Name->getKeyData()+Name->getKeyLength());\n}\n\nvoid Value::setName(const std::string &name) {\n setName(&name[0], name.size());\n}\n\nvoid Value::setName(const char *Name) {\n setName(Name, Name ? strlen(Name) : 0);\n}\n\nvoid Value::setName(const char *NameStr, unsigned NameLen) {\n if (NameLen == 0 && !hasName()) return;\n assert(getType() != Type::VoidTy && \"Cannot assign a name to void values!\");\n \n \/\/ Get the symbol table to update for this object.\n ValueSymbolTable *ST;\n if (getSymTab(this, ST))\n return; \/\/ Cannot set a name on this value (e.g. constant).\n\n if (!ST) { \/\/ No symbol table to update? Just do the change.\n if (NameLen == 0) {\n \/\/ Free the name for this value.\n Name->Destroy();\n Name = 0;\n return;\n }\n \n if (Name) {\n \/\/ Name isn't changing?\n if (NameLen == Name->getKeyLength() &&\n !memcmp(Name->getKeyData(), NameStr, NameLen))\n return;\n Name->Destroy();\n }\n \n \/\/ NOTE: Could optimize for the case the name is shrinking to not deallocate\n \/\/ then reallocated.\n \n \/\/ Create the new name.\n Name = ValueName::Create(NameStr, NameStr+NameLen);\n Name->setValue(this);\n return;\n }\n \n \/\/ NOTE: Could optimize for the case the name is shrinking to not deallocate\n \/\/ then reallocated.\n if (hasName()) {\n \/\/ Name isn't changing?\n if (NameLen == Name->getKeyLength() &&\n !memcmp(Name->getKeyData(), NameStr, NameLen))\n return;\n\n \/\/ Remove old name.\n ST->removeValueName(Name);\n Name->Destroy();\n Name = 0;\n\n if (NameLen == 0)\n return;\n }\n\n \/\/ Name is changing to something new.\n Name = ST->createValueName(NameStr, NameLen, this);\n}\n\n\n\/\/\/ takeName - transfer the name from V to this value, setting V's name to\n\/\/\/ empty. It is an error to call V->takeName(V). \nvoid Value::takeName(Value *V) {\n ValueSymbolTable *ST = 0;\n \/\/ If this value has a name, drop it.\n if (hasName()) {\n \/\/ Get the symtab this is in.\n if (getSymTab(this, ST)) {\n \/\/ We can't set a name on this value, but we need to clear V's name if\n \/\/ it has one.\n if (V->hasName()) V->setName(0, 0);\n return; \/\/ Cannot set a name on this value (e.g. constant).\n }\n \n \/\/ Remove old name.\n if (ST)\n ST->removeValueName(Name);\n Name->Destroy();\n Name = 0;\n } \n \n \/\/ Now we know that this has no name.\n \n \/\/ If V has no name either, we're done.\n if (!V->hasName()) return;\n \n \/\/ Get this's symtab if we didn't before.\n if (!ST) {\n if (getSymTab(this, ST)) {\n \/\/ Clear V's name.\n V->setName(0, 0);\n return; \/\/ Cannot set a name on this value (e.g. constant).\n }\n }\n \n \/\/ Get V's ST, this should always succed, because V has a name.\n ValueSymbolTable *VST;\n bool Failure = getSymTab(V, VST);\n assert(!Failure && \"V has a name, so it should have a ST!\");\n \n \/\/ If these values are both in the same symtab, we can do this very fast.\n \/\/ This works even if both values have no symtab yet.\n if (ST == VST) {\n \/\/ Take the name!\n Name = V->Name;\n V->Name = 0;\n Name->setValue(this);\n return;\n }\n \n \/\/ Otherwise, things are slightly more complex. Remove V's name from VST and\n \/\/ then reinsert it into ST.\n \n if (VST)\n VST->removeValueName(V->Name);\n Name = V->Name;\n V->Name = 0;\n Name->setValue(this);\n \n if (ST)\n ST->reinsertValue(this);\n}\n\n\n\/\/ uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,\n\/\/ except that it doesn't have all of the asserts. The asserts fail because we\n\/\/ are half-way done resolving types, which causes some types to exist as two\n\/\/ different Type*'s at the same time. This is a sledgehammer to work around\n\/\/ this problem.\n\/\/\nvoid Value::uncheckedReplaceAllUsesWith(Value *New) {\n while (!use_empty()) {\n Use &U = *UseList;\n \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n \/\/ constant because they are uniqued.\n if (Constant *C = dyn_cast<Constant>(U.getUser())) {\n if (!isa<GlobalValue>(C)) {\n C->replaceUsesOfWithOnConstant(this, New, &U);\n continue;\n }\n }\n \n U.set(New);\n }\n}\n\nvoid Value::replaceAllUsesWith(Value *New) {\n assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n assert(New->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n\n uncheckedReplaceAllUsesWith(New);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&\n \"Cannot call User::replaceUsesofWith on a constant!\");\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2017 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"governance-validators.h\"\n\n#include \"base58.h\"\n#include \"utilstrencodings.h\"\n\n#include <algorithm>\n\nCProposalValidator::CProposalValidator(const std::string& strDataHexIn)\n : strData(),\n objJSON(UniValue::VOBJ),\n fJSONValid(false),\n strErrorMessages()\n{\n if(!strDataHexIn.empty()) {\n SetHexData(strDataHexIn);\n }\n}\n\nvoid CProposalValidator::Clear()\n{\n strData = std::string();\n objJSON = UniValue(UniValue::VOBJ);\n fJSONValid = false;\n strErrorMessages = std::string();\n}\n\nvoid CProposalValidator::SetHexData(const std::string& strDataHexIn)\n{\n std::vector<unsigned char> v = ParseHex(strDataHexIn);\n strData = std::string(v.begin(), v.end());\n ParseJSONData();\n}\n\nbool CProposalValidator::Validate()\n{\n if(!ValidateJSON()) {\n strErrorMessages += \"JSON parsing error;\";\n return false;\n }\n if(!ValidateName()) {\n strErrorMessages += \"Invalid name;\";\n return false;\n }\n if(!ValidateStartEndEpoch()) {\n strErrorMessages += \"Invalid start:end range;\";\n return false;\n }\n if(!ValidatePaymentAmount()) {\n strErrorMessages += \"Invalid payment amount;\";\n return false;\n }\n if(!ValidatePaymentAddress()) {\n strErrorMessages += \"Invalid payment address;\";\n return false;\n }\n if(!ValidateURL()) {\n strErrorMessages += \"Invalid URL;\";\n return false;\n }\n return true;\n}\n\nbool CProposalValidator::ValidateJSON()\n{\n return fJSONValid;\n}\n\nbool CProposalValidator::ValidateName()\n{\n std::string strName;\n if(!GetDataValue(\"name\", strName)) {\n strErrorMessages += \"name field not found;\";\n return false;\n }\n\n std::string strNameStripped = StripWhitespace(strName);\n\n if(strNameStripped.empty()) {\n strErrorMessages += \"name is empty;\";\n return false;\n }\n\n static const std::string strAllowedChars = \"-_abcdefghijklmnopqrstuvwxyz0123456789\";\n\n std::transform(strName.begin(), strName.end(), strName.begin(), ::tolower);\n\n if(strName.find_first_not_of(strAllowedChars) != std::string::npos) {\n strErrorMessages += \"name contains invalid characters;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateStartEndEpoch()\n{\n int64_t nStartEpoch = 0;\n int64_t nEndEpoch = 0;\n\n if(!GetDataValue(\"start_epoch\", nStartEpoch)) {\n strErrorMessages += \"start_epoch field not found;\";\n return false;\n }\n\n if(!GetDataValue(\"end_epoch\", nEndEpoch)) {\n strErrorMessages += \"end_epoch field not found;\";\n return false;\n }\n\n if(nEndEpoch <= nStartEpoch) {\n strErrorMessages += \"end_epoch <= start_epoch;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAmount()\n{\n double dValue = 0.0;\n\n if(!GetDataValue(\"payment_amount\", dValue)) {\n strErrorMessages += \"payment_amount field not found;\";\n return false;\n }\n\n if(dValue <= 0.0) {\n strErrorMessages += \"payment_amount is negative;\";\n return false;\n }\n\n \/\/ TODO: Should check for an amount which exceeds the budget but this is\n \/\/ currently difficult because start and end epochs are defined in terms of\n \/\/ clock time instead of block height.\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAddress()\n{\n std::string strPaymentAddress;\n\n if(!GetDataValue(\"payment_address\", strPaymentAddress)) {\n strErrorMessages += \"payment_address field not found;\";\n return false;\n }\n\n static const std::string base58chars = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n size_t nLength = strPaymentAddress.size();\n\n if((nLength < 26) || (nLength > 35)) {\n strErrorMessages += \"incorrect payment_address length;\";\n return false;\n }\n\n if(strPaymentAddress.find_first_not_of(base58chars) != std::string::npos) {\n strErrorMessages += \"payment_address contains invalid characters;\";\n return false;\n }\n\n CBitcoinAddress address(strPaymentAddress);\n if(!address.IsValid()) {\n strErrorMessages += \"payment_address is invalid;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateURL()\n{\n std::string strURL;\n if(!GetDataValue(\"url\", strURL)) {\n strErrorMessages += \"url field not found;\";\n return false;\n }\n\n std::string strURLStripped = StripWhitespace(strURL);\n\n if(strURLStripped.size() < 4U) {\n strErrorMessages += \"url too short;\";\n return false;\n }\n\n if(!CheckURL(strURL)) {\n strErrorMessages += \"url invalid;\";\n return false;\n }\n\n return true;\n}\n\nvoid CProposalValidator::ParseJSONData()\n{\n fJSONValid = false;\n\n if(strData.empty()) {\n return;\n }\n\n try {\n UniValue obj(UniValue::VOBJ);\n obj.read(strData);\n std::vector<UniValue> arr1 = obj.getValues();\n std::vector<UniValue> arr2 = arr1.at(0).getValues();\n objJSON = arr2.at(1);\n fJSONValid = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValue)\n{\n bool fOK = false;\n try {\n strValue = objJSON[strKey].get_str();\n fOK = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValue)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n nValue = uValue.get_int64();\n fOK = true;\n break;\n case UniValue::VSTR:\n {\n std::istringstream istr(uValue.get_str());\n istr >> nValue;\n fOK = ! istr.fail();\n }\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, double& dValue)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n dValue = uValue.get_real();\n fOK = true;\n break;\n case UniValue::VSTR:\n {\n std::istringstream istr(uValue.get_str());\n istr >> dValue;\n fOK = ! istr.fail();\n }\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nstd::string CProposalValidator::StripWhitespace(const std::string& strIn)\n{\n static const std::string strWhitespace = \" \\f\\n\\r\\t\\v\";\n\n std::string::size_type nStart = strIn.find_first_not_of(strWhitespace);\n std::string::size_type nEnd = strIn.find_last_not_of(strWhitespace);\n\n if((nStart == std::string::npos) || (nEnd == std::string::npos)) {\n return std::string();\n }\n\n return strIn.substr(nStart, nEnd - nStart + 1);\n}\n\n\/*\n The purpose of this function is to replicate the behavior of the\n Python urlparse function used by sentinel (urlparse.py). This function\n should return false whenever urlparse raises an exception and true\n otherwise.\n *\/\nbool CProposalValidator::CheckURL(const std::string& strURLIn)\n{\n std::string strRest(strURLIn);\n std::string::size_type nPos = strRest.find(':');\n\n if(nPos != std::string::npos) {\n \/\/std::string strSchema = strRest.substr(0,nPos);\n\n if(nPos < strRest.size()) {\n strRest = strRest.substr(nPos + 1);\n }\n else {\n strRest = \"\";\n }\n }\n\n \/\/ Process netloc\n if((strRest.size() > 2) && (strRest.substr(0,2) == \"\/\/\")) {\n static const std::string strNetlocDelimiters = \"\/?#\";\n\n strRest = strRest.substr(2);\n\n std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);\n\n std::string strNetloc = strRest.substr(0,nPos2);\n\n if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {\n return false;\n }\n\n if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {\n return false;\n }\n }\n\n return true;\n}\n<commit_msg>allow up to 40 chars in proposal name (#1693)<commit_after>\/\/ Copyright (c) 2014-2017 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"governance-validators.h\"\n\n#include \"base58.h\"\n#include \"utilstrencodings.h\"\n\n#include <algorithm>\n\nCProposalValidator::CProposalValidator(const std::string& strDataHexIn)\n : strData(),\n objJSON(UniValue::VOBJ),\n fJSONValid(false),\n strErrorMessages()\n{\n if(!strDataHexIn.empty()) {\n SetHexData(strDataHexIn);\n }\n}\n\nvoid CProposalValidator::Clear()\n{\n strData = std::string();\n objJSON = UniValue(UniValue::VOBJ);\n fJSONValid = false;\n strErrorMessages = std::string();\n}\n\nvoid CProposalValidator::SetHexData(const std::string& strDataHexIn)\n{\n std::vector<unsigned char> v = ParseHex(strDataHexIn);\n strData = std::string(v.begin(), v.end());\n ParseJSONData();\n}\n\nbool CProposalValidator::Validate()\n{\n if(!ValidateJSON()) {\n strErrorMessages += \"JSON parsing error;\";\n return false;\n }\n if(!ValidateName()) {\n strErrorMessages += \"Invalid name;\";\n return false;\n }\n if(!ValidateStartEndEpoch()) {\n strErrorMessages += \"Invalid start:end range;\";\n return false;\n }\n if(!ValidatePaymentAmount()) {\n strErrorMessages += \"Invalid payment amount;\";\n return false;\n }\n if(!ValidatePaymentAddress()) {\n strErrorMessages += \"Invalid payment address;\";\n return false;\n }\n if(!ValidateURL()) {\n strErrorMessages += \"Invalid URL;\";\n return false;\n }\n return true;\n}\n\nbool CProposalValidator::ValidateJSON()\n{\n return fJSONValid;\n}\n\nbool CProposalValidator::ValidateName()\n{\n std::string strName;\n if(!GetDataValue(\"name\", strName)) {\n strErrorMessages += \"name field not found;\";\n return false;\n }\n\n if(strName.size() > 40) {\n strErrorMessages += \"name exceeds 40 characters;\";\n return false;\n }\n\n std::string strNameStripped = StripWhitespace(strName);\n\n if(strNameStripped.empty()) {\n strErrorMessages += \"name is empty;\";\n return false;\n }\n\n static const std::string strAllowedChars = \"-_abcdefghijklmnopqrstuvwxyz0123456789\";\n\n std::transform(strName.begin(), strName.end(), strName.begin(), ::tolower);\n\n if(strName.find_first_not_of(strAllowedChars) != std::string::npos) {\n strErrorMessages += \"name contains invalid characters;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateStartEndEpoch()\n{\n int64_t nStartEpoch = 0;\n int64_t nEndEpoch = 0;\n\n if(!GetDataValue(\"start_epoch\", nStartEpoch)) {\n strErrorMessages += \"start_epoch field not found;\";\n return false;\n }\n\n if(!GetDataValue(\"end_epoch\", nEndEpoch)) {\n strErrorMessages += \"end_epoch field not found;\";\n return false;\n }\n\n if(nEndEpoch <= nStartEpoch) {\n strErrorMessages += \"end_epoch <= start_epoch;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAmount()\n{\n double dValue = 0.0;\n\n if(!GetDataValue(\"payment_amount\", dValue)) {\n strErrorMessages += \"payment_amount field not found;\";\n return false;\n }\n\n if(dValue <= 0.0) {\n strErrorMessages += \"payment_amount is negative;\";\n return false;\n }\n\n \/\/ TODO: Should check for an amount which exceeds the budget but this is\n \/\/ currently difficult because start and end epochs are defined in terms of\n \/\/ clock time instead of block height.\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAddress()\n{\n std::string strPaymentAddress;\n\n if(!GetDataValue(\"payment_address\", strPaymentAddress)) {\n strErrorMessages += \"payment_address field not found;\";\n return false;\n }\n\n static const std::string base58chars = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n size_t nLength = strPaymentAddress.size();\n\n if((nLength < 26) || (nLength > 35)) {\n strErrorMessages += \"incorrect payment_address length;\";\n return false;\n }\n\n if(strPaymentAddress.find_first_not_of(base58chars) != std::string::npos) {\n strErrorMessages += \"payment_address contains invalid characters;\";\n return false;\n }\n\n CBitcoinAddress address(strPaymentAddress);\n if(!address.IsValid()) {\n strErrorMessages += \"payment_address is invalid;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateURL()\n{\n std::string strURL;\n if(!GetDataValue(\"url\", strURL)) {\n strErrorMessages += \"url field not found;\";\n return false;\n }\n\n std::string strURLStripped = StripWhitespace(strURL);\n\n if(strURLStripped.size() < 4U) {\n strErrorMessages += \"url too short;\";\n return false;\n }\n\n if(!CheckURL(strURL)) {\n strErrorMessages += \"url invalid;\";\n return false;\n }\n\n return true;\n}\n\nvoid CProposalValidator::ParseJSONData()\n{\n fJSONValid = false;\n\n if(strData.empty()) {\n return;\n }\n\n try {\n UniValue obj(UniValue::VOBJ);\n obj.read(strData);\n std::vector<UniValue> arr1 = obj.getValues();\n std::vector<UniValue> arr2 = arr1.at(0).getValues();\n objJSON = arr2.at(1);\n fJSONValid = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValue)\n{\n bool fOK = false;\n try {\n strValue = objJSON[strKey].get_str();\n fOK = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValue)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n nValue = uValue.get_int64();\n fOK = true;\n break;\n case UniValue::VSTR:\n {\n std::istringstream istr(uValue.get_str());\n istr >> nValue;\n fOK = ! istr.fail();\n }\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, double& dValue)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n dValue = uValue.get_real();\n fOK = true;\n break;\n case UniValue::VSTR:\n {\n std::istringstream istr(uValue.get_str());\n istr >> dValue;\n fOK = ! istr.fail();\n }\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nstd::string CProposalValidator::StripWhitespace(const std::string& strIn)\n{\n static const std::string strWhitespace = \" \\f\\n\\r\\t\\v\";\n\n std::string::size_type nStart = strIn.find_first_not_of(strWhitespace);\n std::string::size_type nEnd = strIn.find_last_not_of(strWhitespace);\n\n if((nStart == std::string::npos) || (nEnd == std::string::npos)) {\n return std::string();\n }\n\n return strIn.substr(nStart, nEnd - nStart + 1);\n}\n\n\/*\n The purpose of this function is to replicate the behavior of the\n Python urlparse function used by sentinel (urlparse.py). This function\n should return false whenever urlparse raises an exception and true\n otherwise.\n *\/\nbool CProposalValidator::CheckURL(const std::string& strURLIn)\n{\n std::string strRest(strURLIn);\n std::string::size_type nPos = strRest.find(':');\n\n if(nPos != std::string::npos) {\n \/\/std::string strSchema = strRest.substr(0,nPos);\n\n if(nPos < strRest.size()) {\n strRest = strRest.substr(nPos + 1);\n }\n else {\n strRest = \"\";\n }\n }\n\n \/\/ Process netloc\n if((strRest.size() > 2) && (strRest.substr(0,2) == \"\/\/\")) {\n static const std::string strNetlocDelimiters = \"\/?#\";\n\n strRest = strRest.substr(2);\n\n std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);\n\n std::string strNetloc = strRest.substr(0,nPos2);\n\n if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {\n return false;\n }\n\n if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {\n return false;\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* X.509 Certificate Path Validation\n* (C) 2010,2011,2012,2014 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/x509path.h>\n#include <botan\/ocsp.h>\n#include <botan\/http_util.h>\n#include <botan\/parsing.h>\n#include <botan\/pubkey.h>\n#include <botan\/oids.h>\n#include <algorithm>\n#include <chrono>\n#include <vector>\n#include <set>\n\n#include <iostream>\n\nnamespace Botan {\n\nnamespace {\n\nconst X509_Certificate*\nfind_issuing_cert(const X509_Certificate& cert,\n Certificate_Store& end_certs,\n const std::vector<Certificate_Store*>& certstores)\n {\n const X509_DN issuer_dn = cert.issuer_dn();\n const std::vector<byte> auth_key_id = cert.authority_key_id();\n\n if(const X509_Certificate* c = end_certs.find_cert(issuer_dn, auth_key_id))\n return c;\n\n for(size_t i = 0; i != certstores.size(); ++i)\n {\n if(const X509_Certificate* c = certstores[i]->find_cert(issuer_dn, auth_key_id))\n return c;\n }\n\n return nullptr;\n }\n\nconst X509_CRL* find_crls_for(const X509_Certificate& cert,\n const std::vector<Certificate_Store*>& certstores)\n {\n for(size_t i = 0; i != certstores.size(); ++i)\n {\n if(const X509_CRL* crl = certstores[i]->find_crl_for(cert))\n return crl;\n }\n\n#if 0\n const std::string crl_url = cert.crl_distribution_point();\n if(crl_url != \"\")\n {\n std::cout << \"Downloading CRL \" << crl_url << \"\\n\";\n auto http = HTTP::GET_sync(crl_url);\n\n std::cout << http.status_message() << \"\\n\";\n\n http.throw_unless_ok();\n \/\/ check the mime type\n\n std::unique_ptr<X509_CRL> crl(new X509_CRL(http.body()));\n\n return crl.release();\n }\n#endif\n\n return nullptr;\n }\n\nstd::vector<std::set<Certificate_Status_Code>>\ncheck_chain(const std::vector<X509_Certificate>& cert_path,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n const std::set<std::string>& trusted_hashes = restrictions.trusted_hashes();\n\n const bool self_signed_ee_cert = (cert_path.size() == 1);\n\n X509_Time current_time(std::chrono::system_clock::now());\n\n std::vector<std::future<OCSP::Response>> ocsp_responses;\n\n std::vector<std::set<Certificate_Status_Code>> cert_status(cert_path.size());\n\n for(size_t i = 0; i != cert_path.size(); ++i)\n {\n std::set<Certificate_Status_Code>& status = cert_status.at(i);\n\n const bool at_self_signed_root = (i == cert_path.size() - 1);\n\n const X509_Certificate& subject = cert_path[i];\n\n const X509_Certificate& issuer = cert_path[at_self_signed_root ? (i) : (i + 1)];\n\n const Certificate_Store* trusted = certstores[0]; \/\/ fixme\n\n if(i == 0 || restrictions.ocsp_all_intermediates())\n ocsp_responses.push_back(\n std::async(std::launch::async,\n OCSP::online_check, issuer, subject, trusted));\n\n \/\/ Check all certs for valid time range\n if(current_time < X509_Time(subject.start_time()))\n status.insert(Certificate_Status_Code::CERT_NOT_YET_VALID);\n\n if(current_time > X509_Time(subject.end_time()))\n status.insert(Certificate_Status_Code::CERT_HAS_EXPIRED);\n\n \/\/ Check issuer constraints\n\n \/\/ Don't require CA bit set on self-signed end entity cert\n if(!issuer.is_CA_cert() && !self_signed_ee_cert)\n status.insert(Certificate_Status_Code::CA_CERT_NOT_FOR_CERT_ISSUER);\n\n if(issuer.path_limit() < i)\n status.insert(Certificate_Status_Code::CERT_CHAIN_TOO_LONG);\n\n std::unique_ptr<Public_Key> issuer_key(issuer.subject_public_key());\n\n if(subject.check_signature(*issuer_key) == false)\n status.insert(Certificate_Status_Code::SIGNATURE_ERROR);\n\n if(issuer_key->estimated_strength() < restrictions.minimum_key_strength())\n status.insert(Certificate_Status_Code::SIGNATURE_METHOD_TOO_WEAK);\n\n \/\/ Allow untrusted hashes on self-signed roots\n if(!trusted_hashes.empty() && !at_self_signed_root)\n {\n if(!trusted_hashes.count(subject.hash_used_for_signature()))\n status.insert(Certificate_Status_Code::UNTRUSTED_HASH);\n }\n }\n\n for(size_t i = 0; i != cert_path.size() - 1; ++i)\n {\n std::set<Certificate_Status_Code>& status = cert_status.at(i);\n\n const X509_Certificate& subject = cert_path.at(i);\n const X509_Certificate& ca = cert_path.at(i+1);\n\n if(i < ocsp_responses.size())\n {\n try\n {\n OCSP::Response ocsp = ocsp_responses[i].get();\n\n auto ocsp_status = ocsp.status_for(ca, subject);\n\n status.insert(ocsp_status);\n\n \/\/std::cout << \"OCSP status: \" << Path_Validation_Result::status_string(ocsp_status) << \"\\n\";\n\n \/\/ Either way we have a definitive answer, no need to check CRLs\n if(ocsp_status == Certificate_Status_Code::CERT_IS_REVOKED)\n return cert_status;\n else if(ocsp_status == Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n continue;\n }\n catch(std::exception& e)\n {\n \/\/std::cout << \"OCSP error: \" << e.what() << \"\\n\";\n }\n }\n\n const X509_CRL* crl_p = find_crls_for(subject, certstores);\n\n if(!crl_p)\n {\n if(restrictions.require_revocation_information())\n status.insert(Certificate_Status_Code::NO_REVOCATION_DATA);\n continue;\n }\n\n const X509_CRL& crl = *crl_p;\n\n if(!ca.allowed_usage(CRL_SIGN))\n status.insert(Certificate_Status_Code::CA_CERT_NOT_FOR_CRL_ISSUER);\n\n if(current_time < X509_Time(crl.this_update()))\n status.insert(Certificate_Status_Code::CRL_NOT_YET_VALID);\n\n if(current_time > X509_Time(crl.next_update()))\n status.insert(Certificate_Status_Code::CRL_HAS_EXPIRED);\n\n if(crl.check_signature(ca.subject_public_key()) == false)\n status.insert(Certificate_Status_Code::CRL_BAD_SIGNATURE);\n\n if(crl.is_revoked(subject))\n status.insert(Certificate_Status_Code::CERT_IS_REVOKED);\n }\n\n if(self_signed_ee_cert)\n cert_status.back().insert(Certificate_Status_Code::CANNOT_ESTABLISH_TRUST);\n\n return cert_status;\n }\n\n}\n\nPath_Validation_Result x509_path_validate(\n const std::vector<X509_Certificate>& end_certs,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n if(end_certs.empty())\n throw std::invalid_argument(\"x509_path_validate called with no subjects\");\n\n std::vector<X509_Certificate> cert_path;\n cert_path.push_back(end_certs[0]);\n\n Certificate_Store_Overlay extra(end_certs);\n\n \/\/ iterate until we reach a root or cannot find the issuer\n while(!cert_path.back().is_self_signed())\n {\n const X509_Certificate* cert = find_issuing_cert(cert_path.back(), extra, certstores);\n if(!cert)\n return Path_Validation_Result(Certificate_Status_Code::CERT_ISSUER_NOT_FOUND);\n\n cert_path.push_back(*cert);\n }\n\n return Path_Validation_Result(check_chain(cert_path, restrictions, certstores),\n std::move(cert_path));\n }\n\nPath_Validation_Result x509_path_validate(\n const X509_Certificate& end_cert,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n std::vector<X509_Certificate> certs;\n certs.push_back(end_cert);\n return x509_path_validate(certs, restrictions, certstores);\n }\n\nPath_Validation_Result x509_path_validate(\n const std::vector<X509_Certificate>& end_certs,\n const Path_Validation_Restrictions& restrictions,\n const Certificate_Store& store)\n {\n std::vector<Certificate_Store*> certstores;\n certstores.push_back(const_cast<Certificate_Store*>(&store));\n\n return x509_path_validate(end_certs, restrictions, certstores);\n }\n\nPath_Validation_Result x509_path_validate(\n const X509_Certificate& end_cert,\n const Path_Validation_Restrictions& restrictions,\n const Certificate_Store& store)\n {\n std::vector<X509_Certificate> certs;\n certs.push_back(end_cert);\n\n std::vector<Certificate_Store*> certstores;\n certstores.push_back(const_cast<Certificate_Store*>(&store));\n\n return x509_path_validate(certs, restrictions, certstores);\n }\n\nPath_Validation_Restrictions::Path_Validation_Restrictions(bool require_rev,\n size_t key_strength,\n bool ocsp_all) :\n m_require_revocation_information(require_rev),\n m_ocsp_all_intermediates(ocsp_all),\n m_minimum_key_strength(key_strength)\n {\n if(key_strength <= 80)\n m_trusted_hashes.insert(\"SHA-160\");\n\n m_trusted_hashes.insert(\"SHA-224\");\n m_trusted_hashes.insert(\"SHA-256\");\n m_trusted_hashes.insert(\"SHA-384\");\n m_trusted_hashes.insert(\"SHA-512\");\n }\n\nPath_Validation_Result::Path_Validation_Result(std::vector<std::set<Certificate_Status_Code>> status,\n std::vector<X509_Certificate>&& cert_chain) :\n m_overall(Certificate_Status_Code::VERIFIED),\n m_all_status(status),\n m_cert_path(cert_chain)\n {\n \/\/ take the \"worst\" error as overall\n for(const auto& s : m_all_status)\n {\n if(!s.empty())\n {\n auto worst = *s.rbegin();\n \/\/ Leave OCSP confirmations on cert-level status only\n if(worst != Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n m_overall = worst;\n }\n }\n }\n\nconst X509_Certificate& Path_Validation_Result::trust_root() const\n {\n return m_cert_path[m_cert_path.size()-1];\n }\n\nstd::set<std::string> Path_Validation_Result::trusted_hashes() const\n {\n std::set<std::string> hashes;\n for(size_t i = 0; i != m_cert_path.size(); ++i)\n hashes.insert(m_cert_path[i].hash_used_for_signature());\n return hashes;\n }\n\nbool Path_Validation_Result::successful_validation() const\n {\n if(result() == Certificate_Status_Code::VERIFIED ||\n result() == Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n return true;\n return false;\n }\n\nstd::string Path_Validation_Result::result_string() const\n {\n return status_string(result());\n }\n\nconst char* Path_Validation_Result::status_string(Certificate_Status_Code code)\n {\n switch(code)\n {\n case Certificate_Status_Code::VERIFIED:\n return \"Verified\";\n case Certificate_Status_Code::OCSP_RESPONSE_GOOD:\n return \"OCSP response good\";\n case Certificate_Status_Code::NO_REVOCATION_DATA:\n return \"No revocation data\";\n case Certificate_Status_Code::SIGNATURE_METHOD_TOO_WEAK:\n return \"Signature method too weak\";\n case Certificate_Status_Code::UNTRUSTED_HASH:\n return \"Untrusted hash\";\n\n case Certificate_Status_Code::CERT_NOT_YET_VALID:\n return \"Certificate is not yet valid\";\n case Certificate_Status_Code::CERT_HAS_EXPIRED:\n return \"Certificate has expired\";\n case Certificate_Status_Code::OCSP_NOT_YET_VALID:\n return \"OCSP is not yet valid\";\n case Certificate_Status_Code::OCSP_HAS_EXPIRED:\n return \"OCSP has expired\";\n case Certificate_Status_Code::CRL_NOT_YET_VALID:\n return \"CRL is not yet valid\";\n case Certificate_Status_Code::CRL_HAS_EXPIRED:\n return \"CRL has expired\";\n\n case Certificate_Status_Code::CERT_ISSUER_NOT_FOUND:\n return \"Certificate issuer not found\";\n case Certificate_Status_Code::CANNOT_ESTABLISH_TRUST:\n return \"Cannot establish trust\";\n\n case Certificate_Status_Code::POLICY_ERROR:\n return \"Policy error\";\n case Certificate_Status_Code::INVALID_USAGE:\n return \"Invalid usage\";\n case Certificate_Status_Code::CERT_CHAIN_TOO_LONG:\n return \"Certificate chain too long\";\n case Certificate_Status_Code::CA_CERT_NOT_FOR_CERT_ISSUER:\n return \"CA certificate not allowed to issue certs\";\n case Certificate_Status_Code::CA_CERT_NOT_FOR_CRL_ISSUER:\n return \"CA certificate not allowed to issue CRLs\";\n case Certificate_Status_Code::OCSP_CERT_NOT_LISTED:\n return \"OCSP cert not listed\";\n case Certificate_Status_Code::OCSP_BAD_STATUS:\n return \"OCSP bad status\";\n\n case Certificate_Status_Code::CERT_IS_REVOKED:\n return \"Certificate is revoked\";\n case Certificate_Status_Code::CRL_BAD_SIGNATURE:\n return \"CRL bad signature\";\n case Certificate_Status_Code::SIGNATURE_ERROR:\n return \"Signature error\";\n default:\n return \"Unknown error\";\n }\n }\n\n}\n<commit_msg>If no certificate stores at all are available skip OCSP checks<commit_after>\/*\n* X.509 Certificate Path Validation\n* (C) 2010,2011,2012,2014 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/x509path.h>\n#include <botan\/ocsp.h>\n#include <botan\/http_util.h>\n#include <botan\/parsing.h>\n#include <botan\/pubkey.h>\n#include <botan\/oids.h>\n#include <algorithm>\n#include <chrono>\n#include <vector>\n#include <set>\n\n#include <iostream>\n\nnamespace Botan {\n\nnamespace {\n\nconst X509_Certificate*\nfind_issuing_cert(const X509_Certificate& cert,\n Certificate_Store& end_certs,\n const std::vector<Certificate_Store*>& certstores)\n {\n const X509_DN issuer_dn = cert.issuer_dn();\n const std::vector<byte> auth_key_id = cert.authority_key_id();\n\n if(const X509_Certificate* c = end_certs.find_cert(issuer_dn, auth_key_id))\n return c;\n\n for(size_t i = 0; i != certstores.size(); ++i)\n {\n if(const X509_Certificate* c = certstores[i]->find_cert(issuer_dn, auth_key_id))\n return c;\n }\n\n return nullptr;\n }\n\nconst X509_CRL* find_crls_for(const X509_Certificate& cert,\n const std::vector<Certificate_Store*>& certstores)\n {\n for(size_t i = 0; i != certstores.size(); ++i)\n {\n if(const X509_CRL* crl = certstores[i]->find_crl_for(cert))\n return crl;\n }\n\n#if 0\n const std::string crl_url = cert.crl_distribution_point();\n if(crl_url != \"\")\n {\n std::cout << \"Downloading CRL \" << crl_url << \"\\n\";\n auto http = HTTP::GET_sync(crl_url);\n\n std::cout << http.status_message() << \"\\n\";\n\n http.throw_unless_ok();\n \/\/ check the mime type\n\n std::unique_ptr<X509_CRL> crl(new X509_CRL(http.body()));\n\n return crl.release();\n }\n#endif\n\n return nullptr;\n }\n\nstd::vector<std::set<Certificate_Status_Code>>\ncheck_chain(const std::vector<X509_Certificate>& cert_path,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n const std::set<std::string>& trusted_hashes = restrictions.trusted_hashes();\n\n const bool self_signed_ee_cert = (cert_path.size() == 1);\n\n X509_Time current_time(std::chrono::system_clock::now());\n\n std::vector<std::future<OCSP::Response>> ocsp_responses;\n\n std::vector<std::set<Certificate_Status_Code>> cert_status(cert_path.size());\n\n for(size_t i = 0; i != cert_path.size(); ++i)\n {\n std::set<Certificate_Status_Code>& status = cert_status.at(i);\n\n const bool at_self_signed_root = (i == cert_path.size() - 1);\n\n const X509_Certificate& subject = cert_path[i];\n\n const X509_Certificate& issuer = cert_path[at_self_signed_root ? (i) : (i + 1)];\n\n if(i == 0 || restrictions.ocsp_all_intermediates())\n {\n \/\/ certstore[0] is treated as trusted for OCSP (FIXME)\n if(certstores.size() > 1)\n ocsp_responses.push_back(\n std::async(std::launch::async,\n OCSP::online_check, issuer, subject, certstores[0]));\n }\n\n \/\/ Check all certs for valid time range\n if(current_time < X509_Time(subject.start_time()))\n status.insert(Certificate_Status_Code::CERT_NOT_YET_VALID);\n\n if(current_time > X509_Time(subject.end_time()))\n status.insert(Certificate_Status_Code::CERT_HAS_EXPIRED);\n\n \/\/ Check issuer constraints\n\n \/\/ Don't require CA bit set on self-signed end entity cert\n if(!issuer.is_CA_cert() && !self_signed_ee_cert)\n status.insert(Certificate_Status_Code::CA_CERT_NOT_FOR_CERT_ISSUER);\n\n if(issuer.path_limit() < i)\n status.insert(Certificate_Status_Code::CERT_CHAIN_TOO_LONG);\n\n std::unique_ptr<Public_Key> issuer_key(issuer.subject_public_key());\n\n if(subject.check_signature(*issuer_key) == false)\n status.insert(Certificate_Status_Code::SIGNATURE_ERROR);\n\n if(issuer_key->estimated_strength() < restrictions.minimum_key_strength())\n status.insert(Certificate_Status_Code::SIGNATURE_METHOD_TOO_WEAK);\n\n \/\/ Allow untrusted hashes on self-signed roots\n if(!trusted_hashes.empty() && !at_self_signed_root)\n {\n if(!trusted_hashes.count(subject.hash_used_for_signature()))\n status.insert(Certificate_Status_Code::UNTRUSTED_HASH);\n }\n }\n\n for(size_t i = 0; i != cert_path.size() - 1; ++i)\n {\n std::set<Certificate_Status_Code>& status = cert_status.at(i);\n\n const X509_Certificate& subject = cert_path.at(i);\n const X509_Certificate& ca = cert_path.at(i+1);\n\n if(i < ocsp_responses.size())\n {\n try\n {\n OCSP::Response ocsp = ocsp_responses[i].get();\n\n auto ocsp_status = ocsp.status_for(ca, subject);\n\n status.insert(ocsp_status);\n\n \/\/std::cout << \"OCSP status: \" << Path_Validation_Result::status_string(ocsp_status) << \"\\n\";\n\n \/\/ Either way we have a definitive answer, no need to check CRLs\n if(ocsp_status == Certificate_Status_Code::CERT_IS_REVOKED)\n return cert_status;\n else if(ocsp_status == Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n continue;\n }\n catch(std::exception& e)\n {\n \/\/std::cout << \"OCSP error: \" << e.what() << \"\\n\";\n }\n }\n\n const X509_CRL* crl_p = find_crls_for(subject, certstores);\n\n if(!crl_p)\n {\n if(restrictions.require_revocation_information())\n status.insert(Certificate_Status_Code::NO_REVOCATION_DATA);\n continue;\n }\n\n const X509_CRL& crl = *crl_p;\n\n if(!ca.allowed_usage(CRL_SIGN))\n status.insert(Certificate_Status_Code::CA_CERT_NOT_FOR_CRL_ISSUER);\n\n if(current_time < X509_Time(crl.this_update()))\n status.insert(Certificate_Status_Code::CRL_NOT_YET_VALID);\n\n if(current_time > X509_Time(crl.next_update()))\n status.insert(Certificate_Status_Code::CRL_HAS_EXPIRED);\n\n if(crl.check_signature(ca.subject_public_key()) == false)\n status.insert(Certificate_Status_Code::CRL_BAD_SIGNATURE);\n\n if(crl.is_revoked(subject))\n status.insert(Certificate_Status_Code::CERT_IS_REVOKED);\n }\n\n if(self_signed_ee_cert)\n cert_status.back().insert(Certificate_Status_Code::CANNOT_ESTABLISH_TRUST);\n\n return cert_status;\n }\n\n}\n\nPath_Validation_Result x509_path_validate(\n const std::vector<X509_Certificate>& end_certs,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n if(end_certs.empty())\n throw std::invalid_argument(\"x509_path_validate called with no subjects\");\n\n std::vector<X509_Certificate> cert_path;\n cert_path.push_back(end_certs[0]);\n\n Certificate_Store_Overlay extra(end_certs);\n\n \/\/ iterate until we reach a root or cannot find the issuer\n while(!cert_path.back().is_self_signed())\n {\n const X509_Certificate* cert = find_issuing_cert(cert_path.back(), extra, certstores);\n if(!cert)\n return Path_Validation_Result(Certificate_Status_Code::CERT_ISSUER_NOT_FOUND);\n\n cert_path.push_back(*cert);\n }\n\n return Path_Validation_Result(check_chain(cert_path, restrictions, certstores),\n std::move(cert_path));\n }\n\nPath_Validation_Result x509_path_validate(\n const X509_Certificate& end_cert,\n const Path_Validation_Restrictions& restrictions,\n const std::vector<Certificate_Store*>& certstores)\n {\n std::vector<X509_Certificate> certs;\n certs.push_back(end_cert);\n return x509_path_validate(certs, restrictions, certstores);\n }\n\nPath_Validation_Result x509_path_validate(\n const std::vector<X509_Certificate>& end_certs,\n const Path_Validation_Restrictions& restrictions,\n const Certificate_Store& store)\n {\n std::vector<Certificate_Store*> certstores;\n certstores.push_back(const_cast<Certificate_Store*>(&store));\n\n return x509_path_validate(end_certs, restrictions, certstores);\n }\n\nPath_Validation_Result x509_path_validate(\n const X509_Certificate& end_cert,\n const Path_Validation_Restrictions& restrictions,\n const Certificate_Store& store)\n {\n std::vector<X509_Certificate> certs;\n certs.push_back(end_cert);\n\n std::vector<Certificate_Store*> certstores;\n certstores.push_back(const_cast<Certificate_Store*>(&store));\n\n return x509_path_validate(certs, restrictions, certstores);\n }\n\nPath_Validation_Restrictions::Path_Validation_Restrictions(bool require_rev,\n size_t key_strength,\n bool ocsp_all) :\n m_require_revocation_information(require_rev),\n m_ocsp_all_intermediates(ocsp_all),\n m_minimum_key_strength(key_strength)\n {\n if(key_strength <= 80)\n m_trusted_hashes.insert(\"SHA-160\");\n\n m_trusted_hashes.insert(\"SHA-224\");\n m_trusted_hashes.insert(\"SHA-256\");\n m_trusted_hashes.insert(\"SHA-384\");\n m_trusted_hashes.insert(\"SHA-512\");\n }\n\nPath_Validation_Result::Path_Validation_Result(std::vector<std::set<Certificate_Status_Code>> status,\n std::vector<X509_Certificate>&& cert_chain) :\n m_overall(Certificate_Status_Code::VERIFIED),\n m_all_status(status),\n m_cert_path(cert_chain)\n {\n \/\/ take the \"worst\" error as overall\n for(const auto& s : m_all_status)\n {\n if(!s.empty())\n {\n auto worst = *s.rbegin();\n \/\/ Leave OCSP confirmations on cert-level status only\n if(worst != Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n m_overall = worst;\n }\n }\n }\n\nconst X509_Certificate& Path_Validation_Result::trust_root() const\n {\n return m_cert_path[m_cert_path.size()-1];\n }\n\nstd::set<std::string> Path_Validation_Result::trusted_hashes() const\n {\n std::set<std::string> hashes;\n for(size_t i = 0; i != m_cert_path.size(); ++i)\n hashes.insert(m_cert_path[i].hash_used_for_signature());\n return hashes;\n }\n\nbool Path_Validation_Result::successful_validation() const\n {\n if(result() == Certificate_Status_Code::VERIFIED ||\n result() == Certificate_Status_Code::OCSP_RESPONSE_GOOD)\n return true;\n return false;\n }\n\nstd::string Path_Validation_Result::result_string() const\n {\n return status_string(result());\n }\n\nconst char* Path_Validation_Result::status_string(Certificate_Status_Code code)\n {\n switch(code)\n {\n case Certificate_Status_Code::VERIFIED:\n return \"Verified\";\n case Certificate_Status_Code::OCSP_RESPONSE_GOOD:\n return \"OCSP response good\";\n case Certificate_Status_Code::NO_REVOCATION_DATA:\n return \"No revocation data\";\n case Certificate_Status_Code::SIGNATURE_METHOD_TOO_WEAK:\n return \"Signature method too weak\";\n case Certificate_Status_Code::UNTRUSTED_HASH:\n return \"Untrusted hash\";\n\n case Certificate_Status_Code::CERT_NOT_YET_VALID:\n return \"Certificate is not yet valid\";\n case Certificate_Status_Code::CERT_HAS_EXPIRED:\n return \"Certificate has expired\";\n case Certificate_Status_Code::OCSP_NOT_YET_VALID:\n return \"OCSP is not yet valid\";\n case Certificate_Status_Code::OCSP_HAS_EXPIRED:\n return \"OCSP has expired\";\n case Certificate_Status_Code::CRL_NOT_YET_VALID:\n return \"CRL is not yet valid\";\n case Certificate_Status_Code::CRL_HAS_EXPIRED:\n return \"CRL has expired\";\n\n case Certificate_Status_Code::CERT_ISSUER_NOT_FOUND:\n return \"Certificate issuer not found\";\n case Certificate_Status_Code::CANNOT_ESTABLISH_TRUST:\n return \"Cannot establish trust\";\n\n case Certificate_Status_Code::POLICY_ERROR:\n return \"Policy error\";\n case Certificate_Status_Code::INVALID_USAGE:\n return \"Invalid usage\";\n case Certificate_Status_Code::CERT_CHAIN_TOO_LONG:\n return \"Certificate chain too long\";\n case Certificate_Status_Code::CA_CERT_NOT_FOR_CERT_ISSUER:\n return \"CA certificate not allowed to issue certs\";\n case Certificate_Status_Code::CA_CERT_NOT_FOR_CRL_ISSUER:\n return \"CA certificate not allowed to issue CRLs\";\n case Certificate_Status_Code::OCSP_CERT_NOT_LISTED:\n return \"OCSP cert not listed\";\n case Certificate_Status_Code::OCSP_BAD_STATUS:\n return \"OCSP bad status\";\n\n case Certificate_Status_Code::CERT_IS_REVOKED:\n return \"Certificate is revoked\";\n case Certificate_Status_Code::CRL_BAD_SIGNATURE:\n return \"CRL bad signature\";\n case Certificate_Status_Code::SIGNATURE_ERROR:\n return \"Signature error\";\n default:\n return \"Unknown error\";\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/utils\/exc_check.h\"\n\nusing namespace std;\n\n\nvoid\nDoOutput(FILE * in, FILE * out)\n{\n int len(0);\n unique_ptr<char> buffer;\n\n size_t n = ::fread(&len, sizeof(len), 1, in);\n ExcCheckNotEqual(n, 0, \"sizeof(len) must be 4\");\n\n buffer.reset(new char[len + 1]);\n n = ::fread(buffer.get(), sizeof(char), len, in);\n ExcCheckNotEqual(n, 0, \"received 0 bytes\");\n\n buffer.get()[len] = 0;\n\n \/\/ ::fprintf(stderr, \"helper output: %s\\n\", buffer);\n\n ::fprintf(out, \"%s\\n\", buffer.get());\n ::fflush(out);\n}\n\nvoid\nDoSleep(FILE * in)\n{\n char delay_buf[5]; \/* in .1 secs units *\/\n delay_buf[4] = 0;\n\n size_t r = ::fread(&delay_buf, 1, 4, in);\n if (r != 4) {\n throw ML::Exception(\"wrong delay: \" + to_string(r));\n }\n\n long delay = ::strtol(delay_buf, NULL, 16);\n ML::sleep(delay * 0.1);\n}\n\nvoid\nDoExit(FILE * in)\n{\n int code;\n\n size_t n = ::fread(&code, sizeof(code), 1, in);\n ExcCheckNotEqual(n, 0, \"no exit code received\");\n\n printf(\"helper: exit with code %d\\n\", code);\n\n exit(code);\n}\n\nint main(int argc, char *argv[])\n{\n \/** commands:\n err\/out|bytes8|nstring\n xit|code(int)\n abt\n *\/\n\n printf(\"helper: ready\\n\");\n fflush(stdout);\n\n while (1) {\n char command[3];\n size_t n = ::fread(command, 1, sizeof(command), stdin);\n if (n < 3) {\n if (::feof(stdin)) {\n break;\n }\n }\n if (n == 0) {\n continue;\n }\n \n if (::strncmp(command, \"err\", 3) == 0) {\n DoOutput(stdin, stderr);\n }\n else if (::strncmp(command, \"out\", 3) == 0) {\n DoOutput(stdin, stdout);\n }\n else if (::strncmp(command, \"slp\", 3) == 0) {\n DoSleep(stdin);\n }\n else if (::strncmp(command, \"xit\", 3) == 0) {\n DoExit(stdin);\n }\n else if (::strncmp(command, \"abt\", 3) == 0) {\n ::abort();\n }\n }\n\n return 0;\n}\n<commit_msg>runner test: include <memory> for unique_ptr<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <memory>\n#include <string>\n\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/utils\/exc_check.h\"\n\nusing namespace std;\n\n\nvoid\nDoOutput(FILE * in, FILE * out)\n{\n int len(0);\n unique_ptr<char> buffer;\n\n size_t n = ::fread(&len, sizeof(len), 1, in);\n ExcCheckNotEqual(n, 0, \"sizeof(len) must be 4\");\n\n buffer.reset(new char[len + 1]);\n n = ::fread(buffer.get(), sizeof(char), len, in);\n ExcCheckNotEqual(n, 0, \"received 0 bytes\");\n\n buffer.get()[len] = 0;\n\n \/\/ ::fprintf(stderr, \"helper output: %s\\n\", buffer);\n\n ::fprintf(out, \"%s\\n\", buffer.get());\n ::fflush(out);\n}\n\nvoid\nDoSleep(FILE * in)\n{\n char delay_buf[5]; \/* in .1 secs units *\/\n delay_buf[4] = 0;\n\n size_t r = ::fread(&delay_buf, 1, 4, in);\n if (r != 4) {\n throw ML::Exception(\"wrong delay: \" + to_string(r));\n }\n\n long delay = ::strtol(delay_buf, NULL, 16);\n ML::sleep(delay * 0.1);\n}\n\nvoid\nDoExit(FILE * in)\n{\n int code;\n\n size_t n = ::fread(&code, sizeof(code), 1, in);\n ExcCheckNotEqual(n, 0, \"no exit code received\");\n\n printf(\"helper: exit with code %d\\n\", code);\n\n exit(code);\n}\n\nint main(int argc, char *argv[])\n{\n \/** commands:\n err\/out|bytes8|nstring\n xit|code(int)\n abt\n *\/\n\n printf(\"helper: ready\\n\");\n fflush(stdout);\n\n while (1) {\n char command[3];\n size_t n = ::fread(command, 1, sizeof(command), stdin);\n if (n < 3) {\n if (::feof(stdin)) {\n break;\n }\n }\n if (n == 0) {\n continue;\n }\n \n if (::strncmp(command, \"err\", 3) == 0) {\n DoOutput(stdin, stderr);\n }\n else if (::strncmp(command, \"out\", 3) == 0) {\n DoOutput(stdin, stdout);\n }\n else if (::strncmp(command, \"slp\", 3) == 0) {\n DoSleep(stdin);\n }\n else if (::strncmp(command, \"xit\", 3) == 0) {\n DoExit(stdin);\n }\n else if (::strncmp(command, \"abt\", 3) == 0) {\n ::abort();\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2021 Google LLC\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkMath.h\"\n#include \"src\/gpu\/GrSubRunAllocator.h\"\n\n#include <cstddef>\n#include <memory>\n#include <new>\n\n\/\/ -- GrBagOfBytes ---------------------------------------------------------------------------------\nGrBagOfBytes::GrBagOfBytes(char* bytes, size_t size, size_t firstHeapAllocation)\n : fFibProgression(size, firstHeapAllocation) {\n SkASSERT_RELEASE(size < kMaxByteSize);\n SkASSERT_RELEASE(firstHeapAllocation < kMaxByteSize);\n\n std::size_t space = size;\n void* ptr = bytes;\n if (bytes && std::align(kMaxAlignment, sizeof(Block), ptr, space)) {\n this->setupBytesAndCapacity(bytes, size);\n new (fEndByte) Block(nullptr, nullptr);\n }\n}\n\nGrBagOfBytes::GrBagOfBytes(size_t firstHeapAllocation)\n : GrBagOfBytes(nullptr, 0, firstHeapAllocation) {}\n\nGrBagOfBytes::~GrBagOfBytes() {\n Block* cursor = reinterpret_cast<Block*>(fEndByte);\n while (cursor != nullptr) {\n char* toDelete = cursor->fBlockStart;\n cursor = cursor->fPrevious;\n delete [] toDelete;\n }\n}\n\nGrBagOfBytes::Block::Block(char* previous, char* startOfBlock)\n : fBlockStart{startOfBlock}\n , fPrevious{reinterpret_cast<Block*>(previous)} {}\n\nvoid* GrBagOfBytes::alignedBytes(int size, int alignment) {\n SkASSERT_RELEASE(0 < size && size < kMaxByteSize);\n SkASSERT_RELEASE(0 < alignment && alignment <= kMaxAlignment);\n SkASSERT_RELEASE(SkIsPow2(alignment));\n\n return this->allocateBytes(size, alignment);\n}\n\nvoid GrBagOfBytes::setupBytesAndCapacity(char* bytes, int size) {\n \/\/ endByte must be aligned to the maximum alignment to allow tracking alignment using capacity;\n \/\/ capacity and endByte are both aligned to max alignment.\n intptr_t endByte = reinterpret_cast<intptr_t>(bytes + size - sizeof(Block)) & -kMaxAlignment;\n fEndByte = reinterpret_cast<char*>(endByte);\n fCapacity = fEndByte - bytes;\n}\n\nvoid GrBagOfBytes::needMoreBytes(int requestedSize, int alignment) {\n int nextBlockSize = fFibProgression.nextBlockSize();\n const int size = PlatformMinimumSizeWithOverhead(\n std::max(requestedSize, nextBlockSize), kAllocationAlignment);\n char* const bytes = new char[size];\n \/\/ fEndByte is changed by setupBytesAndCapacity. Remember it to link back to.\n char* const previousBlock = fEndByte;\n this->setupBytesAndCapacity(bytes, size);\n\n \/\/ Make a block to delete these bytes, and points to the previous block.\n new (fEndByte) Block{previousBlock, bytes};\n\n \/\/ Make fCapacity the alignment for the requested object.\n fCapacity = fCapacity & -alignment;\n SkASSERT(fCapacity >= requestedSize);\n}\n\n\/\/ -- GrSubRunAllocator ----------------------------------------------------------------------------\nGrSubRunAllocator::GrSubRunAllocator(char* bytes, int size, int firstHeapAllocation)\n : fAlloc{bytes, SkTo<size_t>(size), SkTo<size_t>(firstHeapAllocation)} {}\n\nGrSubRunAllocator::GrSubRunAllocator(int firstHeapAllocation)\n : GrSubRunAllocator(nullptr, 0, firstHeapAllocation) {}\n\nvoid* GrSubRunAllocator::alignedBytes(int unsafeSize, int unsafeAlignment) {\n return fAlloc.alignedBytes(unsafeSize, unsafeAlignment);\n}\n<commit_msg>fail on bad size or firstHeapAllocation creating GrSubRunAllocator<commit_after>\/*\n * Copyright 2021 Google LLC\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkMath.h\"\n#include \"src\/gpu\/GrSubRunAllocator.h\"\n\n#include <cstddef>\n#include <memory>\n#include <new>\n\n\/\/ -- GrBagOfBytes ---------------------------------------------------------------------------------\nGrBagOfBytes::GrBagOfBytes(char* bytes, size_t size, size_t firstHeapAllocation)\n : fFibProgression(size, firstHeapAllocation) {\n SkASSERT_RELEASE(size < kMaxByteSize);\n SkASSERT_RELEASE(firstHeapAllocation < kMaxByteSize);\n\n std::size_t space = size;\n void* ptr = bytes;\n if (bytes && std::align(kMaxAlignment, sizeof(Block), ptr, space)) {\n this->setupBytesAndCapacity(bytes, size);\n new (fEndByte) Block(nullptr, nullptr);\n }\n}\n\nGrBagOfBytes::GrBagOfBytes(size_t firstHeapAllocation)\n : GrBagOfBytes(nullptr, 0, firstHeapAllocation) {}\n\nGrBagOfBytes::~GrBagOfBytes() {\n Block* cursor = reinterpret_cast<Block*>(fEndByte);\n while (cursor != nullptr) {\n char* toDelete = cursor->fBlockStart;\n cursor = cursor->fPrevious;\n delete [] toDelete;\n }\n}\n\nGrBagOfBytes::Block::Block(char* previous, char* startOfBlock)\n : fBlockStart{startOfBlock}\n , fPrevious{reinterpret_cast<Block*>(previous)} {}\n\nvoid* GrBagOfBytes::alignedBytes(int size, int alignment) {\n SkASSERT_RELEASE(0 < size && size < kMaxByteSize);\n SkASSERT_RELEASE(0 < alignment && alignment <= kMaxAlignment);\n SkASSERT_RELEASE(SkIsPow2(alignment));\n\n return this->allocateBytes(size, alignment);\n}\n\nvoid GrBagOfBytes::setupBytesAndCapacity(char* bytes, int size) {\n \/\/ endByte must be aligned to the maximum alignment to allow tracking alignment using capacity;\n \/\/ capacity and endByte are both aligned to max alignment.\n intptr_t endByte = reinterpret_cast<intptr_t>(bytes + size - sizeof(Block)) & -kMaxAlignment;\n fEndByte = reinterpret_cast<char*>(endByte);\n fCapacity = fEndByte - bytes;\n}\n\nvoid GrBagOfBytes::needMoreBytes(int requestedSize, int alignment) {\n int nextBlockSize = fFibProgression.nextBlockSize();\n const int size = PlatformMinimumSizeWithOverhead(\n std::max(requestedSize, nextBlockSize), kAllocationAlignment);\n char* const bytes = new char[size];\n \/\/ fEndByte is changed by setupBytesAndCapacity. Remember it to link back to.\n char* const previousBlock = fEndByte;\n this->setupBytesAndCapacity(bytes, size);\n\n \/\/ Make a block to delete these bytes, and points to the previous block.\n new (fEndByte) Block{previousBlock, bytes};\n\n \/\/ Make fCapacity the alignment for the requested object.\n fCapacity = fCapacity & -alignment;\n SkASSERT(fCapacity >= requestedSize);\n}\n\n\/\/ -- GrSubRunAllocator ----------------------------------------------------------------------------\nGrSubRunAllocator::GrSubRunAllocator(char* bytes, int size, int firstHeapAllocation)\n : fAlloc{bytes, SkTo<size_t>(size), SkTo<size_t>(firstHeapAllocation)} {\n SkASSERT_RELEASE(SkTFitsIn<size_t>(size));\n SkASSERT_RELEASE(SkTFitsIn<size_t>(firstHeapAllocation));\n}\n\nGrSubRunAllocator::GrSubRunAllocator(int firstHeapAllocation)\n : GrSubRunAllocator(nullptr, 0, firstHeapAllocation) { }\n\nvoid* GrSubRunAllocator::alignedBytes(int unsafeSize, int unsafeAlignment) {\n return fAlloc.alignedBytes(unsafeSize, unsafeAlignment);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Please refer to license.txt *\/\n\n#include \"window.hpp\"\n\n#include \"..\/2d\/2d.hpp\"\n\n#include <iostream>\n\nnamespace GEngine\n{\n\nnamespace mgfx\n{\n\nWindow::Window()\n{\n\twidth = nullptr;\n\theight = nullptr;\n\tdelete_width = false;\n\tdelete_height = false;\n\n\tfullscreen = false;\n\n\twindowname = \"\";\n\n\twindow2d = nullptr;\n\tevent = nullptr;\n\n\tclosed = true;\n\n\tfocus = true;\n}\n\nWindow::~Window()\n{\n\tif (width) \/\/If the width exists.\n\t{\n\t\tif (delete_width) \/\/If it should be deleted.\n\t\t{\n\t\t\tdelete width; \/\/Delete it.\n\t\t\twidth = nullptr; \/\/Reset it.\n\t\t}\n\t\telse\n\t\t{\n\t\t\twidth = nullptr; \/\/Don't delete it, simply reset it.\n\t\t}\n\t}\n\n\tif (height) \/\/If the height exists.\n\t{\n\t\tif (delete_height) \/\/Delete it.\n\t\t{\n\t\t\tdelete height; \/\/Delete it.\n\t\t\theight = nullptr; \/\/Reset it.\n\t\t}\n\t\telse\n\t\t{\n\t\t\theight = nullptr; \/\/Don't delete it, only reset it.\n\t\t}\n\t}\n\n\tif (window2d) \/\/If the 2d window exists.\n\t{\n\t\twindow2d->close(); \/\/Close the window.\n\t\tdelete window2d; \/\/Delete the window.\n\t\twindow2d = nullptr; \/\/Reset it.\n\t}\n\n\tif (event) \/\/If the event exists.\n\t{\n\t\tdelete event; \/\/Delete it.\n\t\tevent = nullptr; \/\/Set to null.\n\t}\n}\n\nbool Window::create(int _width, int _height, bool _fullscreen, std::string _windowname, bool use_opengl)\n{\n\tif (width) \/\/Delete the width if it exists.\n\t{\n\t\tdelete width;\n\t}\n\twidth = new int; \/\/Allocate memory for the width.\n\tdelete_width = true; \/\/The width is to be deleted.\n\t*width = _width; \/\/Store the width.\n\n\tif (height) \/\/Delete the height if it exists.\n\t{\n\t\tdelete height;\n\t}\n\theight = new int; \/\/Allocate memory for the height.\n\tdelete_height = true; \/\/The height is to be deleted.\n\t*height = _height; \/\/Store the height.\n\n\tfullscreen = _fullscreen; \/\/Store the fullscreen state.\n\n\twindowname = _windowname; \/\/Store the window name.\n\n\t\/\/TODO: Point the width and the height to the SFML window's width and height? Don't know if that's possible.\n\twindow2d = new sf::RenderWindow; \/\/Create a new (2d) window.\n\n\tif(fullscreen) \/\/If it is to be fullscreen, do it.\n\t{\n\t\twindow2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Fullscreen); \/\/Make the window fullscreen.\n\t}\n\telse\n\t{\n\t\twindow2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Default); \/\/Nope, just a normal window.\n\t}\n\n\tclosed = false; \/\/Not closed.\n\n\tif (event) \/\/If it already exists.\n\t{\n\t\tdelete event; \/\/Delete it.\n\t}\n\tevent = new sf::Event; \/\/Allocate memory for it.\n\n\t\/\/TODO: Error checking?\n\n\treturn true; \/\/Success.\n}\n\nvoid Window::update()\n{\n\tevents.clear(); \/\/Reset all events.\n\n\tif (!closed && window2d && event) \/\/If the window is open, the window exists, and event exists.\n\t{\n\t\twhile (window2d->pollEvent(*event)) \/\/Poll events. \/\/TODO: Give access to these events to the game.\n\t\t{\n\t\t\tif (event->type == sf::Event::Closed) \/\/Check if the event is a window close.\n\t\t\t{\n\t\t\t\twindow2d->close(); \/\/Close the window.\n\t\t\t\tclosed = true; \/\/Update that it's closed.\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::Resized && !closed && window2d) \/\/Window resized.\n\t\t\t{\n\t\t\t\twindow2d->setView(sf::View(sf::FloatRect(0, 0, event->size.width, event->size.height)));\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::LostFocus)\n\t\t\t{\n\t\t\t\tfocus = false; \/\/Lost focus.\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::GainedFocus)\n\t\t\t{\n\t\t\t\tfocus = true; \/\/Gained focus.\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tevents.push_back(*event); \/\/Save the event for later processing.\n\t\t\t}\n\t\t}\n\n\t\tif (!closed && window2d) \/\/If the window was not closed.\n\t\t{\n\t\t\twindow2d->display(); \/\/Display the window.\n\t\t\twindow2d->clear();\n\t\t}\n\t}\n}\n\nint Window::getWidth()\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nNo 2d window, fool.\\n\";\n\t\treturn -1;\n\t}\n\n\tif (!width || !delete_width) \/\/If width does not exist or if it should not be deleted (meaning it's pointing to some other int).\n\t{\n\t\twidth = new int; \/\/Allocate it.\n\t\tdelete_width = true; \/\/It will be deleted.\n\t}\n\n\tsf::Vector2u vector = window2d->getSize(); \/\/Get the size.\n\n\t*width = vector.x; \/\/Set\/update the width.\n\n\treturn *width; \/\/Return the width.\n}\n\nint Window::getHeight()\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nNo, seriously, there is no 2d window! Why don't you understand?\\n\";\n\t\treturn -1;\n\t}\n\n\tif (!height || !delete_height) \/\/If height does not exist or if it should not be deleted (meaning it's pointing to some other int).\n\t{\n\t\theight = new int; \/\/Allocate it.\n\t\tdelete_height = true; \/\/It will be deleted.\n\t}\n\n\tsf::Vector2u vector = window2d->getSize(); \/\/Get the size of the window.\n\n\t*height = vector.y; \/\/Set\/update the height.\n\n\treturn *height; \/\/Return the height.\n}\n\nint Window::getX()\n{\n\treturn window2d->getPosition().x;\n\t\/\/return (using_opengl) ? \/*3d*\/window3d->getPosition().x \/*window*\/ : \/*2d*\/ window2d->getPosition().x \/*window*\/;\n}\n\nint Window::getY()\n{\n\treturn window2d->getPosition().y;\n\t\/\/return (using_opengl) ? \/*3d*\/window3d->getPosition().y \/*window*\/ : \/*2d*\/ window2d->getPosition().y \/*window*\/;\n}\n\nvoid Window::drawSprite(mgfx::d2d::Sprite &sprite)\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nAnd just what are you trying to achieve with a window that does not exist?\\n\";\n\t\treturn;\n\t}\n\n\twindow2d->draw(*sprite.sprite); \/\/Draw the sprite.\n}\n\nvoid Window::renderText(std::string text, int _x, int _y, int font_size, sf::Font &font)\n{\n\tsf::Text _text(text, font);\n\t_text.setCharacterSize(font_size);\n\t_text.setPosition(_x, _y);\n\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nAnd just what are you trying to achieve with a 2D window that does not exist?\\n\";\n\t\treturn;\n\t}\n\twindow2d->draw(_text);\n}\n\nvoid Window::setFramerateLimit(int fps)\n{\n\t\/\/Set the frames per second rate for the window.\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"I can't set the framerate limit -- window2d doesn't exist!\\n\"; \/\/Error.\n\t\treturn; \/\/Abort this function.\n\t}\n\n\twindow2d->setFramerateLimit(fps);\n}\n\nvoid Window::showMouseCursor(bool show)\n{\n\t\/\/Set the frames per second rate for the window.\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"I can't show or hide the mouse cursor -- window2d doesn't exist!\\n\"; \/\/Error.\n\t\treturn; \/\/Abort this function.\n\t}\n\n\twindow2d->setMouseCursorVisible(show);\n}\n\n} \/\/namespace mgfx\n\n} \/\/namespace GEngine.\n<commit_msg>Made renderText work.<commit_after>\/* Please refer to license.txt *\/\n\n#include \"window.hpp\"\n\n#include \"..\/2d\/2d.hpp\"\n\n#include <iostream>\n\nnamespace GEngine\n{\n\nnamespace mgfx\n{\n\nWindow::Window()\n{\n\twidth = nullptr;\n\theight = nullptr;\n\tdelete_width = false;\n\tdelete_height = false;\n\n\tfullscreen = false;\n\n\twindowname = \"\";\n\n\twindow2d = nullptr;\n\tevent = nullptr;\n\n\tclosed = true;\n\n\tfocus = true;\n}\n\nWindow::~Window()\n{\n\tif (width) \/\/If the width exists.\n\t{\n\t\tif (delete_width) \/\/If it should be deleted.\n\t\t{\n\t\t\tdelete width; \/\/Delete it.\n\t\t\twidth = nullptr; \/\/Reset it.\n\t\t}\n\t\telse\n\t\t{\n\t\t\twidth = nullptr; \/\/Don't delete it, simply reset it.\n\t\t}\n\t}\n\n\tif (height) \/\/If the height exists.\n\t{\n\t\tif (delete_height) \/\/Delete it.\n\t\t{\n\t\t\tdelete height; \/\/Delete it.\n\t\t\theight = nullptr; \/\/Reset it.\n\t\t}\n\t\telse\n\t\t{\n\t\t\theight = nullptr; \/\/Don't delete it, only reset it.\n\t\t}\n\t}\n\n\tif (window2d) \/\/If the 2d window exists.\n\t{\n\t\twindow2d->close(); \/\/Close the window.\n\t\tdelete window2d; \/\/Delete the window.\n\t\twindow2d = nullptr; \/\/Reset it.\n\t}\n\n\tif (event) \/\/If the event exists.\n\t{\n\t\tdelete event; \/\/Delete it.\n\t\tevent = nullptr; \/\/Set to null.\n\t}\n}\n\nbool Window::create(int _width, int _height, bool _fullscreen, std::string _windowname, bool use_opengl)\n{\n\tif (width) \/\/Delete the width if it exists.\n\t{\n\t\tdelete width;\n\t}\n\twidth = new int; \/\/Allocate memory for the width.\n\tdelete_width = true; \/\/The width is to be deleted.\n\t*width = _width; \/\/Store the width.\n\n\tif (height) \/\/Delete the height if it exists.\n\t{\n\t\tdelete height;\n\t}\n\theight = new int; \/\/Allocate memory for the height.\n\tdelete_height = true; \/\/The height is to be deleted.\n\t*height = _height; \/\/Store the height.\n\n\tfullscreen = _fullscreen; \/\/Store the fullscreen state.\n\n\twindowname = _windowname; \/\/Store the window name.\n\n\t\/\/TODO: Point the width and the height to the SFML window's width and height? Don't know if that's possible.\n\twindow2d = new sf::RenderWindow; \/\/Create a new (2d) window.\n\n\tif(fullscreen) \/\/If it is to be fullscreen, do it.\n\t{\n\t\twindow2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Fullscreen); \/\/Make the window fullscreen.\n\t}\n\telse\n\t{\n\t\twindow2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Default); \/\/Nope, just a normal window.\n\t}\n\n\tclosed = false; \/\/Not closed.\n\n\tif (event) \/\/If it already exists.\n\t{\n\t\tdelete event; \/\/Delete it.\n\t}\n\tevent = new sf::Event; \/\/Allocate memory for it.\n\n\t\/\/TODO: Error checking?\n\n\treturn true; \/\/Success.\n}\n\nvoid Window::update()\n{\n\tevents.clear(); \/\/Reset all events.\n\n\tif (!closed && window2d && event) \/\/If the window is open, the window exists, and event exists.\n\t{\n\t\twhile (window2d->pollEvent(*event)) \/\/Poll events. \/\/TODO: Give access to these events to the game.\n\t\t{\n\t\t\tif (event->type == sf::Event::Closed) \/\/Check if the event is a window close.\n\t\t\t{\n\t\t\t\twindow2d->close(); \/\/Close the window.\n\t\t\t\tclosed = true; \/\/Update that it's closed.\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::Resized && !closed && window2d) \/\/Window resized.\n\t\t\t{\n\t\t\t\twindow2d->setView(sf::View(sf::FloatRect(0, 0, event->size.width, event->size.height)));\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::LostFocus)\n\t\t\t{\n\t\t\t\tfocus = false; \/\/Lost focus.\n\t\t\t}\n\t\t\telse if (event->type == sf::Event::GainedFocus)\n\t\t\t{\n\t\t\t\tfocus = true; \/\/Gained focus.\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tevents.push_back(*event); \/\/Save the event for later processing.\n\t\t\t}\n\t\t}\n\n\t\tif (!closed && window2d) \/\/If the window was not closed.\n\t\t{\n\t\t\twindow2d->display(); \/\/Display the window.\n\t\t\twindow2d->clear();\n\t\t}\n\t}\n}\n\nint Window::getWidth()\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nNo 2d window, fool.\\n\";\n\t\treturn -1;\n\t}\n\n\tif (!width || !delete_width) \/\/If width does not exist or if it should not be deleted (meaning it's pointing to some other int).\n\t{\n\t\twidth = new int; \/\/Allocate it.\n\t\tdelete_width = true; \/\/It will be deleted.\n\t}\n\n\tsf::Vector2u vector = window2d->getSize(); \/\/Get the size.\n\n\t*width = vector.x; \/\/Set\/update the width.\n\n\treturn *width; \/\/Return the width.\n}\n\nint Window::getHeight()\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nNo, seriously, there is no 2d window! Why don't you understand?\\n\";\n\t\treturn -1;\n\t}\n\n\tif (!height || !delete_height) \/\/If height does not exist or if it should not be deleted (meaning it's pointing to some other int).\n\t{\n\t\theight = new int; \/\/Allocate it.\n\t\tdelete_height = true; \/\/It will be deleted.\n\t}\n\n\tsf::Vector2u vector = window2d->getSize(); \/\/Get the size of the window.\n\n\t*height = vector.y; \/\/Set\/update the height.\n\n\treturn *height; \/\/Return the height.\n}\n\nint Window::getX()\n{\n\treturn window2d->getPosition().x;\n\t\/\/return (using_opengl) ? \/*3d*\/window3d->getPosition().x \/*window*\/ : \/*2d*\/ window2d->getPosition().x \/*window*\/;\n}\n\nint Window::getY()\n{\n\treturn window2d->getPosition().y;\n\t\/\/return (using_opengl) ? \/*3d*\/window3d->getPosition().y \/*window*\/ : \/*2d*\/ window2d->getPosition().y \/*window*\/;\n}\n\nvoid Window::drawSprite(mgfx::d2d::Sprite &sprite)\n{\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nAnd just what are you trying to achieve with a window that does not exist?\\n\";\n\t\treturn;\n\t}\n\n\twindow2d->draw(*sprite.sprite); \/\/Draw the sprite.\n}\n\nvoid Window::renderText(std::string text, int _x, int _y, int font_size, sf::Font &font)\n{\n\tsf::Text _text(text, font);\n\t_text.setCharacterSize(font_size);\n\t_text.setPosition(_x, _y);\n\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"\\nAnd just what are you trying to achieve with a 2D window that does not exist?\\n\";\n\t\treturn;\n\t}\n\twindow2d->pushGLStates();\n\twindow2d->draw(_text);\n\twindow2d->popGLStates();\n}\n\nvoid Window::setFramerateLimit(int fps)\n{\n\t\/\/Set the frames per second rate for the window.\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"I can't set the framerate limit -- window2d doesn't exist!\\n\"; \/\/Error.\n\t\treturn; \/\/Abort this function.\n\t}\n\n\twindow2d->setFramerateLimit(fps);\n}\n\nvoid Window::showMouseCursor(bool show)\n{\n\t\/\/Set the frames per second rate for the window.\n\tif (!window2d)\n\t{\n\t\tstd::cout << \"I can't show or hide the mouse cursor -- window2d doesn't exist!\\n\"; \/\/Error.\n\t\treturn; \/\/Abort this function.\n\t}\n\n\twindow2d->setMouseCursorVisible(show);\n}\n\n} \/\/namespace mgfx\n\n} \/\/namespace GEngine.\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"messagecollectionattribute.h\"\n#include \"messagecollectionmodel.h\"\n\n#include <kdebug.h>\n#include <klocale.h>\n\n#include <QFont>\n\nusing namespace PIM;\n\nPIM::MessageCollectionModel::MessageCollectionModel( QObject * parent ) :\n CollectionModel( parent )\n{\n}\n\nint PIM::MessageCollectionModel::columnCount( const QModelIndex & parent ) const\n{\n Q_UNUSED( parent );\n return 3;\n}\n\nQVariant PIM::MessageCollectionModel::data( const QModelIndex & index, int role ) const\n{\n Collection *col = static_cast<Collection*>( index.internalPointer() );\n MessageCollectionAttribute *attr = col->attribute<MessageCollectionAttribute>();\n\n if ( role == Qt::DisplayRole && attr && ( index.column() == 1 || index.column() == 2 ) ) {\n int value = -1;\n switch ( index.column() ) {\n case 1: value = attr->unreadCount(); break;\n case 2: value = attr->count(); break;\n }\n if ( value < 0 )\n return QString();\n else if ( value == 0 )\n return QString( \"-\" );\n else\n return QString::number( value );\n }\n\n if ( role == Qt::TextAlignmentRole && ( index.column() == 1 || index.column() == 2 ) )\n return Qt::AlignRight;\n\n \/\/ ### that's wrong, we'll need a custom delegate anyway\n if ( role == Qt::FontRole && attr && attr->unreadCount() > 0 ) {\n QFont f;\n f.setBold( true );\n return f;\n }\n\n return CollectionModel::data( index, role );\n}\n\nQVariant PIM::MessageCollectionModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )\n switch ( section ) {\n case 1: return i18n( \"Unread\" );\n case 2: return i18n( \"Total\" );\n }\n\n return CollectionModel::headerData( section, orientation, role );\n}\n\n#include \"messagecollectionmodel.moc\"\n<commit_msg>fix crash<commit_after>\/*\n Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"messagecollectionattribute.h\"\n#include \"messagecollectionmodel.h\"\n\n#include <kdebug.h>\n#include <klocale.h>\n\n#include <QFont>\n\nusing namespace PIM;\n\nPIM::MessageCollectionModel::MessageCollectionModel( QObject * parent ) :\n CollectionModel( parent )\n{\n}\n\nint PIM::MessageCollectionModel::columnCount( const QModelIndex & parent ) const\n{\n Q_UNUSED( parent );\n return 3;\n}\n\nQVariant PIM::MessageCollectionModel::data( const QModelIndex & index, int role ) const\n{\n if ( !index.isValid() )\n return QVariant();\n\n Collection *col = static_cast<Collection*>( index.internalPointer() );\n Q_ASSERT( col );\n MessageCollectionAttribute *attr = col->attribute<MessageCollectionAttribute>();\n\n if ( role == Qt::DisplayRole && attr && ( index.column() == 1 || index.column() == 2 ) ) {\n int value = -1;\n switch ( index.column() ) {\n case 1: value = attr->unreadCount(); break;\n case 2: value = attr->count(); break;\n }\n if ( value < 0 )\n return QString();\n else if ( value == 0 )\n return QString( \"-\" );\n else\n return QString::number( value );\n }\n\n if ( role == Qt::TextAlignmentRole && ( index.column() == 1 || index.column() == 2 ) )\n return Qt::AlignRight;\n\n \/\/ ### that's wrong, we'll need a custom delegate anyway\n if ( role == Qt::FontRole && attr && attr->unreadCount() > 0 ) {\n QFont f;\n f.setBold( true );\n return f;\n }\n\n return CollectionModel::data( index, role );\n}\n\nQVariant PIM::MessageCollectionModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )\n switch ( section ) {\n case 1: return i18n( \"Unread\" );\n case 2: return i18n( \"Total\" );\n }\n\n return CollectionModel::headerData( section, orientation, role );\n}\n\n#include \"messagecollectionmodel.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of akregatorstorageexporter\n *\n * Copyright (C) 2009 Frank Osterfeld <osterfeld@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n#include \"feedstorage.h\"\n#include \"storage.h\"\n#include \"storagefactory.h\"\n#include \"storagefactoryregistry.h\"\n#include \"plugin.h\"\n\n#include <syndication\/atom\/constants.h>\n#include <syndication\/constants.h>\n\n#include <QCoreApplication>\n#include <QDateTime>\n#include <QDebug>\n#include <QFile>\n#include <QIODevice>\n#include <QStringList>\n#include <QUrl>\n#include <QXmlStreamWriter>\n#include <QVariant>\n\n#include <KComponentData>\n#include <KGlobal>\n#include <KPluginLoader>\n#include <KService>\n#include <KServiceTypeTrader>\n\n#include <cassert>\n\nusing namespace Akregator;\nusing namespace Akregator::Backend;\n\nnamespace {\n static QString akregatorNamespace() {\n return QString::fromLatin1(\"http:\/\/akregator.kde.org\/StorageExporter#\");\n }\n\n enum TextMode {\n PlainText,\n Html\n };\n\n enum Status\n {\n Deleted=0x01,\n Trash=0x02,\n New=0x04,\n Read=0x08,\n Keep=0x10\n };\n\n class Element\n {\n public:\n Element( const QString& ns_, const QString& name_ ) : ns( ns_ ), name( name_ ), qualifiedName( ns + ':' + name )\n {\n }\n\n const QString ns;\n const QString name;\n const QString qualifiedName;\n\n void writeStartElement( QXmlStreamWriter& writer ) const\n {\n if ( !ns.isNull() )\n writer.writeStartElement( ns, name );\n else\n writer.writeStartElement( name );\n }\n\n void write( const QVariant& value , QXmlStreamWriter& writer, TextMode mode = PlainText ) const\n {\n const QVariant qv( value );\n Q_ASSERT( qv.canConvert( QVariant::String ) );\n const QString str = qv.toString();\n if ( str.isEmpty() )\n return;\n\n if ( ns.isEmpty() )\n writer.writeStartElement( name );\n else\n writer.writeStartElement( ns, name );\n if ( mode == Html )\n {\n writer.writeAttribute( \"type\", \"html\" );\n }\n writer.writeCharacters( str );\n writer.writeEndElement();\n }\n };\n\n struct Elements\n {\n Elements() : atomNS( Syndication::Atom::atom1Namespace() ),\n akregatorNS(akregatorNamespace() ),\n commentNS( Syndication::commentApiNamespace() ),\n title( atomNS, \"title\" ),\n summary( atomNS, \"summary\" ),\n content( atomNS, \"content\" ),\n link( atomNS, \"link\" ),\n language( atomNS, \"language\" ),\n feed( atomNS, \"feed\" ),\n guid( atomNS, \"id\" ),\n published( atomNS, \"published\" ),\n updated( atomNS, \"updated\" ),\n commentsCount( Syndication::slashNamespace(), \"comments\" ),\n commentsFeed( commentNS, \"commentRss\" ),\n commentPostUri( commentNS, \"comment\" ),\n commentsLink( akregatorNS, \"commentsLink\" ),\n status( akregatorNS, \"status\" ),\n hash( akregatorNS, \"hash\" ),\n guidIsHash( akregatorNS, \"idIsHash\" ),\n name( atomNS, \"name\" ),\n uri( atomNS, \"uri\" ),\n email( atomNS, \"email\" ),\n author( atomNS, \"author\" ),\n category( atomNS, \"category\" ),\n entry( atomNS, \"entry\" ),\n itemProperties( akregatorNS, \"itemProperties\" ),\n readStatus( akregatorNS, \"readStatus\" ),\n deleted( akregatorNS, \"deleted\" ),\n important( akregatorNS, \"important\" )\n\n {}\n const QString atomNS;\n const QString akregatorNS;\n const QString commentNS;\n const Element title;\n const Element summary;\n const Element content;\n const Element link;\n const Element language;\n const Element feed;\n const Element guid;\n const Element published;\n const Element updated;\n const Element commentsCount;\n const Element commentsFeed;\n const Element commentPostUri;\n const Element commentsLink;\n const Element status;\n const Element hash;\n const Element guidIsHash;\n const Element name;\n const Element uri;\n const Element email;\n const Element author;\n const Element category;\n const Element entry;\n const Element itemProperties;\n const Element readStatus;\n const Element deleted;\n const Element important;\n static const Elements instance;\n };\n\n const Elements Elements::instance;\n\n void writeAttributeIfNotEmpty( const QString& ns, const QString& element, const QVariant& value, QXmlStreamWriter& writer )\n {\n const QString text = value.toString();\n if ( text.isEmpty() )\n return;\n writer.writeAttribute( ns, element, text );\n }\n\n void writeAttributeIfNotEmpty( const QString& element, const QVariant& value, QXmlStreamWriter& writer )\n {\n const QString text = value.toString();\n if ( text.isEmpty() )\n return;\n writer.writeAttribute( element, text );\n }\n\n void writeEnclosure( const QString& url, const QString& type, int length, QXmlStreamWriter& writer )\n {\n Elements::instance.link.writeStartElement( writer );\n writer.writeAttribute( \"rel\", \"enclosure\" );\n writeAttributeIfNotEmpty( \"href\", url, writer );\n writeAttributeIfNotEmpty( \"type\", type, writer );\n if ( length > 0 )\n writer.writeAttribute( \"length\", QString::number( length ) );\n writer.writeEndElement();\n }\n\n void writeLink( const QString& url, QXmlStreamWriter& writer )\n {\n if ( url.isEmpty() )\n return;\n Elements::instance.link.writeStartElement( writer );\n writer.writeAttribute( \"rel\", \"alternate\" );\n writeAttributeIfNotEmpty( \"href\", url, writer );\n writer.writeEndElement();\n }\n\n void writeAuthor( const QString& name, const QString& uri, const QString& email, QXmlStreamWriter& writer )\n {\n if ( name.isEmpty() && uri.isEmpty() && email.isEmpty() )\n return;\n\n const QString atomNS = Syndication::Atom::atom1Namespace();\n Elements::instance.author.writeStartElement( writer );\n Elements::instance.name.write( name, writer );\n Elements::instance.uri.write( uri, writer );\n Elements::instance.email.write( email, writer );\n writer.writeEndElement(); \/\/ <\/author>\n }\n\n static void writeItem( FeedStorage* storage, const QString& guid, QXmlStreamWriter& writer ) {\n Elements::instance.entry.writeStartElement( writer );\n Elements::instance.guid.write( guid, writer );\n\n const uint published = storage->pubDate( guid );\n if ( published > 0 ) {\n const QString pdStr = QDateTime::fromTime_t( published ).toString( Qt::ISODate );\n Elements::instance.published.write( pdStr, writer );\n }\n\n const int status = storage->status( guid );\n\n Elements::instance.itemProperties.writeStartElement( writer );\n\n if ( status & Deleted ) {\n Elements::instance.deleted.write( QString::fromLatin1(\"true\"), writer );\n writer.writeEndElement(); \/\/ <\/itemProperties>\n writer.writeEndElement(); \/\/ <\/item>\n return;\n }\n\n Elements::instance.hash.write( QString::number( storage->hash( guid ) ), writer );\n if ( storage->guidIsHash( guid ) )\n Elements::instance.guidIsHash.write( QString::fromLatin1(\"true\"), writer );\n if ( status & New )\n Elements::instance.readStatus.write( QString::fromLatin1(\"new\"), writer );\n else if ( ( status & Read) == 0 )\n Elements::instance.readStatus.write( QString::fromLatin1(\"unread\"), writer );\n if ( status & Keep )\n Elements::instance.important.write( QString::fromLatin1(\"true\"), writer );\n writer.writeEndElement(); \/\/ <\/itemProperties>\n\n Elements::instance.title.write( storage->title( guid ), writer, Html );\n writeLink( storage->guidIsPermaLink( guid ) ? guid : storage->link( guid ), writer );\n\n Elements::instance.summary.write( storage->description( guid ), writer, Html );\n Elements::instance.content.write( storage->content( guid ), writer, Html );\n writeAuthor( storage->authorName( guid ),\n storage->authorUri( guid ),\n storage->authorEMail( guid ),\n writer );\n\n if ( const int commentsCount = storage->comments( guid ) )\n Elements::instance.commentsCount.write( QString::number( commentsCount ), writer );\n\n Elements::instance.commentsLink.write( storage->commentsLink( guid ), writer );\n\n bool hasEnc = false;\n QString encUrl, encType;\n int encLength = 0;\n storage->enclosure( guid, hasEnc, encUrl, encType, encLength );\n if ( hasEnc )\n writeEnclosure( encUrl, encType, encLength, writer );\n writer.writeEndElement(); \/\/ <\/item>\n }\n\n static void serialize( FeedStorage* storage, QIODevice* device ) {\n assert( storage );\n assert( device );\n QXmlStreamWriter writer( device );\n writer.setAutoFormatting( true );\n writer.setAutoFormattingIndent( 2 );\n writer.writeStartDocument();\n\n Elements::instance.feed.writeStartElement( writer );\n\n writer.writeDefaultNamespace( Syndication::Atom::atom1Namespace() );\n writer.writeNamespace( Syndication::commentApiNamespace(), \"comment\" );\n writer.writeNamespace( akregatorNamespace(), \"akregator\" );\n writer.writeNamespace( Syndication::itunesNamespace(), \"itunes\" );\n\n Elements::instance.title.write( QString::fromLatin1(\"Akregator Export\"), writer, Html );\n\n\n Q_FOREACH( const QString& i, storage->articles() )\n writeItem( storage, i, writer );\n writer.writeEndElement(); \/\/ <\/feed>\n writer.writeEndDocument();\n }\n\n static void serialize( Storage* storage, const QString& url, QIODevice* device ) {\n serialize( storage->archiveFor( url ), device );\n }\n\n static KService::List queryStoragePlugins() {\n return KServiceTypeTrader::self()->query( \"Akregator\/Plugin\",\n QString::fromLatin1( \"[X-KDE-akregator-framework-version] == %1 and [X-KDE-akregator-plugintype] == 'storage' and [X-KDE-akregator-rank] > 0\" ).arg( QString::number( AKREGATOR_PLUGIN_INTERFACE_VERSION ) ) );\n }\n\n static Plugin* createFromService( const KService::Ptr& service )\n {\n KPluginLoader loader( *service );\n KPluginFactory* factory = loader.factory();\n if ( !factory ) {\n qCritical() << QString( \" Could not create plugin factory for: %1\\n\"\n \" Error message: %2\" ).arg( service->library(), loader.errorString() );\n return 0;\n }\n return factory->create<Akregator::Plugin>();\n }\n\n static void printUsage() {\n\n }\n}\n\n\nint main( int argc, char** argv ) {\n KGlobal::setActiveComponent( KComponentData( \"akregatorstorageexporter\" ) );\n const QString backend = QString::fromLatin1( \"metakit\" );\n\n if ( argc < 2 ) {\n printUsage();\n return 1;\n }\n const QString url = QUrl::fromEncoded( argv[1] ).toString();\n\n Q_FOREACH( const KService::Ptr& i, queryStoragePlugins() )\n if ( Plugin* const plugin = createFromService( i ) )\n plugin->initialize();\n\n const StorageFactory* const storageFactory = StorageFactoryRegistry::self()->getFactory( backend );\n if ( !storageFactory ) {\n qCritical( \"Could not create storage factory for %s.\", qPrintable( backend ) );\n return 1;\n }\n\n Storage* const storage = storageFactory->createStorage( QStringList() );\n if ( !storage ) {\n qCritical( \"Could not create storage object for %s.\", qPrintable( backend ) );\n return 1;\n }\n\n QFile out;\n if ( !out.open( stdout, QIODevice::WriteOnly ) ) {\n qCritical( \"Could not open stdout for writing: %s\", qPrintable( out.errorString() ) );\n return 1;\n }\n\n serialize( storage, url, &out );\n return 0;\n}\n<commit_msg>decode from base64<commit_after>\/*\n * This file is part of akregatorstorageexporter\n *\n * Copyright (C) 2009 Frank Osterfeld <osterfeld@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n#include \"feedstorage.h\"\n#include \"storage.h\"\n#include \"storagefactory.h\"\n#include \"storagefactoryregistry.h\"\n#include \"plugin.h\"\n\n#include <syndication\/atom\/constants.h>\n#include <syndication\/constants.h>\n\n#include <QCoreApplication>\n#include <QDateTime>\n#include <QDebug>\n#include <QFile>\n#include <QIODevice>\n#include <QStringList>\n#include <QUrl>\n#include <QXmlStreamWriter>\n#include <QVariant>\n\n#include <KComponentData>\n#include <KGlobal>\n#include <KPluginLoader>\n#include <KService>\n#include <KServiceTypeTrader>\n\n#include <cassert>\n\nusing namespace Akregator;\nusing namespace Akregator::Backend;\n\nnamespace {\n static QString akregatorNamespace() {\n return QString::fromLatin1(\"http:\/\/akregator.kde.org\/StorageExporter#\");\n }\n\n enum TextMode {\n PlainText,\n Html\n };\n\n enum Status\n {\n Deleted=0x01,\n Trash=0x02,\n New=0x04,\n Read=0x08,\n Keep=0x10\n };\n\n class Element\n {\n public:\n Element( const QString& ns_, const QString& name_ ) : ns( ns_ ), name( name_ ), qualifiedName( ns + ':' + name )\n {\n }\n\n const QString ns;\n const QString name;\n const QString qualifiedName;\n\n void writeStartElement( QXmlStreamWriter& writer ) const\n {\n if ( !ns.isNull() )\n writer.writeStartElement( ns, name );\n else\n writer.writeStartElement( name );\n }\n\n void write( const QVariant& value , QXmlStreamWriter& writer, TextMode mode = PlainText ) const\n {\n const QVariant qv( value );\n Q_ASSERT( qv.canConvert( QVariant::String ) );\n const QString str = qv.toString();\n if ( str.isEmpty() )\n return;\n\n if ( ns.isEmpty() )\n writer.writeStartElement( name );\n else\n writer.writeStartElement( ns, name );\n if ( mode == Html )\n {\n writer.writeAttribute( \"type\", \"html\" );\n }\n writer.writeCharacters( str );\n writer.writeEndElement();\n }\n };\n\n struct Elements\n {\n Elements() : atomNS( Syndication::Atom::atom1Namespace() ),\n akregatorNS(akregatorNamespace() ),\n commentNS( Syndication::commentApiNamespace() ),\n title( atomNS, \"title\" ),\n summary( atomNS, \"summary\" ),\n content( atomNS, \"content\" ),\n link( atomNS, \"link\" ),\n language( atomNS, \"language\" ),\n feed( atomNS, \"feed\" ),\n guid( atomNS, \"id\" ),\n published( atomNS, \"published\" ),\n updated( atomNS, \"updated\" ),\n commentsCount( Syndication::slashNamespace(), \"comments\" ),\n commentsFeed( commentNS, \"commentRss\" ),\n commentPostUri( commentNS, \"comment\" ),\n commentsLink( akregatorNS, \"commentsLink\" ),\n status( akregatorNS, \"status\" ),\n hash( akregatorNS, \"hash\" ),\n guidIsHash( akregatorNS, \"idIsHash\" ),\n name( atomNS, \"name\" ),\n uri( atomNS, \"uri\" ),\n email( atomNS, \"email\" ),\n author( atomNS, \"author\" ),\n category( atomNS, \"category\" ),\n entry( atomNS, \"entry\" ),\n itemProperties( akregatorNS, \"itemProperties\" ),\n readStatus( akregatorNS, \"readStatus\" ),\n deleted( akregatorNS, \"deleted\" ),\n important( akregatorNS, \"important\" )\n\n {}\n const QString atomNS;\n const QString akregatorNS;\n const QString commentNS;\n const Element title;\n const Element summary;\n const Element content;\n const Element link;\n const Element language;\n const Element feed;\n const Element guid;\n const Element published;\n const Element updated;\n const Element commentsCount;\n const Element commentsFeed;\n const Element commentPostUri;\n const Element commentsLink;\n const Element status;\n const Element hash;\n const Element guidIsHash;\n const Element name;\n const Element uri;\n const Element email;\n const Element author;\n const Element category;\n const Element entry;\n const Element itemProperties;\n const Element readStatus;\n const Element deleted;\n const Element important;\n static const Elements instance;\n };\n\n const Elements Elements::instance;\n\n void writeAttributeIfNotEmpty( const QString& ns, const QString& element, const QVariant& value, QXmlStreamWriter& writer )\n {\n const QString text = value.toString();\n if ( text.isEmpty() )\n return;\n writer.writeAttribute( ns, element, text );\n }\n\n void writeAttributeIfNotEmpty( const QString& element, const QVariant& value, QXmlStreamWriter& writer )\n {\n const QString text = value.toString();\n if ( text.isEmpty() )\n return;\n writer.writeAttribute( element, text );\n }\n\n void writeEnclosure( const QString& url, const QString& type, int length, QXmlStreamWriter& writer )\n {\n Elements::instance.link.writeStartElement( writer );\n writer.writeAttribute( \"rel\", \"enclosure\" );\n writeAttributeIfNotEmpty( \"href\", url, writer );\n writeAttributeIfNotEmpty( \"type\", type, writer );\n if ( length > 0 )\n writer.writeAttribute( \"length\", QString::number( length ) );\n writer.writeEndElement();\n }\n\n void writeLink( const QString& url, QXmlStreamWriter& writer )\n {\n if ( url.isEmpty() )\n return;\n Elements::instance.link.writeStartElement( writer );\n writer.writeAttribute( \"rel\", \"alternate\" );\n writeAttributeIfNotEmpty( \"href\", url, writer );\n writer.writeEndElement();\n }\n\n void writeAuthor( const QString& name, const QString& uri, const QString& email, QXmlStreamWriter& writer )\n {\n if ( name.isEmpty() && uri.isEmpty() && email.isEmpty() )\n return;\n\n const QString atomNS = Syndication::Atom::atom1Namespace();\n Elements::instance.author.writeStartElement( writer );\n Elements::instance.name.write( name, writer );\n Elements::instance.uri.write( uri, writer );\n Elements::instance.email.write( email, writer );\n writer.writeEndElement(); \/\/ <\/author>\n }\n\n static void writeItem( FeedStorage* storage, const QString& guid, QXmlStreamWriter& writer ) {\n Elements::instance.entry.writeStartElement( writer );\n Elements::instance.guid.write( guid, writer );\n\n const uint published = storage->pubDate( guid );\n if ( published > 0 ) {\n const QString pdStr = QDateTime::fromTime_t( published ).toString( Qt::ISODate );\n Elements::instance.published.write( pdStr, writer );\n }\n\n const int status = storage->status( guid );\n\n Elements::instance.itemProperties.writeStartElement( writer );\n\n if ( status & Deleted ) {\n Elements::instance.deleted.write( QString::fromLatin1(\"true\"), writer );\n writer.writeEndElement(); \/\/ <\/itemProperties>\n writer.writeEndElement(); \/\/ <\/item>\n return;\n }\n\n Elements::instance.hash.write( QString::number( storage->hash( guid ) ), writer );\n if ( storage->guidIsHash( guid ) )\n Elements::instance.guidIsHash.write( QString::fromLatin1(\"true\"), writer );\n if ( status & New )\n Elements::instance.readStatus.write( QString::fromLatin1(\"new\"), writer );\n else if ( ( status & Read) == 0 )\n Elements::instance.readStatus.write( QString::fromLatin1(\"unread\"), writer );\n if ( status & Keep )\n Elements::instance.important.write( QString::fromLatin1(\"true\"), writer );\n writer.writeEndElement(); \/\/ <\/itemProperties>\n\n Elements::instance.title.write( storage->title( guid ), writer, Html );\n writeLink( storage->guidIsPermaLink( guid ) ? guid : storage->link( guid ), writer );\n\n Elements::instance.summary.write( storage->description( guid ), writer, Html );\n Elements::instance.content.write( storage->content( guid ), writer, Html );\n writeAuthor( storage->authorName( guid ),\n storage->authorUri( guid ),\n storage->authorEMail( guid ),\n writer );\n\n if ( const int commentsCount = storage->comments( guid ) )\n Elements::instance.commentsCount.write( QString::number( commentsCount ), writer );\n\n Elements::instance.commentsLink.write( storage->commentsLink( guid ), writer );\n\n bool hasEnc = false;\n QString encUrl, encType;\n int encLength = 0;\n storage->enclosure( guid, hasEnc, encUrl, encType, encLength );\n if ( hasEnc )\n writeEnclosure( encUrl, encType, encLength, writer );\n writer.writeEndElement(); \/\/ <\/item>\n }\n\n static void serialize( FeedStorage* storage, QIODevice* device ) {\n assert( storage );\n assert( device );\n QXmlStreamWriter writer( device );\n writer.setAutoFormatting( true );\n writer.setAutoFormattingIndent( 2 );\n writer.writeStartDocument();\n\n Elements::instance.feed.writeStartElement( writer );\n\n writer.writeDefaultNamespace( Syndication::Atom::atom1Namespace() );\n writer.writeNamespace( Syndication::commentApiNamespace(), \"comment\" );\n writer.writeNamespace( akregatorNamespace(), \"akregator\" );\n writer.writeNamespace( Syndication::itunesNamespace(), \"itunes\" );\n\n Elements::instance.title.write( QString::fromLatin1(\"Akregator Export\"), writer, Html );\n\n\n Q_FOREACH( const QString& i, storage->articles() )\n writeItem( storage, i, writer );\n writer.writeEndElement(); \/\/ <\/feed>\n writer.writeEndDocument();\n }\n\n static void serialize( Storage* storage, const QString& url, QIODevice* device ) {\n serialize( storage->archiveFor( url ), device );\n }\n\n static KService::List queryStoragePlugins() {\n return KServiceTypeTrader::self()->query( \"Akregator\/Plugin\",\n QString::fromLatin1( \"[X-KDE-akregator-framework-version] == %1 and [X-KDE-akregator-plugintype] == 'storage' and [X-KDE-akregator-rank] > 0\" ).arg( QString::number( AKREGATOR_PLUGIN_INTERFACE_VERSION ) ) );\n }\n\n static Plugin* createFromService( const KService::Ptr& service )\n {\n KPluginLoader loader( *service );\n KPluginFactory* factory = loader.factory();\n if ( !factory ) {\n qCritical() << QString( \" Could not create plugin factory for: %1\\n\"\n \" Error message: %2\" ).arg( service->library(), loader.errorString() );\n return 0;\n }\n return factory->create<Akregator::Plugin>();\n }\n\n static void printUsage() {\n\n }\n}\n\n\nint main( int argc, char** argv ) {\n KGlobal::setActiveComponent( KComponentData( \"akregatorstorageexporter\" ) );\n const QString backend = QString::fromLatin1( \"metakit\" );\n\n if ( argc < 2 ) {\n printUsage();\n return 1;\n }\n const QString url = QUrl::fromEncoded( QByteArray::fromBase64( argv[1] ) ).toString();\n\n Q_FOREACH( const KService::Ptr& i, queryStoragePlugins() )\n if ( Plugin* const plugin = createFromService( i ) )\n plugin->initialize();\n\n const StorageFactory* const storageFactory = StorageFactoryRegistry::self()->getFactory( backend );\n if ( !storageFactory ) {\n qCritical( \"Could not create storage factory for %s.\", qPrintable( backend ) );\n return 1;\n }\n\n Storage* const storage = storageFactory->createStorage( QStringList() );\n if ( !storage ) {\n qCritical( \"Could not create storage object for %s.\", qPrintable( backend ) );\n return 1;\n }\n\n QFile out;\n if ( !out.open( stdout, QIODevice::WriteOnly ) ) {\n qCritical( \"Could not open stdout for writing: %s\", qPrintable( out.errorString() ) );\n return 1;\n }\n\n serialize( storage, url, &out );\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include <stdexcept>\n\n#include \"Token.hpp\"\n#include \"Instruction.hpp\"\n\nclass SemanticAnalyser\n{\npublic:\n class InvalidSemantic : public std::runtime_error\n {\n public:\n InvalidSemantic(const std::string& msg) : std::runtime_error{msg}\n {\n }\n };\n\n Instructions analyse(const Tokens& tokens)\n {\n if (tokens.empty())\n {\n return {};\n }\n if (tokens.size() == 3)\n {\n return {{InstructionType::LdA, 0}};\n }\n throw InvalidSemantic{\"Invalid number of tokens\"};\n }\n\nprivate:\n using Transition = std::pair<TokenType, TokenType>;\n using Transitions = std::vector<Transition>;\n\n Transitions validTransitions;\n};\n\nusing namespace ::testing;\n\nstruct SemanticAnalyserTest : public Test\n{\n SemanticAnalyser analyser;\n\n static constexpr Token createTokenWithZeroValue(TokenType type)\n {\n return{type, 0};\n }\n\n static constexpr Instruction createInstructionWithZeroValue(InstructionType type)\n {\n return{type, 0};\n }\n};\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)\n{\n Tokens tokens{};\n Instructions instructions;\n ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)\n{\n Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};\n ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptValidLdInstructions)\n{\n Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n createTokenWithZeroValue(TokenType::A),\n createTokenWithZeroValue(TokenType::Number8Bit)};\n Instructions instructions{createInstructionWithZeroValue(InstructionType::LdA)};\n ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n<commit_msg>SemanticAnalyser Returs Out instruction<commit_after>#include \"gtest\/gtest.h\"\n\n#include <stdexcept>\n\n#include \"Token.hpp\"\n#include \"Instruction.hpp\"\n\nclass SemanticAnalyser\n{\npublic:\n class InvalidSemantic : public std::runtime_error\n {\n public:\n InvalidSemantic(const std::string& msg) : std::runtime_error{msg}\n {\n }\n };\n\n Instructions analyse(const Tokens& tokens)\n {\n if (tokens.empty())\n {\n return {};\n }\n if (tokens.size() == 3)\n {\n if (tokens.at(0).type == TokenType::Ld)\n {\n return {{InstructionType::LdA, 0}};\n }\n else\n {\n return {{InstructionType::OutA, 0}};\n }\n }\n throw InvalidSemantic{\"Invalid number of tokens\"};\n }\n\nprivate:\n using Transition = std::pair<TokenType, TokenType>;\n using Transitions = std::vector<Transition>;\n\n Transitions validTransitions;\n};\n\nusing namespace ::testing;\n\nstruct SemanticAnalyserTest : public Test\n{\n SemanticAnalyser analyser;\n\n static constexpr Token createTokenWithZeroValue(TokenType type)\n {\n return{type, 0};\n }\n\n static constexpr Instruction createInstructionWithZeroValue(InstructionType type)\n {\n return{type, 0};\n }\n};\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)\n{\n Tokens tokens{};\n Instructions instructions;\n ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)\n{\n Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};\n ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptLdInstruction)\n{\n Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n createTokenWithZeroValue(TokenType::A),\n createTokenWithZeroValue(TokenType::Number8Bit)};\n Instructions instructions{createInstructionWithZeroValue(InstructionType::LdA)};\n ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstruction)\n{\n Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n createTokenWithZeroValue(TokenType::ZeroWithBrackets),\n createTokenWithZeroValue(TokenType::A)};\n Instructions instructions{createInstructionWithZeroValue(InstructionType::OutA)};\n ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FrameStatistics_Service.cpp\n *\n * Copyright (C) 2020 by MegaMol Team\n * Alle Rechte vorbehalten.\n *\/\n\n\/\/ search\/replace FrameStatistics_Service with your class name\n\/\/ you should also delete the FAQ comments in these template files after you read and understood them\n#include \"FrameStatistics_Service.hpp\"\n\n#include <chrono>\n#include <numeric>\n#include <sstream>\n\n#include \"mmcore\/utility\/Timestamp.h\"\n\n#include \"LuaCallbacksCollection.h\"\n\n\n\/\/ local logging wrapper for your convenience until central MegaMol logger established\n#include \"mmcore\/utility\/log\/Log.h\"\nstatic void log(const char* text) {\n const std::string msg = \"FrameStatistics_Service: \" + std::string(text);\n megamol::core::utility::log::Log::DefaultLog.WriteInfo(msg.c_str());\n}\nstatic void log(std::string text) {\n log(text.c_str());\n}\n\nnamespace megamol {\nnamespace frontend {\n\nFrameStatistics_Service::FrameStatistics_Service() {}\n\nFrameStatistics_Service::~FrameStatistics_Service() {}\n\nbool FrameStatistics_Service::init(void* configPtr) {\n if (configPtr == nullptr)\n return false;\n\n return init(*static_cast<Config*>(configPtr));\n}\n\nbool FrameStatistics_Service::init(const Config& config) {\n\n this->m_requestedResourcesNames = {\/\/\"IOpenGL_Context\", \/\/ for GL-specific measures?\n \"RegisterLuaCallbacks\"};\n\n m_program_start_time = std::chrono::steady_clock::time_point::clock::now();\n\n log(\"initialized successfully\");\n return true;\n}\n\nvoid FrameStatistics_Service::close() {}\n\nstd::vector<FrontendResource>& FrameStatistics_Service::getProvidedResources() {\n m_providedResourceReferences = {{frontend_resources::FrameStatistics_Req_Name, m_statistics}};\n\n return m_providedResourceReferences;\n}\n\nconst std::vector<std::string> FrameStatistics_Service::getRequestedResourceNames() const {\n return m_requestedResourcesNames;\n}\n\nvoid FrameStatistics_Service::setRequestedResources(std::vector<FrontendResource> resources) {\n this->m_requestedResourceReferences = resources;\n fill_lua_callbacks();\n}\n\nvoid FrameStatistics_Service::updateProvidedResources() {\n start_frame();\n}\n\nvoid FrameStatistics_Service::digestChangedRequestedResources() {}\n\nvoid FrameStatistics_Service::resetProvidedResources() {\n finish_frame();\n}\n\nvoid FrameStatistics_Service::preGraphRender() {}\n\nvoid FrameStatistics_Service::postGraphRender() {}\n\n\/\/ TODO: maybe port FPS Counter from\n\/\/ #include \"vislib\/graphics\/FpsCounter.h\"\nvoid FrameStatistics_Service::start_frame() {\n m_frame_start_time = std::chrono::steady_clock::time_point::clock::now();\n}\n\nvoid FrameStatistics_Service::finish_frame() {\n auto now = std::chrono::steady_clock::time_point::clock::now();\n\n m_statistics.rendered_frames_count++;\n\n m_statistics.elapsed_program_time_seconds =\n static_cast<double>(std::chrono::duration_cast<std::chrono::seconds>(now - m_program_start_time).count());\n\n const auto last_frame_till_now_micro =\n std::chrono::duration_cast<std::chrono::microseconds>(now - m_frame_start_time).count();\n\n m_statistics.last_rendered_frame_time_milliseconds = static_cast<double>(last_frame_till_now_micro) \/ 1000.0;\n\n m_frame_times_micro[m_ring_buffer_ptr] = last_frame_till_now_micro;\n m_ring_buffer_ptr = (m_ring_buffer_ptr + 1) % m_frame_times_micro.size();\n\n m_statistics.last_averaged_mspf = std::accumulate(m_frame_times_micro.begin(), m_frame_times_micro.end(), 0) \/\n m_frame_times_micro.size() \/ static_cast<double>(1000);\n m_statistics.last_averaged_fps = 1000.0 \/ m_statistics.last_averaged_mspf;\n}\n\nvoid FrameStatistics_Service::fill_lua_callbacks() {\n frontend_resources::LuaCallbacksCollection callbacks;\n\n callbacks.add<frontend_resources::LuaCallbacksCollection::StringResult>(\"mmGetTimeStamp\",\n \"(void)\\n\\tReturns a timestamp in ISO format.\",\n {[&]() -> frontend_resources::LuaCallbacksCollection::StringResult {\n auto const tp = std::chrono::system_clock::now();\n auto const timestamp = core::utility::serialize_timestamp(tp);\n return frontend_resources::LuaCallbacksCollection::StringResult(timestamp);\n }});\n\n auto& register_callbacks =\n m_requestedResourceReferences[0]\n .getResource<std::function<void(frontend_resources::LuaCallbacksCollection const&)>>();\n\n register_callbacks(callbacks);\n}\n\n} \/\/ namespace frontend\n} \/\/ namespace megamol\n<commit_msg>fixed broken timer fix<commit_after>\/*\n * FrameStatistics_Service.cpp\n *\n * Copyright (C) 2020 by MegaMol Team\n * Alle Rechte vorbehalten.\n *\/\n\n\/\/ search\/replace FrameStatistics_Service with your class name\n\/\/ you should also delete the FAQ comments in these template files after you read and understood them\n#include \"FrameStatistics_Service.hpp\"\n\n#include <chrono>\n#include <numeric>\n#include <sstream>\n\n#include \"mmcore\/utility\/Timestamp.h\"\n\n#include \"LuaCallbacksCollection.h\"\n\n\n\/\/ local logging wrapper for your convenience until central MegaMol logger established\n#include \"mmcore\/utility\/log\/Log.h\"\nstatic void log(const char* text) {\n const std::string msg = \"FrameStatistics_Service: \" + std::string(text);\n megamol::core::utility::log::Log::DefaultLog.WriteInfo(msg.c_str());\n}\nstatic void log(std::string text) {\n log(text.c_str());\n}\n\nnamespace megamol {\nnamespace frontend {\n\nFrameStatistics_Service::FrameStatistics_Service() {}\n\nFrameStatistics_Service::~FrameStatistics_Service() {}\n\nbool FrameStatistics_Service::init(void* configPtr) {\n if (configPtr == nullptr)\n return false;\n\n return init(*static_cast<Config*>(configPtr));\n}\n\nbool FrameStatistics_Service::init(const Config& config) {\n\n this->m_requestedResourcesNames = {\/\/\"IOpenGL_Context\", \/\/ for GL-specific measures?\n \"RegisterLuaCallbacks\"};\n\n m_program_start_time = std::chrono::steady_clock::time_point::clock::now();\n\n log(\"initialized successfully\");\n return true;\n}\n\nvoid FrameStatistics_Service::close() {}\n\nstd::vector<FrontendResource>& FrameStatistics_Service::getProvidedResources() {\n m_providedResourceReferences = {{frontend_resources::FrameStatistics_Req_Name, m_statistics}};\n\n return m_providedResourceReferences;\n}\n\nconst std::vector<std::string> FrameStatistics_Service::getRequestedResourceNames() const {\n return m_requestedResourcesNames;\n}\n\nvoid FrameStatistics_Service::setRequestedResources(std::vector<FrontendResource> resources) {\n this->m_requestedResourceReferences = resources;\n fill_lua_callbacks();\n}\n\nvoid FrameStatistics_Service::updateProvidedResources() {\n start_frame();\n}\n\nvoid FrameStatistics_Service::digestChangedRequestedResources() {}\n\nvoid FrameStatistics_Service::resetProvidedResources() {\n finish_frame();\n}\n\nvoid FrameStatistics_Service::preGraphRender() {}\n\nvoid FrameStatistics_Service::postGraphRender() {}\n\n\/\/ TODO: maybe port FPS Counter from\n\/\/ #include \"vislib\/graphics\/FpsCounter.h\"\nvoid FrameStatistics_Service::start_frame() {\n m_frame_start_time = std::chrono::steady_clock::time_point::clock::now();\n}\n\nvoid FrameStatistics_Service::finish_frame() {\n auto now = std::chrono::steady_clock::time_point::clock::now();\n\n m_statistics.rendered_frames_count++;\n\n using double_seconds = std::chrono::duration<double>;\n using double_microseconds = std::chrono::duration<double, std::micro>;\n\n m_statistics.elapsed_program_time_seconds = double_seconds(now - m_program_start_time).count();\n const auto last_frame_till_now_micro = double_microseconds(now - m_frame_start_time).count();\n\n m_statistics.last_rendered_frame_time_milliseconds = last_frame_till_now_micro \/ 1000.0;\n\n m_frame_times_micro[m_ring_buffer_ptr] = static_cast<long long>(last_frame_till_now_micro);\n m_ring_buffer_ptr = (m_ring_buffer_ptr + 1) % m_frame_times_micro.size();\n\n m_statistics.last_averaged_mspf = std::accumulate(m_frame_times_micro.begin(), m_frame_times_micro.end(), 0) \/\n m_frame_times_micro.size() \/ static_cast<double>(1000);\n m_statistics.last_averaged_fps = 1000.0 \/ m_statistics.last_averaged_mspf;\n}\n\nvoid FrameStatistics_Service::fill_lua_callbacks() {\n frontend_resources::LuaCallbacksCollection callbacks;\n\n callbacks.add<frontend_resources::LuaCallbacksCollection::StringResult>(\"mmGetTimeStamp\",\n \"(void)\\n\\tReturns a timestamp in ISO format.\",\n {[&]() -> frontend_resources::LuaCallbacksCollection::StringResult {\n auto const tp = std::chrono::system_clock::now();\n auto const timestamp = core::utility::serialize_timestamp(tp);\n return frontend_resources::LuaCallbacksCollection::StringResult(timestamp);\n }});\n\n auto& register_callbacks =\n m_requestedResourceReferences[0]\n .getResource<std::function<void(frontend_resources::LuaCallbacksCollection const&)>>();\n\n register_callbacks(callbacks);\n}\n\n} \/\/ namespace frontend\n} \/\/ namespace megamol\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Advanced Normalization Tools\n Module: $RCSfile: AverageImages.cxx,v $\n Language: C++\n Date: $Date: 2009\/01\/27 23:25:24 $\n Version: $Revision: 1.21 $\n\n Copyright (c) ConsortiumOfANTS. All rights reserved.\n See accompanying COPYING.txt or\n http:\/\/sourceforge.net\/projects\/advants\/files\/ANTS\/ANTSCopyright.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ We divide the 2nd input image by its mean and add it to the first\n\/\/ input image with weight 1\/n.\n\/\/ The output overwrites the 1st img with the sum.\n\n\/\/ Note: could easily add variance computation\n\/\/ http:\/\/people.revoledu.com\/kardi\/tutorial\/RecursiveStatistic\/Time-Variance.htm\n\n#include \"itkArray.h\"\n#include \"itkVariableLengthVector.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkOptimalSharpeningImageFilter.h\"\n\ntemplate <unsigned int ImageDimension, unsigned int NVectorComponents>\nint AverageImages1(unsigned int argc, char *argv[])\n{\n typedef float PixelType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;\n typedef itk::ImageFileReader<ImageType> ImageFileReader;\n typedef itk::ImageFileWriter<ImageType> writertype;\n\n bool normalizei = atoi(argv[3]);\n float numberofimages = (float)argc - 4.;\n typename ImageType::Pointer averageimage = NULL;\n typename ImageType::Pointer image2 = NULL;\n\n typename ImageType::SizeType size;\n size.Fill(0);\n unsigned int bigimage = 0;\n for( unsigned int j = 4; j < argc; j++ )\n {\n \/\/ Get the image dimension\n std::string fn = std::string(argv[j]);\n std::cout << \" fn \" << fn << std::endl;\n typename itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(fn.c_str(), itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(fn.c_str() );\n imageIO->ReadImageInformation();\n for( unsigned int i = 0; i < imageIO->GetNumberOfDimensions(); i++ )\n {\n if( imageIO->GetDimensions(i) > size[i] )\n {\n size[i] = imageIO->GetDimensions(i);\n bigimage = j;\n std::cout << \" bigimage \" << j << \" size \" << size << std::endl;\n }\n }\n }\n\n std::cout << \" largest image \" << size << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[bigimage]);\n reader->Update();\n averageimage = reader->GetOutput();\n unsigned int vectorlength = reader->GetImageIO()->GetNumberOfComponents();\n std::cout << \" Averaging \" << numberofimages << \" images with dim = \" << ImageDimension << \" vector components \"\n << vectorlength << std::endl;\n PixelType meanval = 0;\n averageimage->FillBuffer(meanval);\n for( unsigned int j = 4; j < argc; j++ )\n {\n std::cout << \" reading \" << std::string(argv[j]) << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[j]);\n reader->Update();\n image2 = reader->GetOutput();\n Iterator vfIter2( image2, image2->GetLargestPossibleRegion() );\n unsigned long ct = 0;\n if( normalizei )\n {\n meanval = 0;\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType localp = image2->GetPixel( vfIter2.GetIndex() );\n meanval = meanval + localp;\n ct++;\n }\n if( ct > 0 )\n {\n meanval = meanval \/ (float)ct;\n }\n if( meanval <= 0 )\n {\n meanval = (1);\n }\n }\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType val = vfIter2.Get();\n if( normalizei )\n {\n val \/= meanval;\n }\n val = val \/ (float)numberofimages;\n PixelType oldval = averageimage->GetPixel(vfIter2.GetIndex() );\n averageimage->SetPixel(vfIter2.GetIndex(), val + oldval );\n }\n }\n\n typedef itk::OptimalSharpeningImageFilter<ImageType, ImageType> sharpeningFilter;\n typename sharpeningFilter::Pointer shFilter = sharpeningFilter::New();\n if( normalizei && argc > 3 && vectorlength == 1 )\n {\n shFilter->SetInput( averageimage );\n shFilter->SetSValue(0.5);\n averageimage = shFilter->GetOutput();\n }\n\n std::cout << \" writing output \";\n {\n typename writertype::Pointer writer = writertype::New();\n writer->SetFileName(argv[2]);\n writer->SetInput( averageimage );\n writer->Update();\n }\n\n return 0;\n}\n\ntemplate <unsigned int ImageDimension, unsigned int NVectorComponents>\nint AverageImages(unsigned int argc, char *argv[])\n{\n typedef itk::Vector<float, NVectorComponents> PixelType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;\n typedef itk::ImageFileReader<ImageType> ImageFileReader;\n typedef itk::ImageFileWriter<ImageType> writertype;\n\n bool normalizei = atoi(argv[3]);\n float numberofimages = (float)argc - 4.;\n typename ImageType::Pointer averageimage = NULL;\n typename ImageType::Pointer image2 = NULL;\n\n typename ImageType::SizeType size;\n size.Fill(0);\n unsigned int bigimage = 0;\n for( unsigned int j = 4; j < argc; j++ )\n {\n \/\/ Get the image dimension\n std::string fn = std::string(argv[j]);\n std::cout << \" fn \" << fn << std::endl;\n typename itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(fn.c_str(), itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(fn.c_str() );\n imageIO->ReadImageInformation();\n for( unsigned int i = 0; i < imageIO->GetNumberOfDimensions(); i++ )\n {\n if( imageIO->GetDimensions(i) > size[i] )\n {\n size[i] = imageIO->GetDimensions(i);\n bigimage = j;\n std::cout << \" bigimage \" << j << \" size \" << size << std::endl;\n }\n }\n }\n\n std::cout << \" largest image \" << size << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[bigimage]);\n reader->Update();\n averageimage = reader->GetOutput();\n unsigned int vectorlength = reader->GetImageIO()->GetNumberOfComponents();\n std::cout << \" Averaging \" << numberofimages << \" images with dim = \" << ImageDimension << \" vector components \"\n << vectorlength << std::endl;\n typename ImageType::IndexType zindex; zindex.Fill(0);\n PixelType meanval = reader->GetOutput()->GetPixel(zindex);\n meanval.Fill(0);\n averageimage->FillBuffer(meanval);\n for( unsigned int j = 4; j < argc; j++ )\n {\n std::cout << \" reading \" << std::string(argv[j]) << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[j]);\n reader->Update();\n image2 = reader->GetOutput();\n Iterator vfIter2( image2, image2->GetLargestPossibleRegion() );\n unsigned long ct = 0;\n if( normalizei )\n {\n meanval.Fill(0);\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType localp = image2->GetPixel( vfIter2.GetIndex() );\n meanval = meanval + localp;\n ct++;\n }\n if( ct > 0 )\n {\n meanval = meanval \/ (float)ct;\n }\n if( meanval.GetNorm() <= 0 )\n {\n meanval.Fill(1);\n }\n }\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType val = vfIter2.Get();\n if( normalizei )\n {\n for( unsigned int k = 0; k < vectorlength; k++ )\n {\n val[k] \/= meanval[k];\n }\n }\n val = val \/ (float)numberofimages;\n PixelType oldval = averageimage->GetPixel(vfIter2.GetIndex() );\n averageimage->SetPixel(vfIter2.GetIndex(), val + oldval );\n }\n }\n\n {\n typename writertype::Pointer writer = writertype::New();\n writer->SetFileName(argv[2]);\n writer->SetInput( averageimage );\n writer->Update();\n }\n\n return 0;\n}\n\nint main(int argc, char * argv[])\n{\n if( argc < 3 )\n {\n std::cout << \"\\n\" << std::endl;\n std::cout << \"Usage: \\n\" << std::endl;\n std::cout << argv[0] << \" ImageDimension Outputfname.nii.gz Normalize <images> \\n\" << std::endl;\n std::cout << \" Compulsory arguments: \\n\" << std::endl;\n std::cout << \" ImageDimension: 2 or 3 (for 2 or 3 dimensional input).\\n \" << std::endl;\n std::cout << \" Outputfname.nii.gz: the name of the resulting image.\\n\" << std::endl;\n std::cout\n <<\n \" Normalize: 0 (false) or 1 (true); if true, the 2nd image is divided by its mean. This will select the largest image to average into.\\n\"\n << std::endl;\n std::cout << \" Example Usage:\\n\" << std::endl;\n std::cout << argv[0] << \" 3 average.nii.gz 1 *.nii.gz \\n\" << std::endl;\n std::cout << \" \\n\" << std::endl;\n return 1;\n }\n\n int dim = atoi( argv[1] );\n itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(argv[4], itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(argv[4]);\n imageIO->ReadImageInformation();\n unsigned int ncomponents = imageIO->GetNumberOfComponents();\n\n \/\/ Get the image dimension\n switch( atoi(argv[1]) )\n {\n case 2:\n {\n switch( ncomponents )\n {\n case 2:\n {\n AverageImages<2, 2>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<2, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n case 3:\n {\n switch( ncomponents )\n {\n case 7:\n {\n AverageImages<3, 7>(argc, argv);\n }\n break;\n case 6:\n {\n AverageImages<3, 6>(argc, argv);\n }\n break;\n case 3:\n {\n AverageImages<3, 3>(argc, argv);\n }\n break;\n case 2:\n {\n AverageImages<3, 2>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<3, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n case 4:\n {\n switch( ncomponents )\n {\n case 7:\n {\n AverageImages<4, 7>(argc, argv);\n }\n break;\n case 6:\n {\n AverageImages<4, 6>(argc, argv);\n }\n break;\n case 4:\n {\n AverageImages<4, 4>(argc, argv);\n }\n break;\n case 3:\n {\n AverageImages<4, 3>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<4, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n default:\n std::cerr << \" You passed ImageDimension: \" << dim << \" . Please use only image domains of 2, 3 or 4 \"\n << std::endl;\n exit( EXIT_FAILURE );\n }\n\n return 0;\n}\n<commit_msg>BUG: ? possible bad behavior in an old averaging filter --- replacing with itk version <commit_after>\/*=========================================================================\n\n Program: Advanced Normalization Tools\n Module: $RCSfile: AverageImages.cxx,v $\n Language: C++\n Date: $Date: 2009\/01\/27 23:25:24 $\n Version: $Revision: 1.21 $\n\n Copyright (c) ConsortiumOfANTS. All rights reserved.\n See accompanying COPYING.txt or\n http:\/\/sourceforge.net\/projects\/advants\/files\/ANTS\/ANTSCopyright.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ We divide the 2nd input image by its mean and add it to the first\n\/\/ input image with weight 1\/n.\n\/\/ The output overwrites the 1st img with the sum.\n\n\/\/ Note: could easily add variance computation\n\/\/ http:\/\/people.revoledu.com\/kardi\/tutorial\/RecursiveStatistic\/Time-Variance.htm\n\n#include \"itkArray.h\"\n#include \"itkVariableLengthVector.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkOptimalSharpeningImageFilter.h\"\n#include \"itkLaplacianSharpeningImageFilter.h\"\n\ntemplate <unsigned int ImageDimension, unsigned int NVectorComponents>\nint AverageImages1(unsigned int argc, char *argv[])\n{\n typedef float PixelType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;\n typedef itk::ImageFileReader<ImageType> ImageFileReader;\n typedef itk::ImageFileWriter<ImageType> writertype;\n\n bool normalizei = atoi(argv[3]);\n float numberofimages = (float)argc - 4.;\n typename ImageType::Pointer averageimage = NULL;\n typename ImageType::Pointer image2 = NULL;\n\n typename ImageType::SizeType size;\n size.Fill(0);\n unsigned int bigimage = 0;\n for( unsigned int j = 4; j < argc; j++ )\n {\n \/\/ Get the image dimension\n std::string fn = std::string(argv[j]);\n std::cout << \" fn \" << fn << std::endl;\n typename itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(fn.c_str(), itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(fn.c_str() );\n imageIO->ReadImageInformation();\n for( unsigned int i = 0; i < imageIO->GetNumberOfDimensions(); i++ )\n {\n if( imageIO->GetDimensions(i) > size[i] )\n {\n size[i] = imageIO->GetDimensions(i);\n bigimage = j;\n std::cout << \" bigimage \" << j << \" size \" << size << std::endl;\n }\n }\n }\n\n std::cout << \" largest image \" << size << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[bigimage]);\n reader->Update();\n averageimage = reader->GetOutput();\n unsigned int vectorlength = reader->GetImageIO()->GetNumberOfComponents();\n std::cout << \" Averaging \" << numberofimages << \" images with dim = \" << ImageDimension << \" vector components \"\n << vectorlength << std::endl;\n PixelType meanval = 0;\n averageimage->FillBuffer(meanval);\n for( unsigned int j = 4; j < argc; j++ )\n {\n std::cout << \" reading \" << std::string(argv[j]) << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[j]);\n reader->Update();\n image2 = reader->GetOutput();\n Iterator vfIter2( image2, image2->GetLargestPossibleRegion() );\n unsigned long ct = 0;\n if( normalizei )\n {\n meanval = 0;\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType localp = image2->GetPixel( vfIter2.GetIndex() );\n meanval = meanval + localp;\n ct++;\n }\n if( ct > 0 )\n {\n meanval = meanval \/ (float)ct;\n }\n if( meanval <= 0 )\n {\n meanval = (1);\n }\n }\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType val = vfIter2.Get();\n if( normalizei )\n {\n val \/= meanval;\n }\n val = val \/ (float)numberofimages;\n PixelType oldval = averageimage->GetPixel(vfIter2.GetIndex() );\n averageimage->SetPixel(vfIter2.GetIndex(), val + oldval );\n }\n }\n\n \/\/ typedef itk::OptimalSharpeningImageFilter<ImageType,ImageType > sharpeningFilter;\n typedef itk::LaplacianSharpeningImageFilter<ImageType, ImageType> sharpeningFilter;\n typename sharpeningFilter::Pointer shFilter = sharpeningFilter::New();\n if( normalizei && argc > 3 && vectorlength == 1 )\n {\n shFilter->SetInput( averageimage );\n \/\/ shFilter->SetSValue(0.5);\n averageimage = shFilter->GetOutput();\n }\n\n std::cout << \" writing output \";\n {\n typename writertype::Pointer writer = writertype::New();\n writer->SetFileName(argv[2]);\n writer->SetInput( averageimage );\n writer->Update();\n }\n\n return 0;\n}\n\ntemplate <unsigned int ImageDimension, unsigned int NVectorComponents>\nint AverageImages(unsigned int argc, char *argv[])\n{\n typedef itk::Vector<float, NVectorComponents> PixelType;\n typedef itk::Image<PixelType, ImageDimension> ImageType;\n typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;\n typedef itk::ImageFileReader<ImageType> ImageFileReader;\n typedef itk::ImageFileWriter<ImageType> writertype;\n\n bool normalizei = atoi(argv[3]);\n float numberofimages = (float)argc - 4.;\n typename ImageType::Pointer averageimage = NULL;\n typename ImageType::Pointer image2 = NULL;\n\n typename ImageType::SizeType size;\n size.Fill(0);\n unsigned int bigimage = 0;\n for( unsigned int j = 4; j < argc; j++ )\n {\n \/\/ Get the image dimension\n std::string fn = std::string(argv[j]);\n std::cout << \" fn \" << fn << std::endl;\n typename itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(fn.c_str(), itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(fn.c_str() );\n imageIO->ReadImageInformation();\n for( unsigned int i = 0; i < imageIO->GetNumberOfDimensions(); i++ )\n {\n if( imageIO->GetDimensions(i) > size[i] )\n {\n size[i] = imageIO->GetDimensions(i);\n bigimage = j;\n std::cout << \" bigimage \" << j << \" size \" << size << std::endl;\n }\n }\n }\n\n std::cout << \" largest image \" << size << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[bigimage]);\n reader->Update();\n averageimage = reader->GetOutput();\n unsigned int vectorlength = reader->GetImageIO()->GetNumberOfComponents();\n std::cout << \" Averaging \" << numberofimages << \" images with dim = \" << ImageDimension << \" vector components \"\n << vectorlength << std::endl;\n typename ImageType::IndexType zindex; zindex.Fill(0);\n PixelType meanval = reader->GetOutput()->GetPixel(zindex);\n meanval.Fill(0);\n averageimage->FillBuffer(meanval);\n for( unsigned int j = 4; j < argc; j++ )\n {\n std::cout << \" reading \" << std::string(argv[j]) << std::endl;\n typename ImageFileReader::Pointer reader = ImageFileReader::New();\n reader->SetFileName(argv[j]);\n reader->Update();\n image2 = reader->GetOutput();\n Iterator vfIter2( image2, image2->GetLargestPossibleRegion() );\n unsigned long ct = 0;\n if( normalizei )\n {\n meanval.Fill(0);\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType localp = image2->GetPixel( vfIter2.GetIndex() );\n meanval = meanval + localp;\n ct++;\n }\n if( ct > 0 )\n {\n meanval = meanval \/ (float)ct;\n }\n if( meanval.GetNorm() <= 0 )\n {\n meanval.Fill(1);\n }\n }\n for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )\n {\n PixelType val = vfIter2.Get();\n if( normalizei )\n {\n for( unsigned int k = 0; k < vectorlength; k++ )\n {\n val[k] \/= meanval[k];\n }\n }\n val = val \/ (float)numberofimages;\n PixelType oldval = averageimage->GetPixel(vfIter2.GetIndex() );\n averageimage->SetPixel(vfIter2.GetIndex(), val + oldval );\n }\n }\n\n {\n typename writertype::Pointer writer = writertype::New();\n writer->SetFileName(argv[2]);\n writer->SetInput( averageimage );\n writer->Update();\n }\n\n return 0;\n}\n\nint main(int argc, char * argv[])\n{\n if( argc < 3 )\n {\n std::cout << \"\\n\" << std::endl;\n std::cout << \"Usage: \\n\" << std::endl;\n std::cout << argv[0] << \" ImageDimension Outputfname.nii.gz Normalize <images> \\n\" << std::endl;\n std::cout << \" Compulsory arguments: \\n\" << std::endl;\n std::cout << \" ImageDimension: 2 or 3 (for 2 or 3 dimensional input).\\n \" << std::endl;\n std::cout << \" Outputfname.nii.gz: the name of the resulting image.\\n\" << std::endl;\n std::cout\n <<\n \" Normalize: 0 (false) or 1 (true); if true, the 2nd image is divided by its mean. This will select the largest image to average into.\\n\"\n << std::endl;\n std::cout << \" Example Usage:\\n\" << std::endl;\n std::cout << argv[0] << \" 3 average.nii.gz 1 *.nii.gz \\n\" << std::endl;\n std::cout << \" \\n\" << std::endl;\n return 1;\n }\n\n int dim = atoi( argv[1] );\n itk::ImageIOBase::Pointer imageIO =\n itk::ImageIOFactory::CreateImageIO(argv[4], itk::ImageIOFactory::ReadMode);\n imageIO->SetFileName(argv[4]);\n imageIO->ReadImageInformation();\n unsigned int ncomponents = imageIO->GetNumberOfComponents();\n\n \/\/ Get the image dimension\n switch( atoi(argv[1]) )\n {\n case 2:\n {\n switch( ncomponents )\n {\n case 2:\n {\n AverageImages<2, 2>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<2, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n case 3:\n {\n switch( ncomponents )\n {\n case 7:\n {\n AverageImages<3, 7>(argc, argv);\n }\n break;\n case 6:\n {\n AverageImages<3, 6>(argc, argv);\n }\n break;\n case 3:\n {\n AverageImages<3, 3>(argc, argv);\n }\n break;\n case 2:\n {\n AverageImages<3, 2>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<3, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n case 4:\n {\n switch( ncomponents )\n {\n case 7:\n {\n AverageImages<4, 7>(argc, argv);\n }\n break;\n case 6:\n {\n AverageImages<4, 6>(argc, argv);\n }\n break;\n case 4:\n {\n AverageImages<4, 4>(argc, argv);\n }\n break;\n case 3:\n {\n AverageImages<4, 3>(argc, argv);\n }\n break;\n default:\n {\n AverageImages1<4, 1>(argc, argv);\n }\n break;\n }\n }\n break;\n default:\n std::cerr << \" You passed ImageDimension: \" << dim << \" . Please use only image domains of 2, 3 or 4 \"\n << std::endl;\n exit( EXIT_FAILURE );\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Effect.cpp\n\/\/ Audio Test\n\/\/\n\/\/ Created by Matthew Bucci on 2\/6\/14.\n\/\/ Copyright (c) 2014 Matthew Bucci. All rights reserved.\n\/\/\n\n#include \"Effect.h\"\n\nEffect::Effect() {\n Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096);\n cout << \"Loading effects\" << endl;\n load_files();\n event test;\n test.type=\"ui-newability\";\n test.id=5;\n PlayEffect(test);\n}\n\nvoid Effect::PlayEffect(event action) {\n if(action.type==\"player-walk\"){\n if(foot)\n Mix_PlayChannel(-1,effects[\"player-left-foot\"],0);\n else\n Mix_PlayChannel(-1,effects[\"player-right-foot\"],0);\n }\n else {\n Mix_PlayChannel(-1,effects[action.type],0);\n }\n}\n\nbool Effect::load_files() {\n \/\/Load the music\n fstream File(\"sounds\/Effects.txt\");\n string tmp;\n \/\/Effect File Defintion Format\n \/\/EffectName pathtofile\n while(File) {\n \/\/super ineffecient but garuntees broken lines won't mess up the rest\n getline(File,tmp);\n stringstream ss(tmp);\n vector<string> params;\n \n while (ss >> tmp) {\n params.push_back(tmp);\n }\n \n \/\/ignore comment lines\n if(params.size() == 2) {\n if(params[0].substr(0,2) != \"\/\/\") {\n cout << \"Loaded: \" << params[0]<< endl;\n effects.insert ( pair<string,Mix_Chunk*>(params[0],Mix_LoadWAV(params[1].c_str())) );\n }\n }\n params.clear();\n }\n File.close();\n \n \n return true;\n}\n\nvoid Effect::SetVolume(uint8_t volume) {\n this->volume = volume;\n \n \/\/sets unallocated channels to new volume\n Mix_Volume(-1, volume);\n \n \/\/need to add a loop to adjust allocated channels\n}<commit_msg>now android can play with the big boys<commit_after>\/\/\n\/\/ Effect.cpp\n\/\/ Audio Test\n\/\/\n\/\/ Created by Matthew Bucci on 2\/6\/14.\n\/\/ Copyright (c) 2014 Matthew Bucci. All rights reserved.\n\/\/\n\n#include \"Effect.h\"\n\nEffect::Effect() {\n Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096);\n cout << \"Loading effects\" << endl;\n load_files();\n event test;\n test.type=\"ui-newability\";\n test.id=5;\n PlayEffect(test);\n}\n\nvoid Effect::PlayEffect(event action) {\n if(action.type==\"player-walk\"){\n if(foot)\n Mix_PlayChannel(-1,effects[\"player-left-foot\"],0);\n else\n Mix_PlayChannel(-1,effects[\"player-right-foot\"],0);\n }\n else {\n Mix_PlayChannel(-1,effects[action.type],0);\n }\n}\n\n\nvoid ReadFiles(string data, map<string,Mix_Chunk*>& effects) {\n\n \n}\nbool Effect::load_files() {\n \/\/Load the effects\n string filename = \"sounds\/Effects.txt\";\n \n\tSDL_RWops *file = SDL_RWFromFile(filename.c_str(), \"r\");\n\tlong size;\n\t\n\tcout << \"Parsing particle file \\\"\" << filename << \"\\\":\";\n \n\tif(!file) {\n\t\tcout << \"\\nFailed to open particle data file \\\"\" << filename << \"\\\"\\n\";\n\t\treturn NULL;\n\t}\n \n\t\/\/Use the SDL system to read the file\n\tSDL_RWseek(file , 0 , RW_SEEK_END);\n\tsize = (long)SDL_RWtell(file);\n\tSDL_RWseek(file,0,RW_SEEK_SET);\n \n\tchar * fileData = new char[size];\n\tSDL_RWread(file,fileData, 1, (size_t)size);\n\tSDL_RWclose(file);\n \n stringstream File(string(fileData,size));\n \n string tmp;\n \/\/Effect File Defintion Format\n \/\/EffectName pathtofile\n while(File) {\n \/\/super ineffecient but garuntees broken lines won't mess up the rest\n getline(File,tmp);\n stringstream ss(tmp);\n vector<string> params;\n \n while (ss >> tmp) {\n params.push_back(tmp);\n }\n \n \/\/ignore comment lines\n if(params.size() == 2) {\n if(params[0].substr(0,2) != \"\/\/\") {\n cout << \"Loaded: \" << params[0]<< endl;\n effects.insert ( pair<string,Mix_Chunk*>(params[0],Mix_LoadWAV(params[1].c_str())) );\n }\n }\n params.clear();\n }\n\n \n \n return true;\n}\n\nvoid Effect::SetVolume(uint8_t volume) {\n this->volume = volume;\n \n \/\/sets unallocated channels to new volume\n Mix_Volume(-1, volume);\n \n \/\/need to add a loop to adjust allocated channels\n}<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <sstream>\n#include <string>\n#include <string.h>\n#include <libwpd-stream\/WPXStream.h>\n#include \"MSPUBParser.h\"\n#include \"MSPUBCollector.h\"\n#include \"libmspub_utils.h\"\n\nlibmspub::MSPUBParser::MSPUBParser(WPXInputStream *input, MSPUBCollector *collector)\n : m_input(input), m_collector(collector), m_blockInfo(), m_lastSeenSeqNum(-1)\n{\n}\n\nlibmspub::MSPUBParser::~MSPUBParser()\n{\n}\n\nshort libmspub::MSPUBParser::getBlockDataLength(unsigned type) \/\/ -1 for variable-length block with the data length as the first DWORD\n{\n switch(type)\n {\n case 0x78:\n case 0x5:\n case 0x8:\n case 0xa:\n return 0;\n case 0x10:\n case 0x12:\n case 0x18:\n case 0x1a:\n return 2;\n case 0x20:\n case 0x22:\n case 0x28:\n case 0x48:\n case 0x58:\n case 0x68:\n case 0x70:\n case 0xb8:\n return 4;\n case 0x38:\n return 16;\n case 0xc0:\n case 0x80:\n case 0x82:\n case 0x88:\n case 0x8a:\n case 0x90:\n case 0x98:\n case 0xa0:\n return -1;\n }\n \/\/FIXME: Debug assertion here? Should never get here.\n return 0;\n}\n\nbool libmspub::MSPUBParser::parse()\n{\n if (!m_input->isOLEStream())\n return false;\n WPXInputStream *quill = m_input->getDocumentOLEStream(\"Quill\/QuillSub\/CONTENTS\");\n if (!quill)\n return false;\n if (!parseQuill(quill))\n {\n delete quill;\n return false;\n }\n delete quill;\n WPXInputStream *escher = m_input->getDocumentOLEStream(\"Escher\/EscherStm\");\n if (!escher)\n return false;\n if (!parseEscher(escher))\n {\n delete escher;\n return false;\n }\n delete escher;\n WPXInputStream *contents = m_input->getDocumentOLEStream(\"Contents\");\n if (!contents)\n return false;\n if (!parseContents(contents))\n {\n delete contents;\n return false;\n }\n delete contents;\n return true;\n}\n\nbool libmspub::MSPUBParser::parseContents(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseContents\\n\"));\n input->seek(0x1a, WPX_SEEK_SET);\n\n unsigned trailerOffset = readU32(input);\n MSPUB_DEBUG_MSG((\"MSPUBParser: trailerOffset %.8x\\n\", trailerOffset));\n input->seek(trailerOffset, WPX_SEEK_SET);\n unsigned trailerLength = readU32(input);\n for (unsigned i=0; i<3; i++)\n {\n libmspub::MSPUBBlockInfo trailerPart = parseBlock(input);\n MSPUB_DEBUG_MSG((\"Trailer SubBlock %i, startPosition 0x%lx, id %i, type 0x%x, dataLength 0x%lx\\n\", i+1, trailerPart.startPosition, trailerPart.id, trailerPart.type, trailerPart.dataLength));\n if (trailerPart.type == 0x90)\n {\n while (input->tell() >= 0 && (unsigned)input->tell() < trailerPart.dataOffset + trailerPart.dataLength)\n {\n m_blockInfo.push_back(parseBlock(input));\n ++m_lastSeenSeqNum;\n if (m_blockInfo.back().type == 0x88)\n {\n parseChunkReference(input, m_blockInfo.back());\n }\n }\n for (MSPUBCollector::cr_iterator_t i = m_collector->getChunkReferences().begin(); i != m_collector->getChunkReferences().end(); ++i)\n {\n if (i->type == 0x44)\n {\n input->seek(i->offset, WPX_SEEK_SET);\n if (!parseDocumentChunk(input, *i))\n {\n return false;\n }\n }\n else if (i->type == 0x43)\n {\n input->seek(i->offset, WPX_SEEK_SET);\n if (!parsePageChunk(input, *i))\n {\n return false;\n }\n }\n }\n m_collector->pagesOver();\n }\n }\n input->seek(trailerOffset + trailerLength, WPX_SEEK_SET);\n\n return true;\n}\n\nbool libmspub::MSPUBParser::parseDocumentChunk(WPXInputStream *input, const ChunkReference &chunk)\n{\n readU32(input); \/\/FIXME: This is the length. Might want to verify that it matches the length we got from subtracting the start of this chunk from the start of the next one.\n while (input->tell() >= 0 && (unsigned)input->tell() < chunk.end)\n {\n libmspub::MSPUBBlockInfo info = parseBlock(input);\n if (info.id == 0x12)\n {\n while (input->tell() >= 0 && (unsigned)input->tell() < info.dataOffset + info.dataLength)\n {\n libmspub::MSPUBBlockInfo subInfo = parseBlock(input, true);\n if (subInfo.id == 0x1)\n {\n m_collector->setWidthInEmu(subInfo.data);\n }\n else if (subInfo.id == 0x2)\n {\n m_collector->setHeightInEmu(subInfo.data);\n }\n }\n }\n else\n {\n skipBlock(input, info);\n }\n }\n return true; \/\/FIXME: return false for failure\n}\n\n\nbool libmspub::MSPUBParser::parsePageChunk(WPXInputStream *input, const ChunkReference &chunk)\n{\n MSPUB_DEBUG_MSG((\"parsePageChunk: offset 0x%lx, end 0x%lx, seqnum 0x%x, parent 0x%x\\n\", input->tell(), chunk.end, chunk.seqNum, chunk.parentSeqNum));\n if (getPageTypeBySeqNum(chunk.seqNum) == NORMAL)\n {\n m_collector->addPage();\n }\n return true;\n}\n\nbool libmspub::MSPUBParser::parseQuill(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseQuill\\n\"));\n return true;\n}\n\nbool libmspub::MSPUBParser::parseEscher(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseEscher\\n\"));\n return true;\n}\n\nbool libmspub::MSPUBParser::parseChunkReference(WPXInputStream *input, const libmspub::MSPUBBlockInfo block)\n{\n \/\/input should be at block.dataOffset + 4 , that is, at the beginning of the list of sub-blocks\n unsigned type = 0;\n unsigned long offset = 0;\n unsigned parentSeqNum = 0;\n bool seenType = false;\n bool seenOffset = false;\n bool seenParentSeqNum = false;\n while (input->tell() >= 0 && (unsigned)input->tell() < block.dataOffset + block.dataLength)\n {\n libmspub::MSPUBBlockInfo subBlock = parseBlock(input);\n \/\/FIXME: Warn if multiple of these blocks seen.\n if (subBlock.id == 0x2)\n {\n type = (unsigned)subBlock.data;\n seenType = true;\n }\n else if (subBlock.id == 0x4)\n {\n offset = subBlock.data;\n seenOffset = true;\n }\n else if (subBlock.id == 0x5)\n {\n parentSeqNum = subBlock.data;\n seenParentSeqNum = true;\n }\n }\n if (seenType && seenOffset)\n {\n m_collector->addChunkReference(type, offset, m_lastSeenSeqNum, seenParentSeqNum ? parentSeqNum : 0);\n return true;\n }\n return false;\n}\n\nbool libmspub::MSPUBParser::isBlockDataString(unsigned type)\n{\n return type == 0xc0;\n}\nvoid libmspub::MSPUBParser::skipBlock(WPXInputStream *input, libmspub::MSPUBBlockInfo block)\n{\n input->seek(block.dataOffset + block.dataLength, WPX_SEEK_SET);\n}\nlibmspub::MSPUBBlockInfo libmspub::MSPUBParser::parseBlock(WPXInputStream *input, bool skipHierarchicalData)\n{\n libmspub::MSPUBBlockInfo info;\n info.startPosition = input->tell();\n info.id = readU8(input);\n info.type = readU8(input);\n info.dataOffset = input->tell();\n int len = getBlockDataLength(info.type);\n bool varLen = len < 0;\n if (varLen)\n {\n info.dataLength = readU32(input);\n if (isBlockDataString(info.type))\n {\n info.stringData = std::vector<char>(info.dataLength - 1);\n for (unsigned i = 0; i < info.dataLength - 1; ++i)\n {\n info.stringData[i] = readU8(input);\n }\n }\n else if (skipHierarchicalData)\n {\n skipBlock(input, info);\n }\n info.data = 0;\n }\n else\n {\n info.dataLength = len;\n switch (info.dataLength)\n {\n case 1:\n info.data = readU8(input);\n break;\n case 2:\n info.data = readU16(input);\n break;\n case 4:\n info.data = readU32(input);\n break;\n default:\n info.data = 0;\n }\n }\n MSPUB_DEBUG_MSG((\"parseBlock dataOffset 0x%lx, id 0x%x, type 0x%x, dataLength %lu, integral data 0x%lx\\n\", info.dataOffset, info.id, info.type, info.dataLength, info.data));\n return info;\n}\n\nlibmspub::PageType libmspub::MSPUBParser::getPageTypeBySeqNum(unsigned seqNum)\n{\n switch(seqNum)\n {\n case 0x107:\n return MASTER;\n case 0x10d:\n case 0x110:\n case 0x113:\n case 0x117:\n return DUMMY;\n default:\n return NORMAL;\n }\n}\n\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>Valek knows more about 0x48<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <sstream>\n#include <string>\n#include <string.h>\n#include <libwpd-stream\/WPXStream.h>\n#include \"MSPUBParser.h\"\n#include \"MSPUBCollector.h\"\n#include \"libmspub_utils.h\"\n\nlibmspub::MSPUBParser::MSPUBParser(WPXInputStream *input, MSPUBCollector *collector)\n : m_input(input), m_collector(collector), m_blockInfo(), m_lastSeenSeqNum(-1)\n{\n}\n\nlibmspub::MSPUBParser::~MSPUBParser()\n{\n}\n\nshort libmspub::MSPUBParser::getBlockDataLength(unsigned type) \/\/ -1 for variable-length block with the data length as the first DWORD\n{\n switch(type)\n {\n case 0x78:\n case 0x5:\n case 0x8:\n case 0xa:\n return 0;\n case 0x10:\n case 0x12:\n case 0x18:\n case 0x1a:\n return 2;\n case 0x20:\n case 0x22:\n case 0x28:\n case 0x58:\n case 0x68:\n case 0x70:\n case 0xb8:\n return 4;\n case 0x38:\n return 16;\n case 0x48:\n return 24;\n case 0xc0:\n case 0x80:\n case 0x82:\n case 0x88:\n case 0x8a:\n case 0x90:\n case 0x98:\n case 0xa0:\n return -1;\n }\n \/\/FIXME: Debug assertion here? Should never get here.\n return 0;\n}\n\nbool libmspub::MSPUBParser::parse()\n{\n if (!m_input->isOLEStream())\n return false;\n WPXInputStream *quill = m_input->getDocumentOLEStream(\"Quill\/QuillSub\/CONTENTS\");\n if (!quill)\n return false;\n if (!parseQuill(quill))\n {\n delete quill;\n return false;\n }\n delete quill;\n WPXInputStream *escher = m_input->getDocumentOLEStream(\"Escher\/EscherStm\");\n if (!escher)\n return false;\n if (!parseEscher(escher))\n {\n delete escher;\n return false;\n }\n delete escher;\n WPXInputStream *contents = m_input->getDocumentOLEStream(\"Contents\");\n if (!contents)\n return false;\n if (!parseContents(contents))\n {\n delete contents;\n return false;\n }\n delete contents;\n return true;\n}\n\nbool libmspub::MSPUBParser::parseContents(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseContents\\n\"));\n input->seek(0x1a, WPX_SEEK_SET);\n\n unsigned trailerOffset = readU32(input);\n MSPUB_DEBUG_MSG((\"MSPUBParser: trailerOffset %.8x\\n\", trailerOffset));\n input->seek(trailerOffset, WPX_SEEK_SET);\n unsigned trailerLength = readU32(input);\n for (unsigned i=0; i<3; i++)\n {\n libmspub::MSPUBBlockInfo trailerPart = parseBlock(input);\n MSPUB_DEBUG_MSG((\"Trailer SubBlock %i, startPosition 0x%lx, id %i, type 0x%x, dataLength 0x%lx\\n\", i+1, trailerPart.startPosition, trailerPart.id, trailerPart.type, trailerPart.dataLength));\n if (trailerPart.type == 0x90)\n {\n while (input->tell() >= 0 && (unsigned)input->tell() < trailerPart.dataOffset + trailerPart.dataLength)\n {\n m_blockInfo.push_back(parseBlock(input));\n ++m_lastSeenSeqNum;\n if (m_blockInfo.back().type == 0x88)\n {\n parseChunkReference(input, m_blockInfo.back());\n }\n }\n for (MSPUBCollector::cr_iterator_t i = m_collector->getChunkReferences().begin(); i != m_collector->getChunkReferences().end(); ++i)\n {\n if (i->type == 0x44)\n {\n input->seek(i->offset, WPX_SEEK_SET);\n if (!parseDocumentChunk(input, *i))\n {\n return false;\n }\n }\n else if (i->type == 0x43)\n {\n input->seek(i->offset, WPX_SEEK_SET);\n if (!parsePageChunk(input, *i))\n {\n return false;\n }\n }\n }\n m_collector->pagesOver();\n }\n }\n input->seek(trailerOffset + trailerLength, WPX_SEEK_SET);\n\n return true;\n}\n\nbool libmspub::MSPUBParser::parseDocumentChunk(WPXInputStream *input, const ChunkReference &chunk)\n{\n readU32(input); \/\/FIXME: This is the length. Might want to verify that it matches the length we got from subtracting the start of this chunk from the start of the next one.\n while (input->tell() >= 0 && (unsigned)input->tell() < chunk.end)\n {\n libmspub::MSPUBBlockInfo info = parseBlock(input);\n if (info.id == 0x12)\n {\n while (input->tell() >= 0 && (unsigned)input->tell() < info.dataOffset + info.dataLength)\n {\n libmspub::MSPUBBlockInfo subInfo = parseBlock(input, true);\n if (subInfo.id == 0x1)\n {\n m_collector->setWidthInEmu(subInfo.data);\n }\n else if (subInfo.id == 0x2)\n {\n m_collector->setHeightInEmu(subInfo.data);\n }\n }\n }\n else\n {\n skipBlock(input, info);\n }\n }\n return true; \/\/FIXME: return false for failure\n}\n\n\nbool libmspub::MSPUBParser::parsePageChunk(WPXInputStream *input, const ChunkReference &chunk)\n{\n MSPUB_DEBUG_MSG((\"parsePageChunk: offset 0x%lx, end 0x%lx, seqnum 0x%x, parent 0x%x\\n\", input->tell(), chunk.end, chunk.seqNum, chunk.parentSeqNum));\n if (getPageTypeBySeqNum(chunk.seqNum) == NORMAL)\n {\n m_collector->addPage();\n }\n return true;\n}\n\nbool libmspub::MSPUBParser::parseQuill(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseQuill\\n\"));\n return true;\n}\n\nbool libmspub::MSPUBParser::parseEscher(WPXInputStream *input)\n{\n MSPUB_DEBUG_MSG((\"MSPUBParser::parseEscher\\n\"));\n return true;\n}\n\nbool libmspub::MSPUBParser::parseChunkReference(WPXInputStream *input, const libmspub::MSPUBBlockInfo block)\n{\n \/\/input should be at block.dataOffset + 4 , that is, at the beginning of the list of sub-blocks\n unsigned type = 0;\n unsigned long offset = 0;\n unsigned parentSeqNum = 0;\n bool seenType = false;\n bool seenOffset = false;\n bool seenParentSeqNum = false;\n while (input->tell() >= 0 && (unsigned)input->tell() < block.dataOffset + block.dataLength)\n {\n libmspub::MSPUBBlockInfo subBlock = parseBlock(input);\n \/\/FIXME: Warn if multiple of these blocks seen.\n if (subBlock.id == 0x2)\n {\n type = (unsigned)subBlock.data;\n seenType = true;\n }\n else if (subBlock.id == 0x4)\n {\n offset = subBlock.data;\n seenOffset = true;\n }\n else if (subBlock.id == 0x5)\n {\n parentSeqNum = subBlock.data;\n seenParentSeqNum = true;\n }\n }\n if (seenType && seenOffset)\n {\n m_collector->addChunkReference(type, offset, m_lastSeenSeqNum, seenParentSeqNum ? parentSeqNum : 0);\n return true;\n }\n return false;\n}\n\nbool libmspub::MSPUBParser::isBlockDataString(unsigned type)\n{\n return type == 0xc0;\n}\nvoid libmspub::MSPUBParser::skipBlock(WPXInputStream *input, libmspub::MSPUBBlockInfo block)\n{\n input->seek(block.dataOffset + block.dataLength, WPX_SEEK_SET);\n}\nlibmspub::MSPUBBlockInfo libmspub::MSPUBParser::parseBlock(WPXInputStream *input, bool skipHierarchicalData)\n{\n libmspub::MSPUBBlockInfo info;\n info.startPosition = input->tell();\n info.id = readU8(input);\n info.type = readU8(input);\n info.dataOffset = input->tell();\n int len = getBlockDataLength(info.type);\n bool varLen = len < 0;\n if (varLen)\n {\n info.dataLength = readU32(input);\n if (isBlockDataString(info.type))\n {\n info.stringData = std::vector<char>(info.dataLength - 1);\n for (unsigned i = 0; i < info.dataLength - 1; ++i)\n {\n info.stringData[i] = readU8(input);\n }\n }\n else if (skipHierarchicalData)\n {\n skipBlock(input, info);\n }\n info.data = 0;\n }\n else\n {\n info.dataLength = len;\n switch (info.dataLength)\n {\n case 1:\n info.data = readU8(input);\n break;\n case 2:\n info.data = readU16(input);\n break;\n case 4:\n info.data = readU32(input);\n break;\n default:\n info.data = 0;\n }\n }\n MSPUB_DEBUG_MSG((\"parseBlock dataOffset 0x%lx, id 0x%x, type 0x%x, dataLength %lu, integral data 0x%lx\\n\", info.dataOffset, info.id, info.type, info.dataLength, info.data));\n return info;\n}\n\nlibmspub::PageType libmspub::MSPUBParser::getPageTypeBySeqNum(unsigned seqNum)\n{\n switch(seqNum)\n {\n case 0x107:\n return MASTER;\n case 0x10d:\n case 0x110:\n case 0x113:\n case 0x117:\n return DUMMY;\n default:\n return NORMAL;\n }\n}\n\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n* (C) 2015,2017 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/ffi.h>\n#include <botan\/internal\/ffi_util.h>\n#include <botan\/internal\/ffi_rng.h>\n#include <botan\/pbkdf.h>\n#include <botan\/kdf.h>\n\n#if defined(BOTAN_HAS_BCRYPT)\n #include <botan\/bcrypt.h>\n#endif\n\n#if defined(BOTAN_HAS_SCRYPT)\n #include <botan\/scrypt.h>\n#endif\n\nextern \"C\" {\n\nusing namespace Botan_FFI;\n\nint botan_pbkdf(const char* algo, uint8_t out[], size_t out_len,\n const char* pass, const uint8_t salt[], size_t salt_len,\n size_t iterations)\n {\n return botan_pwdhash(algo,\n iterations,\n 0,\n 0,\n out, out_len,\n pass, 0,\n salt, salt_len);\n }\n\nint botan_pbkdf_timed(const char* algo,\n uint8_t out[], size_t out_len,\n const char* password,\n const uint8_t salt[], size_t salt_len,\n size_t ms_to_run,\n size_t* iterations_used)\n {\n return botan_pwdhash_timed(algo,\n static_cast<uint32_t>(ms_to_run),\n iterations_used,\n nullptr,\n nullptr,\n out, out_len,\n password, 0,\n salt, salt_len);\n }\n\nint botan_pwdhash(\n const char* algo,\n size_t param1,\n size_t param2,\n size_t param3,\n uint8_t out[],\n size_t out_len,\n const char* password,\n size_t password_len,\n const uint8_t salt[],\n size_t salt_len)\n {\n if(algo == nullptr || password == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(password_len == 0)\n password_len = std::strlen(password);\n\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n auto pwdhash_fam = Botan::PasswordHashFamily::create(algo);\n\n if(!pwdhash_fam)\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n\n auto pwdhash = pwdhash_fam->from_params(param1, param2, param3);\n\n pwdhash->derive_key(out, out_len,\n password, password_len,\n salt, salt_len);\n\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_pwdhash_timed(\n const char* algo,\n uint32_t msec,\n size_t* param1,\n size_t* param2,\n size_t* param3,\n uint8_t out[],\n size_t out_len,\n const char* password,\n size_t password_len,\n const uint8_t salt[],\n size_t salt_len)\n {\n if(algo == nullptr || password == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(password_len == 0)\n password_len = std::strlen(password);\n\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n\n auto pwdhash_fam = Botan::PasswordHashFamily::create(algo);\n\n if(!pwdhash_fam)\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n\n auto pwdhash = pwdhash_fam->tune(out_len, std::chrono::milliseconds(msec));\n\n if(param1)\n *param1 = pwdhash->iterations();\n if(param2)\n *param2 = pwdhash->parallelism();\n if(param3)\n *param3 = pwdhash->memory_param();\n\n pwdhash->derive_key(out, out_len,\n password, password_len,\n salt, salt_len);\n\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_kdf(const char* kdf_algo,\n uint8_t out[], size_t out_len,\n const uint8_t secret[], size_t secret_len,\n const uint8_t salt[], size_t salt_len,\n const uint8_t label[], size_t label_len)\n {\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n std::unique_ptr<Botan::KDF> kdf(Botan::get_kdf(kdf_algo));\n kdf->kdf(out, out_len, secret, secret_len, salt, salt_len, label, label_len);\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_scrypt(uint8_t out[], size_t out_len,\n const char* password,\n const uint8_t salt[], size_t salt_len,\n size_t N, size_t r, size_t p)\n {\n#if defined(BOTAN_HAS_SCRYPT)\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n Botan::scrypt(out, out_len, password, strlen(password), salt, salt_len, N, r, p);\n return BOTAN_FFI_SUCCESS;\n });\n#else\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n#endif\n }\n\nint botan_bcrypt_generate(uint8_t* out, size_t* out_len,\n const char* pass,\n botan_rng_t rng_obj, size_t wf,\n uint32_t flags)\n {\n#if defined(BOTAN_HAS_BCRYPT)\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n if(out == nullptr || out_len == nullptr || pass == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(flags != 0)\n return BOTAN_FFI_ERROR_BAD_FLAG;\n\n if(wf < 4 || wf > 18)\n return BOTAN_FFI_ERROR_BAD_PARAMETER;\n\n Botan::RandomNumberGenerator& rng = safe_get(rng_obj);\n const std::string bcrypt = Botan::generate_bcrypt(pass, rng, static_cast<uint16_t>(wf));\n return write_str_output(out, out_len, bcrypt);\n });\n#else\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n#endif\n }\n\nint botan_bcrypt_is_valid(const char* pass, const char* hash)\n {\n#if defined(BOTAN_HAS_BCRYPT)\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n return Botan::check_bcrypt(pass, hash) ? BOTAN_FFI_SUCCESS : BOTAN_FFI_INVALID_VERIFIER;\n });\n#else\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n#endif\n }\n\n}\n<commit_msg>Define botan_scrypt in terms of botan_pwdhash<commit_after>\/*\n* (C) 2015,2017 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/ffi.h>\n#include <botan\/internal\/ffi_util.h>\n#include <botan\/internal\/ffi_rng.h>\n#include <botan\/pbkdf.h>\n#include <botan\/pwdhash.h>\n#include <botan\/kdf.h>\n\n#if defined(BOTAN_HAS_BCRYPT)\n #include <botan\/bcrypt.h>\n#endif\n\nextern \"C\" {\n\nusing namespace Botan_FFI;\n\nint botan_pbkdf(const char* algo, uint8_t out[], size_t out_len,\n const char* pass, const uint8_t salt[], size_t salt_len,\n size_t iterations)\n {\n return botan_pwdhash(algo,\n iterations,\n 0,\n 0,\n out, out_len,\n pass, 0,\n salt, salt_len);\n }\n\nint botan_pbkdf_timed(const char* algo,\n uint8_t out[], size_t out_len,\n const char* password,\n const uint8_t salt[], size_t salt_len,\n size_t ms_to_run,\n size_t* iterations_used)\n {\n return botan_pwdhash_timed(algo,\n static_cast<uint32_t>(ms_to_run),\n iterations_used,\n nullptr,\n nullptr,\n out, out_len,\n password, 0,\n salt, salt_len);\n }\n\nint botan_pwdhash(\n const char* algo,\n size_t param1,\n size_t param2,\n size_t param3,\n uint8_t out[],\n size_t out_len,\n const char* password,\n size_t password_len,\n const uint8_t salt[],\n size_t salt_len)\n {\n if(algo == nullptr || password == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(password_len == 0)\n password_len = std::strlen(password);\n\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n auto pwdhash_fam = Botan::PasswordHashFamily::create(algo);\n\n if(!pwdhash_fam)\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n\n auto pwdhash = pwdhash_fam->from_params(param1, param2, param3);\n\n pwdhash->derive_key(out, out_len,\n password, password_len,\n salt, salt_len);\n\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_pwdhash_timed(\n const char* algo,\n uint32_t msec,\n size_t* param1,\n size_t* param2,\n size_t* param3,\n uint8_t out[],\n size_t out_len,\n const char* password,\n size_t password_len,\n const uint8_t salt[],\n size_t salt_len)\n {\n if(algo == nullptr || password == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(password_len == 0)\n password_len = std::strlen(password);\n\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n\n auto pwdhash_fam = Botan::PasswordHashFamily::create(algo);\n\n if(!pwdhash_fam)\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n\n auto pwdhash = pwdhash_fam->tune(out_len, std::chrono::milliseconds(msec));\n\n if(param1)\n *param1 = pwdhash->iterations();\n if(param2)\n *param2 = pwdhash->parallelism();\n if(param3)\n *param3 = pwdhash->memory_param();\n\n pwdhash->derive_key(out, out_len,\n password, password_len,\n salt, salt_len);\n\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_kdf(const char* kdf_algo,\n uint8_t out[], size_t out_len,\n const uint8_t secret[], size_t secret_len,\n const uint8_t salt[], size_t salt_len,\n const uint8_t label[], size_t label_len)\n {\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n std::unique_ptr<Botan::KDF> kdf(Botan::get_kdf(kdf_algo));\n kdf->kdf(out, out_len, secret, secret_len, salt, salt_len, label, label_len);\n return BOTAN_FFI_SUCCESS;\n });\n }\n\nint botan_scrypt(uint8_t out[], size_t out_len,\n const char* password,\n const uint8_t salt[], size_t salt_len,\n size_t N, size_t r, size_t p)\n {\n return botan_pwdhash(\"Scrypt\", N, r, p,\n out, out_len,\n password, 0,\n salt, salt_len);\n }\n\nint botan_bcrypt_generate(uint8_t* out, size_t* out_len,\n const char* pass,\n botan_rng_t rng_obj, size_t wf,\n uint32_t flags)\n {\n#if defined(BOTAN_HAS_BCRYPT)\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n if(out == nullptr || out_len == nullptr || pass == nullptr)\n return BOTAN_FFI_ERROR_NULL_POINTER;\n\n if(flags != 0)\n return BOTAN_FFI_ERROR_BAD_FLAG;\n\n if(wf < 4 || wf > 18)\n return BOTAN_FFI_ERROR_BAD_PARAMETER;\n\n Botan::RandomNumberGenerator& rng = safe_get(rng_obj);\n const std::string bcrypt = Botan::generate_bcrypt(pass, rng, static_cast<uint16_t>(wf));\n return write_str_output(out, out_len, bcrypt);\n });\n#else\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n#endif\n }\n\nint botan_bcrypt_is_valid(const char* pass, const char* hash)\n {\n#if defined(BOTAN_HAS_BCRYPT)\n return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {\n return Botan::check_bcrypt(pass, hash) ? BOTAN_FFI_SUCCESS : BOTAN_FFI_INVALID_VERIFIER;\n });\n#else\n return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;\n#endif\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Configuration.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef BENG_LB_CONFIG_H\n#define BENG_LB_CONFIG_H\n\n#include \"address_list.hxx\"\n#include \"sticky.h\"\n#include \"ssl_config.hxx\"\n#include \"net\/AllocatedSocketAddress.hxx\"\n\n#include <http\/status.h>\n\n#include <glib.h>\n\n#include <map>\n#include <list>\n#include <vector>\n#include <string>\n\nstruct pool;\n\nenum lb_protocol {\n LB_PROTOCOL_HTTP,\n LB_PROTOCOL_TCP,\n};\n\nstruct lb_control_config {\n AllocatedSocketAddress bind_address;\n};\n\nstruct lb_monitor_config {\n std::string name;\n\n \/**\n * Time in seconds between two monitor checks.\n *\/\n unsigned interval;\n\n \/**\n * If the monitor does not produce a result after this timeout\n * [seconds], it is assumed to be negative.\n *\/\n unsigned timeout;\n\n enum class Type {\n NONE,\n PING,\n CONNECT,\n TCP_EXPECT,\n } type;\n\n \/**\n * The timeout for establishing a connection. Only applicable for\n * #Type::TCP_EXPECT. 0 means no special setting present.\n *\/\n unsigned connect_timeout;\n\n \/**\n * For #Type::TCP_EXPECT: a string that is sent to the peer\n * after the connection has been established. May be empty.\n *\/\n std::string send;\n\n \/**\n * For #Type::TCP_EXPECT: a string that is expected to be\n * received from the peer after the #send string has been sent.\n *\/\n std::string expect;\n\n \/**\n * For #Type::TCP_EXPECT: if that string is received from the\n * peer (instead of #expect), then the node is assumed to be\n * shutting down gracefully, and will only get sticky requests.\n *\/\n std::string fade_expect;\n\n lb_monitor_config(const char *_name)\n :name(_name),\n interval(10), timeout(0),\n type(Type::NONE),\n connect_timeout(0) {}\n};\n\nstruct lb_node_config {\n std::string name;\n\n AllocatedSocketAddress address;\n\n \/**\n * The Tomcat \"jvmRoute\" setting of this node. It is used for\n * #STICKY_JVM_ROUTE.\n *\/\n std::string jvm_route;\n\n lb_node_config(const char *_name)\n :name(_name) {}\n\n lb_node_config(const char *_name, AllocatedSocketAddress &&_address)\n :name(_name), address(std::move(_address)) {}\n\n lb_node_config(lb_node_config &&src)\n :name(std::move(src.name)), address(std::move(src.address)),\n jvm_route(std::move(src.jvm_route)) {}\n};\n\nstruct lb_member_config {\n const struct lb_node_config *node;\n\n unsigned port;\n\n lb_member_config():node(nullptr), port(0) {}\n};\n\nstruct lb_fallback_config {\n http_status_t status;\n\n \/**\n * The \"Location\" response header.\n *\/\n std::string location;\n\n std::string message;\n\n bool IsDefined() const {\n return !location.empty() || !message.empty();\n }\n};\n\nstruct lb_cluster_config {\n std::string name;\n\n \/**\n * The protocol that is spoken on this cluster.\n *\/\n enum lb_protocol protocol;\n\n \/**\n * Use the client's source IP for the connection to the backend?\n * This is implemented using IP_TRANSPARENT and requires the\n * \"tproxy\" Linux kernel module.\n *\/\n bool transparent_source;\n\n bool mangle_via;\n\n struct lb_fallback_config fallback;\n\n enum sticky_mode sticky_mode;\n\n std::string session_cookie;\n\n const struct lb_monitor_config *monitor;\n\n std::vector<lb_member_config> members;\n\n \/**\n * A list of node addresses.\n *\/\n AddressList address_list;\n\n lb_cluster_config(const char *_name)\n :name(_name),\n protocol(LB_PROTOCOL_HTTP),\n transparent_source(false),\n mangle_via(false),\n sticky_mode(STICKY_NONE),\n session_cookie(\"beng_proxy_session\"),\n monitor(nullptr) {}\n\n\n \/**\n * Returns the member index of the node with the specified\n * jvm_route value, or -1 if not found.\n *\/\n gcc_pure\n int FindJVMRoute(const char *jvm_route) const;\n};\n\nstruct lb_attribute_reference {\n enum class Type {\n METHOD,\n URI,\n HEADER,\n } type;\n\n std::string name;\n\n template<typename N>\n lb_attribute_reference(Type _type, N &&_name)\n :type(_type), name(std::forward<N>(_name)) {}\n};\n\nstruct lb_branch_config;\n\nstruct lb_goto {\n const lb_cluster_config *cluster;\n const lb_branch_config *branch;\n\n lb_goto()\n :cluster(nullptr), branch(nullptr) {}\n\n lb_goto(lb_cluster_config *_cluster)\n :cluster(_cluster), branch(nullptr) {}\n\n lb_goto(lb_branch_config *_branch)\n :cluster(nullptr), branch(_branch) {}\n\n bool IsDefined() const {\n return cluster != nullptr || branch != nullptr;\n }\n\n gcc_pure\n lb_protocol GetProtocol() const;\n\n gcc_pure\n const char *GetName() const;\n};\n\nstruct lb_condition_config {\n lb_attribute_reference attribute_reference;\n\n enum class Operator {\n EQUALS,\n REGEX,\n };\n\n Operator op;\n\n bool negate;\n\n std::string string;\n GRegex *regex;\n\n lb_condition_config(lb_attribute_reference &&a, bool _negate,\n const char *_string)\n :attribute_reference(std::move(a)), op(Operator::EQUALS),\n negate(_negate), string(_string), regex(nullptr) {}\n\n lb_condition_config(lb_attribute_reference &&a, bool _negate,\n GRegex *_regex)\n :attribute_reference(std::move(a)), op(Operator::REGEX),\n negate(_negate), regex(_regex) {}\n\n lb_condition_config(const lb_condition_config &other)\n :attribute_reference(other.attribute_reference),\n op(other.op), negate(other.negate),\n string(other.string),\n regex(other.op == Operator::REGEX\n ? g_regex_ref(other.regex)\n : nullptr) {}\n\n lb_condition_config(lb_condition_config &&other)\n :attribute_reference(std::move(other.attribute_reference)),\n op(other.op), negate(other.negate),\n string(std::move(other.string)),\n regex(other.regex) {\n other.regex = nullptr;\n }\n\n ~lb_condition_config() {\n if (regex != nullptr)\n g_regex_unref(regex);\n }\n\n gcc_pure\n bool Match(const char *value) const {\n switch (op) {\n case Operator::EQUALS:\n return (string == value) ^ negate;\n break;\n\n case Operator::REGEX:\n return g_regex_match(regex, value, GRegexMatchFlags(0),\n nullptr) ^ negate;\n break;\n }\n\n gcc_unreachable();\n }\n};\n\nstruct lb_goto_if_config {\n lb_condition_config condition;\n\n lb_goto destination;\n\n lb_goto_if_config(lb_condition_config &&c, lb_goto d)\n :condition(std::move(c)), destination(d) {}\n};\n\n\/**\n * An object that distributes connections or requests to the \"real\"\n * cluster.\n *\/\nstruct lb_branch_config {\n std::string name;\n\n lb_goto fallback;\n\n std::list<lb_goto_if_config> conditions;\n\n lb_branch_config(const char *_name)\n :name(_name) {}\n\n bool HasFallback() const {\n return fallback.IsDefined();\n }\n\n lb_protocol GetProtocol() const {\n return fallback.GetProtocol();\n }\n};\n\ninline lb_protocol\nlb_goto::GetProtocol() const\n{\n assert(IsDefined());\n\n return cluster != nullptr\n ? cluster->protocol\n : branch->GetProtocol();\n}\n\ninline const char *\nlb_goto::GetName() const\n{\n assert(IsDefined());\n\n return cluster != nullptr\n ? cluster->name.c_str()\n : branch->name.c_str();\n}\n\nstruct lb_listener_config {\n std::string name;\n\n AllocatedSocketAddress bind_address;\n\n lb_goto destination;\n\n bool verbose_response = false;\n\n bool ssl;\n\n struct ssl_config ssl_config;\n\n lb_listener_config(const char *_name)\n :name(_name),\n ssl(false) {\n }\n};\n\nstruct lb_config {\n std::list<lb_control_config> controls;\n\n std::map<std::string, lb_monitor_config> monitors;\n\n std::map<std::string, lb_node_config> nodes;\n\n std::map<std::string, lb_cluster_config> clusters;\n std::map<std::string, lb_branch_config> branches;\n\n std::list<lb_listener_config> listeners;\n\n template<typename T>\n gcc_pure\n const lb_monitor_config *FindMonitor(T &&t) const {\n const auto i = monitors.find(std::forward<T>(t));\n return i != monitors.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_node_config *FindNode(T &&t) const {\n const auto i = nodes.find(std::forward<T>(t));\n return i != nodes.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_cluster_config *FindCluster(T &&t) const {\n const auto i = clusters.find(std::forward<T>(t));\n return i != clusters.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_goto FindGoto(T &&t) const {\n lb_goto g;\n\n g.cluster = FindCluster(t);\n if (g.cluster == nullptr)\n g.branch = FindBranch(std::forward<T>(t));\n\n return g;\n }\n\n template<typename T>\n gcc_pure\n const lb_branch_config *FindBranch(T &&t) const {\n const auto i = branches.find(std::forward<T>(t));\n return i != branches.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_listener_config *FindListener(T &&t) const {\n for (const auto &i : listeners)\n if (i.name == t)\n return &i;\n\n return nullptr;\n }\n};\n\nG_GNUC_CONST\nstatic inline GQuark\nlb_config_quark(void)\n{\n return g_quark_from_static_string(\"lb_config\");\n}\n\n\/**\n * Load and parse the specified configuration file.\n *\/\nstruct lb_config *\nlb_config_load(struct pool *pool, const char *path, GError **error_r);\n\n#endif\n<commit_msg>lb_config: make constructors \"explicit\"<commit_after>\/*\n * Configuration.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef BENG_LB_CONFIG_H\n#define BENG_LB_CONFIG_H\n\n#include \"address_list.hxx\"\n#include \"sticky.h\"\n#include \"ssl_config.hxx\"\n#include \"net\/AllocatedSocketAddress.hxx\"\n\n#include <http\/status.h>\n\n#include <glib.h>\n\n#include <map>\n#include <list>\n#include <vector>\n#include <string>\n\nstruct pool;\n\nenum lb_protocol {\n LB_PROTOCOL_HTTP,\n LB_PROTOCOL_TCP,\n};\n\nstruct lb_control_config {\n AllocatedSocketAddress bind_address;\n};\n\nstruct lb_monitor_config {\n std::string name;\n\n \/**\n * Time in seconds between two monitor checks.\n *\/\n unsigned interval;\n\n \/**\n * If the monitor does not produce a result after this timeout\n * [seconds], it is assumed to be negative.\n *\/\n unsigned timeout;\n\n enum class Type {\n NONE,\n PING,\n CONNECT,\n TCP_EXPECT,\n } type;\n\n \/**\n * The timeout for establishing a connection. Only applicable for\n * #Type::TCP_EXPECT. 0 means no special setting present.\n *\/\n unsigned connect_timeout;\n\n \/**\n * For #Type::TCP_EXPECT: a string that is sent to the peer\n * after the connection has been established. May be empty.\n *\/\n std::string send;\n\n \/**\n * For #Type::TCP_EXPECT: a string that is expected to be\n * received from the peer after the #send string has been sent.\n *\/\n std::string expect;\n\n \/**\n * For #Type::TCP_EXPECT: if that string is received from the\n * peer (instead of #expect), then the node is assumed to be\n * shutting down gracefully, and will only get sticky requests.\n *\/\n std::string fade_expect;\n\n explicit lb_monitor_config(const char *_name)\n :name(_name),\n interval(10), timeout(0),\n type(Type::NONE),\n connect_timeout(0) {}\n};\n\nstruct lb_node_config {\n std::string name;\n\n AllocatedSocketAddress address;\n\n \/**\n * The Tomcat \"jvmRoute\" setting of this node. It is used for\n * #STICKY_JVM_ROUTE.\n *\/\n std::string jvm_route;\n\n explicit lb_node_config(const char *_name)\n :name(_name) {}\n\n lb_node_config(const char *_name, AllocatedSocketAddress &&_address)\n :name(_name), address(std::move(_address)) {}\n\n lb_node_config(lb_node_config &&src)\n :name(std::move(src.name)), address(std::move(src.address)),\n jvm_route(std::move(src.jvm_route)) {}\n};\n\nstruct lb_member_config {\n const struct lb_node_config *node;\n\n unsigned port;\n\n lb_member_config():node(nullptr), port(0) {}\n};\n\nstruct lb_fallback_config {\n http_status_t status;\n\n \/**\n * The \"Location\" response header.\n *\/\n std::string location;\n\n std::string message;\n\n bool IsDefined() const {\n return !location.empty() || !message.empty();\n }\n};\n\nstruct lb_cluster_config {\n std::string name;\n\n \/**\n * The protocol that is spoken on this cluster.\n *\/\n enum lb_protocol protocol;\n\n \/**\n * Use the client's source IP for the connection to the backend?\n * This is implemented using IP_TRANSPARENT and requires the\n * \"tproxy\" Linux kernel module.\n *\/\n bool transparent_source;\n\n bool mangle_via;\n\n struct lb_fallback_config fallback;\n\n enum sticky_mode sticky_mode;\n\n std::string session_cookie;\n\n const struct lb_monitor_config *monitor;\n\n std::vector<lb_member_config> members;\n\n \/**\n * A list of node addresses.\n *\/\n AddressList address_list;\n\n explicit lb_cluster_config(const char *_name)\n :name(_name),\n protocol(LB_PROTOCOL_HTTP),\n transparent_source(false),\n mangle_via(false),\n sticky_mode(STICKY_NONE),\n session_cookie(\"beng_proxy_session\"),\n monitor(nullptr) {}\n\n\n \/**\n * Returns the member index of the node with the specified\n * jvm_route value, or -1 if not found.\n *\/\n gcc_pure\n int FindJVMRoute(const char *jvm_route) const;\n};\n\nstruct lb_attribute_reference {\n enum class Type {\n METHOD,\n URI,\n HEADER,\n } type;\n\n std::string name;\n\n template<typename N>\n lb_attribute_reference(Type _type, N &&_name)\n :type(_type), name(std::forward<N>(_name)) {}\n};\n\nstruct lb_branch_config;\n\nstruct lb_goto {\n const lb_cluster_config *cluster;\n const lb_branch_config *branch;\n\n lb_goto()\n :cluster(nullptr), branch(nullptr) {}\n\n explicit lb_goto(lb_cluster_config *_cluster)\n :cluster(_cluster), branch(nullptr) {}\n\n explicit lb_goto(lb_branch_config *_branch)\n :cluster(nullptr), branch(_branch) {}\n\n bool IsDefined() const {\n return cluster != nullptr || branch != nullptr;\n }\n\n gcc_pure\n lb_protocol GetProtocol() const;\n\n gcc_pure\n const char *GetName() const;\n};\n\nstruct lb_condition_config {\n lb_attribute_reference attribute_reference;\n\n enum class Operator {\n EQUALS,\n REGEX,\n };\n\n Operator op;\n\n bool negate;\n\n std::string string;\n GRegex *regex;\n\n lb_condition_config(lb_attribute_reference &&a, bool _negate,\n const char *_string)\n :attribute_reference(std::move(a)), op(Operator::EQUALS),\n negate(_negate), string(_string), regex(nullptr) {}\n\n lb_condition_config(lb_attribute_reference &&a, bool _negate,\n GRegex *_regex)\n :attribute_reference(std::move(a)), op(Operator::REGEX),\n negate(_negate), regex(_regex) {}\n\n lb_condition_config(const lb_condition_config &other)\n :attribute_reference(other.attribute_reference),\n op(other.op), negate(other.negate),\n string(other.string),\n regex(other.op == Operator::REGEX\n ? g_regex_ref(other.regex)\n : nullptr) {}\n\n lb_condition_config(lb_condition_config &&other)\n :attribute_reference(std::move(other.attribute_reference)),\n op(other.op), negate(other.negate),\n string(std::move(other.string)),\n regex(other.regex) {\n other.regex = nullptr;\n }\n\n ~lb_condition_config() {\n if (regex != nullptr)\n g_regex_unref(regex);\n }\n\n gcc_pure\n bool Match(const char *value) const {\n switch (op) {\n case Operator::EQUALS:\n return (string == value) ^ negate;\n break;\n\n case Operator::REGEX:\n return g_regex_match(regex, value, GRegexMatchFlags(0),\n nullptr) ^ negate;\n break;\n }\n\n gcc_unreachable();\n }\n};\n\nstruct lb_goto_if_config {\n lb_condition_config condition;\n\n lb_goto destination;\n\n lb_goto_if_config(lb_condition_config &&c, lb_goto d)\n :condition(std::move(c)), destination(d) {}\n};\n\n\/**\n * An object that distributes connections or requests to the \"real\"\n * cluster.\n *\/\nstruct lb_branch_config {\n std::string name;\n\n lb_goto fallback;\n\n std::list<lb_goto_if_config> conditions;\n\n explicit lb_branch_config(const char *_name)\n :name(_name) {}\n\n bool HasFallback() const {\n return fallback.IsDefined();\n }\n\n lb_protocol GetProtocol() const {\n return fallback.GetProtocol();\n }\n};\n\ninline lb_protocol\nlb_goto::GetProtocol() const\n{\n assert(IsDefined());\n\n return cluster != nullptr\n ? cluster->protocol\n : branch->GetProtocol();\n}\n\ninline const char *\nlb_goto::GetName() const\n{\n assert(IsDefined());\n\n return cluster != nullptr\n ? cluster->name.c_str()\n : branch->name.c_str();\n}\n\nstruct lb_listener_config {\n std::string name;\n\n AllocatedSocketAddress bind_address;\n\n lb_goto destination;\n\n bool verbose_response = false;\n\n bool ssl;\n\n struct ssl_config ssl_config;\n\n explicit lb_listener_config(const char *_name)\n :name(_name),\n ssl(false) {\n }\n};\n\nstruct lb_config {\n std::list<lb_control_config> controls;\n\n std::map<std::string, lb_monitor_config> monitors;\n\n std::map<std::string, lb_node_config> nodes;\n\n std::map<std::string, lb_cluster_config> clusters;\n std::map<std::string, lb_branch_config> branches;\n\n std::list<lb_listener_config> listeners;\n\n template<typename T>\n gcc_pure\n const lb_monitor_config *FindMonitor(T &&t) const {\n const auto i = monitors.find(std::forward<T>(t));\n return i != monitors.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_node_config *FindNode(T &&t) const {\n const auto i = nodes.find(std::forward<T>(t));\n return i != nodes.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_cluster_config *FindCluster(T &&t) const {\n const auto i = clusters.find(std::forward<T>(t));\n return i != clusters.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_goto FindGoto(T &&t) const {\n lb_goto g;\n\n g.cluster = FindCluster(t);\n if (g.cluster == nullptr)\n g.branch = FindBranch(std::forward<T>(t));\n\n return g;\n }\n\n template<typename T>\n gcc_pure\n const lb_branch_config *FindBranch(T &&t) const {\n const auto i = branches.find(std::forward<T>(t));\n return i != branches.end()\n ? &i->second\n : nullptr;\n }\n\n template<typename T>\n gcc_pure\n const lb_listener_config *FindListener(T &&t) const {\n for (const auto &i : listeners)\n if (i.name == t)\n return &i;\n\n return nullptr;\n }\n};\n\nG_GNUC_CONST\nstatic inline GQuark\nlb_config_quark(void)\n{\n return g_quark_from_static_string(\"lb_config\");\n}\n\n\/**\n * Load and parse the specified configuration file.\n *\/\nstruct lb_config *\nlb_config_load(struct pool *pool, const char *path, GError **error_r);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef slic3r_Utils_hpp_\n#define slic3r_Utils_hpp_\n\n#include <locale>\n#include <utility>\n#include <functional>\n#include <type_traits>\n#include <system_error>\n\n#include \"libslic3r.h\"\n\nnamespace boost { namespace filesystem { class directory_entry; }}\n\nnamespace Slic3r {\n\nextern void set_logging_level(unsigned int level);\nextern unsigned get_logging_level();\nextern void trace(unsigned int level, const char *message);\n\/\/ Format memory allocated, separate thousands by comma.\nextern std::string format_memsize_MB(size_t n);\n\/\/ Return string to be added to the boost::log output to inform about the current process memory allocation.\n\/\/ The string is non-empty if the loglevel >= info (3) or ignore_loglevel==true.\n\/\/ Latter is used to get the memory info from SysInfoDialog.\nextern std::string log_memory_info(bool ignore_loglevel = false);\nextern void disable_multi_threading();\n\/\/ Returns the size of physical memory (RAM) in bytes.\nextern size_t total_physical_memory();\n\n\/\/ Set a path with GUI resource files.\nvoid set_var_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& var_dir();\n\/\/ Return a full resource path for a file_name.\nstd::string var(const std::string &file_name);\n\n\/\/ Set a path with various static definition data (for example the initial config bundles).\nvoid set_resources_dir(const std::string &path);\n\/\/ Return a full path to the resources directory.\nconst std::string& resources_dir();\n\n\/\/ Set a path with GUI localization files.\nvoid set_local_dir(const std::string &path);\n\/\/ Return a full path to the localization directory.\nconst std::string& localization_dir();\n\n\/\/ Set a path with preset files.\nvoid set_data_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& data_dir();\n\n\/\/ A special type for strings encoded in the local Windows 8-bit code page.\n\/\/ This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.\ntypedef std::string local_encoded_string;\n\n\/\/ Convert an UTF-8 encoded string into local coding.\n\/\/ On Windows, the UTF-8 string is converted to a local 8-bit code page.\n\/\/ On OSX and Linux, this function does no conversion and returns a copy of the source string.\nextern local_encoded_string encode_path(const char *src);\nextern std::string decode_path(const char *src);\nextern std::string normalize_utf8_nfc(const char *src);\n\n\/\/ Safely rename a file even if the target exists.\n\/\/ On Windows, the file explorer (or anti-virus or whatever else) often locks the file\n\/\/ for a short while, so the file may not be movable. Retry while we see recoverable errors.\nextern std::error_code rename_file(const std::string &from, const std::string &to);\n\n\/\/ Copy a file, adjust the access attributes, so that the target is writable.\nextern int copy_file(const std::string &from, const std::string &to);\n\n\/\/ Ignore system and hidden files, which may be created by the DropBox synchronisation process.\n\/\/ https:\/\/github.com\/prusa3d\/PrusaSlicer\/issues\/1298\nextern bool is_plain_file(const boost::filesystem::directory_entry &path);\nextern bool is_ini_file(const boost::filesystem::directory_entry &path);\nextern bool is_idx_file(const boost::filesystem::directory_entry &path);\n\n\/\/ File path \/ name \/ extension splitting utilities, working with UTF-8,\n\/\/ to be published to Perl.\nnamespace PerlUtils {\n \/\/ Get a file name including the extension.\n extern std::string path_to_filename(const char *src);\n \/\/ Get a file name without the extension.\n extern std::string path_to_stem(const char *src);\n \/\/ Get just the extension.\n extern std::string path_to_extension(const char *src);\n \/\/ Get a directory without the trailing slash.\n extern std::string path_to_parent_path(const char *src);\n};\n\nstd::string string_printf(const char *format, ...);\n\n\/\/ Standard \"generated by Slic3r version xxx timestamp xxx\" header string, \n\/\/ to be placed at the top of Slic3r generated files.\nstd::string header_slic3r_generated();\n\n\/\/ getpid platform wrapper\nextern unsigned get_current_pid();\n\ntemplate <typename Real>\nReal round_nearest(Real value, unsigned int decimals)\n{\n Real res = (Real)0;\n if (decimals == 0)\n res = ::round(value);\n else\n {\n Real power = ::pow((Real)10, (int)decimals);\n res = ::round(value * power + (Real)0.5) \/ power;\n }\n return res;\n}\n\n\/\/ Compute the next highest power of 2 of 32-bit v\n\/\/ http:\/\/graphics.stanford.edu\/~seander\/bithacks.html\ninline uint16_t next_highest_power_of_2(uint16_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n return ++ v;\n}\ninline uint32_t next_highest_power_of_2(uint32_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n return ++ v;\n}\ninline uint64_t next_highest_power_of_2(uint64_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v |= v >> 32;\n return ++ v;\n}\n\n\/\/ On some implementations (such as some versions of clang), the size_t is a type of its own, so we need to overload for size_t.\n\/\/ Typically, though, the size_t type aliases to uint64_t \/ uint32_t.\n\/\/ We distinguish that here and provide implementation for size_t if and only if it is a distinct type\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 8, T>::type = 0) \/\/ T is 64 bits\n{\n return next_highest_power_of_2(uint64_t(v));\n}\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 4, T>::type = 0) \/\/ T is 32 bits\n{\n return next_highest_power_of_2(uint32_t(v));\n}\n\ntemplate<typename INDEX_TYPE>\ninline INDEX_TYPE prev_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count)\n{\n\tif (idx == 0)\n\t\tidx = count;\n\treturn -- idx;\n}\n\ntemplate<typename INDEX_TYPE>\ninline INDEX_TYPE next_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count)\n{\n\tif (++ idx == count)\n\t\tidx = 0;\n\treturn idx;\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::size_type prev_idx_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container) \n{ \n\treturn prev_idx_modulo(idx, container.size());\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::size_type next_idx_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container)\n{ \n\treturn next_idx_modulo(idx, container.size());\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename const CONTAINER_TYPE::value_type& prev_value_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container) \n{ \n\treturn container[prev_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::value_type& prev_value_modulo(typename CONTAINER_TYPE::size_type idx, CONTAINER_TYPE &container) \n{ \n\treturn container[prev_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename const CONTAINER_TYPE::value_type& next_value_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container)\n{ \n\treturn container[next_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::value_type& next_value_modulo(typename CONTAINER_TYPE::size_type idx, CONTAINER_TYPE &container)\n{ \n\treturn container[next_idx_modulo(idx, container.size())];\n}\n\ntemplate<class T, class U = T>\ninline T exchange(T& obj, U&& new_value)\n{\n T old_value = std::move(obj);\n obj = std::forward<U>(new_value);\n return old_value;\n}\n\nextern std::string xml_escape(std::string text);\n\n\n#if defined __GNUC__ && __GNUC__ < 5 && !defined __clang__\n\/\/ Older GCCs don't have std::is_trivially_copyable\n\/\/ cf. https:\/\/gcc.gnu.org\/onlinedocs\/gcc-4.9.4\/libstdc++\/manual\/manual\/status.html#status.iso.2011\n\/\/ #warning \"GCC version < 5, faking std::is_trivially_copyable\"\ntemplate<typename T> struct IsTriviallyCopyable { static constexpr bool value = true; };\n#else\ntemplate<typename T> struct IsTriviallyCopyable : public std::is_trivially_copyable<T> {};\n#endif\n\n\nclass ScopeGuard\n{\npublic:\n typedef std::function<void()> Closure;\nprivate:\n\/\/ bool committed;\n Closure closure;\n\npublic:\n ScopeGuard() {}\n ScopeGuard(Closure closure) : closure(std::move(closure)) {}\n ScopeGuard(const ScopeGuard&) = delete;\n ScopeGuard(ScopeGuard &&other) : closure(std::move(other.closure)) {}\n\n ~ScopeGuard()\n {\n if (closure) { closure(); }\n }\n\n ScopeGuard& operator=(const ScopeGuard&) = delete;\n ScopeGuard& operator=(ScopeGuard &&other)\n {\n closure = std::move(other.closure);\n return *this;\n }\n\n void reset() { closure = Closure(); }\n};\n\n\/\/ Shorten the dhms time by removing the seconds, rounding the dhm to full minutes\n\/\/ and removing spaces.\ninline std::string short_time(const std::string &time)\n{\n \/\/ Parse the dhms time format.\n int days = 0;\n int hours = 0;\n int minutes = 0;\n int seconds = 0;\n if (time.find('d') != std::string::npos)\n ::sscanf(time.c_str(), \"%dd %dh %dm %ds\", &days, &hours, &minutes, &seconds);\n else if (time.find('h') != std::string::npos)\n ::sscanf(time.c_str(), \"%dh %dm %ds\", &hours, &minutes, &seconds);\n else if (time.find('m') != std::string::npos)\n ::sscanf(time.c_str(), \"%dm %ds\", &minutes, &seconds);\n else if (time.find('s') != std::string::npos)\n ::sscanf(time.c_str(), \"%ds\", &seconds);\n \/\/ Round to full minutes.\n if (days + hours + minutes > 0 && seconds >= 30) {\n if (++minutes == 60) {\n minutes = 0;\n if (++hours == 24) {\n hours = 0;\n ++days;\n }\n }\n }\n \/\/ Format the dhm time.\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd%dh%dm\", days, hours, minutes);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh%dm\", hours, minutes);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm\", minutes);\n else\n ::sprintf(buffer, \"%ds\", seconds);\n return buffer;\n}\n\n\/\/ Returns the given time is seconds in format DDd HHh MMm SSs\ninline std::string get_time_dhms(float time_in_secs)\n{\n int days = (int)(time_in_secs \/ 86400.0f);\n time_in_secs -= (float)days * 86400.0f;\n int hours = (int)(time_in_secs \/ 3600.0f);\n time_in_secs -= (float)hours * 3600.0f;\n int minutes = (int)(time_in_secs \/ 60.0f);\n time_in_secs -= (float)minutes * 60.0f;\n\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd %dh %dm %ds\", days, hours, minutes, (int)time_in_secs);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh %dm %ds\", hours, minutes, (int)time_in_secs);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm %ds\", minutes, (int)time_in_secs);\n else\n ::sprintf(buffer, \"%ds\", (int)time_in_secs);\n\n return buffer;\n}\n\n} \/\/ namespace Slic3r\n\n#if WIN32\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + __alignof(TYPE) - 1) \/ __alignof(TYPE)) * __alignof(TYPE)\n#else\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + alignof(TYPE) - 1) \/ alignof(TYPE)) * alignof(TYPE)\n#endif\n\n#endif \/\/ slic3r_Utils_hpp_\n<commit_msg>Fixed a typo in MeshUtils.hpp<commit_after>#ifndef slic3r_Utils_hpp_\n#define slic3r_Utils_hpp_\n\n#include <locale>\n#include <utility>\n#include <functional>\n#include <type_traits>\n#include <system_error>\n\n#include \"libslic3r.h\"\n\nnamespace boost { namespace filesystem { class directory_entry; }}\n\nnamespace Slic3r {\n\nextern void set_logging_level(unsigned int level);\nextern unsigned get_logging_level();\nextern void trace(unsigned int level, const char *message);\n\/\/ Format memory allocated, separate thousands by comma.\nextern std::string format_memsize_MB(size_t n);\n\/\/ Return string to be added to the boost::log output to inform about the current process memory allocation.\n\/\/ The string is non-empty if the loglevel >= info (3) or ignore_loglevel==true.\n\/\/ Latter is used to get the memory info from SysInfoDialog.\nextern std::string log_memory_info(bool ignore_loglevel = false);\nextern void disable_multi_threading();\n\/\/ Returns the size of physical memory (RAM) in bytes.\nextern size_t total_physical_memory();\n\n\/\/ Set a path with GUI resource files.\nvoid set_var_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& var_dir();\n\/\/ Return a full resource path for a file_name.\nstd::string var(const std::string &file_name);\n\n\/\/ Set a path with various static definition data (for example the initial config bundles).\nvoid set_resources_dir(const std::string &path);\n\/\/ Return a full path to the resources directory.\nconst std::string& resources_dir();\n\n\/\/ Set a path with GUI localization files.\nvoid set_local_dir(const std::string &path);\n\/\/ Return a full path to the localization directory.\nconst std::string& localization_dir();\n\n\/\/ Set a path with preset files.\nvoid set_data_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& data_dir();\n\n\/\/ A special type for strings encoded in the local Windows 8-bit code page.\n\/\/ This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.\ntypedef std::string local_encoded_string;\n\n\/\/ Convert an UTF-8 encoded string into local coding.\n\/\/ On Windows, the UTF-8 string is converted to a local 8-bit code page.\n\/\/ On OSX and Linux, this function does no conversion and returns a copy of the source string.\nextern local_encoded_string encode_path(const char *src);\nextern std::string decode_path(const char *src);\nextern std::string normalize_utf8_nfc(const char *src);\n\n\/\/ Safely rename a file even if the target exists.\n\/\/ On Windows, the file explorer (or anti-virus or whatever else) often locks the file\n\/\/ for a short while, so the file may not be movable. Retry while we see recoverable errors.\nextern std::error_code rename_file(const std::string &from, const std::string &to);\n\n\/\/ Copy a file, adjust the access attributes, so that the target is writable.\nextern int copy_file(const std::string &from, const std::string &to);\n\n\/\/ Ignore system and hidden files, which may be created by the DropBox synchronisation process.\n\/\/ https:\/\/github.com\/prusa3d\/PrusaSlicer\/issues\/1298\nextern bool is_plain_file(const boost::filesystem::directory_entry &path);\nextern bool is_ini_file(const boost::filesystem::directory_entry &path);\nextern bool is_idx_file(const boost::filesystem::directory_entry &path);\n\n\/\/ File path \/ name \/ extension splitting utilities, working with UTF-8,\n\/\/ to be published to Perl.\nnamespace PerlUtils {\n \/\/ Get a file name including the extension.\n extern std::string path_to_filename(const char *src);\n \/\/ Get a file name without the extension.\n extern std::string path_to_stem(const char *src);\n \/\/ Get just the extension.\n extern std::string path_to_extension(const char *src);\n \/\/ Get a directory without the trailing slash.\n extern std::string path_to_parent_path(const char *src);\n};\n\nstd::string string_printf(const char *format, ...);\n\n\/\/ Standard \"generated by Slic3r version xxx timestamp xxx\" header string, \n\/\/ to be placed at the top of Slic3r generated files.\nstd::string header_slic3r_generated();\n\n\/\/ getpid platform wrapper\nextern unsigned get_current_pid();\n\ntemplate <typename Real>\nReal round_nearest(Real value, unsigned int decimals)\n{\n Real res = (Real)0;\n if (decimals == 0)\n res = ::round(value);\n else\n {\n Real power = ::pow((Real)10, (int)decimals);\n res = ::round(value * power + (Real)0.5) \/ power;\n }\n return res;\n}\n\n\/\/ Compute the next highest power of 2 of 32-bit v\n\/\/ http:\/\/graphics.stanford.edu\/~seander\/bithacks.html\ninline uint16_t next_highest_power_of_2(uint16_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n return ++ v;\n}\ninline uint32_t next_highest_power_of_2(uint32_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n return ++ v;\n}\ninline uint64_t next_highest_power_of_2(uint64_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v |= v >> 32;\n return ++ v;\n}\n\n\/\/ On some implementations (such as some versions of clang), the size_t is a type of its own, so we need to overload for size_t.\n\/\/ Typically, though, the size_t type aliases to uint64_t \/ uint32_t.\n\/\/ We distinguish that here and provide implementation for size_t if and only if it is a distinct type\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 8, T>::type = 0) \/\/ T is 64 bits\n{\n return next_highest_power_of_2(uint64_t(v));\n}\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 4, T>::type = 0) \/\/ T is 32 bits\n{\n return next_highest_power_of_2(uint32_t(v));\n}\n\ntemplate<typename INDEX_TYPE>\ninline INDEX_TYPE prev_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count)\n{\n\tif (idx == 0)\n\t\tidx = count;\n\treturn -- idx;\n}\n\ntemplate<typename INDEX_TYPE>\ninline INDEX_TYPE next_idx_modulo(INDEX_TYPE idx, const INDEX_TYPE count)\n{\n\tif (++ idx == count)\n\t\tidx = 0;\n\treturn idx;\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::size_type prev_idx_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container) \n{ \n\treturn prev_idx_modulo(idx, container.size());\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::size_type next_idx_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container)\n{ \n\treturn next_idx_modulo(idx, container.size());\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline const typename CONTAINER_TYPE::value_type& prev_value_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container)\n{ \n\treturn container[prev_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::value_type& prev_value_modulo(typename CONTAINER_TYPE::size_type idx, CONTAINER_TYPE &container) \n{ \n\treturn container[prev_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline const typename CONTAINER_TYPE::value_type& next_value_modulo(typename CONTAINER_TYPE::size_type idx, const CONTAINER_TYPE &container)\n{ \n\treturn container[next_idx_modulo(idx, container.size())];\n}\n\ntemplate<typename CONTAINER_TYPE>\ninline typename CONTAINER_TYPE::value_type& next_value_modulo(typename CONTAINER_TYPE::size_type idx, CONTAINER_TYPE &container)\n{ \n\treturn container[next_idx_modulo(idx, container.size())];\n}\n\ntemplate<class T, class U = T>\ninline T exchange(T& obj, U&& new_value)\n{\n T old_value = std::move(obj);\n obj = std::forward<U>(new_value);\n return old_value;\n}\n\nextern std::string xml_escape(std::string text);\n\n\n#if defined __GNUC__ && __GNUC__ < 5 && !defined __clang__\n\/\/ Older GCCs don't have std::is_trivially_copyable\n\/\/ cf. https:\/\/gcc.gnu.org\/onlinedocs\/gcc-4.9.4\/libstdc++\/manual\/manual\/status.html#status.iso.2011\n\/\/ #warning \"GCC version < 5, faking std::is_trivially_copyable\"\ntemplate<typename T> struct IsTriviallyCopyable { static constexpr bool value = true; };\n#else\ntemplate<typename T> struct IsTriviallyCopyable : public std::is_trivially_copyable<T> {};\n#endif\n\n\nclass ScopeGuard\n{\npublic:\n typedef std::function<void()> Closure;\nprivate:\n\/\/ bool committed;\n Closure closure;\n\npublic:\n ScopeGuard() {}\n ScopeGuard(Closure closure) : closure(std::move(closure)) {}\n ScopeGuard(const ScopeGuard&) = delete;\n ScopeGuard(ScopeGuard &&other) : closure(std::move(other.closure)) {}\n\n ~ScopeGuard()\n {\n if (closure) { closure(); }\n }\n\n ScopeGuard& operator=(const ScopeGuard&) = delete;\n ScopeGuard& operator=(ScopeGuard &&other)\n {\n closure = std::move(other.closure);\n return *this;\n }\n\n void reset() { closure = Closure(); }\n};\n\n\/\/ Shorten the dhms time by removing the seconds, rounding the dhm to full minutes\n\/\/ and removing spaces.\ninline std::string short_time(const std::string &time)\n{\n \/\/ Parse the dhms time format.\n int days = 0;\n int hours = 0;\n int minutes = 0;\n int seconds = 0;\n if (time.find('d') != std::string::npos)\n ::sscanf(time.c_str(), \"%dd %dh %dm %ds\", &days, &hours, &minutes, &seconds);\n else if (time.find('h') != std::string::npos)\n ::sscanf(time.c_str(), \"%dh %dm %ds\", &hours, &minutes, &seconds);\n else if (time.find('m') != std::string::npos)\n ::sscanf(time.c_str(), \"%dm %ds\", &minutes, &seconds);\n else if (time.find('s') != std::string::npos)\n ::sscanf(time.c_str(), \"%ds\", &seconds);\n \/\/ Round to full minutes.\n if (days + hours + minutes > 0 && seconds >= 30) {\n if (++minutes == 60) {\n minutes = 0;\n if (++hours == 24) {\n hours = 0;\n ++days;\n }\n }\n }\n \/\/ Format the dhm time.\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd%dh%dm\", days, hours, minutes);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh%dm\", hours, minutes);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm\", minutes);\n else\n ::sprintf(buffer, \"%ds\", seconds);\n return buffer;\n}\n\n\/\/ Returns the given time is seconds in format DDd HHh MMm SSs\ninline std::string get_time_dhms(float time_in_secs)\n{\n int days = (int)(time_in_secs \/ 86400.0f);\n time_in_secs -= (float)days * 86400.0f;\n int hours = (int)(time_in_secs \/ 3600.0f);\n time_in_secs -= (float)hours * 3600.0f;\n int minutes = (int)(time_in_secs \/ 60.0f);\n time_in_secs -= (float)minutes * 60.0f;\n\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd %dh %dm %ds\", days, hours, minutes, (int)time_in_secs);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh %dm %ds\", hours, minutes, (int)time_in_secs);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm %ds\", minutes, (int)time_in_secs);\n else\n ::sprintf(buffer, \"%ds\", (int)time_in_secs);\n\n return buffer;\n}\n\n} \/\/ namespace Slic3r\n\n#if WIN32\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + __alignof(TYPE) - 1) \/ __alignof(TYPE)) * __alignof(TYPE)\n#else\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + alignof(TYPE) - 1) \/ alignof(TYPE)) * alignof(TYPE)\n#endif\n\n#endif \/\/ slic3r_Utils_hpp_\n<|endoftext|>"} {"text":"<commit_before>#include \"Framework.hpp\"\n#include \"VideoTimer.hpp\"\n\n#include \"..\/core\/jni_helper.hpp\"\n#include \"..\/core\/render_context.hpp\"\n\n#include \"..\/..\/..\/..\/..\/indexer\/drawing_rules.hpp\"\n\n#include \"..\/..\/..\/..\/..\/map\/framework.hpp\"\n\n#include \"..\/..\/..\/..\/..\/std\/shared_ptr.hpp\"\n#include \"..\/..\/..\/..\/..\/std\/bind.hpp\"\n\n\n#include \"..\/..\/..\/..\/..\/yg\/framebuffer.hpp\"\n#include \"..\/..\/..\/..\/..\/yg\/internal\/opengl.hpp\"\n\n#include \"..\/..\/..\/..\/..\/platform\/platform.hpp\"\n#include \"..\/..\/..\/..\/..\/platform\/location.hpp\"\n\n#include \"..\/..\/..\/..\/..\/base\/logging.hpp\"\n#include \"..\/..\/..\/..\/..\/base\/math.hpp\"\n\nandroid::Framework * g_framework = 0;\n\nnamespace android\n{\n void Framework::CallRepaint()\n {\n \/\/LOG(LINFO, (\"Calling Repaint\"));\n }\n\n Framework::Framework(JavaVM * jvm)\n : m_work(),\n m_eventType(NVMultiTouchEventType(0)),\n m_hasFirst(false),\n m_hasSecond(false),\n m_mask(0)\n {\n ASSERT(g_framework == 0, ());\n g_framework = this;\n\n m_videoTimer = new VideoTimer(jvm, bind(&Framework::CallRepaint, this));\n\n \/\/ @TODO refactor storage\n m_work.Storage().ReInitCountries(false);\n }\n\n Framework::~Framework()\n {\n delete m_videoTimer;\n }\n\n void Framework::OnLocationStatusChanged(int newStatus)\n {\n m_work.OnLocationStatusChanged(static_cast<location::TLocationStatus>(newStatus));\n }\n\n void Framework::OnLocationUpdated(uint64_t time, double lat, double lon, float accuracy)\n {\n location::GpsInfo info;\n info.m_timestamp = static_cast<double>(time);\n info.m_latitude = lat;\n info.m_longitude = lon;\n info.m_horizontalAccuracy = accuracy;\n m_work.OnGpsUpdate(info);\n }\n\n void Framework::OnCompassUpdated(uint64_t timestamp, double magneticNorth, double trueNorth, float accuracy)\n {\n location::CompassInfo info;\n info.m_timestamp = static_cast<double>(timestamp);\n info.m_magneticHeading = magneticNorth;\n info.m_trueHeading = trueNorth;\n info.m_accuracy = accuracy;\n m_work.OnCompassUpdate(info);\n }\n\n void Framework::DeleteRenderPolicy()\n {\n m_work.SaveState();\n LOG(LINFO, (\"clearing current render policy.\"));\n m_work.SetRenderPolicy(0);\n }\n\n bool Framework::InitRenderPolicy()\n {\n LOG(LDEBUG, (\"AF::InitRenderer 1\"));\n\n yg::ResourceManager::Params rmParams;\n rmParams.m_videoMemoryLimit = 30 * 1024 * 1024;\n rmParams.m_rtFormat = yg::Data8Bpp;\n rmParams.m_texFormat = yg::Data4Bpp;\n\n try\n {\n m_work.SetRenderPolicy(CreateRenderPolicy(m_videoTimer,\n true,\n rmParams,\n make_shared_ptr(new android::RenderContext())));\n m_work.LoadState();\n }\n catch (yg::gl::platform_unsupported const & e)\n {\n LOG(LINFO, (\"this android platform is unsupported, reason=\", e.what()));\n return false;\n }\n\n m_work.SetUpdatesEnabled(true);\n\n LOG(LDEBUG, (\"AF::InitRenderer 3\"));\n\n return true;\n }\n\n storage::Storage & Framework::Storage()\n {\n return m_work.Storage();\n }\n\n void Framework::Resize(int w, int h)\n {\n m_work.OnSize(w, h);\n }\n\n void Framework::DrawFrame()\n {\n if (m_work.NeedRedraw())\n {\n m_work.SetNeedRedraw(false);\n\n shared_ptr<PaintEvent> paintEvent(new PaintEvent(m_work.GetRenderPolicy()->GetDrawer().get()));\n\n m_work.BeginPaint(paintEvent);\n m_work.DoPaint(paintEvent);\n\n NVEventSwapBuffersEGL();\n\n m_work.EndPaint(paintEvent);\n }\n }\n\n void Framework::Move(int mode, double x, double y)\n {\n DragEvent e(x, y);\n switch (mode)\n {\n case 0: m_work.StartDrag(e); break;\n case 1: m_work.DoDrag(e); break;\n case 2: m_work.StopDrag(e); break;\n }\n }\n\n void Framework::Zoom(int mode, double x1, double y1, double x2, double y2)\n {\n ScaleEvent e(x1, y1, x2, y2);\n switch (mode)\n {\n case 0: m_work.StartScale(e); break;\n case 1: m_work.DoScale(e); break;\n case 2: m_work.StopScale(e); break;\n }\n }\n\n void Framework::Touch(int action, int mask, double x1, double y1, double x2, double y2)\n {\n NVMultiTouchEventType eventType = (NVMultiTouchEventType)action;\n\n if (m_mask != mask)\n {\n if (m_mask == 0x0)\n {\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x1)\n {\n m_work.StopDrag(DragEvent(x1, y1));\n\n if (mask == 0x0)\n {\n if ((eventType != NV_MULTITOUCH_UP) && (eventType != NV_MULTITOUCH_CANCEL))\n LOG(LINFO, (\"should be NV_MULTITOUCH_UP or NV_MULTITOUCH_CANCEL\"));\n }\n\n if (m_mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x2)\n {\n m_work.StopDrag(DragEvent(x2, y2));\n\n if (mask == 0x0)\n {\n if ((eventType != NV_MULTITOUCH_UP) && (eventType != NV_MULTITOUCH_CANCEL))\n LOG(LINFO, (\"should be NV_MULTITOUCH_UP or NV_MULTITOUCH_CANCEL\"));\n }\n\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x3)\n {\n m_work.StopScale(ScaleEvent(m_x1, m_y1, m_x2, m_y2));\n\n if ((eventType == NV_MULTITOUCH_MOVE))\n {\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n }\n else\n mask = 0;\n }\n }\n else\n {\n if (eventType == NV_MULTITOUCH_MOVE)\n {\n if (m_mask == 0x1)\n m_work.DoDrag(DragEvent(x1, y1));\n if (m_mask == 0x2)\n m_work.DoDrag(DragEvent(x2, y2));\n if (m_mask == 0x3)\n m_work.DoScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if ((eventType == NV_MULTITOUCH_CANCEL) || (eventType == NV_MULTITOUCH_UP))\n {\n if (m_mask == 0x1)\n m_work.StopDrag(DragEvent(x1, y1));\n if (m_mask == 0x2)\n m_work.StopDrag(DragEvent(x2, y2));\n if (m_mask == 0x3)\n m_work.StopScale(ScaleEvent(m_x1, m_y1, m_x2, m_y2));\n mask = 0;\n }\n }\n\n m_x1 = x1;\n m_y1 = y1;\n m_x2 = x2;\n m_y2 = y2;\n m_mask = mask;\n m_eventType = eventType;\n\n }\n\n void Framework::LoadState()\n {\n if (!m_work.LoadState())\n {\n LOG(LINFO, (\"no saved state, showing all world\"));\n m_work.ShowAll();\n }\n else\n {\n LOG(LINFO, (\"state loaded successfully\"));\n }\n }\n\n void Framework::SaveState()\n {\n m_work.SaveState();\n }\n\n void Framework::Invalidate()\n {\n m_work.Invalidate();\n }\n\n void Framework::SetupMeasurementSystem()\n {\n m_work.SetupMeasurementSystem();\n }\n}\n<commit_msg>showing all world at first startup, closes #565<commit_after>#include \"Framework.hpp\"\n#include \"VideoTimer.hpp\"\n\n#include \"..\/core\/jni_helper.hpp\"\n#include \"..\/core\/render_context.hpp\"\n\n#include \"..\/..\/..\/..\/..\/indexer\/drawing_rules.hpp\"\n\n#include \"..\/..\/..\/..\/..\/map\/framework.hpp\"\n\n#include \"..\/..\/..\/..\/..\/std\/shared_ptr.hpp\"\n#include \"..\/..\/..\/..\/..\/std\/bind.hpp\"\n\n\n#include \"..\/..\/..\/..\/..\/yg\/framebuffer.hpp\"\n#include \"..\/..\/..\/..\/..\/yg\/internal\/opengl.hpp\"\n\n#include \"..\/..\/..\/..\/..\/platform\/platform.hpp\"\n#include \"..\/..\/..\/..\/..\/platform\/location.hpp\"\n\n#include \"..\/..\/..\/..\/..\/base\/logging.hpp\"\n#include \"..\/..\/..\/..\/..\/base\/math.hpp\"\n\nandroid::Framework * g_framework = 0;\n\nnamespace android\n{\n void Framework::CallRepaint()\n {\n \/\/LOG(LINFO, (\"Calling Repaint\"));\n }\n\n Framework::Framework(JavaVM * jvm)\n : m_work(),\n m_eventType(NVMultiTouchEventType(0)),\n m_hasFirst(false),\n m_hasSecond(false),\n m_mask(0)\n {\n ASSERT(g_framework == 0, ());\n g_framework = this;\n\n m_videoTimer = new VideoTimer(jvm, bind(&Framework::CallRepaint, this));\n\n \/\/ @TODO refactor storage\n m_work.Storage().ReInitCountries(false);\n }\n\n Framework::~Framework()\n {\n delete m_videoTimer;\n }\n\n void Framework::OnLocationStatusChanged(int newStatus)\n {\n m_work.OnLocationStatusChanged(static_cast<location::TLocationStatus>(newStatus));\n }\n\n void Framework::OnLocationUpdated(uint64_t time, double lat, double lon, float accuracy)\n {\n location::GpsInfo info;\n info.m_timestamp = static_cast<double>(time);\n info.m_latitude = lat;\n info.m_longitude = lon;\n info.m_horizontalAccuracy = accuracy;\n m_work.OnGpsUpdate(info);\n }\n\n void Framework::OnCompassUpdated(uint64_t timestamp, double magneticNorth, double trueNorth, float accuracy)\n {\n location::CompassInfo info;\n info.m_timestamp = static_cast<double>(timestamp);\n info.m_magneticHeading = magneticNorth;\n info.m_trueHeading = trueNorth;\n info.m_accuracy = accuracy;\n m_work.OnCompassUpdate(info);\n }\n\n void Framework::DeleteRenderPolicy()\n {\n m_work.SaveState();\n LOG(LINFO, (\"clearing current render policy.\"));\n m_work.SetRenderPolicy(0);\n }\n\n bool Framework::InitRenderPolicy()\n {\n LOG(LDEBUG, (\"AF::InitRenderer 1\"));\n\n yg::ResourceManager::Params rmParams;\n rmParams.m_videoMemoryLimit = 30 * 1024 * 1024;\n rmParams.m_rtFormat = yg::Data8Bpp;\n rmParams.m_texFormat = yg::Data4Bpp;\n\n try\n {\n m_work.SetRenderPolicy(CreateRenderPolicy(m_videoTimer,\n true,\n rmParams,\n make_shared_ptr(new android::RenderContext())));\n LoadState();\n }\n catch (yg::gl::platform_unsupported const & e)\n {\n LOG(LINFO, (\"this android platform is unsupported, reason=\", e.what()));\n return false;\n }\n\n m_work.SetUpdatesEnabled(true);\n\n LOG(LDEBUG, (\"AF::InitRenderer 3\"));\n\n return true;\n }\n\n storage::Storage & Framework::Storage()\n {\n return m_work.Storage();\n }\n\n void Framework::Resize(int w, int h)\n {\n m_work.OnSize(w, h);\n }\n\n void Framework::DrawFrame()\n {\n if (m_work.NeedRedraw())\n {\n m_work.SetNeedRedraw(false);\n\n shared_ptr<PaintEvent> paintEvent(new PaintEvent(m_work.GetRenderPolicy()->GetDrawer().get()));\n\n m_work.BeginPaint(paintEvent);\n m_work.DoPaint(paintEvent);\n\n NVEventSwapBuffersEGL();\n\n m_work.EndPaint(paintEvent);\n }\n }\n\n void Framework::Move(int mode, double x, double y)\n {\n DragEvent e(x, y);\n switch (mode)\n {\n case 0: m_work.StartDrag(e); break;\n case 1: m_work.DoDrag(e); break;\n case 2: m_work.StopDrag(e); break;\n }\n }\n\n void Framework::Zoom(int mode, double x1, double y1, double x2, double y2)\n {\n ScaleEvent e(x1, y1, x2, y2);\n switch (mode)\n {\n case 0: m_work.StartScale(e); break;\n case 1: m_work.DoScale(e); break;\n case 2: m_work.StopScale(e); break;\n }\n }\n\n void Framework::Touch(int action, int mask, double x1, double y1, double x2, double y2)\n {\n NVMultiTouchEventType eventType = (NVMultiTouchEventType)action;\n\n if (m_mask != mask)\n {\n if (m_mask == 0x0)\n {\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x1)\n {\n m_work.StopDrag(DragEvent(x1, y1));\n\n if (mask == 0x0)\n {\n if ((eventType != NV_MULTITOUCH_UP) && (eventType != NV_MULTITOUCH_CANCEL))\n LOG(LINFO, (\"should be NV_MULTITOUCH_UP or NV_MULTITOUCH_CANCEL\"));\n }\n\n if (m_mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x2)\n {\n m_work.StopDrag(DragEvent(x2, y2));\n\n if (mask == 0x0)\n {\n if ((eventType != NV_MULTITOUCH_UP) && (eventType != NV_MULTITOUCH_CANCEL))\n LOG(LINFO, (\"should be NV_MULTITOUCH_UP or NV_MULTITOUCH_CANCEL\"));\n }\n\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x3)\n m_work.StartScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if (m_mask == 0x3)\n {\n m_work.StopScale(ScaleEvent(m_x1, m_y1, m_x2, m_y2));\n\n if ((eventType == NV_MULTITOUCH_MOVE))\n {\n if (mask == 0x1)\n m_work.StartDrag(DragEvent(x1, y1));\n\n if (mask == 0x2)\n m_work.StartDrag(DragEvent(x2, y2));\n }\n else\n mask = 0;\n }\n }\n else\n {\n if (eventType == NV_MULTITOUCH_MOVE)\n {\n if (m_mask == 0x1)\n m_work.DoDrag(DragEvent(x1, y1));\n if (m_mask == 0x2)\n m_work.DoDrag(DragEvent(x2, y2));\n if (m_mask == 0x3)\n m_work.DoScale(ScaleEvent(x1, y1, x2, y2));\n }\n\n if ((eventType == NV_MULTITOUCH_CANCEL) || (eventType == NV_MULTITOUCH_UP))\n {\n if (m_mask == 0x1)\n m_work.StopDrag(DragEvent(x1, y1));\n if (m_mask == 0x2)\n m_work.StopDrag(DragEvent(x2, y2));\n if (m_mask == 0x3)\n m_work.StopScale(ScaleEvent(m_x1, m_y1, m_x2, m_y2));\n mask = 0;\n }\n }\n\n m_x1 = x1;\n m_y1 = y1;\n m_x2 = x2;\n m_y2 = y2;\n m_mask = mask;\n m_eventType = eventType;\n\n }\n\n void Framework::LoadState()\n {\n if (!m_work.LoadState())\n {\n LOG(LINFO, (\"no saved state, showing all world\"));\n m_work.ShowAll();\n }\n else\n {\n LOG(LINFO, (\"state loaded successfully\"));\n }\n }\n\n void Framework::SaveState()\n {\n m_work.SaveState();\n }\n\n void Framework::Invalidate()\n {\n m_work.Invalidate();\n }\n\n void Framework::SetupMeasurementSystem()\n {\n m_work.SetupMeasurementSystem();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef slic3r_Utils_hpp_\n#define slic3r_Utils_hpp_\n\n#include <locale>\n#include <utility>\n#include <functional>\n#include <type_traits>\n\n#include \"libslic3r.h\"\n\nnamespace boost { namespace filesystem { class directory_entry; }}\n\nnamespace Slic3r {\n\nextern void set_logging_level(unsigned int level);\nextern unsigned get_logging_level();\nextern void trace(unsigned int level, const char *message);\n\/\/ Format memory allocated, separate thousands by comma.\nextern std::string format_memsize_MB(size_t n);\n\/\/ Return string to be added to the boost::log output to inform about the current process memory allocation.\n\/\/ The string is non-empty if the loglevel >= info (3) or ignore_loglevel==true.\n\/\/ Latter is used to get the memory info from SysInfoDialog.\nextern std::string log_memory_info(bool ignore_loglevel = false);\nextern void disable_multi_threading();\n\/\/ Returns the size of physical memory (RAM) in bytes.\nextern size_t total_physical_memory();\n\n\/\/ Set a path with GUI resource files.\nvoid set_var_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& var_dir();\n\/\/ Return a full resource path for a file_name.\nstd::string var(const std::string &file_name);\n\n\/\/ Set a path with various static definition data (for example the initial config bundles).\nvoid set_resources_dir(const std::string &path);\n\/\/ Return a full path to the resources directory.\nconst std::string& resources_dir();\n\n\/\/ Set a path with GUI localization files.\nvoid set_local_dir(const std::string &path);\n\/\/ Return a full path to the localization directory.\nconst std::string& localization_dir();\n\n\/\/ Set a path with preset files.\nvoid set_data_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& data_dir();\n\n\/\/ A special type for strings encoded in the local Windows 8-bit code page.\n\/\/ This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.\ntypedef std::string local_encoded_string;\n\n\/\/ Convert an UTF-8 encoded string into local coding.\n\/\/ On Windows, the UTF-8 string is converted to a local 8-bit code page.\n\/\/ On OSX and Linux, this function does no conversion and returns a copy of the source string.\nextern local_encoded_string encode_path(const char *src);\nextern std::string decode_path(const char *src);\nextern std::string normalize_utf8_nfc(const char *src);\n\n\/\/ Safely rename a file even if the target exists.\n\/\/ On Windows, the file explorer (or anti-virus or whatever else) often locks the file\n\/\/ for a short while, so the file may not be movable. Retry while we see recoverable errors.\nextern std::error_code rename_file(const std::string &from, const std::string &to);\n\n\/\/ Copy a file, adjust the access attributes, so that the target is writable.\nextern int copy_file(const std::string &from, const std::string &to);\n\n\/\/ Ignore system and hidden files, which may be created by the DropBox synchronisation process.\n\/\/ https:\/\/github.com\/prusa3d\/PrusaSlicer\/issues\/1298\nextern bool is_plain_file(const boost::filesystem::directory_entry &path);\nextern bool is_ini_file(const boost::filesystem::directory_entry &path);\nextern bool is_idx_file(const boost::filesystem::directory_entry &path);\n\n\/\/ File path \/ name \/ extension splitting utilities, working with UTF-8,\n\/\/ to be published to Perl.\nnamespace PerlUtils {\n \/\/ Get a file name including the extension.\n extern std::string path_to_filename(const char *src);\n \/\/ Get a file name without the extension.\n extern std::string path_to_stem(const char *src);\n \/\/ Get just the extension.\n extern std::string path_to_extension(const char *src);\n \/\/ Get a directory without the trailing slash.\n extern std::string path_to_parent_path(const char *src);\n};\n\nstd::string string_printf(const char *format, ...);\n\n\/\/ Standard \"generated by Slic3r version xxx timestamp xxx\" header string, \n\/\/ to be placed at the top of Slic3r generated files.\nstd::string header_slic3r_generated();\n\n\/\/ getpid platform wrapper\nextern unsigned get_current_pid();\n\ntemplate <typename Real>\nReal round_nearest(Real value, unsigned int decimals)\n{\n Real res = (Real)0;\n if (decimals == 0)\n res = ::round(value);\n else\n {\n Real power = ::pow((Real)10, (int)decimals);\n res = ::round(value * power + (Real)0.5) \/ power;\n }\n return res;\n}\n\n\/\/ Compute the next highest power of 2 of 32-bit v\n\/\/ http:\/\/graphics.stanford.edu\/~seander\/bithacks.html\ninline uint16_t next_highest_power_of_2(uint16_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n return ++ v;\n}\ninline uint32_t next_highest_power_of_2(uint32_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n return ++ v;\n}\ninline uint64_t next_highest_power_of_2(uint64_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v |= v >> 32;\n return ++ v;\n}\n\n\/\/ On some implementations (such as some versions of clang), the size_t is a type of its own, so we need to overload for size_t.\n\/\/ Typically, though, the size_t type aliases to uint64_t \/ uint32_t.\n\/\/ We distinguish that here and provide implementation for size_t if and only if it is a distinct type\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 8, T>::type = 0) \/\/ T is 64 bits\n{\n return next_highest_power_of_2(uint64_t(v));\n}\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 4, T>::type = 0) \/\/ T is 32 bits\n{\n return next_highest_power_of_2(uint32_t(v));\n}\n\n\nextern std::string xml_escape(std::string text);\n\n\n#if defined __GNUC__ && __GNUC__ < 5 && !defined __clang__\n\/\/ Older GCCs don't have std::is_trivially_copyable\n\/\/ cf. https:\/\/gcc.gnu.org\/onlinedocs\/gcc-4.9.4\/libstdc++\/manual\/manual\/status.html#status.iso.2011\n\/\/ #warning \"GCC version < 5, faking std::is_trivially_copyable\"\ntemplate<typename T> struct IsTriviallyCopyable { static constexpr bool value = true; };\n#else\ntemplate<typename T> struct IsTriviallyCopyable : public std::is_trivially_copyable<T> {};\n#endif\n\n\nclass ScopeGuard\n{\npublic:\n typedef std::function<void()> Closure;\nprivate:\n\/\/ bool committed;\n Closure closure;\n\npublic:\n ScopeGuard() {}\n ScopeGuard(Closure closure) : closure(std::move(closure)) {}\n ScopeGuard(const ScopeGuard&) = delete;\n ScopeGuard(ScopeGuard &&other) : closure(std::move(other.closure)) {}\n\n ~ScopeGuard()\n {\n if (closure) { closure(); }\n }\n\n ScopeGuard& operator=(const ScopeGuard&) = delete;\n ScopeGuard& operator=(ScopeGuard &&other)\n {\n closure = std::move(other.closure);\n return *this;\n }\n\n void reset() { closure = Closure(); }\n};\n\n\/\/ Shorten the dhms time by removing the seconds, rounding the dhm to full minutes\n\/\/ and removing spaces.\ninline std::string short_time(const std::string &time)\n{\n \/\/ Parse the dhms time format.\n int days = 0;\n int hours = 0;\n int minutes = 0;\n int seconds = 0;\n if (time.find('d') != std::string::npos)\n ::sscanf(time.c_str(), \"%dd %dh %dm %ds\", &days, &hours, &minutes, &seconds);\n else if (time.find('h') != std::string::npos)\n ::sscanf(time.c_str(), \"%dh %dm %ds\", &hours, &minutes, &seconds);\n else if (time.find('m') != std::string::npos)\n ::sscanf(time.c_str(), \"%dm %ds\", &minutes, &seconds);\n else if (time.find('s') != std::string::npos)\n ::sscanf(time.c_str(), \"%ds\", &seconds);\n \/\/ Round to full minutes.\n if (days + hours + minutes > 0 && seconds >= 30) {\n if (++minutes == 60) {\n minutes = 0;\n if (++hours == 24) {\n hours = 0;\n ++days;\n }\n }\n }\n \/\/ Format the dhm time.\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd%dh%dm\", days, hours, minutes);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh%dm\", hours, minutes);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm\", minutes);\n else\n ::sprintf(buffer, \"%ds\", seconds);\n return buffer;\n}\n\n\/\/ Returns the given time is seconds in format DDd HHh MMm SSs\ninline std::string get_time_dhms(float time_in_secs)\n{\n int days = (int)(time_in_secs \/ 86400.0f);\n time_in_secs -= (float)days * 86400.0f;\n int hours = (int)(time_in_secs \/ 3600.0f);\n time_in_secs -= (float)hours * 3600.0f;\n int minutes = (int)(time_in_secs \/ 60.0f);\n time_in_secs -= (float)minutes * 60.0f;\n\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd %dh %dm %ds\", days, hours, minutes, (int)time_in_secs);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh %dm %ds\", hours, minutes, (int)time_in_secs);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm %ds\", minutes, (int)time_in_secs);\n else\n ::sprintf(buffer, \"%ds\", (int)time_in_secs);\n\n return buffer;\n}\n\n} \/\/ namespace Slic3r\n\n#if WIN32\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + __alignof(TYPE) - 1) \/ __alignof(TYPE)) * __alignof(TYPE)\n#else\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + alignof(TYPE) - 1) \/ alignof(TYPE)) * alignof(TYPE)\n#endif\n\n#endif \/\/ slic3r_Utils_hpp_\n<commit_msg>Fix compilation without pch. <commit_after>#ifndef slic3r_Utils_hpp_\n#define slic3r_Utils_hpp_\n\n#include <locale>\n#include <utility>\n#include <functional>\n#include <type_traits>\n#include <system_error>\n\n#include \"libslic3r.h\"\n\nnamespace boost { namespace filesystem { class directory_entry; }}\n\nnamespace Slic3r {\n\nextern void set_logging_level(unsigned int level);\nextern unsigned get_logging_level();\nextern void trace(unsigned int level, const char *message);\n\/\/ Format memory allocated, separate thousands by comma.\nextern std::string format_memsize_MB(size_t n);\n\/\/ Return string to be added to the boost::log output to inform about the current process memory allocation.\n\/\/ The string is non-empty if the loglevel >= info (3) or ignore_loglevel==true.\n\/\/ Latter is used to get the memory info from SysInfoDialog.\nextern std::string log_memory_info(bool ignore_loglevel = false);\nextern void disable_multi_threading();\n\/\/ Returns the size of physical memory (RAM) in bytes.\nextern size_t total_physical_memory();\n\n\/\/ Set a path with GUI resource files.\nvoid set_var_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& var_dir();\n\/\/ Return a full resource path for a file_name.\nstd::string var(const std::string &file_name);\n\n\/\/ Set a path with various static definition data (for example the initial config bundles).\nvoid set_resources_dir(const std::string &path);\n\/\/ Return a full path to the resources directory.\nconst std::string& resources_dir();\n\n\/\/ Set a path with GUI localization files.\nvoid set_local_dir(const std::string &path);\n\/\/ Return a full path to the localization directory.\nconst std::string& localization_dir();\n\n\/\/ Set a path with preset files.\nvoid set_data_dir(const std::string &path);\n\/\/ Return a full path to the GUI resource files.\nconst std::string& data_dir();\n\n\/\/ A special type for strings encoded in the local Windows 8-bit code page.\n\/\/ This type is only needed for Perl bindings to relay to Perl that the string is raw, not UTF-8 encoded.\ntypedef std::string local_encoded_string;\n\n\/\/ Convert an UTF-8 encoded string into local coding.\n\/\/ On Windows, the UTF-8 string is converted to a local 8-bit code page.\n\/\/ On OSX and Linux, this function does no conversion and returns a copy of the source string.\nextern local_encoded_string encode_path(const char *src);\nextern std::string decode_path(const char *src);\nextern std::string normalize_utf8_nfc(const char *src);\n\n\/\/ Safely rename a file even if the target exists.\n\/\/ On Windows, the file explorer (or anti-virus or whatever else) often locks the file\n\/\/ for a short while, so the file may not be movable. Retry while we see recoverable errors.\nextern std::error_code rename_file(const std::string &from, const std::string &to);\n\n\/\/ Copy a file, adjust the access attributes, so that the target is writable.\nextern int copy_file(const std::string &from, const std::string &to);\n\n\/\/ Ignore system and hidden files, which may be created by the DropBox synchronisation process.\n\/\/ https:\/\/github.com\/prusa3d\/PrusaSlicer\/issues\/1298\nextern bool is_plain_file(const boost::filesystem::directory_entry &path);\nextern bool is_ini_file(const boost::filesystem::directory_entry &path);\nextern bool is_idx_file(const boost::filesystem::directory_entry &path);\n\n\/\/ File path \/ name \/ extension splitting utilities, working with UTF-8,\n\/\/ to be published to Perl.\nnamespace PerlUtils {\n \/\/ Get a file name including the extension.\n extern std::string path_to_filename(const char *src);\n \/\/ Get a file name without the extension.\n extern std::string path_to_stem(const char *src);\n \/\/ Get just the extension.\n extern std::string path_to_extension(const char *src);\n \/\/ Get a directory without the trailing slash.\n extern std::string path_to_parent_path(const char *src);\n};\n\nstd::string string_printf(const char *format, ...);\n\n\/\/ Standard \"generated by Slic3r version xxx timestamp xxx\" header string, \n\/\/ to be placed at the top of Slic3r generated files.\nstd::string header_slic3r_generated();\n\n\/\/ getpid platform wrapper\nextern unsigned get_current_pid();\n\ntemplate <typename Real>\nReal round_nearest(Real value, unsigned int decimals)\n{\n Real res = (Real)0;\n if (decimals == 0)\n res = ::round(value);\n else\n {\n Real power = ::pow((Real)10, (int)decimals);\n res = ::round(value * power + (Real)0.5) \/ power;\n }\n return res;\n}\n\n\/\/ Compute the next highest power of 2 of 32-bit v\n\/\/ http:\/\/graphics.stanford.edu\/~seander\/bithacks.html\ninline uint16_t next_highest_power_of_2(uint16_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n return ++ v;\n}\ninline uint32_t next_highest_power_of_2(uint32_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n return ++ v;\n}\ninline uint64_t next_highest_power_of_2(uint64_t v)\n{\n if (v != 0)\n -- v;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v |= v >> 32;\n return ++ v;\n}\n\n\/\/ On some implementations (such as some versions of clang), the size_t is a type of its own, so we need to overload for size_t.\n\/\/ Typically, though, the size_t type aliases to uint64_t \/ uint32_t.\n\/\/ We distinguish that here and provide implementation for size_t if and only if it is a distinct type\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 8, T>::type = 0) \/\/ T is 64 bits\n{\n return next_highest_power_of_2(uint64_t(v));\n}\ntemplate<class T> size_t next_highest_power_of_2(T v,\n typename std::enable_if<std::is_same<T, size_t>::value, T>::type = 0, \/\/ T is size_t\n typename std::enable_if<!std::is_same<T, uint64_t>::value, T>::type = 0, \/\/ T is not uint64_t\n typename std::enable_if<!std::is_same<T, uint32_t>::value, T>::type = 0, \/\/ T is not uint32_t\n typename std::enable_if<sizeof(T) == 4, T>::type = 0) \/\/ T is 32 bits\n{\n return next_highest_power_of_2(uint32_t(v));\n}\n\n\nextern std::string xml_escape(std::string text);\n\n\n#if defined __GNUC__ && __GNUC__ < 5 && !defined __clang__\n\/\/ Older GCCs don't have std::is_trivially_copyable\n\/\/ cf. https:\/\/gcc.gnu.org\/onlinedocs\/gcc-4.9.4\/libstdc++\/manual\/manual\/status.html#status.iso.2011\n\/\/ #warning \"GCC version < 5, faking std::is_trivially_copyable\"\ntemplate<typename T> struct IsTriviallyCopyable { static constexpr bool value = true; };\n#else\ntemplate<typename T> struct IsTriviallyCopyable : public std::is_trivially_copyable<T> {};\n#endif\n\n\nclass ScopeGuard\n{\npublic:\n typedef std::function<void()> Closure;\nprivate:\n\/\/ bool committed;\n Closure closure;\n\npublic:\n ScopeGuard() {}\n ScopeGuard(Closure closure) : closure(std::move(closure)) {}\n ScopeGuard(const ScopeGuard&) = delete;\n ScopeGuard(ScopeGuard &&other) : closure(std::move(other.closure)) {}\n\n ~ScopeGuard()\n {\n if (closure) { closure(); }\n }\n\n ScopeGuard& operator=(const ScopeGuard&) = delete;\n ScopeGuard& operator=(ScopeGuard &&other)\n {\n closure = std::move(other.closure);\n return *this;\n }\n\n void reset() { closure = Closure(); }\n};\n\n\/\/ Shorten the dhms time by removing the seconds, rounding the dhm to full minutes\n\/\/ and removing spaces.\ninline std::string short_time(const std::string &time)\n{\n \/\/ Parse the dhms time format.\n int days = 0;\n int hours = 0;\n int minutes = 0;\n int seconds = 0;\n if (time.find('d') != std::string::npos)\n ::sscanf(time.c_str(), \"%dd %dh %dm %ds\", &days, &hours, &minutes, &seconds);\n else if (time.find('h') != std::string::npos)\n ::sscanf(time.c_str(), \"%dh %dm %ds\", &hours, &minutes, &seconds);\n else if (time.find('m') != std::string::npos)\n ::sscanf(time.c_str(), \"%dm %ds\", &minutes, &seconds);\n else if (time.find('s') != std::string::npos)\n ::sscanf(time.c_str(), \"%ds\", &seconds);\n \/\/ Round to full minutes.\n if (days + hours + minutes > 0 && seconds >= 30) {\n if (++minutes == 60) {\n minutes = 0;\n if (++hours == 24) {\n hours = 0;\n ++days;\n }\n }\n }\n \/\/ Format the dhm time.\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd%dh%dm\", days, hours, minutes);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh%dm\", hours, minutes);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm\", minutes);\n else\n ::sprintf(buffer, \"%ds\", seconds);\n return buffer;\n}\n\n\/\/ Returns the given time is seconds in format DDd HHh MMm SSs\ninline std::string get_time_dhms(float time_in_secs)\n{\n int days = (int)(time_in_secs \/ 86400.0f);\n time_in_secs -= (float)days * 86400.0f;\n int hours = (int)(time_in_secs \/ 3600.0f);\n time_in_secs -= (float)hours * 3600.0f;\n int minutes = (int)(time_in_secs \/ 60.0f);\n time_in_secs -= (float)minutes * 60.0f;\n\n char buffer[64];\n if (days > 0)\n ::sprintf(buffer, \"%dd %dh %dm %ds\", days, hours, minutes, (int)time_in_secs);\n else if (hours > 0)\n ::sprintf(buffer, \"%dh %dm %ds\", hours, minutes, (int)time_in_secs);\n else if (minutes > 0)\n ::sprintf(buffer, \"%dm %ds\", minutes, (int)time_in_secs);\n else\n ::sprintf(buffer, \"%ds\", (int)time_in_secs);\n\n return buffer;\n}\n\n} \/\/ namespace Slic3r\n\n#if WIN32\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + __alignof(TYPE) - 1) \/ __alignof(TYPE)) * __alignof(TYPE)\n#else\n #define SLIC3R_STDVEC_MEMSIZE(NAME, TYPE) NAME.capacity() * ((sizeof(TYPE) + alignof(TYPE) - 1) \/ alignof(TYPE)) * alignof(TYPE)\n#endif\n\n#endif \/\/ slic3r_Utils_hpp_\n<|endoftext|>"} {"text":"<commit_before>#include \"globals.hh\"\n#include \"util.hh\"\n#include \"archive.hh\"\n#include \"args.hh\"\n#include \"abstract-setting-to-json.hh\"\n#include \"compute-levels.hh\"\n\n#include <algorithm>\n#include <map>\n#include <thread>\n#include <dlfcn.h>\n#include <sys\/utsname.h>\n\n#include <nlohmann\/json.hpp>\n\n\nnamespace nix {\n\n\n\/* The default location of the daemon socket, relative to nixStateDir.\n The socket is in a directory to allow you to control access to the\n Nix daemon by setting the mode\/ownership of the directory\n appropriately. (This wouldn't work on the socket itself since it\n must be deleted and recreated on startup.) *\/\n#define DEFAULT_SOCKET_PATH \"\/daemon-socket\/socket\"\n\nSettings settings;\n\nstatic GlobalConfig::Register rSettings(&settings);\n\nSettings::Settings()\n : nixPrefix(NIX_PREFIX)\n , nixStore(canonPath(getEnv(\"NIX_STORE_DIR\").value_or(getEnv(\"NIX_STORE\").value_or(NIX_STORE_DIR))))\n , nixDataDir(canonPath(getEnv(\"NIX_DATA_DIR\").value_or(NIX_DATA_DIR)))\n , nixLogDir(canonPath(getEnv(\"NIX_LOG_DIR\").value_or(NIX_LOG_DIR)))\n , nixStateDir(canonPath(getEnv(\"NIX_STATE_DIR\").value_or(NIX_STATE_DIR)))\n , nixConfDir(canonPath(getEnv(\"NIX_CONF_DIR\").value_or(NIX_CONF_DIR)))\n , nixUserConfFiles(getUserConfigFiles())\n , nixBinDir(canonPath(getEnv(\"NIX_BIN_DIR\").value_or(NIX_BIN_DIR)))\n , nixManDir(canonPath(NIX_MAN_DIR))\n , nixDaemonSocketFile(canonPath(getEnv(\"NIX_DAEMON_SOCKET_PATH\").value_or(nixStateDir + DEFAULT_SOCKET_PATH)))\n{\n buildUsersGroup = getuid() == 0 ? \"nixbld\" : \"\";\n lockCPU = getEnv(\"NIX_AFFINITY_HACK\") == \"1\";\n allowSymlinkedStore = getEnv(\"NIX_IGNORE_SYMLINK_STORE\") == \"1\";\n\n caFile = getEnv(\"NIX_SSL_CERT_FILE\").value_or(getEnv(\"SSL_CERT_FILE\").value_or(\"\"));\n if (caFile == \"\") {\n for (auto & fn : {\"\/etc\/ssl\/certs\/ca-certificates.crt\", \"\/nix\/var\/nix\/profiles\/default\/etc\/ssl\/certs\/ca-bundle.crt\"})\n if (pathExists(fn)) {\n caFile = fn;\n break;\n }\n }\n\n \/* Backwards compatibility. *\/\n auto s = getEnv(\"NIX_REMOTE_SYSTEMS\");\n if (s) {\n Strings ss;\n for (auto & p : tokenizeString<Strings>(*s, \":\"))\n ss.push_back(\"@\" + p);\n builders = concatStringsSep(\" \", ss);\n }\n\n#if defined(__linux__) && defined(SANDBOX_SHELL)\n sandboxPaths = tokenizeString<StringSet>(\"\/bin\/sh=\" SANDBOX_SHELL);\n#endif\n\n \/* chroot-like behavior from Apple's sandbox *\/\n#if __APPLE__\n sandboxPaths = tokenizeString<StringSet>(\"\/System\/Library\/Frameworks \/System\/Library\/PrivateFrameworks \/bin\/sh \/bin\/bash \/private\/tmp \/private\/var\/tmp \/usr\/lib\");\n allowedImpureHostPrefixes = tokenizeString<StringSet>(\"\/System\/Library \/usr\/lib \/dev \/bin\/sh\");\n#endif\n\n buildHook = getSelfExe().value_or(\"nix\") + \" __build-remote\";\n}\n\nvoid loadConfFile()\n{\n globalConfig.applyConfigFile(settings.nixConfDir + \"\/nix.conf\");\n\n \/* We only want to send overrides to the daemon, i.e. stuff from\n ~\/.nix\/nix.conf or the command line. *\/\n globalConfig.resetOverridden();\n\n auto files = settings.nixUserConfFiles;\n for (auto file = files.rbegin(); file != files.rend(); file++) {\n globalConfig.applyConfigFile(*file);\n }\n\n auto nixConfEnv = getEnv(\"NIX_CONFIG\");\n if (nixConfEnv.has_value()) {\n globalConfig.applyConfig(nixConfEnv.value(), \"NIX_CONFIG\");\n }\n\n}\n\nstd::vector<Path> getUserConfigFiles()\n{\n \/\/ Use the paths specified in NIX_USER_CONF_FILES if it has been defined\n auto nixConfFiles = getEnv(\"NIX_USER_CONF_FILES\");\n if (nixConfFiles.has_value()) {\n return tokenizeString<std::vector<std::string>>(nixConfFiles.value(), \":\");\n }\n\n \/\/ Use the paths specified by the XDG spec\n std::vector<Path> files;\n auto dirs = getConfigDirs();\n for (auto & dir : dirs) {\n files.insert(files.end(), dir + \"\/nix\/nix.conf\");\n }\n return files;\n}\n\nunsigned int Settings::getDefaultCores()\n{\n return std::max(1U, std::thread::hardware_concurrency());\n}\n\nStringSet Settings::getDefaultSystemFeatures()\n{\n \/* For backwards compatibility, accept some \"features\" that are\n used in Nixpkgs to route builds to certain machines but don't\n actually require anything special on the machines. *\/\n StringSet features{\"nixos-test\", \"benchmark\", \"big-parallel\"};\n\n #if __linux__\n if (access(\"\/dev\/kvm\", R_OK | W_OK) == 0)\n features.insert(\"kvm\");\n #endif\n\n return features;\n}\n\nStringSet Settings::getDefaultExtraPlatforms()\n{\n StringSet extraPlatforms;\n\n if (std::string{SYSTEM} == \"x86_64-linux\" && !isWSL1())\n extraPlatforms.insert(\"i686-linux\");\n\n#if __linux__\n StringSet levels = computeLevels();\n for (auto iter = levels.begin(); iter != levels.end(); ++iter)\n extraPlatforms.insert(*iter + \"-linux\");\n#elif __APPLE__\n \/\/ Rosetta 2 emulation layer can run x86_64 binaries on aarch64\n \/\/ machines. Note that we can’t force processes from executing\n \/\/ x86_64 in aarch64 environments or vice versa since they can\n \/\/ always exec with their own binary preferences.\n if (pathExists(\"\/Library\/Apple\/System\/Library\/LaunchDaemons\/com.apple.oahd.plist\") ||\n pathExists(\"\/System\/Library\/LaunchDaemons\/com.apple.oahd.plist\")) {\n if (std::string{SYSTEM} == \"x86_64-darwin\")\n extraPlatforms.insert(\"aarch64-darwin\");\n else if (std::string{SYSTEM} == \"aarch64-darwin\")\n extraPlatforms.insert(\"x86_64-darwin\");\n }\n#endif\n\n return extraPlatforms;\n}\n\nbool Settings::isExperimentalFeatureEnabled(const ExperimentalFeature & feature)\n{\n auto & f = experimentalFeatures.get();\n return std::find(f.begin(), f.end(), feature) != f.end();\n}\n\nvoid Settings::requireExperimentalFeature(const ExperimentalFeature & feature)\n{\n if (!isExperimentalFeatureEnabled(feature))\n throw MissingExperimentalFeature(feature);\n}\n\nbool Settings::isWSL1()\n{\n struct utsname utsbuf;\n uname(&utsbuf);\n \/\/ WSL1 uses -Microsoft suffix\n \/\/ WSL2 uses -microsoft-standard suffix\n return hasSuffix(utsbuf.release, \"-Microsoft\");\n}\n\nconst std::string nixVersion = PACKAGE_VERSION;\n\nNLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {\n {SandboxMode::smEnabled, true},\n {SandboxMode::smRelaxed, \"relaxed\"},\n {SandboxMode::smDisabled, false},\n});\n\ntemplate<> void BaseSetting<SandboxMode>::set(const std::string & str, bool append)\n{\n if (str == \"true\") value = smEnabled;\n else if (str == \"relaxed\") value = smRelaxed;\n else if (str == \"false\") value = smDisabled;\n else throw UsageError(\"option '%s' has invalid value '%s'\", name, str);\n}\n\ntemplate<> bool BaseSetting<SandboxMode>::isAppendable()\n{\n return false;\n}\n\ntemplate<> std::string BaseSetting<SandboxMode>::to_string() const\n{\n if (value == smEnabled) return \"true\";\n else if (value == smRelaxed) return \"relaxed\";\n else if (value == smDisabled) return \"false\";\n else abort();\n}\n\ntemplate<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)\n{\n args.addFlag({\n .longName = name,\n .description = \"Enable sandboxing.\",\n .category = category,\n .handler = {[=]() { override(smEnabled); }}\n });\n args.addFlag({\n .longName = \"no-\" + name,\n .description = \"Disable sandboxing.\",\n .category = category,\n .handler = {[=]() { override(smDisabled); }}\n });\n args.addFlag({\n .longName = \"relaxed-\" + name,\n .description = \"Enable sandboxing, but allow builds to disable it.\",\n .category = category,\n .handler = {[=]() { override(smRelaxed); }}\n });\n}\n\nvoid MaxBuildJobsSetting::set(const std::string & str, bool append)\n{\n if (str == \"auto\") value = std::max(1U, std::thread::hardware_concurrency());\n else {\n if (auto n = string2Int<decltype(value)>(str))\n value = *n;\n else\n throw UsageError(\"configuration setting '%s' should be 'auto' or an integer\", name);\n }\n}\n\n\nvoid PluginFilesSetting::set(const std::string & str, bool append)\n{\n if (pluginsLoaded)\n throw UsageError(\"plugin-files set after plugins were loaded, you may need to move the flag before the subcommand\");\n BaseSetting<Paths>::set(str, append);\n}\n\n\nvoid initPlugins()\n{\n assert(!settings.pluginFiles.pluginsLoaded);\n for (const auto & pluginFile : settings.pluginFiles.get()) {\n Paths pluginFiles;\n try {\n auto ents = readDirectory(pluginFile);\n for (const auto & ent : ents)\n pluginFiles.emplace_back(pluginFile + \"\/\" + ent.name);\n } catch (SysError & e) {\n if (e.errNo != ENOTDIR)\n throw;\n pluginFiles.emplace_back(pluginFile);\n }\n for (const auto & file : pluginFiles) {\n \/* handle is purposefully leaked as there may be state in the\n DSO needed by the action of the plugin. *\/\n void *handle =\n dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);\n if (!handle)\n throw Error(\"could not dynamically open plugin file '%s': %s\", file, dlerror());\n }\n }\n\n \/* Since plugins can add settings, try to re-apply previously\n unknown settings. *\/\n globalConfig.reapplyUnknownSettings();\n globalConfig.warnUnknownSettings();\n\n \/* Tell the user if they try to set plugin-files after we've already loaded *\/\n settings.pluginFiles.pluginsLoaded = true;\n}\n\n}\n<commit_msg>libstore\/globals.cc: Automatically set cores based on cgroup CPU limit<commit_after>#include \"globals.hh\"\n#include \"util.hh\"\n#include \"archive.hh\"\n#include \"args.hh\"\n#include \"abstract-setting-to-json.hh\"\n#include \"compute-levels.hh\"\n\n#include <algorithm>\n#include <map>\n#include <thread>\n#include <dlfcn.h>\n#include <sys\/utsname.h>\n\n#if __linux__\n#include <mntent.h>\n#include <cmath>\n#endif\n\n#include <nlohmann\/json.hpp>\n\n\nnamespace nix {\n\n\n\/* The default location of the daemon socket, relative to nixStateDir.\n The socket is in a directory to allow you to control access to the\n Nix daemon by setting the mode\/ownership of the directory\n appropriately. (This wouldn't work on the socket itself since it\n must be deleted and recreated on startup.) *\/\n#define DEFAULT_SOCKET_PATH \"\/daemon-socket\/socket\"\n\nSettings settings;\n\nstatic GlobalConfig::Register rSettings(&settings);\n\nSettings::Settings()\n : nixPrefix(NIX_PREFIX)\n , nixStore(canonPath(getEnv(\"NIX_STORE_DIR\").value_or(getEnv(\"NIX_STORE\").value_or(NIX_STORE_DIR))))\n , nixDataDir(canonPath(getEnv(\"NIX_DATA_DIR\").value_or(NIX_DATA_DIR)))\n , nixLogDir(canonPath(getEnv(\"NIX_LOG_DIR\").value_or(NIX_LOG_DIR)))\n , nixStateDir(canonPath(getEnv(\"NIX_STATE_DIR\").value_or(NIX_STATE_DIR)))\n , nixConfDir(canonPath(getEnv(\"NIX_CONF_DIR\").value_or(NIX_CONF_DIR)))\n , nixUserConfFiles(getUserConfigFiles())\n , nixBinDir(canonPath(getEnv(\"NIX_BIN_DIR\").value_or(NIX_BIN_DIR)))\n , nixManDir(canonPath(NIX_MAN_DIR))\n , nixDaemonSocketFile(canonPath(getEnv(\"NIX_DAEMON_SOCKET_PATH\").value_or(nixStateDir + DEFAULT_SOCKET_PATH)))\n{\n buildUsersGroup = getuid() == 0 ? \"nixbld\" : \"\";\n lockCPU = getEnv(\"NIX_AFFINITY_HACK\") == \"1\";\n allowSymlinkedStore = getEnv(\"NIX_IGNORE_SYMLINK_STORE\") == \"1\";\n\n caFile = getEnv(\"NIX_SSL_CERT_FILE\").value_or(getEnv(\"SSL_CERT_FILE\").value_or(\"\"));\n if (caFile == \"\") {\n for (auto & fn : {\"\/etc\/ssl\/certs\/ca-certificates.crt\", \"\/nix\/var\/nix\/profiles\/default\/etc\/ssl\/certs\/ca-bundle.crt\"})\n if (pathExists(fn)) {\n caFile = fn;\n break;\n }\n }\n\n \/* Backwards compatibility. *\/\n auto s = getEnv(\"NIX_REMOTE_SYSTEMS\");\n if (s) {\n Strings ss;\n for (auto & p : tokenizeString<Strings>(*s, \":\"))\n ss.push_back(\"@\" + p);\n builders = concatStringsSep(\" \", ss);\n }\n\n#if defined(__linux__) && defined(SANDBOX_SHELL)\n sandboxPaths = tokenizeString<StringSet>(\"\/bin\/sh=\" SANDBOX_SHELL);\n#endif\n\n \/* chroot-like behavior from Apple's sandbox *\/\n#if __APPLE__\n sandboxPaths = tokenizeString<StringSet>(\"\/System\/Library\/Frameworks \/System\/Library\/PrivateFrameworks \/bin\/sh \/bin\/bash \/private\/tmp \/private\/var\/tmp \/usr\/lib\");\n allowedImpureHostPrefixes = tokenizeString<StringSet>(\"\/System\/Library \/usr\/lib \/dev \/bin\/sh\");\n#endif\n\n buildHook = getSelfExe().value_or(\"nix\") + \" __build-remote\";\n}\n\nvoid loadConfFile()\n{\n globalConfig.applyConfigFile(settings.nixConfDir + \"\/nix.conf\");\n\n \/* We only want to send overrides to the daemon, i.e. stuff from\n ~\/.nix\/nix.conf or the command line. *\/\n globalConfig.resetOverridden();\n\n auto files = settings.nixUserConfFiles;\n for (auto file = files.rbegin(); file != files.rend(); file++) {\n globalConfig.applyConfigFile(*file);\n }\n\n auto nixConfEnv = getEnv(\"NIX_CONFIG\");\n if (nixConfEnv.has_value()) {\n globalConfig.applyConfig(nixConfEnv.value(), \"NIX_CONFIG\");\n }\n\n}\n\nstd::vector<Path> getUserConfigFiles()\n{\n \/\/ Use the paths specified in NIX_USER_CONF_FILES if it has been defined\n auto nixConfFiles = getEnv(\"NIX_USER_CONF_FILES\");\n if (nixConfFiles.has_value()) {\n return tokenizeString<std::vector<std::string>>(nixConfFiles.value(), \":\");\n }\n\n \/\/ Use the paths specified by the XDG spec\n std::vector<Path> files;\n auto dirs = getConfigDirs();\n for (auto & dir : dirs) {\n files.insert(files.end(), dir + \"\/nix\/nix.conf\");\n }\n return files;\n}\n\nunsigned int Settings::getDefaultCores()\n{\n unsigned int concurrency = std::max(1U, std::thread::hardware_concurrency());\n\n #if __linux__\n FILE *fp = fopen(\"\/proc\/mounts\", \"r\");\n if (!fp)\n return concurrency;\n\n Strings cgPathParts;\n\n struct mntent *ent;\n while ((ent = getmntent(fp))) {\n std::string mountType, mountPath;\n\n mountType = ent->mnt_type;\n mountPath = ent->mnt_dir;\n\n if (mountType == \"cgroup2\") {\n cgPathParts.push_back(mountPath);\n break;\n }\n }\n\n fclose(fp);\n\n if (cgPathParts.size() > 0 && pathExists(\"\/proc\/self\/cgroup\")) {\n std::string currentCgroup = readFile(\"\/proc\/self\/cgroup\");\n Strings cgValues = tokenizeString<Strings>(currentCgroup, \":\");\n cgPathParts.push_back(trim(cgValues.back(), \"\\n\"));\n cgPathParts.push_back(\"cpu.max\");\n std::string fullCgPath = canonPath(concatStringsSep(\"\/\", cgPathParts));\n\n if (pathExists(fullCgPath)) {\n std::string cpuMax = readFile(fullCgPath);\n std::vector<std::string> cpuMaxParts = tokenizeString<std::vector<std::string>>(cpuMax, \" \");\n std::string quota = cpuMaxParts[0];\n std::string period = trim(cpuMaxParts[1], \"\\n\");\n\n if (quota != \"max\")\n concurrency = std::ceil(std::stoi(quota) \/ std::stof(period));\n }\n }\n #endif\n\n return concurrency;\n}\n\nStringSet Settings::getDefaultSystemFeatures()\n{\n \/* For backwards compatibility, accept some \"features\" that are\n used in Nixpkgs to route builds to certain machines but don't\n actually require anything special on the machines. *\/\n StringSet features{\"nixos-test\", \"benchmark\", \"big-parallel\"};\n\n #if __linux__\n if (access(\"\/dev\/kvm\", R_OK | W_OK) == 0)\n features.insert(\"kvm\");\n #endif\n\n return features;\n}\n\nStringSet Settings::getDefaultExtraPlatforms()\n{\n StringSet extraPlatforms;\n\n if (std::string{SYSTEM} == \"x86_64-linux\" && !isWSL1())\n extraPlatforms.insert(\"i686-linux\");\n\n#if __linux__\n StringSet levels = computeLevels();\n for (auto iter = levels.begin(); iter != levels.end(); ++iter)\n extraPlatforms.insert(*iter + \"-linux\");\n#elif __APPLE__\n \/\/ Rosetta 2 emulation layer can run x86_64 binaries on aarch64\n \/\/ machines. Note that we can’t force processes from executing\n \/\/ x86_64 in aarch64 environments or vice versa since they can\n \/\/ always exec with their own binary preferences.\n if (pathExists(\"\/Library\/Apple\/System\/Library\/LaunchDaemons\/com.apple.oahd.plist\") ||\n pathExists(\"\/System\/Library\/LaunchDaemons\/com.apple.oahd.plist\")) {\n if (std::string{SYSTEM} == \"x86_64-darwin\")\n extraPlatforms.insert(\"aarch64-darwin\");\n else if (std::string{SYSTEM} == \"aarch64-darwin\")\n extraPlatforms.insert(\"x86_64-darwin\");\n }\n#endif\n\n return extraPlatforms;\n}\n\nbool Settings::isExperimentalFeatureEnabled(const ExperimentalFeature & feature)\n{\n auto & f = experimentalFeatures.get();\n return std::find(f.begin(), f.end(), feature) != f.end();\n}\n\nvoid Settings::requireExperimentalFeature(const ExperimentalFeature & feature)\n{\n if (!isExperimentalFeatureEnabled(feature))\n throw MissingExperimentalFeature(feature);\n}\n\nbool Settings::isWSL1()\n{\n struct utsname utsbuf;\n uname(&utsbuf);\n \/\/ WSL1 uses -Microsoft suffix\n \/\/ WSL2 uses -microsoft-standard suffix\n return hasSuffix(utsbuf.release, \"-Microsoft\");\n}\n\nconst std::string nixVersion = PACKAGE_VERSION;\n\nNLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {\n {SandboxMode::smEnabled, true},\n {SandboxMode::smRelaxed, \"relaxed\"},\n {SandboxMode::smDisabled, false},\n});\n\ntemplate<> void BaseSetting<SandboxMode>::set(const std::string & str, bool append)\n{\n if (str == \"true\") value = smEnabled;\n else if (str == \"relaxed\") value = smRelaxed;\n else if (str == \"false\") value = smDisabled;\n else throw UsageError(\"option '%s' has invalid value '%s'\", name, str);\n}\n\ntemplate<> bool BaseSetting<SandboxMode>::isAppendable()\n{\n return false;\n}\n\ntemplate<> std::string BaseSetting<SandboxMode>::to_string() const\n{\n if (value == smEnabled) return \"true\";\n else if (value == smRelaxed) return \"relaxed\";\n else if (value == smDisabled) return \"false\";\n else abort();\n}\n\ntemplate<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)\n{\n args.addFlag({\n .longName = name,\n .description = \"Enable sandboxing.\",\n .category = category,\n .handler = {[=]() { override(smEnabled); }}\n });\n args.addFlag({\n .longName = \"no-\" + name,\n .description = \"Disable sandboxing.\",\n .category = category,\n .handler = {[=]() { override(smDisabled); }}\n });\n args.addFlag({\n .longName = \"relaxed-\" + name,\n .description = \"Enable sandboxing, but allow builds to disable it.\",\n .category = category,\n .handler = {[=]() { override(smRelaxed); }}\n });\n}\n\nvoid MaxBuildJobsSetting::set(const std::string & str, bool append)\n{\n if (str == \"auto\") value = std::max(1U, std::thread::hardware_concurrency());\n else {\n if (auto n = string2Int<decltype(value)>(str))\n value = *n;\n else\n throw UsageError(\"configuration setting '%s' should be 'auto' or an integer\", name);\n }\n}\n\n\nvoid PluginFilesSetting::set(const std::string & str, bool append)\n{\n if (pluginsLoaded)\n throw UsageError(\"plugin-files set after plugins were loaded, you may need to move the flag before the subcommand\");\n BaseSetting<Paths>::set(str, append);\n}\n\n\nvoid initPlugins()\n{\n assert(!settings.pluginFiles.pluginsLoaded);\n for (const auto & pluginFile : settings.pluginFiles.get()) {\n Paths pluginFiles;\n try {\n auto ents = readDirectory(pluginFile);\n for (const auto & ent : ents)\n pluginFiles.emplace_back(pluginFile + \"\/\" + ent.name);\n } catch (SysError & e) {\n if (e.errNo != ENOTDIR)\n throw;\n pluginFiles.emplace_back(pluginFile);\n }\n for (const auto & file : pluginFiles) {\n \/* handle is purposefully leaked as there may be state in the\n DSO needed by the action of the plugin. *\/\n void *handle =\n dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);\n if (!handle)\n throw Error(\"could not dynamically open plugin file '%s': %s\", file, dlerror());\n }\n }\n\n \/* Since plugins can add settings, try to re-apply previously\n unknown settings. *\/\n globalConfig.reapplyUnknownSettings();\n globalConfig.warnUnknownSettings();\n\n \/* Tell the user if they try to set plugin-files after we've already loaded *\/\n settings.pluginFiles.pluginsLoaded = true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2019 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <votca\/xtp\/eigencuda.h>\n\nnamespace votca {\nnamespace xtp {\n\/*\n * Removed all the allocated arrays from the device\n *\/\ntemplate <typename T>\nEigenCuda<T>::~EigenCuda() {\n \/\/ wait for everything to finish\n cudaDeviceSynchronize();\n \/\/ destroy handle\n cublasDestroy(_handle);\n \/\/ destroy stream\n cudaStreamDestroy(_stream);\n}\n\n\/*\n * Allocate memory in the device using either pinned or pageable (default)\n * memory\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gpu_alloc(T **x, std::size_t n) const {\n (_pinned) ? cudaMallocHost(x, n) : cudaMalloc(x, n);\n}\n\n\/*\n * Deallocate memory from the device\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gpu_free(T *x) const {\n (_pinned) ? cudaFreeHost(x) : cudaFree(x);\n};\n\n\/*\n * Allocate memory in the device for matrix A, then if if `copy_to_device`\n * copy the array to the device. Sometimes it only neccesary to allocate\n * space in the device without copying the array because the initial\n * values may not be important like a temporal matrix.\n *\/\ntemplate <typename T>\nT *EigenCuda<T>::initialize_matrix_mem(const Mat<T> &A, bool copy_to_device) {\n\n \/\/ size of the Matrices\n std::size_t size_A = A.size() * sizeof(T);\n\n \/\/ Pointer in the device\n T *dA;\n\n \/\/ Allocate either pageable or pinned memory\n gpu_alloc(&dA, size_A);\n\n \/\/ Transfer data to the GPU\n if (copy_to_device) {\n \/\/ Pointers at the host\n const T *hA = A.data();\n cudaError_t err =\n cudaMemcpyAsync(dA, hA, size_A, cudaMemcpyHostToDevice, _stream);\n if (err != 0) {\n throw std::runtime_error(\"Error copy arrays to device\");\n }\n }\n return dA;\n}\n\n\/*\n * Call the gemm function from cublas, resulting in the multiplication of the\n * two matrices with identifiers id_A and id_B. The result is stored in\n * a Matrix (pointer) with identifier id_C.\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gemm(Shapes sh, const T *dA, const T *dB, T *dC) {\n\n \/\/ Scalar constanst for calling blas\n T _alpha = 1.;\n T _beta = 0.;\n const T *_pa = &_alpha;\n const T *_pb = &_beta;\n\n \/\/ call gemm from cublas\n if constexpr (std::is_same<float, T>()) {\n cublasSgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows, sh.B_cols,\n sh.A_cols, _pa, dA, sh.A_rows, dB, sh.B_rows, _pb, dC,\n sh.C_rows);\n } else if (std::is_same<double, T>()) {\n cublasDgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows, sh.B_cols,\n sh.A_cols, _pa, dA, sh.A_rows, dB, sh.B_rows, _pb, dC,\n sh.C_rows);\n }\n}\n\n\/*\n * Call the gemm?Batched function from cublas, resembling a zip\n * operation of two 3D tensors, applying the gemm function in each pair\n * of matrices. Resulting in a 3D tensor containing the results of the\n * multiplication.\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gemmBatched(Shapes sh, const T **dA, const T **dB, T **dC,\n int batchCount) {\n\n \/\/ Scalar constanst for calling blas\n T _alpha = 1.;\n T _beta = 0.;\n const T *_pa = &_alpha;\n const T *_pb = &_beta;\n\n \/\/ call gemm from cublas\n cublasStatus_t status;\n if constexpr (std::is_same<float, T>()) {\n status = cublasSgemmBatched(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows,\n sh.B_cols, sh.A_cols, _pa, dA, sh.A_rows, dB,\n sh.B_rows, _pb, dC, sh.C_rows, batchCount);\n } else if (std::is_same<double, T>()) {\n status = cublasDgemmBatched(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows,\n sh.B_cols, sh.A_cols, _pa, dA, sh.A_rows, dB,\n sh.B_rows, _pb, dC, sh.C_rows, batchCount);\n }\n if (status != 0) {\n std::runtime_error(\"error calling cublas?DgemmBatched\");\n }\n}\n\n\/*\n * \\brief Multiply a matrix A by a 3D tensor represented as a vector of\n * matrices. \\return a matrix where each column represent the result product.\n * Initially, it allocates memory and copy the matrices A and C together with\n * the tensor to the device. Also, the function allocates the result tensor Y.\n * The method iterates over each submatrix of the tensor computing:\n * Y(i) = tensor(i) * A.\n * Finally, the tensor Y is copy back to the main memory.\n *\/\ntemplate <typename T>\nMat<T> EigenCuda<T>::dot(const Mat<T> &A, const Mat<T> &B) {\n \/\/ Matrix to store the result\n Mat<T> C = Mat<T>::Zero(A.rows(), B.cols());\n std::size_t size_C = C.size() * sizeof(T);\n\n \/\/ Indices of the matrices on the device\n T *dA = initialize_matrix_mem(A);\n T *dB = initialize_matrix_mem(B);\n T *dC = initialize_matrix_mem(C, false);\n\n \/\/ process on GPU\n Shapes sh{A.rows(), A.cols(), B.rows(), B.cols(), C.rows()};\n gemm(sh, dA, dB, dC);\n\n \/\/ send data back to CPU\n T *hC = C.data();\n cudaMemcpy(hC, dC, size_C, cudaMemcpyDeviceToHost);\n\n \/\/ create an eigen matrix\n C = Eigen::Map<Mat<T>>(hC, A.rows(), B.cols());\n\n \/\/ Free the result from the device\n gpu_free(dA);\n gpu_free(dB);\n gpu_free(dC);\n\n return C;\n}\ntemplate <typename T>\nstd::vector<Mat<T>> EigenCuda<T>::right_matrix_tensor(\n const Mat<T> &B, const std::vector<Mat<T>> &tensor) {\n \/\/ Number of submatrices in the input tensor\n int batchCount = tensor.size();\n\n \/\/ Copy Matrix B to the device\n T *mtxB = initialize_matrix_mem(B);\n\n \/\/ allocate space in device for the temporal matrix\n int rows = tensor[0].rows(); \/\/ rows of the submatrices\n int cols = tensor[0].cols(); \/\/ cols of the submatrices\n Mat<T> matrix = Mat<T>::Zero(rows, cols);\n\n \/\/ Allocate space and copy to the device the input tensor\n \/\/ Notice that hA, hB and hC are arrays IN THE HOST by the pointers\n \/\/ are allocated in the DEVICE.\n T *hA[batchCount];\n for (auto i = 0; i < batchCount; i++) {\n hA[i] = initialize_matrix_mem(tensor[i]);\n }\n\n \/\/ represent the matrix B as a tensor where all the submatrices are the same\n T *hB[batchCount];\n for (auto i = 0; i < batchCount; i++) {\n hB[i] = mtxB;\n }\n\n \/\/ Allocate space in the device for the output tensor\n T *hC[batchCount];\n Mat<T> output = Mat<T>::Zero(matrix.rows(), B.cols());\n for (auto i = 0; i < batchCount; i++) {\n hC[i] = initialize_matrix_mem(output, false);\n }\n\n \/\/ Allocate space in the device for the array of pointers\n const T **dA, **dB;\n T **dC;\n size_t size_batch = batchCount * sizeof(T *);\n cudaMalloc(&dA, size_batch);\n cudaMalloc(&dB, size_batch);\n cudaMalloc(&dC, size_batch);\n\n \/\/ Copy the arrays of pointers from host to the device\n cudaMemcpyAsync(dA, hA, size_batch, cudaMemcpyHostToDevice, _stream);\n cudaMemcpyAsync(dB, hB, size_batch, cudaMemcpyHostToDevice, _stream);\n cudaMemcpyAsync(dC, hC, size_batch, cudaMemcpyHostToDevice, _stream);\n\n \/\/ Call tensor matrix multiplication\n Shapes sh{matrix.rows(), matrix.cols(), B.rows(), B.cols(), matrix.rows()};\n gemmBatched(sh, dA, dB, dC, batchCount);\n\n \/\/ Vector containing the results\n std::vector<Mat<T>> rs(batchCount,\n Mat<T>::Zero(output.rows(), output.cols()));\n std::size_t size_out = output.size() * sizeof(T);\n\n \/\/ Copy Array of pointers on the device to the host\n cudaMemcpyAsync(hC, dC, size_batch, cudaMemcpyDeviceToHost, _stream);\n\n \/\/ Copy each array back to the device\n for (auto i = 0; i < batchCount; i++) {\n T *hout = rs[i].data();\n T *dout = hC[i];\n cudaMemcpyAsync(hout, dout, size_out, cudaMemcpyDeviceToHost, _stream);\n rs[i] = Eigen::Map<Mat<T>>(hout, output.rows(), output.cols());\n ;\n }\n \/\/ Deallocate all the memory from the device\n gpu_free(mtxB);\n cudaFree(dA);\n cudaFree(dB);\n cudaFree(dC);\n for (auto i = 0; i < batchCount; i++) {\n gpu_free(hA[i]);\n gpu_free(hC[i]);\n }\n\n return rs;\n}\n\n\/\/ explicit instantiations\ntemplate class EigenCuda<float>;\ntemplate class EigenCuda<double>;\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<commit_msg>updated dot doc #262<commit_after>\/*\n * Copyright 2009-2019 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <votca\/xtp\/eigencuda.h>\n\nnamespace votca {\nnamespace xtp {\n\/*\n * Removed all the allocated arrays from the device\n *\/\ntemplate <typename T>\nEigenCuda<T>::~EigenCuda() {\n \/\/ wait for everything to finish\n cudaDeviceSynchronize();\n \/\/ destroy handle\n cublasDestroy(_handle);\n \/\/ destroy stream\n cudaStreamDestroy(_stream);\n}\n\n\/*\n * Allocate memory in the device using either pinned or pageable (default)\n * memory\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gpu_alloc(T **x, std::size_t n) const {\n (_pinned) ? cudaMallocHost(x, n) : cudaMalloc(x, n);\n}\n\n\/*\n * Deallocate memory from the device\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gpu_free(T *x) const {\n (_pinned) ? cudaFreeHost(x) : cudaFree(x);\n};\n\n\/*\n * Allocate memory in the device for matrix A, then if if `copy_to_device`\n * copy the array to the device. Sometimes it only neccesary to allocate\n * space in the device without copying the array because the initial\n * values may not be important like a temporal matrix.\n *\/\ntemplate <typename T>\nT *EigenCuda<T>::initialize_matrix_mem(const Mat<T> &A, bool copy_to_device) {\n\n \/\/ size of the Matrices\n std::size_t size_A = A.size() * sizeof(T);\n\n \/\/ Pointer in the device\n T *dA;\n\n \/\/ Allocate either pageable or pinned memory\n gpu_alloc(&dA, size_A);\n\n \/\/ Transfer data to the GPU\n if (copy_to_device) {\n \/\/ Pointers at the host\n const T *hA = A.data();\n cudaError_t err =\n cudaMemcpyAsync(dA, hA, size_A, cudaMemcpyHostToDevice, _stream);\n if (err != 0) {\n throw std::runtime_error(\"Error copy arrays to device\");\n }\n }\n return dA;\n}\n\n\/*\n * Call the gemm function from cublas, resulting in the multiplication of the\n * two matrices with identifiers id_A and id_B. The result is stored in\n * a Matrix (pointer) with identifier id_C.\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gemm(Shapes sh, const T *dA, const T *dB, T *dC) {\n\n \/\/ Scalar constanst for calling blas\n T _alpha = 1.;\n T _beta = 0.;\n const T *_pa = &_alpha;\n const T *_pb = &_beta;\n\n \/\/ call gemm from cublas\n if constexpr (std::is_same<float, T>()) {\n cublasSgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows, sh.B_cols,\n sh.A_cols, _pa, dA, sh.A_rows, dB, sh.B_rows, _pb, dC,\n sh.C_rows);\n } else if (std::is_same<double, T>()) {\n cublasDgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows, sh.B_cols,\n sh.A_cols, _pa, dA, sh.A_rows, dB, sh.B_rows, _pb, dC,\n sh.C_rows);\n }\n}\n\n\/*\n * Call the gemm?Batched function from cublas, resembling a zip\n * operation of two 3D tensors, applying the gemm function in each pair\n * of matrices. Resulting in a 3D tensor containing the results of the\n * multiplication.\n *\/\ntemplate <typename T>\nvoid EigenCuda<T>::gemmBatched(Shapes sh, const T **dA, const T **dB, T **dC,\n int batchCount) {\n\n \/\/ Scalar constanst for calling blas\n T _alpha = 1.;\n T _beta = 0.;\n const T *_pa = &_alpha;\n const T *_pb = &_beta;\n\n \/\/ call gemm from cublas\n cublasStatus_t status;\n if constexpr (std::is_same<float, T>()) {\n status = cublasSgemmBatched(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows,\n sh.B_cols, sh.A_cols, _pa, dA, sh.A_rows, dB,\n sh.B_rows, _pb, dC, sh.C_rows, batchCount);\n } else if (std::is_same<double, T>()) {\n status = cublasDgemmBatched(_handle, CUBLAS_OP_N, CUBLAS_OP_N, sh.A_rows,\n sh.B_cols, sh.A_cols, _pa, dA, sh.A_rows, dB,\n sh.B_rows, _pb, dC, sh.C_rows, batchCount);\n }\n if (status != 0) {\n std::runtime_error(\"error calling cublas?DgemmBatched\");\n }\n}\n\n\/*\n * \\brief Matrix-Matrix multiplication in GPU\n *\/\ntemplate <typename T>\nMat<T> EigenCuda<T>::dot(const Mat<T> &A, const Mat<T> &B) {\n \/\/ Matrix to store the result\n Mat<T> C = Mat<T>::Zero(A.rows(), B.cols());\n std::size_t size_C = C.size() * sizeof(T);\n\n \/\/ Indices of the matrices on the device\n T *dA = initialize_matrix_mem(A);\n T *dB = initialize_matrix_mem(B);\n T *dC = initialize_matrix_mem(C, false);\n\n \/\/ process on GPU\n Shapes sh{A.rows(), A.cols(), B.rows(), B.cols(), C.rows()};\n gemm(sh, dA, dB, dC);\n\n \/\/ send data back to CPU\n T *hC = C.data();\n cudaMemcpy(hC, dC, size_C, cudaMemcpyDeviceToHost);\n\n \/\/ create an eigen matrix\n C = Eigen::Map<Mat<T>>(hC, A.rows(), B.cols());\n\n \/\/ Free the result from the device\n gpu_free(dA);\n gpu_free(dB);\n gpu_free(dC);\n\n return C;\n}\ntemplate <typename T>\nstd::vector<Mat<T>> EigenCuda<T>::right_matrix_tensor(\n const Mat<T> &B, const std::vector<Mat<T>> &tensor) {\n \/\/ Number of submatrices in the input tensor\n int batchCount = tensor.size();\n\n \/\/ Copy Matrix B to the device\n T *mtxB = initialize_matrix_mem(B);\n\n \/\/ allocate space in device for the temporal matrix\n int rows = tensor[0].rows(); \/\/ rows of the submatrices\n int cols = tensor[0].cols(); \/\/ cols of the submatrices\n Mat<T> matrix = Mat<T>::Zero(rows, cols);\n\n \/\/ Allocate space and copy to the device the input tensor\n \/\/ Notice that hA, hB and hC are arrays IN THE HOST by the pointers\n \/\/ are allocated in the DEVICE.\n T *hA[batchCount];\n for (auto i = 0; i < batchCount; i++) {\n hA[i] = initialize_matrix_mem(tensor[i]);\n }\n\n \/\/ represent the matrix B as a tensor where all the submatrices are the same\n T *hB[batchCount];\n for (auto i = 0; i < batchCount; i++) {\n hB[i] = mtxB;\n }\n\n \/\/ Allocate space in the device for the output tensor\n T *hC[batchCount];\n Mat<T> output = Mat<T>::Zero(matrix.rows(), B.cols());\n for (auto i = 0; i < batchCount; i++) {\n hC[i] = initialize_matrix_mem(output, false);\n }\n\n \/\/ Allocate space in the device for the array of pointers\n const T **dA, **dB;\n T **dC;\n size_t size_batch = batchCount * sizeof(T *);\n cudaMalloc(&dA, size_batch);\n cudaMalloc(&dB, size_batch);\n cudaMalloc(&dC, size_batch);\n\n \/\/ Copy the arrays of pointers from host to the device\n cudaMemcpyAsync(dA, hA, size_batch, cudaMemcpyHostToDevice, _stream);\n cudaMemcpyAsync(dB, hB, size_batch, cudaMemcpyHostToDevice, _stream);\n cudaMemcpyAsync(dC, hC, size_batch, cudaMemcpyHostToDevice, _stream);\n\n \/\/ Call tensor matrix multiplication\n Shapes sh{matrix.rows(), matrix.cols(), B.rows(), B.cols(), matrix.rows()};\n gemmBatched(sh, dA, dB, dC, batchCount);\n\n \/\/ Vector containing the results\n std::vector<Mat<T>> rs(batchCount,\n Mat<T>::Zero(output.rows(), output.cols()));\n std::size_t size_out = output.size() * sizeof(T);\n\n \/\/ Copy Array of pointers on the device to the host\n cudaMemcpyAsync(hC, dC, size_batch, cudaMemcpyDeviceToHost, _stream);\n\n \/\/ Copy each array back to the device\n for (auto i = 0; i < batchCount; i++) {\n T *hout = rs[i].data();\n T *dout = hC[i];\n cudaMemcpyAsync(hout, dout, size_out, cudaMemcpyDeviceToHost, _stream);\n rs[i] = Eigen::Map<Mat<T>>(hout, output.rows(), output.cols());\n ;\n }\n \/\/ Deallocate all the memory from the device\n gpu_free(mtxB);\n cudaFree(dA);\n cudaFree(dB);\n cudaFree(dC);\n for (auto i = 0; i < batchCount; i++) {\n gpu_free(hA[i]);\n gpu_free(hC[i]);\n }\n\n return rs;\n}\n\n\/\/ explicit instantiations\ntemplate class EigenCuda<float>;\ntemplate class EigenCuda<double>;\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2020 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ Local VOTCA includes\n#include \"votca\/xtp\/rpa.h\"\n#include \"votca\/xtp\/aomatrix.h\"\n#include \"votca\/xtp\/threecenter.h\"\n#include \"votca\/xtp\/vc2index.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies,\n const Eigen::VectorXd& gwaenergies,\n Index qpmin) {\n Index rpatotal = _rpamax - _rpamin + 1;\n _energies = dftenergies.segment(_rpamin, rpatotal);\n Index gwsize = Index(gwaenergies.size());\n Index lumo = _homo + 1;\n\n Index qpmax = qpmin + gwsize - 1;\n _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies;\n\n Eigen::VectorXd corrections_occ =\n _energies.segment(qpmin - _rpamin, lumo - qpmin) -\n dftenergies.segment(qpmin - _rpamin, lumo - qpmin);\n Eigen::VectorXd corrections_virt =\n _energies.segment(lumo - qpmin, gwsize - (lumo - qpmin)) -\n dftenergies.segment(lumo - qpmin, gwsize - (lumo - qpmin));\n double max_correction_occ = (corrections_occ.cwiseAbs()).maxCoeff();\n double max_correction_virt = (corrections_virt.cwiseAbs()).maxCoeff();\n\n Index levelaboveqpmax = _rpamax - qpmax;\n Index levelbelowqpmin = qpmin - _rpamin;\n\n _energies.segment(0, levelbelowqpmin).array() -= max_correction_occ;\n _energies.segment(qpmax + 1 - _rpamin, levelaboveqpmax).array() +=\n max_correction_virt;\n}\n\ntemplate <bool imag>\nEigen::MatrixXd RPA::calculate_epsilon(double frequency) const {\n const Index size = _Mmn.auxsize();\n\n Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size);\n\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const double freq2 = frequency * frequency;\n const double eta2 = _eta * _eta;\n\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n\n const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc);\n\n const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m;\n Eigen::VectorXd denom;\n if (imag) {\n denom = 4 * deltaE \/ (deltaE.square() + freq2);\n } else {\n Eigen::ArrayXd deltEf = deltaE - frequency;\n Eigen::ArrayXd sum = deltEf \/ (deltEf.square() + eta2);\n deltEf = deltaE + frequency;\n sum += deltEf \/ (deltEf.square() + eta2);\n denom = 2 * sum;\n }\n result += Mmn_RPA.transpose() * denom.asDiagonal() * Mmn_RPA;\n }\n\n return result;\n}\n\ntemplate Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const;\ntemplate Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const;\n\nEigen::MatrixXd RPA::calculate_epsilon_r(std::complex<double> frequency) const {\n\n const Index size = _Mmn.auxsize();\n \/\/std::vector<Eigen::MatrixXd> thread_result = std::vector<Eigen::MatrixXd>(\n \/\/ OPENMP::getMaxThreads(), Eigen::MatrixXd::Zero(size, size));\nEigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size);\n\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n\n\/\/#pragma omp parallel for schedule(guided)\n#pragma omp parallel for schedule(dynamic) reduction(+ : result)\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n const Eigen::MatrixXd Mmn_RPA =\n _Mmn[m_level].block(n_occ, 0, n_unocc, size);\n const Eigen::ArrayXd deltaE =\n _energies.segment(n_occ, n_unocc).array() - qp_energy_m;\n\n Eigen::VectorXd chi;\n Eigen::ArrayXd deltaEm = frequency.real() - deltaE;\n Eigen::ArrayXd deltaEp = frequency.real() + deltaE;\n\n double sigma_1 = std::pow(frequency.imag() + _eta, 2);\n double sigma_2 = std::pow(frequency.imag() - _eta, 2);\n\n chi = deltaEm * (deltaEm.cwiseAbs2() + sigma_1).cwiseInverse() -\n deltaEp * (deltaEp.cwiseAbs2() + sigma_2).cwiseInverse();\n \/\/Eigen::MatrixXd tempresult =\n \/\/ Mmn_RPA.transpose() * chi.asDiagonal() * Mmn_RPA;\n result += Mmn_RPA.transpose() * chi.asDiagonal() * Mmn_RPA;\n\n\n \/\/thread_result[OPENMP::getThreadId()] += tempresult;\n }\n\n \/\/Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size);\n\n \/\/for (const auto& mat : thread_result) {\n \/\/ result -= 2 * mat;\n \/\/}\n return -2*result;\n}\n\nEigen::MatrixXcd RPA::calculate_epsilon_complex(\n std::complex<double> frequency) const {\n const Index size = _Mmn.auxsize();\n std::vector<Eigen::MatrixXcd> thread_result = std::vector<Eigen::MatrixXcd>(\n OPENMP::getMaxThreads(), Eigen::MatrixXcd::Zero(size, size));\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n\n std::complex<double> eta(0.0, _eta);\n\n#pragma omp parallel for schedule(guided)\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n const Eigen::MatrixXd Mmn_RPA =\n _Mmn[m_level].block(n_occ, 0, n_unocc, size);\n const Eigen::ArrayXcd deltaE =\n _energies.segment(n_occ, n_unocc).array() - qp_energy_m;\n\n Eigen::VectorXcd chi;\n Eigen::ArrayXcd deltaEm = frequency - deltaE + eta;\n Eigen::ArrayXcd deltaEp = frequency + deltaE - eta;\n\n chi = deltaEm.cwiseInverse() - deltaEp.cwiseInverse();\n Eigen::MatrixXcd tempresult =\n Mmn_RPA.transpose() * chi.asDiagonal() * Mmn_RPA;\n\n thread_result[OPENMP::getThreadId()] += tempresult;\n }\n\n Eigen::MatrixXcd result = Eigen::MatrixXcd::Identity(size, size);\n\n for (const auto& mat : thread_result) {\n result -= 2. * mat;\n }\n return result;\n}\n\nRPA::rpa_eigensolution RPA::Diagonalize_H2p() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n\n Eigen::VectorXd AmB = Calculate_H2p_AmB();\n Eigen::MatrixXd ApB = Calculate_H2p_ApB();\n\n RPA::rpa_eigensolution sol;\n sol.ERPA_correlation = -0.25 * (ApB.trace() + AmB.sum());\n\n \/\/ C = AmB^1\/2 * ApB * AmB^1\/2\n Eigen::MatrixXd& C = ApB;\n C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal());\n C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal());\n\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C);\n\n \/\/ Do not remove this line! It has to be there for MKL to not crash\n sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size());\n sol.omega = es.eigenvalues().cwiseSqrt();\n sol.ERPA_correlation += 0.5 * sol.omega.sum();\n\n XTP_LOG(Log::info, _log) << TimeStamp()\n << \" Lowest neutral excitation energy (eV): \"\n << tools::conv::hrt2ev * sol.omega.minCoeff()\n << std::flush;\n\n \/\/ RPA correlation energy calculated from Eq.9 of J. Chem. Phys. 132, 234114\n \/\/ (2010)\n XTP_LOG(Log::error, _log)\n << TimeStamp()\n << \" RPA correlation energy (Hartree): \" << sol.ERPA_correlation\n << std::flush;\n\n sol.XpY = Eigen::MatrixXd(rpasize, rpasize);\n\n Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt();\n Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse();\n for (int s = 0; s < rpasize; s++) {\n sol.XpY.col(s) =\n Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s));\n }\n\n return sol;\n}\n\nEigen::VectorXd RPA::Calculate_H2p_AmB() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n vc2index vc = vc2index(0, 0, n_unocc);\n Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize);\n for (Index v = 0; v < n_occ; v++) {\n Index i = vc.I(v, 0);\n AmB.segment(i, n_unocc) =\n _energies.segment(n_occ, n_unocc).array() - _energies(v);\n }\n return AmB;\n}\n\nEigen::MatrixXd RPA::Calculate_H2p_ApB() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n const Index auxsize = _Mmn.auxsize();\n vc2index vc = vc2index(0, 0, n_unocc);\n Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize);\n#pragma omp parallel for schedule(guided)\n for (Index v2 = 0; v2 < n_occ; v2++) {\n Index i2 = vc.I(v2, 0);\n const Eigen::MatrixXd Mmn_v2T =\n _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose();\n for (Index v1 = v2; v1 < n_occ; v1++) {\n Index i1 = vc.I(v1, 0);\n \/\/ Multiply with factor 2 to sum over both (identical) spin states\n ApB.block(i1, i2, n_unocc, n_unocc) =\n 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T;\n }\n }\n ApB.diagonal() += Calculate_H2p_AmB();\n return ApB;\n}\n\nEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C(\n const Eigen::MatrixXd& C) const {\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Diagonalizing two-particle Hamiltonian \"\n << std::flush;\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); \/\/ Uses lower triangle\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Diagonalization done \" << std::flush;\n double minCoeff = es.eigenvalues().minCoeff();\n if (minCoeff <= 0.0) {\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Detected non-positive eigenvalue: \" << minCoeff\n << std::flush;\n throw std::runtime_error(\"Detected non-positive eigenvalue.\");\n }\n return es;\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<commit_msg>eigen reductions and cleanup<commit_after>\/*\n * Copyright 2009-2020 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ Local VOTCA includes\n#include \"votca\/xtp\/rpa.h\"\n#include \"votca\/xtp\/aomatrix.h\"\n#include \"votca\/xtp\/threecenter.h\"\n#include \"votca\/xtp\/vc2index.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies,\n const Eigen::VectorXd& gwaenergies,\n Index qpmin) {\n Index rpatotal = _rpamax - _rpamin + 1;\n _energies = dftenergies.segment(_rpamin, rpatotal);\n Index gwsize = Index(gwaenergies.size());\n Index lumo = _homo + 1;\n\n Index qpmax = qpmin + gwsize - 1;\n _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies;\n\n Eigen::VectorXd corrections_occ =\n _energies.segment(qpmin - _rpamin, lumo - qpmin) -\n dftenergies.segment(qpmin - _rpamin, lumo - qpmin);\n Eigen::VectorXd corrections_virt =\n _energies.segment(lumo - qpmin, gwsize - (lumo - qpmin)) -\n dftenergies.segment(lumo - qpmin, gwsize - (lumo - qpmin));\n double max_correction_occ = (corrections_occ.cwiseAbs()).maxCoeff();\n double max_correction_virt = (corrections_virt.cwiseAbs()).maxCoeff();\n\n Index levelaboveqpmax = _rpamax - qpmax;\n Index levelbelowqpmin = qpmin - _rpamin;\n\n _energies.segment(0, levelbelowqpmin).array() -= max_correction_occ;\n _energies.segment(qpmax + 1 - _rpamin, levelaboveqpmax).array() +=\n max_correction_virt;\n}\n\ntemplate <bool imag>\nEigen::MatrixXd RPA::calculate_epsilon(double frequency) const {\n const Index size = _Mmn.auxsize();\n\n Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size);\n\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const double freq2 = frequency * frequency;\n const double eta2 = _eta * _eta;\n\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n\n const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc);\n\n const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m;\n Eigen::VectorXd denom;\n if (imag) {\n denom = 4 * deltaE \/ (deltaE.square() + freq2);\n } else {\n Eigen::ArrayXd deltEf = deltaE - frequency;\n Eigen::ArrayXd sum = deltEf \/ (deltEf.square() + eta2);\n deltEf = deltaE + frequency;\n sum += deltEf \/ (deltEf.square() + eta2);\n denom = 2 * sum;\n }\n result += Mmn_RPA.transpose() * denom.asDiagonal() * Mmn_RPA;\n }\n\n return result;\n}\n\ntemplate Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const;\ntemplate Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const;\n\nEigen::MatrixXd RPA::calculate_epsilon_r(std::complex<double> frequency) const {\n\n const Index size = _Mmn.auxsize();\n Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size);\n\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n\n#pragma omp parallel for schedule(dynamic) reduction(+ : result)\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc);\n const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m;\n\n Eigen::VectorXd chi;\n Eigen::ArrayXd deltaEm = frequency.real() - deltaE;\n Eigen::ArrayXd deltaEp = frequency.real() + deltaE;\n\n double sigma_1 = std::pow(frequency.imag() + _eta, 2);\n double sigma_2 = std::pow(frequency.imag() - _eta, 2);\n\n chi = deltaEm * (deltaEm.cwiseAbs2() + sigma_1).cwiseInverse() -\n deltaEp * (deltaEp.cwiseAbs2() + sigma_2).cwiseInverse();\n result += -2 * Mmn_RPA.transpose() * chi.asDiagonal() * Mmn_RPA;\n }\n\n return result;\n}\n\nEigen::MatrixXcd RPA::calculate_epsilon_complex(\n std::complex<double> frequency) const {\n const Index size = _Mmn.auxsize();\n std::vector<Eigen::MatrixXcd> thread_result = std::vector<Eigen::MatrixXcd>(\n OPENMP::getMaxThreads(), Eigen::MatrixXcd::Zero(size, size));\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n\n std::complex<double> eta(0.0, _eta);\n\n#pragma omp parallel for schedule(guided)\n for (Index m_level = 0; m_level < n_occ; m_level++) {\n const double qp_energy_m = _energies(m_level);\n const Eigen::MatrixXd Mmn_RPA =\n _Mmn[m_level].block(n_occ, 0, n_unocc, size);\n const Eigen::ArrayXcd deltaE =\n _energies.segment(n_occ, n_unocc).array() - qp_energy_m;\n\n Eigen::VectorXcd chi;\n Eigen::ArrayXcd deltaEm = frequency - deltaE + eta;\n Eigen::ArrayXcd deltaEp = frequency + deltaE - eta;\n\n chi = deltaEm.cwiseInverse() - deltaEp.cwiseInverse();\n Eigen::MatrixXcd tempresult =\n Mmn_RPA.transpose() * chi.asDiagonal() * Mmn_RPA;\n\n thread_result[OPENMP::getThreadId()] += tempresult;\n }\n\n Eigen::MatrixXcd result = Eigen::MatrixXcd::Identity(size, size);\n\n for (const auto& mat : thread_result) {\n result -= 2. * mat;\n }\n return result;\n}\n\nRPA::rpa_eigensolution RPA::Diagonalize_H2p() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n\n Eigen::VectorXd AmB = Calculate_H2p_AmB();\n Eigen::MatrixXd ApB = Calculate_H2p_ApB();\n\n RPA::rpa_eigensolution sol;\n sol.ERPA_correlation = -0.25 * (ApB.trace() + AmB.sum());\n\n \/\/ C = AmB^1\/2 * ApB * AmB^1\/2\n Eigen::MatrixXd& C = ApB;\n C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal());\n C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal());\n\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C);\n\n \/\/ Do not remove this line! It has to be there for MKL to not crash\n sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size());\n sol.omega = es.eigenvalues().cwiseSqrt();\n sol.ERPA_correlation += 0.5 * sol.omega.sum();\n\n XTP_LOG(Log::info, _log) << TimeStamp()\n << \" Lowest neutral excitation energy (eV): \"\n << tools::conv::hrt2ev * sol.omega.minCoeff()\n << std::flush;\n\n \/\/ RPA correlation energy calculated from Eq.9 of J. Chem. Phys. 132, 234114\n \/\/ (2010)\n XTP_LOG(Log::error, _log)\n << TimeStamp()\n << \" RPA correlation energy (Hartree): \" << sol.ERPA_correlation\n << std::flush;\n\n sol.XpY = Eigen::MatrixXd(rpasize, rpasize);\n\n Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt();\n Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse();\n for (int s = 0; s < rpasize; s++) {\n sol.XpY.col(s) =\n Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s));\n }\n\n return sol;\n}\n\nEigen::VectorXd RPA::Calculate_H2p_AmB() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n vc2index vc = vc2index(0, 0, n_unocc);\n Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize);\n for (Index v = 0; v < n_occ; v++) {\n Index i = vc.I(v, 0);\n AmB.segment(i, n_unocc) =\n _energies.segment(n_occ, n_unocc).array() - _energies(v);\n }\n return AmB;\n}\n\nEigen::MatrixXd RPA::Calculate_H2p_ApB() const {\n const Index lumo = _homo + 1;\n const Index n_occ = lumo - _rpamin;\n const Index n_unocc = _rpamax - lumo + 1;\n const Index rpasize = n_occ * n_unocc;\n const Index auxsize = _Mmn.auxsize();\n vc2index vc = vc2index(0, 0, n_unocc);\n Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize);\n#pragma omp parallel for schedule(guided)\n for (Index v2 = 0; v2 < n_occ; v2++) {\n Index i2 = vc.I(v2, 0);\n const Eigen::MatrixXd Mmn_v2T =\n _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose();\n for (Index v1 = v2; v1 < n_occ; v1++) {\n Index i1 = vc.I(v1, 0);\n \/\/ Multiply with factor 2 to sum over both (identical) spin states\n ApB.block(i1, i2, n_unocc, n_unocc) =\n 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T;\n }\n }\n ApB.diagonal() += Calculate_H2p_AmB();\n return ApB;\n}\n\nEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C(\n const Eigen::MatrixXd& C) const {\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Diagonalizing two-particle Hamiltonian \"\n << std::flush;\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); \/\/ Uses lower triangle\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Diagonalization done \" << std::flush;\n double minCoeff = es.eigenvalues().minCoeff();\n if (minCoeff <= 0.0) {\n XTP_LOG(Log::error, _log)\n << TimeStamp() << \" Detected non-positive eigenvalue: \" << minCoeff\n << std::flush;\n throw std::runtime_error(\"Detected non-positive eigenvalue.\");\n }\n return es;\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2018 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/\/\/ For an earlier history see ctp repo commit 77795ea591b29e664153f9404c8655ba28dc14e9\n\n\n#include <votca\/ctp\/polarfrag.h>\n#include <votca\/ctp\/dmaspace.h>\n\nnamespace votca {\nnamespace ctp {\n\n\nPolarFrag::~PolarFrag() { \n clear(); \/* Polar sites cleaned by PolarSeg *\/\n if (_indu_cg_site != NULL) delete _indu_cg_site;\n if (_perm_cg_site != NULL) delete _perm_cg_site;\n}\n \n \nconst votca::tools::vec &PolarFrag::CalcPosCenterOfGeom() { \n _pos = votca::tools::vec(0,0,0); \n for (unsigned int i = 0; i < this->size(); ++i) {\n _pos += (*this)[i]->getPos();\n }\n if (this->size() > 0) _pos \/= double(this->size());\n return _pos;\n}\n \n \nconst votca::tools::vec &PolarFrag::CalcPosPolarWeights() {\n \/\/ Establish total weights\n double sum_iso_p = 0.0;\n double sum_abs_q = 0.0;\n for (unsigned int i = 0; i < this->size(); ++i) {\n sum_iso_p += (*this)[i]->getIsoP();\n sum_abs_q += std::abs((*this)[i]->getQ00());\n }\n\n _pos = votca::tools::vec(0,0,0);\n \/\/ Any polar sites in here? If not, return (0,0,0)\n if (this->size() < 1) ;\n \/\/ Noteworthy charge and polarizability? If not, return CoG\n else if (sum_abs_q <= 1e-2 && sum_iso_p <= 1e-2) {\n _pos = this->CalcPosCenterOfGeom();\n }\n \/\/ Else: return weighted 0.5*(center-of-polarity + center-of-charge)\n else {\n for (unsigned int i = 0; i < this->size(); ++i) {\n double weight = 0.0;\n if (sum_abs_q < 1e-2) {\n assert(sum_iso_p >= 1e-2 && \"<CalcPosPolarWeights> P-ERROR\");\n weight = (*this)[i]->getIsoP()\/sum_iso_p;\n }\n else if (sum_iso_p < 1e-2) {\n assert(sum_abs_q >= 1e-2 && \"<CalcPosPolarWeights> Q-ERROR\");\n weight = std::abs((*this)[i]->getQ00())\/sum_abs_q;\n }\n else {\n weight = 0.5 * (\n (*this)[i]->getIsoP()\/sum_iso_p\n + std::abs((*this)[i]->getQ00())\/sum_abs_q);\n }\n _pos += (*this)[i]->getPos() * weight;\n }\n }\n return _pos;\n}\n \n \nvoid PolarFrag::GeneratePermInduCgSite(bool do_cg_polarizabilities) {\n \/\/ ATTENTION The same method appears in <PolarSeg>\n assert(!do_cg_polarizabilities && \"NOT IMPLEMENTED, NOT NEEDED?\");\n \/\/ Collapse multipole moments : position, rank L\n vec target_pos = _pos;\n int state = 0;\n int L = 2;\n vector<double> QCG(L*L+2*L+1, 0.0); \/\/ permanent\n vector<double> uQCG(L*L+2*L+1, 0.0); \/\/ induced\n\n for (PolarFrag::iterator pit = begin();\n pit < end(); ++pit) {\n \/\/ PERMANENT MOMENTS\n \/\/ Convert real to complex moments \n vector<double> Qlm = (*pit)->getQs(0);\n DMA::ComplexSphericalMoments Xlm(Qlm);\n \/\/ Shift moments\n DMA::MomentShift mshift;\n vec shift = target_pos - (*pit)->getPos();\n DMA::RegularSphericalHarmonics Clm(-shift);\n vector<DMA::cmplx> Xlm_shifted = mshift.Shift(Xlm, Clm); \n \/\/ Convert complex to real moments & add to base\n DMA::RealSphericalMoments Qlm_shifted(Xlm_shifted);\n Qlm_shifted.AddToVector(QCG);\n\n \/\/ INDUCED MOMENTS\n \/\/ Convert real to complex moments\n vec u1 = (*pit)->getU1();\n vector<double> uQlm(L*L+2*L+1, 0.0);\n uQlm[1] = u1.getZ(); \/\/ NOTE order is z-x-y == 10-11c-11s\n uQlm[2] = u1.getX();\n uQlm[3] = u1.getY();\n DMA::ComplexSphericalMoments uXlm(uQlm);\n \/\/ Shift moments\n DMA::RegularSphericalHarmonics uClm(-shift);\n vector<DMA::cmplx> uXlm_shifted = mshift.Shift(uXlm, uClm);\n \/\/ Convert complex to real moments & add to base\n DMA::RealSphericalMoments uQlm_shifted(uXlm_shifted);\n uQlm_shifted.AddToVector(uQCG);\n }\n \n \/\/ Collapse polarizabilities\n votca::tools::matrix PCG;\n PCG.ZeroMatrix();\n \n \/\/ Zero induced dipole\n vec u1_cg_red = vec(0,0,0);\n \n \/\/ Generate new coarse-grained site from the above\n APolarSite *indu_cg_site = new APolarSite(this->getId(), \"FGU\");\n APolarSite *perm_cg_site = new APolarSite(this->getId(), \"FGP\");\n \n indu_cg_site->setResolution(APolarSite::coarsegrained);\n indu_cg_site->setPos(target_pos);\n indu_cg_site->setRank(L);\n \n perm_cg_site->setResolution(APolarSite::coarsegrained);\n perm_cg_site->setPos(target_pos);\n perm_cg_site->setRank(L);\n \n \/\/ ATTENTION Save INDUCED moments as PERMANENT moments (<indu_cg_site>)\n \/\/ ATTENTION Save PERMANENT moments as PERMANENT moments (<perm_cg_site>)\n indu_cg_site->setQs(uQCG, state);\n indu_cg_site->setPs(PCG, state);\n indu_cg_site->setU1(u1_cg_red);\n indu_cg_site->Charge(state);\n \n perm_cg_site->setQs(QCG, state);\n perm_cg_site->setPs(PCG, state);\n perm_cg_site->setU1(u1_cg_red);\n perm_cg_site->Charge(state);\n \n \/\/ Deallocate previously allocated sites\n if (_indu_cg_site != NULL) delete _indu_cg_site;\n if (_perm_cg_site != NULL) delete _perm_cg_site;\n _indu_cg_site = indu_cg_site;\n _perm_cg_site = perm_cg_site;\n return;\n}\n \n \n \n \n \n \n \n \n}}\n<commit_msg>polarfrag.cc<commit_after>\/*\n * Copyright 2009-2018 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/\/\/ For an earlier history see ctp repo commit 77795ea591b29e664153f9404c8655ba28dc14e9\n\n#include <votca\/xtp\/polarfrag.h>\n#include <votca\/xtp\/dmaspace.h>\n\nnamespace votca {\nnamespace xtp {\n\n\nPolarFrag::~PolarFrag() { \n clear(); \/* Polar sites cleaned by PolarSeg *\/\n if (_indu_cg_site != NULL) delete _indu_cg_site;\n if (_perm_cg_site != NULL) delete _perm_cg_site;\n}\n \n \nconst votca::tools::vec &PolarFrag::CalcPosCenterOfGeom() { \n _pos = votca::tools::vec(0,0,0); \n for (unsigned int i = 0; i < this->size(); ++i) {\n _pos += (*this)[i]->getPos();\n }\n if (this->size() > 0) _pos \/= double(this->size());\n return _pos;\n}\n \n \nconst votca::tools::vec &PolarFrag::CalcPosPolarWeights() {\n \/\/ Establish total weights\n double sum_iso_p = 0.0;\n double sum_abs_q = 0.0;\n for (unsigned int i = 0; i < this->size(); ++i) {\n sum_iso_p += (*this)[i]->getIsoP();\n sum_abs_q += std::abs((*this)[i]->getQ00());\n }\n\n _pos = votca::tools::vec(0,0,0);\n \/\/ Any polar sites in here? If not, return (0,0,0)\n if (this->size() < 1) ;\n \/\/ Noteworthy charge and polarizability? If not, return CoG\n else if (sum_abs_q <= 1e-2 && sum_iso_p <= 1e-2) {\n _pos = this->CalcPosCenterOfGeom();\n }\n \/\/ Else: return weighted 0.5*(center-of-polarity + center-of-charge)\n else {\n for (unsigned int i = 0; i < this->size(); ++i) {\n double weight = 0.0;\n if (sum_abs_q < 1e-2) {\n assert(sum_iso_p >= 1e-2 && \"<CalcPosPolarWeights> P-ERROR\");\n weight = (*this)[i]->getIsoP()\/sum_iso_p;\n }\n else if (sum_iso_p < 1e-2) {\n assert(sum_abs_q >= 1e-2 && \"<CalcPosPolarWeights> Q-ERROR\");\n weight = std::abs((*this)[i]->getQ00())\/sum_abs_q;\n }\n else {\n weight = 0.5 * (\n (*this)[i]->getIsoP()\/sum_iso_p\n + std::abs((*this)[i]->getQ00())\/sum_abs_q);\n }\n _pos += (*this)[i]->getPos() * weight;\n }\n }\n return _pos;\n}\n \n \nvoid PolarFrag::GeneratePermInduCgSite(bool do_cg_polarizabilities) {\n \/\/ ATTENTION The same method appears in <PolarSeg>\n assert(!do_cg_polarizabilities && \"NOT IMPLEMENTED, NOT NEEDED?\");\n \/\/ Collapse multipole moments : position, rank L\n vec target_pos = _pos;\n int state = 0;\n int L = 2;\n vector<double> QCG(L*L+2*L+1, 0.0); \/\/ permanent\n vector<double> uQCG(L*L+2*L+1, 0.0); \/\/ induced\n\n for (PolarFrag::iterator pit = begin();\n pit < end(); ++pit) {\n \/\/ PERMANENT MOMENTS\n \/\/ Convert real to complex moments \n vector<double> Qlm = (*pit)->getQs(0);\n DMA::ComplexSphericalMoments Xlm(Qlm);\n \/\/ Shift moments\n DMA::MomentShift mshift;\n vec shift = target_pos - (*pit)->getPos();\n DMA::RegularSphericalHarmonics Clm(-shift);\n vector<DMA::cmplx> Xlm_shifted = mshift.Shift(Xlm, Clm); \n \/\/ Convert complex to real moments & add to base\n DMA::RealSphericalMoments Qlm_shifted(Xlm_shifted);\n Qlm_shifted.AddToVector(QCG);\n\n \/\/ INDUCED MOMENTS\n \/\/ Convert real to complex moments\n vec u1 = (*pit)->getU1();\n vector<double> uQlm(L*L+2*L+1, 0.0);\n uQlm[1] = u1.getZ(); \/\/ NOTE order is z-x-y == 10-11c-11s\n uQlm[2] = u1.getX();\n uQlm[3] = u1.getY();\n DMA::ComplexSphericalMoments uXlm(uQlm);\n \/\/ Shift moments\n DMA::RegularSphericalHarmonics uClm(-shift);\n vector<DMA::cmplx> uXlm_shifted = mshift.Shift(uXlm, uClm);\n \/\/ Convert complex to real moments & add to base\n DMA::RealSphericalMoments uQlm_shifted(uXlm_shifted);\n uQlm_shifted.AddToVector(uQCG);\n }\n \n \/\/ Collapse polarizabilities\n votca::tools::matrix PCG;\n PCG.ZeroMatrix();\n \n \/\/ Zero induced dipole\n vec u1_cg_red = vec(0,0,0);\n \n \/\/ Generate new coarse-grained site from the above\n APolarSite *indu_cg_site = new APolarSite(this->getId(), \"FGU\");\n APolarSite *perm_cg_site = new APolarSite(this->getId(), \"FGP\");\n \n indu_cg_site->setResolution(APolarSite::coarsegrained);\n indu_cg_site->setPos(target_pos);\n indu_cg_site->setRank(L);\n \n perm_cg_site->setResolution(APolarSite::coarsegrained);\n perm_cg_site->setPos(target_pos);\n perm_cg_site->setRank(L);\n \n \/\/ ATTENTION Save INDUCED moments as PERMANENT moments (<indu_cg_site>)\n \/\/ ATTENTION Save PERMANENT moments as PERMANENT moments (<perm_cg_site>)\n indu_cg_site->setQs(uQCG, state);\n indu_cg_site->setPs(PCG, state);\n indu_cg_site->setU1(u1_cg_red);\n indu_cg_site->Charge(state);\n \n perm_cg_site->setQs(QCG, state);\n perm_cg_site->setPs(PCG, state);\n perm_cg_site->setU1(u1_cg_red);\n perm_cg_site->Charge(state);\n \n \/\/ Deallocate previously allocated sites\n if (_indu_cg_site != NULL) delete _indu_cg_site;\n if (_perm_cg_site != NULL) delete _perm_cg_site;\n _indu_cg_site = indu_cg_site;\n _perm_cg_site = perm_cg_site;\n return;\n}\n \n \n \n \n \n \n \n \n}}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/transport\/http\/http_auth.h>\n#include \"eventql\/util\/http\/cookies.h\"\n\nnamespace eventql {\n\nconst char HTTPAuth::kSessionCookieKey[] = \"__dxa_session\";\nconst uint64_t HTTPAuth::kSessionLifetimeMicros = 365 * kMicrosPerDay;\n\nOption<AnalyticsSession> HTTPAuth::authenticateRequest(\n const http::HTTPRequest& request,\n AnalyticsAuth* auth) {\n try {\n String cookie;\n\n if (request.hasHeader(\"Authorization\")) {\n static const String hdrprefix = \"Token \";\n auto hdrval = request.getHeader(\"Authorization\");\n if (StringUtil::beginsWith(hdrval, hdrprefix)) {\n cookie = URI::urlDecode(hdrval.substr(hdrprefix.size()));\n }\n }\n\n if (cookie.empty()) {\n const auto& cookies = request.cookies();\n http::Cookies::getCookie(cookies, kSessionCookieKey, &cookie);\n }\n\n if (cookie.empty()) {\n return None<AnalyticsSession>();\n }\n\n return auth->decodeAuthToken(cookie);\n } catch (const StandardException& e) {\n logDebug(\"analyticsd\", e, \"authentication failed because of error\");\n return None<AnalyticsSession>();\n }\n}\n\nStatus HTTPAuth::authenticateRequest(\n Session* session,\n ClientAuth* client_auth,\n const http::HTTPRequest& request) {\n HashMap<String, String> auth_data;\n\n if (request.hasHeader(\"Authorization\")) {\n static const String hdrprefix = \"Token \";\n auto hdrval = request.getHeader(\"Authorization\");\n if (StringUtil::beginsWith(hdrval, hdrprefix)) {\n auth_data.emplace(\n \"auth_token\",\n URI::urlDecode(hdrval.substr(hdrprefix.size())));\n }\n }\n\n return client_auth->authenticateSession(session, auth_data);\n}\n\n}\n<commit_msg>http basic auth<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/transport\/http\/http_auth.h>\n#include \"eventql\/util\/http\/cookies.h\"\n#include \"eventql\/util\/util\/Base64.h\"\n\nnamespace eventql {\n\nconst char HTTPAuth::kSessionCookieKey[] = \"__dxa_session\";\nconst uint64_t HTTPAuth::kSessionLifetimeMicros = 365 * kMicrosPerDay;\n\nOption<AnalyticsSession> HTTPAuth::authenticateRequest(\n const http::HTTPRequest& request,\n AnalyticsAuth* auth) {\n try {\n String cookie;\n\n if (request.hasHeader(\"Authorization\")) {\n static const String hdrprefix = \"Token \";\n auto hdrval = request.getHeader(\"Authorization\");\n if (StringUtil::beginsWith(hdrval, hdrprefix)) {\n cookie = URI::urlDecode(hdrval.substr(hdrprefix.size()));\n }\n }\n\n if (cookie.empty()) {\n const auto& cookies = request.cookies();\n http::Cookies::getCookie(cookies, kSessionCookieKey, &cookie);\n }\n\n if (cookie.empty()) {\n return None<AnalyticsSession>();\n }\n\n return auth->decodeAuthToken(cookie);\n } catch (const StandardException& e) {\n logDebug(\"analyticsd\", e, \"authentication failed because of error\");\n return None<AnalyticsSession>();\n }\n}\n\nStatus HTTPAuth::authenticateRequest(\n Session* session,\n ClientAuth* client_auth,\n const http::HTTPRequest& request) {\n HashMap<String, String> auth_data;\n\n if (request.hasHeader(\"Authorization\")) {\n auto hdrval = request.getHeader(\"Authorization\");\n\n {\n static const String hdrprefix = \"Token \";\n if (StringUtil::beginsWith(hdrval, hdrprefix)) {\n auth_data.emplace(\n \"auth_token\",\n URI::urlDecode(hdrval.substr(hdrprefix.size())));\n }\n }\n\n {\n static const String hdrprefix = \"Basic \";\n if (StringUtil::beginsWith(hdrval, hdrprefix)) {\n String basic_auth;\n util::Base64::decode(hdrval.substr(hdrprefix.size()), &basic_auth);\n auto sep_pos = basic_auth.find(\":\");\n if (sep_pos == String::npos) {\n auth_data.emplace(\"user\", basic_auth);\n } else {\n auth_data.emplace(\"user\", basic_auth.substr(0, sep_pos));\n auth_data.emplace(\"password\", basic_auth.substr(sep_pos + 1));\n }\n }\n }\n }\n\n return client_auth->authenticateSession(session, auth_data);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file FactorTable.cpp\n\/\/\/ @see FactorTable.hpp for documentation.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <FactorTable.hpp>\n#include <pmath.hpp>\n\n#include <limits>\n#include <stdexcept>\n#include <stdint.h>\n#include <vector>\n\nusing namespace std;\n\nnamespace primecount {\n\nconst uint8_t FactorTable::numbers_[48] =\n{\n 1, 11, 13, 17, 19, 23,\n 29, 31, 37, 41, 43, 47,\n 53, 59, 61, 67, 71, 73,\n 79, 83, 89, 97, 101, 103,\n 107, 109, 113, 121, 127, 131,\n 137, 139, 143, 149, 151, 157,\n 163, 167, 169, 173, 179, 181,\n 187, 191, 193, 197, 199, 209\n};\n\nconst int8_t FactorTable::indexes_[210] =\n{\n -1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 1, 2, 2, 2,\n 2, 3, 3, 4, 4, 4, 4, 5,\n 5, 5, 5, 5, 5, 6, 6, 7,\n 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 9, 9, 10, 10, 10, 10, 11,\n 11, 11, 11, 11, 11, 12, 12, 12,\n 12, 12, 12, 13, 13, 14, 14, 14,\n 14, 14, 14, 15, 15, 15, 15, 16,\n 16, 17, 17, 17, 17, 17, 17, 18,\n 18, 18, 18, 19, 19, 19, 19, 19,\n 19, 20, 20, 20, 20, 20, 20, 20,\n 20, 21, 21, 21, 21, 22, 22, 23,\n 23, 23, 23, 24, 24, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 26,\n 26, 27, 27, 27, 27, 27, 27, 28,\n 28, 28, 28, 29, 29, 29, 29, 29,\n 29, 30, 30, 31, 31, 31, 31, 32,\n 32, 32, 32, 32, 32, 33, 33, 34,\n 34, 34, 34, 34, 34, 35, 35, 35,\n 35, 35, 35, 36, 36, 36, 36, 37,\n 37, 38, 38, 38, 38, 39, 39, 39,\n 39, 39, 39, 40, 40, 41, 41, 41,\n 41, 41, 41, 42, 42, 42, 42, 43,\n 43, 44, 44, 44, 44, 45, 45, 46,\n 46, 46, 46, 46, 46, 46, 46, 46,\n 46, 47\n};\n\nFactorTable::FactorTable(int64_t max) :\n max_(max)\n{\n if (isqrt(max) >= numeric_limits<uint16_t>::max())\n throw runtime_error(\"FactorTable: sqrt(max) must be < max(uint16_t).\");\n init();\n}\n\nvoid FactorTable::init()\n{\n int64_t max_index = get_index(max_);\n factor_table_.resize(max_index + 1, 0xffff);\n\n for (size_t i = 1; i < factor_table_.size(); i++)\n {\n if (factor_table_[i] == 0xffff)\n {\n int64_t prime = get_number(i);\n int64_t multiple = prime * get_number(1), j = 2;\n\n if (prime < 0xffff)\n factor_table_[i] = (uint16_t) prime;\n\n for (; multiple <= max_; multiple = prime * get_number(j++))\n {\n int64_t index = get_index(multiple);\n\n \/\/ prime is the smallest factor\n if (factor_table_[index] == 0xffff)\n factor_table_[index] = (uint16_t) prime;\n \/\/ the least significant bit indicates whether multiple has\n \/\/ an even (0) or odd (1) number of prime factors\n else if (factor_table_[index] > 0)\n factor_table_[index] ^= 1;\n }\n\n \/\/ Moebius function is 0 if n has a squared prime factor\n multiple = prime * prime * get_number(0), j = 1;\n for (; multiple <= max_; multiple = prime * prime * get_number(j++))\n factor_table_[get_index(multiple)] = 0;\n }\n }\n}\n\n} \/\/ namespace\n<commit_msg>Fix minimum bug<commit_after>\/\/\/\n\/\/\/ @file FactorTable.cpp\n\/\/\/ @see FactorTable.hpp for documentation.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <FactorTable.hpp>\n#include <pmath.hpp>\n\n#include <limits>\n#include <stdexcept>\n#include <stdint.h>\n#include <vector>\n\nusing namespace std;\n\nnamespace primecount {\n\nconst uint8_t FactorTable::numbers_[48] =\n{\n 1, 11, 13, 17, 19, 23,\n 29, 31, 37, 41, 43, 47,\n 53, 59, 61, 67, 71, 73,\n 79, 83, 89, 97, 101, 103,\n 107, 109, 113, 121, 127, 131,\n 137, 139, 143, 149, 151, 157,\n 163, 167, 169, 173, 179, 181,\n 187, 191, 193, 197, 199, 209\n};\n\nconst int8_t FactorTable::indexes_[210] =\n{\n -1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 1, 2, 2, 2,\n 2, 3, 3, 4, 4, 4, 4, 5,\n 5, 5, 5, 5, 5, 6, 6, 7,\n 7, 7, 7, 7, 7, 8, 8, 8,\n 8, 9, 9, 10, 10, 10, 10, 11,\n 11, 11, 11, 11, 11, 12, 12, 12,\n 12, 12, 12, 13, 13, 14, 14, 14,\n 14, 14, 14, 15, 15, 15, 15, 16,\n 16, 17, 17, 17, 17, 17, 17, 18,\n 18, 18, 18, 19, 19, 19, 19, 19,\n 19, 20, 20, 20, 20, 20, 20, 20,\n 20, 21, 21, 21, 21, 22, 22, 23,\n 23, 23, 23, 24, 24, 25, 25, 25,\n 25, 26, 26, 26, 26, 26, 26, 26,\n 26, 27, 27, 27, 27, 27, 27, 28,\n 28, 28, 28, 29, 29, 29, 29, 29,\n 29, 30, 30, 31, 31, 31, 31, 32,\n 32, 32, 32, 32, 32, 33, 33, 34,\n 34, 34, 34, 34, 34, 35, 35, 35,\n 35, 35, 35, 36, 36, 36, 36, 37,\n 37, 38, 38, 38, 38, 39, 39, 39,\n 39, 39, 39, 40, 40, 41, 41, 41,\n 41, 41, 41, 42, 42, 42, 42, 43,\n 43, 44, 44, 44, 44, 45, 45, 46,\n 46, 46, 46, 46, 46, 46, 46, 46,\n 46, 47\n};\n\nFactorTable::FactorTable(int64_t max) :\n max_((max < 8) ? 8 : max)\n{\n if (isqrt(max_) >= numeric_limits<uint16_t>::max())\n throw runtime_error(\"FactorTable: sqrt(max) must be < max(uint16_t).\");\n init();\n}\n\nvoid FactorTable::init()\n{\n int64_t max_index = get_index(max_);\n factor_table_.resize(max_index + 1, 0xffff);\n\n for (size_t i = 1; i < factor_table_.size(); i++)\n {\n if (factor_table_[i] == 0xffff)\n {\n int64_t prime = get_number(i);\n int64_t multiple = prime * get_number(1), j = 2;\n\n if (prime < 0xffff)\n factor_table_[i] = (uint16_t) prime;\n\n for (; multiple <= max_; multiple = prime * get_number(j++))\n {\n int64_t index = get_index(multiple);\n\n \/\/ prime is the smallest factor\n if (factor_table_[index] == 0xffff)\n factor_table_[index] = (uint16_t) prime;\n \/\/ the least significant bit indicates whether multiple has\n \/\/ an even (0) or odd (1) number of prime factors\n else if (factor_table_[index] > 0)\n factor_table_[index] ^= 1;\n }\n\n \/\/ Moebius function is 0 if n has a squared prime factor\n multiple = prime * prime * get_number(0), j = 1;\n for (; multiple <= max_; multiple = prime * prime * get_number(j++))\n factor_table_[get_index(multiple)] = 0;\n }\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"lola\/PoseService.h\"\n#include \"boost\/thread.hpp\"\n\n#include <cstring>\n#include <iostream>\n\nvoid PoseService::read_handler(\n boost::system::error_code const& ec,\n std::size_t bytes_transferred) {\n std::cerr << \"Pose Service: Received \" << bytes_transferred << std::endl;\n if (bytes_transferred != sizeof(HR_Pose)) {\n std::cerr << \"Pose Service: Error: Invalid datagram size.\"\n << \"Expected \" << sizeof(HR_Pose) << std::endl;\n return;\n }\n boost::shared_ptr<HR_Pose> new_pose(new HR_Pose);\n \/\/ The copy is thread safe since nothing can be writing to the recv_buffer\n \/\/ at this point. No new async read is queued until this callback is complete.\n memcpy(&*new_pose, &recv_buffer_[0], sizeof(HR_Pose));\n \/\/ This performs an atomic update of the pointer, making it a lock-free,\n \/\/ thread-safe operation.\n pose_ = new_pose;\n std::cerr << \"Pose Service: Updated current pose\" << std::endl;\n queue_recv();\n}\n\nvoid PoseService::service_thread() {\n std::cerr << \"Pose Service: Thread started\" << std::endl;\n io_service_.run();\n}\n\nvoid PoseService::queue_recv() {\n socket_.async_receive(\n boost::asio::buffer(recv_buffer_),\n boost::bind(&PoseService::read_handler, this, _1, _2));\n}\n\nvoid PoseService::bind() {\n boost::system::error_code error;\n socket_.open(boost::asio::ip::udp::v4(), error);\n boost::asio::ip::udp::endpoint local(\n boost::asio::ip::address::from_string(host_),\n port_);\n socket_.bind(local);\n}\n\nvoid PoseService::start() {\n bind();\n queue_recv();\n \/\/ Start the thread that will run the associated I\/O service.\n boost::thread(boost::bind(&PoseService::service_thread, this));\n}\n\n\nHR_Pose PoseService::getCurrentPose() const {\n \/\/ This does an atomic copy of the pointer (the refcount is atomically updated)\n \/\/ There can be no race condition since if the service needs to update the\n \/\/ pointer, it will do so atomically and the reader also obtains a copy of the\n \/\/ pointer atomically.\n boost::shared_ptr<HR_Pose> p = pose_;\n \/\/ Now we are safe to manipulate the object itself, since nothing else needs\n \/\/ to directly touch the instance itself and we have safely obtained a\n \/\/ reference to it.\n \/\/ We just return the object (but this involves a non-atomic copy, hence the\n \/\/ pointer dance).\n\n if (p) {\n return *p;\n } else {\n HR_Pose pose = {0};\n return pose;\n }\n}\n<commit_msg>LOLA(PoseService): If the datagram is invalid, queue another receive<commit_after>#include \"lola\/PoseService.h\"\n#include \"boost\/thread.hpp\"\n\n#include <cstring>\n#include <iostream>\n\nvoid PoseService::read_handler(\n boost::system::error_code const& ec,\n std::size_t bytes_transferred) {\n std::cerr << \"Pose Service: Received \" << bytes_transferred << std::endl;\n if (bytes_transferred != sizeof(HR_Pose)) {\n std::cerr << \"Pose Service: Error: Invalid datagram size.\"\n << \"Expected \" << sizeof(HR_Pose) << std::endl;\n \/\/ If this one fails, we still queue another receive...\n queue_recv();\n return;\n }\n boost::shared_ptr<HR_Pose> new_pose(new HR_Pose);\n \/\/ The copy is thread safe since nothing can be writing to the recv_buffer\n \/\/ at this point. No new async read is queued until this callback is complete.\n memcpy(&*new_pose, &recv_buffer_[0], sizeof(HR_Pose));\n \/\/ This performs an atomic update of the pointer, making it a lock-free,\n \/\/ thread-safe operation.\n pose_ = new_pose;\n std::cerr << \"Pose Service: Updated current pose\" << std::endl;\n queue_recv();\n}\n\nvoid PoseService::service_thread() {\n std::cerr << \"Pose Service: Thread started\" << std::endl;\n io_service_.run();\n}\n\nvoid PoseService::queue_recv() {\n socket_.async_receive(\n boost::asio::buffer(recv_buffer_),\n boost::bind(&PoseService::read_handler, this, _1, _2));\n}\n\nvoid PoseService::bind() {\n boost::system::error_code error;\n socket_.open(boost::asio::ip::udp::v4(), error);\n boost::asio::ip::udp::endpoint local(\n boost::asio::ip::address::from_string(host_),\n port_);\n socket_.bind(local);\n}\n\nvoid PoseService::start() {\n bind();\n queue_recv();\n \/\/ Start the thread that will run the associated I\/O service.\n boost::thread(boost::bind(&PoseService::service_thread, this));\n}\n\n\nHR_Pose PoseService::getCurrentPose() const {\n \/\/ This does an atomic copy of the pointer (the refcount is atomically updated)\n \/\/ There can be no race condition since if the service needs to update the\n \/\/ pointer, it will do so atomically and the reader also obtains a copy of the\n \/\/ pointer atomically.\n boost::shared_ptr<HR_Pose> p = pose_;\n \/\/ Now we are safe to manipulate the object itself, since nothing else needs\n \/\/ to directly touch the instance itself and we have safely obtained a\n \/\/ reference to it.\n \/\/ We just return the object (but this involves a non-atomic copy, hence the\n \/\/ pointer dance).\n\n if (p) {\n return *p;\n } else {\n HR_Pose pose = {0};\n return pose;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef __LIBPYTHON_HPP__\n#define __LIBPYTHON_HPP__\n\n#include <string>\n#include <cstdint>\n\n#ifndef LIBPYTHON_CPP\n#define LIBPYTHON_EXTERN extern\n#else\n#define LIBPYTHON_EXTERN\n#endif\n\n#define _PYTHON_API_VERSION 1013\n#define _PYTHON3_ABI_VERSION 3\n\n\/\/ bitness detection\n#if INTPTR_MAX == INT64_MAX\n#define LIBPYTHON_64_BIT 1\n#elif INTPTR_MAX == INT32_MAX\n#define LIBPYTHON_32_BIT 1\n#else\n#error Unknown pointer size or missing size macros!\n#endif\n\n\n#if _WIN32 || _WIN64\n#if LIBPYTHON_64_BIT\ntypedef __int64 Py_ssize_t;\n#else\ntypedef int Py_ssize_t;\n#endif\n#else\ntypedef long Py_ssize_t;\n#endif\n\ntypedef struct _object PyObject;\n\n#define METH_VARARGS 0x0001\n#define METH_KEYWORDS 0x0002\n\n#define __PyObject_HEAD_EXTRA\n#define __PyObject_EXTRA_INIT\n\n#define _PyObject_HEAD \\\n__PyObject_HEAD_EXTRA \\\n Py_ssize_t ob_refcnt; \\\nstruct __typeobject *ob_type;\n\n#define _PyObject_VAR_HEAD \\\n_PyObject_HEAD \\\n Py_ssize_t ob_size;\n\ntypedef struct __typeobject {\n_PyObject_VAR_HEAD\n const char *tp_name;\n Py_ssize_t tp_basicsize, tp_itemsize;\n} _PyTypeObject;\n\ntypedef struct __object {\n_PyObject_HEAD\n} _PyObject;\n\ntypedef struct {\n_PyObject_VAR_HEAD\n} _PyVarObject;\n\ntypedef _PyObject *(*_PyCFunction)(PyObject *, PyObject *);\n\nstruct _PyMethodDef {\n const char\t*ml_name;\n _PyCFunction ml_meth;\n int\t\t ml_flags;\n const char\t*ml_doc;\n};\ntypedef struct _PyMethodDef _PyMethodDef;\n\n#define _PyObject_HEAD3 _PyObject ob_base;\n\n#define _PyObject_HEAD_INIT(type) \\\n{ __PyObject_EXTRA_INIT \\\n 1, type },\n\n#define _PyModuleDef_HEAD_INIT { \\\n_PyObject_HEAD_INIT(NULL) \\\n NULL, \\\n 0, \\\n NULL, \\\n}\n\ntypedef int (*_inquiry)(PyObject *);\ntypedef int (*_visitproc)(PyObject *, void *);\ntypedef int (*_traverseproc)(PyObject *, _visitproc, void *);\ntypedef void (*_freefunc)(void *);\n\ntypedef struct _PyModuleDef_Base {\n _PyObject_HEAD3\n _PyObject* (*m_init)(void);\n Py_ssize_t m_index;\n _PyObject* m_copy;\n} _PyModuleDef_Base;\n\ntypedef struct _PyModuleDef{\n _PyModuleDef_Base m_base;\n const char* m_name;\n const char* m_doc;\n Py_ssize_t m_size;\n _PyMethodDef *m_methods;\n _inquiry m_reload;\n _traverseproc m_traverse;\n _inquiry m_clear;\n _freefunc m_free;\n} _PyModuleDef;\n\n\nLIBPYTHON_EXTERN _PyTypeObject* _PyFunction_Type;\nLIBPYTHON_EXTERN _PyTypeObject* _PyModule_Type;\n\nLIBPYTHON_EXTERN PyObject* _Py_None;\nLIBPYTHON_EXTERN PyObject* _Py_Unicode;\nLIBPYTHON_EXTERN PyObject* _Py_String;\nLIBPYTHON_EXTERN PyObject* _Py_Int;\nLIBPYTHON_EXTERN PyObject* _Py_Long;\nLIBPYTHON_EXTERN PyObject* _Py_Bool;\nLIBPYTHON_EXTERN PyObject* _Py_True;\nLIBPYTHON_EXTERN PyObject* _Py_False;\nLIBPYTHON_EXTERN PyObject* _Py_Dict;\nLIBPYTHON_EXTERN PyObject* _Py_Float;\nLIBPYTHON_EXTERN PyObject* _Py_List;\nLIBPYTHON_EXTERN PyObject* _Py_Tuple;\nLIBPYTHON_EXTERN PyObject* _Py_Complex;\n\n#define _Py_TYPE(ob) (((PyObject*)(ob))->ob_type)\n\n#define _PyUnicode_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Unicode))\n#define _PyString_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_String))\n#define _PyInt_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Int))\n#define _PyLong_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Long))\n#define _PyBool_Check(o) ((o == _Py_False) | (o == _Py_True))\n#define _PyDict_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Dict))\n#define _PyFloat_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Float))\n#define _PyFunction_Check(op) ((_PyTypeObject*)(_Py_TYPE(op)) == _PyFunction_Type)\n#define _PyTuple_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Tuple))\n#define _PyList_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_List))\n#define _PyComplex_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Complex))\n\nLIBPYTHON_EXTERN void (*_Py_Initialize)();\n\nLIBPYTHON_EXTERN PyObject* (*_Py_InitModule4)(const char *name, _PyMethodDef *methods,\n const char *doc, PyObject *self,\n int apiver);\n\nLIBPYTHON_EXTERN PyObject* (*_PyImport_ImportModule)(const char *name);\n\nLIBPYTHON_EXTERN PyObject* (*_PyModule_Create2)(_PyModuleDef *def, int);\nLIBPYTHON_EXTERN int (*_PyImport_AppendInittab)(const char *name, PyObject* (*initfunc)());\n\nLIBPYTHON_EXTERN PyObject* (*_Py_BuildValue)(const char *format, ...);\n\nLIBPYTHON_EXTERN void (*_Py_IncRef)(PyObject *);\nLIBPYTHON_EXTERN void (*_Py_DecRef)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*__PyObject_Str)(PyObject *);\n\nLIBPYTHON_EXTERN int (*_PyObject_IsInstance)(PyObject *object, PyObject *typeorclass);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_Dir)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_Call)(PyObject *callable_object,\n PyObject *args, PyObject *kw);\nLIBPYTHON_EXTERN PyObject* (*_PyObject_CallFunctionObjArgs)(PyObject *callable,\n ...);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_GetAttrString)(PyObject*, const char *);\nLIBPYTHON_EXTERN int (*_PyObject_HasAttrString)(PyObject*, const char *);\n\nLIBPYTHON_EXTERN Py_ssize_t (*_PyTuple_Size)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_GetItem)(PyObject *, Py_ssize_t);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_New)(Py_ssize_t size);\nLIBPYTHON_EXTERN int (*_PyTuple_SetItem)(PyObject *, Py_ssize_t, PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_GetSlice)(PyObject *, Py_ssize_t, Py_ssize_t);\n\nLIBPYTHON_EXTERN PyObject* (*_PyList_New)(Py_ssize_t size);\nLIBPYTHON_EXTERN Py_ssize_t (*_PyList_Size)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyList_GetItem)(PyObject *, Py_ssize_t);\nLIBPYTHON_EXTERN int (*_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *);\n\nLIBPYTHON_EXTERN int (*_PyString_AsStringAndSize)(\n register PyObject *obj,\t\/* string or Unicode object *\/\n register char **s,\t\t\/* pointer to buffer variable *\/\n register Py_ssize_t *len\t\/* pointer to length variable or NULL\n (only possible for 0-terminated\n strings) *\/\n);\n\nLIBPYTHON_EXTERN PyObject* (*_PyString_FromString)(const char *);\nLIBPYTHON_EXTERN PyObject* (*_PyString_FromStringAndSize)(const char *, Py_ssize_t);\n\nLIBPYTHON_EXTERN PyObject* (*_PyUnicode_EncodeLocale)(PyObject *unicode, const char *errors);\nLIBPYTHON_EXTERN int (*_PyBytes_AsStringAndSize)(\n PyObject *obj, \/* string or Unicode object *\/\n char **s, \/* pointer to buffer variable *\/\n Py_ssize_t *len \/* pointer to length variable or NULL\n (only possible for 0-terminated\n strings) *\/\n);\nLIBPYTHON_EXTERN PyObject* (*_PyBytes_FromStringAndSize)(const char *, Py_ssize_t);\nLIBPYTHON_EXTERN PyObject* (*_PyUnicode_FromString)(const char *u);\n\nLIBPYTHON_EXTERN void (*_PyErr_Fetch)(PyObject **, PyObject **, PyObject **);\nLIBPYTHON_EXTERN PyObject* (*_PyErr_Occurred)(void);\nLIBPYTHON_EXTERN void (*_PyErr_NormalizeException)(PyObject**, PyObject**, PyObject**);\n\nLIBPYTHON_EXTERN int (*_PyCallable_Check)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyModule_GetDict)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyImport_AddModule)(const char *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyRun_StringFlags)(const char *, int, PyObject*, PyObject*, void*);\nLIBPYTHON_EXTERN int (*_PyRun_SimpleFileExFlags)(FILE *, const char *, int, void *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_GetIter)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyIter_Next)(PyObject *);\n\nLIBPYTHON_EXTERN void (*_PySys_SetArgv)(int, char **);\nLIBPYTHON_EXTERN void (*_PySys_SetArgv_v3)(int, wchar_t **);\n\ntypedef void (*_PyCapsule_Destructor)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyCapsule_New)(void *pointer, const char *name, _PyCapsule_Destructor destructor);\nLIBPYTHON_EXTERN void* (*_PyCapsule_GetPointer)(PyObject *capsule, const char *name);\n\nLIBPYTHON_EXTERN PyObject* (*_PyDict_New)(void);\nLIBPYTHON_EXTERN int (*_PyDict_SetItem)(PyObject *mp, PyObject *key, PyObject *item);\nLIBPYTHON_EXTERN int (*_PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item);\nLIBPYTHON_EXTERN int (*__PyDict_Next)(\n PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);\n\nLIBPYTHON_EXTERN PyObject* (*_PyInt_FromLong)(long);\nLIBPYTHON_EXTERN long (*_PyInt_AsLong)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyLong_FromLong)(long);\nLIBPYTHON_EXTERN long (*_PyLong_AsLong)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyBool_FromLong)(long);\n\nLIBPYTHON_EXTERN PyObject* (*_PyFloat_FromDouble)(double);\nLIBPYTHON_EXTERN double (*_PyFloat_AsDouble)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyComplex_FromDoubles)(double real, double imag);\nLIBPYTHON_EXTERN double (*_PyComplex_RealAsDouble)(PyObject *op);\nLIBPYTHON_EXTERN double (*_PyComplex_ImagAsDouble)(PyObject *op);\n\n\nenum _NPY_TYPES {\n _NPY_BOOL=0,\n _NPY_BYTE, _NPY_UBYTE,\n _NPY_SHORT, _NPY_USHORT,\n _NPY_INT, _NPY_UINT,\n _NPY_LONG, _NPY_ULONG,\n _NPY_LONGLONG, _NPY_ULONGLONG,\n _NPY_FLOAT, _NPY_DOUBLE, _NPY_LONGDOUBLE,\n _NPY_CFLOAT, _NPY_CDOUBLE, _NPY_CLONGDOUBLE,\n _NPY_OBJECT=17,\n _NPY_STRING, _NPY_UNICODE,\n _NPY_VOID,\n _NPY_DATETIME, _NPY_TIMEDELTA, _NPY_HALF,\n _NPY_NTYPES,\n _NPY_NOTYPE,\n _NPY_CHAR,\n _NPY_USERDEF=256,\n _NPY_NTYPES_ABI_COMPATIBLE=21\n};\n\n\/\/ int is still 32 bits on all relevant 64-bit platforms\n#define _NPY_INT32 _NPY_INT\n\n\nclass SharedLibrary {\n\npublic:\n bool load(const std::string& libPath, bool python3, std::string* pError);\n bool unload(std::string* pError);\n virtual ~SharedLibrary() {}\n\nprivate:\n virtual bool loadSymbols(bool python3, std::string* pError) = 0;\n\nprotected:\n SharedLibrary() : pLib_(NULL) {}\nprivate:\n SharedLibrary(const SharedLibrary&);\n\nprotected:\n void* pLib_;\n};\n\nclass LibPython : public SharedLibrary {\nprivate:\n LibPython() : SharedLibrary() {}\n friend SharedLibrary& libPython();\n virtual bool loadSymbols(bool python3, std::string* pError);\n};\n\ninline SharedLibrary& libPython() {\n static LibPython instance;\n return instance;\n}\n\nclass LibNumPy : public SharedLibrary {\nprivate:\n LibNumPy() : SharedLibrary() {}\n friend SharedLibrary& libNumPy();\n virtual bool loadSymbols(bool python3, std::string* pError);\n};\n\ninline SharedLibrary& libNumPy() {\n static LibNumPy instance;\n return instance;\n}\n\n#endif\n\n<commit_msg>no 64-bitness detection (required C++11)<commit_after>\n#ifndef __LIBPYTHON_HPP__\n#define __LIBPYTHON_HPP__\n\n#include <string>\n\n#ifndef LIBPYTHON_CPP\n#define LIBPYTHON_EXTERN extern\n#else\n#define LIBPYTHON_EXTERN\n#endif\n\n#define _PYTHON_API_VERSION 1013\n#define _PYTHON3_ABI_VERSION 3\n\n\n#if _WIN32 || _WIN64\n#if _WIN64\ntypedef __int64 Py_ssize_t;\n#else\ntypedef int Py_ssize_t;\n#endif\n#else\ntypedef long Py_ssize_t;\n#endif\n\ntypedef struct _object PyObject;\n\n#define METH_VARARGS 0x0001\n#define METH_KEYWORDS 0x0002\n\n#define __PyObject_HEAD_EXTRA\n#define __PyObject_EXTRA_INIT\n\n#define _PyObject_HEAD \\\n__PyObject_HEAD_EXTRA \\\n Py_ssize_t ob_refcnt; \\\nstruct __typeobject *ob_type;\n\n#define _PyObject_VAR_HEAD \\\n_PyObject_HEAD \\\n Py_ssize_t ob_size;\n\ntypedef struct __typeobject {\n_PyObject_VAR_HEAD\n const char *tp_name;\n Py_ssize_t tp_basicsize, tp_itemsize;\n} _PyTypeObject;\n\ntypedef struct __object {\n_PyObject_HEAD\n} _PyObject;\n\ntypedef struct {\n_PyObject_VAR_HEAD\n} _PyVarObject;\n\ntypedef _PyObject *(*_PyCFunction)(PyObject *, PyObject *);\n\nstruct _PyMethodDef {\n const char\t*ml_name;\n _PyCFunction ml_meth;\n int\t\t ml_flags;\n const char\t*ml_doc;\n};\ntypedef struct _PyMethodDef _PyMethodDef;\n\n#define _PyObject_HEAD3 _PyObject ob_base;\n\n#define _PyObject_HEAD_INIT(type) \\\n{ __PyObject_EXTRA_INIT \\\n 1, type },\n\n#define _PyModuleDef_HEAD_INIT { \\\n_PyObject_HEAD_INIT(NULL) \\\n NULL, \\\n 0, \\\n NULL, \\\n}\n\ntypedef int (*_inquiry)(PyObject *);\ntypedef int (*_visitproc)(PyObject *, void *);\ntypedef int (*_traverseproc)(PyObject *, _visitproc, void *);\ntypedef void (*_freefunc)(void *);\n\ntypedef struct _PyModuleDef_Base {\n _PyObject_HEAD3\n _PyObject* (*m_init)(void);\n Py_ssize_t m_index;\n _PyObject* m_copy;\n} _PyModuleDef_Base;\n\ntypedef struct _PyModuleDef{\n _PyModuleDef_Base m_base;\n const char* m_name;\n const char* m_doc;\n Py_ssize_t m_size;\n _PyMethodDef *m_methods;\n _inquiry m_reload;\n _traverseproc m_traverse;\n _inquiry m_clear;\n _freefunc m_free;\n} _PyModuleDef;\n\n\nLIBPYTHON_EXTERN _PyTypeObject* _PyFunction_Type;\nLIBPYTHON_EXTERN _PyTypeObject* _PyModule_Type;\n\nLIBPYTHON_EXTERN PyObject* _Py_None;\nLIBPYTHON_EXTERN PyObject* _Py_Unicode;\nLIBPYTHON_EXTERN PyObject* _Py_String;\nLIBPYTHON_EXTERN PyObject* _Py_Int;\nLIBPYTHON_EXTERN PyObject* _Py_Long;\nLIBPYTHON_EXTERN PyObject* _Py_Bool;\nLIBPYTHON_EXTERN PyObject* _Py_True;\nLIBPYTHON_EXTERN PyObject* _Py_False;\nLIBPYTHON_EXTERN PyObject* _Py_Dict;\nLIBPYTHON_EXTERN PyObject* _Py_Float;\nLIBPYTHON_EXTERN PyObject* _Py_List;\nLIBPYTHON_EXTERN PyObject* _Py_Tuple;\nLIBPYTHON_EXTERN PyObject* _Py_Complex;\n\n#define _Py_TYPE(ob) (((PyObject*)(ob))->ob_type)\n\n#define _PyUnicode_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Unicode))\n#define _PyString_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_String))\n#define _PyInt_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Int))\n#define _PyLong_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Long))\n#define _PyBool_Check(o) ((o == _Py_False) | (o == _Py_True))\n#define _PyDict_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Dict))\n#define _PyFloat_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Float))\n#define _PyFunction_Check(op) ((_PyTypeObject*)(_Py_TYPE(op)) == _PyFunction_Type)\n#define _PyTuple_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Tuple))\n#define _PyList_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_List))\n#define _PyComplex_Check(o) (_Py_TYPE(o) == _Py_TYPE(_Py_Complex))\n\nLIBPYTHON_EXTERN void (*_Py_Initialize)();\n\nLIBPYTHON_EXTERN PyObject* (*_Py_InitModule4)(const char *name, _PyMethodDef *methods,\n const char *doc, PyObject *self,\n int apiver);\n\nLIBPYTHON_EXTERN PyObject* (*_PyImport_ImportModule)(const char *name);\n\nLIBPYTHON_EXTERN PyObject* (*_PyModule_Create2)(_PyModuleDef *def, int);\nLIBPYTHON_EXTERN int (*_PyImport_AppendInittab)(const char *name, PyObject* (*initfunc)());\n\nLIBPYTHON_EXTERN PyObject* (*_Py_BuildValue)(const char *format, ...);\n\nLIBPYTHON_EXTERN void (*_Py_IncRef)(PyObject *);\nLIBPYTHON_EXTERN void (*_Py_DecRef)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*__PyObject_Str)(PyObject *);\n\nLIBPYTHON_EXTERN int (*_PyObject_IsInstance)(PyObject *object, PyObject *typeorclass);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_Dir)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_Call)(PyObject *callable_object,\n PyObject *args, PyObject *kw);\nLIBPYTHON_EXTERN PyObject* (*_PyObject_CallFunctionObjArgs)(PyObject *callable,\n ...);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_GetAttrString)(PyObject*, const char *);\nLIBPYTHON_EXTERN int (*_PyObject_HasAttrString)(PyObject*, const char *);\n\nLIBPYTHON_EXTERN Py_ssize_t (*_PyTuple_Size)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_GetItem)(PyObject *, Py_ssize_t);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_New)(Py_ssize_t size);\nLIBPYTHON_EXTERN int (*_PyTuple_SetItem)(PyObject *, Py_ssize_t, PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyTuple_GetSlice)(PyObject *, Py_ssize_t, Py_ssize_t);\n\nLIBPYTHON_EXTERN PyObject* (*_PyList_New)(Py_ssize_t size);\nLIBPYTHON_EXTERN Py_ssize_t (*_PyList_Size)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyList_GetItem)(PyObject *, Py_ssize_t);\nLIBPYTHON_EXTERN int (*_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *);\n\nLIBPYTHON_EXTERN int (*_PyString_AsStringAndSize)(\n register PyObject *obj,\t\/* string or Unicode object *\/\n register char **s,\t\t\/* pointer to buffer variable *\/\n register Py_ssize_t *len\t\/* pointer to length variable or NULL\n (only possible for 0-terminated\n strings) *\/\n);\n\nLIBPYTHON_EXTERN PyObject* (*_PyString_FromString)(const char *);\nLIBPYTHON_EXTERN PyObject* (*_PyString_FromStringAndSize)(const char *, Py_ssize_t);\n\nLIBPYTHON_EXTERN PyObject* (*_PyUnicode_EncodeLocale)(PyObject *unicode, const char *errors);\nLIBPYTHON_EXTERN int (*_PyBytes_AsStringAndSize)(\n PyObject *obj, \/* string or Unicode object *\/\n char **s, \/* pointer to buffer variable *\/\n Py_ssize_t *len \/* pointer to length variable or NULL\n (only possible for 0-terminated\n strings) *\/\n);\nLIBPYTHON_EXTERN PyObject* (*_PyBytes_FromStringAndSize)(const char *, Py_ssize_t);\nLIBPYTHON_EXTERN PyObject* (*_PyUnicode_FromString)(const char *u);\n\nLIBPYTHON_EXTERN void (*_PyErr_Fetch)(PyObject **, PyObject **, PyObject **);\nLIBPYTHON_EXTERN PyObject* (*_PyErr_Occurred)(void);\nLIBPYTHON_EXTERN void (*_PyErr_NormalizeException)(PyObject**, PyObject**, PyObject**);\n\nLIBPYTHON_EXTERN int (*_PyCallable_Check)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyModule_GetDict)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyImport_AddModule)(const char *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyRun_StringFlags)(const char *, int, PyObject*, PyObject*, void*);\nLIBPYTHON_EXTERN int (*_PyRun_SimpleFileExFlags)(FILE *, const char *, int, void *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyObject_GetIter)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyIter_Next)(PyObject *);\n\nLIBPYTHON_EXTERN void (*_PySys_SetArgv)(int, char **);\nLIBPYTHON_EXTERN void (*_PySys_SetArgv_v3)(int, wchar_t **);\n\ntypedef void (*_PyCapsule_Destructor)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyCapsule_New)(void *pointer, const char *name, _PyCapsule_Destructor destructor);\nLIBPYTHON_EXTERN void* (*_PyCapsule_GetPointer)(PyObject *capsule, const char *name);\n\nLIBPYTHON_EXTERN PyObject* (*_PyDict_New)(void);\nLIBPYTHON_EXTERN int (*_PyDict_SetItem)(PyObject *mp, PyObject *key, PyObject *item);\nLIBPYTHON_EXTERN int (*_PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item);\nLIBPYTHON_EXTERN int (*__PyDict_Next)(\n PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);\n\nLIBPYTHON_EXTERN PyObject* (*_PyInt_FromLong)(long);\nLIBPYTHON_EXTERN long (*_PyInt_AsLong)(PyObject *);\nLIBPYTHON_EXTERN PyObject* (*_PyLong_FromLong)(long);\nLIBPYTHON_EXTERN long (*_PyLong_AsLong)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyBool_FromLong)(long);\n\nLIBPYTHON_EXTERN PyObject* (*_PyFloat_FromDouble)(double);\nLIBPYTHON_EXTERN double (*_PyFloat_AsDouble)(PyObject *);\n\nLIBPYTHON_EXTERN PyObject* (*_PyComplex_FromDoubles)(double real, double imag);\nLIBPYTHON_EXTERN double (*_PyComplex_RealAsDouble)(PyObject *op);\nLIBPYTHON_EXTERN double (*_PyComplex_ImagAsDouble)(PyObject *op);\n\n\nenum _NPY_TYPES {\n _NPY_BOOL=0,\n _NPY_BYTE, _NPY_UBYTE,\n _NPY_SHORT, _NPY_USHORT,\n _NPY_INT, _NPY_UINT,\n _NPY_LONG, _NPY_ULONG,\n _NPY_LONGLONG, _NPY_ULONGLONG,\n _NPY_FLOAT, _NPY_DOUBLE, _NPY_LONGDOUBLE,\n _NPY_CFLOAT, _NPY_CDOUBLE, _NPY_CLONGDOUBLE,\n _NPY_OBJECT=17,\n _NPY_STRING, _NPY_UNICODE,\n _NPY_VOID,\n _NPY_DATETIME, _NPY_TIMEDELTA, _NPY_HALF,\n _NPY_NTYPES,\n _NPY_NOTYPE,\n _NPY_CHAR,\n _NPY_USERDEF=256,\n _NPY_NTYPES_ABI_COMPATIBLE=21\n};\n\n\/\/ int is still 32 bits on all relevant 64-bit platforms\n#define _NPY_INT32 _NPY_INT\n\n\nclass SharedLibrary {\n\npublic:\n bool load(const std::string& libPath, bool python3, std::string* pError);\n bool unload(std::string* pError);\n virtual ~SharedLibrary() {}\n\nprivate:\n virtual bool loadSymbols(bool python3, std::string* pError) = 0;\n\nprotected:\n SharedLibrary() : pLib_(NULL) {}\nprivate:\n SharedLibrary(const SharedLibrary&);\n\nprotected:\n void* pLib_;\n};\n\nclass LibPython : public SharedLibrary {\nprivate:\n LibPython() : SharedLibrary() {}\n friend SharedLibrary& libPython();\n virtual bool loadSymbols(bool python3, std::string* pError);\n};\n\ninline SharedLibrary& libPython() {\n static LibPython instance;\n return instance;\n}\n\nclass LibNumPy : public SharedLibrary {\nprivate:\n LibNumPy() : SharedLibrary() {}\n friend SharedLibrary& libNumPy();\n virtual bool loadSymbols(bool python3, std::string* pError);\n};\n\ninline SharedLibrary& libNumPy() {\n static LibNumPy instance;\n return instance;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef YOTTA_CFG_MBED_OS\n #include \"mbed-drivers\/mbed.h\"\n#else\n #include \"mbed.h\"\n#endif\n#include \"nRF5xn.h\"\n#include \"ble\/blecommon.h\"\n#include \"nrf_soc.h\"\n\n#include \"btle\/btle.h\"\n#include \"btle\/custom\/custom_helper.h\"\n#include \"nrf_delay.h\"\n\nextern \"C\" {\n#include \"softdevice_handler.h\"\n}\n\n#include \"nRF5xPalGattClient.h\"\n\n\/**\n * The singleton which represents the nRF51822 transport for the BLE.\n *\/\nstatic nRF5xn& getDeviceInstance() {\n static nRF5xn deviceInstance;\n return deviceInstance;\n}\n\n\n\/**\n * BLE-API requires an implementation of the following function in order to\n * obtain its transport handle.\n *\/\nBLEInstanceBase *\ncreateBLEInstance(void)\n{\n return &nRF5xn::Instance(BLE::DEFAULT_INSTANCE);\n}\n\nnRF5xn& nRF5xn::Instance(BLE::InstanceID_t instanceId)\n{\n return getDeviceInstance();\n}\n\nnRF5xn::nRF5xn(void) :\n initialized(false),\n instanceID(BLE::DEFAULT_INSTANCE),\n gapInstance(),\n gattServerInstance(NULL),\n gattClient(&(ble::pal::vendor::nordic::nRF5xGattClient::get_client()))\n{\n}\n\nnRF5xn::~nRF5xn(void)\n{\n}\n\nconst char *nRF5xn::getVersion(void)\n{\n if (!initialized) {\n return \"INITIALIZATION_INCOMPLETE\";\n }\n\n static char versionString[32];\n static bool versionFetched = false;\n\n if (!versionFetched) {\n ble_version_t version;\n if ((sd_ble_version_get(&version) == NRF_SUCCESS) && (version.company_id == 0x0059)) {\n switch (version.version_number) {\n case 0x07:\n case 0x08:\n snprintf(versionString, sizeof(versionString), \"Nordic BLE4.1 ver:%u fw:%04x\", version.version_number, version.subversion_number);\n break;\n default:\n snprintf(versionString, sizeof(versionString), \"Nordic (spec unknown) ver:%u fw:%04x\", version.version_number, version.subversion_number);\n break;\n }\n versionFetched = true;\n } else {\n strncpy(versionString, \"unknown\", sizeof(versionString));\n }\n }\n\n return versionString;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Initialize the BLE stack.\n\n @returns ble_error_t\n\n @retval BLE_ERROR_NONE if everything executed properly and\n BLE_ERROR_ALREADY_INITIALIZED if the stack has already\n been initialized (possibly through a call to nRF5xn::init()).\n BLE_ERROR_INTERNAL_STACK_FAILURE is returned if initialization\n of the internal stack (SoftDevice) failed.\n\n*\/\n\/**************************************************************************\/\nble_error_t nRF5xn::init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback)\n{\n if (initialized) {\n BLE::InitializationCompleteCallbackContext context = {\n BLE::Instance(instanceID),\n BLE_ERROR_ALREADY_INITIALIZED\n };\n callback.call(&context);\n return BLE_ERROR_ALREADY_INITIALIZED;\n }\n\n this->instanceID = instanceID;\n\n \/* ToDo: Clear memory contents, reset the SD, etc. *\/\n if (btle_init() != ERROR_NONE) {\n return BLE_ERROR_INTERNAL_STACK_FAILURE;\n }\n\n initialized = true;\n BLE::InitializationCompleteCallbackContext context = {\n BLE::Instance(instanceID),\n BLE_ERROR_NONE\n };\n callback.call(&context);\n return BLE_ERROR_NONE;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Purge the BLE stack of GATT and GAP state.\n\n @returns ble_error_t\n\n @retval BLE_ERROR_NONE\n Everything executed properly\n\n @note When using S110, GattClient::shutdown() will not be called\n since Gatt client features are not supported.\n*\/\n\/**************************************************************************\/\nble_error_t nRF5xn::shutdown(void)\n{\n if (!initialized) {\n return BLE_ERROR_INITIALIZATION_INCOMPLETE;\n }\n\n \/*\n * Shutdown the SoftDevice first. This is because we need to disable all\n * interrupts. Otherwise if we clear the BLE API and glue code first there\n * will be many NULL references and no config information which could lead\n * to errors if the shutdown process is interrupted.\n *\/\n if (softdevice_handler_sd_disable() != NRF_SUCCESS) {\n return BLE_STACK_BUSY;\n }\n\n \/* Shutdown the BLE API and nRF51 glue code *\/\n ble_error_t error;\n\n if (gattServerInstance != NULL) {\n error = gattServerInstance->reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n }\n\n \/* S110 does not support BLE client features, nothing to reset. *\/\n#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)\n error = getGattClient().reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n#endif\n\n \/* Gap instance is always present *\/\n error = gapInstance.reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n\n custom_reset_128bits_uuid_table();\n\n initialized = false;\n return BLE_ERROR_NONE;\n}\n\nSecurityManager& nRF5xn::getSecurityManager()\n{\n const nRF5xn* self = this;\n return const_cast<SecurityManager&>(self->getSecurityManager());\n}\n\nconst SecurityManager& nRF5xn::getSecurityManager() const\n{\n static ble::pal::MemorySecurityDb m_db;\n ble::pal::vendor::nordic::nRF5xSecurityManager &m_pal =\n ble::pal::vendor::nordic::nRF5xSecurityManager::get_security_manager();\n static struct : ble::pal::SigningEventMonitor {\n virtual void set_signing_event_handler(EventHandler *signing_event_handler) { }\n } dummy_signing_event_monitor;\n\n static ble::generic::GenericSecurityManager m_instance(\n m_pal,\n m_db,\n const_cast<nRF5xGap&>(getGap()),\n dummy_signing_event_monitor\n );\n\n return m_instance;\n}\n\nvoid\nnRF5xn::waitForEvent(void)\n{\n processEvents();\n sd_app_evt_wait();\n}\n\nvoid nRF5xn::processEvents() {\n if (isEventsSignaled) {\n isEventsSignaled = false;\n intern_softdevice_events_execute();\n }\n}\n<commit_msg>Nordic BLE: Protect event signaled flag.<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef YOTTA_CFG_MBED_OS\n #include \"mbed-drivers\/mbed.h\"\n#else\n #include \"mbed.h\"\n#endif\n#include \"nRF5xn.h\"\n#include \"ble\/blecommon.h\"\n#include \"nrf_soc.h\"\n\n#include \"btle\/btle.h\"\n#include \"btle\/custom\/custom_helper.h\"\n#include \"nrf_delay.h\"\n\nextern \"C\" {\n#include \"softdevice_handler.h\"\n}\n\n#include \"nRF5xPalGattClient.h\"\n\n\/**\n * The singleton which represents the nRF51822 transport for the BLE.\n *\/\nstatic nRF5xn& getDeviceInstance() {\n static nRF5xn deviceInstance;\n return deviceInstance;\n}\n\n\n\/**\n * BLE-API requires an implementation of the following function in order to\n * obtain its transport handle.\n *\/\nBLEInstanceBase *\ncreateBLEInstance(void)\n{\n return &nRF5xn::Instance(BLE::DEFAULT_INSTANCE);\n}\n\nnRF5xn& nRF5xn::Instance(BLE::InstanceID_t instanceId)\n{\n return getDeviceInstance();\n}\n\nnRF5xn::nRF5xn(void) :\n initialized(false),\n instanceID(BLE::DEFAULT_INSTANCE),\n gapInstance(),\n gattServerInstance(NULL),\n gattClient(&(ble::pal::vendor::nordic::nRF5xGattClient::get_client()))\n{\n}\n\nnRF5xn::~nRF5xn(void)\n{\n}\n\nconst char *nRF5xn::getVersion(void)\n{\n if (!initialized) {\n return \"INITIALIZATION_INCOMPLETE\";\n }\n\n static char versionString[32];\n static bool versionFetched = false;\n\n if (!versionFetched) {\n ble_version_t version;\n if ((sd_ble_version_get(&version) == NRF_SUCCESS) && (version.company_id == 0x0059)) {\n switch (version.version_number) {\n case 0x07:\n case 0x08:\n snprintf(versionString, sizeof(versionString), \"Nordic BLE4.1 ver:%u fw:%04x\", version.version_number, version.subversion_number);\n break;\n default:\n snprintf(versionString, sizeof(versionString), \"Nordic (spec unknown) ver:%u fw:%04x\", version.version_number, version.subversion_number);\n break;\n }\n versionFetched = true;\n } else {\n strncpy(versionString, \"unknown\", sizeof(versionString));\n }\n }\n\n return versionString;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Initialize the BLE stack.\n\n @returns ble_error_t\n\n @retval BLE_ERROR_NONE if everything executed properly and\n BLE_ERROR_ALREADY_INITIALIZED if the stack has already\n been initialized (possibly through a call to nRF5xn::init()).\n BLE_ERROR_INTERNAL_STACK_FAILURE is returned if initialization\n of the internal stack (SoftDevice) failed.\n\n*\/\n\/**************************************************************************\/\nble_error_t nRF5xn::init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback)\n{\n if (initialized) {\n BLE::InitializationCompleteCallbackContext context = {\n BLE::Instance(instanceID),\n BLE_ERROR_ALREADY_INITIALIZED\n };\n callback.call(&context);\n return BLE_ERROR_ALREADY_INITIALIZED;\n }\n\n this->instanceID = instanceID;\n\n \/* ToDo: Clear memory contents, reset the SD, etc. *\/\n if (btle_init() != ERROR_NONE) {\n return BLE_ERROR_INTERNAL_STACK_FAILURE;\n }\n\n initialized = true;\n BLE::InitializationCompleteCallbackContext context = {\n BLE::Instance(instanceID),\n BLE_ERROR_NONE\n };\n callback.call(&context);\n return BLE_ERROR_NONE;\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Purge the BLE stack of GATT and GAP state.\n\n @returns ble_error_t\n\n @retval BLE_ERROR_NONE\n Everything executed properly\n\n @note When using S110, GattClient::shutdown() will not be called\n since Gatt client features are not supported.\n*\/\n\/**************************************************************************\/\nble_error_t nRF5xn::shutdown(void)\n{\n if (!initialized) {\n return BLE_ERROR_INITIALIZATION_INCOMPLETE;\n }\n\n \/*\n * Shutdown the SoftDevice first. This is because we need to disable all\n * interrupts. Otherwise if we clear the BLE API and glue code first there\n * will be many NULL references and no config information which could lead\n * to errors if the shutdown process is interrupted.\n *\/\n if (softdevice_handler_sd_disable() != NRF_SUCCESS) {\n return BLE_STACK_BUSY;\n }\n\n \/* Shutdown the BLE API and nRF51 glue code *\/\n ble_error_t error;\n\n if (gattServerInstance != NULL) {\n error = gattServerInstance->reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n }\n\n \/* S110 does not support BLE client features, nothing to reset. *\/\n#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)\n error = getGattClient().reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n#endif\n\n \/* Gap instance is always present *\/\n error = gapInstance.reset();\n if (error != BLE_ERROR_NONE) {\n return error;\n }\n\n custom_reset_128bits_uuid_table();\n\n initialized = false;\n return BLE_ERROR_NONE;\n}\n\nSecurityManager& nRF5xn::getSecurityManager()\n{\n const nRF5xn* self = this;\n return const_cast<SecurityManager&>(self->getSecurityManager());\n}\n\nconst SecurityManager& nRF5xn::getSecurityManager() const\n{\n static ble::pal::MemorySecurityDb m_db;\n ble::pal::vendor::nordic::nRF5xSecurityManager &m_pal =\n ble::pal::vendor::nordic::nRF5xSecurityManager::get_security_manager();\n static struct : ble::pal::SigningEventMonitor {\n virtual void set_signing_event_handler(EventHandler *signing_event_handler) { }\n } dummy_signing_event_monitor;\n\n static ble::generic::GenericSecurityManager m_instance(\n m_pal,\n m_db,\n const_cast<nRF5xGap&>(getGap()),\n dummy_signing_event_monitor\n );\n\n return m_instance;\n}\n\nvoid\nnRF5xn::waitForEvent(void)\n{\n processEvents();\n sd_app_evt_wait();\n}\n\nvoid nRF5xn::processEvents() {\n core_util_critical_section_enter();\n if (isEventsSignaled) {\n isEventsSignaled = false;\n core_util_critical_section_exit();\n intern_softdevice_events_execute();\n } else {\n core_util_critical_section_exit();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <sysexits.h> \t\/\/ portablish exit values. \n#include <stdlib.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <assert.h>\n\n#include <string>\n\n#include <client.h> \/\/ we are a client of the watcher.\n#include <libwatcher\/edgeMessage.h> \/\/ we send edgeMessages to the watcher. \n#include <logger.h>\n\nusing namespace std;\nusing namespace watcher;\nusing namespace watcher::event;\n\nstatic const char *rcsid __attribute__ ((unused)) = \"$Id: routingfeeder.c,v 1.0 2009\/04\/28 22:08:47 glawler Exp $\";\n\n#define DEBUG 1\n\n\/* This is a feeder which polls the routing table,\n * and draws the routing algorithm's edges on the watcher\n *\n * Copyright (C) 2006,2007,2008,2009 Sparta Inc. Written by the NIP group, SRD, ISSO\n *\/\n\ntypedef struct Route\n{\n unsigned int dst;\n unsigned int nexthop;\n unsigned int mask;\n char iface[16];\n\n struct Route *next;\n} Route;\n\n\/*\n Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\n eth0 7402A8C0 7C02A8C0 0007 0 0 0 FFFFFFFF 00 0\n eth0 7402A8C0 7202A8C0 0007 0 0 0 FFFFFFFF 00 0\n *\/\n\nstatic Route *routeRead(unsigned int network, unsigned int netmask)\n{\n TRACE_ENTER(); \n\n FILE *fil;\n char line[1024];\n Route *list=NULL,*nxt;\n\n fil=fopen(\"\/proc\/net\/route\",\"r\");\n while(fgets(line,sizeof(line)-1,fil))\n {\n char iface[16];\n int flags,refcnt,use,metric,mtu,window;\n unsigned int dst,nexthop,mask;\n int rc;\n\n\n rc=sscanf(line,\"%s\\t%x\\t%x\\t%d\\t%d\\t%d\\t%d\\t%x\\t%o\\t%d\\n\",iface,&dst,&nexthop,&flags,&refcnt,&use,&metric,&mask,&mtu,&window);\n\n if (rc==10 && ((ntohl(dst) & netmask) == network))\n {\n nxt = (Route*)malloc(sizeof(*nxt));\n assert(nxt!=NULL);\n nxt->dst=htonl(dst);\n nxt->nexthop=htonl(nexthop);\n nxt->mask=ntohl(mask); \n strncpy(nxt->iface,iface,sizeof(nxt->iface));\n\n nxt->next=list;\n list=nxt;\n }\n }\n\n fclose(fil);\n\n TRACE_EXIT();\n return list;\n}\n\nstatic void routeDump(Route *r)\n{\n TRACE_ENTER();\n while(r)\n {\n LOG_DEBUG(r->dst << \" -> \" << r->nexthop << \" mask \" << r->mask); \n r=r->next;\n }\n TRACE_EXIT();\n}\n\nstatic int routeNumber(Route *r)\n{\n TRACE_ENTER();\n int count=0;\n\n while(r)\n {\n count++;\n r=r->next;\n }\n\n TRACE_EXIT_RET(count); \n return count;\n}\n\nstatic void routeFree(Route *r)\n{\n TRACE_ENTER();\n Route *d;\n\n while(r)\n {\n d=r;\n r=r->next;\n free(d);\n }\n TRACE_EXIT();\n}\n\nstatic void routeInsert(Route **list, Route *n)\n{\n TRACE_ENTER();\n Route *nxt;\n nxt = (Route*)malloc(sizeof(*nxt));\n nxt->dst=n->dst;\n nxt->nexthop=n->nexthop;\n nxt->mask=n->mask;\n\n nxt->next=*list;\n *list=nxt;\n TRACE_EXIT();\n}\n\n\/* return first route to in list which has the same nexthop\n*\/\nstatic Route *routeSearchNext(Route *list, Route *key)\n{\n TRACE_ENTER();\n Route *r;\n\n r=list;\n while(r)\n {\n if (r->nexthop==key->nexthop)\n {\n TRACE_EXIT_RET(r); \n return r;\n }\n r=r->next;\n }\n TRACE_EXIT_RET(\"NULL\"); \n return NULL;\n}\n\ntypedef struct detector\n{\n Client *watcherClientPtr;\n\n useconds_t reportperiod;\t\t\/* frequency to generate reports at *\/\n int reportnum;\n unsigned int localaddr;\n string iface;\n int routeedgewidth;\n Color onehopcolor;\n Color nexthopcolor;\n\n string nexthoplayer;\n string onehoplayer;\n\n int duration;\t\t\t \/* Time to run (in seconds) or 0 to run until broken *\/\n\n\tstruct in_addr filterNetwork;\n\tstruct in_addr filterMask;\n\tstruct in_addr localhost;\n\n} detector;\n\ntypedef struct DetectorInit\n{\n useconds_t reportperiod;\t\t\/* frequency to generate reports at *\/\n string iface;\n int onehopfamily;\n Color onehopcolor;\n Color nexthopcolor;\n int mouthnum;\n int duration;\t\t\t \/* Time to run (in seconds) or 0 to run until broken *\/\n int routeedgewidth; \n\n string serverName;\n\n string nexthoplayer;\n string onehoplayer;\n\n\tstruct in_addr filterNetwork;\n\tstruct in_addr filterMask;\n\tstruct in_addr localhost;\n\n} DetectorInit;\n\nstatic void updateRoutes(detector *st, Route *list)\n{\n TRACE_ENTER();\n Route *r,*tmpNextHop=NULL;\n Route *tmpOneHop=NULL;\n\n \/*\n * \tfor each edge in newlist,\n * \t \tif there is not an edge in oldList or tmpList to nexthop, add it, and add to tmpList\n *\/\n vector<MessagePtr> messages;\n for(r=list;r;r=r->next)\n {\n\n if (st->iface != string(r->iface)) \/* if we're checking interfaces, and this route is on the wrong one... *\/\n continue;\n\n#if 1\n LOG_DEBUG(\"nexthop inserting us -> \" << r->nexthop); \n#endif\n\n if ((r->nexthop!=0) && (routeSearchNext(tmpNextHop,r)==NULL)) \/* if its multi-hop, and not on the next hop list *\/\n {\n EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); \n em->node1=boost::asio::ip::address_v4(st->localaddr); \n em->node2=boost::asio::ip::address_v4(r->nexthop);\n em->edgeColor=st->nexthopcolor;\n em->expiration=st->reportperiod*1.5;\n em->width=st->routeedgewidth;\n em->layer=ROUTING_LAYER; \/\/ GTL st->nexthoplayer;\n em->addEdge=true;\n em->bidirectional=false;\n messages.push_back(em);\n\n routeInsert(&tmpNextHop,r);\n }\n\n if (r->nexthop==0) \/* if its a one-hop... *\/\n {\n#if 1\n LOG_DEBUG(\"onehop inserting us -> \" << r->dst); \n#endif\n EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); \n em->node1=boost::asio::ip::address_v4(st->localaddr); \n em->node2=boost::asio::ip::address_v4(r->dst); \n em->edgeColor=st->onehopcolor;\n em->expiration=st->reportperiod*1.5;\n em->width=st->routeedgewidth;\n em->layer=ROUTING_LAYER; \/\/ GTL st->onehoplayer;\n em->addEdge=true;\n em->bidirectional=false;\n messages.push_back(em);\n\n routeInsert(&tmpOneHop,r);\n }\n }\n st->watcherClientPtr->sendMessages(messages); \n\n routeFree(tmpNextHop);\n routeFree(tmpOneHop);\n\n TRACE_EXIT();\n}\n\n\n\/* This is called regularly by the select loop (below)\n * It will create a message, and send it to this node's coordinator\n *\/\nstatic void detectorSend(detector *st)\n{\n TRACE_ENTER();\n\n Route *list;\n\n list=routeRead(st->filterNetwork.s_addr, st->filterMask.s_addr);\n\n long long int curtime;\n struct timeval tp;\n gettimeofday(&tp, NULL); \n curtime=(long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n\n LOG_DEBUG(\"node= \" << st->localaddr << \" time= \" << curtime << \" numroutes= \" << routeNumber(list)); \n\n#ifdef DEBUG\n#if 0\n LOG_DEBUG(\"old:\"); \n routeDump(st->oldList);\n#endif\n LOG_DEBUG(\"new:\");\n routeDump(list);\n#endif\n\n st->reportnum++;\n\n updateRoutes(st,list);\n\n routeFree(list);\n\n TRACE_EXIT();\n}\n\nstatic detector *detectorInit(DetectorInit *detinit)\n{\n TRACE_ENTER();\n detector *st;\n\n st=new detector;\n st->iface=\"\";\n\n st->watcherClientPtr=new Client(detinit->serverName); \n if(st->watcherClientPtr==NULL)\n return NULL;\n\n st->duration=detinit->duration;\n st->reportperiod=detinit->reportperiod;\n st->reportnum=0;\n st->iface=detinit->iface;\n\n st->onehoplayer=detinit->onehoplayer;\n st->onehopcolor=detinit->onehopcolor; \n\n st->nexthoplayer=detinit->nexthoplayer;\n st->nexthopcolor=st->nexthopcolor;\n\n st->routeedgewidth=detinit->routeedgewidth;\n\n\tst->filterNetwork.s_addr=detinit->filterNetwork.s_addr;\n\tst->filterMask.s_addr=detinit->filterMask.s_addr;\n\tst->localhost.s_addr=detinit->localhost.s_addr;\n\n TRACE_EXIT();\n return st;\n}\n\n\/* \n * Wait around until we are ready to generate a message, then do it.\n *\/\nstatic void selectLoop(detector *dt)\n{\n TRACE_ENTER();\n\n time_t startTime=time(NULL); \n\n while(1)\n {\n usleep(dt->reportperiod*(useconds_t)1000.0); \n detectorSend(dt);\n\n if (dt->duration) \n if (time(NULL)-startTime>dt->duration)\n break;\n }\n\n dt->watcherClientPtr->wait(); \n\n TRACE_EXIT();\n}\n\nint main(int argc, char *argv[])\n{\n TRACE_ENTER();\n detector *dt;\n int ch;\n string logPropsFile(\"routeFeeder.log.properties\"); \n\n DetectorInit detinit;\n detinit.iface=\"\";\n detinit.onehopcolor=Color::green;\n detinit.onehoplayer=\"One Hop Routing\";\n detinit.nexthopcolor=Color::blue;\n detinit.nexthoplayer=\"Network Routing\"; \n detinit.reportperiod=2000;\n detinit.duration=0;\n detinit.routeedgewidth=15; \n\n\tdetinit.filterNetwork.s_addr=0;\n\tdetinit.filterMask.s_addr=0;\n\tdetinit.localhost.s_addr=0;\n\n while ((ch = getopt(argc, argv, \"m:n:h:o:x:t:e:b:i:d:p:w:l:?\")) != -1)\n switch (ch)\n {\n case 'm': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterMask))\n {\n fprintf(stderr, \"Error parsing filter mask: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'n': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterNetwork)) \n {\n fprintf(stderr, \"Error parsing filter network: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'h': if(-1 == inet_pton(AF_INET, optarg, &detinit.localhost)) \n {\n fprintf(stderr, \"Error parsing localhost address: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'o':\n detinit.onehopcolor.fromString(optarg);\n break;\n case 'x':\n detinit.nexthopcolor.fromString(optarg); \n break;\n case 't':\n sscanf(optarg,\"%d\",&detinit.duration);\n break;\n case 'e':\n detinit.onehoplayer=string(optarg); \n break;\n case 'b':\n detinit.nexthoplayer=string(optarg); \n break;\n case 'i':\n detinit.iface=string(optarg);\n break;\n case 'd':\n detinit.serverName=string(optarg);\n break;\n case 'p':\n sscanf(optarg,\"%d\",&detinit.reportperiod);\n break;\n case 'w':\n sscanf(optarg, \"%d\", &detinit.routeedgewidth); \n break;\n case 'l':\n logPropsFile=string(optarg);\n break;\n case '?':\n default:\n fprintf(stderr,\"routingdetector - poll the linux routing table, and draw the routes in the watcher\\n\"\n \"-d ipaddr\/hostname - specify watcherd address to connect to (duck)\\n\"\n \"-h ipaddr - this host's address\\n\"\n \"-m netmask - the mask used to filter the routes (ex. 255.255.255.0)\\n\"\n \"-n network - the network used to filter the routes (ex. 192.168.1.0)\\n\" \n \"-p milliseconds - specify the period to poll and report\\n\"\n \"-i interface - display only routes through this ethernet interface (or any if unspecified)\\n\"\n \"-o color - onehop edge color\\n\"\n \"-e layer - onehop layer name\\n\"\n \"-x color - nexthop edge color\\n\"\n \"-b layer - nexthop layer name\\n\"\n \"-t seconds - Run for this long, then exit\\n\"\n \"-w width - make edges width pixels wide (default 15)\\n\"\n );\n exit(1);\n break;\n }\n\n \/\/ init the logging system\n LOAD_LOG_PROPS(logPropsFile); \n LOG_INFO(\"Logger initialized from file \\\"\" << logPropsFile << \"\\\"\");\n\n\t\/\/ check args, errors, etc before doing real work\n\tif(detinit.localhost.s_addr == 0) \n {\n fprintf(stderr, \"localhost address cannot be blank\\n\"); \n exit(EX_USAGE);\n }\n\tif(detinit.filterNetwork.s_addr == 0) \n\t{ \n fprintf(stderr, \"filter network cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\tif(detinit.filterMask.s_addr == 0) \n\t{ \n fprintf(stderr, \"filter mask cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\tif(detinit.serverName.empty())\n\t{ \n fprintf(stderr, \"watcherd hostname cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\n dt=detectorInit(&detinit);\n\n if (dt==NULL)\n {\n fprintf(stderr,\"detector init failed, probably could not connect to infrastructure demon.\\n\");\n exit(1);\n }\n printf(\"%s: starting\\n\",argv[0]);\n selectLoop(dt);\n\n TRACE_EXIT(); \n return 0;\n}\n<commit_msg>send routes as array of messages so they all get stuck in the same IP packet.<commit_after>#include <stdio.h>\n#include <sysexits.h> \t\/\/ portablish exit values. \n#include <stdlib.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <assert.h>\n\n#include <string>\n\n#include <client.h> \/\/ we are a client of the watcher.\n#include <libwatcher\/edgeMessage.h> \/\/ we send edgeMessages to the watcher. \n#include <logger.h>\n\nusing namespace std;\nusing namespace watcher;\nusing namespace watcher::event;\n\nstatic const char *rcsid __attribute__ ((unused)) = \"$Id: routingfeeder.c,v 1.0 2009\/04\/28 22:08:47 glawler Exp $\";\n\n\/\/ #define DEBUG 1\n\n\/* This is a feeder which polls the routing table,\n * and draws the routing algorithm's edges on the watcher\n *\n * Copyright (C) 2006,2007,2008,2009 Sparta Inc. Written by the NIP group, SRD, ISSO\n *\/\n\ntypedef struct Route\n{\n unsigned int dst;\n unsigned int nexthop;\n unsigned int mask;\n char iface[16];\n\n struct Route *next;\n} Route;\n\n\/*\n Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT\n eth0 7402A8C0 7C02A8C0 0007 0 0 0 FFFFFFFF 00 0\n eth0 7402A8C0 7202A8C0 0007 0 0 0 FFFFFFFF 00 0\n *\/\n\nstatic Route *routeRead(unsigned int network, unsigned int netmask)\n{\n TRACE_ENTER(); \n\n FILE *fil;\n char line[1024];\n Route *list=NULL,*nxt;\n\n fil=fopen(\"\/proc\/net\/route\",\"r\");\n while(fgets(line,sizeof(line)-1,fil))\n {\n char iface[16];\n int flags,refcnt,use,metric,mtu,window;\n unsigned int dst,nexthop,mask;\n int rc;\n\n\n rc=sscanf(line,\"%s\\t%x\\t%x\\t%d\\t%d\\t%d\\t%d\\t%x\\t%o\\t%d\\n\",iface,&dst,&nexthop,&flags,&refcnt,&use,&metric,&mask,&mtu,&window);\n\n if (rc==10 && ((ntohl(dst) & ntohl(netmask)) == ntohl(network)))\n {\n nxt = (Route*)malloc(sizeof(*nxt));\n assert(nxt!=NULL);\n nxt->dst=htonl(dst);\n nxt->nexthop=htonl(nexthop);\n nxt->mask=ntohl(mask); \n strncpy(nxt->iface,iface,sizeof(nxt->iface));\n\n nxt->next=list;\n list=nxt;\n }\n }\n\n fclose(fil);\n\n TRACE_EXIT();\n return list;\n}\n\n#if DEBUG\nstatic void routeDump(Route *r)\n{\n TRACE_ENTER();\n while(r)\n {\n LOG_DEBUG(r->dst << \" -> \" << r->nexthop << \" mask \" << r->mask); \n r=r->next;\n }\n TRACE_EXIT();\n}\n#endif \/\/ DEBUG\n\nstatic int routeNumber(Route *r)\n{\n TRACE_ENTER();\n int count=0;\n\n while(r)\n {\n count++;\n r=r->next;\n }\n\n TRACE_EXIT_RET(count); \n return count;\n}\n\nstatic void routeFree(Route *r)\n{\n TRACE_ENTER();\n Route *d;\n\n while(r)\n {\n d=r;\n r=r->next;\n free(d);\n }\n TRACE_EXIT();\n}\n\nstatic void routeInsert(Route **list, Route *n)\n{\n TRACE_ENTER();\n Route *nxt;\n nxt = (Route*)malloc(sizeof(*nxt));\n nxt->dst=n->dst;\n nxt->nexthop=n->nexthop;\n nxt->mask=n->mask;\n\n nxt->next=*list;\n *list=nxt;\n TRACE_EXIT();\n}\n\n\/* return first route to in list which has the same nexthop\n*\/\nstatic Route *routeSearchNext(Route *list, Route *key)\n{\n TRACE_ENTER();\n Route *r;\n\n r=list;\n while(r)\n {\n if (r->nexthop==key->nexthop)\n {\n TRACE_EXIT_RET(r); \n return r;\n }\n r=r->next;\n }\n TRACE_EXIT_RET(\"NULL\"); \n return NULL;\n}\n\ntypedef struct detector\n{\n Client *watcherClientPtr;\n\n useconds_t reportperiod;\t\t\/* frequency to generate reports at *\/\n int reportnum;\n string iface;\n int routeedgewidth;\n Color onehopcolor;\n Color nexthopcolor;\n\n string nexthoplayer;\n string onehoplayer;\n\n int duration;\t\t\t \/* Time to run (in seconds) or 0 to run until broken *\/\n\n\tstruct in_addr filterNetwork;\n\tstruct in_addr filterMask;\n\tstruct in_addr localhost;\n\n} detector;\n\ntypedef struct DetectorInit\n{\n useconds_t reportperiod;\t\t\/* frequency to generate reports at *\/\n string iface;\n int onehopfamily;\n Color onehopcolor;\n Color nexthopcolor;\n int mouthnum;\n int duration;\t\t\t \/* Time to run (in seconds) or 0 to run until broken *\/\n int routeedgewidth; \n\n string serverName;\n\n string nexthoplayer;\n string onehoplayer;\n\n\tstruct in_addr filterNetwork;\n\tstruct in_addr filterMask;\n\tstruct in_addr localhost;\n\n} DetectorInit;\n\nstatic void updateRoutes(detector *st, Route *list)\n{\n TRACE_ENTER();\n Route *r,*tmpNextHop=NULL;\n Route *tmpOneHop=NULL;\n\n \/*\n * \tfor each edge in newlist,\n * \t \tif there is not an edge in oldList or tmpList to nexthop, add it, and add to tmpList\n *\/\n vector<MessagePtr> messages;\n for(r=list;r;r=r->next)\n {\n if (!st->iface.empty()) \n if (st->iface != string(r->iface)) \/* if we're checking interfaces, and this route is on the wrong one... *\/\n continue;\n\n#if 1\n LOG_DEBUG(\"nexthop inserting us -> \" << r->nexthop); \n#endif\n\n if ((r->nexthop!=0) && (routeSearchNext(tmpNextHop,r)==NULL)) \/* if its multi-hop, and not on the next hop list *\/\n {\n EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); \n em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); \n em->node2=boost::asio::ip::address_v4(r->nexthop);\n em->edgeColor=st->nexthopcolor;\n em->expiration=st->reportperiod*1.5;\n em->width=st->routeedgewidth;\n em->layer=ROUTING_LAYER; \/\/ GTL st->nexthoplayer;\n em->addEdge=true;\n em->bidirectional=false;\n messages.push_back(em);\n\n routeInsert(&tmpNextHop,r);\n }\n\n if (r->nexthop==0) \/* if its a one-hop... *\/\n {\n#if 1\n LOG_DEBUG(\"onehop inserting us -> \" << r->dst); \n#endif\n EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); \n em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); \n em->node2=boost::asio::ip::address_v4(r->dst); \n em->edgeColor=st->onehopcolor;\n em->expiration=st->reportperiod*1.5;\n em->width=st->routeedgewidth;\n em->layer=ROUTING_LAYER; \/\/ GTL st->onehoplayer;\n em->addEdge=true;\n em->bidirectional=false;\n messages.push_back(em);\n\n routeInsert(&tmpOneHop,r);\n }\n }\n if (!messages.empty())\n st->watcherClientPtr->sendMessages(messages); \n else\n LOG_DEBUG(\"No routes found so no messages sent!\"); \n\n routeFree(tmpNextHop);\n routeFree(tmpOneHop);\n\n TRACE_EXIT();\n}\n\n\n\/* This is called regularly by the select loop (below)\n * It will create a message, and send it to this node's coordinator\n *\/\nstatic void detectorSend(detector *st)\n{\n TRACE_ENTER();\n\n Route *list;\n\n list=routeRead(st->filterNetwork.s_addr, st->filterMask.s_addr);\n\n long long int curtime;\n struct timeval tp;\n gettimeofday(&tp, NULL); \n curtime=(long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n\n LOG_DEBUG(\"node= \" << st->localhost.s_addr << \" time= \" << curtime << \" numroutes= \" << routeNumber(list)); \n\n#ifdef DEBUG\n LOG_DEBUG(\"old:\"); \n routeDump(st->oldList);\n\n LOG_DEBUG(\"new:\");\n routeDump(list);\n#endif\n\n st->reportnum++;\n\n updateRoutes(st,list);\n\n routeFree(list);\n\n TRACE_EXIT();\n}\n\nstatic detector *detectorInit(DetectorInit *detinit)\n{\n TRACE_ENTER();\n detector *st;\n\n st=new detector;\n st->iface=\"\";\n\n st->watcherClientPtr=new Client(detinit->serverName); \n if(st->watcherClientPtr==NULL)\n return NULL;\n\n st->duration=detinit->duration;\n st->reportperiod=detinit->reportperiod;\n st->reportnum=0;\n st->iface=detinit->iface;\n\n st->onehoplayer=detinit->onehoplayer;\n st->onehopcolor=detinit->onehopcolor; \n\n st->nexthoplayer=detinit->nexthoplayer;\n st->nexthopcolor=st->nexthopcolor;\n\n st->routeedgewidth=detinit->routeedgewidth;\n\n\tst->filterNetwork.s_addr=detinit->filterNetwork.s_addr;\n\tst->filterMask.s_addr=detinit->filterMask.s_addr;\n\tst->localhost.s_addr=detinit->localhost.s_addr;\n\n TRACE_EXIT();\n return st;\n}\n\n\/* \n * Wait around until we are ready to generate a message, then do it.\n *\/\nstatic void selectLoop(detector *dt)\n{\n TRACE_ENTER();\n\n time_t startTime=time(NULL); \n\n while(1)\n {\n usleep(dt->reportperiod*(useconds_t)1000.0); \n detectorSend(dt);\n\n if (dt->duration) \n if (time(NULL)-startTime>dt->duration)\n break;\n }\n\n dt->watcherClientPtr->wait(); \n\n TRACE_EXIT();\n}\n\nint main(int argc, char *argv[])\n{\n TRACE_ENTER();\n detector *dt;\n int ch;\n string logPropsFile(\"routeFeeder.log.properties\"); \n\n DetectorInit detinit;\n detinit.iface=\"\";\n detinit.onehopcolor=Color::green;\n detinit.onehoplayer=\"One Hop Routing\";\n detinit.nexthopcolor=Color::blue;\n detinit.nexthoplayer=\"Network Routing\"; \n detinit.reportperiod=2000;\n detinit.duration=0;\n detinit.routeedgewidth=15; \n\n\tdetinit.filterNetwork.s_addr=0;\n\tdetinit.filterMask.s_addr=0;\n\tdetinit.localhost.s_addr=0;\n\n while ((ch = getopt(argc, argv, \"m:n:h:o:x:t:e:b:i:d:p:w:l:?\")) != -1)\n switch (ch)\n {\n case 'm': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterMask))\n {\n fprintf(stderr, \"Error parsing filter mask: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'n': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterNetwork)) \n {\n fprintf(stderr, \"Error parsing filter network: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'h': if(-1 == inet_pton(AF_INET, optarg, &detinit.localhost)) \n {\n fprintf(stderr, \"Error parsing localhost address: %s\\n\", optarg); \n exit(EX_USAGE); \n }\n break;\n case 'o':\n detinit.onehopcolor.fromString(optarg);\n break;\n case 'x':\n detinit.nexthopcolor.fromString(optarg); \n break;\n case 't':\n sscanf(optarg,\"%d\",&detinit.duration);\n break;\n case 'e':\n detinit.onehoplayer=string(optarg); \n break;\n case 'b':\n detinit.nexthoplayer=string(optarg); \n break;\n case 'i':\n detinit.iface=string(optarg);\n break;\n case 'd':\n detinit.serverName=string(optarg);\n break;\n case 'p':\n sscanf(optarg,\"%d\",&detinit.reportperiod);\n break;\n case 'w':\n sscanf(optarg, \"%d\", &detinit.routeedgewidth); \n break;\n case 'l':\n logPropsFile=string(optarg);\n break;\n case '?':\n default:\n fprintf(stderr,\"routingdetector - poll the linux routing table, and draw the routes in the watcher\\n\"\n \"-d ipaddr\/hostname - specify watcherd address to connect to (duck)\\n\"\n \"-h ipaddr - this host's address\\n\"\n \"-m netmask - the mask used to filter the routes (ex. 255.255.255.0)\\n\"\n \"-n network - the network used to filter the routes (ex. 192.168.1.0)\\n\" \n \"-p milliseconds - specify the period to poll and report\\n\"\n \"-i interface - display only routes through this ethernet interface (or any if unspecified)\\n\"\n \"-o color - onehop edge color\\n\"\n \"-e layer - onehop layer name\\n\"\n \"-x color - nexthop edge color\\n\"\n \"-b layer - nexthop layer name\\n\"\n \"-t seconds - Run for this long, then exit\\n\"\n \"-w width - make edges width pixels wide (default 15)\\n\"\n );\n exit(1);\n break;\n }\n\n \/\/ init the logging system\n LOAD_LOG_PROPS(logPropsFile); \n LOG_INFO(\"Logger initialized from file \\\"\" << logPropsFile << \"\\\"\");\n\n\t\/\/ check args, errors, etc before doing real work\n\tif(detinit.localhost.s_addr == 0) \n {\n fprintf(stderr, \"localhost address cannot be blank\\n\"); \n exit(EX_USAGE);\n }\n\tif(detinit.filterNetwork.s_addr == 0) \n\t{ \n fprintf(stderr, \"filter network cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\tif(detinit.filterMask.s_addr == 0) \n\t{ \n fprintf(stderr, \"filter mask cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\tif(detinit.serverName.empty())\n\t{ \n fprintf(stderr, \"watcherd hostname cannot be blank\\n\"); \n exit(EX_USAGE);\n\t}\n\n dt=detectorInit(&detinit);\n\n if (dt==NULL)\n {\n fprintf(stderr,\"detector init failed, probably could not connect to infrastructure demon.\\n\");\n exit(1);\n }\n printf(\"%s: starting\\n\",argv[0]);\n selectLoop(dt);\n\n TRACE_EXIT(); \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"applications.h\"\n#include <QDir>\n\nconst int Applications::NameRole = Qt::UserRole + 1;\nconst int Applications::IconRole = Qt::UserRole + 2;\nconst int Applications::ExecRole = Qt::UserRole + 3;\nconst int Applications::TerminalRole = Qt::UserRole + 4;\n\nApplications::Applications(QObject *parent) :\n QAbstractListModel(parent)\n{\n connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished()));\n m_parserRunning = true;\n m_parserThread = QtConcurrent::run(this, &Applications::parseApplications);\n m_parserThreadWatcher.setFuture(m_parserThread);\n}\n\nApplications::~Applications()\n{\n if (m_parserThread.isRunning())\n m_parserThread.cancel();\n qDeleteAll(this->m_internalData);\n}\n\nvoid Applications::parseApplications()\n{\n this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH));\n this->m_files.append(this->readFolder(APPLICATIONS_PATH));\n\n foreach(QString file, this->m_files)\n {\n DesktopFile* app = new DesktopFile(file);\n if (!app->noDisplay() && !app->terminal())\n {\n m_internalData.append(app);\n }\n }\n this->m_files.clear();\n}\n\nQStringList Applications::readFolder(QString folder)\n{\n QDir dir(folder);\n QFileInfoList file_list = dir.entryInfoList(\n QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable);\n\n QStringList files;\n foreach(QFileInfo file, file_list)\n {\n if (this->m_files.filter(file.fileName()).count() == 0)\n {\n files.append(file.absoluteFilePath());\n }\n }\n return files;\n}\n\nvoid Applications::add(DesktopFile *item)\n{\n beginInsertRows(QModelIndex(), m_data.size(), m_data.size());\n m_data.append(item);\n endInsertRows();\n emit countChanged(m_data.size());\n}\n\nvoid Applications::sort()\n{\n std::sort(this->m_data.begin(), this->m_data.end(),\n [](const DesktopFile* left, const DesktopFile* right) -> bool\n {\n return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0;\n });\n}\n\nDesktopFile* Applications::get(int index) const\n{\n return m_data.at(index);\n}\n\nvoid Applications::filter(QString search)\n{\n if (m_parserRunning) return;\n beginRemoveRows(QModelIndex(), 0, m_data.size());\n m_data.clear();\n endRemoveRows();\n foreach(DesktopFile* file, m_internalData)\n {\n if(file->name().contains(search,Qt::CaseInsensitive)\n || file->comment().contains(search, Qt::CaseInsensitive)\n || file->exec().contains(search, Qt::CaseInsensitive))\n {\n this->add(file);\n }\n }\n this->sort();\n}\n\nint Applications::rowCount(const QModelIndex &) const\n{\n return m_data.count();\n}\n\nQVariant Applications::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid())\n return QVariant();\n if (index.row() > (m_data.size()-1) )\n return QVariant();\n\n DesktopFile* obj = m_data.at(index.row());\n switch(role)\n {\n case Qt::DisplayRole:\n case NameRole:\n return QVariant::fromValue(obj->name());\n break;\n\n case IconRole:\n return QVariant::fromValue(obj->icon());\n\n case ExecRole:\n return QVariant::fromValue(obj->exec());\n\n case TerminalRole:\n return QVariant::fromValue(obj->terminal());\n\n default:\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> Applications::roleNames() const\n{\n QHash<int, QByteArray> roles = QAbstractListModel::roleNames();\n roles.insert(NameRole, QByteArray(\"name\"));\n roles.insert(IconRole, QByteArray(\"icon\"));\n roles.insert(ExecRole, QByteArray(\"exec\"));\n roles.insert(TerminalRole, QByteArray(\"terminal\"));\n return roles;\n}\n\nvoid Applications::parseFinished()\n{\n m_parserRunning = false;\n this->filter(\"\");\n emit ready();\n}\n<commit_msg>Add debug message<commit_after>#include \"applications.h\"\n#include <QDir>\n#include <qdebug.h>\n\nconst int Applications::NameRole = Qt::UserRole + 1;\nconst int Applications::IconRole = Qt::UserRole + 2;\nconst int Applications::ExecRole = Qt::UserRole + 3;\nconst int Applications::TerminalRole = Qt::UserRole + 4;\n\nApplications::Applications(QObject *parent) :\n QAbstractListModel(parent)\n{\n connect(&m_parserThreadWatcher, SIGNAL(finished()), this, SLOT(parseFinished()));\n m_parserRunning = true;\n m_parserThread = QtConcurrent::run(this, &Applications::parseApplications);\n m_parserThreadWatcher.setFuture(m_parserThread);\n}\n\nApplications::~Applications()\n{\n if (m_parserThread.isRunning())\n m_parserThread.cancel();\n qDeleteAll(this->m_internalData);\n}\n\nvoid Applications::parseApplications()\n{\n this->m_files.append(this->readFolder(QDir::homePath() + APPLICATIONS_LOCAL_PATH));\n this->m_files.append(this->readFolder(APPLICATIONS_PATH));\n\n foreach(QString file, this->m_files)\n {\n DesktopFile* app = new DesktopFile(file);\n if (!app->noDisplay() && !app->terminal())\n {\n \/\/ qDebug() << \"Adding application: \" << app->name();\n m_internalData.append(app);\n }\n }\n this->m_files.clear();\n}\n\nQStringList Applications::readFolder(QString folder)\n{\n QDir dir(folder);\n QFileInfoList file_list = dir.entryInfoList(\n QStringList(APPLICATIONS_FILES), QDir::Files | QDir::Readable);\n\n QStringList files;\n foreach(QFileInfo file, file_list)\n {\n if (this->m_files.filter(file.fileName()).count() == 0)\n {\n files.append(file.absoluteFilePath());\n }\n }\n return files;\n}\n\nvoid Applications::add(DesktopFile *item)\n{\n beginInsertRows(QModelIndex(), m_data.size(), m_data.size());\n m_data.append(item);\n endInsertRows();\n emit countChanged(m_data.size());\n}\n\nvoid Applications::sort()\n{\n std::sort(this->m_data.begin(), this->m_data.end(),\n [](const DesktopFile* left, const DesktopFile* right) -> bool\n {\n return QString::compare(left->name(),right->name(), Qt::CaseInsensitive) < 0;\n });\n}\n\nDesktopFile* Applications::get(int index) const\n{\n return m_data.at(index);\n}\n\nvoid Applications::filter(QString search)\n{\n if (m_parserRunning) return;\n beginRemoveRows(QModelIndex(), 0, m_data.size());\n m_data.clear();\n endRemoveRows();\n foreach(DesktopFile* file, m_internalData)\n {\n if(file->name().contains(search,Qt::CaseInsensitive)\n || file->comment().contains(search, Qt::CaseInsensitive)\n || file->exec().contains(search, Qt::CaseInsensitive))\n {\n this->add(file);\n }\n }\n this->sort();\n}\n\nint Applications::rowCount(const QModelIndex &) const\n{\n return m_data.count();\n}\n\nQVariant Applications::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid())\n return QVariant();\n if (index.row() > (m_data.size()-1) )\n return QVariant();\n\n DesktopFile* obj = m_data.at(index.row());\n switch(role)\n {\n case Qt::DisplayRole:\n case NameRole:\n return QVariant::fromValue(obj->name());\n break;\n\n case IconRole:\n return QVariant::fromValue(obj->icon());\n\n case ExecRole:\n return QVariant::fromValue(obj->exec());\n\n case TerminalRole:\n return QVariant::fromValue(obj->terminal());\n\n default:\n return QVariant();\n }\n}\n\nQHash<int, QByteArray> Applications::roleNames() const\n{\n QHash<int, QByteArray> roles = QAbstractListModel::roleNames();\n roles.insert(NameRole, QByteArray(\"name\"));\n roles.insert(IconRole, QByteArray(\"icon\"));\n roles.insert(ExecRole, QByteArray(\"exec\"));\n roles.insert(TerminalRole, QByteArray(\"terminal\"));\n return roles;\n}\n\nvoid Applications::parseFinished()\n{\n m_parserRunning = false;\n this->filter(\"\");\n emit ready();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_DROPWHILE_H_\n#define ITER_DROPWHILE_H_\n\n#include \"internal\/iterbase.hpp\"\n#include \"filter.hpp\"\n\n#include <utility>\n#include <iterator>\n\nnamespace iter {\n namespace impl {\n template <typename FilterFunc, typename Container>\n class Dropper;\n\n using DropWhileFn = IterToolFnOptionalBindFirst<Dropper, BoolTester>;\n }\n constexpr impl::DropWhileFn dropwhile{};\n}\n\ntemplate <typename FilterFunc, typename Container>\nclass iter::impl::Dropper {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend DropWhileFn;\n\n Dropper(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward<Container>(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n Dropper(Dropper&&) = default;\n class Iterator : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>> {\n private:\n using Holder = DerefHolder<iterator_deref<Container>>;\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() {\n while (this->sub_iter != this->sub_end\n && (*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_passes();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n};\n\n#endif\n<commit_msg>Supports different begin and end in dropwhile<commit_after>#ifndef ITER_DROPWHILE_H_\n#define ITER_DROPWHILE_H_\n\n#include \"internal\/iterbase.hpp\"\n#include \"internal\/iterator_wrapper.hpp\"\n#include \"filter.hpp\"\n\n#include <utility>\n#include <iterator>\n\nnamespace iter {\n namespace impl {\n template <typename FilterFunc, typename Container>\n class Dropper;\n\n using DropWhileFn = IterToolFnOptionalBindFirst<Dropper, BoolTester>;\n }\n constexpr impl::DropWhileFn dropwhile{};\n}\n\ntemplate <typename FilterFunc, typename Container>\nclass iter::impl::Dropper {\n private:\n Container container;\n FilterFunc filter_func;\n\n friend DropWhileFn;\n\n Dropper(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward<Container>(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n Dropper(Dropper&&) = default;\n class Iterator : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>> {\n private:\n using Holder = DerefHolder<iterator_deref<Container>>;\n IteratorWrapper<Container> sub_iter;\n IteratorWrapper<Container> sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() {\n while (this->sub_iter != this->sub_end\n && (*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(IteratorWrapper<Container>&& iter, IteratorWrapper<Container>&& end,\n FilterFunc& in_filter_func)\n : sub_iter{std::move(iter)},\n sub_end{std::move(end)},\n filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_passes();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef DROPWHILE__H__\n#define DROPWHILE__H__\n\n#include <iterbase.hpp>\n\n#include <utility>\n\nnamespace iter {\n\n \/\/Forward declarations of DropWhile and dropwhile\n template <typename FilterFunc, typename Container>\n class DropWhile;\n\n template <typename FilterFunc, typename Container>\n DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container &);\n\n template <typename FilterFunc, typename Container>\n class DropWhile : IterBase<Container> {\n private:\n Container & container;\n FilterFunc filter_func;\n\n friend DropWhile dropwhile<FilterFunc, Container>(\n FilterFunc, Container &);\n\n using typename IterBase<Container>::contained_iter_type;\n\n using typename IterBase<Container>::contained_iter_ret;\n\n \n \/\/ Value constructor for use only in the dropwhile function\n DropWhile(FilterFunc filter_func, Container & container) :\n container(container),\n filter_func(filter_func)\n { }\n DropWhile () = delete;\n DropWhile & operator=(const DropWhile &) = delete;\n\n public:\n DropWhile(const DropWhile &) = default;\n class Iterator {\n private:\n contained_iter_type sub_iter;\n const contained_iter_type sub_end;\n FilterFunc filter_func;\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() { \n while (this->sub_iter != this->sub_end\n && this->filter_func(*this->sub_iter)) {\n ++this->sub_iter;\n }\n }\n\n public:\n Iterator (contained_iter_type iter,\n contained_iter_type end,\n FilterFunc filter_func) :\n sub_iter(iter),\n sub_end(end),\n filter_func(filter_func)\n { \n this->skip_passes();\n } \n\n contained_iter_ret operator*() const {\n return *this->sub_iter;\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n return *this;\n }\n\n bool operator!=(const Iterator & other) const {\n return this->sub_iter != other.sub_iter;\n }\n };\n\n Iterator begin() const {\n return Iterator(\n std::begin(this->container),\n std::end(this->container),\n this->filter_func);\n }\n\n Iterator end() const {\n return Iterator(\n std::end(this->container),\n std::end(this->container),\n this->filter_func);\n }\n\n };\n\n \/\/ Helper function to instantiate a DropWhile\n template <typename FilterFunc, typename Container>\n DropWhile<FilterFunc, Container> dropwhile(\n FilterFunc filter_func, Container & container) {\n return DropWhile<FilterFunc, Container>(filter_func, container);\n }\n\n}\n\n#endif \/\/ifndef DROPWHILE__H__\n<commit_msg>Tweaks #includes<commit_after>#ifndef DROPWHILE__H__\n#define DROPWHILE__H__\n\n#include <iterbase.hpp>\n\n#include <utility>\n#include <iterator>\n\nnamespace iter {\n\n \/\/Forward declarations of DropWhile and dropwhile\n template <typename FilterFunc, typename Container>\n class DropWhile;\n\n template <typename FilterFunc, typename Container>\n DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container &);\n\n template <typename FilterFunc, typename Container>\n class DropWhile : IterBase<Container> {\n private:\n Container & container;\n FilterFunc filter_func;\n\n friend DropWhile dropwhile<FilterFunc, Container>(\n FilterFunc, Container &);\n\n using typename IterBase<Container>::contained_iter_type;\n\n using typename IterBase<Container>::contained_iter_ret;\n\n \n \/\/ Value constructor for use only in the dropwhile function\n DropWhile(FilterFunc filter_func, Container & container) :\n container(container),\n filter_func(filter_func)\n { }\n DropWhile () = delete;\n DropWhile & operator=(const DropWhile &) = delete;\n\n public:\n DropWhile(const DropWhile &) = default;\n class Iterator {\n private:\n contained_iter_type sub_iter;\n const contained_iter_type sub_end;\n FilterFunc filter_func;\n\n \/\/ skip all values for which the predicate is true\n void skip_passes() { \n while (this->sub_iter != this->sub_end\n && this->filter_func(*this->sub_iter)) {\n ++this->sub_iter;\n }\n }\n\n public:\n Iterator (contained_iter_type iter,\n contained_iter_type end,\n FilterFunc filter_func) :\n sub_iter(iter),\n sub_end(end),\n filter_func(filter_func)\n { \n this->skip_passes();\n } \n\n contained_iter_ret operator*() const {\n return *this->sub_iter;\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n return *this;\n }\n\n bool operator!=(const Iterator & other) const {\n return this->sub_iter != other.sub_iter;\n }\n };\n\n Iterator begin() const {\n return Iterator(\n std::begin(this->container),\n std::end(this->container),\n this->filter_func);\n }\n\n Iterator end() const {\n return Iterator(\n std::end(this->container),\n std::end(this->container),\n this->filter_func);\n }\n\n };\n\n \/\/ Helper function to instantiate a DropWhile\n template <typename FilterFunc, typename Container>\n DropWhile<FilterFunc, Container> dropwhile(\n FilterFunc filter_func, Container & container) {\n return DropWhile<FilterFunc, Container>(filter_func, container);\n }\n\n}\n\n#endif \/\/ifndef DROPWHILE__H__\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2011-2015 Jeff Bush\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include <iostream>\n#include <stdlib.h>\n#include \"Vsoc_tb.h\"\n#include \"verilated.h\"\n#include \"verilated_vpi.h\"\n#if VM_TRACE\n#include <verilated_vcd_c.h>\n#endif\nusing namespace std;\n\n\/\/\n\/\/ This is compiled into the verilog simulator executable along with the\n\/\/ source files generated by Verilator. It initializes and runs the simulation\n\/\/ loop for the full processor.\n\/\/\n\nnamespace\n{\nvluint64_t currentTime = 0;\n}\n\n\/\/ Called whenever the $time variable is accessed.\ndouble sc_time_stamp()\n{\n return currentTime;\n}\n\nint main(int argc, char **argv, char **env)\n{\n Verilated::commandArgs(argc, argv);\n Verilated::debug(0);\n\n \/\/ Default to randomizing contents of memory before the start of\n \/\/ simulation. This flag can disable it.\n const char *arg = Verilated::commandArgsPlusMatch(\"randomize=\");\n if (arg[0] == '\\0' || atoi(arg + 11) != 0)\n {\n \/\/ Initialize random seed.\n long randomSeed;\n arg = Verilated::commandArgsPlusMatch(\"randseed=\");\n if (arg[0] != '\\0')\n randomSeed = atol(arg + 10);\n else\n {\n time_t t1;\n time(&t1);\n randomSeed = (long) t1;\n }\n\n srand48(randomSeed);\n VL_PRINTF(\"Random seed is %li\\n\", randomSeed);\n Verilated::randReset(2);\n }\n else\n Verilated::randReset(0);\n\n Vsoc_tb* testbench = new Vsoc_tb;\n\n \/\/ As with real hardware, reset is a bit tricky.\n \/\/ - Most assertions will fail before the design has been reset.\n \/\/ - Assertions are not tested while reset is asserted.\n \/\/ BUT:\n \/\/ - Many blocks require a positive edge on reset to trigger\n \/\/ (not all, any block that also triggers on clock will synchronously\n \/\/ reset if it is asserted).\n \/\/\n \/\/ This is a bit of a hack, set the 'last' state of reset to zero and reset to one.\n \/\/ This will cause a positive edge event on the next eval() that will trigger\n \/\/ all reset blocks. Reset will be deasserted in the main loop below.\n \/\/\n testbench->__Vclklast__TOP__reset = 0;\n testbench->reset = 1;\n testbench->clk = 0;\n testbench->eval();\n\n#if VM_TRACE \/\/ If verilator was invoked with --trace\n Verilated::traceEverOn(true);\n VL_PRINTF(\"Writing waveform to trace.vcd\\n\");\n VerilatedVcdC* tfp = new VerilatedVcdC;\n testbench->trace(tfp, 99);\n tfp->open(\"trace.vcd\");\n#endif\n\n while (!Verilated::gotFinish())\n {\n \/\/ Allow it to run for a few clock cycles with reset asserted. This allows\n \/\/ flops that are not reset to settle on valid values so assertions don't trip.\n if (currentTime == 4)\n testbench->reset = 0;\n\n testbench->clk = !testbench->clk;\n testbench->eval();\n#if VM_TRACE\n tfp->dump(currentTime); \/\/ Create waveform trace for this timestamp\n#endif\n\n currentTime++;\n }\n\n#if VM_TRACE\n tfp->close();\n#endif\n\n testbench->final();\n delete testbench;\n\n return 0;\n}\n<commit_msg>A few minor Verilator main loop changes<commit_after>\/\/\n\/\/ Copyright 2011-2015 Jeff Bush\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include <iostream>\n#include <cstdlib>\n#include \"Vsoc_tb.h\"\n#include \"verilated.h\"\n#include \"verilated_vpi.h\"\n#if VM_TRACE\n#include <verilated_vcd_c.h>\n#endif\n\n\/\/\n\/\/ This is compiled into the verilog simulator executable along with the\n\/\/ source files generated by Verilator. It initializes and runs the simulation\n\/\/ loop for the full processor.\n\/\/\n\nnamespace\n{\nvluint64_t currentTime = 0;\n}\n\n\/\/ Called whenever the $time variable is accessed.\ndouble sc_time_stamp()\n{\n return currentTime;\n}\n\nint main(int argc, char **argv, char **env)\n{\n Verilated::commandArgs(argc, argv);\n Verilated::debug(0);\n\n \/\/ Default to randomizing contents of memory before the start of\n \/\/ simulation. This flag can disable it.\n const char *arg = Verilated::commandArgsPlusMatch(\"randomize=\");\n if (arg[0] == '\\0' || atoi(arg + 11) != 0)\n {\n \/\/ Initialize random seed.\n long randomSeed;\n arg = Verilated::commandArgsPlusMatch(\"randseed=\");\n if (arg[0] != '\\0')\n randomSeed = atol(arg + 10);\n else\n {\n time_t t1;\n time(&t1);\n randomSeed = (long) t1;\n }\n\n srand48(randomSeed);\n VL_PRINTF(\"Random seed is %li\\n\", randomSeed);\n Verilated::randReset(2);\n }\n else\n Verilated::randReset(0);\n\n Vsoc_tb* testbench = new Vsoc_tb;\n\n \/\/ As with real hardware, reset is a bit tricky.\n \/\/ - Most assertions will fail before the design has been reset.\n \/\/ - Assertions are not tested while reset is asserted.\n \/\/ BUT:\n \/\/ - Many blocks require a positive edge on reset to trigger\n \/\/ (not all, any block that also triggers on clock will synchronously\n \/\/ reset if it is asserted).\n \/\/\n \/\/ This is a bit of a hack, set the 'last' state of reset to zero and reset to one.\n \/\/ This will cause a positive edge event on the next eval() that will trigger\n \/\/ all reset blocks. Reset will be deasserted in the main loop below.\n testbench->__Vclklast__TOP__reset = 0;\n testbench->reset = 1;\n testbench->clk = 0;\n testbench->eval();\n\n#if VM_TRACE \/\/ If verilator was invoked with --trace\n Verilated::traceEverOn(true);\n VL_PRINTF(\"Writing waveform to trace.vcd\\n\");\n VerilatedVcdC* tfp = new VerilatedVcdC;\n testbench->trace(tfp, 99);\n tfp->open(\"trace.vcd\");\n#endif\n\n while (!Verilated::gotFinish())\n {\n \/\/ Run for a few clock cycles with reset asserted. This allows flops\n \/\/ that are not reset to settle on valid values so assertions don't\n \/\/ trip.\n if (currentTime == 4)\n testbench->reset = 0;\n\n testbench->clk = !testbench->clk;\n testbench->eval();\n#if VM_TRACE\n tfp->dump(currentTime); \/\/ Create waveform trace for this timestamp\n#endif\n\n currentTime++;\n }\n\n testbench->final();\n\n#if VM_TRACE\n tfp->close();\n#endif\n\n delete testbench;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: verbosetrace.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: thb $ $Date: 2004-03-18 10:38:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CANVAS_VERBOSETRACE_HXX\n#define _CANVAS_VERBOSETRACE_HXX\n\n#ifdef VERBOSE\n\/\/\/ Wrap OSL_TRACE with a verbosity switch\n#define VERBOSE_TRACE OSL_TRACE\n#else\n#define VERBOSE_TRACE 1 ? ((void)0) : OSL_TRACE\n#endif\n\n#endif \/* _CANVAS_VERBOSETRACE_HXX *\/\n<commit_msg>INTEGRATION: CWS presentationengine01 (1.2.2); FILE MERGED 2004\/05\/27 14:36:52 thb 1.2.2.2: #110496# verbose tracing is now guarded also with DBG_UTIL. Unified verbose trace output between directx and VCL canvas 2004\/04\/05 15:57:53 thb 1.2.2.1: Resync with canvas01 changes<commit_after>\/*************************************************************************\n *\n * $RCSfile: verbosetrace.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 17:03:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CANVAS_VERBOSETRACE_HXX\n#define _CANVAS_VERBOSETRACE_HXX\n\n#if defined(VERBOSE) && defined(DBG_UTIL)\n\/\/\/ Wrap OSL_TRACE with a verbosity switch\n#define VERBOSE_TRACE OSL_TRACE\n#else\n#define VERBOSE_TRACE 1 ? ((void)0) : OSL_TRACE\n#endif\n\n#endif \/* _CANVAS_VERBOSETRACE_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,\n\n#include <mapnik\/style.hpp>\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/projection.hpp>\n#include <mapnik\/layer.hpp>\n#include <mapnik\/filter_featureset.hpp>\n#include <mapnik\/hit_test_filter.hpp>\n#include <mapnik\/map.hpp>\n\nnamespace mapnik\n{\n Map::Map()\n : width_(400),\n height_(400),\n srs_(\"+proj=latlong +datum=WGS84\") {}\n \n Map::Map(int width,int height, std::string const& srs)\n : width_(width),\n height_(height),\n srs_(srs),\n background_(Color(255,255,255)) {}\n\n Map::Map(const Map& rhs)\n : width_(rhs.width_),\n height_(rhs.height_),\n srs_(rhs.srs_),\n background_(rhs.background_),\n styles_(rhs.styles_),\n layers_(rhs.layers_),\n currentExtent_(rhs.currentExtent_) {}\n \n Map& Map::operator=(const Map& rhs)\n {\n if (this==&rhs) return *this;\n width_=rhs.width_;\n height_=rhs.height_;\n srs_=rhs.srs_;\n background_=rhs.background_;\n styles_=rhs.styles_;\n layers_=rhs.layers_;\n return *this;\n }\n \n Map::style_iterator Map::begin_styles() const\n {\n return styles_.begin();\n }\n Map::style_iterator Map::end_styles() const\n {\n return styles_.end();\n }\n \n bool Map::insert_style(std::string const& name,feature_type_style const& style) \n {\n return styles_.insert(make_pair(name,style)).second;\n }\n \n void Map::remove_style(std::string const& name) \n {\n styles_.erase(name);\n }\n \n feature_type_style const& Map::find_style(std::string const& name) const\n {\n std::map<std::string,feature_type_style>::const_iterator itr = styles_.find(name);\n if (itr!=styles_.end()) \n return itr->second;\n static feature_type_style default_style;\n return default_style;\n }\n \n size_t Map::layerCount() const\n {\n return layers_.size();\n }\n \n void Map::addLayer(const Layer& l)\n {\n layers_.push_back(l);\n }\n void Map::removeLayer(size_t index)\n {\n layers_.erase(layers_.begin()+index);\n }\n \n void Map::remove_all() \n {\n layers_.clear();\n styles_.clear();\n }\n \n const Layer& Map::getLayer(size_t index) const\n {\n return layers_[index];\n }\n\n Layer& Map::getLayer(size_t index)\n {\n return layers_[index];\n }\n\n std::vector<Layer> const& Map::layers() const\n {\n return layers_;\n }\n\n std::vector<Layer> & Map::layers()\n {\n return layers_;\n }\n\n unsigned Map::getWidth() const\n {\n return width_;\n }\n\n unsigned Map::getHeight() const\n {\n return height_;\n }\n \n void Map::setWidth(unsigned width)\n {\n if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)\n {\n width_=width;\n fixAspectRatio();\n }\t\n }\n\n void Map::setHeight(unsigned height)\n {\n if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)\n {\n height_=height;\n fixAspectRatio();\n }\n }\n \n void Map::resize(unsigned width,unsigned height)\n {\n if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&\n height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)\n {\n width_=width;\n height_=height;\n fixAspectRatio();\n }\n }\n\n std::string const& Map::srs() const\n {\n return srs_;\n }\n \n void Map::set_srs(std::string const& srs)\n {\n srs_ = srs;\n }\n \n void Map::setBackground(const Color& c)\n {\n background_=c;\n }\n\n const Color& Map::getBackground() const\n {\n return background_;\n }\n \n void Map::zoom(double factor)\n {\n coord2d center = currentExtent_.center();\n double w = factor * currentExtent_.width();\n double h = factor * currentExtent_.height();\n currentExtent_ = Envelope<double>(center.x - 0.5 * w, \n center.y - 0.5 * h,\n center.x + 0.5 * w, \n center.y + 0.5 * h);\n fixAspectRatio();\n }\n \n void Map::zoom_all() \n {\n try \n {\n projection proj0(srs_);\n Envelope<double> ext;\n bool first = true;\n std::vector<Layer>::const_iterator itr = layers_.begin();\n std::vector<Layer>::const_iterator end = layers_.end();\n while (itr != end)\n {\n std::string const& layer_srs = itr->srs();\n projection proj1(layer_srs);\n proj_transform prj_trans(proj0,proj1);\n \n Envelope<double> layerExt = itr->envelope();\n double x0 = layerExt.minx();\n double y0 = layerExt.miny();\n double z0 = 0.0;\n double x1 = layerExt.maxx();\n double y1 = layerExt.maxy();\n double z1 = 0.0;\n prj_trans.backward(x0,y0,z0);\n prj_trans.backward(x1,y1,z1);\n \n Envelope<double> layerExt2(x0,y0,x1,y1);\n#ifdef MAPNIK_DEBUG\n std::clog << \" layer1 - > \" << layerExt << \"\\n\";\n std::clog << \" layer2 - > \" << layerExt2 << \"\\n\";\n#endif \n if (first)\n {\n ext = layerExt2;\n first = false;\n }\n else \n {\n ext.expand_to_include(layerExt2);\n }\n ++itr;\n }\n zoomToBox(ext);\n }\n catch (proj_init_error & ex)\n {\n std::clog << ex.what() << '\\n';\n }\n }\n\n void Map::zoomToBox(const Envelope<double> &box)\n {\n currentExtent_=box;\n fixAspectRatio();\n }\n\n void Map::fixAspectRatio()\n {\n double ratio1 = (double) width_ \/ (double) height_;\n double ratio2 = currentExtent_.width() \/ currentExtent_.height();\n \n if (ratio2 > ratio1)\n {\n currentExtent_.height(currentExtent_.width() \/ ratio1);\n }\n else if (ratio2 < ratio1)\n {\n currentExtent_.width(currentExtent_.height() * ratio1);\n } \n }\n\n const Envelope<double>& Map::getCurrentExtent() const\n {\n return currentExtent_;\n }\n\n void Map::pan(int x,int y)\n {\n int dx = x - int(0.5 * width_);\n int dy = int(0.5 * height_) - y;\n double s = width_\/currentExtent_.width();\n double minx = currentExtent_.minx() + dx\/s;\n double maxx = currentExtent_.maxx() + dx\/s;\n double miny = currentExtent_.miny() + dy\/s;\n double maxy = currentExtent_.maxy() + dy\/s;\n currentExtent_.init(minx,miny,maxx,maxy);\n }\n\n void Map::pan_and_zoom(int x,int y,double factor)\n {\n pan(x,y);\n zoom(factor);\n }\n\n double Map::scale() const\n {\n if (width_>0)\n return currentExtent_.width()\/width_;\n return currentExtent_.width();\n }\n\n CoordTransform Map::view_transform() const\n {\n return CoordTransform(width_,height_,currentExtent_);\n }\n \n featureset_ptr Map::query_point(unsigned index, double lat, double lon) const\n {\n if ( index< layers_.size())\n {\n mapnik::Layer const& layer = layers_[index]; \n try\n {\n double x = lon;\n double y = lat;\n double z = 0;\n mapnik::projection dest(srs_); \n dest.forward(x,y);\n mapnik::projection source(layer.srs());\n proj_transform prj_trans(source,dest);\n prj_trans.backward(x,y,z);\n \n double minx = currentExtent_.minx();\n double miny = currentExtent_.miny();\n double maxx = currentExtent_.maxx();\n double maxy = currentExtent_.maxy();\n \n prj_trans.backward(minx,miny,z);\n prj_trans.backward(maxx,maxy,z);\n double tol = (maxx - minx) \/ width_ * 3;\n mapnik::datasource_ptr ds = layer.datasource();\n if (ds)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \" query at point tol = \" << tol << \" (\" << x << \",\" << y << \")\\n\";\n#endif \n featureset_ptr fs(new filter_featureset<hit_test_filter>(ds->features_at_point(mapnik::coord2d(x,y)),\n hit_test_filter(x,y,tol)));\n return fs;\n }\n }\n catch (...)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"exception caught in \\\"query_map_point\\\"\\n\";\n#endif\n }\n }\n return featureset_ptr();\n }\n \n featureset_ptr Map::query_map_point(unsigned index, double x, double y) const\n {\n if ( index< layers_.size())\n {\n mapnik::Layer const& layer = layers_[index];\n CoordTransform tr = view_transform();\n tr.backward(&x,&y);\n \n try\n {\n mapnik::projection dest(srs_);\n mapnik::projection source(layer.srs());\n proj_transform prj_trans(source,dest);\n double z = 0;\n prj_trans.backward(x,y,z);\n \n double minx = currentExtent_.minx();\n double miny = currentExtent_.miny();\n double maxx = currentExtent_.maxx();\n double maxy = currentExtent_.maxy();\n \n prj_trans.backward(minx,miny,z);\n prj_trans.backward(maxx,maxy,z);\n double tol = (maxx - minx) \/ width_ * 3;\n mapnik::datasource_ptr ds = layer.datasource();\n if (ds)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \" query at point tol = \" << tol << \" (\" << x << \",\" << y << \")\\n\";\n#endif\n \n featureset_ptr fs(new filter_featureset<hit_test_filter>(ds->features_at_point(mapnik::coord2d(x,y)),\n hit_test_filter(x,y,tol)));\n return fs;\n }\n }\n catch (...)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"exception caught in \\\"query_map_point\\\"\\n\";\n#endif\n }\n }\n return featureset_ptr();\n }\n\n Map::~Map() {}\n}\n<commit_msg>check if featureset is valid before passing to filter_featureset<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,\n\n#include <mapnik\/style.hpp>\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/projection.hpp>\n#include <mapnik\/layer.hpp>\n#include <mapnik\/filter_featureset.hpp>\n#include <mapnik\/hit_test_filter.hpp>\n#include <mapnik\/map.hpp>\n\nnamespace mapnik\n{\n Map::Map()\n : width_(400),\n height_(400),\n srs_(\"+proj=latlong +datum=WGS84\") {}\n \n Map::Map(int width,int height, std::string const& srs)\n : width_(width),\n height_(height),\n srs_(srs),\n background_(Color(255,255,255)) {}\n\n Map::Map(const Map& rhs)\n : width_(rhs.width_),\n height_(rhs.height_),\n srs_(rhs.srs_),\n background_(rhs.background_),\n styles_(rhs.styles_),\n layers_(rhs.layers_),\n currentExtent_(rhs.currentExtent_) {}\n \n Map& Map::operator=(const Map& rhs)\n {\n if (this==&rhs) return *this;\n width_=rhs.width_;\n height_=rhs.height_;\n srs_=rhs.srs_;\n background_=rhs.background_;\n styles_=rhs.styles_;\n layers_=rhs.layers_;\n return *this;\n }\n \n Map::style_iterator Map::begin_styles() const\n {\n return styles_.begin();\n }\n Map::style_iterator Map::end_styles() const\n {\n return styles_.end();\n }\n \n bool Map::insert_style(std::string const& name,feature_type_style const& style) \n {\n return styles_.insert(make_pair(name,style)).second;\n }\n \n void Map::remove_style(std::string const& name) \n {\n styles_.erase(name);\n }\n \n feature_type_style const& Map::find_style(std::string const& name) const\n {\n std::map<std::string,feature_type_style>::const_iterator itr = styles_.find(name);\n if (itr!=styles_.end()) \n return itr->second;\n static feature_type_style default_style;\n return default_style;\n }\n \n size_t Map::layerCount() const\n {\n return layers_.size();\n }\n \n void Map::addLayer(const Layer& l)\n {\n layers_.push_back(l);\n }\n void Map::removeLayer(size_t index)\n {\n layers_.erase(layers_.begin()+index);\n }\n \n void Map::remove_all() \n {\n layers_.clear();\n styles_.clear();\n }\n \n const Layer& Map::getLayer(size_t index) const\n {\n return layers_[index];\n }\n\n Layer& Map::getLayer(size_t index)\n {\n return layers_[index];\n }\n\n std::vector<Layer> const& Map::layers() const\n {\n return layers_;\n }\n\n std::vector<Layer> & Map::layers()\n {\n return layers_;\n }\n\n unsigned Map::getWidth() const\n {\n return width_;\n }\n\n unsigned Map::getHeight() const\n {\n return height_;\n }\n \n void Map::setWidth(unsigned width)\n {\n if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)\n {\n width_=width;\n fixAspectRatio();\n }\t\n }\n\n void Map::setHeight(unsigned height)\n {\n if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)\n {\n height_=height;\n fixAspectRatio();\n }\n }\n \n void Map::resize(unsigned width,unsigned height)\n {\n if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&\n height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)\n {\n width_=width;\n height_=height;\n fixAspectRatio();\n }\n }\n\n std::string const& Map::srs() const\n {\n return srs_;\n }\n \n void Map::set_srs(std::string const& srs)\n {\n srs_ = srs;\n }\n \n void Map::setBackground(const Color& c)\n {\n background_=c;\n }\n\n const Color& Map::getBackground() const\n {\n return background_;\n }\n \n void Map::zoom(double factor)\n {\n coord2d center = currentExtent_.center();\n double w = factor * currentExtent_.width();\n double h = factor * currentExtent_.height();\n currentExtent_ = Envelope<double>(center.x - 0.5 * w, \n center.y - 0.5 * h,\n center.x + 0.5 * w, \n center.y + 0.5 * h);\n fixAspectRatio();\n }\n \n void Map::zoom_all() \n {\n try \n {\n projection proj0(srs_);\n Envelope<double> ext;\n bool first = true;\n std::vector<Layer>::const_iterator itr = layers_.begin();\n std::vector<Layer>::const_iterator end = layers_.end();\n while (itr != end)\n {\n std::string const& layer_srs = itr->srs();\n projection proj1(layer_srs);\n proj_transform prj_trans(proj0,proj1);\n \n Envelope<double> layerExt = itr->envelope();\n double x0 = layerExt.minx();\n double y0 = layerExt.miny();\n double z0 = 0.0;\n double x1 = layerExt.maxx();\n double y1 = layerExt.maxy();\n double z1 = 0.0;\n prj_trans.backward(x0,y0,z0);\n prj_trans.backward(x1,y1,z1);\n \n Envelope<double> layerExt2(x0,y0,x1,y1);\n#ifdef MAPNIK_DEBUG\n std::clog << \" layer1 - > \" << layerExt << \"\\n\";\n std::clog << \" layer2 - > \" << layerExt2 << \"\\n\";\n#endif \n if (first)\n {\n ext = layerExt2;\n first = false;\n }\n else \n {\n ext.expand_to_include(layerExt2);\n }\n ++itr;\n }\n zoomToBox(ext);\n }\n catch (proj_init_error & ex)\n {\n std::clog << ex.what() << '\\n';\n }\n }\n\n void Map::zoomToBox(const Envelope<double> &box)\n {\n currentExtent_=box;\n fixAspectRatio();\n }\n\n void Map::fixAspectRatio()\n {\n double ratio1 = (double) width_ \/ (double) height_;\n double ratio2 = currentExtent_.width() \/ currentExtent_.height();\n \n if (ratio2 > ratio1)\n {\n currentExtent_.height(currentExtent_.width() \/ ratio1);\n }\n else if (ratio2 < ratio1)\n {\n currentExtent_.width(currentExtent_.height() * ratio1);\n } \n }\n\n const Envelope<double>& Map::getCurrentExtent() const\n {\n return currentExtent_;\n }\n\n void Map::pan(int x,int y)\n {\n int dx = x - int(0.5 * width_);\n int dy = int(0.5 * height_) - y;\n double s = width_\/currentExtent_.width();\n double minx = currentExtent_.minx() + dx\/s;\n double maxx = currentExtent_.maxx() + dx\/s;\n double miny = currentExtent_.miny() + dy\/s;\n double maxy = currentExtent_.maxy() + dy\/s;\n currentExtent_.init(minx,miny,maxx,maxy);\n }\n\n void Map::pan_and_zoom(int x,int y,double factor)\n {\n pan(x,y);\n zoom(factor);\n }\n\n double Map::scale() const\n {\n if (width_>0)\n return currentExtent_.width()\/width_;\n return currentExtent_.width();\n }\n\n CoordTransform Map::view_transform() const\n {\n return CoordTransform(width_,height_,currentExtent_);\n }\n \n featureset_ptr Map::query_point(unsigned index, double lat, double lon) const\n {\n if ( index< layers_.size())\n {\n mapnik::Layer const& layer = layers_[index]; \n try\n {\n double x = lon;\n double y = lat;\n double z = 0;\n mapnik::projection dest(srs_); \n dest.forward(x,y);\n mapnik::projection source(layer.srs());\n proj_transform prj_trans(source,dest);\n prj_trans.backward(x,y,z);\n \n double minx = currentExtent_.minx();\n double miny = currentExtent_.miny();\n double maxx = currentExtent_.maxx();\n double maxy = currentExtent_.maxy();\n \n prj_trans.backward(minx,miny,z);\n prj_trans.backward(maxx,maxy,z);\n double tol = (maxx - minx) \/ width_ * 3;\n mapnik::datasource_ptr ds = layer.datasource();\n if (ds)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \" query at point tol = \" << tol << \" (\" << x << \",\" << y << \")\\n\";\n#endif \n featureset_ptr fs = ds->features_at_point(mapnik::coord2d(x,y));\n if (fs) \n return featureset_ptr(new filter_featureset<hit_test_filter>(fs,hit_test_filter(x,y,tol)));\n }\n }\n catch (...)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"exception caught in \\\"query_map_point\\\"\\n\";\n#endif\n }\n }\n return featureset_ptr();\n }\n \n featureset_ptr Map::query_map_point(unsigned index, double x, double y) const\n {\n if ( index< layers_.size())\n {\n mapnik::Layer const& layer = layers_[index];\n CoordTransform tr = view_transform();\n tr.backward(&x,&y);\n \n try\n {\n mapnik::projection dest(srs_);\n mapnik::projection source(layer.srs());\n proj_transform prj_trans(source,dest);\n double z = 0;\n prj_trans.backward(x,y,z);\n \n double minx = currentExtent_.minx();\n double miny = currentExtent_.miny();\n double maxx = currentExtent_.maxx();\n double maxy = currentExtent_.maxy();\n \n prj_trans.backward(minx,miny,z);\n prj_trans.backward(maxx,maxy,z);\n double tol = (maxx - minx) \/ width_ * 3;\n mapnik::datasource_ptr ds = layer.datasource();\n if (ds)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \" query at point tol = \" << tol << \" (\" << x << \",\" << y << \")\\n\";\n#endif\n featureset_ptr fs = ds->features_at_point(mapnik::coord2d(x,y));\n if (fs) \n return featureset_ptr(new filter_featureset<hit_test_filter>(fs,hit_test_filter(x,y,tol)));\n }\n }\n catch (...)\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"exception caught in \\\"query_map_point\\\"\\n\";\n#endif\n }\n }\n return featureset_ptr();\n }\n\n Map::~Map() {}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"parser.h\"\n\n#include <ThreadWeaver\/ThreadWeaver>\n#include <KFormat>\n#include <KLocalizedString>\n\n#include <QTextStream>\n#include <QDebug>\n\n#include \"..\/accumulatedtracedata.h\"\n#include \"flamegraph.h\"\n\n#include <vector>\n\nusing namespace std;\n\nnamespace {\n\n\/\/ TODO: use QString directly\nstruct StringCache\n{\n StringCache()\n {\n m_ipAddresses.reserve(16384);\n }\n\n QString func(const InstructionPointer& ip) const\n {\n if (ip.functionIndex) {\n \/\/ TODO: support removal of template arguments\n return stringify(ip.functionIndex);\n } else {\n auto& ipAddr = m_ipAddresses[ip.instructionPointer];\n if (ipAddr.isEmpty()) {\n ipAddr = QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16);\n }\n return ipAddr;\n }\n }\n\n QString file(const InstructionPointer& ip) const\n {\n if (ip.fileIndex) {\n return stringify(ip.fileIndex);\n } else {\n return {};\n }\n }\n\n QString module(const InstructionPointer& ip) const\n {\n return stringify(ip.moduleIndex);\n }\n\n QString stringify(const StringIndex index) const\n {\n if (!index || index.index > m_strings.size()) {\n return {};\n } else {\n return m_strings.at(index.index - 1);\n }\n }\n\n LocationData location(const InstructionPointer& ip) const\n {\n return {func(ip), file(ip), module(ip), ip.line};\n }\n\n void update(const vector<string>& strings)\n {\n transform(strings.begin() + m_strings.size(), strings.end(),\n back_inserter(m_strings), [] (const string& str) { return QString::fromStdString(str); });\n }\n\n vector<QString> m_strings;\n mutable QHash<uint64_t, QString> m_ipAddresses;\n};\n\nstruct ChartMergeData\n{\n QString function;\n quint64 consumed;\n quint64 allocations;\n quint64 allocated;\n bool operator<(const QString& rhs) const\n {\n return function < rhs;\n }\n};\nstatic_assert(std::is_nothrow_move_assignable<ChartMergeData>::value, \"ChartMergeData must be nothrow move assignable for performance reasons\");\n\nstruct ParserData final : public AccumulatedTraceData\n{\n ParserData()\n {\n \/\/ start off with null data at the origin\n consumedChartData.data.rows.push_back({});\n allocatedChartData.data.rows.push_back({});\n allocationsChartData.data.rows.push_back({});\n \/\/ index 0 indicates the total row\n consumedChartData.labelIds.insert(i18n(\"total\"), 0);\n allocatedChartData.labelIds.insert(i18n(\"total\"), 0);\n allocationsChartData.labelIds.insert(i18n(\"total\"), 0);\n }\n\n void handleTimeStamp(uint64_t \/*oldStamp*\/, uint64_t newStamp)\n {\n stringCache.update(strings);\n maxConsumedSinceLastTimeStamp = max(maxConsumedSinceLastTimeStamp, leaked);\n\n \/\/ merge data for top 10 functions in this timestamp\n vector<ChartMergeData> mergedData;\n for (const auto& allocation : allocations) {\n const auto function = stringCache.func(findIp(findTrace(allocation.traceIndex).ipIndex));\n auto it = lower_bound(mergedData.begin(), mergedData.end(), function);\n if (it != mergedData.end() && it->function == function) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->consumed += allocation.leaked;\n } else {\n it = mergedData.insert(it, {function, allocation.leaked, allocation.allocations, allocation.allocated});\n }\n }\n\n auto addChartData = [&] (quint64 ChartMergeData::* member, ChartDataWithLabels* data, quint64 totalCost) {\n ChartRows row;\n row.timeStamp = newStamp;\n row.cost.insert(0, totalCost);\n sort(mergedData.begin(), mergedData.end(), [=] (const ChartMergeData& left, const ChartMergeData& right) {\n return left.*member > right.*member;\n });\n for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) {\n const auto& alloc = mergedData[i];\n if (!(alloc.*member)) {\n break;\n }\n auto& id = data->labelIds[alloc.function];\n if (!id) {\n id = data->labelIds.size() - 1;\n }\n row.cost.insert(id, alloc.*member);\n }\n data->data.rows.append(row);\n\n if (newStamp == totalTime) {\n \/\/ finalize and convert labels\n data->data.labels.reserve(data->labelIds.size());\n for (auto it = data->labelIds.constBegin(); it != data->labelIds.constEnd(); ++it) {\n data->data.labels.insert(it.value(), it.key());\n }\n }\n };\n addChartData(&ChartMergeData::consumed, &consumedChartData, maxConsumedSinceLastTimeStamp);\n addChartData(&ChartMergeData::allocated, &allocatedChartData, totalAllocated);\n addChartData(&ChartMergeData::allocations, &allocationsChartData, totalAllocations);\n maxConsumedSinceLastTimeStamp = 0;\n }\n\n void handleAllocation()\n {\n maxConsumedSinceLastTimeStamp = max(maxConsumedSinceLastTimeStamp, leaked);\n }\n\n void handleDebuggee(const char* command)\n {\n debuggee = command;\n }\n\n string debuggee;\n\n struct ChartDataWithLabels\n {\n ChartData data;\n QHash<QString, int> labelIds;\n };\n ChartDataWithLabels consumedChartData;\n ChartDataWithLabels allocationsChartData;\n ChartDataWithLabels allocatedChartData;\n uint64_t maxConsumedSinceLastTimeStamp = 0;\n\n StringCache stringCache;\n};\n\nQString generateSummary(const ParserData& data)\n{\n QString ret;\n KFormat format;\n QTextStream stream(&ret);\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"<qt>\"\n << i18n(\"<strong>debuggee<\/strong>: <code>%1<\/code>\", QString::fromStdString(data.debuggee)) << \"<br\/>\"\n \/\/ xgettext:no-c-format\n << i18n(\"<strong>total runtime<\/strong>: %1s\", totalTimeS) << \"<br\/>\"\n << i18n(\"<strong>bytes allocated in total<\/strong> (ignoring deallocations): %1 (%2\/s)\",\n format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated \/ totalTimeS)) << \"<br\/>\"\n << i18n(\"<strong>calls to allocation functions<\/strong>: %1 (%2\/s)\",\n data.totalAllocations, quint64(data.totalAllocations \/ totalTimeS)) << \"<br\/>\"\n << i18n(\"<strong>peak heap memory consumption<\/strong>: %1\", format.formatByteSize(data.peak)) << \"<br\/>\"\n << i18n(\"<strong>total memory leaked<\/strong>: %1\", format.formatByteSize(data.leaked)) << \"<br\/>\";\n stream << \"<\/qt>\";\n return ret;\n}\n\nvoid setParents(QVector<RowData>& children, const RowData* parent)\n{\n for (auto& row: children) {\n row.parent = parent;\n setParents(row.children, &row);\n }\n}\n\nQVector<RowData> mergeAllocations(const ParserData& data)\n{\n QVector<RowData> topRows;\n \/\/ merge allocations, leave parent pointers invalid (their location may change)\n for (const auto& allocation : data.allocations) {\n auto traceIndex = allocation.traceIndex;\n auto rows = &topRows;\n while (traceIndex) {\n const auto& trace = data.findTrace(traceIndex);\n const auto& ip = data.findIp(trace.ipIndex);\n \/\/ TODO: only store the IpIndex and use that\n auto location = data.stringCache.location(ip);\n auto it = lower_bound(rows->begin(), rows->end(), location);\n if (it != rows->end() && it->location == location) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->leaked += allocation.leaked;\n it->peak += allocation.peak;\n } else {\n it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,\n location, nullptr, {}});\n }\n if (data.isStopIndex(ip.functionIndex)) {\n break;\n }\n traceIndex = trace.parentIndex;\n rows = &it->children;\n }\n }\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n\nRowData* findByLocation(const RowData& row, QVector<RowData>* data)\n{\n for (int i = 0; i < data->size(); ++i) {\n if (data->at(i).location == row.location) {\n return data->data() + i;\n }\n }\n return nullptr;\n}\n\nvoid buildTopDown(const QVector<RowData>& bottomUpData, QVector<RowData>* topDownData)\n{\n foreach (const auto& row, bottomUpData) {\n if (row.children.isEmpty()) {\n \/\/ leaf node found, bubble up the parent chain to build a top-down tree\n auto node = &row;\n auto stack = topDownData;\n while (node) {\n auto data = findByLocation(*node, stack);\n if (!data) {\n \/\/ create an empty top-down item for this bottom-up node\n *stack << RowData{0, 0, 0, 0, node->location, nullptr, {}};\n data = &stack->back();\n }\n \/\/ always use the leaf node's cost and propagate that one up the chain\n \/\/ otherwise we'd count the cost of some nodes multiple times\n data->allocations += row.allocations;\n data->peak += row.peak;\n data->leaked += row.leaked;\n data->allocated += row.allocated;\n stack = &data->children;\n node = node->parent;\n }\n } else {\n \/\/ recurse to find a leaf\n buildTopDown(row.children, topDownData);\n }\n }\n}\n\nQVector<RowData> toTopDownData(const QVector<RowData>& bottomUpData)\n{\n QVector<RowData> topRows;\n buildTopDown(bottomUpData, &topRows);\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n\n}\n\nParser::Parser(QObject* parent)\n : QObject(parent)\n{}\n\nParser::~Parser() = default;\n\nvoid Parser::parse(const QString& path)\n{\n using namespace ThreadWeaver;\n stream() << make_job([=]() {\n ParserData data;\n data.read(path.toStdString());\n emit summaryAvailable(generateSummary(data));\n const auto mergedAllocations = mergeAllocations(data);\n emit bottomUpDataAvailable(mergedAllocations);\n emit consumedChartDataAvailable(data.consumedChartData.data);\n emit allocationsChartDataAvailable(data.allocationsChartData.data);\n emit allocatedChartDataAvailable(data.allocatedChartData.data);\n const auto topDownData = toTopDownData(mergedAllocations);\n emit topDownDataAvailable(topDownData);\n emit flameGraphDataAvailable(FlameGraph::parseData(topDownData));\n emit finished();\n });\n}\n<commit_msg>Only create one chart data per second.<commit_after>\/*\n * Copyright 2015 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"parser.h\"\n\n#include <ThreadWeaver\/ThreadWeaver>\n#include <KFormat>\n#include <KLocalizedString>\n\n#include <QTextStream>\n#include <QDebug>\n\n#include \"..\/accumulatedtracedata.h\"\n#include \"flamegraph.h\"\n\n#include <vector>\n\nusing namespace std;\n\nnamespace {\n\n\/\/ TODO: use QString directly\nstruct StringCache\n{\n StringCache()\n {\n m_ipAddresses.reserve(16384);\n }\n\n QString func(const InstructionPointer& ip) const\n {\n if (ip.functionIndex) {\n \/\/ TODO: support removal of template arguments\n return stringify(ip.functionIndex);\n } else {\n auto& ipAddr = m_ipAddresses[ip.instructionPointer];\n if (ipAddr.isEmpty()) {\n ipAddr = QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16);\n }\n return ipAddr;\n }\n }\n\n QString file(const InstructionPointer& ip) const\n {\n if (ip.fileIndex) {\n return stringify(ip.fileIndex);\n } else {\n return {};\n }\n }\n\n QString module(const InstructionPointer& ip) const\n {\n return stringify(ip.moduleIndex);\n }\n\n QString stringify(const StringIndex index) const\n {\n if (!index || index.index > m_strings.size()) {\n return {};\n } else {\n return m_strings.at(index.index - 1);\n }\n }\n\n LocationData location(const InstructionPointer& ip) const\n {\n return {func(ip), file(ip), module(ip), ip.line};\n }\n\n void update(const vector<string>& strings)\n {\n transform(strings.begin() + m_strings.size(), strings.end(),\n back_inserter(m_strings), [] (const string& str) { return QString::fromStdString(str); });\n }\n\n vector<QString> m_strings;\n mutable QHash<uint64_t, QString> m_ipAddresses;\n};\n\nstruct ChartMergeData\n{\n QString function;\n quint64 consumed;\n quint64 allocations;\n quint64 allocated;\n bool operator<(const QString& rhs) const\n {\n return function < rhs;\n }\n};\nstatic_assert(std::is_nothrow_move_assignable<ChartMergeData>::value, \"ChartMergeData must be nothrow move assignable for performance reasons\");\n\nstruct ParserData final : public AccumulatedTraceData\n{\n ParserData()\n {\n \/\/ start off with null data at the origin\n consumedChartData.data.rows.push_back({});\n allocatedChartData.data.rows.push_back({});\n allocationsChartData.data.rows.push_back({});\n \/\/ index 0 indicates the total row\n consumedChartData.labelIds.insert(i18n(\"total\"), 0);\n allocatedChartData.labelIds.insert(i18n(\"total\"), 0);\n allocationsChartData.labelIds.insert(i18n(\"total\"), 0);\n }\n\n void handleTimeStamp(uint64_t \/*oldStamp*\/, uint64_t newStamp)\n {\n maxConsumedSinceLastTimeStamp = max(maxConsumedSinceLastTimeStamp, leaked);\n \/\/ TODO: make this configurable via the GUI\n const uint64_t diffBetweenTimeStamps = 1000; \/\/ 1000ms = 1s\n if (newStamp != totalTime && newStamp - lastTimeStamp < diffBetweenTimeStamps) {\n return;\n }\n lastTimeStamp = newStamp;\n stringCache.update(strings);\n\n \/\/ merge data for top 10 functions in this timestamp\n vector<ChartMergeData> mergedData;\n for (const auto& allocation : allocations) {\n const auto function = stringCache.func(findIp(findTrace(allocation.traceIndex).ipIndex));\n auto it = lower_bound(mergedData.begin(), mergedData.end(), function);\n if (it != mergedData.end() && it->function == function) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->consumed += allocation.leaked;\n } else {\n it = mergedData.insert(it, {function, allocation.leaked, allocation.allocations, allocation.allocated});\n }\n }\n\n auto addChartData = [&] (quint64 ChartMergeData::* member, ChartDataWithLabels* data, quint64 totalCost) {\n ChartRows row;\n row.timeStamp = newStamp;\n row.cost.insert(0, totalCost);\n sort(mergedData.begin(), mergedData.end(), [=] (const ChartMergeData& left, const ChartMergeData& right) {\n return left.*member > right.*member;\n });\n for (size_t i = 0; i < min(size_t(10), mergedData.size()); ++i) {\n const auto& alloc = mergedData[i];\n if (!(alloc.*member)) {\n break;\n }\n auto& id = data->labelIds[alloc.function];\n if (!id) {\n id = data->labelIds.size() - 1;\n }\n row.cost.insert(id, alloc.*member);\n }\n data->data.rows.append(row);\n\n if (newStamp == totalTime) {\n \/\/ finalize and convert labels\n data->data.labels.reserve(data->labelIds.size());\n for (auto it = data->labelIds.constBegin(); it != data->labelIds.constEnd(); ++it) {\n data->data.labels.insert(it.value(), it.key());\n }\n }\n };\n addChartData(&ChartMergeData::consumed, &consumedChartData, maxConsumedSinceLastTimeStamp);\n addChartData(&ChartMergeData::allocated, &allocatedChartData, totalAllocated);\n addChartData(&ChartMergeData::allocations, &allocationsChartData, totalAllocations);\n maxConsumedSinceLastTimeStamp = 0;\n }\n\n void handleAllocation()\n {\n maxConsumedSinceLastTimeStamp = max(maxConsumedSinceLastTimeStamp, leaked);\n }\n\n void handleDebuggee(const char* command)\n {\n debuggee = command;\n }\n\n string debuggee;\n\n struct ChartDataWithLabels\n {\n ChartData data;\n QHash<QString, int> labelIds;\n };\n ChartDataWithLabels consumedChartData;\n ChartDataWithLabels allocationsChartData;\n ChartDataWithLabels allocatedChartData;\n uint64_t maxConsumedSinceLastTimeStamp = 0;\n uint64_t lastTimeStamp = 0;\n\n StringCache stringCache;\n};\n\nQString generateSummary(const ParserData& data)\n{\n QString ret;\n KFormat format;\n QTextStream stream(&ret);\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"<qt>\"\n << i18n(\"<strong>debuggee<\/strong>: <code>%1<\/code>\", QString::fromStdString(data.debuggee)) << \"<br\/>\"\n \/\/ xgettext:no-c-format\n << i18n(\"<strong>total runtime<\/strong>: %1s\", totalTimeS) << \"<br\/>\"\n << i18n(\"<strong>bytes allocated in total<\/strong> (ignoring deallocations): %1 (%2\/s)\",\n format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated \/ totalTimeS)) << \"<br\/>\"\n << i18n(\"<strong>calls to allocation functions<\/strong>: %1 (%2\/s)\",\n data.totalAllocations, quint64(data.totalAllocations \/ totalTimeS)) << \"<br\/>\"\n << i18n(\"<strong>peak heap memory consumption<\/strong>: %1\", format.formatByteSize(data.peak)) << \"<br\/>\"\n << i18n(\"<strong>total memory leaked<\/strong>: %1\", format.formatByteSize(data.leaked)) << \"<br\/>\";\n stream << \"<\/qt>\";\n return ret;\n}\n\nvoid setParents(QVector<RowData>& children, const RowData* parent)\n{\n for (auto& row: children) {\n row.parent = parent;\n setParents(row.children, &row);\n }\n}\n\nQVector<RowData> mergeAllocations(const ParserData& data)\n{\n QVector<RowData> topRows;\n \/\/ merge allocations, leave parent pointers invalid (their location may change)\n for (const auto& allocation : data.allocations) {\n auto traceIndex = allocation.traceIndex;\n auto rows = &topRows;\n while (traceIndex) {\n const auto& trace = data.findTrace(traceIndex);\n const auto& ip = data.findIp(trace.ipIndex);\n \/\/ TODO: only store the IpIndex and use that\n auto location = data.stringCache.location(ip);\n auto it = lower_bound(rows->begin(), rows->end(), location);\n if (it != rows->end() && it->location == location) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->leaked += allocation.leaked;\n it->peak += allocation.peak;\n } else {\n it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,\n location, nullptr, {}});\n }\n if (data.isStopIndex(ip.functionIndex)) {\n break;\n }\n traceIndex = trace.parentIndex;\n rows = &it->children;\n }\n }\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n\nRowData* findByLocation(const RowData& row, QVector<RowData>* data)\n{\n for (int i = 0; i < data->size(); ++i) {\n if (data->at(i).location == row.location) {\n return data->data() + i;\n }\n }\n return nullptr;\n}\n\nvoid buildTopDown(const QVector<RowData>& bottomUpData, QVector<RowData>* topDownData)\n{\n foreach (const auto& row, bottomUpData) {\n if (row.children.isEmpty()) {\n \/\/ leaf node found, bubble up the parent chain to build a top-down tree\n auto node = &row;\n auto stack = topDownData;\n while (node) {\n auto data = findByLocation(*node, stack);\n if (!data) {\n \/\/ create an empty top-down item for this bottom-up node\n *stack << RowData{0, 0, 0, 0, node->location, nullptr, {}};\n data = &stack->back();\n }\n \/\/ always use the leaf node's cost and propagate that one up the chain\n \/\/ otherwise we'd count the cost of some nodes multiple times\n data->allocations += row.allocations;\n data->peak += row.peak;\n data->leaked += row.leaked;\n data->allocated += row.allocated;\n stack = &data->children;\n node = node->parent;\n }\n } else {\n \/\/ recurse to find a leaf\n buildTopDown(row.children, topDownData);\n }\n }\n}\n\nQVector<RowData> toTopDownData(const QVector<RowData>& bottomUpData)\n{\n QVector<RowData> topRows;\n buildTopDown(bottomUpData, &topRows);\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n\n}\n\nParser::Parser(QObject* parent)\n : QObject(parent)\n{}\n\nParser::~Parser() = default;\n\nvoid Parser::parse(const QString& path)\n{\n using namespace ThreadWeaver;\n stream() << make_job([=]() {\n ParserData data;\n data.read(path.toStdString());\n emit summaryAvailable(generateSummary(data));\n const auto mergedAllocations = mergeAllocations(data);\n emit bottomUpDataAvailable(mergedAllocations);\n emit consumedChartDataAvailable(data.consumedChartData.data);\n emit allocationsChartDataAvailable(data.allocationsChartData.data);\n emit allocatedChartDataAvailable(data.allocatedChartData.data);\n const auto topDownData = toTopDownData(mergedAllocations);\n emit topDownDataAvailable(topDownData);\n emit flameGraphDataAvailable(FlameGraph::parseData(topDownData));\n emit finished();\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n#include \"axl_io_File.h\"\n#include \"axl_rtl_String.h\"\n\nnamespace axl {\nnamespace io {\n\n\/\/.............................................................................\n\n#if (_AXL_ENV == AXL_ENV_WIN)\n\nbool\nCFile::Open (\n\tconst char* pFileName,\n\tuint_t Flags\n\t)\n{\n\tuint_t AccessMode = (Flags & EFileFlag_ReadOnly) ?\n\t\tGENERIC_READ :\n\t\tGENERIC_READ | GENERIC_WRITE;\n\n\tuint_t ShareMode = (Flags & EFileFlag_Exclusive) ?\n\t\t0 :\n\t\t(Flags & EFileFlag_ShareWrite) ?\n\t\t\tFILE_SHARE_READ | FILE_SHARE_WRITE :\n\t\t\tFILE_SHARE_READ;\n\n\tuint_t CreationDisposition = (Flags & (EFileFlag_ReadOnly | EFileFlag_OpenExisting)) ?\n\t\tOPEN_EXISTING :\n\t\tOPEN_ALWAYS;\n\n\tuint_t FlagsAttributes = (Flags & EFileFlag_DeleteOnClose) ?\n\t\tFILE_FLAG_DELETE_ON_CLOSE :\n\t\t0;\n\n\tif (Flags & EFileFlag_Asynchronous)\n\t\tFlagsAttributes |= FILE_FLAG_OVERLAPPED;\n\n\tchar Buffer [256];\n\trtl::CString_w FileName (ref::EBuf_Stack, Buffer, sizeof (Buffer));\n\tFileName = pFileName;\n\n\treturn m_File.Create (\n\t\tFileName,\n\t\tAccessMode, \n\t\tShareMode, \n\t\tNULL, \n\t\tCreationDisposition, \n\t\tFlagsAttributes\n\t\t);\n}\n\n#elif (_AXL_ENV == AXL_ENV_POSIX)\n\nuint_t\nGetPosixOpenFlags (uint_t FileFlags)\n{\n\tuint_t PosixFlags = (FileFlags & EFileFlag_ReadOnly) ? O_RDONLY : O_RDWR;\n\n\tif (!(FileFlags & EFileFlag_OpenExisting))\n\t\tPosixFlags |= O_CREAT;\n\n\tif (FileFlags & EFileFlag_Asynchronous)\n\t\tPosixFlags |= O_NONBLOCK;\n\n\treturn PosixFlags;\n}\n\nbool\nCFile::Open (\n\tconst char* pFileName,\n\tuint_t Flags\n\t)\n{\n\tuint_t PosixFlags = GetPosixOpenFlags (Flags);\n\n\t\/\/ TODO: handle exclusive and share write flags with fcntl locks\n\n\tbool Result = m_File.Open (pFileName, PosixFlags);\n\tif (!Result)\n\t\treturn false;\n\n\tif (Flags & EFileFlag_DeleteOnClose)\n\t\tunlink (pFileName);\n\n\treturn true;\n}\n\n#endif\n\nsize_t\nCFile::WriteFormat_va (\n\tconst char* pFormat,\n\taxl_va_list va\n\t)\n{\n\tchar Buffer [256];\n\trtl::CString String (ref::EBuf_Stack, Buffer, sizeof (Buffer));\n\tString.Format_va (pFormat, va);\n\n\treturn Write (String, String.GetLength ());\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace io\n} \/\/ namespace axl\n<commit_msg>[axl.io] add FILE_SHARE_DELETE flag to file open flags -- important when using io::EFileFlag_DeleteOnClose<commit_after>#include \"pch.h\"\n#include \"axl_io_File.h\"\n#include \"axl_rtl_String.h\"\n\nnamespace axl {\nnamespace io {\n\n\/\/.............................................................................\n\n#if (_AXL_ENV == AXL_ENV_WIN)\n\nbool\nCFile::Open (\n\tconst char* pFileName,\n\tuint_t Flags\n\t)\n{\n\tuint_t AccessMode = (Flags & EFileFlag_ReadOnly) ?\n\t\tGENERIC_READ :\n\t\tGENERIC_READ | GENERIC_WRITE;\n\n\tuint_t ShareMode = (Flags & EFileFlag_Exclusive) ?\n\t\t0 :\n\t\t(Flags & EFileFlag_ShareWrite) ?\n\t\t\tFILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE :\n\t\t\tFILE_SHARE_READ | FILE_SHARE_DELETE;\n\n\tuint_t CreationDisposition = (Flags & (EFileFlag_ReadOnly | EFileFlag_OpenExisting)) ?\n\t\tOPEN_EXISTING :\n\t\tOPEN_ALWAYS;\n\n\tuint_t FlagsAttributes = (Flags & EFileFlag_DeleteOnClose) ?\n\t\tFILE_FLAG_DELETE_ON_CLOSE :\n\t\t0;\n\n\tif (Flags & EFileFlag_Asynchronous)\n\t\tFlagsAttributes |= FILE_FLAG_OVERLAPPED;\n\n\tchar Buffer [256];\n\trtl::CString_w FileName (ref::EBuf_Stack, Buffer, sizeof (Buffer));\n\tFileName = pFileName;\n\n\treturn m_File.Create (\n\t\tFileName,\n\t\tAccessMode, \n\t\tShareMode, \n\t\tNULL, \n\t\tCreationDisposition, \n\t\tFlagsAttributes\n\t\t);\n}\n\n#elif (_AXL_ENV == AXL_ENV_POSIX)\n\nuint_t\nGetPosixOpenFlags (uint_t FileFlags)\n{\n\tuint_t PosixFlags = (FileFlags & EFileFlag_ReadOnly) ? O_RDONLY : O_RDWR;\n\n\tif (!(FileFlags & EFileFlag_OpenExisting))\n\t\tPosixFlags |= O_CREAT;\n\n\tif (FileFlags & EFileFlag_Asynchronous)\n\t\tPosixFlags |= O_NONBLOCK;\n\n\treturn PosixFlags;\n}\n\nbool\nCFile::Open (\n\tconst char* pFileName,\n\tuint_t Flags\n\t)\n{\n\tuint_t PosixFlags = GetPosixOpenFlags (Flags);\n\n\t\/\/ TODO: handle exclusive and share write flags with fcntl locks\n\n\tbool Result = m_File.Open (pFileName, PosixFlags);\n\tif (!Result)\n\t\treturn false;\n\n\tif (Flags & EFileFlag_DeleteOnClose)\n\t\tunlink (pFileName);\n\n\treturn true;\n}\n\n#endif\n\nsize_t\nCFile::WriteFormat_va (\n\tconst char* pFormat,\n\taxl_va_list va\n\t)\n{\n\tchar Buffer [256];\n\trtl::CString String (ref::EBuf_Stack, Buffer, sizeof (Buffer));\n\tString.Format_va (pFormat, va);\n\n\treturn Write (String, String.GetLength ());\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace io\n} \/\/ namespace axl\n<|endoftext|>"} {"text":"<commit_before>\/\/ ModelRegistry.hxx -- interface to the OSG model registry\n\/\/\n\/\/ Copyright (C) 2005-2007 Mathias Froehlich \n\/\/ Copyright (C) 2007 Tim Moore <timoore@redhat.com>\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#ifndef _SG_MODELREGISTRY_HXX\n#define _SG_MODELREGISTRY_HXX 1\n\n#include <osg\/ref_ptr>\n#include <osg\/Node>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/ReaderWriter>\n#include <osgDB\/Registry>\n\n#include <simgear\/compiler.h>\n#include <simgear\/scene\/util\/OsgSingleton.hxx>\n\n#include <string>\n#include <map>\n\n\/\/ Class to register per file extension read callbacks with the OSG\n\/\/ registry, mostly to control caching and post load optimization \/\n\/\/ copying that happens above the level of the ReaderWriter.\nnamespace simgear\n{\n\n\/\/ Different caching and optimization strategies are needed for\n\/\/ different file types. Most loaded files should be optimized and the\n\/\/ optimized version should be cached. When an .osg file is\n\/\/ substituted for another, it is assumed to be optimized already but\n\/\/ it should be cached too (under the name of the original?). .stg\n\/\/ files should not be cached (that's the pager's job) but the files\n\/\/ it causes to be loaded should be. .btg files are already optimized\n\/\/ and shouldn't be cached.\n\/\/\n\/\/ Complicating this is the effect that removing CACHE_NODES has from\n\/\/ the ReaderWriter options: it switches the object cache with an\n\/\/ empty one, so that's not an option for the files that could be\n\/\/ loaded from a .stg file. So, we'll let\n\/\/ Registry::readNodeImplementation cache a loaded file and then add\n\/\/ the optimized version to the cache ourselves, replacing the\n\/\/ original subgraph.\n\/\/\n\/\/ To support all these options with a minimum of duplication, the\n\/\/ readNode function is specified as a template with a bunch of\n\/\/ pluggable (and predefined) policies.\ntemplate <typename ProcessPolicy, typename CachePolicy, typename OptimizePolicy,\n typename SubstitutePolicy, typename BVHPolicy>\nclass ModelRegistryCallback : public osgDB::Registry::ReadFileCallback {\npublic:\n ModelRegistryCallback(const std::string& extension) :\n _processPolicy(extension), _cachePolicy(extension),\n _optimizePolicy(extension),\n _substitutePolicy(extension), _bvhPolicy(extension)\n {\n }\n virtual osgDB::ReaderWriter::ReadResult\n readNode(const std::string& fileName,\n const osgDB::Options* opt)\n {\n using namespace osg;\n using namespace osgDB;\n using osgDB::ReaderWriter;\n\/\/ Registry* registry = Registry::instance();\n ref_ptr<osg::Node> optimizedNode = _cachePolicy.find(fileName, opt);\n if (!optimizedNode.valid()) {\n std::string otherFileName = _substitutePolicy.substitute(fileName,\n opt);\n ReaderWriter::ReadResult res;\n if (!otherFileName.empty()) {\n res = loadUsingReaderWriter(otherFileName, opt);\n if (res.validNode())\n optimizedNode = res.getNode();\n }\n if (!optimizedNode.valid()) {\n res = loadUsingReaderWriter(fileName, opt);\n if (!res.validNode())\n return res;\n ref_ptr<osg::Node> processedNode\n = _processPolicy.process(res.getNode(), fileName, opt);\n optimizedNode = _optimizePolicy.optimize(processedNode.get(),\n fileName, opt);\n }\n _bvhPolicy.buildBVH(fileName, optimizedNode.get());\n _cachePolicy.addToCache(fileName, optimizedNode.get());\n }\n return ReaderWriter::ReadResult(optimizedNode.get());\n }\nprotected:\n static osgDB::ReaderWriter::ReadResult\n loadUsingReaderWriter(const std::string& fileName,\n const osgDB::Options* opt)\n {\n using namespace osgDB;\n ReaderWriter* rw = Registry::instance()\n ->getReaderWriterForExtension(osgDB::getFileExtension(fileName));\n if (!rw)\n return ReaderWriter::ReadResult(); \/\/ FILE_NOT_HANDLED\n return rw->readNode(fileName, opt);\n }\n \n ProcessPolicy _processPolicy;\n CachePolicy _cachePolicy;\n OptimizePolicy _optimizePolicy;\n SubstitutePolicy _substitutePolicy;\n BVHPolicy _bvhPolicy;\n virtual ~ModelRegistryCallback() {}\n};\n\n\/\/ Predefined policies\n\nstruct DefaultProcessPolicy {\n DefaultProcessPolicy(const std::string& extension) {}\n osg::Node* process(osg::Node* node, const std::string& filename,\n const osgDB::Options* opt);\n};\n\nstruct DefaultCachePolicy {\n DefaultCachePolicy(const std::string& extension) {}\n osg::Node* find(const std::string& fileName,\n const osgDB::Options* opt);\n void addToCache(const std::string& filename, osg::Node* node);\n};\n\nstruct NoCachePolicy {\n NoCachePolicy(const std::string& extension) {}\n osg::Node* find(const std::string& fileName,\n const osgDB::Options* opt)\n {\n return 0;\n }\n void addToCache(const std::string& filename, osg::Node* node) {}\n};\n\nclass OptimizeModelPolicy {\npublic:\n OptimizeModelPolicy(const std::string& extension);\n osg::Node* optimize(osg::Node* node, const std::string& fileName,\n const osgDB::Options* opt);\nprotected:\n unsigned _osgOptions;\n};\n\nstruct NoOptimizePolicy {\n NoOptimizePolicy(const std::string& extension) {}\n osg::Node* optimize(osg::Node* node, const std::string& fileName,\n const osgDB::Options* opt)\n {\n return node;\n }\n};\n\nstruct OSGSubstitutePolicy {\n OSGSubstitutePolicy(const std::string& extension) {}\n std::string substitute(const std::string& name,\n const osgDB::Options* opt);\n};\n\nstruct NoSubstitutePolicy {\n NoSubstitutePolicy(const std::string& extension) {}\n std::string substitute(const std::string& name,\n const osgDB::Options* opt)\n {\n return std::string();\n }\n};\n\nstruct BuildLeafBVHPolicy {\n BuildLeafBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\nstruct BuildGroupBVHPolicy {\n BuildGroupBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\nstruct NoBuildBVHPolicy {\n NoBuildBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\ntypedef ModelRegistryCallback<DefaultProcessPolicy, DefaultCachePolicy,\n OptimizeModelPolicy,\n OSGSubstitutePolicy, BuildLeafBVHPolicy>\nDefaultCallback;\n\n\/\/ The manager for the callbacks\nclass ModelRegistry : public osgDB::Registry::ReadFileCallback,\n public ReferencedSingleton<ModelRegistry> {\npublic:\n ModelRegistry();\n virtual osgDB::ReaderWriter::ReadResult\n readImage(const std::string& fileName,\n const osgDB::Options* opt);\n virtual osgDB::ReaderWriter::ReadResult\n readNode(const std::string& fileName,\n const osgDB::Options* opt);\n void addImageCallbackForExtension(const std::string& extension,\n osgDB::Registry::ReadFileCallback*\n callback);\n void addNodeCallbackForExtension(const std::string& extension,\n osgDB::Registry::ReadFileCallback*\n callback);\n virtual ~ModelRegistry() {}\nprotected:\n typedef std::map<std::string, osg::ref_ptr<osgDB::Registry::ReadFileCallback> >\n CallbackMap;\n CallbackMap imageCallbackMap;\n CallbackMap nodeCallbackMap;\n osg::ref_ptr<DefaultCallback> _defaultCallback;\n};\n\n\/\/ Callback that only loads the file without any caching or\n\/\/ postprocessing.\ntypedef ModelRegistryCallback<DefaultProcessPolicy, NoCachePolicy,\n NoOptimizePolicy,\n NoSubstitutePolicy, BuildLeafBVHPolicy>\nLoadOnlyCallback;\n\n\/\/ Proxy for registering extension-based callbacks\n\ntemplate<typename T>\nclass ModelRegistryCallbackProxy\n{\npublic:\n ModelRegistryCallbackProxy(std::string extension)\n {\n ModelRegistry::instance()\n ->addNodeCallbackForExtension(extension, new T(extension));\n }\n};\n}\n#endif \/\/ _SG_MODELREGISTRY_HXX\n<commit_msg>scenery: Allow switching off bvh generation.<commit_after>\/\/ ModelRegistry.hxx -- interface to the OSG model registry\n\/\/\n\/\/ Copyright (C) 2005-2007 Mathias Froehlich \n\/\/ Copyright (C) 2007 Tim Moore <timoore@redhat.com>\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#ifndef _SG_MODELREGISTRY_HXX\n#define _SG_MODELREGISTRY_HXX 1\n\n#include <osg\/ref_ptr>\n#include <osg\/Node>\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/ReaderWriter>\n#include <osgDB\/Registry>\n\n#include <simgear\/compiler.h>\n#include <simgear\/scene\/util\/OsgSingleton.hxx>\n\n#include <string>\n#include <map>\n\n\/\/ Class to register per file extension read callbacks with the OSG\n\/\/ registry, mostly to control caching and post load optimization \/\n\/\/ copying that happens above the level of the ReaderWriter.\nnamespace simgear\n{\n\n\/\/ Different caching and optimization strategies are needed for\n\/\/ different file types. Most loaded files should be optimized and the\n\/\/ optimized version should be cached. When an .osg file is\n\/\/ substituted for another, it is assumed to be optimized already but\n\/\/ it should be cached too (under the name of the original?). .stg\n\/\/ files should not be cached (that's the pager's job) but the files\n\/\/ it causes to be loaded should be. .btg files are already optimized\n\/\/ and shouldn't be cached.\n\/\/\n\/\/ Complicating this is the effect that removing CACHE_NODES has from\n\/\/ the ReaderWriter options: it switches the object cache with an\n\/\/ empty one, so that's not an option for the files that could be\n\/\/ loaded from a .stg file. So, we'll let\n\/\/ Registry::readNodeImplementation cache a loaded file and then add\n\/\/ the optimized version to the cache ourselves, replacing the\n\/\/ original subgraph.\n\/\/\n\/\/ To support all these options with a minimum of duplication, the\n\/\/ readNode function is specified as a template with a bunch of\n\/\/ pluggable (and predefined) policies.\ntemplate <typename ProcessPolicy, typename CachePolicy, typename OptimizePolicy,\n typename SubstitutePolicy, typename BVHPolicy>\nclass ModelRegistryCallback : public osgDB::Registry::ReadFileCallback {\npublic:\n ModelRegistryCallback(const std::string& extension) :\n _processPolicy(extension), _cachePolicy(extension),\n _optimizePolicy(extension),\n _substitutePolicy(extension), _bvhPolicy(extension)\n {\n }\n virtual osgDB::ReaderWriter::ReadResult\n readNode(const std::string& fileName,\n const osgDB::Options* opt)\n {\n using namespace osg;\n using namespace osgDB;\n using osgDB::ReaderWriter;\n\/\/ Registry* registry = Registry::instance();\n ref_ptr<osg::Node> optimizedNode = _cachePolicy.find(fileName, opt);\n if (!optimizedNode.valid()) {\n std::string otherFileName = _substitutePolicy.substitute(fileName,\n opt);\n ReaderWriter::ReadResult res;\n if (!otherFileName.empty()) {\n res = loadUsingReaderWriter(otherFileName, opt);\n if (res.validNode())\n optimizedNode = res.getNode();\n }\n if (!optimizedNode.valid()) {\n res = loadUsingReaderWriter(fileName, opt);\n if (!res.validNode())\n return res;\n ref_ptr<osg::Node> processedNode\n = _processPolicy.process(res.getNode(), fileName, opt);\n optimizedNode = _optimizePolicy.optimize(processedNode.get(),\n fileName, opt);\n }\n if (opt->getPluginStringData(\"SimGear::BOUNDINGVOLUMES\") != \"OFF\")\n _bvhPolicy.buildBVH(fileName, optimizedNode.get());\n _cachePolicy.addToCache(fileName, optimizedNode.get());\n }\n return ReaderWriter::ReadResult(optimizedNode.get());\n }\nprotected:\n static osgDB::ReaderWriter::ReadResult\n loadUsingReaderWriter(const std::string& fileName,\n const osgDB::Options* opt)\n {\n using namespace osgDB;\n ReaderWriter* rw = Registry::instance()\n ->getReaderWriterForExtension(osgDB::getFileExtension(fileName));\n if (!rw)\n return ReaderWriter::ReadResult(); \/\/ FILE_NOT_HANDLED\n return rw->readNode(fileName, opt);\n }\n \n ProcessPolicy _processPolicy;\n CachePolicy _cachePolicy;\n OptimizePolicy _optimizePolicy;\n SubstitutePolicy _substitutePolicy;\n BVHPolicy _bvhPolicy;\n virtual ~ModelRegistryCallback() {}\n};\n\n\/\/ Predefined policies\n\nstruct DefaultProcessPolicy {\n DefaultProcessPolicy(const std::string& extension) {}\n osg::Node* process(osg::Node* node, const std::string& filename,\n const osgDB::Options* opt);\n};\n\nstruct DefaultCachePolicy {\n DefaultCachePolicy(const std::string& extension) {}\n osg::Node* find(const std::string& fileName,\n const osgDB::Options* opt);\n void addToCache(const std::string& filename, osg::Node* node);\n};\n\nstruct NoCachePolicy {\n NoCachePolicy(const std::string& extension) {}\n osg::Node* find(const std::string& fileName,\n const osgDB::Options* opt)\n {\n return 0;\n }\n void addToCache(const std::string& filename, osg::Node* node) {}\n};\n\nclass OptimizeModelPolicy {\npublic:\n OptimizeModelPolicy(const std::string& extension);\n osg::Node* optimize(osg::Node* node, const std::string& fileName,\n const osgDB::Options* opt);\nprotected:\n unsigned _osgOptions;\n};\n\nstruct NoOptimizePolicy {\n NoOptimizePolicy(const std::string& extension) {}\n osg::Node* optimize(osg::Node* node, const std::string& fileName,\n const osgDB::Options* opt)\n {\n return node;\n }\n};\n\nstruct OSGSubstitutePolicy {\n OSGSubstitutePolicy(const std::string& extension) {}\n std::string substitute(const std::string& name,\n const osgDB::Options* opt);\n};\n\nstruct NoSubstitutePolicy {\n NoSubstitutePolicy(const std::string& extension) {}\n std::string substitute(const std::string& name,\n const osgDB::Options* opt)\n {\n return std::string();\n }\n};\n\nstruct BuildLeafBVHPolicy {\n BuildLeafBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\nstruct BuildGroupBVHPolicy {\n BuildGroupBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\nstruct NoBuildBVHPolicy {\n NoBuildBVHPolicy(const std::string& extension) {}\n void buildBVH(const std::string& fileName, osg::Node* node);\n};\n\ntypedef ModelRegistryCallback<DefaultProcessPolicy, DefaultCachePolicy,\n OptimizeModelPolicy,\n OSGSubstitutePolicy, BuildLeafBVHPolicy>\nDefaultCallback;\n\n\/\/ The manager for the callbacks\nclass ModelRegistry : public osgDB::Registry::ReadFileCallback,\n public ReferencedSingleton<ModelRegistry> {\npublic:\n ModelRegistry();\n virtual osgDB::ReaderWriter::ReadResult\n readImage(const std::string& fileName,\n const osgDB::Options* opt);\n virtual osgDB::ReaderWriter::ReadResult\n readNode(const std::string& fileName,\n const osgDB::Options* opt);\n void addImageCallbackForExtension(const std::string& extension,\n osgDB::Registry::ReadFileCallback*\n callback);\n void addNodeCallbackForExtension(const std::string& extension,\n osgDB::Registry::ReadFileCallback*\n callback);\n virtual ~ModelRegistry() {}\nprotected:\n typedef std::map<std::string, osg::ref_ptr<osgDB::Registry::ReadFileCallback> >\n CallbackMap;\n CallbackMap imageCallbackMap;\n CallbackMap nodeCallbackMap;\n osg::ref_ptr<DefaultCallback> _defaultCallback;\n};\n\n\/\/ Callback that only loads the file without any caching or\n\/\/ postprocessing.\ntypedef ModelRegistryCallback<DefaultProcessPolicy, NoCachePolicy,\n NoOptimizePolicy,\n NoSubstitutePolicy, BuildLeafBVHPolicy>\nLoadOnlyCallback;\n\n\/\/ Proxy for registering extension-based callbacks\n\ntemplate<typename T>\nclass ModelRegistryCallbackProxy\n{\npublic:\n ModelRegistryCallbackProxy(std::string extension)\n {\n ModelRegistry::instance()\n ->addNodeCallbackForExtension(extension, new T(extension));\n }\n};\n}\n#endif \/\/ _SG_MODELREGISTRY_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"Wind_API.h\"\n\n#include \"util.h\"\n#include \"WindEvent.h\"\n#include \"SocketPair.h\"\n\n#include \"kdb+.util\/K_ptr.h\"\n#include \"kdb+.util\/type_convert.h\"\n#include <iostream>\n#include <mutex>\t\/\/C++11\n#include <map>\n\nnamespace Wind {\n\tnamespace pubsub {\n\n\t\tbool prepare() {\n\t\t\treturn SockPair::prepare();\n\t\t}\n\n\t\tbool finalize() {\n\t\t\treturn SockPair::finalize();\n\t\t}\n\n\t\t\/\/ This is essentially a concurrent map...\n\t\t\/\/NOTE: All std::map<> interface are _not_ protected! Use only the member functions wrapped below.\n\t\tclass CallbackRegistry : public std::map<::WQID, std::string> {\n\t\tpublic:\n\t\t\tstd::string& operator[](::WQID qid) {\n\t\t\t\tlock_guard guard(lock_);\n\t\t\t\treturn parent::operator[](qid);\n\t\t\t}\n\t\t\tsize_type erase(::WQID qid) {\n\t\t\t\tlock_guard guard(lock_);\n\t\t\t\treturn parent::erase(qid);\n\t\t\t}\n\t\tprivate:\n\t\t\ttypedef std::map<::WQID, std::string> parent;\n\t\t\ttypedef std::lock_guard<std::mutex> lock_guard;\n\t\t\tmutable std::mutex lock_;\n\t\t};\n\n\t\tstatic CallbackRegistry REGISTRY;\n\t\tstd::size_t const CLIENT = 0;\n\t\tstd::size_t const SERVER = 1;\n\n\t\t\/\/ Data processor (executed within q's main thread)\n\t\tK invokeCallback(I socket) {\n\t\t\tstatic_assert(sizeof(::SOCKET) == sizeof(I), \"SOCKET vs I: type mismatch!\");\n\t\t\t::SOCKET sock = socket;\n\t\t\tassert(sock != INVALID_SOCKET);\n\n\t\t\t\/\/ Receive (WQID, len, serialized_K) from subscription thread\n#\t\t\tdefine RECV_CHECK(expectedSize, errorMsg)\t\\\n\t\t\tif (recvd != (expectedSize)) {\t\\\n\t\t\t\tstd::cerr << \"<recv> \" << (errorMsg) << \": \" << recvd << \" < \" << (expectedSize) << std::endl;\t\\\n\t\t\t\treturn K_NIL;\t\\\n\t\t\t}\n\t\t\t::WQID qid = 0;\n\t\t\tint recvd = ::recv(sock, reinterpret_cast<char*>(&qid), sizeof(::WQID), 0);\n\t\t\tRECV_CHECK(sizeof(::WQID), \"WQID incomplete\");\n\t\t\tJ len = 0;\n\t\t\trecvd = ::recv(sock, reinterpret_cast<char*>(&len), sizeof(J), 0);\n\t\t\tRECV_CHECK(sizeof(J), \"size incomplete\");\n\t\t\tstd::vector<char> buffer(static_cast<std::size_t>(len), 0);\n\t\t\trecvd = ::recv(sock, &buffer[0], buffer.size(), 0);\n\t\t\tRECV_CHECK(len, \"data incomplete\");\n#\t\t\tundef RECV_CHECK\n\n\t\t\t\/\/ Deserialize K object\n\t\t\tq::K_ptr serialized(ktn(KB, len));\n\t\t\tstd::memcpy(kG(serialized.get()), &buffer[0], buffer.size());\n#\t\t\tif 0\t\/\/TODO: okx(K) will only be available in q.lib 3.2... to check back...\n\t\t\tif (!okx(serialized.get())) {\n\t\t\t\tstd::cerr << \"<recv> invalid data: \";\n\t\t\t\tfor (auto p = buffer.begin(); p != buffer.end(); ++p) {\n\t\t\t\t\tstd::cerr << std::setiosflags(std::ios::uppercase)\n\t\t\t\t\t\t<< std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(*p);\n\t\t\t\t}\n\t\t\t\tstd::cerr << std::endl;\n\t\t\t\treturn K_NIL;\n\t\t\t}\n#\t\t\tendif\n\t\t\tq::K_ptr result(d9(serialized.get()));\n\n\t\t\t\/\/ Identify the origial query and callback\n\t\t\tstd::string const callback = REGISTRY[qid];\n\t\t\tif (callback.empty()) {\n\t\t\t\tstd::cerr << \"unknown WQID: \" << qid << std::endl;\n\t\t\t\treturn K_NIL;\n\t\t\t}\n\n\t\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\t\tq::K_ptr output(k(0, const_cast<S>(callback.c_str()), kj(qid), result.release(), K_NIL));\n\t\t\tif (output->t == -128) {\n\t\t\t\tstd::cerr << \"<q> '\" << output->s << std::endl;\n\t\t\t}\n\t\t\treturn output.release();\n\t\t}\n\n\t\t\/\/ Result publisher (executed within subscription thread)\n\t\tbool publishResult(Event const& event, SockPair::SOCKET_ptr const* socks) {\n\t\t\t\/\/ Convert Wind event into K object\n\t\t\tstd::string error;\n\t\t\tq::K_ptr data;\n\t\t\tif (event.ErrCode != WQERR_OK) {\n\t\t\t\tstd::cerr << \"<WQ> subscription error: \" << util::error2Text(event.ErrCode) << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdata.reset(event.parse());\n\t\t\t}\n\t\t\tcatch (std::string const& ex) {\n\t\t\t\tstd::cerr << \"<WQ> response format error: \" << ex << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ Serialize K object into bytes\n\t\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\t\tq::K_ptr serialized(b9(-1, data.get()));\n\t\t\tassert((serialized->t == KG) && (serialized->n > 0));\n\n\t\t\t\/\/ Send tuple (WQID, len, serialized_K) over to the main thread\n#\t\t\tdefine SEND_CHECK(expectedSize, errorMsg)\t\\\n\t\t\tif (sent != (expectedSize)) {\t\\\n\t\t\t\tstd::cerr << \"<send> \" << (errorMsg) << \": \" << sent << \" < \" << (expectedSize) << std::endl;\t\\\n\t\t\t\treturn false;\t\\\n\t\t\t}\n\t\t\tint sent = ::send(*socks[SERVER], reinterpret_cast<char const*>(&event.RequestID), sizeof(::WQID), 0);\n\t\t\tSEND_CHECK(sizeof(::WQID), \"WQID incomplete\");\n\t\t\tstd::vector<char> buffer(kG(serialized.get()), kG(serialized.get()) + serialized->n);\n\t\t\tsent = ::send(*socks[SERVER], reinterpret_cast<char const*>(&(serialized->n)), sizeof(serialized->n), 0);\n\t\t\tSEND_CHECK(sizeof(serialized->n), \"size incomplete\");\n\t\t\tsent = ::send(*socks[SERVER], &buffer[0], buffer.size(), 0);\n\t\t\tSEND_CHECK(serialized->n, \"data incomplete\");\n#\t\t\tundef SEND_CHECK\n\n\t\t\treturn true;\n\t\t}\n\n\t\tint WINAPI subscribe(::WQEvent* pEvent, LPVOID lpUserParam) {\n\t\t\tSockPair::SOCKET_ptr* socks = static_cast<SockPair::SOCKET_ptr*>(lpUserParam);\n\t\t\tassert(socks != NULL);\n\t\t\t\n\t\t\tassert(pEvent != NULL);\n\t\t\tswitch (pEvent->EventType) {\n\t\t\tcase eWQPartialResponse:\n\t\t\t\treturn publishResult(static_cast<Event&>(*pEvent), socks);\n\t\t\tcase eWQErrorReport:\n\t\t\t\tstd::cerr << \"<WQ> error report: \" << util::error2Text(pEvent->ErrCode) << std::endl;\n\t\t\t\treturn false;\n\t\t\tcase eWQOthers:\n\t\t\t\t\/\/ Detect unsubscribe and free up socket pair\n\t\t\t\tif (pEvent->ErrCode == WQERR_USER_CANCEL) {\n\t\t\t\t\tsd0(*socks[CLIENT]);\n\t\t\t\t\tREGISTRY.erase(pEvent->RequestID);\n\t\t\t\t\tdelete[] socks;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ fall through\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tstd::cerr << \"<WQ> unsupported subscription response: \" << *pEvent << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t}\/\/namespace Wind::pubsub\n}\/\/namespace Wind\n\nWIND_API K K_DECL Wind_wsq(K windCodes, K indicators, K params, K callback) {\n\tstd::wstring codes, indis, paras;\n\tstd::string cb;\n\ttry {\n\t\tcodes = Wind::util::qList2WStringJoin(windCodes, L',');\n\t\tindis = Wind::util::qList2WStringJoin(indicators, L',');\n\t\tparas = Wind::util::qDict2WStringMapJoin(params, L';', L'=');\n\t\tcb = q::q2String(callback);\n\t}\n\tcatch (std::string const& error) {\n\t\treturn q::error2q(error);\n\t}\n\n\t\/\/ Create async socket pair\n\tstd::unique_ptr<SockPair::SOCKET_ptr[]> socks(new ::SockPair::SOCKET_ptr[2]);\n\t::SOCKET server, client;\n\tint result = SockPair::make_socket_pair(server, client);\n\tif (result != 0) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<SockPair> \" << SockPair::getError(result);\n\t\treturn q::error2q(buffer.str());\n\t}\n\tusing Wind::pubsub::SERVER;\n\tusing Wind::pubsub::CLIENT;\n\tsocks[SERVER].reset(server);\n\tsocks[CLIENT].reset(client);\n\n\t\/\/ Setup subscription\n\tstatic_assert(sizeof(::SOCKET) == sizeof(I), \"SOCKET vs I: type mismatch!\");\n\t::WQID const qid = ::WSQ(codes.c_str(), indis.c_str(), paras.c_str(),\n\t\t&Wind::pubsub::subscribe, socks.get());\n\tif (qid <= 0) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> subscription error: \" << Wind::util::error2Text(static_cast<::WQErr>(qid));\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\tsd1(*socks[CLIENT], &Wind::pubsub::invokeCallback);\n\t\tWind::pubsub::REGISTRY[qid] = cb;\n\t\tsocks.release();\n\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\treturn kj(qid);\n\t}\n}\n\nWIND_API K K_DECL Wind_cr(K qid) {\n\t::WQID id = -1;\n\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\ttry {\n\t\tid = q::q2Dec(qid);\n\t}\n\tcatch (std::string const& error) {\n\t\treturn q::error2q(error);\n\t}\n\n\t::WQErr const error = ::CancelRequest(id);\n\tif (error != WQERR_OK) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> cancellation error: \" << Wind::util::error2Text(error);\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\treturn K_NIL;\n\t}\n}\n\nWIND_API K K_DECL Wind_car(K _) {\n\t::WQErr const error = ::CancelAllRequest();\n\tif (error != WQERR_OK) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> cancellation error: \" << Wind::util::error2Text(error);\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\treturn K_NIL;\n\t}\n}\n<commit_msg>+ Prevent accidental misuse of Wind::pubsub::REGISTRY + Reduce data copying on data serialization\/deserialization<commit_after>#include \"stdafx.h\"\n#include \"Wind_API.h\"\n\n#include \"util.h\"\n#include \"WindEvent.h\"\n#include \"SocketPair.h\"\n\n#include \"kdb+.util\/K_ptr.h\"\n#include \"kdb+.util\/type_convert.h\"\n#include <iostream>\n#include <mutex>\t\/\/C++11\n#include <map>\n\nnamespace Wind {\n\tnamespace pubsub {\n\n\t\tbool prepare() {\n\t\t\treturn SockPair::prepare();\n\t\t}\n\n\t\tbool finalize() {\n\t\t\treturn SockPair::finalize();\n\t\t}\n\n\t\t\/\/ This is essentially a concurrent map...\n\t\t\/\/NOTE: All std::map<> interface are _not_ protected! Use only the member functions wrapped below.\n\t\tclass CallbackRegistry : private std::map<::WQID, std::string> {\n\t\tpublic:\n\t\t\tstd::string& operator[](::WQID qid) {\n\t\t\t\tlock_guard guard(lock_);\n\t\t\t\treturn parent::operator[](qid);\n\t\t\t}\n\t\t\tsize_type erase(::WQID qid) {\n\t\t\t\tlock_guard guard(lock_);\n\t\t\t\treturn parent::erase(qid);\n\t\t\t}\n\t\tprivate:\n\t\t\ttypedef std::map<::WQID, std::string> parent;\n\t\t\ttypedef std::lock_guard<std::mutex> lock_guard;\n\t\t\tmutable std::mutex lock_;\n\t\t};\n\n\t\tstatic CallbackRegistry REGISTRY;\n\t\tstd::size_t const CLIENT = 0;\n\t\tstd::size_t const SERVER = 1;\n\n\t\t\/\/ Data processor (executed within q's main thread)\n\t\tK invokeCallback(I socket) {\n\t\t\tstatic_assert(sizeof(::SOCKET) == sizeof(I), \"SOCKET vs I: type mismatch!\");\n\t\t\t::SOCKET sock = socket;\n\t\t\tassert(sock != INVALID_SOCKET);\n\n\t\t\t\/\/ Receive (WQID, len, serialized_K) from subscription thread\n#\t\t\tdefine RECV_CHECK(expectedSize, errorMsg)\t\\\n\t\t\tif (recvd != (expectedSize)) {\t\\\n\t\t\t\tstd::cerr << \"<recv> \" << (errorMsg) << \": \" << recvd << \" < \" << (expectedSize) << std::endl;\t\\\n\t\t\t\treturn K_NIL;\t\\\n\t\t\t}\n\t\t\t::WQID qid = 0;\n\t\t\tint recvd = ::recv(sock, reinterpret_cast<char*>(&qid), sizeof(::WQID), 0);\n\t\t\tRECV_CHECK(sizeof(::WQID), \"WQID incomplete\");\n\t\t\tstd::size_t len = 0;\n\t\t\trecvd = ::recv(sock, reinterpret_cast<char*>(&len), sizeof(len), 0);\n\t\t\tRECV_CHECK(sizeof(len), \"size incomplete\");\n\t\t\tif (len > static_cast<std::size_t>(std::numeric_limits<int>::max())) {\n\t\t\t\tstd::cerr << \"<recv> serialized data (\" << len << \") > 2G\" << std::endl;\n\t\t\t\treturn K_NIL;\n\t\t\t}\n\t\t\tq::K_ptr serialized(ktn(KB, len));\n\t\t\tstd::memset(kG(serialized.get()), 0, len);\n\t\t\trecvd = ::recv(sock, reinterpret_cast<char*>(kG(serialized.get())), len, 0);\n\t\t\tRECV_CHECK(len, \"data incomplete\");\n#\t\t\tundef RECV_CHECK\n\n\t\t\t\/\/ Deserialize K object\n#\t\t\tif 0\t\/\/TODO: okx(K) will only be available in q.lib 3.2... to check back...\n\t\t\tif (!okx(serialized.get())) {\n\t\t\t\tstd::cerr << \"<recv> invalid data: \";\n\t\t\t\tfor (auto p = buffer.begin(); p != buffer.end(); ++p) {\n\t\t\t\t\tstd::cerr << std::setiosflags(std::ios::uppercase)\n\t\t\t\t\t\t<< std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(*p);\n\t\t\t\t}\n\t\t\t\tstd::cerr << std::endl;\n\t\t\t\treturn K_NIL;\n\t\t\t}\n#\t\t\tendif\n\t\t\tq::K_ptr result(d9(serialized.get()));\n\n\t\t\t\/\/ Identify the origial query and callback\n\t\t\tstd::string const callback = REGISTRY[qid];\n\t\t\tif (callback.empty()) {\n\t\t\t\tstd::cerr << \"unknown WQID: \" << qid << std::endl;\n\t\t\t\treturn K_NIL;\n\t\t\t}\n\n\t\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\t\tq::K_ptr output(k(0, const_cast<S>(callback.c_str()), kj(qid), result.release(), K_NIL));\n\t\t\tif (output->t == -128) {\n\t\t\t\tstd::cerr << \"<q> '\" << output->s << std::endl;\n\t\t\t}\n\t\t\treturn output.release();\n\t\t}\n\n\t\t\/\/ Result publisher (executed within subscription thread)\n\t\tbool publishResult(Event const& event, SockPair::SOCKET_ptr const* socks) {\n\t\t\t\/\/ Convert Wind event into K object\n\t\t\tstd::string error;\n\t\t\tq::K_ptr data;\n\t\t\tif (event.ErrCode != WQERR_OK) {\n\t\t\t\tstd::cerr << \"<WQ> subscription error: \" << util::error2Text(event.ErrCode) << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tdata.reset(event.parse());\n\t\t\t}\n\t\t\tcatch (std::string const& ex) {\n\t\t\t\tstd::cerr << \"<WQ> response format error: \" << ex << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ Serialize K object into bytes\n\t\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\t\tq::K_ptr serialized(b9(-1, data.get()));\n\t\t\tassert((serialized->t == KG) && (serialized->n > 0));\n\n\t\t\t\/\/ Send tuple (WQID, len, serialized_K) over to the main thread\n#\t\t\tdefine SEND_CHECK(expectedSize, errorMsg)\t\\\n\t\t\tif (sent != (expectedSize)) {\t\\\n\t\t\t\tstd::cerr << \"<send> \" << (errorMsg) << \": \" << sent << \" < \" << (expectedSize) << std::endl;\t\\\n\t\t\t\treturn false;\t\\\n\t\t\t}\n\t\t\tint sent = ::send(*socks[SERVER], reinterpret_cast<char const*>(&event.RequestID), sizeof(::WQID), 0);\n\t\t\tSEND_CHECK(sizeof(::WQID), \"WQID incomplete\");\n\t\t\tstd::size_t const len = static_cast<std::size_t>(serialized->n);\n\t\t\tif (len > static_cast<std::size_t>(std::numeric_limits<int>::max())) {\n\t\t\t\tstd::cerr << \"<send> serialized data (\" << len << \") > 2G\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tsent = ::send(*socks[SERVER], reinterpret_cast<char const*>(&len), sizeof(len), 0);\n\t\t\tSEND_CHECK(sizeof(len), \"size incomplete\");\n\t\t\tsent = ::send(*socks[SERVER], reinterpret_cast<char const*>(kG(serialized.get())), len, 0);\n\t\t\tSEND_CHECK(serialized->n, \"data incomplete\");\n#\t\t\tundef SEND_CHECK\n\n\t\t\treturn true;\n\t\t}\n\n\t\tint WINAPI subscribe(::WQEvent* pEvent, LPVOID lpUserParam) {\n\t\t\tSockPair::SOCKET_ptr* socks = static_cast<SockPair::SOCKET_ptr*>(lpUserParam);\n\t\t\tassert(socks != NULL);\n\t\t\t\n\t\t\tassert(pEvent != NULL);\n\t\t\tswitch (pEvent->EventType) {\n\t\t\tcase eWQPartialResponse:\n\t\t\t\treturn publishResult(static_cast<Event&>(*pEvent), socks);\n\t\t\tcase eWQErrorReport:\n\t\t\t\tstd::cerr << \"<WQ> error report: \" << util::error2Text(pEvent->ErrCode) << std::endl;\n\t\t\t\treturn false;\n\t\t\tcase eWQOthers:\n\t\t\t\t\/\/ Detect unsubscribe and free up socket pair\n\t\t\t\tif (pEvent->ErrCode == WQERR_USER_CANCEL) {\n\t\t\t\t\tsd0(*socks[CLIENT]);\n\t\t\t\t\tREGISTRY.erase(pEvent->RequestID);\n\t\t\t\t\tdelete[] socks;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ fall through\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tstd::cerr << \"<WQ> unsupported subscription response: \" << *pEvent << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t}\/\/namespace Wind::pubsub\n}\/\/namespace Wind\n\nWIND_API K K_DECL Wind_wsq(K windCodes, K indicators, K params, K callback) {\n\tstd::wstring codes, indis, paras;\n\tstd::string cb;\n\ttry {\n\t\tcodes = Wind::util::qList2WStringJoin(windCodes, L',');\n\t\tindis = Wind::util::qList2WStringJoin(indicators, L',');\n\t\tparas = Wind::util::qDict2WStringMapJoin(params, L';', L'=');\n\t\tcb = q::q2String(callback);\n\t}\n\tcatch (std::string const& error) {\n\t\treturn q::error2q(error);\n\t}\n\n\t\/\/ Create async socket pair\n\tstd::unique_ptr<SockPair::SOCKET_ptr[]> socks(new ::SockPair::SOCKET_ptr[2]);\n\t::SOCKET server, client;\n\tint result = SockPair::make_socket_pair(server, client);\n\tif (result != 0) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<SockPair> \" << SockPair::getError(result);\n\t\treturn q::error2q(buffer.str());\n\t}\n\tusing Wind::pubsub::SERVER;\n\tusing Wind::pubsub::CLIENT;\n\tsocks[SERVER].reset(server);\n\tsocks[CLIENT].reset(client);\n\n\t\/\/ Setup subscription\n\tstatic_assert(sizeof(::SOCKET) == sizeof(I), \"SOCKET vs I: type mismatch!\");\n\t::WQID const qid = ::WSQ(codes.c_str(), indis.c_str(), paras.c_str(),\n\t\t&Wind::pubsub::subscribe, socks.get());\n\tif (qid <= 0) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> subscription error: \" << Wind::util::error2Text(static_cast<::WQErr>(qid));\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\tsd1(*socks[CLIENT], &Wind::pubsub::invokeCallback);\n\t\tWind::pubsub::REGISTRY[qid] = cb;\n\t\tsocks.release();\n\t\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\t\treturn kj(qid);\n\t}\n}\n\nWIND_API K K_DECL Wind_cr(K qid) {\n\t::WQID id = -1;\n\tstatic_assert(std::is_same<::WQID, J>::value, \"WQID data type mismatch\");\n\ttry {\n\t\tid = q::q2Dec(qid);\n\t}\n\tcatch (std::string const& error) {\n\t\treturn q::error2q(error);\n\t}\n\n\t::WQErr const error = ::CancelRequest(id);\n\tif (error != WQERR_OK) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> cancellation error: \" << Wind::util::error2Text(error);\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\treturn K_NIL;\n\t}\n}\n\nWIND_API K K_DECL Wind_car(K _) {\n\t::WQErr const error = ::CancelAllRequest();\n\tif (error != WQERR_OK) {\n\t\tstd::ostringstream buffer;\n\t\tbuffer << \"<WQ> cancellation error: \" << Wind::util::error2Text(error);\n\t\treturn q::error2q(buffer.str());\n\t}\n\telse {\n\t\treturn K_NIL;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file phi_mpi.cpp\n\/\/\/ @brief The PhiCache class calculates the partial sieve function\n\/\/\/ (a.k.a. Legendre-sum) using the recursive formula:\n\/\/\/ phi(x, a) = phi(x, a - 1) - phi(x \/ primes[a], a - 1).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible by\n\/\/\/ any of the first a primes. The algorithm used is an\n\/\/\/ optimized version of the algorithm described in Tomás\n\/\/\/ Oliveira e Silva's paper [1]. I have added 5 optimizations\n\/\/\/ to my implementation which significantly speed up the\n\/\/\/ calculation:\n\/\/\/\n\/\/\/ * Cache results of phi(x, a)\n\/\/\/ * Calculate phi(x, a) using formula [2] if a <= 6\n\/\/\/ * Calculate phi(x, a) using pi(x) lookup table\n\/\/\/ * Calculate all phi(x, a) = 1 upfront\n\/\/\/ * Stop recursion at c instead of 1\n\/\/\/\n\/\/\/ [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial\n\/\/\/ method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.\n\/\/\/ http:\/\/sweet.ua.pt\/tos\/bib\/5.4.pdf\n\/\/\/ [2] phi(x, a) = (x \/ pp) * φ(pp) + phi(x % pp, a)\n\/\/\/ with pp = 2 * 3 * ... * prime[a] \n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <PiTable.hpp>\n#include <primecount-internal.hpp>\n#include <primecount.hpp>\n#include <pmath.hpp>\n#include <PhiTiny.hpp>\n#include <min_max.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <vector>\n#include <cassert>\n#include <limits>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\nclass PhiCache\n{\npublic:\n PhiCache(const vector<int64_t>& primes,\n const PiTable& pi) :\n primes_(primes),\n pi_(pi),\n bytes_(0)\n {\n \/\/ primecount uses 1-indexing i.e. primes[1] = 2\n assert(primes_[0] == 0);\n size_t max_size = CACHE_A_LIMIT + 1;\n cache_.resize(min(primes.size(), max_size));\n }\n\n \/\/\/ Calculate phi(x, a) using the recursive formula:\n \/\/\/ phi(x, a) = phi(x, a - 1) - phi(x \/ primes_[a], a - 1)\n \/\/\/\n template <int SIGN>\n int64_t phi(int64_t x, int64_t a)\n {\n int64_t sum = 0;\n\n if (x <= primes_[a])\n sum = SIGN;\n else if (is_phi_tiny(a))\n sum = phi_tiny(x, a) * SIGN;\n else if (is_phi_by_pix(x, a))\n sum = (pi_[x] - a + 1) * SIGN;\n else\n {\n int64_t sqrtx = isqrt(x);\n int64_t pi_sqrtx = a;\n\n if (sqrtx < pi_.size() && sqrtx < primes_[a])\n pi_sqrtx = pi_[sqrtx];\n\n \/\/ Move out of the loop the calculations where phi(x2, a2) = 1\n \/\/ phi(x, a) = 1 if primes_[a] >= x\n \/\/ x2 = x \/ primes_[a2 + 1]\n \/\/ phi(x2, a2) = 1 if primes_[a2] >= x \/ primes_[a2 + 1]\n \/\/ phi(x2, a2) = 1 if primes_[a2] >= sqrt(x)\n \/\/ phi(x2, a2) = 1 if a2 >= pi(sqrt(x))\n \/\/ \\sum_{a2 = pi(sqrt(x))}^{a - 1} phi(x2, a2) = a - pi(sqrt(x))\n \/\/\n sum = (a - pi_sqrtx) * -SIGN;\n\n \/\/ phi(x, c) = phi(x, 1) - \\sum_{a2 = 1}^{c - 1} phi(x \/ primes_[a2 + 1], a2)\n int64_t c = min(PhiTiny::max_a(), pi_sqrtx);\n sum += phi_tiny(x, c) * SIGN;\n int64_t a2 = c;\n \n \/\/ 64-bit integer division, slow\n for (; a2 < pi_sqrtx && x > numeric_limits<uint32_t>::max(); a2++)\n {\n int64_t x2 = x \/ primes_[a2 + 1];\n if (is_cached(x2, a2))\n sum += cache_[a2][x2] * -SIGN;\n else\n sum += phi<-SIGN>(x2, a2);\n }\n\n \/\/ 32-bit integer division, faster\n for (; a2 < pi_sqrtx; a2++)\n {\n int64_t x2 = (uint32_t) x \/ (uint32_t) primes_[a2 + 1];\n if (is_cached(x2, a2))\n sum += cache_[a2][x2] * -SIGN;\n else\n sum += phi<-SIGN>(x2, a2);\n }\n }\n\n if (write_to_cache(x, a))\n cache_[a][x] = (uint16_t) (sum * SIGN);\n\n return sum;\n }\n\nprivate:\n enum\n {\n \/\/\/ Cache phi(x, a) results if a <= CACHE_A_LIMIT\n CACHE_A_LIMIT = 500,\n \/\/\/ Keep the cache size below CACHE_BYTES_LIMIT per thread\n CACHE_BYTES_LIMIT = 16 << 20\n };\n\n \/\/\/ Cache of phi(x, a) results\n vector<vector<uint16_t> > cache_;\n const vector<int64_t>& primes_;\n const PiTable& pi_;\n int64_t bytes_;\n\n void operator=(const PhiCache&);\n\n bool is_phi_by_pix(int64_t x, int64_t a) const\n {\n return x < pi_.size() &&\n x < isquare(primes_[a + 1]);\n }\n\n int64_t cache_size(int64_t a) const\n {\n return (int64_t) cache_[a].size();\n }\n\n bool is_cached(int64_t x, int64_t a) const\n {\n return a <= CACHE_A_LIMIT && \n x < cache_size(a) && \n cache_[a][x] != 0;\n }\n\n bool write_to_cache(int64_t x, int64_t a)\n {\n if (a > CACHE_A_LIMIT || \n x > numeric_limits<uint16_t>::max())\n return false;\n\n \/\/ check if we need to increase cache size\n if (x >= cache_size(a))\n {\n if (bytes_ > CACHE_BYTES_LIMIT)\n return false;\n bytes_ += (x + 1 - cache_size(a)) * 2;\n cache_[a].resize(x + 1, 0);\n }\n\n return true;\n }\n};\n\n} \/\/ namespace\n\nnamespace primecount {\n\n\/\/\/ Returns a vector with phi(x, i) values for 0 <= i <= a.\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible by any\n\/\/\/ of the first a primes.\n\/\/\/\nvector<int64_t> phi_vector(int64_t x,\n int64_t a,\n const vector<int64_t>& primes,\n const PiTable& pi, \n int threads)\n{\n vector<int64_t> phi(a + 2, 0);\n\n \/\/ phi(x, 0) = x\n \/\/ primecount uses 1-indexing\n phi[1] = x;\n\n if (x > 0 && a > 0)\n {\n PhiCache cache(primes, pi);\n\n int64_t p14 = ipow((int64_t) 10, 14);\n int64_t thread_threshold = p14 \/ primes[a];\n threads = ideal_num_threads(threads, x, thread_threshold);\n\n \/\/ this loop scales only up to about 8 CPU cores\n \/\/ because the cache requires too much memory bandwidth\n threads = min(8, threads);\n\n #pragma omp parallel for num_threads(threads) schedule(dynamic, 16) firstprivate(cache)\n for (int64_t a2 = 2; a2 <= a; a2++)\n phi[a2] = cache.phi<-1>(x \/ primes[a2 - 1], a2 - 2);\n\n \/\/ calculate phi(x, i) using partial results\n for (int64_t i = 2; i <= a; i++)\n phi[i] += phi[i - 1];\n }\n\n return phi;\n}\n\n} \/\/ namespace\n<commit_msg>Refactor<commit_after>\/\/\/\n\/\/\/ @file phi_mpi.cpp\n\/\/\/ @brief The PhiCache class calculates the partial sieve function\n\/\/\/ (a.k.a. Legendre-sum) using the recursive formula:\n\/\/\/ phi(x, a) = phi(x, a - 1) - phi(x \/ primes[a], a - 1).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible by\n\/\/\/ any of the first a primes. The algorithm used is an\n\/\/\/ optimized version of the algorithm described in Tomás\n\/\/\/ Oliveira e Silva's paper [1]. I have added 5 optimizations\n\/\/\/ to my implementation which significantly speed up the\n\/\/\/ calculation:\n\/\/\/\n\/\/\/ * Cache results of phi(x, a)\n\/\/\/ * Calculate phi(x, a) using formula [2] if a <= 6\n\/\/\/ * Calculate phi(x, a) using pi(x) lookup table\n\/\/\/ * Calculate all phi(x, a) = 1 upfront\n\/\/\/ * Stop recursion at c instead of 1\n\/\/\/\n\/\/\/ [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial\n\/\/\/ method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.\n\/\/\/ http:\/\/sweet.ua.pt\/tos\/bib\/5.4.pdf\n\/\/\/ [2] phi(x, a) = (x \/ pp) * φ(pp) + phi(x % pp, a)\n\/\/\/ with pp = 2 * 3 * ... * prime[a] \n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <PiTable.hpp>\n#include <primecount-internal.hpp>\n#include <primecount.hpp>\n#include <pmath.hpp>\n#include <PhiTiny.hpp>\n#include <min_max.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <vector>\n#include <limits>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\nclass PhiCache\n{\npublic:\n PhiCache(const vector<int64_t>& primes,\n const PiTable& pi) :\n primes_(primes),\n pi_(pi),\n bytes_(0)\n {\n size_t max_size = MAX_A + 1;\n size_t size = min(primes.size(), max_size);\n cache_.resize(size);\n }\n\n \/\/\/ Calculate phi(x, a) using the recursive formula:\n \/\/\/ phi(x, a) = phi(x, a - 1) - phi(x \/ primes_[a], a - 1)\n \/\/\/\n template <int SIGN>\n int64_t phi(int64_t x, int64_t a)\n {\n int64_t sum = 0;\n\n if (x <= primes_[a])\n sum = SIGN;\n else if (is_phi_tiny(a))\n sum = phi_tiny(x, a) * SIGN;\n else if (is_phi_by_pix(x, a))\n sum = (pi_[x] - a + 1) * SIGN;\n else\n {\n int64_t sqrtx = isqrt(x);\n int64_t pi_sqrtx = a;\n\n if (sqrtx < pi_.size() && sqrtx < primes_[a])\n pi_sqrtx = pi_[sqrtx];\n\n \/\/ Move out of the loop the calculations where phi(x2, a2) = 1\n \/\/ phi(x, a) = 1 if primes_[a] >= x\n \/\/ x2 = x \/ primes_[a2 + 1]\n \/\/ phi(x2, a2) = 1 if primes_[a2] >= x \/ primes_[a2 + 1]\n \/\/ phi(x2, a2) = 1 if primes_[a2] >= sqrt(x)\n \/\/ phi(x2, a2) = 1 if a2 >= pi(sqrt(x))\n \/\/ \\sum_{a2 = pi(sqrt(x))}^{a - 1} phi(x2, a2) = a - pi(sqrt(x))\n \/\/\n sum = (a - pi_sqrtx) * -SIGN;\n\n \/\/ phi(x, c) = phi(x, 1) - \\sum_{a2 = 1}^{c - 1} phi(x \/ primes_[a2 + 1], a2)\n int64_t c = min(PhiTiny::max_a(), pi_sqrtx);\n sum += phi_tiny(x, c) * SIGN;\n int64_t a2 = c;\n \n \/\/ 64-bit integer division, slow\n for (; a2 < pi_sqrtx && \n x > numeric_limits<uint32_t>::max(); a2++)\n {\n int64_t x2 = x \/ primes_[a2 + 1];\n if (is_cached(x2, a2))\n sum += cache_[a2][x2] * -SIGN;\n else\n sum += phi<-SIGN>(x2, a2);\n }\n\n \/\/ 32-bit integer division, fast\n for (; a2 < pi_sqrtx; a2++)\n {\n int64_t x2 = (uint32_t) x \/ (uint32_t) primes_[a2 + 1];\n if (is_cached(x2, a2))\n sum += cache_[a2][x2] * -SIGN;\n else\n sum += phi<-SIGN>(x2, a2);\n }\n }\n\n if (write_to_cache(x, a))\n cache_[a][x] = (uint16_t) (sum * SIGN);\n\n return sum;\n }\n\nprivate:\n enum\n {\n \/\/\/ Cache phi(x, a) results if a <= MAX_A\n MAX_A = 500,\n \/\/\/ Keep the cache size below MAX_BYTES per thread\n MAX_BYTES = 16 << 20\n };\n\n \/\/\/ Cache of phi(x, a) results\n vector<vector<uint16_t> > cache_;\n const vector<int64_t>& primes_;\n const PiTable& pi_;\n int64_t bytes_;\n\n void operator=(const PhiCache&);\n\n bool is_phi_by_pix(int64_t x, int64_t a) const\n {\n return x < pi_.size() &&\n x < isquare(primes_[a + 1]);\n }\n\n int64_t cache_size(int64_t a) const\n {\n return (int64_t) cache_[a].size();\n }\n\n bool is_cached(int64_t x, int64_t a) const\n {\n return a <= MAX_A && \n x < cache_size(a) && \n cache_[a][x] != 0;\n }\n\n bool write_to_cache(int64_t x, int64_t a)\n {\n if (a > MAX_A || \n x > numeric_limits<uint16_t>::max())\n return false;\n\n \/\/ we need to increase cache size\n if (x >= cache_size(a))\n {\n if (bytes_ > MAX_BYTES)\n return false;\n bytes_ += (x + 1 - cache_size(a)) * 2;\n cache_[a].resize(x + 1, 0);\n }\n\n return true;\n }\n};\n\n} \/\/ namespace\n\nnamespace primecount {\n\n\/\/\/ Returns a vector with phi(x, i) values for 0 <= i <= a.\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible by any\n\/\/\/ of the first a primes.\n\/\/\/\nvector<int64_t> phi_vector(int64_t x,\n int64_t a,\n const vector<int64_t>& primes,\n const PiTable& pi, \n int threads)\n{\n vector<int64_t> phi(a + 2, 0);\n phi[1] = x;\n\n if (x > 0 && a > 0)\n {\n PhiCache cache(primes, pi);\n\n int64_t p14 = ipow((int64_t) 10, 14);\n int64_t thread_threshold = p14 \/ primes[a];\n threads = ideal_num_threads(threads, x, thread_threshold);\n\n \/\/ this loop scales only up to about 8 CPU cores\n \/\/ because the cache requires too much memory bandwidth\n threads = min(8, threads);\n\n #pragma omp parallel for num_threads(threads) schedule(dynamic, 16) firstprivate(cache)\n for (int64_t a2 = 2; a2 <= a; a2++)\n phi[a2] = cache.phi<-1>(x \/ primes[a2 - 1], a2 - 2);\n\n \/\/ calculate phi(x, i) using partial results\n for (int64_t i = 2; i <= a; i++)\n phi[i] += phi[i - 1];\n }\n\n return phi;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <memory>\n#include <thread>\n\n#include \"VisitorUtils.hpp\"\n#include \"Options.hpp\"\n#include \"PerfsTimer.hpp\"\n#include \"iterators.hpp\"\n#include \"likely.hpp\"\n\n#include \"mtac\/Pass.hpp\"\n#include \"mtac\/Optimizer.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Printer.hpp\"\n\n\/\/The custom optimizations\n#include \"mtac\/VariableCleaner.hpp\"\n#include \"mtac\/FunctionOptimizations.hpp\"\n#include \"mtac\/DeadCodeElimination.hpp\"\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/ConcatReduction.hpp\"\n#include \"mtac\/inlining.hpp\"\n\n\/\/The optimization visitors\n#include \"mtac\/ArithmeticIdentities.hpp\"\n#include \"mtac\/ReduceInStrength.hpp\"\n#include \"mtac\/ConstantFolding.hpp\"\n#include \"mtac\/RemoveAssign.hpp\"\n#include \"mtac\/RemoveMultipleAssign.hpp\"\n#include \"mtac\/MathPropagation.hpp\"\n\n\/\/The data-flow problems\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ConstantPropagationProblem.hpp\"\n#include \"mtac\/OffsetConstantPropagationProblem.hpp\"\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n\nusing namespace eddic;\n\nnamespace {\n\nstatic const unsigned int MAX_THREADS = 2;\n\ntemplate<typename Visitor>\nbool apply_to_all(std::shared_ptr<mtac::Function> function){\n Visitor visitor;\n\n for(auto& block : function->getBasicBlocks()){\n visit_each(visitor, block->statements);\n }\n\n return visitor.optimized;\n}\n\ntemplate<typename Visitor>\nbool apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n for(auto& block : function->getBasicBlocks()){\n Visitor visitor;\n visitor.pass = mtac::Pass::DATA_MINING;\n\n visit_each(visitor, block->statements);\n\n visitor.pass = mtac::Pass::OPTIMIZE;\n\n visit_each(visitor, block->statements);\n\n optimized |= visitor.optimized;\n }\n\n return optimized;\n}\n\ntemplate<typename Problem>\nbool data_flow_optimization(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n Problem problem;\n\n auto results = mtac::data_flow(function, problem);\n\n \/\/Once the data-flow problem is fixed, statements can be optimized\n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n optimized |= problem.optimize(statement, results);\n }\n }\n\n return optimized;\n}\n\nbool debug(const std::string& name, bool b, std::shared_ptr<mtac::Function> function){\n if(option_defined(\"dev\")){\n if(b){\n std::cout << \"optimization \" << name << \" returned true\" << std::endl;\n\n \/\/Print the function\n print(function);\n } else {\n std::cout << \"optimization \" << name << \" returned false\" << std::endl;\n }\n }\n\n return b;\n}\n\ntemplate<typename Functor>\nbool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function){\n bool b;\n {\n PerfsTimer timer(name);\n\n b = functor(function);\n }\n\n return debug(name, b, function);\n}\n\ntemplate<typename Functor, typename Arg2>\nbool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function, Arg2& arg2){\n bool b;\n {\n PerfsTimer timer(name);\n\n b = functor(function, arg2);\n }\n\n return debug(name, b, function);\n}\n\nvoid remove_nop(std::shared_ptr<mtac::Function> function){\n for(auto& block : function->getBasicBlocks()){\n auto it = iterate(block->statements);\n\n while(it.has_next()){\n if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){\n it.erase();\n continue;\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){\n if((*ptr)->op == mtac::Operator::NOP){\n it.erase();\n continue;\n }\n }\n\n ++it;\n }\n }\n}\n\n}\n\nvoid optimize_function(std::shared_ptr<mtac::Function> function, std::shared_ptr<StringPool> pool){\n if(option_defined(\"dev\")){\n std::cout << \"Start optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n bool optimized;\n do {\n optimized = false;\n\n optimized |= debug(\"Aritmetic Identities\", &apply_to_all<mtac::ArithmeticIdentities>, function);\n optimized |= debug(\"Reduce in Strength\", &apply_to_all<mtac::ReduceInStrength>, function);\n optimized |= debug(\"Constant folding\", &apply_to_all<mtac::ConstantFolding>, function);\n\n optimized |= debug(\"Constant propagation\", &data_flow_optimization<mtac::ConstantPropagationProblem>, function);\n optimized |= debug(\"Offset Constant Propagation\", &data_flow_optimization<mtac::OffsetConstantPropagationProblem>, function);\n\n \/\/If there was optimizations here, better to try again before perfoming common subexpression\n if(optimized){\n continue;\n }\n\n optimized |= debug(\"Common Subexpression Elimination\", &data_flow_optimization<mtac::CommonSubexpressionElimination>, function);\n\n optimized |= debug(\"Math Propagation\", &apply_to_basic_blocks_two_pass<mtac::MathPropagation>, function);\n\n optimized |= debug(\"Optimize Branches\", &mtac::optimize_branches, function);\n optimized |= debug(\"Optimize Concat\", &mtac::optimize_concat, function, pool);\n optimized |= debug(\"Remove dead basic block\", &mtac::remove_dead_basic_blocks, function);\n optimized |= debug(\"Merge basic block\", &mtac::merge_basic_blocks, function);\n \n optimized |= debug(\"Dead-Code Elimination\", &mtac::dead_code_elimination, function);\n\n remove_nop(function);\n } while (optimized);\n\n \/\/Remove variables that are not used after optimizations\n clean_variables(function);\n}\n\nvoid basic_optimize_function(std::shared_ptr<mtac::Function> function){\n if(option_defined(\"dev\")){\n std::cout << \"Start basic optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n debug(\"Constant folding\", apply_to_all<mtac::ConstantFolding>(function), function);\n \n \/*\/\/Liveness debugging\n mtac::LiveVariableAnalysisProblem problem;\n auto results = mtac::data_flow(function, problem);\n\n for(auto& block : function->getBasicBlocks()){\n auto it = block->statements.begin();\n auto end = block->statements.end();\n\n while(it != end){\n auto statement = *it;\n\n mtac::Printer printer;\n printer.printStatement(statement);\n std::cout << \"OUT{\";\n for(auto& var : results->OUT_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n std::cout << \"IN{\";\n for(auto& var : results->IN_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n\n ++it;\n }\n }*\/\n}\n\nvoid optimize_all_functions(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool){\n PerfsTimer timer(\"Whole optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector<std::thread> pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &string_pool, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n optimize_function(functions[i], string_pool); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n\nvoid mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool) const {\n bool optimized = false;\n\n do{\n mtac::remove_unused_functions(program);\n\n optimize_all_functions(program, string_pool);\n\n optimized = mtac::remove_empty_functions(program);\n optimized = mtac::inline_functions(program);\n } while(optimized);\n}\n\nvoid mtac::Optimizer::basic_optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> \/*string_pool*\/) const {\n PerfsTimer timer(\"Whole basic optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector<std::thread> pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n basic_optimize_function(functions[i]); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n<commit_msg>Cleanup<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <memory>\n#include <thread>\n\n#include \"VisitorUtils.hpp\"\n#include \"Options.hpp\"\n#include \"PerfsTimer.hpp\"\n#include \"iterators.hpp\"\n#include \"likely.hpp\"\n\n#include \"mtac\/Pass.hpp\"\n#include \"mtac\/Optimizer.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Printer.hpp\"\n\n\/\/The custom optimizations\n#include \"mtac\/VariableCleaner.hpp\"\n#include \"mtac\/FunctionOptimizations.hpp\"\n#include \"mtac\/DeadCodeElimination.hpp\"\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/ConcatReduction.hpp\"\n#include \"mtac\/inlining.hpp\"\n\n\/\/The optimization visitors\n#include \"mtac\/ArithmeticIdentities.hpp\"\n#include \"mtac\/ReduceInStrength.hpp\"\n#include \"mtac\/ConstantFolding.hpp\"\n#include \"mtac\/RemoveAssign.hpp\"\n#include \"mtac\/RemoveMultipleAssign.hpp\"\n#include \"mtac\/MathPropagation.hpp\"\n\n\/\/The data-flow problems\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ConstantPropagationProblem.hpp\"\n#include \"mtac\/OffsetConstantPropagationProblem.hpp\"\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n\nusing namespace eddic;\n\nnamespace {\n\nstatic const unsigned int MAX_THREADS = 2;\n\ntemplate<typename Visitor>\nbool apply_to_all(std::shared_ptr<mtac::Function> function){\n Visitor visitor;\n\n for(auto& block : function->getBasicBlocks()){\n visit_each(visitor, block->statements);\n }\n\n return visitor.optimized;\n}\n\ntemplate<typename Visitor>\nbool apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n for(auto& block : function->getBasicBlocks()){\n Visitor visitor;\n visitor.pass = mtac::Pass::DATA_MINING;\n\n visit_each(visitor, block->statements);\n\n visitor.pass = mtac::Pass::OPTIMIZE;\n\n visit_each(visitor, block->statements);\n\n optimized |= visitor.optimized;\n }\n\n return optimized;\n}\n\ntemplate<typename Problem>\nbool data_flow_optimization(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n Problem problem;\n\n auto results = mtac::data_flow(function, problem);\n\n \/\/Once the data-flow problem is fixed, statements can be optimized\n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n optimized |= problem.optimize(statement, results);\n }\n }\n\n return optimized;\n}\n\nbool debug(const std::string& name, bool b, std::shared_ptr<mtac::Function> function){\n if(option_defined(\"dev\")){\n if(b){\n std::cout << \"optimization \" << name << \" returned true\" << std::endl;\n\n \/\/Print the function\n print(function);\n } else {\n std::cout << \"optimization \" << name << \" returned false\" << std::endl;\n }\n }\n\n return b;\n}\n\ntemplate<typename Functor>\nbool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function){\n bool b;\n {\n PerfsTimer timer(name);\n\n b = functor(function);\n }\n\n return debug(name, b, function);\n}\n\ntemplate<typename Functor, typename Arg2>\nbool debug(const std::string& name, Functor functor, std::shared_ptr<mtac::Function> function, Arg2& arg2){\n bool b;\n {\n PerfsTimer timer(name);\n\n b = functor(function, arg2);\n }\n\n return debug(name, b, function);\n}\n\nvoid remove_nop(std::shared_ptr<mtac::Function> function){\n for(auto& block : function->getBasicBlocks()){\n auto it = iterate(block->statements);\n\n while(it.has_next()){\n if(unlikely(boost::get<std::shared_ptr<mtac::NoOp>>(&*it))){\n it.erase();\n continue;\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&*it)){\n if((*ptr)->op == mtac::Operator::NOP){\n it.erase();\n continue;\n }\n }\n\n ++it;\n }\n }\n}\n\n}\n\nvoid optimize_function(std::shared_ptr<mtac::Function> function, std::shared_ptr<StringPool> pool){\n if(option_defined(\"dev\")){\n std::cout << \"Start optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n bool optimized;\n do {\n optimized = false;\n\n optimized |= debug(\"Aritmetic Identities\", &apply_to_all<mtac::ArithmeticIdentities>, function);\n optimized |= debug(\"Reduce in Strength\", &apply_to_all<mtac::ReduceInStrength>, function);\n optimized |= debug(\"Constant folding\", &apply_to_all<mtac::ConstantFolding>, function);\n\n optimized |= debug(\"Constant propagation\", &data_flow_optimization<mtac::ConstantPropagationProblem>, function);\n optimized |= debug(\"Offset Constant Propagation\", &data_flow_optimization<mtac::OffsetConstantPropagationProblem>, function);\n\n \/\/If there was optimizations here, better to try again before perfoming common subexpression\n if(optimized){\n continue;\n }\n\n optimized |= debug(\"Common Subexpression Elimination\", &data_flow_optimization<mtac::CommonSubexpressionElimination>, function);\n\n optimized |= debug(\"Math Propagation\", &apply_to_basic_blocks_two_pass<mtac::MathPropagation>, function);\n\n optimized |= debug(\"Optimize Branches\", &mtac::optimize_branches, function);\n optimized |= debug(\"Optimize Concat\", &mtac::optimize_concat, function, pool);\n optimized |= debug(\"Remove dead basic block\", &mtac::remove_dead_basic_blocks, function);\n optimized |= debug(\"Merge basic block\", &mtac::merge_basic_blocks, function);\n\n remove_nop(function);\n \n optimized |= debug(\"Dead-Code Elimination\", &mtac::dead_code_elimination, function);\n } while (optimized);\n\n \/\/Remove variables that are not used after optimizations\n clean_variables(function);\n}\n\nvoid basic_optimize_function(std::shared_ptr<mtac::Function> function){\n if(option_defined(\"dev\")){\n std::cout << \"Start basic optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n debug(\"Constant folding\", apply_to_all<mtac::ConstantFolding>(function), function);\n \n \/*\/\/Liveness debugging\n mtac::LiveVariableAnalysisProblem problem;\n auto results = mtac::data_flow(function, problem);\n\n for(auto& block : function->getBasicBlocks()){\n auto it = block->statements.begin();\n auto end = block->statements.end();\n\n while(it != end){\n auto statement = *it;\n\n mtac::Printer printer;\n printer.printStatement(statement);\n std::cout << \"OUT{\";\n for(auto& var : results->OUT_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n std::cout << \"IN{\";\n for(auto& var : results->IN_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n\n ++it;\n }\n }*\/\n}\n\nvoid optimize_all_functions(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool){\n PerfsTimer timer(\"Whole optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector<std::thread> pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &string_pool, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n optimize_function(functions[i], string_pool); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n\nvoid mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> string_pool) const {\n bool optimized = false;\n\n do{\n mtac::remove_unused_functions(program);\n\n optimize_all_functions(program, string_pool);\n\n optimized = mtac::remove_empty_functions(program);\n optimized = mtac::inline_functions(program);\n } while(optimized);\n}\n\nvoid mtac::Optimizer::basic_optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> \/*string_pool*\/) const {\n PerfsTimer timer(\"Whole basic optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast<std::size_t>(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector<std::thread> pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n basic_optimize_function(functions[i]); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: layerimport.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2003-12-01 12:04:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_FORMS_LAYERIMPORT_HXX_\n#define _XMLOFF_FORMS_LAYERIMPORT_HXX_\n\n#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_\n#include <com\/sun\/star\/xml\/sax\/XAttributeList.hpp>\n#endif\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _XMLOFF_FORMATTRIBUTES_HXX_\n#include \"formattributes.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_CALLBACKS_HXX_\n#include \"callbacks.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_EVENTIMPORT_HXX_\n#include \"eventimport.hxx\"\n#endif\n#ifndef _REF_HXX\n#include <tools\/ref.hxx>\n#endif\n\nclass SvXMLImport;\nclass SvXMLImportContext;\nclass XMLPropertyHandlerFactory;\nclass SvXMLImportPropertyMapper;\nclass XMLPropStyleContext;\n\nSV_DECL_REF( SvXMLStylesContext );\n \/\/ unfortunately, we can't put this into our namespace, as the macro expands to (amongst others) a forward\n \/\/ declaration of the class name, which then would be in the namespace, too\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n class OAttribute2Property;\n\n \/\/=====================================================================\n \/\/= ControlReference\n \/\/=====================================================================\n \/\/\/ a structure containing a property set (the referred control) and a string (the list of referring controls)\n\/* struct ControlReference\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n xReferredControl;\n ::rtl::OUString\n sReferringControls;\n\n ControlReference(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxReferredControl,\n const ::rtl::OUString& _rReferringControls)\n :xReferredControl(_rxReferredControl)\n ,sReferringControls(_rReferringControls)\n {\n }\n };\n*\/\n\n \/\/=====================================================================\n \/\/= OFormLayerXMLImport_Impl\n \/\/=====================================================================\n class OFormLayerXMLImport_Impl\n :public OAttributeMetaData\n ,public IControlIdMap\n ,public IFormsImportContext\n ,public ODefaultEventAttacherManager\n {\n friend class OFormLayerXMLImport;\n\n protected:\n SvXMLImport& m_rImporter;\n OAttribute2Property m_aAttributeMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >\n m_xForms; \/\/ the forms of the currently imported page\n SvXMLStylesContext* m_pAutoStyles;\n\n protected:\n \/\/ style handling\n ::vos::ORef< XMLPropertyHandlerFactory > m_xPropertyHandlerFactory;\n ::vos::ORef< SvXMLImportPropertyMapper > m_xImportMapper;\n\n DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >, MapString2PropertySet );\n DECLARE_STL_MAP( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >, MapString2PropertySet, ODrawPageCompare, MapDrawPage2Map);\n\n MapDrawPage2Map m_aControlIds; \/\/ ids of the controls on all known page\n MapDrawPage2MapIterator m_aCurrentPageIds; \/\/ ifs of the controls on the current page\n\n typedef ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >, ::rtl::OUString >\n ModelStringPair;\n ::std::vector< ModelStringPair >\n m_aControlReferences; \/\/ control reference descriptions for current page\n ::std::vector< ModelStringPair >\n m_aCellValueBindings; \/\/ information about controls bound to spreadsheet cells\n ::std::vector< ModelStringPair >\n m_aCellRangeListSources;\/\/ information about controls bound to spreadsheet cell range list sources\n\n public:\n \/\/ IControlIdMap\n virtual void registerControlId(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,\n const ::rtl::OUString& _rId);\n virtual void registerControlReferences(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,\n const ::rtl::OUString& _rReferringControls);\n\n \/\/ IFormsImportContext\n virtual IControlIdMap& getControlIdMap();\n virtual OAttribute2Property& getAttributeMap();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n getServiceFactory();\n virtual SvXMLImport& getGlobalContext();\n const SvXMLStyleContext* getStyleElement(const ::rtl::OUString& _rStyleName) const;\n virtual void enterEventContext();\n virtual void leaveEventContext();\n void applyControlNumberStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rControlNumerStyleName\n );\n virtual void registerCellValueBinding(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rCellAddress\n );\n\n virtual void registerCellRangeListSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rCellRangeAddress\n );\n\n protected:\n OFormLayerXMLImport_Impl(SvXMLImport& _rImporter);\n ~OFormLayerXMLImport_Impl();\n\n \/** retrieves the property mapper form form related auto styles.\n *\/\n ::vos::ORef< SvXMLImportPropertyMapper > getStylePropertyMapper() const;\n\n \/** start importing the forms of the given page\n *\/\n void startPage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& _rxDrawPage);\n\n \/** end importing the forms of the current page\n *\/\n void endPage();\n\n \/** creates an import context for the office:forms element\n *\/\n SvXMLImportContext* createOfficeFormsContext(\n SvXMLImport& _rImport,\n sal_uInt16 _nPrefix,\n const rtl::OUString& _rLocalName);\n\n \/** create an <type>SvXMLImportContext<\/type> instance which is able to import the <form:form>\n element.\n *\/\n SvXMLImportContext* createContext(\n const sal_uInt16 _nPrefix,\n const rtl::OUString& _rLocalName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttribs);\n\n \/**\n *\/\n XMLPropStyleContext* createControlStyleContext(\n sal_uInt16 _nPrefix,\n const ::rtl::OUString& _rLocalName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList,\n SvXMLStylesContext& _rParentStyles,\n sal_uInt16 _nFamily = 0,\n sal_Bool _bDefaultStyle = sal_False\n );\n\n \/** get the control with the given id\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n lookupControlId(const ::rtl::OUString& _rControlId);\n\n \/** seek to the given page\n *\/\n void seekPage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& _rxDrawPage);\n\n \/** announces the auto-style context to the form importer\n *\/\n void setAutoStyleContext(SvXMLStylesContext* _pNewContext);\n\n \/** to be called when the document has been completely imported\n\n <p>For some documents (currently: only some spreadsheet documents) it's necessary\n do to a post processing, since not all information from the file can be processed\n if the document is not completed, yet.<\/p>\n *\/\n void documentDone( );\n };\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n#endif \/\/ _XMLOFF_FORMS_LAYERIMPORT_HXX_\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.11.24.2 2003\/11\/24 15:19:46 obo\n * undo last change\n *\n * Revision 1.11 2003\/10\/21 08:40:18 obo\n * INTEGRATION: CWS formcelllinkage (1.10.160); FILE MERGED\n * 2003\/10\/01 09:55:23 fs 1.10.160.1: #i18994# merging the changes from the CWS fs002\n *\n * Revision 1.10.160.1 2003\/10\/01 09:55:23 fs\n * #i18994# merging the changes from the CWS fs002\n *\n * Revision 1.10.156.1 2003\/09\/25 14:28:41 fs\n * #18994# merging the changes from cws_srx645_fs002 branch\n *\n * Revision 1.10.152.1 2003\/09\/17 12:26:56 fs\n * #18999# #19367# persistence for cell value and cell range bindings\n *\n * Revision 1.10 2002\/10\/25 13:17:04 fs\n * #104402# importing grid column styles now\n *\n * Revision 1.9 2001\/05\/28 14:59:18 fs\n * #86712# added control number style related functionality\n *\n * Revision 1.8 2001\/03\/20 13:39:58 fs\n * #83970# +createOfficeFormsContext\n *\n * Revision 1.7 2001\/02\/01 09:46:47 fs\n * no own style handling anymore - the shape exporter is responsible for our styles now\n *\n * Revision 1.6 2001\/01\/24 09:34:40 fs\n * +enter-\/leaveEventContext\n *\n * Revision 1.5 2001\/01\/02 15:58:22 fs\n * event ex- & import\n *\n * Revision 1.4 2000\/12\/18 15:14:35 fs\n * some changes ... now exporting\/importing styles\n *\n * Revision 1.3 2000\/12\/13 10:40:15 fs\n * new import related implementations - at this version, we should be able to import everything we export (which is all except events and styles)\n *\n * Revision 1.2 2000\/12\/12 12:01:05 fs\n * new implementations for the import - still under construction\n *\n * Revision 1.1 2000\/12\/06 17:31:42 fs\n * initial checkin - implementations for formlayer import\/export - still under construction\n *\n *\n * Revision 1.0 04.12.00 15:48:40 fs\n ************************************************************************\/\n\n<commit_msg>INTEGRATION: CWS oasis (1.12.66); FILE MERGED 2004\/06\/08 14:49:18 mib 1.12.66.1: - #i20153#: form controls<commit_after>\/*************************************************************************\n *\n * $RCSfile: layerimport.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 08:14:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_FORMS_LAYERIMPORT_HXX_\n#define _XMLOFF_FORMS_LAYERIMPORT_HXX_\n\n#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_\n#include <com\/sun\/star\/xml\/sax\/XAttributeList.hpp>\n#endif\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _XMLOFF_FORMATTRIBUTES_HXX_\n#include \"formattributes.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_CALLBACKS_HXX_\n#include \"callbacks.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_EVENTIMPORT_HXX_\n#include \"eventimport.hxx\"\n#endif\n#ifndef _REF_HXX\n#include <tools\/ref.hxx>\n#endif\n\nclass SvXMLImport;\nclass SvXMLImportContext;\nclass XMLPropertyHandlerFactory;\nclass SvXMLImportPropertyMapper;\nclass XMLPropStyleContext;\n\nSV_DECL_REF( SvXMLStylesContext );\n \/\/ unfortunately, we can't put this into our namespace, as the macro expands to (amongst others) a forward\n \/\/ declaration of the class name, which then would be in the namespace, too\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n class OAttribute2Property;\n\n \/\/=====================================================================\n \/\/= ControlReference\n \/\/=====================================================================\n \/\/\/ a structure containing a property set (the referred control) and a string (the list of referring controls)\n\/* struct ControlReference\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n xReferredControl;\n ::rtl::OUString\n sReferringControls;\n\n ControlReference(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxReferredControl,\n const ::rtl::OUString& _rReferringControls)\n :xReferredControl(_rxReferredControl)\n ,sReferringControls(_rReferringControls)\n {\n }\n };\n*\/\n\n \/\/=====================================================================\n \/\/= OFormLayerXMLImport_Impl\n \/\/=====================================================================\n class OFormLayerXMLImport_Impl\n :public OAttributeMetaData\n ,public IControlIdMap\n ,public IFormsImportContext\n ,public ODefaultEventAttacherManager\n {\n friend class OFormLayerXMLImport;\n\n protected:\n SvXMLImport& m_rImporter;\n OAttribute2Property m_aAttributeMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >\n m_xForms; \/\/ the forms of the currently imported page\n SvXMLStylesContext* m_pAutoStyles;\n\n protected:\n \/\/ style handling\n ::vos::ORef< XMLPropertyHandlerFactory > m_xPropertyHandlerFactory;\n ::vos::ORef< SvXMLImportPropertyMapper > m_xImportMapper;\n\n DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >, MapString2PropertySet );\n DECLARE_STL_MAP( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >, MapString2PropertySet, ODrawPageCompare, MapDrawPage2Map);\n\n MapDrawPage2Map m_aControlIds; \/\/ ids of the controls on all known page\n MapDrawPage2MapIterator m_aCurrentPageIds; \/\/ ifs of the controls on the current page\n\n typedef ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >, ::rtl::OUString >\n ModelStringPair;\n ::std::vector< ModelStringPair >\n m_aControlReferences; \/\/ control reference descriptions for current page\n ::std::vector< ModelStringPair >\n m_aCellValueBindings; \/\/ information about controls bound to spreadsheet cells\n ::std::vector< ModelStringPair >\n m_aCellRangeListSources;\/\/ information about controls bound to spreadsheet cell range list sources\n\n public:\n \/\/ IControlIdMap\n virtual void registerControlId(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,\n const ::rtl::OUString& _rId);\n virtual void registerControlReferences(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl,\n const ::rtl::OUString& _rReferringControls);\n\n \/\/ IFormsImportContext\n virtual IControlIdMap& getControlIdMap();\n virtual OAttribute2Property& getAttributeMap();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n getServiceFactory();\n virtual SvXMLImport& getGlobalContext();\n const SvXMLStyleContext* getStyleElement(const ::rtl::OUString& _rStyleName) const;\n virtual void enterEventContext();\n virtual void leaveEventContext();\n void applyControlNumberStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rControlNumerStyleName\n );\n virtual void registerCellValueBinding(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rCellAddress\n );\n\n virtual void registerCellRangeListSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel,\n const ::rtl::OUString& _rCellRangeAddress\n );\n\n protected:\n OFormLayerXMLImport_Impl(SvXMLImport& _rImporter);\n ~OFormLayerXMLImport_Impl();\n\n \/** retrieves the property mapper form form related auto styles.\n *\/\n ::vos::ORef< SvXMLImportPropertyMapper > getStylePropertyMapper() const;\n\n \/** start importing the forms of the given page\n *\/\n void startPage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& _rxDrawPage);\n\n \/** end importing the forms of the current page\n *\/\n void endPage();\n\n \/** creates an import context for the office:forms element\n *\/\n SvXMLImportContext* createOfficeFormsContext(\n SvXMLImport& _rImport,\n sal_uInt16 _nPrefix,\n const rtl::OUString& _rLocalName);\n\n \/** create an <type>SvXMLImportContext<\/type> instance which is able to import the <form:form>\n element.\n *\/\n SvXMLImportContext* createContext(\n const sal_uInt16 _nPrefix,\n const rtl::OUString& _rLocalName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttribs);\n\n \/** get the control with the given id\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n lookupControlId(const ::rtl::OUString& _rControlId);\n\n \/** seek to the given page\n *\/\n void seekPage(\n const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& _rxDrawPage);\n\n \/** announces the auto-style context to the form importer\n *\/\n void setAutoStyleContext(SvXMLStylesContext* _pNewContext);\n\n \/** to be called when the document has been completely imported\n\n <p>For some documents (currently: only some spreadsheet documents) it's necessary\n do to a post processing, since not all information from the file can be processed\n if the document is not completed, yet.<\/p>\n *\/\n void documentDone( );\n };\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n#endif \/\/ _XMLOFF_FORMS_LAYERIMPORT_HXX_\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.12.66.1 2004\/06\/08 14:49:18 mib\n * - #i20153#: form controls\n *\n * Revision 1.12 2003\/12\/01 12:04:46 rt\n * INTEGRATION: CWS geordi2q09 (1.11.24); FILE MERGED\n * 2003\/11\/24 15:19:46 obo 1.11.24.2: undo last change\n * 2003\/11\/21 17:04:39 obo 1.11.24.1: #111934# join CWS comboboxlink\n *\n * Revision 1.11.24.2 2003\/11\/24 15:19:46 obo\n * undo last change\n *\n * Revision 1.11 2003\/10\/21 08:40:18 obo\n * INTEGRATION: CWS formcelllinkage (1.10.160); FILE MERGED\n * 2003\/10\/01 09:55:23 fs 1.10.160.1: #i18994# merging the changes from the CWS fs002\n *\n * Revision 1.10.160.1 2003\/10\/01 09:55:23 fs\n * #i18994# merging the changes from the CWS fs002\n *\n * Revision 1.10.156.1 2003\/09\/25 14:28:41 fs\n * #18994# merging the changes from cws_srx645_fs002 branch\n *\n * Revision 1.10.152.1 2003\/09\/17 12:26:56 fs\n * #18999# #19367# persistence for cell value and cell range bindings\n *\n * Revision 1.10 2002\/10\/25 13:17:04 fs\n * #104402# importing grid column styles now\n *\n * Revision 1.9 2001\/05\/28 14:59:18 fs\n * #86712# added control number style related functionality\n *\n * Revision 1.8 2001\/03\/20 13:39:58 fs\n * #83970# +createOfficeFormsContext\n *\n * Revision 1.7 2001\/02\/01 09:46:47 fs\n * no own style handling anymore - the shape exporter is responsible for our styles now\n *\n * Revision 1.6 2001\/01\/24 09:34:40 fs\n * +enter-\/leaveEventContext\n *\n * Revision 1.5 2001\/01\/02 15:58:22 fs\n * event ex- & import\n *\n * Revision 1.4 2000\/12\/18 15:14:35 fs\n * some changes ... now exporting\/importing styles\n *\n * Revision 1.3 2000\/12\/13 10:40:15 fs\n * new import related implementations - at this version, we should be able to import everything we export (which is all except events and styles)\n *\n * Revision 1.2 2000\/12\/12 12:01:05 fs\n * new implementations for the import - still under construction\n *\n * Revision 1.1 2000\/12\/06 17:31:42 fs\n * initial checkin - implementations for formlayer import\/export - still under construction\n *\n *\n * Revision 1.0 04.12.00 15:48:40 fs\n ************************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * @file: adaboost_main.cpp\n * @author: Udit Saxena\n *\n * Implementation of the AdaBoost main file\n *\n * @code\n * @article{Schapire:1999:IBA:337859.337870,\n * author = {Schapire, Robert E. and Singer, Yoram},\n * title = {Improved Boosting Algorithms Using Confidence-rated Predictions},\n * journal = {Mach. Learn.},\n * issue_date = {Dec. 1999},\n * volume = {37},\n * number = {3},\n * month = dec,\n * year = {1999},\n * issn = {0885-6125},\n * pages = {297--336},\n * numpages = {40},\n * url = {http:\/\/dx.doi.org\/10.1023\/A:1007614523901},\n * doi = {10.1023\/A:1007614523901},\n * acmid = {337870},\n * publisher = {Kluwer Academic Publishers},\n * address = {Hingham, MA, USA},\n * keywords = {boosting algorithms, decision trees, multiclass classification,\n * output coding\n * }\n * @endcode\n *\n *\/\n\n#include <mlpack\/core.hpp>\n#include \"adaboost.hpp\"\n\nusing namespace mlpack;\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack::adaboost;\n\nPROGRAM_INFO(\"AdaBoost\",\"This program implements the AdaBoost (or Adaptive Boost)\"\n \" algorithm. The variant of AdaBoost implemented here is AdaBoost.mh. It uses a\"\n \" weak learner, either of Decision Stumps or a Perceptron, and over many\"\n \" iterations, creates a strong learner. It runs these iterations till a tolerance\"\n \" value is crossed for change in the value of rt.\"\n \"\\n\"\n \"This program allows training of a adaboost object, and then application of \"\n \"the strong learner to a test dataset. To train \"\n \"a training dataset must be passed to --train_file (-t). Labels can either\"\n \" be present as the last dimension of the training dataset, or given \"\n \"explicitly with the --labels_file (-l) parameter.\\n\"\n \"\\n\"\n \"A test file is given through the --test_file (-T) parameter. The \"\n \"predicted labels for the test set will be stored in the file specified by \"\n \"the --output_file (-o) parameter.\");\n\n\/\/necessary parameters\nPARAM_STRING_REQ(\"train_file\", \"A file containing the training set.\", \"t\");\nPARAM_STRING_REQ(\"labels_file\", \"A file containing labels for the training set.\",\n \"l\");\nPARAM_STRING_REQ(\"test_file\", \"A file containing the test set.\", \"T\");\n\n\/\/optional parameters.\nPARAM_STRING(\"output\", \"The file in which the predicted labels for the test set\"\n \" will be written.\", \"o\", \"output.csv\");\nPARAM_INT(\"iterations\",\"The maximum number of boosting iterations \"\n \"to be run\", \"i\", 1000);\nPARAM_DOUBLE(\"tolerance\",\"The tolerance for change in values of rt\",\"e\",1e-10);\n\nint main(int argc, char *argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n const string trainingDataFilename = CLI::GetParam<string>(\"train_file\");\n mat trainingData;\n data::Load(trainingDataFilename, trainingData, true);\n\n const string labelsFilename = CLI::GetParam<string>(\"labels_file\");\n \/\/ Load labels.\n mat labelsIn;\n \/\/ data::Load(labelsFilename, labelsIn, true);\n\n if (CLI::HasParam(\"labels_file\"))\n {\n const string labelsFilename = CLI::GetParam<string>(\"labels_file\");\n \/\/ Load labels.\n data::Load(labelsFilename, labelsIn, true);\n\n \/\/ Do the labels need to be transposed?\n if (labelsIn.n_rows == 1)\n labelsIn = labelsIn.t();\n }\n else\n {\n \/\/ Extract the labels as the last\n Log::Info << \"Using the last dimension of training set as labels.\" << endl;\n\n labelsIn = trainingData.row(trainingData.n_rows - 1).t();\n trainingData.shed_row(trainingData.n_rows - 1);\n }\n\n \/\/ helpers for normalizing the labels\n Col<size_t> labels;\n vec mappings;\n\n \/\/ Do the labels need to be transposed?\n if (labelsIn.n_rows == 1)\n labelsIn = labelsIn.t();\n\n \/\/ normalize the labels\n data::NormalizeLabels(labelsIn.unsafe_col(0), labels, mappings);\n\n const string testingDataFilename = CLI::GetParam<string>(\"test_file\");\n mat testingData;\n data::Load(testingDataFilename, testingData, true);\n\n const double tolerance = CLI::GetParam<double>(\"tolerance\");\n\n if (testingData.n_rows != trainingData.n_rows)\n Log::Fatal << \"Test data dimensionality (\" << testingData.n_rows << \") \"\n << \"must be the same as training data (\" << trainingData.n_rows - 1\n << \")!\" << std::endl;\n int iterations = CLI::GetParam<int>(\"iterations\");\n\n \/\/ define your own weak learner, perceptron in this case.\n \/\/ defining the number of iterations of the perceptron.\n int iter = 400;\n\n perceptron::Perceptron<> p(trainingData, labels.t(), iter);\n\n Timer::Start(\"Training\");\n AdaBoost<> a(trainingData, labels.t(), iterations, tolerance, p);\n Timer::Stop(\"Training\");\n\n Row<size_t> predictedLabels(testingData.n_cols);\n Timer::Start(\"testing\");\n a.Classify(testingData, predictedLabels);\n Timer::Stop(\"testing\");\n\n vec results;\n data::RevertLabels(predictedLabels.t(), mappings, results);\n\n \/\/ Save the predicted labels in a transposed form as output.\n const string outputFilename = CLI::GetParam<string>(\"output_file\");\n data::Save(outputFilename, results, true, false);\n return 0;\n}<commit_msg>Fix Adaboost executable for Perceptron API change.<commit_after>\/*\n * @file: adaboost_main.cpp\n * @author: Udit Saxena\n *\n * Implementation of the AdaBoost main file\n *\n * @code\n * @article{Schapire:1999:IBA:337859.337870,\n * author = {Schapire, Robert E. and Singer, Yoram},\n * title = {Improved Boosting Algorithms Using Confidence-rated Predictions},\n * journal = {Mach. Learn.},\n * issue_date = {Dec. 1999},\n * volume = {37},\n * number = {3},\n * month = dec,\n * year = {1999},\n * issn = {0885-6125},\n * pages = {297--336},\n * numpages = {40},\n * url = {http:\/\/dx.doi.org\/10.1023\/A:1007614523901},\n * doi = {10.1023\/A:1007614523901},\n * acmid = {337870},\n * publisher = {Kluwer Academic Publishers},\n * address = {Hingham, MA, USA},\n * keywords = {boosting algorithms, decision trees, multiclass classification,\n * output coding\n * }\n * @endcode\n *\n *\/\n\n#include <mlpack\/core.hpp>\n#include \"adaboost.hpp\"\n\nusing namespace mlpack;\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack::adaboost;\n\nPROGRAM_INFO(\"AdaBoost\",\"This program implements the AdaBoost (or Adaptive Boost)\"\n \" algorithm. The variant of AdaBoost implemented here is AdaBoost.mh. It uses a\"\n \" weak learner, either of Decision Stumps or a Perceptron, and over many\"\n \" iterations, creates a strong learner. It runs these iterations till a tolerance\"\n \" value is crossed for change in the value of rt.\"\n \"\\n\"\n \"This program allows training of a adaboost object, and then application of \"\n \"the strong learner to a test dataset. To train \"\n \"a training dataset must be passed to --train_file (-t). Labels can either\"\n \" be present as the last dimension of the training dataset, or given \"\n \"explicitly with the --labels_file (-l) parameter.\\n\"\n \"\\n\"\n \"A test file is given through the --test_file (-T) parameter. The \"\n \"predicted labels for the test set will be stored in the file specified by \"\n \"the --output_file (-o) parameter.\");\n\n\/\/necessary parameters\nPARAM_STRING_REQ(\"train_file\", \"A file containing the training set.\", \"t\");\nPARAM_STRING_REQ(\"labels_file\", \"A file containing labels for the training set.\",\n \"l\");\nPARAM_STRING_REQ(\"test_file\", \"A file containing the test set.\", \"T\");\n\n\/\/optional parameters.\nPARAM_STRING(\"output\", \"The file in which the predicted labels for the test set\"\n \" will be written.\", \"o\", \"output.csv\");\nPARAM_INT(\"iterations\",\"The maximum number of boosting iterations \"\n \"to be run\", \"i\", 1000);\nPARAM_DOUBLE(\"tolerance\",\"The tolerance for change in values of rt\",\"e\",1e-10);\n\nint main(int argc, char *argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n const string trainingDataFilename = CLI::GetParam<string>(\"train_file\");\n mat trainingData;\n data::Load(trainingDataFilename, trainingData, true);\n\n const string labelsFilename = CLI::GetParam<string>(\"labels_file\");\n \/\/ Load labels.\n mat labelsIn;\n \/\/ data::Load(labelsFilename, labelsIn, true);\n\n if (CLI::HasParam(\"labels_file\"))\n {\n const string labelsFilename = CLI::GetParam<string>(\"labels_file\");\n \/\/ Load labels.\n data::Load(labelsFilename, labelsIn, true);\n\n \/\/ Do the labels need to be transposed?\n if (labelsIn.n_rows == 1)\n labelsIn = labelsIn.t();\n }\n else\n {\n \/\/ Extract the labels as the last\n Log::Info << \"Using the last dimension of training set as labels.\" << endl;\n\n labelsIn = trainingData.row(trainingData.n_rows - 1).t();\n trainingData.shed_row(trainingData.n_rows - 1);\n }\n\n \/\/ helpers for normalizing the labels\n Col<size_t> labels;\n vec mappings;\n\n \/\/ Do the labels need to be transposed?\n if (labelsIn.n_rows == 1)\n labelsIn = labelsIn.t();\n\n \/\/ normalize the labels\n data::NormalizeLabels(labelsIn.unsafe_col(0), labels, mappings);\n\n const string testingDataFilename = CLI::GetParam<string>(\"test_file\");\n mat testingData;\n data::Load(testingDataFilename, testingData, true);\n\n const double tolerance = CLI::GetParam<double>(\"tolerance\");\n\n if (testingData.n_rows != trainingData.n_rows)\n Log::Fatal << \"Test data dimensionality (\" << testingData.n_rows << \") \"\n << \"must be the same as training data (\" << trainingData.n_rows - 1\n << \")!\" << std::endl;\n int iterations = CLI::GetParam<int>(\"iterations\");\n\n \/\/ define your own weak learner, perceptron in this case.\n \/\/ defining the number of iterations of the perceptron.\n int iter = 400;\n\n perceptron::Perceptron<> p(trainingData, labels.t(), max(labels) + 1, iter);\n\n Timer::Start(\"Training\");\n AdaBoost<> a(trainingData, labels.t(), iterations, tolerance, p);\n Timer::Stop(\"Training\");\n\n Row<size_t> predictedLabels(testingData.n_cols);\n Timer::Start(\"testing\");\n a.Classify(testingData, predictedLabels);\n Timer::Stop(\"testing\");\n\n vec results;\n data::RevertLabels(predictedLabels.t(), mappings, results);\n\n \/\/ Save the predicted labels in a transposed form as output.\n const string outputFilename = CLI::GetParam<string>(\"output_file\");\n data::Save(outputFilename, results, true, false);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file dtnn_rules_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of DualTreeKMeansRules.\n *\/\n#ifndef __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP\n#define __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP\n\n#include \"dtnn_rules.hpp\"\n\nnamespace mlpack {\nnamespace kmeans {\n\ntemplate<typename MetricType, typename TreeType>\nDTNNKMeansRules<MetricType, TreeType>::DTNNKMeansRules(\n const arma::mat& centroids,\n const arma::mat& dataset,\n arma::Col<size_t>& assignments,\n arma::vec& upperBounds,\n arma::vec& lowerBounds,\n MetricType& metric,\n const std::vector<bool>& prunedPoints,\n const std::vector<size_t>& oldFromNewCentroids,\n std::vector<bool>& visited) :\n centroids(centroids),\n dataset(dataset),\n assignments(assignments),\n upperBounds(upperBounds),\n lowerBounds(lowerBounds),\n metric(metric),\n prunedPoints(prunedPoints),\n oldFromNewCentroids(oldFromNewCentroids),\n visited(visited),\n baseCases(0),\n scores(0),\n lastQueryIndex(dataset.n_cols),\n lastReferenceIndex(centroids.n_cols)\n{\n \/\/ We must set the traversal info last query and reference node pointers to\n \/\/ something that is both invalid (i.e. not a tree node) and not NULL. We'll\n \/\/ use the this pointer.\n traversalInfo.LastQueryNode() = (TreeType*) this;\n traversalInfo.LastReferenceNode() = (TreeType*) this;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline force_inline double DTNNKMeansRules<MetricType, TreeType>::BaseCase(\n const size_t queryIndex,\n const size_t referenceIndex)\n{\n if (prunedPoints[queryIndex])\n return 0.0; \/\/ Returning 0 shouldn't be a problem.\n\n \/\/ If we have already performed this base case, then do not perform it again.\n if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex))\n return lastBaseCase;\n\n \/\/ Any base cases imply that we will get a result.\n visited[queryIndex] = true;\n\n \/\/ Calculate the distance.\n ++baseCases;\n const double distance = metric.Evaluate(dataset.col(queryIndex),\n centroids.col(referenceIndex));\n\n if (distance < upperBounds[queryIndex])\n {\n lowerBounds[queryIndex] = upperBounds[queryIndex];\n upperBounds[queryIndex] = distance;\n assignments[queryIndex] = (tree::TreeTraits<TreeType>::RearrangesDataset) ?\n oldFromNewCentroids[referenceIndex] : referenceIndex;\n }\n else if (distance < lowerBounds[queryIndex])\n {\n lowerBounds[queryIndex] = distance;\n }\n \n \/\/ Cache this information for the next time BaseCase() is called.\n lastQueryIndex = queryIndex;\n lastReferenceIndex = referenceIndex;\n lastBaseCase = distance;\n\n return distance;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Score(\n const size_t queryIndex,\n TreeType& \/* referenceNode *\/)\n{\n \/\/ If the query point has already been pruned, then don't recurse further.\n if (prunedPoints[queryIndex])\n return DBL_MAX;\n\n \/\/ No pruning at this level; we're not likely to encounter a single query\n \/\/ point with a reference node..\n return 0;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Score(\n TreeType& queryNode,\n TreeType& referenceNode)\n{\n if (queryNode.Stat().StaticPruned() == true)\n return DBL_MAX;\n\n \/\/ Pruned() for the root node must never be set to size_t(-1).\n if (queryNode.Stat().Pruned() == size_t(-1))\n {\n queryNode.Stat().Pruned() = queryNode.Parent()->Stat().Pruned();\n queryNode.Stat().LowerBound() = queryNode.Parent()->Stat().LowerBound();\n queryNode.Stat().Owner() = queryNode.Parent()->Stat().Owner();\n }\n\n if (queryNode.Stat().Pruned() == centroids.n_cols)\n return DBL_MAX;\n\n \/\/ This looks a lot like the hackery used in NeighborSearchRules to avoid\n \/\/ distance computations. We'll use the traversal info to see if a\n \/\/ parent-child or parent-parent prune is possible.\n const double queryParentDist = queryNode.ParentDistance();\n const double queryDescDist = queryNode.FurthestDescendantDistance();\n const double refParentDist = referenceNode.ParentDistance();\n const double refDescDist = referenceNode.FurthestDescendantDistance();\n const double lastScore = traversalInfo.LastScore();\n double adjustedScore;\n double score = 0.0;\n\n \/\/ We want to set adjustedScore to be the distance between the centroid of the\n \/\/ last query node and last reference node. We will do this by adjusting the\n \/\/ last score. In some cases, we can just use the last base case.\n if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)\n {\n adjustedScore = traversalInfo.LastBaseCase();\n }\n else if (lastScore == 0.0) \/\/ Nothing we can do here.\n {\n adjustedScore = 0.0;\n }\n else\n {\n \/\/ The last score is equal to the distance between the centroids minus the\n \/\/ radii of the query and reference bounds along the axis of the line\n \/\/ between the two centroids. In the best case, these radii are the\n \/\/ furthest descendant distances, but that is not always true. It would\n \/\/ take too long to calculate the exact radii, so we are forced to use\n \/\/ MinimumBoundDistance() as a lower-bound approximation.\n const double lastQueryDescDist =\n traversalInfo.LastQueryNode()->MinimumBoundDistance();\n const double lastRefDescDist =\n traversalInfo.LastReferenceNode()->MinimumBoundDistance();\n adjustedScore = lastScore + lastQueryDescDist;\n adjustedScore = lastScore + lastRefDescDist;\n }\n\n \/\/ Assemble an adjusted score. For nearest neighbor search, this adjusted\n \/\/ score is a lower bound on MinDistance(queryNode, referenceNode) that is\n \/\/ assembled without actually calculating MinDistance(). For furthest\n \/\/ neighbor search, it is an upper bound on\n \/\/ MaxDistance(queryNode, referenceNode). If the traversalInfo isn't usable\n \/\/ then the node should not be pruned by this.\n if (traversalInfo.LastQueryNode() == queryNode.Parent())\n {\n const double queryAdjust = queryParentDist + queryDescDist;\n adjustedScore -= queryAdjust;\n }\n else if (traversalInfo.LastQueryNode() == &queryNode)\n {\n adjustedScore -= queryDescDist;\n }\n else\n {\n \/\/ The last query node wasn't this query node or its parent. So we force\n \/\/ the adjustedScore to be such that this combination can't be pruned here,\n \/\/ because we don't really know anything about it.\n\n \/\/ It would be possible to modify this section to try and make a prune based\n \/\/ on the query descendant distance and the distance between the query node\n \/\/ and last traversal query node, but this case doesn't actually happen for\n \/\/ kd-trees or cover trees.\n adjustedScore = 0.0;\n }\n if (traversalInfo.LastReferenceNode() == referenceNode.Parent())\n {\n const double refAdjust = refParentDist + refDescDist;\n adjustedScore -= refAdjust;\n }\n else if (traversalInfo.LastReferenceNode() == &referenceNode)\n {\n adjustedScore -= refDescDist;\n }\n else\n {\n \/\/ The last reference node wasn't this reference node or its parent. So we\n \/\/ force the adjustedScore to be such that this combination can't be pruned\n \/\/ here, because we don't really know anything about it.\n\n \/\/ It would be possible to modify this section to try and make a prune based\n \/\/ on the reference descendant distance and the distance between the\n \/\/ reference node and last traversal reference node, but this case doesn't\n \/\/ actually happen for kd-trees or cover trees.\n adjustedScore = 0.0;\n }\n\n \/\/ Now, check if we can prune.\n \/\/Log::Warn << \"adjusted score: \" << adjustedScore << \".\\n\";\n if (adjustedScore > queryNode.Stat().UpperBound())\n {\n\/\/ Log::Warn << \"Pre-emptive prune!\\n\";\n if (!(tree::TreeTraits<TreeType>::FirstPointIsCentroid && score == 0.0))\n {\n \/\/ There isn't any need to set the traversal information because no\n \/\/ descendant combinations will be visited, and those are the only\n \/\/ combinations that would depend on the traversal information.\n if (adjustedScore < queryNode.Stat().LowerBound())\n {\n \/\/ If this might affect the lower bound, make it more exact.\n queryNode.Stat().LowerBound() = std::min(queryNode.Stat().LowerBound(),\n queryNode.MinDistance(&referenceNode));\n ++scores;\n }\n\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n score = DBL_MAX;\n }\n }\n\n if (score != DBL_MAX)\n {\n \/\/ Get minimum and maximum distances.\n const math::Range distances = queryNode.RangeDistance(&referenceNode);\n\n score = distances.Lo();\n ++scores;\n if (distances.Lo() > queryNode.Stat().UpperBound())\n {\n \/\/ The reference node can own no points in this query node. We may\n \/\/ improve the lower bound on pruned nodes, though.\n if (distances.Lo() < queryNode.Stat().LowerBound())\n queryNode.Stat().LowerBound() = distances.Lo();\n\n \/\/ This assumes that reference clusters don't appear elsewhere in the\n \/\/ tree.\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n score = DBL_MAX;\n }\n else if (distances.Hi() < queryNode.Stat().UpperBound())\n {\n \/\/ Tighten upper bound.\n const double tighterBound =\n queryNode.MaxDistance(centroids.col(referenceNode.Descendant(0)));\n ++scores; \/\/ Count extra distance calculation.\n\n if (tighterBound <= queryNode.Stat().UpperBound())\n {\n \/\/ We can improve the best estimate.\n queryNode.Stat().UpperBound() = tighterBound;\n \/\/ If this node has only one descendant, then it may be the owner.\n if (referenceNode.NumDescendants() == 1)\n queryNode.Stat().Owner() =\n (tree::TreeTraits<TreeType>::RearrangesDataset) ?\n oldFromNewCentroids[referenceNode.Descendant(0)] :\n referenceNode.Descendant(0);\n }\n }\n }\n\n \/\/ Is everything pruned?\n if (queryNode.Stat().Pruned() == centroids.n_cols - 1)\n {\n queryNode.Stat().Pruned() = centroids.n_cols; \/\/ Owner() is already set.\n return DBL_MAX;\n }\n\n \/\/ Set traversal information.\n traversalInfo.LastQueryNode() = &queryNode;\n traversalInfo.LastReferenceNode() = &referenceNode;\n traversalInfo.LastScore() = score;\n\n return score;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Rescore(\n const size_t \/* queryIndex *\/,\n TreeType& \/* referenceNode *\/,\n const double oldScore)\n{\n \/\/ No rescoring (for now).\n return oldScore;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Rescore(\n TreeType& queryNode,\n TreeType& referenceNode,\n const double oldScore)\n{\n if (oldScore == DBL_MAX)\n return DBL_MAX; \/\/ It's already pruned.\n\n \/\/ oldScore contains the minimum distance between queryNode and referenceNode.\n \/\/ In the time since Score() has been called, the upper bound *may* have\n \/\/ tightened. If it has tightened enough, we may prune this node now.\n if (oldScore > queryNode.Stat().UpperBound())\n {\n \/\/ We may still be able to improve the lower bound on pruned nodes.\n if (oldScore < queryNode.Stat().LowerBound())\n queryNode.Stat().LowerBound() = oldScore;\n\n \/\/ This assumes that reference clusters don't appear elsewhere in the tree.\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n return DBL_MAX;\n }\n\n \/\/ Also, check if everything has been pruned.\n if (queryNode.Stat().Pruned() == centroids.n_cols - 1)\n {\n queryNode.Stat().Pruned() = centroids.n_cols; \/\/ Owner() is already set.\n return DBL_MAX;\n }\n\n return oldScore;\n}\n\n} \/\/ namespace kmeans\n} \/\/ namespace mlpack\n\n#endif\n<commit_msg>Always mark the owner. This fixes some unusual and unexpected floating point errors where the owner will not actually be set.<commit_after>\/**\n * @file dtnn_rules_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of DualTreeKMeansRules.\n *\/\n#ifndef __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP\n#define __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP\n\n#include \"dtnn_rules.hpp\"\n\nnamespace mlpack {\nnamespace kmeans {\n\ntemplate<typename MetricType, typename TreeType>\nDTNNKMeansRules<MetricType, TreeType>::DTNNKMeansRules(\n const arma::mat& centroids,\n const arma::mat& dataset,\n arma::Col<size_t>& assignments,\n arma::vec& upperBounds,\n arma::vec& lowerBounds,\n MetricType& metric,\n const std::vector<bool>& prunedPoints,\n const std::vector<size_t>& oldFromNewCentroids,\n std::vector<bool>& visited) :\n centroids(centroids),\n dataset(dataset),\n assignments(assignments),\n upperBounds(upperBounds),\n lowerBounds(lowerBounds),\n metric(metric),\n prunedPoints(prunedPoints),\n oldFromNewCentroids(oldFromNewCentroids),\n visited(visited),\n baseCases(0),\n scores(0),\n lastQueryIndex(dataset.n_cols),\n lastReferenceIndex(centroids.n_cols)\n{\n \/\/ We must set the traversal info last query and reference node pointers to\n \/\/ something that is both invalid (i.e. not a tree node) and not NULL. We'll\n \/\/ use the this pointer.\n traversalInfo.LastQueryNode() = (TreeType*) this;\n traversalInfo.LastReferenceNode() = (TreeType*) this;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline force_inline double DTNNKMeansRules<MetricType, TreeType>::BaseCase(\n const size_t queryIndex,\n const size_t referenceIndex)\n{\n if (prunedPoints[queryIndex])\n return 0.0; \/\/ Returning 0 shouldn't be a problem.\n\n \/\/ If we have already performed this base case, then do not perform it again.\n if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex))\n return lastBaseCase;\n\n \/\/ Any base cases imply that we will get a result.\n visited[queryIndex] = true;\n\n \/\/ Calculate the distance.\n ++baseCases;\n const double distance = metric.Evaluate(dataset.col(queryIndex),\n centroids.col(referenceIndex));\n\n if (distance < upperBounds[queryIndex])\n {\n lowerBounds[queryIndex] = upperBounds[queryIndex];\n upperBounds[queryIndex] = distance;\n assignments[queryIndex] = (tree::TreeTraits<TreeType>::RearrangesDataset) ?\n oldFromNewCentroids[referenceIndex] : referenceIndex;\n }\n else if (distance < lowerBounds[queryIndex])\n {\n lowerBounds[queryIndex] = distance;\n }\n \n \/\/ Cache this information for the next time BaseCase() is called.\n lastQueryIndex = queryIndex;\n lastReferenceIndex = referenceIndex;\n lastBaseCase = distance;\n\n return distance;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Score(\n const size_t queryIndex,\n TreeType& \/* referenceNode *\/)\n{\n \/\/ If the query point has already been pruned, then don't recurse further.\n if (prunedPoints[queryIndex])\n return DBL_MAX;\n\n \/\/ No pruning at this level; we're not likely to encounter a single query\n \/\/ point with a reference node..\n return 0;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Score(\n TreeType& queryNode,\n TreeType& referenceNode)\n{\n if (queryNode.Stat().StaticPruned() == true)\n return DBL_MAX;\n\n \/\/ Pruned() for the root node must never be set to size_t(-1).\n if (queryNode.Stat().Pruned() == size_t(-1))\n {\n queryNode.Stat().Pruned() = queryNode.Parent()->Stat().Pruned();\n queryNode.Stat().LowerBound() = queryNode.Parent()->Stat().LowerBound();\n queryNode.Stat().Owner() = queryNode.Parent()->Stat().Owner();\n }\n\n if (queryNode.Stat().Pruned() == centroids.n_cols)\n return DBL_MAX;\n\n \/\/ This looks a lot like the hackery used in NeighborSearchRules to avoid\n \/\/ distance computations. We'll use the traversal info to see if a\n \/\/ parent-child or parent-parent prune is possible.\n const double queryParentDist = queryNode.ParentDistance();\n const double queryDescDist = queryNode.FurthestDescendantDistance();\n const double refParentDist = referenceNode.ParentDistance();\n const double refDescDist = referenceNode.FurthestDescendantDistance();\n const double lastScore = traversalInfo.LastScore();\n double adjustedScore;\n double score = 0.0;\n\n \/\/ We want to set adjustedScore to be the distance between the centroid of the\n \/\/ last query node and last reference node. We will do this by adjusting the\n \/\/ last score. In some cases, we can just use the last base case.\n if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)\n {\n adjustedScore = traversalInfo.LastBaseCase();\n }\n else if (lastScore == 0.0) \/\/ Nothing we can do here.\n {\n adjustedScore = 0.0;\n }\n else\n {\n \/\/ The last score is equal to the distance between the centroids minus the\n \/\/ radii of the query and reference bounds along the axis of the line\n \/\/ between the two centroids. In the best case, these radii are the\n \/\/ furthest descendant distances, but that is not always true. It would\n \/\/ take too long to calculate the exact radii, so we are forced to use\n \/\/ MinimumBoundDistance() as a lower-bound approximation.\n const double lastQueryDescDist =\n traversalInfo.LastQueryNode()->MinimumBoundDistance();\n const double lastRefDescDist =\n traversalInfo.LastReferenceNode()->MinimumBoundDistance();\n adjustedScore = lastScore + lastQueryDescDist;\n adjustedScore = lastScore + lastRefDescDist;\n }\n\n \/\/ Assemble an adjusted score. For nearest neighbor search, this adjusted\n \/\/ score is a lower bound on MinDistance(queryNode, referenceNode) that is\n \/\/ assembled without actually calculating MinDistance(). For furthest\n \/\/ neighbor search, it is an upper bound on\n \/\/ MaxDistance(queryNode, referenceNode). If the traversalInfo isn't usable\n \/\/ then the node should not be pruned by this.\n if (traversalInfo.LastQueryNode() == queryNode.Parent())\n {\n const double queryAdjust = queryParentDist + queryDescDist;\n adjustedScore -= queryAdjust;\n }\n else if (traversalInfo.LastQueryNode() == &queryNode)\n {\n adjustedScore -= queryDescDist;\n }\n else\n {\n \/\/ The last query node wasn't this query node or its parent. So we force\n \/\/ the adjustedScore to be such that this combination can't be pruned here,\n \/\/ because we don't really know anything about it.\n\n \/\/ It would be possible to modify this section to try and make a prune based\n \/\/ on the query descendant distance and the distance between the query node\n \/\/ and last traversal query node, but this case doesn't actually happen for\n \/\/ kd-trees or cover trees.\n adjustedScore = 0.0;\n }\n if (traversalInfo.LastReferenceNode() == referenceNode.Parent())\n {\n const double refAdjust = refParentDist + refDescDist;\n adjustedScore -= refAdjust;\n }\n else if (traversalInfo.LastReferenceNode() == &referenceNode)\n {\n adjustedScore -= refDescDist;\n }\n else\n {\n \/\/ The last reference node wasn't this reference node or its parent. So we\n \/\/ force the adjustedScore to be such that this combination can't be pruned\n \/\/ here, because we don't really know anything about it.\n\n \/\/ It would be possible to modify this section to try and make a prune based\n \/\/ on the reference descendant distance and the distance between the\n \/\/ reference node and last traversal reference node, but this case doesn't\n \/\/ actually happen for kd-trees or cover trees.\n adjustedScore = 0.0;\n }\n\n \/\/ Now, check if we can prune.\n if (adjustedScore > queryNode.Stat().UpperBound())\n {\n if (!(tree::TreeTraits<TreeType>::FirstPointIsCentroid && score == 0.0))\n {\n \/\/ There isn't any need to set the traversal information because no\n \/\/ descendant combinations will be visited, and those are the only\n \/\/ combinations that would depend on the traversal information.\n if (adjustedScore < queryNode.Stat().LowerBound())\n {\n \/\/ If this might affect the lower bound, make it more exact.\n queryNode.Stat().LowerBound() = std::min(queryNode.Stat().LowerBound(),\n queryNode.MinDistance(&referenceNode));\n ++scores;\n }\n\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n score = DBL_MAX;\n }\n }\n\n if (score != DBL_MAX)\n {\n \/\/ Get minimum and maximum distances.\n const math::Range distances = queryNode.RangeDistance(&referenceNode);\n\n score = distances.Lo();\n ++scores;\n if (distances.Lo() > queryNode.Stat().UpperBound())\n {\n \/\/ The reference node can own no points in this query node. We may\n \/\/ improve the lower bound on pruned nodes, though.\n if (distances.Lo() < queryNode.Stat().LowerBound())\n queryNode.Stat().LowerBound() = distances.Lo();\n\n \/\/ This assumes that reference clusters don't appear elsewhere in the\n \/\/ tree.\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n score = DBL_MAX;\n }\n else if (distances.Hi() < queryNode.Stat().UpperBound())\n {\n \/\/ Tighten upper bound.\n const double tighterBound =\n queryNode.MaxDistance(centroids.col(referenceNode.Descendant(0)));\n ++scores; \/\/ Count extra distance calculation.\n\n if (tighterBound <= queryNode.Stat().UpperBound())\n {\n \/\/ We can improve the best estimate.\n queryNode.Stat().UpperBound() = tighterBound;\n\n \/\/ Remember that our upper bound does correspond to a cluster centroid,\n \/\/ so it does correspond to a cluster. We'll mark the cluster as the\n \/\/ owner, but note that the node is not truly owned unless\n \/\/ Stat().Pruned() is centroids.n_cols.\n queryNode.Stat().Owner() =\n (tree::TreeTraits<TreeType>::RearrangesDataset) ?\n oldFromNewCentroids[referenceNode.Descendant(0)] :\n referenceNode.Descendant(0);\n }\n }\n }\n\n \/\/ Is everything pruned?\n if (queryNode.Stat().Pruned() == centroids.n_cols - 1)\n {\n queryNode.Stat().Pruned() = centroids.n_cols; \/\/ Owner() is already set.\n return DBL_MAX;\n }\n\n \/\/ Set traversal information.\n traversalInfo.LastQueryNode() = &queryNode;\n traversalInfo.LastReferenceNode() = &referenceNode;\n traversalInfo.LastScore() = score;\n\n return score;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Rescore(\n const size_t \/* queryIndex *\/,\n TreeType& \/* referenceNode *\/,\n const double oldScore)\n{\n \/\/ No rescoring (for now).\n return oldScore;\n}\n\ntemplate<typename MetricType, typename TreeType>\ninline double DTNNKMeansRules<MetricType, TreeType>::Rescore(\n TreeType& queryNode,\n TreeType& referenceNode,\n const double oldScore)\n{\n if (oldScore == DBL_MAX)\n return DBL_MAX; \/\/ It's already pruned.\n\n \/\/ oldScore contains the minimum distance between queryNode and referenceNode.\n \/\/ In the time since Score() has been called, the upper bound *may* have\n \/\/ tightened. If it has tightened enough, we may prune this node now.\n if (oldScore > queryNode.Stat().UpperBound())\n {\n \/\/ We may still be able to improve the lower bound on pruned nodes.\n if (oldScore < queryNode.Stat().LowerBound())\n queryNode.Stat().LowerBound() = oldScore;\n\n \/\/ This assumes that reference clusters don't appear elsewhere in the tree.\n queryNode.Stat().Pruned() += referenceNode.NumDescendants();\n return DBL_MAX;\n }\n\n \/\/ Also, check if everything has been pruned.\n if (queryNode.Stat().Pruned() == centroids.n_cols - 1)\n {\n queryNode.Stat().Pruned() = centroids.n_cols; \/\/ Owner() is already set.\n return DBL_MAX;\n }\n\n return oldScore;\n}\n\n} \/\/ namespace kmeans\n} \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <qmath.h>\n\n#include \"qtextureglyphcache_p.h\"\n\n#include \"private\/qnumeric_p.h\"\n#include \"private\/qnativeimage_p.h\"\n#include \"private\/qfontengine_ft_p.h\"\n\n#ifndef QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH\n#define QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH 256\n#endif\n\nQT_BEGIN_NAMESPACE\n\n\/\/ #define CACHE_DEBUG\n\n\/\/ returns the highest number closest to v, which is a power of 2\n\/\/ NB! assumes 32 bit ints\nint qt_next_power_of_two(int v)\n{\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n ++v;\n return v;\n}\n\nvoid QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,\n const QFixedPoint *)\n{\n#ifdef CACHE_DEBUG\n printf(\"Populating with %d glyphs\\n\", numGlyphs);\n qDebug() << \" -> current transformation: \" << m_transform;\n#endif\n\n m_current_fontengine = fontEngine;\n const int margin = glyphMargin();\n\n QHash<glyph_t, Coord> listItemCoordinates;\n int rowHeight = 0;\n\n \/\/ check each glyph for its metrics and get the required rowHeight.\n for (int i=0; i < numGlyphs; ++i) {\n const glyph_t glyph = glyphs[i];\n if (coords.contains(glyph))\n continue;\n if (listItemCoordinates.contains(glyph))\n continue;\n glyph_metrics_t metrics = fontEngine->boundingBox(glyph, m_transform);\n\n#ifdef CACHE_DEBUG\n printf(\"(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\\n\",\n glyph,\n metrics.width.toReal(),\n metrics.height.toReal(),\n metrics.xoff.toReal(),\n metrics.yoff.toReal(),\n metrics.x.toReal(),\n metrics.y.toReal());\n#endif\n int glyph_width = metrics.width.ceil().toInt();\n int glyph_height = metrics.height.ceil().toInt();\n if (glyph_height == 0 || glyph_width == 0)\n continue;\n glyph_width += margin * 2 + 4;\n glyph_height += margin * 2 + 4;\n \/\/ align to 8-bit boundary\n if (m_type == QFontEngineGlyphCache::Raster_Mono)\n glyph_width = (glyph_width+7)&~7;\n\n Coord c = { 0, 0, \/\/ will be filled in later\n glyph_width,\n glyph_height, \/\/ texture coords\n metrics.x.round().truncate(),\n -metrics.y.truncate() }; \/\/ baseline for horizontal scripts\n\n listItemCoordinates.insert(glyph, c);\n rowHeight = qMax(rowHeight, glyph_height);\n }\n if (listItemCoordinates.isEmpty())\n return;\n\n rowHeight += margin * 2;\n if (isNull())\n createCache(QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH, qt_next_power_of_two(rowHeight));\n\n \/\/ now actually use the coords and paint the wanted glyps into cache.\n QHash<glyph_t, Coord>::iterator iter = listItemCoordinates.begin();\n while (iter != listItemCoordinates.end()) {\n Coord c = iter.value();\n\n if (m_cx + c.w > m_w) {\n \/\/ no room on the current line, start new glyph strip\n m_cx = 0;\n m_cy = m_h;\n }\n if (m_cy + c.h > m_h) {\n int new_height = m_h*2;\n while (new_height < m_cy + c.h)\n new_height *= 2;\n \/\/ if no room in the current texture - realloc a larger texture\n resizeTextureData(m_w, new_height);\n m_h = new_height;\n }\n\n c.x = m_cx;\n c.y = m_cy;\n\n fillTexture(c, iter.key());\n coords.insert(iter.key(), c);\n\n if (m_cx + c.w > m_w) {\n m_cx = 0;\n m_cy += rowHeight;\n } else {\n \/\/ for the Mono case, glyph_width is 8-bit aligned,\n \/\/ and therefore so will m_cx\n m_cx += c.w;\n }\n ++iter;\n }\n\n\n}\n\nQImage QTextureGlyphCache::textureMapForGlyph(glyph_t g) const\n{\n#if defined(Q_WS_X11)\n if (m_transform.type() > QTransform::TxTranslate) {\n QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None;\n QImage::Format imageFormat = QImage::Format_Invalid;\n switch (m_type) {\n case Raster_RGBMask:\n format = QFontEngineFT::Format_A32;\n imageFormat = QImage::Format_RGB32;\n break;\n case Raster_A8:\n format = QFontEngineFT::Format_A8;\n imageFormat = QImage::Format_Indexed8;\n break;\n case Raster_Mono:\n format = QFontEngineFT::Format_Mono;\n imageFormat = QImage::Format_Mono;\n break;\n };\n\n QFontEngineFT *ft = static_cast<QFontEngineFT*> (m_current_fontengine);\n QFontEngineFT::QGlyphSet *gset = ft->loadTransformedGlyphSet(m_transform);\n\n if (gset && ft->loadGlyphs(gset, &g, 1, format)) {\n QFontEngineFT::Glyph *glyph = gset->glyph_data.value(g);\n const int bytesPerLine = (format == QFontEngineFT::Format_Mono ? ((glyph->width + 31) & ~31) >> 3\n : (glyph->width + 3) & ~3);\n return QImage(glyph->data, glyph->width, glyph->height, bytesPerLine, imageFormat);\n }\n } else\n#endif\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask)\n return m_current_fontengine->alphaRGBMapForGlyph(g, glyphMargin(), m_transform);\n else\n return m_current_fontengine->alphaMapForGlyph(g, m_transform);\n\n return QImage();\n}\n\n\/************************************************************************\n * QImageTextureGlyphCache\n *\/\n\nvoid QImageTextureGlyphCache::resizeTextureData(int width, int height)\n{\n m_image = m_image.copy(0, 0, width, height);\n}\n\nvoid QImageTextureGlyphCache::createTextureData(int width, int height)\n{\n switch (m_type) {\n case QFontEngineGlyphCache::Raster_Mono:\n m_image = QImage(width, height, QImage::Format_Mono);\n break;\n case QFontEngineGlyphCache::Raster_A8: {\n m_image = QImage(width, height, QImage::Format_Indexed8);\n m_image.fill(0);\n QVector<QRgb> colors(256);\n QRgb *it = colors.data();\n for (int i=0; i<256; ++i, ++it)\n *it = 0xff000000 | i | (i<<8) | (i<<16);\n m_image.setColorTable(colors);\n break; }\n case QFontEngineGlyphCache::Raster_RGBMask:\n m_image = QImage(width, height, QImage::Format_RGB32);\n break;\n }\n}\n\nint QImageTextureGlyphCache::glyphMargin() const\n{\n#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)\n return 0;\n#else\n return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;\n#endif\n}\n\nvoid QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g)\n{\n QImage mask = textureMapForGlyph(g);\n\n#ifdef CACHE_DEBUG\n printf(\"fillTexture of %dx%d at %d,%d in the cache of %dx%d\\n\", c.w, c.h, c.x, c.y, m_image.width(), m_image.height());\n if (mask.width() > c.w || mask.height() > c.h) {\n printf(\" ERROR; mask is bigger than reserved space! %dx%d instead of %dx%d\\n\", mask.width(), mask.height(), c.w,c.h);\n return;\n }\n#endif\n\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask) {\n QPainter p(&m_image);\n p.setCompositionMode(QPainter::CompositionMode_Source);\n p.fillRect(c.x, c.y, c.w, c.h, QColor(0,0,0,0)); \/\/ TODO optimize this\n p.drawImage(c.x, c.y, mask);\n p.end();\n } else if (m_type == QFontEngineGlyphCache::Raster_Mono) {\n if (mask.depth() > 1) {\n \/\/ TODO optimize this\n mask = mask.alphaChannel();\n mask.invertPixels();\n mask = mask.convertToFormat(QImage::Format_Mono);\n }\n\n int mw = qMin(mask.width(), c.w);\n int mh = qMin(mask.height(), c.h);\n uchar *d = m_image.bits();\n int dbpl = m_image.bytesPerLine();\n\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x\/8;\n\n if (y < mh) {\n uchar *src = mask.scanLine(y);\n for (int x = 0; x < c.w\/8; ++x) {\n if (x < (mw+7)\/8)\n dest[x] = src[x];\n else\n dest[x] = 0;\n }\n } else {\n for (int x = 0; x < c.w\/8; ++x)\n dest[x] = 0;\n }\n }\n } else { \/\/ A8\n int mw = qMin(mask.width(), c.w);\n int mh = qMin(mask.height(), c.h);\n uchar *d = m_image.bits();\n int dbpl = m_image.bytesPerLine();\n\n if (mask.depth() == 1) {\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x;\n if (y < mh) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < c.w; ++x) {\n if (x < mw)\n dest[x] = (src[x >> 3] & (1 << (7 - (x & 7)))) > 0 ? 255 : 0;\n }\n }\n }\n } else if (mask.depth() == 8) {\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x;\n if (y < mh) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < c.w; ++x) {\n if (x < mw)\n dest[x] = src[x];\n }\n }\n }\n }\n }\n\n#ifdef CACHE_DEBUG\n\/\/ QPainter p(&m_image);\n\/\/ p.drawLine(\n QPoint base(c.x + glyphMargin(), c.y + glyphMargin() + c.baseLineY-1);\n if (m_image.rect().contains(base))\n m_image.setPixel(base, 255);\n m_image.save(QString::fromLatin1(\"cache-%1.png\").arg(int(this)));\n#endif\n}\n\nQT_END_NAMESPACE\n<commit_msg>Fixed wasted space in the texture cache.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <qmath.h>\n\n#include \"qtextureglyphcache_p.h\"\n\n#include \"private\/qnumeric_p.h\"\n#include \"private\/qnativeimage_p.h\"\n#include \"private\/qfontengine_ft_p.h\"\n\n#ifndef QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH\n#define QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH 256\n#endif\n\nQT_BEGIN_NAMESPACE\n\n\/\/ #define CACHE_DEBUG\n\n\/\/ returns the highest number closest to v, which is a power of 2\n\/\/ NB! assumes 32 bit ints\nint qt_next_power_of_two(int v)\n{\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n ++v;\n return v;\n}\n\nvoid QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,\n const QFixedPoint *)\n{\n#ifdef CACHE_DEBUG\n printf(\"Populating with %d glyphs\\n\", numGlyphs);\n qDebug() << \" -> current transformation: \" << m_transform;\n#endif\n\n m_current_fontengine = fontEngine;\n const int margin = glyphMargin();\n\n QHash<glyph_t, Coord> listItemCoordinates;\n int rowHeight = 0;\n\n \/\/ check each glyph for its metrics and get the required rowHeight.\n for (int i=0; i < numGlyphs; ++i) {\n const glyph_t glyph = glyphs[i];\n if (coords.contains(glyph))\n continue;\n if (listItemCoordinates.contains(glyph))\n continue;\n glyph_metrics_t metrics = fontEngine->boundingBox(glyph, m_transform);\n\n#ifdef CACHE_DEBUG\n printf(\"(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\\n\",\n glyph,\n metrics.width.toReal(),\n metrics.height.toReal(),\n metrics.xoff.toReal(),\n metrics.yoff.toReal(),\n metrics.x.toReal(),\n metrics.y.toReal());\n#endif\n int glyph_width = metrics.width.ceil().toInt();\n int glyph_height = metrics.height.ceil().toInt();\n if (glyph_height == 0 || glyph_width == 0)\n continue;\n glyph_width += margin * 2 + 4;\n glyph_height += margin * 2 + 4;\n \/\/ align to 8-bit boundary\n if (m_type == QFontEngineGlyphCache::Raster_Mono)\n glyph_width = (glyph_width+7)&~7;\n\n Coord c = { 0, 0, \/\/ will be filled in later\n glyph_width,\n glyph_height, \/\/ texture coords\n metrics.x.round().truncate(),\n -metrics.y.truncate() }; \/\/ baseline for horizontal scripts\n\n listItemCoordinates.insert(glyph, c);\n rowHeight = qMax(rowHeight, glyph_height);\n }\n if (listItemCoordinates.isEmpty())\n return;\n\n rowHeight += margin * 2;\n if (isNull())\n createCache(QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH, qt_next_power_of_two(rowHeight));\n\n \/\/ now actually use the coords and paint the wanted glyps into cache.\n QHash<glyph_t, Coord>::iterator iter = listItemCoordinates.begin();\n while (iter != listItemCoordinates.end()) {\n Coord c = iter.value();\n\n if (m_cx + c.w > m_w) {\n \/\/ no room on the current line, start new glyph strip\n m_cx = 0;\n m_cy += rowHeight;\n }\n if (m_cy + c.h > m_h) {\n int new_height = m_h*2;\n while (new_height < m_cy + c.h)\n new_height *= 2;\n \/\/ if no room in the current texture - realloc a larger texture\n resizeTextureData(m_w, new_height);\n m_h = new_height;\n }\n\n c.x = m_cx;\n c.y = m_cy;\n\n fillTexture(c, iter.key());\n coords.insert(iter.key(), c);\n\n if (m_cx + c.w > m_w) {\n m_cx = 0;\n m_cy += rowHeight;\n } else {\n \/\/ for the Mono case, glyph_width is 8-bit aligned,\n \/\/ and therefore so will m_cx\n m_cx += c.w;\n }\n ++iter;\n }\n\n\n}\n\nQImage QTextureGlyphCache::textureMapForGlyph(glyph_t g) const\n{\n#if defined(Q_WS_X11)\n if (m_transform.type() > QTransform::TxTranslate) {\n QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None;\n QImage::Format imageFormat = QImage::Format_Invalid;\n switch (m_type) {\n case Raster_RGBMask:\n format = QFontEngineFT::Format_A32;\n imageFormat = QImage::Format_RGB32;\n break;\n case Raster_A8:\n format = QFontEngineFT::Format_A8;\n imageFormat = QImage::Format_Indexed8;\n break;\n case Raster_Mono:\n format = QFontEngineFT::Format_Mono;\n imageFormat = QImage::Format_Mono;\n break;\n };\n\n QFontEngineFT *ft = static_cast<QFontEngineFT*> (m_current_fontengine);\n QFontEngineFT::QGlyphSet *gset = ft->loadTransformedGlyphSet(m_transform);\n\n if (gset && ft->loadGlyphs(gset, &g, 1, format)) {\n QFontEngineFT::Glyph *glyph = gset->glyph_data.value(g);\n const int bytesPerLine = (format == QFontEngineFT::Format_Mono ? ((glyph->width + 31) & ~31) >> 3\n : (glyph->width + 3) & ~3);\n return QImage(glyph->data, glyph->width, glyph->height, bytesPerLine, imageFormat);\n }\n } else\n#endif\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask)\n return m_current_fontengine->alphaRGBMapForGlyph(g, glyphMargin(), m_transform);\n else\n return m_current_fontengine->alphaMapForGlyph(g, m_transform);\n\n return QImage();\n}\n\n\/************************************************************************\n * QImageTextureGlyphCache\n *\/\n\nvoid QImageTextureGlyphCache::resizeTextureData(int width, int height)\n{\n m_image = m_image.copy(0, 0, width, height);\n}\n\nvoid QImageTextureGlyphCache::createTextureData(int width, int height)\n{\n switch (m_type) {\n case QFontEngineGlyphCache::Raster_Mono:\n m_image = QImage(width, height, QImage::Format_Mono);\n break;\n case QFontEngineGlyphCache::Raster_A8: {\n m_image = QImage(width, height, QImage::Format_Indexed8);\n m_image.fill(0);\n QVector<QRgb> colors(256);\n QRgb *it = colors.data();\n for (int i=0; i<256; ++i, ++it)\n *it = 0xff000000 | i | (i<<8) | (i<<16);\n m_image.setColorTable(colors);\n break; }\n case QFontEngineGlyphCache::Raster_RGBMask:\n m_image = QImage(width, height, QImage::Format_RGB32);\n break;\n }\n}\n\nint QImageTextureGlyphCache::glyphMargin() const\n{\n#if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)\n return 0;\n#else\n return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;\n#endif\n}\n\nvoid QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g)\n{\n QImage mask = textureMapForGlyph(g);\n\n#ifdef CACHE_DEBUG\n printf(\"fillTexture of %dx%d at %d,%d in the cache of %dx%d\\n\", c.w, c.h, c.x, c.y, m_image.width(), m_image.height());\n if (mask.width() > c.w || mask.height() > c.h) {\n printf(\" ERROR; mask is bigger than reserved space! %dx%d instead of %dx%d\\n\", mask.width(), mask.height(), c.w,c.h);\n return;\n }\n#endif\n\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask) {\n QPainter p(&m_image);\n p.setCompositionMode(QPainter::CompositionMode_Source);\n p.fillRect(c.x, c.y, c.w, c.h, QColor(0,0,0,0)); \/\/ TODO optimize this\n p.drawImage(c.x, c.y, mask);\n p.end();\n } else if (m_type == QFontEngineGlyphCache::Raster_Mono) {\n if (mask.depth() > 1) {\n \/\/ TODO optimize this\n mask = mask.alphaChannel();\n mask.invertPixels();\n mask = mask.convertToFormat(QImage::Format_Mono);\n }\n\n int mw = qMin(mask.width(), c.w);\n int mh = qMin(mask.height(), c.h);\n uchar *d = m_image.bits();\n int dbpl = m_image.bytesPerLine();\n\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x\/8;\n\n if (y < mh) {\n uchar *src = mask.scanLine(y);\n for (int x = 0; x < c.w\/8; ++x) {\n if (x < (mw+7)\/8)\n dest[x] = src[x];\n else\n dest[x] = 0;\n }\n } else {\n for (int x = 0; x < c.w\/8; ++x)\n dest[x] = 0;\n }\n }\n } else { \/\/ A8\n int mw = qMin(mask.width(), c.w);\n int mh = qMin(mask.height(), c.h);\n uchar *d = m_image.bits();\n int dbpl = m_image.bytesPerLine();\n\n if (mask.depth() == 1) {\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x;\n if (y < mh) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < c.w; ++x) {\n if (x < mw)\n dest[x] = (src[x >> 3] & (1 << (7 - (x & 7)))) > 0 ? 255 : 0;\n }\n }\n }\n } else if (mask.depth() == 8) {\n for (int y = 0; y < c.h; ++y) {\n uchar *dest = d + (c.y + y) *dbpl + c.x;\n if (y < mh) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < c.w; ++x) {\n if (x < mw)\n dest[x] = src[x];\n }\n }\n }\n }\n }\n\n#ifdef CACHE_DEBUG\n\/\/ QPainter p(&m_image);\n\/\/ p.drawLine(\n QPoint base(c.x + glyphMargin(), c.y + glyphMargin() + c.baseLineY-1);\n if (m_image.rect().contains(base))\n m_image.setPixel(base, 255);\n m_image.save(QString::fromLatin1(\"cache-%1.png\").arg(int(this)));\n#endif\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>#include \"common\/BenchmarkRunner.h\"\n#include \"common\/CommandLineConfiguration.h\"\n#include \"common\/MpiGuard.h\"\n#include \"common\/MpiHelper.h\"\n#include \"matrix\/MatrixHelper.h\"\n#include \"matrix\/Matrix.h\"\n\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\nusing namespace std;\n\nvoid exportClusterConfiguration(const string& filename, BenchmarkResult& result)\n{\n fstream file(filename, fstream::out);\n if (!file.is_open())\n {\n cerr << \"ERROR: Could not write \"<<filename<<endl;\n exit(1);\n }\n file << result;\n file.close();\n}\n\nBenchmarkResult importClusterConfiguration(const string& filename)\n{\n fstream file(filename, fstream::in);\n if (!file.is_open())\n {\n cerr << \"ERROR: Could not read \"<<filename<<endl;\n exit(1);\n }\n BenchmarkResult result;\n file >> result;\n file.close();\n if (result.size() != MpiHelper::numberOfNodes())\n {\n cerr << \"ERROR: Number of nodes does not match configured number of nodes\" <<endl;\n exit(1);\n }\n return result;\n}\n\nvoid silenceOutputStreams(bool keepErrorStreams = false)\n{\n cout.rdbuf(nullptr);\n\n if (!keepErrorStreams)\n {\n cerr.rdbuf(nullptr);\n clog.rdbuf(nullptr);\n }\n}\n\nvoid benchmarkWith(const Configuration& config)\n{\n BenchmarkRunner runner(config);\n BenchmarkResult nodeWeights;\n\n ofstream timeFile(config.timeOutputFilename(), ios::app);\n\n if (!timeFile.is_open())\n throw runtime_error(\"Failed to open file \\\"\" + config.timeOutputFilename() + \"\\\"\");\n\n if (config.shouldExportConfiguration() || !config.shouldImportConfiguration())\n {\n cout << \"Calculating node weights\" <<endl;\n nodeWeights = runner.benchmarkIndividualNodes();\n cout << \"Weighted \" << endl << nodeWeights;\n }\n if (config.shouldExportConfiguration())\n {\n cout << \"Exporting node weights\" <<endl;\n exportClusterConfiguration(config.exportConfigurationFilename(), nodeWeights);\n }\n if (config.shouldImportConfiguration())\n {\n cout << \"Importing node weights\" <<endl;\n nodeWeights = importClusterConfiguration(config.importConfigurationFilename());\n }\n if (!config.shouldSkipBenchmark())\n {\n cout << \"Running benchmark\" <<endl;\n auto clusterResults = runner.runBenchmark(nodeWeights);\n cout << \"Measured Times: µs\" << endl;\n\n for (const auto& measurement : clusterResults)\n {\n cout << \"\\t\" << measurement.count() << endl;\n\n if (MpiHelper::isMaster())\n timeFile << measurement.count() << endl;\n }\n }\n}\n\nint main(int argc, char** argv)\n{\n \/\/ used to ensure MPI::Finalize is called on exit of the application\n MpiGuard guard(argc, argv);\n\n try\n {\n CommandLineConfiguration config(argc, argv);\n\n if (config.shouldPrintHelp())\n {\n config.printHelp();\n return 0;\n }\n\n if (!config.shouldBeVerbose() && (config.shouldBeQuiet() || !MpiHelper::isMaster()))\n silenceOutputStreams(true);\n\n cout << config << endl;\n\n benchmarkWith(config);\n }\n catch (const boost::program_options::error& e)\n {\n CommandLineConfiguration::printHelp();\n cerr << e.what() << endl;\n return 1;\n }\n catch (const logic_error& e)\n {\n cerr << \"ERROR: \" << e.what() << endl;\n return 1;\n }\n catch (const exception& e)\n {\n cerr << \"FATAL: \" << e.what() << endl;\n return 1;\n }\n catch (...)\n {\n cerr << \"FATAL ERROR of unknown type.\" << endl;\n return 1;\n }\n\n return 0;\n}\n\n<commit_msg>only master creates time-output-file<commit_after>#include \"common\/BenchmarkRunner.h\"\n#include \"common\/CommandLineConfiguration.h\"\n#include \"common\/MpiGuard.h\"\n#include \"common\/MpiHelper.h\"\n#include \"matrix\/MatrixHelper.h\"\n#include \"matrix\/Matrix.h\"\n\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\nusing namespace std;\n\nvoid exportClusterConfiguration(const string& filename, BenchmarkResult& result)\n{\n fstream file(filename, fstream::out);\n if (!file.is_open())\n {\n cerr << \"ERROR: Could not write \"<<filename<<endl;\n exit(1);\n }\n file << result;\n file.close();\n}\n\nBenchmarkResult importClusterConfiguration(const string& filename)\n{\n fstream file(filename, fstream::in);\n if (!file.is_open())\n {\n cerr << \"ERROR: Could not read \"<<filename<<endl;\n exit(1);\n }\n BenchmarkResult result;\n file >> result;\n file.close();\n if (result.size() != MpiHelper::numberOfNodes())\n {\n cerr << \"ERROR: Number of nodes does not match configured number of nodes\" <<endl;\n exit(1);\n }\n return result;\n}\n\nvoid silenceOutputStreams(bool keepErrorStreams = false)\n{\n cout.rdbuf(nullptr);\n\n if (!keepErrorStreams)\n {\n cerr.rdbuf(nullptr);\n clog.rdbuf(nullptr);\n }\n}\n\nvoid benchmarkWith(const Configuration& config)\n{\n BenchmarkRunner runner(config);\n BenchmarkResult nodeWeights;\n\n ofstream timeFile;\n\n if (MpiHelper::isMaster())\n {\n timeFile.open(config.timeOutputFilename(), ios::app);\n\n if (!timeFile.is_open())\n throw runtime_error(\"Failed to open file \\\"\" + config.timeOutputFilename() + \"\\\"\");\n }\n\n if (config.shouldExportConfiguration() || !config.shouldImportConfiguration())\n {\n cout << \"Calculating node weights\" <<endl;\n nodeWeights = runner.benchmarkIndividualNodes();\n cout << \"Weighted \" << endl << nodeWeights;\n }\n if (config.shouldExportConfiguration())\n {\n cout << \"Exporting node weights\" <<endl;\n exportClusterConfiguration(config.exportConfigurationFilename(), nodeWeights);\n }\n if (config.shouldImportConfiguration())\n {\n cout << \"Importing node weights\" <<endl;\n nodeWeights = importClusterConfiguration(config.importConfigurationFilename());\n }\n if (!config.shouldSkipBenchmark())\n {\n cout << \"Running benchmark\" <<endl;\n auto clusterResults = runner.runBenchmark(nodeWeights);\n cout << \"Measured Times: µs\" << endl;\n\n for (const auto& measurement : clusterResults)\n {\n cout << \"\\t\" << measurement.count() << endl;\n\n if (MpiHelper::isMaster())\n timeFile << measurement.count() << endl;\n }\n }\n}\n\nint main(int argc, char** argv)\n{\n \/\/ used to ensure MPI::Finalize is called on exit of the application\n MpiGuard guard(argc, argv);\n\n try\n {\n CommandLineConfiguration config(argc, argv);\n\n if (config.shouldPrintHelp())\n {\n config.printHelp();\n return 0;\n }\n\n if (!config.shouldBeVerbose() && (config.shouldBeQuiet() || !MpiHelper::isMaster()))\n silenceOutputStreams(true);\n\n cout << config << endl;\n\n benchmarkWith(config);\n }\n catch (const boost::program_options::error& e)\n {\n CommandLineConfiguration::printHelp();\n cerr << e.what() << endl;\n return 1;\n }\n catch (const logic_error& e)\n {\n cerr << \"ERROR: \" << e.what() << endl;\n return 1;\n }\n catch (const exception& e)\n {\n cerr << \"FATAL: \" << e.what() << endl;\n return 1;\n }\n catch (...)\n {\n cerr << \"FATAL ERROR of unknown type.\" << endl;\n return 1;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"limit_quote.h\"\n\n\nvoid Limit_quote::debug() const\n{\n std::cout << \"data members of this class:\\n\"\n << \"max_qty= \" << this->max_qty << \" \"\n << \"discount= \" << this->discount<< \" \\n\";\n}\n<commit_msg>Delete limit_quote.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2020 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\/\/ clang-format off\n#include \"main.h\"\n#include \"activemasternode.h\"\n#include \"masternode-sync.h\"\n#include \"masternode-payments.h\"\n#include \"masternode-budget.h\"\n#include \"masternode.h\"\n#include \"masternodeman.h\"\n#include \"spork.h\"\n#include \"util.h\"\n#include \"addrman.h\"\n\/\/ clang-format on\n\nclass CMasternodeSync;\nCMasternodeSync masternodeSync;\n\nCMasternodeSync::CMasternodeSync()\n{\n Reset();\n}\n\nbool CMasternodeSync::IsSynced()\n{\n return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED;\n}\n\nbool CMasternodeSync::IsSporkListSynced()\n{\n return RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS;\n}\n\nbool CMasternodeSync::IsMasternodeListSynced()\n{\n return RequestedMasternodeAssets > MASTERNODE_SYNC_LIST;\n}\n\nbool CMasternodeSync::NotCompleted()\n{\n return (!IsSynced() && (\n !IsSporkListSynced() ||\n sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) ||\n sporkManager.IsSporkActive(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) ||\n sporkManager.IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)));\n}\n\nbool CMasternodeSync::IsBlockchainSynced()\n{\n int64_t now = GetTime();\n\n \/\/ if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process\n if (now > lastProcess + 60 * 60) {\n Reset();\n fBlockchainSynced = false;\n }\n lastProcess = now;\n\n if (fBlockchainSynced) return true;\n\n if (fImporting || fReindex) return false;\n\n int64_t blockTime = 0;\n {\n TRY_LOCK(cs_main, lockMain);\n if (!lockMain) return false;\n CBlockIndex *pindex = chainActive.Tip();\n if (pindex == nullptr) return false;\n blockTime = pindex->nTime;\n }\n\n if (blockTime + 60 * 60 < lastProcess)\n return false;\n\n fBlockchainSynced = true;\n\n return true;\n}\n\nvoid CMasternodeSync::Reset()\n{\n fBlockchainSynced = false;\n lastProcess = 0;\n lastMasternodeList = 0;\n lastMasternodeWinner = 0;\n lastBudgetItem = 0;\n mapSeenSyncMNB.clear();\n mapSeenSyncMNW.clear();\n mapSeenSyncBudget.clear();\n lastFailure = 0;\n nCountFailures = 0;\n sumMasternodeList = 0;\n sumMasternodeWinner = 0;\n sumBudgetItemProp = 0;\n sumBudgetItemFin = 0;\n countMasternodeList = 0;\n countMasternodeWinner = 0;\n countBudgetItemProp = 0;\n countBudgetItemFin = 0;\n RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n RequestedMasternodeAttempt = 0;\n nAssetSyncStarted = GetTime();\n}\n\nvoid CMasternodeSync::AddedMasternodeList(uint256 hash)\n{\n if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) {\n if (mapSeenSyncMNB[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastMasternodeList = GetTime();\n mapSeenSyncMNB[hash]++;\n }\n } else {\n lastMasternodeList = GetTime();\n mapSeenSyncMNB.insert(std::make_pair(hash, 1));\n }\n}\n\nvoid CMasternodeSync::AddedMasternodeWinner(uint256 hash)\n{\n if (masternodePayments.mapMasternodePayeeVotes.count(hash)) {\n if (mapSeenSyncMNW[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastMasternodeWinner = GetTime();\n mapSeenSyncMNW[hash]++;\n }\n } else {\n lastMasternodeWinner = GetTime();\n mapSeenSyncMNW.insert(std::make_pair(hash, 1));\n }\n}\n\nvoid CMasternodeSync::AddedBudgetItem(uint256 hash)\n{\n if (budget.mapSeenMasternodeBudgetProposals.count(hash) || budget.mapSeenMasternodeBudgetVotes.count(hash) ||\n budget.mapSeenFinalizedBudgets.count(hash) || budget.mapSeenFinalizedBudgetVotes.count(hash)) {\n if (mapSeenSyncBudget[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastBudgetItem = GetTime();\n mapSeenSyncBudget[hash]++;\n }\n } else {\n lastBudgetItem = GetTime();\n mapSeenSyncBudget.insert(std::make_pair(hash, 1));\n }\n}\n\nbool CMasternodeSync::IsBudgetPropEmpty()\n{\n return sumBudgetItemProp == 0 && countBudgetItemProp > 0;\n}\n\nbool CMasternodeSync::IsBudgetFinEmpty()\n{\n return sumBudgetItemFin == 0 && countBudgetItemFin > 0;\n}\n\nvoid CMasternodeSync::GetNextAsset()\n{\n switch (RequestedMasternodeAssets) {\n case (MASTERNODE_SYNC_INITIAL):\n case (MASTERNODE_SYNC_FAILED): \/\/ should never be used here actually, use Reset() instead\n ClearFulfilledRequest();\n RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;\n break;\n case (MASTERNODE_SYNC_SPORKS):\n RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;\n break;\n case (MASTERNODE_SYNC_LIST):\n RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;\n break;\n case (MASTERNODE_SYNC_MNW):\n RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;\n break;\n case (MASTERNODE_SYNC_BUDGET):\n LogPrintf(\"CMasternodeSync::GetNextAsset - Sync has finished\\n\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n break;\n }\n RequestedMasternodeAttempt = 0;\n nAssetSyncStarted = GetTime();\n}\n\nstd::string CMasternodeSync::GetSyncStatus()\n{\n switch (masternodeSync.RequestedMasternodeAssets) {\n case MASTERNODE_SYNC_INITIAL:\n return _(\"MNs synchronization pending...\");\n case MASTERNODE_SYNC_SPORKS:\n return _(\"Synchronizing sporks...\");\n case MASTERNODE_SYNC_LIST:\n return _(\"Synchronizing masternodes...\");\n case MASTERNODE_SYNC_MNW:\n return _(\"Synchronizing masternode winners...\");\n case MASTERNODE_SYNC_BUDGET:\n return _(\"Synchronizing budgets...\");\n case MASTERNODE_SYNC_FAILED:\n return _(\"Synchronization failed\");\n case MASTERNODE_SYNC_FINISHED:\n return _(\"Synchronization finished\");\n }\n return \"\";\n}\n\nvoid CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { \/\/Sync status count\n int nItemID;\n int nCount;\n vRecv >> nItemID >> nCount;\n\n if (RequestedMasternodeAssets >= MASTERNODE_SYNC_FINISHED) return;\n\n \/\/this means we will receive no further communication\n switch (nItemID) {\n case (MASTERNODE_SYNC_LIST):\n if (nItemID != RequestedMasternodeAssets) return;\n sumMasternodeList += nCount;\n countMasternodeList++;\n break;\n case (MASTERNODE_SYNC_MNW):\n if (nItemID != RequestedMasternodeAssets) return;\n sumMasternodeWinner += nCount;\n countMasternodeWinner++;\n break;\n case (MASTERNODE_SYNC_BUDGET_PROP):\n if (RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;\n sumBudgetItemProp += nCount;\n countBudgetItemProp++;\n break;\n case (MASTERNODE_SYNC_BUDGET_FIN):\n if (RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;\n sumBudgetItemFin += nCount;\n countBudgetItemFin++;\n break;\n }\n\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync:ProcessMessage - ssc - got inventory count %d %d\\n\", nItemID, nCount);\n }\n}\n\nvoid CMasternodeSync::ClearFulfilledRequest()\n{\n g_connman->ForEachNode([](CNode* pnode) {\n pnode->ClearFulfilledRequest(\"getspork\");\n pnode->ClearFulfilledRequest(\"mnsync\");\n pnode->ClearFulfilledRequest(\"mnwsync\");\n pnode->ClearFulfilledRequest(\"busync\");\n });\n}\n\nvoid CMasternodeSync::Process()\n{\n static int tick = 0;\n const bool isRegTestNet = Params().IsRegTestNet();\n\n if (tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return;\n\n if (IsSynced()) {\n \/*\n Resync if we lose all masternodes from sleep\/wake or failure to sync originally\n *\/\n if (mnodeman.CountEnabled() == 0) {\n Reset();\n } else\n return;\n }\n\n \/\/try syncing again\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (1 * 60) < GetTime()) {\n Reset();\n } else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) {\n return;\n }\n\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\\n\", tick, RequestedMasternodeAssets);\n\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();\n\n \/\/ sporks synced but blockchain is not, wait until we're almost at a recent block to continue\n if (!isRegTestNet && !IsBlockchainSynced() &&\n RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;\n\n std::vector<CNode*> vNodesCopy = g_connman->CopyNodeVector();\n for (CNode* pnode : vNodesCopy) {\n if (!SyncWithNode(pnode, isRegTestNet)) {\n g_connman->ReleaseNodeVector(vNodesCopy);\n return;\n }\n }\n g_connman->ReleaseNodeVector(vNodesCopy);\n}\n\nbool CMasternodeSync::SyncWithNode(CNode* pnode, bool isRegTestNet)\n{\n if (isRegTestNet) {\n if (RequestedMasternodeAttempt <= 2) {\n pnode->PushMessage(NetMsgType::GETSPORKS); \/\/get current network sporks\n } else if (RequestedMasternodeAttempt < 4) {\n mnodeman.DsegUpdate(pnode);\n } else if (RequestedMasternodeAttempt < 6) {\n int nMnCount = mnodeman.CountEnabled();\n pnode->PushMessage(NetMsgType::GETMNWINNERS, nMnCount); \/\/sync payees\n uint256 n;\n pnode->PushMessage(NetMsgType::BUDGETVOTESYNC, n); \/\/sync masternode votes\n } else {\n RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n }\n RequestedMasternodeAttempt++;\n return false;\n }\n\n \/\/set to synced\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS) {\n if (pnode->HasFulfilledRequest(\"getspork\")) return true;\n pnode->FulfilledRequest(\"getspork\");\n\n pnode->PushMessage(NetMsgType::GETSPORKS); \/\/get current network sporks\n if (RequestedMasternodeAttempt >= 2) GetNextAsset();\n RequestedMasternodeAttempt++;\n return false;\n }\n\n if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\\n\", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);\n if (lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) { \/\/hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"mnsync\")) return true;\n pnode->FulfilledRequest(\"mnsync\");\n\n \/\/ timeout\n if (lastMasternodeList == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n LogPrintf(\"CMasternodeSync::Process - ERROR - Sync has failed on %s, will retry later\\n\", \"MASTERNODE_SYNC_LIST\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;\n RequestedMasternodeAttempt = 0;\n lastFailure = GetTime();\n nCountFailures++;\n } else {\n GetNextAsset();\n }\n return false;\n }\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n mnodeman.DsegUpdate(pnode);\n RequestedMasternodeAttempt++;\n return false;\n }\n\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {\n if (lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) { \/\/hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"mnwsync\")) return true;\n pnode->FulfilledRequest(\"mnwsync\");\n\n \/\/ timeout\n if (lastMasternodeWinner == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n LogPrintf(\"CMasternodeSync::Process - ERROR - Sync has failed on %s, will retry later\\n\", \"MASTERNODE_SYNC_MNW\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;\n RequestedMasternodeAttempt = 0;\n lastFailure = GetTime();\n nCountFailures++;\n } else {\n GetNextAsset();\n }\n return false;\n }\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n int nMnCount = mnodeman.CountEnabled();\n pnode->PushMessage(NetMsgType::GETMNWINNERS, nMnCount); \/\/sync payees\n RequestedMasternodeAttempt++;\n return false;\n }\n }\n\n if (pnode->nVersion >= ActiveProtocol()) {\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET) {\n \/\/ We'll start rejecting votes if we accidentally get set as synced too soon\n if (lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) {\n \/\/ Hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n\n \/\/ Try to activate our masternode if possible\n activeMasternode.ManageStatus();\n return false;\n }\n\n \/\/ timeout\n if (lastBudgetItem == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n \/\/ maybe there is no budgets at all, so just finish syncing\n GetNextAsset();\n activeMasternode.ManageStatus();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"busync\")) return true;\n pnode->FulfilledRequest(\"busync\");\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n uint256 n;\n pnode->PushMessage(NetMsgType::BUDGETVOTESYNC, n); \/\/sync masternode votes\n RequestedMasternodeAttempt++;\n return false;\n }\n }\n\n return true;\n}\n\n\n<commit_msg>[Refactor] Proper CConnman encapsulation of mnsync<commit_after>\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2020 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\/\/ clang-format off\n#include \"main.h\"\n#include \"activemasternode.h\"\n#include \"masternode-sync.h\"\n#include \"masternode-payments.h\"\n#include \"masternode-budget.h\"\n#include \"masternode.h\"\n#include \"masternodeman.h\"\n#include \"spork.h\"\n#include \"util.h\"\n#include \"addrman.h\"\n\/\/ clang-format on\n\nclass CMasternodeSync;\nCMasternodeSync masternodeSync;\n\nCMasternodeSync::CMasternodeSync()\n{\n Reset();\n}\n\nbool CMasternodeSync::IsSynced()\n{\n return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED;\n}\n\nbool CMasternodeSync::IsSporkListSynced()\n{\n return RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS;\n}\n\nbool CMasternodeSync::IsMasternodeListSynced()\n{\n return RequestedMasternodeAssets > MASTERNODE_SYNC_LIST;\n}\n\nbool CMasternodeSync::NotCompleted()\n{\n return (!IsSynced() && (\n !IsSporkListSynced() ||\n sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) ||\n sporkManager.IsSporkActive(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) ||\n sporkManager.IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)));\n}\n\nbool CMasternodeSync::IsBlockchainSynced()\n{\n int64_t now = GetTime();\n\n \/\/ if the last call to this function was more than 60 minutes ago (client was in sleep mode) reset the sync process\n if (now > lastProcess + 60 * 60) {\n Reset();\n fBlockchainSynced = false;\n }\n lastProcess = now;\n\n if (fBlockchainSynced) return true;\n\n if (fImporting || fReindex) return false;\n\n int64_t blockTime = 0;\n {\n TRY_LOCK(cs_main, lockMain);\n if (!lockMain) return false;\n CBlockIndex *pindex = chainActive.Tip();\n if (pindex == nullptr) return false;\n blockTime = pindex->nTime;\n }\n\n if (blockTime + 60 * 60 < lastProcess)\n return false;\n\n fBlockchainSynced = true;\n\n return true;\n}\n\nvoid CMasternodeSync::Reset()\n{\n fBlockchainSynced = false;\n lastProcess = 0;\n lastMasternodeList = 0;\n lastMasternodeWinner = 0;\n lastBudgetItem = 0;\n mapSeenSyncMNB.clear();\n mapSeenSyncMNW.clear();\n mapSeenSyncBudget.clear();\n lastFailure = 0;\n nCountFailures = 0;\n sumMasternodeList = 0;\n sumMasternodeWinner = 0;\n sumBudgetItemProp = 0;\n sumBudgetItemFin = 0;\n countMasternodeList = 0;\n countMasternodeWinner = 0;\n countBudgetItemProp = 0;\n countBudgetItemFin = 0;\n RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n RequestedMasternodeAttempt = 0;\n nAssetSyncStarted = GetTime();\n}\n\nvoid CMasternodeSync::AddedMasternodeList(uint256 hash)\n{\n if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) {\n if (mapSeenSyncMNB[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastMasternodeList = GetTime();\n mapSeenSyncMNB[hash]++;\n }\n } else {\n lastMasternodeList = GetTime();\n mapSeenSyncMNB.insert(std::make_pair(hash, 1));\n }\n}\n\nvoid CMasternodeSync::AddedMasternodeWinner(uint256 hash)\n{\n if (masternodePayments.mapMasternodePayeeVotes.count(hash)) {\n if (mapSeenSyncMNW[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastMasternodeWinner = GetTime();\n mapSeenSyncMNW[hash]++;\n }\n } else {\n lastMasternodeWinner = GetTime();\n mapSeenSyncMNW.insert(std::make_pair(hash, 1));\n }\n}\n\nvoid CMasternodeSync::AddedBudgetItem(uint256 hash)\n{\n if (budget.mapSeenMasternodeBudgetProposals.count(hash) || budget.mapSeenMasternodeBudgetVotes.count(hash) ||\n budget.mapSeenFinalizedBudgets.count(hash) || budget.mapSeenFinalizedBudgetVotes.count(hash)) {\n if (mapSeenSyncBudget[hash] < MASTERNODE_SYNC_THRESHOLD) {\n lastBudgetItem = GetTime();\n mapSeenSyncBudget[hash]++;\n }\n } else {\n lastBudgetItem = GetTime();\n mapSeenSyncBudget.insert(std::make_pair(hash, 1));\n }\n}\n\nbool CMasternodeSync::IsBudgetPropEmpty()\n{\n return sumBudgetItemProp == 0 && countBudgetItemProp > 0;\n}\n\nbool CMasternodeSync::IsBudgetFinEmpty()\n{\n return sumBudgetItemFin == 0 && countBudgetItemFin > 0;\n}\n\nvoid CMasternodeSync::GetNextAsset()\n{\n switch (RequestedMasternodeAssets) {\n case (MASTERNODE_SYNC_INITIAL):\n case (MASTERNODE_SYNC_FAILED): \/\/ should never be used here actually, use Reset() instead\n ClearFulfilledRequest();\n RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;\n break;\n case (MASTERNODE_SYNC_SPORKS):\n RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;\n break;\n case (MASTERNODE_SYNC_LIST):\n RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;\n break;\n case (MASTERNODE_SYNC_MNW):\n RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;\n break;\n case (MASTERNODE_SYNC_BUDGET):\n LogPrintf(\"CMasternodeSync::GetNextAsset - Sync has finished\\n\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n break;\n }\n RequestedMasternodeAttempt = 0;\n nAssetSyncStarted = GetTime();\n}\n\nstd::string CMasternodeSync::GetSyncStatus()\n{\n switch (masternodeSync.RequestedMasternodeAssets) {\n case MASTERNODE_SYNC_INITIAL:\n return _(\"MNs synchronization pending...\");\n case MASTERNODE_SYNC_SPORKS:\n return _(\"Synchronizing sporks...\");\n case MASTERNODE_SYNC_LIST:\n return _(\"Synchronizing masternodes...\");\n case MASTERNODE_SYNC_MNW:\n return _(\"Synchronizing masternode winners...\");\n case MASTERNODE_SYNC_BUDGET:\n return _(\"Synchronizing budgets...\");\n case MASTERNODE_SYNC_FAILED:\n return _(\"Synchronization failed\");\n case MASTERNODE_SYNC_FINISHED:\n return _(\"Synchronization finished\");\n }\n return \"\";\n}\n\nvoid CMasternodeSync::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)\n{\n if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { \/\/Sync status count\n int nItemID;\n int nCount;\n vRecv >> nItemID >> nCount;\n\n if (RequestedMasternodeAssets >= MASTERNODE_SYNC_FINISHED) return;\n\n \/\/this means we will receive no further communication\n switch (nItemID) {\n case (MASTERNODE_SYNC_LIST):\n if (nItemID != RequestedMasternodeAssets) return;\n sumMasternodeList += nCount;\n countMasternodeList++;\n break;\n case (MASTERNODE_SYNC_MNW):\n if (nItemID != RequestedMasternodeAssets) return;\n sumMasternodeWinner += nCount;\n countMasternodeWinner++;\n break;\n case (MASTERNODE_SYNC_BUDGET_PROP):\n if (RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;\n sumBudgetItemProp += nCount;\n countBudgetItemProp++;\n break;\n case (MASTERNODE_SYNC_BUDGET_FIN):\n if (RequestedMasternodeAssets != MASTERNODE_SYNC_BUDGET) return;\n sumBudgetItemFin += nCount;\n countBudgetItemFin++;\n break;\n }\n\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync:ProcessMessage - ssc - got inventory count %d %d\\n\", nItemID, nCount);\n }\n}\n\nvoid CMasternodeSync::ClearFulfilledRequest()\n{\n g_connman->ForEachNode([](CNode* pnode) {\n pnode->ClearFulfilledRequest(\"getspork\");\n pnode->ClearFulfilledRequest(\"mnsync\");\n pnode->ClearFulfilledRequest(\"mnwsync\");\n pnode->ClearFulfilledRequest(\"busync\");\n });\n}\n\nvoid CMasternodeSync::Process()\n{\n static int tick = 0;\n const bool isRegTestNet = Params().IsRegTestNet();\n\n if (tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return;\n\n if (IsSynced()) {\n \/*\n Resync if we lose all masternodes from sleep\/wake or failure to sync originally\n *\/\n if (mnodeman.CountEnabled() == 0) {\n Reset();\n } else\n return;\n }\n\n \/\/try syncing again\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (1 * 60) < GetTime()) {\n Reset();\n } else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) {\n return;\n }\n\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\\n\", tick, RequestedMasternodeAssets);\n\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();\n\n \/\/ sporks synced but blockchain is not, wait until we're almost at a recent block to continue\n if (!isRegTestNet && !IsBlockchainSynced() &&\n RequestedMasternodeAssets > MASTERNODE_SYNC_SPORKS) return;\n\n CMasternodeSync* sync = this;\n g_connman->ForEachNodeContinueIf([sync, isRegTestNet](CNode* pnode){\n return sync->SyncWithNode(pnode, isRegTestNet);\n });\n}\n\nbool CMasternodeSync::SyncWithNode(CNode* pnode, bool isRegTestNet)\n{\n if (isRegTestNet) {\n if (RequestedMasternodeAttempt <= 2) {\n pnode->PushMessage(NetMsgType::GETSPORKS); \/\/get current network sporks\n } else if (RequestedMasternodeAttempt < 4) {\n mnodeman.DsegUpdate(pnode);\n } else if (RequestedMasternodeAttempt < 6) {\n int nMnCount = mnodeman.CountEnabled();\n pnode->PushMessage(NetMsgType::GETMNWINNERS, nMnCount); \/\/sync payees\n uint256 n;\n pnode->PushMessage(NetMsgType::BUDGETVOTESYNC, n); \/\/sync masternode votes\n } else {\n RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n }\n RequestedMasternodeAttempt++;\n return false;\n }\n\n \/\/set to synced\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS) {\n if (pnode->HasFulfilledRequest(\"getspork\")) return true;\n pnode->FulfilledRequest(\"getspork\");\n\n pnode->PushMessage(NetMsgType::GETSPORKS); \/\/get current network sporks\n if (RequestedMasternodeAttempt >= 2) GetNextAsset();\n RequestedMasternodeAttempt++;\n return false;\n }\n\n if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {\n LogPrint(BCLog::MASTERNODE, \"CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\\n\", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);\n if (lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) { \/\/hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"mnsync\")) return true;\n pnode->FulfilledRequest(\"mnsync\");\n\n \/\/ timeout\n if (lastMasternodeList == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n LogPrintf(\"CMasternodeSync::Process - ERROR - Sync has failed on %s, will retry later\\n\", \"MASTERNODE_SYNC_LIST\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;\n RequestedMasternodeAttempt = 0;\n lastFailure = GetTime();\n nCountFailures++;\n } else {\n GetNextAsset();\n }\n return false;\n }\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n mnodeman.DsegUpdate(pnode);\n RequestedMasternodeAttempt++;\n return false;\n }\n\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {\n if (lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) { \/\/hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"mnwsync\")) return true;\n pnode->FulfilledRequest(\"mnwsync\");\n\n \/\/ timeout\n if (lastMasternodeWinner == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {\n LogPrintf(\"CMasternodeSync::Process - ERROR - Sync has failed on %s, will retry later\\n\", \"MASTERNODE_SYNC_MNW\");\n RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED;\n RequestedMasternodeAttempt = 0;\n lastFailure = GetTime();\n nCountFailures++;\n } else {\n GetNextAsset();\n }\n return false;\n }\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n int nMnCount = mnodeman.CountEnabled();\n pnode->PushMessage(NetMsgType::GETMNWINNERS, nMnCount); \/\/sync payees\n RequestedMasternodeAttempt++;\n return false;\n }\n }\n\n if (pnode->nVersion >= ActiveProtocol()) {\n if (RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET) {\n \/\/ We'll start rejecting votes if we accidentally get set as synced too soon\n if (lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT * 2 && RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD) {\n \/\/ Hasn't received a new item in the last five seconds, so we'll move to the\n GetNextAsset();\n\n \/\/ Try to activate our masternode if possible\n activeMasternode.ManageStatus();\n return false;\n }\n\n \/\/ timeout\n if (lastBudgetItem == 0 &&\n (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3 || GetTime() - nAssetSyncStarted > MASTERNODE_SYNC_TIMEOUT * 5)) {\n \/\/ maybe there is no budgets at all, so just finish syncing\n GetNextAsset();\n activeMasternode.ManageStatus();\n return false;\n }\n\n if (pnode->HasFulfilledRequest(\"busync\")) return true;\n pnode->FulfilledRequest(\"busync\");\n\n if (RequestedMasternodeAttempt >= MASTERNODE_SYNC_THRESHOLD * 3) return false;\n\n uint256 n;\n pnode->PushMessage(NetMsgType::BUDGETVOTESYNC, n); \/\/sync masternode votes\n RequestedMasternodeAttempt++;\n return false;\n }\n }\n\n return true;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016, Andrej Kislovskij\n *\n * This is PUBLIC DOMAIN software so use at your own risk as it comes\n * with no warranties. This code is yours to share, use and modify without\n * any restrictions or obligations.\n *\n * For more information see conwrap\/LICENSE or refer refer to http:\/\/unlicense.org\n *\n * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)\n *\/\n\n#pragma once\n\n#include <condition_variable>\n#include <exception>\n#include <queue>\n#include <mutex>\n\n\nnamespace conwrap\n{\n\n\ttemplate<typename ResourceType1, typename Container1 = std::deque<ResourceType1>>\n\tclass ConcurrentQueue\n\t{\n\t\tpublic:\n\t\t\ttypedef typename Container1::iterator iterator;\n\t\t\ttypedef typename Container1::const_iterator const_iterator;\n\n\t\t\tConcurrentQueue() {}\n\n\t\t\tConcurrentQueue(const ConcurrentQueue&) = delete;\n\n\t\t\tConcurrentQueue &operator=(const ConcurrentQueue&) = delete;\n\n\t\t\tvirtual ~ConcurrentQueue() {}\n\n\t\t\titerator begin()\n\t\t\t{\n\t\t\t\treturn queue_.c.begin();\n\t\t\t}\n\n\t\t\tconst_iterator begin() const\n\t\t\t{\n\t\t\t\treturn queue_.c.begin();\n\t\t\t}\n\n\t\t\tbool empty() const\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(m_);\n\t\t\t\treturn queue_.empty();\n\t\t\t}\n\n\t\t\titerator end()\n\t\t\t{\n\t\t\t\treturn queue_.c.end();\n\t\t\t}\n\n\t\t\tconst_iterator end() const\n\t\t\t{\n\t\t\t\treturn queue_.c.end();\n\t\t\t}\n\n\t\t\tvoid flush()\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::unique_lock<std::mutex> lock(m_);\n\t\t\t\t\tdata_cond_.wait(lock, [&] { return queue_.empty();});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tResourceType1* get()\n\t\t\t{\n\t\t\t\tResourceType1* result = nullptr;\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(m_);\n\t\t\t\t\tif (!queue_.empty()) {\n\t\t\t\t\t\tresult = &queue_.front();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tvoid push(ResourceType1 item)\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(m_);\n\t\t\t\t\tqueue_.push(std::move(item));\n\t\t\t\t}\n\t\t\t\tdata_cond_.notify_all();\n\t\t\t}\n\n\t\t\tbool remove() {\n\t\t\t\tauto result = false;\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(m_);\n\t\t\t\t\tif (!queue_.empty()) {\n\n\t\t\t\t\t\t\/\/ remove the first item in the queue\n\t\t\t\t\t\tqueue_.pop();\n\t\t\t\t\t\tdata_cond_.notify_all();\n\t\t\t\t\t\tresult = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tunsigned size() const\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(m_);\n\t\t\t\treturn queue_.size();\n\t\t\t}\n\n\t\t\tvoid wait()\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::unique_lock<std::mutex> lock(m_);\n\t\t\t\t\tdata_cond_.wait(lock, [&] {return !queue_.empty();});\n\t\t\t\t}\n\t\t\t}\n\n\t\tprotected:\n\t\t\t\/\/ defining internal struct to gain access to sequence of elements in a std::queue\n\t\t\ttemplate<typename ResourceType2, typename Container2>\n\t\t\tstruct IterableQueue : public std::queue<ResourceType2, Container2>\n\t\t\t{\n\t\t\t\tusing std::queue<ResourceType2, Container2>::c;\n\t\t\t};\n\n\t\tprivate:\n\t\t\tIterableQueue<ResourceType1, Container1> queue_;\n\t\t\tmutable std::mutex m_;\n\t\t\tstd::condition_variable data_cond_;\n\t};\n}\n<commit_msg>Refactoring<commit_after>\/*\n * Copyright 2016, Andrej Kislovskij\n *\n * This is PUBLIC DOMAIN software so use at your own risk as it comes\n * with no warranties. This code is yours to share, use and modify without\n * any restrictions or obligations.\n *\n * For more information see conwrap\/LICENSE or refer refer to http:\/\/unlicense.org\n *\n * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)\n *\/\n\n#pragma once\n\n#include <condition_variable>\n#include <exception>\n#include <queue>\n#include <mutex>\n\n\nnamespace conwrap\n{\n\n\ttemplate<typename ResourceType1, typename Container1 = std::deque<ResourceType1>>\n\tclass ConcurrentQueue\n\t{\n\t\tpublic:\n\t\t\ttypedef typename Container1::iterator iterator;\n\t\t\ttypedef typename Container1::const_iterator const_iterator;\n\n\t\t\tConcurrentQueue() {}\n\n\t\t\tConcurrentQueue(const ConcurrentQueue&) = delete;\n\n\t\t\tConcurrentQueue &operator=(const ConcurrentQueue&) = delete;\n\n\t\t\tvirtual ~ConcurrentQueue() {}\n\n\t\t\titerator begin()\n\t\t\t{\n\t\t\t\treturn queue.c.begin();\n\t\t\t}\n\n\t\t\tconst_iterator begin() const\n\t\t\t{\n\t\t\t\treturn queue.c.begin();\n\t\t\t}\n\n\t\t\tbool empty() const\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(queueMutex);\n\t\t\t\treturn queue.empty();\n\t\t\t}\n\n\t\t\titerator end()\n\t\t\t{\n\t\t\t\treturn queue.c.end();\n\t\t\t}\n\n\t\t\tconst_iterator end() const\n\t\t\t{\n\t\t\t\treturn queue.c.end();\n\t\t\t}\n\n\t\t\tvoid flush()\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::unique_lock<std::mutex> lock(queueMutex);\n\t\t\t\t\tconditionVariable.wait(lock, [&]\n\t\t\t\t\t{\n\t\t\t\t\t\treturn queue.empty();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tResourceType1* get()\n\t\t\t{\n\t\t\t\tResourceType1* resultPtr = nullptr;\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(queueMutex);\n\t\t\t\t\tif (!queue.empty()) {\n\t\t\t\t\t\tresultPtr = &queue.front();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn resultPtr;\n\t\t\t}\n\n\t\t\tvoid push(ResourceType1 item)\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(queueMutex);\n\t\t\t\t\tqueue.push(std::move(item));\n\t\t\t\t}\n\t\t\t\tconditionVariable.notify_all();\n\t\t\t}\n\n\t\t\tbool remove() {\n\t\t\t\tauto result = false;\n\t\t\t\t{\n\t\t\t\t\tstd::lock_guard<std::mutex> lock(queueMutex);\n\t\t\t\t\tif (!queue.empty()) {\n\n\t\t\t\t\t\t\/\/ remove the first item in the queue\n\t\t\t\t\t\tqueue.pop();\n\t\t\t\t\t\tconditionVariable.notify_all();\n\t\t\t\t\t\tresult = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tunsigned size() const\n\t\t\t{\n\t\t\t\tstd::lock_guard<std::mutex> lock(queueMutex);\n\t\t\t\treturn queue.size();\n\t\t\t}\n\n\t\t\tvoid wait()\n\t\t\t{\n\t\t\t\t{\n\t\t\t\t\tstd::unique_lock<std::mutex> lock(queueMutex);\n\t\t\t\t\tconditionVariable.wait(lock, [&]\n\t\t\t\t\t{\n\t\t\t\t\t\treturn !queue.empty();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\tprotected:\n\t\t\t\/\/ defining internal struct to gain access to sequence of elements in a std::queue\n\t\t\ttemplate<typename ResourceType2, typename Container2>\n\t\t\tstruct IterableQueue : public std::queue<ResourceType2, Container2>\n\t\t\t{\n\t\t\t\tusing std::queue<ResourceType2, Container2>::c;\n\t\t\t};\n\n\t\tprivate:\n\t\t\tIterableQueue<ResourceType1, Container1> queue;\n\t\t\tmutable std::mutex queueMutex;\n\t\t\tstd::condition_variable conditionVariable;\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Created by Jian Chen\n * @since 2016.04.12\n * @author Jian Chen <admin@chensoft.com>\n * @link http:\/\/chensoft.com\n *\/\n#ifdef CHEN_OS_UNIX\n\n#include \"so_socket_unix.hpp\"\n#include <chen\/net\/tcp\/tcp_server.hpp>\n#include <chen\/net\/so\/so_error.hpp>\n#include <sys\/socket.h>\n#include <sys\/select.h>\n#include <arpa\/inet.h>\n#include <cstring>\n#include <cerrno>\n\nusing namespace chen;\nusing namespace chen::so;\nusing namespace chen::tcp;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ server\nvoid server::bind(const std::string &addr, std::uint16_t port)\n{\n \/\/ check already bind\n if (!this->_impl->_socket || this->localPort())\n this->build(); \/\/ rebuild\n\n \/\/ bind address and port\n struct sockaddr_in in;\n ::memset(&in, 0, sizeof(in));\n\n in.sin_family = AF_INET;\n in.sin_addr.s_addr = ::inet_addr(addr.c_str());\n in.sin_port = htons(port);\n\n if (::bind(this->_impl->_socket, (struct sockaddr*)&in, sizeof(in)) == -1)\n throw error_bind(std::strerror(errno));\n}\n\nvoid server::listen()\n{\n if (::listen(this->_impl->_socket, SOMAXCONN) == -1)\n throw error_listen(std::strerror(errno));\n}\n\nstd::unique_ptr<chen::tcp::conn> server::accept(float timeout)\n{\n struct timeval tv;\n tv.tv_sec = static_cast<int>(timeout);\n tv.tv_usec = static_cast<int>((timeout - tv.tv_sec) * 1000000);\n\n fd_set set;\n\n FD_ZERO(&set);\n FD_SET(this->_impl->_socket, &set);\n\n auto ret = ::select(this->_impl->_socket + 1, &set, nullptr, nullptr, timeout ? &tv : nullptr);\n\n if (ret == 1)\n {\n struct sockaddr_in in;\n socklen_t len = sizeof(in);\n\n auto so = ::accept(this->_impl->_socket, (struct sockaddr*)&in, &len);\n\n if (so != -1)\n return std::unique_ptr<chen::tcp::conn>(new chen::tcp::conn(&so));\n else\n throw error_accept(std::strerror(errno));\n }\n else if (!ret || (errno == EBADF))\n {\n \/\/ timeout or shutdown or close\n return nullptr;\n }\n else\n {\n throw error_accept(std::strerror(errno));\n }\n}\n\n#endif<commit_msg>tcp: use poll instead of select in accept<commit_after>\/**\n * Created by Jian Chen\n * @since 2016.04.12\n * @author Jian Chen <admin@chensoft.com>\n * @link http:\/\/chensoft.com\n *\/\n#ifdef CHEN_OS_UNIX\n\n#include \"so_socket_unix.hpp\"\n#include <chen\/net\/tcp\/tcp_server.hpp>\n#include <chen\/net\/so\/so_error.hpp>\n#include <sys\/socket.h>\n#include <sys\/poll.h>\n#include <arpa\/inet.h>\n#include <cstring>\n#include <cerrno>\n\nusing namespace chen;\nusing namespace chen::so;\nusing namespace chen::tcp;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ server\nvoid server::bind(const std::string &addr, std::uint16_t port)\n{\n \/\/ check already bind\n if (!this->_impl->_socket || this->localPort())\n this->build(); \/\/ rebuild\n\n \/\/ bind address and port\n struct sockaddr_in in;\n ::memset(&in, 0, sizeof(in));\n\n in.sin_family = AF_INET;\n in.sin_addr.s_addr = ::inet_addr(addr.c_str());\n in.sin_port = htons(port);\n\n if (::bind(this->_impl->_socket, (struct sockaddr*)&in, sizeof(in)) == -1)\n throw error_bind(std::strerror(errno));\n}\n\nvoid server::listen()\n{\n if (::listen(this->_impl->_socket, SOMAXCONN) == -1)\n throw error_listen(std::strerror(errno));\n}\n\nstd::unique_ptr<chen::tcp::conn> server::accept(float timeout)\n{\n struct pollfd poll;\n\n poll.fd = this->_impl->_socket;\n poll.events = POLLIN;\n\n auto ret = ::poll(&poll, 1, timeout ? static_cast<int>(timeout * 1000) : -1);\n\n if ((ret == 1) && (poll.revents & POLLIN))\n {\n struct sockaddr_in in;\n socklen_t len = sizeof(in);\n\n auto so = ::accept(this->_impl->_socket, (struct sockaddr*)&in, &len);\n\n if (so != -1)\n return std::unique_ptr<chen::tcp::conn>(new chen::tcp::conn(&so));\n else\n throw error_accept(std::strerror(errno));\n }\n else if (!ret || (errno == EBADF))\n {\n \/\/ timeout or shutdown or close\n return nullptr;\n }\n else\n {\n throw error_accept(std::strerror(errno));\n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>#include \"material\/layer.h\"\n#include \"scene\/hitable.h\"\n\nnamespace aten\n{\n\tvec3 LayeredBSDF::sampleAlbedoMap(real u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tvec3 albedo(1);\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\t\/\/ TODO\n\t\t\tauto c = mtrl->color();\n\t\t\tauto a = mtrl->sampleAlbedoMap(u, v);\n\n\t\t\talbedo *= c * a;\n\t\t}\n\n\t\treturn std::move(albedo);\n\t}\n\n\tvoid LayeredBSDF::applyNormalMap(\n\t\tconst vec3& orgNml,\n\t\tvec3& newNml,\n\t\treal u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\tnewNml = orgNml;\n\t\t}\n\t\telse {\n\t\t\t\/\/ ŕ\\w NormalMap Kp.\n\t\t\tauto mtrl = m_layer[0];\n\t\t\tmtrl->applyNormalMap(orgNml, newNml, u, v);\n\t\t}\n\t}\n\n\treal LayeredBSDF::computeFresnel(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal outsideIor\/*= 1*\/) const\n\t{\n\t\t\/\/ TODO\n\t\tAT_ASSERT(false);\n\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\treturn real(1);\n\t\t}\n\t\telse {\n\t\t\t\/\/ ŕ\\w̃tlԂ.\n\t\t\tauto mtrl = m_layer[0];\n\t\t\tauto f = mtrl->computeFresnel(normal, wi, wo, outsideIor);\n\t\t\treturn f;\n\t\t}\n\t}\n\n\tvoid LayeredBSDF::add(material* mtrl)\n\t{\n\t\tm_layer.push_back(mtrl);\n\t}\n\n\tmaterial::sampling LayeredBSDF::sample(\n\t\tconst ray& ray,\n\t\tconst vec3& normal,\n\t\tconst hitrecord& hitrec,\n\t\tsampler* sampler,\n\t\treal u, real v) const\n\t{\n\t\tsampling ret;\n\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\tAT_ASSERT(false);\n\t\t\treturn std::move(ret);\n\t\t}\n\n\t\treal sumW = 0;\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto sampleres = mtrl->sample(ray, appliedNml, hitrec, sampler, u, v);\n\n\t\t\tconst auto weight = sampleres.fresnel;\n\n\t\t\tret.pdf += weight * sampleres.pdf;\n\t\t\tret.bsdf += weight * sampleres.bsdf;\n\n\t\t\t\/\/ TODO\n\t\t\t\/\/ ret.fresnel\n\n\t\t\tsumW += weight;\n\n\t\t\tif (i == 0) {\n\t\t\t\tret.dir = sampleres.dir;\n\t\t\t}\n\t\t}\n\n\t\tret.pdf \/= sumW;\n\t\tret.bsdf \/= sumW;\n\n\t\treturn std::move(ret);\n\t}\n\n\treal LayeredBSDF::pdf(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal u, real v,\n\t\tsampler* sampler) const\n\t{\n\t\tauto num = m_layer.size();\n\t\t\n\t\treal pdf = 0;\n\n\t\treal sumW = 0;\n\t\treal ior = 1;\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto p = mtrl->pdf(appliedNml, wi, wo, u, v, sampler);\n\t\t\tauto f = mtrl->computeFresnel(appliedNml, wi, wo, ior);\n\n\t\t\tior = mtrl->ior();\n\n\t\t\tpdf += f * p;\n\n\t\t\tsumW += f;\n\t\t}\n\n\t\tpdf \/= sumW;\n\n\t\treturn pdf;\n\t}\n\n\tvec3 LayeredBSDF::sampleDirection(\n\t\tconst ray& ray,\n\t\tconst vec3& normal,\n\t\treal u, real v,\n\t\tsampler* sampler) const\n\t{\n\t\tauto num = m_layer.size();\n\t\tAT_ASSERT(num > 0);\n\n\t\tauto mtrl = m_layer[0];\n\t\t\n\t\tauto dir = mtrl->sampleDirection(ray, normal, u, v, sampler);\n\n\t\treturn std::move(dir);\n\t}\n\n\tvec3 LayeredBSDF::bsdf(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tvec3 bsdf;\n\n\t\treal sumW = 0;\n\t\treal ior = 1;\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto b = mtrl->bsdf(appliedNml, wi, wo, u, v);\n\t\t\tauto f = mtrl->computeFresnel(appliedNml, wi, wo, ior);\n\n\t\t\tior = mtrl->ior();\n\n\t\t\tbsdf += f * b;\n\n\t\t\tsumW += f;\n\t\t}\n\n\t\tbsdf \/= sumW;\n\n\t\treturn std::move(bsdf);\n\t}\n}\n<commit_msg>Modify to compute weight.<commit_after>#include \"material\/layer.h\"\n#include \"scene\/hitable.h\"\n\nnamespace aten\n{\n\tvec3 LayeredBSDF::sampleAlbedoMap(real u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tvec3 albedo(1);\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\t\/\/ TODO\n\t\t\tauto c = mtrl->color();\n\t\t\tauto a = mtrl->sampleAlbedoMap(u, v);\n\n\t\t\talbedo *= c * a;\n\t\t}\n\n\t\treturn std::move(albedo);\n\t}\n\n\tvoid LayeredBSDF::applyNormalMap(\n\t\tconst vec3& orgNml,\n\t\tvec3& newNml,\n\t\treal u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\tnewNml = orgNml;\n\t\t}\n\t\telse {\n\t\t\t\/\/ ŕ\\w NormalMap Kp.\n\t\t\tauto mtrl = m_layer[0];\n\t\t\tmtrl->applyNormalMap(orgNml, newNml, u, v);\n\t\t}\n\t}\n\n\treal LayeredBSDF::computeFresnel(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal outsideIor\/*= 1*\/) const\n\t{\n\t\t\/\/ TODO\n\t\tAT_ASSERT(false);\n\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\treturn real(1);\n\t\t}\n\t\telse {\n\t\t\t\/\/ ŕ\\w̃tlԂ.\n\t\t\tauto mtrl = m_layer[0];\n\t\t\tauto f = mtrl->computeFresnel(normal, wi, wo, outsideIor);\n\t\t\treturn f;\n\t\t}\n\t}\n\n\tvoid LayeredBSDF::add(material* mtrl)\n\t{\n\t\tm_layer.push_back(mtrl);\n\t}\n\n\tmaterial::sampling LayeredBSDF::sample(\n\t\tconst ray& ray,\n\t\tconst vec3& normal,\n\t\tconst hitrecord& hitrec,\n\t\tsampler* sampler,\n\t\treal u, real v) const\n\t{\n\t\tsampling ret;\n\n\t\tauto num = m_layer.size();\n\n\t\tif (num == 0) {\n\t\t\tAT_ASSERT(false);\n\t\t\treturn std::move(ret);\n\t\t}\n\n\t\treal weight = 1;\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto sampleres = mtrl->sample(ray, appliedNml, hitrec, sampler, u, v);\n\n\t\t\tconst auto f = aten::clamp<real>(sampleres.fresnel, 0, 1);\n\n\t\t\tret.pdf += weight * f * sampleres.pdf;\n\t\t\tret.bsdf += weight * f * sampleres.bsdf;\n\n\t\t\t\/\/ TODO\n\t\t\t\/\/ ret.fresnel\n\n\t\t\tweight = aten::clamp<real>(weight - f, 0, 1);\n\t\t\tif (weight <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (i == 0) {\n\t\t\t\tret.dir = sampleres.dir;\n\t\t\t}\n\t\t}\n\n\t\treturn std::move(ret);\n\t}\n\n\treal LayeredBSDF::pdf(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal u, real v,\n\t\tsampler* sampler) const\n\t{\n\t\tauto num = m_layer.size();\n\t\t\n\t\treal pdf = 0;\n\n\t\treal weight = 1;\n\t\treal ior = 1;\t\/\/ ^󂩂n߂.\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto p = mtrl->pdf(appliedNml, wi, wo, u, v, sampler);\n\t\t\tauto f = mtrl->computeFresnel(appliedNml, wi, wo, ior);\n\n\t\t\tf = aten::clamp<real>(f, 0, 1);\n\n\t\t\tpdf += weight * f * p;\n\n\t\t\tweight = aten::clamp<real>(weight - f, 0, 1);\n\t\t\tif (weight <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ w̒lwɎg.\n\t\t\tior = mtrl->ior();\n\t\t}\n\n\t\treturn pdf;\n\t}\n\n\tvec3 LayeredBSDF::sampleDirection(\n\t\tconst ray& ray,\n\t\tconst vec3& normal,\n\t\treal u, real v,\n\t\tsampler* sampler) const\n\t{\n\t\tauto num = m_layer.size();\n\t\tAT_ASSERT(num > 0);\n\n\t\tauto mtrl = m_layer[0];\n\t\t\n\t\tauto dir = mtrl->sampleDirection(ray, normal, u, v, sampler);\n\n\t\treturn std::move(dir);\n\t}\n\n\tvec3 LayeredBSDF::bsdf(\n\t\tconst vec3& normal,\n\t\tconst vec3& wi,\n\t\tconst vec3& wo,\n\t\treal u, real v) const\n\t{\n\t\tauto num = m_layer.size();\n\n\t\tvec3 bsdf;\n\n\t\treal weight = 1;\n\t\treal ior = 1;\t\/\/ ^󂩂n߂.\n\n\t\tfor (int i = 0; i < num; i++) {\n\t\t\tauto mtrl = m_layer[i];\n\n\t\t\tvec3 appliedNml = normal;\n\n\t\t\t\/\/ NOTE\n\t\t\t\/\/ Oł͍ŕ\\w NormalMap KpĂ.\n\t\t\tif (i > 0) {\n\t\t\t\tmtrl->applyNormalMap(normal, appliedNml, u, v);\n\t\t\t}\n\n\t\t\tauto b = mtrl->bsdf(appliedNml, wi, wo, u, v);\n\t\t\tauto f = mtrl->computeFresnel(appliedNml, wi, wo, ior);\n\n\t\t\tf = aten::clamp<real>(f, 0, 1);\n\n\t\t\tbsdf += weight * f * b;\n\n\t\t\tweight = aten::clamp<real>(weight - f, 0, 1);\n\t\t\tif (weight <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ w̒lwɎg.\n\t\t\tior = mtrl->ior();\n\t\t}\n\n\t\treturn std::move(bsdf);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <lib\/battery\/battery.h>\n#include \"analog_battery.h\"\n\n\/\/ Defaults to use if the parameters are not set\n#if BOARD_NUMBER_BRICKS > 0\n#if defined(BOARD_BATT_V_LIST) && defined(BOARD_BATT_I_LIST)\nstatic constexpr int DEFAULT_V_CHANNEL[BOARD_NUMBER_BRICKS] = BOARD_BATT_V_LIST;\nstatic constexpr int DEFAULT_I_CHANNEL[BOARD_NUMBER_BRICKS] = BOARD_BATT_I_LIST;\n#else\nstatic constexpr int DEFAULT_V_CHANNEL[BOARD_NUMBER_BRICKS] = {0};\nstatic constexpr int DEFAULT_I_CHANNEL[BOARD_NUMBER_BRICKS] = {0};\n#endif\n#else\nstatic constexpr int DEFAULT_V_CHANNEL[1] = {0};\nstatic constexpr int DEFAULT_I_CHANNEL[1] = {0};\n#endif\n\nAnalogBattery::AnalogBattery(int index, ModuleParams *parent, const int sample_interval_us) :\n\tBattery(index, parent, sample_interval_us)\n{\n\tchar param_name[17];\n\n\t_analog_param_handles.v_offs_cur = param_find(\"BAT_V_OFFS_CURR\");\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_V_DIV\", index);\n\t_analog_param_handles.v_div = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_A_PER_V\", index);\n\t_analog_param_handles.a_per_v = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_V_CHANNEL\", index);\n\t_analog_param_handles.v_channel = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_I_CHANNEL\", index);\n\t_analog_param_handles.i_channel = param_find(param_name);\n\n\t_analog_param_handles.v_div_old = param_find(\"BAT_V_DIV\");\n\t_analog_param_handles.a_per_v_old = param_find(\"BAT_A_PER_V\");\n\t_analog_param_handles.adc_channel_old = param_find(\"BAT_ADC_CHANNEL\");\n}\n\nvoid\nAnalogBattery::updateBatteryStatusADC(hrt_abstime timestamp, float voltage_raw, float current_raw,\n\t\t\t\t int source, int priority, float throttle_normalized)\n{\n\tfloat voltage_v = voltage_raw * _analog_params.v_div;\n\tfloat current_a = (current_raw - _analog_params.v_offs_cur) * _analog_params.a_per_v;\n\n\tbool connected = voltage_v > BOARD_ADC_OPEN_CIRCUIT_V &&\n\t\t\t (BOARD_ADC_OPEN_CIRCUIT_V <= BOARD_VALID_UV || is_valid());\n\n\n\tBattery::updateBatteryStatus(timestamp, voltage_v, current_a, connected,\n\t\t\t\t source, priority, throttle_normalized);\n}\n\nbool AnalogBattery::is_valid()\n{\n#ifdef BOARD_BRICK_VALID_LIST\n\tbool valid[BOARD_NUMBER_BRICKS] = BOARD_BRICK_VALID_LIST;\n\treturn valid[_index - 1];\n#else\n\t\/\/ TODO: Maybe return false instead?\n\treturn true;\n#endif\n}\n\nint AnalogBattery::get_voltage_channel()\n{\n\tif (_analog_params.v_channel >= 0) {\n\t\treturn _analog_params.v_channel;\n\n\t} else {\n\t\treturn DEFAULT_V_CHANNEL[_index - 1];\n\t}\n}\n\nint AnalogBattery::get_current_channel()\n{\n\tif (_analog_params.i_channel >= 0) {\n\t\treturn _analog_params.i_channel;\n\n\t} else {\n\t\treturn DEFAULT_I_CHANNEL[_index - 1];\n\t}\n}\n\nvoid\nAnalogBattery::updateParams()\n{\n\tif (_index == 1) {\n\t\tmigrateParam<float>(_analog_param_handles.v_div_old, _analog_param_handles.v_div, &_analog_params.v_div_old,\n\t\t\t\t &_analog_params.v_div, _first_parameter_update);\n\t\tmigrateParam<float>(_analog_param_handles.a_per_v_old, _analog_param_handles.a_per_v, &_analog_params.a_per_v_old,\n\t\t\t\t &_analog_params.a_per_v, _first_parameter_update);\n\t\tmigrateParam<int>(_analog_param_handles.adc_channel_old, _analog_param_handles.v_channel,\n\t\t\t\t &_analog_params.adc_channel_old, &_analog_params.v_channel, _first_parameter_update);\n\n\t} else {\n\t\tparam_get(_analog_param_handles.v_div, &_analog_params.v_div);\n\t\tparam_get(_analog_param_handles.a_per_v, &_analog_params.a_per_v);\n\t\tparam_get(_analog_param_handles.v_channel, &_analog_params.v_channel);\n\t}\n\n\tparam_get(_analog_param_handles.i_channel, &_analog_params.i_channel);\n\tparam_get(_analog_param_handles.v_offs_cur, &_analog_params.v_offs_cur);\n\n\tif (_analog_params.v_div <= 0.0f) {\n\t\t\/* apply scaling according to defaults if set to default *\/\n\t\t_analog_params.v_div = BOARD_BATTERY1_V_DIV;\n\t\tparam_set_no_notification(_analog_param_handles.v_div, &_analog_params.v_div);\n\n\t\tif (_index == 1) {\n\t\t\t_analog_params.v_div_old = BOARD_BATTERY1_V_DIV;\n\t\t\tparam_set_no_notification(_analog_param_handles.v_div_old, &_analog_params.v_div_old);\n\t\t}\n\t}\n\n\tif (_analog_params.a_per_v <= 0.0f) {\n\t\t\/* apply scaling according to defaults if set to default *\/\n\n\t\t_analog_params.a_per_v = BOARD_BATTERY1_A_PER_V;\n\t\tparam_set_no_notification(_analog_param_handles.a_per_v, &_analog_params.a_per_v);\n\n\t\tif (_index == 1) {\n\t\t\t_analog_params.a_per_v_old = BOARD_BATTERY1_A_PER_V;\n\t\t\tparam_set_no_notification(_analog_param_handles.a_per_v_old, &_analog_params.a_per_v_old);\n\t\t}\n\t}\n\n\tBattery::updateParams();\n}\n<commit_msg>batterry_status: fix checking default a_per_v<commit_after>#include <lib\/battery\/battery.h>\n#include \"analog_battery.h\"\n\n\/\/ Defaults to use if the parameters are not set\n#if BOARD_NUMBER_BRICKS > 0\n#if defined(BOARD_BATT_V_LIST) && defined(BOARD_BATT_I_LIST)\nstatic constexpr int DEFAULT_V_CHANNEL[BOARD_NUMBER_BRICKS] = BOARD_BATT_V_LIST;\nstatic constexpr int DEFAULT_I_CHANNEL[BOARD_NUMBER_BRICKS] = BOARD_BATT_I_LIST;\n#else\nstatic constexpr int DEFAULT_V_CHANNEL[BOARD_NUMBER_BRICKS] = {0};\nstatic constexpr int DEFAULT_I_CHANNEL[BOARD_NUMBER_BRICKS] = {0};\n#endif\n#else\nstatic constexpr int DEFAULT_V_CHANNEL[1] = {0};\nstatic constexpr int DEFAULT_I_CHANNEL[1] = {0};\n#endif\n\nAnalogBattery::AnalogBattery(int index, ModuleParams *parent, const int sample_interval_us) :\n\tBattery(index, parent, sample_interval_us)\n{\n\tchar param_name[17];\n\n\t_analog_param_handles.v_offs_cur = param_find(\"BAT_V_OFFS_CURR\");\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_V_DIV\", index);\n\t_analog_param_handles.v_div = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_A_PER_V\", index);\n\t_analog_param_handles.a_per_v = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_V_CHANNEL\", index);\n\t_analog_param_handles.v_channel = param_find(param_name);\n\n\tsnprintf(param_name, sizeof(param_name), \"BAT%d_I_CHANNEL\", index);\n\t_analog_param_handles.i_channel = param_find(param_name);\n\n\t_analog_param_handles.v_div_old = param_find(\"BAT_V_DIV\");\n\t_analog_param_handles.a_per_v_old = param_find(\"BAT_A_PER_V\");\n\t_analog_param_handles.adc_channel_old = param_find(\"BAT_ADC_CHANNEL\");\n}\n\nvoid\nAnalogBattery::updateBatteryStatusADC(hrt_abstime timestamp, float voltage_raw, float current_raw,\n\t\t\t\t int source, int priority, float throttle_normalized)\n{\n\tfloat voltage_v = voltage_raw * _analog_params.v_div;\n\tfloat current_a = (current_raw - _analog_params.v_offs_cur) * _analog_params.a_per_v;\n\n\tbool connected = voltage_v > BOARD_ADC_OPEN_CIRCUIT_V &&\n\t\t\t (BOARD_ADC_OPEN_CIRCUIT_V <= BOARD_VALID_UV || is_valid());\n\n\n\tBattery::updateBatteryStatus(timestamp, voltage_v, current_a, connected,\n\t\t\t\t source, priority, throttle_normalized);\n}\n\nbool AnalogBattery::is_valid()\n{\n#ifdef BOARD_BRICK_VALID_LIST\n\tbool valid[BOARD_NUMBER_BRICKS] = BOARD_BRICK_VALID_LIST;\n\treturn valid[_index - 1];\n#else\n\t\/\/ TODO: Maybe return false instead?\n\treturn true;\n#endif\n}\n\nint AnalogBattery::get_voltage_channel()\n{\n\tif (_analog_params.v_channel >= 0) {\n\t\treturn _analog_params.v_channel;\n\n\t} else {\n\t\treturn DEFAULT_V_CHANNEL[_index - 1];\n\t}\n}\n\nint AnalogBattery::get_current_channel()\n{\n\tif (_analog_params.i_channel >= 0) {\n\t\treturn _analog_params.i_channel;\n\n\t} else {\n\t\treturn DEFAULT_I_CHANNEL[_index - 1];\n\t}\n}\n\nvoid\nAnalogBattery::updateParams()\n{\n\tif (_index == 1) {\n\t\tmigrateParam<float>(_analog_param_handles.v_div_old, _analog_param_handles.v_div, &_analog_params.v_div_old,\n\t\t\t\t &_analog_params.v_div, _first_parameter_update);\n\t\tmigrateParam<float>(_analog_param_handles.a_per_v_old, _analog_param_handles.a_per_v, &_analog_params.a_per_v_old,\n\t\t\t\t &_analog_params.a_per_v, _first_parameter_update);\n\t\tmigrateParam<int>(_analog_param_handles.adc_channel_old, _analog_param_handles.v_channel,\n\t\t\t\t &_analog_params.adc_channel_old, &_analog_params.v_channel, _first_parameter_update);\n\n\t} else {\n\t\tparam_get(_analog_param_handles.v_div, &_analog_params.v_div);\n\t\tparam_get(_analog_param_handles.a_per_v, &_analog_params.a_per_v);\n\t\tparam_get(_analog_param_handles.v_channel, &_analog_params.v_channel);\n\t}\n\n\tparam_get(_analog_param_handles.i_channel, &_analog_params.i_channel);\n\tparam_get(_analog_param_handles.v_offs_cur, &_analog_params.v_offs_cur);\n\n\tif (_analog_params.v_div <= 0.0f) {\n\t\t\/* apply scaling according to defaults if set to default *\/\n\t\t_analog_params.v_div = BOARD_BATTERY1_V_DIV;\n\t\tparam_set_no_notification(_analog_param_handles.v_div, &_analog_params.v_div);\n\n\t\tif (_index == 1) {\n\t\t\t_analog_params.v_div_old = BOARD_BATTERY1_V_DIV;\n\t\t\tparam_set_no_notification(_analog_param_handles.v_div_old, &_analog_params.v_div_old);\n\t\t}\n\t}\n\n\tif (_analog_params.a_per_v < 0.0f) {\n\t\t\/* apply scaling according to defaults if set to default *\/\n\n\t\t_analog_params.a_per_v = BOARD_BATTERY1_A_PER_V;\n\t\tparam_set_no_notification(_analog_param_handles.a_per_v, &_analog_params.a_per_v);\n\n\t\tif (_index == 1) {\n\t\t\t_analog_params.a_per_v_old = BOARD_BATTERY1_A_PER_V;\n\t\t\tparam_set_no_notification(_analog_param_handles.a_per_v_old, &_analog_params.a_per_v_old);\n\t\t}\n\t}\n\n\tBattery::updateParams();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main_test.cpp\n\/\/ RosterDesNurses\n\/\/\n\/\/ Created by Jeremy Omer on 04\/03\/2015.\n\/\/ Copyright (c) 2015 Jeremy Omer. All rights reserved.\n\/\/\n\n#include \"main_test.h\"\n#include \"ReadWrite.h\"\n#include \"Greedy.h\"\n#include \"MasterProblem.h\"\n#include \"SubProblem.h\"\n#include \"CbcModeler.h\"\n#include \"MyTools.h\"\n\nvoid main_test()\n{\n\ttestFunction_Antoine();\n\t\/\/ testFunction_Jeremy();\n\t\/\/testFunction_Samuel();\n}\n\n\/\/ Function for testing parts of the code (Antoine)\nvoid testFunction_Antoine(){\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n \/\/ Create a log file\n string logFile = \"logs\/test.log\";\n Tools::LogOutput logStream(logFile);\n\n \/\/Create an output file\n string outFile = \"outfiles\/test.out\";\n Tools::LogOutput outStream(outFile);\n\n string data = \"testdatasets\/\";\/\/ testdatasets datasets\n const char* inst = \"n012w8\";\/\/ n100w4 n030w4 n005w4\n\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n \/\/n005w4: {1, 2, 3, 3}\n \/\/n012w8: {3, 5, 0, 2, 0, 4, 5, 2}\n vector<int> numberWeek = {3, 5, 0, 2, 0, 4, 5, 2};\n vector<string> weekPaths(numberWeek.size());\n for(int i=0; i<numberWeek.size(); ++i){\n string path = data + inst + \"\/WD-\" + inst + \"-\"+std::to_string(numberWeek[i])+\".txt\";\n weekPaths[i] = path;\n }\n string firstHistoryPath = data + inst + \"\/H0-\" + inst + \"-0.txt\";\n\n \/\/ Read the input data from files\n Scenario* pScen = ReadWrite::readScenario(scenarPath);\n Preferences preferences;\n Demand* pWeekDemand = ReadWrite::readWeeks(weekPaths, pScen);\n ReadWrite::readHistory(firstHistoryPath,pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n \/\/ logStream << *pScen << std::endl;\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/ Write the aggregate information on the demand\n \/\/\n\n\n \/\/ Write aggregate information on the cover capacity of the staff\n \/\/ (TBD)\n\n \/\/Compute initial solution\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n outStream << pGreedy->solutionToLogString();\n\n \/\/ Instantiate the solver class as a test\n \/\/\n MasterProblem* pBCP =\n new MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState(), S_BCP, pGreedy->getSolution());\n pBCP->solve();\n\n \/\/ Write the solution in the required output format\n vector<string> solutions = pBCP->solutionToString(pScen->nbWeeks());\n for(int w=0; w<pScen->nbWeeks(); ++w){\n int thisWeek = w+pScen->thisWeek();\n char solutionFile[30];\n snprintf ( solutionFile, 30, \"outfiles\/Sol-%s-%d-%d.txt\", inst, numberWeek[w], thisWeek );\n Tools::LogOutput solutionStream(solutionFile);\n solutionStream << solutions[w];\n }\n\n \/\/ Write the solution in an output file\n outStream << pBCP->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertotal->dSinceInit());\n logStream.print(\"\\n\");\n\n\n \/\/ free the allocated pointers\n \/\/\n \/\/ delete vrp;\n delete timertotal;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n delete pBCP;\n}\n\n\n\/\/ Function for testing parts of the code (Jeremy)\nvoid testFunction_Jeremy(){\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n \/\/ Create a log file\n string logFile = \"..\/logfiles\/test.log\";\n Tools::LogOutput logStream(logFile);\n\n\n \/\/ Read the input data from files\n Scenario* pScen = ReadWrite::readScenario(\"datasets\/n030w4\/Sc-n030w4.txt\");\n Demand* pWeekDemand = ReadWrite::readWeek(\"datasets\/n030w4\/WD-n030w4-1.txt\", pScen);\n ReadWrite::readHistory(\"datasets\/n030w4\/H0-n030w4-0.txt\",pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n \/\/ logStream << *pScen << std::endl;\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/ Write the aggregate information on the demand\n \/\/\n\n\n \/\/ Write aggregate information on the cover capacity of the staff\n \/\/ (TBD)\n\n \/\/ Instantiate the solver class as a test\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand,\tpScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n\n\t\/****************************************\n\t* Test the CBC modeler\n\t*****************************************\/\n\n\t\/\/ Instantiate a master problem to create the mathematical programming model\n\t\/\/ with the columns deduced from the solution of the greedy\n\tMasterProblem* pSolverMP =\n\t\tnew MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(),\n\t\tpScen->pInitialState(), S_CBC, pGreedy->getSolution());\n\tpSolverMP->solve();\n\n\tCoinModeler* coinModel = (CoinModeler*) pSolverMP->getModel();\n\tCbcModeler* cbcModel =\n\t\tnew CbcModeler(coinModel->getCoreVars(),coinModel->getColumns(),coinModel->getCons());\n\n\t\/\/ cbcModel->setModel();\n\tcbcModel->solve();\n\n \/\/ Write the solution in the required output format\n string outFile = \"outfiles\/solution.out\";\n Tools::LogOutput outStream(outFile);\n outStream << pGreedy->solutionToString();\n\n \/\/ Write the solution and advanced information in a more convenient format\n string outLog = \"outfiles\/log.out\";\n Tools::LogOutput outLogStream(outLog);\n outLogStream << pGreedy->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertotal->dSinceInit());\n logStream.print(\"\\n\");\n\n \/\/ free the allocated pointers\n \/\/\n delete timertotal;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n\tdelete pSolverMP;\n\tdelete cbcModel;\n\n\n}\n\n\/\/ Function for testing parts of the code (Samuel)\nvoid testFunction_Samuel(){\n\n Tools::Timer* timertest = new Tools::Timer();\n timertest->init();\n timertest->start();\n\n \/\/ log + output\n \/\/\n string logFile = \"..\/logfiles\/samuel_test.log\";\n Tools::LogOutput logStream(logFile);\n string outFile = \"outfiles\/test.out\";\n Tools::LogOutput outStream(outFile);\n\n \/\/ Instances\n \/\/\n string data = \"datasets\/\";\n string inst = \"n100w4\";\t\t\t\/\/ n100w4 n030w4 n005w4\n\n \/\/ Paths\n \/\/\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n vector<int> numberWeek = {1, 2, 3, 3};\n vector<string> weekPaths(numberWeek.size());\n for(int i=0; i<numberWeek.size(); ++i){\n string path = data + inst + \"\/WD-\" + inst + \"-\"+std::to_string(numberWeek[i])+\".txt\";\n weekPaths[i] = path;\n }\n string firstHistoryPath = data + inst + \"\/H0-\" + inst + \"-0.txt\";\n\n \/\/ Read the input data from files\n \/\/\n Scenario* pScen = ReadWrite::readScenario(scenarPath);\n Preferences preferences;\n Demand* pWeekDemand = ReadWrite::readWeeks(weekPaths, pScen);\n ReadWrite::readHistory(firstHistoryPath,pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/Compute initial solution\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n outStream << pGreedy->solutionToLogString();\n\n \/\/ Instantiate solver + solve the instance\n \/\/\n MasterProblem* pSolverTest = new MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState(), S_BCP, pGreedy->getSolution());\n pSolverTest->solve();\n\n \/\/ Write the solution in an output file\n \/\/\n outStream << pSolverTest->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n \/\/\n timertest->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertest->dSinceInit());\n logStream.print(\"\\n\");\n\n \/\/ Delete\n \/\/\n delete timertest;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n delete pSolverTest;\n\n\n}\n<commit_msg>AL: my main<commit_after>\/\/\n\/\/ main_test.cpp\n\/\/ RosterDesNurses\n\/\/\n\/\/ Created by Jeremy Omer on 04\/03\/2015.\n\/\/ Copyright (c) 2015 Jeremy Omer. All rights reserved.\n\/\/\n\n#include \"main_test.h\"\n#include \"ReadWrite.h\"\n#include \"Greedy.h\"\n#include \"MasterProblem.h\"\n#include \"SubProblem.h\"\n#include \"CbcModeler.h\"\n#include \"MyTools.h\"\n\nvoid main_test()\n{\n\ttestFunction_Antoine();\n\t\/\/ testFunction_Jeremy();\n\t\/\/testFunction_Samuel();\n}\n\n\/\/ Function for testing parts of the code (Antoine)\nvoid testFunction_Antoine(){\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n \/\/ Create a log file\n string logFile = \"logs\/test.log\";\n Tools::LogOutput logStream(logFile);\n\n \/\/Create an output file\n string outFile = \"outfiles\/test.out\";\n Tools::LogOutput outStream(outFile);\n\n string data = \"testdatasets\/\";\/\/ testdatasets datasets\n const char* inst = \"n005w4\";\/\/ n100w4 n030w4 n005w4\n\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n \/\/n005w4: {1, 2, 3, 3}\n \/\/n012w8: {3, 5, 0, 2, 0, 4, 5, 2}\n vector<int> numberWeek = {1, 2, 3, 3};\n vector<string> weekPaths(numberWeek.size());\n for(int i=0; i<numberWeek.size(); ++i){\n string path = data + inst + \"\/WD-\" + inst + \"-\"+std::to_string(numberWeek[i])+\".txt\";\n weekPaths[i] = path;\n }\n string firstHistoryPath = data + inst + \"\/H0-\" + inst + \"-0.txt\";\n\n \/\/ Read the input data from files\n Scenario* pScen = ReadWrite::readScenario(scenarPath);\n Preferences preferences;\n Demand* pWeekDemand = ReadWrite::readWeeks(weekPaths, pScen);\n ReadWrite::readHistory(firstHistoryPath,pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n \/\/ logStream << *pScen << std::endl;\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/ Write the aggregate information on the demand\n \/\/\n\n\n \/\/ Write aggregate information on the cover capacity of the staff\n \/\/ (TBD)\n\n \/\/Compute initial solution\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n outStream << pGreedy->solutionToLogString();\n\n \/\/ Instantiate the solver class as a test\n \/\/\n MasterProblem* pBCP =\n new MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState(), S_BCP, pGreedy->getSolution());\n pBCP->solve();\n\n \/\/ Write the solution in the required output format\n vector<string> solutions = pBCP->solutionToString(pScen->nbWeeks());\n for(int w=0; w<pScen->nbWeeks(); ++w){\n int thisWeek = w+pScen->thisWeek();\n char solutionFile[30];\n snprintf ( solutionFile, 30, \"outfiles\/Sol-%s-%d-%d.txt\", inst, numberWeek[w], thisWeek );\n Tools::LogOutput solutionStream(solutionFile);\n solutionStream << solutions[w];\n }\n\n \/\/ Write the solution in an output file\n outStream << pBCP->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertotal->dSinceInit());\n logStream.print(\"\\n\");\n\n\n \/\/ free the allocated pointers\n \/\/\n \/\/ delete vrp;\n delete timertotal;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n delete pBCP;\n}\n\n\n\/\/ Function for testing parts of the code (Jeremy)\nvoid testFunction_Jeremy(){\n\n \/\/ Time the complete execution of the algorithm\n Tools::Timer* timertotal = new Tools::Timer();\n timertotal->init();\n timertotal->start();\n\n \/\/ Create a log file\n string logFile = \"..\/logfiles\/test.log\";\n Tools::LogOutput logStream(logFile);\n\n\n \/\/ Read the input data from files\n Scenario* pScen = ReadWrite::readScenario(\"datasets\/n030w4\/Sc-n030w4.txt\");\n Demand* pWeekDemand = ReadWrite::readWeek(\"datasets\/n030w4\/WD-n030w4-1.txt\", pScen);\n ReadWrite::readHistory(\"datasets\/n030w4\/H0-n030w4-0.txt\",pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n \/\/ logStream << *pScen << std::endl;\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/ Write the aggregate information on the demand\n \/\/\n\n\n \/\/ Write aggregate information on the cover capacity of the staff\n \/\/ (TBD)\n\n \/\/ Instantiate the solver class as a test\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand,\tpScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n\n\t\/****************************************\n\t* Test the CBC modeler\n\t*****************************************\/\n\n\t\/\/ Instantiate a master problem to create the mathematical programming model\n\t\/\/ with the columns deduced from the solution of the greedy\n\tMasterProblem* pSolverMP =\n\t\tnew MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(),\n\t\tpScen->pInitialState(), S_CBC, pGreedy->getSolution());\n\tpSolverMP->solve();\n\n\tCoinModeler* coinModel = (CoinModeler*) pSolverMP->getModel();\n\tCbcModeler* cbcModel =\n\t\tnew CbcModeler(coinModel->getCoreVars(),coinModel->getColumns(),coinModel->getCons());\n\n\t\/\/ cbcModel->setModel();\n\tcbcModel->solve();\n\n \/\/ Write the solution in the required output format\n string outFile = \"outfiles\/solution.out\";\n Tools::LogOutput outStream(outFile);\n outStream << pGreedy->solutionToString();\n\n \/\/ Write the solution and advanced information in a more convenient format\n string outLog = \"outfiles\/log.out\";\n Tools::LogOutput outLogStream(outLog);\n outLogStream << pGreedy->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n timertotal->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertotal->dSinceInit());\n logStream.print(\"\\n\");\n\n \/\/ free the allocated pointers\n \/\/\n delete timertotal;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n\tdelete pSolverMP;\n\tdelete cbcModel;\n\n\n}\n\n\/\/ Function for testing parts of the code (Samuel)\nvoid testFunction_Samuel(){\n\n Tools::Timer* timertest = new Tools::Timer();\n timertest->init();\n timertest->start();\n\n \/\/ log + output\n \/\/\n string logFile = \"..\/logfiles\/samuel_test.log\";\n Tools::LogOutput logStream(logFile);\n string outFile = \"outfiles\/test.out\";\n Tools::LogOutput outStream(outFile);\n\n \/\/ Instances\n \/\/\n string data = \"datasets\/\";\n string inst = \"n100w4\";\t\t\t\/\/ n100w4 n030w4 n005w4\n\n \/\/ Paths\n \/\/\n string scenarPath = data + inst + \"\/Sc-\" + inst + \".txt\";\n vector<int> numberWeek = {1, 2, 3, 3};\n vector<string> weekPaths(numberWeek.size());\n for(int i=0; i<numberWeek.size(); ++i){\n string path = data + inst + \"\/WD-\" + inst + \"-\"+std::to_string(numberWeek[i])+\".txt\";\n weekPaths[i] = path;\n }\n string firstHistoryPath = data + inst + \"\/H0-\" + inst + \"-0.txt\";\n\n \/\/ Read the input data from files\n \/\/\n Scenario* pScen = ReadWrite::readScenario(scenarPath);\n Preferences preferences;\n Demand* pWeekDemand = ReadWrite::readWeeks(weekPaths, pScen);\n ReadWrite::readHistory(firstHistoryPath,pScen);\n\n \/\/ Check that the scenario was read properly\n \/\/\n logStream << pScen->toString() << std::endl;\n logStream << pWeekDemand->toString(true) << std::endl;\n\n \/\/Compute initial solution\n \/\/\n Greedy* pGreedy =\n new Greedy(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState());\n pGreedy->constructiveGreedy();\n outStream << pGreedy->solutionToLogString();\n\n \/\/ Instantiate solver + solve the instance\n \/\/\n MasterProblem* pSolverTest = new MasterProblem(pScen, pWeekDemand, pScen->pWeekPreferences(), pScen->pInitialState(), S_BCP, pGreedy->getSolution());\n pSolverTest->solve();\n\n \/\/ Write the solution in an output file\n \/\/\n outStream << pSolverTest->solutionToLogString();\n\n \/\/ Display the total time spent in the algorithm\n \/\/\n timertest->stop();\n logStream.print(\"Total time spent in the algorithm : \");\n logStream.print(timertest->dSinceInit());\n logStream.print(\"\\n\");\n\n \/\/ Delete\n \/\/\n delete timertest;\n delete pWeekDemand;\n delete pScen;\n delete pGreedy;\n delete pSolverTest;\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <parseopt.h>\n#include <arpc.h>\n#include \"lsdctl_prot.h\"\n\n\/* Much of the structure and code here is taken from sfskey.C which is GPL2'd.\n * See http:\/\/www.fs.net\/ *\/\n\nbool opt_verbose;\nbool opt_quiet;\nchar *control_socket = \"\/tmp\/lsdctl-sock\";\n\n\/* Prototypes for table. *\/\nvoid lsdctl_help (int argc, char *argv[]);\nvoid lsdctl_exit (int argc, char *argv[]);\nvoid lsdctl_trace (int argc, char *argv[]);\nvoid lsdctl_stabilize (int argc, char *argv[]);\nvoid lsdctl_replicate (int argc, char *argv[]);\nvoid lsdctl_getloctab (int argc, char *argv[]);\nvoid lsdctl_getrpcstats (int argc, char *argv[]);\nvoid lsdctl_getmyids (int argc, char *argv[]);\nvoid lsdctl_getdhashstats (int argc, char *argv[]);\n\nstruct modevec {\n const char *name;\n void (*fn) (int argc, char **argv);\n const char *usage;\n};\nconst modevec modes[] = {\n { \"help\", lsdctl_help, \"help\" },\n { \"exit\", lsdctl_exit, \"exit\" },\n { \"trace\", lsdctl_trace, \"trace crit|warning|info|trace\" },\n { \"stabilize\", lsdctl_stabilize, \"stabilize start|stop\" },\n { \"replicate\", lsdctl_replicate, \"replicate [-r] start|stop\" },\n { \"loctab\", lsdctl_getloctab, \"loctab [vnodenum]\" },\n { \"rpcstats\", lsdctl_getrpcstats, \"rpcstats [-rf]\" },\n { \"myids\", lsdctl_getmyids, \"myids\" },\n { \"dhashstats\", lsdctl_getdhashstats, \"dhashstats [vnodenum]\" },\n { NULL, NULL, NULL }\n};\n\nstatic const modevec *lsdctl_mode;\n\nvoid\nusage (void)\n{\n warnx << \"usage: \" << progname << \" [-S sock] [-vq] \";\n if (lsdctl_mode && lsdctl_mode->usage)\n warnx << lsdctl_mode->usage << \"\\n\";\n else\n warnx << \"command [args]\\n\";\n exit (1);\n}\n\n\/**************************************\/\n\/* The commands that do the real work *\/\n\/**************************************\/\n\nvoid\nlsdctl_help (int argc, char *argv[])\n{\n strbuf msg;\n msg << \"usage: \" << progname << \" [-S sock] [-vq] command [args]\\n\";\n for (const modevec *mp = modes; mp->name; mp++)\n if (mp->usage)\n msg << \"\t \" << progname << \" \" << mp->usage << \"\\n\";\n make_sync (1);\n msg.tosuio ()->output (1);\n exit (0);\n}\n\nptr<aclnt>\nlsdctl_connect (str sockname)\n{\n int fd = unixsocket_connect (sockname);\n if (fd < 0) {\n fatal (\"lsdctl_connect: Error connecting to %s: %s\\n\",\n\t sockname.cstr (), strerror (errno));\n }\n\n ptr<aclnt> c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025),\n\t\t\t lsdctl_prog_1);\n return c;\n}\n\nvoid\nlsdctl_exit (int argc, char *argv[])\n{\n \/\/ Ignore arguments\n ptr<aclnt> c = lsdctl_connect (control_socket);\n clnt_stat err = c->scall (LSDCTL_EXIT, NULL, NULL);\n if (err)\n fatal << \"lsdctl_exit: \" << err << \"\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_trace (int argc, char *argv[])\n{\n if (optind + 1 != argc)\n usage ();\n \n char *level = argv[optind];\n int lvl = 0;\n \/\/ XXX wouldn't it be nice to cleanly derive from utils\/modlogger.h?\n if (!strcmp (\"crit\", level))\n lvl = -1;\n else if (!strcmp (\"warning\", level))\n lvl = 0;\n else if (!strcmp (\"info\", level))\n lvl = 1;\n else if (!strcmp (\"trace\", level))\n lvl = 2;\n else\n usage ();\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n clnt_stat err = c->scall (LSDCTL_SETTRACELEVEL, &lvl, NULL);\n if (err)\n fatal << \"lsdctl_trace: \" << err << \"\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_stabilize (int argc, char *argv[])\n{\n if (optind + 1 != argc)\n usage ();\n \n bool t = false;\n char *toggle = argv[optind];\n if (!strcmp (\"start\", toggle))\n t = true;\n else if (!strcmp (\"stop\", toggle))\n t = false;\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n bool res = !t;\n clnt_stat err = c->scall (LSDCTL_SETSTABILIZE, &t, &res);\n if (err)\n fatal << \"lsdctl_stabilize: \" << err << \"\\n\";\n if (res != t)\n warnx << \"lsdctl_stabilize: lsd did not switch to new state.\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_replicate (int argc, char *argv[])\n{\n ptr<lsdctl_setreplicate_arg> t = New refcounted<lsdctl_setreplicate_arg> ();\n t->randomize = false;\n\n int ch;\n while ((ch = getopt (argc, argv, \"r\")) != -1)\n switch (ch) {\n case 'r':\n t->randomize = true;\n break;\n default:\n usage ();\n break;\n }\n\n if (optind + 1 != argc)\n usage ();\n\n char *toggle = argv[optind];\n if (!strcmp (\"start\", toggle))\n t->enable = true;\n else if (!strcmp (\"stop\", toggle))\n t->enable = false;\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n bool res = !t;\n clnt_stat err = c->scall (LSDCTL_SETREPLICATE, t, &res);\n if (err)\n fatal << \"lsdctl_replicate: \" << err << \"\\n\";\n if (res != t->enable)\n warnx << \"lsdctl_replicate: lsd did not switch to new state.\\n\";\n exit (0);\n}\n\nstrbuf\nlsdctl_nlist_printer (ptr<lsdctl_nodeinfolist> nl)\n{\n strbuf out;\n for (size_t i = 0; i < nl->nlist.size (); i++) {\n out << nl->nlist[i].n << \" \"\n << nl->nlist[i].addr.hostname << \" \"\n << nl->nlist[i].addr.port << \" \"\n << nl->nlist[i].vnode_num << \" \";\n for (size_t j = 0; j < nl->nlist[i].coords.size (); j++)\n out << nl->nlist[i].coords[j] << \" \";\n out << nl->nlist[i].a_lat << \" \"\n << nl->nlist[i].a_var << \" \"\n << nl->nlist[i].nrpc << \" \"\n << nl->nlist[i].pinned << \" \"\n << nl->nlist[i].alive << \" \"\n << nl->nlist[i].dead_time << \"\\n\";\n }\n return out;\n}\n\nvoid\nlsdctl_getmyids (int argc, char *argv[])\n{\n ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETMYIDS, NULL, nl);\n if (err)\n fatal << \"lsdctl_loctab: \" << err << \"\\n\";\n strbuf out (lsdctl_nlist_printer (nl));\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nvoid\nlsdctl_getloctab (int argc, char *argv[])\n{\n int vnode = 0; \/\/ XXX should actually get vnode from cmd line.\n ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETLOCTABLE, &vnode, nl);\n if (err)\n fatal << \"lsdctl_loctab: \" << err << \"\\n\";\n strbuf out (lsdctl_nlist_printer (nl));\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nstatic int\nstatcmp (const void *a, const void *b)\n{\n return strcmp (((lsdctl_rpcstat *) a)->key.cstr (),\n\t\t ((lsdctl_rpcstat *) b)->key.cstr ());\n}\nvoid\nlsdctl_getrpcstats (int argc, char *argv[])\n{\n int ch;\n bool clear = false;\n bool formatted = false;\n while ((ch = getopt (argc, argv, \"rf\")) != -1)\n switch (ch) {\n case 'r':\n clear = true;\n break;\n case 'f':\n formatted = true;\n break;\n default:\n usage ();\n break;\n }\n\n ptr<lsdctl_rpcstatlist> nl = New refcounted <lsdctl_rpcstatlist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETRPCSTATS, &clear, nl);\n if (err)\n fatal << \"lsdctl_rpcstats: \" << err << \"\\n\";\n strbuf out;\n out.fmt (\"Interval %llu.%llu s\\n\",\n\t nl->interval \/ 1000000, nl->interval % 1000000);\n if (formatted)\n out.fmt (\"%54s | %-15s | %-15s | %-15s\\n\",\n\t \"Proc\", \"Calls (bytes\/#)\", \"Rexmits\", \"Replies\");\n \n lsdctl_rpcstat *ndx = New lsdctl_rpcstat[nl->stats.size ()];\n for (size_t i = 0; i < nl->stats.size (); i++)\n ndx[i] = nl->stats[i];\n qsort (ndx, nl->stats.size (), sizeof (lsdctl_rpcstat), &statcmp);\n\n str fmt;\n if (formatted)\n fmt = \"%-54s | %7llu %7llu | %7llu %7llu | %7llu %7llu\\n\";\n else\n fmt = \"%s %llu %llu %llu %llu %llu %llu\\n\";\n for (size_t i = 0; i < nl->stats.size (); i++) {\n out.fmt (fmt,\n\t ndx[i].key.cstr (),\n\t ndx[i].call_bytes,\n\t ndx[i].ncall,\n\t ndx[i].rexmit_bytes,\n\t ndx[i].nrexmit,\n\t ndx[i].reply_bytes,\n\t ndx[i].nreply);\n }\n delete[] ndx;\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nvoid\nlsdctl_getdhashstats (int argc, char *argv[])\n{\n int vnode (0);\n\n if (optind != argc)\n if (!convertint (argv[optind], &vnode))\n usage ();\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n ptr<lsdctl_dhashstats> ds = New refcounted <lsdctl_dhashstats> ();\n clnt_stat err = c->scall (LSDCTL_GETDHASHSTATS, &vnode, ds);\n if (err)\n fatal << \"lsdctl_getdhashstats: \" << err << \"\\n\";\n\n strbuf out;\n out << \"Statistics:\\n\";\n for (size_t i = 0; i < ds->stats.size (); i++)\n out << \" \" << ds->stats[i].desc << \" \" << ds->stats[i].value << \"\\n\";\n for (size_t i = 0; i < ds->blocks.size (); i++) \n out << ds->blocks[i].id << \"\\t\" << ds->blocks[i].missing.size () << \"\\n\";\n out << ds->hack;\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n setprogname (argv[0]);\n putenv (\"POSIXLY_CORRECT=1\"); \/\/ Prevents Linux from reordering options\n\n int ch;\n while ((ch = getopt (argc, argv, \"S:vq\")) != -1)\n switch (ch) {\n case 'S':\n control_socket = optarg;\n break;\n case 'v':\n opt_verbose = true;\n break;\n case 'q':\n opt_quiet = true;\n break;\n default:\n usage ();\n break;\n }\n if (optind >= argc)\n usage ();\n\n \/\/ Prepare to dispatch on command name\n const modevec *mp;\n for (mp = modes; mp->name; mp++)\n if (!strcmp (argv[optind], mp->name))\n break;\n if (!mp->name)\n usage ();\n lsdctl_mode = mp;\n\n \/\/ Skip over command name...\n optind++;\n \n mp->fn (argc, argv);\n \/\/ amain ();\n \n return 0;\n}\n<commit_msg>Fix some error message strings.<commit_after>#include <parseopt.h>\n#include <arpc.h>\n#include \"lsdctl_prot.h\"\n\n\/* Much of the structure and code here is taken from sfskey.C which is GPL2'd.\n * See http:\/\/www.fs.net\/ *\/\n\nbool opt_verbose;\nbool opt_quiet;\nchar *control_socket = \"\/tmp\/lsdctl-sock\";\n\n\/* Prototypes for table. *\/\nvoid lsdctl_help (int argc, char *argv[]);\nvoid lsdctl_exit (int argc, char *argv[]);\nvoid lsdctl_trace (int argc, char *argv[]);\nvoid lsdctl_stabilize (int argc, char *argv[]);\nvoid lsdctl_replicate (int argc, char *argv[]);\nvoid lsdctl_getloctab (int argc, char *argv[]);\nvoid lsdctl_getrpcstats (int argc, char *argv[]);\nvoid lsdctl_getmyids (int argc, char *argv[]);\nvoid lsdctl_getdhashstats (int argc, char *argv[]);\n\nstruct modevec {\n const char *name;\n void (*fn) (int argc, char **argv);\n const char *usage;\n};\nconst modevec modes[] = {\n { \"help\", lsdctl_help, \"help\" },\n { \"exit\", lsdctl_exit, \"exit\" },\n { \"trace\", lsdctl_trace, \"trace crit|warning|info|trace\" },\n { \"stabilize\", lsdctl_stabilize, \"stabilize start|stop\" },\n { \"replicate\", lsdctl_replicate, \"replicate [-r] start|stop\" },\n { \"loctab\", lsdctl_getloctab, \"loctab [vnodenum]\" },\n { \"rpcstats\", lsdctl_getrpcstats, \"rpcstats [-rf]\" },\n { \"myids\", lsdctl_getmyids, \"myids\" },\n { \"dhashstats\", lsdctl_getdhashstats, \"dhashstats [vnodenum]\" },\n { NULL, NULL, NULL }\n};\n\nstatic const modevec *lsdctl_mode;\n\nvoid\nusage (void)\n{\n warnx << \"usage: \" << progname << \" [-S sock] [-vq] \";\n if (lsdctl_mode && lsdctl_mode->usage)\n warnx << lsdctl_mode->usage << \"\\n\";\n else\n warnx << \"command [args]\\n\";\n exit (1);\n}\n\n\/**************************************\/\n\/* The commands that do the real work *\/\n\/**************************************\/\n\nvoid\nlsdctl_help (int argc, char *argv[])\n{\n strbuf msg;\n msg << \"usage: \" << progname << \" [-S sock] [-vq] command [args]\\n\";\n for (const modevec *mp = modes; mp->name; mp++)\n if (mp->usage)\n msg << \"\t \" << progname << \" \" << mp->usage << \"\\n\";\n make_sync (1);\n msg.tosuio ()->output (1);\n exit (0);\n}\n\nptr<aclnt>\nlsdctl_connect (str sockname)\n{\n int fd = unixsocket_connect (sockname);\n if (fd < 0) {\n fatal (\"lsdctl_connect: Error connecting to %s: %s\\n\",\n\t sockname.cstr (), strerror (errno));\n }\n\n ptr<aclnt> c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025),\n\t\t\t lsdctl_prog_1);\n return c;\n}\n\nvoid\nlsdctl_exit (int argc, char *argv[])\n{\n \/\/ Ignore arguments\n ptr<aclnt> c = lsdctl_connect (control_socket);\n clnt_stat err = c->scall (LSDCTL_EXIT, NULL, NULL);\n if (err)\n fatal << \"lsdctl_exit: \" << err << \"\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_trace (int argc, char *argv[])\n{\n if (optind + 1 != argc)\n usage ();\n \n char *level = argv[optind];\n int lvl = 0;\n \/\/ XXX wouldn't it be nice to cleanly derive from utils\/modlogger.h?\n if (!strcmp (\"crit\", level))\n lvl = -1;\n else if (!strcmp (\"warning\", level))\n lvl = 0;\n else if (!strcmp (\"info\", level))\n lvl = 1;\n else if (!strcmp (\"trace\", level))\n lvl = 2;\n else\n usage ();\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n clnt_stat err = c->scall (LSDCTL_SETTRACELEVEL, &lvl, NULL);\n if (err)\n fatal << \"lsdctl_trace: \" << err << \"\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_stabilize (int argc, char *argv[])\n{\n if (optind + 1 != argc)\n usage ();\n \n bool t = false;\n char *toggle = argv[optind];\n if (!strcmp (\"start\", toggle))\n t = true;\n else if (!strcmp (\"stop\", toggle))\n t = false;\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n bool res = !t;\n clnt_stat err = c->scall (LSDCTL_SETSTABILIZE, &t, &res);\n if (err)\n fatal << \"lsdctl_stabilize: \" << err << \"\\n\";\n if (res != t)\n warnx << \"lsdctl_stabilize: lsd did not switch to new state.\\n\";\n exit (0);\n}\n\nvoid\nlsdctl_replicate (int argc, char *argv[])\n{\n ptr<lsdctl_setreplicate_arg> t = New refcounted<lsdctl_setreplicate_arg> ();\n t->randomize = false;\n\n int ch;\n while ((ch = getopt (argc, argv, \"r\")) != -1)\n switch (ch) {\n case 'r':\n t->randomize = true;\n break;\n default:\n usage ();\n break;\n }\n\n if (optind + 1 != argc)\n usage ();\n\n char *toggle = argv[optind];\n if (!strcmp (\"start\", toggle))\n t->enable = true;\n else if (!strcmp (\"stop\", toggle))\n t->enable = false;\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n bool res = !t;\n clnt_stat err = c->scall (LSDCTL_SETREPLICATE, t, &res);\n if (err)\n fatal << \"lsdctl_replicate: \" << err << \"\\n\";\n if (res != t->enable)\n warnx << \"lsdctl_replicate: lsd did not switch to new state.\\n\";\n exit (0);\n}\n\nstrbuf\nlsdctl_nlist_printer (ptr<lsdctl_nodeinfolist> nl)\n{\n strbuf out;\n for (size_t i = 0; i < nl->nlist.size (); i++) {\n out << nl->nlist[i].n << \" \"\n << nl->nlist[i].addr.hostname << \" \"\n << nl->nlist[i].addr.port << \" \"\n << nl->nlist[i].vnode_num << \" \";\n for (size_t j = 0; j < nl->nlist[i].coords.size (); j++)\n out << nl->nlist[i].coords[j] << \" \";\n out << nl->nlist[i].a_lat << \" \"\n << nl->nlist[i].a_var << \" \"\n << nl->nlist[i].nrpc << \" \"\n << nl->nlist[i].pinned << \" \"\n << nl->nlist[i].alive << \" \"\n << nl->nlist[i].dead_time << \"\\n\";\n }\n return out;\n}\n\nvoid\nlsdctl_getmyids (int argc, char *argv[])\n{\n ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETMYIDS, NULL, nl);\n if (err)\n fatal << \"lsdctl_getmyids: \" << err << \"\\n\";\n strbuf out (lsdctl_nlist_printer (nl));\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nvoid\nlsdctl_getloctab (int argc, char *argv[])\n{\n int vnode = 0; \/\/ XXX should actually get vnode from cmd line.\n ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETLOCTABLE, &vnode, nl);\n if (err)\n fatal << \"lsdctl_getloctab: \" << err << \"\\n\";\n strbuf out (lsdctl_nlist_printer (nl));\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nstatic int\nstatcmp (const void *a, const void *b)\n{\n return strcmp (((lsdctl_rpcstat *) a)->key.cstr (),\n\t\t ((lsdctl_rpcstat *) b)->key.cstr ());\n}\nvoid\nlsdctl_getrpcstats (int argc, char *argv[])\n{\n int ch;\n bool clear = false;\n bool formatted = false;\n while ((ch = getopt (argc, argv, \"rf\")) != -1)\n switch (ch) {\n case 'r':\n clear = true;\n break;\n case 'f':\n formatted = true;\n break;\n default:\n usage ();\n break;\n }\n\n ptr<lsdctl_rpcstatlist> nl = New refcounted <lsdctl_rpcstatlist> ();\n ptr<aclnt> c = lsdctl_connect (control_socket);\n\n clnt_stat err = c->scall (LSDCTL_GETRPCSTATS, &clear, nl);\n if (err)\n fatal << \"lsdctl_rpcstats: \" << err << \"\\n\";\n strbuf out;\n out.fmt (\"Interval %llu.%llu s\\n\",\n\t nl->interval \/ 1000000, nl->interval % 1000000);\n if (formatted)\n out.fmt (\"%54s | %-15s | %-15s | %-15s\\n\",\n\t \"Proc\", \"Calls (bytes\/#)\", \"Rexmits\", \"Replies\");\n \n lsdctl_rpcstat *ndx = New lsdctl_rpcstat[nl->stats.size ()];\n for (size_t i = 0; i < nl->stats.size (); i++)\n ndx[i] = nl->stats[i];\n qsort (ndx, nl->stats.size (), sizeof (lsdctl_rpcstat), &statcmp);\n\n str fmt;\n if (formatted)\n fmt = \"%-54s | %7llu %7llu | %7llu %7llu | %7llu %7llu\\n\";\n else\n fmt = \"%s %llu %llu %llu %llu %llu %llu\\n\";\n for (size_t i = 0; i < nl->stats.size (); i++) {\n out.fmt (fmt,\n\t ndx[i].key.cstr (),\n\t ndx[i].call_bytes,\n\t ndx[i].ncall,\n\t ndx[i].rexmit_bytes,\n\t ndx[i].nrexmit,\n\t ndx[i].reply_bytes,\n\t ndx[i].nreply);\n }\n delete[] ndx;\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\nvoid\nlsdctl_getdhashstats (int argc, char *argv[])\n{\n int vnode (0);\n\n if (optind != argc)\n if (!convertint (argv[optind], &vnode))\n usage ();\n \n ptr<aclnt> c = lsdctl_connect (control_socket);\n ptr<lsdctl_dhashstats> ds = New refcounted <lsdctl_dhashstats> ();\n clnt_stat err = c->scall (LSDCTL_GETDHASHSTATS, &vnode, ds);\n if (err)\n fatal << \"lsdctl_getdhashstats: \" << err << \"\\n\";\n\n strbuf out;\n out << \"Statistics:\\n\";\n for (size_t i = 0; i < ds->stats.size (); i++)\n out << \" \" << ds->stats[i].desc << \" \" << ds->stats[i].value << \"\\n\";\n for (size_t i = 0; i < ds->blocks.size (); i++) \n out << ds->blocks[i].id << \"\\t\" << ds->blocks[i].missing.size () << \"\\n\";\n out << ds->hack;\n make_sync (1);\n out.tosuio ()->output (1);\n exit (0);\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n setprogname (argv[0]);\n putenv (\"POSIXLY_CORRECT=1\"); \/\/ Prevents Linux from reordering options\n\n int ch;\n while ((ch = getopt (argc, argv, \"S:vq\")) != -1)\n switch (ch) {\n case 'S':\n control_socket = optarg;\n break;\n case 'v':\n opt_verbose = true;\n break;\n case 'q':\n opt_quiet = true;\n break;\n default:\n usage ();\n break;\n }\n if (optind >= argc)\n usage ();\n\n \/\/ Prepare to dispatch on command name\n const modevec *mp;\n for (mp = modes; mp->name; mp++)\n if (!strcmp (argv[optind], mp->name))\n break;\n if (!mp->name)\n usage ();\n lsdctl_mode = mp;\n\n \/\/ Skip over command name...\n optind++;\n \n mp->fn (argc, argv);\n \/\/ amain ();\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <arpc.h>\n#include <..\/devel\/rpclib.h>\n#include <comm.h>\n\n#include <dhash_prot.h>\n#include <locationtable.h>\n#include <location.h>\n#include <merkle_tree.h>\n#include <merkle_syncer.h>\n\n#include <syncer.h>\n\nstatic int sync_trace (getenv (\"SYNC_TRACE\") ? atoi (getenv (\"SYNC_TRACE\")) : 0);\n\nsyncer::syncer (ptr<locationtable> locations,\n\t\tptr<location> h,\n\t\tstr dbpath,\n\t\tstr dbname,\n\t\tdhash_ctype ctype,\n\t\tu_int dfrags, u_int efrags)\n : locations (locations), ctype (ctype), dfrags (dfrags), efrags (efrags),\n tmptree (NULL), host_loc (h),\n db (New refcounted<adb> (dbpath, dbname)),\n cur_succ (0),\n replica_timer (300)\n{ \n \n warn << \"new syncer: \\n\" \n << \" dbpath: \" << dbpath << \"\\n\"\n << \" dbext: \" << dbname << \"\\n\"\n << \" ctype: \" << ctype << \"\\n\"\n << \" d\/efrags: \" << dfrags << \"\/\" << efrags << \"\\n\";\n\n locations->insert (h);\n locations->pin (h->id ());\n \n if (sync_trace >= 10)\n replica_timer = sync_trace;\n \n \/\/ Initially randomize a little.\n int delay = random_getword () % replica_timer;\n delaycb (delay, wrap(this, &syncer::sync_replicas)); \n}\n\nsyncer::~syncer ()\n{\n delete tmptree;\n tmptree = NULL;\n replica_syncer = NULL;\n db = NULL;\n}\n\nvoid\nsyncer::doRPC (const rpc_program &prog,\n\t\tint procno, const void *in, void *out, aclnt_cb cb)\n{\n chord_node dst;\n host_loc->fill_node (dst);\n ::doRPC (dst, prog, procno, in, out, cb);\n}\n\nvoid\nsyncer::update_pred (cb_location cb)\n{\n ptr<chordID> id = New refcounted<chordID> (host_loc->id ());\n\n chord_noderes *res = New chord_noderes ();\n doRPC (chord_program_1, CHORDPROC_GETPREDECESSOR,\n\t id, res,\n\t wrap (this, &syncer::update_pred_cb, cb, res) );\n}\n\nvoid\nsyncer::update_pred_cb (cb_location cb, chord_noderes *res, clnt_stat err)\n{\n if (err) {\n warn << \"my local node is down?\\n\";\n (*cb) (NULL);\n } else {\n chord_node n = make_chord_node (*res->resok);\n ptr<location> x = locations->lookup_or_create (n);\n locations->insert (x);\n cb (x);\n }\n delete res;\n}\n\n\nvoid\nsyncer::get_succlist (cb_locationlist cb)\n{\n ptr<chordID> ga = New refcounted<chordID> (host_loc->id ());\n chord_nodelistres *lst = New chord_nodelistres ();\n doRPC (chord_program_1,\n\t CHORDPROC_GETSUCCLIST, \n\t ga, lst, wrap (this, &syncer::get_succlist_cb, lst, cb));\n}\n\nvoid\nsyncer::get_succlist_cb (chord_nodelistres *res,\n\t\t cb_locationlist cb,\n\t\t clnt_stat status)\n{\n vec<ptr<location> > ret;\n if (!status) {\n size_t sz = res->resok->nlist.size ();\n for (size_t i = 0; i < sz; i++) {\n chord_node n = make_chord_node (res->resok->nlist[i]);\n ptr<location> s = locations->lookup_or_create (n);\n locations->insert (s);\n ret.push_back (s);\n }\n }\n\n cb (ret);\n delete res;\n}\n\n\nvoid\nsyncer::sync_replicas ()\n{\n if (replica_syncer && !replica_syncer->done ()) {\n \/\/ still working on the last sync\n delaycb (replica_timer, wrap(this, &syncer::sync_replicas)); \n } else {\n warn << \"sync_replicas: starting (ctype = \" << ctype << \")\\n\";\n update_pred (wrap (this, &syncer::sync_replicas_predupdated)); \n } \n}\n\nvoid\nsyncer::sync_replicas_predupdated (ptr<location> pred)\n{\n if (!pred) {\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n warn << \"sync_replicas: my pred is \" << pred << \"\\n\";\n get_succlist (wrap (this, &syncer::sync_replicas_gotsucclist, pred));\n}\n\n\nvoid\nsyncer::sync_replicas_gotsucclist (ptr<location> pred,\n\t\t\t vec<ptr<location> > succs) \n{\n if (succs.size () == 0) {\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n \n \/\/ succs[0] is the vnode we are working for\n \/\/ pred = locations->closestpredloc (succs[0]);\n assert (pred);\n assert (succs[0]);\n assert (host_loc);\n \n cur_succ++; \/\/ start at 1 (0 is me)\n if (efrags > 0 && cur_succ >= efrags) cur_succ = 1;\n else if (cur_succ >= succs.size ()) cur_succ = 1;\n\n assert(succs[cur_succ]);\n\n \/\/sync with the next node\n if (tmptree) {\n delete tmptree;\n }\n u_int64_t start = getusec ();\n\n tmptree = New merkle_tree ();\n db->getkeyson (succs[cur_succ], pred->id (), succs[0]->id (),\n wrap (this, &syncer::populate_tree, start, pred, succs));\n}\n\nvoid\nsyncer::populate_tree (u_int64_t start,\n ptr<location> pred, vec<ptr<location> > succs,\n adb_status astat, vec<chordID> blocks, vec<u_int32_t> aux)\n{\n if (astat != ADB_OK && astat != ADB_COMPLETE) {\n warn << \"syncer adbd error: \" << astat << \"\\n\";\n delete tmptree; tmptree = NULL;\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n\n \/\/ XXX ugh\n switch (ctype) {\n case DHASH_CONTENTHASH:\n for (size_t i = 0; i < blocks.size (); i++) {\n tmptree->insert (blocks[i]);\n }\n break;\n case DHASH_KEYHASH:\n case DHASH_NOAUTH:\n for (size_t i = 0; i < blocks.size (); i++) {\n tmptree->insert (blocks[i], aux[i]);\n }\n break;\n default:\n fatal << \"syncer::populate_tree: unexpected ctype \" << ctype << \"\\n\";\n break;\n }\n if (astat != ADB_COMPLETE) {\n \/\/ Get more, picking up from where we left off\n const chordID last (blocks.back ());\n db->getkeyson (succs[cur_succ], incID(last), succs[0]->id (),\n\twrap (this, &syncer::populate_tree, start, pred, succs));\n return;\n }\n \/\/ move on to tree done\n warn << host_loc->id () << \" tree build: \" \n << getusec () - start << \" usecs\\n\";\n\n replica_syncer = New refcounted<merkle_syncer> \n (ctype, tmptree, \n wrap (this, &syncer::doRPC_unbundler, succs[cur_succ]),\n wrap (this, &syncer::missing, succs[cur_succ]));\n \n bigint rngmin = pred->id ();\n bigint rngmax = succs[0]->id ();\n\n warn << host_loc->id () << \" syncing with \" << succs[cur_succ] \n << \" (succ #\" << cur_succ << \")\"\n << \" for range [ \" << rngmin << \", \" << rngmax << \" ]\\n\";\n \n replica_syncer->sync (rngmin, rngmax);\n \n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n}\n\nvoid\nsyncer::doRPC_unbundler (ptr<location> dst, RPC_delay_args *args)\n{\n chord_node n;\n dst->fill_node (n);\n ::doRPC (n, args->prog, args->procno, args->in, args->out, args->cb);\n}\n\nvoid\nsyncer::missing (ptr<location> from,\n\t\t bigint key, bool missing_local,\n\t\t bool round_over)\n{\n if (round_over) return;\n \/\/ if he tells us that we're missing it, then he has it.\n \/\/ otherwise, we found out he doesn't have it.\n \/\/ XXX this switch business is kinda gross.\n switch (ctype) {\n case DHASH_CONTENTHASH:\n db->update (key, from, missing_local, true);\n break;\n case DHASH_KEYHASH:\n case DHASH_NOAUTH:\n {\n chordID aux = (key & 0xFFFFFFFF);\n chordID dbkey = (key >> 32) << 32;\n db->update (dbkey, from, aux.getui (), missing_local, true);\n }\n break;\n default:\n fatal << \"syncer::missing: unexpected ctype \" << ctype << \"\\n\";\n break;\n }\n}\n<commit_msg>Use new merkle_tree API to disable hashing until tree build is complete.<commit_after>#include <arpc.h>\n#include <..\/devel\/rpclib.h>\n#include <comm.h>\n\n#include <dhash_prot.h>\n#include <locationtable.h>\n#include <location.h>\n#include <merkle_tree.h>\n#include <merkle_syncer.h>\n\n#include <syncer.h>\n\nstatic int sync_trace (getenv (\"SYNC_TRACE\") ? atoi (getenv (\"SYNC_TRACE\")) : 0);\n\nsyncer::syncer (ptr<locationtable> locations,\n\t\tptr<location> h,\n\t\tstr dbpath,\n\t\tstr dbname,\n\t\tdhash_ctype ctype,\n\t\tu_int dfrags, u_int efrags)\n : locations (locations), ctype (ctype), dfrags (dfrags), efrags (efrags),\n tmptree (NULL), host_loc (h),\n db (New refcounted<adb> (dbpath, dbname)),\n cur_succ (0),\n replica_timer (300)\n{ \n \n warn << \"new syncer: \\n\" \n << \" dbpath: \" << dbpath << \"\\n\"\n << \" dbext: \" << dbname << \"\\n\"\n << \" ctype: \" << ctype << \"\\n\"\n << \" d\/efrags: \" << dfrags << \"\/\" << efrags << \"\\n\";\n\n locations->insert (h);\n locations->pin (h->id ());\n \n if (sync_trace >= 10)\n replica_timer = sync_trace;\n \n \/\/ Initially randomize a little.\n int delay = random_getword () % replica_timer;\n delaycb (delay, wrap(this, &syncer::sync_replicas)); \n}\n\nsyncer::~syncer ()\n{\n delete tmptree;\n tmptree = NULL;\n replica_syncer = NULL;\n db = NULL;\n}\n\nvoid\nsyncer::doRPC (const rpc_program &prog,\n\t\tint procno, const void *in, void *out, aclnt_cb cb)\n{\n chord_node dst;\n host_loc->fill_node (dst);\n ::doRPC (dst, prog, procno, in, out, cb);\n}\n\nvoid\nsyncer::update_pred (cb_location cb)\n{\n ptr<chordID> id = New refcounted<chordID> (host_loc->id ());\n\n chord_noderes *res = New chord_noderes ();\n doRPC (chord_program_1, CHORDPROC_GETPREDECESSOR,\n\t id, res,\n\t wrap (this, &syncer::update_pred_cb, cb, res) );\n}\n\nvoid\nsyncer::update_pred_cb (cb_location cb, chord_noderes *res, clnt_stat err)\n{\n if (err) {\n warn << \"my local node is down?\\n\";\n (*cb) (NULL);\n } else {\n chord_node n = make_chord_node (*res->resok);\n ptr<location> x = locations->lookup_or_create (n);\n locations->insert (x);\n cb (x);\n }\n delete res;\n}\n\n\nvoid\nsyncer::get_succlist (cb_locationlist cb)\n{\n ptr<chordID> ga = New refcounted<chordID> (host_loc->id ());\n chord_nodelistres *lst = New chord_nodelistres ();\n doRPC (chord_program_1,\n\t CHORDPROC_GETSUCCLIST, \n\t ga, lst, wrap (this, &syncer::get_succlist_cb, lst, cb));\n}\n\nvoid\nsyncer::get_succlist_cb (chord_nodelistres *res,\n\t\t cb_locationlist cb,\n\t\t clnt_stat status)\n{\n vec<ptr<location> > ret;\n if (!status) {\n size_t sz = res->resok->nlist.size ();\n for (size_t i = 0; i < sz; i++) {\n chord_node n = make_chord_node (res->resok->nlist[i]);\n ptr<location> s = locations->lookup_or_create (n);\n locations->insert (s);\n ret.push_back (s);\n }\n }\n\n cb (ret);\n delete res;\n}\n\n\nvoid\nsyncer::sync_replicas ()\n{\n if (replica_syncer && !replica_syncer->done ()) {\n \/\/ still working on the last sync\n delaycb (replica_timer, wrap(this, &syncer::sync_replicas)); \n } else {\n warn << \"sync_replicas: starting (ctype = \" << ctype << \")\\n\";\n update_pred (wrap (this, &syncer::sync_replicas_predupdated)); \n } \n}\n\nvoid\nsyncer::sync_replicas_predupdated (ptr<location> pred)\n{\n if (!pred) {\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n warn << \"sync_replicas: my pred is \" << pred << \"\\n\";\n get_succlist (wrap (this, &syncer::sync_replicas_gotsucclist, pred));\n}\n\n\nvoid\nsyncer::sync_replicas_gotsucclist (ptr<location> pred,\n\t\t\t vec<ptr<location> > succs) \n{\n if (succs.size () == 0) {\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n \n \/\/ succs[0] is the vnode we are working for\n \/\/ pred = locations->closestpredloc (succs[0]);\n assert (pred);\n assert (succs[0]);\n assert (host_loc);\n \n cur_succ++; \/\/ start at 1 (0 is me)\n if (efrags > 0 && cur_succ >= efrags) cur_succ = 1;\n else if (cur_succ >= succs.size ()) cur_succ = 1;\n\n assert(succs[cur_succ]);\n\n \/\/sync with the next node\n if (tmptree) {\n delete tmptree;\n }\n u_int64_t start = getusec ();\n\n tmptree = New merkle_tree ();\n tmptree->set_rehash_on_modification (false);\n db->getkeyson (succs[cur_succ], pred->id (), succs[0]->id (),\n wrap (this, &syncer::populate_tree, start, pred, succs));\n}\n\nvoid\nsyncer::populate_tree (u_int64_t start,\n ptr<location> pred, vec<ptr<location> > succs,\n adb_status astat, vec<chordID> blocks, vec<u_int32_t> aux)\n{\n if (astat != ADB_OK && astat != ADB_COMPLETE) {\n warn << \"syncer adbd error: \" << astat << \"\\n\";\n delete tmptree; tmptree = NULL;\n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n return;\n }\n\n \/\/ XXX ugh\n switch (ctype) {\n case DHASH_CONTENTHASH:\n for (size_t i = 0; i < blocks.size (); i++) {\n tmptree->insert (blocks[i]);\n }\n break;\n case DHASH_KEYHASH:\n case DHASH_NOAUTH:\n for (size_t i = 0; i < blocks.size (); i++) {\n tmptree->insert (blocks[i], aux[i]);\n }\n break;\n default:\n fatal << \"syncer::populate_tree: unexpected ctype \" << ctype << \"\\n\";\n break;\n }\n if (astat != ADB_COMPLETE) {\n \/\/ Get more, picking up from where we left off\n const chordID last (blocks.back ());\n db->getkeyson (succs[cur_succ], incID(last), succs[0]->id (),\n\twrap (this, &syncer::populate_tree, start, pred, succs));\n return;\n }\n \/\/ move on to tree done\n tmptree->hash_tree ();\n tmptree->set_rehash_on_modification (true);\n warn << host_loc->id () << \" tree build: \" \n << getusec () - start << \" usecs\\n\";\n\n replica_syncer = New refcounted<merkle_syncer> \n (ctype, tmptree, \n wrap (this, &syncer::doRPC_unbundler, succs[cur_succ]),\n wrap (this, &syncer::missing, succs[cur_succ]));\n \n bigint rngmin = pred->id ();\n bigint rngmax = succs[0]->id ();\n\n warn << host_loc->id () << \" syncing with \" << succs[cur_succ] \n << \" (succ #\" << cur_succ << \")\"\n << \" for range [ \" << rngmin << \", \" << rngmax << \" ]\\n\";\n \n replica_syncer->sync (rngmin, rngmax);\n \n delaycb (replica_timer, wrap (this, &syncer::sync_replicas)); \n}\n\nvoid\nsyncer::doRPC_unbundler (ptr<location> dst, RPC_delay_args *args)\n{\n chord_node n;\n dst->fill_node (n);\n ::doRPC (n, args->prog, args->procno, args->in, args->out, args->cb);\n}\n\nvoid\nsyncer::missing (ptr<location> from,\n\t\t bigint key, bool missing_local,\n\t\t bool round_over)\n{\n if (round_over) return;\n \/\/ if he tells us that we're missing it, then he has it.\n \/\/ otherwise, we found out he doesn't have it.\n \/\/ XXX this switch business is kinda gross.\n switch (ctype) {\n case DHASH_CONTENTHASH:\n db->update (key, from, missing_local, true);\n break;\n case DHASH_KEYHASH:\n case DHASH_NOAUTH:\n {\n chordID aux = (key & 0xFFFFFFFF);\n chordID dbkey = (key >> 32) << 32;\n db->update (dbkey, from, aux.getui (), missing_local, true);\n }\n break;\n default:\n fatal << \"syncer::missing: unexpected ctype \" << ctype << \"\\n\";\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--------------------------- new.cpp ----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define _LIBCPP_BUILDING_NEW\n\n#include <stdlib.h>\n\n#include \"new\"\n\n#ifndef __has_include\n#define __has_include(inc) 0\n#endif\n\n#ifdef __APPLE__\n #include <cxxabi.h>\n\n #ifndef _LIBCPPABI_VERSION\n \/\/ On Darwin, there are two STL shared libraries and a lower level ABI\n \/\/ shared library. The global holding the current new handler is\n \/\/ in the ABI library and named __cxa_new_handler.\n #define __new_handler __cxxabiapple::__cxa_new_handler\n #endif\n#else \/\/ __APPLE__\n #if defined(LIBCXXRT) || __has_include(<cxxabi.h>)\n #include <cxxabi.h>\n #endif \/\/ __has_include(<cxxabi.h>)\n #if !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n static std::new_handler __new_handler;\n #endif \/\/ _LIBCPPABI_VERSION\n#endif\n\n#ifndef __GLIBCXX__\n\n\/\/ Implement all new and delete operators as weak definitions\n\/\/ in this shared library, so that they can be overriden by programs\n\/\/ that define non-weak copies of the functions.\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid *\noperator new(std::size_t size)\n#if !__has_feature(cxx_noexcept)\n throw(std::bad_alloc)\n#endif\n{\n if (size == 0)\n size = 1;\n void* p;\n while ((p = ::malloc(size)) == 0)\n {\n \/\/ If malloc fails and there is a new_handler,\n \/\/ call it to try free up memory.\n std::new_handler nh = std::get_new_handler();\n if (nh)\n nh();\n else\n#ifndef _LIBCPP_NO_EXCEPTIONS\n throw std::bad_alloc();\n#else\n break;\n#endif\n }\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new(size_t size, const std::nothrow_t&) _NOEXCEPT\n{\n void* p = 0;\n#ifndef _LIBCPP_NO_EXCEPTIONS\n try\n {\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n p = ::operator new(size);\n#ifndef _LIBCPP_NO_EXCEPTIONS\n }\n catch (...)\n {\n }\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new[](size_t size)\n#if !__has_feature(cxx_noexcept)\n throw(std::bad_alloc)\n#endif\n{\n return ::operator new(size);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new[](size_t size, const std::nothrow_t&) _NOEXCEPT\n{\n void* p = 0;\n#ifndef _LIBCPP_NO_EXCEPTIONS\n try\n {\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n p = ::operator new[](size);\n#ifndef _LIBCPP_NO_EXCEPTIONS\n }\n catch (...)\n {\n }\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete(void* ptr) _NOEXCEPT\n{\n if (ptr)\n ::free(ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT\n{\n ::operator delete(ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete[] (void* ptr) _NOEXCEPT\n{\n ::operator delete (ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT\n{\n ::operator delete[](ptr);\n}\n\n#endif \/\/ !__GLIBCXX__\n\nnamespace std\n{\n\n#ifndef __GLIBCXX__\nconst nothrow_t nothrow = {};\n#endif\n\n#ifndef _LIBCPPABI_VERSION\n\n#ifndef __GLIBCXX__\n\nnew_handler\nset_new_handler(new_handler handler) _NOEXCEPT\n{\n return __sync_lock_test_and_set(&__new_handler, handler);\n}\n\nnew_handler\nget_new_handler() _NOEXCEPT\n{\n return __sync_fetch_and_add(&__new_handler, nullptr);\n}\n\n#endif \/\/ !__GLIBCXX__\n\n#ifndef LIBCXXRT\n\nbad_alloc::bad_alloc() _NOEXCEPT\n{\n}\n\n#ifndef __GLIBCXX__\n\nbad_alloc::~bad_alloc() _NOEXCEPT\n{\n}\n\nconst char*\nbad_alloc::what() const _NOEXCEPT\n{\n return \"std::bad_alloc\";\n}\n\n#endif \/\/ !__GLIBCXX__\n\n#endif \/\/LIBCXXRT\n\nbad_array_new_length::bad_array_new_length() _NOEXCEPT\n{\n}\n\nbad_array_new_length::~bad_array_new_length() _NOEXCEPT\n{\n}\n\nconst char*\nbad_array_length::what() const _NOEXCEPT\n{\n return \"bad_array_length\";\n}\n\nbad_array_length::bad_array_length() _NOEXCEPT\n{\n}\n\nbad_array_length::~bad_array_length() _NOEXCEPT\n{\n}\n\nconst char*\nbad_array_new_length::what() const _NOEXCEPT\n{\n return \"bad_array_new_length\";\n}\n\n#endif \/\/ _LIBCPPABI_VERSION\n\n#ifndef LIBSTDCXX\n\nvoid\n__throw_bad_alloc()\n{\n#ifndef _LIBCPP_NO_EXCEPTIONS\n throw bad_alloc();\n#endif\n}\n\n#endif \/\/ !LIBSTDCXX\n\n} \/\/ std\n<commit_msg>libcxxrt now implements bad_array_new_length and need to gaurd against multiple defines. Patch from Baptiste Daroussin.<commit_after>\/\/===--------------------------- new.cpp ----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define _LIBCPP_BUILDING_NEW\n\n#include <stdlib.h>\n\n#include \"new\"\n\n#ifndef __has_include\n#define __has_include(inc) 0\n#endif\n\n#ifdef __APPLE__\n #include <cxxabi.h>\n\n #ifndef _LIBCPPABI_VERSION\n \/\/ On Darwin, there are two STL shared libraries and a lower level ABI\n \/\/ shared library. The global holding the current new handler is\n \/\/ in the ABI library and named __cxa_new_handler.\n #define __new_handler __cxxabiapple::__cxa_new_handler\n #endif\n#else \/\/ __APPLE__\n #if defined(LIBCXXRT) || __has_include(<cxxabi.h>)\n #include <cxxabi.h>\n #endif \/\/ __has_include(<cxxabi.h>)\n #if !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n static std::new_handler __new_handler;\n #endif \/\/ _LIBCPPABI_VERSION\n#endif\n\n#ifndef __GLIBCXX__\n\n\/\/ Implement all new and delete operators as weak definitions\n\/\/ in this shared library, so that they can be overriden by programs\n\/\/ that define non-weak copies of the functions.\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid *\noperator new(std::size_t size)\n#if !__has_feature(cxx_noexcept)\n throw(std::bad_alloc)\n#endif\n{\n if (size == 0)\n size = 1;\n void* p;\n while ((p = ::malloc(size)) == 0)\n {\n \/\/ If malloc fails and there is a new_handler,\n \/\/ call it to try free up memory.\n std::new_handler nh = std::get_new_handler();\n if (nh)\n nh();\n else\n#ifndef _LIBCPP_NO_EXCEPTIONS\n throw std::bad_alloc();\n#else\n break;\n#endif\n }\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new(size_t size, const std::nothrow_t&) _NOEXCEPT\n{\n void* p = 0;\n#ifndef _LIBCPP_NO_EXCEPTIONS\n try\n {\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n p = ::operator new(size);\n#ifndef _LIBCPP_NO_EXCEPTIONS\n }\n catch (...)\n {\n }\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new[](size_t size)\n#if !__has_feature(cxx_noexcept)\n throw(std::bad_alloc)\n#endif\n{\n return ::operator new(size);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid*\noperator new[](size_t size, const std::nothrow_t&) _NOEXCEPT\n{\n void* p = 0;\n#ifndef _LIBCPP_NO_EXCEPTIONS\n try\n {\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n p = ::operator new[](size);\n#ifndef _LIBCPP_NO_EXCEPTIONS\n }\n catch (...)\n {\n }\n#endif \/\/ _LIBCPP_NO_EXCEPTIONS\n return p;\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete(void* ptr) _NOEXCEPT\n{\n if (ptr)\n ::free(ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT\n{\n ::operator delete(ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete[] (void* ptr) _NOEXCEPT\n{\n ::operator delete (ptr);\n}\n\n_LIBCPP_WEAK _LIBCPP_NEW_DELETE_VIS\nvoid\noperator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT\n{\n ::operator delete[](ptr);\n}\n\n#endif \/\/ !__GLIBCXX__\n\nnamespace std\n{\n\n#ifndef __GLIBCXX__\nconst nothrow_t nothrow = {};\n#endif\n\n#ifndef _LIBCPPABI_VERSION\n\n#ifndef __GLIBCXX__\n\nnew_handler\nset_new_handler(new_handler handler) _NOEXCEPT\n{\n return __sync_lock_test_and_set(&__new_handler, handler);\n}\n\nnew_handler\nget_new_handler() _NOEXCEPT\n{\n return __sync_fetch_and_add(&__new_handler, nullptr);\n}\n\n#endif \/\/ !__GLIBCXX__\n\n#ifndef LIBCXXRT\n\nbad_alloc::bad_alloc() _NOEXCEPT\n{\n}\n\n#ifndef __GLIBCXX__\n\nbad_alloc::~bad_alloc() _NOEXCEPT\n{\n}\n\nconst char*\nbad_alloc::what() const _NOEXCEPT\n{\n return \"std::bad_alloc\";\n}\n\n#endif \/\/ !__GLIBCXX__\n\nbad_array_new_length::bad_array_new_length() _NOEXCEPT\n{\n}\n\nbad_array_new_length::~bad_array_new_length() _NOEXCEPT\n{\n}\n\n#endif \/\/LIBCXXRT\n\nconst char*\nbad_array_length::what() const _NOEXCEPT\n{\n return \"bad_array_length\";\n}\n\nbad_array_length::bad_array_length() _NOEXCEPT\n{\n}\n\nbad_array_length::~bad_array_length() _NOEXCEPT\n{\n}\n\nconst char*\nbad_array_new_length::what() const _NOEXCEPT\n{\n return \"bad_array_new_length\";\n}\n\n#endif \/\/ _LIBCPPABI_VERSION\n\n#ifndef LIBSTDCXX\n\nvoid\n__throw_bad_alloc()\n{\n#ifndef _LIBCPP_NO_EXCEPTIONS\n throw bad_alloc();\n#endif\n}\n\n#endif \/\/ !LIBSTDCXX\n\n} \/\/ std\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include <iDynTree\/Model\/Model.h>\n#include <iDynTree\/Model\/Traversal.h>\n\n#include <cassert>\n#include <deque>\n\nnamespace iDynTree\n{\n\nModel::Model(): defaultBaseLink(LINK_INVALID_INDEX), nrOfPosCoords(0), nrOfDOFs(0)\n{\n\n}\n\nvoid Model::copy(const Model& other)\n{\n \/\/ Add all the links, preserving the numbering\n for(unsigned int lnk=0; lnk < other.getNrOfLinks(); lnk++ )\n {\n this->addLink(other.linkNames[lnk],other.links[lnk]);\n }\n\n \/\/ Add all joints, preserving the numbering\n\n \/\/ reset the nrOfDOFs (it will be then update in addJoint\n nrOfPosCoords = 0;\n nrOfDOFs = 0;\n\n for(unsigned int jnt=0; jnt < other.getNrOfJoints(); jnt++ )\n {\n this->addJoint(other.jointNames[jnt],other.joints[jnt]);\n }\n\n \/\/ Copy the default base link\n this->setDefaultBaseLink(other.getDefaultBaseLink());\n}\n\n\nModel::Model(const Model& other)\n{\n copy(other);\n}\n\nModel& Model::operator=(const Model& other)\n{\n if( &other != this )\n {\n destroy();\n copy(other);\n }\n\n return *this;\n}\n\nvoid Model::destroy()\n{\n links.resize(0);\n linkNames.resize(0);\n for(unsigned int jnt=0; jnt < this->getNrOfJoints(); jnt++ )\n {\n delete this->joints[jnt];\n this->joints[jnt] = 0;\n }\n joints.resize(0);\n nrOfPosCoords = 0;\n nrOfDOFs = 0;\n jointNames.resize(0);\n additionalFrames.resize(0);\n additionalFramesLinks.resize(0);\n frameNames.resize(0);\n neighbors.resize(0);\n}\n\nModel::~Model()\n{\n destroy();\n}\n\nsize_t Model::getNrOfLinks() const\n{\n return links.size();\n}\n\nLinkIndex Model::getLinkIndex(const std::string& linkName) const\n{\n for(size_t i=0; i < this->getNrOfLinks(); i++ )\n {\n if( linkName == linkNames[i] )\n {\n return i;\n }\n }\n\n return LINK_INVALID_INDEX;\n}\n\nstd::string Model::getLinkName(const LinkIndex linkIndex) const\n{\n if( linkIndex >= 0 && linkIndex < (LinkIndex) this->getNrOfLinks() )\n {\n return linkNames[linkIndex];\n }\n else\n {\n return LINK_INVALID_NAME;\n }\n}\n\nLink* Model::getLink(const LinkIndex linkIndex)\n{\n return &(links[linkIndex]);\n}\n\nconst Link* Model::getLink(const LinkIndex linkIndex) const\n{\n return &(links[linkIndex]);\n}\n\nsize_t Model::getNrOfJoints() const\n{\n return joints.size();\n}\n\nJointIndex Model::getJointIndex(const std::string& jointName) const\n{\n for(size_t i=0; i < this->getNrOfJoints(); i++ )\n {\n if( jointName == jointNames[i] )\n {\n return i;\n }\n }\n\n return JOINT_INVALID_INDEX;\n}\n\nstd::string Model::getJointName(const JointIndex jointIndex) const\n{\n if( jointIndex >= 0 && jointIndex < (JointIndex)this->getNrOfJoints() )\n {\n return jointNames[jointIndex];\n }\n else\n {\n return JOINT_INVALID_NAME;\n }\n}\n\nIJoint* Model::getJoint(const JointIndex jointIndex)\n{\n return (joints[jointIndex]);\n}\n\nconst IJoint* Model::getJoint(const JointIndex jointIndex) const\n{\n return (joints[jointIndex]);\n}\n\nbool Model::isLinkNameUsed(const std::string linkName)\n{\n return (LINK_INVALID_INDEX != getLinkIndex(linkName));\n}\n\nLinkIndex Model::addLink(const std::string& name, const Link& link)\n{\n \/\/ Check that the name is not already used by a link or frame\n if(isFrameNameUsed(name))\n {\n std::string error = \"a link or frame of name \" + name + \" is already present in the model\";\n reportError(\"Model\",\"addLink\",error.c_str());\n return LINK_INVALID_INDEX;\n }\n\n \/\/ Add the link to the vector of names and of links\n assert(links.size() == linkNames.size());\n linkNames.push_back(name);\n links.push_back(link);\n\n \/\/ add an empty adjacency list to the neighbors members\n neighbors.push_back(std::vector<Neighbor>());\n\n LinkIndex newLinkIndex = (LinkIndex)(links.size()-1);\n\n links[newLinkIndex].setIndex(newLinkIndex);\n\n \/\/ if this is the first link added to the model\n \/\/ and the defaultBaseLink has not been setted,\n \/\/ set the defaultBaseLink to be this link\n if( newLinkIndex == 0 && getDefaultBaseLink() == LINK_INVALID_INDEX )\n {\n setDefaultBaseLink(newLinkIndex);\n }\n\n return newLinkIndex;\n}\n\nbool Model::isJointNameUsed(const std::string jointName)\n{\n return (JOINT_INVALID_INDEX != getJointIndex(jointName));\n}\n\n\nJointIndex Model::addJoint(const std::string& jointName, IJointConstPtr joint)\n{\n assert(joint->getFirstAttachedLink() != joint->getSecondAttachedLink());\n\n if(isJointNameUsed(jointName))\n {\n std::string error = \"a joint of name \" + jointName + \" is already present in the model\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Check that the joint is referring to links that are in the model\n LinkIndex firstLink = joint->getFirstAttachedLink();\n LinkIndex secondLink = joint->getSecondAttachedLink();\n if( firstLink < 0 || firstLink >= (LinkIndex)this->getNrOfLinks() ||\n secondLink < 0 || secondLink >= (LinkIndex)this->getNrOfLinks() )\n {\n std::string error = \"joint \" + jointName + \" is attached to a link that does not exist\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Check that the joint is not connecting a link to itself\n if( firstLink == secondLink )\n {\n std::string error = \"joint \" + jointName + \" is connecting link \" + this->getLinkName(firstLink) + \" to itself\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Update the joints and jointNames structure\n jointNames.push_back(jointName);\n joints.push_back(joint->clone());\n\n JointIndex thisJointIndex = (JointIndex)(joints.size()-1);\n\n \/\/ Update the adjacency list\n Neighbor firstLinkNeighbor;\n firstLinkNeighbor.neighborLink = secondLink;\n firstLinkNeighbor.neighborJoint = thisJointIndex;\n this->neighbors[firstLink].push_back(firstLinkNeighbor);\n\n Neighbor secondLinkNeighbor;\n secondLinkNeighbor.neighborLink = firstLink;\n secondLinkNeighbor.neighborJoint = thisJointIndex;\n this->neighbors[secondLink].push_back(secondLinkNeighbor);\n\n \/\/ Set the joint index and dof offset\n this->joints[thisJointIndex]->setIndex(thisJointIndex);\n this->joints[thisJointIndex]->setPosCoordsOffset(this->nrOfPosCoords);\n this->joints[thisJointIndex]->setDOFsOffset(this->nrOfDOFs);\n\n \/\/ Update the number of dofs\n this->nrOfPosCoords += this->joints[thisJointIndex]->getNrOfPosCoords();\n this->nrOfDOFs += this->joints[thisJointIndex]->getNrOfDOFs();\n\n return thisJointIndex;\n}\n\nsize_t Model::getNrOfPosCoords() const\n{\n return nrOfDOFs;\n}\n\nsize_t Model::getNrOfDOFs() const\n{\n return nrOfDOFs;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/ Frame Related functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsize_t Model::getNrOfFrames() const\n{\n return (size_t)getNrOfLinks() + this->additionalFrames.size();\n}\n\nstd::string Model::getFrameName(const FrameIndex frameIndex) const\n{\n if( frameIndex >= 0 && frameIndex < (FrameIndex)this->getNrOfLinks() )\n {\n return linkNames[frameIndex];\n }\n else if( frameIndex >= this->getNrOfLinks() && frameIndex < (FrameIndex)this->getNrOfFrames() )\n {\n return frameNames[frameIndex-getNrOfLinks()];\n }\n else\n {\n return FRAME_INVALID_NAME;\n }\n}\n\nFrameIndex Model::getFrameIndex(const std::string& frameName) const\n{\n for(int i=0; i < this->getNrOfLinks(); i++ )\n {\n if( frameName == linkNames[i] )\n {\n return (FrameIndex)i;\n }\n }\n\n for(int i=this->getNrOfLinks(); i < this->getNrOfFrames(); i++ )\n {\n if( frameName == this->frameNames[i-getNrOfLinks()] )\n {\n return (FrameIndex)i;\n }\n }\n\n return FRAME_INVALID_INDEX;\n}\n\nbool Model::isFrameNameUsed(const std::string frameName)\n{\n return (FRAME_INVALID_INDEX != getFrameIndex(frameName));\n}\n\n\nbool Model::addAdditionalFrameToLink(const std::string& linkName,\n const std::string& frameName,\n Transform link_H_frame)\n{\n \/\/ Check that the link actually exist\n LinkIndex linkIndex = this->getLinkIndex(linkName);\n if( linkIndex == LINK_INVALID_INDEX )\n {\n std::string error = \"error adding frame \" + frameName + \" : a link of name \"\n + linkName + \" is not present in the model\";\n reportError(\"Model\",\"addAdditionalFrameToLink\",error.c_str());\n return false;\n }\n\n \/\/ Check that the frame name is not already used by a link or frame\n if(isFrameNameUsed(frameName))\n {\n std::string error = \"a link or frame of name \" + frameName + \" is already present in the model\";\n reportError(\"Model\",\"addAdditionalFrameToLink\",error.c_str());\n return false;\n }\n\n \/\/ If all error has passed, actually add the frame\n this->additionalFrames.push_back(link_H_frame);\n this->additionalFramesLinks.push_back(linkIndex);\n this->frameNames.push_back(frameName);\n\n return true;\n}\n\nTransform Model::getFrameTransform(const FrameIndex frameIndex) const\n{\n \/\/ The link_H_frame transform for the link\n \/\/ main frame is the identity\n if( frameIndex < this->getNrOfLinks() ||\n frameIndex >= this->getNrOfFrames() )\n {\n return Transform::Identity();\n }\n\n \/\/ For an additonal frame the transform is instead stored\n \/\/ in the additionalFrames vector\n return this->additionalFrames[frameIndex-getNrOfLinks()];\n}\n\n\nLinkIndex Model::getFrameLink(const FrameIndex frameIndex) const\n{\n \/\/ The link_H_frame transform for the link\n \/\/ main frame is the link it self\n if( frameIndex >= 0 &&\n frameIndex < this->getNrOfLinks() )\n {\n return (LinkIndex)frameIndex;\n }\n\n if( frameIndex >= this->getNrOfLinks() &&\n frameIndex < this->getNrOfFrames() )\n {\n \/\/ For an additonal frame the link index is instead stored\n \/\/ in the additionalFramesLinks vector\n return this->additionalFramesLinks[frameIndex-getNrOfLinks()];\n }\n\n \/\/ If the frameIndex is out of bounds, return an invalid index\n return LINK_INVALID_INDEX;\n}\n\n\n\n\n\n\nunsigned int Model::getNrOfNeighbors(const LinkIndex link) const\n{\n assert(link < this->neighbors.size());\n return this->neighbors[link].size();\n}\n\nNeighbor Model::getNeighbor(const LinkIndex link, unsigned int neighborIndex) const\n{\n assert(link < this->getNrOfLinks());\n assert(neighborIndex < this->getNrOfNeighbors(link));\n return this->neighbors[link][neighborIndex];\n}\n\nbool Model::setDefaultBaseLink(const LinkIndex linkIndex)\n{\n if( linkIndex < 0 || linkIndex >= this->getNrOfLinks() )\n {\n return false;\n }\n else\n {\n defaultBaseLink = linkIndex;\n return true;\n }\n}\n\nLinkIndex Model::getDefaultBaseLink() const\n{\n return defaultBaseLink;\n}\n\nbool Model::computeFullTreeTraversal(Traversal & traversal) const\n{\n return computeFullTreeTraversal(traversal,this->getDefaultBaseLink());\n}\n\nstruct stackEl { LinkConstPtr link; LinkConstPtr parent;};\n\nvoid addBaseLinkToTraversal(const Model & model, Traversal & traversal, int & traversalFirstEmptySlot,\n LinkIndex linkToAdd, std::deque<stackEl> & linkToVisit)\n{\n assert(traversalFirstEmptySlot == 0);\n traversal.setTraversalElement(traversalFirstEmptySlot,\n model.getLink(linkToAdd),\n 0,\n 0);\n\n traversalFirstEmptySlot++;\n\n stackEl el;\n el.link = model.getLink(linkToAdd);\n el.parent = 0;\n\n linkToVisit.push_back(el);\n}\n\nvoid addLinkToTraversal(const Model & model, Traversal & traversal, int & traversalFirstEmptySlot,\n LinkIndex linkToAdd, JointIndex parentJointToAdd, LinkIndex parentLinkToAdd,\n std::deque<stackEl> & linkToVisit)\n{\n traversal.setTraversalElement(traversalFirstEmptySlot,\n model.getLink(linkToAdd),\n model.getJoint(parentJointToAdd),\n model.getLink(parentLinkToAdd));\n\n traversalFirstEmptySlot++;\n\n stackEl el;\n el.link = model.getLink(linkToAdd);\n el.parent = model.getLink(parentLinkToAdd);\n\n linkToVisit.push_back(el);\n}\n\nbool Model::computeFullTreeTraversal(Traversal & traversal, const LinkIndex traversalBase) const\n{\n if( traversalBase < 0 || traversalBase >= this->getNrOfLinks() )\n {\n reportError(\"Model\",\"computeFullTreeTraversal\",\"requested traversalBase is out of bounds\");\n return false;\n }\n\n \/\/ The full tree traversal is a traversal spanning all the links\n \/\/ of a model, so it include getNrOfLinks() visited links\n traversal.reset(this->getNrOfLinks(),this->getNrOfLinks());\n\n \/\/ A link is considered visit when all its child (given the traversalBase)\n \/\/ have been added to the traversal\n std::deque<stackEl> linkToVisit;\n\n \/\/ We add as first link the requested traversalBase\n int traversalFirstEmptySlot = 0;\n addBaseLinkToTraversal(*this,traversal,traversalFirstEmptySlot,traversalBase,linkToVisit);\n\n \/\/ while there is some link still to visit\n unsigned int visitNumber=0;\n while( linkToVisit.size() > 0 )\n {\n assert(linkToVisit.size() <= this->getNrOfLinks());\n\n \/\/ DPS : we use linkToVisit as a stack\n LinkConstPtr visitedLink = linkToVisit.back().link;\n LinkConstPtr visitedLinkParent = linkToVisit.back().parent;\n LinkIndex visitedLinkIndex = visitedLink->getIndex();\n linkToVisit.pop_back();\n\n for(unsigned int neigh_i=0; neigh_i < this->getNrOfNeighbors(visitedLinkIndex); neigh_i++ )\n {\n \/\/ add to the stack all the neighbors, except for parent link\n \/\/ (if the visited link is the base one, add all the neighbors)\n \/\/ the visited link is already in the Traversal, so we can use it\n \/\/ to check for its parent\n Neighbor neighb = this->getNeighbor(visitedLinkIndex,neigh_i);\n if( visitedLinkParent == 0 || neighb.neighborLink != visitedLinkParent->getIndex() )\n {\n addLinkToTraversal(*this,traversal,traversalFirstEmptySlot,neighb.neighborLink,\n neighb.neighborJoint,visitedLink->getIndex(),linkToVisit);\n }\n }\n }\n\n return true;\n}\n\n\n\n\n}\n<commit_msg>[model] Fix use of initialized memory in Model copy constructor<commit_after>\/*\n * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include <iDynTree\/Model\/Model.h>\n#include <iDynTree\/Model\/Traversal.h>\n\n#include <cassert>\n#include <deque>\n\nnamespace iDynTree\n{\n\nModel::Model(): defaultBaseLink(LINK_INVALID_INDEX), nrOfPosCoords(0), nrOfDOFs(0)\n{\n\n}\n\nvoid Model::copy(const Model& other)\n{\n \/\/ reset the base link, the real one will be copied later\n this->defaultBaseLink = LINK_INVALID_INDEX;\n\n \/\/ Add all the links, preserving the numbering\n for(unsigned int lnk=0; lnk < other.getNrOfLinks(); lnk++ )\n {\n this->addLink(other.linkNames[lnk],other.links[lnk]);\n }\n\n \/\/ Add all joints, preserving the numbering\n \/\/ reset the nrOfDOFs (it will be then update in addJoint)\n nrOfPosCoords = 0;\n nrOfDOFs = 0;\n\n for(unsigned int jnt=0; jnt < other.getNrOfJoints(); jnt++ )\n {\n this->addJoint(other.jointNames[jnt],other.joints[jnt]);\n }\n\n \/\/ Copy the default base link\n this->setDefaultBaseLink(other.getDefaultBaseLink());\n}\n\n\nModel::Model(const Model& other)\n{\n copy(other);\n}\n\nModel& Model::operator=(const Model& other)\n{\n if( &other != this )\n {\n destroy();\n copy(other);\n }\n\n return *this;\n}\n\nvoid Model::destroy()\n{\n links.resize(0);\n linkNames.resize(0);\n for(unsigned int jnt=0; jnt < this->getNrOfJoints(); jnt++ )\n {\n delete this->joints[jnt];\n this->joints[jnt] = 0;\n }\n joints.resize(0);\n nrOfPosCoords = 0;\n nrOfDOFs = 0;\n jointNames.resize(0);\n additionalFrames.resize(0);\n additionalFramesLinks.resize(0);\n frameNames.resize(0);\n neighbors.resize(0);\n}\n\nModel::~Model()\n{\n destroy();\n}\n\nsize_t Model::getNrOfLinks() const\n{\n return links.size();\n}\n\nLinkIndex Model::getLinkIndex(const std::string& linkName) const\n{\n for(size_t i=0; i < this->getNrOfLinks(); i++ )\n {\n if( linkName == linkNames[i] )\n {\n return i;\n }\n }\n\n return LINK_INVALID_INDEX;\n}\n\nstd::string Model::getLinkName(const LinkIndex linkIndex) const\n{\n if( linkIndex >= 0 && linkIndex < (LinkIndex) this->getNrOfLinks() )\n {\n return linkNames[linkIndex];\n }\n else\n {\n return LINK_INVALID_NAME;\n }\n}\n\nLink* Model::getLink(const LinkIndex linkIndex)\n{\n return &(links[linkIndex]);\n}\n\nconst Link* Model::getLink(const LinkIndex linkIndex) const\n{\n return &(links[linkIndex]);\n}\n\nsize_t Model::getNrOfJoints() const\n{\n return joints.size();\n}\n\nJointIndex Model::getJointIndex(const std::string& jointName) const\n{\n for(size_t i=0; i < this->getNrOfJoints(); i++ )\n {\n if( jointName == jointNames[i] )\n {\n return i;\n }\n }\n\n return JOINT_INVALID_INDEX;\n}\n\nstd::string Model::getJointName(const JointIndex jointIndex) const\n{\n if( jointIndex >= 0 && jointIndex < (JointIndex)this->getNrOfJoints() )\n {\n return jointNames[jointIndex];\n }\n else\n {\n return JOINT_INVALID_NAME;\n }\n}\n\nIJoint* Model::getJoint(const JointIndex jointIndex)\n{\n return (joints[jointIndex]);\n}\n\nconst IJoint* Model::getJoint(const JointIndex jointIndex) const\n{\n return (joints[jointIndex]);\n}\n\nbool Model::isLinkNameUsed(const std::string linkName)\n{\n return (LINK_INVALID_INDEX != getLinkIndex(linkName));\n}\n\nLinkIndex Model::addLink(const std::string& name, const Link& link)\n{\n \/\/ Check that the name is not already used by a link or frame\n if(isFrameNameUsed(name))\n {\n std::string error = \"a link or frame of name \" + name + \" is already present in the model\";\n reportError(\"Model\",\"addLink\",error.c_str());\n return LINK_INVALID_INDEX;\n }\n\n \/\/ Add the link to the vector of names and of links\n assert(links.size() == linkNames.size());\n linkNames.push_back(name);\n links.push_back(link);\n\n \/\/ add an empty adjacency list to the neighbors members\n neighbors.push_back(std::vector<Neighbor>());\n\n LinkIndex newLinkIndex = (LinkIndex)(links.size()-1);\n\n links[newLinkIndex].setIndex(newLinkIndex);\n\n \/\/ if this is the first link added to the model\n \/\/ and the defaultBaseLink has not been setted,\n \/\/ set the defaultBaseLink to be this link\n if( newLinkIndex == 0 && getDefaultBaseLink() == LINK_INVALID_INDEX )\n {\n setDefaultBaseLink(newLinkIndex);\n }\n\n return newLinkIndex;\n}\n\nbool Model::isJointNameUsed(const std::string jointName)\n{\n return (JOINT_INVALID_INDEX != getJointIndex(jointName));\n}\n\n\nJointIndex Model::addJoint(const std::string& jointName, IJointConstPtr joint)\n{\n assert(joint->getFirstAttachedLink() != joint->getSecondAttachedLink());\n\n if(isJointNameUsed(jointName))\n {\n std::string error = \"a joint of name \" + jointName + \" is already present in the model\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Check that the joint is referring to links that are in the model\n LinkIndex firstLink = joint->getFirstAttachedLink();\n LinkIndex secondLink = joint->getSecondAttachedLink();\n if( firstLink < 0 || firstLink >= (LinkIndex)this->getNrOfLinks() ||\n secondLink < 0 || secondLink >= (LinkIndex)this->getNrOfLinks() )\n {\n std::string error = \"joint \" + jointName + \" is attached to a link that does not exist\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Check that the joint is not connecting a link to itself\n if( firstLink == secondLink )\n {\n std::string error = \"joint \" + jointName + \" is connecting link \" + this->getLinkName(firstLink) + \" to itself\";\n reportError(\"Model\",\"addJoint\",error.c_str());\n return JOINT_INVALID_INDEX;\n }\n\n \/\/ Update the joints and jointNames structure\n jointNames.push_back(jointName);\n joints.push_back(joint->clone());\n\n JointIndex thisJointIndex = (JointIndex)(joints.size()-1);\n\n \/\/ Update the adjacency list\n Neighbor firstLinkNeighbor;\n firstLinkNeighbor.neighborLink = secondLink;\n firstLinkNeighbor.neighborJoint = thisJointIndex;\n this->neighbors[firstLink].push_back(firstLinkNeighbor);\n\n Neighbor secondLinkNeighbor;\n secondLinkNeighbor.neighborLink = firstLink;\n secondLinkNeighbor.neighborJoint = thisJointIndex;\n this->neighbors[secondLink].push_back(secondLinkNeighbor);\n\n \/\/ Set the joint index and dof offset\n this->joints[thisJointIndex]->setIndex(thisJointIndex);\n this->joints[thisJointIndex]->setPosCoordsOffset(this->nrOfPosCoords);\n this->joints[thisJointIndex]->setDOFsOffset(this->nrOfDOFs);\n\n \/\/ Update the number of dofs\n this->nrOfPosCoords += this->joints[thisJointIndex]->getNrOfPosCoords();\n this->nrOfDOFs += this->joints[thisJointIndex]->getNrOfDOFs();\n\n return thisJointIndex;\n}\n\nsize_t Model::getNrOfPosCoords() const\n{\n return nrOfDOFs;\n}\n\nsize_t Model::getNrOfDOFs() const\n{\n return nrOfDOFs;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/ Frame Related functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsize_t Model::getNrOfFrames() const\n{\n return (size_t)getNrOfLinks() + this->additionalFrames.size();\n}\n\nstd::string Model::getFrameName(const FrameIndex frameIndex) const\n{\n if( frameIndex >= 0 && frameIndex < (FrameIndex)this->getNrOfLinks() )\n {\n return linkNames[frameIndex];\n }\n else if( frameIndex >= this->getNrOfLinks() && frameIndex < (FrameIndex)this->getNrOfFrames() )\n {\n return frameNames[frameIndex-getNrOfLinks()];\n }\n else\n {\n return FRAME_INVALID_NAME;\n }\n}\n\nFrameIndex Model::getFrameIndex(const std::string& frameName) const\n{\n for(int i=0; i < this->getNrOfLinks(); i++ )\n {\n if( frameName == linkNames[i] )\n {\n return (FrameIndex)i;\n }\n }\n\n for(int i=this->getNrOfLinks(); i < this->getNrOfFrames(); i++ )\n {\n if( frameName == this->frameNames[i-getNrOfLinks()] )\n {\n return (FrameIndex)i;\n }\n }\n\n return FRAME_INVALID_INDEX;\n}\n\nbool Model::isFrameNameUsed(const std::string frameName)\n{\n return (FRAME_INVALID_INDEX != getFrameIndex(frameName));\n}\n\n\nbool Model::addAdditionalFrameToLink(const std::string& linkName,\n const std::string& frameName,\n Transform link_H_frame)\n{\n \/\/ Check that the link actually exist\n LinkIndex linkIndex = this->getLinkIndex(linkName);\n if( linkIndex == LINK_INVALID_INDEX )\n {\n std::string error = \"error adding frame \" + frameName + \" : a link of name \"\n + linkName + \" is not present in the model\";\n reportError(\"Model\",\"addAdditionalFrameToLink\",error.c_str());\n return false;\n }\n\n \/\/ Check that the frame name is not already used by a link or frame\n if(isFrameNameUsed(frameName))\n {\n std::string error = \"a link or frame of name \" + frameName + \" is already present in the model\";\n reportError(\"Model\",\"addAdditionalFrameToLink\",error.c_str());\n return false;\n }\n\n \/\/ If all error has passed, actually add the frame\n this->additionalFrames.push_back(link_H_frame);\n this->additionalFramesLinks.push_back(linkIndex);\n this->frameNames.push_back(frameName);\n\n return true;\n}\n\nTransform Model::getFrameTransform(const FrameIndex frameIndex) const\n{\n \/\/ The link_H_frame transform for the link\n \/\/ main frame is the identity\n if( frameIndex < this->getNrOfLinks() ||\n frameIndex >= this->getNrOfFrames() )\n {\n return Transform::Identity();\n }\n\n \/\/ For an additonal frame the transform is instead stored\n \/\/ in the additionalFrames vector\n return this->additionalFrames[frameIndex-getNrOfLinks()];\n}\n\n\nLinkIndex Model::getFrameLink(const FrameIndex frameIndex) const\n{\n \/\/ The link_H_frame transform for the link\n \/\/ main frame is the link it self\n if( frameIndex >= 0 &&\n frameIndex < this->getNrOfLinks() )\n {\n return (LinkIndex)frameIndex;\n }\n\n if( frameIndex >= this->getNrOfLinks() &&\n frameIndex < this->getNrOfFrames() )\n {\n \/\/ For an additonal frame the link index is instead stored\n \/\/ in the additionalFramesLinks vector\n return this->additionalFramesLinks[frameIndex-getNrOfLinks()];\n }\n\n \/\/ If the frameIndex is out of bounds, return an invalid index\n return LINK_INVALID_INDEX;\n}\n\n\n\n\n\n\nunsigned int Model::getNrOfNeighbors(const LinkIndex link) const\n{\n assert(link < this->neighbors.size());\n return this->neighbors[link].size();\n}\n\nNeighbor Model::getNeighbor(const LinkIndex link, unsigned int neighborIndex) const\n{\n assert(link < this->getNrOfLinks());\n assert(neighborIndex < this->getNrOfNeighbors(link));\n return this->neighbors[link][neighborIndex];\n}\n\nbool Model::setDefaultBaseLink(const LinkIndex linkIndex)\n{\n if( linkIndex < 0 || linkIndex >= this->getNrOfLinks() )\n {\n return false;\n }\n else\n {\n defaultBaseLink = linkIndex;\n return true;\n }\n}\n\nLinkIndex Model::getDefaultBaseLink() const\n{\n return defaultBaseLink;\n}\n\nbool Model::computeFullTreeTraversal(Traversal & traversal) const\n{\n return computeFullTreeTraversal(traversal,this->getDefaultBaseLink());\n}\n\nstruct stackEl { LinkConstPtr link; LinkConstPtr parent;};\n\nvoid addBaseLinkToTraversal(const Model & model, Traversal & traversal, int & traversalFirstEmptySlot,\n LinkIndex linkToAdd, std::deque<stackEl> & linkToVisit)\n{\n assert(traversalFirstEmptySlot == 0);\n traversal.setTraversalElement(traversalFirstEmptySlot,\n model.getLink(linkToAdd),\n 0,\n 0);\n\n traversalFirstEmptySlot++;\n\n stackEl el;\n el.link = model.getLink(linkToAdd);\n el.parent = 0;\n\n linkToVisit.push_back(el);\n}\n\nvoid addLinkToTraversal(const Model & model, Traversal & traversal, int & traversalFirstEmptySlot,\n LinkIndex linkToAdd, JointIndex parentJointToAdd, LinkIndex parentLinkToAdd,\n std::deque<stackEl> & linkToVisit)\n{\n traversal.setTraversalElement(traversalFirstEmptySlot,\n model.getLink(linkToAdd),\n model.getJoint(parentJointToAdd),\n model.getLink(parentLinkToAdd));\n\n traversalFirstEmptySlot++;\n\n stackEl el;\n el.link = model.getLink(linkToAdd);\n el.parent = model.getLink(parentLinkToAdd);\n\n linkToVisit.push_back(el);\n}\n\nbool Model::computeFullTreeTraversal(Traversal & traversal, const LinkIndex traversalBase) const\n{\n if( traversalBase < 0 || traversalBase >= this->getNrOfLinks() )\n {\n reportError(\"Model\",\"computeFullTreeTraversal\",\"requested traversalBase is out of bounds\");\n return false;\n }\n\n \/\/ The full tree traversal is a traversal spanning all the links\n \/\/ of a model, so it include getNrOfLinks() visited links\n traversal.reset(this->getNrOfLinks(),this->getNrOfLinks());\n\n \/\/ A link is considered visit when all its child (given the traversalBase)\n \/\/ have been added to the traversal\n std::deque<stackEl> linkToVisit;\n\n \/\/ We add as first link the requested traversalBase\n int traversalFirstEmptySlot = 0;\n addBaseLinkToTraversal(*this,traversal,traversalFirstEmptySlot,traversalBase,linkToVisit);\n\n \/\/ while there is some link still to visit\n unsigned int visitNumber=0;\n while( linkToVisit.size() > 0 )\n {\n assert(linkToVisit.size() <= this->getNrOfLinks());\n\n \/\/ DPS : we use linkToVisit as a stack\n LinkConstPtr visitedLink = linkToVisit.back().link;\n LinkConstPtr visitedLinkParent = linkToVisit.back().parent;\n LinkIndex visitedLinkIndex = visitedLink->getIndex();\n linkToVisit.pop_back();\n\n for(unsigned int neigh_i=0; neigh_i < this->getNrOfNeighbors(visitedLinkIndex); neigh_i++ )\n {\n \/\/ add to the stack all the neighbors, except for parent link\n \/\/ (if the visited link is the base one, add all the neighbors)\n \/\/ the visited link is already in the Traversal, so we can use it\n \/\/ to check for its parent\n Neighbor neighb = this->getNeighbor(visitedLinkIndex,neigh_i);\n if( visitedLinkParent == 0 || neighb.neighborLink != visitedLinkParent->getIndex() )\n {\n addLinkToTraversal(*this,traversal,traversalFirstEmptySlot,neighb.neighborLink,\n neighb.neighborJoint,visitedLink->getIndex(),linkToVisit);\n }\n }\n }\n\n return true;\n}\n\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_main.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n\n#include <windows.h>\n#include <shellapi.h>\n\n#include <algorithm>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/win_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/views\/uninstall_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/helper.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/shell_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/winsock_init.h\"\n#include \"net\/socket\/ssl_client_socket_nss_factory.h\"\n#include \"views\/focus\/accelerator_handler.h\"\n#include \"views\/window\/window.h\"\n\nvoid DidEndMainMessageLoop() {\n OleUninitialize();\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n DWORD len = ::GetEnvironmentVariableW(\n ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0);\n metrics->RecordBreakpadRegistration((len == 0));\n metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n if (base::win::GetVersion() < base::win::VERSION_XP) {\n \/\/ Display a warning message if the user is running chrome on Windows 2000.\n const std::wstring text =\n l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n win_util::MessageBox(NULL, text, caption,\n MB_OK | MB_ICONWARNING | MB_TOPMOST);\n }\n}\n\nint AskForUninstallConfirmation() {\n int ret = ResultCodes::NORMAL_EXIT;\n views::Window::CreateChromeWindow(NULL, gfx::Rect(),\n new UninstallView(ret))->Show();\n views::AcceleratorHandler accelerator_handler;\n MessageLoopForUI::current()->Run(&accelerator_handler);\n return ret;\n}\n\nvoid ShowCloseBrowserFirstMessageBox() {\n const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n}\n\nint DoUninstallTasks(bool chrome_still_running) {\n \/\/ We want to show a warning to user (and exit) if Chrome is already running\n \/\/ *before* we show the uninstall confirmation dialog box. But while the\n \/\/ uninstall confirmation dialog is up, user might start Chrome, so we\n \/\/ check once again after user acknowledges Uninstall dialog.\n if (chrome_still_running) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n int ret = AskForUninstallConfirmation();\n if (Upgrade::IsBrowserAlreadyRunning()) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n\n if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {\n \/\/ The following actions are just best effort.\n VLOG(1) << \"Executing uninstall actions\";\n if (!FirstRun::RemoveSentinel())\n VLOG(1) << \"Failed to delete sentinel file.\";\n \/\/ We want to remove user level shortcuts and we only care about the ones\n \/\/ created by us and not by the installer so |alternate| is false.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER,\n false))\n VLOG(1) << \"Failed to delete desktop shortcut.\";\n if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,\n ShellUtil::CURRENT_USER))\n VLOG(1) << \"Failed to delete quick launch shortcut.\";\n }\n return ret;\n}\n\n\/\/ Prepares the localized strings that are going to be displayed to\n\/\/ the user if the browser process dies. These strings are stored in the\n\/\/ environment block so they are accessible in the early stages of the\n\/\/ chrome executable's lifetime.\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n \/\/ Clear this var so child processes don't show the dialog by default.\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->UnSetVar(env_vars::kShowRestart);\n\n \/\/ For non-interactive tests we don't restart on crash.\n if (env->HasVar(env_vars::kHeadless))\n return;\n\n \/\/ If the known command-line test options are used we don't create the\n \/\/ environment block which means we don't get the restart dialog.\n if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||\n parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||\n parsed_command_line.HasSwitch(switches::kNoErrorDialogs))\n return;\n\n \/\/ The encoding we use for the info is \"title|context|direction\" where\n \/\/ direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending\n \/\/ on the current locale.\n string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));\n dlg_strings.push_back('|');\n string16 adjusted_string(\n l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));\n base::i18n::AdjustStringForLocaleDirection(&adjusted_string);\n dlg_strings.append(adjusted_string);\n dlg_strings.push_back('|');\n dlg_strings.append(ASCIIToUTF16(\n base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));\n\n env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));\n}\n\n\/\/ This method handles the --hide-icons and --show-icons command line options\n\/\/ for chrome that get triggered by Windows from registry entries\n\/\/ HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons\n\/\/ functionality so we just ask the users if they want to uninstall Chrome.\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n if (parsed_command_line.HasSwitch(switches::kHideIcons)) {\n std::wstring cp_applet;\n base::win::Version version = base::win::GetVersion();\n if (version >= base::win::VERSION_VISTA) {\n cp_applet.assign(L\"Programs and Features\"); \/\/ Windows Vista and later.\n } else if (version >= base::win::VERSION_XP) {\n cp_applet.assign(L\"Add\/Remove Programs\"); \/\/ Windows XP.\n } else {\n return ResultCodes::UNSUPPORTED_PARAM; \/\/ Not supported\n }\n\n const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,\n cp_applet);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;\n if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))\n ShellExecute(NULL, NULL, L\"appwiz.cpl\", NULL, NULL, SW_SHOWNORMAL);\n return ResultCodes::NORMAL_EXIT; \/\/ Exit as we are not launching browser.\n }\n \/\/ We don't hide icons so we shouldn't do anything special to show them\n return ResultCodes::UNSUPPORTED_PARAM;\n}\n\n\/\/ Check if there is any machine level Chrome installed on the current\n\/\/ machine. If yes and the current Chrome process is user level, we do not\n\/\/ allow the user level Chrome to run. So we notify the user and uninstall\n\/\/ user level Chrome.\nbool CheckMachineLevelInstall() {\n \/\/ TODO(tommi): Check if using the default distribution is always the right\n \/\/ thing to do.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(dist,\n true));\n if (version.get()) {\n FilePath exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n std::wstring exe = exe_path.value();\n FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));\n if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {\n const std::wstring text =\n l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist));\n CommandLine uninstall_cmd(uninstall_path);\n if (!uninstall_cmd.GetProgram().value().empty()) {\n uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall);\n uninstall_cmd.AppendSwitch(\n installer_util::switches::kDoNotRemoveSharedItems);\n base::LaunchApp(uninstall_cmd, false, false, NULL);\n }\n return true;\n }\n }\n return false;\n}\n\n\/\/ BrowserMainPartsWin ---------------------------------------------------------\n\nclass BrowserMainPartsWin : public BrowserMainParts {\n public:\n explicit BrowserMainPartsWin(const MainFunctionParams& parameters)\n : BrowserMainParts(parameters) {}\n\n protected:\n virtual void PreEarlyInitialization() {\n \/\/ Initialize Winsock.\n net::EnsureWinsockInit();\n }\n\n virtual void PreMainMessageLoopStart() {\n OleInitialize(NULL);\n\n \/\/ If we're running tests (ui_task is non-null), then the ResourceBundle\n \/\/ has already been initialized.\n if (!parameters().ui_task) {\n \/\/ Override the configured locale with the user's preferred UI language.\n l10n_util::OverrideLocaleWithUILanguageList();\n }\n }\n\n private:\n virtual void InitializeSSL() {\n \/\/ Use NSS for SSL by default.\n \/\/ Because of a build system issue (http:\/\/crbug.com\/43461), the default\n \/\/ client socket factory uses SChannel (the system SSL library) for SSL by\n \/\/ default on Windows.\n if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) {\n net::ClientSocketFactory::SetSSLClientSocketFactory(\n net::SSLClientSocketNSSFactory);\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n }\n }\n};\n\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsWin(parameters);\n}\n<commit_msg>Use SChannel for Windows.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_main.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n\n#include <windows.h>\n#include <shellapi.h>\n\n#include <algorithm>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/win_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/views\/uninstall_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/helper.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/shell_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/winsock_init.h\"\n#include \"net\/socket\/ssl_client_socket_nss_factory.h\"\n#include \"views\/focus\/accelerator_handler.h\"\n#include \"views\/window\/window.h\"\n\nvoid DidEndMainMessageLoop() {\n OleUninitialize();\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n DWORD len = ::GetEnvironmentVariableW(\n ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0);\n metrics->RecordBreakpadRegistration((len == 0));\n metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n if (base::win::GetVersion() < base::win::VERSION_XP) {\n \/\/ Display a warning message if the user is running chrome on Windows 2000.\n const std::wstring text =\n l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n win_util::MessageBox(NULL, text, caption,\n MB_OK | MB_ICONWARNING | MB_TOPMOST);\n }\n}\n\nint AskForUninstallConfirmation() {\n int ret = ResultCodes::NORMAL_EXIT;\n views::Window::CreateChromeWindow(NULL, gfx::Rect(),\n new UninstallView(ret))->Show();\n views::AcceleratorHandler accelerator_handler;\n MessageLoopForUI::current()->Run(&accelerator_handler);\n return ret;\n}\n\nvoid ShowCloseBrowserFirstMessageBox() {\n const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n}\n\nint DoUninstallTasks(bool chrome_still_running) {\n \/\/ We want to show a warning to user (and exit) if Chrome is already running\n \/\/ *before* we show the uninstall confirmation dialog box. But while the\n \/\/ uninstall confirmation dialog is up, user might start Chrome, so we\n \/\/ check once again after user acknowledges Uninstall dialog.\n if (chrome_still_running) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n int ret = AskForUninstallConfirmation();\n if (Upgrade::IsBrowserAlreadyRunning()) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n\n if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {\n \/\/ The following actions are just best effort.\n VLOG(1) << \"Executing uninstall actions\";\n if (!FirstRun::RemoveSentinel())\n VLOG(1) << \"Failed to delete sentinel file.\";\n \/\/ We want to remove user level shortcuts and we only care about the ones\n \/\/ created by us and not by the installer so |alternate| is false.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER,\n false))\n VLOG(1) << \"Failed to delete desktop shortcut.\";\n if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,\n ShellUtil::CURRENT_USER))\n VLOG(1) << \"Failed to delete quick launch shortcut.\";\n }\n return ret;\n}\n\n\/\/ Prepares the localized strings that are going to be displayed to\n\/\/ the user if the browser process dies. These strings are stored in the\n\/\/ environment block so they are accessible in the early stages of the\n\/\/ chrome executable's lifetime.\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n \/\/ Clear this var so child processes don't show the dialog by default.\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->UnSetVar(env_vars::kShowRestart);\n\n \/\/ For non-interactive tests we don't restart on crash.\n if (env->HasVar(env_vars::kHeadless))\n return;\n\n \/\/ If the known command-line test options are used we don't create the\n \/\/ environment block which means we don't get the restart dialog.\n if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||\n parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||\n parsed_command_line.HasSwitch(switches::kNoErrorDialogs))\n return;\n\n \/\/ The encoding we use for the info is \"title|context|direction\" where\n \/\/ direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending\n \/\/ on the current locale.\n string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));\n dlg_strings.push_back('|');\n string16 adjusted_string(\n l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));\n base::i18n::AdjustStringForLocaleDirection(&adjusted_string);\n dlg_strings.append(adjusted_string);\n dlg_strings.push_back('|');\n dlg_strings.append(ASCIIToUTF16(\n base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));\n\n env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));\n}\n\n\/\/ This method handles the --hide-icons and --show-icons command line options\n\/\/ for chrome that get triggered by Windows from registry entries\n\/\/ HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons\n\/\/ functionality so we just ask the users if they want to uninstall Chrome.\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n if (parsed_command_line.HasSwitch(switches::kHideIcons)) {\n std::wstring cp_applet;\n base::win::Version version = base::win::GetVersion();\n if (version >= base::win::VERSION_VISTA) {\n cp_applet.assign(L\"Programs and Features\"); \/\/ Windows Vista and later.\n } else if (version >= base::win::VERSION_XP) {\n cp_applet.assign(L\"Add\/Remove Programs\"); \/\/ Windows XP.\n } else {\n return ResultCodes::UNSUPPORTED_PARAM; \/\/ Not supported\n }\n\n const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,\n cp_applet);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;\n if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))\n ShellExecute(NULL, NULL, L\"appwiz.cpl\", NULL, NULL, SW_SHOWNORMAL);\n return ResultCodes::NORMAL_EXIT; \/\/ Exit as we are not launching browser.\n }\n \/\/ We don't hide icons so we shouldn't do anything special to show them\n return ResultCodes::UNSUPPORTED_PARAM;\n}\n\n\/\/ Check if there is any machine level Chrome installed on the current\n\/\/ machine. If yes and the current Chrome process is user level, we do not\n\/\/ allow the user level Chrome to run. So we notify the user and uninstall\n\/\/ user level Chrome.\nbool CheckMachineLevelInstall() {\n \/\/ TODO(tommi): Check if using the default distribution is always the right\n \/\/ thing to do.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(dist,\n true));\n if (version.get()) {\n FilePath exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n std::wstring exe = exe_path.value();\n FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));\n if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {\n const std::wstring text =\n l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist));\n CommandLine uninstall_cmd(uninstall_path);\n if (!uninstall_cmd.GetProgram().value().empty()) {\n uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall);\n uninstall_cmd.AppendSwitch(\n installer_util::switches::kDoNotRemoveSharedItems);\n base::LaunchApp(uninstall_cmd, false, false, NULL);\n }\n return true;\n }\n }\n return false;\n}\n\n\/\/ BrowserMainPartsWin ---------------------------------------------------------\n\nclass BrowserMainPartsWin : public BrowserMainParts {\n public:\n explicit BrowserMainPartsWin(const MainFunctionParams& parameters)\n : BrowserMainParts(parameters) {}\n\n protected:\n virtual void PreEarlyInitialization() {\n \/\/ Initialize Winsock.\n net::EnsureWinsockInit();\n }\n\n virtual void PreMainMessageLoopStart() {\n OleInitialize(NULL);\n\n \/\/ If we're running tests (ui_task is non-null), then the ResourceBundle\n \/\/ has already been initialized.\n if (!parameters().ui_task) {\n \/\/ Override the configured locale with the user's preferred UI language.\n l10n_util::OverrideLocaleWithUILanguageList();\n }\n }\n\n private:\n virtual void InitializeSSL() {\n \/\/ Use NSS for SSL by default.\n \/\/ Because of a build system issue (http:\/\/crbug.com\/43461), the default\n \/\/ client socket factory uses SChannel (the system SSL library) for SSL by\n \/\/ default on Windows.\n\n \/\/ Disabling this temporarily to test out if NSS is causing heap corruption.\n#if 0\n if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) {\n net::ClientSocketFactory::SetSSLClientSocketFactory(\n net::SSLClientSocketNSSFactory);\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n }\n#endif\n }\n};\n\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsWin(parameters);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/includes\/linux\/InotifyEventLoop.h\"\n\nInotifyEventLoop::InotifyEventLoop(\n int inotifyInstance,\n InotifyService *inotifyService\n) :\n mInotifyInstance(inotifyInstance),\n mInotifyService(inotifyService)\n{\n mStarted = !pthread_create(\n &mEventLoop,\n NULL,\n [](void *eventLoop)->void * {\n ((InotifyEventLoop *)eventLoop)->work();\n return NULL;\n },\n (void *)this\n );\n if (mStarted) { mLoopingSemaphore.wait(); }\n}\n\nbool InotifyEventLoop::isLooping() {\n return mStarted;\n}\n\nvoid InotifyEventLoop::work() {\n char buffer[BUFFER_SIZE];\n inotify_event *event = NULL;\n unsigned int bytesRead, position = 0;\n bool isDirectoryEvent = false, isDirectoryRemoval = false;\n InotifyService *inotifyService = mInotifyService;\n InotifyRenameEvent renameEvent;\n renameEvent.isStarted = false;\n\n auto create = [&event, &isDirectoryEvent, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n if (isDirectoryEvent) {\n inotifyService->createDirectory(event->wd, strdup(event->name));\n } else {\n inotifyService->create(event->wd, strdup(event->name));\n }\n };\n\n auto modify = [&event, &isDirectoryEvent, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n inotifyService->modify(event->wd, strdup(event->name));\n };\n\n auto remove = [&event, &isDirectoryRemoval, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n if (isDirectoryRemoval) {\n inotifyService->removeDirectory(event->wd);\n } else {\n inotifyService->remove(event->wd, strdup(event->name));\n }\n };\n\n auto renameStart = [&event, &isDirectoryEvent, &renameEvent]() {\n renameEvent.cookie = event->cookie;\n renameEvent.isDirectory = isDirectoryEvent;\n renameEvent.name = event->name;\n renameEvent.wd = event->wd;\n renameEvent.isStarted = true;\n };\n\n auto renameEnd = [&create, &event, &inotifyService, &isDirectoryEvent, &renameEvent]() {\n if (!renameEvent.isStarted) {\n create();\n return;\n }\n\n if (renameEvent.cookie != event->cookie) {\n if (renameEvent.isDirectory) {\n inotifyService->removeDirectory(renameEvent.wd);\n } else {\n inotifyService->remove(renameEvent.wd, renameEvent.name);\n }\n create();\n } else {\n if (renameEvent.isDirectory) {\n inotifyService->renameDirectory(renameEvent.wd, renameEvent.name, event->wd, event->name);\n } else {\n inotifyService->rename(renameEvent.wd, renameEvent.name, event->wd, event->name);\n }\n }\n renameEvent.isStarted = false;\n };\n\n mLoopingSemaphore.signal();\n while((bytesRead = read(mInotifyInstance, &buffer, BUFFER_SIZE)) > 0) {\n std::lock_guard<std::mutex> syncWithDestructor(mMutex);\n do {\n event = (struct inotify_event *)(buffer + position);\n\n if (renameEvent.isStarted && event->cookie != renameEvent.cookie) {\n renameEnd();\n }\n\n isDirectoryRemoval = event->mask & (uint32_t)(IN_IGNORED | IN_DELETE_SELF);\n isDirectoryEvent = event->mask & (uint32_t)(IN_ISDIR);\n\n if (!isDirectoryRemoval && *event->name <= 31) {\n continue;\n }\n\n if (event->mask & (uint32_t)(IN_ATTRIB | IN_MODIFY)) {\n modify();\n } else if (event->mask & (uint32_t)IN_CREATE) {\n create();\n } else if (event->mask & (uint32_t)(IN_DELETE | IN_DELETE_SELF)) {\n remove();\n } else if (event->mask & (uint32_t)IN_MOVED_TO) {\n if (event->cookie == 0) {\n create();\n continue;\n }\n\n renameEnd();\n } else if (event->mask & (uint32_t)IN_MOVED_FROM) {\n if (event->cookie == 0) {\n remove();\n continue;\n }\n\n renameStart();\n } else if (event->mask & (uint32_t)IN_MOVE_SELF) {\n inotifyService->remove(event->wd, strdup(event->name));\n inotifyService->removeDirectory(event->wd);\n }\n } while((position += sizeof(struct inotify_event) + event->len) < bytesRead);\n if (renameEvent.isStarted) {\n remove();\n renameEvent.isStarted = false;\n }\n position = 0;\n }\n mStarted = false;\n}\n\nInotifyEventLoop::~InotifyEventLoop() {\n if (!mStarted) {\n return;\n }\n\n {\n std::lock_guard<std::mutex> syncWithWork(mMutex);\n pthread_cancel(mEventLoop);\n }\n\n pthread_join(mEventLoop, NULL);\n}\n<commit_msg>Fix memory leaks caused by unneeded strdup()<commit_after>#include \"..\/..\/includes\/linux\/InotifyEventLoop.h\"\n\nInotifyEventLoop::InotifyEventLoop(\n int inotifyInstance,\n InotifyService *inotifyService\n) :\n mInotifyInstance(inotifyInstance),\n mInotifyService(inotifyService)\n{\n mStarted = !pthread_create(\n &mEventLoop,\n NULL,\n [](void *eventLoop)->void * {\n ((InotifyEventLoop *)eventLoop)->work();\n return NULL;\n },\n (void *)this\n );\n if (mStarted) { mLoopingSemaphore.wait(); }\n}\n\nbool InotifyEventLoop::isLooping() {\n return mStarted;\n}\n\nvoid InotifyEventLoop::work() {\n char buffer[BUFFER_SIZE];\n inotify_event *event = NULL;\n unsigned int bytesRead, position = 0;\n bool isDirectoryEvent = false, isDirectoryRemoval = false;\n InotifyService *inotifyService = mInotifyService;\n InotifyRenameEvent renameEvent;\n renameEvent.isStarted = false;\n\n auto create = [&event, &isDirectoryEvent, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n if (isDirectoryEvent) {\n inotifyService->createDirectory(event->wd, event->name);\n } else {\n inotifyService->create(event->wd, event->name);\n }\n };\n\n auto modify = [&event, &isDirectoryEvent, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n inotifyService->modify(event->wd, event->name);\n };\n\n auto remove = [&event, &isDirectoryRemoval, &inotifyService]() {\n if (event == NULL) {\n return;\n }\n\n if (isDirectoryRemoval) {\n inotifyService->removeDirectory(event->wd);\n } else {\n inotifyService->remove(event->wd, event->name);\n }\n };\n\n auto renameStart = [&event, &isDirectoryEvent, &renameEvent]() {\n renameEvent.cookie = event->cookie;\n renameEvent.isDirectory = isDirectoryEvent;\n renameEvent.name = event->name;\n renameEvent.wd = event->wd;\n renameEvent.isStarted = true;\n };\n\n auto renameEnd = [&create, &event, &inotifyService, &isDirectoryEvent, &renameEvent]() {\n if (!renameEvent.isStarted) {\n create();\n return;\n }\n\n if (renameEvent.cookie != event->cookie) {\n if (renameEvent.isDirectory) {\n inotifyService->removeDirectory(renameEvent.wd);\n } else {\n inotifyService->remove(renameEvent.wd, renameEvent.name);\n }\n create();\n } else {\n if (renameEvent.isDirectory) {\n inotifyService->renameDirectory(renameEvent.wd, renameEvent.name, event->wd, event->name);\n } else {\n inotifyService->rename(renameEvent.wd, renameEvent.name, event->wd, event->name);\n }\n }\n renameEvent.isStarted = false;\n };\n\n mLoopingSemaphore.signal();\n while((bytesRead = read(mInotifyInstance, &buffer, BUFFER_SIZE)) > 0) {\n std::lock_guard<std::mutex> syncWithDestructor(mMutex);\n do {\n event = (struct inotify_event *)(buffer + position);\n\n if (renameEvent.isStarted && event->cookie != renameEvent.cookie) {\n renameEnd();\n }\n\n isDirectoryRemoval = event->mask & (uint32_t)(IN_IGNORED | IN_DELETE_SELF);\n isDirectoryEvent = event->mask & (uint32_t)(IN_ISDIR);\n\n if (!isDirectoryRemoval && *event->name <= 31) {\n continue;\n }\n\n if (event->mask & (uint32_t)(IN_ATTRIB | IN_MODIFY)) {\n modify();\n } else if (event->mask & (uint32_t)IN_CREATE) {\n create();\n } else if (event->mask & (uint32_t)(IN_DELETE | IN_DELETE_SELF)) {\n remove();\n } else if (event->mask & (uint32_t)IN_MOVED_TO) {\n if (event->cookie == 0) {\n create();\n continue;\n }\n\n renameEnd();\n } else if (event->mask & (uint32_t)IN_MOVED_FROM) {\n if (event->cookie == 0) {\n remove();\n continue;\n }\n\n renameStart();\n } else if (event->mask & (uint32_t)IN_MOVE_SELF) {\n inotifyService->remove(event->wd, event->name);\n inotifyService->removeDirectory(event->wd);\n }\n } while((position += sizeof(struct inotify_event) + event->len) < bytesRead);\n if (renameEvent.isStarted) {\n remove();\n renameEvent.isStarted = false;\n }\n position = 0;\n }\n mStarted = false;\n}\n\nInotifyEventLoop::~InotifyEventLoop() {\n if (!mStarted) {\n return;\n }\n\n {\n std::lock_guard<std::mutex> syncWithWork(mMutex);\n pthread_cancel(mEventLoop);\n }\n\n pthread_join(mEventLoop, NULL);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Lisa Hsu\n * Nathan Binkert\n *\/\n\n#include <string>\n\n#include \"base\/trace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"kern\/base_kernel_stats.hh\"\n#include \"kern\/tru64\/tru64_syscalls.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace Stats;\n\nnamespace Kernel {\n\nStatistics::Statistics(System *system)\n : iplLast(0), iplLastTick(0)\n{\n}\n\nvoid\nStatistics::regStats(const string &_name)\n{\n myname = _name;\n\n _arm\n .name(name() + \".inst.arm\")\n .desc(\"number of arm instructions executed\")\n ;\n\n _quiesce\n .name(name() + \".inst.quiesce\")\n .desc(\"number of quiesce instructions executed\")\n ;\n\n _iplCount\n .init(32)\n .name(name() + \".ipl_count\")\n .desc(\"number of times we switched to this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplGood\n .init(32)\n .name(name() + \".ipl_good\")\n .desc(\"number of times we switched to this ipl from a different ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplTicks\n .init(32)\n .name(name() + \".ipl_ticks\")\n .desc(\"number of cycles we spent at this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplUsed\n .name(name() + \".ipl_used\")\n .desc(\"fraction of swpipl calls that actually changed the ipl\")\n .flags(total | nozero | nonan)\n ;\n\n _iplUsed = _iplGood \/ _iplCount;\n\n _syscall\n .init(SystemCalls<Tru64>::Number)\n .name(name() + \".syscall\")\n .desc(\"number of syscalls executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {\n const char *str = \"Please fix me\";\/\/SystemCalls<Tru64>::name(i);\n if (str) {\n _syscall.subname(i, str);\n }\n }\n}\n\nvoid\nStatistics::swpipl(int ipl)\n{\n assert(ipl >= 0 && ipl <= 0x1f && \"invalid IPL\\n\");\n\n _iplCount[ipl]++;\n\n if (ipl == iplLast)\n return;\n\n _iplGood[ipl]++;\n _iplTicks[iplLast] += curTick - iplLastTick;\n iplLastTick = curTick;\n iplLast = ipl;\n}\n\nvoid\nStatistics::serialize(ostream &os)\n{\n SERIALIZE_SCALAR(iplLast);\n SERIALIZE_SCALAR(iplLastTick);\n}\n\nvoid\nStatistics::unserialize(Checkpoint *cp, const string §ion)\n{\n UNSERIALIZE_SCALAR(iplLast);\n UNSERIALIZE_SCALAR(iplLastTick);\n}\n\n\/* end namespace Kernel *\/ }\n<commit_msg>A cleaner hack.<commit_after>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Lisa Hsu\n * Nathan Binkert\n *\/\n\n#include <string>\n\n#include \"base\/trace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"kern\/base_kernel_stats.hh\"\n#include \"kern\/tru64\/tru64_syscalls.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace Stats;\n\nnamespace Kernel {\n\nStatistics::Statistics(System *system)\n : iplLast(0), iplLastTick(0)\n{\n}\n\nvoid\nStatistics::regStats(const string &_name)\n{\n myname = _name;\n\n _arm\n .name(name() + \".inst.arm\")\n .desc(\"number of arm instructions executed\")\n ;\n\n _quiesce\n .name(name() + \".inst.quiesce\")\n .desc(\"number of quiesce instructions executed\")\n ;\n\n _iplCount\n .init(32)\n .name(name() + \".ipl_count\")\n .desc(\"number of times we switched to this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplGood\n .init(32)\n .name(name() + \".ipl_good\")\n .desc(\"number of times we switched to this ipl from a different ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplTicks\n .init(32)\n .name(name() + \".ipl_ticks\")\n .desc(\"number of cycles we spent at this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplUsed\n .name(name() + \".ipl_used\")\n .desc(\"fraction of swpipl calls that actually changed the ipl\")\n .flags(total | nozero | nonan)\n ;\n\n _iplUsed = _iplGood \/ _iplCount;\n\n _syscall\n .init(SystemCalls<Tru64>::Number)\n .name(name() + \".syscall\")\n .desc(\"number of syscalls executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n \/\/@todo This needs to get the names of syscalls from an appropriate place.\n#if 0\n for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {\n const char *str = SystemCalls<Tru64>::name(i);\n if (str) {\n _syscall.subname(i, str);\n }\n }\n#endif\n}\n\nvoid\nStatistics::swpipl(int ipl)\n{\n assert(ipl >= 0 && ipl <= 0x1f && \"invalid IPL\\n\");\n\n _iplCount[ipl]++;\n\n if (ipl == iplLast)\n return;\n\n _iplGood[ipl]++;\n _iplTicks[iplLast] += curTick - iplLastTick;\n iplLastTick = curTick;\n iplLast = ipl;\n}\n\nvoid\nStatistics::serialize(ostream &os)\n{\n SERIALIZE_SCALAR(iplLast);\n SERIALIZE_SCALAR(iplLastTick);\n}\n\nvoid\nStatistics::unserialize(Checkpoint *cp, const string §ion)\n{\n UNSERIALIZE_SCALAR(iplLast);\n UNSERIALIZE_SCALAR(iplLastTick);\n}\n\n\/* end namespace Kernel *\/ }\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/epoll.h>\n#include <sys\/errno.h>\n#include <sys\/time.h>\n#include <unistd.h>\n\n#include <common\/buffer.h>\n\n#include <event\/event_callback.h>\n#include <event\/event_poll.h>\n\n#define\tEPOLL_EVENT_COUNT\t128\n\nstruct EventPollState {\n\tint ep_;\n};\n\nEventPoll::EventPoll(void)\n: log_(\"\/event\/poll\"),\n read_poll_(),\n write_poll_(),\n state_(new EventPollState())\n{\n\tstate_->ep_ = epoll_create(EPOLL_EVENT_COUNT);\n\tASSERT(state_->ep_ != -1);\n}\n\nEventPoll::~EventPoll()\n{\n\tASSERT(read_poll_.empty());\n\tASSERT(write_poll_.empty());\n\n\tif (state_ != NULL) {\n\t\tif (state_->ep_ != -1) {\n\t\t\tclose(state_->ep_);\n\t\t\tstate_->ep_ = -1;\n\t\t}\n\t\tdelete state_;\n\t\tstate_ = NULL;\n\t}\n}\n\nAction *\nEventPoll::poll(const Type& type, int fd, EventCallback *cb)\n{\n\tASSERT(fd != -1);\n\n\tEventPoll::PollHandler *poll_handler;\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) == read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\teev.events = EPOLLIN | (unique ? 0 : EPOLLOUT);\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) == write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\teev.events = EPOLLOUT | (unique ? 0 : EPOLLIN);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_ADD : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not add event to epoll.\";\n\tASSERT(rv == 0);\n\tASSERT(poll_handler->action_ == NULL);\n\tpoll_handler->callback_ = cb;\n\tAction *a = new EventPoll::PollAction(this, type, fd);\n\treturn (a);\n}\n\nvoid\nEventPoll::cancel(const Type& type, int fd)\n{\n\tEventPoll::PollHandler *poll_handler;\n\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) != read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\tread_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLOUT;\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) != write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\twrite_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLIN;\n\t\tbreak;\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_DEL : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not delete event from epoll.\";\n\tASSERT(rv == 0);\n}\n\nvoid\nEventPoll::wait(int ms)\n{\n\tstruct timespec ts;\n\n\tts.tv_sec = ms \/ 1000;\n\tts.tv_nsec = (ms % 1000) * 1000000;\n\n\tif (idle()) {\n\t\tif (ms != -1) {\n\t\t\tint rv;\n\n\t\t\trv = nanosleep(&ts, NULL);\n\t\t\tASSERT(rv != -1);\n\t\t}\n\t\treturn;\n\t}\n\n\tstruct epoll_event eev[EPOLL_EVENT_COUNT];\n\tint evcnt = ::epoll_wait(state_->ep_, eev, EPOLL_EVENT_COUNT, ms);\n\tif (evcnt == -1) {\n\t\tif (errno == EINTR) {\n\t\t\tINFO(log_) << \"Received interrupt, ceasing polling until stop handlers have run.\";\n\t\t\treturn;\n\t\t}\n\t\tHALT(log_) << \"Could not poll epoll.\";\n\t}\n\n\tint i;\n\tfor (i = 0; i < evcnt; i++) {\n\t\tstruct epoll_event *ev = &eev[i];\n\t\tEventPoll::PollHandler *poll_handler;\n\t\tif ((ev->events & EPOLLIN) != 0) {\n\t\t\tASSERT(read_poll_.find(ev->data.fd) != read_poll_.end());\n\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLOUT) != 0) {\n\t\t\tASSERT(write_poll_.find(ev->data.fd) != write_poll_.end());\n\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLIN) == 0 && (ev->events & EPOLLOUT) == 0) {\n\t\t\tif (read_poll_.find(ev->data.fd) != read_poll_.end()) {\n\t\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\t} else if (write_poll_.find(ev->data.fd) != write_poll_.end()) {\n\t\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\t} else {\n\t\t\t\tHALT(log_) << \"Unexpected poll fd.\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLERR) != 0) {\n\t\t\t\tpoll_handler->callback(Event::Error);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLHUP) != 0) {\n\t\t\t\tpoll_handler->callback(Event::EOS);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tHALT(log_) << \"Unexpected poll events: \" << ev->events;\n\t\t}\n\t}\n}\n<commit_msg>Ignore hangup on write polls.<commit_after>#include <sys\/types.h>\n#include <sys\/epoll.h>\n#include <sys\/errno.h>\n#include <sys\/time.h>\n#include <unistd.h>\n\n#include <common\/buffer.h>\n\n#include <event\/event_callback.h>\n#include <event\/event_poll.h>\n\n#define\tEPOLL_EVENT_COUNT\t128\n\nstruct EventPollState {\n\tint ep_;\n};\n\nEventPoll::EventPoll(void)\n: log_(\"\/event\/poll\"),\n read_poll_(),\n write_poll_(),\n state_(new EventPollState())\n{\n\tstate_->ep_ = epoll_create(EPOLL_EVENT_COUNT);\n\tASSERT(state_->ep_ != -1);\n}\n\nEventPoll::~EventPoll()\n{\n\tASSERT(read_poll_.empty());\n\tASSERT(write_poll_.empty());\n\n\tif (state_ != NULL) {\n\t\tif (state_->ep_ != -1) {\n\t\t\tclose(state_->ep_);\n\t\t\tstate_->ep_ = -1;\n\t\t}\n\t\tdelete state_;\n\t\tstate_ = NULL;\n\t}\n}\n\nAction *\nEventPoll::poll(const Type& type, int fd, EventCallback *cb)\n{\n\tASSERT(fd != -1);\n\n\tEventPoll::PollHandler *poll_handler;\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) == read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\teev.events = EPOLLIN | (unique ? 0 : EPOLLOUT);\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) == write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\teev.events = EPOLLOUT | (unique ? 0 : EPOLLIN);\n\t\tbreak;\n\tdefault:\n\t\tNOTREACHED();\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_ADD : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not add event to epoll.\";\n\tASSERT(rv == 0);\n\tASSERT(poll_handler->action_ == NULL);\n\tpoll_handler->callback_ = cb;\n\tAction *a = new EventPoll::PollAction(this, type, fd);\n\treturn (a);\n}\n\nvoid\nEventPoll::cancel(const Type& type, int fd)\n{\n\tEventPoll::PollHandler *poll_handler;\n\n\tstruct epoll_event eev;\n\tbool unique = true;\n\teev.data.fd = fd;\n\tswitch (type) {\n\tcase EventPoll::Readable:\n\t\tASSERT(read_poll_.find(fd) != read_poll_.end());\n\t\tunique = write_poll_.find(fd) == write_poll_.end();\n\t\tpoll_handler = &read_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\tread_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLOUT;\n\t\tbreak;\n\tcase EventPoll::Writable:\n\t\tASSERT(write_poll_.find(fd) != write_poll_.end());\n\t\tunique = read_poll_.find(fd) == read_poll_.end();\n\t\tpoll_handler = &write_poll_[fd];\n\t\tpoll_handler->cancel();\n\t\twrite_poll_.erase(fd);\n\t\teev.events = unique ? 0 : EPOLLIN;\n\t\tbreak;\n\t}\n\tint rv = ::epoll_ctl(state_->ep_, unique ? EPOLL_CTL_DEL : EPOLL_CTL_MOD, fd, &eev);\n\tif (rv == -1)\n\t\tHALT(log_) << \"Could not delete event from epoll.\";\n\tASSERT(rv == 0);\n}\n\nvoid\nEventPoll::wait(int ms)\n{\n\tstruct timespec ts;\n\n\tts.tv_sec = ms \/ 1000;\n\tts.tv_nsec = (ms % 1000) * 1000000;\n\n\tif (idle()) {\n\t\tif (ms != -1) {\n\t\t\tint rv;\n\n\t\t\trv = nanosleep(&ts, NULL);\n\t\t\tASSERT(rv != -1);\n\t\t}\n\t\treturn;\n\t}\n\n\tstruct epoll_event eev[EPOLL_EVENT_COUNT];\n\tint evcnt = ::epoll_wait(state_->ep_, eev, EPOLL_EVENT_COUNT, ms);\n\tif (evcnt == -1) {\n\t\tif (errno == EINTR) {\n\t\t\tINFO(log_) << \"Received interrupt, ceasing polling until stop handlers have run.\";\n\t\t\treturn;\n\t\t}\n\t\tHALT(log_) << \"Could not poll epoll.\";\n\t}\n\n\tint i;\n\tfor (i = 0; i < evcnt; i++) {\n\t\tstruct epoll_event *ev = &eev[i];\n\t\tEventPoll::PollHandler *poll_handler;\n\t\tif ((ev->events & EPOLLIN) != 0) {\n\t\t\tASSERT(read_poll_.find(ev->data.fd) != read_poll_.end());\n\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLOUT) != 0) {\n\t\t\tASSERT(write_poll_.find(ev->data.fd) != write_poll_.end());\n\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\t\t\tpoll_handler->callback(Event::Done);\n\t\t}\n\n\t\tif ((ev->events & EPOLLIN) == 0 && (ev->events & EPOLLOUT) == 0) {\n\t\t\tif (read_poll_.find(ev->data.fd) != read_poll_.end()) {\n\t\t\t\tpoll_handler = &read_poll_[ev->data.fd];\n\t\t\t} else if (write_poll_.find(ev->data.fd) != write_poll_.end()) {\n\t\t\t\tpoll_handler = &write_poll_[ev->data.fd];\n\n\t\t\t\tif ((ev->events & (EPOLLERR | EPOLLHUP)) == EPOLLHUP) {\n\t\t\t\t\tDEBUG(log_) << \"Got EPOLLHUP on write poll.\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tHALT(log_) << \"Unexpected poll fd.\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLERR) != 0) {\n\t\t\t\tpoll_handler->callback(Event::Error);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ((ev->events & EPOLLHUP) != 0) {\n\t\t\t\tpoll_handler->callback(Event::EOS);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tHALT(log_) << \"Unexpected poll events: \" << ev->events;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <omp.h>\n#include \"dispar.h\"\n#include \"tournament.h\"\n\ntemplate<typename T>\nmatrix createRandomTournamentPool(T container,\n const size_t nbGroup,\n const size_t poolSize) {\n\n std::bitset<1> bs(container.size());\n matrix pools(nbGroup);\n\n size_t cardinality = 0;\n\n for (auto&& pool: pools) {\n pool.reserve(poolSize);\n }\n\n while(cardinality < nbGroup * poolSize) {\n \/\/int v = rand.nextInt(container.size());\n int v = 0;\n if(!bs[v]) {\n bs[v];\n cardinality++;\n pools[cardinality \/ poolSize][cardinality % poolSize] = v;\n }\n }\n\n return pools;\n}\n\ntemplate<typename T, typename Alloc, template <typename, typename> class TT>\nstd::vector<int> selection(const size_t targetSize,\n TT<T, Alloc> container,\n std::function<void (const T&, const T&)> comparator) {\n\n const size_t nbGroup = 1;\n const size_t poolSize = 5;\n\n std::vector<int> selected_keys;\n selected_keys.reserve(targetSize);\n\n matrix pools = createRandomTournamentPool(container, nbGroup, poolSize);\n\n #pragma omp parallel for\n for (int i = 0; i < pools.size(); i++) {\n selected_keys.push_back(tournament<TT, T>(container, pools[i], comparator));\n }\n\n return selected_keys;\n}\n\n<commit_msg>Use vector of bool instead of bitset that need to know their size at compile time<commit_after>#include <omp.h>\n#include \"dispar.h\"\n#include \"tournament.h\"\n\ntemplate<typename T>\nmatrix createRandomTournamentPool(T container,\n const size_t nbGroup,\n const size_t poolSize) {\n\n std::vector<bool> bs(size);\n matrix pools(nbGroup);\n\n size_t cardinality = 0;\n\n for (auto&& pool: pools) {\n pool.reserve(poolSize);\n }\n\n while(cardinality < nbGroup * poolSize) {\n \/\/int v = rand.random_int(offset, size - 1);\n int v = 0;\n if(!bs[v]) {\n bs[v];\n bs[v] = true;\n pools[cardinality \/ poolSize][cardinality % poolSize] = v;\n cardinality++;\n }\n }\n\n return pools;\n}\n\ntemplate<typename T, typename Alloc, template <typename, typename> class TT>\nstd::vector<int> selection(const size_t targetSize,\n TT<T, Alloc> container,\n std::function<void (const T&, const T&)> comparator) {\n\n const size_t nbGroup = 1;\n const size_t poolSize = 5;\n\n std::vector<int> selected_keys;\n selected_keys.reserve(targetSize);\n\n matrix pools = createRandomTournamentPool(container, nbGroup, poolSize);\n\n #pragma omp parallel for\n for (int i = 0; i < pools.size(); i++) {\n selected_keys.push_back(tournament<TT, T>(container, pools[i], comparator));\n }\n\n return selected_keys;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"MonitorStore.h\"\n#include \"common\/Clock.h\"\n\n#include \"config.h\"\n\n#define DOUT_SUBSYS mon\n#undef dout_prefix\n#define dout_prefix _prefix(dir)\nstatic ostream& _prefix(const string& dir) {\n return *_dout << dbeginl << \"store(\" << dir << \") \";\n}\n\n\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <sys\/file.h>\n\nint MonitorStore::mount()\n{\n char t[1024];\n\n dout(1) << \"mount\" << dendl;\n \/\/ verify dir exists\n DIR *d = ::opendir(dir.c_str());\n if (!d) {\n derr(1) << \"basedir \" << dir << \" dne\" << dendl;\n return -ENOENT;\n }\n ::closedir(d);\n\n \/\/ open lockfile\n snprintf(t, sizeof(t), \"%s\/lock\", dir.c_str());\n lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);\n if (lock_fd < 0)\n return -errno;\n struct flock l;\n memset(&l, 0, sizeof(l));\n l.l_type = F_WRLCK;\n l.l_whence = SEEK_SET;\n l.l_start = 0;\n l.l_len = 0;\n int r = ::fcntl(lock_fd, F_SETLK, &l);\n if (r < 0) {\n derr(0) << \"failed to lock \" << t << \", is another cmon still running?\" << dendl;\n return -errno;\n }\n\n if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '\/') {\n \/\/ combine it with the cwd, in case fuse screws things up (i.e. fakefuse)\n string old = dir;\n char cwd[1024];\n getcwd(cwd, sizeof(cwd));\n dir = cwd;\n dir += \"\/\";\n dir += old;\n }\n return 0;\n}\n\nint MonitorStore::umount()\n{\n ::close(lock_fd);\n return 0;\n}\n\nint MonitorStore::mkfs()\n{\n dout(1) << \"mkfs\" << dendl;\n\n char cmd[1024];\n snprintf(cmd, sizeof(cmd), \"test -d %s && \/bin\/rm -r %s ; mkdir -p %s\", dir.c_str(), dir.c_str(), dir.c_str());\n dout(1) << cmd << dendl;\n int r = system(cmd);\n return r;\n}\n\nvoid MonitorStore::sync()\n{\n dout(10) << \"sync\" << dendl;\n ::sync();\n}\n\nversion_t MonitorStore::get_int(const char *a, const char *b)\n{\n char fn[1024];\n if (b)\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n else\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n \n FILE *f = ::fopen(fn, \"r\");\n if (!f) \n return 0;\n \n char buf[20];\n ::fgets(buf, 20, f);\n ::fclose(f);\n \n version_t val = atoi(buf);\n \n if (b) {\n dout(15) << \"get_int \" << a << \"\/\" << b << \" = \" << val << dendl;\n } else {\n dout(15) << \"get_int \" << a << \" = \" << val << dendl;\n }\n return val;\n}\n\n\nvoid MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)\n{\n char fn[1024];\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n if (b) {\n ::mkdir(fn, 0755);\n dout(15) << \"set_int \" << a << \"\/\" << b << \" = \" << val << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"set_int \" << a << \" = \" << val << dendl;\n }\n \n char vs[30];\n snprintf(vs, sizeof(vs), \"%lld\\n\", (unsigned long long)val);\n\n char tfn[1024];\n snprintf(tfn, sizeof(tfn), \"%s.new\", fn);\n\n int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);\n assert(fd >= 0);\n ::write(fd, vs, strlen(vs));\n if (sync)\n ::fsync(fd);\n ::close(fd);\n ::rename(tfn, fn);\n}\n\n\n\/\/ ----------------------------------------\n\/\/ buffers\n\nbool MonitorStore::exists_bl_ss(const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n dout(15) << \"exists_bl \" << a << \"\/\" << b << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"exists_bl \" << a << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n \n struct stat st;\n int r = ::stat(fn, &st);\n \/\/char buf[80];\n \/\/dout(15) << \"exists_bl stat \" << fn << \" r=\" << r << \" errno \" << errno << \" \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n return r == 0;\n}\n\nint MonitorStore::erase_ss(const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n dout(15) << \"erase_ss \" << a << \"\/\" << b << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"erase_ss \" << a << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n return ::unlink(fn);\n}\n\nint MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n \n int fd = ::open(fn, O_RDONLY);\n if (fd < 0) {\n if (b) {\n dout(15) << \"get_bl \" << a << \"\/\" << b << \" DNE\" << dendl;\n } else {\n dout(15) << \"get_bl \" << a << \" DNE\" << dendl;\n }\n return 0;\n }\n\n \/\/ get size\n struct stat st;\n int rc = ::fstat(fd, &st);\n assert(rc == 0);\n __int32_t len = st.st_size;\n \n \/\/ read buffer\n bl.clear();\n bufferptr bp(len);\n int off = 0;\n while (off < len) {\n dout(20) << \"reading at off \" << off << \" of \" << len << dendl;\n int r = ::read(fd, bp.c_str()+off, len-off);\n if (r < 0) {\n char buf[80];\n derr(0) << \"errno on read \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n }\n assert(r>0);\n off += r;\n }\n bl.append(bp);\n ::close(fd);\n\n if (b) {\n dout(15) << \"get_bl \" << a << \"\/\" << b << \" = \" << bl.length() << \" bytes\" << dendl;\n } else {\n dout(15) << \"get_bl \" << a << \" = \" << bl.length() << \" bytes\" << dendl;\n }\n\n return len;\n}\n\nint MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)\n{\n char fn[1024];\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n if (b) {\n ::mkdir(fn, 0755);\n dout(15) << \"put_bl \" << a << \"\/\" << b << \" = \" << bl.length() << \" bytes\" << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"put_bl \" << a << \" = \" << bl.length() << \" bytes\" << dendl;\n }\n \n char tfn[1024];\n int err = 0;\n int fd;\n if (append) {\n fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);\n } else {\n snprintf(tfn, sizeof(tfn), \"%s.new\", fn);\n fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);\n }\n assert(fd >= 0);\n \n \/\/ write data\n for (list<bufferptr>::const_iterator it = bl.buffers().begin();\n it != bl.buffers().end();\n it++) {\n int r = ::write(fd, it->c_str(), it->length());\n if (r != (int)it->length())\n derr(0) << \"put_bl_ss ::write() returned \" << r << \" not \" << it->length() << dendl;\n if (r < 0) {\n char buf[80];\n derr(0) << \"put_bl_ss ::write() errored out, errno is \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n err = -errno;\n break;\n }\n }\n\n if (sync && !err)\n ::fsync(fd);\n ::close(fd);\n if (!append && !err) {\n ::rename(tfn, fn);\n }\n\n assert(!err); \/\/ for now\n\n return err;\n}\n\n<commit_msg>mkmonfs: rm -rf, so that we kill 0600 admin_keyring.bin<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"MonitorStore.h\"\n#include \"common\/Clock.h\"\n\n#include \"config.h\"\n\n#define DOUT_SUBSYS mon\n#undef dout_prefix\n#define dout_prefix _prefix(dir)\nstatic ostream& _prefix(const string& dir) {\n return *_dout << dbeginl << \"store(\" << dir << \") \";\n}\n\n\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <sys\/file.h>\n\nint MonitorStore::mount()\n{\n char t[1024];\n\n dout(1) << \"mount\" << dendl;\n \/\/ verify dir exists\n DIR *d = ::opendir(dir.c_str());\n if (!d) {\n derr(1) << \"basedir \" << dir << \" dne\" << dendl;\n return -ENOENT;\n }\n ::closedir(d);\n\n \/\/ open lockfile\n snprintf(t, sizeof(t), \"%s\/lock\", dir.c_str());\n lock_fd = ::open(t, O_CREAT|O_RDWR, 0600);\n if (lock_fd < 0)\n return -errno;\n struct flock l;\n memset(&l, 0, sizeof(l));\n l.l_type = F_WRLCK;\n l.l_whence = SEEK_SET;\n l.l_start = 0;\n l.l_len = 0;\n int r = ::fcntl(lock_fd, F_SETLK, &l);\n if (r < 0) {\n derr(0) << \"failed to lock \" << t << \", is another cmon still running?\" << dendl;\n return -errno;\n }\n\n if (g_conf.chdir && g_conf.chdir[0] && dir[0] != '\/') {\n \/\/ combine it with the cwd, in case fuse screws things up (i.e. fakefuse)\n string old = dir;\n char cwd[1024];\n getcwd(cwd, sizeof(cwd));\n dir = cwd;\n dir += \"\/\";\n dir += old;\n }\n return 0;\n}\n\nint MonitorStore::umount()\n{\n ::close(lock_fd);\n return 0;\n}\n\nint MonitorStore::mkfs()\n{\n dout(1) << \"mkfs\" << dendl;\n\n char cmd[1024];\n snprintf(cmd, sizeof(cmd), \"test -d %s && \/bin\/rm -rf %s ; mkdir -p %s\", dir.c_str(), dir.c_str(), dir.c_str());\n dout(1) << cmd << dendl;\n int r = system(cmd);\n return r;\n}\n\nvoid MonitorStore::sync()\n{\n dout(10) << \"sync\" << dendl;\n ::sync();\n}\n\nversion_t MonitorStore::get_int(const char *a, const char *b)\n{\n char fn[1024];\n if (b)\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n else\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n \n FILE *f = ::fopen(fn, \"r\");\n if (!f) \n return 0;\n \n char buf[20];\n ::fgets(buf, 20, f);\n ::fclose(f);\n \n version_t val = atoi(buf);\n \n if (b) {\n dout(15) << \"get_int \" << a << \"\/\" << b << \" = \" << val << dendl;\n } else {\n dout(15) << \"get_int \" << a << \" = \" << val << dendl;\n }\n return val;\n}\n\n\nvoid MonitorStore::put_int(version_t val, const char *a, const char *b, bool sync)\n{\n char fn[1024];\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n if (b) {\n ::mkdir(fn, 0755);\n dout(15) << \"set_int \" << a << \"\/\" << b << \" = \" << val << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"set_int \" << a << \" = \" << val << dendl;\n }\n \n char vs[30];\n snprintf(vs, sizeof(vs), \"%lld\\n\", (unsigned long long)val);\n\n char tfn[1024];\n snprintf(tfn, sizeof(tfn), \"%s.new\", fn);\n\n int fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);\n assert(fd >= 0);\n ::write(fd, vs, strlen(vs));\n if (sync)\n ::fsync(fd);\n ::close(fd);\n ::rename(tfn, fn);\n}\n\n\n\/\/ ----------------------------------------\n\/\/ buffers\n\nbool MonitorStore::exists_bl_ss(const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n dout(15) << \"exists_bl \" << a << \"\/\" << b << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"exists_bl \" << a << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n \n struct stat st;\n int r = ::stat(fn, &st);\n \/\/char buf[80];\n \/\/dout(15) << \"exists_bl stat \" << fn << \" r=\" << r << \" errno \" << errno << \" \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n return r == 0;\n}\n\nint MonitorStore::erase_ss(const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n dout(15) << \"erase_ss \" << a << \"\/\" << b << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"erase_ss \" << a << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n return ::unlink(fn);\n}\n\nint MonitorStore::get_bl_ss(bufferlist& bl, const char *a, const char *b)\n{\n char fn[1024];\n if (b) {\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n }\n \n int fd = ::open(fn, O_RDONLY);\n if (fd < 0) {\n if (b) {\n dout(15) << \"get_bl \" << a << \"\/\" << b << \" DNE\" << dendl;\n } else {\n dout(15) << \"get_bl \" << a << \" DNE\" << dendl;\n }\n return 0;\n }\n\n \/\/ get size\n struct stat st;\n int rc = ::fstat(fd, &st);\n assert(rc == 0);\n __int32_t len = st.st_size;\n \n \/\/ read buffer\n bl.clear();\n bufferptr bp(len);\n int off = 0;\n while (off < len) {\n dout(20) << \"reading at off \" << off << \" of \" << len << dendl;\n int r = ::read(fd, bp.c_str()+off, len-off);\n if (r < 0) {\n char buf[80];\n derr(0) << \"errno on read \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n }\n assert(r>0);\n off += r;\n }\n bl.append(bp);\n ::close(fd);\n\n if (b) {\n dout(15) << \"get_bl \" << a << \"\/\" << b << \" = \" << bl.length() << \" bytes\" << dendl;\n } else {\n dout(15) << \"get_bl \" << a << \" = \" << bl.length() << \" bytes\" << dendl;\n }\n\n return len;\n}\n\nint MonitorStore::write_bl_ss(bufferlist& bl, const char *a, const char *b, bool append, bool sync)\n{\n char fn[1024];\n snprintf(fn, sizeof(fn), \"%s\/%s\", dir.c_str(), a);\n if (b) {\n ::mkdir(fn, 0755);\n dout(15) << \"put_bl \" << a << \"\/\" << b << \" = \" << bl.length() << \" bytes\" << dendl;\n snprintf(fn, sizeof(fn), \"%s\/%s\/%s\", dir.c_str(), a, b);\n } else {\n dout(15) << \"put_bl \" << a << \" = \" << bl.length() << \" bytes\" << dendl;\n }\n \n char tfn[1024];\n int err = 0;\n int fd;\n if (append) {\n fd = ::open(fn, O_WRONLY|O_CREAT|O_APPEND, 0644);\n } else {\n snprintf(tfn, sizeof(tfn), \"%s.new\", fn);\n fd = ::open(tfn, O_WRONLY|O_CREAT, 0644);\n }\n assert(fd >= 0);\n \n \/\/ write data\n for (list<bufferptr>::const_iterator it = bl.buffers().begin();\n it != bl.buffers().end();\n it++) {\n int r = ::write(fd, it->c_str(), it->length());\n if (r != (int)it->length())\n derr(0) << \"put_bl_ss ::write() returned \" << r << \" not \" << it->length() << dendl;\n if (r < 0) {\n char buf[80];\n derr(0) << \"put_bl_ss ::write() errored out, errno is \" << strerror_r(errno, buf, sizeof(buf)) << dendl;\n err = -errno;\n break;\n }\n }\n\n if (sync && !err)\n ::fsync(fd);\n ::close(fd);\n if (!append && !err) {\n ::rename(tfn, fn);\n }\n\n assert(!err); \/\/ for now\n\n return err;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Hardware.h\"\n\n#include <unistd.h>\n#include <stdlib.h>\n#include <iostream>\n\nint main() {\n\tHardware hand;\n\thand.poise();\n\n\tstressTest(&hand, 10);\n}\n\nvoid stressTest(Hardware *hardware, int trials) {\n\tfor (int i=0; i<trials; i++) {\n\t\tif (executeScaledAngles(hardware,rand()*2.0-1,rand()*2.0-1,rand()*2.0-1)) {\n\t\t\tstd::cout << \"Move executed.\\n\";\n\t\t} else {\n\t\t\tstd::cout << \"Move fail-safed.\\n\";\n\t\t} usleep(3000000);\n\t}\n}\n\nbool executeScaledAngles(Hardware *hardware, int i, int j, int k) {\n\tdouble iAng = Hardware::map(i, -1, 1, I_MIN_ANG, I_MAX_ANG);\n\tdouble jAng = Hardware::map(j, -1, 1, J_MIN_ANG, J_MAX_ANG);\n\tdouble kAng = Hardware::map(k, -1, 1, K_MIN_ANG, K_MAX_ANG);\n\n\treturn hardware->setJoints(iAng, jAng, kAng);\n}\n<commit_msg>reorder for c++ sadness<commit_after>#include \"Hardware.h\"\n\n#include <unistd.h>\n#include <stdlib.h>\n#include <iostream>\n\nbool executeScaledAngles(Hardware *hardware, int i, int j, int k) {\n\tdouble iAng = Hardware::map(i, -1, 1, I_MIN_ANG, I_MAX_ANG);\n\tdouble jAng = Hardware::map(j, -1, 1, J_MIN_ANG, J_MAX_ANG);\n\tdouble kAng = Hardware::map(k, -1, 1, K_MIN_ANG, K_MAX_ANG);\n\n\treturn hardware->setJoints(iAng, jAng, kAng);\n}\n\nvoid stressTest(Hardware *hardware, int trials) {\n\tfor (int i=0; i<trials; i++) {\n\t\tif (executeScaledAngles(hardware,rand()*2.0-1,rand()*2.0-1,rand()*2.0-1)) {\n\t\t\tstd::cout << \"Move executed.\\n\";\n\t\t} else {\n\t\t\tstd::cout << \"Move fail-safed.\\n\";\n\t\t} usleep(3000000);\n\t}\n}\n\nint main() {\n\tHardware hand;\n\thand.poise();\n\n\tstressTest(&hand, 10);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008-2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Tests for the top plugins to catch regressions in our plugin host code, as\n\/\/ well as in the out of process code. Currently this tests:\n\/\/ Flash\n\/\/ Real\n\/\/ QuickTime\n\/\/ Windows Media Player\n\/\/ -this includes both WMP plugins. npdsplay.dll is the older one that\n\/\/ comes with XP. np-mswmp.dll can be downloaded from Microsoft and\n\/\/ needs SP2 or Vista.\n\n#include <windows.h>\n#include <shellapi.h>\n#include <shlobj.h>\n#include <comutil.h>\n\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n\n#include <string>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/registry.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"third_party\/npapi\/bindings\/npapi.h\"\n#include \"webkit\/default_plugin\/plugin_impl.h\"\n#include \"webkit\/glue\/plugins\/plugin_constants_win.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\nconst int kShortWaitTimeout = 10 * 1000;\nconst int kLongWaitTimeout = 30 * 1000;\n\nclass PluginTest : public UITest {\n protected:\n virtual void SetUp() {\n const testing::TestInfo* const test_info =\n testing::UnitTest::GetInstance()->current_test_info();\n if (strcmp(test_info->name(), \"MediaPlayerNew\") == 0) {\n \/\/ The installer adds our process names to the registry key below. Since\n \/\/ the installer might not have run on this machine, add it manually.\n RegKey regkey;\n if (regkey.Open(HKEY_LOCAL_MACHINE,\n L\"Software\\\\Microsoft\\\\MediaPlayer\\\\ShimInclusionList\",\n KEY_WRITE)) {\n regkey.CreateKey(L\"CHROME.EXE\", KEY_READ);\n }\n } else if (strcmp(test_info->name(), \"MediaPlayerOld\") == 0) {\n \/\/ When testing the old WMP plugin, we need to force Chrome to not load\n \/\/ the new plugin.\n launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);\n } else if (strcmp(test_info->name(), \"FlashSecurity\") == 0) {\n launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,\n L\"security_tests.dll\");\n }\n\n UITest::SetUp();\n }\n\n void TestPlugin(const std::wstring& test_case,\n int timeout,\n bool mock_http) {\n GURL url = GetTestUrl(test_case, mock_http);\n NavigateToURL(url);\n WaitForFinish(timeout, mock_http);\n }\n\n \/\/ Generate the URL for testing a particular test.\n \/\/ HTML for the tests is all located in test_directory\\plugin\\<testcase>\n \/\/ Set |mock_http| to true to use mock HTTP server.\n GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {\n if (mock_http)\n return URLRequestMockHTTPJob::GetMockUrl(L\"plugin\/\" + test_case);\n\n FilePath path;\n PathService::Get(chrome::DIR_TEST_DATA, &path);\n path = path.AppendASCII(\"plugin\");\n path = path.Append(FilePath::FromWStringHack(test_case));\n return net::FilePathToFileURL(path);\n }\n\n \/\/ Waits for the test case to finish.\n void WaitForFinish(const int wait_time, bool mock_http) {\n const int kSleepTime = 500; \/\/ 2 times per second\n const int kMaxIntervals = wait_time \/ kSleepTime;\n\n GURL url = GetTestUrl(L\"done\", mock_http);\n scoped_refptr<TabProxy> tab(GetActiveTab());\n\n std::string done_str;\n for (int i = 0; i < kMaxIntervals; ++i) {\n Sleep(kSleepTime);\n\n \/\/ The webpage being tested has javascript which sets a cookie\n \/\/ which signals completion of the test.\n std::string cookieName = kTestCompleteCookie;\n tab->GetCookieByName(url, cookieName, &done_str);\n if (!done_str.empty())\n break;\n }\n\n EXPECT_EQ(kTestCompleteSuccess, done_str);\n }\n};\n\nTEST_F(PluginTest, Quicktime) {\n TestPlugin(L\"quicktime.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, MediaPlayerNew) {\n TestPlugin(L\"wmp_new.html\", kShortWaitTimeout, false);\n}\n\n\/\/ http:\/\/crbug.com\/4809\nTEST_F(PluginTest, DISABLED_MediaPlayerOld) {\n TestPlugin(L\"wmp_old.html\", kLongWaitTimeout, false);\n}\n\nTEST_F(PluginTest, Real) {\n TestPlugin(L\"real.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, Flash) {\n TestPlugin(L\"flash.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, FlashOctetStream) {\n TestPlugin(L\"flash-octet-stream.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, FlashSecurity) {\n TestPlugin(L\"flash.html\", kShortWaitTimeout, false);\n}\n\n\/\/ http:\/\/crbug.com\/16114\nTEST_F(PluginTest, FlashLayoutWhilePainting) {\n TestPlugin(L\"flash-layout-while-painting.html\", kShortWaitTimeout, true);\n}\n\n\/\/ http:\/\/crbug.com\/8690\nTEST_F(PluginTest, DISABLED_Java) {\n TestPlugin(L\"Java.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, Silverlight) {\n TestPlugin(L\"silverlight.html\", kShortWaitTimeout, false);\n}\n<commit_msg>Disable flaky plugin tests. These keep causing bogus automatic tree closures.<commit_after>\/\/ Copyright 2008-2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Tests for the top plugins to catch regressions in our plugin host code, as\n\/\/ well as in the out of process code. Currently this tests:\n\/\/ Flash\n\/\/ Real\n\/\/ QuickTime\n\/\/ Windows Media Player\n\/\/ -this includes both WMP plugins. npdsplay.dll is the older one that\n\/\/ comes with XP. np-mswmp.dll can be downloaded from Microsoft and\n\/\/ needs SP2 or Vista.\n\n#include <windows.h>\n#include <shellapi.h>\n#include <shlobj.h>\n#include <comutil.h>\n\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n\n#include <string>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/registry.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"third_party\/npapi\/bindings\/npapi.h\"\n#include \"webkit\/default_plugin\/plugin_impl.h\"\n#include \"webkit\/glue\/plugins\/plugin_constants_win.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\nconst int kShortWaitTimeout = 10 * 1000;\nconst int kLongWaitTimeout = 30 * 1000;\n\nclass PluginTest : public UITest {\n protected:\n virtual void SetUp() {\n const testing::TestInfo* const test_info =\n testing::UnitTest::GetInstance()->current_test_info();\n if (strcmp(test_info->name(), \"MediaPlayerNew\") == 0) {\n \/\/ The installer adds our process names to the registry key below. Since\n \/\/ the installer might not have run on this machine, add it manually.\n RegKey regkey;\n if (regkey.Open(HKEY_LOCAL_MACHINE,\n L\"Software\\\\Microsoft\\\\MediaPlayer\\\\ShimInclusionList\",\n KEY_WRITE)) {\n regkey.CreateKey(L\"CHROME.EXE\", KEY_READ);\n }\n } else if (strcmp(test_info->name(), \"MediaPlayerOld\") == 0) {\n \/\/ When testing the old WMP plugin, we need to force Chrome to not load\n \/\/ the new plugin.\n launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);\n } else if (strcmp(test_info->name(), \"FlashSecurity\") == 0) {\n launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,\n L\"security_tests.dll\");\n }\n\n UITest::SetUp();\n }\n\n void TestPlugin(const std::wstring& test_case,\n int timeout,\n bool mock_http) {\n GURL url = GetTestUrl(test_case, mock_http);\n NavigateToURL(url);\n WaitForFinish(timeout, mock_http);\n }\n\n \/\/ Generate the URL for testing a particular test.\n \/\/ HTML for the tests is all located in test_directory\\plugin\\<testcase>\n \/\/ Set |mock_http| to true to use mock HTTP server.\n GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {\n if (mock_http)\n return URLRequestMockHTTPJob::GetMockUrl(L\"plugin\/\" + test_case);\n\n FilePath path;\n PathService::Get(chrome::DIR_TEST_DATA, &path);\n path = path.AppendASCII(\"plugin\");\n path = path.Append(FilePath::FromWStringHack(test_case));\n return net::FilePathToFileURL(path);\n }\n\n \/\/ Waits for the test case to finish.\n void WaitForFinish(const int wait_time, bool mock_http) {\n const int kSleepTime = 500; \/\/ 2 times per second\n const int kMaxIntervals = wait_time \/ kSleepTime;\n\n GURL url = GetTestUrl(L\"done\", mock_http);\n scoped_refptr<TabProxy> tab(GetActiveTab());\n\n std::string done_str;\n for (int i = 0; i < kMaxIntervals; ++i) {\n Sleep(kSleepTime);\n\n \/\/ The webpage being tested has javascript which sets a cookie\n \/\/ which signals completion of the test.\n std::string cookieName = kTestCompleteCookie;\n tab->GetCookieByName(url, cookieName, &done_str);\n if (!done_str.empty())\n break;\n }\n\n EXPECT_EQ(kTestCompleteSuccess, done_str);\n }\n};\n\nTEST_F(PluginTest, Quicktime) {\n TestPlugin(L\"quicktime.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, MediaPlayerNew) {\n TestPlugin(L\"wmp_new.html\", kShortWaitTimeout, false);\n}\n\n\/\/ http:\/\/crbug.com\/4809\nTEST_F(PluginTest, DISABLED_MediaPlayerOld) {\n TestPlugin(L\"wmp_old.html\", kLongWaitTimeout, false);\n}\n\nTEST_F(PluginTest, Real) {\n TestPlugin(L\"real.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, Flash) {\n TestPlugin(L\"flash.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, FlashOctetStream) {\n TestPlugin(L\"flash-octet-stream.html\", kShortWaitTimeout, false);\n}\n\nTEST_F(PluginTest, FlashSecurity) {\n TestPlugin(L\"flash.html\", kShortWaitTimeout, false);\n}\n\n\/\/ http:\/\/crbug.com\/16114\n\/\/ Disabled for http:\/\/crbug.com\/21538\nTEST_F(PluginTest, DISABLED_FlashLayoutWhilePainting) {\n TestPlugin(L\"flash-layout-while-painting.html\", kShortWaitTimeout, true);\n}\n\n\/\/ http:\/\/crbug.com\/8690\nTEST_F(PluginTest, DISABLED_Java) {\n TestPlugin(L\"Java.html\", kShortWaitTimeout, false);\n}\n\n\/\/ Disabled for http:\/\/crbug.com\/22666\nTEST_F(PluginTest, DISABLED_Silverlight) {\n TestPlugin(L\"silverlight.html\", kShortWaitTimeout, false);\n}\n<|endoftext|>"} {"text":"<commit_before>#undef _WIN32_WINNT\n#define _WIN32_WINNT 0x0601\n\n#undef WINVER\n#define WINVER 0x0601\n\n#include \"keyboard-layout-observer.h\"\n\n#include <string>\n#include <windows.h>\n\nusing namespace v8;\n\nstd::string ToUTF8(const std::wstring& string) {\n if (string.length() < 1) {\n return std::string();\n }\n\n \/\/ NB: In the pathological case, each character could expand up\n \/\/ to 4 bytes in UTF8.\n int cbLen = (string.length()+1) * sizeof(char) * 4;\n char* buf = new char[cbLen];\n int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);\n buf[retLen] = 0;\n\n std::string ret;\n ret.assign(buf);\n return ret;\n}\n\nstd::wstring ToWString(const std::string& string) {\n if (string.length() < 1) {\n return std::wstring();\n }\n\n \/\/ NB: If you got really unlucky, every character could be a two-wchar_t\n \/\/ surrogate pair\n int cchLen = (string.length()+1) * 2;\n wchar_t* buf = new wchar_t[cchLen];\n int retLen = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), strlen(string.c_str()), buf, cchLen);\n buf[retLen] = 0;\n\n std::wstring ret;\n ret.assign(buf);\n return ret;\n}\n\nvoid KeyboardLayoutObserver::Init(Handle<Object> target) {\n NanScope();\n Local<FunctionTemplate> newTemplate = NanNew<FunctionTemplate>(KeyboardLayoutObserver::New);\n newTemplate->SetClassName(NanNew<String>(\"KeyboardLayoutObserver\"));\n newTemplate->InstanceTemplate()->SetInternalFieldCount(1);\n Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();\n\n NODE_SET_METHOD(proto, \"getCurrentKeyboardLayout\", KeyboardLayoutObserver::GetCurrentKeyboardLayout);\n NODE_SET_METHOD(proto, \"getInstalledKeyboardLayouts\", KeyboardLayoutObserver::GetInstalledKeyboardLayouts);\n target->Set(NanNew<String>(\"KeyboardLayoutObserver\"), newTemplate->GetFunction());\n}\n\nNODE_MODULE(keyboard_layout_observer, KeyboardLayoutObserver::Init)\n\nNAN_METHOD(KeyboardLayoutObserver::New) {\n NanScope();\n\n Local<Function> callbackHandle = args[0].As<Function>();\n NanCallback *callback = new NanCallback(callbackHandle);\n\n KeyboardLayoutObserver *observer = new KeyboardLayoutObserver(callback);\n observer->Wrap(args.This());\n NanReturnUndefined();\n}\n\nKeyboardLayoutObserver::KeyboardLayoutObserver(NanCallback *callback) : callback(callback) {\n}\n\nKeyboardLayoutObserver::~KeyboardLayoutObserver() {\n delete callback;\n};\n\nvoid KeyboardLayoutObserver::HandleKeyboardLayoutChanged() {\n}\n\nNAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLayout) {\n NanScope();\n\n HKL layout = GetKeyboardLayout(0 \/* Current Thread *\/);\n\n wchar_t buf[LOCALE_NAME_MAX_LENGTH];\n std::wstring wstr;\n LCIDToLocaleName(MAKELCID((UINT)layout, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);\n wstr.assign(buf);\n\n std::string str = ToUTF8(wstr);\n NanReturnValue(NanNew<String>(str.data(), str.size()));\n}\n\nNAN_METHOD(KeyboardLayoutObserver::GetInstalledKeyboardLayouts) {\n NanScope();\n\n int layoutCount = GetKeyboardLayoutList(0, NULL);\n HKL* layouts = new HKL[layoutCount];\n GetKeyboardLayoutList(layoutCount, layouts);\n\n Local<Array> result = NanNew<Array>(layoutCount);\n wchar_t buf[LOCALE_NAME_MAX_LENGTH];\n\n for (int i=0; i < layoutCount; i++) {\n std::wstring wstr;\n LCIDToLocaleName(MAKELCID((UINT)layouts[i], SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);\n wstr.assign(buf);\n\n std::string str = ToUTF8(wstr);\n result->Set(i, NanNew<String>(str.data(), str.size()));\n }\n\n delete[] layouts;\n NanReturnValue(result);\n}\n<commit_msg>Fix up Windows to match<commit_after>#undef _WIN32_WINNT\n#define _WIN32_WINNT 0x0601\n\n#undef WINVER\n#define WINVER 0x0601\n\n#include \"keyboard-layout-observer.h\"\n\n#include <string>\n#include <windows.h>\n\nusing namespace v8;\n\nstd::string ToUTF8(const std::wstring& string) {\n if (string.length() < 1) {\n return std::string();\n }\n\n \/\/ NB: In the pathological case, each character could expand up\n \/\/ to 4 bytes in UTF8.\n int cbLen = (string.length()+1) * sizeof(char) * 4;\n char* buf = new char[cbLen];\n int retLen = WideCharToMultiByte(CP_UTF8, 0, string.c_str(), string.length(), buf, cbLen, NULL, NULL);\n buf[retLen] = 0;\n\n std::string ret;\n ret.assign(buf);\n return ret;\n}\n\nstd::wstring ToWString(const std::string& string) {\n if (string.length() < 1) {\n return std::wstring();\n }\n\n \/\/ NB: If you got really unlucky, every character could be a two-wchar_t\n \/\/ surrogate pair\n int cchLen = (string.length()+1) * 2;\n wchar_t* buf = new wchar_t[cchLen];\n int retLen = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), strlen(string.c_str()), buf, cchLen);\n buf[retLen] = 0;\n\n std::wstring ret;\n ret.assign(buf);\n return ret;\n}\n\nvoid KeyboardLayoutObserver::Init(Handle<Object> target) {\n NanScope();\n Local<FunctionTemplate> newTemplate = NanNew<FunctionTemplate>(KeyboardLayoutObserver::New);\n newTemplate->SetClassName(NanNew<String>(\"KeyboardLayoutObserver\"));\n newTemplate->InstanceTemplate()->SetInternalFieldCount(1);\n Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate();\n\n NODE_SET_METHOD(proto, \"getCurrentKeyboardLayout\", KeyboardLayoutObserver::GetCurrentKeyboardLayout);\n NODE_SET_METHOD(proto, \"getCurrentKeyboardLanguage\", KeyboardLayoutObserver::GetCurrentKeyboardLanguage);\n NODE_SET_METHOD(proto, \"getInstalledKeyboardLanguages\", KeyboardLayoutObserver::GetInstalledKeyboardLanguages);\n target->Set(NanNew<String>(\"KeyboardLayoutObserver\"), newTemplate->GetFunction());\n}\n\nNODE_MODULE(keyboard_layout_observer, KeyboardLayoutObserver::Init)\n\nNAN_METHOD(KeyboardLayoutObserver::New) {\n NanScope();\n\n Local<Function> callbackHandle = args[0].As<Function>();\n NanCallback *callback = new NanCallback(callbackHandle);\n\n KeyboardLayoutObserver *observer = new KeyboardLayoutObserver(callback);\n observer->Wrap(args.This());\n NanReturnUndefined();\n}\n\nKeyboardLayoutObserver::KeyboardLayoutObserver(NanCallback *callback) : callback(callback) {\n}\n\nKeyboardLayoutObserver::~KeyboardLayoutObserver() {\n delete callback;\n};\n\nvoid KeyboardLayoutObserver::HandleKeyboardLayoutChanged() {\n}\n\nNAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLayout) {\n NanScope();\n\n char layoutName[KL_NAMELENGTH];\n if (::GetKeyboardLayoutName(layoutName))\n NanReturnValue(NanNew(layoutName));\n else\n NanReturnValue(NanUndefined());\n}\n\nNAN_METHOD(KeyboardLayoutObserver::GetCurrentKeyboardLanguage) {\n NanScope();\n\n HKL layout = GetKeyboardLayout(0 \/* Current Thread *\/);\n\n wchar_t buf[LOCALE_NAME_MAX_LENGTH];\n std::wstring wstr;\n LCIDToLocaleName(MAKELCID((UINT)layout, SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);\n wstr.assign(buf);\n\n std::string str = ToUTF8(wstr);\n NanReturnValue(NanNew<String>(str.data(), str.size()));\n}\n\nNAN_METHOD(KeyboardLayoutObserver::GetInstalledKeyboardLanguages) {\n NanScope();\n\n int layoutCount = GetKeyboardLayoutList(0, NULL);\n HKL* layouts = new HKL[layoutCount];\n GetKeyboardLayoutList(layoutCount, layouts);\n\n Local<Array> result = NanNew<Array>(layoutCount);\n wchar_t buf[LOCALE_NAME_MAX_LENGTH];\n\n for (int i=0; i < layoutCount; i++) {\n std::wstring wstr;\n LCIDToLocaleName(MAKELCID((UINT)layouts[i], SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);\n wstr.assign(buf);\n\n std::string str = ToUTF8(wstr);\n result->Set(i, NanNew<String>(str.data(), str.size()));\n }\n\n delete[] layouts;\n NanReturnValue(result);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * endpoints_grammar_test.cpp\n *\n * Created on: Jan 28, 2016\n * Author: zmij\n *\/\n\n#include <gtest\/gtest.h>\n#include <grammar\/grammar_parse_test.hpp>\n#include <wire\/core\/grammar\/endpoint_parse.hpp>\n\nnamespace wire {\nnamespace core {\nnamespace test {\n\nGRAMMAR_TEST(grammar::parse::inet_interface_grammar, InetInterface,\n ::testing::Values(\n \"eth0[v4]\", \"lo[V6]\"\n ),\n ::testing::Values(\n \"eth1\", \"tun0[v5]\", \"lo[\"\n )\n);\n\ntemplate < typename InputIterator >\nusing tcp_data_grammar =\n grammar::parse::ip_endpoint_data_grammar<\n InputIterator, detail::tcp_endpoint_data >;\n\nGRAMMAR_TEST(tcp_data_grammar, TCPEndpoint,\n ::testing::Values(\n \"127.0.0.1:10\",\n \"255.255.2.1:80\",\n \"10.0.254.1:3232\",\n \"192.0.2.33:7678\",\n \"google.com:8888\",\n \"www.mail.ru:765\",\n \"0.0.0.0:0\",\n \"[::8]:5678\",\n \"127.0.0.1:786\",\n \"[ffaa:1234::aadd:255.255.255.0]:567\",\n \"eth0[v4]:0\",\n \"lo[v6]:0\"\n ),\n ::testing::Values(\n \"255.255.2.1:456789\",\n \"10.0.254.1:-78\",\n \"192.0.2.33:bla\",\n \"127.0.0.256\",\n \"255.255.2.387\",\n \"400.0.254.1\",\n \"192.0..33\"\n )\n);\n\nGRAMMAR_TEST(grammar::parse::socket_endpoint_grammar, SocketEndpoint,\n ::testing::Values(\n \"\/tmp\/.socket\", \"\/blabla\/.123123\/adfa\/socket\"\n ),\n ::testing::Values(\n \"\/\", \" \"\n )\n);\n\nGRAMMAR_PARSE_TEST(grammar::parse::endpoint_grammar, Endpoint, endpoint,\n ::testing::Values(\n ParseEndpoint::make_test_data(\"tcp:\/\/localhost:5432\",\n endpoint::tcp(\"localhost\", 5432)),\n ParseEndpoint::make_test_data(\"tcp:\/\/0.0.0.0:0\",\n endpoint::tcp(\"0.0.0.0\", 0)),\n ParseEndpoint::make_test_data(\"ssl:\/\/aw.my.com:5432\",\n endpoint::ssl(\"aw.my.com\", 5432)),\n ParseEndpoint::make_test_data(\"udp:\/\/127.0.0.1:5432\",\n endpoint::udp(\"127.0.0.1\", 5432)),\n ParseEndpoint::make_test_data(\"socket:\/\/\/tmp\/.123.thasocket\",\n endpoint::socket(\"\/tmp\/.123.thasocket\"))\n )\n);\n\ntemplate < typename InputIterator >\nusing endpoint_list_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_list >;\nGRAMMAR_TEST(endpoint_list_grammar, EndpointList,\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"tcp:\/\/localhost:5432,socket:\/\/\/tmp\/.socket,udp:\/\/127.0.0.1:5432\",\n \"udp:\/\/127.0.0.1:5432,tcp:\/\/localhost:5432,socket:\/\/\/tmp\/.socket\",\n \"socket:\/\/\/blabla\/.123123\/adfa\/socket\"\n \"socket:\/\/\/tmp\/.wire.ping_pong,tcp:\/\/127.0.0.1:0\"\n \"tcp:\/\/eth0[v6]:0\"\n ),\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket, tcp:\/\/localhost:5432, udp:\/\/127.0.0.1:5432\",\n \"\/\", \" \"\n )\n);\n\ntemplate < typename InputIterator >\nusing endpoint_set_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_set >;\nGRAMMAR_TEST(endpoint_set_grammar, EndpointSet,\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"socket:\/\/\/blabla\/.123123\/adfa\/socket\"\n ),\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket, tcp:\/\/localhost:5432, udp:\/\/127.0.0.1:5432\",\n \"\/\", \" \"\n )\n);\n\n} \/\/ namespace test\n} \/\/ namespace core\n} \/\/ namespace wire\n<commit_msg>Fix incorrect unit test data<commit_after>\/*\n * endpoints_grammar_test.cpp\n *\n * Created on: Jan 28, 2016\n * Author: zmij\n *\/\n\n#include <gtest\/gtest.h>\n#include <grammar\/grammar_parse_test.hpp>\n#include <wire\/core\/grammar\/endpoint_parse.hpp>\n\nnamespace wire {\nnamespace core {\nnamespace test {\n\nGRAMMAR_TEST(grammar::parse::inet_interface_grammar, InetInterface,\n ::testing::Values(\n \"eth0[v4]\", \"lo[V6]\"\n ),\n ::testing::Values(\n \"eth1\", \"tun0[v5]\", \"lo[\"\n )\n);\n\ntemplate < typename InputIterator >\nusing tcp_data_grammar =\n grammar::parse::ip_endpoint_data_grammar<\n InputIterator, detail::tcp_endpoint_data >;\n\nGRAMMAR_TEST(tcp_data_grammar, TCPEndpoint,\n ::testing::Values(\n \"127.0.0.1:10\",\n \"255.255.2.1:80\",\n \"10.0.254.1:3232\",\n \"192.0.2.33:7678\",\n \"google.com:8888\",\n \"www.mail.ru:765\",\n \"0.0.0.0:0\",\n \"[::8]:5678\",\n \"127.0.0.1:786\",\n \"[ffaa:1234::aadd:255.255.255.0]:567\",\n \"eth0[v4]:0\",\n \"lo[v6]:0\"\n ),\n ::testing::Values(\n \"255.255.2.1:456789\",\n \"10.0.254.1:-78\",\n \"192.0.2.33:bla\",\n \"127.0.0.256\",\n \"255.255.2.387\",\n \"400.0.254.1\",\n \"192.0..33\"\n )\n);\n\nGRAMMAR_TEST(grammar::parse::socket_endpoint_grammar, SocketEndpoint,\n ::testing::Values(\n \"\/tmp\/.socket\", \"\/blabla\/.123123\/adfa\/socket\"\n ),\n ::testing::Values(\n \"\/\", \" \"\n )\n);\n\nGRAMMAR_PARSE_TEST(grammar::parse::endpoint_grammar, Endpoint, endpoint,\n ::testing::Values(\n ParseEndpoint::make_test_data(\"tcp:\/\/localhost:5432\",\n endpoint::tcp(\"localhost\", 5432)),\n ParseEndpoint::make_test_data(\"tcp:\/\/0.0.0.0:0\",\n endpoint::tcp(\"0.0.0.0\", 0)),\n ParseEndpoint::make_test_data(\"ssl:\/\/aw.my.com:5432\",\n endpoint::ssl(\"aw.my.com\", 5432)),\n ParseEndpoint::make_test_data(\"udp:\/\/127.0.0.1:5432\",\n endpoint::udp(\"127.0.0.1\", 5432)),\n ParseEndpoint::make_test_data(\"socket:\/\/\/tmp\/.123.thasocket\",\n endpoint::socket(\"\/tmp\/.123.thasocket\"))\n )\n);\n\ntemplate < typename InputIterator >\nusing endpoint_list_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_list >;\nGRAMMAR_TEST(endpoint_list_grammar, EndpointList,\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"tcp:\/\/localhost:5432,socket:\/\/\/tmp\/.socket,udp:\/\/127.0.0.1:5432\",\n \"udp:\/\/127.0.0.1:5432,tcp:\/\/localhost:5432,socket:\/\/\/tmp\/.socket\",\n \"socket:\/\/\/blabla\/.123123\/adfa\/socket\",\n \"socket:\/\/\/tmp\/.wire.ping_pong,tcp:\/\/127.0.0.1:0\",\n \"tcp:\/\/eth0[v6]:0,tcp:\/\/lo[v4]:0\"\n ),\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket, tcp:\/\/localhost:5432, udp:\/\/127.0.0.1:5432\",\n \"\/\", \" \"\n )\n);\n\ntemplate < typename InputIterator >\nusing endpoint_set_grammar = grammar::parse::endpoints_grammar< InputIterator, endpoint_set >;\nGRAMMAR_TEST(endpoint_set_grammar, EndpointSet,\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"socket:\/\/\/tmp\/.socket,tcp:\/\/localhost:5432,udp:\/\/127.0.0.1:5432\",\n \"socket:\/\/\/blabla\/.123123\/adfa\/socket\"\n ),\n ::testing::Values(\n \"socket:\/\/\/tmp\/.socket, tcp:\/\/localhost:5432, udp:\/\/127.0.0.1:5432\",\n \"\/\", \" \"\n )\n);\n\n} \/\/ namespace test\n} \/\/ namespace core\n} \/\/ namespace wire\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_PARTICLEEMITTER_HPP\n#define NAZARA_PARTICLEEMITTER_HPP\n\n#include <Nazara\/Prerequesites.hpp>\n#include <Nazara\/Graphics\/Config.hpp>\n#include <Nazara\/Utility\/Node.hpp>\n\nnamespace Nz\n{\n\tclass ParticleMapper;\n\tclass ParticleGroup;\n\n\tclass NAZARA_GRAPHICS_API ParticleEmitter : public Node\n\t{\n\t\tpublic:\n\t\t\tParticleEmitter();\n\t\t\tParticleEmitter(const ParticleEmitter& emitter) = default;\n\t\t\tParticleEmitter(ParticleEmitter&& emitter) = default;\n\t\t\tvirtual ~ParticleEmitter();\n\n\t\t\tvirtual void Emit(ParticleGroup& system, float elapsedTime) const;\n\n\t\t\tvoid EnableLagCompensation(bool enable);\n\n\t\t\tunsigned int GetEmissionCount() const;\n\t\t\tfloat GetEmissionRate() const;\n\n\t\t\tbool IsLagCompensationEnabled() const;\n\n\t\t\tvoid SetEmissionCount(unsigned int count);\n\t\t\tvoid SetEmissionRate(float rate);\n\n\t\t\tParticleEmitter& operator=(const ParticleEmitter& emitter) = default;\n\t\t\tParticleEmitter& operator=(ParticleEmitter&& emitter) = default;\n\n\t\tprivate:\n\t\t\tvirtual void SetupParticles(ParticleMapper& mapper, unsigned int count) const = 0;\n\n\t\t\tbool m_lagCompensationEnabled;\n\t\t\tmutable float m_emissionAccumulator;\n\t\t\tfloat m_emissionRate;\n\t\t\tunsigned int m_emissionCount;\n\t};\n}\n\n#endif \/\/ NAZARA_PARTICLEEMITTER_HPP\n<commit_msg>Graphics\/ParticleEmitter: No longer inherit from Node<commit_after>\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_PARTICLEEMITTER_HPP\n#define NAZARA_PARTICLEEMITTER_HPP\n\n#include <Nazara\/Prerequesites.hpp>\n#include <Nazara\/Graphics\/Config.hpp>\n\nnamespace Nz\n{\n\tclass ParticleMapper;\n\tclass ParticleGroup;\n\n\tclass NAZARA_GRAPHICS_API ParticleEmitter\n\t{\n\t\tpublic:\n\t\t\tParticleEmitter();\n\t\t\tParticleEmitter(const ParticleEmitter& emitter) = default;\n\t\t\tParticleEmitter(ParticleEmitter&& emitter) = default;\n\t\t\tvirtual ~ParticleEmitter();\n\n\t\t\tvirtual void Emit(ParticleGroup& system, float elapsedTime) const;\n\n\t\t\tvoid EnableLagCompensation(bool enable);\n\n\t\t\tunsigned int GetEmissionCount() const;\n\t\t\tfloat GetEmissionRate() const;\n\n\t\t\tbool IsLagCompensationEnabled() const;\n\n\t\t\tvoid SetEmissionCount(unsigned int count);\n\t\t\tvoid SetEmissionRate(float rate);\n\n\t\t\tParticleEmitter& operator=(const ParticleEmitter& emitter) = default;\n\t\t\tParticleEmitter& operator=(ParticleEmitter&& emitter) = default;\n\n\t\tprivate:\n\t\t\tvirtual void SetupParticles(ParticleMapper& mapper, unsigned int count) const = 0;\n\n\t\t\tbool m_lagCompensationEnabled;\n\t\t\tmutable float m_emissionAccumulator;\n\t\t\tfloat m_emissionRate;\n\t\t\tunsigned int m_emissionCount;\n\t};\n}\n\n#endif \/\/ NAZARA_PARTICLEEMITTER_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <beluga\/buffer\/buffer_reader.hpp>\n\nnamespace beluga\n{\n template <typename iterator_type>\n class protocol_reader\n {\n public:\n\ttemplate <typename container_type>\n\tprotocol_reader(const container_type& container);\t\n\tprotocol_reader(iterator_type from, iterator_type to);\n\n\tvirtual ~protocol_reader() = default;\n\t\n\tbool has_minimum_length(std::size_t length);\n\n\tbuffer_reader<iterator_type>& get_reader();\n\titerator_type get_to();\n\t\n private:\n\tbuffer_reader<iterator_type> reader;\n\titerator_type to;\n }; \n}\n\n#include <beluga\/protocol\/protocol_reader.inl>\n<commit_msg>changed visibility of get_reader and get_to to protected<commit_after>#pragma once\n\n#include <beluga\/buffer\/buffer_reader.hpp>\n\nnamespace beluga\n{\n template <typename iterator_type>\n class protocol_reader\n {\n public:\n\ttemplate <typename container_type>\n\tprotocol_reader(const container_type& container);\t\n\tprotocol_reader(iterator_type from, iterator_type to);\n\n\tvirtual ~protocol_reader() = default;\n\t\n\tbool has_minimum_length(std::size_t length);\n\n protected:\n\tbuffer_reader<iterator_type>& get_reader();\n\titerator_type get_to();\n\t\n private:\n\tbuffer_reader<iterator_type> reader;\n\titerator_type to;\n }; \n}\n\n#include <beluga\/protocol\/protocol_reader.inl>\n<|endoftext|>"} {"text":"<commit_before>#include \"initializer.h\"\n\n#include <string>\n\n#include <openssl\/x509.h>\n#include <boost\/scoped_array.hpp>\n\n#include \"bootstrap\/bootstrap.h\"\n#include \"crypto\/keymanager.h\"\n#include \"logging\/logging.h\"\n\n\/\/ Postcondition: device_id is in the storage\nbool Initializer::initDeviceId() {\n \/\/ if device_id is already stored, just return\n std::string device_id;\n if (storage_->loadDeviceId(&device_id)) {\n return true;\n }\n\n \/\/ if device_id is specified in config, just use it, otherwise generate a random one\n device_id = config_.device_id;\n if (device_id.empty()) {\n if (config_.mode == ProvisionMode::kAutomatic) {\n device_id = Utils::genPrettyName();\n } else if (config_.mode == ProvisionMode::kImplicit) {\n device_id = keys_.getCN();\n } else {\n LOG_ERROR << \"Unknown provisioning method\";\n return false;\n }\n }\n\n storage_->storeDeviceId(device_id);\n return true;\n}\nvoid Initializer::resetDeviceId() { storage_->clearDeviceId(); }\n\n\/\/ Postcondition [(serial, hw_id)] is in the storage\nbool Initializer::initEcuSerials() {\n EcuSerials ecu_serials;\n\n \/\/ TODO: the assumption now is that the set of connected ECUs doesn't change, but it might obviously\n \/\/ not be the case. ECU discovery seems to be a big story and should be worked on accordingly.\n if (storage_->loadEcuSerials(&ecu_serials)) {\n return true;\n }\n\n std::string primary_ecu_serial_local = config_.primary_ecu_serial;\n if (primary_ecu_serial_local.empty()) {\n primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();\n }\n\n std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;\n if (primary_ecu_hardware_id.empty()) {\n primary_ecu_hardware_id = Utils::getHostname();\n if (primary_ecu_hardware_id == \"\") {\n return false;\n }\n }\n\n ecu_serials.emplace_back(Uptane::EcuSerial(primary_ecu_serial_local),\n Uptane::HardwareIdentifier(primary_ecu_hardware_id));\n\n for (auto it = secondary_info_.begin(); it != secondary_info_.end(); ++it) {\n ecu_serials.emplace_back(it->second->getSerial(), it->second->getHwId());\n }\n\n storage_->storeEcuSerials(ecu_serials);\n return true;\n}\n\nvoid Initializer::resetEcuSerials() { storage_->clearEcuSerials(); }\n\n\/\/ Postcondition: (public, private) is in the storage. It should not be stored until secondaries are provisioned\nbool Initializer::initPrimaryEcuKeys() { return keys_.generateUptaneKeyPair().size() != 0u; }\n\nvoid Initializer::resetEcuKeys() { storage_->clearPrimaryKeys(); }\n\nbool Initializer::loadSetTlsCreds() {\n keys_.copyCertsToCurl(&http_client_);\n return keys_.isOk();\n}\n\n\/\/ Postcondition: TLS credentials are in the storage\nInitRetCode Initializer::initTlsCreds() {\n if (loadSetTlsCreds()) {\n return InitRetCode::kOk;\n }\n\n if (config_.mode != ProvisionMode::kAutomatic) {\n LOG_ERROR << \"Credentials not found\";\n return InitRetCode::kStorageFailure;\n }\n\n \/\/ Autoprovision is needed and possible => autoprovision\n\n \/\/ set bootstrap credentials\n Bootstrap boot(config_.provision_path, config_.p12_password);\n http_client_.setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),\n CryptoSource::kFile);\n\n Json::Value data;\n std::string device_id;\n if (!storage_->loadDeviceId(&device_id)) {\n LOG_ERROR << \"device_id unknown during autoprovisioning process\";\n return InitRetCode::kStorageFailure;\n }\n data[\"deviceId\"] = device_id;\n data[\"ttl\"] = config_.expiry_days;\n HttpResponse response = http_client_.post(config_.server + \"\/devices\", data);\n if (!response.isOk()) {\n Json::Value resp_code = response.getJson()[\"code\"];\n if (resp_code.isString() && resp_code.asString() == \"device_already_registered\") {\n LOG_ERROR << \"Device id\" << device_id << \"is occupied\";\n return InitRetCode::kOccupied;\n }\n LOG_ERROR << \"Autoprovisioning failed, response: \" << response.body;\n return InitRetCode::kServerFailure;\n }\n\n std::string pkey;\n std::string cert;\n std::string ca;\n StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), response.body.size()), BIO_vfree);\n if (!Crypto::parseP12(device_p12.get(), \"\", &pkey, &cert, &ca)) {\n LOG_ERROR << \"Received a malformed P12 package from the server\";\n return InitRetCode::kBadP12;\n }\n storage_->storeTlsCreds(ca, cert, pkey);\n\n \/\/ set provisioned credentials\n if (!loadSetTlsCreds()) {\n LOG_ERROR << \"Failed to set provisioned credentials\";\n return InitRetCode::kStorageFailure;\n }\n\n LOG_INFO << \"Provisioned successfully on Device Gateway\";\n return InitRetCode::kOk;\n}\n\nvoid Initializer::resetTlsCreds() {\n if (config_.mode != ProvisionMode::kImplicit) {\n storage_->clearTlsCreds();\n }\n}\n\n\/\/ Postcondition: \"ECUs registered\" flag set in the storage\nInitRetCode Initializer::initEcuRegister() {\n if (storage_->loadEcuRegistered()) {\n return InitRetCode::kOk;\n }\n\n PublicKey uptane_public_key = keys_.UptanePublicKey();\n\n if (uptane_public_key.Type() == KeyType::kUnknown) {\n return InitRetCode::kStorageFailure;\n }\n\n EcuSerials ecu_serials;\n \/\/ initEcuSerials should have been called by this point\n if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.size() < 1) {\n return InitRetCode::kStorageFailure;\n }\n\n Json::Value all_ecus;\n all_ecus[\"primary_ecu_serial\"] = ecu_serials[0].first.ToString();\n all_ecus[\"ecus\"] = Json::arrayValue;\n {\n Json::Value primary_ecu;\n primary_ecu[\"hardware_identifier\"] = ecu_serials[0].second.ToString();\n primary_ecu[\"ecu_serial\"] = ecu_serials[0].first.ToString();\n primary_ecu[\"clientKey\"] = keys_.UptanePublicKey().ToUptane();\n all_ecus[\"ecus\"].append(primary_ecu);\n }\n\n for (auto it = secondary_info_.cbegin(); it != secondary_info_.cend(); it++) {\n Json::Value ecu;\n auto public_key = it->second->getPublicKey();\n ecu[\"hardware_identifier\"] = it->second->getHwId().ToString();\n ecu[\"ecu_serial\"] = it->second->getSerial().ToString();\n ecu[\"clientKey\"] = public_key.ToUptane();\n all_ecus[\"ecus\"].append(ecu);\n }\n\n HttpResponse response = http_client_.post(config_.ecu_registration_endpoint, all_ecus);\n if (!response.isOk()) {\n Json::Value resp_code = response.getJson()[\"code\"];\n if (resp_code.isString() &&\n (resp_code.asString() == \"ecu_already_registered\" || resp_code.asString() == \"device_already_registered\")) {\n LOG_ERROR << \"Some ECU is already registered\";\n return InitRetCode::kOccupied;\n }\n LOG_ERROR << \"Error registering device on Uptane, response: \" << response.body;\n return InitRetCode::kServerFailure;\n }\n \/\/ do not call storage_->storeEcuRegistered(), it will be called from the top-level Init function after the\n \/\/ acknowledgement\n LOG_INFO << \"ECUs have been successfully registered to the server\";\n return InitRetCode::kOk;\n}\n\n\/\/ Postcondition: \"ECUs registered\" flag set in the storage\nInitializer::Initializer(\n const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in, HttpInterface& http_client_in,\n KeyManager& keys_in,\n const std::map<Uptane::EcuSerial, std::shared_ptr<Uptane::SecondaryInterface> >& secondary_info_in)\n : config_(config_in),\n storage_(std::move(storage_in)),\n http_client_(http_client_in),\n keys_(keys_in),\n secondary_info_(secondary_info_in) {\n success_ = false;\n for (int i = 0; i < MaxInitializationAttempts; i++) {\n if (!initDeviceId()) {\n LOG_ERROR << \"Device ID generation failed, abort initialization\";\n return;\n }\n\n InitRetCode ret_code = initTlsCreds();\n \/\/ if a device with the same ID has already been registered to the server,\n \/\/ generate a new one\n if (ret_code == InitRetCode::kOccupied) {\n resetDeviceId();\n LOG_INFO << \"Device name is already registered, restart\";\n continue;\n }\n if (ret_code != InitRetCode::kOk) {\n LOG_ERROR << \"Autoprovisioning failed, abort initialization\";\n return;\n }\n\n if (!initPrimaryEcuKeys()) {\n LOG_ERROR << \"ECU key generation failed, abort initialization\";\n return;\n }\n if (!initEcuSerials()) {\n LOG_ERROR << \"ECU serial generation failed, abort initialization\";\n return;\n }\n\n ret_code = initEcuRegister();\n \/\/ if ECUs with same ID have been registered to the server, we don't have a\n \/\/ clear remediation path right now, just ignore the error\n if (ret_code == InitRetCode::kOccupied) {\n LOG_INFO << \"ECU serial is already registered\";\n } else if (ret_code != InitRetCode::kOk) {\n LOG_ERROR << \"ECU registration failed, abort initialization\";\n return;\n }\n\n \/\/ TODO: acknowledge on server _before_ setting the flag\n storage_->storeEcuRegistered();\n success_ = true;\n return;\n }\n LOG_ERROR << \"Initialization failed after \" << MaxInitializationAttempts << \" attempts\";\n}\n<commit_msg>Better error message.<commit_after>#include \"initializer.h\"\n\n#include <string>\n\n#include <openssl\/x509.h>\n#include <boost\/scoped_array.hpp>\n\n#include \"bootstrap\/bootstrap.h\"\n#include \"crypto\/keymanager.h\"\n#include \"logging\/logging.h\"\n\n\/\/ Postcondition: device_id is in the storage\nbool Initializer::initDeviceId() {\n \/\/ if device_id is already stored, just return\n std::string device_id;\n if (storage_->loadDeviceId(&device_id)) {\n return true;\n }\n\n \/\/ if device_id is specified in config, just use it, otherwise generate a random one\n device_id = config_.device_id;\n if (device_id.empty()) {\n if (config_.mode == ProvisionMode::kAutomatic) {\n device_id = Utils::genPrettyName();\n } else if (config_.mode == ProvisionMode::kImplicit) {\n device_id = keys_.getCN();\n } else {\n LOG_ERROR << \"Unknown provisioning method\";\n return false;\n }\n }\n\n storage_->storeDeviceId(device_id);\n return true;\n}\nvoid Initializer::resetDeviceId() { storage_->clearDeviceId(); }\n\n\/\/ Postcondition [(serial, hw_id)] is in the storage\nbool Initializer::initEcuSerials() {\n EcuSerials ecu_serials;\n\n \/\/ TODO: the assumption now is that the set of connected ECUs doesn't change, but it might obviously\n \/\/ not be the case. ECU discovery seems to be a big story and should be worked on accordingly.\n if (storage_->loadEcuSerials(&ecu_serials)) {\n return true;\n }\n\n std::string primary_ecu_serial_local = config_.primary_ecu_serial;\n if (primary_ecu_serial_local.empty()) {\n primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();\n }\n\n std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;\n if (primary_ecu_hardware_id.empty()) {\n primary_ecu_hardware_id = Utils::getHostname();\n if (primary_ecu_hardware_id == \"\") {\n return false;\n }\n }\n\n ecu_serials.emplace_back(Uptane::EcuSerial(primary_ecu_serial_local),\n Uptane::HardwareIdentifier(primary_ecu_hardware_id));\n\n for (auto it = secondary_info_.begin(); it != secondary_info_.end(); ++it) {\n ecu_serials.emplace_back(it->second->getSerial(), it->second->getHwId());\n }\n\n storage_->storeEcuSerials(ecu_serials);\n return true;\n}\n\nvoid Initializer::resetEcuSerials() { storage_->clearEcuSerials(); }\n\n\/\/ Postcondition: (public, private) is in the storage. It should not be stored until secondaries are provisioned\nbool Initializer::initPrimaryEcuKeys() { return keys_.generateUptaneKeyPair().size() != 0u; }\n\nvoid Initializer::resetEcuKeys() { storage_->clearPrimaryKeys(); }\n\nbool Initializer::loadSetTlsCreds() {\n keys_.copyCertsToCurl(&http_client_);\n return keys_.isOk();\n}\n\n\/\/ Postcondition: TLS credentials are in the storage\nInitRetCode Initializer::initTlsCreds() {\n if (loadSetTlsCreds()) {\n return InitRetCode::kOk;\n }\n\n if (config_.mode != ProvisionMode::kAutomatic) {\n LOG_ERROR << \"Credentials not found\";\n return InitRetCode::kStorageFailure;\n }\n\n \/\/ Autoprovision is needed and possible => autoprovision\n\n \/\/ set bootstrap credentials\n Bootstrap boot(config_.provision_path, config_.p12_password);\n http_client_.setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),\n CryptoSource::kFile);\n\n Json::Value data;\n std::string device_id;\n if (!storage_->loadDeviceId(&device_id)) {\n LOG_ERROR << \"device_id unknown during autoprovisioning process\";\n return InitRetCode::kStorageFailure;\n }\n data[\"deviceId\"] = device_id;\n data[\"ttl\"] = config_.expiry_days;\n HttpResponse response = http_client_.post(config_.server + \"\/devices\", data);\n if (!response.isOk()) {\n Json::Value resp_code = response.getJson()[\"code\"];\n if (resp_code.isString() && resp_code.asString() == \"device_already_registered\") {\n LOG_ERROR << \"Device id\" << device_id << \"is occupied\";\n return InitRetCode::kOccupied;\n }\n LOG_ERROR << \"Autoprovisioning failed, response: \" << response.body;\n return InitRetCode::kServerFailure;\n }\n\n std::string pkey;\n std::string cert;\n std::string ca;\n StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), response.body.size()), BIO_vfree);\n if (!Crypto::parseP12(device_p12.get(), \"\", &pkey, &cert, &ca)) {\n LOG_ERROR << \"Received a malformed P12 package from the server\";\n return InitRetCode::kBadP12;\n }\n storage_->storeTlsCreds(ca, cert, pkey);\n\n \/\/ set provisioned credentials\n if (!loadSetTlsCreds()) {\n LOG_ERROR << \"Failed to set provisioned credentials\";\n return InitRetCode::kStorageFailure;\n }\n\n LOG_INFO << \"Provisioned successfully on Device Gateway\";\n return InitRetCode::kOk;\n}\n\nvoid Initializer::resetTlsCreds() {\n if (config_.mode != ProvisionMode::kImplicit) {\n storage_->clearTlsCreds();\n }\n}\n\n\/\/ Postcondition: \"ECUs registered\" flag set in the storage\nInitRetCode Initializer::initEcuRegister() {\n if (storage_->loadEcuRegistered()) {\n return InitRetCode::kOk;\n }\n\n PublicKey uptane_public_key = keys_.UptanePublicKey();\n\n if (uptane_public_key.Type() == KeyType::kUnknown) {\n return InitRetCode::kStorageFailure;\n }\n\n EcuSerials ecu_serials;\n \/\/ initEcuSerials should have been called by this point\n if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.size() < 1) {\n return InitRetCode::kStorageFailure;\n }\n\n Json::Value all_ecus;\n all_ecus[\"primary_ecu_serial\"] = ecu_serials[0].first.ToString();\n all_ecus[\"ecus\"] = Json::arrayValue;\n {\n Json::Value primary_ecu;\n primary_ecu[\"hardware_identifier\"] = ecu_serials[0].second.ToString();\n primary_ecu[\"ecu_serial\"] = ecu_serials[0].first.ToString();\n primary_ecu[\"clientKey\"] = keys_.UptanePublicKey().ToUptane();\n all_ecus[\"ecus\"].append(primary_ecu);\n }\n\n for (auto it = secondary_info_.cbegin(); it != secondary_info_.cend(); it++) {\n Json::Value ecu;\n auto public_key = it->second->getPublicKey();\n ecu[\"hardware_identifier\"] = it->second->getHwId().ToString();\n ecu[\"ecu_serial\"] = it->second->getSerial().ToString();\n ecu[\"clientKey\"] = public_key.ToUptane();\n all_ecus[\"ecus\"].append(ecu);\n }\n\n HttpResponse response = http_client_.post(config_.ecu_registration_endpoint, all_ecus);\n if (!response.isOk()) {\n Json::Value resp_code = response.getJson()[\"code\"];\n if (resp_code.isString() &&\n (resp_code.asString() == \"ecu_already_registered\" || resp_code.asString() == \"device_already_registered\")) {\n LOG_ERROR << \"Some ECU is already registered\";\n return InitRetCode::kOccupied;\n }\n LOG_ERROR << \"Error registering device on Uptane, response: \" << response.body;\n return InitRetCode::kServerFailure;\n }\n \/\/ do not call storage_->storeEcuRegistered(), it will be called from the top-level Init function after the\n \/\/ acknowledgement\n LOG_INFO << \"ECUs have been successfully registered to the server\";\n return InitRetCode::kOk;\n}\n\n\/\/ Postcondition: \"ECUs registered\" flag set in the storage\nInitializer::Initializer(\n const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in, HttpInterface& http_client_in,\n KeyManager& keys_in,\n const std::map<Uptane::EcuSerial, std::shared_ptr<Uptane::SecondaryInterface> >& secondary_info_in)\n : config_(config_in),\n storage_(std::move(storage_in)),\n http_client_(http_client_in),\n keys_(keys_in),\n secondary_info_(secondary_info_in) {\n success_ = false;\n for (int i = 0; i < MaxInitializationAttempts; i++) {\n if (!initDeviceId()) {\n LOG_ERROR << \"Device ID generation failed, abort initialization\";\n return;\n }\n\n InitRetCode ret_code = initTlsCreds();\n \/\/ if a device with the same ID has already been registered to the server,\n \/\/ generate a new one\n if (ret_code == InitRetCode::kOccupied) {\n resetDeviceId();\n LOG_INFO << \"Device name is already registered, restart\";\n continue;\n } else if (ret_code == InitRetCode::kStorageFailure) {\n LOG_ERROR << \"Error reading existing provisioning data from storage\";\n return;\n } else if (ret_code != InitRetCode::kOk) {\n LOG_ERROR << \"Autoprovisioning failed, abort initialization\";\n return;\n }\n\n if (!initPrimaryEcuKeys()) {\n LOG_ERROR << \"ECU key generation failed, abort initialization\";\n return;\n }\n if (!initEcuSerials()) {\n LOG_ERROR << \"ECU serial generation failed, abort initialization\";\n return;\n }\n\n ret_code = initEcuRegister();\n \/\/ if ECUs with same ID have been registered to the server, we don't have a\n \/\/ clear remediation path right now, just ignore the error\n if (ret_code == InitRetCode::kOccupied) {\n LOG_INFO << \"ECU serial is already registered\";\n } else if (ret_code != InitRetCode::kOk) {\n LOG_ERROR << \"ECU registration failed, abort initialization\";\n return;\n }\n\n \/\/ TODO: acknowledge on server _before_ setting the flag\n storage_->storeEcuRegistered();\n success_ = true;\n return;\n }\n LOG_ERROR << \"Initialization failed after \" << MaxInitializationAttempts << \" attempts\";\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"..\/..\/expat\/escape_json.h\"\n#include \"output_csv.h\"\n\n\nbool Output_CSV::write_http_headers()\n{\n std::cout<<\"Content-type: text\/csv\\n\";\n return true;\n}\n\n\n\/\/ Escape CSV output according to RFC 4180\nstd::string escape_csv(const std::string& input)\n{\n std::string result;\n bool quotes_needed = false;\n \n for (int i = input.size() - 1; i >= 0; --i)\n {\n if (input[i] == '\\n' || input[i] == ',')\n quotes_needed = true;\n else if (input[i] == '\\\"')\n {\n quotes_needed = true;\n if (result.empty())\n result = input.substr(0, i) + \"\\\"\" + input.substr(i);\n else\n result = result.substr(0, i) + \"\\\"\" + result.substr(i);\n }\n }\n \n if (!quotes_needed)\n return input;\n else if (result.empty())\n return std::string(\"\\\"\") + input + \"\\\"\";\n else\n return std::string(\"\\\"\") + result + \"\\\"\";\n}\n\n\nvoid Output_CSV::write_payload_header\n (const std::string& db_dir, const std::string& timestamp, const std::string& area_timestamp)\n{\n if (csv_settings.with_headerline)\n {\n for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n it != csv_settings.keyfields.end(); ++it)\n {\n std::cout<<(it->second ? \"@\" : \"\")<<escape_csv(it->first);\n if (it + 1 != csv_settings.keyfields.end())\n std::cout<<csv_settings.separator;\n }\n std::cout<<'\\n';\n }\n}\n\n\nvoid Output_CSV::write_footer()\n{\n \/\/ Intentionally empty\n}\n\n\nvoid Output_CSV::display_remark(const std::string& text)\n{\n \/\/ Intentionally empty\n}\n\n\nvoid Output_CSV::display_error(const std::string& text)\n{\n \/\/ Intentionally empty\n}\n\n\nstd::string Output_CSV::dump_config() const\n{\n std::string result = \"(\";\n \n for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n it != csv_settings.keyfields.end(); ++it)\n {\n if (it != csv_settings.keyfields.begin())\n result += \",\";\n \n if (it->second)\n result += \"::\" + it->first;\n else\n result += \"\\\"\" + escape_cstr(it->first) + \"\\\"\";\n }\n \n if (csv_settings.separator != \"\\t\")\n result += std::string(\";\") + (csv_settings.with_headerline ? \"true\" : \"false\") + \";\\\"\"\n + escape_cstr(csv_settings.separator) + \"\\\"\";\n else if (!csv_settings.with_headerline)\n result += \";false\";\n \n return result + \")\";\n}\n\n\ntemplate< typename OSM_Element_Metadata_Skeleton >\nvoid print_meta(const std::string& keyfield,\n const OSM_Element_Metadata_Skeleton& meta, const std::map< uint32, std::string >* users)\n{\n if (keyfield == \"version\")\n std::cout<<meta.version;\n else if (keyfield == \"timestamp\")\n std::cout<<Timestamp(meta.timestamp).str();\n else if (keyfield == \"changeset\")\n std::cout<<meta.changeset;\n else if (keyfield == \"uid\")\n std::cout<<meta.user_id;\n else if (users && keyfield == \"user\")\n {\n std::map< uint32, std::string >::const_iterator uit = users->find(meta.user_id);\n if (uit != users->end())\n std::cout<<uit->second;\n }\n}\n\n\ntemplate< >\nvoid print_meta< int >(const std::string& keyfield,\n const int& meta, const std::map< uint32, std::string >* users) {}\n\n\ntemplate< typename Id_Type, typename OSM_Element_Metadata_Skeleton >\nvoid process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry,\n const OSM_Element_Metadata_Skeleton* meta,\n const std::vector< std::pair< std::string, std::string> >* tags,\n const std::map< uint32, std::string >* users,\n const Csv_Settings& csv_settings,\n Output_Mode mode)\n{\n std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n while (true)\n {\n if (!it->second)\n {\n if (tags)\n {\n\tfor (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();\n\t it_tags != tags->end(); ++it_tags)\n\t{\n\t if (it_tags->first == it->first)\n\t {\n\t std::cout<<escape_csv(it_tags->second);\n\t break;\n\t }\n\t}\n }\n }\n else\n {\n if (meta)\n print_meta(it->first, *meta, users);\n\n if (it->first == \"id\")\n {\n if (mode.mode & Output_Mode::ID)\n std::cout<<id.val();\n }\n else if (it->first == \"otype\")\n std::cout<<otype;\n else if (it->first == \"type\")\n\tstd::cout<<type;\n else if (it->first == \"lat\")\n {\n if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))\n\t && geometry.has_center())\n std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lat();\n }\n else if (it->first == \"lon\")\n {\n if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))\n\t && geometry.has_center())\n std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lon();\n }\n }\n \n if (++it == csv_settings.keyfields.end())\n break;\n std::cout<<csv_settings.separator;\n }\n std::cout<<\"\\n\";\n}\n\n\nvoid Output_CSV::print_item(const Node_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Node_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta)\n{\n process_csv_line(1, \"node\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Way_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Way_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta)\n{\n process_csv_line(2, \"way\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Relation_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta,\n const std::map< uint32, std::string >* roles,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Relation_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta)\n{\n process_csv_line(3, \"relation\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Derived_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n Output_Mode mode)\n{\n process_csv_line< Derived_Skeleton::Id_Type, int >(\n 4, skel.type_name, skel.id, geometry, 0, tags, 0, csv_settings, mode);\n}\n<commit_msg>Fix CSV output for out count<commit_after>\n#include \"..\/..\/expat\/escape_json.h\"\n#include \"output_csv.h\"\n\n\nbool Output_CSV::write_http_headers()\n{\n std::cout<<\"Content-type: text\/csv\\n\";\n return true;\n}\n\n\n\/\/ Escape CSV output according to RFC 4180\nstd::string escape_csv(const std::string& input)\n{\n std::string result;\n bool quotes_needed = false;\n \n for (int i = input.size() - 1; i >= 0; --i)\n {\n if (input[i] == '\\n' || input[i] == ',')\n quotes_needed = true;\n else if (input[i] == '\\\"')\n {\n quotes_needed = true;\n if (result.empty())\n result = input.substr(0, i) + \"\\\"\" + input.substr(i);\n else\n result = result.substr(0, i) + \"\\\"\" + result.substr(i);\n }\n }\n \n if (!quotes_needed)\n return input;\n else if (result.empty())\n return std::string(\"\\\"\") + input + \"\\\"\";\n else\n return std::string(\"\\\"\") + result + \"\\\"\";\n}\n\n\nvoid Output_CSV::write_payload_header\n (const std::string& db_dir, const std::string& timestamp, const std::string& area_timestamp)\n{\n if (csv_settings.with_headerline)\n {\n for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n it != csv_settings.keyfields.end(); ++it)\n {\n std::cout<<(it->second ? \"@\" : \"\")<<escape_csv(it->first);\n if (it + 1 != csv_settings.keyfields.end())\n std::cout<<csv_settings.separator;\n }\n std::cout<<'\\n';\n }\n}\n\n\nvoid Output_CSV::write_footer()\n{\n \/\/ Intentionally empty\n}\n\n\nvoid Output_CSV::display_remark(const std::string& text)\n{\n \/\/ Intentionally empty\n}\n\n\nvoid Output_CSV::display_error(const std::string& text)\n{\n \/\/ Intentionally empty\n}\n\n\nstd::string Output_CSV::dump_config() const\n{\n std::string result = \"(\";\n \n for (std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n it != csv_settings.keyfields.end(); ++it)\n {\n if (it != csv_settings.keyfields.begin())\n result += \",\";\n \n if (it->second)\n result += \"::\" + it->first;\n else\n result += \"\\\"\" + escape_cstr(it->first) + \"\\\"\";\n }\n \n if (csv_settings.separator != \"\\t\")\n result += std::string(\";\") + (csv_settings.with_headerline ? \"true\" : \"false\") + \";\\\"\"\n + escape_cstr(csv_settings.separator) + \"\\\"\";\n else if (!csv_settings.with_headerline)\n result += \";false\";\n \n return result + \")\";\n}\n\n\ntemplate< typename OSM_Element_Metadata_Skeleton >\nvoid print_meta(const std::string& keyfield,\n const OSM_Element_Metadata_Skeleton& meta, const std::map< uint32, std::string >* users)\n{\n if (keyfield == \"version\")\n std::cout<<meta.version;\n else if (keyfield == \"timestamp\")\n std::cout<<Timestamp(meta.timestamp).str();\n else if (keyfield == \"changeset\")\n std::cout<<meta.changeset;\n else if (keyfield == \"uid\")\n std::cout<<meta.user_id;\n else if (users && keyfield == \"user\")\n {\n std::map< uint32, std::string >::const_iterator uit = users->find(meta.user_id);\n if (uit != users->end())\n std::cout<<uit->second;\n }\n}\n\n\ntemplate< >\nvoid print_meta< int >(const std::string& keyfield,\n const int& meta, const std::map< uint32, std::string >* users) {}\n\nstd::string get_count_tag(const std::vector< std::pair< std::string, std::string> >* tags, std::string tag)\n{\n if (tags)\n for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();\n it_tags != tags->end(); ++it_tags)\n if (it_tags->first == tag)\n return it_tags->second;\n return \"0\";\n}\n\n\ntemplate< typename Id_Type, typename OSM_Element_Metadata_Skeleton >\nvoid process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry,\n const OSM_Element_Metadata_Skeleton* meta,\n const std::vector< std::pair< std::string, std::string> >* tags,\n const std::map< uint32, std::string >* users,\n const Csv_Settings& csv_settings,\n Output_Mode mode)\n{\n std::vector< std::pair< std::string, bool > >::const_iterator it = csv_settings.keyfields.begin();\n while (true)\n {\n if (!it->second)\n {\n if (tags)\n {\n\tfor (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin();\n\t it_tags != tags->end(); ++it_tags)\n\t{\n\t if (it_tags->first == it->first)\n\t {\n\t std::cout<<escape_csv(it_tags->second);\n\t break;\n\t }\n\t}\n }\n }\n else\n {\n if (meta)\n print_meta(it->first, *meta, users);\n\n if (it->first == \"id\")\n {\n if (mode.mode & Output_Mode::ID)\n std::cout<<id.val();\n }\n else if (it->first == \"otype\")\n std::cout<<otype;\n else if (it->first == \"type\")\n\tstd::cout<<type;\n else if (it->first == \"lat\")\n {\n if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))\n\t && geometry.has_center())\n std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lat();\n }\n else if (it->first == \"lon\")\n {\n if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER))\n\t && geometry.has_center())\n std::cout<<std::fixed<<std::setprecision(7)<<geometry.center_lon();\n }\n if (type == \"count\")\n {\n if (it->first == \"count\")\n std::cout << get_count_tag(tags, \"total\");\n else if (it->first == \"count:nodes\")\n std::cout << get_count_tag(tags, \"nodes\");\n else if (it->first == \"count:ways\")\n std::cout << get_count_tag(tags, \"ways\");\n else if (it->first == \"count:relations\")\n std::cout << get_count_tag(tags, \"relations\");\n else if (it->first == \"count:areas\")\n std::cout << get_count_tag(tags, \"areas\");\n }\n }\n \n if (++it == csv_settings.keyfields.end())\n break;\n std::cout<<csv_settings.separator;\n }\n std::cout<<\"\\n\";\n}\n\n\nvoid Output_CSV::print_item(const Node_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Node_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta)\n{\n process_csv_line(1, \"node\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Way_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Way_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta)\n{\n process_csv_line(2, \"way\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Relation_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta,\n const std::map< uint32, std::string >* roles,\n const std::map< uint32, std::string >* users,\n Output_Mode mode,\n const Feature_Action& action,\n const Relation_Skeleton* new_skel,\n const Opaque_Geometry* new_geometry,\n const std::vector< std::pair< std::string, std::string > >* new_tags,\n const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta)\n{\n process_csv_line(3, \"relation\", skel.id, geometry, meta, tags, users, csv_settings, mode);\n}\n\n\nvoid Output_CSV::print_item(const Derived_Skeleton& skel,\n const Opaque_Geometry& geometry,\n const std::vector< std::pair< std::string, std::string > >* tags,\n Output_Mode mode)\n{\n process_csv_line< Derived_Skeleton::Id_Type, int >(\n 4, skel.type_name, skel.id, geometry, 0, tags, 0, csv_settings, mode);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ofxXmlSettings.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/----------------------------------------\n\/\/ a pretty useful tokenization system:\nstatic vector<string> tokenize(const string & str, const string & delim);\nstatic vector<string> tokenize(const string & str, const string & delim)\n{\n vector<string> tokens;\n\n size_t p0 = 0, p1 = string::npos;\n while(p0 != string::npos)\n {\n p1 = str.find_first_of(delim, p0);\n if(p1 != p0)\n {\n string token = str.substr(p0, p1 - p0);\n tokens.push_back(token);\n }\n p0 = str.find_first_not_of(delim, p1);\n }\n return tokens;\n}\n\/\/----------------------------------------\n\n\nofxXmlSettings::ofxXmlSettings(){\n\tstoredHandle\t= new TiXmlHandle(NULL);\n\tlevel\t\t\t= 0;\n\t\/\/we do this so that we have a valid handle\n\t\/\/without the need for loadFile\n\t*storedHandle = TiXmlHandle(&doc);\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::setVerbose(bool _verbose){\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::clear(){\n\t\/\/we clear from our root level\n\t\/\/this is usually the document\n\t\/\/but if we are pushed - it could\n\t\/\/be all the tags inside of the pushed\n\t\/\/node - including the node itself!\n\n\tstoredHandle->ToNode()->Clear();\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::loadFile(string xmlFile){\n\n\txmlFile = ofToDataPath(xmlFile);\n\n\tbool loadOkay = doc.LoadFile(xmlFile.c_str());\n\n\t\/\/theo removed bool check as it would\n\t\/\/return false if the file exists but was\n\t\/\/empty\n\n \/\/our push pop level should be set to 0!\n\tlevel = 0;\n\n\t*storedHandle = TiXmlHandle(&doc);\n\treturn loadOkay;\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::saveFile(string xmlFile){\n\n\txmlFile = ofToDataPath(xmlFile);\n\tdoc.SaveFile(xmlFile.c_str());\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::clearTagContents(string tag, int which){\n\t\/\/we check it first to see if it exists\n\t\/\/otherwise setValue will make a new empty tag\n\tif( tagExists(tag, which) )setValue(tag, \"\", which);\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::removeTag(string tag, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\t\/\/no tags so we return\n\tif( tokens.size() == 0 ) return;\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tif(which < 0) which = 0;\n\n\tfor(int x=0;x<tokens.size();x++){\n\n\t\t\/\/we only support multi tags\n\t\t\/\/with same name at root level\n\t\tif(x > 0) which = 0;\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\tif ( !isRealHandle.Node() ) break;\n\t\telse{\n\t\t\tif (x == tokens.size()-1){\n\t\t\t\t\/\/if we are at the last tag and it exists\n\t\t\t\t\/\/we use its parent to remove it - haha\n\t\t\t\ttagHandle.ToNode()->RemoveChild( isRealHandle.ToNode() );\n\t\t\t}\n\t\t\ttagHandle = isRealHandle;\n\t\t}\n\t}\n\n\ttokens.clear();\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getValue(string tag, int defaultValue, int which){\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tint returnValue = defaultValue;\n\n\tif (readTag(tag, tempStr, which)){\n\t\treturnValue = strtol(tempStr, NULL, 0);\n\t}\n\tdelete tempStr;\n\treturn returnValue;\n}\n\n\/\/---------------------------------------------------------\nfloat ofxXmlSettings::getValue(string tag, double defaultValue, int which){\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tfloat returnValue = defaultValue;\n\n\tif (readTag(tag, tempStr, which)){\n\t\treturnValue = strtod(tempStr, NULL);\n\t}\n\tdelete tempStr;\n\treturn returnValue;\n}\n\n\/\/---------------------------------------------------------\nstring ofxXmlSettings::getValue(string tag, string defaultValue, int which){\n\n\t\/\/ lots of char *, string kung-fu here...\n\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tchar * returnPtr = (char *) defaultValue.c_str();\n\tif (readTag(tag, tempStr, which)){\n\t\treturnPtr = tempStr;\n\t}\n\tstring returnString(returnPtr);\n\tdelete tempStr;\n\treturn returnString;\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::readTag(string tag, char * valueString, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\tTiXmlHandle tagHandle = *storedHandle;\n\tfor(int x=0;x<tokens.size();x++){\n\t\tif(x == 0)tagHandle = tagHandle.ChildElement(tokens.at(x), which);\n\t\telse tagHandle = tagHandle.FirstChildElement( tokens.at(x) );\n\t}\n\n\t\/\/ once we've walked, let's get that value...\n\tTiXmlHandle valHandle = tagHandle.Child( 0 );\n\n \/\/now, clear that vector!\n\ttokens.clear();\n\n \/\/ if that value is really text, let's get the value out of it !\n if (valHandle.Text()){\n \tint maxLen = MIN(MAX_TAG_VALUE_LENGTH_IN_CHARS, strlen(valHandle.Text()->Value()));\n \tmemcpy(valueString, valHandle.Text()->Value(), maxLen);\n \treturn true;\n } else {\n\t\treturn false;\n\t}\n}\n\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::pushTag(string tag, int which){\n\n\tint pos = tag.find(\":\");\n\n\tif(pos > 0){\n\t\ttag = tag.substr(0,pos);\n\t}\n\n\t\/\/we only allow to push one tag at a time.\n\tTiXmlHandle isRealHandle = storedHandle->ChildElement(tag, which);\n\n\tif( isRealHandle.Node() ){\n\t\t*storedHandle = isRealHandle;\n\t\tlevel++;\n\t\treturn true;\n\t}else{\n\t\tprintf(\"pushTag - tag not found\\n\");\n\t}\n\n\treturn false;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::popTag(){\n\n\tif(level >= 1){\n\t\tTiXmlHandle parent( (storedHandle->ToNode() )->Parent() );\n\t\t*storedHandle = parent;\n\t\tlevel--;\n\t}else{\n\t\t*storedHandle = TiXmlHandle(&doc);\n\t\tlevel = 0;\n\t}\n\n\treturn level;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getPushLevel(){\n\treturn level;\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::tagExists(string tag, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\tbool found = false;\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tif(which < 0) which = 0;\n\n\tfor(int x=0;x<tokens.size();x++){\n\n\t\t\/\/we only support multi tags\n\t\t\/\/with same name at root level\n\t\tif(x > 0) which = 0;\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\t\/\/as soon as we find a tag that doesn't exist\n\t\t\/\/we return false;\n\t\tif ( !isRealHandle.Node() ){\n\t\t\tfound = false;\n\t\t\tbreak;\n\t\t}\n\t\telse{\n\t\t\tfound = true;\n\t\t\ttagHandle = isRealHandle;\n\t\t}\n\t}\n\n\ttokens.clear();\n\n\treturn found;\n}\n\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getNumTags(string tag){\n\t\/\/this only works for tags at the current root level\n\n\tint pos = tag.find(\":\");\n\n\tif(pos > 0){\n\t\ttag = tag.substr(0,pos);\n\t}\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tint count = 0;\n\n\t\/\/ripped from tinyXML as doing this ourselves once is a LOT! faster\n\t\/\/than having this called n number of times in a while loop - we go from n*n iterations to n iterations\n\n\tTiXmlElement* child = ( storedHandle->FirstChildElement( tag ) ).Element();\n\tfor (count = 0; child; child = child->NextSiblingElement( tag ), ++count){\n\t\t\/\/nothing\n\t}\n\n\treturn count;\n}\n\n\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::writeTag(string tag, char * valueStr, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\t\/\/ allocate then clean up :\n\tTiXmlElement ** elements = new TiXmlElement*[tokens.size()];\n\tfor(int x=0;x<tokens.size();x++){\n\t\telements[x] = new TiXmlElement(tokens.at(x));\n\t}\n\n\tTiXmlText Value(valueStr);\n\n\t\/\/ search our way up - do these tags exist?\n\t\/\/ find the first that DOESNT exist, then move backwards...\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tbool addNewTag = false;\n\tif(which == -1)addNewTag = true;\n\n\tfor(int x=0;x<tokens.size();x++){\n\n\t\tif( x > 0 ){\n\t\t\t\/\/multi tags of same name\n\t\t\t\/\/only for the root level\n\t\t\twhich = 0;\n\t\t\taddNewTag = false;\n\t\t}\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\tif ( !isRealHandle.Node() || addNewTag){\n\n\t\t\tfor(int i=tokens.size()-1;i>=x;i--){\n\t\t\t\tif (i == tokens.size()-1){\n\t\t\t\t\telements[i]->InsertEndChild(Value);\n\t\t\t\t} else {\n\t\t\t\t\telements[i]->InsertEndChild(*(elements[i+1]));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttagHandle.ToNode()->InsertEndChild(*(elements[x]));\n\n\t\t\tbreak;\n\n\t\t} else {\n\t\t\t tagHandle = isRealHandle;\n\t\t\t if (x == tokens.size()-1){\n\t\t\t\t\/\/ what we want to change : TiXmlHandle valHandle = tagHandle.Child( 0 );\n\t\t\t\ttagHandle.ToNode()->Clear();\n\t\t\t\ttagHandle.ToNode()->InsertEndChild(Value);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t\/\/lets count how many tags with our name exist so we can return an index\n\n\t\/\/ripped from tinyXML as doing this ourselves once is a LOT! faster\n\t\/\/than having this called n number of times in a while loop - we go from n*n iterations to n iterations\n\tint numSameTags;\n\tTiXmlElement* child = ( storedHandle->FirstChildElement( tokens.at(0) ) ).Element();\n\tfor (numSameTags = 0; child; child = child->NextSiblingElement( tokens.at(0) ), ++numSameTags){\n\t\t\/\/nothing\n\t}\n\n\t\/\/now, clear that vector!\n\ttokens.clear();\n\n\treturn numSameTags;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, int value, int which){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%i\", value);\n\tint tagID = writeTag(tag, valueStr, which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, double value, int which){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%f\", value);\n\tint tagID = writeTag(tag, valueStr, which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, string value, int which){\n\tint tagID = writeTag(tag, (char *)value.c_str(), which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, int value){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%i\", value);\n\tint tagID = writeTag(tag, valueStr, -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, double value){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%f\", value);\n\tint tagID = writeTag(tag, valueStr, -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, string value){\n\tint tagID = writeTag(tag, (char *)value.c_str(), -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addTag(string tag){\n\tint tagID = writeTag(tag, \"\", -1) -1;\n\treturn tagID;\n}\n<commit_msg>getting rid of some warnings by casting size of vectors to int<commit_after>#include \"ofxXmlSettings.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/----------------------------------------\n\/\/ a pretty useful tokenization system:\nstatic vector<string> tokenize(const string & str, const string & delim);\nstatic vector<string> tokenize(const string & str, const string & delim)\n{\n vector<string> tokens;\n\n size_t p0 = 0, p1 = string::npos;\n while(p0 != string::npos)\n {\n p1 = str.find_first_of(delim, p0);\n if(p1 != p0)\n {\n string token = str.substr(p0, p1 - p0);\n tokens.push_back(token);\n }\n p0 = str.find_first_not_of(delim, p1);\n }\n return tokens;\n}\n\/\/----------------------------------------\n\n\nofxXmlSettings::ofxXmlSettings(){\n\tstoredHandle\t= new TiXmlHandle(NULL);\n\tlevel\t\t\t= 0;\n\t\/\/we do this so that we have a valid handle\n\t\/\/without the need for loadFile\n\t*storedHandle = TiXmlHandle(&doc);\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::setVerbose(bool _verbose){\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::clear(){\n\t\/\/we clear from our root level\n\t\/\/this is usually the document\n\t\/\/but if we are pushed - it could\n\t\/\/be all the tags inside of the pushed\n\t\/\/node - including the node itself!\n\n\tstoredHandle->ToNode()->Clear();\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::loadFile(string xmlFile){\n\n\txmlFile = ofToDataPath(xmlFile);\n\n\tbool loadOkay = doc.LoadFile(xmlFile.c_str());\n\n\t\/\/theo removed bool check as it would\n\t\/\/return false if the file exists but was\n\t\/\/empty\n\n \/\/our push pop level should be set to 0!\n\tlevel = 0;\n\n\t*storedHandle = TiXmlHandle(&doc);\n\treturn loadOkay;\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::saveFile(string xmlFile){\n\n\txmlFile = ofToDataPath(xmlFile);\n\tdoc.SaveFile(xmlFile.c_str());\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::clearTagContents(string tag, int which){\n\t\/\/we check it first to see if it exists\n\t\/\/otherwise setValue will make a new empty tag\n\tif( tagExists(tag, which) )setValue(tag, \"\", which);\n}\n\n\/\/---------------------------------------------------------\nvoid ofxXmlSettings::removeTag(string tag, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\t\/\/no tags so we return\n\tif( tokens.size() == 0 ) return;\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tif(which < 0) which = 0;\n\n\tfor(int x=0;x<(int)tokens.size();x++){\n\n\t\t\/\/we only support multi tags\n\t\t\/\/with same name at root level\n\t\tif(x > 0) which = 0;\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\tif ( !isRealHandle.Node() ) break;\n\t\telse{\n\t\t\tif (x == (int)tokens.size()-1){\n\t\t\t\t\/\/if we are at the last tag and it exists\n\t\t\t\t\/\/we use its parent to remove it - haha\n\t\t\t\ttagHandle.ToNode()->RemoveChild( isRealHandle.ToNode() );\n\t\t\t}\n\t\t\ttagHandle = isRealHandle;\n\t\t}\n\t}\n\n\ttokens.clear();\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getValue(string tag, int defaultValue, int which){\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tint returnValue = defaultValue;\n\n\tif (readTag(tag, tempStr, which)){\n\t\treturnValue = strtol(tempStr, NULL, 0);\n\t}\n\tdelete tempStr;\n\treturn returnValue;\n}\n\n\/\/---------------------------------------------------------\nfloat ofxXmlSettings::getValue(string tag, double defaultValue, int which){\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tfloat returnValue = defaultValue;\n\n\tif (readTag(tag, tempStr, which)){\n\t\treturnValue = strtod(tempStr, NULL);\n\t}\n\tdelete tempStr;\n\treturn returnValue;\n}\n\n\/\/---------------------------------------------------------\nstring ofxXmlSettings::getValue(string tag, string defaultValue, int which){\n\n\t\/\/ lots of char *, string kung-fu here...\n\n\tchar * tempStr = new char[MAX_TAG_VALUE_LENGTH_IN_CHARS];\n\tmemset(tempStr, 0, MAX_TAG_VALUE_LENGTH_IN_CHARS);\n\tchar * returnPtr = (char *) defaultValue.c_str();\n\tif (readTag(tag, tempStr, which)){\n\t\treturnPtr = tempStr;\n\t}\n\tstring returnString(returnPtr);\n\tdelete tempStr;\n\treturn returnString;\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::readTag(string tag, char * valueString, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\tTiXmlHandle tagHandle = *storedHandle;\n\tfor(int x=0;x<(int)tokens.size();x++){\n\t\tif(x == 0)tagHandle = tagHandle.ChildElement(tokens.at(x), which);\n\t\telse tagHandle = tagHandle.FirstChildElement( tokens.at(x) );\n\t}\n\n\t\/\/ once we've walked, let's get that value...\n\tTiXmlHandle valHandle = tagHandle.Child( 0 );\n\n \/\/now, clear that vector!\n\ttokens.clear();\n\n \/\/ if that value is really text, let's get the value out of it !\n if (valHandle.Text()){\n \tint maxLen = MIN(MAX_TAG_VALUE_LENGTH_IN_CHARS, strlen(valHandle.Text()->Value()));\n \tmemcpy(valueString, valHandle.Text()->Value(), maxLen);\n \treturn true;\n } else {\n\t\treturn false;\n\t}\n}\n\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::pushTag(string tag, int which){\n\n\tint pos = tag.find(\":\");\n\n\tif(pos > 0){\n\t\ttag = tag.substr(0,pos);\n\t}\n\n\t\/\/we only allow to push one tag at a time.\n\tTiXmlHandle isRealHandle = storedHandle->ChildElement(tag, which);\n\n\tif( isRealHandle.Node() ){\n\t\t*storedHandle = isRealHandle;\n\t\tlevel++;\n\t\treturn true;\n\t}else{\n\t\tprintf(\"pushTag - tag not found\\n\");\n\t}\n\n\treturn false;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::popTag(){\n\n\tif(level >= 1){\n\t\tTiXmlHandle parent( (storedHandle->ToNode() )->Parent() );\n\t\t*storedHandle = parent;\n\t\tlevel--;\n\t}else{\n\t\t*storedHandle = TiXmlHandle(&doc);\n\t\tlevel = 0;\n\t}\n\n\treturn level;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getPushLevel(){\n\treturn level;\n}\n\n\/\/---------------------------------------------------------\nbool ofxXmlSettings::tagExists(string tag, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\tbool found = false;\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tif(which < 0) which = 0;\n\n\tfor(int x=0;x<(int)tokens.size();x++){\n\n\t\t\/\/we only support multi tags\n\t\t\/\/with same name at root level\n\t\tif(x > 0) which = 0;\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\t\/\/as soon as we find a tag that doesn't exist\n\t\t\/\/we return false;\n\t\tif ( !isRealHandle.Node() ){\n\t\t\tfound = false;\n\t\t\tbreak;\n\t\t}\n\t\telse{\n\t\t\tfound = true;\n\t\t\ttagHandle = isRealHandle;\n\t\t}\n\t}\n\n\ttokens.clear();\n\n\treturn found;\n}\n\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::getNumTags(string tag){\n\t\/\/this only works for tags at the current root level\n\n\tint pos = tag.find(\":\");\n\n\tif(pos > 0){\n\t\ttag = tag.substr(0,pos);\n\t}\n\n\t\/\/grab the handle from the level we are at\n\t\/\/normally this is the doc but could be a pushed node\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tint count = 0;\n\n\t\/\/ripped from tinyXML as doing this ourselves once is a LOT! faster\n\t\/\/than having this called n number of times in a while loop - we go from n*n iterations to n iterations\n\n\tTiXmlElement* child = ( storedHandle->FirstChildElement( tag ) ).Element();\n\tfor (count = 0; child; child = child->NextSiblingElement( tag ), ++count){\n\t\t\/\/nothing\n\t}\n\n\treturn count;\n}\n\n\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::writeTag(string tag, char * valueStr, int which){\n\n\tvector<string> tokens = tokenize(tag,\":\");\n\n\t\/\/ allocate then clean up :\n\tTiXmlElement ** elements = new TiXmlElement*[tokens.size()];\n\tfor(int x=0;x<(int)tokens.size();x++){\n\t\telements[x] = new TiXmlElement(tokens.at(x));\n\t}\n\n\tTiXmlText Value(valueStr);\n\n\t\/\/ search our way up - do these tags exist?\n\t\/\/ find the first that DOESNT exist, then move backwards...\n\tTiXmlHandle tagHandle = *storedHandle;\n\n\tbool addNewTag = false;\n\tif(which == -1)addNewTag = true;\n\n\tfor(int x=0;x<(int)tokens.size();x++){\n\n\t\tif( x > 0 ){\n\t\t\t\/\/multi tags of same name\n\t\t\t\/\/only for the root level\n\t\t\twhich = 0;\n\t\t\taddNewTag = false;\n\t\t}\n\n\t\tTiXmlHandle isRealHandle = tagHandle.ChildElement( tokens.at(x), which);\n\n\t\tif ( !isRealHandle.Node() || addNewTag){\n\n\t\t\tfor(int i=tokens.size()-1;i>=x;i--){\n\t\t\t\tif (i == (int)tokens.size()-1){\n\t\t\t\t\telements[i]->InsertEndChild(Value);\n\t\t\t\t} else {\n\t\t\t\t\telements[i]->InsertEndChild(*(elements[i+1]));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttagHandle.ToNode()->InsertEndChild(*(elements[x]));\n\n\t\t\tbreak;\n\n\t\t} else {\n\t\t\t tagHandle = isRealHandle;\n\t\t\t if (x == (int)tokens.size()-1){\n\t\t\t\t\/\/ what we want to change : TiXmlHandle valHandle = tagHandle.Child( 0 );\n\t\t\t\ttagHandle.ToNode()->Clear();\n\t\t\t\ttagHandle.ToNode()->InsertEndChild(Value);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t\/\/lets count how many tags with our name exist so we can return an index\n\n\t\/\/ripped from tinyXML as doing this ourselves once is a LOT! faster\n\t\/\/than having this called n number of times in a while loop - we go from n*n iterations to n iterations\n\tint numSameTags;\n\tTiXmlElement* child = ( storedHandle->FirstChildElement( tokens.at(0) ) ).Element();\n\tfor (numSameTags = 0; child; child = child->NextSiblingElement( tokens.at(0) ), ++numSameTags){\n\t\t\/\/nothing\n\t}\n\n\t\/\/now, clear that vector!\n\ttokens.clear();\n\n\treturn numSameTags;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, int value, int which){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%i\", value);\n\tint tagID = writeTag(tag, valueStr, which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, double value, int which){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%f\", value);\n\tint tagID = writeTag(tag, valueStr, which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::setValue(string tag, string value, int which){\n\tint tagID = writeTag(tag, (char *)value.c_str(), which) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, int value){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%i\", value);\n\tint tagID = writeTag(tag, valueStr, -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, double value){\n\tchar valueStr[255];\n\tsprintf(valueStr, \"%f\", value);\n\tint tagID = writeTag(tag, valueStr, -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addValue(string tag, string value){\n\tint tagID = writeTag(tag, (char *)value.c_str(), -1) -1;\n\treturn tagID;\n}\n\n\/\/---------------------------------------------------------\nint ofxXmlSettings::addTag(string tag){\n\tint tagID = writeTag(tag, \"\", -1) -1;\n\treturn tagID;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <service>\n#include <net\/interfaces>\n#include <net\/router.hpp>\nusing namespace net;\n\nstatic std::unique_ptr<Router<IP6>> router;\n\nstatic bool\nroute_checker(IP6::addr addr)\n{\n INFO(\"Route checker\", \"asked for route to IP %s\", addr.to_string().c_str());\n\n bool have_route = router->route_check(addr);\n\n INFO(\"Route checker\", \"The router says %i\", have_route);\n\n if (have_route)\n INFO2(\"* Responding YES\");\n else\n INFO2(\"* Responding NO\");\n\n return have_route;\n}\n\nstatic void\nip_forward (IP6::IP_packet_ptr pckt, Inet& stack, Conntrack::Entry_ptr)\n{\n Inet* route = router->get_first_interface(pckt->ip_dst());\n\n if (not route){\n INFO(\"ip_fwd\", \"No route found for %s dropping\\n\", pckt->ip_dst().to_string().c_str());\n return;\n }\n\n if (route == &stack) {\n INFO(\"ip_fwd\", \"* Oh, this packet was for me, so why was it forwarded here? \\n\");\n return;\n }\n\n debug(\"[ ip_fwd ] %s transmitting packet to %s\",stack.ifname().c_str(), route->ifname().c_str());\n route->ip6_obj().ship(std::move(pckt));\n}\n\n\nvoid Service::start(const std::string&)\n{\n auto& inet = Interfaces::get(0);\n inet.network_config6({ 0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x85cd }, \/\/ IP\n 112, \/\/ Prefix6\n { 0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x83e7 }); \/\/ Gateway\n\n INFO(\"Router\",\"Interface 1 IP: %s\\n\", inet.ip6_addr().str().c_str());\n\n auto& inet2 = Interfaces::get(1);\n inet2.network_config6({ 0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0x5678 }, \/\/ IP\n 112, \/\/ Prefix6\n { 0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0x8367}); \/\/ Gateway\n\n INFO(\"Router\",\"Interface2 IP: %s\\n\", inet2.ip6_addr().str().c_str());\n\n\n \/\/ IP Forwarding\n inet.ip6_obj().set_packet_forwarding(ip_forward);\n inet2.ip6_obj().set_packet_forwarding(ip_forward);\n\n \/\/ NDP Route checker\n inet.set_route_checker6(route_checker);\n inet2.set_route_checker6(route_checker);\n\n \/\/ Routing table\n Router<IP6>::Routing_table routing_table{\n {{0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0 }, 112,\n {0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0x8367}, inet2 , 1 },\n {{ 0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0}, 112,\n {0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x83e7}, inet , 1 }\n };\n\n router = std::make_unique<Router<IP6>>(routing_table);\n\n INFO(\"Router\", \"Routing enabled - routing table:\");\n\n for (auto r : routing_table)\n INFO2(\"* %s\/%i -> %s \/ %s, cost %i\", r.net().str().c_str(),\n __builtin_popcount(r.netmask()),\n r.interface()->ifname().c_str(),\n r.nexthop().to_string().c_str(),\n r.cost());\n printf(\"\\n\");\n INFO(\"Router\",\"Service ready\");\n}\n<commit_msg>test: Use correct way to configure network in router6<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <service>\n#include <net\/interfaces>\n#include <net\/router.hpp>\nusing namespace net;\n\nstatic std::unique_ptr<Router<IP6>> router;\n\nstatic bool\nroute_checker(IP6::addr addr)\n{\n INFO(\"Route checker\", \"asked for route to IP %s\", addr.to_string().c_str());\n\n bool have_route = router->route_check(addr);\n\n INFO(\"Route checker\", \"The router says %i\", have_route);\n\n if (have_route)\n INFO2(\"* Responding YES\");\n else\n INFO2(\"* Responding NO\");\n\n return have_route;\n}\n\nstatic void\nip_forward (IP6::IP_packet_ptr pckt, Inet& stack, Conntrack::Entry_ptr)\n{\n Inet* route = router->get_first_interface(pckt->ip_dst());\n\n if (not route){\n INFO(\"ip_fwd\", \"No route found for %s dropping\\n\", pckt->ip_dst().to_string().c_str());\n return;\n }\n\n if (route == &stack) {\n INFO(\"ip_fwd\", \"* Oh, this packet was for me, so why was it forwarded here? \\n\");\n return;\n }\n\n debug(\"[ ip_fwd ] %s transmitting packet to %s\",stack.ifname().c_str(), route->ifname().c_str());\n route->ip6_obj().ship(std::move(pckt));\n}\n\n\nvoid Service::start(const std::string&)\n{\n auto& inet = Interfaces::get(0);\n inet.add_addr({\"fe80::e823:fcff:fef4:85cd\"}, 112);\n \/\/inet.ndp().add_router({\"fe80::e823:fcff:fef4:83e7\"}, 0xffff);\n\n INFO(\"Router\",\"Interface 1 IP: %s\\n\", inet.ip6_addr().str().c_str());\n\n auto& inet2 = Interfaces::get(1);\n inet2.add_addr({\"fe80::abcd:abcd:1234:5678\"}, 112);\n \/\/inet2.ndp().add_router({\"fe80::abcd:abcd:1234:8367\"}, 0xffff);\n\n INFO(\"Router\",\"Interface2 IP: %s\\n\", inet2.ip6_addr().str().c_str());\n\n\n \/\/ IP Forwarding\n inet.ip6_obj().set_packet_forwarding(ip_forward);\n inet2.ip6_obj().set_packet_forwarding(ip_forward);\n\n \/\/ NDP Route checker\n inet.set_route_checker6(route_checker);\n inet2.set_route_checker6(route_checker);\n\n \/\/ Routing table\n Router<IP6>::Routing_table routing_table{\n {{0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0 }, 112,\n {0xfe80, 0, 0, 0, 0xabcd, 0xabcd, 0x1234, 0x8367}, inet2 , 1 },\n {{ 0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0}, 112,\n {0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x83e7}, inet , 1 }\n };\n\n router = std::make_unique<Router<IP6>>(routing_table);\n\n INFO(\"Router\", \"Routing enabled - routing table:\");\n\n for (auto r : routing_table)\n INFO2(\"* %s\/%i -> %s \/ %s, cost %i\", r.net().str().c_str(),\n __builtin_popcount(r.netmask()),\n r.interface()->ifname().c_str(),\n r.nexthop().to_string().c_str(),\n r.cost());\n printf(\"\\n\");\n INFO(\"Router\",\"Service ready\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <assert.h>\n#include \"lms7002_mainPanel.h\"\n#include \"lms7002_pnlAFE_view.h\"\n#include \"lms7002_pnlBIAS_view.h\"\n#include \"lms7002_pnlBIST_view.h\"\n#include \"lms7002_pnlCDS_view.h\"\n#include \"lms7002_pnlCLKGEN_view.h\"\n#include \"lms7002_pnlLDO_view.h\"\n#include \"lms7002_pnlLimeLightPAD_view.h\"\n#include \"lms7002_pnlTxTSP_view.h\"\n#include \"lms7002_pnlRxTSP_view.h\"\n#include \"lms7002_pnlRBB_view.h\"\n#include \"lms7002_pnlRFE_view.h\"\n#include \"lms7002_pnlSX_view.h\"\n#include \"lms7002_pnlTBB_view.h\"\n#include \"lms7002_pnlTRF_view.h\"\n#include \"lms7002_pnlXBUF_view.h\"\n#include \"lms7002_pnlCalibrations_view.h\"\n#include \"LMS7002M.h\"\n#include \"ErrorReporting.h\"\n#include <wx\/time.h>\n#include <wx\/msgdlg.h>\n#include <iostream>\n#include <wx\/filedlg.h>\n#include \"lms7suiteEvents.h\"\n#include \"lms7002_pnlMCU_BD_view.h\"\n#include \"lms7002_pnlBuffers_view.h\"\nusing namespace std;\nusing namespace lime;\n\nlms7002_mainPanel::lms7002_mainPanel(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)\n :\n mainPanel(parent, id, pos, size, style), lmsControl(nullptr)\n{\n mTabMCU = new lms7002_pnlMCU_BD_view(tabsNotebook);\n tabsNotebook->AddPage(mTabMCU, _(\"MCU\"));\n}\n\nlms7002_mainPanel::~lms7002_mainPanel()\n{\n}\n\nvoid lms7002_mainPanel::UpdateVisiblePanel()\n{\n wxLongLong t1, t2;\n t1 = wxGetUTCTimeMillis();\n long visibleTabId = tabsNotebook->GetCurrentPage()->GetId();\n switch (visibleTabId)\n {\n case ID_TAB_AFE:\n mTabAFE->UpdateGUI();\n break;\n case ID_TAB_BIAS:\n mTabBIAS->UpdateGUI();\n break;\n case ID_TAB_BIST:\n mTabBIST->UpdateGUI();\n break;\n case ID_TAB_CDS:\n mTabCDS->UpdateGUI();\n break;\n case ID_TAB_CGEN:\n mTabCGEN->UpdateGUI();\n break;\n case ID_TAB_LDO:\n mTabLDO->UpdateGUI();\n break;\n case ID_TAB_LIMELIGHT:\n mTabLimeLight->UpdateGUI();\n break;\n case ID_TAB_TXTSP:\n mTabTxTSP->UpdateGUI();\n break;\n case ID_TAB_RXTSP:\n mTabRxTSP->UpdateGUI();\n break;\n case ID_TAB_RBB:\n mTabRBB->UpdateGUI();\n break;\n case ID_TAB_RFE:\n mTabRFE->UpdateGUI();\n break;\n case ID_TAB_SXR:\n mTabSXR->UpdateGUI();\n break;\n case ID_TAB_SXT:\n mTabSXT->UpdateGUI();\n break;\n case ID_TAB_TBB:\n mTabTBB->UpdateGUI();\n break;\n case ID_TAB_TRF:\n mTabTRF->UpdateGUI();\n break;\n case ID_TAB_XBUF:\n mTabXBUF->UpdateGUI();\n break;\n case ID_TAB_CALIBRATIONS:\n mTabCalibrations->UpdateGUI();\n break;\n case ID_TAB_BUFFERS:\n mTabBuffers->UpdateGUI();\n break;\n }\n t2 = wxGetUTCTimeMillis();\n#ifndef NDEBUG\n cout << \"Visible GUI update time: \" << (t2 - t1).ToString() << endl;\n#endif\n}\n\nvoid lms7002_mainPanel::Initialize(LMS7002M* pControl)\n{\n assert(pControl != nullptr);\n lmsControl = pControl;\n mTabRFE->Initialize(lmsControl);\n mTabRBB->Initialize(lmsControl);\n mTabTRF->Initialize(lmsControl);\n mTabTBB->Initialize(lmsControl);\n mTabAFE->Initialize(lmsControl);\n mTabBIAS->Initialize(lmsControl);\n mTabLDO->Initialize(lmsControl);\n mTabXBUF->Initialize(lmsControl);\n mTabCGEN->Initialize(lmsControl);\n mTabSXR->Initialize(lmsControl);\n mTabSXT->Initialize(lmsControl);\n mTabLimeLight->Initialize(lmsControl);\n mTabTxTSP->Initialize(lmsControl);\n mTabRxTSP->Initialize(lmsControl);\n mTabCDS->Initialize(lmsControl);\n mTabBIST->Initialize(lmsControl);\n mTabCalibrations->Initialize(lmsControl);\n mTabMCU->Initialize(lmsControl->GetMCUControls());\n\/\/ TODO setup buffers gui\n \/\/mTabBuffers->Initialize(lmsControl->GetControlPort());\n UpdateGUI();\n}\n\nvoid lms7002_mainPanel::OnResetChip(wxCommandEvent &event)\n{\n int status = lmsControl->ResetChip();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Chip reset: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n wxNotebookEvent evt;\n Onnotebook_modulesPageChanged(evt); \/\/after reset chip active channel might change, this refresh channel for active tab\n}\n\nvoid lms7002_mainPanel::UpdateGUI()\n{\n wxLongLong t1, t2;\n t1 = wxGetUTCTimeMillis();\n lmsControl->IsSynced();\n t2 = wxGetUTCTimeMillis();\n LMS7002M::Channel channel = lmsControl->GetActiveChannel();\n if (channel == LMS7002M::ChA)\n {\n rbChannelA->SetValue(true);\n rbChannelB->SetValue(false);\n }\n else if (channel == LMS7002M::ChB)\n {\n rbChannelA->SetValue(false);\n rbChannelB->SetValue(true);\n }\n else\n {\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n rbChannelA->SetValue(true);\n rbChannelB->SetValue(false);\n }\n\n UpdateVisiblePanel();\n#ifndef NDEBUG\n cout << \"GUI update time: \" << (t2 - t1).ToString() << endl;\n#endif\n}\n\nvoid lms7002_mainPanel::OnNewProject( wxCommandEvent& event )\n{\n lmsControl->ResetChip();\n lmsControl->DownloadAll();\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n UpdateGUI();\n}\n\nvoid lms7002_mainPanel::OnOpenProject( wxCommandEvent& event )\n{\n wxFileDialog dlg(this, _(\"Open config file\"), \"\", \"\", \"Project-File (*.ini)|*.ini\", wxFD_OPEN | wxFD_FILE_MUST_EXIST);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n int status = lmsControl->LoadConfig(dlg.GetPath().To8BitData());\n if (status != 0)\n {\n if (lmsControl->GetConnection() == nullptr)\n wxMessageBox(wxString::Format(_(\"Failed to load file: %s\"), GetLastErrorMessage()), _(\"Warning\"));\n }\n wxCommandEvent tevt;\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n UpdateGUI();\n wxCommandEvent evt;\n evt.SetEventType(CGEN_FREQUENCY_CHANGED);\n wxPostEvent(this, evt);\n}\n\nvoid lms7002_mainPanel::OnSaveProject( wxCommandEvent& event )\n{\n wxFileDialog dlg(this, _(\"Save config file\"), \"\", \"\", \"Project-File (*.ini)|*.ini\", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n int status = lmsControl->SaveConfig(dlg.GetPath().To8BitData());\n if (status != 0)\n wxMessageBox(_(\"Failed to save file\"), _(\"Warning\"));\n}\n\nvoid lms7002_mainPanel::OnRegistersTest( wxCommandEvent& event )\n{\n int status = lmsControl->RegistersTest();\n if (status != 0)\n wxMessageBox(_(\"Registers test failed!\"), _(\"WARNING\"));\n else\n wxMessageBox(_(\"Registers test passed!\"), _(\"INFO\"));\n}\n\nvoid lms7002_mainPanel::OnSwitchToChannelA(wxCommandEvent& event)\n{\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnSwitchToChannelB(wxCommandEvent& event)\n{\n lmsControl->SetActiveChannel(LMS7002M::ChB);\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::Onnotebook_modulesPageChanged( wxNotebookEvent& event )\n{\n wxNotebookPage* page = tabsNotebook->GetCurrentPage();\n if (page == mTabAFE || page == mTabBIAS || page == mTabLDO || page == mTabXBUF || page == mTabCGEN || page == mTabCDS || page == mTabBIST)\n {\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else if (page == mTabSXR) \/\/change active channel to A\n {\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else if (page == mTabSXT) \/\/change active channel to B\n {\n lmsControl->SetActiveChannel(LMS7002M::ChB);\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else\n {\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n rbChannelA->Enable();\n rbChannelB->Enable();\n }\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnDownloadAll(wxCommandEvent& event)\n{\n int status = lmsControl->DownloadAll();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Download all registers: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnUploadAll(wxCommandEvent& event)\n{\n int status = lmsControl->UploadAll();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Upload all registers: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n wxCommandEvent evt;\n evt.SetEventType(CGEN_FREQUENCY_CHANGED);\n wxPostEvent(this, evt);\n UpdateVisiblePanel();\n}\n<commit_msg>fix notebook page show on osx<commit_after>#include <assert.h>\n#include \"lms7002_mainPanel.h\"\n#include \"lms7002_pnlAFE_view.h\"\n#include \"lms7002_pnlBIAS_view.h\"\n#include \"lms7002_pnlBIST_view.h\"\n#include \"lms7002_pnlCDS_view.h\"\n#include \"lms7002_pnlCLKGEN_view.h\"\n#include \"lms7002_pnlLDO_view.h\"\n#include \"lms7002_pnlLimeLightPAD_view.h\"\n#include \"lms7002_pnlTxTSP_view.h\"\n#include \"lms7002_pnlRxTSP_view.h\"\n#include \"lms7002_pnlRBB_view.h\"\n#include \"lms7002_pnlRFE_view.h\"\n#include \"lms7002_pnlSX_view.h\"\n#include \"lms7002_pnlTBB_view.h\"\n#include \"lms7002_pnlTRF_view.h\"\n#include \"lms7002_pnlXBUF_view.h\"\n#include \"lms7002_pnlCalibrations_view.h\"\n#include \"LMS7002M.h\"\n#include \"ErrorReporting.h\"\n#include <wx\/time.h>\n#include <wx\/msgdlg.h>\n#include <iostream>\n#include <wx\/filedlg.h>\n#include \"lms7suiteEvents.h\"\n#include \"lms7002_pnlMCU_BD_view.h\"\n#include \"lms7002_pnlBuffers_view.h\"\nusing namespace std;\nusing namespace lime;\n\nlms7002_mainPanel::lms7002_mainPanel(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)\n :\n mainPanel(parent, id, pos, size, style), lmsControl(nullptr)\n{\n mTabMCU = new lms7002_pnlMCU_BD_view(tabsNotebook);\n tabsNotebook->AddPage(mTabMCU, _(\"MCU\"));\n}\n\nlms7002_mainPanel::~lms7002_mainPanel()\n{\n}\n\nvoid lms7002_mainPanel::UpdateVisiblePanel()\n{\n wxLongLong t1, t2;\n t1 = wxGetUTCTimeMillis();\n long visibleTabId = tabsNotebook->GetCurrentPage()->GetId();\n switch (visibleTabId)\n {\n case ID_TAB_AFE:\n mTabAFE->UpdateGUI();\n break;\n case ID_TAB_BIAS:\n mTabBIAS->UpdateGUI();\n break;\n case ID_TAB_BIST:\n mTabBIST->UpdateGUI();\n break;\n case ID_TAB_CDS:\n mTabCDS->UpdateGUI();\n break;\n case ID_TAB_CGEN:\n mTabCGEN->UpdateGUI();\n break;\n case ID_TAB_LDO:\n mTabLDO->UpdateGUI();\n break;\n case ID_TAB_LIMELIGHT:\n mTabLimeLight->UpdateGUI();\n break;\n case ID_TAB_TXTSP:\n mTabTxTSP->UpdateGUI();\n break;\n case ID_TAB_RXTSP:\n mTabRxTSP->UpdateGUI();\n break;\n case ID_TAB_RBB:\n mTabRBB->UpdateGUI();\n break;\n case ID_TAB_RFE:\n mTabRFE->UpdateGUI();\n break;\n case ID_TAB_SXR:\n mTabSXR->UpdateGUI();\n break;\n case ID_TAB_SXT:\n mTabSXT->UpdateGUI();\n break;\n case ID_TAB_TBB:\n mTabTBB->UpdateGUI();\n break;\n case ID_TAB_TRF:\n mTabTRF->UpdateGUI();\n break;\n case ID_TAB_XBUF:\n mTabXBUF->UpdateGUI();\n break;\n case ID_TAB_CALIBRATIONS:\n mTabCalibrations->UpdateGUI();\n break;\n case ID_TAB_BUFFERS:\n mTabBuffers->UpdateGUI();\n break;\n }\n t2 = wxGetUTCTimeMillis();\n#ifndef NDEBUG\n cout << \"Visible GUI update time: \" << (t2 - t1).ToString() << endl;\n#endif\n}\n\nvoid lms7002_mainPanel::Initialize(LMS7002M* pControl)\n{\n assert(pControl != nullptr);\n lmsControl = pControl;\n mTabRFE->Initialize(lmsControl);\n mTabRBB->Initialize(lmsControl);\n mTabTRF->Initialize(lmsControl);\n mTabTBB->Initialize(lmsControl);\n mTabAFE->Initialize(lmsControl);\n mTabBIAS->Initialize(lmsControl);\n mTabLDO->Initialize(lmsControl);\n mTabXBUF->Initialize(lmsControl);\n mTabCGEN->Initialize(lmsControl);\n mTabSXR->Initialize(lmsControl);\n mTabSXT->Initialize(lmsControl);\n mTabLimeLight->Initialize(lmsControl);\n mTabTxTSP->Initialize(lmsControl);\n mTabRxTSP->Initialize(lmsControl);\n mTabCDS->Initialize(lmsControl);\n mTabBIST->Initialize(lmsControl);\n mTabCalibrations->Initialize(lmsControl);\n mTabMCU->Initialize(lmsControl->GetMCUControls());\n\/\/ TODO setup buffers gui\n \/\/mTabBuffers->Initialize(lmsControl->GetControlPort());\n UpdateGUI();\n}\n\nvoid lms7002_mainPanel::OnResetChip(wxCommandEvent &event)\n{\n int status = lmsControl->ResetChip();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Chip reset: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n wxNotebookEvent evt;\n Onnotebook_modulesPageChanged(evt); \/\/after reset chip active channel might change, this refresh channel for active tab\n}\n\nvoid lms7002_mainPanel::UpdateGUI()\n{\n wxLongLong t1, t2;\n t1 = wxGetUTCTimeMillis();\n lmsControl->IsSynced();\n t2 = wxGetUTCTimeMillis();\n LMS7002M::Channel channel = lmsControl->GetActiveChannel();\n if (channel == LMS7002M::ChA)\n {\n rbChannelA->SetValue(true);\n rbChannelB->SetValue(false);\n }\n else if (channel == LMS7002M::ChB)\n {\n rbChannelA->SetValue(false);\n rbChannelB->SetValue(true);\n }\n else\n {\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n rbChannelA->SetValue(true);\n rbChannelB->SetValue(false);\n }\n\n UpdateVisiblePanel();\n#ifndef NDEBUG\n cout << \"GUI update time: \" << (t2 - t1).ToString() << endl;\n#endif\n}\n\nvoid lms7002_mainPanel::OnNewProject( wxCommandEvent& event )\n{\n lmsControl->ResetChip();\n lmsControl->DownloadAll();\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n UpdateGUI();\n}\n\nvoid lms7002_mainPanel::OnOpenProject( wxCommandEvent& event )\n{\n wxFileDialog dlg(this, _(\"Open config file\"), \"\", \"\", \"Project-File (*.ini)|*.ini\", wxFD_OPEN | wxFD_FILE_MUST_EXIST);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n int status = lmsControl->LoadConfig(dlg.GetPath().To8BitData());\n if (status != 0)\n {\n if (lmsControl->GetConnection() == nullptr)\n wxMessageBox(wxString::Format(_(\"Failed to load file: %s\"), GetLastErrorMessage()), _(\"Warning\"));\n }\n wxCommandEvent tevt;\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n UpdateGUI();\n wxCommandEvent evt;\n evt.SetEventType(CGEN_FREQUENCY_CHANGED);\n wxPostEvent(this, evt);\n}\n\nvoid lms7002_mainPanel::OnSaveProject( wxCommandEvent& event )\n{\n wxFileDialog dlg(this, _(\"Save config file\"), \"\", \"\", \"Project-File (*.ini)|*.ini\", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);\n if (dlg.ShowModal() == wxID_CANCEL)\n return;\n int status = lmsControl->SaveConfig(dlg.GetPath().To8BitData());\n if (status != 0)\n wxMessageBox(_(\"Failed to save file\"), _(\"Warning\"));\n}\n\nvoid lms7002_mainPanel::OnRegistersTest( wxCommandEvent& event )\n{\n int status = lmsControl->RegistersTest();\n if (status != 0)\n wxMessageBox(_(\"Registers test failed!\"), _(\"WARNING\"));\n else\n wxMessageBox(_(\"Registers test passed!\"), _(\"INFO\"));\n}\n\nvoid lms7002_mainPanel::OnSwitchToChannelA(wxCommandEvent& event)\n{\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnSwitchToChannelB(wxCommandEvent& event)\n{\n lmsControl->SetActiveChannel(LMS7002M::ChB);\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::Onnotebook_modulesPageChanged( wxNotebookEvent& event )\n{\n wxNotebookPage* page = tabsNotebook->GetCurrentPage();\n if (page == mTabAFE || page == mTabBIAS || page == mTabLDO || page == mTabXBUF || page == mTabCGEN || page == mTabCDS || page == mTabBIST)\n {\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else if (page == mTabSXR) \/\/change active channel to A\n {\n lmsControl->SetActiveChannel(LMS7002M::ChA);\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else if (page == mTabSXT) \/\/change active channel to B\n {\n lmsControl->SetActiveChannel(LMS7002M::ChB);\n rbChannelA->Disable();\n rbChannelB->Disable();\n }\n else\n {\n lmsControl->SetActiveChannel(rbChannelA->GetValue() == 1 ? LMS7002M::ChA : LMS7002M::ChB);\n rbChannelA->Enable();\n rbChannelB->Enable();\n }\n\n \/\/force show the page selected by the event (needed on apple)\n if (event.GetSelection() != -1)\n {\n tabsNotebook->GetPage(event.GetSelection())->Show(true);\n }\n\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnDownloadAll(wxCommandEvent& event)\n{\n int status = lmsControl->DownloadAll();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Download all registers: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n UpdateVisiblePanel();\n}\n\nvoid lms7002_mainPanel::OnUploadAll(wxCommandEvent& event)\n{\n int status = lmsControl->UploadAll();\n if (status != 0)\n wxMessageBox(wxString::Format(_(\"Upload all registers: %s\"), wxString::From8BitData(GetLastErrorMessage())), _(\"Warning\"));\n wxCommandEvent evt;\n evt.SetEventType(CGEN_FREQUENCY_CHANGED);\n wxPostEvent(this, evt);\n UpdateVisiblePanel();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"se_parser_mediawiki.h\"\n#include \"miscutil.h\"\n\n#include <strings.h>\n#include <iostream>\n\nusing sp::miscutil;\n\nnamespace seeks_plugins\n{\n std::string se_parser_mediawiki::_mediawiki_stupid[2] =\n { \"Document title\", \"Titre du document \/ Document title\" };\n\n se_parser_mediawiki::se_parser_mediawiki()\n :se_parser(),_li_sr_flag(false),_a_sr_flag(false),_search_result(false),_end_search(false)\n {\n }\n\n se_parser_mediawiki::~se_parser_mediawiki()\n {\n }\n\n void se_parser_mediawiki::start_element(parser_context *pc,\n const xmlChar *name,\n const xmlChar **attributes)\n {\n const char *tag = (const char*)name;\n\n if (strcasecmp(tag, \"ul\") == 0)\n {\n const char *a_class = se_parser::get_attribute((const char**)attributes, \"class\");\n if (a_class && strcasecmp(a_class, \"mw-search-results\") == 0)\n {\n std::cout << \"[START]\" << std::endl;\n _end_search = false;\n }\n }\n if (!_end_search && strcasecmp(tag, \"li\") == 0)\n {\n std::cout << \"<li>\" << std::endl;\n _li_sr_flag = true;\n\n \/\/ create new snippet.\n search_snippet *sp = new search_snippet(_count + 1);\n _count++;\n sp->_engine |= std::bitset<NSEs>(SE_MEDIAWIKI);\n pc->_current_snippet = sp;\n }\n if (!_end_search && strcasecmp(tag, \"a\") == 0 && _li_sr_flag)\n {\n std::cout << \"<a>\" << std::endl;\n const char *a_link = se_parser::get_attribute((const char**)attributes,\"href\");\n _link = std::string(a_link);\n _a_sr_flag = true;\n\n if (pc->_snippets->empty())\n _results_flag = true;\n }\n if (!_end_search && _li_sr_flag && strcasecmp(tag, \"div\") == 0)\n {\n const char *a_link = se_parser::get_attribute((const char**)attributes,\"class\");\n if (strcasecmp(a_link, \"searchresult\") == 0)\n {\n std::cout << \"<div class=\\\"searchresult\\\">\" << std::endl;\n _search_result = true;\n }\n }\n }\n\n void se_parser_mediawiki::characters(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n handle_characters(pc, chars, length);\n }\n\n void se_parser_mediawiki::cdata(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n handle_characters(pc, chars, length);\n }\n\n void se_parser_mediawiki::handle_characters(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n if (_a_sr_flag)\n {\n std::string a_chars = std::string((char*)chars);\n miscutil::replace_in_string(a_chars,\"\\n\",\" \");\n miscutil::replace_in_string(a_chars,\"\\r\",\" \");\n miscutil::replace_in_string(a_chars,\"-\",\" \");\n _title += a_chars;\n std::cout << _title << std::endl;\n }\n if (_search_result)\n {\n std::string a_chars = std::string((char*)chars);\n miscutil::replace_in_string(a_chars,\"\\n\",\" \");\n miscutil::replace_in_string(a_chars,\"\\r\",\" \");\n miscutil::replace_in_string(a_chars,\"-\",\" \");\n _summary += a_chars;\n std::cout << _summary << std::endl;\n }\n }\n\n void se_parser_mediawiki::end_element(parser_context *pc,\n const xmlChar *name)\n {\n const char *tag = (const char*) name;\n\n if (!_end_search && strcasecmp(tag, \"ul\") == 0)\n _end_search = true;\n\n if (!_results_flag)\n return;\n\n if (_li_sr_flag && strcasecmp(tag,\"li\") == 0)\n {\n std::cout << \"<\/li>\" << std::endl;\n _li_sr_flag = false;\n\n \/\/ assert previous snippet if any.\n if (pc->_current_snippet)\n {\n if (pc->_current_snippet->_title.empty() \/\/ consider the parsing did fail on the snippet.\n || pc->_current_snippet->_url.empty()\n || pc->_current_snippet->_summary.empty()\n || pc->_current_snippet->_cite.empty())\n {\n std::cout << \"[snippet fail]\" << \" title: \" << pc->_current_snippet->_title.empty() << \" url: \" << pc->_current_snippet->_url.empty() << \" summary: \" << pc->_current_snippet->_summary.empty() << \" cite de mes deux: \" << pc->_current_snippet->_cite.empty() << std::endl;\n delete pc->_current_snippet;\n pc->_current_snippet = NULL;\n _count--;\n }\n else pc->_snippets->push_back(pc->_current_snippet);\n }\n\n }\n\n if (_a_sr_flag && strcasecmp(tag,\"a\") == 0)\n {\n std::cout << \"<\/a>\" << std::endl;\n \/\/ TODO ici il faut rajouter le http:\/\/ jusqu'à \/wiki\/...\n pc->_current_snippet->_title = _title;\n _title = \"\";\n pc->_current_snippet->set_url(_link);\n std::cout << \"URL \" << pc->_current_snippet->_url.empty() << std::endl;\n pc->_current_snippet->_cite = _link;\n std::cout << \"url=\" << _link << std::endl;\n _link = \"\";\n _a_sr_flag = false;\n }\n\n if (_search_result && strcasecmp(tag, \"div\") == 0)\n {\n std::cout << \"<\/div>\" << std::endl;\n\n \/\/ some time, mediawiki don't give a body to it's result\n if (_summary == \"\")\n _summary = \" \";\n\n pc->_current_snippet->set_summary(_summary);\n _summary = \"\";\n _cite = \"\";\n _search_result = false;\n }\n }\n\n\n} \/* end of namespace. *\/\n<commit_msg>forget to add some stuff for the mediawiki parser<commit_after>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"se_parser_mediawiki.h\"\n#include \"miscutil.h\"\n\n#include <strings.h>\n#include <iostream>\n\nusing sp::miscutil;\n\nnamespace seeks_plugins\n{\n std::string se_parser_mediawiki::_mediawiki_stupid[2] =\n { \"Document title\", \"Titre du document \/ Document title\" };\n\n se_parser_mediawiki::se_parser_mediawiki()\n :se_parser(),_li_sr_flag(false),_a_sr_flag(false),_search_result(false),_end_search(true)\n {\n }\n\n se_parser_mediawiki::~se_parser_mediawiki()\n {\n }\n\n void se_parser_mediawiki::start_element(parser_context *pc,\n const xmlChar *name,\n const xmlChar **attributes)\n {\n const char *tag = (const char*)name;\n\n if (strcasecmp(tag, \"ul\") == 0)\n {\n const char *a_class = se_parser::get_attribute((const char**)attributes, \"class\");\n if (a_class && strcasecmp(a_class, \"mw-search-results\") == 0)\n {\n std::cout << \"[START]\" << std::endl;\n _end_search = false;\n }\n }\n if (!_end_search && strcasecmp(tag, \"li\") == 0)\n {\n std::cout << \"<li>\" << std::endl;\n _li_sr_flag = true;\n\n \/\/ create new snippet.\n search_snippet *sp = new search_snippet(_count + 1);\n _count++;\n sp->_engine |= std::bitset<NSEs>(SE_MEDIAWIKI);\n pc->_current_snippet = sp;\n }\n if (!_end_search && strcasecmp(tag, \"a\") == 0 && _li_sr_flag)\n {\n std::cout << \"<a>\" << std::endl;\n const char *a_link = se_parser::get_attribute((const char**)attributes,\"href\");\n _link = std::string(a_link);\n _a_sr_flag = true;\n\n if (pc->_snippets->empty())\n _results_flag = true;\n }\n if (!_end_search && _li_sr_flag && strcasecmp(tag, \"div\") == 0)\n {\n const char *a_link = se_parser::get_attribute((const char**)attributes,\"class\");\n if (strcasecmp(a_link, \"searchresult\") == 0)\n {\n std::cout << \"<div class=\\\"searchresult\\\">\" << std::endl;\n _search_result = true;\n }\n }\n }\n\n void se_parser_mediawiki::characters(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n handle_characters(pc, chars, length);\n }\n\n void se_parser_mediawiki::cdata(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n handle_characters(pc, chars, length);\n }\n\n void se_parser_mediawiki::handle_characters(parser_context *pc,\n const xmlChar *chars,\n int length)\n {\n if (_a_sr_flag)\n {\n std::string a_chars = std::string((char*)chars);\n miscutil::replace_in_string(a_chars,\"\\n\",\" \");\n miscutil::replace_in_string(a_chars,\"\\r\",\" \");\n miscutil::replace_in_string(a_chars,\"-\",\" \");\n _title += a_chars;\n std::cout << _title << std::endl;\n }\n if (_search_result)\n {\n std::string a_chars = std::string((char*)chars);\n miscutil::replace_in_string(a_chars,\"\\n\",\" \");\n miscutil::replace_in_string(a_chars,\"\\r\",\" \");\n miscutil::replace_in_string(a_chars,\"-\",\" \");\n _summary += a_chars;\n std::cout << _summary << std::endl;\n }\n }\n\n void se_parser_mediawiki::end_element(parser_context *pc,\n const xmlChar *name)\n {\n const char *tag = (const char*) name;\n\n if (!_end_search && strcasecmp(tag, \"ul\") == 0)\n _end_search = true;\n\n if (!_results_flag)\n return;\n\n if (_li_sr_flag && strcasecmp(tag,\"li\") == 0)\n {\n std::cout << \"<\/li>\" << std::endl;\n _li_sr_flag = false;\n\n \/\/ assert previous snippet if any.\n if (pc->_current_snippet)\n {\n if (pc->_current_snippet->_title.empty() \/\/ consider the parsing did fail on the snippet.\n || pc->_current_snippet->_url.empty()\n || pc->_current_snippet->_summary.empty()\n || pc->_current_snippet->_cite.empty())\n {\n std::cout << \"[snippet fail]\" << \" title: \" << pc->_current_snippet->_title.empty() << \" url: \" << pc->_current_snippet->_url.empty() << \" summary: \" << pc->_current_snippet->_summary.empty() << \" cite de mes deux: \" << pc->_current_snippet->_cite.empty() << std::endl;\n delete pc->_current_snippet;\n pc->_current_snippet = NULL;\n _count--;\n }\n else pc->_snippets->push_back(pc->_current_snippet);\n }\n\n }\n\n if (_a_sr_flag && strcasecmp(tag,\"a\") == 0)\n {\n std::cout << \"<\/a>\" << std::endl;\n \/\/ TODO ici il faut rajouter le http:\/\/ jusqu'à \/wiki\/...\n pc->_current_snippet->_title = _title;\n _title = \"\";\n pc->_current_snippet->set_url(_link);\n std::cout << \"URL \" << pc->_current_snippet->_url.empty() << std::endl;\n pc->_current_snippet->_cite = _link;\n std::cout << \"url=\" << _link << std::endl;\n _link = \"\";\n _a_sr_flag = false;\n }\n\n if (_search_result && strcasecmp(tag, \"div\") == 0)\n {\n std::cout << \"<\/div>\" << std::endl;\n\n \/\/ some time, mediawiki don't give a body to it's result\n if (_summary == \"\")\n _summary = \" \";\n\n pc->_current_snippet->set_summary(_summary);\n _summary = \"\";\n _cite = \"\";\n _search_result = false;\n }\n }\n\n\n} \/* end of namespace. *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include <iostream>\n\n#ifdef ZORBA_WITH_DEBUGGER\n#include \"debugger\/debugger_commons.h\"\n#endif\n#include \"functions\/udf.h\"\n#include \"runtime\/booleans\/BooleanImpl.h\"\n#include \"runtime\/collections\/collections.h\"\n#include \"runtime\/core\/apply_updates.h\"\n#include \"runtime\/core\/arithmetic_impl.h\"\n#include \"runtime\/core\/constructors.h\"\n#include \"runtime\/core\/flwor_iterator.h\"\n#include \"runtime\/core\/fncall_iterator.h\"\n#include \"runtime\/core\/gflwor\/count_iterator.h\"\n#include \"runtime\/core\/gflwor\/for_iterator.h\"\n#include \"runtime\/core\/gflwor\/groupby_iterator.h\"\n#include \"runtime\/core\/gflwor\/let_iterator.h\"\n#include \"runtime\/core\/gflwor\/outerfor_iterator.h\"\n#include \"runtime\/core\/gflwor\/tuplesource_iterator.h\"\n#include \"runtime\/core\/gflwor\/tuplestream_iterator.h\"\n#include \"runtime\/core\/gflwor\/where_iterator.h\"\n#include \"runtime\/core\/gflwor\/window_iterator.h\"\n#include \"runtime\/core\/internal_operators.h\"\n#include \"runtime\/core\/item_iterator.h\"\n#include \"runtime\/core\/nodeid_iterators.h\"\n#include \"runtime\/core\/path_iterators.h\"\n#include \"runtime\/core\/sequencetypes.h\"\n#include \"runtime\/core\/trycatch.h\"\n#include \"runtime\/core\/var_iterators.h\"\n#ifdef ZORBA_WITH_DEBUGGER\n#include \"runtime\/debug\/debug_iterator.h\"\n#endif\n#include \"runtime\/durations_dates_times\/DurationsDatesTimesImpl.h\"\n#include \"runtime\/durations_dates_times\/format_dateTime.h\"\n#include \"runtime\/eval\/eval.h\"\n#ifndef ZORBA_NO_FULL_TEXT\n#include \"runtime\/full_text\/full_text.h\"\n#endif\n#include \"runtime\/hof\/dynamic_fncall_iterator.h\"\n#include \"runtime\/hof\/function_item_iter.h\"\n#include \"runtime\/indexing\/index_ddl.h\"\n#include \"runtime\/json\/json_constructors.h\"\n#include \"runtime\/misc\/materialize.h\"\n#include \"runtime\/numerics\/NumericsImpl.h\"\n#include \"runtime\/scripting\/scripting.h\"\n#include \"runtime\/sequences\/SequencesImpl.h\"\n#include \"runtime\/update\/update.h\"\n#include \"runtime\/visitors\/profile_visitor.h\"\n\nusing namespace std;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nget_pd( PlanIterator const &pi, PlanState &p_state ) {\n PlanIteratorState const *const pi_state =\n StateTraitsImpl<PlanIteratorState>::getState(\n p_state, pi.getStateOffset()\n );\n profile_data const &pd = pi_state->get_profile_data();\n cerr << \"<iterator name=\\\"\" << pi.getNameAsString() << \"\\\" calls=\\\"\" << pd.next_.call_count_ << \"\\\" ms=\\\"\" << pd.next_.cpu_time_ << \"\\\"\/>\\n\";\n}\n\n#define PROFILE_VISITOR_DEFINITION(...) \\\n void ProfileVisitor::beginVisit( __VA_ARGS__ const &iter ) { \\\n get_pd( iter, plan_state_ ); \\\n } \\\n void ProfileVisitor::endVisit( __VA_ARGS__ const& ) { \\\n }\n\nPROFILE_VISITOR_DEFINITION( AncestorAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorSelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorSelfReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( AndIterator )\nPROFILE_VISITOR_DEFINITION( ApplyIterator )\nPROFILE_VISITOR_DEFINITION( ArgumentPlaceholderIterator )\nPROFILE_VISITOR_DEFINITION( AtomicValuesEquivalenceIterator )\nPROFILE_VISITOR_DEFINITION( AttributeAxisIterator )\nPROFILE_VISITOR_DEFINITION( AttributeIterator )\nPROFILE_VISITOR_DEFINITION( CastableIterator )\nPROFILE_VISITOR_DEFINITION( CastIterator )\nPROFILE_VISITOR_DEFINITION( ChildAxisIterator )\nPROFILE_VISITOR_DEFINITION( CommentIterator )\nPROFILE_VISITOR_DEFINITION( CompareIterator )\nPROFILE_VISITOR_DEFINITION( CreateIndexIterator )\nPROFILE_VISITOR_DEFINITION( CreateInternalIndexIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarAssignIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarDeclareIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarIsSetIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarIterator )\n#ifdef ZORBA_WITH_DEBUGGER\nPROFILE_VISITOR_DEFINITION( DebuggerSingletonIterator )\n#endif\nPROFILE_VISITOR_DEFINITION( DeleteIndexIterator )\nPROFILE_VISITOR_DEFINITION( DeleteIterator )\nPROFILE_VISITOR_DEFINITION( DescendantAxisIterator )\nPROFILE_VISITOR_DEFINITION( DescendantSelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( DocumentIterator )\nPROFILE_VISITOR_DEFINITION( EitherNodesOrAtomicsIterator )\nPROFILE_VISITOR_DEFINITION( ElementIterator )\nPROFILE_VISITOR_DEFINITION( EmptyIterator )\nPROFILE_VISITOR_DEFINITION( EnclosedIterator )\nPROFILE_VISITOR_DEFINITION( EvalIterator )\nPROFILE_VISITOR_DEFINITION( ExitCatcherIterator )\nPROFILE_VISITOR_DEFINITION( ExitIterator )\nPROFILE_VISITOR_DEFINITION( ExtFunctionCallIterator )\nPROFILE_VISITOR_DEFINITION( FlowCtlIterator )\nPROFILE_VISITOR_DEFINITION( flwor::CountIterator )\nPROFILE_VISITOR_DEFINITION( flwor::FLWORIterator )\nPROFILE_VISITOR_DEFINITION( flwor::ForIterator )\nPROFILE_VISITOR_DEFINITION( flwor::GroupByIterator )\nPROFILE_VISITOR_DEFINITION( flwor::LetIterator )\nPROFILE_VISITOR_DEFINITION( flwor::OrderByIterator )\nPROFILE_VISITOR_DEFINITION( flwor::OuterForIterator )\nPROFILE_VISITOR_DEFINITION( flwor::TupleSourceIterator )\nPROFILE_VISITOR_DEFINITION( flwor::TupleStreamIterator )\nPROFILE_VISITOR_DEFINITION( flwor::WhereIterator )\nPROFILE_VISITOR_DEFINITION( flwor::WindowIterator )\nPROFILE_VISITOR_DEFINITION( FnAdjustToTimeZoneIterator_1 )\nPROFILE_VISITOR_DEFINITION( FnAdjustToTimeZoneIterator_2 )\nPROFILE_VISITOR_DEFINITION( FnBooleanIterator )\nPROFILE_VISITOR_DEFINITION( FnDateTimeConstructorIterator )\nPROFILE_VISITOR_DEFINITION( FnFormatDateTimeIterator )\nPROFILE_VISITOR_DEFINITION( FnMinMaxIterator )\nPROFILE_VISITOR_DEFINITION( FollowingAxisIterator )\nPROFILE_VISITOR_DEFINITION( ForVarIterator )\n#ifndef ZORBA_NO_FULL_TEXT\nPROFILE_VISITOR_DEFINITION( FTContainsIterator )\n#endif\nPROFILE_VISITOR_DEFINITION( FunctionItemIterator )\nPROFILE_VISITOR_DEFINITION( GeneralIndexEntryBuilderIterator )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<AddOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<DivideOperation>)\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<IntegerDivideOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<ModOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<MultiplyOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<SubtractOperation> )\nPROFILE_VISITOR_DEFINITION( HoistIterator )\nPROFILE_VISITOR_DEFINITION( IfThenElseIterator )\nPROFILE_VISITOR_DEFINITION( InsertIterator )\nPROFILE_VISITOR_DEFINITION( InstanceOfIterator )\nPROFILE_VISITOR_DEFINITION( JSONArrayIterator )\nPROFILE_VISITOR_DEFINITION( JSONDirectObjectIterator )\nPROFILE_VISITOR_DEFINITION( JSONObjectIterator )\nPROFILE_VISITOR_DEFINITION( LetVarIterator )\nPROFILE_VISITOR_DEFINITION( LoopIterator )\nPROFILE_VISITOR_DEFINITION( LSiblingAxisIterator )\nPROFILE_VISITOR_DEFINITION( LSiblingReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( MaterializeIterator )\nPROFILE_VISITOR_DEFINITION( MultiDynamicFnCallIterator )\nPROFILE_VISITOR_DEFINITION( NameCastIterator )\nPROFILE_VISITOR_DEFINITION( NamespaceIterator )\nPROFILE_VISITOR_DEFINITION( NodeDistinctIterator )\nPROFILE_VISITOR_DEFINITION( NodeSortIterator )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<AddOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<DivideOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<IntegerDivideOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<ModOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<MultiplyOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<SubtractOperation> )\nPROFILE_VISITOR_DEFINITION( OpDoubleUnaryIterator )\nPROFILE_VISITOR_DEFINITION( OpNumericUnaryIterator )\nPROFILE_VISITOR_DEFINITION( OrIterator )\nPROFILE_VISITOR_DEFINITION( ParentAxisIterator )\nPROFILE_VISITOR_DEFINITION( PiIterator )\nPROFILE_VISITOR_DEFINITION( PrecedingAxisIterator )\nPROFILE_VISITOR_DEFINITION( PrecedingReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexPointGeneralIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexPointValueIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexRangeGeneralIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexRangeValueIterator )\nPROFILE_VISITOR_DEFINITION( PromoteIterator )\nPROFILE_VISITOR_DEFINITION( RefreshIndexIterator )\nPROFILE_VISITOR_DEFINITION( RenameIterator )\nPROFILE_VISITOR_DEFINITION( ReplaceIterator )\nPROFILE_VISITOR_DEFINITION( RSiblingAxisIterator )\nPROFILE_VISITOR_DEFINITION( SelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( SequentialIterator )\nPROFILE_VISITOR_DEFINITION( SingleDynamicFnCallIterator )\nPROFILE_VISITOR_DEFINITION( SingletonIterator )\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( TextIterator )\nPROFILE_VISITOR_DEFINITION( TransformIterator )\nPROFILE_VISITOR_DEFINITION( TreatIterator )\nPROFILE_VISITOR_DEFINITION( TryCatchIterator )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_DECIMAL> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_DOUBLE> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_FLOAT> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_INTEGER> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_STRING> )\nPROFILE_VISITOR_DEFINITION( UDFunctionCallIterator )\nPROFILE_VISITOR_DEFINITION( UnhoistIterator )\nPROFILE_VISITOR_DEFINITION( ValueIndexEntryBuilderIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertAfterIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertBeforeIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertFirstIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertLastIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertAfterIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertBeforeIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertFirstIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertLastIterator )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProfileVisitor::beginVisitFlworWhereClause(const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitFlworWhereClause(const PlanIterator& ) {\n}\n\nvoid ProfileVisitor::beginVisitFlworLetVariable(\n bool materialize,\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitFlworLetVariable() {\n}\n\nvoid ProfileVisitor::beginVisitFlworForVariable(\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs,\n const std::vector<PlanIter_t>& posRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitFlworForVariable() {\n}\n\nvoid ProfileVisitor::beginVisitOrderBySpec(const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitOrderBySpec(const PlanIterator& ) {\n}\n\nvoid ProfileVisitor::beginVisitOrderByForVariable(\n ForVarIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitOrderByForVariable() {\n}\n\nvoid ProfileVisitor::beginVisitOrderByLetVariable(\n LetVarIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitOrderByLetVariable() {\n}\n\nvoid ProfileVisitor::beginVisitMaterializeClause() {\n}\n\nvoid ProfileVisitor::endVisitMaterializeClause() {\n}\n\nvoid ProfileVisitor::beginVisitMaterializeVariable(\n bool forVar,\n PlanIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitMaterializeVariable() {\n}\n\nvoid ProfileVisitor::beginVisitGroupByClause() {\n}\n\nvoid ProfileVisitor::endVisitGroupByClause() {\n}\n\nvoid ProfileVisitor::beginVisitGroupBySpec() {\n}\n\nvoid ProfileVisitor::endVisitGroupBySpec() {\n}\n\nvoid ProfileVisitor::beginVisitGroupByOuter() {\n}\n\nvoid ProfileVisitor::endVisitGroupByOuter() {\n}\n\nvoid ProfileVisitor::beginVisitGroupVariable(const std::vector<ForVarIter_t>& varRefs) {\n}\n\nvoid ProfileVisitor::endVisitGroupVariable() {\n}\n\nvoid ProfileVisitor::beginVisitNonGroupVariable(const std::vector<LetVarIter_t>& varRefs) {\n}\n\nvoid ProfileVisitor::endVisitNonGroupVariable() {\n}\n\nvoid ProfileVisitor::beginVisitWindowVariable(\n const std::string& varName,\n const std::vector<LetVarIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitWindowVariable() {\n}\n\nvoid ProfileVisitor::beginVisitWinCondVariable(\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitWinCondVariable() {\n}\n\nvoid ProfileVisitor::beginVisitFlworReturn( const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitFlworReturn( const PlanIterator& ) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>Intermediate check-in.<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include <iostream>\n\n#ifdef ZORBA_WITH_DEBUGGER\n#include \"debugger\/debugger_commons.h\"\n#endif\n#include \"functions\/udf.h\"\n#include \"runtime\/booleans\/BooleanImpl.h\"\n#include \"runtime\/collections\/collections.h\"\n#include \"runtime\/core\/apply_updates.h\"\n#include \"runtime\/core\/arithmetic_impl.h\"\n#include \"runtime\/core\/constructors.h\"\n#include \"runtime\/core\/flwor_iterator.h\"\n#include \"runtime\/core\/fncall_iterator.h\"\n#include \"runtime\/core\/gflwor\/count_iterator.h\"\n#include \"runtime\/core\/gflwor\/for_iterator.h\"\n#include \"runtime\/core\/gflwor\/groupby_iterator.h\"\n#include \"runtime\/core\/gflwor\/let_iterator.h\"\n#include \"runtime\/core\/gflwor\/outerfor_iterator.h\"\n#include \"runtime\/core\/gflwor\/tuplesource_iterator.h\"\n#include \"runtime\/core\/gflwor\/tuplestream_iterator.h\"\n#include \"runtime\/core\/gflwor\/where_iterator.h\"\n#include \"runtime\/core\/gflwor\/window_iterator.h\"\n#include \"runtime\/core\/internal_operators.h\"\n#include \"runtime\/core\/item_iterator.h\"\n#include \"runtime\/core\/nodeid_iterators.h\"\n#include \"runtime\/core\/path_iterators.h\"\n#include \"runtime\/core\/sequencetypes.h\"\n#include \"runtime\/core\/trycatch.h\"\n#include \"runtime\/core\/var_iterators.h\"\n#ifdef ZORBA_WITH_DEBUGGER\n#include \"runtime\/debug\/debug_iterator.h\"\n#endif\n#include \"runtime\/durations_dates_times\/DurationsDatesTimesImpl.h\"\n#include \"runtime\/durations_dates_times\/format_dateTime.h\"\n#include \"runtime\/eval\/eval.h\"\n#ifndef ZORBA_NO_FULL_TEXT\n#include \"runtime\/full_text\/full_text.h\"\n#endif\n#include \"runtime\/hof\/dynamic_fncall_iterator.h\"\n#include \"runtime\/hof\/function_item_iter.h\"\n#include \"runtime\/indexing\/index_ddl.h\"\n#include \"runtime\/json\/json_constructors.h\"\n#include \"runtime\/misc\/materialize.h\"\n#include \"runtime\/numerics\/NumericsImpl.h\"\n#include \"runtime\/scripting\/scripting.h\"\n#include \"runtime\/sequences\/SequencesImpl.h\"\n#include \"runtime\/update\/update.h\"\n#include \"runtime\/visitors\/profile_visitor.h\"\n\nusing namespace std;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if 0\nvoid\nget_pd( PlanIterator const &pi, PlanState &p_state ) {\n PlanIteratorState const *const pi_state =\n StateTraitsImpl<PlanIteratorState>::getState(\n p_state, pi.getStateOffset()\n );\n profile_data const &pd = pi_state->get_profile_data();\n cerr << \"<iterator name=\\\"\" << pi.getNameAsString() << \"\\\" calls=\\\"\" << pd.next_.call_count_ << \"\\\" ms=\\\"\" << pd.next_.cpu_time_ << \"\\\"\/>\\n\";\n}\n#endif\n\n#define PROFILE_VISITOR_DEFINITION(...) \\\n void ProfileVisitor::beginVisit( __VA_ARGS__ const &iter ) { \\\n } \\\n void ProfileVisitor::endVisit( __VA_ARGS__ const& ) { \\\n }\n\nPROFILE_VISITOR_DEFINITION( AncestorAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorSelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( AncestorSelfReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( AndIterator )\nPROFILE_VISITOR_DEFINITION( ApplyIterator )\nPROFILE_VISITOR_DEFINITION( ArgumentPlaceholderIterator )\nPROFILE_VISITOR_DEFINITION( AtomicValuesEquivalenceIterator )\nPROFILE_VISITOR_DEFINITION( AttributeAxisIterator )\nPROFILE_VISITOR_DEFINITION( AttributeIterator )\nPROFILE_VISITOR_DEFINITION( CastableIterator )\nPROFILE_VISITOR_DEFINITION( CastIterator )\nPROFILE_VISITOR_DEFINITION( ChildAxisIterator )\nPROFILE_VISITOR_DEFINITION( CommentIterator )\nPROFILE_VISITOR_DEFINITION( CompareIterator )\nPROFILE_VISITOR_DEFINITION( CreateIndexIterator )\nPROFILE_VISITOR_DEFINITION( CreateInternalIndexIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarAssignIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarDeclareIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarIsSetIterator )\nPROFILE_VISITOR_DEFINITION( CtxVarIterator )\n#ifdef ZORBA_WITH_DEBUGGER\nPROFILE_VISITOR_DEFINITION( DebuggerSingletonIterator )\n#endif\nPROFILE_VISITOR_DEFINITION( DeleteIndexIterator )\nPROFILE_VISITOR_DEFINITION( DeleteIterator )\nPROFILE_VISITOR_DEFINITION( DescendantAxisIterator )\nPROFILE_VISITOR_DEFINITION( DescendantSelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( DocumentIterator )\nPROFILE_VISITOR_DEFINITION( EitherNodesOrAtomicsIterator )\nPROFILE_VISITOR_DEFINITION( ElementIterator )\nPROFILE_VISITOR_DEFINITION( EmptyIterator )\nPROFILE_VISITOR_DEFINITION( EnclosedIterator )\nPROFILE_VISITOR_DEFINITION( EvalIterator )\nPROFILE_VISITOR_DEFINITION( ExitCatcherIterator )\nPROFILE_VISITOR_DEFINITION( ExitIterator )\nPROFILE_VISITOR_DEFINITION( ExtFunctionCallIterator )\nPROFILE_VISITOR_DEFINITION( FlowCtlIterator )\nPROFILE_VISITOR_DEFINITION( flwor::CountIterator )\nPROFILE_VISITOR_DEFINITION( flwor::FLWORIterator )\nPROFILE_VISITOR_DEFINITION( flwor::ForIterator )\nPROFILE_VISITOR_DEFINITION( flwor::GroupByIterator )\nPROFILE_VISITOR_DEFINITION( flwor::LetIterator )\nPROFILE_VISITOR_DEFINITION( flwor::OrderByIterator )\nPROFILE_VISITOR_DEFINITION( flwor::OuterForIterator )\nPROFILE_VISITOR_DEFINITION( flwor::TupleSourceIterator )\nPROFILE_VISITOR_DEFINITION( flwor::TupleStreamIterator )\nPROFILE_VISITOR_DEFINITION( flwor::WhereIterator )\nPROFILE_VISITOR_DEFINITION( flwor::WindowIterator )\nPROFILE_VISITOR_DEFINITION( FnAdjustToTimeZoneIterator_1 )\nPROFILE_VISITOR_DEFINITION( FnAdjustToTimeZoneIterator_2 )\nPROFILE_VISITOR_DEFINITION( FnBooleanIterator )\nPROFILE_VISITOR_DEFINITION( FnDateTimeConstructorIterator )\nPROFILE_VISITOR_DEFINITION( FnFormatDateTimeIterator )\nPROFILE_VISITOR_DEFINITION( FnMinMaxIterator )\nPROFILE_VISITOR_DEFINITION( FollowingAxisIterator )\nPROFILE_VISITOR_DEFINITION( ForVarIterator )\n#ifndef ZORBA_NO_FULL_TEXT\nPROFILE_VISITOR_DEFINITION( FTContainsIterator )\n#endif\nPROFILE_VISITOR_DEFINITION( FunctionItemIterator )\nPROFILE_VISITOR_DEFINITION( GeneralIndexEntryBuilderIterator )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<AddOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<DivideOperation>)\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<IntegerDivideOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<ModOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<MultiplyOperation> )\nPROFILE_VISITOR_DEFINITION( GenericArithIterator<SubtractOperation> )\nPROFILE_VISITOR_DEFINITION( HoistIterator )\nPROFILE_VISITOR_DEFINITION( IfThenElseIterator )\nPROFILE_VISITOR_DEFINITION( InsertIterator )\nPROFILE_VISITOR_DEFINITION( InstanceOfIterator )\nPROFILE_VISITOR_DEFINITION( JSONArrayIterator )\nPROFILE_VISITOR_DEFINITION( JSONDirectObjectIterator )\nPROFILE_VISITOR_DEFINITION( JSONObjectIterator )\nPROFILE_VISITOR_DEFINITION( LetVarIterator )\nPROFILE_VISITOR_DEFINITION( LoopIterator )\nPROFILE_VISITOR_DEFINITION( LSiblingAxisIterator )\nPROFILE_VISITOR_DEFINITION( LSiblingReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( MaterializeIterator )\nPROFILE_VISITOR_DEFINITION( MultiDynamicFnCallIterator )\nPROFILE_VISITOR_DEFINITION( NameCastIterator )\nPROFILE_VISITOR_DEFINITION( NamespaceIterator )\nPROFILE_VISITOR_DEFINITION( NodeDistinctIterator )\nPROFILE_VISITOR_DEFINITION( NodeSortIterator )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<AddOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<DivideOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<IntegerDivideOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<ModOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<MultiplyOperation> )\nPROFILE_VISITOR_DEFINITION( NumArithIterator<SubtractOperation> )\nPROFILE_VISITOR_DEFINITION( OpDoubleUnaryIterator )\nPROFILE_VISITOR_DEFINITION( OpNumericUnaryIterator )\nPROFILE_VISITOR_DEFINITION( OrIterator )\nPROFILE_VISITOR_DEFINITION( ParentAxisIterator )\nPROFILE_VISITOR_DEFINITION( PiIterator )\nPROFILE_VISITOR_DEFINITION( PrecedingAxisIterator )\nPROFILE_VISITOR_DEFINITION( PrecedingReverseAxisIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexPointGeneralIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexPointValueIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexRangeGeneralIterator )\nPROFILE_VISITOR_DEFINITION( ProbeIndexRangeValueIterator )\nPROFILE_VISITOR_DEFINITION( PromoteIterator )\nPROFILE_VISITOR_DEFINITION( RefreshIndexIterator )\nPROFILE_VISITOR_DEFINITION( RenameIterator )\nPROFILE_VISITOR_DEFINITION( ReplaceIterator )\nPROFILE_VISITOR_DEFINITION( RSiblingAxisIterator )\nPROFILE_VISITOR_DEFINITION( SelfAxisIterator )\nPROFILE_VISITOR_DEFINITION( SequentialIterator )\nPROFILE_VISITOR_DEFINITION( SingleDynamicFnCallIterator )\nPROFILE_VISITOR_DEFINITION( SingletonIterator )\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<AddOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<DivideOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<ModOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<MultiplyOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_DECIMAL>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_DOUBLE>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_FLOAT>)\nPROFILE_VISITOR_DEFINITION( SpecificNumArithIterator<SubtractOperation,store::XS_INTEGER>)\nPROFILE_VISITOR_DEFINITION( TextIterator )\nPROFILE_VISITOR_DEFINITION( TransformIterator )\nPROFILE_VISITOR_DEFINITION( TreatIterator )\nPROFILE_VISITOR_DEFINITION( TryCatchIterator )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_DECIMAL> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_DOUBLE> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_FLOAT> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_INTEGER> )\nPROFILE_VISITOR_DEFINITION( TypedValueCompareIterator<store::XS_STRING> )\nPROFILE_VISITOR_DEFINITION( UDFunctionCallIterator )\nPROFILE_VISITOR_DEFINITION( UnhoistIterator )\nPROFILE_VISITOR_DEFINITION( ValueIndexEntryBuilderIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertAfterIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertBeforeIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertFirstIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaApplyInsertLastIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertAfterIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertBeforeIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertFirstIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertIterator )\nPROFILE_VISITOR_DEFINITION( ZorbaInsertLastIterator )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProfileVisitor::beginVisitFlworWhereClause(const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitFlworWhereClause(const PlanIterator& ) {\n}\n\nvoid ProfileVisitor::beginVisitFlworLetVariable(\n bool materialize,\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitFlworLetVariable() {\n}\n\nvoid ProfileVisitor::beginVisitFlworForVariable(\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs,\n const std::vector<PlanIter_t>& posRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitFlworForVariable() {\n}\n\nvoid ProfileVisitor::beginVisitOrderBySpec(const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitOrderBySpec(const PlanIterator& ) {\n}\n\nvoid ProfileVisitor::beginVisitOrderByForVariable(\n ForVarIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitOrderByForVariable() {\n}\n\nvoid ProfileVisitor::beginVisitOrderByLetVariable(\n LetVarIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitOrderByLetVariable() {\n}\n\nvoid ProfileVisitor::beginVisitMaterializeClause() {\n}\n\nvoid ProfileVisitor::endVisitMaterializeClause() {\n}\n\nvoid ProfileVisitor::beginVisitMaterializeVariable(\n bool forVar,\n PlanIter_t inputVar,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitMaterializeVariable() {\n}\n\nvoid ProfileVisitor::beginVisitGroupByClause() {\n}\n\nvoid ProfileVisitor::endVisitGroupByClause() {\n}\n\nvoid ProfileVisitor::beginVisitGroupBySpec() {\n}\n\nvoid ProfileVisitor::endVisitGroupBySpec() {\n}\n\nvoid ProfileVisitor::beginVisitGroupByOuter() {\n}\n\nvoid ProfileVisitor::endVisitGroupByOuter() {\n}\n\nvoid ProfileVisitor::beginVisitGroupVariable(const std::vector<ForVarIter_t>& varRefs) {\n}\n\nvoid ProfileVisitor::endVisitGroupVariable() {\n}\n\nvoid ProfileVisitor::beginVisitNonGroupVariable(const std::vector<LetVarIter_t>& varRefs) {\n}\n\nvoid ProfileVisitor::endVisitNonGroupVariable() {\n}\n\nvoid ProfileVisitor::beginVisitWindowVariable(\n const std::string& varName,\n const std::vector<LetVarIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitWindowVariable() {\n}\n\nvoid ProfileVisitor::beginVisitWinCondVariable(\n const zstring& varName,\n const std::vector<PlanIter_t>& varRefs)\n{\n}\n\nvoid ProfileVisitor::endVisitWinCondVariable() {\n}\n\nvoid ProfileVisitor::beginVisitFlworReturn( const PlanIterator& a) {\n}\n\nvoid ProfileVisitor::endVisitFlworReturn( const PlanIterator& ) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011, The University of Oxford\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. Neither the name of the University of Oxford nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cuda_runtime_api.h>\n\n#include \"interferometry\/oskar_interferometer.h\"\n#include \"interferometry\/oskar_correlate.h\"\n#include \"interferometry\/oskar_evaluate_jones_K.h\"\n#include \"interferometry\/oskar_evaluate_station_uvw.h\"\n#include \"math\/oskar_Jones.h\"\n#include \"math\/oskar_jones_join.h\"\n#include \"sky\/oskar_evaluate_jones_R.h\"\n#include \"sky\/oskar_mjd_to_gast_fast.h\"\n#include \"sky\/oskar_sky_model_horizon_clip.h\"\n#include \"station\/oskar_evaluate_jones_E.h\"\n#include <cstdio>\n\nextern \"C\"\nint oskar_interferometer(oskar_Mem* vis_amp, const oskar_SkyModel* sky,\n const oskar_TelescopeModel* telescope, const oskar_SimTime* times,\n double frequency)\n{\n int err = 0;\n int device_id = 0;\n size_t mem_free, mem_total;\n cudaDeviceProp device_prop;\n\n \/\/ Copy telescope model and sky model for frequency scaling.\n oskar_TelescopeModel tel_gpu(telescope, OSKAR_LOCATION_GPU);\n oskar_SkyModel sky_gpu(sky, OSKAR_LOCATION_GPU);\n\n \/\/ Scale GPU telescope coordinates by wavenumber.\n err = tel_gpu.multiply_by_wavenumber(frequency); if (err) return err;\n\n \/\/ Scale by spectral index.\n err = sky_gpu.scale_by_spectral_index(frequency);\n if (err) return err;\n\n \/\/ Initialise blocks of Jones matrices and visibilities.\n int type = sky_gpu.type();\n int n_stations = tel_gpu.num_stations;\n int n_baselines = n_stations * (n_stations - 1) \/ 2;\n int n_sources = sky_gpu.num_sources;\n int complex_scalar = type | OSKAR_COMPLEX;\n int complex_matrix = type | OSKAR_COMPLEX | OSKAR_MATRIX;\n oskar_Jones J(complex_matrix, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones R(complex_matrix, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones E(complex_scalar, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones K(complex_scalar, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Mem vis(complex_matrix, OSKAR_LOCATION_GPU, n_baselines);\n oskar_Mem u(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Mem v(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Mem w(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Work work(type, OSKAR_LOCATION_GPU);\n\n \/\/ Get time increments.\n int num_vis_dumps = times->num_vis_dumps;\n int num_vis_ave = times->num_vis_ave;\n int num_fringe_ave = times->num_fringe_ave;\n double obs_start_mjd_utc = times->obs_start_mjd_utc;\n double dt_dump = times->dt_dump_days;\n double dt_ave = times->dt_ave_days;\n double dt_fringe = times->dt_fringe_days;\n\n cudaMemGetInfo(&mem_free, &mem_total);\n cudaGetDevice(&device_id);\n cudaGetDeviceProperties(&device_prop, device_id);\n printf(\"==> Device memory [%i, %s]: free %.1f MB, total %.1f MB.\\n\",\n device_id, device_prop.name, mem_free\/(1024.*1024.),\n mem_total\/(1024.*1024.));\n\n \/\/ Start simulation.\n for (int j = 0; j < num_vis_dumps; ++j)\n {\n \/\/ Start time for the visibility dump, in MJD(UTC).\n printf(\"--> Simulating snapshot (%i \/ %i) \", j+1, num_vis_dumps);\n double t_dump = obs_start_mjd_utc + j * dt_dump;\n double gast = oskar_mjd_to_gast_fast(t_dump + dt_dump \/ 2.0);\n\n \/\/ Initialise visibilities for the dump to zero.\n err = vis.clear_contents();\n if (err) return err;\n\n \/\/ Compact sky model to temporary.\n oskar_SkyModel local_sky(type, OSKAR_LOCATION_GPU);\n err = oskar_sky_model_horizon_clip(&local_sky, &sky_gpu, &tel_gpu,\n gast, &work);\n printf(\"[num sources = %i]\\n\", local_sky.num_sources);\n if (err == OSKAR_ERR_NO_VISIBLE_SOURCES)\n {\n \/\/ Skip iteration.\n printf(\"--> WARNING: No sources above horizon. Skipping.\\n\");\n continue;\n }\n else if (err != 0) return err;\n\n\/\/ oskar_SkyModel temp_sky(&local_sky, OSKAR_LOCATION_CPU);\n\/\/ printf(\"#### num_sources = %i (%i %i)\\n\", temp_sky.num_sources,\n\/\/ local_sky.num_sources, sky->num_sources);\n\/\/ typedef double real;\n\/\/ for (int source = 0; source < temp_sky.num_sources; ++source)\n\/\/ {\n\/\/ printf(\"##### source[%3i] %f %f | %f %f %f %f | %f %f\\n\", source,\n\/\/ ((real*)temp_sky.RA.data)[source],\n\/\/ ((real*)temp_sky.Dec.data)[source],\n\/\/ ((real*)temp_sky.I.data)[source],\n\/\/ ((real*)temp_sky.Q.data)[source],\n\/\/ ((real*)temp_sky.U.data)[source],\n\/\/ ((real*)temp_sky.V.data)[source],\n\/\/ ((real*)temp_sky.reference_freq.data)[source],\n\/\/ ((real*)temp_sky.spectral_index.data)[source]);\n\/\/ }\n\n \/\/ Set dimensions of Jones matrices (this is not a resize!).\n err = J.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = R.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = E.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = K.set_size(n_stations, local_sky.num_sources); if (err) return err;\n\n \/\/ Average snapshot.\n for (int i = 0; i < num_vis_ave; ++i)\n {\n \/\/ Evaluate Greenwich Apparent Sidereal Time.\n double t_ave = t_dump + i * dt_ave;\n double gast = oskar_mjd_to_gast_fast(t_ave + dt_ave \/ 2);\n\n \/\/ Evaluate parallactic angle rotation (Jones R).\n err = oskar_evaluate_jones_R(&R, &local_sky, &tel_gpu, gast);\n if (err) return err;\n\n \/\/ Evaluate station beam (Jones E).\n err = oskar_evaluate_jones_E(&E, &local_sky, &tel_gpu, gast, &work);\n if (err) return err;\n\n \/\/ Join Jones matrices (R = E * R).\n err = oskar_jones_join(&R, &E, &R);\n if (err) return err;\n\n for (int k = 0; k < num_fringe_ave; ++k)\n {\n \/\/ Evaluate Greenwich Apparent Sidereal Time.\n double t_fringe = t_ave + k * dt_fringe;\n double gast = oskar_mjd_to_gast_fast(t_fringe + dt_fringe \/ 2);\n\n \/\/ Evaluate station u,v,w coordinates.\n err = oskar_evaluate_station_uvw(&u, &v, &w, &tel_gpu, gast);\n if (err) return err;\n\n \/\/ Evaluate interferometer phase (Jones K).\n err = oskar_evaluate_jones_K(&K, &local_sky, &u, &v, &w);\n if (err) return err;\n\n \/\/ Join Jones matrices (J = K * R).\n err = oskar_jones_join(&J, &K, &R); if (err) return err;\n\n \/\/ Produce visibilities.\n err = oskar_correlate(&vis, &J, &tel_gpu, &local_sky, &u, &v);\n if (err) return err;\n }\n }\n\n \/\/ Divide visibilities by number of averages.\n err = vis.scale_real(1.0 \/ (num_fringe_ave * num_vis_ave));\n if (err) return err;\n\n \/\/ Add visibilities to global data.\n err = vis_amp->insert(&vis, j * n_baselines);\n if (err) return err;\n }\n\n return OSKAR_SUCCESS;\n}\n<commit_msg>updated debugging<commit_after>\/*\n * Copyright (c) 2011, The University of Oxford\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. Neither the name of the University of Oxford nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cuda_runtime_api.h>\n\n#include \"interferometry\/oskar_interferometer.h\"\n#include \"interferometry\/oskar_correlate.h\"\n#include \"interferometry\/oskar_evaluate_jones_K.h\"\n#include \"interferometry\/oskar_evaluate_station_uvw.h\"\n#include \"math\/oskar_Jones.h\"\n#include \"math\/oskar_jones_join.h\"\n#include \"sky\/oskar_evaluate_jones_R.h\"\n#include \"sky\/oskar_mjd_to_gast_fast.h\"\n#include \"sky\/oskar_sky_model_horizon_clip.h\"\n#include \"station\/oskar_evaluate_jones_E.h\"\n#include <cstdio>\n\nextern \"C\"\nint oskar_interferometer(oskar_Mem* vis_amp, const oskar_SkyModel* sky,\n const oskar_TelescopeModel* telescope, const oskar_SimTime* times,\n double frequency)\n{\n int err = 0;\n int device_id = 0;\n size_t mem_free, mem_total;\n cudaDeviceProp device_prop;\n\n \/\/ Copy telescope model and sky model for frequency scaling.\n oskar_TelescopeModel tel_gpu(telescope, OSKAR_LOCATION_GPU);\n oskar_SkyModel sky_gpu(sky, OSKAR_LOCATION_GPU);\n\n \/\/ Scale GPU telescope coordinates by wavenumber.\n err = tel_gpu.multiply_by_wavenumber(frequency); if (err) return err;\n\n \/\/ Scale by spectral index.\n err = sky_gpu.scale_by_spectral_index(frequency);\n if (err) return err;\n\n \/\/ Initialise blocks of Jones matrices and visibilities.\n int type = sky_gpu.type();\n int n_stations = tel_gpu.num_stations;\n int n_baselines = n_stations * (n_stations - 1) \/ 2;\n int n_sources = sky_gpu.num_sources;\n int complex_scalar = type | OSKAR_COMPLEX;\n int complex_matrix = type | OSKAR_COMPLEX | OSKAR_MATRIX;\n oskar_Jones J(complex_matrix, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones R(complex_matrix, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones E(complex_scalar, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Jones K(complex_scalar, OSKAR_LOCATION_GPU, n_stations, n_sources);\n oskar_Mem vis(complex_matrix, OSKAR_LOCATION_GPU, n_baselines);\n oskar_Mem u(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Mem v(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Mem w(type, OSKAR_LOCATION_GPU, n_stations, true);\n oskar_Work work(type, OSKAR_LOCATION_GPU);\n\n \/\/ Get time increments.\n int num_vis_dumps = times->num_vis_dumps;\n int num_vis_ave = times->num_vis_ave;\n int num_fringe_ave = times->num_fringe_ave;\n double obs_start_mjd_utc = times->obs_start_mjd_utc;\n double dt_dump = times->dt_dump_days;\n double dt_ave = times->dt_ave_days;\n double dt_fringe = times->dt_fringe_days;\n\n cudaMemGetInfo(&mem_free, &mem_total);\n cudaGetDevice(&device_id);\n cudaGetDeviceProperties(&device_prop, device_id);\n printf(\"==> Device memory [%i, %s]: free %.1f MB, total %.1f MB.\\n\",\n device_id, device_prop.name, mem_free\/(1024.*1024.),\n mem_total\/(1024.*1024.));\n\n \/\/ Start simulation.\n for (int j = 0; j < num_vis_dumps; ++j)\n {\n \/\/ Start time for the visibility dump, in MJD(UTC).\n printf(\"--> Simulating snapshot (%i \/ %i) \", j+1, num_vis_dumps);\n double t_dump = obs_start_mjd_utc + j * dt_dump;\n double gast = oskar_mjd_to_gast_fast(t_dump + dt_dump \/ 2.0);\n\n \/\/ Initialise visibilities for the dump to zero.\n err = vis.clear_contents();\n if (err) return err;\n\n \/\/ Compact sky model to temporary.\n oskar_SkyModel local_sky(type, OSKAR_LOCATION_GPU);\n err = oskar_sky_model_horizon_clip(&local_sky, &sky_gpu, &tel_gpu,\n gast, &work);\n printf(\"[num sources = %i]\\n\", local_sky.num_sources);\n if (err == OSKAR_ERR_NO_VISIBLE_SOURCES)\n {\n \/\/ Skip iteration.\n printf(\"--> WARNING: No sources above horizon. Skipping.\\n\");\n continue;\n }\n else if (err != 0) return err;\n\n oskar_SkyModel temp_sky(&local_sky, OSKAR_LOCATION_CPU);\n printf(\"#### num_sources = %i (%i %i)\\n\", temp_sky.num_sources,\n local_sky.num_sources, sky->num_sources);\n typedef float real;\n for (int source = 0; source < temp_sky.num_sources; ++source)\n {\n printf(\"##### source[%3i] % .2f % .2f | %.2f %.2f %.2f %.2f | %.2f %.2f | % .2f % .2f % .2f\\n\",\n source,\n ((real*)temp_sky.RA.data)[source],\n ((real*)temp_sky.Dec.data)[source],\n ((real*)temp_sky.I.data)[source],\n ((real*)temp_sky.Q.data)[source],\n ((real*)temp_sky.U.data)[source],\n ((real*)temp_sky.V.data)[source],\n ((real*)temp_sky.reference_freq.data)[source],\n ((real*)temp_sky.spectral_index.data)[source],\n ((real*)temp_sky.rel_l.data)[source],\n ((real*)temp_sky.rel_m.data)[source],\n ((real*)temp_sky.rel_n.data)[source]);\n }\n\n \/\/ Set dimensions of Jones matrices (this is not a resize!).\n err = J.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = R.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = E.set_size(n_stations, local_sky.num_sources); if (err) return err;\n err = K.set_size(n_stations, local_sky.num_sources); if (err) return err;\n\n \/\/ Average snapshot.\n for (int i = 0; i < num_vis_ave; ++i)\n {\n \/\/ Evaluate Greenwich Apparent Sidereal Time.\n double t_ave = t_dump + i * dt_ave;\n double gast = oskar_mjd_to_gast_fast(t_ave + dt_ave \/ 2);\n\n \/\/ Evaluate parallactic angle rotation (Jones R).\n err = oskar_evaluate_jones_R(&R, &local_sky, &tel_gpu, gast);\n if (err) return err;\n\n \/\/ Evaluate station beam (Jones E).\n err = oskar_evaluate_jones_E(&E, &local_sky, &tel_gpu, gast, &work);\n if (err) return err;\n\n \/\/ Join Jones matrices (R = E * R).\n err = oskar_jones_join(&R, &E, &R);\n if (err) return err;\n\n for (int k = 0; k < num_fringe_ave; ++k)\n {\n \/\/ Evaluate Greenwich Apparent Sidereal Time.\n double t_fringe = t_ave + k * dt_fringe;\n double gast = oskar_mjd_to_gast_fast(t_fringe + dt_fringe \/ 2);\n\n \/\/ Evaluate station u,v,w coordinates.\n err = oskar_evaluate_station_uvw(&u, &v, &w, &tel_gpu, gast);\n if (err) return err;\n\n \/\/ Evaluate interferometer phase (Jones K).\n err = oskar_evaluate_jones_K(&K, &local_sky, &u, &v, &w);\n if (err) return err;\n\n \/\/ Join Jones matrices (J = K * R).\n err = oskar_jones_join(&J, &K, &R); if (err) return err;\n\n \/\/ Produce visibilities.\n err = oskar_correlate(&vis, &J, &tel_gpu, &local_sky, &u, &v);\n if (err) return err;\n }\n }\n\n \/\/ Divide visibilities by number of averages.\n err = vis.scale_real(1.0 \/ (num_fringe_ave * num_vis_ave));\n if (err) return err;\n\n \/\/ Add visibilities to global data.\n err = vis_amp->insert(&vis, j * n_baselines);\n if (err) return err;\n }\n\n return OSKAR_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"player.hpp\"\n\nPlayer::Player(int num) : Actor(num) {\n compas = Compas();\n error = false;\n time = 0;\n}\n\nPlayer::Player() : Actor() {\n compas = Compas();\n error = false;\n time = 0;\n}\n\nbool Player::updateLogic(float deltaTime, sf::RenderWindow *window) {\n time += deltaTime;\n if (time > BLACKVALUE) {\n compas.incraeseTime();\n time = 0;\n }\n return false;\n}\n\nbool Player::event(sf::Event e, bool def) {\n switch(e.type) {\n case (sf::Event::KeyPressed):\n if(e.key.code == sf::Keyboard::C) {\n compas.start();\n error = false;\n }\n if(e.key.code == sf::Keyboard::Space) {\n if (animate == PlayerState::idle && !error) {\n compas.add();\n if (compas.isPressed()) animate = PlayerState::attacking;\n }\n else {\n compas.end();\n error = true;\n if (animate != PlayerState::inMidle) animate = PlayerState::hurt;\n }\n }\n break;\n case (sf::Event::KeyReleased):\n if (e.key.code == sf::Keyboard::C) {\n compas.end();\n return false;\n }\n break;\n default:\n break;\n }\n return true;\n}\n<commit_msg>fix bugg, start shader<commit_after>#include \"player.hpp\"\n\nPlayer::Player(int num) : Actor(num) {\n compas = Compas();\n error = false;\n time = 0;\n}\n\nPlayer::Player() : Actor() {\n compas = Compas();\n error = false;\n time = 0;\n}\n\nbool Player::updateLogic(float deltaTime, sf::RenderWindow *window) {\n time += deltaTime;\n if (time > BLACKVALUE) {\n compas.incraeseTime();\n time = 0;\n }\n return false;\n}\n\nbool Player::event(sf::Event e, bool def) {\n switch(e.type) {\n case (sf::Event::KeyPressed):\n if(e.key.code == sf::Keyboard::C) {\n compas.start();\n error = false;\n }\n if(e.key.code == sf::Keyboard::Space) {\n if (animate == PlayerState::idle && !error) {\n compas.add();\n if (compas.isPressed()) animate = PlayerState::attacking;\n }\n else {\n compas.end();\n if (!error || (error && animate == PlayerState::idle))\n animate = PlayerState::hurt;\n error = true;\n }\n }\n break;\n case (sf::Event::KeyReleased):\n if (e.key.code == sf::Keyboard::C) {\n compas.end();\n return false;\n }\n break;\n default:\n break;\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Tianfeng Han <mikan.tenny@gmail.com> |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"swoole_api.h\"\n#include \"async.h\"\n\n#include <thread>\n#include <atomic>\n#include <unordered_map>\n#include <chrono>\n#include <condition_variable>\n#include <mutex>\n#include <queue>\n\nusing namespace std;\n\ntypedef swAio_event AsyncEvent;\n\nstatic mutex init_lock;\nstatic atomic<int> refcount(0);\n\nstatic void aio_thread_release(AsyncEvent *event);\n\nnamespace swoole { namespace async {\n\/\/-------------------------------------------------------------------------------\nclass EventQueue\n{\npublic:\n inline void push(AsyncEvent *event)\n {\n unique_lock<mutex> lock(_mutex);\n _queue.push(event);\n }\n\n inline AsyncEvent* pop()\n {\n unique_lock<mutex> lock(_mutex);\n if (_queue.empty())\n {\n return nullptr;\n }\n AsyncEvent* retval = _queue.front();\n _queue.pop();\n return retval;\n }\n\n inline double get_max_wait_time()\n {\n unique_lock<mutex> lock(_mutex);\n if (_queue.empty())\n {\n return 0;\n }\n else\n {\n AsyncEvent* event = _queue.front();\n return swoole_microtime() - event->timestamp;\n }\n }\n\n inline size_t count()\n {\n unique_lock<mutex> lock(_mutex);\n return _queue.size();\n }\n\nprivate:\n queue<AsyncEvent *> _queue;\n mutex _mutex;\n};\n\nclass ThreadPool\n{\npublic:\n ThreadPool(size_t _core_worker_num, size_t _worker_num, double _max_wait_time, double _max_idle_time)\n {\n running = false;\n\n core_worker_num = _core_worker_num == 0 ? SW_CPU_NUM : SW_MAX(1, _core_worker_num);\n worker_num = _worker_num == 0 ? SW_CPU_NUM * SW_AIO_THREAD_NUM_MULTIPLE : SW_MAX(core_worker_num, _worker_num);\n max_wait_time = _max_wait_time == 0 ? SW_AIO_TASK_MAX_WAIT_TIME : _max_wait_time;\n max_idle_time = _max_idle_time == 0 ? SW_AIO_THREAD_MAX_IDLE_TIME : _max_idle_time;\n\n current_pid = getpid();\n }\n\n ~ThreadPool()\n {\n shutdown();\n }\n\n bool start()\n {\n running = true;\n current_task_id = 0;\n n_waiting = 0;\n n_closing = 0;\n for (size_t i = 0; i < core_worker_num; i++)\n {\n create_thread(true);\n }\n return true;\n }\n\n bool shutdown()\n {\n if (!running)\n {\n return false;\n }\n running = false;\n\n event_mutex.lock();\n _cv.notify_all();\n event_mutex.unlock();\n\n for (auto &i : threads)\n {\n thread *_thread = i.second;\n if (_thread->joinable())\n {\n _thread->join();\n }\n delete _thread;\n }\n\n return true;\n }\n\n void schedule()\n {\n if (n_waiting == 0 && threads.size() < worker_num && max_wait_time > 0)\n {\n double _max_wait_time = _queue.get_max_wait_time();\n if (_max_wait_time > max_wait_time)\n {\n size_t n = 1;\n \/**\n * maybe we can find a better strategy\n *\/\n if (threads.size() + n > worker_num)\n {\n n = worker_num - threads.size();\n }\n swTraceLog(SW_TRACE_AIO, \"Create %zu thread due to wait %fs, we will have %zu threads\", n, _max_wait_time, threads.size() + n);\n while (n--)\n {\n create_thread();\n }\n }\n }\n }\n\n AsyncEvent* dispatch(const AsyncEvent *request)\n {\n if (SwooleTG.aio_schedule) \n {\n schedule();\n }\n auto _event_copy = new AsyncEvent(*request);\n _event_copy->task_id = current_task_id++;\n _event_copy->timestamp = swoole_microtime();\n _event_copy->pipe_fd = SwooleTG.aio_pipe_write;\n _queue.push(_event_copy);\n _cv.notify_one();\n return _event_copy;\n }\n\n inline size_t worker_count()\n {\n return threads.size();\n }\n\n inline size_t queue_count()\n {\n return _queue.count();\n }\n\n pid_t current_pid;\n\n void release_thread(thread::id tid)\n {\n auto i = threads.find(tid);\n if (i == threads.end())\n {\n swWarn(\"AIO thread#%zu is missing\", tid);\n return;\n }\n else\n {\n thread *_thread = i->second;\n swTraceLog(SW_TRACE_AIO, \"release idle thread#%zu, we have %zu now\", tid, threads.size() - 1);\n if (_thread->joinable())\n {\n _thread->join();\n }\n threads.erase(i);\n delete _thread;\n }\n }\n\nprivate:\n void create_thread(const bool is_core_worker = false);\n\n size_t core_worker_num;\n size_t worker_num;\n double max_wait_time;\n double max_idle_time;\n\n bool running;\n\n atomic<size_t> n_waiting;\n atomic<size_t> n_closing;\n size_t current_task_id = 0;\n\n unordered_map<thread::id, thread *> threads;\n EventQueue _queue;\n mutex event_mutex;\n condition_variable _cv;\n};\n\/\/-------------------------------------------------------------------------------\n}};\n\nstatic swoole::async::ThreadPool *pool = nullptr;\n\nvoid swoole::async::ThreadPool::create_thread(const bool is_core_worker)\n{\n try\n {\n thread *_thread = new thread([this, is_core_worker]()\n {\n bool exit_flag = false;\n\n SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE);\n if (SwooleTG.buffer_stack == nullptr)\n {\n return;\n }\n\n swSignal_none();\n\n while (running)\n {\n AsyncEvent *event = _queue.pop();\n if (event)\n {\n if (sw_unlikely(event->handler == nullptr))\n {\n event->error = SW_ERROR_AIO_BAD_REQUEST;\n event->ret = -1;\n }\n else if (sw_unlikely(event->canceled))\n {\n event->error = SW_ERROR_AIO_CANCELED;\n event->ret = -1;\n }\n else\n {\n event->handler(event);\n }\n\n swTraceLog(SW_TRACE_AIO, \"aio_thread %s. ret=%d, error=%d\", event->ret > 0 ? \"ok\" : \"failed\", event->ret, event->error);\n\n _send_event:\n while (true)\n {\n int ret = write(event->pipe_fd, &event, sizeof(event));\n if (ret < 0)\n {\n if (errno == EAGAIN)\n {\n swSocket_wait(SwooleTG.aio_pipe_write, 1000, SW_EVENT_WRITE);\n continue;\n }\n else if (errno == EINTR)\n {\n continue;\n }\n else\n {\n swSysWarn(\"sendto swoole_aio_pipe_write failed\");\n }\n }\n break;\n }\n\n \/\/ exit\n if (exit_flag)\n {\n n_closing--;\n break;\n }\n }\n else if (running)\n {\n unique_lock<mutex> lock(event_mutex);\n ++n_waiting;\n if (is_core_worker || max_idle_time <= 0)\n {\n _cv.wait(lock);\n }\n else\n {\n while (true)\n {\n if (_cv.wait_for(lock, chrono::microseconds((size_t) (max_idle_time * 1000 * 1000))) == cv_status::timeout)\n {\n if (running && n_closing != 0)\n {\n \/\/ wait for the next round\n continue;\n }\n \/* notifies the main thread to release this thread *\/\n event = new AsyncEvent;\n event->object = new thread::id(this_thread::get_id());\n event->callback = aio_thread_release;\n event->pipe_fd = SwooleG.aio_default_pipe_fd;\n\n --n_waiting;\n ++n_closing;\n exit_flag = true;\n goto _send_event;\n }\n break;\n }\n }\n --n_waiting;\n }\n }\n });\n threads[_thread->get_id()] = _thread;\n }\n catch (const std::system_error& e)\n {\n swSysNotice(\"create aio thread failed, please check your system configuration or adjust aio_worker_num\");\n return;\n }\n}\n\nstatic void aio_thread_release(swAio_event *event)\n{\n thread::id *tid = static_cast<thread::id *>(event->object);\n pool->release_thread(*tid);\n delete tid;\n \/\/ balance\n SwooleTG.aio_task_num++;\n}\n\nstatic void swAio_free(void *private_data)\n{\n if (!SwooleTG.aio_init)\n {\n return;\n }\n SwooleTG.aio_init = 0;\n swoole_event_del(SwooleTG.aio_pipe_read);\n SwooleTG.aio_pipe.close(&SwooleTG.aio_pipe);\n if (pool->current_pid == getpid())\n {\n if ((--refcount) == 0)\n {\n delete pool;\n pool = nullptr;\n }\n }\n}\n\nstatic int swAio_init()\n{\n if (SwooleTG.aio_init)\n {\n swWarn(\"aio_thread_pool has already been initialized\");\n return SW_ERR;\n }\n if (!SwooleTG.reactor)\n {\n swWarn(\"no event loop, cannot initialized\");\n return SW_ERR;\n }\n\n if (swPipeBase_create(&SwooleTG.aio_pipe, 0) < 0)\n {\n swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL);\n }\n\n SwooleTG.aio_pipe_read = SwooleTG.aio_pipe.getFd(&SwooleTG.aio_pipe, 0);\n SwooleTG.aio_pipe_write = SwooleTG.aio_pipe.getFd(&SwooleTG.aio_pipe, 1);\n swoole_event_add(SwooleTG.aio_pipe_read, SW_EVENT_READ, SW_FD_AIO);\n swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr);\n\n init_lock.lock();\n if ((refcount++) == 0)\n {\n pool = new swoole::async::ThreadPool(SwooleG.aio_core_worker_num, SwooleG.aio_worker_num,\n SwooleG.aio_max_wait_time, SwooleG.aio_max_idle_time);\n pool->start();\n SwooleTG.aio_schedule = 1;\n SwooleG.aio_default_pipe_fd = SwooleTG.aio_pipe_write;\n }\n SwooleTG.aio_init = 1;\n init_lock.unlock();\n\n return SW_OK;\n}\n\nsize_t swAio_thread_count()\n{\n return pool ? pool->worker_count() : 0;\n}\n\nssize_t swAio_dispatch(const swAio_event *request)\n{\n AsyncEvent *event = swAio_dispatch2(request);\n if (event == nullptr)\n {\n return -1;\n }\n return event->task_id;\n}\n\nswAio_event* swAio_dispatch2(const swAio_event *request)\n{\n if (sw_unlikely(!SwooleTG.aio_init))\n {\n swAio_init();\n }\n AsyncEvent *event = pool->dispatch(request);\n if (sw_likely(event))\n {\n SwooleTG.aio_task_num++;\n }\n return event;\n}\n\nint swAio_callback(swReactor *reactor, swEvent *event)\n{\n if (SwooleTG.aio_schedule) \n {\n pool->schedule();\n }\n\n AsyncEvent *events[SW_AIO_EVENT_NUM];\n ssize_t n = read(event->fd, events, sizeof(AsyncEvent *) * SW_AIO_EVENT_NUM);\n if (n < 0)\n {\n swSysWarn(\"read() aio events failed\");\n return SW_ERR;\n }\n for (size_t i = 0; i < n \/ sizeof(AsyncEvent *); i++)\n {\n AsyncEvent *event = events[i];\n if (!event->canceled)\n {\n event->callback(events[i]);\n }\n SwooleTG.aio_task_num--;\n delete event;\n }\n\n return SW_OK;\n}\n<commit_msg>thread safe<commit_after>\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Tianfeng Han <mikan.tenny@gmail.com> |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"swoole_api.h\"\n#include \"async.h\"\n\n#include <thread>\n#include <atomic>\n#include <unordered_map>\n#include <chrono>\n#include <condition_variable>\n#include <mutex>\n#include <queue>\n\nusing namespace std;\n\ntypedef swAio_event AsyncEvent;\n\nstatic mutex init_lock;\nstatic atomic<int> refcount(0);\n\nstatic void aio_thread_release(AsyncEvent *event);\n\nnamespace swoole { namespace async {\n\/\/-------------------------------------------------------------------------------\nclass EventQueue\n{\npublic:\n inline void push(AsyncEvent *event)\n {\n unique_lock<mutex> lock(_mutex);\n _queue.push(event);\n }\n\n inline AsyncEvent* pop()\n {\n unique_lock<mutex> lock(_mutex);\n if (_queue.empty())\n {\n return nullptr;\n }\n AsyncEvent* retval = _queue.front();\n _queue.pop();\n return retval;\n }\n\n inline double get_max_wait_time()\n {\n unique_lock<mutex> lock(_mutex);\n if (_queue.empty())\n {\n return 0;\n }\n else\n {\n AsyncEvent* event = _queue.front();\n return swoole_microtime() - event->timestamp;\n }\n }\n\n inline size_t count()\n {\n unique_lock<mutex> lock(_mutex);\n return _queue.size();\n }\n\nprivate:\n queue<AsyncEvent *> _queue;\n mutex _mutex;\n};\n\nclass ThreadPool\n{\npublic:\n ThreadPool(size_t _core_worker_num, size_t _worker_num, double _max_wait_time, double _max_idle_time)\n {\n running = false;\n\n core_worker_num = _core_worker_num == 0 ? SW_CPU_NUM : SW_MAX(1, _core_worker_num);\n worker_num = _worker_num == 0 ? SW_CPU_NUM * SW_AIO_THREAD_NUM_MULTIPLE : SW_MAX(core_worker_num, _worker_num);\n max_wait_time = _max_wait_time == 0 ? SW_AIO_TASK_MAX_WAIT_TIME : _max_wait_time;\n max_idle_time = _max_idle_time == 0 ? SW_AIO_THREAD_MAX_IDLE_TIME : _max_idle_time;\n\n current_pid = getpid();\n }\n\n ~ThreadPool()\n {\n shutdown();\n }\n\n bool start()\n {\n running = true;\n current_task_id = 0;\n n_waiting = 0;\n n_closing = 0;\n for (size_t i = 0; i < core_worker_num; i++)\n {\n create_thread(true);\n }\n return true;\n }\n\n bool shutdown()\n {\n if (!running)\n {\n return false;\n }\n running = false;\n\n event_mutex.lock();\n _cv.notify_all();\n event_mutex.unlock();\n\n for (auto &i : threads)\n {\n thread *_thread = i.second;\n if (_thread->joinable())\n {\n _thread->join();\n }\n delete _thread;\n }\n\n return true;\n }\n\n void schedule()\n {\n if (n_waiting == 0 && threads.size() < worker_num && max_wait_time > 0)\n {\n double _max_wait_time = _queue.get_max_wait_time();\n if (_max_wait_time > max_wait_time)\n {\n size_t n = 1;\n \/**\n * maybe we can find a better strategy\n *\/\n if (threads.size() + n > worker_num)\n {\n n = worker_num - threads.size();\n }\n swTraceLog(SW_TRACE_AIO, \"Create %zu thread due to wait %fs, we will have %zu threads\", n, _max_wait_time, threads.size() + n);\n while (n--)\n {\n create_thread();\n }\n }\n }\n }\n\n AsyncEvent* dispatch(const AsyncEvent *request)\n {\n if (SwooleTG.aio_schedule) \n {\n schedule();\n }\n auto _event_copy = new AsyncEvent(*request);\n _event_copy->task_id = current_task_id++;\n _event_copy->timestamp = swoole_microtime();\n _event_copy->pipe_fd = SwooleTG.aio_pipe_write;\n event_mutex.lock();\n _queue.push(_event_copy);\n _cv.notify_one();\n event_mutex.unlock();\n return _event_copy;\n }\n\n inline size_t worker_count()\n {\n return threads.size();\n }\n\n inline size_t queue_count()\n {\n return _queue.count();\n }\n\n pid_t current_pid;\n\n void release_thread(thread::id tid)\n {\n auto i = threads.find(tid);\n if (i == threads.end())\n {\n swWarn(\"AIO thread#%zu is missing\", tid);\n return;\n }\n else\n {\n thread *_thread = i->second;\n swTraceLog(SW_TRACE_AIO, \"release idle thread#%zu, we have %zu now\", tid, threads.size() - 1);\n if (_thread->joinable())\n {\n _thread->join();\n }\n threads.erase(i);\n delete _thread;\n }\n }\n\nprivate:\n void create_thread(const bool is_core_worker = false);\n\n size_t core_worker_num;\n size_t worker_num;\n double max_wait_time;\n double max_idle_time;\n\n bool running;\n\n atomic<size_t> n_waiting;\n atomic<size_t> n_closing;\n size_t current_task_id = 0;\n\n unordered_map<thread::id, thread *> threads;\n EventQueue _queue;\n mutex event_mutex;\n condition_variable _cv;\n};\n\/\/-------------------------------------------------------------------------------\n}};\n\nstatic swoole::async::ThreadPool *pool = nullptr;\n\nvoid swoole::async::ThreadPool::create_thread(const bool is_core_worker)\n{\n try\n {\n thread *_thread = new thread([this, is_core_worker]()\n {\n bool exit_flag = false;\n\n SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE);\n if (SwooleTG.buffer_stack == nullptr)\n {\n return;\n }\n\n swSignal_none();\n\n while (running)\n {\n AsyncEvent *event = _queue.pop();\n if (event)\n {\n if (sw_unlikely(event->handler == nullptr))\n {\n event->error = SW_ERROR_AIO_BAD_REQUEST;\n event->ret = -1;\n }\n else if (sw_unlikely(event->canceled))\n {\n event->error = SW_ERROR_AIO_CANCELED;\n event->ret = -1;\n }\n else\n {\n event->handler(event);\n }\n\n swTraceLog(SW_TRACE_AIO, \"aio_thread %s. ret=%d, error=%d\", event->ret > 0 ? \"ok\" : \"failed\", event->ret, event->error);\n\n _send_event:\n while (true)\n {\n int ret = write(event->pipe_fd, &event, sizeof(event));\n if (ret < 0)\n {\n if (errno == EAGAIN)\n {\n swSocket_wait(SwooleTG.aio_pipe_write, 1000, SW_EVENT_WRITE);\n continue;\n }\n else if (errno == EINTR)\n {\n continue;\n }\n else\n {\n swSysWarn(\"sendto swoole_aio_pipe_write failed\");\n }\n }\n break;\n }\n\n \/\/ exit\n if (exit_flag)\n {\n n_closing--;\n break;\n }\n }\n else if (running)\n {\n unique_lock<mutex> lock(event_mutex);\n if (_queue.count() > 0)\n {\n continue;\n }\n ++n_waiting;\n if (is_core_worker || max_idle_time <= 0)\n {\n _cv.wait(lock);\n }\n else\n {\n while (true)\n {\n if (_cv.wait_for(lock, chrono::microseconds((size_t) (max_idle_time * 1000 * 1000))) == cv_status::timeout)\n {\n if (running && n_closing != 0)\n {\n \/\/ wait for the next round\n continue;\n }\n \/* notifies the main thread to release this thread *\/\n event = new AsyncEvent;\n event->object = new thread::id(this_thread::get_id());\n event->callback = aio_thread_release;\n event->pipe_fd = SwooleG.aio_default_pipe_fd;\n\n --n_waiting;\n ++n_closing;\n exit_flag = true;\n goto _send_event;\n }\n break;\n }\n }\n --n_waiting;\n }\n }\n });\n threads[_thread->get_id()] = _thread;\n }\n catch (const std::system_error& e)\n {\n swSysNotice(\"create aio thread failed, please check your system configuration or adjust aio_worker_num\");\n return;\n }\n}\n\nstatic void aio_thread_release(swAio_event *event)\n{\n thread::id *tid = static_cast<thread::id *>(event->object);\n pool->release_thread(*tid);\n delete tid;\n \/\/ balance\n SwooleTG.aio_task_num++;\n}\n\nstatic void swAio_free(void *private_data)\n{\n if (!SwooleTG.aio_init)\n {\n return;\n }\n SwooleTG.aio_init = 0;\n swoole_event_del(SwooleTG.aio_pipe_read);\n SwooleTG.aio_pipe.close(&SwooleTG.aio_pipe);\n if (pool->current_pid == getpid())\n {\n if ((--refcount) == 0)\n {\n delete pool;\n pool = nullptr;\n }\n }\n}\n\nstatic int swAio_init()\n{\n if (SwooleTG.aio_init)\n {\n swWarn(\"aio_thread_pool has already been initialized\");\n return SW_ERR;\n }\n if (!SwooleTG.reactor)\n {\n swWarn(\"no event loop, cannot initialized\");\n return SW_ERR;\n }\n\n if (swPipeBase_create(&SwooleTG.aio_pipe, 0) < 0)\n {\n swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL);\n }\n\n SwooleTG.aio_pipe_read = SwooleTG.aio_pipe.getFd(&SwooleTG.aio_pipe, 0);\n SwooleTG.aio_pipe_write = SwooleTG.aio_pipe.getFd(&SwooleTG.aio_pipe, 1);\n swoole_event_add(SwooleTG.aio_pipe_read, SW_EVENT_READ, SW_FD_AIO);\n swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr);\n\n init_lock.lock();\n if ((refcount++) == 0)\n {\n pool = new swoole::async::ThreadPool(SwooleG.aio_core_worker_num, SwooleG.aio_worker_num,\n SwooleG.aio_max_wait_time, SwooleG.aio_max_idle_time);\n pool->start();\n SwooleTG.aio_schedule = 1;\n SwooleG.aio_default_pipe_fd = SwooleTG.aio_pipe_write;\n }\n SwooleTG.aio_init = 1;\n init_lock.unlock();\n\n return SW_OK;\n}\n\nsize_t swAio_thread_count()\n{\n return pool ? pool->worker_count() : 0;\n}\n\nssize_t swAio_dispatch(const swAio_event *request)\n{\n AsyncEvent *event = swAio_dispatch2(request);\n if (event == nullptr)\n {\n return -1;\n }\n return event->task_id;\n}\n\nswAio_event* swAio_dispatch2(const swAio_event *request)\n{\n if (sw_unlikely(!SwooleTG.aio_init))\n {\n swAio_init();\n }\n AsyncEvent *event = pool->dispatch(request);\n if (sw_likely(event))\n {\n SwooleTG.aio_task_num++;\n }\n return event;\n}\n\nint swAio_callback(swReactor *reactor, swEvent *event)\n{\n if (SwooleTG.aio_schedule) \n {\n pool->schedule();\n }\n\n AsyncEvent *events[SW_AIO_EVENT_NUM];\n ssize_t n = read(event->fd, events, sizeof(AsyncEvent *) * SW_AIO_EVENT_NUM);\n if (n < 0)\n {\n swSysWarn(\"read() aio events failed\");\n return SW_ERR;\n }\n for (size_t i = 0; i < n \/ sizeof(AsyncEvent *); i++)\n {\n AsyncEvent *event = events[i];\n if (!event->canceled)\n {\n event->callback(events[i]);\n }\n SwooleTG.aio_task_num--;\n delete event;\n }\n\n return SW_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <bitcoin\/network\/network.hpp>\n\n#include <functional>\n#include <algorithm>\n#include <iostream>\n\n#include <bitcoin\/utility\/logger.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\nacceptor::acceptor(threadpool& pool, tcp_acceptor_ptr tcp_accept)\n : pool_(pool), tcp_accept_(tcp_accept)\n{\n}\nvoid acceptor::accept(accept_handler handle_accept)\n{\n socket_ptr socket =\n std::make_shared<tcp::socket>(pool_.service());\n tcp_accept_->async_accept(*socket,\n std::bind(&acceptor::call_handle_accept, shared_from_this(),\n _1, socket, handle_accept));\n}\nvoid acceptor::call_handle_accept(const boost::system::error_code& ec,\n socket_ptr socket, accept_handler handle_accept)\n{\n if (ec)\n {\n handle_accept(error::accept_failed, nullptr);\n return;\n }\n auto proxy = std::make_shared<channel_proxy>(pool_, socket);\n proxy->start();\n channel_ptr channel_object = std::make_shared<channel>(proxy);\n handle_accept(std::error_code(), channel_object);\n}\n\nclass perform_connect_with_timeout\n : public std::enable_shared_from_this<perform_connect_with_timeout>\n{\npublic:\n perform_connect_with_timeout(threadpool& pool)\n : timer_(pool.service())\n {\n socket_ = std::make_shared<tcp::socket>(pool.service());\n proxy_ = std::make_shared<channel_proxy>(pool, socket_);\n }\n\n void start(tcp::resolver::iterator endpoint_iterator, size_t timeout,\n network::connect_handler handle_connect)\n {\n timer_.expires_from_now(boost::posix_time::seconds(timeout));\n timer_.async_wait(std::bind(\n &perform_connect_with_timeout::close, shared_from_this(), _1));\n\n boost::asio::async_connect(*socket_, endpoint_iterator,\n std::bind(&perform_connect_with_timeout::call_connect_handler,\n shared_from_this(), _1, _2, handle_connect));\n }\n\nprivate:\n void call_connect_handler(const boost::system::error_code& ec,\n tcp::resolver::iterator next, network::connect_handler handle_connect)\n {\n if (ec)\n {\n handle_connect(error::network_unreachable, nullptr);\n return;\n }\n proxy_->start();\n channel_ptr channel_object = std::make_shared<channel>(proxy_);\n handle_connect(std::error_code(), channel_object);\n }\n\n void close(const boost::system::error_code& ec)\n {\n if (ec)\n \/\/ should be boost::asio::error::operation_aborted)\n proxy_->stop();\n }\n\n socket_ptr socket_;\n channel::channel_proxy_ptr proxy_;\n boost::asio::deadline_timer timer_;\n};\n\nnetwork::network(threadpool& pool)\n : pool_(pool)\n{\n}\n\nvoid network::resolve_handler(const boost::system::error_code& ec,\n tcp::resolver::iterator endpoint_iterator,\n connect_handler handle_connect, resolver_ptr, query_ptr)\n{\n if (ec)\n {\n handle_connect(error::resolve_failed, nullptr);\n return;\n }\n auto connect =\n std::make_shared<perform_connect_with_timeout>(pool_);\n connect->start(endpoint_iterator, 5, handle_connect);\n}\n\nvoid network::connect(const std::string& hostname, uint16_t port,\n connect_handler handle_connect)\n{\n resolver_ptr resolver =\n std::make_shared<tcp::resolver>(pool_.service());\n query_ptr query =\n std::make_shared<tcp::resolver::query>(hostname, std::to_string(port));\n resolver->async_resolve(*query,\n std::bind(&network::resolve_handler,\n this, _1, _2, handle_connect, resolver, query));\n}\n\n\/\/ I personally don't like how exceptions mess with the program flow\nbool listen_error(const boost::system::error_code& ec,\n network::listen_handler handle_listen)\n{\n if (ec == boost::system::errc::address_in_use)\n {\n handle_listen(error::address_in_use, nullptr);\n return true;\n }\n else if (ec)\n {\n handle_listen(error::listen_failed, nullptr);\n return true;\n }\n return false;\n}\nvoid network::listen(uint16_t port, listen_handler handle_listen)\n{\n tcp::endpoint endpoint(tcp::v4(), port);\n acceptor::tcp_acceptor_ptr tcp_accept =\n std::make_shared<tcp::acceptor>(pool_.service());\n \/\/ Need to check error codes for functions\n boost::system::error_code ec;\n tcp_accept->open(endpoint.protocol(), ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->set_option(tcp::acceptor::reuse_address(true), ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->bind(endpoint, ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->listen(boost::asio::socket_base::max_connections, ec);\n if (listen_error(ec, handle_listen))\n return;\n\n acceptor_ptr accept =\n std::make_shared<acceptor>(pool_, tcp_accept);\n handle_listen(std::error_code(), accept);\n}\n\n} \/\/ namespace libbitcoin\n\n<commit_msg>logic error in timeout stuff.<commit_after>#include <bitcoin\/network\/network.hpp>\n\n#include <functional>\n#include <algorithm>\n#include <iostream>\n\n#include <bitcoin\/utility\/logger.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\nacceptor::acceptor(threadpool& pool, tcp_acceptor_ptr tcp_accept)\n : pool_(pool), tcp_accept_(tcp_accept)\n{\n}\nvoid acceptor::accept(accept_handler handle_accept)\n{\n socket_ptr socket =\n std::make_shared<tcp::socket>(pool_.service());\n tcp_accept_->async_accept(*socket,\n std::bind(&acceptor::call_handle_accept, shared_from_this(),\n _1, socket, handle_accept));\n}\nvoid acceptor::call_handle_accept(const boost::system::error_code& ec,\n socket_ptr socket, accept_handler handle_accept)\n{\n if (ec)\n {\n handle_accept(error::accept_failed, nullptr);\n return;\n }\n auto proxy = std::make_shared<channel_proxy>(pool_, socket);\n proxy->start();\n channel_ptr channel_object = std::make_shared<channel>(proxy);\n handle_accept(std::error_code(), channel_object);\n}\n\nclass perform_connect_with_timeout\n : public std::enable_shared_from_this<perform_connect_with_timeout>\n{\npublic:\n perform_connect_with_timeout(threadpool& pool)\n : timer_(pool.service())\n {\n socket_ = std::make_shared<tcp::socket>(pool.service());\n proxy_ = std::make_shared<channel_proxy>(pool, socket_);\n }\n\n void start(tcp::resolver::iterator endpoint_iterator, size_t timeout,\n network::connect_handler handle_connect)\n {\n timer_.expires_from_now(boost::posix_time::seconds(timeout));\n timer_.async_wait(std::bind(\n &perform_connect_with_timeout::close, shared_from_this(), _1));\n\n boost::asio::async_connect(*socket_, endpoint_iterator,\n std::bind(&perform_connect_with_timeout::call_connect_handler,\n shared_from_this(), _1, _2, handle_connect));\n }\n\nprivate:\n void call_connect_handler(const boost::system::error_code& ec,\n tcp::resolver::iterator next, network::connect_handler handle_connect)\n {\n if (ec)\n {\n handle_connect(error::network_unreachable, nullptr);\n return;\n }\n proxy_->start();\n channel_ptr channel_object = std::make_shared<channel>(proxy_);\n handle_connect(std::error_code(), channel_object);\n }\n\n void close(const boost::system::error_code& ec)\n {\n \/\/ ec should be boost::asio::error::operation_aborted or nothing.\n if (!ec)\n proxy_->stop();\n }\n\n socket_ptr socket_;\n channel::channel_proxy_ptr proxy_;\n boost::asio::deadline_timer timer_;\n};\n\nnetwork::network(threadpool& pool)\n : pool_(pool)\n{\n}\n\nvoid network::resolve_handler(const boost::system::error_code& ec,\n tcp::resolver::iterator endpoint_iterator,\n connect_handler handle_connect, resolver_ptr, query_ptr)\n{\n if (ec)\n {\n handle_connect(error::resolve_failed, nullptr);\n return;\n }\n auto connect =\n std::make_shared<perform_connect_with_timeout>(pool_);\n connect->start(endpoint_iterator, 5, handle_connect);\n}\n\nvoid network::connect(const std::string& hostname, uint16_t port,\n connect_handler handle_connect)\n{\n resolver_ptr resolver =\n std::make_shared<tcp::resolver>(pool_.service());\n query_ptr query =\n std::make_shared<tcp::resolver::query>(hostname, std::to_string(port));\n resolver->async_resolve(*query,\n std::bind(&network::resolve_handler,\n this, _1, _2, handle_connect, resolver, query));\n}\n\n\/\/ I personally don't like how exceptions mess with the program flow\nbool listen_error(const boost::system::error_code& ec,\n network::listen_handler handle_listen)\n{\n if (ec == boost::system::errc::address_in_use)\n {\n handle_listen(error::address_in_use, nullptr);\n return true;\n }\n else if (ec)\n {\n handle_listen(error::listen_failed, nullptr);\n return true;\n }\n return false;\n}\nvoid network::listen(uint16_t port, listen_handler handle_listen)\n{\n tcp::endpoint endpoint(tcp::v4(), port);\n acceptor::tcp_acceptor_ptr tcp_accept =\n std::make_shared<tcp::acceptor>(pool_.service());\n \/\/ Need to check error codes for functions\n boost::system::error_code ec;\n tcp_accept->open(endpoint.protocol(), ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->set_option(tcp::acceptor::reuse_address(true), ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->bind(endpoint, ec);\n if (listen_error(ec, handle_listen))\n return;\n tcp_accept->listen(boost::asio::socket_base::max_connections, ec);\n if (listen_error(ec, handle_listen))\n return;\n\n acceptor_ptr accept =\n std::make_shared<acceptor>(pool_, tcp_accept);\n handle_listen(std::error_code(), accept);\n}\n\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"} {"text":"<commit_before>#include \"util.hh\"\n#include \"get-drvs.hh\"\n#include \"derivations.hh\"\n#include \"store-api.hh\"\n#include \"globals.hh\"\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"profiles.hh\"\n\n\nnamespace nix {\n\n\nstatic void readLegacyManifest(const Path & path, DrvInfos & elems);\n\n\nDrvInfos queryInstalled(EvalState & state, const Path & userEnv)\n{\n DrvInfos elems;\n\n Path manifestFile = userEnv + \"\/manifest.nix\";\n Path oldManifestFile = userEnv + \"\/manifest\";\n\n if (pathExists(manifestFile)) {\n Value v;\n state.evalFile(manifestFile, v);\n Bindings bindings;\n getDerivations(state, v, \"\", bindings, elems, false);\n } else if (pathExists(oldManifestFile))\n readLegacyManifest(oldManifestFile, elems);\n\n return elems;\n}\n\n\nbool createUserEnv(EvalState & state, DrvInfos & elems,\n const Path & profile, bool keepDerivations,\n const string & lockToken)\n{\n \/* Build the components in the user environment, if they don't\n exist already. *\/\n PathSet drvsToBuild;\n foreach (DrvInfos::const_iterator, i, elems)\n if (i->queryDrvPath(state) != \"\")\n drvsToBuild.insert(i->queryDrvPath(state));\n\n debug(format(\"building user environment dependencies\"));\n store->buildPaths(drvsToBuild, state.repair);\n\n \/* Construct the whole top level derivation. *\/\n PathSet references;\n Value manifest;\n state.mkList(manifest, elems.size());\n unsigned int n = 0;\n foreach (DrvInfos::iterator, i, elems) {\n \/* Create a pseudo-derivation containing the name, system,\n output paths, and optionally the derivation path, as well\n as the meta attributes. *\/\n Path drvPath = keepDerivations ? i->queryDrvPath(state) : \"\";\n\n Value & v(*state.allocValue());\n manifest.list.elems[n++] = &v;\n state.mkAttrs(v, 16);\n\n mkString(*state.allocAttr(v, state.sType), \"derivation\");\n mkString(*state.allocAttr(v, state.sName), i->name);\n if (!i->system.empty())\n mkString(*state.allocAttr(v, state.sSystem), i->system);\n mkString(*state.allocAttr(v, state.sOutPath), i->queryOutPath(state));\n if (drvPath != \"\")\n mkString(*state.allocAttr(v, state.sDrvPath), i->queryDrvPath(state));\n\n \/\/ Copy each output.\n DrvInfo::Outputs outputs = i->queryOutputs(state);\n Value & vOutputs = *state.allocAttr(v, state.sOutputs);\n state.mkList(vOutputs, outputs.size());\n unsigned int m = 0;\n foreach (DrvInfo::Outputs::iterator, j, outputs) {\n mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j->first);\n Value & vOutputs = *state.allocAttr(v, state.symbols.create(j->first));\n state.mkAttrs(vOutputs, 2);\n mkString(*state.allocAttr(vOutputs, state.sOutPath), j->second);\n\n \/* This is only necessary when installing store paths, e.g.,\n `nix-env -i \/nix\/store\/abcd...-foo'. *\/\n store->addTempRoot(j->second);\n store->ensurePath(j->second);\n\n references.insert(j->second);\n }\n\n \/\/ Copy the meta attributes.\n Value & vMeta = *state.allocAttr(v, state.sMeta);\n state.mkAttrs(vMeta, 16);\n\n MetaInfo meta = i->queryMetaInfo(state);\n\n foreach (MetaInfo::const_iterator, j, meta) {\n Value & v2(*state.allocAttr(vMeta, state.symbols.create(j->first)));\n switch (j->second.type) {\n case MetaValue::tpInt: mkInt(v2, j->second.intValue); break;\n case MetaValue::tpString: mkString(v2, j->second.stringValue); break;\n case MetaValue::tpStrings: {\n state.mkList(v2, j->second.stringValues.size());\n unsigned int m = 0;\n foreach (Strings::const_iterator, k, j->second.stringValues) {\n v2.list.elems[m] = state.allocValue();\n mkString(*v2.list.elems[m++], *k);\n }\n break;\n }\n default: abort();\n }\n }\n\n vMeta.attrs->sort();\n v.attrs->sort();\n\n if (drvPath != \"\") references.insert(drvPath);\n }\n\n \/* Also write a copy of the list of user environment elements to\n the store; we need it for future modifications of the\n environment. *\/\n Path manifestFile = store->addTextToStore(\"env-manifest.nix\",\n (format(\"%1%\") % manifest).str(), references);\n\n \/* Get the environment builder expression. *\/\n Value envBuilder;\n state.evalFile(state.findFile(\"nix\/buildenv.nix\"), envBuilder);\n\n \/* Construct a Nix expression that calls the user environment\n builder with the manifest as argument. *\/\n Value args, topLevel;\n state.mkAttrs(args, 3);\n mkString(*state.allocAttr(args, state.symbols.create(\"manifest\")),\n manifestFile, singleton<PathSet>(manifestFile));\n args.attrs->push_back(Attr(state.symbols.create(\"derivations\"), &manifest));\n args.attrs->sort();\n mkApp(topLevel, envBuilder, args);\n\n \/* Evaluate it. *\/\n debug(\"evaluating user environment builder\");\n DrvInfo topLevelDrv;\n if (!getDerivation(state, topLevel, topLevelDrv, false))\n abort();\n\n \/* Realise the resulting store expression. *\/\n debug(\"building user environment\");\n store->buildPaths(singleton<PathSet>(topLevelDrv.queryDrvPath(state)), state.repair);\n\n \/* Switch the current user environment to the output path. *\/\n PathLocks lock;\n lockProfile(lock, profile);\n\n Path lockTokenCur = optimisticLockProfile(profile);\n if (lockToken != lockTokenCur) {\n printMsg(lvlError, format(\"profile `%1%' changed while we were busy; restarting\") % profile);\n return false;\n }\n\n debug(format(\"switching to new user environment\"));\n Path generation = createGeneration(profile, topLevelDrv.queryOutPath(state));\n switchLink(profile, generation);\n\n return true;\n}\n\n\n\/* Code for parsing manifests in the old textual ATerm format. *\/\n\nstatic string parseStr(std::istream & str)\n{\n expect(str, \"Str(\");\n string s = parseString(str);\n expect(str, \",[])\");\n return s;\n}\n\n\nstatic string parseWord(std::istream & str)\n{\n string res;\n while (isalpha(str.peek()))\n res += str.get();\n return res;\n}\n\n\nstatic MetaInfo parseMeta(std::istream & str)\n{\n MetaInfo meta;\n\n expect(str, \"Attrs([\");\n while (!endOfList(str)) {\n expect(str, \"Bind(\");\n\n MetaValue value;\n\n string name = parseString(str);\n expect(str, \",\");\n\n string type = parseWord(str);\n\n if (type == \"Str\") {\n expect(str, \"(\");\n value.type = MetaValue::tpString;\n value.stringValue = parseString(str);\n expect(str, \",[])\");\n }\n\n else if (type == \"List\") {\n expect(str, \"([\");\n value.type = MetaValue::tpStrings;\n while (!endOfList(str))\n value.stringValues.push_back(parseStr(str));\n expect(str, \")\");\n }\n\n else throw Error(format(\"unexpected token `%1%'\") % type);\n\n expect(str, \",NoPos)\");\n meta[name] = value;\n }\n\n expect(str, \")\");\n\n return meta;\n}\n\n\nstatic void readLegacyManifest(const Path & path, DrvInfos & elems)\n{\n string manifest = readFile(path);\n std::istringstream str(manifest);\n expect(str, \"List([\");\n\n unsigned int n = 0;\n\n while (!endOfList(str)) {\n DrvInfo elem;\n expect(str, \"Attrs([\");\n\n while (!endOfList(str)) {\n expect(str, \"Bind(\");\n string name = parseString(str);\n expect(str, \",\");\n\n if (name == \"meta\") elem.setMetaInfo(parseMeta(str));\n else {\n string value = parseStr(str);\n if (name == \"name\") elem.name = value;\n else if (name == \"outPath\") elem.setOutPath(value);\n else if (name == \"drvPath\") elem.setDrvPath(value);\n else if (name == \"system\") elem.system = value;\n }\n\n expect(str, \",NoPos)\");\n }\n\n expect(str, \")\");\n\n if (elem.name != \"\") {\n elem.attrPath = int2String(n++);\n elems.push_back(elem);\n }\n }\n\n expect(str, \")\");\n}\n\n\n}\n<commit_msg>Drop support for user environment manifests in ATerm format<commit_after>#include \"util.hh\"\n#include \"get-drvs.hh\"\n#include \"derivations.hh\"\n#include \"store-api.hh\"\n#include \"globals.hh\"\n#include \"shared.hh\"\n#include \"eval.hh\"\n#include \"profiles.hh\"\n\n\nnamespace nix {\n\n\nDrvInfos queryInstalled(EvalState & state, const Path & userEnv)\n{\n DrvInfos elems;\n Path manifestFile = userEnv + \"\/manifest.nix\";\n if (pathExists(manifestFile)) {\n Value v;\n state.evalFile(manifestFile, v);\n Bindings bindings;\n getDerivations(state, v, \"\", bindings, elems, false);\n }\n return elems;\n}\n\n\nbool createUserEnv(EvalState & state, DrvInfos & elems,\n const Path & profile, bool keepDerivations,\n const string & lockToken)\n{\n \/* Build the components in the user environment, if they don't\n exist already. *\/\n PathSet drvsToBuild;\n foreach (DrvInfos::const_iterator, i, elems)\n if (i->queryDrvPath(state) != \"\")\n drvsToBuild.insert(i->queryDrvPath(state));\n\n debug(format(\"building user environment dependencies\"));\n store->buildPaths(drvsToBuild, state.repair);\n\n \/* Construct the whole top level derivation. *\/\n PathSet references;\n Value manifest;\n state.mkList(manifest, elems.size());\n unsigned int n = 0;\n foreach (DrvInfos::iterator, i, elems) {\n \/* Create a pseudo-derivation containing the name, system,\n output paths, and optionally the derivation path, as well\n as the meta attributes. *\/\n Path drvPath = keepDerivations ? i->queryDrvPath(state) : \"\";\n\n Value & v(*state.allocValue());\n manifest.list.elems[n++] = &v;\n state.mkAttrs(v, 16);\n\n mkString(*state.allocAttr(v, state.sType), \"derivation\");\n mkString(*state.allocAttr(v, state.sName), i->name);\n if (!i->system.empty())\n mkString(*state.allocAttr(v, state.sSystem), i->system);\n mkString(*state.allocAttr(v, state.sOutPath), i->queryOutPath(state));\n if (drvPath != \"\")\n mkString(*state.allocAttr(v, state.sDrvPath), i->queryDrvPath(state));\n\n \/\/ Copy each output.\n DrvInfo::Outputs outputs = i->queryOutputs(state);\n Value & vOutputs = *state.allocAttr(v, state.sOutputs);\n state.mkList(vOutputs, outputs.size());\n unsigned int m = 0;\n foreach (DrvInfo::Outputs::iterator, j, outputs) {\n mkString(*(vOutputs.list.elems[m++] = state.allocValue()), j->first);\n Value & vOutputs = *state.allocAttr(v, state.symbols.create(j->first));\n state.mkAttrs(vOutputs, 2);\n mkString(*state.allocAttr(vOutputs, state.sOutPath), j->second);\n\n \/* This is only necessary when installing store paths, e.g.,\n `nix-env -i \/nix\/store\/abcd...-foo'. *\/\n store->addTempRoot(j->second);\n store->ensurePath(j->second);\n\n references.insert(j->second);\n }\n\n \/\/ Copy the meta attributes.\n Value & vMeta = *state.allocAttr(v, state.sMeta);\n state.mkAttrs(vMeta, 16);\n\n MetaInfo meta = i->queryMetaInfo(state);\n\n foreach (MetaInfo::const_iterator, j, meta) {\n Value & v2(*state.allocAttr(vMeta, state.symbols.create(j->first)));\n switch (j->second.type) {\n case MetaValue::tpInt: mkInt(v2, j->second.intValue); break;\n case MetaValue::tpString: mkString(v2, j->second.stringValue); break;\n case MetaValue::tpStrings: {\n state.mkList(v2, j->second.stringValues.size());\n unsigned int m = 0;\n foreach (Strings::const_iterator, k, j->second.stringValues) {\n v2.list.elems[m] = state.allocValue();\n mkString(*v2.list.elems[m++], *k);\n }\n break;\n }\n default: abort();\n }\n }\n\n vMeta.attrs->sort();\n v.attrs->sort();\n\n if (drvPath != \"\") references.insert(drvPath);\n }\n\n \/* Also write a copy of the list of user environment elements to\n the store; we need it for future modifications of the\n environment. *\/\n Path manifestFile = store->addTextToStore(\"env-manifest.nix\",\n (format(\"%1%\") % manifest).str(), references);\n\n \/* Get the environment builder expression. *\/\n Value envBuilder;\n state.evalFile(state.findFile(\"nix\/buildenv.nix\"), envBuilder);\n\n \/* Construct a Nix expression that calls the user environment\n builder with the manifest as argument. *\/\n Value args, topLevel;\n state.mkAttrs(args, 3);\n mkString(*state.allocAttr(args, state.symbols.create(\"manifest\")),\n manifestFile, singleton<PathSet>(manifestFile));\n args.attrs->push_back(Attr(state.symbols.create(\"derivations\"), &manifest));\n args.attrs->sort();\n mkApp(topLevel, envBuilder, args);\n\n \/* Evaluate it. *\/\n debug(\"evaluating user environment builder\");\n DrvInfo topLevelDrv;\n if (!getDerivation(state, topLevel, topLevelDrv, false))\n abort();\n\n \/* Realise the resulting store expression. *\/\n debug(\"building user environment\");\n store->buildPaths(singleton<PathSet>(topLevelDrv.queryDrvPath(state)), state.repair);\n\n \/* Switch the current user environment to the output path. *\/\n PathLocks lock;\n lockProfile(lock, profile);\n\n Path lockTokenCur = optimisticLockProfile(profile);\n if (lockToken != lockTokenCur) {\n printMsg(lvlError, format(\"profile `%1%' changed while we were busy; restarting\") % profile);\n return false;\n }\n\n debug(format(\"switching to new user environment\"));\n Path generation = createGeneration(profile, topLevelDrv.queryOutPath(state));\n switchLink(profile, generation);\n\n return true;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kdebug.h>\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n if (!Generator::instance) {\n Generator::instance = new Generator();\n }\n return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n delete Generator::instance;\n Generator::instance = 0;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n KDebug::Block idealBlock(\"Ideal Config\");\n KScreen::Config* config = KScreen::Config::current();\n if (!config) {\n kDebug() << \"Unable get current config\";\n return 0;\n }\n\n disableAllDisconnectedOutputs(config->outputs());\n\n KScreen::OutputList outputs = config->connectedOutputs();\n\n kDebug() << \"Connected outputs: \" << outputs.count();\n if (outputs.count() == 1) {\n singleOutput(outputs);\n return config;\n }\n\n if (isLaptop()) {\n laptop(outputs);\n return config;\n }\n\n extendToRight(outputs);\n\n return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n KDebug::Block switchBlock(\"Display Switch\");\n KScreen::Config* config = KScreen::Config::current();\n if (!config) {\n kDebug() << \"Unable to get current config\";\n return 0;\n }\n\n KScreen::OutputList outputs = config->connectedOutputs();\n\n if (outputs.count() < 2) {\n singleOutput(outputs);\n return config;\n }\n\n if (outputs.count() > 2) {\n extendToRight(outputs);\n return config;\n }\n\n KScreen::Output* embedded, *external;\n embedded = embeddedOutput(outputs);\n outputs.remove(embedded->id());\n external = outputs.value(outputs.keys().first());\n\n if (iteration == 1) {\n kDebug() << \"Cloning\";\n KScreen::ModeList modes = embedded->modes();\n QMap<QString, QSize> embeddedModeSize;\n Q_FOREACH(KScreen::Mode* mode, modes) {\n embeddedModeSize.insert(mode->id(), mode->size());\n }\n\n QList<QString> embeddedKeys;\n KScreen::ModeList externalCommon;\n KScreen::ModeList externalModes = external->modes();\n Q_FOREACH(KScreen::Mode* mode, externalModes) {\n if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n externalCommon.insert(mode->id(), mode);\n embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n }\n }\n\n KScreen::ModeList embeddedCommon;\n Q_FOREACH(const QString& key, embeddedKeys) {\n embeddedCommon.insert(key, modes[key]);\n }\n\n KScreen::Mode* biggestEmbedded = biggestMode(embeddedCommon);\n KScreen::Mode* biggestExternal = biggestMode(externalCommon);\n\n embedded->setEnabled(true);\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(biggestEmbedded->id());\n external->setEnabled(true);\n external->setPos(QPoint(0,0));\n external->setCurrentModeId(biggestExternal->id());\n\n return config;\n }\n\n if (iteration == 2) {\n kDebug() << \"Extend to left\";\n external->setEnabled(true);\n external->setPos(QPoint(0,0));\n external->setCurrentModeId(external->preferredModeId());\n\n QSize size = external->currentMode()->size();\n embedded->setPos(QPoint(size.width(), 0));\n embedded->setEnabled(true);\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n return config;\n }\n\n if (iteration == 3) {\n kDebug() << \"Turn of embedded (laptop)\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n external->setEnabled(true);\n external->setPrimary(true);\n external->setCurrentModeId(external->preferredModeId());\n return config;\n }\n\n if (iteration == 4) {\n kDebug() << \"Turn off external screen\";\n embedded->setEnabled(true);\n embedded->setPrimary(true);\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n\n external->setEnabled(false);\n external->setPrimary(false);\n return config;\n }\n\n if (iteration == 5) {\n kDebug() << \"Extend to the right\";\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n embedded->setEnabled(true);\n\n QSize size = embedded->currentMode()->size();\n external->setPos(QPoint(size.width(), 0));\n external->setEnabled(true);\n external->setCurrentModeId(external->preferredModeId());\n external->setPrimary(false);\n\n return config;\n }\n\n return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n KScreen::Output* output = outputs.take(outputs.keys().first());\n Q_ASSERT(output);\n\n output->setCurrentModeId(output->preferredModeId());\n output->setEnabled(true);\n output->setPrimary(true);\n output->setPos(QPoint(0,0));\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n KDebug::Block laptopBlock(\"Laptop config\");\n\n KScreen::Output* embedded = embeddedOutput(outputs);\n Q_ASSERT(embedded);\n\n outputs.remove(embedded->id());\n\n if (outputs.isEmpty()) {\n kWarning() << \"No external outputs found, going for singleOutput()\";\n outputs.insert(embedded->id(), embedded);\n return singleOutput(outputs);\n }\n\n if (isLidClosed() && outputs.count() == 1) {\n kDebug() << \"With lid closed\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n KScreen::Output* external = outputs.value(outputs.keys().first());\n external->setEnabled(true);\n external->setPrimary(true);\n external->setCurrentModeId(external->preferredModeId());\n external->setPos(QPoint(0, 0));\n\n return;\n }\n\n if (isLidClosed() && outputs.count() > 1) {\n kDebug() << \"Lid is closed, and more than one output\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n extendToRight(outputs);\n return;\n }\n\n kDebug() << \"Lid is open\";\n \/\/If lid is open, laptop screen shuold be primary\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n embedded->setEnabled(true);\n\n int globalWidth;\n if (embedded->isHorizontal()) {\n globalWidth = embedded->preferredMode()->size().width();\n } else {\n globalWidth = embedded->preferredMode()->size().height();\n }\n KScreen::Output* biggest = biggestOutput(outputs);\n outputs.remove(biggest->id());\n\n biggest->setPos(QPoint(globalWidth, 0));\n biggest->setEnabled(true);\n biggest->setCurrentModeId(biggest->preferredModeId());\n biggest->setPrimary(false);\n\n if (biggest->isHorizontal()) {\n globalWidth += biggest->currentMode()->size().width();\n } else {\n globalWidth += biggest->currentMode()->size().height();\n }\n Q_FOREACH(KScreen::Output* output, outputs) {\n output->setEnabled(true);\n output->setCurrentModeId(output->preferredModeId());\n output->setPos(QPoint(globalWidth, 0));\n output->setPrimary(false);\n\n if (output->isHorizontal()) {\n globalWidth += output->currentMode()->size().width();\n } else {\n globalWidth += output->currentMode()->size().height();\n }\n }\n\n if (isDocked()) {\n kDebug() << \"Docked\";\n embedded->setPrimary(false);\n biggest->setPrimary(true);\n }\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n kDebug() << \"Extending to the right\";\n KScreen::Output* biggest = biggestOutput(outputs);\n Q_ASSERT(biggest);\n\n outputs.remove(biggest->id());\n\n biggest->setEnabled(true);\n biggest->setPrimary(true);\n biggest->setCurrentModeId(biggest->preferredModeId());\n biggest->setPos(QPoint(0,0));\n\n int globalWidth;\n if (biggest->isHorizontal()) {\n globalWidth = biggest->currentMode()->size().width();\n } else {\n globalWidth = biggest->currentMode()->size().height();\n }\n\n Q_FOREACH(KScreen::Output* output, outputs) {\n output->setEnabled(true);\n output->setPrimary(false);\n output->setCurrentModeId(output->preferredModeId());\n output->setPos(QPoint(globalWidth, 0));\n\n if (output->isHorizontal()) {\n globalWidth += output->currentMode()->size().width();\n } else {\n globalWidth += output->currentMode()->size().height();\n }\n }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n int area, total = 0;\n KScreen::Mode* biggest = 0;\n Q_FOREACH(KScreen::Mode* mode, modes) {\n area = mode->size().width() * mode->size().height();\n if (area < total) {\n continue;\n }\n if (area == total && mode->refreshRate() > biggest->refreshRate()) {\n biggest = mode;\n continue;\n }\n\n total = area;\n biggest = mode;\n }\n\n return biggest;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n int area, total = 0;\n KScreen::Output* biggest = 0;\n Q_FOREACH(KScreen::Output* output, outputs) {\n KScreen::Mode* mode = output->preferredMode();\n area = mode->size().width() * mode->size().height();\n if (area < total) {\n continue;\n }\n\n total = area;\n biggest = output;\n }\n\n return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n KDebug::Block disableBlock(\"Disabling disconnected screens\");\n Q_FOREACH(KScreen::Output* output, outputs) {\n if (!output->isConnected()) {\n kDebug() << output->name() << \" Disabled\";\n output->setEnabled(false);\n output->setPrimary(false);\n }\n }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n Q_FOREACH(KScreen::Output* output, outputs) {\n if (!isEmbedded(output->name())) {\n continue;\n }\n\n return output;\n }\n\n return 0;\n}\n\nbool Generator::isLaptop()\n{\n if (m_forceLaptop) {\n return true;\n }\n\n return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n if (m_forceLidClosed) {\n return true;\n }\n\n return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n if (m_forceDocked) {\n return true;\n }\n\n return Device::self()->isDocked();\n}\n\nbool Generator::isEmbedded(const QString &name)\n{\n QStringList embedded;\n embedded << \"LVDS\";\n embedded << \"IDP\";\n embedded << \"EDP\";\n\n Q_FOREACH(const QString &pre, embedded) {\n if (name.toUpper().startsWith(pre)) {\n return true;\n }\n }\n\n return false;\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n m_forceDocked = force;\n}\n<commit_msg>If the mode area is the same but the refresh is smaller, continue<commit_after>\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kdebug.h>\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n if (!Generator::instance) {\n Generator::instance = new Generator();\n }\n return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n delete Generator::instance;\n Generator::instance = 0;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n KDebug::Block idealBlock(\"Ideal Config\");\n KScreen::Config* config = KScreen::Config::current();\n if (!config) {\n kDebug() << \"Unable get current config\";\n return 0;\n }\n\n disableAllDisconnectedOutputs(config->outputs());\n\n KScreen::OutputList outputs = config->connectedOutputs();\n\n kDebug() << \"Connected outputs: \" << outputs.count();\n if (outputs.count() == 1) {\n singleOutput(outputs);\n return config;\n }\n\n if (isLaptop()) {\n laptop(outputs);\n return config;\n }\n\n extendToRight(outputs);\n\n return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n KDebug::Block switchBlock(\"Display Switch\");\n KScreen::Config* config = KScreen::Config::current();\n if (!config) {\n kDebug() << \"Unable to get current config\";\n return 0;\n }\n\n KScreen::OutputList outputs = config->connectedOutputs();\n\n if (outputs.count() < 2) {\n singleOutput(outputs);\n return config;\n }\n\n if (outputs.count() > 2) {\n extendToRight(outputs);\n return config;\n }\n\n KScreen::Output* embedded, *external;\n embedded = embeddedOutput(outputs);\n outputs.remove(embedded->id());\n external = outputs.value(outputs.keys().first());\n\n if (iteration == 1) {\n kDebug() << \"Cloning\";\n KScreen::ModeList modes = embedded->modes();\n QMap<QString, QSize> embeddedModeSize;\n Q_FOREACH(KScreen::Mode* mode, modes) {\n embeddedModeSize.insert(mode->id(), mode->size());\n }\n\n QList<QString> embeddedKeys;\n KScreen::ModeList externalCommon;\n KScreen::ModeList externalModes = external->modes();\n Q_FOREACH(KScreen::Mode* mode, externalModes) {\n if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n externalCommon.insert(mode->id(), mode);\n embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n }\n }\n\n KScreen::ModeList embeddedCommon;\n Q_FOREACH(const QString& key, embeddedKeys) {\n embeddedCommon.insert(key, modes[key]);\n }\n\n KScreen::Mode* biggestEmbedded = biggestMode(embeddedCommon);\n KScreen::Mode* biggestExternal = biggestMode(externalCommon);\n\n embedded->setEnabled(true);\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(biggestEmbedded->id());\n external->setEnabled(true);\n external->setPos(QPoint(0,0));\n external->setCurrentModeId(biggestExternal->id());\n\n return config;\n }\n\n if (iteration == 2) {\n kDebug() << \"Extend to left\";\n external->setEnabled(true);\n external->setPos(QPoint(0,0));\n external->setCurrentModeId(external->preferredModeId());\n\n QSize size = external->currentMode()->size();\n embedded->setPos(QPoint(size.width(), 0));\n embedded->setEnabled(true);\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n return config;\n }\n\n if (iteration == 3) {\n kDebug() << \"Turn of embedded (laptop)\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n external->setEnabled(true);\n external->setPrimary(true);\n external->setCurrentModeId(external->preferredModeId());\n return config;\n }\n\n if (iteration == 4) {\n kDebug() << \"Turn off external screen\";\n embedded->setEnabled(true);\n embedded->setPrimary(true);\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n\n external->setEnabled(false);\n external->setPrimary(false);\n return config;\n }\n\n if (iteration == 5) {\n kDebug() << \"Extend to the right\";\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n embedded->setEnabled(true);\n\n QSize size = embedded->currentMode()->size();\n external->setPos(QPoint(size.width(), 0));\n external->setEnabled(true);\n external->setCurrentModeId(external->preferredModeId());\n external->setPrimary(false);\n\n return config;\n }\n\n return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n KScreen::Output* output = outputs.take(outputs.keys().first());\n Q_ASSERT(output);\n\n output->setCurrentModeId(output->preferredModeId());\n output->setEnabled(true);\n output->setPrimary(true);\n output->setPos(QPoint(0,0));\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n KDebug::Block laptopBlock(\"Laptop config\");\n\n KScreen::Output* embedded = embeddedOutput(outputs);\n Q_ASSERT(embedded);\n\n outputs.remove(embedded->id());\n\n if (outputs.isEmpty()) {\n kWarning() << \"No external outputs found, going for singleOutput()\";\n outputs.insert(embedded->id(), embedded);\n return singleOutput(outputs);\n }\n\n if (isLidClosed() && outputs.count() == 1) {\n kDebug() << \"With lid closed\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n KScreen::Output* external = outputs.value(outputs.keys().first());\n external->setEnabled(true);\n external->setPrimary(true);\n external->setCurrentModeId(external->preferredModeId());\n external->setPos(QPoint(0, 0));\n\n return;\n }\n\n if (isLidClosed() && outputs.count() > 1) {\n kDebug() << \"Lid is closed, and more than one output\";\n embedded->setEnabled(false);\n embedded->setPrimary(false);\n\n extendToRight(outputs);\n return;\n }\n\n kDebug() << \"Lid is open\";\n \/\/If lid is open, laptop screen shuold be primary\n embedded->setPos(QPoint(0,0));\n embedded->setCurrentModeId(embedded->preferredModeId());\n embedded->setPrimary(true);\n embedded->setEnabled(true);\n\n int globalWidth;\n if (embedded->isHorizontal()) {\n globalWidth = embedded->preferredMode()->size().width();\n } else {\n globalWidth = embedded->preferredMode()->size().height();\n }\n KScreen::Output* biggest = biggestOutput(outputs);\n outputs.remove(biggest->id());\n\n biggest->setPos(QPoint(globalWidth, 0));\n biggest->setEnabled(true);\n biggest->setCurrentModeId(biggest->preferredModeId());\n biggest->setPrimary(false);\n\n if (biggest->isHorizontal()) {\n globalWidth += biggest->currentMode()->size().width();\n } else {\n globalWidth += biggest->currentMode()->size().height();\n }\n Q_FOREACH(KScreen::Output* output, outputs) {\n output->setEnabled(true);\n output->setCurrentModeId(output->preferredModeId());\n output->setPos(QPoint(globalWidth, 0));\n output->setPrimary(false);\n\n if (output->isHorizontal()) {\n globalWidth += output->currentMode()->size().width();\n } else {\n globalWidth += output->currentMode()->size().height();\n }\n }\n\n if (isDocked()) {\n kDebug() << \"Docked\";\n embedded->setPrimary(false);\n biggest->setPrimary(true);\n }\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n Q_ASSERT(!outputs.isEmpty());\n\n kDebug() << \"Extending to the right\";\n KScreen::Output* biggest = biggestOutput(outputs);\n Q_ASSERT(biggest);\n\n outputs.remove(biggest->id());\n\n biggest->setEnabled(true);\n biggest->setPrimary(true);\n biggest->setCurrentModeId(biggest->preferredModeId());\n biggest->setPos(QPoint(0,0));\n\n int globalWidth;\n if (biggest->isHorizontal()) {\n globalWidth = biggest->currentMode()->size().width();\n } else {\n globalWidth = biggest->currentMode()->size().height();\n }\n\n Q_FOREACH(KScreen::Output* output, outputs) {\n output->setEnabled(true);\n output->setPrimary(false);\n output->setCurrentModeId(output->preferredModeId());\n output->setPos(QPoint(globalWidth, 0));\n\n if (output->isHorizontal()) {\n globalWidth += output->currentMode()->size().width();\n } else {\n globalWidth += output->currentMode()->size().height();\n }\n }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n int area, total = 0;\n KScreen::Mode* biggest = 0;\n Q_FOREACH(KScreen::Mode* mode, modes) {\n area = mode->size().width() * mode->size().height();\n if (area < total) {\n continue;\n }\n if (area == total && mode->refreshRate() < biggest->refreshRate()) {\n continue;\n }\n if (area == total && mode->refreshRate() > biggest->refreshRate()) {\n biggest = mode;\n continue;\n }\n\n total = area;\n biggest = mode;\n }\n\n return biggest;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n int area, total = 0;\n KScreen::Output* biggest = 0;\n Q_FOREACH(KScreen::Output* output, outputs) {\n KScreen::Mode* mode = output->preferredMode();\n area = mode->size().width() * mode->size().height();\n if (area < total) {\n continue;\n }\n\n total = area;\n biggest = output;\n }\n\n return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n KDebug::Block disableBlock(\"Disabling disconnected screens\");\n Q_FOREACH(KScreen::Output* output, outputs) {\n if (!output->isConnected()) {\n kDebug() << output->name() << \" Disabled\";\n output->setEnabled(false);\n output->setPrimary(false);\n }\n }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n Q_FOREACH(KScreen::Output* output, outputs) {\n if (!isEmbedded(output->name())) {\n continue;\n }\n\n return output;\n }\n\n return 0;\n}\n\nbool Generator::isLaptop()\n{\n if (m_forceLaptop) {\n return true;\n }\n\n return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n if (m_forceLidClosed) {\n return true;\n }\n\n return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n if (m_forceDocked) {\n return true;\n }\n\n return Device::self()->isDocked();\n}\n\nbool Generator::isEmbedded(const QString &name)\n{\n QStringList embedded;\n embedded << \"LVDS\";\n embedded << \"IDP\";\n embedded << \"EDP\";\n\n Q_FOREACH(const QString &pre, embedded) {\n if (name.toUpper().startsWith(pre)) {\n return true;\n }\n }\n\n return false;\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n m_forceDocked = force;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2015 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ IndexDataManagerPerfTest:\n\/\/ Performance test for index buffer management.\n\/\/\n\n#include \"ANGLEPerfTest.h\"\n\n#include <gmock\/gmock.h>\n\n#include \"libANGLE\/renderer\/d3d\/BufferD3D.h\"\n#include \"libANGLE\/renderer\/d3d\/IndexBuffer.h\"\n#include \"libANGLE\/renderer\/d3d\/IndexDataManager.h\"\n\nusing namespace testing;\n\nnamespace\n{\n\nclass MockIndexBuffer : public rx::IndexBuffer\n{\n public:\n MockIndexBuffer(unsigned int bufferSize, GLenum indexType)\n : mBufferSize(bufferSize),\n mIndexType(indexType)\n {\n }\n\n MOCK_METHOD3(initialize, gl::Error(unsigned int, GLenum, bool));\n MOCK_METHOD3(mapBuffer, gl::Error(unsigned int, unsigned int, void**));\n MOCK_METHOD0(unmapBuffer, gl::Error());\n MOCK_METHOD0(discard, gl::Error());\n MOCK_METHOD2(setSize, gl::Error(unsigned int, GLenum));\n\n \/\/ inlined for speed\n GLenum getIndexType() const override { return mIndexType; }\n unsigned int getBufferSize() const override { return mBufferSize; }\n\n private:\n unsigned int mBufferSize;\n GLenum mIndexType;\n};\n\nclass MockBufferFactoryD3D : public rx::BufferFactoryD3D\n{\n public:\n MockBufferFactoryD3D(unsigned int bufferSize, GLenum indexType)\n : mBufferSize(bufferSize),\n mIndexType(indexType)\n {\n }\n\n MOCK_METHOD0(createVertexBuffer, rx::VertexBuffer*());\n MOCK_CONST_METHOD1(getVertexConversionType, rx::VertexConversionType(const gl::VertexFormat &));\n MOCK_CONST_METHOD1(getVertexComponentType, GLenum(const gl::VertexFormat &));\n\n \/\/ Dependency injection\n rx::IndexBuffer* createIndexBuffer() override\n {\n return new MockIndexBuffer(mBufferSize, mIndexType);\n }\n\n private:\n unsigned int mBufferSize;\n GLenum mIndexType;\n};\n\nclass MockBufferD3D : public rx::BufferD3D\n{\n public:\n MockBufferD3D(rx::BufferFactoryD3D *factory, size_t bufferSize)\n : BufferD3D(factory),\n mBufferSize(bufferSize)\n {\n }\n\n \/\/ BufferImpl\n MOCK_METHOD3(setData, gl::Error(const void*, size_t, GLenum));\n MOCK_METHOD3(setSubData, gl::Error(const void*, size_t, size_t));\n MOCK_METHOD4(copySubData, gl::Error(BufferImpl*, GLintptr, GLintptr, GLsizeiptr));\n MOCK_METHOD2(map, gl::Error(GLenum, GLvoid **));\n MOCK_METHOD4(mapRange, gl::Error(size_t, size_t, GLbitfield, GLvoid **));\n MOCK_METHOD1(unmap, gl::Error(GLboolean *));\n\n \/\/ BufferD3D\n MOCK_METHOD0(markTransformFeedbackUsage, void());\n\n \/\/ inlined for speed\n bool supportsDirectBinding() const override { return false; }\n size_t getSize() const override { return mBufferSize; }\n gl::Error getData(const uint8_t **) override { return gl::Error(GL_NO_ERROR); }\n\n private:\n size_t mBufferSize;\n};\n\nclass IndexDataManagerPerfTest : public ANGLEPerfTest\n{\n public:\n IndexDataManagerPerfTest();\n\n void step(float dt, double totalTime) override;\n\n rx::IndexDataManager mIndexDataManager;\n GLsizei mIndexCount;\n unsigned int mBufferSize;\n MockBufferFactoryD3D mMockFactory;\n gl::Buffer mIndexBuffer;\n std::vector<GLshort> mIndexData;\n};\n\nMockBufferD3D *InitMockBufferD3D(MockBufferFactoryD3D *mockFactory, unsigned int bufferSize)\n{\n MockBufferD3D *mockBufferD3D = new MockBufferD3D(mockFactory, static_cast<size_t>(bufferSize));\n\n EXPECT_CALL(*mockFactory, createVertexBuffer()).WillOnce(Return(nullptr)).RetiresOnSaturation();\n mockBufferD3D->initializeStaticData();\n\n return mockBufferD3D;\n}\n\nIndexDataManagerPerfTest::IndexDataManagerPerfTest()\n : ANGLEPerfTest(\"IndexDataManger\", \"_run\"),\n mIndexDataManager(&mMockFactory, rx::RENDERER_D3D11),\n mIndexCount(4000),\n mBufferSize(mIndexCount * 2),\n mMockFactory(mBufferSize, GL_UNSIGNED_SHORT),\n mIndexBuffer(InitMockBufferD3D(&mMockFactory, mBufferSize), 1),\n mIndexData(mIndexCount)\n{\n for (GLsizei index = 0; index < mIndexCount; ++index)\n {\n mIndexData[index] = static_cast<GLshort>(index);\n }\n}\n\nvoid IndexDataManagerPerfTest::step(float dt, double totalTime)\n{\n rx::TranslatedIndexData translatedIndexData;\n\n for (unsigned int iteration = 0; iteration < 100; ++iteration)\n {\n mIndexBuffer.getIndexRange(GL_UNSIGNED_SHORT, 0, mIndexCount, &translatedIndexData.indexRange);\n mIndexDataManager.prepareIndexData(GL_UNSIGNED_SHORT, mIndexCount, &mIndexBuffer, nullptr, &translatedIndexData);\n }\n\n if (mTimer->getElapsedTime() >= 5.0)\n {\n mRunning = false;\n }\n}\n\nTEST_F(IndexDataManagerPerfTest, Run)\n{\n run();\n}\n\n}\n<commit_msg>Fix crash in IndexDataManagerPerfTest.<commit_after>\/\/\n\/\/ Copyright 2015 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ IndexDataManagerPerfTest:\n\/\/ Performance test for index buffer management.\n\/\/\n\n#include \"ANGLEPerfTest.h\"\n\n#include <gmock\/gmock.h>\n\n#include \"libANGLE\/renderer\/d3d\/BufferD3D.h\"\n#include \"libANGLE\/renderer\/d3d\/IndexBuffer.h\"\n#include \"libANGLE\/renderer\/d3d\/IndexDataManager.h\"\n\nusing namespace testing;\n\nnamespace\n{\n\nclass MockIndexBuffer : public rx::IndexBuffer\n{\n public:\n MockIndexBuffer(unsigned int bufferSize, GLenum indexType)\n : mBufferSize(bufferSize),\n mIndexType(indexType)\n {\n }\n\n MOCK_METHOD3(initialize, gl::Error(unsigned int, GLenum, bool));\n MOCK_METHOD3(mapBuffer, gl::Error(unsigned int, unsigned int, void**));\n MOCK_METHOD0(unmapBuffer, gl::Error());\n MOCK_METHOD0(discard, gl::Error());\n MOCK_METHOD2(setSize, gl::Error(unsigned int, GLenum));\n\n \/\/ inlined for speed\n GLenum getIndexType() const override { return mIndexType; }\n unsigned int getBufferSize() const override { return mBufferSize; }\n\n private:\n unsigned int mBufferSize;\n GLenum mIndexType;\n};\n\nclass MockBufferFactoryD3D : public rx::BufferFactoryD3D\n{\n public:\n MockBufferFactoryD3D(unsigned int bufferSize, GLenum indexType)\n : mBufferSize(bufferSize),\n mIndexType(indexType)\n {\n }\n\n MOCK_METHOD0(createVertexBuffer, rx::VertexBuffer*());\n MOCK_CONST_METHOD1(getVertexConversionType, rx::VertexConversionType(const gl::VertexFormat &));\n MOCK_CONST_METHOD1(getVertexComponentType, GLenum(const gl::VertexFormat &));\n\n \/\/ Dependency injection\n rx::IndexBuffer* createIndexBuffer() override\n {\n return new MockIndexBuffer(mBufferSize, mIndexType);\n }\n\n private:\n unsigned int mBufferSize;\n GLenum mIndexType;\n};\n\nclass MockBufferD3D : public rx::BufferD3D\n{\n public:\n MockBufferD3D(rx::BufferFactoryD3D *factory)\n : BufferD3D(factory),\n mData()\n {\n }\n\n \/\/ BufferImpl\n gl::Error setData(const void *data, size_t size, GLenum) override\n {\n mData.resize(size);\n if (data && size > 0)\n {\n memcpy(&mData[0], data, size);\n }\n return gl::Error(GL_NO_ERROR);\n }\n\n MOCK_METHOD3(setSubData, gl::Error(const void*, size_t, size_t));\n MOCK_METHOD4(copySubData, gl::Error(BufferImpl*, GLintptr, GLintptr, GLsizeiptr));\n MOCK_METHOD2(map, gl::Error(GLenum, GLvoid **));\n MOCK_METHOD4(mapRange, gl::Error(size_t, size_t, GLbitfield, GLvoid **));\n MOCK_METHOD1(unmap, gl::Error(GLboolean *));\n\n \/\/ BufferD3D\n MOCK_METHOD0(markTransformFeedbackUsage, void());\n\n \/\/ inlined for speed\n bool supportsDirectBinding() const override { return false; }\n size_t getSize() const override { return mData.size(); }\n\n gl::Error getData(const uint8_t **outData) override\n {\n *outData = &mData[0];\n return gl::Error(GL_NO_ERROR);\n }\n\n private:\n std::vector<uint8_t> mData;\n};\n\nclass IndexDataManagerPerfTest : public ANGLEPerfTest\n{\n public:\n IndexDataManagerPerfTest();\n\n void step(float dt, double totalTime) override;\n\n rx::IndexDataManager mIndexDataManager;\n GLsizei mIndexCount;\n unsigned int mBufferSize;\n MockBufferFactoryD3D mMockFactory;\n gl::Buffer mIndexBuffer;\n};\n\nMockBufferD3D *InitMockBufferD3D(MockBufferFactoryD3D *mockFactory)\n{\n MockBufferD3D *mockBufferD3D = new MockBufferD3D(mockFactory);\n\n EXPECT_CALL(*mockFactory, createVertexBuffer()).WillOnce(Return(nullptr)).RetiresOnSaturation();\n mockBufferD3D->initializeStaticData();\n\n return mockBufferD3D;\n}\n\nIndexDataManagerPerfTest::IndexDataManagerPerfTest()\n : ANGLEPerfTest(\"IndexDataManger\", \"_run\"),\n mIndexDataManager(&mMockFactory, rx::RENDERER_D3D11),\n mIndexCount(4000),\n mBufferSize(mIndexCount * sizeof(GLushort)),\n mMockFactory(mBufferSize, GL_UNSIGNED_SHORT),\n mIndexBuffer(InitMockBufferD3D(&mMockFactory), 1)\n{\n std::vector<GLushort> indexData(mIndexCount);\n for (GLsizei index = 0; index < mIndexCount; ++index)\n {\n indexData[index] = static_cast<GLushort>(index);\n }\n mIndexBuffer.bufferData(&indexData[0], indexData.size() * sizeof(GLushort), GL_STATIC_DRAW);\n}\n\nvoid IndexDataManagerPerfTest::step(float dt, double totalTime)\n{\n rx::TranslatedIndexData translatedIndexData;\n for (unsigned int iteration = 0; iteration < 100; ++iteration)\n {\n mIndexBuffer.getIndexRange(GL_UNSIGNED_SHORT, 0, mIndexCount, &translatedIndexData.indexRange);\n mIndexDataManager.prepareIndexData(GL_UNSIGNED_SHORT, mIndexCount, &mIndexBuffer, nullptr, &translatedIndexData);\n }\n\n if (mTimer->getElapsedTime() >= 5.0)\n {\n mRunning = false;\n }\n}\n\nTEST_F(IndexDataManagerPerfTest, Run)\n{\n run();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $\n\n#include <mapnik\/wkb.hpp>\n\n#include <mapnik\/geom_util.hpp>\n#include <mapnik\/feature.hpp>\n\nnamespace mapnik\n{\n struct wkb_reader\n {\n private:\n enum wkbByteOrder {\n wkbXDR=0,\n wkbNDR=1\n };\n const char* wkb_;\n unsigned size_;\n unsigned pos_;\n wkbByteOrder byteOrder_;\n bool needSwap_;\n public:\n\t\n enum wkbGeometryType {\n wkbPoint=1,\n wkbLineString=2,\n wkbPolygon=3,\n wkbMultiPoint=4,\n wkbMultiLineString=5,\n wkbMultiPolygon=6,\n wkbGeometryCollection=7\n };\n\t\n wkb_reader(const char* wkb,unsigned size)\n : wkb_(wkb),\n size_(size),\n pos_(0),\n byteOrder_((wkbByteOrder)wkb_[0])\n {\n ++pos_;\n\t \n#ifndef WORDS_BIGENDIAN\n needSwap_=byteOrder_?wkbXDR:wkbNDR;\n#else\n needSwap_=byteOrder_?wkbNDR:wkbXDR;\t\n#endif\t \n }\n\n ~wkb_reader() {}\n\n void read_multi(Feature & feature) \n {\n int type=read_integer();\n switch (type)\n {\n case wkbPoint:\n read_point(feature);\n break;\n case wkbLineString:\n read_linestring(feature);\n break;\n case wkbPolygon:\n read_polygon(feature);\n break;\n case wkbMultiPoint:\n read_multipoint(feature);\n break;\n case wkbMultiLineString:\n read_multilinestring(feature);\n break;\n case wkbMultiPolygon:\n read_multipolygon(feature);\n break;\n case wkbGeometryCollection:\n break;\n default:\n break;\n }\n }\n \n void read(Feature & feature) \n {\n int type=read_integer();\n switch (type)\n {\n case wkbPoint:\n read_point(feature);\n break;\n case wkbLineString:\n read_linestring(feature);\n break;\n case wkbPolygon:\n read_polygon(feature);\n break;\n case wkbMultiPoint:\n read_multipoint_2(feature);\n break;\n case wkbMultiLineString:\n read_multilinestring_2(feature);\n break;\n case wkbMultiPolygon:\n read_multipolygon_2(feature);\n break;\n case wkbGeometryCollection:\n break;\n default:\n break;\n }\n }\n \n private:\n wkb_reader(const wkb_reader&);\n wkb_reader& operator=(const wkb_reader&);\n\t\n int read_integer() \n {\n int n;\n\n if (!needSwap_)\n {\n memcpy(&n,wkb_+pos_,4);\n } \n else \n {\n const char* b=wkb_+pos_;\n n = (b[3]&0xff) | ((b[2]&0xff)<<8) | ((b[1]&0xff)<<16) | ((b[0]&0xff)<<24);\n }\n pos_+=4;\n\n return n;\n }\n\t\n double read_double()\n {\n double d;\n\n if (!needSwap_)\n {\n memcpy(&d,wkb_+pos_,8);\n }\n else \n {\n \/\/ we rely on the fact that \"long long\" is in C standard,\n \/\/ but not in C++ yet\n \/\/ this is not quite portable\n const char* b= wkb_+pos_;\n long long n = ((long long)b[7]&0xff) | \n (((long long)b[6]&0xff)<<8) | \n (((long long)b[5]&0xff)<<16) | \n (((long long)b[4]&0xff)<<24) |\n (((long long)b[3]&0xff)<<32) |\n (((long long)b[2]&0xff)<<40) |\n (((long long)b[1]&0xff)<<48) |\n (((long long)b[0]&0xff)<<56);\n memcpy(&d,&n,8);\n }\n pos_+=8;\n\n return d;\n }\n\t\n void read_coords(CoordinateArray& ar)\n {\n int size=sizeof(coord<double,2>)*ar.size();\n if (!needSwap_)\n {\n std::memcpy(&ar[0],wkb_+pos_,size);\n\t\t\n }\n else \n {\n for (unsigned i=0;i<ar.size();++i)\n {\n ar[i].x=read_double();\n ar[i].y=read_double();\n }\n }\n pos_+=size;\n }\n\t\n void read_point(Feature & feature)\n {\n geometry2d * pt = new point<vertex2d>;\n double x = read_double();\n double y = read_double();\n pt->move_to(x,y);\n feature.add_geometry(pt);\n }\n \n void read_multipoint(Feature & feature)\n {\n int num_points = read_integer();\n for (int i=0;i<num_points;++i) \n {\n pos_+=5;\n read_point(feature);\n }\n }\n \n void read_multipoint_2(Feature & feature)\n {\n geometry2d * pt = new point<vertex2d>;\n int num_points = read_integer(); \n for (int i=0;i<num_points;++i) \n {\n pos_+=5;\n double x = read_double();\n double y = read_double();\n pt->move_to(x,y);\n }\n feature.add_geometry(pt);\n }\n \n void read_linestring(Feature & feature)\n {\n geometry2d * line = new line_string<vertex2d>;\n int num_points=read_integer();\n CoordinateArray ar(num_points);\n read_coords(ar);\n line->set_capacity(num_points);\n line->move_to(ar[0].x,ar[0].y);\n for (int i=1;i<num_points;++i)\n {\n line->line_to(ar[i].x,ar[i].y);\n }\n feature.add_geometry(line);\n }\n \n void read_multilinestring(Feature & feature)\n {\n int num_lines=read_integer();\n for (int i=0;i<num_lines;++i)\n {\n pos_+=5;\n read_linestring(feature);\n }\n }\n\n void read_multilinestring_2(Feature & feature)\n {\n geometry2d * line = new line_string<vertex2d>;\n int num_lines=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_lines;++i)\n {\n pos_+=5;\n int num_points=read_integer();\n capacity+=num_points;\n CoordinateArray ar(num_points); \n read_coords(ar);\n line->set_capacity(capacity);\n line->move_to(ar[0].x,ar[0].y); \n for (int i=1;i<num_points;++i) \n { \n line->line_to(ar[i].x,ar[i].y); \n } \n }\n feature.add_geometry(line);\n }\n \n void read_polygon(Feature & feature) \n {\n geometry2d * poly = new polygon<vertex2d>;\n int num_rings=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_rings;++i)\n {\n int num_points=read_integer();\n capacity+=num_points;\n CoordinateArray ar(num_points);\n read_coords(ar);\n poly->set_capacity(capacity);\n poly->move_to(ar[0].x,ar[0].y);\n for (int j=1;j<num_points;++j)\n {\n poly->line_to(ar[j].x,ar[j].y);\n }\n poly->line_to(ar[0].x,ar[0].y);\n }\n feature.add_geometry(poly);\n }\n\t\n void read_multipolygon(Feature & feature)\n {\n int num_polys=read_integer();\n for (int i=0;i<num_polys;++i)\n {\n pos_+=5;\n read_polygon(feature);\n }\n }\n\n void read_multipolygon_2(Feature & feature)\n {\n geometry2d * poly = new polygon<vertex2d>;\n int num_polys=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_polys;++i)\n {\n pos_+=5;\n int num_rings=read_integer();\n for (int i=0;i<num_rings;++i)\n {\n int num_points=read_integer();\n capacity += num_points;\n CoordinateArray ar(num_points);\n read_coords(ar);\n poly->set_capacity(capacity);\n poly->move_to(ar[0].x,ar[0].y);\n \n for (int j=1;j<num_points;++j)\n {\n poly->line_to(ar[j].x,ar[j].y);\n }\n poly->line_to(ar[0].x,ar[0].y);\n }\n }\n feature.add_geometry(poly);\n }\n };\n \n void geometry_utils::from_wkb(Feature & feature,const char* wkb, unsigned size, bool multiple_geometries) \n {\n wkb_reader reader(wkb,size);\n if (multiple_geometries)\n return reader.read_multi(feature);\n else\n return reader.read(feature);\n } \n}\n<commit_msg>The final line_to is not required in the WKB reader since the last and first points of the polygon geometry will be the same<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $\n\n#include <mapnik\/wkb.hpp>\n\n#include <mapnik\/geom_util.hpp>\n#include <mapnik\/feature.hpp>\n\nnamespace mapnik\n{\n struct wkb_reader\n {\n private:\n enum wkbByteOrder {\n wkbXDR=0,\n wkbNDR=1\n };\n const char* wkb_;\n unsigned size_;\n unsigned pos_;\n wkbByteOrder byteOrder_;\n bool needSwap_;\n public:\n\t\n enum wkbGeometryType {\n wkbPoint=1,\n wkbLineString=2,\n wkbPolygon=3,\n wkbMultiPoint=4,\n wkbMultiLineString=5,\n wkbMultiPolygon=6,\n wkbGeometryCollection=7\n };\n\t\n wkb_reader(const char* wkb,unsigned size)\n : wkb_(wkb),\n size_(size),\n pos_(0),\n byteOrder_((wkbByteOrder)wkb_[0])\n {\n ++pos_;\n\t \n#ifndef WORDS_BIGENDIAN\n needSwap_=byteOrder_?wkbXDR:wkbNDR;\n#else\n needSwap_=byteOrder_?wkbNDR:wkbXDR;\t\n#endif\t \n }\n\n ~wkb_reader() {}\n\n void read_multi(Feature & feature) \n {\n int type=read_integer();\n switch (type)\n {\n case wkbPoint:\n read_point(feature);\n break;\n case wkbLineString:\n read_linestring(feature);\n break;\n case wkbPolygon:\n read_polygon(feature);\n break;\n case wkbMultiPoint:\n read_multipoint(feature);\n break;\n case wkbMultiLineString:\n read_multilinestring(feature);\n break;\n case wkbMultiPolygon:\n read_multipolygon(feature);\n break;\n case wkbGeometryCollection:\n break;\n default:\n break;\n }\n }\n \n void read(Feature & feature) \n {\n int type=read_integer();\n switch (type)\n {\n case wkbPoint:\n read_point(feature);\n break;\n case wkbLineString:\n read_linestring(feature);\n break;\n case wkbPolygon:\n read_polygon(feature);\n break;\n case wkbMultiPoint:\n read_multipoint_2(feature);\n break;\n case wkbMultiLineString:\n read_multilinestring_2(feature);\n break;\n case wkbMultiPolygon:\n read_multipolygon_2(feature);\n break;\n case wkbGeometryCollection:\n break;\n default:\n break;\n }\n }\n \n private:\n wkb_reader(const wkb_reader&);\n wkb_reader& operator=(const wkb_reader&);\n\t\n int read_integer() \n {\n int n;\n\n if (!needSwap_)\n {\n memcpy(&n,wkb_+pos_,4);\n } \n else \n {\n const char* b=wkb_+pos_;\n n = (b[3]&0xff) | ((b[2]&0xff)<<8) | ((b[1]&0xff)<<16) | ((b[0]&0xff)<<24);\n }\n pos_+=4;\n\n return n;\n }\n\t\n double read_double()\n {\n double d;\n\n if (!needSwap_)\n {\n memcpy(&d,wkb_+pos_,8);\n }\n else \n {\n \/\/ we rely on the fact that \"long long\" is in C standard,\n \/\/ but not in C++ yet\n \/\/ this is not quite portable\n const char* b= wkb_+pos_;\n long long n = ((long long)b[7]&0xff) | \n (((long long)b[6]&0xff)<<8) | \n (((long long)b[5]&0xff)<<16) | \n (((long long)b[4]&0xff)<<24) |\n (((long long)b[3]&0xff)<<32) |\n (((long long)b[2]&0xff)<<40) |\n (((long long)b[1]&0xff)<<48) |\n (((long long)b[0]&0xff)<<56);\n memcpy(&d,&n,8);\n }\n pos_+=8;\n\n return d;\n }\n\t\n void read_coords(CoordinateArray& ar)\n {\n int size=sizeof(coord<double,2>)*ar.size();\n if (!needSwap_)\n {\n std::memcpy(&ar[0],wkb_+pos_,size);\n\t\t\n }\n else \n {\n for (unsigned i=0;i<ar.size();++i)\n {\n ar[i].x=read_double();\n ar[i].y=read_double();\n }\n }\n pos_+=size;\n }\n\t\n void read_point(Feature & feature)\n {\n geometry2d * pt = new point<vertex2d>;\n double x = read_double();\n double y = read_double();\n pt->move_to(x,y);\n feature.add_geometry(pt);\n }\n \n void read_multipoint(Feature & feature)\n {\n int num_points = read_integer();\n for (int i=0;i<num_points;++i) \n {\n pos_+=5;\n read_point(feature);\n }\n }\n \n void read_multipoint_2(Feature & feature)\n {\n geometry2d * pt = new point<vertex2d>;\n int num_points = read_integer(); \n for (int i=0;i<num_points;++i) \n {\n pos_+=5;\n double x = read_double();\n double y = read_double();\n pt->move_to(x,y);\n }\n feature.add_geometry(pt);\n }\n \n void read_linestring(Feature & feature)\n {\n geometry2d * line = new line_string<vertex2d>;\n int num_points=read_integer();\n CoordinateArray ar(num_points);\n read_coords(ar);\n line->set_capacity(num_points);\n line->move_to(ar[0].x,ar[0].y);\n for (int i=1;i<num_points;++i)\n {\n line->line_to(ar[i].x,ar[i].y);\n }\n feature.add_geometry(line);\n }\n \n void read_multilinestring(Feature & feature)\n {\n int num_lines=read_integer();\n for (int i=0;i<num_lines;++i)\n {\n pos_+=5;\n read_linestring(feature);\n }\n }\n\n void read_multilinestring_2(Feature & feature)\n {\n geometry2d * line = new line_string<vertex2d>;\n int num_lines=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_lines;++i)\n {\n pos_+=5;\n int num_points=read_integer();\n capacity+=num_points;\n CoordinateArray ar(num_points); \n read_coords(ar);\n line->set_capacity(capacity);\n line->move_to(ar[0].x,ar[0].y); \n for (int i=1;i<num_points;++i) \n { \n line->line_to(ar[i].x,ar[i].y); \n } \n }\n feature.add_geometry(line);\n }\n \n void read_polygon(Feature & feature) \n {\n geometry2d * poly = new polygon<vertex2d>;\n int num_rings=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_rings;++i)\n {\n int num_points=read_integer();\n capacity+=num_points;\n CoordinateArray ar(num_points);\n read_coords(ar);\n poly->set_capacity(capacity);\n poly->move_to(ar[0].x,ar[0].y);\n for (int j=1;j<num_points;++j)\n {\n poly->line_to(ar[j].x,ar[j].y);\n }\n }\n feature.add_geometry(poly);\n }\n\t\n void read_multipolygon(Feature & feature)\n {\n int num_polys=read_integer();\n for (int i=0;i<num_polys;++i)\n {\n pos_+=5;\n read_polygon(feature);\n }\n }\n\n void read_multipolygon_2(Feature & feature)\n {\n geometry2d * poly = new polygon<vertex2d>;\n int num_polys=read_integer();\n unsigned capacity = 0;\n for (int i=0;i<num_polys;++i)\n {\n pos_+=5;\n int num_rings=read_integer();\n for (int i=0;i<num_rings;++i)\n {\n int num_points=read_integer();\n capacity += num_points;\n CoordinateArray ar(num_points);\n read_coords(ar);\n poly->set_capacity(capacity);\n poly->move_to(ar[0].x,ar[0].y);\n \n for (int j=1;j<num_points;++j)\n {\n poly->line_to(ar[j].x,ar[j].y);\n }\n poly->line_to(ar[0].x,ar[0].y);\n }\n }\n feature.add_geometry(poly);\n }\n };\n \n void geometry_utils::from_wkb(Feature & feature,const char* wkb, unsigned size, bool multiple_geometries) \n {\n wkb_reader reader(wkb,size);\n if (multiple_geometries)\n return reader.read_multi(feature);\n else\n return reader.read(feature);\n } \n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * Copyright 2018 MINRES Technologies GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *******************************************************************************\/\n\n#include <scc\/perf_estimator.h>\n#include <scc\/report.h>\n\n#if defined(_WIN32)\n#include <Windows.h>\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__MACH__) && defined(__APPLE__))\n#include <ctime>\n#include <sys\/resource.h>\n#include <sys\/times.h>\n#include <unistd.h>\n#else\n#error \"Cannot compile file because of an unknown method to retrieve OS time.\"\n#endif\n\nnamespace scc {\nusing namespace sc_core;\n\nSC_HAS_PROCESS(perf_estimator);\n\nperf_estimator::perf_estimator(const sc_module_name& nm, sc_time beat_delay_)\n: sc_module(nm)\n, beat_delay(beat_delay_) {\n soc.set();\n if(beat_delay.value()) {\n SC_METHOD(beat);\n }\n}\n\nperf_estimator::~perf_estimator() {\n time_stamp eod;\n eod.set();\n SCCINFO(SCMOD) << \"constr & elab time: \" << (eoe.proc_clock_stamp - soc.proc_clock_stamp) << \"s\";\n SCCINFO(SCMOD) << \"simulation time: \" << (eos.proc_clock_stamp - sos.proc_clock_stamp) << \"s\";\n}\n\nvoid perf_estimator::end_of_elaboration() { eoe.set(); }\n\nvoid perf_estimator::start_of_simulation() { sos.set(); }\n\nvoid perf_estimator::end_of_simulation() {\n eos.set();\n sc_time now = sc_time_stamp();\n unsigned long long elapsed_wall = (eos.wall_clock_stamp - sos.wall_clock_stamp).total_microseconds();\n auto elapsed_proc = (unsigned long long)((eos.proc_clock_stamp - sos.proc_clock_stamp) * 1000000);\n auto elapsed_sim = (unsigned long long)(now.to_seconds() * 1000000.);\n if(elapsed_sim > 0) {\n double wall_perf = elapsed_wall \/ elapsed_sim;\n double proc_perf = elapsed_proc \/ elapsed_sim;\n SCCINFO(SCMOD) << \"Wall clock (process clock) based simulation real time factor is \" << wall_perf << \"(\"\n << proc_perf << \")\";\n }\n}\n\nvoid perf_estimator::beat() {\n SCCINFO(SCMOD) << \"Heart beat\";\n next_trigger(beat_delay);\n}\n} \/* namespace scc *\/\n\ndouble scc::perf_estimator::time_stamp::get_cpu_time() {\n#if defined(_WIN32)\n FILETIME create_time;\n FILETIME exit_time;\n FILETIME kernel_time;\n FILETIME user_time;\n if(GetProcessTimes(GetCurrentProcess(), &create_tiem, &exit_time, &kernel_time, &user_time) != -1) {\n SYSTEMTIME system_time;\n if(FileTimeToSystemTime(&user_time, system_time) != -1)\n return (double)system_time.wHour * 3600.0 + (double)system_time.wMinute * 60.0 +\n (double)system_time.wSecond + (double)system_time.wMilliseconds \/ 1000.;\n }\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__MACH__) && defined(__APPLE__))\n#if _POSIX_TIMERS > 0\n {\n clockid_t id;\n struct timespec stamp;\n#if _POSIX_CPUTIME > 0\n if(clock_getcpuclockid(0, &id) == -1)\n#endif\n#if defined(CLOCK_PROCESS_CPUTIME_ID)\n id = CLOCK_PROCESS_CPUTIME_ID;\n#elif defined(CLOCK_VIRTUAL)\n id = CLOCK_VIRTUAL;\n#else\n id = (clockid_t)-1;\n#endif\n if(id != (clockid_t)-1 && clock_gettime(id, &stamp) != -1)\n return (double)stamp.tv_sec + (double)stamp.tv_nsec \/ 1000000000.0;\n }\n#endif\n#if defined(RUSAGE_SELF)\n {\n struct rusage usage;\n if(getrusage(RUSAGE_SELF, &usage) != -1)\n return (double)usage.ru_utime.tv_sec + (double)usage.ru_utime.tv_usec \/ 1000000.0;\n }\n#endif\n#if defined(_SC_CLK_TICK)\n {\n const double ticks = (double)sysconf(_SC_CLK_TCK);\n struct tms s;\n if(times(&s) != (clock_t)-1)\n return (double)s.tms_utime \/ ticks;\n }\n#endif\n#if defined(CLOCKS_PER_SEC)\n {\n clock_t c = clock();\n if(c != (clock_t)-1)\n return (double)c \/ (double)CLOCKS_PER_SEC;\n }\n#endif\n#endif\n return 1.0;\n}\n<commit_msg>Fixed heart beat to skip first beat at 0ns<commit_after>\/*******************************************************************************\n * Copyright 2018 MINRES Technologies GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *******************************************************************************\/\n\n#include <scc\/perf_estimator.h>\n#include <scc\/report.h>\n\n#if defined(_WIN32)\n#include <Windows.h>\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__MACH__) && defined(__APPLE__))\n#include <ctime>\n#include <sys\/resource.h>\n#include <sys\/times.h>\n#include <unistd.h>\n#else\n#error \"Cannot compile file because of an unknown method to retrieve OS time.\"\n#endif\n\nnamespace scc {\nusing namespace sc_core;\n\nSC_HAS_PROCESS(perf_estimator);\n\nperf_estimator::perf_estimator(const sc_module_name& nm, sc_time beat_delay_)\n: sc_module(nm)\n, beat_delay(beat_delay_) {\n soc.set();\n if(beat_delay.value()) {\n SC_METHOD(beat);\n }\n}\n\nperf_estimator::~perf_estimator() {\n time_stamp eod;\n eod.set();\n SCCINFO(SCMOD) << \"constr & elab time: \" << (eoe.proc_clock_stamp - soc.proc_clock_stamp) << \"s\";\n SCCINFO(SCMOD) << \"simulation time: \" << (eos.proc_clock_stamp - sos.proc_clock_stamp) << \"s\";\n}\n\nvoid perf_estimator::end_of_elaboration() { eoe.set(); }\n\nvoid perf_estimator::start_of_simulation() { sos.set(); }\n\nvoid perf_estimator::end_of_simulation() {\n eos.set();\n sc_time now = sc_time_stamp();\n unsigned long long elapsed_wall = (eos.wall_clock_stamp - sos.wall_clock_stamp).total_microseconds();\n auto elapsed_proc = (unsigned long long)((eos.proc_clock_stamp - sos.proc_clock_stamp) * 1000000);\n auto elapsed_sim = (unsigned long long)(now.to_seconds() * 1000000.);\n if(elapsed_sim > 0) {\n double wall_perf = elapsed_wall \/ elapsed_sim;\n double proc_perf = elapsed_proc \/ elapsed_sim;\n SCCINFO(SCMOD) << \"Wall clock (process clock) based simulation real time factor is \" << wall_perf << \"(\"\n << proc_perf << \")\";\n }\n}\n\nvoid perf_estimator::beat() {\n if(sc_time_stamp().value())\n SCCINFO(SCMOD) << \"Heart beat\";\n next_trigger(beat_delay);\n}\n} \/* namespace scc *\/\n\ndouble scc::perf_estimator::time_stamp::get_cpu_time() {\n#if defined(_WIN32)\n FILETIME create_time;\n FILETIME exit_time;\n FILETIME kernel_time;\n FILETIME user_time;\n if(GetProcessTimes(GetCurrentProcess(), &create_tiem, &exit_time, &kernel_time, &user_time) != -1) {\n SYSTEMTIME system_time;\n if(FileTimeToSystemTime(&user_time, system_time) != -1)\n return (double)system_time.wHour * 3600.0 + (double)system_time.wMinute * 60.0 +\n (double)system_time.wSecond + (double)system_time.wMilliseconds \/ 1000.;\n }\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__MACH__) && defined(__APPLE__))\n#if _POSIX_TIMERS > 0\n {\n clockid_t id;\n struct timespec stamp;\n#if _POSIX_CPUTIME > 0\n if(clock_getcpuclockid(0, &id) == -1)\n#endif\n#if defined(CLOCK_PROCESS_CPUTIME_ID)\n id = CLOCK_PROCESS_CPUTIME_ID;\n#elif defined(CLOCK_VIRTUAL)\n id = CLOCK_VIRTUAL;\n#else\n id = (clockid_t)-1;\n#endif\n if(id != (clockid_t)-1 && clock_gettime(id, &stamp) != -1)\n return (double)stamp.tv_sec + (double)stamp.tv_nsec \/ 1000000000.0;\n }\n#endif\n#if defined(RUSAGE_SELF)\n {\n struct rusage usage;\n if(getrusage(RUSAGE_SELF, &usage) != -1)\n return (double)usage.ru_utime.tv_sec + (double)usage.ru_utime.tv_usec \/ 1000000.0;\n }\n#endif\n#if defined(_SC_CLK_TICK)\n {\n const double ticks = (double)sysconf(_SC_CLK_TCK);\n struct tms s;\n if(times(&s) != (clock_t)-1)\n return (double)s.tms_utime \/ ticks;\n }\n#endif\n#if defined(CLOCKS_PER_SEC)\n {\n clock_t c = clock();\n if(c != (clock_t)-1)\n return (double)c \/ (double)CLOCKS_PER_SEC;\n }\n#endif\n#endif\n return 1.0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n *\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2004-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n#include \"MarbleAboutDialog.h\"\n#include \"ui_MarbleAboutDialog.h\"\n\n#include <QtCore\/QFile>\n#include <QtGui\/QTextFrame>\n#include <QtCore\/QTextStream>\n#include <QtGui\/QPixmap>\n\n#include \"MarbleDirs.h\"\n\n\nclass MarbleAboutDialogPrivate\n{\npublic: \n Ui::MarbleAboutDialog uiWidget;\n\n bool authorsLoaded;\n bool dataLoaded;\n bool licenseLoaded;\n};\n\n\nMarbleAboutDialog::MarbleAboutDialog(QWidget *parent)\n : QDialog( parent ),\n d( new MarbleAboutDialogPrivate )\n{\n d->uiWidget.setupUi( this );\n\n d->authorsLoaded = false;\n d->dataLoaded = false;\n d->licenseLoaded = false;\n\n d->uiWidget.m_pMarbleLogoLabel->setPixmap( QPixmap( MarbleDirs::path(\"svg\/marble-logo-72dpi.png\") ) );\n\n connect( d->uiWidget.tabWidget, SIGNAL( currentChanged( int ) ), \n this, SLOT( loadPageContents( int ) ) );\n\n d->uiWidget.m_pMarbleAboutBrowser->setHtml( tr(\"<br \/>(c) 2007, The Marble Project<br \/><br \/><a href=\\\"http:\/\/edu.kde.org\/marble\\\">http:\/\/edu.kde.org\/marble<\/a>\") );\n\n}\n\nvoid MarbleAboutDialog::loadPageContents( int idx )\n{\n QTextBrowser* browser = 0;\n\n if ( idx == 1 && d->authorsLoaded == false )\n {\n d->authorsLoaded = true;\n browser = d->uiWidget.m_pMarbleAuthorsBrowser;\n QString filename = MarbleDirs::path( \"credits_authors.html\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setHtml( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n\n if ( idx == 2 && d->dataLoaded == false )\n {\n d->dataLoaded = true;\n browser = d->uiWidget.m_pMarbleDataBrowser;\n QString filename = MarbleDirs::path( \"credits_data.html\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setHtml( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n\n if ( idx == 3 && d->licenseLoaded == false )\n {\n d->licenseLoaded = true;\n browser = d->uiWidget.m_pMarbleLicenseBrowser;\n QString filename = MarbleDirs::path( \"LICENSE.txt\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setText( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n}\n\n#include \"MarbleAboutDialog.moc\"\n\n<commit_msg>- Adding missing border to first tab<commit_after>\/* This file is part of the KDE project\n *\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2004-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n\n#include \"MarbleAboutDialog.h\"\n#include \"ui_MarbleAboutDialog.h\"\n\n#include <QtCore\/QFile>\n#include <QtGui\/QTextFrame>\n#include <QtCore\/QTextStream>\n#include <QtGui\/QPixmap>\n\n#include \"MarbleDirs.h\"\n\n\nclass MarbleAboutDialogPrivate\n{\npublic: \n Ui::MarbleAboutDialog uiWidget;\n\n bool authorsLoaded;\n bool dataLoaded;\n bool licenseLoaded;\n};\n\n\nMarbleAboutDialog::MarbleAboutDialog(QWidget *parent)\n : QDialog( parent ),\n d( new MarbleAboutDialogPrivate )\n{\n d->uiWidget.setupUi( this );\n\n d->authorsLoaded = false;\n d->dataLoaded = false;\n d->licenseLoaded = false;\n\n d->uiWidget.m_pMarbleLogoLabel->setPixmap( QPixmap( MarbleDirs::path(\"svg\/marble-logo-72dpi.png\") ) );\n\n connect( d->uiWidget.tabWidget, SIGNAL( currentChanged( int ) ), \n this, SLOT( loadPageContents( int ) ) );\n\n QTextBrowser* browser = d->uiWidget.m_pMarbleAboutBrowser;\n browser->setHtml( tr(\"<br \/>(c) 2007, The Marble Project<br \/><br \/><a href=\\\"http:\/\/edu.kde.org\/marble\\\">http:\/\/edu.kde.org\/marble<\/a>\") );\n\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n\n}\n\nvoid MarbleAboutDialog::loadPageContents( int idx )\n{\n QTextBrowser* browser = 0;\n\n if ( idx == 1 && d->authorsLoaded == false )\n {\n d->authorsLoaded = true;\n browser = d->uiWidget.m_pMarbleAuthorsBrowser;\n QString filename = MarbleDirs::path( \"credits_authors.html\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setHtml( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n\n if ( idx == 2 && d->dataLoaded == false )\n {\n d->dataLoaded = true;\n browser = d->uiWidget.m_pMarbleDataBrowser;\n QString filename = MarbleDirs::path( \"credits_data.html\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setHtml( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n\n if ( idx == 3 && d->licenseLoaded == false )\n {\n d->licenseLoaded = true;\n browser = d->uiWidget.m_pMarbleLicenseBrowser;\n QString filename = MarbleDirs::path( \"LICENSE.txt\" );\n if( !filename.isEmpty() )\n {\n QFile f( filename );\n if( f.open( QIODevice::ReadOnly ) ) \n {\n QTextStream ts( &f );\n browser->setText( ts.readAll() );\n }\n f.close();\n }\n QTextFrameFormat format = browser->document()->rootFrame()->frameFormat();\n format.setMargin(12);\n browser->document()->rootFrame()->setFrameFormat( format );\n }\n}\n\n#include \"MarbleAboutDialog.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#include <Atema\/Atema.hpp>\n\n#include \"BasicRenderPipeline.hpp\"\n\n#include <iostream>\n\nusing namespace at;\n\nclass TestLayer : public ApplicationLayer\n{\npublic:\n\tTestLayer() :\n\t\tframeCount(0),\n\t\tframeDuration(0.0f)\n\t{\n\t\tinitialize();\n\t}\n\n\t~TestLayer()\n\t{\n\t\trenderPipeline.reset();\n\n\t\t\/\/ Window & Renderer\n\t\twindow.reset();\n\t\t\n\t\tRenderer::destroy();\n\t}\n\n\tvoid initialize()\n\t{\n\t\tmaxFramesInFlight = 2;\n\t\tcurrentFrame = 0;\n\t\tindexCount = 0;\n\n\t\tRenderer::Settings settings;\n\t\tsettings.maxFramesInFlight = maxFramesInFlight;\n\t\t\/\/settings.mainWindowSettings.width = 1920;\n\t\t\/\/settings.mainWindowSettings.height = 1080;\n\n\t\tRenderer::create<VulkanRenderer>(settings);\n\n\t\t\/\/ Window \/ SwapChain\n\t\twindow = Renderer::getInstance().getMainWindow();\n\n\t\tRenderPipeline::Settings renderPipelineSettings;\n\t\trenderPipelineSettings.window = window;\n\n\t\trenderPipeline = std::make_shared<BasicRenderPipeline>(renderPipelineSettings);\n\t}\n\n\tvoid onEvent(Event& event) override\n\t{\n\t\t\n\t}\n\t\n\tvoid update(TimeStep ms) override\n\t{\n\t\tATEMA_BENCHMARK(\"Application update\")\n\n\t\ttotalTime += ms.getSeconds();\n\t\tframeDuration += ms.getSeconds();\n\n\t\tif (window->shouldClose())\n\t\t{\n\t\t\tApplication::instance().close();\n\t\t\treturn;\n\t\t}\n\n\t\twindow->processEvents();\n\t\t\n\t\trenderPipeline->update(ms);\n\t\t\n\t\twindow->swapBuffers();\n\n\t\tframeCount++;\n\n\t\tif (frameDuration >= 0.5f)\n\t\t{\n\t\t\tconst auto frameTime = frameDuration \/ static_cast<float>(frameCount);\n\t\t\tconst auto fps = static_cast<unsigned>(1.0f \/ frameTime);\n\n\t\t\twindow->setTitle(\"Atema (\" + std::to_string(fps) + \" fps \/ \" + std::to_string(frameTime * 1000.0f) + \" ms)\");\n\n\t\t\tBenchmarkManager::getInstance().print(frameCount);\n\t\t\tBenchmarkManager::getInstance().reset();\n\n\t\t\tframeCount = 0;\n\t\t\tframeDuration = 0.0f;\n\t\t}\n\t}\n\n\tuint32_t maxFramesInFlight;\n\tuint32_t currentFrame;\n\tPtr<Window> window;\n\tPtr<SwapChain> swapChain;\n\tPtr<RenderPass> renderPass;\n\tPtr<Image> depthImage;\n\tstd::vector<Ptr<Framebuffer>> framebuffers;\n\tPtr<DescriptorSetLayout> descriptorSetLayout;\n\tPtr<GraphicsPipeline> pipeline;\n\tstd::vector<Ptr<CommandPool>> commandPools;\n\tstd::vector<Ptr<CommandBuffer>> commandBuffers;\n\tstd::vector<Ptr<Fence>> fences;\n\tstd::vector<Ptr<Fence>> imageFences;\n\tstd::vector<Ptr<Semaphore>> imageAvailableSemaphores;\n\tstd::vector<Ptr<Semaphore>> renderFinishedSemaphores;\n\tPtr<DescriptorPool> descriptorPool;\n\n\tPtr<Buffer> vertexBuffer;\n\tPtr<Buffer> indexBuffer;\n\tPtr<Image> texture;\n\tPtr<Sampler> sampler;\n\tstd::vector<Ptr<Buffer>> uniformBuffers;\n\tstd::vector<Ptr<DescriptorSet>> descriptorSets;\n\n\tuint32_t indexCount;\n\n\tfloat totalTime;\n\n\tPtr<BasicRenderPipeline> renderPipeline;\n\n\tint frameCount;\n\tfloat frameDuration;\n\n};\n\nvoid basicApplication()\n{\n\tauto layer = new TestLayer();\n\n\tauto& app = Application::instance();\n\n\tapp.addLayer(layer);\n\n\tapp.run();\n\n\tdelete layer;\n}\n\n\/\/ MAIN\nint main(int argc, char** argv)\n{\n\ttry\n\t{\n\t\tbasicApplication();\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn -1;\n\t}\n\t\n\treturn 0;\n}<commit_msg>Examples - Sandbox - Cleaned code and removed old members<commit_after>#include <Atema\/Atema.hpp>\n\n#include \"BasicRenderPipeline.hpp\"\n\n#include <iostream>\n\nusing namespace at;\n\nclass SandboxLayer : public ApplicationLayer\n{\npublic:\n\tSandboxLayer() :\n\t\tframeCount(0),\n\t\tframeDuration(0.0f)\n\t{\n\t\tinitialize();\n\t}\n\n\t~SandboxLayer()\n\t{\n\t\trenderPipeline.reset();\n\n\t\t\/\/ Window & Renderer\n\t\twindow.reset();\n\t\t\n\t\tRenderer::destroy();\n\t}\n\n\tvoid initialize()\n\t{\n\t\tRenderer::Settings settings;\n\t\tsettings.maxFramesInFlight = 2;\n\t\t\/\/settings.mainWindowSettings.width = 1920;\n\t\t\/\/settings.mainWindowSettings.height = 1080;\n\n\t\tRenderer::create<VulkanRenderer>(settings);\n\n\t\t\/\/ Window \/ SwapChain\n\t\twindow = Renderer::getInstance().getMainWindow();\n\n\t\tRenderPipeline::Settings renderPipelineSettings;\n\t\trenderPipelineSettings.window = window;\n\n\t\trenderPipeline = std::make_shared<BasicRenderPipeline>(renderPipelineSettings);\n\t}\n\n\tvoid onEvent(Event& event) override\n\t{\n\t\t\n\t}\n\t\n\tvoid update(TimeStep ms) override\n\t{\n\t\tATEMA_BENCHMARK(\"Application update\")\n\t\t\n\t\tframeDuration += ms.getSeconds();\n\n\t\tif (window->shouldClose())\n\t\t{\n\t\t\tApplication::instance().close();\n\t\t\treturn;\n\t\t}\n\n\t\twindow->processEvents();\n\t\t\n\t\trenderPipeline->update(ms);\n\t\t\n\t\twindow->swapBuffers();\n\n\t\tframeCount++;\n\n\t\tif (frameDuration >= 0.5f)\n\t\t{\n\t\t\tconst auto frameTime = frameDuration \/ static_cast<float>(frameCount);\n\t\t\tconst auto fps = static_cast<unsigned>(1.0f \/ frameTime);\n\n\t\t\twindow->setTitle(\"Atema (\" + std::to_string(fps) + \" fps \/ \" + std::to_string(frameTime * 1000.0f) + \" ms)\");\n\n\t\t\tBenchmarkManager::getInstance().print(frameCount);\n\t\t\tBenchmarkManager::getInstance().reset();\n\n\t\t\tframeCount = 0;\n\t\t\tframeDuration = 0.0f;\n\t\t}\n\t}\n\n\tPtr<Window> window;\n\n\tPtr<BasicRenderPipeline> renderPipeline;\n\n\tint frameCount;\n\tfloat frameDuration;\n};\n\n\/\/ MAIN\nint main(int argc, char** argv)\n{\n\ttry\n\t{\n\t\tauto sandboxLayer = std::make_unique<SandboxLayer>();\n\n\t\tauto& app = Application::instance();\n\n\t\tapp.addLayer(sandboxLayer.get());\n\n\t\tapp.run();\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cout << e.what() << std::endl;\n\t\t\n\t\treturn -1;\n\t}\n\t\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\n#include <stdio.h>\n#include <stdlib.h>\n#include <semaphore.h>\n#include <unistd.h>\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n\n#include \"FibIndicationWrapper.h\"\n#include \"FibRequestProxy.h\"\n#include \"GeneratedTypes.h\"\n\nsem_t test_sem;\n\nclass FibIndication : public FibIndicationWrapper\n{\npublic:\n virtual void fibresult(uint32_t v) {\n fprintf(stderr, \"fibresult: %d\\n\", v);\n\tsem_post(&test_sem);\n }\n virtual void fibnote(uint32_t v) {\n fprintf(stderr, \"fibnote: %d\\n\", v);\n }\n FibIndication(unsigned int id) : FibIndicationWrapper(id) {}\n};\n\nFibRequestProxy *fibRequestProxy = 0;\nFibIndication *fibIndication;\n\n\nint main(int argc, const char **argv)\n{\n int i;\n \/\/ these use the default poller\n fibRequestProxy = new FibRequestProxy(IfcNames_FibRequest);\n fibIndication = new FibIndication(IfcNames_FibIndication);\n \n if(sem_init(&test_sem, 1, 0)){\n fprintf(stderr, \"failed to init test_sem\\n\");\n return -1;\n }\n pthread_t tid;\n fprintf(stderr, \"creating exec thread\\n\");\n if(pthread_create(&tid, NULL, portalExec, NULL)){\n fprintf(stderr, \"error creating exec thread\\n\");\n exit(1);\n }\n\n for (i = 0; i < 10; i += 1) {\n fprintf(stderr, \"fib(%d)\\n\", i);\n fibRequestProxy->fib(i);\n sem_wait(&test_sem);\n }\n\n return 0;\n}\n<commit_msg>change to first 20 fibs<commit_after>\n#include <stdio.h>\n#include <stdlib.h>\n#include <semaphore.h>\n#include <unistd.h>\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n\n#include \"FibIndicationWrapper.h\"\n#include \"FibRequestProxy.h\"\n#include \"GeneratedTypes.h\"\n\nsem_t test_sem;\n\nclass FibIndication : public FibIndicationWrapper\n{\npublic:\n virtual void fibresult(uint32_t v) {\n fprintf(stderr, \"fibresult: %d\\n\", v);\n\tsem_post(&test_sem);\n }\n virtual void fibnote(uint32_t v) {\n fprintf(stderr, \"fibnote: %d\\n\", v);\n }\n FibIndication(unsigned int id) : FibIndicationWrapper(id) {}\n};\n\nFibRequestProxy *fibRequestProxy = 0;\nFibIndication *fibIndication;\n\n\nint main(int argc, const char **argv)\n{\n int i;\n \/\/ these use the default poller\n fibRequestProxy = new FibRequestProxy(IfcNames_FibRequest);\n fibIndication = new FibIndication(IfcNames_FibIndication);\n \n if(sem_init(&test_sem, 1, 0)){\n fprintf(stderr, \"failed to init test_sem\\n\");\n return -1;\n }\n pthread_t tid;\n fprintf(stderr, \"creating exec thread\\n\");\n if(pthread_create(&tid, NULL, portalExec, NULL)){\n fprintf(stderr, \"error creating exec thread\\n\");\n exit(1);\n }\n\n for (i = 0; i < 20; i += 1) {\n fprintf(stderr, \"fib(%d)\\n\", i);\n fibRequestProxy->fib(i);\n sem_wait(&test_sem);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst int UFSIZE = 100010;\nint union_find[UFSIZE];\n\nvoid init() {\n for (auto i=0; i<UFSIZE; i++) {\n union_find[i] = i;\n }\n}\n\nint root(int a) {\n if (a == union_find[a]) return a;\n return (union_find[a] = root(union_find[a]));\n}\n\nbool issame(int a, int b) {\n return root(a) == root(b);\n}\n\nvoid unite(int a, int b) {\n union_find[root(a)] = root(b);\n}\n\nbool isroot(int a) {\n return root(a) == a;\n}\n\nint N, M;\nint a[100010];\nint b[100010];\nint Q;\nint x[100010];\nint y[100010];\ntuple<int, int> parent[100010];\nint d[100010][20];\nint depth[100010];\nvector<int> V[100010];\n\nint lca(int u, int v) {\n if (depth[u] > depth[v]) swap(u, v);\n for (auto k = 0; k < 20; ++k) {\n if ((depth[v] - depth[u]) >> k & 1) {\n v = d[v][k];\n }\n }\n if (u == v) return u;\n for (auto k = 19; k >= 0; --k) {\n if (d[k][u] != d[k][v]) {\n u = d[u][k];\n v = d[v][k];\n }\n }\n return d[u][0];\n}\n\nint main() {\n \/\/ initが必要\n init();\n fill(&d[0][0], &d[0][0]+100010*20, -1);\n fill(parent, parent+100010, make_tuple(-1, 0));\n cin >> N >> M;\n for (auto i = 0; i < M; ++i) {\n cin >> a[i] >> b[i];\n a[i]--;\n b[i]--;\n }\n cin >> Q;\n for (auto i = 0; i < Q; ++i) {\n cin >> x[i] >> y[i];\n x[i]--;\n y[i]--;\n }\n for (auto i = 0; i < M; ++i) {\n parent[root(a[i])] = make_tuple(root(b[i]), i);\n V[root(b[i])].push_back(root(a[i]));\n unite(a[i], b[i]);\n }\n for (auto i = 0; i < N; ++i) {\n d[i][0] = get<0>(parent[i]);\n }\n for (auto i = 1; i < 20; ++i) {\n for (auto j = 0; j < N; ++j) {\n if (d[j][i-1] >= 0) {\n d[j][i] = d[d[j][i-1]][i-1];\n }\n }\n }\n fill(depth, depth+100010, -1);\n for (auto i = 0; i < N; ++i) {\n if (d[i][0] == -1) {\n stack<tuple<int, int> > S;\n S.push(make_tuple(i, 0));\n while (!S.empty()) {\n int now = get<0>(S.top());\n int dep = get<1>(S.top());\n S.pop();\n if (depth[now] == -1) {\n depth[now] = dep;\n for (auto x : V[now]) {\n if (depth[x] == -1) {\n S.push(make_tuple(x, dep+1));\n }\n }\n }\n }\n }\n }\n for (auto i = 0; i < Q; ++i) {\n if (!issame(x[i], y[i])) {\n cout << -1 << endl;\n } else {\n int c = lca(x[i], y[i]);\n cout << get<1>(parent[c])+1 << endl;\n }\n }\n}\n<commit_msg>tried H.cpp to 'H'<commit_after>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst int UFSIZE = 100010;\nint union_find[UFSIZE];\n\nvoid init() {\n for (auto i=0; i<UFSIZE; i++) {\n union_find[i] = i;\n }\n}\n\nint root(int a) {\n if (a == union_find[a]) return a;\n return (union_find[a] = root(union_find[a]));\n}\n\nbool issame(int a, int b) {\n return root(a) == root(b);\n}\n\nvoid unite(int a, int b) {\n union_find[root(a)] = root(b);\n}\n\nbool isroot(int a) {\n return root(a) == a;\n}\n\nint N, M;\nint a[100010];\nint b[100010];\nint Q;\nint x[100010];\nint y[100010];\ntuple<int, int> parent[100010];\nint d[100010][20];\nint depth[100010];\nvector<int> V[100010];\n\nint lca(int u, int v) {\n if (depth[u] > depth[v]) swap(u, v);\n for (auto k = 0; k < 20; ++k) {\n if ((depth[v] - depth[u]) >> k & 1) {\n v = d[v][k];\n }\n }\n if (u == v) return u;\n for (auto k = 19; k >= 0; --k) {\n if (d[k][u] != d[k][v]) {\n u = d[u][k];\n v = d[v][k];\n }\n }\n return d[u][0];\n}\n\nint main() {\n \/\/ initが必要\n init();\n fill(&d[0][0], &d[0][0]+100010*20, -1);\n fill(parent, parent+100010, make_tuple(-1, 0));\n cin >> N >> M;\n for (auto i = 0; i < M; ++i) {\n cin >> a[i] >> b[i];\n a[i]--;\n b[i]--;\n }\n cin >> Q;\n for (auto i = 0; i < Q; ++i) {\n cin >> x[i] >> y[i];\n x[i]--;\n y[i]--;\n }\n for (auto i = 0; i < M; ++i) {\n parent[root(a[i])] = make_tuple(root(b[i]), i);\n V[root(b[i])].push_back(root(a[i]));\n unite(a[i], b[i]);\n }\n for (auto i = 0; i < N; ++i) {\n d[i][0] = get<0>(parent[i]);\n }\n for (auto i = 1; i < 20; ++i) {\n for (auto j = 0; j < N; ++j) {\n if (d[j][i-1] >= 0) {\n d[j][i] = d[d[j][i-1]][i-1];\n }\n }\n }\n fill(depth, depth+100010, -1);\n for (auto i = 0; i < N; ++i) {\n if (d[i][0] == -1) {\n stack<tuple<int, int> > S;\n S.push(make_tuple(i, 0));\n while (!S.empty()) {\n int now = get<0>(S.top());\n int dep = get<1>(S.top());\n S.pop();\n if (depth[now] == -1) {\n depth[now] = dep;\n for (auto x : V[now]) {\n if (depth[x] == -1) {\n S.push(make_tuple(x, dep+1));\n }\n }\n }\n }\n }\n }\n for (auto i = 0; i < N; ++i) {\n cerr << \"depth[\" << i << \"] = \" << depth[i] << endl;\n }\n for (auto i = 0; i < Q; ++i) {\n if (!issame(x[i], y[i])) {\n cout << -1 << endl;\n } else {\n int c = lca(x[i], y[i]);\n cout << get<1>(parent[c])+1 << endl;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ object that creates and contains a spawn position\n\n#include \"common.h\"\n\n#include \"SpawnPosition.h\"\n#include \"FlagInfo.h\"\n#include \"TeamBases.h\"\n#include \"WorldInfo.h\"\n#include \"PlayerInfo.h\"\n#include \"PlayerState.h\"\n\n\/\/ FIXME: from bzfs.cxx\nextern int getCurMaxPlayers();\nextern bool areFoes(TeamColor team1, TeamColor team2);\nextern BasesList bases;\nextern WorldInfo *world;\nextern PlayerInfo player[];\nextern PlayerState lastState[];\n\nSpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :\n\t\tcurMaxPlayers(getCurMaxPlayers())\n{\n team = player[playerId].getTeam();\n azimuth = (float)bzfrand() * 2.0f * M_PI;\n\n if (player[playerId].shouldRestartAtBase() &&\n (team >= RedTeam) && (team <= PurpleTeam) && \n (bases.find(team) != bases.end())) {\n TeamBases &teamBases = bases[team];\n const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));\n base.getRandomPosition(pos[0], pos[1], pos[2]);\n player[playerId].setRestartOnBase(false);\n } else {\n const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);\n const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);\n safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);\n safeDistance = tankRadius * 20; \/\/ FIXME: is this a good value?\n const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);\n const float maxWorldHeight = world->getMaxWorldHeight();\n ObstacleLocation *building = NULL;\n\n \/\/ keep track of how much time we spend searching for a location\n TimeKeeper start = TimeKeeper::getCurrent();\n\n int inAirAttempts = 50;\n int tries = 0;\n float minProximity = size \/ 3.0f;\n float bestDist = -1.0f;\n bool foundspot = false;\n while (!foundspot) {\n if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {\n if (notNearEdges) {\n \/\/ don't spawn close to map edges in CTF mode\n testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n\t} else {\n testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n\t}\n testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);\n }\n tries++;\n\n int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\n if (onGroundOnly) {\n if (type == NOT_IN_BUILDING)\n foundspot = true;\n } else {\n if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {\n testPos[2] = 0.0f;\n \/\/Find any intersection regardless of z\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, maxWorldHeight);\n }\n\n \/\/ in a building? try climbing on roof until on top\n int lastType = type;\n\tint retriesRemaining = 100; \/\/ don't climb forever\n while (type != NOT_IN_BUILDING) {\n testPos[2] = building->pos[2] + building->size[2] + 0.0001f;\n tries++;\n lastType = type;\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\t if (--retriesRemaining <= 0) {\n\t DEBUG1(\"Warning: getSpawnLocation had to climb too many buildings\\n\");\n\t break;\n\t }\n }\n \/\/ ok, when not on top of pyramid or teleporter\n if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {\n foundspot = true;\n }\n \/\/ only try up in the sky so many times\n if (--inAirAttempts <= 0) {\n onGroundOnly = true;\n }\n }\n\n \/\/ check every now and then if we have already used up 10ms of time\n if (tries >= 50) {\n tries = 0;\n if (TimeKeeper::getCurrent() - start > 0.01f) {\n if (bestDist < 0.0f) { \/\/ haven't found a single spot\n \/\/Just drop the sucka in, and pray\n pos[0] = testPos[0];\n pos[1] = testPos[1];\n pos[2] = maxWorldHeight;\n\t DEBUG1(\"Warning: getSpawnLocation ran out of time, just dropping the sucker in\\n\");\n }\n break;\n }\n }\n\n \/\/ check if spot is safe enough\n bool dangerous = isImminentlyDangerous();\n if (foundspot && !dangerous) {\n\tfloat enemyAngle;\n\tfloat dist = enemyProximityCheck(enemyAngle);\n\tif (dist > bestDist) { \/\/ best so far\n\t bestDist = dist;\n\t pos[0] = testPos[0];\n\t pos[1] = testPos[1];\n\t pos[2] = testPos[2];\n\t azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);\n\t}\n\tif (bestDist < minProximity) { \/\/ not good enough, keep looking\n\t foundspot = false;\n\t minProximity *= 0.99f; \/\/ relax requirements a little\n\t}\n } else if (dangerous) {\n\tfoundspot = false;\n }\n }\n }\n}\n\nSpawnPosition::~SpawnPosition()\n{\n}\n\nconst bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, \n\t\t\t\t const float deviation) const\n{\n \/\/ determine angle from source to dest\n \/\/ (X) using only x & y, resultant will be z rotation\n float dx = testPos[0] - enemyPos[0];\n float dy = testPos[1] - enemyPos[1];\n float angActual;\n if (dx == 0) {\n \/\/ avoid divide by zero error\n angActual = (float)tan(dy \/ (1 \/ 1e12f));\n } else {\n angActual = (float)tan(dy \/ dx);\n }\n\n \/\/ see if our heading angle is within the bounds set by deviation\n \/\/ (X) only compare to z-rotation since that's all we're using\n if (((angActual + deviation \/ 2) > enemyAzimuth) &&\n ((angActual - deviation \/ 2) < enemyAzimuth)) {\n return true;\n } else {\n return false;\n }\n}\n\nconst bool SpawnPosition::isImminentlyDangerous() const\n{\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n const FlagInfo *finfo =&flag[player[i].getFlag()];\n const FlagType *ftype = finfo->flag.type;\n float *enemyPos = lastState[i].pos;\n float enemyAngle = lastState[i].azimuth;\n \/\/ check for dangerous flags, etc\n \/\/ FIXME: any more?\n if (ftype == Flags::Laser) { \/\/ don't spawn in the line of sight of an L\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/ he's looking within 20 degrees of spawn point\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n } else if (ftype == Flags::ShockWave) { \/\/ don't spawn next to a SW\n\tif (distanceFrom(enemyPos) < safeSWRadius) { \/\/ too close to SW\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n }\n \/\/ don't spawn in the line of sight of a normal-shot tank within a certain distance\n if (distanceFrom(enemyPos) < safeDistance) { \/\/ within danger zone?\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/and he's looking at me\n\t return true;\n\t}\n }\n }\n }\n\n \/\/ TODO: should check world weapons also\n\n return false;\n}\n\nconst float SpawnPosition::enemyProximityCheck(float &enemyAngle) const\n{\n float worstDist = 1e12f; \/\/ huge number\n bool noEnemy = true;\n\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n float *enemyPos = lastState[i].pos;\n if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {\n float x = enemyPos[0] - testPos[0];\n float y = enemyPos[1] - testPos[1];\n float distSq = x * x + y * y;\n if (distSq < worstDist) {\n worstDist = distSq;\n\t enemyAngle = lastState[i].azimuth;\n\t noEnemy = false;\n\t}\n }\n }\n }\n if (noEnemy)\n enemyAngle = (float)bzfrand() * 2.0f * M_PI;\n return sqrtf(worstDist);\n}\n\nconst float SpawnPosition::distanceFrom(const float* farPos) const\n{\n float dx = farPos[0] - testPos[0];\n float dy = farPos[1] - testPos[1];\n float dz = farPos[2] - testPos[2];\n return (float)sqrt(dx*dx + dy*dy + dz*dz);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Fix valgrind error; don't spawn if you'll be shot by friendly fire either<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ object that creates and contains a spawn position\n\n#include \"common.h\"\n\n#include \"SpawnPosition.h\"\n#include \"FlagInfo.h\"\n#include \"TeamBases.h\"\n#include \"WorldInfo.h\"\n#include \"PlayerInfo.h\"\n#include \"PlayerState.h\"\n\n\/\/ FIXME: from bzfs.cxx\nextern int getCurMaxPlayers();\nextern bool areFoes(TeamColor team1, TeamColor team2);\nextern BasesList bases;\nextern WorldInfo *world;\nextern PlayerInfo player[];\nextern PlayerState lastState[];\n\nSpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :\n\t\tcurMaxPlayers(getCurMaxPlayers())\n{\n team = player[playerId].getTeam();\n azimuth = (float)bzfrand() * 2.0f * M_PI;\n\n if (player[playerId].shouldRestartAtBase() &&\n (team >= RedTeam) && (team <= PurpleTeam) && \n (bases.find(team) != bases.end())) {\n TeamBases &teamBases = bases[team];\n const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));\n base.getRandomPosition(pos[0], pos[1], pos[2]);\n player[playerId].setRestartOnBase(false);\n } else {\n const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);\n const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);\n safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);\n safeDistance = tankRadius * 20; \/\/ FIXME: is this a good value?\n const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);\n const float maxWorldHeight = world->getMaxWorldHeight();\n ObstacleLocation *building = NULL;\n\n \/\/ keep track of how much time we spend searching for a location\n TimeKeeper start = TimeKeeper::getCurrent();\n\n int inAirAttempts = 50;\n int tries = 0;\n float minProximity = size \/ 3.0f;\n float bestDist = -1.0f;\n bool foundspot = false;\n while (!foundspot) {\n if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {\n if (notNearEdges) {\n \/\/ don't spawn close to map edges in CTF mode\n testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n\t} else {\n testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n\t}\n testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);\n }\n tries++;\n\n int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\n if (onGroundOnly) {\n if (type == NOT_IN_BUILDING)\n foundspot = true;\n } else {\n if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {\n testPos[2] = 0.0f;\n \/\/Find any intersection regardless of z\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, maxWorldHeight);\n }\n\n \/\/ in a building? try climbing on roof until on top\n int lastType = type;\n\tint retriesRemaining = 100; \/\/ don't climb forever\n while (type != NOT_IN_BUILDING) {\n testPos[2] = building->pos[2] + building->size[2] + 0.0001f;\n tries++;\n lastType = type;\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\t if (--retriesRemaining <= 0) {\n\t DEBUG1(\"Warning: getSpawnLocation had to climb too many buildings\\n\");\n\t break;\n\t }\n }\n \/\/ ok, when not on top of pyramid or teleporter\n if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {\n foundspot = true;\n }\n \/\/ only try up in the sky so many times\n if (--inAirAttempts <= 0) {\n onGroundOnly = true;\n }\n }\n\n \/\/ check every now and then if we have already used up 10ms of time\n if (tries >= 50) {\n tries = 0;\n if (TimeKeeper::getCurrent() - start > 0.01f) {\n if (bestDist < 0.0f) { \/\/ haven't found a single spot\n \/\/Just drop the sucka in, and pray\n pos[0] = testPos[0];\n pos[1] = testPos[1];\n pos[2] = maxWorldHeight;\n\t DEBUG1(\"Warning: getSpawnLocation ran out of time, just dropping the sucker in\\n\");\n }\n break;\n }\n }\n\n \/\/ check if spot is safe enough\n bool dangerous = isImminentlyDangerous();\n if (foundspot && !dangerous) {\n\tfloat enemyAngle;\n\tfloat dist = enemyProximityCheck(enemyAngle);\n\tif (dist > bestDist) { \/\/ best so far\n\t bestDist = dist;\n\t pos[0] = testPos[0];\n\t pos[1] = testPos[1];\n\t pos[2] = testPos[2];\n\t azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);\n\t}\n\tif (bestDist < minProximity) { \/\/ not good enough, keep looking\n\t foundspot = false;\n\t minProximity *= 0.99f; \/\/ relax requirements a little\n\t}\n } else if (dangerous) {\n\tfoundspot = false;\n }\n }\n }\n}\n\nSpawnPosition::~SpawnPosition()\n{\n}\n\nconst bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, \n\t\t\t\t const float deviation) const\n{\n \/\/ determine angle from source to dest\n \/\/ (X) using only x & y, resultant will be z rotation\n float dx = testPos[0] - enemyPos[0];\n float dy = testPos[1] - enemyPos[1];\n float angActual;\n if (dx == 0) {\n \/\/ avoid divide by zero error\n angActual = (float)tan(dy \/ (1 \/ 1e12f));\n } else {\n angActual = (float)tan(dy \/ dx);\n }\n\n \/\/ see if our heading angle is within the bounds set by deviation\n \/\/ (X) only compare to z-rotation since that's all we're using\n if (((angActual + deviation \/ 2) > enemyAzimuth) &&\n ((angActual - deviation \/ 2) < enemyAzimuth)) {\n return true;\n } else {\n return false;\n }\n}\n\nconst bool SpawnPosition::isImminentlyDangerous() const\n{\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive()) {\n float *enemyPos = lastState[i].pos;\n float enemyAngle = lastState[i].azimuth;\n if (player[i].getFlag() >= 0) {\n\t\/\/ check for dangerous flags\n \tconst FlagInfo *finfo =&flag[player[i].getFlag()];\n \tconst FlagType *ftype = finfo->flag.type;\n \t\/\/ FIXME: any more?\n \tif (ftype == Flags::Laser) { \/\/ don't spawn in the line of sight of an L\n\t if (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/ he's looking within 20 degrees of spawn point\n\t return true;\t\/\/ eek, don't spawn here\n\t }\n \t} else if (ftype == Flags::ShockWave) { \/\/ don't spawn next to a SW\n\t if (distanceFrom(enemyPos) < safeSWRadius) { \/\/ too close to SW\n\t return true;\t\/\/ eek, don't spawn here\n\t }\n }\n }\n \/\/ don't spawn in the line of sight of a normal-shot tank within a certain distance\n if (distanceFrom(enemyPos) < safeDistance) { \/\/ within danger zone?\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/and he's looking at me\n\t return true;\n\t}\n }\n }\n }\n\n \/\/ TODO: should check world weapons also\n\n return false;\n}\n\nconst float SpawnPosition::enemyProximityCheck(float &enemyAngle) const\n{\n float worstDist = 1e12f; \/\/ huge number\n bool noEnemy = true;\n\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n float *enemyPos = lastState[i].pos;\n if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {\n float x = enemyPos[0] - testPos[0];\n float y = enemyPos[1] - testPos[1];\n float distSq = x * x + y * y;\n if (distSq < worstDist) {\n worstDist = distSq;\n\t enemyAngle = lastState[i].azimuth;\n\t noEnemy = false;\n\t}\n }\n }\n }\n if (noEnemy)\n enemyAngle = (float)bzfrand() * 2.0f * M_PI;\n return sqrtf(worstDist);\n}\n\nconst float SpawnPosition::distanceFrom(const float* farPos) const\n{\n float dx = farPos[0] - testPos[0];\n float dy = farPos[1] - testPos[1];\n float dz = farPos[2] - testPos[2];\n return (float)sqrt(dx*dx + dy*dy + dz*dz);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include \"libtorrent\/magnet_uri.hpp\"\n\nint load_file(std::string const& filename, std::vector<char>& v, libtorrent::error_code& ec, int limit = 8000000)\n{\n\tec.clear();\n\tFILE* f = fopen(filename.c_str(), \"rb\");\n\tif (f == NULL)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\treturn -1;\n\t}\n\n\tint r = fseek(f, 0, SEEK_END);\n\tif (r != 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\tlong s = ftell(f);\n\tif (s < 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tif (s > limit)\n\t{\n\t\tfclose(f);\n\t\treturn -2;\n\t}\n\n\tr = fseek(f, 0, SEEK_SET);\n\tif (r != 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tv.resize(s);\n\tif (s == 0)\n\t{\n\t\tfclose(f);\n\t\treturn 0;\n\t}\n\n\tr = fread(&v[0], 1, v.size(), f);\n\tif (r < 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tfclose(f);\n\n\tif (r != s) return -3;\n\n\treturn 0;\n}\n\nint line_longer_than(libtorrent::lazy_entry const& e, int limit)\n{\n\tusing namespace libtorrent;\n\n\tint line_len = 0;\n\tswitch (e.type())\n\t{\n\tcase lazy_entry::list_t:\n\t\tline_len += 4;\n\t\tif (line_len > limit) return -1;\n\t\tfor (int i = 0; i < e.list_size(); ++i)\n\t\t{\n\t\t\tint ret = line_longer_than(*e.list_at(i), limit - line_len);\n\t\t\tif (ret == -1) return -1;\n\t\t\tline_len += ret + 2;\n\t\t}\n\t\tbreak;\n\tcase lazy_entry::dict_t:\n\t\tline_len += 4;\n\t\tif (line_len > limit) return -1;\n\t\tfor (int i = 0; i < e.dict_size(); ++i)\n\t\t{\n\t\t\tline_len += 4 + e.dict_at(i).first.size();\n\t\t\tif (line_len > limit) return -1;\n\t\t\tint ret = line_longer_than(*e.dict_at(i).second, limit - line_len);\n\t\t\tif (ret == -1) return -1;\n\t\t\tline_len += ret + 1;\n\t\t}\n\t\tbreak;\n\tcase lazy_entry::string_t:\n\t\tline_len += 3 + e.string_length();\n\t\tbreak;\n\tcase lazy_entry::int_t:\n\t{\n\t\tsize_type val = e.int_value();\n\t\twhile (val > 0)\n\t\t{\n\t\t\t++line_len;\n\t\t\tval \/= 10;\n\t\t}\n\t\tline_len += 2;\n\t}\n\tbreak;\n\tcase lazy_entry::none_t:\n\t\tline_len += 4;\n\t\tbreak;\n\t}\n\n\tif (line_len > limit) return -1;\n\treturn line_len;\n}\n\nstd::string print_entry(libtorrent::lazy_entry const& e, bool single_line = false, int indent = 0)\n{\n\tusing namespace libtorrent;\n\n\tchar indent_str[200];\n\tmemset(indent_str, ' ', 200);\n\tindent_str[0] = ',';\n\tindent_str[1] = '\\n';\n\tindent_str[199] = 0;\n\tif (indent < 197 && indent >= 0) indent_str[indent+2] = 0;\n\tstd::string ret;\n\tswitch (e.type())\n\t{\n\t\tcase lazy_entry::none_t: return \"none\";\n\t\tcase lazy_entry::int_t:\n\t\t{\n\t\t\tchar str[100];\n\t\t\tsnprintf(str, sizeof(str), \"%\"PRId64, e.int_value());\n\t\t\treturn str;\n\t\t}\n\t\tcase lazy_entry::string_t:\n\t\t{\n\t\t\tbool printable = true;\n\t\t\tchar const* str = e.string_ptr();\n\t\t\tfor (int i = 0; i < e.string_length(); ++i)\n\t\t\t{\n\t\t\t\tusing namespace std;\n\t\t\t\tif (is_print((unsigned char)str[i])) continue;\n\t\t\t\tprintable = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tret += \"'\";\n\t\t\tif (printable)\n\t\t\t{\n\t\t\t\tret += e.string_value();\n\t\t\t\tret += \"'\";\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tfor (int i = 0; i < e.string_length(); ++i)\n\t\t\t{\n\t\t\t\tchar tmp[5];\n\t\t\t\tsnprintf(tmp, sizeof(tmp), \"%02x\", (unsigned char)str[i]);\n\t\t\t\tret += tmp;\n\t\t\t}\n\t\t\tret += \"'\";\n\t\t\treturn ret;\n\t\t}\n\t\tcase lazy_entry::list_t:\n\t\t{\n\t\t\tret += '[';\n\t\t\tbool one_liner = line_longer_than(e, 200) != -1 || single_line;\n\n\t\t\tif (!one_liner) ret += indent_str + 1;\n\t\t\tfor (int i = 0; i < e.list_size(); ++i)\n\t\t\t{\n\t\t\t\tif (i == 0 && one_liner) ret += \" \";\n\t\t\t\tret += ::print_entry(*e.list_at(i), single_line, indent + 2);\n\t\t\t\tif (i < e.list_size() - 1) ret += (one_liner?\", \":indent_str);\n\t\t\t\telse ret += (one_liner?\" \":indent_str+1);\n\t\t\t}\n\t\t\tret += \"]\";\n\t\t\treturn ret;\n\t\t}\n\t\tcase lazy_entry::dict_t:\n\t\t{\n\t\t\tret += \"{\";\n\t\t\tbool one_liner = line_longer_than(e, 200) != -1 || single_line;\n\n\t\t\tif (!one_liner) ret += indent_str+1;\n\t\t\tfor (int i = 0; i < e.dict_size(); ++i)\n\t\t\t{\n\t\t\t\tif (i == 0 && one_liner) ret += \" \";\n\t\t\t\tstd::pair<std::string, lazy_entry const*> ent = e.dict_at(i);\n\t\t\t\tret += \"'\";\n\t\t\t\tret += ent.first;\n\t\t\t\tret += \"': \";\n\t\t\t\tret += ::print_entry(*ent.second, single_line, indent + 2);\n\t\t\t\tif (i < e.dict_size() - 1) ret += (one_liner?\", \":indent_str);\n\t\t\t\telse ret += (one_liner?\" \":indent_str+1);\n\t\t\t}\n\t\t\tret += \"}\";\n\t\t\treturn ret;\n\t\t}\n\t}\n\treturn ret;\n}\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tif (argc < 2 || argc > 4)\n\t{\n\t\tfputs(\"usage: dump_torrent torrent-file [total-items-limit] [recursion-limit]\\n\", stderr);\n\t\treturn 1;\n\t}\n\n\tint item_limit = 1000000;\n\tint depth_limit = 1000;\n\n\tif (argc > 2) item_limit = atoi(argv[2]);\n\tif (argc > 3) depth_limit = atoi(argv[3]);\n\n\tint size = file_size(argv[1]);\n\tif (size > 40 * 1000000)\n\t{\n\t\tfprintf(stderr, \"file too big (%d), aborting\\n\", size);\n\t\treturn 1;\n\t}\n\tstd::vector<char> buf(size);\n\terror_code ec;\n\tint ret = load_file(argv[1], buf, ec, 40 * 1000000);\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"failed to load file: %s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\tlazy_entry e;\n\tint pos;\n\tprintf(\"decoding. recursion limit: %d total item count limit: %d\\n\"\n\t\t, depth_limit, item_limit);\n\tret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e, ec, &pos\n\t\t, depth_limit, item_limit);\n\n\tprintf(\"\\n\\n----- raw info -----\\n\\n%s\\n\", ::print_entry(e).c_str());\n\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"failed to decode: '%s' at character: %d\\n\", ec.message().c_str(), pos);\n\t\treturn 1;\n\t}\n\n\ttorrent_info t(e, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\te.clear();\n\tstd::vector<char>().swap(buf);\n\n\t\/\/ print info about torrent\n\tprintf(\"\\n\\n----- torrent file info -----\\n\\n\"\n\t\t\"nodes:\\n\");\n\n\ttypedef std::vector<std::pair<std::string, int> > node_vec;\n\tnode_vec const& nodes = t.nodes();\n\tfor (node_vec::const_iterator i = nodes.begin(), end(nodes.end());\n\t\ti != end; ++i)\n\t{\n\t\tprintf(\"%s: %d\\n\", i->first.c_str(), i->second);\n\t}\n\tputs(\"trackers:\\n\");\n\tfor (std::vector<announce_entry>::const_iterator i = t.trackers().begin();\n\t\ti != t.trackers().end(); ++i)\n\t{\n\t\tprintf(\"%2d: %s\\n\", i->tier, i->url.c_str());\n\t}\n\n\tchar ih[41];\n\tto_hex((char const*)&t.info_hash()[0], 20, ih);\n\tprintf(\"number of pieces: %d\\n\"\n\t\t\"piece length: %d\\n\"\n\t\t\"info hash: %s\\n\"\n\t\t\"comment: %s\\n\"\n\t\t\"created by: %s\\n\"\n\t\t\"magnet link: %s\\n\"\n\t\t\"name: %s\\n\"\n\t\t\"number of files: %d\\n\"\n\t\t\"files:\\n\"\n\t\t, t.num_pieces()\n\t\t, t.piece_length()\n\t\t, ih\n\t\t, t.comment().c_str()\n\t\t, t.creator().c_str()\n\t\t, make_magnet_uri(t).c_str()\n\t\t, t.name().c_str()\n\t\t, t.num_files());\n\tint index = 0;\n\tfor (torrent_info::file_iterator i = t.begin_files();\n\t\ti != t.end_files(); ++i, ++index)\n\t{\n\t\tint first = t.map_file(index, 0, 0).piece;\n\t\tint last = t.map_file(index, (std::max)(size_type(i->size)-1, size_type(0)), 0).piece;\n\t\tprintf(\" %8\"PRIx64\" %11\"PRId64\" %c%c%c%c [ %5d, %5d ] %7u %s %s %s%s\\n\"\n\t\t\t, i->offset\n\t\t\t, i->size\n\t\t\t, (i->pad_file?'p':'-')\n\t\t\t, (i->executable_attribute?'x':'-')\n\t\t\t, (i->hidden_attribute?'h':'-')\n\t\t\t, (i->symlink_attribute?'l':'-')\n\t\t\t, first, last\n\t\t\t, boost::uint32_t(t.files().mtime(*i))\n\t\t\t, t.files().hash(*i) != sha1_hash(0) ? to_hex(t.files().hash(*i).to_string()).c_str() : \"\"\n\t\t\t, t.files().file_path(*i).c_str()\n\t\t\t, i->symlink_attribute ? \"-> \": \"\"\n\t\t\t, i->symlink_attribute && i->symlink_index != -1 ? t.files().symlink(*i).c_str() : \"\");\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>make dump_torrent build without deprecated functions<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include \"libtorrent\/magnet_uri.hpp\"\n\nint load_file(std::string const& filename, std::vector<char>& v, libtorrent::error_code& ec, int limit = 8000000)\n{\n\tec.clear();\n\tFILE* f = fopen(filename.c_str(), \"rb\");\n\tif (f == NULL)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\treturn -1;\n\t}\n\n\tint r = fseek(f, 0, SEEK_END);\n\tif (r != 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\tlong s = ftell(f);\n\tif (s < 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tif (s > limit)\n\t{\n\t\tfclose(f);\n\t\treturn -2;\n\t}\n\n\tr = fseek(f, 0, SEEK_SET);\n\tif (r != 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tv.resize(s);\n\tif (s == 0)\n\t{\n\t\tfclose(f);\n\t\treturn 0;\n\t}\n\n\tr = fread(&v[0], 1, v.size(), f);\n\tif (r < 0)\n\t{\n\t\tec.assign(errno, boost::system::get_generic_category());\n\t\tfclose(f);\n\t\treturn -1;\n\t}\n\n\tfclose(f);\n\n\tif (r != s) return -3;\n\n\treturn 0;\n}\n\nint line_longer_than(libtorrent::lazy_entry const& e, int limit)\n{\n\tusing namespace libtorrent;\n\n\tint line_len = 0;\n\tswitch (e.type())\n\t{\n\tcase lazy_entry::list_t:\n\t\tline_len += 4;\n\t\tif (line_len > limit) return -1;\n\t\tfor (int i = 0; i < e.list_size(); ++i)\n\t\t{\n\t\t\tint ret = line_longer_than(*e.list_at(i), limit - line_len);\n\t\t\tif (ret == -1) return -1;\n\t\t\tline_len += ret + 2;\n\t\t}\n\t\tbreak;\n\tcase lazy_entry::dict_t:\n\t\tline_len += 4;\n\t\tif (line_len > limit) return -1;\n\t\tfor (int i = 0; i < e.dict_size(); ++i)\n\t\t{\n\t\t\tline_len += 4 + e.dict_at(i).first.size();\n\t\t\tif (line_len > limit) return -1;\n\t\t\tint ret = line_longer_than(*e.dict_at(i).second, limit - line_len);\n\t\t\tif (ret == -1) return -1;\n\t\t\tline_len += ret + 1;\n\t\t}\n\t\tbreak;\n\tcase lazy_entry::string_t:\n\t\tline_len += 3 + e.string_length();\n\t\tbreak;\n\tcase lazy_entry::int_t:\n\t{\n\t\tsize_type val = e.int_value();\n\t\twhile (val > 0)\n\t\t{\n\t\t\t++line_len;\n\t\t\tval \/= 10;\n\t\t}\n\t\tline_len += 2;\n\t}\n\tbreak;\n\tcase lazy_entry::none_t:\n\t\tline_len += 4;\n\t\tbreak;\n\t}\n\n\tif (line_len > limit) return -1;\n\treturn line_len;\n}\n\nstd::string print_entry(libtorrent::lazy_entry const& e, bool single_line = false, int indent = 0)\n{\n\tusing namespace libtorrent;\n\n\tchar indent_str[200];\n\tmemset(indent_str, ' ', 200);\n\tindent_str[0] = ',';\n\tindent_str[1] = '\\n';\n\tindent_str[199] = 0;\n\tif (indent < 197 && indent >= 0) indent_str[indent+2] = 0;\n\tstd::string ret;\n\tswitch (e.type())\n\t{\n\t\tcase lazy_entry::none_t: return \"none\";\n\t\tcase lazy_entry::int_t:\n\t\t{\n\t\t\tchar str[100];\n\t\t\tsnprintf(str, sizeof(str), \"%\"PRId64, e.int_value());\n\t\t\treturn str;\n\t\t}\n\t\tcase lazy_entry::string_t:\n\t\t{\n\t\t\tbool printable = true;\n\t\t\tchar const* str = e.string_ptr();\n\t\t\tfor (int i = 0; i < e.string_length(); ++i)\n\t\t\t{\n\t\t\t\tusing namespace std;\n\t\t\t\tif (is_print((unsigned char)str[i])) continue;\n\t\t\t\tprintable = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tret += \"'\";\n\t\t\tif (printable)\n\t\t\t{\n\t\t\t\tret += e.string_value();\n\t\t\t\tret += \"'\";\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tfor (int i = 0; i < e.string_length(); ++i)\n\t\t\t{\n\t\t\t\tchar tmp[5];\n\t\t\t\tsnprintf(tmp, sizeof(tmp), \"%02x\", (unsigned char)str[i]);\n\t\t\t\tret += tmp;\n\t\t\t}\n\t\t\tret += \"'\";\n\t\t\treturn ret;\n\t\t}\n\t\tcase lazy_entry::list_t:\n\t\t{\n\t\t\tret += '[';\n\t\t\tbool one_liner = line_longer_than(e, 200) != -1 || single_line;\n\n\t\t\tif (!one_liner) ret += indent_str + 1;\n\t\t\tfor (int i = 0; i < e.list_size(); ++i)\n\t\t\t{\n\t\t\t\tif (i == 0 && one_liner) ret += \" \";\n\t\t\t\tret += ::print_entry(*e.list_at(i), single_line, indent + 2);\n\t\t\t\tif (i < e.list_size() - 1) ret += (one_liner?\", \":indent_str);\n\t\t\t\telse ret += (one_liner?\" \":indent_str+1);\n\t\t\t}\n\t\t\tret += \"]\";\n\t\t\treturn ret;\n\t\t}\n\t\tcase lazy_entry::dict_t:\n\t\t{\n\t\t\tret += \"{\";\n\t\t\tbool one_liner = line_longer_than(e, 200) != -1 || single_line;\n\n\t\t\tif (!one_liner) ret += indent_str+1;\n\t\t\tfor (int i = 0; i < e.dict_size(); ++i)\n\t\t\t{\n\t\t\t\tif (i == 0 && one_liner) ret += \" \";\n\t\t\t\tstd::pair<std::string, lazy_entry const*> ent = e.dict_at(i);\n\t\t\t\tret += \"'\";\n\t\t\t\tret += ent.first;\n\t\t\t\tret += \"': \";\n\t\t\t\tret += ::print_entry(*ent.second, single_line, indent + 2);\n\t\t\t\tif (i < e.dict_size() - 1) ret += (one_liner?\", \":indent_str);\n\t\t\t\telse ret += (one_liner?\" \":indent_str+1);\n\t\t\t}\n\t\t\tret += \"}\";\n\t\t\treturn ret;\n\t\t}\n\t}\n\treturn ret;\n}\n\nint main(int argc, char* argv[])\n{\n\tusing namespace libtorrent;\n\n\tif (argc < 2 || argc > 4)\n\t{\n\t\tfputs(\"usage: dump_torrent torrent-file [total-items-limit] [recursion-limit]\\n\", stderr);\n\t\treturn 1;\n\t}\n\n\tint item_limit = 1000000;\n\tint depth_limit = 1000;\n\n\tif (argc > 2) item_limit = atoi(argv[2]);\n\tif (argc > 3) depth_limit = atoi(argv[3]);\n\n\tint size = file_size(argv[1]);\n\tif (size > 40 * 1000000)\n\t{\n\t\tfprintf(stderr, \"file too big (%d), aborting\\n\", size);\n\t\treturn 1;\n\t}\n\tstd::vector<char> buf(size);\n\terror_code ec;\n\tint ret = load_file(argv[1], buf, ec, 40 * 1000000);\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"failed to load file: %s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\tlazy_entry e;\n\tint pos;\n\tprintf(\"decoding. recursion limit: %d total item count limit: %d\\n\"\n\t\t, depth_limit, item_limit);\n\tret = lazy_bdecode(&buf[0], &buf[0] + buf.size(), e, ec, &pos\n\t\t, depth_limit, item_limit);\n\n\tprintf(\"\\n\\n----- raw info -----\\n\\n%s\\n\", ::print_entry(e).c_str());\n\n\tif (ret != 0)\n\t{\n\t\tfprintf(stderr, \"failed to decode: '%s' at character: %d\\n\", ec.message().c_str(), pos);\n\t\treturn 1;\n\t}\n\n\ttorrent_info t(e, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"%s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n\te.clear();\n\tstd::vector<char>().swap(buf);\n\n\t\/\/ print info about torrent\n\tprintf(\"\\n\\n----- torrent file info -----\\n\\n\"\n\t\t\"nodes:\\n\");\n\n\ttypedef std::vector<std::pair<std::string, int> > node_vec;\n\tnode_vec const& nodes = t.nodes();\n\tfor (node_vec::const_iterator i = nodes.begin(), end(nodes.end());\n\t\ti != end; ++i)\n\t{\n\t\tprintf(\"%s: %d\\n\", i->first.c_str(), i->second);\n\t}\n\tputs(\"trackers:\\n\");\n\tfor (std::vector<announce_entry>::const_iterator i = t.trackers().begin();\n\t\ti != t.trackers().end(); ++i)\n\t{\n\t\tprintf(\"%2d: %s\\n\", i->tier, i->url.c_str());\n\t}\n\n\tchar ih[41];\n\tto_hex((char const*)&t.info_hash()[0], 20, ih);\n\tprintf(\"number of pieces: %d\\n\"\n\t\t\"piece length: %d\\n\"\n\t\t\"info hash: %s\\n\"\n\t\t\"comment: %s\\n\"\n\t\t\"created by: %s\\n\"\n\t\t\"magnet link: %s\\n\"\n\t\t\"name: %s\\n\"\n\t\t\"number of files: %d\\n\"\n\t\t\"files:\\n\"\n\t\t, t.num_pieces()\n\t\t, t.piece_length()\n\t\t, ih\n\t\t, t.comment().c_str()\n\t\t, t.creator().c_str()\n\t\t, make_magnet_uri(t).c_str()\n\t\t, t.name().c_str()\n\t\t, t.num_files());\n\tfile_storage const& st = t.files();\n\tfor (int i = 0; i < st.num_files(); ++i)\n\t{\n\t\tint first = st.map_file(i, 0, 0).piece;\n\t\tint last = st.map_file(i, (std::max)(size_type(st.file_size(i))-1, size_type(0)), 0).piece;\n\t\tint flags = st.file_flags(i);\n\t\tprintf(\" %8\" PRIx64 \" %11\" PRId64 \" %c%c%c%c [ %5d, %5d ] %7u %s %s %s%s\\n\"\n\t\t\t, st.file_offset(i)\n\t\t\t, st.file_size(i)\n\t\t\t, ((flags & file_storage::flag_pad_file)?'p':'-')\n\t\t\t, ((flags & file_storage::flag_executable)?'x':'-')\n\t\t\t, ((flags & file_storage::flag_hidden)?'h':'-')\n\t\t\t, ((flags & file_storage::flag_symlink)?'l':'-')\n\t\t\t, first, last\n\t\t\t, boost::uint32_t(st.mtime(i))\n\t\t\t, st.hash(i) != sha1_hash(0) ? to_hex(st.hash(i).to_string()).c_str() : \"\"\n\t\t\t, st.file_path(i).c_str()\n\t\t\t, (flags & file_storage::flag_symlink) ? \"-> \" : \"\"\n\t\t\t, (flags & file_storage::flag_symlink) ? st.symlink(i).c_str() : \"\");\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <unistd.h>\n\n#include <event2\/event.h>\n#include <event2\/thread.h>\n\n#include <process\/logging.hpp>\n\n#include \"event_loop.hpp\"\n#include \"libevent.hpp\"\n\nnamespace process {\n\nstruct event_base* base = NULL;\n\nvoid* EventLoop::run(void*)\n{\n int result = event_base_loop(base, 0);\n if (result < 0) {\n LOG(FATAL) << \"Failed to run event loop\";\n } else if (result == 1) {\n VLOG(1) << \"Finished running event loop due to lack of events\";\n }\n\n return NULL;\n}\n\n\nvoid EventLoop::initialize()\n{\n if (evthread_use_pthreads() < 0) {\n LOG(FATAL) << \"Failed to initialize, evthread_use_pthreads\";\n }\n\n \/\/ This enables debugging of libevent calls. We can remove this\n \/\/ when the implementation settles and after we gain confidence.\n event_enable_debug_mode();\n\n base = event_base_new();\n if (base == NULL) {\n LOG(FATAL) << \"Failed to initialize, event_base_new\";\n }\n}\n\n} \/\/ namespace process {\n<commit_msg>Introduce libevent clock implementation.<commit_after>#include <unistd.h>\n\n#include <event2\/event.h>\n#include <event2\/thread.h>\n\n#include <process\/logging.hpp>\n\n#include \"event_loop.hpp\"\n#include \"libevent.hpp\"\n#include \"synchronized.hpp\"\n\nnamespace process {\n\nstruct event_base* base = NULL;\n\n\nvoid* EventLoop::run(void*)\n{\n do {\n int result = event_base_loop(base, EVLOOP_ONCE);\n if (result < 0) {\n LOG(FATAL) << \"Failed to run event loop\";\n } else if (result == 1) {\n VLOG(1) << \"All events handled, continuing event loop\";\n continue;\n } else if (event_base_got_break(base)) {\n break;\n } else if (event_base_got_exit(base)) {\n break;\n }\n } while (true);\n return NULL;\n}\n\n\nnamespace internal {\n\nstruct Delay\n{\n void(*function)(void);\n event* timer;\n};\n\nvoid handle_delay(int, short, void* arg)\n{\n Delay* delay = reinterpret_cast<Delay*>(arg);\n delay->function();\n delete delay;\n}\n\n} \/\/ namespace internal {\n\n\nvoid EventLoop::delay(const Duration& duration, void(*function)(void))\n{\n internal::Delay* delay = new internal::Delay();\n delay->timer = evtimer_new(base, &internal::handle_delay, delay);\n if (delay->timer == NULL) {\n LOG(FATAL) << \"Failed to delay, evtimer_new\";\n }\n\n delay->function = function;\n\n timeval t{0, 0};\n if (duration > Seconds(0)) {\n t = duration.timeval();\n }\n\n evtimer_add(delay->timer, &t);\n}\n\n\ndouble EventLoop::time()\n{\n \/\/ Get the cached time if running the event loop, or call\n \/\/ gettimeofday() to get the current time. Since a lot of logic in\n \/\/ libprocess depends on time math, we want to log fatal rather than\n \/\/ cause logic errors if the time fails.\n timeval t;\n if (event_base_gettimeofday_cached(base, &t) < 0) {\n LOG(FATAL) << \"Failed to get time, event_base_gettimeofday_cached\";\n }\n\n return Duration(t).secs();\n}\n\n\nvoid EventLoop::initialize()\n{\n if (evthread_use_pthreads() < 0) {\n LOG(FATAL) << \"Failed to initialize, evthread_use_pthreads\";\n }\n\n \/\/ This enables debugging of libevent calls. We can remove this\n \/\/ when the implementation settles and after we gain confidence.\n event_enable_debug_mode();\n\n base = event_base_new();\n if (base == NULL) {\n LOG(FATAL) << \"Failed to initialize, event_base_new\";\n }\n}\n\n} \/\/ namespace process {\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n#include <cmath>\n#include <memory>\n\nnamespace choreograph\n{\n\n\/\/\/ Define our Time type here so it's easier to change out if needed.\n\/\/\/ Float loses precision pretty quickly, but is fast and doesn't take up much space.\n\/\/\/ Also, since only Motions keep playheads, we only need enough precision for our longest Motion.\nusing Time = float;\n\ntemplate<typename T>\nclass Sequence;\n\n\/\/\/\n\/\/\/ A Source of motion.\n\/\/\/ Virtual base class with concept of value and implementation of time.\n\/\/\/\ntemplate<typename T>\nclass Source\n{\npublic:\n Source() = default;\n\n Source( Time duration ):\n _duration( duration )\n {}\n\n virtual ~Source() = default;\n\n \/\/\/ Override to provide value at requested time.\n \/\/\/ Returns the interpolated value at the given time.\n virtual T getValue( Time atTime ) const = 0;\n\n \/\/\/ Override to provide value at start (and before).\n virtual T getStartValue() const = 0;\n\n \/\/\/ Override to provide value at end (and beyond).\n virtual T getEndValue() const = 0;\n\n \/\/\/ Override to provide a copy of the derived Source. Needed for phrases to be copy-composable.\n virtual std::unique_ptr<Source<T>> clone() const = 0;\n\n \/\/\/ Returns the Source value at \\a time, looping past the end from inflection point to the end.\n \/\/\/ Relies on the subclass implementation of getValue( t ).\n T getValueWrapped( Time time, Time inflectionPoint = 0.0f ) const { return getValue( wrapTime( time, inflectionPoint ) ); }\n\n \/\/\/ Returns normalized time if t is in range [start_time, end_time].\n inline Time normalizeTime( Time t ) const { return t \/ _duration; }\n \/\/\/ Returns the duration of this source.\n inline Time getDuration() const { return _duration; }\n\n \/\/\/ Wrap \\a time around \\a inflectionPoint in the Sequence.\n Time wrapTime( Time time, Time inflectionPoint = 0.0f ) const\n {\n if( time > getDuration() ) {\n return inflectionPoint + std::fmodf( time, getDuration() - inflectionPoint );\n }\n else {\n return time;\n }\n }\n\nprivate:\n Time _duration = 1;\n\n friend class Sequence<T>;\n};\n\ntemplate<typename T>\nusing SourceRef = std::shared_ptr<Source<T>>;\n\ntemplate<typename T>\nusing SourceUniqueRef = std::unique_ptr<Source<T>>;\n\n} \/\/ namespace choreograph\n<commit_msg>Note about double by Time alias.<commit_after>\/*\n * Copyright (c) 2014 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n#include <cmath>\n#include <memory>\n\nnamespace choreograph\n{\n\n\/\/\/ Define our Time type here so it's easier to change out if needed.\n\/\/\/ Float loses precision pretty quickly, but is fast and doesn't take up much space.\n\/\/\/ Sub in double if you find yourself needing extra precision for time.\n\/\/\/ Also, since only Motions keep playheads, we only need enough precision for our longest Motion.\nusing Time = float;\n\ntemplate<typename T>\nclass Sequence;\n\n\/\/\/\n\/\/\/ A Source of motion.\n\/\/\/ Virtual base class with concept of value and implementation of time.\n\/\/\/\ntemplate<typename T>\nclass Source\n{\npublic:\n Source() = default;\n\n Source( Time duration ):\n _duration( duration )\n {}\n\n virtual ~Source() = default;\n\n \/\/\/ Override to provide value at requested time.\n \/\/\/ Returns the interpolated value at the given time.\n virtual T getValue( Time atTime ) const = 0;\n\n \/\/\/ Override to provide value at start (and before).\n virtual T getStartValue() const = 0;\n\n \/\/\/ Override to provide value at end (and beyond).\n virtual T getEndValue() const = 0;\n\n \/\/\/ Override to provide a copy of the derived Source. Needed for phrases to be copy-composable.\n virtual std::unique_ptr<Source<T>> clone() const = 0;\n\n \/\/\/ Returns the Source value at \\a time, looping past the end from inflection point to the end.\n \/\/\/ Relies on the subclass implementation of getValue( t ).\n T getValueWrapped( Time time, Time inflectionPoint = 0.0f ) const { return getValue( wrapTime( time, inflectionPoint ) ); }\n\n \/\/\/ Returns normalized time if t is in range [start_time, end_time].\n inline Time normalizeTime( Time t ) const { return t \/ _duration; }\n \/\/\/ Returns the duration of this source.\n inline Time getDuration() const { return _duration; }\n\n \/\/\/ Wrap \\a time around \\a inflectionPoint in the Sequence.\n Time wrapTime( Time time, Time inflectionPoint = 0.0f ) const\n {\n if( time > getDuration() ) {\n return inflectionPoint + std::fmodf( time, getDuration() - inflectionPoint );\n }\n else {\n return time;\n }\n }\n\nprivate:\n Time _duration = 1;\n\n friend class Sequence<T>;\n};\n\ntemplate<typename T>\nusing SourceRef = std::shared_ptr<Source<T>>;\n\ntemplate<typename T>\nusing SourceUniqueRef = std::unique_ptr<Source<T>>;\n\n} \/\/ namespace choreograph\n<|endoftext|>"} {"text":"<commit_before><commit_msg>planning: fix active_set_spline_2d_solver compile warning.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2012, The Cinder Project, All rights reserved.\n Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#define ASIO_STANDALONE 1\n#include \"asio\/asio.hpp\"\n\n#include \"cinder\/app\/AppBase.h\"\n#include \"cinder\/app\/Renderer.h\"\n#include \"cinder\/Camera.h\"\n#include \"cinder\/System.h\"\n#include \"cinder\/Utilities.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/Log.h\"\n\nusing namespace std;\n\nnamespace cinder { namespace app {\n\nAppBase*\t\t\t\t\tAppBase::sInstance = nullptr;\t\t\t\/\/ Static instance of App, effectively a singleton\nAppBase::Settings*\t\t\tAppBase::sSettingsFromMain;\nstatic std::thread::id\t\tsPrimaryThreadId = std::this_thread::get_id();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ App::Settings\nAppBase::Settings::Settings()\n{\n\tmShouldQuit = false;\n\tmPowerManagement = false;\n\tmFrameRateEnabled = true;\n\tmFrameRate = 60.0f;\n\tmEnableHighDensityDisplay = false;\n\tmEnableMultiTouch = false;\n}\n\nvoid AppBase::Settings::init( const RendererRef &defaultRenderer, const char *title, int argc, char * const argv[] )\n{\n\tmDefaultRenderer = defaultRenderer;\n\tif( title )\n\t\tmTitle = title;\n\n\tfor( int arg = 0; arg < argc; ++arg )\n\t\tmCommandLineArgs.push_back( argv[arg] );\n}\n\nvoid AppBase::Settings::disableFrameRate()\n{\n\tmFrameRateEnabled = false;\n}\n\nvoid AppBase::Settings::setFrameRate( float frameRate )\n{\n\tmFrameRate = frameRate;\n}\n\nvoid AppBase::Settings::enablePowerManagement( bool powerManagement )\n{\n\tmPowerManagement = powerManagement;\n}\n\nvoid AppBase::Settings::prepareWindow( const Window::Format &format )\n{\n\tmWindowFormats.push_back( format );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ App::App\nAppBase::AppBase()\n\t: mFrameCount( 0 ), mAverageFps( 0 ), mFpsSampleInterval( 1 ), mTimer( true ), mTimeline( Timeline::create() ),\n\t\tmFpsLastSampleFrame( 0 ), mFpsLastSampleTime( 0 )\n{\n\tsInstance = this;\n\n\tCI_ASSERT( sSettingsFromMain );\n\tmDefaultRenderer = sSettingsFromMain->getDefaultRenderer();\n\tmMultiTouchEnabled = sSettingsFromMain->isMultiTouchEnabled();\n\tmHighDensityDisplayEnabled = sSettingsFromMain->isHighDensityDisplayEnabled();\n\tmFrameRateEnabled = sSettingsFromMain->isFrameRateEnabled();\n\n\tmIo = shared_ptr<asio::io_service>( new asio::io_service() );\n\tmIoWork = shared_ptr<asio::io_service::work>( new asio::io_service::work( *mIo ) );\n\n\t\/\/ due to an issue with boost::filesystem's static initialization on Windows, \n\t\/\/ it's necessary to create a fs::path here in case of secondary threads doing the same thing simultaneously\n#if (defined( CINDER_MSW ) || defined ( CINDER_WINRT ))\n\tfs::path dummyPath( \"dummy\" );\n#endif\n}\n\nAppBase::~AppBase()\n{\n\tmIo->stop();\n}\n\nvoid AppBase::privateSetup__()\n{\n\tmTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );\n\n\tsetup();\n}\n\nvoid AppBase::privateUpdate__()\n{\n\tmFrameCount++;\n\n\t\/\/ service asio::io_service\n\tmIo->poll();\n\n\tif( getNumWindows() > 0 ) {\n\t\tWindowRef mainWin = getWindowIndex( 0 );\n\t\tif( mainWin )\n\t\t\tmainWin->getRenderer()->makeCurrentContext();\n\t}\n\n\tmSignalUpdate();\n\n\tupdate();\n\n\tmTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );\n\n\tdouble now = mTimer.getSeconds();\n\tif( now > mFpsLastSampleTime + mFpsSampleInterval ) {\n\t\t\/\/calculate average Fps over sample interval\n\t\tuint32_t framesPassed = mFrameCount - mFpsLastSampleFrame;\n\t\tmAverageFps = (float)(framesPassed \/ (now - mFpsLastSampleTime));\n\n\t\tmFpsLastSampleTime = now;\n\t\tmFpsLastSampleFrame = mFrameCount;\n\t}\n}\n\nvoid AppBase::emitShutdown()\n{\n\tmSignalShutdown();\n}\n\nvoid AppBase::emitWillResignActive()\n{\n\tmSignalWillResignActive();\n}\n\nvoid AppBase::emitDidBecomeActive()\n{\n\tmSignalDidBecomeActive();\n}\n\nfs::path AppBase::getOpenFilePath( const fs::path &initialPath, const vector<string> &extensions )\n{\n\treturn Platform::get()->getOpenFilePath( initialPath, extensions );\n}\n\nfs::path AppBase::getFolderPath( const fs::path &initialPath )\n{\n\treturn Platform::get()->getFolderPath( initialPath );\n}\n\nfs::path AppBase::getSaveFilePath( const fs::path &initialPath, const vector<string> &extensions )\n{\n\treturn Platform::get()->getSaveFilePath( initialPath, extensions );\n}\n\nstd::ostream& AppBase::console()\n{\n\treturn Platform::get()->console();\n}\n\nbool AppBase::isPrimaryThread()\n{\n\treturn std::this_thread::get_id() == sPrimaryThreadId;\n}\n\nvoid AppBase::dispatchAsync( const std::function<void()> &fn )\n{\n\tio_service().post( fn );\n}\n\nSurface\tAppBase::copyWindowSurface()\n{\n\treturn getWindow()->getRenderer()->copyWindowSurface( getWindow()->toPixels( getWindow()->getBounds() ) );\n}\n\nSurface\tAppBase::copyWindowSurface( const Area &area )\n{\n\tArea clippedArea = area.getClipBy( getWindowBounds() );\n\treturn getWindow()->getRenderer()->copyWindowSurface( clippedArea );\n}\n\nRendererRef AppBase::findSharedRenderer( RendererRef searchRenderer ) const\n{\n\tif( ! searchRenderer )\n\t\treturn RendererRef();\n\n\tfor( size_t winIdx = 0; winIdx < getNumWindows(); ++winIdx ) {\n\t\tRendererRef thisRenderer = getWindowIndex( winIdx )->getRenderer();\n\t\tif( thisRenderer && (typeid( *thisRenderer ) == typeid(*searchRenderer)) )\n\t\t\treturn getWindowIndex( winIdx )->getRenderer();\n\t}\n\t\n\treturn RendererRef(); \/\/ didn't find one\n}\n\n\/\/ These are called by application instantiation macros\n\/\/ static\nvoid AppBase::prepareLaunch()\n{\n\tPlatform::get()->prepareLaunch();\n}\n\n\/\/ static\nvoid AppBase::initialize( Settings *settings, const RendererRef &defaultRenderer, const char *title, int argc, char * const argv[] )\n{\n\tsettings->init( defaultRenderer, title, argc, argv );\n\n\tsSettingsFromMain = settings;\n}\n\n\/\/ TODO: try to make this non-static, just calls launch() that is wrapped in try\/catch\n\/\/ - need to get through windows updates first\n\/\/ static\nvoid AppBase::executeLaunch( const char *title, int argc, char * const argv[] )\n{\n\ttry {\n\t\tsInstance->launch( title, argc, argv );\n\t}\n\tcatch( std::exception &exc ) {\n\t\tCI_LOG_E( \"Uncaught exception, type: \" << ci::System::demangleTypeName( typeid( exc ).name() ) << \", what : \" << exc.what() );\n\t\tthrow;\n\t}\n}\n\n\/\/ static\nvoid AppBase::cleanupLaunch()\n{\n\tPlatform::get()->cleanupLaunch();\n}\n\n} } \/\/ namespace cinder::app<commit_msg>moved the static instantiation functions higher up in AppBase.cpp, grouping them with the constructor and destructor<commit_after>\/*\n Copyright (c) 2012, The Cinder Project, All rights reserved.\n Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#define ASIO_STANDALONE 1\n#include \"asio\/asio.hpp\"\n\n#include \"cinder\/app\/AppBase.h\"\n#include \"cinder\/app\/Renderer.h\"\n#include \"cinder\/Camera.h\"\n#include \"cinder\/System.h\"\n#include \"cinder\/Utilities.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/Log.h\"\n\nusing namespace std;\n\nnamespace cinder { namespace app {\n\nAppBase*\t\t\t\t\tAppBase::sInstance = nullptr;\t\t\t\/\/ Static instance of App, effectively a singleton\nAppBase::Settings*\t\t\tAppBase::sSettingsFromMain;\nstatic std::thread::id\t\tsPrimaryThreadId = std::this_thread::get_id();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppBase::Settings\n\nAppBase::Settings::Settings()\n{\n\tmShouldQuit = false;\n\tmPowerManagement = false;\n\tmFrameRateEnabled = true;\n\tmFrameRate = 60.0f;\n\tmEnableHighDensityDisplay = false;\n\tmEnableMultiTouch = false;\n}\n\nvoid AppBase::Settings::init( const RendererRef &defaultRenderer, const char *title, int argc, char * const argv[] )\n{\n\tmDefaultRenderer = defaultRenderer;\n\tif( title )\n\t\tmTitle = title;\n\n\tfor( int arg = 0; arg < argc; ++arg )\n\t\tmCommandLineArgs.push_back( argv[arg] );\n}\n\nvoid AppBase::Settings::disableFrameRate()\n{\n\tmFrameRateEnabled = false;\n}\n\nvoid AppBase::Settings::setFrameRate( float frameRate )\n{\n\tmFrameRate = frameRate;\n}\n\nvoid AppBase::Settings::enablePowerManagement( bool powerManagement )\n{\n\tmPowerManagement = powerManagement;\n}\n\nvoid AppBase::Settings::prepareWindow( const Window::Format &format )\n{\n\tmWindowFormats.push_back( format );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppBase\n\nAppBase::AppBase()\n\t: mFrameCount( 0 ), mAverageFps( 0 ), mFpsSampleInterval( 1 ), mTimer( true ), mTimeline( Timeline::create() ),\n\t\tmFpsLastSampleFrame( 0 ), mFpsLastSampleTime( 0 )\n{\n\tsInstance = this;\n\n\tCI_ASSERT( sSettingsFromMain );\n\tmDefaultRenderer = sSettingsFromMain->getDefaultRenderer();\n\tmMultiTouchEnabled = sSettingsFromMain->isMultiTouchEnabled();\n\tmHighDensityDisplayEnabled = sSettingsFromMain->isHighDensityDisplayEnabled();\n\tmFrameRateEnabled = sSettingsFromMain->isFrameRateEnabled();\n\n\tmIo = shared_ptr<asio::io_service>( new asio::io_service() );\n\tmIoWork = shared_ptr<asio::io_service::work>( new asio::io_service::work( *mIo ) );\n\n\t\/\/ due to an issue with boost::filesystem's static initialization on Windows, \n\t\/\/ it's necessary to create a fs::path here in case of secondary threads doing the same thing simultaneously\n#if (defined( CINDER_MSW ) || defined ( CINDER_WINRT ))\n\tfs::path dummyPath( \"dummy\" );\n#endif\n}\n\nAppBase::~AppBase()\n{\n\tmIo->stop();\n}\n\n\/\/ These are called by application instantiation main functions\n\/\/ static\nvoid AppBase::prepareLaunch()\n{\n\tPlatform::get()->prepareLaunch();\n}\n\n\/\/ static\nvoid AppBase::initialize( Settings *settings, const RendererRef &defaultRenderer, const char *title, int argc, char * const argv[] )\n{\n\tsettings->init( defaultRenderer, title, argc, argv );\n\n\tsSettingsFromMain = settings;\n}\n\n\/\/ TODO: try to make this non-static, just calls launch() that is wrapped in try\/catch\n\/\/ - need to get through windows updates first\n\/\/ static\nvoid AppBase::executeLaunch( const char *title, int argc, char * const argv[] )\n{\n\ttry {\n\t\tsInstance->launch( title, argc, argv );\n\t}\n\tcatch( std::exception &exc ) {\n\t\tCI_LOG_E( \"Uncaught exception, type: \" << ci::System::demangleTypeName( typeid( exc ).name() ) << \", what : \" << exc.what() );\n\t\tthrow;\n\t}\n}\n\n\/\/ static\nvoid AppBase::cleanupLaunch()\n{\n\tPlatform::get()->cleanupLaunch();\n}\n\nvoid AppBase::privateSetup__()\n{\n\tmTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );\n\n\tsetup();\n}\n\nvoid AppBase::privateUpdate__()\n{\n\tmFrameCount++;\n\n\t\/\/ service asio::io_service\n\tmIo->poll();\n\n\tif( getNumWindows() > 0 ) {\n\t\tWindowRef mainWin = getWindowIndex( 0 );\n\t\tif( mainWin )\n\t\t\tmainWin->getRenderer()->makeCurrentContext();\n\t}\n\n\tmSignalUpdate();\n\n\tupdate();\n\n\tmTimeline->stepTo( static_cast<float>( getElapsedSeconds() ) );\n\n\tdouble now = mTimer.getSeconds();\n\tif( now > mFpsLastSampleTime + mFpsSampleInterval ) {\n\t\t\/\/calculate average Fps over sample interval\n\t\tuint32_t framesPassed = mFrameCount - mFpsLastSampleFrame;\n\t\tmAverageFps = (float)(framesPassed \/ (now - mFpsLastSampleTime));\n\n\t\tmFpsLastSampleTime = now;\n\t\tmFpsLastSampleFrame = mFrameCount;\n\t}\n}\n\nvoid AppBase::emitShutdown()\n{\n\tmSignalShutdown();\n}\n\nvoid AppBase::emitWillResignActive()\n{\n\tmSignalWillResignActive();\n}\n\nvoid AppBase::emitDidBecomeActive()\n{\n\tmSignalDidBecomeActive();\n}\n\nfs::path AppBase::getOpenFilePath( const fs::path &initialPath, const vector<string> &extensions )\n{\n\treturn Platform::get()->getOpenFilePath( initialPath, extensions );\n}\n\nfs::path AppBase::getFolderPath( const fs::path &initialPath )\n{\n\treturn Platform::get()->getFolderPath( initialPath );\n}\n\nfs::path AppBase::getSaveFilePath( const fs::path &initialPath, const vector<string> &extensions )\n{\n\treturn Platform::get()->getSaveFilePath( initialPath, extensions );\n}\n\nstd::ostream& AppBase::console()\n{\n\treturn Platform::get()->console();\n}\n\nbool AppBase::isPrimaryThread()\n{\n\treturn std::this_thread::get_id() == sPrimaryThreadId;\n}\n\nvoid AppBase::dispatchAsync( const std::function<void()> &fn )\n{\n\tio_service().post( fn );\n}\n\nSurface\tAppBase::copyWindowSurface()\n{\n\treturn getWindow()->getRenderer()->copyWindowSurface( getWindow()->toPixels( getWindow()->getBounds() ) );\n}\n\nSurface\tAppBase::copyWindowSurface( const Area &area )\n{\n\tArea clippedArea = area.getClipBy( getWindowBounds() );\n\treturn getWindow()->getRenderer()->copyWindowSurface( clippedArea );\n}\n\nRendererRef AppBase::findSharedRenderer( RendererRef searchRenderer ) const\n{\n\tif( ! searchRenderer )\n\t\treturn RendererRef();\n\n\tfor( size_t winIdx = 0; winIdx < getNumWindows(); ++winIdx ) {\n\t\tRendererRef thisRenderer = getWindowIndex( winIdx )->getRenderer();\n\t\tif( thisRenderer && (typeid( *thisRenderer ) == typeid(*searchRenderer)) )\n\t\t\treturn getWindowIndex( winIdx )->getRenderer();\n\t}\n\t\n\treturn RendererRef(); \/\/ didn't find one\n}\n\n} } \/\/ namespace cinder::app<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the KDE alarm daemon.\n Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ $Id$\n\n#include <qhbox.h>\n#include <qvbox.h>\n#include <qlabel.h>\n#include <qfile.h>\n#include <qspinbox.h>\n\n#include <klocale.h>\n#include <kprocess.h>\n#include <kaudioplayer.h>\n#include <kdebug.h>\n#include <knotifyclient.h>\n\n#include <libkcal\/event.h>\n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n\nAlarmDialog::AlarmDialog(QWidget *parent,const char *name)\n : KDialogBase(parent,name,false,i18n(\"Alarm\"),Ok|User1,Ok,false,\n i18n(\"Suspend\"))\n{\n QVBox *topBox = new QVBox(this);\n topBox->setSpacing(spacingHint());\n setMainWidget(topBox);\n\n (void)new QLabel(i18n(\"The following events triggered alarms:\"),topBox);\n\n mIncidences.setAutoDelete(true);\n \n mEventViewer = new KOEventViewer(topBox);\n\n QHBox *suspendBox = new QHBox(topBox);\n suspendBox->setSpacing(spacingHint());\n\n (void)new QLabel(i18n(\"Suspend duration (minutes):\"),suspendBox);\n mSuspendSpin = new QSpinBox(1,60,1,suspendBox);\n mSuspendSpin->setValue(5); \/\/ default suspend duration\n\n setMinimumSize(300,200);\n}\n\nAlarmDialog::~AlarmDialog()\n{\n}\n\nvoid AlarmDialog::appendEvent(Event *event)\n{\n mEventViewer->appendEvent(event);\n mIncidences.append(event->clone());\n}\n\nvoid AlarmDialog::appendTodo(Todo *todo)\n{\n mEventViewer->appendTodo(todo);\n mIncidences.append(todo->clone());\n}\n\nvoid AlarmDialog::clearEvents()\n{\n mEventViewer->clearEvents();\n\n mIncidences.clear();\n}\n\nvoid AlarmDialog::slotOk()\n{\n clearEvents();\n accept();\n}\n\nvoid AlarmDialog::slotUser1()\n{\n emit suspendSignal(mSuspendSpin->value());\n accept();\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n\n Incidence *in;\n for (in = mIncidences.first(); in; in = mIncidences.next()) {\n QPtrList<Alarm> alarms = in->alarms();\n const Alarm* alarm;\n for (alarm = alarms.first(); alarm; alarm = alarms.next()) {\n\/\/ TODO: Check whether this should be done for all multiple alarms\n QString program = alarm->programFile();\n if (!program.isEmpty()) {\n kdDebug() << \"Starting program: '\" << program << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n\n if (!alarm->audioFile().isEmpty()) {\n beeped = true;\n KAudioPlayer::play(QFile::encodeName(alarm->audioFile()));\n }\n }\n }\n \n if ( !beeped ) {\n KNotifyClient::beep();\n }\n}\n<commit_msg>disable defaultbutton to prevent the windows being closed accidentally<commit_after>\/*\n This file is part of the KDE alarm daemon.\n Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ $Id$\n\n#include <qhbox.h>\n#include <qvbox.h>\n#include <qlabel.h>\n#include <qfile.h>\n#include <qspinbox.h>\n\n#include <klocale.h>\n#include <kprocess.h>\n#include <kaudioplayer.h>\n#include <kdebug.h>\n#include <knotifyclient.h>\n\n#include <libkcal\/event.h>\n\n#include \"koeventviewer.h\"\n\n#include \"alarmdialog.h\"\n#include \"alarmdialog.moc\"\n\nAlarmDialog::AlarmDialog(QWidget *parent,const char *name)\n : KDialogBase(parent,name,false,i18n(\"Alarm\"),Ok|User1|User2,User2,false,\n i18n(\"Suspend\"))\n{\n QVBox *topBox = new QVBox(this);\n topBox->setSpacing(spacingHint());\n setMainWidget(topBox);\n\n (void)new QLabel(i18n(\"The following events triggered alarms:\"),topBox);\n\n mIncidences.setAutoDelete(true);\n \n mEventViewer = new KOEventViewer(topBox);\n\n QHBox *suspendBox = new QHBox(topBox);\n suspendBox->setSpacing(spacingHint());\n\n (void)new QLabel(i18n(\"Suspend duration (minutes):\"),suspendBox);\n mSuspendSpin = new QSpinBox(1,60,1,suspendBox);\n mSuspendSpin->setValue(5); \/\/ default suspend duration\n \n showButton(User2, false);\n \n setMinimumSize(300,200);\n}\n\nAlarmDialog::~AlarmDialog()\n{\n}\n\nvoid AlarmDialog::appendEvent(Event *event)\n{\n mEventViewer->appendEvent(event);\n mIncidences.append(event->clone());\n}\n\nvoid AlarmDialog::appendTodo(Todo *todo)\n{\n mEventViewer->appendTodo(todo);\n mIncidences.append(todo->clone());\n}\n\nvoid AlarmDialog::clearEvents()\n{\n mEventViewer->clearEvents();\n\n mIncidences.clear();\n}\n\nvoid AlarmDialog::slotOk()\n{\n clearEvents();\n accept();\n}\n\nvoid AlarmDialog::slotUser1()\n{\n emit suspendSignal(mSuspendSpin->value());\n accept();\n}\n\nvoid AlarmDialog::eventNotification()\n{\n bool beeped = false;\n\n Incidence *in;\n for (in = mIncidences.first(); in; in = mIncidences.next()) {\n QPtrList<Alarm> alarms = in->alarms();\n const Alarm* alarm;\n for (alarm = alarms.first(); alarm; alarm = alarms.next()) {\n\/\/ TODO: Check whether this should be done for all multiple alarms\n QString program = alarm->programFile();\n if (!program.isEmpty()) {\n kdDebug() << \"Starting program: '\" << program << \"'\" << endl;\n KProcess proc;\n proc << QFile::encodeName(alarm->programFile());\n proc.start(KProcess::DontCare);\n }\n\n if (!alarm->audioFile().isEmpty()) {\n beeped = true;\n KAudioPlayer::play(QFile::encodeName(alarm->audioFile()));\n }\n }\n }\n \n if ( !beeped ) {\n KNotifyClient::beep();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: ILocalizer.hpp\n * Author: sgaspari\n *\n * Created on November 18, 2015, 12:01 PM\n *\/\n\n#pragma once\n\n#include \"LocalizationResult.hpp\"\n\n#include <openMVG\/image\/image_container.hpp>\n#include <openMVG\/features\/image_describer.hpp>\n#include <openMVG\/cameras\/Camera_Pinhole_Radial.hpp>\n#include <openMVG\/robust_estimation\/robust_estimators.hpp>\n#include <openMVG\/numeric\/numeric.h>\n\nnamespace openMVG {\nnamespace localization {\n\nstruct LocalizerParameters\n{\n LocalizerParameters() :\n _visualDebug(\"\"),\n _refineIntrinsics(false),\n _fDistRatio(0.8),\n _featurePreset(features::EDESCRIBER_PRESET::ULTRA_PRESET),\n _errorMax(std::numeric_limits<double>::infinity()),\n _resectionEstimator(robust::ROBUST_ESTIMATOR_ACRANSAC),\n _matchingEstimator(robust::ROBUST_ESTIMATOR_ACRANSAC),\n _useLocalizeRigNaive(false),\n _angularThreshold(D2R(0.1)) { }\n\n virtual ~LocalizerParameters() = 0;\n\n \/\/\/ enable visual debugging options\n std::string _visualDebug; \n \/\/\/ whether or not the Intrinsics of the query camera has to be refined\n bool _refineIntrinsics;\n \/\/\/ the distance ratio to use when matching feature with the ratio test\n float _fDistRatio;\n \/\/\/ the preset to use for feature extraction of the query image\n features::EDESCRIBER_PRESET _featurePreset;\n \/\/\/ maximum reprojection error allowed for resectioning\n double _errorMax;\n \/\/\/ the type of *sac framework to use for resection\n robust::EROBUST_ESTIMATOR _resectionEstimator;\n \/\/\/ the type of *sac framework to use for matching\n robust::EROBUST_ESTIMATOR _matchingEstimator; \t\n \/\/\/ force the use of the rig localization without openGV\n bool _useLocalizeRigNaive;\n \/\/\/ in rad, it is the maximum angular error for the opengv rig resection\n double _angularThreshold; \n};\n\ninline LocalizerParameters::~LocalizerParameters() {}\n\nusing OccurenceKey = IndMatch3D2D;\nusing OccurenceMap = std::map<OccurenceKey, std::size_t>;\n\nclass ILocalizer\n{\npublic:\n ILocalizer() : _isInit(false) { };\n\n \/\/ Only relevant for CCTagLocalizer\n virtual void setCudaPipe(int) { }\n \n bool isInit() {return _isInit;}\n \n const sfm::SfM_Data& getSfMData() const {return _sfm_data; }\n \n \/**\n * @brief Localize one image\n * \n * @param[in] imageGrey The input greyscale image.\n * @param[in] param The parameters for the localization.\n * @param[in] useInputIntrinsics Uses the \\p queryIntrinsics as known calibration.\n * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the\n * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.\n * @param[out] localizationResult The localization result containing the pose and the associations.\n * @param[in] imagePath Optional complete path to the image, used only for debugging purposes.\n * @return true if the image has been successfully localized.\n *\/\n virtual bool localize(const image::Image<unsigned char> & imageGrey,\n const LocalizerParameters *param,\n bool useInputIntrinsics,\n cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,\n LocalizationResult & localizationResult,\n const std::string& imagePath = std::string()) = 0;\n\n virtual bool localize(const features::MapRegionsPerDesc &queryRegions,\n const std::pair<std::size_t, std::size_t> &imageSize,\n const LocalizerParameters *param,\n bool useInputIntrinsics,\n cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,\n LocalizationResult & localizationResult,\n const std::string& imagePath = std::string()) = 0;\n \n virtual bool localizeRig(const std::vector<image::Image<unsigned char> > & vec_imageGrey,\n const LocalizerParameters *param,\n std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics,\n const std::vector<geometry::Pose3 > &vec_subPoses,\n geometry::Pose3 &rigPose, \n std::vector<LocalizationResult>& vec_locResults)=0;\n \n virtual bool localizeRig(const std::vector<features::MapRegionsPerDesc> & vec_queryRegions,\n const std::vector<std::pair<std::size_t, std::size_t> > &imageSize,\n const LocalizerParameters *param,\n std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics,\n const std::vector<geometry::Pose3 > &vec_subPoses,\n geometry::Pose3 &rigPose,\n std::vector<LocalizationResult>& vec_locResults)=0;\n \n virtual ~ILocalizer( ) {}\n\nprotected:\n bool _isInit;\n sfm::SfM_Data _sfm_data;\n\n};\n\n} \/\/namespace openMVG \n} \/\/namespace localization \n\n<commit_msg>[localization] Add 'const' for ILocalizer 'isInit' method<commit_after>\/* \n * File: ILocalizer.hpp\n * Author: sgaspari\n *\n * Created on November 18, 2015, 12:01 PM\n *\/\n\n#pragma once\n\n#include \"LocalizationResult.hpp\"\n\n#include <openMVG\/image\/image_container.hpp>\n#include <openMVG\/features\/image_describer.hpp>\n#include <openMVG\/cameras\/Camera_Pinhole_Radial.hpp>\n#include <openMVG\/robust_estimation\/robust_estimators.hpp>\n#include <openMVG\/numeric\/numeric.h>\n\nnamespace openMVG {\nnamespace localization {\n\nstruct LocalizerParameters\n{\n LocalizerParameters() :\n _visualDebug(\"\"),\n _refineIntrinsics(false),\n _fDistRatio(0.8),\n _featurePreset(features::EDESCRIBER_PRESET::ULTRA_PRESET),\n _errorMax(std::numeric_limits<double>::infinity()),\n _resectionEstimator(robust::ROBUST_ESTIMATOR_ACRANSAC),\n _matchingEstimator(robust::ROBUST_ESTIMATOR_ACRANSAC),\n _useLocalizeRigNaive(false),\n _angularThreshold(D2R(0.1)) { }\n\n virtual ~LocalizerParameters() = 0;\n\n \/\/\/ enable visual debugging options\n std::string _visualDebug; \n \/\/\/ whether or not the Intrinsics of the query camera has to be refined\n bool _refineIntrinsics;\n \/\/\/ the distance ratio to use when matching feature with the ratio test\n float _fDistRatio;\n \/\/\/ the preset to use for feature extraction of the query image\n features::EDESCRIBER_PRESET _featurePreset;\n \/\/\/ maximum reprojection error allowed for resectioning\n double _errorMax;\n \/\/\/ the type of *sac framework to use for resection\n robust::EROBUST_ESTIMATOR _resectionEstimator;\n \/\/\/ the type of *sac framework to use for matching\n robust::EROBUST_ESTIMATOR _matchingEstimator; \t\n \/\/\/ force the use of the rig localization without openGV\n bool _useLocalizeRigNaive;\n \/\/\/ in rad, it is the maximum angular error for the opengv rig resection\n double _angularThreshold; \n};\n\ninline LocalizerParameters::~LocalizerParameters() {}\n\nusing OccurenceKey = IndMatch3D2D;\nusing OccurenceMap = std::map<OccurenceKey, std::size_t>;\n\nclass ILocalizer\n{\npublic:\n ILocalizer() : _isInit(false) { };\n\n \/\/ Only relevant for CCTagLocalizer\n virtual void setCudaPipe(int) { }\n \n bool isInit() const {return _isInit;}\n \n const sfm::SfM_Data& getSfMData() const {return _sfm_data; }\n \n \/**\n * @brief Localize one image\n * \n * @param[in] imageGrey The input greyscale image.\n * @param[in] param The parameters for the localization.\n * @param[in] useInputIntrinsics Uses the \\p queryIntrinsics as known calibration.\n * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the\n * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.\n * @param[out] localizationResult The localization result containing the pose and the associations.\n * @param[in] imagePath Optional complete path to the image, used only for debugging purposes.\n * @return true if the image has been successfully localized.\n *\/\n virtual bool localize(const image::Image<unsigned char> & imageGrey,\n const LocalizerParameters *param,\n bool useInputIntrinsics,\n cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,\n LocalizationResult & localizationResult,\n const std::string& imagePath = std::string()) = 0;\n\n virtual bool localize(const features::MapRegionsPerDesc &queryRegions,\n const std::pair<std::size_t, std::size_t> &imageSize,\n const LocalizerParameters *param,\n bool useInputIntrinsics,\n cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,\n LocalizationResult & localizationResult,\n const std::string& imagePath = std::string()) = 0;\n \n virtual bool localizeRig(const std::vector<image::Image<unsigned char> > & vec_imageGrey,\n const LocalizerParameters *param,\n std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics,\n const std::vector<geometry::Pose3 > &vec_subPoses,\n geometry::Pose3 &rigPose, \n std::vector<LocalizationResult>& vec_locResults)=0;\n \n virtual bool localizeRig(const std::vector<features::MapRegionsPerDesc> & vec_queryRegions,\n const std::vector<std::pair<std::size_t, std::size_t> > &imageSize,\n const LocalizerParameters *param,\n std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics,\n const std::vector<geometry::Pose3 > &vec_subPoses,\n geometry::Pose3 &rigPose,\n std::vector<LocalizationResult>& vec_locResults)=0;\n \n virtual ~ILocalizer( ) {}\n\nprotected:\n bool _isInit;\n sfm::SfM_Data _sfm_data;\n\n};\n\n} \/\/namespace openMVG \n} \/\/namespace localization \n\n<|endoftext|>"} {"text":"<commit_before>#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <cmath> \/\/ std::pow\n\npass::parallel_swarm_search::parallel_swarm_search() noexcept\n : optimiser(\"Parallel_Swarm_Search\"),\n swarm_size(40),\n inertia(1.0 \/ (2.0 * std::log(2.0))),\n cognitive_acceleration(0.5 + std::log(2.0)),\n social_acceleration(cognitive_acceleration),\n neighbourhood_probability(1.0 -\n std::pow(1.0 - 1.0 \/ static_cast<double>(swarm_size), 3.0)),\n number_threads(pass::number_of_threads())\n#if defined(SUPPORT_MPI)\n ,\n migration_stall(0)\n#endif\n{\n}\n\npass::optimise_result pass::parallel_swarm_search::optimise(\n const pass::problem &problem)\n{\n assert(inertia >= -1.0 && inertia <= 1.0 && \"'inertia' should be greater or equal than 0.0\");\n assert(cognitive_acceleration >= 0.0 && \"'cognitive_acceleration' should be greater or equal than 0.0\");\n assert(social_acceleration >= 0.0 && \"'social_acceleration' should be greater or equal than 0.0\");\n assert(neighbourhood_probability > 0.0 && neighbourhood_probability <= 1.0 &&\n \"'neighbourhood_probability' should be a value between 0.0 and 1.0\");\n assert(swarm_size > 0 && \"Can't generate 0 agents\");\n assert(number_threads > 0 && \"The number of threads should be greater than 0\");\n#if defined(SUPPORT_MPI)\n assert(migration_stall >= 0 && \"The number of threads should be greater or equal than 0\");\n#endif\n\n \/\/ Variables used to analyse the behavior of a particle\n arma::mat verbose(maximal_iterations + 1, 3);\n\n pass::stopwatch stopwatch;\n stopwatch.start();\n\n \/\/ Restart variabel\n arma::uword same_value = 0;\n\n \/\/ Variables needed\n pass::optimise_result result(problem, acceptable_fitness_value);\n\n arma::mat positions;\n arma::mat velocities(problem.dimension(), swarm_size);\n\n arma::mat personal_best_positions;\n arma::rowvec personal_best_fitness_values(swarm_size);\n\n arma::umat topology(swarm_size, swarm_size);\n\n arma::vec local_best_position;\n double local_best_fitness_value;\n\n arma::vec attraction_center;\n arma::vec weighted_personal_attraction;\n arma::vec weighted_local_attraction;\n\n double fitness_value;\n\nrestart: \/\/ Restart point\n\n \/\/ Initialise the positions and the velocities\n \/\/ Particle data, stored column-wise.\n if (result.iterations == 0)\n {\n positions = problem.normalised_hammersley_agents(swarm_size);\n }\n else\n {\n positions = problem.initialise_normalised_agents(swarm_size);\n }\n\n for (arma::uword col = 0; col < swarm_size; ++col)\n {\n for (arma::uword row = 0; row < problem.dimension(); ++row)\n {\n velocities(row, col) = random_double_uniform_in_range(\n 0.0 - positions(row, col),\n 1.0 - positions(row, col));\n }\n }\n\n personal_best_positions = positions;\n\n \/\/ Evaluate the initial positions.\n \/\/ Compute the fitness.\n \/\/ Begin with the previous best set to this initial position\n for (arma::uword n = 0; n < swarm_size; ++n)\n {\n fitness_value = problem.evaluate_normalised(positions.col(n));\n personal_best_fitness_values(n) = fitness_value;\n\n if (fitness_value <= result.fitness_value)\n {\n result.normalised_agent = positions.col(n);\n result.fitness_value = fitness_value;\n }\n }\n ++result.iterations;\n\n \/**\n * +------------+---------------+----------+\n * | Iterations | Fitness Value | Position |\n * +------------+---------------+----------+\n * Each Dimension is independent. So, the analysis can be performed\n * on just one dimension\n * NOT VALID FOR Velocity\n *\/\n if (pass::is_verbose)\n {\n if (maximal_iterations != std::numeric_limits<arma::uword>::max() && maximal_iterations > 0)\n {\n verbose(result.iterations, 0) = result.iterations;\n verbose(result.iterations, 1) = result.fitness_value;\n verbose(result.iterations, 2) = result.normalised_agent[0];\n }\n else\n {\n throw std::runtime_error(\n \"Please set - maximal_iterations - to a valid number to analyse the behaviour of the algorithm.\");\n }\n }\n \/\/end initialisation\n\n bool randomize_topology = true;\n\n \/\/ termination criteria.\n while (stopwatch.get_elapsed() < maximal_duration &&\n result.iterations < maximal_iterations && result.evaluations < maximal_evaluations && !result.solved())\n {\n if (randomize_topology)\n {\n topology = (arma::mat(swarm_size, swarm_size,\n arma::fill::randu) < neighbourhood_probability);\n \/\/ When searching for the best neighbour, we begin with the particles\n \/\/ personal best value; We don't need to visit it twice.\n topology.diag().fill(0);\n }\n randomize_topology = true;\n\n#if defined(SUPPORT_MPI)\n for (arma::uword ms = 0; ms <= migration_stall; ++ms)\n {\n#endif\n\n#if defined(SUPPORT_OPENMP)\n#pragma omp parallel proc_bind(close) num_threads(number_threads)\n { \/\/parallel region start\n#pragma omp for private(local_best_position, local_best_fitness_value, attraction_center, weighted_personal_attraction, weighted_local_attraction, fitness_value) firstprivate(topology) schedule(static)\n#endif\n\n \/\/ iterate over the particles\n for (arma::uword n = 0; n < swarm_size; ++n)\n {\n \/\/ l_i^t\n local_best_position = personal_best_positions.col(n);\n local_best_fitness_value = personal_best_fitness_values(n);\n\n \/\/ check the topology to identify with which particle you communicate\n for (arma::uword i = 0; i < swarm_size; i++)\n {\n if (topology(n, i) && personal_best_fitness_values(i) < local_best_fitness_value)\n {\n local_best_fitness_value = personal_best_fitness_values(i);\n local_best_position = personal_best_positions.col(i);\n }\n }\n\n \/\/p_i\n weighted_personal_attraction = positions.col(n) +\n random_double_uniform_in_range(0.0, cognitive_acceleration) *\n (personal_best_positions.col(n) - positions.col(n));\n\n \/\/ l_i\n weighted_local_attraction = positions.col(n) +\n random_double_uniform_in_range(0.0, social_acceleration) *\n (local_best_position - positions.col(n));\n\n \/\/ If the best informant is the particle itself, define the gravity center G as the middle of x-p'\n if (personal_best_fitness_values(n) == local_best_fitness_value)\n {\n attraction_center = 0.5 * (positions.col(n) + weighted_personal_attraction);\n }\n else\n {\n attraction_center = (positions.col(n) + weighted_personal_attraction + weighted_local_attraction) \/ 3.0;\n }\n\n velocities.col(n) = inertia * velocities.col(n) +\n random_neighbour(attraction_center, 0.0, arma::norm(attraction_center - positions.col(n))) -\n positions.col(n);\n\n \/\/ move by applying this new velocity to the current position\n positions.col(n) = positions.col(n) + velocities.col(n);\n\n \/\/ stay inside the bounds\n for (arma::uword k = 0; k < problem.dimension(); ++k)\n {\n if (positions(k, n) < 0)\n {\n positions(k, n) = 0;\n velocities(k, n) = -0.5 * velocities(k, n);\n }\n else if (positions(k, n) > 1)\n {\n positions(k, n) = 1;\n velocities(k, n) = -0.5 * velocities(k, n);\n }\n }\n\n \/\/ evaluate the new position\n fitness_value = problem.evaluate_normalised(positions.col(n));\n\n if (fitness_value < personal_best_fitness_values(n))\n {\n personal_best_positions.col(n) = positions.col(n);\n personal_best_fitness_values(n) = fitness_value;\n\n#if defined(SUPPORT_OPENMP)\n#pragma omp critical\n { \/\/ critical region start\n#endif\n \/\/ Restart criteria\n if (result.fitness_value - fitness_value > pass::precision)\n {\n result.normalised_agent = positions.col(n);\n result.fitness_value = fitness_value;\n randomize_topology = false;\n same_value = 0;\n }\n else\n {\n same_value++;\n }\n\n#if defined(SUPPORT_OPENMP)\n } \/\/ crititcal region end\n#endif\n }\n }\n#if defined(SUPPORT_OPENMP)\n } \/\/parallel region end\n#endif\n\n ++result.iterations;\n result.evaluations = result.iterations * swarm_size;\n\n#if defined(SUPPORT_MPI)\n if (stopwatch.get_elapsed() > maximal_duration ||\n result.iterations >= maximal_iterations || result.evaluations >= maximal_evaluations || result.solved())\n {\n break;\n }\n } \/\/ end migration stall\n#endif\n\n#if defined(SUPPORT_MPI)\n \/\/ Island model for PSO\n struct\n {\n double fitness_value;\n int best_rank;\n } mpi;\n\n mpi.best_rank = pass::node_rank();\n mpi.fitness_value = result.fitness_value;\n\n \/**\n * All Reduce returns the minimum value of Fitness_value and the rank of the process that owns it.\n *\/\n MPI_Allreduce(MPI_IN_PLACE, &mpi, 1, MPI_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD);\n\n \/**\n * The rank with the minimum Fitness_value broadcast his agent to the others\n *\/\n MPI_Bcast(result.normalised_agent.memptr(), result.normalised_agent.n_elem, MPI_DOUBLE, mpi.best_rank, MPI_COMM_WORLD);\n\n result.fitness_value = mpi.fitness_value;\n\n if (pass::node_rank() != mpi.best_rank)\n {\n \/\/ Find the worst agent and replace it with the best one\n arma::uword min_index = personal_best_fitness_values.index_min();\n\n personal_best_positions.col(min_index) = result.normalised_agent;\n positions.col(min_index) = result.normalised_agent;\n personal_best_fitness_values(min_index) = result.fitness_value;\n }\n#endif\n\n \/**\n * Restart the algorithm\n * If the algorithm does not found a better fitness value within 3000 iterations, it restarts.\n * Precision for a better fitness value is 1-e06\n * If it is restarted then choose random through hammersley or random initialisation\n *\/\n if (same_value >= 3000)\n {\n same_value = 0;\n goto restart;\n }\n\n \/**\n * +------------+---------------+----------+\n * | Iterations | Fitness Value | Position |\n * +------------+---------------+----------+\n * Each Dimension is independent. So, the analysis can be performed\n * on just one dimension\n * NOT VALID FOR Velocity\n *\/\n if (pass::is_verbose)\n {\n verbose(result.iterations, 0) = result.iterations;\n verbose(result.iterations, 1) = result.fitness_value;\n verbose(result.iterations, 2) = result.normalised_agent[0];\n }\n } \/\/ end while for termination criteria\n\n result.duration = stopwatch.get_elapsed();\n\n \/\/ Save the file\n if (pass::is_verbose)\n {\n verbose.shed_row(0);\n verbose.save(\"Verbose_Optimiser_\" + name + \"_Problem_\" + problem.name + \"_Dim_\" +\n std::to_string(problem.dimension()) +\n \"_Run_\" + std::to_string(pass::global_number_of_runs),\n arma::raw_ascii);\n }\n\n return result;\n}\n<commit_msg>bug fix<commit_after>#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <cmath> \/\/ std::pow\n\npass::parallel_swarm_search::parallel_swarm_search() noexcept\n : optimiser(\"Parallel_Swarm_Search\"),\n swarm_size(40),\n inertia(1.0 \/ (2.0 * std::log(2.0))),\n cognitive_acceleration(0.5 + std::log(2.0)),\n social_acceleration(cognitive_acceleration),\n neighbourhood_probability(1.0 -\n std::pow(1.0 - 1.0 \/ static_cast<double>(swarm_size), 3.0)),\n number_threads(pass::number_of_threads())\n#if defined(SUPPORT_MPI)\n ,\n migration_stall(0)\n#endif\n{\n}\n\npass::optimise_result pass::parallel_swarm_search::optimise(\n const pass::problem &problem)\n{\n assert(inertia >= -1.0 && inertia <= 1.0 && \"'inertia' should be greater or equal than 0.0\");\n assert(cognitive_acceleration >= 0.0 && \"'cognitive_acceleration' should be greater or equal than 0.0\");\n assert(social_acceleration >= 0.0 && \"'social_acceleration' should be greater or equal than 0.0\");\n assert(neighbourhood_probability > 0.0 && neighbourhood_probability <= 1.0 &&\n \"'neighbourhood_probability' should be a value between 0.0 and 1.0\");\n assert(swarm_size > 0 && \"Can't generate 0 agents\");\n assert(number_threads > 0 && \"The number of threads should be greater than 0\");\n#if defined(SUPPORT_MPI)\n assert(migration_stall >= 0 && \"The number of threads should be greater or equal than 0\");\n#endif\n\n \/\/ Variables used to analyse the behavior of a particle\n arma::mat verbose(maximal_iterations + 1, 3);\n\n pass::stopwatch stopwatch;\n stopwatch.start();\n\n \/\/ Restart variabel\n arma::uword same_value = 0;\n\n \/\/ Variables needed\n pass::optimise_result result(problem, acceptable_fitness_value);\n\n arma::mat positions;\n arma::mat velocities(problem.dimension(), swarm_size);\n\n arma::mat personal_best_positions;\n arma::rowvec personal_best_fitness_values(swarm_size);\n\n arma::umat topology(swarm_size, swarm_size);\n\n arma::vec local_best_position;\n double local_best_fitness_value;\n\n arma::vec attraction_center;\n arma::vec weighted_personal_attraction;\n arma::vec weighted_local_attraction;\n\n double fitness_value;\n\nrestart: \/\/ Restart point\n\n \/\/ Initialise the positions and the velocities\n \/\/ Particle data, stored column-wise.\n if (result.iterations == 0)\n {\n positions = problem.normalised_hammersley_agents(swarm_size);\n }\n else\n {\n positions = problem.initialise_normalised_agents(swarm_size);\n }\n\n for (arma::uword col = 0; col < swarm_size; ++col)\n {\n for (arma::uword row = 0; row < problem.dimension(); ++row)\n {\n velocities(row, col) = random_double_uniform_in_range(\n 0.0 - positions(row, col),\n 1.0 - positions(row, col));\n }\n }\n\n personal_best_positions = positions;\n\n \/\/ Evaluate the initial positions.\n \/\/ Compute the fitness.\n \/\/ Begin with the previous best set to this initial position\n for (arma::uword n = 0; n < swarm_size; ++n)\n {\n fitness_value = problem.evaluate_normalised(positions.col(n));\n personal_best_fitness_values(n) = fitness_value;\n\n if (fitness_value <= result.fitness_value)\n {\n result.normalised_agent = positions.col(n);\n result.fitness_value = fitness_value;\n }\n }\n ++result.iterations;\n\n \/**\n * +------------+---------------+----------+\n * | Iterations | Fitness Value | Position |\n * +------------+---------------+----------+\n * Each Dimension is independent. So, the analysis can be performed\n * on just one dimension\n * NOT VALID FOR Velocity\n *\/\n if (pass::is_verbose)\n {\n if (maximal_iterations != std::numeric_limits<arma::uword>::max() && maximal_iterations > 0)\n {\n verbose(result.iterations, 0) = result.iterations;\n verbose(result.iterations, 1) = result.fitness_value;\n verbose(result.iterations, 2) = result.normalised_agent[0];\n }\n else\n {\n throw std::runtime_error(\n \"Please set - maximal_iterations - to a valid number to analyse the behaviour of the algorithm.\");\n }\n }\n \/\/end initialisation\n\n bool randomize_topology = true;\n\n \/\/ termination criteria.\n while (stopwatch.get_elapsed() < maximal_duration &&\n result.iterations < maximal_iterations && result.evaluations < maximal_evaluations && !result.solved())\n {\n if (randomize_topology)\n {\n topology = (arma::mat(swarm_size, swarm_size,\n arma::fill::randu) < neighbourhood_probability);\n \/\/ When searching for the best neighbour, we begin with the particles\n \/\/ personal best value; We don't need to visit it twice.\n topology.diag().fill(0);\n }\n randomize_topology = true;\n\n#if defined(SUPPORT_MPI)\n for (arma::uword ms = 0; ms <= migration_stall; ++ms)\n {\n#endif\n\n#if defined(SUPPORT_OPENMP)\n#pragma omp parallel proc_bind(close) num_threads(number_threads)\n { \/\/parallel region start\n#pragma omp for private(local_best_position, local_best_fitness_value, attraction_center, weighted_personal_attraction, weighted_local_attraction, fitness_value) firstprivate(topology) schedule(static)\n#endif\n\n \/\/ iterate over the particles\n for (arma::uword n = 0; n < swarm_size; ++n)\n {\n \/\/ l_i^t\n local_best_position = personal_best_positions.col(n);\n local_best_fitness_value = personal_best_fitness_values(n);\n\n \/\/ check the topology to identify with which particle you communicate\n for (arma::uword i = 0; i < swarm_size; i++)\n {\n if (topology(n, i) && personal_best_fitness_values(i) < local_best_fitness_value)\n {\n local_best_fitness_value = personal_best_fitness_values(i);\n local_best_position = personal_best_positions.col(i);\n }\n }\n\n \/**\n * Compute the new velocity\n * If OpenMP is activated, make sure the random numbers are thread safe\n *\/\n#if defined(SUPPORT_OPENMP)\n arma::arma_rng::set_seed_random();\n#endif\n\n \/\/p_i\n weighted_personal_attraction = positions.col(n) +\n random_double_uniform_in_range(0.0, cognitive_acceleration) *\n (personal_best_positions.col(n) - positions.col(n));\n\n \/\/ l_i\n weighted_local_attraction = positions.col(n) +\n random_double_uniform_in_range(0.0, social_acceleration) *\n (local_best_position - positions.col(n));\n\n \/\/ If the best informant is the particle itself, define the gravity center G as the middle of x-p'\n if (personal_best_fitness_values(n) == local_best_fitness_value)\n {\n attraction_center = 0.5 * (positions.col(n) + weighted_personal_attraction);\n }\n else\n {\n attraction_center = (positions.col(n) + weighted_personal_attraction + weighted_local_attraction) \/ 3.0;\n }\n\n velocities.col(n) = inertia * velocities.col(n) +\n random_neighbour(attraction_center, 0.0, arma::norm(attraction_center - positions.col(n))) -\n positions.col(n);\n\n \/\/ move by applying this new velocity to the current position\n positions.col(n) = positions.col(n) + velocities.col(n);\n\n \/\/ stay inside the bounds\n for (arma::uword k = 0; k < problem.dimension(); ++k)\n {\n if (positions(k, n) < 0)\n {\n positions(k, n) = 0;\n velocities(k, n) = -0.5 * velocities(k, n);\n }\n else if (positions(k, n) > 1)\n {\n positions(k, n) = 1;\n velocities(k, n) = -0.5 * velocities(k, n);\n }\n }\n\n \/\/ evaluate the new position\n fitness_value = problem.evaluate_normalised(positions.col(n));\n\n if (fitness_value < personal_best_fitness_values(n))\n {\n personal_best_positions.col(n) = positions.col(n);\n personal_best_fitness_values(n) = fitness_value;\n\n#if defined(SUPPORT_OPENMP)\n#pragma omp critical\n { \/\/ critical region start\n#endif\n \/\/ Restart criteria\n if (result.fitness_value - fitness_value > pass::precision)\n {\n result.normalised_agent = positions.col(n);\n result.fitness_value = fitness_value;\n randomize_topology = false;\n same_value = 0;\n }\n else\n {\n same_value++;\n }\n\n#if defined(SUPPORT_OPENMP)\n } \/\/ crititcal region end\n#endif\n }\n }\n#if defined(SUPPORT_OPENMP)\n } \/\/parallel region end\n#endif\n\n ++result.iterations;\n result.evaluations = result.iterations * swarm_size;\n\n#if defined(SUPPORT_MPI)\n if (stopwatch.get_elapsed() > maximal_duration ||\n result.iterations >= maximal_iterations || result.evaluations >= maximal_evaluations || result.solved())\n {\n break;\n }\n } \/\/ end migration stall\n#endif\n\n#if defined(SUPPORT_MPI)\n \/\/ Island model for PSO\n struct\n {\n double fitness_value;\n int best_rank;\n } mpi;\n\n mpi.best_rank = pass::node_rank();\n mpi.fitness_value = result.fitness_value;\n\n \/**\n * All Reduce returns the minimum value of Fitness_value and the rank of the process that owns it.\n *\/\n MPI_Allreduce(MPI_IN_PLACE, &mpi, 1, MPI_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD);\n\n \/**\n * The rank with the minimum Fitness_value broadcast his agent to the others\n *\/\n MPI_Bcast(result.normalised_agent.memptr(), result.normalised_agent.n_elem, MPI_DOUBLE, mpi.best_rank, MPI_COMM_WORLD);\n\n result.fitness_value = mpi.fitness_value;\n\n if (pass::node_rank() != mpi.best_rank)\n {\n \/\/ Find the worst agent and replace it with the best one\n arma::uword min_index = personal_best_fitness_values.index_min();\n\n personal_best_positions.col(min_index) = result.normalised_agent;\n positions.col(min_index) = result.normalised_agent;\n personal_best_fitness_values(min_index) = result.fitness_value;\n }\n#endif\n\n \/**\n * Restart the algorithm\n * If the algorithm does not found a better fitness value within 3000 iterations, it restarts.\n * Precision for a better fitness value is 1-e06\n * If it is restarted then choose random through hammersley or random initialisation\n *\/\n if (same_value >= 3000)\n {\n same_value = 0;\n goto restart;\n }\n\n \/**\n * +------------+---------------+----------+\n * | Iterations | Fitness Value | Position |\n * +------------+---------------+----------+\n * Each Dimension is independent. So, the analysis can be performed\n * on just one dimension\n * NOT VALID FOR Velocity\n *\/\n if (pass::is_verbose)\n {\n verbose(result.iterations, 0) = result.iterations;\n verbose(result.iterations, 1) = result.fitness_value;\n verbose(result.iterations, 2) = result.normalised_agent[0];\n }\n } \/\/ end while for termination criteria\n\n result.duration = stopwatch.get_elapsed();\n\n \/\/ Save the file\n if (pass::is_verbose)\n {\n verbose.shed_row(0);\n verbose.save(\"Verbose_Optimiser_\" + name + \"_Problem_\" + problem.name + \"_Dim_\" +\n std::to_string(problem.dimension()) +\n \"_Run_\" + std::to_string(pass::global_number_of_runs),\n arma::raw_ascii);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"prog_translator.h\"\n\n#include <algorithm>\n\n#include \"CoinPackedVector.hpp\"\n#include \"OsiSolverInterface.hpp\"\n\n#include \"cyc_limits.h\"\n#include \"error.h\"\n#include \"exchange_graph.h\"\n#include \"exchange_solver.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface)\n : g_(g),\n iface_(iface),\n excl_(false),\n pseudo_cost_(std::numeric_limits<double>::max()) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n bool exclusive)\n : g_(g),\n iface_(iface),\n excl_(exclusive),\n pseudo_cost_(std::numeric_limits<double>::max()) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n double pseudo_cost)\n : g_(g),\n iface_(iface),\n excl_(false),\n pseudo_cost_(pseudo_cost) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n bool exclusive, double pseudo_cost)\n : g_(g),\n iface_(iface),\n excl_(exclusive),\n pseudo_cost_(pseudo_cost) {\n Init();\n}\n\nvoid ProgTranslator::Init() {\n arc_offset_ = g_->arcs().size();\n int n_cols = arc_offset_ + g_->request_groups().size();\n ctx_.obj_coeffs.resize(n_cols);\n ctx_.col_ubs.resize(n_cols);\n ctx_.col_lbs.resize(n_cols);\n ctx_.m = CoinPackedMatrix(false, 0, 0);\n}\n\nvoid ProgTranslator::CheckPref(double pref) {\n if (pref <= 0) {\n std::stringstream ss;\n ss << \"Preference value found to be nonpositive (\" << pref\n << \"). Preferences must be positive when using an optimization solver.\"\n << \" If using Cyclus in simulation mode (e.g., from the command line),\"\n << \" this error is likely a bug in Cyclus. Please report it to the developer's \"\n << \"list (https:\/\/groups.google.com\/forum\/#!forum\/cyclus-dev).\";\n throw ValueError(ss.str());\n }\n}\n\nvoid ProgTranslator::Translate() {\n \/\/ number of variables = number of arcs + 1 faux arc per request group with arcs\n int nfalse = 0;\n std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();\n for (int i = 0; i != g_->request_groups().size(); ++i)\n nfalse += rgs[i].get()->HasArcs() ? 1 : 0;\n int n_cols = g_->arcs().size() + nfalse;\n ctx_.m.setDimensions(0, n_cols);\n\n bool request;\n std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();\n for (int i = 0; i != sgs.size(); i++) {\n request = false;\n XlateGrp_(sgs[i].get(), request);\n }\n\n for (int i = 0; i != rgs.size(); i++) {\n request = true;\n XlateGrp_(rgs[i].get(), request);\n }\n\n \/\/ add each false arc\n CLOG(LEV_DEBUG1) << \"Adding \" << arc_offset_ - g_->arcs().size()\n << \" false arcs.\";\n double inf = iface_->getInfinity();\n for (int i = g_->arcs().size(); i != arc_offset_; i++) {\n ctx_.obj_coeffs[i] = pseudo_cost_;\n ctx_.col_lbs[i] = 0;\n ctx_.col_ubs[i] = inf;\n }\n}\n\nvoid ProgTranslator::Populate() {\n iface_->setObjSense(1.0); \/\/ minimize\n\n \/\/ load er up!\n iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],\n &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);\n\n \n if (excl_) {\n std::vector<Arc>& arcs = g_->arcs();\n for (int i = 0; i != arcs.size(); i++) {\n Arc& a = arcs[i];\n if (a.exclusive()) {\n iface_->setInteger(g_->arc_ids()[a]);\n }\n }\n }\n\n}\n\nvoid ProgTranslator::ToProg() {\n Translate();\n Populate();\n}\n\nvoid ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {\n double inf = iface_->getInfinity();\n std::vector<double>& caps = grp->capacities();\n\n if (request && !grp->HasArcs())\n return; \/\/ no arcs, no reason to add variables\/constraints\n \n std::vector<CoinPackedVector> cap_rows;\n std::vector<CoinPackedVector> excl_rows;\n for (int i = 0; i != caps.size(); i++) {\n cap_rows.push_back(CoinPackedVector());\n }\n\n std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();\n for (int i = 0; i != nodes.size(); i++) {\n std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;\n std::map<Arc, std::vector<double> >::iterator cap_it;\n\n \/\/ add each arc\n for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {\n const Arc& a = cap_it->first;\n std::vector<double>& ucaps = cap_it->second;\n int arc_id = g_->arc_ids()[a];\n\n \/\/ add each unit capacity coefficient\n for (int j = 0; j != ucaps.size(); j++) {\n double coeff = ucaps[j];\n if (excl_ && a.exclusive()) {\n coeff *= a.excl_val();\n }\n\n cap_rows[j].insert(arc_id, coeff);\n }\n\n if (request) {\n CheckPref(a.pref());\n ctx_.obj_coeffs[arc_id] = ExchangeSolver::Cost(a, excl_);\n ctx_.col_lbs[arc_id] = 0;\n ctx_.col_ubs[arc_id] = (excl_ && a.exclusive()) ? 1 :\n std::min(nodes[i]->qty, inf);\n }\n }\n }\n\n int faux_id;\n if (request) {\n faux_id = arc_offset_++;\n }\n\n \/\/ add all capacity rows\n for (int i = 0; i != cap_rows.size(); i++) {\n if (request) {\n cap_rows[i].insert(faux_id, 1.0); \/\/ faux arc\n }\n\n \/\/ 1e15 is the largest value that doesn't make the solver fall over\n \/\/ (by emperical testing)\n double rlb = std::min(caps[i], 1e15); \n ctx_.row_lbs.push_back(request ? rlb : 0);\n ctx_.row_ubs.push_back(request ? inf : caps[i]);\n ctx_.m.appendRow(cap_rows[i]);\n }\n\n if (excl_) {\n \/\/ add exclusive arcs\n std::vector< std::vector<ExchangeNode::Ptr> >& exngs =\n grp->excl_node_groups();\n for (int i = 0; i != exngs.size(); i++) {\n CoinPackedVector excl_row;\n std::vector<ExchangeNode::Ptr>& nodes = exngs[i];\n for (int j = 0; j != nodes.size(); j++) {\n std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];\n for (int k = 0; k != arcs.size(); k++) {\n excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);\n }\n }\n if (excl_row.getNumElements() > 0) {\n excl_rows.push_back(excl_row);\n }\n }\n\n \/\/ add all exclusive rows\n for (int i = 0; i != excl_rows.size(); i++) {\n ctx_.row_lbs.push_back(0.0);\n ctx_.row_ubs.push_back(1.0);\n ctx_.m.appendRow(excl_rows[i]);\n }\n }\n}\n\nvoid ProgTranslator::FromProg() {\n const double* sol = iface_->getColSolution();\n std::vector<Arc>& arcs = g_->arcs();\n double flow;\n for (int i = 0; i < arcs.size(); i++) {\n Arc& a = g_->arc_by_id().at(i);\n flow = sol[i];\n flow = (excl_ && a.exclusive()) ? flow * a.excl_val() : flow;\n if (flow > cyclus::eps()) {\n g_->AddMatch(a, flow);\n }\n }\n}\n\nProgTranslator::Context::Context() {\n throw DepricatedApiError(\"Class ProgTranslator::Context is not deprecated in favor of ProgTranslatorContext.\");\n}\n\nProgTranslator::Context::~Context() {\n throw DepricatedApiError(\"Class ProgTranslator::Context is not deprecated in favor of ProgTranslatorContext.\");\n}\n\n\n} \/\/ namespace cyclus\n<commit_msg>Fix typo that reverses meaning of error message.<commit_after>#include \"prog_translator.h\"\n\n#include <algorithm>\n\n#include \"CoinPackedVector.hpp\"\n#include \"OsiSolverInterface.hpp\"\n\n#include \"cyc_limits.h\"\n#include \"error.h\"\n#include \"exchange_graph.h\"\n#include \"exchange_solver.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface)\n : g_(g),\n iface_(iface),\n excl_(false),\n pseudo_cost_(std::numeric_limits<double>::max()) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n bool exclusive)\n : g_(g),\n iface_(iface),\n excl_(exclusive),\n pseudo_cost_(std::numeric_limits<double>::max()) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n double pseudo_cost)\n : g_(g),\n iface_(iface),\n excl_(false),\n pseudo_cost_(pseudo_cost) {\n Init();\n}\n\nProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,\n bool exclusive, double pseudo_cost)\n : g_(g),\n iface_(iface),\n excl_(exclusive),\n pseudo_cost_(pseudo_cost) {\n Init();\n}\n\nvoid ProgTranslator::Init() {\n arc_offset_ = g_->arcs().size();\n int n_cols = arc_offset_ + g_->request_groups().size();\n ctx_.obj_coeffs.resize(n_cols);\n ctx_.col_ubs.resize(n_cols);\n ctx_.col_lbs.resize(n_cols);\n ctx_.m = CoinPackedMatrix(false, 0, 0);\n}\n\nvoid ProgTranslator::CheckPref(double pref) {\n if (pref <= 0) {\n std::stringstream ss;\n ss << \"Preference value found to be nonpositive (\" << pref\n << \"). Preferences must be positive when using an optimization solver.\"\n << \" If using Cyclus in simulation mode (e.g., from the command line),\"\n << \" this error is likely a bug in Cyclus. Please report it to the developer's \"\n << \"list (https:\/\/groups.google.com\/forum\/#!forum\/cyclus-dev).\";\n throw ValueError(ss.str());\n }\n}\n\nvoid ProgTranslator::Translate() {\n \/\/ number of variables = number of arcs + 1 faux arc per request group with arcs\n int nfalse = 0;\n std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();\n for (int i = 0; i != g_->request_groups().size(); ++i)\n nfalse += rgs[i].get()->HasArcs() ? 1 : 0;\n int n_cols = g_->arcs().size() + nfalse;\n ctx_.m.setDimensions(0, n_cols);\n\n bool request;\n std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();\n for (int i = 0; i != sgs.size(); i++) {\n request = false;\n XlateGrp_(sgs[i].get(), request);\n }\n\n for (int i = 0; i != rgs.size(); i++) {\n request = true;\n XlateGrp_(rgs[i].get(), request);\n }\n\n \/\/ add each false arc\n CLOG(LEV_DEBUG1) << \"Adding \" << arc_offset_ - g_->arcs().size()\n << \" false arcs.\";\n double inf = iface_->getInfinity();\n for (int i = g_->arcs().size(); i != arc_offset_; i++) {\n ctx_.obj_coeffs[i] = pseudo_cost_;\n ctx_.col_lbs[i] = 0;\n ctx_.col_ubs[i] = inf;\n }\n}\n\nvoid ProgTranslator::Populate() {\n iface_->setObjSense(1.0); \/\/ minimize\n\n \/\/ load er up!\n iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],\n &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);\n\n \n if (excl_) {\n std::vector<Arc>& arcs = g_->arcs();\n for (int i = 0; i != arcs.size(); i++) {\n Arc& a = arcs[i];\n if (a.exclusive()) {\n iface_->setInteger(g_->arc_ids()[a]);\n }\n }\n }\n\n}\n\nvoid ProgTranslator::ToProg() {\n Translate();\n Populate();\n}\n\nvoid ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {\n double inf = iface_->getInfinity();\n std::vector<double>& caps = grp->capacities();\n\n if (request && !grp->HasArcs())\n return; \/\/ no arcs, no reason to add variables\/constraints\n \n std::vector<CoinPackedVector> cap_rows;\n std::vector<CoinPackedVector> excl_rows;\n for (int i = 0; i != caps.size(); i++) {\n cap_rows.push_back(CoinPackedVector());\n }\n\n std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();\n for (int i = 0; i != nodes.size(); i++) {\n std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;\n std::map<Arc, std::vector<double> >::iterator cap_it;\n\n \/\/ add each arc\n for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {\n const Arc& a = cap_it->first;\n std::vector<double>& ucaps = cap_it->second;\n int arc_id = g_->arc_ids()[a];\n\n \/\/ add each unit capacity coefficient\n for (int j = 0; j != ucaps.size(); j++) {\n double coeff = ucaps[j];\n if (excl_ && a.exclusive()) {\n coeff *= a.excl_val();\n }\n\n cap_rows[j].insert(arc_id, coeff);\n }\n\n if (request) {\n CheckPref(a.pref());\n ctx_.obj_coeffs[arc_id] = ExchangeSolver::Cost(a, excl_);\n ctx_.col_lbs[arc_id] = 0;\n ctx_.col_ubs[arc_id] = (excl_ && a.exclusive()) ? 1 :\n std::min(nodes[i]->qty, inf);\n }\n }\n }\n\n int faux_id;\n if (request) {\n faux_id = arc_offset_++;\n }\n\n \/\/ add all capacity rows\n for (int i = 0; i != cap_rows.size(); i++) {\n if (request) {\n cap_rows[i].insert(faux_id, 1.0); \/\/ faux arc\n }\n\n \/\/ 1e15 is the largest value that doesn't make the solver fall over\n \/\/ (by emperical testing)\n double rlb = std::min(caps[i], 1e15); \n ctx_.row_lbs.push_back(request ? rlb : 0);\n ctx_.row_ubs.push_back(request ? inf : caps[i]);\n ctx_.m.appendRow(cap_rows[i]);\n }\n\n if (excl_) {\n \/\/ add exclusive arcs\n std::vector< std::vector<ExchangeNode::Ptr> >& exngs =\n grp->excl_node_groups();\n for (int i = 0; i != exngs.size(); i++) {\n CoinPackedVector excl_row;\n std::vector<ExchangeNode::Ptr>& nodes = exngs[i];\n for (int j = 0; j != nodes.size(); j++) {\n std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];\n for (int k = 0; k != arcs.size(); k++) {\n excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);\n }\n }\n if (excl_row.getNumElements() > 0) {\n excl_rows.push_back(excl_row);\n }\n }\n\n \/\/ add all exclusive rows\n for (int i = 0; i != excl_rows.size(); i++) {\n ctx_.row_lbs.push_back(0.0);\n ctx_.row_ubs.push_back(1.0);\n ctx_.m.appendRow(excl_rows[i]);\n }\n }\n}\n\nvoid ProgTranslator::FromProg() {\n const double* sol = iface_->getColSolution();\n std::vector<Arc>& arcs = g_->arcs();\n double flow;\n for (int i = 0; i < arcs.size(); i++) {\n Arc& a = g_->arc_by_id().at(i);\n flow = sol[i];\n flow = (excl_ && a.exclusive()) ? flow * a.excl_val() : flow;\n if (flow > cyclus::eps()) {\n g_->AddMatch(a, flow);\n }\n }\n}\n\nProgTranslator::Context::Context() {\n throw DepricatedApiError(\"Class ProgTranslator::Context is now deprecated in favor of ProgTranslatorContext.\");\n}\n\nProgTranslator::Context::~Context() {\n throw DepricatedApiError(\"Class ProgTranslator::Context is now deprecated in favor of ProgTranslatorContext.\");\n}\n\n\n} \/\/ namespace cyclus\n<|endoftext|>"} {"text":"<commit_before>\/*\n addaccountwizard.cpp - Kopete Add Account Wizard\n\n Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>\n Copyright (c) 2003 by Martijn Klingens <klingens@kde.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"addaccountwizard.h\"\n\n#include <qcheckbox.h>\n\n#include <kcolorbutton.h>\n#include <kdebug.h>\n#include <kiconloader.h>\n#include <klistview.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kplugininfo.h>\n\n#include \"addaccountwizardpage1.h\"\n#include \"addaccountwizardpage2.h\"\n#include \"addaccountwizardpage3.h\"\n#include \"editaccountwidget.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetepluginmanager.h\"\n\nAddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modal )\n: KWizard( parent, name, modal, WDestructiveClose )\n{\n\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\tm_accountPage = 0L;\n\tm_proto = 0L;\n\n\tm_intro = new AddAccountWizardPage1( this );\n\tm_selectService = new AddAccountWizardPage2( this );\n\tm_finish = new AddAccountWizardPage3( this );\n\n\taddPage( m_intro, m_intro->caption() );\n\taddPage( m_selectService, m_selectService->caption() );\n\taddPage( m_finish, m_finish->caption() );\n\n\tQListViewItem *pluginItem = 0L;\n\n\tQValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( \"Protocols\" );\n\n\tfor ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )\n\t{\n\t\tpluginItem = new QListViewItem( m_selectService->protocolListView );\n\t\tpluginItem->setText( 0, ( *it )->name() );\n\t\tpluginItem->setText( 1, ( *it )->comment() );\n\t\tpluginItem->setPixmap( 0, SmallIcon( ( *it )->icon() ) );\n\t\tm_protocolItems.insert( pluginItem, ( *it ) );\n\t}\n\n\tif ( protocols.count() == 1 )\n\t{\n\t\tpluginItem->setSelected( true );\n\t\t\/\/ I think it is important to select one protocol to make sure.\n\t\t\/\/setAppropriate( m_selectService, false );\n\t}\n\n\tsetNextEnabled( m_selectService, ( protocols.count() == 1 ) );\n\tsetFinishEnabled( m_finish, true );\n\n\tconnect( m_selectService->protocolListView, SIGNAL( clicked( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListClicked( QListViewItem * ) ) );\n\tconnect( m_selectService->protocolListView, SIGNAL( doubleClicked( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListDoubleClicked( QListViewItem * ) ) );\n\tconnect( m_selectService->protocolListView, SIGNAL( selectionChanged( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListClicked( QListViewItem * ) ) );\n}\n\nAddAccountWizard::~AddAccountWizard()\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n}\n\nvoid AddAccountWizard::slotProtocolListClicked( QListViewItem * )\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\n\t\/\/ Make sure only one protocol is selected before allowing the user to continue\n\tsetNextEnabled( m_selectService, ( m_selectService->protocolListView->selectedItem() != 0 ) );\n}\n\nvoid AddAccountWizard::slotProtocolListDoubleClicked( QListViewItem *lvi)\n{\n\t\/\/ Make sure the user clicked on an item\n\tif ( lvi )\n\t\tnext();\n}\n\nvoid AddAccountWizard::accept()\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\tKopeteAccount *account = m_accountPage->apply();\n\tif ( account && m_finish->mUseColor->isChecked() )\n\t\taccount->setColor( m_finish->mColorButton->color() );\n\n\tif(m_proto)\n\t{\n\t\t\/\/Make sur the protocol is correctly enabled. This is not realy needed, but still good\n\t\tQString protocol_name=m_proto->pluginId().remove( \"Protocol\" ).lower();\n\t\tKopetePluginManager::self()->setPluginEnabled( protocol_name , true );\n\t}\n\n\tKWizard::accept();\n\n}\n\nvoid AddAccountWizard::reject()\n{\n\tif(m_proto && KopeteAccountManager::manager()->accounts(m_proto).isEmpty())\n\t{\n\t\t\/\/FIXME: we should use a decent way to do that\n\t\tQString protocol_name=m_proto->pluginId().remove( \"Protocol\" ).lower();\n\n\/\/\t\tKopetePluginManager::self()->setPluginEnabled( protocol_name , false );\n\t\tKopetePluginManager::self()->unloadPlugin( protocol_name );\n\n\t}\n\n\tKWizard::reject();\n\n}\n\nvoid AddAccountWizard::back()\n{\n\tif ( currentPage() == dynamic_cast<QWidget *>( m_accountPage ) )\n\t{\n\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting m_accountPage\" << endl;\n\n\t\t\/\/ Deletes the accountPage, KWizard does not like deleting pages\n\t\t\/\/ using different pointers, it only seems to watch its own pointer\n\t\tdelete currentPage();\n\t\t\/\/removePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\/\/delete m_accountPage;\n\t\tm_accountPage = 0L;\n\t\tm_proto = 0L;\n\n\t\t\/\/ removePage() already goes back to previous page, no back() needed\n\t}\n\telse\n\t{\n\t\tKWizard::back();\n\t}\n}\n\nvoid AddAccountWizard::next()\n{\n\tif ( currentPage() == m_selectService ||\n\t\t( currentPage() == m_intro && !appropriate( m_selectService ) ) )\n\t{\n\t\tif ( m_accountPage )\n\t\t{\n\t\t\tkdDebug( 14100 ) << k_funcinfo << \"AccountPage still valid, part1!\" << endl;\n\/*\n\t\t\t\/\/ FIXME: Why is this commented out? Is this buggy or obsolete? - Martijn\n\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting accountPage, first part\" << endl;\n\t\t\tremovePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\tdelete m_accountPage;\n\t\t\tm_accountPage = 0L;\n*\/\n\t\t}\n\n\t\tQListViewItem *lvi = m_selectService->protocolListView->selectedItem();\n\t\tif ( lvi )\n\t\t{\n\t\t\tm_proto = dynamic_cast<KopeteProtocol *>( KopetePluginManager::self()->loadPlugin( m_protocolItems[ lvi ]->pluginName() ) );\n\t\t\tif ( m_proto )\n\t\t\t{\n\t\t\t\tif ( m_accountPage )\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"AccountPage still valid, part2!\" << endl;\n\/*\n\t\t\t\t\t\/\/ FIXME: Why is this commented out? Is this buggy or obsolete? - Martijn\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting accountPage after finding selected Protocol\" << endl;\n\t\t\t\t\tremovePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\t\t\tdelete m_accountPage;\n\t\t\t\t\tm_accountPage = 0L;\n*\/\n\t\t\t\t}\n\n\t\t\t\tm_accountPage = m_proto->createEditAccountWidget( 0L, this );\n\t\t\t\tif ( !m_accountPage )\n\t\t\t\t{\n\t\t\t\t\tKMessageBox::queuedMessageBox( this, KMessageBox::Error,\n\t\t\t\t\t\ti18n( \"This protocol does not currently support adding accounts.\" ),\n\t\t\t\t\t\ti18n( \"Error While Adding Account\" ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Adding Step Two page and switching to that one\" << endl;\n\t\t\t\t\tinsertPage( dynamic_cast<QWidget *>( m_accountPage ),\n\t\t\t\t\t\ti18n( \"Step Two: Account Information\" ), indexOf( m_finish ) );\n\t\t\t\t\tKWizard::next();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tKMessageBox::queuedMessageBox( this, KMessageBox::Error,\n\t\t\t\t\ti18n( \"Impossible to load the protocol '%1'.\" ).arg( m_protocolItems[ lvi ]->name() ), i18n( \"Error While Adding Account\" ) );\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\telse if ( indexOf( currentPage() ) == 2 )\n\t{\n\t\tif ( !m_accountPage->validateData() )\n\t\t\treturn;\n\n\t\tQColor col = KopeteAccountManager::manager()->guessColor( m_proto );\n\n\t\tm_finish->mColorButton->setColor( col );\n\t\tm_finish->mUseColor->setChecked( col.isValid() );\n\t\tKWizard::next();\n\t}\n\telse\n\t{\n\t\tKWizard::next();\n\t}\n}\n\n#include \"addaccountwizard.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>Clarification.<commit_after>\/*\n addaccountwizard.cpp - Kopete Add Account Wizard\n\n Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>\n Copyright (c) 2003 by Martijn Klingens <klingens@kde.org>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"addaccountwizard.h\"\n\n#include <qcheckbox.h>\n\n#include <kcolorbutton.h>\n#include <kdebug.h>\n#include <kiconloader.h>\n#include <klistview.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kplugininfo.h>\n\n#include \"addaccountwizardpage1.h\"\n#include \"addaccountwizardpage2.h\"\n#include \"addaccountwizardpage3.h\"\n#include \"editaccountwidget.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetepluginmanager.h\"\n\nAddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modal )\n: KWizard( parent, name, modal, WDestructiveClose )\n{\n\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\tm_accountPage = 0L;\n\tm_proto = 0L;\n\n\tm_intro = new AddAccountWizardPage1( this );\n\tm_selectService = new AddAccountWizardPage2( this );\n\tm_finish = new AddAccountWizardPage3( this );\n\n\taddPage( m_intro, m_intro->caption() );\n\taddPage( m_selectService, m_selectService->caption() );\n\taddPage( m_finish, m_finish->caption() );\n\n\tQListViewItem *pluginItem = 0L;\n\n\tQValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( \"Protocols\" );\n\n\tfor ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )\n\t{\n\t\tpluginItem = new QListViewItem( m_selectService->protocolListView );\n\t\tpluginItem->setText( 0, ( *it )->name() );\n\t\tpluginItem->setText( 1, ( *it )->comment() );\n\t\tpluginItem->setPixmap( 0, SmallIcon( ( *it )->icon() ) );\n\t\tm_protocolItems.insert( pluginItem, ( *it ) );\n\t}\n\n\tif ( protocols.count() == 1 )\n\t{\n\t\tpluginItem->setSelected( true );\n\t\t\/\/ I think it is important to select one protocol to make sure.\n\t\t\/\/setAppropriate( m_selectService, false );\n\t}\n\n\tsetNextEnabled( m_selectService, ( protocols.count() == 1 ) );\n\tsetFinishEnabled( m_finish, true );\n\n\tconnect( m_selectService->protocolListView, SIGNAL( clicked( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListClicked( QListViewItem * ) ) );\n\tconnect( m_selectService->protocolListView, SIGNAL( doubleClicked( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListDoubleClicked( QListViewItem * ) ) );\n\tconnect( m_selectService->protocolListView, SIGNAL( selectionChanged( QListViewItem * ) ),\n\t\tthis, SLOT( slotProtocolListClicked( QListViewItem * ) ) );\n}\n\nAddAccountWizard::~AddAccountWizard()\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n}\n\nvoid AddAccountWizard::slotProtocolListClicked( QListViewItem * )\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\n\t\/\/ Make sure only one protocol is selected before allowing the user to continue\n\tsetNextEnabled( m_selectService, ( m_selectService->protocolListView->selectedItem() != 0 ) );\n}\n\nvoid AddAccountWizard::slotProtocolListDoubleClicked( QListViewItem *lvi)\n{\n\t\/\/ Make sure the user clicked on an item\n\tif ( lvi )\n\t\tnext();\n}\n\nvoid AddAccountWizard::accept()\n{\n\t\/\/kdDebug( 14100 ) << k_funcinfo << endl;\n\tKopeteAccount *account = m_accountPage->apply();\n\tif ( account && m_finish->mUseColor->isChecked() )\n\t\taccount->setColor( m_finish->mColorButton->color() );\n\n\tif(m_proto)\n\t{\n\t\t\/\/Make sur the protocol is correctly enabled. This is not realy needed, but still good\n\t\tQString protocol_name=m_proto->pluginId().remove( \"Protocol\" ).lower();\n\t\tKopetePluginManager::self()->setPluginEnabled( protocol_name , true );\n\t}\n\n\tKWizard::accept();\n\n}\n\nvoid AddAccountWizard::reject()\n{\n\tif(m_proto && KopeteAccountManager::manager()->accounts(m_proto).isEmpty())\n\t{\n\t\t\/\/FIXME: we should use a decent way to do that\n\t\tQString protocol_name=m_proto->pluginId().remove( \"Protocol\" ).lower();\n\n\/\/\t\tKopetePluginManager::self()->setPluginEnabled( protocol_name , false );\n\t\tKopetePluginManager::self()->unloadPlugin( protocol_name );\n\n\t}\n\n\tKWizard::reject();\n\n}\n\nvoid AddAccountWizard::back()\n{\n\tif ( currentPage() == dynamic_cast<QWidget *>( m_accountPage ) )\n\t{\n\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting m_accountPage\" << endl;\n\n\t\t\/\/ Deletes the accountPage, KWizard does not like deleting pages\n\t\t\/\/ using different pointers, it only seems to watch its own pointer\n\t\tdelete currentPage();\n\t\t\/\/removePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\/\/delete m_accountPage;\n\t\tm_accountPage = 0L;\n\t\tm_proto = 0L;\n\n\t\t\/\/ removePage() already goes back to previous page, no back() needed\n\t}\n\telse\n\t{\n\t\tKWizard::back();\n\t}\n}\n\nvoid AddAccountWizard::next()\n{\n\tif ( currentPage() == m_selectService ||\n\t\t( currentPage() == m_intro && !appropriate( m_selectService ) ) )\n\t{\n\t\tif ( m_accountPage )\n\t\t{\n\t\t\tkdDebug( 14100 ) << k_funcinfo << \"AccountPage still valid, part1!\" << endl;\n\/*\n\t\t\t\/\/ FIXME: Why is this commented out? Is this buggy or obsolete? - Martijn\n\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting accountPage, first part\" << endl;\n\t\t\tremovePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\tdelete m_accountPage;\n\t\t\tm_accountPage = 0L;\n*\/\n\t\t}\n\n\t\tQListViewItem *lvi = m_selectService->protocolListView->selectedItem();\n\t\tif ( lvi )\n\t\t{\n\t\t\tm_proto = dynamic_cast<KopeteProtocol *>( KopetePluginManager::self()->loadPlugin( m_protocolItems[ lvi ]->pluginName() ) );\n\t\t\tif ( m_proto )\n\t\t\t{\n\t\t\t\tif ( m_accountPage )\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"AccountPage still valid, part2!\" << endl;\n\/*\n\t\t\t\t\t\/\/ FIXME: Why is this commented out? Is this buggy or obsolete? - Martijn\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Deleting accountPage after finding selected Protocol\" << endl;\n\t\t\t\t\tremovePage( dynamic_cast<QWidget *>( m_accountPage ) );\n\t\t\t\t\tdelete m_accountPage;\n\t\t\t\t\tm_accountPage = 0L;\n*\/\n\t\t\t\t}\n\n\t\t\t\tm_accountPage = m_proto->createEditAccountWidget( 0L, this );\n\t\t\t\tif ( !m_accountPage )\n\t\t\t\t{\n\t\t\t\t\tKMessageBox::queuedMessageBox( this, KMessageBox::Error,\n\t\t\t\t\t\ti18n( \"This protocol does not currently support adding accounts.\" ),\n\t\t\t\t\t\ti18n( \"Error While Adding Account\" ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tkdDebug( 14100 ) << k_funcinfo << \"Adding Step Two page and switching to that one\" << endl;\n\t\t\t\t\tinsertPage( dynamic_cast<QWidget *>( m_accountPage ),\n\t\t\t\t\t\ti18n( \"Step Two: Account Information\" ), indexOf( m_finish ) );\n\t\t\t\t\tKWizard::next();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tKMessageBox::queuedMessageBox( this, KMessageBox::Error,\n\t\t\t\t\ti18n( \"Cannot load the %1 protocol plugin!\" ).arg( m_protocolItems[ lvi ]->name() ), i18n( \"Error While Adding Account\" ) );\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\telse if ( indexOf( currentPage() ) == 2 )\n\t{\n\t\tif ( !m_accountPage->validateData() )\n\t\t\treturn;\n\n\t\tQColor col = KopeteAccountManager::manager()->guessColor( m_proto );\n\n\t\tm_finish->mColorButton->setColor( col );\n\t\tm_finish->mUseColor->setChecked( col.isValid() );\n\t\tKWizard::next();\n\t}\n\telse\n\t{\n\t\tKWizard::next();\n\t}\n}\n\n#include \"addaccountwizard.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the krss library\n *\n * Copyright (C) 2009 Frank Osterfeld <osterfeld@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"rssitemserializer.h\"\n#include \"rssitem.h\"\n#include \"category.h\"\n#include \"enclosure.h\"\n#include \"person.h\"\n\n#include <KDateTime>\n\n#include <QDataStream>\n\nusing namespace KRss;\n\nvoid RssItemSerializer::serialize( const RssItem& item, QByteArray& ba, ItemPart part ) {\n QDataStream stream( &ba, QIODevice::WriteOnly );\n stream << static_cast<qint64>( item.hash() )\n << item.guidIsHash()\n << item.title()\n << item.link()\n << item.description()\n << item.content()\n << item.language()\n << item.datePublished().toString()\n << item.dateUpdated().toString()\n << item.guid()\n << static_cast<qint32>( item.commentsCount() )\n << item.commentPostUri()\n << item.commentsFeed()\n << item.commentsLink();\n stream << static_cast<quint32>( item.enclosures().count() );\n Q_FOREACH( const Enclosure& i, item.enclosures() )\n stream << static_cast<qint32>( i.duration() ) << static_cast<qint32>( i.length() ) << i.title() << i.type() << i.url();\n stream << static_cast<quint32>( item.categories().count() );\n Q_FOREACH( const Category& i, item.categories() )\n stream << i.label() << i.scheme() << i.term();\n stream << static_cast<quint32>( item.authors().count() );\n Q_FOREACH( const Person& i, item.authors() )\n stream << i.email() << i.name() << i.uri();\n const QHash<QString, QString> ap = item.customProperties();\n stream << static_cast<quint32>( ap.size() );\n Q_FOREACH( const QString& key, ap.keys() )\n stream << key << ap.value( key );\n\n}\n\n#define READSTRING(name) QString name; stream >> name; item.set##name( name );\n#define READSTRING2(name,target) QString name; stream >> name; target.set##name( name );\n#define READ(type,name) type name; stream >> name; item.set##name( name );\n#define READ2(type,name,target) type name; stream >> name; target.set##name( name );\n#define READDATE(name) QString name; stream >> name; item.set##name( KDateTime::fromString( name ) );\n\nbool RssItemSerializer::deserialize( RssItem& itemOut, const QByteArray& ba, ItemPart part ) {\n QDataStream stream( ba );\n RssItem item;\n READ(qint64,Hash)\n READ(bool,GuidIsHash)\n READSTRING(Title)\n READSTRING(Link)\n READSTRING(Description)\n READSTRING(Content)\n READSTRING(Language)\n READDATE(DatePublished)\n READDATE(DateUpdated)\n READSTRING(Guid)\n READ(qint32,CommentsCount)\n READSTRING(CommentPostUri)\n READSTRING(CommentsFeed)\n READSTRING(CommentsLink)\n quint32 encCount;\n stream >> encCount;\n QList<Enclosure> enclosures;\n for ( quint32 i = 0; i < encCount; ++i ) {\n Enclosure enc;\n READ2(qint32, Duration, enc)\n READ2(qint32, Length, enc)\n READSTRING2(Title, enc)\n READSTRING2(Type, enc)\n READSTRING2(Url, enc)\n enclosures.append( enc );\n }\n item.setEnclosures( enclosures );\n\n quint32 catCount = 0;\n stream >> catCount;\n QList<Category> categories;\n for ( quint32 i = 0; i < catCount; ++i ) {\n Category cat;\n READSTRING2(Label, cat)\n READSTRING2(Scheme, cat)\n READSTRING2(Term, cat)\n categories.append( cat );\n }\n item.setCategories( categories );\n\n quint32 authorCount;\n stream >> authorCount;\n QList<Person> authors;\n for ( quint32 i = 0; i < authorCount; ++i ) {\n Person auth;\n READSTRING2(Email, auth)\n READSTRING2(Name, auth)\n READSTRING2(Uri, auth)\n authors.append( auth );\n }\n item.setAuthors( authors );\n\n quint32 apCount;\n stream >> apCount;\n for ( quint32 i = 0; i < apCount; ++i ) {\n QString key;\n stream >> key;\n QString value;\n stream >> value;\n item.setCustomProperty( key, value );\n }\n\n itemOut = item;\n return true;\n}\n\n#undef READ\n#undef READ2\n#undef READSTRING\n#undef READSTRING2\n#undef READDATE\n<commit_msg>respect the request payload part in the qdatastream serializer<commit_after>\/*\n * This file is part of the krss library\n *\n * Copyright (C) 2009 Frank Osterfeld <osterfeld@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"rssitemserializer.h\"\n#include \"rssitem.h\"\n#include \"category.h\"\n#include \"enclosure.h\"\n#include \"person.h\"\n\n#include <KDateTime>\n\n#include <QDataStream>\n\nusing namespace KRss;\n\nvoid RssItemSerializer::serialize( const RssItem& item, QByteArray& ba, ItemPart part ) {\n QDataStream stream( &ba, QIODevice::WriteOnly );\n const bool writeHeaders = ( part & Headers ) != 0;\n const bool writeContent = ( part & Content ) != 0;\n\n if ( writeHeaders ) {\n stream << static_cast<qint64>( item.hash() )\n << item.guidIsHash()\n << item.title()\n << item.datePublished().toString()\n << item.dateUpdated().toString()\n << item.guid()\n stream << static_cast<quint32>( item.authors().count() );\n Q_FOREACH( const Person& i, item.authors() )\n stream << i.email() << i.name() << i.uri();\n }\n if ( writeContent ) {\n stream << item.content()\n << item.description()\n << item.link()\n << item.language()\n << static_cast<qint32>( item.commentsCount() )\n << item.commentPostUri()\n << item.commentsFeed()\n << item.commentsLink();\n stream << static_cast<quint32>( item.enclosures().count() );\n Q_FOREACH( const Enclosure& i, item.enclosures() )\n stream << static_cast<qint32>( i.duration() ) << static_cast<qint32>( i.length() ) << i.title() << i.type() << i.url();\n stream << static_cast<quint32>( item.categories().count() );\n Q_FOREACH( const Category& i, item.categories() )\n stream << i.label() << i.scheme() << i.term();\n const QHash<QString, QString> ap = item.customProperties();\n stream << static_cast<quint32>( ap.size() );\n Q_FOREACH( const QString& key, ap.keys() )\n stream << key << ap.value( key );\n }\n}\n\n#define READSTRING(name) QString name; stream >> name; item.set##name( name );\n#define READSTRING2(name,target) QString name; stream >> name; target.set##name( name );\n#define READ(type,name) type name; stream >> name; item.set##name( name );\n#define READ2(type,name,target) type name; stream >> name; target.set##name( name );\n#define READDATE(name) QString name; stream >> name; item.set##name( KDateTime::fromString( name ) );\n\nbool RssItemSerializer::deserialize( RssItem& itemOut, const QByteArray& ba, ItemPart part ) {\n const bool readHeaders = ( part & Headers ) != 0;\n const bool readContent = ( part & Content ) != 0;\n\n QDataStream stream( ba );\n RssItem item;\n if ( readHeaders ) {\n READ(qint64,Hash)\n READ(bool,GuidIsHash)\n READSTRING(Title)\n READDATE(DatePublished)\n READDATE(DateUpdated)\n READSTRING(Guid)\n quint32 authorCount;\n stream >> authorCount;\n QList<Person> authors;\n for ( quint32 i = 0; i < authorCount; ++i ) {\n Person auth;\n READSTRING2(Email, auth)\n READSTRING2(Name, auth)\n READSTRING2(Uri, auth)\n authors.append( auth );\n }\n item.setAuthors( authors );\n }\n if ( readContent ) {\n READSTRING(Content)\n READSTRING(Description)\n READSTRING(Link)\n\n READSTRING(Language)\n READ(qint32,CommentsCount)\n READSTRING(CommentPostUri)\n READSTRING(CommentsFeed)\n READSTRING(CommentsLink)\n quint32 encCount;\n stream >> encCount;\n QList<Enclosure> enclosures;\n for ( quint32 i = 0; i < encCount; ++i ) {\n Enclosure enc;\n READ2(qint32, Duration, enc)\n READ2(qint32, Length, enc)\n READSTRING2(Title, enc)\n READSTRING2(Type, enc)\n READSTRING2(Url, enc)\n enclosures.append( enc );\n }\n item.setEnclosures( enclosures );\n\n quint32 catCount = 0;\n stream >> catCount;\n QList<Category> categories;\n for ( quint32 i = 0; i < catCount; ++i ) {\n Category cat;\n READSTRING2(Label, cat)\n READSTRING2(Scheme, cat)\n READSTRING2(Term, cat)\n categories.append( cat );\n }\n item.setCategories( categories );\n\n\n quint32 apCount;\n stream >> apCount;\n for ( quint32 i = 0; i < apCount; ++i ) {\n QString key;\n stream >> key;\n QString value;\n stream >> value;\n item.setCustomProperty( key, value );\n }\n }\n itemOut = item;\n\n if ( readHeaders )\n item.setHeadersLoaded( true );\n\n if ( readContent )\n item.setContentLoaded( true );\n\n return true;\n}\n\n#undef READ\n#undef READ2\n#undef READSTRING\n#undef READSTRING2\n#undef READDATE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <assert.h>\n#include <dlfcn.h> \/\/dlopen\n#include <sys\/time.h>\n#include <tvm\/runtime\/c_runtime_api.h>\n\n#include <iostream>\n#include <random>\n#include <vector>\n\ntemplate <typename F>\nauto getFunc(void* bundle, const char* name) {\n dlerror();\n auto* f = reinterpret_cast<typename std::add_pointer<F>::type>(dlsym(bundle, name));\n assert(!dlerror());\n return f;\n}\n\nstatic int read_all(const char* file_description, const char* file_path, char** out_params,\n size_t* params_size) {\n FILE* fp = fopen(file_path, \"rb\");\n if (fp == NULL) {\n return 2;\n }\n\n int error = 0;\n error = fseek(fp, 0, SEEK_END);\n if (error < 0) {\n return error;\n }\n\n long file_size = ftell(fp);\n if (file_size < 0) {\n return (int)file_size;\n } else if (file_size == 0 || file_size > (10 << 20)) { \/\/ file size should be in (0, 20MB].\n char buf[128];\n snprintf(buf, sizeof(buf), \"determing file size: %s\", file_path);\n perror(buf);\n return 2;\n }\n\n if (params_size != NULL) {\n *params_size = file_size;\n }\n\n error = fseek(fp, 0, SEEK_SET);\n if (error < 0) {\n return error;\n }\n\n *out_params = (char*)malloc((unsigned long)file_size);\n if (fread(*out_params, file_size, 1, fp) != 1) {\n free(*out_params);\n *out_params = NULL;\n\n char buf[128];\n snprintf(buf, sizeof(buf), \"reading: %s\", file_path);\n perror(buf);\n return 2;\n }\n\n error = fclose(fp);\n if (error != 0) {\n free(*out_params);\n *out_params = NULL;\n }\n\n return 0;\n}\n\nint main(int argc, char** argv) {\n assert(argc == 5 && \"Usage: demo <bundle.so> <graph.json> <params.bin> <cat.bin>\");\n auto* bundle = dlopen(argv[1], RTLD_LAZY | RTLD_LOCAL);\n assert(bundle);\n\n char* json_data;\n int error = read_all(\"graph.json\", argv[2], &json_data, NULL);\n if (error != 0) {\n return error;\n }\n\n char* params_data;\n size_t params_size;\n error = read_all(\"params.bin\", argv[3], ¶ms_data, ¶ms_size);\n if (error != 0) {\n return error;\n }\n\n struct timeval t0, t1, t2, t3, t4, t5;\n gettimeofday(&t0, 0);\n\n auto* handle = getFunc<void*(char*, char*, int)>(bundle, \"tvm_runtime_create\")(\n json_data, params_data, params_size);\n gettimeofday(&t1, 0);\n\n float input_storage[1 * 3 * 224 * 224];\n FILE* fp = fopen(argv[3], \"rb\");\n fread(input_storage, 3 * 224 * 224, 4, fp);\n fclose(fp);\n\n std::vector<int64_t> input_shape = {1, 3, 224, 224};\n DLTensor input;\n input.data = input_storage;\n input.ctx = DLContext{kDLCPU, 0};\n input.ndim = 4;\n input.dtype = DLDataType{kDLFloat, 32, 1};\n input.shape = input_shape.data();\n input.strides = nullptr;\n input.byte_offset = 0;\n\n getFunc<void(void*, const char*, void*)>(bundle, \"tvm_runtime_set_input\")(handle, \"data\", &input);\n gettimeofday(&t2, 0);\n\n auto* ftvm_runtime_run = (auto (*)(void*)->void)dlsym(bundle, \"tvm_runtime_run\");\n assert(!dlerror());\n ftvm_runtime_run(handle);\n gettimeofday(&t3, 0);\n\n float output_storage[1000];\n std::vector<int64_t> output_shape = {1, 1000};\n DLTensor output;\n output.data = output_storage;\n output.ctx = DLContext{kDLCPU, 0};\n output.ndim = 2;\n output.dtype = DLDataType{kDLFloat, 32, 1};\n output.shape = output_shape.data();\n output.strides = nullptr;\n output.byte_offset = 0;\n\n getFunc<void(void*, int, void*)>(bundle, \"tvm_runtime_get_output\")(handle, 0, &output);\n gettimeofday(&t4, 0);\n\n float max_iter = -std::numeric_limits<float>::max();\n int32_t max_index = -1;\n for (auto i = 0; i < 1000; ++i) {\n if (output_storage[i] > max_iter) {\n max_iter = output_storage[i];\n max_index = i;\n }\n }\n\n getFunc<void(void*)>(bundle, \"tvm_runtime_destroy\")(handle);\n gettimeofday(&t5, 0);\n\n printf(\"The maximum position in output vector is: %d, with max-value %f.\\n\", max_index, max_iter);\n printf(\n \"timing: %.2f ms (create), %.2f ms (set_input), %.2f ms (run), \"\n \"%.2f ms (get_output), %.2f ms (destroy)\\n\",\n (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) \/ 1000.f,\n (t2.tv_sec - t1.tv_sec) * 1000.0f + (t2.tv_usec - t1.tv_usec) \/ 1000.f,\n (t3.tv_sec - t2.tv_sec) * 1000.0f + (t3.tv_usec - t2.tv_usec) \/ 1000.f,\n (t4.tv_sec - t3.tv_sec) * 1000.0f + (t4.tv_usec - t3.tv_usec) \/ 1000.f,\n (t5.tv_sec - t4.tv_sec) * 1000.0f + (t5.tv_usec - t4.tv_usec) \/ 1000.f);\n dlclose(bundle);\n\n return 0;\n}\n<commit_msg>[APP] Fix misprint in demo.cc during initializing of picture tensor data (#6566)<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <assert.h>\n#include <dlfcn.h> \/\/dlopen\n#include <sys\/time.h>\n#include <tvm\/runtime\/c_runtime_api.h>\n\n#include <iostream>\n#include <random>\n#include <vector>\n\ntemplate <typename F>\nauto getFunc(void* bundle, const char* name) {\n dlerror();\n auto* f = reinterpret_cast<typename std::add_pointer<F>::type>(dlsym(bundle, name));\n assert(!dlerror());\n return f;\n}\n\nstatic int read_all(const char* file_description, const char* file_path, char** out_params,\n size_t* params_size) {\n FILE* fp = fopen(file_path, \"rb\");\n if (fp == NULL) {\n return 2;\n }\n\n int error = 0;\n error = fseek(fp, 0, SEEK_END);\n if (error < 0) {\n return error;\n }\n\n long file_size = ftell(fp);\n if (file_size < 0) {\n return (int)file_size;\n } else if (file_size == 0 || file_size > (10 << 20)) { \/\/ file size should be in (0, 20MB].\n char buf[128];\n snprintf(buf, sizeof(buf), \"determing file size: %s\", file_path);\n perror(buf);\n return 2;\n }\n\n if (params_size != NULL) {\n *params_size = file_size;\n }\n\n error = fseek(fp, 0, SEEK_SET);\n if (error < 0) {\n return error;\n }\n\n *out_params = (char*)malloc((unsigned long)file_size);\n if (fread(*out_params, file_size, 1, fp) != 1) {\n free(*out_params);\n *out_params = NULL;\n\n char buf[128];\n snprintf(buf, sizeof(buf), \"reading: %s\", file_path);\n perror(buf);\n return 2;\n }\n\n error = fclose(fp);\n if (error != 0) {\n free(*out_params);\n *out_params = NULL;\n }\n\n return 0;\n}\n\nint main(int argc, char** argv) {\n assert(argc == 5 && \"Usage: demo <bundle.so> <graph.json> <params.bin> <cat.bin>\");\n auto* bundle = dlopen(argv[1], RTLD_LAZY | RTLD_LOCAL);\n assert(bundle);\n\n char* json_data;\n int error = read_all(\"graph.json\", argv[2], &json_data, NULL);\n if (error != 0) {\n return error;\n }\n\n char* params_data;\n size_t params_size;\n error = read_all(\"params.bin\", argv[3], ¶ms_data, ¶ms_size);\n if (error != 0) {\n return error;\n }\n\n struct timeval t0, t1, t2, t3, t4, t5;\n gettimeofday(&t0, 0);\n\n auto* handle = getFunc<void*(char*, char*, int)>(bundle, \"tvm_runtime_create\")(\n json_data, params_data, params_size);\n gettimeofday(&t1, 0);\n\n float input_storage[1 * 3 * 224 * 224];\n FILE* fp = fopen(argv[4], \"rb\");\n fread(input_storage, 3 * 224 * 224, 4, fp);\n fclose(fp);\n\n std::vector<int64_t> input_shape = {1, 3, 224, 224};\n DLTensor input;\n input.data = input_storage;\n input.ctx = DLContext{kDLCPU, 0};\n input.ndim = 4;\n input.dtype = DLDataType{kDLFloat, 32, 1};\n input.shape = input_shape.data();\n input.strides = nullptr;\n input.byte_offset = 0;\n\n getFunc<void(void*, const char*, void*)>(bundle, \"tvm_runtime_set_input\")(handle, \"data\", &input);\n gettimeofday(&t2, 0);\n\n auto* ftvm_runtime_run = (auto (*)(void*)->void)dlsym(bundle, \"tvm_runtime_run\");\n assert(!dlerror());\n ftvm_runtime_run(handle);\n gettimeofday(&t3, 0);\n\n float output_storage[1000];\n std::vector<int64_t> output_shape = {1, 1000};\n DLTensor output;\n output.data = output_storage;\n output.ctx = DLContext{kDLCPU, 0};\n output.ndim = 2;\n output.dtype = DLDataType{kDLFloat, 32, 1};\n output.shape = output_shape.data();\n output.strides = nullptr;\n output.byte_offset = 0;\n\n getFunc<void(void*, int, void*)>(bundle, \"tvm_runtime_get_output\")(handle, 0, &output);\n gettimeofday(&t4, 0);\n\n float max_iter = -std::numeric_limits<float>::max();\n int32_t max_index = -1;\n for (auto i = 0; i < 1000; ++i) {\n if (output_storage[i] > max_iter) {\n max_iter = output_storage[i];\n max_index = i;\n }\n }\n\n getFunc<void(void*)>(bundle, \"tvm_runtime_destroy\")(handle);\n gettimeofday(&t5, 0);\n\n printf(\"The maximum position in output vector is: %d, with max-value %f.\\n\", max_index, max_iter);\n printf(\n \"timing: %.2f ms (create), %.2f ms (set_input), %.2f ms (run), \"\n \"%.2f ms (get_output), %.2f ms (destroy)\\n\",\n (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) \/ 1000.f,\n (t2.tv_sec - t1.tv_sec) * 1000.0f + (t2.tv_usec - t1.tv_usec) \/ 1000.f,\n (t3.tv_sec - t2.tv_sec) * 1000.0f + (t3.tv_usec - t2.tv_usec) \/ 1000.f,\n (t4.tv_sec - t3.tv_sec) * 1000.0f + (t4.tv_usec - t3.tv_usec) \/ 1000.f,\n (t5.tv_sec - t4.tv_sec) * 1000.0f + (t5.tv_usec - t4.tv_usec) \/ 1000.f);\n dlclose(bundle);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#define SYSDEF_PATH\n#include \"sysdef.h\"\n#include \"csengine\/sysitf.h\"\n#include \"csws\/csws.h\"\n\nclass MazeEditor : public csApp\n{\npublic:\n \/\/\/ Initialize maze editor\n MazeEditor (char *AppTitle, int argc, char *argv[]) :\n csApp (AppTitle, argc, argv) {};\n\n \/\/\/\n virtual bool HandleEvent (csEvent &Event);\n\n virtual bool InitialSetup ();\n};\n\nMazeEditor *app; \/\/ The main Windowing System object\n\n\/\/-----------------------------------------------------------------------------\n\nbool MazeEditor::InitialSetup ()\n{\n if (!csApp::InitialSetup ())\n return false;\n\n \/\/ create a window\n csComponent *window = new csWindow (this, \"-- Drag me --\",\n CSWS_DEFAULTVALUE | CSWS_TOOLBAR | CSWS_CLIENTBORDER);\n\n csMenu *menu = (csMenu *)window->GetChild (CSWID_MENUBAR);\n if (menu)\n {\n menu->SetFont (csFontCourier);\n csMenu *submenu;\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~File\", submenu);\n (void)new csMenuItem (submenu, \"~Open\\tCtrl+O\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Save\\tCtrl+S\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Close\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Quit\\tCtrl+Q\", cscmdQuit);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Edit\", submenu);\n (void)new csMenuItem (submenu, \"~Undo\\tAlt+BackSpace\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Copy\\tCtrl+Ins\", cscmdNothing);\n (void)new csMenuItem (submenu, \"Cu~t\\tShift+Del\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Paste\\tShift+Ins\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Select all\\tCtrl+\/\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Deselect all\\tCtrl+\\\\\", cscmdNothing);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Modify\", submenu);\n (void)new csMenuItem (submenu, \"~Scale\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Rotate\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Move\", cscmdNothing);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Test submenu\", submenu);\n (void)new csMenuItem (submenu, \"~One\", cscmdNothing, CSMIS_DEFAULTVALUE | CSMIS_CHECKED);\n (void)new csMenuItem (submenu, \"~Two\", cscmdNothing);\n (void)new csMenuItem (submenu, \"T~hree\", cscmdNothing);\n csMenu *subsubmenu = new csMenu (NULL);\n (void)new csMenuItem (submenu, \"~Four\", subsubmenu);\n (void)new csMenuItem (subsubmenu, \"Four \/ ~One\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Four \/ ~Two\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Four \/ T~hree\", cscmdNothing);\n subsubmenu = new csMenu (NULL);\n (void)new csMenuItem (submenu, \"Fi~ve\", subsubmenu, CSMIS_NEWCOLUMN);\n (void)new csMenuItem (subsubmenu, \"Five \/ ~One\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Five \/ ~Two\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Five \/ T~hree\", cscmdNothing);\n (void)new csMenuItem (subsubmenu);\n (void)new csMenuItem (subsubmenu, \"~Maximize\", cscmdMaximize, CSMIS_DEFAULTVALUE | CSMIS_NOCLOSE);\n (void)new csMenuItem (subsubmenu, \"~Hide\", cscmdHide);\n (void)new csMenuItem (subsubmenu, \"~Close\", cscmdClose);\n (void)new csMenuItem (subsubmenu);\n (void)new csMenuItem (subsubmenu, \"~Quit\\tCtrl+Q\", cscmdQuit);\n subsubmenu->GetChild (cscmdHide)->SendCommand (cscmdMenuItemCheck, (void *)true);\n subsubmenu->GetChild (cscmdQuit)->SendCommand (cscmdMenuItemCheck, (void *)true);\n (void)new csMenuItem (submenu, \"~Six\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Seven\", cscmdNothing);\n\n (void)new csMenuItem (menu, \"~NoSubmenu\");\n\n (void)new csMenuItem (menu, CSMIS_NEWCOLUMN);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Help\", submenu);\n (void)new csMenuItem (submenu, \"~Index\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~General\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Context\\tF1\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~About\", cscmdNothing);\n submenu->GetChild (cscmdNothing)->SendCommand (cscmdDeactivateMenu, (void *)false);\n\n menu->PlaceItems ();\n }\n csDialog *toolbar = (csDialog *)window->GetChild (CSWID_TOOLBAR);\n if (toolbar)\n {\n csNewToolbarButton (toolbar, cscmdNothing, \"hello\");\n csNewToolbarButton (toolbar, cscmdNothing, \"hello again\");\n csNewToolbarButton (toolbar, cscmdNothing, \"test\");\n csNewToolbarButton (toolbar, cscmdNothing, \"another test\");\n csNewToolbarButton (toolbar, cscmdNothing, \"yet another test\");\n }\n window->SetRect (80, 20, 520, 340);\n\n csComponent *client = new csDialog (window);\n\n {\n csButton *but = new csButton (client, cscmdQuit);\n but->SetText (\"~Quit!\"); but->SetRect (20, 20, 90, 40);\n but->SetState (CSS_GROUP, true);\n csStatic *stat = new csStatic (client, but, \"Test ~Label\", csscsFrameLabel);\n stat->SetRect (10, 10, 420, 110);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE | CSBS_DEFAULT);\n but->SetText (\"~Another one\"); but->SetRect (50, 80, 180, 100);\n\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThinRect);\n but->SetText (\"hmm~...\"); but->SetRect (20, 130, 100, 144);\n but->SetState (CSS_GROUP, true);\n stat = new csStatic (client, but, \"Another ~Group\", csscsFrameLabel);\n stat->SetRect (10, 110, 420, 270);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThickRect);\n but->SetText (\"~whoops!\"); but->SetRect (120, 130, 200, 144);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThinRect);\n but->SetText (\"~crash!\"); but->SetRect (220, 130, 300, 144);\n\n csInputLine *il = new csInputLine (client, 40, csifsThinRect);\n il->SetText (\"input line test: check it out!\"); il->SetRect (100, 200, 300, 216);\n il = new csInputLine (client, 10, csifsThickRect);\n il->SetText (\"another input line\"); il->SetRect (100, 220, 300, 236);\n il->SetFont (csFontCourier); il->SetSelection (0, 999);\n\n csListBox *lb = new csListBox (client, CSLBS_HSCROLL | CSLBS_VSCROLL, cslfsThinRect);\n lb->SetRect (320, 120, 410, 250);\n lb->SetFont (csFontCourier);\n for (int i = 1; i < 100; i++)\n {\n char tmp[20];\n sprintf (tmp, \"item %d - dummy\", i);\n (void)new csListBoxItem (lb, tmp, i);\n }\n lb->PlaceItems ();\n }\n\n window = new csWindow (this, \"SetState (CSS_TOPSELECT, false)\",\n CSWS_DEFAULTVALUE, cswfsThin);\n window->SetState (CSS_TOPSELECT, false);\n window->SetRect (20, 20, 400, 80);\n\n {\n csButton *but = new csButton (this, 9999);\n but->SetText (\"Hello\"); but->SetRect (10, 10, 100, 30);\n but->SetFont (csFontTiny);\n but = new csButton (this, cscmdNothing);\n but->SetText (\"Othello\"); but->SetRect (210, 10, 300, 30);\n }\n return true;\n}\n\nbool MazeEditor::HandleEvent (csEvent &Event)\n{\n switch (Event.Type)\n {\n case csevCommand:\n switch (Event.Command.Code)\n {\n case 9999:\n {\n csWindow *d = csFileDialog (this, \"test file dialog\");\n if (d)\n {\n Execute (d);\n char filename [MAXPATHLEN + 1];\n csQueryFileDialog (d, filename, sizeof (filename));\n delete d;\n MessageBox (app, \"Result\", filename);\n }\n }\n break;\n }\n break;\n }\n#if 0\n static int px, py;\n static bool draw = false;\n\n switch (Event.Type)\n {\n case csevMouseMove:\n if (draw)\n {\n Line (px, py, Event.Mouse.x, Event.Mouse.y, csws_Color_Gray_D);\n px = Event.Mouse.x;\n py = Event.Mouse.y;\n return Mouse->HandleEvent (Event);\n } \/* endif *\/\n break;\n case csevMouseDown:\n if (Event.Mouse.button == 1)\n {\n draw = true;\n px = Event.Mouse.x;\n py = Event.Mouse.y;\n Line (px, py, px, py, csws_Color_White);\n return Mouse->HandleEvent (Event);\n } else if (Event.Mouse.button == 2)\n {\n static int lastcursor = 0;\n lastcursor = (lastcursor + 1) % 4;\n Mouse->SetCursor (lastcursor);\n return Mouse->HandleEvent (Event);\n } \/* endif *\/\n break;\n case csevMouseUp:\n draw = false;\n return true;\n } \/* endswitch *\/\n#endif\n return csApp::HandleEvent (Event);\n}\n\n\/\/---------------------------------------------------------------------------\n\n\/*\n * Main function\n *\/\nint main (int argc, char* argv[])\n{\n config = new csIniFile (\"MazeD.cfg\");\n\n app = new MazeEditor (\"Crystal Space 3D maze editor\", argc, argv);\n\n CsPrintf (MSG_INITIALIZATION, \"Crystal Space Maze Editor version %s (%s).\\n\", VERSION, RELEASE_DATE);\n CsPrintf (MSG_INITIALIZATION, \"Created by Andrew Zabolotny and others...\\n\\n\");\n\n \/\/ For GUI apps double buffering is a performance hit\n System->piG2D->DoubleBuffer (false);\n\n if (app->InitialSetup ())\n app->Loop ();\n\n return (0);\n}\n<commit_msg>Added line drawing (left mouse button) and mouse cursor switching (right mouse button). Use to test these features in 2D drivers.<commit_after>\/*\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#define SYSDEF_PATH\n#include \"sysdef.h\"\n#include \"csengine\/sysitf.h\"\n#include \"csws\/csws.h\"\n\nclass csWsTest : public csApp\n{\npublic:\n \/\/\/ Initialize maze editor\n csWsTest (char *AppTitle, int argc, char *argv[]);\n\n \/\/\/\n virtual bool HandleEvent (csEvent &Event);\n\n virtual bool InitialSetup ();\n};\n\ncsWsTest *app; \/\/ The main Windowing System object\n\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Scroll bar class default palette\nstatic int palette_csWsTest[] =\n{\n cs_Color_Gray_D,\t\t\t\/\/ Application workspace\n cs_Color_Green_L,\t\t\t\/\/ End points\n cs_Color_Red_L,\t\t\t\/\/ lines\n cs_Color_White\t\t\t\/\/ Start points\n};\n\ncsWsTest::csWsTest (char *AppTitle, int argc, char *argv[]) :\n csApp (AppTitle, argc, argv)\n{\n SetPalette (palette_csWsTest, sizeof (palette_csWsTest) \/ sizeof (int));\n}\n\nbool csWsTest::InitialSetup ()\n{\n if (!csApp::InitialSetup ())\n return false;\n\n \/\/ create a window\n csComponent *window = new csWindow (this, \"-- Drag me --\",\n CSWS_DEFAULTVALUE | CSWS_TOOLBAR | CSWS_CLIENTBORDER);\n\n csMenu *menu = (csMenu *)window->GetChild (CSWID_MENUBAR);\n if (menu)\n {\n menu->SetFont (csFontCourier);\n csMenu *submenu;\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~File\", submenu);\n (void)new csMenuItem (submenu, \"~Open\\tCtrl+O\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Save\\tCtrl+S\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Close\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Quit\\tCtrl+Q\", cscmdQuit);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Edit\", submenu);\n (void)new csMenuItem (submenu, \"~Undo\\tAlt+BackSpace\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Copy\\tCtrl+Ins\", cscmdNothing);\n (void)new csMenuItem (submenu, \"Cu~t\\tShift+Del\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Paste\\tShift+Ins\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~Select all\\tCtrl+\/\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Deselect all\\tCtrl+\\\\\", cscmdNothing);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Modify\", submenu);\n (void)new csMenuItem (submenu, \"~Scale\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Rotate\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Move\", cscmdNothing);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Test submenu\", submenu);\n (void)new csMenuItem (submenu, \"~One\", cscmdNothing, CSMIS_DEFAULTVALUE | CSMIS_CHECKED);\n (void)new csMenuItem (submenu, \"~Two\", cscmdNothing);\n (void)new csMenuItem (submenu, \"T~hree\", cscmdNothing);\n csMenu *subsubmenu = new csMenu (NULL);\n (void)new csMenuItem (submenu, \"~Four\", subsubmenu);\n (void)new csMenuItem (subsubmenu, \"Four \/ ~One\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Four \/ ~Two\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Four \/ T~hree\", cscmdNothing);\n subsubmenu = new csMenu (NULL);\n (void)new csMenuItem (submenu, \"Fi~ve\", subsubmenu, CSMIS_NEWCOLUMN);\n (void)new csMenuItem (subsubmenu, \"Five \/ ~One\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Five \/ ~Two\", cscmdNothing);\n (void)new csMenuItem (subsubmenu, \"Five \/ T~hree\", cscmdNothing);\n (void)new csMenuItem (subsubmenu);\n (void)new csMenuItem (subsubmenu, \"~Maximize\", cscmdMaximize, CSMIS_DEFAULTVALUE | CSMIS_NOCLOSE);\n (void)new csMenuItem (subsubmenu, \"~Hide\", cscmdHide);\n (void)new csMenuItem (subsubmenu, \"~Close\", cscmdClose);\n (void)new csMenuItem (subsubmenu);\n (void)new csMenuItem (subsubmenu, \"~Quit\\tCtrl+Q\", cscmdQuit);\n subsubmenu->GetChild (cscmdHide)->SendCommand (cscmdMenuItemCheck, (void *)true);\n subsubmenu->GetChild (cscmdQuit)->SendCommand (cscmdMenuItemCheck, (void *)true);\n (void)new csMenuItem (submenu, \"~Six\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Seven\", cscmdNothing);\n\n (void)new csMenuItem (menu, \"~NoSubmenu\");\n\n (void)new csMenuItem (menu, CSMIS_NEWCOLUMN);\n\n submenu = new csMenu (NULL);\n (void)new csMenuItem (menu, \"~Help\", submenu);\n (void)new csMenuItem (submenu, \"~Index\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~General\", cscmdNothing);\n (void)new csMenuItem (submenu, \"~Context\\tF1\", cscmdNothing);\n (void)new csMenuItem (submenu);\n (void)new csMenuItem (submenu, \"~About\", cscmdNothing);\n submenu->GetChild (cscmdNothing)->SendCommand (cscmdDeactivateMenu, (void *)false);\n\n menu->PlaceItems ();\n }\n csDialog *toolbar = (csDialog *)window->GetChild (CSWID_TOOLBAR);\n if (toolbar)\n {\n csNewToolbarButton (toolbar, cscmdNothing, \"hello\");\n csNewToolbarButton (toolbar, cscmdNothing, \"hello again\");\n csNewToolbarButton (toolbar, cscmdNothing, \"test\");\n csNewToolbarButton (toolbar, cscmdNothing, \"another test\");\n csNewToolbarButton (toolbar, cscmdNothing, \"yet another test\");\n }\n window->SetRect (80, 20, 520, 340);\n\n csComponent *client = new csDialog (window);\n\n {\n csButton *but = new csButton (client, cscmdQuit);\n but->SetText (\"~Quit!\"); but->SetRect (20, 20, 90, 40);\n but->SetState (CSS_GROUP, true);\n csStatic *stat = new csStatic (client, but, \"Test ~Label\", csscsFrameLabel);\n stat->SetRect (10, 10, 420, 110);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE | CSBS_DEFAULT);\n but->SetText (\"~Another one\"); but->SetRect (50, 80, 180, 100);\n\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThinRect);\n but->SetText (\"hmm~...\"); but->SetRect (20, 130, 100, 144);\n but->SetState (CSS_GROUP, true);\n stat = new csStatic (client, but, \"Another ~Group\", csscsFrameLabel);\n stat->SetRect (10, 110, 420, 270);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThickRect);\n but->SetText (\"~whoops!\"); but->SetRect (120, 130, 200, 144);\n but = new csButton (client, cscmdNothing, CSBS_DEFAULTVALUE, csbfsThinRect);\n but->SetText (\"~crash!\"); but->SetRect (220, 130, 300, 144);\n\n csInputLine *il = new csInputLine (client, 40, csifsThinRect);\n il->SetText (\"input line test: check it out!\"); il->SetRect (100, 200, 300, 216);\n il = new csInputLine (client, 10, csifsThickRect);\n il->SetText (\"another input line\"); il->SetRect (100, 220, 300, 236);\n il->SetFont (csFontCourier); il->SetSelection (0, 999);\n\n csListBox *lb = new csListBox (client, CSLBS_HSCROLL | CSLBS_VSCROLL, cslfsThinRect);\n lb->SetRect (320, 120, 410, 250);\n lb->SetFont (csFontCourier);\n for (int i = 1; i < 100; i++)\n {\n char tmp[20];\n sprintf (tmp, \"item %d - dummy\", i);\n (void)new csListBoxItem (lb, tmp, i);\n }\n lb->PlaceItems ();\n }\n\n window = new csWindow (this, \"SetState (CSS_TOPSELECT, false)\",\n CSWS_DEFAULTVALUE, cswfsThin);\n window->SetState (CSS_TOPSELECT, false);\n window->SetRect (20, 20, 400, 80);\n\n {\n csButton *but = new csButton (this, 9999);\n but->SetText (\"Hello\"); but->SetRect (10, 10, 100, 30);\n but->SetFont (csFontTiny);\n but = new csButton (this, cscmdNothing);\n but->SetText (\"Othello\"); but->SetRect (210, 10, 300, 30);\n }\n return true;\n}\n\nbool csWsTest::HandleEvent (csEvent &Event)\n{\n static csMouseCursorID mousecursors [] =\n {\n csmcNone, csmcArrow, csmcLens, csmcCross, csmcPen, csmcMove,\n csmcSizeNWSE, csmcSizeNESW, csmcSizeNS, csmcSizeEW, csmcStop, csmcWait\n };\n\n static int mousecursor = 1;\n static int px, py;\n static bool draw = false;\n\n if (csApp::HandleEvent (Event))\n return true;\n\n switch (Event.Type)\n {\n case csevCommand:\n switch (Event.Command.Code)\n {\n case 9999:\n {\n csWindow *d = csFileDialog (this, \"test file dialog\");\n if (d)\n {\n Execute (d);\n char filename [MAXPATHLEN + 1];\n csQueryFileDialog (d, filename, sizeof (filename));\n delete d;\n MessageBox (app, \"Result\", filename);\n }\n return true;\n }\n }\n break;\n\n case csevMouseMove:\n SetMouse (mousecursors [mousecursor]);\n if (draw)\n {\n \/\/ kludge: set dirty rectangle so that line won't get clipped\n csRect old (dirty);\n dirty.Set (px, py, Event.Mouse.x, Event.Mouse.y);\n dirty.Normalize ();\n dirty.xmax++; dirty.ymax++;\n Line (px, py, Event.Mouse.x, Event.Mouse.y, 2);\n dirty.Set (old);\n\n px = Event.Mouse.x;\n py = Event.Mouse.y;\n } \/* endif *\/\n return true;\n\n case csevMouseDown:\n case csevMouseDoubleClick:\n if (Event.Mouse.Button == 1)\n {\n draw = true;\n px = Event.Mouse.x;\n py = Event.Mouse.y;\n\n \/\/ kludge: set dirty rectangle so that line won't get clipped\n csRect old (dirty);\n dirty.Set (px - 1, py - 1, px + 2, py + 2);\n Box (px - 1, py - 1, px + 2, py + 2, 3);\n dirty.Set (old);\n }\n else if (Event.Mouse.Button == 2)\n {\n mousecursor = (mousecursor + 1) % (sizeof (mousecursors) \/ sizeof (int));\n SetMouse (mousecursors [mousecursor]);\n } \/* endif *\/\n return true;\n\n case csevMouseUp:\n {\n \/\/ kludge: set dirty rectangle so that line won't get clipped\n csRect old (dirty);\n dirty.Set (px - 1, py - 1, px + 2, py + 2);\n Box (px - 1, py - 1, px + 2, py + 2, 1);\n dirty.Set (old);\n\n draw = false;\n return true;\n }\n } \/* endswitch *\/\n\n return false;\n}\n\n\/\/---------------------------------------------------------------------------\n\n\/*\n * Main function\n *\/\nint main (int argc, char* argv[])\n{\n config = new csIniFile (\"MazeD.cfg\");\n\n app = new csWsTest (\"Crystal Space 3D maze editor\", argc, argv);\n\n CsPrintf (MSG_INITIALIZATION, \"Crystal Space Windowing System test version %s (%s).\\n\", VERSION, RELEASE_DATE);\n CsPrintf (MSG_INITIALIZATION, \"Created by Andrew Zabolotny and others...\\n\\n\");\n\n \/\/ For GUI apps double buffering is a performance hit\n System->piG2D->DoubleBuffer (false);\n\n if (app->InitialSetup ())\n app->Loop ();\n\n return (0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n#include <aliceVision\/config.hpp>\n#include <aliceVision\/feature\/PointFeature.hpp>\n#include <aliceVision\/feature\/RegionsPerView.hpp>\n#include <aliceVision\/matching\/IndMatch.hpp>\n#include <aliceVision\/matchingImageCollection\/GeometricFilterMatrix.hpp>\n\n#include <boost\/progress.hpp>\n\n#include <vector>\n#include <map>\n\nnamespace aliceVision {\nnamespace matchingImageCollection {\n\nusing namespace aliceVision::matching;\n\n\/**\n * @brief Perform robust model estimation (with optional guided_matching)\n * or all the pairs and regions correspondences contained in the putativeMatches set.\n * Allow to keep only geometrically coherent matches.\n * It discards pairs that do not lead to a valid robust model estimation.\n * @param[out] geometricMatches\n * @param[in] sfmData\n * @param[in] regionsPerView\n * @param[in] functor\n * @param[in] putativeMatches\n * @param[in] guidedMatching\n * @param[in] distanceRatio\n *\/\ntemplate<typename GeometryFunctor>\nvoid robustModelEstimation(\n PairwiseMatches& out_geometricMatches,\n const sfm::SfMData* sfmData,\n const feature::RegionsPerView& regionsPerView,\n const GeometryFunctor& functor,\n const PairwiseMatches& putativeMatches,\n const bool guidedMatching = false,\n const double distanceRatio = 0.6)\n{\n out_geometricMatches.clear();\n\n boost::progress_display progressBar(putativeMatches.size(), std::cout, \"Robust Model Estimation\\n\");\n \n#pragma omp parallel for schedule(dynamic)\n for (int i = 0; i < (int)putativeMatches.size(); ++i)\n {\n PairwiseMatches::const_iterator iter = putativeMatches.begin();\n std::advance(iter, i);\n\n Pair currentPair = iter->first;\n const MatchesPerDescType& putativeMatchesPerType = iter->second;\n const Pair& imagePair = iter->first;\n\n \/\/ apply the geometric filter (robust model estimation)\n {\n MatchesPerDescType inliers;\n GeometryFunctor geometricFilter = functor; \/\/ use a copy since we are in a multi-thread context\n const EstimationStatus state = geometricFilter.geometricEstimation(sfmData, regionsPerView, imagePair, putativeMatchesPerType, inliers);\n if(state.hasStrongSupport)\n {\n if(guidedMatching)\n {\n MatchesPerDescType guidedGeometricInliers;\n geometricFilter.Geometry_guided_matching(sfmData, regionsPerView, imagePair, distanceRatio, guidedGeometricInliers);\n \/\/ALICEVISION_LOG_DEBUG(\"#before\/#after: \" << putative_inliers.size() << \"\/\" << guided_geometric_inliers.size());\n std::swap(inliers, guidedGeometricInliers);\n }\n\n#pragma omp critical\n {\n out_geometricMatches.insert(std::make_pair(currentPair, std::move(inliers)));\n }\n\n }\n }\n\n#pragma omp critical\n {\n ++progressBar;\n }\n }\n}\n\n} \/\/ namespace aliceVision\n} \/\/ namespace matchingImageCollection\n\n\n<commit_msg>[matchingImageCollection] `GeometricFilter` fix use const<commit_after>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n#include <aliceVision\/config.hpp>\n#include <aliceVision\/feature\/PointFeature.hpp>\n#include <aliceVision\/feature\/RegionsPerView.hpp>\n#include <aliceVision\/matching\/IndMatch.hpp>\n#include <aliceVision\/matchingImageCollection\/GeometricFilterMatrix.hpp>\n\n#include <boost\/progress.hpp>\n\n#include <vector>\n#include <map>\n\nnamespace aliceVision {\nnamespace matchingImageCollection {\n\nusing namespace aliceVision::matching;\n\n\/**\n * @brief Perform robust model estimation (with optional guided_matching)\n * or all the pairs and regions correspondences contained in the putativeMatches set.\n * Allow to keep only geometrically coherent matches.\n * It discards pairs that do not lead to a valid robust model estimation.\n * @param[out] geometricMatches\n * @param[in] sfmData\n * @param[in] regionsPerView\n * @param[in] functor\n * @param[in] putativeMatches\n * @param[in] guidedMatching\n * @param[in] distanceRatio\n *\/\ntemplate<typename GeometryFunctor>\nvoid robustModelEstimation(\n PairwiseMatches& out_geometricMatches,\n const sfm::SfMData* sfmData,\n const feature::RegionsPerView& regionsPerView,\n const GeometryFunctor& functor,\n const PairwiseMatches& putativeMatches,\n const bool guidedMatching = false,\n const double distanceRatio = 0.6)\n{\n out_geometricMatches.clear();\n\n boost::progress_display progressBar(putativeMatches.size(), std::cout, \"Robust Model Estimation\\n\");\n \n#pragma omp parallel for schedule(dynamic)\n for (int i = 0; i < (int)putativeMatches.size(); ++i)\n {\n PairwiseMatches::const_iterator iter = putativeMatches.begin();\n std::advance(iter, i);\n\n const Pair currentPair = iter->first;\n const MatchesPerDescType& putativeMatchesPerType = iter->second;\n const Pair& imagePair = iter->first;\n\n \/\/ apply the geometric filter (robust model estimation)\n {\n MatchesPerDescType inliers;\n GeometryFunctor geometricFilter = functor; \/\/ use a copy since we are in a multi-thread context\n const EstimationStatus state = geometricFilter.geometricEstimation(sfmData, regionsPerView, imagePair, putativeMatchesPerType, inliers);\n if(state.hasStrongSupport)\n {\n if(guidedMatching)\n {\n MatchesPerDescType guidedGeometricInliers;\n geometricFilter.Geometry_guided_matching(sfmData, regionsPerView, imagePair, distanceRatio, guidedGeometricInliers);\n \/\/ALICEVISION_LOG_DEBUG(\"#before\/#after: \" << putative_inliers.size() << \"\/\" << guided_geometric_inliers.size());\n std::swap(inliers, guidedGeometricInliers);\n }\n\n#pragma omp critical\n {\n out_geometricMatches.insert(std::make_pair(currentPair, std::move(inliers)));\n }\n\n }\n }\n\n#pragma omp critical\n {\n ++progressBar;\n }\n }\n}\n\n} \/\/ namespace matchingImageCollection\n} \/\/ namespace aliceVision\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: splits.cpp\n * Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"tr\/mo\/microoperations.h\"\n#include \"tr\/mo\/microsurgery.h\"\n#include \"tr\/mo\/blocks.h\"\n#include \"tr\/mo\/nodemoutils.h\"\n\n#include \"common\/bit_set.h\"\n\ninline int canAcceptNodes(xptr block_xptr, int desc_size)\n{\n if (block_xptr != XNULL) {\n CHECKP(block_xptr);\n node_blk_hdr * block = getBlockHeader(block_xptr);\n\n return (block->dsc_size >= desc_size) ? (getPageDescriptorCapacitySP(block) - block->count) : 0;\n }\n return 0;\n}\n\n\ninline bool tryWidenSingleBlock(xptr block_ptr, node_blk_hdr * block, int required_dsc_size)\n{\n CHECKP(block_ptr);\n xptr * endpoint = (xptr *) ((char *) XADDR(block_ptr) + PAGE_SIZE) - 1;\n int total_cells = getPageDescriptorCapacitySP(block_ptr);\n int new_total_cells;\n bit_set free_cells(total_cells);\n void * indir;\n int save_indir_count;\n int i;\n\n free_cells.clear();\n\n indir = getBlockPointer(block_ptr, getBlockHeaderCP(block_ptr)->free_first_indir);\n\n try {\n while (indir != NULL) {\n i = endpoint - ((xptr *) indir);\n free_cells.setAt(i);\n\n indir = getBlockPointer(block_ptr, * (shft *) indir);\n };\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n try {\n i = total_cells - 1;\n while (i >= 0 && free_cells.testAt(i)) { i--; }\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n save_indir_count = i + 1;\n\n if (save_indir_count * (required_dsc_size + sizeof(xptr)) <= (PAGE_SIZE - sizeof(node_blk_hdr))) {\n shft prev;\n shft indir_count = block->indir_count;\n\n widenBlockDescriptor(block_ptr, required_dsc_size, save_indir_count);\n\n WRITEP(block_ptr);\n block->indir_count = indir_count;\n new_total_cells = getPageDescriptorCapacitySP(block_ptr);\n U_ASSERT(new_total_cells <= total_cells);\n total_cells = new_total_cells;\n U_ASSERT(total_cells >= save_indir_count);\n\n try {\n prev = 0;\n for (i = total_cells - 1; i >=0 ; i--) {\n if (free_cells.testAt(i)) {\n void * iptr = endpoint - i;\n * (shft *) iptr = prev;\n prev = calcShift(iptr);\n }\n }\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n getBlockHeader(block_ptr)->free_first_indir = prev;\n\n MOCHECK(checkBlock(block_ptr));\n\n return true;\n }\n\n return false;\n}\n\nxptr widenDescriptor(xptr node_xptr, int pos, xptr set_value)\n{\n xptr node_indir = getIndirectionSafeCP(node_xptr);\n node_blk_hdr * block = getBlockHeaderCP(node_xptr);\n int required_dsc_size = size_of_node(block->node_type) + (pos + 1) * sizeof(xptr);\n int node_position = 0;\n int nodes_to_move;\n xptr dest_block;\n bool widened = false;\n\n molog((\"MOLOG (0x%llx, %d, 0x%llx)\", node_xptr.to_logical_int(), pos, set_value.to_logical_int()));\n\n if (MAX(block->count, block->indir_count) * (required_dsc_size + sizeof(xptr)) <= (PAGE_SIZE - sizeof(node_blk_hdr))) {\n widened = tryWidenSingleBlock(block_xptr(node_xptr), block, required_dsc_size);\n }\n\n if (!widened) {\n for (node_base_t * node_it = getDsc((char *) xaddr(block_xptr(node_xptr)), block->desc_first);\n (void *) node_it != XADDR(node_xptr);\n node_it = getDsc((char *) xaddr(block_xptr(node_xptr)), node_it->desc_next)) {\n U_ASSERT(node_it != NULL);\n node_position++;\n }\n\n if (block->count - node_position < node_position + 1) {\n \/* Move last nodes to the next block *\/\n nodes_to_move = block->count - node_position;\n\n dest_block = block->nblk;\n while (nodes_to_move > 0) {\n int n;\n\n if ((n = canAcceptNodes(dest_block, required_dsc_size)) > 0) {\n n = MIN(n, nodes_to_move);\n shiftManyNodesToNextBlock(block_xptr(node_xptr), n);\n nodes_to_move -= n;\n }\n\n if (nodes_to_move == 0) { break; }\n CHECKP(node_xptr);\n dest_block = createBlock(XNULL, block_xptr(node_xptr));\n }\n } else {\n \/* Move first nodes to the previous block *\/\n nodes_to_move = node_position + 1;\n\n dest_block = block->pblk;\n while (nodes_to_move > 0) {\n int n;\n\n if ((n = canAcceptNodes(dest_block, required_dsc_size)) > 0) {\n n = MIN(n, nodes_to_move);\n shiftManyNodesToPreviousBlock(block_xptr(node_xptr), n);\n nodes_to_move -= n;\n }\n\n if (nodes_to_move == 0) { break; }\n CHECKP(node_xptr);\n dest_block = createBlock(block->snode, block->pblk);\n }\n }\n }\n\n node_xptr = indirectionDereferenceCP(node_indir);\n setNodeChild(node_xptr, pos, set_value);\n\n return node_xptr;\n}\n\n\nxptr splitBlock(xptr node_xptr)\n{\n xptr nblk, pblk, node_indir;\n node_blk_hdr * block;\n int desc_size;\n int desc_count;\n\n CHECKP(node_xptr);\n node_indir = getIndirectionSafeCP(node_xptr);\n block = getBlockHeader(node_xptr);\n desc_size = block->dsc_size;\n desc_count = block->count;\n nblk = block->nblk;\n pblk = block->pblk;\n\n if (canAcceptNodes(pblk, desc_size) > 1) {\n shiftOneNodeToPreviousBlock(block_xptr(node_xptr));\n } else if (canAcceptNodes(nblk, desc_size) > 1) {\n shiftOneNodeToNextBlock(block_xptr(node_xptr));\n } else {\n U_ASSERT(desc_count > 3);\n createBlock(XNULL, block_xptr(node_xptr));\n shiftManyNodesToNextBlock(block_xptr(node_xptr), desc_count \/ 2);\n }\n\n return indirectionDereferenceCP(node_indir);\n}\n<commit_msg>Block split fix.<commit_after>\/*\n * File: splits.cpp\n * Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"tr\/mo\/microoperations.h\"\n#include \"tr\/mo\/microsurgery.h\"\n#include \"tr\/mo\/blocks.h\"\n#include \"tr\/mo\/nodemoutils.h\"\n\n#include \"common\/bit_set.h\"\n\ninline int canAcceptNodes(xptr block_xptr, int desc_size)\n{\n if (block_xptr != XNULL) {\n CHECKP(block_xptr);\n node_blk_hdr * block = getBlockHeader(block_xptr);\n\n return (block->dsc_size >= desc_size) ? (getPageDescriptorCapacitySP(block) - block->count) : 0;\n }\n return 0;\n}\n\n\ninline bool tryWidenSingleBlock(xptr block_ptr, node_blk_hdr * block, int required_dsc_size)\n{\n CHECKP(block_ptr);\n xptr * endpoint = (xptr *) ((char *) XADDR(block_ptr) + PAGE_SIZE) - 1;\n int total_cells = getPageDescriptorCapacitySP(block_ptr);\n int new_total_cells;\n bit_set free_cells(total_cells);\n void * indir;\n int save_indir_count;\n int i;\n\n free_cells.clear();\n\n indir = getBlockPointer(block_ptr, getBlockHeaderCP(block_ptr)->free_first_indir);\n\n try {\n while (indir != NULL) {\n i = endpoint - ((xptr *) indir);\n free_cells.setAt(i);\n\n indir = getBlockPointer(block_ptr, * (shft *) indir);\n };\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n try {\n i = total_cells - 1;\n while (i >= 0 && free_cells.testAt(i)) { i--; }\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n save_indir_count = i + 1;\n\n if (save_indir_count * (required_dsc_size + sizeof(xptr)) <= (PAGE_SIZE - sizeof(node_blk_hdr))) {\n shft prev;\n shft indir_count = block->indir_count;\n\n widenBlockDescriptor(block_ptr, required_dsc_size, save_indir_count);\n\n WRITEP(block_ptr);\n block->indir_count = indir_count;\n new_total_cells = getPageDescriptorCapacitySP(block_ptr);\n U_ASSERT(new_total_cells <= total_cells);\n total_cells = new_total_cells;\n U_ASSERT(total_cells >= save_indir_count);\n\n try {\n prev = 0;\n for (i = total_cells - 1; i >=0 ; i--) {\n if (free_cells.testAt(i)) {\n void * iptr = endpoint - i;\n * (shft *) iptr = prev;\n prev = calcShift(iptr);\n }\n }\n } catch (ANY_SE_EXCEPTION) {\n throw SYSTEM_EXCEPTION(\"Exception at tryWidenSingleBlock\");\n }\n\n getBlockHeader(block_ptr)->free_first_indir = prev;\n\n MOCHECK(checkBlock(block_ptr));\n\n return true;\n }\n\n return false;\n}\n\nxptr widenDescriptor(xptr node_xptr, int pos, xptr set_value)\n{\n xptr node_indir = getIndirectionSafeCP(node_xptr);\n node_blk_hdr * block = getBlockHeaderCP(node_xptr);\n int required_dsc_size = size_of_node(block->node_type) + (pos + 1) * sizeof(xptr);\n int node_position = 0;\n int nodes_to_move;\n xptr dest_block;\n bool widened = false;\n\n molog((\"MOLOG (0x%llx, %d, 0x%llx)\", node_xptr.to_logical_int(), pos, set_value.to_logical_int()));\n\n if (MAX(block->count, block->indir_count) * (required_dsc_size + sizeof(xptr)) <= (PAGE_SIZE - sizeof(node_blk_hdr))) {\n widened = tryWidenSingleBlock(block_xptr(node_xptr), block, required_dsc_size);\n }\n\n if (!widened) {\n for (node_base_t * node_it = getDsc((char *) xaddr(block_xptr(node_xptr)), block->desc_first);\n (void *) node_it != XADDR(node_xptr);\n node_it = getDsc((char *) xaddr(block_xptr(node_xptr)), node_it->desc_next)) {\n U_ASSERT(node_it != NULL);\n node_position++;\n }\n\n if (block->count - node_position < node_position + 1) {\n \/* Move last nodes to the next block *\/\n nodes_to_move = block->count - node_position;\n\n dest_block = block->nblk;\n while (nodes_to_move > 0) {\n int n;\n\n if ((n = canAcceptNodes(dest_block, required_dsc_size)) > 0) {\n n = MIN(n, nodes_to_move);\n shiftManyNodesToNextBlock(block_xptr(node_xptr), n);\n nodes_to_move -= n;\n }\n\n if (nodes_to_move == 0) { break; }\n CHECKP(node_xptr);\n dest_block = createBlock(XNULL, block_xptr(node_xptr));\n }\n } else {\n \/* Move first nodes to the previous block *\/\n nodes_to_move = node_position + 1;\n\n dest_block = block->pblk;\n while (nodes_to_move > 0) {\n int n;\n\n if ((n = canAcceptNodes(dest_block, required_dsc_size)) > 0) {\n n = MIN(n, nodes_to_move);\n shiftManyNodesToPreviousBlock(block_xptr(node_xptr), n);\n nodes_to_move -= n;\n }\n\n if (nodes_to_move == 0) { break; }\n CHECKP(node_xptr);\n dest_block = createBlock(block->snode, block->pblk);\n }\n }\n }\n\n node_xptr = indirectionDereferenceCP(node_indir);\n setNodeChild(node_xptr, pos, set_value);\n\n return node_xptr;\n}\n\nxptr splitBlock(xptr node_xptr)\n{\n xptr node_indir;\n node_blk_hdr block;\n\n CHECKP(node_xptr);\n node_indir = getIndirectionSafeCP(node_xptr);\n memcpy(&block, getBlockHeader(node_xptr), getHeaderSize(node_xptr));\n\n if (canAcceptNodes(block.pblk, block.dsc_size) > 1) {\n shiftOneNodeToPreviousBlock(block_xptr(node_xptr));\n } else if (canAcceptNodes(block.nblk, block.dsc_size) > 1) {\n shiftOneNodeToNextBlock(block_xptr(node_xptr));\n } else {\n U_ASSERT(block.count > 3);\n\n xptr new_block = createBlock(XNULL, block_xptr(node_xptr));\n int new_block_capacity = canAcceptNodes(new_block, block.dsc_size);\n int to_move = MIN(block.count \/ 2, new_block_capacity);\n\n U_ASSERT(to_move > 0);\n shiftManyNodesToNextBlock(block_xptr(node_xptr), to_move);\n }\n\n return indirectionDereferenceCP(node_indir);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2016 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ WorkerThread:\n\/\/ Task running thread for ANGLE, similar to a TaskRunner in Chromium.\n\/\/ Might be implemented differently depending on platform.\n\/\/\n\n#include \"libANGLE\/WorkerThread.h\"\n\n#include \"libANGLE\/trace.h\"\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED) || (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n# include <condition_variable>\n# include <future>\n# include <mutex>\n# include <queue>\n# include <thread>\n#endif \/\/ (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED) || (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n\nnamespace angle\n{\n\nWaitableEvent::WaitableEvent() = default;\nWaitableEvent::~WaitableEvent() = default;\n\nvoid WaitableEventDone::wait() {}\n\nbool WaitableEventDone::isReady()\n{\n return true;\n}\n\nWorkerThreadPool::WorkerThreadPool() = default;\nWorkerThreadPool::~WorkerThreadPool() = default;\n\nclass SingleThreadedWaitableEvent final : public WaitableEvent\n{\n public:\n SingleThreadedWaitableEvent() = default;\n ~SingleThreadedWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n};\n\nvoid SingleThreadedWaitableEvent::wait() {}\n\nbool SingleThreadedWaitableEvent::isReady()\n{\n return true;\n}\n\nclass SingleThreadedWorkerPool final : public WorkerThreadPool\n{\n public:\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n};\n\n\/\/ SingleThreadedWorkerPool implementation.\nstd::shared_ptr<WaitableEvent> SingleThreadedWorkerPool::postWorkerTask(\n std::shared_ptr<Closure> task)\n{\n (*task)();\n return std::make_shared<SingleThreadedWaitableEvent>();\n}\n\nvoid SingleThreadedWorkerPool::setMaxThreads(size_t maxThreads) {}\n\nbool SingleThreadedWorkerPool::isAsync()\n{\n return false;\n}\n\n#if (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\nclass AsyncWaitableEvent final : public WaitableEvent\n{\n public:\n AsyncWaitableEvent() : mIsPending(true) {}\n ~AsyncWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n\n private:\n friend class AsyncWorkerPool;\n void setFuture(std::future<void> &&future);\n\n \/\/ To block wait() when the task is still in queue to be run.\n \/\/ Also to protect the concurrent accesses from both main thread and\n \/\/ background threads to the member fields.\n std::mutex mMutex;\n\n bool mIsPending;\n std::condition_variable mCondition;\n std::future<void> mFuture;\n};\n\nvoid AsyncWaitableEvent::setFuture(std::future<void> &&future)\n{\n mFuture = std::move(future);\n}\n\nvoid AsyncWaitableEvent::wait()\n{\n ANGLE_TRACE_EVENT0(\"gpu.angle\", \"AsyncWaitableEvent::wait\");\n {\n std::unique_lock<std::mutex> lock(mMutex);\n mCondition.wait(lock, [this] { return !mIsPending; });\n }\n\n ASSERT(mFuture.valid());\n mFuture.wait();\n}\n\nbool AsyncWaitableEvent::isReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n if (mIsPending)\n {\n return false;\n }\n ASSERT(mFuture.valid());\n return mFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready;\n}\n\nclass AsyncWorkerPool final : public WorkerThreadPool\n{\n public:\n AsyncWorkerPool(size_t maxThreads) : mMaxThreads(maxThreads), mRunningThreads(0) {}\n ~AsyncWorkerPool() override = default;\n\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n\n private:\n void checkToRunPendingTasks();\n\n \/\/ To protect the concurrent accesses from both main thread and background\n \/\/ threads to the member fields.\n std::mutex mMutex;\n\n size_t mMaxThreads;\n size_t mRunningThreads;\n std::queue<std::pair<std::shared_ptr<AsyncWaitableEvent>, std::shared_ptr<Closure>>> mTaskQueue;\n};\n\n\/\/ AsyncWorkerPool implementation.\nstd::shared_ptr<WaitableEvent> AsyncWorkerPool::postWorkerTask(std::shared_ptr<Closure> task)\n{\n ASSERT(mMaxThreads > 0);\n\n auto waitable = std::make_shared<AsyncWaitableEvent>();\n {\n std::lock_guard<std::mutex> lock(mMutex);\n mTaskQueue.push(std::make_pair(waitable, task));\n }\n checkToRunPendingTasks();\n return waitable;\n}\n\nvoid AsyncWorkerPool::setMaxThreads(size_t maxThreads)\n{\n {\n std::lock_guard<std::mutex> lock(mMutex);\n mMaxThreads = (maxThreads == 0xFFFFFFFF ? std::thread::hardware_concurrency() : maxThreads);\n }\n checkToRunPendingTasks();\n}\n\nbool AsyncWorkerPool::isAsync()\n{\n return true;\n}\n\nvoid AsyncWorkerPool::checkToRunPendingTasks()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n while (mRunningThreads < mMaxThreads && !mTaskQueue.empty())\n {\n auto task = mTaskQueue.front();\n mTaskQueue.pop();\n auto waitable = task.first;\n auto closure = task.second;\n\n auto future = std::async(std::launch::async, [closure, this] {\n {\n ANGLE_TRACE_EVENT0(\"gpu.angle\", \"AsyncWorkerPool::RunTask\");\n (*closure)();\n }\n {\n std::lock_guard<std::mutex> lock(mMutex);\n ASSERT(mRunningThreads != 0);\n --mRunningThreads;\n }\n checkToRunPendingTasks();\n });\n\n ++mRunningThreads;\n\n {\n std::lock_guard<std::mutex> waitableLock(waitable->mMutex);\n waitable->mIsPending = false;\n waitable->setFuture(std::move(future));\n }\n waitable->mCondition.notify_all();\n }\n}\n#endif \/\/ (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED)\nclass DelegateWaitableEvent final : public WaitableEvent\n{\n public:\n DelegateWaitableEvent() = default;\n ~DelegateWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n\n void markAsReady();\n\n private:\n \/\/ To protect the concurrent accesses from both main thread and background\n \/\/ threads to the member fields.\n std::mutex mMutex;\n\n bool mIsReady = false;\n std::condition_variable mCondition;\n};\n\nvoid DelegateWaitableEvent::markAsReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n mIsReady = true;\n mCondition.notify_all();\n}\n\nvoid DelegateWaitableEvent::wait()\n{\n std::unique_lock<std::mutex> lock(mMutex);\n mCondition.wait(lock, [this] { return mIsReady; });\n}\n\nbool DelegateWaitableEvent::isReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n return mIsReady;\n}\n\nclass DelegateWorkerPool final : public WorkerThreadPool\n{\n public:\n DelegateWorkerPool() = default;\n ~DelegateWorkerPool() override = default;\n\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n};\n\n\/\/ A function wrapper to execute the closure and to notify the waitable\n\/\/ event after the execution.\nclass DelegateWorkerTask\n{\n public:\n DelegateWorkerTask(std::shared_ptr<Closure> task,\n std::shared_ptr<DelegateWaitableEvent> waitable)\n : mTask(task), mWaitable(waitable)\n {}\n DelegateWorkerTask() = delete;\n DelegateWorkerTask(DelegateWorkerTask &) = delete;\n\n static void RunTask(void *userData)\n {\n DelegateWorkerTask *workerTask = static_cast<DelegateWorkerTask *>(userData);\n (*workerTask->mTask)();\n workerTask->mWaitable->markAsReady();\n\n \/\/ Delete the task after its execution.\n delete workerTask;\n }\n\n private:\n ~DelegateWorkerTask() = default;\n\n std::shared_ptr<Closure> mTask;\n std::shared_ptr<DelegateWaitableEvent> mWaitable;\n};\n\nstd::shared_ptr<WaitableEvent> DelegateWorkerPool::postWorkerTask(std::shared_ptr<Closure> task)\n{\n auto waitable = std::make_shared<DelegateWaitableEvent>();\n\n \/\/ The task will be deleted bu RunTask(...) its execution.\n DelegateWorkerTask *workerTask = new DelegateWorkerTask(task, waitable);\n auto *platform = ANGLEPlatformCurrent();\n platform->postWorkerTask(platform, DelegateWorkerTask::RunTask, workerTask);\n\n return waitable;\n}\n\nvoid DelegateWorkerPool::setMaxThreads(size_t maxThreads) {}\n\nbool DelegateWorkerPool::isAsync()\n{\n return true;\n}\n#endif\n\n\/\/ static\nstd::shared_ptr<WorkerThreadPool> WorkerThreadPool::Create(bool multithreaded)\n{\n std::shared_ptr<WorkerThreadPool> pool(nullptr);\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED)\n const bool hasPostWorkerTaskImpl = ANGLEPlatformCurrent()->postWorkerTask;\n if (hasPostWorkerTaskImpl && multithreaded)\n {\n pool = std::shared_ptr<WorkerThreadPool>(new DelegateWorkerPool());\n }\n#endif\n#if (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n if (!pool && multithreaded)\n {\n pool = std::shared_ptr<WorkerThreadPool>(\n new AsyncWorkerPool(std::thread::hardware_concurrency()));\n }\n#endif\n if (!pool)\n {\n return std::shared_ptr<WorkerThreadPool>(new SingleThreadedWorkerPool());\n }\n return pool;\n}\n\n\/\/ static\nstd::shared_ptr<WaitableEvent> WorkerThreadPool::PostWorkerTask(\n std::shared_ptr<WorkerThreadPool> pool,\n std::shared_ptr<Closure> task)\n{\n std::shared_ptr<WaitableEvent> event = pool->postWorkerTask(task);\n if (event.get())\n {\n event->setWorkerThreadPool(pool);\n }\n return event;\n}\n\n} \/\/ namespace angle\n<commit_msg>Fix typos in comment<commit_after>\/\/\n\/\/ Copyright 2016 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ WorkerThread:\n\/\/ Task running thread for ANGLE, similar to a TaskRunner in Chromium.\n\/\/ Might be implemented differently depending on platform.\n\/\/\n\n#include \"libANGLE\/WorkerThread.h\"\n\n#include \"libANGLE\/trace.h\"\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED) || (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n# include <condition_variable>\n# include <future>\n# include <mutex>\n# include <queue>\n# include <thread>\n#endif \/\/ (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED) || (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n\nnamespace angle\n{\n\nWaitableEvent::WaitableEvent() = default;\nWaitableEvent::~WaitableEvent() = default;\n\nvoid WaitableEventDone::wait() {}\n\nbool WaitableEventDone::isReady()\n{\n return true;\n}\n\nWorkerThreadPool::WorkerThreadPool() = default;\nWorkerThreadPool::~WorkerThreadPool() = default;\n\nclass SingleThreadedWaitableEvent final : public WaitableEvent\n{\n public:\n SingleThreadedWaitableEvent() = default;\n ~SingleThreadedWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n};\n\nvoid SingleThreadedWaitableEvent::wait() {}\n\nbool SingleThreadedWaitableEvent::isReady()\n{\n return true;\n}\n\nclass SingleThreadedWorkerPool final : public WorkerThreadPool\n{\n public:\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n};\n\n\/\/ SingleThreadedWorkerPool implementation.\nstd::shared_ptr<WaitableEvent> SingleThreadedWorkerPool::postWorkerTask(\n std::shared_ptr<Closure> task)\n{\n (*task)();\n return std::make_shared<SingleThreadedWaitableEvent>();\n}\n\nvoid SingleThreadedWorkerPool::setMaxThreads(size_t maxThreads) {}\n\nbool SingleThreadedWorkerPool::isAsync()\n{\n return false;\n}\n\n#if (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\nclass AsyncWaitableEvent final : public WaitableEvent\n{\n public:\n AsyncWaitableEvent() : mIsPending(true) {}\n ~AsyncWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n\n private:\n friend class AsyncWorkerPool;\n void setFuture(std::future<void> &&future);\n\n \/\/ To block wait() when the task is still in queue to be run.\n \/\/ Also to protect the concurrent accesses from both main thread and\n \/\/ background threads to the member fields.\n std::mutex mMutex;\n\n bool mIsPending;\n std::condition_variable mCondition;\n std::future<void> mFuture;\n};\n\nvoid AsyncWaitableEvent::setFuture(std::future<void> &&future)\n{\n mFuture = std::move(future);\n}\n\nvoid AsyncWaitableEvent::wait()\n{\n ANGLE_TRACE_EVENT0(\"gpu.angle\", \"AsyncWaitableEvent::wait\");\n {\n std::unique_lock<std::mutex> lock(mMutex);\n mCondition.wait(lock, [this] { return !mIsPending; });\n }\n\n ASSERT(mFuture.valid());\n mFuture.wait();\n}\n\nbool AsyncWaitableEvent::isReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n if (mIsPending)\n {\n return false;\n }\n ASSERT(mFuture.valid());\n return mFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready;\n}\n\nclass AsyncWorkerPool final : public WorkerThreadPool\n{\n public:\n AsyncWorkerPool(size_t maxThreads) : mMaxThreads(maxThreads), mRunningThreads(0) {}\n ~AsyncWorkerPool() override = default;\n\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n\n private:\n void checkToRunPendingTasks();\n\n \/\/ To protect the concurrent accesses from both main thread and background\n \/\/ threads to the member fields.\n std::mutex mMutex;\n\n size_t mMaxThreads;\n size_t mRunningThreads;\n std::queue<std::pair<std::shared_ptr<AsyncWaitableEvent>, std::shared_ptr<Closure>>> mTaskQueue;\n};\n\n\/\/ AsyncWorkerPool implementation.\nstd::shared_ptr<WaitableEvent> AsyncWorkerPool::postWorkerTask(std::shared_ptr<Closure> task)\n{\n ASSERT(mMaxThreads > 0);\n\n auto waitable = std::make_shared<AsyncWaitableEvent>();\n {\n std::lock_guard<std::mutex> lock(mMutex);\n mTaskQueue.push(std::make_pair(waitable, task));\n }\n checkToRunPendingTasks();\n return waitable;\n}\n\nvoid AsyncWorkerPool::setMaxThreads(size_t maxThreads)\n{\n {\n std::lock_guard<std::mutex> lock(mMutex);\n mMaxThreads = (maxThreads == 0xFFFFFFFF ? std::thread::hardware_concurrency() : maxThreads);\n }\n checkToRunPendingTasks();\n}\n\nbool AsyncWorkerPool::isAsync()\n{\n return true;\n}\n\nvoid AsyncWorkerPool::checkToRunPendingTasks()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n while (mRunningThreads < mMaxThreads && !mTaskQueue.empty())\n {\n auto task = mTaskQueue.front();\n mTaskQueue.pop();\n auto waitable = task.first;\n auto closure = task.second;\n\n auto future = std::async(std::launch::async, [closure, this] {\n {\n ANGLE_TRACE_EVENT0(\"gpu.angle\", \"AsyncWorkerPool::RunTask\");\n (*closure)();\n }\n {\n std::lock_guard<std::mutex> lock(mMutex);\n ASSERT(mRunningThreads != 0);\n --mRunningThreads;\n }\n checkToRunPendingTasks();\n });\n\n ++mRunningThreads;\n\n {\n std::lock_guard<std::mutex> waitableLock(waitable->mMutex);\n waitable->mIsPending = false;\n waitable->setFuture(std::move(future));\n }\n waitable->mCondition.notify_all();\n }\n}\n#endif \/\/ (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED)\nclass DelegateWaitableEvent final : public WaitableEvent\n{\n public:\n DelegateWaitableEvent() = default;\n ~DelegateWaitableEvent() override = default;\n\n void wait() override;\n bool isReady() override;\n\n void markAsReady();\n\n private:\n \/\/ To protect the concurrent accesses from both main thread and background\n \/\/ threads to the member fields.\n std::mutex mMutex;\n\n bool mIsReady = false;\n std::condition_variable mCondition;\n};\n\nvoid DelegateWaitableEvent::markAsReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n mIsReady = true;\n mCondition.notify_all();\n}\n\nvoid DelegateWaitableEvent::wait()\n{\n std::unique_lock<std::mutex> lock(mMutex);\n mCondition.wait(lock, [this] { return mIsReady; });\n}\n\nbool DelegateWaitableEvent::isReady()\n{\n std::lock_guard<std::mutex> lock(mMutex);\n return mIsReady;\n}\n\nclass DelegateWorkerPool final : public WorkerThreadPool\n{\n public:\n DelegateWorkerPool() = default;\n ~DelegateWorkerPool() override = default;\n\n std::shared_ptr<WaitableEvent> postWorkerTask(std::shared_ptr<Closure> task) override;\n\n void setMaxThreads(size_t maxThreads) override;\n bool isAsync() override;\n};\n\n\/\/ A function wrapper to execute the closure and to notify the waitable\n\/\/ event after the execution.\nclass DelegateWorkerTask\n{\n public:\n DelegateWorkerTask(std::shared_ptr<Closure> task,\n std::shared_ptr<DelegateWaitableEvent> waitable)\n : mTask(task), mWaitable(waitable)\n {}\n DelegateWorkerTask() = delete;\n DelegateWorkerTask(DelegateWorkerTask &) = delete;\n\n static void RunTask(void *userData)\n {\n DelegateWorkerTask *workerTask = static_cast<DelegateWorkerTask *>(userData);\n (*workerTask->mTask)();\n workerTask->mWaitable->markAsReady();\n\n \/\/ Delete the task after its execution.\n delete workerTask;\n }\n\n private:\n ~DelegateWorkerTask() = default;\n\n std::shared_ptr<Closure> mTask;\n std::shared_ptr<DelegateWaitableEvent> mWaitable;\n};\n\nstd::shared_ptr<WaitableEvent> DelegateWorkerPool::postWorkerTask(std::shared_ptr<Closure> task)\n{\n auto waitable = std::make_shared<DelegateWaitableEvent>();\n\n \/\/ The task will be deleted by DelegateWorkerTask::RunTask(...) after its execution.\n DelegateWorkerTask *workerTask = new DelegateWorkerTask(task, waitable);\n auto *platform = ANGLEPlatformCurrent();\n platform->postWorkerTask(platform, DelegateWorkerTask::RunTask, workerTask);\n\n return waitable;\n}\n\nvoid DelegateWorkerPool::setMaxThreads(size_t maxThreads) {}\n\nbool DelegateWorkerPool::isAsync()\n{\n return true;\n}\n#endif\n\n\/\/ static\nstd::shared_ptr<WorkerThreadPool> WorkerThreadPool::Create(bool multithreaded)\n{\n std::shared_ptr<WorkerThreadPool> pool(nullptr);\n\n#if (ANGLE_DELEGATE_WORKERS == ANGLE_ENABLED)\n const bool hasPostWorkerTaskImpl = ANGLEPlatformCurrent()->postWorkerTask;\n if (hasPostWorkerTaskImpl && multithreaded)\n {\n pool = std::shared_ptr<WorkerThreadPool>(new DelegateWorkerPool());\n }\n#endif\n#if (ANGLE_STD_ASYNC_WORKERS == ANGLE_ENABLED)\n if (!pool && multithreaded)\n {\n pool = std::shared_ptr<WorkerThreadPool>(\n new AsyncWorkerPool(std::thread::hardware_concurrency()));\n }\n#endif\n if (!pool)\n {\n return std::shared_ptr<WorkerThreadPool>(new SingleThreadedWorkerPool());\n }\n return pool;\n}\n\n\/\/ static\nstd::shared_ptr<WaitableEvent> WorkerThreadPool::PostWorkerTask(\n std::shared_ptr<WorkerThreadPool> pool,\n std::shared_ptr<Closure> task)\n{\n std::shared_ptr<WaitableEvent> event = pool->postWorkerTask(task);\n if (event.get())\n {\n event->setWorkerThreadPool(pool);\n }\n return event;\n}\n\n} \/\/ namespace angle\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"meshobjectreader.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/object\/meshobject.h\"\n#include \"renderer\/modeling\/object\/triangle.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/exceptions\/exception.h\"\n#include \"foundation\/core\/exceptions\/exceptionioerror.h\"\n#include \"foundation\/math\/triangulator.h\"\n#include \"foundation\/mesh\/imeshbuilder.h\"\n#include \"foundation\/mesh\/imeshfilereader.h\"\n#include \"foundation\/mesh\/objmeshfilereader.h\"\n#include \"foundation\/utility\/foreach.h\"\n#include \"foundation\/utility\/memory.h\"\n#include \"foundation\/utility\/stopwatch.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include <vector>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ MeshObjectArray class implementation.\n\/\/\n\nDEFINE_ARRAY(MeshObjectArray);\n\n\n\/\/\n\/\/ MeshObjectReader class implementation.\n\/\/\n\nnamespace\n{\n\/\/\n\/\/ Disable erroneous Visual Studio warning C4267:\n\/\/\n\/\/ conversion from 'size_t' to 'foundation::uint32', possible loss of data\n\/\/\n\/\/ for this piece of code. This is a workaround for a bug in Visual Studio:\n\/\/\n\/\/ https:\/\/connect.microsoft.com\/VisualStudio\/feedback\/ViewFeedback.aspx?FeedbackID=253172\n\/\/\n\n#pragma warning (push)\n#pragma warning (disable : 4267)\n\n \/\/\n \/\/ Mesh object builder.\n \/\/\n\n class MeshObjectBuilder\n : public IMeshBuilder\n {\n public:\n typedef vector<MeshObject*> MeshObjectVector;\n\n MeshObjectBuilder(\n const ParamArray& params,\n const string& base_object_name)\n : m_params(params)\n , m_base_object_name(base_object_name)\n , m_untitled_mesh_counter(0)\n {\n }\n\n const MeshObjectVector& get_objects() const\n {\n return m_objects;\n }\n\n virtual void begin_mesh(const string& name)\n {\n string object_name;\n if (name.empty())\n {\n \/\/ Anonymous meshes are assigned increasing numbers, starting at 0.\n object_name = m_base_object_name + \".\" +\n to_string<size_t>(m_untitled_mesh_counter++);\n }\n else\n {\n \/\/ Generate the object name from the base name and the mesh name.\n object_name = m_base_object_name + \".\" + name;\n }\n\n \/\/ Create an empty mesh object.\n m_objects.push_back(\n MeshObjectFactory::create(object_name.c_str(), m_params).release());\n\n m_face_count = 0;\n m_triangulation_errors = 0;\n }\n\n virtual void end_mesh()\n {\n \/\/ Print the number of faces that could not be triangulated (if any).\n if (m_triangulation_errors > 0)\n {\n RENDERER_LOG_WARNING(\n \"%s polygonal %s (out of %s) could not be triangulated\",\n pretty_int(m_triangulation_errors).c_str(),\n plural(m_triangulation_errors, \"face\").c_str(),\n pretty_int(m_face_count).c_str());\n }\n\n \/\/ Print the number of vertices and triangles in the mesh.\n const size_t vertex_count = m_objects.back()->get_vertex_count();\n const size_t triangle_count = m_objects.back()->get_triangle_count();\n RENDERER_LOG_INFO(\n \"loaded mesh object \\\"%s\\\" (%s %s, %s %s)\",\n m_objects.back()->get_name(),\n pretty_int(vertex_count).c_str(),\n plural(vertex_count, \"vertex\", \"vertices\").c_str(),\n pretty_int(triangle_count).c_str(),\n plural(triangle_count, \"triangle\").c_str());\n }\n\n virtual size_t push_vertex(const Vector3d& v)\n {\n return m_objects.back()->push_vertex(GVector3(v));\n }\n\n virtual size_t push_vertex_normal(const Vector3d& v)\n {\n return m_objects.back()->push_vertex_normal(GVector3(v));\n }\n\n virtual size_t push_tex_coords(const Vector2d& v)\n {\n return m_objects.back()->push_tex_coords(GVector2(v));\n }\n\n virtual void begin_face(const size_t vertex_count)\n {\n assert(vertex_count >= 3);\n\n clear_keep_memory(m_face_vertices);\n clear_keep_memory(m_face_normals);\n clear_keep_memory(m_face_tex_coords);\n\n ++m_face_count;\n\n m_vertex_count = vertex_count;\n m_face_material = Triangle::None;\n }\n\n virtual void end_face()\n {\n assert(m_face_vertices.size() == m_vertex_count);\n assert(m_face_normals.size() == 0 || m_face_normals.size() == m_vertex_count);\n assert(m_face_tex_coords.size() == 0 || m_face_tex_coords.size() == m_vertex_count);\n\n if (m_vertex_count > 3)\n {\n \/\/ Create the polygon to triangulate.\n clear_keep_memory(m_polygon);\n for (size_t i = 0; i < m_face_vertices.size(); ++i)\n {\n m_polygon.push_back(\n Vector3d(m_objects.back()->get_vertex(m_face_vertices[i])));\n }\n\n \/\/ Triangulate the polygonal face.\n clear_keep_memory(m_triangles);\n if (!m_triangulator.triangulate(m_polygon, m_triangles))\n {\n \/\/ Skip problematic polygonal faces.\n ++m_triangulation_errors;\n return;\n }\n\n \/\/ Insert all triangles of the triangulation into the mesh.\n for (size_t i = 0; i < m_triangles.size(); i += 3)\n {\n insert_triangle(\n m_triangles[i + 0],\n m_triangles[i + 1],\n m_triangles[i + 2]);\n }\n }\n else\n {\n \/\/ The face is already a triangle, no triangulation is necessary.\n insert_triangle(0, 1, 2);\n }\n }\n\n virtual void set_face_vertices(const size_t vertices[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_vertices.push_back(static_cast<uint32>(vertices[i]));\n }\n\n virtual void set_face_vertex_normals(const size_t vertex_normals[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_normals.push_back(static_cast<uint32>(vertex_normals[i]));\n }\n\n virtual void set_face_vertex_tex_coords(const size_t tex_coords[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_tex_coords.push_back(static_cast<uint32>(tex_coords[i]));\n }\n\n virtual void set_face_material(const size_t material)\n {\n m_face_material = static_cast<uint32>(material);\n }\n\n private:\n ParamArray m_params;\n const string m_base_object_name;\n size_t m_untitled_mesh_counter;\n MeshObjectVector m_objects;\n\n size_t m_vertex_count;\n vector<uint32> m_face_vertices;\n vector<uint32> m_face_normals;\n vector<uint32> m_face_tex_coords;\n uint32 m_face_material;\n\n Triangulator<double> m_triangulator;\n vector<Vector3d> m_polygon;\n vector<size_t> m_triangles;\n\n size_t m_face_count;\n size_t m_triangulation_errors;\n\n void insert_triangle(\n const size_t v0_index,\n const size_t v1_index,\n const size_t v2_index)\n {\n Triangle triangle;\n\n \/\/ Set triangle vertices.\n triangle.m_v0 = m_face_vertices[v0_index];\n triangle.m_v1 = m_face_vertices[v1_index];\n triangle.m_v2 = m_face_vertices[v2_index];\n\n \/\/ Set triangle vertex normals.\n if (m_face_normals.size() == m_vertex_count)\n {\n triangle.m_n0 = m_face_normals[v0_index];\n triangle.m_n1 = m_face_normals[v1_index];\n triangle.m_n2 = m_face_normals[v2_index];\n }\n else\n {\n \/\/ Fetch the triangle vertices.\n const Vector3d v0 = Vector3d(m_objects.back()->get_vertex(triangle.m_v0));\n const Vector3d v1 = Vector3d(m_objects.back()->get_vertex(triangle.m_v1));\n const Vector3d v2 = Vector3d(m_objects.back()->get_vertex(triangle.m_v2));\n\n \/\/ Compute the geometric normal to the triangle.\n const Vector3d geometric_normal = normalize(cross(v1 - v0, v2 - v0));\n\n \/\/ Insert the geometric normal into the mesh.\n const size_t geometric_normal_index =\n m_objects.back()->push_vertex_normal(GVector3(geometric_normal));\n\n \/\/ Assign the geometric normal to all vertices of the triangle.\n triangle.m_n0 = geometric_normal_index;\n triangle.m_n1 = geometric_normal_index;\n triangle.m_n2 = geometric_normal_index;\n }\n\n \/\/ Set triangle vertex texture coordinates (if any).\n if (m_face_tex_coords.size() == m_vertex_count)\n {\n triangle.m_a0 = m_face_tex_coords[v0_index];\n triangle.m_a1 = m_face_tex_coords[v1_index];\n triangle.m_a2 = m_face_tex_coords[v2_index];\n }\n else\n {\n triangle.m_a0 = Triangle::None;\n triangle.m_a1 = Triangle::None;\n triangle.m_a2 = Triangle::None;\n }\n\n \/\/ Set triangle material.\n\/\/ triangle.m_pa = m_face_material;\n triangle.m_pa = 0;\n\n \/\/ Insert the triangle into the mesh.\n m_objects.back()->push_triangle(triangle);\n }\n };\n\n#pragma warning (pop)\n}\n\nMeshObjectArray MeshObjectReader::read(\n const char* filename,\n const char* base_object_name,\n const ParamArray& params)\n{\n assert(filename);\n assert(base_object_name);\n\n OBJMeshFileReader reader;\n MeshObjectBuilder builder(params, base_object_name);\n\n Stopwatch<DefaultWallclockTimer> stopwatch;\n stopwatch.start();\n\n try\n {\n reader.read(filename, builder);\n }\n catch (const OBJMeshFileReader::ExceptionInvalidFaceDef& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: invalid face definition on line \" FMT_SIZE_T,\n filename,\n e.m_line);\n return MeshObjectArray();\n }\n catch (const OBJMeshFileReader::ExceptionParseError& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: parse error on line \" FMT_SIZE_T,\n filename,\n e.m_line);\n return MeshObjectArray();\n }\n catch (const ExceptionIOError&)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: i\/o error\",\n filename);\n return MeshObjectArray();\n }\n catch (const Exception& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: %s\",\n filename,\n e.what());\n return MeshObjectArray();\n }\n\n stopwatch.measure();\n\n MeshObjectArray objects;\n for (const_each<vector<MeshObject*> > i = builder.get_objects(); i; ++i)\n objects.push_back(*i);\n\n \/\/ Print the number of loaded objects.\n RENDERER_LOG_INFO(\n \"loaded mesh file %s (%s %s) in %s\",\n filename,\n pretty_int(objects.size()).c_str(),\n plural(objects.size(), \"object\").c_str(),\n pretty_time(stopwatch.get_seconds()).c_str());\n\n return objects;\n}\n\n} \/\/ namespace renderer\n<commit_msg>removed obsolete #pragma directives, cleaned up and simplified code.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"meshobjectreader.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/object\/meshobject.h\"\n#include \"renderer\/modeling\/object\/triangle.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/exceptions\/exception.h\"\n#include \"foundation\/core\/exceptions\/exceptionioerror.h\"\n#include \"foundation\/math\/triangulator.h\"\n#include \"foundation\/mesh\/imeshbuilder.h\"\n#include \"foundation\/mesh\/imeshfilereader.h\"\n#include \"foundation\/mesh\/objmeshfilereader.h\"\n#include \"foundation\/utility\/foreach.h\"\n#include \"foundation\/utility\/memory.h\"\n#include \"foundation\/utility\/stopwatch.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include <vector>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ MeshObjectArray class implementation.\n\/\/\n\nDEFINE_ARRAY(MeshObjectArray);\n\n\n\/\/\n\/\/ MeshObjectReader class implementation.\n\/\/\n\nnamespace\n{\n class MeshObjectBuilder\n : public IMeshBuilder\n {\n public:\n typedef vector<MeshObject*> MeshObjectVector;\n\n MeshObjectBuilder(\n const ParamArray& params,\n const string& base_object_name)\n : m_params(params)\n , m_base_object_name(base_object_name)\n , m_untitled_mesh_counter(0)\n , m_vertex_count(0)\n , m_face_material(0)\n , m_face_count(0)\n , m_triangulation_error_count(0)\n {\n }\n\n const MeshObjectVector& get_objects() const\n {\n return m_objects;\n }\n\n virtual void begin_mesh(const string& name)\n {\n \/\/ If the mesh has no name, assign it a number (starting with 0).\n const string mesh_name = name.empty() ? to_string(m_untitled_mesh_counter++) : name;\n\n \/\/ Construct the final object name from the base object name and the mesh name.\n const string object_name = m_base_object_name + \".\" + mesh_name;\n\n \/\/ Create an empty mesh object.\n m_objects.push_back(\n MeshObjectFactory::create(object_name.c_str(), m_params).release());\n\n m_face_count = 0;\n m_triangulation_error_count = 0;\n }\n\n virtual void end_mesh()\n {\n \/\/ Print the number of faces that could not be triangulated (if any).\n if (m_triangulation_error_count > 0)\n {\n RENDERER_LOG_WARNING(\n \"%s polygonal %s (out of %s) could not be triangulated\",\n pretty_int(m_triangulation_error_count).c_str(),\n plural(m_triangulation_error_count, \"face\").c_str(),\n pretty_int(m_face_count).c_str());\n }\n\n \/\/ Print the number of vertices and triangles in the mesh.\n const size_t vertex_count = m_objects.back()->get_vertex_count();\n const size_t triangle_count = m_objects.back()->get_triangle_count();\n RENDERER_LOG_INFO(\n \"loaded mesh object \\\"%s\\\" (%s %s, %s %s)\",\n m_objects.back()->get_name(),\n pretty_int(vertex_count).c_str(),\n plural(vertex_count, \"vertex\", \"vertices\").c_str(),\n pretty_int(triangle_count).c_str(),\n plural(triangle_count, \"triangle\").c_str());\n }\n\n virtual size_t push_vertex(const Vector3d& v)\n {\n return m_objects.back()->push_vertex(GVector3(v));\n }\n\n virtual size_t push_vertex_normal(const Vector3d& v)\n {\n return m_objects.back()->push_vertex_normal(GVector3(v));\n }\n\n virtual size_t push_tex_coords(const Vector2d& v)\n {\n return m_objects.back()->push_tex_coords(GVector2(v));\n }\n\n virtual void begin_face(const size_t vertex_count)\n {\n assert(vertex_count >= 3);\n\n clear_keep_memory(m_face_vertices);\n clear_keep_memory(m_face_normals);\n clear_keep_memory(m_face_tex_coords);\n\n ++m_face_count;\n\n m_vertex_count = vertex_count;\n m_face_material = Triangle::None;\n }\n\n virtual void end_face()\n {\n assert(m_face_vertices.size() == m_vertex_count);\n assert(m_face_normals.size() == 0 || m_face_normals.size() == m_vertex_count);\n assert(m_face_tex_coords.size() == 0 || m_face_tex_coords.size() == m_vertex_count);\n\n if (m_vertex_count > 3)\n {\n \/\/ Create the polygon to triangulate.\n clear_keep_memory(m_polygon);\n for (size_t i = 0; i < m_vertex_count; ++i)\n {\n m_polygon.push_back(\n Vector3d(m_objects.back()->get_vertex(m_face_vertices[i])));\n }\n\n \/\/ Triangulate the polygonal face.\n clear_keep_memory(m_triangles);\n if (!m_triangulator.triangulate(m_polygon, m_triangles))\n {\n \/\/ Skip problematic polygonal faces.\n ++m_triangulation_error_count;\n return;\n }\n\n \/\/ Insert all triangles of the triangulation into the mesh.\n const size_t m_triangle_count = m_triangles.size();\n for (size_t i = 0; i < m_triangle_count; i += 3)\n {\n insert_triangle(\n m_triangles[i + 0],\n m_triangles[i + 1],\n m_triangles[i + 2]);\n }\n }\n else\n {\n \/\/ The face is already a triangle, no triangulation is necessary.\n insert_triangle(0, 1, 2);\n }\n }\n\n virtual void set_face_vertices(const size_t vertices[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_vertices.push_back(static_cast<uint32>(vertices[i]));\n }\n\n virtual void set_face_vertex_normals(const size_t vertex_normals[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_normals.push_back(static_cast<uint32>(vertex_normals[i]));\n }\n\n virtual void set_face_vertex_tex_coords(const size_t tex_coords[])\n {\n for (size_t i = 0; i < m_vertex_count; ++i)\n m_face_tex_coords.push_back(static_cast<uint32>(tex_coords[i]));\n }\n\n virtual void set_face_material(const size_t material)\n {\n m_face_material = static_cast<uint32>(material);\n }\n\n private:\n ParamArray m_params;\n const string m_base_object_name;\n size_t m_untitled_mesh_counter;\n MeshObjectVector m_objects;\n\n size_t m_vertex_count;\n vector<uint32> m_face_vertices;\n vector<uint32> m_face_normals;\n vector<uint32> m_face_tex_coords;\n uint32 m_face_material;\n\n Triangulator<double> m_triangulator;\n vector<Vector3d> m_polygon;\n vector<size_t> m_triangles;\n\n size_t m_face_count;\n size_t m_triangulation_error_count;\n\n void insert_triangle(\n const size_t v0_index,\n const size_t v1_index,\n const size_t v2_index)\n {\n Triangle triangle;\n\n \/\/ Set triangle vertices.\n triangle.m_v0 = m_face_vertices[v0_index];\n triangle.m_v1 = m_face_vertices[v1_index];\n triangle.m_v2 = m_face_vertices[v2_index];\n\n \/\/ Set triangle vertex normals.\n if (m_face_normals.size() == m_vertex_count)\n {\n triangle.m_n0 = m_face_normals[v0_index];\n triangle.m_n1 = m_face_normals[v1_index];\n triangle.m_n2 = m_face_normals[v2_index];\n }\n else\n {\n \/\/ Fetch the triangle vertices.\n const Vector3d v0 = Vector3d(m_objects.back()->get_vertex(triangle.m_v0));\n const Vector3d v1 = Vector3d(m_objects.back()->get_vertex(triangle.m_v1));\n const Vector3d v2 = Vector3d(m_objects.back()->get_vertex(triangle.m_v2));\n\n \/\/ Compute the geometric normal to the triangle.\n const Vector3d geometric_normal = normalize(cross(v1 - v0, v2 - v0));\n\n \/\/ Insert the geometric normal into the mesh.\n const size_t geometric_normal_index =\n m_objects.back()->push_vertex_normal(GVector3(geometric_normal));\n\n \/\/ Assign the geometric normal to all vertices of the triangle.\n triangle.m_n0 = geometric_normal_index;\n triangle.m_n1 = geometric_normal_index;\n triangle.m_n2 = geometric_normal_index;\n }\n\n \/\/ Set triangle vertex texture coordinates (if any).\n if (m_face_tex_coords.size() == m_vertex_count)\n {\n triangle.m_a0 = m_face_tex_coords[v0_index];\n triangle.m_a1 = m_face_tex_coords[v1_index];\n triangle.m_a2 = m_face_tex_coords[v2_index];\n }\n else\n {\n triangle.m_a0 = Triangle::None;\n triangle.m_a1 = Triangle::None;\n triangle.m_a2 = Triangle::None;\n }\n\n \/\/ Set triangle material.\n\/\/ triangle.m_pa = m_face_material;\n triangle.m_pa = 0;\n\n \/\/ Insert the triangle into the mesh.\n m_objects.back()->push_triangle(triangle);\n }\n };\n}\n\nMeshObjectArray MeshObjectReader::read(\n const char* filename,\n const char* base_object_name,\n const ParamArray& params)\n{\n assert(filename);\n assert(base_object_name);\n\n OBJMeshFileReader reader;\n MeshObjectBuilder builder(params, base_object_name);\n\n Stopwatch<DefaultWallclockTimer> stopwatch;\n stopwatch.start();\n\n try\n {\n reader.read(filename, builder);\n }\n catch (const OBJMeshFileReader::ExceptionInvalidFaceDef& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: invalid face definition on line \" FMT_SIZE_T,\n filename,\n e.m_line);\n return MeshObjectArray();\n }\n catch (const OBJMeshFileReader::ExceptionParseError& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: parse error on line \" FMT_SIZE_T,\n filename,\n e.m_line);\n return MeshObjectArray();\n }\n catch (const ExceptionIOError&)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: i\/o error\",\n filename);\n return MeshObjectArray();\n }\n catch (const Exception& e)\n {\n RENDERER_LOG_ERROR(\n \"failed to load mesh file %s: %s\",\n filename,\n e.what());\n return MeshObjectArray();\n }\n\n stopwatch.measure();\n\n MeshObjectArray objects;\n for (const_each<vector<MeshObject*> > i = builder.get_objects(); i; ++i)\n objects.push_back(*i);\n\n \/\/ Print the number of loaded objects.\n RENDERER_LOG_INFO(\n \"loaded mesh file %s (%s %s) in %s\",\n filename,\n pretty_int(objects.size()).c_str(),\n plural(objects.size(), \"object\").c_str(),\n pretty_time(stopwatch.get_seconds()).c_str());\n\n return objects;\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PrimeSieve.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieve.h\"\n#include \"defs.h\"\n#include \"ParallelPrimeSieve.h\"\n#include \"pmath.h\"\n#include \"PreSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"PrimeNumberGenerator.h\"\n\n#include <stdexcept>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nPrimeSieve::PrimeSieve() :\n startNumber_(0), stopNumber_(0), flags_(COUNT_PRIMES) {\n parent_ = this;\n this->setSieveSize(defs::PRIMESIEVE_SIEVESIZE);\n this->setPreSieveLimit(defs::PRIMESIEVE_PRESIEVE_LIMIT);\n this->reset();\n}\n\n\/**\n * ParallelPrimeSieve uses multiple PrimeSieve objects and threads to\n * sieve primes in parallel.\n * @see ParallelPrimeSieve::sieve()\n *\/\nPrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber, \n ParallelPrimeSieve* parent) :\n sieveSize_(parent->sieveSize_), \n flags_(parent->flags_),\n preSieveLimit_(parent->preSieveLimit_),\n callback_(parent->callback_),\n callbackOOP_(parent->callbackOOP_), \n cbObj_(parent->cbObj_),\n parent_(parent) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->reset();\n}\n\nuint64_t PrimeSieve::getStartNumber() const {\n return startNumber_;\n}\n\nuint64_t PrimeSieve::getStopNumber() const {\n return stopNumber_;\n}\n\n\/**\n * Get the sieve size in Kilobytes.\n *\/\nuint32_t PrimeSieve::getSieveSize() const {\n return sieveSize_;\n}\n\nuint32_t PrimeSieve::getPreSieveLimit() const {\n return preSieveLimit_;\n}\n\n\/**\n * Get the current set public flags.\n *\/\nuint32_t PrimeSieve::getFlags() const {\n \/\/ clear out private flags\n return flags_ & ((1u << 20) - 1);\n}\n\n\/**\n * Get the count of prime numbers within the interval\n * [startNumber, stopNumber].\n *\/\nuint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(COUNT_PRIMES);\n this->sieve();\n return this->getPrimeCount();\n}\n\n\/**\n * Get the count of prime numbers after sieve().\n *\/\nuint64_t PrimeSieve::getPrimeCount() const {\n return counts_[0];\n}\n\n\/**\n * Get the count of twin primes after sieve().\n *\/\nuint64_t PrimeSieve::getTwinCount() const {\n return counts_[1];\n}\n\n\/**\n * Get the count of prime triplets after sieve().\n *\/\nuint64_t PrimeSieve::getTripletCount() const {\n return counts_[2];\n}\n\n\/**\n * Get the count of prime quadruplets after sieve().\n *\/\nuint64_t PrimeSieve::getQuadrupletCount() const {\n return counts_[3];\n}\n\n\/**\n * Get the count of prime quintuplets after sieve().\n *\/\nuint64_t PrimeSieve::getQuintupletCount() const {\n return counts_[4];\n}\n\n\/**\n * Get the count of prime sextuplets after sieve().\n *\/\nuint64_t PrimeSieve::getSextupletCount() const {\n return counts_[5];\n}\n\n\/**\n * Get the count of prime septuplets after sieve().\n *\/\nuint64_t PrimeSieve::getSeptupletCount() const {\n return counts_[6];\n}\n\n\/**\n * Get the count of prime numbers or prime k-tuplets after sieve().\n * @param type = 0 : Count of prime numbers,\n * type = 1 : Count of twin primes, \n * type = 2 : Count of prime triplets, \n * type = 3 : Count of prime quadruplets, \n * type = 4 : Count of prime quintuplets, \n * type = 5 : Count of prime sextuplets,\n * type = 6 : Count of prime septuplets.\n *\/\nuint64_t PrimeSieve::getCounts(uint32_t type) const {\n if (type >= COUNTS_SIZE)\n throw std::out_of_range(\"getCounts(uint32_t) type out of range\");\n return counts_[type];\n}\n\n\/**\n * Get the time elapsed in seconds of sieve().\n *\/\ndouble PrimeSieve::getTimeElapsed() const {\n return timeElapsed_;\n}\n\n\/**\n * Set a start number for sieving.\n * @pre startNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStartNumber(uint64_t startNumber) {\n \/\/ EratMedium and EratBig stopNumber limit\n if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"START must be < (2^64-1) - (2^32-1) * 10\");\n startNumber_ = startNumber;\n}\n\n\/**\n * Set a stop number for sieving.\n * @pre stopNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStopNumber(uint64_t stopNumber) {\n \/\/ EratMedium and EratBig stopNumber limit\n if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"STOP must be < (2^64-1) - (2^32-1) * 10\");\n stopNumber_ = stopNumber;\n}\n\n\/**\n * Set the size of the sieve of Eratosthenes array (in KiloBytes).\n * Default sieveSize = 64 KB.\n * The best performance is achieved with a sieve size that matches\n * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14\n * and a sieve size of the CPU's L2 cache size (e.g. 512 KB) above.\n *\n * @pre sieveSize >= 1 && <= 8192 KiloBytes.\n * @remark sieveSize is rounded up to the next highest power of 2\n *\/\nvoid PrimeSieve::setSieveSize(uint32_t sieveSize) {\n \/\/ SieveOfEratosthenes needs sieveSize >= 1 KB\n \/\/ EratSmall, EratMedium and EratBig need sieveSize <= 8192\n if (sieveSize < 1 || sieveSize > 8192)\n throw std::invalid_argument(\"sieve size must be >= 1 && <= 8192 KiloBytes\");\n \/\/ EratBig needs a power of 2 sieveSize\n sieveSize_ = nextHighestPowerOf2(sieveSize);\n}\n\n\/**\n * Multiples of small primes <= preSieveLimit are pre-sieved to speed\n * up the sieve of Eratosthenes.\n * @pre preSieveLimit >= 11 && preSieveLimit <= 23\n *\/\nvoid PrimeSieve::setPreSieveLimit(uint32_t preSieveLimit) {\n if (preSieveLimit < 11 || preSieveLimit > 23)\n throw std::invalid_argument(\"pre-sieve limit must be >= 11 && <= 23\");\n preSieveLimit_ = preSieveLimit;\n}\n\n\/**\n * Settings for sieve().\n * @see ..\/docs\/USAGE_EXAMPLES\n * @param flags\n * PrimeSieve::COUNT_PRIMES OR (bitwise '|')\n * PrimeSieve::COUNT_TWINS OR\n * PrimeSieve::COUNT_TRIPLETS OR\n * PrimeSieve::COUNT_QUADRUPLETS OR\n * PrimeSieve::COUNT_QUINTUPLETS OR\n * PrimeSieve::COUNT_SEXTUPLETS OR\n * PrimeSieve::COUNT_SEPTUPLETS OR\n * PrimeSieve::PRINT_PRIMES OR\n * PrimeSieve::PRINT_TWINS OR\n * PrimeSieve::PRINT_TRIPLETS OR\n * PrimeSieve::PRINT_QUADRUPLETS OR\n * PrimeSieve::PRINT_QUINTUPLETS OR\n * PrimeSieve::PRINT_SEXTUPLETS OR\n * PrimeSieve::PRINT_SEPTUPLETS OR\n * PrimeSieve::PRINT_STATUS.\n *\/\nvoid PrimeSieve::setFlags(uint32_t flags) {\n if (flags >= (1u << 20))\n throw std::invalid_argument(\"invalid flags\");\n flags_ = flags;\n}\n\n\/**\n * Generate the prime numbers within the interval\n * [startNumber, stopNumber] and call a callback function for each\n * prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t)) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n flags_ = CALLBACK_PRIMES;\n callback_ = callback;\n this->sieve();\n}\n\n\/**\n * Generate the prime numbers within the interval\n * [startNumber, stopNumber] and call an OOP callback function for\n * each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t, void*), void* cbObj) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n flags_ = CALLBACK_PRIMES_OOP;\n callbackOOP_ = callback;\n cbObj_ = cbObj;\n this->sieve();\n}\n\nvoid PrimeSieve::reset() {\n segments_ = 0;\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n counts_[i] = 0;\n status_ = -1.0;\n timeElapsed_ = 0.0;\n parent_->doStatus(0);\n}\n\n\/**\n * Calculate the current status in percent of sieve().\n *\/\nvoid PrimeSieve::doStatus(uint32_t segment) {\n segments_ += segment;\n int old = static_cast<int> (status_);\n status_ = std::min<double>(100.0, (static_cast<double> (segments_) \/ \n (1 + stopNumber_ - startNumber_)) * 100.0);\n if (flags_ & PRINT_STATUS) {\n int status = static_cast<int> (status_);\n if (status > old)\n std::cout << '\\r' << status << '%' << std::flush;\n }\n}\n\nvoid PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type, \n const std::string& prime) {\n if (startNumber_ <= low && stopNumber_ >= high) {\n if (flags_ & (COUNT_PRIMES << type))\n counts_[type]++;\n if (flags_ & (PRINT_PRIMES << type))\n std::cout << prime << std::endl;\n else if (type == 0 && (flags_ & CALLBACK_PRIMES))\n this->callback_(prime[0]-'0');\n else if (type == 0 && (flags_ & CALLBACK_PRIMES_OOP))\n this->callbackOOP_(prime[0]-'0', cbObj_);\n }\n}\n\n\/**\n * Sieve the prime numbers and\/or prime k-tuplets within the interval\n * [startNumber_, stopNumber_].\n *\/\nvoid PrimeSieve::sieve() {\n clock_t t1 = std::clock();\n this->reset();\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n\n \/\/ small primes have to be examined manually\n if (startNumber_ <= 5) {\n this->doSmallPrime(2, 2, 0, \"2\");\n this->doSmallPrime(3, 3, 0, \"3\");\n this->doSmallPrime(5, 5, 0, \"5\");\n this->doSmallPrime(3, 5, 1, \"(3, 5)\");\n this->doSmallPrime(5, 7, 1, \"(5, 7)\");\n this->doSmallPrime(5, 11, 2, \"(5, 7, 11)\");\n this->doSmallPrime(5, 13, 3, \"(5, 7, 11, 13)\");\n this->doSmallPrime(5, 17, 4, \"(5, 7, 11, 13, 17)\");\n }\n\n if (stopNumber_ >= 7) {\n \/\/ used to sieve the primes and prime k-tuplets within the\n \/\/ interval [startNumber_, stopNumber_]\n PrimeNumberFinder finder(this);\n\n if (isqrt(stopNumber_) > finder.getPreSieveLimit()) {\n \/\/\/ used to generate the primes up to stopNumber_^0.5 needed for\n \/\/\/ sieving by finder\n \/\/\/ @see PrimeNumberGenerator::generate(const uint8_t*, uint32_t)\n PrimeNumberGenerator generator(finder);\n\n \/\/ the following sieve of Eratosthenes implementation generates\n \/\/ the primes up to stopNumber_^0.25 needed for sieving by the\n \/\/ faster PrimeNumberGenerator\n uint32_t N = isqrt(generator.getStopNumber());\n std::vector<uint8_t> isPrime((N+8)\/8, 0xAA);\n for (uint32_t i = 3; i*i <= N; i += 2) {\n if (isPrime[i>>3] & (1<<(i&7)))\n for (uint32_t j = i*i; j <= N; j += i*2)\n isPrime[j>>3] &= ~(1<<(j&7));\n }\n for (uint32_t i = generator.getPreSieveLimit() + 1; i <= N; i++) {\n if (isPrime[i>>3] & (1<<(i&7)))\n generator.sieve(i);\n }\n generator.finish();\n }\n finder.finish();\n }\n \/\/ set status_ to 100.0 percent\n parent_->doStatus(10);\n timeElapsed_ = static_cast<double> (std::clock() - t1) \/ CLOCKS_PER_SEC;\n}\n<commit_msg>improved code readability<commit_after>\/*\n * PrimeSieve.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n#include \"PrimeSieve.h\"\n#include \"defs.h\"\n#include \"ParallelPrimeSieve.h\"\n#include \"pmath.h\"\n#include \"PreSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"PrimeNumberGenerator.h\"\n\n#include <stdexcept>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nPrimeSieve::PrimeSieve() :\n startNumber_(0), stopNumber_(0), flags_(COUNT_PRIMES) {\n parent_ = this;\n this->setSieveSize(defs::PRIMESIEVE_SIEVESIZE);\n this->setPreSieveLimit(defs::PRIMESIEVE_PRESIEVE_LIMIT);\n this->reset();\n}\n\n\/**\n * ParallelPrimeSieve uses multiple PrimeSieve objects and threads to\n * sieve primes in parallel.\n * @see ParallelPrimeSieve::sieve()\n *\/\nPrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber, \n ParallelPrimeSieve* parent) :\n sieveSize_(parent->sieveSize_), \n flags_(parent->flags_),\n preSieveLimit_(parent->preSieveLimit_),\n callback_(parent->callback_),\n callbackOOP_(parent->callbackOOP_), \n cbObj_(parent->cbObj_),\n parent_(parent) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->reset();\n}\n\nuint64_t PrimeSieve::getStartNumber() const {\n return startNumber_;\n}\n\nuint64_t PrimeSieve::getStopNumber() const {\n return stopNumber_;\n}\n\n\/**\n * Get the sieve size in Kilobytes.\n *\/\nuint32_t PrimeSieve::getSieveSize() const {\n return sieveSize_;\n}\n\nuint32_t PrimeSieve::getPreSieveLimit() const {\n return preSieveLimit_;\n}\n\n\/**\n * Get the current set public flags.\n *\/\nuint32_t PrimeSieve::getFlags() const {\n \/\/ clear out private flags\n return flags_ & ((1u << 20) - 1);\n}\n\n\/**\n * Get the count of prime numbers within the interval\n * [startNumber, stopNumber].\n *\/\nuint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n this->setFlags(COUNT_PRIMES);\n this->sieve();\n return this->getPrimeCount();\n}\n\n\/**\n * Get the count of prime numbers after sieve().\n *\/\nuint64_t PrimeSieve::getPrimeCount() const {\n return counts_[0];\n}\n\n\/**\n * Get the count of twin primes after sieve().\n *\/\nuint64_t PrimeSieve::getTwinCount() const {\n return counts_[1];\n}\n\n\/**\n * Get the count of prime triplets after sieve().\n *\/\nuint64_t PrimeSieve::getTripletCount() const {\n return counts_[2];\n}\n\n\/**\n * Get the count of prime quadruplets after sieve().\n *\/\nuint64_t PrimeSieve::getQuadrupletCount() const {\n return counts_[3];\n}\n\n\/**\n * Get the count of prime quintuplets after sieve().\n *\/\nuint64_t PrimeSieve::getQuintupletCount() const {\n return counts_[4];\n}\n\n\/**\n * Get the count of prime sextuplets after sieve().\n *\/\nuint64_t PrimeSieve::getSextupletCount() const {\n return counts_[5];\n}\n\n\/**\n * Get the count of prime septuplets after sieve().\n *\/\nuint64_t PrimeSieve::getSeptupletCount() const {\n return counts_[6];\n}\n\n\/**\n * Get the count of prime numbers or prime k-tuplets after sieve().\n * @param type = 0 : Count of prime numbers,\n * type = 1 : Count of twin primes, \n * type = 2 : Count of prime triplets, \n * type = 3 : Count of prime quadruplets, \n * type = 4 : Count of prime quintuplets, \n * type = 5 : Count of prime sextuplets,\n * type = 6 : Count of prime septuplets.\n *\/\nuint64_t PrimeSieve::getCounts(uint32_t type) const {\n if (type >= COUNTS_SIZE)\n throw std::out_of_range(\"getCounts(uint32_t) type out of range\");\n return counts_[type];\n}\n\n\/**\n * Get the time elapsed in seconds of sieve().\n *\/\ndouble PrimeSieve::getTimeElapsed() const {\n return timeElapsed_;\n}\n\n\/**\n * Set a start number for sieving.\n * @pre startNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStartNumber(uint64_t startNumber) {\n \/\/ EratMedium and EratBig stopNumber limit\n if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"START must be < (2^64-1) - (2^32-1) * 10\");\n startNumber_ = startNumber;\n}\n\n\/**\n * Set a stop number for sieving.\n * @pre stopNumber < (2^64-1) - (2^32-1) * 10\n *\/\nvoid PrimeSieve::setStopNumber(uint64_t stopNumber) {\n \/\/ EratMedium and EratBig stopNumber limit\n if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))\n throw std::invalid_argument(\"STOP must be < (2^64-1) - (2^32-1) * 10\");\n stopNumber_ = stopNumber;\n}\n\n\/**\n * Set the size of the sieve of Eratosthenes array (in KiloBytes).\n * Default sieveSize = 64 KB.\n * The best performance is achieved with a sieve size that matches\n * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14\n * and a sieve size of the CPU's L2 cache size (e.g. 512 KB) above.\n *\n * @pre sieveSize >= 1 && <= 8192 KiloBytes.\n * @remark sieveSize is rounded up to the next highest power of 2\n *\/\nvoid PrimeSieve::setSieveSize(uint32_t sieveSize) {\n \/\/ SieveOfEratosthenes needs sieveSize >= 1 KB\n \/\/ EratSmall, EratMedium and EratBig need sieveSize <= 8192\n if (sieveSize < 1 || sieveSize > 8192)\n throw std::invalid_argument(\"sieve size must be >= 1 && <= 8192 KiloBytes\");\n \/\/ EratBig needs a power of 2 sieveSize\n sieveSize_ = nextHighestPowerOf2(sieveSize);\n}\n\n\/**\n * Multiples of small primes <= preSieveLimit are pre-sieved to speed\n * up the sieve of Eratosthenes.\n * @pre preSieveLimit >= 11 && preSieveLimit <= 23\n *\/\nvoid PrimeSieve::setPreSieveLimit(uint32_t preSieveLimit) {\n if (preSieveLimit < 11 || preSieveLimit > 23)\n throw std::invalid_argument(\"pre-sieve limit must be >= 11 && <= 23\");\n preSieveLimit_ = preSieveLimit;\n}\n\n\/**\n * Settings for sieve().\n * @see ..\/docs\/USAGE_EXAMPLES\n * @param flags\n * PrimeSieve::COUNT_PRIMES OR (bitwise '|')\n * PrimeSieve::COUNT_TWINS OR\n * PrimeSieve::COUNT_TRIPLETS OR\n * PrimeSieve::COUNT_QUADRUPLETS OR\n * PrimeSieve::COUNT_QUINTUPLETS OR\n * PrimeSieve::COUNT_SEXTUPLETS OR\n * PrimeSieve::COUNT_SEPTUPLETS OR\n * PrimeSieve::PRINT_PRIMES OR\n * PrimeSieve::PRINT_TWINS OR\n * PrimeSieve::PRINT_TRIPLETS OR\n * PrimeSieve::PRINT_QUADRUPLETS OR\n * PrimeSieve::PRINT_QUINTUPLETS OR\n * PrimeSieve::PRINT_SEXTUPLETS OR\n * PrimeSieve::PRINT_SEPTUPLETS OR\n * PrimeSieve::PRINT_STATUS.\n *\/\nvoid PrimeSieve::setFlags(uint32_t flags) {\n if (flags >= (1u << 20))\n throw std::invalid_argument(\"invalid flags\");\n flags_ = flags;\n}\n\n\/**\n * Generate the prime numbers within the interval\n * [startNumber, stopNumber] and call a callback function for each\n * prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t)) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n flags_ = CALLBACK_PRIMES;\n callback_ = callback;\n this->sieve();\n}\n\n\/**\n * Generate the prime numbers within the interval\n * [startNumber, stopNumber] and call an OOP callback function for\n * each prime.\n *\/\nvoid PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,\n void (*callback)(uint64_t, void*), void* cbObj) {\n if (callback == NULL)\n throw std::invalid_argument(\"callback must not be NULL\");\n this->setStartNumber(startNumber);\n this->setStopNumber(stopNumber);\n flags_ = CALLBACK_PRIMES_OOP;\n callbackOOP_ = callback;\n cbObj_ = cbObj;\n this->sieve();\n}\n\nvoid PrimeSieve::reset() {\n segments_ = 0;\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n counts_[i] = 0;\n status_ = -1.0;\n timeElapsed_ = 0.0;\n parent_->doStatus(0);\n}\n\n\/**\n * Calculate the current status in percent of sieve().\n *\/\nvoid PrimeSieve::doStatus(uint32_t segment) {\n segments_ += segment;\n int old = static_cast<int> (status_);\n status_ = std::min<double>(100.0, (static_cast<double> (segments_) \/ \n (1 + stopNumber_ - startNumber_)) * 100.0);\n if (flags_ & PRINT_STATUS) {\n int status = static_cast<int> (status_);\n if (status > old)\n std::cout << '\\r' << status << '%' << std::flush;\n }\n}\n\nvoid PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type, \n const std::string& prime) {\n if (startNumber_ <= low && stopNumber_ >= high) {\n if (flags_ & (COUNT_PRIMES << type))\n counts_[type]++;\n if (flags_ & (PRINT_PRIMES << type))\n std::cout << prime << std::endl;\n else if (type == 0 && (flags_ & CALLBACK_PRIMES))\n this->callback_(prime[0]-'0');\n else if (type == 0 && (flags_ & CALLBACK_PRIMES_OOP))\n this->callbackOOP_(prime[0]-'0', cbObj_);\n }\n}\n\n\/**\n * Sieve the prime numbers and\/or prime k-tuplets within the interval\n * [startNumber_, stopNumber_].\n *\/\nvoid PrimeSieve::sieve() {\n clock_t t1 = std::clock();\n this->reset();\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n\n \/\/ small primes have to be examined manually\n if (startNumber_ <= 5) {\n this->doSmallPrime(2, 2, 0, \"2\");\n this->doSmallPrime(3, 3, 0, \"3\");\n this->doSmallPrime(5, 5, 0, \"5\");\n this->doSmallPrime(3, 5, 1, \"(3, 5)\");\n this->doSmallPrime(5, 7, 1, \"(5, 7)\");\n this->doSmallPrime(5, 11, 2, \"(5, 7, 11)\");\n this->doSmallPrime(5, 13, 3, \"(5, 7, 11, 13)\");\n this->doSmallPrime(5, 17, 4, \"(5, 7, 11, 13, 17)\");\n }\n\n if (stopNumber_ >= 7) {\n \/\/ used to sieve the primes and prime k-tuplets within the\n \/\/ interval [startNumber_, stopNumber_]\n PrimeNumberFinder finder(this);\n\n if (isqrt(stopNumber_) > finder.getPreSieveLimit()) {\n \/\/\/ used to generate the primes up to stopNumber_^0.5 needed for\n \/\/\/ sieving by finder\n \/\/\/ @see PrimeNumberGenerator::generate(const uint8_t*, uint32_t)\n PrimeNumberGenerator generator(finder);\n\n \/\/ the following sieve of Eratosthenes implementation generates\n \/\/ the primes up to stopNumber_^0.25 needed for sieving by the\n \/\/ faster PrimeNumberGenerator\n uint32_t N = isqrt(generator.getStopNumber());\n std::vector<uint8_t> isPrime(N\/8+1, 0xAA);\n for (uint32_t i = 3; i*i <= N; i += 2) {\n if (isPrime[i>>3] & (1<<(i&7)))\n for (uint32_t j = i*i; j <= N; j += i*2)\n isPrime[j>>3] &= ~(1<<(j&7));\n }\n for (uint32_t i = generator.getPreSieveLimit() + 1; i <= N; i++) {\n if (isPrime[i>>3] & (1<<(i&7)))\n generator.sieve(i);\n }\n generator.finish();\n }\n finder.finish();\n }\n \/\/ set status_ to 100.0 percent\n parent_->doStatus(10);\n timeElapsed_ = static_cast<double> (std::clock() - t1) \/ CLOCKS_PER_SEC;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TiffVolumeConverter.h\n \\author Tom Fogal\n SCI Institute\n University of Utah\n*\/\n#include \"TiffVolumeConverter.h\"\n#include \"..\/3rdParty\/boost\/cstdint.hpp\"\n#include \"..\/3rdParty\/tiff\/tiffio.h\"\n#include \"..\/StdTuvokDefines.h\"\n#include \"..\/Controller\/MasterController.h\"\n#include \"..\/Basics\/SysTools.h\"\n\n#ifdef __GNUC__\n# define _malloc __attribute__((malloc))\n#else\n# define _malloc \/* nothing *\/\n#endif\n\nstatic void tv_dimensions(TIFF *, size_t dims[3]);\n_malloc static BYTE* tv_read_slice(TIFF *, AbstrDebugOut &);\n#if 0\n\/\/ currently disabled -- mistakenly thought I was reading 4-component data for\n\/\/ a while. left in because we'll probably want to be able to convert\n\/\/ 4-component data to 1-component data at some point.\n_malloc static UINT32* tv_vector_to_scalar_magnitude(UINT32 *, size_t, size_t);\n#endif\n\nTiffVolumeConverter::TiffVolumeConverter()\n{\n m_vConverterDesc = \"TIFF Volume (Image stack)\";\n m_vSupportedExt.push_back(\"OME.TIF\");\n m_vSupportedExt.push_back(\"OME.TIFF\");\n m_vSupportedExt.push_back(\"TIF\");\n m_vSupportedExt.push_back(\"TIFF\");\n}\n\n\/\/ converts a TiffVolume to a `raw' file. We'll read through the TIFF\n\/\/ slice-by-slice, copying each slice to the raw file.\nbool\nTiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string& strTempDir,\n MasterController* pMasterController,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINTVECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n std::string& strSource,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n AbstrDebugOut& dbg = *(pMasterController->DebugOut());\n dbg.Message(_func_, \"Attempting to convert TiffVolume: %s\",\n strSourceFilename.c_str());\n\n TIFF *tif = TIFFOpen(strSourceFilename.c_str(), \"r\");\n if(tif == NULL) {\n dbg.Error(_func_, \"Could not open %s\", strSourceFilename.c_str());\n return false;\n }\n\n \/\/ Get the dimensions of the volume.\n {\n size_t dims[3];\n tv_dimensions(tif, dims);\n vVolumeSize[0] = dims[0];\n vVolumeSize[1] = dims[1];\n vVolumeSize[2] = dims[2];\n dbg.Message(_func_, \"TiffVolume dimensions: %zux%zux%zu\",\n dims[0], dims[1], dims[2]);\n if(dims[2] <= 1) {\n dbg.Error(_func_, \"TIFF is not a volume; use \"\n \"`Load Dataset from Directory' instead!\");\n TIFFClose(tif);\n return false;\n }\n }\n iHeaderSkip = 0;\n\n \/\/ read the number of bits per component from the tiff tag.\n {\n boost::uint16_t bits_per_sample;\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n iComponentSize = bits_per_sample;\n dbg.Message(_func_, \"%ld bits per component.\", iComponentSize);\n }\n \/\/ likewise for the number of components \/ pixel.\n {\n boost::uint16_t components;\n TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);\n iComponentCount = components;\n dbg.Message(_func_, \"%ld component%s.\", iComponentCount,\n (components == 1) ? \"\" : \"s\");\n }\n \/\/ IIRC libtiff handles all the endian issues for us.\n bConvertEndianess = false;\n\n \/\/ This group might be bugs; not quite sure where to read these from. In any\n \/\/ case, we don't have any data which does not have these properties.\n bSigned = false;\n bIsFloat = false;\n vVolumeAspect[0] = 1;\n vVolumeAspect[1] = 1;\n vVolumeAspect[2] = 1;\n\n strTitle = \"TIFF Volume\";\n \/\/ @todo FIXME: this assignment to be the same in every reader, should be\n \/\/ moved to the caller or parent:\n strSource = SysTools::GetFilename(strSourceFilename);\n eType = UVFTables::ES_UNDEFINED;\n\n \/\/ Create an intermediate file to hold the data.\n strIntermediateFile = strTempDir +\n SysTools::GetFilename(strSourceFilename) + \".binary\";\n LargeRAWFile binary(strIntermediateFile);\n binary.Create(iComponentSize\/8 * iComponentCount * vVolumeSize.volume());\n if(!binary.IsOpen()) {\n dbg.Error(_func_, \"Could not create binary file %s\",\n strIntermediateFile.c_str());\n TIFFClose(tif);\n return false;\n }\n bDeleteIntermediateFile = true;\n \/\/ Populate the intermediate file. We'll do this slice-by-slice, which isn't\n \/\/ kosher for Tuvok semantics -- a slice could technically be larger than\n \/\/ INCORESIZE. But it won't be.\n do {\n BYTE* slice = tv_read_slice(tif, dbg);\n if(slice) {\n \/\/ assuming 8-bit monochrome data here, which might not always be valid.\n binary.WriteRAW(static_cast<unsigned char*>(slice),\n vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));\n _TIFFfree(slice);\n } else {\n binary.Close();\n binary.Delete();\n TIFFClose(tif);\n return false;\n }\n } while(TIFFReadDirectory(tif));\n binary.Close();\n\n TIFFClose(tif);\n return true;\n}\n\n\/\/ unimplemented!\nbool\nTiffVolumeConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64, \n UINT64, bool,\n bool,\n UINTVECTOR3,\n FLOATVECTOR3,\n MasterController*,\n bool)\n{\n return false;\n}\n\n\/\/ Reads the dimensions of the TIFF volume. X and Y come from the dimensions\n\/\/ of the first image in the stack: we assume that this stays constant\n\/\/ throughout the volume. Z comes from the number of images in the stack.\nstatic void\ntv_dimensions(TIFF *tif, size_t dims[3])\n{\n UINT32 x,y;\n size_t z=0;\n\n TIFFSetDirectory(tif, 0);\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);\n \/\/ tiff calls the height \"length\" for some reason.\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);\n do {\n ++z;\n } while(TIFFReadDirectory(tif));\n TIFFSetDirectory(tif, 0);\n\n dims[0] = x;\n dims[1] = y;\n dims[2] = z;\n}\n\n_malloc static BYTE*\ntv_read_slice(TIFF *tif, AbstrDebugOut& dbg)\n{\n BYTE *slice;\n UINT32 width;\n UINT32 height;\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n\n dbg.Message(_func_, \"Reading %ux%u TIFF slice.\", width, height);\n slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));\n if(slice == NULL) {\n dbg.Error(_func_, \"TIFFmalloc failed.\");\n return NULL;\n }\n const tstrip_t n_strips = TIFFNumberOfStrips(tif);\n {\n BYTE *data = slice;\n tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));\n for(tstrip_t s=0; s < n_strips; ++s) {\n \/\/\/ @todo FIXME: don't assume the strip is raw; could be encoded.\n \/\/\/ There's a `compression scheme' tag which probably details this.\n tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,\n static_cast<tsize_t>(-1));\n memcpy(data, buf, n_bytes);\n data += TIFFStripSize(tif);\n }\n _TIFFfree(buf);\n }\n\n return slice;\n}\n\n#if 0\n\/\/ Converts an RGBA vector `field' to a scalar field of the \"vector\"'s\n\/\/ magnitude. Ignores the alpha component.\n_malloc static UINT32*\ntv_vector_to_scalar_magnitude(UINT32 *field, size_t w, size_t h)\n{\n UINT32* ret = new UINT32[w*h];\n for(size_t i=0; i < w*h; ++i) {\n unsigned char r = field[i] & 0xFF000000;\n unsigned char g = field[i] & 0x00FF0000;\n unsigned char b = field[i] & 0x0000FF00;\n ret[i] = (static_cast<UINT32>(r) +\n static_cast<UINT32>(g) +\n static_cast<UINT32>(b)) \/ 3;\n }\n return ret;\n}\n#endif\n<commit_msg>Fix comments in the TiffVolume reader.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TiffVolumeConverter.h\n \\author Tom Fogal\n SCI Institute\n University of Utah\n*\/\n#include \"TiffVolumeConverter.h\"\n#include \"..\/3rdParty\/boost\/cstdint.hpp\"\n#include \"..\/3rdParty\/tiff\/tiffio.h\"\n#include \"..\/StdTuvokDefines.h\"\n#include \"..\/Controller\/MasterController.h\"\n#include \"..\/Basics\/SysTools.h\"\n\n#ifdef __GNUC__\n# define _malloc __attribute__((malloc))\n#else\n# define _malloc \/* nothing *\/\n#endif\n\nstatic void tv_dimensions(TIFF *, size_t dims[3]);\n_malloc static BYTE* tv_read_slice(TIFF *, AbstrDebugOut &);\n#if 0\n\/\/ currently disabled -- mistakenly thought I was reading 4-component data for\n\/\/ a while. left in because we'll probably want to be able to convert\n\/\/ 4-component data to 1-component data at some point.\n_malloc static UINT32* tv_vector_to_scalar_magnitude(UINT32 *, size_t, size_t);\n#endif\n\nTiffVolumeConverter::TiffVolumeConverter()\n{\n m_vConverterDesc = \"TIFF Volume (Image stack)\";\n m_vSupportedExt.push_back(\"OME.TIF\");\n m_vSupportedExt.push_back(\"OME.TIFF\");\n m_vSupportedExt.push_back(\"TIF\");\n m_vSupportedExt.push_back(\"TIFF\");\n}\n\n\/\/ converts a TiffVolume to a `raw' file. We'll read through the TIFF\n\/\/ slice-by-slice, copying each slice to the raw file.\nbool\nTiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string& strTempDir,\n MasterController* pMasterController,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINTVECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n std::string& strSource,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n AbstrDebugOut& dbg = *(pMasterController->DebugOut());\n dbg.Message(_func_, \"Attempting to convert TiffVolume: %s\",\n strSourceFilename.c_str());\n\n TIFF *tif = TIFFOpen(strSourceFilename.c_str(), \"r\");\n if(tif == NULL) {\n dbg.Error(_func_, \"Could not open %s\", strSourceFilename.c_str());\n return false;\n }\n\n \/\/ Get the dimensions of the volume.\n {\n size_t dims[3];\n tv_dimensions(tif, dims);\n vVolumeSize[0] = dims[0];\n vVolumeSize[1] = dims[1];\n vVolumeSize[2] = dims[2];\n dbg.Message(_func_, \"TiffVolume dimensions: %zux%zux%zu\",\n dims[0], dims[1], dims[2]);\n if(dims[2] <= 1) {\n dbg.Error(_func_, \"TIFF is not a volume; use \"\n \"`Load Dataset from Directory' instead!\");\n TIFFClose(tif);\n return false;\n }\n }\n iHeaderSkip = 0;\n\n \/\/ read the number of bits per component from the tiff tag.\n {\n boost::uint16_t bits_per_sample;\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n iComponentSize = bits_per_sample;\n dbg.Message(_func_, \"%ld bits per component.\", iComponentSize);\n }\n \/\/ likewise for the number of components \/ pixel.\n {\n boost::uint16_t components;\n TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);\n iComponentCount = components;\n dbg.Message(_func_, \"%ld component%s.\", iComponentCount,\n (components == 1) ? \"\" : \"s\");\n }\n \/\/ IIRC libtiff handles all the endian issues for us.\n bConvertEndianess = false;\n\n \/\/ One might consider setting the values below explicitly as bugs, but we're\n \/\/ not quite sure where to read these from. In any case, we don't have any\n \/\/ data for which these settings are invalid.\n bSigned = false;\n bIsFloat = false;\n vVolumeAspect[0] = 1;\n vVolumeAspect[1] = 1;\n vVolumeAspect[2] = 1;\n\n strTitle = \"TIFF Volume\";\n \/\/ @todo FIXME: this assignment appears to be the same in every reader,\n \/\/ should be moved to the caller or parent:\n strSource = SysTools::GetFilename(strSourceFilename);\n eType = UVFTables::ES_UNDEFINED;\n\n \/\/ Create an intermediate file to hold the data.\n strIntermediateFile = strTempDir +\n SysTools::GetFilename(strSourceFilename) + \".binary\";\n LargeRAWFile binary(strIntermediateFile);\n binary.Create(iComponentSize\/8 * iComponentCount * vVolumeSize.volume());\n if(!binary.IsOpen()) {\n dbg.Error(_func_, \"Could not create binary file %s\",\n strIntermediateFile.c_str());\n TIFFClose(tif);\n return false;\n }\n bDeleteIntermediateFile = true;\n \/\/ Populate the intermediate file. We'll do this slice-by-slice, which isn't\n \/\/ exactly kosher in Tuvok -- a slice could technically be larger than\n \/\/ INCORESIZE. But it won't be.\n do {\n BYTE* slice = tv_read_slice(tif, dbg);\n if(slice) {\n \/\/ assuming 8-bit monochrome data here, which might not always be valid.\n binary.WriteRAW(static_cast<unsigned char*>(slice),\n vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));\n _TIFFfree(slice);\n } else {\n binary.Close();\n binary.Delete();\n TIFFClose(tif);\n return false;\n }\n } while(TIFFReadDirectory(tif));\n binary.Close();\n\n TIFFClose(tif);\n return true;\n}\n\n\/\/ unimplemented!\nbool\nTiffVolumeConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64, \n UINT64, bool,\n bool,\n UINTVECTOR3,\n FLOATVECTOR3,\n MasterController*,\n bool)\n{\n return false;\n}\n\n\/\/ Reads the dimensions of the TIFF volume. X and Y come from the dimensions\n\/\/ of the first image in the stack: we assume that this stays constant\n\/\/ throughout the volume. Z comes from the number of images in the stack.\nstatic void\ntv_dimensions(TIFF *tif, size_t dims[3])\n{\n UINT32 x,y;\n size_t z=0;\n\n TIFFSetDirectory(tif, 0);\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);\n \/\/ tiff calls the height \"length\" for some reason.\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);\n do {\n ++z;\n } while(TIFFReadDirectory(tif));\n TIFFSetDirectory(tif, 0);\n\n dims[0] = x;\n dims[1] = y;\n dims[2] = z;\n}\n\n_malloc static BYTE*\ntv_read_slice(TIFF *tif, AbstrDebugOut& dbg)\n{\n BYTE *slice;\n UINT32 width;\n UINT32 height;\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n\n dbg.Message(_func_, \"Reading %ux%u TIFF slice.\", width, height);\n slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));\n if(slice == NULL) {\n dbg.Error(_func_, \"TIFFmalloc failed.\");\n return NULL;\n }\n const tstrip_t n_strips = TIFFNumberOfStrips(tif);\n {\n BYTE *data = slice;\n tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));\n for(tstrip_t s=0; s < n_strips; ++s) {\n \/\/\/ @todo FIXME: don't assume the strip is raw; could be encoded.\n \/\/\/ There's a `compression scheme' tag which probably details this.\n tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,\n static_cast<tsize_t>(-1));\n memcpy(data, buf, n_bytes);\n data += TIFFStripSize(tif);\n }\n _TIFFfree(buf);\n }\n\n return slice;\n}\n\n#if 0\n\/\/ Converts an RGBA vector `field' to a scalar field of the \"vector\"'s\n\/\/ magnitude. Ignores the alpha component.\n_malloc static UINT32*\ntv_vector_to_scalar_magnitude(UINT32 *field, size_t w, size_t h)\n{\n UINT32* ret = new UINT32[w*h];\n for(size_t i=0; i < w*h; ++i) {\n unsigned char r = field[i] & 0xFF000000;\n unsigned char g = field[i] & 0x00FF0000;\n unsigned char b = field[i] & 0x0000FF00;\n ret[i] = (static_cast<UINT32>(r) +\n static_cast<UINT32>(g) +\n static_cast<UINT32>(b)) \/ 3;\n }\n return ret;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageExport.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to David G. Gobbi who developed this class.\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <ctype.h>\n#include <string.h>\n#include \"vtkImageExport.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport* vtkImageExport::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageExport\");\n if(ret)\n {\n return (vtkImageExport*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkImageExport;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport::vtkImageExport()\n{\n this->ImageLowerLeft = 1;\n this->ExportVoidPointer = 0;\n this->DataDimensions[0] = this->DataDimensions[1] =\n this->DataDimensions[2] = 0;\n this->LastPipelineMTime = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport::~vtkImageExport()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProcessObject::PrintSelf(os,indent);\n\n os << indent << \"ImageLowerLeft: \" \n << (this->ImageLowerLeft ? \"On\\n\" : \"Off\\n\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::SetInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageExport::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkImageExport::GetDataMemorySize()\n{\n vtkImageData *input = this->GetInput();\n if (input == NULL)\n {\n return 0;\n }\n\n input->UpdateInformation();\n int *extent = input->GetWholeExtent();\n int size = input->GetScalarSize();\n size *= input->GetNumberOfScalarComponents();\n size *= (extent[1] - extent[0] + 1);\n size *= (extent[3] - extent[2] + 1);\n size *= (extent[5] - extent[4] + 1);\n\n return size;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::GetDataDimensions(int *dims)\n{\n vtkImageData *input = this->GetInput();\n if (input == NULL)\n {\n dims[0] = dims[1] = dims[2] = 0;\n return;\n }\n\n input->UpdateInformation();\n int *extent = input->GetWholeExtent();\n dims[0] = extent[1]-extent[0]+1;\n dims[1] = extent[3]-extent[2]+1;\n dims[2] = extent[5]-extent[4]+1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::SetExportVoidPointer(void *ptr)\n{\n if (this->ExportVoidPointer == ptr)\n {\n return;\n }\n this->ExportVoidPointer = ptr;\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Exports all the data from the input.\nvoid vtkImageExport::Export(void *output)\n{\n if (this->ImageLowerLeft)\n {\n memcpy(output,this->GetPointerToData(),this->GetDataMemorySize());\n }\n else\n { \/\/ flip the image when it is output\n void *ptr = this->GetPointerToData();\n int *extent = this->GetInput()->GetWholeExtent();\n int xsize = extent[1]-extent[0]+1;\n int ysize = extent[3]-extent[2]+1;\n int zsize = extent[5]-extent[4]+1;\n int csize = this->GetInput()->GetScalarSize()* \\\n this->GetInput()->GetNumberOfScalarComponents();\n\n for (int i = 0; i < zsize; i++)\n {\n ptr = (void *)(((char *)ptr) + ysize*xsize*csize);\n for (int j = 0; j < ysize; j++)\n {\n ptr = (void *)(((char *)ptr) - xsize*csize);\n memcpy(output, ptr, xsize*csize);\n output = (void *)(((char *)output) + xsize*csize);\n }\n ptr = (void *)(((char *)ptr) + ysize*xsize*csize);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Provides a valid pointer to the data (only valid until the next\n\/\/ update, though)\n\nvoid *vtkImageExport::GetPointerToData()\n{\n \/\/ Error checking\n if ( this->GetInput() == NULL )\n {\n vtkErrorMacro(<<\"Export: Please specify an input!\");\n return 0;\n }\n\n vtkImageData *input = this->GetInput();\n input->UpdateInformation();\n input->SetUpdateExtent(input->GetWholeExtent());\n input->ReleaseDataFlagOff();\n\n input->Update();\n this->UpdateProgress(0.0);\n this->UpdateProgress(1.0);\n\n return input->GetScalarPointer();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid* vtkImageExport::GetCallbackUserData()\n{\n return this;\n}\n\nvtkImageExport::UpdateInformationCallbackType\nvtkImageExport::GetUpdateInformationCallback() const\n{\n return &vtkImageExport::UpdateInformationCallbackFunction;\n}\n\nvtkImageExport::PipelineModifiedCallbackType\nvtkImageExport::GetPipelineModifiedCallback() const\n{\n return &vtkImageExport::PipelineModifiedCallbackFunction;\n}\n\nvtkImageExport::WholeExtentCallbackType\nvtkImageExport::GetWholeExtentCallback() const\n{\n return &vtkImageExport::WholeExtentCallbackFunction;\n}\n\nvtkImageExport::SpacingCallbackType\nvtkImageExport::GetSpacingCallback() const\n{\n return &vtkImageExport::SpacingCallbackFunction;\n}\n\nvtkImageExport::OriginCallbackType\nvtkImageExport::GetOriginCallback() const\n{\n return &vtkImageExport::OriginCallbackFunction;\n}\n\nvtkImageExport::ScalarTypeCallbackType\nvtkImageExport::GetScalarTypeCallback() const\n{\n return &vtkImageExport::ScalarTypeCallbackFunction;\n}\n\nvtkImageExport::NumberOfComponentsCallbackType\nvtkImageExport::GetNumberOfComponentsCallback() const\n{\n return &vtkImageExport::NumberOfComponentsCallbackFunction;\n}\n\nvtkImageExport::PropagateUpdateExtentCallbackType\nvtkImageExport::GetPropagateUpdateExtentCallback() const\n{\n return &vtkImageExport::PropagateUpdateExtentCallbackFunction;\n}\n\nvtkImageExport::UpdateDataCallbackType\nvtkImageExport::GetUpdateDataCallback() const\n{\n return &vtkImageExport::UpdateDataCallbackFunction;\n}\n\nvtkImageExport::DataExtentCallbackType\nvtkImageExport::GetDataExtentCallback() const\n{\n return &vtkImageExport::DataExtentCallbackFunction;\n}\n\nvtkImageExport::BufferPointerCallbackType\nvtkImageExport::GetBufferPointerCallback() const\n{\n return &vtkImageExport::BufferPointerCallbackFunction;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::UpdateInformationCallbackFunction(void* userData)\n{\n static_cast<vtkImageExport*>(userData)->\n UpdateInformationCallback();\n}\n\nint vtkImageExport::PipelineModifiedCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n PipelineModifiedCallback();\n}\n\nint* vtkImageExport::WholeExtentCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n WholeExtentCallback();\n}\n\nfloat* vtkImageExport::SpacingCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n SpacingCallback();\n}\n\nfloat* vtkImageExport::OriginCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n OriginCallback();\n}\n\nconst char* vtkImageExport::ScalarTypeCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n ScalarTypeCallback();\n}\n \nint vtkImageExport::NumberOfComponentsCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n NumberOfComponentsCallback();\n}\n\nvoid vtkImageExport::PropagateUpdateExtentCallbackFunction(void* userData,\n int* extent)\n{\n static_cast<vtkImageExport*>(userData)->\n PropagateUpdateExtentCallback(extent);\n}\n\nvoid vtkImageExport::UpdateDataCallbackFunction(void* userData)\n{\n static_cast<vtkImageExport*>(userData)->\n UpdateDataCallback();\n}\n\nint* vtkImageExport::DataExtentCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n DataExtentCallback();\n}\n\nvoid* vtkImageExport::BufferPointerCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n BufferPointerCallback();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::UpdateInformationCallback()\n{\n this->GetInput()->UpdateInformation();\n}\n\nint vtkImageExport::PipelineModifiedCallback()\n{\n unsigned long mtime = this->GetInput()->GetPipelineMTime();\n if(mtime > this->LastPipelineMTime)\n {\n this->LastPipelineMTime = mtime;\n return 1;\n }\n return 0;\n}\n\nint* vtkImageExport::WholeExtentCallback()\n{\n return this->GetInput()->GetWholeExtent();\n}\n\nfloat* vtkImageExport::SpacingCallback()\n{\n return this->GetInput()->GetSpacing();\n}\n\nfloat* vtkImageExport::OriginCallback()\n{\n return this->GetInput()->GetOrigin();\n}\n\nconst char* vtkImageExport::ScalarTypeCallback()\n{\n switch (this->GetInput()->GetScalarType())\n {\n case VTK_DOUBLE:\n { return \"double\"; } break;\n case VTK_FLOAT:\n { return \"float\"; } break;\n case VTK_LONG:\n { return \"long\"; } break;\n case VTK_UNSIGNED_LONG:\n { return \"unsigned long\"; } break;\n case VTK_INT:\n { return \"int\"; } break;\n case VTK_UNSIGNED_INT:\n { return \"unsigned int\"; } break;\n case VTK_SHORT:\n { return \"short\"; } break;\n case VTK_UNSIGNED_SHORT:\n { return \"unsigned short\"; } break;\n case VTK_CHAR:\n { return \"char\"; } break;\n case VTK_UNSIGNED_CHAR:\n { return \"unsigned char\"; } break;\n default:\n { return \"<unsupported>\"; } break;\n }\n}\n \nint vtkImageExport::NumberOfComponentsCallback()\n{\n return this->GetInput()->GetNumberOfScalarComponents();\n}\n\nvoid vtkImageExport::PropagateUpdateExtentCallback(int* extent)\n{\n this->GetInput()->SetUpdateExtent(extent);\n}\n\nvoid vtkImageExport::UpdateDataCallback()\n{\n this->GetInput()->Update();\n}\n\nint* vtkImageExport::DataExtentCallback()\n{\n return this->GetInput()->GetExtent();\n}\n\nvoid* vtkImageExport::BufferPointerCallback()\n{\n return this->GetInput()->GetScalarPointer();\n}\n<commit_msg>ERR: unreachable statements caused warnings.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageExport.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to David G. Gobbi who developed this class.\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <ctype.h>\n#include <string.h>\n#include \"vtkImageExport.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport* vtkImageExport::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageExport\");\n if(ret)\n {\n return (vtkImageExport*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkImageExport;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport::vtkImageExport()\n{\n this->ImageLowerLeft = 1;\n this->ExportVoidPointer = 0;\n this->DataDimensions[0] = this->DataDimensions[1] =\n this->DataDimensions[2] = 0;\n this->LastPipelineMTime = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageExport::~vtkImageExport()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkProcessObject::PrintSelf(os,indent);\n\n os << indent << \"ImageLowerLeft: \" \n << (this->ImageLowerLeft ? \"On\\n\" : \"Off\\n\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::SetInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageExport::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkImageExport::GetDataMemorySize()\n{\n vtkImageData *input = this->GetInput();\n if (input == NULL)\n {\n return 0;\n }\n\n input->UpdateInformation();\n int *extent = input->GetWholeExtent();\n int size = input->GetScalarSize();\n size *= input->GetNumberOfScalarComponents();\n size *= (extent[1] - extent[0] + 1);\n size *= (extent[3] - extent[2] + 1);\n size *= (extent[5] - extent[4] + 1);\n\n return size;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::GetDataDimensions(int *dims)\n{\n vtkImageData *input = this->GetInput();\n if (input == NULL)\n {\n dims[0] = dims[1] = dims[2] = 0;\n return;\n }\n\n input->UpdateInformation();\n int *extent = input->GetWholeExtent();\n dims[0] = extent[1]-extent[0]+1;\n dims[1] = extent[3]-extent[2]+1;\n dims[2] = extent[5]-extent[4]+1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::SetExportVoidPointer(void *ptr)\n{\n if (this->ExportVoidPointer == ptr)\n {\n return;\n }\n this->ExportVoidPointer = ptr;\n this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Exports all the data from the input.\nvoid vtkImageExport::Export(void *output)\n{\n if (this->ImageLowerLeft)\n {\n memcpy(output,this->GetPointerToData(),this->GetDataMemorySize());\n }\n else\n { \/\/ flip the image when it is output\n void *ptr = this->GetPointerToData();\n int *extent = this->GetInput()->GetWholeExtent();\n int xsize = extent[1]-extent[0]+1;\n int ysize = extent[3]-extent[2]+1;\n int zsize = extent[5]-extent[4]+1;\n int csize = this->GetInput()->GetScalarSize()* \\\n this->GetInput()->GetNumberOfScalarComponents();\n\n for (int i = 0; i < zsize; i++)\n {\n ptr = (void *)(((char *)ptr) + ysize*xsize*csize);\n for (int j = 0; j < ysize; j++)\n {\n ptr = (void *)(((char *)ptr) - xsize*csize);\n memcpy(output, ptr, xsize*csize);\n output = (void *)(((char *)output) + xsize*csize);\n }\n ptr = (void *)(((char *)ptr) + ysize*xsize*csize);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Provides a valid pointer to the data (only valid until the next\n\/\/ update, though)\n\nvoid *vtkImageExport::GetPointerToData()\n{\n \/\/ Error checking\n if ( this->GetInput() == NULL )\n {\n vtkErrorMacro(<<\"Export: Please specify an input!\");\n return 0;\n }\n\n vtkImageData *input = this->GetInput();\n input->UpdateInformation();\n input->SetUpdateExtent(input->GetWholeExtent());\n input->ReleaseDataFlagOff();\n\n input->Update();\n this->UpdateProgress(0.0);\n this->UpdateProgress(1.0);\n\n return input->GetScalarPointer();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid* vtkImageExport::GetCallbackUserData()\n{\n return this;\n}\n\nvtkImageExport::UpdateInformationCallbackType\nvtkImageExport::GetUpdateInformationCallback() const\n{\n return &vtkImageExport::UpdateInformationCallbackFunction;\n}\n\nvtkImageExport::PipelineModifiedCallbackType\nvtkImageExport::GetPipelineModifiedCallback() const\n{\n return &vtkImageExport::PipelineModifiedCallbackFunction;\n}\n\nvtkImageExport::WholeExtentCallbackType\nvtkImageExport::GetWholeExtentCallback() const\n{\n return &vtkImageExport::WholeExtentCallbackFunction;\n}\n\nvtkImageExport::SpacingCallbackType\nvtkImageExport::GetSpacingCallback() const\n{\n return &vtkImageExport::SpacingCallbackFunction;\n}\n\nvtkImageExport::OriginCallbackType\nvtkImageExport::GetOriginCallback() const\n{\n return &vtkImageExport::OriginCallbackFunction;\n}\n\nvtkImageExport::ScalarTypeCallbackType\nvtkImageExport::GetScalarTypeCallback() const\n{\n return &vtkImageExport::ScalarTypeCallbackFunction;\n}\n\nvtkImageExport::NumberOfComponentsCallbackType\nvtkImageExport::GetNumberOfComponentsCallback() const\n{\n return &vtkImageExport::NumberOfComponentsCallbackFunction;\n}\n\nvtkImageExport::PropagateUpdateExtentCallbackType\nvtkImageExport::GetPropagateUpdateExtentCallback() const\n{\n return &vtkImageExport::PropagateUpdateExtentCallbackFunction;\n}\n\nvtkImageExport::UpdateDataCallbackType\nvtkImageExport::GetUpdateDataCallback() const\n{\n return &vtkImageExport::UpdateDataCallbackFunction;\n}\n\nvtkImageExport::DataExtentCallbackType\nvtkImageExport::GetDataExtentCallback() const\n{\n return &vtkImageExport::DataExtentCallbackFunction;\n}\n\nvtkImageExport::BufferPointerCallbackType\nvtkImageExport::GetBufferPointerCallback() const\n{\n return &vtkImageExport::BufferPointerCallbackFunction;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::UpdateInformationCallbackFunction(void* userData)\n{\n static_cast<vtkImageExport*>(userData)->\n UpdateInformationCallback();\n}\n\nint vtkImageExport::PipelineModifiedCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n PipelineModifiedCallback();\n}\n\nint* vtkImageExport::WholeExtentCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n WholeExtentCallback();\n}\n\nfloat* vtkImageExport::SpacingCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n SpacingCallback();\n}\n\nfloat* vtkImageExport::OriginCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n OriginCallback();\n}\n\nconst char* vtkImageExport::ScalarTypeCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n ScalarTypeCallback();\n}\n \nint vtkImageExport::NumberOfComponentsCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n NumberOfComponentsCallback();\n}\n\nvoid vtkImageExport::PropagateUpdateExtentCallbackFunction(void* userData,\n int* extent)\n{\n static_cast<vtkImageExport*>(userData)->\n PropagateUpdateExtentCallback(extent);\n}\n\nvoid vtkImageExport::UpdateDataCallbackFunction(void* userData)\n{\n static_cast<vtkImageExport*>(userData)->\n UpdateDataCallback();\n}\n\nint* vtkImageExport::DataExtentCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n DataExtentCallback();\n}\n\nvoid* vtkImageExport::BufferPointerCallbackFunction(void* userData)\n{\n return static_cast<vtkImageExport*>(userData)->\n BufferPointerCallback();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageExport::UpdateInformationCallback()\n{\n this->GetInput()->UpdateInformation();\n}\n\nint vtkImageExport::PipelineModifiedCallback()\n{\n unsigned long mtime = this->GetInput()->GetPipelineMTime();\n if(mtime > this->LastPipelineMTime)\n {\n this->LastPipelineMTime = mtime;\n return 1;\n }\n return 0;\n}\n\nint* vtkImageExport::WholeExtentCallback()\n{\n return this->GetInput()->GetWholeExtent();\n}\n\nfloat* vtkImageExport::SpacingCallback()\n{\n return this->GetInput()->GetSpacing();\n}\n\nfloat* vtkImageExport::OriginCallback()\n{\n return this->GetInput()->GetOrigin();\n}\n\nconst char* vtkImageExport::ScalarTypeCallback()\n{\n switch (this->GetInput()->GetScalarType())\n {\n case VTK_DOUBLE:\n { return \"double\"; }\n case VTK_FLOAT:\n { return \"float\"; }\n case VTK_LONG:\n { return \"long\"; }\n case VTK_UNSIGNED_LONG:\n { return \"unsigned long\"; }\n case VTK_INT:\n { return \"int\"; }\n case VTK_UNSIGNED_INT:\n { return \"unsigned int\"; }\n case VTK_SHORT:\n { return \"short\"; }\n case VTK_UNSIGNED_SHORT:\n { return \"unsigned short\"; }\n case VTK_CHAR:\n { return \"char\"; }\n case VTK_UNSIGNED_CHAR:\n { return \"unsigned char\"; }\n default:\n { return \"<unsupported>\"; }\n }\n}\n \nint vtkImageExport::NumberOfComponentsCallback()\n{\n return this->GetInput()->GetNumberOfScalarComponents();\n}\n\nvoid vtkImageExport::PropagateUpdateExtentCallback(int* extent)\n{\n this->GetInput()->SetUpdateExtent(extent);\n}\n\nvoid vtkImageExport::UpdateDataCallback()\n{\n this->GetInput()->Update();\n}\n\nint* vtkImageExport::DataExtentCallback()\n{\n return this->GetInput()->GetExtent();\n}\n\nvoid* vtkImageExport::BufferPointerCallback()\n{\n return this->GetInput()->GetScalarPointer();\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.2, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"filesearch.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QFutureInterface>\n#include <QtCore\/QtConcurrentRun>\n#include <QtCore\/QRegExp>\n#include <QtGui\/QApplication>\n\n#include <qtconcurrent\/runextensions.h>\n\nusing namespace Core::Utils;\n\nnamespace {\n\nvoid runFileSearch(QFutureInterface<FileSearchResult> &future,\n QString searchTerm,\n QStringList files,\n QTextDocument::FindFlags flags)\n{\n future.setProgressRange(0, files.size());\n int numFilesSearched = 0;\n int numMatches = 0;\n\n bool caseInsensitive = !(flags & QTextDocument::FindCaseSensitively);\n bool wholeWord = (flags & QTextDocument::FindWholeWords);\n\n QByteArray sa = searchTerm.toUtf8();\n int scMaxIndex = sa.length()-1;\n const char *sc = sa.constData();\n\n QByteArray sal = searchTerm.toLower().toUtf8();\n const char *scl = sal.constData();\n\n QByteArray sau = searchTerm.toUpper().toUtf8();\n const char *scu = sau.constData();\n\n int chunkSize = qMax(100000, sa.length());\n\n foreach (QString s, files) {\n if (future.isPaused())\n future.waitForResume();\n if (future.isCanceled()) {\n future.setProgressValueAndText(numFilesSearched,\n qApp->translate(\"FileSearch\", \"%1: canceled. %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n break;\n }\n QFile file(s);\n if (!file.open(QIODevice::ReadOnly))\n continue;\n int lineNr = 1;\n const char *startOfLastLine = NULL;\n\n bool firstChunk = true;\n while (!file.atEnd()) {\n if (!firstChunk)\n file.seek(file.pos()-sa.length()+1);\n\n const QByteArray chunk = file.read(chunkSize);\n const char *chunkPtr = chunk.constData();\n startOfLastLine = chunkPtr;\n for (const char *regionPtr = chunkPtr; regionPtr < chunkPtr + chunk.length()-scMaxIndex; ++regionPtr) {\n const char *regionEnd = regionPtr + scMaxIndex;\n\n if (*regionPtr == '\\n') {\n startOfLastLine = regionPtr + 1;\n ++lineNr;\n }\n else if (\n \/\/ case sensitive\n (!caseInsensitive && *regionPtr == sc[0] && *regionEnd == sc[scMaxIndex])\n ||\n \/\/ case insensitive\n (caseInsensitive && (*regionPtr == scl[0] || *regionPtr == scu[0])\n && (*regionEnd == scl[scMaxIndex] || *regionEnd == scu[scMaxIndex]))\n ) {\n const char *afterRegion = regionEnd + 1;\n const char *beforeRegion = regionPtr - 1;\n bool equal = true;\n if (wholeWord &&\n ( ((*beforeRegion >= '0' && *beforeRegion <= '9') || *beforeRegion >= 'A')\n || ((*afterRegion >= '0' && *afterRegion <= '9') || *afterRegion >= 'A')))\n {\n equal = false;\n }\n\n int regionIndex = 1;\n for (const char *regionCursor = regionPtr + 1; regionCursor < regionEnd; ++regionCursor, ++regionIndex) {\n if ( \/\/ case sensitive\n (!caseInsensitive && equal && *regionCursor != sc[regionIndex])\n ||\n \/\/ case insensitive\n (caseInsensitive && equal && *regionCursor != sc[regionIndex] && *regionCursor != scl[regionIndex] && *regionCursor != scu[regionIndex])\n ) {\n equal = false;\n }\n }\n if (equal) {\n int textLength = chunk.length() - (startOfLastLine - chunkPtr);\n if (textLength > 0) {\n QByteArray res;\n res.reserve(256);\n int i = 0;\n int n = 0;\n while (startOfLastLine[i] != '\\n' && startOfLastLine[i] != '\\r' && i < textLength && n++ < 256)\n res.append(startOfLastLine[i++]);\n future.reportResult(FileSearchResult(QDir::toNativeSeparators(s), lineNr, QString(res),\n regionPtr - startOfLastLine, sa.length()));\n ++numMatches;\n }\n }\n }\n }\n firstChunk = false;\n }\n ++numFilesSearched;\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 of %4 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched).arg(files.size()));\n }\n if (!future.isCanceled())\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n}\n\nvoid runFileSearchRegExp(QFutureInterface<FileSearchResult> &future,\n QString searchTerm,\n QStringList files,\n QTextDocument::FindFlags flags)\n{\n future.setProgressRange(0, files.size());\n int numFilesSearched = 0;\n int numMatches = 0;\n if (flags & QTextDocument::FindWholeWords)\n searchTerm = QString(\"\\b%1\\b\").arg(searchTerm);\n Qt::CaseSensitivity caseSensitivity = (flags & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive;\n QRegExp expression(searchTerm, caseSensitivity);\n\n foreach (QString s, files) {\n if (future.isPaused())\n future.waitForResume();\n if (future.isCanceled()) {\n future.setProgressValueAndText(numFilesSearched,\n qApp->translate(\"FileSearch\", \"%1: canceled. %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n break;\n }\n QFile file(s);\n if (!file.open(QIODevice::ReadOnly))\n continue;\n QTextStream stream(&file);\n int lineNr = 1;\n QString line;\n while (!stream.atEnd()) {\n line = stream.readLine();\n int pos = 0;\n while ((pos = expression.indexIn(line, pos)) != -1) {\n future.reportResult(FileSearchResult(QDir::toNativeSeparators(s), lineNr, line,\n pos, expression.matchedLength()));\n pos += expression.matchedLength();\n }\n ++lineNr;\n }\n ++numFilesSearched;\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 of %4 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched).arg(files.size()));\n }\n if (!future.isCanceled())\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n}\n\n} \/\/ namespace\n\n\nQFuture<FileSearchResult> Core::Utils::findInFiles(const QString &searchTerm, const QStringList &files,\n QTextDocument::FindFlags flags)\n{\n return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags>(runFileSearch, searchTerm, files, flags);\n}\n\nQFuture<FileSearchResult> Core::Utils::findInFilesRegExp(const QString &searchTerm, const QStringList &files,\n QTextDocument::FindFlags flags)\n{\n return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags>(runFileSearchRegExp, searchTerm, files, flags);\n}\n<commit_msg>escape backslash => make \"whole words only\" work with \"regular expression\"<commit_after>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.2, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"filesearch.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QFutureInterface>\n#include <QtCore\/QtConcurrentRun>\n#include <QtCore\/QRegExp>\n#include <QtGui\/QApplication>\n\n#include <qtconcurrent\/runextensions.h>\n\nusing namespace Core::Utils;\n\nnamespace {\n\nvoid runFileSearch(QFutureInterface<FileSearchResult> &future,\n QString searchTerm,\n QStringList files,\n QTextDocument::FindFlags flags)\n{\n future.setProgressRange(0, files.size());\n int numFilesSearched = 0;\n int numMatches = 0;\n\n bool caseInsensitive = !(flags & QTextDocument::FindCaseSensitively);\n bool wholeWord = (flags & QTextDocument::FindWholeWords);\n\n QByteArray sa = searchTerm.toUtf8();\n int scMaxIndex = sa.length()-1;\n const char *sc = sa.constData();\n\n QByteArray sal = searchTerm.toLower().toUtf8();\n const char *scl = sal.constData();\n\n QByteArray sau = searchTerm.toUpper().toUtf8();\n const char *scu = sau.constData();\n\n int chunkSize = qMax(100000, sa.length());\n\n foreach (QString s, files) {\n if (future.isPaused())\n future.waitForResume();\n if (future.isCanceled()) {\n future.setProgressValueAndText(numFilesSearched,\n qApp->translate(\"FileSearch\", \"%1: canceled. %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n break;\n }\n QFile file(s);\n if (!file.open(QIODevice::ReadOnly))\n continue;\n int lineNr = 1;\n const char *startOfLastLine = NULL;\n\n bool firstChunk = true;\n while (!file.atEnd()) {\n if (!firstChunk)\n file.seek(file.pos()-sa.length()+1);\n\n const QByteArray chunk = file.read(chunkSize);\n const char *chunkPtr = chunk.constData();\n startOfLastLine = chunkPtr;\n for (const char *regionPtr = chunkPtr; regionPtr < chunkPtr + chunk.length()-scMaxIndex; ++regionPtr) {\n const char *regionEnd = regionPtr + scMaxIndex;\n\n if (*regionPtr == '\\n') {\n startOfLastLine = regionPtr + 1;\n ++lineNr;\n }\n else if (\n \/\/ case sensitive\n (!caseInsensitive && *regionPtr == sc[0] && *regionEnd == sc[scMaxIndex])\n ||\n \/\/ case insensitive\n (caseInsensitive && (*regionPtr == scl[0] || *regionPtr == scu[0])\n && (*regionEnd == scl[scMaxIndex] || *regionEnd == scu[scMaxIndex]))\n ) {\n const char *afterRegion = regionEnd + 1;\n const char *beforeRegion = regionPtr - 1;\n bool equal = true;\n if (wholeWord &&\n ( ((*beforeRegion >= '0' && *beforeRegion <= '9') || *beforeRegion >= 'A')\n || ((*afterRegion >= '0' && *afterRegion <= '9') || *afterRegion >= 'A')))\n {\n equal = false;\n }\n\n int regionIndex = 1;\n for (const char *regionCursor = regionPtr + 1; regionCursor < regionEnd; ++regionCursor, ++regionIndex) {\n if ( \/\/ case sensitive\n (!caseInsensitive && equal && *regionCursor != sc[regionIndex])\n ||\n \/\/ case insensitive\n (caseInsensitive && equal && *regionCursor != sc[regionIndex] && *regionCursor != scl[regionIndex] && *regionCursor != scu[regionIndex])\n ) {\n equal = false;\n }\n }\n if (equal) {\n int textLength = chunk.length() - (startOfLastLine - chunkPtr);\n if (textLength > 0) {\n QByteArray res;\n res.reserve(256);\n int i = 0;\n int n = 0;\n while (startOfLastLine[i] != '\\n' && startOfLastLine[i] != '\\r' && i < textLength && n++ < 256)\n res.append(startOfLastLine[i++]);\n future.reportResult(FileSearchResult(QDir::toNativeSeparators(s), lineNr, QString(res),\n regionPtr - startOfLastLine, sa.length()));\n ++numMatches;\n }\n }\n }\n }\n firstChunk = false;\n }\n ++numFilesSearched;\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 of %4 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched).arg(files.size()));\n }\n if (!future.isCanceled())\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n}\n\nvoid runFileSearchRegExp(QFutureInterface<FileSearchResult> &future,\n QString searchTerm,\n QStringList files,\n QTextDocument::FindFlags flags)\n{\n future.setProgressRange(0, files.size());\n int numFilesSearched = 0;\n int numMatches = 0;\n if (flags & QTextDocument::FindWholeWords)\n searchTerm = QString(\"\\\\b%1\\\\b\").arg(searchTerm);\n Qt::CaseSensitivity caseSensitivity = (flags & QTextDocument::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive;\n QRegExp expression(searchTerm, caseSensitivity);\n\n foreach (QString s, files) {\n if (future.isPaused())\n future.waitForResume();\n if (future.isCanceled()) {\n future.setProgressValueAndText(numFilesSearched,\n qApp->translate(\"FileSearch\", \"%1: canceled. %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n break;\n }\n QFile file(s);\n if (!file.open(QIODevice::ReadOnly))\n continue;\n QTextStream stream(&file);\n int lineNr = 1;\n QString line;\n while (!stream.atEnd()) {\n line = stream.readLine();\n int pos = 0;\n while ((pos = expression.indexIn(line, pos)) != -1) {\n future.reportResult(FileSearchResult(QDir::toNativeSeparators(s), lineNr, line,\n pos, expression.matchedLength()));\n pos += expression.matchedLength();\n }\n ++lineNr;\n }\n ++numFilesSearched;\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 of %4 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched).arg(files.size()));\n }\n if (!future.isCanceled())\n future.setProgressValueAndText(numFilesSearched, qApp->translate(\"FileSearch\", \"%1: %2 occurrences found in %3 files.\").\n arg(searchTerm).arg(numMatches).arg(numFilesSearched));\n}\n\n} \/\/ namespace\n\n\nQFuture<FileSearchResult> Core::Utils::findInFiles(const QString &searchTerm, const QStringList &files,\n QTextDocument::FindFlags flags)\n{\n return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags>(runFileSearch, searchTerm, files, flags);\n}\n\nQFuture<FileSearchResult> Core::Utils::findInFilesRegExp(const QString &searchTerm, const QStringList &files,\n QTextDocument::FindFlags flags)\n{\n return QtConcurrent::run<FileSearchResult, QString, QStringList, QTextDocument::FindFlags>(runFileSearchRegExp, searchTerm, files, flags);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* $Id: middlewareSubscriptionTests.cpp,v 1.1.2.5 2012\/12\/17 15:46:04 matthewmulhern Exp $\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include <gtest\/gtest.h>\n#include \"mama\/mama.h\"\n#include \"MainUnitTestC.h\"\n#include <iostream>\n#include \"bridge.h\"\n#include \"mama\/types.h\"\n\nusing std::cout;\nusing std::endl;\n\nstatic void onCreate (mamaSubscription subscription, void* closure);\n\nstatic void onError(mamaSubscription subscription,\n mama_status status,\n void* platformError,\n const char* subject,\n void* closure);\n\nstatic void onQuality(mamaSubscription subsc,\n mamaQuality quality,\n const char* symbol,\n short cause,\n const void* platformInfo,\n void* closure);\n\nstatic void onMsg(mamaSubscription subscription,\n mamaMsg msg,\n void* closure,\n void* itemClosure);\n\nstatic void onGap(mamaSubscription subsc, void* closure);\nstatic void onRecapRequest(mamaSubscription subsc, void* closure);\nstatic void onDestroy(mamaSubscription subsc, void* closure);\n\nclass MiddlewareSubscriptionTests : public ::testing::Test\n{\nprotected:\n MiddlewareSubscriptionTests(void);\n virtual ~MiddlewareSubscriptionTests(void);\n\n virtual void SetUp(void);\n virtual void TearDown(void);\n\n mamaBridge mBridge;\n mamaTransport tport;\n const char* tportName;\n\n subscriptionBridge subscriber;\n mamaSource source;\n const char* sourceName;\n const char* symbol;\n mamaQueue queue;\n void* closure;\n mamaSubscription parent;\n mamaMsgCallbacks callbacks;\n};\n\nMiddlewareSubscriptionTests::MiddlewareSubscriptionTests(void)\n : tport (NULL),\n tportName (\"test_tport\"),\n source (NULL),\n sourceName (\"src\"),\n symbol (\"SYM\"),\n queue (NULL),\n closure (NULL)\n{\n mama_loadBridge (&mBridge, getMiddleware());\n\n mamaQueue_create(&queue, mBridge);\n}\n\nMiddlewareSubscriptionTests::~MiddlewareSubscriptionTests(void)\n{\n mamaQueue_destroy (queue);\n}\n\nvoid MiddlewareSubscriptionTests::SetUp(void)\n{\n mama_open(); \/* Forces loading of entitlements bridges as necessary *\/\n mamaTransport_allocate (&tport);\n mamaTransport_create (tport, tportName, mBridge);\n\n mamaSource_create(&source);\n mamaSource_setId(source, \"SRC\");\n mamaSource_setTransport(source, tport);\n mamaSource_setSymbolNamespace(source, \"NASDAQ\");\n\n mamaSubscription_allocate(&parent);\n\n callbacks.onCreate = onCreate; \n callbacks.onError = onError; \n callbacks.onQuality = onQuality; \n callbacks.onMsg = onMsg; \n callbacks.onGap = onGap; \n callbacks.onRecapRequest = onRecapRequest;\n callbacks.onDestroy = onDestroy;\n}\n\nvoid MiddlewareSubscriptionTests::TearDown(void)\n{\n mamaTransport_destroy (tport);\n mamaSubscription_deallocate(parent);\n mama_close();\n}\n\nstatic void onCreate (mamaSubscription subscription,\n void* closure)\n{\n}\n\nstatic void onError(mamaSubscription subscription,\n mama_status status,\n void* platformError,\n const char* subject,\n void* closure)\n{\n}\n\nstatic void onQuality(mamaSubscription subsc,\n mamaQuality quality,\n const char* symbol,\n short cause,\n const void* platformInfo,\n void* closure)\n{\n}\n\nstatic void onMsg(mamaSubscription subscription,\n mamaMsg msg,\n void* closure,\n void* itemClosure)\n{\n}\n\nstatic void onGap(mamaSubscription subsc, void* closure)\n{\n}\n\nstatic void onRecapRequest(mamaSubscription subsc, void* closure)\n{\n}\n\nstatic void onDestroy(mamaSubscription subsc, void* closure)\n{\n}\n\n\n\/*===================================================================\n = mamaSubscription bridge functions =\n ====================================================================*\/\n\n\/* TODO:\n * Discuss the validity of these tests - ultimately we double create\n * subscriptions, which I would assume isn't supposed to be expected behaviour.\n *\/\nTEST_F (MiddlewareSubscriptionTests, DISABLED_createDestroy)\n\/* cores*\/\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_destroy(parent));\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_deallocate(parent));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidResult)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(NULL, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidTport)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n NULL, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidSourceName)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, NULL, symbol,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidSymbol)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, NULL,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidQueue)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, NULL, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidParent)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n NULL, closure));\n}\n\/* TEST COMMENTED OUT BECAUSE mamaMsgCallbacks CAN'T BE CAST AS NULL!\nTEST_F (MiddlewareSubscriptionTests, createInvalidCallbacks)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, NULL,\n parent, closure));\n}\n*\/\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidResult)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(NULL, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSource)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, NULL, symbol,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSymbol)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, NULL,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidTport)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n NULL, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidQueue)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n tport, NULL, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidParent)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n NULL, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n status);\n}\n\/* COMMENTED OUT BECAUSE mamaMsg Callbacks CAN'T BE CAST AS NULL\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidCallbacks)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol, \n tport, queue, NULL, \n parent, closure));\n}\n*\/\n\nTEST_F (MiddlewareSubscriptionTests, mute)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK, \n mBridge->bridgeMamaSubscriptionMute(subscriber));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n}\n\nTEST_F (MiddlewareSubscriptionTests, muteInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionMute(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, destroyInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionDestroy(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, isValid)\n{\n int res = NULL;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n \n res = mBridge->bridgeMamaSubscriptionIsValid(subscriber);\n ASSERT_TRUE(res != NULL);\n\n}\n\nTEST_F (MiddlewareSubscriptionTests, isValidInvalid)\n{\n int res = NULL;\n\n res = mBridge->bridgeMamaSubscriptionIsValid(NULL);\n \n ASSERT_TRUE(res == 0);\n}\n\n\nTEST_F (MiddlewareSubscriptionTests, hasWildcards)\n{\n int res = NULL;\n\n res = mBridge->bridgeMamaSubscriptionHasWildcards(NULL);\n \n ASSERT_TRUE(res == 0);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformError)\n{\n void* error = NOT_NULL;\n mama_status status = MAMA_STATUS_OK;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK,\n \t\t mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n \t\t tport, queue, callbacks,\n \t\t parent, closure));\n\n status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber, &error);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidError)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber,\n NULL);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ (MAMA_STATUS_NULL_ARG,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidSubBridge)\n{\n void* error = NOT_NULL;\n mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(NULL,\n &error);\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, isTportDisconnectedInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionIsTportDisconnected(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, setTopicClosure)\n{\n void* newClosure = NOT_NULL;\n mama_status status = MAMA_STATUS_OK;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n status = mBridge->bridgeMamaSubscriptionSetTopicClosure(subscriber,newClosure);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ (MAMA_STATUS_OK,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, setTopicClosureInvalidSubBridge)\n{\n void* closure = NOT_NULL;\n mama_status status = mBridge->bridgeMamaSubscriptionSetTopicClosure(NULL,\n closure);\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n status);\n}\n\n\nTEST_F (MiddlewareSubscriptionTests, muteCurrentTopic)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK, \n mBridge->bridgeMamaSubscriptionMuteCurrentTopic(subscriber));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n}\n\nTEST_F (MiddlewareSubscriptionTests, muteCurrentTopicInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionMuteCurrentTopic(NULL));\n}\n\n<commit_msg>UNITTEST: Fixed issue where MAMA queue destroy was attempted after close<commit_after>\/* $Id: middlewareSubscriptionTests.cpp,v 1.1.2.5 2012\/12\/17 15:46:04 matthewmulhern Exp $\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include <gtest\/gtest.h>\n#include \"mama\/mama.h\"\n#include \"MainUnitTestC.h\"\n#include <iostream>\n#include \"bridge.h\"\n#include \"mama\/types.h\"\n\nusing std::cout;\nusing std::endl;\n\nstatic void onCreate (mamaSubscription subscription, void* closure);\n\nstatic void onError(mamaSubscription subscription,\n mama_status status,\n void* platformError,\n const char* subject,\n void* closure);\n\nstatic void onQuality(mamaSubscription subsc,\n mamaQuality quality,\n const char* symbol,\n short cause,\n const void* platformInfo,\n void* closure);\n\nstatic void onMsg(mamaSubscription subscription,\n mamaMsg msg,\n void* closure,\n void* itemClosure);\n\nstatic void onGap(mamaSubscription subsc, void* closure);\nstatic void onRecapRequest(mamaSubscription subsc, void* closure);\nstatic void onDestroy(mamaSubscription subsc, void* closure);\n\nclass MiddlewareSubscriptionTests : public ::testing::Test\n{\nprotected:\n MiddlewareSubscriptionTests(void);\n virtual ~MiddlewareSubscriptionTests(void);\n\n virtual void SetUp(void);\n virtual void TearDown(void);\n\n mamaBridge mBridge;\n mamaTransport tport;\n const char* tportName;\n\n subscriptionBridge subscriber;\n mamaSource source;\n const char* sourceName;\n const char* symbol;\n mamaQueue queue;\n void* closure;\n mamaSubscription parent;\n mamaMsgCallbacks callbacks;\n};\n\nMiddlewareSubscriptionTests::MiddlewareSubscriptionTests(void)\n : tport (NULL),\n tportName (\"test_tport\"),\n source (NULL),\n sourceName (\"src\"),\n symbol (\"SYM\"),\n queue (NULL),\n closure (NULL)\n{\n mama_loadBridge (&mBridge, getMiddleware());\n\n mamaQueue_create(&queue, mBridge);\n}\n\nMiddlewareSubscriptionTests::~MiddlewareSubscriptionTests(void)\n{\n}\n\nvoid MiddlewareSubscriptionTests::SetUp(void)\n{\n mama_open(); \/* Forces loading of entitlements bridges as necessary *\/\n mamaTransport_allocate (&tport);\n mamaTransport_create (tport, tportName, mBridge);\n\n mamaSource_create(&source);\n mamaSource_setId(source, \"SRC\");\n mamaSource_setTransport(source, tport);\n mamaSource_setSymbolNamespace(source, \"NASDAQ\");\n\n mamaSubscription_allocate(&parent);\n\n callbacks.onCreate = onCreate; \n callbacks.onError = onError; \n callbacks.onQuality = onQuality; \n callbacks.onMsg = onMsg; \n callbacks.onGap = onGap; \n callbacks.onRecapRequest = onRecapRequest;\n callbacks.onDestroy = onDestroy;\n}\n\nvoid MiddlewareSubscriptionTests::TearDown(void)\n{\n mamaTransport_destroy (tport);\n mamaSubscription_deallocate(parent);\n mamaQueue_destroy (queue);\n mama_close();\n}\n\nstatic void onCreate (mamaSubscription subscription,\n void* closure)\n{\n}\n\nstatic void onError(mamaSubscription subscription,\n mama_status status,\n void* platformError,\n const char* subject,\n void* closure)\n{\n}\n\nstatic void onQuality(mamaSubscription subsc,\n mamaQuality quality,\n const char* symbol,\n short cause,\n const void* platformInfo,\n void* closure)\n{\n}\n\nstatic void onMsg(mamaSubscription subscription,\n mamaMsg msg,\n void* closure,\n void* itemClosure)\n{\n}\n\nstatic void onGap(mamaSubscription subsc, void* closure)\n{\n}\n\nstatic void onRecapRequest(mamaSubscription subsc, void* closure)\n{\n}\n\nstatic void onDestroy(mamaSubscription subsc, void* closure)\n{\n}\n\n\n\/*===================================================================\n = mamaSubscription bridge functions =\n ====================================================================*\/\n\n\/* TODO:\n * Discuss the validity of these tests - ultimately we double create\n * subscriptions, which I would assume isn't supposed to be expected behaviour.\n *\/\nTEST_F (MiddlewareSubscriptionTests, DISABLED_createDestroy)\n\/* cores*\/\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_destroy(parent));\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_deallocate(parent));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidResult)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(NULL, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidTport)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n NULL, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidSourceName)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, NULL, symbol,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidSymbol)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, NULL,\n tport, queue, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidQueue)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, NULL, callbacks,\n parent, closure));\n}\n\nTEST_F (MiddlewareSubscriptionTests, createInvalidParent)\n{\n ASSERT_EQ(MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n NULL, closure));\n}\n\/* TEST COMMENTED OUT BECAUSE mamaMsgCallbacks CAN'T BE CAST AS NULL!\nTEST_F (MiddlewareSubscriptionTests, createInvalidCallbacks)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, NULL,\n parent, closure));\n}\n*\/\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidResult)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(NULL, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSource)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, NULL, symbol,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidSymbol)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, NULL,\n tport, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidTport)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n NULL, queue, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidQueue)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n tport, NULL, callbacks,\n parent, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n \t\t status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidParent)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n NULL, closure);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ(MAMA_STATUS_OK,\n status);\n}\n\/* COMMENTED OUT BECAUSE mamaMsg Callbacks CAN'T BE CAST AS NULL\nTEST_F (MiddlewareSubscriptionTests, createWildCardInvalidCallbacks)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreateWildCard(&subscriber, sourceName, symbol, \n tport, queue, NULL, \n parent, closure));\n}\n*\/\n\nTEST_F (MiddlewareSubscriptionTests, mute)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK, \n mBridge->bridgeMamaSubscriptionMute(subscriber));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n}\n\nTEST_F (MiddlewareSubscriptionTests, muteInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionMute(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, destroyInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionDestroy(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, isValid)\n{\n int res = NULL;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n \n res = mBridge->bridgeMamaSubscriptionIsValid(subscriber);\n ASSERT_TRUE(res != NULL);\n\n}\n\nTEST_F (MiddlewareSubscriptionTests, isValidInvalid)\n{\n int res = NULL;\n\n res = mBridge->bridgeMamaSubscriptionIsValid(NULL);\n \n ASSERT_TRUE(res == 0);\n}\n\n\nTEST_F (MiddlewareSubscriptionTests, hasWildcards)\n{\n int res = NULL;\n\n res = mBridge->bridgeMamaSubscriptionHasWildcards(NULL);\n \n ASSERT_TRUE(res == 0);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformError)\n{\n void* error = NOT_NULL;\n mama_status status = MAMA_STATUS_OK;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK,\n \t\t mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n \t\t tport, queue, callbacks,\n \t\t parent, closure));\n\n status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber, &error);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidError)\n{\n\tmama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(subscriber,\n NULL);\n\tCHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ (MAMA_STATUS_NULL_ARG,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, getPlatformErrorInvalidSubBridge)\n{\n void* error = NOT_NULL;\n mama_status status = mBridge->bridgeMamaSubscriptionGetPlatformError(NULL,\n &error);\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, isTportDisconnectedInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionIsTportDisconnected(NULL));\n}\n\nTEST_F (MiddlewareSubscriptionTests, setTopicClosure)\n{\n void* newClosure = NOT_NULL;\n mama_status status = MAMA_STATUS_OK;\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n status = mBridge->bridgeMamaSubscriptionSetTopicClosure(subscriber,newClosure);\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ (MAMA_STATUS_OK,\n status);\n}\n\nTEST_F (MiddlewareSubscriptionTests, setTopicClosureInvalidSubBridge)\n{\n void* closure = NOT_NULL;\n mama_status status = mBridge->bridgeMamaSubscriptionSetTopicClosure(NULL,\n closure);\n\n CHECK_NON_IMPLEMENTED_OPTIONAL(status);\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n status);\n}\n\n\nTEST_F (MiddlewareSubscriptionTests, muteCurrentTopic)\n{\n ASSERT_EQ(MAMA_STATUS_OK,\n mamaSubscription_create(parent, queue, &callbacks, source, sourceName, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionCreate(&subscriber, sourceName, symbol,\n tport, queue, callbacks,\n parent, closure));\n\n ASSERT_EQ (MAMA_STATUS_OK, \n mBridge->bridgeMamaSubscriptionMuteCurrentTopic(subscriber));\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mBridge->bridgeMamaSubscriptionDestroy(subscriber));\n}\n\nTEST_F (MiddlewareSubscriptionTests, muteCurrentTopicInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaSubscriptionMuteCurrentTopic(NULL));\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"motor\/car_motor_mapper.hpp\"\n\n#include <array>\n#include <cstddef>\n#include \"protocol\/messages.hpp\"\n\nCarMotorMapper::CarMotorMapper(PWMDeviceGroup<4>& motorDevices, PWMDeviceGroup<4>& servoDevices, Communicator& communicator)\n : motorDevices(motorDevices),\n servoDevices(servoDevices),\n throttleStream(communicator, 1) {\n}\n\nvoid CarMotorMapper::init() {\n}\n\nvoid CarMotorMapper::run(bool armed, actuator_setpoint_t& input) {\n \/\/ Motor speeds depend only on throttle input\n std::array<float, 4> motors {\n input.throttle_sp, \/\/ front left\n input.throttle_sp, \/\/ back left\n input.throttle_sp, \/\/ back right\n input.throttle_sp \/\/ front right\n };\n\n motorDevices.set(armed, motorOutputs);\n\n \/\/ Servos control yaw angle of the vehicle\n std::array<float, 4> servos {\n \/\/ TODO(kyle): signs\n -input.yaw_sp \/ 2, \/\/ front left\n input.yaw_sp \/ 2, \/\/ back left\n input.yaw_sp \/ 2, \/\/ back right\n -input.yaw_sp \/ 2 \/\/ front right\n };\n\n servoDevices.set(armed, servoOutputs);\n\n if(throttleStream.ready()) {\n protocol::message::motor_throttle_message_t msg;\n\n for(std::size_t i = 0; i < 4; i++) {\n msg.throttles[i] = motorOutputs[i];\n }\n\n throttleStream.publish(msg);\n }\n}\n<commit_msg>Fix changed name.<commit_after>#include \"motor\/car_motor_mapper.hpp\"\n\n#include <array>\n#include <cstddef>\n#include \"protocol\/messages.hpp\"\n\nCarMotorMapper::CarMotorMapper(PWMDeviceGroup<4>& motorDevices, PWMDeviceGroup<4>& servoDevices, Communicator& communicator)\n : motorDevices(motorDevices),\n servoDevices(servoDevices),\n throttleStream(communicator, 1) {\n}\n\nvoid CarMotorMapper::init() {\n}\n\nvoid CarMotorMapper::run(bool armed, actuator_setpoint_t& input) {\n \/\/ Motor speeds depend only on throttle input\n std::array<float, 4> motors {\n input.throttle_sp, \/\/ front left\n input.throttle_sp, \/\/ back left\n input.throttle_sp, \/\/ back right\n input.throttle_sp \/\/ front right\n };\n\n motorDevices.set(armed, motors);\n\n \/\/ Servos control yaw angle of the vehicle\n std::array<float, 4> servos {\n \/\/ TODO(kyle): signs\n -input.yaw_sp \/ 2, \/\/ front left\n input.yaw_sp \/ 2, \/\/ back left\n input.yaw_sp \/ 2, \/\/ back right\n -input.yaw_sp \/ 2 \/\/ front right\n };\n\n servoDevices.set(armed, servos);\n\n if(throttleStream.ready()) {\n protocol::message::motor_throttle_message_t msg;\n\n for(std::size_t i = 0; i < 4; i++) {\n msg.throttles[i] = motors[i];\n }\n\n throttleStream.publish(msg);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n#include <string>\n#include <boost\/lexical_cast.hpp>\n#include \"asioWrapper.h\"\n\nnamespace twitpp {\nnamespace asioWrapper {\n\nnamespace asio = boost::asio;\n\nClient::Client(asio::io_service& io_service, asio::ssl::context& context, const std::string& host, const std::string& path)\n : resolver_(io_service), socket_(io_service, context), host_(host), path_(path) {}\n\n\/\/ GET method\nvoid Client::get(const std::string& header, std::function<void(std::string&)> handler) {\n handler_ = handler;\n\n \/\/ create request;\n std::ostream request_stream(&request_buffer_);\n request_stream << \"GET \" << path_ << \" HTTP\/1.1\\r\\n\";\n request_stream << \"Host: \" << host_ << \"\\r\\n\";\n request_stream << \"Accept: *\/*\\r\\n\";\n if (!header.empty()) {\n request_stream << header << \"\\r\\n\";\n }\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n\n \/\/ get server name and host info\n asio::ip::tcp::resolver::query query(host_, \"443\");\n resolver_.async_resolve(query,\n boost::bind(&Client::handleResolve, this, asio::placeholders::error, asio::placeholders::iterator));\n}\n\n\/\/ POST method\nvoid Client::post(const std::string& header, const std::string& data, std::function<void(std::string&)> handler) {\n handler_ = handler;\n\n \/\/ create request;\n std::ostream request_stream(&request_buffer_);\n request_stream << \"POST \" << path_ << \" HTTP\/1.1\\r\\n\";\n request_stream << \"Host: \" << host_ << \"\\r\\n\";\n request_stream << \"Accept: *\/*\\r\\n\";\n if (!header.empty()) {\n request_stream << header << \"\\r\\n\";\n }\n if (!data.empty()) {\n request_stream << \"Content-Length: \" << data.length() << \"\\r\\n\";\n request_stream << \"Content-Type: application\/x-www-form-urlencoded\\r\\n\";\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n request_stream << data << \"\\r\\n\";\n } else {\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n }\n\n \/\/ get server name and host info\n asio::ip::tcp::resolver::query query(host_, \"443\");\n resolver_.async_resolve(query,\n boost::bind(&Client::handleResolve, this, asio::placeholders::error, asio::placeholders::iterator));\n}\n\nvoid Client::handleResolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpoint_iterator) {\n if (!error) {\n asio::async_connect(socket_.lowest_layer(), endpoint_iterator,\n boost::bind(&Client::handleConnect, this, asio::placeholders::error));\n } else {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleConnect(const boost::system::error_code& error) {\n if (!error) {\n socket_.async_handshake(asio::ssl::stream_base::client,\n boost::bind(&Client::handleHandshake, this, asio::placeholders::error));\n } else {\n std::cout << \"Connect failed: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleHandshake(const boost::system::error_code& error) {\n if (!error) {\n asio::async_write(socket_, request_buffer_, boost::bind(&Client::handleWrite, this, asio::placeholders::error));\n } else {\n std::cout << \"Handshake failed: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleWrite(const boost::system::error_code& error) {\n if (!error) {\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadStatus, this, asio::placeholders::error));\n } else {\n std::cout << \"Write failed: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadStatus(const boost::system::error_code& error) {\n if (!error) {\n \/\/ check response\n std::istream responseStream(&response_buffer_);\n responseStream >> response_.http_version;\n responseStream >> response_.status_code;\n std::getline(responseStream, response_.status_message);\n\n if (!responseStream || response_.http_version.substr(0, 5) != \"HTTP\/\") {\n std::cout << \"Invalid response\\n\";\n return;\n }\n\n \/\/ read response header\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\\r\\n\",\n boost::bind(&Client::handleReadHeader, this, asio::placeholders::error));\n } else {\n std::cout << \"Read failed: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadHeader(const boost::system::error_code& error) {\n if (!error) {\n \/\/ read response header\n std::istream responseStream(&response_buffer_);\n std::string header;\n while (std::getline(responseStream, header) && header != \"\\r\") {\n std::string field_name(header, 0, header.find(\":\", 0));\n std::string field_body(header, header.find(\":\", 0) + 2);\n\n response_.response_header[field_name] = field_body;\n }\n\n if (response_.response_header.count(\"transfer-encoding\") != 0 ||\n response_.response_header[\"transfer-encoding\"] == \"chunked\") {\n \/\/ chuncked transfer\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else if (response_.response_header.count(\"Content-Length\") != 0) {\n \/\/ use content length\n std::size_t content_length = std::stoi(response_.response_header[\"Content-Length\"]);\n\n asio::async_read(socket_, response_buffer_,\n asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadContent, this, content_length, asio::placeholders::error));\n } else if (response_.response_header.count(\"content-length\") != 0) {\n std::size_t content_length = std::stoi(response_.response_header[\"content-length\"]);\n\n asio::async_read(socket_, response_buffer_,\n asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadContent, this, content_length, asio::placeholders::error));\n } else {\n \/\/ other (not working now\n asio::async_read(socket_, response_buffer_, asio::transfer_all(),\n boost::bind(&Client::handleReadContentAll, this, asio::placeholders::error));\n }\n\n } else {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadChunkSize(const boost::system::error_code& error) {\n if (!error) {\n if (response_buffer_.size() == 0) {\n return;\n } else if (response_buffer_.size() <= 2) {\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else {\n \/\/ read chunk size\n boost::system::error_code ec;\n asio::read_until(socket_, response_buffer_, \"\\r\\n\", ec);\n std::size_t chunk;\n response_buffer_.consume(chunk_parser((std::string)asio::buffer_cast<const char*>(response_buffer_.data()), chunk));\n\n asio::async_read(socket_, response_buffer_, asio::transfer_at_least(chunk - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadChunkBody, this, chunk, asio::placeholders::error));\n }\n } else if (error != asio::error::eof) {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadChunkBody(std::size_t content_length, const boost::system::error_code& error) {\n if (!error) {\n boost::system::error_code ec;\n asio::read(socket_, response_buffer_,\n asio::transfer_at_least((content_length + 2) - asio::buffer_size(response_buffer_.data())), ec);\n\n response_.response_body.append(boost::asio::buffer_cast<const char*>(response_buffer_.data()), content_length);\n response_buffer_.consume(content_length + 2);\n handler_(response_.response_body);\n\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else if (error != asio::error::eof) {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadContent(std::size_t content_length, const boost::system::error_code& error) {\n if (!error) {\n if (response_buffer_.size() == 0) {\n std::cout << \"ERROR\" << std::endl;\n }\n\n response_.response_body.append(asio::buffers_begin(response_buffer_.data()), asio::buffers_end(response_buffer_.data()));\n response_buffer_.consume(response_buffer_.size());\n handler_(response_.response_body);\n } else if (error != asio::error::eof) {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\nvoid Client::handleReadContentAll(const boost::system::error_code& error) {\n if (!error) {\n std::ostringstream tmp;\n tmp << &response_buffer_;\n response_.response_body = tmp.str();\n handler_(response_.response_body);\n\n \/\/ Continue reading remaining data until EOF.\n asio::async_read(socket_, response_buffer_, asio::transfer_at_least(1),\n boost::bind(&Client::handleReadContentAll, this, asio::placeholders::error));\n } else if (error != asio::error::eof) {\n std::cout << \"Error: \" << error.message() << \"\\n\";\n }\n}\n\n}\n}\n<commit_msg>change error massage<commit_after>#include <sstream>\n#include <string>\n#include <boost\/lexical_cast.hpp>\n#include \"asioWrapper.h\"\n\nnamespace twitpp {\nnamespace asioWrapper {\n\nnamespace asio = boost::asio;\n\nClient::Client(asio::io_service& io_service, asio::ssl::context& context, const std::string& host, const std::string& path)\n : resolver_(io_service), socket_(io_service, context), host_(host), path_(path) {}\n\n\/\/ GET method\nvoid Client::get(const std::string& header, std::function<void(std::string&)> handler) {\n handler_ = handler;\n\n \/\/ create request;\n std::ostream request_stream(&request_buffer_);\n request_stream << \"GET \" << path_ << \" HTTP\/1.1\\r\\n\";\n request_stream << \"Host: \" << host_ << \"\\r\\n\";\n request_stream << \"Accept: *\/*\\r\\n\";\n if (!header.empty()) {\n request_stream << header << \"\\r\\n\";\n }\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n\n \/\/ get server name and host info\n asio::ip::tcp::resolver::query query(host_, \"443\");\n resolver_.async_resolve(query,\n boost::bind(&Client::handleResolve, this, asio::placeholders::error, asio::placeholders::iterator));\n}\n\n\/\/ POST method\nvoid Client::post(const std::string& header, const std::string& data, std::function<void(std::string&)> handler) {\n handler_ = handler;\n\n \/\/ create request;\n std::ostream request_stream(&request_buffer_);\n request_stream << \"POST \" << path_ << \" HTTP\/1.1\\r\\n\";\n request_stream << \"Host: \" << host_ << \"\\r\\n\";\n request_stream << \"Accept: *\/*\\r\\n\";\n if (!header.empty()) {\n request_stream << header << \"\\r\\n\";\n }\n if (!data.empty()) {\n request_stream << \"Content-Length: \" << data.length() << \"\\r\\n\";\n request_stream << \"Content-Type: application\/x-www-form-urlencoded\\r\\n\";\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n request_stream << data << \"\\r\\n\";\n } else {\n request_stream << \"Connection: close\\r\\n\\r\\n\";\n }\n\n \/\/ get server name and host info\n asio::ip::tcp::resolver::query query(host_, \"443\");\n resolver_.async_resolve(query,\n boost::bind(&Client::handleResolve, this, asio::placeholders::error, asio::placeholders::iterator));\n}\n\nvoid Client::handleResolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpoint_iterator) {\n if (!error) {\n asio::async_connect(socket_.lowest_layer(), endpoint_iterator,\n boost::bind(&Client::handleConnect, this, asio::placeholders::error));\n } else {\n std::cout << \"Resolve failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleConnect(const boost::system::error_code& error) {\n if (!error) {\n socket_.async_handshake(asio::ssl::stream_base::client,\n boost::bind(&Client::handleHandshake, this, asio::placeholders::error));\n } else {\n std::cout << \"Connect failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleHandshake(const boost::system::error_code& error) {\n if (!error) {\n asio::async_write(socket_, request_buffer_, boost::bind(&Client::handleWrite, this, asio::placeholders::error));\n } else {\n std::cout << \"Handshake failed: \" << error.value()<< \"\\n\";\n }\n}\n\nvoid Client::handleWrite(const boost::system::error_code& error) {\n if (!error) {\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadStatus, this, asio::placeholders::error));\n } else {\n std::cout << \"Write failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadStatus(const boost::system::error_code& error) {\n if (!error) {\n \/\/ check response\n std::istream responseStream(&response_buffer_);\n responseStream >> response_.http_version;\n responseStream >> response_.status_code;\n std::getline(responseStream, response_.status_message);\n\n if (!responseStream || response_.http_version.substr(0, 5) != \"HTTP\/\") {\n std::cout << \"Invalid response\\n\";\n return;\n }\n\n \/\/ read response header\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\\r\\n\",\n boost::bind(&Client::handleReadHeader, this, asio::placeholders::error));\n } else {\n std::cout << \"Read status failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadHeader(const boost::system::error_code& error) {\n if (!error) {\n \/\/ read response header\n std::istream responseStream(&response_buffer_);\n std::string header;\n while (std::getline(responseStream, header) && header != \"\\r\") {\n std::string field_name(header, 0, header.find(\":\", 0));\n std::string field_body(header, header.find(\":\", 0) + 2);\n\n response_.response_header[field_name] = field_body;\n }\n\n if (response_.response_header.count(\"transfer-encoding\") != 0 ||\n response_.response_header[\"transfer-encoding\"] == \"chunked\") {\n \/\/ chuncked transfer\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else if (response_.response_header.count(\"Content-Length\") != 0) {\n \/\/ use content length\n std::size_t content_length = std::stoi(response_.response_header[\"Content-Length\"]);\n\n asio::async_read(socket_, response_buffer_,\n asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadContent, this, content_length, asio::placeholders::error));\n } else if (response_.response_header.count(\"content-length\") != 0) {\n std::size_t content_length = std::stoi(response_.response_header[\"content-length\"]);\n\n asio::async_read(socket_, response_buffer_,\n asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadContent, this, content_length, asio::placeholders::error));\n } else {\n \/\/ other (not working now\n asio::async_read(socket_, response_buffer_, asio::transfer_all(),\n boost::bind(&Client::handleReadContentAll, this, asio::placeholders::error));\n }\n\n } else {\n std::cout << \"Read header failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadChunkSize(const boost::system::error_code& error) {\n if (!error) {\n if (response_buffer_.size() == 0) {\n return;\n } else if (response_buffer_.size() <= 2) {\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else {\n \/\/ read chunk size\n boost::system::error_code ec;\n asio::read_until(socket_, response_buffer_, \"\\r\\n\", ec);\n std::size_t chunk;\n response_buffer_.consume(chunk_parser((std::string)asio::buffer_cast<const char*>(response_buffer_.data()), chunk));\n\n asio::async_read(socket_, response_buffer_, asio::transfer_at_least(chunk - asio::buffer_size(response_buffer_.data())),\n boost::bind(&Client::handleReadChunkBody, this, chunk, asio::placeholders::error));\n }\n } else if (error != asio::error::eof) {\n std::cout << \"Read chunksize failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadChunkBody(std::size_t content_length, const boost::system::error_code& error) {\n if (!error) {\n boost::system::error_code ec;\n asio::read(socket_, response_buffer_,\n asio::transfer_at_least((content_length + 2) - asio::buffer_size(response_buffer_.data())), ec);\n\n response_.response_body.append(boost::asio::buffer_cast<const char*>(response_buffer_.data()), content_length);\n response_buffer_.consume(content_length + 2);\n handler_(response_.response_body);\n\n asio::async_read_until(socket_, response_buffer_, \"\\r\\n\",\n boost::bind(&Client::handleReadChunkSize, this, asio::placeholders::error));\n } else if (error != asio::error::eof) {\n std::cout << \"Read chunk failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadContent(std::size_t content_length, const boost::system::error_code& error) {\n if (!error) {\n response_.response_body.append(asio::buffers_begin(response_buffer_.data()), asio::buffers_end(response_buffer_.data()));\n response_buffer_.consume(response_buffer_.size());\n handler_(response_.response_body);\n } else if (error != asio::error::eof) {\n std::cout << \"Read content failed: \" << error.value() << \"\\n\";\n }\n}\n\nvoid Client::handleReadContentAll(const boost::system::error_code& error) {\n if (!error) {\n std::ostringstream tmp;\n tmp << &response_buffer_;\n response_.response_body = tmp.str();\n handler_(response_.response_body);\n\n \/\/ Continue reading remaining data until EOF.\n asio::async_read(socket_, response_buffer_, asio::transfer_at_least(1),\n boost::bind(&Client::handleReadContentAll, this, asio::placeholders::error));\n } else if (error != asio::error::eof) {\n std::cout << \"Read content all failed: \" << error.value() << \"\\n\";\n }\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mugen_background.h\"\n\n#include <math.h>\n#include <ostream>\n#include <cstring>\n#include <string>\n#include <algorithm>\n#include \"globals.h\"\n#include \"mugen_sprite.h\"\n#include \"util\/bitmap.h\"\n\n\/\/static double pi = 3.14159265;\n\nusing namespace std;\n\nstatic double interpolate(double f1, double f2, double p){\n return (f1 * (1.0 - p)) + (f2 * p);\n}\n\nstruct Tile {\n int start;\n int total;\n};\n\nstatic Tile getTileData( int location, int length, int spacing, int total ){\n Tile tile;\n if (total == 0){\n\ttile.start = location;\n\ttile.total = 1;\n\treturn tile;\n } else if (total > 1){\n\ttile.start = location;\n\ttile.total = total;\n\treturn tile;\n } else if (total == 1){\n\t\/\/ Infinite tiling.. just tile on the board\n\tif (location < 0){\n\t \/\/ Less than the board itself lets get location up to that point\n\t while (location < 0){\n\t\tlocation+=spacing;\n\t }\n\t \/\/ Now backup 1 so we get the wrap effect \n\t location-=spacing;\n\t} else{\n\t \/\/ Either Larger than the board or inside seek back to beginning\n\t while (location > 0){\n\t\tlocation-=spacing;\n\t }\n\t}\n\t\/\/ Now figure out how many we need to do\n\tint temp = location;\n\t\/\/ Reuse total\n\ttotal = 0;\n\twhile (temp < length){\n\t total++;\n\t temp+=spacing;\n\t}\n\t\/\/ Blammo\n\ttile.start = location;\n\ttile.total = total;\n\treturn tile;\n }\n tile.start = 0;\n tile.total = 0;\n return tile;\n}\n\nstatic void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){\n const int height = bmp.getHeight();\n const int w = bmp.getWidth();\n int movex = 0;\n \/\/double z = 1.0 \/ z1;\n \/\/const double z_add = ((1.0 \/ z2) - z) \/ (y2 - y1);\n\n\n Global::debug(3) << \"background leftx \" << leftx << endl;\n\n for (int localy = 0; localy < height; ++localy ){\n\t\/\/int width = bmp.getWidth()*z;\n const double range = (double)localy \/ (double)height;\n\tconst double scale = interpolate(top, bot, range) - top;\n\t\/\/const double newHeight = height*((yscalestart+(yoffset*yscaledelta))\/100);\n\t\/\/const double yscale = (newHeight\/height);\n\tmovex = (int)(leftx + (leftx - xoffset) * scale);\n\tbmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);\n\t\/\/z += z_add;\n\t\/\/Global::debug(1) << \"Height: \" << height << \" | yscalestart: \" << yscalestart << \" | yscaledelta: \" << yscaledelta << \" | yoffset: \" << yoffset << \" | New Height: \" << newHeight << \" | yscale: \" << yscale << endl;\t\n }\n}\n\n\/\/ mugen background\nMugenBackground::MugenBackground( const unsigned long int &ticker ):\ntype(Normal),\ngroupNumber(-1),\nimageNumber(-1),\nactionno(-1),\nid(0),\nlayerno(0),\nstartx(0),\nstarty(0),\ndeltax(1),\ndeltay(1),\ntrans(None),\nalphalow(0),\nalphahigh(0),\nmask(false),\ntilex(0),\ntiley(0),\ntilespacingx(0),\ntilespacingy(0),\nwindowdeltax(0),\nwindowdeltay(0),\nxscaletop(0),\nxscalebot(0),\nyscalestart(100),\nyscaledelta(100),\npositionlink(false),\nvelocityx(0),\nvelocityy(0),\nsinx_amp(0),\nsinx_period(0),\nsinx_offset(0),\nsinx_angle(0),\nsiny_amp(0),\nsiny_period(0),\nsiny_offset(0),\nsiny_angle(0),\nxoffset(0),\nyoffset(0),\nmovex(0),\nmovey(0),\nvelx(0),\nvely(0),\nstageTicker( ticker ),\nx(0),\ny(0),\nvisible(true),\nenabled(true),\ncontroller_offsetx(0),\ncontroller_offsety(0),\nsprite(0),\nspriteBmp(0),\naction(0),\nlinked(0),\nrunLink(false){\n}\nMugenBackground::MugenBackground( const MugenBackground © ):\nstageTicker( copy.stageTicker ){\n}\nMugenBackground::~MugenBackground(){\n \/\/ Kill the bmp\n if( spriteBmp )delete spriteBmp;\n}\nMugenBackground & MugenBackground::operator=( const MugenBackground © ){\n \n return *this;\n}\n \nvoid MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){\n if (enabled){\n\tmovex = movey = 0;\n\tmovex += x * deltax;\n\tmovey += y * deltay;\n\tvelx += velocityx;\n\tvely += velocityy;\n\t\/* how much should sin_angle be incremented by each frame?\n\t* I think the total angle should be (ticks % sin_period) * 2pi \/ sin_period\n\t* M (decimal) is the magnitude in pixels (amp)\n\t* P (decimal) is the period in game ticks (period) \n\t* O (decimal) is the time offset in game ticks (offset)\n\t* From updates.txt: M * sine ((ticks+O)\/P * 2 * Pi)\n\t* sinx_amp * sin((stageTicker+sinx_offset)\/sinx_period * 2 * pi)) ? useless it seems\n\t*\/\n\t\/\/sin_angle += 0.00005;\n\tsinx_angle += 0.00005;\n\tsiny_angle += 0.00005;\n\t\n\tif( type == Anim ) action->logic();\n\t\n\tthis->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));\n\tthis->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));\n }\n}\n \nvoid MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){\n if (visible){\n\tswitch( type ){\n\t case Normal:{\n\t\t\/\/ Normal is a sprite\n\t\t\/\/ Tile it\n\t\tconst int addw = spriteBmp->getWidth() + tilespacingx;\n\t\tconst int addh = spriteBmp->getHeight() + tilespacingy;\n\t\tTile tilev = getTileData(y, totalHeight, addh, tiley);\n\t\tfor (int v = 0; v < tilev.total; ++v){\n\t\t Tile tileh = getTileData(x, totalLength, addw, tilex);\n\t\t for (int h = 0; h < tileh.total; ++h){\n\t\t\tdraw( tileh.start, tilev.start, *work);\n\t\t\ttileh.start+=addw;\n\t\t }\n\t\t tilev.start+=addh;\n\t\t}\n\t\tbreak;\n\t }\n\t case Parallax:{\n\t\t\/\/ This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth\n\t\tdoParallax( *spriteBmp, *work, x, y, xoffset+((totalLength)\/2), xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);\n\t\tbreak;\n\t }\n\t case Anim:{\n\t\t\/\/ there is no sprite use our action!\n\t\t\/\/ Tiling action\n\t\tconst int addw = tilespacingx;\n\t\tconst int addh = tilespacingy;\n\t\tTile tilev = getTileData(y, totalHeight, addh, tiley);\n\t\tfor (int v = 0; v < tilev.total; ++v){\n\t\t Tile tileh = getTileData(x, totalLength, addw, tilex);\n\t\t for (int h = 0; h < tileh.total; ++h){\n\t\t\taction->render( tileh.start, tilev.start, *work);\n\t\t\ttileh.start+=addw;\n\t\t }\n\t\t tilev.start+=addh;\n\t\t}\n\t\tbreak;\n\t }\n\t case Dummy:\n\t\t\/\/ Do nothing\n\t default:\n\t\tbreak;\n\t}\n }\n}\n\nvoid MugenBackground::preload( const int xaxis, const int yaxis ){\n \/\/ Do positionlink crap\n if (positionlink && !runLink){\n\tif (linked){\n\t linked->setPositionLink(this);\n\t}\n\trunLink = true;\n }\n \n if (sprite){\n\t\/\/ Lets load our sprite\n\tGlobal::debug(1) << \"Name: \" << name << \" | Mask: \" << mask << endl;\n\tspriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength, mask));\n#if 0\n\tif (!mask){\n\t \/\/ Restore color in case\n\t int colors = 256;\n\t int maskR = (int)sprite->pcx[sprite->newlength - colors*3 + 0];\n\t int maskG = (int)sprite->pcx[sprite->newlength - colors*3 + 1];\n\t int maskB = (int)sprite->pcx[sprite->newlength - colors*3 + 2];\n\t int mask = Bitmap::makeColor(maskR, maskG, maskB);\n\t for( int i = 0; i < spriteBmp->getHeight(); ++i ){\n for( int j = 0; j < spriteBmp->getWidth(); ++j ){\n \/* use getPixel\/putPixel? *\/\n int pix = spriteBmp->getPixel(j,i);\n if (pix == Bitmap::MaskColor){\n spriteBmp->putPixel(j,i, mask);\n }\n }\n }\n\t}\n#endif\n\n\t\/\/ Set our initial offsets\n\txoffset = (xaxis - sprite->x) + startx;\n\tyoffset = (yaxis - sprite->y) + starty; \n\tvelx = vely = 0;\n\tGlobal::debug(1) << \"Using sprite. Name: \" << name << \" | X: \" << sprite->x << \" | Y: \" << sprite->y << endl;\n } else {\n\t\/\/ Set our initial offsets\n\txoffset = (xaxis) + startx;\n\tyoffset = (yaxis) + starty;\n\tvelx = vely = 0;\n }\n}\n\nvoid MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){\n \/\/ This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha\n switch( trans ){\n\tcase Addalpha:{\n\t \/\/ Need to figure out blend correctly addalpha is given to two locations low and high ?\n\t Bitmap::transBlender( 255, 255, 255, alphalow );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Add:{\n\t \/\/ this additive 100% I assume... not totally sure\n\t Bitmap::addBlender( 255, 255, 255, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Add1:{\n\t \/\/ 50%\n\t Bitmap::addBlender( 128, 128, 128, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Sub:{\n\t \/\/ Shadow effect\n\t Bitmap::differenceBlender( 128, 128, 128, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase None:\n\tdefault:{\n\t if( mask )spriteBmp->draw( ourx,oury, work );\n\t else spriteBmp->Blit( ourx, oury, work );\n\t break;\n\t}\n }\n}\n\n\n \/\/ Lets do our positionlink stuff\nvoid MugenBackground::setPositionLink(MugenBackground *bg){\n if (positionlink){\n\tif (linked){\n\t linked->setPositionLink(bg);\n\t return;\n\t}\n }\n bg->startx += startx;\n bg->starty += starty;\n bg->deltax = deltax;\n bg->deltay = deltay;\n bg->sinx_amp = sinx_amp;\n bg->sinx_offset = sinx_offset;\n bg->sinx_period = sinx_period;\n bg->siny_amp = siny_amp;\n bg->siny_offset = siny_offset;\n bg->siny_period = siny_period;\n bg->velocityx = velocityx;\n bg->velocityy = velocityy;\n \n \/\/Global::debug(1) << \"Positionlinked bg: \" << bg->name << \" set to x: \" << bg->startx << \" y: \" << bg->starty << endl;\n}\n\n\n<commit_msg>Corrected possible memory leak, removed old code<commit_after>#include \"mugen_background.h\"\n\n#include <math.h>\n#include <ostream>\n#include <cstring>\n#include <string>\n#include <algorithm>\n#include \"globals.h\"\n#include \"mugen_sprite.h\"\n#include \"util\/bitmap.h\"\n\n\/\/static double pi = 3.14159265;\n\nusing namespace std;\n\nstatic double interpolate(double f1, double f2, double p){\n return (f1 * (1.0 - p)) + (f2 * p);\n}\n\nstruct Tile {\n int start;\n int total;\n};\n\nstatic Tile getTileData( int location, int length, int spacing, int total ){\n Tile tile;\n if (total == 0){\n\ttile.start = location;\n\ttile.total = 1;\n\treturn tile;\n } else if (total > 1){\n\ttile.start = location;\n\ttile.total = total;\n\treturn tile;\n } else if (total == 1){\n\t\/\/ Infinite tiling.. just tile on the board\n\tif (location < 0){\n\t \/\/ Less than the board itself lets get location up to that point\n\t while (location < 0){\n\t\tlocation+=spacing;\n\t }\n\t \/\/ Now backup 1 so we get the wrap effect \n\t location-=spacing;\n\t} else{\n\t \/\/ Either Larger than the board or inside seek back to beginning\n\t while (location > 0){\n\t\tlocation-=spacing;\n\t }\n\t}\n\t\/\/ Now figure out how many we need to do\n\tint temp = location;\n\t\/\/ Reuse total\n\ttotal = 0;\n\twhile (temp < length){\n\t total++;\n\t temp+=spacing;\n\t}\n\t\/\/ Blammo\n\ttile.start = location;\n\ttile.total = total;\n\treturn tile;\n }\n tile.start = 0;\n tile.total = 0;\n return tile;\n}\n\nstatic void doParallax(Bitmap &bmp, Bitmap &work, int leftx, int lefty, int xoffset, double top, double bot, int yscalestart, double yscaledelta, double yoffset, bool mask){\n const int height = bmp.getHeight();\n const int w = bmp.getWidth();\n int movex = 0;\n \/\/double z = 1.0 \/ z1;\n \/\/const double z_add = ((1.0 \/ z2) - z) \/ (y2 - y1);\n\n\n Global::debug(3) << \"background leftx \" << leftx << endl;\n\n for (int localy = 0; localy < height; ++localy ){\n\t\/\/int width = bmp.getWidth()*z;\n const double range = (double)localy \/ (double)height;\n\tconst double scale = interpolate(top, bot, range) - top;\n\t\/\/const double newHeight = height*((yscalestart+(yoffset*yscaledelta))\/100);\n\t\/\/const double yscale = (newHeight\/height);\n\tmovex = (int)(leftx + (leftx - xoffset) * scale);\n\tbmp.Stretch(work, 0, localy, w, 1,movex, lefty+localy, w,1);\n\t\/\/z += z_add;\n\t\/\/Global::debug(1) << \"Height: \" << height << \" | yscalestart: \" << yscalestart << \" | yscaledelta: \" << yscaledelta << \" | yoffset: \" << yoffset << \" | New Height: \" << newHeight << \" | yscale: \" << yscale << endl;\t\n }\n}\n\n\/\/ mugen background\nMugenBackground::MugenBackground( const unsigned long int &ticker ):\ntype(Normal),\ngroupNumber(-1),\nimageNumber(-1),\nactionno(-1),\nid(0),\nlayerno(0),\nstartx(0),\nstarty(0),\ndeltax(1),\ndeltay(1),\ntrans(None),\nalphalow(0),\nalphahigh(0),\nmask(false),\ntilex(0),\ntiley(0),\ntilespacingx(0),\ntilespacingy(0),\nwindowdeltax(0),\nwindowdeltay(0),\nxscaletop(0),\nxscalebot(0),\nyscalestart(100),\nyscaledelta(100),\npositionlink(false),\nvelocityx(0),\nvelocityy(0),\nsinx_amp(0),\nsinx_period(0),\nsinx_offset(0),\nsinx_angle(0),\nsiny_amp(0),\nsiny_period(0),\nsiny_offset(0),\nsiny_angle(0),\nxoffset(0),\nyoffset(0),\nmovex(0),\nmovey(0),\nvelx(0),\nvely(0),\nstageTicker( ticker ),\nx(0),\ny(0),\nvisible(true),\nenabled(true),\ncontroller_offsetx(0),\ncontroller_offsety(0),\nsprite(0),\nspriteBmp(0),\naction(0),\nlinked(0),\nrunLink(false){\n}\nMugenBackground::MugenBackground( const MugenBackground © ):\nstageTicker( copy.stageTicker ){\n}\nMugenBackground::~MugenBackground(){\n \/\/ Kill the bmp\n if( spriteBmp )delete spriteBmp;\n}\nMugenBackground & MugenBackground::operator=( const MugenBackground © ){\n \n return *this;\n}\n \nvoid MugenBackground::logic( const double x, const double y, const double placementx, const double placementy ){\n if (enabled){\n\tmovex = movey = 0;\n\tmovex += x * deltax;\n\tmovey += y * deltay;\n\tvelx += velocityx;\n\tvely += velocityy;\n\t\/* how much should sin_angle be incremented by each frame?\n\t* I think the total angle should be (ticks % sin_period) * 2pi \/ sin_period\n\t* M (decimal) is the magnitude in pixels (amp)\n\t* P (decimal) is the period in game ticks (period) \n\t* O (decimal) is the time offset in game ticks (offset)\n\t* From updates.txt: M * sine ((ticks+O)\/P * 2 * Pi)\n\t* sinx_amp * sin((stageTicker+sinx_offset)\/sinx_period * 2 * pi)) ? useless it seems\n\t*\/\n\t\/\/sin_angle += 0.00005;\n\tsinx_angle += 0.00005;\n\tsiny_angle += 0.00005;\n\t\n\tif( type == Anim ) action->logic();\n\t\n\tthis->x = (int)(placementx + xoffset + movex + velx + controller_offsetx + sinx_amp * sin(sinx_angle*sinx_period + sinx_offset));\n\tthis->y = (int)(placementy + yoffset + movey + vely + controller_offsety + siny_amp * sin(siny_angle*siny_period + siny_offset));\n }\n}\n \nvoid MugenBackground::render( const int totalLength, const int totalHeight, Bitmap *work ){\n if (visible){\n\tswitch( type ){\n\t case Normal:{\n\t\t\/\/ Normal is a sprite\n\t\t\/\/ Tile it\n\t\tconst int addw = spriteBmp->getWidth() + tilespacingx;\n\t\tconst int addh = spriteBmp->getHeight() + tilespacingy;\n\t\tTile tilev = getTileData(y, totalHeight, addh, tiley);\n\t\tfor (int v = 0; v < tilev.total; ++v){\n\t\t Tile tileh = getTileData(x, totalLength, addw, tilex);\n\t\t for (int h = 0; h < tileh.total; ++h){\n\t\t\tdraw( tileh.start, tilev.start, *work);\n\t\t\ttileh.start+=addw;\n\t\t }\n\t\t tilev.start+=addh;\n\t\t}\n\t\tbreak;\n\t }\n\t case Parallax:{\n\t\t\/\/ This is also a sprite but we must parallax it across the top and bottom to give the illusion of depth\n\t\tdoParallax( *spriteBmp, *work, x, y, xoffset+((totalLength)\/2), xscaletop, xscalebot, yscalestart, yscaledelta, (movey-deltay), mask);\n\t\tbreak;\n\t }\n\t case Anim:{\n\t\t\/\/ there is no sprite use our action!\n\t\t\/\/ Tiling action\n\t\tconst int addw = tilespacingx;\n\t\tconst int addh = tilespacingy;\n\t\tTile tilev = getTileData(y, totalHeight, addh, tiley);\n\t\tfor (int v = 0; v < tilev.total; ++v){\n\t\t Tile tileh = getTileData(x, totalLength, addw, tilex);\n\t\t for (int h = 0; h < tileh.total; ++h){\n\t\t\taction->render( tileh.start, tilev.start, *work);\n\t\t\ttileh.start+=addw;\n\t\t }\n\t\t tilev.start+=addh;\n\t\t}\n\t\tbreak;\n\t }\n\t case Dummy:\n\t\t\/\/ Do nothing\n\t default:\n\t\tbreak;\n\t}\n }\n}\n\nvoid MugenBackground::preload( const int xaxis, const int yaxis ){\n \/\/ Do positionlink crap\n if (positionlink && !runLink){\n\tif (linked){\n\t linked->setPositionLink(this);\n\t}\n\trunLink = true;\n }\n \n if (sprite){\n\t\/\/ Lets load our sprite\n\tGlobal::debug(1) << \"Name: \" << name << \" | Mask: \" << mask << endl;\n\tif( spriteBmp == 0 ){\n\t spriteBmp = new Bitmap(Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength, mask));\n\t}\n\t\/\/ Set our initial offsets\n\txoffset = (xaxis - sprite->x) + startx;\n\tyoffset = (yaxis - sprite->y) + starty; \n\tvelx = vely = 0;\n\tGlobal::debug(1) << \"Using sprite. Name: \" << name << \" | X: \" << sprite->x << \" | Y: \" << sprite->y << endl;\n } else {\n\t\/\/ Set our initial offsets\n\txoffset = (xaxis) + startx;\n\tyoffset = (yaxis) + starty;\n\tvelx = vely = 0;\n }\n}\n\nvoid MugenBackground::draw( const int ourx, const int oury, Bitmap &work ){\n \/\/ This needs to be a switch trans = None, Add, Add1, Sub1, Addalpha\n switch( trans ){\n\tcase Addalpha:{\n\t \/\/ Need to figure out blend correctly addalpha is given to two locations low and high ?\n\t Bitmap::transBlender( 255, 255, 255, alphalow );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Add:{\n\t \/\/ this additive 100% I assume... not totally sure\n\t Bitmap::addBlender( 255, 255, 255, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Add1:{\n\t \/\/ 50%\n\t Bitmap::addBlender( 128, 128, 128, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase Sub:{\n\t \/\/ Shadow effect\n\t Bitmap::differenceBlender( 128, 128, 128, 255 );\n\t spriteBmp->drawTrans( ourx, oury, work);\n\t break;\n\t}\n\tcase None:\n\tdefault:{\n\t if( mask )spriteBmp->draw( ourx,oury, work );\n\t else spriteBmp->Blit( ourx, oury, work );\n\t break;\n\t}\n }\n}\n\n\n \/\/ Lets do our positionlink stuff\nvoid MugenBackground::setPositionLink(MugenBackground *bg){\n if (positionlink){\n\tif (linked){\n\t linked->setPositionLink(bg);\n\t return;\n\t}\n }\n bg->startx += startx;\n bg->starty += starty;\n bg->deltax = deltax;\n bg->deltay = deltay;\n bg->sinx_amp = sinx_amp;\n bg->sinx_offset = sinx_offset;\n bg->sinx_period = sinx_period;\n bg->siny_amp = siny_amp;\n bg->siny_offset = siny_offset;\n bg->siny_period = siny_period;\n bg->velocityx = velocityx;\n bg->velocityy = velocityy;\n \n \/\/Global::debug(1) << \"Positionlinked bg: \" << bg->name << \" set to x: \" << bg->startx << \" y: \" << bg->starty << endl;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"FarPluginBase.hpp\"\n#include \"array.hpp\"\n\n#include \"FarDialog.hpp\"\n#include \"FarMessage.hpp\"\n#include \"FarMenu.hpp\"\n<commit_msg>cleanup<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*-\n * Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgAnimation\/Animation>\n\nusing namespace osgAnimation;\n\nAnimation::Animation(const osgAnimation::Animation& anim, const osg::CopyOp& copyop): osg::Object(anim, copyop),\n _duration(anim._duration),\n _originalDuration(anim._originalDuration),\n _weight(anim._weight),\n _startTime(anim._startTime),\n _playmode(anim._playmode)\n{\n const ChannelList& cl = anim.getChannels();\n for (ChannelList::const_iterator it = cl.begin(); it != cl.end(); ++it)\n {\n addChannel(it->get()->clone());\n }\n}\n\n\nvoid Animation::addChannel(Channel* pChannel)\n{\n _channels.push_back(pChannel);\n if (_duration == _originalDuration)\n computeDuration();\n else\n _originalDuration = computeDurationFromChannels();\n}\n\ndouble Animation::computeDurationFromChannels() const\n{\n double tmin = 1e5;\n double tmax = -1e5;\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); chan++ )\n {\n float min = (*chan)->getStartTime();\n if (min < tmin)\n tmin = min;\n float max = (*chan)->getEndTime();\n if (max > tmax)\n tmax = max;\n }\n return tmax-tmin;\n}\n\nvoid Animation::computeDuration()\n{\n _duration = computeDurationFromChannels();\n _originalDuration = _duration;\n}\n\nosgAnimation::ChannelList& Animation::getChannels()\n{\n return _channels;\n}\n\nconst osgAnimation::ChannelList& Animation::getChannels() const\n{\n return _channels;\n}\n\n\nvoid Animation::setDuration(double duration)\n{\n _originalDuration = computeDurationFromChannels();\n _duration = duration;\n}\n\ndouble Animation::getDuration() const\n{\n return _duration;\n}\n\nfloat Animation::getWeight () const\n{\n return _weight;\n}\n\nvoid Animation::setWeight (float weight)\n{\n _weight = weight;\n}\n\nbool Animation::update (double time, int priority)\n{\n if (!_duration) \/\/ if not initialized then do it\n computeDuration();\n\n double ratio = _originalDuration \/ _duration;\n\n double t = (time - _startTime) * ratio;\n switch (_playmode)\n {\n case ONCE:\n if (t > _originalDuration)\n return false;\n break;\n case STAY:\n if (t > _originalDuration)\n t = _originalDuration;\n break;\n case LOOP:\n if (!_originalDuration)\n t = _startTime;\n else if (t > _originalDuration)\n t = fmod(t, _originalDuration);\n \/\/ std::cout << \"t \" << t << \" duration \" << _duration << std::endl;\n break;\n case PPONG:\n if (!_originalDuration)\n t = _startTime;\n else\n {\n int tt = (int) (t \/ _originalDuration);\n t = fmod(t, _originalDuration);\n if (tt%2)\n t = _originalDuration - t;\n }\n break;\n }\n\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); ++chan)\n {\n (*chan)->update(t, _weight, priority);\n }\n return true;\n}\n\nvoid Animation::resetTargets()\n{\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); ++chan)\n (*chan)->reset();\n}\n<commit_msg>From Konstantin Matveyev, \"Last update in the osgAnimation::Animation ONCE mode bug fix\"<commit_after>\/* -*-c++-*-\n * Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgAnimation\/Animation>\n\nusing namespace osgAnimation;\n\nAnimation::Animation(const osgAnimation::Animation& anim, const osg::CopyOp& copyop): osg::Object(anim, copyop),\n _duration(anim._duration),\n _originalDuration(anim._originalDuration),\n _weight(anim._weight),\n _startTime(anim._startTime),\n _playmode(anim._playmode)\n{\n const ChannelList& cl = anim.getChannels();\n for (ChannelList::const_iterator it = cl.begin(); it != cl.end(); ++it)\n {\n addChannel(it->get()->clone());\n }\n}\n\n\nvoid Animation::addChannel(Channel* pChannel)\n{\n _channels.push_back(pChannel);\n if (_duration == _originalDuration)\n computeDuration();\n else\n _originalDuration = computeDurationFromChannels();\n}\n\ndouble Animation::computeDurationFromChannels() const\n{\n double tmin = 1e5;\n double tmax = -1e5;\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); chan++ )\n {\n float min = (*chan)->getStartTime();\n if (min < tmin)\n tmin = min;\n float max = (*chan)->getEndTime();\n if (max > tmax)\n tmax = max;\n }\n return tmax-tmin;\n}\n\nvoid Animation::computeDuration()\n{\n _duration = computeDurationFromChannels();\n _originalDuration = _duration;\n}\n\nosgAnimation::ChannelList& Animation::getChannels()\n{\n return _channels;\n}\n\nconst osgAnimation::ChannelList& Animation::getChannels() const\n{\n return _channels;\n}\n\n\nvoid Animation::setDuration(double duration)\n{\n _originalDuration = computeDurationFromChannels();\n _duration = duration;\n}\n\ndouble Animation::getDuration() const\n{\n return _duration;\n}\n\nfloat Animation::getWeight () const\n{\n return _weight;\n}\n\nvoid Animation::setWeight (float weight)\n{\n _weight = weight;\n}\n\nbool Animation::update (double time, int priority)\n{\n if (!_duration) \/\/ if not initialized then do it\n computeDuration();\n\n double ratio = _originalDuration \/ _duration;\n\n double t = (time - _startTime) * ratio;\n switch (_playmode)\n {\n case ONCE:\n if (t > _originalDuration)\n {\n for (ChannelList::const_iterator chan = _channels.begin();\n chan != _channels.end(); ++chan)\n (*chan)->update(_originalDuration, _weight, priority);\n\n return false;\n }\n break;\n case STAY:\n if (t > _originalDuration)\n t = _originalDuration;\n break;\n case LOOP:\n if (!_originalDuration)\n t = _startTime;\n else if (t > _originalDuration)\n t = fmod(t, _originalDuration);\n \/\/ std::cout << \"t \" << t << \" duration \" << _duration << std::endl;\n break;\n case PPONG:\n if (!_originalDuration)\n t = _startTime;\n else\n {\n int tt = (int) (t \/ _originalDuration);\n t = fmod(t, _originalDuration);\n if (tt%2)\n t = _originalDuration - t;\n }\n break;\n }\n\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); ++chan)\n {\n (*chan)->update(t, _weight, priority);\n }\n return true;\n}\n\nvoid Animation::resetTargets()\n{\n ChannelList::const_iterator chan;\n for( chan=_channels.begin(); chan!=_channels.end(); ++chan)\n (*chan)->reset();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FltFile.h\"\n#include \"Registry.h\"\n#include \"Record.h\"\n#include \"RecordVisitor.h\"\n#include \"ExternalRecord.h\"\n#include \"flt2osg.h\" \/\/ ConvertFromFLT\n#include \"Input.h\"\n\n#include <osg\/Node>\n#include <osg\/NodeVisitor>\n#include <osg\/Notify>\n\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n\n#include <osgSim\/GeographicLocation>\n\n#include <string>\n\n\nusing namespace flt;\n\n\nFltFile::FltFile(\n ColorPool* pColorPool,\n TexturePool* pTexturePool,\n MaterialPool* pMaterialPool,\n LtPtAppearancePool* pLtPtAppearancePool,\n LtPtAnimationPool* pLtPtAnimationPool,\n osgDB::ReaderWriter::Options* options)\n{\n _useTextureAlphaForTransparancyBinning = true;\n _doUnitsConversion = true;\n _desiredUnits = ConvertToMeters;\n\n if (pColorPool)\n {\n \/\/ use external color palette, ignore internal\n _useInternalColorPalette = false;\n setColorPool( pColorPool );\n }\n else\n {\n \/\/ use internal color palette\n _useInternalColorPalette = true;\n setColorPool( new ColorPool );\n }\n\n if (pTexturePool)\n {\n \/\/ use external texture palette, ignore internal\n _useInternalTexturePalette = false;\n setTexturePool( pTexturePool );\n }\n else\n {\n \/\/ use internal texture palette\n _useInternalTexturePalette = true;\n setTexturePool( new TexturePool );\n }\n\n if (pMaterialPool)\n {\n \/\/ use external material palette, ignore internal\n _useInternalMaterialPalette = false;\n setMaterialPool( pMaterialPool );\n }\n else\n {\n \/\/ use internal material palette\n _useInternalMaterialPalette = true;\n setMaterialPool( new MaterialPool );\n }\n\n if (pLtPtAppearancePool && pLtPtAnimationPool) \/\/ Can only be non-NULL if parent is 15.8.\n {\n \/\/ use external light point appearance and animation palettes, ignore internal\n _useInternalLtPtPalettes = false;\n setLtPtAppearancePool( pLtPtAppearancePool );\n setLtPtAnimationPool( pLtPtAnimationPool );\n }\n else\n {\n \/\/ If they aren't both set, then they must both be NULL.\n assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );\n \/\/ use internal light point palettes\n _useInternalLtPtPalettes = true;\n setLtPtAppearancePool( new LtPtAppearancePool );\n setLtPtAnimationPool( new LtPtAnimationPool );\n }\n\n \/\/ no support for external light palettes\n setLightPool( new LightPool );\n\n \/\/ instances are always internally defined \n setInstancePool( new InstancePool );\n \n _options = options;\n}\n\n\nosg::Object* FltFile::readObject(const std::string& fileName)\n{\n return readNode(fileName);\n}\n\n\nosg::Node* FltFile::readNode(const std::string& fileName)\n{\n _directory = osgDB::getFilePath(fileName);\n\n if (readModel(fileName))\n {\n \/\/ Convert record tree to osg scene graph\n osg::Node* model = convert();\n \n if (model)\n {\n \/\/ Store model origin in returned Node userData.\n osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;\n double lat, lon;\n getOrigin( lat, lon );\n loc->set( lat, lon );\n model->setUserData( loc.get() );\n \n osg::notify(osg::INFO)<<\"FltFile::readNode(\"<<fileName<<\") lat=\"<<lat<<\" lon=\"<<lon<<std::endl;\n \n return model;\n }\n }\n\n return NULL;\n}\n\n\nosg::Group* FltFile::convert()\n{\n ConvertFromFLT visit;\n visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());\n visit.setDoUnitsConversion(getDoUnitsConversion());\n return visit.convert(getHeaderRecord());\n}\n\n\n\/\/ Read flight model (include externals)\nbool FltFile::readModel(const std::string& fileName)\n{\n if (readFile(fileName))\n {\n readExternals();\n return getHeaderRecord() ? true : false;\n }\n return false;\n}\n\n\nbool FltFile::readFile(const std::string& fileName)\n{\n\n \/\/ havn't found file, look in OSGFILEPATH\n std::string foundFileName = osgDB::findDataFile(fileName, _options.get());\n if (foundFileName.empty()) return false;\n\n FileInput fin;\n if (!fin.open(foundFileName)) return false;\n\n Record* pRec = fin.readCreateRecord(this);\n if (pRec == NULL)\n {\n osg::notify(osg::WARN) << \"File not found \" << fileName << std::endl;\n return false;\n }\n\n _headerRecord = (HeaderRecord*)pRec;\n if (pRec->isPrimaryNode()) \/\/ Header\n pRec->readLocalData(fin);\/\/ Read rest of file\n\n fin.close();\n\n return true;\n}\n\n\n#define REGISTER_FLT 1\n\n\/\/ This class was originally scoped within FltFile::readExternals() function.\n\/\/ Irix 7.3 compilers hork on this.\n\n class ReadExternal : public RecordVisitor\n {\n public:\n ReadExternal(FltFile* fltFile)\n {\n _pFltFile = fltFile;\n setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);\n }\n\n virtual void apply(ExternalRecord& rec)\n {\n SExternalReference* pSExternal = (SExternalReference*)rec.getData();\n\n if (pSExternal)\n {\n FltFile* pExternalFltFile = NULL;\n ColorPool* pColorPool = NULL;\n TexturePool* pTexturePool = NULL;\n MaterialPool* pMaterialPool = NULL;\n LtPtAppearancePool* pLtPtAppearancePool = NULL;\n LtPtAnimationPool* pLtPtAnimationPool = NULL;\n std::string filename( rec.getFilename() );\n\n osg::notify(osg::INFO) << \"External=\" << filename << std::endl;\n\n if (rec.getFlightVersion() > 13)\n {\n if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))\n pColorPool = _pFltFile->getColorPool();\n\n if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))\n pTexturePool = _pFltFile->getTexturePool();\n\n if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))\n pMaterialPool = _pFltFile->getMaterialPool();\n\n if (rec.getFlightVersion() >= 1580)\n {\n if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))\n {\n pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();\n pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();\n }\n }\n }\n\n\n #if REGISTER_FLT\n bool registerFLT = true;\n #else\n bool registerFLT = false;\n #endif\n \n pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;\n if (pExternalFltFile == NULL)\n {\n osg::ref_ptr<osgDB::ReaderWriter::Options> options = \n _pFltFile->getOptions() ? _pFltFile->getOptions() : \n new osgDB::ReaderWriter::Options;\n\n \/\/Path for Nested external references\n osgDB::FilePathList& fpl = options->getDatabasePathList();\n const std::string& filePath = osgDB::getFilePath(filename);\n std::string pushAndPopPath;\n \/\/If absolute path\n if( (filePath.length()>0 && filePath.find_first_of(\"\/\\\\\")==0) ||\n (filePath.length()>2 && filePath.substr(1,1)==\":\" && filePath.find_first_of(\"\/\\\\\")==2) )\n {\n pushAndPopPath = filePath;\n }\n else\n {\n pushAndPopPath = (fpl.empty() | fpl.back().empty() ? \".\" : fpl.back()) + \"\/\" + filePath;\n }\n\n char optionsString[256];\n sprintf(optionsString,\"FLT_VER %d\",rec.getFlightVersion());\n options->setOptionString(optionsString);\n\n \/\/osg::notify(osg::NOTICE)<<\"Create local path\"<<pushAndPopPath<<std::endl;\n\n fpl.push_back(pushAndPopPath);\n \n\n pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,\n pLtPtAppearancePool, pLtPtAnimationPool, options.get() );\n\n if (registerFLT)\n {\n Registry::instance()->addFltFile(filename, pExternalFltFile);\n }\n\n pExternalFltFile->readModel(filename);\n }\n\n rec.setExternal(pExternalFltFile);\n }\n }\n\n public:\n\n FltFile* _pFltFile;\n };\n\nvoid FltFile::readExternals()\n{\n ReadExternal visitor(this);\n _headerRecord->accept(visitor);\n}\n\n\nint FltFile::getFlightVersion() const\n{\n if (_headerRecord.get())\n {\n SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();\n if (pSHeader)\n return pSHeader->diFormatRevLev;\n }\n return 0;\n}\n\n\nvoid FltFile::getOrigin( double& latitude, double& longitude ) const\n{\n if (_headerRecord.get())\n {\n SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();\n if (pSHeader)\n {\n latitude = pSHeader->Origin.x();\n longitude = pSHeader->Origin.y();\n }\n }\n}\n\n\nstd::string FltFile::getDesiredUnitsString() const\n{\n switch (_desiredUnits)\n {\n case ConvertToMeters:\n return \"ConvertToMeters\";\n break;\n case ConvertToKilometers:\n return \"ConvertToKilometers\";\n break;\n case ConvertToFeet:\n return \"ConvertToFeet\";\n break;\n case ConvertToInches:\n return \"ConvertToInches\";\n break;\n case ConvertToNauticalMiles:\n return \"ConvertToNauticalMiles\";\n break;\n default:\n return \"Invalid\";\n break;\n }\n}\n\n\n<commit_msg>From Alberto Farre, \"Missed a FilepathList pop_back line from my last submission.<commit_after>#include \"FltFile.h\"\n#include \"Registry.h\"\n#include \"Record.h\"\n#include \"RecordVisitor.h\"\n#include \"ExternalRecord.h\"\n#include \"flt2osg.h\" \/\/ ConvertFromFLT\n#include \"Input.h\"\n\n#include <osg\/Node>\n#include <osg\/NodeVisitor>\n#include <osg\/Notify>\n\n#include <osgDB\/FileUtils>\n#include <osgDB\/FileNameUtils>\n\n#include <osgSim\/GeographicLocation>\n\n#include <string>\n\n\nusing namespace flt;\n\n\nFltFile::FltFile(\n ColorPool* pColorPool,\n TexturePool* pTexturePool,\n MaterialPool* pMaterialPool,\n LtPtAppearancePool* pLtPtAppearancePool,\n LtPtAnimationPool* pLtPtAnimationPool,\n osgDB::ReaderWriter::Options* options)\n{\n _useTextureAlphaForTransparancyBinning = true;\n _doUnitsConversion = true;\n _desiredUnits = ConvertToMeters;\n\n if (pColorPool)\n {\n \/\/ use external color palette, ignore internal\n _useInternalColorPalette = false;\n setColorPool( pColorPool );\n }\n else\n {\n \/\/ use internal color palette\n _useInternalColorPalette = true;\n setColorPool( new ColorPool );\n }\n\n if (pTexturePool)\n {\n \/\/ use external texture palette, ignore internal\n _useInternalTexturePalette = false;\n setTexturePool( pTexturePool );\n }\n else\n {\n \/\/ use internal texture palette\n _useInternalTexturePalette = true;\n setTexturePool( new TexturePool );\n }\n\n if (pMaterialPool)\n {\n \/\/ use external material palette, ignore internal\n _useInternalMaterialPalette = false;\n setMaterialPool( pMaterialPool );\n }\n else\n {\n \/\/ use internal material palette\n _useInternalMaterialPalette = true;\n setMaterialPool( new MaterialPool );\n }\n\n if (pLtPtAppearancePool && pLtPtAnimationPool) \/\/ Can only be non-NULL if parent is 15.8.\n {\n \/\/ use external light point appearance and animation palettes, ignore internal\n _useInternalLtPtPalettes = false;\n setLtPtAppearancePool( pLtPtAppearancePool );\n setLtPtAnimationPool( pLtPtAnimationPool );\n }\n else\n {\n \/\/ If they aren't both set, then they must both be NULL.\n assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );\n \/\/ use internal light point palettes\n _useInternalLtPtPalettes = true;\n setLtPtAppearancePool( new LtPtAppearancePool );\n setLtPtAnimationPool( new LtPtAnimationPool );\n }\n\n \/\/ no support for external light palettes\n setLightPool( new LightPool );\n\n \/\/ instances are always internally defined \n setInstancePool( new InstancePool );\n \n _options = options;\n}\n\n\nosg::Object* FltFile::readObject(const std::string& fileName)\n{\n return readNode(fileName);\n}\n\n\nosg::Node* FltFile::readNode(const std::string& fileName)\n{\n _directory = osgDB::getFilePath(fileName);\n\n if (readModel(fileName))\n {\n \/\/ Convert record tree to osg scene graph\n osg::Node* model = convert();\n \n if (model)\n {\n \/\/ Store model origin in returned Node userData.\n osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;\n double lat, lon;\n getOrigin( lat, lon );\n loc->set( lat, lon );\n model->setUserData( loc.get() );\n \n osg::notify(osg::INFO)<<\"FltFile::readNode(\"<<fileName<<\") lat=\"<<lat<<\" lon=\"<<lon<<std::endl;\n \n return model;\n }\n }\n\n return NULL;\n}\n\n\nosg::Group* FltFile::convert()\n{\n ConvertFromFLT visit;\n visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());\n visit.setDoUnitsConversion(getDoUnitsConversion());\n return visit.convert(getHeaderRecord());\n}\n\n\n\/\/ Read flight model (include externals)\nbool FltFile::readModel(const std::string& fileName)\n{\n if (readFile(fileName))\n {\n readExternals();\n return getHeaderRecord() ? true : false;\n }\n return false;\n}\n\n\nbool FltFile::readFile(const std::string& fileName)\n{\n\n \/\/ havn't found file, look in OSGFILEPATH\n std::string foundFileName = osgDB::findDataFile(fileName, _options.get());\n if (foundFileName.empty()) return false;\n\n FileInput fin;\n if (!fin.open(foundFileName)) return false;\n\n Record* pRec = fin.readCreateRecord(this);\n if (pRec == NULL)\n {\n osg::notify(osg::WARN) << \"File not found \" << fileName << std::endl;\n return false;\n }\n\n _headerRecord = (HeaderRecord*)pRec;\n if (pRec->isPrimaryNode()) \/\/ Header\n pRec->readLocalData(fin);\/\/ Read rest of file\n\n fin.close();\n\n return true;\n}\n\n\n#define REGISTER_FLT 1\n\n\/\/ This class was originally scoped within FltFile::readExternals() function.\n\/\/ Irix 7.3 compilers hork on this.\n\n class ReadExternal : public RecordVisitor\n {\n public:\n ReadExternal(FltFile* fltFile)\n {\n _pFltFile = fltFile;\n setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);\n }\n\n virtual void apply(ExternalRecord& rec)\n {\n SExternalReference* pSExternal = (SExternalReference*)rec.getData();\n\n if (pSExternal)\n {\n FltFile* pExternalFltFile = NULL;\n ColorPool* pColorPool = NULL;\n TexturePool* pTexturePool = NULL;\n MaterialPool* pMaterialPool = NULL;\n LtPtAppearancePool* pLtPtAppearancePool = NULL;\n LtPtAnimationPool* pLtPtAnimationPool = NULL;\n std::string filename( rec.getFilename() );\n\n osg::notify(osg::INFO) << \"External=\" << filename << std::endl;\n\n if (rec.getFlightVersion() > 13)\n {\n if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))\n pColorPool = _pFltFile->getColorPool();\n\n if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))\n pTexturePool = _pFltFile->getTexturePool();\n\n if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))\n pMaterialPool = _pFltFile->getMaterialPool();\n\n if (rec.getFlightVersion() >= 1580)\n {\n if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))\n {\n pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();\n pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();\n }\n }\n }\n\n\n #if REGISTER_FLT\n bool registerFLT = true;\n #else\n bool registerFLT = false;\n #endif\n \n pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;\n if (pExternalFltFile == NULL)\n {\n osg::ref_ptr<osgDB::ReaderWriter::Options> options = \n _pFltFile->getOptions() ? _pFltFile->getOptions() : \n new osgDB::ReaderWriter::Options;\n\n \/\/Path for Nested external references\n osgDB::FilePathList& fpl = options->getDatabasePathList();\n const std::string& filePath = osgDB::getFilePath(filename);\n std::string pushAndPopPath;\n \/\/If absolute path\n if( (filePath.length()>0 && filePath.find_first_of(\"\/\\\\\")==0) ||\n (filePath.length()>2 && filePath.substr(1,1)==\":\" && filePath.find_first_of(\"\/\\\\\")==2) )\n {\n pushAndPopPath = filePath;\n }\n else\n {\n pushAndPopPath = (fpl.empty() | fpl.back().empty() ? \".\" : fpl.back()) + \"\/\" + filePath;\n }\n\n \/*char optionsString[256];\n sprintf(optionsString,\"FLT_VER %d\",rec.getFlightVersion());\n options->setOptionString(optionsString);*\/\n\n \/\/osg::notify(osg::NOTICE)<<\"Create local path\"<<pushAndPopPath<<std::endl;\n\n fpl.push_back(pushAndPopPath);\n \n\n pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,\n pLtPtAppearancePool, pLtPtAnimationPool, options.get() );\n\n if (registerFLT)\n {\n Registry::instance()->addFltFile(filename, pExternalFltFile);\n }\n\n pExternalFltFile->readModel(filename);\n\n fpl.pop_back();\n }\n\n rec.setExternal(pExternalFltFile);\n }\n }\n\n public:\n\n FltFile* _pFltFile;\n };\n\nvoid FltFile::readExternals()\n{\n ReadExternal visitor(this);\n _headerRecord->accept(visitor);\n}\n\n\nint FltFile::getFlightVersion() const\n{\n if (_headerRecord.get())\n {\n SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();\n if (pSHeader)\n return pSHeader->diFormatRevLev;\n }\n return 0;\n}\n\n\nvoid FltFile::getOrigin( double& latitude, double& longitude ) const\n{\n if (_headerRecord.get())\n {\n SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();\n if (pSHeader)\n {\n latitude = pSHeader->Origin.x();\n longitude = pSHeader->Origin.y();\n }\n }\n}\n\n\nstd::string FltFile::getDesiredUnitsString() const\n{\n switch (_desiredUnits)\n {\n case ConvertToMeters:\n return \"ConvertToMeters\";\n break;\n case ConvertToKilometers:\n return \"ConvertToKilometers\";\n break;\n case ConvertToFeet:\n return \"ConvertToFeet\";\n break;\n case ConvertToInches:\n return \"ConvertToInches\";\n break;\n case ConvertToNauticalMiles:\n return \"ConvertToNauticalMiles\";\n break;\n default:\n return \"Invalid\";\n break;\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\authors (impus@hotbox.ru)\r\n \\date 2.10.2011\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#define BOOST_TEST_MODULE RDOSequencesTest\r\n#include <iostream>\r\n#include <fstream>\r\n#include <list>\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n#include <boost\/bind.hpp>\r\n#include <boost\/function.hpp>\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"utils\/rdofile.h\"\r\n#include \"simulator\/runtime\/rdo_random_distribution.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\ntypedef std::list<double> Container;\r\ntypedef const tstring contstr;\r\n\r\nconst long int g_seed = 123456789; \/\/!< \r\ncontstr g_fileNormalName = _T(\"data_normal.txt\"); \/\/!< \r\ncontstr g_fileUniformName = _T(\"data_uniform.txt\"); \/\/!< \r\ncontstr g_fileExponentialName = _T(\"data_exponential.txt\"); \/\/!< \r\ncontstr g_fileTriangularName = _T(\"data_trinagular.txt\"); \/\/!< \r\nconst ruint g_count = 100000; \/\/!< \r\nconst double g_main = 10.0; \/\/!< \r\nconst double g_var = 1.0; \/\/!< \r\nconst double g_from = 1.0; \/\/!< \r\nconst double g_to = 7.0; \/\/!< \r\nconst double g_top = 5.0; \/\/!< \r\nconst ruint g_precision = 20; \/\/!< \r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Templates\r\n\/\/ --------------------------------------------------------------------------------\r\ntemplate <class T, class F, class contstr>\r\nvoid onGenerateData(F binder, contstr g_fileName)\r\n{\r\n\tif (rdo::File::exist(g_fileName.c_str()))\r\n\t\treturn;\r\n\r\n\tT sequence(g_seed);\r\n\tContainer test;\r\n\r\n\tfor (ruint i = 0; i < g_count; ++i)\r\n\t{\r\n\t\ttest.push_back(binder.operator()(&sequence));\r\n\t}\r\n\r\n\tstd::ofstream stream(g_fileName.c_str());\r\n\tstream.precision(g_precision);\r\n\tSTL_FOR_ALL(test, it)\r\n\t{\r\n\t\tstream << *it << std::endl;\r\n\t}\r\n}\r\n\r\ntemplate <class T, class F, class contstr>\r\nvoid onCheckData(F binder, contstr g_fileName)\r\n{\r\n\tstd::ifstream stream(g_fileName.c_str());\r\n\tBOOST_CHECK(stream.good());\r\n\r\n\tContainer test;\r\n\tT sequence(g_seed);\r\n\tfor (ruint i = 0; i < g_count; ++i)\r\n\t{\r\n\t\ttest.push_back(binder.operator()(&sequence));\r\n\t}\r\n\r\n\tstream.precision(g_precision);\r\n\tSTL_FOR_ALL(test, it)\r\n\t{\r\n\t\tBOOST_CHECK(stream.good());\r\n\t\ttstring str;\r\n\t\tstream >> str;\r\n\r\n\t\tdouble val;\r\n\t\tBOOST_CHECK(sscanf_s(str.c_str(), _T(\"%lf\"), &val) == 1);\r\n\t\tBOOST_CHECK(val == *it);\r\n\t\t\t\tif (val != *it)\r\n\t\t{\r\n\t\t\tstd::cout.precision(g_precision);\r\n\t\t\tstd::cout << *it << std::endl;\r\n\t\t\tstd::cout << val << std::endl;\r\n\t\t}\r\n\t}\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_SUITE(RDOSequencesTest)\r\n\/*\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Normal sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDONormalTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorNormal>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDONormalTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorNormal>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Uniform sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOUniformTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorUniform>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOUniformTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorUniform>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n*\/\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Exponential sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorExponential>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorExponential>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\/*\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Triangular sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorTriangular>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorTriangular>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n*\/\r\nBOOST_AUTO_TEST_SUITE_END()<commit_msg> - доведен до финишного состояния автотест законов на точное соостветствие эталонным данным<commit_after>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\authors (impus@hotbox.ru)\r\n \\date 2.10.2011\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#define BOOST_TEST_MODULE RDOSequencesTest\r\n#include <iostream>\r\n#include <fstream>\r\n#include <list>\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n#include <boost\/bind.hpp>\r\n#include <boost\/function.hpp>\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"utils\/rdofile.h\"\r\n#include \"simulator\/runtime\/rdo_random_distribution.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\ntypedef std::list<double> Container;\r\ntypedef const tstring contstr;\r\n\r\nconst long int g_seed = 123456789; \/\/!< \r\ncontstr g_fileNormalName = _T(\"data_normal.txt\"); \/\/!< \r\ncontstr g_fileUniformName = _T(\"data_uniform.txt\"); \/\/!< \r\ncontstr g_fileExponentialName = _T(\"data_exponential.txt\"); \/\/!< \r\ncontstr g_fileTriangularName = _T(\"data_trinagular.txt\"); \/\/!< \r\nconst ruint g_count = 100000; \/\/!< \r\nconst double g_main = 10.0; \/\/!< \r\nconst double g_var = 1.0; \/\/!< \r\nconst double g_from = 1.0; \/\/!< \r\nconst double g_to = 7.0; \/\/!< \r\nconst double g_top = 5.0; \/\/!< \r\nconst ruint g_precision = 20; \/\/!< \r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Templates\r\n\/\/ --------------------------------------------------------------------------------\r\ntemplate <class T, class F, class contstr>\r\nvoid onGenerateData(F binder, contstr g_fileName)\r\n{\r\n\tif (rdo::File::exist(g_fileName.c_str()))\r\n\t\treturn;\r\n\r\n\tT sequence(g_seed);\r\n\tContainer test;\r\n\r\n\tfor (ruint i = 0; i < g_count; ++i)\r\n\t{\r\n\t\ttest.push_back(binder.operator()(&sequence));\r\n\t}\r\n\r\n\tstd::ofstream stream(g_fileName.c_str());\r\n\tstream.precision(g_precision);\r\n\tSTL_FOR_ALL(test, it)\r\n\t{\r\n\t\tstream << *it << std::endl;\r\n\t}\r\n}\r\n\r\ntemplate <class T, class F, class contstr>\r\nvoid onCheckData(F binder, contstr g_fileName)\r\n{\r\n\tstd::ifstream stream(g_fileName.c_str());\r\n\tBOOST_CHECK(stream.good());\r\n\r\n\tContainer test;\r\n\tT sequence(g_seed);\r\n\tfor (ruint i = 0; i < g_count; ++i)\r\n\t{\r\n\t\ttest.push_back(binder.operator()(&sequence));\r\n\t}\r\n\r\n\tstream.precision(g_precision);\r\n\tSTL_FOR_ALL(test, it)\r\n\t{\r\n\t\tBOOST_CHECK(stream.good());\r\n\t\ttstring str;\r\n\t\tstream >> str;\r\n\r\n\t\tdouble val;\r\n\t\tBOOST_CHECK(sscanf_s(str.c_str(), _T(\"%lf\"), &val) == 1);\r\n\t\tBOOST_CHECK(val == *it);\r\n\t\t\t\tif (val != *it)\r\n\t\t{\r\n\t\t\tstd::cout.precision(g_precision);\r\n\t\t\tstd::cout << *it << std::endl;\r\n\t\t\tstd::cout << val << std::endl;\r\n\t\t}\r\n\t}\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_SUITE(RDOSequencesTest)\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Normal sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDONormalTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorNormal>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDONormalTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorNormal>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Uniform sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOUniformTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorUniform>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOUniformTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorUniform>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Exponential sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorExponential>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorExponential>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------Triangular sequence\r\n\/\/ --------------------------------------------------------------------------------\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)\r\n{\r\n\tonGenerateData<rdoRuntime::RandGeneratorTriangular>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)\r\n{\r\n\tonCheckData<rdoRuntime::RandGeneratorTriangular>\r\n\t\t(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);\r\n}\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_SUITE_END()<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/include\/pixkit-image.hpp\"\n\nusing namespace\tcv;\nusing namespace std;\n\n\/\/ SCDBS\nbool SCDBS(const cv::Mat &src1b, const cv::Mat &init1b,const bool randGenInit,cv::Mat &dst1b,double *autocoeData,int FilterSize){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ exceptions\n\tif(src1b.type()!=CV_8UC1){\n\t\tassert(false);\n\t}\n\tif(FilterSize==1){\n\t\tassert(false);\n\t}else if(FilterSize%2==0){\n\t\tassert(false);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ initialization\n\tconst\tint\t&m_Height\t=\tsrc1b.rows;\n\tconst\tint\t&m_Width\t=\tsrc1b.cols;\n\tMat\tdst1f;\n\tdst1f.create(src1b.size(),CV_32FC1);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ get autocorrelation.\n\tint\texFS=FilterSize;\n\tint\ttempFS=FilterSize\/2;\n\tdouble\t**\tautocoe\t\t=\tnew\tdouble\t*\t[exFS];\n\tfor(int i=0;i<exFS;i++){\n\t\tautocoe[i]=&autocoeData[i*exFS];\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ load original image\n\tMat\tsrc1f(src1b.size(),CV_32FC1);\n\tsrc1b.convertTo(src1f,CV_32FC1);\n\t\/\/ get initial image\n\tinit1b.convertTo(dst1f,CV_32FC1);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Change grayscale to absorb\n\tsrc1f\t=\t1.-src1f\/255.;\n\tdst1f\t=\t1.-dst1f\/255.;\n\n\t\/\/\/ get error matrix\n\tMat\tem1f(src1b.size(),CV_32FC1);\n\tem1f\t=\tdst1f\t-\tsrc1f;\n\n\t\/\/\/ get cross correlation\n\tdouble\t*\tcrosscoeData\t=\tnew\tdouble\t\t[m_Height*m_Width];\n\tdouble\t**\tcrosscoe\t\t=\tnew\tdouble\t*\t[m_Height];\n\tfor(int i=0;i<m_Height;i++){\n\t\tcrosscoe[i]=&crosscoeData[i*m_Width];\n\t\tfor(int j=0;j<m_Width;j++){\n\t\t\tcrosscoe[i][j]=0.;\n\t\t\tfor(int m=i-tempFS;m<=i+tempFS;m++){\n\t\t\t\tfor(int n=j-tempFS;n<=j+tempFS;n++){\n\t\t\t\t\tif(m>=0&&m<m_Height&&n>=0&&n<m_Width){\n\t\t\t\t\t\tcrosscoe[i][j]+=em1f.ptr<float>(m)[n]*autocoe[tempFS+m-i][tempFS+n-j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ DBS process\n\tint\t\tBenefitPixelNumber;\n\tdouble\tdE[10],a0[10],a1[10];\n\twhile(1){\n\t\tBenefitPixelNumber=0;\n\t\tfor(int i=0;i<m_Height;i++){\t\/\/ entire image\n\t\t\tfor(int j=0;j<m_Width;j++){\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ check whether the current position is needed to be processed or not\n\t\t\t\tif(!randGenInit){\n\t\t\t\t\tif(init1b.ptr<uchar>(i)[j]==255){\t\/\/ inherit\n\t\t\t\t\t\tfloat\tinitv\t=\t1 - (float)init1b.ptr<uchar>(i)[j]\/255,\t\/\/ change to absorb for comparison\n\t\t\t\t\t\t\t\tdstv\t=\tdst1f.ptr<float>(i)[j];\n\t\t\t\t\t\tCV_DbgAssert(initv==dstv);\t\/\/ these two should be the same\n\t\t\t\t\t\tcontinue;\t\/\/ ignore.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ = = = = = trial part = = = = = \/\/\n\t\t\t\t\/\/ initialize psnr\t\t0: original psnr, 1~8: Swap, 9: Toggel.\n\t\t\t\t\/\/ 8 1 2\n\t\t\t\t\/\/ 7 0 3\n\t\t\t\t\/\/ 6 5 4\t\n\t\t\t\tfor(int m=0;m<10;m++){\n\t\t\t\t\tdE[m]=0.;\t\/\/ original error =0\n\t\t\t\t\ta0[m]=0.;\n\t\t\t\t\ta1[m]=0.;\n\t\t\t\t}\n\t\t\t\t\/\/ change the delta error as per different replacement methods\n\t\t\t\tfor(int mode=1;mode<10;mode++){\n\t\t\t\t\tint\t\tm,n;\n\t\t\t\t\tif(mode>=1&&mode<=8){\n\t\t\t\t\t\t\/\/ set position\n\t\t\t\t\t\tif(mode==1){\n\t\t\t\t\t\t\tm=1;\tn=0;\n\t\t\t\t\t\t}else if(mode==2){\n\t\t\t\t\t\t\tm=1;\tn=1;\n\t\t\t\t\t\t}else if(mode==3){\n\t\t\t\t\t\t\tm=0;\tn=1;\n\t\t\t\t\t\t}else if(mode==4){\n\t\t\t\t\t\t\tm=-1;\tn=1;\n\t\t\t\t\t\t}else if(mode==5){\n\t\t\t\t\t\t\tm=-1;\tn=0;\n\t\t\t\t\t\t}else if(mode==6){\n\t\t\t\t\t\t\tm=-1;\tn=-1;\n\t\t\t\t\t\t}else if(mode==7){\n\t\t\t\t\t\t\tm=0;\tn=-1;\n\t\t\t\t\t\t}else if(mode==8){\n\t\t\t\t\t\t\tm=1;\tn=-1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\t\t\/\/ get dE\n\t\t\t\t\t\tif(i+m>=0&&i+m<m_Height&&j+n>=0&&j+n<m_Width){\n\t\t\t\t\t\t\tif(!randGenInit){\n\t\t\t\t\t\t\t\tif(init1b.ptr<uchar>(i+m)[j+n]==255){\t\/\/ inherit\n\t\t\t\t\t\t\t\t\tcontinue;\t\/\/ ignore \n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/ get a0 and a1\n\t\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]==1){\n\t\t\t\t\t\t\t\ta0[mode]=-1;\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\ta0[mode]=1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(dst1f.ptr<float>(i+m)[j+n]==1){\n\t\t\t\t\t\t\t\ta1[mode]=-1;\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\ta1[mode]=1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/ get error\n\t\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]!=dst1f.ptr<float>(i+m)[j+n]){\n\t\t\t\t\t\t\t\tdE[mode]=(a0[mode]*a0[mode]+a1[mode]*a1[mode])\t*autocoe[tempFS][tempFS]\t+\t2.*a0[mode]\t*crosscoe[i][j]\t\t+\t2.*a0[mode]*a1[mode]\t\t\t\t\t*autocoe[tempFS+m][tempFS+n]\t+\t2.*a1[mode]\t\t\t\t\t\t\t\t*crosscoe[i+m][j+n];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if(mode==9){\n\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]==1){\n\t\t\t\t\t\t\ta0[mode]=-1;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ta0[mode]=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdE[mode]=\tautocoe[tempFS][tempFS]\t+\t2.*a0[mode]*crosscoe[i][j];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/\/\/\/ get minimum delta error and its position\n\t\t\t\tint\t\ttempMinNumber\t=0;\n\t\t\t\tdouble\ttempMindE\t\t=dE[0];\t\/\/ original error =0\n\t\t\t\tfor(int x=1;x<10;x++){\n\t\t\t\t\tif(dE[x]<tempMindE){\t\/\/ get smaller error only\n\t\t\t\t\t\ttempMindE\t\t=dE[x];\n\t\t\t\t\t\ttempMinNumber\t=x;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ check swap position\n\t\t\t\tint nm,nn;\n\t\t\t\tif(tempMinNumber==1){\n\t\t\t\t\tnm=1;\tnn=0;\n\t\t\t\t}else if(tempMinNumber==2){\n\t\t\t\t\tnm=1;\tnn=1;\n\t\t\t\t}else if(tempMinNumber==3){\n\t\t\t\t\tnm=0;\tnn=1;\n\t\t\t\t}else if(tempMinNumber==4){\n\t\t\t\t\tnm=-1;\tnn=1;\n\t\t\t\t}else if(tempMinNumber==5){\n\t\t\t\t\tnm=-1;\tnn=0;\n\t\t\t\t}else if(tempMinNumber==6){\n\t\t\t\t\tnm=-1;\tnn=-1;\n\t\t\t\t}else if(tempMinNumber==7){\n\t\t\t\t\tnm=0;\tnn=-1;\n\t\t\t\t}else if(tempMinNumber==8){\n\t\t\t\t\tnm=1;\tnn=-1;\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ = = = = = update part = = = = = \/\/\n\t\t\t\tif(tempMindE<0.){\t\/\/ error is reduced\n\t\t\t\t\t\/\/ update current hft position\n\t\t\t\t\tdst1f.ptr<float>(i)[j]\t=1.-dst1f.ptr<float>(i)[j];\n\t\t\t\t\tif(tempMinNumber>=1&&tempMinNumber<=8){\t\/\/ swap case\n\t\t\t\t\t\t\/\/ get position\n\t\t\t\t\t\tint nm,nn;\n\t\t\t\t\t\tif(tempMinNumber==1){\n\t\t\t\t\t\t\tnm=1;\tnn=0;\n\t\t\t\t\t\t}else if(tempMinNumber==2){\n\t\t\t\t\t\t\tnm=1;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==3){\n\t\t\t\t\t\t\tnm=0;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==4){\n\t\t\t\t\t\t\tnm=-1;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==5){\n\t\t\t\t\t\t\tnm=-1;\tnn=0;\n\t\t\t\t\t\t}else if(tempMinNumber==6){\n\t\t\t\t\t\t\tnm=-1;\tnn=-1;\n\t\t\t\t\t\t}else if(tempMinNumber==7){\n\t\t\t\t\t\t\tnm=0;\tnn=-1;\n\t\t\t\t\t\t}else if(tempMinNumber==8){\n\t\t\t\t\t\t\tnm=1;\tnn=-1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ update swapped hft position\n\t\t\t\t\t\tdst1f.ptr<float>(i+nm)[j+nn]\t=\t1.\t-\tdst1f.ptr<float>(i+nm)[j+nn];\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ update cross correlation\n\t\t\t\t\t\tfor(int m=-tempFS;m<=tempFS;m++){\n\t\t\t\t\t\t\tfor(int n=-tempFS;n<=tempFS;n++){\n\t\t\t\t\t\t\t\tif(i+m>=0&&i+m<m_Height&&j+n>=0&&j+n<m_Width){\n\t\t\t\t\t\t\t\t\tcrosscoe[i+m][j+n]+=a0[tempMinNumber]*autocoe[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(i+m+nm>=0&&i+m+nm<m_Height&&j+n+nn>=0&&j+n+nn<m_Width){\n\t\t\t\t\t\t\t\t\tcrosscoe[i+m+nm][j+n+nn]+=a1[tempMinNumber]*autocoe[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if(tempMinNumber==9){\t\/\/ toggle case\n\t\t\t\t\t\t\/\/ update cross correlation\n\t\t\t\t\t\tfor(int m=-tempFS;m<=tempFS;m++){\n\t\t\t\t\t\t\tfor(int n=-tempFS;n<=tempFS;n++){\n\t\t\t\t\t\t\t\tif(i+m>=0&&i+m<m_Height&&j+n>=0&&j+n<m_Width){\n\t\t\t\t\t\t\t\t\tcrosscoe[i+m][j+n]+=a0[tempMinNumber]*autocoe[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tBenefitPixelNumber++;\n\t\t\t\t} \/\/ end of entire image\n\t\t\t}\n\t\t}\n\t\tif(BenefitPixelNumber==0){\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Change absorb to grayscale\n\tdst1b.create(src1b.size(),CV_8UC1);\n\tfor(int i=0;i<m_Height;i++){\n\t\tfor(int j=0;j<m_Width;j++){\n\t\t\tdst1b.ptr<uchar>(i)[j]=(1.-dst1f.ptr<float>(i)[j])*255.;\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ release space\n\tdelete\t[]\tcrosscoeData;\n\tdelete\t[]\tcrosscoe;\n\tdelete\t[]\tautocoe;\n\n\treturn true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool pixkit::halftoning::ordereddithering::DMS_2Level2012_genDitherArray(cv::Mat &DA, int daSize){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ init\n\tconst\tuchar\tMAX_GRAYSCALE\t=\t255;\n\tconst\tuchar\tMIN_GRAYSCALE\t=\t0;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ initialization \n\tcv::Mat compressedTable1b, src1b, dst1b;\n\tcompressedTable1b.create(Size(daSize, daSize), CV_8UC1);\n\tsrc1b.create(Size(daSize, daSize), CV_8UC1);\n\tdst1b.create(Size(daSize, daSize), CV_8UC1);\n\tsrc1b.setTo(MIN_GRAYSCALE);\n\tdst1b.setTo(MIN_GRAYSCALE);\n\tcompressedTable1b.setTo(MIN_GRAYSCALE);\n\t\/\/ get coe\n\tMat\thvs_model_cpp;\n\tpixkit::halftoning::ungrouped::generateTwoComponentGaussianModel(hvs_model_cpp,43.2,38.7,0.02,0.06);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ process for masks of 0 to 255\n\tMat\tpre_dst1b;\n\tMat\tinit1b(Size(daSize, daSize), CV_8UC1);\n\tinit1b.setTo(MIN_GRAYSCALE);\n\tfor (int grayscale = MIN_GRAYSCALE; grayscale <= MAX_GRAYSCALE; grayscale++){\n\t\tcout << \"grayscale = \" << (int)grayscale << endl;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ init\n\t\tsrc1b.setTo(grayscale);\n\t\tpre_dst1b = dst1b.clone(); \/\/ recode the result of dst(g-1)\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ rand generates the initial mask\n\t\tbool\trandGenInit\t=false;\n\t\tif(cv::sum(init1b)[0]==0){\n\t\t\trandGenInit\t=\ttrue;\n\t\t\tsrand(0);\n\t\t\tfor(int i=0;i<init1b.rows;i++){\n\t\t\t\tfor(int j=0;j<init1b.cols;j++){\n\t\t\t\t\tdouble\ttemp=((double)rand())\/32767.;\n\t\t\t\t\tinit1b.ptr<uchar>(i)[j]=temp<0.5?MIN_GRAYSCALE:MAX_GRAYSCALE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ process\n\t\tSCDBS(src1b,init1b,randGenInit,dst1b,&(double&)hvs_model_cpp.data[0],hvs_model_cpp.rows);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ get init\n\t\tinit1b\t=\tdst1b.clone();\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ record position that the white point is firstly toggled\n\t\tfor (int i = 0; i < dst1b.rows; i++){\n\t\t\tfor (int j = 0; j < dst1b.cols; j++){\n\t\t\t\tif (dst1b.ptr<uchar>(i)[j] == MAX_GRAYSCALE && pre_dst1b.ptr<uchar>(i)[j] == MIN_GRAYSCALE){\n\t\t\t\t\tcompressedTable1b.ptr<uchar>(i)[j]\t=\tgrayscale;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tDA\t=\tcompressedTable1b.clone();\n\n\treturn true;\n}\n\nbool pixkit::halftoning::ordereddithering::DMS_2Level2012(const cv::Mat &src1b, const cv::Mat &ditherarray1b,cv::Mat &dst1b){\n\tdst1b.create(src1b.size(),src1b.type());\n\tfor(int i=0;i<src1b.rows;i++){\n\t\tfor(int j=0;j<src1b.cols;j++){\n\t\t\tif(src1b.ptr<uchar>(i)[j]>=ditherarray1b.ptr<uchar>(i%ditherarray1b.rows)[j%ditherarray1b.cols]){\n\t\t\t\tdst1b.ptr<uchar>(i)[j]\t=\t255;\n\t\t\t}else{\n\t\t\t\tdst1b.ptr<uchar>(i)[j]\t=\t0;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}<commit_msg>add warp-around property<commit_after>#include \"..\/..\/..\/include\/pixkit-image.hpp\"\n\nusing namespace\tcv;\nusing namespace std;\n\n\/\/ coordination correction\ninline int\tcirCC(int cor,int limitation){\n\tint\ttempv\t=\tcor%limitation;\n\tif(tempv>=0){\n\t\treturn\ttempv;\n\t}else{\t\/\/ if(tempv<0)\n\t\treturn\tlimitation+tempv;\n\t}\n}\n\n\/\/ SCDBS\nbool SCDBS(const cv::Mat &src1b, const cv::Mat &init1b,const bool first_grayscale,cv::Mat &dst1b,double *c_ppData,int FilterSize){\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ exceptions\n\tif(src1b.type()!=CV_8UC1){\n\t\tassert(false);\n\t}\n\tif(FilterSize==1){\n\t\tassert(false);\n\t}else if(FilterSize%2==0){\n\t\tassert(false);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ initialization\n\tconst\tint\t&height\t=\tsrc1b.rows;\n\tconst\tint\t&width\t=\tsrc1b.cols;\n\tMat\tdst1f;\n\tdst1f.create(src1b.size(),CV_32FC1);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ get autocorrelation.\n\tint\texFS=FilterSize;\n\tint\ttempFS=FilterSize\/2;\n\tdouble\t**\tc_pp\t\t=\tnew\tdouble\t*\t[exFS];\n\tfor(int i=0;i<exFS;i++){\n\t\tc_pp[i]=&c_ppData[i*exFS];\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ load original image\n\tMat\tsrc1f(src1b.size(),CV_32FC1);\n\tsrc1b.convertTo(src1f,CV_32FC1);\n\t\/\/ get initial image\n\tinit1b.convertTo(dst1f,CV_32FC1);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Change grayscale to absorb\n\tsrc1f\t=\t1.-src1f\/255.;\n\tdst1f\t=\t1.-dst1f\/255.;\n\n\t\/\/\/ get error matrix\n\tMat\tem1f(src1b.size(),CV_32FC1);\n\tem1f\t=\tdst1f\t-\tsrc1f;\n\n\t\/\/\/ get cross correlation\n\tMat\tcrosscoe1d(Size(width,height),CV_64FC1);\n\tcrosscoe1d.setTo(0);\n\tfor(int i=0;i<crosscoe1d.rows;i++){\n\t\tfor(int j=0;j<crosscoe1d.cols;j++){\n\t\t\tfor(int m=i-tempFS;m<=i+tempFS;m++){\n\t\t\t\tfor(int n=j-tempFS;n<=j+tempFS;n++){\n\t\t\t\t\tcrosscoe1d.ptr<double>(i)[j]+=em1f.ptr<float>(cirCC(m,height))[cirCC(n,width)]*c_pp[tempFS+m-i][tempFS+n-j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ DBS process\n\tint\t\tBenefitPixelNumber;\n\tdouble\tdE[10],a0[10],a1[10];\n\twhile(1){\n\t\tBenefitPixelNumber=0;\n\t\tfor(int i=0;i<height;i++){\t\/\/ entire image\n\t\t\tfor(int j=0;j<width;j++){\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ check whether the current position is needed to be processed or not\n\t\t\t\tif(!first_grayscale){\n\t\t\t\t\tif(init1b.ptr<uchar>(i)[j]==255){\t\/\/ inherit\n\t\t\t\t\t\tfloat\tinitv\t=\t1 - (float)init1b.ptr<uchar>(i)[j]\/255,\t\/\/ change to absorb for comparison\n\t\t\t\t\t\t\t\tdstv\t=\tdst1f.ptr<float>(i)[j];\n\t\t\t\t\t\tCV_DbgAssert(initv==dstv);\t\/\/ these two should be the same\n\t\t\t\t\t\tcontinue;\t\/\/ ignore.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ = = = = = trial part = = = = = \/\/\n\t\t\t\t\/\/ initialize psnr\t\t0: original psnr, 1~8: Swap, 9: Toggel.\n\t\t\t\t\/\/ 8 1 2\n\t\t\t\t\/\/ 7 0 3\n\t\t\t\t\/\/ 6 5 4\t\n\t\t\t\tfor(int m=0;m<10;m++){\n\t\t\t\t\tdE[m]=0.;\t\/\/ original error =0\n\t\t\t\t\ta0[m]=0.;\n\t\t\t\t\ta1[m]=0.;\n\t\t\t\t}\n\t\t\t\t\/\/ change the delta error as per different replacement methods\n\t\t\t\tfor(int mode=1;mode<10;mode++){\n\t\t\t\t\tint\t\tm,n;\n\t\t\t\t\tif(mode>=1&&mode<=8){\n\t\t\t\t\t\t\/\/ set position\n\t\t\t\t\t\tif(mode==1){\n\t\t\t\t\t\t\tm=1;\tn=0;\n\t\t\t\t\t\t}else if(mode==2){\n\t\t\t\t\t\t\tm=1;\tn=1;\n\t\t\t\t\t\t}else if(mode==3){\n\t\t\t\t\t\t\tm=0;\tn=1;\n\t\t\t\t\t\t}else if(mode==4){\n\t\t\t\t\t\t\tm=-1;\tn=1;\n\t\t\t\t\t\t}else if(mode==5){\n\t\t\t\t\t\t\tm=-1;\tn=0;\n\t\t\t\t\t\t}else if(mode==6){\n\t\t\t\t\t\t\tm=-1;\tn=-1;\n\t\t\t\t\t\t}else if(mode==7){\n\t\t\t\t\t\t\tm=0;\tn=-1;\n\t\t\t\t\t\t}else if(mode==8){\n\t\t\t\t\t\t\tm=1;\tn=-1;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\t\t\/\/ get dE\n\t\t\t\t\t\tif(!first_grayscale){\n\t\t\t\t\t\t\tif(init1b.ptr<uchar>(cirCC(i+m,height))[cirCC(j+n,width)]==255){\t\/\/ inherit\n\t\t\t\t\t\t\t\tcontinue;\t\/\/ ignore \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ get a0 and a1\n\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]==1){\n\t\t\t\t\t\t\ta0[mode]=-1;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ta0[mode]=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(dst1f.ptr<float>(cirCC(i+m,height))[cirCC(j+n,width)]==1){\n\t\t\t\t\t\t\ta1[mode]=-1;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ta1[mode]=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ get error\n\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]!=dst1f.ptr<float>(cirCC(i+m,height))[cirCC(j+n,width)]){\n\t\t\t\t\t\t\tdE[mode]=(a0[mode]*a0[mode]+a1[mode]*a1[mode])\t*c_pp[tempFS][tempFS]\t+\t2.*a0[mode]\t*crosscoe1d.ptr<double>(i)[j]\t\t\n\t\t\t\t\t\t\t+2.*a0[mode]*a1[mode]\t*\tc_pp[tempFS+m][tempFS+n]\t\n\t\t\t\t\t\t\t+2.*a1[mode]\t\t\t*\tcrosscoe1d.ptr<double>(cirCC(i+m,height))[cirCC(j+n,width)];\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if(mode==9){\n\t\t\t\t\t\tif(dst1f.ptr<float>(i)[j]==1){\n\t\t\t\t\t\t\ta0[mode]=-1;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ta0[mode]=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdE[mode]=\tc_pp[tempFS][tempFS]\t+\t2.*a0[mode]*crosscoe1d.ptr<double>(i)[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/\/\/\/ get minimum delta error and its position\n\t\t\t\tint\t\ttempMinNumber\t=0;\n\t\t\t\tdouble\ttempMindE\t\t=dE[0];\t\/\/ original error =0\n\t\t\t\tfor(int x=1;x<10;x++){\n\t\t\t\t\tif(dE[x]<tempMindE){\t\/\/ get smaller error only\n\t\t\t\t\t\ttempMindE\t\t=dE[x];\n\t\t\t\t\t\ttempMinNumber\t=x;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\t\/\/ = = = = = update part = = = = = \/\/\n\t\t\t\tif(tempMindE<0.){\t\/\/ error is reduced\n\t\t\t\t\t\/\/ update current hft position\n\t\t\t\t\tdst1f.ptr<float>(i)[j]\t=\tsaturate_cast<float>(1.-dst1f.ptr<float>(i)[j]);\n\t\t\t\t\tif(tempMinNumber>=1&&tempMinNumber<=8){\t\/\/ swap case\n\t\t\t\t\t\t\/\/ get position, and check swap position\n\t\t\t\t\t\tint nm,nn;\n\t\t\t\t\t\tif(tempMinNumber==1){\n\t\t\t\t\t\t\tnm=1;\tnn=0;\n\t\t\t\t\t\t}else if(tempMinNumber==2){\n\t\t\t\t\t\t\tnm=1;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==3){\n\t\t\t\t\t\t\tnm=0;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==4){\n\t\t\t\t\t\t\tnm=-1;\tnn=1;\n\t\t\t\t\t\t}else if(tempMinNumber==5){\n\t\t\t\t\t\t\tnm=-1;\tnn=0;\n\t\t\t\t\t\t}else if(tempMinNumber==6){\n\t\t\t\t\t\t\tnm=-1;\tnn=-1;\n\t\t\t\t\t\t}else if(tempMinNumber==7){\n\t\t\t\t\t\t\tnm=0;\tnn=-1;\n\t\t\t\t\t\t}else if(tempMinNumber==8){\n\t\t\t\t\t\t\tnm=1;\tnn=-1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ update swapped hft position\n\t\t\t\t\t\tdst1f.ptr<float>(cirCC(i+nm,height))[cirCC(j+nn,width)]\t=\tsaturate_cast<float>(1.\t-\tdst1f.ptr<float>(cirCC(i+nm,height))[cirCC(j+nn,width)]);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ update cross correlation\n\t\t\t\t\t\tfor(int m=-tempFS;m<=tempFS;m++){\n\t\t\t\t\t\t\tfor(int n=-tempFS;n<=tempFS;n++){\n\t\t\t\t\t\t\t\tcrosscoe1d.ptr<double>(cirCC(i+m,height))[cirCC(j+n,width)]+=a0[tempMinNumber]*c_pp[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t\tcrosscoe1d.ptr<double>(cirCC(i+m+nm,height))[cirCC(j+n+nn,width)]+=a1[tempMinNumber]*c_pp[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}else if(tempMinNumber==9){\t\/\/ toggle case\n\t\t\t\t\t\t\/\/ update cross correlation\n\t\t\t\t\t\tfor(int m=-tempFS;m<=tempFS;m++){\n\t\t\t\t\t\t\tfor(int n=-tempFS;n<=tempFS;n++){\n\t\t\t\t\t\t\t\tcrosscoe1d.ptr<double>(cirCC(i+m,height))[cirCC(j+n,width)]+=a0[tempMinNumber]*c_pp[tempFS+m][tempFS+n];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tBenefitPixelNumber++;\n\t\t\t\t} \/\/ end of entire image\n\t\t\t}\n\t\t}\n\t\tif(BenefitPixelNumber==0){\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Change absorb to grayscale\n\tdst1b.create(src1b.size(),CV_8UC1);\n\tfor(int i=0;i<height;i++){\n\t\tfor(int j=0;j<width;j++){\n\t\t\tdst1b.ptr<uchar>(i)[j]=cvRound((1.-dst1f.ptr<float>(i)[j])*255.);\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ release space\n\tdelete\t[]\tc_pp;\n\n\treturn true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool pixkit::halftoning::ordereddithering::DMS_2Level2012_genDitherArray(cv::Mat &DA, int daSize){\n\/\/ the N defined in paper is supposed as daSize in this program.\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ init\n\tconst\tuchar\tMAX_GRAYSCALE\t=\t255;\t\/\/ defined R in paper\n\tconst\tuchar\tMIN_GRAYSCALE\t=\t0;\n\tconst\tuchar\tafa_1\t\t\t=\t0;\t\t\/\/ parameter defined in paper\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ initialization \n\tcv::Mat compressedTable1b, src1b, dst1b;\n\tcompressedTable1b.create(Size(daSize, daSize), CV_8UC1);\n\tsrc1b.create(Size(daSize, daSize), CV_8UC1);\n\tdst1b.create(Size(daSize, daSize), CV_8UC1);\n\tsrc1b.setTo(MIN_GRAYSCALE);\n\tdst1b.setTo(MIN_GRAYSCALE);\n\tcompressedTable1b.setTo(MIN_GRAYSCALE);\n\t\/\/ get coe\n\tMat\thvs_model_cpp;\n\tpixkit::halftoning::ungrouped::generateTwoComponentGaussianModel(hvs_model_cpp,43.2,38.7,0.02,0.06);\t\/\/ checked\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/ process for masks of 0 to 255\n\tMat\tpre_dst1b;\n\tMat\tinit1b(Size(daSize, daSize), CV_8UC1);\n\tinit1b.setTo(afa_1);\t\/\/ as described in paper, this value should be zero.\n\tfor (int eta = MIN_GRAYSCALE; eta <= MAX_GRAYSCALE; eta++){\t\t\/\/ eta is defined as a grayscale in paper\n\t\tcout << \"grayscale = \" << (int)eta << endl;\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ init\n\t\tsrc1b.setTo(eta);\n\t\tpre_dst1b = dst1b.clone(); \/\/ recode the result of dst(g-1)\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ process\n\t\t\/\/ check whether it's the first grayscale\n\t\tbool\tfirst_grayscale\t=false;\n\t\tif(cv::sum(init1b)[0]==0){\n\t\t\tfirst_grayscale\t=\ttrue;\n\t\t}\t\n\t\t\/\/ process\n\t\tSCDBS(src1b,init1b,first_grayscale,dst1b,&(double&)hvs_model_cpp.data[0],hvs_model_cpp.rows);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ get init\n\t\tinit1b\t=\tdst1b.clone();\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/\/\/\/ record position that the white point is firstly toggled\n\t\tfor (int i = 0; i < dst1b.rows; i++){\n\t\t\tfor (int j = 0; j < dst1b.cols; j++){\n\t\t\t\tif (dst1b.ptr<uchar>(i)[j] == MAX_GRAYSCALE && pre_dst1b.ptr<uchar>(i)[j] == MIN_GRAYSCALE){\n\t\t\t\t\tcompressedTable1b.ptr<uchar>(i)[j]\t=\teta;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tDA\t=\tcompressedTable1b.clone();\n\n\treturn true;\n}\n\nbool pixkit::halftoning::ordereddithering::DMS_2Level2012(const cv::Mat &src1b, const cv::Mat &ditherarray1b,cv::Mat &dst1b){\t\n\tdst1b.create(src1b.size(),src1b.type());\n\tfor(int i=0;i<src1b.rows;i++){\n\t\tfor(int j=0;j<src1b.cols;j++){\n\t\t\tif(src1b.ptr<uchar>(i)[j]>=ditherarray1b.ptr<uchar>(i%ditherarray1b.rows)[j%ditherarray1b.cols]){\n\t\t\t\tdst1b.ptr<uchar>(i)[j]\t=\t255;\n\t\t\t}else{\n\t\t\t\tdst1b.ptr<uchar>(i)[j]\t=\t0;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/Utility\/Resource.h>\n#include <Magnum\/AbstractShaderProgram.h>\n#include <Magnum\/Buffer.h>\n#include <Magnum\/Context.h>\n#include <Magnum\/DefaultFramebuffer.h>\n#include <Magnum\/Framebuffer.h>\n#include <Magnum\/Image.h>\n#include <Magnum\/PixelFormat.h>\n#include <Magnum\/Renderbuffer.h>\n#include <Magnum\/RenderbufferFormat.h>\n#include <Magnum\/Renderer.h>\n#include <Magnum\/Shader.h>\n#include <Magnum\/Texture.h>\n#include <Magnum\/TextureFormat.h>\n#include <Magnum\/Version.h>\n#include <Magnum\/Math\/Color.h>\n#include <Magnum\/MeshTools\/CompressIndices.h>\n#include <Magnum\/MeshTools\/Interleave.h>\n#include <Magnum\/Platform\/Sdl2Application.h>\n#include <Magnum\/Primitives\/Cube.h>\n#include <Magnum\/Primitives\/Plane.h>\n#include <Magnum\/Primitives\/UVSphere.h>\n#include <Magnum\/Trade\/MeshData3D.h>\n#include <Magnum\/SceneGraph\/Scene.h>\n#include <Magnum\/SceneGraph\/MatrixTransformation3D.h>\n#include <Magnum\/SceneGraph\/Camera.h>\n#include <Magnum\/SceneGraph\/Drawable.h>\n\nusing namespace Magnum;\n\ntypedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;\ntypedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;\n\nclass PhongIdShader: public AbstractShaderProgram {\n public:\n typedef Attribute<0, Vector3> Position;\n typedef Attribute<1, Vector3> Normal;\n\n enum: UnsignedInt {\n ColorOutput = 0,\n ObjectIdOutput = 1\n };\n\n explicit PhongIdShader();\n\n PhongIdShader& setObjectId(Int id) {\n setUniform(_objectIdUniform, id);\n return *this;\n }\n\n PhongIdShader& setLightPosition(const Vector3& position) {\n setUniform(_lightPositionUniform, position);\n return *this;\n }\n\n PhongIdShader& setAmbientColor(const Color3& color) {\n setUniform(_ambientColorUniform, color);\n return *this;\n }\n\n PhongIdShader& setColor(const Color3& color) {\n setUniform(_colorUniform, color);\n return *this;\n }\n\n PhongIdShader& setTransformationMatrix(const Matrix4& matrix) {\n setUniform(_transformationMatrixUniform, matrix);\n return *this;\n }\n\n PhongIdShader& setNormalMatrix(const Matrix3x3& matrix) {\n setUniform(_normalMatrixUniform, matrix);\n return *this;\n }\n\n PhongIdShader& setProjectionMatrix(const Matrix4& matrix) {\n setUniform(_projectionMatrixUniform, matrix);\n return *this;\n }\n\n private:\n Int _objectIdUniform,\n _lightPositionUniform,\n _ambientColorUniform,\n _colorUniform,\n _transformationMatrixUniform,\n _normalMatrixUniform,\n _projectionMatrixUniform;\n};\n\nPhongIdShader::PhongIdShader() {\n Utility::Resource rs(\"picking-data\");\n\n Shader vert{Version::GL330, Shader::Type::Vertex},\n frag{Version::GL330, Shader::Type::Fragment};\n vert.addSource(rs.get(\"PhongId.vert\"));\n frag.addSource(rs.get(\"PhongId.frag\"));\n CORRADE_INTERNAL_ASSERT(Shader::compile({vert, frag}));\n attachShaders({vert, frag});\n CORRADE_INTERNAL_ASSERT(link());\n\n _objectIdUniform = uniformLocation(\"objectId\");\n _lightPositionUniform = uniformLocation(\"light\");\n _ambientColorUniform = uniformLocation(\"ambientColor\");\n _colorUniform = uniformLocation(\"color\");\n _transformationMatrixUniform = uniformLocation(\"transformationMatrix\");\n _projectionMatrixUniform = uniformLocation(\"projectionMatrix\");\n _normalMatrixUniform = uniformLocation(\"normalMatrix\");\n}\n\nclass PickableObject: public Object3D, SceneGraph::Drawable3D {\n public:\n explicit PickableObject(UnsignedByte id, PhongIdShader& shader, const Color3& color, Mesh& mesh, Object3D& parent, SceneGraph::DrawableGroup3D& drawables): Object3D{&parent}, SceneGraph::Drawable3D{*this, &drawables}, _id{id}, _selected{false}, _shader(shader), _color{color}, _mesh(mesh) {}\n\n void setSelected(bool selected) { _selected = selected; }\n\n private:\n virtual void draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) {\n _shader.setTransformationMatrix(transformationMatrix)\n .setNormalMatrix(transformationMatrix.rotationScaling())\n .setProjectionMatrix(camera.projectionMatrix())\n .setAmbientColor(_selected ? _color*0.3f : Color3{})\n .setColor(_color*(_selected ? 2.0f : 1.0f))\n \/* relative to the camera *\/\n .setLightPosition({13.0f, 2.0f, 5.0f})\n .setObjectId(_id);\n _mesh.draw(_shader);\n }\n\n UnsignedByte _id;\n bool _selected;\n PhongIdShader& _shader;\n Color3 _color;\n Mesh& _mesh;\n};\n\nclass PickingExample: public Platform::Application {\n public:\n explicit PickingExample(const Arguments& arguments);\n\n private:\n void drawEvent() override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n void mouseReleaseEvent(MouseEvent& event) override;\n\n Scene3D _scene;\n Object3D* _cameraObject;\n SceneGraph::Camera3D* _camera;\n SceneGraph::DrawableGroup3D _drawables;\n\n PhongIdShader _shader;\n Buffer _cubeVertices, _cubeIndices,\n _sphereVertices, _sphereIndices,\n _planeVertices;\n Mesh _cube, _plane, _sphere;\n\n enum { ObjectCount = 6 };\n PickableObject* _objects[ObjectCount];\n\n Framebuffer _framebuffer;\n Renderbuffer _color, _objectId, _depth;\n\n Vector2i _previousMousePosition, _mousePressPosition;\n};\n\nPickingExample::PickingExample(const Arguments& arguments): Platform::Application{arguments, Configuration{}.setTitle(\"Magnum object picking example\")}, _framebuffer{defaultFramebuffer.viewport()} {\n MAGNUM_ASSERT_VERSION_SUPPORTED(Version::GL330);\n\n \/* Global renderer configuration *\/\n Renderer::enable(Renderer::Feature::DepthTest);\n\n \/* Configure framebuffer (using R8UI for object ID which means 255 objects max) *\/\n _color.setStorage(RenderbufferFormat::RGBA8, defaultFramebuffer.viewport().size());\n _objectId.setStorage(RenderbufferFormat::R8UI, defaultFramebuffer.viewport().size());\n _depth.setStorage(RenderbufferFormat::DepthComponent24, defaultFramebuffer.viewport().size());\n _framebuffer.attachRenderbuffer(Framebuffer::ColorAttachment{0}, _color)\n .attachRenderbuffer(Framebuffer::ColorAttachment{1}, _objectId)\n .attachRenderbuffer(Framebuffer::BufferAttachment::Depth, _depth)\n .mapForDraw({{PhongIdShader::ColorOutput, Framebuffer::ColorAttachment{0}},\n {PhongIdShader::ObjectIdOutput, Framebuffer::ColorAttachment{1}}});\n CORRADE_INTERNAL_ASSERT(_framebuffer.checkStatus(FramebufferTarget::Draw) == Framebuffer::Status::Complete);\n\n \/* Set up meshes *\/\n {\n Trade::MeshData3D data = Primitives::Cube::solid();\n _cubeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _cubeIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), BufferUsage::StaticDraw);\n _cube.setCount(data.indices().size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_cubeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{})\n .setIndexBuffer(_cubeIndices, 0, Mesh::IndexType::UnsignedShort);\n } {\n Trade::MeshData3D data = Primitives::UVSphere::solid(16, 32);\n _sphereVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _sphereIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), BufferUsage::StaticDraw);\n _sphere.setCount(data.indices().size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_sphereVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{})\n .setIndexBuffer(_sphereIndices, 0, Mesh::IndexType::UnsignedShort);\n } {\n Trade::MeshData3D data = Primitives::Plane::solid();\n _planeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _plane.setCount(data.positions(0).size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_planeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{});\n }\n\n \/* Set up objects *\/\n (*(_objects[0] = new PickableObject{1, _shader, Color3::fromHSV(25.0_degf, 0.9f, 0.9f), _cube, _scene, _drawables}))\n .rotate(34.0_degf, Vector3(1.0f).normalized())\n .translate({1.0f, 0.3f, -1.2f});\n (*(_objects[1] = new PickableObject{2, _shader, Color3::fromHSV(54.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({-1.2f, -0.3f, -0.2f});\n (*(_objects[2] = new PickableObject{3, _shader, Color3::fromHSV(105.0_degf, 0.9f, 0.9f), _plane, _scene, _drawables}))\n .rotate(254.0_degf, Vector3(1.0f).normalized())\n .scale(Vector3(0.45f))\n .translate({0.5f, 1.3f, 1.5f});\n (*(_objects[3] = new PickableObject{4, _shader, Color3::fromHSV(162.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({-0.2f, -1.7f, -2.7f});\n (*(_objects[4] = new PickableObject{5, _shader, Color3::fromHSV(210.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({0.7f, 0.6f, 2.2f})\n .scale(Vector3(0.75f));\n (*(_objects[5] = new PickableObject{6, _shader, Color3::fromHSV(280.0_degf, 0.9f, 0.9f), _cube, _scene, _drawables}))\n .rotate(-92.0_degf, Vector3(1.0f).normalized())\n .scale(Vector3(0.25f))\n .translate({-0.5f, -0.3f, 1.8f});\n\n \/* Configure camera *\/\n _cameraObject = new Object3D{&_scene};\n _cameraObject->translate(Vector3::zAxis(8.0f));\n _camera = new SceneGraph::Camera3D{*_cameraObject};\n _camera->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)\n .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 4.0f\/3.0f, 0.001f, 100.0f))\n .setViewport(defaultFramebuffer.viewport().size());\n}\n\nvoid PickingExample::drawEvent() {\n \/* Draw to custom framebuffer *\/\n _framebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth)\n .bind();\n _camera->draw(_drawables);\n\n \/* Blit color to window framebuffer *\/\n _framebuffer.mapForRead(Framebuffer::ColorAttachment{0});\n AbstractFramebuffer::blit(_framebuffer, defaultFramebuffer,\n {{}, _framebuffer.viewport().size()}, FramebufferBlit::Color);\n\n swapBuffers();\n}\n\nvoid PickingExample::mousePressEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left) return;\n\n _previousMousePosition = _mousePressPosition = event.position();\n event.setAccepted();\n}\n\nvoid PickingExample::mouseMoveEvent(MouseMoveEvent& event) {\n if(!(event.buttons() & MouseMoveEvent::Button::Left)) return;\n\n const Vector2 delta = 3.0f*\n Vector2{event.position() - _previousMousePosition}\/\n Vector2{defaultFramebuffer.viewport().size()};\n\n (*_cameraObject)\n .rotate(Rad{-delta.y()}, _cameraObject->transformation().right().normalized())\n .rotateY(Rad{-delta.x()});\n\n _previousMousePosition = event.position();\n event.setAccepted();\n redraw();\n}\n\nvoid PickingExample::mouseReleaseEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left || _mousePressPosition != event.position()) return;\n\n \/* Read object ID at given click position (framebuffer has Y up while windowing system Y down) *\/\n _framebuffer.mapForRead(Framebuffer::ColorAttachment{1});\n Image2D data = _framebuffer.read(\n Range2Di::fromSize({event.position().x(), _framebuffer.viewport().sizeY() - event.position().y() - 1}, {1, 1}),\n {PixelFormat::RedInteger, PixelType::UnsignedByte});\n\n \/* Highlight object under mouse and deselect all other *\/\n for(auto* o: _objects) o->setSelected(false);\n UnsignedByte id = data.data<UnsignedByte>()[0];\n if(id > 0 && id < ObjectCount + 1)\n _objects[id - 1]->setSelected(true);\n\n event.setAccepted();\n redraw();\n}\n\nMAGNUM_APPLICATION_MAIN(PickingExample)\n<commit_msg>picking: make the example working on Mesa.<commit_after>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/Utility\/Resource.h>\n#include <Magnum\/AbstractShaderProgram.h>\n#include <Magnum\/Buffer.h>\n#include <Magnum\/Context.h>\n#include <Magnum\/DefaultFramebuffer.h>\n#include <Magnum\/Framebuffer.h>\n#include <Magnum\/Image.h>\n#include <Magnum\/PixelFormat.h>\n#include <Magnum\/Renderbuffer.h>\n#include <Magnum\/RenderbufferFormat.h>\n#include <Magnum\/Renderer.h>\n#include <Magnum\/Shader.h>\n#include <Magnum\/Texture.h>\n#include <Magnum\/TextureFormat.h>\n#include <Magnum\/Version.h>\n#include <Magnum\/Math\/Color.h>\n#include <Magnum\/MeshTools\/CompressIndices.h>\n#include <Magnum\/MeshTools\/Interleave.h>\n#include <Magnum\/Platform\/Sdl2Application.h>\n#include <Magnum\/Primitives\/Cube.h>\n#include <Magnum\/Primitives\/Plane.h>\n#include <Magnum\/Primitives\/UVSphere.h>\n#include <Magnum\/Trade\/MeshData3D.h>\n#include <Magnum\/SceneGraph\/Scene.h>\n#include <Magnum\/SceneGraph\/MatrixTransformation3D.h>\n#include <Magnum\/SceneGraph\/Camera.h>\n#include <Magnum\/SceneGraph\/Drawable.h>\n\nusing namespace Magnum;\n\ntypedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;\ntypedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;\n\nclass PhongIdShader: public AbstractShaderProgram {\n public:\n typedef Attribute<0, Vector3> Position;\n typedef Attribute<1, Vector3> Normal;\n\n enum: UnsignedInt {\n ColorOutput = 0,\n ObjectIdOutput = 1\n };\n\n explicit PhongIdShader();\n\n PhongIdShader& setObjectId(Int id) {\n setUniform(_objectIdUniform, id);\n return *this;\n }\n\n PhongIdShader& setLightPosition(const Vector3& position) {\n setUniform(_lightPositionUniform, position);\n return *this;\n }\n\n PhongIdShader& setAmbientColor(const Color3& color) {\n setUniform(_ambientColorUniform, color);\n return *this;\n }\n\n PhongIdShader& setColor(const Color3& color) {\n setUniform(_colorUniform, color);\n return *this;\n }\n\n PhongIdShader& setTransformationMatrix(const Matrix4& matrix) {\n setUniform(_transformationMatrixUniform, matrix);\n return *this;\n }\n\n PhongIdShader& setNormalMatrix(const Matrix3x3& matrix) {\n setUniform(_normalMatrixUniform, matrix);\n return *this;\n }\n\n PhongIdShader& setProjectionMatrix(const Matrix4& matrix) {\n setUniform(_projectionMatrixUniform, matrix);\n return *this;\n }\n\n private:\n Int _objectIdUniform,\n _lightPositionUniform,\n _ambientColorUniform,\n _colorUniform,\n _transformationMatrixUniform,\n _normalMatrixUniform,\n _projectionMatrixUniform;\n};\n\nPhongIdShader::PhongIdShader() {\n Utility::Resource rs(\"picking-data\");\n\n Shader vert{Version::GL330, Shader::Type::Vertex},\n frag{Version::GL330, Shader::Type::Fragment};\n vert.addSource(rs.get(\"PhongId.vert\"));\n frag.addSource(rs.get(\"PhongId.frag\"));\n CORRADE_INTERNAL_ASSERT(Shader::compile({vert, frag}));\n attachShaders({vert, frag});\n CORRADE_INTERNAL_ASSERT(link());\n\n _objectIdUniform = uniformLocation(\"objectId\");\n _lightPositionUniform = uniformLocation(\"light\");\n _ambientColorUniform = uniformLocation(\"ambientColor\");\n _colorUniform = uniformLocation(\"color\");\n _transformationMatrixUniform = uniformLocation(\"transformationMatrix\");\n _projectionMatrixUniform = uniformLocation(\"projectionMatrix\");\n _normalMatrixUniform = uniformLocation(\"normalMatrix\");\n}\n\nclass PickableObject: public Object3D, SceneGraph::Drawable3D {\n public:\n explicit PickableObject(UnsignedByte id, PhongIdShader& shader, const Color3& color, Mesh& mesh, Object3D& parent, SceneGraph::DrawableGroup3D& drawables): Object3D{&parent}, SceneGraph::Drawable3D{*this, &drawables}, _id{id}, _selected{false}, _shader(shader), _color{color}, _mesh(mesh) {}\n\n void setSelected(bool selected) { _selected = selected; }\n\n private:\n virtual void draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) {\n _shader.setTransformationMatrix(transformationMatrix)\n .setNormalMatrix(transformationMatrix.rotationScaling())\n .setProjectionMatrix(camera.projectionMatrix())\n .setAmbientColor(_selected ? _color*0.3f : Color3{})\n .setColor(_color*(_selected ? 2.0f : 1.0f))\n \/* relative to the camera *\/\n .setLightPosition({13.0f, 2.0f, 5.0f})\n .setObjectId(_id);\n _mesh.draw(_shader);\n }\n\n UnsignedByte _id;\n bool _selected;\n PhongIdShader& _shader;\n Color3 _color;\n Mesh& _mesh;\n};\n\nclass PickingExample: public Platform::Application {\n public:\n explicit PickingExample(const Arguments& arguments);\n\n private:\n void drawEvent() override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n void mouseReleaseEvent(MouseEvent& event) override;\n\n Scene3D _scene;\n Object3D* _cameraObject;\n SceneGraph::Camera3D* _camera;\n SceneGraph::DrawableGroup3D _drawables;\n\n PhongIdShader _shader;\n Buffer _cubeVertices, _cubeIndices,\n _sphereVertices, _sphereIndices,\n _planeVertices;\n Mesh _cube, _plane, _sphere;\n\n enum { ObjectCount = 6 };\n PickableObject* _objects[ObjectCount];\n\n Framebuffer _framebuffer;\n Renderbuffer _color, _objectId, _depth;\n\n Vector2i _previousMousePosition, _mousePressPosition;\n};\n\nPickingExample::PickingExample(const Arguments& arguments): Platform::Application{arguments, Configuration{}.setTitle(\"Magnum object picking example\")}, _framebuffer{defaultFramebuffer.viewport()} {\n MAGNUM_ASSERT_VERSION_SUPPORTED(Version::GL330);\n\n \/* Global renderer configuration *\/\n Renderer::enable(Renderer::Feature::DepthTest);\n\n \/* Configure framebuffer (using R8UI for object ID which means 255 objects max) *\/\n _color.setStorage(RenderbufferFormat::RGBA8, defaultFramebuffer.viewport().size());\n _objectId.setStorage(RenderbufferFormat::R8UI, defaultFramebuffer.viewport().size());\n _depth.setStorage(RenderbufferFormat::DepthComponent24, defaultFramebuffer.viewport().size());\n _framebuffer.attachRenderbuffer(Framebuffer::ColorAttachment{0}, _color)\n .attachRenderbuffer(Framebuffer::ColorAttachment{1}, _objectId)\n .attachRenderbuffer(Framebuffer::BufferAttachment::Depth, _depth)\n .mapForDraw({{PhongIdShader::ColorOutput, Framebuffer::ColorAttachment{0}},\n {PhongIdShader::ObjectIdOutput, Framebuffer::ColorAttachment{1}}});\n CORRADE_INTERNAL_ASSERT(_framebuffer.checkStatus(FramebufferTarget::Draw) == Framebuffer::Status::Complete);\n\n \/* Set up meshes *\/\n {\n Trade::MeshData3D data = Primitives::Cube::solid();\n _cubeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _cubeIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), BufferUsage::StaticDraw);\n _cube.setCount(data.indices().size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_cubeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{})\n .setIndexBuffer(_cubeIndices, 0, Mesh::IndexType::UnsignedShort);\n } {\n Trade::MeshData3D data = Primitives::UVSphere::solid(16, 32);\n _sphereVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _sphereIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), BufferUsage::StaticDraw);\n _sphere.setCount(data.indices().size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_sphereVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{})\n .setIndexBuffer(_sphereIndices, 0, Mesh::IndexType::UnsignedShort);\n } {\n Trade::MeshData3D data = Primitives::Plane::solid();\n _planeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), BufferUsage::StaticDraw);\n _plane.setCount(data.positions(0).size())\n .setPrimitive(data.primitive())\n .addVertexBuffer(_planeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{});\n }\n\n \/* Set up objects *\/\n (*(_objects[0] = new PickableObject{1, _shader, Color3::fromHSV(25.0_degf, 0.9f, 0.9f), _cube, _scene, _drawables}))\n .rotate(34.0_degf, Vector3(1.0f).normalized())\n .translate({1.0f, 0.3f, -1.2f});\n (*(_objects[1] = new PickableObject{2, _shader, Color3::fromHSV(54.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({-1.2f, -0.3f, -0.2f});\n (*(_objects[2] = new PickableObject{3, _shader, Color3::fromHSV(105.0_degf, 0.9f, 0.9f), _plane, _scene, _drawables}))\n .rotate(254.0_degf, Vector3(1.0f).normalized())\n .scale(Vector3(0.45f))\n .translate({0.5f, 1.3f, 1.5f});\n (*(_objects[3] = new PickableObject{4, _shader, Color3::fromHSV(162.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({-0.2f, -1.7f, -2.7f});\n (*(_objects[4] = new PickableObject{5, _shader, Color3::fromHSV(210.0_degf, 0.9f, 0.9f), _sphere, _scene, _drawables}))\n .translate({0.7f, 0.6f, 2.2f})\n .scale(Vector3(0.75f));\n (*(_objects[5] = new PickableObject{6, _shader, Color3::fromHSV(280.0_degf, 0.9f, 0.9f), _cube, _scene, _drawables}))\n .rotate(-92.0_degf, Vector3(1.0f).normalized())\n .scale(Vector3(0.25f))\n .translate({-0.5f, -0.3f, 1.8f});\n\n \/* Configure camera *\/\n _cameraObject = new Object3D{&_scene};\n _cameraObject->translate(Vector3::zAxis(8.0f));\n _camera = new SceneGraph::Camera3D{*_cameraObject};\n _camera->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)\n .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 4.0f\/3.0f, 0.001f, 100.0f))\n .setViewport(defaultFramebuffer.viewport().size());\n}\n\nvoid PickingExample::drawEvent() {\n \/* Draw to custom framebuffer *\/\n _framebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth)\n .bind();\n _camera->draw(_drawables);\n\n \/* Bind the main buffer back *\/\n defaultFramebuffer.bind();\n\n \/* Blit color to window framebuffer *\/\n _framebuffer.mapForRead(Framebuffer::ColorAttachment{0});\n AbstractFramebuffer::blit(_framebuffer, defaultFramebuffer,\n {{}, _framebuffer.viewport().size()}, FramebufferBlit::Color);\n\n swapBuffers();\n}\n\nvoid PickingExample::mousePressEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left) return;\n\n _previousMousePosition = _mousePressPosition = event.position();\n event.setAccepted();\n}\n\nvoid PickingExample::mouseMoveEvent(MouseMoveEvent& event) {\n if(!(event.buttons() & MouseMoveEvent::Button::Left)) return;\n\n const Vector2 delta = 3.0f*\n Vector2{event.position() - _previousMousePosition}\/\n Vector2{defaultFramebuffer.viewport().size()};\n\n (*_cameraObject)\n .rotate(Rad{-delta.y()}, _cameraObject->transformation().right().normalized())\n .rotateY(Rad{-delta.x()});\n\n _previousMousePosition = event.position();\n event.setAccepted();\n redraw();\n}\n\nvoid PickingExample::mouseReleaseEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left || _mousePressPosition != event.position()) return;\n\n \/* Read object ID at given click position (framebuffer has Y up while windowing system Y down) *\/\n _framebuffer.mapForRead(Framebuffer::ColorAttachment{1});\n Image2D data = _framebuffer.read(\n Range2Di::fromSize({event.position().x(), _framebuffer.viewport().sizeY() - event.position().y() - 1}, {1, 1}),\n {PixelFormat::RedInteger, PixelType::UnsignedByte});\n\n \/* Highlight object under mouse and deselect all other *\/\n for(auto* o: _objects) o->setSelected(false);\n UnsignedByte id = data.data<UnsignedByte>()[0];\n if(id > 0 && id < ObjectCount + 1)\n _objects[id - 1]->setSelected(true);\n\n event.setAccepted();\n redraw();\n}\n\nMAGNUM_APPLICATION_MAIN(PickingExample)\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n#include <planning_request_adapter\/planning_request_adapter.h>\n#include <planning_models\/conversions.h>\n#include <boost\/bind.hpp>\n\nnamespace planning_request_adapter\n{\nstatic bool callPlannerInterfaceSolve(const planning_interface::Planner *planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res)\n{\n return planner->solve(planning_scene, req, res);\n}\n}\n\nbool planning_request_adapter::PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index) const\n{\n return adaptAndPlan(boost::bind(&callPlannerInterfaceSolve, planner.get(), _1, _2, _3), planning_scene, req, res, added_path_index);\n}\n\nbool planning_request_adapter::PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res) const\n{\n std::vector<std::size_t> dummy;\n return adaptAndPlan(planner, planning_scene, req, res, dummy);\n}\n\nnamespace planning_request_adapter\n{\n\n\/\/ boost bind is not happy with overloading, so we add intermediate function objects\n\nstatic bool callAdapter1(const PlanningRequestAdapter *adapter,\n const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index)\n{\n return adapter->adaptAndPlan(planner, planning_scene, req, res, added_path_index);\n}\n\nstatic bool callAdapter2(const PlanningRequestAdapter *adapter,\n const PlannerFn &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index)\n{\n return adapter->adaptAndPlan(planner, planning_scene, req, res, added_path_index);\n}\n\n}\n\nbool planning_request_adapter::PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res) const\n{\n std::vector<std::size_t> dummy;\n return adaptAndPlan(planner, planning_scene, req, res, dummy);\n}\n\nbool planning_request_adapter::PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index) const\n{\n \/\/ if there are no adapters, run the planner directly \n if (adapters_.empty())\n {\n added_path_index.clear();\n return planner->solve(planning_scene, req, res);\n }\n else\n {\n \/\/ the index values added by each adapter\n std::vector<std::vector<std::size_t> > added_path_index_each(adapters_.size());\n \n \/\/ if there are adapters, construct a function pointer for each, in order,\n \/\/ so that in the end we have a nested sequence of function pointers that call the adapters in the correct order.\n PlannerFn fn = boost::bind(&callAdapter1, adapters_.back().get(), planner, _1, _2, _3, boost::ref(added_path_index_each.back()));\n for (int i = adapters_.size() - 2 ; i >= 0 ; --i)\n fn = boost::bind(&callAdapter2, adapters_[i].get(), fn, _1, _2, _3, boost::ref(added_path_index_each[i]));\n bool result = fn(planning_scene, req, res);\n added_path_index.clear();\n \n \/\/ merge the index values from each adapter\n for (std::size_t i = 0 ; i < added_path_index_each.size() ; ++i)\n for (std::size_t j = 0 ; j < added_path_index_each[i].size() ; ++j)\n {\n for (std::size_t k = 0 ; k < added_path_index.size() ; ++k)\n if (added_path_index_each[i][j] <= added_path_index[k])\n added_path_index[k]++;\n added_path_index.push_back(added_path_index_each[i][j]);\n }\n \n return result;\n }\n}\n<commit_msg>sorting the reported index values<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n#include <planning_request_adapter\/planning_request_adapter.h>\n#include <planning_models\/conversions.h>\n#include <boost\/bind.hpp>\n#include <algorithm>\n\nnamespace planning_request_adapter\n{\nstatic bool callPlannerInterfaceSolve(const planning_interface::Planner *planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res)\n{\n return planner->solve(planning_scene, req, res);\n}\n}\n\nbool planning_request_adapter::PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index) const\n{\n return adaptAndPlan(boost::bind(&callPlannerInterfaceSolve, planner.get(), _1, _2, _3), planning_scene, req, res, added_path_index);\n}\n\nbool planning_request_adapter::PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res) const\n{\n std::vector<std::size_t> dummy;\n return adaptAndPlan(planner, planning_scene, req, res, dummy);\n}\n\nnamespace planning_request_adapter\n{\n\n\/\/ boost bind is not happy with overloading, so we add intermediate function objects\n\nstatic bool callAdapter1(const PlanningRequestAdapter *adapter,\n const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index)\n{\n return adapter->adaptAndPlan(planner, planning_scene, req, res, added_path_index);\n}\n\nstatic bool callAdapter2(const PlanningRequestAdapter *adapter,\n const PlannerFn &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index)\n{\n return adapter->adaptAndPlan(planner, planning_scene, req, res, added_path_index);\n}\n\n}\n\nbool planning_request_adapter::PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res) const\n{\n std::vector<std::size_t> dummy;\n return adaptAndPlan(planner, planning_scene, req, res, dummy);\n}\n\nbool planning_request_adapter::PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerPtr &planner,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::GetMotionPlan::Request &req, \n moveit_msgs::GetMotionPlan::Response &res,\n std::vector<std::size_t> &added_path_index) const\n{\n \/\/ if there are no adapters, run the planner directly \n if (adapters_.empty())\n {\n added_path_index.clear();\n return planner->solve(planning_scene, req, res);\n }\n else\n {\n \/\/ the index values added by each adapter\n std::vector<std::vector<std::size_t> > added_path_index_each(adapters_.size());\n \n \/\/ if there are adapters, construct a function pointer for each, in order,\n \/\/ so that in the end we have a nested sequence of function pointers that call the adapters in the correct order.\n PlannerFn fn = boost::bind(&callAdapter1, adapters_.back().get(), planner, _1, _2, _3, boost::ref(added_path_index_each.back()));\n for (int i = adapters_.size() - 2 ; i >= 0 ; --i)\n fn = boost::bind(&callAdapter2, adapters_[i].get(), fn, _1, _2, _3, boost::ref(added_path_index_each[i]));\n bool result = fn(planning_scene, req, res);\n added_path_index.clear();\n \n \/\/ merge the index values from each adapter\n for (std::size_t i = 0 ; i < added_path_index_each.size() ; ++i)\n for (std::size_t j = 0 ; j < added_path_index_each[i].size() ; ++j)\n {\n for (std::size_t k = 0 ; k < added_path_index.size() ; ++k)\n if (added_path_index_each[i][j] <= added_path_index[k])\n added_path_index[k]++;\n added_path_index.push_back(added_path_index_each[i][j]);\n }\n std::sort(added_path_index.begin(), added_path_index.end());\n return result;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * =====================================================================================\n *\n * Filename: 1.cpp\n *\n * Description: Solution to the first problem of the `all' section.\n *\n * Version: 1.0\n * Created: 27.01.2015 19,21,01\n * Revision: none\n * Compiler: gcc\n *\n * Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com\n * Company: Faculty of Mathematics and Informatics at Sofia University\n *\n * =====================================================================================\n *\/\n\n#include <iostream>\nusing namespace std;\n\nint fact(int n)\n{\n int P = 1;\n\n for (int i = 2; i <= n; i++)\n P *= i;\n\n return P;\n}\n\nbool areEqual(int n, int m)\n{\n double S = 0;\n\n for (int i = 1; i <= n; i++)\n {\n int P = 1;\n\n for (int j = i; j <= i + m; j++)\n P *= j;\n\n S += 1 \/ (double) P;\n }\n\n int P = 1;\n\n for (int i = n + 1; i <= n + m; i++)\n P *= i;\n\n return S == 1 \/ (double) m * (1 \/ (double) fact(m) - 1 \/ (double) P);\n}\n\nbool areEqualForAll(int a, int b)\n{\n for (int i = 1; i <= a; i++)\n for (int j = 1; j <= b; j++)\n if (!areEqual(i, j))\n return false;\n\n return true;\n}\n\nint main()\n{\n int n, m;\n\n cin >> n >> m;\n cout << (areEqualForAll(n, m) ? \"Yes\" : \"No\");\n\n return 0;\n}\n \n<commit_msg>changed doubles comparison method to is-absolute-difference-less-than-epsilon<commit_after>\/*\n * =====================================================================================\n *\n * Filename: 1.cpp\n *\n * Description: Solution to the first problem of the `all' section.\n *\n * Version: 1.0\n * Created: 27.01.2015 19,21,01\n * Revision: none\n * Compiler: gcc\n *\n * Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com\n * Company: Faculty of Mathematics and Informatics at Sofia University\n *\n * =====================================================================================\n *\/\n\n#include <iostream>\nusing namespace std;\n\nconst double EPS = 0.001;\n\nint fact(int n)\n{\n int P = 1;\n\n for (int i = 2; i <= n; i++)\n P *= i;\n\n return P;\n}\n\nbool eq(double a, double b)\n{\n return a - b > -EPS && a - b < EPS;\n}\n\nbool areEqual(int n, int m)\n{\n double S = 0;\n\n for (int i = 1; i <= n; i++)\n {\n int P = 1;\n\n for (int j = i; j <= i + m; j++)\n P *= j;\n\n S += 1 \/ (double) P;\n }\n\n int P = 1;\n\n for (int i = n + 1; i <= n + m; i++)\n P *= i;\n\n return eq(S, 1 \/ (double) m * (1 \/ (double) fact(m) - 1 \/ (double) P));\n}\n\nbool areEqualForAll(int a, int b)\n{\n for (int i = 1; i <= a; i++)\n for (int j = 1; j <= b; j++)\n if (!areEqual(i, j))\n return false;\n\n return true;\n}\n\nint main()\n{\n int n, m;\n\n cin >> n >> m;\n cout << (areEqualForAll(n, m) ? \"Yes\" : \"No\");\n\n return 0;\n}\n \n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ file : hydra_logo.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/hydra\/hydra\/hydra_logo.hpp\n\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: Fri Sep 02 2016 19:41:28 GMT+0200 (CEST)\n\/\/\n\/\/\n\/\/ Copyright (c) 2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n#define __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n\n#include <cstdint> \/\/ uint*\n#include <cstddef> \/\/ size_t\n#include <cstring> \/\/ memset\n\nnamespace neam\n{\n namespace hydra\n {\n \/\/\/ \\brief Generate the RGBA logo of hydra\n \/\/\/ \\param[out] pixels Where the image will be written. Must have a size of at least icon_sz * icon_sz * 4\n \/\/\/ \\param icon_sz The size of the image. Must be a power of 2 and greater than 16.\n \/\/\/ \\param glyph_count The number of glyph the image will have (must be lower than 5 and lower than 4 if icon_sz is 16)\n static uint8_t *generate_rgba_logo(uint8_t *pixels, size_t icon_sz = 256, size_t glyph_count = 4)\n {\n const uint8_t hydra_logo[] = {0x7D, 0x3D, 0xEB, 0x5F, 0x7B};\n\n if (icon_sz < 16) return pixels; \/\/ not possible\n if (glyph_count < 1 || glyph_count > sizeof(hydra_logo)) glyph_count = 4;\n if (icon_sz == 16 && glyph_count > 4) glyph_count = 4;\n\n const size_t sq_sz = icon_sz \/ (glyph_count * 4) ;\n const size_t y_pos = (glyph_count == 1 ? (sq_sz \/ 2) : (icon_sz \/ 2 - (sq_sz \/ 2 + 1)));\n const size_t x_pos = sq_sz \/ 2;\n memset(pixels, 0, icon_sz * icon_sz * 4);\n\n for (size_t i = 0; i < glyph_count; ++i)\n {\n for (size_t y = 0; y < sq_sz; ++y)\n {\n for (size_t x = 0; x < sq_sz; ++x)\n {\n size_t bidx = (y_pos + y) * icon_sz * 4 + (x_pos + x + 4 * sq_sz * i) * 4;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x01 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x02 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x04 ? 255 : 0;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x08 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x10 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x20 ? 255 : 0;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x40 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x80 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = 255;\n }\n }\n }\n return pixels;\n }\n } \/\/ namespace hydra\n} \/\/ namespace neam\n\n#endif \/\/ __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n\n<commit_msg>Add support for coloring the logo<commit_after>\/\/\n\/\/ file : hydra_logo.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/hydra\/hydra\/hydra_logo.hpp\n\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: Fri Sep 02 2016 19:41:28 GMT+0200 (CEST)\n\/\/\n\/\/\n\/\/ Copyright (c) 2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n#define __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n\n#include <cstdint> \/\/ uint*\n#include <cstddef> \/\/ size_t\n#include <cstring> \/\/ memset\n\nnamespace neam\n{\n namespace hydra\n {\n \/\/\/ \\brief Generate the RGBA logo of hydra\n \/\/\/ \\param[out] pixels Where the image will be written. Must have a size of at least icon_sz * icon_sz * 4\n \/\/\/ \\param icon_sz The size of the image. Must be a power of 2 and greater than 16.\n \/\/\/ \\param glyph_count The number of glyph the image will have (must be lower than 5 and lower than 4 if icon_sz is 16)\n static uint8_t* generate_rgba_logo(uint8_t* pixels, size_t icon_sz = 256, size_t glyph_count = 4, uint32_t color = 0)\n {\n const uint8_t hydra_logo[] = {0x7D, 0x3D, 0xEB, 0x5F, 0x7B};\n\n if (icon_sz < 16) return pixels; \/\/ not possible\n if (glyph_count < 1 || glyph_count > sizeof(hydra_logo)) glyph_count = 4;\n if (icon_sz == 16 && glyph_count > 4) glyph_count = 4;\n\n const size_t sq_sz = icon_sz \/ (glyph_count * 4) ;\n const size_t y_pos = (glyph_count == 1 ? (sq_sz \/ 2) : (icon_sz \/ 2 - (sq_sz \/ 2 + 1)));\n const size_t x_pos = sq_sz \/ 2;\n color = color & 0x00FFFFFF;\n if (!color)\n {\n memset(pixels, 0, icon_sz * icon_sz * 4);\n }\n else\n {\n uint32_t* upixels = (uint32_t*)pixels;\n for (uint32_t i = 0; i < icon_sz * icon_sz; ++i)\n {\n upixels[i] = color;\n }\n }\n\n for (size_t i = 0; i < glyph_count; ++i)\n {\n for (size_t y = 0; y < sq_sz; ++y)\n {\n for (size_t x = 0; x < sq_sz; ++x)\n {\n size_t bidx = (y_pos + y) * icon_sz * 4 + (x_pos + x + 4 * sq_sz * i) * 4;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x01 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x02 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 0 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x04 ? 255 : 0;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x08 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x10 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 1 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x20 ? 255 : 0;\n pixels[bidx + 3 + 0 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x40 ? 255 : 0;\n pixels[bidx + 3 + 1 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = hydra_logo[i] & 0x80 ? 255 : 0;\n pixels[bidx + 3 + 2 * sq_sz * 4 + 2 * icon_sz * sq_sz * 4] = 255;\n }\n }\n }\n return pixels;\n }\n } \/\/ namespace hydra\n} \/\/ namespace neam\n\n#endif \/\/ __N_200324051639512063_182864571_HYDRA_LOGO_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"loadcoredialog.h\"\n\n#include \"debuggerconstants.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstartparameters.h\"\n#include \"debuggerdialogs.h\"\n\n#include <coreplugin\/icore.h>\n#include <projectexplorer\/abi.h>\n#include <projectexplorer\/kitchooser.h>\n#include <projectexplorer\/kitinformation.h>\n#include <ssh\/sshconnection.h>\n#include <ssh\/sshremoteprocessrunner.h>\n#include <ssh\/sftpdefs.h>\n#include <ssh\/sftpfilesystemmodel.h>\n#include <utils\/historycompleter.h>\n#include <utils\/pathchooser.h>\n#include <utils\/qtcassert.h>\n\n#include <QCoreApplication>\n#include <QDebug>\n#include <QDir>\n#include <QRegExp>\n#include <QTemporaryFile>\n\n#include <QButtonGroup>\n#include <QComboBox>\n#include <QDialogButtonBox>\n#include <QFileDialog>\n#include <QFormLayout>\n#include <QGridLayout>\n#include <QGroupBox>\n#include <QHeaderView>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QRadioButton>\n#include <QScrollArea>\n#include <QSortFilterProxyModel>\n#include <QStandardItemModel>\n#include <QTableView>\n#include <QTextBrowser>\n#include <QTreeView>\n#include <QVBoxLayout>\n\nusing namespace Core;\nusing namespace ProjectExplorer;\nusing namespace QSsh;\nusing namespace Utils;\n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SelectRemoteFileDialog\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SelectRemoteFileDialog : public QDialog\n{\n Q_OBJECT\n\npublic:\n explicit SelectRemoteFileDialog(QWidget *parent);\n\n void attachToDevice(Kit *k);\n QString localFile() const { return m_localFile; }\n QString remoteFile() const { return m_remoteFile; }\n\nprivate slots:\n void handleSftpOperationFinished(QSsh::SftpJobId, const QString &error);\n void handleSftpOperationFailed(const QString &errorMessage);\n void handleConnectionError(const QString &errorMessage);\n void handleRemoteError(const QString &errorMessage);\n void selectFile();\n\nprivate:\n QSortFilterProxyModel m_model;\n SftpFileSystemModel m_fileSystemModel;\n QTreeView *m_fileSystemView;\n QTextBrowser *m_textBrowser;\n QDialogButtonBox *m_buttonBox;\n QString m_localFile;\n QString m_remoteFile;\n SftpJobId m_sftpJobId;\n};\n\nSelectRemoteFileDialog::SelectRemoteFileDialog(QWidget *parent)\n : QDialog(parent)\n{\n m_model.setSourceModel(&m_fileSystemModel);\n\n m_fileSystemView = new QTreeView(this);\n m_fileSystemView->setModel(&m_model);\n m_fileSystemView->setSortingEnabled(true);\n m_fileSystemView->setUniformRowHeights(true);\n m_fileSystemView->setSelectionMode(QAbstractItemView::SingleSelection);\n m_fileSystemView->setSelectionBehavior(QAbstractItemView::SelectRows);\n m_fileSystemView->header()->setDefaultSectionSize(100);\n m_fileSystemView->header()->setStretchLastSection(true);\n\n m_textBrowser = new QTextBrowser(this);\n m_textBrowser->setEnabled(false);\n\n m_buttonBox = new QDialogButtonBox(this);\n m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n m_buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->addWidget(m_fileSystemView);\n layout->addWidget(m_textBrowser);\n layout->addWidget(m_buttonBox);\n\n QObject::connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));\n QObject::connect(m_buttonBox, SIGNAL(accepted()), SLOT(selectFile()));\n\n connect(&m_fileSystemModel, SIGNAL(sftpOperationFailed(QString)),\n SLOT(handleSftpOperationFailed(QString)));\n connect(&m_fileSystemModel, SIGNAL(connectionError(QString)),\n SLOT(handleConnectionError(QString)));\n}\n\nvoid SelectRemoteFileDialog::attachToDevice(Kit *k)\n{\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);\n QTC_ASSERT(k, return);\n IDevice::ConstPtr device = DeviceKitInformation::device(k);\n QTC_ASSERT(device, return);\n QSsh::SshConnectionParameters sshParams = device->sshParameters();\n m_fileSystemModel.setSshConnection(sshParams);\n}\n\nvoid SelectRemoteFileDialog::handleSftpOperationFailed(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n \/\/reject();\n}\n\nvoid SelectRemoteFileDialog::handleConnectionError(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n \/\/reject();\n}\n\nvoid SelectRemoteFileDialog::handleSftpOperationFinished(QSsh::SftpJobId, const QString &error)\n{\n if (error.isEmpty()) {\n m_textBrowser->append(tr(\"Download of remote file succeeded.\"));\n accept();\n } else {\n m_textBrowser->append(error);\n \/\/reject();\n }\n}\n\nvoid SelectRemoteFileDialog::handleRemoteError(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n}\n\nvoid SelectRemoteFileDialog::selectFile()\n{\n QModelIndex idx = m_model.mapToSource(m_fileSystemView->currentIndex());\n if (!idx.isValid())\n return;\n\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n m_fileSystemView->setEnabled(false);\n\n connect(&m_fileSystemModel, SIGNAL(sftpOperationFinished(QSsh::SftpJobId,QString)),\n SLOT(handleSftpOperationFinished(QSsh::SftpJobId,QString)));\n\n {\n QTemporaryFile localFile(QDir::tempPath() + QLatin1String(\"\/remotecore-XXXXXX\"));\n localFile.open();\n m_localFile = localFile.fileName();\n }\n\n idx = idx.sibling(idx.row(), 1);\n m_remoteFile = m_fileSystemModel.data(idx, SftpFileSystemModel::PathRole).toString();\n m_sftpJobId = m_fileSystemModel.downloadFile(idx, m_localFile);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AttachCoreDialog\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass AttachCoreDialogPrivate\n{\npublic:\n KitChooser *kitChooser;\n\n QSettings *settings;\n\n PathChooser *localExecFileName;\n PathChooser *localCoreFileName;\n QLineEdit *remoteCoreFileName;\n QPushButton *selectRemoteCoreButton;\n\n PathChooser *overrideStartScriptFileName;\n\n QDialogButtonBox *buttonBox;\n};\n\nAttachCoreDialog::AttachCoreDialog(QWidget *parent)\n : QDialog(parent), d(new AttachCoreDialogPrivate)\n{\n setWindowTitle(tr(\"Load Core File\"));\n setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n\n d->settings = ICore::settings();\n\n d->kitChooser = new DebuggerKitChooser(DebuggerKitChooser::RemoteDebugging, this);\n d->kitChooser->populate();\n\n d->selectRemoteCoreButton = new QPushButton(tr(\"Browse...\"), this);\n d->remoteCoreFileName = new QLineEdit(this);\n d->remoteCoreFileName->setEnabled(false);\n\n d->localCoreFileName = new PathChooser(this);\n d->localCoreFileName->setExpectedKind(PathChooser::File);\n d->localCoreFileName->setPromptDialogTitle(tr(\"Select Core File\"));\n\n d->localExecFileName = new PathChooser(this);\n d->localExecFileName->setExpectedKind(PathChooser::File);\n d->localExecFileName->setPromptDialogTitle(tr(\"Select Executable\"));\n\n d->overrideStartScriptFileName = new PathChooser(this);\n d->overrideStartScriptFileName->setExpectedKind(PathChooser::File);\n d->overrideStartScriptFileName->setPromptDialogTitle(tr(\"Select Startup Script\"));\n\n d->buttonBox = new QDialogButtonBox(this);\n d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n d->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n\n QHBoxLayout *coreLayout = new QHBoxLayout;\n coreLayout->addWidget(d->localCoreFileName);\n coreLayout->addWidget(d->remoteCoreFileName);\n coreLayout->addWidget(d->selectRemoteCoreButton);\n\n QFormLayout *formLayout = new QFormLayout;\n formLayout->setContentsMargins(0, 0, 0, 0);\n formLayout->setHorizontalSpacing(6);\n formLayout->setVerticalSpacing(6);\n formLayout->addRow(tr(\"Kit:\"), d->kitChooser);\n formLayout->addRow(tr(\"&Executable:\"), d->localExecFileName);\n formLayout->addRow(tr(\"Core file:\"), coreLayout);\n formLayout->addRow(tr(\"Override &start script:\"), d->overrideStartScriptFileName);\n\n QFrame *line = new QFrame(this);\n line->setFrameShape(QFrame::HLine);\n line->setFrameShadow(QFrame::Sunken);\n\n formLayout->addRow(d->buttonBox);\n\n QVBoxLayout *vboxLayout = new QVBoxLayout(this);\n vboxLayout->addLayout(formLayout);\n vboxLayout->addStretch();\n vboxLayout->addWidget(line);\n vboxLayout->addWidget(d->buttonBox);\n\n connect(d->selectRemoteCoreButton, SIGNAL(clicked()), SLOT(selectRemoteCoreFile()));\n connect(d->remoteCoreFileName, SIGNAL(textChanged(QString)), SLOT(changed()));\n connect(d->localCoreFileName, SIGNAL(changed(QString)), SLOT(changed()));\n connect(d->kitChooser, SIGNAL(activated(int)), SLOT(changed()));\n connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));\n connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));\n changed();\n}\n\nAttachCoreDialog::~AttachCoreDialog()\n{\n delete d;\n}\n\nbool AttachCoreDialog::isLocal() const\n{\n Kit *k = d->kitChooser->currentKit();\n QTC_ASSERT(k, return false);\n IDevice::ConstPtr device = DeviceKitInformation::device(k);\n QTC_ASSERT(device, return false);\n SshConnectionParameters sshParams = device->sshParameters();\n d->settings->setValue(QLatin1String(\"LastProfile\"),\n d->kitChooser->currentKitId().toString());\n return sshParams.host.isEmpty();\n}\n\nvoid AttachCoreDialog::changed()\n{\n bool isValid = d->kitChooser->currentIndex() >= 0 && d->localExecFileName->isValid();\n\n if (isLocal()) {\n d->localCoreFileName->setVisible(true);\n d->remoteCoreFileName->setVisible(false);\n d->selectRemoteCoreButton->setVisible(false);\n if (isValid)\n isValid = d->localCoreFileName->isValid();\n } else {\n d->remoteCoreFileName->setVisible(true);\n d->selectRemoteCoreButton->setVisible(true);\n d->localCoreFileName->setVisible(false);\n if (isValid)\n isValid = !remoteCoreFile().isEmpty();\n }\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(isValid);\n}\n\nvoid AttachCoreDialog::selectRemoteCoreFile()\n{\n changed();\n QTC_ASSERT(!isLocal(), return);\n SelectRemoteFileDialog dlg(this);\n dlg.setWindowTitle(tr(\"Select Remote Core File\"));\n dlg.attachToDevice(d->kitChooser->currentKit());\n if (dlg.exec() == QDialog::Rejected)\n return;\n d->localCoreFileName->setPath(dlg.localFile());\n d->remoteCoreFileName->setText(dlg.remoteFile());\n changed();\n}\n\nQString AttachCoreDialog::localCoreFile() const\n{\n return d->localCoreFileName->path();\n}\n\nQString AttachCoreDialog::localExecutableFile() const\n{\n return d->localExecFileName->path();\n}\n\nvoid AttachCoreDialog::setLocalExecutableFile(const QString &fileName)\n{\n d->localExecFileName->setPath(fileName);\n}\n\nvoid AttachCoreDialog::setLocalCoreFile(const QString &fileName)\n{\n d->localCoreFileName->setPath(fileName);\n}\n\nvoid AttachCoreDialog::setRemoteCoreFile(const QString &fileName)\n{\n d->remoteCoreFileName->setText(fileName);\n}\n\nQString AttachCoreDialog::remoteCoreFile() const\n{\n return d->remoteCoreFileName->text();\n}\n\nvoid AttachCoreDialog::setKitId(const Core::Id &id)\n{\n d->kitChooser->setCurrentKitId(id);\n changed();\n}\n\nKit *AttachCoreDialog::kit() const\n{\n return d->kitChooser->currentKit();\n}\n\nQString AttachCoreDialog::overrideStartScript() const\n{\n return d->overrideStartScriptFileName->path();\n}\n\nvoid AttachCoreDialog::setOverrideStartScript(const QString &scriptName)\n{\n d->overrideStartScriptFileName->setPath(scriptName);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n\n#include \"loadcoredialog.moc\"\n<commit_msg>Attach to Core: Sort by file name<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"loadcoredialog.h\"\n\n#include \"debuggerconstants.h\"\n#include \"debuggercore.h\"\n#include \"debuggerstartparameters.h\"\n#include \"debuggerdialogs.h\"\n\n#include <coreplugin\/icore.h>\n#include <projectexplorer\/abi.h>\n#include <projectexplorer\/kitchooser.h>\n#include <projectexplorer\/kitinformation.h>\n#include <ssh\/sshconnection.h>\n#include <ssh\/sshremoteprocessrunner.h>\n#include <ssh\/sftpdefs.h>\n#include <ssh\/sftpfilesystemmodel.h>\n#include <utils\/historycompleter.h>\n#include <utils\/pathchooser.h>\n#include <utils\/qtcassert.h>\n\n#include <QCoreApplication>\n#include <QDebug>\n#include <QDir>\n#include <QRegExp>\n#include <QTemporaryFile>\n\n#include <QButtonGroup>\n#include <QComboBox>\n#include <QDialogButtonBox>\n#include <QFileDialog>\n#include <QFormLayout>\n#include <QGridLayout>\n#include <QGroupBox>\n#include <QHeaderView>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QRadioButton>\n#include <QScrollArea>\n#include <QSortFilterProxyModel>\n#include <QStandardItemModel>\n#include <QTableView>\n#include <QTextBrowser>\n#include <QTreeView>\n#include <QVBoxLayout>\n\nusing namespace Core;\nusing namespace ProjectExplorer;\nusing namespace QSsh;\nusing namespace Utils;\n\nnamespace Debugger {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SelectRemoteFileDialog\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SelectRemoteFileDialog : public QDialog\n{\n Q_OBJECT\n\npublic:\n explicit SelectRemoteFileDialog(QWidget *parent);\n\n void attachToDevice(Kit *k);\n QString localFile() const { return m_localFile; }\n QString remoteFile() const { return m_remoteFile; }\n\nprivate slots:\n void handleSftpOperationFinished(QSsh::SftpJobId, const QString &error);\n void handleSftpOperationFailed(const QString &errorMessage);\n void handleConnectionError(const QString &errorMessage);\n void handleRemoteError(const QString &errorMessage);\n void selectFile();\n\nprivate:\n QSortFilterProxyModel m_model;\n SftpFileSystemModel m_fileSystemModel;\n QTreeView *m_fileSystemView;\n QTextBrowser *m_textBrowser;\n QDialogButtonBox *m_buttonBox;\n QString m_localFile;\n QString m_remoteFile;\n SftpJobId m_sftpJobId;\n};\n\nSelectRemoteFileDialog::SelectRemoteFileDialog(QWidget *parent)\n : QDialog(parent)\n{\n m_model.setSourceModel(&m_fileSystemModel);\n\n m_fileSystemView = new QTreeView(this);\n m_fileSystemView->setModel(&m_model);\n m_fileSystemView->setSortingEnabled(true);\n m_fileSystemView->sortByColumn(1, Qt::AscendingOrder);\n m_fileSystemView->setUniformRowHeights(true);\n m_fileSystemView->setSelectionMode(QAbstractItemView::SingleSelection);\n m_fileSystemView->setSelectionBehavior(QAbstractItemView::SelectRows);\n m_fileSystemView->header()->setDefaultSectionSize(100);\n m_fileSystemView->header()->setStretchLastSection(true);\n\n m_textBrowser = new QTextBrowser(this);\n m_textBrowser->setEnabled(false);\n\n m_buttonBox = new QDialogButtonBox(this);\n m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n m_buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->addWidget(m_fileSystemView);\n layout->addWidget(m_textBrowser);\n layout->addWidget(m_buttonBox);\n\n QObject::connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));\n QObject::connect(m_buttonBox, SIGNAL(accepted()), SLOT(selectFile()));\n\n connect(&m_fileSystemModel, SIGNAL(sftpOperationFailed(QString)),\n SLOT(handleSftpOperationFailed(QString)));\n connect(&m_fileSystemModel, SIGNAL(connectionError(QString)),\n SLOT(handleConnectionError(QString)));\n}\n\nvoid SelectRemoteFileDialog::attachToDevice(Kit *k)\n{\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);\n QTC_ASSERT(k, return);\n IDevice::ConstPtr device = DeviceKitInformation::device(k);\n QTC_ASSERT(device, return);\n QSsh::SshConnectionParameters sshParams = device->sshParameters();\n m_fileSystemModel.setSshConnection(sshParams);\n}\n\nvoid SelectRemoteFileDialog::handleSftpOperationFailed(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n \/\/reject();\n}\n\nvoid SelectRemoteFileDialog::handleConnectionError(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n \/\/reject();\n}\n\nvoid SelectRemoteFileDialog::handleSftpOperationFinished(QSsh::SftpJobId, const QString &error)\n{\n if (error.isEmpty()) {\n m_textBrowser->append(tr(\"Download of remote file succeeded.\"));\n accept();\n } else {\n m_textBrowser->append(error);\n \/\/reject();\n }\n}\n\nvoid SelectRemoteFileDialog::handleRemoteError(const QString &errorMessage)\n{\n m_textBrowser->append(errorMessage);\n}\n\nvoid SelectRemoteFileDialog::selectFile()\n{\n QModelIndex idx = m_model.mapToSource(m_fileSystemView->currentIndex());\n if (!idx.isValid())\n return;\n\n m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n m_fileSystemView->setEnabled(false);\n\n connect(&m_fileSystemModel, SIGNAL(sftpOperationFinished(QSsh::SftpJobId,QString)),\n SLOT(handleSftpOperationFinished(QSsh::SftpJobId,QString)));\n\n {\n QTemporaryFile localFile(QDir::tempPath() + QLatin1String(\"\/remotecore-XXXXXX\"));\n localFile.open();\n m_localFile = localFile.fileName();\n }\n\n idx = idx.sibling(idx.row(), 1);\n m_remoteFile = m_fileSystemModel.data(idx, SftpFileSystemModel::PathRole).toString();\n m_sftpJobId = m_fileSystemModel.downloadFile(idx, m_localFile);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AttachCoreDialog\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass AttachCoreDialogPrivate\n{\npublic:\n KitChooser *kitChooser;\n\n QSettings *settings;\n\n PathChooser *localExecFileName;\n PathChooser *localCoreFileName;\n QLineEdit *remoteCoreFileName;\n QPushButton *selectRemoteCoreButton;\n\n PathChooser *overrideStartScriptFileName;\n\n QDialogButtonBox *buttonBox;\n};\n\nAttachCoreDialog::AttachCoreDialog(QWidget *parent)\n : QDialog(parent), d(new AttachCoreDialogPrivate)\n{\n setWindowTitle(tr(\"Load Core File\"));\n setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n\n d->settings = ICore::settings();\n\n d->kitChooser = new DebuggerKitChooser(DebuggerKitChooser::RemoteDebugging, this);\n d->kitChooser->populate();\n\n d->selectRemoteCoreButton = new QPushButton(tr(\"Browse...\"), this);\n d->remoteCoreFileName = new QLineEdit(this);\n d->remoteCoreFileName->setEnabled(false);\n\n d->localCoreFileName = new PathChooser(this);\n d->localCoreFileName->setExpectedKind(PathChooser::File);\n d->localCoreFileName->setPromptDialogTitle(tr(\"Select Core File\"));\n\n d->localExecFileName = new PathChooser(this);\n d->localExecFileName->setExpectedKind(PathChooser::File);\n d->localExecFileName->setPromptDialogTitle(tr(\"Select Executable\"));\n\n d->overrideStartScriptFileName = new PathChooser(this);\n d->overrideStartScriptFileName->setExpectedKind(PathChooser::File);\n d->overrideStartScriptFileName->setPromptDialogTitle(tr(\"Select Startup Script\"));\n\n d->buttonBox = new QDialogButtonBox(this);\n d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);\n d->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n\n QHBoxLayout *coreLayout = new QHBoxLayout;\n coreLayout->addWidget(d->localCoreFileName);\n coreLayout->addWidget(d->remoteCoreFileName);\n coreLayout->addWidget(d->selectRemoteCoreButton);\n\n QFormLayout *formLayout = new QFormLayout;\n formLayout->setContentsMargins(0, 0, 0, 0);\n formLayout->setHorizontalSpacing(6);\n formLayout->setVerticalSpacing(6);\n formLayout->addRow(tr(\"Kit:\"), d->kitChooser);\n formLayout->addRow(tr(\"&Executable:\"), d->localExecFileName);\n formLayout->addRow(tr(\"Core file:\"), coreLayout);\n formLayout->addRow(tr(\"Override &start script:\"), d->overrideStartScriptFileName);\n\n QFrame *line = new QFrame(this);\n line->setFrameShape(QFrame::HLine);\n line->setFrameShadow(QFrame::Sunken);\n\n formLayout->addRow(d->buttonBox);\n\n QVBoxLayout *vboxLayout = new QVBoxLayout(this);\n vboxLayout->addLayout(formLayout);\n vboxLayout->addStretch();\n vboxLayout->addWidget(line);\n vboxLayout->addWidget(d->buttonBox);\n\n connect(d->selectRemoteCoreButton, SIGNAL(clicked()), SLOT(selectRemoteCoreFile()));\n connect(d->remoteCoreFileName, SIGNAL(textChanged(QString)), SLOT(changed()));\n connect(d->localCoreFileName, SIGNAL(changed(QString)), SLOT(changed()));\n connect(d->kitChooser, SIGNAL(activated(int)), SLOT(changed()));\n connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));\n connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));\n changed();\n}\n\nAttachCoreDialog::~AttachCoreDialog()\n{\n delete d;\n}\n\nbool AttachCoreDialog::isLocal() const\n{\n Kit *k = d->kitChooser->currentKit();\n QTC_ASSERT(k, return false);\n IDevice::ConstPtr device = DeviceKitInformation::device(k);\n QTC_ASSERT(device, return false);\n SshConnectionParameters sshParams = device->sshParameters();\n d->settings->setValue(QLatin1String(\"LastProfile\"),\n d->kitChooser->currentKitId().toString());\n return sshParams.host.isEmpty();\n}\n\nvoid AttachCoreDialog::changed()\n{\n bool isValid = d->kitChooser->currentIndex() >= 0 && d->localExecFileName->isValid();\n\n if (isLocal()) {\n d->localCoreFileName->setVisible(true);\n d->remoteCoreFileName->setVisible(false);\n d->selectRemoteCoreButton->setVisible(false);\n if (isValid)\n isValid = d->localCoreFileName->isValid();\n } else {\n d->remoteCoreFileName->setVisible(true);\n d->selectRemoteCoreButton->setVisible(true);\n d->localCoreFileName->setVisible(false);\n if (isValid)\n isValid = !remoteCoreFile().isEmpty();\n }\n d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(isValid);\n}\n\nvoid AttachCoreDialog::selectRemoteCoreFile()\n{\n changed();\n QTC_ASSERT(!isLocal(), return);\n SelectRemoteFileDialog dlg(this);\n dlg.setWindowTitle(tr(\"Select Remote Core File\"));\n dlg.attachToDevice(d->kitChooser->currentKit());\n if (dlg.exec() == QDialog::Rejected)\n return;\n d->localCoreFileName->setPath(dlg.localFile());\n d->remoteCoreFileName->setText(dlg.remoteFile());\n changed();\n}\n\nQString AttachCoreDialog::localCoreFile() const\n{\n return d->localCoreFileName->path();\n}\n\nQString AttachCoreDialog::localExecutableFile() const\n{\n return d->localExecFileName->path();\n}\n\nvoid AttachCoreDialog::setLocalExecutableFile(const QString &fileName)\n{\n d->localExecFileName->setPath(fileName);\n}\n\nvoid AttachCoreDialog::setLocalCoreFile(const QString &fileName)\n{\n d->localCoreFileName->setPath(fileName);\n}\n\nvoid AttachCoreDialog::setRemoteCoreFile(const QString &fileName)\n{\n d->remoteCoreFileName->setText(fileName);\n}\n\nQString AttachCoreDialog::remoteCoreFile() const\n{\n return d->remoteCoreFileName->text();\n}\n\nvoid AttachCoreDialog::setKitId(const Core::Id &id)\n{\n d->kitChooser->setCurrentKitId(id);\n changed();\n}\n\nKit *AttachCoreDialog::kit() const\n{\n return d->kitChooser->currentKit();\n}\n\nQString AttachCoreDialog::overrideStartScript() const\n{\n return d->overrideStartScriptFileName->path();\n}\n\nvoid AttachCoreDialog::setOverrideStartScript(const QString &scriptName)\n{\n d->overrideStartScriptFileName->setPath(scriptName);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n\n#include \"loadcoredialog.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"types.h\"\n#include \"mmu.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"cpu.hh\"\n#include \"traps.h\"\n#include \"queue.h\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"kmtrace.hh\"\n#include \"bits.hh\"\n#include \"kalloc.hh\"\n\nextern \"C\" void __fetch_end(void);\n\nstruct intdesc idt[256] __attribute__((aligned(16)));\n\n\/\/ boot.S\nextern u64 trapentry[];\n\nu64\nsysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 num)\n{\n sti();\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf));\n myproc()->tf = tf;\n u64 r = syscall(a0, a1, a2, a3, a4, num);\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n return r;\n}\n\nint\ndo_pagefault(struct trapframe *tf)\n{\n uptr addr = rcr2();\n if (myproc()->uaccess_) {\n if (addr >= USERTOP)\n panic(\"Oops\");\n\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in kernel\\n\");\n tf->rax = -1;\n tf->rip = (u64)__fetch_end;\n return 0;\n } else if (tf->err & FEC_U) {\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in user\\n\");\n cli();\n }\n return -1;\n}\n\nvoid\ntrap(struct trapframe *tf)\n{\n if (tf->trapno == T_NMI) {\n \/\/ The only locks that we can acquire during NMI are ones\n \/\/ we acquire only during NMI.\n if (sampintr(tf))\n return;\n panic(\"NMI\");\n }\n\n if(tf->trapno == T_SYSCALL){\n sti();\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n myproc()->tf = tf;\n tf->rax = syscall(tf->rdi, tf->rsi, tf->rdx, tf->rcx, tf->r8, tf->rax);\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n return;\n }\n\n#if MTRACE\n if (myproc()->mtrace_stacks.curr >= 0)\n mtpause(myproc());\n mtstart(trap, myproc());\n \/\/ XXX mt_ascope ascope(\"trap:%d\", tf->trapno);\n#endif\n\n switch(tf->trapno){\n case T_IRQ0 + IRQ_TIMER:\n if (mycpu()->timer_printpc) {\n cprintf(\"cpu%d: proc %s rip %lx rsp %lx cs %x\\n\",\n mycpu()->id,\n myproc() ? myproc()->name : \"(none)\",\n tf->rip, tf->rsp, tf->cs);\n if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {\n uptr pc[10];\n getcallerpcs((void *) tf->rbp, pc, NELEM(pc));\n for (int i = 0; i < 10 && pc[i]; i++)\n cprintf(\"cpu%d: %lx\\n\", mycpu()->id, pc[i]);\n }\n mycpu()->timer_printpc = 0;\n }\n if (mycpu()->id == 0)\n cv_tick();\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_IDE:\n ideintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_IDE+1:\n \/\/ Bochs generates spurious IDE1 interrupts.\n break;\n case T_IRQ0 + IRQ_KBD:\n kbdintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_COM2:\n case T_IRQ0 + IRQ_COM1:\n uartintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + 7:\n case T_IRQ0 + IRQ_SPURIOUS:\n cprintf(\"cpu%d: spurious interrupt at %x:%lx\\n\",\n mycpu()->id, tf->cs, tf->rip);\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_ERROR:\n cprintf(\"cpu%d: lapic error?\\n\", mycpu()->id);\n lapiceoi();\n break;\n case T_TLBFLUSH: {\n lapiceoi();\n u64 nreq = tlbflush_req.load();\n lcr3(rcr3());\n mycpu()->tlbflush_done = nreq;\n break;\n }\n case T_SAMPCONF:\n lapiceoi();\n sampconf(); \n break;\n default:\n if (tf->trapno == T_IRQ0+e1000irq) {\n e1000intr();\n lapiceoi();\n piceoi();\n break;\n }\n\n if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0)\n return;\n \n if (myproc() == 0 || (tf->cs&3) == 0)\n kerneltrap(tf);\n\n \/\/ In user space, assume process misbehaved.\n cprintf(\"pid %d %s: trap %lu err %d on cpu %d \"\n \"rip 0x%lx rsp 0x%lx addr 0x%lx--kill proc\\n\",\n myproc()->pid, myproc()->name, tf->trapno, tf->err,\n mycpu()->id, tf->rip, tf->rsp, rcr2());\n myproc()->killed = 1;\n }\n\n \/\/ Force process exit if it has been killed and is in user space.\n \/\/ (If it is still executing in the kernel, let it keep running \n \/\/ until it gets to the regular system call return.)\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n \/\/ Force process to give up CPU on clock tick.\n \/\/ If interrupts were on while locks held, would need to check nlock.\n if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)\n yield();\n\n \/\/ Check if the process has been killed since we yielded\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n}\n\nvoid\ninittrap(void)\n{\n u64 entry;\n u8 bits;\n int i;\n \n bits = INT_P | SEG_INTR64; \/\/ present, interrupt gate\n for(i=0; i<256; i++) {\n entry = trapentry[i];\n idt[i] = INTDESC(KCSEG, entry, bits);\n }\n entry = trapentry[T_SYSCALL];\n idt[T_SYSCALL] = INTDESC(KCSEG, entry, SEG_DPL(3) | SEG_INTR64 |INT_P);\n}\n\nvoid\ninitnmi(void)\n{\n void *nmistackbase = ksalloc(slab_stack);\n mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE;\n\n if (mycpu()->id == 0)\n idt[T_NMI].ist = 1;\n}\n\nvoid\ninitseg(void)\n{\n volatile struct desctr dtr;\n struct cpu *c;\n\n dtr.limit = sizeof(idt) - 1;\n dtr.base = (u64)idt;\n lidt((void *)&dtr.limit);\n\n \/\/ TLS might not be ready\n c = &cpus[myid()];\n \/\/ Load per-CPU GDT\n memmove(c->gdt, bootgdt, sizeof(bootgdt));\n dtr.limit = sizeof(c->gdt) - 1;\n dtr.base = (u64)c->gdt;\n lgdt((void *)&dtr.limit);\n\n \/\/ When executing a syscall instruction the CPU sets the SS selector\n \/\/ to (star >> 32) + 8 and the CS selector to (star >> 32).\n \/\/ When executing a sysret instruction the CPU sets the SS selector\n \/\/ to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.\n u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);\n writemsr(MSR_STAR, star);\n writemsr(MSR_LSTAR, (u64)&sysentry);\n writemsr(MSR_SFMASK, FL_TF | FL_IF);\n}\n\n\/\/ Pushcli\/popcli are like cli\/sti except that they are matched:\n\/\/ it takes two popcli to undo two pushcli. Also, if interrupts\n\/\/ are off, then pushcli, popcli leaves them off.\nvoid\npushcli(void)\n{\n u64 rflags;\n\n rflags = readrflags();\n cli();\n if(mycpu()->ncli++ == 0)\n mycpu()->intena = rflags & FL_IF;\n}\n\nvoid\npopcli(void)\n{\n if(readrflags()&FL_IF)\n panic(\"popcli - interruptible\");\n if(--mycpu()->ncli < 0)\n panic(\"popcli\");\n if(mycpu()->ncli == 0 && mycpu()->intena)\n sti();\n}\n\n\/\/ Record the current call stack in pcs[] by following the %rbp chain.\nvoid\ngetcallerpcs(void *v, uptr pcs[], int n)\n{\n uptr *rbp;\n int i;\n\n rbp = (uptr*)v;\n for(i = 0; i < n; i++){\n if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) ||\n (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE))\n break;\n pcs[i] = rbp[1]; \/\/ saved %rip\n rbp = (uptr*)rbp[0]; \/\/ saved %rbp\n }\n for(; i < n; i++)\n pcs[i] = 0;\n}\n<commit_msg>Better panic message<commit_after>#include \"types.h\"\n#include \"mmu.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"cpu.hh\"\n#include \"traps.h\"\n#include \"queue.h\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"kmtrace.hh\"\n#include \"bits.hh\"\n#include \"kalloc.hh\"\n\nextern \"C\" void __fetch_end(void);\n\nstruct intdesc idt[256] __attribute__((aligned(16)));\n\n\/\/ boot.S\nextern u64 trapentry[];\n\nu64\nsysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 num)\n{\n sti();\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf));\n myproc()->tf = tf;\n u64 r = syscall(a0, a1, a2, a3, a4, num);\n\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n\n return r;\n}\n\nint\ndo_pagefault(struct trapframe *tf)\n{\n uptr addr = rcr2();\n if (myproc()->uaccess_) {\n if (addr >= USERTOP)\n panic(\"do_pagefault: %lx\", addr);\n\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in kernel\\n\");\n tf->rax = -1;\n tf->rip = (u64)__fetch_end;\n return 0;\n } else if (tf->err & FEC_U) {\n sti();\n if(pagefault(myproc()->vmap, addr, tf->err) >= 0){\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n return 0;\n }\n cprintf(\"pagefault: failed in user\\n\");\n cli();\n }\n return -1;\n}\n\nvoid\ntrap(struct trapframe *tf)\n{\n if (tf->trapno == T_NMI) {\n \/\/ The only locks that we can acquire during NMI are ones\n \/\/ we acquire only during NMI.\n if (sampintr(tf))\n return;\n panic(\"NMI\");\n }\n\n if(tf->trapno == T_SYSCALL){\n sti();\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n myproc()->tf = tf;\n tf->rax = syscall(tf->rdi, tf->rsi, tf->rdx, tf->rcx, tf->r8, tf->rax);\n if(myproc()->killed) {\n mtstart(trap, myproc());\n exit();\n }\n return;\n }\n\n#if MTRACE\n if (myproc()->mtrace_stacks.curr >= 0)\n mtpause(myproc());\n mtstart(trap, myproc());\n \/\/ XXX mt_ascope ascope(\"trap:%d\", tf->trapno);\n#endif\n\n switch(tf->trapno){\n case T_IRQ0 + IRQ_TIMER:\n if (mycpu()->timer_printpc) {\n cprintf(\"cpu%d: proc %s rip %lx rsp %lx cs %x\\n\",\n mycpu()->id,\n myproc() ? myproc()->name : \"(none)\",\n tf->rip, tf->rsp, tf->cs);\n if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {\n uptr pc[10];\n getcallerpcs((void *) tf->rbp, pc, NELEM(pc));\n for (int i = 0; i < 10 && pc[i]; i++)\n cprintf(\"cpu%d: %lx\\n\", mycpu()->id, pc[i]);\n }\n mycpu()->timer_printpc = 0;\n }\n if (mycpu()->id == 0)\n cv_tick();\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_IDE:\n ideintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_IDE+1:\n \/\/ Bochs generates spurious IDE1 interrupts.\n break;\n case T_IRQ0 + IRQ_KBD:\n kbdintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + IRQ_COM2:\n case T_IRQ0 + IRQ_COM1:\n uartintr();\n lapiceoi();\n piceoi();\n break;\n case T_IRQ0 + 7:\n case T_IRQ0 + IRQ_SPURIOUS:\n cprintf(\"cpu%d: spurious interrupt at %x:%lx\\n\",\n mycpu()->id, tf->cs, tf->rip);\n lapiceoi();\n break;\n case T_IRQ0 + IRQ_ERROR:\n cprintf(\"cpu%d: lapic error?\\n\", mycpu()->id);\n lapiceoi();\n break;\n case T_TLBFLUSH: {\n lapiceoi();\n u64 nreq = tlbflush_req.load();\n lcr3(rcr3());\n mycpu()->tlbflush_done = nreq;\n break;\n }\n case T_SAMPCONF:\n lapiceoi();\n sampconf(); \n break;\n default:\n if (tf->trapno == T_IRQ0+e1000irq) {\n e1000intr();\n lapiceoi();\n piceoi();\n break;\n }\n\n if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0)\n return;\n \n if (myproc() == 0 || (tf->cs&3) == 0)\n kerneltrap(tf);\n\n \/\/ In user space, assume process misbehaved.\n cprintf(\"pid %d %s: trap %lu err %d on cpu %d \"\n \"rip 0x%lx rsp 0x%lx addr 0x%lx--kill proc\\n\",\n myproc()->pid, myproc()->name, tf->trapno, tf->err,\n mycpu()->id, tf->rip, tf->rsp, rcr2());\n myproc()->killed = 1;\n }\n\n \/\/ Force process exit if it has been killed and is in user space.\n \/\/ (If it is still executing in the kernel, let it keep running \n \/\/ until it gets to the regular system call return.)\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n \/\/ Force process to give up CPU on clock tick.\n \/\/ If interrupts were on while locks held, would need to check nlock.\n if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)\n yield();\n\n \/\/ Check if the process has been killed since we yielded\n if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)\n exit();\n\n#if MTRACE\n mtstop(myproc());\n if (myproc()->mtrace_stacks.curr >= 0)\n mtresume(myproc());\n#endif\n}\n\nvoid\ninittrap(void)\n{\n u64 entry;\n u8 bits;\n int i;\n \n bits = INT_P | SEG_INTR64; \/\/ present, interrupt gate\n for(i=0; i<256; i++) {\n entry = trapentry[i];\n idt[i] = INTDESC(KCSEG, entry, bits);\n }\n entry = trapentry[T_SYSCALL];\n idt[T_SYSCALL] = INTDESC(KCSEG, entry, SEG_DPL(3) | SEG_INTR64 |INT_P);\n}\n\nvoid\ninitnmi(void)\n{\n void *nmistackbase = ksalloc(slab_stack);\n mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE;\n\n if (mycpu()->id == 0)\n idt[T_NMI].ist = 1;\n}\n\nvoid\ninitseg(void)\n{\n volatile struct desctr dtr;\n struct cpu *c;\n\n dtr.limit = sizeof(idt) - 1;\n dtr.base = (u64)idt;\n lidt((void *)&dtr.limit);\n\n \/\/ TLS might not be ready\n c = &cpus[myid()];\n \/\/ Load per-CPU GDT\n memmove(c->gdt, bootgdt, sizeof(bootgdt));\n dtr.limit = sizeof(c->gdt) - 1;\n dtr.base = (u64)c->gdt;\n lgdt((void *)&dtr.limit);\n\n \/\/ When executing a syscall instruction the CPU sets the SS selector\n \/\/ to (star >> 32) + 8 and the CS selector to (star >> 32).\n \/\/ When executing a sysret instruction the CPU sets the SS selector\n \/\/ to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.\n u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);\n writemsr(MSR_STAR, star);\n writemsr(MSR_LSTAR, (u64)&sysentry);\n writemsr(MSR_SFMASK, FL_TF | FL_IF);\n}\n\n\/\/ Pushcli\/popcli are like cli\/sti except that they are matched:\n\/\/ it takes two popcli to undo two pushcli. Also, if interrupts\n\/\/ are off, then pushcli, popcli leaves them off.\nvoid\npushcli(void)\n{\n u64 rflags;\n\n rflags = readrflags();\n cli();\n if(mycpu()->ncli++ == 0)\n mycpu()->intena = rflags & FL_IF;\n}\n\nvoid\npopcli(void)\n{\n if(readrflags()&FL_IF)\n panic(\"popcli - interruptible\");\n if(--mycpu()->ncli < 0)\n panic(\"popcli\");\n if(mycpu()->ncli == 0 && mycpu()->intena)\n sti();\n}\n\n\/\/ Record the current call stack in pcs[] by following the %rbp chain.\nvoid\ngetcallerpcs(void *v, uptr pcs[], int n)\n{\n uptr *rbp;\n int i;\n\n rbp = (uptr*)v;\n for(i = 0; i < n; i++){\n if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) ||\n (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE))\n break;\n pcs[i] = rbp[1]; \/\/ saved %rip\n rbp = (uptr*)rbp[0]; \/\/ saved %rbp\n }\n for(; i < n; i++)\n pcs[i] = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Intel 8250 serial port (UART).\n\/\/ http:\/\/en.wikibooks.org\/wiki\/Serial_Programming\/8250_UART_Programming\n\n#include \"types.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"traps.h\"\n#include \"apic.hh\"\n#include \"irq.hh\"\n\n#define COM2 0x2f8\n#define COM1 0x3f8\n\n#define COM_IN_RECEIVE 0 \/\/ DLAB = 0, in\n#define COM_OUT_TRANSMIT 0 \/\/ DLAB = 0, out\n#define COM_INT_EN 1 \/\/ DLAB = 0\n# define COM_INT_RECEIVE 0x01\n# define COM_INT_TRANSMIT 0x02\n# define COM_INT_LINE 0x04\n# define COM_INT_MODEM 0x08\n#define COM_DIVISOR_LSB 0 \/\/ DLAB = 1\n#define COM_DIVISOR_MSB 1 \/\/ DLAB = 1\n#define COM_IN_IIR 2\n# define COM_IN_IIR_NOT_PENDING 0x01\n# define COM_IN_IIR_ID_MASK 0x0E\n#define COM_OUT_FIFO_CTL 2\n# define COM_OUT_FIFO_ENABLE 0x01\n# define COM_OUT_FIFO_RECV_RESET 0x02\n# define COM_OUT_FIFO_XMIT_RESET 0x04\n# define COM_OUT_FIFO_DMA 0x08\n# define COM_OUT_FIFO_TRIGGER_MASK 0xC0\n# define COM_OUT_FIFO_TRIGGER_1 (0<<6)\n# define COM_OUT_FIFO_TRIGGER_4 (1<<6)\n# define COM_OUT_FIFO_TRIGGER_8 (2<<6)\n# define COM_OUT_FIFO_TRIGGER_14 (3<<6)\n#define COM_LINE_CTL 3\n# define COM_LINE_LEN_MASK 0x03\n# define COM_LINE_LEN_5 0\n# define COM_LINE_LEN_6 1\n# define COM_LINE_LEN_7 2\n# define COM_LINE_LEN_8 3\n# define COM_LINE_STOP_BITS 0x04\n# define COM_LINE_PARITY 0x08\n# define COM_LINE_EVEN_PARITY 0x10\n# define COM_LINE_STICK_PARITY 0x20\n# define COM_LINE_BREAK_CTL 0x40\n# define COM_LINE_DLAB 0x80\n#define COM_MODEM_CTL 4\n#define COM_LINE_STATUS 5\n# define COM_LINE_DATA_READY 0x01\n# define COM_LINE_OVERRUN_ERR 0x02\n# define COM_LINE_PARITY_ERR 0x04\n# define COM_LINE_FRAMING_ERR 0x08\n# define COM_LINE_BREAK 0x10\n# define COM_LINE_XMIT_HOLDING 0x20\n# define COM_LINE_XMIT_EMPTY 0x40\n# define COM_LINE_FIFO_ERR 0x80\n#define COM_MODEM_STATUS 6\n#define COM_SCRATCH 7\n\nstatic int com;\nstatic int irq_com;\nstatic int uart; \/\/ is there a uart?\n\nvoid\nuartputc(char c)\n{\n int i;\n\n if (!uart)\n return;\n for (i = 0; i < 128 && !(inb(com+COM_LINE_STATUS) & COM_LINE_XMIT_HOLDING);\n i++)\n microdelay(10);\n#ifdef UART_SEND_DELAY_USEC\n microdelay(UART_SEND_DELAY_USEC);\n#endif\n outb(com+COM_OUT_TRANSMIT, c);\n#ifdef UART_SEND_DELAY_USEC\n microdelay(UART_SEND_DELAY_USEC);\n#endif\n}\n\nstatic int\nuartgetc(void)\n{\n if (!uart)\n return -1;\n if (!(inb(com+COM_LINE_STATUS) & COM_LINE_DATA_READY))\n return -1;\n return inb(com+COM_IN_RECEIVE);\n}\n\nvoid\nuartintr(void)\n{\n consoleintr(uartgetc);\n}\n\nvoid\ninituart(void)\n{\n static struct {\n int com;\n int irq;\n } conf[] = {\n \/\/ Try COM2 (aka ttyS1) first, because it usually does SOL for IPMI.\n { COM2, IRQ_COM2 },\n \/\/ Still try COM1 (aka ttyS0), because it is what QEMU emulates.\n { COM1, IRQ_COM1 },\n };\n\n int i;\n#if defined(UART_BAUD)\n int baud = UART_BAUD;\n#else\n int baud = 19200;\n#endif\n for (i = 0; i < 2; i++) {\n com = conf[i].com;\n irq_com = conf[i].irq;\n\n \/\/ Turn off the FIFO\n outb(com+COM_OUT_FIFO_CTL, 0);\n \/\/ 19200 baud\n outb(com+COM_LINE_CTL, COM_LINE_DLAB); \/\/ Unlock divisor\n outb(com+COM_DIVISOR_LSB, 115200\/baud);\n outb(com+COM_DIVISOR_MSB, 0);\n \/\/ 8 bits, one stop bit, no parity\n outb(com+COM_LINE_CTL, COM_LINE_LEN_8); \/\/ Lock divisor, 8 data bits.\n outb(com+COM_INT_EN, COM_INT_RECEIVE); \/\/ Enable receive interrupts.\n \/\/ Data terminal ready\n outb(com+COM_MODEM_CTL, 0x0);\n \n \/\/ If status is 0xFF, no serial port.\n if(inb(com+COM_LINE_STATUS) != 0xFF)\n break;\n }\n if (i == 2)\n return;\n\n uart = 1;\n\n \/\/ Clean up the serial console (beginning of line, erase down)\n for (const char *p=\"\\r\\x1b[J\"; *p; p++)\n uartputc(*p);\n\n \/\/ Announce that we're here.\n for (const char *p=DEBUG?\"xv6 DEBUG\\n\":\"xv6\\n\"; *p; p++)\n uartputc(*p);\n}\n\nvoid\ninituartcons(void)\n{\n \/\/ Acknowledge pre-existing interrupt conditions;\n \/\/ enable interrupts.\n inb(com+COM_IN_IIR);\n inb(com+COM_IN_RECEIVE);\n extpic->map_isa_irq(irq_com).enable();\n}\n<commit_msg>inituartcons: fix race condition that shows up with qemu<commit_after>\/\/ Intel 8250 serial port (UART).\n\/\/ http:\/\/en.wikibooks.org\/wiki\/Serial_Programming\/8250_UART_Programming\n\n#include \"types.h\"\n#include \"kernel.hh\"\n#include \"amd64.h\"\n#include \"traps.h\"\n#include \"apic.hh\"\n#include \"irq.hh\"\n\n#define COM2 0x2f8\n#define COM1 0x3f8\n\n#define COM_IN_RECEIVE 0 \/\/ DLAB = 0, in\n#define COM_OUT_TRANSMIT 0 \/\/ DLAB = 0, out\n#define COM_INT_EN 1 \/\/ DLAB = 0\n# define COM_INT_RECEIVE 0x01\n# define COM_INT_TRANSMIT 0x02\n# define COM_INT_LINE 0x04\n# define COM_INT_MODEM 0x08\n#define COM_DIVISOR_LSB 0 \/\/ DLAB = 1\n#define COM_DIVISOR_MSB 1 \/\/ DLAB = 1\n#define COM_IN_IIR 2\n# define COM_IN_IIR_NOT_PENDING 0x01\n# define COM_IN_IIR_ID_MASK 0x0E\n#define COM_OUT_FIFO_CTL 2\n# define COM_OUT_FIFO_ENABLE 0x01\n# define COM_OUT_FIFO_RECV_RESET 0x02\n# define COM_OUT_FIFO_XMIT_RESET 0x04\n# define COM_OUT_FIFO_DMA 0x08\n# define COM_OUT_FIFO_TRIGGER_MASK 0xC0\n# define COM_OUT_FIFO_TRIGGER_1 (0<<6)\n# define COM_OUT_FIFO_TRIGGER_4 (1<<6)\n# define COM_OUT_FIFO_TRIGGER_8 (2<<6)\n# define COM_OUT_FIFO_TRIGGER_14 (3<<6)\n#define COM_LINE_CTL 3\n# define COM_LINE_LEN_MASK 0x03\n# define COM_LINE_LEN_5 0\n# define COM_LINE_LEN_6 1\n# define COM_LINE_LEN_7 2\n# define COM_LINE_LEN_8 3\n# define COM_LINE_STOP_BITS 0x04\n# define COM_LINE_PARITY 0x08\n# define COM_LINE_EVEN_PARITY 0x10\n# define COM_LINE_STICK_PARITY 0x20\n# define COM_LINE_BREAK_CTL 0x40\n# define COM_LINE_DLAB 0x80\n#define COM_MODEM_CTL 4\n#define COM_LINE_STATUS 5\n# define COM_LINE_DATA_READY 0x01\n# define COM_LINE_OVERRUN_ERR 0x02\n# define COM_LINE_PARITY_ERR 0x04\n# define COM_LINE_FRAMING_ERR 0x08\n# define COM_LINE_BREAK 0x10\n# define COM_LINE_XMIT_HOLDING 0x20\n# define COM_LINE_XMIT_EMPTY 0x40\n# define COM_LINE_FIFO_ERR 0x80\n#define COM_MODEM_STATUS 6\n#define COM_SCRATCH 7\n\nstatic int com;\nstatic int irq_com;\nstatic int uart; \/\/ is there a uart?\n\nvoid\nuartputc(char c)\n{\n int i;\n\n if (!uart)\n return;\n for (i = 0; i < 128 && !(inb(com+COM_LINE_STATUS) & COM_LINE_XMIT_HOLDING);\n i++)\n microdelay(10);\n#ifdef UART_SEND_DELAY_USEC\n microdelay(UART_SEND_DELAY_USEC);\n#endif\n outb(com+COM_OUT_TRANSMIT, c);\n#ifdef UART_SEND_DELAY_USEC\n microdelay(UART_SEND_DELAY_USEC);\n#endif\n}\n\nstatic int\nuartgetc(void)\n{\n if (!uart)\n return -1;\n if (!(inb(com+COM_LINE_STATUS) & COM_LINE_DATA_READY))\n return -1;\n return inb(com+COM_IN_RECEIVE);\n}\n\nvoid\nuartintr(void)\n{\n consoleintr(uartgetc);\n}\n\nvoid\ninituart(void)\n{\n static struct {\n int com;\n int irq;\n } conf[] = {\n \/\/ Try COM2 (aka ttyS1) first, because it usually does SOL for IPMI.\n { COM2, IRQ_COM2 },\n \/\/ Still try COM1 (aka ttyS0), because it is what QEMU emulates.\n { COM1, IRQ_COM1 },\n };\n\n int i;\n#if defined(UART_BAUD)\n int baud = UART_BAUD;\n#else\n int baud = 19200;\n#endif\n for (i = 0; i < 2; i++) {\n com = conf[i].com;\n irq_com = conf[i].irq;\n\n \/\/ Turn off the FIFO\n outb(com+COM_OUT_FIFO_CTL, 0);\n \/\/ 19200 baud\n outb(com+COM_LINE_CTL, COM_LINE_DLAB); \/\/ Unlock divisor\n outb(com+COM_DIVISOR_LSB, 115200\/baud);\n outb(com+COM_DIVISOR_MSB, 0);\n \/\/ 8 bits, one stop bit, no parity\n outb(com+COM_LINE_CTL, COM_LINE_LEN_8); \/\/ Lock divisor, 8 data bits.\n outb(com+COM_INT_EN, COM_INT_RECEIVE); \/\/ Enable receive interrupts.\n \/\/ Data terminal ready\n outb(com+COM_MODEM_CTL, 0x0);\n \n \/\/ If status is 0xFF, no serial port.\n if(inb(com+COM_LINE_STATUS) != 0xFF)\n break;\n }\n if (i == 2)\n return;\n\n uart = 1;\n\n \/\/ Clean up the serial console (beginning of line, erase down)\n for (const char *p=\"\\r\\x1b[J\"; *p; p++)\n uartputc(*p);\n\n \/\/ Announce that we're here.\n for (const char *p=DEBUG?\"xv6 DEBUG\\n\":\"xv6\\n\"; *p; p++)\n uartputc(*p);\n}\n\nvoid\ninituartcons(void)\n{\n \/\/ Acknowledge pre-existing interrupt conditions;\n \/\/ enable interrupts.\n extpic->map_isa_irq(irq_com).enable();\n inb(com+COM_IN_IIR);\n inb(com+COM_IN_RECEIVE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2007 by Kevin Krammer <kevin.krammer@gmx.at> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"xdgbasedirs_p.h\"\n\n#include \"akonadi-prefix.h\" \/\/ for prefix defines\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n\n#include <cstdlib>\n\nstatic QStringList alternateExecPaths( const QString& path )\n{\n QStringList pathList;\n\n pathList << path;\n\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n pathList << path + QLatin1String( \".exe\" );\n#elif defined(Q_OS_MAC) \/\/krazy:exclude=cpp\n pathList << path + QLatin1String( \".app\/Contents\/MacOS\/\" ) + path.section( QLatin1Char( '\/' ), -1 );\n#endif\n\n return pathList;\n}\n\nnamespace Akonadi {\n\nclass XdgBaseDirsPrivate\n{\n public:\n XdgBaseDirsPrivate() {}\n\n ~XdgBaseDirsPrivate() {}\n};\n\nclass XdgBaseDirsSingleton\n{\npublic:\n QString homePath( const char *variable, const char *defaultSubDir );\n\n QStringList systemPathList( const char *variable, const char *defaultDirList );\n\n public:\n QString mConfigHome;\n QString mDataHome;\n\n QStringList mConfigDirs;\n QStringList mDataDirs;\n QStringList mExecutableDirs;\n};\n\nQ_GLOBAL_STATIC(XdgBaseDirsSingleton, instance)\n\n}\n\nusing namespace Akonadi;\n\nXdgBaseDirs::XdgBaseDirs() : d( new XdgBaseDirsPrivate() )\n{\n}\n\nXdgBaseDirs::~XdgBaseDirs()\n{\n delete d;\n}\n\nQString XdgBaseDirs::homePath( const char *resource )\n{\n if ( qstrncmp( \"data\", resource, 4 ) == 0 ) {\n if ( instance()->mDataHome.isEmpty() ) {\n instance()->mDataHome = instance()->homePath( \"XDG_DATA_HOME\", \".local\/share\" );\n }\n return instance()->mDataHome;\n } else if ( qstrncmp( \"config\", resource, 6 ) == 0 ) {\n if ( instance()->mConfigHome.isEmpty() ) {\n instance()->mConfigHome = instance()->homePath( \"XDG_CONFIG_HOME\", \".config\" );\n }\n return instance()->mConfigHome;\n }\n\n return QString();\n}\n\nQStringList XdgBaseDirs::systemPathList( const char *resource )\n{\n if ( qstrncmp( \"data\", resource, 4 ) == 0 ) {\n if ( instance()->mDataDirs.isEmpty() ) {\n QStringList dataDirs = instance()->systemPathList( \"XDG_DATA_DIRS\", \"\/usr\/local\/share:\/usr\/share\" );\n\n const QString prefixDataDir = QLatin1String( AKONADIDATA );\n if ( !dataDirs.contains( prefixDataDir ) ) {\n dataDirs << prefixDataDir;\n }\n\n instance()->mDataDirs = dataDirs;\n }\n return instance()->mDataDirs;\n } else if ( qstrncmp( \"config\", resource, 6 ) == 0 ) {\n if ( instance()->mConfigDirs.isEmpty() ) {\n QStringList configDirs = instance()->systemPathList( \"XDG_CONFIG_DIRS\", \"\/etc\/xdg\" );\n\n const QString prefixConfigDir = QLatin1String( AKONADICONFIG );\n if ( !configDirs.contains( prefixConfigDir ) ) {\n configDirs << prefixConfigDir;\n }\n\n instance()->mConfigDirs = configDirs;\n }\n return instance()->mConfigDirs;\n }\n\n return QStringList();\n}\n\nQString XdgBaseDirs::findResourceFile( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable() ) {\n return fullPath;\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.begin();\n QStringList::const_iterator endIt = pathList.end();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable() ) {\n return fileInfo.absoluteFilePath();\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::findExecutableFile( const QString &relPath, const QStringList &searchPath )\n{\n if ( instance()->mExecutableDirs.isEmpty() ) {\n QStringList executableDirs = instance()->systemPathList( \"PATH\", \"\/usr\/local\/bin:\/usr\/bin\" );\n\n const QString prefixExecutableDir = QLatin1String( AKONADIPREFIX \"\/bin\" );\n if ( !executableDirs.contains( prefixExecutableDir ) ) {\n executableDirs << prefixExecutableDir;\n }\n\n executableDirs += searchPath;\n\n instance()->mExecutableDirs = executableDirs;\n }\n\n QStringList::const_iterator pathIt = instance()->mExecutableDirs.begin();\n QStringList::const_iterator pathEndIt = instance()->mExecutableDirs.end();\n for ( ; pathIt != pathEndIt; ++pathIt ) {\n QStringList fullPathList = alternateExecPaths(*pathIt + QLatin1Char( '\/' ) + relPath );\n\n QStringList::const_iterator it = fullPathList.begin();\n QStringList::const_iterator endIt = fullPathList.end();\n for ( ; it != endIt; ++it ) {\n QFileInfo fileInfo(*it);\n\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable() ) {\n return *it;\n }\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::findResourceDir( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char( '\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n return fullPath;\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.begin();\n QStringList::const_iterator endIt = pathList.end();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n return fileInfo.absoluteFilePath();\n }\n }\n\n return QString();\n}\n\nQStringList XdgBaseDirs::findAllResourceDirs( const char *resource, const QString &relPath )\n{\n QStringList resultList;\n\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n resultList << fileInfo.absoluteFilePath();\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.begin();\n QStringList::const_iterator endIt = pathList.end();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n resultList << fileInfo.absoluteFilePath();\n }\n }\n\n return resultList;\n}\n\nQString XdgBaseDirs::saveDir( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() ) {\n if ( fileInfo.isDir() ) {\n return fullPath;\n } else {\n qWarning() << \"XdgBaseDirs::saveDir: '\" << fileInfo.absoluteFilePath()\n << \"' exists but is not a directory\";\n }\n } else {\n if ( !QDir::home().mkpath( fileInfo.absoluteFilePath() ) ) {\n qWarning() << \"XdgBaseDirs::saveDir: failed to create directory '\"\n << fileInfo.absoluteFilePath() << \"'\";\n } else {\n return fullPath;\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::akonadiServerConfigFile( FileAccessMode openMode )\n{\n return akonadiConfigFile( QLatin1String( \"akonadiserverrc\" ), openMode );\n}\n\nQString XdgBaseDirs::akonadiConnectionConfigFile( FileAccessMode openMode )\n{\n return akonadiConfigFile( QLatin1String( \"akonadiconnectionrc\" ), openMode );\n}\n\nQString XdgBaseDirs::akonadiConfigFile( const QString &file, FileAccessMode openMode )\n{\n const QString akonadiDir = QLatin1String( \"akonadi\" );\n\n QString savePath = saveDir( \"config\", akonadiDir ) + QLatin1Char( '\/' ) + file;\n\n if ( openMode == WriteOnly ) return savePath;\n\n QString path = findResourceFile( \"config\", akonadiDir + QLatin1Char( '\/' ) + file );\n\n if ( path.isEmpty() ) {\n return savePath;\n } else if ( openMode == ReadOnly || path == savePath ) {\n return path;\n }\n\n \/\/ file found in system paths and mode is ReadWrite, thus\n \/\/ we copy to the home path location and return this path\n QFile systemFile( path );\n\n systemFile.copy( savePath );\n\n return savePath;\n}\n\nQString XdgBaseDirsSingleton::homePath( const char *variable, const char *defaultSubDir )\n{\n const QByteArray env = qgetenv( variable );\n\n QString xdgPath;\n if ( env.isEmpty() ) {\n xdgPath = QDir::homePath() + QLatin1Char( '\/' ) + QLatin1String( defaultSubDir );\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n } else if ( QDir::isAbsolutePath( QString::fromLocal8Bit( env ) ) ) {\n#else\n } else if ( env.startsWith( '\/' ) ) {\n#endif\n xdgPath = QString::fromLocal8Bit( env );\n } else {\n xdgPath = QDir::homePath() + QLatin1Char( '\/' ) + QString::fromLocal8Bit( env );\n }\n\n return xdgPath;\n}\n\nQStringList XdgBaseDirsSingleton::systemPathList( const char *variable, const char *defaultDirList )\n{\n const QByteArray env = qgetenv( variable );\n\n QString xdgDirList;\n if ( env.isEmpty() ) {\n xdgDirList = QLatin1String( defaultDirList );\n } else {\n xdgDirList = QString::fromLocal8Bit( env );\n }\n\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n return xdgDirList.split( QLatin1Char( ';' ) );\n#else\n return xdgDirList.split( QLatin1Char( ':' ) );\n#endif\n}\n<commit_msg>Fix iterator<commit_after>\/***************************************************************************\n * Copyright (C) 2007 by Kevin Krammer <kevin.krammer@gmx.at> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"xdgbasedirs_p.h\"\n\n#include \"akonadi-prefix.h\" \/\/ for prefix defines\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n\n#include <cstdlib>\n\nstatic QStringList alternateExecPaths( const QString& path )\n{\n QStringList pathList;\n\n pathList << path;\n\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n pathList << path + QLatin1String( \".exe\" );\n#elif defined(Q_OS_MAC) \/\/krazy:exclude=cpp\n pathList << path + QLatin1String( \".app\/Contents\/MacOS\/\" ) + path.section( QLatin1Char( '\/' ), -1 );\n#endif\n\n return pathList;\n}\n\nnamespace Akonadi {\n\nclass XdgBaseDirsPrivate\n{\n public:\n XdgBaseDirsPrivate() {}\n\n ~XdgBaseDirsPrivate() {}\n};\n\nclass XdgBaseDirsSingleton\n{\npublic:\n QString homePath( const char *variable, const char *defaultSubDir );\n\n QStringList systemPathList( const char *variable, const char *defaultDirList );\n\n public:\n QString mConfigHome;\n QString mDataHome;\n\n QStringList mConfigDirs;\n QStringList mDataDirs;\n QStringList mExecutableDirs;\n};\n\nQ_GLOBAL_STATIC(XdgBaseDirsSingleton, instance)\n\n}\n\nusing namespace Akonadi;\n\nXdgBaseDirs::XdgBaseDirs() : d( new XdgBaseDirsPrivate() )\n{\n}\n\nXdgBaseDirs::~XdgBaseDirs()\n{\n delete d;\n}\n\nQString XdgBaseDirs::homePath( const char *resource )\n{\n if ( qstrncmp( \"data\", resource, 4 ) == 0 ) {\n if ( instance()->mDataHome.isEmpty() ) {\n instance()->mDataHome = instance()->homePath( \"XDG_DATA_HOME\", \".local\/share\" );\n }\n return instance()->mDataHome;\n } else if ( qstrncmp( \"config\", resource, 6 ) == 0 ) {\n if ( instance()->mConfigHome.isEmpty() ) {\n instance()->mConfigHome = instance()->homePath( \"XDG_CONFIG_HOME\", \".config\" );\n }\n return instance()->mConfigHome;\n }\n\n return QString();\n}\n\nQStringList XdgBaseDirs::systemPathList( const char *resource )\n{\n if ( qstrncmp( \"data\", resource, 4 ) == 0 ) {\n if ( instance()->mDataDirs.isEmpty() ) {\n QStringList dataDirs = instance()->systemPathList( \"XDG_DATA_DIRS\", \"\/usr\/local\/share:\/usr\/share\" );\n\n const QString prefixDataDir = QLatin1String( AKONADIDATA );\n if ( !dataDirs.contains( prefixDataDir ) ) {\n dataDirs << prefixDataDir;\n }\n\n instance()->mDataDirs = dataDirs;\n }\n return instance()->mDataDirs;\n } else if ( qstrncmp( \"config\", resource, 6 ) == 0 ) {\n if ( instance()->mConfigDirs.isEmpty() ) {\n QStringList configDirs = instance()->systemPathList( \"XDG_CONFIG_DIRS\", \"\/etc\/xdg\" );\n\n const QString prefixConfigDir = QLatin1String( AKONADICONFIG );\n if ( !configDirs.contains( prefixConfigDir ) ) {\n configDirs << prefixConfigDir;\n }\n\n instance()->mConfigDirs = configDirs;\n }\n return instance()->mConfigDirs;\n }\n\n return QStringList();\n}\n\nQString XdgBaseDirs::findResourceFile( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable() ) {\n return fullPath;\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.constBegin();\n QStringList::const_iterator endIt = pathList.constEnd();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable() ) {\n return fileInfo.absoluteFilePath();\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::findExecutableFile( const QString &relPath, const QStringList &searchPath )\n{\n if ( instance()->mExecutableDirs.isEmpty() ) {\n QStringList executableDirs = instance()->systemPathList( \"PATH\", \"\/usr\/local\/bin:\/usr\/bin\" );\n\n const QString prefixExecutableDir = QLatin1String( AKONADIPREFIX \"\/bin\" );\n if ( !executableDirs.contains( prefixExecutableDir ) ) {\n executableDirs << prefixExecutableDir;\n }\n\n executableDirs += searchPath;\n\n instance()->mExecutableDirs = executableDirs;\n }\n\n QStringList::const_iterator pathIt = instance()->mExecutableDirs.constBegin();\n QStringList::const_iterator pathEndIt = instance()->mExecutableDirs.constEnd();\n for ( ; pathIt != pathEndIt; ++pathIt ) {\n QStringList fullPathList = alternateExecPaths(*pathIt + QLatin1Char( '\/' ) + relPath );\n\n QStringList::const_iterator it = fullPathList.constBegin();\n QStringList::const_iterator endIt = fullPathList.constEnd();\n for ( ; it != endIt; ++it ) {\n QFileInfo fileInfo(*it);\n\n if ( fileInfo.exists() && fileInfo.isFile() && fileInfo.isExecutable() ) {\n return *it;\n }\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::findResourceDir( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char( '\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n return fullPath;\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.constBegin();\n QStringList::const_iterator endIt = pathList.constEnd();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n return fileInfo.absoluteFilePath();\n }\n }\n\n return QString();\n}\n\nQStringList XdgBaseDirs::findAllResourceDirs( const char *resource, const QString &relPath )\n{\n QStringList resultList;\n\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n resultList << fileInfo.absoluteFilePath();\n }\n\n QStringList pathList = systemPathList( resource );\n\n QStringList::const_iterator it = pathList.constBegin();\n QStringList::const_iterator endIt = pathList.constEnd();\n for ( ; it != endIt; ++it ) {\n fileInfo = QFileInfo( *it + QLatin1Char('\/' ) + relPath );\n if ( fileInfo.exists() && fileInfo.isDir() && fileInfo.isReadable() ) {\n resultList << fileInfo.absoluteFilePath();\n }\n }\n\n return resultList;\n}\n\nQString XdgBaseDirs::saveDir( const char *resource, const QString &relPath )\n{\n QString fullPath = homePath( resource ) + QLatin1Char('\/' ) + relPath;\n\n QFileInfo fileInfo( fullPath );\n if ( fileInfo.exists() ) {\n if ( fileInfo.isDir() ) {\n return fullPath;\n } else {\n qWarning() << \"XdgBaseDirs::saveDir: '\" << fileInfo.absoluteFilePath()\n << \"' exists but is not a directory\";\n }\n } else {\n if ( !QDir::home().mkpath( fileInfo.absoluteFilePath() ) ) {\n qWarning() << \"XdgBaseDirs::saveDir: failed to create directory '\"\n << fileInfo.absoluteFilePath() << \"'\";\n } else {\n return fullPath;\n }\n }\n\n return QString();\n}\n\nQString XdgBaseDirs::akonadiServerConfigFile( FileAccessMode openMode )\n{\n return akonadiConfigFile( QLatin1String( \"akonadiserverrc\" ), openMode );\n}\n\nQString XdgBaseDirs::akonadiConnectionConfigFile( FileAccessMode openMode )\n{\n return akonadiConfigFile( QLatin1String( \"akonadiconnectionrc\" ), openMode );\n}\n\nQString XdgBaseDirs::akonadiConfigFile( const QString &file, FileAccessMode openMode )\n{\n const QString akonadiDir = QLatin1String( \"akonadi\" );\n\n QString savePath = saveDir( \"config\", akonadiDir ) + QLatin1Char( '\/' ) + file;\n\n if ( openMode == WriteOnly ) return savePath;\n\n QString path = findResourceFile( \"config\", akonadiDir + QLatin1Char( '\/' ) + file );\n\n if ( path.isEmpty() ) {\n return savePath;\n } else if ( openMode == ReadOnly || path == savePath ) {\n return path;\n }\n\n \/\/ file found in system paths and mode is ReadWrite, thus\n \/\/ we copy to the home path location and return this path\n QFile systemFile( path );\n\n systemFile.copy( savePath );\n\n return savePath;\n}\n\nQString XdgBaseDirsSingleton::homePath( const char *variable, const char *defaultSubDir )\n{\n const QByteArray env = qgetenv( variable );\n\n QString xdgPath;\n if ( env.isEmpty() ) {\n xdgPath = QDir::homePath() + QLatin1Char( '\/' ) + QLatin1String( defaultSubDir );\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n } else if ( QDir::isAbsolutePath( QString::fromLocal8Bit( env ) ) ) {\n#else\n } else if ( env.startsWith( '\/' ) ) {\n#endif\n xdgPath = QString::fromLocal8Bit( env );\n } else {\n xdgPath = QDir::homePath() + QLatin1Char( '\/' ) + QString::fromLocal8Bit( env );\n }\n\n return xdgPath;\n}\n\nQStringList XdgBaseDirsSingleton::systemPathList( const char *variable, const char *defaultDirList )\n{\n const QByteArray env = qgetenv( variable );\n\n QString xdgDirList;\n if ( env.isEmpty() ) {\n xdgDirList = QLatin1String( defaultDirList );\n } else {\n xdgDirList = QString::fromLocal8Bit( env );\n }\n\n#if defined(Q_OS_WIN) \/\/krazy:exclude=cpp\n return xdgDirList.split( QLatin1Char( ';' ) );\n#else\n return xdgDirList.split( QLatin1Char( ':' ) );\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ArduinoJson - https:\/\/arduinojson.org\n\/\/ Copyright Benoit Blanchon 2014-2021\n\/\/ MIT License\n\n#pragma once\n\n#include <ArduinoJson\/Memory\/Alignment.hpp>\n#include <ArduinoJson\/Polyfills\/assert.hpp>\n#include <ArduinoJson\/Polyfills\/mpl\/max.hpp>\n#include <ArduinoJson\/Variant\/VariantSlot.hpp>\n\n#include <string.h> \/\/ memmove\n\n#define JSON_STRING_SIZE(SIZE) (SIZE + 1)\n\nnamespace ARDUINOJSON_NAMESPACE {\n\n\/\/ _begin _end\n\/\/ v v\n\/\/ +-------------+--------------+--------------+\n\/\/ | strings... | (free) | ...variants |\n\/\/ +-------------+--------------+--------------+\n\/\/ ^ ^\n\/\/ _left _right\n\nclass MemoryPool {\n public:\n MemoryPool(char* buf, size_t capa)\n : _begin(buf),\n _left(buf),\n _right(buf ? buf + capa : 0),\n _end(buf ? buf + capa : 0),\n _overflowed(false) {\n ARDUINOJSON_ASSERT(isAligned(_begin));\n ARDUINOJSON_ASSERT(isAligned(_right));\n ARDUINOJSON_ASSERT(isAligned(_end));\n }\n\n void* buffer() {\n return _begin;\n }\n\n \/\/ Gets the capacity of the memoryPool in bytes\n size_t capacity() const {\n return size_t(_end - _begin);\n }\n\n size_t size() const {\n return size_t(_left - _begin + _end - _right);\n }\n\n bool overflowed() const {\n return _overflowed;\n }\n\n VariantSlot* allocVariant() {\n return allocRight<VariantSlot>();\n }\n\n template <typename TAdaptedString>\n const char* saveString(const TAdaptedString& str) {\n if (str.isNull())\n return 0;\n\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n const char* existingCopy = findString(str.begin());\n if (existingCopy)\n return existingCopy;\n#endif\n\n size_t n = str.size();\n\n char* newCopy = allocString(n + 1);\n if (newCopy) {\n str.copyTo(newCopy, n);\n newCopy[n] = 0; \/\/ force null-terminator\n }\n return newCopy;\n }\n\n void getFreeZone(char** zoneStart, size_t* zoneSize) const {\n *zoneStart = _left;\n *zoneSize = size_t(_right - _left);\n }\n\n const char* saveStringFromFreeZone(size_t len) {\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n const char* dup = findString(_left);\n if (dup)\n return dup;\n#endif\n\n const char* str = _left;\n _left += len;\n checkInvariants();\n return str;\n }\n\n void markAsOverflowed() {\n _overflowed = true;\n }\n\n void clear() {\n _left = _begin;\n _right = _end;\n _overflowed = false;\n }\n\n bool canAlloc(size_t bytes) const {\n return _left + bytes <= _right;\n }\n\n bool owns(void* p) const {\n return _begin <= p && p < _end;\n }\n\n \/\/ Workaround for missing placement new\n void* operator new(size_t, void* p) {\n return p;\n }\n\n \/\/ Squash the free space between strings and variants\n \/\/\n \/\/ _begin _end\n \/\/ v v\n \/\/ +-------------+--------------+\n \/\/ | strings... | ...variants |\n \/\/ +-------------+--------------+\n \/\/ ^\n \/\/ _left _right\n \/\/\n \/\/ This funcion is called before a realloc.\n ptrdiff_t squash() {\n char* new_right = addPadding(_left);\n if (new_right >= _right)\n return 0;\n\n size_t right_size = static_cast<size_t>(_end - _right);\n memmove(new_right, _right, right_size);\n\n ptrdiff_t bytes_reclaimed = _right - new_right;\n _right = new_right;\n _end = new_right + right_size;\n return bytes_reclaimed;\n }\n\n \/\/ Move all pointers together\n \/\/ This funcion is called after a realloc.\n void movePointers(ptrdiff_t offset) {\n _begin += offset;\n _left += offset;\n _right += offset;\n _end += offset;\n }\n\n private:\n void checkInvariants() {\n ARDUINOJSON_ASSERT(_begin <= _left);\n ARDUINOJSON_ASSERT(_left <= _right);\n ARDUINOJSON_ASSERT(_right <= _end);\n ARDUINOJSON_ASSERT(isAligned(_right));\n }\n\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n template <typename TIterator>\n const char* findString(TIterator str) {\n for (char* next = _begin; next < _left; ++next) {\n char* begin = next;\n\n \/\/ try to match\n for (TIterator it = str; *it == *next; ++it) {\n if (*next++ == 0)\n return begin;\n }\n\n \/\/ jump to next terminator\n while (*next) ++next;\n }\n return 0;\n }\n#endif\n\n char* allocString(size_t n) {\n if (!canAlloc(n)) {\n _overflowed = true;\n return 0;\n }\n char* s = _left;\n _left += n;\n checkInvariants();\n return s;\n }\n\n template <typename T>\n T* allocRight() {\n return reinterpret_cast<T*>(allocRight(sizeof(T)));\n }\n\n void* allocRight(size_t bytes) {\n if (!canAlloc(bytes)) {\n _overflowed = true;\n return 0;\n }\n _right -= bytes;\n return _right;\n }\n\n char *_begin, *_left, *_right, *_end;\n bool _overflowed;\n};\n\n} \/\/ namespace ARDUINOJSON_NAMESPACE\n<commit_msg>clang-tidy: muted \"use of memory after it is freed\" in MemoryPool<commit_after>\/\/ ArduinoJson - https:\/\/arduinojson.org\n\/\/ Copyright Benoit Blanchon 2014-2021\n\/\/ MIT License\n\n#pragma once\n\n#include <ArduinoJson\/Memory\/Alignment.hpp>\n#include <ArduinoJson\/Polyfills\/assert.hpp>\n#include <ArduinoJson\/Polyfills\/mpl\/max.hpp>\n#include <ArduinoJson\/Variant\/VariantSlot.hpp>\n\n#include <string.h> \/\/ memmove\n\n#define JSON_STRING_SIZE(SIZE) (SIZE + 1)\n\nnamespace ARDUINOJSON_NAMESPACE {\n\n\/\/ _begin _end\n\/\/ v v\n\/\/ +-------------+--------------+--------------+\n\/\/ | strings... | (free) | ...variants |\n\/\/ +-------------+--------------+--------------+\n\/\/ ^ ^\n\/\/ _left _right\n\nclass MemoryPool {\n public:\n MemoryPool(char* buf, size_t capa)\n : _begin(buf),\n _left(buf),\n _right(buf ? buf + capa : 0),\n _end(buf ? buf + capa : 0),\n _overflowed(false) {\n ARDUINOJSON_ASSERT(isAligned(_begin));\n ARDUINOJSON_ASSERT(isAligned(_right));\n ARDUINOJSON_ASSERT(isAligned(_end));\n }\n\n void* buffer() {\n return _begin; \/\/ NOLINT(clang-analyzer-unix.Malloc)\n \/\/ movePointers() alters this pointer\n }\n\n \/\/ Gets the capacity of the memoryPool in bytes\n size_t capacity() const {\n return size_t(_end - _begin);\n }\n\n size_t size() const {\n return size_t(_left - _begin + _end - _right);\n }\n\n bool overflowed() const {\n return _overflowed;\n }\n\n VariantSlot* allocVariant() {\n return allocRight<VariantSlot>();\n }\n\n template <typename TAdaptedString>\n const char* saveString(const TAdaptedString& str) {\n if (str.isNull())\n return 0;\n\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n const char* existingCopy = findString(str.begin());\n if (existingCopy)\n return existingCopy;\n#endif\n\n size_t n = str.size();\n\n char* newCopy = allocString(n + 1);\n if (newCopy) {\n str.copyTo(newCopy, n);\n newCopy[n] = 0; \/\/ force null-terminator\n }\n return newCopy;\n }\n\n void getFreeZone(char** zoneStart, size_t* zoneSize) const {\n *zoneStart = _left;\n *zoneSize = size_t(_right - _left);\n }\n\n const char* saveStringFromFreeZone(size_t len) {\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n const char* dup = findString(_left);\n if (dup)\n return dup;\n#endif\n\n const char* str = _left;\n _left += len;\n checkInvariants();\n return str;\n }\n\n void markAsOverflowed() {\n _overflowed = true;\n }\n\n void clear() {\n _left = _begin;\n _right = _end;\n _overflowed = false;\n }\n\n bool canAlloc(size_t bytes) const {\n return _left + bytes <= _right;\n }\n\n bool owns(void* p) const {\n return _begin <= p && p < _end;\n }\n\n \/\/ Workaround for missing placement new\n void* operator new(size_t, void* p) {\n return p;\n }\n\n \/\/ Squash the free space between strings and variants\n \/\/\n \/\/ _begin _end\n \/\/ v v\n \/\/ +-------------+--------------+\n \/\/ | strings... | ...variants |\n \/\/ +-------------+--------------+\n \/\/ ^\n \/\/ _left _right\n \/\/\n \/\/ This funcion is called before a realloc.\n ptrdiff_t squash() {\n char* new_right = addPadding(_left);\n if (new_right >= _right)\n return 0;\n\n size_t right_size = static_cast<size_t>(_end - _right);\n memmove(new_right, _right, right_size);\n\n ptrdiff_t bytes_reclaimed = _right - new_right;\n _right = new_right;\n _end = new_right + right_size;\n return bytes_reclaimed;\n }\n\n \/\/ Move all pointers together\n \/\/ This funcion is called after a realloc.\n void movePointers(ptrdiff_t offset) {\n _begin += offset;\n _left += offset;\n _right += offset;\n _end += offset;\n }\n\n private:\n void checkInvariants() {\n ARDUINOJSON_ASSERT(_begin <= _left);\n ARDUINOJSON_ASSERT(_left <= _right);\n ARDUINOJSON_ASSERT(_right <= _end);\n ARDUINOJSON_ASSERT(isAligned(_right));\n }\n\n#if ARDUINOJSON_ENABLE_STRING_DEDUPLICATION\n template <typename TIterator>\n const char* findString(TIterator str) {\n for (char* next = _begin; next < _left; ++next) {\n char* begin = next;\n\n \/\/ try to match\n for (TIterator it = str; *it == *next; ++it) {\n if (*next++ == 0)\n return begin;\n }\n\n \/\/ jump to next terminator\n while (*next) ++next;\n }\n return 0;\n }\n#endif\n\n char* allocString(size_t n) {\n if (!canAlloc(n)) {\n _overflowed = true;\n return 0;\n }\n char* s = _left;\n _left += n;\n checkInvariants();\n return s;\n }\n\n template <typename T>\n T* allocRight() {\n return reinterpret_cast<T*>(allocRight(sizeof(T)));\n }\n\n void* allocRight(size_t bytes) {\n if (!canAlloc(bytes)) {\n _overflowed = true;\n return 0;\n }\n _right -= bytes;\n return _right;\n }\n\n char *_begin, *_left, *_right, *_end;\n bool _overflowed;\n};\n\n} \/\/ namespace ARDUINOJSON_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n Vinzenz Feenstra\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"sqlite.hpp\"\n#include <boost\/lexical_cast.hpp>\n\nnamespace sqlite3_plugin {\n\nusing namespace flusspferd;\n\nvoid raise_sqlite_error(::sqlite3* db)\n{\n std::string s = \"SQLite3 Error: \";\n s += sqlite3_errmsg(db);\n throw exception(s.c_str());\n}\n\nsqlite3::sqlite3(object const &obj, call_context &x)\n: base_type(obj)\n, db(0)\n{\n if (x.arg.size() == 0) {\n throw exception (\"SQLite3 requires more than 0 arguments\");\n }\n string dsn = x.arg[0];\n\n \/\/ TODO: pull arguments from 2nd\/options argument\n if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {\n if (db) {\n raise_sqlite_error(db);\n }\n else {\n throw std::bad_alloc(); \/\/ out of memory. better way to signal this?\n }\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::~sqlite3()\n{\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::close()\n{\n if (db) {\n sqlite3_close(db);\n db = NULL;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::cursor(call_context &x) { \n local_root_scope scope;\n ensure_opened();\n\n if (x.arg.size() < 1) {\n throw exception (\"cursor requires more than 0 arguments\");\n }\n\n string sql = x.arg[0].to_string();\n size_t n_bytes = sql.length() * 2;\n sqlite3_stmt *sth = 0;\n char16_t *tail = 0; \/\/ uncompiled part of the sql (when multiple stmts)\n \n if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)\n {\n raise_sqlite_error(db);\n }\n \n object cursor = create_native_object<sqlite3_cursor>(object(), sth);\n\n \/\/ TODO: remove tail and set it seperately\n cursor.define_property(\"sql\", sql);\n\n x.result = cursor;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::last_insert_id(call_context & x) {\n local_root_scope scope;\n ensure_opened();\n \n x.result = boost::lexical_cast< std::string >( sqlite3_last_insert_rowid( db ) );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::ensure_opened() {\n if (!db) {\n throw exception(\"SQLite3.cursor called on closed dbh\");\n }\n}\n}\n\n<commit_msg>Fixed exception message<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n Vinzenz Feenstra\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"sqlite.hpp\"\n#include <boost\/lexical_cast.hpp>\n\nnamespace sqlite3_plugin {\n\nusing namespace flusspferd;\n\nvoid raise_sqlite_error(::sqlite3* db)\n{\n std::string s = \"SQLite3 Error: \";\n s += sqlite3_errmsg(db);\n throw exception(s.c_str());\n}\n\nsqlite3::sqlite3(object const &obj, call_context &x)\n: base_type(obj)\n, db(0)\n{\n if (x.arg.size() == 0) {\n throw exception (\"SQLite3 requires more than 0 arguments\");\n }\n string dsn = x.arg[0];\n\n \/\/ TODO: pull arguments from 2nd\/options argument\n if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {\n if (db) {\n raise_sqlite_error(db);\n }\n else {\n throw std::bad_alloc(); \/\/ out of memory. better way to signal this?\n }\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsqlite3::~sqlite3()\n{\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::close()\n{\n if (db) {\n sqlite3_close(db);\n db = NULL;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::cursor(call_context &x) { \n local_root_scope scope;\n ensure_opened();\n\n if (x.arg.size() < 1) {\n throw exception (\"cursor requires more than 0 arguments\");\n }\n\n string sql = x.arg[0].to_string();\n size_t n_bytes = sql.length() * 2;\n sqlite3_stmt *sth = 0;\n char16_t *tail = 0; \/\/ uncompiled part of the sql (when multiple stmts)\n \n if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)\n {\n raise_sqlite_error(db);\n }\n \n object cursor = create_native_object<sqlite3_cursor>(object(), sth);\n\n \/\/ TODO: remove tail and set it seperately\n cursor.define_property(\"sql\", sql);\n\n x.result = cursor;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::last_insert_id(call_context & x) {\n local_root_scope scope;\n ensure_opened();\n \n x.result = boost::lexical_cast< std::string >( sqlite3_last_insert_rowid( db ) );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid sqlite3::ensure_opened() {\n if (!db) {\n throw exception(\"SQLite3 method called on a closed database handle\");\n }\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <memory>\n\n#include <Gui\/TransformEditor\/TransformEditor.hpp>\n#include <Gui\/Utils\/KeyMappingManager.hpp>\n#include <Gui\/Viewer\/Gizmo\/Gizmo.hpp>\n#include <QMouseEvent>\n#include <QObject>\n\nnamespace Ra {\nnamespace Engine {\nstruct ItemEntry;\n}\n} \/\/ namespace Ra\nnamespace Ra {\nnamespace Gui {\n\/\/\/ This class interfaces the gizmos with the ui commands.\n\/\/\/ It allows to change the gizmo type when editing an editable transform object\n\/\/\/ Note : currently the scale gizmo is not implemented so it will just return a null pointer\nclass RA_GUI_API GizmoManager : public QObject,\n public Gui::TransformEditor,\n public KeyMappingManageable<GizmoManager>\n{\n Q_OBJECT\n friend class KeyMappingManageable<GizmoManager>;\n\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n enum GizmoType { NONE, TRANSLATION, ROTATION, SCALE };\n\n explicit GizmoManager( QObject* parent = nullptr );\n ~GizmoManager() = default;\n\n public:\n \/\/\/ Receive mouse events and transmit them to the gizmos.\n virtual bool handleMousePressEvent( QMouseEvent* event,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key );\n virtual bool handleMouseReleaseEvent( QMouseEvent* event );\n virtual bool handleMouseMoveEvent( QMouseEvent* event,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key );\n\n public slots:\n \/\/\/ Set the object being currently edited\n void setEditable( const Engine::Scene::ItemEntry& ent ) override;\n\n \/\/\/ Destroy all gizmos\n void cleanup();\n\n \/\/\/ Callback when a drawable is picked.\n void handlePickingResult( int drawableId );\n\n \/\/\/ Change mode from local axis to global\n void setLocal( bool useLocal );\n\n \/\/\/ Change gizmo type (rotation or translation)\n void changeGizmoType( GizmoType type );\n\n \/\/\/ Retrieve the transform from the editable and update the gizmos.\n void updateValues() override;\n\n private:\n bool isValidAction( const Gui::KeyMappingManager::KeyMappingAction& action ) const;\n\n \/\/ Helper method to change the current gizmo\n void updateGizmo();\n\n \/\/ Returs the current gizmo\n Gizmo* currentGizmo();\n\n private:\n std::array<std::unique_ptr<Gizmo>, 3> m_gizmos; \/\/! Owning pointers to the gizmos\n GizmoType m_currentGizmoType; \/\/! Type of the gizmo\n Gizmo::Mode m_mode; \/\/! Local\/global axis mode.\n\n static void configureKeyMapping_impl();\n\n#define KeyMappingGizmo \\\n KMA_VALUE( GIZMOMANAGER_MANIPULATION ) \\\n KMA_VALUE( GIZMOMANAGER_STEP ) \\\n KMA_VALUE( GIZMOMANAGER_WHOLE ) \\\n KMA_VALUE( GIZMOMANAGER_STEP_WHOLE )\n\n#define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX;\n KeyMappingGizmo\n#undef KMA_VALUE\n};\n} \/\/ namespace Gui\n} \/\/ namespace Ra\n<commit_msg>predefine the struct ItemEntry in the right namespace<commit_after>#pragma once\n\n#include <memory>\n\n#include <Gui\/TransformEditor\/TransformEditor.hpp>\n#include <Gui\/Utils\/KeyMappingManager.hpp>\n#include <Gui\/Viewer\/Gizmo\/Gizmo.hpp>\n#include <QMouseEvent>\n#include <QObject>\n\nnamespace Ra {\nnamespace Engine {\nnamespace Scene {\nstruct ItemEntry;\n} \/\/ namespace Scene\n} \/\/ namespace Engine\n} \/\/ namespace Ra\nnamespace Ra {\nnamespace Gui {\n\/\/\/ This class interfaces the gizmos with the ui commands.\n\/\/\/ It allows to change the gizmo type when editing an editable transform object\n\/\/\/ Note : currently the scale gizmo is not implemented so it will just return a null pointer\nclass RA_GUI_API GizmoManager : public QObject,\n public Gui::TransformEditor,\n public KeyMappingManageable<GizmoManager>\n{\n Q_OBJECT\n friend class KeyMappingManageable<GizmoManager>;\n\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n enum GizmoType { NONE, TRANSLATION, ROTATION, SCALE };\n\n explicit GizmoManager( QObject* parent = nullptr );\n ~GizmoManager() = default;\n\n public:\n \/\/\/ Receive mouse events and transmit them to the gizmos.\n virtual bool handleMousePressEvent( QMouseEvent* event,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key );\n virtual bool handleMouseReleaseEvent( QMouseEvent* event );\n virtual bool handleMouseMoveEvent( QMouseEvent* event,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key );\n\n public slots:\n \/\/\/ Set the object being currently edited\n void setEditable( const Engine::Scene::ItemEntry& ent ) override;\n\n \/\/\/ Destroy all gizmos\n void cleanup();\n\n \/\/\/ Callback when a drawable is picked.\n void handlePickingResult( int drawableId );\n\n \/\/\/ Change mode from local axis to global\n void setLocal( bool useLocal );\n\n \/\/\/ Change gizmo type (rotation or translation)\n void changeGizmoType( GizmoType type );\n\n \/\/\/ Retrieve the transform from the editable and update the gizmos.\n void updateValues() override;\n\n private:\n bool isValidAction( const Gui::KeyMappingManager::KeyMappingAction& action ) const;\n\n \/\/ Helper method to change the current gizmo\n void updateGizmo();\n\n \/\/ Returs the current gizmo\n Gizmo* currentGizmo();\n\n private:\n std::array<std::unique_ptr<Gizmo>, 3> m_gizmos; \/\/! Owning pointers to the gizmos\n GizmoType m_currentGizmoType; \/\/! Type of the gizmo\n Gizmo::Mode m_mode; \/\/! Local\/global axis mode.\n\n static void configureKeyMapping_impl();\n\n#define KeyMappingGizmo \\\n KMA_VALUE( GIZMOMANAGER_MANIPULATION ) \\\n KMA_VALUE( GIZMOMANAGER_STEP ) \\\n KMA_VALUE( GIZMOMANAGER_WHOLE ) \\\n KMA_VALUE( GIZMOMANAGER_STEP_WHOLE )\n\n#define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX;\n KeyMappingGizmo\n#undef KMA_VALUE\n};\n} \/\/ namespace Gui\n} \/\/ namespace Ra\n<|endoftext|>"} {"text":"<commit_before>\/*\n * bridge.cpp\n *\n * Created on: Jun 11, 2015\n * Author: Jinwoong Kim\n *\/\n\nextern \"C\"{\n#include \"postgres.h\"\n\n#include \"access\/heapam.h\"\n#include \"utils\/rel.h\"\n#include \"utils\/ruleutils.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/lsyscache.h\"\n}\n\nclass Bridge {\n\n public:\n\n \/**\n * @brief Getting the relation name.\n * @param relation id relation id\n *\/\n static char* GetRelationName(Oid relation_id) {\n Relation relation;\n char *relation_name;\n\n relation = relation_open(relation_id, NoLock);\n\n \/\/ Get name for given relation\n relation_name = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation));\n\n relation_close(relation, NoLock);\n\n return relation_name;\n }\n\n};\n\n\n<commit_msg>Add GetNumberOfAttributes function in src\/postgres\/bridge<commit_after>\/*\n * bridge.cpp\n *\n * Created on: Jun 11, 2015\n * Author: Jinwoong Kim\n *\/\n\nextern \"C\"{\n#include \"postgres.h\"\n\n#include \"access\/heapam.h\"\n#include \"utils\/rel.h\"\n#include \"utils\/ruleutils.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/lsyscache.h\"\n}\n\nclass Bridge {\n\n public:\n\n \/**\n * @brief Getting the relation name.\n * @param relation_id relation id\n *\/\n static char* GetRelationName(Oid relation_id) {\n Relation relation;\n char *relation_name;\n\n relation = relation_open(relation_id, NoLock);\n\n \/\/ Get name for given relation\n relation_name = quote_qualified_identifier(get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation));\n\n \/\/ Simply version of above function\n \/\/ relation_name = RelationGetRelationName(relation);\n\n\n relation_close(relation, NoLock);\n\n return relation_name;\n }\n\n \/**\n * @brief Getting the number of attributes.\n * @param relation_id relation id\n *\/\n int GetNumberOfAttributes(Oid relation_id) {\n Relation relation;\n AttrNumber numOfAttris;\n \n relation = relation_open(relation_id, NoLock);\n \n \/\/Get the number of attributes\n numOfAttris = RelationGetNumberOfAttributes(relation);\n\n relation_close(relation, NoLock);\n \n return numOfAttris;\n }\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * lxqt-connman-applet - a gui frontend for connman\n *\n * Copyright: 2014-2015 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QFormLayout>\n#include <QLabel>\n#include <QLineEdit>\n\n#include \"strings.h\"\n\n#include \"dialog.h\"\n\nDialog::Dialog(QString service, QVariantMap request, QWidget *parent) :\n QDialog(parent), Ui::Dialog()\n{\n setupUi(this);\n headingLabel->setText(headingLabel->text().arg(service));\n\n foreach (QString key, request.keys())\n {\n QLabel *label = new QLabel(string(key), this);\n QLineEdit *lineEdit = new QLineEdit(this);\n inputFields[key] = lineEdit;\n inputFieldsLayout->addRow(label, lineEdit);\n }\n}\n\nDialog::~Dialog()\n{\n}\n\nQVariantMap Dialog::collectedInput()\n{\n QVariantMap collected;\n\n foreach (QString key, inputFields.keys())\n {\n collected[key] = inputFields[key]->text(); \/\/ FIXME Handle bytearrays\n }\n\n return collected;\n}\n\n<commit_msg>Only send fields from agent if they are none empty<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * lxqt-connman-applet - a gui frontend for connman\n *\n * Copyright: 2014-2015 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QFormLayout>\n#include <QLabel>\n#include <QLineEdit>\n#include <QDebug>\n#include \"strings.h\"\n\n#include \"dialog.h\"\n\nDialog::Dialog(QString service, QVariantMap request, QWidget *parent) :\n QDialog(parent), Ui::Dialog()\n{\n setupUi(this);\n headingLabel->setText(headingLabel->text().arg(service));\n\n foreach (QString key, request.keys())\n {\n QLabel *label = new QLabel(string(key), this);\n QLineEdit *lineEdit = new QLineEdit(this);\n inputFields[key] = lineEdit;\n inputFieldsLayout->addRow(label, lineEdit);\n }\n}\n\nDialog::~Dialog()\n{\n}\n\nQVariantMap Dialog::collectedInput()\n{\n QVariantMap collected;\n\n foreach (QString key, inputFields.keys())\n {\n if (!inputFields[key]->text().trimmed().isEmpty())\n {\n collected[key] = inputFields[key]->text(); \/\/ FIXME Handle bytearrays\n }\n }\n\n qDebug() << \"Dialog returning: \" << collected << \"\\n\";\n return collected;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"numerics\/elliptic_functions.hpp\"\n\n#include <filesystem>\n#include <fstream>\n#include <utility>\n\n#include \"glog\/logging.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"google\/protobuf\/text_format.h\"\n#include \"gtest\/gtest.h\"\n#include \"serialization\/numerics.pb.h\"\n#include \"testing_utilities\/almost_equals.hpp\"\n#include \"testing_utilities\/is_near.hpp\"\n\nnamespace principia {\n\nusing testing_utilities::AlmostEquals;\nusing testing_utilities::IsNear;\n\nnamespace numerics {\n\nclass EllipticFunctionsTest : public ::testing::Test {\n protected:\n serialization::TabulatedData ReadTabulatedData(\n std::filesystem::path const& tabulated_data_filename) {\n serialization::TabulatedData tabulated_data;\n std::ifstream tabulated_data_ifstream(tabulated_data_filename);\n CHECK(tabulated_data_ifstream.good());\n google::protobuf::io::IstreamInputStream tabulated_data_zcs(\n &tabulated_data_ifstream);\n CHECK(google::protobuf::TextFormat::Parse(&tabulated_data_zcs,\n &tabulated_data));\n CHECK_LT(0, tabulated_data.entry_size());\n return tabulated_data;\n }\n};\n\nTEST_F(EllipticFunctionsTest, Xgscd) {\n \/\/ These expected values come from the output given by Fukushima at the end of\n \/\/ his xgscd.txt. For our purpose, an unit test with assertions is more\n \/\/ useful than eyeballing the output.\n auto xgscd_expected =\n ReadTabulatedData(SOLUTION_DIR \/ \"numerics\" \/ \"xgscd.proto.txt\");\n constexpr double PI = 3.1415926535897932384626433;\n constexpr double PIHALF = PI * 0.5;\n double dmc, mc, m, du, u, s, c, d;\n int jend, iend;\n jend = 10;\n iend = 8;\n dmc = 1.0 \/ static_cast<double>(jend);\n std::printf(\"%10s%10s%25s%25s%25s\\n\", \"m\", \"u\", \"s\", \"c\", \"d\");\n int expected_index = 0;\n for (int j = 1; j <= jend; ++j) {\n mc = static_cast<double>(j) * dmc;\n m = 1.0 - mc;\n du = Elk(mc) \/ static_cast<double>(iend);\n for (int i = 0; i <= iend * 8; ++i) {\n u = du * static_cast<double>(i);\n Gscd(u, mc, s, c, d);\n std::printf(\"%10.5f%10.5f%25.15e%25.15e%25.15e\\n\", m, u, s, c, d);\n\n auto const& expected_entry = xgscd_expected.entry(expected_index);\n auto const expected_argument_u = expected_entry.argument(0);\n auto const expected_argument_mc = expected_entry.argument(1);\n auto const expected_value_s = expected_entry.value(0);\n auto const expected_value_c = expected_entry.value(1);\n auto const expected_value_d = expected_entry.value(2);\n EXPECT_THAT(u, IsNear(expected_argument_u, 1.001));\n EXPECT_THAT(mc, IsNear(expected_argument_mc, 1.001));\n EXPECT_THAT(s, AlmostEquals(expected_value_s, 0, 0));\n EXPECT_THAT(c, AlmostEquals(expected_value_c, 0, 0));\n EXPECT_THAT(d, AlmostEquals(expected_value_d, 0, 0));\n ++expected_index;\n }\n std::printf(\"\\n\");\n }\n}\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<commit_msg>The test passes.<commit_after>\n#include \"numerics\/elliptic_functions.hpp\"\n\n#include <filesystem>\n#include <fstream>\n#include <utility>\n\n#include \"glog\/logging.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"google\/protobuf\/text_format.h\"\n#include \"gtest\/gtest.h\"\n#include \"serialization\/numerics.pb.h\"\n#include \"testing_utilities\/almost_equals.hpp\"\n#include \"testing_utilities\/is_near.hpp\"\n\nnamespace principia {\n\nusing testing_utilities::AlmostEquals;\nusing testing_utilities::IsNear;\n\nnamespace numerics {\n\nclass EllipticFunctionsTest : public ::testing::Test {\n protected:\n serialization::TabulatedData ReadTabulatedData(\n std::filesystem::path const& tabulated_data_filename) {\n serialization::TabulatedData tabulated_data;\n std::ifstream tabulated_data_ifstream(tabulated_data_filename);\n CHECK(tabulated_data_ifstream.good());\n google::protobuf::io::IstreamInputStream tabulated_data_zcs(\n &tabulated_data_ifstream);\n CHECK(google::protobuf::TextFormat::Parse(&tabulated_data_zcs,\n &tabulated_data));\n CHECK_LT(0, tabulated_data.entry_size());\n return tabulated_data;\n }\n};\n\nTEST_F(EllipticFunctionsTest, Xgscd) {\n \/\/ These expected values come from the output given by Fukushima at the end of\n \/\/ his xgscd.txt. For our purpose, an unit test with assertions is more\n \/\/ useful than eyeballing the output.\n auto xgscd_expected =\n ReadTabulatedData(SOLUTION_DIR \/ \"numerics\" \/ \"xgscd.proto.txt\");\n constexpr double PI = 3.1415926535897932384626433;\n constexpr double PIHALF = PI * 0.5;\n double dmc, mc, m, du, u, s, c, d;\n int jend, iend;\n jend = 10;\n iend = 8;\n dmc = 1.0 \/ static_cast<double>(jend);\n std::printf(\"%10s%10s%25s%25s%25s\\n\", \"m\", \"u\", \"s\", \"c\", \"d\");\n int expected_index = 0;\n for (int j = 1; j <= jend; ++j) {\n mc = static_cast<double>(j) * dmc;\n m = 1.0 - mc;\n du = Elk(mc) \/ static_cast<double>(iend);\n for (int i = 0; i <= iend * 8; ++i) {\n u = du * static_cast<double>(i);\n Gscd(u, mc, s, c, d);\n std::printf(\"%10.5f%10.5f%25.15e%25.15e%25.15e\\n\", m, u, s, c, d);\n\n auto const& expected_entry = xgscd_expected.entry(expected_index);\n auto const expected_argument_m = expected_entry.argument(0);\n auto const expected_argument_u = expected_entry.argument(1);\n auto const expected_value_s = expected_entry.value(0);\n auto const expected_value_c = expected_entry.value(1);\n auto const expected_value_d = expected_entry.value(2);\n EXPECT_THAT(m, IsNear(expected_argument_m, 1.001));\n EXPECT_THAT(u, IsNear(expected_argument_u, 1.001));\n EXPECT_THAT(s, AlmostEquals(expected_value_s, 0, 2));\n EXPECT_THAT(c, AlmostEquals(expected_value_c, 0, 3));\n EXPECT_THAT(d, AlmostEquals(expected_value_d, 0, 1));\n ++expected_index;\n }\n std::printf(\"\\n\");\n }\n}\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Note - pyconfig.h must be included before condor_common to avoid\n\/\/ re-definition warnings.\n# include <pyconfig.h>\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_version.h\"\n#include \"param_info.h\"\n\n#include <boost\/python.hpp>\n\n#include \"old_boost.h\"\n\nusing namespace boost::python;\n\nstruct Param\n{\n bool contains(const std::string &attr)\n {\n std::string result;\n return param(result, attr.c_str());\n }\n\n\n static object param_to_py(const char *attr, const MACRO_META *pmeta, const char *raw_string)\n {\n param_info_t_type_t ty = param_default_type_by_id(pmeta->param_id);\n object pyresult;\n switch (ty)\n {\n case PARAM_TYPE_STRING:\n {\n std::string result;\n if (!param(result, attr)) { THROW_EX(ValueError, (\"Unable to convert value for param \" + std::string(attr) + \" to string (raw value \" + raw_string + \")\").c_str()); }\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_INT:\n {\n int result = param_integer(attr);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_BOOL:\n {\n bool result = param_boolean(attr, result);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_DOUBLE:\n {\n double result = param_double(attr);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_LONG:\n {\n long long result = param_integer(attr, result);\n pyresult = object(result);\n break;\n }\n }\n return pyresult;\n }\n\n\n object getitem_impl(const std::string &attr, object default_val, bool throw_exception)\n {\n MyString name_used;\n const char *pdef_value;\n const MACRO_META *pmeta;\n const char * result_str = param_get_info(attr.c_str(), NULL, NULL, name_used, &pdef_value, &pmeta);\n if (!result_str)\n {\n if (throw_exception)\n {\n THROW_EX(KeyError, attr.c_str());\n }\n else\n {\n return default_val;\n }\n }\n try\n {\n return param_to_py(attr.c_str(), pmeta, result_str);\n }\n catch (error_already_set)\n {\n PyErr_Clear();\n return object(result_str);\n }\n }\n\n\n object getitem(const std::string &attr)\n {\n return getitem_impl(attr, object(), true);\n }\n\n\n object get(const std::string &attr, object default_val)\n {\n return getitem_impl(attr, default_val, false);\n }\n\n\n void setitem(const std::string &attr, const std::string &val)\n {\n param_insert(attr.c_str(), val.c_str());\n }\n\n\n std::string setdefault(const std::string &attr, const std::string &def)\n {\n std::string result;\n if (!param(result, attr.c_str()))\n {\n param_insert(attr.c_str(), def.c_str());\n return def;\n }\n return result;\n }\n\n\n static bool keys_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) { return true; }\n\n list &results = *static_cast<list*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n try\n {\n results.append(name);\n }\n catch (error_already_set)\n {\n \/\/ Suppress the C++ exception. The HTCondor code is not thread safe.\n }\n return true;\n }\n\n\n list keys()\n {\n list results;\n void *results_ptr = static_cast<void*>(&results);\n foreach_param(0, &keys_processor, results_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return results;\n }\n\n\n object iter()\n {\n return keys().attr(\"__iter__\")();\n }\n\n\n static bool len_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) { return true; }\n\n unsigned long &result = *static_cast<unsigned long*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n result++;\n return true;\n }\n\n\n unsigned long len()\n {\n unsigned long result = 0;\n void *result_ptr = static_cast<void*>(&result);\n foreach_param(0, &len_processor, result_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return result;\n }\n\n\n static bool items_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) return true;\n\n list &results = *static_cast<list*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n try\n {\n MACRO_META *pmeta = hash_iter_meta(it);\n object pyvalue;\n try\n {\n pyvalue = param_to_py(name, pmeta, value);\n }\n catch (error_already_set)\n {\n PyErr_Clear();\n pyvalue = object(value);\n }\n results.append(make_tuple<std::string, object>(name, pyvalue));\n }\n catch (error_already_set)\n {\n \/\/ Suppress the python-to-C++ exception. The HTCondor code is not thread safe.\n \/\/ This will set PyErr_Occurred so eventually the python exception fires.\n }\n return true;\n }\n\n\n list items()\n {\n list results;\n void *results_ptr = static_cast<void*>(&results);\n foreach_param(0, &items_processor, results_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return results;\n }\n\n void update(boost::python::object source)\n {\n \/\/ See if we have a dictionary-like object.\n if (py_hasattr(source, \"items\"))\n {\n return this->update(source.attr(\"items\")());\n }\n if (!py_hasattr(source, \"__iter__\")) { THROW_EX(ValueError, \"Must provide a dictionary-like object to update()\"); }\n\n object iter = source.attr(\"__iter__\")();\n while (true) {\n PyObject *pyobj = PyIter_Next(iter.ptr());\n if (!pyobj) break;\n if (PyErr_Occurred()) {\n throw_error_already_set();\n }\n\n object obj = object(handle<>(pyobj));\n\n tuple tup = extract<tuple>(obj);\n std::string attr = extract<std::string>(tup[0]);\n std::string value = extract<std::string>(tup[1]);\n setitem(attr, value);\n }\n }\n\n};\n\nstd::string CondorVersionWrapper() { return CondorVersion(); }\n\nstd::string CondorPlatformWrapper() { return CondorPlatform(); }\n\n\/\/BOOST_PYTHON_FUNCTION_OVERLOADS(config_overloads, config, 0, 3);\nvoid configWrapper() { config(); }\n\nvoid export_config()\n{\n config_ex(CONFIG_OPT_NO_EXIT | CONFIG_OPT_WANT_META);\n def(\"version\", CondorVersionWrapper, \"Returns the version of HTCondor this module is linked against.\");\n def(\"platform\", CondorPlatformWrapper, \"Returns the platform of HTCondor this module is running on.\");\n def(\"reload_config\", configWrapper, \"Reload the HTCondor configuration from disk.\");\n class_<Param>(\"_Param\")\n .def(\"__getitem__\", &Param::getitem)\n .def(\"__setitem__\", &Param::setitem)\n .def(\"__contains__\", &Param::contains)\n .def(\"setdefault\", &Param::setdefault)\n .def(\"get\", &Param::get, \"Returns the value associated with the key; if the key is not a defined parameter, returns the default argument. Default is None.\", (arg(\"self\"), arg(\"key\"), arg(\"default\")=object()))\n .def(\"keys\", &Param::keys)\n .def(\"__iter__\", &Param::iter)\n .def(\"__len__\", &Param::len)\n .def(\"items\", &Param::items)\n .def(\"update\", &Param::update)\n ;\n object param = object(Param());\n param.attr(\"__doc__\") = \"A dictionary-like object containing the HTCondor configuration.\";\n scope().attr(\"param\") = param;\n}\n<commit_msg>Avoid warnings on Fedora. #4336<commit_after>\n\/\/ Note - pyconfig.h must be included before condor_common to avoid\n\/\/ re-definition warnings.\n# include <pyconfig.h>\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_version.h\"\n#include \"param_info.h\"\n\n#include <boost\/python.hpp>\n\n#include \"old_boost.h\"\n\nusing namespace boost::python;\n\nstruct Param\n{\n bool contains(const std::string &attr)\n {\n std::string result;\n return param(result, attr.c_str());\n }\n\n\n static object param_to_py(const char *attr, const MACRO_META *pmeta, const char *raw_string)\n {\n param_info_t_type_t ty = param_default_type_by_id(pmeta->param_id);\n object pyresult;\n switch (ty)\n {\n case PARAM_TYPE_STRING:\n {\n std::string result;\n if (!param(result, attr)) { THROW_EX(ValueError, (\"Unable to convert value for param \" + std::string(attr) + \" to string (raw value \" + raw_string + \")\").c_str()); }\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_INT:\n {\n int result = param_integer(attr);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_BOOL:\n {\n bool result = param_boolean(attr, false);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_DOUBLE:\n {\n double result = param_double(attr);\n pyresult = object(result);\n break;\n }\n case PARAM_TYPE_LONG:\n {\n long long result = param_integer(attr);\n pyresult = object(result);\n break;\n }\n }\n return pyresult;\n }\n\n\n object getitem_impl(const std::string &attr, object default_val, bool throw_exception)\n {\n MyString name_used;\n const char *pdef_value;\n const MACRO_META *pmeta;\n const char * result_str = param_get_info(attr.c_str(), NULL, NULL, name_used, &pdef_value, &pmeta);\n if (!result_str)\n {\n if (throw_exception)\n {\n THROW_EX(KeyError, attr.c_str());\n }\n else\n {\n return default_val;\n }\n }\n try\n {\n return param_to_py(attr.c_str(), pmeta, result_str);\n }\n catch (error_already_set)\n {\n PyErr_Clear();\n return object(result_str);\n }\n }\n\n\n object getitem(const std::string &attr)\n {\n return getitem_impl(attr, object(), true);\n }\n\n\n object get(const std::string &attr, object default_val)\n {\n return getitem_impl(attr, default_val, false);\n }\n\n\n void setitem(const std::string &attr, const std::string &val)\n {\n param_insert(attr.c_str(), val.c_str());\n }\n\n\n std::string setdefault(const std::string &attr, const std::string &def)\n {\n std::string result;\n if (!param(result, attr.c_str()))\n {\n param_insert(attr.c_str(), def.c_str());\n return def;\n }\n return result;\n }\n\n\n static bool keys_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) { return true; }\n\n list &results = *static_cast<list*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n try\n {\n results.append(name);\n }\n catch (error_already_set)\n {\n \/\/ Suppress the C++ exception. The HTCondor code is not thread safe.\n }\n return true;\n }\n\n\n list keys()\n {\n list results;\n void *results_ptr = static_cast<void*>(&results);\n foreach_param(0, &keys_processor, results_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return results;\n }\n\n\n object iter()\n {\n return keys().attr(\"__iter__\")();\n }\n\n\n static bool len_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) { return true; }\n\n unsigned long &result = *static_cast<unsigned long*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n result++;\n return true;\n }\n\n\n unsigned long len()\n {\n unsigned long result = 0;\n void *result_ptr = static_cast<void*>(&result);\n foreach_param(0, &len_processor, result_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return result;\n }\n\n\n static bool items_processor(void* user, HASHITER& it)\n {\n if (PyErr_Occurred()) return true;\n\n list &results = *static_cast<list*>(user);\n const char * name = hash_iter_key(it);\n const char * value = hash_iter_value(it);\n if (!name || !value) { return true; }\n try\n {\n MACRO_META *pmeta = hash_iter_meta(it);\n object pyvalue;\n try\n {\n pyvalue = param_to_py(name, pmeta, value);\n }\n catch (error_already_set)\n {\n PyErr_Clear();\n pyvalue = object(value);\n }\n results.append(make_tuple<std::string, object>(name, pyvalue));\n }\n catch (error_already_set)\n {\n \/\/ Suppress the python-to-C++ exception. The HTCondor code is not thread safe.\n \/\/ This will set PyErr_Occurred so eventually the python exception fires.\n }\n return true;\n }\n\n\n list items()\n {\n list results;\n void *results_ptr = static_cast<void*>(&results);\n foreach_param(0, &items_processor, results_ptr);\n if (PyErr_Occurred())\n {\n throw_error_already_set();\n }\n return results;\n }\n\n void update(boost::python::object source)\n {\n \/\/ See if we have a dictionary-like object.\n if (py_hasattr(source, \"items\"))\n {\n return this->update(source.attr(\"items\")());\n }\n if (!py_hasattr(source, \"__iter__\")) { THROW_EX(ValueError, \"Must provide a dictionary-like object to update()\"); }\n\n object iter = source.attr(\"__iter__\")();\n while (true) {\n PyObject *pyobj = PyIter_Next(iter.ptr());\n if (!pyobj) break;\n if (PyErr_Occurred()) {\n throw_error_already_set();\n }\n\n object obj = object(handle<>(pyobj));\n\n tuple tup = extract<tuple>(obj);\n std::string attr = extract<std::string>(tup[0]);\n std::string value = extract<std::string>(tup[1]);\n setitem(attr, value);\n }\n }\n\n};\n\nstd::string CondorVersionWrapper() { return CondorVersion(); }\n\nstd::string CondorPlatformWrapper() { return CondorPlatform(); }\n\n\/\/BOOST_PYTHON_FUNCTION_OVERLOADS(config_overloads, config, 0, 3);\nvoid configWrapper() { config(); }\n\nvoid export_config()\n{\n config_ex(CONFIG_OPT_NO_EXIT | CONFIG_OPT_WANT_META);\n def(\"version\", CondorVersionWrapper, \"Returns the version of HTCondor this module is linked against.\");\n def(\"platform\", CondorPlatformWrapper, \"Returns the platform of HTCondor this module is running on.\");\n def(\"reload_config\", configWrapper, \"Reload the HTCondor configuration from disk.\");\n class_<Param>(\"_Param\")\n .def(\"__getitem__\", &Param::getitem)\n .def(\"__setitem__\", &Param::setitem)\n .def(\"__contains__\", &Param::contains)\n .def(\"setdefault\", &Param::setdefault)\n .def(\"get\", &Param::get, \"Returns the value associated with the key; if the key is not a defined parameter, returns the default argument. Default is None.\", (arg(\"self\"), arg(\"key\"), arg(\"default\")=object()))\n .def(\"keys\", &Param::keys)\n .def(\"__iter__\", &Param::iter)\n .def(\"__len__\", &Param::len)\n .def(\"items\", &Param::items)\n .def(\"update\", &Param::update)\n ;\n object param = object(Param());\n param.attr(\"__doc__\") = \"A dictionary-like object containing the HTCondor configuration.\";\n scope().attr(\"param\") = param;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ lab2\n\/\/\n\/\/ Created by Dylan Brown on 2\/5\/14.\n\/\/ Copyright (c) 2014 Dylan Brown. All rights reserved.\n\/\/\n\n#include <iostream>\n#include \"BitMap.h\"\n#include \"FreeList.h\"\n\nint main(int argc, const char * argv[])\n{\n \n \/* Create a BitMap object and blocks array *\/\n BitMap map = BitMap();\n const int numBlocks = 10;\n unsigned int blocks[numBlocks] = {0};\n \n \/* Output the blocks array, or error if search failed *\/\n if (map.search(numBlocks, blocks)) {\n std::cout << \"List of \" << numBlocks << \" available blocks: \";\n for (int i = 0; i < numBlocks; i++) {\n std::cout << blocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n \n \/* Test writeBlocks and deleteBlocks *\/\n map.writeBlocks(numBlocks, blocks);\n unsigned int testBlocks[numBlocks];\n if (map.search(numBlocks, testBlocks)) {\n std::cout << \"List of \" << numBlocks << \" available blocks: \";\n for (int i = 0; i < numBlocks; i++) {\n std::cout << testBlocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n map.deleteBlocks(numBlocks, blocks);\n if (map.search(numBlocks, testBlocks)) {\n std::cout << \"List of \" << numBlocks << \" available blocks: \";\n for (int i = 0; i < numBlocks; i++) {\n std::cout << testBlocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n \n \/* Test consecutive search *\/\n unsigned int consecutiveBlocks[numBlocks];\n unsigned int *blockAddress = consecutiveBlocks;\n if (map.searchConsecutive(numBlocks, 1, blockAddress)) {\n std::cout << \"List of \" << numBlocks << \" consecutive blocks: \";\n for (int i = 0; i < numBlocks; i++) {\n std::cout << consecutiveBlocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n \n \/* Test FreeList *\/\n FreeList freelist = FreeList();\n unsigned int listBlocks[numBlocks];\n freelist.writeBlocks(numBlocks, listBlocks);\n freelist.deleteBlocks(numBlocks, listBlocks);\n if (freelist.writeBlocks(numBlocks, listBlocks)) {\n std::cout << \"List of \" << numBlocks << \" list blocks: \";\n for (int i = 0; i < numBlocks; i++) {\n std::cout << listBlocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n \n return 0;\n}\n<commit_msg>Made main() function of test drivers presentable. No more spaghetti code!<commit_after>\/\/\n\/\/ main.cpp\n\/\/ lab2\n\/\/\n\/\/ Created by Dylan Brown on 2\/5\/14.\n\/\/ Copyright (c) 2014 Dylan Brown. All rights reserved.\n\/\/\n\n#include <iostream>\n#include \"BitMap.h\"\n#include \"FreeList.h\"\n\n\/* Below is a collection of test output functions.\n * The arguments 'BitMap& map' and 'FreeList& freelist' are\n * class instances passed into the functions by reference.\n *\/\n\nvoid testSearch(BitMap& map, int numBlocks, unsigned int blocks[]) {\n if (map.search(numBlocks, blocks)) {\n for (int i = 0; i < numBlocks; i++) {\n std::cout << blocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n}\n\nvoid testSearch(FreeList& freelist, int numBlocks, unsigned int listBlocks[]) {\n if (freelist.writeBlocks(numBlocks, listBlocks)) {\n for (int i = 0; i < numBlocks; i++) {\n std::cout << listBlocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n}\n\nvoid testConsecutiveSearch(BitMap& map, int numBlocks, unsigned int blocks[]) {\n if (map.searchConsecutive(numBlocks, 1, blocks)) {\n for (int i = 0; i < numBlocks; i++) {\n std::cout << blocks[i] << \" \";\n }\n std::cout << \"\\n\";\n } else {\n std::cout << \"Insufficient disk space available!\\n\";\n }\n}\n\nint main(int argc, const char * argv[])\n{\n\n\/\/ (1) TEST the BitMap class\n std::cout << \"-- PART 1: BitMap --\\n\\n\";\n \n \/* Create a BitMap object and blocks array with numBlocks elements initialized to zero *\/\n BitMap map = BitMap();\n const int numBlocks = 10;\n unsigned int blocks[numBlocks] = {0};\n \n \/* Search in the BitMap to fill the blocks array, or error if search failed *\/\n std::cout << \"List of first \" << numBlocks << \" free blocks in BitMap: \";\n testSearch(map, numBlocks, blocks);\n \n \/* Test writeBlocks and search again for numBlocks free blocks *\/\n map.writeBlocks(numBlocks, blocks);\n std::cout << \"\\nBlocks WRITTEN to BitMap.\\n\\n\";\n unsigned int nextBlocks[numBlocks];\n std::cout << \"List of next \" << numBlocks << \" free blocks in BitMap: \";\n testSearch(map, numBlocks, nextBlocks);\n \n \/* Test deleteBlocks and search again for numBlocks free blocks *\/\n map.deleteBlocks(numBlocks, blocks);\n std::cout << \"\\nFirst group of blocks DELETED from BitMap.\\n\\n\";\n std::cout << \"List of next \" << numBlocks << \" free blocks in BitMap: \";\n testSearch(map, numBlocks, blocks);\n \n \/* Test consecutive search *\/\n unsigned int consecutiveBlocks[numBlocks];\n std::cout << \"\\nList of \" << numBlocks << \" consecutive free blocks: \";\n testConsecutiveSearch(map, numBlocks, consecutiveBlocks);\n \n\/\/ (2) TEST the FreeList class\n std::cout << \"\\n\\n-- PART 2: FreeList --\\n\\n\";\n \n \/* Create an instance of FreeList and another array of numBlocks blocks *\/\n FreeList freelist = FreeList();\n unsigned int listBlocks[numBlocks];\n \n \/* Test searching for the first numBlocks blocks in the FreeList *\/\n std::cout << \"Writing to first \" << numBlocks << \" free blocks in FreeList: \";\n testSearch(freelist, numBlocks, listBlocks);\n \n \/* Test the freeing of blocks to the FreeList *\/\n freelist.deleteBlocks(numBlocks, listBlocks);\n std::cout << \"\\nFirst \" << numBlocks << \" blocks DELETED and appended to FreeList.\\n\\n\";\n \n \/* Test searching for the next numBlocks available blocks *\/\n std::cout << \"List of next \" << numBlocks << \" free blocks in FreeList: \";\n testSearch(freelist, numBlocks, listBlocks);\n std::cout << \"\\n\";\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Sketcher: [skip ci] fix bad static_cast<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/bitcoin-config.h>\n#endif\n\n#include <qt\/askpassphrasedialog.h>\n#include <qt\/forms\/ui_askpassphrasedialog.h>\n\n#include <qt\/guiconstants.h>\n#include <qt\/walletmodel.h>\n\n#include <support\/allocators\/secure.h>\n\n#include <QKeyEvent>\n#include <QMessageBox>\n#include <QPushButton>\n\nAskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent, SecureString* passphrase_out) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(_mode),\n model(nullptr),\n fCapsLock(false),\n m_passphrase_out(passphrase_out)\n{\n ui->setupUi(this);\n\n ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());\n ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());\n ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());\n\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->warningLabel->setText(tr(\"Enter the new passphrase for the wallet.<br\/>Please use a passphrase of <b>ten or more random characters<\/b>, or <b>eight or more words<\/b>.\"));\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old passphrase and new passphrase for the wallet.\"));\n break;\n }\n textChanged();\n connect(ui->toggleShowPasswordButton, &QPushButton::toggled, this, &AskPassphraseDialog::toggleShowPassword);\n connect(ui->passEdit1, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n connect(ui->passEdit2, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n connect(ui->passEdit3, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n secureClearPassFields();\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *_model)\n{\n this->model = _model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if (!model && mode != Encrypt)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n secureClearPassFields();\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR VERTCOIN<\/b>!\") + \"<br><br>\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n QString encryption_reminder = tr(\"Remember that encrypting your wallet cannot fully protect \"\n \"your bitcoins from being stolen by malware infecting your computer.\");\n if (m_passphrase_out) {\n m_passphrase_out->assign(newpass1);\n QMessageBox::warning(this, tr(\"Wallet to be encrypted\"),\n \"<qt>\" +\n tr(\"Your wallet is about to be encrypted. \") + encryption_reminder +\n \"<\/b><\/qt>\");\n } else {\n assert(model != nullptr);\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"<qt>\" +\n tr(\"Your wallet is now encrypted. \") + encryption_reminder +\n \"<br><br><b>\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n try {\n if (!model->setWalletLocked(false, oldpass)) {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n } else {\n QDialog::accept(); \/\/ Success\n }\n } catch (const std::runtime_error& e) {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"), e.what());\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nvoid AskPassphraseDialog::toggleShowPassword(bool show)\n{\n ui->toggleShowPasswordButton->setDown(show);\n const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;\n ui->passEdit1->setEchoMode(mode);\n ui->passEdit2->setEchoMode(mode);\n ui->passEdit3->setEchoMode(mode);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\n\nstatic void SecureClearQLineEdit(QLineEdit* edit)\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n edit->setText(QString(\" \").repeated(edit->text().size()));\n edit->clear();\n}\n\nvoid AskPassphraseDialog::secureClearPassFields()\n{\n SecureClearQLineEdit(ui->passEdit1);\n SecureClearQLineEdit(ui->passEdit2);\n SecureClearQLineEdit(ui->passEdit3);\n}\n<commit_msg>Update askpassphrasedialog.cpp<commit_after>\/\/ Copyright (c) 2011-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/bitcoin-config.h>\n#endif\n\n#include <qt\/askpassphrasedialog.h>\n#include <qt\/forms\/ui_askpassphrasedialog.h>\n\n#include <qt\/guiconstants.h>\n#include <qt\/walletmodel.h>\n\n#include <support\/allocators\/secure.h>\n\n#include <QKeyEvent>\n#include <QMessageBox>\n#include <QPushButton>\n\nAskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent, SecureString* passphrase_out) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(_mode),\n model(nullptr),\n fCapsLock(false),\n m_passphrase_out(passphrase_out)\n{\n ui->setupUi(this);\n\n ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());\n ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());\n ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());\n\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->warningLabel->setText(tr(\"Enter the new passphrase for the wallet.<br\/>Please use a passphrase of <b>ten or more random characters<\/b>, or <b>eight or more words<\/b>.\"));\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old passphrase and new passphrase for the wallet.\"));\n break;\n }\n textChanged();\n connect(ui->toggleShowPasswordButton, &QPushButton::toggled, this, &AskPassphraseDialog::toggleShowPassword);\n connect(ui->passEdit1, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n connect(ui->passEdit2, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n connect(ui->passEdit3, &QLineEdit::textChanged, this, &AskPassphraseDialog::textChanged);\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n secureClearPassFields();\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *_model)\n{\n this->model = _model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if (!model && mode != Encrypt)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n secureClearPassFields();\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR VERTCOIN<\/b>!\") + \"<br><br>\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n QString encryption_reminder = tr(\"Remember that encrypting your wallet cannot fully protect \"\n \"your vertcoin from being stolen by malware infecting your computer.\");\n if (m_passphrase_out) {\n m_passphrase_out->assign(newpass1);\n QMessageBox::warning(this, tr(\"Wallet to be encrypted\"),\n \"<qt>\" +\n tr(\"Your wallet is about to be encrypted. \") + encryption_reminder +\n \"<\/b><\/qt>\");\n } else {\n assert(model != nullptr);\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"<qt>\" +\n tr(\"Your wallet is now encrypted. \") + encryption_reminder +\n \"<br><br><b>\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n try {\n if (!model->setWalletLocked(false, oldpass)) {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n } else {\n QDialog::accept(); \/\/ Success\n }\n } catch (const std::runtime_error& e) {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"), e.what());\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nvoid AskPassphraseDialog::toggleShowPassword(bool show)\n{\n ui->toggleShowPasswordButton->setDown(show);\n const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;\n ui->passEdit1->setEchoMode(mode);\n ui->passEdit2->setEchoMode(mode);\n ui->passEdit3->setEchoMode(mode);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\n\nstatic void SecureClearQLineEdit(QLineEdit* edit)\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n edit->setText(QString(\" \").repeated(edit->text().size()));\n edit->clear();\n}\n\nvoid AskPassphraseDialog::secureClearPassFields()\n{\n SecureClearQLineEdit(ui->passEdit1);\n SecureClearQLineEdit(ui->passEdit2);\n SecureClearQLineEdit(ui->passEdit3);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n @file XYZReader.hpp\n @brief definition of a class that reads xyz file.\n \n @author Toru Niina (niina.toru.68u@gmail.com)\n @date 2017-01-05 17:00\n @copyright Toru Niina 2016 on MIT License\n*\/\n\n#ifndef COFFEE_MILL_XYZ_READER\n#define COFFEE_MILL_XYZ_READER\n#include <mill\/data\/XYZData.hpp>\n#include <memory>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace mill\n{\n\n\/\/! read XYZfile and return the data as std::vector<std::vector<position>>.\n\/*!\n * @tparam vectorT type of position\n *\/\ntemplate<typename vectorT>\nclass XYZReader\n{\n public:\n using vector_type = vectorT;\n using position_type = vector_type;\n using frame_type = XYZFrame<position_type>;\n using trajectory_type = std::vector<frame_type>;\n\n public:\n\n XYZReader(const std::string& fname): xyz_(fname)\n {\n if(!xyz_.good())\n {\n throw std::runtime_error(\"XYZReader: file open error: \" + fname);\n }\n }\n ~XYZReader() = default;\n\n trajectory_type read();\n snapshot_type read_frame();\n\n bool is_eof() const noexcept {return xyz_.eof();}\n\n private:\n std::ifstream xyz_;\n};\n\ntemplate<typename vecT>\ntypename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()\n{\n trajectory_type traj;\n while(!this->xyz_.eof())\n {\n traj.push_back(this->read_frame());\n }\n return traj;\n}\n\ntemplate<typename vecT>\ntypename XYZReader<vecT>::frame_type XYZReader<vecT>::read_frame()\n{\n std::string line;\n std::getline(this->xyz_, line);\n std::size_t N = 0;\n try\n {\n N = std::stoull(line);\n }\n catch(...)\n {\n throw std::runtime_error(\"XYZReader::read_frame: expected number, \"\n \"but get \" + line);\n }\n frame_type frame;\n std::getline(this->xyz_, frame.comment);\n frame.particles.reserve(N);\n\n for(std::size_t i=0; i<N; ++i)\n {\n std::getline(this->xyz_, line);\n std::istringstream iss(line);\n std::string atom;\n double x, y, z;\n iss >> atom >> x >> y >> z;\n frame.particles.emplace_back(atom, vector_type(x, y, z));\n }\n return frame;\n}\n\n}\/\/ mill\n#endif \/\/COFFEE_MILL_XYZ_READER\n<commit_msg>fix: peek before checking eof flag<commit_after>\/*!\n @file XYZReader.hpp\n @brief definition of a class that reads xyz file.\n \n @author Toru Niina (niina.toru.68u@gmail.com)\n @date 2017-01-05 17:00\n @copyright Toru Niina 2016 on MIT License\n*\/\n\n#ifndef COFFEE_MILL_XYZ_READER\n#define COFFEE_MILL_XYZ_READER\n#include <mill\/data\/XYZData.hpp>\n#include <memory>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace mill\n{\n\n\/\/! read XYZfile and return the data as std::vector<std::vector<position>>.\n\/*!\n * @tparam vectorT type of position\n *\/\ntemplate<typename vectorT>\nclass XYZReader\n{\n public:\n using vector_type = vectorT;\n using position_type = vector_type;\n using frame_type = XYZFrame<position_type>;\n using snapshot_type = frame_type;\n using trajectory_type = std::vector<frame_type>;\n\n public:\n\n XYZReader(const std::string& fname): xyz_(fname)\n {\n if(!xyz_.good())\n {\n throw std::runtime_error(\"XYZReader: file open error: \" + fname);\n }\n }\n ~XYZReader() = default;\n\n trajectory_type read();\n snapshot_type read_frame();\n\n bool is_eof() const noexcept {return xyz_.eof();}\n\n private:\n std::ifstream xyz_;\n};\n\ntemplate<typename vecT>\ntypename XYZReader<vecT>::trajectory_type XYZReader<vecT>::read()\n{\n trajectory_type traj;\n while(!this->xyz_.eof())\n {\n traj.push_back(this->read_frame());\n this->xyz_.peek();\n }\n return traj;\n}\n\ntemplate<typename vecT>\ntypename XYZReader<vecT>::frame_type XYZReader<vecT>::read_frame()\n{\n std::string line;\n std::getline(this->xyz_, line);\n std::size_t N = 0;\n try\n {\n N = std::stoull(line);\n }\n catch(...)\n {\n throw std::runtime_error(\"XYZReader::read_frame: expected number, \"\n \"but get \" + line);\n }\n frame_type frame;\n std::getline(this->xyz_, frame.comment);\n frame.particles.reserve(N);\n\n for(std::size_t i=0; i<N; ++i)\n {\n std::getline(this->xyz_, line);\n std::istringstream iss(line);\n std::string atom;\n double x, y, z;\n iss >> atom >> x >> y >> z;\n frame.particles.emplace_back(atom, vector_type(x, y, z));\n }\n return frame;\n}\n\n}\/\/ mill\n#endif \/\/COFFEE_MILL_XYZ_READER\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * TIGHTDB CONFIDENTIAL\n * __________________\n *\n * [2011] - [2014] TightDB Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n\n#ifndef TIGHTDB_OBJC_UTIL_HPP\n#define TIGHTDB_OBJC_UTIL_HPP\n\n#include <cstddef>\n#include <stdexcept>\n\n#include <tightdb\/util\/safe_int_ops.hpp>\n#include <tightdb\/util\/file.hpp>\n#include <tightdb\/string_data.hpp>\n#include <tightdb\/mixed.hpp>\n#include <tightdb\/descriptor.hpp>\n#include <tightdb\/table.hpp>\n#include <tightdb\/table_ref.hpp>\n\nstruct ObjcStringAccessor {\n ObjcStringAccessor(const NSString* s)\n {\n using namespace std;\n using namespace tightdb;\n NSUInteger size = [s length];\n if (size == 0) {\n m_data = 0;\n m_size = 0;\n }\n else {\n size_t max_size;\n if (util::int_cast_with_overflow_detect([s maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding], max_size))\n throw runtime_error(\"String size overflow\");\n char* data = new char[max_size];\n NSUInteger used;\n NSRange range = NSMakeRange(0, size);\n NSRange remaining_range;\n BOOL at_leat_one = [s getBytes:data maxLength:max_size usedLength:&used encoding:NSUTF8StringEncoding options:0 range:range remainingRange:&remaining_range];\n if (!at_leat_one || remaining_range.length != 0) {\n delete[] data;\n throw runtime_error(\"String transcoding failed\");\n }\n m_data = data;\n m_size = used;\n }\n }\n\n ~ObjcStringAccessor()\n {\n delete[] m_data;\n }\n\n operator tightdb::StringData() const TIGHTDB_NOEXCEPT { return tightdb::StringData(m_data, m_size); }\n\nprivate:\n const char* m_data;\n std::size_t m_size;\n};\n\ninline NSString* to_objc_string(tightdb::StringData s)\n{\n using namespace std;\n using namespace tightdb;\n const char* data = s.data();\n NSUInteger size;\n if (util::int_cast_with_overflow_detect(s.size(), size))\n throw runtime_error(\"String size overflow\");\n return [[NSString alloc] initWithBytes:data length:size encoding:NSUTF8StringEncoding];\n}\n\ninline NSObject* to_objc_object(tightdb::Mixed m)\n{\n switch (m.get_type()) {\n case tightdb::type_Bool:\n return [NSNumber numberWithBool:m.get_bool()];\n case tightdb::type_Int:\n return [NSNumber numberWithLongLong:m.get_int()];\n case tightdb::type_Float:\n return [NSNumber numberWithFloat:m.get_float()];\n case tightdb::type_Double:\n return [NSNumber numberWithDouble:m.get_double()];\n case tightdb::type_DateTime:\n return [NSDate dateWithTimeIntervalSince1970:m.get_datetime().get_datetime()];\n case tightdb::type_String:\n return to_objc_string(m.get_string());\n case tightdb::type_Binary: {\n tightdb::BinaryData bd = m.get_binary();\n return [NSData dataWithBytes:bd.data() length:bd.size()];\n }\n case tightdb::type_Mixed:\n TIGHTDB_ASSERT(false); \/* we should never get here *\/\n case tightdb::type_Table:\n TIGHTDB_ASSERT(false);\n }\n return nil;\n}\n\n\ninline NSUInteger was_not_found(size_t n)\n{\n if (n == tightdb::not_found)\n return (NSUInteger)NSNotFound;\n return (NSUInteger)n;\n}\n\ninline bool nsnumber_is_like_bool(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n \/* @encode(BOOL) is 'B' on iOS 64 and 'c'\n objcType is always 'c'. Therefore compare to \"c\".\n *\/\n return data_type[0] == 'c';\n}\n\ninline bool nsnumber_is_like_integer(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\ninline bool nsnumber_is_like_float(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(float)) == 0 ||\n strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\ninline bool nsnumber_is_like_double(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(double)) == 0 ||\n strcmp(data_type, @encode(float)) == 0 ||\n strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\nvoid to_mixed(id value, tightdb::Mixed& m);\n\nBOOL set_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table, NSObject *obj);\nBOOL verify_object_is_type(id obj, tightdb::DataType type);\nBOOL verify_cell(const tightdb::Descriptor& descr, size_t col_ndx, NSObject *obj);\nNSObject* get_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table);\n\nvoid verify_row(const tightdb::Descriptor& descr, NSArray * data);\nvoid insert_row(size_t ndx, tightdb::Table& table, NSArray * data);\nvoid set_row(size_t ndx, tightdb::Table& table, NSArray *data);\n\nvoid verify_row_with_labels(const tightdb::Descriptor& descr, NSDictionary* data);\nvoid insert_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);\nvoid set_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);\n\nvoid verify_row_from_object(const tightdb::Descriptor& descr, NSObject* data);\nvoid insert_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);\nvoid set_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);\n\n\nBOOL set_columns(tightdb::TableRef& parent, NSArray *schema);\n\n\/\/ Still used in the new error strategy. Perhaps it should be public?\nenum TightdbErr {\n tdb_err_Ok = 0,\n tdb_err_Fail = 1,\n tdb_err_FailRdOnly = 2,\n tdb_err_File_AccessError = 3,\n tdb_err_File_PermissionDenied = 4,\n tdb_err_File_Exists = 5,\n tdb_err_File_NotFound = 6,\n tdb_err_Rollback = 7,\n tdb_err_InvalidDatabase = 8,\n tdb_err_TableNotFound = 9\n};\n\ninline NSError* make_realm_error(TightdbErr code, NSString* desc)\n{\n NSMutableDictionary* details = [NSMutableDictionary dictionary];\n [details setValue:desc forKey:NSLocalizedDescriptionKey];\n return [NSError errorWithDomain:@\"com.realm\" code:code userInfo:details];\n}\n\n#define REALM_OBJC_SIZE_T_NUMBER_IN numberWithUnsignedLong\n#define REALM_OBJC_SIZE_T_NUMBER_OUT unsignedLongValue\n\n#define REALM_EXCEPTION_ERRHANDLER(action, fail_return_value) \\\nREALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, error)\n\n\/\/ This is the old macro, which should be phased out.\n#define REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, err_var) \\\ntry { action } \\\ncatch (tightdb::util::File::AccessError& ex) { \\\n if (err_var) \\\n *err_var = make_realm_error(tdb_err_File_AccessError, [NSString stringWithUTF8String:ex.what()]); \\\n return fail_return_value; \\\n} \\\ncatch (std::exception& ex) { \\\n if (err_var) \\\n *err_var = make_realm_error(tdb_err_Fail, [NSString stringWithUTF8String:ex.what()]); \\\n return fail_return_value; \\\n}\n\n\/\/ This macro is part of the new error strategy, specifically for table value setters.\n#define REALM_EXCEPTION_HANDLER_SETTERS(action, datatype) \\\nif (m_read_only) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:table_is_read_only\" \\\n reason:@\"You tried to modify an immutable table\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif (col_ndx >= self.columnCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:column_index_out_of_bounds\" \\\n reason:@\"The specified column index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif ([self columnTypeOfColumnWithIndex:col_ndx] != datatype) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:illegal_type\" \\\n reason:@\"The supplied type is not compatible with the column type\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif (row_ndx >= self.rowCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:row_index_out_of_bounds\" \\\n reason:@\"The specified row index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\ntry { action } \\\ncatch(std::exception& ex) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:core_exception\" \\\n reason:[NSString stringWithUTF8String:ex.what()] \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n}\n\n#define REALM_EXCEPTION_HANDLER_COLUMN_INDEX_VALID(columnIndex) \\\nif (columnIndex >= self.columnCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:column_index_out_of_bounds\" \\\n reason:@\"The specified column index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\n\n#define REALM_EXCEPTION_HANDLER_CORE_EXCEPTION(action) \\\ntry { action } \\\ncatch(std::exception& ex) { \\\n NSException* exception = [NSException exceptionWithName:@\"tightdb:core_exception\" \\\n reason:[NSString stringWithUTF8String:ex.what()] \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n}\n\n\n#endif \/\/ TIGHTDB_OBJC_UTIL_HPP\n<commit_msg>Updated exception messages<commit_after>\/*************************************************************************\n *\n * TIGHTDB CONFIDENTIAL\n * __________________\n *\n * [2011] - [2014] TightDB Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n\n#ifndef TIGHTDB_OBJC_UTIL_HPP\n#define TIGHTDB_OBJC_UTIL_HPP\n\n#include <cstddef>\n#include <stdexcept>\n\n#include <tightdb\/util\/safe_int_ops.hpp>\n#include <tightdb\/util\/file.hpp>\n#include <tightdb\/string_data.hpp>\n#include <tightdb\/mixed.hpp>\n#include <tightdb\/descriptor.hpp>\n#include <tightdb\/table.hpp>\n#include <tightdb\/table_ref.hpp>\n\nstruct ObjcStringAccessor {\n ObjcStringAccessor(const NSString* s)\n {\n using namespace std;\n using namespace tightdb;\n NSUInteger size = [s length];\n if (size == 0) {\n m_data = 0;\n m_size = 0;\n }\n else {\n size_t max_size;\n if (util::int_cast_with_overflow_detect([s maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding], max_size))\n throw runtime_error(\"String size overflow\");\n char* data = new char[max_size];\n NSUInteger used;\n NSRange range = NSMakeRange(0, size);\n NSRange remaining_range;\n BOOL at_leat_one = [s getBytes:data maxLength:max_size usedLength:&used encoding:NSUTF8StringEncoding options:0 range:range remainingRange:&remaining_range];\n if (!at_leat_one || remaining_range.length != 0) {\n delete[] data;\n throw runtime_error(\"String transcoding failed\");\n }\n m_data = data;\n m_size = used;\n }\n }\n\n ~ObjcStringAccessor()\n {\n delete[] m_data;\n }\n\n operator tightdb::StringData() const TIGHTDB_NOEXCEPT { return tightdb::StringData(m_data, m_size); }\n\nprivate:\n const char* m_data;\n std::size_t m_size;\n};\n\ninline NSString* to_objc_string(tightdb::StringData s)\n{\n using namespace std;\n using namespace tightdb;\n const char* data = s.data();\n NSUInteger size;\n if (util::int_cast_with_overflow_detect(s.size(), size))\n throw runtime_error(\"String size overflow\");\n return [[NSString alloc] initWithBytes:data length:size encoding:NSUTF8StringEncoding];\n}\n\ninline NSObject* to_objc_object(tightdb::Mixed m)\n{\n switch (m.get_type()) {\n case tightdb::type_Bool:\n return [NSNumber numberWithBool:m.get_bool()];\n case tightdb::type_Int:\n return [NSNumber numberWithLongLong:m.get_int()];\n case tightdb::type_Float:\n return [NSNumber numberWithFloat:m.get_float()];\n case tightdb::type_Double:\n return [NSNumber numberWithDouble:m.get_double()];\n case tightdb::type_DateTime:\n return [NSDate dateWithTimeIntervalSince1970:m.get_datetime().get_datetime()];\n case tightdb::type_String:\n return to_objc_string(m.get_string());\n case tightdb::type_Binary: {\n tightdb::BinaryData bd = m.get_binary();\n return [NSData dataWithBytes:bd.data() length:bd.size()];\n }\n case tightdb::type_Mixed:\n TIGHTDB_ASSERT(false); \/* we should never get here *\/\n case tightdb::type_Table:\n TIGHTDB_ASSERT(false);\n }\n return nil;\n}\n\n\ninline NSUInteger was_not_found(size_t n)\n{\n if (n == tightdb::not_found)\n return (NSUInteger)NSNotFound;\n return (NSUInteger)n;\n}\n\ninline bool nsnumber_is_like_bool(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n \/* @encode(BOOL) is 'B' on iOS 64 and 'c'\n objcType is always 'c'. Therefore compare to \"c\".\n *\/\n return data_type[0] == 'c';\n}\n\ninline bool nsnumber_is_like_integer(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\ninline bool nsnumber_is_like_float(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(float)) == 0 ||\n strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\ninline bool nsnumber_is_like_double(NSObject *obj)\n{\n const char* data_type = [(NSNumber *)obj objCType];\n return (strcmp(data_type, @encode(double)) == 0 ||\n strcmp(data_type, @encode(float)) == 0 ||\n strcmp(data_type, @encode(int)) == 0 ||\n strcmp(data_type, @encode(long)) == 0 ||\n strcmp(data_type, @encode(long long)) == 0 ||\n strcmp(data_type, @encode(unsigned int)) == 0 ||\n strcmp(data_type, @encode(unsigned long)) == 0 ||\n strcmp(data_type, @encode(unsigned long long)) == 0);\n}\n\nvoid to_mixed(id value, tightdb::Mixed& m);\n\nBOOL set_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table, NSObject *obj);\nBOOL verify_object_is_type(id obj, tightdb::DataType type);\nBOOL verify_cell(const tightdb::Descriptor& descr, size_t col_ndx, NSObject *obj);\nNSObject* get_cell(size_t col_ndx, size_t row_ndx, tightdb::Table& table);\n\nvoid verify_row(const tightdb::Descriptor& descr, NSArray * data);\nvoid insert_row(size_t ndx, tightdb::Table& table, NSArray * data);\nvoid set_row(size_t ndx, tightdb::Table& table, NSArray *data);\n\nvoid verify_row_with_labels(const tightdb::Descriptor& descr, NSDictionary* data);\nvoid insert_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);\nvoid set_row_with_labels(size_t row_ndx, tightdb::Table& table, NSDictionary *data);\n\nvoid verify_row_from_object(const tightdb::Descriptor& descr, NSObject* data);\nvoid insert_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);\nvoid set_row_from_object(size_t row_ndx, tightdb::Table& table, NSObject *data);\n\n\nBOOL set_columns(tightdb::TableRef& parent, NSArray *schema);\n\n\/\/ Still used in the new error strategy. Perhaps it should be public?\nenum TightdbErr {\n tdb_err_Ok = 0,\n tdb_err_Fail = 1,\n tdb_err_FailRdOnly = 2,\n tdb_err_File_AccessError = 3,\n tdb_err_File_PermissionDenied = 4,\n tdb_err_File_Exists = 5,\n tdb_err_File_NotFound = 6,\n tdb_err_Rollback = 7,\n tdb_err_InvalidDatabase = 8,\n tdb_err_TableNotFound = 9\n};\n\ninline NSError* make_realm_error(TightdbErr code, NSString* desc)\n{\n NSMutableDictionary* details = [NSMutableDictionary dictionary];\n [details setValue:desc forKey:NSLocalizedDescriptionKey];\n return [NSError errorWithDomain:@\"com.realm\" code:code userInfo:details];\n}\n\n#define REALM_OBJC_SIZE_T_NUMBER_IN numberWithUnsignedLong\n#define REALM_OBJC_SIZE_T_NUMBER_OUT unsignedLongValue\n\n#define REALM_EXCEPTION_ERRHANDLER(action, fail_return_value) \\\nREALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, error)\n\n\/\/ This is the old macro, which should be phased out.\n#define REALM_EXCEPTION_ERRHANDLER_EX(action, fail_return_value, err_var) \\\ntry { action } \\\ncatch (tightdb::util::File::AccessError& ex) { \\\n if (err_var) \\\n *err_var = make_realm_error(tdb_err_File_AccessError, [NSString stringWithUTF8String:ex.what()]); \\\n return fail_return_value; \\\n} \\\ncatch (std::exception& ex) { \\\n if (err_var) \\\n *err_var = make_realm_error(tdb_err_Fail, [NSString stringWithUTF8String:ex.what()]); \\\n return fail_return_value; \\\n}\n\n\/\/ This macro is part of the new error strategy, specifically for table value setters.\n#define REALM_EXCEPTION_HANDLER_SETTERS(action, datatype) \\\nif (m_read_only) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:table_is_read_only\" \\\n reason:@\"You tried to modify an immutable table\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif (col_ndx >= self.columnCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:column_index_out_of_bounds\" \\\n reason:@\"The specified column index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif ([self columnTypeOfColumnWithIndex:col_ndx] != datatype) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:illegal_type\" \\\n reason:@\"The supplied type is not compatible with the column type\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\nif (row_ndx >= self.rowCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:row_index_out_of_bounds\" \\\n reason:@\"The specified row index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\ntry { action } \\\ncatch(std::exception& ex) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:core_exception\" \\\n reason:[NSString stringWithUTF8String:ex.what()] \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n}\n\n#define REALM_EXCEPTION_HANDLER_COLUMN_INDEX_VALID(columnIndex) \\\nif (columnIndex >= self.columnCount) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:column_index_out_of_bounds\" \\\n reason:@\"The specified column index is not within the table bounds\" \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n} \\\n\n#define REALM_EXCEPTION_HANDLER_CORE_EXCEPTION(action) \\\ntry { action } \\\ncatch(std::exception& ex) { \\\n NSException* exception = [NSException exceptionWithName:@\"realm:core_exception\" \\\n reason:[NSString stringWithUTF8String:ex.what()] \\\n userInfo:[NSMutableDictionary dictionary]]; \\\n [exception raise]; \\\n}\n\n\n#endif \/\/ TIGHTDB_OBJC_UTIL_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_SYSTEM\n#define MJOLNIR_SYSTEM\n#include \"Particle.hpp\"\n#include <vector>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass System\n{\n public:\n typedef traitsT traits_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n typedef Particle<coordinate_type> particle_type;\n typedef std::vector<particle_type> container_type;\n typedef typename container_type::iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n typedef typename traits_type::boundary_type boundary_type;\n\n System() = default;\n System(std::size_t num_particle) : particles_(num_particle){}\n ~System() = default;\n\n std::size_t size() const noexcept {return particles_.size();}\n\n real_type& pressure() noexcept {return pressure_;}\n real_type pressure() const noexcept {return pressure_;}\n real_type& temperature() noexcept {return temperature_;}\n real_type temperature() const noexcept {return temperature_;}\n real_type& ionic_strength() noexcept {return ionic_strength_;}\n real_type ionic_strength() const noexcept {return ionic_strength_;}\n\n coordinate_type adjust_direction(coordiate_type dr) const noexcept\n {return boundary_.adjust_direction(dr);}\n coordinate_type adjust_position(coordiate_type dr) const noexcept\n {return boundary_.adjust_position(dr);}\n\n particle_type & operator[](std::size_t i) noexcept\n {return particles_[i];}\n particle_type const& operator[](std::size_t i) const noexcept\n {return particles_[i];}\n particle_type & at(std::size_t i) noexcept\n {return particles_.at(i);}\n particle_type const& at(std::size_t i) const noexcept\n {return particles_.at(i);}\n\n iterator begin() noexcept {return particles_.begin();}\n iterator end() noexcept {return particles_.end();}\n const_iterator cbegin() const noexcept {return particles_.cbegin();}\n const_iterator cend() const noexcept {return particles_.cend();}\n\n boundary_type const& boundary() const noexcept {return boundary_;}\n\n private:\n\n real_type temperature_;\n real_type pressure_;\n real_type ionic_strength_;\n boundary_type boundary_;\n container_type particles_;\n};\n\n\n\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_SYSTEM\n<commit_msg>add ctor from particles and boundary to System<commit_after>#ifndef MJOLNIR_SYSTEM\n#define MJOLNIR_SYSTEM\n#include \"Particle.hpp\"\n#include <vector>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass System\n{\n public:\n typedef traitsT traits_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n typedef Particle<coordinate_type> particle_type;\n typedef std::vector<particle_type> container_type;\n typedef typename container_type::iterator iterator;\n typedef typename container_type::const_iterator const_iterator;\n typedef typename traits_type::boundary_type boundary_type;\n\n System() = default;\n ~System() = default;\n\n System(container_type&& pcon, boundary_type&& bound)\n : boundary_(bound), particles(pcon), temperature_(0.), pressure_(0.),\n ionic_strength_(0.)\n {}\n\n std::size_t size() const noexcept {return particles_.size();}\n\n real_type& pressure() noexcept {return pressure_;}\n real_type pressure() const noexcept {return pressure_;}\n real_type& temperature() noexcept {return temperature_;}\n real_type temperature() const noexcept {return temperature_;}\n real_type& ionic_strength() noexcept {return ionic_strength_;}\n real_type ionic_strength() const noexcept {return ionic_strength_;}\n\n coordinate_type adjust_direction(coordiate_type dr) const noexcept\n {return boundary_.adjust_direction(dr);}\n coordinate_type adjust_position(coordiate_type dr) const noexcept\n {return boundary_.adjust_position(dr);}\n\n particle_type & operator[](std::size_t i) noexcept\n {return particles_[i];}\n particle_type const& operator[](std::size_t i) const noexcept\n {return particles_[i];}\n particle_type & at(std::size_t i) noexcept\n {return particles_.at(i);}\n particle_type const& at(std::size_t i) const noexcept\n {return particles_.at(i);}\n\n iterator begin() noexcept {return particles_.begin();}\n iterator end() noexcept {return particles_.end();}\n const_iterator cbegin() const noexcept {return particles_.cbegin();}\n const_iterator cend() const noexcept {return particles_.cend();}\n\n boundary_type const& boundary() const noexcept {return boundary_;}\n\n private:\n\n real_type temperature_;\n real_type pressure_;\n real_type ionic_strength_;\n boundary_type boundary_;\n container_type particles_;\n};\n\n\n\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_SYSTEM\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 Hewlett-Packard Development Company, L.P. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\nextern \"C\" {\n #include <mlt\/framework\/mlt_producer.h>\n #include <mlt\/framework\/mlt_frame.h>\n}\n#include <webvfx\/image.h>\n#include \"factory.h\"\n#include \"service_locker.h\"\n#include \"service_manager.h\"\n\nstatic const char* kWebVfxProducerPropertyName = \"WebVfxProducer\";\nstatic const char* kWebVfxPositionPropertyName = \"webvfx.position\";\n\nstatic int producerGetImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int \/*writable*\/) {\n int error = 0;\n mlt_properties properties = MLT_FRAME_PROPERTIES(frame);\n mlt_producer producer = (mlt_producer)mlt_properties_get_data(properties, kWebVfxProducerPropertyName, NULL);\n mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);\n int size;\n int bpp;\n bool hasTransparency = false;\n {\n MLTWebVfx::ServiceLocker locker(MLT_PRODUCER_SERVICE(producer));\n if (!locker.initialize(*width, *height))\n return 1;\n\n if (mlt_properties_get_int( producer_props, \"transparent\") ) {\n *format = mlt_image_rgb24a;\n hasTransparency = true;\n }\n else {\n *format = mlt_image_rgb24;\n }\n \/\/ Get bpp from image format\n mlt_image_format_size(*format, 0, 0, &bpp);\n size = *width * *height * bpp;\n *buffer = (uint8_t*)mlt_pool_alloc(size);\n\n \/\/ When not using transparency, this will make the background black...\n memset( *buffer, 255, size );\n WebVfx::Image outputImage(*buffer, *width, *height, size, hasTransparency);\n locker.getManager()->render(&outputImage,\n mlt_properties_get_position(properties, kWebVfxPositionPropertyName),\n mlt_producer_get_length(producer), hasTransparency);\n\t}\n mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);\n if (hasTransparency) {\n\t\/\/ Create the alpha channel\n\tint alpha_size = *width * *height;\n\tuint8_t *alpha = (uint8_t *)mlt_pool_alloc( alpha_size );\n\t\/\/ Initialise the alpha\n\tmemset( alpha, 255, alpha_size );\n\tmlt_frame_set_alpha(frame, alpha, alpha_size, mlt_pool_release);\n }\n\n mlt_properties_set_int(properties, \"meta.media.width\", *width);\n mlt_properties_set_int(properties, \"meta.media.height\", *height);\n return error;\n}\n\nstatic int getFrame(mlt_producer producer, mlt_frame_ptr frame, int \/*index*\/) {\n \/\/ Generate a frame\n *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));\n\n if (*frame) {\n \/\/ Obtain properties of frame and producer\n mlt_properties properties = MLT_FRAME_PROPERTIES(*frame);\n\n \/\/ Obtain properties of producer\n \/\/mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);\n\n \/\/ Set the producer on the frame properties\n mlt_properties_set_data(properties, kWebVfxProducerPropertyName, producer, 0, NULL, NULL);\n\n \/\/ Update timecode on the frame we're creating\n mlt_position position = mlt_producer_position(producer);\n mlt_frame_set_position(*frame, position);\n mlt_properties_set_position(properties, kWebVfxPositionPropertyName, position);\n\n \/\/ Push the get_image method\n mlt_frame_push_get_image(*frame, producerGetImage);\n }\n\n \/\/ Calculate the next timecode\n mlt_producer_prepare_next(producer);\n\n return 0;\n}\n\nstatic void producer_close( mlt_producer parent )\n{\n \/\/ Close the parent\n parent->close = NULL;\n mlt_producer_close( parent );\n \/\/ Free the memory\n free( parent );\n}\n\nmlt_service MLTWebVfx::createProducer(mlt_profile profile) {\n mlt_producer producer = mlt_producer_new(profile);\n if (producer) {\n producer->get_frame = getFrame;\n producer->close = (mlt_destructor) producer_close;\n mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );\n mlt_properties_set_int( properties, \"meta.media.progressive\", 1 );\n mlt_properties_set_int( properties, \"meta.media.sample_aspect_num\", 1 );\n mlt_properties_set_int( properties, \"meta.media.sample_aspect_den\", 1 );\n return MLT_PRODUCER_SERVICE(producer);\n }\n return 0;\n}\n<commit_msg>Fix crash in transitions because of missing progressive flag, fix indent<commit_after>\/\/ Copyright (c) 2010 Hewlett-Packard Development Company, L.P. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\nextern \"C\" {\n #include <mlt\/framework\/mlt_producer.h>\n #include <mlt\/framework\/mlt_frame.h>\n}\n#include <webvfx\/image.h>\n#include \"factory.h\"\n#include \"service_locker.h\"\n#include \"service_manager.h\"\n\nstatic const char* kWebVfxProducerPropertyName = \"WebVfxProducer\";\nstatic const char* kWebVfxPositionPropertyName = \"webvfx.position\";\n\nstatic int producerGetImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int \/*writable*\/) {\n int error = 0;\n mlt_properties properties = MLT_FRAME_PROPERTIES(frame);\n mlt_producer producer = (mlt_producer)mlt_properties_get_data(properties, kWebVfxProducerPropertyName, NULL);\n mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);\n int size;\n int bpp;\n bool hasTransparency = false;\n {\n MLTWebVfx::ServiceLocker locker(MLT_PRODUCER_SERVICE(producer));\n if (!locker.initialize(*width, *height))\n return 1;\n\n if (mlt_properties_get_int( producer_props, \"transparent\") ) {\n *format = mlt_image_rgb24a;\n hasTransparency = true;\n }\n else {\n *format = mlt_image_rgb24;\n }\n \/\/ Get bpp from image format\n mlt_image_format_size(*format, 0, 0, &bpp);\n size = *width * *height * bpp;\n *buffer = (uint8_t*)mlt_pool_alloc(size);\n\n \/\/ When not using transparency, this will make the background black...\n memset( *buffer, 255, size );\n WebVfx::Image outputImage(*buffer, *width, *height, size, hasTransparency);\n locker.getManager()->render(&outputImage,\n mlt_properties_get_position(properties, kWebVfxPositionPropertyName),\n mlt_producer_get_length(producer), hasTransparency);\n }\n mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);\n if (hasTransparency) {\n \/\/ Create the alpha channel\n int alpha_size = *width * *height;\n uint8_t *alpha = (uint8_t *)mlt_pool_alloc( alpha_size );\n \/\/ Initialise the alpha\n memset( alpha, 255, alpha_size );\n mlt_frame_set_alpha(frame, alpha, alpha_size, mlt_pool_release);\n }\n\n mlt_properties_set_int(properties, \"meta.media.width\", *width);\n mlt_properties_set_int(properties, \"meta.media.height\", *height);\n return error;\n}\n\nstatic int getFrame(mlt_producer producer, mlt_frame_ptr frame, int \/*index*\/) {\n \/\/ Generate a frame\n *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));\n\n if (*frame) {\n \/\/ Obtain properties of frame and producer\n mlt_properties properties = MLT_FRAME_PROPERTIES(*frame);\n\n \/\/ Set the producer on the frame properties\n mlt_properties_set_data(properties, kWebVfxProducerPropertyName, producer, 0, NULL, NULL);\n\n \/\/ Update timecode on the frame we're creating\n mlt_position position = mlt_producer_position(producer);\n mlt_frame_set_position(*frame, position);\n mlt_properties_set_position(properties, kWebVfxPositionPropertyName, position);\n \n \/\/ Set producer-specific frame properties\n mlt_properties_set_int(properties, \"progressive\", 1);\n\n \/\/ Push the get_image method\n mlt_frame_push_get_image(*frame, producerGetImage);\n }\n\n \/\/ Calculate the next timecode\n mlt_producer_prepare_next(producer);\n\n return 0;\n}\n\nstatic void producer_close( mlt_producer parent )\n{\n \/\/ Close the parent\n parent->close = NULL;\n mlt_producer_close( parent );\n \/\/ Free the memory\n free( parent );\n}\n\nmlt_service MLTWebVfx::createProducer(mlt_profile profile) {\n mlt_producer producer = mlt_producer_new(profile);\n if (producer) {\n producer->get_frame = getFrame;\n producer->close = (mlt_destructor) producer_close;\n mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );\n mlt_properties_set_int( properties, \"meta.media.progressive\", 1 );\n mlt_properties_set_int( properties, \"meta.media.sample_aspect_num\", 1 );\n mlt_properties_set_int( properties, \"meta.media.sample_aspect_den\", 1 );\n return MLT_PRODUCER_SERVICE(producer);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <eosio\/trace_api\/common.hpp>\n#include <eosio\/trace_api\/trace.hpp>\n#include <eosio\/trace_api\/extract_util.hpp>\n#include <exception>\n#include <functional>\n#include <map>\n\nnamespace eosio { namespace trace_api {\n\nusing chain::transaction_id_type;\nusing chain::packed_transaction;\n\ntemplate <typename StoreProvider>\nclass chain_extraction_impl_type {\npublic:\n \/**\n * Chain Extractor for capturing transaction traces, action traces, and block info.\n * @param store provider of append & append_lib\n * @param except_handler called on exceptions, logging if any is left to the user\n *\/\n chain_extraction_impl_type( StoreProvider store, exception_handler except_handler )\n : store(std::move(store))\n , except_handler(std::move(except_handler))\n {}\n\n \/\/\/ connect to chain controller applied_transaction signal\n void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::packed_transaction_ptr& ptrx ) {\n on_applied_transaction( trace, ptrx );\n }\n\n \/\/\/ connect to chain controller accepted_block signal\n void signal_accepted_block( const chain::block_state_ptr& bsp ) {\n on_accepted_block( bsp );\n }\n\n \/\/\/ connect to chain controller irreversible_block signal\n void signal_irreversible_block( const chain::block_state_ptr& bsp ) {\n on_irreversible_block( bsp );\n }\n\nprivate:\n static bool is_onblock(const chain::transaction_trace_ptr& p) {\n if (p->action_traces.empty())\n return false;\n const auto& act = p->action_traces[0].act;\n if (act.account != eosio::chain::config::system_account_name || act.name != N(onblock) ||\n act.authorization.size() != 1)\n return false;\n const auto& auth = act.authorization[0];\n return auth.actor == eosio::chain::config::system_account_name &&\n auth.permission == eosio::chain::config::active_name;\n }\n\n void on_applied_transaction(const chain::transaction_trace_ptr& trace, const chain::packed_transaction_ptr& t) {\n if( !trace->receipt ) return;\n \/\/ include only executed transactions; soft_fail included so that onerror (and any inlines via onerror) are included\n if((trace->receipt->status != chain::transaction_receipt_header::executed &&\n trace->receipt->status != chain::transaction_receipt_header::soft_fail)) {\n return;\n }\n if( is_onblock( trace )) {\n onblock_trace.emplace( cache_trace{trace, t} );\n } else if( trace->failed_dtrx_trace ) {\n cached_traces[trace->failed_dtrx_trace->id] = {trace, t};\n } else {\n cached_traces[trace->id] = {trace, t};\n }\n }\n\n void on_accepted_block(const chain::block_state_ptr& block_state) {\n store_block_trace( block_state );\n }\n\n void on_irreversible_block( const chain::block_state_ptr& block_state ) {\n store_lib( block_state );\n }\n\n void store_block_trace( const chain::block_state_ptr& block_state ) {\n try {\n block_trace_v1 bt = create_block_trace_v1( block_state );\n\n std::vector<transaction_trace_v1>& traces = bt.transactions_v1;\n traces.reserve( block_state->block->transactions.size() + 1 );\n if( onblock_trace )\n traces.emplace_back( to_transaction_trace_v1( {*onblock_trace} ));\n for( const auto& r : block_state->block->transactions ) {\n transaction_id_type id;\n if( r.trx.contains<transaction_id_type>()) {\n id = r.trx.get<transaction_id_type>();\n } else {\n id = r.trx.get<packed_transaction>().id();\n }\n const auto it = cached_traces.find( id );\n if( it != cached_traces.end() ) {\n traces.emplace_back( to_transaction_trace_v1( it->second ));\n }\n }\n cached_traces.clear();\n onblock_trace.reset();\n\n store.append( std::move( bt ) );\n\n } catch( ... ) {\n except_handler( MAKE_EXCEPTION_WITH_CONTEXT( std::current_exception() ) );\n }\n }\n\n void store_lib( const chain::block_state_ptr& bsp ) {\n try {\n store.append_lib( bsp->block_num );\n } catch( ... ) {\n except_handler( MAKE_EXCEPTION_WITH_CONTEXT( std::current_exception() ) );\n }\n }\n\nprivate:\n StoreProvider store;\n exception_handler except_handler;\n std::map<transaction_id_type, cache_trace> cached_traces;\n fc::optional<cache_trace> onblock_trace;\n\n};\n\n}}<commit_msg>Remove unneded {}<commit_after>#pragma once\n\n#include <eosio\/trace_api\/common.hpp>\n#include <eosio\/trace_api\/trace.hpp>\n#include <eosio\/trace_api\/extract_util.hpp>\n#include <exception>\n#include <functional>\n#include <map>\n\nnamespace eosio { namespace trace_api {\n\nusing chain::transaction_id_type;\nusing chain::packed_transaction;\n\ntemplate <typename StoreProvider>\nclass chain_extraction_impl_type {\npublic:\n \/**\n * Chain Extractor for capturing transaction traces, action traces, and block info.\n * @param store provider of append & append_lib\n * @param except_handler called on exceptions, logging if any is left to the user\n *\/\n chain_extraction_impl_type( StoreProvider store, exception_handler except_handler )\n : store(std::move(store))\n , except_handler(std::move(except_handler))\n {}\n\n \/\/\/ connect to chain controller applied_transaction signal\n void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::packed_transaction_ptr& ptrx ) {\n on_applied_transaction( trace, ptrx );\n }\n\n \/\/\/ connect to chain controller accepted_block signal\n void signal_accepted_block( const chain::block_state_ptr& bsp ) {\n on_accepted_block( bsp );\n }\n\n \/\/\/ connect to chain controller irreversible_block signal\n void signal_irreversible_block( const chain::block_state_ptr& bsp ) {\n on_irreversible_block( bsp );\n }\n\nprivate:\n static bool is_onblock(const chain::transaction_trace_ptr& p) {\n if (p->action_traces.empty())\n return false;\n const auto& act = p->action_traces[0].act;\n if (act.account != eosio::chain::config::system_account_name || act.name != N(onblock) ||\n act.authorization.size() != 1)\n return false;\n const auto& auth = act.authorization[0];\n return auth.actor == eosio::chain::config::system_account_name &&\n auth.permission == eosio::chain::config::active_name;\n }\n\n void on_applied_transaction(const chain::transaction_trace_ptr& trace, const chain::packed_transaction_ptr& t) {\n if( !trace->receipt ) return;\n \/\/ include only executed transactions; soft_fail included so that onerror (and any inlines via onerror) are included\n if((trace->receipt->status != chain::transaction_receipt_header::executed &&\n trace->receipt->status != chain::transaction_receipt_header::soft_fail)) {\n return;\n }\n if( is_onblock( trace )) {\n onblock_trace.emplace( cache_trace{trace, t} );\n } else if( trace->failed_dtrx_trace ) {\n cached_traces[trace->failed_dtrx_trace->id] = {trace, t};\n } else {\n cached_traces[trace->id] = {trace, t};\n }\n }\n\n void on_accepted_block(const chain::block_state_ptr& block_state) {\n store_block_trace( block_state );\n }\n\n void on_irreversible_block( const chain::block_state_ptr& block_state ) {\n store_lib( block_state );\n }\n\n void store_block_trace( const chain::block_state_ptr& block_state ) {\n try {\n block_trace_v1 bt = create_block_trace_v1( block_state );\n\n std::vector<transaction_trace_v1>& traces = bt.transactions_v1;\n traces.reserve( block_state->block->transactions.size() + 1 );\n if( onblock_trace )\n traces.emplace_back( to_transaction_trace_v1( *onblock_trace ));\n for( const auto& r : block_state->block->transactions ) {\n transaction_id_type id;\n if( r.trx.contains<transaction_id_type>()) {\n id = r.trx.get<transaction_id_type>();\n } else {\n id = r.trx.get<packed_transaction>().id();\n }\n const auto it = cached_traces.find( id );\n if( it != cached_traces.end() ) {\n traces.emplace_back( to_transaction_trace_v1( it->second ));\n }\n }\n cached_traces.clear();\n onblock_trace.reset();\n\n store.append( std::move( bt ) );\n\n } catch( ... ) {\n except_handler( MAKE_EXCEPTION_WITH_CONTEXT( std::current_exception() ) );\n }\n }\n\n void store_lib( const chain::block_state_ptr& bsp ) {\n try {\n store.append_lib( bsp->block_num );\n } catch( ... ) {\n except_handler( MAKE_EXCEPTION_WITH_CONTEXT( std::current_exception() ) );\n }\n }\n\nprivate:\n StoreProvider store;\n exception_handler except_handler;\n std::map<transaction_id_type, cache_trace> cached_traces;\n fc::optional<cache_trace> onblock_trace;\n\n};\n\n}}<|endoftext|>"} {"text":"<commit_before>#include \"getusername.h\"\n#include <errno.h>\n#include <langinfo.h>\n#include <locale.h>\n#include <unistd.h>\n#include <string>\n\nusing namespace std;\n\nconst string utf8 = \"UTF-8\";\n\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724432(v=vs.85).aspx\n\/\/ Sets errno to:\n\/\/ ERROR_INVALID_PARAMETER - parameter is not valid\n\/\/ ERROR_BAD_ENVIRONMENT - locale is not UTF-8\n\/\/ ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files\n\/\/ ERROR_NO_ASSOCIATION - calling process has no controlling terminal\n\/\/ ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string\n\/\/ ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file\n\/\/ ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure\n\/\/ ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal\n\/\/ ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code\n\/\/\n\/\/ Returns:\n\/\/ 1 - succeeded\n\/\/ 0 - failed\nBOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)\n{\n\terrno = 0;\n\n\t\/\/ Check parameters\n\tif (!lpBuffer || !lpnSize) {\n\t\terrno = ERROR_INVALID_PARAMETER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Select locale from environment\n\tsetlocale(LC_ALL, \"\");\n\t\/\/ Check that locale is UTF-8\n\tif (nl_langinfo(CODESET) != utf8) {\n\t\terrno = ERROR_BAD_ENVIRONMENT;\n\t\treturn 0;\n\t}\n\n\t\/\/ Get username from system in a thread-safe manner\n\tchar userName[*lpnSize];\n\tint err = getlogin_r(userName, *lpnSize);\n\t\/\/ Map errno to Win32 Error Codes\n\tif (err != 0) {\n\t\tswitch (errno) {\n\t\tcase EMFILE:\n\t\tcase ENFILE:\n\t\t\terrno = ERROR_TOO_MANY_OPEN_FILES;\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tcase ERANGE:\n\t\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\t\tbreak;\n\t\tcase ENOENT:\n\t\t\terrno = ERROR_NO_SUCH_USER;\n\t\t\tbreak;\n\t\tcase ENOMEM:\n\t\t\terrno = ERROR_OUTOFMEMORY;\n\t\t\tbreak;\n\t\tcase ENOTTY:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrno = ERROR_INVALID_FUNCTION;\n\t\t}\n\t\treturn 0;\n\t}\n\n\t\/\/ TODO: Convert to char* to wchar* (UTF-8 to UTF-16 LE w\/o BOM)\n\n\t\/\/ Unfortunately codecvt is not yet supported by G++, othwerise:\n\t\/\/ wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> conversion;\n\n\t\/\/ TODO: Use PAL's Unicode converters\n\n\t\/\/ TODO: set the lpnSize to the userName length (see msdn)\n\n\treturn 1;\n}\n\n<commit_msg>Convert get_login_r to UTF-16 and return<commit_after>#include \"getusername.h\"\n#include <errno.h>\n#include <langinfo.h>\n#include <locale.h>\n#include <unistd.h>\n#include <string>\n#include <vector>\n#include <scxcorelib\/scxstrencodingconv.h>\n\nusing std::string;\nusing std::vector;\n\nusing SCXCoreLib::Utf8ToUtf16le;\n\nconst string utf8 = \"UTF-8\";\n\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724432(v=vs.85).aspx\n\/\/ Sets errno to:\n\/\/ ERROR_INVALID_PARAMETER - parameter is not valid\n\/\/ ERROR_BAD_ENVIRONMENT - locale is not UTF-8\n\/\/ ERROR_TOO_MANY_OPEN_FILES - already have the maximum allowed number of open files\n\/\/ ERROR_NO_ASSOCIATION - calling process has no controlling terminal\n\/\/ ERROR_INSUFFICIENT_BUFFER - buffer not large enough to hold username string\n\/\/ ERROR_NO_SUCH_USER - there was no corresponding entry in the utmp-file\n\/\/ ERROR_OUTOFMEMORY - insufficient memory to allocate passwd structure\n\/\/ ERROR_NO_ASSOCIATION - standard input didn't refer to a terminal\n\/\/ ERROR_INVALID_FUNCTION - getlogin_r() returned an unrecognized error code\n\/\/\n\/\/ Returns:\n\/\/ 1 - succeeded\n\/\/ 0 - failed\nBOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize)\n{\n\terrno = 0;\n\n\t\/\/ Check parameters\n\tif (!lpBuffer || !lpnSize) {\n\t\terrno = ERROR_INVALID_PARAMETER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Select locale from environment\n\tsetlocale(LC_ALL, \"\");\n\t\/\/ Check that locale is UTF-8\n\tif (nl_langinfo(CODESET) != utf8) {\n\t\terrno = ERROR_BAD_ENVIRONMENT;\n\t\treturn 0;\n\t}\n\n\t\/\/ Get username from system in a thread-safe manner\n\tchar userName[*lpnSize];\n\tint err = getlogin_r(userName, *lpnSize);\n\t\/\/ Map errno to Win32 Error Codes\n\tif (err != 0) {\n\t\tswitch (errno) {\n\t\tcase EMFILE:\n\t\tcase ENFILE:\n\t\t\terrno = ERROR_TOO_MANY_OPEN_FILES;\n\t\t\tbreak;\n\t\tcase ENXIO:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tcase ERANGE:\n\t\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\t\tbreak;\n\t\tcase ENOENT:\n\t\t\terrno = ERROR_NO_SUCH_USER;\n\t\t\tbreak;\n\t\tcase ENOMEM:\n\t\t\terrno = ERROR_OUTOFMEMORY;\n\t\t\tbreak;\n\t\tcase ENOTTY:\n\t\t\terrno = ERROR_NO_ASSOCIATION;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrno = ERROR_INVALID_FUNCTION;\n\t\t}\n\t\treturn 0;\n\t}\n\n\t\/\/ Convert to char * to WCHAR_T * (UTF-8 to UTF-16 LE w\/o BOM)\n\tstring input = string(userName);\n\tvector<unsigned char> output;\n\tUtf8ToUtf16le(input, output);\n\n\tif (output.size()\/2 + 1 > *lpnSize) {\n\t\terrno = ERROR_INSUFFICIENT_BUFFER;\n\t\treturn 0;\n\t}\n\n\t\/\/ Add two null bytes (because it's UTF-16)\n\toutput.push_back('\\0');\n\toutput.push_back('\\0');\n\n\tmemcpy(lpBuffer, &output[0], output.size());\n\t*lpnSize = output.size()\/2;\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"qfiletrans.h\"\n#include \"session.h\"\n#include \"utils\/qapparg.h\"\n\n#include <QBuffer>\n#include <QXmppUtils.h>\n#include <QTextCodec>\n#include <QSettings>\n\n#include <QFile>\n\nQFileTrans::QFileTrans(QObject *parent):QXmppClient(parent),transferManager(0)\n{\n bool check;\n Q_UNUSED(check);\n\n \/\/ add transfer manager\n transferManager = new QXmppTransferManager();\n addExtension(transferManager);\n transferManager->setSupportedMethods(QXmppTransferJob::SocksMethod);\n transferManager->setSupportedMethods(QXmppTransferJob::InBandMethod);\n\n}\nvoid QFileTrans::setRecipient(const QString &recipient)\n{\n m_recipient = recipient;\n}\n\n\/\/\/ A file transfer failed.\n\nvoid QFileTrans::slotError(QXmppTransferJob::Error error)\n{\n qDebug() << \"Transmission failed:\" << error;\n}\n\n\/\/\/ A file transfer request was received.\n\nvoid QFileTrans::slotFileReceived(QXmppTransferJob *job)\n{\n\n}\n\n\/\/\/ A file transfer finished.\n\nvoid QFileTrans::slotFinished()\n{\n qDebug() << \"Transmission finished\";\n}\n\n\/\/\/ A presence was received\n\nvoid QFileTrans::slotPresenceReceived(const QXmppPresence &presence)\n{\n bool check;\n Q_UNUSED(check);\n\n \/\/ if we don't have a recipient, or if the presence is not from the recipient,\n \/\/ do nothing\n if (m_recipient.isEmpty() ||\n QXmppUtils::jidToBareJid(presence.from()) != m_recipient ||\n presence.type() != QXmppPresence::Available)\n return;\n\n \/\/ send the file and connect to the job's signals\n QXmppTransferJob *job = transferManager->sendFile(presence.from(), \":\/example_3_transferHandling.cpp\", \"example source code\");\n\n check = connect(job, SIGNAL(error(QXmppTransferJob::Error)),\n this, SLOT(slotError(QXmppTransferJob::Error)));\n Q_ASSERT(check);\n\n check = connect(job, SIGNAL(finished()),\n this, SLOT(slotFinished()));\n Q_ASSERT(check);\n\n check = connect(job, SIGNAL(progress(qint64,qint64)),\n this, SLOT(slotProgress(qint64,qint64)));\n Q_ASSERT(check);\n}\n\n\/\/\/ A file transfer has made progress.\n\nvoid QFileTrans::slotProgress(qint64 done, qint64 total)\n{\n qDebug() << \"Transmission progress:\" << done << \"\/\" << total;\n}\nQXmppTransferJob * QFileTrans::sendFile(const QString recipient, const QString file)\n{\n bool check;\n Q_UNUSED(check);\n QXmppTransferJob *job = transferManager->sendFile(recipient, file, \"\");\n return job;\n}\nvoid QFileTrans::login(QString usr, QString pwd, QString domain, QString host,LoginType type)\n{\n QString jid;\n QFile logf(\"log.txt\");\n logf.open(QIODevice::Append);\n\n jid = usr + tr(\"@\") + domain + \"\/safe\";\n logf.write(jid.toLocal8Bit());\n logf.write(\"\\r\\n\");\n logf.write(domain.toLocal8Bit());\n logf.write(\"\\r\\n\");\n logf.write(host.toLocal8Bit());\n logf.write(\"\\r\\n\");\n\n logf.close();\n if ( type == CA)\n {\n\n pwd = usr + \":\" + pwd;\n }\n Session::Instance()->setJID(jid);\n logger()->setLoggingType(QXmppLogger::StdoutLogging);\n configuration().setDomain(domain);\n configuration().setHost(host);\n configuration().setJid(jid);\n configuration().setPassword(pwd);\n configuration().setPort(5222);\n\n configuration().setStreamSecurityMode(QXmppConfiguration::TLSDisabled);\n connectToServer( configuration() );\n Session::Instance()->setJID(jid);\n Session::Instance()->SetPassWord(pwd);\n QSettings set;\n set.setValue(\"usr\",usr);\n set.setValue(\"pwd\",pwd);\n set.setValue(\"domain\",domain);\n set.setValue(\"svr\",host);\n set.setValue(\"xmpp_jid\",jid);\n set.setValue(\"xmpp_pwd\",pwd);\n\n QAppArg::ref().argCount() = 5;\n QAppArg::ref().argList().clear();\n QAppArg::ref().argList()<<usr<<pwd<<domain<<host;\n}\n\nvoid QFileTrans::qxmpp_sendMessage(QString to, QString msg)\n{\n sendMessage(to,msg);\n}\nvoid QFileTrans::qxmpp_sendData(QString data)\n{\n sendData(data.toLocal8Bit());\n}\n<commit_msg>SASL To Plain<commit_after>#include \"qfiletrans.h\"\n#include \"session.h\"\n#include \"utils\/qapparg.h\"\n\n#include <QBuffer>\n#include <QXmppUtils.h>\n#include <QTextCodec>\n#include <QSettings>\n\n#include <QFile>\n\nQFileTrans::QFileTrans(QObject *parent):QXmppClient(parent),transferManager(0)\n{\n bool check;\n Q_UNUSED(check);\n\n \/\/ add transfer manager\n transferManager = new QXmppTransferManager();\n addExtension(transferManager);\n transferManager->setSupportedMethods(QXmppTransferJob::SocksMethod);\n transferManager->setSupportedMethods(QXmppTransferJob::InBandMethod);\n\n}\nvoid QFileTrans::setRecipient(const QString &recipient)\n{\n m_recipient = recipient;\n}\n\n\/\/\/ A file transfer failed.\n\nvoid QFileTrans::slotError(QXmppTransferJob::Error error)\n{\n qDebug() << \"Transmission failed:\" << error;\n}\n\n\/\/\/ A file transfer request was received.\n\nvoid QFileTrans::slotFileReceived(QXmppTransferJob *job)\n{\n\n}\n\n\/\/\/ A file transfer finished.\n\nvoid QFileTrans::slotFinished()\n{\n qDebug() << \"Transmission finished\";\n}\n\n\/\/\/ A presence was received\n\nvoid QFileTrans::slotPresenceReceived(const QXmppPresence &presence)\n{\n bool check;\n Q_UNUSED(check);\n\n \/\/ if we don't have a recipient, or if the presence is not from the recipient,\n \/\/ do nothing\n if (m_recipient.isEmpty() ||\n QXmppUtils::jidToBareJid(presence.from()) != m_recipient ||\n presence.type() != QXmppPresence::Available)\n return;\n\n \/\/ send the file and connect to the job's signals\n QXmppTransferJob *job = transferManager->sendFile(presence.from(), \":\/example_3_transferHandling.cpp\", \"example source code\");\n\n check = connect(job, SIGNAL(error(QXmppTransferJob::Error)),\n this, SLOT(slotError(QXmppTransferJob::Error)));\n Q_ASSERT(check);\n\n check = connect(job, SIGNAL(finished()),\n this, SLOT(slotFinished()));\n Q_ASSERT(check);\n\n check = connect(job, SIGNAL(progress(qint64,qint64)),\n this, SLOT(slotProgress(qint64,qint64)));\n Q_ASSERT(check);\n}\n\n\/\/\/ A file transfer has made progress.\n\nvoid QFileTrans::slotProgress(qint64 done, qint64 total)\n{\n qDebug() << \"Transmission progress:\" << done << \"\/\" << total;\n}\nQXmppTransferJob * QFileTrans::sendFile(const QString recipient, const QString file)\n{\n bool check;\n Q_UNUSED(check);\n QXmppTransferJob *job = transferManager->sendFile(recipient, file, \"\");\n return job;\n}\nvoid QFileTrans::login(QString usr, QString pwd, QString domain, QString host,LoginType type)\n{\n QString jid;\n QFile logf(\"log.txt\");\n logf.open(QIODevice::Append);\n\n jid = usr + tr(\"@\") + domain + \"\/safe\";\n logf.write(jid.toLocal8Bit());\n logf.write(\"\\r\\n\");\n logf.write(domain.toLocal8Bit());\n logf.write(\"\\r\\n\");\n logf.write(host.toLocal8Bit());\n logf.write(\"\\r\\n\");\n\n logf.close();\n if ( type == CA)\n {\n\n pwd = usr + \":\" + pwd;\n }\n Session::Instance()->setJID(jid);\n\/\/ logger()->setLoggingType(QXmppLogger::StdoutLogging);\n configuration().setDomain(domain);\n configuration().setHost(host);\n configuration().setJid(jid);\n configuration().setPassword(pwd);\n configuration().setPort(5222);\n\n configuration().setSaslAuthMechanism(\"PLAIN\");\n configuration().setStreamSecurityMode(QXmppConfiguration::TLSDisabled);\n connectToServer( configuration() );\n Session::Instance()->setJID(jid);\n Session::Instance()->SetPassWord(pwd);\n QSettings set;\n set.setValue(\"usr\",usr);\n set.setValue(\"pwd\",pwd);\n set.setValue(\"domain\",domain);\n set.setValue(\"svr\",host);\n set.setValue(\"xmpp_jid\",jid);\n set.setValue(\"xmpp_pwd\",pwd);\n\n QAppArg::ref().argCount() = 5;\n QAppArg::ref().argList().clear();\n QAppArg::ref().argList()<<usr<<pwd<<domain<<host;\n}\n\nvoid QFileTrans::qxmpp_sendMessage(QString to, QString msg)\n{\n sendMessage(to,msg);\n}\nvoid QFileTrans::qxmpp_sendData(QString data)\n{\n sendData(data.toLocal8Bit());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RowVector\/instance_method_get.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n#define EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(RowVector, get,\n{\n NanScope();\n\n if (args.Length() == 1 &&\n args[0]->IsNumber()\n ) {\n const RowVector* const& obj =\n node::ObjectWrap::Unwrap<RowVector>(args.This());\n const typename RowVector::value_type& rowvector = **obj;\n const typename RowVector::value_type::Index& col = args[0]->Int32Value();\n\n if (RowVector::is_out_of_range(rowvector, col, 0)) {\n NanReturnUndefined();\n }\n\n const typename RowVector::scalar_type& value = rowvector(0, col);\n NanReturnValue(NanNew(value));\n }\n\n EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n NanReturnUndefined();\n})\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n<commit_msg>src: fixed a mistake<commit_after>\/\/\n\/\/ RowVector\/instance_method_get.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n#define EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(RowVector, get,\n{\n NanScope();\n\n if (args.Length() == 1 &&\n args[0]->IsNumber()\n ) {\n const RowVector* const& obj =\n node::ObjectWrap::Unwrap<RowVector>(args.This());\n const typename RowVector::value_type& rowvector = **obj;\n const typename RowVector::value_type::Index& col = args[0]->Int32Value();\n\n if (RowVector::is_out_of_range(rowvector, 0, col)) {\n NanReturnUndefined();\n }\n\n const typename RowVector::scalar_type& value = rowvector(0, col);\n NanReturnValue(NanNew(value));\n }\n\n EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n NanReturnUndefined();\n})\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_ROWVECTOR_INSTANCE_METHOD_GET_HPP\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"Scheduler_node.hpp\"\n\n#include <Eigen\/Dense>\n#include <exception>\n#include <iostream>\n#include <map>\n#include <node.h>\n#include <pthread.h>\n#include <queue>\n#include <stdio.h>\n#include <uv.h>\n#include <v8.h>\n\n#include \"..\/..\/Algorithms\/ProximalGradientDescent.hpp\"\n#include \"..\/..\/Algorithms\/IterativeUpdate.hpp\"\n#include \"..\/..\/Algorithms\/Algorithm.hpp\"\n#include \"..\/..\/Algorithms\/AlgorithmOptions.hpp\"\n#include \"..\/..\/Algorithms\/HypoTestPlaceHolder.h\"\n#include \"..\/..\/Models\/ModelOptions.hpp\"\n#include \"..\/Job.hpp\"\n#include \"..\/Scheduler.hpp\"\n#include \"..\/..\/JSON\/JsonCoder.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace v8;\n\n\n\/\/ Sets the X matrix of a given model.\n\/\/ Arguments: job_id, JSON matrix\nvoid setX(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[1]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setX(job_id, *mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n}\n\n\/\/ Sets the Y matrix of a given model.\n\/\/ Arguments: job_id, JSON matrix\nvoid setY(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[1]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setY(job_id, *mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n}\n\n\/\/ Arguments: job_id, string of attribute name, matrix to use\nvoid setModelAttributeMatrix(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tconst string attribute_name(*v8::String::Utf8Value(args[1]->ToString()));\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[2]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setModelAttributeMatrix(job_id, attribute_name, mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\t\n}\n\n\n\/\/ Creates a new job, but does not run it. Synchronous.\n\/\/ Arguments: JSON to be converted to JobOptions_t\nvoid newJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst JobOptions_t& options = JobOptions_t(isolate, options_v8);\n\ttry {\n\t\tconst int id = Scheduler::Instance()->newJob(options);\n\t\tif (id < 0) {\n\t\t\tisolate->ThrowException(Exception::Error(\n\t\t\t\tString::NewFromUtf8(isolate, \"Could not add another job\")));\n\t\t\treturn;\n\t\t}\n\n\t\tLocal<Integer> retval = Integer::New(isolate, id);\n\t\targs.GetReturnValue().Set(retval);\n\t} catch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t\treturn;\n\t}\n}\n\n\n\/\/ Maybe begins the training of an algorithm, given the job number.\n\/\/ Asynchronous.\n\/\/ Arguments: int job_id, function callback\nvoid startJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\t\/\/ Inspect arguments.\n\ttry {\n\t\tif (!ArgsHaveJobID(args, 0)) {\n\t\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\t\treturn;\n\t\t}\n\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tJob_t* job = Scheduler::Instance()->getJob(job_id);\n\t\tjob->exception = nullptr;\n\t\tjob->callback.Reset(isolate, Local<Function>::Cast(args[1]));\n\t\tjob->job_id = job_id;\n\t\tbool result = Scheduler::Instance()->startJob(job_id, trainAlgorithmComplete);\n\t\tusleep(1);\t\/\/ let the execution thread start -- necessary?\n\t\tif (job->exception) {\n\t\t\trethrow_exception(job->exception);\n\t\t}\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n\t} catch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t}\n}\n\n\/\/ Checks the status of an algorithm, given the algorithm's job number.\n\/\/ Currently synchronous.\n\/\/ Arguments: int job_id\nvoid checkJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\t\/\/ Check argument types.\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\n\tint job_id = (int)Local<Number>::Cast(args[0])->Value();\n\tconst double progress = Scheduler::Instance()->checkJobProgress(job_id);\n\tLocal<Number> retval = Number::New(isolate, progress);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Gets the results of a job, given the job's id.\n\/\/ Synchronous.\n\/\/ Arguments: int job_id\n\/\/ Returns: MatrixXd of results, empty on error.\nvoid getJobResult(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\ttry {\n\t\t\/\/ Check argument types.\n\t\tif (!ArgsHaveJobID(args, 0)) {\n\t\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\t\treturn;\n\t\t}\n\n\t\tint job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tconst MatrixXd& result = Scheduler::Instance()->getJobResult(job_id);\n\t\tLocal<v8::Array> obj = v8::Array::New(isolate);\n\t\t\/\/ TODO: Fewer convserions to return a matrix [Issue: https:\/\/github.com\/blengerich\/GenAMap_V2\/issues\/17]\n\t\tobj->Set(0, v8::String::NewFromUtf8(isolate, JsonCoder::getInstance().encodeMatrix(result).c_str()));\n\t\targs.GetReturnValue().Set(obj);\n\t}\n\tcatch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t}\n}\n\n\n\/\/ Cancels a potentially running Algorithm.\n\/\/ Synchronous.\n\/\/ Arguments: int job_id\n\/\/ Returns: boolean representing success.\nvoid cancelJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\t\/\/ Check argument types.\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\ttry {\n\t\tconst int job_id = (int)Local<Integer>::Cast(args[0])->Value();\n\t\tconst bool success = Scheduler::Instance()->cancelJob(job_id);\n\t\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\t\targs.GetReturnValue().Set(retval);\n\t} catch(const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t}\n}\n\n\n\/\/ Arguments: job_id\nvoid deleteJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\n\tconst int job_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteJob(job_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Handles packaging of algorithm results to return to the frontend.\n\/\/ Called by libuv in event loop when async training completes.\nvoid trainAlgorithmComplete(uv_work_t* req, int status) {\n\t\/\/ Runs in event loop when algorithm completes.\n\tIsolate* isolate = Isolate::GetCurrent();\n\tHandleScope handleScope(isolate);\n\tJob_t* job = static_cast<Job_t*>(req->data);\n\tLocal<v8::Array> obj = v8::Array::New(isolate);\n\n\ttry {\n\t\t\/\/ Pack up the data to be returned to JS\n\t\tconst MatrixXd& result = Scheduler::Instance()->getJobResult(job->job_id);\n\t\t\/\/ TODO: Fewer convserions to return a matrix [Issue: https:\/\/github.com\/blengerich\/GenAMap_V2\/issues\/17]\n\t\tobj->Set(0, v8::String::NewFromUtf8(isolate, JsonCoder::getInstance().encodeMatrix(result).c_str()));\n\t\t\n\t\tif (status < 0) { \/\/libuv error\n\t\t\tthrow runtime_error(\"Libuv error (check server)\");\n\t\t}\n\t\tif (job->exception) {\n\t\t\trethrow_exception(job->exception); \n\t\t}\n\t} catch(const exception& e) {\n\t\t\/\/ If the job failed, the second entry in the array is the exception text.\n\t\t\/\/ Is this really a good way to return data? It is different than the result from getJobResult()\n\t\tobj->Set(1, v8::String::NewFromUtf8(isolate, e.what()));\t\n\t}\n\t\n\tHandle<Value> argv[] = { obj };\n\t\/\/ execute the callback\n\tLocal<Function>::New(isolate, job->callback)->Call(\n\t\tisolate->GetCurrentContext()->Global(), 1, argv);\n\tjob->callback.Reset();\n}\n\n\nMatrixXd* v8toEigen(Local<v8::Array>& ar) {\n\tconst unsigned int rows = ar->Length();\n\tLocal<v8::Array> props = Local<v8::Object>::Cast(ar->Get(0))->GetPropertyNames();\n\tconst unsigned int cols = props->Length();\n\tEigen::MatrixXd* mat = new Eigen::MatrixXd(rows, cols);\n\n\tfor (unsigned int i=0; i<rows; i++) {\n\t\tfor (unsigned int j=0; j<cols; j++) {\n\t\t\t(*mat)(i,j) = (double)Local<v8::Object>::Cast(ar->Get(i))->Get(props->Get(j))->NumberValue();\n\t\t}\n\t}\n\treturn mat;\n}\n\n\/\/ Checks that the argument in the supplied position is a number type.\n\/\/ Doesn't check that it is a valid job ID.\nbool ArgsHaveJobID(const FunctionCallbackInfo<Value>& args, const int position) {\n\tIsolate* isolate = args.GetIsolate();\n\tif (args.Length() < 1) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Must supply a job id.\")));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn false;\n\t}\n\n\tif (!(args[0]->IsNumber())) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Job id must be a number.\")));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/* Deprecated - only interacting with jobs now\n\/\/ Creates a new algorithm, but does not run it. Currently synchronous.\n\/\/ Arguments: JSON to be converted to AlgorithmOptions_t\nvoid newAlgorithm(const FunctionCallbackInfo<Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\tif (args.Length() < 1) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n\t\treturn;\n\t}\n\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst AlgorithmOptions_t& options = AlgorithmOptions_t(isolate, options_v8);\n\n\tconst int id = Scheduler::Instance()->newAlgorithm(options);\n\tif (id < 0) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, \"Could not add another algorithm.\")));\n\t\treturn;\n\t}\n\n\tLocal<Integer> retval = Integer::New(isolate, id);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Creates a new model, but does not run it. Synchronous.\n\/\/ Arguments: JSON to be converted to ModelOptions_t\nvoid newModel(const FunctionCallbackInfo<Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst ModelOptions_t& options = ModelOptions_t(isolate, options_v8);\n\tconst int id = Scheduler::Instance()->newModel(options);\n\tif (id < 0) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, \"Could not add another model\")));\n\t\treturn;\n\t}\n\n\tLocal<Integer> retval = Integer::New(isolate, id);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Arguments: int alg_id\n\/\/ Returns: boolean for success\nvoid deleteAlgorithm(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tconst int algorithm_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteAlgorithm(algorithm_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n\n\/\/ Arguments: int model_id\nvoid deleteModel(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tconst int model_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteModel(model_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n*\/\n<commit_msg>Remove matrix conversion TODO<commit_after>\n\n#include \"Scheduler_node.hpp\"\n\n#include <Eigen\/Dense>\n#include <exception>\n#include <iostream>\n#include <map>\n#include <node.h>\n#include <pthread.h>\n#include <queue>\n#include <stdio.h>\n#include <uv.h>\n#include <v8.h>\n\n#include \"..\/..\/Algorithms\/ProximalGradientDescent.hpp\"\n#include \"..\/..\/Algorithms\/IterativeUpdate.hpp\"\n#include \"..\/..\/Algorithms\/Algorithm.hpp\"\n#include \"..\/..\/Algorithms\/AlgorithmOptions.hpp\"\n#include \"..\/..\/Algorithms\/HypoTestPlaceHolder.h\"\n#include \"..\/..\/Models\/ModelOptions.hpp\"\n#include \"..\/Job.hpp\"\n#include \"..\/Scheduler.hpp\"\n#include \"..\/..\/JSON\/JsonCoder.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace v8;\n\n\n\/\/ Sets the X matrix of a given model.\n\/\/ Arguments: job_id, JSON matrix\nvoid setX(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[1]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setX(job_id, *mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n}\n\n\/\/ Sets the Y matrix of a given model.\n\/\/ Arguments: job_id, JSON matrix\nvoid setY(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[1]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setY(job_id, *mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n}\n\n\/\/ Arguments: job_id, string of attribute name, matrix to use\nvoid setModelAttributeMatrix(const FunctionCallbackInfo<Value>& args) {\n\tbool result = false;\n\tIsolate* isolate = args.GetIsolate();\n\tif (ArgsHaveJobID(args, 0)) {\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tconst string attribute_name(*v8::String::Utf8Value(args[1]->ToString()));\n\t\tLocal<v8::Array> ar = Local<v8::Array>::Cast(args[2]);\n\t\tMatrixXd* mat = v8toEigen(ar);\n\t\tresult = Scheduler::Instance()->setModelAttributeMatrix(job_id, attribute_name, mat);\n\t}\n\targs.GetReturnValue().Set(Boolean::New(isolate, result));\t\n}\n\n\n\/\/ Creates a new job, but does not run it. Synchronous.\n\/\/ Arguments: JSON to be converted to JobOptions_t\nvoid newJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst JobOptions_t& options = JobOptions_t(isolate, options_v8);\n\ttry {\n\t\tconst int id = Scheduler::Instance()->newJob(options);\n\t\tif (id < 0) {\n\t\t\tisolate->ThrowException(Exception::Error(\n\t\t\t\tString::NewFromUtf8(isolate, \"Could not add another job\")));\n\t\t\treturn;\n\t\t}\n\n\t\tLocal<Integer> retval = Integer::New(isolate, id);\n\t\targs.GetReturnValue().Set(retval);\n\t} catch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t\treturn;\n\t}\n}\n\n\n\/\/ Maybe begins the training of an algorithm, given the job number.\n\/\/ Asynchronous.\n\/\/ Arguments: int job_id, function callback\nvoid startJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\t\/\/ Inspect arguments.\n\ttry {\n\t\tif (!ArgsHaveJobID(args, 0)) {\n\t\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\t\treturn;\n\t\t}\n\n\t\tconst int job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tJob_t* job = Scheduler::Instance()->getJob(job_id);\n\t\tjob->exception = nullptr;\n\t\tjob->callback.Reset(isolate, Local<Function>::Cast(args[1]));\n\t\tjob->job_id = job_id;\n\t\tbool result = Scheduler::Instance()->startJob(job_id, trainAlgorithmComplete);\n\t\tusleep(1);\t\/\/ let the execution thread start -- necessary?\n\t\tif (job->exception) {\n\t\t\trethrow_exception(job->exception);\n\t\t}\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, result));\n\t} catch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t}\n}\n\n\/\/ Checks the status of an algorithm, given the algorithm's job number.\n\/\/ Currently synchronous.\n\/\/ Arguments: int job_id\nvoid checkJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\t\/\/ Check argument types.\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\n\tint job_id = (int)Local<Number>::Cast(args[0])->Value();\n\tconst double progress = Scheduler::Instance()->checkJobProgress(job_id);\n\tLocal<Number> retval = Number::New(isolate, progress);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Gets the results of a job, given the job's id.\n\/\/ Synchronous.\n\/\/ Arguments: int job_id\n\/\/ Returns: MatrixXd of results, empty on error.\nvoid getJobResult(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\ttry {\n\t\t\/\/ Check argument types.\n\t\tif (!ArgsHaveJobID(args, 0)) {\n\t\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\t\treturn;\n\t\t}\n\n\t\tint job_id = (int)Local<Number>::Cast(args[0])->Value();\n\t\tconst MatrixXd& result = Scheduler::Instance()->getJobResult(job_id);\n\t\tLocal<v8::Array> obj = v8::Array::New(isolate);\n\t\tobj->Set(0, v8::String::NewFromUtf8(isolate, JsonCoder::getInstance().encodeMatrix(result).c_str()));\n\t\targs.GetReturnValue().Set(obj);\n\t}\n\tcatch (const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t}\n}\n\n\n\/\/ Cancels a potentially running Algorithm.\n\/\/ Synchronous.\n\/\/ Arguments: int job_id\n\/\/ Returns: boolean representing success.\nvoid cancelJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\t\/\/ Check argument types.\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\ttry {\n\t\tconst int job_id = (int)Local<Integer>::Cast(args[0])->Value();\n\t\tconst bool success = Scheduler::Instance()->cancelJob(job_id);\n\t\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\t\targs.GetReturnValue().Set(retval);\n\t} catch(const exception& e) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, e.what())));\n\t}\n}\n\n\n\/\/ Arguments: job_id\nvoid deleteJob(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\tif (!ArgsHaveJobID(args, 0)) {\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn;\n\t}\n\n\tconst int job_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteJob(job_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Handles packaging of algorithm results to return to the frontend.\n\/\/ Called by libuv in event loop when async training completes.\nvoid trainAlgorithmComplete(uv_work_t* req, int status) {\n\t\/\/ Runs in event loop when algorithm completes.\n\tIsolate* isolate = Isolate::GetCurrent();\n\tHandleScope handleScope(isolate);\n\tJob_t* job = static_cast<Job_t*>(req->data);\n\tLocal<v8::Array> obj = v8::Array::New(isolate);\n\n\ttry {\n\t\t\/\/ Pack up the data to be returned to JS\n\t\tconst MatrixXd& result = Scheduler::Instance()->getJobResult(job->job_id);\n\t\t\/\/ TODO: Fewer convserions to return a matrix [Issue: https:\/\/github.com\/blengerich\/GenAMap_V2\/issues\/17]\n\t\tobj->Set(0, v8::String::NewFromUtf8(isolate, JsonCoder::getInstance().encodeMatrix(result).c_str()));\n\t\t\n\t\tif (status < 0) { \/\/libuv error\n\t\t\tthrow runtime_error(\"Libuv error (check server)\");\n\t\t}\n\t\tif (job->exception) {\n\t\t\trethrow_exception(job->exception); \n\t\t}\n\t} catch(const exception& e) {\n\t\t\/\/ If the job failed, the second entry in the array is the exception text.\n\t\t\/\/ Is this really a good way to return data? It is different than the result from getJobResult()\n\t\tobj->Set(1, v8::String::NewFromUtf8(isolate, e.what()));\t\n\t}\n\t\n\tHandle<Value> argv[] = { obj };\n\t\/\/ execute the callback\n\tLocal<Function>::New(isolate, job->callback)->Call(\n\t\tisolate->GetCurrentContext()->Global(), 1, argv);\n\tjob->callback.Reset();\n}\n\n\nMatrixXd* v8toEigen(Local<v8::Array>& ar) {\n\tconst unsigned int rows = ar->Length();\n\tLocal<v8::Array> props = Local<v8::Object>::Cast(ar->Get(0))->GetPropertyNames();\n\tconst unsigned int cols = props->Length();\n\tEigen::MatrixXd* mat = new Eigen::MatrixXd(rows, cols);\n\n\tfor (unsigned int i=0; i<rows; i++) {\n\t\tfor (unsigned int j=0; j<cols; j++) {\n\t\t\t(*mat)(i,j) = (double)Local<v8::Object>::Cast(ar->Get(i))->Get(props->Get(j))->NumberValue();\n\t\t}\n\t}\n\treturn mat;\n}\n\n\/\/ Checks that the argument in the supplied position is a number type.\n\/\/ Doesn't check that it is a valid job ID.\nbool ArgsHaveJobID(const FunctionCallbackInfo<Value>& args, const int position) {\n\tIsolate* isolate = args.GetIsolate();\n\tif (args.Length() < 1) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Must supply a job id.\")));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn false;\n\t}\n\n\tif (!(args[0]->IsNumber())) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Job id must be a number.\")));\n\t\targs.GetReturnValue().Set(Boolean::New(isolate, false));\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/* Deprecated - only interacting with jobs now\n\/\/ Creates a new algorithm, but does not run it. Currently synchronous.\n\/\/ Arguments: JSON to be converted to AlgorithmOptions_t\nvoid newAlgorithm(const FunctionCallbackInfo<Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\n\tif (args.Length() < 1) {\n\t\tisolate->ThrowException(Exception::TypeError(\n\t\t\tString::NewFromUtf8(isolate, \"Wrong number of arguments\")));\n\t\treturn;\n\t}\n\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst AlgorithmOptions_t& options = AlgorithmOptions_t(isolate, options_v8);\n\n\tconst int id = Scheduler::Instance()->newAlgorithm(options);\n\tif (id < 0) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, \"Could not add another algorithm.\")));\n\t\treturn;\n\t}\n\n\tLocal<Integer> retval = Integer::New(isolate, id);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Creates a new model, but does not run it. Synchronous.\n\/\/ Arguments: JSON to be converted to ModelOptions_t\nvoid newModel(const FunctionCallbackInfo<Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tHandle<Object> options_v8 = Handle<Object>::Cast(args[0]);\n\tconst ModelOptions_t& options = ModelOptions_t(isolate, options_v8);\n\tconst int id = Scheduler::Instance()->newModel(options);\n\tif (id < 0) {\n\t\tisolate->ThrowException(Exception::Error(\n\t\t\tString::NewFromUtf8(isolate, \"Could not add another model\")));\n\t\treturn;\n\t}\n\n\tLocal<Integer> retval = Integer::New(isolate, id);\n\targs.GetReturnValue().Set(retval);\n}\n\n\/\/ Arguments: int alg_id\n\/\/ Returns: boolean for success\nvoid deleteAlgorithm(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tconst int algorithm_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteAlgorithm(algorithm_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n\n\/\/ Arguments: int model_id\nvoid deleteModel(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tIsolate* isolate = args.GetIsolate();\n\tconst int model_id = (int)Local<Integer>::Cast(args[0])->Value();\n\tconst bool success = Scheduler::Instance()->deleteModel(model_id);\n\tHandle<Boolean> retval = Boolean::New(isolate, success);\n\targs.GetReturnValue().Set(retval);\n}\n\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 Till Kolditz\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/* \n * File: TestModuloInverseComputation.cpp\n * Author: Till Kolditz <till.kolditz@gmail.com>\n *\n * Created on 20. Februar 2017, 18:21\n *\/\n\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n\n#include <boost\/multiprecision\/cpp_int.hpp>\n\n#include \"Util\/Euclidean.hpp\"\n#include \"Util\/Stopwatch.hpp\"\n\nusing boost::multiprecision::uint128_t;\n\nconst size_t wCmin = 16;\nconst size_t wCmax = 127;\nconst size_t wAmin = 3;\n\/\/const size_t wAmax = 16;\n\nuint64_t convert(uint128_t & source) {\n uint64_t target = 0;\n const unsigned limb_num = source.backend().size(); \/\/ number of limbs\n const unsigned limb_bits = sizeof(boost::multiprecision::limb_type) * CHAR_BIT; \/\/ size of limb in bits\n for (unsigned i = 0; i < limb_num && ((i * limb_bits) < (sizeof(target) * 8)); ++i) {\n target |= (source.backend().limbs()[i]) << (i * limb_bits);\n }\n return target;\n}\n\nint main(int argc, char ** argv) {\n if (argc != 2) {\n std::cerr << \"Usage: \" << argv[0] << \" <totalnum [#iterations]>\" << std::endl;\n return 1;\n }\n\n size_t TOTALNUM = strtoll(argv[1], nullptr, 0);\n uint128_t result;\n \/\/ volatile uint64_t result64;\n\n std::cout << TOTALNUM << \" iterations per combination of |A| and |C|.\" << std::endl;\n std::cout << \"|C|\";\n for (size_t wA = wAmin; wA <= wCmax; ++wA) {\n std::cout << '\\t' << wA;\n }\n std::cout << std::endl;\n\n for (size_t wC = wCmin; wC <= wCmax; ++wC) {\n std::cout << wC;\n for (size_t wA = wAmin; wA <= (wC - (wCmin - (wAmin - 1))); ++wA) {\n std::cout << \"\\t-\";\n }\n for (size_t wA = (wC - (wCmin - (wAmin - 1))); wA < wC; ++wA) {\n uint128_t A(1);\n A <<= (wA - 1);\n A += 1;\n Stopwatch sw;\n for (size_t i = 0; i < TOTALNUM; ++i) {\n result = ext_euclidean(A, wC);\n \/\/ result64 = convert(result);\n }\n auto nanoseconds = sw.Current();\n std::cout << '\\t' << std::hex << std::showbase << A << ':' << std::dec << std::noshowbase << nanoseconds;\n }\n std::cout << std::endl;\n }\n}\n<commit_msg>run from code word width 3 to 127 use smallest integer possible for euclidean computation<commit_after>\/\/ Copyright (c) 2016 Till Kolditz\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/* \n * File: TestModuloInverseComputation.cpp\n * Author: Till Kolditz <till.kolditz@gmail.com>\n *\n * Created on 20. Februar 2017, 18:21\n *\/\n\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n\n#include <boost\/multiprecision\/cpp_int.hpp>\n\n#include \"Util\/Euclidean.hpp\"\n#include \"Util\/Stopwatch.hpp\"\n\nusing boost::multiprecision::uint128_t;\n\nconst size_t wCmin = 3;\nconst size_t wCmax = 127;\nconst size_t wAmin = 2;\n\/\/const size_t wAmax = 16;\n\nuint64_t convert(uint128_t & source) {\n uint64_t target = 0;\n const unsigned limb_num = source.backend().size(); \/\/ number of limbs\n const unsigned limb_bits = sizeof(boost::multiprecision::limb_type) * CHAR_BIT; \/\/ size of limb in bits\n for (unsigned i = 0; i < limb_num && ((i * limb_bits) < (sizeof(target) * 8)); ++i) {\n target |= (source.backend().limbs()[i]) << (i * limb_bits);\n }\n return target;\n}\n\ntemplate<typename T>\nT test(size_t TOTALNUM, size_t wC) {\n T result(0);\n std::cout << wC;\n#ifdef DEBUG\n for (size_t wA = wAmin; wA <= (wC - (wCmin - (wAmin - 1))); ++wA) {\n std::cout << \"\\t-\";\n }\n for (size_t wA = (wC - (wCmin - (wAmin - 1))); wA < wC; ++wA) {\n#else\n for (size_t wA = wAmin; wA < wC; ++wA) {\n#endif\n T A(1);\n A <<= (wA - 1);\n A += 1;\n Stopwatch sw;\n for (size_t i = 0; i < TOTALNUM; ++i) {\n result = ext_euclidean(A, wC);\n \/\/ result64 = convert(result);\n }\n auto nanoseconds = sw.Current();\n#ifdef DEBUG\n std::cout << '\\t' << std::hex << std::showbase << A << ':' << std::dec << std::noshowbase << nanoseconds;\n#else\n std::cout << '\\t' << nanoseconds;\n#endif\n }\n std::cout << std::endl;\n return result;\n}\n\nint main(int argc, char ** argv) {\n if (argc != 2) {\n std::cerr << \"Usage: \" << argv[0] << \" <totalnum [#iterations]>\" << std::endl;\n return 1;\n }\n\n size_t TOTALNUM = strtoll(argv[1], nullptr, 0);\n\/\/ volatile uint64_t result64;\n\n std::cout << TOTALNUM << \" iterations per combination of |A| and |C|.\" << std::endl;\n std::cout << \"|C|\";\n for (size_t wA = wAmin; wA <= wCmax; ++wA) {\n std::cout << '\\t' << wA;\n }\n std::cout << std::endl;\n\n for (size_t wC = wCmin; wC <= wCmax; ++wC) {\n if (wC < 8) {\n __attribute__((unused)) volatile uint8_t result = test<uint8_t>(TOTALNUM, wC);\n } else if (wC < 16) {\n __attribute__((unused)) volatile uint16_t result = test<uint16_t>(TOTALNUM, wC);\n } else if (wC < 32) {\n __attribute__((unused)) volatile uint32_t result = test<uint32_t>(TOTALNUM, wC);\n } else if (wC < 64) {\n __attribute__((unused)) volatile uint64_t result = test<uint64_t>(TOTALNUM, wC);\n } else if (wC < 128) {\n __attribute__((unused)) volatile uint128_t result = test<uint128_t>(TOTALNUM, wC);\n } else {\n throw std::runtime_error(\"unsupported code word widht\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ round_thing.cc\n\/\/ AirHockey\n\/\/\n\/\/ Created by Jonathan Sharkey on 10-04-14.\n\/\/ Copyright 2010 Sharkable. All rights reserved.\n\/\/\n\n#include \"airhockey\/entities\/round_thing.h\"\n\n#include <cmath>\n\n#include \"airhockey\/entities\/paddle.h\"\n#include \"airhockey\/entities\/puck.h\"\n#include \"gameengine\/game_engine.h\"\n#include \"gameengine\/resource_loader.h\"\n#include \"gameengine\/touch.h\"\n#include \"soundengine\/sound_player.h\"\n\nRoundThing::RoundThing(sp<GameEngine> game_engine)\n : sprite_(game_engine),\n x_(0),\n y_(0),\n old_x_(0),\n old_y_(0),\n vx_(0),\n vy_(0),\n radius_(0),\n mass_(0),\n friction_(0),\n grabbed_(false),\n grabbed_touch_(NULL),\n active_(true) {\n}\n\nRoundThing::RoundThing(sp<GameEngine> game_engine, string texture_name)\n : sprite_(game_engine, texture_name),\n x_(0),\n y_(0),\n old_x_(0),\n old_y_(0),\n vx_(0),\n vy_(0),\n radius_(0),\n mass_(0),\n friction_(0),\n grabbed_(false),\n grabbed_touch_(NULL),\n active_(true) {\n}\n\nRoundThing::~RoundThing() {\n if (sprite_.texture().data_loaded()) {\n ResourceLoader::Instance().ReleaseResource(sprite_.texture());\n }\n}\n\nvoid RoundThing::ApplyFriction() {\n if (!is_grabbed()) {\n vx_ *= friction_;\n vy_ *= friction_;\n }\n}\n\nvoid RoundThing::MaybeBounceOff(RoundThing *other) {\n \/\/ TODO optimize this function.\n \/\/ For now I'm just getting it to work.\n \n double dxFull = x_ - other->x();\n double dyFull = y_ - other->y();\n double radiusTotal = other->radius() + radius_;\n\/\/ double v = sqrt(self.vx * self.vx + self.vy * self.vy);\n\/\/ double otherV = sqrt(other.vx * other.vx + other.vy * other.vy);\n \n if (dxFull*dxFull + dyFull*dyFull <= radiusTotal*radiusTotal) { \n \/\/ Normalize N\n double nL = sqrt(dxFull*dxFull + dyFull*dyFull);\n double dx = dxFull \/ nL;\n double dy = dyFull \/ nL;\n \n \/\/ *** Move the round things outside of each other. ***\n double vFraction = mass_ \/ (other->mass() + mass_);\n \n if ((grabbed_ && !other->is_grabbed() && other->IsMovable()) || !IsMovable()) {\n vFraction = 1;\n } else if ((!grabbed_ && other->is_grabbed()) || !other->IsMovable()) {\n vFraction = 0;\n }\n \n double diff = sqrt(radiusTotal*radiusTotal) - nL;\n other->set_x(other->x() - dx * diff * vFraction);\n other->set_y(other->y() - dy * diff * vFraction);\n vFraction = 1 - vFraction;\n x_ += dx * diff * vFraction;\n y_ += dy * diff * vFraction;\n \n \/\/ *** Now change the direction based on the bounce. ***\n \n \/\/ Based on this: http:\/\/stackoverflow.com\/questions\/573084\/how-to-calculate-bounce-angle\n \/\/ But it had some problems.\n \/\/ Looked at Wikipedia dot product article to help.\n double vDn = vx_ * dx + vy_ * dy;\n double ux = dx * vDn;\n double uy = dy * vDn;\n double wx = vx_ - ux;\n double wy = vy_ - uy;\n \n double othervDn_ = other->vx() * dx + other->vy() * dy;\n double otherux_ = dx * othervDn_;\n double otheruy_ = dy * othervDn_;\n double otherwx_ = other->vx() - otherux_;\n double otherwy_ = other->vy() - otheruy_;\n \n double newux_ = (ux * (mass_ - other->mass()) + 2.0 * other->mass() * otherux_) \/ (mass_ + other->mass());\n double newuy_ = (uy * (mass_ - other->mass()) + 2.0 * other->mass() * otheruy_) \/ (mass_ + other->mass()); \n \n double newother_ux_ = (otherux_ * (other->mass() - mass_) + 2.0 * mass_ * ux) \/ (mass_ + other->mass());\n double newother_uy_ = (otheruy_ * (other->mass() - mass_) + 2.0 * mass_ * uy) \/ (mass_ + other->mass()); \n \n if (!is_grabbed() && IsMovable()) {\n vx_ = newux_ + wx;\n vy_ = newuy_ + wy;\n }\n \n if (!other->is_grabbed() && other->IsMovable()) {\n other->set_vx(newother_ux_ + otherwx_);\n other->set_vy(newother_uy_ + otherwy_);\n }\n\n double newVSquared = vx_ * vx_ + vy_ * vy_;\n double newOtherVSquared = other->vx() * other->vx() + other->vy() * other->vy();\n \n if (newVSquared > (MAX_SPEED*MAX_SPEED)) {\n double newV = sqrt(newVSquared);\n double newRatio = MAX_SPEED \/ newV;\n vx_ *= newRatio;\n vy_ *= newRatio;\n }\n if (newOtherVSquared > (MAX_SPEED*MAX_SPEED)) {\n double newOtherV = sqrt(newOtherVSquared);\n double newRatio = MAX_SPEED \/ newOtherV;\n other->set_vx(other->vx() * newRatio);\n other->set_vy(other->vy() * newRatio);\n }\n\n DidBounceOff(other);\n } \n}\n\nbool RoundThing::ContainsTouch(Touch *touch) {\n double dx = touch->location().x - x_;\n double dy = touch->location().y - y_;\n return (dx*dx + dy*dy <= radius_*radius_);\n}\n\nbool RoundThing::Overlaps(RoundThing * thing) {\n double dx = thing->x() - x_;\n double dy = thing->y() - y_;\n double totalRadius = thing->radius() + radius_;\n return (dx*dx + dy*dy <= totalRadius*totalRadius);\n}\n\nbool RoundThing::IsGrabbable() {\n return false;\n}\n\nbool RoundThing::IsMovable() {\n return true;\n}\n\n\n\/\/ ViewEntity\n\nvoid RoundThing::Update() {\n if (!IsMovable() || !is_active()) {\n return;\n }\n \n if (!grabbed_) {\n x_ += vx_;\n y_ += vy_;\n } else { \n vx_ = vx_ * 0.75 + (x_ - old_x_) * 0.25;\n vy_ = vy_ * 0.75 + (y_ - old_y_) * 0.25;\n old_x_ = x_;\n old_y_ = y_;\n }\n}\n\nvoid RoundThing::Render() {\n if (active_) {\n sprite_.DrawAtPoint(game_point_make(x_ - sprite_.content_size().width \/ 2,\n y_ - sprite_.content_size().height \/ 2));\n }\n}\n\nvoid RoundThing::TouchesBegan(vector<Touch> touches) {\n if (!IsGrabbable() || !is_active() || is_grabbed()) {\n return;\n }\n for (int i = 0; i < touches.size(); i++) {\n if (ContainsTouch(&touches[i])) {\n grabbed_ = true;\n grabbed_touch_ = touches[i].identifier();\n TouchesMoved(touches);\n vx_ = 0;\n vy_ = 0;\n \/\/ Set oldX_ and oldY_ here so that the velocity stays around 0.\n \/\/ This is when you touch the outside of the RoundThing and it\n \/\/ snaps to center on your touch, it doesn't have a really high\n \/\/ initial velocity.\n old_x_ = x_;\n old_y_ = y_; \n }\n }\n}\n\nvoid RoundThing::TouchesMoved(vector<Touch> touches) {\n Touch* correctTouch = NULL;\n for (int i = 0; i < touches.size(); i++) {\n if (touches[i].identifier() == grabbed_touch_) {\n correctTouch = &touches[i];\n break;\n }\n }\n if (grabbed_ && correctTouch != NULL) {\n GamePoint p = correctTouch->location();\n x_ = p.x;\n y_ = p.y;\n }\n}\n\nvoid RoundThing::TouchesEnded(vector<Touch> touches) {\n Touch* correctTouch = NULL;\n for (int i = 0; i < touches.size(); i++) {\n if (touches[i].identifier() == grabbed_touch_) {\n correctTouch = &touches[i];\n break;\n }\n }\n if (grabbed_ && correctTouch != NULL) {\n grabbed_ = false;\n grabbed_touch_ = NULL;\n }\n}\n\nvoid RoundThing::ClearTouches() {\n grabbed_ = false;\n grabbed_touch_ = NULL;\n}\n\n\/\/bool RoundThing::isGrabbable() {\n\/\/ return false;\n\/\/}\n\/\/\n\/\/bool RoundThing::isMovable() {\n\/\/ return true;\n\/\/}\n\/\/ \n\/\/bool RoundThing::containsTouch(Touch *touch) {\n\/\/ double dx = touch->location().x - x_;\n\/\/ double dy = touch->location().y - y_;\n\/\/ return (dx*dx + dy*dy <= radius_*radius_);\n\/\/}\n\/\/\n\/\/bool RoundThing::overlaps(RoundThing * thing) {\n\/\/ double dx = thing->getX() - x_;\n\/\/ double dy = thing->getY() - y_;\n\/\/ double totalRadius = thing->getRadius() + radius_;\n\/\/ return (dx*dx + dy*dy <= totalRadius*totalRadius);\n\/\/}\n<commit_msg>Fixed physics bugs! BIG DEAL.<commit_after>\/\/\n\/\/ round_thing.cc\n\/\/ AirHockey\n\/\/\n\/\/ Created by Jonathan Sharkey on 10-04-14.\n\/\/ Copyright 2010 Sharkable. All rights reserved.\n\/\/\n\n#include \"airhockey\/entities\/round_thing.h\"\n\n#include <cmath>\n\n#include \"airhockey\/entities\/paddle.h\"\n#include \"airhockey\/entities\/puck.h\"\n#include \"gameengine\/game_engine.h\"\n#include \"gameengine\/resource_loader.h\"\n#include \"gameengine\/touch.h\"\n#include \"soundengine\/sound_player.h\"\n\nRoundThing::RoundThing(sp<GameEngine> game_engine)\n : sprite_(game_engine),\n x_(0),\n y_(0),\n old_x_(0),\n old_y_(0),\n vx_(0),\n vy_(0),\n radius_(0),\n mass_(0),\n friction_(0),\n grabbed_(false),\n grabbed_touch_(NULL),\n active_(true) {\n}\n\nRoundThing::RoundThing(sp<GameEngine> game_engine, string texture_name)\n : sprite_(game_engine, texture_name),\n x_(0),\n y_(0),\n old_x_(0),\n old_y_(0),\n vx_(0),\n vy_(0),\n radius_(0),\n mass_(0),\n friction_(0),\n grabbed_(false),\n grabbed_touch_(NULL),\n active_(true) {\n}\n\nRoundThing::~RoundThing() {\n if (sprite_.texture().data_loaded()) {\n ResourceLoader::Instance().ReleaseResource(sprite_.texture());\n }\n}\n\nvoid RoundThing::ApplyFriction() {\n if (!is_grabbed()) {\n vx_ *= friction_;\n vy_ *= friction_;\n }\n}\n\nvoid RoundThing::MaybeBounceOff(RoundThing *other) {\n \/\/ TODO optimize this function.\n \/\/ For now I'm just getting it to work.\n \n double dxFull = x_ - other->x();\n double dyFull = y_ - other->y();\n double radiusTotal = other->radius() + radius_;\n\/\/ double v = sqrt(self.vx * self.vx + self.vy * self.vy);\n\/\/ double otherV = sqrt(other.vx * other.vx + other.vy * other.vy);\n \n if (dxFull*dxFull + dyFull*dyFull <= radiusTotal*radiusTotal) { \n \/\/ Normalize N\n double nL = sqrt(dxFull*dxFull + dyFull*dyFull);\n double dx = dxFull \/ nL;\n double dy = dyFull \/ nL;\n \n \/\/ *** Move the round things outside of each other. ***\n double vFraction = mass_ \/ (other->mass() + mass_);\n \n if ((grabbed_ && !other->is_grabbed() && other->IsMovable()) || !IsMovable()) {\n vFraction = 1;\n } else if ((!grabbed_ && other->is_grabbed()) || !other->IsMovable()) {\n vFraction = 0;\n }\n \n double diff = sqrt(radiusTotal*radiusTotal) - nL;\n other->set_x(other->x() - dx * diff * vFraction);\n other->set_y(other->y() - dy * diff * vFraction);\n vFraction = 1 - vFraction;\n x_ += dx * diff * vFraction;\n y_ += dy * diff * vFraction;\n \n \/\/ *** Now change the direction based on the bounce. ***\n \n \/\/ Based on this: http:\/\/stackoverflow.com\/questions\/573084\/how-to-calculate-bounce-angle\n \/\/ But it had some problems.\n \/\/ Looked at Wikipedia dot product article to help.\n double vDn = vx_ * dx + vy_ * dy;\n double ux = dx * vDn;\n double uy = dy * vDn;\n double wx = vx_ - ux;\n double wy = vy_ - uy;\n \n double othervDn_ = other->vx() * -dx + other->vy() * -dy;\n double otherux_ = -dx * othervDn_;\n double otheruy_ = -dy * othervDn_;\n double otherwx_ = other->vx() - otherux_;\n double otherwy_ = other->vy() - otheruy_;\n \n double newux_ = (ux * fabs(mass_ - other->mass()) - 2.0 * other->mass() * otherux_) \/\n (mass_ + other->mass());\n double newuy_ = (uy * fabs(mass_ - other->mass()) - 2.0 * other->mass() * otheruy_) \/\n (mass_ + other->mass());\n \n double newother_ux_ = (otherux_ * fabs(other->mass() - mass_) - 2.0 * mass_ * ux) \/\n (mass_ + other->mass());\n double newother_uy_ = (otheruy_ * fabs(other->mass() - mass_) - 2.0 * mass_ * uy) \/\n (mass_ + other->mass());\n \n if (!is_grabbed() && IsMovable()) {\n vx_ = wx - newux_;\n vy_ = wy - newuy_;\n }\n \n if (!other->is_grabbed() && other->IsMovable()) {\n other->set_vx(otherwx_ - newother_ux_);\n other->set_vy(otherwy_ - newother_uy_);\n }\n\n double newVSquared = vx_ * vx_ + vy_ * vy_;\n double newOtherVSquared = other->vx() * other->vx() + other->vy() * other->vy();\n \n if (newVSquared > (MAX_SPEED*MAX_SPEED)) {\n double newV = sqrt(newVSquared);\n double newRatio = MAX_SPEED \/ newV;\n vx_ *= newRatio;\n vy_ *= newRatio;\n }\n if (newOtherVSquared > (MAX_SPEED*MAX_SPEED)) {\n double newOtherV = sqrt(newOtherVSquared);\n double newRatio = MAX_SPEED \/ newOtherV;\n other->set_vx(other->vx() * newRatio);\n other->set_vy(other->vy() * newRatio);\n }\n\n DidBounceOff(other);\n } \n}\n\nbool RoundThing::ContainsTouch(Touch *touch) {\n double dx = touch->location().x - x_;\n double dy = touch->location().y - y_;\n return (dx*dx + dy*dy <= radius_*radius_);\n}\n\nbool RoundThing::Overlaps(RoundThing * thing) {\n double dx = thing->x() - x_;\n double dy = thing->y() - y_;\n double totalRadius = thing->radius() + radius_;\n return (dx*dx + dy*dy <= totalRadius*totalRadius);\n}\n\nbool RoundThing::IsGrabbable() {\n return false;\n}\n\nbool RoundThing::IsMovable() {\n return true;\n}\n\n\n\/\/ ViewEntity\n\nvoid RoundThing::Update() {\n if (!IsMovable() || !is_active()) {\n return;\n }\n \n if (!grabbed_) {\n x_ += vx_;\n y_ += vy_;\n } else { \n vx_ = vx_ * 0.75 + (x_ - old_x_) * 0.25;\n vy_ = vy_ * 0.75 + (y_ - old_y_) * 0.25;\n old_x_ = x_;\n old_y_ = y_;\n }\n}\n\nvoid RoundThing::Render() {\n if (active_) {\n sprite_.DrawAtPoint(game_point_make(x_ - sprite_.content_size().width \/ 2,\n y_ - sprite_.content_size().height \/ 2));\n }\n}\n\nvoid RoundThing::TouchesBegan(vector<Touch> touches) {\n if (!IsGrabbable() || !is_active() || is_grabbed()) {\n return;\n }\n for (int i = 0; i < touches.size(); i++) {\n if (ContainsTouch(&touches[i])) {\n grabbed_ = true;\n grabbed_touch_ = touches[i].identifier();\n TouchesMoved(touches);\n vx_ = 0;\n vy_ = 0;\n \/\/ Set oldX_ and oldY_ here so that the velocity stays around 0.\n \/\/ This is when you touch the outside of the RoundThing and it\n \/\/ snaps to center on your touch, it doesn't have a really high\n \/\/ initial velocity.\n old_x_ = x_;\n old_y_ = y_; \n }\n }\n}\n\nvoid RoundThing::TouchesMoved(vector<Touch> touches) {\n Touch* correctTouch = NULL;\n for (int i = 0; i < touches.size(); i++) {\n if (touches[i].identifier() == grabbed_touch_) {\n correctTouch = &touches[i];\n break;\n }\n }\n if (grabbed_ && correctTouch != NULL) {\n GamePoint p = correctTouch->location();\n x_ = p.x;\n y_ = p.y;\n }\n}\n\nvoid RoundThing::TouchesEnded(vector<Touch> touches) {\n Touch* correctTouch = NULL;\n for (int i = 0; i < touches.size(); i++) {\n if (touches[i].identifier() == grabbed_touch_) {\n correctTouch = &touches[i];\n break;\n }\n }\n if (grabbed_ && correctTouch != NULL) {\n grabbed_ = false;\n grabbed_touch_ = NULL;\n }\n}\n\nvoid RoundThing::ClearTouches() {\n grabbed_ = false;\n grabbed_touch_ = NULL;\n}\n\n\/\/bool RoundThing::isGrabbable() {\n\/\/ return false;\n\/\/}\n\/\/\n\/\/bool RoundThing::isMovable() {\n\/\/ return true;\n\/\/}\n\/\/ \n\/\/bool RoundThing::containsTouch(Touch *touch) {\n\/\/ double dx = touch->location().x - x_;\n\/\/ double dy = touch->location().y - y_;\n\/\/ return (dx*dx + dy*dy <= radius_*radius_);\n\/\/}\n\/\/\n\/\/bool RoundThing::overlaps(RoundThing * thing) {\n\/\/ double dx = thing->getX() - x_;\n\/\/ double dy = thing->getY() - y_;\n\/\/ double totalRadius = thing->getRadius() + radius_;\n\/\/ return (dx*dx + dy*dy <= totalRadius*totalRadius);\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <znc\/Chan.h>\n#include <znc\/IRCNetwork.h>\n\nusing std::map;\n\nclass CFloodDetachMod : public CModule {\npublic:\n\tMODCONSTRUCTOR(CFloodDetachMod) {\n\t\tm_iThresholdSecs = 0;\n\t\tm_iThresholdMsgs = 0;\n\t}\n\n\t~CFloodDetachMod() {\n\t}\n\n\tvoid Save() {\n\t\t\/\/ We save the settings twice because the module arguments can\n\t\t\/\/ be more easily edited via webadmin, while the SetNV() stuff\n\t\t\/\/ survives e.g. \/msg *status reloadmod ctcpflood.\n\t\tSetNV(\"secs\", CString(m_iThresholdSecs));\n\t\tSetNV(\"msgs\", CString(m_iThresholdMsgs));\n\n\t\tSetArgs(CString(m_iThresholdMsgs) + \" \" + CString(m_iThresholdSecs));\n\t}\n\n\tbool OnLoad(const CString& sArgs, CString& sMessage) {\n\t\tm_iThresholdMsgs = sArgs.Token(0).ToUInt();\n\t\tm_iThresholdSecs = sArgs.Token(1).ToUInt();\n\n\t\tif (m_iThresholdMsgs == 0 || m_iThresholdSecs == 0) {\n\t\t\tm_iThresholdMsgs = GetNV(\"msgs\").ToUInt();\n\t\t\tm_iThresholdSecs = GetNV(\"secs\").ToUInt();\n\t\t}\n\n\t\tif (m_iThresholdSecs == 0)\n\t\t\tm_iThresholdSecs = 2;\n\t\tif (m_iThresholdMsgs == 0)\n\t\t\tm_iThresholdMsgs = 5;\n\n\t\tSave();\n\n\t\treturn true;\n\t}\n\n\tvoid OnIRCDisconnected() {\n\t\tm_chans.clear();\n\t}\n\n\tvoid Cleanup() {\n\t\tLimits::iterator it;\n\t\ttime_t now = time(NULL);\n\n\t\tfor (it = m_chans.begin(); it != m_chans.end(); ++it) {\n\t\t\t\/\/ The timeout for this channel did not expire yet?\n\t\t\tif (it->second.first + (time_t)m_iThresholdSecs >= now)\n\t\t\t\tcontinue;\n\n\t\t\tCChan *pChan = m_pNetwork->FindChan(it->first);\n\t\t\tif (it->second.second >= m_iThresholdMsgs\n\t\t\t\t\t&& pChan && pChan->IsDetached()) {\n\t\t\t\t\/\/ The channel is detached and it is over the\n\t\t\t\t\/\/ messages limit. Since we only track those\n\t\t\t\t\/\/ limits for non-detached channels or for\n\t\t\t\t\/\/ channels which we detached, this means that\n\t\t\t\t\/\/ we detached because of a flood.\n\n\t\t\t\tPutModule(\"Flood in [\" + pChan->GetName() + \"] is over, \"\n\t\t\t\t\t\t\"re-attaching...\");\n\t\t\t\t\/\/ No buffer playback, makes sense, doesn't it?\n\t\t\t\tpChan->ClearBuffer();\n\t\t\t\tpChan->JoinUser();\n\t\t\t}\n\n\t\t\tLimits::iterator it2 = it++;\n\t\t\tm_chans.erase(it2);\n\n\t\t\t\/\/ Without this Bad Things (tm) could happen\n\t\t\tif (it == m_chans.end())\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Message(CChan& Channel) {\n\t\tLimits::iterator it;\n\t\ttime_t now = time(NULL);\n\n\t\t\/\/ First: Clean up old entries and reattach where necessary\n\t\tCleanup();\n\n\t\tit = m_chans.find(Channel.GetName());\n\n\t\tif (it == m_chans.end()) {\n\t\t\t\/\/ We don't track detached channels\n\t\t\tif (Channel.IsDetached())\n\t\t\t\treturn;\n\n\t\t\t\/\/ This is the first message for this channel, start a\n\t\t\t\/\/ new timeout.\n\t\t\tstd::pair<time_t, unsigned int> tmp(now, 1);\n\t\t\tm_chans[Channel.GetName()] = tmp;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ No need to check it->second.first (expiry time), since\n\t\t\/\/ Cleanup() would have removed it if it was expired.\n\n\t\tif (it->second.second >= m_iThresholdMsgs) {\n\t\t\t\/\/ The channel already hit the limit and we detached the\n\t\t\t\/\/ user, but it is still being flooded, reset the timeout\n\t\t\tit->second.first = now;\n\t\t\tit->second.second++;\n\t\t\treturn;\n\t\t}\n\n\t\tit->second.second++;\n\n\t\tif (it->second.second < m_iThresholdMsgs)\n\t\t\treturn;\n\n\t\t\/\/ The channel hit the limit, reset the timeout so that we keep\n\t\t\/\/ it detached for longer.\n\t\tit->second.first = now;\n\n\t\tChannel.DetachUser();\n\t\tPutModule(\"Channel [\" + Channel.GetName() + \"] was \"\n\t\t\t\t\"flooded, you've been detached\");\n\t}\n\n\tEModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\t\/\/ This also catches OnChanAction()\n\tEModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tEModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tEModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tvoid OnModCommand(const CString& sCommand) {\n\t\tconst CString& sCmd = sCommand.Token(0);\n\t\tconst CString& sArg = sCommand.Token(1, true);\n\n\t\tif (sCmd.Equals(\"secs\") && !sArg.empty()) {\n\t\t\tm_iThresholdSecs = sArg.ToUInt();\n\t\t\tif (m_iThresholdSecs == 0)\n\t\t\t\tm_iThresholdSecs = 1;\n\n\t\t\tPutModule(\"Set seconds limit to [\" + CString(m_iThresholdSecs) + \"]\");\n\t\t\tSave();\n\t\t} else if (sCmd.Equals(\"lines\") && !sArg.empty()) {\n\t\t\tm_iThresholdMsgs = sArg.ToUInt();\n\t\t\tif (m_iThresholdMsgs == 0)\n\t\t\t\tm_iThresholdMsgs = 2;\n\n\t\t\tPutModule(\"Set lines limit to [\" + CString(m_iThresholdMsgs) + \"]\");\n\t\t\tSave();\n\t\t} else if (sCmd.Equals(\"show\")) {\n\t\t\tPutModule(\"Current limit is \" + CString(m_iThresholdMsgs) + \" lines \"\n\t\t\t\t\t\"in \" + CString(m_iThresholdSecs) + \" secs.\");\n\t\t} else {\n\t\t\tPutModule(\"Commands: show, secs <limit>, lines <limit>\");\n\t\t}\n\t}\nprivate:\n\ttypedef map<CString, std::pair<time_t, unsigned int> > Limits;\n\tLimits m_chans;\n\tunsigned int m_iThresholdSecs;\n\tunsigned int m_iThresholdMsgs;\n};\n\ntemplate<> void TModInfo<CFloodDetachMod>(CModInfo& Info) {\n\tInfo.SetWikiPage(\"flooddetach\");\n\tInfo.SetHasArgs(true);\n\tInfo.SetArgsHelpText(\"This user module takes up to two arguments. Arguments are msgs and secs numbers.\");\n}\n\nUSERMODULEDEFS(CFloodDetachMod, \"Detach channels when flooded\")\n<commit_msg>Refactor flooddetach to use command callbacks<commit_after>\/*\n * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <znc\/Chan.h>\n#include <znc\/IRCNetwork.h>\n\nusing std::map;\n\nclass CFloodDetachMod : public CModule {\npublic:\n\tMODCONSTRUCTOR(CFloodDetachMod) {\n\t\tm_iThresholdSecs = 0;\n\t\tm_iThresholdMsgs = 0;\n\n\t\tAddHelpCommand();\n\t\tAddCommand(\"Show\", static_cast<CModCommand::ModCmdFunc>(&CFloodDetachMod::ShowCommand), \"\");\n\t\tAddCommand(\"Secs\", static_cast<CModCommand::ModCmdFunc>(&CFloodDetachMod::SecsCommand), \"[<limit>]\");\n\t\tAddCommand(\"Lines\", static_cast<CModCommand::ModCmdFunc>(&CFloodDetachMod::LinesCommand), \"[<limit>]\");\n\t}\n\n\t~CFloodDetachMod() {\n\t}\n\n\tvoid Save() {\n\t\t\/\/ We save the settings twice because the module arguments can\n\t\t\/\/ be more easily edited via webadmin, while the SetNV() stuff\n\t\t\/\/ survives e.g. \/msg *status reloadmod ctcpflood.\n\t\tSetNV(\"secs\", CString(m_iThresholdSecs));\n\t\tSetNV(\"msgs\", CString(m_iThresholdMsgs));\n\n\t\tSetArgs(CString(m_iThresholdMsgs) + \" \" + CString(m_iThresholdSecs));\n\t}\n\n\tbool OnLoad(const CString& sArgs, CString& sMessage) {\n\t\tm_iThresholdMsgs = sArgs.Token(0).ToUInt();\n\t\tm_iThresholdSecs = sArgs.Token(1).ToUInt();\n\n\t\tif (m_iThresholdMsgs == 0 || m_iThresholdSecs == 0) {\n\t\t\tm_iThresholdMsgs = GetNV(\"msgs\").ToUInt();\n\t\t\tm_iThresholdSecs = GetNV(\"secs\").ToUInt();\n\t\t}\n\n\t\tif (m_iThresholdSecs == 0)\n\t\t\tm_iThresholdSecs = 2;\n\t\tif (m_iThresholdMsgs == 0)\n\t\t\tm_iThresholdMsgs = 5;\n\n\t\tSave();\n\n\t\treturn true;\n\t}\n\n\tvoid OnIRCDisconnected() {\n\t\tm_chans.clear();\n\t}\n\n\tvoid Cleanup() {\n\t\tLimits::iterator it;\n\t\ttime_t now = time(NULL);\n\n\t\tfor (it = m_chans.begin(); it != m_chans.end(); ++it) {\n\t\t\t\/\/ The timeout for this channel did not expire yet?\n\t\t\tif (it->second.first + (time_t)m_iThresholdSecs >= now)\n\t\t\t\tcontinue;\n\n\t\t\tCChan *pChan = m_pNetwork->FindChan(it->first);\n\t\t\tif (it->second.second >= m_iThresholdMsgs\n\t\t\t\t\t&& pChan && pChan->IsDetached()) {\n\t\t\t\t\/\/ The channel is detached and it is over the\n\t\t\t\t\/\/ messages limit. Since we only track those\n\t\t\t\t\/\/ limits for non-detached channels or for\n\t\t\t\t\/\/ channels which we detached, this means that\n\t\t\t\t\/\/ we detached because of a flood.\n\n\t\t\t\tPutModule(\"Flood in [\" + pChan->GetName() + \"] is over, \"\n\t\t\t\t\t\t\"re-attaching...\");\n\t\t\t\t\/\/ No buffer playback, makes sense, doesn't it?\n\t\t\t\tpChan->ClearBuffer();\n\t\t\t\tpChan->JoinUser();\n\t\t\t}\n\n\t\t\tLimits::iterator it2 = it++;\n\t\t\tm_chans.erase(it2);\n\n\t\t\t\/\/ Without this Bad Things (tm) could happen\n\t\t\tif (it == m_chans.end())\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Message(CChan& Channel) {\n\t\tLimits::iterator it;\n\t\ttime_t now = time(NULL);\n\n\t\t\/\/ First: Clean up old entries and reattach where necessary\n\t\tCleanup();\n\n\t\tit = m_chans.find(Channel.GetName());\n\n\t\tif (it == m_chans.end()) {\n\t\t\t\/\/ We don't track detached channels\n\t\t\tif (Channel.IsDetached())\n\t\t\t\treturn;\n\n\t\t\t\/\/ This is the first message for this channel, start a\n\t\t\t\/\/ new timeout.\n\t\t\tstd::pair<time_t, unsigned int> tmp(now, 1);\n\t\t\tm_chans[Channel.GetName()] = tmp;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ No need to check it->second.first (expiry time), since\n\t\t\/\/ Cleanup() would have removed it if it was expired.\n\n\t\tif (it->second.second >= m_iThresholdMsgs) {\n\t\t\t\/\/ The channel already hit the limit and we detached the\n\t\t\t\/\/ user, but it is still being flooded, reset the timeout\n\t\t\tit->second.first = now;\n\t\t\tit->second.second++;\n\t\t\treturn;\n\t\t}\n\n\t\tit->second.second++;\n\n\t\tif (it->second.second < m_iThresholdMsgs)\n\t\t\treturn;\n\n\t\t\/\/ The channel hit the limit, reset the timeout so that we keep\n\t\t\/\/ it detached for longer.\n\t\tit->second.first = now;\n\n\t\tChannel.DetachUser();\n\t\tPutModule(\"Channel [\" + Channel.GetName() + \"] was \"\n\t\t\t\t\"flooded, you've been detached\");\n\t}\n\n\tEModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\t\/\/ This also catches OnChanAction()\n\tEModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tEModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tEModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) {\n\t\tMessage(Channel);\n\t\treturn CONTINUE;\n\t}\n\n\tvoid ShowCommand(const CString& sLine) {\n\t\tPutModule(\"Current limit is \" + CString(m_iThresholdMsgs) + \" lines \"\n\t\t\t\t\"in \" + CString(m_iThresholdSecs) + \" secs.\");\n\t}\n\n\tvoid SecsCommand(const CString& sLine) {\n\t\tconst CString sArg = sLine.Token(1, true);\n\n\t\tif (!sArg.empty()) {\n\t\t\tm_iThresholdSecs = sArg.ToUInt();\n\t\t\tif (m_iThresholdSecs == 0)\n\t\t\t\tm_iThresholdSecs = 1;\n\n\t\t\tPutModule(\"Set seconds limit to [\" + CString(m_iThresholdSecs) + \"]\");\n\t\t\tSave();\n\t\t}\n\t}\n\n\tvoid LinesCommand(const CString& sLine) {\n\t\tconst CString sArg = sLine.Token(1, true);\n\n\t\tif (!sArg.empty()) {\n\t\t\tm_iThresholdMsgs = sArg.ToUInt();\n\t\t\tif (m_iThresholdMsgs == 0)\n\t\t\t\tm_iThresholdMsgs = 2;\n\n\t\t\tPutModule(\"Set lines limit to [\" + CString(m_iThresholdMsgs) + \"]\");\n\t\t\tSave();\n\t\t}\n\t}\n\nprivate:\n\ttypedef map<CString, std::pair<time_t, unsigned int> > Limits;\n\tLimits m_chans;\n\tunsigned int m_iThresholdSecs;\n\tunsigned int m_iThresholdMsgs;\n};\n\ntemplate<> void TModInfo<CFloodDetachMod>(CModInfo& Info) {\n\tInfo.SetWikiPage(\"flooddetach\");\n\tInfo.SetHasArgs(true);\n\tInfo.SetArgsHelpText(\"This user module takes up to two arguments. Arguments are msgs and secs numbers.\");\n}\n\nUSERMODULEDEFS(CFloodDetachMod, \"Detach channels when flooded\")\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 David Shah <david@symbioticeda.com>\n * Copyright (C) 2021 William D. Jones <wjones@wdj-consulting.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include <fstream>\n\n#include \"bitstream.h\"\n#include \"config.h\"\n#include \"nextpnr.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ These seem simple enough to do inline for now.\nnamespace BaseConfigs {\n void config_empty_lcmxo2_1200hc(ChipConfig &cc)\n {\n cc.chip_name = \"LCMXO2-1200HC\";\n\n cc.tiles[\"EBR_R6C11:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C15:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C18:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C21:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C2:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C5:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C8:EBR1\"].add_unknown(0, 12);\n\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 30);\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 32);\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 36);\n\n cc.tiles[\"PT7:CFG3\"].add_unknown(5, 18);\n }\n} \/\/ namespace BaseConfigs\n\n\/\/ Convert an absolute wire name to a relative Trellis one\nstatic std::string get_trellis_wirename(Context *ctx, Location loc, WireId wire)\n{\n std::string basename = ctx->tileInfo(wire)->wire_data[wire.index].name.get();\n std::string prefix2 = basename.substr(0, 2);\n std::string prefix7 = basename.substr(0, 7);\n if (prefix2 == \"G_\" || prefix2 == \"L_\" || prefix2 == \"R_\" || prefix2 == \"U_\" || prefix2 == \"D_\" || prefix7 == \"BRANCH_\")\n return basename;\n if (loc == wire.location)\n return basename;\n std::string rel_prefix;\n if (wire.location.y < loc.y)\n rel_prefix += \"N\" + std::to_string(loc.y - wire.location.y);\n if (wire.location.y > loc.y)\n rel_prefix += \"S\" + std::to_string(wire.location.y - loc.y);\n if (wire.location.x > loc.x)\n rel_prefix += \"E\" + std::to_string(wire.location.x - loc.x);\n if (wire.location.x < loc.x)\n rel_prefix += \"W\" + std::to_string(loc.x - wire.location.x);\n return rel_prefix + \"_\" + basename;\n}\n\nstatic void set_pip(Context *ctx, ChipConfig &cc, PipId pip)\n{\n std::string tile = ctx->getPipTilename(pip);\n std::string source = get_trellis_wirename(ctx, pip.location, ctx->getPipSrcWire(pip));\n std::string sink = get_trellis_wirename(ctx, pip.location, ctx->getPipDstWire(pip));\n cc.tiles[tile].add_arc(sink, source);\n}\n\nstatic std::vector<bool> int_to_bitvector(int val, int size)\n{\n std::vector<bool> bv;\n for (int i = 0; i < size; i++) {\n bv.push_back((val & (1 << i)) != 0);\n }\n return bv;\n}\n\nstatic std::vector<bool> str_to_bitvector(std::string str, int size)\n{\n std::vector<bool> bv;\n bv.resize(size, 0);\n if (str.substr(0, 2) != \"0b\")\n log_error(\"error parsing value '%s', expected 0b prefix\\n\", str.c_str());\n for (int i = 0; i < int(str.size()) - 2; i++) {\n char c = str.at((str.size() - i) - 1);\n NPNR_ASSERT(c == '0' || c == '1');\n bv.at(i) = (c == '1');\n }\n return bv;\n}\n\nstd::string intstr_or_default(const std::unordered_map<IdString, Property> &ct, const IdString &key,\n std::string def = \"0\")\n{\n auto found = ct.find(key);\n if (found == ct.end())\n return def;\n else {\n if (found->second.is_string)\n return found->second.as_string();\n else\n return std::to_string(found->second.as_int64());\n }\n};\n\nvoid write_bitstream(Context *ctx, std::string text_config_file)\n{\n ChipConfig cc;\n\n switch (ctx->args.type) {\n case ArchArgs::LCMXO2_1200HC:\n BaseConfigs::config_empty_lcmxo2_1200hc(cc);\n break;\n default:\n NPNR_ASSERT_FALSE(\"Unsupported device type\");\n }\n\n cc.metadata.push_back(\"Part: \" + ctx->getFullChipName());\n\n \/\/ Add all set, configurable pips to the config\n for (auto pip : ctx->getPips()) {\n if (ctx->getBoundPipNet(pip) != nullptr) {\n if (ctx->getPipClass(pip) == 0) { \/\/ ignore fixed pips\n set_pip(ctx, cc, pip);\n }\n }\n }\n\n \/\/ TODO: Bank Voltages\n\n \/\/ Configure slices\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (ci->bel == BelId()) {\n log_warning(\"found unplaced cell '%s' during bitstream gen\\n\", ci->name.c_str(ctx));\n }\n BelId bel = ci->bel;\n if (ci->type == id_FACADE_SLICE) {\n std::string tname = ctx->getTileByTypeAndLocation(bel.location.y, bel.location.x, \"PLC\");\n std::string slice = ctx->tileInfo(bel)->bel_data[bel.index].name.get();\n\n NPNR_ASSERT(slice.substr(0, 5) == \"SLICE\");\n int int_index = slice[5] - 'A';\n NPNR_ASSERT(int_index >= 0 && int_index < 4);\n\n int lut0_init = int_or_default(ci->params, ctx->id(\"LUT0_INITVAL\"));\n int lut1_init = int_or_default(ci->params, ctx->id(\"LUT1_INITVAL\"));\n cc.tiles[tname].add_word(slice + \".K0.INIT\", int_to_bitvector(lut0_init, 16));\n cc.tiles[tname].add_word(slice + \".K1.INIT\", int_to_bitvector(lut1_init, 16));\n cc.tiles[tname].add_enum(slice + \".MODE\", str_or_default(ci->params, ctx->id(\"MODE\"), \"LOGIC\"));\n cc.tiles[tname].add_enum(slice + \".GSR\", str_or_default(ci->params, ctx->id(\"GSR\"), \"ENABLED\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".SRMODE\", str_or_default(ci->params, ctx->id(\"SRMODE\"), \"LSR_OVER_CE\"));\n cc.tiles[tname].add_enum(slice + \".CEMUX\", intstr_or_default(ci->params, ctx->id(\"CEMUX\"), \"1\"));\n cc.tiles[tname].add_enum(\"CLK\" + std::to_string(int_index) + \".CLKMUX\", intstr_or_default(ci->params, ctx->id(\"CLKMUX\"), \"0\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".LSRMUX\", str_or_default(ci->params, ctx->id(\"LSRMUX\"), \"LSR\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".LSRONMUX\", intstr_or_default(ci->params, ctx->id(\"LSRONMUX\"), \"LSRMUX\"));\n cc.tiles[tname].add_enum(slice + \".REG0.SD\", intstr_or_default(ci->params, ctx->id(\"REG0_SD\"), \"0\"));\n cc.tiles[tname].add_enum(slice + \".REG1.SD\", intstr_or_default(ci->params, ctx->id(\"REG1_SD\"), \"0\"));\n cc.tiles[tname].add_enum(slice + \".REG0.REGSET\",\n str_or_default(ci->params, ctx->id(\"REG0_REGSET\"), \"RESET\"));\n cc.tiles[tname].add_enum(slice + \".REG1.REGSET\",\n str_or_default(ci->params, ctx->id(\"REG1_REGSET\"), \"RESET\"));\n }\n }\n\n \/\/ Configure chip\n if (!text_config_file.empty()) {\n std::ofstream out_config(text_config_file);\n out_config << cc;\n }\n}\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>machxo2: Add REGMODE to bitstream output.<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 David Shah <david@symbioticeda.com>\n * Copyright (C) 2021 William D. Jones <wjones@wdj-consulting.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include <fstream>\n\n#include \"bitstream.h\"\n#include \"config.h\"\n#include \"nextpnr.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ These seem simple enough to do inline for now.\nnamespace BaseConfigs {\n void config_empty_lcmxo2_1200hc(ChipConfig &cc)\n {\n cc.chip_name = \"LCMXO2-1200HC\";\n\n cc.tiles[\"EBR_R6C11:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C15:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C18:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C21:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C2:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C5:EBR1\"].add_unknown(0, 12);\n cc.tiles[\"EBR_R6C8:EBR1\"].add_unknown(0, 12);\n\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 30);\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 32);\n cc.tiles[\"PT4:CFG0\"].add_unknown(5, 36);\n\n cc.tiles[\"PT7:CFG3\"].add_unknown(5, 18);\n }\n} \/\/ namespace BaseConfigs\n\n\/\/ Convert an absolute wire name to a relative Trellis one\nstatic std::string get_trellis_wirename(Context *ctx, Location loc, WireId wire)\n{\n std::string basename = ctx->tileInfo(wire)->wire_data[wire.index].name.get();\n std::string prefix2 = basename.substr(0, 2);\n std::string prefix7 = basename.substr(0, 7);\n if (prefix2 == \"G_\" || prefix2 == \"L_\" || prefix2 == \"R_\" || prefix2 == \"U_\" || prefix2 == \"D_\" || prefix7 == \"BRANCH_\")\n return basename;\n if (loc == wire.location)\n return basename;\n std::string rel_prefix;\n if (wire.location.y < loc.y)\n rel_prefix += \"N\" + std::to_string(loc.y - wire.location.y);\n if (wire.location.y > loc.y)\n rel_prefix += \"S\" + std::to_string(wire.location.y - loc.y);\n if (wire.location.x > loc.x)\n rel_prefix += \"E\" + std::to_string(wire.location.x - loc.x);\n if (wire.location.x < loc.x)\n rel_prefix += \"W\" + std::to_string(loc.x - wire.location.x);\n return rel_prefix + \"_\" + basename;\n}\n\nstatic void set_pip(Context *ctx, ChipConfig &cc, PipId pip)\n{\n std::string tile = ctx->getPipTilename(pip);\n std::string source = get_trellis_wirename(ctx, pip.location, ctx->getPipSrcWire(pip));\n std::string sink = get_trellis_wirename(ctx, pip.location, ctx->getPipDstWire(pip));\n cc.tiles[tile].add_arc(sink, source);\n}\n\nstatic std::vector<bool> int_to_bitvector(int val, int size)\n{\n std::vector<bool> bv;\n for (int i = 0; i < size; i++) {\n bv.push_back((val & (1 << i)) != 0);\n }\n return bv;\n}\n\nstatic std::vector<bool> str_to_bitvector(std::string str, int size)\n{\n std::vector<bool> bv;\n bv.resize(size, 0);\n if (str.substr(0, 2) != \"0b\")\n log_error(\"error parsing value '%s', expected 0b prefix\\n\", str.c_str());\n for (int i = 0; i < int(str.size()) - 2; i++) {\n char c = str.at((str.size() - i) - 1);\n NPNR_ASSERT(c == '0' || c == '1');\n bv.at(i) = (c == '1');\n }\n return bv;\n}\n\nstd::string intstr_or_default(const std::unordered_map<IdString, Property> &ct, const IdString &key,\n std::string def = \"0\")\n{\n auto found = ct.find(key);\n if (found == ct.end())\n return def;\n else {\n if (found->second.is_string)\n return found->second.as_string();\n else\n return std::to_string(found->second.as_int64());\n }\n};\n\nvoid write_bitstream(Context *ctx, std::string text_config_file)\n{\n ChipConfig cc;\n\n switch (ctx->args.type) {\n case ArchArgs::LCMXO2_1200HC:\n BaseConfigs::config_empty_lcmxo2_1200hc(cc);\n break;\n default:\n NPNR_ASSERT_FALSE(\"Unsupported device type\");\n }\n\n cc.metadata.push_back(\"Part: \" + ctx->getFullChipName());\n\n \/\/ Add all set, configurable pips to the config\n for (auto pip : ctx->getPips()) {\n if (ctx->getBoundPipNet(pip) != nullptr) {\n if (ctx->getPipClass(pip) == 0) { \/\/ ignore fixed pips\n set_pip(ctx, cc, pip);\n }\n }\n }\n\n \/\/ TODO: Bank Voltages\n\n \/\/ Configure slices\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (ci->bel == BelId()) {\n log_warning(\"found unplaced cell '%s' during bitstream gen\\n\", ci->name.c_str(ctx));\n }\n BelId bel = ci->bel;\n if (ci->type == id_FACADE_SLICE) {\n std::string tname = ctx->getTileByTypeAndLocation(bel.location.y, bel.location.x, \"PLC\");\n std::string slice = ctx->tileInfo(bel)->bel_data[bel.index].name.get();\n\n NPNR_ASSERT(slice.substr(0, 5) == \"SLICE\");\n int int_index = slice[5] - 'A';\n NPNR_ASSERT(int_index >= 0 && int_index < 4);\n\n int lut0_init = int_or_default(ci->params, ctx->id(\"LUT0_INITVAL\"));\n int lut1_init = int_or_default(ci->params, ctx->id(\"LUT1_INITVAL\"));\n cc.tiles[tname].add_word(slice + \".K0.INIT\", int_to_bitvector(lut0_init, 16));\n cc.tiles[tname].add_word(slice + \".K1.INIT\", int_to_bitvector(lut1_init, 16));\n cc.tiles[tname].add_enum(slice + \".MODE\", str_or_default(ci->params, ctx->id(\"MODE\"), \"LOGIC\"));\n cc.tiles[tname].add_enum(slice + \".GSR\", str_or_default(ci->params, ctx->id(\"GSR\"), \"ENABLED\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".SRMODE\", str_or_default(ci->params, ctx->id(\"SRMODE\"), \"LSR_OVER_CE\"));\n cc.tiles[tname].add_enum(slice + \".CEMUX\", intstr_or_default(ci->params, ctx->id(\"CEMUX\"), \"1\"));\n cc.tiles[tname].add_enum(\"CLK\" + std::to_string(int_index) + \".CLKMUX\", intstr_or_default(ci->params, ctx->id(\"CLKMUX\"), \"0\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".LSRMUX\", str_or_default(ci->params, ctx->id(\"LSRMUX\"), \"LSR\"));\n cc.tiles[tname].add_enum(\"LSR\" + std::to_string(int_index) + \".LSRONMUX\", intstr_or_default(ci->params, ctx->id(\"LSRONMUX\"), \"LSRMUX\"));\n cc.tiles[tname].add_enum(slice + \".REGMODE\", str_or_default(ci->params, ctx->id(\"REGMODE\"), \"FF\"));\n cc.tiles[tname].add_enum(slice + \".REG0.SD\", intstr_or_default(ci->params, ctx->id(\"REG0_SD\"), \"0\"));\n cc.tiles[tname].add_enum(slice + \".REG1.SD\", intstr_or_default(ci->params, ctx->id(\"REG1_SD\"), \"0\"));\n cc.tiles[tname].add_enum(slice + \".REG0.REGSET\",\n str_or_default(ci->params, ctx->id(\"REG0_REGSET\"), \"RESET\"));\n cc.tiles[tname].add_enum(slice + \".REG1.REGSET\",\n str_or_default(ci->params, ctx->id(\"REG1_REGSET\"), \"RESET\"));\n }\n }\n\n \/\/ Configure chip\n if (!text_config_file.empty()) {\n std::ofstream out_config(text_config_file);\n out_config << cc;\n }\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\/* HANDLER ... commands - direct access to ISAM *\/\n\n#include \"mysql_priv.h\"\n#include \"sql_select.h\"\n#include <assert.h>\n\n\/* TODO:\n HANDLER blabla OPEN [ AS foobar ] [ (column-list) ]\n\n the most natural (easiest, fastest) way to do it is to\n compute List<Item> field_list not in mysql_ha_read\n but in mysql_ha_open, and then store it in TABLE structure.\n\n The problem here is that mysql_parse calls free_item to free all the\n items allocated at the end of every query. The workaround would to\n keep two item lists per THD - normal free_list and handler_items.\n The second is to be freeed only on thread end. mysql_ha_open should\n then do { handler_items=concat(handler_items, free_list); free_list=0; }\n\n But !!! do_cammand calls free_root at the end of every query and frees up\n all the sql_alloc'ed memory. It's harder to work around...\n *\/\n\n#define HANDLER_TABLES_HACK(thd) { \\\n TABLE *tmp=thd->open_tables; \\\n thd->open_tables=thd->handler_tables; \\\n thd->handler_tables=tmp; }\n\nstatic TABLE **find_table_ptr_by_name(THD *thd,const char *db,\n\t\t\t\t const char *table_name, bool is_alias);\n\nint mysql_ha_open(THD *thd, TABLE_LIST *tables)\n{\n HANDLER_TABLES_HACK(thd);\n int err=open_tables(thd,tables);\n HANDLER_TABLES_HACK(thd);\n if (err)\n return -1;\n\n \/\/ there can be only one table in *tables\n if (!(tables->table->file->table_flags() & HA_CAN_SQL_HANDLER))\n {\n my_printf_error(ER_ILLEGAL_HA,ER(ER_ILLEGAL_HA),MYF(0), tables->alias);\n mysql_ha_close(thd, tables,1);\n return -1;\n }\n\n send_ok(&thd->net);\n return 0;\n}\n\nint mysql_ha_close(THD *thd, TABLE_LIST *tables, bool dont_send_ok)\n{\n TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->alias, 1);\n\n if (*ptr)\n {\n VOID(pthread_mutex_lock(&LOCK_open));\n close_thread_table(thd, ptr);\n VOID(pthread_mutex_unlock(&LOCK_open));\n }\n else\n {\n my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),\n\t\t tables->alias, \"HANDLER\");\n return -1;\n }\n if (!dont_send_ok)\n send_ok(&thd->net);\n return 0;\n}\n\nint mysql_ha_closeall(THD *thd, TABLE_LIST *tables)\n{\n TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->real_name, 0);\n if (*ptr)\n close_thread_table(thd, ptr);\n return 0;\n}\n\nstatic enum enum_ha_read_modes rkey_to_rnext[]=\n { RNEXT, RNEXT, RPREV, RNEXT, RPREV, RNEXT, RPREV };\n\n\nint mysql_ha_read(THD *thd, TABLE_LIST *tables,\n enum enum_ha_read_modes mode, char *keyname, List<Item> *key_expr,\n enum ha_rkey_function ha_rkey_mode, Item *cond,\n ha_rows select_limit,ha_rows offset_limit)\n{\n int err, keyno=-1;\n TABLE *table=*find_table_ptr_by_name(thd, tables->db, tables->alias, 1);\n if (!table)\n {\n my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),\n\t\t tables->alias,\"HANDLER\");\n return -1;\n }\n tables->table=table;\n\n if (cond && cond->fix_fields(thd,tables))\n return -1;\n\n table->file->init_table_handle_for_HANDLER(); \/\/ Only InnoDB requires it\n\n if (keyname)\n {\n if ((keyno=find_type(keyname, &table->keynames, 1+2)-1)<0)\n {\n my_printf_error(ER_KEY_DOES_NOT_EXITS,ER(ER_KEY_DOES_NOT_EXITS),MYF(0),\n keyname,tables->alias);\n return -1;\n }\n table->file->index_init(keyno);\n }\n\n List<Item> list;\n list.push_front(new Item_field(NULL,NULL,\"*\"));\n List_iterator<Item> it(list);\n uint num_rows;\n it++;\n\n insert_fields(thd,tables,tables->db,tables->alias,&it);\n\n select_limit+=offset_limit;\n send_fields(thd,list,1);\n\n HANDLER_TABLES_HACK(thd);\n MYSQL_LOCK *lock=mysql_lock_tables(thd,&tables->table,1);\n HANDLER_TABLES_HACK(thd);\n if (!lock)\n goto err0; \/\/ mysql_lock_tables() printed error message already\n\n table->file->init_table_handle_for_HANDLER(); \/\/ Only InnoDB requires it\n\n for (num_rows=0; num_rows < select_limit; )\n {\n switch(mode) {\n case RFIRST:\n if (keyname)\n err=table->file->index_first(table->record[0]);\n else\n {\n\tif (!(err=table->file->rnd_init(1)))\n err=table->file->rnd_next(table->record[0]);\n }\n mode=RNEXT;\n break;\n case RLAST:\n DBUG_ASSERT(keyname != 0);\n err=table->file->index_last(table->record[0]);\n mode=RPREV;\n break;\n case RNEXT:\n err=keyname ?\n\ttable->file->index_next(table->record[0]) :\n\ttable->file->rnd_next(table->record[0]);\n break;\n case RPREV:\n DBUG_ASSERT(keyname != 0);\n err=table->file->index_prev(table->record[0]);\n break;\n case RKEY:\n {\n DBUG_ASSERT(keyname != 0);\n KEY *keyinfo=table->key_info+keyno;\n KEY_PART_INFO *key_part=keyinfo->key_part;\n uint key_len;\n byte *key;\n if (key_expr->elements > keyinfo->key_parts)\n {\n\tmy_printf_error(ER_TOO_MANY_KEY_PARTS,ER(ER_TOO_MANY_KEY_PARTS),\n\t\t\tMYF(0),keyinfo->key_parts);\n\tgoto err;\n }\n List_iterator_fast<Item> it_ke(*key_expr);\n Item *item;\n for (key_len=0 ; (item=it_ke++) ; key_part++)\n {\n\tif (item->fix_fields(thd, tables))\n\t return -1;\n\titem->save_in_field(key_part->field, 1);\n\tkey_len+=key_part->store_length;\n }\n if (!(key= (byte*) thd->calloc(ALIGN_SIZE(key_len))))\n {\n\tsend_error(&thd->net,ER_OUTOFMEMORY);\n\tgoto err;\n }\n key_copy(key, table, keyno, key_len);\n err=table->file->index_read(table->record[0],\n\t\t\t\t key,key_len,ha_rkey_mode);\n mode=rkey_to_rnext[(int)ha_rkey_mode];\n break;\n }\n default:\n send_error(&thd->net,ER_ILLEGAL_HA);\n goto err;\n }\n\n if (err)\n {\n if (err != HA_ERR_KEY_NOT_FOUND && err != HA_ERR_END_OF_FILE)\n {\n sql_print_error(\"mysql_ha_read: Got error %d when reading table\",\n err);\n table->file->print_error(err,MYF(0));\n goto err;\n }\n goto ok;\n }\n if (cond)\n {\n err=err;\n if (!cond->val_int())\n continue;\n }\n if (num_rows>=offset_limit)\n {\n if (!err)\n {\n String *packet = &thd->packet;\n Item *item;\n packet->length(0);\n it.rewind();\n while ((item=it++))\n {\n if (item->send(thd,packet))\n {\n packet->free(); \/\/ Free used\n my_error(ER_OUT_OF_RESOURCES,MYF(0));\n goto err;\n }\n }\n my_net_write(&thd->net, (char*)packet->ptr(), packet->length());\n }\n }\n num_rows++;\n }\nok:\n mysql_unlock_tables(thd,lock);\n send_eof(&thd->net);\n return 0;\nerr:\n mysql_unlock_tables(thd,lock);\nerr0:\n return -1;\n}\n\nstatic TABLE **find_table_ptr_by_name(THD *thd, const char *db,\n\t\t\t\t const char *table_name, bool is_alias)\n{\n int dblen;\n TABLE **ptr;\n\n if (!db || ! *db)\n db= thd->db ? thd->db : \"\";\n dblen=strlen(db)+1;\n ptr=&(thd->handler_tables);\n\n for (TABLE *table=*ptr; table ; table=*ptr)\n {\n if (!memcmp(table->table_cache_key, db, dblen) &&\n !my_strcasecmp((is_alias ? table->table_name : table->real_name),table_name))\n break;\n ptr=&(table->next);\n }\n return ptr;\n}\n\n<commit_msg>Fixed memory\/lock leak from bug fix<commit_after>\/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\/* HANDLER ... commands - direct access to ISAM *\/\n\n#include \"mysql_priv.h\"\n#include \"sql_select.h\"\n#include <assert.h>\n\n\/* TODO:\n HANDLER blabla OPEN [ AS foobar ] [ (column-list) ]\n\n the most natural (easiest, fastest) way to do it is to\n compute List<Item> field_list not in mysql_ha_read\n but in mysql_ha_open, and then store it in TABLE structure.\n\n The problem here is that mysql_parse calls free_item to free all the\n items allocated at the end of every query. The workaround would to\n keep two item lists per THD - normal free_list and handler_items.\n The second is to be freeed only on thread end. mysql_ha_open should\n then do { handler_items=concat(handler_items, free_list); free_list=0; }\n\n But !!! do_cammand calls free_root at the end of every query and frees up\n all the sql_alloc'ed memory. It's harder to work around...\n *\/\n\n#define HANDLER_TABLES_HACK(thd) { \\\n TABLE *tmp=thd->open_tables; \\\n thd->open_tables=thd->handler_tables; \\\n thd->handler_tables=tmp; }\n\nstatic TABLE **find_table_ptr_by_name(THD *thd,const char *db,\n\t\t\t\t const char *table_name, bool is_alias);\n\nint mysql_ha_open(THD *thd, TABLE_LIST *tables)\n{\n HANDLER_TABLES_HACK(thd);\n int err=open_tables(thd,tables);\n HANDLER_TABLES_HACK(thd);\n if (err)\n return -1;\n\n \/\/ there can be only one table in *tables\n if (!(tables->table->file->table_flags() & HA_CAN_SQL_HANDLER))\n {\n my_printf_error(ER_ILLEGAL_HA,ER(ER_ILLEGAL_HA),MYF(0), tables->alias);\n mysql_ha_close(thd, tables,1);\n return -1;\n }\n\n send_ok(&thd->net);\n return 0;\n}\n\nint mysql_ha_close(THD *thd, TABLE_LIST *tables, bool dont_send_ok)\n{\n TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->alias, 1);\n\n if (*ptr)\n {\n VOID(pthread_mutex_lock(&LOCK_open));\n close_thread_table(thd, ptr);\n VOID(pthread_mutex_unlock(&LOCK_open));\n }\n else\n {\n my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),\n\t\t tables->alias, \"HANDLER\");\n return -1;\n }\n if (!dont_send_ok)\n send_ok(&thd->net);\n return 0;\n}\n\nint mysql_ha_closeall(THD *thd, TABLE_LIST *tables)\n{\n TABLE **ptr=find_table_ptr_by_name(thd, tables->db, tables->real_name, 0);\n if (*ptr)\n close_thread_table(thd, ptr);\n return 0;\n}\n\nstatic enum enum_ha_read_modes rkey_to_rnext[]=\n { RNEXT, RNEXT, RPREV, RNEXT, RPREV, RNEXT, RPREV };\n\n\nint mysql_ha_read(THD *thd, TABLE_LIST *tables,\n enum enum_ha_read_modes mode, char *keyname, List<Item> *key_expr,\n enum ha_rkey_function ha_rkey_mode, Item *cond,\n ha_rows select_limit,ha_rows offset_limit)\n{\n int err, keyno=-1;\n TABLE *table=*find_table_ptr_by_name(thd, tables->db, tables->alias, 1);\n if (!table)\n {\n my_printf_error(ER_UNKNOWN_TABLE,ER(ER_UNKNOWN_TABLE),MYF(0),\n\t\t tables->alias,\"HANDLER\");\n return -1;\n }\n tables->table=table;\n\n if (cond && cond->fix_fields(thd,tables))\n return -1;\n\n table->file->init_table_handle_for_HANDLER(); \/\/ Only InnoDB requires it\n\n if (keyname)\n {\n if ((keyno=find_type(keyname, &table->keynames, 1+2)-1)<0)\n {\n my_printf_error(ER_KEY_DOES_NOT_EXITS,ER(ER_KEY_DOES_NOT_EXITS),MYF(0),\n keyname,tables->alias);\n return -1;\n }\n table->file->index_init(keyno);\n }\n\n List<Item> list;\n list.push_front(new Item_field(NULL,NULL,\"*\"));\n List_iterator<Item> it(list);\n uint num_rows;\n it++;\n\n insert_fields(thd,tables,tables->db,tables->alias,&it);\n\n select_limit+=offset_limit;\n send_fields(thd,list,1);\n\n HANDLER_TABLES_HACK(thd);\n MYSQL_LOCK *lock=mysql_lock_tables(thd,&tables->table,1);\n HANDLER_TABLES_HACK(thd);\n if (!lock)\n goto err0; \/\/ mysql_lock_tables() printed error message already\n\n table->file->init_table_handle_for_HANDLER(); \/\/ Only InnoDB requires it\n\n for (num_rows=0; num_rows < select_limit; )\n {\n switch(mode) {\n case RFIRST:\n if (keyname)\n err=table->file->index_first(table->record[0]);\n else\n {\n\tif (!(err=table->file->rnd_init(1)))\n err=table->file->rnd_next(table->record[0]);\n }\n mode=RNEXT;\n break;\n case RLAST:\n DBUG_ASSERT(keyname != 0);\n err=table->file->index_last(table->record[0]);\n mode=RPREV;\n break;\n case RNEXT:\n err=keyname ?\n\ttable->file->index_next(table->record[0]) :\n\ttable->file->rnd_next(table->record[0]);\n break;\n case RPREV:\n DBUG_ASSERT(keyname != 0);\n err=table->file->index_prev(table->record[0]);\n break;\n case RKEY:\n {\n DBUG_ASSERT(keyname != 0);\n KEY *keyinfo=table->key_info+keyno;\n KEY_PART_INFO *key_part=keyinfo->key_part;\n uint key_len;\n byte *key;\n if (key_expr->elements > keyinfo->key_parts)\n {\n\tmy_printf_error(ER_TOO_MANY_KEY_PARTS,ER(ER_TOO_MANY_KEY_PARTS),\n\t\t\tMYF(0),keyinfo->key_parts);\n\tgoto err;\n }\n List_iterator_fast<Item> it_ke(*key_expr);\n Item *item;\n for (key_len=0 ; (item=it_ke++) ; key_part++)\n {\n\tif (item->fix_fields(thd, tables))\n\t goto err;\n\titem->save_in_field(key_part->field, 1);\n\tkey_len+=key_part->store_length;\n }\n if (!(key= (byte*) thd->calloc(ALIGN_SIZE(key_len))))\n {\n\tsend_error(&thd->net,ER_OUTOFMEMORY);\n\tgoto err;\n }\n key_copy(key, table, keyno, key_len);\n err=table->file->index_read(table->record[0],\n\t\t\t\t key,key_len,ha_rkey_mode);\n mode=rkey_to_rnext[(int)ha_rkey_mode];\n break;\n }\n default:\n send_error(&thd->net,ER_ILLEGAL_HA);\n goto err;\n }\n\n if (err)\n {\n if (err != HA_ERR_KEY_NOT_FOUND && err != HA_ERR_END_OF_FILE)\n {\n sql_print_error(\"mysql_ha_read: Got error %d when reading table\",\n err);\n table->file->print_error(err,MYF(0));\n goto err;\n }\n goto ok;\n }\n if (cond)\n {\n err=err;\n if (!cond->val_int())\n continue;\n }\n if (num_rows>=offset_limit)\n {\n if (!err)\n {\n String *packet = &thd->packet;\n Item *item;\n packet->length(0);\n it.rewind();\n while ((item=it++))\n {\n if (item->send(thd,packet))\n {\n packet->free(); \/\/ Free used\n my_error(ER_OUT_OF_RESOURCES,MYF(0));\n goto err;\n }\n }\n my_net_write(&thd->net, (char*)packet->ptr(), packet->length());\n }\n }\n num_rows++;\n }\nok:\n mysql_unlock_tables(thd,lock);\n send_eof(&thd->net);\n return 0;\nerr:\n mysql_unlock_tables(thd,lock);\nerr0:\n return -1;\n}\n\nstatic TABLE **find_table_ptr_by_name(THD *thd, const char *db,\n\t\t\t\t const char *table_name, bool is_alias)\n{\n int dblen;\n TABLE **ptr;\n\n if (!db || ! *db)\n db= thd->db ? thd->db : \"\";\n dblen=strlen(db)+1;\n ptr=&(thd->handler_tables);\n\n for (TABLE *table=*ptr; table ; table=*ptr)\n {\n if (!memcmp(table->table_cache_key, db, dblen) &&\n !my_strcasecmp((is_alias ? table->table_name : table->real_name),table_name))\n break;\n ptr=&(table->next);\n }\n return ptr;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n \/\/ clang-format off\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_START EVT_STOP EVT_TOGGLE EVT_TIMER EVT_EOPAT EVT_REPEAT ELSE *\/\n \/* IDLE *\/ ENT_IDLE, ATM_SLEEP, -1, START, -1, START, -1, -1, -1, -1,\n \/* START *\/ ENT_START, -1, -1, -1, -1, -1, -1, -1, -1, SOUND,\n \/* SOUND *\/ ENT_SOUND, -1, -1, -1, IDLE, IDLE, QUIET, -1, -1, -1,\n \/* QUIET *\/ ENT_QUIET, -1, -1, -1, IDLE, IDLE, NEXT, -1, -1, -1,\n \/* NEXT *\/ ENT_NEXT, -1, -1, -1, IDLE, IDLE, -1, REPEAT, -1, SOUND,\n \/* REPEAT *\/ ENT_REPEAT, -1, -1, -1, IDLE, IDLE, -1, -1, FINISH, START,\n \/* FINISH *\/ ENT_FINISH, -1, -1, -1, -1, -1, -1, -1, IDLE, START,\n };\n Machine::begin( state_table, ELSE );\n Atm_player::pin = pin;\n counter_repeat.set( repeatCount = 1 );\n speed( 100 );\n return *this; \n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n switch ( id ) {\n case EVT_START:\n return 0;\n case EVT_TIMER:\n return timer.expired( this );\n case EVT_EOPAT:\n return ( step * 3 ) >= ( patternsize \/ sizeof( pattern[0] ) );\n case EVT_REPEAT:\n return counter_repeat.expired();\n }\n return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n switch ( id ) {\n case ENT_FINISH:\n onfinish.push(); \n return;\n case ENT_IDLE:\n if ( pin >= 0 ) noTone( pin );\n counter_repeat.set( repeatCount );\n return;\n case ENT_START:\n step = 0;\n counter_repeat.decrement();\n return;\n case ENT_SOUND:\n onnote[1].push( pattern[step * 3], 1 );\n if ( pin >= 0 ) tone( pin, pattern[step * 3] );\n timer.set( pattern[step * 3 + 1] * speedFactor );\n return;\n case ENT_QUIET:\n onnote[0].push( pattern[step * 3], 0 );\n if ( pin >= 0 ) noTone( pin );\n timer.set( pattern[step * 3 + 2] * speedFactor );\n return;\n case ENT_NEXT:\n step++;\n return;\n case ENT_REPEAT:\n return;\n }\n}\n\n\/* onNote\/onFinish connector initialization\n * \n *\/\n\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onnote[0].set( callback, idx );\n onnote[1].set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( Machine& machine, int event \/* = 0 *\/ ) {\n onnote[0].set( &machine, event );\n onnote[1].set( &machine, event );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( bool status, atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onnote[status?1:0].set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( bool status, Machine& machine, int event \/* = 0 *\/ ) {\n onnote[status?1:0].set( &machine, event );\n return *this;\n}\n\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onfinish.set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event \/* = 0 *\/ ) {\n onfinish.set( &machine, event );\n return *this;\n}\n\n\/* How many times to repeat the pattern\n * \n *\/\n\nAtm_player& Atm_player::repeat( int v ) {\n counter_repeat.set( repeatCount = v );\n return *this;\n}\n\nAtm_player& Atm_player::speed( int v ) {\n speedFactor = 100 \/ float( v );\n return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n * \n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n pattern = pat;\n patternsize = patsize; \n step = 0;\n return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n stub[0] = freq;\n stub[1] = period;\n stub[2] = pause;\n pattern = stub;\n patternsize = 6; \n counter_repeat.set( repeatCount );\n step = 0;\n return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n Machine::trigger( event );\n return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n return Machine::state();\n}\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream & stream ) {\n Machine::setTrace( &stream, atm_serial_debug::trace,\n \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n return *this;\n}\r\n<commit_msg>Better way to do pattern chaining<commit_after>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n \/\/ clang-format off\n const static state_t state_table[] PROGMEM = {\n \/* ON_ENTER ON_LOOP ON_EXIT EVT_START EVT_STOP EVT_TOGGLE EVT_TIMER EVT_EOPAT EVT_REPEAT ELSE *\/\n \/* IDLE *\/ ENT_IDLE, ATM_SLEEP, -1, START, -1, START, -1, -1, -1, -1,\n \/* START *\/ ENT_START, -1, -1, -1, -1, -1, -1, -1, -1, SOUND,\n \/* SOUND *\/ ENT_SOUND, -1, -1, -1, IDLE, IDLE, QUIET, -1, -1, -1,\n \/* QUIET *\/ ENT_QUIET, -1, -1, -1, IDLE, IDLE, NEXT, -1, -1, -1,\n \/* NEXT *\/ ENT_NEXT, -1, -1, -1, IDLE, IDLE, -1, REPEAT, -1, SOUND,\n \/* REPEAT *\/ ENT_REPEAT, -1, -1, -1, IDLE, IDLE, -1, -1, FINISH, START,\n \/* FINISH *\/ ENT_FINISH, -1, -1, -1, IDLE, -1, -1, -1, IDLE, START,\n };\n Machine::begin( state_table, ELSE );\n Atm_player::pin = pin;\n counter_repeat.set( repeatCount = 1 );\n speed( 100 );\n return *this; \n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n switch ( id ) {\n case EVT_START:\n return 0;\n case EVT_TIMER:\n return timer.expired( this );\n case EVT_EOPAT:\n return ( step * 3 ) >= ( patternsize \/ sizeof( pattern[0] ) );\n case EVT_REPEAT:\n return counter_repeat.expired();\n }\n return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n switch ( id ) {\n case ENT_FINISH:\n onfinish.push(); \n return;\n case ENT_IDLE:\n if ( pin >= 0 ) noTone( pin );\n counter_repeat.set( repeatCount );\n return;\n case ENT_START:\n step = 0;\n counter_repeat.decrement();\n return;\n case ENT_SOUND:\n onnote[1].push( pattern[step * 3], 1 );\n if ( pin >= 0 ) tone( pin, pattern[step * 3] );\n timer.set( pattern[step * 3 + 1] * speedFactor );\n return;\n case ENT_QUIET:\n onnote[0].push( pattern[step * 3], 0 );\n if ( pin >= 0 ) noTone( pin );\n timer.set( pattern[step * 3 + 2] * speedFactor );\n return;\n case ENT_NEXT:\n step++;\n return;\n case ENT_REPEAT:\n return;\n }\n}\n\n\/* onNote\/onFinish connector initialization\n * \n *\/\n\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onnote[0].set( callback, idx );\n onnote[1].set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( Machine& machine, int event \/* = 0 *\/ ) {\n onnote[0].set( &machine, event );\n onnote[1].set( &machine, event );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( bool status, atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onnote[status?1:0].set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onNote( bool status, Machine& machine, int event \/* = 0 *\/ ) {\n onnote[status?1:0].set( &machine, event );\n return *this;\n}\n\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx \/* = 0 *\/ ) {\n onfinish.set( callback, idx );\n return *this;\n}\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event \/* = 0 *\/ ) {\n onfinish.set( &machine, event );\n return *this;\n}\n\n\/* How many times to repeat the pattern\n * \n *\/\n\nAtm_player& Atm_player::repeat( int v ) {\n counter_repeat.set( repeatCount = v );\n return *this;\n}\n\nAtm_player& Atm_player::speed( int v ) {\n speedFactor = 100 \/ float( v );\n return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n * \n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n pattern = pat;\n patternsize = patsize; \n counter_repeat.set( repeatCount );\n step = 0;\n return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n stub[0] = freq;\n stub[1] = period;\n stub[2] = pause;\n pattern = stub;\n patternsize = 6; \n step = 0;\n return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n Machine::trigger( event );\n return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n return Machine::state();\n}\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream & stream ) {\n Machine::setTrace( &stream, atm_serial_debug::trace,\n \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n return *this;\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ WiringPi-Api einbinden\n#include <wiringPi.h>\n\n\/\/Rest einbinden\n#include <iostream>\n#include \"sha256.h\"\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sstream>\n#include <curl\/curl.h>\n\nusing namespace std;\n\n\ntemplate <typename T>\nstring to_string(T value)\n{\n ostringstream os ;\n os << value ;\n return os.str() ;\n}\n\n\n\/\/der Status wird übertragen an den Bashscript\nint send(string status){\nint random = 000000;\nint salt = 000000;\n\nsrand (time(NULL));\t\t\/\/random zeug\nrandom = rand() % 9999 + 10000; \/\/random nummer erzeugen 100000 bis 999999\n\nstring input;\ninput = to_string(random + salt); \/\/nur Strings können gehasht werden und random wird gesalzen durch addition\n\nstring hash = sha256(input); \/\/hashpower!\n\nstringstream sstr;\nsstr << \"hash=\" << hash << \"&pin=\" << random << \"&status=\" << status;\nstring befehl = sstr.str();\n\n\/\/cout << befehl << endl;\n\n\n CURL *curl;\n CURLcode res;\n\n \/\/static const char *postthis=\"hash=hash1337&pin=pin2448&status=statusoffen\";\n\t\/\/static const \n\tconst char* postthis = befehl.c_str();\n\n\n curl = curl_easy_init();\n if(curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"nordlab-ev.de\/doorstate\/setdoorstate.php\");\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);\n\n \/* if we don't provide POSTFIELDSIZE, libcurl will strlen() by\n itself *\/\n curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));\n\n \/* Perform the request, res will get the return code *\/\n res = curl_easy_perform(curl);\n \/* Check for errors *\/\n if(res != CURLE_OK)\n fprintf(stderr, \"curl_easy_perform() failed: %s\\n\",\n curl_easy_strerror(res));\n\n \/* always cleanup *\/\n curl_easy_cleanup(curl);\n }\n\n\n}\n\n\nint main()\n{\n\nint last = 2; \/\/zum start gleich null setzten ist doof, villeicht ist der status noch nicht gemeldet\n \/\/dh. sensor sagt 0 und auf der webseite ist nochd er alte wert 1 ... daher einmal alles melden\n\n \/\/ Starte die WiringPi-Api (wichtig)\n if (wiringPiSetup() == -1)\n return 1;\n\n\t\/\/Ja sind mehr als nötig, aber wer weiß was noch dazu kommt :>\n \/\/ Schalte GPIO 17 (=WiringPi Pin 0) auf Eingang\n pinMode(0, INPUT);\n\n \/\/ Schalte GPIO 27 (=WiringPi Pin 2) auf Eingang\n pinMode(2, INPUT);\n\n \/\/ Schalte GPIO 22 (=WiringPi Pin 3) auf Eingang\n pinMode(3, INPUT);\n\n\n \/\/ Dauerschleife\n while(1) {\n delay(1000); \/\/bremseeee ...\n\n \/\/ GPIO lesen\n if(digitalRead(3)==1 && (last == 0 || last == 2)) {\n printf(\"Geschlossen\\n\");\n \/\/status = \"geschlossen\";\n send(\"geschlossen\");\n last = 1;\n delay(1000); \/\/noch ne bremse ... macht kein sinn aber bremsen stören heir ja nicht\n }\n if(digitalRead(3)==0 && (last == 1 || last == 2)){\n printf(\"Geöffnet\\n\");\n \/\/status = \"offen\";\n send(\"offen\");\n last = 0;\n delay(1000); \/\/noch ne bremse ... macht kein sinn aber bremsen stören heir ja nicht\n }\n}\nreturn 0;\n}\n\n<commit_msg>Cleanup code a bit (indentation, unused code, ...)<commit_after>\/\/ WiringPi-API einbinden\n#include <wiringPi.h>\n\n\/\/ Rest einbinden\n#include <iostream>\n#include \"sha256.h\"\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sstream>\n#include <curl\/curl.h>\n\nusing namespace std;\n\ntemplate <typename T>\nstring to_string(T value)\n{\n\tostringstream os;\n\tos << value;\n\n\treturn os.str();\n}\n\n\/\/ Status an Webseite übertragen\nint send(string status)\n{\n\tint random = 0;\n\tint salt = 0;\n\n\t\/\/ Random Zeug\n\tsrand (time(NULL));\n\t\/\/ zufällige Nummer erzeugen (100000 bis 999999)\n\trandom = rand() % 9999 + 10000;\n\n\tstring input;\n\t\/\/nur Strings können gehasht werden und random wird gesalzen durch addition\n\tinput = to_string(random + salt);\n\n\tstring hash = sha256(input); \/\/hashpower!\n\n\tstringstream sstr;\n\tsstr << \"hash=\" << hash << \"&pin=\" << random << \"&status=\" << status;\n\tstring befehl = sstr.str();\n\n\tCURL *curl;\n\tCURLcode res;\n\n\tconst char* postthis = befehl.c_str();\n\n\tcurl = curl_easy_init();\n\tif (curl) {\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, \"nordlab-ev.de\/doorstate\/setdoorstate.php\");\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);\n\n\t\t\/\/ If we don't provide POSTFIELDSIZE, libcurl will strlen() by itself\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));\n\n\t\t\/\/ Perform the request, res will get the return code\n\t\tres = curl_easy_perform(curl);\n\n\t\t\/\/ Check for errors\n\t\tif (res != CURLE_OK)\n\t\t\tfprintf(stderr, \"curl_easy_perform() failed: %s\\n\",\n\t\t\t\tcurl_easy_strerror(res));\n\n\t\t\/\/ Always cleanup\n\t\tcurl_easy_cleanup(curl);\n\t}\n}\n\nint main()\n{\n\t\/\/ zum start gleich null setzten ist doof, vielleicht ist der status noch nicht gemeldet\n\t\/\/ dh. sensor sagt 0 und auf der webseite ist noch der alte wert 1 ... daher einmal alles melden\n\tint last = 2;\n\n\t\/\/ Starte die WiringPi-API (wichtig)\n\tif (wiringPiSetup() == -1)\n\t\treturn 1;\n\n\t\/\/ Ja sind mehr als nötig, aber wer weiß was noch dazu kommt :>\n\t\/\/ Schalte GPIO 17 (=WiringPi Pin 0) auf Eingang\n\tpinMode(0, INPUT);\n\n\t\/\/ Schalte GPIO 27 (=WiringPi Pin 2) auf Eingang\n\tpinMode(2, INPUT);\n\n\t\/\/ Schalte GPIO 22 (=WiringPi Pin 3) auf Eingang\n\tpinMode(3, INPUT);\n\n\n\t\/\/ Dauerschleife\n\twhile (1) {\n\t\tdelay(1000); \/\/bremseeee ...\n\n\t\t\/\/ GPIO lesen\n\t\tif (digitalRead(3)==1 && (last == 0 || last == 2)) {\n\t\t\tprintf(\"Geschlossen\\n\");\n\t\t\t\/\/status = \"geschlossen\";\n\t\t\tsend(\"geschlossen\");\n\t\t\tlast = 1;\n\t\t\tdelay(1000); \/\/noch ne bremse ... macht kein sinn aber bremsen stören hier ja nicht\n\t\t}\n\t\tif (digitalRead(3)==0 && (last == 1 || last == 2)) {\n\t\t\tprintf(\"Geöffnet\\n\");\n\t\t\t\/\/status = \"offen\";\n\t\t\tsend(\"offen\");\n\t\t\tlast = 0;\n\t\t\tdelay(1000); \/\/noch ne bremse ... macht kein sinn aber bremsen stören hier ja nicht\n }\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * Copyright (c) 2016 by Contributors\n * \\file plan_memory.cc\n * \\brief Assign memory tag to each of the data entries.\n *\/\n#include <nnvm\/graph.h>\n#include <nnvm\/pass.h>\n#include <nnvm\/graph_attr_types.h>\n#include <nnvm\/op_attr_types.h>\n#include <memory>\n#include \".\/graph_algorithm.h\"\n\nnamespace nnvm {\nnamespace pass {\nnamespace {\n\n\/\/ simple graph based allocator.\nclass GraphAllocator {\n public:\n \/\/ storage id equals integer.\n using StorageID = int;\n\n \/\/ bad storage id\n static const StorageID kBadStorageID = -1;\n \/\/ external storage id\n static const StorageID kExternalStorageID = -2;\n\n \/\/ request a free storage\n StorageID Request(int dev_id, int dtype, TShape shape, uint32_t node_id) {\n if (shape.ndim() == 0) return kBadStorageID;\n \/\/ search memory block in [size \/ match_range_, size * match_range_)\n \/\/ TODO(tqchen) add size of the dtype, assume 4 bytes for now\n size_t size = shape.Size() * 4;\n if (match_range_ == 0) return this->Alloc(dev_id, size);\n auto begin = free_.lower_bound(size \/ match_range_);\n auto mid = free_.lower_bound(size);\n auto end = free_.upper_bound(size * match_range_);\n \/\/ search for memory blocks larger than requested\n for (auto it = mid; it != end; ++it) {\n StorageEntry *e = it->second;\n if (e->device_id != dev_id) continue;\n if (node_color_.size() != 0 &&\n node_color_[e->released_by_node] != node_color_[node_id]) continue;\n \/\/ Use exect matching strategy\n e->max_bytes = std::max(size, e->max_bytes);\n \/\/ find a exact match, erase from map and return\n free_.erase(it);\n return e->id;\n }\n \/\/ then search for memory blocks smaller than requested space\n for (auto it = mid; it != begin;) {\n --it;\n StorageEntry *e = it->second;\n if (e->device_id != dev_id) continue;\n if (node_color_.size() != 0 &&\n node_color_[e->released_by_node] != node_color_[node_id]) continue;\n \/\/ Use exect matching strategy\n e->max_bytes = std::max(size, e->max_bytes);\n \/\/ erase from map and return\n free_.erase(it);\n return e->id;\n }\n \/\/ cannot find anything return a new one.\n return this->Alloc(dev_id, size);\n }\n \/\/ release a memory space.\n void Release(StorageID id, uint32_t node_id) {\n CHECK_NE(id, kBadStorageID);\n if (id == kExternalStorageID) return;\n StorageEntry *e = data_[id].get();\n e->released_by_node = node_id;\n free_.insert({e->max_bytes, e});\n }\n\n \/\/ totoal number of bytes allocated\n size_t TotalAllocBytes() const {\n size_t total = 0;\n for (auto &p : data_) {\n total += p->max_bytes;\n }\n return total;\n }\n\n \/\/ constructor\n explicit GraphAllocator(const IndexedGraph* idx, const size_t match_range) : idx_(idx) {\n this->Init(match_range, dmlc::GetEnv(\"NNVM_EXEC_NUM_TEMP\", 1));\n }\n\n private:\n \/\/ initialize the graph allocator\n void Init(const size_t match_range, const uint32_t num_match_color) {\n match_range_ = match_range;\n num_match_color_ = num_match_color;\n if (num_match_color_ > 1) {\n std::vector<uint32_t> importance(idx_->num_nodes(), 0);\n for (uint32_t nid = 0; nid < idx_->num_nodes(); ++nid) {\n if ((*idx_)[nid].source->is_variable()) continue;\n importance[nid] = 1;\n }\n num_match_color_ = pass::ColorNodeGroup(\n *idx_, importance, num_match_color_, &node_color_);\n }\n }\n\n StorageID Alloc(int dev_id, size_t size) {\n StorageID id = static_cast<StorageID>(data_.size());\n std::unique_ptr<StorageEntry> ptr(new StorageEntry());\n ptr->id = id;\n ptr->device_id = dev_id;\n ptr->max_bytes = size;\n data_.emplace_back(std::move(ptr));\n return id;\n }\n \/\/ internal storage entry\n struct StorageEntry {\n \/\/ the id of the entry.\n StorageID id;\n \/\/ the device id of the storage.\n int device_id;\n \/\/ maximum size of storage requested.\n size_t max_bytes{0};\n \/\/ node index that released it last time\n uint32_t released_by_node{0};\n };\n \/\/ scale used for rough match\n size_t match_range_;\n \/\/ whether use color based match algorithm\n uint32_t num_match_color_{1};\n \/\/ the size of each dtype\n std::vector<size_t> dtype_size_dict_;\n \/\/ free list of storage entry\n std::multimap<size_t, StorageEntry*> free_;\n \/\/ all the storage resources available\n std::vector<std::unique_ptr<StorageEntry> > data_;\n \/\/ color of nodes in the graph, used for auxiliary policy making.\n std::vector<uint32_t> node_color_;\n \/\/ internal indexed graph\n const IndexedGraph* idx_;\n};\n\n\/*\n * Internal method to perform the memory allocation for a graph\n * *\/\nsize_t AllocMemory(const Graph& ret, const IndexedGraph& idx, StorageVector* storage_ptr,\n std::vector<int>* storage_inplace_index_ptr, std::vector<uint32_t> ref_count,\n GraphAllocator* allocator) {\n \/\/ Get reference\n auto &storage = *storage_ptr;\n auto &storage_inplace_index = *storage_inplace_index_ptr;\n\n \/\/ Get attributes from the graph\n const ShapeVector& shape_vec = ret.GetAttr<ShapeVector>(\"shape\");\n const DTypeVector& dtype_vec = ret.GetAttr<DTypeVector>(\"dtype\");\n const DeviceVector* device_vec = nullptr;\n static auto& finplace_option = Op::GetAttr<FInplaceOption>(\"FInplaceOption\");\n\n if (ret.attrs.count(\"device\") != 0) {\n device_vec = &(ret.GetAttr<DeviceVector>(\"device\"));\n }\n size_t num_not_allocated = 0;\n\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n const auto& inode = idx[nid];\n if (inode.source->is_variable()) continue;\n \/\/ check inplace option\n if (finplace_option.count(inode.source->op()) != 0) {\n auto inplace_pairs = finplace_option[inode.source->op()](inode.source->attrs);\n for (auto& kv : inplace_pairs) {\n uint32_t eid_out = idx.entry_id(nid, kv.second);\n uint32_t eid_in = idx.entry_id(inode.inputs[kv.first]);\n if (ref_count[eid_in] == 1 &&\n ref_count[eid_out] != 0 &&\n storage[eid_out] == GraphAllocator::kBadStorageID &&\n storage[eid_in] != GraphAllocator::kBadStorageID &&\n shape_vec[eid_out].Size() == shape_vec[eid_in].Size() &&\n dtype_vec[eid_out] == dtype_vec[eid_in]) {\n \/\/ inplace optimization\n storage[eid_out] = storage[eid_in];\n ref_count[eid_in] = 0;\n storage_inplace_index[eid_out] = kv.first;\n }\n }\n }\n \/\/ normal allocation\n const int dev_id = (device_vec != nullptr) ? device_vec->at(nid) : 0;\n \/\/ sort output nodes based on size before allocating output\n std::multimap<size_t, uint32_t> eids;\n for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {\n uint32_t eid = idx.entry_id(nid, index);\n if (storage[eid] == GraphAllocator::kBadStorageID) {\n auto &eshape = shape_vec[eid];\n size_t esize = 0;\n if (eshape.ndim() != 0) esize = eshape.Size();\n eids.insert(std::make_pair(esize, eid));\n }\n }\n for (auto rit = eids.rbegin(); rit != eids.rend(); ++rit) {\n uint32_t eid = rit->second;\n storage[eid] = allocator->Request(dev_id, dtype_vec[eid], shape_vec[eid], nid);\n }\n\n \/\/ check if certain inputs is ignored.\n static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>(\"FIgnoreInputs\");\n std::vector<uint32_t> ignore_inputs;\n if (fignore_inputs.count(inode.source->op()) != 0) {\n ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs);\n std::sort(ignore_inputs.begin(), ignore_inputs.end());\n }\n \/\/ then free inputs\n for (size_t i = 0; i < inode.inputs.size(); ++i) {\n \/\/ ref counter of ignored input is already decreased.\n if (std::binary_search(ignore_inputs.begin(), ignore_inputs.end(), i)) continue;\n const auto& e = inode.inputs[i];\n uint32_t eid = idx.entry_id(e);\n \/\/ temp_ref_count == 0 means it is taken by inplace op\n if (ref_count[eid] == 0) continue;\n \/\/ if we decrease it to zero, means we are ready to relase\n --ref_count[eid];\n if (ref_count[eid] == 0 && storage[eid] != GraphAllocator::kBadStorageID) {\n allocator->Release(storage[eid], nid);\n }\n }\n \/\/ check if there are outputs that can be freeded immediately\n \/\/ these output are not referenced by any operator.\n for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {\n uint32_t eid = idx.entry_id(nid, index);\n if (ref_count[eid] == 0 && storage[eid] != GraphAllocator::kBadStorageID) {\n allocator->Release(storage[eid], nid);\n \/\/ use -2 to indicate that the node was never touched.\n storage_inplace_index[eid] = -2;\n }\n if (storage[eid] == GraphAllocator::kBadStorageID) {\n ++num_not_allocated;\n }\n }\n }\n return num_not_allocated;\n}\n\n\n\/\/ function to plan memory\nGraph PlanMemory(Graph ret) {\n \/\/ setup ref counter\n const IndexedGraph& idx = ret.indexed_graph();\n static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>(\"FIgnoreInputs\");\n \/\/ reference counter of each node\n std::vector<uint32_t> ref_count(idx.num_node_entries(), 0);\n \/\/ step 1: initialize reference count\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n const auto& inode = idx[nid];\n if (inode.source->is_variable()) continue;\n for (const auto& e : inode.inputs) {\n ++ref_count[idx.entry_id(e)];\n }\n \/\/ no dataflow dependency is needed for those are ignored.\n \/\/ revoke the dependency counter.\n if (fignore_inputs.count(inode.source->op()) != 0) {\n auto ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs);\n for (uint32_t i : ignore_inputs) {\n --ref_count[idx.entry_id(inode.inputs[i])];\n }\n }\n }\n for (const auto& e : idx.outputs()) {\n ++ref_count[idx.entry_id(e)];\n }\n \/\/ step 2: allocate memory.\n StorageVector storage;\n if (ret.attrs.count(\"storage\") != 0) {\n storage = ret.MoveCopyAttr<StorageVector>(\"storage\");\n } else {\n storage.resize(idx.num_node_entries(), -1);\n }\n\n \/\/ Search the best NNVM_EXEC_MATCH_RANGE parameter. This is turned off by default\n size_t min_allocated_bytes = -1;\n size_t max_match_range = dmlc::GetEnv(\"NNVM_EXEC_MATCH_RANGE\", 16);\n size_t min_match_range =\n dmlc::GetEnv(\"NNVM_AUTO_SEARCH_MATCH_RANGE\", false) ? 1 : max_match_range;\n for (size_t match_range = min_match_range; match_range <= max_match_range; match_range *= 2) {\n \/\/ Make a copy of related fields\n StorageVector storage_vec(storage);\n std::vector<int> storage_inplace_index(idx.num_node_entries(), -1);\n\n \/\/ the allocator\n GraphAllocator allocator(&idx, match_range);\n\n \/\/ number of entries that are not statically allocated.\n size_t storage_num_not_allocated =\n AllocMemory(ret, idx, &storage_vec, &storage_inplace_index, ref_count, &allocator);\n size_t storage_allocated_bytes = allocator.TotalAllocBytes();\n \/\/ Choose the plan which leads to minimal memory usage\n if (min_allocated_bytes > storage_allocated_bytes) {\n ret.attrs[\"storage_id\"] = std::make_shared<any>(std::move(storage_vec));\n ret.attrs[\"storage_inplace_index\"] = std::make_shared<any>(std::move(storage_inplace_index));\n ret.attrs[\"storage_allocated_bytes\"] = std::make_shared<any>(storage_allocated_bytes);\n ret.attrs[\"storage_num_not_allocated\"] = std::make_shared<any>(storage_num_not_allocated);\n min_allocated_bytes = storage_allocated_bytes;\n }\n }\n return ret;\n}\n\nNNVM_REGISTER_PASS(PlanMemory)\n.describe(\"Plan the memory allocation of each node entries.\")\n.set_body(PlanMemory)\n.set_change_graph(false)\n.depend_graph_attr(\"dtype\")\n.depend_graph_attr(\"shape\")\n.provide_graph_attr(\"storage_id\")\n.provide_graph_attr(\"storage_inplace_index\");\n\n} \/\/ namespace\n} \/\/ namespace pass\n} \/\/ namespace nnvm\n<commit_msg>fix (#111)<commit_after>\/*!\n * Copyright (c) 2016 by Contributors\n * \\file plan_memory.cc\n * \\brief Assign memory tag to each of the data entries.\n *\/\n#include <nnvm\/graph.h>\n#include <nnvm\/pass.h>\n#include <nnvm\/graph_attr_types.h>\n#include <nnvm\/op_attr_types.h>\n#include <memory>\n#include \".\/graph_algorithm.h\"\n\nnamespace nnvm {\nnamespace pass {\nnamespace {\n\n\/\/ simple graph based allocator.\nclass GraphAllocator {\n public:\n \/\/ storage id equals integer.\n using StorageID = int;\n\n \/\/ bad storage id\n static const StorageID kBadStorageID = -1;\n \/\/ external storage id\n static const StorageID kExternalStorageID = -2;\n\n \/\/ request a free storage\n StorageID Request(int dev_id, int dtype, TShape shape, uint32_t node_id) {\n if (shape.ndim() == 0) return kBadStorageID;\n \/\/ search memory block in [size \/ match_range_, size * match_range_)\n \/\/ TODO(tqchen) add size of the dtype, assume 4 bytes for now\n size_t size = shape.Size() * 4;\n if (match_range_ == 0) return this->Alloc(dev_id, size);\n auto begin = free_.lower_bound(size \/ match_range_);\n auto mid = free_.lower_bound(size);\n auto end = free_.upper_bound(size * match_range_);\n \/\/ search for memory blocks larger than requested\n for (auto it = mid; it != end; ++it) {\n StorageEntry *e = it->second;\n if (e->device_id != dev_id) continue;\n if (node_color_.size() != 0 &&\n node_color_[e->released_by_node] != node_color_[node_id]) continue;\n \/\/ Use exect matching strategy\n e->max_bytes = std::max(size, e->max_bytes);\n \/\/ find a exact match, erase from map and return\n free_.erase(it);\n return e->id;\n }\n \/\/ then search for memory blocks smaller than requested space\n for (auto it = mid; it != begin;) {\n --it;\n StorageEntry *e = it->second;\n if (e->device_id != dev_id) continue;\n if (node_color_.size() != 0 &&\n node_color_[e->released_by_node] != node_color_[node_id]) continue;\n \/\/ Use exect matching strategy\n e->max_bytes = std::max(size, e->max_bytes);\n \/\/ erase from map and return\n free_.erase(it);\n return e->id;\n }\n \/\/ cannot find anything return a new one.\n return this->Alloc(dev_id, size);\n }\n \/\/ release a memory space.\n void Release(StorageID id, uint32_t node_id) {\n CHECK_NE(id, kBadStorageID);\n if (id == kExternalStorageID) return;\n StorageEntry *e = data_[id].get();\n e->released_by_node = node_id;\n free_.insert({e->max_bytes, e});\n }\n\n \/\/ totoal number of bytes allocated\n size_t TotalAllocBytes() const {\n size_t total = 0;\n for (auto &p : data_) {\n total += p->max_bytes;\n }\n return total;\n }\n\n \/\/ constructor\n explicit GraphAllocator(const IndexedGraph* idx, const size_t match_range) : idx_(idx) {\n this->Init(match_range, dmlc::GetEnv(\"NNVM_EXEC_NUM_TEMP\", 1));\n }\n\n private:\n \/\/ initialize the graph allocator\n void Init(const size_t match_range, const uint32_t num_match_color) {\n match_range_ = match_range;\n num_match_color_ = num_match_color;\n if (num_match_color_ > 1) {\n std::vector<uint32_t> importance(idx_->num_nodes(), 0);\n for (uint32_t nid = 0; nid < idx_->num_nodes(); ++nid) {\n if ((*idx_)[nid].source->is_variable()) continue;\n importance[nid] = 1;\n }\n num_match_color_ = pass::ColorNodeGroup(\n *idx_, importance, num_match_color_, &node_color_);\n }\n }\n\n StorageID Alloc(int dev_id, size_t size) {\n StorageID id = static_cast<StorageID>(data_.size());\n std::unique_ptr<StorageEntry> ptr(new StorageEntry());\n ptr->id = id;\n ptr->device_id = dev_id;\n ptr->max_bytes = size;\n data_.emplace_back(std::move(ptr));\n return id;\n }\n \/\/ internal storage entry\n struct StorageEntry {\n \/\/ the id of the entry.\n StorageID id;\n \/\/ the device id of the storage.\n int device_id;\n \/\/ maximum size of storage requested.\n size_t max_bytes{0};\n \/\/ node index that released it last time\n uint32_t released_by_node{0};\n };\n \/\/ scale used for rough match\n size_t match_range_;\n \/\/ whether use color based match algorithm\n uint32_t num_match_color_{1};\n \/\/ the size of each dtype\n std::vector<size_t> dtype_size_dict_;\n \/\/ free list of storage entry\n std::multimap<size_t, StorageEntry*> free_;\n \/\/ all the storage resources available\n std::vector<std::unique_ptr<StorageEntry> > data_;\n \/\/ color of nodes in the graph, used for auxiliary policy making.\n std::vector<uint32_t> node_color_;\n \/\/ internal indexed graph\n const IndexedGraph* idx_;\n};\n\n\/*\n * Internal method to perform the memory allocation for a graph\n * *\/\nsize_t AllocMemory(const Graph& ret, const IndexedGraph& idx, StorageVector* storage_ptr,\n std::vector<int>* storage_inplace_index_ptr, std::vector<uint32_t> ref_count,\n GraphAllocator* allocator) {\n \/\/ Get reference\n auto &storage = *storage_ptr;\n auto &storage_inplace_index = *storage_inplace_index_ptr;\n\n \/\/ Get attributes from the graph\n const ShapeVector& shape_vec = ret.GetAttr<ShapeVector>(\"shape\");\n const DTypeVector& dtype_vec = ret.GetAttr<DTypeVector>(\"dtype\");\n const DeviceVector* device_vec = nullptr;\n static auto& finplace_option = Op::GetAttr<FInplaceOption>(\"FInplaceOption\");\n\n if (ret.attrs.count(\"device\") != 0) {\n device_vec = &(ret.GetAttr<DeviceVector>(\"device\"));\n }\n size_t num_not_allocated = 0;\n\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n const auto& inode = idx[nid];\n if (inode.source->is_variable()) continue;\n \/\/ check inplace option\n if (finplace_option.count(inode.source->op()) != 0) {\n auto inplace_pairs = finplace_option[inode.source->op()](inode.source->attrs);\n for (auto& kv : inplace_pairs) {\n uint32_t eid_out = idx.entry_id(nid, kv.second);\n uint32_t eid_in = idx.entry_id(inode.inputs[kv.first]);\n if (ref_count[eid_in] == 1 &&\n ref_count[eid_out] != 0 &&\n storage[eid_out] == GraphAllocator::kBadStorageID &&\n storage[eid_in] >= 0 &&\n shape_vec[eid_out].Size() == shape_vec[eid_in].Size() &&\n dtype_vec[eid_out] == dtype_vec[eid_in]) {\n \/\/ inplace optimization\n storage[eid_out] = storage[eid_in];\n ref_count[eid_in] = 0;\n storage_inplace_index[eid_out] = kv.first;\n }\n }\n }\n \/\/ normal allocation\n const int dev_id = (device_vec != nullptr) ? device_vec->at(nid) : 0;\n \/\/ sort output nodes based on size before allocating output\n std::multimap<size_t, uint32_t> eids;\n for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {\n uint32_t eid = idx.entry_id(nid, index);\n if (storage[eid] == GraphAllocator::kBadStorageID) {\n auto &eshape = shape_vec[eid];\n size_t esize = 0;\n if (eshape.ndim() != 0) esize = eshape.Size();\n eids.insert(std::make_pair(esize, eid));\n }\n }\n for (auto rit = eids.rbegin(); rit != eids.rend(); ++rit) {\n uint32_t eid = rit->second;\n storage[eid] = allocator->Request(dev_id, dtype_vec[eid], shape_vec[eid], nid);\n }\n\n \/\/ check if certain inputs is ignored.\n static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>(\"FIgnoreInputs\");\n std::vector<uint32_t> ignore_inputs;\n if (fignore_inputs.count(inode.source->op()) != 0) {\n ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs);\n std::sort(ignore_inputs.begin(), ignore_inputs.end());\n }\n \/\/ then free inputs\n for (size_t i = 0; i < inode.inputs.size(); ++i) {\n \/\/ ref counter of ignored input is already decreased.\n if (std::binary_search(ignore_inputs.begin(), ignore_inputs.end(), i)) continue;\n const auto& e = inode.inputs[i];\n uint32_t eid = idx.entry_id(e);\n \/\/ temp_ref_count == 0 means it is taken by inplace op\n if (ref_count[eid] == 0) continue;\n \/\/ if we decrease it to zero, means we are ready to relase\n --ref_count[eid];\n if (ref_count[eid] == 0 && storage[eid] != GraphAllocator::kBadStorageID) {\n allocator->Release(storage[eid], nid);\n }\n }\n \/\/ check if there are outputs that can be freeded immediately\n \/\/ these output are not referenced by any operator.\n for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {\n uint32_t eid = idx.entry_id(nid, index);\n if (ref_count[eid] == 0 && storage[eid] != GraphAllocator::kBadStorageID) {\n allocator->Release(storage[eid], nid);\n \/\/ use -2 to indicate that the node was never touched.\n storage_inplace_index[eid] = -2;\n }\n if (storage[eid] == GraphAllocator::kBadStorageID) {\n ++num_not_allocated;\n }\n }\n }\n return num_not_allocated;\n}\n\n\n\/\/ function to plan memory\nGraph PlanMemory(Graph ret) {\n \/\/ setup ref counter\n const IndexedGraph& idx = ret.indexed_graph();\n static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>(\"FIgnoreInputs\");\n \/\/ reference counter of each node\n std::vector<uint32_t> ref_count(idx.num_node_entries(), 0);\n \/\/ step 1: initialize reference count\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n const auto& inode = idx[nid];\n if (inode.source->is_variable()) continue;\n for (const auto& e : inode.inputs) {\n ++ref_count[idx.entry_id(e)];\n }\n \/\/ no dataflow dependency is needed for those are ignored.\n \/\/ revoke the dependency counter.\n if (fignore_inputs.count(inode.source->op()) != 0) {\n auto ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs);\n for (uint32_t i : ignore_inputs) {\n --ref_count[idx.entry_id(inode.inputs[i])];\n }\n }\n }\n for (const auto& e : idx.outputs()) {\n ++ref_count[idx.entry_id(e)];\n }\n \/\/ step 2: allocate memory.\n StorageVector storage;\n if (ret.attrs.count(\"storage\") != 0) {\n storage = ret.MoveCopyAttr<StorageVector>(\"storage\");\n } else {\n storage.resize(idx.num_node_entries(), -1);\n }\n\n \/\/ Search the best NNVM_EXEC_MATCH_RANGE parameter. This is turned off by default\n size_t min_allocated_bytes = -1;\n size_t max_match_range = dmlc::GetEnv(\"NNVM_EXEC_MATCH_RANGE\", 16);\n size_t min_match_range =\n dmlc::GetEnv(\"NNVM_AUTO_SEARCH_MATCH_RANGE\", false) ? 1 : max_match_range;\n for (size_t match_range = min_match_range; match_range <= max_match_range; match_range *= 2) {\n \/\/ Make a copy of related fields\n StorageVector storage_vec(storage);\n std::vector<int> storage_inplace_index(idx.num_node_entries(), -1);\n\n \/\/ the allocator\n GraphAllocator allocator(&idx, match_range);\n\n \/\/ number of entries that are not statically allocated.\n size_t storage_num_not_allocated =\n AllocMemory(ret, idx, &storage_vec, &storage_inplace_index, ref_count, &allocator);\n size_t storage_allocated_bytes = allocator.TotalAllocBytes();\n \/\/ Choose the plan which leads to minimal memory usage\n if (min_allocated_bytes > storage_allocated_bytes) {\n ret.attrs[\"storage_id\"] = std::make_shared<any>(std::move(storage_vec));\n ret.attrs[\"storage_inplace_index\"] = std::make_shared<any>(std::move(storage_inplace_index));\n ret.attrs[\"storage_allocated_bytes\"] = std::make_shared<any>(storage_allocated_bytes);\n ret.attrs[\"storage_num_not_allocated\"] = std::make_shared<any>(storage_num_not_allocated);\n min_allocated_bytes = storage_allocated_bytes;\n }\n }\n return ret;\n}\n\nNNVM_REGISTER_PASS(PlanMemory)\n.describe(\"Plan the memory allocation of each node entries.\")\n.set_body(PlanMemory)\n.set_change_graph(false)\n.depend_graph_attr(\"dtype\")\n.depend_graph_attr(\"shape\")\n.provide_graph_attr(\"storage_id\")\n.provide_graph_attr(\"storage_inplace_index\");\n\n} \/\/ namespace\n} \/\/ namespace pass\n} \/\/ namespace nnvm\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <v8.h>\n#include <uv.h>\n\n#include \"..\/INCHI-1-API\/INCHI_API\/inchi_dll\/inchi_api.h\"\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(\"world\"));\n}\n\nHandle<Value> StructureToInChI(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(\"world\"));\n\n \/\/ build INCHI_Input structure from args\n\n \/\/\n\n}\n\n\nvoid init(Handle<Object> exports) {\n exports->Set(String::NewSymbol(\"hello\"),\n FunctionTemplate::New(Method)->GetFunction());\n\n}\n\nNODE_MODULE(libinchi, init)\n<commit_msg>add getAlgorithmVersion<commit_after>#include <node.h>\n#include <v8.h>\n#include <uv.h>\n\n#include \"..\/INCHI-1-API\/INCHI_API\/inchi_dll\/inchi_api.h\"\n#include \"..\/INCHI-1-API\/INCHI_API\/inchi_dll\/mode.h\"\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(\"world\"));\n}\n\nHandle<Value> StructureToInChI(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(\"world\"));\n\n \/\/ build INCHI_Input structure from args\n\n \/\/\n\n}\n\nHandle<Value> getAlgorithmVersion(const Arguments& args) {\n HandleScope scope;\n return scope.Close(String::New(INCHI_VERSION));\n}\n\n\nvoid init(Handle<Object> exports) {\n exports->Set(String::NewSymbol(\"hello\"),\n FunctionTemplate::New(Method)->GetFunction());\n exports->Set(String::NewSymbol(\"getAlgorithmVersion\"),\n FunctionTemplate::New(getAlgorithmVersion)->GetFunction());\n}\n\nNODE_MODULE(libinchi, init)\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RealTimeClock.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 07\/05\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Apple_RealTimeClock_hpp\n#define Apple_RealTimeClock_hpp\n\nnamespace Apple {\nnamespace Clock {\n\n\/*!\n\tModels Apple's real-time clocks, as contained in the Macintosh and IIgs.\n\n\tSince tracking of time is pushed to this class, it is assumed\n\tthat whomever is translating real time into emulated time\n\twill also signal interrupts — this is just the storage and time counting.\n*\/\nclass ClockStorage {\n\tpublic:\n\t\tClockStorage() {\n\t\t\t\/\/ TODO: this should persist, if possible, rather than\n\t\t\t\/\/ being default initialised.\n\t\t\tconstexpr uint8_t default_data[] = {\n\t\t\t\t0xa8, 0x00, 0x00, 0x00,\n\t\t\t\t0xcc, 0x0a, 0xcc, 0x0a,\n\t\t\t\t0x00, 0x00, 0x00, 0x00,\n\t\t\t\t0x00, 0x02, 0x63, 0x00,\n\t\t\t\t0x03, 0x88, 0x00, 0x4c\n\t\t\t};\n\t\t\tmemcpy(data_, default_data, sizeof(default_data));\n\t\t\tmemset(&data_[sizeof(default_data)], 0xff, sizeof(data_) - sizeof(default_data));\n\t\t}\n\n\t\t\/*!\n\t\t\tAdvances the clock by 1 second.\n\n\t\t\tThe caller should also signal an interrupt.\n\t\t*\/\n\t\tvoid update() {\n\t\t\tfor(int c = 0; c < 4; ++c) {\n\t\t\t\t++seconds_[c];\n\t\t\t\tif(seconds_[c]) break;\n\t\t\t}\n\t\t}\n\n\tprotected:\n\t\tstatic constexpr uint16_t NoResult = 0x100;\n\t\tstatic constexpr uint16_t DidComplete = 0x101;\n\t\tuint16_t perform(uint8_t command) {\n\t\t\t\/*\n\t\t\t\tDocumented commands:\n\n\t\t\t\t\tz0000001\t\tSeconds register 0 (lowest order byte)\n\t\t\t\t\tz0000101\t\tSeconds register 1\n\t\t\t\t\tz0001001\t\tSeconds register 2\n\t\t\t\t\tz0001101\t\tSeconds register 3\n\t\t\t\t\t00110001\t\tTest register (write only)\n\t\t\t\t\t00110101\t\tWrite-protect register (write only)\n\t\t\t\t\tz010aa01\t\tRAM addresses 0x10 - 0x13\n\t\t\t\t\tz1aaaa01\t\tRAM addresses 0x00 – 0x0f\n\n\t\t\t\t\tz0111abc, followed by 0defgh00\n\t\t\t\t\t\t\t\t\tRAM address abcdefgh\n\n\t\t\t\t\tz = 1 => a read; z = 0 => a write.\n\n\t\t\t\tThe top bit of the write-protect register enables (0) or disables (1)\n\t\t\t\twrites to other locations.\n\n\t\t\t\tAll the documentation says about the test register is to set the top\n\t\t\t\ttwo bits to 0 for normal operation. Abnormal operation is undefined.\n\t\t\t*\/\n\t\t\tswitch(phase_) {\n\t\t\t\tcase Phase::Command:\n\t\t\t\t\t\/\/ Decode an address.\n\t\t\t\t\tswitch(command & 0x70) {\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tif(command & 0x40) {\n\t\t\t\t\t\t\t\t\/\/ RAM addresses 0x00 – 0x0f.\n\t\t\t\t\t\t\t\taddress_ = (command >> 2) & 0xf;\n\t\t\t\t\t\t\t} else return DidComplete;\t\/\/ Unrecognised.\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\t\t\/\/ A time access.\n\t\t\t\t\t\t\taddress_ = SecondsBuffer + ((command >> 2)&3);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x30:\n\t\t\t\t\t\t\t\/\/ Either a register access or an extended instruction.\n\t\t\t\t\t\t\tif(command & 0x08) {\n\t\t\t\t\t\t\t\taddress_ = (command & 0x7) << 5;\n\t\t\t\t\t\t\t\tphase_ = (command & 0x80) ? Phase::SecondAddressByteRead : Phase::SecondAddressByteWrite;\n\t\t\t\t\t\t\t\treturn NoResult;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\taddress_ = (command & 4) ? RegisterWriteProtect : RegisterTest;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\/\/ RAM addresses 0x10 – 0x13.\n\t\t\t\t\t\t\taddress_ = 0x10 + ((command >> 2) & 0x3);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ If this is a read, return a result; otherwise prepare to write.\n\t\t\t\t\tif(command & 0x80) {\n\t\t\t\t\t\t\/\/ The two registers are write-only.\n\t\t\t\t\t\tif(address_ == RegisterTest || address_ == RegisterWriteProtect) {\n\t\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (address_ >= SecondsBuffer) ? seconds_[address_ & 0xff] : data_[address_];\n\t\t\t\t\t}\n\t\t\t\t\tphase_ = Phase::WriteData;\n\t\t\t\treturn NoResult;\n\n\t\t\t\tcase Phase::SecondAddressByteRead:\n\t\t\t\tcase Phase::SecondAddressByteWrite:\n\t\t\t\t\tif(command & 0x83) {\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\t\t\t\t\taddress_ |= command >> 2;\n\n\t\t\t\t\tif(phase_ == Phase::SecondAddressByteRead) {\n\t\t\t\t\t\tphase_ = Phase::Command;\n\t\t\t\t\t\treturn data_[address_];\t\/\/ Only RAM accesses can get this far.\n\t\t\t\t\t} else {\n\t\t\t\t\t\tphase_ = Phase::WriteData;\n\t\t\t\t\t}\n\t\t\t\treturn NoResult;\n\n\t\t\t\tcase Phase::WriteData:\n\t\t\t\t\t\/\/ First test: is this to the write-protect register?\n\t\t\t\t\tif(address_ == RegisterWriteProtect) {\n\t\t\t\t\t\twrite_protect_ = command;\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(address_ == RegisterTest) {\n\t\t\t\t\t\t\/\/ No documentation here.\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ No other writing is permitted if the write protect\n\t\t\t\t\t\/\/ register won't allow it.\n\t\t\t\t\tif(!(write_protect_ & 0x80)) {\n\t\t\t\t\t\tif(address_ >= SecondsBuffer) {\n\t\t\t\t\t\t\tseconds_[address_ & 0xff] = command;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdata_[address_] = command;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tphase_ = Phase::Command;\n\t\t\t\treturn DidComplete;\n\t\t\t}\n\n\t\t\treturn NoResult;\n\t\t}\n\n\n\tprivate:\n\t\tuint8_t data_[256];\n\t\tuint8_t seconds_[4];\n\t\tuint8_t write_protect_;\n\t\tint address_;\n\n\t\tstatic constexpr int SecondsBuffer = 0x100;\n\t\tstatic constexpr int RegisterTest = 0x200;\n\t\tstatic constexpr int RegisterWriteProtect = 0x201;\n\n\t\tenum class Phase {\n\t\t\tCommand,\n\t\t\tSecondAddressByteRead,\n\t\t\tSecondAddressByteWrite,\n\t\t\tWriteData\n\t\t};\n\t\tPhase phase_ = Phase::Command;\n\n};\n\n\/*!\n\tProvides the serial interface implemented by the Macintosh.\n*\/\nclass SerialClock: public ClockStorage {\n\tpublic:\n\t\t\/*!\n\t\t\tSets the current clock and data inputs to the clock.\n\t\t*\/\n\t\tvoid set_input(bool clock, bool data) {\n\t\t\t\/\/ \tThe data line is valid when the clock transitions to level 0.\n\t\t\tif(clock && !previous_clock_) {\n\t\t\t\t\/\/ Shift into the command_ register, no matter what.\n\t\t\t\tcommand_ = uint16_t((command_ << 1) | (data ? 1 : 0));\n\t\t\t\tresult_ <<= 1;\n\n\t\t\t\t\/\/ Increment phase.\n\t\t\t\t++phase_;\n\n\t\t\t\t\/\/ If a whole byte has been collected, push it onwards.\n\t\t\t\tif(!(phase_&7)) {\n\t\t\t\t\t\/\/ Begin pessimistically.\n\t\t\t\t\tconst auto effect = perform(uint8_t(command_));\n\n\t\t\t\t\tswitch(effect) {\n\t\t\t\t\t\tcase ClockStorage::NoResult:\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tresult_ = uint8_t(effect);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase ClockStorage::DidComplete:\n\t\t\t\t\t\t\tabort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprevious_clock_ = clock;\n\t\t}\n\n\t\t\/*!\n\t\t\tReads the current data output level from the clock.\n\t\t*\/\n\t\tbool get_data() {\n\t\t\treturn !!(result_ & 0x80);\n\t\t}\n\n\t\t\/*!\n\t\t\tAnnounces that a serial command has been aborted.\n\t\t*\/\n\t\tvoid abort() {\n\t\t\tresult_ = 0;\n\t\t\tphase_ = 0;\n\t\t\tcommand_ = 0;\n\t\t}\n\n\tprivate:\n\t\tint phase_ = 0;\n\t\tuint16_t command_;\n\t\tuint8_t result_ = 0;\n\n\t\tbool previous_clock_ = false;\n};\n\n\/*!\n\tProvides the parallel interface implemented by the IIgs.\n*\/\nclass ParallelClock: public ClockStorage {\n\tpublic:\n\t\tvoid set_control(uint8_t control) {\n\t\t\tif(!(control&0x80)) return;\n\n\t\t\tif(control & 0x40) {\n\t\t\t\t\/\/ Read from the RTC.\n\t\t\t\t\/\/ A no-op for now.\n\t\t\t} else {\n\t\t\t\t\/\/ Write to the RTC. Which in this implementation also sets up a future read.\n\t\t\t\tconst auto result = perform(data_);\n\t\t\t\tif(result != NoResult) {\n\t\t\t\t\tdata_ = uint8_t(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ MAGIC! The transaction took 0 seconds.\n\t\t\t\/\/ TODO: no magic.\n\t\t\tcontrol_ = control & 0x7f;\n\n\t\t\t\/\/ Bit 5 is also meant to be 1 or 0 to indicate the final byte.\n\t\t}\n\n\t\tuint8_t get_control() {\n\t\t\treturn control_;\n\t\t}\n\n\t\tvoid set_data(uint8_t data) {\n\t\t\tdata_ = data;\n\t\t}\n\n\t\tuint8_t get_data() {\n\t\t\treturn data_;\n\t\t}\n\n\tprivate:\n\t\tuint8_t data_;\n\t\tuint8_t control_;\n};\n\n}\n}\n\n#endif \/* Apple_RealTimeClock_hpp *\/\n<commit_msg>Switch to zero-initialised state; be more careful about resetting data.<commit_after>\/\/\n\/\/ RealTimeClock.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 07\/05\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Apple_RealTimeClock_hpp\n#define Apple_RealTimeClock_hpp\n\nnamespace Apple {\nnamespace Clock {\n\n\/*!\n\tModels Apple's real-time clocks, as contained in the Macintosh and IIgs.\n\n\tSince tracking of time is pushed to this class, it is assumed\n\tthat whomever is translating real time into emulated time\n\twill also signal interrupts — this is just the storage and time counting.\n*\/\nclass ClockStorage {\n\tpublic:\n\t\tClockStorage() {\n\t\t\t\/\/ TODO: this should persist, if possible, rather than\n\t\t\t\/\/ being default initialised.\n\/\/\t\t\tconstexpr uint8_t default_data[] = {\n\/\/\t\t\t\t0xa8, 0x00, 0x00, 0x00,\n\/\/\t\t\t\t0xcc, 0x0a, 0xcc, 0x0a,\n\/\/\t\t\t\t0x00, 0x00, 0x00, 0x00,\n\/\/\t\t\t\t0x00, 0x02, 0x63, 0x00,\n\/\/\t\t\t\t0x03, 0x88, 0x00, 0x4c\n\/\/\t\t\t};\n\/\/\t\t\tmemcpy(data_, default_data, sizeof(default_data));\n\/\/\t\t\tmemset(&data_[sizeof(default_data)], 0xff, sizeof(data_) - sizeof(default_data));\n\t\t}\n\n\t\t\/*!\n\t\t\tAdvances the clock by 1 second.\n\n\t\t\tThe caller should also signal an interrupt.\n\t\t*\/\n\t\tvoid update() {\n\t\t\tfor(int c = 0; c < 4; ++c) {\n\t\t\t\t++seconds_[c];\n\t\t\t\tif(seconds_[c]) break;\n\t\t\t}\n\t\t}\n\n\tprotected:\n\t\tstatic constexpr uint16_t NoResult = 0x100;\n\t\tstatic constexpr uint16_t DidComplete = 0x101;\n\t\tuint16_t perform(uint8_t command) {\n\t\t\t\/*\n\t\t\t\tDocumented commands:\n\n\t\t\t\t\tz0000001\t\tSeconds register 0 (lowest order byte)\n\t\t\t\t\tz0000101\t\tSeconds register 1\n\t\t\t\t\tz0001001\t\tSeconds register 2\n\t\t\t\t\tz0001101\t\tSeconds register 3\n\t\t\t\t\t00110001\t\tTest register (write only)\n\t\t\t\t\t00110101\t\tWrite-protect register (write only)\n\t\t\t\t\tz010aa01\t\tRAM addresses 0x10 - 0x13\n\t\t\t\t\tz1aaaa01\t\tRAM addresses 0x00 – 0x0f\n\n\t\t\t\t\tz0111abc, followed by 0defgh00\n\t\t\t\t\t\t\t\t\tRAM address abcdefgh\n\n\t\t\t\t\tz = 1 => a read; z = 0 => a write.\n\n\t\t\t\tThe top bit of the write-protect register enables (0) or disables (1)\n\t\t\t\twrites to other locations.\n\n\t\t\t\tAll the documentation says about the test register is to set the top\n\t\t\t\ttwo bits to 0 for normal operation. Abnormal operation is undefined.\n\t\t\t*\/\n\t\t\tswitch(phase_) {\n\t\t\t\tcase Phase::Command:\n\t\t\t\t\t\/\/ Decode an address.\n\t\t\t\t\tswitch(command & 0x70) {\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tif(command & 0x40) {\n\t\t\t\t\t\t\t\t\/\/ RAM addresses 0x00 – 0x0f.\n\t\t\t\t\t\t\t\taddress_ = (command >> 2) & 0xf;\n\t\t\t\t\t\t\t} else return DidComplete;\t\/\/ Unrecognised.\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 0x00:\n\t\t\t\t\t\t\t\/\/ A time access.\n\t\t\t\t\t\t\taddress_ = SecondsBuffer + ((command >> 2)&3);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x30:\n\t\t\t\t\t\t\t\/\/ Either a register access or an extended instruction.\n\t\t\t\t\t\t\tif(command & 0x08) {\n\t\t\t\t\t\t\t\taddress_ = (command & 0x7) << 5;\n\t\t\t\t\t\t\t\tphase_ = (command & 0x80) ? Phase::SecondAddressByteRead : Phase::SecondAddressByteWrite;\n\t\t\t\t\t\t\t\treturn NoResult;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\taddress_ = (command & 4) ? RegisterWriteProtect : RegisterTest;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\/\/ RAM addresses 0x10 – 0x13.\n\t\t\t\t\t\t\taddress_ = 0x10 + ((command >> 2) & 0x3);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ If this is a read, return a result; otherwise prepare to write.\n\t\t\t\t\tif(command & 0x80) {\n\t\t\t\t\t\t\/\/ The two registers are write-only.\n\t\t\t\t\t\tif(address_ == RegisterTest || address_ == RegisterWriteProtect) {\n\t\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn (address_ >= SecondsBuffer) ? seconds_[address_ & 0xff] : data_[address_];\n\t\t\t\t\t}\n\t\t\t\t\tphase_ = Phase::WriteData;\n\t\t\t\treturn NoResult;\n\n\t\t\t\tcase Phase::SecondAddressByteRead:\n\t\t\t\tcase Phase::SecondAddressByteWrite:\n\t\t\t\t\tif(command & 0x83) {\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\t\t\t\t\taddress_ |= command >> 2;\n\n\t\t\t\t\tif(phase_ == Phase::SecondAddressByteRead) {\n\t\t\t\t\t\tphase_ = Phase::Command;\n\t\t\t\t\t\treturn data_[address_];\t\/\/ Only RAM accesses can get this far.\n\t\t\t\t\t} else {\n\t\t\t\t\t\tphase_ = Phase::WriteData;\n\t\t\t\t\t}\n\t\t\t\treturn NoResult;\n\n\t\t\t\tcase Phase::WriteData:\n\t\t\t\t\t\/\/ First test: is this to the write-protect register?\n\t\t\t\t\tif(address_ == RegisterWriteProtect) {\n\t\t\t\t\t\twrite_protect_ = command;\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(address_ == RegisterTest) {\n\t\t\t\t\t\t\/\/ No documentation here.\n\t\t\t\t\t\treturn DidComplete;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ No other writing is permitted if the write protect\n\t\t\t\t\t\/\/ register won't allow it.\n\t\t\t\t\tif(!(write_protect_ & 0x80)) {\n\t\t\t\t\t\tif(address_ >= SecondsBuffer) {\n\t\t\t\t\t\t\tseconds_[address_ & 0xff] = command;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdata_[address_] = command;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tphase_ = Phase::Command;\n\t\t\t\treturn DidComplete;\n\t\t\t}\n\n\t\t\treturn NoResult;\n\t\t}\n\n\n\tprivate:\n\t\tuint8_t data_[256]{};\n\t\tuint8_t seconds_[4]{};\n\t\tuint8_t write_protect_ = 0;\n\t\tint address_ = 0;\n\n\t\tstatic constexpr int SecondsBuffer = 0x100;\n\t\tstatic constexpr int RegisterTest = 0x200;\n\t\tstatic constexpr int RegisterWriteProtect = 0x201;\n\n\t\tenum class Phase {\n\t\t\tCommand,\n\t\t\tSecondAddressByteRead,\n\t\t\tSecondAddressByteWrite,\n\t\t\tWriteData\n\t\t};\n\t\tPhase phase_ = Phase::Command;\n\n};\n\n\/*!\n\tProvides the serial interface implemented by the Macintosh.\n*\/\nclass SerialClock: public ClockStorage {\n\tpublic:\n\t\t\/*!\n\t\t\tSets the current clock and data inputs to the clock.\n\t\t*\/\n\t\tvoid set_input(bool clock, bool data) {\n\t\t\t\/\/ \tThe data line is valid when the clock transitions to level 0.\n\t\t\tif(clock && !previous_clock_) {\n\t\t\t\t\/\/ Shift into the command_ register, no matter what.\n\t\t\t\tcommand_ = uint16_t((command_ << 1) | (data ? 1 : 0));\n\t\t\t\tresult_ <<= 1;\n\n\t\t\t\t\/\/ Increment phase.\n\t\t\t\t++phase_;\n\n\t\t\t\t\/\/ If a whole byte has been collected, push it onwards.\n\t\t\t\tif(!(phase_&7)) {\n\t\t\t\t\t\/\/ Begin pessimistically.\n\t\t\t\t\tconst auto effect = perform(uint8_t(command_));\n\n\t\t\t\t\tswitch(effect) {\n\t\t\t\t\t\tcase ClockStorage::NoResult:\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tresult_ = uint8_t(effect);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase ClockStorage::DidComplete:\n\t\t\t\t\t\t\tabort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprevious_clock_ = clock;\n\t\t}\n\n\t\t\/*!\n\t\t\tReads the current data output level from the clock.\n\t\t*\/\n\t\tbool get_data() {\n\t\t\treturn !!(result_ & 0x80);\n\t\t}\n\n\t\t\/*!\n\t\t\tAnnounces that a serial command has been aborted.\n\t\t*\/\n\t\tvoid abort() {\n\t\t\tresult_ = 0;\n\t\t\tphase_ = 0;\n\t\t\tcommand_ = 0;\n\t\t}\n\n\tprivate:\n\t\tint phase_ = 0;\n\t\tuint16_t command_;\n\t\tuint8_t result_ = 0;\n\n\t\tbool previous_clock_ = false;\n};\n\n\/*!\n\tProvides the parallel interface implemented by the IIgs.\n*\/\nclass ParallelClock: public ClockStorage {\n\tpublic:\n\t\tvoid set_control(uint8_t control) {\n\t\t\tif(!(control&0x80)) return;\n\n\t\t\tif(control & 0x40) {\n\t\t\t\t\/\/ Read from the RTC.\n\t\t\t\t\/\/ A no-op for now.\n\t\t\t} else {\n\t\t\t\t\/\/ Write to the RTC. Which in this implementation also sets up a future read.\n\t\t\t\tconst auto result = perform(data_);\n\t\t\t\tif(result < 0x100) {\n\t\t\t\t\tdata_ = uint8_t(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ MAGIC! The transaction took 0 seconds.\n\t\t\t\/\/ TODO: no magic.\n\t\t\tcontrol_ = control & 0x7f;\n\n\t\t\t\/\/ Bit 5 is also meant to be 1 or 0 to indicate the final byte.\n\t\t}\n\n\t\tuint8_t get_control() {\n\t\t\treturn control_;\n\t\t}\n\n\t\tvoid set_data(uint8_t data) {\n\t\t\tdata_ = data;\n\t\t}\n\n\t\tuint8_t get_data() {\n\t\t\treturn data_;\n\t\t}\n\n\tprivate:\n\t\tuint8_t data_;\n\t\tuint8_t control_;\n};\n\n}\n}\n\n#endif \/* Apple_RealTimeClock_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ \n\/\/ Primary interface to machine description for the UltraSPARC. Primarily just\n\/\/ initializes machine-dependent parameters in class TargetMachine, and creates\n\/\/ machine-dependent subclasses for classes such as TargetInstrInfo.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Function.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/CodeGen\/InstrScheduling.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"MappingInfo.h\" \n#include \"MachineFunctionInfo.h\"\n#include \"MachineCodeForInstruction.h\"\n#include \"SparcV9Internals.h\"\n#include \"SparcV9TargetMachine.h\"\n#include \"SparcV9BurgISel.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\nstatic const unsigned ImplicitRegUseList[] = { 0 }; \/* not used yet *\/\n\/\/ Build the MachineInstruction Description Array...\nconst TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {\n#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \\\n NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \\\n { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \\\n NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \\\n ImplicitRegUseList, ImplicitRegUseList },\n#include \"SparcV9Instr.def\"\n};\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command line options to control choice of code generation passes.\n\/\/---------------------------------------------------------------------------\n\nnamespace llvm {\n bool EmitMappingInfo = false;\n}\n\nnamespace {\n cl::opt<bool> DisableSched(\"disable-sched\",\n cl::desc(\"Disable local scheduling pass\"));\n\n cl::opt<bool> DisablePeephole(\"disable-peephole\",\n cl::desc(\"Disable peephole optimization pass\"));\n\n cl::opt<bool, true> EmitMappingInfoOpt(\"enable-maps\",\n cl::location(EmitMappingInfo),\n cl::init(false),\n cl::desc(\"Emit LLVM-to-MachineCode mapping info to assembly\"));\n\n cl::opt<bool> DisableStrip(\"disable-strip\",\n cl::desc(\"Do not strip the LLVM bytecode in executable\"));\n\n \n cl::opt<bool> EnableModSched(\"enable-ModSched\", cl::desc(\"Enable modulo scheduling pass instead of local scheduling\"));\n\n \/\/ Register the target.\n RegisterTarget<SparcV9TargetMachine> X(\"sparcv9\", \" SPARC V9\");\n}\n\nunsigned SparcV9TargetMachine::getJITMatchQuality() {\n#if defined(__sparcv9)\n return 10;\n#else\n return 0;\n#endif\n}\n\nunsigned SparcV9TargetMachine::getModuleMatchQuality(const Module &M) {\n if (M.getEndianness() == Module::BigEndian &&\n M.getPointerSize() == Module::Pointer64)\n return 10; \/\/ Direct match\n else if (M.getEndianness() != Module::AnyEndianness ||\n M.getPointerSize() != Module::AnyPointerSize)\n return 0; \/\/ Match for some other target\n\n return getJITMatchQuality()\/2;\n}\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ Code generation\/destruction passes\n\/\/===---------------------------------------------------------------------===\/\/\n\nnamespace {\n class ConstructMachineFunction : public FunctionPass {\n TargetMachine &Target;\n public:\n ConstructMachineFunction(TargetMachine &T) : Target(T) {}\n \n const char *getPassName() const {\n return \"ConstructMachineFunction\";\n }\n \n bool runOnFunction(Function &F) {\n MachineFunction::construct(&F, Target).getInfo<SparcV9FunctionInfo>()->CalculateArgSize();\n return false;\n }\n };\n\n struct DestroyMachineFunction : public FunctionPass {\n const char *getPassName() const { return \"DestroyMachineFunction\"; }\n \n static void freeMachineCode(Instruction &I) {\n MachineCodeForInstruction::destroy(&I);\n }\n \n bool runOnFunction(Function &F) {\n for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)\n for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)\n MachineCodeForInstruction::get(I).dropAllReferences();\n \n for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)\n for_each(FI->begin(), FI->end(), freeMachineCode);\n \n MachineFunction::destruct(&F);\n return false;\n }\n };\n \n FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {\n return new ConstructMachineFunction(Target);\n }\n}\n\nFunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {\n return new DestroyMachineFunction();\n}\n\n\nSparcV9TargetMachine::SparcV9TargetMachine(const Module &M,\n IntrinsicLowering *il)\n : TargetMachine(\"UltraSparcV9-Native\", il, false),\n schedInfo(*this),\n regInfo(*this),\n frameInfo(*this),\n jitInfo(*this) {\n}\n\n\/\/\/ addPassesToEmitAssembly - This method controls the entire code generation\n\/\/\/ process for the ultra sparc.\n\/\/\/\nbool\nSparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)\n{\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ Replace malloc and free instructions with library calls.\n PM.add(createLowerAllocationsPass());\n \n \/\/ FIXME: implement the switch instruction in the instruction selector.\n PM.add(createLowerSwitchPass());\n\n \/\/ FIXME: implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n \n \/\/ decompose multi-dimensional array references into single-dim refs\n PM.add(createDecomposeMultiDimRefsPass());\n\n \/\/ Lower LLVM code to the form expected by the SPARCv9 instruction selector.\n PM.add(createPreSelectionPass(*this));\n PM.add(createLowerSelectPass());\n\n \/\/ Run basic LLVM dataflow optimizations, to clean up after pre-selection.\n PM.add(createReassociatePass());\n PM.add(createLICMPass());\n PM.add(createGCSEPass());\n\n \/\/ If the user's trying to read the generated code, they'll need to see the\n \/\/ transformed input.\n if (PrintMachineCode)\n PM.add(new PrintModulePass());\n\n \/\/ Construct and initialize the MachineFunction object for this fn.\n PM.add(createMachineCodeConstructionPass(*this));\n\n \/\/ Insert empty stackslots in the stack frame of each function\n \/\/ so %fp+offset-8 and %fp+offset-16 are empty slots now!\n PM.add(createStackSlotsPass(*this));\n \n PM.add(createSparcV9BurgInstSelector(*this));\n\n if(PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before modulo scheduling:\\n\"));\n\n \/\/Use ModuloScheduling if enabled, otherwise use local scheduling if not disabled.\n if(EnableModSched)\n PM.add(createModuloSchedulingPass(*this));\n else {\n if (!DisableSched)\n PM.add(createInstructionSchedulingWithSSAPass(*this));\n }\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before reg alloc:\\n\"));\n\n PM.add(getRegisterAllocator(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"After reg alloc:\\n\"));\n\n PM.add(createPrologEpilogInsertionPass());\n\n if (!DisablePeephole)\n PM.add(createPeepholeOptsPass(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Final code:\\n\"));\n\n if (EmitMappingInfo) {\n PM.add(createInternalGlobalMapperPass());\n PM.add(getMappingInfoAsmPrinterPass(Out));\n }\n\n \/\/ Output assembly language to the .s file. Assembly emission is split into\n \/\/ two parts: Function output and Global value output. This is because\n \/\/ function output is pipelined with all of the rest of code generation stuff,\n \/\/ allowing machine code representations for functions to be free'd after the\n \/\/ function has been emitted.\n PM.add(createAsmPrinterPass(Out, *this));\n\n \/\/ Free machine-code IR which is no longer needed:\n PM.add(createSparcV9MachineCodeDestructionPass());\n\n \/\/ Emit bytecode to the assembly file into its special section next\n if (EmitMappingInfo) {\n \/\/ Strip all of the symbols from the bytecode so that it will be smaller...\n if (!DisableStrip)\n PM.add(createSymbolStrippingPass());\n PM.add(createBytecodeAsmPrinterPass(Out));\n }\n \n return false;\n}\n\n\/\/\/ addPassesToJITCompile - This method controls the JIT method of code\n\/\/\/ generation for the UltraSparcV9.\n\/\/\/\nvoid SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ Replace malloc and free instructions with library calls.\n PM.add(createLowerAllocationsPass());\n \n \/\/ FIXME: implement the switch instruction in the instruction selector.\n PM.add(createLowerSwitchPass());\n\n \/\/ FIXME: implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n \n \/\/ decompose multi-dimensional array references into single-dim refs\n PM.add(createDecomposeMultiDimRefsPass());\n\n \/\/ Lower LLVM code to the form expected by the SPARCv9 instruction selector.\n PM.add(createPreSelectionPass(TM));\n PM.add(createLowerSelectPass());\n\n \/\/ Run basic LLVM dataflow optimizations, to clean up after pre-selection.\n PM.add(createReassociatePass());\n \/\/ FIXME: these passes crash the FunctionPassManager when being added...\n \/\/PM.add(createLICMPass());\n \/\/PM.add(createGCSEPass());\n\n \/\/ If the user's trying to read the generated code, they'll need to see the\n \/\/ transformed input.\n if (PrintMachineCode)\n PM.add(new PrintFunctionPass());\n\n \/\/ Construct and initialize the MachineFunction object for this fn.\n PM.add(createMachineCodeConstructionPass(TM));\n\n PM.add(createSparcV9BurgInstSelector(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before reg alloc:\\n\"));\n\n PM.add(getRegisterAllocator(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"After reg alloc:\\n\"));\n\n PM.add(createPrologEpilogInsertionPass());\n\n if (!DisablePeephole)\n PM.add(createPeepholeOptsPass(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Final code:\\n\"));\n}\n\n<commit_msg>Fixed to fit in 80 columns.<commit_after>\/\/===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ \n\/\/ Primary interface to machine description for the UltraSPARC. Primarily just\n\/\/ initializes machine-dependent parameters in class TargetMachine, and creates\n\/\/ machine-dependent subclasses for classes such as TargetInstrInfo.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Function.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/CodeGen\/InstrScheduling.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"MappingInfo.h\" \n#include \"MachineFunctionInfo.h\"\n#include \"MachineCodeForInstruction.h\"\n#include \"SparcV9Internals.h\"\n#include \"SparcV9TargetMachine.h\"\n#include \"SparcV9BurgISel.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\nstatic const unsigned ImplicitRegUseList[] = { 0 }; \/* not used yet *\/\n\/\/ Build the MachineInstruction Description Array...\nconst TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {\n#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \\\n NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \\\n { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \\\n NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \\\n ImplicitRegUseList, ImplicitRegUseList },\n#include \"SparcV9Instr.def\"\n};\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command line options to control choice of code generation passes.\n\/\/---------------------------------------------------------------------------\n\nnamespace llvm {\n bool EmitMappingInfo = false;\n}\n\nnamespace {\n cl::opt<bool> DisableSched(\"disable-sched\",\n cl::desc(\"Disable local scheduling pass\"));\n\n cl::opt<bool> DisablePeephole(\"disable-peephole\",\n cl::desc(\"Disable peephole optimization pass\"));\n\n cl::opt<bool, true> EmitMappingInfoOpt(\"enable-maps\",\n cl::location(EmitMappingInfo),\n cl::init(false),\n cl::desc(\"Emit LLVM-to-MachineCode mapping info to assembly\"));\n\n cl::opt<bool> DisableStrip(\"disable-strip\",\n cl::desc(\"Do not strip the LLVM bytecode in executable\"));\n\n \n cl::opt<bool> EnableModSched(\"enable-ModSched\", \n\t cl::desc(\"Enable modulo scheduling pass instead of local scheduling\"));\n\n \/\/ Register the target.\n RegisterTarget<SparcV9TargetMachine> X(\"sparcv9\", \" SPARC V9\");\n}\n\nunsigned SparcV9TargetMachine::getJITMatchQuality() {\n#if defined(__sparcv9)\n return 10;\n#else\n return 0;\n#endif\n}\n\nunsigned SparcV9TargetMachine::getModuleMatchQuality(const Module &M) {\n if (M.getEndianness() == Module::BigEndian &&\n M.getPointerSize() == Module::Pointer64)\n return 10; \/\/ Direct match\n else if (M.getEndianness() != Module::AnyEndianness ||\n M.getPointerSize() != Module::AnyPointerSize)\n return 0; \/\/ Match for some other target\n\n return getJITMatchQuality()\/2;\n}\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ Code generation\/destruction passes\n\/\/===---------------------------------------------------------------------===\/\/\n\nnamespace {\n class ConstructMachineFunction : public FunctionPass {\n TargetMachine &Target;\n public:\n ConstructMachineFunction(TargetMachine &T) : Target(T) {}\n \n const char *getPassName() const {\n return \"ConstructMachineFunction\";\n }\n \n bool runOnFunction(Function &F) {\n MachineFunction::construct(&F, Target).getInfo<SparcV9FunctionInfo>()->CalculateArgSize();\n return false;\n }\n };\n\n struct DestroyMachineFunction : public FunctionPass {\n const char *getPassName() const { return \"DestroyMachineFunction\"; }\n \n static void freeMachineCode(Instruction &I) {\n MachineCodeForInstruction::destroy(&I);\n }\n \n bool runOnFunction(Function &F) {\n for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)\n for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)\n MachineCodeForInstruction::get(I).dropAllReferences();\n \n for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)\n for_each(FI->begin(), FI->end(), freeMachineCode);\n \n MachineFunction::destruct(&F);\n return false;\n }\n };\n \n FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {\n return new ConstructMachineFunction(Target);\n }\n}\n\nFunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {\n return new DestroyMachineFunction();\n}\n\n\nSparcV9TargetMachine::SparcV9TargetMachine(const Module &M,\n IntrinsicLowering *il)\n : TargetMachine(\"UltraSparcV9-Native\", il, false),\n schedInfo(*this),\n regInfo(*this),\n frameInfo(*this),\n jitInfo(*this) {\n}\n\n\/\/\/ addPassesToEmitAssembly - This method controls the entire code generation\n\/\/\/ process for the ultra sparc.\n\/\/\/\nbool\nSparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)\n{\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ Replace malloc and free instructions with library calls.\n PM.add(createLowerAllocationsPass());\n \n \/\/ FIXME: implement the switch instruction in the instruction selector.\n PM.add(createLowerSwitchPass());\n\n \/\/ FIXME: implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n \n \/\/ decompose multi-dimensional array references into single-dim refs\n PM.add(createDecomposeMultiDimRefsPass());\n\n \/\/ Lower LLVM code to the form expected by the SPARCv9 instruction selector.\n PM.add(createPreSelectionPass(*this));\n PM.add(createLowerSelectPass());\n\n \/\/ Run basic LLVM dataflow optimizations, to clean up after pre-selection.\n PM.add(createReassociatePass());\n PM.add(createLICMPass());\n PM.add(createGCSEPass());\n\n \/\/ If the user's trying to read the generated code, they'll need to see the\n \/\/ transformed input.\n if (PrintMachineCode)\n PM.add(new PrintModulePass());\n\n \/\/ Construct and initialize the MachineFunction object for this fn.\n PM.add(createMachineCodeConstructionPass(*this));\n\n \/\/ Insert empty stackslots in the stack frame of each function\n \/\/ so %fp+offset-8 and %fp+offset-16 are empty slots now!\n PM.add(createStackSlotsPass(*this));\n \n PM.add(createSparcV9BurgInstSelector(*this));\n\n if(PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before modulo scheduling:\\n\"));\n\n \/\/Use ModuloScheduling if enabled, otherwise use local scheduling if not disabled.\n if(EnableModSched)\n PM.add(createModuloSchedulingPass(*this));\n else {\n if (!DisableSched)\n PM.add(createInstructionSchedulingWithSSAPass(*this));\n }\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before reg alloc:\\n\"));\n\n PM.add(getRegisterAllocator(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"After reg alloc:\\n\"));\n\n PM.add(createPrologEpilogInsertionPass());\n\n if (!DisablePeephole)\n PM.add(createPeepholeOptsPass(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Final code:\\n\"));\n\n if (EmitMappingInfo) {\n PM.add(createInternalGlobalMapperPass());\n PM.add(getMappingInfoAsmPrinterPass(Out));\n }\n\n \/\/ Output assembly language to the .s file. Assembly emission is split into\n \/\/ two parts: Function output and Global value output. This is because\n \/\/ function output is pipelined with all of the rest of code generation stuff,\n \/\/ allowing machine code representations for functions to be free'd after the\n \/\/ function has been emitted.\n PM.add(createAsmPrinterPass(Out, *this));\n\n \/\/ Free machine-code IR which is no longer needed:\n PM.add(createSparcV9MachineCodeDestructionPass());\n\n \/\/ Emit bytecode to the assembly file into its special section next\n if (EmitMappingInfo) {\n \/\/ Strip all of the symbols from the bytecode so that it will be smaller...\n if (!DisableStrip)\n PM.add(createSymbolStrippingPass());\n PM.add(createBytecodeAsmPrinterPass(Out));\n }\n \n return false;\n}\n\n\/\/\/ addPassesToJITCompile - This method controls the JIT method of code\n\/\/\/ generation for the UltraSparcV9.\n\/\/\/\nvoid SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ Replace malloc and free instructions with library calls.\n PM.add(createLowerAllocationsPass());\n \n \/\/ FIXME: implement the switch instruction in the instruction selector.\n PM.add(createLowerSwitchPass());\n\n \/\/ FIXME: implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n \n \/\/ decompose multi-dimensional array references into single-dim refs\n PM.add(createDecomposeMultiDimRefsPass());\n\n \/\/ Lower LLVM code to the form expected by the SPARCv9 instruction selector.\n PM.add(createPreSelectionPass(TM));\n PM.add(createLowerSelectPass());\n\n \/\/ Run basic LLVM dataflow optimizations, to clean up after pre-selection.\n PM.add(createReassociatePass());\n \/\/ FIXME: these passes crash the FunctionPassManager when being added...\n \/\/PM.add(createLICMPass());\n \/\/PM.add(createGCSEPass());\n\n \/\/ If the user's trying to read the generated code, they'll need to see the\n \/\/ transformed input.\n if (PrintMachineCode)\n PM.add(new PrintFunctionPass());\n\n \/\/ Construct and initialize the MachineFunction object for this fn.\n PM.add(createMachineCodeConstructionPass(TM));\n\n PM.add(createSparcV9BurgInstSelector(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Before reg alloc:\\n\"));\n\n PM.add(getRegisterAllocator(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"After reg alloc:\\n\"));\n\n PM.add(createPrologEpilogInsertionPass());\n\n if (!DisablePeephole)\n PM.add(createPeepholeOptsPass(TM));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr, \"Final code:\\n\"));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map<CURL*,\n\t cURLManager*> cURLManager::cURLMap;\nchar cURLManager::errorBuffer[CURL_ERROR_SIZE];\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n if (debugLevel >= 2) {\n result = curl_easy_setopt(easyHandle, CURLOPT_VERBOSE, (long)1);\n if (result != CURLE_OK) {\n DEBUG1(\"CURLOPT_VERBOSE error: %d\\n\", result);\n }\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_ERRORBUFFER, errorBuffer);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_ERRORBUFFER error: %d\\n\", result);\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error %d : %s\\n\", result, errorBuffer);\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error %d : %s\\n\", result, errorBuffer);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEDATA error %d : %s\\n\", result, errorBuffer);\n\n cURLMap[easyHandle] = this;\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n cURLMap.erase(easyHandle);\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"cURL Global init Error: %d\\n\", result);\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setURL(const std::string url)\n{\n CURLcode result;\n\n DEBUG4(\"Tried to fetch URL: %s\\n\", url.c_str());\n\n if (url == \"\") {\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n } else {\n usedUrl = url;\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, usedUrl.c_str());\n DEBUG2(\"CURLOPT_URL is : %s\\n\", usedUrl.c_str());\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result > CURLM_OK)\n DEBUG1(\"Error while adding easy handle from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while removing easy handle from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Error while doing multi_perform from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n if (cURLMap.count(easy))\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"File transfer terminated with error from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error %d : %s\\n\", result, errorBuffer);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\nvoid cURLManager::setTimeCondition(timeCondition condition, time_t &t)\n{\n CURLcode result;\n\n switch (condition) {\n case None:\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMECONDITION,\n\t\t\t CURL_TIMECOND_NONE);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMECONDITION error %d : %s\\n\", result, errorBuffer);\n }\n break;\n case ModifiedSince:\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMECONDITION,\n\t\t\t CURL_TIMECOND_IFMODSINCE);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMECONDITION error %d : %s\\n\", result, errorBuffer);\n }\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMEVALUE,\n\t\t\t (long)t);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEVALUE error %d : %s\\n\", result, errorBuffer);\n }\n break;\n default:\n break;\n }\n}\n\n\n\/\/**************************resourceGeter*************************\n\nresourceGeter::resourceGeter() : cURLManager()\n{\n\tdoingStuff = false;\n}\n\nresourceGeter::~resourceGeter()\n{\n\n}\n\nvoid resourceGeter::addResource ( trResourceItem &item )\n{\n\tresources.push_back(item);\n\n\tif (!doingStuff)\n\t\tgetResource();\n}\n\nvoid resourceGeter::flush ( void )\n{\n\tresources.clear();\n\tdoingStuff = false;\n}\n\nvoid resourceGeter::finalization(char *data, unsigned int length, bool good)\n{\n\tif (!resources.size() || !doingStuff)\n\t\treturn;\t\/\/ we are suposed to be done\n\n\t\/\/ this is who we are suposed to be geting\n\ttrResourceItem item = resources[0]; \n\tresources.erase(resources.begin());\n\tif (good)\n\t{\n\t\t\/\/ save the thing\n\t\tFILE *fp = fopen(item.filePath.c_str(),\"wb\");\n\t\tif (fp)\n\t\t{\n\t\t\tfwrite(data,length,1,fp);\n\t\t\tfclose(fp);\n\t\t}\n\n\t\t\/\/ maybe send a message here saying we did it?\n\t}\n\t\n\t\/\/ do the next one if we must\n\tgetResource();\n}\n\nbool resourceGeter::itemExists ( trResourceItem &item )\n{\n\t\/\/ save the thing\n\tFILE *fp = fopen(item.filePath.c_str(),\"rb\");\n\tif (fp)\n\t{\n\t\tfclose(fp);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid resourceGeter::getResource ( void )\n{\n\twhile ( resources.size() || itemExists(resources[0]) )\n\t\tresources.erase(resources.begin());\n\n\tif ( !resources.size() )\n\t\tdoingStuff = false;\n\telse\n\t{\n\t\ttrResourceItem item = resources[0]; \n\n\t\tdoingStuff = true;\n\t\tsetURL(item.URL);\n\t\tperform();\n\t}\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>call the method the man says we should call to start a job<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map<CURL*,\n\t cURLManager*> cURLManager::cURLMap;\nchar cURLManager::errorBuffer[CURL_ERROR_SIZE];\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n if (debugLevel >= 2) {\n result = curl_easy_setopt(easyHandle, CURLOPT_VERBOSE, (long)1);\n if (result != CURLE_OK) {\n DEBUG1(\"CURLOPT_VERBOSE error: %d\\n\", result);\n }\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_ERRORBUFFER, errorBuffer);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_ERRORBUFFER error: %d\\n\", result);\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error %d : %s\\n\", result, errorBuffer);\n }\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error %d : %s\\n\", result, errorBuffer);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEDATA error %d : %s\\n\", result, errorBuffer);\n\n cURLMap[easyHandle] = this;\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n cURLMap.erase(easyHandle);\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"cURL Global init Error: %d\\n\", result);\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setURL(const std::string url)\n{\n CURLcode result;\n\n DEBUG4(\"Tried to fetch URL: %s\\n\", url.c_str());\n\n if (url == \"\") {\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n } else {\n usedUrl = url;\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, usedUrl.c_str());\n DEBUG2(\"CURLOPT_URL is : %s\\n\", usedUrl.c_str());\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error %d : %s\\n\", result, errorBuffer);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result > CURLM_OK)\n DEBUG1(\"Error while adding easy handle from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while removing easy handle from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Error while doing multi_perform from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n if (cURLMap.count(easy))\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"File transfer terminated with error from libcurl %d : %s\\n\",\n\t result, errorBuffer);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error %d : %s\\n\", result, errorBuffer);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\nvoid cURLManager::setTimeCondition(timeCondition condition, time_t &t)\n{\n CURLcode result;\n\n switch (condition) {\n case None:\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMECONDITION,\n\t\t\t CURL_TIMECOND_NONE);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMECONDITION error %d : %s\\n\", result, errorBuffer);\n }\n break;\n case ModifiedSince:\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMECONDITION,\n\t\t\t CURL_TIMECOND_IFMODSINCE);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMECONDITION error %d : %s\\n\", result, errorBuffer);\n }\n result = curl_easy_setopt(easyHandle,\n\t\t\t CURLOPT_TIMEVALUE,\n\t\t\t (long)t);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEVALUE error %d : %s\\n\", result, errorBuffer);\n }\n break;\n default:\n break;\n }\n}\n\n\n\/\/**************************resourceGeter*************************\n\nresourceGeter::resourceGeter() : cURLManager()\n{\n\tdoingStuff = false;\n}\n\nresourceGeter::~resourceGeter()\n{\n\n}\n\nvoid resourceGeter::addResource ( trResourceItem &item )\n{\n\tresources.push_back(item);\n\n\tif (!doingStuff)\n\t\tgetResource();\n}\n\nvoid resourceGeter::flush ( void )\n{\n\tresources.clear();\n\tdoingStuff = false;\n}\n\nvoid resourceGeter::finalization(char *data, unsigned int length, bool good)\n{\n\tif (!resources.size() || !doingStuff)\n\t\treturn;\t\/\/ we are suposed to be done\n\n\t\/\/ this is who we are suposed to be geting\n\ttrResourceItem item = resources[0]; \n\tresources.erase(resources.begin());\n\tif (good)\n\t{\n\t\t\/\/ save the thing\n\t\tFILE *fp = fopen(item.filePath.c_str(),\"wb\");\n\t\tif (fp)\n\t\t{\n\t\t\tfwrite(data,length,1,fp);\n\t\t\tfclose(fp);\n\t\t}\n\n\t\t\/\/ maybe send a message here saying we did it?\n\t}\n\t\n\t\/\/ do the next one if we must\n\tgetResource();\n}\n\nbool resourceGeter::itemExists ( trResourceItem &item )\n{\n\t\/\/ save the thing\n\tFILE *fp = fopen(item.filePath.c_str(),\"rb\");\n\tif (fp)\n\t{\n\t\tfclose(fp);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid resourceGeter::getResource ( void )\n{\n\twhile ( resources.size() || itemExists(resources[0]) )\n\t\tresources.erase(resources.begin());\n\n\tif ( !resources.size() )\n\t\tdoingStuff = false;\n\telse\n\t{\n\t\ttrResourceItem item = resources[0]; \n\n\t\tdoingStuff = true;\n\t\tsetURL(item.URL);\n\t\taddHandle();\n\t}\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/persist\/sql\/PersistModule.cc\n *\n * Copyright (c) 2008 by OpenCog Foundation\n * Copyright (c) 2008, 2009, 2013 Linas Vepstas <linasvepstas@gmail.com>\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atomspace\/AtomSpace.h>\n#include <opencog\/atomspace\/BackingStore.h>\n#include <opencog\/guile\/SchemePrimitive.h>\n#include <opencog\/nlp\/types\/atom_types.h>\n\n#include \"PersistModule.h\"\n#include \"AtomStorage.h\"\n\nusing namespace opencog;\n\nnamespace opencog {\nclass SQLBackingStore : public BackingStore\n{\n\tprivate:\n\t\tAtomStorage *_store;\n\tpublic:\n\t\tSQLBackingStore();\n\t\tvoid set_store(AtomStorage *);\n\n\t\tvirtual NodePtr getNode(Type, const char *) const;\n\t\tvirtual LinkPtr getLink(Type, const HandleSeq&) const;\n\t\tvirtual AtomPtr getAtom(Handle) const;\n\t\tvirtual HandleSeq getIncomingSet(Handle) const;\n\t\tvirtual void storeAtom(Handle);\n\t\tvirtual void loadType(AtomTable&, Type);\n\t\tvirtual void barrier();\n};\n};\n\nSQLBackingStore::SQLBackingStore()\n{\n\t_store = NULL;\n}\n\nvoid SQLBackingStore::set_store(AtomStorage *as)\n{\n\t_store = as;\n}\n\nNodePtr SQLBackingStore::getNode(Type t, const char *name) const\n{\n\treturn _store->getNode(t, name);\n}\n\nLinkPtr SQLBackingStore::getLink(Type t, const std::vector<Handle>& oset) const\n{\n\treturn _store->getLink(t, oset);\n}\n\nAtomPtr SQLBackingStore::getAtom(Handle h) const\n{\n\treturn _store->getAtom(h);\n}\n\nHandleSeq SQLBackingStore::getIncomingSet(Handle h) const\n{\n\treturn _store->getIncomingSet(h);\n}\n\nvoid SQLBackingStore::storeAtom(Handle h)\n{\n\t_store->storeAtom(h);\n}\n\nvoid SQLBackingStore::loadType(AtomTable& at, Type t)\n{\n\t_store->loadType(at, t);\n}\n\nvoid SQLBackingStore::barrier()\n{\n\t_store->flushStoreQueue();\n}\n\nDECLARE_MODULE(PersistModule);\n\nPersistModule::PersistModule(CogServer& cs) : Module(cs), _store(NULL)\n{\n\t_backing = new SQLBackingStore();\n\n\t\/\/ XXX FIXME Huge hack alert.\n\t\/\/ As of 2013, no one uses this thing, except for NLP processing.\n\t\/\/ Since I'm too lazy to find an elegant solution right now, I'm\n\t\/\/ just going to hack this in. Fix this someday.\n\t\/\/\n\t\/\/ Anyway, what the below does is to ignore these certain types,\n\t\/\/ when they are to be fetched from the backing store. This can\n\t\/\/ speed up document processing, since we know that word instances\n\t\/\/ and documents and sentences will not be stored in the database.\n\t\/\/ Thus, we don't even try to fetch these.\n\n#define NLP_HACK 1\n#ifdef NLP_HACK\n\t_backing->_ignored_types.insert(DOCUMENT_NODE);\n\t_backing->_ignored_types.insert(SENTENCE_NODE);\n\t_backing->_ignored_types.insert(PARSE_NODE);\n\t_backing->_ignored_types.insert(PARSE_LINK);\n\t_backing->_ignored_types.insert(WORD_INSTANCE_NODE);\n\t_backing->_ignored_types.insert(WORD_INSTANCE_LINK);\n#endif \/\/ NLP_HACK\n\n\tdo_close_register();\n\tdo_load_register();\n\tdo_open_register();\n\tdo_store_register();\n\n#ifdef HAVE_GUILE\n\t\/\/ XXX These should be declared in some generic persistance module,\n\t\/\/ as they are not specific to the SQL backend only.\n\t\/\/ But I guess this is an OK home for now.\n\tdefine_scheme_primitive(\"fetch-atom\", &PersistModule::fetch_atom, this);\n\tdefine_scheme_primitive(\"fetch-incoming-set\", &PersistModule::fetch_incoming_set, this);\n\tdefine_scheme_primitive(\"store-atom\", &PersistModule::store_atom, this);\n\tdefine_scheme_primitive(\"load-atoms-of-type\", &PersistModule::load_type, this);\n\tdefine_scheme_primitive(\"barrier\", &PersistModule::barrier, this);\n#endif\n}\n\nPersistModule::~PersistModule()\n{\n\tdo_close_unregister();\n\tdo_load_unregister();\n\tdo_open_unregister();\n\tdo_store_unregister();\n\tdelete _backing;\n}\n\nvoid PersistModule::init(void)\n{\n}\n\nstd::string PersistModule::do_close(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-close: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-close: Error: Database not open\\n\";\n\n\t_cogserver.getAtomSpace().getImpl().unregisterBackingStore(_backing);\n\n\t_backing->set_store(NULL);\n\tdelete _store;\n\t_store = NULL;\n\treturn \"Database closed\\n\";\n}\n\nstd::string PersistModule::do_load(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-load: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-load: Error: Database not open\\n\";\n\n\t\/\/ XXX TODO: this should probably be done in a separate thread.\n\t_store->load(const_cast<AtomTable&>(_cogserver.getAtomSpace().getAtomTable()));\n\n\treturn \"Database load completed\\n\";\n}\n\n\nstd::string PersistModule::do_open(Request *dummy, std::list<std::string> args)\n{\n\tif (args.size() != 3)\n\t\treturn \"sql-open: Error: invalid command syntax\\n\"\n\t\t \"Usage: sql-open <dbname> <username> <auth>\\n\";\n\n\tstd::string dbname = args.front(); args.pop_front();\n\tstd::string username = args.front(); args.pop_front();\n\tstd::string auth\t = args.front(); args.pop_front();\n\n\t_store = new AtomStorage(dbname, username, auth);\n\tif (!_store)\n\t\treturn \"sql-open: Error: Unable to open the database\\n\";\n\n\tif (!_store->connected())\n\t{\n\t\tdelete _store;\n\t\t_store = NULL;\n\t\treturn \"sql-open: Error: Unable to connect to the database\\n\";\n\t}\n\n\t\/\/ reserve() is critical here, to reserve UUID range.\n\t_store->reserve();\n\t_backing->set_store(_store);\n\t_cogserver.getAtomSpace().getImpl().registerBackingStore(_backing);\n\n\tstd::string rc = \"Opened \\\"\" + dbname + \"\\\" as user \\\"\" + username + \"\\\"\\n\"; \n\treturn rc;\n}\n\nstd::string PersistModule::do_store(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-store: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-store: Error: Database not open\\n\";\n\n\t\/\/ XXX TODO This should really be started in a new thread ...\n\t_store->store(const_cast<AtomTable&>(_cogserver.getAtomSpace().getAtomTable()));\n\n\treturn \"Database store completed\\n\";\n}\n\n\/\/ =====================================================================\n\/\/ XXX TODO: the methods below really belong in their own module,\n\/\/ independent of this SQL module; they would be applicable for\n\/\/ any backend, not just the SQL backend.\nHandle PersistModule::fetch_atom(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\th = as->getImpl().fetchAtom(h);\n\treturn h;\n}\n\nHandle PersistModule::fetch_incoming_set(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\t\/\/ The \"false\" flag here means that the fetch is NOT recursive.\n\th = as->getImpl().fetchIncomingSet(h, false);\n\treturn h;\n}\n\n\/**\n * Store the single atom to the backing store hanging off the atom-space\n *\/\nHandle PersistModule::store_atom(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().storeAtom(h);\n\treturn h;\n}\n\nvoid PersistModule::load_type(Type t)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().loadType(t);\n}\n\nvoid PersistModule::barrier(void)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().barrier();\n}\n\n<commit_msg>Ignore more link types<commit_after>\/*\n * opencog\/persist\/sql\/PersistModule.cc\n *\n * Copyright (c) 2008 by OpenCog Foundation\n * Copyright (c) 2008, 2009, 2013 Linas Vepstas <linasvepstas@gmail.com>\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atomspace\/AtomSpace.h>\n#include <opencog\/atomspace\/BackingStore.h>\n#include <opencog\/guile\/SchemePrimitive.h>\n#include <opencog\/nlp\/types\/atom_types.h>\n\n#include \"PersistModule.h\"\n#include \"AtomStorage.h\"\n\nusing namespace opencog;\n\nnamespace opencog {\nclass SQLBackingStore : public BackingStore\n{\n\tprivate:\n\t\tAtomStorage *_store;\n\tpublic:\n\t\tSQLBackingStore();\n\t\tvoid set_store(AtomStorage *);\n\n\t\tvirtual NodePtr getNode(Type, const char *) const;\n\t\tvirtual LinkPtr getLink(Type, const HandleSeq&) const;\n\t\tvirtual AtomPtr getAtom(Handle) const;\n\t\tvirtual HandleSeq getIncomingSet(Handle) const;\n\t\tvirtual void storeAtom(Handle);\n\t\tvirtual void loadType(AtomTable&, Type);\n\t\tvirtual void barrier();\n};\n};\n\nSQLBackingStore::SQLBackingStore()\n{\n\t_store = NULL;\n}\n\nvoid SQLBackingStore::set_store(AtomStorage *as)\n{\n\t_store = as;\n}\n\nNodePtr SQLBackingStore::getNode(Type t, const char *name) const\n{\n\treturn _store->getNode(t, name);\n}\n\nLinkPtr SQLBackingStore::getLink(Type t, const std::vector<Handle>& oset) const\n{\n\treturn _store->getLink(t, oset);\n}\n\nAtomPtr SQLBackingStore::getAtom(Handle h) const\n{\n\treturn _store->getAtom(h);\n}\n\nHandleSeq SQLBackingStore::getIncomingSet(Handle h) const\n{\n\treturn _store->getIncomingSet(h);\n}\n\nvoid SQLBackingStore::storeAtom(Handle h)\n{\n\t_store->storeAtom(h);\n}\n\nvoid SQLBackingStore::loadType(AtomTable& at, Type t)\n{\n\t_store->loadType(at, t);\n}\n\nvoid SQLBackingStore::barrier()\n{\n\t_store->flushStoreQueue();\n}\n\nDECLARE_MODULE(PersistModule);\n\nPersistModule::PersistModule(CogServer& cs) : Module(cs), _store(NULL)\n{\n\t_backing = new SQLBackingStore();\n\n\t\/\/ XXX FIXME Huge hack alert.\n\t\/\/ As of 2013, no one uses this thing, except for NLP processing.\n\t\/\/ Since I'm too lazy to find an elegant solution right now, I'm\n\t\/\/ just going to hack this in. Fix this someday.\n\t\/\/\n\t\/\/ Anyway, what the below does is to ignore these certain types,\n\t\/\/ when they are to be fetched from the backing store. This can\n\t\/\/ speed up document processing, since we know that word instances\n\t\/\/ and documents and sentences will not be stored in the database.\n\t\/\/ Thus, we don't even try to fetch these.\n\n#define NLP_HACK 1\n#ifdef NLP_HACK\n\t_backing->_ignored_types.insert(VARIABLE_NODE);\n\t_backing->_ignored_types.insert(VARIABLE_TYPE_NODE);\n\t_backing->_ignored_types.insert(TYPED_VARIABLE_LINK);\n\t_backing->_ignored_types.insert(BIND_LINK);\n\n\t_backing->_ignored_types.insert(DOCUMENT_NODE);\n\t_backing->_ignored_types.insert(SENTENCE_NODE);\n\t_backing->_ignored_types.insert(PARSE_NODE);\n\t_backing->_ignored_types.insert(PARSE_LINK);\n\t_backing->_ignored_types.insert(WORD_INSTANCE_NODE);\n\t_backing->_ignored_types.insert(WORD_INSTANCE_LINK);\n#endif \/\/ NLP_HACK\n\n\tdo_close_register();\n\tdo_load_register();\n\tdo_open_register();\n\tdo_store_register();\n\n#ifdef HAVE_GUILE\n\t\/\/ XXX These should be declared in some generic persistance module,\n\t\/\/ as they are not specific to the SQL backend only.\n\t\/\/ But I guess this is an OK home for now.\n\tdefine_scheme_primitive(\"fetch-atom\", &PersistModule::fetch_atom, this);\n\tdefine_scheme_primitive(\"fetch-incoming-set\", &PersistModule::fetch_incoming_set, this);\n\tdefine_scheme_primitive(\"store-atom\", &PersistModule::store_atom, this);\n\tdefine_scheme_primitive(\"load-atoms-of-type\", &PersistModule::load_type, this);\n\tdefine_scheme_primitive(\"barrier\", &PersistModule::barrier, this);\n#endif\n}\n\nPersistModule::~PersistModule()\n{\n\tdo_close_unregister();\n\tdo_load_unregister();\n\tdo_open_unregister();\n\tdo_store_unregister();\n\tdelete _backing;\n}\n\nvoid PersistModule::init(void)\n{\n}\n\nstd::string PersistModule::do_close(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-close: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-close: Error: Database not open\\n\";\n\n\t_cogserver.getAtomSpace().getImpl().unregisterBackingStore(_backing);\n\n\t_backing->set_store(NULL);\n\tdelete _store;\n\t_store = NULL;\n\treturn \"Database closed\\n\";\n}\n\nstd::string PersistModule::do_load(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-load: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-load: Error: Database not open\\n\";\n\n\t\/\/ XXX TODO: this should probably be done in a separate thread.\n\t_store->load(const_cast<AtomTable&>(_cogserver.getAtomSpace().getAtomTable()));\n\n\treturn \"Database load completed\\n\";\n}\n\n\nstd::string PersistModule::do_open(Request *dummy, std::list<std::string> args)\n{\n\tif (args.size() != 3)\n\t\treturn \"sql-open: Error: invalid command syntax\\n\"\n\t\t \"Usage: sql-open <dbname> <username> <auth>\\n\";\n\n\tstd::string dbname = args.front(); args.pop_front();\n\tstd::string username = args.front(); args.pop_front();\n\tstd::string auth\t = args.front(); args.pop_front();\n\n\t_store = new AtomStorage(dbname, username, auth);\n\tif (!_store)\n\t\treturn \"sql-open: Error: Unable to open the database\\n\";\n\n\tif (!_store->connected())\n\t{\n\t\tdelete _store;\n\t\t_store = NULL;\n\t\treturn \"sql-open: Error: Unable to connect to the database\\n\";\n\t}\n\n\t\/\/ reserve() is critical here, to reserve UUID range.\n\t_store->reserve();\n\t_backing->set_store(_store);\n\t_cogserver.getAtomSpace().getImpl().registerBackingStore(_backing);\n\n\tstd::string rc = \"Opened \\\"\" + dbname + \"\\\" as user \\\"\" + username + \"\\\"\\n\"; \n\treturn rc;\n}\n\nstd::string PersistModule::do_store(Request *dummy, std::list<std::string> args)\n{\n\tif (!args.empty()) \n\t\treturn \"sql-store: Error: Unexpected argument\\n\";\n\n\tif (_store == NULL)\n\t\treturn \"sql-store: Error: Database not open\\n\";\n\n\t\/\/ XXX TODO This should really be started in a new thread ...\n\t_store->store(const_cast<AtomTable&>(_cogserver.getAtomSpace().getAtomTable()));\n\n\treturn \"Database store completed\\n\";\n}\n\n\/\/ =====================================================================\n\/\/ XXX TODO: the methods below really belong in their own module,\n\/\/ independent of this SQL module; they would be applicable for\n\/\/ any backend, not just the SQL backend.\nHandle PersistModule::fetch_atom(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\th = as->getImpl().fetchAtom(h);\n\treturn h;\n}\n\nHandle PersistModule::fetch_incoming_set(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\t\/\/ The \"false\" flag here means that the fetch is NOT recursive.\n\th = as->getImpl().fetchIncomingSet(h, false);\n\treturn h;\n}\n\n\/**\n * Store the single atom to the backing store hanging off the atom-space\n *\/\nHandle PersistModule::store_atom(Handle h)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().storeAtom(h);\n\treturn h;\n}\n\nvoid PersistModule::load_type(Type t)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().loadType(t);\n}\n\nvoid PersistModule::barrier(void)\n{\n\tAtomSpace *as = &_cogserver.getAtomSpace();\n\tas->getImpl().barrier();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DAVRequestEnvironment.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 05:33:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _DAVREQUESTENVIRONMENT_HXX_\n#define _DAVREQUESTENVIRONMENT_HXX_\n\n#ifndef _RTL_REF_HXX_\n#include <rtl\/ref.hxx>\n#endif\n\n#ifndef _DAVAUTHLISTENER_HXX_\n#include \"DAVAuthListener.hxx\"\n#endif\n\nnamespace webdav_ucp\n{\n\nstruct DAVRequestEnvironment\n{\n rtl::OUString m_aRequestURI;\n rtl::Reference< DAVAuthListener > m_xAuthListener;\n\/\/ rtl::Reference< DAVStatusListener > m_xStatusListener;\n\/\/ rtl::Reference< DAVProgressListener > m_xStatusListener;\n\n DAVRequestEnvironment( const rtl::OUString & rRequestURI,\n const rtl::Reference< DAVAuthListener > & xListener )\n : m_aRequestURI( rRequestURI ), m_xAuthListener( xListener ) {}\n\n DAVRequestEnvironment() {}\n};\n\n} \/\/ namespace webdav_ucp\n\n#endif \/\/ _DAVREQUESTENVIRONMENT_HXX_\n<commit_msg>INTEGRATION: CWS updatefeed (1.6.42); FILE MERGED 2006\/12\/04 16:54:47 kso 1.6.42.1: #i72055# - Added support for XWebDAVCommandEnvironment.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DAVRequestEnvironment.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 15:03:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _DAVREQUESTENVIRONMENT_HXX_\n#define _DAVREQUESTENVIRONMENT_HXX_\n\n#include <vector>\n\n#ifndef _RTL_REF_HXX_\n#include <rtl\/ref.hxx>\n#endif\n\n#ifndef _DAVAUTHLISTENER_HXX_\n#include \"DAVAuthListener.hxx\"\n#endif\n\nnamespace webdav_ucp\n{\n typedef std::pair< rtl::OUString, rtl::OUString > DAVRequestHeader;\n typedef std::vector< DAVRequestHeader > DAVRequestHeaders;\n\nstruct DAVRequestEnvironment\n{\n rtl::OUString m_aRequestURI;\n rtl::Reference< DAVAuthListener > m_xAuthListener;\n\/\/ rtl::Reference< DAVStatusListener > m_xStatusListener;\n\/\/ rtl::Reference< DAVProgressListener > m_xStatusListener;\n DAVRequestHeaders m_aRequestHeaders;\n\n DAVRequestEnvironment( const rtl::OUString & rRequestURI,\n const rtl::Reference< DAVAuthListener > & xListener,\n const DAVRequestHeaders & rRequestHeaders )\n : m_aRequestURI( rRequestURI ),\n m_xAuthListener( xListener ),\n m_aRequestHeaders( rRequestHeaders ) {}\n\n DAVRequestEnvironment() {}\n};\n\n} \/\/ namespace webdav_ucp\n\n#endif \/\/ _DAVREQUESTENVIRONMENT_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file painter_stroke_params.hpp\n * \\brief file painter_stroke_params.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/painter\/painter_shader_data.hpp>\n#include <fastuidraw\/painter\/painter_stroke_shader.hpp>\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * \\brief\n * Class to specify stroking parameters, data is packed\n * as according to PainterStrokeParams::stroke_data_offset_t.\n *\/\n class PainterStrokeParams:public PainterItemShaderData\n {\n public:\n \/*!\n * \\brief\n * Enumeration to specify the units of the stroking radius\n *\/\n enum stroking_units_t\n {\n \/*!\n * Indicates that the stroking units is in local\n * coordinates of the Path being stroking\n *\/\n path_stroking_units,\n\n \/*!\n * Indicates that the stroking units are in pixels\n *\/\n pixel_stroking_units,\n };\n\n \/*!\n * \\brief\n * Enumeration that provides offsets for the stroking\n * parameters.\n *\/\n enum stroke_data_offset_t\n {\n \/*!\n * Offset to stroke radius (packed as float).\n * The absolute value gives the stroking radius,\n * if teh value is negative then the stroking radius\n * is in units of pixels, if positive it is in local\n * path coordinates.\n *\/\n stroke_radius_offset,\n stroke_miter_limit_offset, \/*!< offset to stroke miter limit (packed as float) *\/\n\n stroke_data_size \/*!< size of data for stroking*\/\n };\n\n \/*!\n * Ctor.\n *\/\n PainterStrokeParams(void);\n\n \/*!\n * The miter limit for miter joins\n *\/\n float\n miter_limit(void) const;\n\n \/*!\n * Set the value of miter_limit(void) const\n *\/\n PainterStrokeParams&\n miter_limit(float f);\n\n \/*!\n * The stroking width, always non-negative\n *\/\n float\n width(void) const;\n\n \/*!\n * Set the value of width(void) const,\n * values are clamped to be non-negative.\n *\/\n PainterStrokeParams&\n width(float f);\n\n \/*!\n * The stroking radius, equivalent to\n * \\code\n * width() * 0.5\n * \\endcode\n *\/\n float\n radius(void) const;\n\n \/*!\n * Set the value of radius(void) const,\n * equivalent to\n * \\code\n * width(2.0 * f)\n * \\endcode\n *\/\n PainterStrokeParams&\n radius(float f);\n\n \/*!\n * Returns the units of the stroking, default value is\n * \\ref path_stroking_units\n *\/\n enum stroking_units_t\n stroking_units(void) const;\n\n \/*!\n * Set the value of stroking_units(void) const,\n * values are clamped to be non-negative.\n *\/\n PainterStrokeParams&\n stroking_units(enum stroking_units_t);\n\n \/*!\n * Returns a StrokingDataSelectorBase suitable for PainterStrokeParams.\n * \\param pixel_arc_stroking_possible if true, will inform that arc-stroking\n * width in \\ref pixel_stroking_units is\n * possible.\n *\/\n static\n reference_counted_ptr<const StrokingDataSelectorBase>\n stroking_data_selector(bool pixel_arc_stroking_possible);\n };\n\n\/*! @} *\/\n\n} \/\/namespace fastuidraw\n<commit_msg>fastuidraw\/painter\/painter_stroke_params: better doxy tags<commit_after>\/*!\n * \\file painter_stroke_params.hpp\n * \\brief file painter_stroke_params.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/painter\/painter_shader_data.hpp>\n#include <fastuidraw\/painter\/painter_stroke_shader.hpp>\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * \\brief\n * Class to specify stroking parameters, data is packed\n * as according to PainterStrokeParams::stroke_data_offset_t.\n *\/\n class PainterStrokeParams:public PainterItemShaderData\n {\n public:\n \/*!\n * \\brief\n * Enumeration to specify the units of the stroking radius\n *\/\n enum stroking_units_t\n {\n \/*!\n * Indicates that the stroking units is in local\n * coordinates of the Path being stroking\n *\/\n path_stroking_units,\n\n \/*!\n * Indicates that the stroking units are in pixels\n *\/\n pixel_stroking_units,\n };\n\n \/*!\n * \\brief\n * Enumeration that provides offsets for the stroking\n * parameters.\n *\/\n enum stroke_data_offset_t\n {\n \/*!\n * Offset to stroke radius (packed as float).\n * The absolute value gives the stroking radius,\n * if teh value is negative then the stroking radius\n * is in units of pixels, if positive it is in local\n * path coordinates.\n *\/\n stroke_radius_offset,\n stroke_miter_limit_offset, \/*!< offset to stroke miter limit (packed as float) *\/\n\n stroke_data_size \/*!< size of data for stroking*\/\n };\n\n \/*!\n * Ctor.\n *\/\n PainterStrokeParams(void);\n\n \/*!\n * The miter limit for miter joins.\n * Default value is 15.0.\n *\/\n float\n miter_limit(void) const;\n\n \/*!\n * Set the value of miter_limit(void) const\n *\/\n PainterStrokeParams&\n miter_limit(float f);\n\n \/*!\n * The stroking width, always non-negative.\n * Default value is 2.0.\n *\/\n float\n width(void) const;\n\n \/*!\n * Set the value of width(void) const,\n * values are clamped to be non-negative.\n *\/\n PainterStrokeParams&\n width(float f);\n\n \/*!\n * The stroking radius, equivalent to\n * \\code\n * width() * 0.5\n * \\endcode\n * Default value is 1.0.\n *\/\n float\n radius(void) const;\n\n \/*!\n * Set the value of radius(void) const,\n * equivalent to\n * \\code\n * width(2.0 * f)\n * \\endcode\n *\/\n PainterStrokeParams&\n radius(float f);\n\n \/*!\n * Returns the units of the stroking, default value is\n * \\ref path_stroking_units\n *\/\n enum stroking_units_t\n stroking_units(void) const;\n\n \/*!\n * Set the value of stroking_units(void) const\n *\/\n PainterStrokeParams&\n stroking_units(enum stroking_units_t);\n\n \/*!\n * Returns a StrokingDataSelectorBase suitable for PainterStrokeParams.\n * \\param pixel_arc_stroking_possible if true, will inform that arc-stroking\n * width in \\ref pixel_stroking_units is\n * possible.\n *\/\n static\n reference_counted_ptr<const StrokingDataSelectorBase>\n stroking_data_selector(bool pixel_arc_stroking_possible);\n };\n\n\/*! @} *\/\n\n} \/\/namespace fastuidraw\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 syzkaller project authors. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\n\/\/ +build\n\n#define SYZ_EXECUTOR\n#include \"common_bsd.h\"\n\n#include \"executor_posix.h\"\n\n#include \"executor.h\"\n\n\/\/ This file is used by both freebsd and netbsd (as a link to executor_bsd.cc).\n#if defined(__FreeBSD__)\n#include \"syscalls_freebsd.h\"\n#elif defined(__NetBSD__)\n#include \"syscalls_netbsd.h\"\n#else\n\/\/ This is just so that \"make executor TARGETOS=freebsd\" works on linux.\n#include \"syscalls_freebsd.h\"\n#define __syscall syscall\n#endif\n\n#include <signal.h>\n#include <sys\/mman.h>\n#include <sys\/resource.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n\nconst int kInFd = 3;\nconst int kOutFd = 4;\n\nuint32* output_data;\nuint32* output_pos;\n\nint main(int argc, char** argv)\n{\n\tif (argc == 2 && strcmp(argv[1], \"version\") == 0) {\n\t\tputs(GOOS \" \" GOARCH \" \" SYZ_REVISION \" \" GIT_REVISION);\n\t\treturn 0;\n\t}\n\n\tif (mmap(&input_data[0], kMaxInput, PROT_READ, MAP_PRIVATE | MAP_FIXED, kInFd, 0) != &input_data[0])\n\t\tfail(\"mmap of input file failed\");\n\t\/\/ The output region is the only thing in executor process for which consistency matters.\n\t\/\/ If it is corrupted ipc package will fail to parse its contents and panic.\n\t\/\/ But fuzzer constantly invents new ways of how to currupt the region,\n\t\/\/ so we map the region at a (hopefully) hard to guess address surrounded by unmapped pages.\n\tvoid* const kOutputDataAddr = (void*)0x1ddbc20000;\n\toutput_data = (uint32*)mmap(kOutputDataAddr, kMaxOutput, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, kOutFd, 0);\n\tif (output_data != kOutputDataAddr)\n\t\tfail(\"mmap of output file failed\");\n\tif (mmap((void*)SYZ_DATA_OFFSET, SYZ_NUM_PAGES * SYZ_PAGE_SIZE, PROT_READ | PROT_WRITE,\n\t\t MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) != (void*)SYZ_DATA_OFFSET)\n\t\tfail(\"mmap of data segment failed\");\n\t\/\/ Prevent random programs to mess with these fds.\n\t\/\/ Due to races in collider mode, a program can e.g. ftruncate one of these fds,\n\t\/\/ which will cause fuzzer to crash.\n\t\/\/ That's also the reason why we close kInPipeFd\/kOutPipeFd below.\n\tclose(kInFd);\n\tclose(kOutFd);\n\n\t\/\/ Some minimal sandboxing.\n\tstruct rlimit rlim;\n#ifndef __NetBSD__\n\t\/\/ This causes frequent random aborts on netbsd. Reason unknown.\n\trlim.rlim_cur = rlim.rlim_max = 128 << 20;\n\tsetrlimit(RLIMIT_AS, &rlim);\n#endif\n\trlim.rlim_cur = rlim.rlim_max = 8 << 20;\n\tsetrlimit(RLIMIT_MEMLOCK, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 1 << 20;\n\tsetrlimit(RLIMIT_FSIZE, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 1 << 20;\n\tsetrlimit(RLIMIT_STACK, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 0;\n\tsetrlimit(RLIMIT_CORE, &rlim);\n\n\tinstall_segv_handler();\n\tsetup_control_pipes();\n\treceive_handshake();\n\treply_handshake();\n\tcover_open();\n\n\tfor (;;) {\n\t\treceive_execute(false);\n\t\tchar cwdbuf[128] = \"\/syz-tmpXXXXXX\";\n\t\tif (!mkdtemp(cwdbuf))\n\t\t\tfail(\"mkdtemp failed\");\n\t\tint pid = fork();\n\t\tif (pid < 0)\n\t\t\tfail(\"fork failed\");\n\t\tif (pid == 0) {\n\t\t\tclose(kInPipeFd);\n\t\t\tclose(kOutPipeFd);\n\t\t\tif (chdir(cwdbuf))\n\t\t\t\tfail(\"chdir failed\");\n\t\t\toutput_pos = output_data;\n\t\t\texecute_one();\n\t\t\tdoexit(0);\n\t\t}\n\t\tint status = 0;\n\t\tuint64 start = current_time_ms();\n\t\tuint64 last_executed = start;\n\t\tuint32 executed_calls = __atomic_load_n(output_data, __ATOMIC_RELAXED);\n\t\tfor (;;) {\n\t\t\tint res = waitpid(pid, &status, WNOHANG);\n\t\t\tif (res == pid)\n\t\t\t\tbreak;\n\t\t\tsleep_ms(1);\n\t\t\tuint64 now = current_time_ms();\n\t\t\tuint32 now_executed = __atomic_load_n(output_data, __ATOMIC_RELAXED);\n\t\t\tif (executed_calls != now_executed) {\n\t\t\t\texecuted_calls = now_executed;\n\t\t\t\tlast_executed = now;\n\t\t\t}\n\t\t\tif ((now - start < 3 * 1000) && (now - last_executed < 500))\n\t\t\t\tcontinue;\n\t\t\tkill(pid, SIGKILL);\n\t\t\twhile (waitpid(pid, &status, 0) != pid) {\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tstatus = WEXITSTATUS(status);\n\t\tif (status == kFailStatus)\n\t\t\tfail(\"child failed\");\n\t\tif (status == kErrorStatus)\n\t\t\terror(\"child errored\");\n\t\tremove_dir(cwdbuf);\n\t\treply_execute(0);\n\t}\n\treturn 0;\n}\n\nlong execute_syscall(call_t* c, long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8)\n{\n\tif (c->call)\n\t\treturn c->call(a0, a1, a2, a3, a4, a5, a6, a7, a8);\n\treturn __syscall(c->sys_nr, a0, a1, a2, a3, a4, a5, a6, a7, a8);\n}\n\nvoid cover_open()\n{\n\tif (!flag_cover)\n\t\treturn;\n\tfor (int i = 0; i < kMaxThreads; i++) {\n\t\tthread_t* th = &threads[i];\n\t\tth->cover_data = &th->cover_buffer[0];\n\t}\n}\n\nvoid cover_enable(thread_t* th)\n{\n}\n\nvoid cover_reset(thread_t* th)\n{\n}\n\nuint64 read_cover_size(thread_t* th)\n{\n\tif (!flag_cover)\n\t\treturn 0;\n\t\/\/ Fallback coverage since we have no real coverage available.\n\t\/\/ We use syscall number or-ed with returned errno value as signal.\n\t\/\/ At least this gives us all combinations of syscall+errno.\n\tth->cover_data[0] = (th->call_num << 16) | ((th->res == -1 ? th->reserrno : 0) & 0x3ff);\n\treturn 1;\n}\n\nuint32* write_output(uint32 v)\n{\n\tif (collide)\n\t\treturn 0;\n\tif (output_pos < output_data || (char*)output_pos >= (char*)output_data + kMaxOutput)\n\t\tfail(\"output overflow\");\n\t*output_pos = v;\n\treturn output_pos++;\n}\n\nvoid write_completed(uint32 completed)\n{\n\t__atomic_store_n(output_data, completed, __ATOMIC_RELEASE);\n}\n\nbool kcov_comparison_t::ignore() const\n{\n\treturn false;\n}\n<commit_msg>executor: update to support FreeBSD kcov<commit_after>\/\/ Copyright 2017 syzkaller project authors. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\n\/\/ +build\n\n#define SYZ_EXECUTOR\n#include \"common_bsd.h\"\n\n#include \"executor_posix.h\"\n\n#include \"executor.h\"\n\n\/\/ This file is used by both freebsd and netbsd (as a link to executor_bsd.cc).\n#if defined(__FreeBSD__)\n#include \"syscalls_freebsd.h\"\n#elif defined(__NetBSD__)\n#include \"syscalls_netbsd.h\"\n#else\n\/\/ This is just so that \"make executor TARGETOS=freebsd\" works on linux.\n#include \"syscalls_freebsd.h\"\n#define __syscall syscall\n#endif\n\n#include <fcntl.h>\n#include <signal.h>\n#include <sys\/ioctl.h>\n#include <sys\/mman.h>\n#include <sys\/resource.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n\n#if defined(__FreeBSD__)\n#define KIOENABLE _IOW('c', 2, int) \/\/ Enable coverage recording\n#define KIODISABLE _IO('c', 3) \/\/ Disable coverage recording\n#define KIOSETBUFSIZE _IOW('c', 4, unsigned int) \/\/ Set the buffer size\n\n#define KCOV_MODE_NONE -1\n#define KCOV_MODE_TRACE_PC 0\n#define KCOV_MODE_TRACE_CMP 1\n#endif\n\nconst int kInFd = 3;\nconst int kOutFd = 4;\n\nuint32* output_data;\nuint32* output_pos;\n\nint main(int argc, char** argv)\n{\n\tif (argc == 2 && strcmp(argv[1], \"version\") == 0) {\n\t\tputs(GOOS \" \" GOARCH \" \" SYZ_REVISION \" \" GIT_REVISION);\n\t\treturn 0;\n\t}\n\n\tif (mmap(&input_data[0], kMaxInput, PROT_READ, MAP_PRIVATE | MAP_FIXED, kInFd, 0) != &input_data[0])\n\t\tfail(\"mmap of input file failed\");\n\t\/\/ The output region is the only thing in executor process for which consistency matters.\n\t\/\/ If it is corrupted ipc package will fail to parse its contents and panic.\n\t\/\/ But fuzzer constantly invents new ways of how to currupt the region,\n\t\/\/ so we map the region at a (hopefully) hard to guess address surrounded by unmapped pages.\n\tvoid* const kOutputDataAddr = (void*)0x1ddbc20000;\n\toutput_data = (uint32*)mmap(kOutputDataAddr, kMaxOutput, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, kOutFd, 0);\n\tif (output_data != kOutputDataAddr)\n\t\tfail(\"mmap of output file failed\");\n\tif (mmap((void*)SYZ_DATA_OFFSET, SYZ_NUM_PAGES * SYZ_PAGE_SIZE, PROT_READ | PROT_WRITE,\n\t\t MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) != (void*)SYZ_DATA_OFFSET)\n\t\tfail(\"mmap of data segment failed\");\n\t\/\/ Prevent random programs to mess with these fds.\n\t\/\/ Due to races in collider mode, a program can e.g. ftruncate one of these fds,\n\t\/\/ which will cause fuzzer to crash.\n\t\/\/ That's also the reason why we close kInPipeFd\/kOutPipeFd below.\n\tclose(kInFd);\n\tclose(kOutFd);\n\n\t\/\/ Some minimal sandboxing.\n\tstruct rlimit rlim;\n#ifndef __NetBSD__\n\t\/\/ This causes frequent random aborts on netbsd. Reason unknown.\n\trlim.rlim_cur = rlim.rlim_max = 128 << 20;\n\tsetrlimit(RLIMIT_AS, &rlim);\n#endif\n\trlim.rlim_cur = rlim.rlim_max = 8 << 20;\n\tsetrlimit(RLIMIT_MEMLOCK, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 1 << 20;\n\tsetrlimit(RLIMIT_FSIZE, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 1 << 20;\n\tsetrlimit(RLIMIT_STACK, &rlim);\n\trlim.rlim_cur = rlim.rlim_max = 0;\n\tsetrlimit(RLIMIT_CORE, &rlim);\n\n\tinstall_segv_handler();\n\tsetup_control_pipes();\n\treceive_handshake();\n\treply_handshake();\n\tcover_open();\n\n\tfor (;;) {\n\t\treceive_execute(false);\n\t\tchar cwdbuf[128] = \"\/syz-tmpXXXXXX\";\n\t\tif (!mkdtemp(cwdbuf))\n\t\t\tfail(\"mkdtemp failed\");\n\t\tint pid = fork();\n\t\tif (pid < 0)\n\t\t\tfail(\"fork failed\");\n\t\tif (pid == 0) {\n\t\t\tclose(kInPipeFd);\n\t\t\tclose(kOutPipeFd);\n\t\t\tif (chdir(cwdbuf))\n\t\t\t\tfail(\"chdir failed\");\n\t\t\toutput_pos = output_data;\n\t\t\texecute_one();\n\t\t\tdoexit(0);\n\t\t}\n\t\tint status = 0;\n\t\tuint64 start = current_time_ms();\n\t\tuint64 last_executed = start;\n\t\tuint32 executed_calls = __atomic_load_n(output_data, __ATOMIC_RELAXED);\n\t\tfor (;;) {\n\t\t\tint res = waitpid(pid, &status, WNOHANG);\n\t\t\tif (res == pid)\n\t\t\t\tbreak;\n\t\t\tsleep_ms(1);\n\t\t\tuint64 now = current_time_ms();\n\t\t\tuint32 now_executed = __atomic_load_n(output_data, __ATOMIC_RELAXED);\n\t\t\tif (executed_calls != now_executed) {\n\t\t\t\texecuted_calls = now_executed;\n\t\t\t\tlast_executed = now;\n\t\t\t}\n\t\t\tif ((now - start < 3 * 1000) && (now - last_executed < 500))\n\t\t\t\tcontinue;\n\t\t\tkill(pid, SIGKILL);\n\t\t\twhile (waitpid(pid, &status, 0) != pid) {\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tstatus = WEXITSTATUS(status);\n\t\tif (status == kFailStatus)\n\t\t\tfail(\"child failed\");\n\t\tif (status == kErrorStatus)\n\t\t\terror(\"child errored\");\n\t\tremove_dir(cwdbuf);\n\t\treply_execute(0);\n\t}\n\treturn 0;\n}\n\nlong execute_syscall(call_t* c, long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8)\n{\n\tif (c->call)\n\t\treturn c->call(a0, a1, a2, a3, a4, a5, a6, a7, a8);\n\treturn __syscall(c->sys_nr, a0, a1, a2, a3, a4, a5, a6, a7, a8);\n}\n\nvoid cover_open()\n{\n\tif (!flag_cover)\n\t\treturn;\n\tfor (int i = 0; i < kMaxThreads; i++) {\n\t\tthread_t* th = &threads[i];\n#if defined(__FreeBSD__)\n\t\tth->cover_fd = open(\"\/dev\/kcov\", O_RDWR);\n\t\tif (th->cover_fd == -1)\n\t\t\tfail(\"open of \/dev\/kcov failed\");\n\t\tif (ioctl(th->cover_fd, KIOSETBUFSIZE, &kCoverSize))\n\t\t\tfail(\"ioctl init trace write failed\");\n\t\tsize_t mmap_alloc_size = kCoverSize * sizeof(th->cover_data[0]);\n\t\tuint64* mmap_ptr = (uint64*)mmap(NULL, mmap_alloc_size,\n\t\t\t\t\t\t PROT_READ | PROT_WRITE,\n\t\t\t\t\t\t MAP_SHARED, th->cover_fd, 0);\n\t\tif (mmap_ptr == NULL)\n\t\t\tfail(\"cover mmap failed\");\n\t\tth->cover_size_ptr = mmap_ptr;\n\t\tth->cover_data = &mmap_ptr[1];\n#else\n\t\tth->cover_data = &th->cover_buffer[0];\n#endif\n\t}\n}\n\nvoid cover_enable(thread_t* th)\n{\n#if defined(__FreeBSD__)\n\tif (!flag_cover)\n\t\treturn;\n\tdebug(\"#%d: enabling \/dev\/kcov\\n\", th->id);\n\tint kcov_mode = flag_collect_comps ? KCOV_MODE_TRACE_CMP : KCOV_MODE_TRACE_PC;\n\tif (ioctl(th->cover_fd, KIOENABLE, &kcov_mode))\n\t\texitf(\"cover enable write trace failed, mode=%d\", kcov_mode);\n\tdebug(\"#%d: enabled \/dev\/kcov\\n\", th->id);\n#endif\n}\n\nvoid cover_reset(thread_t* th)\n{\n#if defined(__FreeBSD__)\n\tif (!flag_cover)\n\t\treturn;\n\n\t*th->cover_size_ptr = 0;\n#endif\n}\n\nuint64 read_cover_size(thread_t* th)\n{\n\tif (!flag_cover)\n\t\treturn 0;\n#if defined(__FreeBSD__)\n\tuint64 size = *th->cover_size_ptr;\n\tdebug(\"#%d: read cover size = %llu\\n\", th->id, size);\n\tif (size > kCoverSize)\n\t\tfail(\"#%d: too much cover %llu\", th->id, size);\n\treturn size;\n#else\n\t\/\/ Fallback coverage since we have no real coverage available.\n\t\/\/ We use syscall number or-ed with returned errno value as signal.\n\t\/\/ At least this gives us all combinations of syscall+errno.\n\tth->cover_data[0] = (th->call_num << 16) | ((th->res == -1 ? th->reserrno : 0) & 0x3ff);\n\treturn 1;\n#endif\n}\n\nuint32* write_output(uint32 v)\n{\n\tif (collide)\n\t\treturn 0;\n\tif (output_pos < output_data || (char*)output_pos >= (char*)output_data + kMaxOutput)\n\t\tfail(\"output overflow\");\n\t*output_pos = v;\n\treturn output_pos++;\n}\n\nvoid write_completed(uint32 completed)\n{\n\t__atomic_store_n(output_data, completed, __ATOMIC_RELEASE);\n}\n\nbool kcov_comparison_t::ignore() const\n{\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n\n#include \"RawBuffer.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/Rect.hpp\"\n#include \"depthai-shared\/datatype\/RawImgDetections.hpp\"\n\nnamespace dai {\n\n\/**\n * Tracklet structure\n *\n * Contains tracklets from object tracker output.\n *\/\nstruct Tracklet {\n enum class TrackingStatus : std::int32_t {\n NEW, \/**< The object is newly added. *\/\n TRACKED, \/**< The object is being tracked. *\/\n LOST \/**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short\n term and zero term tracking). *\/\n };\n \/**\n * Tracked region of interest.\n *\/\n Rect roi;\n \/**\n * Tracklet's ID.\n *\/\n std::int32_t id;\n \/**\n * Tracklet's label ID.\n *\/\n std::int32_t label;\n \/**\n * Number of frames it is being tracked for.\n *\/\n std::int32_t age;\n \/**\n * Status of tracklet.\n *\/\n TrackingStatus status;\n\n \/**\n * Image detection that is tracked.\n *\/\n ImgDetection srcImgDetection;\n \/**\n * Spatial coordinates of tracklet.\n *\/\n Point3f spatialCoordinates;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(Tracklet, roi, id, label, age, status, srcImgDetection, spatialCoordinates);\n};\n\nstruct RawTracklets : public RawBuffer {\n std::vector<Tracklet> tracklets;\n\n void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {\n nlohmann::json j = *this;\n metadata = nlohmann::json::to_msgpack(j);\n datatype = DatatypeEnum::Tracklets;\n };\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawTracklets, tracklets);\n};\n\n} \/\/ namespace dai\n<commit_msg>Add new object tracker state: Removed<commit_after>#pragma once\n\n#include <iostream>\n\n#include \"RawBuffer.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/Rect.hpp\"\n#include \"depthai-shared\/datatype\/RawImgDetections.hpp\"\n\nnamespace dai {\n\n\/**\n * Tracklet structure\n *\n * Contains tracklets from object tracker output.\n *\/\nstruct Tracklet {\n enum class TrackingStatus : std::int32_t {\n NEW, \/**< The object is newly added. *\/\n TRACKED, \/**< The object is being tracked. *\/\n LOST, \/**< The object gets lost now. The object can be tracked again automatically(long term tracking) or by specifying detected object manually(short\n term and zero term tracking). *\/\n REMOVED \/**< The object is removed. *\/\n };\n \/**\n * Tracked region of interest.\n *\/\n Rect roi;\n \/**\n * Tracklet's ID.\n *\/\n std::int32_t id;\n \/**\n * Tracklet's label ID.\n *\/\n std::int32_t label;\n \/**\n * Number of frames it is being tracked for.\n *\/\n std::int32_t age;\n \/**\n * Status of tracklet.\n *\/\n TrackingStatus status;\n\n \/**\n * Image detection that is tracked.\n *\/\n ImgDetection srcImgDetection;\n \/**\n * Spatial coordinates of tracklet.\n *\/\n Point3f spatialCoordinates;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(Tracklet, roi, id, label, age, status, srcImgDetection, spatialCoordinates);\n};\n\nstruct RawTracklets : public RawBuffer {\n std::vector<Tracklet> tracklets;\n\n void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {\n nlohmann::json j = *this;\n metadata = nlohmann::json::to_msgpack(j);\n datatype = DatatypeEnum::Tracklets;\n };\n\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawTracklets, tracklets);\n};\n\n} \/\/ namespace dai\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Main file for a unified video-based and inertial tracking system.\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"ImageSources\/ImageSource.h\"\n#include \"ImageSources\/ImageSourceFactories.h\"\n\n#include \"MakeHDKTrackingSystem.h\"\n#include \"TrackingSystem.h\"\n#include \"ThreadsafeBodyReporting.h\"\n\n#include \"HDKLedIdentifierFactory.h\"\n#include \"CameraParameters.h\"\n#include \"HDKData.h\"\n#include <osvr\/AnalysisPluginKit\/AnalysisPluginKitC.h>\n#include <osvr\/PluginKit\/PluginKit.h>\n#include <osvr\/PluginKit\/TrackerInterfaceC.h>\n#include <osvr\/PluginKit\/AnalogInterfaceC.h>\n\n#include \"ConfigurationParser.h\"\n\n\/\/ Generated JSON header file\n#include \"org_osvr_unifiedvideoinertial_json.h\"\n\n\/\/ Library\/third-party includes\n#include <opencv2\/core\/core.hpp> \/\/ for basic OpenCV types\n#include <opencv2\/core\/operations.hpp>\n#include <opencv2\/highgui\/highgui.hpp> \/\/ for image capture\n#include <opencv2\/imgproc\/imgproc.hpp> \/\/ for image scaling\n#include <json\/value.h>\n#include <json\/reader.h>\n\n#include <boost\/noncopyable.hpp>\n\n#include <util\/Stride.h>\n\n\/\/ Standard includes\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <memory>\n#include <thread>\n#include <mutex>\n#include <stdexcept>\n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\nstatic const auto DRIVER_NAME = \"UnifiedTrackingSystem\";\n\nstatic const auto DEBUGGABLE_BEACONS = 34;\nstatic const auto DATAPOINTS_PER_BEACON = 5;\nusing TrackingSystemPtr = std::unique_ptr<osvr::vbtracker::TrackingSystem>;\nusing BodyReportingVector = std::vector<osvr::vbtracker::BodyReportingPtr>;\nclass TrackerThread : boost::noncopyable {\n public:\n TrackerThread(osvr::vbtracker::TrackingSystem &trackingSystem,\n osvr::vbtracker::ImageSource &imageSource,\n BodyReportingVector &reportingVec,\n osvr::vbtracker::CameraParameters const &camParams)\n : m_trackingSystem(trackingSystem), m_cam(imageSource),\n m_reportingVec(reportingVec), m_camParams(camParams) {\n msg() << \"Tracker thread object created.\" << std::endl;\n }\n\n void operator()() {\n msg() << \"Tracker thread object invoked.\" << std::endl;\n bool keepGoing = true;\n while (keepGoing) {\n doFrame();\n\n {\n \/\/\/ Copy the run flag.\n std::lock_guard<std::mutex> lock(m_runMutex);\n keepGoing = m_run;\n }\n if (!keepGoing) {\n msg() << \"Tracker thread object: Just checked our run flag and noticed it turned false...\" << std::endl;\n }\n }\n msg() << \"Tracker thread object: functor exiting.\" << std::endl;\n }\n\n \/\/\/ Call from the main thread!\n void triggerStop() {\n msg() << \"Tracker thread object: triggerStop() called\" << std::endl;\n std::lock_guard<std::mutex> lock(m_runMutex);\n m_run = false;\n }\n\n private:\n std::ostream &msg() const { return std::cout << \"[UnifiedTracker] \"; }\n std::ostream &warn() const { return msg() << \"Warning: \"; }\n void doFrame() {\n \/\/ Check camera status.\n if (!m_cam.ok()) {\n \/\/ Hmm, camera seems bad. Might regain it? Skip for now...\n warn() << \"Camera is reporting it is not OK.\" << std::endl;\n return;\n }\n \/\/ Trigger a grab.\n if (!m_cam.grab()) {\n \/\/ Again failing without quitting, in hopes we get better luck next\n \/\/ time...\n warn() << \"Camera grab failed.\" << std::endl;\n return;\n }\n \/\/ When we triggered the grab is our current best guess of the time for\n \/\/ the image\n \/\/\/ @todo backdate to account for image transfer image, exposure time,\n \/\/\/ etc.\n auto tv = osvr::util::time::getNow();\n\n \/\/ Pull the image into an OpenCV matrix named m_frame.\n m_cam.retrieve(m_frame, m_frameGray);\n if (!m_frame.data || !m_frameGray.data) {\n warn()\n << \"Camera retrieve appeared to fail: frames had null pointers!\"\n << std::endl;\n return;\n }\n\n \/\/ Submit to the tracking system.\n auto bodyIds = m_trackingSystem.processFrame(tv, m_frame, m_frameGray,\n m_camParams);\n\n for (auto const &bodyId : bodyIds) {\n \/\/\/ @todo stick stuff in m_reportingVec here.\n }\n }\n osvr::vbtracker::TrackingSystem &m_trackingSystem;\n osvr::vbtracker::ImageSource &m_cam;\n BodyReportingVector &m_reportingVec;\n osvr::vbtracker::CameraParameters m_camParams;\n cv::Mat m_frame;\n cv::Mat m_frameGray;\n std::mutex m_runMutex;\n volatile bool m_run = true;\n};\n\nclass UnifiedVideoInertialTracker : boost::noncopyable {\n public:\n using size_type = std::size_t;\n UnifiedVideoInertialTracker(OSVR_PluginRegContext ctx,\n osvr::vbtracker::ImageSourcePtr &&source,\n osvr::vbtracker::ConfigParams params,\n TrackingSystemPtr &&trackingSystem)\n : m_source(std::move(source)),\n m_trackingSystem(std::move(trackingSystem)) {\n\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n \/\/ Configure the tracker interface.\n osvrDeviceTrackerConfigure(opts, &m_tracker);\n#if 0\n osvrDeviceAnalogConfigure(opts, &m_analog,\n DEBUGGABLE_BEACONS * DATAPOINTS_PER_BEACON);\n#endif\n\n \/\/\/ Create the analysis device token with the options\n OSVR_DeviceToken dev;\n if (OSVR_RETURN_FAILURE ==\n osvrAnalysisSyncInit(ctx, DRIVER_NAME, opts, &dev, &m_clientCtx)) {\n throw std::runtime_error(\"Could not initialize analysis plugin!\");\n }\n m_dev = osvr::pluginkit::DeviceToken(dev);\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(org_osvr_unifiedvideoinertial_json);\n\n \/\/\/ Set up thread communication.\n setupBodyReporting();\n\n \/\/\/ Set up the object that will run in the other thread, and spawn the\n \/\/\/ thread.\n startTrackerThread();\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n }\n\n ~UnifiedVideoInertialTracker() { stopTrackerThread(); }\n\n \/\/\/ Create a \"BodyReporting\" interchange structure for each body we track.\n void setupBodyReporting() {\n m_bodyReportingVector.clear();\n auto n = m_trackingSystem->getNumBodies();\n for (size_type i = 0; i < n; ++i) {\n m_bodyReportingVector.emplace_back(\n osvr::vbtracker::BodyReporting::make());\n }\n }\n\n OSVR_ReturnCode update();\n\n void startTrackerThread() {\n if (m_trackerThreadFunctor) {\n throw std::logic_error(\"Trying to start the tracker thread when \"\n \"it's already started!\");\n }\n std::cout << \"Starting the tracker thread...\" << std::endl;\n m_trackerThreadFunctor.reset(new TrackerThread(\n *m_trackingSystem, *m_source, m_bodyReportingVector,\n osvr::vbtracker::getHDKCameraParameters()));\n m_trackerThread = std::thread([&] { (*m_trackerThreadFunctor)(); });\n }\n void stopTrackerThread() {\n if (m_trackerThreadFunctor) {\n std::cout << \"Shutting down the tracker thread...\" << std::endl;\n m_trackerThreadFunctor->triggerStop();\n m_trackerThread.join();\n m_trackerThreadFunctor.reset();\n m_trackerThread = std::thread();\n }\n }\n\n private:\n osvr::pluginkit::DeviceToken m_dev;\n OSVR_ClientContext m_clientCtx;\n OSVR_ClientInterface m_clientInterface;\n OSVR_TrackerDeviceInterface m_tracker;\n#if 0\n OSVR_AnalogDeviceInterface m_analog;\n#endif\n osvr::vbtracker::ImageSourcePtr m_source;\n cv::Mat m_frame;\n cv::Mat m_imageGray;\n TrackingSystemPtr m_trackingSystem;\n std::vector<osvr::vbtracker::BodyReportingPtr> m_bodyReportingVector;\n std::unique_ptr<TrackerThread> m_trackerThreadFunctor;\n std::thread m_trackerThread;\n};\n\ninline OSVR_ReturnCode UnifiedVideoInertialTracker::update() {\n \/\/\/ @todo use the m_bodyReportingVector to report stuff.\n\n return OSVR_RETURN_SUCCESS;\n}\n\nclass ConfiguredDeviceConstructor {\n public:\n \/\/\/ @brief This is the required signature for a device instantiation\n \/\/\/ callback.\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) {\n \/\/ Read the JSON data from parameters.\n Json::Value root;\n if (params) {\n Json::Reader r;\n if (!r.parse(params, root)) {\n std::cerr << \"Could not parse parameters!\" << std::endl;\n }\n }\n\n \/\/ Read these parameters from a \"params\" field in the device Json\n \/\/ configuration file.\n\n \/\/ This is in a separate function\/header for sharing and for clarity.\n auto config = osvr::vbtracker::parseConfigParams(root);\n\n#ifdef _WIN32\n auto cam = osvr::vbtracker::openHDKCameraDirectShow();\n#else \/\/ !_WIN32\n \/\/\/ @todo This is rather crude, as we can't select the exact camera we\n \/\/\/ want, nor set the \"50Hz\" high-gain mode (and only works with HDK\n \/\/\/ camera firmware v7 and up). Presumably eventually use libuvc on\n \/\/\/ other platforms instead, at least for the HDK IR camera.\n\n auto cam = osvr::vbtracker::openOpenCVCamera(0);\n#endif\n\n if (!cam || !cam->ok()) {\n std::cerr << \"Could not access the tracking camera, skipping \"\n \"video-based tracking!\"\n << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n auto trackingSystem = osvr::vbtracker::makeHDKTrackingSystem(config);\n \/\/ OK, now that we have our parameters, create the device.\n osvr::pluginkit::PluginContext context(ctx);\n auto newTracker = osvr::pluginkit::registerObjectForDeletion(\n ctx, new UnifiedVideoInertialTracker(ctx, std::move(cam), config,\n std::move(trackingSystem)));\n\n return OSVR_RETURN_SUCCESS;\n }\n};\n\n} \/\/ namespace\n\nOSVR_PLUGIN(org_osvr_unifiedvideoinertial) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Tell the core we're available to create a device object.\n osvr::pluginkit::registerDriverInstantiationCallback(\n ctx, DRIVER_NAME, new ConfiguredDeviceConstructor);\n\n return OSVR_RETURN_SUCCESS;\n}\n<commit_msg>Re-enable thread capping for OpenCV<commit_after>\/** @file\n @brief Main file for a unified video-based and inertial tracking system.\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"ImageSources\/ImageSource.h\"\n#include \"ImageSources\/ImageSourceFactories.h\"\n\n#include \"MakeHDKTrackingSystem.h\"\n#include \"TrackingSystem.h\"\n#include \"ThreadsafeBodyReporting.h\"\n\n#include \"HDKLedIdentifierFactory.h\"\n#include \"CameraParameters.h\"\n#include \"HDKData.h\"\n#include <osvr\/AnalysisPluginKit\/AnalysisPluginKitC.h>\n#include <osvr\/PluginKit\/PluginKit.h>\n#include <osvr\/PluginKit\/TrackerInterfaceC.h>\n#include <osvr\/PluginKit\/AnalogInterfaceC.h>\n\n#include \"ConfigurationParser.h\"\n\n\/\/ Generated JSON header file\n#include \"org_osvr_unifiedvideoinertial_json.h\"\n\n\/\/ Library\/third-party includes\n#include <opencv2\/core\/core.hpp> \/\/ for basic OpenCV types\n#include <opencv2\/core\/operations.hpp>\n#include <opencv2\/highgui\/highgui.hpp> \/\/ for image capture\n#include <opencv2\/imgproc\/imgproc.hpp> \/\/ for image scaling\n#include <json\/value.h>\n#include <json\/reader.h>\n\n#include <boost\/noncopyable.hpp>\n\n#include <util\/Stride.h>\n\n\/\/ Standard includes\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <memory>\n#include <thread>\n#include <mutex>\n#include <stdexcept>\n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\nstatic const auto DRIVER_NAME = \"UnifiedTrackingSystem\";\n\nstatic const auto DEBUGGABLE_BEACONS = 34;\nstatic const auto DATAPOINTS_PER_BEACON = 5;\nusing TrackingSystemPtr = std::unique_ptr<osvr::vbtracker::TrackingSystem>;\nusing BodyReportingVector = std::vector<osvr::vbtracker::BodyReportingPtr>;\nclass TrackerThread : boost::noncopyable {\n public:\n TrackerThread(osvr::vbtracker::TrackingSystem &trackingSystem,\n osvr::vbtracker::ImageSource &imageSource,\n BodyReportingVector &reportingVec,\n osvr::vbtracker::CameraParameters const &camParams)\n : m_trackingSystem(trackingSystem), m_cam(imageSource),\n m_reportingVec(reportingVec), m_camParams(camParams) {\n msg() << \"Tracker thread object created.\" << std::endl;\n }\n\n void operator()() {\n msg() << \"Tracker thread object invoked.\" << std::endl;\n bool keepGoing = true;\n while (keepGoing) {\n doFrame();\n\n {\n \/\/\/ Copy the run flag.\n std::lock_guard<std::mutex> lock(m_runMutex);\n keepGoing = m_run;\n }\n if (!keepGoing) {\n msg() << \"Tracker thread object: Just checked our run flag and \"\n \"noticed it turned false...\"\n << std::endl;\n }\n }\n msg() << \"Tracker thread object: functor exiting.\" << std::endl;\n }\n\n \/\/\/ Call from the main thread!\n void triggerStop() {\n msg() << \"Tracker thread object: triggerStop() called\" << std::endl;\n std::lock_guard<std::mutex> lock(m_runMutex);\n m_run = false;\n }\n\n private:\n std::ostream &msg() const { return std::cout << \"[UnifiedTracker] \"; }\n std::ostream &warn() const { return msg() << \"Warning: \"; }\n void doFrame() {\n \/\/ Check camera status.\n if (!m_cam.ok()) {\n \/\/ Hmm, camera seems bad. Might regain it? Skip for now...\n warn() << \"Camera is reporting it is not OK.\" << std::endl;\n return;\n }\n \/\/ Trigger a grab.\n if (!m_cam.grab()) {\n \/\/ Again failing without quitting, in hopes we get better luck next\n \/\/ time...\n warn() << \"Camera grab failed.\" << std::endl;\n return;\n }\n \/\/ When we triggered the grab is our current best guess of the time for\n \/\/ the image\n \/\/\/ @todo backdate to account for image transfer image, exposure time,\n \/\/\/ etc.\n auto tv = osvr::util::time::getNow();\n\n \/\/ Pull the image into an OpenCV matrix named m_frame.\n m_cam.retrieve(m_frame, m_frameGray);\n if (!m_frame.data || !m_frameGray.data) {\n warn()\n << \"Camera retrieve appeared to fail: frames had null pointers!\"\n << std::endl;\n return;\n }\n\n \/\/ Submit to the tracking system.\n auto bodyIds = m_trackingSystem.processFrame(tv, m_frame, m_frameGray,\n m_camParams);\n\n for (auto const &bodyId : bodyIds) {\n \/\/\/ @todo stick stuff in m_reportingVec here.\n }\n }\n osvr::vbtracker::TrackingSystem &m_trackingSystem;\n osvr::vbtracker::ImageSource &m_cam;\n BodyReportingVector &m_reportingVec;\n osvr::vbtracker::CameraParameters m_camParams;\n cv::Mat m_frame;\n cv::Mat m_frameGray;\n std::mutex m_runMutex;\n volatile bool m_run = true;\n};\n\nclass UnifiedVideoInertialTracker : boost::noncopyable {\n public:\n using size_type = std::size_t;\n UnifiedVideoInertialTracker(OSVR_PluginRegContext ctx,\n osvr::vbtracker::ImageSourcePtr &&source,\n osvr::vbtracker::ConfigParams params,\n TrackingSystemPtr &&trackingSystem)\n : m_source(std::move(source)),\n m_trackingSystem(std::move(trackingSystem)) {\n if (params.numThreads > 0) {\n \/\/ Set the number of threads for OpenCV to use.\n cv::setNumThreads(params.numThreads);\n }\n\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n \/\/ Configure the tracker interface.\n osvrDeviceTrackerConfigure(opts, &m_tracker);\n#if 0\n osvrDeviceAnalogConfigure(opts, &m_analog,\n DEBUGGABLE_BEACONS * DATAPOINTS_PER_BEACON);\n#endif\n\n \/\/\/ Create the analysis device token with the options\n OSVR_DeviceToken dev;\n if (OSVR_RETURN_FAILURE ==\n osvrAnalysisSyncInit(ctx, DRIVER_NAME, opts, &dev, &m_clientCtx)) {\n throw std::runtime_error(\"Could not initialize analysis plugin!\");\n }\n m_dev = osvr::pluginkit::DeviceToken(dev);\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(org_osvr_unifiedvideoinertial_json);\n\n \/\/\/ Set up thread communication.\n setupBodyReporting();\n\n \/\/\/ Set up the object that will run in the other thread, and spawn the\n \/\/\/ thread.\n startTrackerThread();\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n }\n\n ~UnifiedVideoInertialTracker() { stopTrackerThread(); }\n\n \/\/\/ Create a \"BodyReporting\" interchange structure for each body we track.\n void setupBodyReporting() {\n m_bodyReportingVector.clear();\n auto n = m_trackingSystem->getNumBodies();\n for (size_type i = 0; i < n; ++i) {\n m_bodyReportingVector.emplace_back(\n osvr::vbtracker::BodyReporting::make());\n }\n }\n\n OSVR_ReturnCode update();\n\n void startTrackerThread() {\n if (m_trackerThreadFunctor) {\n throw std::logic_error(\"Trying to start the tracker thread when \"\n \"it's already started!\");\n }\n std::cout << \"Starting the tracker thread...\" << std::endl;\n m_trackerThreadFunctor.reset(new TrackerThread(\n *m_trackingSystem, *m_source, m_bodyReportingVector,\n osvr::vbtracker::getHDKCameraParameters()));\n m_trackerThread = std::thread([&] { (*m_trackerThreadFunctor)(); });\n }\n void stopTrackerThread() {\n if (m_trackerThreadFunctor) {\n std::cout << \"Shutting down the tracker thread...\" << std::endl;\n m_trackerThreadFunctor->triggerStop();\n m_trackerThread.join();\n m_trackerThreadFunctor.reset();\n m_trackerThread = std::thread();\n }\n }\n\n private:\n osvr::pluginkit::DeviceToken m_dev;\n OSVR_ClientContext m_clientCtx;\n OSVR_ClientInterface m_clientInterface;\n OSVR_TrackerDeviceInterface m_tracker;\n#if 0\n OSVR_AnalogDeviceInterface m_analog;\n#endif\n osvr::vbtracker::ImageSourcePtr m_source;\n cv::Mat m_frame;\n cv::Mat m_imageGray;\n TrackingSystemPtr m_trackingSystem;\n std::vector<osvr::vbtracker::BodyReportingPtr> m_bodyReportingVector;\n std::unique_ptr<TrackerThread> m_trackerThreadFunctor;\n std::thread m_trackerThread;\n};\n\ninline OSVR_ReturnCode UnifiedVideoInertialTracker::update() {\n \/\/\/ @todo use the m_bodyReportingVector to report stuff.\n\n return OSVR_RETURN_SUCCESS;\n}\n\nclass ConfiguredDeviceConstructor {\n public:\n \/\/\/ @brief This is the required signature for a device instantiation\n \/\/\/ callback.\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) {\n \/\/ Read the JSON data from parameters.\n Json::Value root;\n if (params) {\n Json::Reader r;\n if (!r.parse(params, root)) {\n std::cerr << \"Could not parse parameters!\" << std::endl;\n }\n }\n\n \/\/ Read these parameters from a \"params\" field in the device Json\n \/\/ configuration file.\n\n \/\/ This is in a separate function\/header for sharing and for clarity.\n auto config = osvr::vbtracker::parseConfigParams(root);\n\n#ifdef _WIN32\n auto cam = osvr::vbtracker::openHDKCameraDirectShow();\n#else \/\/ !_WIN32\n \/\/\/ @todo This is rather crude, as we can't select the exact camera we\n \/\/\/ want, nor set the \"50Hz\" high-gain mode (and only works with HDK\n \/\/\/ camera firmware v7 and up). Presumably eventually use libuvc on\n \/\/\/ other platforms instead, at least for the HDK IR camera.\n\n auto cam = osvr::vbtracker::openOpenCVCamera(0);\n#endif\n\n if (!cam || !cam->ok()) {\n std::cerr << \"Could not access the tracking camera, skipping \"\n \"video-based tracking!\"\n << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n auto trackingSystem = osvr::vbtracker::makeHDKTrackingSystem(config);\n \/\/ OK, now that we have our parameters, create the device.\n osvr::pluginkit::PluginContext context(ctx);\n auto newTracker = osvr::pluginkit::registerObjectForDeletion(\n ctx, new UnifiedVideoInertialTracker(ctx, std::move(cam), config,\n std::move(trackingSystem)));\n\n return OSVR_RETURN_SUCCESS;\n }\n};\n\n} \/\/ namespace\n\nOSVR_PLUGIN(org_osvr_unifiedvideoinertial) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Tell the core we're available to create a device object.\n osvr::pluginkit::registerDriverInstantiationCallback(\n ctx, DRIVER_NAME, new ConfiguredDeviceConstructor);\n\n return OSVR_RETURN_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n\n#include <sys\/stat.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#include \"config.h\"\n\n#include \"osd\/OSDMap.h\"\n#include \"mon\/MonMap.h\"\n\nvoid usage(const char *me)\n{\n cout << me << \" usage: [--print] [--createsimple <monmapfile> <numosd> [--clobber] [--pgbits <bitsperosd>]] <mapfilename>\" << std::endl;\n cout << me << \" --export-crush <file> write osdmap's crush map to <file>\" << std::endl;\n cout << me << \" --import-crush <file> replace osdmap's crush map with <file>\" << std::endl;\n exit(1);\n}\n\nvoid printmap(const char *me, OSDMap *m)\n{\n cout << me << \": osdmap: epoch \" << m->get_epoch() << std::endl\n << me << \": osdmap: fsid \" << m->get_fsid() << std::endl;\n \/*for (unsigned i=0; i<m->mon_inst.size(); i++)\n cout << me << \": osdmap: \" \/\/<< \"mon\" << i << \" \" \n\t << m->mon_inst[i] << std::endl;\n *\/\n}\n\n\nint main(int argc, const char **argv)\n{\n vector<const char*> args;\n argv_to_vec(argc, argv, args);\n parse_config_options(args);\n\n const char *me = argv[0];\n\n const char *fn = 0;\n bool print = false;\n bool createsimple = false;\n const char *monmapfn = 0;\n int num_osd = 0;\n int pg_bits = g_conf.osd_pg_bits;\n bool clobber = false;\n bool modified = false;\n const char *export_crush = 0;\n const char *import_crush = 0;\n list<entity_addr_t> add, rm;\n\n for (unsigned i=0; i<args.size(); i++) {\n if (strcmp(args[i], \"--print\") == 0)\n print = true;\n else if (strcmp(args[i], \"--createsimple\") == 0) {\n createsimple = true;\n monmapfn = args[++i];\n num_osd = atoi(args[++i]);\n } else if (strcmp(args[i], \"--clobber\") == 0) \n clobber = true;\n else if (strcmp(args[i], \"--pgbits\") == 0)\n pg_bits = atoi(args[++i]);\n else if (strcmp(args[i], \"--export-crush\") == 0)\n export_crush = args[++i];\n else if (strcmp(args[i], \"--import-crush\") == 0)\n import_crush = args[++i];\n else if (!fn)\n fn = args[i];\n else \n usage(me);\n }\n if (!fn) {\n cerr << me << \": must specify osdmap filename\" << std::endl;\n usage(me);\n }\n \n OSDMap osdmap;\n bufferlist bl;\n\n cout << me << \": osdmap file '\" << fn << \"'\" << std::endl;\n \n int r = 0;\n if (!(createsimple && clobber)) {\n r = bl.read_file(fn);\n osdmap.decode(bl);\n }\n if (!createsimple && r < 0) {\n cerr << me << \": couldn't open \" << fn << \": \" << strerror(errno) << std::endl;\n return -1;\n } \n else if (createsimple && !clobber && r == 0) {\n cerr << me << \": \" << fn << \" exists, --clobber to overwrite\" << std::endl;\n return -1;\n }\n\n if (createsimple) {\n MonMap monmap;\n int r = monmap.read(monmapfn);\n if (r < 0) {\n cerr << me << \": can't read monmap from \" << monmapfn << \": \" << strerror(r) << std::endl;\n exit(1);\n }\n osdmap.build_simple(0, monmap.fsid, num_osd, pg_bits, 0);\n modified = true;\n }\n\n if (import_crush) {\n bufferlist cbl;\n r = cbl.read_file(import_crush);\n if (r < 0) {\n cerr << me << \": error reading crush map from \" << import_crush << std::endl;\n exit(1);\n }\n \/\/ validate\n CrushWrapper cw;\n \/\/cw._decode(cbl, FIXME\n bufferlist::iterator p = cbl.begin();\n osdmap.crush.decode(p);\n cout << me << \": imported crush map from \" << import_crush << std::endl;\n modified = true;\n }\n\n if (export_crush) {\n bufferlist cbl;\n osdmap.crush.encode(cbl);\n r = cbl.write_file(export_crush);\n if (r < 0) {\n cerr << me << \": error writing crush map to \" << import_crush << std::endl;\n exit(1);\n }\n cout << me << \": exported crush map to \" << export_crush << std::endl;\n } \n\n if (!print && !modified && !export_crush && !import_crush) {\n cerr << me << \": no action specified?\" << std::endl;\n usage(me);\n }\n if (modified)\n osdmap.inc_epoch();\n\n if (print) \n printmap(me, &osdmap);\n\n if (modified) {\n osdmap.encode(bl);\n\n \/\/ write it out\n cout << me << \": writing epoch \" << osdmap.get_epoch()\n\t << \" to \" << fn\n\t << std::endl;\n int r = bl.write_file(fn);\n assert(r >= 0);\n }\n \n\n return 0;\n}\n<commit_msg>osdmaptool: require num_osd > 0 when creating new osdmap<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n\n#include <sys\/stat.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#include \"config.h\"\n\n#include \"osd\/OSDMap.h\"\n#include \"mon\/MonMap.h\"\n\nvoid usage(const char *me)\n{\n cout << me << \" usage: [--print] [--createsimple <monmapfile> <numosd> [--clobber] [--pgbits <bitsperosd>]] <mapfilename>\" << std::endl;\n cout << me << \" --export-crush <file> write osdmap's crush map to <file>\" << std::endl;\n cout << me << \" --import-crush <file> replace osdmap's crush map with <file>\" << std::endl;\n exit(1);\n}\n\nvoid printmap(const char *me, OSDMap *m)\n{\n cout << me << \": osdmap: epoch \" << m->get_epoch() << std::endl\n << me << \": osdmap: fsid \" << m->get_fsid() << std::endl;\n \/*for (unsigned i=0; i<m->mon_inst.size(); i++)\n cout << me << \": osdmap: \" \/\/<< \"mon\" << i << \" \" \n\t << m->mon_inst[i] << std::endl;\n *\/\n}\n\n\nint main(int argc, const char **argv)\n{\n vector<const char*> args;\n argv_to_vec(argc, argv, args);\n parse_config_options(args);\n\n const char *me = argv[0];\n\n const char *fn = 0;\n bool print = false;\n bool createsimple = false;\n const char *monmapfn = 0;\n int num_osd = 0;\n int pg_bits = g_conf.osd_pg_bits;\n bool clobber = false;\n bool modified = false;\n const char *export_crush = 0;\n const char *import_crush = 0;\n list<entity_addr_t> add, rm;\n\n for (unsigned i=0; i<args.size(); i++) {\n if (strcmp(args[i], \"--print\") == 0)\n print = true;\n else if (strcmp(args[i], \"--createsimple\") == 0) {\n createsimple = true;\n monmapfn = args[++i];\n num_osd = atoi(args[++i]);\n } else if (strcmp(args[i], \"--clobber\") == 0) \n clobber = true;\n else if (strcmp(args[i], \"--pgbits\") == 0)\n pg_bits = atoi(args[++i]);\n else if (strcmp(args[i], \"--export-crush\") == 0)\n export_crush = args[++i];\n else if (strcmp(args[i], \"--import-crush\") == 0)\n import_crush = args[++i];\n else if (!fn)\n fn = args[i];\n else \n usage(me);\n }\n if (!fn) {\n cerr << me << \": must specify osdmap filename\" << std::endl;\n usage(me);\n }\n \n OSDMap osdmap;\n bufferlist bl;\n\n cout << me << \": osdmap file '\" << fn << \"'\" << std::endl;\n \n int r = 0;\n if (!(createsimple && clobber)) {\n r = bl.read_file(fn);\n osdmap.decode(bl);\n }\n if (!createsimple && r < 0) {\n cerr << me << \": couldn't open \" << fn << \": \" << strerror(errno) << std::endl;\n return -1;\n } \n else if (createsimple && !clobber && r == 0) {\n cerr << me << \": \" << fn << \" exists, --clobber to overwrite\" << std::endl;\n return -1;\n }\n\n if (createsimple) {\n MonMap monmap;\n int r = monmap.read(monmapfn);\n if (r < 0) {\n cerr << me << \": can't read monmap from \" << monmapfn << \": \" << strerror(r) << std::endl;\n exit(1);\n }\n if (num_osd < 1) {\n cerr << me << \": osd count must be > 0\" << std::endl;\n exit(1);\n }\n osdmap.build_simple(0, monmap.fsid, num_osd, pg_bits, 0);\n modified = true;\n }\n\n if (import_crush) {\n bufferlist cbl;\n r = cbl.read_file(import_crush);\n if (r < 0) {\n cerr << me << \": error reading crush map from \" << import_crush << std::endl;\n exit(1);\n }\n \/\/ validate\n CrushWrapper cw;\n \/\/cw._decode(cbl, FIXME\n bufferlist::iterator p = cbl.begin();\n osdmap.crush.decode(p);\n cout << me << \": imported crush map from \" << import_crush << std::endl;\n modified = true;\n }\n\n if (export_crush) {\n bufferlist cbl;\n osdmap.crush.encode(cbl);\n r = cbl.write_file(export_crush);\n if (r < 0) {\n cerr << me << \": error writing crush map to \" << import_crush << std::endl;\n exit(1);\n }\n cout << me << \": exported crush map to \" << export_crush << std::endl;\n } \n\n if (!print && !modified && !export_crush && !import_crush) {\n cerr << me << \": no action specified?\" << std::endl;\n usage(me);\n }\n if (modified)\n osdmap.inc_epoch();\n\n if (print) \n printmap(me, &osdmap);\n\n if (modified) {\n osdmap.encode(bl);\n\n \/\/ write it out\n cout << me << \": writing epoch \" << osdmap.get_epoch()\n\t << \" to \" << fn\n\t << std::endl;\n int r = bl.write_file(fn);\n assert(r >= 0);\n }\n \n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is part of primesieve.\n\/\/ Homepage: http:\/\/primesieve.googlecode.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of the author nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"ParallelPrimeSieve.h\"\n#include \"PrimeSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"defs.h\"\n#include \"imath.h\"\n\n#if defined(_OPENMP)\n #include <omp.h>\n#endif\n\n#include <cstdlib>\n#include <stdexcept>\n#include <algorithm>\n\nParallelPrimeSieve::ParallelPrimeSieve() :\n numThreads_(USE_IDEAL_NUM_THREADS),\n shm_(NULL)\n{\n \/\/ prevents prime k-tuplet gaps\n static_assert(defs::MIN_THREAD_INTERVAL >= 100,\n \"defs::MIN_THREAD_INTERVAL >= 100\");\n}\n\n\/**\n * Used with the primesieve Qt application in ..\/qt-gui.\n * Initializes the ParallelPrimeSieve object with values from\n * a shared memory segment.\n *\/\nvoid ParallelPrimeSieve::init(SharedMemory* shm) {\n if (shm == NULL)\n throw std::invalid_argument(\n \"ParallelPrimeSieve: shared memory segment must not be NULL\");\n shm_ = shm;\n this->setStartNumber(shm_->startNumber);\n this->setStopNumber(shm_->stopNumber);\n this->setSieveSize(shm_->sieveSize);\n this->setFlags(shm_->flags);\n this->setNumThreads(shm_->threads);\n}\n\n\/**\n * Calculate the current status in percent of sieve().\n * @param processed The size of the processed segment (interval)\n *\/\nvoid ParallelPrimeSieve::doStatus(uint32_t processed) {\n#if defined(_OPENMP)\n #pragma omp critical (doStatus)\n#endif\n {\n PrimeSieve::doStatus(processed);\n \/\/ communicate the current status via shared memory\n \/\/ to the Qt GUI process\n if (shm_ != NULL)\n shm_->status = status_;\n }\n}\n\nint ParallelPrimeSieve::getMaxThreads() {\n#if defined(_OPENMP)\n return omp_get_max_threads();\n#else\n return 1;\n#endif\n}\n\n\/**\n * Get the current set number of threads for sieving.\n *\/\nint ParallelPrimeSieve::getNumThreads() const {\n return (numThreads_ == USE_IDEAL_NUM_THREADS)\n ? this->getIdealNumThreads() \n : numThreads_;\n}\n\n\/**\n * Set the number of threads for sieving.\n * If numThreads is invalid (numThreads < 1 or > getMaxThreads()) it\n * is set to numThreads = USE_IDEAL_NUM_THREADS.\n *\/\nvoid ParallelPrimeSieve::setNumThreads(int numThreads) {\n numThreads_ = (numThreads < 1 && numThreads > this->getMaxThreads())\n ? USE_IDEAL_NUM_THREADS\n : numThreads;\n}\n\n\/**\n * Get an ideal number of threads for the current set\n * startNumber_, stopNumber_ and flags_.\n *\/\nint ParallelPrimeSieve::getIdealNumThreads() const {\n \/\/ 1 thread to print primes and k-tuplets in sequential order\n if (testFlags(PRINT_PRIMES | PRINT_KTUPLETS))\n return 1;\n\n \/\/ each thread sieves at least an interval of size sqrt(n) \/ 6\n \/\/ but not smaller than defs::MIN_THREAD_INTERVAL\n uint64_t threadThreshold = std::max<uint64_t>(\n defs::MIN_THREAD_INTERVAL,\n isqrt(stopNumber_) \/ 6);\n\n \/\/ use all threads if the sieve interval is sufficiently large\n int idealNumThreads = static_cast<int> (\n std::min<uint64_t>(\n this->getInterval() \/ threadThreshold,\n this->getMaxThreads()));\n\n return std::max<int>(1, idealNumThreads);\n}\n\nuint64_t ParallelPrimeSieve::getInterval() const {\n return stopNumber_ - startNumber_;\n}\n\n\/**\n * Get an interval size that ensures a good load\n * balance among threads.\n *\/\nuint64_t ParallelPrimeSieve::getIdealInterval() const {\n uint64_t threads = this->getNumThreads();\n uint64_t interval = this->getInterval();\n if (threads == 1)\n return interval;\n\n \/\/ idealInterval = sqrt(n)*2000, 0.1 percent initialization\n uint64_t idealInterval = std::max<uint64_t>(\n defs::MIN_THREAD_INTERVAL,\n static_cast<uint64_t> (isqrt(stopNumber_)) * 2000);\n\n uint64_t maxThreadInterval = interval \/ threads;\n \/\/ correct the user's bad settings\n if (maxThreadInterval < interval &&\n maxThreadInterval < defs::MIN_THREAD_INTERVAL)\n maxThreadInterval = interval \/ this->getIdealNumThreads();\n\n return std::min<uint64_t>(idealInterval, maxThreadInterval);\n}\n\n\/**\n * Sieve the primes and prime k-tuplets within [startNumber, stopNumber]\n * in parallel using OpenMP.\n *\/\nvoid ParallelPrimeSieve::sieve() {\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n\n#if defined(_OPENMP)\n double t1 = omp_get_wtime();\n this->reset();\n uint64_t idealInterval = this->getIdealInterval();\n int64_t chunks = (idealInterval > 0) ? this->getInterval() \/ idealInterval : 1;\n uint64_t maxOffset = idealInterval * chunks;\n uint64_t maxStop = startNumber_ + maxOffset + (32 - maxOffset % 30);\n if (maxStop < stopNumber_) \n chunks += 1;\n\n int threads = this->getNumThreads();\n\n \/\/ split the sieve interval [startNumber_, stopNumber_]\n \/\/ into 'chunks' sub-intervals that are processed in\n \/\/ parallel using OpenMP\n #pragma omp parallel for num_threads(threads) schedule(dynamic)\n for (int64_t i = 0; i < chunks; i++) {\n uint64_t start = startNumber_ + idealInterval * i;\n uint64_t stop = startNumber_ + idealInterval * (i+1);\n \/\/ start\/stop numbers must be chosen carefully\n \/\/ to prevent prime k-tuplets gaps\n if (i > 0)\n start += 32 - start % 30;\n stop += 32 - stop % 30;\n if (stop > stopNumber_)\n stop = stopNumber_;\n \/\/ sieve the primes within [start, stop]\n PrimeSieve ps(start, stop, this);\n ps.sieve();\n #pragma omp critical (counts)\n for (uint32_t j = 0; j < COUNTS_SIZE; j++)\n counts_[j] += ps.getCounts(j);\n }\n timeElapsed_ = omp_get_wtime() - t1;\n#else\n PrimeSieve::sieve();\n#endif\n \/\/ communicate the sieving results via shared memory\n \/\/ segment to the Qt GUI process\n if (shm_ != NULL) {\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n shm_->counts[i] = counts_[i];\n shm_->timeElapsed = timeElapsed_;\n }\n}\n<commit_msg>minor update<commit_after>\/\/\n\/\/ Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.\n\/\/ All rights reserved.\n\/\/\n\/\/ This file is part of primesieve.\n\/\/ Homepage: http:\/\/primesieve.googlecode.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of the author nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"ParallelPrimeSieve.h\"\n#include \"PrimeSieve.h\"\n#include \"PrimeNumberFinder.h\"\n#include \"defs.h\"\n#include \"imath.h\"\n\n#if defined(_OPENMP)\n #include <omp.h>\n#endif\n\n#include <cstdlib>\n#include <stdexcept>\n#include <algorithm>\n\nParallelPrimeSieve::ParallelPrimeSieve() :\n numThreads_(USE_IDEAL_NUM_THREADS),\n shm_(NULL)\n{\n \/\/ prevents prime k-tuplet gaps\n static_assert(defs::MIN_THREAD_INTERVAL >= 100,\n \"defs::MIN_THREAD_INTERVAL >= 100\");\n}\n\n\/**\n * Used with the primesieve Qt application in ..\/qt-gui.\n * Initializes the ParallelPrimeSieve object with values from\n * a shared memory segment.\n *\/\nvoid ParallelPrimeSieve::init(SharedMemory* shm) {\n if (shm == NULL)\n throw std::invalid_argument(\n \"ParallelPrimeSieve: shared memory segment must not be NULL\");\n shm_ = shm;\n this->setStartNumber(shm_->startNumber);\n this->setStopNumber(shm_->stopNumber);\n this->setSieveSize(shm_->sieveSize);\n this->setFlags(shm_->flags);\n this->setNumThreads(shm_->threads);\n}\n\n\/**\n * Calculate the current status in percent of sieve().\n * @param processed The size of the processed segment (interval)\n *\/\nvoid ParallelPrimeSieve::doStatus(uint32_t processed) {\n#if defined(_OPENMP)\n #pragma omp critical (doStatus)\n#endif\n {\n PrimeSieve::doStatus(processed);\n \/\/ communicate the current status via shared memory\n \/\/ to the Qt GUI process\n if (shm_ != NULL)\n shm_->status = status_;\n }\n}\n\nint ParallelPrimeSieve::getMaxThreads() {\n#if defined(_OPENMP)\n return omp_get_max_threads();\n#else\n return 1;\n#endif\n}\n\n\/**\n * Get the current set number of threads for sieving.\n *\/\nint ParallelPrimeSieve::getNumThreads() const {\n return (numThreads_ == USE_IDEAL_NUM_THREADS)\n ? this->getIdealNumThreads() \n : numThreads_;\n}\n\n\/**\n * Set the number of threads for sieving.\n * If numThreads is invalid (numThreads < 1 or > getMaxThreads()) it\n * is set to numThreads = USE_IDEAL_NUM_THREADS.\n *\/\nvoid ParallelPrimeSieve::setNumThreads(int numThreads) {\n numThreads_ = (numThreads < 1 && numThreads > this->getMaxThreads())\n ? USE_IDEAL_NUM_THREADS\n : numThreads;\n}\n\n\/**\n * Get an ideal number of threads for the current set\n * startNumber_, stopNumber_ and flags_.\n *\/\nint ParallelPrimeSieve::getIdealNumThreads() const {\n \/\/ 1 thread to generate primes and k-tuplets in sequential order\n if (testFlags(GENERATE_FLAGS))\n return 1;\n\n \/\/ each thread sieves at least an interval of size sqrt(n) \/ 6\n \/\/ but not smaller than defs::MIN_THREAD_INTERVAL\n uint64_t threadThreshold = std::max<uint64_t>(\n defs::MIN_THREAD_INTERVAL,\n isqrt(stopNumber_) \/ 6);\n\n \/\/ use all threads if the sieve interval is sufficiently large\n int idealNumThreads = static_cast<int> (\n std::min<uint64_t>(\n this->getInterval() \/ threadThreshold,\n this->getMaxThreads()));\n\n return std::max<int>(1, idealNumThreads);\n}\n\nuint64_t ParallelPrimeSieve::getInterval() const {\n return stopNumber_ - startNumber_;\n}\n\n\/**\n * Get an interval size that ensures a good load\n * balance among threads.\n *\/\nuint64_t ParallelPrimeSieve::getIdealInterval() const {\n uint64_t threads = this->getNumThreads();\n uint64_t interval = this->getInterval();\n if (threads == 1)\n return interval;\n\n \/\/ idealInterval = sqrt(n)*2000, 0.1 percent initialization\n uint64_t idealInterval = std::max<uint64_t>(\n defs::MIN_THREAD_INTERVAL,\n static_cast<uint64_t> (isqrt(stopNumber_)) * 2000);\n\n uint64_t maxThreadInterval = interval \/ threads;\n \/\/ correct the user's bad settings\n if (maxThreadInterval < interval &&\n maxThreadInterval < defs::MIN_THREAD_INTERVAL)\n maxThreadInterval = interval \/ this->getIdealNumThreads();\n\n return std::min<uint64_t>(idealInterval, maxThreadInterval);\n}\n\n\/**\n * Sieve the primes and prime k-tuplets within [startNumber, stopNumber]\n * in parallel using OpenMP.\n *\/\nvoid ParallelPrimeSieve::sieve() {\n if (stopNumber_ < startNumber_)\n throw std::invalid_argument(\"STOP must be >= START\");\n\n#if defined(_OPENMP)\n double t1 = omp_get_wtime();\n this->reset();\n uint64_t idealInterval = this->getIdealInterval();\n int64_t chunks = (idealInterval > 0) ? this->getInterval() \/ idealInterval : 1;\n uint64_t maxOffset = idealInterval * chunks;\n uint64_t maxStop = startNumber_ + maxOffset + (32 - maxOffset % 30);\n if (maxStop < stopNumber_) \n chunks += 1;\n\n int threads = this->getNumThreads();\n\n \/\/ split the sieve interval [startNumber_, stopNumber_]\n \/\/ into 'chunks' sub-intervals that are processed in\n \/\/ parallel using OpenMP\n #pragma omp parallel for num_threads(threads) schedule(dynamic)\n for (int64_t i = 0; i < chunks; i++) {\n uint64_t start = startNumber_ + idealInterval * i;\n uint64_t stop = startNumber_ + idealInterval * (i+1);\n \/\/ start\/stop numbers must be chosen carefully\n \/\/ to prevent prime k-tuplets gaps\n if (i > 0)\n start += 32 - start % 30;\n stop += 32 - stop % 30;\n if (stop > stopNumber_)\n stop = stopNumber_;\n \/\/ sieve the primes within [start, stop]\n PrimeSieve ps(start, stop, this);\n ps.sieve();\n #pragma omp critical (counts)\n for (uint32_t j = 0; j < COUNTS_SIZE; j++)\n counts_[j] += ps.getCounts(j);\n }\n timeElapsed_ = omp_get_wtime() - t1;\n#else\n PrimeSieve::sieve();\n#endif\n \/\/ communicate the sieving results via shared memory\n \/\/ segment to the Qt GUI process\n if (shm_ != NULL) {\n for (uint32_t i = 0; i < COUNTS_SIZE; i++)\n shm_->counts[i] = counts_[i];\n shm_->timeElapsed = timeElapsed_;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbFineRegistrationImageFilter.h\"\n#include \"otbStandardWriterWatcher.h\"\n#include \"otbCommandLineArgumentParser.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageList.h\"\n#include \"otbImageListToVectorImageFilter.h\"\n\n#include \"itkTimeProbe.h\"\n#include \"itkFixedArray.h\"\n#include \"itkNormalizedCorrelationImageToImageMetric.h\"\n#include \"itkMeanReciprocalSquareDifferenceImageToImageMetric.h\"\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkAbsImageFilter.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n#include \"itkBinaryThresholdImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n \/\/ Parse command line parameters\n typedef otb::CommandLineArgumentParser ParserType;\n ParserType::Pointer parser = ParserType::New();\n\n parser->SetProgramDescription(\"Estimate disparity map between two images. Output image contain x offset, y offset and metric value.\");\n parser->AddOption(\"--Reference\",\"The reference image\",\"-ref\", 1,true);\n parser->AddOption(\"--Secondary\",\"The secondary image\",\"-sec\", 1,true);\n parser->AddOutputImage();\n parser->AddOption(\"--ExplorationRadius\",\"Radius (in pixels) of the exploration window\",\"-er\",2,true);\n parser->AddOption(\"--MetricRadius\",\"Radius (in pixels) of the metric computation window\",\"-mr\",2,true);\n parser->AddOption(\"--CoarseOffset\",\"(optional) Coarse offset (in physical space) between the two images. Default is [0,0].\",\"-co\",2,false);\n parser->AddOption(\"--SubSamplingRate\",\"(optional) Generate a result at a coarser resolution with a given sub-sampling rate in each direction (in pixels). Default is no sub-sampling\",\"-ssr\",2,false);\n parser->AddOption(\"--ReferenceGaussianSmoothing\",\"(optional) Perform a gaussian smoothing of the reference image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.\",\"-rgs\",2,false);\n parser->AddOption(\"--SecondaryGaussianSmoothing\",\"(optional) Perform a gaussian smoothing of the secondary image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.\",\"-sgs\",2,false);\n parser->AddOption(\"--Metric\",\"(optional) Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation\",\"-m\",1,false);\n parser->AddOption(\"--SubPixelAccuracy\",\"(optional) Metric extrema location will be refined up to the given accuracy. Default is 0.01\",\"-spa\",1,false);\n parser->AddOption(\"--ValidityMask\",\"(optional) Threshold to obtain a validity mask. Params are lowerThan or greaterThan and a threshold\",\"-vm\",2,true);\n\n typedef otb::CommandLineArgumentParseResult ParserResultType;\n ParserResultType::Pointer parseResult = ParserResultType::New();\n\n try\n {\n parser->ParseCommandLine(argc,argv,parseResult);\n }\n catch ( itk::ExceptionObject & err )\n {\n std::string descriptionException = err.GetDescription();\n if (descriptionException.find(\"ParseCommandLine(): Help Parser\") != std::string::npos)\n {\n return EXIT_SUCCESS;\n }\n if (descriptionException.find(\"ParseCommandLine(): Version Parser\") != std::string::npos)\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n const unsigned int Dimension = 2;\n typedef double PixelType;\n\n typedef itk::FixedArray<PixelType,Dimension> DeformationValueType;\n typedef otb::Image< PixelType, Dimension > ImageType;\n typedef otb::VectorImage<PixelType,Dimension> VectorImageType;\n typedef otb::ImageList<ImageType> ImageListType;\n typedef otb::ImageListToVectorImageFilter<ImageListType,VectorImageType> IL2VIFilterType;\n typedef otb::Image<DeformationValueType,Dimension> FieldImageType;\n typedef otb::ImageFileReader< ImageType > ReaderType;\n typedef otb::StreamingImageFileWriter< VectorImageType > WriterType;\n typedef otb::FineRegistrationImageFilter<ImageType,ImageType,FieldImageType> RegistrationFilterType;\n typedef itk::DiscreteGaussianImageFilter<ImageType,ImageType> GaussianFilterType;\n typedef itk::VectorIndexSelectionCastImageFilter<FieldImageType,ImageType> VectorImageToImageFilterType;\n typedef itk::AbsImageFilter<ImageType,ImageType> AbsFilterType;\n typedef itk::BinaryThresholdImageFilter<ImageType,ImageType> BinaryThresholdImageFilterType;\n\n \/\/ Read reference image\n ReaderType::Pointer freader = ReaderType::New();\n freader->SetFileName(parseResult->GetParameterString(\"--Reference\"));\n\n \/\/ Read secondary image\n ReaderType::Pointer mreader = ReaderType::New();\n mreader->SetFileName(parseResult->GetParameterString(\"--Secondary\"));\n\n \/\/ Retrieve main registration parameters\n RegistrationFilterType::SizeType radius, sradius;\n ImageType::OffsetType ssrate;\n sradius[0] = parseResult->GetParameterULong(\"--ExplorationRadius\",0);\n sradius[1] = parseResult->GetParameterULong(\"--ExplorationRadius\",1);\n radius[0] = parseResult->GetParameterULong(\"--MetricRadius\",0);\n radius[1] = parseResult->GetParameterULong(\"--MetricRadius\",1);\n\n double accuracy = 0.01;\n if(parseResult->IsOptionPresent(\"--SubPixelAccuracy\"))\n {\n accuracy = parseResult->GetParameterDouble(\"--SubPixelAccuracy\");\n }\n ssrate.Fill(1);\n if(parseResult->IsOptionPresent(\"--SubSamplingRate\"))\n {\n ssrate[0] = parseResult->GetParameterDouble(\"--SubSamplingRate\",0);\n ssrate[1] = parseResult->GetParameterDouble(\"--SubSamplingRate\",1);\n }\n RegistrationFilterType::SpacingType initialOffset;\n initialOffset.Fill(0);\n if(parseResult->IsOptionPresent(\"--CoarseOffset\"))\n {\n initialOffset[0] = parseResult->GetParameterDouble(\"--CoarseOffset\",0);\n initialOffset[1] = parseResult->GetParameterDouble(\"--CoarseOffset\",1);\n }\n\n \/\/ Display info\n std::cout<<\"Reference image : \"<<freader->GetFileName()<<std::endl;\n std::cout<<\"Secondary image : \"<<mreader->GetFileName()<<std::endl;\n\n std::cout<<\"Exploration radius: \"<<sradius<<\" (pixels)\"<<std::endl;\n std::cout<<\"Metric radius : \"<<radius<<\" (pixels)\"<<std::endl;\n std::cout<<\"Sub-sampling rate : \"<<ssrate<<\" (pixels)\"<<std::endl;\n std::cout<<\"Coarse offset : \"<<initialOffset<<\" (physical unit)\"<<std::endl;\n std::cout<<\"Accuracy : \"<<accuracy<<\" (physical unit)\"<<std::endl;\n\n\n RegistrationFilterType::Pointer registration = RegistrationFilterType::New();\n registration->SetRadius(radius);\n registration->SetSearchRadius(sradius);\n registration->SetSubPixelAccuracy(accuracy);\n registration->SetGridStep(ssrate);\n registration->SetInitialOffset(initialOffset);\n\n GaussianFilterType::Pointer refGaussianFilter,secGaussianFilter;\n\n if(parseResult->IsOptionPresent(\"--ReferenceGaussianSmoothing\"))\n {\n refGaussianFilter = GaussianFilterType::New();\n refGaussianFilter->SetInput(freader->GetOutput());\n GaussianFilterType::ArrayType sigma;\n sigma[0] = parseResult->GetParameterDouble(\"--ReferenceGaussianSmoothing\",0);\n sigma[1] = parseResult->GetParameterDouble(\"--ReferenceGaussianSmoothing\",1);\n refGaussianFilter->SetVariance(sigma);\n refGaussianFilter->SetUseImageSpacingOff();\n std::cout<<\"Reference image gaussian smoothing on.\"<<std::endl;\n std::cout<<\"variance : \"<<sigma<<\" (pixels)\"<<std::endl;\n registration->SetFixedInput(refGaussianFilter->GetOutput());\n }\n else\n {\n std::cout<<\"Reference image gaussian smoothing off.\"<<std::endl;\n registration->SetFixedInput(freader->GetOutput());\n }\n\n if(parseResult->IsOptionPresent(\"--SecondaryGaussianSmoothing\"))\n {\n secGaussianFilter = GaussianFilterType::New();\n secGaussianFilter->SetInput(mreader->GetOutput());\n GaussianFilterType::ArrayType sigma;\n sigma[0] = parseResult->GetParameterDouble(\"--SecondaryGaussianSmoothing\",0);\n sigma[1] = parseResult->GetParameterDouble(\"--SecondaryGaussianSmoothing\",1);\n secGaussianFilter->SetVariance(sigma);\n secGaussianFilter->SetUseImageSpacingOff();\n std::cout<<\"Secondary image gaussian smoothing on.\"<<std::endl;\n std::cout<<\"variance : \"<<sigma<<\" (pixels)\"<<std::endl;\n registration->SetMovingInput(secGaussianFilter->GetOutput());\n }\n else\n {\n std::cout<<\"Secondary image gaussian smoothing off.\"<<std::endl;\n registration->SetMovingInput(mreader->GetOutput());\n }\n\n \/\/ Retrieve metric name\n std::string metricId = \"CC\";\n if(parseResult->IsOptionPresent(\"--Metric\"))\n {\n metricId = parseResult->GetParameterString(\"--Metric\");\n }\n\n if(metricId == \"CC\")\n {\n std::cout<<\"Metric : Cross-correlation\"<<std::endl;\n typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType;\n NCCType::Pointer metricPtr = NCCType::New();\n metricPtr->SubtractMeanOff();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"CCSM\")\n {\n std::cout<<\"Metric : Cross-correlation (mean subtracted)\"<<std::endl;\n typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType;\n NCCType::Pointer metricPtr = NCCType::New();\n metricPtr->SubtractMeanOn();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"MSD\")\n {\n std::cout<<\"Metric : Mean square difference\"<<std::endl;\n typedef itk::MeanSquaresImageToImageMetric<ImageType,ImageType> MeanSquareType;\n MeanSquareType::Pointer metricPtr = MeanSquareType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"MRSD\")\n {\n std::cout<<\"Metric : Mean reciprocal square difference\"<<std::endl;\n typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<ImageType,ImageType> MRSDType;\n MRSDType::Pointer metricPtr = MRSDType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOff();\n }\n else if(metricId == \"MI\")\n {\n std::cout<<\"Metric : Mutual information\"<<std::endl;\n typedef itk::MattesMutualInformationImageToImageMetric<ImageType,ImageType> MIType;\n MIType::Pointer metricPtr = MIType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else\n {\n std::cerr<<\"Metric \"<<metricId<<\" not recognized.\"<<std::endl;\n std::cerr<<\"Possible choices are: CC, CCMS, MSD, MRSD, MI\"<<std::endl;\n return EXIT_FAILURE;\n }\n VectorImageToImageFilterType::Pointer xExtractor = VectorImageToImageFilterType::New();\n xExtractor->SetInput(registration->GetOutputDeformationField());\n xExtractor->SetIndex(0);\n\n VectorImageToImageFilterType::Pointer yExtractor = VectorImageToImageFilterType::New();\n yExtractor->SetInput(registration->GetOutputDeformationField());\n yExtractor->SetIndex(1);\n\n ImageListType::Pointer il = ImageListType::New();\n il->PushBack(xExtractor->GetOutput());\n il->PushBack(yExtractor->GetOutput());\n\n AbsFilterType::Pointer absFilter;\n\n \/\/ Invert correlation to get classical rendering\n if(metricId == \"CC\" || metricId == \"CCSM\")\n {\n absFilter = AbsFilterType::New();\n absFilter->SetInput(registration->GetOutput());\n il->PushBack(absFilter->GetOutput());\n }\n else\n {\n il->PushBack(registration->GetOutput());\n }\n\n BinaryThresholdImageFilterType::Pointer threshold;\n if(parseResult->IsOptionPresent(\"--ValidityMask\"))\n {\n threshold = BinaryThresholdImageFilterType::New();\n\n if(metricId == \"CC\" || metricId == \"CCSM\")\n {\n threshold->SetInput(absFilter->GetOutput());\n }\n else\n {\n threshold->SetInput(registration->GetOutput());\n }\n if(parseResult->GetParameterString(\"--ValidityMask\",0)==\"greaterThan\")\n {\n threshold->SetLowerThreshold(parseResult->GetParameterDouble(\"--ValidityMask\",1));\n }\n else if(parseResult->GetParameterString(\"--ValidityMask\",0)==\"lowerThan\")\n {\n threshold->SetUpperThreshold(parseResult->GetParameterDouble(\"--ValidityMask\",1));\n }\n else\n {\n std::cerr<<\"Arguments of --ValidityMask option should begin with lowerThan or greaterThan\"<<std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout<<\"A validity mask will be produced as the 4th band (valid pixels = 1.0, not valid = 0.0).\"<<std::endl;\n std::cout<<\"Pixels are considered valid if metric is \"<<parseResult->GetParameterString(\"--ValidityMask\",0)<<\" \";\n std::cout<<parseResult->GetParameterDouble(\"--ValidityMask\",1)<<std::endl;\n\n threshold->SetInsideValue(1.0);\n threshold->SetOutsideValue(0.);\n il->PushBack(threshold->GetOutput());\n }\n\n IL2VIFilterType::Pointer il2vi = IL2VIFilterType::New();\n il2vi->SetInput(il);\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(parseResult->GetOutputImage());\n writer->SetInput(il2vi->GetOutput());\n\n std::cout<<std::endl;\n otb::StandardWriterWatcher watcher(writer,registration,\"Fine Registration\");\n\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>BUG: validity mask is optional<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbFineRegistrationImageFilter.h\"\n#include \"otbStandardWriterWatcher.h\"\n#include \"otbCommandLineArgumentParser.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageList.h\"\n#include \"otbImageListToVectorImageFilter.h\"\n\n#include \"itkTimeProbe.h\"\n#include \"itkFixedArray.h\"\n#include \"itkNormalizedCorrelationImageToImageMetric.h\"\n#include \"itkMeanReciprocalSquareDifferenceImageToImageMetric.h\"\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkMattesMutualInformationImageToImageMetric.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkAbsImageFilter.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n#include \"itkBinaryThresholdImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n \/\/ Parse command line parameters\n typedef otb::CommandLineArgumentParser ParserType;\n ParserType::Pointer parser = ParserType::New();\n\n parser->SetProgramDescription(\"Estimate disparity map between two images. Output image contain x offset, y offset and metric value.\");\n parser->AddOption(\"--Reference\",\"The reference image\",\"-ref\", 1,true);\n parser->AddOption(\"--Secondary\",\"The secondary image\",\"-sec\", 1,true);\n parser->AddOutputImage();\n parser->AddOption(\"--ExplorationRadius\",\"Radius (in pixels) of the exploration window\",\"-er\",2,true);\n parser->AddOption(\"--MetricRadius\",\"Radius (in pixels) of the metric computation window\",\"-mr\",2,true);\n parser->AddOption(\"--CoarseOffset\",\"(optional) Coarse offset (in physical space) between the two images. Default is [0,0].\",\"-co\",2,false);\n parser->AddOption(\"--SubSamplingRate\",\"(optional) Generate a result at a coarser resolution with a given sub-sampling rate in each direction (in pixels). Default is no sub-sampling\",\"-ssr\",2,false);\n parser->AddOption(\"--ReferenceGaussianSmoothing\",\"(optional) Perform a gaussian smoothing of the reference image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.\",\"-rgs\",2,false);\n parser->AddOption(\"--SecondaryGaussianSmoothing\",\"(optional) Perform a gaussian smoothing of the secondary image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.\",\"-sgs\",2,false);\n parser->AddOption(\"--Metric\",\"(optional) Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation\",\"-m\",1,false);\n parser->AddOption(\"--SubPixelAccuracy\",\"(optional) Metric extrema location will be refined up to the given accuracy. Default is 0.01\",\"-spa\",1,false);\n parser->AddOption(\"--ValidityMask\",\"(optional) Threshold to obtain a validity mask. Params are lowerThan or greaterThan and a threshold\",\"-vm\",2,false);\n\n typedef otb::CommandLineArgumentParseResult ParserResultType;\n ParserResultType::Pointer parseResult = ParserResultType::New();\n\n try\n {\n parser->ParseCommandLine(argc,argv,parseResult);\n }\n catch ( itk::ExceptionObject & err )\n {\n std::string descriptionException = err.GetDescription();\n if (descriptionException.find(\"ParseCommandLine(): Help Parser\") != std::string::npos)\n {\n return EXIT_SUCCESS;\n }\n if (descriptionException.find(\"ParseCommandLine(): Version Parser\") != std::string::npos)\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n const unsigned int Dimension = 2;\n typedef double PixelType;\n\n typedef itk::FixedArray<PixelType,Dimension> DeformationValueType;\n typedef otb::Image< PixelType, Dimension > ImageType;\n typedef otb::VectorImage<PixelType,Dimension> VectorImageType;\n typedef otb::ImageList<ImageType> ImageListType;\n typedef otb::ImageListToVectorImageFilter<ImageListType,VectorImageType> IL2VIFilterType;\n typedef otb::Image<DeformationValueType,Dimension> FieldImageType;\n typedef otb::ImageFileReader< ImageType > ReaderType;\n typedef otb::StreamingImageFileWriter< VectorImageType > WriterType;\n typedef otb::FineRegistrationImageFilter<ImageType,ImageType,FieldImageType> RegistrationFilterType;\n typedef itk::DiscreteGaussianImageFilter<ImageType,ImageType> GaussianFilterType;\n typedef itk::VectorIndexSelectionCastImageFilter<FieldImageType,ImageType> VectorImageToImageFilterType;\n typedef itk::AbsImageFilter<ImageType,ImageType> AbsFilterType;\n typedef itk::BinaryThresholdImageFilter<ImageType,ImageType> BinaryThresholdImageFilterType;\n\n \/\/ Read reference image\n ReaderType::Pointer freader = ReaderType::New();\n freader->SetFileName(parseResult->GetParameterString(\"--Reference\"));\n\n \/\/ Read secondary image\n ReaderType::Pointer mreader = ReaderType::New();\n mreader->SetFileName(parseResult->GetParameterString(\"--Secondary\"));\n\n \/\/ Retrieve main registration parameters\n RegistrationFilterType::SizeType radius, sradius;\n ImageType::OffsetType ssrate;\n sradius[0] = parseResult->GetParameterULong(\"--ExplorationRadius\",0);\n sradius[1] = parseResult->GetParameterULong(\"--ExplorationRadius\",1);\n radius[0] = parseResult->GetParameterULong(\"--MetricRadius\",0);\n radius[1] = parseResult->GetParameterULong(\"--MetricRadius\",1);\n\n double accuracy = 0.01;\n if(parseResult->IsOptionPresent(\"--SubPixelAccuracy\"))\n {\n accuracy = parseResult->GetParameterDouble(\"--SubPixelAccuracy\");\n }\n ssrate.Fill(1);\n if(parseResult->IsOptionPresent(\"--SubSamplingRate\"))\n {\n ssrate[0] = parseResult->GetParameterDouble(\"--SubSamplingRate\",0);\n ssrate[1] = parseResult->GetParameterDouble(\"--SubSamplingRate\",1);\n }\n RegistrationFilterType::SpacingType initialOffset;\n initialOffset.Fill(0);\n if(parseResult->IsOptionPresent(\"--CoarseOffset\"))\n {\n initialOffset[0] = parseResult->GetParameterDouble(\"--CoarseOffset\",0);\n initialOffset[1] = parseResult->GetParameterDouble(\"--CoarseOffset\",1);\n }\n\n \/\/ Display info\n std::cout<<\"Reference image : \"<<freader->GetFileName()<<std::endl;\n std::cout<<\"Secondary image : \"<<mreader->GetFileName()<<std::endl;\n\n std::cout<<\"Exploration radius: \"<<sradius<<\" (pixels)\"<<std::endl;\n std::cout<<\"Metric radius : \"<<radius<<\" (pixels)\"<<std::endl;\n std::cout<<\"Sub-sampling rate : \"<<ssrate<<\" (pixels)\"<<std::endl;\n std::cout<<\"Coarse offset : \"<<initialOffset<<\" (physical unit)\"<<std::endl;\n std::cout<<\"Accuracy : \"<<accuracy<<\" (physical unit)\"<<std::endl;\n\n\n RegistrationFilterType::Pointer registration = RegistrationFilterType::New();\n registration->SetRadius(radius);\n registration->SetSearchRadius(sradius);\n registration->SetSubPixelAccuracy(accuracy);\n registration->SetGridStep(ssrate);\n registration->SetInitialOffset(initialOffset);\n\n GaussianFilterType::Pointer refGaussianFilter,secGaussianFilter;\n\n if(parseResult->IsOptionPresent(\"--ReferenceGaussianSmoothing\"))\n {\n refGaussianFilter = GaussianFilterType::New();\n refGaussianFilter->SetInput(freader->GetOutput());\n GaussianFilterType::ArrayType sigma;\n sigma[0] = parseResult->GetParameterDouble(\"--ReferenceGaussianSmoothing\",0);\n sigma[1] = parseResult->GetParameterDouble(\"--ReferenceGaussianSmoothing\",1);\n refGaussianFilter->SetVariance(sigma);\n refGaussianFilter->SetUseImageSpacingOff();\n std::cout<<\"Reference image gaussian smoothing on.\"<<std::endl;\n std::cout<<\"variance : \"<<sigma<<\" (pixels)\"<<std::endl;\n registration->SetFixedInput(refGaussianFilter->GetOutput());\n }\n else\n {\n std::cout<<\"Reference image gaussian smoothing off.\"<<std::endl;\n registration->SetFixedInput(freader->GetOutput());\n }\n\n if(parseResult->IsOptionPresent(\"--SecondaryGaussianSmoothing\"))\n {\n secGaussianFilter = GaussianFilterType::New();\n secGaussianFilter->SetInput(mreader->GetOutput());\n GaussianFilterType::ArrayType sigma;\n sigma[0] = parseResult->GetParameterDouble(\"--SecondaryGaussianSmoothing\",0);\n sigma[1] = parseResult->GetParameterDouble(\"--SecondaryGaussianSmoothing\",1);\n secGaussianFilter->SetVariance(sigma);\n secGaussianFilter->SetUseImageSpacingOff();\n std::cout<<\"Secondary image gaussian smoothing on.\"<<std::endl;\n std::cout<<\"variance : \"<<sigma<<\" (pixels)\"<<std::endl;\n registration->SetMovingInput(secGaussianFilter->GetOutput());\n }\n else\n {\n std::cout<<\"Secondary image gaussian smoothing off.\"<<std::endl;\n registration->SetMovingInput(mreader->GetOutput());\n }\n\n \/\/ Retrieve metric name\n std::string metricId = \"CC\";\n if(parseResult->IsOptionPresent(\"--Metric\"))\n {\n metricId = parseResult->GetParameterString(\"--Metric\");\n }\n\n if(metricId == \"CC\")\n {\n std::cout<<\"Metric : Cross-correlation\"<<std::endl;\n typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType;\n NCCType::Pointer metricPtr = NCCType::New();\n metricPtr->SubtractMeanOff();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"CCSM\")\n {\n std::cout<<\"Metric : Cross-correlation (mean subtracted)\"<<std::endl;\n typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType;\n NCCType::Pointer metricPtr = NCCType::New();\n metricPtr->SubtractMeanOn();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"MSD\")\n {\n std::cout<<\"Metric : Mean square difference\"<<std::endl;\n typedef itk::MeanSquaresImageToImageMetric<ImageType,ImageType> MeanSquareType;\n MeanSquareType::Pointer metricPtr = MeanSquareType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else if(metricId == \"MRSD\")\n {\n std::cout<<\"Metric : Mean reciprocal square difference\"<<std::endl;\n typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<ImageType,ImageType> MRSDType;\n MRSDType::Pointer metricPtr = MRSDType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOff();\n }\n else if(metricId == \"MI\")\n {\n std::cout<<\"Metric : Mutual information\"<<std::endl;\n typedef itk::MattesMutualInformationImageToImageMetric<ImageType,ImageType> MIType;\n MIType::Pointer metricPtr = MIType::New();\n registration->SetMetric(metricPtr);\n registration->MinimizeOn();\n }\n else\n {\n std::cerr<<\"Metric \"<<metricId<<\" not recognized.\"<<std::endl;\n std::cerr<<\"Possible choices are: CC, CCMS, MSD, MRSD, MI\"<<std::endl;\n return EXIT_FAILURE;\n }\n VectorImageToImageFilterType::Pointer xExtractor = VectorImageToImageFilterType::New();\n xExtractor->SetInput(registration->GetOutputDeformationField());\n xExtractor->SetIndex(0);\n\n VectorImageToImageFilterType::Pointer yExtractor = VectorImageToImageFilterType::New();\n yExtractor->SetInput(registration->GetOutputDeformationField());\n yExtractor->SetIndex(1);\n\n ImageListType::Pointer il = ImageListType::New();\n il->PushBack(xExtractor->GetOutput());\n il->PushBack(yExtractor->GetOutput());\n\n AbsFilterType::Pointer absFilter;\n\n \/\/ Invert correlation to get classical rendering\n if(metricId == \"CC\" || metricId == \"CCSM\")\n {\n absFilter = AbsFilterType::New();\n absFilter->SetInput(registration->GetOutput());\n il->PushBack(absFilter->GetOutput());\n }\n else\n {\n il->PushBack(registration->GetOutput());\n }\n\n BinaryThresholdImageFilterType::Pointer threshold;\n if(parseResult->IsOptionPresent(\"--ValidityMask\"))\n {\n threshold = BinaryThresholdImageFilterType::New();\n\n if(metricId == \"CC\" || metricId == \"CCSM\")\n {\n threshold->SetInput(absFilter->GetOutput());\n }\n else\n {\n threshold->SetInput(registration->GetOutput());\n }\n if(parseResult->GetParameterString(\"--ValidityMask\",0)==\"greaterThan\")\n {\n threshold->SetLowerThreshold(parseResult->GetParameterDouble(\"--ValidityMask\",1));\n }\n else if(parseResult->GetParameterString(\"--ValidityMask\",0)==\"lowerThan\")\n {\n threshold->SetUpperThreshold(parseResult->GetParameterDouble(\"--ValidityMask\",1));\n }\n else\n {\n std::cerr<<\"Arguments of --ValidityMask option should begin with lowerThan or greaterThan\"<<std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout<<\"A validity mask will be produced as the 4th band (valid pixels = 1.0, not valid = 0.0).\"<<std::endl;\n std::cout<<\"Pixels are considered valid if metric is \"<<parseResult->GetParameterString(\"--ValidityMask\",0)<<\" \";\n std::cout<<parseResult->GetParameterDouble(\"--ValidityMask\",1)<<std::endl;\n\n threshold->SetInsideValue(1.0);\n threshold->SetOutsideValue(0.);\n il->PushBack(threshold->GetOutput());\n }\n\n IL2VIFilterType::Pointer il2vi = IL2VIFilterType::New();\n il2vi->SetInput(il);\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(parseResult->GetOutputImage());\n writer->SetInput(il2vi->GetOutput());\n\n std::cout<<std::endl;\n otb::StandardWriterWatcher watcher(writer,registration,\"Fine Registration\");\n\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef HTTP_CLIENT_HH\n#define HTTP_CLIENT_HH\n\n#include \"http\/http_message.hh\"\n#include \"shared_pool.hh\"\n#include \"buffer.hh\"\n\nnamespace ten {\n\nclass http_client {\nprivate:\n std::shared_ptr<netsock> s;\n buffer buf;\n\n void ensure_connection() {\n if (s && s->valid()) return;\n s.reset(new netsock(AF_INET, SOCK_STREAM));\n if (s->dial(host.c_str(), port) != 0) {\n throw errorx(\"dial %s:%d failed\", host.c_str(), port);\n }\n }\n\npublic:\n const std::string host;\n const uint16_t port;\n\n http_client(const std::string &host_, uint16_t port_=80)\n : buf(4*1024), host(host_), port(port_) {}\n\n http_response perform(const std::string &method, const std::string &path, const std::string &data=\"\") {\n try {\n ensure_connection();\n uri u;\n u.scheme = \"http\";\n u.host = host;\n u.port = port;\n u.path = path;\n u.normalize();\n\n http_request r(method, u.compose(true));\n \/\/ HTTP\/1.1 requires host header\n r.append(\"Host\", u.host); \n r.append(\"Content-Length\", data.size());\n\n std::string hdata = r.data();\n ssize_t nw = s->send(hdata.c_str(), hdata.size());\n nw = s->send(data.c_str(), data.size());\n\n http_parser parser;\n http_response resp;\n resp.parser_init(&parser);\n\n buf.clear();\n\n while (!resp.complete) {\n buf.reserve(4*1024);\n ssize_t nr = s->recv(buf.back(), buf.available());\n if (nr <= 0) { throw errorx(\"http get error\"); }\n buf.commit(nr);\n size_t len = buf.size();\n resp.parse(&parser, buf.front(), len);\n buf.remove(len);\n }\n \/\/ should not be any data left over in buf\n CHECK(buf.size() == 0);\n\n return resp;\n } catch (errorx &e) {\n s.reset();\n throw;\n }\n }\n\n http_response get(const std::string &path) {\n return perform(\"GET\", path);\n }\n\n http_response post(const std::string &path, const std::string &data) {\n return perform(\"POST\", path, data);\n }\n\n};\n\nclass http_pool : public shared_pool<http_client> {\npublic:\n http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)\n : shared_pool<http_client>(\"http:\/\/\" + host_,\n std::bind(&http_pool::new_resource, this),\n max_conn\n ),\n host(host_), port(port_) {}\n\nprotected:\n std::string host;\n uint16_t port;\n\n std::shared_ptr<http_client> new_resource() {\n VLOG(3) << \"new http_client resource \" << host;\n return std::make_shared<http_client>(host, port);\n }\n};\n\n} \/\/ end namespace ten\n#endif \/\/ HTTP_CLIENT_HH\n\n<commit_msg>max_content_length<commit_after>#ifndef HTTP_CLIENT_HH\n#define HTTP_CLIENT_HH\n\n#include \"http\/http_message.hh\"\n#include \"shared_pool.hh\"\n#include \"buffer.hh\"\n\nnamespace ten {\n\nclass http_client {\nprivate:\n std::shared_ptr<netsock> s;\n buffer buf;\n\n void ensure_connection() {\n if (s && s->valid()) return;\n s.reset(new netsock(AF_INET, SOCK_STREAM));\n if (s->dial(host.c_str(), port) != 0) {\n throw errorx(\"dial %s:%d failed\", host.c_str(), port);\n }\n }\n\npublic:\n const std::string host;\n const uint16_t port;\n size_t max_content_length;\n\n http_client(const std::string &host_, uint16_t port_=80)\n : buf(4*1024), host(host_), port(port_), max_content_length(-1) {}\n\n http_response perform(const std::string &method, const std::string &path, const std::string &data=\"\") {\n try {\n ensure_connection();\n uri u;\n u.scheme = \"http\";\n u.host = host;\n u.port = port;\n u.path = path;\n u.normalize();\n\n http_request r(method, u.compose(true));\n \/\/ HTTP\/1.1 requires host header\n r.append(\"Host\", u.host); \n r.append(\"Content-Length\", data.size());\n\n std::string hdata = r.data();\n ssize_t nw = s->send(hdata.c_str(), hdata.size());\n nw = s->send(data.c_str(), data.size());\n\n http_parser parser;\n http_response resp;\n resp.parser_init(&parser);\n\n buf.clear();\n\n while (!resp.complete) {\n buf.reserve(4*1024);\n ssize_t nr = s->recv(buf.back(), buf.available());\n if (nr <= 0) { throw errorx(\"http get error\"); }\n buf.commit(nr);\n size_t len = buf.size();\n resp.parse(&parser, buf.front(), len);\n buf.remove(len);\n if (resp.body.size() >= max_content_length) {\n s.reset(); \/\/ close this socket, we won't read anymore\n return resp;\n }\n }\n \/\/ should not be any data left over in buf\n CHECK(buf.size() == 0);\n\n return resp;\n } catch (errorx &e) {\n s.reset();\n throw;\n }\n }\n\n http_response get(const std::string &path) {\n return perform(\"GET\", path);\n }\n\n http_response post(const std::string &path, const std::string &data) {\n return perform(\"POST\", path, data);\n }\n\n};\n\nclass http_pool : public shared_pool<http_client> {\npublic:\n http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)\n : shared_pool<http_client>(\"http:\/\/\" + host_,\n std::bind(&http_pool::new_resource, this),\n max_conn\n ),\n host(host_), port(port_) {}\n\nprotected:\n std::string host;\n uint16_t port;\n\n std::shared_ptr<http_client> new_resource() {\n VLOG(3) << \"new http_client resource \" << host;\n return std::make_shared<http_client>(host, port);\n }\n};\n\n} \/\/ end namespace ten\n#endif \/\/ HTTP_CLIENT_HH\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP\n#define TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP\n\n#if !defined( NOMINMAX )\n#define NOMINMAX\n#define TAO_PEGTL_NOMINMAX_WAS_DEFINED\n#endif\n\n#if !defined( WIN32_LEAN_AND_MEAN )\n#define WIN32_LEAN_AND_MEAN\n#define TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED\n#endif\n\n#include <windows.h>\n\n#if defined( TAO_PEGTL_NOMINMAX_WAS_DEFINED )\n#undef NOMINMAX\n#undef TAO_PEGTL_NOMINMAX_WAS_DEFINED\n#endif\n\n#if defined( TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED )\n#undef WIN32_LEAN_AND_MEAN\n#undef TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED\n#endif\n\n#include <system_error>\n\n#include \"..\/config.hpp\"\n\nnamespace tao\n{\n namespace TAO_PEGTL_NAMESPACE\n {\n namespace internal\n {\n struct win32_file_opener\n {\n explicit win32_file_opener( const char* filename )\n : m_source( filename ),\n m_handle( open() )\n {\n }\n\n win32_file_opener( const win32_file_opener& ) = delete;\n win32_file_opener( win32_file_opener&& ) = delete;\n\n ~win32_file_opener() noexcept\n {\n ::CloseHandle( m_handle );\n }\n\n void operator=( const win32_file_opener& ) = delete;\n void operator=( win32_file_opener&& ) = delete;\n\n [[nodiscard]] std::size_t size() const\n {\n LARGE_INTEGER size;\n if( !::GetFileSizeEx( m_handle, &size ) ) {\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"GetFileSizeEx(): \" ) + m_source );\n }\n return std::size_t( size.QuadPart );\n }\n\n const char* const m_source;\n const HANDLE m_handle;\n\n private:\n [[nodiscard]] HANDLE open() const\n {\n SetLastError( 0 );\n std::wstring ws( m_source, m_source + strlen( m_source ) );\n const HANDLE handle = ::CreateFile2( ws.c_str(),\n GENERIC_READ,\n FILE_SHARE_READ,\n OPEN_EXISTING,\n nullptr );\n if( handle != INVALID_HANDLE_VALUE ) {\n return handle;\n }\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"CreateFile2(): \" ) + m_source );\n }\n };\n\n struct win32_file_mapper\n {\n explicit win32_file_mapper( const char* filename )\n : win32_file_mapper( win32_file_opener( filename ) )\n {\n }\n\n explicit win32_file_mapper( const win32_file_opener& reader )\n : m_size( reader.size() ),\n m_handle( open( reader ) )\n {\n }\n\n win32_file_mapper( const win32_file_mapper& ) = delete;\n win32_file_mapper( win32_file_mapper&& ) = delete;\n\n ~win32_file_mapper() noexcept\n {\n ::CloseHandle( m_handle );\n }\n\n void operator=( const win32_file_mapper& ) = delete;\n void operator=( win32_file_mapper&& ) = delete;\n\n const size_t m_size;\n const HANDLE m_handle;\n\n private:\n [[nodiscard]] HANDLE open( const win32_file_opener& reader ) const\n {\n const uint64_t file_size = reader.size();\n SetLastError( 0 );\n \/\/ Use `CreateFileMappingW` because a) we're not specifying a\n \/\/ mapping name, so the character type is of no consequence, and\n \/\/ b) it's defined in `memoryapi.h`, unlike\n \/\/ `CreateFileMappingA`(?!)\n const HANDLE handle = ::CreateFileMappingW( reader.m_handle,\n nullptr,\n PAGE_READONLY,\n DWORD( file_size >> 32 ),\n DWORD( file_size & 0xffffffff ),\n nullptr );\n if( handle != NULL || file_size == 0 ) {\n return handle;\n }\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"CreateFileMappingW(): \" ) + reader.m_source );\n }\n };\n\n class file_mapper\n {\n public:\n explicit file_mapper( const char* filename )\n : file_mapper( win32_file_mapper( filename ) )\n {\n }\n\n explicit file_mapper( const win32_file_mapper& mapper )\n : m_size( mapper.m_size ),\n m_data( static_cast< const char* >( ::MapViewOfFile( mapper.m_handle,\n FILE_MAP_READ,\n 0,\n 0,\n 0 ) ) )\n {\n if( ( m_size != 0 ) && ( intptr_t( m_data ) == 0 ) ) {\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), \"MapViewOfFile()\" );\n }\n }\n\n file_mapper( const file_mapper& ) = delete;\n file_mapper( file_mapper&& ) = delete;\n\n ~file_mapper() noexcept\n {\n ::UnmapViewOfFile( LPCVOID( m_data ) );\n }\n\n void operator=( const file_mapper& ) = delete;\n void operator=( file_mapper&& ) = delete;\n\n [[nodiscard]] bool empty() const noexcept\n {\n return m_size == 0;\n }\n\n [[nodiscard]] std::size_t size() const noexcept\n {\n return m_size;\n }\n\n using iterator = const char*;\n using const_iterator = const char*;\n\n [[nodiscard]] iterator data() const noexcept\n {\n return m_data;\n }\n\n [[nodiscard]] iterator begin() const noexcept\n {\n return m_data;\n }\n\n [[nodiscard]] iterator end() const noexcept\n {\n return m_data + m_size;\n }\n\n private:\n const std::size_t m_size;\n const char* const m_data;\n };\n\n } \/\/ namespace internal\n\n } \/\/ namespace TAO_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\n<commit_msg>Fix #155<commit_after>\/\/ Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP\n#define TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP\n\n#if !defined( NOMINMAX )\n#define NOMINMAX\n#define TAO_PEGTL_NOMINMAX_WAS_DEFINED\n#endif\n\n#if !defined( WIN32_LEAN_AND_MEAN )\n#define WIN32_LEAN_AND_MEAN\n#define TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED\n#endif\n\n#include <windows.h>\n\n#if defined( TAO_PEGTL_NOMINMAX_WAS_DEFINED )\n#undef NOMINMAX\n#undef TAO_PEGTL_NOMINMAX_WAS_DEFINED\n#endif\n\n#if defined( TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED )\n#undef WIN32_LEAN_AND_MEAN\n#undef TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED\n#endif\n\n#include <system_error>\n\n#include \"..\/config.hpp\"\n\nnamespace tao\n{\n namespace TAO_PEGTL_NAMESPACE\n {\n namespace internal\n {\n struct win32_file_opener\n {\n explicit win32_file_opener( const char* filename )\n : m_source( filename ),\n m_handle( open() )\n {\n }\n\n win32_file_opener( const win32_file_opener& ) = delete;\n win32_file_opener( win32_file_opener&& ) = delete;\n\n ~win32_file_opener() noexcept\n {\n ::CloseHandle( m_handle );\n }\n\n void operator=( const win32_file_opener& ) = delete;\n void operator=( win32_file_opener&& ) = delete;\n\n [[nodiscard]] std::size_t size() const\n {\n LARGE_INTEGER size;\n if( !::GetFileSizeEx( m_handle, &size ) ) {\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"GetFileSizeEx(): \" ) + m_source );\n }\n return std::size_t( size.QuadPart );\n }\n\n const char* const m_source;\n const HANDLE m_handle;\n\n private:\n [[nodiscard]] HANDLE open() const\n {\n SetLastError( 0 );\n std::wstring ws( m_source, m_source + strlen( m_source ) );\n\n#if( _WIN32_WINNT >= 0x0602 )\n const HANDLE handle = ::CreateFile2( ws.c_str(),\n GENERIC_READ,\n FILE_SHARE_READ,\n OPEN_EXISTING,\n nullptr );\n#else\n const HANDLE handle = ::CreateFileW( ws.c_str(),\n GENERIC_READ,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n nullptr );\n#endif\n\n if( handle != INVALID_HANDLE_VALUE ) {\n return handle;\n }\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"CreateFile2(): \" ) + m_source );\n }\n };\n\n struct win32_file_mapper\n {\n explicit win32_file_mapper( const char* filename )\n : win32_file_mapper( win32_file_opener( filename ) )\n {\n }\n\n explicit win32_file_mapper( const win32_file_opener& reader )\n : m_size( reader.size() ),\n m_handle( open( reader ) )\n {\n }\n\n win32_file_mapper( const win32_file_mapper& ) = delete;\n win32_file_mapper( win32_file_mapper&& ) = delete;\n\n ~win32_file_mapper() noexcept\n {\n ::CloseHandle( m_handle );\n }\n\n void operator=( const win32_file_mapper& ) = delete;\n void operator=( win32_file_mapper&& ) = delete;\n\n const size_t m_size;\n const HANDLE m_handle;\n\n private:\n [[nodiscard]] HANDLE open( const win32_file_opener& reader ) const\n {\n const uint64_t file_size = reader.size();\n SetLastError( 0 );\n \/\/ Use `CreateFileMappingW` because a) we're not specifying a\n \/\/ mapping name, so the character type is of no consequence, and\n \/\/ b) it's defined in `memoryapi.h`, unlike\n \/\/ `CreateFileMappingA`(?!)\n const HANDLE handle = ::CreateFileMappingW( reader.m_handle,\n nullptr,\n PAGE_READONLY,\n DWORD( file_size >> 32 ),\n DWORD( file_size & 0xffffffff ),\n nullptr );\n if( handle != NULL || file_size == 0 ) {\n return handle;\n }\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), std::string( \"CreateFileMappingW(): \" ) + reader.m_source );\n }\n };\n\n class file_mapper\n {\n public:\n explicit file_mapper( const char* filename )\n : file_mapper( win32_file_mapper( filename ) )\n {\n }\n\n explicit file_mapper( const win32_file_mapper& mapper )\n : m_size( mapper.m_size ),\n m_data( static_cast< const char* >( ::MapViewOfFile( mapper.m_handle,\n FILE_MAP_READ,\n 0,\n 0,\n 0 ) ) )\n {\n if( ( m_size != 0 ) && ( intptr_t( m_data ) == 0 ) ) {\n const auto ec = ::GetLastError();\n throw std::system_error( ec, std::system_category(), \"MapViewOfFile()\" );\n }\n }\n\n file_mapper( const file_mapper& ) = delete;\n file_mapper( file_mapper&& ) = delete;\n\n ~file_mapper() noexcept\n {\n ::UnmapViewOfFile( LPCVOID( m_data ) );\n }\n\n void operator=( const file_mapper& ) = delete;\n void operator=( file_mapper&& ) = delete;\n\n [[nodiscard]] bool empty() const noexcept\n {\n return m_size == 0;\n }\n\n [[nodiscard]] std::size_t size() const noexcept\n {\n return m_size;\n }\n\n using iterator = const char*;\n using const_iterator = const char*;\n\n [[nodiscard]] iterator data() const noexcept\n {\n return m_data;\n }\n\n [[nodiscard]] iterator begin() const noexcept\n {\n return m_data;\n }\n\n [[nodiscard]] iterator end() const noexcept\n {\n return m_data + m_size;\n }\n\n private:\n const std::size_t m_size;\n const char* const m_data;\n };\n\n } \/\/ namespace internal\n\n } \/\/ namespace TAO_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"RectNode.h\"\n\n#include \"NodeDefinition.h\"\n\n#include \"..\/graphics\/VertexArray.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/MathHelper.h\"\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition RectNode::createDefinition()\n{\n return NodeDefinition(\"rect\", Node::buildNode<RectNode>)\n .extendDefinition(VectorNode::createDefinition())\n .addArg(Arg<double>(\"x\", 0, false, offsetof(RectNode, m_Rect.tl.x)))\n .addArg(Arg<double>(\"y\", 0, false, offsetof(RectNode, m_Rect.tl.y)))\n .addArg(Arg<double>(\"width\", 0))\n .addArg(Arg<double>(\"height\", 0))\n .addArg(Arg<double>(\"angle\", 0.0, false, offsetof(RectNode, m_Angle)))\n .addArg(Arg<double>(\"fillopacity\", 0, false, \n offsetof(RectNode, m_FillOpacity)))\n .addArg(Arg<string>(\"fillcolor\", \"FFFFFF\", false, \n offsetof(RectNode, m_sFillColorName)));\n}\n\nRectNode::RectNode(const ArgList& Args, bool bFromXML)\n : VectorNode(Args)\n{\n Args.setMembers(this);\n m_Rect.setWidth(Args.getArgVal<double>(\"width\"));\n m_Rect.setHeight(Args.getArgVal<double>(\"height\"));\n m_FillColor = colorStringToColor(m_sFillColorName);\n}\n\nRectNode::~RectNode()\n{\n}\n\ndouble RectNode::getX() const \n{\n return m_Rect.tl.x;\n}\n\nvoid RectNode::setX(double x) \n{\n double w = m_Rect.width();\n m_Rect.tl.x = x;\n m_Rect.setWidth(w);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getY() const \n{\n return m_Rect.tl.y;\n}\n\nvoid RectNode::setY(double y) \n{\n double h = m_Rect.height();\n m_Rect.tl.y = y;\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\nconst DPoint& RectNode::getPos() const \n{\n return m_Rect.tl;\n}\n\nvoid RectNode::setPos(const DPoint& pt) \n{\n double w = m_Rect.width();\n double h = m_Rect.height();\n m_Rect.tl = pt;\n m_Rect.setHeight(w);\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getWidth() const\n{\n return m_Rect.width();\n}\n\nvoid RectNode::setWidth(double w)\n{\n m_Rect.setWidth(w);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getHeight() const\n{\n return m_Rect.height();\n}\n\nvoid RectNode::setHeight(double h)\n{\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\nDPoint RectNode::getSize() const \n{\n return m_Rect.size();\n}\n\nvoid RectNode::setSize(const DPoint& pt) \n{\n m_Rect.setWidth(pt.x);\n m_Rect.setHeight(pt.y);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getAngle() const\n{\n return m_Angle;\n}\n\nvoid RectNode::setAngle(double angle)\n{\n m_Angle = fmod(angle, 2*PI);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getFillOpacity() const\n{\n return m_FillOpacity;\n}\n\nvoid RectNode::setFillOpacity(double opacity)\n{\n m_FillOpacity = opacity;\n setDrawNeeded(true);\n}\n\nvoid RectNode::setFillColor(const string& sFillColor)\n{\n if (m_sFillColorName != sFillColor) {\n m_sFillColorName = sFillColor;\n m_FillColor = colorStringToColor(m_sFillColorName);\n setDrawNeeded(true);\n }\n}\n\nconst string& RectNode::getFillColor() const\n{\n return m_sFillColorName;\n}\n\nint RectNode::getNumVertexes()\n{\n return 4*5;\n}\n\nint RectNode::getNumIndexes()\n{\n return 6*5;\n}\n\nvoid RectNode::updateData(VertexArrayPtr& pVertexArray, int curVertex, int curIndex, \n double opacity, bool bParentDrawNeeded)\n{\n if (isDrawNeeded() || bParentDrawNeeded) {\n double curOpacity = opacity*m_FillOpacity;\n Pixel32 color = m_FillColor;\n color.setA((unsigned char)(curOpacity*255));\n\n DPoint pivot = m_Rect.tl+m_Rect.size()\/2;\n\n DPoint p1 = m_Rect.tl;\n DPoint p2(m_Rect.tl.x, m_Rect.br.y);\n DPoint p3 = m_Rect.br;\n DPoint p4(m_Rect.br.x, m_Rect.tl.y);\n DPoint rp1 = rotate(p1, m_Angle, pivot); \n DPoint rp2 = rotate(p2, m_Angle, pivot); \n DPoint rp3 = rotate(p3, m_Angle, pivot); \n DPoint rp4 = rotate(p4, m_Angle, pivot); \n pVertexArray->setPos(curVertex, rp1, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+1, rp2, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+2, rp3, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+3, rp4, DPoint(0,0), color);\n pVertexArray->setIndex(curIndex, curVertex);\n pVertexArray->setIndex(curIndex+1, curVertex+1);\n pVertexArray->setIndex(curIndex+2, curVertex+2);\n pVertexArray->setIndex(curIndex+3, curVertex);\n pVertexArray->setIndex(curIndex+4, curVertex+2);\n pVertexArray->setIndex(curIndex+5, curVertex+3);\n\n updateLineData(pVertexArray, curVertex+4, curIndex+6, opacity, rp1, rp2);\n updateLineData(pVertexArray, curVertex+8, curIndex+12, opacity, rp3, rp4);\n p1.x -= getStrokeWidth()\/2;\n p2.x -= getStrokeWidth()\/2;\n p3.x += getStrokeWidth()\/2;\n p4.x += getStrokeWidth()\/2;\n rp1 = rotate(p1, m_Angle, pivot); \n rp2 = rotate(p2, m_Angle, pivot); \n rp3 = rotate(p3, m_Angle, pivot); \n rp4 = rotate(p4, m_Angle, pivot); \n updateLineData(pVertexArray, curVertex+12, curIndex+18, opacity, rp2, rp3);\n updateLineData(pVertexArray, curVertex+16, curIndex+24, opacity, rp4, rp1);\n }\n setDrawNeeded(false);\n}\n\n}\n<commit_msg>bugfix: rectnode setPos()<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"RectNode.h\"\n\n#include \"NodeDefinition.h\"\n\n#include \"..\/graphics\/VertexArray.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/MathHelper.h\"\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition RectNode::createDefinition()\n{\n return NodeDefinition(\"rect\", Node::buildNode<RectNode>)\n .extendDefinition(VectorNode::createDefinition())\n .addArg(Arg<double>(\"x\", 0, false, offsetof(RectNode, m_Rect.tl.x)))\n .addArg(Arg<double>(\"y\", 0, false, offsetof(RectNode, m_Rect.tl.y)))\n .addArg(Arg<double>(\"width\", 0))\n .addArg(Arg<double>(\"height\", 0))\n .addArg(Arg<double>(\"angle\", 0.0, false, offsetof(RectNode, m_Angle)))\n .addArg(Arg<double>(\"fillopacity\", 0, false, \n offsetof(RectNode, m_FillOpacity)))\n .addArg(Arg<string>(\"fillcolor\", \"FFFFFF\", false, \n offsetof(RectNode, m_sFillColorName)));\n}\n\nRectNode::RectNode(const ArgList& Args, bool bFromXML)\n : VectorNode(Args)\n{\n Args.setMembers(this);\n m_Rect.setWidth(Args.getArgVal<double>(\"width\"));\n m_Rect.setHeight(Args.getArgVal<double>(\"height\"));\n m_FillColor = colorStringToColor(m_sFillColorName);\n}\n\nRectNode::~RectNode()\n{\n}\n\ndouble RectNode::getX() const \n{\n return m_Rect.tl.x;\n}\n\nvoid RectNode::setX(double x) \n{\n double w = m_Rect.width();\n m_Rect.tl.x = x;\n m_Rect.setWidth(w);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getY() const \n{\n return m_Rect.tl.y;\n}\n\nvoid RectNode::setY(double y) \n{\n double h = m_Rect.height();\n m_Rect.tl.y = y;\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\nconst DPoint& RectNode::getPos() const \n{\n return m_Rect.tl;\n}\n\nvoid RectNode::setPos(const DPoint& pt) \n{\n double w = m_Rect.width();\n double h = m_Rect.height();\n m_Rect.tl = pt;\n m_Rect.setWidth(w);\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getWidth() const\n{\n return m_Rect.width();\n}\n\nvoid RectNode::setWidth(double w)\n{\n m_Rect.setWidth(w);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getHeight() const\n{\n return m_Rect.height();\n}\n\nvoid RectNode::setHeight(double h)\n{\n m_Rect.setHeight(h);\n setDrawNeeded(true);\n}\n\nDPoint RectNode::getSize() const \n{\n return m_Rect.size();\n}\n\nvoid RectNode::setSize(const DPoint& pt) \n{\n m_Rect.setWidth(pt.x);\n m_Rect.setHeight(pt.y);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getAngle() const\n{\n return m_Angle;\n}\n\nvoid RectNode::setAngle(double angle)\n{\n m_Angle = fmod(angle, 2*PI);\n setDrawNeeded(true);\n}\n\ndouble RectNode::getFillOpacity() const\n{\n return m_FillOpacity;\n}\n\nvoid RectNode::setFillOpacity(double opacity)\n{\n m_FillOpacity = opacity;\n setDrawNeeded(true);\n}\n\nvoid RectNode::setFillColor(const string& sFillColor)\n{\n if (m_sFillColorName != sFillColor) {\n m_sFillColorName = sFillColor;\n m_FillColor = colorStringToColor(m_sFillColorName);\n setDrawNeeded(true);\n }\n}\n\nconst string& RectNode::getFillColor() const\n{\n return m_sFillColorName;\n}\n\nint RectNode::getNumVertexes()\n{\n return 4*5;\n}\n\nint RectNode::getNumIndexes()\n{\n return 6*5;\n}\n\nvoid RectNode::updateData(VertexArrayPtr& pVertexArray, int curVertex, int curIndex, \n double opacity, bool bParentDrawNeeded)\n{\n if (isDrawNeeded() || bParentDrawNeeded) {\n double curOpacity = opacity*m_FillOpacity;\n Pixel32 color = m_FillColor;\n color.setA((unsigned char)(curOpacity*255));\n\n DPoint pivot = m_Rect.tl+m_Rect.size()\/2;\n\n DPoint p1 = m_Rect.tl;\n DPoint p2(m_Rect.tl.x, m_Rect.br.y);\n DPoint p3 = m_Rect.br;\n DPoint p4(m_Rect.br.x, m_Rect.tl.y);\n DPoint rp1 = rotate(p1, m_Angle, pivot); \n DPoint rp2 = rotate(p2, m_Angle, pivot); \n DPoint rp3 = rotate(p3, m_Angle, pivot); \n DPoint rp4 = rotate(p4, m_Angle, pivot); \n pVertexArray->setPos(curVertex, rp1, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+1, rp2, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+2, rp3, DPoint(0,0), color);\n pVertexArray->setPos(curVertex+3, rp4, DPoint(0,0), color);\n pVertexArray->setIndex(curIndex, curVertex);\n pVertexArray->setIndex(curIndex+1, curVertex+1);\n pVertexArray->setIndex(curIndex+2, curVertex+2);\n pVertexArray->setIndex(curIndex+3, curVertex);\n pVertexArray->setIndex(curIndex+4, curVertex+2);\n pVertexArray->setIndex(curIndex+5, curVertex+3);\n\n updateLineData(pVertexArray, curVertex+4, curIndex+6, opacity, rp1, rp2);\n updateLineData(pVertexArray, curVertex+8, curIndex+12, opacity, rp3, rp4);\n p1.x -= getStrokeWidth()\/2;\n p2.x -= getStrokeWidth()\/2;\n p3.x += getStrokeWidth()\/2;\n p4.x += getStrokeWidth()\/2;\n rp1 = rotate(p1, m_Angle, pivot); \n rp2 = rotate(p2, m_Angle, pivot); \n rp3 = rotate(p3, m_Angle, pivot); \n rp4 = rotate(p4, m_Angle, pivot); \n updateLineData(pVertexArray, curVertex+12, curIndex+18, opacity, rp2, rp3);\n updateLineData(pVertexArray, curVertex+16, curIndex+24, opacity, rp4, rp1);\n }\n setDrawNeeded(false);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n \\copyright (c) RDO-Team, 2012\r\n \\file simulator\/compiler\/parser\/rdo_logic_base.cpp\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\authors (impus@hotbox.ru)\r\n \\date 5.02.2012\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n#include \"simulator\/compiler\/parser\/pch.h\"\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/compiler\/parser\/rdoparser.h\"\r\n#include \"simulator\/compiler\/parser\/rdo_logic_base.h\"\r\n#include \"simulator\/runtime\/rdo_priority.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nOPEN_RDO_PARSER_NAMESPACE\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------------------- RDOLogicBase\r\n\/\/ --------------------------------------------------------------------------------\r\nRDOLogicBase::RDOLogicBase(CREF(RDOParserSrcInfo) src_info)\r\n\t: RDOParserSrcInfo(src_info)\r\n{}\r\n\r\nRDOLogicBase::~RDOLogicBase()\r\n{}\r\n\r\nCREF(tstring) RDOLogicBase::name() const\r\n{\r\n\treturn src_info().src_text();\r\n}\r\n\r\nrbool RDOLogicBase::setPrior(REF(LPRDOFUNArithm) pPrior)\r\n{\r\n\tLPIPriority pPriority = m_pRuntimeLogic;\r\n\tif (pPriority)\r\n\t{\r\n\t\treturn pPriority->setPrior(pPrior->createCalc());\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nrbool RDOLogicBase::getMultithreading() const\r\n{\r\n\treturn m_multithreading;\r\n}\r\n\r\nvoid RDOLogicBase::setMultithreading(rbool multithreading)\r\n{\r\n\tm_multithreading = multithreading;\r\n}\r\n\r\nvoid RDOLogicBase::setCondition(CREF(LPRDOFUNLogic) pConditon)\r\n{\r\n\tm_pConditon = pConditon;\r\n}\r\n\r\nLPRDOFUNLogic RDOLogicBase::getConditon() const\r\n{\r\n\treturn m_pConditon;\r\n}\r\n\r\nLPILogic RDOLogicBase::getLogic() const\r\n{\r\n\treturn m_pRuntimeLogic;\r\n}\r\n\r\nvoid RDOLogicBase::end()\r\n{\r\n\tif (getConditon())\r\n\t{\r\n\t\tm_pRuntimeLogic->setCondition(getConditon()->getCalc());\r\n\t}\r\n\tm_pRuntimeLogic->setMultithreading(m_multithreading);\r\n\tRDOParser::s_parser()->contextStack()->pop();\r\n}\r\n\r\nCLOSE_RDO_PARSER_NAMESPACE\r\n<commit_msg> - добавлена инициализация<commit_after>\/*!\r\n \\copyright (c) RDO-Team, 2012\r\n \\file simulator\/compiler\/parser\/rdo_logic_base.cpp\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\authors (impus@hotbox.ru)\r\n \\date 5.02.2012\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n#include \"simulator\/compiler\/parser\/pch.h\"\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/compiler\/parser\/rdoparser.h\"\r\n#include \"simulator\/compiler\/parser\/rdo_logic_base.h\"\r\n#include \"simulator\/runtime\/rdo_priority.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nOPEN_RDO_PARSER_NAMESPACE\r\n\r\n\/\/ --------------------------------------------------------------------------------\r\n\/\/ -------------------- RDOLogicBase\r\n\/\/ --------------------------------------------------------------------------------\r\nRDOLogicBase::RDOLogicBase(CREF(RDOParserSrcInfo) src_info)\r\n\t: RDOParserSrcInfo(src_info)\r\n\t, m_multithreading(false )\r\n{}\r\n\r\nRDOLogicBase::~RDOLogicBase()\r\n{}\r\n\r\nCREF(tstring) RDOLogicBase::name() const\r\n{\r\n\treturn src_info().src_text();\r\n}\r\n\r\nrbool RDOLogicBase::setPrior(REF(LPRDOFUNArithm) pPrior)\r\n{\r\n\tLPIPriority pPriority = m_pRuntimeLogic;\r\n\tif (pPriority)\r\n\t{\r\n\t\treturn pPriority->setPrior(pPrior->createCalc());\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nrbool RDOLogicBase::getMultithreading() const\r\n{\r\n\treturn m_multithreading;\r\n}\r\n\r\nvoid RDOLogicBase::setMultithreading(rbool multithreading)\r\n{\r\n\tm_multithreading = multithreading;\r\n}\r\n\r\nvoid RDOLogicBase::setCondition(CREF(LPRDOFUNLogic) pConditon)\r\n{\r\n\tm_pConditon = pConditon;\r\n}\r\n\r\nLPRDOFUNLogic RDOLogicBase::getConditon() const\r\n{\r\n\treturn m_pConditon;\r\n}\r\n\r\nLPILogic RDOLogicBase::getLogic() const\r\n{\r\n\treturn m_pRuntimeLogic;\r\n}\r\n\r\nvoid RDOLogicBase::end()\r\n{\r\n\tif (getConditon())\r\n\t{\r\n\t\tm_pRuntimeLogic->setCondition(getConditon()->getCalc());\r\n\t}\r\n\tm_pRuntimeLogic->setMultithreading(m_multithreading);\r\n\tRDOParser::s_parser()->contextStack()->pop();\r\n}\r\n\r\nCLOSE_RDO_PARSER_NAMESPACE\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Rüdiger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/class.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include <gmpxx.h>\n\nusing namespace flusspferd;\n\nnamespace {\n\nnamespace multi_precission {\nstruct Integer : public flusspferd::native_object_base {\n struct class_info : flusspferd::class_info {\n static char const *constructor_name() {\n return \"Integer\";\n }\n\n static char const *full_name() {\n return \"Integer\";\n }\n\n static object create_prototype() {\n flusspferd::object proto = flusspferd::create_object();\n create_native_method(proto, \"fits_int\", &Integer::fits_int);\n create_native_method(proto, \"get_int\", &Integer::get_int);\n create_native_method(proto, \"get_double\", &Integer::get_double);\n create_native_method(proto, \"get_string\", &Integer::get_string);\n create_native_method(proto, \"get_string_base\", &Integer::get_string_base);\n create_native_method(proto, \"sqrt\", &Integer::sqrt);\n create_native_method(proto, \"sgn\", &Integer::sgn);\n create_native_method(proto, \"abs\", &Integer::abs);\n return proto;\n }\n };\n mpz_class mp;\n\n Integer(flusspferd::object const &self, mpz_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n Integer(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n if(x.arg.size() == 1) {\n value v = x.arg.front();\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else\n mp = flusspferd::get_native<Integer>(v.get_object()).mp;\n }\n else if(x.arg.size() == 2) {\n value v = x.arg.front();\n value u = x.arg.back();\n if(v.is_string() && u.is_int())\n mp.set_str(v.to_std_string(), u.get_int());\n else\n throw flusspferd::exception(\"Wrong arguments! (string, int) expected.\");\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments!\");\n }\n\n bool fits_int() \/*const*\/ {\n return mp.fits_sint_p();\n }\n int get_int() \/*const*\/ {\n assert(fits_int());\n return mp.get_si();\n }\n double get_double() \/*const*\/ {\n return mp.get_d();\n }\n std::string get_string() \/*const*\/ {\n return mp.get_str();\n }\n std::string get_string_base(int base) \/*const*\/ {\n return mp.get_str(base);\n }\n\n template<typename T>\n Integer &create_integer(T mp) \/*const*\/ {\n return create_native_object<Integer>(object(), mpz_class(mp));\n }\n\n \/\/ this should be external but js doesn't support overloading!\n Integer &sqrt() \/*const*\/ {\n return create_integer(::sqrt(mp));\n }\n\n int sgn() \/*const*\/ {\n return ::sgn(mp);\n }\n\n Integer &abs() \/*const*\/ {\n return create_integer(::abs(mp));\n }\n};\n\n\nstruct Float : public flusspferd::native_object_base {\n struct class_info : flusspferd::class_info {\n static char const *constructor_name() {\n return \"Float\";\n }\n\n static char const *full_name() {\n return \"Float\";\n }\n\n static object create_prototype() {\n flusspferd::object proto = flusspferd::create_object();\n create_native_method(proto, \"fits_int\", &Float::fits_int);\n create_native_method(proto, \"get_int\", &Float::get_int);\n create_native_method(proto, \"get_double\", &Float::get_double);\n create_native_method(proto, \"get_string\", &Float::get_string);\n create_native_method(proto, \"get_string_base\", &Float::get_string_base);\n create_native_method(proto, \"get_prec\", &Float::get_prec);\n create_native_method(proto, \"set_prec\", &Float::set_prec);\n create_native_method(proto, \"sqrt\", &Float::sqrt);\n create_native_method(proto, \"sgn\", &Float::sgn);\n create_native_method(proto, \"abs\", &Float::abs);\n create_native_method(proto, \"ceil\", &Float::ceil);\n create_native_method(proto, \"floor\", &Float::floor);\n create_native_method(proto, \"trunc\", &Float::trunc);\n create_native_method(proto, \"cmp\", &Float::cmp);\n create_native_method(proto, \"add\", &Float::add);\n create_native_method(proto, \"sub\", &Float::sub);\n create_native_method(proto, \"mul\", &Float::mul);\n create_native_method(proto, \"div\", &Float::div);\n return proto;\n }\n };\n mpf_class mp;\n\n Float(flusspferd::object const &self, mpf_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n void init_with_value(value v) {\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else\n mp = flusspferd::get_native<Float>(v.get_object()).mp;\n }\n\n Float(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n if(x.arg.size() == 1) {\n init_with_value(x.arg.front());\n }\n else if(x.arg.size() == 2) {\n value v = x.arg.front();\n value u = x.arg.back();\n if(v.is_string() && u.is_int())\n mp.set_str(v.to_std_string(), u.get_int());\n else {\n mp.set_prec(u.get_int());\n init_with_value(v);\n }\n }\n else if(x.arg.size() == 3) {\n value v = x.arg[0];\n value u = x.arg[1];\n value w = x.arg[2];\n if(v.is_string() && u.is_int() && w.is_int()) {\n mp.set_prec(u.get_int());\n mp.set_str(v.to_std_string(), w.get_int());\n }\n else\n throw flusspferd::exception(\"Wrong arguments! (string, int, int) expected.\");\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments!\");\n }\n\n bool fits_int() \/*const*\/ {\n return mp.fits_sint_p();\n }\n int get_int() \/*const*\/ {\n assert(fits_int());\n return mp.get_si();\n }\n double get_double() \/*const*\/ {\n return mp.get_d();\n }\n std::string get_string() \/*const*\/ {\n mp_exp_t expo; \/\/ TODO handle expo\n return mp.get_str(expo);\n }\n std::string get_string_base(int base) \/*const*\/ {\n mp_exp_t expo; \/\/ TODO handle expo\n return mp.get_str(expo, base);\n }\n int get_prec() \/*const*\/ {\n return mp.get_prec();\n }\n void set_prec(int p) {\n mp.set_prec(p);\n }\n\n template<typename T>\n Float &create_float(T mp) \/*const*\/ {\n return create_native_object<Float>(object(), mpf_class(mp));\n }\n\n \/\/ this should be external but js doesn't support overloading!\n Float &sqrt() \/*const*\/ {\n return create_float(::sqrt(mp));\n }\n\n int sgn() \/*const*\/ {\n return ::sgn(mp);\n }\n\n Float &abs() \/*const*\/ {\n return create_float(::abs(mp));\n }\n\n Float &ceil() \/*const*\/ {\n return create_float(::ceil(mp));\n }\n\n Float &floor() \/*const*\/ {\n return create_float(::floor(mp));\n }\n\n \/\/ hypot\n\n Float &trunc() \/*const*\/ {\n return create_float(::trunc(mp));\n }\n\n \/\/ operators\n void cmp(flusspferd::call_context &x) {\n if(x.arg.empty() || x.arg.size() > 1)\n throw flusspferd::exception(\"Expected one parameter!\");\n value v = x.arg.front();\n if(v.is_int())\n x.result = ::cmp(v.get_int(), mp);\n else if(v.is_double())\n x.result = ::cmp(v.get_double(), mp);\n else\n x.result = ::cmp(flusspferd::get_native<Float>(v.get_object()).mp, mp);\n }\n\n Float &add(Float const &f) { \/\/ TODO Integer\n return create_float(mp + f.mp);\n }\n\n Float &sub(Float const &f) { \/\/ TODO Integer\n return create_float(mp - f.mp);\n }\n\n Float &mul(Float const &f) { \/\/ TODO Integer\n return create_float(mp * f.mp);\n }\n\n Float &div(Float const &f) { \/\/ TODO Integer\n return create_float(mp \/ f.mp);\n }\n};\n}\n\n}\/*namespace*\/\n\nFLUSSPFERD_LOADER(gmp) {\n load_class<multi_precission::Integer>(gmp);\n \/\/ TODO Rational\n load_class<multi_precission::Float>(gmp);\n}\n<commit_msg>plugins.gmp: fixed cmp<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Rüdiger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/class.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include <gmpxx.h>\n\nusing namespace flusspferd;\n\nnamespace {\n\nnamespace multi_precission {\nstruct Integer : public flusspferd::native_object_base {\n struct class_info : flusspferd::class_info {\n static char const *constructor_name() {\n return \"Integer\";\n }\n\n static char const *full_name() {\n return \"Integer\";\n }\n\n static object create_prototype() {\n flusspferd::object proto = flusspferd::create_object();\n create_native_method(proto, \"fits_int\", &Integer::fits_int);\n create_native_method(proto, \"get_int\", &Integer::get_int);\n create_native_method(proto, \"get_double\", &Integer::get_double);\n create_native_method(proto, \"get_string\", &Integer::get_string);\n create_native_method(proto, \"get_string_base\", &Integer::get_string_base);\n create_native_method(proto, \"sqrt\", &Integer::sqrt);\n create_native_method(proto, \"sgn\", &Integer::sgn);\n create_native_method(proto, \"abs\", &Integer::abs);\n return proto;\n }\n };\n mpz_class mp;\n\n Integer(flusspferd::object const &self, mpz_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n Integer(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n if(x.arg.size() == 1) {\n value v = x.arg.front();\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else\n mp = flusspferd::get_native<Integer>(v.get_object()).mp;\n }\n else if(x.arg.size() == 2) {\n value v = x.arg.front();\n value u = x.arg.back();\n if(v.is_string() && u.is_int())\n mp.set_str(v.to_std_string(), u.get_int());\n else\n throw flusspferd::exception(\"Wrong arguments! (string, int) expected.\");\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments!\");\n }\n\n bool fits_int() \/*const*\/ {\n return mp.fits_sint_p();\n }\n int get_int() \/*const*\/ {\n assert(fits_int());\n return mp.get_si();\n }\n double get_double() \/*const*\/ {\n return mp.get_d();\n }\n std::string get_string() \/*const*\/ {\n return mp.get_str();\n }\n std::string get_string_base(int base) \/*const*\/ {\n return mp.get_str(base);\n }\n\n template<typename T>\n Integer &create_integer(T mp) \/*const*\/ {\n return create_native_object<Integer>(object(), mpz_class(mp));\n }\n\n \/\/ this should be external but js doesn't support overloading!\n Integer &sqrt() \/*const*\/ {\n return create_integer(::sqrt(mp));\n }\n\n int sgn() \/*const*\/ {\n return ::sgn(mp);\n }\n\n Integer &abs() \/*const*\/ {\n return create_integer(::abs(mp));\n }\n};\n\n\nstruct Float : public flusspferd::native_object_base {\n struct class_info : flusspferd::class_info {\n static char const *constructor_name() {\n return \"Float\";\n }\n\n static char const *full_name() {\n return \"Float\";\n }\n\n static object create_prototype() {\n flusspferd::object proto = flusspferd::create_object();\n create_native_method(proto, \"fits_int\", &Float::fits_int);\n create_native_method(proto, \"get_int\", &Float::get_int);\n create_native_method(proto, \"get_double\", &Float::get_double);\n create_native_method(proto, \"get_string\", &Float::get_string);\n create_native_method(proto, \"get_string_base\", &Float::get_string_base);\n create_native_method(proto, \"get_prec\", &Float::get_prec);\n create_native_method(proto, \"set_prec\", &Float::set_prec);\n create_native_method(proto, \"sqrt\", &Float::sqrt);\n create_native_method(proto, \"sgn\", &Float::sgn);\n create_native_method(proto, \"abs\", &Float::abs);\n create_native_method(proto, \"ceil\", &Float::ceil);\n create_native_method(proto, \"floor\", &Float::floor);\n create_native_method(proto, \"trunc\", &Float::trunc);\n create_native_method(proto, \"cmp\", &Float::cmp);\n create_native_method(proto, \"add\", &Float::add);\n create_native_method(proto, \"sub\", &Float::sub);\n create_native_method(proto, \"mul\", &Float::mul);\n create_native_method(proto, \"div\", &Float::div);\n return proto;\n }\n };\n mpf_class mp;\n\n Float(flusspferd::object const &self, mpf_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n void init_with_value(value v) {\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else\n mp = flusspferd::get_native<Float>(v.get_object()).mp;\n }\n\n Float(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n if(x.arg.size() == 1) {\n init_with_value(x.arg.front());\n }\n else if(x.arg.size() == 2) {\n value v = x.arg.front();\n value u = x.arg.back();\n if(v.is_string() && u.is_int())\n mp.set_str(v.to_std_string(), u.get_int());\n else {\n mp.set_prec(u.get_int());\n init_with_value(v);\n }\n }\n else if(x.arg.size() == 3) {\n value v = x.arg[0];\n value u = x.arg[1];\n value w = x.arg[2];\n if(v.is_string() && u.is_int() && w.is_int()) {\n mp.set_prec(u.get_int());\n mp.set_str(v.to_std_string(), w.get_int());\n }\n else\n throw flusspferd::exception(\"Wrong arguments! (string, int, int) expected.\");\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments!\");\n }\n\n bool fits_int() \/*const*\/ {\n return mp.fits_sint_p();\n }\n int get_int() \/*const*\/ {\n assert(fits_int());\n return mp.get_si();\n }\n double get_double() \/*const*\/ {\n return mp.get_d();\n }\n std::string get_string() \/*const*\/ {\n mp_exp_t expo; \/\/ TODO handle expo\n return mp.get_str(expo);\n }\n std::string get_string_base(int base) \/*const*\/ {\n mp_exp_t expo; \/\/ TODO handle expo\n return mp.get_str(expo, base);\n }\n int get_prec() \/*const*\/ {\n return mp.get_prec();\n }\n void set_prec(int p) {\n mp.set_prec(p);\n }\n\n template<typename T>\n Float &create_float(T mp) \/*const*\/ {\n return create_native_object<Float>(object(), mpf_class(mp));\n }\n\n \/\/ this should be external but js doesn't support overloading!\n Float &sqrt() \/*const*\/ {\n return create_float(::sqrt(mp));\n }\n\n int sgn() \/*const*\/ {\n return ::sgn(mp);\n }\n\n Float &abs() \/*const*\/ {\n return create_float(::abs(mp));\n }\n\n Float &ceil() \/*const*\/ {\n return create_float(::ceil(mp));\n }\n\n Float &floor() \/*const*\/ {\n return create_float(::floor(mp));\n }\n\n \/\/ hypot\n\n Float &trunc() \/*const*\/ {\n return create_float(::trunc(mp));\n }\n\n \/\/ operators\n void cmp(flusspferd::call_context &x) {\n if(x.arg.empty() || x.arg.size() > 1)\n throw flusspferd::exception(\"Expected one parameter!\");\n value v = x.arg.front();\n if(v.is_int())\n x.result = ::cmp(mp, v.get_int());\n else if(v.is_double())\n x.result = ::cmp(mp, v.get_double());\n else\n x.result = ::cmp(mp, flusspferd::get_native<Float>(v.get_object()).mp);\n }\n\n Float &add(Float const &f) { \/\/ TODO Integer\n return create_float(mp + f.mp);\n }\n\n Float &sub(Float const &f) { \/\/ TODO Integer\n return create_float(mp - f.mp);\n }\n\n Float &mul(Float const &f) { \/\/ TODO Integer\n return create_float(mp * f.mp);\n }\n\n Float &div(Float const &f) { \/\/ TODO Integer\n return create_float(mp \/ f.mp);\n }\n};\n}\n\n}\/*namespace*\/\n\nFLUSSPFERD_LOADER(gmp) {\n load_class<multi_precission::Integer>(gmp);\n \/\/ TODO Rational\n load_class<multi_precission::Float>(gmp);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file server.cpp\n * @author Shae Bolt, CS3800 Section A\n * @author Jordan Giacone, CS3800 Section B\n * @date Apr 25, 2016\n * @brief Description: The server file to handle multiple\n * clients sending messages to one another\n * @details Details:\n *\/\n\n#include <string.h>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <pthread.h>\n#include <signal.h>\n\n\/\/server port\n#define SERVER_PORT 9993\n\/\/max number of clients\n#define MAX_CLIENT 100\n\n\/\/handles clients on a per client basis and is responsible for sending messages out to all clients\n\/\/these threads are removed if a client disconnects or the server is shutdown\nvoid *client_messenger(void* arg);\n\n\/\/handles signal processing for cntrlc which closes the entire server given a message\nvoid cntrlc_signal_handle(int signal);\n\n\/\/mutex for stop variable\npthread_mutex_t stop_lock;\n\/\/mutex for file descriptor array\npthread_mutex_t file_descriptor_lock;\n\/\/stop variable to end the server\nbool stop = false;\n\/\/stream_socket = socket,\n\/\/temp_fd = temporaray file descriptor\n\/\/k = temporary size variable for write and\n\/\/reads for the amount written\nint stream_socket, temp_fd, k;\n\/\/server address\nstruct sockaddr_in server_addr;\n\/\/client address\nstruct sockaddr_in client_addr;\n\/\/client length\nunsigned int client_len;\n\/\/host pointer\nchar *host;\n\/\/file descriptor arrays for client connections\nint file_descriptor_array[MAX_CLIENT]; \/* allocate as many file descriptors\n as the number of clients *\/\npthread_t client_handlers[100];\n\/\/counter for the number of current connections\nint counter;\n\nint main()\n{\n \/\/signals cntrlc quit\n signal(SIGINT, cntrlc_signal_handle);\n server_addr =\n { AF_INET, htons( SERVER_PORT)};\n client_addr =\n { AF_INET};\n client_len = sizeof(client_addr);\n\n counter = 0;\n\n \/* create a stream socket *\/\n if ((stream_socket = socket( AF_INET, SOCK_STREAM, 0)) == -1)\n {\n perror(\"server: socket failed\");\n exit(1);\n }\n int enable = 1;\n \/* setting socket to be resuable incase of previous runt *\/\n if (setsockopt(stream_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int))\n < 0)\n {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n\n \/* bind the socket to an internet port *\/\n if (bind(stream_socket, (struct sockaddr*) &server_addr, sizeof(server_addr))\n == -1)\n {\n perror(\"server: bind failed\");\n exit(1);\n }\n\n \/\/listening for the server\n if (listen(stream_socket, 10) == -1)\n {\n perror(\"server: listen failed\");\n exit(1);\n }\n \/\/checking for client connections to accept\n printf(\"SERVER is listening for clients to establish a connection\\n\");\n while (((temp_fd = accept(stream_socket, (struct sockaddr*) &client_addr,\n &client_len)) > 0) && !stop)\n {\n pthread_mutex_lock(&file_descriptor_lock);\n if (counter < MAX_CLIENT)\n {\n file_descriptor_array[counter] = temp_fd;\n pthread_create(&client_handlers[counter], NULL, client_messenger,\n (void*) &file_descriptor_array[counter]);\n pthread_mutex_unlock(&file_descriptor_lock);\n counter++;\n }\n else\n {\n std::cerr << \"Error too many threads\" << std::endl;\n }\n }\n\n close(stream_socket);\n unlink((const char*) &server_addr.sin_addr);\n\n return (0);\n}\n\nvoid cntrlc_signal_handle(int signal)\n{\n std::cout << \"\\nCNTRLC detected\" << std::endl;\n\n char message_buffer[512] =\n \"WARNING: The server will shut down in 10 seconds\\n\";\n char quit_msg[32] = \"\/quit\";\n for (int i = 0; i < counter; i++)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n\n }\n for (int i = 0; i < counter; i++)\n {\n\n write(file_descriptor_array[i], quit_msg, sizeof(quit_msg));\n }\n sleep(10);\n pthread_mutex_lock(&stop_lock);\n stop = true;\n pthread_mutex_unlock(&stop_lock);\n\n for (int i = 0; i < counter; i++)\n {\n\n pthread_cancel(client_handlers[i]);\n\n }\n close(stream_socket);\n unlink((const char*) &server_addr.sin_addr);\n\n}\n\nvoid *client_messenger(void* arg) \/* what does 'bob' do ? *\/\n{\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);\n printf(\n \"Child accept() successful.. a client has connected to child ! waiting for a message\\n\");\n \/\/buffer for read in messages\n char buf[512];\n \/\/this is FD, fd, or file descriptor\n int some_fd = *(int*) arg;\n\n char host_name[100];\n gethostname(host_name, 100);\n char client_name[512];\n char message_buffer[100 + 512];\n char server_message[100];\n\n while ((k = read(some_fd, buf, sizeof(buf))) != 0)\n {\n strcpy(message_buffer, \"User \");\n strcpy(client_name, buf);\n strncat(message_buffer, client_name, 512);\n strncat(message_buffer, \" has joined the channel\\n\", 3);\n \/\/printf(\"GIVEN MESSAGE: %s\\n\", buf);\n\n pthread_mutex_lock(&file_descriptor_lock);\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n pthread_mutex_unlock(&file_descriptor_lock);\n break;\n }\n while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop)\n {\n bzero(message_buffer, 512 + 100);\n printf(\"SERVER RECEIVED: %s\\n\", buf);\n if (strcmp(buf, \"\/quit\") == 0)\n {\n break;\n }\n\n strcpy(message_buffer, \">> \");\n strncat(message_buffer, client_name, sizeof(client_name));\n strncat(message_buffer, \": \", 8);\n strncat(message_buffer, buf, 512);\n strncat(message_buffer, \"\\n\", 3);\n\n pthread_mutex_lock(&file_descriptor_lock);\n\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n\n pthread_mutex_unlock(&file_descriptor_lock);\n pthread_yield();\n }\n\n pthread_mutex_lock(&file_descriptor_lock);\n bzero(message_buffer, 512 + 100);\n strcpy(message_buffer, \"User \");\n strncat(message_buffer, client_name, sizeof(client_name));\n strncat(message_buffer, \" has disconnected.\", 24);\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n int i = 0;\n while ((file_descriptor_array[i] != some_fd))\n {\n i++;\n }\n counter--;\n for (int j = i; j < counter; j++)\n {\n file_descriptor_array[j] = file_descriptor_array[j - 1];\n }\n pthread_mutex_unlock(&file_descriptor_lock);\n close(some_fd);\n std::cout << \"\\n EXITING THREAD\" << std::endl;\n pthread_exit(0);\n}\n<commit_msg>asdfa<commit_after>\/**\n * @file server.cpp\n * @author Shae Bolt, CS3800 Section A\n * @author Jordan Giacone, CS3800 Section B\n * @date Apr 25, 2016\n * @brief Description: The server file to handle multiple\n * clients sending messages to one another\n * @details Details:\n *\/\n\n#include <string.h>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <pthread.h>\n#include <signal.h>\n\n\/\/server port\n#define SERVER_PORT 9993\n\/\/max number of clients\n#define MAX_CLIENT 100\n\n\/\/handles clients on a per client basis and is responsible for sending messages out to all clients\n\/\/these threads are removed if a client disconnects or the server is shutdown\nvoid *client_messenger(void* arg);\n\n\/\/handles signal processing for cntrlc which closes the entire server given a message\nvoid cntrlc_signal_handle(int signal);\n\n\/\/mutex for stop variable\npthread_mutex_t stop_lock;\n\/\/mutex for file descriptor array\npthread_mutex_t file_descriptor_lock;\n\/\/stop variable to end the server\nbool stop = false;\n\/\/stream_socket = socket,\n\/\/temp_fd = temporaray file descriptor\n\/\/k = temporary size variable for write and\n\/\/reads for the amount written\nint stream_socket, temp_fd, k;\n\/\/server address\nstruct sockaddr_in server_addr;\n\/\/client address\nstruct sockaddr_in client_addr;\n\/\/client length\nunsigned int client_len;\n\/\/host pointer\nchar *host;\n\/\/file descriptor arrays for client connections\nint file_descriptor_array[MAX_CLIENT]; \/* allocate as many file descriptors\n as the number of clients *\/\npthread_t client_handlers[100];\n\/\/counter for the number of current connections\nint counter;\n\nint main()\n{\n \/\/signals cntrlc quit\n signal(SIGINT, cntrlc_signal_handle);\n server_addr =\n { AF_INET, htons( SERVER_PORT)};\n client_addr =\n { AF_INET};\n client_len = sizeof(client_addr);\n\n counter = 0;\n\n \/* create a stream socket *\/\n if ((stream_socket = socket( AF_INET, SOCK_STREAM, 0)) == -1)\n {\n perror(\"server: socket failed\");\n exit(1);\n }\n int enable = 1;\n \/* setting socket to be resuable incase of previous runt *\/\n if (setsockopt(stream_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int))\n < 0)\n {\n perror(\"setsockopt(SO_REUSEADDR) failed\");\n }\n\n \/* bind the socket to an internet port *\/\n if (bind(stream_socket, (struct sockaddr*) &server_addr, sizeof(server_addr))\n == -1)\n {\n perror(\"server: bind failed\");\n exit(1);\n }\n\n \/\/listening for the server\n if (listen(stream_socket, 10) == -1)\n {\n perror(\"server: listen failed\");\n exit(1);\n }\n \/\/checking for client connections to accept\n printf(\"SERVER is listening for clients to establish a connection\\n\");\n while (((temp_fd = accept(stream_socket, (struct sockaddr*) &client_addr,\n &client_len)) > 0) && !stop)\n {\n pthread_mutex_lock(&file_descriptor_lock);\n if (counter < MAX_CLIENT)\n {\n file_descriptor_array[counter] = temp_fd;\n pthread_create(&client_handlers[counter], NULL, client_messenger,\n (void*) &file_descriptor_array[counter]);\n pthread_mutex_unlock(&file_descriptor_lock);\n counter++;\n }\n else\n {\n std::cerr << \"Error too many threads\" << std::endl;\n }\n }\n\n close(stream_socket);\n unlink((const char*) &server_addr.sin_addr);\n\n return (0);\n}\n\nvoid cntrlc_signal_handle(int signal)\n{\n std::cout << \"\\nCNTRLC detected\" << std::endl;\n\n char message_buffer[512] =\n \"WARNING: The server will shut down in 10 seconds\\n\";\n char quit_msg[32] = \"\/quit\";\n for (int i = 0; i < counter; i++)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n\n }\n for (int i = 0; i < counter; i++)\n {\n\n write(file_descriptor_array[i], quit_msg, sizeof(quit_msg));\n }\n sleep(10);\n pthread_mutex_lock(&stop_lock);\n stop = true;\n pthread_mutex_unlock(&stop_lock);\n\n for (int i = 0; i < counter; i++)\n {\n\n pthread_cancel(client_handlers[i]);\n\n }\n close(stream_socket);\n unlink((const char*) &server_addr.sin_addr);\n\n}\n\nvoid *client_messenger(void* arg) \/* what does 'bob' do ? *\/\n{\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);\n printf(\n \"Child accept() successful.. a client has connected to child ! waiting for a message\\n\");\n \/\/buffer for read in messages\n char buf[512];\n \/\/this is FD, fd, or file descriptor\n int some_fd = *(int*) arg;\n\n char host_name[100];\n gethostname(host_name, 100);\n char client_name[512];\n char message_buffer[100 + 512];\n char server_message[100];\n\n while ((k = read(some_fd, buf, sizeof(buf))) != 0)\n {\n strcpy(message_buffer, \"User \");\n strcpy(client_name, buf);\n strncat(message_buffer, client_name, 512);\n strncat(message_buffer, \" has joined the channel\\n\", 512);\n \/\/printf(\"GIVEN MESSAGE: %s\\n\", buf);\n\n pthread_mutex_lock(&file_descriptor_lock);\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n pthread_mutex_unlock(&file_descriptor_lock);\n break;\n }\n while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop)\n {\n bzero(message_buffer, 512 + 100);\n printf(\"SERVER RECEIVED: %s\\n\", buf);\n if (strcmp(buf, \"\/quit\") == 0)\n {\n break;\n }\n\n strcpy(message_buffer, \">> \");\n strncat(message_buffer, client_name, sizeof(client_name));\n strncat(message_buffer, \": \", 8);\n strncat(message_buffer, buf, 512);\n strncat(message_buffer, \"\\n\", 3);\n\n pthread_mutex_lock(&file_descriptor_lock);\n\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n\n pthread_mutex_unlock(&file_descriptor_lock);\n pthread_yield();\n }\n\n pthread_mutex_lock(&file_descriptor_lock);\n bzero(message_buffer, 512 + 100);\n strcpy(message_buffer, \"User \");\n strncat(message_buffer, client_name, sizeof(client_name));\n strncat(message_buffer, \" has disconnected.\", 24);\n for (int i = 0; i < counter; i++)\n {\n if (file_descriptor_array[i] != some_fd)\n {\n\n write(file_descriptor_array[i], message_buffer, sizeof(message_buffer));\n }\n }\n int i = 0;\n while ((file_descriptor_array[i] != some_fd))\n {\n i++;\n }\n counter--;\n for (int j = i; j < counter; j++)\n {\n file_descriptor_array[j] = file_descriptor_array[j - 1];\n }\n pthread_mutex_unlock(&file_descriptor_lock);\n close(some_fd);\n std::cout << \"\\n EXITING THREAD\" << std::endl;\n pthread_exit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"state.h\"\n#include \"math.h\"\n\nnamespace gparse {\n\nconst std::string State::OP_G1 = \"G1\";\nconst std::string State::OP_G20 = \"G20\";\nconst std::string State::OP_G21 = \"G21\";\nconst std::string State::OP_G90 = \"G90\";\nconst std::string State::OP_G91 = \"G91\";\nconst std::string State::OP_M21 = \"M21\";\nconst std::string State::OP_M105 = \"M105\";\nconst std::string State::OP_M110 = \"M110\";\n\nState::State(const drv::Driver &drv) {\n\tthis->positionMode = POS_ABSOLUTE;\n\tthis->unitMode = UNIT_MM;\n\tthis->_destXPrimitive = 0;\n\tthis->_destYPrimitive = 0;\n\tthis->_destZPrimitive = 0;\n\tthis->_destEPrimitive = 0;\n\tthis->setDestMoveRatePrimitive(drv.defaultMoveRate());\n\tthis->setDestFeedRatePrimitive(drv.defaultFeedRate());\n}\n\nvoid State::setPositionMode(PositionMode mode) {\n\tthis->positionMode = mode; \n}\n\nvoid State::setUnitMode(LengthUnit mode) {\n\tthis->unitMode = mode;\n}\n\nfloat State::xUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destXPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::yUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destYPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::zUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destZPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::eUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destEPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::posUnitToMM(float posUnit) const {\n\tswitch (this->unitMode) {\n\t\tcase UNIT_IN:\n\t\t\treturn gparse::math::MM_PER_IN * posUnit;\n\t\tcase UNIT_MM:\n\t\tdefault: \/\/impossible case.\n\t\t\treturn posUnit;\n\t}\n}\n\nfloat State::xUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(xUnitToAbsolute(posUnit));\n}\nfloat State::yUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(yUnitToAbsolute(posUnit));\n}\nfloat State::zUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(zUnitToAbsolute(posUnit));\n}\nfloat State::eUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(eUnitToAbsolute(posUnit));\n}\nfloat State::fUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(posUnit); \/\/feed rate is always relative, so no need to call toAbsolute\n}\n\nfloat State::destXPrimitive() const {\n\treturn this->_destXPrimitive;\n}\nfloat State::destYPrimitive() const {\n\treturn this->_destYPrimitive;\n}\nfloat State::destZPrimitive() const {\n\treturn this->_destZPrimitive;\n}\nfloat State::destEPrimitive() const {\n\treturn this->_destEPrimitive;\n}\nfloat State::destMoveRatePrimitive() const {\n\treturn this->_destMoveRatePrimitive;\n}\nvoid State::setDestMoveRatePrimitive(float f) {\n\tthis->_destMoveRatePrimitive = f;\n}\nfloat State::destFeedRatePrimitive() const {\n\treturn this->_destFeedRatePrimitive;\n}\nvoid State::setDestFeedRatePrimitive(float f) {\n\tthis->_destFeedRatePrimitive = f;\n}\n\n}\n<commit_msg>Use initialization list<commit_after>#include \"state.h\"\n#include \"math.h\"\n\nnamespace gparse {\n\nconst std::string State::OP_G1 = \"G1\";\nconst std::string State::OP_G20 = \"G20\";\nconst std::string State::OP_G21 = \"G21\";\nconst std::string State::OP_G90 = \"G90\";\nconst std::string State::OP_G91 = \"G91\";\nconst std::string State::OP_M21 = \"M21\";\nconst std::string State::OP_M105 = \"M105\";\nconst std::string State::OP_M110 = \"M110\";\n\nState::State(const drv::Driver &drv) : positionMode(POS_ABSOLUTE), unitMode(UNIT_MM),\n\t_destXPrimitive(0), _destYPrimitive(0), _destZPrimitive(0), _destEPrimitive(0) {\n\tthis->setDestMoveRatePrimitive(drv.defaultMoveRate());\n\tthis->setDestFeedRatePrimitive(drv.defaultFeedRate());\n}\n\nvoid State::setPositionMode(PositionMode mode) {\n\tthis->positionMode = mode; \n}\n\nvoid State::setUnitMode(LengthUnit mode) {\n\tthis->unitMode = mode;\n}\n\nfloat State::xUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destXPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::yUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destYPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::zUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destZPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::eUnitToAbsolute(float posUnit) const {\n\tswitch (this->positionMode) {\n\t\tcase POS_RELATIVE:\n\t\t\tposUnit += this->_destEPrimitive;\n\t\t\tbreak;\n\t\tcase POS_ABSOLUTE:\n\t\tdefault:\n\t\t\tbreak; \/\/no transformation needed.\n\t}\n\treturn posUnit;\n}\nfloat State::posUnitToMM(float posUnit) const {\n\tswitch (this->unitMode) {\n\t\tcase UNIT_IN:\n\t\t\treturn gparse::math::MM_PER_IN * posUnit;\n\t\tcase UNIT_MM:\n\t\tdefault: \/\/impossible case.\n\t\t\treturn posUnit;\n\t}\n}\n\nfloat State::xUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(xUnitToAbsolute(posUnit));\n}\nfloat State::yUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(yUnitToAbsolute(posUnit));\n}\nfloat State::zUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(zUnitToAbsolute(posUnit));\n}\nfloat State::eUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(eUnitToAbsolute(posUnit));\n}\nfloat State::fUnitToPrimitive(float posUnit) const {\n\treturn posUnitToMM(posUnit); \/\/feed rate is always relative, so no need to call toAbsolute\n}\n\nfloat State::destXPrimitive() const {\n\treturn this->_destXPrimitive;\n}\nfloat State::destYPrimitive() const {\n\treturn this->_destYPrimitive;\n}\nfloat State::destZPrimitive() const {\n\treturn this->_destZPrimitive;\n}\nfloat State::destEPrimitive() const {\n\treturn this->_destEPrimitive;\n}\nfloat State::destMoveRatePrimitive() const {\n\treturn this->_destMoveRatePrimitive;\n}\nvoid State::setDestMoveRatePrimitive(float f) {\n\tthis->_destMoveRatePrimitive = f;\n}\nfloat State::destFeedRatePrimitive() const {\n\treturn this->_destFeedRatePrimitive;\n}\nvoid State::setDestFeedRatePrimitive(float f) {\n\tthis->_destFeedRatePrimitive = f;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Arduino.h>\r\n#include <roboteqMC.h>\r\n\r\nAX2550::AX2550(HardwareSerial& serial_port):uart(serial_port)\r\n{\r\n uart.begin(9600,SERIAL_7E1);\r\n}\r\n\r\nvoid AX2550::init(uint8_t x,uint8_t y){\r\n x_key = x;\r\n y_key = y;\r\n}\r\n\r\nvoid AX2550::set_report(uint8_t v,uint8_t l,uint8_t r){\r\n volt_key = v;\r\n amps_left_key = l;\r\n amps_right_key = r;\r\n}\r\n\r\nbool AX2550::move(int Steering,int Throttle, bool check)\r\n{\r\n int8_t Dir1 = 0;\r\n int8_t Dir2 = 0;\r\n while(uart.available()>0)\r\n {\r\n uart.read();\r\n }\r\n if(Throttle>=0)\r\n {\r\n Dir1 = 0x41;\r\n }\r\n if(Throttle<0)\r\n {\r\n Dir1 = 0x61;\r\n }\r\n if(Steering>=0)\r\n {\r\n Dir2 = 0x42;\r\n }\r\n if(Steering<0)\r\n {\r\n Dir2 = 0x62;\r\n }\r\n\r\n Throttle = map(abs(Throttle),0,100,0,126);\r\n \r\n Steering = map(abs(Steering),0,100,0,126);\r\n\r\n char command[12];\r\n sprintf(command,\"!%c%02x\\r\\n!%c%02x\\r\\n\",Dir1,abs(Throttle),Dir2,abs(Steering));\r\n uart.print(command);\r\n\r\n if(check){\r\n delay(10);\r\n\r\n bool chk_throttle = chkResponse();\r\n bool chk_steering = chkResponse();\r\n\r\n while(uart.available()>0){\r\n uart.read();\r\n }\r\n return chk_throttle & chk_steering;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool AX2550::move(Message inp, bool check){\r\n if(inp.new_data(y_key) || inp.new_data(x_key)){\r\n return move(int16_t(inp.get_data(y_key)),int16_t(inp.get_data(x_key)),check);\r\n }\r\n return false;\r\n}\r\n\r\nbool AX2550::chkResponse()\r\n{\r\n char status;\r\n uint8_t counter=0;\r\n while(1)\r\n {\r\n status = uart.read();\r\n \/\/Serial.print(status);\r\n if(status == '+')\r\n {\r\n return true;\r\n }\r\n else if(status == '-')\r\n {\r\n \/\/Serial.println(\"Command Fails!\");\r\n return false;\r\n }\r\n else if(counter == 20)\r\n {\r\n Serial3.println(\"Chk response Timeout\");\r\n return false;\r\n }\r\n else\r\n {\r\n counter+=1;\r\n delay(1);\r\n }\r\n }\r\n}\r\n\r\nfloat AX2550::volt()\r\n{\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n char command[2];\r\n sprintf(command,\"?e\");\r\n if(sendChk(command))\r\n {\r\n char inp[4];\r\n\/*\r\n while(uart.available()){\r\n Serial.println(char(uart.read()));\r\n }\r\n\r\n\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n\r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read()); \r\n\r\n \/\/ Serial.println(inp[0]);\r\n \/\/ Serial.println(inp[1]);\r\n \/\/ Serial.println(inp[2]);\r\n \/\/ Serial.println(inp[3]);\r\n\r\n*\/\r\n uart.read();\r\n\r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read());\r\n\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n\r\n uint16_t conv = strtoul(inp,0,16);\r\n\r\n Serial.println(conv);\r\n\r\n float volt = 55 * conv\/256.0;\r\n\r\n Serial.println(volt);\r\n\r\n delay(10);\r\n\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n\r\n return volt;\r\n }\r\n return 0.0;\r\n}\r\n\r\nint AX2550::amps(uint8_t channel)\r\n{\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n\r\n char command[2];\r\n sprintf(command,\"?a\");\r\n \r\n if(sendChk(command))\r\n {\r\n char inp[2];\r\n \r\n if(channel == 1)\r\n {\r\n uart.read();\r\n \r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read());\r\n }\r\n\r\n if(channel == 2)\r\n {\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n \r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read());\r\n }\r\n\r\n\r\n \/\/ Serial.println(inp[0]);\r\n \/\/ Serial.println(inp[1]);\r\n \/\/ Serial.println(inp[2]);\r\n \/\/ Serial.println(inp[3]);\r\n\r\n int amps = strtoul(inp,0,16);\r\n\r\n \/\/ Serial.println(volt);\r\n\r\n delay(10);\r\n\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n return amps;\r\n }\r\n \/\/ Serial.println(\"Fail!\");\r\n return 0;\r\n}\r\n\r\nbool AX2550::sendChk(char buff[])\r\n{\r\n uint8_t lenght = strlen(buff);\r\n char input_buff[lenght];\r\n uart.println(buff);\r\n\r\n uint8_t counter=0;\r\n uint8_t timeout=100;\r\n\r\n delay(10);\r\n\r\n while(1)\r\n {\r\n if(uart.available()>0)\r\n {\r\n for(int i=0;i<lenght;i++)\r\n {\r\n input_buff[i]=uart.read();\r\n if(input_buff[i]!=buff[i])\r\n {\r\n \/\/Echo Condition\r\n \/\/ Serial.println(\"Echo Error!\");\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n else if(counter == timeout)\r\n {\r\n \/\/Timeout condition\r\n \/\/ Serial.println(\"Timeout Error!\");\r\n return false;\r\n }\r\n else\r\n {\r\n counter+=1;\r\n delay(1);\r\n }\r\n }\r\n}\r\n\r\nMessage AX2550::report(){\r\n Message output;\r\n output.add_data(amps_left_key,uint16_t(amps(1)));\r\n output.add_data(amps_right_key,uint16_t(amps(2)));\r\n output.add_data(volt_key,uint16_t(volt()));\r\n return output;\r\n}<commit_msg>Update<commit_after>#include <Arduino.h>\r\n#include <roboteqMC.h>\r\n\r\nAX2550::AX2550(HardwareSerial& serial_port):uart(serial_port)\r\n{\r\n uart.begin(9600,SERIAL_7E1);\r\n}\r\n\r\nvoid AX2550::init(uint8_t x,uint8_t y){\r\n x_key = x;\r\n y_key = y;\r\n}\r\n\r\nvoid AX2550::set_report(uint8_t v,uint8_t l,uint8_t r){\r\n volt_key = v;\r\n amps_left_key = l;\r\n amps_right_key = r;\r\n}\r\n\r\nbool AX2550::move(int Steering,int Throttle, bool check)\r\n{\r\n int8_t Dir1 = 0;\r\n int8_t Dir2 = 0;\r\n while(uart.available()>0)\r\n {\r\n uart.read();\r\n }\r\n if(Throttle>=0)\r\n {\r\n Dir1 = 0x41;\r\n }\r\n if(Throttle<0)\r\n {\r\n Dir1 = 0x61;\r\n }\r\n if(Steering>=0)\r\n {\r\n Dir2 = 0x42;\r\n }\r\n if(Steering<0)\r\n {\r\n Dir2 = 0x62;\r\n }\r\n\r\n Throttle = map(abs(Throttle),0,100,0,126);\r\n \r\n Steering = map(abs(Steering),0,100,0,126);\r\n\r\n char command[12];\r\n sprintf(command,\"!%c%02x\\r\\n!%c%02x\\r\\n\",Dir1,abs(Throttle),Dir2,abs(Steering));\r\n uart.print(command);\r\n\r\n if(check){\r\n delay(10);\r\n\r\n bool chk_throttle = chkResponse();\r\n bool chk_steering = chkResponse();\r\n\r\n while(uart.available()>0){\r\n uart.read();\r\n }\r\n return chk_throttle & chk_steering;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nbool AX2550::move(Message inp, bool check){\r\n if(inp.new_data(y_key) || inp.new_data(x_key)){\r\n return move(int16_t(inp.get_data(y_key)),int16_t(inp.get_data(x_key)),check);\r\n }\r\n return false;\r\n}\r\n\r\nbool AX2550::chkResponse()\r\n{\r\n char status;\r\n uint8_t counter=0;\r\n while(1)\r\n {\r\n status = uart.read();\r\n \/\/Serial.print(status);\r\n if(status == '+')\r\n {\r\n return true;\r\n }\r\n else if(status == '-')\r\n {\r\n \/\/Serial.println(\"Command Fails!\");\r\n return false;\r\n }\r\n else if(counter == 20)\r\n {\r\n Serial3.println(\"Chk response Timeout\");\r\n return false;\r\n }\r\n else\r\n {\r\n counter+=1;\r\n delay(1);\r\n }\r\n }\r\n}\r\n\r\n\r\nfloat AX2550::volt()\r\n{\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n char command[2];\r\n sprintf(command,\"?e\");\r\n if(sendChk(command))\r\n {\r\n char convert[4];\r\n\/*\r\n while(uart.available()){\r\n Serial.println(char(uart.read()));\r\n }\r\n\r\n\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n\r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read()); \r\n\r\n \/\/ Serial.println(inp[0]);\r\n \/\/ Serial.println(inp[1]);\r\n \/\/ Serial.println(inp[2]);\r\n \/\/ Serial.println(inp[3]);\r\n\r\n*\/\r\n uart.read();\r\n\r\n convert[0] = '0';\r\n convert[1] = 'x';\r\n convert[2] = char(uart.read());\r\n convert[3] = char(uart.read());\r\n\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n\r\n\/*\r\n\r\n Serial.println(\"--- ---\");\r\n Serial.println(convert[0]);\r\n Serial.println(convert[1]);\r\n Serial.println(convert[2]);\r\n Serial.println(convert[3]);\r\n Serial.println(\"--- ---\");\r\n\r\n*\/\r\n\r\n uint16_t conv = strtoul(convert,NULL,16);\r\n\r\n \/\/Serial.println(conv);\r\n \/\/Serial.println(\"--- ---\");\r\n float volt = 55 * (conv\/256.0);\r\n \/\/Serial.println(volt);\r\n\r\n delay(10);\r\n\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n\r\n return volt;\r\n }\r\n return 0.0;\r\n}\r\n\r\n\r\nint AX2550::amps(uint8_t channel)\r\n{\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n\r\n char command[2];\r\n sprintf(command,\"?a\");\r\n \r\n if(sendChk(command))\r\n {\r\n char inp[2];\r\n \r\n if(channel == 1)\r\n {\r\n uart.read();\r\n \r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read());\r\n }\r\n\r\n if(channel == 2)\r\n {\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n uart.read();\r\n \r\n inp[0] = '0';\r\n inp[1] = 'x';\r\n inp[2] = char(uart.read());\r\n inp[3] = char(uart.read());\r\n }\r\n\r\n\r\n \/\/ Serial.println(inp[0]);\r\n \/\/ Serial.println(inp[1]);\r\n \/\/ Serial.println(inp[2]);\r\n \/\/ Serial.println(inp[3]);\r\n\r\n int amps = strtoul(inp,0,16);\r\n\r\n \/\/ Serial.println(volt);\r\n\r\n delay(10);\r\n\r\n while(uart.available())\r\n {\r\n uart.read();\r\n }\r\n return amps;\r\n }\r\n \/\/ Serial.println(\"Fail!\");\r\n return 0;\r\n}\r\n\r\nbool AX2550::sendChk(char buff[])\r\n{\r\n uint8_t lenght = strlen(buff);\r\n char input_buff[lenght];\r\n uart.println(buff);\r\n\r\n uint8_t counter=0;\r\n uint8_t timeout=100;\r\n\r\n delay(10);\r\n\r\n while(1)\r\n {\r\n if(uart.available()>0)\r\n {\r\n for(int i=0;i<lenght;i++)\r\n {\r\n input_buff[i]=uart.read();\r\n if(input_buff[i]!=buff[i])\r\n {\r\n \/\/Echo Condition\r\n \/\/ Serial.println(\"Echo Error!\");\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n else if(counter == timeout)\r\n {\r\n \/\/Timeout condition\r\n \/\/ Serial.println(\"Timeout Error!\");\r\n return false;\r\n }\r\n else\r\n {\r\n counter+=1;\r\n delay(1);\r\n }\r\n }\r\n}\r\n\r\nMessage AX2550::report(){\r\n Message output;\r\n output.add_data(amps_left_key,uint16_t(amps(1)));\r\n output.add_data(amps_right_key,uint16_t(amps(2)));\r\n output.add_data(volt_key,uint16_t(volt()));\r\n return output;\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"BootstrapInfo.h\"\n\n#ifdef DEBUGGER\n #include <Debugger.h>\n #include <LocksCommand.h>\n#endif\n\n#include <linker\/KernelElf.h> \/\/ KernelElf::initialise()\n#include <Version.h>\n#include <Log.h>\n#include <panic.h>\n#include <Archive.h>\n\n#include \"cppsupport.h\" \/\/ initialiseConstructors()\n\n#include <processor\/Processor.h> \/\/ Processor::initialise1(), Processor::initialise2()\n#include <processor\/PhysicalMemoryManager.h>\n#include <processor\/KernelCoreSyscallManager.h>\n\n#include <machine\/Machine.h> \/\/ Machine::initialise()\n#include <LocalIO.h>\n#include <SerialIO.h>\n#include <DebuggerIO.h>\n#include \"BootIO.h\"\n\n#include <process\/initialiseMultitasking.h>\n#include <process\/Thread.h>\n#include <process\/Scheduler.h>\n#include <process\/SchedulingAlgorithm.h>\n\n#include <machine\/Device.h>\n\n#ifdef OPENFIRMWARE\n #include <machine\/openfirmware\/Device.h>\n#endif\n\n#include <utilities\/List.h>\n#include <utilities\/RadixTree.h>\n#include <utilities\/StaticString.h>\n\n#include <machine\/InputManager.h>\n\n#ifdef THREADS\n#include <utilities\/ZombieQueue.h>\n#endif\n\nvoid apmm()\n{\n}\n\/** Output device for boot-time information. *\/\nBootIO bootIO;\n\n\/** Global copy of the bootstrap information. *\/\nBootstrapStruct_t *g_pBootstrapInfo;\n\n\/** Kernel entry point for application processors (after processor\/machine has been initialised\n on the particular processor *\/\nvoid apMain()\n{\n NOTICE(\"Processor #\" << Processor::id() << \" started.\");\n\n Processor::setInterrupts(true);\n for (;;)\n {\n#ifdef THREADS\n Scheduler::instance().yield();\n#endif\n }\n}\n\n\/** A processor idle function. *\/\n\/*int idle(void *)\n{\n NOTICE(\"Idle \" << Processor::information().getCurrentThread()->getId());\n Processor::setInterrupts(true);\n for (;;)\n {\n Scheduler::instance().yield();\n }\n return 0;\n}*\/\n\n\/** Loads all kernel modules *\/\nint loadModules(void *inf)\n{\n BootstrapStruct_t bsInf = *static_cast<BootstrapStruct_t*>(inf);\n\n \/\/\/ \\note We have to do this before we call Processor::initialisationDone() otherwise the\n \/\/\/ BootstrapStruct_t might already be unmapped\n Archive initrd(bsInf.getInitrdAddress(), bsInf.getInitrdSize());\n\n size_t nFiles = initrd.getNumFiles();\n g_BootProgressTotal = nFiles*2; \/\/ Each file has to be preloaded and executed.\n for (size_t i = 0; i < nFiles; i++)\n {\n \/\/ Load file.\n KernelElf::instance().loadModule(reinterpret_cast<uint8_t*> (initrd.getFile(i)),\n initrd.getFileSize(i));\n }\n\n \/\/ The initialisation is done here, unmap\/free the .init section and on x86\/64 the identity\n \/\/ mapping of 0-4MB\n \/\/ NOTE: BootstrapStruct_t unusable after this point\n #ifdef X86_COMMON\n Processor::initialisationDone();\n #endif\n\n return 0;\n}\n\n\/** Kernel entry point. *\/\nextern \"C\" void _main(BootstrapStruct_t &bsInf)\n{\n \/\/ Firstly call the constructors of all global objects.\n initialiseConstructors();\n\n g_pBootstrapInfo = &bsInf;\n\n \/\/ Initialise the processor-specific interface\n Processor::initialise1(bsInf);\n\n \/\/ Initialise the machine-specific interface\n Machine &machine = Machine::instance();\n\n#if defined(X86_COMMON) || defined(PPC_COMMON)\n Machine::instance().initialiseDeviceTree();\n#endif\n\n machine.initialise();\n\n#if defined(DEBUGGER)\n Debugger::instance().initialise();\n#endif\n\n \/\/ Initialise the kernel log.\n Log::instance().initialise();\n\n#ifndef ARM_BEAGLE\n \/\/ Initialise the Kernel Elf class\n if (KernelElf::instance().initialise(bsInf) == false)\n panic(\"KernelElf::initialise() failed\");\n#endif\n\n#ifndef ARM_COMMON\n if (bsInf.isInitrdLoaded() == false)\n panic(\"Initrd module not loaded!\");\n\n KernelCoreSyscallManager::instance().initialise();\n#endif\n\n \/\/ Initialise the processor-specific interface\n \/\/ Bootup of the other Application Processors and related tasks\n Processor::initialise2(bsInf);\n\n#ifdef THREADS\n ZombieQueue::instance().initialise();\n#endif\n\n#ifndef ARM_COMMON \/\/ No ARM port is ready for interrupts yet.\n Processor::setInterrupts(true);\n\n \/\/ Initialise the input manager\n InputManager::instance().initialise();\n#endif\n\n \/\/ Initialise the boot output.\n bootIO.initialise();\n\n \/\/ Spew out a starting string.\n HugeStaticString str;\n str += \"Pedigree - revision \";\n str += g_pBuildRevision;\n str += \"\\n=======================\\n\";\n bootIO.write(str, BootIO::White, BootIO::Black);\n\n str.clear();\n str += \"Built at \";\n str += g_pBuildTime;\n str += \" by \";\n str += g_pBuildUser;\n str += \" on \";\n str += g_pBuildMachine;\n str += \"\\n\";\n bootIO.write(str, BootIO::LightGrey, BootIO::Black);\n\n str.clear();\n str += \"Build flags: \";\n str += g_pBuildFlags;\n str += \"\\n\";\n bootIO.write(str, BootIO::LightGrey, BootIO::Black);\n\n#ifdef ARM_COMMON\n NOTICE(\"ARM build now boots properly. Now hanging forever...\");\n while(1);\n#endif\n\n#ifdef TRACK_LOCKS\n g_LocksCommand.setReady();\n#endif\n\n#ifdef THREADS\n new Thread(Processor::information().getCurrentThread()->getParent(), &loadModules, static_cast<void*>(&bsInf), 0);\n#else\n loadModules(&bsInf);\n#endif\n\n#ifdef DEBUGGER_RUN_AT_START\n \/\/Processor::breakpoint();\n#endif\n\n#ifdef THREADS\n Processor::information().getCurrentThread()->setPriority(MAX_PRIORITIES-1);\n#endif\n\n \/\/ This will run when nothing else is available to run\n for (;;)\n {\n \/\/ Kernel idle thread.\n Processor::setInterrupts(true);\n \n asm volatile (\"hlt\");\n \n#ifdef THREADS\n Scheduler::instance().yield();\n#endif\n }\n}\n\nvoid system_reset()\n{\n NOTICE(\"Resetting...\");\n KernelElf::instance().unloadModules();\n Processor::reset();\n}\n<commit_msg>More of the same - adding carriage returns where needed.<commit_after>\/*\n * Copyright (c) 2010 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"BootstrapInfo.h\"\n\n#ifdef DEBUGGER\n #include <Debugger.h>\n #include <LocksCommand.h>\n#endif\n\n#include <linker\/KernelElf.h> \/\/ KernelElf::initialise()\n#include <Version.h>\n#include <Log.h>\n#include <panic.h>\n#include <Archive.h>\n\n#include \"cppsupport.h\" \/\/ initialiseConstructors()\n\n#include <processor\/Processor.h> \/\/ Processor::initialise1(), Processor::initialise2()\n#include <processor\/PhysicalMemoryManager.h>\n#include <processor\/KernelCoreSyscallManager.h>\n\n#include <machine\/Machine.h> \/\/ Machine::initialise()\n#include <LocalIO.h>\n#include <SerialIO.h>\n#include <DebuggerIO.h>\n#include \"BootIO.h\"\n\n#include <process\/initialiseMultitasking.h>\n#include <process\/Thread.h>\n#include <process\/Scheduler.h>\n#include <process\/SchedulingAlgorithm.h>\n\n#include <machine\/Device.h>\n\n#ifdef OPENFIRMWARE\n #include <machine\/openfirmware\/Device.h>\n#endif\n\n#include <utilities\/List.h>\n#include <utilities\/RadixTree.h>\n#include <utilities\/StaticString.h>\n\n#include <machine\/InputManager.h>\n\n#ifdef THREADS\n#include <utilities\/ZombieQueue.h>\n#endif\n\nvoid apmm()\n{\n}\n\/** Output device for boot-time information. *\/\nBootIO bootIO;\n\n\/** Global copy of the bootstrap information. *\/\nBootstrapStruct_t *g_pBootstrapInfo;\n\n\/** Kernel entry point for application processors (after processor\/machine has been initialised\n on the particular processor *\/\nvoid apMain()\n{\n NOTICE(\"Processor #\" << Processor::id() << \" started.\");\n\n Processor::setInterrupts(true);\n for (;;)\n {\n#ifdef THREADS\n Scheduler::instance().yield();\n#endif\n }\n}\n\n\/** A processor idle function. *\/\n\/*int idle(void *)\n{\n NOTICE(\"Idle \" << Processor::information().getCurrentThread()->getId());\n Processor::setInterrupts(true);\n for (;;)\n {\n Scheduler::instance().yield();\n }\n return 0;\n}*\/\n\n\/** Loads all kernel modules *\/\nint loadModules(void *inf)\n{\n BootstrapStruct_t bsInf = *static_cast<BootstrapStruct_t*>(inf);\n\n \/\/\/ \\note We have to do this before we call Processor::initialisationDone() otherwise the\n \/\/\/ BootstrapStruct_t might already be unmapped\n Archive initrd(bsInf.getInitrdAddress(), bsInf.getInitrdSize());\n\n size_t nFiles = initrd.getNumFiles();\n g_BootProgressTotal = nFiles*2; \/\/ Each file has to be preloaded and executed.\n for (size_t i = 0; i < nFiles; i++)\n {\n \/\/ Load file.\n KernelElf::instance().loadModule(reinterpret_cast<uint8_t*> (initrd.getFile(i)),\n initrd.getFileSize(i));\n }\n\n \/\/ The initialisation is done here, unmap\/free the .init section and on x86\/64 the identity\n \/\/ mapping of 0-4MB\n \/\/ NOTE: BootstrapStruct_t unusable after this point\n #ifdef X86_COMMON\n Processor::initialisationDone();\n #endif\n\n return 0;\n}\n\n\/** Kernel entry point. *\/\nextern \"C\" void _main(BootstrapStruct_t &bsInf)\n{\n \/\/ Firstly call the constructors of all global objects.\n initialiseConstructors();\n\n g_pBootstrapInfo = &bsInf;\n\n \/\/ Initialise the processor-specific interface\n Processor::initialise1(bsInf);\n\n \/\/ Initialise the machine-specific interface\n Machine &machine = Machine::instance();\n\n#if defined(X86_COMMON) || defined(PPC_COMMON)\n Machine::instance().initialiseDeviceTree();\n#endif\n\n machine.initialise();\n\n#if defined(DEBUGGER)\n Debugger::instance().initialise();\n#endif\n\n \/\/ Initialise the kernel log.\n Log::instance().initialise();\n\n#ifndef ARM_BEAGLE\n \/\/ Initialise the Kernel Elf class\n if (KernelElf::instance().initialise(bsInf) == false)\n panic(\"KernelElf::initialise() failed\");\n#endif\n\n#ifndef ARM_COMMON\n if (bsInf.isInitrdLoaded() == false)\n panic(\"Initrd module not loaded!\");\n\n KernelCoreSyscallManager::instance().initialise();\n#endif\n\n \/\/ Initialise the processor-specific interface\n \/\/ Bootup of the other Application Processors and related tasks\n Processor::initialise2(bsInf);\n\n#ifdef THREADS\n ZombieQueue::instance().initialise();\n#endif\n\n#ifndef ARM_COMMON \/\/ No ARM port is ready for interrupts yet.\n Processor::setInterrupts(true);\n\n \/\/ Initialise the input manager\n InputManager::instance().initialise();\n#endif\n\n \/\/ Initialise the boot output.\n bootIO.initialise();\n\n \/\/ Spew out a starting string.\n HugeStaticString str;\n str += \"Pedigree - revision \";\n str += g_pBuildRevision;\n#ifndef DONT_LOG_TO_SERIAL\n str += \"\\r\\n=======================\\r\\n\";\n#else\n str += \"\\n=======================\\n\";\n#endif\n bootIO.write(str, BootIO::White, BootIO::Black);\n\n str.clear();\n str += \"Built at \";\n str += g_pBuildTime;\n str += \" by \";\n str += g_pBuildUser;\n str += \" on \";\n str += g_pBuildMachine;\n#ifndef DONT_LOG_TO_SERIAL\n str += \"\\r\\n\";\n#else\n str += \"\\n\";\n#endif\n bootIO.write(str, BootIO::LightGrey, BootIO::Black);\n\n str.clear();\n str += \"Build flags: \";\n str += g_pBuildFlags;\n#ifndef DONT_LOG_TO_SERIAL\n str += \"\\r\\n\";\n#else\n str += \"\\n\";\n#endif\n bootIO.write(str, BootIO::LightGrey, BootIO::Black);\n\n#ifdef ARM_COMMON\n NOTICE(\"ARM build now boots properly. Now hanging forever...\");\n while(1);\n#endif\n\n#ifdef TRACK_LOCKS\n g_LocksCommand.setReady();\n#endif\n\n#ifdef THREADS\n new Thread(Processor::information().getCurrentThread()->getParent(), &loadModules, static_cast<void*>(&bsInf), 0);\n#else\n loadModules(&bsInf);\n#endif\n\n#ifdef DEBUGGER_RUN_AT_START\n \/\/Processor::breakpoint();\n#endif\n\n#ifdef THREADS\n Processor::information().getCurrentThread()->setPriority(MAX_PRIORITIES-1);\n#endif\n\n \/\/ This will run when nothing else is available to run\n for (;;)\n {\n \/\/ Kernel idle thread.\n Processor::setInterrupts(true);\n \n asm volatile (\"hlt\");\n \n#ifdef THREADS\n Scheduler::instance().yield();\n#endif\n }\n}\n\nvoid system_reset()\n{\n NOTICE(\"Resetting...\");\n KernelElf::instance().unloadModules();\n Processor::reset();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/LU>\n\ntemplate<typename MatrixType> void lu_non_invertible()\n{\n \/* this test covers the following files:\n LU.h\n *\/\n int rows = ei_random<int>(20,200), cols = ei_random<int>(20,200), cols2 = ei_random<int>(20,200);\n int rank = ei_random<int>(1, std::min(rows, cols)-1);\n\n MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);\n createRandomMatrixOfRank(rank, rows, cols, m1);\n\n LU<MatrixType> lu(m1);\n typename LU<MatrixType>::KernelResultType m1kernel = lu.kernel();\n typename LU<MatrixType>::ImageResultType m1image = lu.image();\n\n VERIFY(rank == lu.rank());\n VERIFY(cols - lu.rank() == lu.dimensionOfKernel());\n VERIFY(!lu.isInjective());\n VERIFY(!lu.isInvertible());\n VERIFY(lu.isSurjective() == (lu.rank() == rows));\n VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));\n VERIFY(m1image.lu().rank() == rank);\n MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());\n sidebyside << m1, m1image;\n VERIFY(sidebyside.lu().rank() == rank);\n m2 = MatrixType::Random(cols,cols2);\n m3 = m1*m2;\n m2 = MatrixType::Random(cols,cols2);\n lu.solve(m3, &m2);\n VERIFY_IS_APPROX(m3, m1*m2);\n m3 = MatrixType::Random(rows,cols2);\n VERIFY(!lu.solve(m3, &m2));\n \n typedef Matrix<typename MatrixType::Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;\n SquareMatrixType m4(rows, rows), m5(rows, rows);\n createRandomMatrixOfRank(rows\/2, rows, rows, m4);\n VERIFY(!m4.computeInverseWithCheck(&m5));\n}\n\ntemplate<typename MatrixType> void lu_invertible()\n{\n \/* this test covers the following files:\n LU.h\n *\/\n typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n int size = ei_random<int>(10,200);\n\n MatrixType m1(size, size), m2(size, size), m3(size, size);\n m1 = MatrixType::Random(size,size);\n\n if (ei_is_same_type<RealScalar,float>::ret)\n {\n \/\/ let's build a matrix more stable to inverse\n MatrixType a = MatrixType::Random(size,size*2);\n m1 += a * a.adjoint();\n }\n\n LU<MatrixType> lu(m1);\n VERIFY(0 == lu.dimensionOfKernel());\n VERIFY(size == lu.rank());\n VERIFY(lu.isInjective());\n VERIFY(lu.isSurjective());\n VERIFY(lu.isInvertible());\n VERIFY(lu.image().lu().isInvertible());\n m3 = MatrixType::Random(size,size);\n lu.solve(m3, &m2);\n VERIFY_IS_APPROX(m3, m1*m2);\n VERIFY_IS_APPROX(m2, lu.inverse()*m3);\n m3 = MatrixType::Random(size,size);\n VERIFY(lu.solve(m3, &m2));\n}\n\ntemplate<typename MatrixType> void lu_verify_assert()\n{\n MatrixType tmp;\n\n LU<MatrixType> lu;\n VERIFY_RAISES_ASSERT(lu.matrixLU())\n VERIFY_RAISES_ASSERT(lu.permutationP())\n VERIFY_RAISES_ASSERT(lu.permutationQ())\n VERIFY_RAISES_ASSERT(lu.computeKernel(&tmp))\n VERIFY_RAISES_ASSERT(lu.computeImage(&tmp))\n VERIFY_RAISES_ASSERT(lu.kernel())\n VERIFY_RAISES_ASSERT(lu.image())\n VERIFY_RAISES_ASSERT(lu.solve(tmp,&tmp))\n VERIFY_RAISES_ASSERT(lu.determinant())\n VERIFY_RAISES_ASSERT(lu.rank())\n VERIFY_RAISES_ASSERT(lu.dimensionOfKernel())\n VERIFY_RAISES_ASSERT(lu.isInjective())\n VERIFY_RAISES_ASSERT(lu.isSurjective())\n VERIFY_RAISES_ASSERT(lu.isInvertible())\n VERIFY_RAISES_ASSERT(lu.computeInverse(&tmp))\n VERIFY_RAISES_ASSERT(lu.inverse())\n\n PartialLU<MatrixType> plu;\n VERIFY_RAISES_ASSERT(plu.matrixLU())\n VERIFY_RAISES_ASSERT(plu.permutationP())\n VERIFY_RAISES_ASSERT(plu.solve(tmp,&tmp))\n VERIFY_RAISES_ASSERT(plu.determinant())\n VERIFY_RAISES_ASSERT(plu.computeInverse(&tmp))\n VERIFY_RAISES_ASSERT(plu.inverse())\n}\n\nvoid test_lu()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( lu_non_invertible<MatrixXf>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXd>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );\n CALL_SUBTEST( lu_invertible<MatrixXf>() );\n CALL_SUBTEST( lu_invertible<MatrixXd>() );\n CALL_SUBTEST( lu_invertible<MatrixXcf>() );\n CALL_SUBTEST( lu_invertible<MatrixXcd>() );\n }\n\n CALL_SUBTEST( lu_verify_assert<Matrix3f>() );\n CALL_SUBTEST( lu_verify_assert<Matrix3d>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXf>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXd>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXcf>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXcd>() );\n}\n<commit_msg>small improvements<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/LU>\n\ntemplate<typename MatrixType> void lu_non_invertible()\n{\n \/* this test covers the following files:\n LU.h\n *\/\n int rows = ei_random<int>(20,200), cols = ei_random<int>(20,200), cols2 = ei_random<int>(20,200);\n int rank = ei_random<int>(1, std::min(rows, cols)-1);\n\n MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);\n createRandomMatrixOfRank(rank, rows, cols, m1);\n\n LU<MatrixType> lu(m1);\n typename LU<MatrixType>::KernelResultType m1kernel = lu.kernel();\n typename LU<MatrixType>::ImageResultType m1image = lu.image();\n\n VERIFY(rank == lu.rank());\n VERIFY(cols - lu.rank() == lu.dimensionOfKernel());\n VERIFY(!lu.isInjective());\n VERIFY(!lu.isInvertible());\n VERIFY(!lu.isSurjective());\n VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));\n VERIFY(m1image.lu().rank() == rank);\n MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());\n sidebyside << m1, m1image;\n VERIFY(sidebyside.lu().rank() == rank);\n m2 = MatrixType::Random(cols,cols2);\n m3 = m1*m2;\n m2 = MatrixType::Random(cols,cols2);\n VERIFY(lu.solve(m3, &m2));\n VERIFY_IS_APPROX(m3, m1*m2);\n m3 = MatrixType::Random(rows,cols2);\n VERIFY(!lu.solve(m3, &m2));\n \n typedef Matrix<typename MatrixType::Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;\n SquareMatrixType m4(rows, rows), m5(rows, rows);\n createRandomMatrixOfRank(rows\/2, rows, rows, m4);\n VERIFY(!m4.computeInverseWithCheck(&m5));\n}\n\ntemplate<typename MatrixType> void lu_invertible()\n{\n \/* this test covers the following files:\n LU.h\n *\/\n typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n int size = ei_random<int>(10,200);\n\n MatrixType m1(size, size), m2(size, size), m3(size, size);\n m1 = MatrixType::Random(size,size);\n\n if (ei_is_same_type<RealScalar,float>::ret)\n {\n \/\/ let's build a matrix more stable to inverse\n MatrixType a = MatrixType::Random(size,size*2);\n m1 += a * a.adjoint();\n }\n\n LU<MatrixType> lu(m1);\n VERIFY(0 == lu.dimensionOfKernel());\n VERIFY(size == lu.rank());\n VERIFY(lu.isInjective());\n VERIFY(lu.isSurjective());\n VERIFY(lu.isInvertible());\n VERIFY(lu.image().lu().isInvertible());\n m3 = MatrixType::Random(size,size);\n lu.solve(m3, &m2);\n VERIFY_IS_APPROX(m3, m1*m2);\n VERIFY_IS_APPROX(m2, lu.inverse()*m3);\n m3 = MatrixType::Random(size,size);\n VERIFY(lu.solve(m3, &m2));\n}\n\ntemplate<typename MatrixType> void lu_verify_assert()\n{\n MatrixType tmp;\n\n LU<MatrixType> lu;\n VERIFY_RAISES_ASSERT(lu.matrixLU())\n VERIFY_RAISES_ASSERT(lu.permutationP())\n VERIFY_RAISES_ASSERT(lu.permutationQ())\n VERIFY_RAISES_ASSERT(lu.computeKernel(&tmp))\n VERIFY_RAISES_ASSERT(lu.computeImage(&tmp))\n VERIFY_RAISES_ASSERT(lu.kernel())\n VERIFY_RAISES_ASSERT(lu.image())\n VERIFY_RAISES_ASSERT(lu.solve(tmp,&tmp))\n VERIFY_RAISES_ASSERT(lu.determinant())\n VERIFY_RAISES_ASSERT(lu.rank())\n VERIFY_RAISES_ASSERT(lu.dimensionOfKernel())\n VERIFY_RAISES_ASSERT(lu.isInjective())\n VERIFY_RAISES_ASSERT(lu.isSurjective())\n VERIFY_RAISES_ASSERT(lu.isInvertible())\n VERIFY_RAISES_ASSERT(lu.computeInverse(&tmp))\n VERIFY_RAISES_ASSERT(lu.inverse())\n\n PartialLU<MatrixType> plu;\n VERIFY_RAISES_ASSERT(plu.matrixLU())\n VERIFY_RAISES_ASSERT(plu.permutationP())\n VERIFY_RAISES_ASSERT(plu.solve(tmp,&tmp))\n VERIFY_RAISES_ASSERT(plu.determinant())\n VERIFY_RAISES_ASSERT(plu.computeInverse(&tmp))\n VERIFY_RAISES_ASSERT(plu.inverse())\n}\n\nvoid test_lu()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( lu_non_invertible<MatrixXf>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXd>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );\n CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );\n CALL_SUBTEST( lu_invertible<MatrixXf>() );\n CALL_SUBTEST( lu_invertible<MatrixXd>() );\n CALL_SUBTEST( lu_invertible<MatrixXcf>() );\n CALL_SUBTEST( lu_invertible<MatrixXcd>() );\n }\n\n CALL_SUBTEST( lu_verify_assert<Matrix3f>() );\n CALL_SUBTEST( lu_verify_assert<Matrix3d>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXf>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXd>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXcf>() );\n CALL_SUBTEST( lu_verify_assert<MatrixXcd>() );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <complex>\n\nnamespace meep_math{\n\t\/\/TODO: cache this somewhere or we're gonna be slow\n\tdouble binomial_cdf(int successes, int trials, long double p){\n\t\tlong double cdf = 0.0;\n\t\tfor(int i = 0; i < k; i++){\n\t\t\tcdf += meep_math::binomial_pdf(i, trials, p);\n\t\t}\n\t\treturn cdf;\n\t}\n\n\tdouble binomial_pdf(int successes, int trials, long double p){\n\t\treturn (double)meep_math::binomial_coeff(trials, successes) * (p ** successes) * (1 - p) ** (trials - successes);\n\t}\n\n\t\/\/n choose k\n\tint binomial_coeff(int n, int k){\n\t\tif (k > n){\n\t\t\tthrow std::runtime_error(\"error calculating binomial with n = \" << n << \" and k = \" << k << std::endl);\n\t\t}\n\t\tint product = 1;\n\t\tfor(int i=1; i <= k; i++){\n\t\t\tproduct *= ((n + 1 - i) \/ i);\n\t\t}\n\t\treturn product;\n\t}\n\n\tstd::array<double,2> solve_quadratic(double a, double b, double c){\n\t\tstd::array<double,2> x = {0.0,0.0};\n\t\tx[0] = (-b - sqrt(std::pow(b,2) - 4 * a * c))\/(2 * a);\n\t\tx[1] = (-b + sqrt(std::pow(b,2) - 4 * a * c))\/(2 * a);\n\t}\n\n\t\/\/https:\/\/en.wikipedia.org\/wiki\/Quartic_function#Solving_a_quartic_equation\n\tstd::array<double,4> solve_quartic(double a, double b, double c, double d, double e){\n\t\tstd::array<double,4> x = {0.0,0.0,0.0,0.0};\n\t\tdouble p = (8.0 * a * c - 3 * b^2)\/(8.0 * a^2);\n\t\tdouble q = (b^3 - 4.0 * a * b * c + 8.0 * a^2 * d)\/(8.0 * a^3);\n\t\tdouble disc = 256 * a^3 * e^3 - 192 * a^2 * b * d * e^2 - 128 * a^2 * c^2 * e^2 + 144 * a^2 * c * d^2 * e - 27 * a^2 * d^4\n\t\t\t\t\t\t+ 144 * a * b^2 * c * e^2 - 6 * a * b^2 * d^2 * e - 80 * a * b * c^2 * d * e + 18 * a * b * c * d^3\n\t\t\t\t\t\t+ 16 * a * c^4 * e - 4 * a * c^3 * d^2 - 27 * b^4 * e^2 + 18 * b^3 * c * d * e - 4 * b^3 * d^3\n\t\t\t\t\t\t- 4 * b^2 * c^3 * e + b^2 * c^2 * d^2;\n\t\tdouble disc0 = c^2 - 3.0 * b * d + 12.0 * a * e;\n\t\tdouble disc1 = 2.0 * c^3 - 9 * b * c * d + 27 * b^2 * e + 27 * a * d^2 - 72 * a * c * e;\n\t\tstd::complex<double> Q = std::pow((disc1 + std::sqrt(-27 * disc))\/2,1\/3);\n\t\tdouble S = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\n\t\t\/\/check special cases\n\t\tif(disc != 0 && disc0 == 0){\n\t\t\tQ = std::pow(disc1,1\/3);\n\t\t}\n\t\tif(S == 0){\n\t\t\tQ = Q * std::complex<double>(-0.5,std::sqrt(3)\/2);\n\t\t\tS = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\t\t\tif (S == 0){\n\t\t\t\tQ = Q * std::complex<double>(-0.5,-std::sqrt(3)\/2);\n\t\t\t\tS = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\t\t\t\tif (S == 0){\n\t\t\t\t\tstd::array<double,2> z = meep_math::solve_quadratic(a,c,e);\n\t\t\t\t\tx[0] = std::sqrt(z[0]);\n\t\t\t\t\tx[1] = -std::sqrt(z[0]);\n\t\t\t\t\tx[2] = std::sqrt(z[1]);\n\t\t\t\t\tx[3] = -std::sqrt(z[2]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/compute roots\n\t\tx[0] = -b \/ (4.0 * a) - S - 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[1] = -b \/ (4.0 * a) - S + 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[2] = -b \/ (4.0 * a) + S - 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[3] = -b \/ (4.0 * a) + S + 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\treturn x;\n\t}\n}<commit_msg>shore up the quartic solver<commit_after>#include <complex>\n\nnamespace meep_math{\n\t\/\/TODO: cache this somewhere or we're gonna be slow\n\tdouble binomial_cdf(int successes, int trials, long double p){\n\t\tlong double cdf = 0.0;\n\t\tfor(int i = 0; i < k; i++){\n\t\t\tcdf += meep_math::binomial_pdf(i, trials, p);\n\t\t}\n\t\treturn cdf;\n\t}\n\n\tdouble binomial_pdf(int successes, int trials, long double p){\n\t\treturn (double)meep_math::binomial_coeff(trials, successes) * (p ** successes) * (1 - p) ** (trials - successes);\n\t}\n\n\t\/\/n choose k\n\tint binomial_coeff(int n, int k){\n\t\tif (k > n){\n\t\t\tthrow std::runtime_error(\"error calculating binomial with n = \" << n << \" and k = \" << k << std::endl);\n\t\t}\n\t\tint product = 1;\n\t\tfor(int i=1; i <= k; i++){\n\t\t\tproduct *= ((n + 1 - i) \/ i);\n\t\t}\n\t\treturn product;\n\t}\n\n\tstd::array<double,2> solve_quadratic(double a, double b, double c){\n\t\tstd::array<double,2> x = {0.0,0.0};\n\t\tx[0] = (-b - sqrt(std::pow(b,2) - 4 * a * c))\/(2 * a);\n\t\tx[1] = (-b + sqrt(std::pow(b,2) - 4 * a * c))\/(2 * a);\n\t}\n\n\t\/\/https:\/\/en.wikipedia.org\/wiki\/Quartic_function#Solving_a_quartic_equation\n\tstd::array<double,4> solve_quartic(double a, double b, double c, double d, double e){\n\t\tstd::array<double,4> x = {0.0,0.0,0.0,0.0};\n\t\tdouble p = (8.0 * a * c - 3 * b^2)\/(8.0 * a^2);\n\t\tdouble q = (b^3 - 4.0 * a * b * c + 8.0 * a^2 * d)\/(8.0 * a^3);\n\t\tdouble disc = 256 * a^3 * e^3 - 192 * a^2 * b * d * e^2 - 128 * a^2 * c^2 * e^2 + 144 * a^2 * c * d^2 * e - 27 * a^2 * d^4\n\t\t\t\t\t\t+ 144 * a * b^2 * c * e^2 - 6 * a * b^2 * d^2 * e - 80 * a * b * c^2 * d * e + 18 * a * b * c * d^3\n\t\t\t\t\t\t+ 16 * a * c^4 * e - 4 * a * c^3 * d^2 - 27 * b^4 * e^2 + 18 * b^3 * c * d * e - 4 * b^3 * d^3\n\t\t\t\t\t\t- 4 * b^2 * c^3 * e + b^2 * c^2 * d^2;\n\t\tdouble disc0 = c^2 - 3.0 * b * d + 12.0 * a * e;\n\t\tdouble disc1 = 2.0 * c^3 - 9 * b * c * d + 27 * b^2 * e + 27 * a * d^2 - 72 * a * c * e;\n\t\tstd::complex<double> Q;\n\t\tif(disc != 0 && disc0 == 0){\n\t\t\tQ = std::pow(disc1,1\/3); \/\/special case\n\t\t}\n\t\telse{\n\t\t\tQ = std::pow((disc1 + std::sqrt(-27 * disc))\/2,1\/3);\t\n\t\t}\n\t\tdouble S = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\n\t\t\/\/special case. when S == 0 we try other cube roots.\n\t\t\/\/see https:\/\/en.wikipedia.org\/wiki\/Cube_root\n\t\t\/\/if none of them work, it's because the depressed quartic is biquadratic\n\t\tif(S == 0){\n\t\t\tstd::complex<double> old_Q = Q;\n\t\t\tQ = old_Q * std::complex<double>(-0.5,std::sqrt(3)\/2);\n\t\t\tS = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\t\t\tif (S == 0){\n\t\t\t\tQ = old_Q * std::complex<double>(-0.5,-std::sqrt(3)\/2);\n\t\t\t\tS = 0.5 * std::sqrt(-(2.0\/3.0)*p + 1.0\/(3.0*a) * (Q + disc0\/Q));\n\t\t\t\tif (S == 0){\n\t\t\t\t\tstd::array<double,2> z = meep_math::solve_quadratic(a,c,e);\n\t\t\t\t\tx[0] = std::sqrt(z[0]);\n\t\t\t\t\tx[1] = -std::sqrt(z[0]);\n\t\t\t\t\tx[2] = std::sqrt(z[1]);\n\t\t\t\t\tx[3] = -std::sqrt(z[2]);\n\t\t\t\t\treturn x;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/compute roots\n\t\tx[0] = -b \/ (4.0 * a) - S - 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[1] = -b \/ (4.0 * a) - S + 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[2] = -b \/ (4.0 * a) + S - 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\tx[3] = -b \/ (4.0 * a) + S + 0.5 * std::sqrt(-4.0 * S^2 - 2*p + q\/S);\n\t\treturn x;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Justin Madsen\n\/\/ =============================================================================\n\/\/\n\/\/ Tracked vehicle model built from subsystems.\n\/\/ Location of subsystems hard-coded for M113 vehicle\n\/\/ TODO: specify this w\/ JSON input data file\n\/\/\n\/\/ =============================================================================\n\n#include <cstdio>\n\n#include \"assets\/ChCylinderShape.h\"\n#include \"assets\/ChTriangleMeshShape.h\"\n#include \"assets\/ChTexture.h\"\n#include \"assets\/ChColorAsset.h\"\n#include \"assets\/ChAssetLevel.h\"\n#include \"physics\/ChGlobal.h\"\n\n#include \"TrackVehicle.h\"\n\n#include \"subsys\/trackSystem\/TrackSystem.h\"\n#include \"subsys\/driveline\/TrackDriveline.h\"\n\n#include \"utils\/ChUtilsInputOutput.h\"\n#include \"utils\/ChUtilsData.h\"\n\n\/\/ collision mesh\n#include \"geometry\/ChCTriangleMeshSoup.h\"\n\nnamespace chrono {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\nconst size_t TrackVehicle::m_num_tracks = 2; \/\/ number of trackSystems to create\nconst size_t TrackVehicle::m_num_engines = 1; \/\/ number of powertrains (and drivelines) to create\n\nconst ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); \/\/ relative to chassis COG\nconst ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); \/\/ relative to chassis COG\n\nconst double TrackVehicle::m_mass = 5489.2; \/\/ chassis sprung mass\nconst ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.); \/\/ COM location, relative to body Csys REF frame\nconst ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2); \/\/ chassis inertia (roll,yaw,pitch)\n\nconst std::string TrackVehicle::m_meshName(\"M113_chassis\");\nconst std::string TrackVehicle::m_meshFile = utils::GetModelDataFile(\"M113\/Chassis_XforwardYup.obj\");\nconst ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));\nconst ChVector<> TrackVehicle::m_chassisBoxSize(2.0, 0.6, 0.75); \/\/ length, height, width HALF DIMS\n\n\/\/\/ constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff\nTrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide)\n : m_vis(chassisVis),\n m_collide(chassisCollide),\n m_ownsSystem(true),\n m_stepsize(1e-3)\n{\n \/\/ Integration and Solver settings\n SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);\n SetIterLCPmaxItersSpeed(150);\n SetIterLCPmaxItersStab(150);\n SetMaxPenetrationRecoverySpeed(2.0);\n \/\/ SetIterLCPomega(2.0);\n \/\/ SetIterLCPsharpnessLambda(2.0);\n \n\n \/\/ create the chassis body \n m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);\n m_chassis->SetIdentifier(0);\n m_chassis->SetNameString(name);\n m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));\n \/\/ basic body info\n m_chassis->SetMass(m_mass);\n m_chassis->SetInertiaXX(m_inertia);\n\n \/\/ add visualization assets to the chassis\n AddVisualization();\n\n \/\/ m_chassis->SetBodyFixed(true);\n \/\/ add the chassis body to the system\n Add(m_chassis);\n\n \/\/ resize all vectors for the number of track systems\n m_TrackSystems.resize(m_num_tracks);\n m_TrackSystem_locs.resize(m_num_tracks);\n \/\/ Right and Left track System relative locations, respectively\n m_TrackSystem_locs[0] = m_trackPos_Right;\n m_TrackSystem_locs[1] = m_trackPos_Left;\n\n \/\/ Each trackSystem has its own driveline and powertrain, so the left and right\n \/\/ sides can have power applied independently\n m_drivelines.resize(m_num_engines);\n m_ptrains.resize(m_num_engines);\n\n \/\/ create track systems\n for (int i = 0; i < m_num_tracks; i++) {\n m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem(\"track chain \"+std::to_string(i), i) );\n }\n \n \/\/ create the powertrain and drivelines\n for (int j = 0; j < m_num_engines; j++)\n {\n m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline(\"driveline \"+std::to_string(j)) );\n m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain(\"powertrain \"+std::to_string(j)) );\n \n }\n\n \/\/ TODO: add brakes. Perhaps they are a part of the suspension subsystem?\n\n}\n\n\nTrackVehicle::~TrackVehicle()\n{\n if(m_ownsSystem)\n delete m_system;\n}\n\n\/\/ Set any collision geometry on the hull, then Initialize() all subsystems\nvoid TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)\n{\n \/\/ move the chassis REF frame to the specified initial position\/orientation\n m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));\n\n \/\/ add collision geometry to the chassis\n AddCollisionGeometry();\n\n \/\/ initialize the subsystems with the initial c-sys and specified offsets\n for (int i = 0; i < m_num_tracks; i++)\n {\n m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);\n }\n\n \/\/ initialize the powertrain, drivelines\n for (int j = 0; j < m_num_engines; j++)\n {\n size_t driveGear_R_idx = 2*j;\n size_t driveGear_L_idx = 2*j + 1;\n m_drivelines[j]->Initialize(m_chassis,\n m_TrackSystems[driveGear_R_idx]->GetDriveGear(),\n m_TrackSystems[driveGear_L_idx]->GetDriveGear());\n m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());\n }\n\n}\n\n\nvoid TrackVehicle::Update(double\ttime,\n const std::vector<double>& throttle,\n const std::vector<double>& braking)\n{\n assert( throttle.size() >= m_num_tracks);\n assert( braking.size() >= m_num_tracks );\n \/\/ update left and right powertrains, with the new left and right throttle\/shaftspeed\n for(int i = 0; i < m_num_engines; i++)\n {\n m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() );\n }\n\n}\n\nvoid TrackVehicle::AddVisualization()\n{\n \/\/ add visual geometry asset to the chassis, if enabled\n switch (m_vis) {\n case VisualizationType::NONE:\n {\n \/\/ put a sphere at the chassis COM and at the REF point\n ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape);\n COMsphere->GetSphereGeometry().rad = 0.1;\n COMsphere->Pos = m_COM;\n m_chassis->AddAsset(COMsphere);\n \/\/ make the COM sphere blue\n ChSharedPtr<ChColorAsset> blue(new ChColorAsset(0.1f, 0.2f, 0.8f));\n m_chassis->AddAsset(blue);\n \n \/\/ to give the REF sphere a different color, add it to the level first.\n ChSharedPtr<ChAssetLevel> ref_level(new ChAssetLevel);\n ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape);\n REFsphere->GetSphereGeometry().rad = 0.1;\n REFsphere->Pos = ChVector<>(0,0,0); \/\/ REF should be at the body c-sys origin\n ref_level->AddAsset(REFsphere);\n \/\/ make the REF sphere red\n ChSharedPtr<ChColorAsset> red(new ChColorAsset(0.8f, 0.2f, 0.1f) );\n ref_level->AddAsset(red);\n \/\/ add the level to the body\n m_chassis->AddAsset(ref_level);\n\n break;\n }\n case VisualizationType::PRIMITIVES:\n {\n ChSharedPtr<ChBoxShape> box(new ChBoxShape);\n box->GetBoxGeometry().SetLengths(m_chassisBoxSize );\n m_chassis->AddAsset(box);\n break;\n }\n case VisualizationType::MESH:\n {\n geometry::ChTriangleMeshConnected trimesh;\n trimesh.LoadWavefrontMesh(m_meshFile, true, true);\n\n ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);\n trimesh_shape->SetMesh(trimesh);\n trimesh_shape->SetName(\"chassis triMesh\");\n m_chassis->AddAsset(trimesh_shape);\n\n break;\n }\n } \/\/ end switch\n\n\n}\n\nvoid TrackVehicle::AddCollisionGeometry()\n{\n \/\/ add collision geometrey to the chassis, if enabled\n if( m_collide == CollisionType::NONE)\n {\n m_chassis->SetCollide(false);\n return;\n }\n m_chassis->SetCollide(true);\n m_chassis->GetCollisionModel()->ClearModel();\n\n \/\/ 1 cm outwards, 0.5 inwards for envelope and margin, respectfully.\n m_chassis->GetCollisionModel()->SetSafeMargin(0.005);\t\/\/ inward safe margin\n\tm_chassis->GetCollisionModel()->SetEnvelope(0.010);\t\t\/\/ distance of the outward \"collision envelope\"\n\n switch (m_collide) {\n case CollisionType::PRIMITIVES:\n {\n \/\/ use a simple box\n m_chassis->GetCollisionModel()->AddBox(m_chassisBoxSize.x, m_chassisBoxSize.y, m_chassisBoxSize.z);\n\n break;\n }\n case CollisionType::MESH:\n {\n \/\/ use a triangle mesh\n \n\t\tgeometry::ChTriangleMeshSoup temp_trianglemesh; \n\t\t\n \/\/ TODO: fill the triangleMesh here with some track shoe geometry\n\n \/\/ is there an offset??\n double shoelength = 0.2;\n ChVector<> mesh_displacement(shoelength*0.5,0,0); \/\/ since mesh origin is not in body center of mass\n m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);\n\n break;\n }\n case CollisionType::CONVEXHULL:\n {\n \/\/ use convex hulls, loaded from file\n ChStreamInAsciiFile chull_file(GetChronoDataFile(\"track_shoe.chulls\").c_str());\n \/\/ transform the collision geometry as needed\n double mangle = 45.0; \/\/ guess\n ChQuaternion<>rot;\n rot.Q_from_AngAxis(mangle*(CH_C_PI\/180.),VECT_X);\n ChMatrix33<> rot_offset(rot);\n ChVector<> disp_offset(0,0,0); \/\/ no displacement offset\n m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);\n break;\n }\n default:\n \/\/ no collision geometry\n GetLog() << \"not recognized CollisionType: \" << (int)m_collide <<\" for chassis \\n\";\n m_chassis->SetCollide(false);\n return;\n } \/\/ end switch\n\n \/\/ set the collision family\n m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL );\n \/\/ don't collide with rolling elements or tracks\n \/\/ m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) );\n m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) );\n\n m_chassis->GetCollisionModel()->BuildModel();\n}\n\nvoid TrackVehicle::Advance(double step)\n{\n double t = 0;\n double settlePhaseA = 0.001;\n double settlePhaseB = 0.01;\n while (t < step) {\n double h = std::min<>(m_stepsize, step - t);\n if( GetChTime() < settlePhaseA )\n {\n h = 1e-5;\n } else if ( GetChTime() < settlePhaseB )\n {\n h = 1e-4;\n }\n DoStepDynamics(h);\n t += h;\n }\n}\n\n\ndouble TrackVehicle::GetIdlerForce(size_t side)\n{\n assert(side < m_num_tracks);\n ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react();\n\n return out_force.Length();\n}\n\n} \/\/ end namespace chrono\n<commit_msg>remove things already in the abstract class functions. Add the pure virtual function defs<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Justin Madsen\n\/\/ =============================================================================\n\/\/\n\/\/ Tracked vehicle model built from subsystems.\n\/\/ Location of subsystems hard-coded for M113 vehicle\n\/\/ TODO: specify this w\/ JSON input data file\n\/\/\n\/\/ =============================================================================\n\n#include <cstdio>\n\n#include \"assets\/ChCylinderShape.h\"\n#include \"assets\/ChTriangleMeshShape.h\"\n#include \"assets\/ChTexture.h\"\n#include \"assets\/ChColorAsset.h\"\n#include \"assets\/ChAssetLevel.h\"\n#include \"physics\/ChGlobal.h\"\n\n#include \"TrackVehicle.h\"\n\n#include \"subsys\/trackSystem\/TrackSystem.h\"\n#include \"subsys\/driveline\/TrackDriveline.h\"\n\n#include \"utils\/ChUtilsInputOutput.h\"\n#include \"utils\/ChUtilsData.h\"\n\n\/\/ collision mesh\n#include \"geometry\/ChCTriangleMeshSoup.h\"\n\nnamespace chrono {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\nconst ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); \/\/ relative to chassis COG\nconst ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); \/\/ relative to chassis COG\n\nconst double TrackVehicle::m_mass = 5489.2; \/\/ chassis sprung mass\nconst ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.); \/\/ COM location, relative to body Csys REF frame\nconst ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2); \/\/ chassis inertia (roll,yaw,pitch)\n\nconst std::string TrackVehicle::m_meshName(\"M113_chassis\");\nconst std::string TrackVehicle::m_meshFile = utils::GetModelDataFile(\"M113\/Chassis_XforwardYup.obj\");\nconst ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));\nconst ChVector<> TrackVehicle::m_chassisBoxSize(2.0, 0.6, 0.75); \/\/ length, height, width HALF DIMS\n\n\/\/\/ constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff\nTrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide)\n : m_vis(chassisVis),\n m_collide(chassisCollide),\n m_num_tracks(2)\n{\n \/\/ Integration and Solver settings, set in ChTrackVehicle\n\n \/\/ create the chassis body \n m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);\n m_chassis->SetIdentifier(0);\n m_chassis->SetNameString(name);\n m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));\n \/\/ basic body info\n m_chassis->SetMass(m_mass);\n m_chassis->SetInertiaXX(m_inertia);\n\n \/\/ add visualization assets to the chassis\n AddVisualization();\n\n \/\/ m_chassis->SetBodyFixed(true);\n \/\/ add the chassis body to the system\n m_system->Add(m_chassis);\n\n \/\/ resize all vectors for the number of track systems\n m_TrackSystems.resize(m_num_tracks);\n m_TrackSystem_locs.resize(m_num_tracks);\n \/\/ Right and Left track System relative locations, respectively\n m_TrackSystem_locs[0] = m_trackPos_Right;\n m_TrackSystem_locs[1] = m_trackPos_Left;\n\n \/\/ two drive Gears, like a 2WD driven vehicle.\n m_num_engines = 1;\n m_drivelines.resize(m_num_engines);\n m_ptrains.resize(m_num_engines);\n\n \/\/ create track systems\n for (int i = 0; i < m_num_tracks; i++) {\n m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem(\"track chain \"+std::to_string(i), i) );\n }\n \n \/\/ create the powertrain and drivelines\n for (int j = 0; j < m_num_engines; j++)\n {\n m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline(\"driveline \"+std::to_string(j)) );\n m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain(\"powertrain \"+std::to_string(j)) );\n \n }\n\n \/\/ TODO: add brakes. Perhaps they are a part of the suspension subsystem?\n\n}\n\n\nTrackVehicle::~TrackVehicle()\n{\n if(m_ownsSystem)\n delete m_system;\n}\n\n\/\/ Set any collision geometry on the hull, then Initialize() all subsystems\nvoid TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)\n{\n \/\/ move the chassis REF frame to the specified initial position\/orientation\n m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));\n\n \/\/ add collision geometry to the chassis\n AddCollisionGeometry();\n\n \/\/ initialize the subsystems with the initial c-sys and specified offsets\n for (int i = 0; i < m_num_tracks; i++)\n {\n m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);\n }\n\n \/\/ initialize the powertrain, drivelines\n for (int j = 0; j < m_num_engines; j++)\n {\n size_t driveGear_R_idx = 2*j;\n size_t driveGear_L_idx = 2*j + 1;\n m_drivelines[j]->Initialize(m_chassis,\n m_TrackSystems[driveGear_R_idx]->GetDriveGear(),\n m_TrackSystems[driveGear_L_idx]->GetDriveGear());\n m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());\n }\n\n}\n\n\nvoid TrackVehicle::Update(double\ttime,\n const std::vector<double>& throttle,\n const std::vector<double>& braking)\n{\n assert( throttle.size() >= m_num_tracks);\n assert( braking.size() >= m_num_tracks );\n \/\/ update left and right powertrains, with the new left and right throttle\/shaftspeed\n for(int i = 0; i < m_num_engines; i++)\n {\n m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() );\n }\n\n}\n\nvoid TrackVehicle::AddVisualization()\n{\n \/\/ add visual geometry asset to the chassis, if enabled\n switch (m_vis) {\n case VisualizationType::NONE:\n {\n \/\/ put a sphere at the chassis COM and at the REF point\n ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape);\n COMsphere->GetSphereGeometry().rad = 0.1;\n COMsphere->Pos = m_COM;\n m_chassis->AddAsset(COMsphere);\n \/\/ make the COM sphere blue\n ChSharedPtr<ChColorAsset> blue(new ChColorAsset(0.1f, 0.2f, 0.8f));\n m_chassis->AddAsset(blue);\n \n \/\/ to give the REF sphere a different color, add it to the level first.\n ChSharedPtr<ChAssetLevel> ref_level(new ChAssetLevel);\n ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape);\n REFsphere->GetSphereGeometry().rad = 0.1;\n REFsphere->Pos = ChVector<>(0,0,0); \/\/ REF should be at the body c-sys origin\n ref_level->AddAsset(REFsphere);\n \/\/ make the REF sphere red\n ChSharedPtr<ChColorAsset> red(new ChColorAsset(0.8f, 0.2f, 0.1f) );\n ref_level->AddAsset(red);\n \/\/ add the level to the body\n m_chassis->AddAsset(ref_level);\n\n break;\n }\n case VisualizationType::PRIMITIVES:\n {\n ChSharedPtr<ChBoxShape> box(new ChBoxShape);\n box->GetBoxGeometry().SetLengths(m_chassisBoxSize );\n m_chassis->AddAsset(box);\n break;\n }\n case VisualizationType::MESH:\n {\n geometry::ChTriangleMeshConnected trimesh;\n trimesh.LoadWavefrontMesh(m_meshFile, true, true);\n\n ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);\n trimesh_shape->SetMesh(trimesh);\n trimesh_shape->SetName(\"chassis triMesh\");\n m_chassis->AddAsset(trimesh_shape);\n\n break;\n }\n } \/\/ end switch\n\n\n}\n\nvoid TrackVehicle::AddCollisionGeometry()\n{\n \/\/ add collision geometrey to the chassis, if enabled\n if( m_collide == CollisionType::NONE)\n {\n m_chassis->SetCollide(false);\n return;\n }\n m_chassis->SetCollide(true);\n m_chassis->GetCollisionModel()->ClearModel();\n\n \/\/ 1 cm outwards, 0.5 inwards for envelope and margin, respectfully.\n m_chassis->GetCollisionModel()->SetSafeMargin(0.005);\t\/\/ inward safe margin\n\tm_chassis->GetCollisionModel()->SetEnvelope(0.010);\t\t\/\/ distance of the outward \"collision envelope\"\n\n switch (m_collide) {\n case CollisionType::PRIMITIVES:\n {\n \/\/ use a simple box\n m_chassis->GetCollisionModel()->AddBox(m_chassisBoxSize.x, m_chassisBoxSize.y, m_chassisBoxSize.z);\n\n break;\n }\n case CollisionType::MESH:\n {\n \/\/ use a triangle mesh\n \n\t\tgeometry::ChTriangleMeshSoup temp_trianglemesh; \n\t\t\n \/\/ TODO: fill the triangleMesh here with some track shoe geometry\n\n \/\/ is there an offset??\n double shoelength = 0.2;\n ChVector<> mesh_displacement(shoelength*0.5,0,0); \/\/ since mesh origin is not in body center of mass\n m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);\n\n break;\n }\n case CollisionType::CONVEXHULL:\n {\n \/\/ use convex hulls, loaded from file\n ChStreamInAsciiFile chull_file(GetChronoDataFile(\"track_shoe.chulls\").c_str());\n \/\/ transform the collision geometry as needed\n double mangle = 45.0; \/\/ guess\n ChQuaternion<>rot;\n rot.Q_from_AngAxis(mangle*(CH_C_PI\/180.),VECT_X);\n ChMatrix33<> rot_offset(rot);\n ChVector<> disp_offset(0,0,0); \/\/ no displacement offset\n m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);\n break;\n }\n default:\n \/\/ no collision geometry\n GetLog() << \"not recognized CollisionType: \" << (int)m_collide <<\" for chassis \\n\";\n m_chassis->SetCollide(false);\n return;\n } \/\/ end switch\n\n \/\/ set the collision family\n m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL );\n \/\/ don't collide with rolling elements or tracks\n \/\/ m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) );\n m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) );\n\n m_chassis->GetCollisionModel()->BuildModel();\n}\n\nvoid TrackVehicle::Advance(double step)\n{\n double t = 0;\n double settlePhaseA = 0.001;\n double settlePhaseB = 0.01;\n while (t < step) {\n double h = std::min<>(m_stepsize, step - t);\n if( m_system->GetChTime() < settlePhaseA )\n {\n h = 1e-5;\n } else if ( m_system->GetChTime() < settlePhaseB )\n {\n h = 1e-4;\n }\n m_system->DoStepDynamics(h);\n t += h;\n }\n}\n\n\ndouble TrackVehicle::GetIdlerForce(size_t side)\n{\n assert(side < m_num_tracks);\n ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react();\n\n return out_force.Length();\n}\n\n\ndouble TrackVehicle::GetDriveshaftSpeed(size_t idx) const\n{\n assert(idx < m_drivelines.size() );\n return m_drivelines[idx]->GetDriveshaftSpeed();\n}\n\n\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"<commit_before>#include \"optimizer.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass AddressAnalyzer : Visitor {\n public:\n int lane_a, lane_b;\n using result_type = std::pair<bool, int>;\n std::map<Expr, result_type> memo;\n\n AddressAnalyzer(int lane_a, int lane_b)\n : Visitor(Visitor::Order::parent_first), lane_a(lane_a), lane_b(lane_b) {\n }\n\n result_type run(Expr &expr) {\n expr.accept(*this);\n return memo[expr];\n }\n\n void visit(Expr &expr) override {\n if (memo.find(expr) != memo.end()) {\n return;\n }\n\n std::vector<result_type> ch_results;\n\n for (int i = 0; i < (int)expr->ch.size(); i++) {\n ch_results.push_back(memo[expr->ch[i]]);\n }\n\n result_type ret{false, 0};\n auto t = expr->type;\n if (t == NodeType::binary) {\n \/\/ TODO: sub\n \/\/ TODO: imm + val\n if (expr->binary_type == BinaryType::add) {\n if (expr[1]->type == NodeType::imm) {\n if (ch_results[0].first) {\n ret = {true, ch_results[0].second + expr[1]->value<int>(lane_b) -\n expr[1]->value<int>(lane_a)};\n }\n }\n }\n } else if (t == NodeType::adapter_load) {\n \/\/ adapter_id\n if (expr[0]->value<int>(lane_a) == expr[0]->value<int>(lane_b)) {\n \/\/ adapter offset\n if (expr[1]->value<int>(lane_a) == expr[1]->value<int>(lane_b)) {\n ret = {true, 0};\n }\n }\n }\n memo[expr] = ret;\n }\n};\n\nbool Optimizer::search_and_replace(Expr &expr) {\n if (visited.find(expr) == visited.end()) {\n visited.insert(expr);\n } else {\n return false;\n }\n for (auto &ch : expr->ch) {\n bool ret = search_and_replace(ch);\n if (ret)\n return true;\n }\n return optimize(expr);\n}\n\nclass ContinuousMemOptimizer : public Optimizer {\n public:\n bool optimize(Expr &expr) override {\n if (expr->type == NodeType::load || expr->type == NodeType::store) {\n auto &ptr = expr._pointer();\n auto &addr_node = expr._pointer()._address();\n bool all_same = true;\n\n for (int i = 0; i < addr_node->lanes; i++) {\n if (addr_node->snode_ptr(i) != addr_node->snode_ptr(0))\n all_same = false;\n }\n\n bool incremental = true;\n bool regular_elements = true;\n int offset_start;\n int offset_inc;\n\n \/\/ only consider the last one.\n auto &index_node = expr._pointer()->ch.back();\n\n if (index_node->type != NodeType::index) {\n return false;\n }\n bool indirect = false;\n if (kernel->program.current_snode->type == SNodeType::indirect &&\n index_node->index_id(0) == kernel->program.current_snode->index_id) {\n TC_INFO(\"Skipped optimization since it is indirect.\");\n indirect = true;\n }\n\n \/\/ TODO: check non-last indices are uniform\n if (index_node->type == NodeType::index) {\n offset_start = index_node->index_offset(0);\n offset_inc = index_node->index_offset(1) - offset_start;\n for (int i = 0; i + 1 < addr_node->lanes; i++) {\n if (index_node->index_offset(i) + offset_inc !=\n index_node->index_offset(i + 1)) {\n incremental = false;\n }\n }\n } else {\n \/\/ computed indices\n \/\/ case I: adapter load\n incremental = true;\n offset_start = 0; \/\/ useless\n offset_inc = 0;\n\n \/\/ second DFS to match two lanes\n if (all_same) {\n for (int i = 0; i + 1 < index_node->lanes; i++) {\n auto ret = AddressAnalyzer(i, i + 1).run(index_node);\n if (!ret.first) {\n incremental = false;\n } else {\n if (i == 0) {\n offset_inc = ret.second;\n } else if (offset_inc != ret.second) {\n incremental = false;\n break;\n }\n }\n }\n }\n }\n\n for (int i = 0; i < addr_node->lanes; i++) {\n auto p = addr_node->snode_ptr(i)->parent;\n if (p != addr_node->snode_ptr(0)->parent)\n regular_elements = false;\n if (p->child_id(addr_node->snode_ptr(i)) != i)\n regular_elements = false;\n }\n\n auto snode = addr_node->snode_ptr(0);\n \/\/ continuous index, same element\n bool vpointer_case_1 =\n incremental && offset_start == 0 && offset_inc == 1 &&\n snode->parent->type == SNodeType::fixed && all_same;\n \/\/ continuous element, same index\n bool vpointer_case_2 = regular_elements && incremental && offset_inc == 0;\n bool vpointer = !indirect && (vpointer_case_1 || vpointer_case_2);\n\n if (vpointer) {\n \/\/ replace load with vload\n if (expr->type == NodeType::load) {\n TC_INFO(\"Optimized load to vloadu\");\n auto vload = Expr::create(NodeType::vload, addr_node);\n vload->ch.resize(ptr->ch.size());\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n TC_ASSERT(c->lanes == 8);\n if (c->type == NodeType::index)\n c->set_lanes(1);\n vload->ch[i] = c;\n }\n vload->set_similar(expr);\n expr.set(vload);\n return true;\n } else {\n TC_INFO(\"Optimized store to vstoreu\");\n auto vstore = Expr::create(NodeType::vstore, addr_node, expr->ch[1]);\n vstore->ch.resize(ptr->ch.size() + 1);\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n TC_ASSERT(c->lanes == 8);\n if (c->type == NodeType::index)\n c->set_lanes(1);\n vstore->ch[i + 1] = c;\n }\n vstore->set_similar(expr);\n expr.set(vstore);\n return true;\n }\n }\n }\n return false;\n }\n};\n\nclass GatherMemOptimizer : public Optimizer {\n public:\n bool optimize(Expr &expr) override {\n if (expr->type != NodeType::load)\n return false;\n auto &ptr = expr._pointer();\n auto &addr_node = expr._pointer()._address();\n\n for (int i = 0; i < addr_node->lanes; i++) {\n if (addr_node->snode_ptr(i) != addr_node->snode_ptr(0))\n return false;\n }\n\n \/\/ only consider the last one.\n auto &index_node = expr._pointer()->ch.back();\n\n if (index_node->type != NodeType::index) {\n \/\/ return false;\n }\n \/*\n if (kernel->program.current_snode->type == SNodeType::indirect &&\n index_node->index_id(0) == kernel->program.current_snode->index_id) {\n TC_INFO(\"Skipped optimization since it is indirect.\");\n }\n *\/\n\n \/\/ TODO: check non-last indices are uniform\n auto snode = addr_node->snode_ptr(0);\n \/\/ continuous index, same element\n\n if (snode->parent->type == SNodeType::fixed) {\n TC_INFO(\"Optimized store to gather\"); \/\/ gather\n Expr gather = Expr::create(NodeType::gather, addr_node);\n gather->ch.resize(ptr->ch.size());\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n gather->ch[i] = c;\n }\n gather->set_similar(expr);\n expr.set(gather);\n return true;\n }\n return false;\n }\n};\nvoid apply_optimizers(Kernel &ker, Expr &expr) {\n ContinuousMemOptimizer().run(ker, expr);\n GatherMemOptimizer().run(ker, expr);\n}\n\nTLANG_NAMESPACE_END\n<commit_msg>vectorized load for dynamic<commit_after>#include \"optimizer.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass AddressAnalyzer : Visitor {\n public:\n int lane_a, lane_b;\n using result_type = std::pair<bool, int>;\n std::map<Expr, result_type> memo;\n\n AddressAnalyzer(int lane_a, int lane_b)\n : Visitor(Visitor::Order::parent_first), lane_a(lane_a), lane_b(lane_b) {\n }\n\n result_type run(Expr &expr) {\n expr.accept(*this);\n return memo[expr];\n }\n\n void visit(Expr &expr) override {\n if (memo.find(expr) != memo.end()) {\n return;\n }\n\n std::vector<result_type> ch_results;\n\n for (int i = 0; i < (int)expr->ch.size(); i++) {\n ch_results.push_back(memo[expr->ch[i]]);\n }\n\n result_type ret{false, 0};\n auto t = expr->type;\n if (t == NodeType::binary) {\n \/\/ TODO: sub\n \/\/ TODO: imm + val\n if (expr->binary_type == BinaryType::add) {\n if (expr[1]->type == NodeType::imm) {\n if (ch_results[0].first) {\n ret = {true, ch_results[0].second + expr[1]->value<int>(lane_b) -\n expr[1]->value<int>(lane_a)};\n }\n }\n }\n } else if (t == NodeType::adapter_load) {\n \/\/ adapter_id\n if (expr[0]->value<int>(lane_a) == expr[0]->value<int>(lane_b)) {\n \/\/ adapter offset\n if (expr[1]->value<int>(lane_a) == expr[1]->value<int>(lane_b)) {\n ret = {true, 0};\n }\n }\n }\n memo[expr] = ret;\n }\n};\n\nbool Optimizer::search_and_replace(Expr &expr) {\n if (visited.find(expr) == visited.end()) {\n visited.insert(expr);\n } else {\n return false;\n }\n for (auto &ch : expr->ch) {\n bool ret = search_and_replace(ch);\n if (ret)\n return true;\n }\n return optimize(expr);\n}\n\nclass ContinuousMemOptimizer : public Optimizer {\n public:\n bool optimize(Expr &expr) override {\n if (expr->type == NodeType::load || expr->type == NodeType::store) {\n auto &ptr = expr._pointer();\n auto &addr_node = expr._pointer()._address();\n bool all_same = true;\n\n for (int i = 0; i < addr_node->lanes; i++) {\n if (addr_node->snode_ptr(i) != addr_node->snode_ptr(0))\n all_same = false;\n }\n\n bool incremental = true;\n bool regular_elements = true;\n int offset_start;\n int offset_inc;\n\n \/\/ only consider the last one.\n auto &index_node = expr._pointer()->ch.back();\n\n if (index_node->type != NodeType::index) {\n return false;\n }\n bool indirect = false;\n if (kernel->program.current_snode->type == SNodeType::indirect &&\n index_node->index_id(0) == kernel->program.current_snode->index_id) {\n TC_INFO(\"Skipped optimization since it is indirect.\");\n indirect = true;\n }\n\n \/\/ TODO: check non-last indices are uniform\n if (index_node->type == NodeType::index) {\n offset_start = index_node->index_offset(0);\n offset_inc = index_node->index_offset(1) - offset_start;\n for (int i = 0; i + 1 < addr_node->lanes; i++) {\n if (index_node->index_offset(i) + offset_inc !=\n index_node->index_offset(i + 1)) {\n incremental = false;\n }\n }\n } else {\n \/\/ computed indices\n \/\/ case I: adapter load\n incremental = true;\n offset_start = 0; \/\/ useless\n offset_inc = 0;\n\n \/\/ second DFS to match two lanes\n if (all_same) {\n for (int i = 0; i + 1 < index_node->lanes; i++) {\n auto ret = AddressAnalyzer(i, i + 1).run(index_node);\n if (!ret.first) {\n incremental = false;\n } else {\n if (i == 0) {\n offset_inc = ret.second;\n } else if (offset_inc != ret.second) {\n incremental = false;\n break;\n }\n }\n }\n }\n }\n\n for (int i = 0; i < addr_node->lanes; i++) {\n auto p = addr_node->snode_ptr(i)->parent;\n if (p != addr_node->snode_ptr(0)->parent)\n regular_elements = false;\n if (p->child_id(addr_node->snode_ptr(i)) != i)\n regular_elements = false;\n }\n\n auto snode = addr_node->snode_ptr(0);\n \/\/ continuous index, same element\n bool vpointer_case_1 = incremental && offset_start == 0 &&\n offset_inc == 1 &&\n (snode->parent->type == SNodeType::fixed ||\n snode->parent->type == SNodeType::dynamic) &&\n all_same;\n \/\/ continuous element, same index\n bool vpointer_case_2 = regular_elements && incremental && offset_inc == 0;\n bool vpointer = !indirect && (vpointer_case_1 || vpointer_case_2);\n\n if (vpointer) {\n \/\/ replace load with vload\n if (expr->type == NodeType::load) {\n TC_INFO(\"Optimized load to vloadu\");\n auto vload = Expr::create(NodeType::vload, addr_node);\n vload->ch.resize(ptr->ch.size());\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n TC_ASSERT(c->lanes == kernel->program.config.simd_width);\n if (c->type == NodeType::index)\n c->set_lanes(1);\n vload->ch[i] = c;\n }\n vload->set_similar(expr);\n expr.set(vload);\n return true;\n } else {\n TC_INFO(\"Optimized store to vstoreu\");\n auto vstore = Expr::create(NodeType::vstore, addr_node, expr->ch[1]);\n vstore->ch.resize(ptr->ch.size() + 1);\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n TC_ASSERT(c->lanes == kernel->program.config.simd_width);\n if (c->type == NodeType::index)\n c->set_lanes(1);\n vstore->ch[i + 1] = c;\n }\n vstore->set_similar(expr);\n expr.set(vstore);\n return true;\n }\n }\n }\n return false;\n }\n};\n\nclass GatherMemOptimizer : public Optimizer {\n public:\n bool optimize(Expr &expr) override {\n if (expr->type != NodeType::load)\n return false;\n auto &ptr = expr._pointer();\n auto &addr_node = expr._pointer()._address();\n\n for (int i = 0; i < addr_node->lanes; i++) {\n if (addr_node->snode_ptr(i) != addr_node->snode_ptr(0))\n return false;\n }\n\n \/\/ only consider the last one.\n auto &index_node = expr._pointer()->ch.back();\n\n if (index_node->type != NodeType::index) {\n \/\/ return false;\n }\n \/*\n if (kernel->program.current_snode->type == SNodeType::indirect &&\n index_node->index_id(0) == kernel->program.current_snode->index_id) {\n TC_INFO(\"Skipped optimization since it is indirect.\");\n }\n *\/\n\n \/\/ TODO: check non-last indices are uniform\n auto snode = addr_node->snode_ptr(0);\n \/\/ continuous index, same element\n\n if (snode->parent->type == SNodeType::fixed) {\n TC_INFO(\"Optimized store to gather\"); \/\/ gather\n Expr gather = Expr::create(NodeType::gather, addr_node);\n gather->ch.resize(ptr->ch.size());\n for (int i = 1; i < (int)ptr->ch.size(); i++) {\n auto c = Expr::copy_from(ptr->ch[i]);\n gather->ch[i] = c;\n }\n gather->set_similar(expr);\n expr.set(gather);\n return true;\n }\n return false;\n }\n};\nvoid apply_optimizers(Kernel &ker, Expr &expr) {\n ContinuousMemOptimizer().run(ker, expr);\n GatherMemOptimizer().run(ker, expr);\n}\n\nTLANG_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/vespalib\/util\/slaveproc.h>\n\nusing vespalib::SlaveProc;\n\nTEST(\"simple run, ignore output\") { \n EXPECT_TRUE(SlaveProc::run(\"echo foo\"));\n}\n\nTEST(\"simple run, ignore output, failure\") {\n EXPECT_TRUE(!SlaveProc::run(\"false\"));\n}\n\nTEST(\"simple run, ignore output, timeout\") {\n EXPECT_TRUE(!SlaveProc::run(\"sleep 60\", 10));\n}\n\nTEST(\"simple run\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo -n foo\", out));\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"simple run, strip single-line trailing newline\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo foo\", out));\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"simple run, don't strip multi-line output\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo -e \\\"foo\\\\n\\\"\", out));\n EXPECT_EQUAL(out, \"foo\\n\\n\");\n}\n\nTEST(\"simple run with input\") {\n std::string in = \"bar\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(out, \"bar\");\n}\n\nTEST(\"simple run with input, strip single-line trailing newline\") {\n std::string in = \"bar\\n\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(out, \"bar\");\n}\n\nTEST(\"simple run with input, don't strip multi-line output\") {\n std::string in = \"bar\\n\\n\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(\"bar\\n\\n\", out);\n}\n\nTEST_MT(\"simple run, partial output due to timeout\", 2) {\n std::string out;\n std::vector<size_t> timeouts({150, 300, 3000, 6000, 60000});\n for (size_t timeout: timeouts) {\n fprintf(stderr, \"... verifying partial output with%s input (timeout = %zu)\\n\",\n (thread_id == 0) ? \"out\" : \"\", timeout);\n if (thread_id == 0) {\n out.clear();\n EXPECT_TRUE(!SlaveProc::run(\"echo foo; sleep 600; echo bar\", out, timeout));\n } else {\n out.clear();\n std::string in = \"ignored\\n\";\n EXPECT_TRUE(!SlaveProc::run(in, \"echo foo; sleep 600; echo bar\", out, timeout));\n }\n if (out == \"foo\") {\n break;\n }\n }\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"proc failure\") {\n SlaveProc proc(\"false\");\n \/\/ read with length 0 will wait for output\n EXPECT_TRUE(proc.read(NULL, 0) == 0);\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(proc.failed());\n}\n\nTEST(\"basic read\/write\") {\n int x;\n int read;\n char buf[64];\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\", 3));\n for (x = 0, read = 0; x < 10 && read < 3; ++x) {\n read += proc.read(buf + read, sizeof(buf) - read);\n }\n EXPECT_TRUE(read == 3 && memcmp(buf, \"foo\", 3) == 0);\n EXPECT_TRUE(proc.write(\"bar!\", 4));\n for (x = 0, read = 0; x < 10 && read < 4; ++x) {\n read += proc.read(buf + read, sizeof(buf) - read);\n }\n EXPECT_TRUE(read == 4 && memcmp(buf, \"bar!\", 4) == 0);\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(proc.read(buf, sizeof(buf)) == 0);\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(proc.read(buf, sizeof(buf)) == 0);\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"continuos run, readLine\") {\n std::string str;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\\n\", 4));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"foo\");\n EXPECT_TRUE(proc.write(\"bar!\\n\", 5));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"bar!\");\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"readLine, eof flushes last line\") {\n std::string str;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\\n\", 4));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"foo\");\n EXPECT_TRUE(proc.write(\"bar!\", 4));\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"bar!\");\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"long continuos run, readLine\") {\n std::string in;\n std::string out;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n for (uint32_t i = 0; i < 10000; ++i) {\n char num[32];\n sprintf(num, \"%d\", i);\n in.assign(\"long continous run, line \");\n in.append(num).append(\"\\n\");\n EXPECT_TRUE(proc.write(in.data(), in.length()));\n in.erase(in.size() - 1, 1);\n EXPECT_TRUE(proc.readLine(out));\n EXPECT_EQUAL(in, out);\n }\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }\n<commit_msg>avoid multiple levels of sub-processes<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/vespalib\/util\/slaveproc.h>\n\nusing vespalib::SlaveProc;\n\nTEST(\"simple run, ignore output\") { \n EXPECT_TRUE(SlaveProc::run(\"echo foo\"));\n}\n\nTEST(\"simple run, ignore output, failure\") {\n EXPECT_TRUE(!SlaveProc::run(\"false\"));\n}\n\nTEST(\"simple run, ignore output, timeout\") {\n EXPECT_TRUE(!SlaveProc::run(\"exec sleep 60\", 10));\n}\n\nTEST(\"simple run\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo -n foo\", out));\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"simple run, strip single-line trailing newline\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo foo\", out));\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"simple run, don't strip multi-line output\") {\n std::string out;\n EXPECT_TRUE(SlaveProc::run(\"echo -e \\\"foo\\\\n\\\"\", out));\n EXPECT_EQUAL(out, \"foo\\n\\n\");\n}\n\nTEST(\"simple run with input\") {\n std::string in = \"bar\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(out, \"bar\");\n}\n\nTEST(\"simple run with input, strip single-line trailing newline\") {\n std::string in = \"bar\\n\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(out, \"bar\");\n}\n\nTEST(\"simple run with input, don't strip multi-line output\") {\n std::string in = \"bar\\n\\n\";\n std::string out;\n EXPECT_TRUE(SlaveProc::run(in, \"cat\", out));\n EXPECT_EQUAL(\"bar\\n\\n\", out);\n}\n\nTEST_MT(\"simple run, partial output due to timeout\", 2) {\n std::string out;\n std::vector<size_t> timeouts({150, 300, 3000, 6000, 60000});\n const char *my_cmd = \"exec perl -e '$| = 1; print \\\"foo\\\\\\n\\\"; sleep(600); print \\\"bar\\\\\\n\\\"'\";\n for (size_t timeout: timeouts) {\n fprintf(stderr, \"... verifying partial output with%s input (timeout = %zu)\\n\",\n (thread_id == 0) ? \"out\" : \"\", timeout);\n if (thread_id == 0) {\n out.clear();\n EXPECT_TRUE(!SlaveProc::run(my_cmd, out, timeout));\n } else {\n out.clear();\n std::string in = \"ignored\\n\";\n EXPECT_TRUE(!SlaveProc::run(in, my_cmd, out, timeout));\n }\n if (out == \"foo\") {\n break;\n }\n }\n EXPECT_EQUAL(out, \"foo\");\n}\n\nTEST(\"proc failure\") {\n SlaveProc proc(\"false\");\n \/\/ read with length 0 will wait for output\n EXPECT_TRUE(proc.read(NULL, 0) == 0);\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(proc.failed());\n}\n\nTEST(\"basic read\/write\") {\n int x;\n int read;\n char buf[64];\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\", 3));\n for (x = 0, read = 0; x < 10 && read < 3; ++x) {\n read += proc.read(buf + read, sizeof(buf) - read);\n }\n EXPECT_TRUE(read == 3 && memcmp(buf, \"foo\", 3) == 0);\n EXPECT_TRUE(proc.write(\"bar!\", 4));\n for (x = 0, read = 0; x < 10 && read < 4; ++x) {\n read += proc.read(buf + read, sizeof(buf) - read);\n }\n EXPECT_TRUE(read == 4 && memcmp(buf, \"bar!\", 4) == 0);\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(proc.read(buf, sizeof(buf)) == 0);\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(proc.read(buf, sizeof(buf)) == 0);\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"continuos run, readLine\") {\n std::string str;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\\n\", 4));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"foo\");\n EXPECT_TRUE(proc.write(\"bar!\\n\", 5));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"bar!\");\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"readLine, eof flushes last line\") {\n std::string str;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n EXPECT_TRUE(proc.write(\"foo\\n\", 4));\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"foo\");\n EXPECT_TRUE(proc.write(\"bar!\", 4));\n EXPECT_TRUE(!proc.eof()); \/\/ not eof yet\n EXPECT_TRUE(proc.close()); \/\/ close stdin\n EXPECT_TRUE(!proc.eof()); \/\/ eof not detected yet\n EXPECT_TRUE(proc.readLine(str));\n EXPECT_EQUAL(str, \"bar!\");\n EXPECT_TRUE(proc.eof());\n EXPECT_TRUE(!proc.readLine(str));\n EXPECT_EQUAL(str, \"\");\n EXPECT_TRUE(proc.wait(60000));\n EXPECT_TRUE(!proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST(\"long continuos run, readLine\") {\n std::string in;\n std::string out;\n SlaveProc proc(\"cat\");\n\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n for (uint32_t i = 0; i < 10000; ++i) {\n char num[32];\n sprintf(num, \"%d\", i);\n in.assign(\"long continous run, line \");\n in.append(num).append(\"\\n\");\n EXPECT_TRUE(proc.write(in.data(), in.length()));\n in.erase(in.size() - 1, 1);\n EXPECT_TRUE(proc.readLine(out));\n EXPECT_EQUAL(in, out);\n }\n EXPECT_TRUE(proc.running());\n EXPECT_TRUE(!proc.failed());\n}\n\nTEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"subcomponentmanager.h\"\n#include \"model.h\"\n#include \"metainfo.h\"\n\n#include <utils\/hostosinfo.h>\n\n#include <QDir>\n#include <QMetaType>\n#include <QUrl>\n\nenum { debug = false };\n\nQT_BEGIN_NAMESPACE\n\n\/\/ Allow usage of QFileInfo in qSort\n\nstatic bool operator<(const QFileInfo &file1, const QFileInfo &file2)\n{\n return file1.filePath() < file2.filePath();\n}\n\n\nQT_END_NAMESPACE\n\nstatic inline QStringList importPaths() {\n QStringList paths;\n\n \/\/ env import paths\n QByteArray envImportPath = qgetenv(\"QML_IMPORT_PATH\");\n if (!envImportPath.isEmpty()) {\n paths = QString::fromLatin1(envImportPath)\n .split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);\n }\n\n return paths;\n}\n\nnamespace QmlDesigner {\nstatic const QString s_qmlFilePattern = QString(QLatin1String(\"*.qml\"));\n\nSubComponentManager::SubComponentManager(Model *model, QObject *parent)\n : QObject(parent),\n m_model(model)\n{\n connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));\n}\n\nvoid SubComponentManager::addImport(int pos, const Import &import)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << pos << import.file().toLatin1();\n\n if (import.isFileImport()) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n m_watcher.addPath(canonicalDirPath);\n \/\/m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n }\n } else {\n QString url = import.url();\n\n url.replace(QLatin1Char('.'), QLatin1Char('\/'));\n\n foreach (const QString &path, importPaths()) {\n url = path + QLatin1Char('\/') + url;\n QFileInfo dirInfo = QFileInfo(url);\n if (dirInfo.exists() && dirInfo.isDir()) {\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n m_watcher.addPath(canonicalDirPath);\n \/\/m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n }\n }\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n\n m_imports.insert(pos, import);\n}\n\nvoid SubComponentManager::removeImport(int pos)\n{\n const Import import = m_imports.takeAt(pos);\n\n if (import.isFileImport()) {\n const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n\n \/\/m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n\n if (!m_dirToQualifier.contains(canonicalDirPath))\n m_watcher.removePath(canonicalDirPath);\n\n\/\/ foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as\n\/\/ if (!m_dirToQualifier.contains(canonicalDirPath))\n\/\/ unregisterQmlFile(monitoredFile, import.qualifier());\n\/\/ }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n}\n\nvoid SubComponentManager::parseDirectories()\n{\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());\n if (dirInfo.exists() && dirInfo.isDir())\n parseDirectory(dirInfo.canonicalFilePath());\n }\n\n foreach (const Import &import, m_imports) {\n if (import.isFileImport()) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n parseDirectory(dirInfo.canonicalFilePath());\n }\n } else {\n QString url = import.url();\n foreach (const QString &path, importPaths()) {\n url.replace(QLatin1Char('.'), QLatin1Char('\/'));\n url = path + QLatin1Char('\/') + url;\n QFileInfo dirInfo = QFileInfo(url);\n if (dirInfo.exists() && dirInfo.isDir()) {\n \/\/### todo full qualified names QString nameSpace = import.uri();\n parseDirectory(dirInfo.canonicalFilePath(), false);\n }\n }\n }\n }\n}\n\nvoid SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const QString& qualification)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << canonicalDirPath;\n\n QDir dir(canonicalDirPath);\n\n dir.setNameFilters(QStringList(s_qmlFilePattern));\n dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);\n\n QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);\n QList<QFileInfo> newList;\n foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {\n if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {\n \/\/ do not parse main file\n continue;\n }\n if (!qmlFile.fileName().at(0).isUpper()) {\n \/\/ QML sub components must be upper case\n continue;\n }\n newList << qmlFile;\n }\n\n qSort(monitoredList);\n qSort(newList);\n\n if (debug)\n qDebug() << \"monitored list \" << monitoredList.size() << \"new list \" << newList.size();\n QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();\n QList<QFileInfo>::const_iterator newIter = newList.constBegin();\n\n while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {\n const QFileInfo oldFileInfo = *oldIter;\n const QFileInfo newFileInfo = *newIter;\n if (oldFileInfo == newFileInfo) {\n ++oldIter;\n ++newIter;\n continue;\n }\n if (oldFileInfo < newFileInfo) {\n foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))\n unregisterQmlFile(oldFileInfo, qualifier);\n m_watcher.removePath(oldFileInfo.filePath());\n ++oldIter;\n continue;\n }\n \/\/ oldFileInfo > newFileInfo\n parseFile(newFileInfo.filePath(), addToLibrary, qualification);\n ++newIter;\n }\n\n while (oldIter != monitoredList.constEnd()) {\n foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))\n unregisterQmlFile(*oldIter, qualifier);\n ++oldIter;\n }\n\n while (newIter != newList.constEnd()) {\n parseFile(newIter->filePath(), addToLibrary, qualification);\n if (debug)\n qDebug() << \"m_watcher.addPath(\" << newIter->filePath() << ')';\n ++newIter;\n }\n}\n\nvoid SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& \/* qualification *\/)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << canonicalFilePath;\n\n QFile file(canonicalFilePath);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QString dir = QFileInfo(canonicalFilePath).path();\n foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {\n registerQmlFile(canonicalFilePath, qualifier, addToLibrary);\n }\n registerQmlFile(canonicalFilePath, QString(), addToLibrary);\n}\n\nvoid SubComponentManager::parseFile(const QString &canonicalFilePath)\n{\n parseFile(canonicalFilePath, true, QString());\n}\n\n\/\/ dirInfo must already contain a canonical path\nQList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)\n{\n QList<QFileInfo> files;\n\n foreach (const QString &monitoredFile, m_watcher.files()) {\n QFileInfo fileInfo(monitoredFile);\n if (fileInfo.dir().absolutePath() == canonicalDirPath) {\n files.append(fileInfo);\n }\n }\n return files;\n}\n\nvoid SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '.' + componentName;\n}\n\nstatic inline bool isDepricatedQtType(const QString &typeName)\n{\n if (typeName.length() < 8)\n return false;\n\n return typeName.contains(\"Qt.\");\n}\n\n\nvoid SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,\n bool addToLibrary)\n{\n if (!model())\n return;\n\n QString componentName = fileInfo.baseName();\n\n if (!qualifier.isEmpty()) {\n QString fixedQualifier = qualifier;\n if (qualifier.right(1) == QLatin1String(\".\"))\n fixedQualifier.chop(1); \/\/remove last char if it is a dot\n componentName = fixedQualifier + '.' + componentName;\n }\n\n if (debug)\n qDebug() << \"SubComponentManager\" << __FUNCTION__ << componentName;\n\n if (addToLibrary) {\n \/\/ Add file components to the library\n ItemLibraryEntry itemLibraryEntry;\n itemLibraryEntry.setType(componentName, -1, -1);\n itemLibraryEntry.setName(componentName);\n itemLibraryEntry.setCategory(\"QML Components\");\n\n\n if (model()->metaInfo(componentName).isValid() && model()->metaInfo(componentName).isSubclassOf(\"QtQuick.Item\", -1, -1) &&\n !model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {\n\n model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);\n }\n }\n}\n\nModel *SubComponentManager::model() const\n{\n return m_model.data();\n}\n\n\n\/*!\n \\class SubComponentManager\n\n Detects & monitors (potential) component files in a list of directories, and registers\n these in the metatype system.\n*\/\n\nQStringList SubComponentManager::directories() const\n{\n return m_watcher.directories();\n}\n\nQStringList SubComponentManager::qmlFiles() const\n{\n return m_watcher.files();\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath << imports.size();\n\n QFileInfo oldDir, newDir;\n\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n oldDir = QFileInfo(QFileInfo(file).path());\n }\n if (!filePath.isEmpty()) {\n const QString file = filePath.toLocalFile();\n newDir = QFileInfo(QFileInfo(file).path());\n }\n\n m_filePath = filePath;\n\n \/\/\n \/\/ (implicit) import of local directory\n \/\/\n if (oldDir != newDir) {\n if (!oldDir.filePath().isEmpty()) {\n m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());\n if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))\n m_watcher.removePath(oldDir.filePath());\n }\n\n if (!newDir.filePath().isEmpty()) {\n m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());\n }\n }\n\n \/\/\n \/\/ Imports\n \/\/\n\n \/\/ skip first list items until the lists differ\n int i = 0;\n while (i < qMin(imports.size(), m_imports.size())) {\n if (!(imports.at(i) == m_imports.at(i)))\n break;\n ++i;\n }\n\n for (int ii = m_imports.size() - 1; ii >= i; --ii)\n removeImport(ii);\n\n for (int ii = i; ii < imports.size(); ++ii) {\n addImport(ii, imports.at(ii));\n }\n\n parseDirectories();\n}\n\n} \/\/ namespace QmlDesigner\n\n<commit_msg>QmlDesigner.SubComponentManager: fix qualification of file imports<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"subcomponentmanager.h\"\n#include \"model.h\"\n#include \"metainfo.h\"\n\n#include <utils\/hostosinfo.h>\n\n#include <QDir>\n#include <QMetaType>\n#include <QUrl>\n\nenum { debug = false };\n\nQT_BEGIN_NAMESPACE\n\n\/\/ Allow usage of QFileInfo in qSort\n\nstatic bool operator<(const QFileInfo &file1, const QFileInfo &file2)\n{\n return file1.filePath() < file2.filePath();\n}\n\n\nQT_END_NAMESPACE\n\nstatic inline QStringList importPaths() {\n QStringList paths;\n\n \/\/ env import paths\n QByteArray envImportPath = qgetenv(\"QML_IMPORT_PATH\");\n if (!envImportPath.isEmpty()) {\n paths = QString::fromLatin1(envImportPath)\n .split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);\n }\n\n return paths;\n}\n\nnamespace QmlDesigner {\nstatic const QString s_qmlFilePattern = QString(QLatin1String(\"*.qml\"));\n\nSubComponentManager::SubComponentManager(Model *model, QObject *parent)\n : QObject(parent),\n m_model(model)\n{\n connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));\n}\n\nvoid SubComponentManager::addImport(int pos, const Import &import)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << pos << import.file().toLatin1();\n\n if (import.isFileImport()) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n m_watcher.addPath(canonicalDirPath);\n \/\/m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n }\n } else {\n QString url = import.url();\n\n url.replace(QLatin1Char('.'), QLatin1Char('\/'));\n\n foreach (const QString &path, importPaths()) {\n url = path + QLatin1Char('\/') + url;\n QFileInfo dirInfo = QFileInfo(url);\n if (dirInfo.exists() && dirInfo.isDir()) {\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n m_watcher.addPath(canonicalDirPath);\n \/\/m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n }\n }\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n\n m_imports.insert(pos, import);\n}\n\nvoid SubComponentManager::removeImport(int pos)\n{\n const Import import = m_imports.takeAt(pos);\n\n if (import.isFileImport()) {\n const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n const QString canonicalDirPath = dirInfo.canonicalFilePath();\n\n \/\/m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as\n\n if (!m_dirToQualifier.contains(canonicalDirPath))\n m_watcher.removePath(canonicalDirPath);\n\n\/\/ foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as\n\/\/ if (!m_dirToQualifier.contains(canonicalDirPath))\n\/\/ unregisterQmlFile(monitoredFile, import.qualifier());\n\/\/ }\n } else {\n \/\/ TODO: QDeclarativeDomImport::Library\n }\n}\n\nvoid SubComponentManager::parseDirectories()\n{\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());\n if (dirInfo.exists() && dirInfo.isDir())\n parseDirectory(dirInfo.canonicalFilePath());\n }\n\n foreach (const Import &import, m_imports) {\n if (import.isFileImport()) {\n QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());\n if (dirInfo.exists() && dirInfo.isDir()) {\n parseDirectory(dirInfo.canonicalFilePath());\n }\n } else {\n QString url = import.url();\n foreach (const QString &path, importPaths()) {\n url.replace(QLatin1Char('.'), QLatin1Char('\/'));\n url = path + QLatin1Char('\/') + url;\n QFileInfo dirInfo = QFileInfo(url);\n if (dirInfo.exists() && dirInfo.isDir()) {\n \/\/### todo full qualified names QString nameSpace = import.uri();\n parseDirectory(dirInfo.canonicalFilePath(), false);\n }\n }\n }\n }\n}\n\nvoid SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const QString& qualification)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << canonicalDirPath;\n\n QDir dir(canonicalDirPath);\n\n dir.setNameFilters(QStringList(s_qmlFilePattern));\n dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);\n\n QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);\n QList<QFileInfo> newList;\n foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {\n if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {\n \/\/ do not parse main file\n continue;\n }\n if (!qmlFile.fileName().at(0).isUpper()) {\n \/\/ QML sub components must be upper case\n continue;\n }\n newList << qmlFile;\n }\n\n qSort(monitoredList);\n qSort(newList);\n\n if (debug)\n qDebug() << \"monitored list \" << monitoredList.size() << \"new list \" << newList.size();\n QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();\n QList<QFileInfo>::const_iterator newIter = newList.constBegin();\n\n while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {\n const QFileInfo oldFileInfo = *oldIter;\n const QFileInfo newFileInfo = *newIter;\n if (oldFileInfo == newFileInfo) {\n ++oldIter;\n ++newIter;\n continue;\n }\n if (oldFileInfo < newFileInfo) {\n foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))\n unregisterQmlFile(oldFileInfo, qualifier);\n m_watcher.removePath(oldFileInfo.filePath());\n ++oldIter;\n continue;\n }\n \/\/ oldFileInfo > newFileInfo\n parseFile(newFileInfo.filePath(), addToLibrary, qualification);\n ++newIter;\n }\n\n while (oldIter != monitoredList.constEnd()) {\n foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))\n unregisterQmlFile(*oldIter, qualifier);\n ++oldIter;\n }\n\n while (newIter != newList.constEnd()) {\n parseFile(newIter->filePath(), addToLibrary, qualification);\n if (debug)\n qDebug() << \"m_watcher.addPath(\" << newIter->filePath() << ')';\n ++newIter;\n }\n}\n\nvoid SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << canonicalFilePath;\n\n QFile file(canonicalFilePath);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QString dir = QFileInfo(canonicalFilePath).path();\n foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {\n registerQmlFile(canonicalFilePath, qualifier, addToLibrary);\n }\n registerQmlFile(canonicalFilePath, qualification, addToLibrary);\n}\n\nvoid SubComponentManager::parseFile(const QString &canonicalFilePath)\n{\n parseFile(canonicalFilePath, true, QString());\n}\n\n\/\/ dirInfo must already contain a canonical path\nQList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)\n{\n QList<QFileInfo> files;\n\n foreach (const QString &monitoredFile, m_watcher.files()) {\n QFileInfo fileInfo(monitoredFile);\n if (fileInfo.dir().absolutePath() == canonicalDirPath) {\n files.append(fileInfo);\n }\n }\n return files;\n}\n\nvoid SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)\n{\n QString componentName = fileInfo.baseName();\n if (!qualifier.isEmpty())\n componentName = qualifier + '.' + componentName;\n}\n\nstatic inline bool isDepricatedQtType(const QString &typeName)\n{\n if (typeName.length() < 8)\n return false;\n\n return typeName.contains(\"Qt.\");\n}\n\n\nvoid SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,\n bool addToLibrary)\n{\n if (!model())\n return;\n\n QString componentName = fileInfo.baseName();\n\n\n if (debug)\n qDebug() << \"SubComponentManager\" << __FUNCTION__ << componentName;\n\n if (addToLibrary) {\n \/\/ Add file components to the library\n ItemLibraryEntry itemLibraryEntry;\n itemLibraryEntry.setType(componentName, -1, -1);\n itemLibraryEntry.setName(componentName);\n itemLibraryEntry.setCategory(\"QML Components\");\n if (!qualifier.isEmpty()) {\n itemLibraryEntry.setForceImport(true);\n itemLibraryEntry.setRequiredImport(qualifier);\n }\n\n\n if (model()->metaInfo(componentName).isValid() && model()->metaInfo(componentName).isSubclassOf(\"QtQuick.Item\", -1, -1) &&\n !model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {\n\n model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);\n }\n }\n}\n\nModel *SubComponentManager::model() const\n{\n return m_model.data();\n}\n\n\n\/*!\n \\class SubComponentManager\n\n Detects & monitors (potential) component files in a list of directories, and registers\n these in the metatype system.\n*\/\n\nQStringList SubComponentManager::directories() const\n{\n return m_watcher.directories();\n}\n\nQStringList SubComponentManager::qmlFiles() const\n{\n return m_watcher.files();\n}\n\nvoid SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)\n{\n if (debug)\n qDebug() << Q_FUNC_INFO << filePath << imports.size();\n\n QFileInfo oldDir, newDir;\n\n if (!m_filePath.isEmpty()) {\n const QString file = m_filePath.toLocalFile();\n oldDir = QFileInfo(QFileInfo(file).path());\n }\n if (!filePath.isEmpty()) {\n const QString file = filePath.toLocalFile();\n newDir = QFileInfo(QFileInfo(file).path());\n }\n\n m_filePath = filePath;\n\n \/\/\n \/\/ (implicit) import of local directory\n \/\/\n if (oldDir != newDir) {\n if (!oldDir.filePath().isEmpty()) {\n m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());\n if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))\n m_watcher.removePath(oldDir.filePath());\n }\n\n if (!newDir.filePath().isEmpty()) {\n m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());\n }\n }\n\n \/\/\n \/\/ Imports\n \/\/\n\n \/\/ skip first list items until the lists differ\n int i = 0;\n while (i < qMin(imports.size(), m_imports.size())) {\n if (!(imports.at(i) == m_imports.at(i)))\n break;\n ++i;\n }\n\n for (int ii = m_imports.size() - 1; ii >= i; --ii)\n removeImport(ii);\n\n for (int ii = i; ii < imports.size(); ++ii) {\n addImport(ii, imports.at(ii));\n }\n\n parseDirectories();\n}\n\n} \/\/ namespace QmlDesigner\n\n<|endoftext|>"} {"text":"<commit_before>#include \"viewer\/primitives\/simple_geometry_primitives.hh\"\n\n#include <GL\/glew.h>\n#include \"viewer\/colors\/material.hh\"\n#include \"viewer\/gl_aliases.hh\"\n\n#include \"geometry\/perp.hh\"\n\nnamespace viewer {\n\nusing Vec3 = Eigen::Vector3d;\nusing Vec4 = Eigen::Vector4d;\n\nvoid draw_axes(const Axes &axes) {\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n glLineWidth(1.0);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glTransform(axes.world_from_axes);\n glScaled(axes.scale, axes.scale, axes.scale);\n\n if (axes.dotted) {\n glLineStipple(1.0, 0x1010);\n }\n glLineWidth(axes.line_width);\n\n glBegin(GL_LINES);\n\n glColor4d(1.0, 0.0, 0.0, 0.9);\n glVertex(Vec3::UnitX().eval());\n glVertex(Vec3::Zero().eval());\n\n glColor4d(0.0, 1.0, 0.0, 0.9);\n glVertex(Vec3::UnitY().eval());\n glVertex(Vec3::Zero().eval());\n\n glColor4d(0.0, 0.0, 1.0, 0.9);\n glVertex(Vec3::UnitZ().eval());\n glVertex(Vec3::Zero().eval());\n glEnd();\n\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid draw_lines(const std::vector<Line> &lines) {\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n\n for (const auto &line : lines) {\n glLineWidth(line.width);\n glBegin(GL_LINES);\n glColor(line.color);\n glVertex(line.start);\n glVertex(line.end);\n glEnd();\n }\n\n glPopAttrib();\n}\n\nvoid draw_polygon(const Polygon &polygon) {\n const int n_points = static_cast<int>(polygon.points.size());\n const Eigen::Vector3d offset(0.0, 0.0, polygon.height);\n\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n glLineWidth(polygon.width);\n \/\/ Draw the height of the poly\n \/*\n glBegin(GL_QUADS);\n glColor(polygon.color);\n for (int k = 0; k < n_points; ++k) {\n const auto &start = polygon.points[k];\n const auto &end = polygon.points[(k + 1) % n_points];\n glVertex(start);\n glVertex(end);\n\n glVertex(Vec3(end + offset));\n glVertex(Vec3(start + offset));\n }\n glEnd();\n *\/\n\n \/*\n if (polygon.outline) {\n glLineWidth(0.8);\n glBegin(GL_LINE_LOOP);\n glColor(Vec4(Vec4::Ones()));\n for (int k = 0; k < n_points; ++k) {\n const auto &start = polygon.points[k];\n const auto &end = polygon.points[(k + 1) % n_points];\n glVertex(start);\n glVertex(end);\n\n glVertex(Vec3(end + offset));\n glVertex(Vec3(start + offset));\n }\n glEnd();\n }\n *\/\n\n glColor(polygon.color);\n glBegin(GL_TRIANGLE_FAN);\n for (int k = 0; k < n_points; ++k) {\n const auto &point = polygon.points[k];\n glVertex(point);\n }\n glEnd();\n\n if (polygon.outline) {\n glLineWidth(3.0);\n glColor(Vec4(Vec4::Ones()));\n glBegin(GL_LINE_LOOP);\n for (int k = 0; k < n_points; ++k) {\n const auto &point = polygon.points[k];\n glVertex(point);\n }\n glEnd();\n }\n\n glPopAttrib();\n}\n\nvoid draw_points(const Points &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glColor(points.color);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (const auto &pt : points.points) {\n glVertex(pt);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_colored_points(const ColoredPoints &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (std::size_t k = 0; k < points.points.size(); ++k) {\n glColor(points.colors[k]);\n glVertex(points.points[k]);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_points2d(const Points2d &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glColor(points.color);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (const auto &pt : points.points) {\n glVertex3d(pt.x(), pt.y(), points.z_offset);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_circle(const Vec3 ¢er,\n const Vec3 &normal,\n const double radius,\n const Vec4 &color) {\n constexpr double CIRCLE_RES = 0.05;\n\n const Vec3 x_u = geometry::perp(normal);\n const Vec3 y_u = -x_u.cross(normal);\n\n Eigen::Matrix3d world_from_circle_frame;\n world_from_circle_frame.col(0) = x_u;\n world_from_circle_frame.col(1) = y_u;\n world_from_circle_frame.col(2) = normal;\n\n glColor(color);\n glBegin(GL_LINE_LOOP);\n for (double t = 0.0; t < (2.0 * M_PI); t += CIRCLE_RES) {\n const Vec3 pt_circle_frm(radius * std::sin(t), radius * std::cos(t), 0.0);\n const Vec3 pt_world_frm = (world_from_circle_frame * pt_circle_frm) + center;\n glVertex(pt_world_frm);\n }\n glEnd();\n}\n\nvoid draw_sphere(const Sphere &sphere) {\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitX(), sphere.radius,\n sphere.color);\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitY(), sphere.radius,\n sphere.color);\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitZ(), sphere.radius,\n sphere.color);\n}\n\nvoid draw_plane_grid(const Plane &plane) {\n const Vec3 &n = plane.plane.u_normal;\n const Vec3 x_dir = geometry::perp(n);\n const Vec3 y_dir = x_dir.cross(n).normalized();\n\n const int n_lines = 10;\n const double displacement = n_lines * plane.line_spacing;\n const Vec3 offset = plane.plane.u_normal * plane.plane.distance_from_origin;\n\n const Vec3 y_offset = y_dir * 10.0;\n const Vec3 x_offset = x_dir * 10.0;\n\n glPushAttrib(GL_CURRENT_BIT);\n glColor(plane.color);\n glBegin(GL_LINES);\n {\n for (double x = -displacement; x <= displacement; x += plane.line_spacing) {\n const Vec3 v = (x * x_dir) + offset;\n\n \/\/ Lines retreating off to infinity by homogeneousness\n \/\/ turns out, it doesn't look that good.\n\n \/*glVertex4d(v.x(), v.y(), v.z(), 0.0);\n glVertex4d(y_dir.x(), y_dir.y(), y_dir.z(), 0.0);\n glVertex4d(v.x(), v.y(), v.z(), 1.0);*\/\n\n glVertex(Vec3(v + y_offset));\n glVertex(Vec3(v - y_offset));\n }\n for (double y = -displacement; y <= displacement; y += plane.line_spacing) {\n const Vec3 v = (y * y_dir) + offset;\n\n glVertex(Vec3(v + x_offset));\n glVertex(Vec3(v - x_offset));\n }\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_point(const Point &point) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glPointSize(point.size);\n glColor(point.color);\n\n glBegin(GL_POINTS);\n glVertex(point.point);\n glEnd();\n\n glPopAttrib();\n}\n\nvoid draw_trimesh(const TriMesh &trimesh) {\n glPushAttrib(GL_CURRENT_BIT);\n\n glPushMatrix();\n glTransform(trimesh.world_from_mesh);\n\n glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n if (trimesh.outline) {\n glPushAttrib(GL_LINE_BIT);\n glLineWidth(trimesh.outline_width);\n glBegin(GL_LINES);\n for (const auto &tri : trimesh.mesh.triangles) {\n glVertex(tri.vertices[0]);\n glVertex(tri.vertices[1]);\n glVertex(tri.vertices[2]);\n }\n glEnd();\n glPopAttrib();\n }\n\n \/\/ glEnable(GL_LIGHTING);\n const auto material = colors::get_plastic(trimesh.color);\n colors::gl_material(material);\n glColor(trimesh.color);\n if (trimesh.filled) {\n glBegin(GL_TRIANGLES);\n for (const auto &tri : trimesh.mesh.triangles) {\n glVertex(tri.vertices[0]);\n glVertex(tri.vertices[1]);\n glVertex(tri.vertices[2]);\n }\n\n glEnd();\n }\n \/\/ glDisable(GL_LIGHTING);\n glPopMatrix();\n\n glPopAttrib();\n \/\/ draw the display list\n}\n} \/\/ namespace viewer\n<commit_msg>[Viewer] Fix stippling<commit_after>#include \"viewer\/primitives\/simple_geometry_primitives.hh\"\n\n#include <GL\/glew.h>\n#include \"viewer\/colors\/material.hh\"\n#include \"viewer\/gl_aliases.hh\"\n\n#include \"geometry\/perp.hh\"\n\nnamespace viewer {\n\nusing Vec3 = Eigen::Vector3d;\nusing Vec4 = Eigen::Vector4d;\n\nvoid draw_axes(const Axes &axes) {\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n glLineWidth(1.0);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glTransform(axes.world_from_axes);\n glScaled(axes.scale, axes.scale, axes.scale);\n\n if (axes.dotted) {\n glEnable(GL_LINE_STIPPLE);\n glLineStipple(1.0, 0x00FF);\n }\n glLineWidth(axes.line_width);\n\n glBegin(GL_LINES);\n\n glColor4d(1.0, 0.0, 0.0, 0.9);\n glVertex(Vec3::UnitX().eval());\n glVertex(Vec3::Zero().eval());\n\n glColor4d(0.0, 1.0, 0.0, 0.9);\n glVertex(Vec3::UnitY().eval());\n glVertex(Vec3::Zero().eval());\n\n glColor4d(0.0, 0.0, 1.0, 0.9);\n glVertex(Vec3::UnitZ().eval());\n glVertex(Vec3::Zero().eval());\n glEnd();\n\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid draw_lines(const std::vector<Line> &lines) {\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n\n for (const auto &line : lines) {\n glLineWidth(line.width);\n glBegin(GL_LINES);\n glColor(line.color);\n glVertex(line.start);\n glVertex(line.end);\n glEnd();\n }\n\n glPopAttrib();\n}\n\nvoid draw_polygon(const Polygon &polygon) {\n const int n_points = static_cast<int>(polygon.points.size());\n const Eigen::Vector3d offset(0.0, 0.0, polygon.height);\n\n glPushAttrib(GL_CURRENT_BIT | GL_LINE_BIT);\n glLineWidth(polygon.width);\n \/\/ Draw the height of the poly\n \/*\n glBegin(GL_QUADS);\n glColor(polygon.color);\n for (int k = 0; k < n_points; ++k) {\n const auto &start = polygon.points[k];\n const auto &end = polygon.points[(k + 1) % n_points];\n glVertex(start);\n glVertex(end);\n\n glVertex(Vec3(end + offset));\n glVertex(Vec3(start + offset));\n }\n glEnd();\n *\/\n\n \/*\n if (polygon.outline) {\n glLineWidth(0.8);\n glBegin(GL_LINE_LOOP);\n glColor(Vec4(Vec4::Ones()));\n for (int k = 0; k < n_points; ++k) {\n const auto &start = polygon.points[k];\n const auto &end = polygon.points[(k + 1) % n_points];\n glVertex(start);\n glVertex(end);\n\n glVertex(Vec3(end + offset));\n glVertex(Vec3(start + offset));\n }\n glEnd();\n }\n *\/\n\n glColor(polygon.color);\n glBegin(GL_TRIANGLE_FAN);\n for (int k = 0; k < n_points; ++k) {\n const auto &point = polygon.points[k];\n glVertex(point);\n }\n glEnd();\n\n if (polygon.outline) {\n glLineWidth(3.0);\n glColor(Vec4(Vec4::Ones()));\n glBegin(GL_LINE_LOOP);\n for (int k = 0; k < n_points; ++k) {\n const auto &point = polygon.points[k];\n glVertex(point);\n }\n glEnd();\n }\n\n glPopAttrib();\n}\n\nvoid draw_points(const Points &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glColor(points.color);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (const auto &pt : points.points) {\n glVertex(pt);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_colored_points(const ColoredPoints &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (std::size_t k = 0; k < points.points.size(); ++k) {\n glColor(points.colors[k]);\n glVertex(points.points[k]);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_points2d(const Points2d &points) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glColor(points.color);\n glPointSize(points.size);\n glBegin(GL_POINTS);\n for (const auto &pt : points.points) {\n glVertex3d(pt.x(), pt.y(), points.z_offset);\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_circle(const Vec3 ¢er,\n const Vec3 &normal,\n const double radius,\n const Vec4 &color) {\n constexpr double CIRCLE_RES = 0.05;\n\n const Vec3 x_u = geometry::perp(normal);\n const Vec3 y_u = -x_u.cross(normal);\n\n Eigen::Matrix3d world_from_circle_frame;\n world_from_circle_frame.col(0) = x_u;\n world_from_circle_frame.col(1) = y_u;\n world_from_circle_frame.col(2) = normal;\n\n glColor(color);\n glBegin(GL_LINE_LOOP);\n for (double t = 0.0; t < (2.0 * M_PI); t += CIRCLE_RES) {\n const Vec3 pt_circle_frm(radius * std::sin(t), radius * std::cos(t), 0.0);\n const Vec3 pt_world_frm = (world_from_circle_frame * pt_circle_frm) + center;\n glVertex(pt_world_frm);\n }\n glEnd();\n}\n\nvoid draw_sphere(const Sphere &sphere) {\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitX(), sphere.radius,\n sphere.color);\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitY(), sphere.radius,\n sphere.color);\n draw_circle(sphere.center, sphere.world_from_sphere * Vec3::UnitZ(), sphere.radius,\n sphere.color);\n}\n\nvoid draw_plane_grid(const Plane &plane) {\n const Vec3 &n = plane.plane.u_normal;\n const Vec3 x_dir = geometry::perp(n);\n const Vec3 y_dir = x_dir.cross(n).normalized();\n\n const int n_lines = 10;\n const double displacement = n_lines * plane.line_spacing;\n const Vec3 offset = plane.plane.u_normal * plane.plane.distance_from_origin;\n\n const Vec3 y_offset = y_dir * 10.0;\n const Vec3 x_offset = x_dir * 10.0;\n\n glPushAttrib(GL_CURRENT_BIT);\n glColor(plane.color);\n glBegin(GL_LINES);\n {\n for (double x = -displacement; x <= displacement; x += plane.line_spacing) {\n const Vec3 v = (x * x_dir) + offset;\n\n \/\/ Lines retreating off to infinity by homogeneousness\n \/\/ turns out, it doesn't look that good.\n\n \/*glVertex4d(v.x(), v.y(), v.z(), 0.0);\n glVertex4d(y_dir.x(), y_dir.y(), y_dir.z(), 0.0);\n glVertex4d(v.x(), v.y(), v.z(), 1.0);*\/\n\n glVertex(Vec3(v + y_offset));\n glVertex(Vec3(v - y_offset));\n }\n for (double y = -displacement; y <= displacement; y += plane.line_spacing) {\n const Vec3 v = (y * y_dir) + offset;\n\n glVertex(Vec3(v + x_offset));\n glVertex(Vec3(v - x_offset));\n }\n }\n glEnd();\n glPopAttrib();\n}\n\nvoid draw_point(const Point &point) {\n glPushAttrib(GL_POINT_BIT | GL_CURRENT_BIT);\n glPointSize(point.size);\n glColor(point.color);\n\n glBegin(GL_POINTS);\n glVertex(point.point);\n glEnd();\n\n glPopAttrib();\n}\n\nvoid draw_trimesh(const TriMesh &trimesh) {\n glPushAttrib(GL_CURRENT_BIT);\n\n glPushMatrix();\n glTransform(trimesh.world_from_mesh);\n\n glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\n if (trimesh.outline) {\n glPushAttrib(GL_LINE_BIT);\n glLineWidth(trimesh.outline_width);\n glBegin(GL_LINES);\n for (const auto &tri : trimesh.mesh.triangles) {\n glVertex(tri.vertices[0]);\n glVertex(tri.vertices[1]);\n glVertex(tri.vertices[2]);\n }\n glEnd();\n glPopAttrib();\n }\n\n \/\/ glEnable(GL_LIGHTING);\n const auto material = colors::get_plastic(trimesh.color);\n colors::gl_material(material);\n glColor(trimesh.color);\n if (trimesh.filled) {\n glBegin(GL_TRIANGLES);\n for (const auto &tri : trimesh.mesh.triangles) {\n glVertex(tri.vertices[0]);\n glVertex(tri.vertices[1]);\n glVertex(tri.vertices[2]);\n }\n\n glEnd();\n }\n \/\/ glDisable(GL_LIGHTING);\n glPopMatrix();\n\n glPopAttrib();\n \/\/ draw the display list\n}\n} \/\/ namespace viewer\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABC_CORE_HXX\n #error Please #include <abc\/core.hxx> instead of this file\n#endif\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals\n\nnamespace abc {\n\n\/** Indicates the level of UTF-8 string literals support:\n• 2 - The UTF-8 string literal prefix (u8) is supported;\n• 1 - The u8 prefix is not supported, but the compiler will generate valid UTF-8 string literals if\n the source file is UTF-8+BOM-encoded;\n• 0 - UTF-8 string literals are not supported in any way.\n*\/\n#define ABC_CXX_UTF8LIT 0\n\n\/** Indicates how char16_t is defined:\n• 2 - char16_t is a native type, distinct from uint16_t and wchar_t;\n• 1 - abc::char16_t is a typedef for native 16-bit wchar_t, distinct from uint16_t;\n• 0 - abc::char16_t is a typedef for uint16_t.\n*\/\n#define ABC_CXX_CHAR16 0\n\n\/** Indicates how char32_t is defined:\n• 2 - char32_t is a native type, distinct from uint32_t and wchar_t;\n• 1 - abc::char32_t is a typedef for native 32-bit wchar_t, distinct from uint32_t;\n• 0 - abc::char32_t is a typedef for uint32_t.\n*\/\n#define ABC_CXX_CHAR32 0\n\n#if ABC_HOST_GCC >= 40400\n \/\/ char16_t is a native type, different than uint16_t.\n #undef ABC_CXX_CHAR16\n #define ABC_CXX_CHAR16 2\n \/\/ char32_t is a native type, different than uint32_t.\n #undef ABC_CXX_CHAR32\n #define ABC_CXX_CHAR32 2\n\n #if ABC_HOST_GCC >= 40500\n \/\/ UTF-8 string literals are supported.\n #undef ABC_CXX_UTF8LIT\n #define ABC_CXX_UTF8LIT 2\n #endif\n#else \/\/if ABC_HOST_GCC >= 40400\n #if ABC_HOST_MSC\n #if !defined(_WCHAR_T_DEFINED) || !defined(_NATIVE_WCHAR_T_DEFINED)\n #error Please compile with \/Zc:wchar_t\n #endif\n\n \/\/ char16_t is not a native type, but we can typedef it as wchar_t.\n #undef ABC_CXX_CHAR16\n #define ABC_CXX_CHAR16 1\n #else\n \/\/ MSC16 will transcode non-wchar_t string literals into whatever single-byte encoding is\n \/\/ selected for the user running cl.exe; a solution has been provided in form of a hotfix\n \/\/ (<http:\/\/support.microsoft.com\/kb\/2284668\/en-us>), but it no longer seems available, and it\n \/\/ was not ported to MSC17\/VS2012, thought it seems it was finally built into MSC18\/VS2013\n \/\/ (<http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/773186\/pragma-execution-\n \/\/ character-set-utf-8-didnt-support-in-vc-2012>).\n \/\/\n \/\/ Here we assume that no other compiler exhibits such a random behavior, and they will all\n \/\/ emit valid UTF-8 string literals it the source file is UTF-8+BOM-encoded.\n #undef ABC_CXX_UTF8LIT\n #define ABC_CXX_UTF8LIT 1\n\n \/\/ char32_t is not a native type, but we can typedef it as wchar_t.\n #undef ABC_CXX_CHAR32\n #define ABC_CXX_CHAR32 1\n #endif\n#endif \/\/if ABC_HOST_GCC >= 40400 … else\n#if ABC_CXX_CHAR16 == 0 && ABC_CXX_CHAR32 == 0\n #error ABC_CXX_CHAR16 and\/or ABC_CXX_CHAR32 must be > 0; please fix detection logic\n#endif\n\n\n\/** UTF-8 character type. *\/\ntypedef char char8_t;\n\n\/** UTF-16 character type. *\/\n#if ABC_CXX_CHAR16 == 1\n typedef wchar_t char16_t;\n#elif ABC_CXX_CHAR16 == 0\n typedef uint16_t char16_t;\n#endif\n\n\/** UTF-32 character type. *\/\n#if ABC_CXX_CHAR32 == 1\n typedef wchar_t char32_t;\n#elif ABC_CXX_CHAR32 == 0\n typedef uint32_t char32_t;\n#endif\n\n\n\/** Defines an 8-bit character literal.\n\nch\n Character literal.\nreturn\n 8-bit character literal.\n*\/\n#define U8CL(ch) ::abc::char8_t(ch)\n\n\n\/** Defines a UCS-16 character literal.\n\nch\n Character literal.\nreturn\n UCS-16 character literal.\n*\/\n#if ABC_CXX_CHAR16 == 2\n #define U16CL(ch) u ## ch\n#elif ABC_CXX_CHAR16 == 1\n #define U16CL(ch) L ## ch\n#elif ABC_CXX_CHAR16 == 0\n \/\/ No native type for char16_t, but we can at least use 32-bit wchar_t to store any Unicode\n \/\/ character correctly, and then truncate that to our typedef’ed char16_t.\n \/\/ TODO: make the truncation explicit (compiler warning?).\n #define U16CL(ch) ::abc::char16_t(L ## ch)\n#endif\n\n\n\/** Defines a UTF-32\/UCS-32 character literal. Code points outside the Basic Multilingual Plane are\nnot supported on all platforms.\n\nch\n Character literal.\nreturn\n UTF-32\/UCS-32 character literal.\n*\/\n#if ABC_CXX_CHAR32 == 2\n #define U32CL(ch) U ## ch\n#elif ABC_CXX_CHAR32 == 1\n #define U32CL(ch) L ## ch\n#elif ABC_CXX_CHAR32 == 0\n \/\/ No native type for char32_t, but we can at least use 16-bit wchar_t to store all Unicode BMP\n \/\/ characters correctly, and then cast that to our typedef’ed char32_t.\n #define U32CL(ch) ::abc::char32_t(L ## ch)\n#endif\n\n\n\/** Defines a UTF-8 string literal. On some platforms, this relies on the source files being encoded\nin UTF-8.\n\ns\n String literal.\nreturn\n UTF-8 string literal.\n*\/\n#if ABC_CXX_UTF8LIT == 2\n #define U8SL(s) u8 ## s\n#elif ABC_CXX_UTF8LIT == 1\n \/\/ Rely on the source files being encoded in UTF-8.\n #define U8SL(s) s\n#endif\n\n\n\/** Defines a UTF-16 string literal. Not supported on all platforms; check with #ifdef before using.\n\ns\n String literal.\nreturn\n UTF-16 string literal.\n*\/\n#if ABC_CXX_CHAR16 == 2\n #define U16SL(s) u ## s\n#elif ABC_CXX_CHAR16 == 1\n #define U16SL(s) L ## s\n#endif\n\n\n\/** Defines a UTF-32\/UCS-32 string literal. Not supported on all platforms; check with #ifdef before\nusing.\n\ns\n String literal.\nreturn\n UTF-32 string literal.\n*\/\n#if ABC_CXX_CHAR32 == 2\n #define U32SL(s) U ## s\n#elif ABC_CXX_CHAR32 == 1\n #define U32SL(s) L ## s\n#endif\n\n\n\/** UTF-* encoding supported by the host. *\/\n#if ABC_HOST_API_WIN32 && defined(UNICODE)\n #define ABC_HOST_UTF 16\n#else\n #define ABC_HOST_UTF 8\n#endif\n\n\/** Default UTF character type for the host. *\/\n#if ABC_HOST_UTF == 8\n typedef char8_t char_t;\n#elif ABC_HOST_UTF == 16\n typedef char16_t char_t;\n#elif ABC_HOST_UTF == 32\n typedef char32_t char_t;\n#endif\n\n\n\/** Defines a character literal of the default host character literal type.\n\nch\n Character literal.\nreturn\n UCS character literal.\n*\/\n#if ABC_HOST_UTF == 8\n #define CL(ch) U8CL(ch)\n#elif ABC_HOST_UTF == 16\n #define CL(ch) U16CL(ch)\n#elif ABC_HOST_UTF == 32\n #define CL(ch) U32CL(ch)\n#endif\n\n\n\/** Defines a string literal of the default host string literal type.\n\ns\n String literal.\nreturn\n UTF string literal.\n*\/\n#if ABC_HOST_UTF == 8\n #define SL(s) U8SL(s)\n#elif ABC_HOST_UTF == 16\n #define SL(s) U16SL(s)\n#elif ABC_HOST_UTF == 32\n #define SL(s) U32SL(s)\n#endif\n\n} \/\/namespace abc\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Move all char types except char_t into :: namespace for consistency with C++11 char*_t<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABC_CORE_HXX\n #error Please #include <abc\/core.hxx> instead of this file\n#endif\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals\n\n\n\/** Indicates the level of UTF-8 string literals support:\n• 2 - The UTF-8 string literal prefix (u8) is supported;\n• 1 - The u8 prefix is not supported, but the compiler will generate valid UTF-8 string literals if\n the source file is UTF-8+BOM-encoded;\n• 0 - UTF-8 string literals are not supported in any way.\n*\/\n#define ABC_CXX_UTF8LIT 0\n\n\/** Indicates how char16_t is defined:\n• 2 - char16_t is a native type, distinct from uint16_t and wchar_t;\n• 1 - abc::char16_t is a typedef for native 16-bit wchar_t, distinct from uint16_t;\n• 0 - abc::char16_t is a typedef for uint16_t.\n*\/\n#define ABC_CXX_CHAR16 0\n\n\/** Indicates how char32_t is defined:\n• 2 - char32_t is a native type, distinct from uint32_t and wchar_t;\n• 1 - abc::char32_t is a typedef for native 32-bit wchar_t, distinct from uint32_t;\n• 0 - abc::char32_t is a typedef for uint32_t.\n*\/\n#define ABC_CXX_CHAR32 0\n\n#if ABC_HOST_GCC >= 40400\n \/\/ char16_t is a native type, different than uint16_t.\n #undef ABC_CXX_CHAR16\n #define ABC_CXX_CHAR16 2\n \/\/ char32_t is a native type, different than uint32_t.\n #undef ABC_CXX_CHAR32\n #define ABC_CXX_CHAR32 2\n\n #if ABC_HOST_GCC >= 40500\n \/\/ UTF-8 string literals are supported.\n #undef ABC_CXX_UTF8LIT\n #define ABC_CXX_UTF8LIT 2\n #endif\n#else \/\/if ABC_HOST_GCC >= 40400\n #if ABC_HOST_MSC\n #if !defined(_WCHAR_T_DEFINED) || !defined(_NATIVE_WCHAR_T_DEFINED)\n #error Please compile with \/Zc:wchar_t\n #endif\n\n \/\/ char16_t is not a native type, but we can typedef it as wchar_t.\n #undef ABC_CXX_CHAR16\n #define ABC_CXX_CHAR16 1\n #else\n \/\/ MSC16 will transcode non-wchar_t string literals into whatever single-byte encoding is\n \/\/ selected for the user running cl.exe; a solution has been provided in form of a hotfix\n \/\/ (<http:\/\/support.microsoft.com\/kb\/2284668\/en-us>), but it no longer seems available, and it\n \/\/ was not ported to MSC17\/VS2012, thought it seems it was finally built into MSC18\/VS2013\n \/\/ (<http:\/\/connect.microsoft.com\/VisualStudio\/feedback\/details\/773186\/pragma-execution-\n \/\/ character-set-utf-8-didnt-support-in-vc-2012>).\n \/\/\n \/\/ Here we assume that no other compiler exhibits such a random behavior, and they will all\n \/\/ emit valid UTF-8 string literals it the source file is UTF-8+BOM-encoded.\n #undef ABC_CXX_UTF8LIT\n #define ABC_CXX_UTF8LIT 1\n\n \/\/ char32_t is not a native type, but we can typedef it as wchar_t.\n #undef ABC_CXX_CHAR32\n #define ABC_CXX_CHAR32 1\n #endif\n#endif \/\/if ABC_HOST_GCC >= 40400 … else\n#if ABC_CXX_CHAR16 == 0 && ABC_CXX_CHAR32 == 0\n #error ABC_CXX_CHAR16 and\/or ABC_CXX_CHAR32 must be > 0; please fix detection logic\n#endif\n\n\n\/** UTF-8 character type. *\/\ntypedef char char8_t;\n\n\/** UTF-16 character type. *\/\n#if ABC_CXX_CHAR16 == 1\n typedef wchar_t char16_t;\n#elif ABC_CXX_CHAR16 == 0\n typedef uint16_t char16_t;\n#endif\n\n\/** UTF-32 character type. *\/\n#if ABC_CXX_CHAR32 == 1\n typedef wchar_t char32_t;\n#elif ABC_CXX_CHAR32 == 0\n typedef uint32_t char32_t;\n#endif\n\n\n\/** Defines an 8-bit character literal.\n\nch\n Character literal.\nreturn\n 8-bit character literal.\n*\/\n#define U8CL(ch) ch\n\n\n\/** Defines a UCS-16 character literal.\n\nch\n Character literal.\nreturn\n UCS-16 character literal.\n*\/\n#if ABC_CXX_CHAR16 == 2\n #define U16CL(ch) u ## ch\n#elif ABC_CXX_CHAR16 == 1\n #define U16CL(ch) L ## ch\n#elif ABC_CXX_CHAR16 == 0\n \/\/ No native type for char16_t, but we can at least use 32-bit wchar_t to store any Unicode\n \/\/ character correctly, and then truncate that to our typedef’ed char16_t.\n \/\/ TODO: make the truncation explicit (compiler warning?).\n #define U16CL(ch) ::abc::char16_t(L ## ch)\n#endif\n\n\n\/** Defines a UTF-32\/UCS-32 character literal. Code points outside the Basic Multilingual Plane are\nnot supported on all platforms.\n\nch\n Character literal.\nreturn\n UTF-32\/UCS-32 character literal.\n*\/\n#if ABC_CXX_CHAR32 == 2\n #define U32CL(ch) U ## ch\n#elif ABC_CXX_CHAR32 == 1\n #define U32CL(ch) L ## ch\n#elif ABC_CXX_CHAR32 == 0\n \/\/ No native type for char32_t, but we can at least use 16-bit wchar_t to store all Unicode BMP\n \/\/ characters correctly, and then cast that to our typedef’ed char32_t.\n #define U32CL(ch) ::abc::char32_t(L ## ch)\n#endif\n\n\n\/** Defines a UTF-8 string literal. On some platforms, this relies on the source files being encoded\nin UTF-8.\n\ns\n String literal.\nreturn\n UTF-8 string literal.\n*\/\n#if ABC_CXX_UTF8LIT == 2\n #define U8SL(s) u8 ## s\n#elif ABC_CXX_UTF8LIT == 1\n \/\/ Rely on the source files being encoded in UTF-8.\n #define U8SL(s) s\n#endif\n\n\n\/** Defines a UTF-16 string literal. Not supported on all platforms; check with #ifdef before using.\n\ns\n String literal.\nreturn\n UTF-16 string literal.\n*\/\n#if ABC_CXX_CHAR16 == 2\n #define U16SL(s) u ## s\n#elif ABC_CXX_CHAR16 == 1\n #define U16SL(s) L ## s\n#endif\n\n\n\/** Defines a UTF-32\/UCS-32 string literal. Not supported on all platforms; check with #ifdef before\nusing.\n\ns\n String literal.\nreturn\n UTF-32 string literal.\n*\/\n#if ABC_CXX_CHAR32 == 2\n #define U32SL(s) U ## s\n#elif ABC_CXX_CHAR32 == 1\n #define U32SL(s) L ## s\n#endif\n\n\n\/** UTF-* encoding supported by the host. *\/\n#if ABC_HOST_API_WIN32 && defined(UNICODE)\n #define ABC_HOST_UTF 16\n#else\n #define ABC_HOST_UTF 8\n#endif\n\nnamespace abc {\n\n\/** Default UTF character type for the host. *\/\n#if ABC_HOST_UTF == 8\n typedef char8_t char_t;\n#elif ABC_HOST_UTF == 16\n typedef char16_t char_t;\n#elif ABC_HOST_UTF == 32\n typedef char32_t char_t;\n#endif\n\n} \/\/namespace abc\n\n\n\/** Defines a character literal of the default host character literal type.\n\nch\n Character literal.\nreturn\n UCS character literal.\n*\/\n#if ABC_HOST_UTF == 8\n #define CL(ch) U8CL(ch)\n#elif ABC_HOST_UTF == 16\n #define CL(ch) U16CL(ch)\n#elif ABC_HOST_UTF == 32\n #define CL(ch) U32CL(ch)\n#endif\n\n\n\/** Defines a string literal of the default host string literal type.\n\ns\n String literal.\nreturn\n UTF string literal.\n*\/\n#if ABC_HOST_UTF == 8\n #define SL(s) U8SL(s)\n#elif ABC_HOST_UTF == 16\n #define SL(s) U16SL(s)\n#elif ABC_HOST_UTF == 32\n #define SL(s) U32SL(s)\n#endif\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"<commit_before>#include \"tests.h\"\n#include <cstdlib>\n#include <chrono>\n#include <memory>\n#include <algorithm>\n#include <unordered_set>\n#ifdef _WIN32\n #define WIN32_LEAN_AND_MEAN\n #include <Windows.h>\n #include <conio.h> \/\/ _kbhit\n#elif __ANDROID__\n #include <unistd.h> \/\/ usleep\n #include <android\/log.h>\n #include <stdarg.h>\n#else\n #include <unistd.h>\n #include <termios.h>\n#endif\n\n\nnamespace rpp\n{\n int test::asserts_failed;\n\n \/\/ there are initialization order issues with this global variable, so wrap it to guarantee initialization order\n static vector<test*>& all_tests() noexcept\n {\n static vector<test*> tests;\n return tests;\n }\n\n test::test(strview name, bool autorun) : name(name), auto_run(autorun)\n {\n all_tests().push_back(this);\n }\n\n test::~test()\n {\n if (!all_tests().empty())\n {\n auto it = find(all_tests().begin(), all_tests().end(), this);\n if (it != all_tests().end())\n all_tests().erase(it);\n }\n }\n\n void test::consolef(ConsoleColor color, const char* fmt, ...)\n {\n va_list ap;\n va_start(ap, fmt);\n #if _WIN32\n static HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);\n static const int colormap[] = {\n FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, \/\/ Default\n FOREGROUND_GREEN, \/\/ dark green\n FOREGROUND_RED | FOREGROUND_GREEN, \/\/ dark yellow\n FOREGROUND_RED, \/\/ dark red\n };\n if (color != Default) SetConsoleTextAttribute(console, colormap[color]);\n if (color == Red) vfprintf(stderr, fmt, ap);\n else vfprintf(stdout, fmt, ap);\n if (color != Default) SetConsoleTextAttribute(console, colormap[Default]);\n #elif __ANDROID__\n int priority = 0;\n switch (color) {\n case Default: priority = ANDROID_LOG_DEBUG; break;\n case Green: priority = ANDROID_LOG_INFO; break;\n case Yellow: priority = ANDROID_LOG_WARN; break;\n case Red: priority = ANDROID_LOG_ERROR; break;\n }\n __android_log_vprint(priority, \"rpp\", fmt, ap);\n #else \/\/ @todo Proper Linux & OSX implementations\n if (color == Red) vfprintf(stderr, fmt, ap);\n else vfprintf(stdout, fmt, ap);\n #endif\n }\n\n void test::assert_failed(const char* file, int line, const char* fmt, ...)\n {\n const char* filename = file + int(strview{ file }.rfindany(\"\\\\\/\") - file) + 1;\n\n char message[8192];\n va_list ap; va_start(ap, fmt);\n vsnprintf(message, 8192, fmt, ap);\n\n ++asserts_failed;\n consolef(Red, \"FAILURE %12s:%d %s\\n\", filename, line, message);\n }\n\n void test::run_test(strview methodFilter)\n {\n char title[256];\n int len = methodFilter\n ? snprintf(title, sizeof(title), \"-------- running '%s.%.*s' --------\", name.str, methodFilter.len, methodFilter.str)\n : snprintf(title, sizeof(title), \"-------- running '%s' --------\", name.str);\n\n consolef(Yellow, \"%s\\n\", title);\n run_init();\n\n if (methodFilter)\n {\n for (size_t i = 0u; i < test_count; ++i)\n if (test_funcs[i].name.find(methodFilter))\n run_test(test_funcs[i]);\n }\n else\n {\n for (size_t i = 0u; i < test_count; ++i) {\n consolef(Yellow, \"%s::%s\\n\", name.str, test_funcs[i].name.str);\n run_test(test_funcs[i]);\n }\n }\n\n run_cleanup();\n consolef(Yellow, \"%s\\n\\n\", (char*)memset(title, '-', (size_t)len)); \/\/ \"-------------\"\n }\n\n bool test::run_init()\n {\n try {\n init_test();\n return true;\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in [%s]::TestInit(): %s\\n\", name.str, e.what());\n ++asserts_failed;\n return false;\n }\n }\n\n void test::run_cleanup()\n {\n try {\n cleanup_test();\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in [%s]::TestCleanup(): %s\\n\", name.str, e.what());\n ++asserts_failed;\n }\n }\n\n void test::run_test(test_func& test)\n {\n try {\n (test.lambda.*test.func)();\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in %s::%s: %s\\n\", name.str, test.name.str, e.what());\n ++asserts_failed;\n }\n }\n\n void test::sleep(int millis)\n {\n #if _WIN32\n Sleep(millis);\n #elif __ANDROID__\n usleep(useconds_t(millis) * 1000);\n #else\n usleep(millis * 1000);\n #endif\n }\n\n#if !_WIN32 && !__ANDROID__ \/\/ Linux:\n static int _kbhit()\n {\n termios oldSettings; tcgetattr(STDIN_FILENO, &oldSettings);\n termios newSettings = oldSettings;\n newSettings.c_cc[VTIME] = 0;\n newSettings.c_cc[VMIN] = 0;\n newSettings.c_iflag &= ~(IXOFF);\n newSettings.c_lflag &= ~(ECHO | ICANON);\n tcsetattr(STDIN_FILENO, TCSANOW, &newSettings);\n\n char keycodes[16];\n int count = (int)::read(fileno(stdin), (void*)keycodes, 16);\n\n tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings);\n\n return count == 0 ? 0 : keycodes[0];\n }\n#endif\n\n#if __ANDROID__\n static int _kbhit() { return 1; }\n#endif\n\n static void pause(int millis = -1\/*forever*\/)\n {\n printf(\"\\nPress any key to continue...\\n\");\n\n using namespace chrono;\n auto start = system_clock::now();\n while (!_kbhit())\n {\n if (millis != -1)\n {\n auto elapsed = duration_cast<milliseconds>(system_clock::now() - start);\n if (elapsed.count() >= millis)\n break;\n }\n test::sleep(50);\n }\n }\n\n \/\/TestImpl(test_test)\n \/\/{\n \/\/\tImplement(test_test)\n \/\/\t{\n \/\/\t\tAssert(1 == 1);\n \/\/\t}\n \/\/}\n \/\/Instance;\n\n int test::run_tests(const char* testNamePattern)\n {\n return run_tests(&testNamePattern, 1);\n }\n\n int test::run_tests(const vector<string>& testNamePatterns)\n {\n vector<const char*> names;\n names.push_back(\"\");\n for (const string& name : testNamePatterns) names.push_back(name.c_str());\n return run_tests((int)names.size(), (char**)names.data());\n }\n\n int test::run_tests(const char** testNamePatterns, int numPatterns)\n {\n vector<const char*> names;\n names.push_back(\"\");\n names.insert(names.end(), testNamePatterns, testNamePatterns+numPatterns);\n return run_tests((int)names.size(), (char**)names.data());\n }\n\n\n\n int test::run_tests()\n {\n char empty[1] = \"\";\n char* argv[1] = { empty };\n return run_tests(1, argv);\n }\n\n int test::add_test_func(test_func func) \/\/ @note Because we can't dllexport std::vector\n {\n if (test_count == test_cap)\n {\n test_cap = test_funcs ? test_count * 2 : 8;\n auto* funcs = new test_func[test_cap];\n for (int i = 0; i < test_count; ++i) funcs[i] = move(test_funcs[i]);\n delete[] test_funcs;\n test_funcs = funcs;\n }\n test_funcs[test_count++] = move(func);\n return test_count - 1;\n }\n\n static void move_console_window()\n {\n \/\/ move console window to the other monitor to make test debugging more seamless\n \/\/ if debugger is attached with Visual Studio\n #if _WIN32 && _MSC_VER\n int numMonitors = 0;\n if (IsDebuggerPresent() && (numMonitors = GetSystemMetrics(SM_CMONITORS)) > 1)\n {\n vector<HMONITOR> mon;\n EnumDisplayMonitors(0, 0, [](HMONITOR monitor, HDC, RECT*, LPARAM data) {\n ((vector<HMONITOR>*)data)->push_back(monitor); return 1; }, (LPARAM)&mon);\n\n RECT consoleRect; GetWindowRect(GetConsoleWindow(), &consoleRect);\n HMONITOR consoleMon = MonitorFromRect(&consoleRect, MONITOR_DEFAULTTONEAREST);\n HMONITOR otherMon = consoleMon != mon[0] ? mon[0] : mon[1];\n\n MONITORINFO consoleMI = { sizeof(MONITORINFO) };\n MONITORINFO otherMI = { sizeof(MONITORINFO) };\n GetMonitorInfo(consoleMon, &consoleMI);\n GetMonitorInfo(otherMon, &otherMI);\n\n int x = consoleMI.rcMonitor.left > otherMI.rcMonitor.left \/\/ moveLeft ?\n ? otherMI.rcMonitor.right - (consoleRect.left - consoleMI.rcMonitor.left) - (consoleRect.right-consoleRect.left)\n : otherMI.rcMonitor.left + (consoleRect.left - consoleMI.rcMonitor.left);\n int y = otherMI.rcMonitor.top + (consoleRect.top - consoleMI.rcMonitor.top);\n SetWindowPos(GetConsoleWindow(), 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n #endif\n }\n\n int test::run_tests(int argc, char* argv[])\n {\n move_console_window();\n \n for (test* t : all_tests()) { \/\/ set the defaults\n if (!t->auto_run) t->test_enabled = false;\n }\n\n int numTest = 0;\n if (argc > 1)\n {\n \/\/ if arg is provided, we assume they are:\n \/\/ test_testname or testname or -test_testname or -testname\n \/\/ OR to run a specific test: testname.specifictest\n unordered_set<strview> enabled, disabled;\n\n for (int iarg = 1; iarg < argc; ++iarg)\n {\n rpp::strview arg = argv[iarg];\n rpp::strview testName = arg.next('.');\n rpp::strview specific = arg.next('.');\n\n const bool enableTest = testName[0] != '-';\n if (!enableTest) testName.chomp_first();\n\n const bool exactMatch = testName.starts_with(\"test_\");\n if (exactMatch) consolef(Yellow, \"Filtering exact tests '%s'\\n\\n\", argv[iarg]);\n else consolef(Yellow, \"Filtering substr tests '%s'\\n\\n\", argv[iarg]);\n \n for (test* t : all_tests())\n {\n if (( exactMatch && t->name == testName) ||\n (!exactMatch && t->name.find(testName)))\n {\n t->test_specific = specific;\n if (enableTest) enabled.insert(t->name);\n else disabled.insert(t->name);\n break;\n }\n }\n }\n\n if (disabled.size())\n {\n for (test* t : all_tests()) {\n if (t->auto_run) { \/\/ only consider disabling auto_run tests\n t->test_enabled = disabled.find(t->name) == disabled.end();\n if (!t->test_enabled)\n consolef(Red, \" Disabled %s\\n\", t->name.to_cstr());\n }\n }\n }\n else if (enabled.size())\n {\n for (test* t : all_tests()) { \/\/ enable whatever was requested\n t->test_enabled = enabled.find(t->name) != enabled.end();\n if (t->test_enabled)\n consolef(Green, \" Enabled %s\\n\", t->name.to_cstr());\n }\n }\n }\n else\n {\n consolef(Green, \"Running all auto-run tests\\n\");\n for (test* t : all_tests())\n if (!t->auto_run && !t->test_enabled)\n consolef(Yellow, \" Disabled NoAutoRun %s\\n\", t->name.to_cstr());\n }\n\n \/\/ run all the marked tests\n for (test* t : all_tests()) {\n if (t->test_enabled) {\n t->run_test(t->test_specific);\n ++numTest;\n }\n }\n\n if (test::asserts_failed)\n {\n consolef(Red, \"\\nWARNING: %d assertions failed!\\n\", test::asserts_failed);\n pause();\n return -1;\n }\n\n if (numTest > 0)\n consolef(Green, \"\\nSUCCESS: All test runs passed!\\n\");\n else\n consolef(Yellow, \"\\nNOTE: No tests were run! (out of %d)\\n\", (int)all_tests().size());\n\n #if _MSC_VER\n if (IsDebuggerPresent()) \/\/ only pause if we launched from Visual Studio\n pause();\n #endif\n return 0;\n }\n\n} \/\/ namespace rpp\n\n#if RPP_TESTS_DEFINE_MAIN\nint main(int argc, char* argv[])\n{\n return rpp::test::run_tests(argc, argv);\n}\n#endif\n<commit_msg>Disable pausing on __APPLE__<commit_after>#include \"tests.h\"\n#include <cstdlib>\n#include <chrono>\n#include <memory>\n#include <algorithm>\n#include <unordered_set>\n#ifdef _WIN32\n #define WIN32_LEAN_AND_MEAN\n #include <Windows.h>\n #include <conio.h> \/\/ _kbhit\n#elif __ANDROID__\n #include <unistd.h> \/\/ usleep\n #include <android\/log.h>\n #include <stdarg.h>\n#else\n #include <unistd.h>\n #include <termios.h>\n#endif\n\n\nnamespace rpp\n{\n int test::asserts_failed;\n\n \/\/ there are initialization order issues with this global variable, so wrap it to guarantee initialization order\n static vector<test*>& all_tests() noexcept\n {\n static vector<test*> tests;\n return tests;\n }\n\n test::test(strview name, bool autorun) : name(name), auto_run(autorun)\n {\n all_tests().push_back(this);\n }\n\n test::~test()\n {\n if (!all_tests().empty())\n {\n auto it = find(all_tests().begin(), all_tests().end(), this);\n if (it != all_tests().end())\n all_tests().erase(it);\n }\n }\n\n void test::consolef(ConsoleColor color, const char* fmt, ...)\n {\n va_list ap;\n va_start(ap, fmt);\n #if _WIN32\n static HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);\n static const int colormap[] = {\n FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, \/\/ Default\n FOREGROUND_GREEN, \/\/ dark green\n FOREGROUND_RED | FOREGROUND_GREEN, \/\/ dark yellow\n FOREGROUND_RED, \/\/ dark red\n };\n if (color != Default) SetConsoleTextAttribute(console, colormap[color]);\n if (color == Red) vfprintf(stderr, fmt, ap);\n else vfprintf(stdout, fmt, ap);\n if (color != Default) SetConsoleTextAttribute(console, colormap[Default]);\n #elif __ANDROID__\n int priority = 0;\n switch (color) {\n case Default: priority = ANDROID_LOG_DEBUG; break;\n case Green: priority = ANDROID_LOG_INFO; break;\n case Yellow: priority = ANDROID_LOG_WARN; break;\n case Red: priority = ANDROID_LOG_ERROR; break;\n }\n __android_log_vprint(priority, \"rpp\", fmt, ap);\n #else \/\/ @todo Proper Linux & OSX implementations\n if (color == Red) vfprintf(stderr, fmt, ap);\n else vfprintf(stdout, fmt, ap);\n #endif\n }\n\n void test::assert_failed(const char* file, int line, const char* fmt, ...)\n {\n const char* filename = file + int(strview{ file }.rfindany(\"\\\\\/\") - file) + 1;\n\n char message[8192];\n va_list ap; va_start(ap, fmt);\n vsnprintf(message, 8192, fmt, ap);\n\n ++asserts_failed;\n consolef(Red, \"FAILURE %12s:%d %s\\n\", filename, line, message);\n }\n\n void test::run_test(strview methodFilter)\n {\n char title[256];\n int len = methodFilter\n ? snprintf(title, sizeof(title), \"-------- running '%s.%.*s' --------\", name.str, methodFilter.len, methodFilter.str)\n : snprintf(title, sizeof(title), \"-------- running '%s' --------\", name.str);\n\n consolef(Yellow, \"%s\\n\", title);\n run_init();\n\n if (methodFilter)\n {\n for (size_t i = 0u; i < test_count; ++i)\n if (test_funcs[i].name.find(methodFilter))\n run_test(test_funcs[i]);\n }\n else\n {\n for (size_t i = 0u; i < test_count; ++i) {\n consolef(Yellow, \"%s::%s\\n\", name.str, test_funcs[i].name.str);\n run_test(test_funcs[i]);\n }\n }\n\n run_cleanup();\n consolef(Yellow, \"%s\\n\\n\", (char*)memset(title, '-', (size_t)len)); \/\/ \"-------------\"\n }\n\n bool test::run_init()\n {\n try {\n init_test();\n return true;\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in [%s]::TestInit(): %s\\n\", name.str, e.what());\n ++asserts_failed;\n return false;\n }\n }\n\n void test::run_cleanup()\n {\n try {\n cleanup_test();\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in [%s]::TestCleanup(): %s\\n\", name.str, e.what());\n ++asserts_failed;\n }\n }\n\n void test::run_test(test_func& test)\n {\n try {\n (test.lambda.*test.func)();\n } catch (const std::exception& e) {\n consolef(Red, \"Unhandled Exception in %s::%s: %s\\n\", name.str, test.name.str, e.what());\n ++asserts_failed;\n }\n }\n\n void test::sleep(int millis)\n {\n #if _WIN32\n Sleep(millis);\n #elif __ANDROID__\n usleep(useconds_t(millis) * 1000);\n #else\n usleep(millis * 1000);\n #endif\n }\n\n#if !_WIN32 && !__ANDROID__ && !__APPLE__ \/\/ Linux:\n static int _kbhit()\n {\n termios oldSettings; tcgetattr(STDIN_FILENO, &oldSettings);\n termios newSettings = oldSettings;\n newSettings.c_cc[VTIME] = 0;\n newSettings.c_cc[VMIN] = 0;\n newSettings.c_iflag &= ~(IXOFF);\n newSettings.c_lflag &= ~(ECHO | ICANON);\n tcsetattr(STDIN_FILENO, TCSANOW, &newSettings);\n\n char keycodes[16];\n int count = (int)::read(fileno(stdin), (void*)keycodes, 16);\n\n tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings);\n\n return count == 0 ? 0 : keycodes[0];\n }\n#endif\n\n#if __ANDROID__ || __APPLE__\n static int _kbhit() { return 1; }\n#endif\n\n static void pause(int millis = -1\/*forever*\/)\n {\n printf(\"\\nPress any key to continue...\\n\");\n\n using namespace chrono;\n auto start = system_clock::now();\n while (!_kbhit())\n {\n if (millis != -1)\n {\n auto elapsed = duration_cast<milliseconds>(system_clock::now() - start);\n if (elapsed.count() >= millis)\n break;\n }\n test::sleep(50);\n }\n }\n\n \/\/TestImpl(test_test)\n \/\/{\n \/\/\tImplement(test_test)\n \/\/\t{\n \/\/\t\tAssert(1 == 1);\n \/\/\t}\n \/\/}\n \/\/Instance;\n\n int test::run_tests(const char* testNamePattern)\n {\n return run_tests(&testNamePattern, 1);\n }\n\n int test::run_tests(const vector<string>& testNamePatterns)\n {\n vector<const char*> names;\n names.push_back(\"\");\n for (const string& name : testNamePatterns) names.push_back(name.c_str());\n return run_tests((int)names.size(), (char**)names.data());\n }\n\n int test::run_tests(const char** testNamePatterns, int numPatterns)\n {\n vector<const char*> names;\n names.push_back(\"\");\n names.insert(names.end(), testNamePatterns, testNamePatterns+numPatterns);\n return run_tests((int)names.size(), (char**)names.data());\n }\n\n\n\n int test::run_tests()\n {\n char empty[1] = \"\";\n char* argv[1] = { empty };\n return run_tests(1, argv);\n }\n\n int test::add_test_func(test_func func) \/\/ @note Because we can't dllexport std::vector\n {\n if (test_count == test_cap)\n {\n test_cap = test_funcs ? test_count * 2 : 8;\n auto* funcs = new test_func[test_cap];\n for (int i = 0; i < test_count; ++i) funcs[i] = move(test_funcs[i]);\n delete[] test_funcs;\n test_funcs = funcs;\n }\n test_funcs[test_count++] = move(func);\n return test_count - 1;\n }\n\n static void move_console_window()\n {\n \/\/ move console window to the other monitor to make test debugging more seamless\n \/\/ if debugger is attached with Visual Studio\n #if _WIN32 && _MSC_VER\n int numMonitors = 0;\n if (IsDebuggerPresent() && (numMonitors = GetSystemMetrics(SM_CMONITORS)) > 1)\n {\n vector<HMONITOR> mon;\n EnumDisplayMonitors(0, 0, [](HMONITOR monitor, HDC, RECT*, LPARAM data) {\n ((vector<HMONITOR>*)data)->push_back(monitor); return 1; }, (LPARAM)&mon);\n\n RECT consoleRect; GetWindowRect(GetConsoleWindow(), &consoleRect);\n HMONITOR consoleMon = MonitorFromRect(&consoleRect, MONITOR_DEFAULTTONEAREST);\n HMONITOR otherMon = consoleMon != mon[0] ? mon[0] : mon[1];\n\n MONITORINFO consoleMI = { sizeof(MONITORINFO) };\n MONITORINFO otherMI = { sizeof(MONITORINFO) };\n GetMonitorInfo(consoleMon, &consoleMI);\n GetMonitorInfo(otherMon, &otherMI);\n\n int x = consoleMI.rcMonitor.left > otherMI.rcMonitor.left \/\/ moveLeft ?\n ? otherMI.rcMonitor.right - (consoleRect.left - consoleMI.rcMonitor.left) - (consoleRect.right-consoleRect.left)\n : otherMI.rcMonitor.left + (consoleRect.left - consoleMI.rcMonitor.left);\n int y = otherMI.rcMonitor.top + (consoleRect.top - consoleMI.rcMonitor.top);\n SetWindowPos(GetConsoleWindow(), 0, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);\n }\n #endif\n }\n\n int test::run_tests(int argc, char* argv[])\n {\n move_console_window();\n \n for (test* t : all_tests()) { \/\/ set the defaults\n if (!t->auto_run) t->test_enabled = false;\n }\n\n int numTest = 0;\n if (argc > 1)\n {\n \/\/ if arg is provided, we assume they are:\n \/\/ test_testname or testname or -test_testname or -testname\n \/\/ OR to run a specific test: testname.specifictest\n unordered_set<strview> enabled, disabled;\n\n for (int iarg = 1; iarg < argc; ++iarg)\n {\n rpp::strview arg = argv[iarg];\n rpp::strview testName = arg.next('.');\n rpp::strview specific = arg.next('.');\n\n const bool enableTest = testName[0] != '-';\n if (!enableTest) testName.chomp_first();\n\n const bool exactMatch = testName.starts_with(\"test_\");\n if (exactMatch) consolef(Yellow, \"Filtering exact tests '%s'\\n\\n\", argv[iarg]);\n else consolef(Yellow, \"Filtering substr tests '%s'\\n\\n\", argv[iarg]);\n \n for (test* t : all_tests())\n {\n if (( exactMatch && t->name == testName) ||\n (!exactMatch && t->name.find(testName)))\n {\n t->test_specific = specific;\n if (enableTest) enabled.insert(t->name);\n else disabled.insert(t->name);\n break;\n }\n }\n }\n\n if (disabled.size())\n {\n for (test* t : all_tests()) {\n if (t->auto_run) { \/\/ only consider disabling auto_run tests\n t->test_enabled = disabled.find(t->name) == disabled.end();\n if (!t->test_enabled)\n consolef(Red, \" Disabled %s\\n\", t->name.to_cstr());\n }\n }\n }\n else if (enabled.size())\n {\n for (test* t : all_tests()) { \/\/ enable whatever was requested\n t->test_enabled = enabled.find(t->name) != enabled.end();\n if (t->test_enabled)\n consolef(Green, \" Enabled %s\\n\", t->name.to_cstr());\n }\n }\n }\n else\n {\n consolef(Green, \"Running all auto-run tests\\n\");\n for (test* t : all_tests())\n if (!t->auto_run && !t->test_enabled)\n consolef(Yellow, \" Disabled NoAutoRun %s\\n\", t->name.to_cstr());\n }\n\n \/\/ run all the marked tests\n for (test* t : all_tests()) {\n if (t->test_enabled) {\n t->run_test(t->test_specific);\n ++numTest;\n }\n }\n\n if (test::asserts_failed)\n {\n consolef(Red, \"\\nWARNING: %d assertions failed!\\n\", test::asserts_failed);\n #if _MSC_VER\n pause();\n #endif\n return -1;\n }\n\n if (numTest > 0)\n consolef(Green, \"\\nSUCCESS: All test runs passed!\\n\");\n else\n consolef(Yellow, \"\\nNOTE: No tests were run! (out of %d)\\n\", (int)all_tests().size());\n\n #if _MSC_VER\n if (IsDebuggerPresent()) \/\/ only pause if we launched from Visual Studio\n pause();\n #endif\n return 0;\n }\n\n} \/\/ namespace rpp\n\n#if RPP_TESTS_DEFINE_MAIN\nint main(int argc, char* argv[])\n{\n return rpp::test::run_tests(argc, argv);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ Causal Dynamical Triangulations in C++ using CGAL\n\/\/\/\n\/\/\/ Copyright © 2018 Adam Getchell\n\/\/\/\n\/\/\/ Geometric quantities of Manifold used by MoveAlgorithm.\n\/\/\/\n\/\/\/ @file Geometry.hpp\n\/\/\/ @brief Data structures for geometry\n\/\/\/ @author Adam Getchell\n\n#ifndef CDT_PLUSPLUS_GEOMETRY_HPP\n#define CDT_PLUSPLUS_GEOMETRY_HPP\n\n#include <S3Triangulation.hpp>\n#include <algorithm>\n#include <cstddef>\n#include <gsl\/gsl>\n\nenum class Cell_type\n{\n THREE_ONE = 31,\n TWO_TWO = 22,\n ONE_THREE = 13\n};\n\n\/\/\/ Geometry class template\n\/\/\/ @tparam dimension Dimensionality of geometry\ntemplate <std::size_t dimension>\nstruct Geometry;\n\n\/\/\/ 3D Geometry\ntemplate <>\nstruct Geometry<3>\n{\n \/\/\/ @brief Default ctor\n Geometry()\n : number_of_vertices{0}\n , number_of_edges{0}\n , number_of_faces{0}\n , number_of_cells{0}\n {}\n\n \/\/\/ @brief Constructor with triangulation\n \/\/\/ @param triangulation Triangulation for which Geometry is being\n \/\/\/ calculated\n explicit Geometry(const std::unique_ptr<Delaunay3>& triangulation)\n : number_of_vertices{triangulation->number_of_vertices()}\n , number_of_edges{triangulation->number_of_finite_edges()}\n , number_of_faces{triangulation->number_of_finite_facets()}\n , number_of_cells{triangulation->number_of_finite_cells()}\n , cells{classify_cells(collect_cells(triangulation))}\n , edges{collect_edges(triangulation)}\n , vertices{collect_vertices(triangulation)}\n , three_one{filter_cells(cells, Cell_type::THREE_ONE)}\n , two_two{filter_cells(cells, Cell_type::TWO_TWO)}\n , one_three{filter_cells(cells, Cell_type::ONE_THREE)}\n {}\n\n \/\/\/ @brief Collect all finite cells of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all the finite cells in the triangulation\n template <typename T>\n std::vector<Cell_handle> collect_cells(T& universe)\n {\n Expects(universe != nullptr);\n std::vector<Cell_handle> init_cells;\n init_cells.reserve(number_of_cells);\n Delaunay3::Finite_cells_iterator cit;\n for (cit = universe->finite_cells_begin();\n cit != universe->finite_cells_end(); ++cit)\n { init_cells.emplace_back(cit); }\n Ensures(init_cells.size() == universe->number_of_finite_cells());\n return init_cells;\n }\n\n std::vector<Cell_handle> classify_cells(std::vector<Cell_handle> cells)\n {\n Expects(!cells.empty());\n std::vector<Vertex_handle> cell_vertices;\n cell_vertices.reserve(4);\n std::vector<size_t> vertex_timevalues;\n vertex_timevalues.reserve(4);\n for (auto& c : cells)\n {\n std::cout << \"Cell info was \" << c->info() << '\\n';\n for (size_t j = 0; j < 4; ++j)\n {\n cell_vertices.emplace_back(c->vertex(j));\n vertex_timevalues.emplace_back(c->vertex(j)->info());\n std::cout << \"Cell vertex \" << j << \" has timevalue \"\n << c->vertex(j)->info() << '\\n';\n }\n\n auto max_timevalue =\n std::max_element(vertex_timevalues.begin(), vertex_timevalues.end());\n auto max_timevalue_vertices =\n std::count_if(cell_vertices.begin(), cell_vertices.end(),\n [max_timevalue](auto const& vertex) {\n return vertex->info() == *max_timevalue;\n });\n\n switch (max_timevalue_vertices)\n {\n case 1:\n c->info() = static_cast<size_t>(Cell_type::ONE_THREE);\n break;\n case 2:\n c->info() = static_cast<size_t>(Cell_type::TWO_TWO);\n break;\n case 3:\n c->info() = static_cast<size_t>(Cell_type::THREE_ONE);\n break;\n default:\n throw std::logic_error(\"Mis-classified cell.\");\n }\n std::cout << \"Max timevalue is \" << *max_timevalue << '\\n';\n std::cout << \"There are \" << max_timevalue_vertices\n << \" vertices with max timeslice in the cell.\\n\";\n std::cout << \"Cell info is now \" << c->info() << '\\n';\n std::cout << \"Next cell:\\n\";\n cell_vertices.clear();\n vertex_timevalues.clear();\n }\n return cells;\n }\n\n \/\/\/ @brief Filter simplices by Cell_type\n \/\/\/ @param cells_v The vector of simplices to filter\n \/\/\/ @param cell_t The Cell_type to filter by\n \/\/\/ @return A vector of Cell_type simplices\n std::vector<Cell_handle> filter_cells(std::vector<Cell_handle> cells_v,\n const Cell_type cell_t)\n {\n std::vector<Cell_handle> filtered_cells(cells_v.size());\n auto it =\n std::copy_if(cells_v.begin(), cells_v.end(), filtered_cells.begin(),\n [&](auto const& cell) {\n return cell->info() == static_cast<std::size_t>(cell_t);\n });\n filtered_cells.resize(std::distance(filtered_cells.begin(), it));\n return filtered_cells;\n }\n\n \/\/\/ @brief Collect all finite edges of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all the finite edges in the triangulation\n template <typename T>\n std::vector<Edge_handle> collect_edges(T& universe)\n {\n Expects(universe != nullptr);\n std::vector<Edge_handle> init_edges;\n init_edges.reserve(number_of_edges);\n Delaunay3::Finite_edges_iterator eit;\n for (eit = universe->finite_edges_begin();\n eit != universe->finite_edges_end(); ++eit)\n {\n Cell_handle ch = eit->first;\n Edge_handle thisEdge{ch, ch->index(ch->vertex(eit->second)),\n ch->index(ch->vertex(eit->third))};\n init_edges.emplace_back(thisEdge);\n }\n Ensures(init_edges.size() == universe->number_of_finite_edges());\n return init_edges;\n }\n\n \/\/\/ @brief Collect all finite vertices of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all finite vertices in the triangulation\n template <typename T>\n std::vector<Vertex_handle> collect_vertices(T& universe)\n {\n Expects(universe != nullptr);\n std::vector<Vertex_handle> init_vertices;\n init_vertices.reserve(number_of_vertices);\n Delaunay3::Finite_vertices_iterator fit;\n for (fit = universe->finite_vertices_begin();\n fit != universe->finite_vertices_end(); ++fit)\n { init_vertices.emplace_back(fit); }\n Ensures(init_vertices.size() == universe->number_of_vertices());\n return init_vertices;\n }\n\n std::size_t number_of_vertices;\n std::size_t number_of_edges;\n std::size_t number_of_faces;\n std::size_t number_of_cells;\n std::vector<Cell_handle> cells;\n std::vector<Edge_handle> edges;\n std::vector<Vertex_handle> vertices;\n std::vector<Cell_handle> three_one;\n std::vector<Cell_handle> two_two;\n std::vector<Cell_handle> one_three;\n std::vector<Edge_handle> timelike_edges;\n std::vector<Edge_handle> spacelike_edges;\n};\n\nusing Geometry3 = Geometry<3>;\n\n#endif \/\/ CDT_PLUSPLUS_GEOMETRY_HPP<commit_msg>Some best practices<commit_after>\/\/\/ Causal Dynamical Triangulations in C++ using CGAL\n\/\/\/\n\/\/\/ Copyright © 2018 Adam Getchell\n\/\/\/\n\/\/\/ Geometric quantities of Manifold used by MoveAlgorithm.\n\/\/\/\n\/\/\/ @file Geometry.hpp\n\/\/\/ @brief Data structures for geometry\n\/\/\/ @author Adam Getchell\n\n#ifndef CDT_PLUSPLUS_GEOMETRY_HPP\n#define CDT_PLUSPLUS_GEOMETRY_HPP\n\n#include <S3Triangulation.hpp>\n#include <algorithm>\n#include <cstddef>\n#include <gsl\/gsl>\n\nenum class Cell_type\n{\n THREE_ONE = 31,\n TWO_TWO = 22,\n ONE_THREE = 13\n};\n\n\/\/\/ Geometry class template\n\/\/\/ @tparam dimension Dimensionality of geometry\ntemplate <std::size_t dimension>\nstruct Geometry;\n\n\/\/\/ 3D Geometry\ntemplate <>\nstruct Geometry<3>\n{\n \/\/\/ @brief Default ctor\n Geometry()\n : number_of_vertices{0}\n , number_of_edges{0}\n , number_of_faces{0}\n , number_of_cells{0}\n {}\n\n \/\/\/ @brief Constructor with triangulation\n \/\/\/ @param triangulation Triangulation for which Geometry is being\n \/\/\/ calculated\n explicit Geometry(const std::unique_ptr<Delaunay3>& triangulation)\n : number_of_vertices{triangulation->number_of_vertices()}\n , number_of_edges{triangulation->number_of_finite_edges()}\n , number_of_faces{triangulation->number_of_finite_facets()}\n , number_of_cells{triangulation->number_of_finite_cells()}\n , cells{classify_cells(collect_cells(triangulation))}\n , edges{collect_edges(triangulation)}\n , vertices{collect_vertices(triangulation)}\n , three_one{filter_cells(cells, Cell_type::THREE_ONE)}\n , two_two{filter_cells(cells, Cell_type::TWO_TWO)}\n , one_three{filter_cells(cells, Cell_type::ONE_THREE)}\n {}\n\n \/\/\/ @brief Collect all finite cells of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all the finite cells in the triangulation\n template <typename T>\n [[nodiscard]] auto collect_cells(T& universe) -> std::vector<Cell_handle>\n {\n Expects(universe != nullptr);\n std::vector<Cell_handle> init_cells;\n init_cells.reserve(number_of_cells);\n Delaunay3::Finite_cells_iterator cit;\n for (cit = universe->finite_cells_begin();\n cit != universe->finite_cells_end(); ++cit)\n { init_cells.emplace_back(cit); }\n Ensures(init_cells.size() == universe->number_of_finite_cells());\n return init_cells;\n }\n\n [[nodiscard]] auto classify_cells(std::vector<Cell_handle> cells)\n -> std::vector<Cell_handle>\n {\n Expects(!cells.empty());\n std::vector<Vertex_handle> cell_vertices;\n cell_vertices.reserve(4);\n std::vector<size_t> vertex_timevalues;\n vertex_timevalues.reserve(4);\n for (auto& c : cells)\n {\n std::cout << \"Cell info was \" << c->info() << '\\n';\n for (size_t j = 0; j < 4; ++j)\n {\n cell_vertices.emplace_back(c->vertex(j));\n vertex_timevalues.emplace_back(c->vertex(j)->info());\n std::cout << \"Cell vertex \" << j << \" has timevalue \"\n << c->vertex(j)->info() << '\\n';\n }\n\n auto max_timevalue =\n std::max_element(vertex_timevalues.begin(), vertex_timevalues.end());\n auto max_timevalue_vertices =\n std::count_if(cell_vertices.begin(), cell_vertices.end(),\n [max_timevalue](auto const& vertex) {\n return vertex->info() == *max_timevalue;\n });\n\n switch (max_timevalue_vertices)\n {\n case 1:\n c->info() = static_cast<size_t>(Cell_type::ONE_THREE);\n break;\n case 2:\n c->info() = static_cast<size_t>(Cell_type::TWO_TWO);\n break;\n case 3:\n c->info() = static_cast<size_t>(Cell_type::THREE_ONE);\n break;\n default:\n throw std::logic_error(\"Mis-classified cell.\");\n }\n std::cout << \"Max timevalue is \" << *max_timevalue << '\\n';\n std::cout << \"There are \" << max_timevalue_vertices\n << \" vertices with max timeslice in the cell.\\n\";\n std::cout << \"Cell info is now \" << c->info() << '\\n';\n std::cout << \"Next cell:\\n\";\n cell_vertices.clear();\n vertex_timevalues.clear();\n }\n return cells;\n }\n\n \/\/\/ @brief Filter simplices by Cell_type\n \/\/\/ @param cells_v The vector of simplices to filter\n \/\/\/ @param cell_t The Cell_type to filter by\n \/\/\/ @return A vector of Cell_type simplices\n [[nodiscard]] auto filter_cells(std::vector<Cell_handle> cells_v,\n const Cell_type cell_t)\n -> std::vector<Cell_handle>\n {\n std::vector<Cell_handle> filtered_cells(cells_v.size());\n auto it =\n std::copy_if(cells_v.begin(), cells_v.end(), filtered_cells.begin(),\n [&](auto const& cell) {\n return cell->info() == static_cast<std::size_t>(cell_t);\n });\n filtered_cells.resize(std::distance(filtered_cells.begin(), it));\n return filtered_cells;\n }\n\n \/\/\/ @brief Collect all finite edges of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all the finite edges in the triangulation\n template <typename T>\n [[nodiscard]] auto collect_edges(T& universe) -> std::vector<Edge_handle>\n {\n Expects(universe != nullptr);\n std::vector<Edge_handle> init_edges;\n init_edges.reserve(number_of_edges);\n Delaunay3::Finite_edges_iterator eit;\n for (eit = universe->finite_edges_begin();\n eit != universe->finite_edges_end(); ++eit)\n {\n Cell_handle ch = eit->first;\n Edge_handle thisEdge{ch, ch->index(ch->vertex(eit->second)),\n ch->index(ch->vertex(eit->third))};\n init_edges.emplace_back(thisEdge);\n }\n Ensures(init_edges.size() == universe->number_of_finite_edges());\n return init_edges;\n }\n\n \/\/\/ @brief Collect all finite vertices of the triangulation\n \/\/\/ @tparam T Reference type of triangulation\n \/\/\/ @param universe Reference to triangulation\n \/\/\/ @return Vector of all finite vertices in the triangulation\n template <typename T>\n [[nodiscard]] auto collect_vertices(T& universe) -> std::vector<Vertex_handle>\n {\n Expects(universe != nullptr);\n std::vector<Vertex_handle> init_vertices;\n init_vertices.reserve(number_of_vertices);\n Delaunay3::Finite_vertices_iterator fit;\n for (fit = universe->finite_vertices_begin();\n fit != universe->finite_vertices_end(); ++fit)\n { init_vertices.emplace_back(fit); }\n Ensures(init_vertices.size() == universe->number_of_vertices());\n return init_vertices;\n }\n\n std::size_t number_of_vertices;\n std::size_t number_of_edges;\n std::size_t number_of_faces;\n std::size_t number_of_cells;\n std::vector<Cell_handle> cells;\n std::vector<Edge_handle> edges;\n std::vector<Vertex_handle> vertices;\n std::vector<Cell_handle> three_one;\n std::vector<Cell_handle> two_two;\n std::vector<Cell_handle> one_three;\n std::vector<Edge_handle> timelike_edges;\n std::vector<Edge_handle> spacelike_edges;\n};\n\nusing Geometry3 = Geometry<3>;\n\n#endif \/\/ CDT_PLUSPLUS_GEOMETRY_HPP<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliTaskCDBconnect.h\"\n\n#include <TChain.h>\n#include <TFile.h>\n#include <TGeoGlobalMagField.h>\n#include \"TGeoManager.h\"\n \n#include \"AliAnalysisManager.h\"\n#include \"AliGeomManager.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPManager.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliLog.h\"\n\nClassImp(AliTaskCDBconnect)\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::AliTaskCDBconnect():\n AliAnalysisTask(),\n fRun(0),\n fRunChanged(kFALSE),\n fESDhandler(NULL),\n fESD(NULL),\n fGRPManager(NULL)\n{\n\/\/ Dummy constructor\n}\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::AliTaskCDBconnect(const char* name):\n AliAnalysisTask(name, \"ESD analysis tender car\"),\n fRun(0),\n fRunChanged(kFALSE),\n fESDhandler(NULL),\n fESD(NULL),\n fGRPManager(NULL)\n{\n\/\/ Default constructor\n AliCDBManager *cdb = AliCDBManager::Instance();\n cdb->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n cdb->SetRun(0);\n DefineInput (0, TChain::Class());\n\/\/ DefineOutput(0, AliESDEvent::Class());\n}\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::~AliTaskCDBconnect()\n{\n\/\/ Destructor\n if (fGRPManager) delete fGRPManager;\n\/\/ if (gGeoManager) delete gGeoManager;\n} \n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::LocalInit()\n{\n\/\/ Init CDB locally if run number is defined.\n}\n \n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::ConnectInputData(Option_t* \/*option*\/)\n{\n\/\/ Connect the input data, create CDB manager.\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::InitGRP()\n{\n\/\/ Initialize geometry and mag. field\n if (!fGRPManager) {\n \/\/ magnetic field\n if (!TGeoGlobalMagField::Instance()->GetField()) {\n printf(\"AliCDBconnect: #### Loading field map...\\n\");\n fGRPManager = new AliGRPManager();\n if(!fGRPManager->ReadGRPEntry()) { \n AliError(\"Cannot get GRP entry\"); \n }\n if( !fGRPManager->SetMagField() ) { \n AliError(\"Problem with magnetic field setup\"); \n }\n }\n\n \/\/ geometry\n if (!gGeoManager) {\n printf(\"AliCDBconnect: #### Loading geometry...\\n\");\n AliGeomManager::LoadGeometry();\n if( !AliGeomManager::ApplyAlignObjsFromCDB(\"GRP ITS TPC\") ) {\n AliError(\"Problem with align objects\"); \n }\n } \n } \n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::CreateOutputObjects()\n{\n\/\/ Init CDB locally if run number is defined.\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) AliFatal(\"No analysis manager\");\n fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());\n \n if (!fESDhandler) {\n AliFatal(\"No ESD input event handler connected\");\n return;\n } \n \/\/ Try to get event number before the first event is read (this has precedence\n \/\/ over existing fRun)\n Int_t run = mgr->GetRunFromPath();\n if (!run) {\n AliWarning(\"AliTaskCDBconnect: Could not set run from path\");\n if (!fRun) {\n AliError(\"AliTaskCDBconnect: Run not set - no CDB connection\");\n return;\n } \n }\n \/\/ Create CDB manager\n AliCDBManager *cdb = AliCDBManager::Instance();\n \/\/ If CDB is already locked, return\n if (cdb->GetLock()) return;\n \/\/ SetDefault storage. Specific storages must be set by TaskCDBconnectSupply::Init()\n \/\/ cdb->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n if (cdb->IsDefaultStorageSet()) {\n AliError(\"AliTaskCDBconnect: CDB default storage already set!\");\n } else {\n cdb->SetDefaultStorage(\"alien:\/\/?Folder=\/alice\/data\/2010\/OCDB\");\n } \n if (run && (run != fRun)) {\n fRunChanged = kTRUE;\n fRun = run;\n } else {\n fRunChanged = kFALSE;\n }\n \/\/ Set run\n printf(\"AliCDBconnect: #### Setting run to: %d\\n\", fRun);\n cdb->SetRun(fRun);\n \/\/ Initialize GRP manager only once\n if (fRun) InitGRP();\n}\n\n\/\/______________________________________________________________________________\nBool_t AliTaskCDBconnect::Notify()\n{\n\/\/ Init CDB locally if run number is defined.\n CreateOutputObjects();\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::Exec(Option_t* \/*option*\/)\n{\n\/\/\n\/\/ Execute all supplied analysis of one event. Notify run change via RunChanged().\n fESD = fESDhandler->GetEvent();\n \/\/ Intercept when the run number changed\n if (fRun != fESD->GetRunNumber()) {\n fRunChanged = kTRUE;\n fRun = fESD->GetRunNumber();\n Warning(\"Exec\", \"Run number changed in ESDEvent to %d\", fRun);\n AliCDBManager::Instance()->SetRun(fRun);\n }\n\/\/ PostData(0, fESD);\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::Terminate(Option_t *)\n{\n\/\/ Initialize CDB also in Terminate\n CreateOutputObjects();\n}\n<commit_msg>Changed back to raw:\/\/<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliTaskCDBconnect.h\"\n\n#include <TChain.h>\n#include <TFile.h>\n#include <TGeoGlobalMagField.h>\n#include \"TGeoManager.h\"\n \n#include \"AliAnalysisManager.h\"\n#include \"AliGeomManager.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPManager.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliLog.h\"\n\nClassImp(AliTaskCDBconnect)\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::AliTaskCDBconnect():\n AliAnalysisTask(),\n fRun(0),\n fRunChanged(kFALSE),\n fESDhandler(NULL),\n fESD(NULL),\n fGRPManager(NULL)\n{\n\/\/ Dummy constructor\n}\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::AliTaskCDBconnect(const char* name):\n AliAnalysisTask(name, \"ESD analysis tender car\"),\n fRun(0),\n fRunChanged(kFALSE),\n fESDhandler(NULL),\n fESD(NULL),\n fGRPManager(NULL)\n{\n\/\/ Default constructor\n AliCDBManager *cdb = AliCDBManager::Instance();\n cdb->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n cdb->SetRun(0);\n DefineInput (0, TChain::Class());\n\/\/ DefineOutput(0, AliESDEvent::Class());\n}\n\n\/\/______________________________________________________________________________\nAliTaskCDBconnect::~AliTaskCDBconnect()\n{\n\/\/ Destructor\n if (fGRPManager) delete fGRPManager;\n\/\/ if (gGeoManager) delete gGeoManager;\n} \n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::LocalInit()\n{\n\/\/ Init CDB locally if run number is defined.\n}\n \n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::ConnectInputData(Option_t* \/*option*\/)\n{\n\/\/ Connect the input data, create CDB manager.\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::InitGRP()\n{\n\/\/ Initialize geometry and mag. field\n if (!fGRPManager) {\n \/\/ magnetic field\n if (!TGeoGlobalMagField::Instance()->GetField()) {\n printf(\"AliCDBconnect: #### Loading field map...\\n\");\n fGRPManager = new AliGRPManager();\n if(!fGRPManager->ReadGRPEntry()) { \n AliError(\"Cannot get GRP entry\"); \n }\n if( !fGRPManager->SetMagField() ) { \n AliError(\"Problem with magnetic field setup\"); \n }\n }\n\n \/\/ geometry\n if (!gGeoManager) {\n printf(\"AliCDBconnect: #### Loading geometry...\\n\");\n AliGeomManager::LoadGeometry();\n if( !AliGeomManager::ApplyAlignObjsFromCDB(\"GRP ITS TPC\") ) {\n AliError(\"Problem with align objects\"); \n }\n } \n } \n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::CreateOutputObjects()\n{\n\/\/ Init CDB locally if run number is defined.\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) AliFatal(\"No analysis manager\");\n fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());\n \n if (!fESDhandler) {\n AliFatal(\"No ESD input event handler connected\");\n return;\n } \n \/\/ Try to get event number before the first event is read (this has precedence\n \/\/ over existing fRun)\n Int_t run = mgr->GetRunFromPath();\n if (!run) {\n AliWarning(\"AliTaskCDBconnect: Could not set run from path\");\n if (!fRun) {\n AliError(\"AliTaskCDBconnect: Run not set - no CDB connection\");\n return;\n } \n }\n \/\/ Create CDB manager\n AliCDBManager *cdb = AliCDBManager::Instance();\n \/\/ If CDB is already locked, return\n if (cdb->GetLock()) return;\n \/\/ SetDefault storage. Specific storages must be set by TaskCDBconnectSupply::Init()\n \/\/ cdb->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n if (cdb->IsDefaultStorageSet()) {\n AliError(\"AliTaskCDBconnect: CDB default storage already set!\");\n } else {\n cdb->SetDefaultStorage(\"raw:\/\/\");\n } \n if (run && (run != fRun)) {\n fRunChanged = kTRUE;\n fRun = run;\n } else {\n fRunChanged = kFALSE;\n }\n \/\/ Set run\n printf(\"AliCDBconnect: #### Setting run to: %d\\n\", fRun);\n cdb->SetRun(fRun);\n \/\/ Initialize GRP manager only once\n if (fRun) InitGRP();\n}\n\n\/\/______________________________________________________________________________\nBool_t AliTaskCDBconnect::Notify()\n{\n\/\/ Init CDB locally if run number is defined.\n CreateOutputObjects();\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::Exec(Option_t* \/*option*\/)\n{\n\/\/\n\/\/ Execute all supplied analysis of one event. Notify run change via RunChanged().\n fESD = fESDhandler->GetEvent();\n \/\/ Intercept when the run number changed\n if (fRun != fESD->GetRunNumber()) {\n fRunChanged = kTRUE;\n fRun = fESD->GetRunNumber();\n Warning(\"Exec\", \"Run number changed in ESDEvent to %d\", fRun);\n AliCDBManager::Instance()->SetRun(fRun);\n }\n\/\/ PostData(0, fESD);\n}\n\n\/\/______________________________________________________________________________\nvoid AliTaskCDBconnect::Terminate(Option_t *)\n{\n\/\/ Initialize CDB also in Terminate\n CreateOutputObjects();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/version.hpp>\n#include <gtest\/gtest.h>\n\nTEST(Stan, macro) {\n EXPECT_EQ(2, STAN_MAJOR);\n EXPECT_EQ(22, STAN_MINOR);\n EXPECT_EQ(0, STAN_PATCH);\n}\n\nTEST(Stan, version) {\n EXPECT_EQ(\"2\", stan::MAJOR_VERSION);\n EXPECT_EQ(\"22\", stan::MINOR_VERSION);\n EXPECT_EQ(\"0\", stan::PATCH_VERSION);\n}\n<commit_msg>Updated stan version test.<commit_after>#include <stan\/version.hpp>\n#include <gtest\/gtest.h>\n\nTEST(Stan, macro) {\n EXPECT_EQ(2, STAN_MAJOR);\n EXPECT_EQ(22, STAN_MINOR);\n EXPECT_EQ(1, STAN_PATCH);\n}\n\nTEST(Stan, version) {\n EXPECT_EQ(\"2\", stan::MAJOR_VERSION);\n EXPECT_EQ(\"22\", stan::MINOR_VERSION);\n EXPECT_EQ(\"1\", stan::PATCH_VERSION);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nclass HandshakeF3MessageExt : public HandshakeF3Message {\n public:\n HandshakeF3MessageExt() : HandshakeF3Message() {}\n\n void update_static_header_ext() {\n HandshakeF3Message::update_static_header();\n }\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nTEST(MessageTest, HandshakeF3__Constructor_01) {\n HandshakeF3MessageExt message;\n\n \/*\n uint16_t session_id_length;\n std::string session_id;\n uint16_t path_length;\n std::string path;\n std::vector<uint8_t> other_auth;\n *\/\n\n message.session_id_length = 64;\n std::string session_id(\"session-id123456789012345678901234567890123456789012345678901234\");\n message.session_id = session_id;\n\n message.path = 32;\n std::string path(\"path5678901234567890123456789012\");\n message.path = path;\n\n uint8_t auth[] = \"auth5678901234567890123456789012\";\n message.other_auth = std::vector<uint8_t>(auth, auth + Message::AuthLength);\n\n message.update_static_header_ext();\n\n uint8_t buf[1024];\n message.write(buf);\n\n \/\/ 15 + 2 + 64 + 2 + 32 + 32 = 147\n uint8_t expected_values[147];\n\n uint32_t message_size = 147;\n uint16_t header_size = message_size;\n MessageType type = MessageType::Handshake2;\n uint32_t request_id = 0;\n uint32_t ack_id = 0;\n\n std::memcpy(&expected_values[StaticHeaders::MessageSizeOffset], &message_size,\n sizeof(uint32_t));\n std::memcpy(&expected_values[StaticHeaders::HeaderSizeOffset], &header_size,\n sizeof(uint16_t));\n std::memcpy(&expected_values[StaticHeaders::TypeOffset], &type,\n sizeof(uint8_t));\n std::memcpy(&expected_values[StaticHeaders::RequestIdOffset], &request_id,\n sizeof(request_id));\n std::memcpy(&expected_values[StaticHeaders::AckIdOffset], &ack_id,\n sizeof(ack_id));\n\n uint8_t SessionIdLengthOffset = StaticHeaders::TotalSize;\n uint8_t SessionIdOffset = SessionIdLengthOffset + sizeof(uint16_t);\n uint8_t PathLengthOffset = SessionIdOffset + message.session_id.size();\n uint8_t PathOffset = PathLengthOffset + sizeof(uint16_t);\n uint8_t AuthOffset = PathOffset + Message::AuthLength;\n\n std::memcpy(&expected_values[SessionIdLengthOffset], &message.session_id_length, sizeof(message.session_id_length));\n std::memcpy(&expected_values[SessionIdOffset], message.session_id.data(), message.session_id.size());\n std::memcpy(&expected_values[PathLengthOffset], &message.path_length, sizeof(message.path_length));\n std::memcpy(&expected_values[PathOffset], message.path.data(), message.path.size());\n std::memcpy(&expected_values[AuthOffset], message.other_auth.data(), Message::AuthLength);\n\n\/\/ EXPECT_EQ(0, memcmp(expected_values, buf, message_size));\n\n}\n<commit_msg>update handshake unittests<commit_after>#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nclass HandshakeF3MessageExt : public HandshakeF3Message {\n public:\n HandshakeF3MessageExt() : HandshakeF3Message() {}\n\n void update_static_header_ext() {\n HandshakeF3Message::update_static_header();\n }\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nTEST(MessageTest, HandshakeF3__Constructor_01) {\n HandshakeF3MessageExt message;\n\n \/*\n uint16_t session_id_length;\n std::string session_id;\n uint16_t path_length;\n std::string path;\n std::vector<uint8_t> other_auth;\n *\/\n\n message.session_id_length = 64;\n std::string session_id(\"session-id123456789012345678901234567890123456789012345678901234\");\n message.session_id = session_id;\n\n message.path_length = 32;\n std::string path(\"path5678901234567890123456789012\");\n message.path = path;\n\n uint8_t auth[] = \"auth5678901234567890123456789012\";\n message.other_auth = std::vector<uint8_t>(auth, auth + Message::AuthLength);\n\n message.update_static_header_ext();\n\n uint8_t buf[1024];\n message.write(buf);\n\n \/\/ 15 + 2 + 64 + 2 + 32 + 32 = 147\n uint8_t expected_values[147];\n\n uint32_t message_size = 147;\n uint16_t header_size = message_size;\n MessageType type = MessageType::Handshake3;\n uint32_t request_id = 0;\n uint32_t ack_id = 0;\n\n std::memcpy(&expected_values[StaticHeaders::MessageSizeOffset], &message_size,\n sizeof(uint32_t));\n std::memcpy(&expected_values[StaticHeaders::HeaderSizeOffset], &header_size,\n sizeof(uint16_t));\n std::memcpy(&expected_values[StaticHeaders::TypeOffset], &type,\n sizeof(uint8_t));\n std::memcpy(&expected_values[StaticHeaders::RequestIdOffset], &request_id,\n sizeof(request_id));\n std::memcpy(&expected_values[StaticHeaders::AckIdOffset], &ack_id,\n sizeof(ack_id));\n\n uint8_t SessionIdLengthOffset = StaticHeaders::TotalSize;\n uint8_t SessionIdOffset = SessionIdLengthOffset + sizeof(uint16_t);\n uint8_t PathLengthOffset = SessionIdOffset + message.session_id.size();\n uint8_t PathOffset = PathLengthOffset + sizeof(uint16_t);\n uint8_t AuthOffset = PathOffset + message.path_length;\n\n std::memcpy(&expected_values[SessionIdLengthOffset], &message.session_id_length, sizeof(message.session_id_length));\n std::memcpy(&expected_values[SessionIdOffset], message.session_id.data(), message.session_id.size());\n std::memcpy(&expected_values[PathLengthOffset], &message.path_length, sizeof(message.path_length));\n std::memcpy(&expected_values[PathOffset], message.path.data(), message.path.size());\n std::memcpy(&expected_values[AuthOffset], message.other_auth.data(), Message::AuthLength);\n\n\/\/ EXPECT_EQ(0, memcmp(expected_values, buf, message_size));\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ This code comes from:\n\/\/ https:\/\/github.com\/google\/protobuf\/blob\/master\/src\/google\/protobuf\/stubs\/map_util.h\n\/\/ and was adapted to Visual Studio 2013 and to the needs of this project.\n\n\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ from google3\/util\/gtl\/map_util.h\n\/\/ Author: Anton Carver\n\n#include \"glog\/logging.h\"\n\nnamespace principia {\nnamespace base {\n\ntemplate <class Collection>\nconst typename Collection::value_type::second_type&\nFindOrDie(const Collection& collection,\n const typename Collection::value_type::first_type& key) {\n typename Collection::const_iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n\/\/ Same as above, but returns a non-const reference.\ntemplate <class Collection>\ntypename Collection::value_type::second_type&\nFindOrDie(Collection& collection, \/\/ NOLINT\n const typename Collection::value_type::first_type& key) {\n typename Collection::iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<commit_msg>After egg's review.<commit_after>#pragma once\n\n\/\/ This code comes from:\n\/\/ https:\/\/github.com\/google\/protobuf\/blob\/master\/src\/google\/protobuf\/stubs\/map_util.h\n\/\/ and was adapted to Visual Studio 2013 and to the needs of this project.\n\n\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ from google3\/util\/gtl\/map_util.h\n\/\/ Author: Anton Carver\n\n#include \"glog\/logging.h\"\n\nnamespace principia {\nnamespace base {\n\ntemplate <class Collection>\nconst typename Collection::value_type::second_type&\nFindOrDie(const Collection& collection,\n const typename Collection::value_type::first_type& key) {\n typename Collection::const_iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n\/\/ Same as above, but returns a non-const reference.\ntemplate <class Collection>\ntypename Collection::value_type::second_type&\nFindOrDie(Collection& collection, \/\/ NOLINT(runtime\/references)\n const typename Collection::value_type::first_type& key) {\n typename Collection::iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include \"font2D.hpp\"\n#include \"entity_templates.hpp\"\n#include \"code\/ylikuutio\/loaders\/shader_loader.hpp\"\n#include \"code\/ylikuutio\/loaders\/texture_loader.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#include <glm\/gtc\/matrix_transform.hpp>\n#endif\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n#include <cstring> \/\/ std::memcmp, std::strcmp, std::strlen, std::strncmp\n#include <stdint.h> \/\/ uint32_t etc.\n#include <string> \/\/ std::string\n\nnamespace ontology\n{\n class Universe;\n\n Font2D::Font2D(\n ontology::Universe* universe_pointer,\n GLuint screen_width,\n GLuint screen_height,\n std::string texture_filename,\n std::string font_texture_file_format)\n {\n \/\/ constructor.\n const char* char_font_texture_file_format = font_texture_file_format.c_str();\n\n \/\/ Initialize texture\n if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n this->texture = loaders::load_BMP_texture(texture_filename);\n }\n else if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n this->texture = loaders::load_DDS_texture(texture_filename);\n }\n else\n {\n printf(\"Invalid font texture file format: `%s`. Supported font texture file formats: bmp, BMP, dds, DDS.\\n\", char_font_texture_file_format);\n this->texture = 0;\n return;\n }\n\n \/\/ Initialize VBO\n glGenBuffers(1, &vertexbuffer);\n glGenBuffers(1, &uvbuffer);\n\n \/\/ Initialize Shader\n programID = loaders::load_shaders(\"TextVertexShader.vertexshader\", \"TextVertexShader.fragmentshader\");\n\n \/\/ Get a handle for our buffers\n vertex_position_in_screenspaceID = glGetAttribLocation(programID, \"vertexPosition_screenspace\");\n vertexUVID = glGetAttribLocation(programID, \"vertexUV\");\n\n \/\/ Initialize uniforms' IDs\n Text2DUniformID = glGetUniformLocation(programID, \"myTextureSampler\");\n\n \/\/ Initialize uniform window width.\n screen_width_uniform_ID = glGetUniformLocation(programID, \"screen_width\");\n glUniform1i(screen_width_uniform_ID, screen_width);\n\n \/\/ Initialize uniform window height.\n screen_height_uniform_ID = glGetUniformLocation(programID, \"screen_height\");\n glUniform1i(screen_height_uniform_ID, screen_height);\n\n this->universe_pointer = universe_pointer;\n }\n\n Font2D::~Font2D()\n {\n \/\/ destructor.\n\n \/\/ Delete buffers\n glDeleteBuffers(1, &vertexbuffer);\n glDeleteBuffers(1, &uvbuffer);\n\n \/\/ Delete texture\n glDeleteTextures(1, &texture);\n\n \/\/ Delete shader\n glDeleteProgram(programID);\n }\n\n int32_t Font2D::get_number_of_children()\n {\n return -1;\n }\n\n int32_t Font2D::get_number_of_descendants()\n {\n return -1;\n }\n\n void Font2D::printText2D(\n GLuint screen_width,\n GLuint screen_height,\n GLuint x,\n GLuint y,\n GLuint text_size,\n GLuint font_size,\n const char* text_char,\n const char* char_font_texture_file_format,\n const char* horizontal_alignment,\n const char* vertical_alignment)\n {\n \/\/ If horizontal alignment is `\"left\"`, each line begins from the same x coordinate.\n \/\/ If horizontal alignment is `\"left\"` and vertical alignment is `\"top\"`,\n \/\/ then there is no need to check the text beforehand for newlines.\n \/\/ Otherwise newlines need to be checked beforehand.\n \/\/\n \/\/ If horizontal alignment is right, each line ends in the same x coordinate.\n \/\/ Newlines need to be checked beforehand.\n uint32_t length = std::strlen(text_char);\n\n \/\/ Count the number of lines.\n uint32_t number_of_lines = 1;\n\n uint32_t i = 0;\n\n while (i < length)\n {\n char character = text_char[i++];\n\n if (character == (char) '\\\\')\n {\n \/\/ OK, this character was backslash, so read the next character.\n character = text_char[i++];\n\n if (character == 'n')\n {\n number_of_lines++;\n }\n }\n }\n\n GLuint current_left_x;\n GLuint current_top_y;\n\n if (std::strcmp(horizontal_alignment, \"left\") == 0)\n {\n current_left_x = x;\n }\n else if (std::strcmp(horizontal_alignment, \"center\") == 0)\n {\n current_left_x = x - 0.5f * length * text_size;\n }\n else if (std::strcmp(horizontal_alignment, \"right\") == 0)\n {\n current_left_x = x - length * text_size;\n }\n\n if (std::strcmp(vertical_alignment, \"top\") == 0)\n {\n current_top_y = y;\n }\n else if (std::strcmp(vertical_alignment, \"center\") == 0)\n {\n current_top_y = y + 0.5f * number_of_lines * text_size;\n }\n else if (std::strcmp(vertical_alignment, \"bottom\") == 0)\n {\n current_top_y = y + number_of_lines * text_size;\n }\n\n \/\/ Fill buffers\n std::vector<glm::vec2> vertices;\n std::vector<glm::vec2> UVs;\n\n i = 0;\n\n while (i < length)\n {\n \/\/ Print to the right side of X (so far there is no check for input length).\n \/\/ Print up of Y.\n GLfloat vertex_up_left_x;\n GLfloat vertex_up_left_y;\n GLfloat vertex_up_right_x;\n GLfloat vertex_up_right_y;\n GLfloat vertex_down_left_x;\n GLfloat vertex_down_left_y;\n GLfloat vertex_down_right_x;\n GLfloat vertex_down_right_y;\n\n char character = text_char[i++];\n\n if (character == (char) '\\\\')\n {\n \/\/ OK, this character was backslash, so read the next character.\n character = text_char[i++];\n\n if (character == 'n')\n {\n \/\/ jump to the beginning of the next line.\n \/\/ `\"left\"` horizontal alignment and `\"top\"` vertical alignment are assumed.\n \/\/ TODO: implement newline for other horizontal and vertical alignments too!\n current_left_x = x;\n current_top_y -= text_size;\n continue;\n }\n }\n\n vertex_up_left_x = vertex_down_left_x = current_left_x;\n vertex_up_right_x = vertex_down_right_x = current_left_x + text_size;\n current_left_x += text_size;\n\n vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;\n vertex_up_left_y = vertex_up_right_y = current_top_y;\n\n glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y);\n glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y);\n glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y);\n glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y);\n\n vertices.push_back(vertex_up_left);\n vertices.push_back(vertex_down_left);\n vertices.push_back(vertex_up_right);\n\n vertices.push_back(vertex_down_right);\n vertices.push_back(vertex_up_right);\n vertices.push_back(vertex_down_left);\n\n float uv_x = (character % font_size) \/ (GLfloat) font_size;\n float uv_y;\n\n if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n uv_y = (character \/ font_size) \/ (GLfloat) font_size;\n }\n else if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n \/\/ BMP is stored in the file beginning from the bottom line.\n uv_y = 1 - (character \/ font_size) \/ (GLfloat) font_size;\n }\n\n glm::vec2 uv_up_left = glm::vec2(uv_x, uv_y);\n glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), uv_y);\n glm::vec2 uv_down_right;\n glm::vec2 uv_down_left;\n\n if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n uv_down_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), (uv_y + 1.0f \/ (GLfloat) font_size));\n uv_down_left = glm::vec2(uv_x, (uv_y + 1.0f \/ (GLfloat) font_size));\n }\n else if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n \/\/ BMP is stored in the file beginning from the bottom line.\n uv_down_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), (uv_y - 1.0f \/ (GLfloat) font_size));\n uv_down_left = glm::vec2(uv_x, (uv_y - 1.0f \/ (GLfloat) font_size));\n }\n UVs.push_back(uv_up_left);\n UVs.push_back(uv_down_left);\n UVs.push_back(uv_up_right);\n\n UVs.push_back(uv_down_right);\n UVs.push_back(uv_up_right);\n UVs.push_back(uv_down_left);\n }\n\n glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW);\n\n \/\/ Bind shader\n glUseProgram(programID);\n\n \/\/ Bind texture\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, texture);\n \/\/ Set our \"myTextureSampler\" sampler to user Material Unit 0\n glUniform1i(Text2DUniformID, 0);\n\n \/\/ Set screen width.\n glUniform1i(screen_width_uniform_ID, screen_width);\n\n \/\/ Set screen height.\n glUniform1i(screen_height_uniform_ID, screen_height);\n\n \/\/ 1st attribute buffer : vertices\n glEnableVertexAttribArray(vertex_position_in_screenspaceID);\n glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n glVertexAttribPointer(vertex_position_in_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);\n\n \/\/ 2nd attribute buffer : UVs\n glEnableVertexAttribArray(vertexUVID);\n glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n \/\/ Draw call\n glDrawArrays(GL_TRIANGLES, 0, vertices.size());\n\n glDisable(GL_BLEND);\n\n glDisableVertexAttribArray(vertex_position_in_screenspaceID);\n glDisableVertexAttribArray(vertexUVID);\n }\n\n void Font2D::printText2D(PrintingStruct printing_struct)\n {\n if (printing_struct.text.empty())\n {\n printText2D(\n printing_struct.screen_width,\n printing_struct.screen_height,\n printing_struct.x,\n printing_struct.y,\n printing_struct.text_size,\n printing_struct.font_size,\n printing_struct.text_char,\n printing_struct.char_font_texture_file_format,\n printing_struct.horizontal_alignment,\n printing_struct.vertical_alignment);\n }\n else\n {\n printText2D(\n printing_struct.screen_width,\n printing_struct.screen_height,\n printing_struct.x,\n printing_struct.y,\n printing_struct.text_size,\n printing_struct.font_size,\n printing_struct.text.c_str(),\n printing_struct.char_font_texture_file_format,\n printing_struct.horizontal_alignment,\n printing_struct.vertical_alignment);\n }\n }\n\n void Font2D::printText2D(\n GLuint screen_width,\n GLuint screen_height,\n GLuint x,\n GLuint y,\n GLuint text_size,\n GLuint font_size,\n const char* text_char,\n const char* char_font_texture_file_format)\n {\n printText2D(screen_width, screen_height, x, y, text_size, font_size, text_char, char_font_texture_file_format, \"left\", \"bottom\");\n }\n\n void Font2D::set_name(std::string name)\n {\n ontology::set_name(name, this);\n }\n}\n<commit_msg>Bugfix `Font2D::Font2D`: initialize class members (with dummy values).<commit_after>#include \"font2D.hpp\"\n#include \"entity_templates.hpp\"\n#include \"code\/ylikuutio\/loaders\/shader_loader.hpp\"\n#include \"code\/ylikuutio\/loaders\/texture_loader.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#include <glm\/gtc\/matrix_transform.hpp>\n#endif\n\n\/\/ Include standard headers\n#include <vector> \/\/ std::vector\n#include <cstring> \/\/ std::memcmp, std::strcmp, std::strlen, std::strncmp\n#include <stdint.h> \/\/ uint32_t etc.\n#include <string> \/\/ std::string\n\nnamespace ontology\n{\n class Universe;\n\n Font2D::Font2D(\n ontology::Universe* universe_pointer,\n GLuint screen_width,\n GLuint screen_height,\n std::string texture_filename,\n std::string font_texture_file_format)\n {\n \/\/ constructor.\n\n \/\/ Initialize class members with some dummy values.\n this->vertexbuffer = 0;\n this->uvbuffer = 0;\n this->programID = 0;\n this->vertex_position_in_screenspaceID = 0;\n this->vertexUVID = 0;\n this->Text2DUniformID = 0;\n this->screen_width_uniform_ID = 0;\n this->screen_height_uniform_ID = 0;\n\n const char* char_font_texture_file_format = font_texture_file_format.c_str();\n\n \/\/ Initialize texture\n if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n this->texture = loaders::load_BMP_texture(texture_filename);\n }\n else if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n this->texture = loaders::load_DDS_texture(texture_filename);\n }\n else\n {\n printf(\"Invalid font texture file format: `%s`. Supported font texture file formats: bmp, BMP, dds, DDS.\\n\", char_font_texture_file_format);\n this->texture = 0;\n return;\n }\n\n \/\/ Initialize VBO\n glGenBuffers(1, &vertexbuffer);\n glGenBuffers(1, &uvbuffer);\n\n \/\/ Initialize Shader\n programID = loaders::load_shaders(\"TextVertexShader.vertexshader\", \"TextVertexShader.fragmentshader\");\n\n \/\/ Get a handle for our buffers\n vertex_position_in_screenspaceID = glGetAttribLocation(programID, \"vertexPosition_screenspace\");\n vertexUVID = glGetAttribLocation(programID, \"vertexUV\");\n\n \/\/ Initialize uniforms' IDs\n Text2DUniformID = glGetUniformLocation(programID, \"myTextureSampler\");\n\n \/\/ Initialize uniform window width.\n screen_width_uniform_ID = glGetUniformLocation(programID, \"screen_width\");\n glUniform1i(screen_width_uniform_ID, screen_width);\n\n \/\/ Initialize uniform window height.\n screen_height_uniform_ID = glGetUniformLocation(programID, \"screen_height\");\n glUniform1i(screen_height_uniform_ID, screen_height);\n\n this->universe_pointer = universe_pointer;\n }\n\n Font2D::~Font2D()\n {\n \/\/ destructor.\n\n \/\/ Delete buffers\n glDeleteBuffers(1, &vertexbuffer);\n glDeleteBuffers(1, &uvbuffer);\n\n \/\/ Delete texture\n glDeleteTextures(1, &texture);\n\n \/\/ Delete shader\n glDeleteProgram(programID);\n }\n\n int32_t Font2D::get_number_of_children()\n {\n return -1;\n }\n\n int32_t Font2D::get_number_of_descendants()\n {\n return -1;\n }\n\n void Font2D::printText2D(\n GLuint screen_width,\n GLuint screen_height,\n GLuint x,\n GLuint y,\n GLuint text_size,\n GLuint font_size,\n const char* text_char,\n const char* char_font_texture_file_format,\n const char* horizontal_alignment,\n const char* vertical_alignment)\n {\n \/\/ If horizontal alignment is `\"left\"`, each line begins from the same x coordinate.\n \/\/ If horizontal alignment is `\"left\"` and vertical alignment is `\"top\"`,\n \/\/ then there is no need to check the text beforehand for newlines.\n \/\/ Otherwise newlines need to be checked beforehand.\n \/\/\n \/\/ If horizontal alignment is right, each line ends in the same x coordinate.\n \/\/ Newlines need to be checked beforehand.\n uint32_t length = std::strlen(text_char);\n\n \/\/ Count the number of lines.\n uint32_t number_of_lines = 1;\n\n uint32_t i = 0;\n\n while (i < length)\n {\n char character = text_char[i++];\n\n if (character == (char) '\\\\')\n {\n \/\/ OK, this character was backslash, so read the next character.\n character = text_char[i++];\n\n if (character == 'n')\n {\n number_of_lines++;\n }\n }\n }\n\n GLuint current_left_x;\n GLuint current_top_y;\n\n if (std::strcmp(horizontal_alignment, \"left\") == 0)\n {\n current_left_x = x;\n }\n else if (std::strcmp(horizontal_alignment, \"center\") == 0)\n {\n current_left_x = x - 0.5f * length * text_size;\n }\n else if (std::strcmp(horizontal_alignment, \"right\") == 0)\n {\n current_left_x = x - length * text_size;\n }\n\n if (std::strcmp(vertical_alignment, \"top\") == 0)\n {\n current_top_y = y;\n }\n else if (std::strcmp(vertical_alignment, \"center\") == 0)\n {\n current_top_y = y + 0.5f * number_of_lines * text_size;\n }\n else if (std::strcmp(vertical_alignment, \"bottom\") == 0)\n {\n current_top_y = y + number_of_lines * text_size;\n }\n\n \/\/ Fill buffers\n std::vector<glm::vec2> vertices;\n std::vector<glm::vec2> UVs;\n\n i = 0;\n\n while (i < length)\n {\n \/\/ Print to the right side of X (so far there is no check for input length).\n \/\/ Print up of Y.\n GLfloat vertex_up_left_x;\n GLfloat vertex_up_left_y;\n GLfloat vertex_up_right_x;\n GLfloat vertex_up_right_y;\n GLfloat vertex_down_left_x;\n GLfloat vertex_down_left_y;\n GLfloat vertex_down_right_x;\n GLfloat vertex_down_right_y;\n\n char character = text_char[i++];\n\n if (character == (char) '\\\\')\n {\n \/\/ OK, this character was backslash, so read the next character.\n character = text_char[i++];\n\n if (character == 'n')\n {\n \/\/ jump to the beginning of the next line.\n \/\/ `\"left\"` horizontal alignment and `\"top\"` vertical alignment are assumed.\n \/\/ TODO: implement newline for other horizontal and vertical alignments too!\n current_left_x = x;\n current_top_y -= text_size;\n continue;\n }\n }\n\n vertex_up_left_x = vertex_down_left_x = current_left_x;\n vertex_up_right_x = vertex_down_right_x = current_left_x + text_size;\n current_left_x += text_size;\n\n vertex_down_left_y = vertex_down_right_y = current_top_y - text_size;\n vertex_up_left_y = vertex_up_right_y = current_top_y;\n\n glm::vec2 vertex_up_left = glm::vec2(vertex_up_left_x, vertex_up_left_y);\n glm::vec2 vertex_up_right = glm::vec2(vertex_up_right_x, vertex_up_right_y);\n glm::vec2 vertex_down_left = glm::vec2(vertex_down_left_x, vertex_down_left_y);\n glm::vec2 vertex_down_right = glm::vec2(vertex_down_right_x, vertex_down_right_y);\n\n vertices.push_back(vertex_up_left);\n vertices.push_back(vertex_down_left);\n vertices.push_back(vertex_up_right);\n\n vertices.push_back(vertex_down_right);\n vertices.push_back(vertex_up_right);\n vertices.push_back(vertex_down_left);\n\n float uv_x = (character % font_size) \/ (GLfloat) font_size;\n float uv_y;\n\n if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n uv_y = (character \/ font_size) \/ (GLfloat) font_size;\n }\n else if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n \/\/ BMP is stored in the file beginning from the bottom line.\n uv_y = 1 - (character \/ font_size) \/ (GLfloat) font_size;\n }\n\n glm::vec2 uv_up_left = glm::vec2(uv_x, uv_y);\n glm::vec2 uv_up_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), uv_y);\n glm::vec2 uv_down_right;\n glm::vec2 uv_down_left;\n\n if ((std::strcmp(char_font_texture_file_format, \"dds\") == 0) || (std::strcmp(char_font_texture_file_format, \"DDS\") == 0))\n {\n uv_down_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), (uv_y + 1.0f \/ (GLfloat) font_size));\n uv_down_left = glm::vec2(uv_x, (uv_y + 1.0f \/ (GLfloat) font_size));\n }\n else if ((std::strcmp(char_font_texture_file_format, \"bmp\") == 0) || (std::strcmp(char_font_texture_file_format, \"BMP\") == 0))\n {\n \/\/ BMP is stored in the file beginning from the bottom line.\n uv_down_right = glm::vec2(uv_x + (1.0f \/ (GLfloat) font_size), (uv_y - 1.0f \/ (GLfloat) font_size));\n uv_down_left = glm::vec2(uv_x, (uv_y - 1.0f \/ (GLfloat) font_size));\n }\n UVs.push_back(uv_up_left);\n UVs.push_back(uv_down_left);\n UVs.push_back(uv_up_right);\n\n UVs.push_back(uv_down_right);\n UVs.push_back(uv_up_right);\n UVs.push_back(uv_down_left);\n }\n\n glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec2), &vertices[0], GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW);\n\n \/\/ Bind shader\n glUseProgram(programID);\n\n \/\/ Bind texture\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, texture);\n \/\/ Set our \"myTextureSampler\" sampler to user Material Unit 0\n glUniform1i(Text2DUniformID, 0);\n\n \/\/ Set screen width.\n glUniform1i(screen_width_uniform_ID, screen_width);\n\n \/\/ Set screen height.\n glUniform1i(screen_height_uniform_ID, screen_height);\n\n \/\/ 1st attribute buffer : vertices\n glEnableVertexAttribArray(vertex_position_in_screenspaceID);\n glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n glVertexAttribPointer(vertex_position_in_screenspaceID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);\n\n \/\/ 2nd attribute buffer : UVs\n glEnableVertexAttribArray(vertexUVID);\n glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n \/\/ Draw call\n glDrawArrays(GL_TRIANGLES, 0, vertices.size());\n\n glDisable(GL_BLEND);\n\n glDisableVertexAttribArray(vertex_position_in_screenspaceID);\n glDisableVertexAttribArray(vertexUVID);\n }\n\n void Font2D::printText2D(PrintingStruct printing_struct)\n {\n if (printing_struct.text.empty())\n {\n printText2D(\n printing_struct.screen_width,\n printing_struct.screen_height,\n printing_struct.x,\n printing_struct.y,\n printing_struct.text_size,\n printing_struct.font_size,\n printing_struct.text_char,\n printing_struct.char_font_texture_file_format,\n printing_struct.horizontal_alignment,\n printing_struct.vertical_alignment);\n }\n else\n {\n printText2D(\n printing_struct.screen_width,\n printing_struct.screen_height,\n printing_struct.x,\n printing_struct.y,\n printing_struct.text_size,\n printing_struct.font_size,\n printing_struct.text.c_str(),\n printing_struct.char_font_texture_file_format,\n printing_struct.horizontal_alignment,\n printing_struct.vertical_alignment);\n }\n }\n\n void Font2D::printText2D(\n GLuint screen_width,\n GLuint screen_height,\n GLuint x,\n GLuint y,\n GLuint text_size,\n GLuint font_size,\n const char* text_char,\n const char* char_font_texture_file_format)\n {\n printText2D(screen_width, screen_height, x, y, text_size, font_size, text_char, char_font_texture_file_format, \"left\", \"bottom\");\n }\n\n void Font2D::set_name(std::string name)\n {\n ontology::set_name(name, this);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Sampling.cpp\n *\n * Created on: 17.02.2014\n * Author: cls\n *\/\n\n#include \"Sampling.h\"\n#include \"..\/auxiliary\/Random.h\"\n\nnamespace NetworKit {\n\nnode Sampling::randomNode(const Graph& G) {\n\tassert (G.numberOfNodes() > 0);\n\tnode v = none;\n\tdo {\n\t\tv = Aux::Random::integer(G.upperNodeIdBound());\n\t} while (!G.hasNode(v));\n\treturn v;\n}\n\nstd::pair<node, node> Sampling::randomEdge(const Graph& G) {\n\t\/\/ TODO:\n}\n\nnode Sampling::randomNeighbor(const Graph& G, node u) {\n\t\/\/ TODO:\n}\n\n\n\n} \/* namespace NetworKit *\/\n\n<commit_msg>comment implementation of non-implemented methods to create linker error upon use and silence warnings<commit_after>\/*\n * Sampling.cpp\n *\n * Created on: 17.02.2014\n * Author: cls\n *\/\n\n#include \"Sampling.h\"\n#include \"..\/auxiliary\/Random.h\"\n\nnamespace NetworKit {\n\nnode Sampling::randomNode(const Graph& G) {\n\tassert (G.numberOfNodes() > 0);\n\tnode v = none;\n\tdo {\n\t\tv = Aux::Random::integer(G.upperNodeIdBound());\n\t} while (!G.hasNode(v));\n\treturn v;\n}\n\n\/\/ the following methdods are commented in order to create linker-errors should they be used before\n\/\/ they are actually defined (not returning from a function with a returntype != void is UB):\n\n\/\/std::pair<node, node> Sampling::randomEdge(const Graph& G) {\n\/\/\t\/\/ TODO: implement\n\/\/}\n\n\/\/node Sampling::randomNeighbor(const Graph& G, node u) {\n\/\/\t\/\/ TODO: implement\n\/\/}\n\n\n\n} \/* namespace NetworKit *\/\n\n<|endoftext|>"} {"text":"<commit_before>#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/timeutil.h\"\n\n\/\/ For NV time functions. Ugly!\n#include \"gfx_es2\/gl_state.h\"\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <sys\/time.h>\n#include <unistd.h>\n#endif\n#include <stdio.h>\n\nstatic double curtime = 0;\nstatic float curtime_f = 0;\n\n#ifdef _WIN32\n\nLARGE_INTEGER frequency;\ndouble frequencyMult;\nLARGE_INTEGER startTime;\n\ndouble real_time_now() {\n\tif (frequency.QuadPart == 0) {\n\t\tQueryPerformanceFrequency(&frequency);\n\t\tQueryPerformanceCounter(&startTime);\n\t\tcurtime = 0.0;\n\t\tfrequencyMult = 1.0 \/ static_cast<double>(frequency.QuadPart);\n\t}\n\tLARGE_INTEGER time;\n\tQueryPerformanceCounter(&time);\n\tdouble elapsed = static_cast<double>(time.QuadPart - startTime.QuadPart);\n\treturn elapsed * frequencyMult;\n}\n\n#elif defined(BLACKBERRY)\ndouble real_time_now() {\n\tstruct timespec time;\n\tclock_gettime(CLOCK_MONOTONIC, &time); \/\/ Linux must use CLOCK_MONOTONIC_RAW due to time warps\n\treturn time.tv_sec + time.tv_nsec \/ 1.0e9;\n}\n#else\n\nuint64_t _frequency = 0;\nuint64_t _starttime = 0;\n\ndouble real_time_now() {\n#ifdef ANDROID\n\tif (false && gl_extensions.EGL_NV_system_time) {\n\t\t\/\/ This is needed to profile using PerfHUD on Tegra\n\t\tif (_frequency == 0) {\n\t\t\t_frequency = eglGetSystemTimeFrequencyNV();\n\t\t\t_starttime = eglGetSystemTimeNV();\n\t\t}\n\n\t\tuint64_t cur = eglGetSystemTimeNV();\n\t\tint64_t diff = cur - _starttime;\n\n\t\treturn (double)diff \/ (double)_frequency;\n\t}\n\tstruct timespec time;\n\tclock_gettime(CLOCK_MONOTONIC_RAW, &time);\n\treturn time.tv_sec + time.tv_nsec \/ 1.0e9;\n#else\n\tstatic time_t start;\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\tif (start == 0) {\n\t\tstart = tv.tv_sec;\n\t}\n\ttv.tv_sec -= start;\n\treturn (double)tv.tv_sec + (double)tv.tv_usec \/ 1000000.0;\n#endif\n}\n\n#endif\n\nvoid time_update() {\n\tcurtime = real_time_now();\n\tcurtime_f = (float)curtime;\n\n\t\/\/printf(\"curtime: %f %f\\n\", curtime, curtime_f);\n\t\/\/ also smooth time.\n\t\/\/curtime+=float((double) (time-_starttime) \/ (double) _frequency);\n\t\/\/curtime*=0.5f;\n\t\/\/curtime+=1.0f\/60.0f;\n\t\/\/lastTime=curtime;\n\t\/\/curtime_f = (float)curtime;\n}\n\nfloat time_now() {\n\treturn curtime_f;\n}\n\ndouble time_now_d() {\n\treturn curtime;\n}\n\nint time_now_ms() {\n\treturn int(curtime*1000.0);\n}\n\nvoid sleep_ms(int ms) {\n#ifdef _WIN32\n#ifndef METRO\n\tSleep(ms);\n#endif\n#else\n\tusleep(ms * 1000);\n#endif\n}\n\nLoggingDeadline::LoggingDeadline(const char *name, int ms) : name_(name), endCalled_(false) {\n\ttotalTime_ = (double)ms * 0.001;\n\ttime_update();\n\tendTime_ = time_now_d() + totalTime_;\n}\n\nLoggingDeadline::~LoggingDeadline() {\n\tif (!endCalled_)\n\t\tEnd();\n}\n\nbool LoggingDeadline::End() {\n\tendCalled_ = true;\n\ttime_update();\n\tif (time_now_d() > endTime_) {\n\t\tdouble late = (time_now_d() - endTime_);\n\t\tdouble totalTime = late + totalTime_;\n\t\tELOG(\"===== %0.2fms DEADLINE PASSED FOR %s at %0.2fms - %0.2fms late =====\", totalTime_ * 1000.0, name_, 1000.0 * totalTime, 1000.0 * late);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n<commit_msg>Don't use CLOCK_MONOTONIC_RAW on android, it is super choppy on Nexus 9.<commit_after>#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/timeutil.h\"\n\n\/\/ For NV time functions. Ugly!\n#include \"gfx_es2\/gl_state.h\"\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <sys\/time.h>\n#include <unistd.h>\n#endif\n#include <stdio.h>\n\nstatic double curtime = 0;\nstatic float curtime_f = 0;\n\n#ifdef _WIN32\n\nLARGE_INTEGER frequency;\ndouble frequencyMult;\nLARGE_INTEGER startTime;\n\ndouble real_time_now() {\n\tif (frequency.QuadPart == 0) {\n\t\tQueryPerformanceFrequency(&frequency);\n\t\tQueryPerformanceCounter(&startTime);\n\t\tcurtime = 0.0;\n\t\tfrequencyMult = 1.0 \/ static_cast<double>(frequency.QuadPart);\n\t}\n\tLARGE_INTEGER time;\n\tQueryPerformanceCounter(&time);\n\tdouble elapsed = static_cast<double>(time.QuadPart - startTime.QuadPart);\n\treturn elapsed * frequencyMult;\n}\n\n#elif defined(BLACKBERRY)\ndouble real_time_now() {\n\tstruct timespec time;\n\tclock_gettime(CLOCK_MONOTONIC, &time); \/\/ Linux must use CLOCK_MONOTONIC_RAW due to time warps\n\treturn time.tv_sec + time.tv_nsec \/ 1.0e9;\n}\n#else\n\nuint64_t _frequency = 0;\nuint64_t _starttime = 0;\n\ndouble real_time_now() {\n#ifdef ANDROID\n\tif (false && gl_extensions.EGL_NV_system_time) {\n\t\t\/\/ This is needed to profile using PerfHUD on Tegra\n\t\tif (_frequency == 0) {\n\t\t\t_frequency = eglGetSystemTimeFrequencyNV();\n\t\t\t_starttime = eglGetSystemTimeNV();\n\t\t}\n\n\t\tuint64_t cur = eglGetSystemTimeNV();\n\t\tint64_t diff = cur - _starttime;\n\n\t\treturn (double)diff \/ (double)_frequency;\n\t}\n#if 0\n\t\/\/ This clock is really \"choppy\" on Nexus 9!\n\tstruct timespec time;\n\tclock_gettime(CLOCK_MONOTONIC_RAW, &time);\n\treturn time.tv_sec + time.tv_nsec \/ 1.0e9;\n#else\n\tstatic time_t start;\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\tif (start == 0) {\n\t\tstart = tv.tv_sec;\n\t}\n\ttv.tv_sec -= start;\n\treturn (double)tv.tv_sec + (double)tv.tv_usec \/ 1000000.0;\n#endif\n\n#else\n\tstatic time_t start;\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\tif (start == 0) {\n\t\tstart = tv.tv_sec;\n\t}\n\ttv.tv_sec -= start;\n\treturn (double)tv.tv_sec + (double)tv.tv_usec \/ 1000000.0;\n#endif\n}\n\n#endif\n\nvoid time_update() {\n\tcurtime = real_time_now();\n\tcurtime_f = (float)curtime;\n\n\t\/\/printf(\"curtime: %f %f\\n\", curtime, curtime_f);\n\t\/\/ also smooth time.\n\t\/\/curtime+=float((double) (time-_starttime) \/ (double) _frequency);\n\t\/\/curtime*=0.5f;\n\t\/\/curtime+=1.0f\/60.0f;\n\t\/\/lastTime=curtime;\n\t\/\/curtime_f = (float)curtime;\n}\n\nfloat time_now() {\n\treturn curtime_f;\n}\n\ndouble time_now_d() {\n\treturn curtime;\n}\n\nint time_now_ms() {\n\treturn int(curtime*1000.0);\n}\n\nvoid sleep_ms(int ms) {\n#ifdef _WIN32\n#ifndef METRO\n\tSleep(ms);\n#endif\n#else\n\tusleep(ms * 1000);\n#endif\n}\n\nLoggingDeadline::LoggingDeadline(const char *name, int ms) : name_(name), endCalled_(false) {\n\ttotalTime_ = (double)ms * 0.001;\n\ttime_update();\n\tendTime_ = time_now_d() + totalTime_;\n}\n\nLoggingDeadline::~LoggingDeadline() {\n\tif (!endCalled_)\n\t\tEnd();\n}\n\nbool LoggingDeadline::End() {\n\tendCalled_ = true;\n\ttime_update();\n\tif (time_now_d() > endTime_) {\n\t\tdouble late = (time_now_d() - endTime_);\n\t\tdouble totalTime = late + totalTime_;\n\t\tELOG(\"===== %0.2fms DEADLINE PASSED FOR %s at %0.2fms - %0.2fms late =====\", totalTime_ * 1000.0, name_, 1000.0 * totalTime, 1000.0 * late);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Bugfix: add missing `#include` line.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>`void Object::bind_to_parent`: refactoring the code.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <primitives\/executor.h>\n\n#include <iostream>\n#include <string>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\n\/\/#include \"log.h\"\n\/\/DECLARE_STATIC_LOGGER(logger, \"executor\");\n\nsize_t get_max_threads(size_t N)\n{\n return std::max<size_t>(N, std::thread::hardware_concurrency());\n}\n\nExecutor::Executor(const std::string &name, size_t nThreads)\n : Executor(nThreads, name)\n{\n}\n\nExecutor::Executor(size_t nThreads, const std::string &name)\n : nThreads(nThreads)\n{\n thread_pool.resize(nThreads);\n for (size_t i = 0; i < nThreads; i++)\n {\n thread_pool[i].t = std::move(std::thread([this, i, name = name]() mutable\n {\n name += \" \" + std::to_string(i);\n set_thread_name(name, i);\n run(i);\n }));\n }\n}\n\nExecutor::~Executor()\n{\n stop();\n for (auto &t : thread_pool)\n t.t.join();\n}\n\nvoid Executor::run(size_t i)\n{\n while (!done)\n {\n std::string error;\n try\n {\n Task t;\n const size_t spin_count = nThreads * 4;\n for (auto n = 0; n != spin_count; ++n)\n {\n if (thread_pool[(i + n) % nThreads].q.try_pop(t))\n break;\n }\n\n \/\/ no task popped, probably shutdown command was issues\n if (!t && !thread_pool[i].q.pop(t))\n break;\n\n thread_pool[i].busy = true;\n t();\n }\n catch (const std::exception &e)\n {\n error = e.what();\n thread_pool[i].eptr = std::current_exception();\n }\n catch (...)\n {\n error = \"unknown exception\";\n thread_pool[i].eptr = std::current_exception();\n }\n thread_pool[i].busy = false;\n\n if (!error.empty())\n {\n if (throw_exceptions)\n done = true;\n else\n std::cerr << \"executor: \" << this << \", thread #\" << i + 1 << \", error: \" << error << \"\\n\";\n \/\/LOG_ERROR(logger, \"executor: \" << this << \", thread #\" << i + 1 << \", error: \" << error);\n }\n }\n}\n\nvoid Executor::stop()\n{\n done = true;\n for (auto &t : thread_pool)\n t.q.done();\n}\n\nvoid Executor::wait()\n{\n \/\/ wait for empty queues\n for (auto &t : thread_pool)\n while (!t.q.empty() && !done)\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n \/\/ wait for end of execution\n for (auto &t : thread_pool)\n while (t.busy && !done)\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n if (throw_exceptions)\n for (auto &t : thread_pool)\n if (t.eptr)\n std::rethrow_exception(t.eptr);\n}\n\nvoid Executor::set_thread_name(const std::string &name, size_t i) const\n{\n if (name.empty())\n return;\n\n#if defined(_MSC_VER)\n constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;\n\n#pragma pack(push, 8)\n struct THREADNAME_INFO\n {\n DWORD dwType; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to thread name\n DWORD dwThreadId; \/\/ Thread ID (-1 == current thread)\n DWORD dwFlags; \/\/ Reserved. Do not use.\n };\n#pragma pack(pop)\n\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = name.c_str();\n info.dwThreadId = *(DWORD *)&std::this_thread::get_id();\n info.dwFlags = 0;\n\n __try\n {\n ::RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) \/ sizeof(ULONG_PTR), (ULONG_PTR *)&info);\n }\n __except (EXCEPTION_EXECUTE_HANDLER)\n {\n }\n#endif\n}\n<commit_msg>Simplify set_thread_name().<commit_after>#include <primitives\/executor.h>\n\n#include <iostream>\n#include <string>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\n\/\/#include \"log.h\"\n\/\/DECLARE_STATIC_LOGGER(logger, \"executor\");\n\nsize_t get_max_threads(size_t N)\n{\n return std::max<size_t>(N, std::thread::hardware_concurrency());\n}\n\nExecutor::Executor(const std::string &name, size_t nThreads)\n : Executor(nThreads, name)\n{\n}\n\nExecutor::Executor(size_t nThreads, const std::string &name)\n : nThreads(nThreads)\n{\n thread_pool.resize(nThreads);\n for (size_t i = 0; i < nThreads; i++)\n {\n thread_pool[i].t = std::move(std::thread([this, i, name = name]() mutable\n {\n name += \" \" + std::to_string(i);\n set_thread_name(name, i);\n run(i);\n }));\n }\n}\n\nExecutor::~Executor()\n{\n stop();\n for (auto &t : thread_pool)\n t.t.join();\n}\n\nvoid Executor::run(size_t i)\n{\n while (!done)\n {\n std::string error;\n try\n {\n Task t;\n const size_t spin_count = nThreads * 4;\n for (auto n = 0; n != spin_count; ++n)\n {\n if (thread_pool[(i + n) % nThreads].q.try_pop(t))\n break;\n }\n\n \/\/ no task popped, probably shutdown command was issues\n if (!t && !thread_pool[i].q.pop(t))\n break;\n\n thread_pool[i].busy = true;\n t();\n }\n catch (const std::exception &e)\n {\n error = e.what();\n thread_pool[i].eptr = std::current_exception();\n }\n catch (...)\n {\n error = \"unknown exception\";\n thread_pool[i].eptr = std::current_exception();\n }\n thread_pool[i].busy = false;\n\n if (!error.empty())\n {\n if (throw_exceptions)\n done = true;\n else\n std::cerr << \"executor: \" << this << \", thread #\" << i + 1 << \", error: \" << error << \"\\n\";\n \/\/LOG_ERROR(logger, \"executor: \" << this << \", thread #\" << i + 1 << \", error: \" << error);\n }\n }\n}\n\nvoid Executor::stop()\n{\n done = true;\n for (auto &t : thread_pool)\n t.q.done();\n}\n\nvoid Executor::wait()\n{\n \/\/ wait for empty queues\n for (auto &t : thread_pool)\n while (!t.q.empty() && !done)\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n \/\/ wait for end of execution\n for (auto &t : thread_pool)\n while (t.busy && !done)\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n if (throw_exceptions)\n for (auto &t : thread_pool)\n if (t.eptr)\n std::rethrow_exception(t.eptr);\n}\n\nvoid Executor::set_thread_name(const std::string &name, size_t i) const\n{\n if (name.empty())\n return;\n\n#if defined(_MSC_VER)\n#pragma pack(push, 8)\n struct THREADNAME_INFO\n {\n DWORD dwType = 0x1000; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to thread name\n DWORD dwThreadId = -1; \/\/ Thread ID (-1 == current thread)\n DWORD dwFlags = 0; \/\/ Reserved. Do not use.\n };\n#pragma pack(pop)\n\n THREADNAME_INFO info;\n info.szName = name.c_str();\n\n __try\n {\n ::RaiseException(0x406D1388, 0, sizeof(info) \/ sizeof(ULONG_PTR), (ULONG_PTR *)&info);\n }\n __except (EXCEPTION_EXECUTE_HANDLER)\n {\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"commandwatcher.h\"\n#include \"sconnect.h\"\n#include \"contextproperty.h\"\n#include \"propertylistener.h\"\n#include <QTextStream>\n#include <QFile>\n#include <QSocketNotifier>\n#include <QStringList>\n#include <QCoreApplication>\n#include \"contextpropertyinfo.h\"\n#include <QDebug>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <QMap>\n\nCommandWatcher::CommandWatcher(int commandfd, QMap<QString, ContextProperty*> *properties, QObject *parent) :\n QObject(parent), commandfd(commandfd), properties(properties)\n{\n commandNotifier = new QSocketNotifier(commandfd, QSocketNotifier::Read, this);\n sconnect(commandNotifier, SIGNAL(activated(int)), this, SLOT(onActivated()));\n help();\n}\n\nvoid CommandWatcher::onActivated()\n{\n \/\/ read all available input to commandBuffer\n static QByteArray commandBuffer = \"\";\n static char buf[1024];\n int readSize;\n fcntl(commandfd, F_SETFL, O_NONBLOCK);\n while ((readSize = read(commandfd, &buf, 1024)) > 0)\n commandBuffer += QByteArray(buf, readSize);\n\n \/\/ handle all available whole input lines as commands\n int nextSeparator;\n while ((nextSeparator = commandBuffer.indexOf('\\n')) != -1) {\n \/\/ split lines to separate commands by semicolons\n QStringList commands = QString::fromUtf8(commandBuffer.constData()).left(nextSeparator).split(\";\");\n foreach (QString command, commands)\n interpret(command.trimmed());\n commandBuffer.remove(0, nextSeparator + 1);\n }\n\n if (readSize == 0) \/\/ EOF\n QCoreApplication::exit(0);\n}\n\nvoid CommandWatcher::help()\n{\n qDebug() << \"Available commands:\";\n qDebug() << \" new KEY... - create context properties\";\n qDebug() << \" delete KEY... - delete context properties\";\n qDebug() << \" subscribe KEY... - subscribe to keys\";\n qDebug() << \" waitforsubscription KEY... - subscribe to keys\";\n qDebug() << \" unsubscribe KEY... - unsubscribe from keys\";\n qDebug() << \" value KEY [DEF] - get value for a key\";\n qDebug() << \" key KEY - get the key for a key (rather useless)\";\n qDebug() << \" ikey KEY - get the info()->key for a key (rather useless)\";\n qDebug() << \" man KEY - get the info()->doc for a key\";\n qDebug() << \" type KEY - get the info()->type for a key\";\n qDebug() << \" plugin KEY - get the info()->plugin for a key\";\n qDebug() << \" constructionstring KEY - get the info()->constructionstring for a key\";\n qDebug() << \" flush - write FLUSHED to stderr and stdout\";\n qDebug() << \"Any prefix of a command can be used as an abbreviation\";\n}\n\nvoid CommandWatcher::interpret(const QString& command) const\n{\n QTextStream out(stdout);\n QTextStream err(stderr);\n if (command == \"\") {\n help();\n } else {\n QStringList args = command.split(\" \");\n QString commandName = args[0];\n args.pop_front();\n\n if (args.size() == 0 && !QString(\"flush\").startsWith(commandName)) {\n help();\n return;\n }\n\n if (QString(\"new\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n qDebug() << \"key already exists: \" << key;\n else {\n properties->insert(key, new ContextProperty(key, QCoreApplication::instance()));\n new PropertyListener(properties->value(key));\n }\n } else if (QString(\"delete\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n delete properties->take(key);\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"subscribe\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n properties->value(key)->subscribe();\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"waitforsubscription\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key)) {\n properties->value(key)->waitForSubscription();\n out << \"wait finished for \" << key << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"unsubscribe\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n properties->value(key)->unsubscribe();\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"value\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QVariant value;\n if (args.size() > 1) {\n value = properties->value(key)->value(args[1]);\n } else {\n value = properties->value(key)->value();\n }\n if (value.isNull())\n out << \"value is Unknown\" << endl;\n else\n out << \"value: \" << value.typeName() << \":\" << value.toString() << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"key\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"key: \" << properties->value(key)->key() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"ikey\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"ikey: \" << properties->value(key)->info()->key() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"man\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"man: \" << properties->value(key)->info()->doc() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"type\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"type: \" << properties->value(key)->info()->type() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"plugin\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n if (providers.size() > 0)\n out << \"plugin: \" << providers.at(0).plugin;\n else\n out << \"no plugin for key:\" << key;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"constructionstring\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n if (providers.size() > 0)\n out << \"constructionstring: \" << providers.at(0).constructionString;\n else\n out << \"no constructionString for key:\" << key;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"providers\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n foreach(ContextProviderInfo info, providers)\n out << \"Provider:\" << info.plugin << \":\" << info.constructionString;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"flush\").startsWith(commandName)) {\n out << \"FLUSHED\" << endl;\n out.flush();\n err << \"FLUSHED\" << endl;\n err.flush();\n } else\n help();\n }\n}\n<commit_msg>context-listen update.<commit_after>\/*\n * Copyright (C) 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"commandwatcher.h\"\n#include \"sconnect.h\"\n#include \"contextproperty.h\"\n#include \"propertylistener.h\"\n#include <QTextStream>\n#include <QFile>\n#include <QSocketNotifier>\n#include <QStringList>\n#include <QCoreApplication>\n#include \"contextpropertyinfo.h\"\n#include <QDebug>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <QMap>\n\nCommandWatcher::CommandWatcher(int commandfd, QMap<QString, ContextProperty*> *properties, QObject *parent) :\n QObject(parent), commandfd(commandfd), properties(properties)\n{\n commandNotifier = new QSocketNotifier(commandfd, QSocketNotifier::Read, this);\n sconnect(commandNotifier, SIGNAL(activated(int)), this, SLOT(onActivated()));\n help();\n}\n\nvoid CommandWatcher::onActivated()\n{\n \/\/ read all available input to commandBuffer\n static QByteArray commandBuffer = \"\";\n static char buf[1024];\n int readSize;\n fcntl(commandfd, F_SETFL, O_NONBLOCK);\n while ((readSize = read(commandfd, &buf, 1024)) > 0)\n commandBuffer += QByteArray(buf, readSize);\n\n \/\/ handle all available whole input lines as commands\n int nextSeparator;\n while ((nextSeparator = commandBuffer.indexOf('\\n')) != -1) {\n \/\/ split lines to separate commands by semicolons\n QStringList commands = QString::fromUtf8(commandBuffer.constData()).left(nextSeparator).split(\";\");\n foreach (QString command, commands)\n interpret(command.trimmed());\n commandBuffer.remove(0, nextSeparator + 1);\n }\n\n if (readSize == 0) \/\/ EOF\n QCoreApplication::exit(0);\n}\n\nvoid CommandWatcher::help()\n{\n qDebug() << \"Available commands:\";\n qDebug() << \" new KEY... - create context properties\";\n qDebug() << \" delete KEY... - delete context properties\";\n qDebug() << \" subscribe KEY... - subscribe to keys\";\n qDebug() << \" waitforsubscription KEY... - subscribe to keys\";\n qDebug() << \" unsubscribe KEY... - unsubscribe from keys\";\n qDebug() << \" value KEY [DEF] - get value for a key\";\n qDebug() << \" key KEY - get the key for a key (rather useless)\";\n qDebug() << \" ikey KEY - get the info()->key for a key (rather useless)\";\n qDebug() << \" man KEY - get the info()->doc for a key\";\n qDebug() << \" type KEY - get the info()->type for a key\";\n qDebug() << \" plugin KEY - get the info()->plugin for a key\";\n qDebug() << \" constructionstring KEY - get the info()->constructionstring for a key\";\n qDebug() << \" flush - write FLUSHED to stderr and stdout\";\n qDebug() << \"Any prefix of a command can be used as an abbreviation\";\n}\n\nvoid CommandWatcher::interpret(const QString& command) const\n{\n QTextStream out(stdout);\n QTextStream err(stderr);\n if (command == \"\") {\n help();\n } else {\n QStringList args = command.split(\" \");\n QString commandName = args[0];\n args.pop_front();\n\n if (args.size() == 0 && !QString(\"flush\").startsWith(commandName)) {\n help();\n return;\n }\n\n if (QString(\"new\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n qDebug() << \"key already exists: \" << key;\n else {\n properties->insert(key, new ContextProperty(key, QCoreApplication::instance()));\n new PropertyListener(properties->value(key));\n }\n } else if (QString(\"delete\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n delete properties->take(key);\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"subscribe\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n properties->value(key)->subscribe();\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"waitforsubscription\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key)) {\n properties->value(key)->waitForSubscription();\n out << \"wait finished for \" << key << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"unsubscribe\").startsWith(commandName)) {\n foreach (QString key, args)\n if (properties->contains(key))\n properties->value(key)->unsubscribe();\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"value\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QVariant value;\n if (args.size() > 1) {\n value = properties->value(key)->value(args[1]);\n } else {\n value = properties->value(key)->value();\n }\n if (value.isNull())\n out << \"value is Unknown\" << endl;\n else\n out << \"value: \" << value.typeName() << \":\" << value.toString() << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"key\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"key: \" << properties->value(key)->key() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"ikey\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"ikey: \" << properties->value(key)->info()->key() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"man\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"man: \" << properties->value(key)->info()->doc() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"type\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key))\n out << \"type: \" << properties->value(key)->info()->type() << endl;\n else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"plugin\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n if (providers.size() > 0)\n out << \"plugin: \" << providers.at(0).plugin << endl;\n else\n out << \"no plugin for key:\" << key << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"constructionstring\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n if (providers.size() > 0)\n out << \"constructionstring: \" << providers.at(0).constructionString << endl;\n else\n out << \"no constructionString for key:\" << key << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"providers\").startsWith(commandName)) {\n QString key = args[0];\n if (properties->contains(key)) {\n QList<ContextProviderInfo> providers = properties->value(key)->info()->providers();\n foreach(ContextProviderInfo info, providers)\n out << \"Provider:\" << info.plugin << \":\" << info.constructionString << endl;\n } else\n qDebug() << \"no such key:\" << key;\n } else if (QString(\"flush\").startsWith(commandName)) {\n out << \"FLUSHED\" << endl;\n out.flush();\n err << \"FLUSHED\" << endl;\n err.flush();\n } else\n help();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n\n#include <ctype.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include <string>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nenum ParsingState {\n KEY_NAME,\n KEY_VALUE\n};\n\n\/\/ Reads \/proc\/<pid>\/stat and populates |proc_stats| with the values split by\n\/\/ spaces.\nvoid GetProcStats(pid_t pid, std::vector<std::string>* proc_stats) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(pid));\n stat_file = stat_file.Append(\"stat\");\n std::string mem_stats;\n if (!file_util::ReadFileToString(stat_file, &mem_stats))\n return;\n SplitString(mem_stats, ' ', proc_stats);\n}\n\n} \/\/ namespace\n\nnamespace base {\n\nProcessId GetParentProcessId(ProcessHandle process) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(process));\n stat_file = stat_file.Append(\"status\");\n std::string status;\n if (!file_util::ReadFileToString(stat_file, &status))\n return -1;\n\n StringTokenizer tokenizer(status, \":\\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"PPid\") {\n pid_t ppid = StringToInt(tokenizer.token());\n return ppid;\n }\n state = KEY_NAME;\n break;\n }\n }\n NOTREACHED();\n return -1;\n}\n\nFilePath GetProcessExecutablePath(ProcessHandle process) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(process));\n stat_file = stat_file.Append(\"exe\");\n char exename[2048];\n ssize_t len = readlink(stat_file.value().c_str(), exename, sizeof(exename));\n if (len < 1) {\n \/\/ No such process. Happens frequently in e.g. TerminateAllChromeProcesses\n return FilePath();\n }\n return FilePath(std::string(exename, len));\n}\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const environment_vector& environ,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n pid_t pid = fork();\n if (pid < 0)\n return false;\n\n if (pid == 0) {\n \/\/ Child process\n InjectiveMultimap fd_shuffle;\n for (file_handle_mapping_vector::const_iterator\n it = fds_to_remap.begin(); it != fds_to_remap.end(); ++it) {\n fd_shuffle.push_back(InjectionArc(it->first, it->second, false));\n }\n\n for (environment_vector::const_iterator it = environ.begin();\n it != environ.end(); ++it) {\n if (it->first) {\n if (it->second) {\n setenv(it->first, it->second, 1);\n } else {\n unsetenv(it->first);\n }\n }\n }\n\n if (!ShuffleFileDescriptors(fd_shuffle))\n exit(127);\n\n \/\/ If we are using the SUID sandbox, it sets a magic environment variable\n \/\/ (\"SBX_D\"), so we remove that variable from the environment here on the\n \/\/ off chance that it's already set.\n unsetenv(\"SBX_D\");\n\n CloseSuperfluousFds(fd_shuffle);\n\n scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);\n for (size_t i = 0; i < argv.size(); i++)\n argv_cstr[i] = const_cast<char*>(argv[i].c_str());\n argv_cstr[argv.size()] = NULL;\n execvp(argv_cstr[0], argv_cstr.get());\n LOG(ERROR) << \"LaunchApp: exec failed!, argv_cstr[0] \" << argv_cstr[0]\n << \", errno \" << errno;\n exit(127);\n } else {\n \/\/ Parent process\n if (wait)\n HANDLE_EINTR(waitpid(pid, 0, 0));\n\n if (process_handle)\n *process_handle = pid;\n }\n\n return true;\n}\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n base::environment_vector no_env;\n return LaunchApp(argv, no_env, fds_to_remap, wait, process_handle);\n}\n\nbool LaunchApp(const CommandLine& cl,\n bool wait, bool start_hidden,\n ProcessHandle* process_handle) {\n file_handle_mapping_vector no_files;\n return LaunchApp(cl.argv(), no_files, wait, process_handle);\n}\n\nNamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,\n const ProcessFilter* filter)\n : executable_name_(executable_name), filter_(filter) {\n procfs_dir_ = opendir(\"\/proc\");\n}\n\nNamedProcessIterator::~NamedProcessIterator() {\n if (procfs_dir_) {\n closedir(procfs_dir_);\n procfs_dir_ = NULL;\n }\n}\n\nconst ProcessEntry* NamedProcessIterator::NextProcessEntry() {\n bool result = false;\n do {\n result = CheckForNextProcess();\n } while (result && !IncludeEntry());\n\n if (result)\n return &entry_;\n\n return NULL;\n}\n\nbool NamedProcessIterator::CheckForNextProcess() {\n \/\/ TODO(port): skip processes owned by different UID\n\n dirent* slot = 0;\n const char* openparen;\n const char* closeparen;\n\n \/\/ Arbitrarily guess that there will never be more than 200 non-process\n \/\/ files in \/proc. Hardy has 53.\n int skipped = 0;\n const int kSkipLimit = 200;\n while (skipped < kSkipLimit) {\n slot = readdir(procfs_dir_);\n \/\/ all done looking through \/proc?\n if (!slot)\n return false;\n\n \/\/ If not a process, keep looking for one.\n bool notprocess = false;\n int i;\n for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) {\n if (!isdigit(slot->d_name[i])) {\n notprocess = true;\n break;\n }\n }\n if (i == NAME_MAX || notprocess) {\n skipped++;\n continue;\n }\n\n \/\/ Read the process's status.\n char buf[NAME_MAX + 12];\n sprintf(buf, \"\/proc\/%s\/stat\", slot->d_name);\n FILE *fp = fopen(buf, \"r\");\n if (!fp)\n return false;\n const char* result = fgets(buf, sizeof(buf), fp);\n fclose(fp);\n if (!result)\n return false;\n\n \/\/ Parse the status. It is formatted like this:\n \/\/ %d (%s) %c %d ...\n \/\/ pid (name) runstate ppid\n \/\/ To avoid being fooled by names containing a closing paren, scan\n \/\/ backwards.\n openparen = strchr(buf, '(');\n closeparen = strrchr(buf, ')');\n if (!openparen || !closeparen)\n return false;\n char runstate = closeparen[2];\n\n \/\/ Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?\n \/\/ Allowed values: D R S T Z\n if (runstate != 'Z')\n break;\n\n \/\/ Nope, it's a zombie; somebody isn't cleaning up after their children.\n \/\/ (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)\n \/\/ There could be a lot of zombies, can't really decrement i here.\n }\n if (skipped >= kSkipLimit) {\n NOTREACHED();\n return false;\n }\n\n entry_.pid = atoi(slot->d_name);\n entry_.ppid = atoi(closeparen + 3);\n\n \/\/ TODO(port): read pid's commandline's $0, like killall does. Using the\n \/\/ short name between openparen and closeparen won't work for long names!\n int len = closeparen - openparen - 1;\n if (len > NAME_MAX)\n len = NAME_MAX;\n memcpy(entry_.szExeFile, openparen + 1, len);\n entry_.szExeFile[len] = 0;\n\n return true;\n}\n\nbool NamedProcessIterator::IncludeEntry() {\n \/\/ TODO(port): make this also work for non-ASCII filenames\n if (WideToASCII(executable_name_) != entry_.szExeFile)\n return false;\n if (!filter_)\n return true;\n return filter_->Includes(entry_.pid, entry_.ppid);\n}\n\n\/\/ On linux, we return vsize.\nsize_t ProcessMetrics::GetPagefileUsage() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmSize = 22;\n if (proc_stats.size() > kVmSize)\n return static_cast<size_t>(StringToInt(proc_stats[kVmSize]));\n return 0;\n}\n\nsize_t ProcessMetrics::GetPeakPagefileUsage() const {\n \/\/ http:\/\/crbug.com\/16251\n return 0;\n}\n\n\/\/ On linux, we return RSS.\nsize_t ProcessMetrics::GetWorkingSetSize() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmRss = 23;\n if (proc_stats.size() > kVmRss) {\n size_t num_pages = static_cast<size_t>(StringToInt(proc_stats[kVmRss]));\n return num_pages * getpagesize();\n }\n return 0;\n}\n\nsize_t ProcessMetrics::GetPeakWorkingSetSize() const {\n \/\/ http:\/\/crbug.com\/16251\n return 0;\n}\n\nsize_t ProcessMetrics::GetPrivateBytes() const {\n \/\/ http:\/\/crbug.com\/16251\n return 0;\n}\n\nbool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {\n \/\/ http:\/\/crbug.com\/16251\n return false;\n}\n\n\/\/ To have \/proc\/self\/io file you must enable CONFIG_TASK_IO_ACCOUNTING\n\/\/ in your kernel configuration.\nbool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {\n std::string proc_io_contents;\n FilePath io_file(\"\/proc\");\n io_file = io_file.Append(IntToString(process_));\n io_file = io_file.Append(\"io\");\n if (!file_util::ReadFileToString(io_file, &proc_io_contents))\n return false;\n\n (*io_counters).OtherOperationCount = 0;\n (*io_counters).OtherTransferCount = 0;\n\n StringTokenizer tokenizer(proc_io_contents, \": \\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"syscr\") {\n (*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"syscw\") {\n (*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"rchar\") {\n (*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"wchar\") {\n (*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());\n }\n state = KEY_NAME;\n break;\n }\n }\n return true;\n}\n\n} \/\/ namespace base\n<commit_msg>This implements the functions necessary for the task manager on Linux.<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n\n#include <ctype.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include <string>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nenum ParsingState {\n KEY_NAME,\n KEY_VALUE\n};\n\n\/\/ Reads \/proc\/<pid>\/stat and populates |proc_stats| with the values split by\n\/\/ spaces.\nvoid GetProcStats(pid_t pid, std::vector<std::string>* proc_stats) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(pid));\n stat_file = stat_file.Append(\"stat\");\n std::string mem_stats;\n if (!file_util::ReadFileToString(stat_file, &mem_stats))\n return;\n SplitString(mem_stats, ' ', proc_stats);\n}\n\n} \/\/ namespace\n\nnamespace base {\n\nProcessId GetParentProcessId(ProcessHandle process) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(process));\n stat_file = stat_file.Append(\"status\");\n std::string status;\n if (!file_util::ReadFileToString(stat_file, &status))\n return -1;\n\n StringTokenizer tokenizer(status, \":\\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"PPid\") {\n pid_t ppid = StringToInt(tokenizer.token());\n return ppid;\n }\n state = KEY_NAME;\n break;\n }\n }\n NOTREACHED();\n return -1;\n}\n\nFilePath GetProcessExecutablePath(ProcessHandle process) {\n FilePath stat_file(\"\/proc\");\n stat_file = stat_file.Append(IntToString(process));\n stat_file = stat_file.Append(\"exe\");\n char exename[2048];\n ssize_t len = readlink(stat_file.value().c_str(), exename, sizeof(exename));\n if (len < 1) {\n \/\/ No such process. Happens frequently in e.g. TerminateAllChromeProcesses\n return FilePath();\n }\n return FilePath(std::string(exename, len));\n}\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const environment_vector& environ,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n pid_t pid = fork();\n if (pid < 0)\n return false;\n\n if (pid == 0) {\n \/\/ Child process\n InjectiveMultimap fd_shuffle;\n for (file_handle_mapping_vector::const_iterator\n it = fds_to_remap.begin(); it != fds_to_remap.end(); ++it) {\n fd_shuffle.push_back(InjectionArc(it->first, it->second, false));\n }\n\n for (environment_vector::const_iterator it = environ.begin();\n it != environ.end(); ++it) {\n if (it->first) {\n if (it->second) {\n setenv(it->first, it->second, 1);\n } else {\n unsetenv(it->first);\n }\n }\n }\n\n if (!ShuffleFileDescriptors(fd_shuffle))\n exit(127);\n\n \/\/ If we are using the SUID sandbox, it sets a magic environment variable\n \/\/ (\"SBX_D\"), so we remove that variable from the environment here on the\n \/\/ off chance that it's already set.\n unsetenv(\"SBX_D\");\n\n CloseSuperfluousFds(fd_shuffle);\n\n scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);\n for (size_t i = 0; i < argv.size(); i++)\n argv_cstr[i] = const_cast<char*>(argv[i].c_str());\n argv_cstr[argv.size()] = NULL;\n execvp(argv_cstr[0], argv_cstr.get());\n LOG(ERROR) << \"LaunchApp: exec failed!, argv_cstr[0] \" << argv_cstr[0]\n << \", errno \" << errno;\n exit(127);\n } else {\n \/\/ Parent process\n if (wait)\n HANDLE_EINTR(waitpid(pid, 0, 0));\n\n if (process_handle)\n *process_handle = pid;\n }\n\n return true;\n}\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n base::environment_vector no_env;\n return LaunchApp(argv, no_env, fds_to_remap, wait, process_handle);\n}\n\nbool LaunchApp(const CommandLine& cl,\n bool wait, bool start_hidden,\n ProcessHandle* process_handle) {\n file_handle_mapping_vector no_files;\n return LaunchApp(cl.argv(), no_files, wait, process_handle);\n}\n\nNamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,\n const ProcessFilter* filter)\n : executable_name_(executable_name), filter_(filter) {\n procfs_dir_ = opendir(\"\/proc\");\n}\n\nNamedProcessIterator::~NamedProcessIterator() {\n if (procfs_dir_) {\n closedir(procfs_dir_);\n procfs_dir_ = NULL;\n }\n}\n\nconst ProcessEntry* NamedProcessIterator::NextProcessEntry() {\n bool result = false;\n do {\n result = CheckForNextProcess();\n } while (result && !IncludeEntry());\n\n if (result)\n return &entry_;\n\n return NULL;\n}\n\nbool NamedProcessIterator::CheckForNextProcess() {\n \/\/ TODO(port): skip processes owned by different UID\n\n dirent* slot = 0;\n const char* openparen;\n const char* closeparen;\n\n \/\/ Arbitrarily guess that there will never be more than 200 non-process\n \/\/ files in \/proc. Hardy has 53.\n int skipped = 0;\n const int kSkipLimit = 200;\n while (skipped < kSkipLimit) {\n slot = readdir(procfs_dir_);\n \/\/ all done looking through \/proc?\n if (!slot)\n return false;\n\n \/\/ If not a process, keep looking for one.\n bool notprocess = false;\n int i;\n for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) {\n if (!isdigit(slot->d_name[i])) {\n notprocess = true;\n break;\n }\n }\n if (i == NAME_MAX || notprocess) {\n skipped++;\n continue;\n }\n\n \/\/ Read the process's status.\n char buf[NAME_MAX + 12];\n sprintf(buf, \"\/proc\/%s\/stat\", slot->d_name);\n FILE *fp = fopen(buf, \"r\");\n if (!fp)\n return false;\n const char* result = fgets(buf, sizeof(buf), fp);\n fclose(fp);\n if (!result)\n return false;\n\n \/\/ Parse the status. It is formatted like this:\n \/\/ %d (%s) %c %d ...\n \/\/ pid (name) runstate ppid\n \/\/ To avoid being fooled by names containing a closing paren, scan\n \/\/ backwards.\n openparen = strchr(buf, '(');\n closeparen = strrchr(buf, ')');\n if (!openparen || !closeparen)\n return false;\n char runstate = closeparen[2];\n\n \/\/ Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?\n \/\/ Allowed values: D R S T Z\n if (runstate != 'Z')\n break;\n\n \/\/ Nope, it's a zombie; somebody isn't cleaning up after their children.\n \/\/ (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)\n \/\/ There could be a lot of zombies, can't really decrement i here.\n }\n if (skipped >= kSkipLimit) {\n NOTREACHED();\n return false;\n }\n\n entry_.pid = atoi(slot->d_name);\n entry_.ppid = atoi(closeparen + 3);\n\n \/\/ TODO(port): read pid's commandline's $0, like killall does. Using the\n \/\/ short name between openparen and closeparen won't work for long names!\n int len = closeparen - openparen - 1;\n if (len > NAME_MAX)\n len = NAME_MAX;\n memcpy(entry_.szExeFile, openparen + 1, len);\n entry_.szExeFile[len] = 0;\n\n return true;\n}\n\nbool NamedProcessIterator::IncludeEntry() {\n \/\/ TODO(port): make this also work for non-ASCII filenames\n if (WideToASCII(executable_name_) != entry_.szExeFile)\n return false;\n if (!filter_)\n return true;\n return filter_->Includes(entry_.pid, entry_.ppid);\n}\n\n\/\/ On linux, we return vsize.\nsize_t ProcessMetrics::GetPagefileUsage() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmSize = 22;\n if (proc_stats.size() > kVmSize)\n return static_cast<size_t>(StringToInt(proc_stats[kVmSize]));\n return 0;\n}\n\n\/\/ On linux, we return the high water mark of vsize.\nsize_t ProcessMetrics::GetPeakPagefileUsage() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmPeak = 21;\n if (proc_stats.size() > kVmPeak)\n return static_cast<size_t>(StringToInt(proc_stats[kVmPeak]));\n return 0;\n}\n\n\/\/ On linux, we return RSS.\nsize_t ProcessMetrics::GetWorkingSetSize() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmRss = 23;\n if (proc_stats.size() > kVmRss) {\n size_t num_pages = static_cast<size_t>(StringToInt(proc_stats[kVmRss]));\n return num_pages * getpagesize();\n }\n return 0;\n}\n\n\/\/ On linux, we return the high water mark of RSS.\nsize_t ProcessMetrics::GetPeakWorkingSetSize() const {\n std::vector<std::string> proc_stats;\n GetProcStats(process_, &proc_stats);\n const size_t kVmHwm = 23;\n if (proc_stats.size() > kVmHwm) {\n size_t num_pages = static_cast<size_t>(StringToInt(proc_stats[kVmHwm]));\n return num_pages * getpagesize();\n }\n return 0;\n}\n\nsize_t ProcessMetrics::GetPrivateBytes() const {\n \/\/ http:\/\/crbug.com\/16251\n return 0;\n}\n\n\/\/ Private and Shared working set sizes are obtained from \/proc\/<pid>\/smaps,\n\/\/ as in http:\/\/www.pixelbeat.org\/scripts\/ps_mem.py\nbool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {\n FilePath stat_file =\n FilePath(\"\/proc\").Append(IntToString(process_)).Append(\"smaps\");\n std::string smaps;\n int shared_kb = 0;\n int private_kb = 0;\n int pss_kb = 0;\n bool have_pss = false;\n const int kPssAdjust = 0.5;\n if (!file_util::ReadFileToString(stat_file, &smaps))\n return false;\n\n StringTokenizer tokenizer(smaps, \":\\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n if (last_key_name.empty()) {\n NOTREACHED();\n return false;\n }\n if (StartsWithASCII(last_key_name, \"Shared_\", 1)) {\n shared_kb += StringToInt(tokenizer.token());\n } else if (StartsWithASCII(last_key_name, \"Private_\", 1)) {\n private_kb += StringToInt(tokenizer.token());\n } else if (StartsWithASCII(last_key_name, \"Pss\", 1)) {\n have_pss = true;\n pss_kb += StringToInt(tokenizer.token()) + kPssAdjust;\n }\n state = KEY_NAME;\n break;\n }\n }\n ws_usage->priv = private_kb;\n \/\/ Sharable is not calculated, as it does not provide interesting data.\n ws_usage->shareable = 0;\n if (have_pss) {\n ws_usage->shared = pss_kb - private_kb;\n } else {\n ws_usage->shared = shared_kb;\n }\n return true;\n}\n\n\/\/ To have \/proc\/self\/io file you must enable CONFIG_TASK_IO_ACCOUNTING\n\/\/ in your kernel configuration.\nbool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {\n std::string proc_io_contents;\n FilePath io_file(\"\/proc\");\n io_file = io_file.Append(IntToString(process_));\n io_file = io_file.Append(\"io\");\n if (!file_util::ReadFileToString(io_file, &proc_io_contents))\n return false;\n\n (*io_counters).OtherOperationCount = 0;\n (*io_counters).OtherTransferCount = 0;\n\n StringTokenizer tokenizer(proc_io_contents, \": \\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"syscr\") {\n (*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"syscw\") {\n (*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"rchar\") {\n (*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"wchar\") {\n (*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());\n }\n state = KEY_NAME;\n break;\n }\n }\n return true;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Convert NOTIMPLs into a bug.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/mat.hpp>\n#include <gtest\/gtest.h>\n\nTEST(MathMatrix, multiply_c_v) {\n stan::math::vector_d v(3);\n v << 1, 2, 3;\n stan::math::vector_d result = stan::math::multiply(2.0, v);\n EXPECT_FLOAT_EQ(2.0, result(0));\n EXPECT_FLOAT_EQ(4.0, result(1));\n EXPECT_FLOAT_EQ(6.0, result(2));\n}\nTEST(MathMatrix, multiply_c_rv) {\n stan::math::row_vector_d rv(3);\n rv << 1, 2, 3;\n stan::math::row_vector_d result = stan::math::multiply(2.0, rv);\n EXPECT_FLOAT_EQ(2.0, result(0));\n EXPECT_FLOAT_EQ(4.0, result(1));\n EXPECT_FLOAT_EQ(6.0, result(2));\n}\nTEST(MathMatrix, multiply_c_m) {\n stan::math::matrix_d m(2, 3);\n m << 1, 2, 3, 4, 5, 6;\n stan::math::matrix_d result = stan::math::multiply(2.0, m);\n EXPECT_FLOAT_EQ(2.0, result(0, 0));\n EXPECT_FLOAT_EQ(4.0, result(0, 1));\n EXPECT_FLOAT_EQ(6.0, result(0, 2));\n EXPECT_FLOAT_EQ(8.0, result(1, 0));\n EXPECT_FLOAT_EQ(10.0, result(1, 1));\n EXPECT_FLOAT_EQ(12.0, result(1, 2));\n}\n\nTEST(MathMatrix, multiply_rv_v_exception) {\n stan::math::row_vector_d rv;\n stan::math::vector_d v;\n\n rv.resize(3);\n v.resize(3);\n EXPECT_NO_THROW(stan::math::multiply(rv, v));\n\n rv.resize(0);\n v.resize(0);\n EXPECT_NO_THROW(stan::math::multiply(rv, v));\n\n rv.resize(2);\n v.resize(3);\n EXPECT_THROW(stan::math::multiply(rv, v), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_m_v_exception) {\n stan::math::matrix_d m;\n stan::math::vector_d v;\n\n m.resize(3, 5);\n v.resize(5);\n EXPECT_NO_THROW(stan::math::multiply(m, v));\n\n m.resize(3, 0);\n v.resize(0);\n EXPECT_THROW(stan::math::multiply(m, v), std::invalid_argument);\n\n m.resize(2, 3);\n v.resize(2);\n EXPECT_THROW(stan::math::multiply(m, v), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_rv_m_exception) {\n stan::math::row_vector_d rv;\n stan::math::matrix_d m;\n\n rv.resize(3);\n m.resize(3, 5);\n EXPECT_NO_THROW(stan::math::multiply(rv, m));\n\n rv.resize(0);\n m.resize(0, 3);\n EXPECT_THROW(stan::math::multiply(rv, m), std::invalid_argument);\n\n rv.resize(3);\n m.resize(2, 3);\n EXPECT_THROW(stan::math::multiply(rv, m), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_m_m_exception) {\n stan::math::matrix_d m1, m2;\n\n m1.resize(1, 3);\n m2.resize(3, 5);\n EXPECT_NO_THROW(stan::math::multiply(m1, m2));\n\n m1.resize(2, 0);\n m2.resize(0, 3);\n EXPECT_THROW(stan::math::multiply(m1, m2), std::invalid_argument);\n\n m1.resize(4, 3);\n m2.resize(2, 3);\n EXPECT_THROW(stan::math::multiply(m1, m2), std::invalid_argument);\n}\n\nTEST(MathMatrix, multiply) {\n stan::math::vector_d v0;\n stan::math::row_vector_d rv0;\n stan::math::matrix_d m0;\n\n using stan::math::multiply;\n EXPECT_NO_THROW(multiply(v0, 2.0));\n EXPECT_NO_THROW(multiply(rv0, 2.0));\n EXPECT_NO_THROW(multiply(m0, 2.0));\n EXPECT_NO_THROW(multiply(2.0, v0));\n EXPECT_NO_THROW(multiply(2.0, rv0));\n EXPECT_NO_THROW(multiply(2.0, m0));\n}\n\nTEST(AgradRevMatrix, multiply_int) {\n using stan::math::assign;\n using stan::math::multiply;\n\n typedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector_d;\n\n int d_int = 2;\n vector_d vec(4);\n vec << 1, 2, 3, 4;\n vector_d t_vec(4);\n assign(t_vec, multiply(vec, d_int));\n}\n\nTEST(AgradRevMatrix, multiply_vector_int) {\n using stan::math::multiply;\n using stan::math::vector_d;\n\n vector_d dvec(3);\n dvec << 1, 2, 3;\n int a = 2;\n vector_d prod_vec = multiply(dvec, a);\n EXPECT_EQ(3, prod_vec.size());\n EXPECT_EQ(2.0, prod_vec[0]);\n EXPECT_EQ(4.0, prod_vec[1]);\n EXPECT_EQ(6.0, prod_vec[2]);\n}\n\n#ifdef STAN_OPENCL\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n for (int i = 0; i < A.size(); i++) \\\n EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(MathMatrix, multiply_opencl) {\n int multiply_dim_prod_worth_transfer\n = stan::math::opencl_context.tuning_opts()\n .multiply_dim_prod_worth_transfer;\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n = 0;\n using stan::math::multiply;\n int size = 400;\n stan::math::matrix_d m1 = stan::math::matrix_d::Random(size, size).eval();\n stan::math::matrix_d m2 = stan::math::matrix_d::Random(size, size).eval();\n\n stan::math::matrix_d m3_cl = multiply(m1, m2);\n \/\/ to make sure we dont use OpenCL\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n = INT_MAX;\n\n stan::math::matrix_d m3 = multiply(m1, m2);\n\n EXPECT_MATRIX_NEAR(m3_cl, m3, 1e-10);\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n = multiply_dim_prod_worth_transfer;\n}\n#endif\n<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags\/google\/stable\/2017-11-14)<commit_after>#include <stan\/math\/prim\/mat.hpp>\n#include <gtest\/gtest.h>\n\nTEST(MathMatrix, multiply_c_v) {\n stan::math::vector_d v(3);\n v << 1, 2, 3;\n stan::math::vector_d result = stan::math::multiply(2.0, v);\n EXPECT_FLOAT_EQ(2.0, result(0));\n EXPECT_FLOAT_EQ(4.0, result(1));\n EXPECT_FLOAT_EQ(6.0, result(2));\n}\nTEST(MathMatrix, multiply_c_rv) {\n stan::math::row_vector_d rv(3);\n rv << 1, 2, 3;\n stan::math::row_vector_d result = stan::math::multiply(2.0, rv);\n EXPECT_FLOAT_EQ(2.0, result(0));\n EXPECT_FLOAT_EQ(4.0, result(1));\n EXPECT_FLOAT_EQ(6.0, result(2));\n}\nTEST(MathMatrix, multiply_c_m) {\n stan::math::matrix_d m(2, 3);\n m << 1, 2, 3, 4, 5, 6;\n stan::math::matrix_d result = stan::math::multiply(2.0, m);\n EXPECT_FLOAT_EQ(2.0, result(0, 0));\n EXPECT_FLOAT_EQ(4.0, result(0, 1));\n EXPECT_FLOAT_EQ(6.0, result(0, 2));\n EXPECT_FLOAT_EQ(8.0, result(1, 0));\n EXPECT_FLOAT_EQ(10.0, result(1, 1));\n EXPECT_FLOAT_EQ(12.0, result(1, 2));\n}\n\nTEST(MathMatrix, multiply_rv_v_exception) {\n stan::math::row_vector_d rv;\n stan::math::vector_d v;\n\n rv.resize(3);\n v.resize(3);\n EXPECT_NO_THROW(stan::math::multiply(rv, v));\n\n rv.resize(0);\n v.resize(0);\n EXPECT_NO_THROW(stan::math::multiply(rv, v));\n\n rv.resize(2);\n v.resize(3);\n EXPECT_THROW(stan::math::multiply(rv, v), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_m_v_exception) {\n stan::math::matrix_d m;\n stan::math::vector_d v;\n\n m.resize(3, 5);\n v.resize(5);\n EXPECT_NO_THROW(stan::math::multiply(m, v));\n\n m.resize(3, 0);\n v.resize(0);\n EXPECT_THROW(stan::math::multiply(m, v), std::invalid_argument);\n\n m.resize(2, 3);\n v.resize(2);\n EXPECT_THROW(stan::math::multiply(m, v), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_rv_m_exception) {\n stan::math::row_vector_d rv;\n stan::math::matrix_d m;\n\n rv.resize(3);\n m.resize(3, 5);\n EXPECT_NO_THROW(stan::math::multiply(rv, m));\n\n rv.resize(0);\n m.resize(0, 3);\n EXPECT_THROW(stan::math::multiply(rv, m), std::invalid_argument);\n\n rv.resize(3);\n m.resize(2, 3);\n EXPECT_THROW(stan::math::multiply(rv, m), std::invalid_argument);\n}\nTEST(MathMatrix, multiply_m_m_exception) {\n stan::math::matrix_d m1, m2;\n\n m1.resize(1, 3);\n m2.resize(3, 5);\n EXPECT_NO_THROW(stan::math::multiply(m1, m2));\n\n m1.resize(2, 0);\n m2.resize(0, 3);\n EXPECT_THROW(stan::math::multiply(m1, m2), std::invalid_argument);\n\n m1.resize(4, 3);\n m2.resize(2, 3);\n EXPECT_THROW(stan::math::multiply(m1, m2), std::invalid_argument);\n}\n\nTEST(MathMatrix, multiply) {\n stan::math::vector_d v0;\n stan::math::row_vector_d rv0;\n stan::math::matrix_d m0;\n\n using stan::math::multiply;\n EXPECT_NO_THROW(multiply(v0, 2.0));\n EXPECT_NO_THROW(multiply(rv0, 2.0));\n EXPECT_NO_THROW(multiply(m0, 2.0));\n EXPECT_NO_THROW(multiply(2.0, v0));\n EXPECT_NO_THROW(multiply(2.0, rv0));\n EXPECT_NO_THROW(multiply(2.0, m0));\n}\n\nTEST(AgradRevMatrix, multiply_int) {\n using stan::math::assign;\n using stan::math::multiply;\n\n typedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector_d;\n\n int d_int = 2;\n vector_d vec(4);\n vec << 1, 2, 3, 4;\n vector_d t_vec(4);\n assign(t_vec, multiply(vec, d_int));\n}\n\nTEST(AgradRevMatrix, multiply_vector_int) {\n using stan::math::multiply;\n using stan::math::vector_d;\n\n vector_d dvec(3);\n dvec << 1, 2, 3;\n int a = 2;\n vector_d prod_vec = multiply(dvec, a);\n EXPECT_EQ(3, prod_vec.size());\n EXPECT_EQ(2.0, prod_vec[0]);\n EXPECT_EQ(4.0, prod_vec[1]);\n EXPECT_EQ(6.0, prod_vec[2]);\n}\n\n#ifdef STAN_OPENCL\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n for (int i = 0; i < A.size(); i++) \\\n EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(MathMatrix, multiply_opencl) {\n int multiply_dim_prod_worth_transfer\n = stan::math::opencl_context.tuning_opts()\n .multiply_dim_prod_worth_transfer;\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer = 0;\n using stan::math::multiply;\n int size = 400;\n stan::math::matrix_d m1 = stan::math::matrix_d::Random(size, size).eval();\n stan::math::matrix_d m2 = stan::math::matrix_d::Random(size, size).eval();\n\n stan::math::matrix_d m3_cl = multiply(m1, m2);\n \/\/ to make sure we dont use OpenCL\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n = INT_MAX;\n\n stan::math::matrix_d m3 = multiply(m1, m2);\n\n EXPECT_MATRIX_NEAR(m3_cl, m3, 1e-10);\n stan::math::opencl_context.tuning_opts().multiply_dim_prod_worth_transfer\n = multiply_dim_prod_worth_transfer;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include <gloperate\/stages\/multiframe\/MultiFrameAggregationStage.h>\n\n#include <globjects\/base\/StringTemplate.h>\n#include <globjects\/base\/StaticStringSource.h>\n#include <globjects\/VertexArray.h>\n#include <globjects\/VertexAttributeBinding.h>\n#include <globjects\/Framebuffer.h>\n#include <globjects\/globjects.h>\n\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/enum.h>\n\nstatic const std::array<glm::vec2, 4> s_vertices { {\n glm::vec2( +1.f, -1.f ),\n glm::vec2( +1.f, +1.f ),\n glm::vec2( -1.f, -1.f ),\n glm::vec2( -1.f, +1.f ) } };\n\nstatic const char * s_vertexShader = R\"(\n #version 140\n #extension GL_ARB_explicit_attrib_location : require\n\n layout (location = 0) in vec2 a_vertex;\n out vec2 v_uv;\n\n void main()\n {\n v_uv = a_vertex * 0.5 + 0.5;\n gl_Position = vec4(a_vertex, 0.0, 1.0);\n }\n)\";\n\nstatic const char * s_fragmentShader = R\"(\n #version 140\n #extension GL_ARB_explicit_attrib_location : require\n\n uniform sampler2D tex;\n\n layout (location = 0) out vec4 fragColor;\n\n in vec2 v_uv;\n\n void main()\n {\n fragColor = texture(tex, v_uv);\n }\n)\";\n\n\nnamespace gloperate\n{\n\n\nCPPEXPOSE_COMPONENT(MultiFrameAggregationStage, gloperate::Stage)\n\n\nMultiFrameAggregationStage::MultiFrameAggregationStage(Environment * environment, const std::string & name)\n: Stage(environment, name)\n, aggregationFBO(\"aggregationFBO\", this)\n, texture(\"texture\", this)\n, textureRerendered(\"textureRerendered\", this)\n, viewport(\"viewport\", this)\n, aggregationFactor(\"aggregationFactor\", this)\n, aggregatedFBO(\"aggregatedFBO\", this)\n{\n}\n\nMultiFrameAggregationStage::~MultiFrameAggregationStage()\n{\n}\n\nvoid MultiFrameAggregationStage::onContextInit(AbstractGLContext * context)\n{\n setupGeometry();\n setupProgram();\n}\n\nvoid MultiFrameAggregationStage::onProcess(AbstractGLContext * context)\n{\n gl::glViewport(\n (*viewport).x,\n (*viewport).y,\n (*viewport).z,\n (*viewport).w\n );\n\n globjects::Framebuffer * fbo = *aggregationFBO;\n if (!fbo) fbo = globjects::Framebuffer::defaultFBO();\n fbo->bind(gl::GL_FRAMEBUFFER);\n\n (*texture)->bindActive(0);\n gl::glBlendColor(0.0f, 0.0f, 0.0f, *aggregationFactor);\n gl::glBlendFunc(gl::GL_CONSTANT_ALPHA, gl::GL_ONE_MINUS_CONSTANT_ALPHA);\n gl::glBlendEquation(gl::GL_FUNC_ADD);\n gl::glEnable(gl::GL_BLEND);\n gl::glDisable(gl::GL_DEPTH_TEST);\n\n m_program->use();\n m_vao->drawArrays(gl::GL_TRIANGLE_STRIP, 0, 4);\n m_program->release();\n\n gl::glDisable(gl::GL_BLEND);\n gl::glEnable(gl::GL_DEPTH_TEST);\n\n aggregatedFBO.setValue(*aggregationFBO);\n}\n\nvoid MultiFrameAggregationStage::setupGeometry()\n{\n m_vao = new globjects::VertexArray;\n m_vertexBuffer = new globjects::Buffer();\n m_vertexBuffer->setData(s_vertices, gl::GL_STATIC_DRAW);\n\n auto binding = m_vao->binding(0);\n binding->setAttribute(0);\n binding->setBuffer(m_vertexBuffer, 0, sizeof(glm::vec2));\n binding->setFormat(2, gl::GL_FLOAT, gl::GL_FALSE, 0);\n m_vao->enable(0);\n}\n\nvoid MultiFrameAggregationStage::setupProgram()\n{\n globjects::StringTemplate * vertexShaderSource = new globjects::StringTemplate(new globjects::StaticStringSource(s_vertexShader ));\n globjects::StringTemplate * fragmentShaderSource = new globjects::StringTemplate(new globjects::StaticStringSource(s_fragmentShader));\n\n#ifdef __APPLE__\n vertexShaderSource ->replace(\"#version 140\", \"#version 150\");\n fragmentShaderSource->replace(\"#version 140\", \"#version 150\");\n#endif\n\n m_vertexShader = new globjects::Shader(gl::GL_VERTEX_SHADER, vertexShaderSource);\n m_fragmentShader = new globjects::Shader(gl::GL_FRAGMENT_SHADER, fragmentShaderSource);\n m_program = new globjects::Program();\n m_program->attach(m_vertexShader, m_fragmentShader);\n\n m_program->setUniform(\"tex\", 0);\n}\n\n\n} \/\/ namespace gloperate\n<commit_msg>Fix black bottom & left borders<commit_after>\n#include <gloperate\/stages\/multiframe\/MultiFrameAggregationStage.h>\n\n#include <globjects\/base\/StringTemplate.h>\n#include <globjects\/base\/StaticStringSource.h>\n#include <globjects\/VertexArray.h>\n#include <globjects\/VertexAttributeBinding.h>\n#include <globjects\/Framebuffer.h>\n#include <globjects\/globjects.h>\n\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/enum.h>\n\nstatic const std::array<glm::vec2, 4> s_vertices { {\n glm::vec2( +1.f, -1.f ),\n glm::vec2( +1.f, +1.f ),\n glm::vec2( -1.f, -1.f ),\n glm::vec2( -1.f, +1.f ) } };\n\nstatic const char * s_vertexShader = R\"(\n #version 140\n #extension GL_ARB_explicit_attrib_location : require\n\n layout (location = 0) in vec2 a_vertex;\n out vec2 v_uv;\n\n void main()\n {\n v_uv = a_vertex * 0.5 + 0.5;\n gl_Position = vec4(a_vertex, 0.0, 1.0);\n }\n)\";\n\nstatic const char * s_fragmentShader = R\"(\n #version 140\n #extension GL_ARB_explicit_attrib_location : require\n\n uniform sampler2D tex;\n\n layout (location = 0) out vec4 fragColor;\n\n in vec2 v_uv;\n\n void main()\n {\n fragColor = texture(tex, v_uv);\n }\n)\";\n\n\nnamespace gloperate\n{\n\n\nCPPEXPOSE_COMPONENT(MultiFrameAggregationStage, gloperate::Stage)\n\n\nMultiFrameAggregationStage::MultiFrameAggregationStage(Environment * environment, const std::string & name)\n: Stage(environment, name)\n, aggregationFBO(\"aggregationFBO\", this)\n, texture(\"texture\", this)\n, textureRerendered(\"textureRerendered\", this)\n, viewport(\"viewport\", this)\n, aggregationFactor(\"aggregationFactor\", this)\n, aggregatedFBO(\"aggregatedFBO\", this)\n{\n}\n\nMultiFrameAggregationStage::~MultiFrameAggregationStage()\n{\n}\n\nvoid MultiFrameAggregationStage::onContextInit(AbstractGLContext * context)\n{\n setupGeometry();\n setupProgram();\n}\n\nvoid MultiFrameAggregationStage::onProcess(AbstractGLContext * context)\n{\n gl::glViewport(\n 0, \/\/ Origin (0,0) because content was already shifted in main render pass\n 0, \/\/ Applying the origin again would shift the result again\n (*viewport).z,\n (*viewport).w\n );\n\n globjects::Framebuffer * fbo = *aggregationFBO;\n if (!fbo) fbo = globjects::Framebuffer::defaultFBO();\n fbo->bind(gl::GL_FRAMEBUFFER);\n\n (*texture)->bindActive(0);\n gl::glBlendColor(0.0f, 0.0f, 0.0f, *aggregationFactor);\n gl::glBlendFunc(gl::GL_CONSTANT_ALPHA, gl::GL_ONE_MINUS_CONSTANT_ALPHA);\n gl::glBlendEquation(gl::GL_FUNC_ADD);\n gl::glEnable(gl::GL_BLEND);\n gl::glDisable(gl::GL_DEPTH_TEST);\n\n m_program->use();\n m_vao->drawArrays(gl::GL_TRIANGLE_STRIP, 0, 4);\n m_program->release();\n\n gl::glDisable(gl::GL_BLEND);\n gl::glEnable(gl::GL_DEPTH_TEST);\n\n aggregatedFBO.setValue(*aggregationFBO);\n}\n\nvoid MultiFrameAggregationStage::setupGeometry()\n{\n m_vao = new globjects::VertexArray;\n m_vertexBuffer = new globjects::Buffer();\n m_vertexBuffer->setData(s_vertices, gl::GL_STATIC_DRAW);\n\n auto binding = m_vao->binding(0);\n binding->setAttribute(0);\n binding->setBuffer(m_vertexBuffer, 0, sizeof(glm::vec2));\n binding->setFormat(2, gl::GL_FLOAT, gl::GL_FALSE, 0);\n m_vao->enable(0);\n}\n\nvoid MultiFrameAggregationStage::setupProgram()\n{\n globjects::StringTemplate * vertexShaderSource = new globjects::StringTemplate(new globjects::StaticStringSource(s_vertexShader ));\n globjects::StringTemplate * fragmentShaderSource = new globjects::StringTemplate(new globjects::StaticStringSource(s_fragmentShader));\n\n#ifdef __APPLE__\n vertexShaderSource ->replace(\"#version 140\", \"#version 150\");\n fragmentShaderSource->replace(\"#version 140\", \"#version 150\");\n#endif\n\n m_vertexShader = new globjects::Shader(gl::GL_VERTEX_SHADER, vertexShaderSource);\n m_fragmentShader = new globjects::Shader(gl::GL_FRAGMENT_SHADER, fragmentShaderSource);\n m_program = new globjects::Program();\n m_program->attach(m_vertexShader, m_fragmentShader);\n\n m_program->setUniform(\"tex\", 0);\n}\n\n\n} \/\/ namespace gloperate\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Decl.cpp - Declaration AST Node Implementation -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Chris Lattner and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Decl class and subclasses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/Lex\/IdentifierTable.h\"\nusing namespace clang;\n\n\/\/ temporary statistics gathering\nstatic unsigned nFuncs = 0;\nstatic unsigned nBlockVars = 0;\nstatic unsigned nFileVars = 0;\nstatic unsigned nParmVars = 0;\nstatic unsigned nSUC = 0;\nstatic unsigned nEnumConst = 0;\nstatic unsigned nEnumDecls = 0;\nstatic unsigned nTypedef = 0;\nstatic unsigned nFieldDecls = 0;\nstatic unsigned nInterfaceDecls = 0;\nstatic bool StatSwitch = false;\n\nconst char *Decl::getDeclKindName() {\n switch (DeclKind) {\n default: assert(0 && \"Unknown decl kind!\");\n case Typedef:\n return \"Typedef\";\n case Function:\n return \"Function\";\n case BlockVariable:\n return \"BlockVariable\";\n case FileVariable:\n return \"FileVariable\";\n case ParmVariable:\n return \"ParmVariable\";\n case EnumConstant:\n return \"EnumConstant\";\n case ObjcInterface:\n return \"ObjcInterface\";\n case ObjcClass:\n return \"ObjcClass\";\n case ObjcMethod:\n return \"ObjcMethod\";\n case ObjcProtoMethod:\n return \"ObjcProtoMethod\";\n case ObjcProtocol:\n return \"ObjcProtocol\";\n case Struct:\n return \"Struct\";\n case Union:\n return \"Union\";\n case Class:\n return \"Class\";\n case Enum:\n return \"Enum\";\n }\n}\n\nbool Decl::CollectingStats(bool enable) {\n if (enable) StatSwitch = true;\n\treturn StatSwitch;\n}\n\nvoid Decl::PrintStats() {\n fprintf(stderr, \"*** Decl Stats:\\n\");\n fprintf(stderr, \" %d decls total.\\n\", \n\t int(nFuncs+nBlockVars+nFileVars+nParmVars+nFieldDecls+nSUC+\n\t nEnumDecls+nEnumConst+nTypedef));\n fprintf(stderr, \" %d function decls, %d each (%d bytes)\\n\", \n\t nFuncs, (int)sizeof(FunctionDecl), int(nFuncs*sizeof(FunctionDecl)));\n fprintf(stderr, \" %d block variable decls, %d each (%d bytes)\\n\", \n\t nBlockVars, (int)sizeof(BlockVarDecl), \n\t int(nBlockVars*sizeof(BlockVarDecl)));\n fprintf(stderr, \" %d file variable decls, %d each (%d bytes)\\n\", \n\t nFileVars, (int)sizeof(FileVarDecl), \n\t int(nFileVars*sizeof(FileVarDecl)));\n fprintf(stderr, \" %d parameter variable decls, %d each (%d bytes)\\n\", \n\t nParmVars, (int)sizeof(ParmVarDecl),\n\t int(nParmVars*sizeof(ParmVarDecl)));\n fprintf(stderr, \" %d field decls, %d each (%d bytes)\\n\", \n\t nFieldDecls, (int)sizeof(FieldDecl),\n\t int(nFieldDecls*sizeof(FieldDecl)));\n fprintf(stderr, \" %d struct\/union\/class decls, %d each (%d bytes)\\n\", \n\t nSUC, (int)sizeof(RecordDecl),\n\t int(nSUC*sizeof(RecordDecl)));\n fprintf(stderr, \" %d enum decls, %d each (%d bytes)\\n\", \n\t nEnumDecls, (int)sizeof(EnumDecl), \n\t int(nEnumDecls*sizeof(EnumDecl)));\n fprintf(stderr, \" %d enum constant decls, %d each (%d bytes)\\n\", \n\t nEnumConst, (int)sizeof(EnumConstantDecl),\n\t int(nEnumConst*sizeof(EnumConstantDecl)));\n fprintf(stderr, \" %d typedef decls, %d each (%d bytes)\\n\", \n\t nTypedef, (int)sizeof(TypedefDecl),int(nTypedef*sizeof(TypedefDecl)));\n fprintf(stderr, \"Total bytes = %d\\n\", \n\t int(nFuncs*sizeof(FunctionDecl)+nBlockVars*sizeof(BlockVarDecl)+\n\t nFileVars*sizeof(FileVarDecl)+nParmVars*sizeof(ParmVarDecl)+\n\t nFieldDecls*sizeof(FieldDecl)+nSUC*sizeof(RecordDecl)+\n\t nEnumDecls*sizeof(EnumDecl)+nEnumConst*sizeof(EnumConstantDecl)+\n\t nTypedef*sizeof(TypedefDecl)));\n}\n\nvoid Decl::addDeclKind(const Kind k) {\n switch (k) {\n case Typedef:\n nTypedef++;\n break;\n case Function:\n nFuncs++;\n break;\n case BlockVariable:\n nBlockVars++;\n break;\n case FileVariable:\n nFileVars++;\n break;\n case ParmVariable:\n nParmVars++;\n break;\n case EnumConstant:\n nEnumConst++;\n break;\n case Field:\n nFieldDecls++;\n break;\n case Struct:\n case Union:\n case Class:\n nSUC++;\n break;\n case Enum:\n nEnumDecls++;\n break;\n case ObjcInterface:\n nInterfaceDecls++;\n break;\n }\n}\n\n\/\/ Out-of-line virtual method providing a home for Decl.\nDecl::~Decl() {\n}\n\nconst char *FieldDecl::getName() const {\n if (const IdentifierInfo *II = getIdentifier())\n return II->getName();\n return \"\";\n}\n\nconst char *ScopedDecl::getName() const {\n if (const IdentifierInfo *II = getIdentifier())\n return II->getName();\n return \"\";\n}\n\n\nFunctionDecl::~FunctionDecl() {\n delete[] ParamInfo;\n}\n\nunsigned FunctionDecl::getNumParams() const {\n return cast<FunctionTypeProto>(getType().getTypePtr())->getNumArgs();\n}\n\nvoid FunctionDecl::setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) {\n assert(ParamInfo == 0 && \"Already has param info!\");\n assert(NumParams == getNumParams() && \"Parameter count mismatch!\");\n \n \/\/ Zero params -> null pointer.\n if (NumParams) {\n ParamInfo = new ParmVarDecl*[NumParams];\n memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);\n }\n}\n\n\n\/\/\/ defineBody - When created, RecordDecl's correspond to a forward declared\n\/\/\/ record. This method is used to mark the decl as being defined, with the\n\/\/\/ specified contents.\nvoid RecordDecl::defineBody(FieldDecl **members, unsigned numMembers) {\n assert(!isDefinition() && \"Cannot redefine record!\");\n setDefinition(true);\n NumMembers = numMembers;\n if (numMembers) {\n Members = new FieldDecl*[numMembers];\n memcpy(Members, members, numMembers*sizeof(Decl*));\n }\n}\n\nFieldDecl* RecordDecl::getMember(IdentifierInfo *name) {\n if (Members == 0 || NumMembers < 0)\n return 0;\n\t\n \/\/ linear search. When C++ classes come along, will likely need to revisit.\n for (int i = 0; i < NumMembers; ++i) {\n if (Members[i]->getIdentifier() == name)\n return Members[i];\n }\n return 0;\n}\n\nvoid ObjcMethodDecl::setMethodParams(ParmVarDecl **NewParamInfo, \n\t\t unsigned NumParams) {\n assert(ParamInfo == 0 && \"Already has param info!\");\n\n \/\/ Zero params -> null pointer.\n if (NumParams) {\n ParamInfo = new ParmVarDecl*[NumParams];\n memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);\n NumMethodParams = NumParams;\n }\n}\n\nObjcMethodDecl::~ObjcMethodDecl() {\n delete[] ParamInfo;\n}\n\n\/\/\/ ObjcAddInstanceVariablesToClass - Inserts instance variables\n\/\/\/ into ObjcInterfaceDecl's fields.\n\/\/\/\nvoid ObjcInterfaceDecl::ObjcAddInstanceVariablesToClass(ObjcIvarDecl **ivars,\n\t\t\t\t\t \t\tunsigned numIvars) {\n NumIvars = numIvars;\n if (numIvars) {\n Ivars = new ObjcIvarDecl*[numIvars];\n memcpy(Ivars, ivars, numIvars*sizeof(ObjcIvarDecl*));\n }\n}\n\n\/\/\/ addObjcMethods - Insert instance and methods declarations into\n\/\/\/ ObjcInterfaceDecl's InsMethods and ClsMethods fields.\n\/\/\/\nvoid ObjcInterfaceDecl::ObjcAddMethods(ObjcMethodDecl **insMethods, \n\t\t\t\t unsigned numInsMembers,\n ObjcMethodDecl **clsMethods,\n unsigned numClsMembers) {\n NumInsMethods = numInsMembers;\n if (numInsMembers) {\n InsMethods = new ObjcMethodDecl*[numInsMembers];\n memcpy(InsMethods, insMethods, numInsMembers*sizeof(ObjcMethodDecl*));\n }\n NumClsMethods = numClsMembers;\n if (numClsMembers) {\n ClsMethods = new ObjcMethodDecl*[numClsMembers];\n memcpy(ClsMethods, clsMethods, numClsMembers*sizeof(ObjcMethodDecl*));\n }\n}\n\n<commit_msg>decl counting isn't implemented yet for objc. -stats probably crashes for it. Patch by Justin Handville<commit_after>\/\/===--- Decl.cpp - Declaration AST Node Implementation -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Chris Lattner and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Decl class and subclasses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/Lex\/IdentifierTable.h\"\nusing namespace clang;\n\n\/\/ temporary statistics gathering\nstatic unsigned nFuncs = 0;\nstatic unsigned nBlockVars = 0;\nstatic unsigned nFileVars = 0;\nstatic unsigned nParmVars = 0;\nstatic unsigned nSUC = 0;\nstatic unsigned nEnumConst = 0;\nstatic unsigned nEnumDecls = 0;\nstatic unsigned nTypedef = 0;\nstatic unsigned nFieldDecls = 0;\nstatic unsigned nInterfaceDecls = 0;\nstatic bool StatSwitch = false;\n\nconst char *Decl::getDeclKindName() {\n switch (DeclKind) {\n default: assert(0 && \"Unknown decl kind!\");\n case Typedef:\n return \"Typedef\";\n case Function:\n return \"Function\";\n case BlockVariable:\n return \"BlockVariable\";\n case FileVariable:\n return \"FileVariable\";\n case ParmVariable:\n return \"ParmVariable\";\n case EnumConstant:\n return \"EnumConstant\";\n case ObjcInterface:\n return \"ObjcInterface\";\n case ObjcClass:\n return \"ObjcClass\";\n case ObjcMethod:\n return \"ObjcMethod\";\n case ObjcProtoMethod:\n return \"ObjcProtoMethod\";\n case ObjcProtocol:\n return \"ObjcProtocol\";\n case Struct:\n return \"Struct\";\n case Union:\n return \"Union\";\n case Class:\n return \"Class\";\n case Enum:\n return \"Enum\";\n }\n}\n\nbool Decl::CollectingStats(bool enable) {\n if (enable) StatSwitch = true;\n\treturn StatSwitch;\n}\n\nvoid Decl::PrintStats() {\n fprintf(stderr, \"*** Decl Stats:\\n\");\n fprintf(stderr, \" %d decls total.\\n\", \n\t int(nFuncs+nBlockVars+nFileVars+nParmVars+nFieldDecls+nSUC+\n\t nEnumDecls+nEnumConst+nTypedef));\n fprintf(stderr, \" %d function decls, %d each (%d bytes)\\n\", \n\t nFuncs, (int)sizeof(FunctionDecl), int(nFuncs*sizeof(FunctionDecl)));\n fprintf(stderr, \" %d block variable decls, %d each (%d bytes)\\n\", \n\t nBlockVars, (int)sizeof(BlockVarDecl), \n\t int(nBlockVars*sizeof(BlockVarDecl)));\n fprintf(stderr, \" %d file variable decls, %d each (%d bytes)\\n\", \n\t nFileVars, (int)sizeof(FileVarDecl), \n\t int(nFileVars*sizeof(FileVarDecl)));\n fprintf(stderr, \" %d parameter variable decls, %d each (%d bytes)\\n\", \n\t nParmVars, (int)sizeof(ParmVarDecl),\n\t int(nParmVars*sizeof(ParmVarDecl)));\n fprintf(stderr, \" %d field decls, %d each (%d bytes)\\n\", \n\t nFieldDecls, (int)sizeof(FieldDecl),\n\t int(nFieldDecls*sizeof(FieldDecl)));\n fprintf(stderr, \" %d struct\/union\/class decls, %d each (%d bytes)\\n\", \n\t nSUC, (int)sizeof(RecordDecl),\n\t int(nSUC*sizeof(RecordDecl)));\n fprintf(stderr, \" %d enum decls, %d each (%d bytes)\\n\", \n\t nEnumDecls, (int)sizeof(EnumDecl), \n\t int(nEnumDecls*sizeof(EnumDecl)));\n fprintf(stderr, \" %d enum constant decls, %d each (%d bytes)\\n\", \n\t nEnumConst, (int)sizeof(EnumConstantDecl),\n\t int(nEnumConst*sizeof(EnumConstantDecl)));\n fprintf(stderr, \" %d typedef decls, %d each (%d bytes)\\n\", \n\t nTypedef, (int)sizeof(TypedefDecl),int(nTypedef*sizeof(TypedefDecl)));\n fprintf(stderr, \"Total bytes = %d\\n\", \n\t int(nFuncs*sizeof(FunctionDecl)+nBlockVars*sizeof(BlockVarDecl)+\n\t nFileVars*sizeof(FileVarDecl)+nParmVars*sizeof(ParmVarDecl)+\n\t nFieldDecls*sizeof(FieldDecl)+nSUC*sizeof(RecordDecl)+\n\t nEnumDecls*sizeof(EnumDecl)+nEnumConst*sizeof(EnumConstantDecl)+\n\t nTypedef*sizeof(TypedefDecl)));\n}\n\nvoid Decl::addDeclKind(const Kind k) {\n switch (k) {\n case Typedef:\n nTypedef++;\n break;\n case Function:\n nFuncs++;\n break;\n case BlockVariable:\n nBlockVars++;\n break;\n case FileVariable:\n nFileVars++;\n break;\n case ParmVariable:\n nParmVars++;\n break;\n case EnumConstant:\n nEnumConst++;\n break;\n case Field:\n nFieldDecls++;\n break;\n case Struct:\n case Union:\n case Class:\n nSUC++;\n break;\n case Enum:\n nEnumDecls++;\n break;\n case ObjcInterface:\n nInterfaceDecls++;\n break;\n case ObjcClass:\n case ObjcMethod:\n case ObjcProtoMethod:\n case ObjcProtocol:\n case ObjcIvar:\n assert(0 && \"FIXME: Count these decls!\");\n break;\n }\n}\n\n\/\/ Out-of-line virtual method providing a home for Decl.\nDecl::~Decl() {\n}\n\nconst char *FieldDecl::getName() const {\n if (const IdentifierInfo *II = getIdentifier())\n return II->getName();\n return \"\";\n}\n\nconst char *ScopedDecl::getName() const {\n if (const IdentifierInfo *II = getIdentifier())\n return II->getName();\n return \"\";\n}\n\n\nFunctionDecl::~FunctionDecl() {\n delete[] ParamInfo;\n}\n\nunsigned FunctionDecl::getNumParams() const {\n return cast<FunctionTypeProto>(getType().getTypePtr())->getNumArgs();\n}\n\nvoid FunctionDecl::setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) {\n assert(ParamInfo == 0 && \"Already has param info!\");\n assert(NumParams == getNumParams() && \"Parameter count mismatch!\");\n \n \/\/ Zero params -> null pointer.\n if (NumParams) {\n ParamInfo = new ParmVarDecl*[NumParams];\n memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);\n }\n}\n\n\n\/\/\/ defineBody - When created, RecordDecl's correspond to a forward declared\n\/\/\/ record. This method is used to mark the decl as being defined, with the\n\/\/\/ specified contents.\nvoid RecordDecl::defineBody(FieldDecl **members, unsigned numMembers) {\n assert(!isDefinition() && \"Cannot redefine record!\");\n setDefinition(true);\n NumMembers = numMembers;\n if (numMembers) {\n Members = new FieldDecl*[numMembers];\n memcpy(Members, members, numMembers*sizeof(Decl*));\n }\n}\n\nFieldDecl* RecordDecl::getMember(IdentifierInfo *name) {\n if (Members == 0 || NumMembers < 0)\n return 0;\n\t\n \/\/ linear search. When C++ classes come along, will likely need to revisit.\n for (int i = 0; i < NumMembers; ++i) {\n if (Members[i]->getIdentifier() == name)\n return Members[i];\n }\n return 0;\n}\n\nvoid ObjcMethodDecl::setMethodParams(ParmVarDecl **NewParamInfo, \n\t\t unsigned NumParams) {\n assert(ParamInfo == 0 && \"Already has param info!\");\n\n \/\/ Zero params -> null pointer.\n if (NumParams) {\n ParamInfo = new ParmVarDecl*[NumParams];\n memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);\n NumMethodParams = NumParams;\n }\n}\n\nObjcMethodDecl::~ObjcMethodDecl() {\n delete[] ParamInfo;\n}\n\n\/\/\/ ObjcAddInstanceVariablesToClass - Inserts instance variables\n\/\/\/ into ObjcInterfaceDecl's fields.\n\/\/\/\nvoid ObjcInterfaceDecl::ObjcAddInstanceVariablesToClass(ObjcIvarDecl **ivars,\n\t\t\t\t\t \t\tunsigned numIvars) {\n NumIvars = numIvars;\n if (numIvars) {\n Ivars = new ObjcIvarDecl*[numIvars];\n memcpy(Ivars, ivars, numIvars*sizeof(ObjcIvarDecl*));\n }\n}\n\n\/\/\/ addObjcMethods - Insert instance and methods declarations into\n\/\/\/ ObjcInterfaceDecl's InsMethods and ClsMethods fields.\n\/\/\/\nvoid ObjcInterfaceDecl::ObjcAddMethods(ObjcMethodDecl **insMethods, \n\t\t\t\t unsigned numInsMembers,\n ObjcMethodDecl **clsMethods,\n unsigned numClsMembers) {\n NumInsMethods = numInsMembers;\n if (numInsMembers) {\n InsMethods = new ObjcMethodDecl*[numInsMembers];\n memcpy(InsMethods, insMethods, numInsMembers*sizeof(ObjcMethodDecl*));\n }\n NumClsMethods = numClsMembers;\n if (numClsMembers) {\n ClsMethods = new ObjcMethodDecl*[numClsMembers];\n memcpy(ClsMethods, clsMethods, numClsMembers*sizeof(ObjcMethodDecl*));\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ AppOnMap.cpp\n\/\/ ExampleApp\n\/\/\n\n#include \"AppOnMap.h\"\n#include \"EegeoWorld.h\"\n#include \"GlobeCameraTouchController.h\"\n#include \"RenderCamera.h\"\n#include \"GlobeCameraController.h\"\n#include \"GlobeCameraInterestPointProvider.h\"\n#include \"GlobeCameraController.h\"\n#include \"CameraHelpers.h\"\n#include \"WeatherController.h\"\n#include \"NativeUIFactories.h\"\n\n#include \"DebugSphereExample.h\"\n#include \"ScreenUnprojectExample.h\"\n#include \"LoadModelExample.h\"\n#include \"EnvironmentNotifierExample.h\"\n#include \"WebRequestExample.h\"\n#include \"FileIOExample.h\"\n#include \"NavigationGraphExample.h\"\n#include \"ModifiedRenderingExample.h\"\n#include \"ToggleTrafficExample.h\"\n#include \"ResourceSpatialQueryExample.h\"\n#include \"EnvironmentFlatteningExample.h\"\n#include \"SearchExample.h\"\n#include \"KeyboardInputExample.h\"\n#include \"PODAnimationExample.h\"\n#include \"Pick3DObjectExample.h\"\n#include \"ScreenPickExample.h\"\n\nMyApp::MyApp(Eegeo::Camera::GlobeCamera::GlobeCameraInterestPointProvider& globeCameraInterestPointProvider,\n ExampleTypes::Examples selectedExample)\n: m_globeCameraController(NULL)\n, m_cameraTouchController(NULL)\n, m_globeCameraInterestPointProvider(globeCameraInterestPointProvider)\n, m_selectedExampleType(selectedExample)\n, pExample(NULL)\n{\n Eegeo_ASSERT(&m_globeCameraInterestPointProvider != NULL);\n}\n\nMyApp::~MyApp()\n{\n pExample->Suspend();\n delete pExample;\n delete m_globeCameraController;\n delete m_cameraTouchController;\n}\n\nvoid MyApp::OnStart ()\n{\n Eegeo_ASSERT(&World() != NULL);\n \n Eegeo::EegeoWorld& eegeoWorld = World();\n \n \n Eegeo::Camera::GlobeCamera::GlobeCameraTouchControllerConfiguration touchControllerConfig = Eegeo::Camera::GlobeCamera::GlobeCameraTouchControllerConfiguration::CreateDefault();\n \n \/\/ override default configuration to enable two-finger pan gesture to control additional camera pitch\n touchControllerConfig.tiltEnabled = true;\n \n m_cameraTouchController = new Eegeo::Camera::GlobeCamera::GlobeCameraTouchController(touchControllerConfig);\n \n const bool useLowSpecSettings = false;\n Eegeo::Camera::GlobeCamera::GlobeCameraControllerConfiguration globeCameraControllerConfig = Eegeo::Camera::GlobeCamera::GlobeCameraControllerConfiguration::CreateDefault(useLowSpecSettings);\n\n m_globeCameraController = new Eegeo::Camera::GlobeCamera::GlobeCameraController(eegeoWorld.GetTerrainHeightProvider(),\n eegeoWorld.GetEnvironmentFlatteningService(),\n eegeoWorld.GetResourceCeilingProvider(),\n *m_cameraTouchController,\n globeCameraControllerConfig);\n \n\n \n Eegeo::Camera::RenderCamera* renderCamera = m_globeCameraController->GetCamera();\n const Eegeo::Rendering::RenderContext& renderContext = eegeoWorld.GetRenderContext();\n renderCamera->SetViewport(0.f, 0.f, renderContext.GetScreenWidth(), renderContext.GetScreenHeight());\n eegeoWorld.SetCamera(renderCamera);\n \n m_globeCameraInterestPointProvider.SetGlobeCamera(m_globeCameraController);\n\n float interestPointLatitudeDegrees = 37.7858f;\n float interestPointLongitudeDegrees = -122.401f;\n float interestPointAltitudeMeters = 2.7;\n \n Eegeo::Space::LatLongAltitude location = Eegeo::Space::LatLongAltitude(interestPointLatitudeDegrees,\n interestPointLongitudeDegrees,\n interestPointAltitudeMeters,\n Eegeo::Space::LatLongUnits::Degrees);\n \n \n \n float cameraControllerOrientationDegrees = 0.0f;\n float cameraControllerDistanceFromInterestPointMeters = 1781.0f;\n \n Eegeo::Space::EcefTangentBasis cameraInterestBasis;\n Eegeo::Camera::CameraHelpers::EcefTangentBasisFromPointAndHeading(location.ToECEF(), cameraControllerOrientationDegrees, cameraInterestBasis);\n \n m_globeCameraController->SetView(cameraInterestBasis, cameraControllerDistanceFromInterestPointMeters);\n \n eegeoWorld.GetWeatherController().SetWeather(Eegeo::Weather::Sunny, 1.0f);\n \n Eegeo::Search::Service::SearchService* searchService = NULL;\n \n if (eegeoWorld.IsSearchServiceAvailable())\n {\n searchService = &eegeoWorld.GetSearchService();\n }\n \n pExample = CreateExample(m_selectedExampleType,\n eegeoWorld.GetRenderContext(),\n location,\n eegeoWorld.GetCameraProvider(),\n *m_globeCameraController,\n *m_cameraTouchController,\n eegeoWorld.GetTerrainHeightProvider(),\n eegeoWorld.GetTextureLoader(),\n eegeoWorld.GetFileIO(),\n eegeoWorld.GetTerrainStreaming(),\n eegeoWorld.GetWebRequestFactory(),\n eegeoWorld.GetNavigationGraphRepository(),\n eegeoWorld.GetBuildingMeshPool(),\n eegeoWorld.GetShadowMeshPool(),\n eegeoWorld.GetStreamingVolume(),\n eegeoWorld.GetGlobalLighting(),\n eegeoWorld.GetGlobalFogging(),\n eegeoWorld.GetTrafficSimulation(),\n eegeoWorld.GetResourceSpatialQueryService(),\n eegeoWorld.GetEnvironmentFlatteningService(),\n searchService,\n eegeoWorld.GetNativeUIFactories(),\n eegeoWorld.GetInterestPointProvider());\n \n pExample->Start();\n}\n\nvoid MyApp::Update (float dt)\n{\n Eegeo::EegeoWorld& eegeoWorld = World();\n \n eegeoWorld.EarlyUpdate(dt);\n \n m_cameraTouchController->Update(dt);\n m_globeCameraController->Update(dt);\n \n eegeoWorld.Update(dt);\n pExample->Update();\n}\n\nvoid MyApp::Draw (float dt)\n{\n Eegeo::Rendering::GLState& glState = World().GetRenderContext().GetGLState();\n glState.ClearColor(0.8f, 0.8f, 0.8f, 1.f);\n World().Draw(dt);\n pExample->Draw();\n}\n\nvoid MyApp::JumpTo(double latitudeDegrees, double longitudeDegrees, double altitudeMetres, double headingDegrees, double distanceToInterestMetres)\n{\n Eegeo::dv3 interestPoint = Eegeo::Space::LatLongAltitude(latitudeDegrees, longitudeDegrees, altitudeMetres, Eegeo::Space::LatLongUnits::Degrees).ToECEF();\n \n Eegeo::Space::EcefTangentBasis interestBasis;\n \n Eegeo::Camera::CameraHelpers::EcefTangentBasisFromPointAndHeading(interestPoint, headingDegrees, interestBasis);\n \n m_globeCameraController->SetView(interestBasis, distanceToInterestMetres);\n}\n\nExamples::IExample* MyApp::CreateExample(ExampleTypes::Examples example,\n Eegeo::Rendering::RenderContext& renderContext,\n Eegeo::Space::LatLongAltitude interestLocation,\n Eegeo::Camera::ICameraProvider& cameraProvider,\n Eegeo::Camera::GlobeCamera::GlobeCameraController& globeCameraController,\n Eegeo::ITouchController& cameraTouchController,\n Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,\n Eegeo::Helpers::ITextureFileLoader& textureLoader,\n Eegeo::Helpers::IFileIO& fileIO,\n Eegeo::Resources::Terrain::TerrainStreaming& terrainStreaming,\n Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,\n Eegeo::Resources::Roads::Navigation::NavigationGraphRepository& navigationGraphs,\n Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,\n Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool,\n Eegeo::Streaming::IStreamingVolume& visibleVolume,\n Eegeo::Lighting::GlobalLighting& lighting,\n Eegeo::Lighting::GlobalFogging& fogging,\n Eegeo::Traffic::TrafficSimulation& trafficSimulation,\n Eegeo::Resources::ResourceSpatialQueryService& resourceSpatialQueryService,\n Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,\n Eegeo::Search::Service::SearchService* searchService,\n Eegeo::UI::NativeUIFactories& nativeInputFactories,\n Eegeo::Location::IInterestPointProvider& interestPointProvider)\n{\n switch(example)\n {\n case ExampleTypes::LoadModel:\n return new Examples::LoadModelExample(renderContext,\n interestLocation,\n fileIO,\n textureLoader,\n fogging);\n case ExampleTypes::ScreenUnproject:\n case ExampleTypes::TerrainHeightQuery:\n return new Examples::ScreenUnprojectExample(renderContext,\n cameraProvider,\n terrainHeightProvider);\n \n case ExampleTypes::ScreenPick:\n return new Examples::ScreenPickExample(renderContext,\n cameraProvider,\n terrainHeightProvider);\n\n case ExampleTypes::DebugSphere:\n return new Examples::DebugSphereExample(renderContext,\n interestLocation);\n case ExampleTypes::EnvironmentNotifier:\n return new Examples::EnvironmentNotifierExample(renderContext,\n terrainStreaming);\n case ExampleTypes::WebRequest:\n return new Examples::WebRequestExample(webRequestFactory);\n \n case ExampleTypes::FileIO:\n return new Examples::FileIOExample(fileIO);\n \n case ExampleTypes::NavigationGraph:\n return new Examples::NavigationGraphExample(renderContext,\n navigationGraphs);\n \n case ExampleTypes::ModifiedRendering:\n return new Examples::ModifiedRenderingExample(renderContext,\n cameraProvider,\n interestPointProvider,\n visibleVolume,\n lighting,\n buildingPool,\n shadowPool);\n \n case ExampleTypes::ToggleTraffic:\n return new Examples::ToggleTrafficExample(trafficSimulation);\n \n case ExampleTypes::ResourceSpatialQuery:\n return new Examples::ResourceSpatialQueryExample(resourceSpatialQueryService,\n interestPointProvider);\n \n case ExampleTypes::EnvironmentFlattening:\n return new Examples::EnvironmentFlatteningExample(environmentFlatteningService);\n \n case ExampleTypes::Search:\n Eegeo_ASSERT(searchService != NULL, \"Cannot run Search example, you must set up here.com Credentials in ViewController.mm\");\n return new Examples::SearchExample(*searchService, interestPointProvider);\n \n case ExampleTypes::KeyboardInput:\n return new Examples::KeyboardInputExample(nativeInputFactories.IKeyboardInputFactory());\n \n case ExampleTypes::PODAnimation:\n return new Examples::PODAnimationExample(renderContext,\n fileIO,\n textureLoader,\n fogging);\n case ExampleTypes::Pick3DObject:\n return new Examples::Pick3DObjectExample(renderContext,\n interestLocation,\n cameraProvider);\n \n \n }\n}\n\n\nvoid MyApp::Event_TouchRotate(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate(data))\n {\n m_cameraTouchController->Event_TouchRotate(data);\n }\n}\n\nvoid MyApp::Event_TouchRotate_Start(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate_Start(data))\n {\n m_cameraTouchController->Event_TouchRotate_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchRotate_End(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate_End(data))\n {\n m_cameraTouchController->Event_TouchRotate_End(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch(data))\n {\n m_cameraTouchController->Event_TouchPinch(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch_Start(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch_Start(data))\n {\n m_cameraTouchController->Event_TouchPinch_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch_End(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch_End(data))\n {\n m_cameraTouchController->Event_TouchPinch_End(data);\n }\n}\n\nvoid MyApp::Event_TouchPan(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan(data))\n {\n m_cameraTouchController->Event_TouchPan(data);\n }\n}\n\nvoid MyApp::Event_TouchPan_Start(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan_Start(data))\n {\n m_cameraTouchController->Event_TouchPan_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchPan_End(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan_End(data))\n {\n m_cameraTouchController->Event_TouchPan_End(data);\n }\n}\n\nvoid MyApp::Event_TouchTap(const AppInterface::TapData& data)\n{\n if(!pExample->Event_TouchTap(data))\n {\n m_cameraTouchController->Event_TouchTap(data);\n }\n}\n\nvoid MyApp::Event_TouchDoubleTap(const AppInterface::TapData& data)\n{\n if(!pExample->Event_TouchDoubleTap(data))\n {\n m_cameraTouchController->Event_TouchDoubleTap(data);\n }\n}\n\nvoid MyApp::Event_TouchDown(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchDown(data))\n {\n m_cameraTouchController->Event_TouchDown(data);\n }\n}\n\nvoid MyApp::Event_TouchMove(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchMove(data))\n {\n m_cameraTouchController->Event_TouchMove(data);\n }\n}\n\nvoid MyApp::Event_TouchUp(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchUp(data))\n {\n m_cameraTouchController->Event_TouchUp(data);\n }\n}\n\n<commit_msg>Update lat long creation to use factory methods. Buddy: Malc B<commit_after>\/\/\n\/\/ AppOnMap.cpp\n\/\/ ExampleApp\n\/\/\n\n#include \"AppOnMap.h\"\n#include \"EegeoWorld.h\"\n#include \"GlobeCameraTouchController.h\"\n#include \"RenderCamera.h\"\n#include \"GlobeCameraController.h\"\n#include \"GlobeCameraInterestPointProvider.h\"\n#include \"GlobeCameraController.h\"\n#include \"CameraHelpers.h\"\n#include \"WeatherController.h\"\n#include \"NativeUIFactories.h\"\n\n#include \"DebugSphereExample.h\"\n#include \"ScreenUnprojectExample.h\"\n#include \"LoadModelExample.h\"\n#include \"EnvironmentNotifierExample.h\"\n#include \"WebRequestExample.h\"\n#include \"FileIOExample.h\"\n#include \"NavigationGraphExample.h\"\n#include \"ModifiedRenderingExample.h\"\n#include \"ToggleTrafficExample.h\"\n#include \"ResourceSpatialQueryExample.h\"\n#include \"EnvironmentFlatteningExample.h\"\n#include \"SearchExample.h\"\n#include \"KeyboardInputExample.h\"\n#include \"PODAnimationExample.h\"\n#include \"Pick3DObjectExample.h\"\n#include \"ScreenPickExample.h\"\n\nMyApp::MyApp(Eegeo::Camera::GlobeCamera::GlobeCameraInterestPointProvider& globeCameraInterestPointProvider,\n ExampleTypes::Examples selectedExample)\n: m_globeCameraController(NULL)\n, m_cameraTouchController(NULL)\n, m_globeCameraInterestPointProvider(globeCameraInterestPointProvider)\n, m_selectedExampleType(selectedExample)\n, pExample(NULL)\n{\n Eegeo_ASSERT(&m_globeCameraInterestPointProvider != NULL);\n}\n\nMyApp::~MyApp()\n{\n pExample->Suspend();\n delete pExample;\n delete m_globeCameraController;\n delete m_cameraTouchController;\n}\n\nvoid MyApp::OnStart ()\n{\n Eegeo_ASSERT(&World() != NULL);\n \n Eegeo::EegeoWorld& eegeoWorld = World();\n \n \n Eegeo::Camera::GlobeCamera::GlobeCameraTouchControllerConfiguration touchControllerConfig = Eegeo::Camera::GlobeCamera::GlobeCameraTouchControllerConfiguration::CreateDefault();\n \n \/\/ override default configuration to enable two-finger pan gesture to control additional camera pitch\n touchControllerConfig.tiltEnabled = true;\n \n m_cameraTouchController = new Eegeo::Camera::GlobeCamera::GlobeCameraTouchController(touchControllerConfig);\n \n const bool useLowSpecSettings = false;\n Eegeo::Camera::GlobeCamera::GlobeCameraControllerConfiguration globeCameraControllerConfig = Eegeo::Camera::GlobeCamera::GlobeCameraControllerConfiguration::CreateDefault(useLowSpecSettings);\n\n m_globeCameraController = new Eegeo::Camera::GlobeCamera::GlobeCameraController(eegeoWorld.GetTerrainHeightProvider(),\n eegeoWorld.GetEnvironmentFlatteningService(),\n eegeoWorld.GetResourceCeilingProvider(),\n *m_cameraTouchController,\n globeCameraControllerConfig);\n \n\n \n Eegeo::Camera::RenderCamera* renderCamera = m_globeCameraController->GetCamera();\n const Eegeo::Rendering::RenderContext& renderContext = eegeoWorld.GetRenderContext();\n renderCamera->SetViewport(0.f, 0.f, renderContext.GetScreenWidth(), renderContext.GetScreenHeight());\n eegeoWorld.SetCamera(renderCamera);\n \n m_globeCameraInterestPointProvider.SetGlobeCamera(m_globeCameraController);\n\n float interestPointLatitudeDegrees = 37.7858f;\n float interestPointLongitudeDegrees = -122.401f;\n float interestPointAltitudeMeters = 2.7;\n \n Eegeo::Space::LatLongAltitude location = Eegeo::Space::LatLongAltitude::FromDegrees(interestPointLatitudeDegrees,\n interestPointLongitudeDegrees,\n interestPointAltitudeMeters);\n \n \n \n float cameraControllerOrientationDegrees = 0.0f;\n float cameraControllerDistanceFromInterestPointMeters = 1781.0f;\n \n Eegeo::Space::EcefTangentBasis cameraInterestBasis;\n Eegeo::Camera::CameraHelpers::EcefTangentBasisFromPointAndHeading(location.ToECEF(), cameraControllerOrientationDegrees, cameraInterestBasis);\n \n m_globeCameraController->SetView(cameraInterestBasis, cameraControllerDistanceFromInterestPointMeters);\n \n eegeoWorld.GetWeatherController().SetWeather(Eegeo::Weather::Sunny, 1.0f);\n \n Eegeo::Search::Service::SearchService* searchService = NULL;\n \n if (eegeoWorld.IsSearchServiceAvailable())\n {\n searchService = &eegeoWorld.GetSearchService();\n }\n \n pExample = CreateExample(m_selectedExampleType,\n eegeoWorld.GetRenderContext(),\n location,\n eegeoWorld.GetCameraProvider(),\n *m_globeCameraController,\n *m_cameraTouchController,\n eegeoWorld.GetTerrainHeightProvider(),\n eegeoWorld.GetTextureLoader(),\n eegeoWorld.GetFileIO(),\n eegeoWorld.GetTerrainStreaming(),\n eegeoWorld.GetWebRequestFactory(),\n eegeoWorld.GetNavigationGraphRepository(),\n eegeoWorld.GetBuildingMeshPool(),\n eegeoWorld.GetShadowMeshPool(),\n eegeoWorld.GetStreamingVolume(),\n eegeoWorld.GetGlobalLighting(),\n eegeoWorld.GetGlobalFogging(),\n eegeoWorld.GetTrafficSimulation(),\n eegeoWorld.GetResourceSpatialQueryService(),\n eegeoWorld.GetEnvironmentFlatteningService(),\n searchService,\n eegeoWorld.GetNativeUIFactories(),\n eegeoWorld.GetInterestPointProvider());\n \n pExample->Start();\n}\n\nvoid MyApp::Update (float dt)\n{\n Eegeo::EegeoWorld& eegeoWorld = World();\n \n eegeoWorld.EarlyUpdate(dt);\n \n m_cameraTouchController->Update(dt);\n m_globeCameraController->Update(dt);\n \n eegeoWorld.Update(dt);\n pExample->Update();\n}\n\nvoid MyApp::Draw (float dt)\n{\n Eegeo::Rendering::GLState& glState = World().GetRenderContext().GetGLState();\n glState.ClearColor(0.8f, 0.8f, 0.8f, 1.f);\n World().Draw(dt);\n pExample->Draw();\n}\n\nvoid MyApp::JumpTo(double latitudeDegrees, double longitudeDegrees, double altitudeMetres, double headingDegrees, double distanceToInterestMetres)\n{\n Eegeo::dv3 interestPoint = Eegeo::Space::LatLongAltitude::FromDegrees(latitudeDegrees, longitudeDegrees, altitudeMetres).ToECEF();\n \n Eegeo::Space::EcefTangentBasis interestBasis;\n \n Eegeo::Camera::CameraHelpers::EcefTangentBasisFromPointAndHeading(interestPoint, headingDegrees, interestBasis);\n \n m_globeCameraController->SetView(interestBasis, distanceToInterestMetres);\n}\n\nExamples::IExample* MyApp::CreateExample(ExampleTypes::Examples example,\n Eegeo::Rendering::RenderContext& renderContext,\n Eegeo::Space::LatLongAltitude interestLocation,\n Eegeo::Camera::ICameraProvider& cameraProvider,\n Eegeo::Camera::GlobeCamera::GlobeCameraController& globeCameraController,\n Eegeo::ITouchController& cameraTouchController,\n Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,\n Eegeo::Helpers::ITextureFileLoader& textureLoader,\n Eegeo::Helpers::IFileIO& fileIO,\n Eegeo::Resources::Terrain::TerrainStreaming& terrainStreaming,\n Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,\n Eegeo::Resources::Roads::Navigation::NavigationGraphRepository& navigationGraphs,\n Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,\n Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool,\n Eegeo::Streaming::IStreamingVolume& visibleVolume,\n Eegeo::Lighting::GlobalLighting& lighting,\n Eegeo::Lighting::GlobalFogging& fogging,\n Eegeo::Traffic::TrafficSimulation& trafficSimulation,\n Eegeo::Resources::ResourceSpatialQueryService& resourceSpatialQueryService,\n Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,\n Eegeo::Search::Service::SearchService* searchService,\n Eegeo::UI::NativeUIFactories& nativeInputFactories,\n Eegeo::Location::IInterestPointProvider& interestPointProvider)\n{\n switch(example)\n {\n case ExampleTypes::LoadModel:\n return new Examples::LoadModelExample(renderContext,\n interestLocation,\n fileIO,\n textureLoader,\n fogging);\n case ExampleTypes::ScreenUnproject:\n case ExampleTypes::TerrainHeightQuery:\n return new Examples::ScreenUnprojectExample(renderContext,\n cameraProvider,\n terrainHeightProvider);\n \n case ExampleTypes::ScreenPick:\n return new Examples::ScreenPickExample(renderContext,\n cameraProvider,\n terrainHeightProvider);\n\n case ExampleTypes::DebugSphere:\n return new Examples::DebugSphereExample(renderContext,\n interestLocation);\n case ExampleTypes::EnvironmentNotifier:\n return new Examples::EnvironmentNotifierExample(renderContext,\n terrainStreaming);\n case ExampleTypes::WebRequest:\n return new Examples::WebRequestExample(webRequestFactory);\n \n case ExampleTypes::FileIO:\n return new Examples::FileIOExample(fileIO);\n \n case ExampleTypes::NavigationGraph:\n return new Examples::NavigationGraphExample(renderContext,\n navigationGraphs);\n \n case ExampleTypes::ModifiedRendering:\n return new Examples::ModifiedRenderingExample(renderContext,\n cameraProvider,\n interestPointProvider,\n visibleVolume,\n lighting,\n buildingPool,\n shadowPool);\n \n case ExampleTypes::ToggleTraffic:\n return new Examples::ToggleTrafficExample(trafficSimulation);\n \n case ExampleTypes::ResourceSpatialQuery:\n return new Examples::ResourceSpatialQueryExample(resourceSpatialQueryService,\n interestPointProvider);\n \n case ExampleTypes::EnvironmentFlattening:\n return new Examples::EnvironmentFlatteningExample(environmentFlatteningService);\n \n case ExampleTypes::Search:\n Eegeo_ASSERT(searchService != NULL, \"Cannot run Search example, you must set up here.com Credentials in ViewController.mm\");\n return new Examples::SearchExample(*searchService, interestPointProvider);\n \n case ExampleTypes::KeyboardInput:\n return new Examples::KeyboardInputExample(nativeInputFactories.IKeyboardInputFactory());\n \n case ExampleTypes::PODAnimation:\n return new Examples::PODAnimationExample(renderContext,\n fileIO,\n textureLoader,\n fogging);\n case ExampleTypes::Pick3DObject:\n return new Examples::Pick3DObjectExample(renderContext,\n interestLocation,\n cameraProvider);\n \n \n }\n}\n\n\nvoid MyApp::Event_TouchRotate(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate(data))\n {\n m_cameraTouchController->Event_TouchRotate(data);\n }\n}\n\nvoid MyApp::Event_TouchRotate_Start(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate_Start(data))\n {\n m_cameraTouchController->Event_TouchRotate_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchRotate_End(const AppInterface::RotateData& data)\n{\n if(!pExample->Event_TouchRotate_End(data))\n {\n m_cameraTouchController->Event_TouchRotate_End(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch(data))\n {\n m_cameraTouchController->Event_TouchPinch(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch_Start(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch_Start(data))\n {\n m_cameraTouchController->Event_TouchPinch_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchPinch_End(const AppInterface::PinchData& data)\n{\n if(!pExample->Event_TouchPinch_End(data))\n {\n m_cameraTouchController->Event_TouchPinch_End(data);\n }\n}\n\nvoid MyApp::Event_TouchPan(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan(data))\n {\n m_cameraTouchController->Event_TouchPan(data);\n }\n}\n\nvoid MyApp::Event_TouchPan_Start(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan_Start(data))\n {\n m_cameraTouchController->Event_TouchPan_Start(data);\n }\n}\n\nvoid MyApp::Event_TouchPan_End(const AppInterface::PanData& data)\n{\n if(!pExample->Event_TouchPan_End(data))\n {\n m_cameraTouchController->Event_TouchPan_End(data);\n }\n}\n\nvoid MyApp::Event_TouchTap(const AppInterface::TapData& data)\n{\n if(!pExample->Event_TouchTap(data))\n {\n m_cameraTouchController->Event_TouchTap(data);\n }\n}\n\nvoid MyApp::Event_TouchDoubleTap(const AppInterface::TapData& data)\n{\n if(!pExample->Event_TouchDoubleTap(data))\n {\n m_cameraTouchController->Event_TouchDoubleTap(data);\n }\n}\n\nvoid MyApp::Event_TouchDown(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchDown(data))\n {\n m_cameraTouchController->Event_TouchDown(data);\n }\n}\n\nvoid MyApp::Event_TouchMove(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchMove(data))\n {\n m_cameraTouchController->Event_TouchMove(data);\n }\n}\n\nvoid MyApp::Event_TouchUp(const AppInterface::TouchData& data)\n{\n if(!pExample->Event_TouchUp(data))\n {\n m_cameraTouchController->Event_TouchUp(data);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\/\n#include <cstdint>\n#include <cstring>\n\n#include <array>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <adios2.h>\n#include <adios2\/common\/ADIOSTypes.h>\n\n#include <gtest\/gtest.h>\n\nstd::string engineName; \/\/ comes from command line\n\nclass ADIOSSelectionTest : public ::testing::Test\n{\npublic:\n ADIOSSelectionTest() = default;\n};\n\nvoid copySelection3D(const double *a, const adios2::Dims &shape,\n const adios2::Dims &start, const adios2::Dims &count,\n double *b)\n{\n \/*std::cout << \" copy Block: shape = \" << adios2::ToString(shape)\n << \" start = \" << adios2::ToString(start)\n << \" count = \" << adios2::ToString(count) << std::endl;*\/\n double *bp = b;\n for (size_t x = 0; x < count[0]; ++x)\n {\n for (size_t y = 0; y < count[1]; ++y)\n {\n for (size_t z = 0; z < count[2]; ++z)\n {\n const size_t aidx = (start[0] + x) * shape[1] * shape[2] +\n (start[1] + y) * shape[2] + start[2] + z;\n \/*if (x == 0 && y == 0 && z == 0)\n {\n std::cout << \" idx of pos = \" << adios2::ToString({x, y, z})\n << \" => \" << aidx << \", a = \" << a[aidx]\n << std::endl;\n }*\/\n *bp = a[aidx];\n ++bp;\n }\n }\n }\n}\n\nbool compareSelection3D(const double *a, const adios2::Dims &shape,\n const adios2::Dims &start, const adios2::Dims &count,\n double *b, adios2::Dims &firstNonEqPoint)\n{\n std::cout << \" compare Block: shape = \" << adios2::ToString(shape)\n << \" start = \" << adios2::ToString(start)\n << \" count = \" << adios2::ToString(count) << std::endl;\n double *bp = b;\n for (size_t x = 0; x < count[0]; ++x)\n {\n for (size_t y = 0; y < count[1]; ++y)\n {\n for (size_t z = 0; z < count[2]; ++z)\n {\n const size_t aidx = (start[0] + x) * shape[1] * shape[2] +\n (start[1] + y) * shape[2] + start[2] + z;\n\n if (*bp != a[aidx])\n {\n firstNonEqPoint = {x, y, z};\n return false;\n }\n ++bp;\n }\n }\n }\n return true;\n}\n\nTEST_F(ADIOSSelectionTest, 3D)\n{\n constexpr size_t DIM1 = 15;\n constexpr size_t DIM2 = 12;\n constexpr size_t DIM3 = 9;\n const std::string filename = \"ADIOSSelection3D.bp\";\n const adios2::Dims shape = {DIM1, DIM2, DIM3};\n const adios2::Dims count = {5, 4, 3};\n double a[DIM1 * DIM2 * DIM3];\n\n double *ap = a;\n for (size_t x = 1; x <= DIM1; ++x)\n {\n for (size_t y = 1; y <= DIM2; ++y)\n {\n for (size_t z = 1; z <= DIM3; ++z)\n {\n *ap = x * 1.0 + y \/ 100.0 + z \/ 1000.0;\n ++ap;\n }\n }\n }\n \/* .\/bin\/bpls -la testing\/adios2\/engine\/bp\/bp4\/ADIOSSelection3D.bp\n -d a -n 9 -f \"%6.3f\"\n *\/\n\n adios2::ADIOS adios;\n \/\/ Write test data using BP\n {\n adios2::IO ioWrite = adios.DeclareIO(\"TestIOWrite\");\n if (!engineName.empty())\n {\n ioWrite.SetEngine(engineName);\n }\n else\n {\n \/\/ Create the BP Engine\n ioWrite.SetEngine(\"BPFile\");\n }\n\n adios2::Engine engine = ioWrite.Open(filename, adios2::Mode::Write);\n adios2::Dims start{0, 0, 0};\n double b[count[0] * count[1] * count[2]];\n\n adios2::Variable<double> var =\n ioWrite.DefineVariable<double>(\"a\", shape, start, count);\n\n \/*adios2::Variable<double> vara1 =\n ioWrite.DefineVariable<double>(\"a1\", shape, start, shape);*\/\n\n engine.BeginStep();\n \/*engine.Put(vara1, a);*\/\n\n for (size_t x = 0; x < DIM1; x += count[0])\n {\n for (size_t y = 0; y < DIM2; y += count[1])\n {\n for (size_t z = 0; z < DIM3; z += count[2])\n {\n start = {x, y, z};\n copySelection3D(a, shape, start, count, b);\n var.SetSelection({start, count});\n engine.Put(var, b, adios2::Mode::Sync);\n }\n }\n }\n\n engine.EndStep();\n engine.Close();\n }\n\n \/\/ Read data\n {\n adios2::IO ioRead = adios.DeclareIO(\"TestIORead\");\n ioRead.SetEngine(\"File\");\n adios2::Engine engine = ioRead.Open(filename, adios2::Mode::Read);\n EXPECT_TRUE(engine);\n engine.BeginStep();\n adios2::Variable<double> var = ioRead.InquireVariable<double>(\"a\");\n EXPECT_TRUE(var);\n adios2::Dims s{0, 0, 0};\n adios2::Dims c = shape;\n adios2::Dims firstNonMatch{0, 0, 0};\n std::vector<double> res;\n\n \/* Entire array *\/\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), DIM1 * DIM2 * DIM3);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Single block in the center *\/\n s = {5, 4, 3};\n c = count;\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Two blocks in X direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], count[1], count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Three blocks in Y direction *\/\n s = {5, 0, 3};\n c = {count[0], 3 * count[1], count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Two blocks in Z direction *\/\n s = {5, 4, 0};\n c = {count[0], count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Four blocks in X-Z direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* 8 blocks in X-Y-Z direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], 2 * count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/*\n * Partial blocks\n *\/\n\n \/* center part of single block in center *\/\n s = {6, 5, 4};\n c = {count[0] - 2, count[1] - 2, count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in X direction *\/\n s = {6, 5, 4};\n c = {2 * count[0] - 2, count[1] - 1, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in Y direction *\/\n s = {6, 5, 4};\n c = {count[0] - 1, 2 * count[1] - 2, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into three blocks in Y direction\n while contiguous in Z direction, making the read of the\n center of the three blocks as a single contiguous 4xYxZ copy *\/\n s = {6, 1, 3};\n c = {count[0] - 1, 3 * count[1] - 2, count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in Z direction *\/\n s = {6, 5, 4};\n c = {count[0] - 1, count[1] - 1, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in X-Y direction *\/\n s = {1, 5, 4};\n c = {2 * count[0] - 2, 2 * count[1] - 2, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in X-Z direction *\/\n s = {1, 5, 4};\n c = {2 * count[0] - 2, count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in Y-Z direction *\/\n s = {6, 5, 4};\n c = {count[0] - 2, 2 * count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into six blocks in X-Z direction *\/\n s = {1, 5, 4};\n c = {3 * count[0] - 2, count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Center block plus 1 in each direction, cutting into all blocks *\/\n \/* .\/bin\/bpls -la testing\/adios2\/engine\/bp\/bp4\/ADIOSSelection3D.bp\n -d a -f \"%6.3f \" -s \"4,3,2\" -c \"7,6,5\" -n 5\n *\/\n s = {4, 3, 2};\n c = {count[0] + 2, count[1] + 2, count[2] + 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n engine.EndStep();\n engine.Close();\n }\n}\n\nint main(int argc, char **argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n if (argc > 1)\n {\n engineName = std::string(argv[1]);\n }\n int result = RUN_ALL_TESTS();\n return result;\n}\n<commit_msg>fix windows build<commit_after>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\/\n#include <cstdint>\n#include <cstring>\n\n#include <array>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <adios2.h>\n#include <adios2\/common\/ADIOSTypes.h>\n\n#include <gtest\/gtest.h>\n\nstd::string engineName; \/\/ comes from command line\n\nclass ADIOSSelectionTest : public ::testing::Test\n{\npublic:\n ADIOSSelectionTest() = default;\n};\n\nvoid copySelection3D(const double *a, const adios2::Dims &shape,\n const adios2::Dims &start, const adios2::Dims &count,\n double *b)\n{\n \/*std::cout << \" copy Block: shape = \" << adios2::ToString(shape)\n << \" start = \" << adios2::ToString(start)\n << \" count = \" << adios2::ToString(count) << std::endl;*\/\n double *bp = b;\n for (size_t x = 0; x < count[0]; ++x)\n {\n for (size_t y = 0; y < count[1]; ++y)\n {\n for (size_t z = 0; z < count[2]; ++z)\n {\n const size_t aidx = (start[0] + x) * shape[1] * shape[2] +\n (start[1] + y) * shape[2] + start[2] + z;\n \/*if (x == 0 && y == 0 && z == 0)\n {\n std::cout << \" idx of pos = \" << adios2::ToString({x, y, z})\n << \" => \" << aidx << \", a = \" << a[aidx]\n << std::endl;\n }*\/\n *bp = a[aidx];\n ++bp;\n }\n }\n }\n}\n\nbool compareSelection3D(const double *a, const adios2::Dims &shape,\n const adios2::Dims &start, const adios2::Dims &count,\n double *b, adios2::Dims &firstNonEqPoint)\n{\n std::cout << \" compare Block: shape = \" << adios2::ToString(shape)\n << \" start = \" << adios2::ToString(start)\n << \" count = \" << adios2::ToString(count) << std::endl;\n double *bp = b;\n for (size_t x = 0; x < count[0]; ++x)\n {\n for (size_t y = 0; y < count[1]; ++y)\n {\n for (size_t z = 0; z < count[2]; ++z)\n {\n const size_t aidx = (start[0] + x) * shape[1] * shape[2] +\n (start[1] + y) * shape[2] + start[2] + z;\n\n if (*bp != a[aidx])\n {\n firstNonEqPoint = {x, y, z};\n return false;\n }\n ++bp;\n }\n }\n }\n return true;\n}\n\nTEST_F(ADIOSSelectionTest, 3D)\n{\n constexpr size_t C1 = 5;\n constexpr size_t C2 = 4;\n constexpr size_t C3 = 3;\n constexpr size_t DIM1 = 3 * C1;\n constexpr size_t DIM2 = 3 * C2;\n constexpr size_t DIM3 = 3 * C3;\n const std::string filename = \"ADIOSSelection3D.bp\";\n const adios2::Dims shape = {DIM1, DIM2, DIM3};\n const adios2::Dims count = {C1, C2, C3};\n double a[DIM1 * DIM2 * DIM3];\n\n double *ap = a;\n for (size_t x = 1; x <= DIM1; ++x)\n {\n for (size_t y = 1; y <= DIM2; ++y)\n {\n for (size_t z = 1; z <= DIM3; ++z)\n {\n *ap = x * 1.0 + y \/ 100.0 + z \/ 1000.0;\n ++ap;\n }\n }\n }\n \/* .\/bin\/bpls -la testing\/adios2\/engine\/bp\/bp4\/ADIOSSelection3D.bp\n -d a -n 9 -f \"%6.3f\"\n *\/\n\n adios2::ADIOS adios;\n \/\/ Write test data using BP\n {\n adios2::IO ioWrite = adios.DeclareIO(\"TestIOWrite\");\n if (!engineName.empty())\n {\n ioWrite.SetEngine(engineName);\n }\n else\n {\n \/\/ Create the BP Engine\n ioWrite.SetEngine(\"BPFile\");\n }\n\n adios2::Engine engine = ioWrite.Open(filename, adios2::Mode::Write);\n adios2::Dims start{0, 0, 0};\n double b[C1 * C2 * C3];\n\n adios2::Variable<double> var =\n ioWrite.DefineVariable<double>(\"a\", shape, start, count);\n\n \/*adios2::Variable<double> vara1 =\n ioWrite.DefineVariable<double>(\"a1\", shape, start, shape);*\/\n\n engine.BeginStep();\n \/*engine.Put(vara1, a);*\/\n\n for (size_t x = 0; x < DIM1; x += count[0])\n {\n for (size_t y = 0; y < DIM2; y += count[1])\n {\n for (size_t z = 0; z < DIM3; z += count[2])\n {\n start = {x, y, z};\n copySelection3D(a, shape, start, count, b);\n var.SetSelection({start, count});\n engine.Put(var, b, adios2::Mode::Sync);\n }\n }\n }\n\n engine.EndStep();\n engine.Close();\n }\n\n \/\/ Read data\n {\n adios2::IO ioRead = adios.DeclareIO(\"TestIORead\");\n ioRead.SetEngine(\"File\");\n adios2::Engine engine = ioRead.Open(filename, adios2::Mode::Read);\n EXPECT_TRUE(engine);\n engine.BeginStep();\n adios2::Variable<double> var = ioRead.InquireVariable<double>(\"a\");\n EXPECT_TRUE(var);\n adios2::Dims s{0, 0, 0};\n adios2::Dims c = shape;\n adios2::Dims firstNonMatch{0, 0, 0};\n std::vector<double> res;\n\n \/* Entire array *\/\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), DIM1 * DIM2 * DIM3);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Single block in the center *\/\n s = {5, 4, 3};\n c = count;\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Two blocks in X direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], count[1], count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Three blocks in Y direction *\/\n s = {5, 0, 3};\n c = {count[0], 3 * count[1], count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Two blocks in Z direction *\/\n s = {5, 4, 0};\n c = {count[0], count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Four blocks in X-Z direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* 8 blocks in X-Y-Z direction *\/\n s = {5, 4, 3};\n c = {2 * count[0], 2 * count[1], 2 * count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/*\n * Partial blocks\n *\/\n\n \/* center part of single block in center *\/\n s = {6, 5, 4};\n c = {count[0] - 2, count[1] - 2, count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in X direction *\/\n s = {6, 5, 4};\n c = {2 * count[0] - 2, count[1] - 1, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in Y direction *\/\n s = {6, 5, 4};\n c = {count[0] - 1, 2 * count[1] - 2, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into three blocks in Y direction\n while contiguous in Z direction, making the read of the\n center of the three blocks as a single contiguous 4xYxZ copy *\/\n s = {6, 1, 3};\n c = {count[0] - 1, 3 * count[1] - 2, count[2]};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into two blocks in Z direction *\/\n s = {6, 5, 4};\n c = {count[0] - 1, count[1] - 1, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in X-Y direction *\/\n s = {1, 5, 4};\n c = {2 * count[0] - 2, 2 * count[1] - 2, count[2] - 1};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in X-Z direction *\/\n s = {1, 5, 4};\n c = {2 * count[0] - 2, count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into four blocks in Y-Z direction *\/\n s = {6, 5, 4};\n c = {count[0] - 2, 2 * count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* partial selection cutting into six blocks in X-Z direction *\/\n s = {1, 5, 4};\n c = {3 * count[0] - 2, count[1] - 2, 2 * count[2] - 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n \/* Center block plus 1 in each direction, cutting into all blocks *\/\n \/* .\/bin\/bpls -la testing\/adios2\/engine\/bp\/bp4\/ADIOSSelection3D.bp\n -d a -f \"%6.3f \" -s \"4,3,2\" -c \"7,6,5\" -n 5\n *\/\n s = {4, 3, 2};\n c = {count[0] + 2, count[1] + 2, count[2] + 2};\n var.SetSelection({s, c});\n engine.Get<double>(var, res, adios2::Mode::Sync);\n EXPECT_EQ(res.size(), c[0] * c[1] * c[2]);\n EXPECT_TRUE(\n compareSelection3D(a, shape, s, c, res.data(), firstNonMatch));\n\n engine.EndStep();\n engine.Close();\n }\n}\n\nint main(int argc, char **argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n if (argc > 1)\n {\n engineName = std::string(argv[1]);\n }\n int result = RUN_ALL_TESTS();\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/idle_timer.h\"\n#include \"base\/message_loop.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing base::IdleTimer;\n\nnamespace {\n\n\/\/ We Mock the GetLastInputInfo function to return\n\/\/ the time stored here.\nstatic Time mock_timer_started;\n\nbool MockIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n TimeDelta delta = Time::Now() - mock_timer_started;\n *milliseconds_interval_since_last_event = \n static_cast<int32>(delta.InMilliseconds());\n return true;\n}\n\n\/\/ TestIdle task fires after 100ms of idle time.\nclass TestIdleTask : public IdleTimer {\n public:\n TestIdleTask(bool repeat)\n : IdleTimer(TimeDelta::FromMilliseconds(100), repeat),\n idle_counter_(0) {\n set_idle_time_source(MockIdleTimeSource);\n }\n\n int get_idle_counter() { return idle_counter_; }\n\n virtual void OnIdle() {\n idle_counter_++;\n }\n\n private:\n int idle_counter_;\n};\n\n\/\/ A task to help us quit the test.\nclass TestFinishedTask {\n public:\n TestFinishedTask() {}\n void Run() {\n MessageLoop::current()->Quit();\n }\n};\n\n\/\/ A timer which resets the idle clock.\nclass ResetIdleTask {\n public:\n ResetIdleTask() {}\n void Run() {\n mock_timer_started = Time::Now();\n }\n};\n\nclass IdleTimerTest : public testing::Test {\n private:\n \/\/ IdleTimer requires a UI message loop on the current thread.\n MessageLoopForUI message_loop_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoRepeat tests:\n\/\/ A non-repeating idle timer will fire once on idle, and\n\/\/ then will not fire again unless it goes non-idle first.\n\nTEST_F(IdleTimerTest, NoRepeatIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Verify that we fired exactly once.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n base::OneShotTimer<TestFinishedTask> timer;\n timer.Start(TimeDelta::FromSeconds(1), &finish_task, &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 1);\n}\n\nTEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset once, idle after 500ms.\n \/\/ Verify that we fired exactly twice.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(500), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 2);\n}\n\nTEST_F(IdleTimerTest, NoRepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Repeat tests:\n\/\/ A repeating idle timer will fire repeatedly on each interval, as long\n\/\/ as it has been idle. So, if the machine remains idle, it will continue\n\/\/ firing over and over.\n\nTEST_F(IdleTimerTest, Repeat) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1.05s.\n \/\/ Verify that we fired 10 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1050), &finish_task,\n &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 10. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 10.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 10);\n}\n\n\/\/ TODO(darin): http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=3780\nTEST_F(IdleTimerTest, DISABLED_RepeatIdleReset) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a reset timer, which fires after 550ms\n \/\/ Verify that we fired 9 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n ResetIdleTask reset_task;\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(550), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 9. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 9.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 9);\n}\n\nTEST_F(IdleTimerTest, RepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n} \/\/ namespace\n<commit_msg>Weee. More TODO(darin)s. :)<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/idle_timer.h\"\n#include \"base\/message_loop.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing base::IdleTimer;\n\nnamespace {\n\n\/\/ We Mock the GetLastInputInfo function to return\n\/\/ the time stored here.\nstatic Time mock_timer_started;\n\nbool MockIdleTimeSource(int32 *milliseconds_interval_since_last_event) {\n TimeDelta delta = Time::Now() - mock_timer_started;\n *milliseconds_interval_since_last_event = \n static_cast<int32>(delta.InMilliseconds());\n return true;\n}\n\n\/\/ TestIdle task fires after 100ms of idle time.\nclass TestIdleTask : public IdleTimer {\n public:\n TestIdleTask(bool repeat)\n : IdleTimer(TimeDelta::FromMilliseconds(100), repeat),\n idle_counter_(0) {\n set_idle_time_source(MockIdleTimeSource);\n }\n\n int get_idle_counter() { return idle_counter_; }\n\n virtual void OnIdle() {\n idle_counter_++;\n }\n\n private:\n int idle_counter_;\n};\n\n\/\/ A task to help us quit the test.\nclass TestFinishedTask {\n public:\n TestFinishedTask() {}\n void Run() {\n MessageLoop::current()->Quit();\n }\n};\n\n\/\/ A timer which resets the idle clock.\nclass ResetIdleTask {\n public:\n ResetIdleTask() {}\n void Run() {\n mock_timer_started = Time::Now();\n }\n};\n\nclass IdleTimerTest : public testing::Test {\n private:\n \/\/ IdleTimer requires a UI message loop on the current thread.\n MessageLoopForUI message_loop_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoRepeat tests:\n\/\/ A non-repeating idle timer will fire once on idle, and\n\/\/ then will not fire again unless it goes non-idle first.\n\nTEST_F(IdleTimerTest, NoRepeatIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Verify that we fired exactly once.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n base::OneShotTimer<TestFinishedTask> timer;\n timer.Start(TimeDelta::FromSeconds(1), &finish_task, &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 1);\n}\n\nTEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset once, idle after 500ms.\n \/\/ Verify that we fired exactly twice.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(500), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n EXPECT_EQ(test_task.get_idle_counter(), 2);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_NoRepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire once after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(false);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Repeat tests:\n\/\/ A repeating idle timer will fire repeatedly on each interval, as long\n\/\/ as it has been idle. So, if the machine remains idle, it will continue\n\/\/ firing over and over.\n\nTEST_F(IdleTimerTest, Repeat) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1.05s.\n \/\/ Verify that we fired 10 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1050), &finish_task,\n &TestFinishedTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 10. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 10.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 10);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3780\nTEST_F(IdleTimerTest, DISABLED_RepeatIdleReset) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a reset timer, which fires after 550ms\n \/\/ Verify that we fired 9 times.\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n ResetIdleTask reset_task;\n TestFinishedTask finish_task;\n\n base::OneShotTimer<TestFinishedTask> t1;\n t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::OneShotTimer<ResetIdleTask> t2;\n t2.Start(TimeDelta::FromMilliseconds(550), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n \/\/ In a perfect world, the idle_counter should be 9. However,\n \/\/ since timers aren't guaranteed to fire perfectly, this can\n \/\/ be less. Just expect more than 5 and no more than 9.\n EXPECT_GT(test_task.get_idle_counter(), 5);\n EXPECT_LE(test_task.get_idle_counter(), 9);\n}\n\n\/\/ TODO(darin): http:\/\/crbug.com\/3704\nTEST_F(IdleTimerTest, DISABLED_RepeatNotIdle) {\n \/\/ Create an IdleTimer, which should fire repeatedly after 100ms.\n \/\/ Create a Quit timer which will fire after 1s.\n \/\/ Create a timer to reset idle every 50ms.\n \/\/ Verify that we never fired.\n\n mock_timer_started = Time::Now();\n TestIdleTask test_task(true);\n\n TestFinishedTask finish_task;\n ResetIdleTask reset_task;\n\n base::OneShotTimer<TestFinishedTask> t;\n t.Start(TimeDelta::FromMilliseconds(1000), &finish_task,\n &TestFinishedTask::Run);\n \n base::RepeatingTimer<ResetIdleTask> reset_timer;\n reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task,\n &ResetIdleTask::Run);\n\n test_task.Start();\n MessageLoop::current()->Run();\n\n reset_timer.Stop();\n\n EXPECT_EQ(test_task.get_idle_counter(), 0);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n\/* Test Case Description:\n Scenario 1: The test validates if fine grain\n behavior is observed or not with memory allocated using hipHostMalloc()\n Scenario 2: The test validates if fine grain\n behavior is observed or not with memory allocated using hipMallocManaged()\n Scenario 3: The test validates if memory access is fine\n with memory allocated using hipMallocManaged() and CoarseGrain Advise\n Scenario 4: The test validates if memory access is fine\n with memory allocated using hipMalloc() and CoarseGrain Advise\n Scenario 5: The test validates if fine grain\n behavior is observed or not with memory allocated using\n hipExtMallocWithFlags()*\/\n\n\n#include <hip_test_common.hh>\n#include <chrono>\n\n__global__ void CoherentTst(int *ptr, int PeakClk) {\n \/\/ Incrementing the value by 1\n int64_t GpuFrq = (PeakClk * 1000);\n int64_t StrtTck = clock64();\n atomicAdd(ptr, 1);\n \/\/ The following while loop checks the value in ptr for around 3-4 seconds\n while ((clock64() - StrtTck) <= (3 * GpuFrq)) {\n if (*ptr == 3) {\n atomicAdd(ptr, 1);\n return;\n }\n }\n}\n\n__global__ void SquareKrnl(int *ptr) {\n \/\/ ptr value squared here\n *ptr = (*ptr) * (*ptr);\n}\n\n\n\n\/\/ The variable below will work as signal to decide pass\/fail\nstatic bool YES_COHERENT = false;\n\n\/\/ The function tests the coherency of allocated memory\nstatic void TstCoherency(int *Ptr, bool HmmMem) {\n int *Dptr = nullptr, peak_clk;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n \/\/ storing value 1 in the memory created above\n *Ptr = 1;\n \/\/ Getting gpu frequency\n HIP_CHECK(hipDeviceGetAttribute(&peak_clk, hipDeviceAttributeClockRate, 0));\n if (!HmmMem) {\n HIP_CHECK(hipHostGetDevicePointer(reinterpret_cast<void **>(&Dptr), Ptr,\n 0));\n CoherentTst<<<1, 1, 0, strm>>>(Dptr, peak_clk);\n } else {\n CoherentTst<<<1, 1, 0, strm>>>(Ptr, peak_clk);\n }\n \/\/ looping until the value is 2 for 3 seconds\n std::chrono::steady_clock::time_point start =\n std::chrono::steady_clock::now();\n while (std::chrono::duration_cast<std::chrono::seconds>(\n std::chrono::steady_clock::now() - start).count() < 3) {\n if (*Ptr == 2) {\n *Ptr += 1;\n break;\n }\n }\n HIP_CHECK(hipStreamSynchronize(strm));\n HIP_CHECK(hipStreamDestroy(strm));\n if (*Ptr == 4) {\n YES_COHERENT = true;\n }\n}\n\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using hipHostMalloc()*\/\n\/\/ The following tests are disabled for Nvidia as they are not consistently\n\/\/ passing\n#if HT_AMD\nTEST_CASE(\"Unit_hipHostMalloc_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n bool HmmMem = false;\n YES_COHERENT = false;\n \/\/ Allocating hipHostMalloc() memory with hipHostMallocCoherent flag\n SECTION(\"hipHostMalloc with hipHostMallocCoherent flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE, hipHostMallocCoherent));\n }\n SECTION(\"hipHostMalloc with Default flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE));\n }\n SECTION(\"hipHostMalloc with hipHostMallocMapped flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE, hipHostMallocMapped));\n }\n\n TstCoherency(Ptr, HmmMem);\n HIP_CHECK(hipHostFree(Ptr));\n REQUIRE(YES_COHERENT);\n}\n#endif\n\n\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using hipMallocManaged()*\/\n\/\/ The following tests are disabled for Nvidia as they are not consistently\n\/\/ passing\n#if HT_AMD\nTEST_CASE(\"Unit_hipMallocManaged_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n bool HmmMem = true;\n YES_COHERENT = false;\n \/\/ Allocating hipMallocManaged() memory\n SECTION(\"hipMallocManaged with hipMemAttachGlobal flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachGlobal));\n }\n SECTION(\"hipMallocManaged with hipMemAttachHost flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachHost));\n }\n TstCoherency(Ptr, HmmMem);\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(YES_COHERENT);\n}\n#endif\n\n\/* Test case description: The following test validates if memory access is fine\n with memory allocated using hipMallocManaged() and CoarseGrain Advise*\/\nTEST_CASE(\"Unit_hipMallocManaged_CoherentTstWthAdvise\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n YES_COHERENT = false;\n \/\/ Allocating hipMallocManaged() memory\n SECTION(\"hipMallocManaged with hipMemAttachGlobal flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachGlobal));\n }\n SECTION(\"hipMallocManaged with hipMemAttachHost flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachHost));\n }\n#if HT_AMD\n HIP_CHECK(hipMemAdvise(Ptr, SIZE, hipMemAdviseSetCoarseGrain, 0));\n#endif\n \/\/ Initializing Ptr memory with 9\n *Ptr = 9;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n SquareKrnl<<<1, 1, 0, strm>>>(Ptr);\n HIP_CHECK(hipStreamSynchronize(strm));\n if (*Ptr == 81) {\n YES_COHERENT = true;\n }\n HIP_CHECK(hipFree(Ptr));\n HIP_CHECK(hipStreamDestroy(strm));\n REQUIRE(YES_COHERENT);\n}\n\n\n\/* Test case description: The following test validates if memory allocated\n using hipMalloc() are of type Coarse Grain*\/\n\/\/ The following tests are disabled for Nvidia as they are not applicable\n#if HT_AMD\nTEST_CASE(\"Unit_hipMalloc_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n uint32_t svm_attrib = 0;\n bool IfTstPassed = false;\n \/\/ Allocating hipMalloc() memory\n HIP_CHECK(hipMalloc(&Ptr, SIZE));\n HIP_CHECK(hipMemRangeGetAttribute(&svm_attrib, sizeof(svm_attrib),\n hipMemRangeAttributeCoherencyMode, Ptr, SIZE));\n if (svm_attrib == hipMemRangeCoherencyModeCoarseGrain) {\n IfTstPassed = true;\n }\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(IfTstPassed);\n}\n#endif\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using\n hipExtMallocWithFlags()*\/\n#if HT_AMD\nTEST_CASE(\"Unit_hipExtMallocWithFlags_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int), InitVal = 9;\n bool FineGrain = true;\n YES_COHERENT = false;\n \/\/ Allocating hipExtMallocWithFlags() memory with flags\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocFinegrained flag\") {\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipDeviceMallocFinegrained));\n }\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocSignalMemory flag\") {\n \/\/ for hipMallocSignalMemory flag the size of memory must be 8\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipMallocSignalMemory));\n }\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocDefault flag\") {\n \/* hipExtMallocWithFlags() with flag\n hipDeviceMallocDefault allocates CoarseGrain memory *\/\n FineGrain = false;\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipDeviceMallocDefault));\n }\n if (FineGrain) {\n TstCoherency(Ptr, FineGrain);\n } else {\n *Ptr = InitVal;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n SquareKrnl<<<1, 1, 0, strm>>>(Ptr);\n HIP_CHECK(hipStreamSynchronize(strm));\n if (*Ptr == (InitVal * InitVal)) {\n YES_COHERENT = true;\n }\n }\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(YES_COHERENT);\n}\n#endif\n\n<commit_msg>Add missing checks in hipMemCoherencyTst.cc (#2442)<commit_after>\/*\n Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n\/* Test Case Description:\n Scenario 1: The test validates if fine grain\n behavior is observed or not with memory allocated using hipHostMalloc()\n Scenario 2: The test validates if fine grain\n behavior is observed or not with memory allocated using hipMallocManaged()\n Scenario 3: The test validates if memory access is fine\n with memory allocated using hipMallocManaged() and CoarseGrain Advise\n Scenario 4: The test validates if memory access is fine\n with memory allocated using hipMalloc() and CoarseGrain Advise\n Scenario 5: The test validates if fine grain\n behavior is observed or not with memory allocated using\n hipExtMallocWithFlags()*\/\n\n\n#include <hip_test_common.hh>\n#include <chrono>\n\n__global__ void CoherentTst(int *ptr, int PeakClk) {\n \/\/ Incrementing the value by 1\n int64_t GpuFrq = (PeakClk * 1000);\n int64_t StrtTck = clock64();\n atomicAdd(ptr, 1);\n \/\/ The following while loop checks the value in ptr for around 3-4 seconds\n while ((clock64() - StrtTck) <= (3 * GpuFrq)) {\n if (*ptr == 3) {\n atomicAdd(ptr, 1);\n return;\n }\n }\n}\n\n__global__ void SquareKrnl(int *ptr) {\n \/\/ ptr value squared here\n *ptr = (*ptr) * (*ptr);\n}\n\n\n\n\/\/ The variable below will work as signal to decide pass\/fail\nstatic bool YES_COHERENT = false;\n\n\/\/ The function tests the coherency of allocated memory\nstatic void TstCoherency(int *Ptr, bool HmmMem) {\n int *Dptr = nullptr, peak_clk;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n \/\/ storing value 1 in the memory created above\n *Ptr = 1;\n \/\/ Getting gpu frequency\n HIP_CHECK(hipDeviceGetAttribute(&peak_clk, hipDeviceAttributeClockRate, 0));\n if (!HmmMem) {\n HIP_CHECK(hipHostGetDevicePointer(reinterpret_cast<void **>(&Dptr), Ptr,\n 0));\n CoherentTst<<<1, 1, 0, strm>>>(Dptr, peak_clk);\n } else {\n CoherentTst<<<1, 1, 0, strm>>>(Ptr, peak_clk);\n }\n \/\/ looping until the value is 2 for 3 seconds\n std::chrono::steady_clock::time_point start =\n std::chrono::steady_clock::now();\n while (std::chrono::duration_cast<std::chrono::seconds>(\n std::chrono::steady_clock::now() - start).count() < 3) {\n if (*Ptr == 2) {\n *Ptr += 1;\n break;\n }\n }\n HIP_CHECK(hipStreamSynchronize(strm));\n HIP_CHECK(hipStreamDestroy(strm));\n if (*Ptr == 4) {\n YES_COHERENT = true;\n }\n}\n\nstatic int HmmAttrPrint() {\n int managed = 0;\n INFO(\"The following are the attribute values related to HMM for\"\n \" device 0:\\n\");\n HIP_CHECK(hipDeviceGetAttribute(&managed,\n hipDeviceAttributeDirectManagedMemAccessFromHost, 0));\n INFO(\"hipDeviceAttributeDirectManagedMemAccessFromHost: \" << managed);\n HIP_CHECK(hipDeviceGetAttribute(&managed,\n hipDeviceAttributeConcurrentManagedAccess, 0));\n INFO(\"hipDeviceAttributeConcurrentManagedAccess: \" << managed);\n HIP_CHECK(hipDeviceGetAttribute(&managed,\n hipDeviceAttributePageableMemoryAccess, 0));\n INFO(\"hipDeviceAttributePageableMemoryAccess: \" << managed);\n HIP_CHECK(hipDeviceGetAttribute(&managed,\n hipDeviceAttributePageableMemoryAccessUsesHostPageTables, 0));\n INFO(\"hipDeviceAttributePageableMemoryAccessUsesHostPageTables:\"\n << managed);\n\n HIP_CHECK(hipDeviceGetAttribute(&managed, hipDeviceAttributeManagedMemory,\n 0));\n INFO(\"hipDeviceAttributeManagedMemory: \" << managed);\n return managed;\n}\n\n\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using hipHostMalloc()*\/\n\/\/ The following tests are disabled for Nvidia as they are not consistently\n\/\/ passing\n#if HT_AMD\nTEST_CASE(\"Unit_hipHostMalloc_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n bool HmmMem = false;\n YES_COHERENT = false;\n \/\/ Allocating hipHostMalloc() memory with hipHostMallocCoherent flag\n SECTION(\"hipHostMalloc with hipHostMallocCoherent flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE, hipHostMallocCoherent));\n }\n SECTION(\"hipHostMalloc with Default flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE));\n }\n SECTION(\"hipHostMalloc with hipHostMallocMapped flag\") {\n HIP_CHECK(hipHostMalloc(&Ptr, SIZE, hipHostMallocMapped));\n }\n\n TstCoherency(Ptr, HmmMem);\n HIP_CHECK(hipHostFree(Ptr));\n REQUIRE(YES_COHERENT);\n}\n#endif\n\n\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using hipMallocManaged()*\/\n\/\/ The following tests are disabled for Nvidia as they are not consistently\n\/\/ passing\n#if HT_AMD\nTEST_CASE(\"Unit_hipMallocManaged_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n bool HmmMem = true;\n YES_COHERENT = false;\n\n int managed = HmmAttrPrint();\n if (managed == 1) {\n \/\/ Allocating hipMallocManaged() memory\n SECTION(\"hipMallocManaged with hipMemAttachGlobal flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachGlobal));\n }\n SECTION(\"hipMallocManaged with hipMemAttachHost flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachHost));\n }\n TstCoherency(Ptr, HmmMem);\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(YES_COHERENT);\n } else {\n SUCCEED(\"GPU 0 doesn't support hipDeviceAttributeManagedMemory \"\n \"attribute. Hence skipping the testing with Pass result.\\n\");\n }\n}\n#endif\n\n\/* Test case description: The following test validates if memory access is fine\n with memory allocated using hipMallocManaged() and CoarseGrain Advise*\/\nTEST_CASE(\"Unit_hipMallocManaged_CoherentTstWthAdvise\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n YES_COHERENT = false;\n \/\/ Allocating hipMallocManaged() memory\n SECTION(\"hipMallocManaged with hipMemAttachGlobal flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachGlobal));\n }\n SECTION(\"hipMallocManaged with hipMemAttachHost flag\") {\n HIP_CHECK(hipMallocManaged(&Ptr, SIZE, hipMemAttachHost));\n }\n#if HT_AMD\n HIP_CHECK(hipMemAdvise(Ptr, SIZE, hipMemAdviseSetCoarseGrain, 0));\n#endif\n \/\/ Initializing Ptr memory with 9\n *Ptr = 9;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n SquareKrnl<<<1, 1, 0, strm>>>(Ptr);\n HIP_CHECK(hipStreamSynchronize(strm));\n if (*Ptr == 81) {\n YES_COHERENT = true;\n }\n HIP_CHECK(hipFree(Ptr));\n HIP_CHECK(hipStreamDestroy(strm));\n REQUIRE(YES_COHERENT);\n}\n\n\n\/* Test case description: The following test validates if memory allocated\n using hipMalloc() are of type Coarse Grain*\/\n\/\/ The following tests are disabled for Nvidia as they are not applicable\n#if HT_AMD\nTEST_CASE(\"Unit_hipMalloc_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int);\n uint32_t svm_attrib = 0;\n bool IfTstPassed = false;\n \/\/ Allocating hipMalloc() memory\n HIP_CHECK(hipMalloc(&Ptr, SIZE));\n HIP_CHECK(hipMemRangeGetAttribute(&svm_attrib, sizeof(svm_attrib),\n hipMemRangeAttributeCoherencyMode, Ptr, SIZE));\n if (svm_attrib == hipMemRangeCoherencyModeCoarseGrain) {\n IfTstPassed = true;\n }\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(IfTstPassed);\n}\n#endif\n\/* Test case description: The following test validates if fine grain\n behavior is observed or not with memory allocated using\n hipExtMallocWithFlags()*\/\n#if HT_AMD\nTEST_CASE(\"Unit_hipExtMallocWithFlags_CoherentTst\") {\n int *Ptr = nullptr, SIZE = sizeof(int), InitVal = 9;\n bool FineGrain = true;\n YES_COHERENT = false;\n\n int managed = HmmAttrPrint();\n if (managed == 1) {\n \/\/ Allocating hipExtMallocWithFlags() memory with flags\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocFinegrained flag\") {\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipDeviceMallocFinegrained));\n }\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocSignalMemory flag\") {\n \/\/ for hipMallocSignalMemory flag the size of memory must be 8\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipMallocSignalMemory));\n }\n SECTION(\"hipExtMallocWithFlags with hipDeviceMallocDefault flag\") {\n \/* hipExtMallocWithFlags() with flag\n hipDeviceMallocDefault allocates CoarseGrain memory *\/\n FineGrain = false;\n HIP_CHECK(hipExtMallocWithFlags(reinterpret_cast<void**>(&Ptr), SIZE*2,\n hipDeviceMallocDefault));\n }\n if (FineGrain) {\n TstCoherency(Ptr, FineGrain);\n } else {\n *Ptr = InitVal;\n hipStream_t strm;\n HIP_CHECK(hipStreamCreate(&strm));\n SquareKrnl<<<1, 1, 0, strm>>>(Ptr);\n HIP_CHECK(hipStreamSynchronize(strm));\n if (*Ptr == (InitVal * InitVal)) {\n YES_COHERENT = true;\n }\n }\n HIP_CHECK(hipFree(Ptr));\n REQUIRE(YES_COHERENT);\n } else {\n SUCCEED(\"GPU 0 doesn't support hipDeviceAttributeManagedMemory \"\n \"attribute. Hence skipping the testing with Pass result.\\n\");\n }\n}\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <limits>\n#include <deque>\n#include <cstdlib>\n#include <hpp\/util\/assertion.hh>\n#include <hpp\/util\/debug.hh>\n#include <hpp\/core\/distance.hh>\n#include <hpp\/core\/path-validation.hh>\n#include <hpp\/core\/path-vector.hh>\n#include <hpp\/core\/problem.hh>\n#include <hpp\/core\/random-shortcut.hh>\n\nnamespace hpp {\n namespace core {\n \/\/ Compute the length of a vector of paths assuming that each element\n \/\/ is optimal for the given distance.\n static value_type pathLength (const PathVectorPtr_t& path,\n\t\t\t\t const DistancePtr_t& distance)\n {\n value_type result = 0;\n for (std::size_t i=0; i<path->numberPaths (); ++i) {\n\tconst PathPtr_t& element (path->pathAtRank (i));\n\tConfiguration_t q1 = element->initial ();\n\tConfiguration_t q2 = element->end ();\n\tresult += (*distance) (q1, q2);\n }\n return result;\n }\n\n RandomShortcutPtr_t\n RandomShortcut::create (const Problem& problem)\n {\n RandomShortcut* ptr = new RandomShortcut (problem);\n return RandomShortcutPtr_t (ptr);\n }\n\n RandomShortcut::RandomShortcut (const Problem& problem) :\n PathOptimizer (problem)\n {\n }\n\n PathVectorPtr_t RandomShortcut::optimize (const PathVectorPtr_t& path)\n {\n using std::numeric_limits;\n using std::make_pair;\n bool finished = false;\n value_type t3 = path->timeRange ().second;\n Configuration_t q0 = path->initial ();\n Configuration_t q3 = path->end ();\n PathVectorPtr_t tmpPath = path;\n\n \/\/ Maximal number of iterations without improvements\n const std::size_t n = 5;\n std::deque <value_type> length (n-1,\n\t\t\t\t numeric_limits <value_type>::infinity ());\n length.push_back (pathLength (tmpPath, problem ().distance ()));\n PathVectorPtr_t result;\n Configuration_t q1 (path->outputSize ()),\n q2 (path->outputSize ());\n\n while (!finished) {\n\tt3 = tmpPath->timeRange ().second;\n\tvalue_type u2 = t3 * rand ()\/RAND_MAX;\n\tvalue_type u1 = t3 * rand ()\/RAND_MAX;\n\tvalue_type t1, t2;\n\tif (u1 < u2) {t1 = u1; t2 = u2;} else {t1 = u2; t2 = u1;}\n\tif (!(*tmpPath) (q1, t1)) {\n hppDout (error, \"Configuration at param \" << t1 << \" could not be \"\n \"projected\");\n }\n\tif (!(*tmpPath) (q2, t2)) {\n hppDout (error, \"Configuration at param \" << t1 << \" could not be \"\n \"projected\");\n }\n\t\/\/ Validate sub parts\n\tbool valid [3];\n\tPathPtr_t straight [3];\n\tstraight [0] = steer (q0, q1);\n\tstraight [1] = steer (q1, q2);\n\tstraight [2] = steer (q2, q3);\n\tfor (unsigned i=0; i<3; ++i) {\n\t PathPtr_t validPart;\n\t PathValidationReportPtr_t report;\n if (!straight [i]) valid[i] = false;\n else {\n valid [i] = problem ().pathValidation ()->validate\n (straight [i], false, validPart, report);\n }\n\t}\n\t\/\/ Replace valid parts\n\tresult = PathVector::create (path->outputSize (),\n\t\t\t\t path->outputDerivativeSize ());\n\tif (valid [0])\n\t result->appendPath (straight [0]);\n\telse\n\t result->concatenate (*(tmpPath->extract\n\t\t\t\t (make_pair <value_type,value_type> (0, t1))->\n\t\t\t\t as <PathVector> ()));\n\tif (valid [1])\n\t result->appendPath (straight [1]);\n\telse\n\t result->concatenate (*(tmpPath->extract\n\t\t\t\t (make_pair <value_type,value_type> (t1, t2))->\n\t\t\t\t as <PathVector> ()));\n\tif (valid [2])\n\t result->appendPath (straight [2]);\n\telse\n\t result->concatenate (*(tmpPath->extract\n\t\t\t\t(make_pair <value_type, value_type> (t2, t3))->\n\t\t\t\t as <PathVector> ()));\n\tlength.push_back (pathLength (result, problem ().distance ()));\n\tlength.pop_front ();\n\tfinished = (length [0] <= length [n-1]);\n\thppDout (info, \"length = \" << length [n-1]);\n\ttmpPath = result;\n }\n hppDout (info, \"RandomShortcut:\" << *result);\n for (std::size_t i = 0; i < result->numberPaths (); ++i) {\n if (result->pathAtRank(i)->constraints())\n hppDout (info, \"At rank \" << i << \", constraints are \" <<\n *result->pathAtRank(i)->constraints());\n else\n hppDout (info, \"At rank \" << i << \", no constraints\");\n }\n return result;\n }\n } \/\/ namespace core\n} \/\/ namespace hpp\n<commit_msg>RandomShortcut handles projection errors<commit_after>\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <limits>\n#include <deque>\n#include <cstdlib>\n#include <hpp\/util\/assertion.hh>\n#include <hpp\/util\/debug.hh>\n#include <hpp\/core\/distance.hh>\n#include <hpp\/core\/path-validation.hh>\n#include <hpp\/core\/path-vector.hh>\n#include <hpp\/core\/problem.hh>\n#include <hpp\/core\/random-shortcut.hh>\n\nnamespace hpp {\n namespace core {\n \/\/ Compute the length of a vector of paths assuming that each element\n \/\/ is optimal for the given distance.\n static value_type pathLength (const PathVectorPtr_t& path,\n\t\t\t\t const DistancePtr_t& distance)\n {\n value_type result = 0;\n for (std::size_t i=0; i<path->numberPaths (); ++i) {\n\tconst PathPtr_t& element (path->pathAtRank (i));\n\tConfiguration_t q1 = element->initial ();\n\tConfiguration_t q2 = element->end ();\n\tresult += (*distance) (q1, q2);\n }\n return result;\n }\n\n RandomShortcutPtr_t\n RandomShortcut::create (const Problem& problem)\n {\n RandomShortcut* ptr = new RandomShortcut (problem);\n return RandomShortcutPtr_t (ptr);\n }\n\n RandomShortcut::RandomShortcut (const Problem& problem) :\n PathOptimizer (problem)\n {\n }\n\n PathVectorPtr_t RandomShortcut::optimize (const PathVectorPtr_t& path)\n {\n using std::numeric_limits;\n using std::make_pair;\n bool finished = false;\n value_type t3 = path->timeRange ().second;\n Configuration_t q0 = path->initial ();\n Configuration_t q3 = path->end ();\n PathVectorPtr_t tmpPath = path;\n\n \/\/ Maximal number of iterations without improvements\n const std::size_t n = 5;\n std::size_t projectionError = n;\n std::deque <value_type> length (n-1,\n\t\t\t\t numeric_limits <value_type>::infinity ());\n length.push_back (pathLength (tmpPath, problem ().distance ()));\n PathVectorPtr_t result;\n Configuration_t q1 (path->outputSize ()),\n q2 (path->outputSize ());\n\n while (!finished && projectionError != 0) {\n\tt3 = tmpPath->timeRange ().second;\n\tvalue_type u2 = t3 * rand ()\/RAND_MAX;\n\tvalue_type u1 = t3 * rand ()\/RAND_MAX;\n\tvalue_type t1, t2;\n\tif (u1 < u2) {t1 = u1; t2 = u2;} else {t1 = u2; t2 = u1;}\n\tif (!(*tmpPath) (q1, t1)) {\n hppDout (error, \"Configuration at param \" << t1 << \" could not be \"\n \"projected\");\n projectionError--;\n continue;\n }\n\tif (!(*tmpPath) (q2, t2)) {\n hppDout (error, \"Configuration at param \" << t1 << \" could not be \"\n \"projected\");\n projectionError--;\n continue;\n }\n\t\/\/ Validate sub parts\n\tbool valid [3];\n\tPathPtr_t straight [3];\n\tstraight [0] = steer (q0, q1);\n\tstraight [1] = steer (q1, q2);\n\tstraight [2] = steer (q2, q3);\n\tfor (unsigned i=0; i<3; ++i) {\n\t PathPtr_t validPart;\n\t PathValidationReportPtr_t report;\n if (!straight [i]) valid[i] = false;\n else {\n valid [i] = problem ().pathValidation ()->validate\n (straight [i], false, validPart, report);\n }\n\t}\n\t\/\/ Replace valid parts\n\tresult = PathVector::create (path->outputSize (),\n\t\t\t\t path->outputDerivativeSize ());\n try {\n if (valid [0])\n result->appendPath (straight [0]);\n else\n result->concatenate (*(tmpPath->extract\n (make_pair <value_type,value_type> (0, t1))->\n as <PathVector> ()));\n if (valid [1])\n result->appendPath (straight [1]);\n else\n result->concatenate (*(tmpPath->extract\n (make_pair <value_type,value_type> (t1, t2))->\n as <PathVector> ()));\n if (valid [2])\n result->appendPath (straight [2]);\n else\n result->concatenate (*(tmpPath->extract\n (make_pair <value_type, value_type> (t2, t3))->\n as <PathVector> ()));\n } catch (const projection_error& e) {\n hppDout (error, \"Caught exception at with time \" << t1 << \" and \" <<\n t2 << \": \" << e.what ());\n projectionError--;\n result = tmpPath;\n continue;\n }\n\tlength.push_back (pathLength (result, problem ().distance ()));\n\tlength.pop_front ();\n\tfinished = (length [0] <= length [n-1]);\n\thppDout (info, \"length = \" << length [n-1]);\n\ttmpPath = result;\n }\n hppDout (info, \"RandomShortcut:\" << *result);\n for (std::size_t i = 0; i < result->numberPaths (); ++i) {\n if (result->pathAtRank(i)->constraints())\n hppDout (info, \"At rank \" << i << \", constraints are \" <<\n *result->pathAtRank(i)->constraints());\n else\n hppDout (info, \"At rank \" << i << \", no constraints\");\n }\n return result;\n }\n } \/\/ namespace core\n} \/\/ namespace hpp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * raspberrysensor\n * https:\/\/github.com\/markw\/raspberrysensor\n *\n * Access a temperature and humidity sensor using the GPIO ports on the Raspberry Pi\n *\n * Copyright (c) 2012 Mark Wolfe\n * Licensed under the MIT license.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <sched.h>\n#include <sys\/io.h>\n#include <bcm2835.h>\n\n#define NSEC_PER_SEC 1000000000\n\n#include <node.h>\n#include <string>\n\nusing namespace v8;\n\nstatic inline int timespec_cmp (struct timespec a, struct timespec b)\n{\n return (a.tv_sec < b.tv_sec ? -1\n : a.tv_sec > b.tv_sec ? 1\n : a.tv_nsec - b.tv_nsec);\n}\n\n\/\/ Forward declaration. Usually, you do this in a header file.\nHandle<Value> Async(const Arguments& args);\nvoid AsyncWork(uv_work_t* req);\nvoid AsyncAfter(uv_work_t* req);\n\n\/\/ We use a struct to store information about the asynchronous \"work request\".\nstruct Baton {\n \/\/ This handle holds the callback function we'll call after the work request\n \/\/ has been completed in a threadpool thread. It's persistent so that V8\n \/\/ doesn't garbage collect it away while our request waits to be processed.\n \/\/ This means that we'll have to dispose of it later ourselves.\n Persistent<Function> callback;\n\n \/\/ The GPIO pin which will be read\n int32_t pin;\n\n \/\/ return values \n int32_t temp;\n int32_t humidity;\n\n \/\/ time taken\n int32_t time_taken;\n\n \/\/ time stamps\n struct timespec t_before;\n struct timespec t_after;\n \n \/\/ Tracking errors that happened in the worker function. You can use any\n \/\/ variables you want. E.g. in some cases, it might be useful to report\n \/\/ an error number.\n bool error;\n\n \/\/ an optional error message\n std::string error_message;\n\n \/\/ Custom data you can pass through.\n int32_t result;\n};\n\n\/\/ This is the function called directly from JavaScript land. It creates a\n\/\/ work request object and schedules it for execution.\nHandle<Value> Async(const Arguments& args) {\n HandleScope scope;\n\n if (!args[0]->IsFunction()) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a callback function.\")));\n }\n\n if (!args[1]->IsUndefined() && !args[1]->IsNumber()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Second argument must be the number of the pin to read data from.\")));\n }\n\n \/\/ There's no ToFunction(), use a Cast instead.\n Local<Function> callback = Local<Function>::Cast(args[0]);\n\n \/\/ The baton holds our custom status information for this asynchronous call,\n \/\/ like the callback function we want to call when returning to the main\n \/\/ thread and the status information.\n Baton* baton = new Baton();\n baton->error = false;\n baton->callback = Persistent<Function>::New(callback);\n baton->pin = args[1]->IsUndefined() ? 4 : args[1]->NumberValue();\n\n \/\/ This creates the work request struct.\n uv_work_t *req = new uv_work_t();\n req->data = baton;\n\n \/\/ Schedule our work request with libuv. Here you can specify the functions\n \/\/ that should be executed in the threadpool and back in the main thread\n \/\/ after the threadpool function completed.\n int status = uv_queue_work(uv_default_loop(), req, AsyncWork, AsyncAfter);\n assert(status == 0);\n\n return Undefined();\n}\n\n\/\/ This function is executed in another thread at some point after it has been\n\/\/ scheduled. IT MUST NOT USE ANY V8 FUNCTIONALITY. Otherwise your extension\n\/\/ will crash randomly and you'll have a lot of fun debugging.\n\/\/ If you want to use parameters passed into the original call, you have to\n\/\/ convert them to PODs or some other fancy method.\nvoid AsyncWork(uv_work_t* req) {\n Baton* baton = static_cast<Baton*>(req->data);\n\n \/\/ initialise the bcm2835, returning an error if this fails.\n if (!bcm2835_init()){\n baton->error_message = \"Unable to initialise bcm2835\";\n baton->error = true;\n return;\n }\n\n struct sched_param param;\n int retryCount = 0;\n\n clock_gettime(0, &baton->t_before);\n\n do {\n\n if(retryCount > 100){\n clock_gettime(0, &baton->t_after);\n baton->result = timespec_cmp(baton->t_after, baton->t_before);\n return; \n }\n \n bcm2835_delayMicroseconds(10);\n\n retryCount++;\n\n } while (1);\n\n\n \/\/ Do work in threadpool here.\n baton->result = baton->pin;\n\n \/\/ If the work we do fails, set baton->error_message to the error string\n \/\/ and baton->error to true.\n}\n\n\/\/ This function is executed in the main V8\/JavaScript thread. That means it's\n\/\/ safe to use V8 functions again. Don't forget the HandleScope!\nvoid AsyncAfter(uv_work_t* req) {\n HandleScope scope;\n Baton* baton = static_cast<Baton*>(req->data);\n\n if (baton->error) {\n Local<Value> err = Exception::Error(String::New(baton->error_message.c_str()));\n\n \/\/ Prepare the parameters for the callback function.\n const unsigned argc = 1;\n Local<Value> argv[argc] = { err };\n\n \/\/ Wrap the callback function call in a TryCatch so that we can call\n \/\/ node's FatalException afterwards. This makes it possible to catch\n \/\/ the exception from JavaScript land using the\n \/\/ process.on('uncaughtException') event.\n TryCatch try_catch;\n baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n } else {\n \/\/ In case the operation succeeded, convention is to pass null as the\n \/\/ first argument before the result arguments.\n \/\/ In case you produced more complex data, this is the place to convert\n \/\/ your plain C++ data structures into JavaScript\/V8 data structures.\n const unsigned argc = 2;\n Local<Value> argv[argc] = {\n Local<Value>::New(Null()),\n Local<Value>::New(Integer::New(baton->result))\n };\n\n \/\/ Wrap the callback function call in a TryCatch so that we can call\n \/\/ node's FatalException afterwards. This makes it possible to catch\n \/\/ the exception from JavaScript land using the\n \/\/ process.on('uncaughtException') event.\n TryCatch try_catch;\n baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n }\n\n \/\/ The callback is a permanent handle, so we have to dispose of it manually.\n baton->callback.Dispose();\n\n \/\/ We also created the baton and the work_req struct with new, so we have to\n \/\/ manually delete both.\n delete baton;\n delete req;\n}\n\nvoid RegisterModule(Handle<Object> target) {\n target->Set(String::NewSymbol(\"async\"),\n FunctionTemplate::New(Async)->GetFunction());\n}\n\nNODE_MODULE(raspberrysensor, RegisterModule);\n<commit_msg>Reading data is working need to work on decoding.<commit_after>\/*\n * raspberrysensor\n * https:\/\/github.com\/markw\/raspberrysensor\n *\n * Access a temperature and humidity sensor using the GPIO ports on the Raspberry Pi\n *\n * Copyright (c) 2012 Mark Wolfe\n * Licensed under the MIT license.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <sched.h>\n#include <sys\/io.h>\n#include <bcm2835.h>\n\n#define DHT22_DATA_BIT_COUNT 41\n\n#include <node.h>\n#include <string>\n\nusing namespace v8;\n\nstatic inline int timespec_cmp (struct timespec a, struct timespec b)\n{\n return (a.tv_sec < b.tv_sec ? -1\n : a.tv_sec > b.tv_sec ? 1\n : a.tv_nsec - b.tv_nsec);\n}\n\n\/\/ Forward declaration. Usually, you do this in a header file.\nHandle<Value> Async(const Arguments& args);\nvoid AsyncWork(uv_work_t* req);\nvoid AsyncAfter(uv_work_t* req);\n\n\/\/ We use a struct to store information about the asynchronous \"work request\".\nstruct Baton {\n \/\/ This handle holds the callback function we'll call after the work request\n \/\/ has been completed in a threadpool thread. It's persistent so that V8\n \/\/ doesn't garbage collect it away while our request waits to be processed.\n \/\/ This means that we'll have to dispose of it later ourselves.\n Persistent<Function> callback;\n\n \/\/ The GPIO pin which will be read\n int32_t pin;\n\n \/\/ return values \n int32_t temp;\n int32_t humidity;\n\n \/\/ time taken\n int32_t time_taken;\n\n \/\/ time stamps\n struct timespec t_before;\n struct timespec t_after;\n \n \/\/ Tracking errors that happened in the worker function. You can use any\n \/\/ variables you want. E.g. in some cases, it might be useful to report\n \/\/ an error number.\n bool error;\n\n \/\/ an optional error message\n std::string error_message;\n\n \/\/ Custom data you can pass through.\n int32_t result;\n};\n\n\/\/ This is the function called directly from JavaScript land. It creates a\n\/\/ work request object and schedules it for execution.\nHandle<Value> Async(const Arguments& args) {\n HandleScope scope;\n\n if (!args[0]->IsFunction()) {\n return ThrowException(Exception::TypeError(\n String::New(\"First argument must be a callback function.\")));\n }\n\n if (!args[1]->IsUndefined() && !args[1]->IsNumber()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Second argument must be the number of the pin to read data from.\")));\n }\n\n \/\/ There's no ToFunction(), use a Cast instead.\n Local<Function> callback = Local<Function>::Cast(args[0]);\n\n \/\/ The baton holds our custom status information for this asynchronous call,\n \/\/ like the callback function we want to call when returning to the main\n \/\/ thread and the status information.\n Baton* baton = new Baton();\n baton->error = false;\n baton->callback = Persistent<Function>::New(callback);\n baton->pin = args[1]->IsUndefined() ? 4 : args[1]->NumberValue();\n\n \/\/ This creates the work request struct.\n uv_work_t *req = new uv_work_t();\n req->data = baton;\n\n \/\/ Schedule our work request with libuv. Here you can specify the functions\n \/\/ that should be executed in the threadpool and back in the main thread\n \/\/ after the threadpool function completed.\n int status = uv_queue_work(uv_default_loop(), req, AsyncWork, AsyncAfter);\n assert(status == 0);\n\n return Undefined();\n}\n\n\/\/ This function is executed in another thread at some point after it has been\n\/\/ scheduled. IT MUST NOT USE ANY V8 FUNCTIONALITY. Otherwise your extension\n\/\/ will crash randomly and you'll have a lot of fun debugging.\n\/\/ If you want to use parameters passed into the original call, you have to\n\/\/ convert them to PODs or some other fancy method.\nvoid AsyncWork(uv_work_t* req) {\n Baton* baton = static_cast<Baton*>(req->data);\n\n \/\/ initialise the bcm2835, returning an error if this fails.\n if (!bcm2835_init()){\n baton->error_message = \"Unable to initialise bcm2835\";\n baton->error = true;\n return;\n }\n\n\/\/ struct sched_param param;\n uint8_t retryCount;\n uint8_t bitTimes[DHT22_DATA_BIT_COUNT];\n int i;\n\n int currentTemperature;\n int currentHumidity;\n \n \/\/ configure the pin for output\n bcm2835_gpio_fsel(baton->pin, BCM2835_GPIO_FSEL_OUTP);\n\n \/\/ Pin needs to start HIGH, wait until it is HIGH with a timeout\n retryCount = 0;\n\n do {\n if (retryCount > 125) {\n baton->error_message = \"DHT bus timeout\"; \n baton->error = true;\n return;\n }\n bcm2835_delayMicroseconds(2);\n retryCount++;\n } while (bcm2835_gpio_lev(baton->pin) == HIGH); \/\/ should be high\n\n \/\/ set the pin low \n bcm2835_gpio_write(baton->pin, LOW);\n\n \/\/ hold it for 1ms\n bcm2835_delay(1);\n\n \/\/ configure the pin for output\n bcm2835_gpio_fsel(baton->pin, BCM2835_GPIO_FSEL_INPT);\n\n \/\/ Find the start of the ACK Pulse\n retryCount = 0;\n \n do {\n if(retryCount > 25) { \/\/(Spec is 20 to 40 us, 25*2 == 50 us)\n baton->error_message = \"DHT not present.\"; \n baton->error = true;\n return;\n } \n bcm2835_delayMicroseconds(2);\n retryCount++;\n } while (bcm2835_gpio_lev(baton->pin) == LOW); \n \n \/\/ Find the end of the ACK Pulse\n retryCount = 0;\n\n do {\n if (retryCount > 50) { \/\/(Spec is 80 us, 50*2 == 100 us)\n baton->error_message = \"DHT not present.\"; \n baton->error = true;\n return;\n }\n bcm2835_delayMicroseconds(2);\n retryCount++;\n } while (bcm2835_gpio_lev(baton->pin) == HIGH); \n\n \/\/ Read the 40 bit data stream\n for(i = 0; i < DHT22_DATA_BIT_COUNT; i++) {\n\n \/\/ Find the start of the sync pulse\n retryCount = 0;\n do {\n if (retryCount > 35) { \/\/(Spec is 50 us, 35*2 == 70 us)\n baton->error_message = \"DHT sync error.\"; \n baton->error = true;\n return;\n }\n bcm2835_delayMicroseconds(2);\n retryCount++;\n } while (bcm2835_gpio_lev(baton->pin) == LOW);\n \n \/\/ Measure the width of the data pulse\n retryCount = 0;\n do {\n if (retryCount > 50) { \/\/(Spec is 80 us, 50*2 == 100 us)\n baton->error_message = \"DHT data timeout error.\"; \n baton->error = true;\n return;\n }\n bcm2835_delayMicroseconds(2);\n retryCount++;\n } while (bcm2835_gpio_lev(baton->pin) == HIGH);\n\n \/\/ assign the bit value\n bitTimes[i] = retryCount;\n }\n\n \/\/ DEBUG\n printf(\"values: \");\n for(i = 0; i < DHT22_DATA_BIT_COUNT; i++) {\n printf(\"%d \", bitTimes[i]); \n }\n printf(\"\\n\");\n \/\/ DEBUG\n\n \/\/ Spec: 0 is 26 to 28 us\n \/\/ Spec: 1 is 70 us\n \/\/ bitTimes[x] <= 11 is a 0\n \/\/ bitTimes[x] > 11 is a 1 \n\n \/\/ read humidity \n currentHumidity = 0;\n for(i = 0; i < 16; i++) {\n if(bitTimes[i + 1] > 11) {\n currentHumidity |= (1 << (15 - i));\n } \n }\n\n baton->humidity = currentHumidity & 0x7FFF;\n\n \/\/ DEBUG\n printf(\"currentHumidity = %d\\n\", baton->humidity);\n \/\/ DEBUG\n\n \/\/ read the temperature\n currentTemperature = 0;\n for(i = 0; i < 16; i++) {\n if(bitTimes[i + 17] > 11){\n currentTemperature |= (1 << (15 - i));\n }\n }\n\n baton->temp = currentTemperature & 0x7FFF;\n\n \/\/ DEBUG\n printf(\"currentTemperature = %d\\n\", baton->temp);\n \/\/ DEBUG\n\n\/*\n clock_gettime(0, &baton->t_before);\n\n retryCount = 0;\n\n do {\n\n if(retryCount > 100){\n clock_gettime(0, &baton->t_after);\n baton->result = timespec_cmp(baton->t_after, baton->t_before);\n return; \n }\n \n bcm2835_delayMicroseconds(10);\n retryCount++;\n\n } while (1);\n*\/\n \/\/ Do work in threadpool here.\n baton->result = baton->pin;\n\n \/\/ If the work we do fails, set baton->error_message to the error string\n \/\/ and baton->error to true.\n}\n\n\/\/ This function is executed in the main V8\/JavaScript thread. That means it's\n\/\/ safe to use V8 functions again. Don't forget the HandleScope!\nvoid AsyncAfter(uv_work_t* req) {\n HandleScope scope;\n Baton* baton = static_cast<Baton*>(req->data);\n\n if (baton->error) {\n Local<Value> err = Exception::Error(String::New(baton->error_message.c_str()));\n\n \/\/ Prepare the parameters for the callback function.\n const unsigned argc = 1;\n Local<Value> argv[argc] = { err };\n\n \/\/ Wrap the callback function call in a TryCatch so that we can call\n \/\/ node's FatalException afterwards. This makes it possible to catch\n \/\/ the exception from JavaScript land using the\n \/\/ process.on('uncaughtException') event.\n TryCatch try_catch;\n baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n } else {\n \/\/ In case the operation succeeded, convention is to pass null as the\n \/\/ first argument before the result arguments.\n \/\/ In case you produced more complex data, this is the place to convert\n \/\/ your plain C++ data structures into JavaScript\/V8 data structures.\n const unsigned argc = 2;\n Local<Value> argv[argc] = {\n Local<Value>::New(Null()),\n Local<Value>::New(Integer::New(baton->result))\n };\n\n \/\/ Wrap the callback function call in a TryCatch so that we can call\n \/\/ node's FatalException afterwards. This makes it possible to catch\n \/\/ the exception from JavaScript land using the\n \/\/ process.on('uncaughtException') event.\n TryCatch try_catch;\n baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n }\n\n \/\/ The callback is a permanent handle, so we have to dispose of it manually.\n baton->callback.Dispose();\n\n \/\/ We also created the baton and the work_req struct with new, so we have to\n \/\/ manually delete both.\n delete baton;\n delete req;\n}\n\nvoid RegisterModule(Handle<Object> target) {\n target->Set(String::NewSymbol(\"async\"),\n FunctionTemplate::New(Async)->GetFunction());\n}\n\nNODE_MODULE(raspberrysensor, RegisterModule);\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=3 --benchmark_filter=Planetarium \/\/ NOLINT(whitespace\/line_length)\n\n#include \"ksp_plugin\/planetarium.hpp\"\n\n#include <random>\n#include <vector>\n\n#include \"astronomy\/time_scales.hpp\"\n#include \"benchmark\/benchmark.h\"\n#include \"physics\/body_centred_non_rotating_dynamic_frame.hpp\"\n#include \"physics\/solar_system.hpp\"\n#include \"testing_utilities\/solar_system_factory.hpp\"\n\nnamespace principia {\nnamespace geometry {\n\nusing astronomy::operator\"\"_UT1;\nusing astronomy::operator\"\"_TT;\nusing base::make_not_null_unique;\nusing base::not_null;\nusing geometry::Bivector;\nusing geometry::Perspective;\nusing geometry::RigidTransformation;\nusing geometry::RP2Lines;\nusing geometry::Vector;\nusing geometry::Velocity;\nusing integrators::SymmetricLinearMultistepIntegrator;\nusing integrators::methods::Quinlan1999Order8A;\nusing integrators::methods::QuinlanTremaine1990Order12;\nusing ksp_plugin::Camera;\nusing ksp_plugin::Barycentric;\nusing ksp_plugin::Navigation;\nusing ksp_plugin::NavigationFrame;\nusing ksp_plugin::Planetarium;\nusing physics::BodyCentredNonRotatingDynamicFrame;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::Ephemeris;\nusing physics::KeplerianElements;\nusing physics::KeplerOrbit;\nusing physics::MassiveBody;\nusing physics::MasslessBody;\nusing physics::SolarSystem;\nusing quantities::Angle;\nusing quantities::Cos;\nusing quantities::Infinity;\nusing quantities::Length;\nusing quantities::Sin;\nusing quantities::Time;\nusing quantities::si::ArcMinute;\nusing quantities::si::Day;\nusing quantities::si::Degree;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nusing quantities::si::Milli;\nusing quantities::si::Minute;\nusing quantities::si::Radian;\nusing quantities::si::Second;\nusing testing_utilities::SolarSystemFactory;\n\nnamespace {\n\nconstexpr Length near = 40'000 * Kilo(Metre);\nconstexpr Length far = 400'000 * Kilo(Metre);\nconstexpr Length focal = 1 * Metre;\n\nPerspective<Navigation, Camera> PolarPerspective(\n Length const distance_from_earth) {\n return {\n RigidTransformation<Navigation, Camera>(\n Navigation::origin + Displacement<Navigation>(\n {0 * Metre, 0 * Metre, distance_from_earth}),\n Camera::origin,\n Rotation<Navigation, Camera>(Vector<double, Navigation>({1, 0, 0}),\n Vector<double, Navigation>({0, 0, 1}),\n Bivector<double, Navigation>({0, -1, 0}))\n .Forget()),\n focal};\n}\n\nPerspective<Navigation, Camera> EquatorialPerspective(\n Length const distance_from_earth) {\n return {\n RigidTransformation<Navigation, Camera>(\n Navigation::origin + Displacement<Navigation>(\n {0 * Metre, distance_from_earth, 0 * Metre}),\n Camera::origin,\n Rotation<Navigation, Camera>(Vector<double, Navigation>({1, 0, 0}),\n Vector<double, Navigation>({0, 0, 1}),\n Bivector<double, Navigation>({0, -1, 0}))\n .Forget()),\n focal};\n}\n\nclass Satellites {\n public:\n Satellites()\n : solar_system_(make_not_null_unique<SolarSystem<Barycentric>>(\n SOLUTION_DIR \/ \"astronomy\" \/ \"sol_gravity_model.proto.txt\",\n SOLUTION_DIR \/ \"astronomy\" \/\n \"sol_initial_state_jd_2451545_000000000.proto.txt\",\n \/*ignore_frame=*\/true)),\n ephemeris_(\n solar_system_->MakeEphemeris(\/*fitting_tolerance=*\/1 * Milli(Metre),\n EphemerisParameters())),\n earth_(solar_system_->massive_body(\n *ephemeris_,\n SolarSystemFactory::name(SolarSystemFactory::Earth))),\n earth_centred_inertial_(\n make_not_null_unique<\n BodyCentredNonRotatingDynamicFrame<Barycentric, Navigation>>(\n ephemeris_.get(),\n earth_)) {\n \/\/ Two-line elements for GOES-8:\n \/\/ 1 23051U 94022A 00004.06628221 -.00000243 00000-0 00000-0 0 9630\n \/\/ 2 23051 0.4232 97.7420 0004776 192.8349 121.5613 1.00264613 28364\n constexpr Instant goes_8_epoch = \"JD2451548.56628221\"_UT1;\n KeplerianElements<Barycentric> goes_8_elements;\n goes_8_elements.inclination = 0.4232 * Degree;\n goes_8_elements.longitude_of_ascending_node = 97.7420 * Degree;\n goes_8_elements.eccentricity = 0.0004776;\n goes_8_elements.argument_of_periapsis = 192.8349 * Degree;\n goes_8_elements.mean_anomaly = 121.5613 * Degree;\n goes_8_elements.mean_motion = 1.00264613 * (2 * π * Radian \/ Day);\n KeplerOrbit<Barycentric> const goes_8_orbit(\n earth_, MasslessBody{}, goes_8_elements, goes_8_epoch);\n goes_8_trajectory_.Append(\n goes_8_epoch,\n ephemeris_->trajectory(earth_)->EvaluateDegreesOfFreedom(goes_8_epoch) +\n goes_8_orbit.StateVectors(goes_8_epoch));\n\n ephemeris_->Prolong(goes_8_epoch);\n auto goes_8_instance = ephemeris_->NewInstance(\n {&goes_8_trajectory_},\n Ephemeris<Barycentric>::NoIntrinsicAccelerations,\n HistoryParameters());\n ephemeris_->FlowWithFixedStep(goes_8_epoch + 100 * Day, goes_8_instance)\n }\n\n DiscreteTrajectory<Barycentric> const& GOES8Trajectory() const {\n return goes_8_trajectory_;\n }\n\n Planetarium MakePlanetarium(\n Perspective<Navigation, Camera> const& perspective) const {\n \/\/ No dark area, human visual acuity, wide field of view.\n Planetarium::Parameters parameters(\n \/*sphere_radius_multiplier=*\/1,\n \/*angular_resolution=*\/0.4 * ArcMinute,\n \/*field_of_view=*\/90 * Degree);\n Planetarium planetarium(\n parameters, perspective, &ephemeris_, &earth_centred_inertial_);\n }\n\n private:\n Ephemeris<Barycentric>::FixedStepParameters EphemerisParameters() {\n return Ephemeris<Barycentric>::FixedStepParameters(\n SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,\n Position<Barycentric>>(),\n \/*step=*\/10 * Minute);\n }\n\n Ephemeris<Barycentric>::FixedStepParameters HistoryParameters() {\n return Ephemeris<Barycentric>::FixedStepParameters(\n SymmetricLinearMultistepIntegrator<Quinlan1999Order8A,\n Position<Barycentric>>(),\n \/*step=*\/10 * Second);\n }\n\n not_null<std::unique_ptr<SolarSystem<Barycentric>>> const solar_system_;\n not_null<std::unique_ptr<Ephemeris<Barycentric>>> const ephemeris_;\n not_null<MassiveBody const*> const earth_;\n not_null<std::unique_ptr<NavigationFrame>> const earth_centred_inertial_;\n DiscreteTrajectory<Barycentric> goes_8_trajectory_;\n\n};\n\n} \/\/ namespace\n\nvoid RunBenchmark(benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n Satellites satellites;\n Planetarium planetarium = satellites.MakePlanetarium(perspective);\n RP2Lines<Length, Camera> lines;\n int total_lines = 0;\n int total_points = 0;\n int iterations = 0;\n constexpr Instant now = \"2000-01-21T04:41:30,5\"_TT;\n while (state.KeepRunning()) {\n lines = planetarium.PlotMethod2(satellites.GOES8Trajectory().Begin(),\n satellites.GOES8Trajectory().End(),\n now,\n \/*reverse=*\/false);\n state.PauseTiming();\n total_lines += lines.size();\n for (auto const& line : lines) {\n total_points += line.size();\n }\n ++iterations;\n state.ResumeTiming();\n }\n Length min_x = Infinity<Length>();\n Length min_y = Infinity<Length>();\n Length max_x = Infinity<Length>();\n Length max_y = Infinity<Length>();\n for (auto const& line : lines) {\n for (auto const& point : line) {\n min_x = std::min(min_x, point.x());\n min_y = std::min(min_y, point.y());\n max_x = std::max(max_x, point.x());\n max_y = std::max(max_y, point.y());\n }\n }\n state.SetLabel(std::to_string(total_points \/ iterations) + \" points in \" +\n std::to_string(total_lines \/ iterations) + \" within [\" +\n DebugString(min_x) + \", \" + DebugString(max_x) + \"] × [\" +\n DebugString(min_y) + \", \" + DebugString(max_y) + \"]\")\n}\n\nvoid BM_PlanetariumPlotMethod2NearPolarPerspective(\n benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n RunBenchmark(state, PolarPerspective(near));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2NearPolarPerspective);\n\nvoid BM_PlanetariumPlotMethod2FarPolarPerspective(\n benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n RunBenchmark(state, PolarPerspective(far));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2FarPolarPerspective);\n\nvoid BM_PlanetariumPlotMethod2NearEquatorialPerspective(\n benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n RunBenchmark(state, EquatorialPerspective(near));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2NearEquatorialPerspective);\n\nvoid BM_PlanetariumPlotMethod2FarEquatorialPerspective(\n benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n RunBenchmark(state, EquatorialPerspective(far));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2FarEquatorialPerspective);\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<commit_msg>make it compile<commit_after>\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=3 --benchmark_filter=Planetarium \/\/ NOLINT(whitespace\/line_length)\n\n#include \"ksp_plugin\/planetarium.hpp\"\n\n#include <random>\n#include <vector>\n\n#include \"astronomy\/time_scales.hpp\"\n#include \"benchmark\/benchmark.h\"\n#include \"physics\/body_centred_non_rotating_dynamic_frame.hpp\"\n#include \"physics\/solar_system.hpp\"\n#include \"testing_utilities\/solar_system_factory.hpp\"\n\nnamespace principia {\nnamespace geometry {\n\nusing astronomy::operator\"\"_UT1;\nusing astronomy::operator\"\"_TT;\nusing base::make_not_null_unique;\nusing base::not_null;\nusing geometry::Bivector;\nusing geometry::Perspective;\nusing geometry::RigidTransformation;\nusing geometry::RP2Lines;\nusing geometry::Vector;\nusing geometry::Velocity;\nusing integrators::SymmetricLinearMultistepIntegrator;\nusing integrators::methods::Quinlan1999Order8A;\nusing integrators::methods::QuinlanTremaine1990Order12;\nusing ksp_plugin::Camera;\nusing ksp_plugin::Barycentric;\nusing ksp_plugin::Navigation;\nusing ksp_plugin::NavigationFrame;\nusing ksp_plugin::Planetarium;\nusing physics::BodyCentredNonRotatingDynamicFrame;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::Ephemeris;\nusing physics::KeplerianElements;\nusing physics::KeplerOrbit;\nusing physics::MassiveBody;\nusing physics::MasslessBody;\nusing physics::SolarSystem;\nusing quantities::Angle;\nusing quantities::Cos;\nusing quantities::Infinity;\nusing quantities::Length;\nusing quantities::Sin;\nusing quantities::Time;\nusing quantities::si::ArcMinute;\nusing quantities::si::Day;\nusing quantities::si::Degree;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nusing quantities::si::Milli;\nusing quantities::si::Minute;\nusing quantities::si::Radian;\nusing quantities::si::Second;\nusing testing_utilities::SolarSystemFactory;\n\nnamespace {\n\nconstexpr Length near = 40'000 * Kilo(Metre);\nconstexpr Length far = 400'000 * Kilo(Metre);\nconstexpr Length focal = 1 * Metre;\n\nPerspective<Navigation, Camera> PolarPerspective(\n Length const distance_from_earth) {\n return {\n RigidTransformation<Navigation, Camera>(\n Navigation::origin + Displacement<Navigation>(\n {0 * Metre, 0 * Metre, distance_from_earth}),\n Camera::origin,\n Rotation<Navigation, Camera>(Vector<double, Navigation>({1, 0, 0}),\n Vector<double, Navigation>({0, 0, 1}),\n Bivector<double, Navigation>({0, -1, 0}))\n .Forget()),\n focal};\n}\n\nPerspective<Navigation, Camera> EquatorialPerspective(\n Length const distance_from_earth) {\n return {\n RigidTransformation<Navigation, Camera>(\n Navigation::origin + Displacement<Navigation>(\n {0 * Metre, distance_from_earth, 0 * Metre}),\n Camera::origin,\n Rotation<Navigation, Camera>(Vector<double, Navigation>({1, 0, 0}),\n Vector<double, Navigation>({0, 0, 1}),\n Bivector<double, Navigation>({0, -1, 0}))\n .Forget()),\n focal};\n}\n\nclass Satellites {\n public:\n Satellites()\n : solar_system_(make_not_null_unique<SolarSystem<Barycentric>>(\n SOLUTION_DIR \/ \"astronomy\" \/ \"sol_gravity_model.proto.txt\",\n SOLUTION_DIR \/ \"astronomy\" \/\n \"sol_initial_state_jd_2451545_000000000.proto.txt\",\n \/*ignore_frame=*\/true)),\n ephemeris_(\n solar_system_->MakeEphemeris(\/*fitting_tolerance=*\/1 * Milli(Metre),\n EphemerisParameters())),\n earth_(solar_system_->massive_body(\n *ephemeris_,\n SolarSystemFactory::name(SolarSystemFactory::Earth))),\n earth_centred_inertial_(\n make_not_null_unique<\n BodyCentredNonRotatingDynamicFrame<Barycentric, Navigation>>(\n ephemeris_.get(),\n earth_)) {\n \/\/ Two-line elements for GOES-8:\n \/\/ 1 23051U 94022A 00004.06628221 -.00000243 00000-0 00000-0 0 9630\n \/\/ 2 23051 0.4232 97.7420 0004776 192.8349 121.5613 1.00264613 28364\n constexpr Instant goes_8_epoch = \"JD2451548.56628221\"_UT1;\n KeplerianElements<Barycentric> goes_8_elements;\n goes_8_elements.inclination = 0.4232 * Degree;\n goes_8_elements.longitude_of_ascending_node = 97.7420 * Degree;\n goes_8_elements.eccentricity = 0.0004776;\n goes_8_elements.argument_of_periapsis = 192.8349 * Degree;\n goes_8_elements.mean_anomaly = 121.5613 * Degree;\n goes_8_elements.mean_motion = 1.00264613 * (2 * π * Radian \/ Day);\n KeplerOrbit<Barycentric> const goes_8_orbit(\n *earth_, MasslessBody{}, goes_8_elements, goes_8_epoch);\n goes_8_trajectory_.Append(\n goes_8_epoch,\n ephemeris_->trajectory(earth_)->EvaluateDegreesOfFreedom(goes_8_epoch) +\n goes_8_orbit.StateVectors(goes_8_epoch));\n\n ephemeris_->Prolong(goes_8_epoch);\n auto goes_8_instance = ephemeris_->NewInstance(\n {&goes_8_trajectory_},\n Ephemeris<Barycentric>::NoIntrinsicAccelerations,\n HistoryParameters());\n CHECK_OK(ephemeris_->FlowWithFixedStep(goes_8_epoch + 100 * Day,\n *goes_8_instance));\n }\n\n DiscreteTrajectory<Barycentric> const& GOES8Trajectory() const {\n return goes_8_trajectory_;\n }\n\n Planetarium MakePlanetarium(\n Perspective<Navigation, Camera> const& perspective) const {\n \/\/ No dark area, human visual acuity, wide field of view.\n Planetarium::Parameters parameters(\n \/*sphere_radius_multiplier=*\/1,\n \/*angular_resolution=*\/0.4 * ArcMinute,\n \/*field_of_view=*\/90 * Degree);\n return Planetarium(parameters,\n perspective,\n ephemeris_.get(),\n earth_centred_inertial_.get());\n }\n\n private:\n Ephemeris<Barycentric>::FixedStepParameters EphemerisParameters() {\n return Ephemeris<Barycentric>::FixedStepParameters(\n SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,\n Position<Barycentric>>(),\n \/*step=*\/10 * Minute);\n }\n\n Ephemeris<Barycentric>::FixedStepParameters HistoryParameters() {\n return Ephemeris<Barycentric>::FixedStepParameters(\n SymmetricLinearMultistepIntegrator<Quinlan1999Order8A,\n Position<Barycentric>>(),\n \/*step=*\/10 * Second);\n }\n\n not_null<std::unique_ptr<SolarSystem<Barycentric>>> const solar_system_;\n not_null<std::unique_ptr<Ephemeris<Barycentric>>> const ephemeris_;\n not_null<MassiveBody const*> const earth_;\n not_null<std::unique_ptr<NavigationFrame>> const earth_centred_inertial_;\n DiscreteTrajectory<Barycentric> goes_8_trajectory_;\n\n};\n\n} \/\/ namespace\n\nvoid RunBenchmark(benchmark::State& state,\n Perspective<Navigation, Camera> const& perspective) {\n Satellites satellites;\n Planetarium planetarium = satellites.MakePlanetarium(perspective);\n RP2Lines<Length, Camera> lines;\n int total_lines = 0;\n int total_points = 0;\n int iterations = 0;\n constexpr Instant now = \"2000-01-21T04:41:30,5\"_TT;\n while (state.KeepRunning()) {\n lines = planetarium.PlotMethod2(satellites.GOES8Trajectory().Begin(),\n satellites.GOES8Trajectory().End(),\n now,\n \/*reverse=*\/false);\n state.PauseTiming();\n total_lines += lines.size();\n for (auto const& line : lines) {\n total_points += line.size();\n }\n ++iterations;\n state.ResumeTiming();\n }\n Length min_x = Infinity<Length>();\n Length min_y = Infinity<Length>();\n Length max_x = Infinity<Length>();\n Length max_y = Infinity<Length>();\n for (auto const& line : lines) {\n for (auto const& point : line) {\n min_x = std::min(min_x, point.x());\n min_y = std::min(min_y, point.y());\n max_x = std::max(max_x, point.x());\n max_y = std::max(max_y, point.y());\n }\n }\n state.SetLabel(std::to_string(total_points \/ iterations) + \" points in \" +\n std::to_string(total_lines \/ iterations) + \" within [\" +\n DebugString(min_x) + \", \" + DebugString(max_x) + \"] × [\" +\n DebugString(min_y) + \", \" + DebugString(max_y) + \"]\");\n}\n\nvoid BM_PlanetariumPlotMethod2NearPolarPerspective(benchmark::State& state) {\n RunBenchmark(state, PolarPerspective(near));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2NearPolarPerspective);\n\nvoid BM_PlanetariumPlotMethod2FarPolarPerspective(benchmark::State& state) {\n RunBenchmark(state, PolarPerspective(far));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2FarPolarPerspective);\n\nvoid BM_PlanetariumPlotMethod2NearEquatorialPerspective(\n benchmark::State& state) {\n RunBenchmark(state, EquatorialPerspective(near));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2NearEquatorialPerspective);\n\nvoid BM_PlanetariumPlotMethod2FarEquatorialPerspective(\n benchmark::State& state) {\n RunBenchmark(state, EquatorialPerspective(far));\n}\n\nBENCHMARK(BM_PlanetariumPlotMethod2FarEquatorialPerspective);\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include \"psinc\/Transport.h\"\n#include <emergent\/logger\/Logger.hpp>\n#include <regex>\n#include <set>\n\nusing namespace std;\nusing namespace emergent;\n\n#define WRITE_PIPE\t0x03\n#define READ_PIPE\t0x81\n\n\nnamespace psinc\n{\n\tTransport::Transport()\n\t{\n\t\tlibusb_init(&this->context);\n\n\t\tthis->legacy = !libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG);\n\t}\n\n\n\tTransport::~Transport()\n\t{\n\t\tthis->Release();\n\n\t\tif (!this->legacy)\n\t\t{\n\t\t\tlibusb_hotplug_deregister_callback(this->context, this->hotplug);\n\t\t}\n\n\t\tlibusb_exit(this->context);\n\t}\n\n\n\tbool Transport::Initialise(uint16_t product, string serial, std::function<void(bool)> onConnection, int timeout)\n\t{\n\t\tthis->serial\t\t= serial;\n\t\tthis->product\t\t= product;\n\t\tthis->onConnection\t= onConnection;\n\t\tthis->timeout\t\t= timeout;\n\n\t\tif (!this->legacy)\n\t\t{\n\t\t\tlibusb_hotplug_deregister_callback(this->context, this->hotplug);\n\t\t\tthis->registered = false;\n\t\t}\n\t\telse Log::Info(\"USB hotplug not supported on this platform, running in legacy mode\");\n\n\t\treturn true;\n\t}\n\n\n\tbool Transport::Connected()\n\t{\n\t\treturn this->handle;\n\t}\n\n\n\tint LIBUSB_CALL OnHotplug(libusb_context *context, libusb_device *device, libusb_hotplug_event event, void *data)\n\t{\n\t\treinterpret_cast<Transport *>(data)->pending.enqueue({ device, event });\n\t\treturn 0;\n\t}\n\n\n\tvoid Transport::Poll(int time)\n\t{\n\t\tif (this->legacy)\n\t\t{\n\t\t\tif (!this->handle) this->LegacyConnect();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this->registered)\n\t\t{\n\t\t\tauto events = (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);\n\n\t\t\tif (libusb_hotplug_register_callback(this->context, events, LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, this->product, LIBUSB_HOTPLUG_MATCH_ANY, &OnHotplug, this, &this->hotplug))\n\t\t\t{\n\t\t\t\tLog::Error(\"Unable to register USB hotplug callback\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis->registered = true;\n\t\t}\n\n\t\tstruct timeval tv = { 0, time * 1000 };\n\t\tlibusb_handle_events_timeout_completed(this->context, &tv, nullptr);\n\n\t\tPending item;\n\t\tif (this->pending.try_dequeue(item))\n\t\t{\n\t\t\tif (Valid(item.device, this->product))\n\t\t\t{\n\t\t\t\tif (item.event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT && this->handle)\n\t\t\t\t{\n\t\t\t\t\tif (item.device == libusb_get_device(this->handle))\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->cs.lock();\n\t\t\t\t\t\t\tthis->Release();\n\t\t\t\t\t\tthis->cs.unlock();\n\n\t\t\t\t\t\tif (this->onConnection) this->onConnection(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (item.event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED && !this->handle)\n\t\t\t\t{\n\t\t\t\t\tif (this->Claim(item.device) && this->onConnection)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->onConnection(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tbool Transport::Match(libusb_device_handle *device, int index)\n\t{\n\t\tunsigned char data[128];\n\n\t\tlibusb_get_string_descriptor_ascii(device, index, data, 128);\n\n\t\tthis->id = reinterpret_cast<char *>(data);\n\n\t\treturn this->serial.empty() ? true : regex_match(this->id, regex(this->serial));\n\t}\n\n\n\tbool Transport::Valid(libusb_device *device, uint16_t product)\n\t{\n\t\tstatic const set<uint16_t> VENDORS = { 0x0525 };\n\t\tlibusb_device_descriptor descriptor;\n\n\t\treturn libusb_get_device_descriptor(device, &descriptor) == 0\n\t\t\t&& VENDORS.count(descriptor.idVendor)\n\t\t\t&& descriptor.idProduct == product;\n\t}\n\n\n\tvoid Transport::LegacyConnect()\n\t{\n\t\tlibusb_device **list;\n\t\tlibusb_get_device_list(this->context, &list);\n\n\t\t\/\/ Loop through the list of connected USB devices\n\t\tfor (libusb_device **device = list; *device; device++)\n\t\t{\n\t\t\tif (Valid(*device, this->product))\n\t\t\t{\n\t\t\t\t\/\/ If a particular device matches the known vendor, product ID then attempt to claim it.\n\t\t\t\tif (this->Claim(*device))\n\t\t\t\t{\n\t\t\t\t\tif (this->onConnection) this->onConnection(true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlibusb_free_device_list(list, 1);\n\t}\n\n\n\tbool Transport::Claim(libusb_device *device)\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tlibusb_device_descriptor descriptor;\n\n\t\tif (libusb_get_device_descriptor(device, &descriptor) == 0)\n\t\t{\n\t\t\t\/\/ Attempt to open and claim the device\n\t\t\tif (libusb_open(device, &this->handle) == 0)\n\t\t\t{\n\t\t\t\t\/\/ If a serial number has been specified then check that this device matches it\n\t\t\t\tif (this->Match(this->handle, descriptor.iSerialNumber))\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: Disabled this while PSI is solving an issue with\n\t\t\t\t\t\/\/ the camera that causes it to get stuck in a strange state.\n\t\t\t\t\t\/\/if (libusb_set_configuration(this->handle, 1) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (libusb_claim_interface(this->handle, 0) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tLog::Info(\"%u: USB device claimed - %s\", Timestamp::LogTime(), this->id);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Claiming was unsuccessful so clean up\n\t\t\t\tlibusb_close(this->handle);\n\t\t\t\tthis->handle \t= nullptr;\n\t\t\t\tthis->id\t\t= \"\";\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\n\tvector<string> Transport::List(uint16_t product)\n\t{\n\t\tvector<string> result;\n\n\t\tunsigned char data[128];\n\t\tlibusb_device **list;\n\t\tlibusb_device_descriptor descriptor;\n\t\tlibusb_device_handle *handle;\n\t\tlibusb_context *context = nullptr;\n\n\t\tlibusb_init(&context);\n\t\tlibusb_get_device_list(context, &list);\n\n\t\tfor (libusb_device **device = list; *device; device++)\n\t\t{\n\t\t\tif (Valid(*device, product) && libusb_get_device_descriptor(*device, &descriptor) == 0)\n\t\t\t{\n\t\t\t\tif (libusb_open(*device, &handle) == 0)\n\t\t\t\t{\n\t\t\t\t\tlibusb_get_string_descriptor_ascii(handle, descriptor.iSerialNumber, data, 128);\n\n\t\t\t\t\tresult.push_back(reinterpret_cast<char *>(data));\n\n\t\t\t\t\tlibusb_close(handle);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlibusb_exit(context);\n\n\t\treturn result;\n\t}\n\n\n\tvoid Transport::Disconnect()\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tthis->Release();\n\t}\n\n\n\tvoid Transport::Release()\n\t{\n\t\tif (this->handle)\n\t\t{\n\t\t\t\/\/ Release the device and close the handle\n\t\t\tlibusb_release_interface(this->handle, 0);\n\t\t\tlibusb_close(this->handle);\n\n\t\t\tLog::Info(\"%u: USB deviced released - %s\", Timestamp::LogTime(), this->id);\n\n\t\t\tthis->handle\t= nullptr;\n\t\t\tthis->id\t\t= \"\";\n\t\t}\n\t}\n\n\n\n\tbool Transport::Reset()\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tif (this->handle)\n\t\t{\n\t\t\tif (libusb_reset_device(this->handle) != 0)\n\t\t\t{\n\t\t\t\t\/\/ Something has gone wrong with the reset and so the device appears\n\t\t\t\t\/\/ as if it has been reconnected. Therefore this handle is invalid\n\t\t\t\t\/\/ and must be cleaned up.\n\t\t\t\tthis->Release();\n\n\t\t\t\tLog::Error(\"Problem resetting USB device, handle has been released\");\n\t\t\t}\n\t\t}\n\n\t\treturn this->handle;\n\t}\n\n\n\tbool Transport::Transfer(Buffer<byte> *send, Buffer<byte> *receive, atomic<bool> &waiting, bool check, bool truncate)\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\treturn this->handle ? this->Transfer(send, true, check, false) && (waiting = true) && this->Transfer(receive, false, check, truncate) : false;\n\t}\n\n\n\tbool Transport::Transfer(Buffer<byte> *buffer, bool write, bool check, bool truncate)\n\t{\n\t\tif (buffer)\n\t\t{\n\t\t\tint transferred;\n\t\t\tbool result\t= false;\n\t\t\tint err\t\t= libusb_bulk_transfer(this->handle, write ? WRITE_PIPE : READ_PIPE, *buffer, buffer->Size(), &transferred, this->timeout);\n\n\t\t\tif (!err)\n\t\t\t{\n\t\t\t\tresult = (write || check) ? transferred == buffer->Size() : true;\n\n\t\t\t\t\/\/ When requested, truncate the buffer to the size of data actually received.\n\t\t\t\tif (!write && result && truncate)\n\t\t\t\t{\n\t\t\t\t\tbuffer->Truncate(transferred);\n\t\t\t\t}\n\n\t\t\t\tif (!result)\n\t\t\t\t{\n\t\t\t\t\tLog::Error(\n\t\t\t\t\t\t\"%u: USB device %s - Incomplete transfer when %s (%d of %d bytes)\",\n\t\t\t\t\t\tTimestamp::LogTime(),\n\t\t\t\t\t\tthis->id,\n\t\t\t\t\t\twrite ? \"writing\" : \"reading\",\n\t\t\t\t\t\ttransferred,\n\t\t\t\t\t\tbuffer->Size()\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this->legacy && (err == LIBUSB_ERROR_NO_DEVICE || err == LIBUSB_ERROR_IO))\n\t\t\t{\n\t\t\t\tLog::Error(\"%u: USB device %s - Device has been disconnected\", Timestamp::LogTime(), this->id);\n\t\t\t\tthis->Release();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog::Error(\"%u: USB device %s - Transfer error %d when %s\", Timestamp::LogTime(), this->id, err, write ? \"writing\" : \"reading\");\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\treturn true;\n\t}\n}\n\n<commit_msg>Added new PSI vendor ID. Original one remains for backwards compatibility with previous generation cameras.<commit_after>#include \"psinc\/Transport.h\"\n#include <emergent\/logger\/Logger.hpp>\n#include <regex>\n#include <set>\n\nusing namespace std;\nusing namespace emergent;\n\n#define WRITE_PIPE\t0x03\n#define READ_PIPE\t0x81\n\n\nnamespace psinc\n{\n\tTransport::Transport()\n\t{\n\t\tlibusb_init(&this->context);\n\n\t\tthis->legacy = !libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG);\n\t}\n\n\n\tTransport::~Transport()\n\t{\n\t\tthis->Release();\n\n\t\tif (!this->legacy)\n\t\t{\n\t\t\tlibusb_hotplug_deregister_callback(this->context, this->hotplug);\n\t\t}\n\n\t\tlibusb_exit(this->context);\n\t}\n\n\n\tbool Transport::Initialise(uint16_t product, string serial, std::function<void(bool)> onConnection, int timeout)\n\t{\n\t\tthis->serial\t\t= serial;\n\t\tthis->product\t\t= product;\n\t\tthis->onConnection\t= onConnection;\n\t\tthis->timeout\t\t= timeout;\n\n\t\tif (!this->legacy)\n\t\t{\n\t\t\tlibusb_hotplug_deregister_callback(this->context, this->hotplug);\n\t\t\tthis->registered = false;\n\t\t}\n\t\telse Log::Info(\"USB hotplug not supported on this platform, running in legacy mode\");\n\n\t\treturn true;\n\t}\n\n\n\tbool Transport::Connected()\n\t{\n\t\treturn this->handle;\n\t}\n\n\n\tint LIBUSB_CALL OnHotplug(libusb_context *context, libusb_device *device, libusb_hotplug_event event, void *data)\n\t{\n\t\treinterpret_cast<Transport *>(data)->pending.enqueue({ device, event });\n\t\treturn 0;\n\t}\n\n\n\tvoid Transport::Poll(int time)\n\t{\n\t\tif (this->legacy)\n\t\t{\n\t\t\tif (!this->handle) this->LegacyConnect();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this->registered)\n\t\t{\n\t\t\tauto events = (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);\n\n\t\t\tif (libusb_hotplug_register_callback(this->context, events, LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, this->product, LIBUSB_HOTPLUG_MATCH_ANY, &OnHotplug, this, &this->hotplug))\n\t\t\t{\n\t\t\t\tLog::Error(\"Unable to register USB hotplug callback\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis->registered = true;\n\t\t}\n\n\t\tstruct timeval tv = { 0, time * 1000 };\n\t\tlibusb_handle_events_timeout_completed(this->context, &tv, nullptr);\n\n\t\tPending item;\n\t\tif (this->pending.try_dequeue(item))\n\t\t{\n\t\t\tif (Valid(item.device, this->product))\n\t\t\t{\n\t\t\t\tif (item.event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT && this->handle)\n\t\t\t\t{\n\t\t\t\t\tif (item.device == libusb_get_device(this->handle))\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->cs.lock();\n\t\t\t\t\t\t\tthis->Release();\n\t\t\t\t\t\tthis->cs.unlock();\n\n\t\t\t\t\t\tif (this->onConnection) this->onConnection(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (item.event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED && !this->handle)\n\t\t\t\t{\n\t\t\t\t\tif (this->Claim(item.device) && this->onConnection)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->onConnection(true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tbool Transport::Match(libusb_device_handle *device, int index)\n\t{\n\t\tunsigned char data[128];\n\n\t\tlibusb_get_string_descriptor_ascii(device, index, data, 128);\n\n\t\tthis->id = reinterpret_cast<char *>(data);\n\n\t\treturn this->serial.empty() ? true : regex_match(this->id, regex(this->serial));\n\t}\n\n\n\tbool Transport::Valid(libusb_device *device, uint16_t product)\n\t{\n\t\tstatic const set<uint16_t> VENDORS = { 0x2dd8, 0x0525 };\n\t\tlibusb_device_descriptor descriptor;\n\n\t\treturn libusb_get_device_descriptor(device, &descriptor) == 0\n\t\t\t&& VENDORS.count(descriptor.idVendor)\n\t\t\t&& descriptor.idProduct == product;\n\t}\n\n\n\tvoid Transport::LegacyConnect()\n\t{\n\t\tlibusb_device **list;\n\t\tlibusb_get_device_list(this->context, &list);\n\n\t\t\/\/ Loop through the list of connected USB devices\n\t\tfor (libusb_device **device = list; *device; device++)\n\t\t{\n\t\t\tif (Valid(*device, this->product))\n\t\t\t{\n\t\t\t\t\/\/ If a particular device matches the known vendor, product ID then attempt to claim it.\n\t\t\t\tif (this->Claim(*device))\n\t\t\t\t{\n\t\t\t\t\tif (this->onConnection) this->onConnection(true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlibusb_free_device_list(list, 1);\n\t}\n\n\n\tbool Transport::Claim(libusb_device *device)\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tlibusb_device_descriptor descriptor;\n\n\t\tif (libusb_get_device_descriptor(device, &descriptor) == 0)\n\t\t{\n\t\t\t\/\/ Attempt to open and claim the device\n\t\t\tif (libusb_open(device, &this->handle) == 0)\n\t\t\t{\n\t\t\t\t\/\/ If a serial number has been specified then check that this device matches it\n\t\t\t\tif (this->Match(this->handle, descriptor.iSerialNumber))\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: Disabled this while PSI is solving an issue with\n\t\t\t\t\t\/\/ the camera that causes it to get stuck in a strange state.\n\t\t\t\t\t\/\/if (libusb_set_configuration(this->handle, 1) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (libusb_claim_interface(this->handle, 0) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tLog::Info(\"%u: USB device claimed - %s\", Timestamp::LogTime(), this->id);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Claiming was unsuccessful so clean up\n\t\t\t\tlibusb_close(this->handle);\n\t\t\t\tthis->handle \t= nullptr;\n\t\t\t\tthis->id\t\t= \"\";\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\n\tvector<string> Transport::List(uint16_t product)\n\t{\n\t\tvector<string> result;\n\n\t\tunsigned char data[128];\n\t\tlibusb_device **list;\n\t\tlibusb_device_descriptor descriptor;\n\t\tlibusb_device_handle *handle;\n\t\tlibusb_context *context = nullptr;\n\n\t\tlibusb_init(&context);\n\t\tlibusb_get_device_list(context, &list);\n\n\t\tfor (libusb_device **device = list; *device; device++)\n\t\t{\n\t\t\tif (Valid(*device, product) && libusb_get_device_descriptor(*device, &descriptor) == 0)\n\t\t\t{\n\t\t\t\tif (libusb_open(*device, &handle) == 0)\n\t\t\t\t{\n\t\t\t\t\tlibusb_get_string_descriptor_ascii(handle, descriptor.iSerialNumber, data, 128);\n\n\t\t\t\t\tresult.push_back(reinterpret_cast<char *>(data));\n\n\t\t\t\t\tlibusb_close(handle);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlibusb_exit(context);\n\n\t\treturn result;\n\t}\n\n\n\tvoid Transport::Disconnect()\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tthis->Release();\n\t}\n\n\n\tvoid Transport::Release()\n\t{\n\t\tif (this->handle)\n\t\t{\n\t\t\t\/\/ Release the device and close the handle\n\t\t\tlibusb_release_interface(this->handle, 0);\n\t\t\tlibusb_close(this->handle);\n\n\t\t\tLog::Info(\"%u: USB deviced released - %s\", Timestamp::LogTime(), this->id);\n\n\t\t\tthis->handle\t= nullptr;\n\t\t\tthis->id\t\t= \"\";\n\t\t}\n\t}\n\n\n\n\tbool Transport::Reset()\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\tif (this->handle)\n\t\t{\n\t\t\tif (libusb_reset_device(this->handle) != 0)\n\t\t\t{\n\t\t\t\t\/\/ Something has gone wrong with the reset and so the device appears\n\t\t\t\t\/\/ as if it has been reconnected. Therefore this handle is invalid\n\t\t\t\t\/\/ and must be cleaned up.\n\t\t\t\tthis->Release();\n\n\t\t\t\tLog::Error(\"Problem resetting USB device, handle has been released\");\n\t\t\t}\n\t\t}\n\n\t\treturn this->handle;\n\t}\n\n\n\tbool Transport::Transfer(Buffer<byte> *send, Buffer<byte> *receive, atomic<bool> &waiting, bool check, bool truncate)\n\t{\n\t\tlock_guard<mutex> lock(this->cs);\n\n\t\treturn this->handle ? this->Transfer(send, true, check, false) && (waiting = true) && this->Transfer(receive, false, check, truncate) : false;\n\t}\n\n\n\tbool Transport::Transfer(Buffer<byte> *buffer, bool write, bool check, bool truncate)\n\t{\n\t\tif (buffer)\n\t\t{\n\t\t\tint transferred;\n\t\t\tbool result\t= false;\n\t\t\tint err\t\t= libusb_bulk_transfer(this->handle, write ? WRITE_PIPE : READ_PIPE, *buffer, buffer->Size(), &transferred, this->timeout);\n\n\t\t\tif (!err)\n\t\t\t{\n\t\t\t\tresult = (write || check) ? transferred == buffer->Size() : true;\n\n\t\t\t\t\/\/ When requested, truncate the buffer to the size of data actually received.\n\t\t\t\tif (!write && result && truncate)\n\t\t\t\t{\n\t\t\t\t\tbuffer->Truncate(transferred);\n\t\t\t\t}\n\n\t\t\t\tif (!result)\n\t\t\t\t{\n\t\t\t\t\tLog::Error(\n\t\t\t\t\t\t\"%u: USB device %s - Incomplete transfer when %s (%d of %d bytes)\",\n\t\t\t\t\t\tTimestamp::LogTime(),\n\t\t\t\t\t\tthis->id,\n\t\t\t\t\t\twrite ? \"writing\" : \"reading\",\n\t\t\t\t\t\ttransferred,\n\t\t\t\t\t\tbuffer->Size()\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (this->legacy && (err == LIBUSB_ERROR_NO_DEVICE || err == LIBUSB_ERROR_IO))\n\t\t\t{\n\t\t\t\tLog::Error(\"%u: USB device %s - Device has been disconnected\", Timestamp::LogTime(), this->id);\n\t\t\t\tthis->Release();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog::Error(\"%u: USB device %s - Transfer error %d when %s\", Timestamp::LogTime(), this->id, err, write ? \"writing\" : \"reading\");\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\treturn true;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file hoeffding_split_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of the HoeffdingSplit class.\n *\/\n#ifndef __MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_SPLIT_IMPL_HPP\n#define __MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_SPLIT_IMPL_HPP\n\nnamespace mlpack {\nnamespace tree {\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nHoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::HoeffdingSplit(const size_t dimensionality,\n const size_t numClasses,\n const data::DatasetInfo& datasetInfo,\n const double successProbability,\n const size_t maxSamples,\n std::unordered_map<size_t, std::pair<size_t, size_t>>*\n dimensionMappingsIn) :\n dimensionMappings((dimensionMappingsIn != NULL) ? dimensionMappingsIn :\n new std::unordered_map<size_t, std::pair<size_t, size_t>>()),\n ownsMappings(dimensionMappingsIn == NULL),\n numSamples(0),\n numClasses(numClasses),\n maxSamples(maxSamples),\n datasetInfo(datasetInfo),\n successProbability(successProbability),\n splitDimension(size_t(-1)),\n categoricalSplit(0),\n numericSplit()\n{\n \/\/ Do we need to generate the mappings too?\n if (ownsMappings)\n {\n for (size_t i = 0; i < dimensionality; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n {\n categoricalSplits.push_back(\n CategoricalSplitType(datasetInfo.NumMappings(i), numClasses));\n (*dimensionMappings)[i] = std::make_pair(data::Datatype::categorical,\n categoricalSplits.size() - 1);\n }\n else\n {\n numericSplits.push_back(NumericSplitType(numClasses));\n (*dimensionMappings)[i] = std::make_pair(data::Datatype::numeric,\n numericSplits.size() - 1);\n }\n }\n }\n else\n {\n for (size_t i = 0; i < dimensionality; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n {\n categoricalSplits.push_back(\n CategoricalSplitType(datasetInfo.NumMappings(i), numClasses));\n }\n else\n {\n numericSplits.push_back(NumericSplitType(numClasses));\n }\n }\n }\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nHoeffdingSplit<FitnessFunction, NumericSplitType, CategoricalSplitType>::\n ~HoeffdingSplit()\n{\n if (ownsMappings)\n delete dimensionMappings;\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\ntemplate<typename VecType>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Train(const VecType& point, const size_t label)\n{\n if (splitDimension == size_t(-1))\n {\n ++numSamples;\n size_t numericIndex = 0;\n size_t categoricalIndex = 0;\n for (size_t i = 0; i < point.n_rows; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n categoricalSplits[categoricalIndex++].Train(point[i], label);\n else if (datasetInfo.Type(i) == data::Datatype::numeric)\n numericSplits[numericIndex++].Train(point[i], label);\n }\n }\n else\n {\n \/\/ Already split.\n \/\/ But we should probably pass it down anyway.\n }\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::SplitCheck()\n{\n \/\/ Do nothing if we've already split.\n if (splitDimension != size_t(-1))\n return 0;\n\n \/\/ Check the fitness of each dimension. Then we'll use a Hoeffding bound\n \/\/ somehow.\n\n \/\/ Calculate epsilon, the value we need things to be greater than.\n const double rSquared = std::pow(FitnessFunction::Range(numClasses), 2.0);\n const double epsilon = std::sqrt(rSquared *\n std::log(1.0 \/ (1.0 - successProbability)) \/ (2 * numSamples));\n\n arma::vec gains(categoricalSplits.size() + numericSplits.size());\n for (size_t i = 0; i < gains.n_elem; ++i)\n {\n size_t type = dimensionMappings->at(i).first;\n size_t index = dimensionMappings->at(i).second;\n if (type == data::Datatype::categorical)\n gains[i] = categoricalSplits[index].EvaluateFitnessFunction();\n else if (type == data::Datatype::numeric)\n gains[i] = numericSplits[index].EvaluateFitnessFunction();\n }\n\n \/\/ Now find the largest and second-largest.\n double largest = -DBL_MAX;\n size_t largestIndex = 0;\n double secondLargest = -DBL_MAX;\n for (size_t i = 0; i < gains.n_elem; ++i)\n {\n if (gains[i] > largest)\n {\n secondLargest = largest;\n largest = gains[i];\n largestIndex = i;\n }\n else if (gains[i] > secondLargest)\n {\n secondLargest = gains[i];\n }\n }\n\n \/\/ Are these far enough apart to split?\n if (largest - secondLargest > epsilon || numSamples > maxSamples)\n {\n \/\/ Split!\n splitDimension = largestIndex;\n if (datasetInfo.Type(largestIndex) == data::Datatype::categorical)\n {\n \/\/ I don't know if this should be here.\n majorityClass = categoricalSplits[largestIndex].MajorityClass();\n return datasetInfo.NumMappings(largestIndex);\n }\n else\n {\n majorityClass = numericSplits[largestIndex].MajorityClass();\n return numericSplits[largestIndex].Bins();\n }\n }\n else\n {\n return 0; \/\/ Don't split.\n }\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::MajorityClass() const\n{\n \/\/ If the node is not split yet, we have to grab the majority class from any\n \/\/ of the structures figuring out what to split on.\n if (splitDimension == size_t(-1))\n {\n \/\/ Grab majority class from splits.\n if (categoricalSplits.size() > 0)\n majorityClass = categoricalSplits[0].MajorityClass();\n else\n majorityClass = numericSplits[0].MajorityClass();\n }\n\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\nsize_t& HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::MajorityClass()\n{\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename VecType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::CalculateDirection(const VecType& point) const\n{\n \/\/ Don't call this before the node is split...\n if (datasetInfo.Type(splitDimension) == data::Datatype::numeric)\n return numericSplit.CalculateDirection(point[splitDimension]);\n else if (datasetInfo.Type(splitDimension) == data::Datatype::categorical)\n return categoricalSplit.CalculateDirection(point[splitDimension]);\n else\n return 0; \/\/ Not sure what to do here...\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename VecType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Classify(const VecType& \/* point *\/) const\n{\n \/\/ We're a leaf (or being considered a leaf), so classify based on what we\n \/\/ know.\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename StreamingDecisionTreeType>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::CreateChildren(std::vector<StreamingDecisionTreeType>& children)\n{\n \/\/ Create the children.\n arma::Col<size_t> childMajorities;\n if (dimensionMappings->at(splitDimension).first ==\n data::Datatype::categorical)\n {\n categoricalSplits[dimensionMappings->at(splitDimension).second].Split(\n childMajorities, categoricalSplit);\n }\n else if (dimensionMappings->at(splitDimension).first ==\n data::Datatype::numeric)\n {\n numericSplits[dimensionMappings->at(splitDimension).second].Split(\n childMajorities, numericSplit);\n }\n\n \/\/ We already know what the splitDimension will be.\n const size_t dimensionality = numericSplits.size() + categoricalSplits.size();\n for (size_t i = 0; i < childMajorities.n_elem; ++i)\n {\n children.push_back(StreamingDecisionTreeType(datasetInfo, dimensionality,\n numClasses, successProbability, numSamples, dimensionMappings));\n children[i].MajorityClass() = childMajorities[i];\n }\n\n \/\/ Eliminate now-unnecessary split information.\n numericSplits.clear();\n categoricalSplits.clear();\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename Archive>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Serialize(Archive& ar, const unsigned int \/* version *\/)\n{\n using data::CreateNVP;\n\n ar & CreateNVP(splitDimension, \"splitDimension\");\n ar & CreateNVP(dimensionMappings, \"dimensionMappings\");\n \/\/ What to do here about ownership...?\n if (Archive::is_loading::value)\n ownsMappings = true;\n\n \/\/ Depending on whether or not we have split yet, we may need to save\n \/\/ different things.\n if (splitDimension == size_t(-1))\n {\n \/\/ We have not yet split. So we have to serialize the splits.\n ar & CreateNVP(numericSplits, \"numericSplits\");\n ar & CreateNVP(categoricalSplits, \"categoricalSplits\");\n\n ar & CreateNVP(numSamples, \"numSamples\");\n ar & CreateNVP(numClasses, \"numClasses\");\n ar & CreateNVP(maxSamples, \"maxSamples\");\n ar & CreateNVP(successProbability, \"successProbability\");\n\n if (Archive::is_loading::value)\n {\n \/\/ Clear things we don't need.\n majorityClass = 0;\n categoricalSplit = CategoricalSplitType::SplitInfo();\n numericSplit = NumericSplitType::SplitInfo();\n }\n }\n else\n {\n \/\/ We have split, so we only need to cache the numeric and categorical\n \/\/ split.\n ar & CreateNVP(categoricalSplit, \"categoricalSplit\");\n ar & CreateNVP(numericSplit, \"numericSplit\");\n ar & CreateNVP(majorityClass, \"majorityClass\");\n\n if (Archive::is_loading::value)\n {\n numericSplits.clear();\n categoricalSplits.clear();\n\n numSamples = 0;\n numClasses = 0;\n maxSamples = 0;\n successProbability = 0.0;\n }\n }\n}\n\n} \/\/ namespace tree\n} \/\/ namespace mlpack\n\n#endif\n<commit_msg>Fix compilation issue.<commit_after>\/**\n * @file hoeffding_split_impl.hpp\n * @author Ryan Curtin\n *\n * Implementation of the HoeffdingSplit class.\n *\/\n#ifndef __MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_SPLIT_IMPL_HPP\n#define __MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_SPLIT_IMPL_HPP\n\nnamespace mlpack {\nnamespace tree {\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nHoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::HoeffdingSplit(const size_t dimensionality,\n const size_t numClasses,\n const data::DatasetInfo& datasetInfo,\n const double successProbability,\n const size_t maxSamples,\n std::unordered_map<size_t, std::pair<size_t, size_t>>*\n dimensionMappingsIn) :\n dimensionMappings((dimensionMappingsIn != NULL) ? dimensionMappingsIn :\n new std::unordered_map<size_t, std::pair<size_t, size_t>>()),\n ownsMappings(dimensionMappingsIn == NULL),\n numSamples(0),\n numClasses(numClasses),\n maxSamples(maxSamples),\n datasetInfo(datasetInfo),\n successProbability(successProbability),\n splitDimension(size_t(-1)),\n categoricalSplit(0),\n numericSplit()\n{\n \/\/ Do we need to generate the mappings too?\n if (ownsMappings)\n {\n for (size_t i = 0; i < dimensionality; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n {\n categoricalSplits.push_back(\n CategoricalSplitType(datasetInfo.NumMappings(i), numClasses));\n (*dimensionMappings)[i] = std::make_pair(data::Datatype::categorical,\n categoricalSplits.size() - 1);\n }\n else\n {\n numericSplits.push_back(NumericSplitType(numClasses));\n (*dimensionMappings)[i] = std::make_pair(data::Datatype::numeric,\n numericSplits.size() - 1);\n }\n }\n }\n else\n {\n for (size_t i = 0; i < dimensionality; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n {\n categoricalSplits.push_back(\n CategoricalSplitType(datasetInfo.NumMappings(i), numClasses));\n }\n else\n {\n numericSplits.push_back(NumericSplitType(numClasses));\n }\n }\n }\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nHoeffdingSplit<FitnessFunction, NumericSplitType, CategoricalSplitType>::\n ~HoeffdingSplit()\n{\n if (ownsMappings)\n delete dimensionMappings;\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\ntemplate<typename VecType>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Train(const VecType& point, const size_t label)\n{\n if (splitDimension == size_t(-1))\n {\n ++numSamples;\n size_t numericIndex = 0;\n size_t categoricalIndex = 0;\n for (size_t i = 0; i < point.n_rows; ++i)\n {\n if (datasetInfo.Type(i) == data::Datatype::categorical)\n categoricalSplits[categoricalIndex++].Train(point[i], label);\n else if (datasetInfo.Type(i) == data::Datatype::numeric)\n numericSplits[numericIndex++].Train(point[i], label);\n }\n }\n else\n {\n \/\/ Already split.\n \/\/ But we should probably pass it down anyway.\n }\n}\n\ntemplate<typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::SplitCheck()\n{\n \/\/ Do nothing if we've already split.\n if (splitDimension != size_t(-1))\n return 0;\n\n \/\/ Check the fitness of each dimension. Then we'll use a Hoeffding bound\n \/\/ somehow.\n\n \/\/ Calculate epsilon, the value we need things to be greater than.\n const double rSquared = std::pow(FitnessFunction::Range(numClasses), 2.0);\n const double epsilon = std::sqrt(rSquared *\n std::log(1.0 \/ (1.0 - successProbability)) \/ (2 * numSamples));\n\n arma::vec gains(categoricalSplits.size() + numericSplits.size());\n for (size_t i = 0; i < gains.n_elem; ++i)\n {\n size_t type = dimensionMappings->at(i).first;\n size_t index = dimensionMappings->at(i).second;\n if (type == data::Datatype::categorical)\n gains[i] = categoricalSplits[index].EvaluateFitnessFunction();\n else if (type == data::Datatype::numeric)\n gains[i] = numericSplits[index].EvaluateFitnessFunction();\n }\n\n \/\/ Now find the largest and second-largest.\n double largest = -DBL_MAX;\n size_t largestIndex = 0;\n double secondLargest = -DBL_MAX;\n for (size_t i = 0; i < gains.n_elem; ++i)\n {\n if (gains[i] > largest)\n {\n secondLargest = largest;\n largest = gains[i];\n largestIndex = i;\n }\n else if (gains[i] > secondLargest)\n {\n secondLargest = gains[i];\n }\n }\n\n \/\/ Are these far enough apart to split?\n if (largest - secondLargest > epsilon || numSamples > maxSamples)\n {\n \/\/ Split!\n splitDimension = largestIndex;\n if (datasetInfo.Type(largestIndex) == data::Datatype::categorical)\n {\n \/\/ I don't know if this should be here.\n majorityClass = categoricalSplits[largestIndex].MajorityClass();\n return datasetInfo.NumMappings(largestIndex);\n }\n else\n {\n majorityClass = numericSplits[largestIndex].MajorityClass();\n return numericSplits[largestIndex].Bins();\n }\n }\n else\n {\n return 0; \/\/ Don't split.\n }\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::MajorityClass() const\n{\n \/\/ If the node is not split yet, we have to grab the majority class from any\n \/\/ of the structures figuring out what to split on.\n if (splitDimension == size_t(-1))\n {\n \/\/ Grab majority class from splits.\n if (categoricalSplits.size() > 0)\n majorityClass = categoricalSplits[0].MajorityClass();\n else\n majorityClass = numericSplits[0].MajorityClass();\n }\n\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\nsize_t& HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::MajorityClass()\n{\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename VecType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::CalculateDirection(const VecType& point) const\n{\n \/\/ Don't call this before the node is split...\n if (datasetInfo.Type(splitDimension) == data::Datatype::numeric)\n return numericSplit.CalculateDirection(point[splitDimension]);\n else if (datasetInfo.Type(splitDimension) == data::Datatype::categorical)\n return categoricalSplit.CalculateDirection(point[splitDimension]);\n else\n return 0; \/\/ Not sure what to do here...\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename VecType>\nsize_t HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Classify(const VecType& \/* point *\/) const\n{\n \/\/ We're a leaf (or being considered a leaf), so classify based on what we\n \/\/ know.\n return majorityClass;\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename StreamingDecisionTreeType>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::CreateChildren(std::vector<StreamingDecisionTreeType>& children)\n{\n \/\/ Create the children.\n arma::Col<size_t> childMajorities;\n if (dimensionMappings->at(splitDimension).first ==\n data::Datatype::categorical)\n {\n categoricalSplits[dimensionMappings->at(splitDimension).second].Split(\n childMajorities, categoricalSplit);\n }\n else if (dimensionMappings->at(splitDimension).first ==\n data::Datatype::numeric)\n {\n numericSplits[dimensionMappings->at(splitDimension).second].Split(\n childMajorities, numericSplit);\n }\n\n \/\/ We already know what the splitDimension will be.\n const size_t dimensionality = numericSplits.size() + categoricalSplits.size();\n for (size_t i = 0; i < childMajorities.n_elem; ++i)\n {\n children.push_back(StreamingDecisionTreeType(datasetInfo, dimensionality,\n numClasses, successProbability, numSamples, dimensionMappings));\n children[i].MajorityClass() = childMajorities[i];\n }\n\n \/\/ Eliminate now-unnecessary split information.\n numericSplits.clear();\n categoricalSplits.clear();\n}\n\ntemplate<\n typename FitnessFunction,\n typename NumericSplitType,\n typename CategoricalSplitType\n>\ntemplate<typename Archive>\nvoid HoeffdingSplit<\n FitnessFunction,\n NumericSplitType,\n CategoricalSplitType\n>::Serialize(Archive& ar, const unsigned int \/* version *\/)\n{\n using data::CreateNVP;\n\n ar & CreateNVP(splitDimension, \"splitDimension\");\n ar & CreateNVP(dimensionMappings, \"dimensionMappings\");\n \/\/ What to do here about ownership...?\n if (Archive::is_loading::value)\n ownsMappings = true;\n\n \/\/ Depending on whether or not we have split yet, we may need to save\n \/\/ different things.\n if (splitDimension == size_t(-1))\n {\n \/\/ We have not yet split. So we have to serialize the splits.\n ar & CreateNVP(numericSplits, \"numericSplits\");\n ar & CreateNVP(categoricalSplits, \"categoricalSplits\");\n\n ar & CreateNVP(numSamples, \"numSamples\");\n ar & CreateNVP(numClasses, \"numClasses\");\n ar & CreateNVP(maxSamples, \"maxSamples\");\n ar & CreateNVP(successProbability, \"successProbability\");\n\n if (Archive::is_loading::value)\n {\n \/\/ Clear things we don't need.\n majorityClass = 0;\n categoricalSplit = typename CategoricalSplitType::SplitInfo(numClasses);\n numericSplit = typename NumericSplitType::SplitInfo();\n }\n }\n else\n {\n \/\/ We have split, so we only need to cache the numeric and categorical\n \/\/ split.\n ar & CreateNVP(categoricalSplit, \"categoricalSplit\");\n ar & CreateNVP(numericSplit, \"numericSplit\");\n ar & CreateNVP(majorityClass, \"majorityClass\");\n\n if (Archive::is_loading::value)\n {\n numericSplits.clear();\n categoricalSplits.clear();\n\n numSamples = 0;\n numClasses = 0;\n maxSamples = 0;\n successProbability = 0.0;\n }\n }\n}\n\n} \/\/ namespace tree\n} \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <ctime>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <utils.hpp>\n#include <SNR.hpp>\n\n\nint main(int argc, char *argv[]) {\n std::string typeName;\n\tAstroData::Observation observation;\n PulsarSearch::snrDedispersedConf dConf;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n typeName = args.getSwitchArgument< std::string >(\"-type\");\n observation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n dConf.setNrSamplesPerBlock(args.getSwitchArgument< unsigned int >(\"-db\"));\n observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n\t\tobservation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, 0.0);\n\t} catch ( isa::utils::SwitchNotFound &err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n } catch ( std::exception &err ) {\n std::cerr << \"Usage: \" << argv[0] << \" -type ... -padding ... -db ... -dms ... -samples ...\" << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Generate kernel\n std::string * code;\n code = PulsarSearch::getSNRDedispersedOpenCL(dConf, typeName, observation);\n std::cout << *code << std::endl;\n\n\treturn 0;\n}\n\n<commit_msg>Format fix.<commit_after>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <ctime>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <utils.hpp>\n#include <SNR.hpp>\n\n\nint main(int argc, char *argv[]) {\n std::string typeName;\n\tAstroData::Observation observation;\n PulsarSearch::snrDedispersedConf dConf;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n typeName = args.getSwitchArgument< std::string >(\"-type\");\n observation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n dConf.setNrSamplesPerBlock(args.getSwitchArgument< unsigned int >(\"-sb\"));\n observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n\t\tobservation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, 0.0);\n\t} catch ( isa::utils::SwitchNotFound &err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n } catch ( std::exception &err ) {\n std::cerr << \"Usage: \" << argv[0] << \" -type ... -padding ... -sb ... -dms ... -samples ...\" << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Generate kernel\n std::string * code;\n code = PulsarSearch::getSNRDedispersedOpenCL(dConf, typeName, observation);\n std::cout << *code << std::endl;\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nstruct padded_length {\n volatile u64 v_ __mpalign__;\n __padout__;\n};\n\n\/\/ Compile-time max number of workers\n#define NWORKERS (NCPU-1)\nstruct uwq_ipcbuf {\n \/\/ Run-time max number of workers\n u64 maxworkers __mpalign__;\n padded_length len[NWORKERS]__mpalign__;\n};\n\n#if defined (XV6_KERNEL)\nbool uwq_trywork(void);\n\nclass uwq;\n\nclass uwq_worker {\n uwq_worker(uwq*, proc*);\n long wait();\n void exit();\n\n uwq* uwq_;\n proc *proc_;\n bool running_;\n struct spinlock lock_;\n struct condvar cv_;\n\n NEW_DELETE_OPS(uwq_worker);\n};\n\nclass uwq : public referenced, public rcu_freed {\n friend class uwq_worker;\n\n static uwq* alloc(proc_pgmap* pgmap, vmap* vmap,\n filetable *ftable, uptr uentry);\n bool haswork() const;\n bool tryworker();\n\n virtual void do_gc(void) { delete this; }\n\nprotected:\n virtual void onzero() const;\n\nprivate:\n uwq(proc_pgmap* pgmap, vmap* vmap,\n filetable* ftable, uwq_ipcbuf *ipc, uptr uentry);\n ~uwq();\n uwq& operator=(const uwq&);\n uwq(const uwq& x);\n proc* allocworker();\n void finish();\n NEW_DELETE_OPS(uwq);\n\n struct spinlock lock_;\n proc_pgmap *pgmap_;\n vmap* vmap_;\n filetable* ftable_;\n uwq_ipcbuf* ipc_;\n uptr uentry_;\n std::atomic<uptr> ustack_;\n std::atomic<u64> uref_;\n\n std::atomic<uwq_worker*> worker_[NWORKERS];\n};\n#endif\n<commit_msg>Fix class struct mismatch in uwq.hh<commit_after>#pragma once\n\nstruct padded_length {\n volatile u64 v_ __mpalign__;\n __padout__;\n};\n\n\/\/ Compile-time max number of workers\n#define NWORKERS (NCPU-1)\nstruct uwq_ipcbuf {\n \/\/ Run-time max number of workers\n u64 maxworkers __mpalign__;\n padded_length len[NWORKERS]__mpalign__;\n};\n\n#if defined (XV6_KERNEL)\nbool uwq_trywork(void);\n\nclass uwq;\n\nclass uwq_worker {\npublic:\n uwq_worker(uwq*, proc*);\n long wait();\n void exit();\n\n uwq* uwq_;\n proc *proc_;\n bool running_;\n struct spinlock lock_;\n struct condvar cv_;\n\n NEW_DELETE_OPS(uwq_worker);\n};\n\nclass uwq : public referenced, public rcu_freed {\n friend class uwq_worker;\n\npublic:\n static uwq* alloc(proc_pgmap* pgmap, vmap* vmap,\n filetable *ftable, uptr uentry);\n bool haswork() const;\n bool tryworker();\n\n virtual void do_gc(void) { delete this; }\n\nprotected:\n virtual void onzero() const;\n\nprivate:\n uwq(proc_pgmap* pgmap, vmap* vmap,\n filetable* ftable, uwq_ipcbuf *ipc, uptr uentry);\n ~uwq();\n uwq& operator=(const uwq&);\n uwq(const uwq& x);\n proc* allocworker();\n void finish();\n NEW_DELETE_OPS(uwq);\n\n struct spinlock lock_;\n proc_pgmap *pgmap_;\n vmap* vmap_;\n filetable* ftable_;\n uwq_ipcbuf* ipc_;\n uptr uentry_;\n std::atomic<uptr> ustack_;\n std::atomic<u64> uref_;\n\n std::atomic<uwq_worker*> worker_[NWORKERS];\n};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @brief Implementation of CorryvreckanWriter module\n * @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"CorryvreckanWriterModule.hpp\"\n\n#include <Math\/RotationZYX.h>\n\n#include <fstream>\n#include <string>\n#include <utility>\n\n#include \"core\/utils\/file.h\"\n#include \"core\/utils\/log.h\"\n\nusing namespace allpix;\n\nCorryvreckanWriterModule::CorryvreckanWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geoManager)\n : Module(config), messenger_(messenger), geometryManager_(geoManager) {\n\n \/\/ Require PixelCharge messages for single detector\n messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);\n\n config_.setDefault(\"file_name\", \"corryvreckanOutput.root\");\n config_.setDefault(\"geometry_file\", \"corryvreckanGeometry.conf\");\n config_.setDefault(\"output_mctruth\", true);\n}\n\n\/\/ Set up the output trees\nvoid CorryvreckanWriterModule::init() {\n\n \/\/ Check if MC data to be saved\n output_mc_truth_ = config_.get<bool>(\"output_mctruth\");\n\n reference_ = config_.get<std::string>(\"reference\");\n if(!geometryManager_->hasDetector(reference_)) {\n throw InvalidValueError(config_, \"reference\", \"detector not defined\");\n }\n dut_ = config_.getArray<std::string>(\"dut\", std::vector<std::string>());\n for(auto& dut : dut_) {\n if(!geometryManager_->hasDetector(dut)) {\n throw InvalidValueError(config_, \"dut\", \"detector not defined\");\n }\n }\n\n \/\/ Create output file and directories\n fileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"file_name\"), \"root\"));\n output_file_ = std::make_unique<TFile>(fileName_.c_str(), \"RECREATE\");\n output_file_->cd();\n\n \/\/ Create geometry file:\n geometryFileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"geometry_file\"), \"conf\"));\n\n \/\/ Create trees:\n event_tree_ = std::make_unique<TTree>(\"Event\", (std::string(\"Tree of Events\").c_str()));\n event_tree_->Bronch(\"global\", \"corryvreckan::Event\", &event_);\n\n pixel_tree_ = std::make_unique<TTree>(\"Pixel\", (std::string(\"Tree of Pixels\").c_str()));\n\n if(output_mc_truth_) {\n mcparticle_tree_ = std::make_unique<TTree>(\"MCParticle\", (std::string(\"Tree of MCParticles\").c_str()));\n }\n\n \/\/ Initialise the time\n time_ = 0;\n}\n\n\/\/ Make instantiations of Corryvreckan pixels, and store these in the trees during run time\nvoid CorryvreckanWriterModule::run(unsigned int event) {\n\n \/\/ Create and store a new Event:\n event_ = new corryvreckan::Event(time_, time_ + 5);\n LOG(DEBUG) << \"Defining event for Corryvreckan: [\" << Units::display(event_->start(), {\"ns\", \"um\"}) << \",\"\n << Units::display(event_->end(), {\"ns\", \"um\"}) << \"]\";\n event_tree_->Fill();\n\n \/\/ Loop through all receieved messages\n for(auto& message : pixel_messages_) {\n\n auto detector_name = message->getDetector()->getName();\n LOG(DEBUG) << \"Receieved \" << message->getData().size() << \" pixel hits from detector \" << detector_name;\n\n \/\/ Events start with 1, pre-filling only with empty events before:\n event--;\n\n if(write_list_px_.find(detector_name) == write_list_px_.end()) {\n write_list_px_[detector_name] = new std::vector<corryvreckan::Pixel*>();\n pixel_tree_->Bronch(detector_name.c_str(),\n std::string(\"std::vector<corryvreckan::Pixel*>\").c_str(),\n &write_list_px_[detector_name]);\n\n LOG(DEBUG) << \"Pre-filling new branch \" << detector_name << \" of corryvreckan::Pixel with \" << event\n << \" empty events\";\n auto* branch = pixel_tree_->GetBranch(detector_name.c_str());\n for(unsigned int i = 0; i < event; ++i) {\n branch->Fill();\n }\n }\n\n if(output_mc_truth_ && write_list_mcp_.find(detector_name) == write_list_mcp_.end()) {\n write_list_mcp_[detector_name] = new std::vector<corryvreckan::MCParticle*>();\n mcparticle_tree_->Bronch(detector_name.c_str(),\n std::string(\"std::vector<corryvreckan::MCParticle*>\").c_str(),\n &write_list_mcp_[detector_name]);\n\n LOG(DEBUG) << \"Pre-filling new branch \" << detector_name << \" of corryvreckan::MCParticle with \" << event\n << \" empty events\";\n auto* branch = mcparticle_tree_->GetBranch(detector_name.c_str());\n for(unsigned int i = 0; i < event; ++i) {\n branch->Fill();\n }\n }\n\n \/\/ Fill the branch vector\n for(auto& apx_pixel : message->getData()) {\n auto corry_pixel = new corryvreckan::Pixel(detector_name,\n static_cast<int>(apx_pixel.getPixel().getIndex().X()),\n static_cast<int>(apx_pixel.getPixel().getIndex().Y()),\n static_cast<int>(apx_pixel.getSignal()),\n apx_pixel.getSignal(),\n event_->start());\n write_list_px_[detector_name]->push_back(corry_pixel);\n\n \/\/ If writing MC truth then also write out associated particle info\n if(!output_mc_truth_) {\n continue;\n }\n\n \/\/ Get all associated particles\n auto mcp = apx_pixel.getMCParticles();\n for(auto& particle : mcp) {\n auto mcParticle = new corryvreckan::MCParticle(detector_name,\n particle->getParticleID(),\n particle->getLocalStartPoint(),\n particle->getLocalEndPoint(),\n event_->start());\n write_list_mcp_[detector_name]->push_back(mcParticle);\n }\n }\n }\n\n LOG(TRACE) << \"Writing new objects to tree\";\n output_file_->cd();\n\n pixel_tree_->Fill();\n mcparticle_tree_->Fill();\n\n \/\/ Clear the current write lists\n for(auto& index_data : write_list_px_) {\n for(auto& pixel : (*index_data.second)) {\n delete pixel;\n }\n index_data.second->clear();\n }\n\n \/\/ Clear the current write lists\n for(auto& index_data : write_list_mcp_) {\n for(auto& mcp : (*index_data.second)) {\n delete mcp;\n }\n index_data.second->clear();\n }\n\n \/\/ Increment the time till the next event\n time_ += 10;\n}\n\n\/\/ Save the output trees to file\nvoid CorryvreckanWriterModule::finalize() {\n\n \/\/ Finish writing to output file\n output_file_->Write();\n\n \/\/ Print statistics\n LOG(STATUS) << \"Wrote output data to file:\" << std::endl << fileName_;\n\n \/\/ Loop over all detectors and store the geometry:\n \/\/ Write geometry:\n std::ofstream geometry_file;\n if(!geometryFileName_.empty()) {\n geometry_file.open(geometryFileName_, std::ios_base::out | std::ios_base::trunc);\n if(!geometry_file.good()) {\n throw ModuleError(\"Cannot write to Corryvreckan geometry file\");\n }\n\n geometry_file << \"# Allpix Squared detector geometry - https:\/\/cern.ch\/allpix-squared\" << std::endl << std::endl;\n\n auto detectors = geometryManager_->getDetectors();\n for(auto& detector : detectors) {\n geometry_file << \"[\" << detector->getName() << \"]\" << std::endl;\n geometry_file << \"position = \" << Units::display(detector->getPosition().x(), {\"mm\", \"um\"}) << \", \"\n << Units::display(detector->getPosition().y(), {\"mm\", \"um\"}) << \", \"\n << Units::display(detector->getPosition().z(), {\"mm\", \"um\"}) << std::endl;\n\n \/\/ Transform the rotation matrix to a ZYX rotation and invert it to get a XYZ rotation\n \/\/ This way we stay compatible to old Corryvreckan versions which only support XYZ.\n geometry_file << \"orientation_mode = \\\"xyz\\\"\" << std::endl;\n ROOT::Math::RotationZYX rotations(detector->getOrientation().Inverse());\n geometry_file << \"orientation = \" << Units::display(-rotations.Psi(), \"deg\") << \", \"\n << Units::display(-rotations.Theta(), \"deg\") << \", \" << Units::display(-rotations.Phi(), \"deg\")\n << std::endl;\n\n auto model = detector->getModel();\n geometry_file << \"type = \\\"\" << model->getType() << \"\\\"\" << std::endl;\n geometry_file << \"pixel_pitch = \" << Units::display(model->getPixelSize().x(), \"um\") << \", \"\n << Units::display(model->getPixelSize().y(), \"um\") << std::endl;\n geometry_file << \"number_of_pixels = \" << model->getNPixels().x() << \", \" << model->getNPixels().y()\n << std::endl;\n\n std::string roles;\n if(detector->getName() == reference_) {\n roles += \"reference\";\n }\n if(std::find(dut_.begin(), dut_.end(), detector->getName()) != dut_.end()) {\n if(!roles.empty()) {\n roles += \",\";\n }\n roles += \"dut\";\n }\n geometry_file << \"role = \" << roles;\n geometry_file << std::endl;\n }\n }\n}\n<commit_msg>CorryvreckanWriter: write MCP tree only if created<commit_after>\/**\n * @file\n * @brief Implementation of CorryvreckanWriter module\n * @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"CorryvreckanWriterModule.hpp\"\n\n#include <Math\/RotationZYX.h>\n\n#include <fstream>\n#include <string>\n#include <utility>\n\n#include \"core\/utils\/file.h\"\n#include \"core\/utils\/log.h\"\n\nusing namespace allpix;\n\nCorryvreckanWriterModule::CorryvreckanWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geoManager)\n : Module(config), messenger_(messenger), geometryManager_(geoManager) {\n\n \/\/ Require PixelCharge messages for single detector\n messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);\n\n config_.setDefault(\"file_name\", \"corryvreckanOutput.root\");\n config_.setDefault(\"geometry_file\", \"corryvreckanGeometry.conf\");\n config_.setDefault(\"output_mctruth\", true);\n}\n\n\/\/ Set up the output trees\nvoid CorryvreckanWriterModule::init() {\n\n \/\/ Check if MC data to be saved\n output_mc_truth_ = config_.get<bool>(\"output_mctruth\");\n\n reference_ = config_.get<std::string>(\"reference\");\n if(!geometryManager_->hasDetector(reference_)) {\n throw InvalidValueError(config_, \"reference\", \"detector not defined\");\n }\n dut_ = config_.getArray<std::string>(\"dut\", std::vector<std::string>());\n for(auto& dut : dut_) {\n if(!geometryManager_->hasDetector(dut)) {\n throw InvalidValueError(config_, \"dut\", \"detector not defined\");\n }\n }\n\n \/\/ Create output file and directories\n fileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"file_name\"), \"root\"));\n output_file_ = std::make_unique<TFile>(fileName_.c_str(), \"RECREATE\");\n output_file_->cd();\n\n \/\/ Create geometry file:\n geometryFileName_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"geometry_file\"), \"conf\"));\n\n \/\/ Create trees:\n event_tree_ = std::make_unique<TTree>(\"Event\", (std::string(\"Tree of Events\").c_str()));\n event_tree_->Bronch(\"global\", \"corryvreckan::Event\", &event_);\n\n pixel_tree_ = std::make_unique<TTree>(\"Pixel\", (std::string(\"Tree of Pixels\").c_str()));\n\n if(output_mc_truth_) {\n mcparticle_tree_ = std::make_unique<TTree>(\"MCParticle\", (std::string(\"Tree of MCParticles\").c_str()));\n }\n\n \/\/ Initialise the time\n time_ = 0;\n}\n\n\/\/ Make instantiations of Corryvreckan pixels, and store these in the trees during run time\nvoid CorryvreckanWriterModule::run(unsigned int event) {\n\n \/\/ Create and store a new Event:\n event_ = new corryvreckan::Event(time_, time_ + 5);\n LOG(DEBUG) << \"Defining event for Corryvreckan: [\" << Units::display(event_->start(), {\"ns\", \"um\"}) << \",\"\n << Units::display(event_->end(), {\"ns\", \"um\"}) << \"]\";\n event_tree_->Fill();\n\n \/\/ Loop through all receieved messages\n for(auto& message : pixel_messages_) {\n\n auto detector_name = message->getDetector()->getName();\n LOG(DEBUG) << \"Receieved \" << message->getData().size() << \" pixel hits from detector \" << detector_name;\n\n \/\/ Events start with 1, pre-filling only with empty events before:\n event--;\n\n if(write_list_px_.find(detector_name) == write_list_px_.end()) {\n write_list_px_[detector_name] = new std::vector<corryvreckan::Pixel*>();\n pixel_tree_->Bronch(detector_name.c_str(),\n std::string(\"std::vector<corryvreckan::Pixel*>\").c_str(),\n &write_list_px_[detector_name]);\n\n LOG(DEBUG) << \"Pre-filling new branch \" << detector_name << \" of corryvreckan::Pixel with \" << event\n << \" empty events\";\n auto* branch = pixel_tree_->GetBranch(detector_name.c_str());\n for(unsigned int i = 0; i < event; ++i) {\n branch->Fill();\n }\n }\n\n if(output_mc_truth_ && write_list_mcp_.find(detector_name) == write_list_mcp_.end()) {\n write_list_mcp_[detector_name] = new std::vector<corryvreckan::MCParticle*>();\n mcparticle_tree_->Bronch(detector_name.c_str(),\n std::string(\"std::vector<corryvreckan::MCParticle*>\").c_str(),\n &write_list_mcp_[detector_name]);\n\n LOG(DEBUG) << \"Pre-filling new branch \" << detector_name << \" of corryvreckan::MCParticle with \" << event\n << \" empty events\";\n auto* branch = mcparticle_tree_->GetBranch(detector_name.c_str());\n for(unsigned int i = 0; i < event; ++i) {\n branch->Fill();\n }\n }\n\n \/\/ Fill the branch vector\n for(auto& apx_pixel : message->getData()) {\n auto corry_pixel = new corryvreckan::Pixel(detector_name,\n static_cast<int>(apx_pixel.getPixel().getIndex().X()),\n static_cast<int>(apx_pixel.getPixel().getIndex().Y()),\n static_cast<int>(apx_pixel.getSignal()),\n apx_pixel.getSignal(),\n event_->start());\n write_list_px_[detector_name]->push_back(corry_pixel);\n\n \/\/ If writing MC truth then also write out associated particle info\n if(!output_mc_truth_) {\n continue;\n }\n\n \/\/ Get all associated particles\n auto mcp = apx_pixel.getMCParticles();\n for(auto& particle : mcp) {\n auto mcParticle = new corryvreckan::MCParticle(detector_name,\n particle->getParticleID(),\n particle->getLocalStartPoint(),\n particle->getLocalEndPoint(),\n event_->start());\n write_list_mcp_[detector_name]->push_back(mcParticle);\n }\n }\n }\n\n LOG(TRACE) << \"Writing new objects to tree\";\n output_file_->cd();\n\n pixel_tree_->Fill();\n if(output_mc_truth_) {\n mcparticle_tree_->Fill();\n }\n\n \/\/ Clear the current write lists\n for(auto& index_data : write_list_px_) {\n for(auto& pixel : (*index_data.second)) {\n delete pixel;\n }\n index_data.second->clear();\n }\n\n \/\/ Clear the current write lists\n for(auto& index_data : write_list_mcp_) {\n for(auto& mcp : (*index_data.second)) {\n delete mcp;\n }\n index_data.second->clear();\n }\n\n \/\/ Increment the time till the next event\n time_ += 10;\n}\n\n\/\/ Save the output trees to file\nvoid CorryvreckanWriterModule::finalize() {\n\n \/\/ Finish writing to output file\n output_file_->Write();\n\n \/\/ Print statistics\n LOG(STATUS) << \"Wrote output data to file:\" << std::endl << fileName_;\n\n \/\/ Loop over all detectors and store the geometry:\n \/\/ Write geometry:\n std::ofstream geometry_file;\n if(!geometryFileName_.empty()) {\n geometry_file.open(geometryFileName_, std::ios_base::out | std::ios_base::trunc);\n if(!geometry_file.good()) {\n throw ModuleError(\"Cannot write to Corryvreckan geometry file\");\n }\n\n geometry_file << \"# Allpix Squared detector geometry - https:\/\/cern.ch\/allpix-squared\" << std::endl << std::endl;\n\n auto detectors = geometryManager_->getDetectors();\n for(auto& detector : detectors) {\n geometry_file << \"[\" << detector->getName() << \"]\" << std::endl;\n geometry_file << \"position = \" << Units::display(detector->getPosition().x(), {\"mm\", \"um\"}) << \", \"\n << Units::display(detector->getPosition().y(), {\"mm\", \"um\"}) << \", \"\n << Units::display(detector->getPosition().z(), {\"mm\", \"um\"}) << std::endl;\n\n \/\/ Transform the rotation matrix to a ZYX rotation and invert it to get a XYZ rotation\n \/\/ This way we stay compatible to old Corryvreckan versions which only support XYZ.\n geometry_file << \"orientation_mode = \\\"xyz\\\"\" << std::endl;\n ROOT::Math::RotationZYX rotations(detector->getOrientation().Inverse());\n geometry_file << \"orientation = \" << Units::display(-rotations.Psi(), \"deg\") << \", \"\n << Units::display(-rotations.Theta(), \"deg\") << \", \" << Units::display(-rotations.Phi(), \"deg\")\n << std::endl;\n\n auto model = detector->getModel();\n geometry_file << \"type = \\\"\" << model->getType() << \"\\\"\" << std::endl;\n geometry_file << \"pixel_pitch = \" << Units::display(model->getPixelSize().x(), \"um\") << \", \"\n << Units::display(model->getPixelSize().y(), \"um\") << std::endl;\n geometry_file << \"number_of_pixels = \" << model->getNPixels().x() << \", \" << model->getNPixels().y()\n << std::endl;\n\n std::string roles;\n if(detector->getName() == reference_) {\n roles += \"reference\";\n }\n if(std::find(dut_.begin(), dut_.end(), detector->getName()) != dut_.end()) {\n if(!roles.empty()) {\n roles += \",\";\n }\n roles += \"dut\";\n }\n geometry_file << \"role = \" << roles;\n geometry_file << std::endl;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2018 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <grpc\/support\/port_platform.h>\n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n\n#ifdef GRPC_CFSTREAM\n#import <CoreFoundation\/CoreFoundation.h>\n#import \"src\/core\/lib\/iomgr\/cfstream_handle.h\"\n\n#include <grpc\/support\/atm.h>\n#include <grpc\/support\/sync.h>\n\n#include \"src\/core\/lib\/debug\/trace.h\"\n#include \"src\/core\/lib\/iomgr\/closure.h\"\n#include \"src\/core\/lib\/iomgr\/error_cfstream.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n\nextern grpc_core::TraceFlag grpc_tcp_trace;\n\nvoid* CFStreamHandle::Retain(void* info) {\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);\n CFSTREAM_HANDLE_REF(handle, \"retain\");\n return info;\n}\n\nvoid CFStreamHandle::Release(void* info) {\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);\n CFSTREAM_HANDLE_UNREF(handle, \"release\");\n}\n\nCFStreamHandle* CFStreamHandle::CreateStreamHandle(\n CFReadStreamRef read_stream, CFWriteStreamRef write_stream) {\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(gpr_malloc(sizeof(CFStreamHandle)));\n return new (handle) CFStreamHandle(read_stream, write_stream);\n}\n\nvoid CFStreamHandle::ReadCallback(CFReadStreamRef stream,\n CFStreamEventType type,\n void* client_callback_info) {\n grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;\n grpc_core::ExecCtx exec_ctx;\n grpc_error* error;\n CFErrorRef stream_error;\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_DEBUG, \"CFStream ReadCallback (%p, %p, %lu, %p)\", handle,\n stream, type, client_callback_info);\n }\n switch (type) {\n case kCFStreamEventOpenCompleted:\n handle->open_event_.SetReady();\n break;\n case kCFStreamEventHasBytesAvailable:\n case kCFStreamEventEndEncountered:\n handle->read_event_.SetReady();\n break;\n case kCFStreamEventErrorOccurred:\n stream_error = CFReadStreamCopyError(stream);\n error = grpc_error_set_int(\n GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, \"read error\"),\n GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);\n CFRelease(stream_error);\n handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n break;\n default:\n GPR_UNREACHABLE_CODE(return );\n }\n}\nvoid CFStreamHandle::WriteCallback(CFWriteStreamRef stream,\n CFStreamEventType type,\n void* clientCallBackInfo) {\n grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;\n grpc_core::ExecCtx exec_ctx;\n grpc_error* error;\n CFErrorRef stream_error;\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_DEBUG, \"CFStream WriteCallback (%p, %p, %lu, %p)\", handle,\n stream, type, clientCallBackInfo);\n }\n switch (type) {\n case kCFStreamEventOpenCompleted:\n handle->open_event_.SetReady();\n break;\n case kCFStreamEventCanAcceptBytes:\n case kCFStreamEventEndEncountered:\n handle->write_event_.SetReady();\n break;\n case kCFStreamEventErrorOccurred:\n stream_error = CFWriteStreamCopyError(stream);\n error = grpc_error_set_int(\n GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, \"write error\"),\n GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);\n CFRelease(stream_error);\n handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n break;\n default:\n GPR_UNREACHABLE_CODE(return );\n }\n}\n\nCFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream,\n CFWriteStreamRef write_stream) {\n gpr_ref_init(&refcount_, 1);\n open_event_.InitEvent();\n read_event_.InitEvent();\n write_event_.InitEvent();\n dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);\n CFStreamClientContext ctx = {0, static_cast<void*>(this),\n CFStreamHandle::Retain, CFStreamHandle::Release,\n nil};\n CFReadStreamSetClient(\n read_stream,\n kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable |\n kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,\n CFStreamHandle::ReadCallback, &ctx);\n CFWriteStreamSetClient(\n write_stream,\n kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes |\n kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,\n CFStreamHandle::WriteCallback, &ctx);\n CFReadStreamSetDispatchQueue(read_stream, dispatch_queue_);\n CFWriteStreamSetDispatchQueue(write_stream, dispatch_queue_);\n}\n\nCFStreamHandle::~CFStreamHandle() {\n open_event_.DestroyEvent();\n read_event_.DestroyEvent();\n write_event_.DestroyEvent();\n}\n\nvoid CFStreamHandle::NotifyOnOpen(grpc_closure* closure) {\n open_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::NotifyOnRead(grpc_closure* closure) {\n read_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::NotifyOnWrite(grpc_closure* closure) {\n write_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::Shutdown(grpc_error* error) {\n open_event_.SetShutdown(GRPC_ERROR_REF(error));\n read_event_.SetShutdown(GRPC_ERROR_REF(error));\n write_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n}\n\nvoid CFStreamHandle::Ref(const char* file, int line, const char* reason) {\n if (grpc_tcp_trace.enabled()) {\n gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);\n gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,\n \"CFStream Handle ref %p : %s %\" PRIdPTR \" -> %\" PRIdPTR, this,\n reason, val, val + 1);\n }\n gpr_ref(&refcount_);\n}\n\nvoid CFStreamHandle::Unref(const char* file, int line, const char* reason) {\n if (grpc_tcp_trace.enabled()) {\n gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);\n gpr_log(GPR_ERROR,\n \"CFStream Handle unref %p : %s %\" PRIdPTR \" -> %\" PRIdPTR, this,\n reason, val, val - 1);\n }\n if (gpr_unref(&refcount_)) {\n this->~CFStreamHandle();\n gpr_free(this);\n }\n}\n\n#else\n\n\/* Creating a dummy function so that the grpc_cfstream library will be\n * non-empty.\n *\/\nvoid CFStreamDummy() {}\n\n#endif\n<commit_msg>Use grpc_core::New and grpc_core::Delete<commit_after>\/*\n *\n * Copyright 2018 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <grpc\/support\/port_platform.h>\n\n#include \"src\/core\/lib\/iomgr\/port.h\"\n#include \"src\/core\/lib\/gprpp\/memory.h\"\n\n#ifdef GRPC_CFSTREAM\n#import <CoreFoundation\/CoreFoundation.h>\n#import \"src\/core\/lib\/iomgr\/cfstream_handle.h\"\n\n#include <grpc\/support\/atm.h>\n#include <grpc\/support\/sync.h>\n\n#include \"src\/core\/lib\/debug\/trace.h\"\n#include \"src\/core\/lib\/iomgr\/closure.h\"\n#include \"src\/core\/lib\/iomgr\/error_cfstream.h\"\n#include \"src\/core\/lib\/iomgr\/exec_ctx.h\"\n\nextern grpc_core::TraceFlag grpc_tcp_trace;\n\nvoid* CFStreamHandle::Retain(void* info) {\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);\n CFSTREAM_HANDLE_REF(handle, \"retain\");\n return info;\n}\n\nvoid CFStreamHandle::Release(void* info) {\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(info);\n CFSTREAM_HANDLE_UNREF(handle, \"release\");\n}\n\nCFStreamHandle* CFStreamHandle::CreateStreamHandle(\n CFReadStreamRef read_stream, CFWriteStreamRef write_stream) {\n return grpc_core::New<CFStreamHandle>(read_stream, write_stream);\n}\n\nvoid CFStreamHandle::ReadCallback(CFReadStreamRef stream,\n CFStreamEventType type,\n void* client_callback_info) {\n grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;\n grpc_core::ExecCtx exec_ctx;\n grpc_error* error;\n CFErrorRef stream_error;\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info);\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_DEBUG, \"CFStream ReadCallback (%p, %p, %lu, %p)\", handle,\n stream, type, client_callback_info);\n }\n switch (type) {\n case kCFStreamEventOpenCompleted:\n handle->open_event_.SetReady();\n break;\n case kCFStreamEventHasBytesAvailable:\n case kCFStreamEventEndEncountered:\n handle->read_event_.SetReady();\n break;\n case kCFStreamEventErrorOccurred:\n stream_error = CFReadStreamCopyError(stream);\n error = grpc_error_set_int(\n GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, \"read error\"),\n GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);\n CFRelease(stream_error);\n handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n break;\n default:\n GPR_UNREACHABLE_CODE(return );\n }\n}\nvoid CFStreamHandle::WriteCallback(CFWriteStreamRef stream,\n CFStreamEventType type,\n void* clientCallBackInfo) {\n grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;\n grpc_core::ExecCtx exec_ctx;\n grpc_error* error;\n CFErrorRef stream_error;\n CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo);\n if (grpc_tcp_trace.enabled()) {\n gpr_log(GPR_DEBUG, \"CFStream WriteCallback (%p, %p, %lu, %p)\", handle,\n stream, type, clientCallBackInfo);\n }\n switch (type) {\n case kCFStreamEventOpenCompleted:\n handle->open_event_.SetReady();\n break;\n case kCFStreamEventCanAcceptBytes:\n case kCFStreamEventEndEncountered:\n handle->write_event_.SetReady();\n break;\n case kCFStreamEventErrorOccurred:\n stream_error = CFWriteStreamCopyError(stream);\n error = grpc_error_set_int(\n GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, \"write error\"),\n GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);\n CFRelease(stream_error);\n handle->open_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->write_event_.SetShutdown(GRPC_ERROR_REF(error));\n handle->read_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n break;\n default:\n GPR_UNREACHABLE_CODE(return );\n }\n}\n\nCFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream,\n CFWriteStreamRef write_stream) {\n gpr_ref_init(&refcount_, 1);\n open_event_.InitEvent();\n read_event_.InitEvent();\n write_event_.InitEvent();\n dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL);\n CFStreamClientContext ctx = {0, static_cast<void*>(this),\n CFStreamHandle::Retain, CFStreamHandle::Release,\n nil};\n CFReadStreamSetClient(\n read_stream,\n kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable |\n kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,\n CFStreamHandle::ReadCallback, &ctx);\n CFWriteStreamSetClient(\n write_stream,\n kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes |\n kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,\n CFStreamHandle::WriteCallback, &ctx);\n CFReadStreamSetDispatchQueue(read_stream, dispatch_queue_);\n CFWriteStreamSetDispatchQueue(write_stream, dispatch_queue_);\n}\n\nCFStreamHandle::~CFStreamHandle() {\n open_event_.DestroyEvent();\n read_event_.DestroyEvent();\n write_event_.DestroyEvent();\n}\n\nvoid CFStreamHandle::NotifyOnOpen(grpc_closure* closure) {\n open_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::NotifyOnRead(grpc_closure* closure) {\n read_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::NotifyOnWrite(grpc_closure* closure) {\n write_event_.NotifyOn(closure);\n}\n\nvoid CFStreamHandle::Shutdown(grpc_error* error) {\n open_event_.SetShutdown(GRPC_ERROR_REF(error));\n read_event_.SetShutdown(GRPC_ERROR_REF(error));\n write_event_.SetShutdown(GRPC_ERROR_REF(error));\n GRPC_ERROR_UNREF(error);\n}\n\nvoid CFStreamHandle::Ref(const char* file, int line, const char* reason) {\n if (grpc_tcp_trace.enabled()) {\n gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);\n gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,\n \"CFStream Handle ref %p : %s %\" PRIdPTR \" -> %\" PRIdPTR, this,\n reason, val, val + 1);\n }\n gpr_ref(&refcount_);\n}\n\nvoid CFStreamHandle::Unref(const char* file, int line, const char* reason) {\n if (grpc_tcp_trace.enabled()) {\n gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count);\n gpr_log(GPR_ERROR,\n \"CFStream Handle unref %p : %s %\" PRIdPTR \" -> %\" PRIdPTR, this,\n reason, val, val - 1);\n }\n if (gpr_unref(&refcount_)) {\n grpc_core::Delete<CFStreamHandle>(this);\n }\n}\n\n#else\n\n\/* Creating a dummy function so that the grpc_cfstream library will be\n * non-empty.\n *\/\nvoid CFStreamDummy() {}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017-2018 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include <unicode\/uchar.h>\n\n#include <wx\/translation.h>\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\nclass NotAllPlurals : public QACheck\n{\npublic:\n bool CheckItem(CatalogItemPtr item) override\n {\n if (!item->HasPlural())\n return false;\n\n bool foundTranslated = false;\n bool foundEmpty = false;\n for (auto& s: item->GetTranslations())\n {\n if (s.empty())\n foundEmpty = true;\n else\n foundTranslated = true;\n }\n\n if (foundEmpty && foundTranslated)\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"Not all plural forms are translated.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass CaseMismatch : public QACheck\n{\npublic:\n CaseMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isupper(source[0]) && u_islower(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start as a sentence.\"));\n return true;\n }\n\n if (u_islower(source[0]) && u_isupper(translation[0]))\n {\n if (m_lang != \"de\")\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start with a lowercase character.\"));\n return true;\n }\n \/\/ else: German nouns start uppercased, this would cause too many false positives\n }\n\n return false;\n }\n\nprivate:\n std::string m_lang;\n};\n\n\nclass WhitespaceMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isspace(source[0]) && !u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation doesn’t start with a space.\"));\n return true;\n }\n\n if (!u_isspace(source[0]) && u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation starts with a space, but the source text doesn’t.\"));\n return true;\n }\n\n if (source.Last() == '\\n' && translation.Last() != '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a newline at the end.\"));\n return true;\n }\n\n if (source.Last() != '\\n' && translation.Last() == '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a newline, but the source text doesn’t.\"));\n return true;\n }\n\n if (u_isspace(source.Last()) && !u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a space at the end.\"));\n return true;\n }\n\n if (!u_isspace(source.Last()) && u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a space, but the source text doesn’t.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass PunctuationMismatch : public QACheck\n{\npublic:\n PunctuationMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n const UChar32 s_last = source.Last();\n const UChar32 t_last = translation.Last();\n const bool s_punct = u_ispunct(s_last);\n const bool t_punct = u_ispunct(t_last);\n\n if (u_getIntPropertyValue(s_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE ||\n u_getIntPropertyValue(t_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE)\n {\n \/\/ too many reordering related false positives for brackets\n \/\/ e.g. \"your {site} account\" -> \"váš účet na {site}\"\n if ((wchar_t)u_getBidiPairedBracket(s_last) != (wchar_t)source[0])\n {\n return false;\n }\n else\n {\n \/\/ OTOH, it's desirable to check strings fully enclosed in brackets like \"(unsaved)\"\n if (source.find_first_of((wchar_t)s_last, 1) != source.size() - 1)\n {\n \/\/ it's more complicated, possibly something like \"your {foo} on {bar}\"\n return false;\n }\n }\n }\n\n if (s_punct && !t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should end with “%s”.\"), wxString(wxUniChar(s_last))));\n return true;\n }\n else if (!s_punct && t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should not end with “%s”.\"), wxString(wxUniChar(t_last))));\n return true;\n }\n else if (s_punct && t_punct && s_last != t_last)\n {\n if (t_last == L'…' && source.EndsWith(\"...\"))\n {\n \/\/ as a special case, allow translating ... (3 dots) as … (ellipsis)\n }\n else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) || u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))\n {\n \/\/ quoted fragments can move around, e.g., so ignore quotes in reporting:\n \/\/ >> Invalid value for ‘{fieldName}’​ field\n \/\/ >> Valor inválido para el campo ‘{fieldName}’\n \/\/ TODO: count quote characters to check if used correctly in translation; don't check position\n \/\/ (don't check for correct quotes for now, accept any quotations marks as equal)\n\n }\n else if (IsEquivalent(s_last, t_last))\n {\n \/\/ some characters are mostly equivalent and we shouldn't warn about them\n }\n else\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation ends with “%s”, but the source text ends with “%s”.\"),\n wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n bool IsEquivalent(UChar32 src, UChar32 trans) const\n {\n if (src == trans)\n return true;\n\n if (m_lang == \"zh\" || m_lang == \"ja\")\n {\n \/\/ Chinese uses full-width punctuation.\n \/\/ See https:\/\/en.wikipedia.org\/wiki\/Chinese_punctuation\n switch (src)\n {\n case '.':\n return trans == L'。';\n case ',':\n return trans == L'、';\n case '!':\n return trans == L'!';\n case '?':\n return trans == L'?';\n case ':':\n return trans == L':';\n case '(':\n return trans == L'(';\n case ')':\n return trans == L')';\n default:\n break;\n }\n }\n else if (m_lang == \"ar\" || m_lang == \"fa\")\n {\n \/\/ In Arabic (but not other RTL languages), some punctuation is mirrored.\n switch (src)\n {\n case ';':\n return trans == L'؛';\n case '?':\n return trans == L'؟';\n case ',':\n return trans == L'،';\n default:\n break;\n }\n }\n else if (m_lang == \"el\")\n {\n \/\/ In Greek, questions end with ';' and not '?'.\n if (src == '?')\n return trans == ';';\n }\n\n return false;\n }\n\n std::string m_lang;\n};\n\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& catalog)\n{\n auto lang = catalog.GetLanguage();\n auto c = std::make_shared<QAChecker>();\n c->AddCheck<QA::NotAllPlurals>();\n c->AddCheck<QA::CaseMismatch>(lang);\n c->AddCheck<QA::WhitespaceMismatch>();\n c->AddCheck<QA::PunctuationMismatch>(lang);\n return c;\n}\n<commit_msg>Fix logic error in quotes QA check<commit_after>\/*\n * This file is part of Poedit (https:\/\/poedit.net)\n *\n * Copyright (C) 2017-2018 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"qa_checks.h\"\n\n#include <unicode\/uchar.h>\n\n#include <wx\/translation.h>\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck implementations\n\/\/ -------------------------------------------------------------\n\nnamespace QA\n{\n\nclass NotAllPlurals : public QACheck\n{\npublic:\n bool CheckItem(CatalogItemPtr item) override\n {\n if (!item->HasPlural())\n return false;\n\n bool foundTranslated = false;\n bool foundEmpty = false;\n for (auto& s: item->GetTranslations())\n {\n if (s.empty())\n foundEmpty = true;\n else\n foundTranslated = true;\n }\n\n if (foundEmpty && foundTranslated)\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"Not all plural forms are translated.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass CaseMismatch : public QACheck\n{\npublic:\n CaseMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isupper(source[0]) && u_islower(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start as a sentence.\"));\n return true;\n }\n\n if (u_islower(source[0]) && u_isupper(translation[0]))\n {\n if (m_lang != \"de\")\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(\"The translation should start with a lowercase character.\"));\n return true;\n }\n \/\/ else: German nouns start uppercased, this would cause too many false positives\n }\n\n return false;\n }\n\nprivate:\n std::string m_lang;\n};\n\n\nclass WhitespaceMismatch : public QACheck\n{\npublic:\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n if (u_isspace(source[0]) && !u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation doesn’t start with a space.\"));\n return true;\n }\n\n if (!u_isspace(source[0]) && u_isspace(translation[0]))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation starts with a space, but the source text doesn’t.\"));\n return true;\n }\n\n if (source.Last() == '\\n' && translation.Last() != '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a newline at the end.\"));\n return true;\n }\n\n if (source.Last() != '\\n' && translation.Last() == '\\n')\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a newline, but the source text doesn’t.\"));\n return true;\n }\n\n if (u_isspace(source.Last()) && !u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation is missing a space at the end.\"));\n return true;\n }\n\n if (!u_isspace(source.Last()) && u_isspace(translation.Last()))\n {\n item->SetIssue(CatalogItem::Issue::Warning, _(L\"The translation ends with a space, but the source text doesn’t.\"));\n return true;\n }\n\n return false;\n }\n};\n\n\nclass PunctuationMismatch : public QACheck\n{\npublic:\n PunctuationMismatch(Language lang) : m_lang(lang.Lang())\n {\n }\n\n bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override\n {\n const UChar32 s_last = source.Last();\n const UChar32 t_last = translation.Last();\n const bool s_punct = u_ispunct(s_last);\n const bool t_punct = u_ispunct(t_last);\n\n if (u_getIntPropertyValue(s_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE ||\n u_getIntPropertyValue(t_last, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE)\n {\n \/\/ too many reordering related false positives for brackets\n \/\/ e.g. \"your {site} account\" -> \"váš účet na {site}\"\n if ((wchar_t)u_getBidiPairedBracket(s_last) != (wchar_t)source[0])\n {\n return false;\n }\n else\n {\n \/\/ OTOH, it's desirable to check strings fully enclosed in brackets like \"(unsaved)\"\n if (source.find_first_of((wchar_t)s_last, 1) != source.size() - 1)\n {\n \/\/ it's more complicated, possibly something like \"your {foo} on {bar}\"\n return false;\n }\n }\n }\n\n if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) || (!s_punct && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK)))\n {\n \/\/ quoted fragments can move around, e.g., so ignore quotes in reporting:\n \/\/ >> Invalid value for ‘{fieldName}’​ field\n \/\/ >> Valor inválido para el campo ‘{fieldName}’\n \/\/ TODO: count quote characters to check if used correctly in translation; don't check position\n return false;\n }\n\n if (s_punct && !t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should end with “%s”.\"), wxString(wxUniChar(s_last))));\n return true;\n }\n else if (!s_punct && t_punct)\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation should not end with “%s”.\"), wxString(wxUniChar(t_last))));\n return true;\n }\n else if (s_punct && t_punct && s_last != t_last)\n {\n if (t_last == L'…' && source.EndsWith(\"...\"))\n {\n \/\/ as a special case, allow translating ... (3 dots) as … (ellipsis)\n }\n else if (u_hasBinaryProperty(s_last, UCHAR_QUOTATION_MARK) && u_hasBinaryProperty(t_last, UCHAR_QUOTATION_MARK))\n {\n \/\/ don't check for correct quotes for now, accept any quotations marks as equal\n }\n else if (IsEquivalent(s_last, t_last))\n {\n \/\/ some characters are mostly equivalent and we shouldn't warn about them\n }\n else\n {\n item->SetIssue(CatalogItem::Issue::Warning,\n wxString::Format(_(L\"The translation ends with “%s”, but the source text ends with “%s”.\"),\n wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));\n return true;\n }\n }\n\n return false;\n }\n\nprivate:\n bool IsEquivalent(UChar32 src, UChar32 trans) const\n {\n if (src == trans)\n return true;\n\n if (m_lang == \"zh\" || m_lang == \"ja\")\n {\n \/\/ Chinese uses full-width punctuation.\n \/\/ See https:\/\/en.wikipedia.org\/wiki\/Chinese_punctuation\n switch (src)\n {\n case '.':\n return trans == L'。';\n case ',':\n return trans == L'、';\n case '!':\n return trans == L'!';\n case '?':\n return trans == L'?';\n case ':':\n return trans == L':';\n case '(':\n return trans == L'(';\n case ')':\n return trans == L')';\n default:\n break;\n }\n }\n else if (m_lang == \"ar\" || m_lang == \"fa\")\n {\n \/\/ In Arabic (but not other RTL languages), some punctuation is mirrored.\n switch (src)\n {\n case ';':\n return trans == L'؛';\n case '?':\n return trans == L'؟';\n case ',':\n return trans == L'،';\n default:\n break;\n }\n }\n else if (m_lang == \"el\")\n {\n \/\/ In Greek, questions end with ';' and not '?'.\n if (src == '?')\n return trans == ';';\n }\n\n return false;\n }\n\n std::string m_lang;\n};\n\n\n} \/\/ namespace QA\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QACheck support code\n\/\/ -------------------------------------------------------------\n\nbool QACheck::CheckItem(CatalogItemPtr item)\n{\n if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))\n return true;\n\n if (item->HasPlural())\n {\n unsigned count = item->GetNumberOfTranslations();\n for (unsigned i = 1; i < count; i++)\n {\n auto t = item->GetTranslation(i);\n if (!t.empty() && CheckString(item, item->GetPluralString(), t))\n return true;\n }\n }\n\n return false;\n}\n\n\nbool QACheck::CheckString(CatalogItemPtr \/*item*\/, const wxString& \/*source*\/, const wxString& \/*translation*\/)\n{\n wxFAIL_MSG(\"not implemented - must override CheckString OR CheckItem\");\n return false;\n}\n\n\n\/\/ -------------------------------------------------------------\n\/\/ QAChecker\n\/\/ -------------------------------------------------------------\n\nint QAChecker::Check(Catalog& catalog)\n{\n \/\/ TODO: parallelize this (make async tasks for chunks of the catalog)\n \/\/ doing it per-checker is MT-unsafe with API that calls SetIssue()!\n\n int issues = 0;\n\n for (auto& i: catalog.items())\n issues += Check(i);\n\n return issues;\n}\n\n\nint QAChecker::Check(CatalogItemPtr item)\n{\n int issues = 0;\n\n for (auto& c: m_checks)\n {\n if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))\n continue;\n\n if (c->CheckItem(item))\n issues++;\n }\n\n return issues;\n}\n\n\nstd::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& catalog)\n{\n auto lang = catalog.GetLanguage();\n auto c = std::make_shared<QAChecker>();\n c->AddCheck<QA::NotAllPlurals>();\n c->AddCheck<QA::CaseMismatch>(lang);\n c->AddCheck<QA::WhitespaceMismatch>();\n c->AddCheck<QA::PunctuationMismatch>(lang);\n return c;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ============================================================================\n *\n * Filename: qc-adaptor.cc\n * Description: Trim adaptor read-through from reads\n * License: LGPL-3+\n * Author: Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n\/* Copyright (c) 2015 Kevin Murray\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <yaml-cpp\/yaml.h>\n\n#include <seqan\/modifier.h>\n#include <seqan\/align.h>\n\n#include \"qc-adaptor.hh\"\n\nnamespace qcpp\n{\n\nAdaptorTrimPE::\nAdaptorTrimPE(const std::string &name, int min_overlap):\n ReadProcessor(name),\n _num_pairs_trimmed(0),\n _num_pairs_joined(0),\n _min_overlap(min_overlap)\n{\n}\n\nvoid\nAdaptorTrimPE::\nprocess_read_pair(ReadPair &the_read_pair)\n{\n seqan::Align<std::string, seqan::ArrayGaps> aligner;\n std::string r2_rc = the_read_pair.second.sequence;\n int score = 0;\n\n seqan::reverseComplement(r2_rc);\n resize(rows(aligner), 2);\n assignSource(row(aligner, 0), the_read_pair.first.sequence);\n assignSource(row(aligner, 1), r2_rc);\n\n score = seqan::globalAlignment(aligner,\n seqan::Score<int, seqan::Simple>(1, -3, -3, -3),\n seqan::AlignConfig<true, true, true, true>());\n\n if (score >= _min_overlap) {\n size_t r1_len = the_read_pair.first.size();\n size_t r2_len = the_read_pair.second.size();\n ssize_t read_len_diff = r1_len - r2_len;\n size_t r1_start = toViewPosition(row(aligner, 0), 0);\n size_t r2_start = toViewPosition(row(aligner, 1), 0);\n std::string &r1_seq = the_read_pair.first.sequence;\n std::string &r2_seq = the_read_pair.second.sequence;\n std::string &r1_qual = the_read_pair.first.quality;\n std::string &r2_qual = the_read_pair.second.quality;\n\n \/\/ Complement R2, as we use it to correct R1 below or concatenation it\n \/\/ to R1 if it's the read needs merging\n seqan::complement(r2_seq);\n\n if (r1_start > r2_start) {\n \/\/ Adaptor read-through, trim R1, truncate R2.\n size_t new_seq_len = r1_len - read_len_diff - r1_start + 1;\n\n \/\/ If R1 base is lower quality than R2, use the base from R2\n for (size_t i = 0; i < new_seq_len; i++) {\n size_t r2_pos = r2_len + read_len_diff - r1_start - i;\n if (r1_qual[i] < r2_qual[r2_pos]) {\n r1_seq[i] = r2_seq[r2_pos];\n r1_qual[i] = r2_qual[r2_pos];\n }\n }\n\n \/\/ Trim the read to its new length\n r1_seq.erase(new_seq_len - 1);\n r1_qual.erase(new_seq_len - 1);\n\n \/\/ Remove R2, as it's just duplicated\n r2_seq.erase();\n r2_qual.erase();\n\n \/\/ Mark read as trimmed\n \/\/the_read_pair.first.name += \" AdaptorTrimPE_trimmed\";\n \/\/the_read_pair.second.name += \" AdaptorTrimPE_trimmed\";\n\n _num_pairs_trimmed++;\n } else {\n \/\/ Read-through into acutal read, needs merging\n size_t overlap_starts = r2_start - read_len_diff;\n size_t overlap_size = r1_len - r2_start;\n\n \/\/ If R1 base is lower quality than R2, use the base from R2\n for (size_t i = 0; i < overlap_size; i++) {\n size_t r1_pos = overlap_starts + i + read_len_diff;\n size_t r2_pos = r2_len + read_len_diff - i;\n if (r1_qual[r1_pos] < r2_qual[r2_pos]) {\n r1_seq[r1_pos] = r2_seq[r2_pos];\n r1_qual[r1_pos] = r2_qual[r2_pos];\n }\n }\n\n \/\/ Remove the overlap from the read\n r2_seq.erase(overlap_starts);\n r2_qual.erase(overlap_starts);\n\n \/\/ Reverse the second read, so we can append it directly to the\n \/\/ first read\n std::reverse(r2_seq.begin(), r2_seq.end());\n std::reverse(r2_qual.begin(), r2_qual.end());\n\n \/\/ Append to form one psuedo read\n r1_seq += r2_seq;\n r1_qual += r2_qual;\n\n \/\/ Remove the second read from the read pair, so it doesn't get\n \/\/ printed.\n r2_seq.erase();\n r2_qual.erase();\n\n \/\/ Mark the read as having been merged\n \/\/the_read_pair.first.name += \" AdaptorTrimPE_merged\";\n \/\/the_read_pair.second.name += \" AdaptorTrimPE_merged\";\n\n _num_pairs_joined++;\n }\n }\n\n _num_reads += 2;\n}\n\nstd::string\nAdaptorTrimPE::\nreport()\n{\n std::ostringstream ss;\n YAML::Emitter yml;\n float percent_trimmed = (_num_pairs_trimmed * 2 \/ (float) _num_reads ) * 100;\n float percent_merged = (_num_pairs_joined * 2 \/ (float) _num_reads ) * 100;\n\n yml << YAML::BeginSeq;\n yml << YAML::BeginMap;\n yml << YAML::Key << \"AdaptorTrimPE\"\n << YAML::Value\n << YAML::BeginMap\n << YAML::Key << \"name\"\n << YAML::Value << _name\n << YAML::Key << \"parameters\"\n << YAML::Value << YAML::BeginMap\n << YAML::EndMap\n << YAML::Key << \"output\"\n << YAML::Value << YAML::BeginMap\n << YAML::Key << \"num_reads\"\n << YAML::Value << _num_reads\n << YAML::Key << \"num_trimmed\"\n << YAML::Value << (_num_pairs_trimmed * 2)\n << YAML::Key << \"num_merged\"\n << YAML::Value << (_num_pairs_joined * 2)\n << YAML::Key << \"percent_trimmed\"\n << YAML::Value << percent_trimmed\n << YAML::Key << \"percent_merged\"\n << YAML::Value << percent_merged\n << YAML::EndMap\n << YAML::EndMap;\n yml << YAML::EndMap;\n yml << YAML::EndSeq;\n ss << yml.c_str() << \"\\n\";\n return ss.str();\n\n}\n\n} \/\/ namespace qcpp\n<commit_msg>Fix rare bug in AdaptorTrimPE<commit_after>\/*\n * ============================================================================\n *\n * Filename: qc-adaptor.cc\n * Description: Trim adaptor read-through from reads\n * License: LGPL-3+\n * Author: Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n\/* Copyright (c) 2015 Kevin Murray\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <yaml-cpp\/yaml.h>\n\n#include <seqan\/modifier.h>\n#include <seqan\/align.h>\n\n#include \"qc-adaptor.hh\"\n\nnamespace qcpp\n{\n\nAdaptorTrimPE::\nAdaptorTrimPE(const std::string &name, int min_overlap):\n ReadProcessor(name),\n _num_pairs_trimmed(0),\n _num_pairs_joined(0),\n _min_overlap(min_overlap)\n{\n}\n\nvoid\nAdaptorTrimPE::\nprocess_read_pair(ReadPair &the_read_pair)\n{\n seqan::Align<std::string, seqan::ArrayGaps> aligner;\n std::string r2_rc = the_read_pair.second.sequence;\n int score = 0;\n\n seqan::reverseComplement(r2_rc);\n resize(rows(aligner), 2);\n assignSource(row(aligner, 0), the_read_pair.first.sequence);\n assignSource(row(aligner, 1), r2_rc);\n\n score = seqan::globalAlignment(aligner,\n seqan::Score<int, seqan::Simple>(1, -3, -3, -3),\n seqan::AlignConfig<true, true, true, true>());\n\n if (score >= _min_overlap) {\n size_t r1_len = the_read_pair.first.size();\n size_t r2_len = the_read_pair.second.size();\n ssize_t read_len_diff = r1_len - r2_len;\n size_t r1_start = toViewPosition(row(aligner, 0), 0);\n size_t r2_start = toViewPosition(row(aligner, 1), 0);\n std::string &r1_seq = the_read_pair.first.sequence;\n std::string &r2_seq = the_read_pair.second.sequence;\n std::string &r1_qual = the_read_pair.first.quality;\n std::string &r2_qual = the_read_pair.second.quality;\n\n \/\/ Complement R2, as we use it to correct R1 below or concatenation it\n \/\/ to R1 if it's the read needs merging.\n seqan::complement(r2_seq);\n\n if (r1_start > r2_start) {\n \/\/ Adaptor read-through, trim R1, remove R2.\n size_t new_len = r1_len - read_len_diff - r1_start;\n new_len = new_len > r1_seq.size() ? r1_seq.size() : new_len;\n\n for (size_t i = 0; i < new_len; i++) {\n size_t r2_pos = r2_len + read_len_diff - r1_start - i;\n if (r1_qual[i] < r2_qual[r2_pos]) {\n r1_seq[i] = r2_seq[r2_pos];\n r1_qual[i] = r2_qual[r2_pos];\n }\n }\n\n \/\/ Trim the read to its new length\n r1_seq.erase(new_len);\n r1_qual.erase(new_len);\n\n \/\/ Remove R2, as it's just duplicated\n r2_seq.erase();\n r2_qual.erase();\n\n _num_pairs_trimmed++;\n } else {\n \/\/ Read-through into acutal read, needs merging\n size_t overlap_starts = r2_start - read_len_diff;\n size_t overlap_size = r1_len - r2_start;\n\n \/\/ If R1 base is lower quality than R2, use the base from R2\n for (size_t i = 0; i < overlap_size; i++) {\n size_t r1_pos = overlap_starts + i + read_len_diff;\n size_t r2_pos = r2_len + read_len_diff - i;\n if (r1_qual[r1_pos] < r2_qual[r2_pos]) {\n r1_seq[r1_pos] = r2_seq[r2_pos];\n r1_qual[r1_pos] = r2_qual[r2_pos];\n }\n }\n\n \/\/ Remove the overlap from the read\n r2_seq.erase(overlap_starts);\n r2_qual.erase(overlap_starts);\n\n \/\/ Reverse the second read, so we can append it directly to the\n \/\/ first read\n std::reverse(r2_seq.begin(), r2_seq.end());\n std::reverse(r2_qual.begin(), r2_qual.end());\n\n \/\/ Append to form one psuedo read\n r1_seq += r2_seq;\n r1_qual += r2_qual;\n\n \/\/ Remove the second read from the read pair, so it doesn't get\n \/\/ printed.\n r2_seq.erase();\n r2_qual.erase();\n\n _num_pairs_joined++;\n }\n }\n\n _num_reads += 2;\n}\n\nstd::string\nAdaptorTrimPE::\nreport()\n{\n std::ostringstream ss;\n YAML::Emitter yml;\n float percent_trimmed = (_num_pairs_trimmed * 2 \/ (float) _num_reads ) * 100;\n float percent_merged = (_num_pairs_joined * 2 \/ (float) _num_reads ) * 100;\n\n yml << YAML::BeginSeq;\n yml << YAML::BeginMap;\n yml << YAML::Key << \"AdaptorTrimPE\"\n << YAML::Value\n << YAML::BeginMap\n << YAML::Key << \"name\"\n << YAML::Value << _name\n << YAML::Key << \"parameters\"\n << YAML::Value << YAML::BeginMap\n << YAML::EndMap\n << YAML::Key << \"output\"\n << YAML::Value << YAML::BeginMap\n << YAML::Key << \"num_reads\"\n << YAML::Value << _num_reads\n << YAML::Key << \"num_trimmed\"\n << YAML::Value << (_num_pairs_trimmed * 2)\n << YAML::Key << \"num_merged\"\n << YAML::Value << (_num_pairs_joined * 2)\n << YAML::Key << \"percent_trimmed\"\n << YAML::Value << percent_trimmed\n << YAML::Key << \"percent_merged\"\n << YAML::Value << percent_merged\n << YAML::EndMap\n << YAML::EndMap;\n yml << YAML::EndMap;\n yml << YAML::EndSeq;\n ss << yml.c_str() << \"\\n\";\n return ss.str();\n\n}\n\n} \/\/ namespace qcpp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"database_autocommit.h\"\n\n\nstd::mutex DatabaseAutocommit::mtx;\nstd::condition_variable DatabaseAutocommit::wakeup_signal;\nstd::unordered_map<Endpoints, DatabaseCommitStatus> DatabaseAutocommit::databases;\nstd::chrono::time_point<std::chrono::system_clock> DatabaseAutocommit::next_wakeup_time(std::chrono::system_clock::now() + 10s);\n\n\nstd::chrono::time_point<std::chrono::system_clock>\nDatabaseCommitStatus::next_wakeup_time()\n{\n\treturn max_commit_time < commit_time ? max_commit_time : commit_time;\n}\n\n\nDatabaseAutocommit::DatabaseAutocommit(const std::shared_ptr<XapiandManager>& manager_)\n\t: running(true),\n\t manager(manager_) { }\n\n\nDatabaseAutocommit::~DatabaseAutocommit()\n{\n\trunning.store(false);\n}\n\n\nvoid\nDatabaseAutocommit::signal_changed(const std::shared_ptr<Database>& database)\n{\n\tstd::lock_guard<std::mutex> lk(DatabaseAutocommit::mtx);\n\n\tDatabaseCommitStatus& status = DatabaseAutocommit::databases[database->endpoints];\n\n\tauto now = std::chrono::system_clock::now();\n\tif (!status.database.lock()) {\n\t\tstatus.database = database;\n\t\tstatus.max_commit_time = now + 9s;\n\t}\n\tstatus.commit_time = now + 3s;\n\n\tif (DatabaseAutocommit::next_wakeup_time > status.next_wakeup_time()) {\n\t\tDatabaseAutocommit::wakeup_signal.notify_one();\n\t}\n}\n\n\nvoid\nDatabaseAutocommit::run()\n{\n\twhile (running) {\n\t\tstd::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx);\n\t\tDatabaseAutocommit::wakeup_signal.wait_until(lk, DatabaseAutocommit::next_wakeup_time);\n\n\t\tauto now = std::chrono::system_clock::now();\n\n\t\tfor (auto it = DatabaseAutocommit::databases.begin(); it != DatabaseAutocommit::databases.end(); ) {\n\t\t\tauto endpoints = it->first;\n\t\t\tauto status = it->second;\n\t\t\tif (status.database.lock()) {\n\t\t\t\tauto next_wakeup_time = status.next_wakeup_time();\n\t\t\t\tif (next_wakeup_time <= now) {\n\t\t\t\t\tDatabaseAutocommit::databases.erase(it);\n\t\t\t\t\tlk.unlock();\n\t\t\t\t\tstd::shared_ptr<Database> database;\n\t\t\t\t\tif (manager->database_pool.checkout(database, endpoints, DB_WRITABLE)) {\n\t\t\t\t\t\tdatabase->commit();\n\t\t\t\t\t\tmanager->database_pool.checkin(database);\n\t\t\t\t\t}\n\t\t\t\t\tlk.lock();\n\t\t\t\t\tit = DatabaseAutocommit::databases.begin();\n\t\t\t\t} else if (DatabaseAutocommit::next_wakeup_time > next_wakeup_time) {\n\t\t\t\t\tDatabaseAutocommit::next_wakeup_time = next_wakeup_time;\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tDatabaseAutocommit::databases.erase(it++);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fixing bug<commit_after>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"database_autocommit.h\"\n\n\nstd::mutex DatabaseAutocommit::mtx;\nstd::condition_variable DatabaseAutocommit::wakeup_signal;\nstd::unordered_map<Endpoints, DatabaseCommitStatus> DatabaseAutocommit::databases;\nstd::chrono::time_point<std::chrono::system_clock> DatabaseAutocommit::next_wakeup_time(std::chrono::system_clock::now() + 10s);\n\n\nstd::chrono::time_point<std::chrono::system_clock>\nDatabaseCommitStatus::next_wakeup_time()\n{\n\treturn max_commit_time < commit_time ? max_commit_time : commit_time;\n}\n\n\nDatabaseAutocommit::DatabaseAutocommit(const std::shared_ptr<XapiandManager>& manager_)\n\t: running(true),\n\t manager(manager_) { }\n\n\nDatabaseAutocommit::~DatabaseAutocommit()\n{\n\trunning.store(false);\n}\n\n\nvoid\nDatabaseAutocommit::signal_changed(const std::shared_ptr<Database>& database)\n{\n\tstd::lock_guard<std::mutex> lk(DatabaseAutocommit::mtx);\n\n\tDatabaseCommitStatus& status = DatabaseAutocommit::databases[database->endpoints];\n\n\tauto now = std::chrono::system_clock::now();\n\tif (!status.database.lock()) {\n\t\tstatus.database = database;\n\t\tstatus.max_commit_time = now + 9s;\n\t}\n\tstatus.commit_time = now + 3s;\n\n\tif (DatabaseAutocommit::next_wakeup_time > status.next_wakeup_time()) {\n\t\tDatabaseAutocommit::wakeup_signal.notify_one();\n\t}\n}\n\n\nvoid\nDatabaseAutocommit::run()\n{\n\twhile (running) {\n\t\tstd::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx);\n\t\tDatabaseAutocommit::wakeup_signal.wait_until(lk, DatabaseAutocommit::next_wakeup_time);\n\n\t\tauto now = std::chrono::system_clock::now();\n\n\t\tfor (auto it = DatabaseAutocommit::databases.begin(); it != DatabaseAutocommit::databases.end(); ) {\n\t\t\tauto endpoints = it->first;\n\t\t\tauto status = it->second;\n\t\t\tif (status.database.lock()) {\n\t\t\t\tauto next_wakeup_time = status.next_wakeup_time();\n\t\t\t\tif (next_wakeup_time <= now) {\n\t\t\t\t\tDatabaseAutocommit::databases.erase(it);\n\t\t\t\t\tlk.unlock();\n\t\t\t\t\tstd::shared_ptr<Database> database;\n\t\t\t\t\tif (manager->database_pool.checkout(database, endpoints, DB_WRITABLE)) {\n\t\t\t\t\t\tdatabase->commit();\n\t\t\t\t\t\tmanager->database_pool.checkin(database);\n\t\t\t\t\t}\n\t\t\t\t\tlk.lock();\n\t\t\t\t\tit = DatabaseAutocommit::databases.begin();\n\t\t\t\t} else if (DatabaseAutocommit::next_wakeup_time > next_wakeup_time) {\n\t\t\t\t\tDatabaseAutocommit::next_wakeup_time = next_wakeup_time;\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tit = DatabaseAutocommit::databases.erase(it);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#pragma once\n\n#include <ecto\/version.hpp>\n#include <ecto\/util.hpp>\n\nnamespace ecto {\n namespace abi {\n\n#define ECTO_ABI_VERSION 6\n\n struct ECTO_EXPORT verifier {\n verifier(unsigned);\n };\n\n namespace { \n verifier verify(ECTO_ABI_VERSION);\n }\n }\n}\n<commit_msg>abi bizzump<commit_after>\/*\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#pragma once\n\n#include <ecto\/version.hpp>\n#include <ecto\/util.hpp>\n\nnamespace ecto {\n namespace abi {\n\n \/\/ lucky 7 !!!!!\n#define ECTO_ABI_VERSION 7\n\n struct ECTO_EXPORT verifier {\n verifier(unsigned);\n };\n\n namespace { \n verifier verify(ECTO_ABI_VERSION);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP\n#define INCLUDE_AL_GRAPHICS_MESH_HPP\n\n\/*\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS).\n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs\n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n*\/\n\n\n#include \"allocore\/math\/al_Vec.hpp\"\n#include \"allocore\/math\/al_Matrix4.hpp\"\n#include \"allocore\/types\/al_Buffer.hpp\"\n#include \"allocore\/types\/al_Color.hpp\"\n\nnamespace al{\n\n\/\/\/ Stores buffers related to rendering graphical objects\nclass Mesh {\npublic:\n\n\ttypedef Vec3f\t\t\tVertex;\n\ttypedef Vec3f\t\t\tNormal;\n\ttypedef Vec4f\t\t\tColor;\n\ttypedef Vec2f\t\t\tTexCoord2;\n\ttypedef Vec3f\t\t\tTexCoord3;\n\ttypedef unsigned int\tIndex;\n\n\tMesh(): mPrimitive(0){}\n\n\tvoid getBounds(Vec3f& min, Vec3f& max) const;\n\n\t\/\/\/ Get center of vertices\n\tVec3f getCenter() const;\n\n\t\/\/ destructive edits to internal vertices:\n\n\t\/\/\/ Convert indices (if any) to flat vertex buffers\n\tvoid decompress();\n\n\t\/\/\/ Extend buffers to match number of vertices\n\tvoid equalizeBuffers();\n\n\t\/\/\/ Reset all buffers\n\tvoid reset();\n\n\t\/\/\/ Scale all vertices to lie in [-1,1]\n\tvoid unitize();\n\n\tvoid scale(double x, double y, double z);\n\tvoid scale(Vec3f v) { scale(v[0], v[1], v[2]); }\n\tvoid scale(double s) { scale(s, s, s); }\n\tvoid translate(double x, double y, double z);\n\tvoid translate(Vec3f v) { translate(v[0], v[1], v[2]); }\n\n\t\/\/ generates smoothed normals for a set of vertices\n\t\/\/ will replace any normals currently in use\n\t\/\/ angle - maximum angle (in degrees) to smooth across\n\tvoid generateNormals(float angle=360);\n\n\tint primitive() const { return mPrimitive; }\n\tconst Buffer<Vertex>& vertices() const { return mVertices; }\n\tconst Buffer<Normal>& normals() const { return mNormals; }\n\tconst Buffer<Color>& colors() const { return mColors; }\n\tconst Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }\n\tconst Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }\n\tconst Buffer<Index>& indices() const { return mIndices; }\n\n\tvoid index(unsigned int i){ indices().append(i); }\n\t\n\ttemplate <class Tindex>\n\tvoid index(const Tindex * buf, int size){ for(int i=0; i<size; ++i) index(buf[i]); }\n\n\tvoid color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }\n\tvoid color(const Color& v) { colors().append(v); }\n\tvoid color(const al::Color& v) { color(v.r, v.g, v.b, v.a); }\n\n\tvoid normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }\n\tvoid normal(const Normal& v) { normals().append(v); }\n\n\tvoid texCoord(float u, float v){ texCoord(TexCoord2(u,v)); }\n\tvoid texCoord(const TexCoord2& v){ texCoord2s().append(v); }\n\n\tvoid texCoord(float u, float v, float w){ texCoord(TexCoord3(u,v,w)); }\n\tvoid texCoord(const TexCoord3& v){ texCoord3s().append(v); }\n\n\tvoid vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }\n\tvoid vertex(const Vertex& v){ vertices().append(v); }\n\n\ttemplate <class T>\n\tvoid vertex(const T * buf, int size){\n\t\tfor(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);\n\t}\n\n\ttemplate <class T>\n\tvoid vertex(const Vec<3,T> * buf, int size){\n\t\tfor(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);\n\t}\n\n\tvoid primitive(int prim){ mPrimitive=prim; }\n\n\tBuffer<Vertex>& vertices(){ return mVertices; }\n\tBuffer<Normal>& normals(){ return mNormals; }\n\tBuffer<Color>& colors(){ return mColors; }\n\tBuffer<TexCoord2>& texCoord2s(){ return mTexCoord2s; }\n\tBuffer<TexCoord3>& texCoord3s(){ return mTexCoord3s; }\n\tBuffer<Index>& indices(){ return mIndices; }\n\nprotected:\n\n\t\/\/ Only populated (size>0) buffers will be used\n\tBuffer<Vertex> mVertices;\n\tBuffer<Normal> mNormals;\n\tBuffer<Color> mColors;\n\tBuffer<TexCoord2> mTexCoord2s;\n\tBuffer<TexCoord3> mTexCoord3s;\n\tBuffer<Index> mIndices;\n\n\tint mPrimitive;\n};\n\n} \/\/ ::al\n\n\n#endif\t\/* include guard *\/\n\n<commit_msg>Mesh: matrix transform of vertex range<commit_after>#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP\n#define INCLUDE_AL_GRAPHICS_MESH_HPP\n\n\/*\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS).\n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs\n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n*\/\n\n\n#include \"allocore\/math\/al_Vec.hpp\"\n#include \"allocore\/math\/al_Matrix4.hpp\"\n#include \"allocore\/types\/al_Buffer.hpp\"\n#include \"allocore\/types\/al_Color.hpp\"\n\nnamespace al{\n\n\/\/\/ Stores buffers related to rendering graphical objects\nclass Mesh {\npublic:\n\n\ttypedef Vec3f\t\t\tVertex;\n\ttypedef Vec3f\t\t\tNormal;\n\ttypedef Vec4f\t\t\tColor;\n\ttypedef Vec2f\t\t\tTexCoord2;\n\ttypedef Vec3f\t\t\tTexCoord3;\n\ttypedef unsigned int\tIndex;\n\n\tMesh(): mPrimitive(0){}\n\n\tvoid getBounds(Vec3f& min, Vec3f& max) const;\n\n\t\/\/\/ Get center of vertices\n\tVec3f getCenter() const;\n\n\t\/\/ destructive edits to internal vertices:\n\n\t\/\/\/ Convert indices (if any) to flat vertex buffers\n\tvoid decompress();\n\n\t\/\/\/ Extend buffers to match number of vertices\n\tvoid equalizeBuffers();\n\n\t\/\/\/ Reset all buffers\n\tvoid reset();\n\n\t\/\/\/ Scale all vertices to lie in [-1,1]\n\tvoid unitize();\n\n\tvoid scale(double x, double y, double z);\n\tvoid scale(Vec3f v) { scale(v[0], v[1], v[2]); }\n\tvoid scale(double s) { scale(s, s, s); }\n\tvoid translate(double x, double y, double z);\n\tvoid translate(Vec3f v) { translate(v[0], v[1], v[2]); }\n\t\n\t\/\/\/ Transform vertices by projective transform matrix\n\t\n\t\/\/\/ @param[in] m\t\tprojective transform matrix\n\t\/\/\/ @param[in] begin\tbeginning index of vertices\n\t\/\/\/ @param[in] end\t\tending index of vertices, negative amount specify distance from one past last element\n\ttemplate <class T>\n\tvoid transform(const Mat<4,T>& m, int begin=0, int end=-1);\n\n\t\/\/ generates smoothed normals for a set of vertices\n\t\/\/ will replace any normals currently in use\n\t\/\/ angle - maximum angle (in degrees) to smooth across\n\tvoid generateNormals(float angle=360);\n\n\tint primitive() const { return mPrimitive; }\n\tconst Buffer<Vertex>& vertices() const { return mVertices; }\n\tconst Buffer<Normal>& normals() const { return mNormals; }\n\tconst Buffer<Color>& colors() const { return mColors; }\n\tconst Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }\n\tconst Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }\n\tconst Buffer<Index>& indices() const { return mIndices; }\n\n\tvoid index(unsigned int i){ indices().append(i); }\n\t\n\ttemplate <class Tindex>\n\tvoid index(const Tindex * buf, int size, int indexOffset=0){\n\t\tfor(int i=0; i<size; ++i) index(buf[i] + indexOffset); }\n\n\tvoid color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }\n\tvoid color(const Color& v) { colors().append(v); }\n\tvoid color(const al::Color& v) { color(v.r, v.g, v.b, v.a); }\n\n\tvoid normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }\n\tvoid normal(const Normal& v) { normals().append(v); }\n\n\tvoid texCoord(float u, float v){ texCoord(TexCoord2(u,v)); }\n\tvoid texCoord(const TexCoord2& v){ texCoord2s().append(v); }\n\n\tvoid texCoord(float u, float v, float w){ texCoord(TexCoord3(u,v,w)); }\n\tvoid texCoord(const TexCoord3& v){ texCoord3s().append(v); }\n\n\tvoid vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }\n\tvoid vertex(const Vertex& v){ vertices().append(v); }\n\n\ttemplate <class T>\n\tvoid vertex(const T * buf, int size){\n\t\tfor(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);\n\t}\n\n\ttemplate <class T>\n\tvoid vertex(const Vec<3,T> * buf, int size){\n\t\tfor(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);\n\t}\n\n\tvoid primitive(int prim){ mPrimitive=prim; }\n\n\tBuffer<Vertex>& vertices(){ return mVertices; }\n\tBuffer<Normal>& normals(){ return mNormals; }\n\tBuffer<Color>& colors(){ return mColors; }\n\tBuffer<TexCoord2>& texCoord2s(){ return mTexCoord2s; }\n\tBuffer<TexCoord3>& texCoord3s(){ return mTexCoord3s; }\n\tBuffer<Index>& indices(){ return mIndices; }\n\nprotected:\n\n\t\/\/ Only populated (size>0) buffers will be used\n\tBuffer<Vertex> mVertices;\n\tBuffer<Normal> mNormals;\n\tBuffer<Color> mColors;\n\tBuffer<TexCoord2> mTexCoord2s;\n\tBuffer<TexCoord3> mTexCoord3s;\n\tBuffer<Index> mIndices;\n\n\tint mPrimitive;\n};\n\n\n\ntemplate <class T>\nvoid Mesh::transform(const Mat<4,T>& m, int begin, int end){\n\tif(end<0) end += vertices().size()+1; \/\/ negative index wraps to end of array\n\tfor(int i=begin; i<end; ++i){\n\t\tVertex& ver = vertices()[i];\n\t\tVec<4,T> vec(ver[0], ver[1], ver[2], 1);\n\t\tver.set(m*vec);\n\t}\n}\n\n} \/\/ ::al\n\n\n#endif\t\/* include guard *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef ETL_STOP_HPP\n#define ETL_STOP_HPP\n\n#include \"tmp.hpp\"\n\nnamespace etl {\n\ntemplate<typename T, std::size_t Rows>\nstruct fast_vector;\n\ntemplate<typename T>\nstruct dyn_vector;\n\ntemplate<typename T>\nstruct dyn_matrix;\n\ntemplate<typename T, size_t Rows, size_t Columns>\nstruct fast_matrix;\n\n\/\/TODO Implement it for fast_XXX\n\ntemplate<typename T, typename Enable = void>\nstruct stop;\n\ntemplate <typename T, typename Expr, typename UnaryOp>\nstruct stop <unary_expr<T, Expr, UnaryOp>, enable_if_t<etl_traits<unary_expr<T, Expr, UnaryOp>>::is_vector>> {\n template<typename TT, typename T2 = Expr, disable_if_u<etl_traits<T2>::is_fast> = detail::dummy>\n static dyn_vector<T> s(TT&& value){\n return {std::forward<TT>(value)};\n }\n\n template<typename TT, typename T2 = remove_cv_t<remove_reference_t<Expr>>, enable_if_u<etl_traits<T2>::is_fast> = detail::dummy>\n static auto s(TT&& value){\n return fast_vector<T, etl_traits<T2>::size()>(std::forward<TT>(value));\n }\n};\n\ntemplate <typename T, typename Expr, typename UnaryOp>\nstruct stop <unary_expr<T, Expr, UnaryOp>, enable_if_t<etl_traits<unary_expr<T, Expr, UnaryOp>>::is_matrix>> {\n template<typename TT, typename T2 = Expr, disable_if_u<etl_traits<T2>::is_fast> = detail::dummy>\n static dyn_matrix<T> s(TT&& value){\n return {std::forward<TT>(value)};\n }\n\n template<typename TT, typename T2 = remove_cv_t<remove_reference_t<Expr>>, enable_if_u<etl_traits<T2>::is_fast> = detail::dummy>\n static auto s(TT&& value){\n return fast_matrix<T, etl_traits<Expr>::rows(), etl_traits<Expr>::columns()>(std::forward<TT>(value));\n }\n};\n\ntemplate<typename T>\nauto s(const T& value){\n return stop<T>::s(value);\n}\n\n} \/\/end of namespace etl\n\n#endif\n<commit_msg>Review stop completely<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef ETL_STOP_HPP\n#define ETL_STOP_HPP\n\n#include \"tmp.hpp\"\n\nnamespace etl {\n\ntemplate<typename T, enable_if_u<and_u<is_etl_expr<T>::value, not_u<etl_traits<T>::is_value>::value, not_u<etl_traits<T>::is_fast>::value, etl_traits<T>::is_vector>::value> = detail::dummy>\ndyn_vector<typename T::value_type> s(const T& value){\n return {value};\n}\n\ntemplate<typename T, enable_if_u<and_u<is_etl_expr<T>::value, not_u<etl_traits<T>::is_value>::value, not_u<etl_traits<T>::is_fast>::value, etl_traits<T>::is_matrix>::value> = detail::dummy>\ndyn_matrix<typename T::value_type> s(const T& value){\n return {value};\n}\n\ntemplate<typename T, enable_if_u<and_u<is_etl_expr<T>::value, not_u<etl_traits<T>::is_value>::value, etl_traits<T>::is_fast, etl_traits<T>::is_vector>::value> = detail::dummy>\nauto s(const T& value){\n return fast_vector<typename T::value_type, etl_traits<T>::size()>(value);\n}\n\ntemplate<typename T, enable_if_u<and_u<is_etl_expr<T>::value, not_u<etl_traits<T>::is_value>::value, etl_traits<T>::is_fast, etl_traits<T>::is_matrix>::value> = detail::dummy>\nauto s(const T& value){\n return fast_matrix<typename T::value_type, etl_traits<T>::rows(), etl_traits<T>::columns()>(value);\n}\n\n} \/\/end of namespace etl\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n#include \"stdafx.h\"\n\nHostConfigFlags HostConfigFlags::flags;\nLPWSTR* HostConfigFlags::argsVal;\nint HostConfigFlags::argsCount;\nvoid(__stdcall *HostConfigFlags::pfnPrintUsage)();\n\ntemplate <>\nvoid HostConfigFlags::Parse<bool>(ICmdLineArgsParser * parser, bool * value)\n{\n *value = parser->GetCurrentBoolean();\n}\n\ntemplate <>\nvoid HostConfigFlags::Parse<int>(ICmdLineArgsParser * parser, int* value)\n{\n try\n {\n *value = parser->GetCurrentInt();\n }\n catch (...)\n {\n \/\/ Don't do anything, *value will remain its default value.\n }\n}\n\ntemplate <>\nvoid HostConfigFlags::Parse<BSTR>(ICmdLineArgsParser * parser, BSTR * bstr)\n{\n if (*bstr != NULL)\n {\n SysFreeString(*bstr);\n }\n *bstr = parser->GetCurrentString();\n if (*bstr == NULL)\n {\n *bstr = SysAllocString(_u(\"\"));\n }\n}\n\nHostConfigFlags::HostConfigFlags() :\n#define FLAG(Type, Name, Desc, Default) \\\n Name##IsEnabled(false), \\\n Name(Default),\n#include \"HostConfigFlagsList.h\"\n nDummy(0)\n{\n}\n\nbool HostConfigFlags::ParseFlag(LPCWSTR flagsString, ICmdLineArgsParser * parser)\n{\n#define FLAG(Type, Name, Desc, Default) \\\n if (_wcsicmp(_u(#Name), flagsString) == 0) \\\n { \\\n this->Name##IsEnabled = true; \\\n Parse<Type>(parser, &this->Name); \\\n return true; \\\n }\n#include \"HostConfigFlagsList.h\"\n return false;\n}\n\nvoid HostConfigFlags::PrintUsageString()\n{\n#define FLAG(Type, Name, Desc, Default) \\\n wprintf(_u(\"%20ls \\t%ls\\n\"), _u(#Name), _u(#Desc));\n#include \"HostConfigFlagsList.h\"\n}\n\nvoid HostConfigFlags::PrintUsage()\n{\n if (pfnPrintUsage)\n {\n pfnPrintUsage();\n }\n\n wprintf(_u(\"\\nHost Config Flags: \\n\\n\"));\n HostConfigFlags::PrintUsageString();\n ChakraRTInterface::PrintConfigFlagsUsageString();\n}\n\nint HostConfigFlags::FindArg(int argc, _In_reads_(argc) PWSTR argv[], PCWSTR targetArg, size_t targetArgLen)\n{\n return FindArg(argc, argv, [=](PCWSTR arg) -> bool\n {\n return _wcsnicmp(arg, targetArg, targetArgLen) == 0;\n });\n}\n\nvoid HostConfigFlags::RemoveArg(int& argc, _Inout_updates_to_(argc, argc) LPWSTR argv[], int index)\n{\n Assert(index >= 0 && index < argc);\n for (int i = index + 1; i < argc; ++i)\n {\n#pragma prefast(suppress:6385, \"Operation is safe but PREfast is difficult to convince\")\n argv[i - 1] = argv[i];\n }\n --argc;\n}\n\nvoid HostConfigFlags::HandleArgsFlag(int& argc, _Inout_updates_to_(argc, argc) LPWSTR argv[])\n{\n const LPCWSTR argsFlag = _u(\"-args\");\n const LPCWSTR endArgsFlag = _u(\"-endargs\");\n int argsFlagLen = static_cast<int>(wcslen(argsFlag));\n int i;\n for (i = 1; i < argc; i++)\n {\n if (_wcsnicmp(argv[i], argsFlag, argsFlagLen) == 0)\n {\n break;\n }\n }\n int argsStart = ++i;\n for (; i < argc; i++)\n {\n if (_wcsnicmp(argv[i], endArgsFlag, argsFlagLen) == 0)\n {\n break;\n }\n }\n int argsEnd = i;\n\n int argsCount = argsEnd - argsStart;\n if (argsCount == 0)\n {\n return;\n }\n HostConfigFlags::argsVal = new LPWSTR[argsCount];\n HostConfigFlags::argsCount = argsCount;\n int argIndex = argsStart;\n for (i = 0; i < argsCount; i++)\n {\n HostConfigFlags::argsVal[i] = argv[argIndex++];\n }\n\n argIndex = argsStart - 1;\n for (i = argsEnd + 1; i < argc; i++)\n {\n LPWSTR temp = argv[argIndex];\n argv[argIndex] = argv[i];\n argv[i] = temp;\n argIndex++;\n }\n Assert(argIndex == argc - argsCount - 1 - (argsEnd < argc));\n argc = argIndex;\n}\n<commit_msg>Change suppression number to named macro<commit_after>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n#include \"stdafx.h\"\n\nHostConfigFlags HostConfigFlags::flags;\nLPWSTR* HostConfigFlags::argsVal;\nint HostConfigFlags::argsCount;\nvoid(__stdcall *HostConfigFlags::pfnPrintUsage)();\n\ntemplate <>\nvoid HostConfigFlags::Parse<bool>(ICmdLineArgsParser * parser, bool * value)\n{\n *value = parser->GetCurrentBoolean();\n}\n\ntemplate <>\nvoid HostConfigFlags::Parse<int>(ICmdLineArgsParser * parser, int* value)\n{\n try\n {\n *value = parser->GetCurrentInt();\n }\n catch (...)\n {\n \/\/ Don't do anything, *value will remain its default value.\n }\n}\n\ntemplate <>\nvoid HostConfigFlags::Parse<BSTR>(ICmdLineArgsParser * parser, BSTR * bstr)\n{\n if (*bstr != NULL)\n {\n SysFreeString(*bstr);\n }\n *bstr = parser->GetCurrentString();\n if (*bstr == NULL)\n {\n *bstr = SysAllocString(_u(\"\"));\n }\n}\n\nHostConfigFlags::HostConfigFlags() :\n#define FLAG(Type, Name, Desc, Default) \\\n Name##IsEnabled(false), \\\n Name(Default),\n#include \"HostConfigFlagsList.h\"\n nDummy(0)\n{\n}\n\nbool HostConfigFlags::ParseFlag(LPCWSTR flagsString, ICmdLineArgsParser * parser)\n{\n#define FLAG(Type, Name, Desc, Default) \\\n if (_wcsicmp(_u(#Name), flagsString) == 0) \\\n { \\\n this->Name##IsEnabled = true; \\\n Parse<Type>(parser, &this->Name); \\\n return true; \\\n }\n#include \"HostConfigFlagsList.h\"\n return false;\n}\n\nvoid HostConfigFlags::PrintUsageString()\n{\n#define FLAG(Type, Name, Desc, Default) \\\n wprintf(_u(\"%20ls \\t%ls\\n\"), _u(#Name), _u(#Desc));\n#include \"HostConfigFlagsList.h\"\n}\n\nvoid HostConfigFlags::PrintUsage()\n{\n if (pfnPrintUsage)\n {\n pfnPrintUsage();\n }\n\n wprintf(_u(\"\\nHost Config Flags: \\n\\n\"));\n HostConfigFlags::PrintUsageString();\n ChakraRTInterface::PrintConfigFlagsUsageString();\n}\n\nint HostConfigFlags::FindArg(int argc, _In_reads_(argc) PWSTR argv[], PCWSTR targetArg, size_t targetArgLen)\n{\n return FindArg(argc, argv, [=](PCWSTR arg) -> bool\n {\n return _wcsnicmp(arg, targetArg, targetArgLen) == 0;\n });\n}\n\nvoid HostConfigFlags::RemoveArg(int& argc, _Inout_updates_to_(argc, argc) LPWSTR argv[], int index)\n{\n Assert(index >= 0 && index < argc);\n for (int i = index + 1; i < argc; ++i)\n {\n#pragma prefast(suppress:__WARNING_READ_OVERRUN, \"Operation is safe but PREfast is difficult to convince\")\n argv[i - 1] = argv[i];\n }\n --argc;\n}\n\nvoid HostConfigFlags::HandleArgsFlag(int& argc, _Inout_updates_to_(argc, argc) LPWSTR argv[])\n{\n const LPCWSTR argsFlag = _u(\"-args\");\n const LPCWSTR endArgsFlag = _u(\"-endargs\");\n int argsFlagLen = static_cast<int>(wcslen(argsFlag));\n int i;\n for (i = 1; i < argc; i++)\n {\n if (_wcsnicmp(argv[i], argsFlag, argsFlagLen) == 0)\n {\n break;\n }\n }\n int argsStart = ++i;\n for (; i < argc; i++)\n {\n if (_wcsnicmp(argv[i], endArgsFlag, argsFlagLen) == 0)\n {\n break;\n }\n }\n int argsEnd = i;\n\n int argsCount = argsEnd - argsStart;\n if (argsCount == 0)\n {\n return;\n }\n HostConfigFlags::argsVal = new LPWSTR[argsCount];\n HostConfigFlags::argsCount = argsCount;\n int argIndex = argsStart;\n for (i = 0; i < argsCount; i++)\n {\n HostConfigFlags::argsVal[i] = argv[argIndex++];\n }\n\n argIndex = argsStart - 1;\n for (i = argsEnd + 1; i < argc; i++)\n {\n LPWSTR temp = argv[argIndex];\n argv[argIndex] = argv[i];\n argv[i] = temp;\n argIndex++;\n }\n Assert(argIndex == argc - argsCount - 1 - (argsEnd < argc));\n argc = argIndex;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <chrono>\n#include <unordered_map>\n\n#include \"message.hpp\"\n\nclass MessageTimes\n{\n\tusing time_point = std::chrono::steady_clock::time_point;\n\tusing map_type = std::unordered_map<MESSAGE_TYPE, time_point>;\npublic:\n\tMessageTimes()\n\t{\n\t}\n\n\tvoid\n\tmark(MESSAGE_TYPE m_type)\n\t{\n\t\tm[m_type] = std::chrono::steady_clock::now();\n\t}\n\n\tint ms_since(MESSAGE_TYPE m_type)\n\t{\n\t\treturn std::chrono::duration_cast<std::chrono::milliseconds>(\n\t\t\tstd::chrono::steady_clock::now() - m[m_type]\n\t\t).count();\n\t}\n\n\nprivate:\n\tmap_type m;\n}; \/\/ MessageTimes\n<commit_msg>uint8_t map key<commit_after>#pragma once\n\n#include <chrono>\n#include <unordered_map>\n\n#include \"message.hpp\"\n\nclass MessageTimes\n{\n\tusing time_point = std::chrono::steady_clock::time_point;\n\tusing map_type = std::unordered_map<uint8_t, time_point>;\npublic:\n\tMessageTimes()\n\t{\n\t}\n\n\tvoid\n\tmark(MESSAGE_TYPE m_type)\n\t{\n\t\tm[m_type] = std::chrono::steady_clock::now();\n\t}\n\n\tint ms_since(MESSAGE_TYPE m_type)\n\t{\n\t\treturn std::chrono::duration_cast<std::chrono::milliseconds>(\n\t\t\tstd::chrono::steady_clock::now() - m[m_type]\n\t\t).count();\n\t}\n\n\nprivate:\n\tmap_type m;\n}; \/\/ MessageTimes\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cstring>\n\n#ifdef WIN32\n #include <windows.h>\n typedef unsigned __int32 uint32_t;\n#else\n #include <stdint.h>\n #include <unistd.h>\n #include <sys\/mman.h>\n#endif\n\nstatic void Unprotect(void *address, int size) {\n#if defined WIN32 || defined _WIN32\n DWORD oldProtect;\n VirtualProtect(address, size, PAGE_EXECUTE_READWRITE, &oldProtect);\n#else\n \/\/ Both address and size must be multiples of page size \n size_t pagesize = getpagesize();\n size_t where = ((reinterpret_cast<uint32_t>(address) \/ pagesize) * pagesize);\n size_t count = (size \/ pagesize) * pagesize + pagesize * 2;\n mprotect(reinterpret_cast<void*>(where), count, PROT_READ | PROT_WRITE | PROT_EXEC);\n#endif\n}\n\nvoid SetJump(void *from, void *to, unsigned char (&oldCode)[5]) {\n Unprotect(from, 5);\n \/\/ Store the code we are goin to overwrite (probably to copy it back later)\n memcpy(oldCode, from, 5);\n \/\/ E9 - jump near, relative\n unsigned char JMP = 0xE9;\n memcpy(from, &JMP, 1);\n \/\/ Jump address is relative to the next instruction's address\n size_t offset = (uint32_t)to - ((uint32_t)from + 5);\n memcpy((void*)((uint32_t)from + 1), &offset, 4);\n}\n\nvoid SetJump(void *from, void *to) {\n unsigned char dummy[5];\n SetJump(from, to, dummy);\n}\n<commit_msg>Check for _WIN32 as well<commit_after>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cstring>\n\n#if defined WIN32 || defined _WIN32\n #include <windows.h>\n typedef unsigned __int32 uint32_t;\n#else\n #include <stdint.h>\n #include <unistd.h>\n #include <sys\/mman.h>\n#endif\n\nstatic void Unprotect(void *address, int size) {\n#if defined WIN32 || defined _WIN32\n DWORD oldProtect;\n VirtualProtect(address, size, PAGE_EXECUTE_READWRITE, &oldProtect);\n#else\n \/\/ Both address and size must be multiples of page size\n size_t pagesize = getpagesize();\n size_t where = ((reinterpret_cast<uint32_t>(address) \/ pagesize) * pagesize);\n size_t count = (size \/ pagesize) * pagesize + pagesize * 2;\n mprotect(reinterpret_cast<void*>(where), count, PROT_READ | PROT_WRITE | PROT_EXEC);\n#endif\n}\n\nvoid SetJump(void *from, void *to, unsigned char (&oldCode)[5]) {\n Unprotect(from, 5);\n \/\/ Store the code we are goin to overwrite (probably to copy it back later)\n memcpy(oldCode, from, 5);\n \/\/ E9 - jump near, relative\n unsigned char JMP = 0xE9;\n memcpy(from, &JMP, 1);\n \/\/ Jump address is relative to the next instruction's address\n size_t offset = (uint32_t)to - ((uint32_t)from + 5);\n memcpy((void*)((uint32_t)from + 1), &offset, 4);\n}\n\nvoid SetJump(void *from, void *to) {\n unsigned char dummy[5];\n SetJump(from, to, dummy);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CREATE_TORRENT_HPP_INCLUDED\n#define TORRENT_CREATE_TORRENT_HPP_INCLUDED\n\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/file_storage.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include \"libtorrent\/allocator.hpp\"\n\n#include <vector>\n#include <string>\n#include <utility>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\nnamespace libtorrent\n{\n\tnamespace fs = boost::filesystem;\n\tnamespace pt = boost::posix_time;\n\tclass torrent_info;\n\n\tstruct TORRENT_EXPORT create_torrent\n\t{\n\t\tcreate_torrent(file_storage& fs, int piece_size = 0, int pad_file_limit = -1);\n\t\tcreate_torrent(torrent_info const& ti);\n\t\tentry generate() const;\n\n\t\tfile_storage const& files() const { return m_files; }\n\n\t\tvoid set_comment(char const* str);\n\t\tvoid set_creator(char const* str);\n\t\tvoid set_hash(int index, sha1_hash const& h);\n\t\tvoid add_url_seed(std::string const& url);\n\t\tvoid add_node(std::pair<std::string, int> const& node);\n\t\tvoid add_tracker(std::string const& url, int tier = 0);\n\t\tvoid set_priv(bool p) { m_private = p; }\n\n\t\tint num_pieces() const { return m_files.num_pieces(); }\n\t\tint piece_length() const { return m_files.piece_length(); }\n\t\tint piece_size(int i) const { return m_files.piece_size(i); }\n\t\tbool priv() const { return m_private; }\n\n\tprivate:\n\n\t\tfile_storage& m_files;\n\t\t\/\/ if m_info_dict is initialized, it is \n\t\t\/\/ used instead of m_files to generate\n\t\t\/\/ the info dictionary\n\t\tentry m_info_dict;\n\n\t\t\/\/ the urls to the trackers\n\t\ttypedef std::pair<std::string, int> announce_entry;\n\t\tstd::vector<announce_entry> m_urls;\n\n\t\tstd::vector<std::string> m_url_seeds;\n\n\t\tstd::vector<sha1_hash> m_piece_hash;\n\n\t\t\/\/ dht nodes to add to the routing table\/bootstrap from\n\t\ttypedef std::vector<std::pair<std::string, int> > nodes_t;\n\t\tnodes_t m_nodes;\n\n\t\t\/\/ the hash that identifies this torrent\n\t\t\/\/ is mutable because it's calculated\n\t\t\/\/ lazily\n\t\tmutable sha1_hash m_info_hash;\n\n\t\t\/\/ if a creation date is found in the torrent file\n\t\t\/\/ this will be set to that, otherwise it'll be\n\t\t\/\/ 1970, Jan 1\n\t\tpt::ptime m_creation_date;\n\n\t\t\/\/ if a comment is found in the torrent file\n\t\t\/\/ this will be set to that comment\n\t\tstd::string m_comment;\n\n\t\t\/\/ an optional string naming the software used\n\t\t\/\/ to create the torrent file\n\t\tstd::string m_created_by;\n\n\t\t\/\/ this is used when creating a torrent. If there's\n\t\t\/\/ only one file there are cases where it's impossible\n\t\t\/\/ to know if it should be written as a multifile torrent\n\t\t\/\/ or not. e.g. test\/test there's one file and one directory\n\t\t\/\/ and they have the same name.\n\t\tbool m_multifile;\n\t\t\n\t\t\/\/ this is true if the torrent is private. i.e., is should not\n\t\t\/\/ be announced on the dht\n\t\tbool m_private;\n\t};\n\n\tnamespace detail\n\t{\n\t\tinline bool default_pred(boost::filesystem::path const&) { return true; }\n\t\tinline bool wdefault_pred(boost::filesystem::wpath const&) { return true; }\n\n\t\tinline bool ignore_subdir(std::string const& leaf)\n\t\t{ return leaf == \"..\" || leaf == \".\"; }\n\n\t\tinline bool ignore_subdir(std::wstring const& leaf)\n\t\t{ return leaf == L\"..\" || leaf == L\".\"; }\n\n\t\tinline void nop(int i) {}\n\n\t\tint get_file_attributes(boost::filesystem::path const& p);\n\t\tint get_file_attributes(boost::filesystem::wpath const& p);\n\n\t\ttemplate <class Pred, class Str, class PathTraits>\n\t\tvoid add_files_impl(file_storage& fs, boost::filesystem::basic_path<Str, PathTraits> const& p\n\t\t\t, boost::filesystem::basic_path<Str, PathTraits> const& l, Pred pred)\n\t\t{\n\t\t\tusing boost::filesystem::basic_path;\n\t\t\tusing boost::filesystem::basic_directory_iterator;\n#if BOOST_VERSION < 103600\n\t\t\tStr const& leaf = l.leaf();\n#else\n\t\t\tStr const& leaf = l.filename();\n#endif\n\t\t\tif (ignore_subdir(leaf)) return;\n\t\t\tif (!pred(l)) return;\n\t\t\tbasic_path<Str, PathTraits> f(p \/ l);\n\t\t\tif (is_directory(f))\n\t\t\t{\n\t\t\t\tfor (basic_directory_iterator<basic_path<Str, PathTraits> > i(f), end; i != end; ++i)\n#if BOOST_VERSION < 103600\n\t\t\t\t\tadd_files_impl(fs, p, l \/ i->path().leaf(), pred);\n#else\n\t\t\t\t\tadd_files_impl(fs, p, l \/ i->path().filename(), pred);\n#endif\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint file_flags = get_file_attributes(f);\n\t\t\t\tfs.add_file(l, file_size(f), file_flags);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ path versions\n\n\ttemplate <class Pred>\n\tvoid add_files(file_storage& fs, boost::filesystem::path const& file, Pred p)\n\t{\n\t\tusing boost::filesystem::path;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), path(file.leaf()), p);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), path(file.filename()), p);\n#endif\n\t}\n\n\tinline void add_files(file_storage& fs, boost::filesystem::path const& file)\n\t{\n\t\tusing boost::filesystem::path;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), path(file.leaf()), detail::default_pred);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), path(file.filename()), detail::default_pred);\n#endif\n\t}\n\t\n\tstruct piece_holder\n\t{\n\t\tpiece_holder(int bytes): m_piece(page_aligned_allocator::malloc(bytes)) {}\n\t\t~piece_holder() { page_aligned_allocator::free(m_piece); }\n\t\tchar* bytes() { return m_piece; }\n\tprivate:\n\t\tchar* m_piece;\n\t};\n\n\ttemplate <class Fun>\n\tvoid set_piece_hashes(create_torrent& t, boost::filesystem::path const& p, Fun f)\n\t{\n\t\tfile_pool fp;\n\t\tboost::scoped_ptr<storage_interface> st(\n\t\t\tdefault_storage_constructor(const_cast<file_storage&>(t.files()), p, fp));\n\n\t\t\/\/ calculate the hash for all pieces\n\t\tint num = t.num_pieces();\n\t\tpiece_holder buf(t.piece_length());\n\t\tfor (int i = 0; i < num; ++i)\n\t\t{\n\t\t\t\/\/ read hits the disk and will block. Progress should\n\t\t\t\/\/ be updated in between reads\n\t\t\tst->read(buf.bytes(), i, 0, t.piece_size(i));\n\t\t\thasher h(buf.bytes(), t.piece_size(i));\n\t\t\tt.set_hash(i, h.final());\n\t\t\tf(i);\n\t\t}\n\t}\n\n\tinline void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p)\n\t{\n\t\tset_piece_hashes(t, p, detail::nop);\n\t}\n\n\t\/\/ wpath versions\n\n\ttemplate <class Pred>\n\tvoid add_files(file_storage& fs, boost::filesystem::wpath const& file, Pred p)\n\t{\n\t\tusing boost::filesystem::wpath;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), wpath(file.leaf()), p);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), wpath(file.filename()), p);\n#endif\n\t}\n\n\tinline void add_files(file_storage& fs, boost::filesystem::wpath const& file)\n\t{\n\t\tusing boost::filesystem::wpath;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), wpath(file.leaf()), detail::wdefault_pred);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), wpath(file.filename()), detail::wdefault_pred);\n#endif\n\t}\n\t\n\ttemplate <class Fun>\n\tvoid set_piece_hashes(create_torrent& t, boost::filesystem::wpath const& p, Fun f)\n\t{\n\t\tfile_pool fp;\n\t\tstd::string utf8;\n\t\twchar_utf8(p.string(), utf8);\n\t\tboost::scoped_ptr<storage_interface> st(\n\t\t\tdefault_storage_constructor(const_cast<file_storage&>(t.files()), utf8, fp));\n\n\t\t\/\/ calculate the hash for all pieces\n\t\tint num = t.num_pieces();\n\t\tstd::vector<char> buf(t.piece_length());\n\t\tfor (int i = 0; i < num; ++i)\n\t\t{\n\t\t\t\/\/ read hits the disk and will block. Progress should\n\t\t\t\/\/ be updated in between reads\n\t\t\tst->read(&buf[0], i, 0, t.piece_size(i));\n\t\t\thasher h(&buf[0], t.piece_size(i));\n\t\t\tt.set_hash(i, h.final());\n\t\t\tf(i);\n\t\t}\n\t}\n\n\tinline void set_piece_hashes(create_torrent& t, boost::filesystem::wpath const& p)\n\t{\n\t\tset_piece_hashes(t, p, detail::nop);\n\t}\n}\n\n#endif\n\n<commit_msg>added missing export directives<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CREATE_TORRENT_HPP_INCLUDED\n#define TORRENT_CREATE_TORRENT_HPP_INCLUDED\n\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/file_storage.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include \"libtorrent\/allocator.hpp\"\n\n#include <vector>\n#include <string>\n#include <utility>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\nnamespace libtorrent\n{\n\tnamespace fs = boost::filesystem;\n\tnamespace pt = boost::posix_time;\n\tclass torrent_info;\n\n\tstruct TORRENT_EXPORT create_torrent\n\t{\n\t\tcreate_torrent(file_storage& fs, int piece_size = 0, int pad_file_limit = -1);\n\t\tcreate_torrent(torrent_info const& ti);\n\t\tentry generate() const;\n\n\t\tfile_storage const& files() const { return m_files; }\n\n\t\tvoid set_comment(char const* str);\n\t\tvoid set_creator(char const* str);\n\t\tvoid set_hash(int index, sha1_hash const& h);\n\t\tvoid add_url_seed(std::string const& url);\n\t\tvoid add_node(std::pair<std::string, int> const& node);\n\t\tvoid add_tracker(std::string const& url, int tier = 0);\n\t\tvoid set_priv(bool p) { m_private = p; }\n\n\t\tint num_pieces() const { return m_files.num_pieces(); }\n\t\tint piece_length() const { return m_files.piece_length(); }\n\t\tint piece_size(int i) const { return m_files.piece_size(i); }\n\t\tbool priv() const { return m_private; }\n\n\tprivate:\n\n\t\tfile_storage& m_files;\n\t\t\/\/ if m_info_dict is initialized, it is \n\t\t\/\/ used instead of m_files to generate\n\t\t\/\/ the info dictionary\n\t\tentry m_info_dict;\n\n\t\t\/\/ the urls to the trackers\n\t\ttypedef std::pair<std::string, int> announce_entry;\n\t\tstd::vector<announce_entry> m_urls;\n\n\t\tstd::vector<std::string> m_url_seeds;\n\n\t\tstd::vector<sha1_hash> m_piece_hash;\n\n\t\t\/\/ dht nodes to add to the routing table\/bootstrap from\n\t\ttypedef std::vector<std::pair<std::string, int> > nodes_t;\n\t\tnodes_t m_nodes;\n\n\t\t\/\/ the hash that identifies this torrent\n\t\t\/\/ is mutable because it's calculated\n\t\t\/\/ lazily\n\t\tmutable sha1_hash m_info_hash;\n\n\t\t\/\/ if a creation date is found in the torrent file\n\t\t\/\/ this will be set to that, otherwise it'll be\n\t\t\/\/ 1970, Jan 1\n\t\tpt::ptime m_creation_date;\n\n\t\t\/\/ if a comment is found in the torrent file\n\t\t\/\/ this will be set to that comment\n\t\tstd::string m_comment;\n\n\t\t\/\/ an optional string naming the software used\n\t\t\/\/ to create the torrent file\n\t\tstd::string m_created_by;\n\n\t\t\/\/ this is used when creating a torrent. If there's\n\t\t\/\/ only one file there are cases where it's impossible\n\t\t\/\/ to know if it should be written as a multifile torrent\n\t\t\/\/ or not. e.g. test\/test there's one file and one directory\n\t\t\/\/ and they have the same name.\n\t\tbool m_multifile;\n\t\t\n\t\t\/\/ this is true if the torrent is private. i.e., is should not\n\t\t\/\/ be announced on the dht\n\t\tbool m_private;\n\t};\n\n\tnamespace detail\n\t{\n\t\tinline bool default_pred(boost::filesystem::path const&) { return true; }\n\t\tinline bool wdefault_pred(boost::filesystem::wpath const&) { return true; }\n\n\t\tinline bool ignore_subdir(std::string const& leaf)\n\t\t{ return leaf == \"..\" || leaf == \".\"; }\n\n\t\tinline bool ignore_subdir(std::wstring const& leaf)\n\t\t{ return leaf == L\"..\" || leaf == L\".\"; }\n\n\t\tinline void nop(int i) {}\n\n\t\tint TORRENT_EXPORT get_file_attributes(boost::filesystem::path const& p);\n\t\tint TORRENT_EXPORT get_file_attributes(boost::filesystem::wpath const& p);\n\n\t\ttemplate <class Pred, class Str, class PathTraits>\n\t\tvoid add_files_impl(file_storage& fs, boost::filesystem::basic_path<Str, PathTraits> const& p\n\t\t\t, boost::filesystem::basic_path<Str, PathTraits> const& l, Pred pred)\n\t\t{\n\t\t\tusing boost::filesystem::basic_path;\n\t\t\tusing boost::filesystem::basic_directory_iterator;\n#if BOOST_VERSION < 103600\n\t\t\tStr const& leaf = l.leaf();\n#else\n\t\t\tStr const& leaf = l.filename();\n#endif\n\t\t\tif (ignore_subdir(leaf)) return;\n\t\t\tif (!pred(l)) return;\n\t\t\tbasic_path<Str, PathTraits> f(p \/ l);\n\t\t\tif (is_directory(f))\n\t\t\t{\n\t\t\t\tfor (basic_directory_iterator<basic_path<Str, PathTraits> > i(f), end; i != end; ++i)\n#if BOOST_VERSION < 103600\n\t\t\t\t\tadd_files_impl(fs, p, l \/ i->path().leaf(), pred);\n#else\n\t\t\t\t\tadd_files_impl(fs, p, l \/ i->path().filename(), pred);\n#endif\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint file_flags = get_file_attributes(f);\n\t\t\t\tfs.add_file(l, file_size(f), file_flags);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ path versions\n\n\ttemplate <class Pred>\n\tvoid add_files(file_storage& fs, boost::filesystem::path const& file, Pred p)\n\t{\n\t\tusing boost::filesystem::path;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), path(file.leaf()), p);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), path(file.filename()), p);\n#endif\n\t}\n\n\tinline void add_files(file_storage& fs, boost::filesystem::path const& file)\n\t{\n\t\tusing boost::filesystem::path;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), path(file.leaf()), detail::default_pred);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), path(file.filename()), detail::default_pred);\n#endif\n\t}\n\t\n\tstruct piece_holder\n\t{\n\t\tpiece_holder(int bytes): m_piece(page_aligned_allocator::malloc(bytes)) {}\n\t\t~piece_holder() { page_aligned_allocator::free(m_piece); }\n\t\tchar* bytes() { return m_piece; }\n\tprivate:\n\t\tchar* m_piece;\n\t};\n\n\ttemplate <class Fun>\n\tvoid set_piece_hashes(create_torrent& t, boost::filesystem::path const& p, Fun f)\n\t{\n\t\tfile_pool fp;\n\t\tboost::scoped_ptr<storage_interface> st(\n\t\t\tdefault_storage_constructor(const_cast<file_storage&>(t.files()), p, fp));\n\n\t\t\/\/ calculate the hash for all pieces\n\t\tint num = t.num_pieces();\n\t\tpiece_holder buf(t.piece_length());\n\t\tfor (int i = 0; i < num; ++i)\n\t\t{\n\t\t\t\/\/ read hits the disk and will block. Progress should\n\t\t\t\/\/ be updated in between reads\n\t\t\tst->read(buf.bytes(), i, 0, t.piece_size(i));\n\t\t\thasher h(buf.bytes(), t.piece_size(i));\n\t\t\tt.set_hash(i, h.final());\n\t\t\tf(i);\n\t\t}\n\t}\n\n\tinline void set_piece_hashes(create_torrent& t, boost::filesystem::path const& p)\n\t{\n\t\tset_piece_hashes(t, p, detail::nop);\n\t}\n\n\t\/\/ wpath versions\n\n\ttemplate <class Pred>\n\tvoid add_files(file_storage& fs, boost::filesystem::wpath const& file, Pred p)\n\t{\n\t\tusing boost::filesystem::wpath;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), wpath(file.leaf()), p);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), wpath(file.filename()), p);\n#endif\n\t}\n\n\tinline void add_files(file_storage& fs, boost::filesystem::wpath const& file)\n\t{\n\t\tusing boost::filesystem::wpath;\n#if BOOST_VERSION < 103600\n\t\tdetail::add_files_impl(fs, complete(file).branch_path(), wpath(file.leaf()), detail::wdefault_pred);\n#else\n\t\tdetail::add_files_impl(fs, complete(file).parent_path(), wpath(file.filename()), detail::wdefault_pred);\n#endif\n\t}\n\t\n\ttemplate <class Fun>\n\tvoid set_piece_hashes(create_torrent& t, boost::filesystem::wpath const& p, Fun f)\n\t{\n\t\tfile_pool fp;\n\t\tstd::string utf8;\n\t\twchar_utf8(p.string(), utf8);\n\t\tboost::scoped_ptr<storage_interface> st(\n\t\t\tdefault_storage_constructor(const_cast<file_storage&>(t.files()), utf8, fp));\n\n\t\t\/\/ calculate the hash for all pieces\n\t\tint num = t.num_pieces();\n\t\tstd::vector<char> buf(t.piece_length());\n\t\tfor (int i = 0; i < num; ++i)\n\t\t{\n\t\t\t\/\/ read hits the disk and will block. Progress should\n\t\t\t\/\/ be updated in between reads\n\t\t\tst->read(&buf[0], i, 0, t.piece_size(i));\n\t\t\thasher h(&buf[0], t.piece_size(i));\n\t\t\tt.set_hash(i, h.final());\n\t\t\tf(i);\n\t\t}\n\t}\n\n\tinline void set_piece_hashes(create_torrent& t, boost::filesystem::wpath const& p)\n\t{\n\t\tset_piece_hashes(t, p, detail::nop);\n\t}\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_DISK_IO_THREAD\n#define TORRENT_DISK_IO_THREAD\n\n#ifdef TORRENT_DISK_STATS\n#include <fstream>\n#endif\n\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/allocator.hpp\"\n#include <boost\/thread\/thread.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/condition.hpp>\n#include <boost\/function.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/noncopyable.hpp>\n#include <boost\/shared_array.hpp>\n#include <list>\n#include \"libtorrent\/config.hpp\"\n#ifndef TORRENT_DISABLE_POOL_ALLOCATOR\n#include <boost\/pool\/pool.hpp>\n#endif\n#include \"libtorrent\/session_settings.hpp\"\n\nnamespace libtorrent\n{\n\tstruct cached_piece_info\n\t{\n\t\tint piece;\n\t\tstd::vector<bool> blocks;\n\t\tptime last_use;\n\t\tenum kind_t { read_cache = 0, write_cache = 1 };\n\t\tkind_t kind;\n\t};\n\t\n\tstruct disk_io_job\n\t{\n\t\tdisk_io_job()\n\t\t\t: action(read)\n\t\t\t, buffer(0)\n\t\t\t, buffer_size(0)\n\t\t\t, piece(0)\n\t\t\t, offset(0)\n\t\t\t, priority(0)\n\t\t{}\n\n\t\tenum action_t\n\t\t{\n\t\t\tread\n\t\t\t, write\n\t\t\t, hash\n\t\t\t, move_storage\n\t\t\t, release_files\n\t\t\t, delete_files\n\t\t\t, check_fastresume\n\t\t\t, check_files\n\t\t\t, save_resume_data\n\t\t\t, rename_file\n\t\t\t, abort_thread\n\t\t\t, clear_read_cache\n\t\t\t, abort_torrent\n\t\t\t, update_settings\n\t\t\t, read_and_hash\n\t\t};\n\n\t\taction_t action;\n\n\t\tchar* buffer;\n\t\tint buffer_size;\n\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\/\/ arguments used for read and write\n\t\tint piece, offset;\n\t\t\/\/ used for move_storage and rename_file. On errors, this is set\n\t\t\/\/ to the error message\n\t\tstd::string str;\n\n\t\t\/\/ on error, this is set to the path of the\n\t\t\/\/ file the disk operation failed on\n\t\tstd::string error_file;\n\n\t\t\/\/ priority decides whether or not this\n\t\t\/\/ job will skip entries in the queue or\n\t\t\/\/ not. It always skips in front of entries\n\t\t\/\/ with lower priority\n\t\tint priority;\n\n\t\tboost::shared_ptr<entry> resume_data;\n\n\t\t\/\/ the error code from the file operation\n\t\terror_code error;\n\n\t\t\/\/ this is called when operation completes\n\t\tboost::function<void(int, disk_io_job const&)> callback;\n\t};\n\n\tstruct cache_status\n\t{\n\t\tcache_status()\n\t\t\t: blocks_written(0)\n\t\t\t, writes(0)\n\t\t\t, blocks_read(0)\n\t\t\t, blocks_read_hit(0)\n\t\t\t, reads(0)\n\t\t\t, cache_size(0)\n\t\t\t, read_cache_size(0)\n\t\t{}\n\n\t\t\/\/ the number of 16kB blocks written\n\t\tsize_type blocks_written;\n\t\t\/\/ the number of write operations used\n\t\tsize_type writes;\n\t\t\/\/ (blocks_written - writes) \/ blocks_written represents the\n\t\t\/\/ \"cache hit\" ratio in the write cache\n\t\t\/\/ the number of blocks read\n\n\t\t\/\/ the number of blocks passed back to the bittorrent engine\n\t\tsize_type blocks_read;\n\t\t\/\/ the number of blocks that was just copied from the read cache\n\t\tsize_type blocks_read_hit;\n\t\t\/\/ the number of read operations used\n\t\tsize_type reads;\n\n\t\t\/\/ the number of blocks in the cache (both read and write)\n\t\tint cache_size;\n\n\t\t\/\/ the number of blocks in the cache used for read cache\n\t\tint read_cache_size;\n\t};\n\t\n\tstruct disk_buffer_pool : boost::noncopyable\n\t{\n\t\tdisk_buffer_pool(int block_size);\n\n#ifdef TORRENT_DEBUG\n\t\tbool is_disk_buffer(char* buffer) const;\n#endif\n\n\t\tchar* allocate_buffer(char const* category);\n\t\tvoid free_buffer(char* buf);\n\n\t\tchar* allocate_buffers(int blocks, char const* category);\n\t\tvoid free_buffers(char* buf, int blocks);\n\n\t\tint block_size() const { return m_block_size; }\n\n#ifdef TORRENT_STATS\n\t\tint disk_allocations() const\n\t\t{ return m_allocations; }\n#endif\n\n\t\tvoid release_memory();\n\n\tprotected:\n\n\t\t\/\/ number of bytes per block. The BitTorrent\n\t\t\/\/ protocol defines the block size to 16 KiB.\n\t\tconst int m_block_size;\n\n\t\tsession_settings m_settings;\n\n\tprivate:\n\n\t\t\/\/ this only protects the pool allocator\n\t\ttypedef boost::mutex mutex_t;\n\t\tmutable mutex_t m_pool_mutex;\n#ifndef TORRENT_DISABLE_POOL_ALLOCATOR\n\t\t\/\/ memory pool for read and write operations\n\t\t\/\/ and disk cache\n\t\tboost::pool<page_aligned_allocator> m_pool;\n#endif\n\n#ifdef TORRENT_STATS\n\t\tint m_allocations;\n\t\tstd::map<std::string, int> m_categories;\n\t\tstd::map<char*, std::string> m_buf_to_category;\n\t\tstd::ofstream m_log;\n#endif\n\t};\n\n\t\/\/ this is a singleton consisting of the thread and a queue\n\t\/\/ of disk io jobs\n\tstruct disk_io_thread : disk_buffer_pool\n\t{\n\t\tdisk_io_thread(io_service& ios, int block_size = 16 * 1024);\n\t\t~disk_io_thread();\n\n\t\tvoid join();\n\n\t\t\/\/ aborts read operations\n\t\tvoid stop(boost::intrusive_ptr<piece_manager> s);\n\t\tvoid add_job(disk_io_job const& j\n\t\t\t, boost::function<void(int, disk_io_job const&)> const& f\n\t\t\t= boost::function<void(int, disk_io_job const&)>());\n\n\t\t\/\/ keep track of the number of bytes in the job queue\n\t\t\/\/ at any given time. i.e. the sum of all buffer_size.\n\t\t\/\/ this is used to slow down the download global download\n\t\t\/\/ speed when the queue buffer size is too big.\n\t\tsize_type queue_buffer_size() const\n\t\t{ return m_queue_buffer_size; }\n\n\t\tvoid get_cache_info(sha1_hash const& ih\n\t\t\t, std::vector<cached_piece_info>& ret) const;\n\n\t\tcache_status status() const;\n\n\t\tvoid operator()();\n\n#ifdef TORRENT_DEBUG\n\t\tvoid check_invariant() const;\n#endif\n\t\t\n\tprivate:\n\n\t\tstruct cached_piece_entry\n\t\t{\n\t\t\tint piece;\n\t\t\t\/\/ storage this piece belongs to\n\t\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\t\/\/ the last time a block was writting to this piece\n\t\t\tptime last_use;\n\t\t\t\/\/ the number of blocks in the cache for this piece\n\t\t\tint num_blocks;\n\t\t\t\/\/ the pointers to the block data\n\t\t\tboost::shared_array<char*> blocks;\n\t\t};\n\n\t\ttypedef boost::recursive_mutex mutex_t;\n\t\ttypedef std::list<cached_piece_entry> cache_t;\n\n\t\tbool test_error(disk_io_job& j);\n\n\t\t\/\/ cache operations\n\t\tcache_t::iterator find_cached_piece(\n\t\t\tcache_t& cache, disk_io_job const& j\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint copy_from_piece(cache_t::iterator p, bool& hit\n\t\t\t, disk_io_job const& j, mutex_t::scoped_lock& l);\n\n\t\t\/\/ write cache operations\n\t\tvoid flush_oldest_piece(mutex_t::scoped_lock& l);\n\t\tvoid flush_expired_pieces();\n\t\tvoid flush_and_remove(cache_t::iterator i, mutex_t::scoped_lock& l);\n\t\tvoid flush(cache_t::iterator i, mutex_t::scoped_lock& l);\n\t\tvoid cache_block(disk_io_job& j, mutex_t::scoped_lock& l);\n\n\t\t\/\/ read cache operations\n\t\tbool clear_oldest_read_piece(cache_t::iterator ignore\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint read_into_piece(cached_piece_entry& p, int start_block\n\t\t\t, int options, mutex_t::scoped_lock& l);\n\t\tint cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l);\n\t\tint cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l);\n\t\tvoid free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l);\n\t\tbool make_room(int num_blocks\n\t\t\t, cache_t::iterator ignore\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint try_read_from_cache(disk_io_job const& j);\n\t\tint read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h);\n\n\t\t\/\/ this mutex only protects m_jobs, m_queue_buffer_size\n\t\t\/\/ and m_abort\n\t\tmutable mutex_t m_queue_mutex;\n\t\tboost::condition m_signal;\n\t\tbool m_abort;\n\t\tstd::list<disk_io_job> m_jobs;\n\t\tsize_type m_queue_buffer_size;\n\n\t\t\/\/ this protects the piece cache and related members\n\t\tmutable mutex_t m_piece_mutex;\n\t\t\/\/ write cache\n\t\tcache_t m_pieces;\n\t\t\n\t\t\/\/ read cache\n\t\tcache_t m_read_pieces;\n\n\t\t\/\/ total number of blocks in use by both the read\n\t\t\/\/ and the write cache. This is not supposed to\n\t\t\/\/ exceed m_cache_size\n\t\tcache_status m_cache_stats;\n\t\tint m_num_cached_blocks;\n\n#ifdef TORRENT_DISK_STATS\n\t\tstd::ofstream m_log;\n#endif\n\t\tsize_type m_writes;\n\t\tsize_type m_blocks_written;\n\n\t\tio_service& m_ios;\n\n\t\t\/\/ thread for performing blocking disk io operations\n\t\tboost::thread m_disk_io_thread;\n\t};\n\n}\n\n#endif\n\n<commit_msg>removed unused member variable<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_DISK_IO_THREAD\n#define TORRENT_DISK_IO_THREAD\n\n#ifdef TORRENT_DISK_STATS\n#include <fstream>\n#endif\n\n#include \"libtorrent\/storage.hpp\"\n#include \"libtorrent\/allocator.hpp\"\n#include <boost\/thread\/thread.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/condition.hpp>\n#include <boost\/function.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/noncopyable.hpp>\n#include <boost\/shared_array.hpp>\n#include <list>\n#include \"libtorrent\/config.hpp\"\n#ifndef TORRENT_DISABLE_POOL_ALLOCATOR\n#include <boost\/pool\/pool.hpp>\n#endif\n#include \"libtorrent\/session_settings.hpp\"\n\nnamespace libtorrent\n{\n\tstruct cached_piece_info\n\t{\n\t\tint piece;\n\t\tstd::vector<bool> blocks;\n\t\tptime last_use;\n\t\tenum kind_t { read_cache = 0, write_cache = 1 };\n\t\tkind_t kind;\n\t};\n\t\n\tstruct disk_io_job\n\t{\n\t\tdisk_io_job()\n\t\t\t: action(read)\n\t\t\t, buffer(0)\n\t\t\t, buffer_size(0)\n\t\t\t, piece(0)\n\t\t\t, offset(0)\n\t\t\t, priority(0)\n\t\t{}\n\n\t\tenum action_t\n\t\t{\n\t\t\tread\n\t\t\t, write\n\t\t\t, hash\n\t\t\t, move_storage\n\t\t\t, release_files\n\t\t\t, delete_files\n\t\t\t, check_fastresume\n\t\t\t, check_files\n\t\t\t, save_resume_data\n\t\t\t, rename_file\n\t\t\t, abort_thread\n\t\t\t, clear_read_cache\n\t\t\t, abort_torrent\n\t\t\t, update_settings\n\t\t\t, read_and_hash\n\t\t};\n\n\t\taction_t action;\n\n\t\tchar* buffer;\n\t\tint buffer_size;\n\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\/\/ arguments used for read and write\n\t\tint piece, offset;\n\t\t\/\/ used for move_storage and rename_file. On errors, this is set\n\t\t\/\/ to the error message\n\t\tstd::string str;\n\n\t\t\/\/ on error, this is set to the path of the\n\t\t\/\/ file the disk operation failed on\n\t\tstd::string error_file;\n\n\t\t\/\/ priority decides whether or not this\n\t\t\/\/ job will skip entries in the queue or\n\t\t\/\/ not. It always skips in front of entries\n\t\t\/\/ with lower priority\n\t\tint priority;\n\n\t\tboost::shared_ptr<entry> resume_data;\n\n\t\t\/\/ the error code from the file operation\n\t\terror_code error;\n\n\t\t\/\/ this is called when operation completes\n\t\tboost::function<void(int, disk_io_job const&)> callback;\n\t};\n\n\tstruct cache_status\n\t{\n\t\tcache_status()\n\t\t\t: blocks_written(0)\n\t\t\t, writes(0)\n\t\t\t, blocks_read(0)\n\t\t\t, blocks_read_hit(0)\n\t\t\t, reads(0)\n\t\t\t, cache_size(0)\n\t\t\t, read_cache_size(0)\n\t\t{}\n\n\t\t\/\/ the number of 16kB blocks written\n\t\tsize_type blocks_written;\n\t\t\/\/ the number of write operations used\n\t\tsize_type writes;\n\t\t\/\/ (blocks_written - writes) \/ blocks_written represents the\n\t\t\/\/ \"cache hit\" ratio in the write cache\n\t\t\/\/ the number of blocks read\n\n\t\t\/\/ the number of blocks passed back to the bittorrent engine\n\t\tsize_type blocks_read;\n\t\t\/\/ the number of blocks that was just copied from the read cache\n\t\tsize_type blocks_read_hit;\n\t\t\/\/ the number of read operations used\n\t\tsize_type reads;\n\n\t\t\/\/ the number of blocks in the cache (both read and write)\n\t\tint cache_size;\n\n\t\t\/\/ the number of blocks in the cache used for read cache\n\t\tint read_cache_size;\n\t};\n\t\n\tstruct disk_buffer_pool : boost::noncopyable\n\t{\n\t\tdisk_buffer_pool(int block_size);\n\n#ifdef TORRENT_DEBUG\n\t\tbool is_disk_buffer(char* buffer) const;\n#endif\n\n\t\tchar* allocate_buffer(char const* category);\n\t\tvoid free_buffer(char* buf);\n\n\t\tchar* allocate_buffers(int blocks, char const* category);\n\t\tvoid free_buffers(char* buf, int blocks);\n\n\t\tint block_size() const { return m_block_size; }\n\n#ifdef TORRENT_STATS\n\t\tint disk_allocations() const\n\t\t{ return m_allocations; }\n#endif\n\n\t\tvoid release_memory();\n\n\tprotected:\n\n\t\t\/\/ number of bytes per block. The BitTorrent\n\t\t\/\/ protocol defines the block size to 16 KiB.\n\t\tconst int m_block_size;\n\n\t\tsession_settings m_settings;\n\n\tprivate:\n\n\t\t\/\/ this only protects the pool allocator\n\t\ttypedef boost::mutex mutex_t;\n\t\tmutable mutex_t m_pool_mutex;\n#ifndef TORRENT_DISABLE_POOL_ALLOCATOR\n\t\t\/\/ memory pool for read and write operations\n\t\t\/\/ and disk cache\n\t\tboost::pool<page_aligned_allocator> m_pool;\n#endif\n\n#ifdef TORRENT_STATS\n\t\tint m_allocations;\n\t\tstd::map<std::string, int> m_categories;\n\t\tstd::map<char*, std::string> m_buf_to_category;\n\t\tstd::ofstream m_log;\n#endif\n\t};\n\n\t\/\/ this is a singleton consisting of the thread and a queue\n\t\/\/ of disk io jobs\n\tstruct disk_io_thread : disk_buffer_pool\n\t{\n\t\tdisk_io_thread(io_service& ios, int block_size = 16 * 1024);\n\t\t~disk_io_thread();\n\n\t\tvoid join();\n\n\t\t\/\/ aborts read operations\n\t\tvoid stop(boost::intrusive_ptr<piece_manager> s);\n\t\tvoid add_job(disk_io_job const& j\n\t\t\t, boost::function<void(int, disk_io_job const&)> const& f\n\t\t\t= boost::function<void(int, disk_io_job const&)>());\n\n\t\t\/\/ keep track of the number of bytes in the job queue\n\t\t\/\/ at any given time. i.e. the sum of all buffer_size.\n\t\t\/\/ this is used to slow down the download global download\n\t\t\/\/ speed when the queue buffer size is too big.\n\t\tsize_type queue_buffer_size() const\n\t\t{ return m_queue_buffer_size; }\n\n\t\tvoid get_cache_info(sha1_hash const& ih\n\t\t\t, std::vector<cached_piece_info>& ret) const;\n\n\t\tcache_status status() const;\n\n\t\tvoid operator()();\n\n#ifdef TORRENT_DEBUG\n\t\tvoid check_invariant() const;\n#endif\n\t\t\n\tprivate:\n\n\t\tstruct cached_piece_entry\n\t\t{\n\t\t\tint piece;\n\t\t\t\/\/ storage this piece belongs to\n\t\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\t\/\/ the last time a block was writting to this piece\n\t\t\tptime last_use;\n\t\t\t\/\/ the number of blocks in the cache for this piece\n\t\t\tint num_blocks;\n\t\t\t\/\/ the pointers to the block data\n\t\t\tboost::shared_array<char*> blocks;\n\t\t};\n\n\t\ttypedef boost::recursive_mutex mutex_t;\n\t\ttypedef std::list<cached_piece_entry> cache_t;\n\n\t\tbool test_error(disk_io_job& j);\n\n\t\t\/\/ cache operations\n\t\tcache_t::iterator find_cached_piece(\n\t\t\tcache_t& cache, disk_io_job const& j\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint copy_from_piece(cache_t::iterator p, bool& hit\n\t\t\t, disk_io_job const& j, mutex_t::scoped_lock& l);\n\n\t\t\/\/ write cache operations\n\t\tvoid flush_oldest_piece(mutex_t::scoped_lock& l);\n\t\tvoid flush_expired_pieces();\n\t\tvoid flush_and_remove(cache_t::iterator i, mutex_t::scoped_lock& l);\n\t\tvoid flush(cache_t::iterator i, mutex_t::scoped_lock& l);\n\t\tvoid cache_block(disk_io_job& j, mutex_t::scoped_lock& l);\n\n\t\t\/\/ read cache operations\n\t\tbool clear_oldest_read_piece(cache_t::iterator ignore\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint read_into_piece(cached_piece_entry& p, int start_block\n\t\t\t, int options, mutex_t::scoped_lock& l);\n\t\tint cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l);\n\t\tint cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l);\n\t\tvoid free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l);\n\t\tbool make_room(int num_blocks\n\t\t\t, cache_t::iterator ignore\n\t\t\t, mutex_t::scoped_lock& l);\n\t\tint try_read_from_cache(disk_io_job const& j);\n\t\tint read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h);\n\n\t\t\/\/ this mutex only protects m_jobs, m_queue_buffer_size\n\t\t\/\/ and m_abort\n\t\tmutable mutex_t m_queue_mutex;\n\t\tboost::condition m_signal;\n\t\tbool m_abort;\n\t\tstd::list<disk_io_job> m_jobs;\n\t\tsize_type m_queue_buffer_size;\n\n\t\t\/\/ this protects the piece cache and related members\n\t\tmutable mutex_t m_piece_mutex;\n\t\t\/\/ write cache\n\t\tcache_t m_pieces;\n\t\t\n\t\t\/\/ read cache\n\t\tcache_t m_read_pieces;\n\n\t\t\/\/ total number of blocks in use by both the read\n\t\t\/\/ and the write cache. This is not supposed to\n\t\t\/\/ exceed m_cache_size\n\t\tcache_status m_cache_stats;\n\n#ifdef TORRENT_DISK_STATS\n\t\tstd::ofstream m_log;\n#endif\n\t\tsize_type m_writes;\n\t\tsize_type m_blocks_written;\n\n\t\tio_service& m_ios;\n\n\t\t\/\/ thread for performing blocking disk io operations\n\t\tboost::thread m_disk_io_thread;\n\t};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifdef TORRENT_DISK_STATS\n#include <fstream>\n#endif\n\n#include \"libtorrent\/storage.hpp\"\n#include <boost\/thread\/thread.hpp>\n#include <boost\/function.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/pool\/pool.hpp>\n#include <boost\/noncopyable.hpp>\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\n\tstruct disk_io_job\n\t{\n\t\tdisk_io_job()\n\t\t\t: action(read)\n\t\t\t, buffer(0)\n\t\t\t, buffer_size(0)\n\t\t\t, piece(0)\n\t\t\t, offset(0)\n\t\t\t, priority(0)\n\t\t{}\n\n\t\tenum action_t\n\t\t{\n\t\t\tread\n\t\t\t, write\n\t\t\t, hash\n\t\t\t, move_storage\n\t\t\t, release_files\n\t\t\t, delete_files\n\t\t};\n\n\t\taction_t action;\n\n\t\tchar* buffer;\n\t\tsize_type buffer_size;\n\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\/\/ arguments used for read and write\n\t\tint piece, offset;\n\t\t\/\/ used for move_storage. On errors, this is set\n\t\t\/\/ to the error message\n\t\tstd::string str;\n\n\t\t\/\/ priority decides whether or not this\n\t\t\/\/ job will skip entries in the queue or\n\t\t\/\/ not. It always skips in front of entries\n\t\t\/\/ with lower priority\n\t\tint priority;\n\n\t\t\/\/ this is called when operation completes\n\t\tboost::function<void(int, disk_io_job const&)> callback;\n\t};\n\n\t\/\/ this is a singleton consisting of the thread and a queue\n\t\/\/ of disk io jobs\n\tstruct disk_io_thread : boost::noncopyable\n\t{\n\t\tdisk_io_thread(int block_size = 16 * 1024);\n\t\t~disk_io_thread();\n\n#ifdef TORRENT_STATS\n\t\tint disk_allocations() const\n\t\t{ return m_allocations; }\n#endif\n\t\n\t\t\/\/ aborts read operations\n\t\tvoid stop(boost::intrusive_ptr<piece_manager> s);\n\t\tvoid add_job(disk_io_job const& j\n\t\t\t, boost::function<void(int, disk_io_job const&)> const& f\n\t\t\t= boost::function<void(int, disk_io_job const&)>());\n\n#ifndef NDEBUG\n\t\tdisk_io_job find_job(boost::intrusive_ptr<piece_manager> s\n\t\t\t, int action, int piece) const;\n#endif\n\t\t\/\/ keep track of the number of bytes in the job queue\n\t\t\/\/ at any given time. i.e. the sum of all buffer_size.\n\t\t\/\/ this is used to slow down the download global download\n\t\t\/\/ speed when the queue buffer size is too big.\n\t\tsize_type queue_buffer_size() const\n\t\t{ return m_queue_buffer_size; }\n\n\t\tvoid operator()();\n\n\t\tchar* allocate_buffer();\n\t\tvoid free_buffer(char* buf);\n\n\tprivate:\n\n\t\ttypedef boost::recursive_mutex mutex_t;\n\t\tmutable mutex_t m_mutex;\n\t\tboost::condition m_signal;\n\t\tbool m_abort;\n\t\tstd::deque<disk_io_job> m_jobs;\n\t\tsize_type m_queue_buffer_size;\n\n\t\t\/\/ memory pool for read and write operations\n\t\tboost::pool<> m_pool;\n\n#ifndef NDEBUG\n\t\tint m_block_size;\n\t\tdisk_io_job m_current;\n#endif\n\n#ifdef TORRENT_DISK_STATS\n\t\tstd::ofstream m_log;\n#endif\n#ifdef TORRENT_STATS\n\t\tint m_allocations;\n#endif\n\n\t\t\/\/ thread for performing blocking disk io operations\n\t\tboost::thread m_disk_io_thread;\n\t};\n\n}\n\n<commit_msg>added missing include guard to disk_io_thread.hpp<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_DISK_IO_THREAD\n#define TORRENT_DISK_IO_THREAD\n\n#ifdef TORRENT_DISK_STATS\n#include <fstream>\n#endif\n\n#include \"libtorrent\/storage.hpp\"\n#include <boost\/thread\/thread.hpp>\n#include <boost\/function.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/pool\/pool.hpp>\n#include <boost\/noncopyable.hpp>\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\n\tstruct disk_io_job\n\t{\n\t\tdisk_io_job()\n\t\t\t: action(read)\n\t\t\t, buffer(0)\n\t\t\t, buffer_size(0)\n\t\t\t, piece(0)\n\t\t\t, offset(0)\n\t\t\t, priority(0)\n\t\t{}\n\n\t\tenum action_t\n\t\t{\n\t\t\tread\n\t\t\t, write\n\t\t\t, hash\n\t\t\t, move_storage\n\t\t\t, release_files\n\t\t\t, delete_files\n\t\t};\n\n\t\taction_t action;\n\n\t\tchar* buffer;\n\t\tsize_type buffer_size;\n\t\tboost::intrusive_ptr<piece_manager> storage;\n\t\t\/\/ arguments used for read and write\n\t\tint piece, offset;\n\t\t\/\/ used for move_storage. On errors, this is set\n\t\t\/\/ to the error message\n\t\tstd::string str;\n\n\t\t\/\/ priority decides whether or not this\n\t\t\/\/ job will skip entries in the queue or\n\t\t\/\/ not. It always skips in front of entries\n\t\t\/\/ with lower priority\n\t\tint priority;\n\n\t\t\/\/ this is called when operation completes\n\t\tboost::function<void(int, disk_io_job const&)> callback;\n\t};\n\n\t\/\/ this is a singleton consisting of the thread and a queue\n\t\/\/ of disk io jobs\n\tstruct disk_io_thread : boost::noncopyable\n\t{\n\t\tdisk_io_thread(int block_size = 16 * 1024);\n\t\t~disk_io_thread();\n\n#ifdef TORRENT_STATS\n\t\tint disk_allocations() const\n\t\t{ return m_allocations; }\n#endif\n\t\n\t\t\/\/ aborts read operations\n\t\tvoid stop(boost::intrusive_ptr<piece_manager> s);\n\t\tvoid add_job(disk_io_job const& j\n\t\t\t, boost::function<void(int, disk_io_job const&)> const& f\n\t\t\t= boost::function<void(int, disk_io_job const&)>());\n\n#ifndef NDEBUG\n\t\tdisk_io_job find_job(boost::intrusive_ptr<piece_manager> s\n\t\t\t, int action, int piece) const;\n#endif\n\t\t\/\/ keep track of the number of bytes in the job queue\n\t\t\/\/ at any given time. i.e. the sum of all buffer_size.\n\t\t\/\/ this is used to slow down the download global download\n\t\t\/\/ speed when the queue buffer size is too big.\n\t\tsize_type queue_buffer_size() const\n\t\t{ return m_queue_buffer_size; }\n\n\t\tvoid operator()();\n\n\t\tchar* allocate_buffer();\n\t\tvoid free_buffer(char* buf);\n\n\tprivate:\n\n\t\ttypedef boost::recursive_mutex mutex_t;\n\t\tmutable mutex_t m_mutex;\n\t\tboost::condition m_signal;\n\t\tbool m_abort;\n\t\tstd::deque<disk_io_job> m_jobs;\n\t\tsize_type m_queue_buffer_size;\n\n\t\t\/\/ memory pool for read and write operations\n\t\tboost::pool<> m_pool;\n\n#ifndef NDEBUG\n\t\tint m_block_size;\n\t\tdisk_io_job m_current;\n#endif\n\n#ifdef TORRENT_DISK_STATS\n\t\tstd::ofstream m_log;\n#endif\n#ifdef TORRENT_STATS\n\t\tint m_allocations;\n#endif\n\n\t\t\/\/ thread for performing blocking disk io operations\n\t\tboost::thread m_disk_io_thread;\n\t};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Function.cpp - Implement the Global object classes ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Function class for the VMCore library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ParameterAttributes.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include \"SymbolTableListTraitsImpl.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\nusing namespace llvm;\n\nBasicBlock *ilist_traits<BasicBlock>::createSentinel() {\n BasicBlock *Ret = new BasicBlock();\n \/\/ This should not be garbage monitored.\n LeakDetector::removeGarbageObject(Ret);\n return Ret;\n}\n\niplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {\n return F->getBasicBlockList();\n}\n\nArgument *ilist_traits<Argument>::createSentinel() {\n Argument *Ret = new Argument(Type::Int32Ty);\n \/\/ This should not be garbage monitored.\n LeakDetector::removeGarbageObject(Ret);\n return Ret;\n}\n\niplist<Argument> &ilist_traits<Argument>::getList(Function *F) {\n return F->getArgumentList();\n}\n\n\/\/ Explicit instantiations of SymbolTableListTraits since some of the methods\n\/\/ are not in the public header file...\ntemplate class SymbolTableListTraits<Argument, Function, Function>;\ntemplate class SymbolTableListTraits<BasicBlock, Function, Function>;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Argument Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nArgument::Argument(const Type *Ty, const std::string &Name, Function *Par)\n : Value(Ty, Value::ArgumentVal) {\n Parent = 0;\n\n \/\/ Make sure that we get added to a function\n LeakDetector::addGarbageObject(this);\n\n if (Par)\n Par->getArgumentList().push_back(this);\n setName(Name);\n}\n\nvoid Argument::setParent(Function *parent) {\n if (getParent())\n LeakDetector::addGarbageObject(this);\n Parent = parent;\n if (getParent())\n LeakDetector::removeGarbageObject(this);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ParamAttrsList Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nuint16_t\nParamAttrsList::getParamAttrs(uint16_t Index) const {\n unsigned limit = attrs.size();\n for (unsigned i = 0; i < limit; ++i)\n if (attrs[i].index == Index)\n return attrs[i].attrs;\n return ParamAttr::None;\n}\n\n\nstd::string \nParamAttrsList::getParamAttrsText(uint16_t Attrs) {\n std::string Result;\n if (Attrs & ParamAttr::ZExt)\n Result += \"zext \";\n if (Attrs & ParamAttr::SExt)\n Result += \"sext \";\n if (Attrs & ParamAttr::NoReturn)\n Result += \"noreturn \";\n if (Attrs & ParamAttr::NoUnwind)\n Result += \"nounwind \";\n if (Attrs & ParamAttr::InReg)\n Result += \"inreg \";\n if (Attrs & ParamAttr::StructRet)\n Result += \"sret \"; \n return Result;\n}\n\nvoid\nParamAttrsList::addAttributes(uint16_t Index, uint16_t Attrs) {\n \/\/ First, try to replace an existing one\n for (unsigned i = 0; i < attrs.size(); ++i)\n if (attrs[i].index == Index) {\n attrs[i].attrs |= Attrs;\n return;\n }\n\n \/\/ If not found, add a new one\n ParamAttrsWithIndex Val;\n Val.attrs = Attrs;\n Val.index = Index;\n attrs.push_back(Val);\n}\n\nvoid\nParamAttrsList::removeAttributes(uint16_t Index, uint16_t Attrs) {\n \/\/ Find the index from which to remove the attributes\n for (unsigned i = 0; i < attrs.size(); ++i)\n if (attrs[i].index == Index) {\n attrs[i].attrs &= ~Attrs;\n if (attrs[i].attrs == ParamAttr::None)\n attrs.erase(&attrs[i]);\n return;\n }\n\n \/\/ The index wasn't found above\n assert(0 && \"Index not found for removeAttributes\");\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Function Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nFunction::Function(const FunctionType *Ty, LinkageTypes Linkage,\n const std::string &name, Module *ParentModule)\n : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {\n ParamAttrs = 0;\n CallingConvention = 0;\n BasicBlocks.setItemParent(this);\n BasicBlocks.setParent(this);\n ArgumentList.setItemParent(this);\n ArgumentList.setParent(this);\n SymTab = new ValueSymbolTable();\n\n assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)\n && \"LLVM functions cannot return aggregate values!\");\n\n \/\/ Create the arguments vector, all arguments start out unnamed.\n for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {\n assert(Ty->getParamType(i) != Type::VoidTy &&\n \"Cannot have void typed arguments!\");\n ArgumentList.push_back(new Argument(Ty->getParamType(i)));\n }\n\n \/\/ Make sure that we get added to a function\n LeakDetector::addGarbageObject(this);\n\n if (ParentModule)\n ParentModule->getFunctionList().push_back(this);\n}\n\nFunction::~Function() {\n dropAllReferences(); \/\/ After this it is safe to delete instructions.\n\n \/\/ Delete all of the method arguments and unlink from symbol table...\n ArgumentList.clear();\n ArgumentList.setParent(0);\n delete SymTab;\n}\n\nvoid Function::setParent(Module *parent) {\n if (getParent())\n LeakDetector::addGarbageObject(this);\n Parent = parent;\n if (getParent())\n LeakDetector::removeGarbageObject(this);\n}\n\nconst FunctionType *Function::getFunctionType() const {\n return cast<FunctionType>(getType()->getElementType());\n}\n\nbool Function::isVarArg() const {\n return getFunctionType()->isVarArg();\n}\n\nconst Type *Function::getReturnType() const {\n return getFunctionType()->getReturnType();\n}\n\nvoid Function::removeFromParent() {\n getParent()->getFunctionList().remove(this);\n}\n\nvoid Function::eraseFromParent() {\n getParent()->getFunctionList().erase(this);\n}\n\n\/\/ dropAllReferences() - This function causes all the subinstructions to \"let\n\/\/ go\" of all references that they are maintaining. This allows one to\n\/\/ 'delete' a whole class at a time, even though there may be circular\n\/\/ references... first all references are dropped, and all use counts go to\n\/\/ zero. Then everything is deleted for real. Note that no operations are\n\/\/ valid on an object that has \"dropped all references\", except operator\n\/\/ delete.\n\/\/\nvoid Function::dropAllReferences() {\n for (iterator I = begin(), E = end(); I != E; ++I)\n I->dropAllReferences();\n BasicBlocks.clear(); \/\/ Delete all basic blocks...\n}\n\n\/\/\/ getIntrinsicID - This method returns the ID number of the specified\n\/\/\/ function, or Intrinsic::not_intrinsic if the function is not an\n\/\/\/ intrinsic, or if the pointer is null. This value is always defined to be\n\/\/\/ zero to allow easy checking for whether a function is intrinsic or not. The\n\/\/\/ particular intrinsic functions which correspond to this value are defined in\n\/\/\/ llvm\/Intrinsics.h.\n\/\/\/\nunsigned Function::getIntrinsicID(bool noAssert) const {\n const ValueName *ValName = this->getValueName();\n unsigned Len = ValName->getKeyLength();\n const char *Name = ValName->getKeyData();\n \n if (Len <= 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'\n || Name[2] != 'v' || Name[3] != 'm')\n return 0; \/\/ All intrinsics start with 'llvm.'\n\n assert((Len != 5 || noAssert) && \"'llvm.' is an invalid intrinsic name!\");\n\n#define GET_FUNCTION_RECOGNIZER\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_FUNCTION_RECOGNIZER\n assert(noAssert && \"Invalid LLVM intrinsic name\");\n return 0;\n}\n\nstd::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { \n assert(id < num_intrinsics && \"Invalid intrinsic ID!\");\n const char * const Table[] = {\n \"not_intrinsic\",\n#define GET_INTRINSIC_NAME_TABLE\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_INTRINSIC_NAME_TABLE\n };\n if (numTys == 0)\n return Table[id];\n std::string Result(Table[id]);\n for (unsigned i = 0; i < numTys; ++i) \n if (Tys[i])\n Result += \".\" + Tys[i]->getDescription();\n return Result;\n}\n\nconst FunctionType *Intrinsic::getType(ID id, const Type **Tys, \n uint32_t numTys) {\n const Type *ResultTy = NULL;\n std::vector<const Type*> ArgTys;\n bool IsVarArg = false;\n \n#define GET_INTRINSIC_GENERATOR\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_INTRINSIC_GENERATOR\n\n return FunctionType::get(ResultTy, ArgTys, IsVarArg); \n}\n\nFunction *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, \n unsigned numTys) {\n\/\/ There can never be multiple globals with the same name of different types,\n\/\/ because intrinsics must be a specific type.\n return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), \n getType(id, Tys, numTys)));\n}\n\nValue *IntrinsicInst::StripPointerCasts(Value *Ptr) {\n if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {\n if (CE->getOpcode() == Instruction::BitCast) {\n if (isa<PointerType>(CE->getOperand(0)->getType()))\n return StripPointerCasts(CE->getOperand(0));\n } else if (CE->getOpcode() == Instruction::GetElementPtr) {\n for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)\n if (!CE->getOperand(i)->isNullValue())\n return Ptr;\n return StripPointerCasts(CE->getOperand(0));\n }\n return Ptr;\n }\n\n if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {\n if (isa<PointerType>(CI->getOperand(0)->getType()))\n return StripPointerCasts(CI->getOperand(0));\n } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {\n for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)\n if (!isa<Constant>(GEP->getOperand(i)) ||\n !cast<Constant>(GEP->getOperand(i))->isNullValue())\n return Ptr;\n return StripPointerCasts(GEP->getOperand(0));\n }\n return Ptr;\n}\n\n\/\/ vim: sw=2 ai\n<commit_msg>Fix test\/CodeGen\/Generic\/vector-constantexpr.ll<commit_after>\/\/===-- Function.cpp - Implement the Global object classes ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Function class for the VMCore library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ParameterAttributes.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include \"SymbolTableListTraitsImpl.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\nusing namespace llvm;\n\nBasicBlock *ilist_traits<BasicBlock>::createSentinel() {\n BasicBlock *Ret = new BasicBlock();\n \/\/ This should not be garbage monitored.\n LeakDetector::removeGarbageObject(Ret);\n return Ret;\n}\n\niplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) {\n return F->getBasicBlockList();\n}\n\nArgument *ilist_traits<Argument>::createSentinel() {\n Argument *Ret = new Argument(Type::Int32Ty);\n \/\/ This should not be garbage monitored.\n LeakDetector::removeGarbageObject(Ret);\n return Ret;\n}\n\niplist<Argument> &ilist_traits<Argument>::getList(Function *F) {\n return F->getArgumentList();\n}\n\n\/\/ Explicit instantiations of SymbolTableListTraits since some of the methods\n\/\/ are not in the public header file...\ntemplate class SymbolTableListTraits<Argument, Function, Function>;\ntemplate class SymbolTableListTraits<BasicBlock, Function, Function>;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Argument Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nArgument::Argument(const Type *Ty, const std::string &Name, Function *Par)\n : Value(Ty, Value::ArgumentVal) {\n Parent = 0;\n\n \/\/ Make sure that we get added to a function\n LeakDetector::addGarbageObject(this);\n\n if (Par)\n Par->getArgumentList().push_back(this);\n setName(Name);\n}\n\nvoid Argument::setParent(Function *parent) {\n if (getParent())\n LeakDetector::addGarbageObject(this);\n Parent = parent;\n if (getParent())\n LeakDetector::removeGarbageObject(this);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ParamAttrsList Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nuint16_t\nParamAttrsList::getParamAttrs(uint16_t Index) const {\n unsigned limit = attrs.size();\n for (unsigned i = 0; i < limit; ++i)\n if (attrs[i].index == Index)\n return attrs[i].attrs;\n return ParamAttr::None;\n}\n\n\nstd::string \nParamAttrsList::getParamAttrsText(uint16_t Attrs) {\n std::string Result;\n if (Attrs & ParamAttr::ZExt)\n Result += \"zext \";\n if (Attrs & ParamAttr::SExt)\n Result += \"sext \";\n if (Attrs & ParamAttr::NoReturn)\n Result += \"noreturn \";\n if (Attrs & ParamAttr::NoUnwind)\n Result += \"nounwind \";\n if (Attrs & ParamAttr::InReg)\n Result += \"inreg \";\n if (Attrs & ParamAttr::StructRet)\n Result += \"sret \"; \n return Result;\n}\n\nvoid\nParamAttrsList::addAttributes(uint16_t Index, uint16_t Attrs) {\n \/\/ First, try to replace an existing one\n for (unsigned i = 0; i < attrs.size(); ++i)\n if (attrs[i].index == Index) {\n attrs[i].attrs |= Attrs;\n return;\n }\n\n \/\/ If not found, add a new one\n ParamAttrsWithIndex Val;\n Val.attrs = Attrs;\n Val.index = Index;\n attrs.push_back(Val);\n}\n\nvoid\nParamAttrsList::removeAttributes(uint16_t Index, uint16_t Attrs) {\n \/\/ Find the index from which to remove the attributes\n for (unsigned i = 0; i < attrs.size(); ++i)\n if (attrs[i].index == Index) {\n attrs[i].attrs &= ~Attrs;\n if (attrs[i].attrs == ParamAttr::None)\n attrs.erase(&attrs[i]);\n return;\n }\n\n \/\/ The index wasn't found above\n assert(0 && \"Index not found for removeAttributes\");\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Function Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nFunction::Function(const FunctionType *Ty, LinkageTypes Linkage,\n const std::string &name, Module *ParentModule)\n : GlobalValue(PointerType::get(Ty), Value::FunctionVal, 0, 0, Linkage, name) {\n ParamAttrs = 0;\n CallingConvention = 0;\n BasicBlocks.setItemParent(this);\n BasicBlocks.setParent(this);\n ArgumentList.setItemParent(this);\n ArgumentList.setParent(this);\n SymTab = new ValueSymbolTable();\n\n assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy)\n && \"LLVM functions cannot return aggregate values!\");\n\n \/\/ Create the arguments vector, all arguments start out unnamed.\n for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) {\n assert(Ty->getParamType(i) != Type::VoidTy &&\n \"Cannot have void typed arguments!\");\n ArgumentList.push_back(new Argument(Ty->getParamType(i)));\n }\n\n \/\/ Make sure that we get added to a function\n LeakDetector::addGarbageObject(this);\n\n if (ParentModule)\n ParentModule->getFunctionList().push_back(this);\n}\n\nFunction::~Function() {\n dropAllReferences(); \/\/ After this it is safe to delete instructions.\n\n \/\/ Delete all of the method arguments and unlink from symbol table...\n ArgumentList.clear();\n ArgumentList.setParent(0);\n delete SymTab;\n}\n\nvoid Function::setParent(Module *parent) {\n if (getParent())\n LeakDetector::addGarbageObject(this);\n Parent = parent;\n if (getParent())\n LeakDetector::removeGarbageObject(this);\n}\n\nconst FunctionType *Function::getFunctionType() const {\n return cast<FunctionType>(getType()->getElementType());\n}\n\nbool Function::isVarArg() const {\n return getFunctionType()->isVarArg();\n}\n\nconst Type *Function::getReturnType() const {\n return getFunctionType()->getReturnType();\n}\n\nvoid Function::removeFromParent() {\n getParent()->getFunctionList().remove(this);\n}\n\nvoid Function::eraseFromParent() {\n getParent()->getFunctionList().erase(this);\n}\n\n\/\/ dropAllReferences() - This function causes all the subinstructions to \"let\n\/\/ go\" of all references that they are maintaining. This allows one to\n\/\/ 'delete' a whole class at a time, even though there may be circular\n\/\/ references... first all references are dropped, and all use counts go to\n\/\/ zero. Then everything is deleted for real. Note that no operations are\n\/\/ valid on an object that has \"dropped all references\", except operator\n\/\/ delete.\n\/\/\nvoid Function::dropAllReferences() {\n for (iterator I = begin(), E = end(); I != E; ++I)\n I->dropAllReferences();\n BasicBlocks.clear(); \/\/ Delete all basic blocks...\n}\n\n\/\/\/ getIntrinsicID - This method returns the ID number of the specified\n\/\/\/ function, or Intrinsic::not_intrinsic if the function is not an\n\/\/\/ intrinsic, or if the pointer is null. This value is always defined to be\n\/\/\/ zero to allow easy checking for whether a function is intrinsic or not. The\n\/\/\/ particular intrinsic functions which correspond to this value are defined in\n\/\/\/ llvm\/Intrinsics.h.\n\/\/\/\nunsigned Function::getIntrinsicID(bool noAssert) const {\n const ValueName *ValName = this->getValueName();\n if (!ValName)\n return 0;\n unsigned Len = ValName->getKeyLength();\n const char *Name = ValName->getKeyData();\n \n if (Len <= 5 || Name[4] != '.' || Name[0] != 'l' || Name[1] != 'l'\n || Name[2] != 'v' || Name[3] != 'm')\n return 0; \/\/ All intrinsics start with 'llvm.'\n\n assert((Len != 5 || noAssert) && \"'llvm.' is an invalid intrinsic name!\");\n\n#define GET_FUNCTION_RECOGNIZER\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_FUNCTION_RECOGNIZER\n assert(noAssert && \"Invalid LLVM intrinsic name\");\n return 0;\n}\n\nstd::string Intrinsic::getName(ID id, const Type **Tys, unsigned numTys) { \n assert(id < num_intrinsics && \"Invalid intrinsic ID!\");\n const char * const Table[] = {\n \"not_intrinsic\",\n#define GET_INTRINSIC_NAME_TABLE\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_INTRINSIC_NAME_TABLE\n };\n if (numTys == 0)\n return Table[id];\n std::string Result(Table[id]);\n for (unsigned i = 0; i < numTys; ++i) \n if (Tys[i])\n Result += \".\" + Tys[i]->getDescription();\n return Result;\n}\n\nconst FunctionType *Intrinsic::getType(ID id, const Type **Tys, \n uint32_t numTys) {\n const Type *ResultTy = NULL;\n std::vector<const Type*> ArgTys;\n bool IsVarArg = false;\n \n#define GET_INTRINSIC_GENERATOR\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_INTRINSIC_GENERATOR\n\n return FunctionType::get(ResultTy, ArgTys, IsVarArg); \n}\n\nFunction *Intrinsic::getDeclaration(Module *M, ID id, const Type **Tys, \n unsigned numTys) {\n\/\/ There can never be multiple globals with the same name of different types,\n\/\/ because intrinsics must be a specific type.\n return cast<Function>(M->getOrInsertFunction(getName(id, Tys, numTys), \n getType(id, Tys, numTys)));\n}\n\nValue *IntrinsicInst::StripPointerCasts(Value *Ptr) {\n if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {\n if (CE->getOpcode() == Instruction::BitCast) {\n if (isa<PointerType>(CE->getOperand(0)->getType()))\n return StripPointerCasts(CE->getOperand(0));\n } else if (CE->getOpcode() == Instruction::GetElementPtr) {\n for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)\n if (!CE->getOperand(i)->isNullValue())\n return Ptr;\n return StripPointerCasts(CE->getOperand(0));\n }\n return Ptr;\n }\n\n if (BitCastInst *CI = dyn_cast<BitCastInst>(Ptr)) {\n if (isa<PointerType>(CI->getOperand(0)->getType()))\n return StripPointerCasts(CI->getOperand(0));\n } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {\n for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)\n if (!isa<Constant>(GEP->getOperand(i)) ||\n !cast<Constant>(GEP->getOperand(i))->isNullValue())\n return Ptr;\n return StripPointerCasts(GEP->getOperand(0));\n }\n return Ptr;\n}\n\n\/\/ vim: sw=2 ai\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_ERROR_HANDLER_HPP\n#define MAPNIK_JSON_ERROR_HANDLER_HPP\n\n#include <string>\n#include <sstream>\n#include <boost\/spirit\/home\/support\/info.hpp>\n\nnamespace mapnik { namespace json {\n\ntemplate <typename Iterator>\nstruct error_handler\n{\n using result_type = void;\n void operator() (\n Iterator, Iterator last,\n Iterator err_pos, boost::spirit::info const& what) const\n {\n std::stringstream s;\n s << what << \" expected but got: \" << std::string(err_pos, std::min(err_pos + 16,last));\n throw std::runtime_error(s.str());\n }\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_ERROR_HANDLER_HPP\n<commit_msg>use std::advance to work with std::iterators<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_ERROR_HANDLER_HPP\n#define MAPNIK_JSON_ERROR_HANDLER_HPP\n\n#include <string>\n#include <sstream>\n#include <boost\/spirit\/home\/support\/info.hpp>\n\nnamespace mapnik { namespace json {\n\ntemplate <typename Iterator>\nstruct error_handler\n{\n using result_type = void;\n void operator() (\n Iterator, Iterator last,\n Iterator err_pos, boost::spirit::info const& what) const\n {\n std::stringstream s;\n auto start = err_pos;\n std::advance(err_pos,16);\n auto end = err_pos;\n s << what << \" expected but got: \" << std::string(start, end);\n throw std::runtime_error(s.str());\n }\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_ERROR_HANDLER_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef CORE_STORAGE_TPP\n#define CORE_STORAGE_TPP\n\n#include \"..\/storage.hpp\"\n#include \"nnlib\/serialization\/serialized.hpp\"\n\nnamespace nnlib\n{\n\ntemplate <typename T>\nStorage<T>::Storage(size_t n, const T &defaultValue) :\n m_ptr(new T[n]),\n m_size(n),\n m_capacity(n)\n{\n for(size_t i = 0; i < n; ++i)\n m_ptr[i] = defaultValue;\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const Storage<T> ©) :\n m_ptr(new T[copy.size()]),\n m_size(copy.size()),\n m_capacity(copy.size())\n{\n size_t index = 0;\n for(const T &value : copy)\n {\n m_ptr[index] = value;\n ++index;\n }\n}\n\ntemplate <typename T>\nStorage<T>::Storage(Storage<T> &&rhs) :\n m_ptr(rhs.m_ptr),\n m_size(rhs.m_size),\n m_capacity(rhs.m_capacity)\n{\n rhs.m_ptr\t\t= nullptr;\n rhs.m_size\t\t= 0;\n rhs.m_capacity\t= 0;\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const std::initializer_list<T> &values) :\n m_ptr(new T[values.size()]),\n m_size(values.size()),\n m_capacity(values.size())\n{\n size_t index = 0;\n for(const T &value : values)\n {\n m_ptr[index] = value;\n ++index;\n }\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const Serialized &node) :\n m_ptr(new T[node.size()]),\n m_size(node.size()),\n m_capacity(node.size())\n{\n node.get(begin(), end());\n}\n\ntemplate <typename T>\nStorage<T>::~Storage()\n{\n delete[] m_ptr;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::operator=(const Storage<T> ©)\n{\n if(this != ©)\n {\n resize(copy.size());\n size_t index = 0;\n for(const T &value : copy)\n {\n m_ptr[index] = value;\n ++index;\n }\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::operator=(const std::initializer_list<T> &values)\n{\n resize(values.size());\n size_t index = 0;\n for(const T &value : values)\n {\n m_ptr[index] = value;\n ++index;\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::resize(size_t n, const T &defaultValue)\n{\n reserve(n);\n for(size_t i = m_size; i < n; ++i)\n m_ptr[i] = defaultValue;\n m_size = n;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::reserve(size_t n)\n{\n if(n > m_capacity)\n {\n T *ptr = new T[n];\n for(size_t i = 0; i < m_size; ++i)\n ptr[i] = m_ptr[i];\n delete[] m_ptr;\n m_ptr = ptr;\n m_capacity = n;\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::push_back(const T &value)\n{\n resize(m_size + 1);\n m_ptr[m_size - 1] = value;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::pop_back()\n{\n --m_size;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::append(const Storage<T> &other)\n{\n reserve(m_size + other.m_size);\n for(const T &value : other)\n push_back(value);\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::erase(size_t index)\n{\n NNAssertLessThan(index, m_size, \"Attempted to erase an index that is out of bounds!\");\n for(size_t i = index + 1; i < m_size; ++i)\n {\n m_ptr[i - 1] = m_ptr[i];\n }\n --m_size;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::clear()\n{\n m_size = 0;\n return *this;\n}\n\ntemplate <typename T>\nT *Storage<T>::ptr()\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::ptr() const\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nsize_t Storage<T>::size() const\n{\n return m_size;\n}\n\ntemplate <typename T>\nbool Storage<T>::operator==(const Storage<T> &other) const\n{\n if(this == &other)\n {\n return true;\n }\n if(m_size != other.m_size)\n {\n return false;\n }\n for(size_t i = 0; i < other.m_size; ++i)\n {\n if(m_ptr[i] != other.m_ptr[i])\n {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename T>\nbool Storage<T>::operator!=(const Storage<T> &other) const\n{\n return !(*this == other);\n}\n\ntemplate <typename T>\nT &Storage<T>::at(size_t i)\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::at(size_t i) const\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nT &Storage<T>::operator[](size_t i)\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::operator[](size_t i) const\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nT &Storage<T>::front()\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return *m_ptr;\n}\n\ntemplate <typename T>\nconst T &Storage<T>::front() const\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return *m_ptr;\n}\n\ntemplate <typename T>\nT &Storage<T>::back()\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[m_size - 1];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::back() const\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[m_size - 1];\n}\n\ntemplate <typename T>\nT *Storage<T>::begin()\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::begin() const\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nT *Storage<T>::end()\n{\n return m_ptr + m_size;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::end() const\n{\n return m_ptr + m_size;\n}\n\ntemplate <typename T>\nvoid Storage<T>::save(Serialized &node) const\n{\n node.set(begin(), end());\n}\n\n}\n\n#endif\n<commit_msg>Changed some formatting things.<commit_after>#ifndef CORE_STORAGE_TPP\n#define CORE_STORAGE_TPP\n\n#include \"..\/storage.hpp\"\n#include \"nnlib\/serialization\/serialized.hpp\"\n\nnamespace nnlib\n{\n\ntemplate <typename T>\nStorage<T>::Storage(size_t n, const T &defaultValue) :\n m_ptr(new T[n]),\n m_size(n),\n m_capacity(n)\n{\n for(size_t i = 0; i < n; ++i)\n m_ptr[i] = defaultValue;\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const Storage<T> ©) :\n m_ptr(new T[copy.size()]),\n m_size(copy.size()),\n m_capacity(copy.size())\n{\n size_t index = 0;\n for(const T &value : copy)\n {\n m_ptr[index] = value;\n ++index;\n }\n}\n\ntemplate <typename T>\nStorage<T>::Storage(Storage<T> &&rhs) :\n m_ptr(rhs.m_ptr),\n m_size(rhs.m_size),\n m_capacity(rhs.m_capacity)\n{\n rhs.m_ptr\t\t= nullptr;\n rhs.m_size\t\t= 0;\n rhs.m_capacity\t= 0;\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const std::initializer_list<T> &values) :\n m_ptr(new T[values.size()]),\n m_size(values.size()),\n m_capacity(values.size())\n{\n size_t index = 0;\n for(const T &value : values)\n {\n m_ptr[index] = value;\n ++index;\n }\n}\n\ntemplate <typename T>\nStorage<T>::Storage(const Serialized &node) :\n m_ptr(new T[node.size()]),\n m_size(node.size()),\n m_capacity(node.size())\n{\n node.get(begin(), end());\n}\n\ntemplate <typename T>\nStorage<T>::~Storage()\n{\n delete[] m_ptr;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::operator=(const Storage<T> ©)\n{\n if(this != ©)\n {\n resize(copy.size());\n size_t index = 0;\n for(const T &value : copy)\n {\n m_ptr[index] = value;\n ++index;\n }\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::operator=(const std::initializer_list<T> &values)\n{\n resize(values.size());\n size_t index = 0;\n for(const T &value : values)\n {\n m_ptr[index] = value;\n ++index;\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::resize(size_t n, const T &defaultValue)\n{\n reserve(n);\n for(size_t i = m_size; i < n; ++i)\n m_ptr[i] = defaultValue;\n m_size = n;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::reserve(size_t n)\n{\n if(n > m_capacity)\n {\n T *ptr = new T[n];\n for(size_t i = 0; i < m_size; ++i)\n ptr[i] = m_ptr[i];\n delete[] m_ptr;\n m_ptr = ptr;\n m_capacity = n;\n }\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::push_back(const T &value)\n{\n resize(m_size + 1);\n m_ptr[m_size - 1] = value;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::pop_back()\n{\n --m_size;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::append(const Storage<T> &other)\n{\n reserve(m_size + other.m_size);\n for(const T &value : other)\n push_back(value);\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::erase(size_t index)\n{\n NNAssertLessThan(index, m_size, \"Attempted to erase an index that is out of bounds!\");\n for(size_t i = index + 1; i < m_size; ++i)\n m_ptr[i - 1] = m_ptr[i];\n --m_size;\n return *this;\n}\n\ntemplate <typename T>\nStorage<T> &Storage<T>::clear()\n{\n m_size = 0;\n return *this;\n}\n\ntemplate <typename T>\nT *Storage<T>::ptr()\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::ptr() const\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nsize_t Storage<T>::size() const\n{\n return m_size;\n}\n\ntemplate <typename T>\nbool Storage<T>::operator==(const Storage<T> &other) const\n{\n if(this == &other)\n return true;\n else if(m_size != other.m_size)\n return false;\n\n for(size_t i = 0; i < other.m_size; ++i)\n if(m_ptr[i] != other.m_ptr[i])\n return false;\n\n return true;\n}\n\ntemplate <typename T>\nbool Storage<T>::operator!=(const Storage<T> &other) const\n{\n return !(*this == other);\n}\n\ntemplate <typename T>\nT &Storage<T>::at(size_t i)\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::at(size_t i) const\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nT &Storage<T>::operator[](size_t i)\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::operator[](size_t i) const\n{\n NNAssertLessThan(i, m_size, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[i];\n}\n\ntemplate <typename T>\nT &Storage<T>::front()\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return *m_ptr;\n}\n\ntemplate <typename T>\nconst T &Storage<T>::front() const\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return *m_ptr;\n}\n\ntemplate <typename T>\nT &Storage<T>::back()\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[m_size - 1];\n}\n\ntemplate <typename T>\nconst T &Storage<T>::back() const\n{\n NNAssertGreaterThan(m_size, 0, \"Attempted to access an index that is out of bounds!\");\n return m_ptr[m_size - 1];\n}\n\ntemplate <typename T>\nT *Storage<T>::begin()\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::begin() const\n{\n return m_ptr;\n}\n\ntemplate <typename T>\nT *Storage<T>::end()\n{\n return m_ptr + m_size;\n}\n\ntemplate <typename T>\nconst T *Storage<T>::end() const\n{\n return m_ptr + m_size;\n}\n\ntemplate <typename T>\nvoid Storage<T>::save(Serialized &node) const\n{\n node.set(begin(), end());\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* ************************************************************************* *\/\n\/* This file is part of Shard. *\/\n\/* *\/\n\/* Shard is free software: you can redistribute it and\/or modify *\/\n\/* it under the terms of the GNU Affero General Public License as *\/\n\/* published by the Free Software Foundation. *\/\n\/* *\/\n\/* This program is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\/\n\/* GNU Affero General Public License for more details. *\/\n\/* *\/\n\/* You should have received a copy of the GNU Affero General Public License *\/\n\/* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\/\n\/* ************************************************************************* *\/\n\n#pragma once\n\n\/* ************************************************************************* *\/\n\n\/\/ Shard\n#include \"shard\/Path.hpp\"\n#include \"shard\/Assert.hpp\"\n#include \"shard\/String.hpp\"\n#include \"shard\/ViewPtr.hpp\"\n#include \"shard\/tokenizer\/Source.hpp\"\n#include \"shard\/tokenizer\/KeywordType.hpp\"\n#include \"shard\/tokenizer\/TokenType.hpp\"\n#include \"shard\/tokenizer\/Token.hpp\"\n#include \"shard\/tokenizer\/TokenizerException.hpp\"\n\n\/* ************************************************************************* *\/\n\nnamespace shard {\ninline namespace v1 {\nnamespace tokenizer {\n\n\/* ************************************************************************* *\/\n\nclass Tokenizer; \/\/FWD declaration\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief Input iterator from Shard lexical analyzer.\n *\/\nclass TokenizerIterator\n{\n\nprotected:\n\n ViewPtr<Tokenizer> m_tokenizer;\n\npublic:\n\n \/**\n * @brief constructs empty TokenizerIterator.\n *\/\n TokenizerIterator() = default;\n\n \/**\n * @brief constructs TokenizerIterator for given Tokenizer.\n *\/\n explicit TokenizerIterator(ViewPtr<Tokenizer> tokenizer):\n m_tokenizer(tokenizer) {}\n\n inline const Token& operator*() const;\n inline TokenizerIterator& operator++();\n inline TokenizerIterator operator++(int);\n\n \/**\n * @brief returns pointer to related tokenizer.\n *\/\n inline ViewPtr<Tokenizer> getTokenizer() const noexcept\n {\n return m_tokenizer;\n }\n};\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief checks whether lhs or rhs is at final token.\n *\n * This operator serves for range-for purposes. \n *\/\ninline bool operator==(const TokenizerIterator& lhs, const TokenizerIterator& rhs)\n{\n return (lhs.getTokenizer() == nullptr || (*lhs).getType() == TokenType::End)\n && (rhs.getTokenizer() == nullptr || (*rhs).getType() == TokenType::End);\n}\n\ninline bool operator!=(const TokenizerIterator& lhs, const TokenizerIterator& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief Shard lexical analyzer.\n *\/\nclass Tokenizer\n{\n\nprotected:\n\n Source m_src;\n Token m_current;\n\n static constexpr char string_literal_border = '\"';\n static constexpr char char_literal_border = '\\'';\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief constructs Tokenizer which reads from file.\n *\/\n explicit Tokenizer(const Path& path): m_src(path)\n {\n next();\n }\n\n \/**\n * @brief constructs Tokenizer which reads from String.\n *\/\n explicit Tokenizer(const String& source): m_src(source)\n {\n next();\n }\n \n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief returns if current character is between two chars in the ASCII table.\n *\/\n inline bool isBetween(char value1, char value2) noexcept\n {\n return !empty() && (m_src.get() >= value1) && (m_src.get() <= value2);\n }\n\n \/**\n * @brief returns if current character is whitespace.\n *\/\n inline bool isWhitespace() noexcept\n {\n return isBetween('\\1', ' ');\n }\n\n \/**\n * @brief returns if current character is a letter.\n *\/\n inline bool isLetter() noexcept\n {\n return isBetween('a', 'z') || isBetween('A', 'Z');\n }\n\n \/**\n * @brief returns if current character is a letter, number or '_'.\n *\/\n inline bool isIdentifier() noexcept\n {\n return isBetween('a', 'z') || isBetween('A', 'Z') || isDigit() || is('_');\n }\n\n \/**\n * @brief returns if current character is a number in given numeric system.\n *\/\n inline bool isDigit(int base = 10) noexcept\n {\n SHARD_ASSERT(base == 10 || base == 16 || base == 8 || base == 2);\n switch (base)\n {\n case 10: return isBetween('0', '9');\n case 16: return isBetween('0', '9') || isBetween('a', 'f') || isBetween('A', 'F');\n case 8: return isBetween('0', '7');\n case 2: return isBetween('0', '1');\n }\n }\n\n \/**\n * @brief returns if current character is tested character.\n *\/\n inline bool is(char value) noexcept\n {\n return !empty() && m_src.get() == value;\n }\n\n \/**\n * @brief returns if current character is one of tested characters.\n *\/\n template<typename... Chars>\n inline bool is(char a, Chars... options) noexcept\n {\n char chars[]{a, options...};\n for (const char option : chars)\n {\n if (is(option))\n {\n return true;\n }\n }\n return false;\n }\n\n \/**\n * @brief returns if current character is tested character.\n * If so, moves to next character.\n *\/\n inline bool match(char value) noexcept\n {\n if (is(value))\n {\n m_src.toss();\n return true;\n }\n return false;\n }\n\n \/**\n * @brief returns if current character is one of tested characters.\n * If so, moves to next character.\n *\/\n template<typename... Chars>\n inline bool match(Chars... options) noexcept\n {\n const char chars[]{options...};\n for (const char option : chars)\n {\n if (is(option))\n {\n m_src.toss();\n return true;\n }\n }\n return false;\n }\n\n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief Iterates to next non-whitespace char.\n *\/\n inline void skipWhitespace() noexcept\n {\n while (isWhitespace())\n {\n m_src.toss();\n }\n }\n\n \/**\n * @brief chcecks if source is empty.\n *\/\n inline bool empty()\n {\n return m_src.empty();\n }\n\n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief tokenizes tokentype number.\n *\/\n void tokenizeNumber();\n\n \/**\n * @brief tokenizes string into identifier.\n *\/\n void tokenizeIdentifier() noexcept;\n\n \/**\n * @brief tokenizes string value into keyword, function or identifier.\n *\/\n void tokenizeString();\n\n \/**\n * @brief tokenizes string value into keyword, function or identifier.\n *\/\n void tokenizeChar();\n\n \/**\n * @brief tokenizes operators.\n *\/\n void tokenizeOperator();\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief go to next token.\n *\/\n void next();\n\n \/**\n * @brief get current token.\n *\/\n inline const Token& get() const noexcept\n {\n return m_current;\n }\n\n \/**\n * @brief get current token an move to next.\n *\/\n inline Token extract()\n {\n auto tmp = m_current;\n next();\n return tmp;\n }\n\n \/**\n * @brief checks if there is non-ending token available.\n *\/\n inline bool isEof()\n {\n return m_current.getType() == TokenType::End;\n }\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief returns tokenizer iterator pointing to currect token.\n *\/\n inline TokenizerIterator begin() noexcept\n {\n return TokenizerIterator(this);\n }\n\n \/**\n * @brief returns tokenizer iterator pointing to token with end.\n *\/\n inline TokenizerIterator end() noexcept\n {\n return TokenizerIterator(nullptr);\n }\n};\n\n\/* ************************************************************************* *\/\n\ninline const Token& TokenizerIterator::operator*() const\n{\n return m_tokenizer->get();\n}\n\ninline TokenizerIterator& TokenizerIterator::operator++()\n{\n m_tokenizer->next();\n return *this;\n}\n\ninline TokenizerIterator TokenizerIterator::operator++(int)\n{\n TokenizerIterator tmp(*this);\n operator++();\n return tmp;\n}\n\n\/* ************************************************************************* *\/\n\n}\n}\n}\n\n\/* ************************************************************************* *\/\n\n<commit_msg>fixed comments<commit_after>\/* ************************************************************************* *\/\n\/* This file is part of Shard. *\/\n\/* *\/\n\/* Shard is free software: you can redistribute it and\/or modify *\/\n\/* it under the terms of the GNU Affero General Public License as *\/\n\/* published by the Free Software Foundation. *\/\n\/* *\/\n\/* This program is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\/\n\/* GNU Affero General Public License for more details. *\/\n\/* *\/\n\/* You should have received a copy of the GNU Affero General Public License *\/\n\/* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\/\n\/* ************************************************************************* *\/\n\n#pragma once\n\n\/* ************************************************************************* *\/\n\n\/\/ Shard\n#include \"shard\/Path.hpp\"\n#include \"shard\/Assert.hpp\"\n#include \"shard\/String.hpp\"\n#include \"shard\/ViewPtr.hpp\"\n#include \"shard\/tokenizer\/Source.hpp\"\n#include \"shard\/tokenizer\/KeywordType.hpp\"\n#include \"shard\/tokenizer\/TokenType.hpp\"\n#include \"shard\/tokenizer\/Token.hpp\"\n#include \"shard\/tokenizer\/TokenizerException.hpp\"\n\n\/* ************************************************************************* *\/\n\nnamespace shard {\ninline namespace v1 {\nnamespace tokenizer {\n\n\/* ************************************************************************* *\/\n\nclass Tokenizer; \/\/FWD declaration\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief Input iterator from Shard lexical analyzer.\n *\/\nclass TokenizerIterator\n{\n\nprotected:\n\n ViewPtr<Tokenizer> m_tokenizer;\n\npublic:\n\n \/**\n * @brief constructs empty TokenizerIterator.\n *\/\n TokenizerIterator() = default;\n\n \/**\n * @brief constructs TokenizerIterator for given Tokenizer.\n *\/\n explicit TokenizerIterator(ViewPtr<Tokenizer> tokenizer):\n m_tokenizer(tokenizer) {}\n\n inline const Token& operator*() const;\n inline TokenizerIterator& operator++();\n inline TokenizerIterator operator++(int);\n\n \/**\n * @brief returns pointer to related tokenizer.\n *\/\n inline ViewPtr<Tokenizer> getTokenizer() const noexcept\n {\n return m_tokenizer;\n }\n};\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief checks whether lhs or rhs is at final token.\n *\n * This operator serves for range-for purposes. \n *\/\ninline bool operator==(const TokenizerIterator& lhs, const TokenizerIterator& rhs)\n{\n return (lhs.getTokenizer() == nullptr || (*lhs).getType() == TokenType::End)\n && (rhs.getTokenizer() == nullptr || (*rhs).getType() == TokenType::End);\n}\n\ninline bool operator!=(const TokenizerIterator& lhs, const TokenizerIterator& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/* ************************************************************************* *\/\n\n\/**\n * @brief Shard lexical analyzer.\n *\/\nclass Tokenizer\n{\n\nprotected:\n\n Source m_src;\n Token m_current;\n\n static constexpr char string_literal_border = '\"';\n static constexpr char char_literal_border = '\\'';\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief constructs Tokenizer which reads from file.\n *\/\n explicit Tokenizer(const Path& path): m_src(path)\n {\n next();\n }\n\n \/**\n * @brief constructs Tokenizer which reads from String.\n *\/\n explicit Tokenizer(const String& source): m_src(source)\n {\n next();\n }\n \n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief returns if current character is between two chars in the ASCII table.\n *\/\n inline bool isBetween(char value1, char value2) noexcept\n {\n return !empty() && (m_src.get() >= value1) && (m_src.get() <= value2);\n }\n\n \/**\n * @brief returns if current character is whitespace.\n *\/\n inline bool isWhitespace() noexcept\n {\n return isBetween('\\1', ' ');\n }\n\n \/**\n * @brief returns if current character is a letter.\n *\/\n inline bool isLetter() noexcept\n {\n return isBetween('a', 'z') || isBetween('A', 'Z');\n }\n\n \/**\n * @brief returns if current character is a letter, number or '_'.\n *\/\n inline bool isIdentifier() noexcept\n {\n return isBetween('a', 'z') || isBetween('A', 'Z') || isDigit() || is('_');\n }\n\n \/**\n * @brief returns if current character is a number in given numeric system.\n *\/\n inline bool isDigit(int base = 10) noexcept\n {\n SHARD_ASSERT(base == 10 || base == 16 || base == 8 || base == 2);\n switch (base)\n {\n case 10: return isBetween('0', '9');\n case 16: return isBetween('0', '9') || isBetween('a', 'f') || isBetween('A', 'F');\n case 8: return isBetween('0', '7');\n case 2: return isBetween('0', '1');\n }\n }\n\n \/**\n * @brief returns if current character is tested character.\n *\/\n inline bool is(char value) noexcept\n {\n return !empty() && m_src.get() == value;\n }\n\n \/**\n * @brief returns if current character is one of tested characters.\n *\/\n template<typename... Chars>\n inline bool is(char a, Chars... options) noexcept\n {\n char chars[]{a, options...};\n for (const char option : chars)\n {\n if (is(option))\n {\n return true;\n }\n }\n return false;\n }\n\n \/**\n * @brief returns if current character is tested character.\n * If so, moves to next character.\n *\/\n inline bool match(char value) noexcept\n {\n if (is(value))\n {\n m_src.toss();\n return true;\n }\n return false;\n }\n\n \/**\n * @brief returns if current character is one of tested characters.\n * If so, moves to next character.\n *\/\n template<typename... Chars>\n inline bool match(Chars... options) noexcept\n {\n const char chars[]{options...};\n for (const char option : chars)\n {\n if (is(option))\n {\n m_src.toss();\n return true;\n }\n }\n return false;\n }\n\n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief Iterates to next non-whitespace char.\n *\/\n inline void skipWhitespace() noexcept\n {\n while (isWhitespace())\n {\n m_src.toss();\n }\n }\n\n \/**\n * @brief chcecks if source is empty.\n *\/\n inline bool empty()\n {\n return m_src.empty();\n }\n\n\/* ************************************************************************* *\/\n\nprotected:\n\n \/**\n * @brief tokenizes tokentype number.\n *\/\n void tokenizeNumber();\n\n \/**\n * @brief tokenizes string into identifier.\n *\/\n void tokenizeIdentifier() noexcept;\n\n \/**\n * @brief tokenizes string value into keyword, function or identifier.\n *\/\n void tokenizeString();\n\n \/**\n * @brief tokenizes string value into keyword, function or identifier.\n *\/\n void tokenizeChar();\n\n \/**\n * @brief tokenizes operators.\n *\/\n void tokenizeOperator();\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief go to next token.\n *\/\n void next();\n\n \/**\n * @brief get current token.\n *\/\n inline const Token& get() const noexcept\n {\n return m_current;\n }\n\n \/**\n * @brief get current token and move to next.\n *\/\n inline Token extract()\n {\n auto tmp = m_current;\n next();\n return tmp;\n }\n\n \/**\n * @brief checks if current token is final EOF type.\n *\/\n inline bool isEof()\n {\n return m_current.getType() == TokenType::End;\n }\n\n\/* ************************************************************************* *\/\n\npublic:\n\n \/**\n * @brief returns tokenizer iterator pointing to currect token.\n *\/\n inline TokenizerIterator begin() noexcept\n {\n return TokenizerIterator(this);\n }\n\n \/**\n * @brief returns tokenizer iterator pointing to token with end.\n *\/\n inline TokenizerIterator end() noexcept\n {\n return TokenizerIterator(nullptr);\n }\n};\n\n\/* ************************************************************************* *\/\n\ninline const Token& TokenizerIterator::operator*() const\n{\n return m_tokenizer->get();\n}\n\ninline TokenizerIterator& TokenizerIterator::operator++()\n{\n m_tokenizer->next();\n return *this;\n}\n\ninline TokenizerIterator TokenizerIterator::operator++(int)\n{\n TokenizerIterator tmp(*this);\n operator++();\n return tmp;\n}\n\n\/* ************************************************************************* *\/\n\n}\n}\n}\n\n\/* ************************************************************************* *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/** @mainpage C++11 Proton Library\n*\n* @authors <a href=\"http:\/\/lenx.100871.net\">Lenx Tao Wei<\/a> (lenx.wei at gmail.com)\n*\n* @section intro Introduction\n* Proton is a library to provide Python-like interfaces for C++11,\n* which try to make porting from Python to C++11 easier,\n* and make programming in C++11 more convenient :)\n*\n* The main git repository is at https:\/\/github.com\/LenxWei\/libproton.\n*\n* @section install Install\n* Download site:\n* - http:\/\/code.google.com\/p\/libproton\/downloads\/list\n* - https:\/\/github.com\/LenxWei\/libproton\/downloads\n*\n* Need a compiler supporting c++11, such as gcc 4.7, clang 3.2 or higher.<br>\n* Install <a href=\"http:\/\/www.boost.org\/\">Boost C++ Library<\/a> 1.48 or higher first.\n*\n* After that, just standard \".\/configure; make; make check; make install\"\n*\n* @section modules Modules\n* You can find documents about modules <a href=\"modules.html\">here<\/a>.\n* <hr>\n* @todo add tutorial\n* @todo add weak_\n* @todo 1.2 milestone\n* @todo add os module\n* @todo add socket module(?)\n* @todo add server\/client module\n* @todo add regex module\n* @todo add threading\n* @todo 1.4 milestone\n* @todo add gc support\n* @todo 1.6 milestone\n*\n* @defgroup ref Smart reference\n* Provide basic reference support for proton.\n* @{\n* @defgroup ref_ ref_\n* Core reference template supporting interface through inheritance\/multiple inheritance.\n*\n* @defgroup functor func_\n* General functor interface template.\n*\n* @}\n*\n* @defgroup stl Containers\n* Repack stl containers in new templates following python's habits.\n* @{\n* @defgroup seq common\n* common container operations\n*\n* @defgroup str str\n* like string in python.\n*\n* @defgroup vector_ vector_\n* like list in python, better for small sequences\n*\n* @defgroup deque_ deque_\n* like list in python, better for long sequences.\n*\n* @defgroup map_ map_\n* like dict in python.\n*\n* @defgroup set_ set_\n* like set in python.\n*\n* @defgroup tuple tuple\n* like tuple in python.\n*\n* @}\n*\n* @defgroup util Utilities\n* @{\n*\n* @defgroup getopt getopt\n* get options\n*\n* @defgroup debug Debug utilities\n* Macros, global variables, classes for debug.\n*\n* @defgroup pool Smart allocator\n* A high-performance and smart allocator.\n*\n* @}\n*\n*\/\n<commit_msg>add 1.3 note<commit_after>\/** @mainpage C++11 Proton Library\n*\n* @authors <a href=\"http:\/\/lenx.100871.net\">Lenx Tao Wei<\/a> (lenx.wei at gmail.com)\n*\n* @section intro Introduction\n* Proton is a library to provide Python-like interfaces for C++11,\n* which try to make porting from Python to C++11 easier,\n* and make programming in C++11 more convenient :)\n*\n* The main git repository is at https:\/\/github.com\/LenxWei\/libproton.\n*\n* @section install Install\n* Download site:\n* - http:\/\/code.google.com\/p\/libproton\/downloads\/list\n* - https:\/\/github.com\/LenxWei\/libproton\/downloads\n*\n* Need a compiler supporting c++11, such as gcc 4.7, clang 3.2 or higher.<br>\n* Install <a href=\"http:\/\/www.boost.org\/\">Boost C++ Library<\/a> 1.48 or higher first.\n*\n* After that, just standard \".\/configure; make; make check; make install\"\n*\n* @section modules Modules\n* You can find documents about modules <a href=\"modules.html\">here<\/a>.\n* <hr>\n* @todo add tutorial\n* @todo add weak_\n* @todo 1.2 milestone\n* @todo add os module\n* @todo add socket module(?)\n* @todo add server\/client module\n* @todo add regex module\n* @todo 1.3 milestone\n* @todo add threading\n* @todo 1.4 milestone\n* @todo add gc support\n* @todo 1.6 milestone\n*\n* @defgroup ref Smart reference\n* Provide basic reference support for proton.\n* @{\n* @defgroup ref_ ref_\n* Core reference template supporting interface through inheritance\/multiple inheritance.\n*\n* @defgroup functor func_\n* General functor interface template.\n*\n* @}\n*\n* @defgroup stl Containers\n* Repack stl containers in new templates following python's habits.\n* @{\n* @defgroup seq common\n* common container operations\n*\n* @defgroup str str\n* like string in python.\n*\n* @defgroup vector_ vector_\n* like list in python, better for small sequences\n*\n* @defgroup deque_ deque_\n* like list in python, better for long sequences.\n*\n* @defgroup map_ map_\n* like dict in python.\n*\n* @defgroup set_ set_\n* like set in python.\n*\n* @defgroup tuple tuple\n* like tuple in python.\n*\n* @}\n*\n* @defgroup util Utilities\n* @{\n*\n* @defgroup getopt getopt\n* get options\n*\n* @defgroup debug Debug utilities\n* Macros, global variables, classes for debug.\n*\n* @defgroup pool Smart allocator\n* A high-performance and smart allocator.\n*\n* @}\n*\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * MIT License\n *\n * Copyright (c) 2016 Jacek Galowicz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#pragma once\n\n#include \"stl_symbols.hpp\"\n#include \"charlist.hpp\"\n\nnamespace pprintpp {\n\ntemplate <typename T> struct always_false { static constexpr bool value {false}; };\n\nusing namespace typelist;\nusing namespace charlist;\n\ntemplate <typename T> struct type2fmt;\n\ntemplate <> struct type2fmt<char> { using type = char_tl_t<'c'>; };\ntemplate <> struct type2fmt<short> { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<int> { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<long int> { using type = char_tl_t<'l', 'd'>; };\ntemplate <> struct type2fmt<long long int> { using type = char_tl_t<'l', 'l', 'd'>; };\ntemplate <> struct type2fmt<unsigned char> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned short> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned long> { using type = char_tl_t<'l', 'u'>; };\ntemplate <> struct type2fmt<unsigned long long> { using type = char_tl_t<'l', 'l', 'u'>; };\n\ntemplate <> struct type2fmt<bool> { using type = char_tl_t<'d'>; };\n\ntemplate <> struct type2fmt<float> { using type = char_tl_t<'f'>; };\ntemplate <> struct type2fmt<double> { using type = char_tl_t<'l', 'f'>; };\n\ntemplate <> struct type2fmt<nullptr_t> { using type = char_tl_t<'p'>; };\ntemplate <typename T> struct type2fmt<T*> { using type = char_tl_t<'p'>; };\n\ntemplate <typename T, typename FL>\nstruct format_str {\n using raw_T = remove_cv_t<T>;\n static constexpr bool s_fmt {contains<FL, char_t<'s'>>::value};\n static constexpr bool is_str {std::is_same<char,\n remove_cv_t<typename std::remove_pointer<raw_T>::type>>::value};\n\n static constexpr bool is_uint {std::is_unsigned<raw_T>::value};\n static constexpr bool has_x {contains<FL, char_t<'x'>>::value};\n\n using raw_fmt = typename type2fmt<T>::type;\n\n using uint_x_fmt = typename std::conditional<is_uint && has_x,\n substitute_t<raw_fmt, char_t<'u'>, char_t<'x'>>,\n raw_fmt\n >::type;\n\n using fmt_type = typename std::conditional<s_fmt && is_str,\n substitute_t<raw_fmt, char_t<'p'>, char_t<'s'>>,\n uint_x_fmt\n >::type;\n\n using filtered_fl = remove_t<remove_t<FL, char_t<'x'>>, char_t<'s'>>;\n\n using type = append_t<filtered_fl, fmt_type>;\n};\n\ntemplate <class InList, class OutList, size_t Counter>\nstruct find_brace;\n\ntemplate <class InList, class OutList>\nstruct find_brace<tl<char_t<'}'>, InList>, OutList, 1> {\n using before = OutList;\n using after = InList;\n};\n\ntemplate <char C, class InList, class OutList, size_t N>\nstruct find_brace<tl<char_t<C>, InList>, OutList, N>\n : public find_brace<InList, append_t<OutList, char_t<C>>, N>\n{\n static_assert(C != '{', \"Found nested braces: {...{...}...}!\"\n \" Maybe you want to mask the outer one?\");\n};\n\ntemplate <class OutList, size_t N>\nstruct find_brace<null_t, OutList, N>\n{\n static_assert(N + 1 == N, \"Missing } after {.\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat;\n\ntemplate <>\nstruct autoformat<null_t, null_t> { using type = null_t; };\n\ntemplate <typename TL>\nstruct autoformat<null_t, TL> {\n using type = null_t;\n static_assert(always_false<TL>::value, \"There are more vars than format tokens!\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'%'>, tl<char_t<'%'>, SL>>, TL>\n{\n using type = tl<char_t<'%'>, tl<char_t<'%'>, typename autoformat<SL, TL>::type>>;\n};\n\ntemplate <typename SL, typename T, typename TL>\nstruct autoformat<tl<char_t<'%'>, SL>, tl<T, TL>>\n{\n using type = tl<char_t<'%'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'\\\\'>, tl<char_t<'{'>, SL>>, TL>\n{\n using type = tl<char_t<'{'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'{'>, SL>, TL>\n{\n using other_brace = find_brace<SL, null_t, 1>;\n using format_block = typename other_brace::before;\n using rest_str = typename other_brace::after;\n\n static_assert(!std::is_same<TL, null_t>::value, \"There are more {} than arguments to print\");\n using T = typename TL::head;\n using fmt_str = typename format_str<T, format_block>::type;\n\n using type = tl<char_t<'%'>,\n append_t<fmt_str, typename autoformat<rest_str, typename TL::tail>::type>>;\n};\n\ntemplate <typename C, typename SL, typename TL>\nstruct autoformat<tl<C, SL>, TL> {\n using type = tl<C, typename autoformat<SL, TL>::type>;\n};\n\n\ntemplate <typename StringProvider, typename PtList>\nusing autoformat_t =\n tl_to_varlist<\n typename autoformat<string_list_t<StringProvider>, PtList>::type\n >;\n\ntemplate <typename ... Ts>\nmake_t<Ts...> tie_types(Ts...);\n\n#define AUTOFORMAT(s, ...) \\\n ({ \\\n struct strprov { static constexpr const char * const str() { return s; } }; \\\n using paramtypes = decltype(pprintpp::tie_types(__VA_ARGS__)); \\\n using af = pprintpp::autoformat_t<strprov, paramtypes>; \\\n af::str(); \\\n })\n\n#define pprintf(s, ...) printf(AUTOFORMAT(s, ## __VA_ARGS__), ## __VA_ARGS__);\n\n}\n<commit_msg>Outsource std::is_same from pprintpp.hpp<commit_after>\/*\n * MIT License\n *\n * Copyright (c) 2016 Jacek Galowicz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#pragma once\n\n#include \"stl_symbols.hpp\"\n#include \"charlist.hpp\"\n\nnamespace pprintpp {\n\ntemplate <typename T> struct always_false { static constexpr bool value {false}; };\n\nusing namespace typelist;\nusing namespace charlist;\n\ntemplate <typename T> struct type2fmt;\n\ntemplate <> struct type2fmt<char> { using type = char_tl_t<'c'>; };\ntemplate <> struct type2fmt<short> { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<int> { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<long int> { using type = char_tl_t<'l', 'd'>; };\ntemplate <> struct type2fmt<long long int> { using type = char_tl_t<'l', 'l', 'd'>; };\ntemplate <> struct type2fmt<unsigned char> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned short> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned> { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned long> { using type = char_tl_t<'l', 'u'>; };\ntemplate <> struct type2fmt<unsigned long long> { using type = char_tl_t<'l', 'l', 'u'>; };\n\ntemplate <> struct type2fmt<bool> { using type = char_tl_t<'d'>; };\n\ntemplate <> struct type2fmt<float> { using type = char_tl_t<'f'>; };\ntemplate <> struct type2fmt<double> { using type = char_tl_t<'l', 'f'>; };\n\ntemplate <> struct type2fmt<nullptr_t> { using type = char_tl_t<'p'>; };\ntemplate <typename T> struct type2fmt<T*> { using type = char_tl_t<'p'>; };\n\ntemplate <typename T, typename FL>\nstruct format_str {\n using raw_T = remove_cv_t<T>;\n static constexpr bool s_fmt {contains<FL, char_t<'s'>>::value};\n static constexpr bool is_str {is_same<char,\n remove_cv_t<typename std::remove_pointer<raw_T>::type>>::value};\n\n static constexpr bool is_uint {std::is_unsigned<raw_T>::value};\n static constexpr bool has_x {contains<FL, char_t<'x'>>::value};\n\n using raw_fmt = typename type2fmt<T>::type;\n\n using uint_x_fmt = typename std::conditional<is_uint && has_x,\n substitute_t<raw_fmt, char_t<'u'>, char_t<'x'>>,\n raw_fmt\n >::type;\n\n using fmt_type = typename std::conditional<s_fmt && is_str,\n substitute_t<raw_fmt, char_t<'p'>, char_t<'s'>>,\n uint_x_fmt\n >::type;\n\n using filtered_fl = remove_t<remove_t<FL, char_t<'x'>>, char_t<'s'>>;\n\n using type = append_t<filtered_fl, fmt_type>;\n};\n\ntemplate <class InList, class OutList, size_t Counter>\nstruct find_brace;\n\ntemplate <class InList, class OutList>\nstruct find_brace<tl<char_t<'}'>, InList>, OutList, 1> {\n using before = OutList;\n using after = InList;\n};\n\ntemplate <char C, class InList, class OutList, size_t N>\nstruct find_brace<tl<char_t<C>, InList>, OutList, N>\n : public find_brace<InList, append_t<OutList, char_t<C>>, N>\n{\n static_assert(C != '{', \"Found nested braces: {...{...}...}!\"\n \" Maybe you want to mask the outer one?\");\n};\n\ntemplate <class OutList, size_t N>\nstruct find_brace<null_t, OutList, N>\n{\n static_assert(N + 1 == N, \"Missing } after {.\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat;\n\ntemplate <>\nstruct autoformat<null_t, null_t> { using type = null_t; };\n\ntemplate <typename TL>\nstruct autoformat<null_t, TL> {\n using type = null_t;\n static_assert(always_false<TL>::value, \"There are more vars than format tokens!\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'%'>, tl<char_t<'%'>, SL>>, TL>\n{\n using type = tl<char_t<'%'>, tl<char_t<'%'>, typename autoformat<SL, TL>::type>>;\n};\n\ntemplate <typename SL, typename T, typename TL>\nstruct autoformat<tl<char_t<'%'>, SL>, tl<T, TL>>\n{\n using type = tl<char_t<'%'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'\\\\'>, tl<char_t<'{'>, SL>>, TL>\n{\n using type = tl<char_t<'{'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'{'>, SL>, TL>\n{\n using other_brace = find_brace<SL, null_t, 1>;\n using format_block = typename other_brace::before;\n using rest_str = typename other_brace::after;\n\n static_assert(!is_same<TL, null_t>::value, \"There are more {} than arguments to print\");\n using T = typename TL::head;\n using fmt_str = typename format_str<T, format_block>::type;\n\n using type = tl<char_t<'%'>,\n append_t<fmt_str, typename autoformat<rest_str, typename TL::tail>::type>>;\n};\n\ntemplate <typename C, typename SL, typename TL>\nstruct autoformat<tl<C, SL>, TL> {\n using type = tl<C, typename autoformat<SL, TL>::type>;\n};\n\n\ntemplate <typename StringProvider, typename PtList>\nusing autoformat_t =\n tl_to_varlist<\n typename autoformat<string_list_t<StringProvider>, PtList>::type\n >;\n\ntemplate <typename ... Ts>\nmake_t<Ts...> tie_types(Ts...);\n\n#define AUTOFORMAT(s, ...) \\\n ({ \\\n struct strprov { static constexpr const char * const str() { return s; } }; \\\n using paramtypes = decltype(pprintpp::tie_types(__VA_ARGS__)); \\\n using af = pprintpp::autoformat_t<strprov, paramtypes>; \\\n af::str(); \\\n })\n\n#define pprintf(s, ...) printf(AUTOFORMAT(s, ## __VA_ARGS__), ## __VA_ARGS__);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file lldrawpool.cpp\n * @brief LLDrawPoolMaterials class implementation\n * @author Jonathan \"Geenz\" Goodman\n *\n * $LicenseInfo:firstyear=2002&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2013, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"lldrawpoolmaterials.h\"\n#include \"llviewershadermgr.h\"\n#include \"pipeline.h\"\n\nS32 diffuse_channel = -1;\n\nLLDrawPoolMaterials::LLDrawPoolMaterials()\n: LLRenderPass(LLDrawPool::POOL_MATERIALS)\n{\n\t\n}\n\nvoid LLDrawPoolMaterials::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT); \n}\n\nvoid LLDrawPoolMaterials::beginDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n}\n\nvoid LLDrawPoolMaterials::endDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\tLLRenderPass::endRenderPass(pass);\n}\n\nvoid LLDrawPoolMaterials::renderDeferred(S32 pass)\n{\n\tU32 type = LLRenderPass::PASS_MATERIALS;\n\tLLCullResult::drawinfo_iterator begin = gPipeline.beginRenderMap(type);\n\tLLCullResult::drawinfo_iterator end = gPipeline.endRenderMap(type);\n\t\n\tfor (LLCullResult::drawinfo_iterator i = begin; i != end; ++i)\n\t{\n\t\tLLDrawInfo& params = **i;\n\t\t\n\t\tswitch (params.mDiffuseAlphaMode)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormal;\n\t\t\t\tmShader->bind();\n\t\t\t\tbreak;\n\t\t\tcase 1: \/\/ Alpha blending not supported in the opaque draw pool.\n\t\t\t\treturn;\n\t\t\tcase 2:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormalAlphaTest;\n\t\t\t\tmShader->bind();\n\t\t\t\tmShader->setMinimumAlpha(params.mAlphaMaskCutoff);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormalEmissive;\n\t\t\t\tmShader->bind();\n\t\t\t\tbreak;\n\t\t};\n\t\t\n\t\t\n\t\t\n\t\tmShader->uniform4f(LLShaderMgr::SPECULAR_COLOR, params.mSpecColor.mV[0], params.mSpecColor.mV[1], params.mSpecColor.mV[2], params.mSpecColor.mV[3]);\n\t\tmShader->uniform1f(LLShaderMgr::ENVIRONMENT_INTENSITY, params.mEnvIntensity);\n\t\t\n\t\tparams.mNormalMap->addTextureStats(params.mVSize);\n\t\tbindNormalMap(params.mNormalMap);\n\t\t\n\t\tparams.mSpecularMap->addTextureStats(params.mVSize);\n\t\tbindSpecularMap(params.mSpecularMap);\n\t\t\n\t\tdiffuse_channel = mShader->enableTexture(LLShaderMgr::DIFFUSE_MAP);\n\t\tpushBatch(params, VERTEX_DATA_MASK, TRUE);\n\t\tmShader->disableTexture(LLShaderMgr::DIFFUSE_MAP);\n\t\tmShader->unbind();\n\t}\n}\n\nvoid LLDrawPoolMaterials::bindSpecularMap(LLViewerTexture* tex)\n{\n\tmShader->bindTexture(LLShaderMgr::SPECULAR_MAP, tex);\n}\n\nvoid LLDrawPoolMaterials::bindNormalMap(LLViewerTexture* tex)\n{\n\tmShader->bindTexture(LLShaderMgr::BUMP_MAP, tex);\n}\n\nvoid LLDrawPoolMaterials::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\t\n\t\/\/ Materials isn't supported under forward rendering.\n\t\/\/ Use the simple shaders to handle it instead.\n\t\/\/ This is basically replicated from LLDrawPoolSimple.\n\t\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tmShader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tmShader = &gObjectSimpleProgram;\n\t}\n\t\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tmShader->bind();\n\t}\n\telse\n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\n\t}\n}\n\nvoid LLDrawPoolMaterials::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\tstop_glerror();\n\tLLRenderPass::endRenderPass(pass);\n\tstop_glerror();\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tmShader->unbind();\n\t}\n}\n\nvoid LLDrawPoolMaterials::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\t\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\t\tgPipeline.enableLightsDynamic();\n\t\t\n\t\tif (mVertexShaderLevel > 0)\n\t\t{\n\t\t\tU32 mask = getVertexDataMask() | LLVertexBuffer::MAP_TEXTURE_INDEX;\n\t\t\t\n\t\t\tpushBatches(LLRenderPass::PASS_MATERIALS, mask, TRUE, TRUE);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\t\t\trenderTexture(LLRenderPass::PASS_MATERIALS, getVertexDataMask());\n\t\t}\n\t}\n}\n\n\nvoid LLDrawPoolMaterials::pushBatch(LLDrawInfo& params, U32 mask, BOOL texture, BOOL batch_textures)\n{\n\tapplyModelMatrix(params);\n\t\n\tbool tex_setup = false;\n\t\n\tif (batch_textures && params.mTextureList.size() > 1)\n\t{\n\t\tfor (U32 i = 0; i < params.mTextureList.size(); ++i)\n\t\t{\n\t\t\tif (params.mTextureList[i].notNull())\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(i)->bind(params.mTextureList[i], TRUE);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{ \/\/not batching textures or batch has only 1 texture -- might need a texture matrix\n\t\tif (params.mTextureMatrix)\n\t\t{\n\t\t\t\/\/if (mShiny)\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(0)->activate();\n\t\t\t\tgGL.matrixMode(LLRender::MM_TEXTURE);\n\t\t\t}\n\t\t\t\n\t\t\tgGL.loadMatrix((GLfloat*) params.mTextureMatrix->mMatrix);\n\t\t\tgPipeline.mTextureMatrixOps++;\n\t\t\t\n\t\t\ttex_setup = true;\n\t\t}\n\t\t\n\t\tif (mVertexShaderLevel > 1 && texture)\n\t\t{\n\t\t\tif (params.mTexture.notNull())\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(diffuse_channel)->bind(params.mTexture);\n\t\t\t\tparams.mTexture->addTextureStats(params.mVSize);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(diffuse_channel)->unbind(LLTexUnit::TT_TEXTURE);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (params.mGroup)\n\t{\n\t\tparams.mGroup->rebuildMesh();\n\t}\n\tparams.mVertexBuffer->setBuffer(mask);\n\tparams.mVertexBuffer->drawRange(params.mDrawMode, params.mStart, params.mEnd, params.mCount, params.mOffset);\n\tgPipeline.addTrianglesDrawn(params.mCount, params.mDrawMode);\n\tif (tex_setup)\n\t{\n\t\tgGL.getTexUnit(0)->activate();\n\t\tgGL.loadIdentity();\n\t\tgGL.matrixMode(LLRender::MM_MODELVIEW);\n\t}\n}\n<commit_msg>protect against missing mNormalMap or mSpecularMap<commit_after>\/** \n * @file lldrawpool.cpp\n * @brief LLDrawPoolMaterials class implementation\n * @author Jonathan \"Geenz\" Goodman\n *\n * $LicenseInfo:firstyear=2002&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2013, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"lldrawpoolmaterials.h\"\n#include \"llviewershadermgr.h\"\n#include \"pipeline.h\"\n\nS32 diffuse_channel = -1;\n\nLLDrawPoolMaterials::LLDrawPoolMaterials()\n: LLRenderPass(LLDrawPool::POOL_MATERIALS)\n{\n\t\n}\n\nvoid LLDrawPoolMaterials::prerender()\n{\n\tmVertexShaderLevel = LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_OBJECT); \n}\n\nvoid LLDrawPoolMaterials::beginDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n}\n\nvoid LLDrawPoolMaterials::endDeferredPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\tLLRenderPass::endRenderPass(pass);\n}\n\nvoid LLDrawPoolMaterials::renderDeferred(S32 pass)\n{\n\tU32 type = LLRenderPass::PASS_MATERIALS;\n\tLLCullResult::drawinfo_iterator begin = gPipeline.beginRenderMap(type);\n\tLLCullResult::drawinfo_iterator end = gPipeline.endRenderMap(type);\n\t\n\tfor (LLCullResult::drawinfo_iterator i = begin; i != end; ++i)\n\t{\n\t\tLLDrawInfo& params = **i;\n\t\t\n\t\tswitch (params.mDiffuseAlphaMode)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormal;\n\t\t\t\tmShader->bind();\n\t\t\t\tbreak;\n\t\t\tcase 1: \/\/ Alpha blending not supported in the opaque draw pool.\n\t\t\t\treturn;\n\t\t\tcase 2:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormalAlphaTest;\n\t\t\t\tmShader->bind();\n\t\t\t\tmShader->setMinimumAlpha(params.mAlphaMaskCutoff);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tmShader = &gDeferredMaterialShinyNormalEmissive;\n\t\t\t\tmShader->bind();\n\t\t\t\tbreak;\n\t\t};\n\t\t\n\t\t\n\t\t\n\t\tmShader->uniform4f(LLShaderMgr::SPECULAR_COLOR, params.mSpecColor.mV[0], params.mSpecColor.mV[1], params.mSpecColor.mV[2], params.mSpecColor.mV[3]);\n\t\tmShader->uniform1f(LLShaderMgr::ENVIRONMENT_INTENSITY, params.mEnvIntensity);\n\t\t\n\t\tif (params.mNormalMap)\n\t\t{\n\t\t\tparams.mNormalMap->addTextureStats(params.mVSize);\n\t\t\tbindNormalMap(params.mNormalMap);\n\t\t}\n\t\t\n\t\tif (params.mSpecularMap)\n\t\t{\n\t\t\tparams.mSpecularMap->addTextureStats(params.mVSize);\n\t\t\tbindSpecularMap(params.mSpecularMap);\n\t\t}\n\t\t\n\t\tdiffuse_channel = mShader->enableTexture(LLShaderMgr::DIFFUSE_MAP);\n\t\tpushBatch(params, VERTEX_DATA_MASK, TRUE);\n\t\tmShader->disableTexture(LLShaderMgr::DIFFUSE_MAP);\n\t\tmShader->unbind();\n\t}\n}\n\nvoid LLDrawPoolMaterials::bindSpecularMap(LLViewerTexture* tex)\n{\n\tmShader->bindTexture(LLShaderMgr::SPECULAR_MAP, tex);\n}\n\nvoid LLDrawPoolMaterials::bindNormalMap(LLViewerTexture* tex)\n{\n\tmShader->bindTexture(LLShaderMgr::BUMP_MAP, tex);\n}\n\nvoid LLDrawPoolMaterials::beginRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\t\n\t\/\/ Materials isn't supported under forward rendering.\n\t\/\/ Use the simple shaders to handle it instead.\n\t\/\/ This is basically replicated from LLDrawPoolSimple.\n\t\n\tif (LLPipeline::sUnderWaterRender)\n\t{\n\t\tmShader = &gObjectSimpleWaterProgram;\n\t}\n\telse\n\t{\n\t\tmShader = &gObjectSimpleProgram;\n\t}\n\t\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tmShader->bind();\n\t}\n\telse\n\t{\n\t\t\/\/ don't use shaders!\n\t\tif (gGLManager.mHasShaderObjects)\n\t\t{\n\t\t\tLLGLSLShader::bindNoShader();\n\t\t}\n\t}\n}\n\nvoid LLDrawPoolMaterials::endRenderPass(S32 pass)\n{\n\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\tstop_glerror();\n\tLLRenderPass::endRenderPass(pass);\n\tstop_glerror();\n\tif (mVertexShaderLevel > 0)\n\t{\n\t\tmShader->unbind();\n\t}\n}\n\nvoid LLDrawPoolMaterials::render(S32 pass)\n{\n\tLLGLDisable blend(GL_BLEND);\n\t\n\t{ \/\/render simple\n\t\tLLFastTimer t(FTM_RENDER_MATERIALS);\n\t\tgPipeline.enableLightsDynamic();\n\t\t\n\t\tif (mVertexShaderLevel > 0)\n\t\t{\n\t\t\tU32 mask = getVertexDataMask() | LLVertexBuffer::MAP_TEXTURE_INDEX;\n\t\t\t\n\t\t\tpushBatches(LLRenderPass::PASS_MATERIALS, mask, TRUE, TRUE);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLLGLDisable alpha_test(GL_ALPHA_TEST);\n\t\t\trenderTexture(LLRenderPass::PASS_MATERIALS, getVertexDataMask());\n\t\t}\n\t}\n}\n\n\nvoid LLDrawPoolMaterials::pushBatch(LLDrawInfo& params, U32 mask, BOOL texture, BOOL batch_textures)\n{\n\tapplyModelMatrix(params);\n\t\n\tbool tex_setup = false;\n\t\n\tif (batch_textures && params.mTextureList.size() > 1)\n\t{\n\t\tfor (U32 i = 0; i < params.mTextureList.size(); ++i)\n\t\t{\n\t\t\tif (params.mTextureList[i].notNull())\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(i)->bind(params.mTextureList[i], TRUE);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{ \/\/not batching textures or batch has only 1 texture -- might need a texture matrix\n\t\tif (params.mTextureMatrix)\n\t\t{\n\t\t\t\/\/if (mShiny)\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(0)->activate();\n\t\t\t\tgGL.matrixMode(LLRender::MM_TEXTURE);\n\t\t\t}\n\t\t\t\n\t\t\tgGL.loadMatrix((GLfloat*) params.mTextureMatrix->mMatrix);\n\t\t\tgPipeline.mTextureMatrixOps++;\n\t\t\t\n\t\t\ttex_setup = true;\n\t\t}\n\t\t\n\t\tif (mVertexShaderLevel > 1 && texture)\n\t\t{\n\t\t\tif (params.mTexture.notNull())\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(diffuse_channel)->bind(params.mTexture);\n\t\t\t\tparams.mTexture->addTextureStats(params.mVSize);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgGL.getTexUnit(diffuse_channel)->unbind(LLTexUnit::TT_TEXTURE);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (params.mGroup)\n\t{\n\t\tparams.mGroup->rebuildMesh();\n\t}\n\tparams.mVertexBuffer->setBuffer(mask);\n\tparams.mVertexBuffer->drawRange(params.mDrawMode, params.mStart, params.mEnd, params.mCount, params.mOffset);\n\tgPipeline.addTrianglesDrawn(params.mCount, params.mDrawMode);\n\tif (tex_setup)\n\t{\n\t\tgGL.getTexUnit(0)->activate();\n\t\tgGL.loadIdentity();\n\t\tgGL.matrixMode(LLRender::MM_MODELVIEW);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file lsh_test.cpp\n *\n * Unit tests for the 'LSHSearch' class.\n *\/\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\n#include <mlpack\/methods\/lsh\/lsh_search.hpp>\n#include <mlpack\/methods\/neighbor_search\/neighbor_search.hpp>\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\ndouble compute_recall(arma::Mat<size_t> LSHneighbors, \n arma::Mat<size_t> groundTruth)\n{\n const int n_queries = LSHneighbors.n_cols;\n const int n_neigh = LSHneighbors.n_rows;\n\n int found_same = 0;\n for (int q = 0; q < n_queries; ++q)\n {\n for (int n = 0; n < n_neigh; ++n)\n {\n found_same+=(LSHneighbors(n,q)==groundTruth(n,q));\n }\n }\n return static_cast<double>(found_same)\/\n (static_cast<double>(n_queries*n_neigh));\n}\n\nBOOST_AUTO_TEST_SUITE(LSHTest);\n\nBOOST_AUTO_TEST_CASE(LSHSearchTest)\n{\n\n math::RandomSeed(time(0));\n \/\/kNN and LSH parameters (use LSH default parameters)\n const int k = 4;\n const int numTables = 30;\n const int numProj = 10;\n const double hashWidth = 0;\n const int secondHashSize = 99901;\n const int bucketSize = 500;\n \n \/\/test parameters\n const double epsilon = 0.1;\n\n \/\/read iris training and testing data as reference and query\n const string data_train=\"iris_train.csv\";\n const string data_test=\"iris_test.csv\";\n arma::mat rdata;\n arma::mat qdata;\n data::Load(data_train, rdata, true);\n data::Load(data_test, qdata, true);\n\n \/\/Run classic knn on reference data\n AllkNN knn(rdata);\n arma::Mat<size_t> groundTruth;\n arma::mat groundDistances;\n knn.Search(qdata, k, groundTruth, groundDistances);\n\n \/\/Test: Run LSH with varying number of tables, keeping all other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the number of\n \/\/tables will increase recall. Epsilon ensures that if noise lightly affects\n \/\/the projections, the test will not fail.\n \n const int numTries = 5; \/\/tries for each test before declaring failure\n bool fail = false;\n\n for (int t = 0; t < numTries; ++t){\n\n const int Lsize = 6; \/\/number of runs\n const int L_value[] = {1, 8, 16, 32, 64, 128}; \/\/number of tables\n double L_value_recall[Lsize] = {0.0}; \/\/recall of each LSH run\n\n for (int l=0; l < Lsize; ++l)\n {\n \/\/run LSH with only numTables varying (other values default)\n LSHSearch<> lsh_test1(rdata, numProj, L_value[l], \n hashWidth, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test1.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n L_value_recall[l] = compute_recall(LSHneighbors, groundTruth);\n\n if (l > 0){\n if(L_value_recall[l] < L_value_recall[l-1]-epsilon){\n fail = true; \/\/if test fails at one point, stop and retry\n break;\n }\n }\n }\n if ( !fail ){\n break; \/\/if test passes one time, it is sufficient\n }\n }\n BOOST_CHECK(fail == false);\n \n \/\/Test: Run LSH with varying hash width, keeping all other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the hash width\n \/\/will increase recall. Epsilon ensures that if noise lightly affects the \n \/\/projections, the test will not fail.\n \n const int Hsize = 7; \/\/number of runs\n const double H_value[] = {0.1, 0.5, 1, 5, 10, 50, 500}; \/\/hash width\n double H_value_recall[Hsize] = {0.0}; \/\/recall of each run\n\n for (int h=0; h < Hsize; ++h)\n {\n \/\/run LSH with only hashWidth varying (other values default)\n LSHSearch<> lsh_test2(rdata, numProj, numTables, \n H_value[h], secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test2.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n H_value_recall[h] = compute_recall(LSHneighbors, groundTruth);\n\n if (h > 0)\n BOOST_CHECK(H_value_recall[h] >= H_value_recall[h-1]-epsilon);\n \n }\n\n \/\/Test: Run LSH with varying number of Projections, keeping all other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the number of\n \/\/projections per table will decrease recall. Epsilon ensures that if noise lightly \n \/\/affects the projections, the test will not fail.\n \n const int Psize = 5; \/\/number of runs\n const int P_value[] = {1, 10, 20, 50, 100}; \/\/number of projections\n double P_value_recall[Psize] = {0.0}; \/\/recall of each run\n\n for (int p=0; p < Psize; ++p)\n {\n \/\/run LSH with only numProj varying (other values default)\n LSHSearch<> lsh_test3(rdata, P_value[p], numTables, \n hashWidth, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test3.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n P_value_recall[p] = compute_recall(LSHneighbors, groundTruth);\n\n if (p > 0) \/\/don't check first run, only that increasing P decreases recall\n BOOST_CHECK(P_value_recall[p] - epsilon <= P_value_recall[p-1]);\n }\n \n \/\/Test: Run a very expensive LSH search, with a large number of hash tables\n \/\/and a large hash width. This run should return an acceptable recall. We set\n \/\/the bar very low (recall >= 50%) to make sure that a test fail means bad\n \/\/implementation.\n \n const int H_exp = 10000; \/\/first-level hash width\n const int K_exp = 1; \/\/projections per table\n const int T_exp = 128; \/\/number of tables\n const double recall_thresh_exp = 0.5;\n\n LSHSearch<> lsh_test_exp(rdata, K_exp, T_exp, H_exp, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors_exp;\n arma::mat LSHdistances_exp;\n lsh_test_exp.Search(qdata, k, LSHneighbors_exp, LSHdistances_exp);\n \n const double recall_exp = compute_recall(LSHneighbors_exp, groundTruth);\n\n BOOST_CHECK(recall_exp >= recall_thresh_exp);\n\n \/\/Test: Run a very cheap LSH search, with parameters that should cause recall\n \/\/to be very low. Set the threshhold very high (recall <= 25%) to make sure\n \/\/that a test fail means bad implementation.\n \/\/This mainly checks that user-specified parameters are not ignored.\n \n const int H_chp = 1; \/\/small first-level hash width\n const int K_chp = 1000; \/\/large number of projections per table\n const int T_chp = 1; \/\/only one table\n const double recall_thresh_chp = 0.25; \/\/recall threshold\n\n LSHSearch<> lsh_test_chp(rdata, K_chp, T_chp, H_chp, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors_chp;\n arma::mat LSHdistances_chp;\n lsh_test_chp.Search(qdata, k, LSHneighbors_chp, LSHdistances_chp);\n\n const double recall_chp = compute_recall(LSHneighbors_chp, groundTruth);\n BOOST_CHECK(recall_chp <= recall_thresh_chp);\n}\n\nBOOST_AUTO_TEST_CASE(LSHTrainTest)\n{\n \/\/ This is a not very good test that simply checks that the re-trained LSH\n \/\/ model operates on the correct dimensionality and returns the correct number\n \/\/ of results.\n arma::mat referenceData = arma::randu<arma::mat>(3, 100);\n arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);\n arma::mat queryData = arma::randu<arma::mat>(10, 200);\n\n LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);\n\n lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);\n\n arma::Mat<size_t> neighbors;\n arma::mat distances;\n\n lsh.Search(queryData, 3, neighbors, distances);\n\n BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);\n BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n BOOST_REQUIRE_EQUAL(distances.n_cols, 200);\n BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_CASE(EmptyConstructorTest)\n{\n \/\/ If we create an empty LSH model and then call Search(), it should throw an\n \/\/ exception.\n LSHSearch<> lsh;\n\n arma::mat dataset = arma::randu<arma::mat>(5, 50);\n arma::mat distances;\n arma::Mat<size_t> neighbors;\n BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),\n std::invalid_argument);\n\n \/\/ Now, train.\n lsh.Train(dataset, 4, 3, 3.0, 12, 4);\n\n lsh.Search(dataset, 3, neighbors, distances);\n\n BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);\n BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n BOOST_REQUIRE_EQUAL(distances.n_cols, 50);\n BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<commit_msg>Style Fixes<commit_after>\/**\n * @file lsh_test.cpp\n *\n * Unit tests for the 'LSHSearch' class.\n *\/\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\n#include <mlpack\/methods\/lsh\/lsh_search.hpp>\n#include <mlpack\/methods\/neighbor_search\/neighbor_search.hpp>\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\ndouble compute_recall(\n arma::Mat<size_t> LSHneighbors, \n arma::Mat<size_t> groundTruth)\n{\n const int n_queries = LSHneighbors.n_cols;\n const int n_neigh = LSHneighbors.n_rows;\n\n int found_same = 0;\n for (int q = 0; q < n_queries; ++q)\n {\n for (int n = 0; n < n_neigh; ++n)\n {\n found_same+=(LSHneighbors(n,q)==groundTruth(n,q));\n }\n }\n return static_cast<double>(found_same)\/\n (static_cast<double>(n_queries*n_neigh));\n}\n\nBOOST_AUTO_TEST_SUITE(LSHTest);\n\nBOOST_AUTO_TEST_CASE(LSHSearchTest)\n{\n\n math::RandomSeed(time(0));\n \/\/kNN and LSH parameters (use LSH default parameters)\n const int k = 4;\n const int numTables = 30;\n const int numProj = 10;\n const double hashWidth = 0;\n const int secondHashSize = 99901;\n const int bucketSize = 500;\n \n \/\/test parameters\n const double epsilon = 0.1;\n\n \/\/read iris training and testing data as reference and query\n const string data_train=\"iris_train.csv\";\n const string data_test=\"iris_test.csv\";\n arma::mat rdata;\n arma::mat qdata;\n data::Load(data_train, rdata, true);\n data::Load(data_test, qdata, true);\n\n \/\/Run classic knn on reference data\n AllkNN knn(rdata);\n arma::Mat<size_t> groundTruth;\n arma::mat groundDistances;\n knn.Search(qdata, k, groundTruth, groundDistances);\n\n \/\/Test: Run LSH with varying number of tables, keeping all other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the number of\n \/\/tables will increase recall. Epsilon ensures that if noise lightly affects\n \/\/the projections, the test will not fail.\n \n const int numTries = 5; \/\/tries for each test before declaring failure\n bool fail = false;\n\n for (int t = 0; t < numTries; ++t){\n\n const int Lsize = 6; \/\/number of runs\n const int L_value[] = {1, 8, 16, 32, 64, 128}; \/\/number of tables\n double L_value_recall[Lsize] = {0.0}; \/\/recall of each LSH run\n\n for (int l=0; l < Lsize; ++l)\n {\n \/\/run LSH with only numTables varying (other values default)\n LSHSearch<> lsh_test1(rdata, numProj, L_value[l], \n hashWidth, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test1.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n L_value_recall[l] = compute_recall(LSHneighbors, groundTruth);\n\n if (l > 0){\n if(L_value_recall[l] < L_value_recall[l-1]-epsilon){\n fail = true; \/\/if test fails at one point, stop and retry\n break;\n }\n }\n }\n if ( !fail ){\n break; \/\/if test passes one time, it is sufficient\n }\n }\n BOOST_CHECK(fail == false);\n \n \/\/Test: Run LSH with varying hash width, keeping all other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the hash width\n \/\/will increase recall. Epsilon ensures that if noise lightly affects the \n \/\/projections, the test will not fail.\n \n const int Hsize = 7; \/\/number of runs\n const double H_value[] = {0.1, 0.5, 1, 5, 10, 50, 500}; \/\/hash width\n double H_value_recall[Hsize] = {0.0}; \/\/recall of each run\n\n for (int h=0; h < Hsize; ++h)\n {\n \/\/run LSH with only hashWidth varying (other values default)\n LSHSearch<> lsh_test2(rdata, numProj, numTables, \n H_value[h], secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test2.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n H_value_recall[h] = compute_recall(LSHneighbors, groundTruth);\n\n if (h > 0)\n BOOST_CHECK(H_value_recall[h] >= H_value_recall[h-1]-epsilon);\n \n }\n\n \/\/Test: Run LSH with varying number of projections, keeping other parameters \n \/\/constant. Compute the recall, i.e. the number of reported neighbors that\n \/\/are real neighbors of the query.\n \/\/LSH's property is that (with high probability), increasing the number of\n \/\/projections per table will decrease recall. Epsilon ensures that if noise \n \/\/lightly affects the projections, the test will not fail.\n \n const int Psize = 5; \/\/number of runs\n const int P_value[] = {1, 10, 20, 50, 100}; \/\/number of projections\n double P_value_recall[Psize] = {0.0}; \/\/recall of each run\n\n for (int p=0; p < Psize; ++p)\n {\n \/\/run LSH with only numProj varying (other values default)\n LSHSearch<> lsh_test3(rdata, P_value[p], numTables, \n hashWidth, secondHashSize, bucketSize);\n arma::Mat<size_t> LSHneighbors;\n arma::mat LSHdistances;\n lsh_test3.Search(qdata, k, LSHneighbors, LSHdistances);\n\n \/\/compute recall for each query\n P_value_recall[p] = compute_recall(LSHneighbors, groundTruth);\n\n if (p > 0) \/\/don't check first run, only that increasing P decreases recall\n BOOST_CHECK(P_value_recall[p] - epsilon <= P_value_recall[p-1]);\n }\n \n \/\/Test: Run a very expensive LSH search, with a large number of hash tables\n \/\/and a large hash width. This run should return an acceptable recall. We set\n \/\/the bar very low (recall >= 50%) to make sure that a test fail means bad\n \/\/implementation.\n \n const int H_exp = 10000; \/\/first-level hash width\n const int K_exp = 1; \/\/projections per table\n const int T_exp = 128; \/\/number of tables\n const double recall_thresh_exp = 0.5;\n\n LSHSearch<> lsh_test_exp(\n rdata, \n K_exp, \n T_exp, \n H_exp, \n secondHashSize, \n bucketSize);\n arma::Mat<size_t> LSHneighbors_exp;\n arma::mat LSHdistances_exp;\n lsh_test_exp.Search(qdata, k, LSHneighbors_exp, LSHdistances_exp);\n \n const double recall_exp = compute_recall(LSHneighbors_exp, groundTruth);\n\n BOOST_CHECK(recall_exp >= recall_thresh_exp);\n\n \/\/Test: Run a very cheap LSH search, with parameters that should cause recall\n \/\/to be very low. Set the threshhold very high (recall <= 25%) to make sure\n \/\/that a test fail means bad implementation.\n \/\/This mainly checks that user-specified parameters are not ignored.\n \n const int H_chp = 1; \/\/small first-level hash width\n const int K_chp = 1000; \/\/large number of projections per table\n const int T_chp = 1; \/\/only one table\n const double recall_thresh_chp = 0.25; \/\/recall threshold\n\n LSHSearch<> lsh_test_chp(\n rdata, \n K_chp, \n T_chp, \n H_chp, \n secondHashSize, \n bucketSize);\n arma::Mat<size_t> LSHneighbors_chp;\n arma::mat LSHdistances_chp;\n lsh_test_chp.Search(qdata, k, LSHneighbors_chp, LSHdistances_chp);\n\n const double recall_chp = compute_recall(LSHneighbors_chp, groundTruth);\n BOOST_CHECK(recall_chp <= recall_thresh_chp);\n}\n\nBOOST_AUTO_TEST_CASE(LSHTrainTest)\n{\n \/\/ This is a not very good test that simply checks that the re-trained LSH\n \/\/ model operates on the correct dimensionality and returns the correct number\n \/\/ of results.\n arma::mat referenceData = arma::randu<arma::mat>(3, 100);\n arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);\n arma::mat queryData = arma::randu<arma::mat>(10, 200);\n\n LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);\n\n lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);\n\n arma::Mat<size_t> neighbors;\n arma::mat distances;\n\n lsh.Search(queryData, 3, neighbors, distances);\n\n BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);\n BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n BOOST_REQUIRE_EQUAL(distances.n_cols, 200);\n BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_CASE(EmptyConstructorTest)\n{\n \/\/ If we create an empty LSH model and then call Search(), it should throw an\n \/\/ exception.\n LSHSearch<> lsh;\n\n arma::mat dataset = arma::randu<arma::mat>(5, 50);\n arma::mat distances;\n arma::Mat<size_t> neighbors;\n BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),\n std::invalid_argument);\n\n \/\/ Now, train.\n lsh.Train(dataset, 4, 3, 3.0, 12, 4);\n\n lsh.Search(dataset, 3, neighbors, distances);\n\n BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);\n BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);\n BOOST_REQUIRE_EQUAL(distances.n_cols, 50);\n BOOST_REQUIRE_EQUAL(distances.n_rows, 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cmath>\n\n#include \"mocc-core\/global_config.hpp\"\n\nconst int N = 100000;\n\nnamespace mocc {\n \/**\n * Base class defining a class of simple utility classes for computing\n * exponential functions. The base version uses the stock library call to\n * exp(), while derived versions can override this with more efficient table\n * lookups.\n *\/\n class Exponential {\n public:\n Exponential():\n max_error_( 0.0 )\n { }\n\n inline virtual real_t exp( real_t v ) {\n return std::exp(v);\n }\n\n real_t max_error() {\n return max_error_;\n }\n\n protected:\n real_t max_error_;\n };\n\n class Exponential_Linear: public Exponential {\n public:\n Exponential_Linear():\n min_( -10.0 ),\n space_( -min_\/(real_t)(N-1)),\n rspace_( 1.0\/space_ )\n {\n for( int i=0; i<N; i++ ) {\n d_[i] = std::exp(min_+i*space_);\n }\n\n for( int i=0; i<N-1; i++ ) {\n real_t x = min_+space_*(0.5+i);\n real_t err = std::abs(this->exp(x) - std::exp(x));\n max_error_ = std::max( max_error_, err );\n }\n }\n\n inline real_t exp( real_t v ) {\n assert((v < 0.0) && (v >= min_));\n int i = (v-min_)*rspace_;\n v -= space_*i+min_;\n return d_[i] + (d_[i+1] - d_[i])*v*rspace_;\n }\n private:\n real_t min_;\n real_t space_;\n real_t rspace_;\n std::array<real_t, N> d_;\n };\n}\n<commit_msg>Add contingency for out-of-bounds exponentials<commit_after>#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cmath>\n\n#include \"mocc-core\/global_config.hpp\"\n\nconst int N = 10000;\n\nnamespace mocc {\n \/**\n * Base class defining a class of simple utility classes for computing\n * exponential functions. The base version uses the stock library call to\n * exp(), while derived versions can override this with more efficient table\n * lookups.\n *\/\n class Exponential {\n public:\n Exponential():\n max_error_( 0.0 )\n { }\n\n inline virtual real_t exp( real_t v ) {\n return std::exp(v);\n }\n\n real_t max_error() {\n return max_error_;\n }\n\n protected:\n real_t max_error_;\n };\n\n class Exponential_Linear: public Exponential {\n public:\n Exponential_Linear():\n min_( -10.0 ),\n space_( -min_\/(real_t)(N-1)),\n rspace_( 1.0\/space_ )\n {\n for( int i=0; i<N; i++ ) {\n d_[i] = std::exp(min_+i*space_);\n }\n\n for( int i=0; i<N-1; i++ ) {\n real_t x = min_+space_*(0.5+i);\n real_t err = std::abs(this->exp(x) - std::exp(x));\n max_error_ = std::max( max_error_, err );\n }\n }\n\n inline real_t exp( real_t v ) {\n assert((v < 0.0));\n if( v < min_ ) {\n std::cout << \"Big exponential argument: \" << v << std::endl;\n return std::exp(v);\n }\n int i = (v-min_)*rspace_;\n v -= space_*i+min_;\n return d_[i] + (d_[i+1] - d_[i])*v*rspace_;\n }\n private:\n real_t min_;\n real_t space_;\n real_t rspace_;\n std::array<real_t, N> d_;\n };\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"moc_sweeper.hpp\"\n\n#include <iomanip>\n#include \"error.hpp\"\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\n\nmocc::VecF temp;\n\nnamespace mocc {\n \n MoCSweeper::MoCSweeper( const pugi::xml_node& input, \n const CoreMesh& mesh ):\n TransportSweeper( mesh ),\n mesh_( mesh ),\n ang_quad_( input.child(\"ang_quad\") ),\n rays_( input.child(\"rays\"), ang_quad_, mesh ),\n xstr_( n_reg_, 1 ),\n flux_1g_( n_reg_, 1 ),\n qbar_( n_reg_, 1 ),\n bc_type_( mesh_.boundary() )\n { \n \/\/ Make sure we have input from the XML\n if( input.empty() ) {\n Error(\"No input specified to initialize MoC sweeper.\");\n }\n\n \/\/ Parse the number of inner iterations\n int int_in = input.attribute(\"n_inner\").as_int(-1);\n if(int_in < 0) {\n Error(\"Invalid number of inner iterations specified (n_inner).\");\n }\n n_inner_ = int_in;\n\n \/\/ Set up the array of volumes (surface area)\n int ireg = 0;\n for( auto &pin: mesh_ ) {\n const VecF& pin_vols = pin->vols();\n for( auto &v: pin_vols ) {\n vol_(ireg) = v;\n ireg++;\n }\n }\n\n \/\/ allocate space to store the boundary conditions\n boundary_.resize( ng_ );\n for( auto &group_rays: boundary_ ) {\n group_rays.resize( mesh_.nz() );\n for( auto &angle_rays: group_rays ) {\n \/\/ We actually allocate BCs for all 4 octants to make things a\n \/\/ little simpler.\n angle_rays.resize( ang_quad_.ndir_oct()*4 );\n int iang = 0;\n for( auto ang_it=ang_quad_.octant(1); \n ang_it!=ang_quad_.octant(5); ang_it++ ) {\n angle_rays[iang].resize(rays_.n_rays(iang));\n iang++;\n }\n }\n }\n boundary_out_.resize( mesh_.nz() );\n for( auto &angle_rays: boundary_out_ ) {\n \/\/ We actually allocate BCs for all 4 octants to make things a\n \/\/ little simpler.\n angle_rays.resize( ang_quad_.ndir_oct()*4 );\n int iang = 0;\n for( auto ang_it=ang_quad_.octant(1); \n ang_it!=ang_quad_.octant(5); ang_it++ ) {\n angle_rays[iang].resize(rays_.n_rays(iang));\n iang++;\n }\n }\n\n return;\n }\n\n void MoCSweeper::sweep( int group ) {\n assert(source_);\n\n \/\/ set up the xstr_ array\n for( auto &xsr: *xs_mesh_ ) {\n real_t xstr = xsr.xsmactr()[group];\n for( auto &ireg: xsr.reg() ) {\n xstr_(ireg) = xstr;\n }\n }\n\n flux_1g_ = flux_.col( group );\n\n \/\/ Perform inner iterations\n for( unsigned int inner=0; inner<n_inner_; inner++ ) {\n \/\/ update the self-scattering source\n source_->self_scatter( group, flux_1g_, qbar_ );\n \/\/ Perform the stock sweep unless we are on the last outer and have\n \/\/ a CoarseData object.\n if( inner == n_inner_-1 && coarse_data_ ) {\n this->sweep1g_final( group );\n } else {\n this->sweep1g( group );\n }\n }\n\n flux_.col( group ) = flux_1g_;\n\n return;\n }\n\n\n void MoCSweeper::update_boundary( int group ) {\n int iplane=0;\n for( auto &plane_bcs: boundary_[group] ) {\n for( unsigned int iang=0; iang<plane_bcs.size(); iang++ ) {\n int nx = rays_.nx(iang);\n int ny = rays_.ny(iang);\n\n \/\/ Determine based on the angle quadrant which surfaces are\n \/\/ upwind and need to be updated for the given angle\n Surface upwind[2];\n if(ang_quad_[iang].ox > 0.0) {\n upwind[0] = Surface::WEST;\n } else {\n upwind[0] = Surface::EAST;\n }\n if(ang_quad_[iang].oy > 0.0) {\n upwind[1] = Surface::SOUTH;\n } else {\n upwind[1] = Surface::NORTH;\n }\n\n \/\/ Treat the two surfaces that were determined above\n if( bc_type_[(int)upwind[0]] == Boundary::REFLECT ) {\n int ang_ref = ang_quad_.reflect(iang, upwind[0]);\n for( int ibc=0; ibc<ny; ibc++ ) {\n plane_bcs[iang][ibc] =\n boundary_out_[iplane][ang_ref][ibc];\n }\n } else {\n for( int ibc=0; ibc<ny; ibc++ ) {\n plane_bcs[iang][ibc] = 0.0;\n }\n }\n \n if( bc_type_[(int)upwind[1]] == Boundary::REFLECT ) {\n int ang_ref = ang_quad_.reflect(iang, upwind[1]);\n for( int ibc=ny; ibc<(nx+ny); ibc++ ) {\n plane_bcs[iang][ibc] =\n boundary_out_[iplane][ang_ref][ibc];\n }\n } else {\n for( int ibc=ny; ibc<(nx+ny); ibc++ ) {\n plane_bcs[iang][ibc] = 0.0;\n }\n }\n } \/\/ angle loop\n iplane++;\n } \/\/ plane loop\n }\n\n void MoCSweeper::initialize() {\n \/\/ There are better ways to do this, but for now, just start with 1.0\n flux_.fill(1.0);\n\n \/\/ Walk through the boundary conditions and initialize them the 1\/4pi\n real_t val = 1.0\/FPI;\n for( auto &group_rays: boundary_ ) {\n for( auto &plane_rays: group_rays ) {\n for( auto &angle_rays: plane_rays ) {\n for( auto &ray: angle_rays ) {\n ray = val;\n }\n }\n }\n }\n return;\n }\n\n void MoCSweeper::homogenize( CoarseData &data ) const {\n \n return;\n }\n\n void MoCSweeper::get_pin_flux( int group, VecF& flux ) const {\n flux.resize( mesh_.n_pin() );\n for( auto &f: flux ) {\n f = 0.0;\n }\n\n int ireg = 0;\n int ipin = 0;\n for( auto &pin: mesh_ ) {\n Position pos = mesh_.pin_position(ipin);\n int i = mesh_.index_lex(pos);\n real_t v = 0.0;\n for( int ir=0; ir<pin->n_reg(); ir++) {\n v += vol_(ireg);\n flux[i] += flux_(ireg, group)*vol_(ireg);\n ireg++;\n }\n flux[i] \/= v;\n ipin++;\n }\n\n return;\n }\n\n void MoCSweeper::output( H5File& file ) const {\n \/\/ Get core dimensions from the mesh\n const int nx = mesh_.nx();\n const int ny = mesh_.ny();\n const int nz = mesh_.nz();\n VecI dims;\n dims.push_back(nz);\n dims.push_back(ny);\n dims.push_back(nx);\n \n \/\/ Make a group in the file to store the flux\n file.mkdir(\"\/flux\");\n \n \/\/ Provide energy group upper bounds\n file.write(\"\/eubounds\", xs_mesh_->eubounds(), VecI(1, ng_));\n file.write(\"\/ng\", ng_);\n \n for( unsigned int ig=0; ig<ng_; ig++ ) {\n VecF flux;\n this->get_pin_flux(ig, flux);\n \n \n std::stringstream setname;\n setname << \"\/flux\/\" << std::setfill('0') << std::setw(3) << ig+1;\n \n file.write(setname.str(), flux, dims);\n }\n\n return;\n }\n\n#include \"moc_kernels.hpp.inc\"\n}\n<commit_msg>Fix some whitespace<commit_after>#include \"moc_sweeper.hpp\"\n\n#include <iomanip>\n#include \"error.hpp\"\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\n\nmocc::VecF temp;\n\nnamespace mocc {\n \n MoCSweeper::MoCSweeper( const pugi::xml_node& input, \n const CoreMesh& mesh ):\n TransportSweeper( mesh ),\n mesh_( mesh ),\n ang_quad_( input.child(\"ang_quad\") ),\n rays_( input.child(\"rays\"), ang_quad_, mesh ),\n xstr_( n_reg_, 1 ),\n flux_1g_( n_reg_, 1 ),\n qbar_( n_reg_, 1 ),\n bc_type_( mesh_.boundary() )\n { \n \/\/ Make sure we have input from the XML\n if( input.empty() ) {\n Error(\"No input specified to initialize MoC sweeper.\");\n }\n\n \/\/ Parse the number of inner iterations\n int int_in = input.attribute(\"n_inner\").as_int(-1);\n if(int_in < 0) {\n Error(\"Invalid number of inner iterations specified (n_inner).\");\n }\n n_inner_ = int_in;\n\n \/\/ Set up the array of volumes (surface area)\n int ireg = 0;\n for( auto &pin: mesh_ ) {\n const VecF& pin_vols = pin->vols();\n for( auto &v: pin_vols ) {\n vol_(ireg) = v;\n ireg++;\n }\n }\n\n \/\/ allocate space to store the boundary conditions\n boundary_.resize( ng_ );\n for( auto &group_rays: boundary_ ) {\n group_rays.resize( mesh_.nz() );\n for( auto &angle_rays: group_rays ) {\n \/\/ We actually allocate BCs for all 4 octants to make things a\n \/\/ little simpler.\n angle_rays.resize( ang_quad_.ndir_oct()*4 );\n int iang = 0;\n for( auto ang_it=ang_quad_.octant(1); \n ang_it!=ang_quad_.octant(5); ang_it++ ) {\n angle_rays[iang].resize(rays_.n_rays(iang));\n iang++;\n }\n }\n }\n boundary_out_.resize( mesh_.nz() );\n for( auto &angle_rays: boundary_out_ ) {\n \/\/ We actually allocate BCs for all 4 octants to make things a\n \/\/ little simpler.\n angle_rays.resize( ang_quad_.ndir_oct()*4 );\n int iang = 0;\n for( auto ang_it=ang_quad_.octant(1); \n ang_it!=ang_quad_.octant(5); ang_it++ ) {\n angle_rays[iang].resize(rays_.n_rays(iang));\n iang++;\n }\n }\n\n return;\n }\n\n void MoCSweeper::sweep( int group ) {\n assert(source_);\n\n \/\/ set up the xstr_ array\n for( auto &xsr: *xs_mesh_ ) {\n real_t xstr = xsr.xsmactr()[group];\n for( auto &ireg: xsr.reg() ) {\n xstr_(ireg) = xstr;\n }\n }\n\n flux_1g_ = flux_.col( group );\n\n \/\/ Perform inner iterations\n for( unsigned int inner=0; inner<n_inner_; inner++ ) {\n \/\/ update the self-scattering source\n source_->self_scatter( group, flux_1g_, qbar_ );\n \/\/ Perform the stock sweep unless we are on the last outer and have\n \/\/ a CoarseData object.\n if( inner == n_inner_-1 && coarse_data_ ) {\n this->sweep1g_final( group );\n } else {\n this->sweep1g( group );\n }\n }\n\n flux_.col( group ) = flux_1g_;\n\n return;\n }\n\n\n void MoCSweeper::update_boundary( int group ) {\n int iplane=0;\n for( auto &plane_bcs: boundary_[group] ) {\n for( unsigned int iang=0; iang<plane_bcs.size(); iang++ ) {\n int nx = rays_.nx(iang);\n int ny = rays_.ny(iang);\n\n \/\/ Determine based on the angle quadrant which surfaces are\n \/\/ upwind and need to be updated for the given angle\n Surface upwind[2];\n if(ang_quad_[iang].ox > 0.0) {\n upwind[0] = Surface::WEST;\n } else {\n upwind[0] = Surface::EAST;\n }\n if(ang_quad_[iang].oy > 0.0) {\n upwind[1] = Surface::SOUTH;\n } else {\n upwind[1] = Surface::NORTH;\n }\n\n \/\/ Treat the two surfaces that were determined above\n if( bc_type_[(int)upwind[0]] == Boundary::REFLECT ) {\n int ang_ref = ang_quad_.reflect(iang, upwind[0]);\n for( int ibc=0; ibc<ny; ibc++ ) {\n plane_bcs[iang][ibc] =\n boundary_out_[iplane][ang_ref][ibc];\n }\n } else {\n for( int ibc=0; ibc<ny; ibc++ ) {\n plane_bcs[iang][ibc] = 0.0;\n }\n }\n \n if( bc_type_[(int)upwind[1]] == Boundary::REFLECT ) {\n int ang_ref = ang_quad_.reflect(iang, upwind[1]);\n for( int ibc=ny; ibc<(nx+ny); ibc++ ) {\n plane_bcs[iang][ibc] =\n boundary_out_[iplane][ang_ref][ibc];\n }\n } else {\n for( int ibc=ny; ibc<(nx+ny); ibc++ ) {\n plane_bcs[iang][ibc] = 0.0;\n }\n }\n } \/\/ angle loop\n iplane++;\n } \/\/ plane loop\n }\n\n void MoCSweeper::initialize() {\n \/\/ There are better ways to do this, but for now, just start with 1.0\n flux_.fill(1.0);\n\n \/\/ Walk through the boundary conditions and initialize them the 1\/4pi\n real_t val = 1.0\/FPI;\n for( auto &group_rays: boundary_ ) {\n for( auto &plane_rays: group_rays ) {\n for( auto &angle_rays: plane_rays ) {\n for( auto &ray: angle_rays ) {\n ray = val;\n }\n }\n }\n }\n return;\n }\n\n void MoCSweeper::homogenize( CoarseData &data ) const {\n \n return;\n }\n\n void MoCSweeper::get_pin_flux( int group, VecF& flux ) const {\n flux.resize( mesh_.n_pin() );\n for( auto &f: flux ) {\n f = 0.0;\n }\n\n int ireg = 0;\n int ipin = 0;\n for( auto &pin: mesh_ ) {\n Position pos = mesh_.pin_position(ipin);\n int i = mesh_.index_lex(pos);\n real_t v = 0.0;\n for( int ir=0; ir<pin->n_reg(); ir++ ) {\n v += vol_(ireg);\n flux[i] += flux_(ireg, group)*vol_(ireg);\n ireg++;\n }\n flux[i] \/= v;\n ipin++;\n }\n\n return;\n }\n\n void MoCSweeper::output( H5File& file ) const {\n \/\/ Get core dimensions from the mesh\n const int nx = mesh_.nx();\n const int ny = mesh_.ny();\n const int nz = mesh_.nz();\n VecI dims;\n dims.push_back(nz);\n dims.push_back(ny);\n dims.push_back(nx);\n \n \/\/ Make a group in the file to store the flux\n file.mkdir(\"\/flux\");\n \n \/\/ Provide energy group upper bounds\n file.write(\"\/eubounds\", xs_mesh_->eubounds(), VecI(1, ng_));\n file.write(\"\/ng\", ng_);\n \n for( unsigned int ig=0; ig<ng_; ig++ ) {\n VecF flux;\n this->get_pin_flux(ig, flux);\n \n \n std::stringstream setname;\n setname << \"\/flux\/\" << std::setfill('0') << std::setw(3) << ig+1;\n \n file.write(setname.str(), flux, dims);\n }\n\n return;\n }\n\n#include \"moc_kernels.hpp.inc\"\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"buildsettingspropertiespage.h\"\n#include \"buildstep.h\"\n#include \"buildstepspage.h\"\n#include \"project.h\"\n#include \"projectexplorerconstants.h\"\n#include \"target.h\"\n#include \"buildconfiguration.h\"\n#include \"buildconfigurationmodel.h\"\n\n#include <coreplugin\/coreconstants.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcassert.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <projectexplorer\/buildmanager.h>\n\n#include <QMargins>\n#include <QTimer>\n#include <QCoreApplication>\n#include <QComboBox>\n#include <QInputDialog>\n#include <QLabel>\n#include <QMenu>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QVBoxLayout>\n\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\n\n\/\/\/\n\/\/ BuildSettingsPanelFactory\n\/\/\/\n\nQString BuildSettingsPanelFactory::id() const\n{\n return QLatin1String(BUILDSETTINGS_PANEL_ID);\n}\n\nQString BuildSettingsPanelFactory::displayName() const\n{\n return QCoreApplication::translate(\"BuildSettingsPanelFactory\", \"Build Settings\");\n}\n\nint BuildSettingsPanelFactory::priority() const\n{\n return 10;\n}\n\nbool BuildSettingsPanelFactory::supports(Target *target)\n{\n return IBuildConfigurationFactory::find(target);\n}\n\nPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)\n{\n PropertiesPanel *panel = new PropertiesPanel;\n QWidget *w = new QWidget();\n QVBoxLayout *l = new QVBoxLayout(w);\n QWidget *b = new BuildSettingsWidget(target);\n l->addWidget(b);\n l->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));\n l->setContentsMargins(QMargins());\n panel->setWidget(w);\n panel->setIcon(QIcon(QLatin1String(\":\/projectexplorer\/images\/BuildSettings.png\")));\n panel->setDisplayName(QCoreApplication::translate(\"BuildSettingsPanel\", \"Build Settings\"));\n return panel;\n}\n\n\/\/\/\n\/\/ BuildSettingsWidget\n\/\/\/\n\nBuildSettingsWidget::~BuildSettingsWidget()\n{\n clear();\n}\n\nBuildSettingsWidget::BuildSettingsWidget(Target *target) :\n m_target(target),\n m_buildConfiguration(0)\n{\n Q_ASSERT(m_target);\n\n QVBoxLayout *vbox = new QVBoxLayout(this);\n vbox->setContentsMargins(0, 0, 0, 0);\n\n if (!IBuildConfigurationFactory::find(m_target)) {\n QLabel *noSettingsLabel = new QLabel(this);\n noSettingsLabel->setText(tr(\"No build settings available\"));\n QFont f = noSettingsLabel->font();\n f.setPointSizeF(f.pointSizeF() * 1.2);\n noSettingsLabel->setFont(f);\n vbox->addWidget(noSettingsLabel);\n return;\n }\n\n { \/\/ Edit Build Configuration row\n QHBoxLayout *hbox = new QHBoxLayout();\n hbox->setContentsMargins(0, 0, 0, 0);\n hbox->addWidget(new QLabel(tr(\"Edit build configuration:\"), this));\n m_buildConfigurationComboBox = new QComboBox(this);\n m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);\n m_buildConfigurationComboBox->setModel(new BuildConfigurationModel(m_target, this));\n hbox->addWidget(m_buildConfigurationComboBox);\n\n m_addButton = new QPushButton(this);\n m_addButton->setText(tr(\"Add\"));\n m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_addButton);\n m_addButtonMenu = new QMenu(this);\n m_addButton->setMenu(m_addButtonMenu);\n\n m_removeButton = new QPushButton(this);\n m_removeButton->setText(tr(\"Remove\"));\n m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_removeButton);\n\n m_renameButton = new QPushButton(this);\n m_renameButton->setText(tr(\"Rename...\"));\n m_renameButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_renameButton);\n\n hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));\n vbox->addLayout(hbox);\n }\n\n m_buildConfiguration = m_target->activeBuildConfiguration();\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n m_buildConfigurationComboBox->setCurrentIndex(model->indexFor(m_buildConfiguration).row());\n\n updateAddButtonMenu();\n updateBuildSettings();\n\n connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),\n this, SLOT(currentIndexChanged(int)));\n\n connect(m_removeButton, SIGNAL(clicked()),\n this, SLOT(deleteConfiguration()));\n\n connect(m_renameButton, SIGNAL(clicked()),\n this, SLOT(renameConfiguration()));\n\n connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),\n this, SLOT(updateActiveConfiguration()));\n\n connect(m_target, SIGNAL(kitChanged()), this, SLOT(updateAddButtonMenu()));\n}\n\nvoid BuildSettingsWidget::addSubWidget(BuildConfigWidget *widget)\n{\n widget->setContentsMargins(0, 10, 0, 0);\n\n QLabel *label = new QLabel(this);\n label->setText(widget->displayName());\n connect(widget, SIGNAL(displayNameChanged(QString)),\n label, SLOT(setText(QString)));\n QFont f = label->font();\n f.setBold(true);\n f.setPointSizeF(f.pointSizeF() * 1.2);\n label->setFont(f);\n\n label->setContentsMargins(0, 10, 0, 0);\n\n layout()->addWidget(label);\n layout()->addWidget(widget);\n\n m_labels.append(label);\n m_subWidgets.append(widget);\n}\n\nvoid BuildSettingsWidget::clear()\n{\n qDeleteAll(m_subWidgets);\n m_subWidgets.clear();\n qDeleteAll(m_labels);\n m_labels.clear();\n}\n\nQList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const\n{\n return m_subWidgets;\n}\n\nvoid BuildSettingsWidget::updateAddButtonMenu()\n{\n m_addButtonMenu->clear();\n if (m_target) {\n if (m_target->activeBuildConfiguration()) {\n m_addButtonMenu->addAction(tr(\"&Clone Selected\"),\n this, SLOT(cloneConfiguration()));\n }\n IBuildConfigurationFactory * factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n foreach (Core::Id id, factory->availableCreationIds(m_target)) {\n QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));\n action->setData(QVariant::fromValue(id));\n }\n }\n}\n\nvoid BuildSettingsWidget::updateBuildSettings()\n{\n clear();\n\n \/\/ update buttons\n m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);\n\n \/\/ Add pages\n BuildConfigWidget *generalConfigWidget = m_buildConfiguration->createConfigWidget();\n addSubWidget(generalConfigWidget);\n\n addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_BUILD)));\n addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_CLEAN)));\n\n QList<BuildConfigWidget *> subConfigWidgets = m_buildConfiguration->createSubConfigWidgets();\n foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)\n addSubWidget(subConfigWidget);\n\n foreach (BuildConfigWidget *widget, subWidgets())\n widget->init(m_buildConfiguration);\n}\n\nvoid BuildSettingsWidget::currentIndexChanged(int index)\n{\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n BuildConfiguration *buildConfiguration = model->buildConfigurationAt(index);\n m_target->setActiveBuildConfiguration(buildConfiguration);\n}\n\nvoid BuildSettingsWidget::updateActiveConfiguration()\n{\n if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())\n return;\n\n m_buildConfiguration = m_target->activeBuildConfiguration();\n\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n m_buildConfigurationComboBox->setCurrentIndex(model->indexFor(m_buildConfiguration).row());\n\n foreach (QWidget *widget, subWidgets()) {\n if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {\n buildStepWidget->init(m_buildConfiguration);\n }\n }\n}\n\nvoid BuildSettingsWidget::createConfiguration()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n Core::Id id = action->data().value<Core::Id>();\n\n IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n\n BuildConfiguration *bc = factory->create(m_target, id);\n if (!bc)\n return;\n\n m_target->addBuildConfiguration(bc);\n\n QTC_CHECK(bc->id() == id);\n m_target->setActiveBuildConfiguration(bc);\n updateBuildSettings();\n}\n\nvoid BuildSettingsWidget::cloneConfiguration()\n{\n cloneConfiguration(m_buildConfiguration);\n}\n\nvoid BuildSettingsWidget::deleteConfiguration()\n{\n deleteConfiguration(m_buildConfiguration);\n}\n\nQString BuildSettingsWidget::uniqueName(const QString & name)\n{\n QString result = name.trimmed();\n if (!result.isEmpty()) {\n QStringList bcNames;\n foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {\n if (bc == m_buildConfiguration)\n continue;\n bcNames.append(bc->displayName());\n }\n result = Project::makeUnique(result, bcNames);\n }\n return result;\n}\n\nvoid BuildSettingsWidget::renameConfiguration()\n{\n bool ok;\n QString name = QInputDialog::getText(this, tr(\"Rename...\"),\n tr(\"New name for build configuration <b>%1<\/b>:\").\n arg(m_buildConfiguration->displayName()),\n QLineEdit::Normal,\n m_buildConfiguration->displayName(), &ok);\n if (!ok)\n return;\n\n name = uniqueName(name);\n if (name.isEmpty())\n return;\n\n m_buildConfiguration->setDisplayName(name);\n\n}\n\nvoid BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)\n{\n if (!sourceConfiguration)\n return;\n IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n\n \/\/: Title of a the cloned BuildConfiguration window, text of the window\n QString name = uniqueName(QInputDialog::getText(this, tr(\"Clone Configuration\"), tr(\"New configuration name:\")));\n if (name.isEmpty())\n return;\n\n BuildConfiguration *bc = factory->clone(m_target, sourceConfiguration);\n if (!bc)\n return;\n\n bc->setDisplayName(name);\n m_target->addBuildConfiguration(bc);\n updateBuildSettings();\n\n m_target->setActiveBuildConfiguration(bc);\n}\n\nvoid BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)\n{\n if (!deleteConfiguration ||\n m_target->buildConfigurations().size() <= 1)\n return;\n\n ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();\n if (bm->isBuilding(deleteConfiguration)) {\n QMessageBox box;\n QPushButton *closeAnyway = box.addButton(tr(\"Cancel Build && Remove Build Configuration\"), QMessageBox::AcceptRole);\n QPushButton *cancelClose = box.addButton(tr(\"Do Not Remove\"), QMessageBox::RejectRole);\n box.setDefaultButton(cancelClose);\n box.setWindowTitle(tr(\"Remove Build Configuration %1?\").arg(deleteConfiguration->displayName()));\n box.setText(tr(\"The build configuration <b>%1<\/b> is currently being built.\").arg(deleteConfiguration->displayName()));\n box.setInformativeText(tr(\"Do you want to cancel the build process and remove the Build Configuration anyway?\"));\n box.exec();\n if (box.clickedButton() != closeAnyway)\n return;\n bm->cancel();\n } else {\n QMessageBox msgBox(QMessageBox::Question, tr(\"Remove Build Configuration?\"),\n tr(\"Do you really want to delete build configuration <b>%1<\/b>?\").arg(deleteConfiguration->displayName()),\n QMessageBox::Yes|QMessageBox::No, this);\n msgBox.setDefaultButton(QMessageBox::No);\n msgBox.setEscapeButton(QMessageBox::No);\n if (msgBox.exec() == QMessageBox::No)\n return;\n }\n\n m_target->removeBuildConfiguration(deleteConfiguration);\n\n updateBuildSettings();\n}\n<commit_msg>BuildSettingsWidget: Recreate BuildConfigWidgets per BuildConfiguration<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"buildsettingspropertiespage.h\"\n#include \"buildstep.h\"\n#include \"buildstepspage.h\"\n#include \"project.h\"\n#include \"projectexplorerconstants.h\"\n#include \"target.h\"\n#include \"buildconfiguration.h\"\n#include \"buildconfigurationmodel.h\"\n\n#include <coreplugin\/coreconstants.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcassert.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <projectexplorer\/buildmanager.h>\n\n#include <QMargins>\n#include <QTimer>\n#include <QCoreApplication>\n#include <QComboBox>\n#include <QInputDialog>\n#include <QLabel>\n#include <QMenu>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QVBoxLayout>\n\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\n\n\/\/\/\n\/\/ BuildSettingsPanelFactory\n\/\/\/\n\nQString BuildSettingsPanelFactory::id() const\n{\n return QLatin1String(BUILDSETTINGS_PANEL_ID);\n}\n\nQString BuildSettingsPanelFactory::displayName() const\n{\n return QCoreApplication::translate(\"BuildSettingsPanelFactory\", \"Build Settings\");\n}\n\nint BuildSettingsPanelFactory::priority() const\n{\n return 10;\n}\n\nbool BuildSettingsPanelFactory::supports(Target *target)\n{\n return IBuildConfigurationFactory::find(target);\n}\n\nPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)\n{\n PropertiesPanel *panel = new PropertiesPanel;\n QWidget *w = new QWidget();\n QVBoxLayout *l = new QVBoxLayout(w);\n QWidget *b = new BuildSettingsWidget(target);\n l->addWidget(b);\n l->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));\n l->setContentsMargins(QMargins());\n panel->setWidget(w);\n panel->setIcon(QIcon(QLatin1String(\":\/projectexplorer\/images\/BuildSettings.png\")));\n panel->setDisplayName(QCoreApplication::translate(\"BuildSettingsPanel\", \"Build Settings\"));\n return panel;\n}\n\n\/\/\/\n\/\/ BuildSettingsWidget\n\/\/\/\n\nBuildSettingsWidget::~BuildSettingsWidget()\n{\n clear();\n}\n\nBuildSettingsWidget::BuildSettingsWidget(Target *target) :\n m_target(target),\n m_buildConfiguration(0)\n{\n Q_ASSERT(m_target);\n\n QVBoxLayout *vbox = new QVBoxLayout(this);\n vbox->setContentsMargins(0, 0, 0, 0);\n\n if (!IBuildConfigurationFactory::find(m_target)) {\n QLabel *noSettingsLabel = new QLabel(this);\n noSettingsLabel->setText(tr(\"No build settings available\"));\n QFont f = noSettingsLabel->font();\n f.setPointSizeF(f.pointSizeF() * 1.2);\n noSettingsLabel->setFont(f);\n vbox->addWidget(noSettingsLabel);\n return;\n }\n\n { \/\/ Edit Build Configuration row\n QHBoxLayout *hbox = new QHBoxLayout();\n hbox->setContentsMargins(0, 0, 0, 0);\n hbox->addWidget(new QLabel(tr(\"Edit build configuration:\"), this));\n m_buildConfigurationComboBox = new QComboBox(this);\n m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);\n m_buildConfigurationComboBox->setModel(new BuildConfigurationModel(m_target, this));\n hbox->addWidget(m_buildConfigurationComboBox);\n\n m_addButton = new QPushButton(this);\n m_addButton->setText(tr(\"Add\"));\n m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_addButton);\n m_addButtonMenu = new QMenu(this);\n m_addButton->setMenu(m_addButtonMenu);\n\n m_removeButton = new QPushButton(this);\n m_removeButton->setText(tr(\"Remove\"));\n m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_removeButton);\n\n m_renameButton = new QPushButton(this);\n m_renameButton->setText(tr(\"Rename...\"));\n m_renameButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n hbox->addWidget(m_renameButton);\n\n hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));\n vbox->addLayout(hbox);\n }\n\n m_buildConfiguration = m_target->activeBuildConfiguration();\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n m_buildConfigurationComboBox->setCurrentIndex(model->indexFor(m_buildConfiguration).row());\n\n updateAddButtonMenu();\n updateBuildSettings();\n\n connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),\n this, SLOT(currentIndexChanged(int)));\n\n connect(m_removeButton, SIGNAL(clicked()),\n this, SLOT(deleteConfiguration()));\n\n connect(m_renameButton, SIGNAL(clicked()),\n this, SLOT(renameConfiguration()));\n\n connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),\n this, SLOT(updateActiveConfiguration()));\n\n connect(m_target, SIGNAL(kitChanged()), this, SLOT(updateAddButtonMenu()));\n}\n\nvoid BuildSettingsWidget::addSubWidget(BuildConfigWidget *widget)\n{\n widget->setContentsMargins(0, 10, 0, 0);\n\n QLabel *label = new QLabel(this);\n label->setText(widget->displayName());\n connect(widget, SIGNAL(displayNameChanged(QString)),\n label, SLOT(setText(QString)));\n QFont f = label->font();\n f.setBold(true);\n f.setPointSizeF(f.pointSizeF() * 1.2);\n label->setFont(f);\n\n label->setContentsMargins(0, 10, 0, 0);\n\n layout()->addWidget(label);\n layout()->addWidget(widget);\n\n m_labels.append(label);\n m_subWidgets.append(widget);\n}\n\nvoid BuildSettingsWidget::clear()\n{\n qDeleteAll(m_subWidgets);\n m_subWidgets.clear();\n qDeleteAll(m_labels);\n m_labels.clear();\n}\n\nQList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const\n{\n return m_subWidgets;\n}\n\nvoid BuildSettingsWidget::updateAddButtonMenu()\n{\n m_addButtonMenu->clear();\n if (m_target) {\n if (m_target->activeBuildConfiguration()) {\n m_addButtonMenu->addAction(tr(\"&Clone Selected\"),\n this, SLOT(cloneConfiguration()));\n }\n IBuildConfigurationFactory * factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n foreach (Core::Id id, factory->availableCreationIds(m_target)) {\n QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));\n action->setData(QVariant::fromValue(id));\n }\n }\n}\n\nvoid BuildSettingsWidget::updateBuildSettings()\n{\n clear();\n\n \/\/ update buttons\n m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);\n\n if (!m_buildConfiguration)\n return;\n\n \/\/ Add pages\n BuildConfigWidget *generalConfigWidget = m_buildConfiguration->createConfigWidget();\n addSubWidget(generalConfigWidget);\n\n addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_BUILD)));\n addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_CLEAN)));\n\n QList<BuildConfigWidget *> subConfigWidgets = m_buildConfiguration->createSubConfigWidgets();\n foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)\n addSubWidget(subConfigWidget);\n\n foreach (BuildConfigWidget *widget, subWidgets())\n widget->init(m_buildConfiguration);\n}\n\nvoid BuildSettingsWidget::currentIndexChanged(int index)\n{\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n BuildConfiguration *buildConfiguration = model->buildConfigurationAt(index);\n m_target->setActiveBuildConfiguration(buildConfiguration);\n}\n\nvoid BuildSettingsWidget::updateActiveConfiguration()\n{\n if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())\n return;\n\n m_buildConfiguration = m_target->activeBuildConfiguration();\n\n BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());\n m_buildConfigurationComboBox->setCurrentIndex(model->indexFor(m_buildConfiguration).row());\n\n updateBuildSettings();\n}\n\nvoid BuildSettingsWidget::createConfiguration()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n Core::Id id = action->data().value<Core::Id>();\n\n IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n\n BuildConfiguration *bc = factory->create(m_target, id);\n if (!bc)\n return;\n\n m_target->addBuildConfiguration(bc);\n\n QTC_CHECK(bc->id() == id);\n m_target->setActiveBuildConfiguration(bc);\n}\n\nvoid BuildSettingsWidget::cloneConfiguration()\n{\n cloneConfiguration(m_buildConfiguration);\n}\n\nvoid BuildSettingsWidget::deleteConfiguration()\n{\n deleteConfiguration(m_buildConfiguration);\n}\n\nQString BuildSettingsWidget::uniqueName(const QString & name)\n{\n QString result = name.trimmed();\n if (!result.isEmpty()) {\n QStringList bcNames;\n foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {\n if (bc == m_buildConfiguration)\n continue;\n bcNames.append(bc->displayName());\n }\n result = Project::makeUnique(result, bcNames);\n }\n return result;\n}\n\nvoid BuildSettingsWidget::renameConfiguration()\n{\n bool ok;\n QString name = QInputDialog::getText(this, tr(\"Rename...\"),\n tr(\"New name for build configuration <b>%1<\/b>:\").\n arg(m_buildConfiguration->displayName()),\n QLineEdit::Normal,\n m_buildConfiguration->displayName(), &ok);\n if (!ok)\n return;\n\n name = uniqueName(name);\n if (name.isEmpty())\n return;\n\n m_buildConfiguration->setDisplayName(name);\n\n}\n\nvoid BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)\n{\n if (!sourceConfiguration)\n return;\n IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);\n if (!factory)\n return;\n\n \/\/: Title of a the cloned BuildConfiguration window, text of the window\n QString name = uniqueName(QInputDialog::getText(this, tr(\"Clone Configuration\"), tr(\"New configuration name:\")));\n if (name.isEmpty())\n return;\n\n BuildConfiguration *bc = factory->clone(m_target, sourceConfiguration);\n if (!bc)\n return;\n\n bc->setDisplayName(name);\n m_target->addBuildConfiguration(bc);\n m_target->setActiveBuildConfiguration(bc);\n}\n\nvoid BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)\n{\n if (!deleteConfiguration ||\n m_target->buildConfigurations().size() <= 1)\n return;\n\n ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();\n if (bm->isBuilding(deleteConfiguration)) {\n QMessageBox box;\n QPushButton *closeAnyway = box.addButton(tr(\"Cancel Build && Remove Build Configuration\"), QMessageBox::AcceptRole);\n QPushButton *cancelClose = box.addButton(tr(\"Do Not Remove\"), QMessageBox::RejectRole);\n box.setDefaultButton(cancelClose);\n box.setWindowTitle(tr(\"Remove Build Configuration %1?\").arg(deleteConfiguration->displayName()));\n box.setText(tr(\"The build configuration <b>%1<\/b> is currently being built.\").arg(deleteConfiguration->displayName()));\n box.setInformativeText(tr(\"Do you want to cancel the build process and remove the Build Configuration anyway?\"));\n box.exec();\n if (box.clickedButton() != closeAnyway)\n return;\n bm->cancel();\n } else {\n QMessageBox msgBox(QMessageBox::Question, tr(\"Remove Build Configuration?\"),\n tr(\"Do you really want to delete build configuration <b>%1<\/b>?\").arg(deleteConfiguration->displayName()),\n QMessageBox::Yes|QMessageBox::No, this);\n msgBox.setDefaultButton(QMessageBox::No);\n msgBox.setEscapeButton(QMessageBox::No);\n if (msgBox.exec() == QMessageBox::No)\n return;\n }\n\n m_target->removeBuildConfiguration(deleteConfiguration);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlmodelview.h\"\n#include \"qmlobjectnode.h\"\n#include \"qmlitemnode.h\"\n#include \"itemlibraryinfo.h\"\n#include \"modelutilities.h\"\n#include \"mathutils.h\"\n#include <QDir>\n#include <QFileInfo>\n#include <QDebug>\n\nnamespace QmlDesigner {\n\nQmlModelView::QmlModelView(QObject *parent)\n : ForwardView<NodeInstanceView>(parent)\n{\n NodeInstanceView *nodeInstanceView = new NodeInstanceView(this);\n nodeInstanceView->setQmlModelView(this);\n appendView(nodeInstanceView);\n}\n\nvoid QmlModelView::setCurrentState(const QmlModelState &state)\n{\n if (!state.isValid())\n return;\n\n emitCustomNotification(\"__state changed__\", QList<ModelNode>() << state.modelNode());\n}\n\nQmlModelState QmlModelView::currentState() const\n{\n return m_state;\n}\n\nQmlModelState QmlModelView::baseState() const\n{\n return QmlModelState::createBaseState(this);\n}\n\nQmlObjectNode QmlModelView::createQmlObjectNode(const QString &typeString,\n int majorVersion,\n int minorVersion,\n const PropertyListType &propertyList)\n{\n return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));\n}\n\nQmlItemNode QmlModelView::createQmlItemNode(const QString &typeString,\n int majorVersion,\n int minorVersion,\n const PropertyListType &propertyList)\n{\n return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();\n}\n\nQmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)\n{\n if (!parentNode.isValid())\n parentNode = rootQmlItemNode();\n\n if (!parentNode.isValid())\n return QmlItemNode();\n\n QmlItemNode newNode;\n RewriterTransaction transaction = beginRewriterTransaction();\n {\n QList<QPair<QString, QVariant> > propertyPairList;\n propertyPairList.append(qMakePair(QString(\"x\"), QVariant( round(position.x(), 4))));\n propertyPairList.append(qMakePair(QString(\"y\"), QVariant( round(position.y(), 4))));\n\n QString relativeImageName = imageName;\n\n \/\/use relative path\n if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {\n QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());\n relativeImageName = fileDir.relativeFilePath(imageName);\n }\n\n propertyPairList.append(qMakePair(QString(\"source\"), QVariant(relativeImageName)));\n newNode = createQmlItemNode(\"Qt\/Image\",4, 7, propertyPairList);\n parentNode.nodeAbstractProperty(\"data\").reparentHere(newNode);\n\n Q_ASSERT(newNode.isValid());\n\n QString id;\n int i = 1;\n QString name(\"image\");\n name.remove(QLatin1Char(' '));\n do {\n id = name + QString::number(i);\n i++;\n } while (hasId(id)); \/\/If the name already exists count upwards\n\n newNode.setId(id);\n if (!currentState().isBaseState()) {\n newNode.modelNode().variantProperty(\"visible\") = false;\n newNode.setVariantProperty(\"visible\", true);\n }\n\n Q_ASSERT(newNode.isValid());\n }\n\n Q_ASSERT(newNode.isValid());\n\n return newNode;\n}\n\nQmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)\n{\n if (!parentNode.isValid())\n parentNode = rootQmlItemNode();\n\n Q_ASSERT(parentNode.isValid());\n\n\n QmlItemNode newNode;\n RewriterTransaction transaction = beginRewriterTransaction();\n {\n QList<QPair<QString, QVariant> > propertyPairList;\n propertyPairList.append(qMakePair(QString(\"x\"), QVariant(round(position.x(), 4))));\n propertyPairList.append(qMakePair(QString(\"y\"), QVariant(round(position.y(), 4))));\n\n foreach (const PropertyContainer &property, itemLibraryEntry.properties())\n propertyPairList.append(qMakePair(property.name(), property.value()));\n\n newNode = createQmlItemNode(itemLibraryEntry.typeName(), itemLibraryEntry.majorVersion(), itemLibraryEntry.minorVersion(), propertyPairList);\n parentNode.nodeAbstractProperty(\"data\").reparentHere(newNode);\n\n Q_ASSERT(newNode.isValid());\n\n QString id;\n int i = 1;\n QString name(itemLibraryEntry.name().toLower());\n name.remove(QLatin1Char(' '));\n do {\n id = name + QString::number(i);\n i++;\n } while (hasId(id)); \/\/If the name already exists count upwards\n\n newNode.setId(id);\n if (!currentState().isBaseState()) {\n newNode.modelNode().variantProperty(\"visible\") = false;\n newNode.setVariantProperty(\"visible\", true);\n }\n\n Q_ASSERT(newNode.isValid());\n }\n\n Q_ASSERT(newNode.isValid());\n\n return newNode;\n}\n\nQmlObjectNode QmlModelView::rootQmlObjectNode() const\n{\n return QmlObjectNode(rootModelNode());\n}\n\nQmlItemNode QmlModelView::rootQmlItemNode() const\n{\n return rootQmlObjectNode().toQmlItemNode();\n}\n\nvoid QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)\n{\n setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));\n}\n\nvoid QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)\n{\n selectModelNode(node.modelNode());\n}\n\nvoid QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)\n{\n deselectModelNode(node.modelNode());\n}\n\nQList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const\n{\n return toQmlObjectNodeList(selectedModelNodes());\n}\n\nQList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const\n{\n return toQmlItemNodeList(selectedModelNodes());\n}\n\nvoid QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)\n{\n return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));\n}\n\nQmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)\n{\n return QmlObjectNode(modelNodeForId(id));\n}\n\nvoid QmlModelView::customNotification(const AbstractView * \/* view *\/, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> & \/* data *\/)\n{\n if (identifier == \"__state changed__\") {\n QmlModelState state(nodeList.first());\n if (state.isValid())\n activateState(state);\n else\n activateState(baseState());\n }\n}\n\nNodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)\n{\n return nodeInstanceView()->instanceForNode(modelNode);\n}\n\nbool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)\n{\n return nodeInstanceView()->hasInstanceForNode(modelNode);\n}\n\nNodeInstanceView *QmlModelView::nodeInstanceView() const\n{\n return firstView();\n}\n\nvoid QmlModelView::modelAttached(Model *model)\n{\n m_state = QmlModelState();\n ForwardView<NodeInstanceView>::modelAttached(model);\n m_state = baseState();\n Q_ASSERT(m_state.isBaseState());\n}\n\nvoid QmlModelView::modelAboutToBeDetached(Model *model)\n{\n ForwardView<NodeInstanceView>::modelAboutToBeDetached(model);\n m_state = QmlModelState();\n}\n\nstatic bool isTransformProperty(const QString &name)\n{\n static QStringList transformProperties(QStringList() << \"x\"\n << \"y\"\n << \"width\"\n << \"height\"\n << \"z\"\n << \"rotation\"\n << \"scale\"\n << \"transformOrigin\");\n\n return transformProperties.contains(name);\n}\n\nvoid QmlModelView::nodeInstancePropertyChanged(const ModelNode &node, const QString &propertyName)\n{\n\n QmlObjectNode qmlObjectNode(node);\n\n if (!qmlObjectNode.isValid())\n return;\n\n if (isTransformProperty(propertyName))\n transformChanged(qmlObjectNode, propertyName);\n else if (propertyName == \"parent\")\n parentChanged(qmlObjectNode);\n else if (propertyName == \"state\")\n changeToState(node, qmlObjectNode.instanceValue(propertyName).toString());\n else\n otherPropertyChanged(qmlObjectNode, propertyName);\n}\n\nvoid QmlModelView::activateState(const QmlModelState &state)\n{\n if (!state.isValid())\n return;\n\n if (m_state == state)\n return;\n\n QmlModelState oldState = m_state;\n\n NodeInstance newStateInstance = instanceForModelNode(state.modelNode());\n\n if (state.isBaseState()) {\n nodeInstanceView()->activateBaseState();\n } else {\n nodeInstanceView()->activateState(newStateInstance);\n }\n}\n\nvoid QmlModelView::changeToState(const ModelNode &node, const QString &stateName)\n{\n QmlItemNode itemNode(node);\n\n QmlModelState newState;\n if (stateName.isEmpty())\n newState = baseState();\n else\n newState = itemNode.states().state(stateName);\n\n QmlModelState oldState = m_state;\n\n if (newState.isValid() && oldState != newState) {\n m_state = newState;\n stateChanged(newState, oldState);\n }\n}\n\n\nvoid QmlModelView::transformChanged(const QmlObjectNode &\/*qmlObjectNode*\/, const QString &\/*propertyName*\/)\n{\n}\n\nvoid QmlModelView::parentChanged(const QmlObjectNode &\/*qmlObjectNode*\/)\n{\n}\n\nvoid QmlModelView::otherPropertyChanged(const QmlObjectNode &\/*qmlObjectNode*\/, const QString &\/*propertyName*\/)\n{\n}\n\nvoid QmlModelView::stateChanged(const QmlModelState &\/*newQmlModelState*\/, const QmlModelState &\/*oldQmlModelState*\/)\n{\n}\n\n} \/\/QmlDesigner\n<commit_msg>QuickDesigner: Fix Drag&Drop with items from different directories<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlmodelview.h\"\n#include \"qmlobjectnode.h\"\n#include \"qmlitemnode.h\"\n#include \"itemlibraryinfo.h\"\n#include \"modelutilities.h\"\n#include \"mathutils.h\"\n#include \"invalididexception.h\"\n#include <QDir>\n#include <QFileInfo>\n#include <QDebug>\n#include <QMessageBox>\n\nnamespace QmlDesigner {\n\nQmlModelView::QmlModelView(QObject *parent)\n : ForwardView<NodeInstanceView>(parent)\n{\n NodeInstanceView *nodeInstanceView = new NodeInstanceView(this);\n nodeInstanceView->setQmlModelView(this);\n appendView(nodeInstanceView);\n}\n\nvoid QmlModelView::setCurrentState(const QmlModelState &state)\n{\n if (!state.isValid())\n return;\n\n emitCustomNotification(\"__state changed__\", QList<ModelNode>() << state.modelNode());\n}\n\nQmlModelState QmlModelView::currentState() const\n{\n return m_state;\n}\n\nQmlModelState QmlModelView::baseState() const\n{\n return QmlModelState::createBaseState(this);\n}\n\nQmlObjectNode QmlModelView::createQmlObjectNode(const QString &typeString,\n int majorVersion,\n int minorVersion,\n const PropertyListType &propertyList)\n{\n return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));\n}\n\nQmlItemNode QmlModelView::createQmlItemNode(const QString &typeString,\n int majorVersion,\n int minorVersion,\n const PropertyListType &propertyList)\n{\n return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();\n}\n\nQmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)\n{\n if (!parentNode.isValid())\n parentNode = rootQmlItemNode();\n\n if (!parentNode.isValid())\n return QmlItemNode();\n\n QmlItemNode newNode;\n RewriterTransaction transaction = beginRewriterTransaction();\n {\n QList<QPair<QString, QVariant> > propertyPairList;\n propertyPairList.append(qMakePair(QString(\"x\"), QVariant( round(position.x(), 4))));\n propertyPairList.append(qMakePair(QString(\"y\"), QVariant( round(position.y(), 4))));\n\n QString relativeImageName = imageName;\n\n \/\/use relative path\n if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {\n QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());\n relativeImageName = fileDir.relativeFilePath(imageName);\n }\n\n propertyPairList.append(qMakePair(QString(\"source\"), QVariant(relativeImageName)));\n newNode = createQmlItemNode(\"Qt\/Image\",4, 7, propertyPairList);\n parentNode.nodeAbstractProperty(\"data\").reparentHere(newNode);\n\n Q_ASSERT(newNode.isValid());\n\n QString id;\n int i = 1;\n QString name(\"image\");\n name.remove(QLatin1Char(' '));\n do {\n id = name + QString::number(i);\n i++;\n } while (hasId(id)); \/\/If the name already exists count upwards\n\n newNode.setId(id);\n if (!currentState().isBaseState()) {\n newNode.modelNode().variantProperty(\"visible\") = false;\n newNode.setVariantProperty(\"visible\", true);\n }\n\n Q_ASSERT(newNode.isValid());\n }\n\n Q_ASSERT(newNode.isValid());\n\n return newNode;\n}\n\nQmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)\n{\n if (!parentNode.isValid())\n parentNode = rootQmlItemNode();\n\n Q_ASSERT(parentNode.isValid());\n\n\n QmlItemNode newNode;\n RewriterTransaction transaction = beginRewriterTransaction();\n {\n QList<QPair<QString, QVariant> > propertyPairList;\n propertyPairList.append(qMakePair(QString(\"x\"), QVariant(round(position.x(), 4))));\n propertyPairList.append(qMakePair(QString(\"y\"), QVariant(round(position.y(), 4))));\n\n foreach (const PropertyContainer &property, itemLibraryEntry.properties())\n propertyPairList.append(qMakePair(property.name(), property.value()));\n\n newNode = createQmlItemNode(itemLibraryEntry.typeName(), itemLibraryEntry.majorVersion(), itemLibraryEntry.minorVersion(), propertyPairList);\n parentNode.nodeAbstractProperty(\"data\").reparentHere(newNode);\n\n Q_ASSERT(newNode.isValid());\n\n QString id;\n int i = 1;\n QString name(itemLibraryEntry.name().toLower());\n \/\/remove forbidden characters\n name.replace(QRegExp(QLatin1String(\"[^a-zA-Z0-9_]\")), QLatin1String(\"_\"));\n do {\n id = name + QString::number(i);\n i++;\n } while (hasId(id)); \/\/If the name already exists count upwards\n\n try {\n newNode.setId(id);\n } catch (InvalidIdException &e) {\n \/\/ should never happen\n QMessageBox::warning(0, tr(\"Invalid Id\"), e.description());\n }\n\n if (!currentState().isBaseState()) {\n newNode.modelNode().variantProperty(\"visible\") = false;\n newNode.setVariantProperty(\"visible\", true);\n }\n\n Q_ASSERT(newNode.isValid());\n }\n\n Q_ASSERT(newNode.isValid());\n\n return newNode;\n}\n\nQmlObjectNode QmlModelView::rootQmlObjectNode() const\n{\n return QmlObjectNode(rootModelNode());\n}\n\nQmlItemNode QmlModelView::rootQmlItemNode() const\n{\n return rootQmlObjectNode().toQmlItemNode();\n}\n\nvoid QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)\n{\n setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));\n}\n\nvoid QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)\n{\n selectModelNode(node.modelNode());\n}\n\nvoid QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)\n{\n deselectModelNode(node.modelNode());\n}\n\nQList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const\n{\n return toQmlObjectNodeList(selectedModelNodes());\n}\n\nQList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const\n{\n return toQmlItemNodeList(selectedModelNodes());\n}\n\nvoid QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)\n{\n return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));\n}\n\nQmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)\n{\n return QmlObjectNode(modelNodeForId(id));\n}\n\nvoid QmlModelView::customNotification(const AbstractView * \/* view *\/, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> & \/* data *\/)\n{\n if (identifier == \"__state changed__\") {\n QmlModelState state(nodeList.first());\n if (state.isValid())\n activateState(state);\n else\n activateState(baseState());\n }\n}\n\nNodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)\n{\n return nodeInstanceView()->instanceForNode(modelNode);\n}\n\nbool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)\n{\n return nodeInstanceView()->hasInstanceForNode(modelNode);\n}\n\nNodeInstanceView *QmlModelView::nodeInstanceView() const\n{\n return firstView();\n}\n\nvoid QmlModelView::modelAttached(Model *model)\n{\n m_state = QmlModelState();\n ForwardView<NodeInstanceView>::modelAttached(model);\n m_state = baseState();\n Q_ASSERT(m_state.isBaseState());\n}\n\nvoid QmlModelView::modelAboutToBeDetached(Model *model)\n{\n ForwardView<NodeInstanceView>::modelAboutToBeDetached(model);\n m_state = QmlModelState();\n}\n\nstatic bool isTransformProperty(const QString &name)\n{\n static QStringList transformProperties(QStringList() << \"x\"\n << \"y\"\n << \"width\"\n << \"height\"\n << \"z\"\n << \"rotation\"\n << \"scale\"\n << \"transformOrigin\");\n\n return transformProperties.contains(name);\n}\n\nvoid QmlModelView::nodeInstancePropertyChanged(const ModelNode &node, const QString &propertyName)\n{\n\n QmlObjectNode qmlObjectNode(node);\n\n if (!qmlObjectNode.isValid())\n return;\n\n if (isTransformProperty(propertyName))\n transformChanged(qmlObjectNode, propertyName);\n else if (propertyName == \"parent\")\n parentChanged(qmlObjectNode);\n else if (propertyName == \"state\")\n changeToState(node, qmlObjectNode.instanceValue(propertyName).toString());\n else\n otherPropertyChanged(qmlObjectNode, propertyName);\n}\n\nvoid QmlModelView::activateState(const QmlModelState &state)\n{\n if (!state.isValid())\n return;\n\n if (m_state == state)\n return;\n\n QmlModelState oldState = m_state;\n\n NodeInstance newStateInstance = instanceForModelNode(state.modelNode());\n\n if (state.isBaseState()) {\n nodeInstanceView()->activateBaseState();\n } else {\n nodeInstanceView()->activateState(newStateInstance);\n }\n}\n\nvoid QmlModelView::changeToState(const ModelNode &node, const QString &stateName)\n{\n QmlItemNode itemNode(node);\n\n QmlModelState newState;\n if (stateName.isEmpty())\n newState = baseState();\n else\n newState = itemNode.states().state(stateName);\n\n QmlModelState oldState = m_state;\n\n if (newState.isValid() && oldState != newState) {\n m_state = newState;\n stateChanged(newState, oldState);\n }\n}\n\n\nvoid QmlModelView::transformChanged(const QmlObjectNode &\/*qmlObjectNode*\/, const QString &\/*propertyName*\/)\n{\n}\n\nvoid QmlModelView::parentChanged(const QmlObjectNode &\/*qmlObjectNode*\/)\n{\n}\n\nvoid QmlModelView::otherPropertyChanged(const QmlObjectNode &\/*qmlObjectNode*\/, const QString &\/*propertyName*\/)\n{\n}\n\nvoid QmlModelView::stateChanged(const QmlModelState &\/*newQmlModelState*\/, const QmlModelState &\/*oldQmlModelState*\/)\n{\n}\n\n} \/\/QmlDesigner\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Dennis Goldfarb on 9\/28\/16.\n\/\/\n\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include <OpenMS\/CHEMISTRY\/AASequence.h>\n#include <OpenMS\/CHEMISTRY\/ResidueDB.h>\n#include <OpenMS\/CHEMISTRY\/ElementDB.h>\n\n\nstatic const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();\nstatic const OpenMS::ElementDB* elementDB = OpenMS::ElementDB::getInstance();\n\nstatic std::string AMINO_ACIDS = \"ADEFGHIKLNPQRSTVWY\";\nstatic std::string AMINO_ACIDS_SULFUR = \"CM\";\nstatic std::string AMINO_ACIDS_SELENIUM = \"U\";\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_int_distribution<> dis_AA(0, AMINO_ACIDS.length()-1);\nstd::uniform_int_distribution<> dis_S(0, AMINO_ACIDS_SULFUR.length()-1);\n\nint max_depth;\n\nOpenMS::AASequence create_random_peptide_sequence(int peptide_length, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n OpenMS::AASequence random_peptide;\n\n \/\/ for insertion of sulfur containing amino acids in fragment\n for (int i = 0; i < num_sulfurs; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_S(gen)]);\n }\n\n \/\/ for insertion of selenocysteines in fragment\n for (int i = 0; i < num_selenium; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SELENIUM[0]);\n }\n\n \/\/ random amino acid insertion (non Sulfur and Selenium amino acids)\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS[dis_AA(gen)]);\n }\n\n \/\/ for insertion of sulfur containing amino acids in fragment\n for (int i = 0; i < num_c_sulfurs; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_S(gen)]);\n }\n\n \/\/ for insertion of selenocysteines in fragment\n for (int i = 0; i < num_c_selenium; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SELENIUM[0]);\n }\n\n\n return random_peptide;\n}\n\nvoid create_fragments(OpenMS::AASequence &p, std::ofstream** outfiles, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n int num_fragments = p.size()-1;\n\n int tot_left_SSe = std::max(num_sulfurs + num_selenium,1);\n int tot_right_SSe = std::max(num_c_sulfurs + num_c_selenium,1);\n\n OpenMS::EmpiricalFormula precursor_ef = p.getFormula();\n\n for (int index = tot_left_SSe; index < num_fragments-tot_right_SSe; ++index)\n {\n OpenMS::EmpiricalFormula b_ion = p.getPrefix(index).getFormula(OpenMS::Residue::ResidueType::BIon);\n OpenMS::EmpiricalFormula y_ion = p.getPrefix(index).getFormula(OpenMS::Residue::ResidueType::YIon);\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n std::vector<OpenMS::UInt> isolated_isotopes;\n isolated_isotopes.push_back(precursor_isotope);\n\n OpenMS::IsotopeDistribution b_id = b_ion.getConditionalFragmentIsotopeDist(precursor_ef, isolated_isotopes);\n OpenMS::IsotopeDistribution y_id = y_ion.getConditionalFragmentIsotopeDist(precursor_ef, isolated_isotopes);\n\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope && fragment_isotope < b_id.size(); ++fragment_isotope)\n {\n outfiles[precursor_isotope][fragment_isotope] << b_id.getContainer()[fragment_isotope].second\n << \"\\t\" << b_ion.getMonoWeight()\n << \"\\t\" << p.getMonoWeight() << std::endl;\n outfiles[precursor_isotope][fragment_isotope] << y_id.getContainer()[fragment_isotope].second\n << \"\\t\" << y_ion.getMonoWeight()\n << \"\\t\" << p.getMonoWeight() << std::endl;\n }\n }\n }\n}\n\n\nvoid sample_fragment_isotopic_distributions(std::string base_path, float max_mass, int num_samples, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n\n \/\/ create all output files and write header to each\n std::ofstream** outfiles = new std::ofstream*[max_depth];\n for (int precursor_isotope = 1; precursor_isotope < max_depth; ++precursor_isotope) {\n outfiles[precursor_isotope] = new std::ofstream[max_depth];\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope; ++fragment_isotope) {\n std::string filename = \"Precursor\" + std::to_string(precursor_isotope) + \"_\" +\n \"Fragment\" + std::to_string(fragment_isotope) + \".tab\";\n outfiles[precursor_isotope][fragment_isotope].open(base_path + filename);\n\n outfiles[precursor_isotope][fragment_isotope] << \"probability\" << \"\\tfrag.mass\" << \"\\tprecursor.mass\" << std::endl; \/\/\"\\tfrag.a.mass\" << \"\\tprecursor.a.mass\" << std::endl;\n }\n }\n\n int max_length = max_mass\/100;\n\n for (int peptide_length = 0; peptide_length <= max_length; ++peptide_length) {\n\n for (int sample = 0; sample < num_samples; ++sample) {\n\n OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, num_sulfurs, num_c_sulfurs,\n num_selenium, num_c_selenium);\n\n if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass) {\n create_fragments(random_sequence, outfiles, num_sulfurs, num_c_sulfurs, num_selenium, num_c_selenium);\n }\n }\n\n }\n\n \/\/ close all output files\n for (int precursor_isotope = 1; precursor_isotope < max_depth; ++precursor_isotope) {\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope; ++fragment_isotope) {\n outfiles[precursor_isotope][fragment_isotope].close();\n }\n delete[] outfiles[precursor_isotope];\n }\n delete[] outfiles;\n}\n\nvoid usage()\n{\n std::cout << \"PeptideFragmentSampler out_path max_mass num_samples S CS Se CSe max_isotope\" << std::endl;\n std::cout << \"out_path: The path to the directory that will store the training data, e.g. ~\/data\/\" << std::endl;\n std::cout << \"max_mass: maximum mass allowed for sampled peptides, e.g. 8500\" << std::endl;\n std::cout << \"num_samples: number of random peptides to generate for each peptide length, e.g 100\" << std::endl;\n std::cout << \"S: number of sulfurs that should be in the fragment ion, e.g. 0\" << std::endl;\n std::cout << \"CS: number of sulfurs that should be in the complementary fragment ion, e.g. 0\" << std::endl;\n std::cout << \"Se: number of seleniums that should be in the fragment ion, e.g. 0\" << std::endl;\n std::cout << \"CSe: number of seleniums that should be in the complementary fragment ion, e.g. 0\" << std::endl;\n std::cout << \"max_isotope: The maximum isotope to generate training data for, e.g. 5\" << std::endl;\n}\n\nint main(int argc, const char ** argv) {\n\n if (argc != 8)\n {\n usage();\n }\n\n \/\/ Increase the maximum number of open files for this process. Was necessary for me.\n struct rlimit rlp;\n rlp.rlim_cur = 600;\n setrlimit(RLIMIT_NOFILE, &rlp);\n\n max_depth = atoi(argv[8])+1;\n sample_fragment_isotopic_distributions(argv[1], atof(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), atoi(argv[7]));\n\n return 0;\n}<commit_msg>had the number of command line arguments wrong<commit_after>\/\/\n\/\/ Created by Dennis Goldfarb on 9\/28\/16.\n\/\/\n\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include <OpenMS\/CHEMISTRY\/AASequence.h>\n#include <OpenMS\/CHEMISTRY\/ResidueDB.h>\n#include <OpenMS\/CHEMISTRY\/ElementDB.h>\n\n\nstatic const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();\nstatic const OpenMS::ElementDB* elementDB = OpenMS::ElementDB::getInstance();\n\nstatic std::string AMINO_ACIDS = \"ADEFGHIKLNPQRSTVWY\";\nstatic std::string AMINO_ACIDS_SULFUR = \"CM\";\nstatic std::string AMINO_ACIDS_SELENIUM = \"U\";\n\nstd::random_device rd;\nstd::mt19937 gen(rd());\nstd::uniform_int_distribution<> dis_AA(0, AMINO_ACIDS.length()-1);\nstd::uniform_int_distribution<> dis_S(0, AMINO_ACIDS_SULFUR.length()-1);\n\nint max_depth;\n\nOpenMS::AASequence create_random_peptide_sequence(int peptide_length, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n OpenMS::AASequence random_peptide;\n\n \/\/ for insertion of sulfur containing amino acids in fragment\n for (int i = 0; i < num_sulfurs; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_S(gen)]);\n }\n\n \/\/ for insertion of selenocysteines in fragment\n for (int i = 0; i < num_selenium; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SELENIUM[0]);\n }\n\n \/\/ random amino acid insertion (non Sulfur and Selenium amino acids)\n for (int aa_index = 0; aa_index < peptide_length; ++aa_index) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS[dis_AA(gen)]);\n }\n\n \/\/ for insertion of sulfur containing amino acids in fragment\n for (int i = 0; i < num_c_sulfurs; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[dis_S(gen)]);\n }\n\n \/\/ for insertion of selenocysteines in fragment\n for (int i = 0; i < num_c_selenium; ++i) {\n random_peptide += residueDB->getResidue(AMINO_ACIDS_SELENIUM[0]);\n }\n\n\n return random_peptide;\n}\n\nvoid create_fragments(OpenMS::AASequence &p, std::ofstream** outfiles, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n int num_fragments = p.size()-1;\n\n int tot_left_SSe = std::max(num_sulfurs + num_selenium,1);\n int tot_right_SSe = std::max(num_c_sulfurs + num_c_selenium,1);\n\n OpenMS::EmpiricalFormula precursor_ef = p.getFormula();\n\n for (int index = tot_left_SSe; index < num_fragments-tot_right_SSe; ++index)\n {\n OpenMS::EmpiricalFormula b_ion = p.getPrefix(index).getFormula(OpenMS::Residue::ResidueType::BIon);\n OpenMS::EmpiricalFormula y_ion = p.getPrefix(index).getFormula(OpenMS::Residue::ResidueType::YIon);\n\n for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)\n {\n std::vector<OpenMS::UInt> isolated_isotopes;\n isolated_isotopes.push_back(precursor_isotope);\n\n OpenMS::IsotopeDistribution b_id = b_ion.getConditionalFragmentIsotopeDist(precursor_ef, isolated_isotopes);\n OpenMS::IsotopeDistribution y_id = y_ion.getConditionalFragmentIsotopeDist(precursor_ef, isolated_isotopes);\n\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope && fragment_isotope < b_id.size(); ++fragment_isotope)\n {\n outfiles[precursor_isotope][fragment_isotope] << b_id.getContainer()[fragment_isotope].second\n << \"\\t\" << b_ion.getMonoWeight()\n << \"\\t\" << p.getMonoWeight() << std::endl;\n outfiles[precursor_isotope][fragment_isotope] << y_id.getContainer()[fragment_isotope].second\n << \"\\t\" << y_ion.getMonoWeight()\n << \"\\t\" << p.getMonoWeight() << std::endl;\n }\n }\n }\n}\n\n\nvoid sample_fragment_isotopic_distributions(std::string base_path, float max_mass, int num_samples, int num_sulfurs, int num_c_sulfurs, int num_selenium, int num_c_selenium) {\n\n \/\/ create all output files and write header to each\n std::ofstream** outfiles = new std::ofstream*[max_depth];\n for (int precursor_isotope = 1; precursor_isotope < max_depth; ++precursor_isotope) {\n outfiles[precursor_isotope] = new std::ofstream[max_depth];\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope; ++fragment_isotope) {\n std::string filename = \"Precursor\" + std::to_string(precursor_isotope) + \"_\" +\n \"Fragment\" + std::to_string(fragment_isotope) + \".tab\";\n outfiles[precursor_isotope][fragment_isotope].open(base_path + filename);\n\n outfiles[precursor_isotope][fragment_isotope] << \"probability\" << \"\\tfrag.mass\" << \"\\tprecursor.mass\" << std::endl; \/\/\"\\tfrag.a.mass\" << \"\\tprecursor.a.mass\" << std::endl;\n }\n }\n\n int max_length = max_mass\/100;\n\n for (int peptide_length = 0; peptide_length <= max_length; ++peptide_length) {\n\n for (int sample = 0; sample < num_samples; ++sample) {\n\n OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, num_sulfurs, num_c_sulfurs,\n num_selenium, num_c_selenium);\n\n if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass) {\n create_fragments(random_sequence, outfiles, num_sulfurs, num_c_sulfurs, num_selenium, num_c_selenium);\n }\n }\n\n }\n\n \/\/ close all output files\n for (int precursor_isotope = 1; precursor_isotope < max_depth; ++precursor_isotope) {\n for (int fragment_isotope = 0; fragment_isotope <= precursor_isotope; ++fragment_isotope) {\n outfiles[precursor_isotope][fragment_isotope].close();\n }\n delete[] outfiles[precursor_isotope];\n }\n delete[] outfiles;\n}\n\nvoid usage()\n{\n std::cout << \"PeptideFragmentSampler out_path max_mass num_samples S CS Se CSe max_isotope\" << std::endl;\n std::cout << \"out_path: The path to the directory that will store the training data, e.g. ~\/data\/\" << std::endl;\n std::cout << \"max_mass: maximum mass allowed for sampled peptides, e.g. 8500\" << std::endl;\n std::cout << \"num_samples: number of random peptides to generate for each peptide length, e.g 100\" << std::endl;\n std::cout << \"S: number of sulfurs that should be in the fragment ion, e.g. 0\" << std::endl;\n std::cout << \"CS: number of sulfurs that should be in the complementary fragment ion, e.g. 0\" << std::endl;\n std::cout << \"Se: number of seleniums that should be in the fragment ion, e.g. 0\" << std::endl;\n std::cout << \"CSe: number of seleniums that should be in the complementary fragment ion, e.g. 0\" << std::endl;\n std::cout << \"max_isotope: The maximum isotope to generate training data for, e.g. 5\" << std::endl;\n}\n\nint main(int argc, const char ** argv) {\n\n if (argc != 9)\n {\n usage();\n }\n\n \/\/ Increase the maximum number of open files for this process. Was necessary for me.\n struct rlimit rlp;\n rlp.rlim_cur = 600;\n setrlimit(RLIMIT_NOFILE, &rlp);\n\n max_depth = atoi(argv[8])+1;\n sample_fragment_isotopic_distributions(argv[1], atof(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), atoi(argv[7]));\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/***\nCreated by: Veer Shubhranshu Shrivastav\nMail: veer@veershubhranshu.com\nCopyright: Veer S. Shrivastav\n\nSQLHelper version1.0\n\nSQLHelper - SelectDBExample.cpp\n\nIn this file, I am trying to show you how to use Multiple connection\nwith the database. this is one of the best way to use this library \nfor creating multiple connection. Somehow, there may be some memory error\nwhich is yet to be sorted. You can use this library for your use to create multiple\nconnections.\n\n**Note:\n If you look closely at the structure\n of program you will find that I have\n declared the two databases but have\n not opened it without use. When you\n open a database, the previous connection\n is lost. Good part in this is you don't \n need to explicitely close the connection.\n It is handled automatically.\n\n**Suggestion:\n Try to use this library with only one database.\n If you need to access another database, try to use\n synonyms in that case. \n\n Do not switch database unnecessarily. It is a\n good habbit to fetch data just from one table.\n Else it can result in massive outputs.\n\nThis program works in following manner:\n\n1. Connection to databases are declared BUT NOT CONNECTED.\n\n2. Under try-catch block the connection is opened for first database.\n\n3. Value is fetched and used.\n\n4. Again when the other SQLHelper Object makes a connection, the previous\n connection is closed and the connection is re-written over the\n previous connection pointer.\n\n5. Again the Data is fetched from the newly connected database.\n\n**Explanation:\n SQLHelper can make multiple connection, however it holds one\n connection at a time. That is, when you will write a normal\n program, before connecting to the database, you have to disconnect\n from the current database being used.\n\n Here you don't need to bother about closing the connection.\n It is handled automatically. Just create the new connection and\n it will close the previous connection.\n\n You can think it another way also, you can hold only one connection\n at a time, when using Oracle Database - sqlplus. To make another \n connection you have to open a new SSH connection to the server over\n new window.\n\n****\/\n#include<iostream>\n#include<vector>\nusing namespace std;\n#include \"..\/..\/SQLHelper\/SQLHelper.h\"\n#include \"..\/..\/SQLHelperException\/SQLHelperException.h\"\n\nint main()\n{\n SQLHelper DB(\"scott@unixdb\",\"tiger\");\n SQLHelper DB2(\"veer@unixdb\",\"Veer\");\n vector< vector<string> > rowData;\n try\n {\n DB.openDB();\n if(DB.checkDBStatus())\n {\n cout<<\"connected\"<<endl;\n }\n rowData=DB.selectDB(\"select * from veer_date\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j)<<\"\\t\";\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n\n DB2.openDB(); \n rowData = DB2.selectDB(\"select to_char(sysdate) from dual\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j);\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n DB.openDB();\n rowData=DB.selectDB(\"select * from veer_date\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j)<<\"\\t\";\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n\n }\n catch(SQLHelperException sqlExp)\n {\n cout<<sqlExp.getExceptionString()<<endl;\n }\n\treturn 0;\n}\n\n<commit_msg>Update MultipleConnection.cpp<commit_after>\/***\nCreated by: Veer Shubhranshu Shrivastav\nMail: veer@veershubhranshu.com\nCopyright: Veer S. Shrivastav\n\nSQLHelper version1.0\n\nSQLHelper - MultipleConnection.cpp\n\nIn this file, I am trying to show you how to use Multiple connection\nwith the database. this is one of the best way to use this library \nfor creating multiple connection. Somehow, there may be some memory error\nwhich is yet to be sorted. You can use this library for your use to create multiple\nconnections.\n\n**Note:\n If you look closely at the structure\n of program you will find that I have\n declared the two databases but have\n not opened it without use. When you\n open a database, the previous connection\n is lost. Good part in this is you don't \n need to explicitely close the connection.\n It is handled automatically.\n\n**Suggestion:\n Try to use this library with only one database.\n If you need to access another database, try to use\n synonyms in that case. \n\n Do not switch database unnecessarily. It is a\n good habbit to fetch data just from one table.\n Else it can result in massive outputs.\n\nThis program works in following manner:\n\n1. Connection to databases are declared BUT NOT CONNECTED.\n\n2. Under try-catch block the connection is opened for first database.\n\n3. Value is fetched and used.\n\n4. Again when the other SQLHelper Object makes a connection, the previous\n connection is closed and the connection is re-written over the\n previous connection pointer.\n\n5. Again the Data is fetched from the newly connected database.\n\n**Explanation:\n SQLHelper can make multiple connection, however it holds one\n connection at a time. That is, when you will write a normal\n program, before connecting to the database, you have to disconnect\n from the current database being used.\n\n Here you don't need to bother about closing the connection.\n It is handled automatically. Just create the new connection and\n it will close the previous connection.\n\n You can think it another way also, you can hold only one connection\n at a time, when using Oracle Database - sqlplus. To make another \n connection you have to open a new SSH connection to the server over\n new window.\n\n****\/\n#include<iostream>\n#include<vector>\nusing namespace std;\n#include \"..\/..\/SQLHelper\/SQLHelper.h\"\n#include \"..\/..\/SQLHelperException\/SQLHelperException.h\"\n\nint main()\n{\n SQLHelper DB(\"scott@unixdb\",\"tiger\");\n SQLHelper DB2(\"veer@unixdb\",\"Veer\");\n vector< vector<string> > rowData;\n try\n {\n DB.openDB();\n if(DB.checkDBStatus())\n {\n cout<<\"connected\"<<endl;\n }\n rowData=DB.selectDB(\"select * from veer_date\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j)<<\"\\t\";\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n\n DB2.openDB(); \n rowData = DB2.selectDB(\"select to_char(sysdate) from dual\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j);\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n DB.openDB();\n rowData=DB.selectDB(\"select * from veer_date\");\n if(rowData.size()>0)\n {\n for(int i=0;i<rowData.size();i++)\n {\n for(int j=0;j<rowData.at(i).size();j++)\n {\n cout<<rowData.at(i).at(j)<<\"\\t\";\n }\n cout<<endl;\n }\n }\n else\n {\n cout<<\"No rows fetched\"<<endl;\n }\n\n }\n catch(SQLHelperException sqlExp)\n {\n cout<<sqlExp.getExceptionString()<<endl;\n }\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_training_adv.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2017,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_mss_draminit_training_adv.C\n\/\/\/ @brief Perform read_centering again but with a custom pattern for better eye\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n#include <vector>\n\n#include <p9_mss_draminit_training_adv.H>\n#include <lib\/utils\/count_dimm.H>\n#include <lib\/shared\/mss_const.H>\n#include <lib\/phy\/dp16.H>\n#include <lib\/phy\/seq.H>\n#include <lib\/phy\/ddr_phy.H>\n#include <lib\/phy\/mss_training.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n\/\/\/\n\/\/\/ @brief Perform training_adv on the dimms (perform read centering with custom pattern)\n\/\/\/ @param[in] i_target, the McBIST of the ports of the dram you're training\n\/\/\/ @param[in] i_abort_on_error, optional CAL_ABORT_ON_ERROR override. Used in sim, debug\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/ @note turn off rd cntr periodic cal if training_adv is run. Add OFF value for CUSTOM_PATTERN?\n\/\/\/\n\n fapi2::ReturnCode p9_mss_draminit_training_adv( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,\n const uint8_t i_abort_on_error)\n {\n uint8_t l_cal_abort_on_error = i_abort_on_error;\n uint8_t l_sim = 0;\n FAPI_TRY( mss::is_simulation (l_sim) );\n\n FAPI_INF(\"Start draminit training advance %s\", mss::c_str(i_target));\n\n \/\/ If there are no DIMMs installed, we don't need to bother. In fact, we can't as we didn't setup\n \/\/ attributes for the PHY, etc.\n if (mss::count_dimm(i_target) == 0 || l_sim)\n {\n FAPI_INF(\"... skipping draminit_training_adv %s... %s Dimms. %s SIM.\",\n mss::c_str(i_target),\n mss::count_dimm(i_target) == 0 ? \"Has no\" : \"Has\",\n l_sim ? \"Is\" : \"Is not\");\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n if (i_abort_on_error == CAL_ADV_ABORT_SENTINAL)\n {\n FAPI_TRY( mss::cal_abort_on_error(l_cal_abort_on_error) );\n }\n\n \/\/ If Custom Read Centering or Custom Write Centering was performed,\n \/\/ an Initial Pattern Write of 5555 hex, the reset value of the registers described in,\n \/\/ must be performed before any periodic calibration routines are performed.\n \/\/ Clean out any previous calibration results, set bad-bits and configure the ranks.\n for( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))\n {\n fapi2::buffer<uint32_t> l_cal_steps_enabled;\n std::vector<std::shared_ptr<mss::training::step>> l_steps;\n FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled), \"Error in p9_mss_draminit_training %s\", mss::c_str(i_target) );\n\n if (!l_cal_steps_enabled.getBit<mss::TRAINING_ADV>())\n {\n FAPI_INF(\"ATTR_MSS_CAL_STEPS_ENABLED says to skip draminit training advance, so skipping %s\",\n mss::c_str(i_target));\n continue;\n }\n\n \/\/ If we see the bit to for training_adv, let's set up our cal config.\n \/\/ As per the PHY spec, only INITIAL_PAT_WRITE and the CUSTOM_RD_PATTERN bits should be set\n \/\/ TRAINING_ADV == CUSTOM_RD_PATTERN\n l_cal_steps_enabled = 0;\n l_cal_steps_enabled.setBit<mss::INITIAL_PAT_WR>().setBit<mss::TRAINING_ADV>();\n\n \/\/ Gets the training steps to calibrate\n l_steps = mss::training::steps_factory(l_cal_steps_enabled, l_sim);\n\n \/\/ Keep track of the last error seen by a rank pair\n fapi2::ReturnCode l_rank_pair_error(fapi2::FAPI2_RC_SUCCESS);\n\n \/\/ Clear all of the errors before we start\n FAPI_TRY(mss::clear_initial_cal_errors(p), \"%s error resetting errors prior to init cal\", mss::c_str(p));\n\n \/\/ Returned from set_rank_pairs, it tells us how many rank pairs\n \/\/ we configured on this port.\n std::vector<uint64_t> l_pairs;\n\n \/\/ Let's set the pattern to run\n FAPI_TRY( mss::configure_custom_pattern(p) );\n\n \/\/ Set staggered mode\n FAPI_TRY( mss::rc::change_staggered_pattern(p) );\n\n \/\/ Set custom read centering mode\n FAPI_TRY( mss::dp16::setup_custom_read_centering_mode(p), \"Error in p9_mss_draminit_training %s\",\n mss::c_str(i_target) );\n\n \/\/ Get our rank pairs.\n FAPI_TRY( mss::rank::get_rank_pairs(p, l_pairs), \"Error in p9_mss_draminit_training\" );\n\n \/\/ For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.\n \/\/ NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE\n \/\/ THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.\n for (const auto& rp : l_pairs)\n {\n bool l_cal_fail = false;\n\n \/\/ Save off registers in case adv training fails\n mss::dp16::rd_ctr_settings<TARGET_TYPE_MCA> l_original_settings(p, rp);\n FAPI_TRY( l_original_settings.save() );\n\n std::vector<fapi2::ReturnCode> l_fails_on_rp;\n\n \/\/ Loop through all of the steps (should just be initial pattern write and custom read centering)\n for(const auto l_step : l_steps)\n {\n FAPI_TRY( l_step->execute(p, rp, l_cal_abort_on_error) );\n }\n\n FAPI_TRY( mss::find_and_log_cal_errors(p, rp, l_cal_abort_on_error, l_cal_fail, l_fails_on_rp) );\n\n \/\/ If we got a fail, let's ignore the previous fails and run backup pattern\n if (l_fails_on_rp.size() != 0)\n {\n l_cal_fail = false;\n l_fails_on_rp.clear();\n\n \/\/ Clear the disable bits from last run.\n \/\/ This function restores bad_bits to how the attribute has them\n \/\/ (which was updated at the end of regular training)\n \/\/ So we won't run on known bad bits, but will rerun on the iffy bits from last custom_pattern run\n FAPI_TRY( mss::dp16::reset_bad_bits( p ) );\n FAPI_INF(\"%s rp%x running back up pattern for draminit_training_adv\", mss::c_str(p), rp);\n\n \/\/ Clear the cal errors so we can retry\n FAPI_TRY(mss::clear_initial_cal_errors(p), \"%s error resetting errors prior to init cal\", mss::c_str(p));\n\n fapi2::buffer<uint32_t> l_backup;\n FAPI_TRY( mss::custom_training_adv_backup_patterns( p, l_backup) );\n\n \/\/ Put the backup into the registers\n FAPI_TRY( mss::seq::setup_rd_wr_data( p, l_backup) );\n\n \/\/ Rerun the training for this rp\n \/\/ Loop through all of the steps (should just be initial pattern write and custom read centering)\n for(const auto l_step : l_steps)\n {\n FAPI_TRY( l_step->execute(p, rp, l_cal_abort_on_error) );\n }\n\n FAPI_TRY( mss::find_and_log_cal_errors(p, rp, l_cal_abort_on_error, l_cal_fail, l_fails_on_rp) );\n\n \/\/ If we got fails from the backup pattern, restore the pre-adv training settings for this rank pair\n if (l_fails_on_rp.size() != 0)\n {\n l_fails_on_rp.clear();\n FAPI_INF(\"%s rp%d draminit_training_adv failed. Restoring original settings\", mss::c_str(p), rp);\n\n \/\/ Restore pre-training_adv settings\n FAPI_TRY( l_original_settings.restore() );\n }\n }\n }\/\/ rank pairs\n\n \/\/ Resetting current_err.\n \/\/ The error has either already been \"logged\" or we have exited and returned the error up the call stack.\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n }\n\n return fapi2::FAPI2_RC_SUCCESS;\n fapi_try_exit:\n return fapi2::current_err;\n }\n}\n<commit_msg>Updates training advanced and adds custom WR CTR<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_training_adv.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2017,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_mss_draminit_training_adv.C\n\/\/\/ @brief Perform read_centering again but with a custom pattern for better eye\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n#include <vector>\n\n#include <p9_mss_draminit_training_adv.H>\n#include <lib\/utils\/count_dimm.H>\n#include <lib\/shared\/mss_const.H>\n#include <lib\/phy\/dp16.H>\n#include <lib\/phy\/seq.H>\n#include <lib\/phy\/ddr_phy.H>\n#include <lib\/phy\/mss_training.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n\/\/\/\n\/\/\/ @brief Perform training_adv on the dimms (perform read centering with custom pattern)\n\/\/\/ @param[in] i_target, the McBIST of the ports of the dram you're training\n\/\/\/ @param[in] i_abort_on_error, optional CAL_ABORT_ON_ERROR override. Used in sim, debug\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/ @note turn off rd cntr periodic cal if training_adv is run. Add OFF value for CUSTOM_PATTERN?\n\/\/\/\n\n fapi2::ReturnCode p9_mss_draminit_training_adv( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,\n const uint8_t i_abort_on_error)\n {\n uint8_t l_cal_abort_on_error = i_abort_on_error;\n uint8_t l_sim = 0;\n FAPI_TRY( mss::is_simulation (l_sim) );\n\n FAPI_INF(\"Start draminit training advance %s\", mss::c_str(i_target));\n\n \/\/ If there are no DIMMs installed, we don't need to bother. In fact, we can't as we didn't setup\n \/\/ attributes for the PHY, etc.\n if (mss::count_dimm(i_target) == 0 || l_sim)\n {\n FAPI_INF(\"... skipping draminit_training_adv %s... %s Dimms. %s SIM.\",\n mss::c_str(i_target),\n mss::count_dimm(i_target) == 0 ? \"Has no\" : \"Has\",\n l_sim ? \"Is\" : \"Is not\");\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n if (i_abort_on_error == CAL_ADV_ABORT_SENTINAL)\n {\n FAPI_TRY( mss::cal_abort_on_error(l_cal_abort_on_error) );\n }\n\n \/\/ If Custom Read Centering or Custom Write Centering was performed,\n \/\/ an Initial Pattern Write of 5555 hex, the reset value of the registers described in,\n \/\/ must be performed before any periodic calibration routines are performed.\n \/\/ Clean out any previous calibration results, set bad-bits and configure the ranks.\n for( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))\n {\n fapi2::buffer<uint32_t> l_cal_steps_enabled;\n std::vector<std::shared_ptr<mss::training::step>> l_steps;\n FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled), \"Error in p9_mss_draminit_training %s\", mss::c_str(i_target) );\n\n if (!((l_cal_steps_enabled.getBit<mss::TRAINING_ADV_RD>()) || (l_cal_steps_enabled.getBit<mss::TRAINING_ADV_WR>())))\n {\n FAPI_INF(\"ATTR_MSS_CAL_STEPS_ENABLED says to skip draminit training advance, so skipping %s\",\n mss::c_str(i_target));\n continue;\n }\n\n \/\/ Clear all non training advanced bits\n l_cal_steps_enabled.clearBit<0, mss::TRAINING_ADV_RD>();\n\n \/\/ Gets the training steps to calibrate\n l_steps = mss::training::steps_factory(l_cal_steps_enabled, l_sim);\n\n \/\/ Keep track of the last error seen by a rank pair\n fapi2::ReturnCode l_rank_pair_error(fapi2::FAPI2_RC_SUCCESS);\n\n \/\/ Returned from set_rank_pairs, it tells us how many rank pairs\n \/\/ we configured on this port.\n std::vector<uint64_t> l_pairs;\n\n \/\/ Get our rank pairs.\n FAPI_TRY( mss::rank::get_rank_pairs(p, l_pairs), \"Error in p9_mss_draminit_training\" );\n\n \/\/ For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.\n \/\/ NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE\n \/\/ THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.\n for (const auto& rp : l_pairs)\n {\n \/\/ Loop through all of the steps (should just be initial pattern write and custom read centering)\n for(const auto l_step : l_steps)\n {\n FAPI_TRY( l_step->execute(p, rp, l_cal_abort_on_error) );\n }\n }\/\/ rank pairs\n\n \/\/ Resetting current_err.\n \/\/ The error has either already been \"logged\" or we have exited and returned the error up the call stack.\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n }\n\n return fapi2::FAPI2_RC_SUCCESS;\n fapi_try_exit:\n return fapi2::current_err;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This software is distributed under BSD 3-clause license (see LICENSE file).\n *\n * Authors: Saurabh Mahindre, Soumyajit De, Thoralf Klein, Heiko Strathmann,\n * Viktor Gal\n *\/\n\n#include <algorithm>\n#include <gtest\/gtest.h>\n#include <numeric>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/mathematics\/RandomNamespace.h>\n#include <shogun\/mathematics\/UniformIntDistribution.h>\n#include <shogun\/mathematics\/NormalDistribution.h>\n#include <shogun\/lib\/View.h>\n\n#include <random>\n\nnamespace shogun\n{\n\nclass DenseFeaturesMock : public DenseFeatures<float64_t>\n{\npublic:\n\tDenseFeaturesMock(const SGMatrix<float64_t>& data) : DenseFeatures<float64_t>(data)\n\t{\n\t}\n\n\tvoid copy_feature_matrix_public(const SGMatrix<float64_t>& target, index_t column_offset)\n\t{\n\t\tcopy_feature_matrix(target, column_offset);\n\t}\n};\n\n}\n\nusing namespace shogun;\n\nTEST(DenseFeaturesTest,create_merged_copy)\n{\n\t\/* create two matrices, feature objects for them, call create_merged_copy,\n\t * and check if it worked *\/\n\tint32_t seed = 10;\n\tindex_t n_1=3;\n\tindex_t n_2=4;\n\tindex_t dim=2;\n\n\tSGMatrix<float64_t> data_1(dim,n_1);\n\tfor (index_t i=0; i<dim*n_1; ++i)\n\t\tdata_1.matrix[i]=i;\n\n\t\/\/data_1.display_matrix(\"data_1\");\n\tstd::mt19937_64 prng(seed);\n\tNormalDistribution<float64_t> normal_dist;\n\tSGMatrix<float64_t> data_2(dim,n_2);\n\tfor (index_t i=0; i<dim*n_2; ++i)\n\t\tdata_2.matrix[i]=normal_dist(prng);\n\n\t\/\/data_2.display_matrix(\"data_2\");\n\n\tauto features_1=std::make_shared<DenseFeatures<float64_t>>(data_1);\n\tauto features_2=std::make_shared<DenseFeatures<float64_t>>(data_2);\n\n\tauto concatenation=features_1->create_merged_copy(features_2);\n\n\tSGMatrix<float64_t> concat_data=\n\t\t\tconcatenation->as<DenseFeatures<float64_t>>()->get_feature_matrix();\n\t\/\/concat_data.display_matrix(\"concat_data\");\n\n\t\/* check for equality with data_1 *\/\n\tfor (index_t i=0; i<dim*n_1; ++i)\n\t\tEXPECT_EQ(data_1.matrix[i], concat_data.matrix[i]);\n\n\t\/* check for equality with data_2 *\/\n\tfor (index_t i=0; i<dim*n_2; ++i)\n\t\tEXPECT_NEAR(data_2.matrix[i], concat_data.matrix[n_1*dim+i], 1E-15);\n\n\n\n\n}\n\nTEST(DenseFeaturesTest, create_merged_copy_with_subsets)\n{\n\tconst index_t n_1=10;\n\tconst index_t n_2=15;\n\tconst index_t dim=2;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data_1(dim, n_1);\n\tstd::iota(data_1.matrix, data_1.matrix + data_1.size(), 1);\n\n\tSGMatrix<float64_t> data_2(dim, n_2);\n\tstd::iota(data_2.matrix, data_2.matrix + data_2.size(), data_2.size());\n\n\tauto features_1=std::make_shared<DenseFeatures<float64_t> >(data_1);\n\tauto features_2=std::make_shared<DenseFeatures<float64_t> >(data_2);\n\n\tSGVector<index_t> subset_1(n_1\/2);\n\trandom::fill_array(subset_1, 0, n_1-1, prng);\n\tfeatures_1->add_subset(subset_1);\n\tauto active_data_1=features_1->get_feature_matrix();\n\n\tSGVector<index_t> subset_2(n_2\/3);\n\trandom::fill_array(subset_2, 0, n_2-1, prng);\n\tfeatures_2->add_subset(subset_2);\n\tauto active_data_2=features_2->get_feature_matrix();\n\n\tSGMatrix<float64_t> expected_merged_mat(dim, active_data_1.num_cols+active_data_2.num_cols);\n\tstd::copy(active_data_1.matrix, active_data_1.matrix+active_data_1.size(),\n\t\t\texpected_merged_mat.matrix);\n\tstd::copy(active_data_2.matrix, active_data_2.matrix+active_data_2.size(),\n\t\t\texpected_merged_mat.matrix+active_data_1.size());\n\n\tauto merged=features_1->create_merged_copy(features_2)->as<DenseFeatures<float64_t>>();\n\tSGMatrix<float64_t> merged_mat = merged->get_feature_matrix();\n\n\tASSERT_EQ(expected_merged_mat.num_rows, merged_mat.num_rows);\n\tASSERT_EQ(expected_merged_mat.num_cols, merged_mat.num_cols);\n\tfor (index_t j=0; j<expected_merged_mat.num_cols; ++j)\n\t{\n\t\tfor (index_t i=0; i<expected_merged_mat.num_rows; ++i)\n\t\t\tEXPECT_NEAR(expected_merged_mat(i, j), merged_mat(i, j), 1E-15);\n\t}\n\n}\n\nTEST(DenseFeaturesTest, copy_dimension_subset)\n{\n\tint32_t seed = 12;\n\tindex_t dim=5;\n\tindex_t n=10;\n\n\tSGMatrix<float64_t> data(dim, n);\n\tfor (index_t i=0; i<dim*n; ++i)\n\t\tdata.matrix[i]=i;\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tSGVector<index_t> dims(dim\/2);\n\tstd::mt19937_64 prng(seed);\n\tUniformIntDistribution<int32_t> uniform_int_dist;\n\tfor (index_t i=0; i<dims.vlen; ++i)\n\t\tdims[i]=uniform_int_dist(prng, {0, dim-1});\n\n\tauto f_reduced=\n\t\tfeatures->copy_dimension_subset(dims)->as<DenseFeatures<float64_t>>();\n\n\tSGMatrix<float64_t> data_reduced=f_reduced->get_feature_matrix();\n\n\tfor (index_t i=0; i<data_reduced.num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<data_reduced.num_cols; ++j)\n\t\t\tEXPECT_NEAR(data(dims[i], j), data_reduced(i, j), 1E-16);\n\t}\n\n\n\n}\n\nTEST(DenseFeaturesTest, copy_dimension_subset_with_subsets)\n{\n\tint32_t seed = 12;\n\tindex_t dim=5;\n\tindex_t n=10;\n\n\tSGMatrix<float64_t> data(dim, n);\n\tfor (index_t i=0; i<dim*n; ++i)\n\t\tdata.matrix[i]=i;\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tstd::mt19937_64 prng(seed);\n\tUniformIntDistribution<int32_t> uniform_int_dist;\n\tSGVector<index_t> inds(n\/2);\n\tfor (index_t i=0; i<inds.vlen; ++i)\n\t\tinds[i]=uniform_int_dist(prng, {0, n-1});\n\n\tfeatures->add_subset(inds);\n\n\tSGVector<index_t> dims(dim\/2);\n\tfor (index_t i=0; i<dims.vlen; ++i)\n\t\tdims[i]=uniform_int_dist(prng, {0, dim-1});\n\n\tauto f_reduced=\n\t\tfeatures->copy_dimension_subset(dims)->as<DenseFeatures<float64_t>>();\n\n\tSGMatrix<float64_t> data_reduced=f_reduced->get_feature_matrix();\n\tfor (index_t i=0; i<data_reduced.num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<data_reduced.num_cols; ++j)\n\t\t\tEXPECT_NEAR(data(dims[i], inds[j]), data_reduced(i, j), 1E-16);\n\t}\n\n\n\n}\n\nTEST(DenseFeaturesTest, shallow_copy_subset_data)\n{\n\tindex_t dim=5;\n\tindex_t n=10;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data(dim, n);\n\tstd::iota(data.data(), data.data()+data.size(), 1);\n\tSGVector<index_t> inds(n\/2);\n\trandom::fill_array(inds, 0, n-1, prng);\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\tfeatures->add_subset(inds);\n\tauto features_copy = features->shallow_subset_copy();\n\n\tSGMatrix<float64_t> orig_matrix=features->get_feature_matrix();\n\tSGMatrix<float64_t> copy_matrix=features_copy->as<DenseFeatures<float64_t>>()->get_feature_matrix();\n\n\n\tfor (index_t i=0; i<dim; ++i)\n\t{\n\t\tfor (index_t j=0; j<inds.size(); ++j)\n\t\t\tEXPECT_NEAR(orig_matrix(i,j), copy_matrix(i,j), 1E-15);\n\t}\n\n}\n\nTEST(DenseFeaturesTest, copy_feature_matrix)\n{\n\tindex_t dim=5;\n\tindex_t n=10;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data(dim, n);\n\tstd::iota(data.data(), data.data()+data.size(), 1);\n\tSGVector<index_t> inds(n\/2);\n\trandom::fill_array(inds, 0, n-1, prng);\n\n\tauto features=std::make_shared<DenseFeaturesMock>(data);\n\tfeatures->add_subset(inds);\n\n\tindex_t offset=3;\n\tSGMatrix<float64_t> copy(dim, inds.vlen+offset);\n\tauto data_ptr=copy.matrix;\n\tstd::fill(copy.data(), copy.data()+copy.size(), 0);\n\tfeatures->copy_feature_matrix_public(copy, offset);\n\n\tASSERT_EQ(copy.num_rows, dim);\n\tASSERT_EQ(copy.num_cols, inds.vlen+offset);\n\tASSERT_EQ(copy.matrix, data_ptr);\n\n\tfor (index_t j=0; j<offset; ++j)\n\t{\n\t\tfor (index_t i=0; i<dim; ++i)\n\t\t\tEXPECT_NEAR(copy(i, j), 0, 1E-15);\n\t}\n\n\tfor (index_t j=0; j<inds.vlen; ++j)\n\t{\n\t\tfor (index_t i=0; i<dim; ++i)\n\t\t\tEXPECT_NEAR(copy(i, j+offset), data(i, inds[j]), 1E-15);\n\t}\n}\n\nTEST(DenseFeaturesTest, view)\n{\n\tauto num_feats = 2;\n\tauto num_vectors = 4;\n\tSGMatrix<float64_t> data(num_feats, num_vectors);\n\n\tfor (auto i : range(num_feats * num_vectors))\n\t{\n\t\tdata[i] = i;\n\t}\n\tauto feats_original = std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tSGVector<index_t> subset1{0, 2, 3};\n\tauto feats_subset1 = view(feats_original, subset1);\n\tASSERT_EQ(feats_subset1->get_num_features(), num_feats);\n\tASSERT_EQ(feats_subset1->get_num_vectors(), subset1.vlen);\n\tauto feature_matrix_subset1 = feats_subset1->get_feature_matrix();\n\n\t\/\/ check feature_matrix(i, j) == feature_matrix_original(i, subset(j))\n\tfor (auto j : range(subset1.vlen))\n\t{\n\t\tfor (auto i : range(num_feats))\n\t\t\tEXPECT_EQ(feature_matrix_subset1(i, j), data(i, subset1[j]));\n\t}\n\n\tSGVector<index_t> subset2{\n\t 0, 2}; \/\/ subset2 is column 0 & 3 of original features\n\tauto feats_subset2 = view(feats_subset1, subset2);\n\tASSERT_EQ(feats_subset2->get_num_features(), num_feats);\n\tASSERT_EQ(feats_subset2->get_num_vectors(), subset2.vlen);\n\tauto feature_matrix_subset2 = feats_subset2->get_feature_matrix();\n\n\tfor (auto j : range(subset2.size()))\n\t{\n\t\tfor (auto i : range(num_feats))\n\t\t\tEXPECT_EQ(\n\t\t\t feature_matrix_subset2(i, j), data(i, subset1[subset2[j]]));\n\t}\n}\n<commit_msg>dense features iterator tests<commit_after>\/*\n * This software is distributed under BSD 3-clause license (see LICENSE file).\n *\n * Authors: Saurabh Mahindre, Soumyajit De, Thoralf Klein, Heiko Strathmann,\n * Viktor Gal\n *\/\n\n#include <algorithm>\n#include <gtest\/gtest.h>\n#include <numeric>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/mathematics\/RandomNamespace.h>\n#include <shogun\/mathematics\/UniformIntDistribution.h>\n#include <shogun\/mathematics\/NormalDistribution.h>\n#include <shogun\/lib\/View.h>\n\n#include <random>\n\nnamespace shogun\n{\n\nclass DenseFeaturesMock : public DenseFeatures<float64_t>\n{\npublic:\n\tDenseFeaturesMock(const SGMatrix<float64_t>& data) : DenseFeatures<float64_t>(data)\n\t{\n\t}\n\n\tvoid copy_feature_matrix_public(const SGMatrix<float64_t>& target, index_t column_offset)\n\t{\n\t\tcopy_feature_matrix(target, column_offset);\n\t}\n};\n\n}\n\nusing namespace shogun;\n\nTEST(DenseFeaturesTest,create_merged_copy)\n{\n\t\/* create two matrices, feature objects for them, call create_merged_copy,\n\t * and check if it worked *\/\n\tint32_t seed = 10;\n\tindex_t n_1=3;\n\tindex_t n_2=4;\n\tindex_t dim=2;\n\n\tSGMatrix<float64_t> data_1(dim,n_1);\n\tfor (index_t i=0; i<dim*n_1; ++i)\n\t\tdata_1.matrix[i]=i;\n\n\t\/\/data_1.display_matrix(\"data_1\");\n\tstd::mt19937_64 prng(seed);\n\tNormalDistribution<float64_t> normal_dist;\n\tSGMatrix<float64_t> data_2(dim,n_2);\n\tfor (index_t i=0; i<dim*n_2; ++i)\n\t\tdata_2.matrix[i]=normal_dist(prng);\n\n\t\/\/data_2.display_matrix(\"data_2\");\n\n\tauto features_1=std::make_shared<DenseFeatures<float64_t>>(data_1);\n\tauto features_2=std::make_shared<DenseFeatures<float64_t>>(data_2);\n\n\tauto concatenation=features_1->create_merged_copy(features_2);\n\n\tSGMatrix<float64_t> concat_data=\n\t\t\tconcatenation->as<DenseFeatures<float64_t>>()->get_feature_matrix();\n\t\/\/concat_data.display_matrix(\"concat_data\");\n\n\t\/* check for equality with data_1 *\/\n\tfor (index_t i=0; i<dim*n_1; ++i)\n\t\tEXPECT_EQ(data_1.matrix[i], concat_data.matrix[i]);\n\n\t\/* check for equality with data_2 *\/\n\tfor (index_t i=0; i<dim*n_2; ++i)\n\t\tEXPECT_NEAR(data_2.matrix[i], concat_data.matrix[n_1*dim+i], 1E-15);\n\n\n\n\n}\n\nTEST(DenseFeaturesTest, create_merged_copy_with_subsets)\n{\n\tconst index_t n_1=10;\n\tconst index_t n_2=15;\n\tconst index_t dim=2;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data_1(dim, n_1);\n\tstd::iota(data_1.matrix, data_1.matrix + data_1.size(), 1);\n\n\tSGMatrix<float64_t> data_2(dim, n_2);\n\tstd::iota(data_2.matrix, data_2.matrix + data_2.size(), data_2.size());\n\n\tauto features_1=std::make_shared<DenseFeatures<float64_t> >(data_1);\n\tauto features_2=std::make_shared<DenseFeatures<float64_t> >(data_2);\n\n\tSGVector<index_t> subset_1(n_1\/2);\n\trandom::fill_array(subset_1, 0, n_1-1, prng);\n\tfeatures_1->add_subset(subset_1);\n\tauto active_data_1=features_1->get_feature_matrix();\n\n\tSGVector<index_t> subset_2(n_2\/3);\n\trandom::fill_array(subset_2, 0, n_2-1, prng);\n\tfeatures_2->add_subset(subset_2);\n\tauto active_data_2=features_2->get_feature_matrix();\n\n\tSGMatrix<float64_t> expected_merged_mat(dim, active_data_1.num_cols+active_data_2.num_cols);\n\tstd::copy(active_data_1.matrix, active_data_1.matrix+active_data_1.size(),\n\t\t\texpected_merged_mat.matrix);\n\tstd::copy(active_data_2.matrix, active_data_2.matrix+active_data_2.size(),\n\t\t\texpected_merged_mat.matrix+active_data_1.size());\n\n\tauto merged=features_1->create_merged_copy(features_2)->as<DenseFeatures<float64_t>>();\n\tSGMatrix<float64_t> merged_mat = merged->get_feature_matrix();\n\n\tASSERT_EQ(expected_merged_mat.num_rows, merged_mat.num_rows);\n\tASSERT_EQ(expected_merged_mat.num_cols, merged_mat.num_cols);\n\tfor (index_t j=0; j<expected_merged_mat.num_cols; ++j)\n\t{\n\t\tfor (index_t i=0; i<expected_merged_mat.num_rows; ++i)\n\t\t\tEXPECT_NEAR(expected_merged_mat(i, j), merged_mat(i, j), 1E-15);\n\t}\n\n}\n\nTEST(DenseFeaturesTest, copy_dimension_subset)\n{\n\tint32_t seed = 12;\n\tindex_t dim=5;\n\tindex_t n=10;\n\n\tSGMatrix<float64_t> data(dim, n);\n\tfor (index_t i=0; i<dim*n; ++i)\n\t\tdata.matrix[i]=i;\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tSGVector<index_t> dims(dim\/2);\n\tstd::mt19937_64 prng(seed);\n\tUniformIntDistribution<int32_t> uniform_int_dist;\n\tfor (index_t i=0; i<dims.vlen; ++i)\n\t\tdims[i]=uniform_int_dist(prng, {0, dim-1});\n\n\tauto f_reduced=\n\t\tfeatures->copy_dimension_subset(dims)->as<DenseFeatures<float64_t>>();\n\n\tSGMatrix<float64_t> data_reduced=f_reduced->get_feature_matrix();\n\n\tfor (index_t i=0; i<data_reduced.num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<data_reduced.num_cols; ++j)\n\t\t\tEXPECT_NEAR(data(dims[i], j), data_reduced(i, j), 1E-16);\n\t}\n\n\n\n}\n\nTEST(DenseFeaturesTest, copy_dimension_subset_with_subsets)\n{\n\tint32_t seed = 12;\n\tindex_t dim=5;\n\tindex_t n=10;\n\n\tSGMatrix<float64_t> data(dim, n);\n\tfor (index_t i=0; i<dim*n; ++i)\n\t\tdata.matrix[i]=i;\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tstd::mt19937_64 prng(seed);\n\tUniformIntDistribution<int32_t> uniform_int_dist;\n\tSGVector<index_t> inds(n\/2);\n\tfor (index_t i=0; i<inds.vlen; ++i)\n\t\tinds[i]=uniform_int_dist(prng, {0, n-1});\n\n\tfeatures->add_subset(inds);\n\n\tSGVector<index_t> dims(dim\/2);\n\tfor (index_t i=0; i<dims.vlen; ++i)\n\t\tdims[i]=uniform_int_dist(prng, {0, dim-1});\n\n\tauto f_reduced=\n\t\tfeatures->copy_dimension_subset(dims)->as<DenseFeatures<float64_t>>();\n\n\tSGMatrix<float64_t> data_reduced=f_reduced->get_feature_matrix();\n\tfor (index_t i=0; i<data_reduced.num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<data_reduced.num_cols; ++j)\n\t\t\tEXPECT_NEAR(data(dims[i], inds[j]), data_reduced(i, j), 1E-16);\n\t}\n\n\n\n}\n\nTEST(DenseFeaturesTest, shallow_copy_subset_data)\n{\n\tindex_t dim=5;\n\tindex_t n=10;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data(dim, n);\n\tstd::iota(data.data(), data.data()+data.size(), 1);\n\tSGVector<index_t> inds(n\/2);\n\trandom::fill_array(inds, 0, n-1, prng);\n\n\tauto features=std::make_shared<DenseFeatures<float64_t>>(data);\n\tfeatures->add_subset(inds);\n\tauto features_copy = features->shallow_subset_copy();\n\n\tSGMatrix<float64_t> orig_matrix=features->get_feature_matrix();\n\tSGMatrix<float64_t> copy_matrix=features_copy->as<DenseFeatures<float64_t>>()->get_feature_matrix();\n\n\n\tfor (index_t i=0; i<dim; ++i)\n\t{\n\t\tfor (index_t j=0; j<inds.size(); ++j)\n\t\t\tEXPECT_NEAR(orig_matrix(i,j), copy_matrix(i,j), 1E-15);\n\t}\n\n}\n\nTEST(DenseFeaturesTest, copy_feature_matrix)\n{\n\tindex_t dim=5;\n\tindex_t n=10;\n\tstd::mt19937_64 prng(57);\n\n\tSGMatrix<float64_t> data(dim, n);\n\tstd::iota(data.data(), data.data()+data.size(), 1);\n\tSGVector<index_t> inds(n\/2);\n\trandom::fill_array(inds, 0, n-1, prng);\n\n\tauto features=std::make_shared<DenseFeaturesMock>(data);\n\tfeatures->add_subset(inds);\n\n\tindex_t offset=3;\n\tSGMatrix<float64_t> copy(dim, inds.vlen+offset);\n\tauto data_ptr=copy.matrix;\n\tstd::fill(copy.data(), copy.data()+copy.size(), 0);\n\tfeatures->copy_feature_matrix_public(copy, offset);\n\n\tASSERT_EQ(copy.num_rows, dim);\n\tASSERT_EQ(copy.num_cols, inds.vlen+offset);\n\tASSERT_EQ(copy.matrix, data_ptr);\n\n\tfor (index_t j=0; j<offset; ++j)\n\t{\n\t\tfor (index_t i=0; i<dim; ++i)\n\t\t\tEXPECT_NEAR(copy(i, j), 0, 1E-15);\n\t}\n\n\tfor (index_t j=0; j<inds.vlen; ++j)\n\t{\n\t\tfor (index_t i=0; i<dim; ++i)\n\t\t\tEXPECT_NEAR(copy(i, j+offset), data(i, inds[j]), 1E-15);\n\t}\n}\n\nTEST(DenseFeaturesTest, view)\n{\n\tauto num_feats = 2;\n\tauto num_vectors = 4;\n\tSGMatrix<float64_t> data(num_feats, num_vectors);\n\n\tfor (auto i : range(num_feats * num_vectors))\n\t{\n\t\tdata[i] = i;\n\t}\n\tauto feats_original = std::make_shared<DenseFeatures<float64_t>>(data);\n\n\tSGVector<index_t> subset1{0, 2, 3};\n\tauto feats_subset1 = view(feats_original, subset1);\n\tASSERT_EQ(feats_subset1->get_num_features(), num_feats);\n\tASSERT_EQ(feats_subset1->get_num_vectors(), subset1.vlen);\n\tauto feature_matrix_subset1 = feats_subset1->get_feature_matrix();\n\n\t\/\/ check feature_matrix(i, j) == feature_matrix_original(i, subset(j))\n\tfor (auto j : range(subset1.vlen))\n\t{\n\t\tfor (auto i : range(num_feats))\n\t\t\tEXPECT_EQ(feature_matrix_subset1(i, j), data(i, subset1[j]));\n\t}\n\n\tSGVector<index_t> subset2{\n\t 0, 2}; \/\/ subset2 is column 0 & 3 of original features\n\tauto feats_subset2 = view(feats_subset1, subset2);\n\tASSERT_EQ(feats_subset2->get_num_features(), num_feats);\n\tASSERT_EQ(feats_subset2->get_num_vectors(), subset2.vlen);\n\tauto feature_matrix_subset2 = feats_subset2->get_feature_matrix();\n\n\tfor (auto j : range(subset2.size()))\n\t{\n\t\tfor (auto i : range(num_feats))\n\t\t\tEXPECT_EQ(\n\t\t\t feature_matrix_subset2(i, j), data(i, subset1[subset2[j]]));\n\t}\n}\n\nTEST(DenseFeaturesTest, iterator)\n{\n SGVector<float64_t> vals(20);\n vals.range_fill();\n auto mat = SGMatrix(vals, 5, 4);\n auto subset = SGVector{1,0,2,4,1,3,1,1,2};\n auto ordered_subset = SGVector{0,1,1,1,1,2,2,3,4};\n auto feat = some<CDenseFeatures<float64_t>>(mat);\n int counter = 0;\n feat->add_subset(subset);\n for (auto iter: *feat)\n {\n int i = 0;\n for (const auto& val: iter)\n {\n EXPECT_EQ(val, mat[ordered_subset[counter]*5+i]);\n i++;\n }\n counter++;\n }\n}\n\nTEST(DenseFeaturesTest, const_iterator)\n{\n SGVector<float64_t> vals(20);\n vals.range_fill();\n auto mat = SGMatrix(vals, 5, 4);\n const auto feat = some<CDenseFeatures<float64_t>>(mat);\n int counter = 0;\n for (const auto& iter: *feat)\n {\n for (int i = 0; i<5;++i)\n EXPECT_EQ(iter[i], mat[counter*5+i]);\n counter++;\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007-2012, Un Shyam & Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\n#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED\n#define TORRENT_PE_CRYPTO_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_USE_GCRYPT\n#include <gcrypt.h>\n#elif defined TORRENT_USE_OPENSSL\n#include <openssl\/rc4.h>\n#include <openssl\/evp.h>\n#include <openssl\/aes.h>\n#else\n\/\/ RC4 state from libtomcrypt\nstruct rc4 {\n\tint x, y;\n\tunsigned char buf[256];\n};\n\nvoid TORRENT_EXTRA_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state);\nunsigned long TORRENT_EXTRA_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state);\n#endif\n\n#include \"libtorrent\/peer_id.hpp\" \/\/ For sha1_hash\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tclass TORRENT_EXTRA_EXPORT dh_key_exchange\n\t{\n\tpublic:\n\t\tdh_key_exchange();\n\t\tbool good() const { return true; }\n\n\t\t\/\/ Get local public key, always 96 bytes\n\t\tchar const* get_local_key() const;\n\n\t\t\/\/ read remote_pubkey, generate and store shared secret in\n\t\t\/\/ m_dh_shared_secret.\n\t\tint compute_secret(const char* remote_pubkey);\n\n\t\tchar const* get_secret() const { return m_dh_shared_secret; }\n\n\t\tsha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }\n\t\t\n\tprivate:\n\n\t\tint get_local_key_size() const\n\t\t{ return sizeof(m_dh_local_key); }\n\n\t\tchar m_dh_local_key[96];\n\t\tchar m_dh_local_secret[96];\n\t\tchar m_dh_shared_secret[96];\n\t\tsha1_hash m_xor_mask;\n\t};\n\n\tstruct encryption_handler\n\t{\n\t\tvirtual void set_incoming_key(unsigned char const* key, int len) = 0;\n\t\tvirtual void set_outgoing_key(unsigned char const* key, int len) = 0;\n\t\tvirtual void encrypt(char* pos, int len) = 0;\n\t\tvirtual void decrypt(char* pos, int len) = 0;\n\t\tvirtual ~encryption_handler() {}\n\t};\n\n\tstruct rc4_handler : encryption_handler\n\t{\n\tpublic:\n\t\t\/\/ Input longkeys must be 20 bytes\n\t\trc4_handler()\n\t\t\t: m_encrypt(false)\n\t\t\t, m_decrypt(false)\n\t\t{\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n#endif\n\t\t};\n\n\t\tvoid set_incoming_key(unsigned char const* key, int len)\n\t\t{\n\t\t\tm_decrypt = true;\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_incoming);\n\t\t\tgcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_setkey(m_rc4_incoming, key, len);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4_set_key(&m_remote_key, len, key);\n#else\n\t\t\trc4_init(key, len, &m_rc4_incoming);\n#endif\n\t\t\t\/\/ Discard first 1024 bytes\n\t\t\tchar buf[1024];\n\t\t\tdecrypt(buf, 1024);\n\t\t}\n\t\t\n\t\tvoid set_outgoing_key(unsigned char const* key, int len)\n\t\t{\n\t\t\tm_encrypt = true;\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_outgoing);\n\t\t\tgcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_setkey(m_rc4_outgoing, key, len);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4_set_key(&m_local_key, len, key);\n#else\n\t\t\trc4_init(key, len, &m_rc4_outgoing);\n#endif\n\t\t\t\/\/ Discard first 1024 bytes\n\t\t\tchar buf[1024];\n\t\t\tencrypt(buf, 1024);\n\t\t}\n\t\t\n\t\t~rc4_handler()\n\t\t{\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_incoming);\n\t\t\tgcry_cipher_close(m_rc4_outgoing);\n#endif\n\t\t};\n\n\t\tvoid encrypt(char* pos, int len)\n\t\t{\n\t\t\tif (!m_encrypt) return;\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos);\n#else\n\t\t\trc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing);\n#endif\n\t\t}\n\n\t\tvoid decrypt(char* pos, int len)\n\t\t{\n\t\t\tif (!m_decrypt) return;\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos);\n#else\n\t\t\trc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming);\n#endif\n\t\t}\n\n\tprivate:\n#ifdef TORRENT_USE_GCRYPT\n\t\tgcry_cipher_hd_t m_rc4_incoming;\n\t\tgcry_cipher_hd_t m_rc4_outgoing;\n#elif defined TORRENT_USE_OPENSSL\n\t\tRC4_KEY m_local_key; \/\/ Key to encrypt outgoing data\n\t\tRC4_KEY m_remote_key; \/\/ Key to decrypt incoming data\n#else\n\t\trc4 m_rc4_incoming;\n\t\trc4 m_rc4_outgoing;\n#endif\n\t\t\/\/ determines whether or not encryption and decryption is enabled\n\t\tbool m_encrypt;\n\t\tbool m_decrypt;\n\t};\n\n#ifdef TORRENT_USE_OPENSSL\n\tstruct aes256_handler : encryption_handler\n\t{\n\t\taes256_handler() : m_enc_pos(0), m_dec_pos(0)\n\t\t{\n\t\t\tEVP_CIPHER_CTX_init(&m_enc);\n\t\t\tEVP_CIPHER_CTX_init(&m_dec);\n\t\t}\n\n\t\t~aes256_handler()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_cleanup(&m_enc);\n\t\t\tEVP_CIPHER_CTX_cleanup(&m_dec);\n\t\t}\n\n\t\tvoid set_incoming_key(unsigned char const* in_key, int len)\n\t\t{\n\t\t\tconst int nrounds = 5;\n\t\t\tboost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 };\n\t\t\tboost::uint8_t key[32];\n\t\t\tboost::uint8_t iv[32];\n\n\t\t\tEVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv);\n\t\t\tTORRENT_ASSERT(len == 32);\n\t\t\tEVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv);\n\t\t\t\/\/ since we're using the AES as a stream cipher, both the encrypt and\n\t\t\t\/\/ decrypt context will in fact only _encrypt_ stuff, so initializing\n\t\t\t\/\/ this as encrypt is not a typo\n\t\t\tEVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv);\n\t\t\tm_enc_pos = 0;\n\t\t\tm_dec_pos = 0;\n\t\t\tstd::memcpy(m_enc_state, iv, sizeof(m_enc_state));\n\t\t\tstd::memcpy(m_dec_state, iv, sizeof(m_enc_state));\n\t\t}\n\t\tvoid set_outgoing_key(unsigned char const* key, int len) { \/* no-op *\/ }\n\t\tvoid encrypt(char* pos, int len)\n\t\t{\n\t\t\twhile (len > 0)\n\t\t\t{\n\t\t\t\twhile (m_enc_pos < AES_BLOCK_SIZE && len > 0)\n\t\t\t\t{\n\t\t\t\t\t*pos ^= m_enc_state[m_enc_pos];\n\t\t\t\t\t++m_enc_pos;\n\t\t\t\t\t++pos;\n\t\t\t\t\t--len;\n\t\t\t\t}\n\n\t\t\t\tif (m_enc_pos == AES_BLOCK_SIZE)\n\t\t\t\t{\n\t\t\t\t\tnext_block(&m_enc, m_enc_state);\n\t\t\t\t\tm_enc_pos = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid decrypt(char* pos, int len)\n\t\t{\n\t\t\twhile (len > 0)\n\t\t\t{\n\t\t\t\twhile (m_dec_pos < AES_BLOCK_SIZE && len > 0)\n\t\t\t\t{\n\t\t\t\t\t*pos ^= m_dec_state[m_dec_pos];\n\t\t\t\t\t++m_dec_pos;\n\t\t\t\t\t++pos;\n\t\t\t\t\t--len;\n\t\t\t\t}\n\n\t\t\t\tif (m_dec_pos == AES_BLOCK_SIZE)\n\t\t\t\t{\n\t\t\t\t\tnext_block(&m_dec, m_dec_state);\n\t\t\t\t\tm_dec_pos = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ we're turning the AES block-cipher into a stream cipher. This\n\t\t\/\/ function will produce the next block in the sequence of\n\t\t\/\/ block-sized buffers. We're using \"Output feedback\" (OFB) mode.\n\t\tvoid next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad)\n\t\t{\n\t\t\tint outlen = AES_BLOCK_SIZE;\n\t\t\tEVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE);\n\t\t\tTORRENT_ASSERT(outlen == AES_BLOCK_SIZE);\n\t\t}\n\n\t\tEVP_CIPHER_CTX m_enc;\n\t\tEVP_CIPHER_CTX m_dec;\n\n\t\tboost::uint8_t m_enc_state[AES_BLOCK_SIZE];\n\t\tboost::uint8_t m_dec_state[AES_BLOCK_SIZE];\n\t\tint m_enc_pos;\n\t\tint m_dec_pos;\n\n\t};\n#endif \/\/ TORRENT_USE_OPENSSL\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_PE_CRYPTO_HPP_INCLUDED\n#endif \/\/ TORRENT_DISABLE_ENCRYPTION\n\n<commit_msg>Fix build with LibreSSL<commit_after>\/*\n\nCopyright (c) 2007-2012, Un Shyam & Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\n#ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED\n#define TORRENT_PE_CRYPTO_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_USE_GCRYPT\n#include <gcrypt.h>\n#elif defined TORRENT_USE_OPENSSL\n#include <openssl\/rc4.h>\n#include <openssl\/evp.h>\n#include <openssl\/aes.h>\n#include <openssl\/rand.h>\n#else\n\/\/ RC4 state from libtomcrypt\nstruct rc4 {\n\tint x, y;\n\tunsigned char buf[256];\n};\n\nvoid TORRENT_EXTRA_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state);\nunsigned long TORRENT_EXTRA_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state);\n#endif\n\n#include \"libtorrent\/peer_id.hpp\" \/\/ For sha1_hash\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tclass TORRENT_EXTRA_EXPORT dh_key_exchange\n\t{\n\tpublic:\n\t\tdh_key_exchange();\n\t\tbool good() const { return true; }\n\n\t\t\/\/ Get local public key, always 96 bytes\n\t\tchar const* get_local_key() const;\n\n\t\t\/\/ read remote_pubkey, generate and store shared secret in\n\t\t\/\/ m_dh_shared_secret.\n\t\tint compute_secret(const char* remote_pubkey);\n\n\t\tchar const* get_secret() const { return m_dh_shared_secret; }\n\n\t\tsha1_hash const& get_hash_xor_mask() const { return m_xor_mask; }\n\t\t\n\tprivate:\n\n\t\tint get_local_key_size() const\n\t\t{ return sizeof(m_dh_local_key); }\n\n\t\tchar m_dh_local_key[96];\n\t\tchar m_dh_local_secret[96];\n\t\tchar m_dh_shared_secret[96];\n\t\tsha1_hash m_xor_mask;\n\t};\n\n\tstruct encryption_handler\n\t{\n\t\tvirtual void set_incoming_key(unsigned char const* key, int len) = 0;\n\t\tvirtual void set_outgoing_key(unsigned char const* key, int len) = 0;\n\t\tvirtual void encrypt(char* pos, int len) = 0;\n\t\tvirtual void decrypt(char* pos, int len) = 0;\n\t\tvirtual ~encryption_handler() {}\n\t};\n\n\tstruct rc4_handler : encryption_handler\n\t{\n\tpublic:\n\t\t\/\/ Input longkeys must be 20 bytes\n\t\trc4_handler()\n\t\t\t: m_encrypt(false)\n\t\t\t, m_decrypt(false)\n\t\t{\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n#endif\n\t\t};\n\n\t\tvoid set_incoming_key(unsigned char const* key, int len)\n\t\t{\n\t\t\tm_decrypt = true;\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_incoming);\n\t\t\tgcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_setkey(m_rc4_incoming, key, len);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4_set_key(&m_remote_key, len, key);\n#else\n\t\t\trc4_init(key, len, &m_rc4_incoming);\n#endif\n\t\t\t\/\/ Discard first 1024 bytes\n\t\t\tchar buf[1024];\n\t\t\tdecrypt(buf, 1024);\n\t\t}\n\t\t\n\t\tvoid set_outgoing_key(unsigned char const* key, int len)\n\t\t{\n\t\t\tm_encrypt = true;\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_outgoing);\n\t\t\tgcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0);\n\t\t\tgcry_cipher_setkey(m_rc4_outgoing, key, len);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4_set_key(&m_local_key, len, key);\n#else\n\t\t\trc4_init(key, len, &m_rc4_outgoing);\n#endif\n\t\t\t\/\/ Discard first 1024 bytes\n\t\t\tchar buf[1024];\n\t\t\tencrypt(buf, 1024);\n\t\t}\n\t\t\n\t\t~rc4_handler()\n\t\t{\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_close(m_rc4_incoming);\n\t\t\tgcry_cipher_close(m_rc4_outgoing);\n#endif\n\t\t};\n\n\t\tvoid encrypt(char* pos, int len)\n\t\t{\n\t\t\tif (!m_encrypt) return;\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos);\n#else\n\t\t\trc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing);\n#endif\n\t\t}\n\n\t\tvoid decrypt(char* pos, int len)\n\t\t{\n\t\t\tif (!m_decrypt) return;\n\n\t\t\tTORRENT_ASSERT(len >= 0);\n\t\t\tTORRENT_ASSERT(pos);\n\n#ifdef TORRENT_USE_GCRYPT\n\t\t\tgcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0);\n#elif defined TORRENT_USE_OPENSSL\n\t\t\tRC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos);\n#else\n\t\t\trc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming);\n#endif\n\t\t}\n\n\tprivate:\n#ifdef TORRENT_USE_GCRYPT\n\t\tgcry_cipher_hd_t m_rc4_incoming;\n\t\tgcry_cipher_hd_t m_rc4_outgoing;\n#elif defined TORRENT_USE_OPENSSL\n\t\tRC4_KEY m_local_key; \/\/ Key to encrypt outgoing data\n\t\tRC4_KEY m_remote_key; \/\/ Key to decrypt incoming data\n#else\n\t\trc4 m_rc4_incoming;\n\t\trc4 m_rc4_outgoing;\n#endif\n\t\t\/\/ determines whether or not encryption and decryption is enabled\n\t\tbool m_encrypt;\n\t\tbool m_decrypt;\n\t};\n\n#ifdef TORRENT_USE_OPENSSL\n\tstruct aes256_handler : encryption_handler\n\t{\n\t\taes256_handler() : m_enc_pos(0), m_dec_pos(0)\n\t\t{\n\t\t\tEVP_CIPHER_CTX_init(&m_enc);\n\t\t\tEVP_CIPHER_CTX_init(&m_dec);\n\t\t}\n\n\t\t~aes256_handler()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_cleanup(&m_enc);\n\t\t\tEVP_CIPHER_CTX_cleanup(&m_dec);\n\t\t}\n\n\t\tvoid set_incoming_key(unsigned char const* in_key, int len)\n\t\t{\n\t\t\tconst int nrounds = 5;\n\t\t\tboost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 };\n\t\t\tboost::uint8_t key[32];\n\t\t\tboost::uint8_t iv[32];\n\n\t\t\tEVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv);\n\t\t\tTORRENT_ASSERT(len == 32);\n\t\t\tEVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv);\n\t\t\t\/\/ since we're using the AES as a stream cipher, both the encrypt and\n\t\t\t\/\/ decrypt context will in fact only _encrypt_ stuff, so initializing\n\t\t\t\/\/ this as encrypt is not a typo\n\t\t\tEVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv);\n\t\t\tm_enc_pos = 0;\n\t\t\tm_dec_pos = 0;\n\t\t\tstd::memcpy(m_enc_state, iv, sizeof(m_enc_state));\n\t\t\tstd::memcpy(m_dec_state, iv, sizeof(m_enc_state));\n\t\t}\n\t\tvoid set_outgoing_key(unsigned char const* key, int len) { \/* no-op *\/ }\n\t\tvoid encrypt(char* pos, int len)\n\t\t{\n\t\t\twhile (len > 0)\n\t\t\t{\n\t\t\t\twhile (m_enc_pos < AES_BLOCK_SIZE && len > 0)\n\t\t\t\t{\n\t\t\t\t\t*pos ^= m_enc_state[m_enc_pos];\n\t\t\t\t\t++m_enc_pos;\n\t\t\t\t\t++pos;\n\t\t\t\t\t--len;\n\t\t\t\t}\n\n\t\t\t\tif (m_enc_pos == AES_BLOCK_SIZE)\n\t\t\t\t{\n\t\t\t\t\tnext_block(&m_enc, m_enc_state);\n\t\t\t\t\tm_enc_pos = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid decrypt(char* pos, int len)\n\t\t{\n\t\t\twhile (len > 0)\n\t\t\t{\n\t\t\t\twhile (m_dec_pos < AES_BLOCK_SIZE && len > 0)\n\t\t\t\t{\n\t\t\t\t\t*pos ^= m_dec_state[m_dec_pos];\n\t\t\t\t\t++m_dec_pos;\n\t\t\t\t\t++pos;\n\t\t\t\t\t--len;\n\t\t\t\t}\n\n\t\t\t\tif (m_dec_pos == AES_BLOCK_SIZE)\n\t\t\t\t{\n\t\t\t\t\tnext_block(&m_dec, m_dec_state);\n\t\t\t\t\tm_dec_pos = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ we're turning the AES block-cipher into a stream cipher. This\n\t\t\/\/ function will produce the next block in the sequence of\n\t\t\/\/ block-sized buffers. We're using \"Output feedback\" (OFB) mode.\n\t\tvoid next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad)\n\t\t{\n\t\t\tint outlen = AES_BLOCK_SIZE;\n\t\t\tEVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE);\n\t\t\tTORRENT_ASSERT(outlen == AES_BLOCK_SIZE);\n\t\t}\n\n\t\tEVP_CIPHER_CTX m_enc;\n\t\tEVP_CIPHER_CTX m_dec;\n\n\t\tboost::uint8_t m_enc_state[AES_BLOCK_SIZE];\n\t\tboost::uint8_t m_dec_state[AES_BLOCK_SIZE];\n\t\tint m_enc_pos;\n\t\tint m_dec_pos;\n\n\t};\n#endif \/\/ TORRENT_USE_OPENSSL\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_PE_CRYPTO_HPP_INCLUDED\n#endif \/\/ TORRENT_DISABLE_ENCRYPTION\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ut_volumebarlogic.h\"\n#include <volumebarlogic.h>\n\nvoid\nUt_VolumeBarLogic::init ()\n{\n}\n\nvoid\nUt_VolumeBarLogic::cleanup ()\n{\n}\n\nvoid\nUt_VolumeBarLogic::initTestCase ()\n{\n m_Api = new VolumeBarLogic;\n m_Api->stepsUpdated (30, 100);\n}\n\nvoid\nUt_VolumeBarLogic::cleanupTestCase ()\n{\n delete m_Api;\n}\n\n\/\/ Check if setting \/ getting works correctly\nvoid\nUt_VolumeBarLogic::testVolumeSetGet ()\n{\n quint32 val = 5;\n\n m_Api->setVolume (val);\n\n QVERIFY (m_Api->getVolume () == val) ;\n}\n\nvoid\nUt_VolumeBarLogic::testVolumeChangeByPa ()\n{\n quint32 currentstep = 10;\n quint32 stepcount = 20;\n\n \/\/ A D-bus message calls this slot [inside the logic],\n \/\/ now we call this outside :\n m_Api->stepsUpdated (currentstep, stepcount);\n\n \/\/ Check the current ...\n QVERIFY (m_Api->getVolume () == currentstep);\n \/\/ .. and the maximal values\n QVERIFY (m_Api->getMaxVolume () == stepcount);\n}\n\nvoid\nUt_VolumeBarLogic::testSignaling ()\n{\n quint32 currentstep = 0;\n quint32 stepcount = 13;\n\n \/\/ Whe PulseAudio sends the D-Bus signal about stepcount\/currentstep\n \/\/ changes logic should emit itself volumeChanged signal\n QSignalSpy spy (m_Api, SIGNAL (volumeChanged (quint32, quint32)));\n\n \/\/ Do what PulseAudio do [of course Pa doing this indirectly...]\n m_Api->stepsUpdated (currentstep, stepcount);\n\n QTest::qWait (500); \/\/ wait for a little time\n\n QList<QVariant> arguments = spy.takeFirst ();\n \/\/ Verify the signal parameters\n QVERIFY (arguments.at (0).toUInt () == currentstep);\n QVERIFY (arguments.at (1).toUInt () == stepcount);\n}\n\nQTEST_MAIN(Ut_VolumeBarLogic)\n<commit_msg>Update ut_volumebarlogic<commit_after>#include \"ut_volumebarlogic.h\"\n#include <volumebarlogic.h>\n\nvoid\nUt_VolumeBarLogic::init ()\n{\n}\n\nvoid\nUt_VolumeBarLogic::cleanup ()\n{\n}\n\nvoid\nUt_VolumeBarLogic::initTestCase ()\n{\n m_Api = new VolumeBarLogic;\n m_Api->stepsUpdated (30, 100);\n}\n\nvoid\nUt_VolumeBarLogic::cleanupTestCase ()\n{\n delete m_Api;\n}\n\n\/\/ Check if setting \/ getting works correctly\nvoid\nUt_VolumeBarLogic::testVolumeSetGet ()\n{\n quint32 val = 5;\n\n m_Api->setVolume (val);\n\n QVERIFY (m_Api->getVolume () == val) ;\n}\n\nvoid\nUt_VolumeBarLogic::testVolumeChangeByPa ()\n{\n quint32 currentstep = 10;\n quint32 stepcount = 20;\n\n \/\/ A D-bus message calls this slot [inside the logic],\n \/\/ now we call this outside :\n m_Api->stepsUpdated (currentstep, stepcount);\n\n \/\/ Check the current ...\n QVERIFY (m_Api->getVolume () == currentstep);\n \/\/ .. and the maximal values\n QVERIFY (m_Api->getMaxVolume () == stepcount);\n}\n\nvoid\nUt_VolumeBarLogic::testSignaling ()\n{\n quint32 currentstep = 0;\n quint32 stepcount = 13;\n\n \/\/ Whe PulseAudio sends the D-Bus signal about stepcount\/currentstep\n \/\/ changes logic should emit itself volumeChanged signal\n QSignalSpy spy (m_Api, SIGNAL (volumeChanged (quint32, quint32, bool)));\n\n \/\/ Do what PulseAudio do [of course Pa doing this indirectly...]\n m_Api->stepsUpdated (currentstep, stepcount);\n\n QTest::qWait (500); \/\/ wait for a little time\n\n QList<QVariant> arguments = spy.takeFirst ();\n \/\/ Verify the signal parameters\n QVERIFY (arguments.at (0).toUInt () == currentstep);\n QVERIFY (arguments.at (1).toUInt () == stepcount);\n}\n\nQTEST_MAIN(Ut_VolumeBarLogic)\n<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include <test_common.h>\n\n#include <vistk\/pipeline_util\/export_dot.h>\n#include <vistk\/pipeline_util\/export_dot_exception.h>\n#include <vistk\/pipeline_util\/pipe_bakery.h>\n\n#include <vistk\/pipeline\/modules.h>\n\n#include <boost\/filesystem\/path.hpp>\n\n#include <exception>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nstatic std::string const pipe_ext = \".pipe\";\n\nstatic void run_test(std::string const& test_name, boost::filesystem::path const& pipe_file);\n\nint\nmain(int argc, char* argv[])\n{\n if (argc != 3)\n {\n std::cerr << \"Error: Expected two arguments\" << std::endl;\n\n return 1;\n }\n\n std::string const test_name = argv[1];\n boost::filesystem::path const pipe_dir = argv[2];\n\n boost::filesystem::path const pipe_file = pipe_dir \/ (test_name + pipe_ext);\n\n try\n {\n run_test(test_name, pipe_file);\n }\n catch (std::exception& e)\n {\n std::cerr << \"Error: Unexpected exception: \" << e.what() << std::endl;\n\n return 1;\n }\n\n return 0;\n}\n\nstatic void test_pipeline_null(boost::filesystem::path const& pipe_file);\nstatic void test_simple_pipeline(boost::filesystem::path const& pipe_file);\n\nvoid\nrun_test(std::string const& test_name, boost::filesystem::path const& pipe_file)\n{\n if (test_name == \"pipeline_null\")\n {\n test_pipeline_null(pipe_file);\n }\n else if (test_name == \"simple_pipeline\")\n {\n test_simple_pipeline(pipe_file);\n }\n else\n {\n std::cerr << \"Error: Unknown test: \" << test_name << std::endl;\n }\n}\n\nvoid test_pipeline_null(boost::filesystem::path const& \/*pipe_file*\/)\n{\n vistk::pipeline_t pipeline;\n\n std::ostringstream sstr;\n\n EXPECT_EXCEPTION(vistk::null_pipeline_export_dot_exception,\n vistk::export_dot(sstr, pipeline, \"(unnamed)\"),\n \"exporting a NULL pipeline to dot\");\n}\n\nvoid\ntest_simple_pipeline(boost::filesystem::path const& pipe_file)\n{\n vistk::load_known_modules();\n\n vistk::pipeline_t const pipeline = vistk::bake_pipe_from_file(pipe_file);\n\n std::ostringstream sstr;\n\n vistk::export_dot(sstr, pipeline, \"(unnamed)\");\n}\n<commit_msg>Fix some style<commit_after>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include <test_common.h>\n\n#include <vistk\/pipeline_util\/export_dot.h>\n#include <vistk\/pipeline_util\/export_dot_exception.h>\n#include <vistk\/pipeline_util\/pipe_bakery.h>\n\n#include <vistk\/pipeline\/modules.h>\n\n#include <boost\/filesystem\/path.hpp>\n\n#include <exception>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nstatic std::string const pipe_ext = \".pipe\";\n\nstatic void run_test(std::string const& test_name, boost::filesystem::path const& pipe_file);\n\nint\nmain(int argc, char* argv[])\n{\n if (argc != 3)\n {\n std::cerr << \"Error: Expected two arguments\" << std::endl;\n\n return 1;\n }\n\n std::string const test_name = argv[1];\n boost::filesystem::path const pipe_dir = argv[2];\n\n boost::filesystem::path const pipe_file = pipe_dir \/ (test_name + pipe_ext);\n\n try\n {\n run_test(test_name, pipe_file);\n }\n catch (std::exception& e)\n {\n std::cerr << \"Error: Unexpected exception: \" << e.what() << std::endl;\n\n return 1;\n }\n\n return 0;\n}\n\nstatic void test_pipeline_null(boost::filesystem::path const& pipe_file);\nstatic void test_simple_pipeline(boost::filesystem::path const& pipe_file);\n\nvoid\nrun_test(std::string const& test_name, boost::filesystem::path const& pipe_file)\n{\n if (test_name == \"pipeline_null\")\n {\n test_pipeline_null(pipe_file);\n }\n else if (test_name == \"simple_pipeline\")\n {\n test_simple_pipeline(pipe_file);\n }\n else\n {\n std::cerr << \"Error: Unknown test: \" << test_name << std::endl;\n }\n}\n\nvoid\ntest_pipeline_null(boost::filesystem::path const& \/*pipe_file*\/)\n{\n vistk::pipeline_t pipeline;\n\n std::ostringstream sstr;\n\n EXPECT_EXCEPTION(vistk::null_pipeline_export_dot_exception,\n vistk::export_dot(sstr, pipeline, \"(unnamed)\"),\n \"exporting a NULL pipeline to dot\");\n}\n\nvoid\ntest_simple_pipeline(boost::filesystem::path const& pipe_file)\n{\n vistk::load_known_modules();\n\n vistk::pipeline_t const pipeline = vistk::bake_pipe_from_file(pipe_file);\n\n std::ostringstream sstr;\n\n vistk::export_dot(sstr, pipeline, \"(unnamed)\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"PlatformAbstractions.h\"\n#include <nan.h>\n#include <stdlib.h>\n#include <uv.h>\n#include \"CallbackData.h\"\n\nnamespace ClrLoader {\n\nusing namespace v8;\n\ntypedef void (STDMETHODCALLTYPE *PUnmanagedCallback)(const intptr_t, const char*);\n\ntypedef void (STDMETHODCALLTYPE *PManagedEntryPoint)(const intptr_t, const char*, const char*, const void (*PUnmanagedCallback));\n\n\/\/ Declare a variable pointing to our managed method.\nPManagedEntryPoint pManagedEntryPoint;\n\nvoid ClrCallback(const intptr_t returnPtr, const char* value){\n auto callbackData = (CallbackData*)returnPtr;\n callbackData->setResult(value);\n uv_async_send(callbackData->getLoopData());\n}\n\nvoid FinalizeUvCallback(uv_async_t* handle){\n Nan::HandleScope handleScope;\n auto data = (CallbackData*)handle->data;\n const unsigned argc = 1;\n Local<Value> argv[argc] = { Nan::New<String>(data->getResult()).ToLocalChecked() };\n Local<Function> origFunc = Nan::New(*data->getCallback());\n Nan::Callback cb(origFunc);\n cb.Call(argc, argv);\n delete data;\n}\n\nvoid ClrExecute(const Nan::FunctionCallbackInfo<Value>& args) {\n if (args.Length() < 3) {\n Nan::ThrowTypeError(\"Wrong number of arguments\");\n return;\n }\n\n if (!args[0]->IsString()\n || !args[1]->IsString()\n || !args[2]->IsFunction()) {\n Nan::ThrowError(\"Wrong arguments\");\n return;\n }\n\n String::Utf8Value utfStringConfig(args[0].As<String>());\n auto stdCStringConfig = std::string(*utfStringConfig);\n\n String::Utf8Value utfStringData(args[1].As<String>());\n auto stdCStringData = std::string(*utfStringData);\n\n \/\/ Perform the operation\n auto cb = args[2].As<Function>();\n auto nanCb = new CallbackData(new Nan::Persistent<Function>(cb));\n auto initResult = uv_async_init(uv_default_loop(), nanCb->getLoopData(), FinalizeUvCallback);\n if (!SUCCEEDED(initResult)){\n Nan::ThrowError(uv_strerror(initResult));\n return;\n }\n\n pManagedEntryPoint((intptr_t)nanCb, stdCStringConfig.c_str(), stdCStringData.c_str(), ClrCallback);\n}\n\nvoid Init(Local<Object> exports) {\n auto libPath = std::getenv(\"CLR_LIB_PATH\");\n if (libPath == NULL){\n Nan::ThrowError(\"CLR_LIB_PATH not set\");\n return;\n }\n\n auto appBasePath = std::getenv(\"CLR_APPBASE_PATH\");\n if (appBasePath == NULL){\n Nan::ThrowError(\"CLR_APPBASE_PATH not set\");\n return;\n }\n\n auto trustedPlatformAssemblies = std::getenv(\"CLR_TRUSTED_PLATFORM_ASSEMBLIES\");\n if (trustedPlatformAssemblies == NULL){\n Nan::ThrowError(\"CLR_TRUSTED_PLATFORM_ASSEMBLIES not set\");\n return;\n }\n\n auto appPaths = std::getenv(\"CLR_APP_PATHS\");\n if (appPaths == NULL){\n Nan::ThrowError(\"CLR_APP_PATHS not set\");\n return;\n }\n\n void* pCLRRuntimeHost = nullptr;\n clr_domain_id domainId;\n auto initClrResult = InitializeCoreClr(libPath,\n\t\t appBasePath,\n\t\t trustedPlatformAssemblies,\n\t\t appPaths,\n\t\t pCLRRuntimeHost,\n\t\t (void*)&pManagedEntryPoint,\n\t\t &domainId);\n switch(initClrResult){\n case Success:\n break;\n case CantLoadLibrary:\n Nan::ThrowError(\"Can't load coreclr.dll\");\n return;\n case CantFindRuntimeHostFactory:\n Nan::ThrowError(\"Can't get CLR Runtime Host factory\");\n return;\n case CantStartClrHost:\n Nan::ThrowError(\"Error starting CLR host\");\n return;\n case CantSetStartupFlags:\n Nan::ThrowError(\"Error while setting CLR Runtime startup flags\");\n return;\n case CantAuthenticateHost:\n Nan::ThrowError(\"Error while authenticating CLR host\");\n return;\n case CantCreateClrHost:\n Nan::ThrowError(\"Error while initializing CLR Runtime host\");\n return;\n case CantCreateAppDomain:\n Nan::ThrowError(\"Failed to create default AppDomain\");\n return;\n case CantFindClrDelegate:\n Nan::ThrowError(\"Failed to find managed entry point\");\n return;\n default:\n Nan::ThrowError(\"Unknown error\");\n return;\n }\n\n Nan::SetMethod(exports, \"ClrExecute\", ClrExecute);\n}\n\nNODE_MODULE(addon, Init)\n}\n<commit_msg>Cross platform fixes<commit_after>#include \"PlatformAbstractions.h\"\n#include <nan.h>\n#include <stdlib.h>\n#include <uv.h>\n#include \"CallbackData.h\"\n\nnamespace ClrLoader {\n\nusing namespace v8;\n\ntypedef void (PUnmanagedCallback)(const intptr_t, const char*);\n\ntypedef void (PManagedEntryPoint)(const intptr_t, const char*, const char*, const void (*PUnmanagedCallback));\n\n\/\/ Declare a variable pointing to our managed method.\nPManagedEntryPoint* pManagedEntryPoint;\n\nvoid ClrCallback(const intptr_t returnPtr, const char* value){\n auto callbackData = (CallbackData*)returnPtr;\n callbackData->setResult(value);\n uv_async_send(callbackData->getLoopData());\n}\n\nvoid FinalizeUvCallback(uv_async_t* handle){\n Nan::HandleScope handleScope;\n auto data = (CallbackData*)handle->data;\n const unsigned argc = 1;\n Local<Value> argv[argc] = { Nan::New<String>(data->getResult()).ToLocalChecked() };\n Local<Function> origFunc = Nan::New(*data->getCallback());\n Nan::Callback cb(origFunc);\n cb.Call(argc, argv);\n delete data;\n}\n\nvoid ClrExecute(const Nan::FunctionCallbackInfo<Value>& args) {\n if (args.Length() < 3) {\n Nan::ThrowTypeError(\"Wrong number of arguments\");\n return;\n }\n\n if (!args[0]->IsString()\n || !args[1]->IsString()\n || !args[2]->IsFunction()) {\n Nan::ThrowError(\"Wrong arguments\");\n return;\n }\n\n String::Utf8Value utfStringConfig(args[0].As<String>());\n auto stdCStringConfig = std::string(*utfStringConfig);\n\n String::Utf8Value utfStringData(args[1].As<String>());\n auto stdCStringData = std::string(*utfStringData);\n\n \/\/ Perform the operation\n auto cb = args[2].As<Function>();\n auto nanCb = new CallbackData(new Nan::Persistent<Function>(cb));\n auto initResult = uv_async_init(uv_default_loop(), nanCb->getLoopData(), FinalizeUvCallback);\n if (!SUCCEEDED(initResult)){\n Nan::ThrowError(uv_strerror(initResult));\n return;\n }\n\n pManagedEntryPoint((intptr_t)nanCb, stdCStringConfig.c_str(), stdCStringData.c_str(), ClrCallback);\n}\n\nvoid Init(Local<Object> exports) {\n auto libPath = std::getenv(\"CLR_LIB_PATH\");\n if (libPath == NULL){\n Nan::ThrowError(\"CLR_LIB_PATH not set\");\n return;\n }\n\n auto appBasePath = std::getenv(\"CLR_APPBASE_PATH\");\n if (appBasePath == NULL){\n Nan::ThrowError(\"CLR_APPBASE_PATH not set\");\n return;\n }\n\n auto trustedPlatformAssemblies = std::getenv(\"CLR_TRUSTED_PLATFORM_ASSEMBLIES\");\n if (trustedPlatformAssemblies == NULL){\n Nan::ThrowError(\"CLR_TRUSTED_PLATFORM_ASSEMBLIES not set\");\n return;\n }\n\n auto appPaths = std::getenv(\"CLR_APP_PATHS\");\n if (appPaths == NULL){\n Nan::ThrowError(\"CLR_APP_PATHS not set\");\n return;\n }\n\n void* pCLRRuntimeHost = nullptr;\n clr_domain_id domainId;\n auto initClrResult = InitializeCoreClr(libPath,\n\t\t appBasePath,\n\t\t trustedPlatformAssemblies,\n\t\t appPaths,\n\t\t pCLRRuntimeHost,\n\t\t (void*)&pManagedEntryPoint,\n\t\t &domainId);\n switch(initClrResult){\n case Success:\n break;\n case CantLoadLibrary:\n Nan::ThrowError(\"Can't load coreclr.dll\");\n return;\n case CantFindRuntimeHostFactory:\n Nan::ThrowError(\"Can't get CLR Runtime Host factory\");\n return;\n case CantStartClrHost:\n Nan::ThrowError(\"Error starting CLR host\");\n return;\n case CantSetStartupFlags:\n Nan::ThrowError(\"Error while setting CLR Runtime startup flags\");\n return;\n case CantAuthenticateHost:\n Nan::ThrowError(\"Error while authenticating CLR host\");\n return;\n case CantCreateClrHost:\n Nan::ThrowError(\"Error while initializing CLR Runtime host\");\n return;\n case CantCreateAppDomain:\n Nan::ThrowError(\"Failed to create default AppDomain\");\n return;\n case CantFindClrDelegate:\n Nan::ThrowError(\"Failed to find managed entry point\");\n return;\n default:\n Nan::ThrowError(\"Unknown error\");\n return;\n }\n\n Nan::SetMethod(exports, \"ClrExecute\", ClrExecute);\n}\n\nNODE_MODULE(addon, Init)\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include \"Entity\/Aspect.h\"\n#include \"Ecs.h\"\n\n#include \"Entity\/Entity.h\"\n#include \"Entity\/Index.h\"\n#include \"Entity\/Archetype.h\"\n#include \"System\/SystemGroup.h\"\n\nDC_BEGIN_DREEMCHEST\n\nnamespace Ecs {\n\nIMPLEMENT_LOGGER( log )\n\n\/\/ ** Ecs::Ecs\nEcs::Ecs( const EntityIdGeneratorPtr& entityIdGenerator ) : m_entityId( entityIdGenerator )\n{\n}\n\n\/\/ ** Ecs::create\nEcsPtr Ecs::create( const EntityIdGeneratorPtr& entityIdGenerator )\n{\n\tDC_BREAK_IF( entityIdGenerator == EntityIdGeneratorPtr() );\n\treturn DC_NEW Ecs( entityIdGenerator );\n}\n\n\/\/ ** Ecs::registerEntity\nvoid Ecs::registerEntity( EntityPtr entity, const EntityId& id )\n{\n\tDC_BREAK_IF( isUsedId( id ) );\n\n\t\/\/ Setup entity\n\tentity->setEcs( this );\n\tentity->setId( id );\n\n\t\/\/ Register the entity\n\tm_entities[id] = entity;\n}\n\n\/\/ ** Ecs::createArchetypeByName\nArchetypePtr Ecs::createArchetypeByName( const String& name, const EntityId& id )\n{\n\t\/\/ Create archetype instance by name\n\tArchetypePtr instance = m_archetypeFactory.construct( name );\n\n\t\/\/ Ensure we found the archetype type\n\tif( !instance.valid() ) {\n\t\tlog::error( \"Ecs::createArchetypeByName : unknown archetype '%s'\\n\", name.c_str() );\n\t\treturn ArchetypePtr();\n\t}\n\n\t\/\/ Initialize the entity id\n\tEntityId eid = id.isNull() ? m_entityId->generate() : id;\n\n\t\/\/ Register the entity\n\tregisterEntity( instance, eid );\n\n\t\/\/ Construct the archetype\n\tinstance->construct();\n\n\treturn instance;\n}\n\n\/\/ ** Ecs::createComponentByName\nComponentPtr Ecs::createComponentByName( const String& name ) const\n{\n\treturn m_componentFactory.construct( name );\n}\n\n\/\/ ** Ecs::createEntity\nEntityPtr Ecs::createEntity( const EntityId& id )\n{\n\tDC_BREAK_IF( isUsedId( id ) );\n\n\tEntityPtr entity( DC_NEW Entity );\n\tregisterEntity( entity, id );\n\n\treturn entity;\n}\n\n\/\/ ** Ecs::createEntity\nEntityPtr Ecs::createEntity( void )\n{\n\tEntityId id = m_entityId->generate();\n\treturn createEntity( id );\n}\n\n\/\/ ** Ecs::findEntity\nEntityPtr Ecs::findEntity( const EntityId& id ) const\n{\n\tEntities::const_iterator i = m_entities.find( id );\n\treturn i != m_entities.end() ? i->second : EntityPtr();\n}\n\n\/\/ ** Ecs::findByAspect\nEntitySet Ecs::findByAspect( const Aspect& aspect ) const\n{\n\tEntitySet result;\n\n\tfor( Entities::const_iterator i = m_entities.begin(), end = m_entities.end(); i != end; ++i ) {\n\t\tif( aspect.hasIntersection( i->second ) ) {\n\t\t\tresult.insert( i->second );\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\/\/ ** Ecs::removeEntity\nvoid Ecs::removeEntity( const EntityId& id )\n{\n\tDC_BREAK_IF( !isUsedId( id ) );\n\n\tEntities::iterator i = m_entities.find( id );\n\n\tif( i == m_entities.end() ) {\n\t\treturn;\n\t}\n\n\ti->second->markAsRemoved();\n\n\tm_changed.insert( i->second );\n\tm_removed.insert( i->second );\n}\n\n\/\/ ** Ecs::isUsedId\nbool Ecs::isUsedId( const EntityId& id ) const\n{\n\treturn m_entities.find( id ) != m_entities.end();\n}\n\n\/\/ ** Ecs::requestIndex\nIndexPtr Ecs::requestIndex( const String& name, const Aspect& aspect )\n{\n\tIndices::iterator i = m_indices.find( aspect );\n\n\tif( i != m_indices.end() ) {\n\t\treturn i->second;\n\t}\n\n\tIndexPtr index( DC_NEW Index( this, name, aspect ) );\n\tm_indices[aspect] = index;\n\n\treturn index;\n}\n\n\/\/ ** Ecs::createGroup\nSystemGroupPtr Ecs::createGroup( const String& name, u32 mask )\n{\n\tSystemGroupPtr group( DC_NEW SystemGroup( this, name, mask ) );\n\tm_systems.push_back( group );\n\treturn group;\n}\n\n\/\/ ** Ecs::notifyEntityChanged\nvoid Ecs::notifyEntityChanged( const EntityId& id )\n{\n\tDC_BREAK_IF( !isUsedId( id ) );\n\n\tEntities::iterator i = m_entities.find( id );\n\n\tif( i != m_entities.end() ) {\n\t\tm_changed.insert( i->second );\n\t}\n}\n\n\/\/ ** Ecs::update\nvoid Ecs::update( u32 currentTime, f32 dt, u32 systems )\n{\n\t\/\/ Process all changed entities.\n\twhile( m_changed.size() ) {\n\t\tEntitySet changed = m_changed;\n\t\tm_changed.clear();\n\n\t\tfor( EntitySet::iterator i = changed.begin(), end = changed.end(); i != end; ++i ) {\n\t\t\tfor( Indices::iterator j = m_indices.begin(), jend = m_indices.end(); j != jend; j++ ) {\n\t\t\t\tj->second->notifyEntityChanged( *i );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Remove all queued entities\n\twhile( m_removed.size() ) {\n\t\tEntitySet removed = m_removed;\n\t\tm_removed.clear();\n\n\t\tfor( EntitySet::iterator i = removed.begin(), end = removed.end(); i != end; ++i ) {\n\t\t\tm_entities.erase( (*i)->id() );\n\t\t}\n\t}\n\n\t\/\/ Update all system groups.\n\tfor( u32 i = 0, n = ( u32 )m_systems.size(); i < n; i++ ) {\n\t\tSystemGroupPtr& group = m_systems[i];\n\n\t\tif( group->mask() & systems ) {\n\t\t\tgroup->update( currentTime, dt );\n\t\t}\n\t}\n}\n\n\/\/ ** EntityIdGenerator::EntityIdGenerator\nEntityIdGenerator::EntityIdGenerator( void )\n{\n#if DC_ECS_INTEGER_IDS\n\tm_nextId = 1;\n#endif\n}\n\n\/\/ ** EntityIdGenerator::generate\nEntityId EntityIdGenerator::generate( void )\n{\n#if DC_ECS_INTEGER_IDS\n\treturn m_nextId++;\n#else\n\treturn Guid::generate();\n#endif\n}\n\n} \/\/ namespace Ecs\n\nDC_END_DREEMCHEST<commit_msg>Added GUID randomization to EntityIdGenerator<commit_after>\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include \"Entity\/Aspect.h\"\n#include \"Ecs.h\"\n\n#include \"Entity\/Entity.h\"\n#include \"Entity\/Index.h\"\n#include \"Entity\/Archetype.h\"\n#include \"System\/SystemGroup.h\"\n\n#include <time.h>\n\nDC_BEGIN_DREEMCHEST\n\nnamespace Ecs {\n\nIMPLEMENT_LOGGER( log )\n\n\/\/ ** Ecs::Ecs\nEcs::Ecs( const EntityIdGeneratorPtr& entityIdGenerator ) : m_entityId( entityIdGenerator )\n{\n}\n\n\/\/ ** Ecs::create\nEcsPtr Ecs::create( const EntityIdGeneratorPtr& entityIdGenerator )\n{\n\tDC_BREAK_IF( entityIdGenerator == EntityIdGeneratorPtr() );\n\treturn DC_NEW Ecs( entityIdGenerator );\n}\n\n\/\/ ** Ecs::registerEntity\nvoid Ecs::registerEntity( EntityPtr entity, const EntityId& id )\n{\n\tDC_BREAK_IF( isUsedId( id ) );\n\n\t\/\/ Setup entity\n\tentity->setEcs( this );\n\tentity->setId( id );\n\n\t\/\/ Register the entity\n\tm_entities[id] = entity;\n}\n\n\/\/ ** Ecs::createArchetypeByName\nArchetypePtr Ecs::createArchetypeByName( const String& name, const EntityId& id )\n{\n\t\/\/ Create archetype instance by name\n\tArchetypePtr instance = m_archetypeFactory.construct( name );\n\n\t\/\/ Ensure we found the archetype type\n\tif( !instance.valid() ) {\n\t\tlog::error( \"Ecs::createArchetypeByName : unknown archetype '%s'\\n\", name.c_str() );\n\t\treturn ArchetypePtr();\n\t}\n\n\t\/\/ Initialize the entity id\n\tEntityId eid = id.isNull() ? m_entityId->generate() : id;\n\n\t\/\/ Register the entity\n\tregisterEntity( instance, eid );\n\n\t\/\/ Construct the archetype\n\tinstance->construct();\n\n\treturn instance;\n}\n\n\/\/ ** Ecs::createComponentByName\nComponentPtr Ecs::createComponentByName( const String& name ) const\n{\n\treturn m_componentFactory.construct( name );\n}\n\n\/\/ ** Ecs::createEntity\nEntityPtr Ecs::createEntity( const EntityId& id )\n{\n\tDC_BREAK_IF( isUsedId( id ) );\n\n\tEntityPtr entity( DC_NEW Entity );\n\tregisterEntity( entity, id );\n\n\treturn entity;\n}\n\n\/\/ ** Ecs::createEntity\nEntityPtr Ecs::createEntity( void )\n{\n\tEntityId id = m_entityId->generate();\n\treturn createEntity( id );\n}\n\n\/\/ ** Ecs::findEntity\nEntityPtr Ecs::findEntity( const EntityId& id ) const\n{\n\tEntities::const_iterator i = m_entities.find( id );\n\treturn i != m_entities.end() ? i->second : EntityPtr();\n}\n\n\/\/ ** Ecs::findByAspect\nEntitySet Ecs::findByAspect( const Aspect& aspect ) const\n{\n\tEntitySet result;\n\n\tfor( Entities::const_iterator i = m_entities.begin(), end = m_entities.end(); i != end; ++i ) {\n\t\tif( aspect.hasIntersection( i->second ) ) {\n\t\t\tresult.insert( i->second );\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\/\/ ** Ecs::removeEntity\nvoid Ecs::removeEntity( const EntityId& id )\n{\n\tDC_BREAK_IF( !isUsedId( id ) );\n\n\tEntities::iterator i = m_entities.find( id );\n\n\tif( i == m_entities.end() ) {\n\t\treturn;\n\t}\n\n\ti->second->markAsRemoved();\n\n\tm_changed.insert( i->second );\n\tm_removed.insert( i->second );\n}\n\n\/\/ ** Ecs::isUsedId\nbool Ecs::isUsedId( const EntityId& id ) const\n{\n\treturn m_entities.find( id ) != m_entities.end();\n}\n\n\/\/ ** Ecs::requestIndex\nIndexPtr Ecs::requestIndex( const String& name, const Aspect& aspect )\n{\n\tIndices::iterator i = m_indices.find( aspect );\n\n\tif( i != m_indices.end() ) {\n\t\treturn i->second;\n\t}\n\n\tIndexPtr index( DC_NEW Index( this, name, aspect ) );\n\tm_indices[aspect] = index;\n\n\treturn index;\n}\n\n\/\/ ** Ecs::createGroup\nSystemGroupPtr Ecs::createGroup( const String& name, u32 mask )\n{\n\tSystemGroupPtr group( DC_NEW SystemGroup( this, name, mask ) );\n\tm_systems.push_back( group );\n\treturn group;\n}\n\n\/\/ ** Ecs::notifyEntityChanged\nvoid Ecs::notifyEntityChanged( const EntityId& id )\n{\n\tDC_BREAK_IF( !isUsedId( id ) );\n\n\tEntities::iterator i = m_entities.find( id );\n\n\tif( i != m_entities.end() ) {\n\t\tm_changed.insert( i->second );\n\t}\n}\n\n\/\/ ** Ecs::update\nvoid Ecs::update( u32 currentTime, f32 dt, u32 systems )\n{\n\t\/\/ Process all changed entities.\n\twhile( m_changed.size() ) {\n\t\tEntitySet changed = m_changed;\n\t\tm_changed.clear();\n\n\t\tfor( EntitySet::iterator i = changed.begin(), end = changed.end(); i != end; ++i ) {\n\t\t\tfor( Indices::iterator j = m_indices.begin(), jend = m_indices.end(); j != jend; j++ ) {\n\t\t\t\tj->second->notifyEntityChanged( *i );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Remove all queued entities\n\twhile( m_removed.size() ) {\n\t\tEntitySet removed = m_removed;\n\t\tm_removed.clear();\n\n\t\tfor( EntitySet::iterator i = removed.begin(), end = removed.end(); i != end; ++i ) {\n\t\t\tm_entities.erase( (*i)->id() );\n\t\t}\n\t}\n\n\t\/\/ Update all system groups.\n\tfor( u32 i = 0, n = ( u32 )m_systems.size(); i < n; i++ ) {\n\t\tSystemGroupPtr& group = m_systems[i];\n\n\t\tif( group->mask() & systems ) {\n\t\t\tgroup->update( currentTime, dt );\n\t\t}\n\t}\n}\n\n\/\/ ** EntityIdGenerator::EntityIdGenerator\nEntityIdGenerator::EntityIdGenerator( void )\n{\n#if DC_ECS_INTEGER_IDS\n\tm_nextId = 1;\n#else\n\tsrand( static_cast<u32>( time( NULL ) ) );\n#endif\n}\n\n\/\/ ** EntityIdGenerator::generate\nEntityId EntityIdGenerator::generate( void )\n{\n#if DC_ECS_INTEGER_IDS\n\treturn m_nextId++;\n#else\n\treturn Guid::generate();\n#endif\n}\n\n} \/\/ namespace Ecs\n\nDC_END_DREEMCHEST<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/common\/include\/p9_misc_scom_addresses_fld_fixes.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file misc_scom_addresses_fld_fixes.H\n\/\/\/ @brief The *scom_addresses_fld.H files are generated form figtree,\n\/\/\/ but the figree can be wrong. This file is included in\n\/\/\/ *_scom_addresses_fld.H and allows incorrect constants to be\n\/\/\/ fixed manually.\n\/\/\/\n\/\/ *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>\n\/\/ *HWP FW Owner: ? <?>\n\/\/ *HWP Team: SAO\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE\n\n#ifndef __P9_MISC_SCOM_ADDRESSES_FLD_FIXES_H\n#define __P9_MISC_SCOM_ADDRESSES_FLD_FIXES_H\n\n\/\/ N2 Chiplet Config Register1\nREG64_FLD(PERV_N2_CPLT_CONF1_TC_PSI_IOVALID_DC, 10, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Receive Status Register\nREG64_FLD(PU_RX_PSI_STATUS_CHECK_PASS, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_RX_PSI_STATUS_CHECK_FAIL, 1, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Control Register\nREG64_FLD(PU_TX_PSI_CNTL_IORESET, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Receive Control Register\nREG64_FLD(PU_RX_PSI_CNTL_IORESET, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Channel Internal Address Register\nREG64_FLD(PU_TX_CH_INTADDR_IAR_ADDR, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_INTADDR_IAR_ADDR_LEN, 8, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Channel Misc Register\nREG64_FLD(PU_TX_CH_MISC_WEN0, 12, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_MISC_WEN1, 13, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_MISC_WEN2, 14, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ RX VGA Control Register1\nREG64_FLD(PEC_SCOM0X0B_EDMOD, 52, SH_UNT_PEC, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PEC_SCOM0X0B_EDMOD_LEN, 2, SH_UNT_PEC, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/Example\n\/\/Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG\n\/\/and add another paramter that is the new value you want.\n\/\/\n\/\/FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,\n\/\/ 12);\n\n\n#endif\n<commit_msg>update HWP level metadata for nest, common files<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/common\/include\/p9_misc_scom_addresses_fld_fixes.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file misc_scom_addresses_fld_fixes.H\n\/\/\/ @brief The *scom_addresses_fld.H files are generated form figtree,\n\/\/\/ but the figree can be wrong. This file is included in\n\/\/\/ *_scom_addresses_fld.H and allows incorrect constants to be\n\/\/\/ fixed manually.\n\/\/\/\n\/\/ *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>\n\/\/ *HWP FW Owner: ? <?>\n\/\/ *HWP Team: SAO\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE\n\n#ifndef __P9_MISC_SCOM_ADDRESSES_FLD_FIXES_H\n#define __P9_MISC_SCOM_ADDRESSES_FLD_FIXES_H\n\n\/\/ N2 Chiplet Config Register1\nREG64_FLD(PERV_N2_CPLT_CONF1_TC_PSI_IOVALID_DC, 10, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Receive Status Register\nREG64_FLD(PU_RX_PSI_STATUS_CHECK_PASS, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_RX_PSI_STATUS_CHECK_FAIL, 1, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Control Register\nREG64_FLD(PU_TX_PSI_CNTL_IORESET, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Receive Control Register\nREG64_FLD(PU_RX_PSI_CNTL_IORESET, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Channel Internal Address Register\nREG64_FLD(PU_TX_CH_INTADDR_IAR_ADDR, 0, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_INTADDR_IAR_ADDR_LEN, 8, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ PSI Transmit Channel Misc Register\nREG64_FLD(PU_TX_CH_MISC_WEN0, 12, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_MISC_WEN1, 13, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PU_TX_CH_MISC_WEN2, 14, SH_UNT, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/ RX VGA Control Register1\nREG64_FLD(PEC_SCOM0X0B_EDMOD, 52, SH_UNT_PEC, SH_ACS_SCOM, SH_FLD_UNUSED);\nREG64_FLD(PEC_SCOM0X0B_EDMOD_LEN, 2, SH_UNT_PEC, SH_ACS_SCOM, SH_FLD_UNUSED);\n\n\/\/Example\n\/\/Copy the whole line from the *scom_addresses_fld.H file. Then add FIX in front of REG\n\/\/and add another paramter that is the new value you want.\n\/\/\n\/\/FIXREG64_FLD( PU_ALTD_CMD_REG_FBC_WITH_TM_QUIESCE, 24, SH_UNT, SH_ACS_SCOM, SH_FLD_FBC_WITH_TM_QUIESCE,\n\/\/ 12);\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_erepairAccessorHwpFuncs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_erepairAccessorHwpFuncs.C\n\/\/\/ @brief FW Team utility functions that access fabric and memory eRepair data.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n#include <fapi2.H>\n#include <string.h>\n#include <p9_io_erepairConsts.H>\n\nusing namespace EREPAIR;\nusing namespace fapi2;\n\n\/***** Function definitions *****\/\n\n\/**\n * @brief This function checks to see if the passed vectors have matching\n * fail lane numbers. If no matching lane number is found, such lane\n * value will be invalidated in the vector\n *\n * @param [in] io_endp1_txFaillanes Reference to vector which has fail\n * lane numbers of Tx side\n * @param [in] io_endp2_rxFaillanes Reference to vector which has fail\n * lane numbers of Rx side\n * @param [out] o_invalidFails_inTx_Ofendp1 If TRUE, indicates that Tx has fail\n * lane numbers for which there is no\n * matching entry on Rx side\n * @param [out] o_invalidFails_inRx_Ofendp2 If TRUE, indicates that Tx has fail\n * lane numbers for which there is no\n * matching entry on Tx side\n *\n * @return void\n *\/\nvoid invalidateNonMatchingFailLanes(std::vector<uint8_t>& io_endp1_txFaillanes,\n std::vector<uint8_t>& io_endp2_rxFaillanes,\n bool& o_invalidFails_inTx_Ofendp1,\n bool& o_invalidFails_inRx_Ofendp2)\n{\n std::vector<uint8_t>::iterator l_it;\n std::vector<uint8_t>::iterator l_itTmp;\n std::vector<uint8_t>::iterator l_itDrv;\n std::vector<uint8_t>::iterator l_itRcv;\n\n o_invalidFails_inTx_Ofendp1 = false;\n o_invalidFails_inRx_Ofendp2 = false;\n\n std::sort(io_endp1_txFaillanes.begin(), io_endp1_txFaillanes.end());\n std::sort(io_endp2_rxFaillanes.begin(), io_endp2_rxFaillanes.end());\n\n \/\/ Start with drive side fail lanes and check for matching lanes\n \/\/ on the recieve side\n l_itTmp = io_endp2_rxFaillanes.begin();\n\n for(l_itDrv = io_endp1_txFaillanes.begin();\n l_itDrv != io_endp1_txFaillanes.end();\n l_itDrv++)\n {\n l_it = std::lower_bound(io_endp2_rxFaillanes.begin(),\n io_endp2_rxFaillanes.end(),\n *l_itDrv);\n\n \/\/ If matching fail lane is not found on the receive side,\n \/\/ invalidate the drive side fail lane number\n if((l_it == io_endp2_rxFaillanes.end()) || (*l_it > *l_itDrv))\n {\n *l_itDrv = INVALID_FAIL_LANE_NUMBER;\n o_invalidFails_inTx_Ofendp1 = true;\n }\n else\n {\n \/\/ save the iterator for the next search\n l_itTmp = l_it;\n }\n }\n\n \/\/ Sort again as we might have invalidated some lanes\n std::sort(io_endp1_txFaillanes.begin(), io_endp1_txFaillanes.end());\n\n \/\/ Now, traverse through the receive side fail lanes and\n \/\/ check for matching lanes on the drive side\n for(l_itRcv = io_endp2_rxFaillanes.begin();\n ((l_itRcv <= l_itTmp) && (l_itRcv != io_endp2_rxFaillanes.end()));\n l_itRcv++)\n {\n l_it = std::lower_bound(io_endp1_txFaillanes.begin(),\n io_endp1_txFaillanes.end(),\n *l_itRcv);\n\n \/\/ If matching lane is not found on the driver side,\n \/\/ invalidate the receive side fail lane number\n if((l_it == io_endp1_txFaillanes.end()) || (*l_it > *l_itRcv))\n {\n *l_itRcv = INVALID_FAIL_LANE_NUMBER;\n o_invalidFails_inRx_Ofendp2 = true;\n }\n }\n\n \/\/ Need to invalidate all the entries beyond the last\n \/\/ lower bound of first search\n if(l_itTmp != io_endp2_rxFaillanes.end())\n {\n for(l_itTmp++; l_itTmp != io_endp2_rxFaillanes.end(); l_itTmp++)\n {\n *l_itTmp = INVALID_FAIL_LANE_NUMBER;\n }\n }\n}\n\n\/**\n * @brief This function combines the eRepair lane numbers read from\n * Manufacturing VPD and Field VPD\n *\n * @param [in] i_mnfgFaillanes The eRepair lane numbers read from the\n * Manufacturing VPD\n * @param [in] i_fieldFaillanes The eRepair lane numbers read from the\n * Field VPD\n * @param [out] o_allFaillanes The eRepair lane numbers which is the union\n * of the Field and Manufacturing eRepair lanes\n * passed as first iand second params\n *\n * @return void\n *\/\nvoid combineFieldandMnfgLanes(std::vector<uint8_t>& i_mnfgFaillanes,\n std::vector<uint8_t>& i_fieldFaillanes,\n std::vector<uint8_t>& o_allFaillanes)\n{\n std::vector<uint8_t>::iterator l_it;\n\n \/\/ Merge the Field and Mnfg fail lanes\n l_it = o_allFaillanes.begin();\n o_allFaillanes.insert(l_it,\n i_mnfgFaillanes.begin(),\n i_mnfgFaillanes.end());\n\n l_it = o_allFaillanes.end();\n o_allFaillanes.insert(l_it,\n i_fieldFaillanes.begin(),\n i_fieldFaillanes.end());\n\n \/\/ Check if Mfg VPD and Field VPD have same fail lanes.\n \/\/ If found, erase them\n std::sort(o_allFaillanes.begin(), o_allFaillanes.end());\n\n o_allFaillanes.erase(std::unique(o_allFaillanes.begin(),\n o_allFaillanes.end()),\n o_allFaillanes.end());\n\n}\n<commit_msg>eRepair: Fix to invalidate vpd records correctly<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_erepairAccessorHwpFuncs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_erepairAccessorHwpFuncs.C\n\/\/\/ @brief FW Team utility functions that access fabric and memory eRepair data.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n#include <fapi2.H>\n#include <string.h>\n#include <p9_io_erepairConsts.H>\n\nusing namespace EREPAIR;\nusing namespace fapi2;\n\n\/***** Function definitions *****\/\n\n\/**\n * @brief This function checks to see if the passed vectors have matching\n * fail lane numbers. If no matching lane number is found, such lane\n * value will be invalidated in the vector\n *\n * @param [in] io_endp1_txFaillanes Reference to vector which has fail\n * lane numbers of Tx side\n * @param [in] io_endp2_rxFaillanes Reference to vector which has fail\n * lane numbers of Rx side\n * @param [out] o_invalidFails_inTx_Ofendp1 If TRUE, indicates that Tx has fail\n * lane numbers for which there is no\n * matching entry on Rx side\n * @param [out] o_invalidFails_inRx_Ofendp2 If TRUE, indicates that Tx has fail\n * lane numbers for which there is no\n * matching entry on Tx side\n *\n * @return void\n *\/\nvoid invalidateNonMatchingFailLanes(std::vector<uint8_t>& io_endp1_txFaillanes,\n std::vector<uint8_t>& io_endp2_rxFaillanes,\n bool& o_invalidFails_inTx_Ofendp1,\n bool& o_invalidFails_inRx_Ofendp2)\n{\n std::vector<uint8_t>::iterator l_it;\n std::vector<uint8_t>::iterator l_itTmp;\n std::vector<uint8_t>::iterator l_itDrv;\n std::vector<uint8_t>::iterator l_itRcv;\n\n FAPI_INF(\"invalidateNonMatchingFailLanes - endp1Tx size:%llu endp2Rx size:%llu\",\n io_endp1_txFaillanes.size(), io_endp2_rxFaillanes.size());\n\n for(unsigned long i = 0; (i < io_endp1_txFaillanes.size() && io_endp1_txFaillanes.size() != 0); i++)\n {\n FAPI_INF(\"Endp1Tx(%lu):%llu \", i, io_endp1_txFaillanes[i]);\n }\n\n for(unsigned long i = 0; (i < io_endp2_rxFaillanes.size() && io_endp2_rxFaillanes.size() != 0); i++)\n {\n FAPI_INF(\"Endp2Rx(%lu):%llu \", i, io_endp2_rxFaillanes[i]);\n }\n\n o_invalidFails_inTx_Ofendp1 = false;\n o_invalidFails_inRx_Ofendp2 = false;\n\n std::sort(io_endp1_txFaillanes.begin(), io_endp1_txFaillanes.end());\n std::sort(io_endp2_rxFaillanes.begin(), io_endp2_rxFaillanes.end());\n\n \/\/ Start with drive side fail lanes and check for matching lanes\n \/\/ on the recieve side\n l_itTmp = io_endp2_rxFaillanes.begin();\n\n for(l_itDrv = io_endp1_txFaillanes.begin();\n l_itDrv != io_endp1_txFaillanes.end();\n l_itDrv++)\n {\n l_it = std::lower_bound(io_endp2_rxFaillanes.begin(),\n io_endp2_rxFaillanes.end(),\n *l_itDrv);\n\n \/\/ If matching fail lane is not found on the receive side,\n \/\/ invalidate the drive side fail lane number\n if((l_it == io_endp2_rxFaillanes.end()) || (*l_it > *l_itDrv))\n {\n *l_itDrv = INVALID_FAIL_LANE_NUMBER;\n o_invalidFails_inTx_Ofendp1 = true;\n }\n else\n {\n \/\/ save the iterator for the next search\n l_itTmp = l_it;\n }\n }\n\n \/\/ Sort again as we might have invalidated some lanes\n std::sort(io_endp1_txFaillanes.begin(), io_endp1_txFaillanes.end());\n\n \/\/ Now, traverse through the receive side fail lanes and\n \/\/ check for matching lanes on the drive side\n for(l_itRcv = io_endp2_rxFaillanes.begin();\n ((l_itRcv <= l_itTmp) && (l_itRcv != io_endp2_rxFaillanes.end()));\n l_itRcv++)\n {\n l_it = std::lower_bound(io_endp1_txFaillanes.begin(),\n io_endp1_txFaillanes.end(),\n *l_itRcv);\n\n \/\/ If matching lane is not found on the driver side,\n \/\/ invalidate the receive side fail lane number\n if((l_it == io_endp1_txFaillanes.end()) || (*l_it > *l_itRcv))\n {\n *l_itRcv = INVALID_FAIL_LANE_NUMBER;\n o_invalidFails_inRx_Ofendp2 = true;\n }\n }\n\n \/\/ Need to invalidate all the entries beyond the last\n \/\/ lower bound of first search\n if(l_itTmp != io_endp2_rxFaillanes.end())\n {\n for(l_itTmp++; l_itTmp != io_endp2_rxFaillanes.end(); l_itTmp++)\n {\n *l_itTmp = INVALID_FAIL_LANE_NUMBER;\n }\n }\n}\n\n\/**\n * @brief This function combines the eRepair lane numbers read from\n * Manufacturing VPD and Field VPD\n *\n * @param [in] i_mnfgFaillanes The eRepair lane numbers read from the\n * Manufacturing VPD\n * @param [in] i_fieldFaillanes The eRepair lane numbers read from the\n * Field VPD\n * @param [out] o_allFaillanes The eRepair lane numbers which is the union\n * of the Field and Manufacturing eRepair lanes\n * passed as first iand second params\n *\n * @return void\n *\/\nvoid combineFieldandMnfgLanes(std::vector<uint8_t>& i_mnfgFaillanes,\n std::vector<uint8_t>& i_fieldFaillanes,\n std::vector<uint8_t>& o_allFaillanes)\n{\n std::vector<uint8_t>::iterator l_it;\n\n FAPI_INF(\"combineFieldandMnfgLanes - mnfgFailLanes size:%llu fieldFailLanes size:%llu\",\n i_mnfgFaillanes.size(), i_fieldFaillanes.size());\n\n \/\/ Merge the Field and Mnfg fail lanes\n l_it = o_allFaillanes.begin();\n o_allFaillanes.insert(l_it,\n i_mnfgFaillanes.begin(),\n i_mnfgFaillanes.end());\n\n l_it = o_allFaillanes.end();\n o_allFaillanes.insert(l_it,\n i_fieldFaillanes.begin(),\n i_fieldFaillanes.end());\n\n \/\/ Check if Mfg VPD and Field VPD have same fail lanes.\n \/\/ If found, erase them\n std::sort(o_allFaillanes.begin(), o_allFaillanes.end());\n\n o_allFaillanes.erase(std::unique(o_allFaillanes.begin(),\n o_allFaillanes.end()),\n o_allFaillanes.end());\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file navigator_rtl.cpp\n * Helper class to access RTL\n * @author Julian Oes <julian@oes.ch>\n * @author Anton Babushkin <anton.babushkin@me.com>\n *\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n#include <fcntl.h>\n#include <float.h>\n\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/err.h>\n#include <geo\/geo.h>\n\n#include <uORB\/uORB.h>\n#include <navigator\/navigation.h>\n#include <uORB\/topics\/home_position.h>\n#include <uORB\/topics\/vtol_vehicle_status.h>\n\n#include \"navigator.h\"\n#include \"rtl.h\"\n\n#define DELAY_SIGMA\t0.01f\n\nRTL::RTL(Navigator *navigator, const char *name) :\n\tMissionBlock(navigator, name),\n\t_rtl_state(RTL_STATE_NONE),\n\t_param_return_alt(this, \"RTL_RETURN_ALT\", false),\n\t_param_min_loiter_alt(this, \"MIS_LTRMIN_ALT\", false),\n\t_param_descend_alt(this, \"RTL_DESCEND_ALT\", false),\n\t_param_land_delay(this, \"RTL_LAND_DELAY\", false),\n\t_param_rtl_min_dist(this, \"RTL_MIN_DIST\", false)\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nRTL::~RTL()\n{\n}\n\nvoid\nRTL::on_inactive()\n{\n\t\/\/ reset RTL state\n\t_rtl_state = RTL_STATE_NONE;\n}\n\nfloat\nRTL::get_rtl_altitude()\n{\n\treturn (_param_return_alt.get() < _navigator->get_land_detected()->alt_max) ? _param_return_alt.get() :\n\t _navigator->get_land_detected()->alt_max;\n}\n\nvoid\nRTL::on_activation()\n{\n\tset_current_position_item(&_mission_item);\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->previous.valid = false;\n\tpos_sp_triplet->next.valid = false;\n\n\t\/* for safety reasons don't go into RTL if landed *\/\n\tif (_navigator->get_land_detected()->landed) {\n\t\t_rtl_state = RTL_STATE_LANDED;\n\t\tmavlink_log_critical(_navigator->get_mavlink_log_pub(), \"Already landed, not executing RTL\");\n\n\t\t\/* if lower than return altitude, climb up first *\/\n\n\t} else if (_navigator->get_global_position()->alt < (_navigator->get_home_position()->alt\n\t\t\t+ get_rtl_altitude())) {\n\t\t_rtl_state = RTL_STATE_CLIMB;\n\n\t\t\/* otherwise go straight to return *\/\n\n\t} else {\n\t\t\/* set altitude setpoint to current altitude *\/\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_global_position()->alt;\n\t}\n\n\tset_rtl_item();\n}\n\nvoid\nRTL::on_active()\n{\n\tif (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {\n\t\tadvance_rtl();\n\t\tset_rtl_item();\n\t}\n}\n\nvoid\nRTL::set_rtl_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t_navigator->set_can_loiter_at_sp(false);\n\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB: {\n\n\t\t\t\/\/ check if we are pretty close to home already\n\t\t\tfloat home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat,\n\t\t\t\t\t _navigator->get_home_position()->lon,\n\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon);\n\n\t\t\t\/\/ if we are close to home we do not climb as high, otherwise we climb to return alt\n\t\t\tfloat climb_alt = _navigator->get_home_position()->alt + get_rtl_altitude();\n\n\t\t\t\/\/ we are close to home, limit climb to min\n\t\t\tif (home_dist < _param_rtl_min_dist.get()) {\n\t\t\t\tclimb_alt = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\t\t\t}\n\n\t\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t\t_mission_item.altitude_is_relative = false;\n\t\t\t_mission_item.altitude = climb_alt;\n\t\t\t_mission_item.yaw = NAN;\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = true;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: climb to %d m (%d m above home)\",\n\t\t\t\t\t (int)(climb_alt),\n\t\t\t\t\t (int)(climb_alt - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_RETURN: {\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t\/\/ don't change altitude\n\n\t\t\t\/\/ use home yaw if close to home\n\t\t\t\/* check if we are pretty close to home already *\/\n\t\t\tfloat home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat,\n\t\t\t\t\t _navigator->get_home_position()->lon,\n\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon);\n\n\t\t\tif (home_dist < _param_rtl_min_dist.get()) {\n\t\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\t} else {\n\t\t\t\t\/\/ use current heading to home\n\t\t\t\t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t\t _navigator->get_home_position()->lat, _navigator->get_home_position()->lon);\n\t\t\t}\n\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = true;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: return at %d m (%d m above home)\",\n\t\t\t\t\t (int)(_mission_item.altitude),\n\t\t\t\t\t (int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_TRANSITION_TO_MC: {\n\t\t\t_mission_item.nav_cmd = NAV_CMD_DO_VTOL_TRANSITION;\n\t\t\t_mission_item.params[0] = vtol_vehicle_status_s::VEHICLE_VTOL_STATE_MC;\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_DESCEND: {\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t_mission_item.altitude_is_relative = false;\n\t\t\t_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\n\t\t\t\/\/ check if we are already lower - then we will just stay there\n\t\t\tif (_mission_item.altitude > _navigator->get_global_position()->alt) {\n\t\t\t\t_mission_item.altitude = _navigator->get_global_position()->alt;\n\t\t\t}\n\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\t\/\/ except for vtol which might be still off here and should point towards this location\n\t\t\tfloat d_current = get_distance_to_next_waypoint(\n\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t _mission_item.lat, _mission_item.lon);\n\n\t\t\tif (_navigator->get_vstatus()->is_vtol && d_current > _navigator->get_acceptance_radius()) {\n\t\t\t\t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t\t _mission_item.lat, _mission_item.lon);\n\t\t\t}\n\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = false;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\t\/* disable previous setpoint to prevent drift *\/\n\t\t\tpos_sp_triplet->previous.valid = false;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: descend to %d m (%d m above home)\",\n\t\t\t\t\t (int)(_mission_item.altitude),\n\t\t\t\t\t (int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LOITER: {\n\t\t\tbool autoland = _param_land_delay.get() > -DELAY_SIGMA;\n\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t\/\/ don't change altitude\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();\n\t\t\t_mission_item.autocontinue = autoland;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\t_navigator->set_can_loiter_at_sp(true);\n\n\t\t\tif (autoland && (Navigator::get_time_inside(_mission_item) > FLT_EPSILON)) {\n\t\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: loiter %.1fs\",\n\t\t\t\t\t\t (double)Navigator::get_time_inside(_mission_item));\n\n\t\t\t} else {\n\t\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: completed, loiter\");\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LAND: {\n\t\t\tset_land_item(&_mission_item, false);\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: land at home\");\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LANDED: {\n\t\t\tset_idle_item(&_mission_item);\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: completed, landed\");\n\t\t\tbreak;\n\t\t}\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treset_mission_item_reached();\n\n\t\/* execute command if set *\/\n\tif (!item_contains_position(&_mission_item)) {\n\t\tissue_command(&_mission_item);\n\t}\n\n\t\/* convert mission item to current position setpoint and make it valid *\/\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->next.valid = false;\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nRTL::advance_rtl()\n{\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_RETURN:\n\t\t_rtl_state = RTL_STATE_DESCEND;\n\n\t\tif (_navigator->get_vstatus()->is_vtol && !_navigator->get_vstatus()->is_rotary_wing) {\n\t\t\t_rtl_state = RTL_STATE_TRANSITION_TO_MC;\n\t\t}\n\n\t\tbreak;\n\n\tcase RTL_STATE_TRANSITION_TO_MC:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_DESCEND:\n\n\t\t\/* only go to land if autoland is enabled *\/\n\t\tif (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {\n\t\t\t_rtl_state = RTL_STATE_LOITER;\n\n\t\t} else {\n\t\t\t_rtl_state = RTL_STATE_LAND;\n\t\t}\n\n\t\tbreak;\n\n\tcase RTL_STATE_LOITER:\n\t\t_rtl_state = RTL_STATE_LAND;\n\t\tbreak;\n\n\tcase RTL_STATE_LAND:\n\t\t_rtl_state = RTL_STATE_LANDED;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n<commit_msg>Navigator: Fix RTL state handling by enabling auto-continue after descend<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file navigator_rtl.cpp\n * Helper class to access RTL\n * @author Julian Oes <julian@oes.ch>\n * @author Anton Babushkin <anton.babushkin@me.com>\n *\/\n\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n#include <fcntl.h>\n#include <float.h>\n\n#include <systemlib\/mavlink_log.h>\n#include <systemlib\/err.h>\n#include <geo\/geo.h>\n\n#include <uORB\/uORB.h>\n#include <navigator\/navigation.h>\n#include <uORB\/topics\/home_position.h>\n#include <uORB\/topics\/vtol_vehicle_status.h>\n\n#include \"navigator.h\"\n#include \"rtl.h\"\n\n#define DELAY_SIGMA\t0.01f\n\nRTL::RTL(Navigator *navigator, const char *name) :\n\tMissionBlock(navigator, name),\n\t_rtl_state(RTL_STATE_NONE),\n\t_param_return_alt(this, \"RTL_RETURN_ALT\", false),\n\t_param_min_loiter_alt(this, \"MIS_LTRMIN_ALT\", false),\n\t_param_descend_alt(this, \"RTL_DESCEND_ALT\", false),\n\t_param_land_delay(this, \"RTL_LAND_DELAY\", false),\n\t_param_rtl_min_dist(this, \"RTL_MIN_DIST\", false)\n{\n\t\/* load initial params *\/\n\tupdateParams();\n\t\/* initial reset *\/\n\ton_inactive();\n}\n\nRTL::~RTL()\n{\n}\n\nvoid\nRTL::on_inactive()\n{\n\t\/\/ reset RTL state\n\t_rtl_state = RTL_STATE_NONE;\n}\n\nfloat\nRTL::get_rtl_altitude()\n{\n\treturn (_param_return_alt.get() < _navigator->get_land_detected()->alt_max) ? _param_return_alt.get() :\n\t _navigator->get_land_detected()->alt_max;\n}\n\nvoid\nRTL::on_activation()\n{\n\tset_current_position_item(&_mission_item);\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->previous.valid = false;\n\tpos_sp_triplet->next.valid = false;\n\n\t\/* for safety reasons don't go into RTL if landed *\/\n\tif (_navigator->get_land_detected()->landed) {\n\t\t_rtl_state = RTL_STATE_LANDED;\n\t\tmavlink_log_critical(_navigator->get_mavlink_log_pub(), \"Already landed, not executing RTL\");\n\n\t\t\/* if lower than return altitude, climb up first *\/\n\n\t} else if (_navigator->get_global_position()->alt < (_navigator->get_home_position()->alt\n\t\t\t+ get_rtl_altitude())) {\n\t\t_rtl_state = RTL_STATE_CLIMB;\n\n\t\t\/* otherwise go straight to return *\/\n\n\t} else {\n\t\t\/* set altitude setpoint to current altitude *\/\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\t_mission_item.altitude_is_relative = false;\n\t\t_mission_item.altitude = _navigator->get_global_position()->alt;\n\t}\n\n\tset_rtl_item();\n}\n\nvoid\nRTL::on_active()\n{\n\tif (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {\n\t\tadvance_rtl();\n\t\tset_rtl_item();\n\t}\n}\n\nvoid\nRTL::set_rtl_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t_navigator->set_can_loiter_at_sp(false);\n\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB: {\n\n\t\t\t\/\/ check if we are pretty close to home already\n\t\t\tfloat home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat,\n\t\t\t\t\t _navigator->get_home_position()->lon,\n\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon);\n\n\t\t\t\/\/ if we are close to home we do not climb as high, otherwise we climb to return alt\n\t\t\tfloat climb_alt = _navigator->get_home_position()->alt + get_rtl_altitude();\n\n\t\t\t\/\/ we are close to home, limit climb to min\n\t\t\tif (home_dist < _param_rtl_min_dist.get()) {\n\t\t\t\tclimb_alt = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\t\t\t}\n\n\t\t\t_mission_item.lat = _navigator->get_global_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_global_position()->lon;\n\t\t\t_mission_item.altitude_is_relative = false;\n\t\t\t_mission_item.altitude = climb_alt;\n\t\t\t_mission_item.yaw = NAN;\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = true;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: climb to %d m (%d m above home)\",\n\t\t\t\t\t (int)(climb_alt),\n\t\t\t\t\t (int)(climb_alt - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_RETURN: {\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t\/\/ don't change altitude\n\n\t\t\t\/\/ use home yaw if close to home\n\t\t\t\/* check if we are pretty close to home already *\/\n\t\t\tfloat home_dist = get_distance_to_next_waypoint(_navigator->get_home_position()->lat,\n\t\t\t\t\t _navigator->get_home_position()->lon,\n\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon);\n\n\t\t\tif (home_dist < _param_rtl_min_dist.get()) {\n\t\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\t} else {\n\t\t\t\t\/\/ use current heading to home\n\t\t\t\t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t\t _navigator->get_home_position()->lat, _navigator->get_home_position()->lon);\n\t\t\t}\n\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = true;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: return at %d m (%d m above home)\",\n\t\t\t\t\t (int)(_mission_item.altitude),\n\t\t\t\t\t (int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_TRANSITION_TO_MC: {\n\t\t\t_mission_item.nav_cmd = NAV_CMD_DO_VTOL_TRANSITION;\n\t\t\t_mission_item.params[0] = vtol_vehicle_status_s::VEHICLE_VTOL_STATE_MC;\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_DESCEND: {\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t_mission_item.altitude_is_relative = false;\n\t\t\t_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();\n\n\t\t\t\/\/ check if we are already lower - then we will just stay there\n\t\t\tif (_mission_item.altitude > _navigator->get_global_position()->alt) {\n\t\t\t\t_mission_item.altitude = _navigator->get_global_position()->alt;\n\t\t\t}\n\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\t\/\/ except for vtol which might be still off here and should point towards this location\n\t\t\tfloat d_current = get_distance_to_next_waypoint(\n\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t _mission_item.lat, _mission_item.lon);\n\n\t\t\tif (_navigator->get_vstatus()->is_vtol && d_current > _navigator->get_acceptance_radius()) {\n\t\t\t\t_mission_item.yaw = get_bearing_to_next_waypoint(\n\t\t\t\t\t\t\t _navigator->get_global_position()->lat, _navigator->get_global_position()->lon,\n\t\t\t\t\t\t\t _mission_item.lat, _mission_item.lon);\n\t\t\t}\n\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = NAV_CMD_WAYPOINT;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = 0.0f;\n\t\t\t_mission_item.autocontinue = true;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\t\/* disable previous setpoint to prevent drift *\/\n\t\t\tpos_sp_triplet->previous.valid = false;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: descend to %d m (%d m above home)\",\n\t\t\t\t\t (int)(_mission_item.altitude),\n\t\t\t\t\t (int)(_mission_item.altitude - _navigator->get_home_position()->alt));\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LOITER: {\n\t\t\tbool autoland = _param_land_delay.get() > -DELAY_SIGMA;\n\n\t\t\t_mission_item.lat = _navigator->get_home_position()->lat;\n\t\t\t_mission_item.lon = _navigator->get_home_position()->lon;\n\t\t\t\/\/ don't change altitude\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\t\t\t_mission_item.loiter_radius = _navigator->get_loiter_radius();\n\t\t\t_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;\n\t\t\t_mission_item.acceptance_radius = _navigator->get_acceptance_radius();\n\t\t\t_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();\n\t\t\t_mission_item.autocontinue = autoland;\n\t\t\t_mission_item.origin = ORIGIN_ONBOARD;\n\n\t\t\t_navigator->set_can_loiter_at_sp(true);\n\n\t\t\tif (autoland && (Navigator::get_time_inside(_mission_item) > FLT_EPSILON)) {\n\t\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: loiter %.1fs\",\n\t\t\t\t\t\t (double)Navigator::get_time_inside(_mission_item));\n\n\t\t\t} else {\n\t\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: completed, loiter\");\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LAND: {\n\t\t\tset_land_item(&_mission_item, false);\n\t\t\t_mission_item.yaw = _navigator->get_home_position()->yaw;\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: land at home\");\n\t\t\tbreak;\n\t\t}\n\n\tcase RTL_STATE_LANDED: {\n\t\t\tset_idle_item(&_mission_item);\n\n\t\t\tmavlink_log_info(_navigator->get_mavlink_log_pub(), \"RTL: completed, landed\");\n\t\t\tbreak;\n\t\t}\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treset_mission_item_reached();\n\n\t\/* execute command if set *\/\n\tif (!item_contains_position(&_mission_item)) {\n\t\tissue_command(&_mission_item);\n\t}\n\n\t\/* convert mission item to current position setpoint and make it valid *\/\n\tmission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);\n\tpos_sp_triplet->next.valid = false;\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nRTL::advance_rtl()\n{\n\tswitch (_rtl_state) {\n\tcase RTL_STATE_CLIMB:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_RETURN:\n\t\t_rtl_state = RTL_STATE_DESCEND;\n\n\t\tif (_navigator->get_vstatus()->is_vtol && !_navigator->get_vstatus()->is_rotary_wing) {\n\t\t\t_rtl_state = RTL_STATE_TRANSITION_TO_MC;\n\t\t}\n\n\t\tbreak;\n\n\tcase RTL_STATE_TRANSITION_TO_MC:\n\t\t_rtl_state = RTL_STATE_RETURN;\n\t\tbreak;\n\n\tcase RTL_STATE_DESCEND:\n\n\t\t\/* only go to land if autoland is enabled *\/\n\t\tif (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {\n\t\t\t_rtl_state = RTL_STATE_LOITER;\n\n\t\t} else {\n\t\t\t_rtl_state = RTL_STATE_LAND;\n\t\t}\n\n\t\tbreak;\n\n\tcase RTL_STATE_LOITER:\n\t\t_rtl_state = RTL_STATE_LAND;\n\t\tbreak;\n\n\tcase RTL_STATE_LAND:\n\t\t_rtl_state = RTL_STATE_LANDED;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ inputSystem.cpp\n\/\/ YorkshireTea\n\/\/\n\/\/ Created by Karl Jacques on 24\/05\/2014.\n\/\/\n\/\/\n\n#include <SDL.h>\n#include \"inputSystem.h\"\n#include \"..\/event\/eventSystem.h\"\n\nInputSystem::InputSystem( EventSystem* eventSys, SDL_Window* window )\n{\n\tm_EventSystem = eventSys;\n\tmWindow = window;\n\tmWindowActive = true;\n\n\tSDL_ShowCursor( false );\n\n}\n\nvoid InputSystem::update()\n{\n\twhile( SDL_PollEvent( &m_inputEvent ) )\n\t{\n\t\tswitch(m_inputEvent.type )\n\t\t{\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t{\n\t\t\t\t\/\/ Key down, create and dispatch event\n\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_KEY_PRESS );\n\t\t\t\te->mPressed = true;\n\t\t\t\te->mReleased =false;\n\t\t\t\te->mKeycode = m_inputEvent.key.keysym.scancode;\n\t\t\t\tm_EventSystem->dispatchEvent( e );\n\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase SDL_KEYUP:\n\t\t\t{\n\t\t\t\t\/\/ Key down, create and dispatch event\n\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_KEY_RELEASE );\n\t\t\t\te->mPressed = false;\n\t\t\t\te->mReleased = true;\n\t\t\t\te->mKeycode = m_inputEvent.key.keysym.scancode;\n\t\t\t\tm_EventSystem->dispatchEvent( e );\n\n\t\t\t\t\/\/TODO Hack, so what.\n\t\t\t\tif( e->mKeycode == SDL_SCANCODE_COMMA )\n\t\t\t\t\tmWindowActive=!mWindowActive;\n\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase SDL_TEXTINPUT:\n\t\t\t\t{\n\t\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_TEXT_INPUT);\n\t\t\t\t\te->mKey = *m_inputEvent.text.text;\n\t\t\t\t\tm_EventSystem->dispatchEvent(e);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\n\t\t}\n\t}\n\t\/\/ TODO make this take half window values\n\tif( mWindowActive)\n\t{\n\t\tint MouseX,MouseY;\n\t\tSDL_GetMouseState(&MouseX,&MouseY);\n\t\tint DeltaX = MouseX - 400;\n\t\tint DeltaY = MouseY - 300;\n\t\tMouseEvent* e = new MouseEvent( EV_CORE_MOUSE_MOVEMENT );\n\t\te->mMouseMoveX = DeltaX;\n\t\te->mMouseMoveY = DeltaY;\n\n\t\tm_EventSystem->dispatchEvent( e );\n\t\tSDL_WarpMouseInWindow( mWindow, 400, 300 );\n\t}\n}\n<commit_msg>Window focus taken into account when grabbing mouse<commit_after>\/\/\n\/\/ inputSystem.cpp\n\/\/ YorkshireTea\n\/\/\n\/\/ Created by Karl Jacques on 24\/05\/2014.\n\/\/\n\/\/\n\n#include <SDL.h>\n#include \"inputSystem.h\"\n#include \"..\/event\/eventSystem.h\"\n\nInputSystem::InputSystem( EventSystem* eventSys, SDL_Window* window )\n{\n\tm_EventSystem = eventSys;\n\tmWindow = window;\n\tmWindowActive = true;\n\n\tSDL_ShowCursor( false );\n\n}\n\nvoid InputSystem::update()\n{\n\twhile( SDL_PollEvent( &m_inputEvent ) )\n\t{\n\t\tswitch(m_inputEvent.type )\n\t\t{\n\t\t\tcase SDL_WINDOWEVENT_FOCUS_GAINED:\n\t\t\t\tmWindowActive = true;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_WINDOWEVENT_HIDDEN:\n\t\t\t\tmWindowActive = false;\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t{\n\t\t\t\t\/\/ Key down, create and dispatch event\n\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_KEY_PRESS );\n\t\t\t\te->mPressed = true;\n\t\t\t\te->mReleased =false;\n\t\t\t\te->mKeycode = m_inputEvent.key.keysym.scancode;\n\t\t\t\tm_EventSystem->dispatchEvent( e );\n\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase SDL_KEYUP:\n\t\t\t\t{\n\t\t\t\t\t\/\/ Key down, create and dispatch event\n\t\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_KEY_RELEASE );\n\t\t\t\t\te->mPressed = false;\n\t\t\t\t\te->mReleased = true;\n\t\t\t\t\te->mKeycode = m_inputEvent.key.keysym.scancode;\n\t\t\t\t\tm_EventSystem->dispatchEvent( e );\n\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase SDL_TEXTINPUT:\n\t\t\t\t{\n\t\t\t\t\tKeyboardEvent*\te = new KeyboardEvent(EV_CORE_TEXT_INPUT);\n\t\t\t\t\te->mKey = *m_inputEvent.text.text;\n\t\t\t\t\tm_EventSystem->dispatchEvent(e);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase SDL_WINDOWEVENT:\n\t\t\t\tswitch( m_inputEvent.window.event )\n\t\t\t\t{\n\t\t\t\tcase SDL_WINDOWEVENT_FOCUS_GAINED:\n\t\t\t\t\tmWindowActive = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SDL_WINDOWEVENT_FOCUS_LOST:\n\t\t\t\t\tmWindowActive = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\n\t\t}\n\t}\n\t\/\/ TODO make this take half window values\n\tif( mWindowActive)\n\t{\n\t\tint MouseX,MouseY;\n\t\tSDL_GetMouseState(&MouseX,&MouseY);\n\t\tint DeltaX = MouseX - 400;\n\t\tint DeltaY = MouseY - 300;\n\t\tMouseEvent* e = new MouseEvent( EV_CORE_MOUSE_MOVEMENT );\n\t\te->mMouseMoveX = DeltaX;\n\t\te->mMouseMoveY = DeltaY;\n\n\t\tm_EventSystem->dispatchEvent( e );\n\t\tSDL_WarpMouseInWindow( mWindow, 400, 300 );\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file sched\/job.hh\n ** \\brief Definition of Job.\n *\/\n\n#ifndef SCHED_JOB_HH\n# define SCHED_JOB_HH\n\n# include <iosfwd>\n# include <list>\n\n# include <boost\/any.hpp>\n\n# include <libport\/symbol.hh>\n# include <libport\/utime.hh>\n\n# include <sched\/coroutine.hh>\n# include <sched\/export.hh>\n# include <sched\/fwd.hh>\n# include <sched\/tag.hh>\n\nnamespace sched\n{\n\n enum job_state\n {\n to_start, \/\/\/< Job needs to be started\n running, \/\/\/< Job is waiting for the CPU\n sleeping, \/\/\/< Job is sleeping until a specified deadline\n waiting, \/\/\/< Job is waiting for changes to happen\n joining, \/\/\/< Job is waiting for another job to terminate\n zombie, \/\/\/< Job wants to be dead but isn't really yet\n };\n\n \/\/\/ State names to string, for debugging purpose.\n const char* name(job_state);\n\n \/\/\/ Dump \\a s on \\a o for debugging purpose.\n std::ostream& operator<<(std::ostream& o, job_state s);\n\n \/\/\/ A Job represents a thread of control, implemented using coroutines.\n \/\/\/ The scheduler decides which job to launch and resumes its execution.\n \/\/\/ The lifetime of a job is the following\n \/\/\/\n \/\/\/ \\li Job() : job creation\n \/\/\/\n \/\/\/ \\li start_job() : add job to the scheduler; the scheduler\n \/\/\/ will call run(), and the job will\n \/\/\/ yield() itself into the scheduler run\n \/\/\/ queue during the course of work()\n \/\/\/\n \/\/\/ \\li work() : this method, which must be overridden,\n \/\/\/ does the real work\n \/\/\/\n \/\/\/ Due to the way coroutines work, a job may not delete itself\n \/\/\/ as once the coroutine structure has been freed, it is illegal to\n \/\/\/ continue its execution, even only to switch to another coroutine.\n \/\/\/ And if a job switches back to the scheduler before terminating its\n \/\/\/ destructor, the coroutine structure will not be freed. Because of\n \/\/\/ that, it is necessary for a job to be deleted by another one or\n \/\/\/ by the scheduler.\n \/\/\/\n \/\/\/ An additional constraint comes from the fact that even when a job\n \/\/\/ has terminated its work, its structure may not always be deleted.\n \/\/\/ For example, other jobs may have kept a reference to this job and\n \/\/\/ expect to retrieve some information (such as a result) after the\n \/\/\/ job termination.\n \/\/\/\n \/\/\/ We have several ways of dealing with those constraints and not leaking\n \/\/\/ memory upon a job termination:\n \/\/\/\n \/\/\/ \\li 1. Make sure the job spits out all the useful information concerning\n \/\/\/ its state by the way of inter-job communication before asking to\n \/\/\/ be deleted.\n \/\/\/\n \/\/\/ \\li 2. Make sure the job is kept alive as long as there is at least one\n \/\/\/ reference onto it, and that it gets deleted from another\n \/\/\/ coroutine, or from the main one.\n\n class SCHED_API Job: public libport::RefCounted\n {\n public:\n \/\/\/ Create a job from another one.\n \/\/\/\n \/\/\/ \\param model The parent job. The scheduler and tags will be inherited\n \/\/ from it.\n \/\/\/\n \/\/\/ \\param name The name of the new job, or a name derived from \\a model\n \/\/\/ if none is provided.\n Job(const Job& model, const libport::Symbol& name);\n\n \/\/\/ Create a new job.\n \/\/\/\n \/\/\/ \\param scheduler The scheduler to which this job will be attached.\n \/\/\/\n \/\/\/ \\param name The name of the new job, or an automatically created\n \/\/\/ one if none is provided.\n Job(Scheduler& scheduler, const libport::Symbol& name);\n\n \/\/\/ Job destructor.\n \/\/\/\n \/\/\/ The destructor is in charge of unscheduling the job in the\n \/\/\/ scheduler.\n virtual ~Job();\n\n \/\/\/ Get this job scheduler.\n \/\/\/\n \/\/\/ \\return A reference on the job scheduler.\n Scheduler& scheduler_get() const;\n\n \/\/\/ Dump internal data (for the developper).\n \/\/\/\n \/\/\/ \\return \\a o\n std::ostream& dump(std::ostream& o) const;\n\n \/\/\/ Get the underlying coroutine corresponding to this job.\n \/\/\/\n \/\/\/ \\return The coroutine structure.\n Coro* coro_get() const;\n\n \/\/\/ Has this job terminated?\n \/\/\/\n \/\/\/ \\return True if this job is in the \\c zombie state.\n bool terminated() const;\n\n \/\/\/ Start job by adding it to the scheduler.\n void start_job();\n\n \/\/\/ Run the job. This function is called from the scheduler.\n void run();\n\n \/\/\/ Terminate the job. The job will execute its cleanup method\n \/\/\/ and inform the scheduler that it is ready to be destroyed.\n \/\/\/ Must not be called by a child to an ancester of his.\n void terminate_now();\n\n \/\/\/ Asynchronous termination. Allows a child to kill its parent.\n \/\/\/ Will be killed at the next cycle.\n void terminate_asap();\n\n \/\/\/ Register this Job on its Scheduler so that it is rescheduled\n \/\/\/ during the next cycle. This should be called from the\n \/\/\/ currently scheduled job only but must be kept visible to be\n \/\/\/ callable from the primitives.\n \/\/\/ \\sa yield_until(), yield_until_terminated(),\n \/\/\/ yield_until_things_changed()\n void yield();\n\n \/\/\/ As yield(), but ask not to be woken up before the deadline.\n \/\/\/ \\sa yield(), yield_until_terminated(), yield_until_things_changed()\n void yield_until(libport::utime_t deadline);\n\n \/\/\/ Wait for another job to terminate before resuming execution of\n \/\/\/ the current one. If the other job has already terminated, the\n \/\/\/ caller will continue its execution.\n \/\/\/\n \/\/\/ \\param other The job to wait for. It is allowed to specify the\n \/\/\/ same Job as the target and the waiting job, in which case\n \/\/\/ the Job will only be woken up by an asynchronous exception.\n \/\/\/\n \/\/\/ \\sa yield(), yield_until(), yield_until_things_changed()\n void yield_until_terminated(Job& other);\n\n \/\/\/ Same as \\p yield_until_terminated above(), but wait for every\n \/\/\/ job in the collection.\n void yield_until_terminated(const jobs_type& jobs);\n\n \/\/\/ Wait for any other task to be scheduled.\n \/\/\/ \\sa yield(), yield_until_terminated(), yield_until()\n void yield_until_things_changed();\n\n \/\/\/ Mark the current job as side-effect free.\n \/\/\/\n \/\/\/ \\param s True if the job is now side-effect free.\n \/\/\/\n \/\/\/ Indicate whether the current state of a job may influence other\n \/\/\/ parts of the system. This is used by the scheduler to choose\n \/\/\/ whether other jobs need scheduling or not. The default value\n \/\/\/ for \\c side_effect_free is false.\n void side_effect_free_set(bool s);\n\n \/\/\/ Is the current job side-effect free?\n \/\/\/\n \/\/\/ \\return True if the job is currently side-effect free.\n bool side_effect_free_get() const;\n\n \/\/\/ Raise an exception next time this job will be resumed.\n \/\/\/\n \/\/\/ \\param e The exception to throw when the job will be scheduled\n \/\/\/ again.\n void async_throw(const exception& e);\n\n \/\/\/ Maybe raise a deferred exception. Must be called from the scheduler\n \/\/\/ while resuming the job execution. For example, StopException\n \/\/\/ may be raised from here if the job has been blocked by a tag.\n void check_for_pending_exception();\n\n \/\/\/ Get the job name\n \/\/\/\n \/\/\/ \\return The job name as set from the constructor.\n const libport::Symbol& name_get() const;\n\n \/\/\/ Throw an exception if the stack space for this job is near\n \/\/\/ exhaustion.\n void check_stack_space();\n\n \/\/\/ Is the job frozen?\n \/\/\/\n \/\/\/ \\return This depends from the job tags state.\n virtual bool frozen() const = 0;\n\n \/\/\/ Check if the job holds a tag.\n \/\/\/\n \/\/\/ \\return 0 if the job does not hold the tag,\n \/\/\/ the position of the tag in the tag stack\n \/\/\/ (starting from 1) otherwise.\n virtual size_t has_tag(const Tag& tag, size_t max_depth = (size_t)-1)\n const = 0;\n\n \/\/\/ Get the current job state.\n \/\/\/\n \/\/\/ \\return The current job state.\n job_state state_get() const;\n\n \/\/\/ Set the current job state\n \/\/\/\n \/\/\/ \\param state The new job state.\n void state_set(job_state state);\n\n \/\/\/ Get this job deadline if it is sleeping.\n \/\/\/\n \/\/\/ \\return The date on which this job needs to be awoken.\n \/\/\/\n \/\/\/ This function must not be called unless the job is in the\n \/\/\/ \\c sleeping state.\n libport::utime_t deadline_get() const;\n\n \/\/\/ Check if the job can be interrupted.\n \/\/\/\n \/\/\/ \\return True if the job cannot be interrupted right now because\n \/\/\/ it is executing an atomic operation.\n bool non_interruptible_get() const;\n\n \/\/\/ Indicate if the job can be interrupted or not\n \/\/\/\n \/\/\/ \\param ni True if the job must not be interrupted until further\n \/\/\/ notice.\n void non_interruptible_set(bool ni);\n\n \/\/\/ Remember the time we have been frozen since if not remembered\n \/\/\/ yet.\n \/\/\/\n \/\/\/ \\param current_time The current time.\n void notice_frozen(libport::utime_t current_time);\n\n \/\/\/ Note that we are not frozen anymore.\n \/\/\/\n \/\/\/ \\param current_time The current time.\n void notice_not_frozen(libport::utime_t current_time);\n\n \/\/\/ Return the origin since we have been frozen.\n \/\/\/\n \/\/\/ \\return 0 if we have not been frozen, the date since we have\n \/\/\/ been frozen otherwise.\n libport::utime_t frozen_since_get() const;\n\n \/\/\/ Return the current time shift.\n \/\/\/\n \/\/\/ \\return The value to subtract from the system time to get the\n \/\/\/ unfrozen time of this runner.\n libport::utime_t time_shift_get() const;\n\n \/\/\/ Set the current time shift.\n \/\/\/\n \/\/\/ \\param ts The new time shift. This should probably only be used\n \/\/\/ at runner creation time.\n void time_shift_set(libport::utime_t ts);\n\n \/\/\/ Check and maybe register the fact that a tag has been stopped.\n \/\/\/\n \/\/\/ \\param tag The tag that has been stopped.\n \/\/\/\n \/\/\/ \\param payload The data to embed in the StopException.\n virtual void register_stopped_tag\n (const Tag& tag, const boost::any& payload);\n\n \/\/\/ Check whether the job has a pending exception.\n \/\/\/\n \/\/\/ \\return true if the job has a pending exception.\n bool has_pending_exception() const;\n\n \/\/\/ Get the current job priority.\n \/\/\/\n \/\/\/ \\return The job priority, as previously computed.\n virtual prio_type prio_get() const = 0;\n\n \/\/\/ Ensure proper cleanup.\n virtual void terminate_cleanup();\n\n \/\/\/ Number of jobs created and not yet destroyed.\n \/\/\/\n \/\/\/ \\return The number of jobs.\n static unsigned int alive_jobs();\n\n \/\/\/ Helper to unregister all children upon destruction.\n class Collector: public jobs_type\n {\n public:\n typedef jobs_type super_type;\n \/\/\/ Construct a child collector.\n \/\/\/\n \/\/\/ \\param parent Parent of the child to collect\n \/\/\/\n \/\/\/ \\param size Approximative previsional number of children.\n Collector(rJob parent, size_t);\n \/\/\/ Terminate all children.\n ~Collector();\n\n \/\/\/ If there are terminated children, collect them.\n void collect();\n\n \/\/\/ Print, for debugging.\n std::ostream& dump(std::ostream& o) const;\n\n private:\n rJob parent_;\n };\n\n \/\/\/ Register a child.\n \/\/\/\n \/\/\/ \\param child The child job.\n \/\/\/\n \/\/\/ \\param collector Children will be automatically terminated\n \/\/\/ when this object is destroyed.\n void register_child(const rJob& child, Collector& collector);\n\n \/\/\/ Terminate child and remove it from our children list.\n void terminate_child(const rJob& child);\n\n \/\/\/ Do we have a parent?\n \/\/\/\n \/\/\/ \\return True if we have a parent.\n bool child_job() const;\n\n \/\/\/ Whether \\a this is an ancester of \\a that.\n bool ancester_of(const rJob& that) const;\n\n protected:\n\n \/\/\/ Must be implemented to do something useful. If an exception is\n \/\/\/ raised, it will be propagated to our parent if we have one or\n \/\/\/ lost otherwise.\n virtual void work() = 0;\n\n \/\/\/ Must be overriden. Called if a scheduling error is detected\n \/\/\/ during the execution course of this job.\n \/\/\/\n \/\/\/ \\param msg The explanation of the scheduling error.\n virtual void scheduling_error(const std::string& msg = \"\") = 0;\n\n private:\n \/\/\/ Current job state, to be manipulated only from the job and the\n \/\/\/ scheduler.\n job_state state_;\n\n \/\/\/ Current job deadline. The deadline is only meaningful when the\n \/\/\/ job state is \\c sleeping.\n libport::utime_t deadline_;\n\n \/\/\/ The last time we have been frozen (in system time), or 0 if we\n \/\/\/ are not currently frozen.\n libport::utime_t frozen_since_;\n\n \/\/\/ The value we have to deduce from system time because we have\n \/\/\/ been frozen.\n libport::utime_t time_shift_;\n\n \/\/\/ Scheduler in charge of this job. Do not delete.\n Scheduler& scheduler_;\n\n \/\/\/ This job name.\n libport::Symbol name_;\n\n \/\/\/ Other jobs to wake up when we terminate.\n jobs_type to_wake_up_;\n\n \/\/\/ Coro structure corresponding to this job.\n Coro* coro_;\n\n protected:\n\n \/\/\/ Is the current job non-interruptible? If yes, yielding will\n \/\/\/ do nothing and blocking operations may raise an exception.\n bool non_interruptible_;\n\n private:\n\n \/\/\/ Helper functions for constructors.\n void init_common(const libport::Symbol& name);\n\n \/\/\/ Is the current job side-effect free?\n bool side_effect_free_;\n\n \/\/\/ The next exception to be propagated if any.\n exception_ptr pending_exception_;\n\n \/\/\/ Our parent if any.\n rJob parent_;\n\n \/\/\/ Our children.\n jobs_type children_;\n\n \/\/\/ Check stack space from time to time.\n bool check_stack_space_;\n\n \/\/\/ Number of jobs created and not yet destroyed.\n static unsigned int alive_jobs_;\n\n protected:\n \/\/\/ Exception used to terminate a job.\n struct SCHED_API TerminateException : public SchedulerException\n {\n COMPLETE_EXCEPTION(TerminateException)\n };\n\n };\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const Job& j);\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const jobs_type& js);\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const Job::Collector& c);\n\n \/\/\/ This exception will be raised to tell the job that it is currently\n \/\/\/ stopped and must try to unwind tags from its tag stack until it\n \/\/\/ is either dead or not stopped anymore.\n struct SCHED_API StopException : public SchedulerException\n {\n StopException(unsigned int, boost::any);\n ~StopException() throw() {}\n ADD_FIELD(unsigned int, depth)\n ADD_FIELD(boost::any, payload)\n COMPLETE_EXCEPTION(StopException)\n };\n\n \/\/\/ This exception encapsulates another one, sent by a child job.\n struct SCHED_API ChildException : public SchedulerException\n {\n ChildException(exception_ptr);\n ChildException(const ChildException&);\n ~ChildException() throw() {}\n virtual exception_ptr clone() const;\n ATTRIBUTE_NORETURN void rethrow_child_exception() const;\n protected:\n ATTRIBUTE_NORETURN virtual void rethrow_() const;\n private:\n mutable exception_ptr child_exception_;\n };\n\n \/\/\/ Terminate all jobs present in container and empty it.\n SCHED_API\n void terminate_jobs(jobs_type& jobs);\n\n} \/\/ namespace sched\n\n# include <sched\/job.hxx>\n\n#endif \/\/ !SCHED_JOB_HH\n<commit_msg>sched: Job::Collector: better ctor.<commit_after>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file sched\/job.hh\n ** \\brief Definition of Job.\n *\/\n\n#ifndef SCHED_JOB_HH\n# define SCHED_JOB_HH\n\n# include <iosfwd>\n# include <list>\n\n# include <boost\/any.hpp>\n\n# include <libport\/symbol.hh>\n# include <libport\/utime.hh>\n\n# include <sched\/coroutine.hh>\n# include <sched\/export.hh>\n# include <sched\/fwd.hh>\n# include <sched\/tag.hh>\n\nnamespace sched\n{\n\n enum job_state\n {\n to_start, \/\/\/< Job needs to be started\n running, \/\/\/< Job is waiting for the CPU\n sleeping, \/\/\/< Job is sleeping until a specified deadline\n waiting, \/\/\/< Job is waiting for changes to happen\n joining, \/\/\/< Job is waiting for another job to terminate\n zombie, \/\/\/< Job wants to be dead but isn't really yet\n };\n\n \/\/\/ State names to string, for debugging purpose.\n const char* name(job_state);\n\n \/\/\/ Dump \\a s on \\a o for debugging purpose.\n std::ostream& operator<<(std::ostream& o, job_state s);\n\n \/\/\/ A Job represents a thread of control, implemented using coroutines.\n \/\/\/ The scheduler decides which job to launch and resumes its execution.\n \/\/\/ The lifetime of a job is the following\n \/\/\/\n \/\/\/ \\li Job() : job creation\n \/\/\/\n \/\/\/ \\li start_job() : add job to the scheduler; the scheduler\n \/\/\/ will call run(), and the job will\n \/\/\/ yield() itself into the scheduler run\n \/\/\/ queue during the course of work()\n \/\/\/\n \/\/\/ \\li work() : this method, which must be overridden,\n \/\/\/ does the real work\n \/\/\/\n \/\/\/ Due to the way coroutines work, a job may not delete itself\n \/\/\/ as once the coroutine structure has been freed, it is illegal to\n \/\/\/ continue its execution, even only to switch to another coroutine.\n \/\/\/ And if a job switches back to the scheduler before terminating its\n \/\/\/ destructor, the coroutine structure will not be freed. Because of\n \/\/\/ that, it is necessary for a job to be deleted by another one or\n \/\/\/ by the scheduler.\n \/\/\/\n \/\/\/ An additional constraint comes from the fact that even when a job\n \/\/\/ has terminated its work, its structure may not always be deleted.\n \/\/\/ For example, other jobs may have kept a reference to this job and\n \/\/\/ expect to retrieve some information (such as a result) after the\n \/\/\/ job termination.\n \/\/\/\n \/\/\/ We have several ways of dealing with those constraints and not leaking\n \/\/\/ memory upon a job termination:\n \/\/\/\n \/\/\/ \\li 1. Make sure the job spits out all the useful information concerning\n \/\/\/ its state by the way of inter-job communication before asking to\n \/\/\/ be deleted.\n \/\/\/\n \/\/\/ \\li 2. Make sure the job is kept alive as long as there is at least one\n \/\/\/ reference onto it, and that it gets deleted from another\n \/\/\/ coroutine, or from the main one.\n\n class SCHED_API Job: public libport::RefCounted\n {\n public:\n \/\/\/ Create a job from another one.\n \/\/\/\n \/\/\/ \\param model The parent job. The scheduler and tags will be inherited\n \/\/ from it.\n \/\/\/\n \/\/\/ \\param name The name of the new job, or a name derived from \\a model\n \/\/\/ if none is provided.\n Job(const Job& model, const libport::Symbol& name);\n\n \/\/\/ Create a new job.\n \/\/\/\n \/\/\/ \\param scheduler The scheduler to which this job will be attached.\n \/\/\/\n \/\/\/ \\param name The name of the new job, or an automatically created\n \/\/\/ one if none is provided.\n Job(Scheduler& scheduler, const libport::Symbol& name);\n\n \/\/\/ Job destructor.\n \/\/\/\n \/\/\/ The destructor is in charge of unscheduling the job in the\n \/\/\/ scheduler.\n virtual ~Job();\n\n \/\/\/ Get this job scheduler.\n \/\/\/\n \/\/\/ \\return A reference on the job scheduler.\n Scheduler& scheduler_get() const;\n\n \/\/\/ Dump internal data (for the developper).\n \/\/\/\n \/\/\/ \\return \\a o\n std::ostream& dump(std::ostream& o) const;\n\n \/\/\/ Get the underlying coroutine corresponding to this job.\n \/\/\/\n \/\/\/ \\return The coroutine structure.\n Coro* coro_get() const;\n\n \/\/\/ Has this job terminated?\n \/\/\/\n \/\/\/ \\return True if this job is in the \\c zombie state.\n bool terminated() const;\n\n \/\/\/ Start job by adding it to the scheduler.\n void start_job();\n\n \/\/\/ Run the job. This function is called from the scheduler.\n void run();\n\n \/\/\/ Terminate the job. The job will execute its cleanup method\n \/\/\/ and inform the scheduler that it is ready to be destroyed.\n \/\/\/ Must not be called by a child to an ancester of his.\n void terminate_now();\n\n \/\/\/ Asynchronous termination. Allows a child to kill its parent.\n \/\/\/ Will be killed at the next cycle.\n void terminate_asap();\n\n \/\/\/ Register this Job on its Scheduler so that it is rescheduled\n \/\/\/ during the next cycle. This should be called from the\n \/\/\/ currently scheduled job only but must be kept visible to be\n \/\/\/ callable from the primitives.\n \/\/\/ \\sa yield_until(), yield_until_terminated(),\n \/\/\/ yield_until_things_changed()\n void yield();\n\n \/\/\/ As yield(), but ask not to be woken up before the deadline.\n \/\/\/ \\sa yield(), yield_until_terminated(), yield_until_things_changed()\n void yield_until(libport::utime_t deadline);\n\n \/\/\/ Wait for another job to terminate before resuming execution of\n \/\/\/ the current one. If the other job has already terminated, the\n \/\/\/ caller will continue its execution.\n \/\/\/\n \/\/\/ \\param other The job to wait for. It is allowed to specify the\n \/\/\/ same Job as the target and the waiting job, in which case\n \/\/\/ the Job will only be woken up by an asynchronous exception.\n \/\/\/\n \/\/\/ \\sa yield(), yield_until(), yield_until_things_changed()\n void yield_until_terminated(Job& other);\n\n \/\/\/ Same as \\p yield_until_terminated above(), but wait for every\n \/\/\/ job in the collection.\n void yield_until_terminated(const jobs_type& jobs);\n\n \/\/\/ Wait for any other task to be scheduled.\n \/\/\/ \\sa yield(), yield_until_terminated(), yield_until()\n void yield_until_things_changed();\n\n \/\/\/ Mark the current job as side-effect free.\n \/\/\/\n \/\/\/ \\param s True if the job is now side-effect free.\n \/\/\/\n \/\/\/ Indicate whether the current state of a job may influence other\n \/\/\/ parts of the system. This is used by the scheduler to choose\n \/\/\/ whether other jobs need scheduling or not. The default value\n \/\/\/ for \\c side_effect_free is false.\n void side_effect_free_set(bool s);\n\n \/\/\/ Is the current job side-effect free?\n \/\/\/\n \/\/\/ \\return True if the job is currently side-effect free.\n bool side_effect_free_get() const;\n\n \/\/\/ Raise an exception next time this job will be resumed.\n \/\/\/\n \/\/\/ \\param e The exception to throw when the job will be scheduled\n \/\/\/ again.\n void async_throw(const exception& e);\n\n \/\/\/ Maybe raise a deferred exception. Must be called from the scheduler\n \/\/\/ while resuming the job execution. For example, StopException\n \/\/\/ may be raised from here if the job has been blocked by a tag.\n void check_for_pending_exception();\n\n \/\/\/ Get the job name\n \/\/\/\n \/\/\/ \\return The job name as set from the constructor.\n const libport::Symbol& name_get() const;\n\n \/\/\/ Throw an exception if the stack space for this job is near\n \/\/\/ exhaustion.\n void check_stack_space();\n\n \/\/\/ Is the job frozen?\n \/\/\/\n \/\/\/ \\return This depends from the job tags state.\n virtual bool frozen() const = 0;\n\n \/\/\/ Check if the job holds a tag.\n \/\/\/\n \/\/\/ \\return 0 if the job does not hold the tag,\n \/\/\/ the position of the tag in the tag stack\n \/\/\/ (starting from 1) otherwise.\n virtual size_t has_tag(const Tag& tag, size_t max_depth = (size_t)-1)\n const = 0;\n\n \/\/\/ Get the current job state.\n \/\/\/\n \/\/\/ \\return The current job state.\n job_state state_get() const;\n\n \/\/\/ Set the current job state\n \/\/\/\n \/\/\/ \\param state The new job state.\n void state_set(job_state state);\n\n \/\/\/ Get this job deadline if it is sleeping.\n \/\/\/\n \/\/\/ \\return The date on which this job needs to be awoken.\n \/\/\/\n \/\/\/ This function must not be called unless the job is in the\n \/\/\/ \\c sleeping state.\n libport::utime_t deadline_get() const;\n\n \/\/\/ Check if the job can be interrupted.\n \/\/\/\n \/\/\/ \\return True if the job cannot be interrupted right now because\n \/\/\/ it is executing an atomic operation.\n bool non_interruptible_get() const;\n\n \/\/\/ Indicate if the job can be interrupted or not\n \/\/\/\n \/\/\/ \\param ni True if the job must not be interrupted until further\n \/\/\/ notice.\n void non_interruptible_set(bool ni);\n\n \/\/\/ Remember the time we have been frozen since if not remembered\n \/\/\/ yet.\n \/\/\/\n \/\/\/ \\param current_time The current time.\n void notice_frozen(libport::utime_t current_time);\n\n \/\/\/ Note that we are not frozen anymore.\n \/\/\/\n \/\/\/ \\param current_time The current time.\n void notice_not_frozen(libport::utime_t current_time);\n\n \/\/\/ Return the origin since we have been frozen.\n \/\/\/\n \/\/\/ \\return 0 if we have not been frozen, the date since we have\n \/\/\/ been frozen otherwise.\n libport::utime_t frozen_since_get() const;\n\n \/\/\/ Return the current time shift.\n \/\/\/\n \/\/\/ \\return The value to subtract from the system time to get the\n \/\/\/ unfrozen time of this runner.\n libport::utime_t time_shift_get() const;\n\n \/\/\/ Set the current time shift.\n \/\/\/\n \/\/\/ \\param ts The new time shift. This should probably only be used\n \/\/\/ at runner creation time.\n void time_shift_set(libport::utime_t ts);\n\n \/\/\/ Check and maybe register the fact that a tag has been stopped.\n \/\/\/\n \/\/\/ \\param tag The tag that has been stopped.\n \/\/\/\n \/\/\/ \\param payload The data to embed in the StopException.\n virtual void register_stopped_tag\n (const Tag& tag, const boost::any& payload);\n\n \/\/\/ Check whether the job has a pending exception.\n \/\/\/\n \/\/\/ \\return true if the job has a pending exception.\n bool has_pending_exception() const;\n\n \/\/\/ Get the current job priority.\n \/\/\/\n \/\/\/ \\return The job priority, as previously computed.\n virtual prio_type prio_get() const = 0;\n\n \/\/\/ Ensure proper cleanup.\n virtual void terminate_cleanup();\n\n \/\/\/ Number of jobs created and not yet destroyed.\n \/\/\/\n \/\/\/ \\return The number of jobs.\n static unsigned int alive_jobs();\n\n \/\/\/ Helper to unregister all children upon destruction.\n class Collector: public jobs_type\n {\n public:\n typedef jobs_type super_type;\n \/\/\/ Construct a child collector.\n \/\/\/\n \/\/\/ \\param parent Parent of the child to collect\n \/\/\/\n \/\/\/ \\param size Approximative previsional number of children.\n Collector(rJob parent, size_t = 0);\n \/\/\/ Terminate all children.\n ~Collector();\n\n \/\/\/ If there are terminated children, collect them.\n void collect();\n\n \/\/\/ Print, for debugging.\n std::ostream& dump(std::ostream& o) const;\n\n private:\n rJob parent_;\n };\n\n \/\/\/ Register a child.\n \/\/\/\n \/\/\/ \\param child The child job.\n \/\/\/\n \/\/\/ \\param collector Children will be automatically terminated\n \/\/\/ when this object is destroyed.\n void register_child(const rJob& child, Collector& collector);\n\n \/\/\/ Terminate child and remove it from our children list.\n void terminate_child(const rJob& child);\n\n \/\/\/ Do we have a parent?\n \/\/\/\n \/\/\/ \\return True if we have a parent.\n bool child_job() const;\n\n \/\/\/ Whether \\a this is an ancester of \\a that.\n bool ancester_of(const rJob& that) const;\n\n protected:\n\n \/\/\/ Must be implemented to do something useful. If an exception is\n \/\/\/ raised, it will be propagated to our parent if we have one or\n \/\/\/ lost otherwise.\n virtual void work() = 0;\n\n \/\/\/ Must be overriden. Called if a scheduling error is detected\n \/\/\/ during the execution course of this job.\n \/\/\/\n \/\/\/ \\param msg The explanation of the scheduling error.\n virtual void scheduling_error(const std::string& msg = \"\") = 0;\n\n private:\n \/\/\/ Current job state, to be manipulated only from the job and the\n \/\/\/ scheduler.\n job_state state_;\n\n \/\/\/ Current job deadline. The deadline is only meaningful when the\n \/\/\/ job state is \\c sleeping.\n libport::utime_t deadline_;\n\n \/\/\/ The last time we have been frozen (in system time), or 0 if we\n \/\/\/ are not currently frozen.\n libport::utime_t frozen_since_;\n\n \/\/\/ The value we have to deduce from system time because we have\n \/\/\/ been frozen.\n libport::utime_t time_shift_;\n\n \/\/\/ Scheduler in charge of this job. Do not delete.\n Scheduler& scheduler_;\n\n \/\/\/ This job name.\n libport::Symbol name_;\n\n \/\/\/ Other jobs to wake up when we terminate.\n jobs_type to_wake_up_;\n\n \/\/\/ Coro structure corresponding to this job.\n Coro* coro_;\n\n protected:\n\n \/\/\/ Is the current job non-interruptible? If yes, yielding will\n \/\/\/ do nothing and blocking operations may raise an exception.\n bool non_interruptible_;\n\n private:\n\n \/\/\/ Helper functions for constructors.\n void init_common(const libport::Symbol& name);\n\n \/\/\/ Is the current job side-effect free?\n bool side_effect_free_;\n\n \/\/\/ The next exception to be propagated if any.\n exception_ptr pending_exception_;\n\n \/\/\/ Our parent if any.\n rJob parent_;\n\n \/\/\/ Our children.\n jobs_type children_;\n\n \/\/\/ Check stack space from time to time.\n bool check_stack_space_;\n\n \/\/\/ Number of jobs created and not yet destroyed.\n static unsigned int alive_jobs_;\n\n protected:\n \/\/\/ Exception used to terminate a job.\n struct SCHED_API TerminateException : public SchedulerException\n {\n COMPLETE_EXCEPTION(TerminateException)\n };\n\n };\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const Job& j);\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const jobs_type& js);\n\n SCHED_API\n std::ostream& operator<< (std::ostream& o, const Job::Collector& c);\n\n \/\/\/ This exception will be raised to tell the job that it is currently\n \/\/\/ stopped and must try to unwind tags from its tag stack until it\n \/\/\/ is either dead or not stopped anymore.\n struct SCHED_API StopException : public SchedulerException\n {\n StopException(unsigned int, boost::any);\n ~StopException() throw() {}\n ADD_FIELD(unsigned int, depth)\n ADD_FIELD(boost::any, payload)\n COMPLETE_EXCEPTION(StopException)\n };\n\n \/\/\/ This exception encapsulates another one, sent by a child job.\n struct SCHED_API ChildException : public SchedulerException\n {\n ChildException(exception_ptr);\n ChildException(const ChildException&);\n ~ChildException() throw() {}\n virtual exception_ptr clone() const;\n ATTRIBUTE_NORETURN void rethrow_child_exception() const;\n protected:\n ATTRIBUTE_NORETURN virtual void rethrow_() const;\n private:\n mutable exception_ptr child_exception_;\n };\n\n \/\/\/ Terminate all jobs present in container and empty it.\n SCHED_API\n void terminate_jobs(jobs_type& jobs);\n\n} \/\/ namespace sched\n\n# include <sched\/job.hxx>\n\n#endif \/\/ !SCHED_JOB_HH\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"backlog.hpp\"\n#include \"detail\/util.hpp\"\n\nnamespace sts\n{\n class scroller\n {\n public:\n scroller() = delete;\n scroller(backlog &bl)\n : backlog_{ bl }\n { }\n\n template <typename It>\n void write(It const &begin, It end)\n {\n auto const size(std::distance(begin, end));\n if(::write(STDOUT_FILENO, &*begin, size) != size)\n { throw std::runtime_error{ \"partial\/failed write (stdout)\" }; }\n\n end = filter(begin, end);\n backlog_.write(begin, end);\n\n auto &impl(backlog_.get_impl());\n auto const line_markers_size(impl.line_markers_.size());\n auto const rows(impl.tty_.get().size.ws_row);\n if(following_ && line_markers_size > rows)\n { scroll_pos_ = line_markers_size - rows; }\n }\n\n void up()\n {\n if(!scroll_pos_)\n { return; }\n following_ = false;\n --scroll_pos_;\n redraw();\n }\n\n void down()\n {\n auto &impl(backlog_.get_impl());\n if(scroll_pos_ + impl.tty_.get().size.ws_row >= impl.line_markers_.size())\n {\n following_ = true;\n return;\n }\n ++scroll_pos_;\n redraw();\n }\n\n void follow()\n {\n auto &impl(backlog_.get_impl());\n if(following_)\n { return; }\n\n scroll_pos_ = impl.line_markers_.size() - impl.tty_.get().size.ws_row;\n following_ = true;\n redraw();\n }\n\n void clear()\n {\n static std::string const clear{ \"\\x1B[H\\x1B[2J\" };\n static ssize_t const clear_size(clear.size());\n if(::write(STDOUT_FILENO, clear.c_str(), clear.size()) != clear_size)\n { throw std::runtime_error{ \"unable to clear screen\" }; }\n }\n\n private:\n template <typename It>\n It filter(It const &begin, It end)\n {\n std::ofstream ofs{ \".filter\", std::ios_base::app };\n auto distance(std::distance(begin, end));\n size_t d{};\n auto const predicates(detail::make_array<std::function<size_t (It)>>(\n [&](It const it)\n {\n d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '4', '7', 'h' });\n if(d)\n { backlog_.impls_.emplace_back(backlog_.tty_, backlog_.limit_); }\n return d;\n },\n [&](It const it)\n { \n d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '4', '7', 'l' });\n if(d && backlog_.impls_.size() > 1)\n { backlog_.impls_.erase(backlog_.impls_.end() - 1); }\n return d;\n },\n [&](It const it)\n { return d = detail::seq_eq<4>(distance, it, { 27, '[', '2', 'J' }); },\n [&](It const it)\n { return d = detail::seq_eq<2>(distance, it, { 27, '7' }); },\n [&](It const it)\n { return d = detail::seq_eq<2>(distance, it, { 27, '8' }); },\n [&](It const it)\n { return d = detail::seq_eq<3>(distance, it, { 27, '[', 'K' }); },\n [&](It const it)\n { return d = detail::seq_eq<4>(distance, it, { 27, '[', '?', '1' }); },\n [&](It const it)\n { return d = detail::seq_eq<2>(distance, it, { 27, '>' }); },\n [&](It const it)\n { return d = detail::seq_eq<6>(distance, it, { 27, '[', '?', '2', '5', 'h' }); },\n [&](It const it)\n { return d = detail::seq_eq<8>(distance, it, { 27, '[', '3', '0', ';', '1', 'H', 'l' }); },\n [&](It const it)\n { return d = detail::seq_eq<7>(distance, it, { 27, '[', '3', '0', ';', '1', 'H' }); }\n ));\n\n auto const pred_end(std::end(predicates));\n for(auto it(begin); it != end; ++it, --distance)\n {\n while(std::find_if(std::begin(predicates), pred_end,\n [&](std::function<size_t (It)> const &f)\n { return f(it); }) != pred_end)\n {\n std::copy(begin, end, std::ostream_iterator<int>(ofs, \" \"));\n ofs << std::endl;\n auto const sub_end(it + d);\n auto rit(begin);\n end = std::remove_if(begin, end, [&](char const)\n {\n auto const cur(rit++);\n return (cur >= it && cur < sub_end);\n });\n std::copy(begin, end, std::ostream_iterator<int>(ofs, \" \"));\n ofs << std::endl;\n\n if(it == end)\n { break; }\n }\n\n if(it == end)\n { break; }\n }\n\n return end;\n }\n\n void redraw()\n {\n clear();\n\n auto &impl(backlog_.get_impl());\n std::size_t const rows{ impl.tty_.get().size.ws_row };\n for(std::size_t i{ scroll_pos_ };\n i < scroll_pos_ + std::min(impl.line_markers_.size(), rows);\n ++i)\n {\n ssize_t size((impl.line_markers_[i].second -\n impl.line_markers_[i].first) + 1);\n if(i == scroll_pos_ + std::min(impl.line_markers_.size() - 1,\n rows - 1))\n { --size; }\n if(::write(STDOUT_FILENO, &impl.buf_[impl.line_markers_[i].first],\n size) != size)\n { throw std::runtime_error{ \"partial\/failed write (stdout)\" }; }\n }\n }\n\n backlog &backlog_;\n std::size_t scroll_pos_{};\n bool following_{ true };\n };\n}\n<commit_msg>regex to the rescue<commit_after>#pragma once\n\n#include \"backlog.hpp\"\n#include \"detail\/util.hpp\"\n\n#include <regex>\n#include <algorithm>\n\nnamespace sts\n{\n class scroller\n {\n public:\n scroller() = delete;\n scroller(backlog &bl)\n : backlog_{ bl }\n { }\n\n template <typename It>\n void write(It const &begin, It end)\n {\n auto const size(std::distance(begin, end));\n if(::write(STDOUT_FILENO, &*begin, size) != size)\n { throw std::runtime_error{ \"partial\/failed write (stdout)\" }; }\n\n end = filter(begin, end);\n backlog_.write(begin, end);\n\n auto &impl(backlog_.get_impl());\n auto const line_markers_size(impl.line_markers_.size());\n auto const rows(impl.tty_.get().size.ws_row);\n if(following_ && line_markers_size > rows)\n { scroll_pos_ = line_markers_size - rows; }\n }\n\n void up()\n {\n if(!scroll_pos_)\n { return; }\n following_ = false;\n --scroll_pos_;\n redraw();\n }\n\n void down()\n {\n auto &impl(backlog_.get_impl());\n if(scroll_pos_ + impl.tty_.get().size.ws_row >= impl.line_markers_.size())\n {\n following_ = true;\n return;\n }\n ++scroll_pos_;\n redraw();\n }\n\n void follow()\n {\n auto &impl(backlog_.get_impl());\n if(following_)\n { return; }\n\n scroll_pos_ = impl.line_markers_.size() - impl.tty_.get().size.ws_row;\n following_ = true;\n redraw();\n }\n\n void clear()\n {\n static std::string const clear{ \"\\x1B[H\\x1B[2J\" };\n static ssize_t const clear_size(clear.size());\n if(::write(STDOUT_FILENO, clear.c_str(), clear.size()) != clear_size)\n { throw std::runtime_error{ \"unable to clear screen\" }; }\n }\n\n private:\n template <typename It>\n It filter(It const &begin, It end)\n {\n std::ofstream ofs{ \".filter\", std::ios_base::app };\n static auto const predicates(detail::make_array\n (\n std::regex{ \"\\x1B\\\\[\\\\?47(h|l)\" }, \/* smcup\/rmcup *\/\n std::regex{ \"\\x1B\\\\[2J\" }, \/* clear *\/\n std::regex{ \"\\x1B\\\\[([[:digit:]])*(A|B|C|D|E|F|G|J|K|S|T)\" }, \/* move cursor\/scroll *\/\n std::regex{ \"\\x1B\\\\[([[:digit:]])*;([[:digit:]])*(H|f)\" }, \/* move cursor *\/\n std::regex{ \"\\x1B\\\\[6n\" }, \/* report cursor *\/\n std::regex{ \"\\x1B\\\\[(s|u)\" }, \/* save\/restore cursor *\/\n std::regex{ \"\\x1B\\\\[\\\\?25(h|l)\" } \/* show\/hide cursor *\/\n ));\n\n std::smatch match;\n for(auto const &pred : predicates)\n {\n while(std::regex_search(std::string{begin, end}, match, pred))\n {\n std::copy(begin, end, std::ostream_iterator<int>(ofs, \" \"));\n ofs << std::endl;\n ofs << \"filtering (\" << match.position() << \")\"\n << \"[\" << match.length() << \"]: \";\n std::copy(begin, end, std::ostream_iterator<int>(ofs, \" \"));\n ofs << std::endl;\n\n auto const it(begin + match.position());\n auto const sub_end(it + match.length());\n auto rit(begin);\n end = std::remove_if(begin, end, [&](char const)\n {\n auto const cur(rit++);\n return (cur >= it && cur < sub_end);\n });\n\n std::copy(begin, end, std::ostream_iterator<int>(ofs, \" \"));\n ofs << std::endl;\n }\n }\n\n return end;\n }\n\n void redraw()\n {\n clear();\n\n auto &impl(backlog_.get_impl());\n std::size_t const rows{ impl.tty_.get().size.ws_row };\n for(std::size_t i{ scroll_pos_ };\n i < scroll_pos_ + std::min(impl.line_markers_.size(), rows);\n ++i)\n {\n ssize_t size((impl.line_markers_[i].second -\n impl.line_markers_[i].first) + 1);\n if(i == scroll_pos_ + std::min(impl.line_markers_.size() - 1,\n rows - 1))\n { --size; }\n if(::write(STDOUT_FILENO, &impl.buf_[impl.line_markers_[i].first],\n size) != size)\n { throw std::runtime_error{ \"partial\/failed write (stdout)\" }; }\n }\n }\n\n backlog &backlog_;\n std::size_t scroll_pos_{};\n bool following_{ true };\n };\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n\n#include <iostream>\n\nextern \"C\" {\n\n#include \"lua\/lualib.h\"\n\n}\n\n#include \"lualite\/lualite.hpp\"\n\nstruct point\n{\n int x;\n int y;\n};\n\ninline int set_result(lua_State* const L, point p)\n{\n using namespace ::lualite::detail;\n\n lua_createtable(L, 2, 0);\n\n lua_pushliteral(L, \"x\");\n set_result(L, const_cast<decltype(p.x) const&>(p.x));\n assert(lua_istable(L, -3));\n lua_rawset(L, -3);\n\n lua_pushliteral(L, \"y\");\n set_result(L, const_cast<decltype(p.y) const&>(p.y));\n assert(lua_istable(L, -3));\n lua_rawset(L, -3);\n\n return 1;\n}\n\ntemplate <std::size_t I, typename T>\ninline typename std::enable_if<\n std::is_same<T, point>::value, point>::type\nget_arg(lua_State* const L)\n{\n using namespace ::lualite::detail;\n\n assert(lua_istable(L, I));\n\n struct point p;\n\n lua_pushliteral(L, \"x\");\n lua_rawget(L, -2);\n p.x = lua_tointeger(L, -1);\n\n lua_pushliteral(L, \"y\");\n lua_rawget(L, -2);\n p.y = lua_tointeger(L, -1);\n\n return p;\n}\n\npoint testfunc(int i)\n{\n std::cout << \"testfunc(): \" << i << std::endl;\n\n return {-1, -222};\n}\n\nstruct testbase\n{\n std::string dummy(std::string msg)\n {\n return { \"dummy() called: \" + msg };\n }\n};\n\nstruct testclass : testbase\n{\n testclass()\n : a_(777)\n {\n std::cout << \"testclass::testclass()\" << std::endl;\n }\n\n testclass(int i)\n : a_(777)\n {\n std::cout << \"testclass::testclass(int):\" << i << std::endl;\n }\n\n std::vector<std::string> print(std::string msg) const\n {\n std::cout << \"hello world!: \" << msg << std::endl;\n\n return { 10, \"bla!!!\" };\n }\n\n std::tuple<int, std::string, char const*> print(int i)\n {\n std::cout << i << std::endl;\n\n return std::make_tuple(9, \"huh?\", \"tralala\");\n }\n\n int const& a()\n {\n std::cout << \"getter called\" << std::endl;\n\n return a_;\n }\n\n void set_a(int i)\n {\n std::cout << \"setter called: \" << i << std::endl;\n\n a_ = i;\n }\n\n std::string const& test_array(std::array<int, 10> const& a)\n {\n std::cout << a[0] << std::endl;\n\n s_ = \"blablabla\";\n\n return s_;\n }\n\n testclass* pointer()\n {\n return this;\n }\n\n testclass& reference()\n {\n return *this;\n }\n\nprivate:\n int a_;\n std::string s_;\n};\n\nint main(int argc, char* argv[])\n{\n lua_State* L(luaL_newstate());\n\n luaL_openlibs(L);\n\n lualite::module(L,\n lualite::class_<testbase>(\"testbase\")\n .def(\"dummy\", &testbase::dummy),\n lualite::class_<testclass>(\"testclass\")\n .constructor(\"defaultNew\")\n .constructor<int>()\n .inherits<testbase>()\n .enum_(\"smell\", 9)\n .def(\"print\", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)\n .def(\"print_\", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)\n .def(\"pointer\", &testclass::pointer)\n .def(\"reference\", &testclass::reference)\n .property(\"a\", &testclass::a, &testclass::set_a)\n .def(\"test_array\", &testclass::test_array),\n lualite::scope(\"subscope\",\n lualite::class_<testclass>(\"testclass\")\n .constructor<>(\"defaultNew\")\n .constructor<int>()\n .enum_(\"smell\", 10)\n .def(\"testfunc\", &testfunc)\n .def(\"print\", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)\n .def(\"print_\", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)\n )\n )\n .enum_(\"apple\", 1)\n .def(\"testfunc\", &testfunc);\n\n luaL_dostring(\n L,\n \"local a = testfunc(3)\\n\"\n \"print(a.y)\\n\"\n \"print(apple)\\n\"\n \"print(testclass.__classname)\\n\"\n \"print(testclass.smell)\\n\"\n \"local b = testclass.defaultNew()\\n\"\n \"print(\\\"---\\\")\\n\"\n \"print(b.a)\\n\"\n \"b:reference().a = 888\\n\"\n \"print(b.a .. \\\" \\\" .. b:dummy(\\\"test\\\"))\\n\"\n \"local tmp1, tmp2, tmp3 = b:pointer():print(100)\\n\"\n \"print(tmp1 .. \\\" \\\" .. tmp2 .. \\\" \\\" .. tmp3)\\n\"\n \"b:reference():print_(\\\"msg1\\\")\\n\"\n \"local a = subscope.testclass.new(1111)\\n\"\n \"print(subscope.testclass.smell)\\n\"\n \"subscope.testclass.testfunc(200)\\n\"\n \"local c = a:reference():print_(\\\"msg2\\\")\\n\"\n \"print(c[10])\\n\"\n \"r = {}\"\n \"for i = 1, 10 do\\n\"\n \" r[i] = 7\\n\"\n \"end\\n\"\n \"print(a:test_array(r))\\n\"\n );\n\n lua_close(L);\n\n return EXIT_SUCCESS;\n}\n<commit_msg>test fix<commit_after>#include <cstdlib>\n\n#include <iostream>\n\nextern \"C\" {\n\n#include \"lua\/lualib.h\"\n\n}\n\n#include \"lualite\/lualite.hpp\"\n\nstruct point\n{\n int x;\n int y;\n};\n\ninline int set_result(lua_State* const L, point p)\n{\n using namespace ::lualite::detail;\n\n lua_createtable(L, 2, 0);\n\n lua_pushliteral(L, \"x\");\n set_result(L, const_cast<decltype(p.x) const&>(p.x));\n assert(lua_istable(L, -3));\n lua_rawset(L, -3);\n\n lua_pushliteral(L, \"y\");\n set_result(L, const_cast<decltype(p.y) const&>(p.y));\n assert(lua_istable(L, -3));\n lua_rawset(L, -3);\n\n return 1;\n}\n\ntemplate <std::size_t I, typename T>\ninline typename std::enable_if<\n std::is_same<T, point>::value, point>::type\nget_arg(lua_State* const L)\n{\n using namespace ::lualite::detail;\n\n assert(lua_istable(L, I));\n\n struct point p;\n\n lua_pushliteral(L, \"x\");\n lua_rawget(L, -2);\n p.x = lua_tointeger(L, -1);\n\n lua_pushliteral(L, \"y\");\n lua_rawget(L, -2);\n p.y = lua_tointeger(L, -1);\n\n return p;\n}\n\npoint testfunc(int i, int j, int k)\n{\n std::cout << \"testfunc(): \" << i << \" \" << j << \" \" << k << std::endl;\n\n return {-1, -222};\n}\n\nstruct testbase\n{\n std::string dummy(std::string msg)\n {\n return { \"dummy() called: \" + msg };\n }\n};\n\nstruct testclass : testbase\n{\n testclass()\n : a_(777)\n {\n std::cout << \"testclass::testclass()\" << std::endl;\n }\n\n testclass(int i)\n : a_(777)\n {\n std::cout << \"testclass::testclass(int):\" << i << std::endl;\n }\n\n std::vector<std::string> print(std::string msg) const\n {\n std::cout << \"hello world!: \" << msg << std::endl;\n\n return { 10, \"bla!!!\" };\n }\n\n std::tuple<int, std::string, char const*> print(int i)\n {\n std::cout << i << std::endl;\n\n return std::make_tuple(9, \"huh?\", \"tralala\");\n }\n\n int const& a()\n {\n std::cout << \"getter called\" << std::endl;\n\n return a_;\n }\n\n void set_a(int i)\n {\n std::cout << \"setter called: \" << i << std::endl;\n\n a_ = i;\n }\n\n std::string const& test_array(std::array<int, 10> const& a)\n {\n std::cout << a[0] << std::endl;\n\n s_ = \"blablabla\";\n\n return s_;\n }\n\n testclass* pointer()\n {\n return this;\n }\n\n testclass& reference()\n {\n return *this;\n }\n\nprivate:\n int a_;\n std::string s_;\n};\n\nint main(int argc, char* argv[])\n{\n lua_State* L(luaL_newstate());\n\n luaL_openlibs(L);\n\n lualite::module(L,\n lualite::class_<testbase>(\"testbase\")\n .def(\"dummy\", &testbase::dummy),\n lualite::class_<testclass>(\"testclass\")\n .constructor(\"defaultNew\")\n .constructor<int>()\n .inherits<testbase>()\n .enum_(\"smell\", 9)\n .def(\"print\", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)\n .def(\"print_\", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)\n .def(\"pointer\", &testclass::pointer)\n .def(\"reference\", &testclass::reference)\n .property(\"a\", &testclass::a, &testclass::set_a)\n .def(\"test_array\", &testclass::test_array),\n lualite::scope(\"subscope\",\n lualite::class_<testclass>(\"testclass\")\n .constructor<>(\"defaultNew\")\n .constructor<int>()\n .enum_(\"smell\", 10)\n .def(\"testfunc\", &testfunc)\n .def(\"print\", (std::tuple<int, std::string, char const*> (testclass::*)(int))&testclass::print)\n .def(\"print_\", (std::vector<std::string> (testclass::*)(std::string) const)&testclass::print)\n )\n )\n .enum_(\"apple\", 1)\n .def(\"testfunc\", &testfunc);\n\n luaL_dostring(\n L,\n \"local a = testfunc(3, 2, 1)\\n\"\n \"print(a.y)\\n\"\n \"print(apple)\\n\"\n \"print(testclass.__classname)\\n\"\n \"print(testclass.smell)\\n\"\n \"local b = testclass.defaultNew()\\n\"\n \"print(\\\"---\\\")\\n\"\n \"print(b.a)\\n\"\n \"b:reference().a = 888\\n\"\n \"print(b.a .. \\\" \\\" .. b:dummy(\\\"test\\\"))\\n\"\n \"local tmp1, tmp2, tmp3 = b:pointer():print(100)\\n\"\n \"print(tmp1 .. \\\" \\\" .. tmp2 .. \\\" \\\" .. tmp3)\\n\"\n \"b:reference():print_(\\\"msg1\\\")\\n\"\n \"local a = subscope.testclass.new(1111)\\n\"\n \"print(subscope.testclass.smell)\\n\"\n \"subscope.testclass.testfunc(200)\\n\"\n \"local c = a:reference():print_(\\\"msg2\\\")\\n\"\n \"print(c[10])\\n\"\n \"r = {}\"\n \"for i = 1, 10 do\\n\"\n \" r[i] = 7\\n\"\n \"end\\n\"\n \"print(a:test_array(r))\\n\"\n );\n\n lua_close(L);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2012, British Broadcasting Corporation\n * All Rights Reserved.\n *\n * Author: Philip de Nier\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the British Broadcasting Corporation nor the names\n * of its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cstdlib>\n#include <cstring>\n\n#include <bmx\/mxf_reader\/MXFAPPInfo.h>\n#include <mxf\/mxf_app.h>\n#include <bmx\/BMXException.h>\n#include <bmx\/Logging.h>\n\nusing namespace std;\nusing namespace bmx;\nusing namespace mxfpp;\n\n\n\nvoid MXFAPPInfo::RegisterExtensions(HeaderMetadata *header_metadata)\n{\n BMX_CHECK(mxf_app_load_extensions(header_metadata->getDataModel()->getCDataModel()));\n}\n\nbool MXFAPPInfo::IsAPP(HeaderMetadata *header_metadata)\n{\n return mxf_app_is_app_mxf(header_metadata->getCHeaderMetadata());\n}\n\nMXFAPPInfo::MXFAPPInfo()\n{\n source_record = 0;\n lto_record = 0;\n pse_failures = 0;\n num_pse_failures = 0;\n vtr_errors = 0;\n num_vtr_errors = 0;\n digibeta_dropouts = 0;\n num_digibeta_dropouts = 0;\n timecode_breaks = 0;\n num_timecode_breaks = 0;\n}\n\nMXFAPPInfo::~MXFAPPInfo()\n{\n ResetAll();\n}\n\nbool MXFAPPInfo::CheckIssues(mxfpp::HeaderMetadata *header_metadata)\n{\n return mxf_app_check_issues(header_metadata->getCHeaderMetadata());\n\n}\n\nbool MXFAPPInfo::ReadAll(HeaderMetadata *header_metadata)\n{\n ResetAll();\n\n if (!ReadInfo(header_metadata))\n return false;\n\n ReadPSEFailures(header_metadata);\n ReadVTRErrors(header_metadata);\n ReadDigiBetaDropouts(header_metadata);\n ReadTimecodeBreaks(header_metadata);\n\n return true;\n}\n\nbool MXFAPPInfo::ReadInfo(HeaderMetadata *header_metadata)\n{\n ResetInfo();\n\n ArchiveMXFInfo info;\n if (!mxf_app_get_info(header_metadata->getCHeaderMetadata(), &info))\n return false;\n\n original_filename = info.filename;\n if (info.haveSourceInfaxData) {\n source_record = new InfaxData;\n *source_record = info.sourceInfaxData;\n }\n if (info.haveLTOInfaxData) {\n lto_record = new InfaxData;\n *lto_record = info.ltoInfaxData;\n }\n vtr_error_count = info.vtrErrorCount;\n pse_failure_count = info.pseFailureCount;\n digibeta_dropout_count = info.digibetaDropoutCount;\n timecode_break_count = info.timecodeBreakCount;\n\n return true;\n}\n\nbool MXFAPPInfo::ReadPSEFailures(HeaderMetadata *header_metadata)\n{\n ResetPSEFailures();\n\n return mxf_app_get_pse_failures(header_metadata->getCHeaderMetadata(), &pse_failures, &num_pse_failures);\n}\n\nbool MXFAPPInfo::ReadVTRErrors(HeaderMetadata *header_metadata)\n{\n ResetVTRErrors();\n\n return mxf_app_get_vtr_errors(header_metadata->getCHeaderMetadata(), &vtr_errors, &num_vtr_errors);\n}\n\nbool MXFAPPInfo::ReadDigiBetaDropouts(HeaderMetadata *header_metadata)\n{\n ResetDigiBetaDropouts();\n\n return mxf_app_get_digibeta_dropouts(header_metadata->getCHeaderMetadata(), &digibeta_dropouts, &num_digibeta_dropouts);\n}\n\nbool MXFAPPInfo::ReadTimecodeBreaks(HeaderMetadata *header_metadata)\n{\n ResetTimecodeBreaks();\n\n return mxf_app_get_timecode_breaks(header_metadata->getCHeaderMetadata(), &timecode_breaks, &num_timecode_breaks);\n}\n\nvoid MXFAPPInfo::ResetAll()\n{\n ResetInfo();\n ResetPSEFailures();\n ResetVTRErrors();\n ResetDigiBetaDropouts();\n ResetTimecodeBreaks();\n}\n\nvoid MXFAPPInfo::ResetInfo()\n{\n original_filename.clear();\n delete source_record;\n source_record = 0;\n delete lto_record;\n lto_record = 0;\n}\n\nvoid MXFAPPInfo::ResetPSEFailures()\n{\n free(pse_failures);\n pse_failures = 0;\n num_pse_failures = 0;\n}\n\nvoid MXFAPPInfo::ResetVTRErrors()\n{\n free(vtr_errors);\n vtr_errors = 0;\n num_vtr_errors = 0;\n}\n\nvoid MXFAPPInfo::ResetDigiBetaDropouts()\n{\n free(digibeta_dropouts);\n digibeta_dropouts = 0;\n num_digibeta_dropouts = 0;\n}\n\nvoid MXFAPPInfo::ResetTimecodeBreaks()\n{\n free(timecode_breaks);\n timecode_breaks = 0;\n num_timecode_breaks = 0;\n}\n\n<commit_msg>mxf2raw: fix incomplete bbc archive data model<commit_after>\/*\n * Copyright (C) 2012, British Broadcasting Corporation\n * All Rights Reserved.\n *\n * Author: Philip de Nier\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the British Broadcasting Corporation nor the names\n * of its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cstdlib>\n#include <cstring>\n\n#include <bmx\/mxf_reader\/MXFAPPInfo.h>\n#include <mxf\/mxf_app.h>\n#include <bmx\/BMXException.h>\n#include <bmx\/Logging.h>\n\nusing namespace std;\nusing namespace bmx;\nusing namespace mxfpp;\n\n\n\nvoid MXFAPPInfo::RegisterExtensions(HeaderMetadata *header_metadata)\n{\n BMX_CHECK(mxf_app_load_extensions(header_metadata->getDataModel()->getCDataModel()));\n header_metadata->getDataModel()->finalise();\n}\n\nbool MXFAPPInfo::IsAPP(HeaderMetadata *header_metadata)\n{\n return mxf_app_is_app_mxf(header_metadata->getCHeaderMetadata());\n}\n\nMXFAPPInfo::MXFAPPInfo()\n{\n source_record = 0;\n lto_record = 0;\n pse_failures = 0;\n num_pse_failures = 0;\n vtr_errors = 0;\n num_vtr_errors = 0;\n digibeta_dropouts = 0;\n num_digibeta_dropouts = 0;\n timecode_breaks = 0;\n num_timecode_breaks = 0;\n}\n\nMXFAPPInfo::~MXFAPPInfo()\n{\n ResetAll();\n}\n\nbool MXFAPPInfo::CheckIssues(mxfpp::HeaderMetadata *header_metadata)\n{\n return mxf_app_check_issues(header_metadata->getCHeaderMetadata());\n\n}\n\nbool MXFAPPInfo::ReadAll(HeaderMetadata *header_metadata)\n{\n ResetAll();\n\n if (!ReadInfo(header_metadata))\n return false;\n\n ReadPSEFailures(header_metadata);\n ReadVTRErrors(header_metadata);\n ReadDigiBetaDropouts(header_metadata);\n ReadTimecodeBreaks(header_metadata);\n\n return true;\n}\n\nbool MXFAPPInfo::ReadInfo(HeaderMetadata *header_metadata)\n{\n ResetInfo();\n\n ArchiveMXFInfo info;\n if (!mxf_app_get_info(header_metadata->getCHeaderMetadata(), &info))\n return false;\n\n original_filename = info.filename;\n if (info.haveSourceInfaxData) {\n source_record = new InfaxData;\n *source_record = info.sourceInfaxData;\n }\n if (info.haveLTOInfaxData) {\n lto_record = new InfaxData;\n *lto_record = info.ltoInfaxData;\n }\n vtr_error_count = info.vtrErrorCount;\n pse_failure_count = info.pseFailureCount;\n digibeta_dropout_count = info.digibetaDropoutCount;\n timecode_break_count = info.timecodeBreakCount;\n\n return true;\n}\n\nbool MXFAPPInfo::ReadPSEFailures(HeaderMetadata *header_metadata)\n{\n ResetPSEFailures();\n\n return mxf_app_get_pse_failures(header_metadata->getCHeaderMetadata(), &pse_failures, &num_pse_failures);\n}\n\nbool MXFAPPInfo::ReadVTRErrors(HeaderMetadata *header_metadata)\n{\n ResetVTRErrors();\n\n return mxf_app_get_vtr_errors(header_metadata->getCHeaderMetadata(), &vtr_errors, &num_vtr_errors);\n}\n\nbool MXFAPPInfo::ReadDigiBetaDropouts(HeaderMetadata *header_metadata)\n{\n ResetDigiBetaDropouts();\n\n return mxf_app_get_digibeta_dropouts(header_metadata->getCHeaderMetadata(), &digibeta_dropouts, &num_digibeta_dropouts);\n}\n\nbool MXFAPPInfo::ReadTimecodeBreaks(HeaderMetadata *header_metadata)\n{\n ResetTimecodeBreaks();\n\n return mxf_app_get_timecode_breaks(header_metadata->getCHeaderMetadata(), &timecode_breaks, &num_timecode_breaks);\n}\n\nvoid MXFAPPInfo::ResetAll()\n{\n ResetInfo();\n ResetPSEFailures();\n ResetVTRErrors();\n ResetDigiBetaDropouts();\n ResetTimecodeBreaks();\n}\n\nvoid MXFAPPInfo::ResetInfo()\n{\n original_filename.clear();\n delete source_record;\n source_record = 0;\n delete lto_record;\n lto_record = 0;\n}\n\nvoid MXFAPPInfo::ResetPSEFailures()\n{\n free(pse_failures);\n pse_failures = 0;\n num_pse_failures = 0;\n}\n\nvoid MXFAPPInfo::ResetVTRErrors()\n{\n free(vtr_errors);\n vtr_errors = 0;\n num_vtr_errors = 0;\n}\n\nvoid MXFAPPInfo::ResetDigiBetaDropouts()\n{\n free(digibeta_dropouts);\n digibeta_dropouts = 0;\n num_digibeta_dropouts = 0;\n}\n\nvoid MXFAPPInfo::ResetTimecodeBreaks()\n{\n free(timecode_breaks);\n timecode_breaks = 0;\n num_timecode_breaks = 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright (C) 2017 Kitsune Ral <kitsune-ral@users.sf.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"avatar.h\"\n\n#include \"jobs\/mediathumbnailjob.h\"\n#include \"events\/eventcontent.h\"\n#include \"connection.h\"\n\n#include <QtGui\/QPainter>\n#include <QtCore\/QPointer>\n\nusing namespace QMatrixClient;\n\nclass Avatar::Private\n{\n public:\n explicit Private(QIcon di, QUrl url = {})\n : _defaultIcon(di), _url(url)\n { }\n QImage get(Connection* connection, QSize size,\n get_callback_t callback) const;\n bool upload(UploadContentJob* job, upload_callback_t callback);\n\n bool checkUrl(QUrl url) const;\n\n const QIcon _defaultIcon;\n QUrl _url;\n\n \/\/ The below are related to image caching, hence mutable\n mutable QImage _originalImage;\n mutable std::vector<QPair<QSize, QImage>> _scaledImages;\n mutable QSize _requestedSize;\n mutable bool _bannedUrl = false;\n mutable bool _fetched = false;\n mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;\n mutable QPointer<BaseJob> _uploadRequest = nullptr;\n mutable std::vector<get_callback_t> callbacks;\n mutable get_callback_t uploadCallback;\n};\n\nAvatar::Avatar(QIcon defaultIcon)\n : d(std::make_unique<Private>(std::move(defaultIcon)))\n{ }\n\nAvatar::Avatar(QUrl url, QIcon defaultIcon)\n : d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))\n{ }\n\nAvatar::Avatar(Avatar&&) = default;\n\nAvatar::~Avatar() = default;\n\nAvatar& Avatar::operator=(Avatar&&) = default;\n\nQImage Avatar::get(Connection* connection, int dimension,\n get_callback_t callback) const\n{\n return d->get(connection, {dimension, dimension}, callback);\n}\n\nQImage Avatar::get(Connection* connection, int width, int height,\n get_callback_t callback) const\n{\n return d->get(connection, {width, height}, callback);\n}\n\nbool Avatar::upload(Connection* connection, const QString& fileName,\n upload_callback_t callback) const\n{\n if (isJobRunning(d->_uploadRequest))\n return false;\n return d->upload(connection->uploadFile(fileName), callback);\n}\n\nbool Avatar::upload(Connection* connection, QIODevice* source,\n upload_callback_t callback) const\n{\n if (isJobRunning(d->_uploadRequest) || !source->isReadable())\n return false;\n return d->upload(connection->uploadContent(source), callback);\n}\n\nQString Avatar::mediaId() const\n{\n return d->_url.authority() + d->_url.path();\n}\n\nQImage Avatar::Private::get(Connection* connection, QSize size,\n get_callback_t callback) const\n{\n \/\/ FIXME: Alternating between longer-width and longer-height requests\n \/\/ is a sure way to trick the below code into constantly getting another\n \/\/ image from the server because the existing one is alleged unsatisfactory.\n \/\/ This is plain abuse by the client, though; so not critical for now.\n if( ( !(_fetched || _thumbnailRequest)\n || size.width() > _requestedSize.width()\n || size.height() > _requestedSize.height() ) && checkUrl(_url) )\n {\n qCDebug(MAIN) << \"Getting avatar from\" << _url.toString();\n _requestedSize = size;\n if (isJobRunning(_thumbnailRequest))\n _thumbnailRequest->abandon();\n callbacks.emplace_back(std::move(callback));\n _thumbnailRequest = connection->getThumbnail(_url, size);\n QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, [this]\n {\n _fetched = true;\n _originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize);\n _scaledImages.clear();\n for (auto n: callbacks)\n n();\n });\n }\n\n if( _originalImage.isNull() )\n {\n if (_defaultIcon.isNull())\n return _originalImage;\n\n QPainter p { &_originalImage };\n _defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });\n }\n\n for (auto p: _scaledImages)\n if (p.first == size)\n return p.second;\n auto result = _originalImage.scaled(size,\n Qt::KeepAspectRatio, Qt::SmoothTransformation);\n _scaledImages.emplace_back(size, result);\n return result;\n}\n\nbool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)\n{\n _uploadRequest = job;\n if (!isJobRunning(_uploadRequest))\n return false;\n _uploadRequest->connect(_uploadRequest, &BaseJob::success,\n [job,callback] { callback(job->contentUri()); });\n return true;\n}\n\nbool Avatar::Private::checkUrl(QUrl url) const\n{\n if (_bannedUrl || url.isEmpty())\n return false;\n\n \/\/ FIXME: Make \"mxc\" a library-wide constant and maybe even make\n \/\/ the URL checker a Connection(?) method.\n _bannedUrl = !(url.isValid() &&\n url.scheme() == \"mxc\" && url.path().count('\/') == 1);\n if (_bannedUrl)\n qCWarning(MAIN) << \"Avatar URL is invalid or not mxc-based:\"\n << url.toDisplayString();\n return !_bannedUrl;\n}\n\nQUrl Avatar::url() const { return d->_url; }\n\nbool Avatar::updateUrl(const QUrl& newUrl)\n{\n if (newUrl == d->_url)\n return false;\n\n d->_url = newUrl;\n d->_fetched = false;\n if (isJobRunning(d->_thumbnailRequest))\n d->_thumbnailRequest->abandon();\n return true;\n}\n\n<commit_msg>Avatar: clear the list of callbacks after completion + general code cleanup<commit_after>#include <utility>\n\n\/******************************************************************************\n * Copyright (C) 2017 Kitsune Ral <kitsune-ral@users.sf.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"avatar.h\"\n\n#include \"jobs\/mediathumbnailjob.h\"\n#include \"events\/eventcontent.h\"\n#include \"connection.h\"\n\n#include <QtGui\/QPainter>\n#include <QtCore\/QPointer>\n\nusing namespace QMatrixClient;\nusing std::move;\n\nclass Avatar::Private\n{\n public:\n explicit Private(QIcon di, QUrl url = {})\n : _defaultIcon(move(di)), _url(move(url))\n { }\n QImage get(Connection* connection, QSize size,\n get_callback_t callback) const;\n bool upload(UploadContentJob* job, upload_callback_t callback);\n\n bool checkUrl(QUrl url) const;\n\n const QIcon _defaultIcon;\n QUrl _url;\n\n \/\/ The below are related to image caching, hence mutable\n mutable QImage _originalImage;\n mutable std::vector<QPair<QSize, QImage>> _scaledImages;\n mutable QSize _requestedSize;\n mutable bool _bannedUrl = false;\n mutable bool _fetched = false;\n mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr;\n mutable QPointer<BaseJob> _uploadRequest = nullptr;\n mutable std::vector<get_callback_t> callbacks;\n};\n\nAvatar::Avatar(QIcon defaultIcon)\n : d(std::make_unique<Private>(std::move(defaultIcon)))\n{ }\n\nAvatar::Avatar(QUrl url, QIcon defaultIcon)\n : d(std::make_unique<Private>(std::move(defaultIcon), std::move(url)))\n{ }\n\nAvatar::Avatar(Avatar&&) = default;\n\nAvatar::~Avatar() = default;\n\nAvatar& Avatar::operator=(Avatar&&) = default;\n\nQImage Avatar::get(Connection* connection, int dimension,\n get_callback_t callback) const\n{\n return d->get(connection, {dimension, dimension}, move(callback));\n}\n\nQImage Avatar::get(Connection* connection, int width, int height,\n get_callback_t callback) const\n{\n return d->get(connection, {width, height}, move(callback));\n}\n\nbool Avatar::upload(Connection* connection, const QString& fileName,\n upload_callback_t callback) const\n{\n if (isJobRunning(d->_uploadRequest))\n return false;\n return d->upload(connection->uploadFile(fileName), move(callback));\n}\n\nbool Avatar::upload(Connection* connection, QIODevice* source,\n upload_callback_t callback) const\n{\n if (isJobRunning(d->_uploadRequest) || !source->isReadable())\n return false;\n return d->upload(connection->uploadContent(source), move(callback));\n}\n\nQString Avatar::mediaId() const\n{\n return d->_url.authority() + d->_url.path();\n}\n\nQImage Avatar::Private::get(Connection* connection, QSize size,\n get_callback_t callback) const\n{\n \/\/ FIXME: Alternating between longer-width and longer-height requests\n \/\/ is a sure way to trick the below code into constantly getting another\n \/\/ image from the server because the existing one is alleged unsatisfactory.\n \/\/ This is plain abuse by the client, though; so not critical for now.\n if( ( !(_fetched || _thumbnailRequest)\n || size.width() > _requestedSize.width()\n || size.height() > _requestedSize.height() ) && checkUrl(_url) )\n {\n qCDebug(MAIN) << \"Getting avatar from\" << _url.toString();\n _requestedSize = size;\n if (isJobRunning(_thumbnailRequest))\n _thumbnailRequest->abandon();\n callbacks.emplace_back(move(callback));\n _thumbnailRequest = connection->getThumbnail(_url, size);\n QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success,\n _thumbnailRequest, [this] {\n _fetched = true;\n _originalImage =\n _thumbnailRequest->scaledThumbnail(_requestedSize);\n _scaledImages.clear();\n for (const auto& n: callbacks)\n n();\n callbacks.clear();\n });\n }\n\n if( _originalImage.isNull() )\n {\n if (_defaultIcon.isNull())\n return _originalImage;\n\n QPainter p { &_originalImage };\n _defaultIcon.paint(&p, { QPoint(), _defaultIcon.actualSize(size) });\n }\n\n for (const auto& p: _scaledImages)\n if (p.first == size)\n return p.second;\n auto result = _originalImage.scaled(size,\n Qt::KeepAspectRatio, Qt::SmoothTransformation);\n _scaledImages.emplace_back(size, result);\n return result;\n}\n\nbool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback)\n{\n _uploadRequest = job;\n if (!isJobRunning(_uploadRequest))\n return false;\n _uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest,\n [job,callback] { callback(job->contentUri()); });\n return true;\n}\n\nbool Avatar::Private::checkUrl(QUrl url) const\n{\n if (_bannedUrl || url.isEmpty())\n return false;\n\n \/\/ FIXME: Make \"mxc\" a library-wide constant and maybe even make\n \/\/ the URL checker a Connection(?) method.\n _bannedUrl = !(url.isValid() &&\n url.scheme() == \"mxc\" && url.path().count('\/') == 1);\n if (_bannedUrl)\n qCWarning(MAIN) << \"Avatar URL is invalid or not mxc-based:\"\n << url.toDisplayString();\n return !_bannedUrl;\n}\n\nQUrl Avatar::url() const { return d->_url; }\n\nbool Avatar::updateUrl(const QUrl& newUrl)\n{\n if (newUrl == d->_url)\n return false;\n\n d->_url = newUrl;\n d->_fetched = false;\n if (isJobRunning(d->_thumbnailRequest))\n d->_thumbnailRequest->abandon();\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ .each(...any boundValues, function callback) -> undefined\n\nNAN_METHOD(Statement::Each) {\n\tStatement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This());\n\tif (!(stmt->state & RETURNS_DATA)) {\n\t\treturn Nan::ThrowTypeError(\"This statement does not return data. Use run() instead\");\n\t}\n\tREQUIRE_LAST_ARGUMENT_FUNCTION(func_index, callback);\n\tQUERY_START(stmt, statement, STATEMENT_BIND, info, func_index);\n\tconst bool safe_integers = (stmt->state & SAFE_INTS) != 0;\n\tconst bool pluck = (stmt->state & PLUCK_COLUMN) != 0;\n\tv8::Isolate* const isolate = v8::Isolate::GetCurrent();\n\t\n\tstmt->db->busy = true;\n\t\n\t\/\/ Retrieve and feed rows.\n\twhile (sqlite3_step(stmt->st_handle) == SQLITE_ROW) {\n\t\tv8::HandleScope scope(isolate);\n\t\t\n\t\tv8::Local<v8::Value> args[1];\n\t\targs[0] = pluck ? Data::GetValueJS(stmt->st_handle, 0, safe_integers)\n\t\t : Data::GetRowJS(stmt->st_handle, safe_integers);\n\t\tv8::MaybeLocal<v8::Value> callback_return_value = callback->Call(Nan::GetCurrentContext(), Nan::Null(), 1, args);\n\t\t\n\t\t\/\/ If an exception was thrown in the callback, clean up and stop.\n\t\tif (callback_return_value.IsEmpty()) {\n\t\t\tsqlite3_reset(stmt->st_handle);\n\t\t\tstmt->db->busy = false;\n\t\t\tstmt->db->was_js_error = true;\n\t\t\tQUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tstmt->db->busy = false;\n\t\n\tif (sqlite3_reset(stmt->st_handle) == SQLITE_OK) {\n\t\tQUERY_RETURN(stmt, STATEMENT_CLEAR_BINDINGS, Nan::Undefined());\n\t}\n\tQUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);\n}\n<commit_msg>perf tweak<commit_after>\/\/ .each(...any boundValues, function callback) -> undefined\n\nNAN_METHOD(Statement::Each) {\n\tStatement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This());\n\tif (!(stmt->state & RETURNS_DATA)) {\n\t\treturn Nan::ThrowTypeError(\"This statement does not return data. Use run() instead\");\n\t}\n\tREQUIRE_LAST_ARGUMENT_FUNCTION(func_index, callback);\n\tQUERY_START(stmt, statement, STATEMENT_BIND, info, func_index);\n\tconst bool safe_integers = (stmt->state & SAFE_INTS) != 0;\n\tconst bool pluck = (stmt->state & PLUCK_COLUMN) != 0;\n\tv8::Isolate* const isolate = info.GetIsolate();\n\t\n\tstmt->db->busy = true;\n\t\n\t\/\/ Retrieve and feed rows.\n\twhile (sqlite3_step(stmt->st_handle) == SQLITE_ROW) {\n\t\tv8::HandleScope scope(isolate);\n\t\t\n\t\tv8::Local<v8::Value> args[1];\n\t\targs[0] = pluck ? Data::GetValueJS(stmt->st_handle, 0, safe_integers)\n\t\t : Data::GetRowJS(stmt->st_handle, safe_integers);\n\t\tv8::MaybeLocal<v8::Value> callback_return_value = callback->Call(Nan::GetCurrentContext(), Nan::Null(), 1, args);\n\t\t\n\t\t\/\/ If an exception was thrown in the callback, clean up and stop.\n\t\tif (callback_return_value.IsEmpty()) {\n\t\t\tsqlite3_reset(stmt->st_handle);\n\t\t\tstmt->db->busy = false;\n\t\t\tstmt->db->was_js_error = true;\n\t\t\tQUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tstmt->db->busy = false;\n\t\n\tif (sqlite3_reset(stmt->st_handle) == SQLITE_OK) {\n\t\tQUERY_RETURN(stmt, STATEMENT_CLEAR_BINDINGS, Nan::Undefined());\n\t}\n\tQUERY_THROW(stmt, STATEMENT_CLEAR_BINDINGS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/petsc_macro.h\"\n\n\/\/ This only works with petsc-3.3 and above.\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/nonlinear_implicit_system.h\"\n#include \"libmesh\/petsc_dm_nonlinear_solver.h\"\n#include \"libmesh\/petsc_linear_solver.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/preconditioner.h\"\n\n\/\/ PETSc extern definition\nEXTERN_C_BEGIN\nPetscErrorCode DMCreate_libMesh(DM);\nEXTERN_C_END\n\n#include <libmesh\/petscdmlibmesh.h>\n\nnamespace libMesh {\n PetscBool PetscDMRegistered = PETSC_FALSE;\n void PetscDMRegister()\n {\n if (PetscDMRegistered)\n return;\n\n PetscErrorCode ierr;\n ierr = DMRegister(DMLIBMESH, PETSC_NULL, \"DMCreate_libMesh\", DMCreate_libMesh); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n PetscDMRegistered = PETSC_TRUE;\n }\n\n\n template <typename T>\n PetscDMNonlinearSolver<T>::PetscDMNonlinearSolver(sys_type& system) :\n PetscNonlinearSolver<T>(system)\n {\n PetscDMRegister();\n }\n\n template <typename T>\n inline\n PetscDMNonlinearSolver<T>::~PetscDMNonlinearSolver ()\n {\n this->clear ();\n }\n\n\n\n template <typename T>\n void PetscDMNonlinearSolver<T>::init()\n {\n PetscErrorCode ierr;\n DM dm;\n this->PetscNonlinearSolver<T>::init();\n\n \/\/ Attaching a DM with the function and Jacobian callbacks to SNES.\n ierr = DMCreateLibMesh(libMesh::COMM_WORLD, this->system(), &dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = DMSetFromOptions(dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = DMSetUp(dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = SNESSetDM(this->_snes, dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n \/\/ SNES now owns the reference to dm.\n ierr = DMDestroy(&dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n KSP ksp;\n ierr = SNESGetKSP (this->_snes, &ksp); CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the iterative solver. Use the user-supplied\n \/\/ tolerance for the relative residual & leave the others at default values\n ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,PETSC_DEFAULT, this->max_linear_iterations); CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the non-linear solver.\n ierr = SNESSetTolerances(this->_snes,\n\t\t\t this->absolute_residual_tolerance,\n\t\t\t this->relative_residual_tolerance,\n\t\t\t this->absolute_step_tolerance,\n\t\t\t this->max_nonlinear_iterations,\n\t\t\t this->max_function_evaluations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/Pull in command-line options\n KSPSetFromOptions(ksp);\n SNESSetFromOptions(this->_snes);\n }\n\n\n template <typename T>\n std::pair<unsigned int, Real>\n PetscDMNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\t NumericVector<T>& x_in, \/\/ Solution vector\n\t\t\t\t NumericVector<T>& r_in, \/\/ Residual vector\n\t\t\t\t const double, \/\/ Stopping tolerance\n\t\t\t\t const unsigned int)\n {\n START_LOG(\"solve()\", \"PetscNonlinearSolver\");\n this->init ();\n\n \/\/ Make sure the data passed in are really of Petsc types\n libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);\n libmesh_cast_ptr<PetscVector<T>*>(&r_in);\n\n \/\/ Extract solution vector\n PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);\n\n int ierr=0;\n int n_iterations =0;\n\n \/\/ Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal\n Real final_residual_norm=0.;\n\n if (this->user_presolve)\n this->user_presolve(this->system());\n\n \/\/Set the preconditioning matrix\n if (this->_preconditioner)\n this->_preconditioner->set_matrix(jac_in);\n\n ierr = SNESSolve (this->_snes, PETSC_NULL, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetIterationNumber(this->_snes,&n_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetLinearSolveIterations(this->_snes, &this->_n_linear_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetFunctionNorm(this->_snes,&final_residual_norm);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Get and store the reason for convergence\n SNESGetConvergedReason(this->_snes, &this->_reason);\n\n \/\/Based on Petsc 2.3.3 documentation all diverged reasons are negative\n this->converged = (this->_reason >= 0);\n\n this->clear();\n\n STOP_LOG(\"solve()\", \"PetscNonlinearSolver\");\n\n \/\/ return the # of its. and the final residual norm.\n return std::make_pair(n_iterations, final_residual_norm);\n }\n\n\n \/\/------------------------------------------------------------------\n \/\/ Explicit instantiations\n template class PetscDMNonlinearSolver<Number>;\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ #if !PETSC_VERSION_LESS_THAN(3,3,0)\n<commit_msg>Changes in petsc_dm_nonlinear_solver.C for -Wshadow.<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"libmesh\/petsc_macro.h\"\n\n\/\/ This only works with petsc-3.3 and above.\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/nonlinear_implicit_system.h\"\n#include \"libmesh\/petsc_dm_nonlinear_solver.h\"\n#include \"libmesh\/petsc_linear_solver.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/preconditioner.h\"\n\n\/\/ PETSc extern definition\nEXTERN_C_BEGIN\nPetscErrorCode DMCreate_libMesh(DM);\nEXTERN_C_END\n\n#include <libmesh\/petscdmlibmesh.h>\n\nnamespace libMesh {\n PetscBool PetscDMRegistered = PETSC_FALSE;\n void PetscDMRegister()\n {\n if (PetscDMRegistered)\n return;\n\n PetscErrorCode ierr;\n ierr = DMRegister(DMLIBMESH, PETSC_NULL, \"DMCreate_libMesh\", DMCreate_libMesh); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n PetscDMRegistered = PETSC_TRUE;\n }\n\n\n template <typename T>\n PetscDMNonlinearSolver<T>::PetscDMNonlinearSolver(sys_type& system_in) :\n PetscNonlinearSolver<T>(system_in)\n {\n PetscDMRegister();\n }\n\n template <typename T>\n inline\n PetscDMNonlinearSolver<T>::~PetscDMNonlinearSolver ()\n {\n this->clear ();\n }\n\n\n\n template <typename T>\n void PetscDMNonlinearSolver<T>::init()\n {\n PetscErrorCode ierr;\n DM dm;\n this->PetscNonlinearSolver<T>::init();\n\n \/\/ Attaching a DM with the function and Jacobian callbacks to SNES.\n ierr = DMCreateLibMesh(libMesh::COMM_WORLD, this->system(), &dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = DMSetFromOptions(dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = DMSetUp(dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n ierr = SNESSetDM(this->_snes, dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n \/\/ SNES now owns the reference to dm.\n ierr = DMDestroy(&dm); CHKERRABORT(libMesh::COMM_WORLD, ierr);\n KSP ksp;\n ierr = SNESGetKSP (this->_snes, &ksp); CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the iterative solver. Use the user-supplied\n \/\/ tolerance for the relative residual & leave the others at default values\n ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,PETSC_DEFAULT, this->max_linear_iterations); CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Set the tolerances for the non-linear solver.\n ierr = SNESSetTolerances(this->_snes,\n\t\t\t this->absolute_residual_tolerance,\n\t\t\t this->relative_residual_tolerance,\n\t\t\t this->absolute_step_tolerance,\n\t\t\t this->max_nonlinear_iterations,\n\t\t\t this->max_function_evaluations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/Pull in command-line options\n KSPSetFromOptions(ksp);\n SNESSetFromOptions(this->_snes);\n }\n\n\n template <typename T>\n std::pair<unsigned int, Real>\n PetscDMNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\t NumericVector<T>& x_in, \/\/ Solution vector\n\t\t\t\t NumericVector<T>& r_in, \/\/ Residual vector\n\t\t\t\t const double, \/\/ Stopping tolerance\n\t\t\t\t const unsigned int)\n {\n START_LOG(\"solve()\", \"PetscNonlinearSolver\");\n this->init ();\n\n \/\/ Make sure the data passed in are really of Petsc types\n libmesh_cast_ptr<PetscMatrix<T>*>(&jac_in);\n libmesh_cast_ptr<PetscVector<T>*>(&r_in);\n\n \/\/ Extract solution vector\n PetscVector<T>* x = libmesh_cast_ptr<PetscVector<T>*>(&x_in);\n\n int ierr=0;\n int n_iterations =0;\n\n \/\/ Should actually be a PetscReal, but I don't know which version of PETSc first introduced PetscReal\n Real final_residual_norm=0.;\n\n if (this->user_presolve)\n this->user_presolve(this->system());\n\n \/\/Set the preconditioning matrix\n if (this->_preconditioner)\n this->_preconditioner->set_matrix(jac_in);\n\n ierr = SNESSolve (this->_snes, PETSC_NULL, x->vec());\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetIterationNumber(this->_snes,&n_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetLinearSolveIterations(this->_snes, &this->_n_linear_iterations);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n ierr = SNESGetFunctionNorm(this->_snes,&final_residual_norm);\n CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n \/\/ Get and store the reason for convergence\n SNESGetConvergedReason(this->_snes, &this->_reason);\n\n \/\/Based on Petsc 2.3.3 documentation all diverged reasons are negative\n this->converged = (this->_reason >= 0);\n\n this->clear();\n\n STOP_LOG(\"solve()\", \"PetscNonlinearSolver\");\n\n \/\/ return the # of its. and the final residual norm.\n return std::make_pair(n_iterations, final_residual_norm);\n }\n\n\n \/\/------------------------------------------------------------------\n \/\/ Explicit instantiations\n template class PetscDMNonlinearSolver<Number>;\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ #if !PETSC_VERSION_LESS_THAN(3,3,0)\n<|endoftext|>"} {"text":"<commit_before>\/* _______ __ __ __ ______ __ __ _______ __ __\n * \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___ \/\\ \/ |\\\/ \/\\\n * \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n * \/ \/ \/__ \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/ \/ ___ \/ \/\/ ___ \/ \/\/ \/| ' \/ \/\n * \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_ \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ | \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n * Js_.\/\n * Per Larsson a.k.a finalman _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem _asww7!uY`> )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk<P ` _: :+' .' \"{[\n * .)j(] .d_\/ '-( P . S\n * License: (BSD) <Td\/Z <fP\"5(\\\"??\"\\a. .L\n * Redistribution and use in source and _dV>ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<<WP+k\/);. _W=j f\n * 1. Redistributions of source code must .$%w\\\/]Q . .\"' . mj$\n * retain the above copyright notice, ]E.pYY(Q]>. a J@\\\n * this list of conditions and the j(]1u<sE\"L,. . .\/^ ]{a\n * following disclaimer. 4'_uomm\\. )L);-4 (3=\n * 2. Redistributions in binary form must )_]X{Z('a_\"a7'<a\"a, ]\"[\n * reproduce the above copyright notice, #}<]m7`Za??4,P-\"'7. ).m\n * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ\/\n * following disclaimer in the <B!<\/]C)d_, '(<' .f. =C+m\n * documentation and\/or other materials .Z!=J ]e []('-4f _ ) -.)m]'\n * provided with the distribution. .w[5]' _[ \/.)_-\"+? _\/ <W\"\n * 3. Neither the name of Guichan nor the :$we` _! + _\/ . j?\n * names of its contributors may be used =3)= _f (_yQmWW$#( \"\n * to endorse or promote products derived - W, sQQQQmZQ#Wwa]..\n * from this software without specific (js, \\[QQW$QWW#?!V\"\".\n * prior written permission. ]y:.<\\.. .\n * -]n w\/ ' [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )\/ )\/ !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY < (; sac , '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f\/<[]\/ ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%\"' \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/opengl\/openglgraphics.hpp\"\n\n#if defined (_WIN32)\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#endif\n\n#if defined (__amigaos4__)\n#include <mgl\/gl.h>\n#define glVertex3i glVertex3f\n#elif defined(__APPLE__)\n#include <OpenGL\/gl.h>\n#else\n#include <GL\/gl.h>\n#endif\n\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/image.hpp\"\n#include \"guichan\/opengl\/openglimage.hpp\"\n\nnamespace gcn\n{\n OpenGLGraphics::OpenGLGraphics()\n {\n setTargetPlane(640, 480);\n mAlpha = false;\n }\n\n OpenGLGraphics::OpenGLGraphics(int width, int height)\n {\n setTargetPlane(width, height);\n }\n\n OpenGLGraphics::~OpenGLGraphics()\n {\n\n }\n\n void OpenGLGraphics::_beginDraw()\n {\n glPushAttrib(\n GL_COLOR_BUFFER_BIT |\n GL_CURRENT_BIT |\n GL_DEPTH_BUFFER_BIT |\n GL_ENABLE_BIT |\n GL_FOG_BIT |\n GL_LIGHTING_BIT |\n GL_LINE_BIT |\n GL_POINT_BIT |\n GL_POLYGON_BIT |\n GL_SCISSOR_BIT |\n GL_STENCIL_BUFFER_BIT |\n GL_TEXTURE_BIT |\n GL_TRANSFORM_BIT |\n GL_POINT_BIT |\n GL_LINE_BIT\n );\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glMatrixMode(GL_TEXTURE);\n glPushMatrix();\n glLoadIdentity();\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n\n glOrtho(0.0,\n (double)mWidth,\n (double)mHeight,\n 0.0,\n -1.0,\n 1.0);\n\n glDisable(GL_LIGHTING);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_TEXTURE_2D);\n\n glEnable(GL_SCISSOR_TEST);\n glPointSize(1.0);\n glLineWidth(1.0);\n\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n\n pushClipArea(Rectangle(0, 0, mWidth, mHeight));\n }\n\n void OpenGLGraphics::_endDraw()\n {\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n glMatrixMode(GL_TEXTURE);\n glPopMatrix();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n\n glPopAttrib();\n\n popClipArea();\n }\n\n bool OpenGLGraphics::pushClipArea(Rectangle area)\n {\n bool result = Graphics::pushClipArea(area);\n\n glScissor(mClipStack.top().x,\n mHeight - mClipStack.top().y - mClipStack.top().height,\n mClipStack.top().width,\n mClipStack.top().height);\n\n return result;\n }\n\n void OpenGLGraphics::popClipArea()\n {\n Graphics::popClipArea();\n\n if (mClipStack.empty())\n {\n return;\n }\n\n glScissor(mClipStack.top().x,\n mHeight - mClipStack.top().y - mClipStack.top().height,\n mClipStack.top().width,\n mClipStack.top().height);\n }\n\n void OpenGLGraphics::setTargetPlane(int width, int height)\n {\n mWidth = width;\n mHeight = height;\n }\n\n void OpenGLGraphics::drawImage(const Image* image,\n int srcX,\n int srcY,\n int dstX,\n int dstY,\n int width,\n int height)\n {\n\t\tconst OpenGLImage* srcImage = dynamic_cast<const OpenGLImage*>(image);\n\n if (srcImage == NULL)\n {\n throw GCN_EXCEPTION(\"Trying to draw an image of unknown format, must be an OpenGLImage.\");\n }\n\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n dstX += top.xOffset;\n dstY += top.yOffset;\n\n \/\/ Find OpenGL texture coordinates\n float texX1 = srcX \/ (float)srcImage->getTextureWidth();\n float texY1 = srcY \/ (float)srcImage->getTextureHeight();\n float texX2 = (srcX+width) \/ (float)srcImage->getTextureWidth();\n float texY2 = (srcY+height) \/ (float)srcImage->getTextureHeight();\n\n glBindTexture(GL_TEXTURE_2D, srcImage->getTextureHandle());\n\n glEnable(GL_TEXTURE_2D);\n\n \/\/ Check if blending already is enabled\n if (!mAlpha)\n {\n glEnable(GL_BLEND);\n }\n\n \/\/ Draw a textured quad -- the image\n glBegin(GL_QUADS);\n glTexCoord2f(texX1, texY1);\n glVertex3i(dstX, dstY, 0);\n\n glTexCoord2f(texX1, texY2);\n glVertex3i(dstX, dstY + height, 0);\n\n glTexCoord2f(texX2, texY2);\n glVertex3i(dstX + width, dstY + height, 0);\n\n glTexCoord2f(texX2, texY1);\n glVertex3i(dstX + width, dstY, 0);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n\n \/\/ Don't disable blending if the color has alpha\n if (!mAlpha)\n {\n glDisable(GL_BLEND);\n }\n }\n\n void OpenGLGraphics::drawPoint(int x, int y)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n x += top.xOffset;\n y += top.yOffset;\n\n glBegin(GL_POINTS);\n glVertex3i(x, y, 0);\n glEnd();\n }\n\n void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n x1 += top.xOffset;\n y1 += top.yOffset;\n x2 += top.xOffset;\n y2 += top.yOffset;\n\n glBegin(GL_LINES);\n glVertex3f(x1 + 0.5f - 1, y1 + 0.5f, 0.0f);\n glVertex3f(x2 + 0.5f + 1, y2 + 0.5f, 0.0f);\n glEnd();\n\n glBegin(GL_POINTS);\n glVertex3f(x1 + 0.5f, y1 + 0.5f, 0.0f);\n glEnd();\n\n glBegin(GL_POINTS);\n glVertex3f(x2 + 0.5f, y2 + 0.5f, 0.0f);\n glEnd();\n }\n\n void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n glBegin(GL_LINE_LOOP);\n glVertex3f(rectangle.x + top.xOffset + 0.5f,\n rectangle.y + top.yOffset + 0.5f,\n 0);\n glVertex3f(rectangle.x + rectangle.width - 0.5f + top.xOffset,\n rectangle.y + top.yOffset + 0.5f,\n 0);\n glVertex3f(rectangle.x + rectangle.width - 0.5f + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset - 0.5f,\n 0);\n glVertex3f(rectangle.x + top.xOffset + 0.5f,\n rectangle.y + rectangle.height + top.yOffset - 0.5f,\n 0);\n glEnd();\n }\n\n void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n glBegin(GL_QUADS);\n glVertex3i(rectangle.x + top.xOffset,\n rectangle.y + top.yOffset,\n 0);\n glVertex3i(rectangle.x + rectangle.width + top.xOffset,\n rectangle.y + top.yOffset,\n 0);\n glVertex3i(rectangle.x + rectangle.width + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset,\n 0);\n glVertex3i(rectangle.x + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset,\n 0);\n glEnd();\n }\n\n void OpenGLGraphics::setColor(const Color& color)\n {\n mColor = color;\n glColor4ub(color.r, color.g, color.b, color.a);\n\n mAlpha = color.a != 255;\n\n if (mAlpha)\n {\n glEnable(GL_BLEND);\n }\n }\n\n const Color& OpenGLGraphics::getColor() const\n {\n return mColor;\n }\n}\n<commit_msg>Issue 6 has been fixed.<commit_after>\/* _______ __ __ __ ______ __ __ _______ __ __\n * \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___ \/\\ \/ |\\\/ \/\\\n * \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n * \/ \/ \/__ \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/ \/ ___ \/ \/\/ ___ \/ \/\/ \/| ' \/ \/\n * \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_ \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ | \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n * Js_.\/\n * Per Larsson a.k.a finalman _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem _asww7!uY`> )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk<P ` _: :+' .' \"{[\n * .)j(] .d_\/ '-( P . S\n * License: (BSD) <Td\/Z <fP\"5(\\\"??\"\\a. .L\n * Redistribution and use in source and _dV>ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<<WP+k\/);. _W=j f\n * 1. Redistributions of source code must .$%w\\\/]Q . .\"' . mj$\n * retain the above copyright notice, ]E.pYY(Q]>. a J@\\\n * this list of conditions and the j(]1u<sE\"L,. . .\/^ ]{a\n * following disclaimer. 4'_uomm\\. )L);-4 (3=\n * 2. Redistributions in binary form must )_]X{Z('a_\"a7'<a\"a, ]\"[\n * reproduce the above copyright notice, #}<]m7`Za??4,P-\"'7. ).m\n * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ\/\n * following disclaimer in the <B!<\/]C)d_, '(<' .f. =C+m\n * documentation and\/or other materials .Z!=J ]e []('-4f _ ) -.)m]'\n * provided with the distribution. .w[5]' _[ \/.)_-\"+? _\/ <W\"\n * 3. Neither the name of Guichan nor the :$we` _! + _\/ . j?\n * names of its contributors may be used =3)= _f (_yQmWW$#( \"\n * to endorse or promote products derived - W, sQQQQmZQ#Wwa]..\n * from this software without specific (js, \\[QQW$QWW#?!V\"\".\n * prior written permission. ]y:.<\\.. .\n * -]n w\/ ' [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )\/ )\/ !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY < (; sac , '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f\/<[]\/ ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%\"' \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/opengl\/openglgraphics.hpp\"\n\n#if defined (_WIN32)\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#endif\n\n#if defined (__amigaos4__)\n#include <mgl\/gl.h>\n#define glVertex3i glVertex3f\n#elif defined(__APPLE__)\n#include <OpenGL\/gl.h>\n#else\n#include <GL\/gl.h>\n#endif\n\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/image.hpp\"\n#include \"guichan\/opengl\/openglimage.hpp\"\n\nnamespace gcn\n{\n OpenGLGraphics::OpenGLGraphics()\n {\n setTargetPlane(640, 480);\n mAlpha = false;\n }\n\n OpenGLGraphics::OpenGLGraphics(int width, int height)\n {\n setTargetPlane(width, height);\n }\n\n OpenGLGraphics::~OpenGLGraphics()\n {\n\n }\n\n void OpenGLGraphics::_beginDraw()\n {\n glPushAttrib(\n GL_COLOR_BUFFER_BIT |\n GL_CURRENT_BIT |\n GL_DEPTH_BUFFER_BIT |\n GL_ENABLE_BIT |\n GL_FOG_BIT |\n GL_LIGHTING_BIT |\n GL_LINE_BIT |\n GL_POINT_BIT |\n GL_POLYGON_BIT |\n GL_SCISSOR_BIT |\n GL_STENCIL_BUFFER_BIT |\n GL_TEXTURE_BIT |\n GL_TRANSFORM_BIT |\n GL_POINT_BIT |\n GL_LINE_BIT\n );\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glMatrixMode(GL_TEXTURE);\n glPushMatrix();\n glLoadIdentity();\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n \n glOrtho(0.0,\n (double)mWidth,\n (double)mHeight,\n 0.0,\n -1.0,\n 1.0);\n\n glDisable(GL_LIGHTING);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_TEXTURE_2D);\n\n glEnable(GL_SCISSOR_TEST);\n glPointSize(1.0);\n glLineWidth(1.0);\n\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n\n pushClipArea(Rectangle(0, 0, mWidth, mHeight));\n }\n\n void OpenGLGraphics::_endDraw()\n {\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n glMatrixMode(GL_TEXTURE);\n glPopMatrix();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n\n glPopAttrib();\n\n popClipArea();\n }\n\n bool OpenGLGraphics::pushClipArea(Rectangle area)\n {\n bool result = Graphics::pushClipArea(area);\n\n glScissor(mClipStack.top().x,\n mHeight - mClipStack.top().y - mClipStack.top().height,\n mClipStack.top().width,\n mClipStack.top().height);\n\n return result;\n }\n\n void OpenGLGraphics::popClipArea()\n {\n Graphics::popClipArea();\n\n if (mClipStack.empty())\n {\n return;\n }\n\n glScissor(mClipStack.top().x,\n mHeight - mClipStack.top().y - mClipStack.top().height,\n mClipStack.top().width,\n mClipStack.top().height);\n }\n\n void OpenGLGraphics::setTargetPlane(int width, int height)\n {\n mWidth = width;\n mHeight = height;\n }\n\n void OpenGLGraphics::drawImage(const Image* image,\n int srcX,\n int srcY,\n int dstX,\n int dstY,\n int width,\n int height)\n {\n\t\tconst OpenGLImage* srcImage = dynamic_cast<const OpenGLImage*>(image);\n\n if (srcImage == NULL)\n {\n throw GCN_EXCEPTION(\"Trying to draw an image of unknown format, must be an OpenGLImage.\");\n }\n\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n dstX += top.xOffset;\n dstY += top.yOffset;\n\n \/\/ Find OpenGL texture coordinates\n float texX1 = srcX \/ (float)srcImage->getTextureWidth();\n float texY1 = srcY \/ (float)srcImage->getTextureHeight();\n float texX2 = (srcX+width) \/ (float)srcImage->getTextureWidth();\n float texY2 = (srcY+height) \/ (float)srcImage->getTextureHeight();\n\n glBindTexture(GL_TEXTURE_2D, srcImage->getTextureHandle());\n\n glEnable(GL_TEXTURE_2D);\n\n \/\/ Check if blending already is enabled\n if (!mAlpha)\n {\n glEnable(GL_BLEND);\n }\n\n \/\/ Draw a textured quad -- the image\n glBegin(GL_QUADS);\n glTexCoord2f(texX1, texY1);\n glVertex3i(dstX, dstY, 0);\n\n glTexCoord2f(texX1, texY2);\n glVertex3i(dstX, dstY + height, 0);\n\n glTexCoord2f(texX2, texY2);\n glVertex3i(dstX + width, dstY + height, 0);\n\n glTexCoord2f(texX2, texY1);\n glVertex3i(dstX + width, dstY, 0);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n\n \/\/ Don't disable blending if the color has alpha\n if (!mAlpha)\n {\n glDisable(GL_BLEND);\n }\n }\n\n void OpenGLGraphics::drawPoint(int x, int y)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n x += top.xOffset;\n y += top.yOffset;\n\n glBegin(GL_POINTS);\n glVertex3i(x, y, 0);\n glEnd();\n }\n\n void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n x1 += top.xOffset;\n y1 += top.yOffset;\n x2 += top.xOffset;\n y2 += top.yOffset;\n\n glBegin(GL_LINES);\n glVertex2f(x1 + 0.375,\n y1 + 0.375);\n glVertex2f(x2 + 1.0f - 0.375f,\n y2 + 1.0f - 0.375f);\n glEnd();\n }\n\n void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n \n glBegin(GL_LINE_LOOP);\n glVertex2f(rectangle.x + top.xOffset,\n rectangle.y + top.yOffset);\n glVertex2f(rectangle.x + rectangle.width + top.xOffset - 1.0f,\n rectangle.y + top.yOffset + 0.375f);\n glVertex2f(rectangle.x + rectangle.width + top.xOffset - 1.0f,\n rectangle.y + rectangle.height + top.yOffset);\n glVertex2f(rectangle.x + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset);\n glEnd();\n }\n\n void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)\n {\n if (mClipStack.empty())\n {\n throw GCN_EXCEPTION(\"Clip stack is empty, perhaps you called a draw funtion outside of _beginDraw() and _endDraw()?\");\n }\n\n const ClipRectangle& top = mClipStack.top();\n\n glBegin(GL_QUADS);\n glVertex2i(rectangle.x + top.xOffset,\n rectangle.y + top.yOffset);\n glVertex2i(rectangle.x + rectangle.width + top.xOffset,\n rectangle.y + top.yOffset);\n glVertex2i(rectangle.x + rectangle.width + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset);\n glVertex2i(rectangle.x + top.xOffset,\n rectangle.y + rectangle.height + top.yOffset);\n glEnd();\n }\n\n void OpenGLGraphics::setColor(const Color& color)\n {\n mColor = color;\n glColor4ub(color.r, color.g, color.b, color.a);\n\n mAlpha = color.a != 255;\n\n if (mAlpha)\n {\n glEnable(GL_BLEND);\n }\n }\n\n const Color& OpenGLGraphics::getColor() const\n {\n return mColor;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Matrix.h\"\n#include <osg\/Notify>\n\n\nbool readMatrix(osg::Matrix& matrix, osgDB::Input& fr, const char* keyword)\n{\n bool iteratorAdvanced = false;\n \n if (fr[0].matchWord(keyword) && fr[1].isOpenBracket())\n {\n\n osg::notify(osg::NOTICE)<<\"found keyword \"<<fr[0].getStr()<<\" looking for \"<<keyword<<std::endl;\n\n int entry = fr[0].getNoNestedBrackets();\n\n fr += 2;\n\n int row=0;\n int col=0;\n double v;\n while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)\n {\n if (fr[0].getFloat(v))\n {\n matrix(row,col)=v;\n ++col;\n if (col>=4)\n {\n col = 0;\n ++row;\n }\n ++fr;\n }\n else fr.advanceOverCurrentFieldOrBlock();\n }\n iteratorAdvanced = true;\n } \n \n return iteratorAdvanced;\n}\n\n\nbool writeMatrix(const osg::Matrix& matrix, osgDB::Output& fw, const char* keyword)\n{\n fw.indent() << keyword <<\" {\" << std::endl;\n fw.moveIn();\n fw.indent() << matrix(0,0) << \" \" << matrix(0,1) << \" \" << matrix(0,2) << \" \" << matrix(0,3) << std::endl;\n fw.indent() << matrix(1,0) << \" \" << matrix(1,1) << \" \" << matrix(1,2) << \" \" << matrix(1,3) << std::endl;\n fw.indent() << matrix(2,0) << \" \" << matrix(2,1) << \" \" << matrix(2,2) << \" \" << matrix(2,3) << std::endl;\n fw.indent() << matrix(3,0) << \" \" << matrix(3,1) << \" \" << matrix(3,2) << \" \" << matrix(3,3) << std::endl;\n fw.moveOut();\n fw.indent() << \"}\"<< std::endl;\n return true;\n}\n\n<commit_msg>Removed debugging message<commit_after>#include \"Matrix.h\"\n\n\nbool readMatrix(osg::Matrix& matrix, osgDB::Input& fr, const char* keyword)\n{\n bool iteratorAdvanced = false;\n \n if (fr[0].matchWord(keyword) && fr[1].isOpenBracket())\n {\n int entry = fr[0].getNoNestedBrackets();\n\n fr += 2;\n\n int row=0;\n int col=0;\n double v;\n while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)\n {\n if (fr[0].getFloat(v))\n {\n matrix(row,col)=v;\n ++col;\n if (col>=4)\n {\n col = 0;\n ++row;\n }\n ++fr;\n }\n else fr.advanceOverCurrentFieldOrBlock();\n }\n iteratorAdvanced = true;\n } \n \n return iteratorAdvanced;\n}\n\n\nbool writeMatrix(const osg::Matrix& matrix, osgDB::Output& fw, const char* keyword)\n{\n fw.indent() << keyword <<\" {\" << std::endl;\n fw.moveIn();\n fw.indent() << matrix(0,0) << \" \" << matrix(0,1) << \" \" << matrix(0,2) << \" \" << matrix(0,3) << std::endl;\n fw.indent() << matrix(1,0) << \" \" << matrix(1,1) << \" \" << matrix(1,2) << \" \" << matrix(1,3) << std::endl;\n fw.indent() << matrix(2,0) << \" \" << matrix(2,1) << \" \" << matrix(2,2) << \" \" << matrix(2,3) << std::endl;\n fw.indent() << matrix(3,0) << \" \" << matrix(3,1) << \" \" << matrix(3,2) << \" \" << matrix(3,3) << std::endl;\n fw.moveOut();\n fw.indent() << \"}\"<< std::endl;\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"camera\/cameraPerspective.hpp\"\n\nint main(void)\n{\n Vec3f origin = Vec3f(0,0,0);\n Vec3f view = Vec3f(1,0,0);\n Vec3f up = Vec3f(0,1,0);\n CameraPerspective* cp = new CameraPerspective(1920, 1080, origin, view, up, 0.035, 0.035);\n \n std::cout << cp << std::endl;\n delete cp;\n \n return 0;\n \n}<commit_msg>added some tests for perspective camera<commit_after>#include <iostream>\n\n#include \"camera\/cameraPerspective.hpp\"\n\nint main(void)\n{\n Vec3f origin = Vec3f(0,0,0);\n Vec3f view = Vec3f(1,0,0);\n Vec3f up = Vec3f(0,1,0);\n CameraPerspective* cp = new CameraPerspective(1920, 1080, origin, view, up, 0.035, 0.035);\n \n std::cout << cp << std::endl;\n \n std::cout << \"ray to 0,0 \" << cp->getRay(0, 0) << std::endl;\n std::cout << \"ray to 960, 540 \" << cp->getRay(960, 540) << std::endl;\n std::cout << \"ray to 1920, 1080 \" << cp->getRay(1920, 1080) << std::endl;\n\n delete cp;\n \n return 0;\n \n}<|endoftext|>"} {"text":"<commit_before>#include \"explorerpage.h\"\n#include \"ui_explorerpage.h\"\n\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include <QAbstractItemDelegate>\n#include <QPainter>\n\n#define DECORATION_SIZE 64\n\nclass ExplorerViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n ExplorerViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n icon.paint(painter, decorationRect);\n\n QColor foreground = option.palette.color(QPalette::Text);\n painter->setPen(foreground);\n painter->setPen(foreground);\n painter->setPen(option.palette.color(QPalette::Text));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"explorerpage.moc\"\n\nExplorerPage::ExplorerPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::ExplorerPage),\n clientModel(0),\n walletModel(0),\n explorerdelegate(new ExplorerViewDelegate())\n{\n ui->setupUi(this); \n nam = new QNetworkAccessManager(this);\n connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));\n connect(ui->submitButton,SIGNAL(clicked()),this,SLOT(DoHttpGet()));\n}\n\nExplorerPage::~ExplorerPage()\n{\n delete ui;\n}\n\nvoid ExplorerPage::setClientModel(ClientModel *model)\n{\n this->clientModel = model;\n if(model)\n {\n }\n}\n\nvoid ExplorerPage::setWalletModel(WalletModel *model)\n{\n this->walletModel = model;\n}\n\nvoid ExplorerPage::finished(QNetworkReply *reply) {\n if(reply->error() == QNetworkReply::NoError) {\n ui->textBrowser->setText(reply->readAll());\n } else {\n ui->textBrowser->setText(reply->errorString());\n }\n}\n\nvoid ExplorerPage::DoHttpGet() {\n QString urltn = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/txn.php?\";\n QString urlti = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/txi.php?\";\n QString urla = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/addr.php?\";\n QString urlb = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/block.php?\";\n QString urle = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/error.php\";\n QString data = ui->dataLine->text();\n QString final;\n int size = data.size();\n if(size == 64){\n final = urltxn + data;\n } else if(size == 68){\n final = urltxi + data;\n } else if(size == 34){\n final = urla + data;\n } else if(size >= 7){\n final = urlb + data;\n }else {\n final = urle;\n }\n QNetworkRequest req;\n QByteArray postData;\n postData.append(data.toLocal8Bit());\n req.setUrl(QUrl(final));\n req.setRawHeader(\"User-Agent\", \"CanadaeCoin QT v1.0.0.1\");\n nam->get(req);\n}\n<commit_msg>fine tuning of UI<commit_after>#include \"explorerpage.h\"\n#include \"ui_explorerpage.h\"\n\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include <QAbstractItemDelegate>\n#include <QPainter>\n\n#define DECORATION_SIZE 64\n\nclass ExplorerViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n ExplorerViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n icon.paint(painter, decorationRect);\n\n QColor foreground = option.palette.color(QPalette::Text);\n painter->setPen(foreground);\n painter->setPen(foreground);\n painter->setPen(option.palette.color(QPalette::Text));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"explorerpage.moc\"\n\nExplorerPage::ExplorerPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::ExplorerPage),\n clientModel(0),\n walletModel(0),\n explorerdelegate(new ExplorerViewDelegate())\n{\n ui->setupUi(this); \n nam = new QNetworkAccessManager(this);\n connect(nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(finished(QNetworkReply*)));\n connect(ui->submitButton,SIGNAL(clicked()),this,SLOT(DoHttpGet()));\n}\n\nExplorerPage::~ExplorerPage()\n{\n delete ui;\n}\n\nvoid ExplorerPage::setClientModel(ClientModel *model)\n{\n this->clientModel = model;\n if(model)\n {\n }\n}\n\nvoid ExplorerPage::setWalletModel(WalletModel *model)\n{\n this->walletModel = model;\n}\n\nvoid ExplorerPage::finished(QNetworkReply *reply) {\n if(reply->error() == QNetworkReply::NoError) {\n ui->textBrowser->setText(reply->readAll());\n } else {\n ui->textBrowser->setText(reply->errorString());\n }\n}\n\nvoid ExplorerPage::DoHttpGet() {\n QString urltxn = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/txn.php?\";\n QString urltxi = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/txi.php?\";\n QString urla = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/addr.php?\";\n QString urlb = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/block.php?\";\n QString urle = \"http:\/\/qt.canadaecoin.net\/v1.0.0.1\/error.php\";\n QString data = ui->dataLine->text();\n QString final;\n int size = data.size();\n if(size == 64){\n final = urltxn + data;\n } else if(size == 68){\n final = urltxi + data;\n } else if(size == 34){\n final = urla + data;\n } else if(size >= 7){\n final = urlb + data;\n }else {\n final = urle;\n }\n QNetworkRequest req;\n QByteArray postData;\n postData.append(data.toLocal8Bit());\n req.setUrl(QUrl(final));\n req.setRawHeader(\"User-Agent\", \"CanadaeCoin QT v1.0.0.1\");\n nam->get(req);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"optionsmodel.h\"\n#include \"bitcoinunits.h\"\n#include <QSettings>\n\n#include \"init.h\"\n#include \"walletdb.h\"\n\nOptionsModel::OptionsModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n Init();\n}\n\nvoid OptionsModel::Init()\n{\n QSettings settings;\n\n \/\/ These are QT-only settings:\n nDisplayUnit = settings.value(\"nDisplayUnit\", BitcoinUnits::BTC).toInt();\n bDisplayAddresses = settings.value(\"bDisplayAddresses\", false).toBool();\n fMinimizeToTray = settings.value(\"fMinimizeToTray\", false).toBool();\n fMinimizeOnClose = settings.value(\"fMinimizeOnClose\", false).toBool();\n nTransactionFee = settings.value(\"nTransactionFee\").toLongLong();\n\n \/\/ These are shared with core bitcoin; we want\n \/\/ command-line options to override the GUI settings:\n if (settings.contains(\"fUseUPnP\"))\n SoftSetBoolArg(\"-upnp\", settings.value(\"fUseUPnP\").toBool());\n if (settings.contains(\"addrProxy\") && settings.value(\"fUseProxy\").toBool())\n SoftSetArg(\"-proxy\", settings.value(\"addrProxy\").toString().toStdString());\n}\n\nbool OptionsModel::Upgrade()\n{\n QSettings settings;\n\n if (settings.contains(\"bImportFinished\"))\n return false; \/\/ Already upgraded\n\n settings.setValue(\"bImportFinished\", true);\n\n \/\/ Move settings from old wallet.dat (if any):\n CWalletDB walletdb(\"wallet.dat\");\n\n QList<QString> intOptions;\n intOptions << \"nDisplayUnit\" << \"nTransactionFee\";\n foreach(QString key, intOptions)\n {\n int value = 0;\n if (walletdb.ReadSetting(key.toStdString(), value))\n {\n settings.setValue(key, value);\n walletdb.EraseSetting(key.toStdString());\n }\n }\n QList<QString> boolOptions;\n boolOptions << \"bDisplayAddresses\" << \"fMinimizeToTray\" << \"fMinimizeOnClose\" << \"fUseProxy\" << \"fUseUPnP\";\n foreach(QString key, boolOptions)\n {\n bool value = false;\n if (walletdb.ReadSetting(key.toStdString(), value))\n {\n settings.setValue(key, value);\n walletdb.EraseSetting(key.toStdString());\n }\n }\n try\n {\n CAddress addrProxyAddress;\n if (walletdb.ReadSetting(\"addrProxy\", addrProxyAddress))\n {\n addrProxy = addrProxyAddress;\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n walletdb.EraseSetting(\"addrProxy\");\n }\n }\n catch (std::ios_base::failure &e)\n {\n \/\/ 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress\n if (walletdb.ReadSetting(\"addrProxy\", addrProxy))\n {\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n walletdb.EraseSetting(\"addrProxy\");\n }\n }\n Init();\n\n return true;\n}\n\n\nint OptionsModel::rowCount(const QModelIndex & parent) const\n{\n return OptionIDRowCount;\n}\n\nQVariant OptionsModel::data(const QModelIndex & index, int role) const\n{\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n return QVariant(GetStartOnSystemStartup());\n case MinimizeToTray:\n return QVariant(fMinimizeToTray);\n case MapPortUPnP:\n return settings.value(\"fUseUPnP\", GetBoolArg(\"-upnp\", true));\n case MinimizeOnClose:\n return QVariant(fMinimizeOnClose);\n case ConnectSOCKS4:\n return settings.value(\"fUseProxy\", false);\n case ProxyIP:\n return QVariant(QString::fromStdString(addrProxy.ToStringIP()));\n case ProxyPort:\n return QVariant(addrProxy.GetPort());\n case Fee:\n return QVariant(nTransactionFee);\n case DisplayUnit:\n return QVariant(nDisplayUnit);\n case DisplayAddresses:\n return QVariant(bDisplayAddresses);\n default:\n return QVariant();\n }\n }\n return QVariant();\n}\n\nbool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)\n{\n bool successful = true; \/* set to false on parse error *\/\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n successful = SetStartOnSystemStartup(value.toBool());\n break;\n case MinimizeToTray:\n fMinimizeToTray = value.toBool();\n settings.setValue(\"fMinimizeToTray\", fMinimizeToTray);\n break;\n case MapPortUPnP:\n {\n bool bUseUPnP = value.toBool();\n settings.setValue(\"fUseUPnP\", bUseUPnP);\n MapPort(bUseUPnP);\n }\n break;\n case MinimizeOnClose:\n fMinimizeOnClose = value.toBool();\n settings.setValue(\"fMinimizeOnClose\", fMinimizeOnClose);\n break;\n case ConnectSOCKS4:\n fUseProxy = value.toBool();\n settings.setValue(\"fUseProxy\", fUseProxy);\n break;\n case ProxyIP:\n {\n \/\/ Use CAddress to parse and check IP\n CNetAddr addr(value.toString().toStdString());\n if (addr.IsValid())\n {\n addrProxy.SetIP(addr);\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n }\n else\n {\n successful = false;\n }\n }\n break;\n case ProxyPort:\n {\n int nPort = atoi(value.toString().toAscii().data());\n if (nPort > 0 && nPort < std::numeric_limits<unsigned short>::max())\n {\n addrProxy.SetPort(nPort);\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n }\n else\n {\n successful = false;\n }\n }\n break;\n case Fee: {\n nTransactionFee = value.toLongLong();\n settings.setValue(\"nTransactionFee\", nTransactionFee);\n }\n break;\n case DisplayUnit: {\n int unit = value.toInt();\n nDisplayUnit = unit;\n settings.setValue(\"nDisplayUnit\", nDisplayUnit);\n emit displayUnitChanged(unit);\n }\n case DisplayAddresses: {\n bDisplayAddresses = value.toBool();\n settings.setValue(\"bDisplayAddresses\", bDisplayAddresses);\n }\n default:\n break;\n }\n }\n emit dataChanged(index, index);\n\n return successful;\n}\n\nqint64 OptionsModel::getTransactionFee()\n{\n return nTransactionFee;\n}\n\nbool OptionsModel::getMinimizeToTray()\n{\n return fMinimizeToTray;\n}\n\nbool OptionsModel::getMinimizeOnClose()\n{\n return fMinimizeOnClose;\n}\n\nint OptionsModel::getDisplayUnit()\n{\n return nDisplayUnit;\n}\n\nbool OptionsModel::getDisplayAddresses()\n{\n return bDisplayAddresses;\n}\n<commit_msg>Add missing breaks in optionmodel's switch case<commit_after>#include \"optionsmodel.h\"\n#include \"bitcoinunits.h\"\n#include <QSettings>\n\n#include \"init.h\"\n#include \"walletdb.h\"\n\nOptionsModel::OptionsModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n Init();\n}\n\nvoid OptionsModel::Init()\n{\n QSettings settings;\n\n \/\/ These are QT-only settings:\n nDisplayUnit = settings.value(\"nDisplayUnit\", BitcoinUnits::BTC).toInt();\n bDisplayAddresses = settings.value(\"bDisplayAddresses\", false).toBool();\n fMinimizeToTray = settings.value(\"fMinimizeToTray\", false).toBool();\n fMinimizeOnClose = settings.value(\"fMinimizeOnClose\", false).toBool();\n nTransactionFee = settings.value(\"nTransactionFee\").toLongLong();\n\n \/\/ These are shared with core bitcoin; we want\n \/\/ command-line options to override the GUI settings:\n if (settings.contains(\"fUseUPnP\"))\n SoftSetBoolArg(\"-upnp\", settings.value(\"fUseUPnP\").toBool());\n if (settings.contains(\"addrProxy\") && settings.value(\"fUseProxy\").toBool())\n SoftSetArg(\"-proxy\", settings.value(\"addrProxy\").toString().toStdString());\n}\n\nbool OptionsModel::Upgrade()\n{\n QSettings settings;\n\n if (settings.contains(\"bImportFinished\"))\n return false; \/\/ Already upgraded\n\n settings.setValue(\"bImportFinished\", true);\n\n \/\/ Move settings from old wallet.dat (if any):\n CWalletDB walletdb(\"wallet.dat\");\n\n QList<QString> intOptions;\n intOptions << \"nDisplayUnit\" << \"nTransactionFee\";\n foreach(QString key, intOptions)\n {\n int value = 0;\n if (walletdb.ReadSetting(key.toStdString(), value))\n {\n settings.setValue(key, value);\n walletdb.EraseSetting(key.toStdString());\n }\n }\n QList<QString> boolOptions;\n boolOptions << \"bDisplayAddresses\" << \"fMinimizeToTray\" << \"fMinimizeOnClose\" << \"fUseProxy\" << \"fUseUPnP\";\n foreach(QString key, boolOptions)\n {\n bool value = false;\n if (walletdb.ReadSetting(key.toStdString(), value))\n {\n settings.setValue(key, value);\n walletdb.EraseSetting(key.toStdString());\n }\n }\n try\n {\n CAddress addrProxyAddress;\n if (walletdb.ReadSetting(\"addrProxy\", addrProxyAddress))\n {\n addrProxy = addrProxyAddress;\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n walletdb.EraseSetting(\"addrProxy\");\n }\n }\n catch (std::ios_base::failure &e)\n {\n \/\/ 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress\n if (walletdb.ReadSetting(\"addrProxy\", addrProxy))\n {\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n walletdb.EraseSetting(\"addrProxy\");\n }\n }\n Init();\n\n return true;\n}\n\n\nint OptionsModel::rowCount(const QModelIndex & parent) const\n{\n return OptionIDRowCount;\n}\n\nQVariant OptionsModel::data(const QModelIndex & index, int role) const\n{\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n return QVariant(GetStartOnSystemStartup());\n case MinimizeToTray:\n return QVariant(fMinimizeToTray);\n case MapPortUPnP:\n return settings.value(\"fUseUPnP\", GetBoolArg(\"-upnp\", true));\n case MinimizeOnClose:\n return QVariant(fMinimizeOnClose);\n case ConnectSOCKS4:\n return settings.value(\"fUseProxy\", false);\n case ProxyIP:\n return QVariant(QString::fromStdString(addrProxy.ToStringIP()));\n case ProxyPort:\n return QVariant(addrProxy.GetPort());\n case Fee:\n return QVariant(nTransactionFee);\n case DisplayUnit:\n return QVariant(nDisplayUnit);\n case DisplayAddresses:\n return QVariant(bDisplayAddresses);\n default:\n return QVariant();\n }\n }\n return QVariant();\n}\n\nbool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)\n{\n bool successful = true; \/* set to false on parse error *\/\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n successful = SetStartOnSystemStartup(value.toBool());\n break;\n case MinimizeToTray:\n fMinimizeToTray = value.toBool();\n settings.setValue(\"fMinimizeToTray\", fMinimizeToTray);\n break;\n case MapPortUPnP:\n {\n bool bUseUPnP = value.toBool();\n settings.setValue(\"fUseUPnP\", bUseUPnP);\n MapPort(bUseUPnP);\n }\n break;\n case MinimizeOnClose:\n fMinimizeOnClose = value.toBool();\n settings.setValue(\"fMinimizeOnClose\", fMinimizeOnClose);\n break;\n case ConnectSOCKS4:\n fUseProxy = value.toBool();\n settings.setValue(\"fUseProxy\", fUseProxy);\n break;\n case ProxyIP:\n {\n \/\/ Use CAddress to parse and check IP\n CNetAddr addr(value.toString().toStdString());\n if (addr.IsValid())\n {\n addrProxy.SetIP(addr);\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n }\n else\n {\n successful = false;\n }\n }\n break;\n case ProxyPort:\n {\n int nPort = atoi(value.toString().toAscii().data());\n if (nPort > 0 && nPort < std::numeric_limits<unsigned short>::max())\n {\n addrProxy.SetPort(nPort);\n settings.setValue(\"addrProxy\", addrProxy.ToStringIPPort().c_str());\n }\n else\n {\n successful = false;\n }\n }\n break;\n case Fee: {\n nTransactionFee = value.toLongLong();\n settings.setValue(\"nTransactionFee\", nTransactionFee);\n }\n break;\n case DisplayUnit: {\n int unit = value.toInt();\n nDisplayUnit = unit;\n settings.setValue(\"nDisplayUnit\", nDisplayUnit);\n emit displayUnitChanged(unit);\n }\n break;\n case DisplayAddresses: {\n bDisplayAddresses = value.toBool();\n settings.setValue(\"bDisplayAddresses\", bDisplayAddresses);\n }\n break;\n default:\n break;\n }\n }\n emit dataChanged(index, index);\n\n return successful;\n}\n\nqint64 OptionsModel::getTransactionFee()\n{\n return nTransactionFee;\n}\n\nbool OptionsModel::getMinimizeToTray()\n{\n return fMinimizeToTray;\n}\n\nbool OptionsModel::getMinimizeOnClose()\n{\n return fMinimizeOnClose;\n}\n\nint OptionsModel::getDisplayUnit()\n{\n return nDisplayUnit;\n}\n\nbool OptionsModel::getDisplayAddresses()\n{\n return bDisplayAddresses;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Native Client Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"native_client\/src\/trusted\/plugin\/srpc\/video.h\"\n#include \"native_client\/src\/trusted\/plugin\/srpc\/browser_interface.h\"\n\n\/\/ This file provides empty implementation for video functions used in NaCl code\n\/\/ These functions should not be used when running as part of Chrome, but to\n\/\/ avoid multiple changes in many places in the code, we just provide this\n\/\/ dummy implementation.\n\nnamespace plugin {\n\nclass Plugin;\n\nvoid VideoGlobalLock() {\n return;\n}\n\nvoid VideoGlobalUnlock() {\n return;\n}\n\nvoid VideoMap::Redraw() {\n return;\n}\n\nvoid VideoMap::RedrawAsync(void *platform_parm) {\n return;\n}\n\n\/\/ assumes event is already normalized to NaClMultimediaEvent\nint VideoMap::EventQueuePut(union NaClMultimediaEvent *event) {\n return -1;\n}\n\n\/\/ tests event queue to see if it is full\nint VideoMap::EventQueueIsFull() {\n return 1;\n}\n\n\/\/ Gets the last recorded mouse motion (position)\n\/\/ note: outputs normalized for NaCl events\nvoid VideoMap::GetMotion(uint16_t *x, uint16_t *y) {\n return;\n}\n\n\/\/ Sets the mouse motion (position)\n\/\/ note: the inputs must be normalized for NaCl events\nvoid VideoMap::SetMotion(uint16_t x, uint16_t y, int last_valid) {\n return;\n}\n\n\/\/ Gets the relative mouse motion and updates position\n\/\/ note: the inputs must be normalized for NaCl events\nvoid VideoMap::GetRelativeMotion(uint16_t x,\n uint16_t y,\n int16_t *rel_x,\n int16_t *rel_y) {\n return;\n}\n\n\/\/ Gets the current mouse button state\n\/\/ note: output is normalized for NaCl events\nint VideoMap::GetButton() {\n return 0;\n}\n\n\/\/ Modifies the mouse button state\n\/\/ note: input must be normalized for NaCl events\nvoid VideoMap::SetButton(int button, int state) {\n return;\n}\n\n\/\/ Modifies the keyboard modifier state (shift, ctrl, alt, etc)\n\/\/ note: input must be normalized for NaCl events\nvoid VideoMap::SetKeyMod(int nsym, int state) {\n return;\n}\n\n\/\/ Gets the current keyboard modifier state\n\/\/ note: output is normalized for NaCl Events\nint VideoMap::GetKeyMod() {\n return 0;\n}\n\n\/\/ handle video map specific NPAPI SetWindow\nbool VideoMap::SetWindow(PluginWindow *window) {\n \/\/ TODO(gregoryd): do something with this information\n \/\/ or remove this file.\n return true;\n}\n\nint16_t VideoMap::HandleEvent(void *param) {\n return 0;\n}\n\nScriptableHandle* VideoMap::VideoSharedMemorySetup() {\n return NULL;\n}\n\nvoid VideoMap::Invalidate() {\n return;\n}\n\nVideoCallbackData* VideoMap::InitCallbackData(nacl::DescWrapper* desc,\n BrowserInterface *p,\n MultimediaSocket *msp) {\n return NULL;\n}\n\n\/\/ static method\nVideoCallbackData* VideoMap::ReleaseCallbackData(VideoCallbackData* vcd) {\n return NULL;\n}\n\n\/\/ static method\n\/\/ normally, the Release version is preferred, which reference counts.\n\/\/ in some cases we may just need to forcefully delete the callback data,\n\/\/ and ignore the refcount.\nvoid VideoMap::ForceDeleteCallbackData(VideoCallbackData* vcd) {\n return;\n}\n\n\/\/ opens shared memory map into untrusted space\n\/\/ returns 0 success, -1 failure\nint VideoMap::InitializeSharedMemory(PluginWindow *window) {\n return -1;\n}\n\n\/\/ this is the draw method the upcall thread should invoke\nvoid VideoMap::RequestRedraw() {\n return;\n}\n\nVideoMap::VideoMap(BrowserInterface *browser_interface) {\n browser_interface_ = browser_interface;\n}\n\nVideoMap::~VideoMap() {\n}\n\n} \/\/ namespace plugin\n<commit_msg>Once more trying to fix Chrome video build errors.<commit_after>\/\/ Copyright (c) 2008 The Native Client Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"native_client\/src\/trusted\/plugin\/srpc\/video.h\"\n#include \"native_client\/src\/trusted\/plugin\/srpc\/browser_interface.h\"\n\n\/\/ This file provides empty implementation for video functions used in NaCl code\n\/\/ These functions should not be used when running as part of Chrome, but to\n\/\/ avoid multiple changes in many places in the code, we just provide this\n\/\/ dummy implementation.\n\nnamespace plugin {\n\nclass Plugin;\n\nvoid VideoGlobalLock() {\n return;\n}\n\nvoid VideoGlobalUnlock() {\n return;\n}\n\nvoid VideoMap::Redraw() {\n return;\n}\n\nvoid VideoMap::RedrawAsync(void *platform_parm) {\n return;\n}\n\n\/\/ assumes event is already normalized to NaClMultimediaEvent\nint VideoMap::EventQueuePut(union NaClMultimediaEvent *event) {\n return -1;\n}\n\n\/\/ tests event queue to see if it is full\nint VideoMap::EventQueueIsFull() {\n return 1;\n}\n\n\/\/ Gets the last recorded mouse motion (position)\n\/\/ note: outputs normalized for NaCl events\nvoid VideoMap::GetMotion(uint16_t *x, uint16_t *y) {\n return;\n}\n\n\/\/ Sets the mouse motion (position)\n\/\/ note: the inputs must be normalized for NaCl events\nvoid VideoMap::SetMotion(uint16_t x, uint16_t y, int last_valid) {\n return;\n}\n\n\/\/ Gets the relative mouse motion and updates position\n\/\/ note: the inputs must be normalized for NaCl events\nvoid VideoMap::GetRelativeMotion(uint16_t x,\n uint16_t y,\n int16_t *rel_x,\n int16_t *rel_y) {\n return;\n}\n\n\/\/ Gets the current mouse button state\n\/\/ note: output is normalized for NaCl events\nint VideoMap::GetButton() {\n return 0;\n}\n\n\/\/ Modifies the mouse button state\n\/\/ note: input must be normalized for NaCl events\nvoid VideoMap::SetButton(int button, int state) {\n return;\n}\n\n\/\/ Modifies the keyboard modifier state (shift, ctrl, alt, etc)\n\/\/ note: input must be normalized for NaCl events\nvoid VideoMap::SetKeyMod(int nsym, int state) {\n return;\n}\n\n\/\/ Gets the current keyboard modifier state\n\/\/ note: output is normalized for NaCl Events\nint VideoMap::GetKeyMod() {\n return 0;\n}\n\n\/\/ handle video map specific NPAPI SetWindow\nbool VideoMap::SetWindow(PluginWindow *window) {\n \/\/ TODO(gregoryd): do something with this information\n \/\/ or remove this file.\n return true;\n}\n\nint16_t VideoMap::HandleEvent(void *param) {\n return 0;\n}\n\nScriptableHandle* VideoMap::VideoSharedMemorySetup() {\n return NULL;\n}\n\nvoid VideoMap::Invalidate() {\n return;\n}\n\nVideoCallbackData* VideoMap::InitCallbackData(nacl::DescWrapper* desc,\n Plugin *p,\n MultimediaSocket *msp) {\n return NULL;\n}\n\n\/\/ static method\nVideoCallbackData* VideoMap::ReleaseCallbackData(VideoCallbackData* vcd) {\n return NULL;\n}\n\n\/\/ static method\n\/\/ normally, the Release version is preferred, which reference counts.\n\/\/ in some cases we may just need to forcefully delete the callback data,\n\/\/ and ignore the refcount.\nvoid VideoMap::ForceDeleteCallbackData(VideoCallbackData* vcd) {\n return;\n}\n\n\/\/ opens shared memory map into untrusted space\n\/\/ returns 0 success, -1 failure\nint VideoMap::InitializeSharedMemory(PluginWindow *window) {\n return -1;\n}\n\n\/\/ this is the draw method the upcall thread should invoke\nvoid VideoMap::RequestRedraw() {\n return;\n}\n\nVideoMap::VideoMap(Plugin *plugin) {\n}\n\nVideoMap::~VideoMap() {\n}\n\n} \/\/ namespace plugin\n<|endoftext|>"} {"text":"<commit_before>\/*\n===========================================================================\n\ndaemon gpl source code\ncopyright (c) 2013 unvanquished developers\n\nthis file is part of the daemon gpl source code (daemon source code).\n\ndaemon source code is free software: you can redistribute it and\/or modify\nit under the terms of the gnu general public license as published by\nthe free software foundation, either version 3 of the license, or\n(at your option) any later version.\n\ndaemon source code is distributed in the hope that it will be useful,\nbut without any warranty; without even the implied warranty of\nmerchantability or fitness for a particular purpose. see the\ngnu general public license for more details.\n\nyou should have received a copy of the gnu general public license\nalong with daemon source code. if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n===========================================================================\n*\/\n\n#include \"AudioPrivate.h\"\n\nnamespace Audio {\n\n \/\/TODO lazily check for the values\n static Cvar::Range<Cvar::Cvar<float>> effectsVolume(\"audio.volume.effects\", \"the volume of the effects\", Cvar::ARCHIVE, 0.8f, 0.0f, 1.0f);\n static Cvar::Range<Cvar::Cvar<float>> musicVolume(\"audio.volume.music\", \"the volume of the music\", Cvar::ARCHIVE, 0.8f, 0.0f, 1.0f);\n\n \/\/ We have a big, fixed number of source to avoid rendering too many sounds and slowing down the rest of the engine.\n struct sourceRecord_t {\n AL::Source source;\n std::shared_ptr<Sound> usingSound;\n bool active;\n int priority;\n };\n\n static sourceRecord_t* sources = nullptr;\n static const int nSources = 128; \/\/TODO see what's the limit for OpenAL soft\n\n sourceRecord_t* GetSource(int priority);\n\n static bool initialized = false;\n\n void InitSounds() {\n if (initialized) {\n return;\n }\n\n sources = new sourceRecord_t[nSources];\n\n for (int i = 0; i < nSources; i++) {\n sources[i].active = false;\n }\n\n initialized = true;\n }\n\n void ShutdownSounds() {\n if (not initialized) {\n return;\n }\n\n delete[] sources;\n sources = nullptr;\n\n initialized = false;\n }\n\n void UpdateSounds() {\n for (int i = 0; i < nSources; i++) {\n if (sources[i].active) {\n auto sound = sources[i].usingSound;\n\n \/\/ Update and Emitter::UpdateSound can call Sound::Stop\n if (not sound->IsStopped()) {\n sound->Update();\n }\n\n if (not sound->IsStopped()) {\n sound->GetEmitter()->UpdateSound(*sound);\n }\n\n if (sound->IsStopped()) {\n sources[i].active = false;\n sources[i].usingSound = nullptr;\n }\n }\n }\n }\n\n void AddSound(std::shared_ptr<Emitter> emitter, std::shared_ptr<Sound> sound, int priority) {\n sourceRecord_t* source = GetSource(priority);\n\n if (source) {\n \/\/ Make the source forget if it was a \"static\" or a \"streaming\" source.\n source->source.ResetBuffer();\n sound->SetEmitter(emitter);\n sound->AcquireSource(source->source);\n source->usingSound = sound;\n source->priority = priority;\n source->active = true;\n\n sound->FinishSetup();\n sound->Play();\n }\n }\n\n \/\/ Finds a inactive or low-priority source to play a new sound.\n sourceRecord_t* GetSource(int priority) {\n \/\/TODO make a better heuristic? (take into account the distance \/ the volume \/... ?)\n int best = -1;\n int bestPriority = priority;\n\n \/\/ Gets the minimum sound by comparing activity first then priority\n for (int i = 0; i < nSources; i++) {\n sourceRecord_t& source = sources[i];\n\n if (not source.active) {\n return &source;\n }\n\n if (best < 0 && source.priority <= priority) {\n best = i;\n bestPriority = source.priority;\n continue;\n }\n\n if (source.priority < bestPriority) {\n best = i;\n bestPriority = source.priority;\n continue;\n }\n }\n\n if (best >= 0) {\n sourceRecord_t& source = sources[best];\n\n source.source.Stop();\n source.source.RemoveAllQueuedBuffers();\n\n source.usingSound = nullptr;\n return &source;\n } else {\n return nullptr;\n }\n }\n\n \/\/ Implementation of Sound\n\n Sound::Sound(): positionalGain(1.0f), soundGain(1.0f), currentGain(1.0f), playing(false), source(nullptr) {\n }\n\n Sound::~Sound() {\n }\n\n void Sound::Play() {\n source->Play();\n playing = true;\n }\n\n void Sound::Stop() {\n source->Stop();\n playing = false;\n }\n\n bool Sound::IsStopped() {\n return not playing;\n }\n\n void Sound::SetPositionalGain(float gain) {\n positionalGain = gain;\n }\n\n void Sound::SetSoundGain(float gain) {\n soundGain = gain;\n }\n\n float Sound::GetCurrentGain() {\n return currentGain;\n }\n\n void Sound::SetEmitter(std::shared_ptr<Emitter> emitter) {\n this->emitter = emitter;\n }\n\n std::shared_ptr<Emitter> Sound::GetEmitter() {\n return emitter;\n }\n\n void Sound::AcquireSource(AL::Source& source) {\n this->source = &source;\n\n source.SetLooping(false);\n\n SetupSource(source);\n emitter->SetupSound(*this);\n }\n\n AL::Source& Sound::GetSource() {\n return *source;\n }\n\n \/\/ Set the gain before the source is started to avoid having a few milliseconds of very lound sound\n void Sound::FinishSetup() {\n currentGain = positionalGain * soundGain * effectsVolume.Get();\n source->SetGain(currentGain);\n }\n\n void Sound::Update() {\n \/\/ Fade the Gain update to avoid \"ticking\" sounds when there is a gain discontinuity\n float targetGain = positionalGain * soundGain * effectsVolume.Get();\n\n \/\/TODO make it framerate independant and fade out in about 1\/8 seconds ?\n if (currentGain > targetGain) {\n currentGain = std::max(currentGain - 0.02f, targetGain);\n \/\/currentGain = std::max(currentGain * 1.05f, targetGain);\n } else if (currentGain < targetGain) {\n currentGain = std::min(currentGain + 0.02f, targetGain);\n \/\/currentGain = std::min(currentGain \/ 1.05f - 0.01f, targetGain);\n }\n\n source->SetGain(currentGain);\n\n InternalUpdate();\n }\n \/\/ Implementation of OneShotSound\n\n OneShotSound::OneShotSound(Sample* sample): sample(sample) {\n }\n\n OneShotSound::~OneShotSound() {\n }\n\n void OneShotSound::SetupSource(AL::Source& source) {\n source.SetBuffer(sample->GetBuffer());\n SetSoundGain(effectsVolume.Get());\n }\n\n void OneShotSound::InternalUpdate() {\n if (GetSource().IsStopped()) {\n Stop();\n return;\n }\n SetSoundGain(effectsVolume.Get());\n }\n\n \/\/ Implementation of LoopingSound\n\n LoopingSound::LoopingSound(Sample* sample): sample(sample), fadingOut(false) {\n }\n\n LoopingSound::~LoopingSound() {\n }\n\n void LoopingSound::FadeOutAndDie() {\n fadingOut = true;\n SetSoundGain(0.0f);\n }\n\n void LoopingSound::SetupSource(AL::Source& source) {\n source.SetLooping(true);\n source.SetBuffer(sample->GetBuffer());\n SetSoundGain(effectsVolume.Get());\n }\n\n void LoopingSound::InternalUpdate() {\n if (fadingOut and GetCurrentGain() == 0.0f) {\n Stop();\n }\n\n if (not fadingOut) {\n SetSoundGain(effectsVolume.Get());\n }\n }\n\n \/\/ Implementation of MusicSound\n\n MusicSound::MusicSound(Str::StringRef leadingStreamName, Str::StringRef loopStreamName)\n : leadingStream(S_CodecOpenStream(leadingStreamName.c_str())),\n loopStreamName(loopStreamName), loopStream(nullptr), playingLeadingSound(true){\n }\n\n MusicSound::~MusicSound() {\n if (leadingStream) {\n S_CodecCloseStream(leadingStream);\n }\n if (loopStream) {\n S_CodecCloseStream(loopStream);\n }\n }\n\n void MusicSound::SetupSource(AL::Source& source) {\n for (int i = 0; i < NUM_BUFFERS; i++) {\n AppendBuffer(source, std::move(AL::Buffer()));\n }\n SetSoundGain(musicVolume.Get());\n }\n\n void MusicSound::InternalUpdate() {\n AL::Source& source = GetSource();\n\n \/\/ Fill processed buffers and queue them back in the source\n while (source.GetNumProcessedBuffers() > 0) {\n AppendBuffer(source, std::move(source.PopBuffer()));\n }\n\n \/\/ If we don't have any more buffers queued it means we have to stop the music\n if (source.GetNumQueuedBuffers() == 0) {\n Stop();\n\n \/\/ If the source stopped because of a lack of buffer but we still have data to play we start the source again\n } else if (source.IsStopped()) {\n Play();\n }\n\n SetSoundGain(musicVolume.Get());\n }\n\n void MusicSound::AppendBuffer(AL::Source& source, AL::Buffer buffer) {\n snd_stream_t* streamToRead;\n if (playingLeadingSound and leadingStream) {\n streamToRead = leadingStream;\n } else if (loopStream) {\n streamToRead = loopStream;\n } else {\n return;\n }\n\n static char tempBuffer[CHUNK_SIZE];\n int lengthRead = S_CodecReadStream(streamToRead, CHUNK_SIZE, tempBuffer);\n\n \/\/ if a stream is finished, we start playing the loop again, if possible\n if (lengthRead == 0) {\n S_CodecCloseStream(streamToRead);\n playingLeadingSound = false;\n \/\/ either the stream was the leadin stream and we null it\n leadingStream = nullptr;\n \/\/ either it is the loop stream and we overwrite it\n loopStream = S_CodecOpenStream(loopStreamName.c_str());\n AppendBuffer(source, std::move(buffer));\n return;\n }\n\n snd_info_t streamInfo = streamToRead->info;\n streamInfo.size = lengthRead; \/\/ this isn't set by Codec\n buffer.Feed(streamInfo, tempBuffer);\n\n source.QueueBuffer(std::move(buffer));\n }\n\n \/\/ Implementation of StreamingSound\n\n StreamingSound::StreamingSound() {\n }\n\n StreamingSound::~StreamingSound() {\n }\n\n void StreamingSound::SetupSource(AL::Source&) {\n }\n\n void StreamingSound::InternalUpdate() {\n AL::Source& source = GetSource();\n\n while (source.GetNumProcessedBuffers() > 0) {\n source.PopBuffer();\n }\n\n if (source.GetNumQueuedBuffers() == 0) {\n Stop();\n }\n }\n\n\t\/\/TODO somehow try to catch back when data is coming faster than we consume (e.g. capture data)\n void StreamingSound::AppendBuffer(AL::Buffer buffer) {\n if (IsStopped()) {\n return;\n }\n\n AL::Source& source = GetSource();\n source.QueueBuffer(std::move(buffer));\n\n if (source.IsStopped()) {\n source.Play();\n }\n }\n\n void StreamingSound::SetGain(float gain) {\n SetSoundGain(gain);\n }\n}\n<commit_msg>Audio: fix the music loop not starting if there is no leading sound<commit_after>\/*\n===========================================================================\n\ndaemon gpl source code\ncopyright (c) 2013 unvanquished developers\n\nthis file is part of the daemon gpl source code (daemon source code).\n\ndaemon source code is free software: you can redistribute it and\/or modify\nit under the terms of the gnu general public license as published by\nthe free software foundation, either version 3 of the license, or\n(at your option) any later version.\n\ndaemon source code is distributed in the hope that it will be useful,\nbut without any warranty; without even the implied warranty of\nmerchantability or fitness for a particular purpose. see the\ngnu general public license for more details.\n\nyou should have received a copy of the gnu general public license\nalong with daemon source code. if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n===========================================================================\n*\/\n\n#include \"AudioPrivate.h\"\n\nnamespace Audio {\n\n \/\/TODO lazily check for the values\n static Cvar::Range<Cvar::Cvar<float>> effectsVolume(\"audio.volume.effects\", \"the volume of the effects\", Cvar::ARCHIVE, 0.8f, 0.0f, 1.0f);\n static Cvar::Range<Cvar::Cvar<float>> musicVolume(\"audio.volume.music\", \"the volume of the music\", Cvar::ARCHIVE, 0.8f, 0.0f, 1.0f);\n\n \/\/ We have a big, fixed number of source to avoid rendering too many sounds and slowing down the rest of the engine.\n struct sourceRecord_t {\n AL::Source source;\n std::shared_ptr<Sound> usingSound;\n bool active;\n int priority;\n };\n\n static sourceRecord_t* sources = nullptr;\n static const int nSources = 128; \/\/TODO see what's the limit for OpenAL soft\n\n sourceRecord_t* GetSource(int priority);\n\n static bool initialized = false;\n\n void InitSounds() {\n if (initialized) {\n return;\n }\n\n sources = new sourceRecord_t[nSources];\n\n for (int i = 0; i < nSources; i++) {\n sources[i].active = false;\n }\n\n initialized = true;\n }\n\n void ShutdownSounds() {\n if (not initialized) {\n return;\n }\n\n delete[] sources;\n sources = nullptr;\n\n initialized = false;\n }\n\n void UpdateSounds() {\n for (int i = 0; i < nSources; i++) {\n if (sources[i].active) {\n auto sound = sources[i].usingSound;\n\n \/\/ Update and Emitter::UpdateSound can call Sound::Stop\n if (not sound->IsStopped()) {\n sound->Update();\n }\n\n if (not sound->IsStopped()) {\n sound->GetEmitter()->UpdateSound(*sound);\n }\n\n if (sound->IsStopped()) {\n sources[i].active = false;\n sources[i].usingSound = nullptr;\n }\n }\n }\n }\n\n void AddSound(std::shared_ptr<Emitter> emitter, std::shared_ptr<Sound> sound, int priority) {\n sourceRecord_t* source = GetSource(priority);\n\n if (source) {\n \/\/ Make the source forget if it was a \"static\" or a \"streaming\" source.\n source->source.ResetBuffer();\n sound->SetEmitter(emitter);\n sound->AcquireSource(source->source);\n source->usingSound = sound;\n source->priority = priority;\n source->active = true;\n\n sound->FinishSetup();\n sound->Play();\n }\n }\n\n \/\/ Finds a inactive or low-priority source to play a new sound.\n sourceRecord_t* GetSource(int priority) {\n \/\/TODO make a better heuristic? (take into account the distance \/ the volume \/... ?)\n int best = -1;\n int bestPriority = priority;\n\n \/\/ Gets the minimum sound by comparing activity first then priority\n for (int i = 0; i < nSources; i++) {\n sourceRecord_t& source = sources[i];\n\n if (not source.active) {\n return &source;\n }\n\n if (best < 0 && source.priority <= priority) {\n best = i;\n bestPriority = source.priority;\n continue;\n }\n\n if (source.priority < bestPriority) {\n best = i;\n bestPriority = source.priority;\n continue;\n }\n }\n\n if (best >= 0) {\n sourceRecord_t& source = sources[best];\n\n source.source.Stop();\n source.source.RemoveAllQueuedBuffers();\n\n source.usingSound = nullptr;\n return &source;\n } else {\n return nullptr;\n }\n }\n\n \/\/ Implementation of Sound\n\n Sound::Sound(): positionalGain(1.0f), soundGain(1.0f), currentGain(1.0f), playing(false), source(nullptr) {\n }\n\n Sound::~Sound() {\n }\n\n void Sound::Play() {\n source->Play();\n playing = true;\n }\n\n void Sound::Stop() {\n source->Stop();\n playing = false;\n }\n\n bool Sound::IsStopped() {\n return not playing;\n }\n\n void Sound::SetPositionalGain(float gain) {\n positionalGain = gain;\n }\n\n void Sound::SetSoundGain(float gain) {\n soundGain = gain;\n }\n\n float Sound::GetCurrentGain() {\n return currentGain;\n }\n\n void Sound::SetEmitter(std::shared_ptr<Emitter> emitter) {\n this->emitter = emitter;\n }\n\n std::shared_ptr<Emitter> Sound::GetEmitter() {\n return emitter;\n }\n\n void Sound::AcquireSource(AL::Source& source) {\n this->source = &source;\n\n source.SetLooping(false);\n\n SetupSource(source);\n emitter->SetupSound(*this);\n }\n\n AL::Source& Sound::GetSource() {\n return *source;\n }\n\n \/\/ Set the gain before the source is started to avoid having a few milliseconds of very lound sound\n void Sound::FinishSetup() {\n currentGain = positionalGain * soundGain * effectsVolume.Get();\n source->SetGain(currentGain);\n }\n\n void Sound::Update() {\n \/\/ Fade the Gain update to avoid \"ticking\" sounds when there is a gain discontinuity\n float targetGain = positionalGain * soundGain * effectsVolume.Get();\n\n \/\/TODO make it framerate independant and fade out in about 1\/8 seconds ?\n if (currentGain > targetGain) {\n currentGain = std::max(currentGain - 0.02f, targetGain);\n \/\/currentGain = std::max(currentGain * 1.05f, targetGain);\n } else if (currentGain < targetGain) {\n currentGain = std::min(currentGain + 0.02f, targetGain);\n \/\/currentGain = std::min(currentGain \/ 1.05f - 0.01f, targetGain);\n }\n\n source->SetGain(currentGain);\n\n InternalUpdate();\n }\n \/\/ Implementation of OneShotSound\n\n OneShotSound::OneShotSound(Sample* sample): sample(sample) {\n }\n\n OneShotSound::~OneShotSound() {\n }\n\n void OneShotSound::SetupSource(AL::Source& source) {\n source.SetBuffer(sample->GetBuffer());\n SetSoundGain(effectsVolume.Get());\n }\n\n void OneShotSound::InternalUpdate() {\n if (GetSource().IsStopped()) {\n Stop();\n return;\n }\n SetSoundGain(effectsVolume.Get());\n }\n\n \/\/ Implementation of LoopingSound\n\n LoopingSound::LoopingSound(Sample* sample): sample(sample), fadingOut(false) {\n }\n\n LoopingSound::~LoopingSound() {\n }\n\n void LoopingSound::FadeOutAndDie() {\n fadingOut = true;\n SetSoundGain(0.0f);\n }\n\n void LoopingSound::SetupSource(AL::Source& source) {\n source.SetLooping(true);\n source.SetBuffer(sample->GetBuffer());\n SetSoundGain(effectsVolume.Get());\n }\n\n void LoopingSound::InternalUpdate() {\n if (fadingOut and GetCurrentGain() == 0.0f) {\n Stop();\n }\n\n if (not fadingOut) {\n SetSoundGain(effectsVolume.Get());\n }\n }\n\n \/\/ Implementation of MusicSound\n\n MusicSound::MusicSound(Str::StringRef leadingStreamName, Str::StringRef loopStreamName)\n : leadingStream(nullptr), loopStreamName(loopStreamName), loopStream(nullptr), playingLeadingSound(true) {\n\n \/\/Try to open the leading sound\n if (leadingStreamName != \"\") {\n leadingStream = S_CodecOpenStream(leadingStreamName.c_str());\n }\n\n \/\/Start the loop if it failed\n if (not leadingStream) {\n playingLeadingSound = false;\n if (loopStreamName != \"\") {\n loopStream = S_CodecOpenStream(loopStreamName.c_str());\n }\n }\n }\n\n MusicSound::~MusicSound() {\n if (leadingStream) {\n S_CodecCloseStream(leadingStream);\n }\n if (loopStream) {\n S_CodecCloseStream(loopStream);\n }\n }\n\n void MusicSound::SetupSource(AL::Source& source) {\n for (int i = 0; i < NUM_BUFFERS; i++) {\n AppendBuffer(source, std::move(AL::Buffer()));\n }\n SetSoundGain(musicVolume.Get());\n }\n\n void MusicSound::InternalUpdate() {\n AL::Source& source = GetSource();\n\n \/\/ Fill processed buffers and queue them back in the source\n while (source.GetNumProcessedBuffers() > 0) {\n AppendBuffer(source, std::move(source.PopBuffer()));\n }\n\n \/\/ If we don't have any more buffers queued it means we have to stop the music\n if (source.GetNumQueuedBuffers() == 0) {\n Stop();\n\n \/\/ If the source stopped because of a lack of buffer but we still have data to play we start the source again\n } else if (source.IsStopped()) {\n Play();\n }\n\n SetSoundGain(musicVolume.Get());\n }\n\n void MusicSound::AppendBuffer(AL::Source& source, AL::Buffer buffer) {\n snd_stream_t* streamToRead;\n if (playingLeadingSound and leadingStream) {\n streamToRead = leadingStream;\n } else if (loopStream) {\n streamToRead = loopStream;\n } else {\n return;\n }\n\n static char tempBuffer[CHUNK_SIZE];\n int lengthRead = S_CodecReadStream(streamToRead, CHUNK_SIZE, tempBuffer);\n\n \/\/ if a stream is finished, we start playing the loop again, if possible\n if (lengthRead == 0) {\n S_CodecCloseStream(streamToRead);\n playingLeadingSound = false;\n \/\/ either the stream was the leadin stream and we null it\n leadingStream = nullptr;\n\n \/\/ either it is the loop stream and we overwrite it\n if (loopStreamName != \"\") {\n loopStream = S_CodecOpenStream(loopStreamName.c_str());\n AppendBuffer(source, std::move(buffer));\n }\n return;\n }\n\n snd_info_t streamInfo = streamToRead->info;\n streamInfo.size = lengthRead; \/\/ this isn't set by Codec\n buffer.Feed(streamInfo, tempBuffer);\n\n source.QueueBuffer(std::move(buffer));\n }\n\n \/\/ Implementation of StreamingSound\n\n StreamingSound::StreamingSound() {\n }\n\n StreamingSound::~StreamingSound() {\n }\n\n void StreamingSound::SetupSource(AL::Source&) {\n }\n\n void StreamingSound::InternalUpdate() {\n AL::Source& source = GetSource();\n\n while (source.GetNumProcessedBuffers() > 0) {\n source.PopBuffer();\n }\n\n if (source.GetNumQueuedBuffers() == 0) {\n Stop();\n }\n }\n\n\t\/\/TODO somehow try to catch back when data is coming faster than we consume (e.g. capture data)\n void StreamingSound::AppendBuffer(AL::Buffer buffer) {\n if (IsStopped()) {\n return;\n }\n\n AL::Source& source = GetSource();\n source.QueueBuffer(std::move(buffer));\n\n if (source.IsStopped()) {\n source.Play();\n }\n }\n\n void StreamingSound::SetGain(float gain) {\n SetSoundGain(gain);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"scene\/Scene.hpp\"\n#include \"scene\/Sky.hpp\"\n#include \"system\/TextUtilities.hpp\"\n#include \"system\/Query.hpp\"\n\n#include <map>\n#include <sstream>\n\nScene::Scene(const std::string & name) {\n\t\/\/ Append the extension if needed.\n\tstd::string fullName = name;\n\tif(!TextUtilities::hasSuffix(name, \".scene\")) {\n\t\tfullName += \".scene\";\n\t}\n\t_name = fullName;\n}\n\nvoid printToken(const KeyValues & tk, const std::string & shift) {\n\tLog::Info() << shift << tk.key << \": \" << std::endl;\n\tif(!tk.values.empty()) {\n\t\tLog::Info() << shift << \"\\t\";\n\t\tfor(const auto & val : tk.values) {\n\t\t\tLog::Info() << val << \" | \";\n\t\t}\n\t\tLog::Info() << std::endl;\n\t}\n\tfor(const auto & subtk : tk.elements) {\n\t\tprintToken(subtk, shift + \"\\t\");\n\t}\n}\n\nbool Scene::init(Storage options) {\n\tif(_loaded) {\n\t\treturn true;\n\t}\n\n\tQuery timer;\n\ttimer.begin();\n\t\n\t\/\/ Define loaders for each keyword.\n\tstd::map<std::string, void (Scene::*)(const KeyValues &, Storage)> loaders = {\n\t\t{\"scene\", &Scene::loadScene}, {\"object\", &Scene::loadObject}, {\"point\", &Scene::loadLight}, {\"directional\", &Scene::loadLight}, {\"spot\", &Scene::loadLight}, {\"camera\", &Scene::loadCamera}, {\"background\", &Scene::loadBackground}, {\"probe\", &Scene::loadProbe}};\n\n\t\/\/ Parse the file.\n\tconst std::string sceneFile\t\t\t = Resources::manager().getString(_name);\n\tif(sceneFile.empty()) {\n\t\treturn false;\n\t}\n\tconst std::vector<KeyValues> allParams = Codable::decode(sceneFile);\n\n\t\/\/ Process each group of keyvalues.\n\tfor(const auto & element : allParams) {\n\t\tconst std::string key = element.key;\n\t\t\/\/ By construction (see above), all keys should have a loader.\n\t\t(this->*loaders[key])(element, options);\n\t}\n\n\t\/\/ Update all objects poses.\n\tfor(auto & object : objects) {\n\t\tconst glm::mat4 newModel = _sceneModel * object.model();\n\t\tobject.set(newModel);\n\t}\n\t\/\/ The scene model matrix has been applied to all objects, we can reset it.\n\t_sceneModel = glm::mat4(1.0f);\n\t\/\/ Update all lights bounding box infos.\n\t_bbox = computeBoundingBox(true);\n\tfor(auto & light : lights) {\n\t\tlight->setScene(_bbox);\n\t}\n\n\t\/\/ Check if the environment has been setup.\n\tif(environment.type() == LightProbe::Type::DEFAULT){\n\t\tKeyValues defaultKv(\"probe\");\n\t\tenvironment.decode(defaultKv, options);\n\t}\n\t_loaded = true;\n\n\t\/\/ Check if the scene is static.\n\tfor(const auto & obj : objects){\n\t\tif(obj.animated()){\n\t\t\t_animated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(const auto & light : lights){\n\t\tif(light->animated()){\n\t\t\t_animated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\ttimer.end();\n\tLog::Info() << Log::Resources << \"Loading took \" << (float(timer.value())\/1000000.0f) << \"ms.\" << std::endl;\n\treturn true;\n}\n\nvoid Scene::loadObject(const KeyValues & params, Storage options) {\n\tobjects.emplace_back();\n\tobjects.back().decode(params, options);\n}\n\nvoid Scene::loadLight(const KeyValues & params, Storage) {\n\tconst auto light = Light::decode(params);\n\tif(light) {\n\t\tlights.push_back(light);\n\t}\n}\n\nvoid Scene::loadCamera(const KeyValues & params, Storage) {\n\t_camera.decode(params);\n}\n\nvoid Scene::loadBackground(const KeyValues & params, Storage options) {\n\tbackground = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh(\"plane\", options), false));\n\n\tfor(const auto & param : params.elements) {\n\t\tif(param.key == \"color\") {\n\t\t\tbackgroundMode = Background::COLOR;\n\t\t\t\/\/ Background is a plane, store the color.\n\t\t\tbackgroundColor = Codable::decodeVec3(param);\n\n\t\t} else if(param.key == \"image\" && !param.elements.empty()) {\n\t\t\tbackgroundMode = Background::IMAGE;\n\t\t\t\/\/ Load image described as sub-element.\n\t\t\tconst auto texInfos = Codable::decodeTexture(param.elements[0]);\n\t\t\tconst Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, options);\n\t\t\tbackground->addTexture(tex);\n\n\t\t} else if(param.key == \"cube\" && !param.elements.empty()) {\n\t\t\tbackgroundMode = Background::SKYBOX;\n\t\t\t\/\/ Object is a textured skybox.\n\t\t\tbackground = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh(\"skybox\", options), false));\n\t\t\tbackground->decode(params, options);\n\t\t\t\/\/ Load cubemap described as subelement.\n\t\t\tconst auto texInfos = Codable::decodeTexture(param.elements[0]);\n\t\t\tconst Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, options);\n\t\t\tbackground->addTexture(tex);\n\n\t\t} else if(param.key == \"sun\") {\n\t\t\t\/\/ In that case the background is a sky object.\n\t\t\tbackgroundMode = Background::ATMOSPHERE;\n\t\t\tbackground\t = std::unique_ptr<Sky>(new Sky(options));\n\t\t\tbackground->decode(params, options);\n\t\t\t\/\/ Load the scattering table.\n\t\t\tconst Texture * tex = Resources::manager().getTexture(\"scattering-precomputed\", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, options);\n\t\t\tbackground->addTexture(tex);\n\t\t}\n\t}\n}\n\nvoid Scene::loadProbe(const KeyValues & params, Storage options) {\n\tenvironment.decode(params, options);\n}\n\nvoid Scene::loadScene(const KeyValues & params, Storage) {\n\t\/\/ Update matrix, there is at most one transformation in the scene object.\n\t_sceneModel = Codable::decodeTransformation(params.elements);\n}\n\nstd::vector<KeyValues> Scene::encode() const {\n\tstd::vector<KeyValues> tokens;\n\t\n\t\/\/ Encode the scene\n\ttokens.emplace_back(\"scene\");\n\tauto & scnNode = tokens.back();\n\tscnNode.elements.push_back(environment.encode());\n\t\n\t\/\/ Encode the scene transformation.\n\tconst auto modelKeys = Codable::encode(_sceneModel);\n\tfor(const auto & key : modelKeys){\n\t\tscnNode.elements.push_back(key);\n\t}\n\t\n\t\/\/ Encode the background.\n\tKeyValues bgNode(\"background\");\n\t\n\tswitch (backgroundMode) {\n\t\tcase Background::COLOR:\n\t\t\tbgNode.elements.emplace_back(\"color\");\n\t\t\tbgNode.elements.back().values = { Codable::encode(backgroundColor) };\n\t\t\tbreak;\n\t\tcase Background::IMAGE:\n\t\t\tbgNode.elements.emplace_back(\"image\");\n\t\t\tbgNode.elements.back().elements = { Codable::encode(background->textures()[0]) };\n\t\t\tbreak;\n\t\tcase Background::SKYBOX:\n\t\t\tbgNode.elements.emplace_back(\"cube\");\n\t\t\tbgNode.elements.back().elements = { Codable::encode(background->textures()[0]) };\n\t\tbreak;\n\t\tcase Background::ATMOSPHERE:\n\t\t\tbgNode = background->encode();\n\t\t\tbgNode.key = \"background\";\n\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\ttokens.push_back(bgNode);\n\t\/\/ Encode the objects\n\tfor(const auto & obj : objects){\n\t\ttokens.push_back(obj.encode());\n\t}\n\t\/\/ Encode the lights\n\tfor(const auto & light : lights){\n\t\ttokens.push_back(light->encode());\n\t}\n\ttokens.push_back(_camera.encode());\n\treturn tokens;\n}\n\nBoundingBox Scene::computeBoundingBox(bool onlyShadowCasters) {\n\tBoundingBox bbox;\n\tif(objects.empty()) {\n\t\treturn bbox;\n\t}\n\n\tfor(Object & obj : objects) {\n\t\tif(onlyShadowCasters && !obj.castsShadow()) {\n\t\t\tcontinue;\n\t\t}\n\t\tbbox.merge(obj.boundingBox());\n\t}\n\tLog::Info() << Log::Resources << \"Scene bounding box:\" << std::endl\n\t\t\t\t<< \"\\t\\tmini: \" << bbox.minis << std::endl\n\t\t\t\t<< \"\\t\\tmaxi: \" << bbox.maxis << \".\" << std::endl;\n\treturn bbox;\n}\n\nvoid Scene::update(double fullTime, double frameTime) {\n\tfor(auto & light : lights) {\n\t\tlight->update(fullTime, frameTime);\n\t}\n\tfor(auto & object : objects) {\n\t\tobject.update(fullTime, frameTime);\n\t}\n\tbackground->update(fullTime, frameTime);\n}\n<commit_msg>Scene: pre-sort objects based on material.<commit_after>#include \"scene\/Scene.hpp\"\n#include \"scene\/Sky.hpp\"\n#include \"system\/TextUtilities.hpp\"\n#include \"system\/Query.hpp\"\n\n#include <map>\n#include <sstream>\n\nScene::Scene(const std::string & name) {\n\t\/\/ Append the extension if needed.\n\tstd::string fullName = name;\n\tif(!TextUtilities::hasSuffix(name, \".scene\")) {\n\t\tfullName += \".scene\";\n\t}\n\t_name = fullName;\n}\n\nvoid printToken(const KeyValues & tk, const std::string & shift) {\n\tLog::Info() << shift << tk.key << \": \" << std::endl;\n\tif(!tk.values.empty()) {\n\t\tLog::Info() << shift << \"\\t\";\n\t\tfor(const auto & val : tk.values) {\n\t\t\tLog::Info() << val << \" | \";\n\t\t}\n\t\tLog::Info() << std::endl;\n\t}\n\tfor(const auto & subtk : tk.elements) {\n\t\tprintToken(subtk, shift + \"\\t\");\n\t}\n}\n\nbool Scene::init(Storage options) {\n\tif(_loaded) {\n\t\treturn true;\n\t}\n\n\tQuery timer;\n\ttimer.begin();\n\t\n\t\/\/ Define loaders for each keyword.\n\tstd::map<std::string, void (Scene::*)(const KeyValues &, Storage)> loaders = {\n\t\t{\"scene\", &Scene::loadScene}, {\"object\", &Scene::loadObject}, {\"point\", &Scene::loadLight}, {\"directional\", &Scene::loadLight}, {\"spot\", &Scene::loadLight}, {\"camera\", &Scene::loadCamera}, {\"background\", &Scene::loadBackground}, {\"probe\", &Scene::loadProbe}};\n\n\t\/\/ Parse the file.\n\tconst std::string sceneFile\t\t\t = Resources::manager().getString(_name);\n\tif(sceneFile.empty()) {\n\t\treturn false;\n\t}\n\tconst std::vector<KeyValues> allParams = Codable::decode(sceneFile);\n\n\t\/\/ Process each group of keyvalues.\n\tfor(const auto & element : allParams) {\n\t\tconst std::string key = element.key;\n\t\t\/\/ By construction (see above), all keys should have a loader.\n\t\t(this->*loaders[key])(element, options);\n\t}\n\n\t\/\/ Update all objects poses.\n\tfor(auto & object : objects) {\n\t\tconst glm::mat4 newModel = _sceneModel * object.model();\n\t\tobject.set(newModel);\n\t}\n\t\/\/ The scene model matrix has been applied to all objects, we can reset it.\n\t_sceneModel = glm::mat4(1.0f);\n\t\/\/ Update all lights bounding box infos.\n\t_bbox = computeBoundingBox(true);\n\tfor(auto & light : lights) {\n\t\tlight->setScene(_bbox);\n\t}\n\n\t\/\/ Check if the environment has been setup.\n\tif(environment.type() == LightProbe::Type::DEFAULT){\n\t\tKeyValues defaultKv(\"probe\");\n\t\tenvironment.decode(defaultKv, options);\n\t}\n\t_loaded = true;\n\n\t\/\/ Sort objects by material.\n\tstd::sort(objects.begin(), objects.end(), [](const Object & a, const Object & b){\n\t\treturn int(a.type()) < int(b.type());\n\t});\n\n\t\/\/ Check if the scene is static.\n\tfor(const auto & obj : objects){\n\t\tif(obj.animated()){\n\t\t\t_animated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(const auto & light : lights){\n\t\tif(light->animated()){\n\t\t\t_animated = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\ttimer.end();\n\tLog::Info() << Log::Resources << \"Loading took \" << (float(timer.value())\/1000000.0f) << \"ms.\" << std::endl;\n\treturn true;\n}\n\nvoid Scene::loadObject(const KeyValues & params, Storage options) {\n\tobjects.emplace_back();\n\tobjects.back().decode(params, options);\n}\n\nvoid Scene::loadLight(const KeyValues & params, Storage) {\n\tconst auto light = Light::decode(params);\n\tif(light) {\n\t\tlights.push_back(light);\n\t}\n}\n\nvoid Scene::loadCamera(const KeyValues & params, Storage) {\n\t_camera.decode(params);\n}\n\nvoid Scene::loadBackground(const KeyValues & params, Storage options) {\n\tbackground = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh(\"plane\", options), false));\n\n\tfor(const auto & param : params.elements) {\n\t\tif(param.key == \"color\") {\n\t\t\tbackgroundMode = Background::COLOR;\n\t\t\t\/\/ Background is a plane, store the color.\n\t\t\tbackgroundColor = Codable::decodeVec3(param);\n\n\t\t} else if(param.key == \"image\" && !param.elements.empty()) {\n\t\t\tbackgroundMode = Background::IMAGE;\n\t\t\t\/\/ Load image described as sub-element.\n\t\t\tconst auto texInfos = Codable::decodeTexture(param.elements[0]);\n\t\t\tconst Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, options);\n\t\t\tbackground->addTexture(tex);\n\n\t\t} else if(param.key == \"cube\" && !param.elements.empty()) {\n\t\t\tbackgroundMode = Background::SKYBOX;\n\t\t\t\/\/ Object is a textured skybox.\n\t\t\tbackground = std::unique_ptr<Object>(new Object(Object::Type::Common, Resources::manager().getMesh(\"skybox\", options), false));\n\t\t\tbackground->decode(params, options);\n\t\t\t\/\/ Load cubemap described as subelement.\n\t\t\tconst auto texInfos = Codable::decodeTexture(param.elements[0]);\n\t\t\tconst Texture * tex = Resources::manager().getTexture(texInfos.first, texInfos.second, options);\n\t\t\tbackground->addTexture(tex);\n\n\t\t} else if(param.key == \"sun\") {\n\t\t\t\/\/ In that case the background is a sky object.\n\t\t\tbackgroundMode = Background::ATMOSPHERE;\n\t\t\tbackground\t = std::unique_ptr<Sky>(new Sky(options));\n\t\t\tbackground->decode(params, options);\n\t\t\t\/\/ Load the scattering table.\n\t\t\tconst Texture * tex = Resources::manager().getTexture(\"scattering-precomputed\", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, options);\n\t\t\tbackground->addTexture(tex);\n\t\t}\n\t}\n}\n\nvoid Scene::loadProbe(const KeyValues & params, Storage options) {\n\tenvironment.decode(params, options);\n}\n\nvoid Scene::loadScene(const KeyValues & params, Storage) {\n\t\/\/ Update matrix, there is at most one transformation in the scene object.\n\t_sceneModel = Codable::decodeTransformation(params.elements);\n}\n\nstd::vector<KeyValues> Scene::encode() const {\n\tstd::vector<KeyValues> tokens;\n\t\n\t\/\/ Encode the scene\n\ttokens.emplace_back(\"scene\");\n\tauto & scnNode = tokens.back();\n\tscnNode.elements.push_back(environment.encode());\n\t\n\t\/\/ Encode the scene transformation.\n\tconst auto modelKeys = Codable::encode(_sceneModel);\n\tfor(const auto & key : modelKeys){\n\t\tscnNode.elements.push_back(key);\n\t}\n\t\n\t\/\/ Encode the background.\n\tKeyValues bgNode(\"background\");\n\t\n\tswitch (backgroundMode) {\n\t\tcase Background::COLOR:\n\t\t\tbgNode.elements.emplace_back(\"color\");\n\t\t\tbgNode.elements.back().values = { Codable::encode(backgroundColor) };\n\t\t\tbreak;\n\t\tcase Background::IMAGE:\n\t\t\tbgNode.elements.emplace_back(\"image\");\n\t\t\tbgNode.elements.back().elements = { Codable::encode(background->textures()[0]) };\n\t\t\tbreak;\n\t\tcase Background::SKYBOX:\n\t\t\tbgNode.elements.emplace_back(\"cube\");\n\t\t\tbgNode.elements.back().elements = { Codable::encode(background->textures()[0]) };\n\t\tbreak;\n\t\tcase Background::ATMOSPHERE:\n\t\t\tbgNode = background->encode();\n\t\t\tbgNode.key = \"background\";\n\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\ttokens.push_back(bgNode);\n\t\/\/ Encode the objects\n\tfor(const auto & obj : objects){\n\t\ttokens.push_back(obj.encode());\n\t}\n\t\/\/ Encode the lights\n\tfor(const auto & light : lights){\n\t\ttokens.push_back(light->encode());\n\t}\n\ttokens.push_back(_camera.encode());\n\treturn tokens;\n}\n\nBoundingBox Scene::computeBoundingBox(bool onlyShadowCasters) {\n\tBoundingBox bbox;\n\tif(objects.empty()) {\n\t\treturn bbox;\n\t}\n\n\tfor(Object & obj : objects) {\n\t\tif(onlyShadowCasters && !obj.castsShadow()) {\n\t\t\tcontinue;\n\t\t}\n\t\tbbox.merge(obj.boundingBox());\n\t}\n\tLog::Info() << Log::Resources << \"Scene bounding box:\" << std::endl\n\t\t\t\t<< \"\\t\\tmini: \" << bbox.minis << std::endl\n\t\t\t\t<< \"\\t\\tmaxi: \" << bbox.maxis << \".\" << std::endl;\n\treturn bbox;\n}\n\nvoid Scene::update(double fullTime, double frameTime) {\n\tfor(auto & light : lights) {\n\t\tlight->update(fullTime, frameTime);\n\t}\n\tfor(auto & object : objects) {\n\t\tobject.update(fullTime, frameTime);\n\t}\n\tbackground->update(fullTime, frameTime);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ imgui-metal.c\n\/\/ Since this will only need to compile with clang we can\n\/\/ mix C99 designated initializers and C++ code.\n\/\/\n\/\/ NOTE: this demo is using the sokol_imgui.h utility header which\n\/\/ implements a renderer for Dear ImGui on top of sokol_gfx.h, but without\n\/\/ sokol_app.h (via the config define SOKOL_IMGUI_NO_SOKOL_APP).\n\/\/------------------------------------------------------------------------------\n#include \"osxentry.h\"\n#include \"sokol_gfx.h\"\n#include \"sokol_time.h\"\n#include \"imgui.h\"\n#define SOKOL_METAL\n#define SOKOL_IMGUI_IMPL\n#define SOKOL_IMGUI_NO_SOKOL_APP\n#include \"sokol_imgui.h\"\n\nstatic const int WIDTH = 1024;\nstatic const int HEIGHT = 768;\n\nstatic uint64_t last_time = 0;\nstatic bool show_test_window = true;\nstatic bool show_another_window = false;\nstatic sg_pass_action pass_action;\n\nvoid init() {\n \/\/ setup sokol_gfx and sokol_time\n sg_desc desc = {\n .context = osx_get_context()\n };\n sg_setup(&desc);\n stm_setup();\n simgui_desc_t simgui_desc = { };\n simgui_setup(&simgui_desc);\n\n \/\/ setup the imgui environment\n ImGuiIO& io = ImGui::GetIO();\n io.KeyMap[ImGuiKey_Tab] = 0x30;\n io.KeyMap[ImGuiKey_LeftArrow] = 0x7B;\n io.KeyMap[ImGuiKey_RightArrow] = 0x7C;\n io.KeyMap[ImGuiKey_DownArrow] = 0x7D;\n io.KeyMap[ImGuiKey_UpArrow] = 0x7E;\n io.KeyMap[ImGuiKey_Home] = 0x73;\n io.KeyMap[ImGuiKey_End] = 0x77;\n io.KeyMap[ImGuiKey_Delete] = 0x75;\n io.KeyMap[ImGuiKey_Backspace] = 0x33;\n io.KeyMap[ImGuiKey_Enter] = 0x24;\n io.KeyMap[ImGuiKey_Escape] = 0x35;\n io.KeyMap[ImGuiKey_A] = 0x00;\n io.KeyMap[ImGuiKey_C] = 0x08;\n io.KeyMap[ImGuiKey_V] = 0x09;\n io.KeyMap[ImGuiKey_X] = 0x07;\n io.KeyMap[ImGuiKey_Y] = 0x10;\n io.KeyMap[ImGuiKey_Z] = 0x06;\n\n \/\/ OSX => ImGui input forwarding\n osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); });\n osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; });\n osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; });\n osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; });\n osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; });\n osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; });\n osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); });\n\n \/\/ initial clear color\n pass_action = (sg_pass_action){\n .colors[0] = { .action = SG_ACTION_CLEAR, .val = { 0.0f, 0.5f, 0.7f, 1.0f } }\n };\n}\n\nvoid frame() {\n const int width = osx_width();\n const int height = osx_height();\n simgui_new_frame(width, height, stm_laptime(&last_time));\n\n \/\/ 1. Show a simple window\n \/\/ Tip: if we don't call ImGui::Begin()\/ImGui::End() the widgets appears in a window automatically called \"Debug\"\n static float f = 0.0f;\n ImGui::Text(\"Hello, world!\");\n ImGui::SliderFloat(\"float\", &f, 0.0f, 1.0f);\n ImGui::ColorEdit3(\"clear color\", &pass_action.colors[0].val[0]);\n if (ImGui::Button(\"Test Window\")) show_test_window ^= 1;\n if (ImGui::Button(\"Another Window\")) show_another_window ^= 1;\n ImGui::Text(\"Application average %.3f ms\/frame (%.1f FPS)\", 1000.0f \/ ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\n \/\/ 2. Show another simple window, this time using an explicit Begin\/End pair\n if (show_another_window) {\n ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiCond_FirstUseEver);\n ImGui::Begin(\"Another Window\", &show_another_window);\n ImGui::Text(\"Hello\");\n ImGui::End();\n }\n\n \/\/ 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()\n if (show_test_window) {\n ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiCond_FirstUseEver);\n ImGui::ShowTestWindow();\n }\n\n \/\/ the sokol draw pass\n sg_begin_default_pass(&pass_action, width, height);\n simgui_render();\n sg_end_pass();\n sg_commit();\n}\n\nvoid shutdown() {\n simgui_shutdown();\n sg_shutdown();\n}\n\nint main() {\n osx_start(WIDTH, HEIGHT, 1, \"Sokol Dear ImGui (Metal)\", init, frame, shutdown);\n return 0;\n}\n<commit_msg>imgui-metal: fix frametime computation<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ imgui-metal.c\n\/\/ Since this will only need to compile with clang we can\n\/\/ mix C99 designated initializers and C++ code.\n\/\/\n\/\/ NOTE: this demo is using the sokol_imgui.h utility header which\n\/\/ implements a renderer for Dear ImGui on top of sokol_gfx.h, but without\n\/\/ sokol_app.h (via the config define SOKOL_IMGUI_NO_SOKOL_APP).\n\/\/------------------------------------------------------------------------------\n#include \"osxentry.h\"\n#include \"sokol_gfx.h\"\n#include \"sokol_time.h\"\n#include \"imgui.h\"\n#define SOKOL_METAL\n#define SOKOL_IMGUI_IMPL\n#define SOKOL_IMGUI_NO_SOKOL_APP\n#include \"sokol_imgui.h\"\n\nstatic const int WIDTH = 1024;\nstatic const int HEIGHT = 768;\n\nstatic uint64_t last_time = 0;\nstatic bool show_test_window = true;\nstatic bool show_another_window = false;\nstatic sg_pass_action pass_action;\n\nvoid init() {\n \/\/ setup sokol_gfx and sokol_time\n sg_desc desc = {\n .context = osx_get_context()\n };\n sg_setup(&desc);\n stm_setup();\n simgui_desc_t simgui_desc = { };\n simgui_setup(&simgui_desc);\n\n \/\/ setup the imgui environment\n ImGuiIO& io = ImGui::GetIO();\n io.KeyMap[ImGuiKey_Tab] = 0x30;\n io.KeyMap[ImGuiKey_LeftArrow] = 0x7B;\n io.KeyMap[ImGuiKey_RightArrow] = 0x7C;\n io.KeyMap[ImGuiKey_DownArrow] = 0x7D;\n io.KeyMap[ImGuiKey_UpArrow] = 0x7E;\n io.KeyMap[ImGuiKey_Home] = 0x73;\n io.KeyMap[ImGuiKey_End] = 0x77;\n io.KeyMap[ImGuiKey_Delete] = 0x75;\n io.KeyMap[ImGuiKey_Backspace] = 0x33;\n io.KeyMap[ImGuiKey_Enter] = 0x24;\n io.KeyMap[ImGuiKey_Escape] = 0x35;\n io.KeyMap[ImGuiKey_A] = 0x00;\n io.KeyMap[ImGuiKey_C] = 0x08;\n io.KeyMap[ImGuiKey_V] = 0x09;\n io.KeyMap[ImGuiKey_X] = 0x07;\n io.KeyMap[ImGuiKey_Y] = 0x10;\n io.KeyMap[ImGuiKey_Z] = 0x06;\n\n \/\/ OSX => ImGui input forwarding\n osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); });\n osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; });\n osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; });\n osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; });\n osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; });\n osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; });\n osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); });\n\n \/\/ initial clear color\n pass_action = (sg_pass_action){\n .colors[0] = { .action = SG_ACTION_CLEAR, .val = { 0.0f, 0.5f, 0.7f, 1.0f } }\n };\n}\n\nvoid frame() {\n const int width = osx_width();\n const int height = osx_height();\n simgui_new_frame(width, height, stm_sec(stm_laptime(&last_time)));\n\n \/\/ 1. Show a simple window\n \/\/ Tip: if we don't call ImGui::Begin()\/ImGui::End() the widgets appears in a window automatically called \"Debug\"\n static float f = 0.0f;\n ImGui::Text(\"Hello, world!\");\n ImGui::SliderFloat(\"float\", &f, 0.0f, 1.0f);\n ImGui::ColorEdit3(\"clear color\", &pass_action.colors[0].val[0]);\n if (ImGui::Button(\"Test Window\")) show_test_window ^= 1;\n if (ImGui::Button(\"Another Window\")) show_another_window ^= 1;\n ImGui::Text(\"Application average %.3f ms\/frame (%.1f FPS)\", 1000.0f \/ ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\n \/\/ 2. Show another simple window, this time using an explicit Begin\/End pair\n if (show_another_window) {\n ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiCond_FirstUseEver);\n ImGui::Begin(\"Another Window\", &show_another_window);\n ImGui::Text(\"Hello\");\n ImGui::End();\n }\n\n \/\/ 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()\n if (show_test_window) {\n ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiCond_FirstUseEver);\n ImGui::ShowTestWindow();\n }\n\n \/\/ the sokol draw pass\n sg_begin_default_pass(&pass_action, width, height);\n simgui_render();\n sg_end_pass();\n sg_commit();\n}\n\nvoid shutdown() {\n simgui_shutdown();\n sg_shutdown();\n}\n\nint main() {\n osx_start(WIDTH, HEIGHT, 1, \"Sokol Dear ImGui (Metal)\", init, frame, shutdown);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"simplesp.h\"\n#include \"spex\/spcv.h\"\n\nusing namespace sp;\n\nvoid sample(cv::Mat &cvimg, const int key);\n\nint main(){\n cv::VideoCapture cap(0);\n if (cap.isOpened() == false){\n printf(\"could not find USB camera\\n\");\n exit(0);\n }\n\n printf(\"'s' key : switch center pose \/ markers pose\\n\");\n printf(\"'ESC' key : exit\\n\");\n\n int key = 0;\n\n \/\/ 27 = 'ESC' key\n while ((key = cv::waitKey(1)) != 27){\n\n \/\/ capture\n cv::Mat cvimg;\n cap >> cvimg;\n\n sample(cvimg, key);\n\n cv::imshow(\"bitmarker\", cvimg);\n }\n\n cv::destroyAllWindows();\n return 0;\n}\n\nvoid sample(cv::Mat &cvimg, const int key){\n Mem2<Col3> img;\n\n \/\/ convert data type\n cvCnvImg(img, cvimg);\n\n \/\/ markers parameter\n Mem1<BitMarkerParam> mrks;\n\n \/\/ set marker info\n {\n const int dsize[2] = { 4, 3 };\n const int block = 3;\n const double length = 60.0;\n const double interval = 5.0;\n \n \/\/const int dsize[2] = { 8, 6 };\n \/\/const int block = 3;\n \/\/const double length = 28.0;\n \/\/const double interval = 5.0;\n\n mrks = getBitMarkerParam(0, block, length, dsize[0], dsize[1], interval);\n\n SP_ONCE(saveBitMarkerParamSVG(\"mrks.svg\", 0, block, length, dsize[0], dsize[1], interval));\n }\n\n\n \/\/ detector class\n BitMarker bitMarker;\n\n static bool flag = true;\n if (key == 's') flag ^= true;\n\n \/\/ detect marker\n if(flag){\n bitMarker.addMrks(mrks);\n\n bitMarker.execute(img);\n\n if (bitMarker.getPose(0) != NULL) {\n\n const Mem1<Vec2> &cpixs = *bitMarker.getCrspPixs(0);\n renderPoint(img, *bitMarker.getCrspPixs(0), getCol(0, 255, 255), 3);\n\n renderAxis(img, bitMarker.getCam(), *bitMarker.getPose(0), 50.0, 2);\n }\n }\n else {\n for (int i = 0; i < mrks.size(); i++) {\n mrks[i].offset = zeroPose();\n bitMarker.addMrks(mrks[i]);\n }\n\n bitMarker.execute(img);\n\n for (int i = 0; i < mrks.size(); i++) {\n if (bitMarker.getPose(i) == NULL) continue;\n\n const Mem1<Vec2> &cpixs = *bitMarker.getCrspPixs(i);\n renderPoint(img, cpixs, getCol(0, 255, 255), 3);\n\n renderAxis(img, bitMarker.getCam(), *bitMarker.getPose(i), 20.0, 2);\n }\n }\n\n\n cvCnvImg(cvimg, img);\n}\n\n<commit_msg>refactoring<commit_after>#include \"simplesp.h\"\n#include \"spex\/spcv.h\"\n\nusing namespace sp;\n\nvoid sample(cv::Mat &cvimg, const int key);\n\nint main(){\n cv::VideoCapture cap(0);\n if (cap.isOpened() == false){\n printf(\"could not find USB camera\\n\");\n exit(0);\n }\n\n printf(\"'s' key : switch center pose \/ markers pose\\n\");\n printf(\"'ESC' key : exit\\n\");\n\n int key = 0;\n\n \/\/ 27 = 'ESC' key\n while ((key = cv::waitKey(1)) != 27){\n\n \/\/ capture\n cv::Mat cvimg;\n cap >> cvimg;\n\n sample(cvimg, key);\n\n cv::imshow(\"bitmarker\", cvimg);\n }\n\n cv::destroyAllWindows();\n return 0;\n}\n\nvoid sample(cv::Mat &cvimg, const int key){\n Mem2<Col3> img;\n\n \/\/ convert data type\n cvCnvImg(img, cvimg);\n\n \/\/ markers parameter\n Mem1<BitMarkerParam> mrks;\n\n \/\/ set marker info\n {\n const int dsize[2] = { 4, 3 };\n const int block = 3;\n const double length = 60.0;\n const double interval = 5.0;\n \n \/\/const int dsize[2] = { 8, 6 };\n \/\/const int block = 3;\n \/\/const double length = 28.0;\n \/\/const double interval = 5.0;\n\n mrks = getBitMarkerParam(0, block, length, dsize[0], dsize[1], interval);\n\n SP_ONCE(saveBitMarkerParamSVG(\"mrks.svg\", 0, block, length, dsize[0], dsize[1], interval));\n }\n\n\n \/\/ detector class\n BitMarker bitMarker;\n\n static bool flag = true;\n if (key == 's') flag ^= true;\n\n \/\/ detect marker\n if(flag){\n\n bitMarker.addMrks(mrks);\n\n bitMarker.execute(img);\n }\n else {\n for (int i = 0; i < mrks.size(); i++) {\n mrks[i].offset = zeroPose();\n bitMarker.addMrks(mrks[i]);\n }\n\n bitMarker.execute(img);\n }\n\n \/\/ render\n {\n for (int i = 0; i < bitMarker.size(); i++) {\n if (bitMarker.getPose(i) == NULL) continue;\n\n const Mem1<Vec2> &cpixs = *bitMarker.getCrspPixs(i);\n renderPoint(img, cpixs, getCol(0, 255, 255), 3);\n\n renderAxis(img, bitMarker.getCam(), *bitMarker.getPose(i), 30.0, 2);\n }\n }\n\n\n cvCnvImg(cvimg, img);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/feature_type_style.hpp>\n\nnamespace mapnik\n{\n\nstatic const char * filter_mode_strings[] = {\n \"all\",\n \"first\",\n \"\"\n};\n\nIMPLEMENT_ENUM( filter_mode_e, filter_mode_strings )\n\n\nfeature_type_style::feature_type_style()\n : filter_mode_(FILTER_ALL),\n scale_denom_validity_(-1) {}\n\nfeature_type_style::feature_type_style(feature_type_style const& rhs, bool deep_copy)\n : filter_mode_(rhs.filter_mode_),\n scale_denom_valicity_(-1)\n{\n if (!deep_copy) {\n rules_ = rhs.rules_;\n } else {\n rules::const_iterator it = rhs.rules_.begin(),\n end = rhs.rules_.end();\n for(; it != end; ++it) {\n rules_.push_back(rule(*it, deep_copy));\n }\n }\n}\n \nfeature_type_style& feature_type_style::operator=(feature_type_style const& rhs)\n{\n if (this == &rhs) return *this;\n rules_=rhs.rules_;\n scale_denom_validity_ = -1;\n return *this;\n}\n \nvoid feature_type_style::add_rule(rule const& rule)\n{\n rules_.push_back(rule);\n scale_denom_validity_ = -1;\n} \n \nrules const& feature_type_style::get_rules() const\n{\n return rules_;\n}\n\nrules &feature_type_style::get_rules_nonconst()\n{\n return rules_;\n}\n \nvoid feature_type_style::set_filter_mode(filter_mode_e mode)\n{\n filter_mode_ = mode;\n}\n\nfilter_mode_e feature_type_style::get_filter_mode() const\n{\n return filter_mode_;\n}\n\n\nvoid feature_type_style::update_rule_cache(double scale_denom)\n{\n if_rules_.clear();\n else_rules_.clear();\n also_rules_.clear();\n\n BOOST_FOREACH(rule const& r, rules_)\n {\n if (r.active(scale_denom))\n {\n if (r.has_else_filter())\n {\n else_rules_.push_back(const_cast<rule*>(&r));\n }\n else if (r.has_also_filter())\n {\n also_rules_.push_back(const_cast<rule*>(&r));\n }\n else\n {\n if_rules_.push_back(const_cast<rule*>(&r));\n }\n }\n }\n\n scale_denom_validity_ = scale_denom;\n}\n\nrule_ptrs const& feature_type_style::get_if_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return if_rules_;\n}\n\nrule_ptrs const& feature_type_style::get_else_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return else_rules_;\n}\n\nrule_ptrs const& feature_type_style::get_also_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return also_rules_;\n}\n\n}\n<commit_msg>fix typo<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/feature_type_style.hpp>\n\nnamespace mapnik\n{\n\nstatic const char * filter_mode_strings[] = {\n \"all\",\n \"first\",\n \"\"\n};\n\nIMPLEMENT_ENUM( filter_mode_e, filter_mode_strings )\n\n\nfeature_type_style::feature_type_style()\n : filter_mode_(FILTER_ALL),\n scale_denom_validity_(-1) {}\n\nfeature_type_style::feature_type_style(feature_type_style const& rhs, bool deep_copy)\n : filter_mode_(rhs.filter_mode_),\n scale_denom_validity_(-1)\n{\n if (!deep_copy) {\n rules_ = rhs.rules_;\n } else {\n rules::const_iterator it = rhs.rules_.begin(),\n end = rhs.rules_.end();\n for(; it != end; ++it) {\n rules_.push_back(rule(*it, deep_copy));\n }\n }\n}\n \nfeature_type_style& feature_type_style::operator=(feature_type_style const& rhs)\n{\n if (this == &rhs) return *this;\n rules_=rhs.rules_;\n scale_denom_validity_ = -1;\n return *this;\n}\n \nvoid feature_type_style::add_rule(rule const& rule)\n{\n rules_.push_back(rule);\n scale_denom_validity_ = -1;\n} \n \nrules const& feature_type_style::get_rules() const\n{\n return rules_;\n}\n\nrules &feature_type_style::get_rules_nonconst()\n{\n return rules_;\n}\n \nvoid feature_type_style::set_filter_mode(filter_mode_e mode)\n{\n filter_mode_ = mode;\n}\n\nfilter_mode_e feature_type_style::get_filter_mode() const\n{\n return filter_mode_;\n}\n\n\nvoid feature_type_style::update_rule_cache(double scale_denom)\n{\n if_rules_.clear();\n else_rules_.clear();\n also_rules_.clear();\n\n BOOST_FOREACH(rule const& r, rules_)\n {\n if (r.active(scale_denom))\n {\n if (r.has_else_filter())\n {\n else_rules_.push_back(const_cast<rule*>(&r));\n }\n else if (r.has_also_filter())\n {\n also_rules_.push_back(const_cast<rule*>(&r));\n }\n else\n {\n if_rules_.push_back(const_cast<rule*>(&r));\n }\n }\n }\n\n scale_denom_validity_ = scale_denom;\n}\n\nrule_ptrs const& feature_type_style::get_if_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return if_rules_;\n}\n\nrule_ptrs const& feature_type_style::get_else_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return else_rules_;\n}\n\nrule_ptrs const& feature_type_style::get_also_rules(double scale_denom)\n{\n if (scale_denom_validity_ != scale_denom)\n {\n update_rule_cache(scale_denom);\n }\n return also_rules_;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <stdio.h>\n\n#include <cstdlib>\n\n#include \"gtest\/gtest.h\"\n#include \"webrtc\/common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/test\/testsupport\/fileutils.h\"\n#include \"webrtc\/tools\/frame_editing\/frame_editing_lib.h\"\n\nnamespace webrtc {\nnamespace test {\n\nconst int kWidth = 352;\nconst int kHeight = 288;\nconst int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);\nconst std::string kRefVideo = ResourcePath(\"foreman_cif\", \"yuv\");\nconst std::string kTestVideo = OutputPath() + \"testvideo.yuv\";\n\nclass FrameEditingTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n original_fid_ = fopen(kRefVideo.c_str(), \"rb\");\n ASSERT_TRUE(original_fid_ != NULL);\n edited_fid_ = fopen(kTestVideo.c_str(), \"rb\");\n ASSERT_TRUE(edited_fid_ != NULL);\n original_buffer_.reset(new int[kFrameSize]);\n edited_buffer_.reset(new int[kFrameSize]);\n num_frames_read_ = 0;\n }\n virtual void TearDown() {\n fclose(original_fid_);\n fclose(edited_fid_);\n }\n \/\/ Compares the frames in both streams to the end of one of the streams.\n void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,\n scoped_array<int>* ref_buffer,\n scoped_array<int>* test_buffer) {\n while (!feof(test_video_fid) && !feof(ref_video_fid)) {\n num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);\n if (!feof(ref_video_fid)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,\n test_video_fid);\n if (!feof(test_video_fid)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n if (!feof(test_video_fid) && !feof(test_video_fid)) {\n EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),\n kFrameSize));\n }\n }\n \/\/ There should not be anything left in either stream.\n EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));\n }\n FILE* original_fid_;\n FILE* edited_fid_;\n int kFrameSize_;\n int num_bytes_read_;\n scoped_array<int> original_buffer_;\n scoped_array<int> edited_buffer_;\n int num_frames_read_;\n};\n\nTEST_F(FrameEditingTest, ValidInPath) {\n const int kFirstFrameToProcess = 160;\n const int kInterval = -1;\n const int kLastFrameToProcess = 240;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n for (int i = 1; i < kFirstFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n \/\/ Do not compare the frames that have been cut.\n for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,\n &edited_buffer_);\n}\n\nTEST_F(FrameEditingTest, EmptySetToCut) {\n const int kFirstFrameToProcess = 2;\n const int kInterval = -1;\n const int kLastFrameToProcess = 1;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(-10, result);\n}\n\nTEST_F(FrameEditingTest, InValidInPath) {\n const std::string kRefVideo = \"PATH\/THAT\/DOES\/NOT\/EXIST\";\n\n const int kFirstFrameToProcess = 30;\n const int kInterval = 1;\n const int kLastFrameToProcess = 120;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(-11, result);\n}\n\nTEST_F(FrameEditingTest, DeletingEverySecondFrame) {\n const int kFirstFrameToProcess = 1;\n const int kInterval = -2;\n const int kLastFrameToProcess = 10000;\n \/\/ Set kLastFrameToProcess to a large value so that all frame are processed.\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n while (!feof(original_fid_) && !feof(edited_fid_)) {\n num_bytes_read_ =\n fread(original_buffer_.get(), 1, kFrameSize, original_fid_);\n if (!feof(original_fid_)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n num_frames_read_++;\n }\n \/\/ We want to compare every second frame of the original to the edited.\n \/\/ kInterval=-2 and (num_frames_read_ - 1) % kInterval will be -1 for\n \/\/ every second frame.\n \/\/ num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.\n if ((num_frames_read_ - 1) % kInterval == -1) {\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,\n edited_fid_);\n if (!feof(edited_fid_)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n if (!feof(original_fid_) && !feof(edited_fid_)) {\n EXPECT_EQ(0, memcmp(original_buffer_.get(),\n edited_buffer_.get(), kFrameSize));\n }\n }\n }\n}\n\nTEST_F(FrameEditingTest, RepeatFrames) {\n const int kFirstFrameToProcess = 160;\n const int kInterval = 2;\n const int kLastFrameToProcess = 240;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n for (int i = 1; i < kFirstFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n \/\/ Do not compare the frames that have been repeated.\n for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n for (int i = 1; i <= kInterval; ++i) {\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,\n edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n }\n CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,\n &edited_buffer_);\n}\n} \/\/ namespace test\n} \/\/ namespace webrtc\n\n<commit_msg>Fix frame_editing_unittest.cc<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <stdio.h>\n\n#include <cstdlib>\n#include <fstream>\n\n#include \"gtest\/gtest.h\"\n#include \"webrtc\/common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/test\/testsupport\/fileutils.h\"\n#include \"webrtc\/tools\/frame_editing\/frame_editing_lib.h\"\n\nnamespace webrtc {\nnamespace test {\n\nconst int kWidth = 352;\nconst int kHeight = 288;\nconst int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);\nconst std::string kRefVideo = ResourcePath(\"foreman_cif\", \"yuv\");\nconst std::string kTestVideo = OutputPath() + \"testvideo.yuv\";\n\nclass FrameEditingTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n original_fid_ = fopen(kRefVideo.c_str(), \"rb\");\n ASSERT_TRUE(original_fid_ != NULL);\n\n \/\/ Ensure the output file exists on disk.\n std::ofstream(kTestVideo.c_str(), std::ios::out);\n \/\/ Open the output file for reading.\n \/\/ TODO(holmer): Figure out why this file has to be opened here (test fails\n \/\/ if it's opened after the write operation performed in EditFrames).\n edited_fid_ = fopen(kTestVideo.c_str(), \"rb\");\n ASSERT_TRUE(edited_fid_ != NULL);\n\n original_buffer_.reset(new int[kFrameSize]);\n edited_buffer_.reset(new int[kFrameSize]);\n num_frames_read_ = 0;\n }\n virtual void TearDown() {\n fclose(original_fid_);\n fclose(edited_fid_);\n }\n \/\/ Compares the frames in both streams to the end of one of the streams.\n void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,\n scoped_array<int>* ref_buffer,\n scoped_array<int>* test_buffer) {\n while (!feof(test_video_fid) && !feof(ref_video_fid)) {\n num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);\n if (!feof(ref_video_fid)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,\n test_video_fid);\n if (!feof(test_video_fid)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n if (!feof(test_video_fid) && !feof(test_video_fid)) {\n EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),\n kFrameSize));\n }\n }\n \/\/ There should not be anything left in either stream.\n EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));\n }\n FILE* original_fid_;\n FILE* edited_fid_;\n int kFrameSize_;\n int num_bytes_read_;\n scoped_array<int> original_buffer_;\n scoped_array<int> edited_buffer_;\n int num_frames_read_;\n};\n\nTEST_F(FrameEditingTest, ValidInPath) {\n const int kFirstFrameToProcess = 160;\n const int kInterval = -1;\n const int kLastFrameToProcess = 240;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n for (int i = 1; i < kFirstFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n \/\/ Do not compare the frames that have been cut.\n for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,\n &edited_buffer_);\n}\n\nTEST_F(FrameEditingTest, EmptySetToCut) {\n const int kFirstFrameToProcess = 2;\n const int kInterval = -1;\n const int kLastFrameToProcess = 1;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(-10, result);\n}\n\nTEST_F(FrameEditingTest, InValidInPath) {\n const std::string kRefVideo = \"PATH\/THAT\/DOES\/NOT\/EXIST\";\n\n const int kFirstFrameToProcess = 30;\n const int kInterval = 1;\n const int kLastFrameToProcess = 120;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(-11, result);\n}\n\nTEST_F(FrameEditingTest, DeletingEverySecondFrame) {\n const int kFirstFrameToProcess = 1;\n const int kInterval = -2;\n const int kLastFrameToProcess = 10000;\n \/\/ Set kLastFrameToProcess to a large value so that all frame are processed.\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n while (!feof(original_fid_) && !feof(edited_fid_)) {\n num_bytes_read_ =\n fread(original_buffer_.get(), 1, kFrameSize, original_fid_);\n if (!feof(original_fid_)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n num_frames_read_++;\n }\n \/\/ We want to compare every second frame of the original to the edited.\n \/\/ kInterval=-2 and (num_frames_read_ - 1) % kInterval will be -1 for\n \/\/ every second frame.\n \/\/ num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.\n if ((num_frames_read_ - 1) % kInterval == -1) {\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,\n edited_fid_);\n if (!feof(edited_fid_)) {\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n }\n if (!feof(original_fid_) && !feof(edited_fid_)) {\n EXPECT_EQ(0, memcmp(original_buffer_.get(),\n edited_buffer_.get(), kFrameSize));\n }\n }\n }\n}\n\nTEST_F(FrameEditingTest, RepeatFrames) {\n const int kFirstFrameToProcess = 160;\n const int kInterval = 2;\n const int kLastFrameToProcess = 240;\n\n int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,\n kInterval, kLastFrameToProcess, kTestVideo);\n EXPECT_EQ(0, result);\n\n for (int i = 1; i < kFirstFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n \/\/ Do not compare the frames that have been repeated.\n for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {\n num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,\n original_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n for (int i = 1; i <= kInterval; ++i) {\n num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,\n edited_fid_);\n EXPECT_EQ(kFrameSize, num_bytes_read_);\n EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),\n kFrameSize));\n }\n }\n CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,\n &edited_buffer_);\n}\n} \/\/ namespace test\n} \/\/ namespace webrtc\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGradientEffects.h\"\n#include \"gl\/GrGLProgramStage.h\"\n#include \"GrProgramStageFactory.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLRadialGradient : public GrGLProgramStage {\n\npublic:\n\n GrGLRadialGradient(const GrProgramStageFactory& factory,\n const GrCustomStage&) : INHERITED (factory) { }\n virtual ~GrGLRadialGradient() { }\n\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE { }\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) { return 0; }\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nvoid GrGLRadialGradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n state->fSampleCoords.printf(\"vec2(length(%s.xy), 0.5)\",\n state->fSampleCoords.c_str());\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nGrRadialGradient::GrRadialGradient() {\n\n}\n\nGrRadialGradient::~GrRadialGradient() {\n\n}\n\n\nconst GrProgramStageFactory& GrRadialGradient::getFactory() const {\n return GrTProgramStageFactory<GrRadialGradient>::getInstance();\n}\n\nbool GrRadialGradient::isEqual(const GrCustomStage& sBase) const {\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLRadial2Gradient : public GrGLProgramStage {\n\npublic:\n\n GrGLRadial2Gradient(const GrProgramStageFactory& factory,\n const GrCustomStage&);\n virtual ~GrGLRadial2Gradient() { }\n\n virtual void setupVariables(GrGLShaderBuilder* state,\n int stage) SK_OVERRIDE;\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE;\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;\n virtual void setData(const GrGLInterface*,\n const GrGLTexture&,\n const GrCustomStage&,\n int stageNum) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) {\n return (static_cast<const GrRadial2Gradient&>(s).isDegenerate());\n }\n\nprotected:\n\n const GrGLShaderVar* fParamVar;\n GrGLint fParamLocation;\n\n const char* fVSVaryingName;\n const char* fFSVaryingName;\n\n bool fIsDegenerate;\n\n \/\/ @{\n \/\/\/ Values last uploaded as uniforms\n\n GrScalar fCachedCenter;\n GrScalar fCachedRadius;\n bool fCachedPosRoot;\n\n \/\/ @}\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nGrGLRadial2Gradient::GrGLRadial2Gradient(\n const GrProgramStageFactory& factory,\n const GrCustomStage& baseData)\n : INHERITED(factory)\n , fParamVar(NULL)\n , fVSVaryingName(NULL)\n , fFSVaryingName(NULL)\n , fCachedCenter(GR_ScalarMax)\n , fCachedRadius(-GR_ScalarMax)\n , fCachedPosRoot(0) {\n\n const GrRadial2Gradient& data =\n static_cast<const GrRadial2Gradient&>(baseData);\n fIsDegenerate = data.isDegenerate();\n}\n\nvoid GrGLRadial2Gradient::setupVariables(GrGLShaderBuilder* state, int stage) {\n fParamVar = &state->addUniform(\n GrGLShaderBuilder::kBoth_VariableLifetime,\n kFloat_GrSLType, \"uRadial2Params\", stage, 6);\n\n fParamLocation = GrGLProgramStage::kUseUniform;\n\n \/\/ For radial gradients without perspective we can pass the linear\n \/\/ part of the quadratic as a varying.\n if (state->fVaryingDims == state->fCoordDims) {\n state->addVarying(kFloat_GrSLType, \"Radial2BCoeff\", stage,\n &fVSVaryingName, &fFSVaryingName);\n }\n}\n\nvoid GrGLRadial2Gradient::emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) {\n GrStringBuilder* code = &state->fVSCode;\n GrStringBuilder p2;\n GrStringBuilder p3;\n fParamVar->appendArrayAccess(2, &p2);\n fParamVar->appendArrayAccess(3, &p3);\n\n \/\/ For radial gradients without perspective we can pass the linear\n \/\/ part of the quadratic as a varying.\n if (state->fVaryingDims == state->fCoordDims) {\n \/\/ r2Var = 2 * (r2Parm[2] * varCoord.x - r2Param[3])\n code->appendf(\"\\t%s = 2.0 *(%s * %s.x - %s);\\n\",\n fVSVaryingName, p2.c_str(),\n vertexCoords, p3.c_str());\n }\n}\n\nvoid GrGLRadial2Gradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n GrStringBuilder* code = &state->fFSCode;\n GrStringBuilder cName(\"c\");\n GrStringBuilder ac4Name(\"ac4\");\n GrStringBuilder rootName(\"root\");\n GrStringBuilder p0;\n GrStringBuilder p1;\n GrStringBuilder p2;\n GrStringBuilder p3;\n GrStringBuilder p4;\n GrStringBuilder p5;\n fParamVar->appendArrayAccess(0, &p0);\n fParamVar->appendArrayAccess(1, &p1);\n fParamVar->appendArrayAccess(2, &p2);\n fParamVar->appendArrayAccess(3, &p3);\n fParamVar->appendArrayAccess(4, &p4);\n fParamVar->appendArrayAccess(5, &p5);\n\n \/\/ If we we're able to interpolate the linear component,\n \/\/ bVar is the varying; otherwise compute it\n GrStringBuilder bVar;\n if (state->fCoordDims == state->fVaryingDims) {\n bVar = fFSVaryingName;\n GrAssert(2 == state->fVaryingDims);\n } else {\n GrAssert(3 == state->fVaryingDims);\n bVar = \"b\";\n \/\/bVar.appendS32(stageNum);\n code->appendf(\"\\tfloat %s = 2.0 * (%s * %s.x - %s);\\n\",\n bVar.c_str(), p2.c_str(),\n state->fSampleCoords.c_str(), p3.c_str());\n }\n\n \/\/ c = (x^2)+(y^2) - params[4]\n code->appendf(\"\\tfloat %s = dot(%s, %s) - %s;\\n\",\n cName.c_str(), state->fSampleCoords.c_str(),\n state->fSampleCoords.c_str(),\n p4.c_str());\n\n \/\/ If we aren't degenerate, emit some extra code, and accept a slightly\n \/\/ more complex coord.\n if (!fIsDegenerate) {\n\n \/\/ ac4 = 4.0 * params[0] * c\n code->appendf(\"\\tfloat %s = %s * 4.0 * %s;\\n\",\n ac4Name.c_str(), p0.c_str(),\n cName.c_str());\n\n \/\/ root = sqrt(b^2-4ac)\n \/\/ (abs to avoid exception due to fp precision)\n code->appendf(\"\\tfloat %s = sqrt(abs(%s*%s - %s));\\n\",\n rootName.c_str(), bVar.c_str(), bVar.c_str(),\n ac4Name.c_str());\n\n \/\/ x coord is: (-b + params[5] * sqrt(b^2-4ac)) * params[1]\n \/\/ y coord is 0.5 (texture is effectively 1D)\n state->fSampleCoords.printf(\"vec2((-%s + %s * %s) * %s, 0.5)\",\n bVar.c_str(), p5.c_str(),\n rootName.c_str(), p1.c_str());\n } else {\n \/\/ x coord is: -c\/b\n \/\/ y coord is 0.5 (texture is effectively 1D)\n state->fSampleCoords.printf(\"vec2((-%s \/ %s), 0.5)\",\n cName.c_str(), bVar.c_str());\n }\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\nvoid GrGLRadial2Gradient::initUniforms(const GrGLInterface* gl, int programID) {\n GR_GL_CALL_RET(gl, fParamLocation,\n GetUniformLocation(programID, fParamVar->getName().c_str()));\n}\n\nvoid GrGLRadial2Gradient::setData(const GrGLInterface* gl,\n const GrGLTexture& texture,\n const GrCustomStage& baseData,\n int stageNum) {\n const GrRadial2Gradient& data =\n static_cast<const GrRadial2Gradient&>(baseData);\n GrAssert(data.isDegenerate() == fIsDegenerate);\n GrScalar centerX1 = data.center();\n GrScalar radius0 = data.radius();\n if (fCachedCenter != centerX1 ||\n fCachedRadius != radius0 ||\n fCachedPosRoot != data.isPosRoot()) {\n\n GrScalar a = GrMul(centerX1, centerX1) - GR_Scalar1;\n\n \/\/ When we're in the degenerate (linear) case, the second\n \/\/ value will be INF but the program doesn't read it. (We\n \/\/ use the same 6 uniforms even though we don't need them\n \/\/ all in the linear case just to keep the code complexity\n \/\/ down).\n float values[6] = {\n GrScalarToFloat(a),\n 1 \/ (2.f * GrScalarToFloat(a)),\n GrScalarToFloat(centerX1),\n GrScalarToFloat(radius0),\n GrScalarToFloat(GrMul(radius0, radius0)),\n data.isPosRoot() ? 1.f : -1.f\n };\n\n GR_GL_CALL(gl, Uniform1fv(fParamLocation, 6, values));\n fCachedCenter = centerX1;\n fCachedRadius = radius0;\n fCachedPosRoot = data.isPosRoot();\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrRadial2Gradient::GrRadial2Gradient(GrScalar center,\n GrScalar radius,\n bool posRoot)\n : fCenterX1 (center)\n , fRadius0 (radius)\n , fPosRoot (posRoot) {\n\n}\n\nGrRadial2Gradient::~GrRadial2Gradient() {\n\n}\n\n\nconst GrProgramStageFactory& GrRadial2Gradient::getFactory() const {\n return GrTProgramStageFactory<GrRadial2Gradient>::getInstance();\n}\n\nbool GrRadial2Gradient::isEqual(const GrCustomStage& sBase) const {\n const GrRadial2Gradient& s = static_cast<const GrRadial2Gradient&>(sBase);\n return (this->isDegenerate() == s.isDegenerate());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLSweepGradient : public GrGLProgramStage {\n\npublic:\n\n GrGLSweepGradient(const GrProgramStageFactory& factory,\n const GrCustomStage&) : INHERITED (factory) { }\n virtual ~GrGLSweepGradient() { }\n\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE { }\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) { return 0; }\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nvoid GrGLSweepGradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n state->fSampleCoords.printf(\n \"vec2(atan(- %s.y, - %s.x) * 0.1591549430918 + 0.5, 0.5)\",\n state->fSampleCoords.c_str(), state->fSampleCoords.c_str());\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrSweepGradient::GrSweepGradient() {\n\n}\n\nGrSweepGradient::~GrSweepGradient() {\n\n}\n\nconst GrProgramStageFactory& GrSweepGradient::getFactory() const {\n return GrTProgramStageFactory<GrSweepGradient>::getInstance();\n}\n\nbool GrSweepGradient::isEqual(const GrCustomStage& sBase) const {\n return true;\n}\n\n<commit_msg>Split two-point radial gradient parameters into two arrays of uniforms, to avoid sharing arrays between fragment & vertex shaders. Appears to work around driver bug on Xoom.<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGradientEffects.h\"\n#include \"gl\/GrGLProgramStage.h\"\n#include \"GrProgramStageFactory.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLRadialGradient : public GrGLProgramStage {\n\npublic:\n\n GrGLRadialGradient(const GrProgramStageFactory& factory,\n const GrCustomStage&) : INHERITED (factory) { }\n virtual ~GrGLRadialGradient() { }\n\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE { }\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) { return 0; }\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nvoid GrGLRadialGradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n state->fSampleCoords.printf(\"vec2(length(%s.xy), 0.5)\",\n state->fSampleCoords.c_str());\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nGrRadialGradient::GrRadialGradient() {\n\n}\n\nGrRadialGradient::~GrRadialGradient() {\n\n}\n\n\nconst GrProgramStageFactory& GrRadialGradient::getFactory() const {\n return GrTProgramStageFactory<GrRadialGradient>::getInstance();\n}\n\nbool GrRadialGradient::isEqual(const GrCustomStage& sBase) const {\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLRadial2Gradient : public GrGLProgramStage {\n\npublic:\n\n GrGLRadial2Gradient(const GrProgramStageFactory& factory,\n const GrCustomStage&);\n virtual ~GrGLRadial2Gradient() { }\n\n virtual void setupVariables(GrGLShaderBuilder* state,\n int stage) SK_OVERRIDE;\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE;\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;\n virtual void setData(const GrGLInterface*,\n const GrGLTexture&,\n const GrCustomStage&,\n int stageNum) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) {\n return (static_cast<const GrRadial2Gradient&>(s).isDegenerate());\n }\n\nprotected:\n\n const GrGLShaderVar* fVSParamVar;\n GrGLint fVSParamLocation;\n const GrGLShaderVar* fFSParamVar;\n GrGLint fFSParamLocation;\n\n const char* fVSVaryingName;\n const char* fFSVaryingName;\n\n bool fIsDegenerate;\n\n \/\/ @{\n \/\/\/ Values last uploaded as uniforms\n\n GrScalar fCachedCenter;\n GrScalar fCachedRadius;\n bool fCachedPosRoot;\n\n \/\/ @}\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nGrGLRadial2Gradient::GrGLRadial2Gradient(\n const GrProgramStageFactory& factory,\n const GrCustomStage& baseData)\n : INHERITED(factory)\n , fVSParamVar(NULL)\n , fFSParamVar(NULL)\n , fVSVaryingName(NULL)\n , fFSVaryingName(NULL)\n , fCachedCenter(GR_ScalarMax)\n , fCachedRadius(-GR_ScalarMax)\n , fCachedPosRoot(0) {\n\n const GrRadial2Gradient& data =\n static_cast<const GrRadial2Gradient&>(baseData);\n fIsDegenerate = data.isDegenerate();\n}\n\nvoid GrGLRadial2Gradient::setupVariables(GrGLShaderBuilder* state, int stage) {\n \/\/ 2 copies of uniform array, 1 for each of vertex & fragment shader,\n \/\/ to work around Xoom bug. Doesn't seem to cause performance decrease\n \/\/ in test apps, but need to keep an eye on it.\n fVSParamVar = &state->addUniform(\n GrGLShaderBuilder::kVertex_VariableLifetime,\n kFloat_GrSLType, \"uRadial2VSParams\", stage, 6);\n fFSParamVar = &state->addUniform(\n GrGLShaderBuilder::kFragment_VariableLifetime,\n kFloat_GrSLType, \"uRadial2FSParams\", stage, 6);\n\n fVSParamLocation = GrGLProgramStage::kUseUniform;\n fFSParamLocation = GrGLProgramStage::kUseUniform;\n\n \/\/ For radial gradients without perspective we can pass the linear\n \/\/ part of the quadratic as a varying.\n if (state->fVaryingDims == state->fCoordDims) {\n state->addVarying(kFloat_GrSLType, \"Radial2BCoeff\", stage,\n &fVSVaryingName, &fFSVaryingName);\n }\n}\n\nvoid GrGLRadial2Gradient::emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) {\n GrStringBuilder* code = &state->fVSCode;\n GrStringBuilder p2;\n GrStringBuilder p3;\n fVSParamVar->appendArrayAccess(2, &p2);\n fVSParamVar->appendArrayAccess(3, &p3);\n\n \/\/ For radial gradients without perspective we can pass the linear\n \/\/ part of the quadratic as a varying.\n if (state->fVaryingDims == state->fCoordDims) {\n \/\/ r2Var = 2 * (r2Parm[2] * varCoord.x - r2Param[3])\n code->appendf(\"\\t%s = 2.0 *(%s * %s.x - %s);\\n\",\n fVSVaryingName, p2.c_str(),\n vertexCoords, p3.c_str());\n }\n}\n\nvoid GrGLRadial2Gradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n GrStringBuilder* code = &state->fFSCode;\n GrStringBuilder cName(\"c\");\n GrStringBuilder ac4Name(\"ac4\");\n GrStringBuilder rootName(\"root\");\n GrStringBuilder p0;\n GrStringBuilder p1;\n GrStringBuilder p2;\n GrStringBuilder p3;\n GrStringBuilder p4;\n GrStringBuilder p5;\n fFSParamVar->appendArrayAccess(0, &p0);\n fFSParamVar->appendArrayAccess(1, &p1);\n fFSParamVar->appendArrayAccess(2, &p2);\n fFSParamVar->appendArrayAccess(3, &p3);\n fFSParamVar->appendArrayAccess(4, &p4);\n fFSParamVar->appendArrayAccess(5, &p5);\n\n \/\/ If we we're able to interpolate the linear component,\n \/\/ bVar is the varying; otherwise compute it\n GrStringBuilder bVar;\n if (state->fCoordDims == state->fVaryingDims) {\n bVar = fFSVaryingName;\n GrAssert(2 == state->fVaryingDims);\n } else {\n GrAssert(3 == state->fVaryingDims);\n bVar = \"b\";\n \/\/bVar.appendS32(stageNum);\n code->appendf(\"\\tfloat %s = 2.0 * (%s * %s.x - %s);\\n\",\n bVar.c_str(), p2.c_str(),\n state->fSampleCoords.c_str(), p3.c_str());\n }\n\n \/\/ c = (x^2)+(y^2) - params[4]\n code->appendf(\"\\tfloat %s = dot(%s, %s) - %s;\\n\",\n cName.c_str(), state->fSampleCoords.c_str(),\n state->fSampleCoords.c_str(),\n p4.c_str());\n\n \/\/ If we aren't degenerate, emit some extra code, and accept a slightly\n \/\/ more complex coord.\n if (!fIsDegenerate) {\n\n \/\/ ac4 = 4.0 * params[0] * c\n code->appendf(\"\\tfloat %s = %s * 4.0 * %s;\\n\",\n ac4Name.c_str(), p0.c_str(),\n cName.c_str());\n\n \/\/ root = sqrt(b^2-4ac)\n \/\/ (abs to avoid exception due to fp precision)\n code->appendf(\"\\tfloat %s = sqrt(abs(%s*%s - %s));\\n\",\n rootName.c_str(), bVar.c_str(), bVar.c_str(),\n ac4Name.c_str());\n\n \/\/ x coord is: (-b + params[5] * sqrt(b^2-4ac)) * params[1]\n \/\/ y coord is 0.5 (texture is effectively 1D)\n state->fSampleCoords.printf(\"vec2((-%s + %s * %s) * %s, 0.5)\",\n bVar.c_str(), p5.c_str(),\n rootName.c_str(), p1.c_str());\n } else {\n \/\/ x coord is: -c\/b\n \/\/ y coord is 0.5 (texture is effectively 1D)\n state->fSampleCoords.printf(\"vec2((-%s \/ %s), 0.5)\",\n cName.c_str(), bVar.c_str());\n }\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\nvoid GrGLRadial2Gradient::initUniforms(const GrGLInterface* gl, int programID) {\n GR_GL_CALL_RET(gl, fVSParamLocation,\n GetUniformLocation(programID, fVSParamVar->getName().c_str()));\n GR_GL_CALL_RET(gl, fFSParamLocation,\n GetUniformLocation(programID, fFSParamVar->getName().c_str()));\n}\n\nvoid GrGLRadial2Gradient::setData(const GrGLInterface* gl,\n const GrGLTexture& texture,\n const GrCustomStage& baseData,\n int stageNum) {\n const GrRadial2Gradient& data =\n static_cast<const GrRadial2Gradient&>(baseData);\n GrAssert(data.isDegenerate() == fIsDegenerate);\n GrScalar centerX1 = data.center();\n GrScalar radius0 = data.radius();\n if (fCachedCenter != centerX1 ||\n fCachedRadius != radius0 ||\n fCachedPosRoot != data.isPosRoot()) {\n\n GrScalar a = GrMul(centerX1, centerX1) - GR_Scalar1;\n\n \/\/ When we're in the degenerate (linear) case, the second\n \/\/ value will be INF but the program doesn't read it. (We\n \/\/ use the same 6 uniforms even though we don't need them\n \/\/ all in the linear case just to keep the code complexity\n \/\/ down).\n float values[6] = {\n GrScalarToFloat(a),\n 1 \/ (2.f * GrScalarToFloat(a)),\n GrScalarToFloat(centerX1),\n GrScalarToFloat(radius0),\n GrScalarToFloat(GrMul(radius0, radius0)),\n data.isPosRoot() ? 1.f : -1.f\n };\n\n GR_GL_CALL(gl, Uniform1fv(fVSParamLocation, 6, values));\n GR_GL_CALL(gl, Uniform1fv(fFSParamLocation, 6, values));\n fCachedCenter = centerX1;\n fCachedRadius = radius0;\n fCachedPosRoot = data.isPosRoot();\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrRadial2Gradient::GrRadial2Gradient(GrScalar center,\n GrScalar radius,\n bool posRoot)\n : fCenterX1 (center)\n , fRadius0 (radius)\n , fPosRoot (posRoot) {\n\n}\n\nGrRadial2Gradient::~GrRadial2Gradient() {\n\n}\n\n\nconst GrProgramStageFactory& GrRadial2Gradient::getFactory() const {\n return GrTProgramStageFactory<GrRadial2Gradient>::getInstance();\n}\n\nbool GrRadial2Gradient::isEqual(const GrCustomStage& sBase) const {\n const GrRadial2Gradient& s = static_cast<const GrRadial2Gradient&>(sBase);\n return (this->isDegenerate() == s.isDegenerate());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GrGLSweepGradient : public GrGLProgramStage {\n\npublic:\n\n GrGLSweepGradient(const GrProgramStageFactory& factory,\n const GrCustomStage&) : INHERITED (factory) { }\n virtual ~GrGLSweepGradient() { }\n\n virtual void emitVS(GrGLShaderBuilder* state,\n const char* vertexCoords) SK_OVERRIDE { }\n virtual void emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) SK_OVERRIDE;\n\n static StageKey GenKey(const GrCustomStage& s) { return 0; }\n\nprivate:\n\n typedef GrGLProgramStage INHERITED;\n\n};\n\nvoid GrGLSweepGradient::emitFS(GrGLShaderBuilder* state,\n const char* outputColor,\n const char* inputColor,\n const char* samplerName) {\n state->fSampleCoords.printf(\n \"vec2(atan(- %s.y, - %s.x) * 0.1591549430918 + 0.5, 0.5)\",\n state->fSampleCoords.c_str(), state->fSampleCoords.c_str());\n state->fComplexCoord = true;\n\n state->emitDefaultFetch(outputColor, samplerName);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrSweepGradient::GrSweepGradient() {\n\n}\n\nGrSweepGradient::~GrSweepGradient() {\n\n}\n\nconst GrProgramStageFactory& GrSweepGradient::getFactory() const {\n return GrTProgramStageFactory<GrSweepGradient>::getInstance();\n}\n\nbool GrSweepGradient::isEqual(const GrCustomStage& sBase) const {\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifdef LOCAL_OPENCV\n#include <opencv2\/features2d.hpp>\n#include <opencv2\/imgcodecs.hpp>\n#include <opencv2\/opencv.hpp>\n#else\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/features2d\/features2d.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#endif\n\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace cv;\n\n\/\/ http:\/\/stackoverflow.com\/questions\/675039\/how-can-i-create-directory-tree-in-c-linux\n#include <errno.h> \/\/ errno, ENOENT, EEXIST\n#include <sys\/stat.h> \/\/ stat\n#include <string>\n#if defined(_WIN32)\n#include <direct.h> \/\/ _mkdir\n#endif\n\nbool isDirExist(const std::string& path) {\n#if defined(_WIN32)\n struct _stat info;\n if (_stat(path.c_str(), &info) != 0) {\n return false;\n }\n return (info.st_mode & _S_IFDIR) != 0;\n#else\n struct stat info;\n if (stat(path.c_str(), &info) != 0) {\n return false;\n }\n return (info.st_mode & S_IFDIR) != 0;\n#endif\n}\n\nbool makePath(const std::string& path) {\n#if defined(_WIN32)\n int ret = _mkdir(path.c_str());\n#else\n mode_t mode = 0755;\n int ret = mkdir(path.c_str(), mode);\n#endif\n if (ret == 0) return true;\n\n switch (errno) {\n case ENOENT:\n \/\/ parent didn't exist, try to create it\n {\n int pos = path.find_last_of('\/');\n if ((size_t)pos == std::string::npos)\n#if defined(_WIN32)\n pos = path.find_last_of('\\\\');\n if (pos == std::string::npos)\n#endif\n return false;\n if (!makePath(path.substr(0, pos))) return false;\n }\n \/\/ now, try to create again\n#if defined(_WIN32)\n return 0 == _mkdir(path.c_str());\n#else\n return 0 == mkdir(path.c_str(), mode);\n#endif\n\n case EEXIST:\n \/\/ done!\n return isDirExist(path);\n\n default:\n return false;\n }\n}\n\nint main(int argc, char** argv) {\n\n if (argc < 3) {\n std::cout << \"Dump all frames of a video into a folder\\n\";\n std::cout\n << \"Frames are named by their timestamps in the video in nanosecs\\n\";\n std::cout << \"Usage: \" << argv[0]\n << \" input_video_name \/output\/image\/folder [start_index(=0)] \"\n \"[finish_index(inclusive)]\\n\";\n std::cout\n << \"If you are convert the video for kalibr, set start_index such that \"\n \"the start from has a timestamp greater than 1 sec\\n\";\n std::cout << \"to avoid timestamp less than 9 digits causing error in \"\n \"kalibr_bagcreator\\n\";\n std::cout << \"The output does not need to exist beforehand\\n\";\n std::cout << \"Ex:\" << argv[0]\n << \"\/home\/user\/Desktop\/IMG_0658.MOV \/home\/user\/Desktop\/IMG_0658\/\"\n << std::endl;\n\n return 1;\n }\n\n int startIndex = 0, finishIndex = 1e6;\n if (argc > 3) {\n startIndex = std::atoi(argv[3]);\n }\n if (argc > 4) {\n finishIndex = std::atoi(argv[4]);\n }\n std::cout << \"start and finish index \" << startIndex << \" \" << finishIndex\n << std::endl;\n std::string videoName(argv[1]);\n std::string imageSeqPath = argv[2];\n makePath(argv[2]);\n\n std::string windowName = \"DisplayVideo\";\n cv::namedWindow(windowName, CV_WINDOW_AUTOSIZE);\n\n int downscale = 1;\n cv::VideoCapture cap(videoName);\n char buffer[100];\n double rate = cap.get(CV_CAP_PROP_FPS);\n if (!rate) cerr << \"Error opening video file \" << videoName << endl;\n\n assert(cap.get(CV_CAP_PROP_POS_FRAMES) == 0);\n assert(cap.get(CV_CAP_PROP_POS_MSEC) == 0);\n\n cap.set(CV_CAP_PROP_POS_FRAMES, startIndex); \/\/ start from a 0 based index\n int totalImages =\n std::min(finishIndex, (int)cap.get(CV_CAP_PROP_FRAME_COUNT) - 1);\n int width = cap.get(CV_CAP_PROP_FRAME_WIDTH),\n height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\n cv::Mat left_img, dst, last_left_img;\n double time_frame(-1); \/\/ unit milli sec\n double last_time_frame(-1);\n for (int numImages = startIndex; numImages <= totalImages; ++numImages) {\n int currentId = cap.get(CV_CAP_PROP_POS_FRAMES);\n if (currentId != numImages) {\n cout << \"current image video id 0 based \" << currentId << \" and counter \"\n << numImages << endl;\n }\n time_frame = cap.get(CV_CAP_PROP_POS_MSEC);\n\n cout << \"frame time \" << std::setprecision(16) << time_frame\n << \"[ms] and index \" << numImages;\n if (last_time_frame != -1) {\n std::cout << \" \" << (time_frame - last_time_frame) * 1000000 << \"[ns]\";\n }\n std::cout << std::endl;\n cap.read(left_img);\n if (left_img.empty()) { \/\/ this happens when a frame is missed\n continue;\n }\n if (downscale > 1) {\n cv::pyrDown(left_img, dst, cv::Size((width + 1) \/ 2, (height + 1) \/ 2));\n left_img = dst;\n }\n if (numImages % 30 == 0)\n std::cout << \"process image of index in the video \" << numImages\n << std::endl;\n sprintf(buffer, \"%.0f.png\", time_frame * 1e6);\n string filename = imageSeqPath + '\/' + buffer;\n imwrite(filename, left_img);\n imshow(windowName, left_img);\n waitKey(3);\n last_time_frame = time_frame;\n }\n cv::destroyWindow(windowName);\n}\n<commit_msg>Update video2images_kalibr.cpp<commit_after>#ifdef LOCAL_OPENCV\n#include <opencv2\/features2d.hpp>\n#include <opencv2\/imgcodecs.hpp>\n#include <opencv2\/opencv.hpp>\n#else\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/features2d\/features2d.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#endif\n\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace cv;\n\n\/\/ http:\/\/stackoverflow.com\/questions\/675039\/how-can-i-create-directory-tree-in-c-linux\n#include <errno.h> \/\/ errno, ENOENT, EEXIST\n#include <sys\/stat.h> \/\/ stat\n#include <string>\n#if defined(_WIN32)\n#include <direct.h> \/\/ _mkdir\n#endif\n\nbool isDirExist(const std::string& path) {\n#if defined(_WIN32)\n struct _stat info;\n if (_stat(path.c_str(), &info) != 0) {\n return false;\n }\n return (info.st_mode & _S_IFDIR) != 0;\n#else\n struct stat info;\n if (stat(path.c_str(), &info) != 0) {\n return false;\n }\n return (info.st_mode & S_IFDIR) != 0;\n#endif\n}\n\nbool makePath(const std::string& path) {\n#if defined(_WIN32)\n int ret = _mkdir(path.c_str());\n#else\n mode_t mode = 0755;\n int ret = mkdir(path.c_str(), mode);\n#endif\n if (ret == 0) return true;\n\n switch (errno) {\n case ENOENT:\n \/\/ parent didn't exist, try to create it\n {\n int pos = path.find_last_of('\/');\n if ((size_t)pos == std::string::npos)\n#if defined(_WIN32)\n pos = path.find_last_of('\\\\');\n if (pos == std::string::npos)\n#endif\n return false;\n if (!makePath(path.substr(0, pos))) return false;\n }\n \/\/ now, try to create again\n#if defined(_WIN32)\n return 0 == _mkdir(path.c_str());\n#else\n return 0 == mkdir(path.c_str(), mode);\n#endif\n\n case EEXIST:\n \/\/ done!\n return isDirExist(path);\n\n default:\n return false;\n }\n}\n\nint main(int argc, char** argv) {\n\n if (argc < 3) {\n std::cout << \"Dump all frames of a video into a folder\\n\";\n std::cout\n << \"Frames are named by their timestamps in the video in nanosecs\\n\";\n std::cout << \"Usage: \" << argv[0]\n << \" input_video_name \/output\/image\/folder [start_index(=0)] \"\n \"[finish_index(inclusive)]\\n\";\n std::cout\n << \"If you are convert the video for kalibr, set start_index such that \"\n \"the start from has a timestamp greater than 1 sec\\n\";\n std::cout << \"to avoid timestamp less than 9 digits causing error in \"\n \"kalibr_bagcreator\\n\";\n std::cout << \"The output does not need to exist beforehand\\n\";\n std::cout << \"Ex: \" << argv[0]\n << \" \/home\/user\/Desktop\/IMG_0658.MOV \/home\/user\/Desktop\/IMG_0658\/\"\n << std::endl;\n\n return 1;\n }\n\n int startIndex = 0, finishIndex = 1e6;\n if (argc > 3) {\n startIndex = std::atoi(argv[3]);\n }\n if (argc > 4) {\n finishIndex = std::atoi(argv[4]);\n }\n std::cout << \"start and finish index \" << startIndex << \" \" << finishIndex\n << std::endl;\n std::string videoName(argv[1]);\n std::string imageSeqPath = argv[2];\n makePath(argv[2]);\n\n std::string windowName = \"DisplayVideo\";\n cv::namedWindow(windowName, CV_WINDOW_AUTOSIZE);\n\n int downscale = 1;\n cv::VideoCapture cap(videoName);\n char buffer[100];\n double rate = cap.get(CV_CAP_PROP_FPS);\n if (!rate) cerr << \"Error opening video file \" << videoName << endl;\n\n assert(cap.get(CV_CAP_PROP_POS_FRAMES) == 0);\n assert(cap.get(CV_CAP_PROP_POS_MSEC) == 0);\n\n cap.set(CV_CAP_PROP_POS_FRAMES, startIndex); \/\/ start from a 0 based index\n int totalImages =\n std::min(finishIndex, (int)cap.get(CV_CAP_PROP_FRAME_COUNT) - 1);\n int width = cap.get(CV_CAP_PROP_FRAME_WIDTH),\n height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\n cv::Mat left_img, dst, last_left_img;\n double time_frame(-1); \/\/ unit milli sec\n double last_time_frame(-1);\n for (int numImages = startIndex; numImages <= totalImages; ++numImages) {\n int currentId = cap.get(CV_CAP_PROP_POS_FRAMES);\n if (currentId != numImages) {\n cout << \"current image video id 0 based \" << currentId << \" and counter \"\n << numImages << endl;\n }\n time_frame = cap.get(CV_CAP_PROP_POS_MSEC);\n\n cout << \"frame time \" << std::setprecision(16) << time_frame\n << \"[ms] and index \" << numImages;\n if (last_time_frame != -1) {\n std::cout << \" \" << (time_frame - last_time_frame) * 1000000 << \"[ns]\";\n }\n std::cout << std::endl;\n cap.read(left_img);\n if (left_img.empty()) { \/\/ this happens when a frame is missed\n continue;\n }\n if (downscale > 1) {\n cv::pyrDown(left_img, dst, cv::Size((width + 1) \/ 2, (height + 1) \/ 2));\n left_img = dst;\n }\n if (numImages % 30 == 0)\n std::cout << \"process image of index in the video \" << numImages\n << std::endl;\n sprintf(buffer, \"%.0f.png\", time_frame * 1e6);\n string filename = imageSeqPath + '\/' + buffer;\n imwrite(filename, left_img);\n imshow(windowName, left_img);\n waitKey(3);\n last_time_frame = time_frame;\n }\n cv::destroyWindow(windowName);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cinder\/app\/App.h\"\n#include \"metal.h\"\n#include \"VertexBuffer.h\"\n#include \"Batch.h\"\n#include \"Shader.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass CubeApp : public App\n{\npublic:\n \n void setup() override;\n void resize() override;\n void update() override;\n void draw() override;\n \n CameraPersp mCam;\n mat4 mCubeRotation;\n \n mtl::RenderPassDescriptorRef mRenderDescriptor;\n mtl::TextureBufferRef mTexture;\n mtl::RenderPipelineStateRef mPipeline;\n mtl::DepthStateRef mDepthEnabled;\n mtl::BatchRef mBatchCube;\n \n};\n\nvoid CubeApp::setup()\n{\n mRenderDescriptor = mtl::RenderPassDescriptor::create();\n\n mCam.lookAt( vec3( 3, 2, 4 ), vec3( 0 ) );\n\n mTexture = mtl::TextureBuffer::create(loadImage(getAssetPath(\"texture.jpg\")),\n mtl::TextureBuffer::Format().mipmapLevel(3).flipVertically());\n\n mDepthEnabled = mtl::DepthState::create( mtl::DepthState::Format().depthWriteEnabled() );\n\n mPipeline = mtl::RenderPipelineState::create(\"batch_vertex\", \"cube_fragment\");\n mBatchCube = mtl::Batch::create(geom::Cube(), mPipeline);\n \n\/\/ mPipeline = mtl::getStockPipeline(mtl::ShaderDef().texture());\n\/\/ mBatchCube = mtl::Batch::create(geom::Cube(), mPipeline);\n\n\n}\n\nvoid CubeApp::resize()\n{\n mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );\n}\n\nvoid CubeApp::update()\n{\n \/\/ Rotate the cube by 0.2 degrees around the y-axis\n mCubeRotation *= rotate( toRadians( 0.2f ), normalize( vec3( 0, 1, 0 ) ) );\n}\n\nvoid CubeApp::draw()\n{\n mtl::ScopedRenderCommandBuffer renderBuffer;\n mtl::ScopedRenderEncoder renderEncoder = renderBuffer.scopedRenderEncoder(mRenderDescriptor);\n\n renderEncoder.setDepthStencilState(mDepthEnabled);\n renderEncoder.setTexture(mTexture);\n \n mtl::setMatrices(mCam);\n mtl::setModelMatrix(mCubeRotation);\n \/\/mBatchCube->draw(renderEncoder);\n renderEncoder.draw(mBatchCube);\n}\n\nCINDER_APP( CubeApp, RendererMetal( RendererMetal::Options().numInflightBuffers(1) ) )\n<commit_msg>Sample cleanup<commit_after>#include \"cinder\/app\/App.h\"\n#include \"metal.h\"\n#include \"VertexBuffer.h\"\n#include \"Batch.h\"\n#include \"Shader.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass CubeApp : public App\n{\npublic:\n \n void setup() override;\n void resize() override;\n void update() override;\n void draw() override;\n \n CameraPersp mCam;\n mat4 mCubeRotation;\n \n mtl::RenderPassDescriptorRef mRenderDescriptor;\n mtl::TextureBufferRef mTexture;\n mtl::RenderPipelineStateRef mPipeline;\n mtl::DepthStateRef mDepthEnabled;\n mtl::BatchRef mBatchCube;\n \n};\n\nvoid CubeApp::setup()\n{\n mRenderDescriptor = mtl::RenderPassDescriptor::create();\n\n mCam.lookAt( vec3( 3, 2, 4 ), vec3( 0 ) );\n\n mTexture = mtl::TextureBuffer::create(loadImage(getAssetPath(\"texture.jpg\")),\n mtl::TextureBuffer::Format().mipmapLevel(3).flipVertically());\n\n mDepthEnabled = mtl::DepthState::create( mtl::DepthState::Format().depthWriteEnabled() );\n\n mPipeline = mtl::RenderPipelineState::create(\"batch_vertex\", \"cube_fragment\");\n mBatchCube = mtl::Batch::create(geom::Cube(), mPipeline);\n}\n\nvoid CubeApp::resize()\n{\n mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );\n}\n\nvoid CubeApp::update()\n{\n \/\/ Rotate the cube by 0.2 degrees around the y-axis\n mCubeRotation *= rotate( toRadians( 0.2f ), normalize( vec3( 0, 1, 0 ) ) );\n}\n\nvoid CubeApp::draw()\n{\n mtl::ScopedRenderCommandBuffer renderBuffer;\n mtl::ScopedRenderEncoder renderEncoder = renderBuffer.scopedRenderEncoder(mRenderDescriptor);\n\n renderEncoder.setDepthStencilState(mDepthEnabled);\n renderEncoder.setTexture(mTexture);\n \n mtl::setMatrices(mCam);\n mtl::setModelMatrix(mCubeRotation);\n renderEncoder.draw(mBatchCube);\n}\n\nCINDER_APP( CubeApp, RendererMetal( RendererMetal::Options().numInflightBuffers(1) ) )\n<|endoftext|>"} {"text":"<commit_before>#include \"GameView.h\"\n#include \"..\/CarrotQt5.h\"\n#include \"..\/actor\/Player.h\"\n#include \"..\/graphics\/ShaderSource.h\"\n\nGameView::GameView(std::shared_ptr<CarrotQt5> root, const uint& playerID, const sf::Vector2f& dimensions) \n : playerID(playerID), root(root) {\n canvas = std::make_shared<sf::RenderTexture>();\n canvas->create(dimensions.x, dimensions.y);\n renderAuxiliaryCanvas = std::make_shared<sf::RenderTexture>();\n renderAuxiliaryCanvas->create(dimensions.x, dimensions.y);\n playerView = std::make_unique<sf::View>(sf::FloatRect(0, 0, dimensions.x, dimensions.y));\n uiView = std::make_unique<sf::View>(sf::FloatRect(0, 0, dimensions.x, dimensions.y));\n viewSprite = std::make_unique<sf::Sprite>(canvas->getTexture());\n}\n\nvoid GameView::setLighting(int target, bool immediate) {\n if (target == targetLightingLevel) {\n return;\n }\n\n targetLightingLevel = target;\n if (immediate) {\n lightingLevel = target;\n } else {\n addTimer(3.0, false, static_cast<TimerCallbackFunc>(&GameView::setLightingStep));\n }\n}\n\nstd::weak_ptr<sf::RenderTexture> GameView::getCanvas() {\n return canvas;\n}\n\nvoid GameView::setLightingStep() {\n if (targetLightingLevel == lightingLevel) {\n return;\n }\n short dir = (targetLightingLevel < lightingLevel) ? -1 : 1;\n lightingLevel += dir;\n addTimer(3.0, false, static_cast<TimerCallbackFunc>(&GameView::setLightingStep));\n}\n\nCoordinatePair GameView::getViewCenter() {\n return CoordinatePair(playerView->getCenter());\n}\n\nunsigned GameView::getViewWidth() {\n return playerView->getSize().x;\n}\n\nunsigned GameView::getViewHeight() {\n return playerView->getSize().y;\n}\n\nint GameView::getLightingLevel() {\n return lightingLevel;\n}\n\nvoid GameView::drawView(std::shared_ptr<sf::RenderTarget> windowCanvas) {\n canvas->display();\n windowCanvas->draw(*viewSprite.get());\n\n \/\/ Clear the drawing surface; we don't want to do this if we emulate the JJ2 behavior\n canvas->clear();\n}\n\nvoid GameView::drawUiElements() {\n advanceTimers();\n\n auto player = root->getPlayer(playerID).lock();\n if (player == nullptr) {\n return;\n }\n canvas->setView(*uiView.get());\n\n sf::RenderStates states;\n auto shader = ShaderSource::getShader(\"LightingShader\");\n shader->setParameter(\"color\", sf::Color::Black);\n shader->setParameter(\"lightingLevel\", lightingLevel \/ 100.0);\n\n shader->setParameter(\"center\", sf::Vector2f(\n player->getPosition().x - playerView->getCenter().x + playerView->getSize().x \/ 2,\n \/\/ Reverse the vertical coordinate, as the frame buffer is \"upside down\"\n playerView->getSize().y - ((player->getPosition().y - 15) - playerView->getCenter().y + playerView->getSize().y \/ 2)\n ));\n states.shader = shader.get();\n renderAuxiliaryCanvas->clear();\n renderAuxiliaryCanvas->draw(*viewSprite.get(), states);\n renderAuxiliaryCanvas->display();\n std::swap(canvas, renderAuxiliaryCanvas);\n viewSprite->setTexture(canvas->getTexture());\n\n \/\/ Draw the character icon; managed by the player object\n player->drawUIOverlay();\n\n}\n\nvoid GameView::centerToPlayer() {\n auto player = root->getPlayer(playerID).lock();\n if (player == nullptr) {\n return;\n }\n\n player->setToViewCenter();\n}\n\nvoid GameView::setSize(const sf::Vector2f& dimensions) {\n canvas->create(dimensions.x, dimensions.y);\n renderAuxiliaryCanvas->create(dimensions.x, dimensions.y);\n playerView->setCenter(dimensions.x \/ 2, dimensions.y \/ 2);\n playerView->setSize(dimensions);\n uiView->setCenter(dimensions.x \/ 2, dimensions.y \/ 2);\n uiView->setSize(dimensions);\n viewSprite->setTextureRect(sf::IntRect(0, 0, std::ceil(dimensions.x), std::ceil(dimensions.y)));\n}\n\nvoid GameView::centerView(const double& x, const double& y) {\n playerView->setCenter(x, y);\n canvas->setView(*playerView.get());\n}\n\nvoid GameView::centerView(const CoordinatePair& pair) {\n playerView->setCenter(pair.x, pair.y);\n canvas->setView(*playerView.get());\n}\n<commit_msg>Fix upside-down frames when resizing and at level start<commit_after>#include \"GameView.h\"\n#include \"..\/CarrotQt5.h\"\n#include \"..\/actor\/Player.h\"\n#include \"..\/graphics\/ShaderSource.h\"\n\nGameView::GameView(std::shared_ptr<CarrotQt5> root, const uint& playerID, const sf::Vector2f& dimensions) \n : playerID(playerID), root(root) {\n canvas = std::make_shared<sf::RenderTexture>();\n canvas->create(dimensions.x, dimensions.y);\n renderAuxiliaryCanvas = std::make_shared<sf::RenderTexture>();\n renderAuxiliaryCanvas->create(dimensions.x, dimensions.y);\n playerView = std::make_unique<sf::View>(sf::FloatRect(0, 0, dimensions.x, dimensions.y));\n uiView = std::make_unique<sf::View>(sf::FloatRect(0, 0, dimensions.x, dimensions.y));\n viewSprite = std::make_unique<sf::Sprite>(canvas->getTexture());\n}\n\nvoid GameView::setLighting(int target, bool immediate) {\n if (target == targetLightingLevel) {\n return;\n }\n\n targetLightingLevel = target;\n if (immediate) {\n lightingLevel = target;\n } else {\n addTimer(3.0, false, static_cast<TimerCallbackFunc>(&GameView::setLightingStep));\n }\n}\n\nstd::weak_ptr<sf::RenderTexture> GameView::getCanvas() {\n return canvas;\n}\n\nvoid GameView::setLightingStep() {\n if (targetLightingLevel == lightingLevel) {\n return;\n }\n short dir = (targetLightingLevel < lightingLevel) ? -1 : 1;\n lightingLevel += dir;\n addTimer(3.0, false, static_cast<TimerCallbackFunc>(&GameView::setLightingStep));\n}\n\nCoordinatePair GameView::getViewCenter() {\n return CoordinatePair(playerView->getCenter());\n}\n\nunsigned GameView::getViewWidth() {\n return playerView->getSize().x;\n}\n\nunsigned GameView::getViewHeight() {\n return playerView->getSize().y;\n}\n\nint GameView::getLightingLevel() {\n return lightingLevel;\n}\n\nvoid GameView::drawView(std::shared_ptr<sf::RenderTarget> windowCanvas) {\n canvas->display();\n windowCanvas->draw(*viewSprite.get());\n\n \/\/ Clear the drawing surface; we don't want to do this if we emulate the JJ2 behavior\n canvas->clear();\n}\n\nvoid GameView::drawUiElements() {\n advanceTimers();\n\n auto player = root->getPlayer(playerID).lock();\n if (player == nullptr) {\n return;\n }\n canvas->setView(*uiView.get());\n canvas->display();\n\n sf::RenderStates states;\n auto shader = ShaderSource::getShader(\"LightingShader\");\n shader->setParameter(\"color\", sf::Color::Black);\n shader->setParameter(\"lightingLevel\", lightingLevel \/ 100.0);\n\n shader->setParameter(\"center\", sf::Vector2f(\n player->getPosition().x - playerView->getCenter().x + playerView->getSize().x \/ 2,\n \/\/ Reverse the vertical coordinate, as the frame buffer is \"upside down\"\n playerView->getSize().y - ((player->getPosition().y - 15) - playerView->getCenter().y + playerView->getSize().y \/ 2)\n ));\n states.shader = shader.get();\n renderAuxiliaryCanvas->clear();\n renderAuxiliaryCanvas->draw(*viewSprite.get(), states);\n renderAuxiliaryCanvas->display();\n std::swap(canvas, renderAuxiliaryCanvas);\n viewSprite->setTexture(canvas->getTexture());\n\n \/\/ Draw the character icon; managed by the player object\n player->drawUIOverlay();\n\n}\n\nvoid GameView::centerToPlayer() {\n auto player = root->getPlayer(playerID).lock();\n if (player == nullptr) {\n return;\n }\n\n player->setToViewCenter();\n}\n\nvoid GameView::setSize(const sf::Vector2f& dimensions) {\n canvas->create(dimensions.x, dimensions.y);\n renderAuxiliaryCanvas->create(dimensions.x, dimensions.y);\n playerView->setCenter(dimensions.x \/ 2, dimensions.y \/ 2);\n playerView->setSize(dimensions);\n uiView->setCenter(dimensions.x \/ 2, dimensions.y \/ 2);\n uiView->setSize(dimensions);\n viewSprite->setTextureRect(sf::IntRect(0, 0, std::ceil(dimensions.x), std::ceil(dimensions.y)));\n}\n\nvoid GameView::centerView(const double& x, const double& y) {\n playerView->setCenter(x, y);\n canvas->setView(*playerView.get());\n}\n\nvoid GameView::centerView(const CoordinatePair& pair) {\n playerView->setCenter(pair.x, pair.y);\n canvas->setView(*playerView.get());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"treemenu.h\"\n#include \"treewidget.h\"\n#include \"treeitem.h\"\n#include <QContextMenuEvent>\n#include <QCoreApplication>\n#include <IrcConnection>\n#include <IrcCommand>\n#include <IrcChannel>\n\nTreeMenu::TreeMenu(TreeWidget* tree) : QMenu(tree)\n{\n d.item = 0;\n d.tree = tree;\n d.disconnectAction = addAction(tr(\"Disconnect\"));\n d.reconnectAction = addAction(tr(\"Reconnect\"));\n addSeparator();\n d.editAction = addAction(tr(\"Edit\"), this, SLOT(onEditTriggered()));\n d.whoisAction = addAction(tr(\"Whois\"), this, SLOT(onWhoisTriggered()));\n d.joinAction = addAction(tr(\"Join\"), this, SLOT(onJoinTriggered()));\n d.partAction = addAction(tr(\"Part\"), this, SLOT(onPartTriggered()));\n addSeparator();\n d.closeAction = addAction(tr(\"Close\"), this, SLOT(onCloseTriggered()), QKeySequence::Close);\n\n tree->installEventFilter(this);\n}\n\nbool TreeMenu::eventFilter(QObject *object, QEvent *event)\n{\n Q_UNUSED(object);\n if (event->type() == QEvent::ContextMenu) {\n QContextMenuEvent* cme = static_cast<QContextMenuEvent*>(event);\n QTreeWidgetItem* item = d.tree->itemAt(cme->pos());\n if (item)\n exec(static_cast<TreeItem*>(item), cme->globalPos());\n return true;\n }\n return false;\n}\n\nvoid TreeMenu::exec(TreeItem* item, const QPoint& pos)\n{\n setup(item);\n updateActions();\n QMenu::exec(pos);\n}\n\nvoid TreeMenu::onEditTriggered()\n{\n \/\/ TODO: QMetaObject::invokeMethod(parent(), \"editConnection\", Q_ARG(IrcConnection*, d.item->connection()));\n}\n\nvoid TreeMenu::onWhoisTriggered()\n{\n IrcCommand* command = IrcCommand::createWhois(d.item->text(0));\n d.item->connection()->sendCommand(command);\n}\n\nvoid TreeMenu::onJoinTriggered()\n{\n IrcCommand* command = IrcCommand::createJoin(d.item->text(0));\n d.item->connection()->sendCommand(command);\n}\n\nvoid TreeMenu::onPartTriggered()\n{\n IrcChannel* channel = d.item->buffer()->toChannel();\n if (channel) {\n QString reason = tr(\"%1 %2 - http:\/\/%3\").arg(QCoreApplication::applicationName())\n .arg(QCoreApplication::applicationVersion())\n .arg(QCoreApplication::organizationDomain());\n channel->part(reason);\n }\n}\n\nvoid TreeMenu::onCloseTriggered()\n{\n onPartTriggered();\n d.item->buffer()->deleteLater();\n}\n\nvoid TreeMenu::updateActions()\n{\n if (d.item) {\n const bool child = d.item->parentItem();\n const bool connected = d.item->connection()->isActive();\n const bool active = d.item->buffer()->isActive();\n const bool channel = d.item->buffer()->isChannel();\n d.disconnectAction->setVisible(connected);\n d.reconnectAction->setVisible(!connected);\n d.editAction->setVisible(!connected && !child);\n d.joinAction->setVisible(connected && channel && !active);\n d.partAction->setVisible(connected && channel && active);\n d.whoisAction->setVisible(connected && child && !channel);\n } else {\n d.disconnectAction->setVisible(false);\n d.reconnectAction->setVisible(false);\n d.editAction->setVisible(false);\n d.whoisAction->setVisible(false);\n d.joinAction->setVisible(false);\n d.partAction->setVisible(false);\n }\n\n d.closeAction->setVisible(d.item);\n}\n\nvoid TreeMenu::setup(TreeItem* item)\n{\n if (d.item != item) {\n if (d.item && d.item->connection()) {\n IrcConnection* connection = d.item->connection();\n disconnect(connection, SIGNAL(connecting()), this, SLOT(updateActions()));\n disconnect(connection, SIGNAL(connected()), this, SLOT(updateActions()));\n disconnect(connection, SIGNAL(disconnected()), this, SLOT(updateActions()));\n\n disconnect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(setDisabled()));\n disconnect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(quit()));\n\n disconnect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(setEnabled()));\n disconnect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(open()));\n }\n if (item && item->connection()) {\n IrcConnection* connection = item->connection();\n connect(connection, SIGNAL(connecting()), this, SLOT(updateActions()));\n connect(connection, SIGNAL(connected()), this, SLOT(updateActions()));\n connect(connection, SIGNAL(disconnected()), this, SLOT(updateActions()));\n\n connect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(setDisabled()));\n connect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(quit()));\n\n connect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(setEnabled()));\n connect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(open()));\n }\n d.item = item;\n }\n}\n<commit_msg>TreeMenu: disable non-functional \"Edit\"<commit_after>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"treemenu.h\"\n#include \"treewidget.h\"\n#include \"treeitem.h\"\n#include <QContextMenuEvent>\n#include <QCoreApplication>\n#include <IrcConnection>\n#include <IrcCommand>\n#include <IrcChannel>\n\nTreeMenu::TreeMenu(TreeWidget* tree) : QMenu(tree)\n{\n d.item = 0;\n d.tree = tree;\n d.disconnectAction = addAction(tr(\"Disconnect\"));\n d.reconnectAction = addAction(tr(\"Reconnect\"));\n addSeparator();\n \/\/ TODO: d.editAction = addAction(tr(\"Edit\"), this, SLOT(onEditTriggered()));\n d.whoisAction = addAction(tr(\"Whois\"), this, SLOT(onWhoisTriggered()));\n d.joinAction = addAction(tr(\"Join\"), this, SLOT(onJoinTriggered()));\n d.partAction = addAction(tr(\"Part\"), this, SLOT(onPartTriggered()));\n addSeparator();\n d.closeAction = addAction(tr(\"Close\"), this, SLOT(onCloseTriggered()), QKeySequence::Close);\n\n tree->installEventFilter(this);\n}\n\nbool TreeMenu::eventFilter(QObject *object, QEvent *event)\n{\n Q_UNUSED(object);\n if (event->type() == QEvent::ContextMenu) {\n QContextMenuEvent* cme = static_cast<QContextMenuEvent*>(event);\n QTreeWidgetItem* item = d.tree->itemAt(cme->pos());\n if (item)\n exec(static_cast<TreeItem*>(item), cme->globalPos());\n return true;\n }\n return false;\n}\n\nvoid TreeMenu::exec(TreeItem* item, const QPoint& pos)\n{\n setup(item);\n updateActions();\n QMenu::exec(pos);\n}\n\nvoid TreeMenu::onEditTriggered()\n{\n \/\/ TODO: QMetaObject::invokeMethod(parent(), \"editConnection\", Q_ARG(IrcConnection*, d.item->connection()));\n}\n\nvoid TreeMenu::onWhoisTriggered()\n{\n IrcCommand* command = IrcCommand::createWhois(d.item->text(0));\n d.item->connection()->sendCommand(command);\n}\n\nvoid TreeMenu::onJoinTriggered()\n{\n IrcCommand* command = IrcCommand::createJoin(d.item->text(0));\n d.item->connection()->sendCommand(command);\n}\n\nvoid TreeMenu::onPartTriggered()\n{\n IrcChannel* channel = d.item->buffer()->toChannel();\n if (channel) {\n QString reason = tr(\"%1 %2 - http:\/\/%3\").arg(QCoreApplication::applicationName())\n .arg(QCoreApplication::applicationVersion())\n .arg(QCoreApplication::organizationDomain());\n channel->part(reason);\n }\n}\n\nvoid TreeMenu::onCloseTriggered()\n{\n onPartTriggered();\n d.item->buffer()->deleteLater();\n}\n\nvoid TreeMenu::updateActions()\n{\n if (d.item) {\n const bool child = d.item->parentItem();\n const bool connected = d.item->connection()->isActive();\n const bool active = d.item->buffer()->isActive();\n const bool channel = d.item->buffer()->isChannel();\n d.disconnectAction->setVisible(connected);\n d.reconnectAction->setVisible(!connected);\n \/\/ TODO: d.editAction->setVisible(!connected && !child);\n d.joinAction->setVisible(connected && channel && !active);\n d.partAction->setVisible(connected && channel && active);\n d.whoisAction->setVisible(connected && child && !channel);\n } else {\n d.disconnectAction->setVisible(false);\n d.reconnectAction->setVisible(false);\n \/\/ TODO: d.editAction->setVisible(false);\n d.whoisAction->setVisible(false);\n d.joinAction->setVisible(false);\n d.partAction->setVisible(false);\n }\n\n d.closeAction->setVisible(d.item);\n}\n\nvoid TreeMenu::setup(TreeItem* item)\n{\n if (d.item != item) {\n if (d.item && d.item->connection()) {\n IrcConnection* connection = d.item->connection();\n disconnect(connection, SIGNAL(connecting()), this, SLOT(updateActions()));\n disconnect(connection, SIGNAL(connected()), this, SLOT(updateActions()));\n disconnect(connection, SIGNAL(disconnected()), this, SLOT(updateActions()));\n\n disconnect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(setDisabled()));\n disconnect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(quit()));\n\n disconnect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(setEnabled()));\n disconnect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(open()));\n }\n if (item && item->connection()) {\n IrcConnection* connection = item->connection();\n connect(connection, SIGNAL(connecting()), this, SLOT(updateActions()));\n connect(connection, SIGNAL(connected()), this, SLOT(updateActions()));\n connect(connection, SIGNAL(disconnected()), this, SLOT(updateActions()));\n\n connect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(setDisabled()));\n connect(d.disconnectAction, SIGNAL(triggered()), connection, SLOT(quit()));\n\n connect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(setEnabled()));\n connect(d.reconnectAction, SIGNAL(triggered()), connection, SLOT(open()));\n }\n d.item = item;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pluginmanager.h\"\n\n#include <QApplication>\n#include <QDir>\n#include <QPluginLoader>\n#include <QSettings>\n\n#include <QDebug>\n\nnamespace OpenCOR {\n\nPluginManager::PluginManager()\n{\n#ifndef Q_WS_MAC\n QString pluginsDir = \"plugins\";\n#else\n QString pluginsDir = QString(\"..\")+QDir::separator()+\"PlugIns\";\n#endif\n\n mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath()\n +QDir::separator()+pluginsDir;\n\n#ifdef Q_WS_MAC\n mPluginsDir += QDir::separator()+qApp->applicationName();\n#endif\n}\n\nPluginManager::~PluginManager()\n{\n}\n\nvoid PluginManager::loadPlugins(QSettings *pSettings)\n{\n \/\/ Determine which plugins are available for loading\n\n#ifdef Q_WS_WIN\n const QString extension = \".dll\";\n#elif defined(Q_WS_MAC)\n const QString extension = \".dylib\";\n#else\n const QString extension = \".so\";\n#endif\n\n QFileInfoList files = QDir(mPluginsDir).entryInfoList(QStringList(\"*\"+extension), QDir::Files);\n QStringList pluginFiles;\n\n foreach (const QFileInfo &file, files) {\n QString pluginFileName = file.canonicalFilePath();\n\n pluginFiles << pluginFileName;\n\n qDebug() << \"Plugin #\" << pluginFiles.count() << \":\" << pluginFileName;\n\n QString pluginBaseName = QFileInfo(pluginFileName).baseName();\n\n if (!pluginBaseName.compare(\"Core\") || !pluginBaseName.compare(\"Viewer\")) {\n \/\/ Try to load the plugin as a 'proper' plugin\n\n QPluginLoader loader(pluginFileName);\n\n if (loader.load()) {\n qDebug() << \" -\" << pluginFileName << \" loaded...\";\n } else {\n qDebug() << \" -\" << pluginFileName << \" NOT loaded...\";\n qDebug() << \" ===>\" << loader.errorString();\n }\n }\n }\n\n \/\/---GRY--- TO BE DONE...\n}\n\n}\n<commit_msg>Addendum to the previous commit.<commit_after>#include \"pluginmanager.h\"\n\n#include <QApplication>\n#include <QDir>\n#include <QPluginLoader>\n#include <QSettings>\n\n#include <QDebug>\n\nnamespace OpenCOR {\n\nPluginManager::PluginManager()\n{\n#ifndef Q_WS_MAC\n QString pluginsDir = \"plugins\";\n#else\n QString pluginsDir = QString(\"..\")+QDir::separator()+\"PlugIns\";\n#endif\n\n mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath()\n +QDir::separator()+pluginsDir;\n\n#ifdef Q_WS_MAC\n mPluginsDir += QDir::separator()+qApp->applicationName();\n#endif\n}\n\nPluginManager::~PluginManager()\n{\n}\n\nvoid PluginManager::loadPlugins(QSettings *pSettings)\n{\n \/\/ Determine which plugins are available for loading\n\n#ifdef Q_WS_WIN\n const QString extension = \".dll\";\n#elif defined(Q_WS_MAC)\n const QString extension = \".dylib\";\n#else\n const QString extension = \".so\";\n#endif\n\n QFileInfoList files = QDir(mPluginsDir).entryInfoList(QStringList(\"*\"+extension), QDir::Files);\n QStringList pluginFiles;\n\n foreach (const QFileInfo &file, files) {\n QString pluginFileName = file.canonicalFilePath();\n\n pluginFiles << pluginFileName;\n\n qDebug() << \"Plugin #\" << pluginFiles.count() << \":\" << pluginFileName;\n\n QString pluginBaseName = QFileInfo(pluginFileName).baseName();\n\n if ( !pluginBaseName.compare(\"Core\") || !pluginBaseName.compare(\"libCore\")\n || !pluginBaseName.compare(\"Viewer\") || !pluginBaseName.compare(\"libViewer\")) {\n \/\/ Try to load the plugin as a 'proper' plugin\n\n QPluginLoader loader(pluginFileName);\n\n if (loader.load()) {\n qDebug() << \" -\" << pluginFileName << \" loaded...\";\n } else {\n qDebug() << \" -\" << pluginFileName << \" NOT loaded...\";\n qDebug() << \" ===>\" << loader.errorString();\n }\n }\n }\n\n \/\/---GRY--- TO BE DONE...\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/vk\/GrVkTexture.h\"\n\n#include \"src\/gpu\/GrTexturePriv.h\"\n#include \"src\/gpu\/vk\/GrVkDescriptorSet.h\"\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#include \"src\/gpu\/vk\/GrVkImageView.h\"\n#include \"src\/gpu\/vk\/GrVkTextureRenderTarget.h\"\n#include \"src\/gpu\/vk\/GrVkUtil.h\"\n\n#include \"include\/gpu\/vk\/GrVkTypes.h\"\n\n#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), GrBackendObjectOwnership::kOwned)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ We don't support creating external GrVkTextures\n SkASSERT(!info.fYcbcrConversionInfo.isValid() || !info.fYcbcrConversionInfo.fExternalFormat);\n this->registerWithCache(budgeted);\n if (GrVkFormatIsCompressed(info.fFormat)) {\n this->setReadOnly();\n }\n}\n\nGrVkTexture::GrVkTexture(GrVkGpu* gpu, SkISize dimensions, const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout, const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus, GrBackendObjectOwnership ownership,\n GrWrapCacheable cacheable, GrIOType ioType, bool isExternal)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), ownership)\n , INHERITED(gpu, dimensions, info.fProtected,\n isExternal ? GrTextureType::kExternal : GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n if (ioType == kRead_GrIOType) {\n this->setReadOnly();\n }\n this->registerWithCacheWrapped(cacheable);\n}\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus,\n GrBackendObjectOwnership ownership)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, layout, ownership)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ Since this ctor is only called from GrVkTextureRenderTarget, we can't have a ycbcr conversion\n \/\/ since we don't support that on render targets.\n SkASSERT(!info.fYcbcrConversionInfo.isValid());\n}\n\nsk_sp<GrVkTexture> GrVkTexture::MakeNewTexture(GrVkGpu* gpu, SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImage::ImageDesc& imageDesc,\n GrMipMapsStatus mipMapsStatus) {\n SkASSERT(imageDesc.fUsageFlags & VK_IMAGE_USAGE_SAMPLED_BIT);\n\n GrVkImageInfo info;\n if (!GrVkImage::InitImageInfo(gpu, imageDesc, &info)) {\n return nullptr;\n }\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n GrVkImage::DestroyImageInfo(gpu, &info);\n return nullptr;\n }\n sk_sp<GrVkImageLayout> layout(new GrVkImageLayout(info.fImageLayout));\n\n return sk_sp<GrVkTexture>(new GrVkTexture(gpu, budgeted, dimensions, info, std::move(layout),\n imageView, mipMapsStatus));\n}\n\nsk_sp<GrVkTexture> GrVkTexture::MakeWrappedTexture(GrVkGpu* gpu,\n SkISize dimensions,\n GrWrapOwnership wrapOwnership,\n GrWrapCacheable cacheable,\n GrIOType ioType,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout) {\n \/\/ Adopted textures require both image and allocation because we're responsible for freeing\n SkASSERT(VK_NULL_HANDLE != info.fImage &&\n (kBorrow_GrWrapOwnership == wrapOwnership || VK_NULL_HANDLE != info.fAlloc.fMemory));\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n return nullptr;\n }\n\n GrMipMapsStatus mipMapsStatus = info.fLevelCount > 1 ? GrMipMapsStatus::kValid\n : GrMipMapsStatus::kNotAllocated;\n\n GrBackendObjectOwnership ownership = kBorrow_GrWrapOwnership == wrapOwnership\n ? GrBackendObjectOwnership::kBorrowed : GrBackendObjectOwnership::kOwned;\n bool isExternal = info.fYcbcrConversionInfo.isValid() &&\n (info.fYcbcrConversionInfo.fExternalFormat != 0);\n return sk_sp<GrVkTexture>(new GrVkTexture(gpu, dimensions, info, std::move(layout), imageView,\n mipMapsStatus, ownership, cacheable, ioType,\n isExternal));\n}\n\nGrVkTexture::~GrVkTexture() {\n \/\/ either release or abandon should have been called by the owner of this object.\n SkASSERT(!fTextureView);\n}\n\nvoid GrVkTexture::onRelease() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n\n INHERITED::onRelease();\n}\n\nstruct GrVkTexture::DescriptorCacheEntry {\n DescriptorCacheEntry(const GrVkDescriptorSet* fDescSet, GrVkGpu* gpu)\n : fDescriptorSet(fDescSet), fGpu(gpu) {}\n ~DescriptorCacheEntry() {\n if (fDescriptorSet) {\n fDescriptorSet->recycle(fGpu);\n }\n }\n\n const GrVkDescriptorSet* fDescriptorSet;\n GrVkGpu* fGpu;\n};\n\nvoid GrVkTexture::onAbandon() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n INHERITED::onAbandon();\n}\n\nGrBackendTexture GrVkTexture::getBackendTexture() const {\n return GrBackendTexture(this->width(), this->height(), fInfo, this->grVkImageLayout());\n}\n\nGrVkGpu* GrVkTexture::getVkGpu() const {\n SkASSERT(!this->wasDestroyed());\n return static_cast<GrVkGpu*>(this->getGpu());\n}\n\nconst GrVkImageView* GrVkTexture::textureView() {\n return fTextureView;\n}\n\nvoid GrVkTexture::addIdleProc(sk_sp<GrRefCntedCallback> idleProc, IdleState type) {\n INHERITED::addIdleProc(idleProc, type);\n if (type == IdleState::kFinished) {\n if (auto* resource = this->resource()) {\n resource->addIdleProc(this, std::move(idleProc));\n }\n }\n}\n\nvoid GrVkTexture::callIdleProcsOnBehalfOfResource() {\n \/\/ If we got here then the resource is being removed from its last command buffer and the\n \/\/ texture is idle in the cache. Any kFlush idle procs should already have been called. So\n \/\/ the texture and resource should have the same set of procs.\n SkASSERT(this->resource());\n SkASSERT(this->resource()->idleProcCnt() == fIdleProcs.count());\n#ifdef SK_DEBUG\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n SkASSERT(fIdleProcs[i] == this->resource()->idleProc(i));\n }\n#endif\n fIdleProcs.reset();\n this->resource()->resetIdleProcs();\n}\n\nvoid GrVkTexture::willRemoveLastRef() {\n if (!fIdleProcs.count()) {\n return;\n }\n \/\/ This is called when the GrTexture is purgeable. However, we need to check whether the\n \/\/ Resource is still owned by any command buffers. If it is then it will call the proc.\n auto* resource = this->hasResource() ? this->resource() : nullptr;\n bool callFinishProcs = !resource || !resource->isOwnedByCommandBuffer();\n if (callFinishProcs) {\n \/\/ Everything must go!\n fIdleProcs.reset();\n resource->resetIdleProcs();\n } else {\n \/\/ The procs that should be called on flush but not finish are those that are owned\n \/\/ by the GrVkTexture and not the Resource. We do this by copying the resource's array\n \/\/ and thereby dropping refs to procs we own but the resource does not.\n SkASSERT(resource);\n fIdleProcs.reset(resource->idleProcCnt());\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n fIdleProcs[i] = resource->idleProc(i);\n }\n }\n}\n\nvoid GrVkTexture::removeFinishIdleProcs() {\n \/\/ This should only be called by onRelease\/onAbandon when we have already checked for a\n \/\/ resource.\n const auto* resource = this->resource();\n SkASSERT(resource);\n SkSTArray<4, sk_sp<GrRefCntedCallback>> procsToKeep;\n int resourceIdx = 0;\n \/\/ The idle procs that are common between the GrVkTexture and its Resource should be found in\n \/\/ the same order.\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n if (fIdleProcs[i] == resource->idleProc(resourceIdx)) {\n ++resourceIdx;\n } else {\n procsToKeep.push_back(fIdleProcs[i]);\n }\n }\n SkASSERT(resourceIdx == resource->idleProcCnt());\n fIdleProcs = procsToKeep;\n}\n\nconst GrVkDescriptorSet* GrVkTexture::cachedSingleDescSet(GrSamplerState state) {\n if (std::unique_ptr<DescriptorCacheEntry>* e = fDescSetCache.find(state)) {\n return (*e)->fDescriptorSet;\n }\n return nullptr;\n}\n\nvoid GrVkTexture::addDescriptorSetToCache(const GrVkDescriptorSet* descSet, GrSamplerState state) {\n SkASSERT(!fDescSetCache.find(state));\n descSet->ref();\n fDescSetCache.insert(state,\n std::unique_ptr<DescriptorCacheEntry>(\n new DescriptorCacheEntry(descSet, this->getVkGpu())));\n}\n<commit_msg>Avoid possible nullptr dereference am: e26a98217e am: f6cc75d713<commit_after>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/vk\/GrVkTexture.h\"\n\n#include \"src\/gpu\/GrTexturePriv.h\"\n#include \"src\/gpu\/vk\/GrVkDescriptorSet.h\"\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#include \"src\/gpu\/vk\/GrVkImageView.h\"\n#include \"src\/gpu\/vk\/GrVkTextureRenderTarget.h\"\n#include \"src\/gpu\/vk\/GrVkUtil.h\"\n\n#include \"include\/gpu\/vk\/GrVkTypes.h\"\n\n#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), GrBackendObjectOwnership::kOwned)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ We don't support creating external GrVkTextures\n SkASSERT(!info.fYcbcrConversionInfo.isValid() || !info.fYcbcrConversionInfo.fExternalFormat);\n this->registerWithCache(budgeted);\n if (GrVkFormatIsCompressed(info.fFormat)) {\n this->setReadOnly();\n }\n}\n\nGrVkTexture::GrVkTexture(GrVkGpu* gpu, SkISize dimensions, const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout, const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus, GrBackendObjectOwnership ownership,\n GrWrapCacheable cacheable, GrIOType ioType, bool isExternal)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), ownership)\n , INHERITED(gpu, dimensions, info.fProtected,\n isExternal ? GrTextureType::kExternal : GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n if (ioType == kRead_GrIOType) {\n this->setReadOnly();\n }\n this->registerWithCacheWrapped(cacheable);\n}\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus,\n GrBackendObjectOwnership ownership)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, layout, ownership)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ Since this ctor is only called from GrVkTextureRenderTarget, we can't have a ycbcr conversion\n \/\/ since we don't support that on render targets.\n SkASSERT(!info.fYcbcrConversionInfo.isValid());\n}\n\nsk_sp<GrVkTexture> GrVkTexture::MakeNewTexture(GrVkGpu* gpu, SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImage::ImageDesc& imageDesc,\n GrMipMapsStatus mipMapsStatus) {\n SkASSERT(imageDesc.fUsageFlags & VK_IMAGE_USAGE_SAMPLED_BIT);\n\n GrVkImageInfo info;\n if (!GrVkImage::InitImageInfo(gpu, imageDesc, &info)) {\n return nullptr;\n }\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n GrVkImage::DestroyImageInfo(gpu, &info);\n return nullptr;\n }\n sk_sp<GrVkImageLayout> layout(new GrVkImageLayout(info.fImageLayout));\n\n return sk_sp<GrVkTexture>(new GrVkTexture(gpu, budgeted, dimensions, info, std::move(layout),\n imageView, mipMapsStatus));\n}\n\nsk_sp<GrVkTexture> GrVkTexture::MakeWrappedTexture(GrVkGpu* gpu,\n SkISize dimensions,\n GrWrapOwnership wrapOwnership,\n GrWrapCacheable cacheable,\n GrIOType ioType,\n const GrVkImageInfo& info,\n sk_sp<GrVkImageLayout> layout) {\n \/\/ Adopted textures require both image and allocation because we're responsible for freeing\n SkASSERT(VK_NULL_HANDLE != info.fImage &&\n (kBorrow_GrWrapOwnership == wrapOwnership || VK_NULL_HANDLE != info.fAlloc.fMemory));\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n return nullptr;\n }\n\n GrMipMapsStatus mipMapsStatus = info.fLevelCount > 1 ? GrMipMapsStatus::kValid\n : GrMipMapsStatus::kNotAllocated;\n\n GrBackendObjectOwnership ownership = kBorrow_GrWrapOwnership == wrapOwnership\n ? GrBackendObjectOwnership::kBorrowed : GrBackendObjectOwnership::kOwned;\n bool isExternal = info.fYcbcrConversionInfo.isValid() &&\n (info.fYcbcrConversionInfo.fExternalFormat != 0);\n return sk_sp<GrVkTexture>(new GrVkTexture(gpu, dimensions, info, std::move(layout), imageView,\n mipMapsStatus, ownership, cacheable, ioType,\n isExternal));\n}\n\nGrVkTexture::~GrVkTexture() {\n \/\/ either release or abandon should have been called by the owner of this object.\n SkASSERT(!fTextureView);\n}\n\nvoid GrVkTexture::onRelease() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n\n INHERITED::onRelease();\n}\n\nstruct GrVkTexture::DescriptorCacheEntry {\n DescriptorCacheEntry(const GrVkDescriptorSet* fDescSet, GrVkGpu* gpu)\n : fDescriptorSet(fDescSet), fGpu(gpu) {}\n ~DescriptorCacheEntry() {\n if (fDescriptorSet) {\n fDescriptorSet->recycle(fGpu);\n }\n }\n\n const GrVkDescriptorSet* fDescriptorSet;\n GrVkGpu* fGpu;\n};\n\nvoid GrVkTexture::onAbandon() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n INHERITED::onAbandon();\n}\n\nGrBackendTexture GrVkTexture::getBackendTexture() const {\n return GrBackendTexture(this->width(), this->height(), fInfo, this->grVkImageLayout());\n}\n\nGrVkGpu* GrVkTexture::getVkGpu() const {\n SkASSERT(!this->wasDestroyed());\n return static_cast<GrVkGpu*>(this->getGpu());\n}\n\nconst GrVkImageView* GrVkTexture::textureView() {\n return fTextureView;\n}\n\nvoid GrVkTexture::addIdleProc(sk_sp<GrRefCntedCallback> idleProc, IdleState type) {\n INHERITED::addIdleProc(idleProc, type);\n if (type == IdleState::kFinished) {\n if (auto* resource = this->resource()) {\n resource->addIdleProc(this, std::move(idleProc));\n }\n }\n}\n\nvoid GrVkTexture::callIdleProcsOnBehalfOfResource() {\n \/\/ If we got here then the resource is being removed from its last command buffer and the\n \/\/ texture is idle in the cache. Any kFlush idle procs should already have been called. So\n \/\/ the texture and resource should have the same set of procs.\n SkASSERT(this->resource());\n SkASSERT(this->resource()->idleProcCnt() == fIdleProcs.count());\n#ifdef SK_DEBUG\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n SkASSERT(fIdleProcs[i] == this->resource()->idleProc(i));\n }\n#endif\n fIdleProcs.reset();\n this->resource()->resetIdleProcs();\n}\n\nvoid GrVkTexture::willRemoveLastRef() {\n if (!fIdleProcs.count()) {\n return;\n }\n \/\/ This is called when the GrTexture is purgeable. However, we need to check whether the\n \/\/ Resource is still owned by any command buffers. If it is then it will call the proc.\n auto* resource = this->hasResource() ? this->resource() : nullptr;\n bool callFinishProcs = !resource || !resource->isOwnedByCommandBuffer();\n if (callFinishProcs) {\n \/\/ Everything must go!\n fIdleProcs.reset();\n if (resource) {\n resource->resetIdleProcs();\n }\n } else {\n \/\/ The procs that should be called on flush but not finish are those that are owned\n \/\/ by the GrVkTexture and not the Resource. We do this by copying the resource's array\n \/\/ and thereby dropping refs to procs we own but the resource does not.\n SkASSERT(resource);\n fIdleProcs.reset(resource->idleProcCnt());\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n fIdleProcs[i] = resource->idleProc(i);\n }\n }\n}\n\nvoid GrVkTexture::removeFinishIdleProcs() {\n \/\/ This should only be called by onRelease\/onAbandon when we have already checked for a\n \/\/ resource.\n const auto* resource = this->resource();\n SkASSERT(resource);\n SkSTArray<4, sk_sp<GrRefCntedCallback>> procsToKeep;\n int resourceIdx = 0;\n \/\/ The idle procs that are common between the GrVkTexture and its Resource should be found in\n \/\/ the same order.\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n if (fIdleProcs[i] == resource->idleProc(resourceIdx)) {\n ++resourceIdx;\n } else {\n procsToKeep.push_back(fIdleProcs[i]);\n }\n }\n SkASSERT(resourceIdx == resource->idleProcCnt());\n fIdleProcs = procsToKeep;\n}\n\nconst GrVkDescriptorSet* GrVkTexture::cachedSingleDescSet(GrSamplerState state) {\n if (std::unique_ptr<DescriptorCacheEntry>* e = fDescSetCache.find(state)) {\n return (*e)->fDescriptorSet;\n }\n return nullptr;\n}\n\nvoid GrVkTexture::addDescriptorSetToCache(const GrVkDescriptorSet* descSet, GrSamplerState state) {\n SkASSERT(!fDescSetCache.find(state));\n descSet->ref();\n fDescSetCache.insert(state,\n std::unique_ptr<DescriptorCacheEntry>(\n new DescriptorCacheEntry(descSet, this->getVkGpu())));\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file gsDofMapper.h\n\n @brief Provides the gsDofMapper class for re-indexing DoFs.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n*\/\n\n#include <gsCore\/gsDofMapper.h>\n\n\nnamespace gismo \n{\n\ngsDofMapper::gsDofMapper() : \nm_shift(0), m_numFreeDofs(0), m_curElimId(-1), m_curCouplingId(1)\n{ \n m_offset.resize(1,0);\n}\n\n\nvoid gsDofMapper::localToGlobal(const gsMatrix<unsigned>& locals,\n index_t patchIndex,\n gsMatrix<unsigned>& globals) const\n{\n GISMO_ASSERT( locals.cols() == 1, \"localToGlobal: Expecting one column of locals\");\n const index_t numActive = locals.rows();\n \n globals.resize(numActive,1);\n \n for (index_t i = 0; i < numActive; ++i)\n globals(i,0) = MAPPER_PATCH_DOF(locals(i,0), patchIndex)+m_shift;\n}\n\n\/\/ This function can not have enough information to do its job if dim>2\n\/\/ GISMO_DEPRECATED\nvoid gsDofMapper::matchInterface( index_t k1, index_t k2,\n const gsMatrix<unsigned> & b1,\n const gsMatrix<unsigned> & b2,\n const gsVector<bool> &orient )\n{\n \/\/ Boundaries must be conforming (matching)\n const index_t sz = b1.size();\n if ( sz != b2.size() )\n {\n gsWarn<<\"gsDofMapper: Problem: non-conforming interface \"<<\n \"(\" <<k1<<\",\"<< \/\/i.first().side<<\n \")<->(\"<<k2<<\",\"<< \/\/i.second().side<<\n \") ~ (\"<<sz<<\",\"<<b2.size() <<\").\\n\";\n\n gsWarn<< b1.transpose() << \"\\n\";\n gsWarn<< b2.transpose() << \"\\n\";\n\n GISMO_ERROR( \"Non-conforming boundaries.\\n\" );\n }\n\n if( orient.size() )\n {\n if ( orient[0] == true ) \/\/ assumes 1D side\n {\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(k,0) );\n }\n else\n {\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(sz-k-1,0) );\n }\n }\n else\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(k,0) );\n}\n\nvoid gsDofMapper::colapseDofs(index_t k, const gsMatrix<unsigned> & b )\n{\n const index_t last = b.size()-1;\n for ( index_t k=0; k<last; ++k)\n {\n this->matchDof( k, b(k,0), k, b(k+1,0) );\n }\n}\n\n\n\n\n\nvoid gsDofMapper::matchDof( index_t u, index_t i, index_t v, index_t j )\n{\n index_t d1 = MAPPER_PATCH_DOF(i,u);\n index_t d2 = MAPPER_PATCH_DOF(j,v);\n\n \/\/ make sure that d1 <= d2, simplifies implementation\n if (d1 > d2)\n {\n std::swap(d1, d2);\n std::swap(u, v);\n std::swap(i, j);\n }\n\n if (d1 < 0) \/\/ first dof is eliminated\n {\n if (d2 < 0) mergeDofsGlobally( d1, d2 ); \/\/ both are eliminated, merge their indices\n else if (d2 == 0) MAPPER_PATCH_DOF(j,v) = d1; \/\/ second is free, eliminate it along with first\n else \/* d2 > 0*\/ replaceDofGlobally( d2, d1 ); \/\/ second is coupling, eliminate all instances of it\n }\n else if (d1 == 0) \/\/ first dof is a free dof\n {\n if (d2 == 0) MAPPER_PATCH_DOF(i,u) = MAPPER_PATCH_DOF(j,v) = m_curCouplingId++; \/\/ both are free, assign them a new coupling id\n else if (d2 > 0) MAPPER_PATCH_DOF(i,u) = d2; \/\/ second is coupling, add first to the same coupling group\n else GISMO_ERROR(\"Something went terribly wrong\");\n }\n else \/* d1 > 0 *\/ \/\/ first dof is a coupling dof\n {\n GISMO_ASSERT(d2 > 0, \"Something went terribly wrong\");\n mergeDofsGlobally( d1, d2 ); \/\/ both are coupling dofs, merge them\n }\n\n \/\/ if we merged two different non-eliminated dofs, we lost one free dof\n if ( (d1 != d2 && (d1 >= 0 || d2 >= 0) ) || (d1 == 0 && d2 == 0) )\n --m_numFreeDofs;\n}\n\n\nvoid gsDofMapper::markBoundary( index_t k, const gsMatrix<unsigned> & boundaryDofs )\n{\n for (index_t i = 0; i < boundaryDofs.rows(); ++i)\n {\n eliminateDof( boundaryDofs(i,0), k );\n }\n\n \/\/ TO DO: save inverse, eg boundaryDofs(i,0)\n}\n\nvoid gsDofMapper::eliminateDof( index_t i, index_t k )\n{\n const index_t old = MAPPER_PATCH_DOF(i,k);\n if (old == 0) \/\/ regular free dof\n {\n --m_numFreeDofs;\n MAPPER_PATCH_DOF(i,k) = m_curElimId--;\n }\n else if (old > 0) \/\/ coupling dof\n {\n --m_numFreeDofs;\n replaceDofGlobally( old, m_curElimId-- );\n }\n \/\/ else: old < 0: already an eliminated dof, nothing to do\n}\n\nvoid gsDofMapper::finalize()\n{\n GISMO_ASSERT(m_curElimId!=0, \"Error in gsDofMapper::finalize() called twince.\");\n \n index_t curFreeDof = 0; \/\/ free dofs start at 0\n index_t curElimDof = m_numFreeDofs; \/\/ eliminated dofs start after free dofs\n std::vector<index_t> couplingDofs(m_curCouplingId - 1, -1);\n std::vector<index_t> elimDofs(-m_curElimId - 1, -1);\n\n \/\/ Coupled dofs start after standard dofs\n index_t curCplDof = m_numFreeDofs - couplingDofs.size();\n\n for (std::size_t k = 0; k < m_dofs.size(); ++k)\n {\n const index_t dofType = m_dofs[k];\n\n if (dofType == 0) \/\/ standard dof\n m_dofs[k] = curFreeDof++;\n else if (dofType < 0) \/\/ eliminated dof\n {\n const index_t id = -dofType - 1;\n if (elimDofs[id] < 0)\n elimDofs[id] = curElimDof++;\n m_dofs[k] = elimDofs[id];\n }\n else \/\/ dofType > 0 \/\/ coupling dof\n {\n const index_t id = dofType - 1;\n if (couplingDofs[id] < 0)\n \/\/couplingDofs[id] = curFreeDof++;\n couplingDofs[id] = curCplDof++;\n m_dofs[k] = couplingDofs[id];\n }\n }\n m_numElimDofs = curElimDof - m_numFreeDofs;\n\n GISMO_ASSERT(curCplDof == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of coupling dofs does not match allocated number\");\n GISMO_ASSERT(curFreeDof + static_cast<index_t>(couplingDofs.size()) == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of free dofs does not match allocated number\");\n\n m_curElimId = 0;\/\/ Only equal to zero after finalize is called.\n\n}\n\nvoid gsDofMapper::print() const\n{\n gsInfo<<\"Dofs: \"<< this->size() <<\"\\n\";\n gsInfo<<\" free: \"<< this->freeSize() <<\"\\n\";\n gsInfo<<\" elim: \"<< this->boundarySize() <<\"\\n\";\n}\n\n\n\nvoid gsDofMapper::setIdentity(index_t nPatches, size_t nDofs)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n m_numFreeDofs = nDofs;\n\n \/\/ Initialize all offsets to zero\n m_offset.resize(nPatches, 0);\n\n m_dofs.resize( m_numFreeDofs, 0);\n\n finalize();\n}\n\nvoid gsDofMapper::initPatchDofs(const gsVector<index_t> & patchDofSizes)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n\n const size_t nPatches = patchDofSizes.size();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n {\n m_offset.push_back( m_offset.back() + patchDofSizes[k-1] );\n }\n\n m_numFreeDofs = m_offset.back() + patchDofSizes[nPatches-1];\n\n m_dofs.resize( m_numFreeDofs, 0);\n}\n\n\n\nvoid gsDofMapper::replaceDofGlobally(index_t oldIdx, index_t newIdx)\n{\n std::replace( m_dofs.begin(), m_dofs.end(), oldIdx, newIdx );\n}\n\nvoid gsDofMapper::mergeDofsGlobally(index_t dof1, index_t dof2)\n{\n if (dof1 != dof2)\n {\n \/\/ replace the larger by the smaller for more consistent numbering.\n if (dof1 < dof2)\n std::swap(dof1, dof2);\n\n replaceDofGlobally(dof1, dof2);\n }\n}\n\n\nindex_t gsDofMapper::coupledSize() const\n{ \n \/\/ Property: coupled (eliminated or not) DoFs appear more than once in the mapping.\n GISMO_ENSURE(m_curElimId==0, \"finalize() was not called on gsDofMapper\");\n \n std::vector<index_t> CountMap(m_numFreeDofs,0);\n \n \/\/ Count number of appearances of each free DoF\n for (std::vector<index_t>::const_iterator it = m_dofs.begin(); it != m_dofs.end(); ++it)\n if ( *it < m_numFreeDofs )\n CountMap[*it]++;\n \n \/\/ Count the number of freeDoFs that appear more than once\n return std::count_if( CountMap.begin(), CountMap.end(), std::bind1st(std::greater<index_t>(), 1) );\n \/* \/\/ Equivalent implementation\n index_t count = 0;\n for (std::vector<index_t>::const_iterator it = CountMap.begin(); it != CountMap.end(); ++it)\n if ( *it > 1 )\n count++;\n return count; \n *\/\n}\n\n\nvoid gsDofMapper::setShift (index_t shift)\n{\n m_shift=shift;\n}\n\n} \/\/ namespace gismo\n\n\n<commit_msg>small fix<commit_after>\/** @file gsDofMapper.h\n\n @brief Provides the gsDofMapper class for re-indexing DoFs.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n*\/\n\n#include <gsCore\/gsDofMapper.h>\n\n\nnamespace gismo \n{\n\ngsDofMapper::gsDofMapper() : \nm_shift(0), m_numFreeDofs(0), m_curElimId(-1), m_curCouplingId(1)\n{ \n m_offset.resize(1,0);\n}\n\n\nvoid gsDofMapper::localToGlobal(const gsMatrix<unsigned>& locals,\n index_t patchIndex,\n gsMatrix<unsigned>& globals) const\n{\n GISMO_ASSERT( locals.cols() == 1, \"localToGlobal: Expecting one column of locals\");\n const index_t numActive = locals.rows();\n \n globals.resize(numActive,1);\n \n for (index_t i = 0; i < numActive; ++i)\n globals(i,0) = MAPPER_PATCH_DOF(locals(i,0), patchIndex)+m_shift;\n}\n\n\/\/ This function can not have enough information to do its job if dim>2\n\/\/ GISMO_DEPRECATED\nvoid gsDofMapper::matchInterface( index_t k1, index_t k2,\n const gsMatrix<unsigned> & b1,\n const gsMatrix<unsigned> & b2,\n const gsVector<bool> &orient )\n{\n \/\/ Boundaries must be conforming (matching)\n const index_t sz = b1.size();\n if ( sz != b2.size() )\n {\n gsWarn<<\"gsDofMapper: Problem: non-conforming interface \"<<\n \"(\" <<k1<<\",\"<< \/\/i.first().side<<\n \")<->(\"<<k2<<\",\"<< \/\/i.second().side<<\n \") ~ (\"<<sz<<\",\"<<b2.size() <<\").\\n\";\n\n gsWarn<< b1.transpose() << \"\\n\";\n gsWarn<< b2.transpose() << \"\\n\";\n\n GISMO_ERROR( \"Non-conforming boundaries.\\n\" );\n }\n\n if( orient.size() )\n {\n if ( orient[0] == true ) \/\/ assumes 1D side\n {\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(k,0) );\n }\n else\n {\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(sz-k-1,0) );\n }\n }\n else\n for ( index_t k=0; k<sz; ++k)\n this->matchDof( k1, b1(k,0), k2, b2(k,0) );\n}\n\nvoid gsDofMapper::colapseDofs(index_t k, const gsMatrix<unsigned> & b )\n{\n const index_t last = b.size()-1;\n for ( index_t k=0; k<last; ++k)\n {\n this->matchDof( k, b(k,0), k, b(k+1,0) );\n }\n}\n\n\n\n\n\nvoid gsDofMapper::matchDof( index_t u, index_t i, index_t v, index_t j )\n{\n index_t d1 = MAPPER_PATCH_DOF(i,u);\n index_t d2 = MAPPER_PATCH_DOF(j,v);\n\n \/\/ make sure that d1 <= d2, simplifies implementation\n if (d1 > d2)\n {\n std::swap(d1, d2);\n std::swap(u, v);\n std::swap(i, j);\n }\n\n if (d1 < 0) \/\/ first dof is eliminated\n {\n if (d2 < 0) mergeDofsGlobally( d1, d2 ); \/\/ both are eliminated, merge their indices\n else if (d2 == 0) MAPPER_PATCH_DOF(j,v) = d1; \/\/ second is free, eliminate it along with first\n else \/* d2 > 0*\/ replaceDofGlobally( d2, d1 ); \/\/ second is coupling, eliminate all instances of it\n }\n else if (d1 == 0) \/\/ first dof is a free dof\n {\n if (d2 == 0) MAPPER_PATCH_DOF(i,u) = MAPPER_PATCH_DOF(j,v) = m_curCouplingId++; \/\/ both are free, assign them a new coupling id\n else if (d2 > 0) MAPPER_PATCH_DOF(i,u) = d2; \/\/ second is coupling, add first to the same coupling group\n else GISMO_ERROR(\"Something went terribly wrong\");\n }\n else \/* d1 > 0 *\/ \/\/ first dof is a coupling dof\n {\n GISMO_ASSERT(d2 > 0, \"Something went terribly wrong\");\n mergeDofsGlobally( d1, d2 ); \/\/ both are coupling dofs, merge them\n }\n\n \/\/ if we merged two different non-eliminated dofs, we lost one free dof\n if ( (d1 != d2 && (d1 >= 0 || d2 >= 0) ) || (d1 == 0 && d2 == 0) )\n --m_numFreeDofs;\n}\n\n\nvoid gsDofMapper::markBoundary( index_t k, const gsMatrix<unsigned> & boundaryDofs )\n{\n for (index_t i = 0; i < boundaryDofs.rows(); ++i)\n {\n eliminateDof( boundaryDofs(i,0), k );\n }\n\n \/\/ TO DO: save inverse, eg boundaryDofs(i,0)\n}\n\nvoid gsDofMapper::eliminateDof( index_t i, index_t k )\n{\n const index_t old = MAPPER_PATCH_DOF(i,k);\n if (old == 0) \/\/ regular free dof\n {\n --m_numFreeDofs;\n MAPPER_PATCH_DOF(i,k) = m_curElimId--;\n }\n else if (old > 0) \/\/ coupling dof\n {\n --m_numFreeDofs;\n replaceDofGlobally( old, m_curElimId-- );\n }\n \/\/ else: old < 0: already an eliminated dof, nothing to do\n}\n\nvoid gsDofMapper::finalize()\n{\n GISMO_ASSERT(m_curElimId!=0, \"Error in gsDofMapper::finalize() called twince.\");\n \n index_t curFreeDof = 0; \/\/ free dofs start at 0\n index_t curElimDof = m_numFreeDofs; \/\/ eliminated dofs start after free dofs\n std::vector<index_t> couplingDofs(m_curCouplingId - 1, -1);\n std::vector<index_t> elimDofs(-m_curElimId - 1, -1);\n\n \/\/ Coupled dofs start after standard dofs\n index_t curCplDof = m_numFreeDofs - couplingDofs.size();\n\n for (std::size_t k = 0; k < m_dofs.size(); ++k)\n {\n const index_t dofType = m_dofs[k];\n\n if (dofType == 0) \/\/ standard dof\n m_dofs[k] = curFreeDof++;\n else if (dofType < 0) \/\/ eliminated dof\n {\n const index_t id = -dofType - 1;\n if (elimDofs[id] < 0)\n elimDofs[id] = curElimDof++;\n m_dofs[k] = elimDofs[id];\n }\n else \/\/ dofType > 0 \/\/ coupling dof\n {\n const index_t id = dofType - 1;\n if (couplingDofs[id] < 0)\n \/\/couplingDofs[id] = curFreeDof++;\n couplingDofs[id] = curCplDof++;\n m_dofs[k] = couplingDofs[id];\n }\n }\n m_numElimDofs = curElimDof - m_numFreeDofs;\n\n GISMO_ASSERT(curCplDof == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of coupling dofs does not match allocated number\");\n GISMO_ASSERT(curFreeDof + static_cast<index_t>(couplingDofs.size()) == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of free dofs does not match allocated number\");\n\n m_curElimId = 0;\/\/ Only equal to zero after finalize is called.\n\n}\n\nvoid gsDofMapper::print() const\n{\n gsInfo<<\"Dofs: \"<< this->size() <<\"\\n\";\n gsInfo<<\" free: \"<< this->freeSize() <<\"\\n\";\n gsInfo<<\" elim: \"<< this->boundarySize() <<\"\\n\";\n}\n\n\n\nvoid gsDofMapper::setIdentity(index_t nPatches, size_t nDofs)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n m_numFreeDofs = nDofs;\n\n \/\/ Initialize all offsets to zero\n m_offset.resize(nPatches, 0);\n\n m_dofs.resize( m_numFreeDofs, 0);\n\n finalize();\n}\n\nvoid gsDofMapper::initPatchDofs(const gsVector<index_t> & patchDofSizes)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n\n const size_t nPatches = patchDofSizes.size();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n {\n m_offset.push_back( m_offset.back() + patchDofSizes[k-1] );\n }\n\n m_numFreeDofs = m_offset.back() + patchDofSizes[nPatches-1];\n\n m_dofs.resize( m_numFreeDofs, 0);\n}\n\n\n\nvoid gsDofMapper::replaceDofGlobally(index_t oldIdx, index_t newIdx)\n{\n std::replace( m_dofs.begin(), m_dofs.end(), oldIdx, newIdx );\n}\n\nvoid gsDofMapper::mergeDofsGlobally(index_t dof1, index_t dof2)\n{\n if (dof1 != dof2)\n {\n \/\/ replace the larger by the smaller for more consistent numbering.\n if (dof1 < dof2)\n std::swap(dof1, dof2);\n\n replaceDofGlobally(dof1, dof2);\n }\n}\n\n\nindex_t gsDofMapper::coupledSize() const\n{ \n \/\/ Property: coupled (eliminated or not) DoFs appear more than once in the mapping.\n GISMO_ENSURE(m_curElimId==0, \"finalize() was not called on gsDofMapper\");\n \n std::vector<index_t> CountMap(m_numFreeDofs,0);\n \n \/\/ Count number of appearances of each free DoF\n for (std::vector<index_t>::const_iterator it = m_dofs.begin(); it != m_dofs.end(); ++it)\n if ( *it < m_numFreeDofs )\n CountMap[*it]++;\n \n \/\/ Count the number of freeDoFs that appear more than once\n return std::count_if( CountMap.begin(), CountMap.end(), std::bind2nd(std::greater<index_t>(), 1) );\n \/* \/\/ Equivalent implementation\n index_t count = 0;\n for (std::vector<index_t>::const_iterator it = CountMap.begin(); it != CountMap.end(); ++it)\n if ( *it > 1 )\n count++;\n return count; \n *\/\n}\n\n\nvoid gsDofMapper::setShift (index_t shift)\n{\n m_shift=shift;\n}\n\n} \/\/ namespace gismo\n\n\n<|endoftext|>"} {"text":"<commit_before>\/** @file gsFileManager.cpp\n\n @brief Utility class for finding files and handling paths\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): S. Takacs\n*\/\n\n#include <gsIO\/gsFileManager.h>\n#include <iostream>\n#include <fstream>\n#include <gsCore\/gsConfig.h>\n#include <gsUtils\/gsUtils.h> \n\nnamespace gismo\n{\n\nclass gsFileManagerData;\n\n\/\/ Use a singleton to store data:\nclass GISMO_EXPORT gsFileManagerData\n{\npublic:\n\n friend gsFileManagerData& gsFileManagerDataSingleton();\n friend class gsFileManager;\n\n void setSearchPaths(const std::string& paths);\n\nprivate:\n gsFileManagerData()\n {\n#ifdef GISMO_SEARCH_PATHS\n setSearchPaths(\"\" GISMO_SEARCH_PATHS);\n#endif\n }\n\n gsFileManagerData(const gsFileManagerData&);\n gsFileManagerData& operator= (const gsFileManagerData&);\n std::vector<std::string> m_paths;\n};\n\ngsFileManagerData& gsFileManagerDataSingleton()\n{\n static gsFileManagerData singleton;\n return singleton;\n}\n\n\nbool gsFileManager::fileExists(const std::string& name)\n{\n std::ifstream f(name.c_str());\n return f.good();\n}\n\nchar gsFileManager::getLocalPathSeperator()\n{\n#if defined _WIN32\n return '\\\\';\n#else\n return '\/';\n#endif\n}\n\nbool gsFileManager::isFullyQualified(const std::string& fn)\n{\n#if defined _WIN32\n return util::starts_with(fn,\"\/\")\n || util::starts_with(fn,\"\\\\\")\n || ( fn.size() > 2 && fn[1] == ':' && ( fn[2] == '\/' || fn[2] == '\\\\' ) );\n#else\n return util::starts_with(fn,\"\/\");\n#endif\n}\n\nbool gsFileManager::isRelative(const std::string& fn)\n{\n#if defined _WIN32\n return util::starts_with(fn,\".\/\")\n || util::starts_with(fn,\".\\\\\")\n || util::starts_with(fn,\"..\/\")\n || util::starts_with(fn,\"..\\\\\");\n#else\n return util::starts_with(fn,\".\/\")\n || util::starts_with(fn,\"..\/\");\n#endif\n}\n\nvoid _replace_slash_by_basckslash(std::string& str)\n{\n for ( std::string::iterator it=str.begin(); it!=str.end(); it++ )\n if ( *it=='\/' ) *it = '\\\\';\n}\n\nvoid gsFileManager::setSearchPaths(const std::string& paths)\n{\n gsFileManagerDataSingleton().setSearchPaths(paths);\n}\n\nvoid gsFileManagerData::setSearchPaths(const std::string& paths)\n{\n m_paths.clear();\n\n std::string::const_iterator a;\n std::string::const_iterator b = paths.begin();\n while (true)\n {\n a = b;\n while (b != paths.end() && (*b) != ';') { ++b; }\n\n std::string p(a,b);\n\n#if defined _WIN32\n _replace_slash_by_basckslash(p);\n#endif\n\n if (!p.empty())\n {\n#if defined _WIN32\n if (*p.rbegin() != '\\\\')\n p.push_back('\\\\');\n#else\n if (*p.rbegin() != '\/')\n p.push_back('\/');\n#endif\n\n m_paths.push_back(p);\n }\n\n if ( b == paths.end() ) break;\n\n ++b;\n }\n}\n\nstd::string gsFileManager::getSearchPaths()\n{\n std::string result;\n gsFileManagerData& dat = gsFileManagerDataSingleton();\n for (std::vector<std::string>::const_iterator it = dat.m_paths.begin();\n it < dat.m_paths.end(); ++it)\n {\n result += (*it) + \";\";\n }\n return result;\n}\n\nbool gsFileManager::find( std::string& fn )\n{\n#if defined _WIN32\n _replace_slash_by_basckslash(p);\n#endif\n\n if ( fileExists(fn) ) return true;\n\n if ( isFullyQualified(fn) || isRelative(fn) ) return false;\n\n gsFileManagerData& dat = gsFileManagerDataSingleton();\n\n for (std::vector<std::string>::const_iterator it = dat.m_paths.begin();\n it < dat.m_paths.end(); ++it)\n {\n const std::string tmp = (*it) + fn;\n if ( fileExists( tmp ) )\n {\n fn = tmp;\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/namespace gismo\n\n\n<commit_msg><commit_after>\/** @file gsFileManager.cpp\n\n @brief Utility class for finding files and handling paths\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): S. Takacs\n*\/\n\n#include <gsIO\/gsFileManager.h>\n#include <iostream>\n#include <fstream>\n#include <gsCore\/gsConfig.h>\n#include <gsUtils\/gsUtils.h> \n\nnamespace gismo\n{\n\nclass gsFileManagerData;\n\n\/\/ Use a singleton to store data:\nclass GISMO_EXPORT gsFileManagerData\n{\npublic:\n\n friend gsFileManagerData& gsFileManagerDataSingleton();\n friend class gsFileManager;\n\n void setSearchPaths(const std::string& paths);\n\nprivate:\n gsFileManagerData()\n {\n#ifdef GISMO_SEARCH_PATHS\n setSearchPaths(\"\" GISMO_SEARCH_PATHS);\n#endif\n }\n\n gsFileManagerData(const gsFileManagerData&);\n gsFileManagerData& operator= (const gsFileManagerData&);\n std::vector<std::string> m_paths;\n};\n\ngsFileManagerData& gsFileManagerDataSingleton()\n{\n static gsFileManagerData singleton;\n return singleton;\n}\n\n\nbool gsFileManager::fileExists(const std::string& name)\n{\n std::ifstream f(name.c_str());\n return f.good();\n}\n\nchar gsFileManager::getLocalPathSeperator()\n{\n#if defined _WIN32\n return '\\\\';\n#else\n return '\/';\n#endif\n}\n\nbool gsFileManager::isFullyQualified(const std::string& fn)\n{\n#if defined _WIN32\n return util::starts_with(fn,\"\/\")\n || util::starts_with(fn,\"\\\\\")\n || ( fn.size() > 2 && fn[1] == ':' && ( fn[2] == '\/' || fn[2] == '\\\\' ) );\n#else\n return util::starts_with(fn,\"\/\");\n#endif\n}\n\nbool gsFileManager::isRelative(const std::string& fn)\n{\n#if defined _WIN32\n return util::starts_with(fn,\".\/\")\n || util::starts_with(fn,\".\\\\\")\n || util::starts_with(fn,\"..\/\")\n || util::starts_with(fn,\"..\\\\\");\n#else\n return util::starts_with(fn,\".\/\")\n || util::starts_with(fn,\"..\/\");\n#endif\n}\n\nvoid _replace_slash_by_basckslash(std::string& str)\n{\n for ( std::string::iterator it=str.begin(); it!=str.end(); it++ )\n if ( *it=='\/' ) *it = '\\\\';\n}\n\nvoid gsFileManager::setSearchPaths(const std::string& paths)\n{\n gsFileManagerDataSingleton().setSearchPaths(paths);\n}\n\nvoid gsFileManagerData::setSearchPaths(const std::string& paths)\n{\n m_paths.clear();\n\n std::string::const_iterator a;\n std::string::const_iterator b = paths.begin();\n while (true)\n {\n a = b;\n while (b != paths.end() && (*b) != ';') { ++b; }\n\n std::string p(a,b);\n\n#if defined _WIN32\n _replace_slash_by_basckslash(p);\n#endif\n\n if (!p.empty())\n {\n#if defined _WIN32\n if (*p.rbegin() != '\\\\')\n p.push_back('\\\\');\n#else\n if (*p.rbegin() != '\/')\n p.push_back('\/');\n#endif\n\n m_paths.push_back(p);\n }\n\n if ( b == paths.end() ) break;\n\n ++b;\n }\n}\n\nstd::string gsFileManager::getSearchPaths()\n{\n std::string result;\n gsFileManagerData& dat = gsFileManagerDataSingleton();\n for (std::vector<std::string>::const_iterator it = dat.m_paths.begin();\n it < dat.m_paths.end(); ++it)\n {\n result += (*it) + \";\";\n }\n return result;\n}\n\nbool gsFileManager::find( std::string& fn )\n{\n#if defined _WIN32\n _replace_slash_by_basckslash(fn);\n#endif\n\n if ( fileExists(fn) ) return true;\n\n if ( isFullyQualified(fn) || isRelative(fn) ) return false;\n\n gsFileManagerData& dat = gsFileManagerDataSingleton();\n\n for (std::vector<std::string>::const_iterator it = dat.m_paths.begin();\n it < dat.m_paths.end(); ++it)\n {\n const std::string tmp = (*it) + fn;\n if ( fileExists( tmp ) )\n {\n fn = tmp;\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/namespace gismo\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-\n * vi: set shiftwidth=4 tabstop=8:\n * :indentSize=4:tabSize=8:\n *\/\n#include \"file_index.h\"\n#include \"error.h\"\n#include \"event.h\"\n#include <cassert>\n#include <sysexits.h>\n\nfile_index::file_index(const std::string& filename) :\n file_(filename),\n has_parsed_all_(false)\n{\n if (file_.empty()) {\n\tthrow error(\"could not memory map: \" + filename, EX_NOINPUT);\n }\n\n \/\/ we start counting lines with number 1. So add an invalid pointer to index 0.\n line_.push_back(line_t(nullptr, nullptr, nullptr, 0));\n}\n\nbool\nfile_index::parse_line(const line_number_t num_)\n{\n if (file_.empty()) {\n\thas_parsed_all_ = true;\n\treturn false;\n }\n\n if (num_ <= size()) {\n\treturn true;\n }\n\n line_number_t num = 0;\n const c_t* it = nullptr;\n if (num_ > 1 && size() > 0) {\n\tline_t current_line = line_[size()];\n\tit = current_line.next_;\n\tnum = current_line.num_;\n } else {\n\tit = file_.begin();\n }\n\n const c_t* const end = file_.end();\n if (it == end) {\n\treturn false;\n }\n if (it == nullptr) {\n\treturn false;\n }\n\n assert(it);\n const c_t* beg = it;\n while(num < num_) {\n\tif (*it == '\\n') {\n\t const c_t* next = it + 1;\n\t push_line(beg, it, next, ++num);\n\t beg = next;\n\t}\n\t++it;\n\tif (it == end) {\n\t if (it != beg) {\n\t\tpush_line(beg, it, nullptr, ++num);\n\t }\n\t has_parsed_all_ = true;\n\t break;\n\t}\n }\n\n return num == num_;\n}\n\nvoid\nfile_index::push_line(const c_t* beg, const c_t* end, const c_t* next, const line_number_t num)\n{\n while(beg < end) {\n\tif (*(end - 1) == '\\n') {\n\t --end;\n\t continue;\n\t}\n\tif (*(end - 1) == '\\r') {\n\t --end;\n\t continue;\n\t}\n\tbreak;\n }\n line_.push_back(line_t(beg, end, next, num));\n}\n\nline_t file_index::line(const line_number_t num)\n{\n if (num > size()) {\n\tif (! parse_line(num)) {\n\t throw std::runtime_error(\"file_index::line(\" + std::to_string(num) + \"): number too large, file only contains \" + std::to_string(size()));\n\t}\n }\n line_t l = line_[num];\n assert(l.num_ == num);\n return l;\n}\n\nlineNum_vector_t\nfile_index::lineNum_vector()\n{\n const line_number_t s = size();\n lineNum_vector_t v(s);\n for(line_number_t i = 0; i < s; ++i) {\n\tv[i] = i + 1;\n }\n return v;\n}\n\nvoid\nfile_index::parse_all(regex_index_vec_t& regex_index_vec, ProgressFunctor *func)\n{\n for(line_number_t num = 1; true; ++num) {\n\tif (num > size()) {\n\t if (! parse_line(num)) {\n\t\tbreak;\n\t }\n\t}\n\n\tconst line_t& line = line_[num];\n\tfor(auto ri : regex_index_vec) {\n\t ri->match(line);\n\t}\n\n\tif (func && (num % 10000) == 0) {\n\t const uint64_t pos = line.end_ - line_[1].beg_;\n\t func->progress(num, static_cast<unsigned>(pos * 100llu \/ file_.size()));\n\t}\n }\n}\n\nvoid\nfile_index::parse_all(std::shared_ptr<regex_index> ri, ProgressFunctor *func)\n{\n regex_index_vec_t v = { ri };\n parse_all(v, func);\n}\n\nvoid\nfile_index::parse_all()\n{\n regex_index_vec_t v;\n parse_all(v);\n}\n\nunsigned\nfile_index::perc(const line_number_t num)\n{\n const line_number_t s = size();\n if (num > s) { return 100u; }\n return static_cast<uint64_t>(num) * 100llu \/ s;\n}\n\nvoid\nfile_index::parse_all_in_background(std::shared_ptr<regex_index> ri) const\n{\n if (! has_parsed_all_) {\n\treturn;\n }\n for(unsigned i = 1; i < line_.size(); ++i) {\n\tri->match(line_[i]);\n\tif ((i % 10000) == 0) {\n\t eventAdd(event(\"matching line \" + std::to_string(i)));\n\t}\n }\n}\n<commit_msg>print percentage when matching filter regex<commit_after>\/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-\n * vi: set shiftwidth=4 tabstop=8:\n * :indentSize=4:tabSize=8:\n *\/\n#include \"file_index.h\"\n#include \"error.h\"\n#include \"event.h\"\n#include <cassert>\n#include <sysexits.h>\n\nfile_index::file_index(const std::string& filename) :\n file_(filename),\n has_parsed_all_(false)\n{\n if (file_.empty()) {\n\tthrow error(\"could not memory map: \" + filename, EX_NOINPUT);\n }\n\n \/\/ we start counting lines with number 1. So add an invalid pointer to index 0.\n line_.push_back(line_t(nullptr, nullptr, nullptr, 0));\n}\n\nbool\nfile_index::parse_line(const line_number_t num_)\n{\n if (file_.empty()) {\n\thas_parsed_all_ = true;\n\treturn false;\n }\n\n if (num_ <= size()) {\n\treturn true;\n }\n\n line_number_t num = 0;\n const c_t* it = nullptr;\n if (num_ > 1 && size() > 0) {\n\tline_t current_line = line_[size()];\n\tit = current_line.next_;\n\tnum = current_line.num_;\n } else {\n\tit = file_.begin();\n }\n\n const c_t* const end = file_.end();\n if (it == end) {\n\treturn false;\n }\n if (it == nullptr) {\n\treturn false;\n }\n\n assert(it);\n const c_t* beg = it;\n while(num < num_) {\n\tif (*it == '\\n') {\n\t const c_t* next = it + 1;\n\t push_line(beg, it, next, ++num);\n\t beg = next;\n\t}\n\t++it;\n\tif (it == end) {\n\t if (it != beg) {\n\t\tpush_line(beg, it, nullptr, ++num);\n\t }\n\t has_parsed_all_ = true;\n\t break;\n\t}\n }\n\n return num == num_;\n}\n\nvoid\nfile_index::push_line(const c_t* beg, const c_t* end, const c_t* next, const line_number_t num)\n{\n while(beg < end) {\n\tif (*(end - 1) == '\\n') {\n\t --end;\n\t continue;\n\t}\n\tif (*(end - 1) == '\\r') {\n\t --end;\n\t continue;\n\t}\n\tbreak;\n }\n line_.push_back(line_t(beg, end, next, num));\n}\n\nline_t file_index::line(const line_number_t num)\n{\n if (num > size()) {\n\tif (! parse_line(num)) {\n\t throw std::runtime_error(\"file_index::line(\" + std::to_string(num) + \"): number too large, file only contains \" + std::to_string(size()));\n\t}\n }\n line_t l = line_[num];\n assert(l.num_ == num);\n return l;\n}\n\nlineNum_vector_t\nfile_index::lineNum_vector()\n{\n const line_number_t s = size();\n lineNum_vector_t v(s);\n for(line_number_t i = 0; i < s; ++i) {\n\tv[i] = i + 1;\n }\n return v;\n}\n\nvoid\nfile_index::parse_all(regex_index_vec_t& regex_index_vec, ProgressFunctor *func)\n{\n for(line_number_t num = 1; true; ++num) {\n\tif (num > size()) {\n\t if (! parse_line(num)) {\n\t\tbreak;\n\t }\n\t}\n\n\tconst line_t& line = line_[num];\n\tfor(auto ri : regex_index_vec) {\n\t ri->match(line);\n\t}\n\n\tif (func && (num % 10000) == 0) {\n\t const uint64_t pos = line.end_ - line_[1].beg_;\n\t func->progress(num, static_cast<unsigned>(pos * 100llu \/ file_.size()));\n\t}\n }\n}\n\nvoid\nfile_index::parse_all(std::shared_ptr<regex_index> ri, ProgressFunctor *func)\n{\n regex_index_vec_t v = { ri };\n parse_all(v, func);\n}\n\nvoid\nfile_index::parse_all()\n{\n regex_index_vec_t v;\n parse_all(v);\n}\n\nunsigned\nfile_index::perc(const line_number_t num)\n{\n const line_number_t s = size();\n if (num > s) { return 100u; }\n return static_cast<uint64_t>(num) * 100llu \/ s;\n}\n\nvoid\nfile_index::parse_all_in_background(std::shared_ptr<regex_index> ri) const\n{\n if (! has_parsed_all_) {\n\treturn;\n }\n const unsigned line_size = line_.size();\n for(unsigned i = 1; i < line_size; ++i) {\n\tri->match(line_[i]);\n\tif ((i % 10000) == 0) {\n\t const unsigned perc = static_cast<double>(i) \/ static_cast<double>(line_size) * 100.0;\n\t eventAdd(event(\" matching line \" + std::to_string(i) + \" \" + std::to_string(perc) + \"% \"));\n\t}\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <cassert>\n\n\nnamespace math {\n\ttemplate<unsigned int _n, unsigned int _m, typename _Type>\n\tstruct Determinant {};\n\n\n\ttemplate<unsigned int _n, unsigned int _m = _n, typename _Type = double>\n\tstruct mat {\n\t\t_Type m_a[_m][_n];\n\n\t\tmat() {}\n\n\t\tmat(_Type const (&a_a)[_m][_n])\n\t\t\t:\n\t\tm_a(a_a) {}\n\n\t\tmat(_Type (&&a_a)[_m][_n])\n\t\t\t:\n\t\tm_a(move(a_a)) {}\n\n\t\tstruct row {\n\t\t\t_Type (&m_ra)[_m][_n];\n\t\t\tunsigned int m_i;\n\n\t\t\trow(_Type (&a_ra)[_m][_n], unsigned int a_i)\n\t\t\t\t:\n\t\t\tm_ra(a_ra),\n\t\t\t\tm_i(a_i) {}\n\n\t\t\tinline _Type &operator [] (unsigned int j) {\n\t\t\t\tassert(j < _m);\n\t\t\t\treturn m_ra[j][m_i];\n\t\t\t}\n\t\t};\n\n\t\tstruct const_row {\n\t\t\t_Type const (&m_ra)[_m][_n];\n\t\t\tunsigned int m_i;\n\n\t\t\tconst_row(_Type const (&a_ra)[_m][_n], unsigned int a_i)\n\t\t\t\t:\n\t\t\tm_ra(a_ra),\n\t\t\t\tm_i(a_i) {}\n\n\t\t\tinline _Type const &operator [] (unsigned int j) const {\n\t\t\t\tassert(j < _m);\n\t\t\t\treturn m_ra[j][m_i];\n\t\t\t}\n\t\t};\n\n\t\tinline row operator [] (unsigned int i) {\n\t\t\tassert(i < _n);\n\t\t\treturn row(m_a, i);\n\t\t}\n\n\t\tinline const_row operator [] (unsigned int i) const {\n\t\t\tassert(i < _n);\n\t\t\treturn const_row(m_a, i);\n\t\t}\n\n\t\tmat<_m, _n, _Type> transpose() const {\n\t\t\tmat<_m, _n, _Type> Result;\n\t\t\tfor(unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor(unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[j][i] = m_a[j][i];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tinline _Type determinant() const {\n\t\t\treturn Determinant<_n, _m, _Type>::Compute(*this);\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator + (mat<_n, _m, _Type> const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] += m_a[j][i] + r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator += (mat<_n, _m, _Type> const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] += r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator - (mat<_n, _m, _Type> const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] += m_a[j][i] + r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator -= (mat<_n, _m, _Type> const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] -= r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator * (_Type const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] = m_a[j][i] * r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator *= (_Type const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] *= r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator \/ (_Type const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] = m_a[j][i] \/ r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator \/= (_Type const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] \/= r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<unsigned int _l>\n\t\tmat<_n, _l, _Type> operator * (mat<_m, _l, _Type> const &r) const {\n\t\t\tmat<_n, _l, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _l; ++j) {\n\t\t\t\t\tfor (unsigned int k = 0; k < _m; ++k) {\n\t\t\t\t\t\tResult[i][j] += m_a[k][i] * r[k][j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\t};\n\n\n\ttemplate<unsigned int _n, typename _Type>\n\tstruct Determinant<_n, _n, _Type> {\n\t\tstatic _Type Compute(mat<_n, _n, _Type> const &r) {\n\t\t\t_Type d(0);\n\t\t\tint n = 1;\n\t\t\tfor (unsigned int j = 0; j < _n; ++j) {\n\t\t\t\t\/\/ TODO\n\t\t\t\tn = -n;\n\t\t\t}\n\t\t\treturn d;\n\t\t}\n\t};\n\n\n\ttypedef mat<2, 2> mat22, mat2;\n\ttypedef mat<2, 3> mat23;\n\ttypedef mat<2, 4> mat24;\n\ttypedef mat<3, 2> mat32;\n\ttypedef mat<3, 3> mat33, mat3;\n\ttypedef mat<3, 4> mat34;\n\ttypedef mat<4, 2> mat42;\n\ttypedef mat<4, 3> mat43;\n\ttypedef mat<4, 4> mat44, mat4;\n\n\n\ttemplate<unsigned int _n, typename _Type = double>\n\tstruct vec : public mat<_n, 1, _Type> {};\n\n\n\ttypedef vec<2> vec2;\n\ttypedef vec<3> vec3;\n\ttypedef vec<4> vec4;\n}\n<commit_msg>Optimized determinants<commit_after>#pragma once\n\n#include <algorithm>\n#include <cassert>\n\n\nnamespace math {\n\ttemplate<unsigned int _n, unsigned int _m, typename _Type>\n\tstruct Determinant {};\n\n\n\ttemplate<unsigned int _n, unsigned int _m = _n, typename _Type = double>\n\tstruct mat {\n\t\t_Type m_a[_m][_n];\n\n\t\tmat() {}\n\n\t\tmat(_Type const (&a_a)[_m][_n])\n\t\t\t:\n\t\tm_a(a_a) {}\n\n\t\tmat(_Type (&&a_a)[_m][_n])\n\t\t\t:\n\t\tm_a(move(a_a)) {}\n\n\t\tstruct row {\n\t\t\t_Type (&m_ra)[_m][_n];\n\t\t\tunsigned int m_i;\n\n\t\t\tinline row(_Type (&a_ra)[_m][_n], unsigned int a_i)\n\t\t\t\t:\n\t\t\tm_ra(a_ra),\n\t\t\t\tm_i(a_i) {}\n\n\t\t\tinline _Type &operator [] (unsigned int j) {\n\t\t\t\tassert(j < _m);\n\t\t\t\treturn m_ra[j][m_i];\n\t\t\t}\n\t\t};\n\n\t\tstruct const_row {\n\t\t\t_Type const (&m_ra)[_m][_n];\n\t\t\tunsigned int m_i;\n\n\t\t\tinline const_row(_Type const (&a_ra)[_m][_n], unsigned int a_i)\n\t\t\t\t:\n\t\t\tm_ra(a_ra),\n\t\t\t\tm_i(a_i) {}\n\n\t\t\tinline _Type const &operator [] (unsigned int j) const {\n\t\t\t\tassert(j < _m);\n\t\t\t\treturn m_ra[j][m_i];\n\t\t\t}\n\t\t};\n\n\t\tinline row operator [] (unsigned int i) {\n\t\t\tassert(i < _n);\n\t\t\treturn row(m_a, i);\n\t\t}\n\n\t\tinline const_row operator [] (unsigned int i) const {\n\t\t\tassert(i < _n);\n\t\t\treturn const_row(m_a, i);\n\t\t}\n\n\t\tmat<_m, _n, _Type> transpose() const {\n\t\t\tmat<_m, _n, _Type> Result;\n\t\t\tfor(unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor(unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[j][i] = m_a[j][i];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tinline _Type det() const {\n\t\t\treturn Determinant<_n, _m, _Type>::Compute(*this);\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator + (mat<_n, _m, _Type> const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] += m_a[j][i] + r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator += (mat<_n, _m, _Type> const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] += r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator - (mat<_n, _m, _Type> const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] += m_a[j][i] + r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator -= (mat<_n, _m, _Type> const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] -= r[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator * (_Type const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] = m_a[j][i] * r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator *= (_Type const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] *= r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tmat<_n, _m, _Type> operator \/ (_Type const &r) const {\n\t\t\tmat<_n, _m, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tResult[i][j] = m_a[j][i] \/ r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\n\t\tmat<_n, _m, _Type> &operator \/= (_Type const &r) {\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _m; ++j) {\n\t\t\t\t\tm_a[j][i] \/= r;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<unsigned int _l>\n\t\tmat<_n, _l, _Type> operator * (mat<_m, _l, _Type> const &r) const {\n\t\t\tmat<_n, _l, _Type> Result;\n\t\t\tfor (unsigned int i = 0; i < _n; ++i) {\n\t\t\t\tfor (unsigned int j = 0; j < _l; ++j) {\n\t\t\t\t\tfor (unsigned int k = 0; k < _m; ++k) {\n\t\t\t\t\t\tResult[i][j] += m_a[k][i] * r[k][j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Result;\n\t\t}\n\t};\n\n\n\ttemplate<typename _Type>\n\tstruct Determinant<1, 1, _Type> {\n\t\tstatic inline _Type Compute(mat<1, 1, _Type> const &r) {\n\t\t\treturn r.m_a[0][0];\n\t\t}\n\t};\n\n\n\ttemplate<typename _Type>\n\tstruct Determinant<2, 2, _Type> {\n\t\tstatic inline _Type Compute(mat<2, 2, _Type> const &r) {\n\t\t\treturn r.m_a[0][0] * r.m_a[1][1] - r.m_a[0][1] * r.m_a[1][0];\n\t\t}\n\t};\n\n\n\ttemplate<typename _Type>\n\tstruct Determinant<3, 3, _Type> {\n\t\tstatic inline _Type Compute(mat<3, 3, _Type> const &r) {\n\t\t\treturn\n\t\t\t\tr.m_a[0][0] * (r.m_a[1][1] * r.m_a[2][2] - r.m_a[1][2] * r.m_a[2][1]) -\n\t\t\t\tr.m_a[1][0] * (r.m_a[0][1] * r.m_a[2][2] - r.m_a[0][2] * r.m_a[2][1]) +\n\t\t\t\tr.m_a[2][0] * (r.m_a[0][1] * r.m_a[1][2] - r.m_a[0][2] * r.m_a[1][1]);\n\t\t}\n\t};\n\n\n\ttemplate<typename _Type>\n\tstruct Determinant<4, 4, _Type> {\n\t\tstatic inline _Type Compute(mat<4, 4, _Type> const &r) {\n\t\t\treturn\n\t\t\t\tr.m_a[0][0] * (r.m_a[1][1] * (r.m_a[2][2] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][2]) -\n\t\t\t\t r.m_a[1][2] * (r.m_a[2][1] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][1]) +\n\t\t\t\t r.m_a[1][3] * (r.m_a[2][1] * r.m_a[3][2] - r.m_a[2][2] * r.m_a[3][1])) -\n\t\t\t\tr.m_a[0][1] * (r.m_a[1][0] * (r.m_a[2][2] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][2]) -\n\t\t\t\t r.m_a[1][2] * (r.m_a[2][0] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][0]) +\n\t\t\t\t r.m_a[1][3] * (r.m_a[2][0] * r.m_a[3][2] - r.m_a[2][2] * r.m_a[3][0])) +\n\t\t\t\tr.m_a[0][2] * (r.m_a[1][0] * (r.m_a[2][1] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][1]) -\n\t\t\t\t r.m_a[1][1] * (r.m_a[2][0] * r.m_a[3][3] - r.m_a[2][3] * r.m_a[3][0]) +\n\t\t\t\t r.m_a[1][3] * (r.m_a[2][0] * r.m_a[3][1] - r.m_a[2][1] * r.m_a[3][0])) -\n\t\t\t\tr.m_a[0][3] * (r.m_a[1][0] * (r.m_a[2][1] * r.m_a[3][2] - r.m_a[2][2] * r.m_a[3][1]) -\n\t\t\t\t r.m_a[1][1] * (r.m_a[2][0] * r.m_a[3][2] - r.m_a[2][2] * r.m_a[3][0]) +\n\t\t\t\t r.m_a[1][2] * (r.m_a[2][0] * r.m_a[3][1] - r.m_a[2][1] * r.m_a[3][0]));\n\t\t}\n\t};\n\n\n\ttemplate<unsigned int _n, typename _Type>\n\tstruct Determinant<_n, _n, _Type> {\n\t\tstatic _Type Compute(mat<_n, _n, _Type> const &r) {\n\t\t\t_Type d(0);\n\t\t\tint n = 1;\n\t\t\tfor (unsigned int j = 0; j < _n; ++j) {\n\t\t\t\t\/\/ TODO\n\t\t\t\tn = -n;\n\t\t\t}\n\t\t\treturn d;\n\t\t}\n\t};\n\n\n\ttypedef mat<2, 2> mat22, mat2;\n\ttypedef mat<2, 3> mat23;\n\ttypedef mat<2, 4> mat24;\n\ttypedef mat<3, 2> mat32;\n\ttypedef mat<3, 3> mat33, mat3;\n\ttypedef mat<3, 4> mat34;\n\ttypedef mat<4, 2> mat42;\n\ttypedef mat<4, 3> mat43;\n\ttypedef mat<4, 4> mat44, mat4;\n\n\n\ttemplate<unsigned int _n, typename _Type = double>\n\tstruct vec : public mat<_n, 1, _Type> {};\n\n\n\ttypedef vec<2> vec2;\n\ttypedef vec<3> vec3;\n\ttypedef vec<4> vec4;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2015, Hobu Inc., hobu@hobu.co\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/pdal_internal.hpp>\n\n#include <zlib.h>\n\n#include <pdal\/Options.hpp>\n\n#include \"BpfWriter.hpp\"\n\nnamespace pdal\n{\n\nvoid BpfWriter::processOptions(const Options&)\n{\n if (m_filename.empty())\n throw pdal_error(\"Can't write BPF file without filename.\");\n}\n\n\nvoid BpfWriter::ready(PointContextRef ctx)\n{\n Dimension::IdList dims = ctx.dims(); \n for (auto id : dims)\n {\n BpfDimension dim;\n dim.m_id = id;\n dim.m_label = ctx.dimName(id);\n m_dims.push_back(dim);\n }\n\n m_stream = FileUtils::createFile(m_filename, true);\n m_header.m_version = 3;\n m_header.m_numDim = dims.size();\n \/\/ABELL - For now.\n m_header.m_pointFormat = BpfFormat::PointMajor;\n m_header.m_coordType = BpfCoordType::None;\n m_header.m_coordId = 0;\n m_header.setLog(log());\n\n \/\/ We will re-write the header and dimensions to account for the point\n \/\/ count and dimension min\/max.\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_header.m_len = m_stream.position();\n}\n\n\nvoid BpfWriter::write(const PointBuffer& data)\n{\n writePointMajor(data);\n m_header.m_numPts += data.size();\n}\n\n\nvoid BpfWriter::writePointMajor(const PointBuffer& data)\n{\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n for (auto & bpfDim : m_dims)\n {\n float v = data.getFieldAs<float>(bpfDim.m_id, idx);\n bpfDim.m_min = std::min(bpfDim.m_min, bpfDim.m_offset + v);\n bpfDim.m_max = std::min(bpfDim.m_max, bpfDim.m_offset + v);\n m_stream << v;\n }\n }\n}\n\n\nvoid BpfWriter::done(PointContextRef)\n{\n m_stream.seek(0);\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_stream.flush();\n}\n\n} \/\/namespace pdal\n<commit_msg>dimension max in bpf header never gets updated<commit_after>\/******************************************************************************\n* Copyright (c) 2015, Hobu Inc., hobu@hobu.co\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/pdal_internal.hpp>\n\n#include <zlib.h>\n\n#include <pdal\/Options.hpp>\n\n#include \"BpfWriter.hpp\"\n\nnamespace pdal\n{\n\nvoid BpfWriter::processOptions(const Options&)\n{\n if (m_filename.empty())\n throw pdal_error(\"Can't write BPF file without filename.\");\n}\n\n\nvoid BpfWriter::ready(PointContextRef ctx)\n{\n Dimension::IdList dims = ctx.dims(); \n for (auto id : dims)\n {\n BpfDimension dim;\n dim.m_id = id;\n dim.m_label = ctx.dimName(id);\n m_dims.push_back(dim);\n }\n\n m_stream = FileUtils::createFile(m_filename, true);\n m_header.m_version = 3;\n m_header.m_numDim = dims.size();\n \/\/ABELL - For now.\n m_header.m_pointFormat = BpfFormat::PointMajor;\n m_header.m_coordType = BpfCoordType::None;\n m_header.m_coordId = 0;\n m_header.setLog(log());\n\n \/\/ We will re-write the header and dimensions to account for the point\n \/\/ count and dimension min\/max.\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_header.m_len = m_stream.position();\n}\n\n\nvoid BpfWriter::write(const PointBuffer& data)\n{\n writePointMajor(data);\n m_header.m_numPts += data.size();\n}\n\n\nvoid BpfWriter::writePointMajor(const PointBuffer& data)\n{\n for (PointId idx = 0; idx < data.size(); ++idx)\n {\n for (auto & bpfDim : m_dims)\n {\n float v = data.getFieldAs<float>(bpfDim.m_id, idx);\n bpfDim.m_min = std::min(bpfDim.m_min, bpfDim.m_offset + v);\n bpfDim.m_max = std::max(bpfDim.m_max, bpfDim.m_offset + v);\n m_stream << v;\n }\n }\n}\n\n\nvoid BpfWriter::done(PointContextRef)\n{\n m_stream.seek(0);\n m_header.write(m_stream);\n m_header.writeDimensions(m_stream, m_dims);\n m_stream.flush();\n}\n\n} \/\/namespace pdal\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <math.h>\n\n#include \"gtest\/gtest.h\"\n\n#include \"base\/common.h\"\n\nconst int kMaxFactorial = 13;\n\nint Factorial(int v) {\n \/\/ NB we wrote the implementation of this function on the lecture;\n \/\/ before the lecture it was simply \"return -1;\"\n\n CHECK_GE(v, 0);\n CHECK_LT(v, kMaxFactorial);\n\n if (v <= 1)\n return 1;\n\n \/\/ TODO(timurrrr): don't use recursion.\n return v * Factorial(v - 1);\n}\n\n\/\/ Tests factorial of positive numbers.\nTEST(FactorialTest, HandlesPositiveInput) {\n EXPECT_EQ(1, Factorial(1));\n EXPECT_EQ(2, Factorial(2));\n EXPECT_EQ(6, Factorial(3));\n EXPECT_EQ(40320, Factorial(8));\n EXPECT_EQ(479001600, Factorial(12));\n}\n\n\/\/ Tests factorial of 0.\n\/\/ \"Corner case test\"\nTEST(FactorialTest, HandlesZeroInput) {\n EXPECT_EQ(1, Factorial(0));\n}\n\n\/\/ Tests factorial of number that will cause integer type overflow.\nTEST(FactorialTest, FailsOnTooBigInputDeathTest) {\n ASSERT_DEATH(Factorial(13), \"\");\n ASSERT_DEATH(Factorial(42), \"\");\n}\n\nTEST(FactorialTest, FailsOnNegativeInputDeathTest) {\n ASSERT_DEATH(Factorial(-1), \"\");\n}\n\nTEST(FailureTest, WillRemove) {\n ASSERT_EQ(1, 2);\n}\n<commit_msg>Temporary fix for the test again<commit_after>\/\/ Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <math.h>\n\n#include \"gtest\/gtest.h\"\n\n#include \"base\/common.h\"\n\nconst int kMaxFactorial = 13;\n\nint Factorial(int v) {\n \/\/ NB we wrote the implementation of this function on the lecture;\n \/\/ before the lecture it was simply \"return -1;\"\n\n CHECK_GE(v, 0);\n CHECK_LT(v, kMaxFactorial);\n\n if (v <= 1)\n return 1;\n\n \/\/ TODO(timurrrr): don't use recursion.\n return v * Factorial(v - 1);\n}\n\n\/\/ Tests factorial of positive numbers.\nTEST(FactorialTest, HandlesPositiveInput) {\n EXPECT_EQ(1, Factorial(1));\n EXPECT_EQ(2, Factorial(2));\n EXPECT_EQ(6, Factorial(3));\n EXPECT_EQ(40320, Factorial(8));\n EXPECT_EQ(479001600, Factorial(12));\n}\n\n\/\/ Tests factorial of 0.\n\/\/ \"Corner case test\"\nTEST(FactorialTest, HandlesZeroInput) {\n EXPECT_EQ(1, Factorial(0));\n}\n\n\/\/ Tests factorial of number that will cause integer type overflow.\nTEST(FactorialTest, FailsOnTooBigInputDeathTest) {\n ASSERT_DEATH(Factorial(13), \"\");\n ASSERT_DEATH(Factorial(42), \"\");\n}\n\nTEST(FactorialTest, FailsOnNegativeInputDeathTest) {\n ASSERT_DEATH(Factorial(-1), \"\");\n}\n\nTEST(FailureTest, WillRemove) {\n \/\/ASSERT_EQ(1, 2);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SysUtil.h\"\n#include \"lib\/mace.h\"\n\n#include \"TcpTransport-init.h\"\n#include \"load_protocols.h\"\n#include <signal.h>\n#include <string>\n#include \"mlist.h\"\n\n#include \"RandomUtil.h\"\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <stdio.h>\n#include <pthread.h>\n\/\/#include \"TagServiceClass.h\"\n\/\/#include \"Tag-init.h\"\n#include \"ContextJobApplication.h\"\n#include \"..\/services\/interfaces\/NullServiceClass.h\"\n \nusing namespace std;\n \n\/*class TagResponseHandler : public TagDataHandler {\n \n};*\/ \ntypedef mace::vector<mace::list<mace::string> > StringListVector;\ntypedef mace::vector<mace::string> StringVector;\n\n\nstd::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n std::vector<std::string> elems;\n split(s, delim, elems);\n return elems;\n}\n\nvoid loadContextFromParam( const mace::string& service, mace::map< mace::string, ContextMappingType >& contexts, mace::map< mace::string, MaceAddr>& migrateContexts){\n if( ! params::containsKey(\"nodeset\") || ! params::containsKey(\"mapping\") ){\n return;\n }\n NodeSet ns = params::get<NodeSet>(\"nodeset\");\n\n StringVector mapping = split(params::get<mace::string>(\"mapping\"), '\\n');\n\n typedef mace::map<MaceAddr, mace::list<mace::string> > ContextMappingType;\n\n StringListVector node_context;\n\n ASSERT(ns.size() > 0);\n for( uint32_t i=0; i<ns.size(); i++ ) {\n mace::list<mace::string> string_list;\n node_context.push_back(string_list);\n }\n\n \/\/ Set for head node\n node_context[0].push_back( mace::ContextMapping::getHeadContext() ); \/\/head context\n node_context[0].push_back( \"\" ); \/\/ global\n\n \/\/ key:value\n \/\/ context_peer_id:context_value\n \/\/ 2:A[0] 2:A[1] ...\n \n for( StringVector::const_iterator it = mapping.begin(); it != mapping.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n node_context[key].push_back(kv[1]);\n }\n\n ContextMappingType contextMap;\n\n int i=0;\n std::vector< MaceAddr > nodeAddrs;\n for( NodeSet::iterator it = ns.begin(); it != ns.end(); it++ ) {\n std::cout << \"nodeset[\" << i << \"] = \" << *it << std::endl;\n contextMap[ (*it).getMaceAddr() ] = node_context[ i++ ];\n nodeAddrs.push_back( (*it).getMaceAddr() );\n }\n\n contexts[ service ] = contextMap;\n\n if( params::containsKey(\"migrateBatch\") ){\n \/\/ create a number of migrations \n StringVector migrateBatch = split(params::get<mace::string>(\"migrateBatch\"), ':');\n std::string contextName = migrateBatch[0];\n uint32_t migrateFrom = atoi( migrateBatch[1].c_str() );\n uint32_t migrateTo = atoi( migrateBatch[2].c_str() );\n uint32_t nodeID = atoi( migrateBatch[3].c_str() );\n\n for( uint32_t index = migrateFrom; index <= migrateTo; index++ ){\n std::ostringstream oss;\n oss << contextName << \"[\" << index << \"]\";\n migrateContexts[ oss.str() ] = nodeAddrs[ nodeID ];\n }\n\n }else{\n\n if( !params::containsKey(\"migrate\") ) return;\n StringVector migrate = split(params::get<mace::string>(\"migrate\"), '\\n');\n for( StringVector::const_iterator it = migrate.begin(); it != migrate.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n migrateContexts[ kv[1] ] = nodeAddrs[key];\n }\n\n if ( !params::containsKey(\"migrate2\") ) return;\n StringVector migrateBack = split(params::get<mace::string>(\"migrate2\"), '\\n');\n for( StringVector::const_iterator it = migrate.begin(); it != migrate.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n migrateContexts[ kv[1] ] = nodeAddrs[key];\n }\n\n if ( !params::containsKey(\"migrate3\") ) return;\n StringVector migrateBack = split(params::get<mace::string>(\"migrate3\"), '\\n');\n for( StringVector::const_iterator it = migrate.begin(); it != migrate.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n migrateContexts[ kv[1] ] = nodeAddrs[key];\n }\n }\n\n}\n\nbool ishead = false;\nvoid writeOutProf( int signum ){\n if( ishead ){\n std::cout<<\"Head node. perform global exit and clean up\"<<std::endl;\n }else{\n std::cout<<\"This is not a head node! You must terminate the head node first!\"<<std::endl;\n }\n exit(EXIT_SUCCESS);\n}\n \nint main(int argc, char* argv[]) {\n \/\/Log::autoAdd(\"^Tag\");\n mace::Init(argc, argv);\n load_protocols();\n\n if( params::get<bool>(\"gprof\", false ) ){\n\n SysUtil::signal( SIGINT, writeOutProf ); \/\/ intercept ctrl+c and call exit to force gprof output\n SysUtil::signal( SIGABRT, writeOutProf ); \/\/ intercept abort and call exit to force gprof output\n SysUtil::signal( SIGSEGV, writeOutProf ); \/\/ intercept seg fault and call exit to force gprof output\n }\n\n uint64_t runtime = (uint64_t)(params::get<double>(\"run_time\", 2) * 1000 * 1000);\n mace::string service = \"Tag\";\n \n mace::ContextJobApplication<NullServiceClass> app;\n app.installSignalHandler();\n\n params::print(stdout);\n\n typedef mace::map<MaceAddr, mace::list<mace::string> > ContextMappingType;\n mace::map< mace::string, ContextMappingType > contexts;\n mace::map< mace::string, MaceAddr> migrateContexts;\n mace::map< mace::string, MaceAddr> migrateteBackContexts;\n\n loadContextFromParam( service, contexts, migrateContexts );\n app.loadContext(contexts);\n\n std::cout << \"Starting at time \" << TimeUtil::timeu() << std::endl;\n\n\n \/\/ create new thread. one is used to launch the service, one is to initiates the migration request.\n\n app.startService( service );\n\n mace::list< mace::string > &nodectx = contexts[ service ][ Util::getMaceAddr() ];\n mace::list< mace::string >::iterator it = find( nodectx.begin(), nodectx.end(), mace::ContextMapping::getHeadContext() );\n if( it != nodectx.end() ){\n ishead = true;\n }\n\n if( ishead ){\n uint8_t serviceID = 0; \n \n uint32_t migration_start = params::get<uint32_t>(\"migration_start\",1);\n SysUtil::sleepm( 1000 * migration_start ); \/\/ sleep for one second\n \n std::cout << TimeUtil::timeu() << \" Migration started.\" << std::endl;\n for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts.begin(); migctxIt != migrateContexts.end(); migctxIt++ ){\n app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n }\n\n uint32_t migration_start2 = params::get<uint32_t>(\"migration_start2\",1);\n SysUtil::sleepm( 1000 * migration_start ); \/\/ sleep for one second\n \n std::cout << TimeUtil::timeu() << \" Migration2 started.\" << std::endl;\n for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts.begin(); migctxIt != migrateContexts.end(); migctxIt++ ){\n app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n }\n\n uint32_t migration_start3 = params::get<uint32_t>(\"migration_start3\",1);\n SysUtil::sleepm( 1000 * migration_start ); \/\/ sleep for one second\n \n std::cout << TimeUtil::timeu() << \" Migration3 started.\" << std::endl;\n for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts.begin(); migctxIt != migrateContexts.end(); migctxIt++ ){\n app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n }\n\n }\n app.waitService( runtime );\n\n if( ishead ){ \/\/ head node sents exit event\n app.globalExit();\n }\n\n return EXIT_SUCCESS;\n} \n<commit_msg>firstTag.cc updated<commit_after>#include \"SysUtil.h\"\n#include \"lib\/mace.h\"\n\n#include \"TcpTransport-init.h\"\n#include \"load_protocols.h\"\n#include <signal.h>\n#include <string>\n#include \"mlist.h\"\n\n#include \"RandomUtil.h\"\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <stdio.h>\n#include <pthread.h>\n\/\/#include \"TagServiceClass.h\"\n\/\/#include \"Tag-init.h\"\n#include \"ContextJobApplication.h\"\n#include \"..\/services\/interfaces\/NullServiceClass.h\"\n \nusing namespace std;\n \n\/*class TagResponseHandler : public TagDataHandler {\n \n};*\/ \ntypedef mace::vector<mace::list<mace::string> > StringListVector;\ntypedef mace::vector<mace::string> StringVector;\n\n\nstd::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n std::vector<std::string> elems;\n split(s, delim, elems);\n return elems;\n}\n\nvoid loadContextFromParam( const mace::string& service, mace::map< mace::string, ContextMappingType >& contexts, mace::map< mace::string, MaceAddr>& migrateContexts, mace::map< mace::string, MaceAddr>& migrateContexts2 ){\n if( ! params::containsKey(\"nodeset\") || ! params::containsKey(\"mapping\") ){\n return;\n }\n NodeSet ns = params::get<NodeSet>(\"nodeset\");\n\n StringVector mapping = split(params::get<mace::string>(\"mapping\"), '\\n');\n\n typedef mace::map<MaceAddr, mace::list<mace::string> > ContextMappingType;\n\n StringListVector node_context;\n\n ASSERT(ns.size() > 0);\n for( uint32_t i=0; i<ns.size(); i++ ) {\n mace::list<mace::string> string_list;\n node_context.push_back(string_list);\n }\n\n \/\/ Set for head node\n node_context[0].push_back( mace::ContextMapping::getHeadContext() ); \/\/head context\n node_context[0].push_back( \"\" ); \/\/ global\n\n \/\/ key:value\n \/\/ context_peer_id:context_value\n \/\/ 2:A[0] 2:A[1] ...\n \n for( StringVector::const_iterator it = mapping.begin(); it != mapping.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n node_context[key].push_back(kv[1]);\n }\n\n ContextMappingType contextMap;\n\n int i=0;\n std::vector< MaceAddr > nodeAddrs;\n for( NodeSet::iterator it = ns.begin(); it != ns.end(); it++ ) {\n std::cout << \"nodeset[\" << i << \"] = \" << *it << std::endl;\n contextMap[ (*it).getMaceAddr() ] = node_context[ i++ ];\n nodeAddrs.push_back( (*it).getMaceAddr() );\n }\n\n contexts[ service ] = contextMap;\n\n if( params::containsKey(\"migrateBatch\") ){\n \/\/ create a number of migrations \n StringVector migrateBatch = split(params::get<mace::string>(\"migrateBatch\"), ':');\n std::string contextName = migrateBatch[0];\n uint32_t migrateFrom = atoi( migrateBatch[1].c_str() );\n uint32_t migrateTo = atoi( migrateBatch[2].c_str() );\n uint32_t nodeID = atoi( migrateBatch[3].c_str() );\n\n for( uint32_t index = migrateFrom; index <= migrateTo; index++ ){\n std::ostringstream oss;\n oss << contextName << \"[\" << index << \"]\";\n migrateContexts[ oss.str() ] = nodeAddrs[ nodeID ];\n }\n\n }else{\n\n if( !params::containsKey(\"migrate\") ) return;\n StringVector migrate = split(params::get<mace::string>(\"migrate\"), '\\n');\n for( StringVector::const_iterator it = migrate.begin(); it != migrate.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n migrateContexts[ kv[1] ] = nodeAddrs[key];\n }\n\n if ( !params::containsKey(\"migrate2\") ) return;\n StringVector migrate2 = split(params::get<mace::string>(\"migrate2\"), '\\n');\n for( StringVector::const_iterator it = migrate2.begin(); it != migrate2.end(); it++ ) {\n StringVector kv = split(*it, ':');\n ASSERT(kv.size() == 2);\n \n uint32_t key;\n istringstream(kv[0]) >> key;\n ASSERT(key >= 0 && key < ns.size());\n migrateContexts2[ kv[1] ] = nodeAddrs[key];\n }\n\n \/\/if ( !params::containsKey(\"migrate3\") ) return;\n \/\/StringVector migrateBack = split(params::get<mace::string>(\"migrate3\"), '\\n');\n \/\/for( StringVector::const_iterator it = migrate.begin(); it != migrate.end(); it++ ) {\n \/\/StringVector kv = split(*it, ':');\n \/\/ASSERT(kv.size() == 2);\n \n \/\/uint32_t key;\n \/\/istringstream(kv[0]) >> key;\n \/\/ASSERT(key >= 0 && key < ns.size());\n \/\/migrateContexts[ kv[1] ] = nodeAddrs[key];\n \/\/}\n }\n\n}\n\nbool ishead = false;\nvoid writeOutProf( int signum ){\n if( ishead ){\n std::cout<<\"Head node. perform global exit and clean up\"<<std::endl;\n }else{\n std::cout<<\"This is not a head node! You must terminate the head node first!\"<<std::endl;\n }\n exit(EXIT_SUCCESS);\n}\n \nint main(int argc, char* argv[]) {\n \/\/Log::autoAdd(\"^Tag\");\n mace::Init(argc, argv);\n load_protocols();\n\n if( params::get<bool>(\"gprof\", false ) ){\n\n SysUtil::signal( SIGINT, writeOutProf ); \/\/ intercept ctrl+c and call exit to force gprof output\n SysUtil::signal( SIGABRT, writeOutProf ); \/\/ intercept abort and call exit to force gprof output\n SysUtil::signal( SIGSEGV, writeOutProf ); \/\/ intercept seg fault and call exit to force gprof output\n }\n\n uint64_t runtime = (uint64_t)(params::get<double>(\"run_time\", 2) * 1000 * 1000);\n mace::string service = \"Tag\";\n \n mace::ContextJobApplication<NullServiceClass> app;\n app.installSignalHandler();\n\n params::print(stdout);\n\n typedef mace::map<MaceAddr, mace::list<mace::string> > ContextMappingType;\n mace::map< mace::string, ContextMappingType > contexts;\n mace::map< mace::string, MaceAddr> migrateContexts;\n mace::map< mace::string, MaceAddr> migrateContexts2;\n mace::map< mace::string, MaceAddr> migrateteBackContexts;\n\n loadContextFromParam( service, contexts, migrateContexts, migrateContexts2 );\n app.loadContext(contexts);\n\n std::cout << \"Starting at time \" << TimeUtil::timeu() << std::endl;\n\n\n \/\/ create new thread. one is used to launch the service, one is to initiates the migration request.\n\n app.startService( service );\n\n mace::list< mace::string > &nodectx = contexts[ service ][ Util::getMaceAddr() ];\n mace::list< mace::string >::iterator it = find( nodectx.begin(), nodectx.end(), mace::ContextMapping::getHeadContext() );\n if( it != nodectx.end() ){\n ishead = true;\n }\n\n if( ishead ){\n uint8_t serviceID = 0; \n \n uint32_t migration_start = params::get<uint32_t>(\"migration_start\",1);\n SysUtil::sleepm( 1000 * migration_start ); \/\/ sleep until migration\n \n std::cout << TimeUtil::timeu() << \" Migration started.\" << std::endl;\n for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts.begin(); migctxIt != migrateContexts.end(); migctxIt++ ){\n app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n }\n\n uint32_t migration_start2 = params::get<uint32_t>(\"migration_start2\",1);\n if( migration_start2 > migration_start1 ) {\n SysUtil::sleepm( 1000 * (migration_start2-migration_start) ); \/\/ sleep until second migration\n \n std::cout << TimeUtil::timeu() << \" Migration2 started.\" << std::endl;\n for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts2.begin(); migctxIt != migrateContexts2.end(); migctxIt++ ){\n app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n }\n } else {\n std::cout << TimeUtil::timeu() << \" Migration2 will not be started.\" << std::endl;\n }\n\n \/\/uint32_t migration_start3 = params::get<uint32_t>(\"migration_start3\",1);\n \/\/SysUtil::sleepm( 1000 * migration_start ); \/\/ sleep for one second\n \n \/\/std::cout << TimeUtil::timeu() << \" Migration3 started.\" << std::endl;\n \/\/for( mace::map< mace::string, MaceAddr>::iterator migctxIt = migrateContexts.begin(); migctxIt != migrateContexts.end(); migctxIt++ ){\n \/\/app.getServiceObject()->requestContextMigration( serviceID, migctxIt->first, migctxIt->second, false );\n \/\/SysUtil::sleepm( params::get<uint32_t>(\"sleep\", 10) ); \/\/ sleep for 0.1 second\n \/\/}\n\n }\n app.waitService( runtime );\n\n if( ishead ){ \/\/ head node sents exit event\n app.globalExit();\n }\n\n return EXIT_SUCCESS;\n} \n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"qvalidatedlineedit.h\"\n\n#include \"bitcoinaddressvalidator.h\"\n#include \"guiconstants.h\"\n\nQValidatedLineEdit::QValidatedLineEdit(QWidget *parent) :\n QLineEdit(parent),\n valid(true),\n checkValidator(0)\n{\n connect(this, SIGNAL(textChanged(QString)), this, SLOT(markValid()));\n}\n\nvoid QValidatedLineEdit::setValid(bool _valid)\n{\n if(_valid == this->valid)\n {\n return;\n }\n\n if(_valid)\n {\n setStyleSheet(\"\");\n }\n else\n {\n setStyleSheet(\"QValidatedLineEdit { \" STYLE_INVALID \"}\");\n }\n this->valid = _valid;\n}\n\nvoid QValidatedLineEdit::focusInEvent(QFocusEvent *evt)\n{\n \/\/ Clear invalid flag on focus\n setValid(true);\n\n QLineEdit::focusInEvent(evt);\n}\n\nvoid QValidatedLineEdit::focusOutEvent(QFocusEvent *evt)\n{\n checkValidity();\n\n QLineEdit::focusOutEvent(evt);\n}\n\nvoid QValidatedLineEdit::markValid()\n{\n \/\/ As long as a user is typing ensure we display state as valid\n setValid(true);\n}\n\nvoid QValidatedLineEdit::clear()\n{\n setValid(true);\n QLineEdit::clear();\n}\n\nvoid QValidatedLineEdit::setEnabled(bool enabled)\n{\n if (!enabled)\n {\n \/\/ A disabled QValidatedLineEdit should be marked valid\n setValid(true);\n }\n else\n {\n \/\/ Recheck validity when QValidatedLineEdit gets enabled\n checkValidity();\n }\n\n QLineEdit::setEnabled(enabled);\n}\n\nvoid QValidatedLineEdit::checkValidity()\n{\n if (text().isEmpty())\n {\n setValid(true);\n }\n else if (hasAcceptableInput())\n {\n setValid(true);\n\n \/\/ Check contents on focus out\n if (checkValidator)\n {\n QString address = text();\n int pos = 0;\n if (checkValidator->validate(address, pos) == QValidator::Acceptable)\n setValid(true);\n else\n setValid(false);\n }\n }\n else\n setValid(false);\n\n Q_EMIT validationDidChange(this);\n}\n\nvoid QValidatedLineEdit::setCheckValidator(const QValidator *v)\n{\n checkValidator = v;\n}\n\nbool QValidatedLineEdit::isValid()\n{\n \/\/ use checkValidator in case the QValidatedLineEdit is disabled\n if (checkValidator)\n {\n QString address = text();\n int pos = 0;\n if (checkValidator->validate(address, pos) == QValidator::Acceptable)\n return true;\n }\n\n return valid;\n}\n<commit_msg>Bugfix: GUI: Re-check validity after QValidatedLineEdit::setCheckValidator<commit_after>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"qvalidatedlineedit.h\"\n\n#include \"bitcoinaddressvalidator.h\"\n#include \"guiconstants.h\"\n\nQValidatedLineEdit::QValidatedLineEdit(QWidget *parent) :\n QLineEdit(parent),\n valid(true),\n checkValidator(0)\n{\n connect(this, SIGNAL(textChanged(QString)), this, SLOT(markValid()));\n}\n\nvoid QValidatedLineEdit::setValid(bool _valid)\n{\n if(_valid == this->valid)\n {\n return;\n }\n\n if(_valid)\n {\n setStyleSheet(\"\");\n }\n else\n {\n setStyleSheet(\"QValidatedLineEdit { \" STYLE_INVALID \"}\");\n }\n this->valid = _valid;\n}\n\nvoid QValidatedLineEdit::focusInEvent(QFocusEvent *evt)\n{\n \/\/ Clear invalid flag on focus\n setValid(true);\n\n QLineEdit::focusInEvent(evt);\n}\n\nvoid QValidatedLineEdit::focusOutEvent(QFocusEvent *evt)\n{\n checkValidity();\n\n QLineEdit::focusOutEvent(evt);\n}\n\nvoid QValidatedLineEdit::markValid()\n{\n \/\/ As long as a user is typing ensure we display state as valid\n setValid(true);\n}\n\nvoid QValidatedLineEdit::clear()\n{\n setValid(true);\n QLineEdit::clear();\n}\n\nvoid QValidatedLineEdit::setEnabled(bool enabled)\n{\n if (!enabled)\n {\n \/\/ A disabled QValidatedLineEdit should be marked valid\n setValid(true);\n }\n else\n {\n \/\/ Recheck validity when QValidatedLineEdit gets enabled\n checkValidity();\n }\n\n QLineEdit::setEnabled(enabled);\n}\n\nvoid QValidatedLineEdit::checkValidity()\n{\n if (text().isEmpty())\n {\n setValid(true);\n }\n else if (hasAcceptableInput())\n {\n setValid(true);\n\n \/\/ Check contents on focus out\n if (checkValidator)\n {\n QString address = text();\n int pos = 0;\n if (checkValidator->validate(address, pos) == QValidator::Acceptable)\n setValid(true);\n else\n setValid(false);\n }\n }\n else\n setValid(false);\n\n Q_EMIT validationDidChange(this);\n}\n\nvoid QValidatedLineEdit::setCheckValidator(const QValidator *v)\n{\n checkValidator = v;\n checkValidity();\n}\n\nbool QValidatedLineEdit::isValid()\n{\n \/\/ use checkValidator in case the QValidatedLineEdit is disabled\n if (checkValidator)\n {\n QString address = text();\n int pos = 0;\n if (checkValidator->validate(address, pos) == QValidator::Acceptable)\n return true;\n }\n\n return valid;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>[wasm] fix memory info creation (#7461)<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2015] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_COLUMN_DATETIME_HPP\n#define REALM_COLUMN_DATETIME_HPP\n\n#include <realm\/column.hpp>\n\nnamespace realm {\n\nstruct NewDate {\n NewDate(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) \n {\n REALM_ASSERT_3(nanoseconds, <, 1000000000);\n }\n NewDate(const null&) : m_is_null(true) { }\n NewDate() : NewDate(null()) { }\n\n bool is_null() const { return m_is_null; }\n bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }\n bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }\n bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }\n bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }\n bool operator <= (const NewDate& rhs) const { return *this < rhs || *this == rhs; }\n bool operator >= (const NewDate& rhs) const { return *this > rhs || *this == rhs; }\n NewDate& operator = (const NewDate& rhs) = default;\n\n template<class Ch, class Tr>\n friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const NewDate&);\n\n int64_t m_seconds;\n uint32_t m_nanoseconds;\n bool m_is_null;\n};\n\ntemplate<class C, class T>\ninline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const NewDate& d)\n{\n out << \"NewDate(\" << d.m_seconds << \", \" << d.m_nanoseconds << \")\";\n return out;\n}\n\nclass DateTimeColumn : public ColumnBaseSimple {\npublic:\n DateTimeColumn(Allocator& alloc, ref_type ref);\n \/\/\/ Get the number of entries in this column. This operation is relatively\n \/\/\/ slow.\n\n static ref_type create(Allocator& alloc, size_t size);\n\n size_t size() const noexcept override;\n \/\/\/ Whether or not this column is nullable.\n bool is_nullable() const noexcept override;\n \/\/\/ Whether or not the value at \\a row_ndx is NULL. If the column is not\n \/\/\/ nullable, always returns false.\n bool is_null(size_t row_ndx) const noexcept override;\n \/\/\/ Sets the value at \\a row_ndx to be NULL.\n \/\/\/ \\throw LogicError Thrown if this column is not nullable.\n void set_null(size_t row_ndx) override;\n void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;\n void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,\n bool broken_reciprocal_backlinks) override;\n void move_last_row_over(size_t row_ndx, size_t prior_num_rows,\n bool broken_reciprocal_backlinks) override;\n void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;\n void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;\n void destroy() noexcept override;\n StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;\n MemRef clone_deep(Allocator& alloc) const override;\n ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;\n void update_from_parent(size_t old_baseline) noexcept override;\n void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;\n#ifdef REALM_DEBUG\n void verify() const override;\n void to_dot(std::ostream&, StringData title = StringData()) const override;\n void do_dump_node_structure(std::ostream&, int level) const override;\n void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;\n#endif\n void add(const NewDate& ndt = NewDate{});\n NewDate get(size_t row_ndx) const noexcept;\n void set(size_t row_ndx, const NewDate& ndt);\nprivate:\n\n IntNullColumn m_seconds;\n IntegerColumn m_nanoseconds;\n\n};\n\n} \/\/ namespace realm\n\n#endif \/\/ REALM_COLUMN_DATETIME_HPP\n<commit_msg>Moved comment to correct place<commit_after>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2015] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_COLUMN_DATETIME_HPP\n#define REALM_COLUMN_DATETIME_HPP\n\n#include <realm\/column.hpp>\n\nnamespace realm {\n\nstruct NewDate {\n NewDate(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) \n {\n REALM_ASSERT_3(nanoseconds, <, 1000000000);\n }\n NewDate(const null&) : m_is_null(true) { }\n NewDate() : NewDate(null()) { }\n\n bool is_null() const { return m_is_null; }\n bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }\n bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }\n bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }\n bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }\n bool operator <= (const NewDate& rhs) const { return *this < rhs || *this == rhs; }\n bool operator >= (const NewDate& rhs) const { return *this > rhs || *this == rhs; }\n NewDate& operator = (const NewDate& rhs) = default;\n\n template<class Ch, class Tr>\n friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const NewDate&);\n\n int64_t m_seconds;\n uint32_t m_nanoseconds;\n bool m_is_null;\n};\n\ntemplate<class C, class T>\ninline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const NewDate& d)\n{\n out << \"NewDate(\" << d.m_seconds << \", \" << d.m_nanoseconds << \")\";\n return out;\n}\n\nclass DateTimeColumn : public ColumnBaseSimple {\npublic:\n DateTimeColumn(Allocator& alloc, ref_type ref);\n\n static ref_type create(Allocator& alloc, size_t size);\n\n \/\/\/ Get the number of entries in this column. This operation is relatively\n \/\/\/ slow.\n size_t size() const noexcept override;\n \/\/\/ Whether or not this column is nullable.\n bool is_nullable() const noexcept override;\n \/\/\/ Whether or not the value at \\a row_ndx is NULL. If the column is not\n \/\/\/ nullable, always returns false.\n bool is_null(size_t row_ndx) const noexcept override;\n \/\/\/ Sets the value at \\a row_ndx to be NULL.\n \/\/\/ \\throw LogicError Thrown if this column is not nullable.\n void set_null(size_t row_ndx) override;\n void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;\n void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,\n bool broken_reciprocal_backlinks) override;\n void move_last_row_over(size_t row_ndx, size_t prior_num_rows,\n bool broken_reciprocal_backlinks) override;\n void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;\n void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;\n void destroy() noexcept override;\n StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;\n MemRef clone_deep(Allocator& alloc) const override;\n ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;\n void update_from_parent(size_t old_baseline) noexcept override;\n void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;\n#ifdef REALM_DEBUG\n void verify() const override;\n void to_dot(std::ostream&, StringData title = StringData()) const override;\n void do_dump_node_structure(std::ostream&, int level) const override;\n void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;\n#endif\n void add(const NewDate& ndt = NewDate{});\n NewDate get(size_t row_ndx) const noexcept;\n void set(size_t row_ndx, const NewDate& ndt);\nprivate:\n\n IntNullColumn m_seconds;\n IntegerColumn m_nanoseconds;\n\n};\n\n} \/\/ namespace realm\n\n#endif \/\/ REALM_COLUMN_DATETIME_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/inductive\/inductive.h\"\n#include \"library\/user_recursors.h\"\n#include \"library\/blast\/revert_action.h\"\n#include \"library\/blast\/blast.h\"\n\nnamespace lean {\nnamespace blast {\noptional<name> is_recursor_action_target(hypothesis_idx hidx) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n if (!is_app(type) && !is_constant(type))\n return optional<name>();\n if (is_relation(type))\n return optional<name>(); \/\/ we don't apply recursors to equivalence relations: =, ~, <->, etc.\n if (!h->is_assumption())\n return optional<name>(); \/\/ we only consider assumptions\n \/\/ TODO(Leo): more restrictions?\n \/\/ TODO(Leo): consider user-provided hints\n expr const & I = get_app_fn(type);\n if (!is_constant(I))\n return optional<name>();\n if (inductive::is_inductive_decl(env(), const_name(I)))\n return optional<name>(name(inductive::get_elim_name(const_name(I)))); \/\/ it is builtin recursive datatype\n list<name> Rs = get_recursors_for(env(), const_name(I));\n if (!Rs)\n return optional<name>();\n else\n return optional<name>(head(Rs)); \/\/ type has user-defined recursors\n}\n\nunsigned get_num_minor_premises(name const & R) {\n return get_recursor_info(env(), R).get_num_minors();\n}\n\nbool is_recursive_recursor(name const & R) {\n return get_recursor_info(env(), R).is_recursive();\n}\n\nstruct recursor_proof_step_cell : public proof_step_cell {\n bool m_dep;\n branch m_branch; \/\/ branch for backtracking\n expr m_proof; \/\/ recursor-application (the position where the goal-proofs are marked by the local constants).\n list<expr> m_goals; \/\/ type of each subgoal\/branch encoded as a local constant\n list<expr> m_goal_proofs; \/\/ proofs generated so far\n\n recursor_proof_step_cell(bool dep, branch const & b, expr const & pr, list<expr> const & goals, list<expr> const & goal_proofs):\n m_dep(dep), m_branch(b), m_proof(pr), m_goals(goals), m_goal_proofs(goal_proofs) {\n }\n\n virtual ~recursor_proof_step_cell() {}\n\n virtual action_result resolve(expr const & pr) const {\n state & s = curr_state();\n s.set_branch(m_branch);\n if (!m_dep) {\n \/\/ It is not a dependent elimination, so if pr did not use new hypothesis,\n \/\/ we don't need to investigate other branches.\n \/\/ This is also a form of non-chronological backtracking.\n expr const & goal = head(m_goals);\n unsigned arity = get_arity(mlocal_type(goal));\n expr it = pr;\n bool skip = true;\n for (unsigned i = 0; i < arity; i++) {\n if (!is_lambda(it)) {\n skip = false;\n break;\n }\n it = binding_body(it);\n if (!closed(it)) {\n skip = false;\n break;\n }\n }\n if (skip) {\n lean_assert(closed(it));\n return action_result::solved(it);\n }\n }\n list<expr> new_goals = tail(m_goals);\n list<expr> new_prs = cons(pr, m_goal_proofs);\n if (empty(new_goals)) {\n buffer<expr> proof_args;\n buffer<expr> gs;\n to_buffer(m_goals, gs);\n expr const & rec = get_app_args(m_proof, proof_args);\n \/\/ update proof_args that are goals with their proofs\n unsigned i = proof_args.size();\n while (i > 0) {\n --i;\n if (!gs.empty() && proof_args[i] == gs.back()) {\n lean_assert(new_prs);\n proof_args[i] = head(new_prs);\n new_prs = tail(new_prs);\n }\n }\n return action_result::solved(mk_app(rec, proof_args));\n } else {\n s.pop_proof_step();\n s.push_proof_step(new recursor_proof_step_cell(m_dep, m_branch, m_proof, new_goals, new_prs));\n s.set_target(mlocal_type(head(new_goals)));\n return action_result::new_branch();\n }\n }\n};\n\naction_result recursor_action(hypothesis_idx hidx, name const & R) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n lean_assert(is_constant(get_app_fn(type)));\n\n recursor_info rec_info = get_recursor_info(env(), R);\n\n if (!rec_info.has_dep_elim() && s.target_depends_on(hidx)) {\n \/\/ recursor does does not support dependent elimination, but conclusion\n \/\/ depends on major premise\n return action_result::failed();\n }\n\n buffer<expr> type_args;\n get_app_args(type, type_args);\n buffer<optional<expr>> params;\n for (optional<unsigned> const & pos : rec_info.get_params_pos()) {\n if (!pos) {\n params.push_back(none_expr());\n } else if (*pos >= type_args.size()) {\n return action_result::failed(); \/\/ major premise type is ill-formed\n } else {\n params.push_back(some_expr(type_args[*pos]));\n }\n }\n\n buffer<expr> indices;\n list<unsigned> const & idx_pos = rec_info.get_indices_pos();\n for (unsigned pos : idx_pos) {\n if (pos >= type_args.size()) {\n return action_result::failed(); \/\/ major premise type is ill-formed\");\n }\n expr const & idx = type_args[pos];\n if (!is_href(idx)) {\n return action_result::failed(); \/\/ argument of major premise type is not a href\n }\n for (unsigned i = 0; i < type_args.size(); i++) {\n if (i != pos && is_local(type_args[i]) && mlocal_name(type_args[i]) == mlocal_name(idx)) {\n return action_result::failed(); \/\/ argument of major premise is an index, but it occurs more than once\n }\n if (i > pos && \/\/ occurs after idx\n std::find(idx_pos.begin(), idx_pos.end(), i) != idx_pos.end() && \/\/ it is also an index\n is_href(type_args[i]) && \/\/ if it is not an index, it will fail anyway.\n s.hidx_depends_on(href_index(idx), href_index(type_args[i]))) {\n \/\/ argument of major premise type is an index, but its type depends on another index\n return action_result::failed();\n }\n }\n indices.push_back(idx);\n }\n\n scope_curr_state save_state;\n hypothesis_idx_buffer_set to_revert;\n s.collect_direct_forward_deps(hidx, to_revert);\n for (auto i : indices)\n s.collect_direct_forward_deps(href_index(i), to_revert);\n revert_action(to_revert);\n\n expr target = s.get_target();\n auto target_level = get_type_context().get_level_core(target);\n if (!target_level) return action_result::failed(); \/\/ failed to extract universe level of target\n\n buffer<level> rec_lvls;\n expr const & I = get_app_fn(type);\n buffer<level> I_lvls;\n to_buffer(const_levels(I), I_lvls);\n bool found_target_lvl = false;\n for (unsigned idx : rec_info.get_universe_pos()) {\n if (idx == recursor_info::get_motive_univ_idx()) {\n rec_lvls.push_back(*target_level);\n found_target_lvl = true;\n } else {\n if (idx >= I_lvls.size())\n return action_result::failed(); \/\/ ill-formed recursor\n rec_lvls.push_back(I_lvls[idx]);\n }\n }\n\n if (!found_target_lvl && !is_zero(*target_level)) {\n \/\/ recursor can only eliminate into Prop\n return action_result::failed();\n }\n expr rec = mk_constant(rec_info.get_name(), to_list(rec_lvls));\n\n for (optional<expr> const & p : params) {\n if (p) {\n rec = mk_app(rec, *p);\n } else {\n \/\/ try type class resolution to synthesize argument\n expr rec_type = relaxed_whnf(infer_type(rec));\n if (!is_pi(rec_type))\n return action_result::failed(); \/\/ ill-formed recursor\n expr arg_type = binding_domain(rec_type);\n if (auto inst = mk_class_instance(arg_type)) {\n rec = mk_app(rec, *inst);\n } else {\n return action_result::failed(); \/\/ failed to generate instance\n }\n }\n }\n\n expr motive = target;\n if (rec_info.has_dep_elim())\n motive = s.mk_lambda(h->get_self(), motive);\n motive = s.mk_lambda(indices, motive);\n rec = mk_app(rec, motive);\n\n expr rec_type = relaxed_whnf(infer_type(rec));\n unsigned curr_pos = params.size() + 1 \/* motive *\/;\n unsigned first_idx_pos = rec_info.get_first_index_pos();\n bool consumed_major = false;\n buffer<expr> new_goals;\n\n while (is_pi(rec_type) && curr_pos < rec_info.get_num_args()) {\n if (first_idx_pos == curr_pos) {\n for (expr const & idx : indices) {\n rec = mk_app(rec, idx);\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), idx));\n if (!is_pi(rec_type))\n return action_result::failed(); \/\/ ill-formed type\n curr_pos++;\n }\n rec = mk_app(rec, h->get_self());\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), h->get_self()));\n consumed_major = true;\n curr_pos++;\n } else {\n expr new_type = binding_domain(rec_type);\n expr rec_arg;\n if (binding_info(rec_type).is_inst_implicit()) {\n auto inst = mk_class_instance(new_type);\n if (!inst) return action_result::failed(); \/\/ type class resolution failed\n rec_arg = *inst;\n } else {\n rec_arg = mk_fresh_local(new_type); \/\/ placeholder\n new_goals.push_back(rec_arg);\n }\n rec = mk_app(rec, rec_arg);\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), rec_arg));\n curr_pos++;\n }\n }\n\n if (curr_pos != rec_info.get_num_args() || !consumed_major)\n return action_result::failed(); \/\/ ill-formed recursor\n\n save_state.commit();\n\n if (new_goals.empty())\n return action_result::solved(rec);\n s.del_hypothesis(hidx);\n s.push_proof_step(new recursor_proof_step_cell(rec_info.has_dep_elim(), s.get_branch(), rec, to_list(new_goals), list<expr>()));\n s.set_target(mlocal_type(new_goals[0]));\n return action_result::new_branch();\n}\n\naction_result recursor_action(hypothesis_idx hidx) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n expr const & I = get_app_fn(type);\n if (!is_constant(I))\n return action_result::failed();\n list<name> Rs = get_recursors_for(env(), const_name(I));\n for (auto R : Rs) {\n auto r = recursor_action(hidx, R);\n if (!failed(r))\n return r;\n }\n return action_result::failed();\n}\n}}\n<commit_msg>feat(library\/blast\/recursor_action): ignore type class instances in the recursor action<commit_after>\/*\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/inductive\/inductive.h\"\n#include \"library\/user_recursors.h\"\n#include \"library\/blast\/revert_action.h\"\n#include \"library\/blast\/blast.h\"\n\nnamespace lean {\nnamespace blast {\noptional<name> is_recursor_action_target(hypothesis_idx hidx) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n if (!is_app(type) && !is_constant(type))\n return optional<name>();\n if (is_relation(type))\n return optional<name>(); \/\/ we don't apply recursors to equivalence relations: =, ~, <->, etc.\n if (!h->is_assumption())\n return optional<name>(); \/\/ we only consider assumptions\n if (get_type_context().is_class(type)) {\n \/\/ we don't eliminate type classes instances\n \/\/ TODO(Leo): we may revise that in the future... some type classes instances may be worth eliminating (e.g., decidable).\n return optional<name>();\n }\n \/\/ TODO(Leo): more restrictions?\n \/\/ TODO(Leo): consider user-provided hints\n expr const & I = get_app_fn(type);\n if (!is_constant(I))\n return optional<name>();\n if (inductive::is_inductive_decl(env(), const_name(I)))\n return optional<name>(name(inductive::get_elim_name(const_name(I)))); \/\/ it is builtin recursive datatype\n list<name> Rs = get_recursors_for(env(), const_name(I));\n if (!Rs)\n return optional<name>();\n else\n return optional<name>(head(Rs)); \/\/ type has user-defined recursors\n}\n\nunsigned get_num_minor_premises(name const & R) {\n return get_recursor_info(env(), R).get_num_minors();\n}\n\nbool is_recursive_recursor(name const & R) {\n return get_recursor_info(env(), R).is_recursive();\n}\n\nstruct recursor_proof_step_cell : public proof_step_cell {\n bool m_dep;\n branch m_branch; \/\/ branch for backtracking\n expr m_proof; \/\/ recursor-application (the position where the goal-proofs are marked by the local constants).\n list<expr> m_goals; \/\/ type of each subgoal\/branch encoded as a local constant\n list<expr> m_goal_proofs; \/\/ proofs generated so far\n\n recursor_proof_step_cell(bool dep, branch const & b, expr const & pr, list<expr> const & goals, list<expr> const & goal_proofs):\n m_dep(dep), m_branch(b), m_proof(pr), m_goals(goals), m_goal_proofs(goal_proofs) {\n }\n\n virtual ~recursor_proof_step_cell() {}\n\n virtual action_result resolve(expr const & pr) const {\n state & s = curr_state();\n s.set_branch(m_branch);\n if (!m_dep) {\n \/\/ It is not a dependent elimination, so if pr did not use new hypothesis,\n \/\/ we don't need to investigate other branches.\n \/\/ This is also a form of non-chronological backtracking.\n expr const & goal = head(m_goals);\n unsigned arity = get_arity(mlocal_type(goal));\n expr it = pr;\n bool skip = true;\n for (unsigned i = 0; i < arity; i++) {\n if (!is_lambda(it)) {\n skip = false;\n break;\n }\n it = binding_body(it);\n if (!closed(it)) {\n skip = false;\n break;\n }\n }\n if (skip) {\n lean_assert(closed(it));\n return action_result::solved(it);\n }\n }\n list<expr> new_goals = tail(m_goals);\n list<expr> new_prs = cons(pr, m_goal_proofs);\n if (empty(new_goals)) {\n buffer<expr> proof_args;\n buffer<expr> gs;\n to_buffer(m_goals, gs);\n expr const & rec = get_app_args(m_proof, proof_args);\n \/\/ update proof_args that are goals with their proofs\n unsigned i = proof_args.size();\n while (i > 0) {\n --i;\n if (!gs.empty() && proof_args[i] == gs.back()) {\n lean_assert(new_prs);\n proof_args[i] = head(new_prs);\n new_prs = tail(new_prs);\n }\n }\n return action_result::solved(mk_app(rec, proof_args));\n } else {\n s.pop_proof_step();\n s.push_proof_step(new recursor_proof_step_cell(m_dep, m_branch, m_proof, new_goals, new_prs));\n s.set_target(mlocal_type(head(new_goals)));\n return action_result::new_branch();\n }\n }\n};\n\naction_result recursor_action(hypothesis_idx hidx, name const & R) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n lean_assert(is_constant(get_app_fn(type)));\n\n recursor_info rec_info = get_recursor_info(env(), R);\n\n if (!rec_info.has_dep_elim() && s.target_depends_on(hidx)) {\n \/\/ recursor does does not support dependent elimination, but conclusion\n \/\/ depends on major premise\n return action_result::failed();\n }\n\n buffer<expr> type_args;\n get_app_args(type, type_args);\n buffer<optional<expr>> params;\n for (optional<unsigned> const & pos : rec_info.get_params_pos()) {\n if (!pos) {\n params.push_back(none_expr());\n } else if (*pos >= type_args.size()) {\n return action_result::failed(); \/\/ major premise type is ill-formed\n } else {\n params.push_back(some_expr(type_args[*pos]));\n }\n }\n\n buffer<expr> indices;\n list<unsigned> const & idx_pos = rec_info.get_indices_pos();\n for (unsigned pos : idx_pos) {\n if (pos >= type_args.size()) {\n return action_result::failed(); \/\/ major premise type is ill-formed\");\n }\n expr const & idx = type_args[pos];\n if (!is_href(idx)) {\n return action_result::failed(); \/\/ argument of major premise type is not a href\n }\n for (unsigned i = 0; i < type_args.size(); i++) {\n if (i != pos && is_local(type_args[i]) && mlocal_name(type_args[i]) == mlocal_name(idx)) {\n return action_result::failed(); \/\/ argument of major premise is an index, but it occurs more than once\n }\n if (i > pos && \/\/ occurs after idx\n std::find(idx_pos.begin(), idx_pos.end(), i) != idx_pos.end() && \/\/ it is also an index\n is_href(type_args[i]) && \/\/ if it is not an index, it will fail anyway.\n s.hidx_depends_on(href_index(idx), href_index(type_args[i]))) {\n \/\/ argument of major premise type is an index, but its type depends on another index\n return action_result::failed();\n }\n }\n indices.push_back(idx);\n }\n\n scope_curr_state save_state;\n hypothesis_idx_buffer_set to_revert;\n s.collect_direct_forward_deps(hidx, to_revert);\n for (auto i : indices)\n s.collect_direct_forward_deps(href_index(i), to_revert);\n revert_action(to_revert);\n\n expr target = s.get_target();\n auto target_level = get_type_context().get_level_core(target);\n if (!target_level) return action_result::failed(); \/\/ failed to extract universe level of target\n\n buffer<level> rec_lvls;\n expr const & I = get_app_fn(type);\n buffer<level> I_lvls;\n to_buffer(const_levels(I), I_lvls);\n bool found_target_lvl = false;\n for (unsigned idx : rec_info.get_universe_pos()) {\n if (idx == recursor_info::get_motive_univ_idx()) {\n rec_lvls.push_back(*target_level);\n found_target_lvl = true;\n } else {\n if (idx >= I_lvls.size())\n return action_result::failed(); \/\/ ill-formed recursor\n rec_lvls.push_back(I_lvls[idx]);\n }\n }\n\n if (!found_target_lvl && !is_zero(*target_level)) {\n \/\/ recursor can only eliminate into Prop\n return action_result::failed();\n }\n expr rec = mk_constant(rec_info.get_name(), to_list(rec_lvls));\n\n for (optional<expr> const & p : params) {\n if (p) {\n rec = mk_app(rec, *p);\n } else {\n \/\/ try type class resolution to synthesize argument\n expr rec_type = relaxed_whnf(infer_type(rec));\n if (!is_pi(rec_type))\n return action_result::failed(); \/\/ ill-formed recursor\n expr arg_type = binding_domain(rec_type);\n if (auto inst = mk_class_instance(arg_type)) {\n rec = mk_app(rec, *inst);\n } else {\n return action_result::failed(); \/\/ failed to generate instance\n }\n }\n }\n\n expr motive = target;\n if (rec_info.has_dep_elim())\n motive = s.mk_lambda(h->get_self(), motive);\n motive = s.mk_lambda(indices, motive);\n rec = mk_app(rec, motive);\n\n expr rec_type = relaxed_whnf(infer_type(rec));\n unsigned curr_pos = params.size() + 1 \/* motive *\/;\n unsigned first_idx_pos = rec_info.get_first_index_pos();\n bool consumed_major = false;\n buffer<expr> new_goals;\n\n while (is_pi(rec_type) && curr_pos < rec_info.get_num_args()) {\n if (first_idx_pos == curr_pos) {\n for (expr const & idx : indices) {\n rec = mk_app(rec, idx);\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), idx));\n if (!is_pi(rec_type))\n return action_result::failed(); \/\/ ill-formed type\n curr_pos++;\n }\n rec = mk_app(rec, h->get_self());\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), h->get_self()));\n consumed_major = true;\n curr_pos++;\n } else {\n expr new_type = binding_domain(rec_type);\n expr rec_arg;\n if (binding_info(rec_type).is_inst_implicit()) {\n auto inst = mk_class_instance(new_type);\n if (!inst) return action_result::failed(); \/\/ type class resolution failed\n rec_arg = *inst;\n } else {\n rec_arg = mk_fresh_local(new_type); \/\/ placeholder\n new_goals.push_back(rec_arg);\n }\n rec = mk_app(rec, rec_arg);\n rec_type = relaxed_whnf(instantiate(binding_body(rec_type), rec_arg));\n curr_pos++;\n }\n }\n\n if (curr_pos != rec_info.get_num_args() || !consumed_major)\n return action_result::failed(); \/\/ ill-formed recursor\n\n save_state.commit();\n\n if (new_goals.empty())\n return action_result::solved(rec);\n s.del_hypothesis(hidx);\n s.push_proof_step(new recursor_proof_step_cell(rec_info.has_dep_elim(), s.get_branch(), rec, to_list(new_goals), list<expr>()));\n s.set_target(mlocal_type(new_goals[0]));\n return action_result::new_branch();\n}\n\naction_result recursor_action(hypothesis_idx hidx) {\n state & s = curr_state();\n hypothesis const * h = s.get_hypothesis_decl(hidx);\n lean_assert(h);\n expr const & type = h->get_type();\n expr const & I = get_app_fn(type);\n if (!is_constant(I))\n return action_result::failed();\n list<name> Rs = get_recursors_for(env(), const_name(I));\n for (auto R : Rs) {\n auto r = recursor_action(hidx, R);\n if (!failed(r))\n return r;\n }\n return action_result::failed();\n}\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FastMETISParser.cpp\n *\n * Created on: 04.10.2013\n * Author: cls\n *\/\n\n#include \"FastMETISParser.h\"\n\n#include <fstream>\n\nnamespace NetworKit {\n\nFastMETISParser::FastMETISParser() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nFastMETISParser::~FastMETISParser() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nstatic inline node fast_string_to_node(std::string::iterator it, const std::string::iterator& end) {\n\tnode val = *it - '0';\t\/\/ works on ASCII code points\n\t++it;\n\twhile (it != end) {\n\t\tval *= 10;\n\t\tval += *it - '0';\n\t\t++it;\n\t}\n\treturn val;\n}\n\nstatic inline std::tuple<count, count, int> parseHeader(const std::string& header) {\n\tcount n;\n\tcount m;\n\tint flag;\n\n\tstd::vector<std::string> parts = Aux::StringTools::split(header);\n\tn = std::stoi(parts[0]);\n\tm = std::stoi(parts[1]);\n\tflag = std::stoi(parts[2]);\n\n\treturn std::make_tuple(n, m, flag);\n}\n\n\nNetworKit::Graph FastMETISParser::parse(const std::string& path) {\n\tstd::ifstream stream(path);\n\tstd::string line;\n\tstd::getline(stream, line); \/\/ get header\n\tcount n;\n\tcount m;\n\tint flag; \/\/ weight flag\n\tstd::tie(n, m, flag) = parseHeader(line);\n\tGraph G(n);\n\tnode u = 0;\n\twhile(std::getline(stream, line)) {\n\t\t++u;\n\t\tif(line.empty()){\n\t\t\tcontinue;\n\t\t}\n\t\tauto it1 = line.begin();\n\t\tauto end = line.end();\n\t\tauto it2 = std::find(it1, end, ' ');\n\t\tif (line.back() == ' ') { \/\/ if line ends with one white space, do this trick...\n\t\t\t--end;\n\t\t}\n\t\twhile(true) {\n\t\t\tnode v = fast_string_to_node(it1, it2);\n\t\t\tif (u < v) {\n\t\t\t\tG.addEdge(u, v);\n\t\t\t}\n\t\t\tif(it2 == end) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++it2;\n\t\t\tit1 = it2;\n\t\t\tit2 = std::find(it1, end, ' ');\n\t\t}\n\t}\n\treturn G;\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>minor edits on FastMETISParser<commit_after>\/*\n * FastMETISParser.cpp\n *\n * Created on: 04.10.2013\n * Author: cls\n *\/\n\n#include \"FastMETISParser.h\"\n\n#include <fstream>\n\nnamespace NetworKit {\n\nFastMETISParser::FastMETISParser() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nFastMETISParser::~FastMETISParser() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nstatic inline node fast_string_to_node(std::string::iterator it, const std::string::iterator& end) {\n\tnode val = *it - '0';\t\/\/ works on ASCII code points\n\t++it;\n\twhile (it != end) {\n\t\tval *= 10;\n\t\tval += *it - '0';\n\t\t++it;\n\t}\n\treturn val;\n}\n\nstatic inline std::tuple<count, count, int> parseHeader(const std::string& header) {\n\tcount n;\n\tcount m;\n\tint flag;\n\n\tstd::vector<std::string> parts = Aux::StringTools::split(header);\n\tn = std::stoi(parts[0]);\n\tm = std::stoi(parts[1]);\n\tif (parts.size > 2) {\n\t\tflag = std::stoi(parts[2]);\n\t} else {\n\t\tflag = 0;\n\t}\n\n\n\treturn std::make_tuple(n, m, flag);\n}\n\n\nNetworKit::Graph FastMETISParser::parse(const std::string& path) {\n\tstd::ifstream stream(path);\n\tstd::string line;\n\tstd::getline(stream, line); \/\/ get header\n\tcount n;\n\tcount m;\n\tint flag; \/\/ weight flag\n\tstd::tie(n, m, flag) = parseHeader(line);\n\tGraph G(n);\n\tnode u = 0;\n\n\tif (flag == 0) {\n\t\twhile (std::getline(stream, line)) {\n\t\t\t++u;\n\t\t\tif (line.empty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto it1 = line.begin();\n\t\t\tauto end = line.end();\n\t\t\tauto it2 = std::find(it1, end, ' ');\n\t\t\tif (line.back() == ' ') { \/\/ if line ends with one white space, do this trick...\n\t\t\t\t--end;\n\t\t\t}\n\t\t\twhile (true) {\n\t\t\t\tnode v = fast_string_to_node(it1, it2);\n\t\t\t\tif (u < v) {\n\t\t\t\t\tG.addEdge(u, v);\n\t\t\t\t}\n\t\t\t\tif (it2 == end) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t++it2;\n\t\t\t\tit1 = it2;\n\t\t\t\tit2 = std::find(it1, end, ' ');\n\t\t\t}\n\t\t}\n\t} else {\n\t\tERROR(\"parsing graphs with weight flag \" << flag << \" not yet supported\");\n\t\texit(1);\n\t}\n\n\n\treturn G;\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"src\/report_aggregator_impl.h\"\n#include \"src\/signature.h\"\n\n#include \"google\/protobuf\/stubs\/logging.h\"\n\nusing std::string;\nusing ::google::api::MetricDescriptor;\nusing ::google::api::servicecontrol::v1::Operation;\nusing ::google::api::servicecontrol::v1::ReportRequest;\nusing ::google::api::servicecontrol::v1::ReportResponse;\nusing ::google::protobuf::util::Status;\nusing ::google::protobuf::util::error::Code;\n\nnamespace google {\nnamespace service_control_client {\nnamespace {\n\n\/\/ A report can carry many operations, merge multiple report requests\n\/\/ into one report request until its number of operations reach this limit.\nconst int kMaxOperationsToSend = 1000;\n\n\/\/ Returns whether the given report request has high value operations.\nbool HasHighImportantOperation(const ReportRequest& request) {\n for (const auto& operation : request.operations()) {\n if (operation.importance() != Operation::LOW) {\n return true;\n }\n }\n return false;\n}\n\n} \/\/ namespace\n\nReportAggregatorImpl::ReportAggregatorImpl(\n const string& service_name, const std::string& service_config_id,\n const ReportAggregationOptions& options,\n std::shared_ptr<MetricKindMap> metric_kinds)\n : service_name_(service_name),\n service_config_id_(service_config_id),\n options_(options),\n metric_kinds_(metric_kinds) {\n if (options.num_entries > 0) {\n cache_.reset(\n new ReportCache(options.num_entries,\n std::bind(&ReportAggregatorImpl::OnCacheEntryDelete,\n this, std::placeholders::_1)));\n cache_->SetAgeBasedEviction(options.flush_interval_ms \/ 1000.0);\n }\n}\n\nReportAggregatorImpl::~ReportAggregatorImpl() {\n \/\/ FlushAll() is a blocking call to remove all cache items.\n \/\/ For each removed item, it will call flush_callback().\n \/\/ At the destructor, it is better not to call the callback.\n SetFlushCallback(NULL);\n FlushAll();\n}\n\n\/\/ Set the flush callback function.\nvoid ReportAggregatorImpl::SetFlushCallback(FlushCallback callback) {\n InternalSetFlushCallback(callback);\n}\n\n\/\/ Add a report request to cache\nStatus ReportAggregatorImpl::Report(\n const ::google::api::servicecontrol::v1::ReportRequest& request) {\n if (request.service_name() != service_name_) {\n return Status(Code::INVALID_ARGUMENT,\n (string(\"Invalid service name: \") + request.service_name() +\n string(\" Expecting: \") + service_name_));\n }\n if (HasHighImportantOperation(request) || !cache_) {\n \/\/ By returning NO_FOUND, caller will send request to server.\n return Status(Code::NOT_FOUND, \"\");\n }\n\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n\n \/\/ Starts to cache and aggregate low important operations.\n for (const auto& operation : request.operations()) {\n string signature = GenerateReportOperationSignature(operation);\n\n ReportCache::ScopedLookup lookup(cache_.get(), signature);\n if (lookup.Found()) {\n lookup.value()->MergeOperation(operation);\n } else {\n OperationAggregator* iop =\n new OperationAggregator(operation, metric_kinds_.get());\n cache_->Insert(signature, iop, 1);\n }\n }\n return Status::OK;\n}\n\nvoid ReportAggregatorImpl::OnCacheEntryDelete(OperationAggregator* iop) {\n \/\/ iop or cache is under projected. This function is only called when\n \/\/ cache::Insert() or cache::Removed() is called and these operations\n \/\/ are already protected by cache_mutex.\n ReportRequest request;\n request.set_service_name(service_name_);\n request.set_service_config_id(service_config_id_);\n \/\/ TODO(qiwzhang): Remove this copy\n *(request.add_operations()) = iop->ToOperationProto();\n delete iop;\n\n AddRemovedItem(request);\n}\n\nbool ReportAggregatorImpl::MergeItem(const ReportRequest& new_item,\n ReportRequest* old_item) {\n if (old_item->service_name() != new_item.service_name() ||\n old_item->operations().size() + new_item.operations().size() >\n kMaxOperationsToSend) {\n return false;\n }\n old_item->MergeFrom(new_item);\n return true;\n}\n\n\/\/ When the next Flush() should be called.\n\/\/ Return in ms from now, or -1 for never\nint ReportAggregatorImpl::GetNextFlushInterval() {\n if (!cache_) return -1;\n return options_.flush_interval_ms;\n}\n\n\/\/ Flush aggregated requests whom are longer than flush_interval.\n\/\/ Called at time specified by GetNextFlushInterval().\nStatus ReportAggregatorImpl::Flush() {\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n if (cache_) {\n cache_->RemoveExpiredEntries();\n }\n return Status::OK;\n}\n\n\/\/ Flush out aggregated report requests, clear all cache items.\n\/\/ Usually called at destructor.\nStatus ReportAggregatorImpl::FlushAll() {\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n GOOGLE_LOG(INFO) << \"Remove all entries of report aggregator.\";\n if (cache_) {\n cache_->RemoveAll();\n }\n return Status::OK;\n}\n\nstd::unique_ptr<ReportAggregator> CreateReportAggregator(\n const std::string& service_name, const std::string& service_config_id,\n const ReportAggregationOptions& options,\n std::shared_ptr<MetricKindMap> metric_kind) {\n return std::unique_ptr<ReportAggregator>(new ReportAggregatorImpl(\n service_name, service_config_id, options, metric_kind));\n}\n\n} \/\/ namespace service_control_client\n} \/\/ namespace google\n<commit_msg>Reduce kMaxOperationsToSend from to 100 so its size is within 1MB limit<commit_after>\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"src\/report_aggregator_impl.h\"\n#include \"src\/signature.h\"\n\n#include \"google\/protobuf\/stubs\/logging.h\"\n\nusing std::string;\nusing ::google::api::MetricDescriptor;\nusing ::google::api::servicecontrol::v1::Operation;\nusing ::google::api::servicecontrol::v1::ReportRequest;\nusing ::google::api::servicecontrol::v1::ReportResponse;\nusing ::google::protobuf::util::Status;\nusing ::google::protobuf::util::error::Code;\n\nnamespace google {\nnamespace service_control_client {\nnamespace {\n\n\/\/ A report can carry many operations, merge multiple report requests\n\/\/ into one report request until its number of operations reach this limit.\n\/\/ Each report is about 4KB now. Maximum allowed size from server is 1MB.\nconst int kMaxOperationsToSend = 100;\n\n\/\/ Returns whether the given report request has high value operations.\nbool HasHighImportantOperation(const ReportRequest& request) {\n for (const auto& operation : request.operations()) {\n if (operation.importance() != Operation::LOW) {\n return true;\n }\n }\n return false;\n}\n\n} \/\/ namespace\n\nReportAggregatorImpl::ReportAggregatorImpl(\n const string& service_name, const std::string& service_config_id,\n const ReportAggregationOptions& options,\n std::shared_ptr<MetricKindMap> metric_kinds)\n : service_name_(service_name),\n service_config_id_(service_config_id),\n options_(options),\n metric_kinds_(metric_kinds) {\n if (options.num_entries > 0) {\n cache_.reset(\n new ReportCache(options.num_entries,\n std::bind(&ReportAggregatorImpl::OnCacheEntryDelete,\n this, std::placeholders::_1)));\n cache_->SetAgeBasedEviction(options.flush_interval_ms \/ 1000.0);\n }\n}\n\nReportAggregatorImpl::~ReportAggregatorImpl() {\n \/\/ FlushAll() is a blocking call to remove all cache items.\n \/\/ For each removed item, it will call flush_callback().\n \/\/ At the destructor, it is better not to call the callback.\n SetFlushCallback(NULL);\n FlushAll();\n}\n\n\/\/ Set the flush callback function.\nvoid ReportAggregatorImpl::SetFlushCallback(FlushCallback callback) {\n InternalSetFlushCallback(callback);\n}\n\n\/\/ Add a report request to cache\nStatus ReportAggregatorImpl::Report(\n const ::google::api::servicecontrol::v1::ReportRequest& request) {\n if (request.service_name() != service_name_) {\n return Status(Code::INVALID_ARGUMENT,\n (string(\"Invalid service name: \") + request.service_name() +\n string(\" Expecting: \") + service_name_));\n }\n if (HasHighImportantOperation(request) || !cache_) {\n \/\/ By returning NO_FOUND, caller will send request to server.\n return Status(Code::NOT_FOUND, \"\");\n }\n\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n\n \/\/ Starts to cache and aggregate low important operations.\n for (const auto& operation : request.operations()) {\n string signature = GenerateReportOperationSignature(operation);\n\n ReportCache::ScopedLookup lookup(cache_.get(), signature);\n if (lookup.Found()) {\n lookup.value()->MergeOperation(operation);\n } else {\n OperationAggregator* iop =\n new OperationAggregator(operation, metric_kinds_.get());\n cache_->Insert(signature, iop, 1);\n }\n }\n return Status::OK;\n}\n\nvoid ReportAggregatorImpl::OnCacheEntryDelete(OperationAggregator* iop) {\n \/\/ iop or cache is under projected. This function is only called when\n \/\/ cache::Insert() or cache::Removed() is called and these operations\n \/\/ are already protected by cache_mutex.\n ReportRequest request;\n request.set_service_name(service_name_);\n request.set_service_config_id(service_config_id_);\n \/\/ TODO(qiwzhang): Remove this copy\n *(request.add_operations()) = iop->ToOperationProto();\n delete iop;\n\n AddRemovedItem(request);\n}\n\nbool ReportAggregatorImpl::MergeItem(const ReportRequest& new_item,\n ReportRequest* old_item) {\n if (old_item->service_name() != new_item.service_name() ||\n old_item->operations().size() + new_item.operations().size() >\n kMaxOperationsToSend) {\n return false;\n }\n old_item->MergeFrom(new_item);\n return true;\n}\n\n\/\/ When the next Flush() should be called.\n\/\/ Return in ms from now, or -1 for never\nint ReportAggregatorImpl::GetNextFlushInterval() {\n if (!cache_) return -1;\n return options_.flush_interval_ms;\n}\n\n\/\/ Flush aggregated requests whom are longer than flush_interval.\n\/\/ Called at time specified by GetNextFlushInterval().\nStatus ReportAggregatorImpl::Flush() {\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n if (cache_) {\n cache_->RemoveExpiredEntries();\n }\n return Status::OK;\n}\n\n\/\/ Flush out aggregated report requests, clear all cache items.\n\/\/ Usually called at destructor.\nStatus ReportAggregatorImpl::FlushAll() {\n ReportCacheRemovedItemsHandler::StackBuffer stack_buffer(this);\n MutexLock lock(cache_mutex_);\n ReportCacheRemovedItemsHandler::StackBuffer::Swapper swapper(this,\n &stack_buffer);\n GOOGLE_LOG(INFO) << \"Remove all entries of report aggregator.\";\n if (cache_) {\n cache_->RemoveAll();\n }\n return Status::OK;\n}\n\nstd::unique_ptr<ReportAggregator> CreateReportAggregator(\n const std::string& service_name, const std::string& service_config_id,\n const ReportAggregationOptions& options,\n std::shared_ptr<MetricKindMap> metric_kind) {\n return std::unique_ptr<ReportAggregator>(new ReportAggregatorImpl(\n service_name, service_config_id, options, metric_kind));\n}\n\n} \/\/ namespace service_control_client\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/server\/Agent.cc\n *\n * Copyright (C) 2008 by OpenCog Foundation\n * All Rights Reserved\n *\n * Written by Gustavo Gama <gama@vettalabs.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"Agent.h\"\n\n#include <opencog\/server\/CogServer.h>\n#include <opencog\/util\/Config.h>\n\nusing namespace opencog;\n\nAgent::Agent(CogServer& cs, const unsigned int f) : _cogserver(cs), _frequency(f)\n{\n \/\/ an empty set of parameters and defaults (so that various\n \/\/ methods will still work even if none are set in this or a derived\n \/\/ class)\n static const std::string defaultConfig[] = {\n \"\", \"\"\n };\n setParameters(defaultConfig);\n\n stimulatedAtoms = new AtomStimHashMap();\n totalStimulus = 0;\n\n conn = _cogserver.getAtomSpace().atomSpaceAsync->removeAtomSignal(\n boost::bind(&Agent::atomRemoved, this, _1, _2));\n}\n\nAgent::~Agent()\n{\n \/\/ give back funds\n _cogserver.getAtomSpace().getAttentionBank().setSTI(AttentionValueHolderPtr(this), 0);\n _cogserver.getAtomSpace().getAttentionBank().setLTI(AttentionValueHolderPtr(this), 0);\n\n resetUtilizedHandleSets();\n delete stimulatedAtoms;\n conn.disconnect();\n}\n\nvoid Agent::setParameters(const std::string* params)\n{\n PARAMETERS = params;\n\n for (unsigned int i = 0; params[i] != \"\"; i += 2) {\n if (!config().has(params[i])) {\n config().set(params[i], params[i + 1]);\n }\n }\n}\n\nstd::string Agent::to_string() const\n{\n std::ostringstream oss;\n oss << classinfo().id;\n oss << \" {\\\"\";\n for (unsigned int i = 0; PARAMETERS[i] != \"\"; i += 2) {\n if (i != 0) oss << \"\\\", \\\"\";\n oss << PARAMETERS[i] << \"\\\" => \\\"\" << config()[PARAMETERS[i]];\n }\n oss << \"\\\"}\";\n return oss.str();\n}\n\nvoid Agent::atomRemoved(AtomSpaceImpl* a, Handle h)\n{\n for (size_t i = 0; i < _utilizedHandleSets.size(); i++)\n _utilizedHandleSets[i].erase(h);\n removeAtomStimulus(h);\n}\n\nvoid Agent::resetUtilizedHandleSets()\n{\n for (size_t i = 0; i < _utilizedHandleSets.size(); i++)\n _utilizedHandleSets[i].clear();\n _utilizedHandleSets.clear();\n}\n\n\nstim_t Agent::stimulateAtom(Handle h, stim_t amount)\n{\n \/\/ Add atom to the map of atoms with stimulus\n \/\/ and add stimulus to it\n (*stimulatedAtoms)[h] += amount;\n\n \/\/ update record of total stimulus given out\n totalStimulus += amount;\n \/\/logger().fine(\"%d added to totalStimulus, now %d\", amount, totalStimulus);\n return totalStimulus;\n}\n\nvoid Agent::removeAtomStimulus(Handle h)\n{\n stim_t amount;\n \/\/ if handle not in map then return\n if (stimulatedAtoms->find(h) == stimulatedAtoms->end())\n return;\n\n amount = (*stimulatedAtoms)[h];\n stimulatedAtoms->erase(h);\n\n \/\/ update record of total stimulus given out\n totalStimulus -= amount;\n}\n\nstim_t Agent::stimulateAtom(HandleSeq hs, stim_t amount)\n{\n stim_t split;\n\n \/\/ how much to give each atom\n split = amount \/ hs.size();\n\n foreach(Handle handle, hs) {\n stimulateAtom(handle, split);\n }\n \/\/ return unused stimulus\n return amount - (split * hs.size());\n}\n\nstim_t Agent::resetStimulus()\n{\n stimulatedAtoms->clear();\n \/\/ reset stimulus counter\n totalStimulus = 0;\n return totalStimulus;\n}\n\nstim_t Agent::getTotalStimulus() const\n{\n return totalStimulus;\n}\n\nstim_t Agent::getAtomStimulus(Handle h) const\n{\n if (stimulatedAtoms->find(h) == stimulatedAtoms->end()) {\n return 0;\n } else {\n return (*stimulatedAtoms)[h];\n }\n}\n\n<commit_msg>bugfix: cannot reference shared_ptr(this)<commit_after>\/*\n * opencog\/server\/Agent.cc\n *\n * Copyright (C) 2008 by OpenCog Foundation\n * All Rights Reserved\n *\n * Written by Gustavo Gama <gama@vettalabs.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"Agent.h\"\n\n#include <opencog\/server\/CogServer.h>\n#include <opencog\/util\/Config.h>\n\nusing namespace opencog;\n\nAgent::Agent(CogServer& cs, const unsigned int f) : _cogserver(cs), _frequency(f)\n{\n \/\/ an empty set of parameters and defaults (so that various\n \/\/ methods will still work even if none are set in this or a derived\n \/\/ class)\n static const std::string defaultConfig[] = {\n \"\", \"\"\n };\n setParameters(defaultConfig);\n\n stimulatedAtoms = new AtomStimHashMap();\n totalStimulus = 0;\n\n conn = _cogserver.getAtomSpace().atomSpaceAsync->removeAtomSignal(\n boost::bind(&Agent::atomRemoved, this, _1, _2));\n}\n\nAgent::~Agent()\n{\n \/\/ give back funds\n _cogserver.getAtomSpace().getAttentionBank().updateSTIFunds(getAttentionValue().getSTI());\n _cogserver.getAtomSpace().getAttentionBank().updateLTIFunds(getAttentionValue().getLTI());\n\n resetUtilizedHandleSets();\n conn.disconnect();\n delete stimulatedAtoms;\n}\n\nvoid Agent::setParameters(const std::string* params)\n{\n PARAMETERS = params;\n\n for (unsigned int i = 0; params[i] != \"\"; i += 2) {\n if (!config().has(params[i])) {\n config().set(params[i], params[i + 1]);\n }\n }\n}\n\nstd::string Agent::to_string() const\n{\n std::ostringstream oss;\n oss << classinfo().id;\n oss << \" {\\\"\";\n for (unsigned int i = 0; PARAMETERS[i] != \"\"; i += 2) {\n if (i != 0) oss << \"\\\", \\\"\";\n oss << PARAMETERS[i] << \"\\\" => \\\"\" << config()[PARAMETERS[i]];\n }\n oss << \"\\\"}\";\n return oss.str();\n}\n\nvoid Agent::atomRemoved(AtomSpaceImpl* a, Handle h)\n{\n for (size_t i = 0; i < _utilizedHandleSets.size(); i++)\n _utilizedHandleSets[i].erase(h);\n removeAtomStimulus(h);\n}\n\nvoid Agent::resetUtilizedHandleSets()\n{\n for (size_t i = 0; i < _utilizedHandleSets.size(); i++)\n _utilizedHandleSets[i].clear();\n _utilizedHandleSets.clear();\n}\n\n\nstim_t Agent::stimulateAtom(Handle h, stim_t amount)\n{\n \/\/ Add atom to the map of atoms with stimulus\n \/\/ and add stimulus to it\n (*stimulatedAtoms)[h] += amount;\n\n \/\/ update record of total stimulus given out\n totalStimulus += amount;\n \/\/logger().fine(\"%d added to totalStimulus, now %d\", amount, totalStimulus);\n return totalStimulus;\n}\n\nvoid Agent::removeAtomStimulus(Handle h)\n{\n stim_t amount;\n \/\/ if handle not in map then return\n if (stimulatedAtoms->find(h) == stimulatedAtoms->end())\n return;\n\n amount = (*stimulatedAtoms)[h];\n stimulatedAtoms->erase(h);\n\n \/\/ update record of total stimulus given out\n totalStimulus -= amount;\n}\n\nstim_t Agent::stimulateAtom(HandleSeq hs, stim_t amount)\n{\n stim_t split;\n\n \/\/ how much to give each atom\n split = amount \/ hs.size();\n\n foreach(Handle handle, hs) {\n stimulateAtom(handle, split);\n }\n \/\/ return unused stimulus\n return amount - (split * hs.size());\n}\n\nstim_t Agent::resetStimulus()\n{\n stimulatedAtoms->clear();\n \/\/ reset stimulus counter\n totalStimulus = 0;\n return totalStimulus;\n}\n\nstim_t Agent::getTotalStimulus() const\n{\n return totalStimulus;\n}\n\nstim_t Agent::getAtomStimulus(Handle h) const\n{\n if (stimulatedAtoms->find(h) == stimulatedAtoms->end()) {\n return 0;\n } else {\n return (*stimulatedAtoms)[h];\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"TextureAtlas.hpp\"\n#include \"vec.hpp\"\n\nusing namespace rffalcon;\n\nTextureAtlas::TextureAtlas(const int width, const int height, const int depth) \n\t: _width(width), _height(height), _depth(depth)\n{\n\t\/\/ starter node for fitting algorithm\n\t\/\/ contains padding in atlas to avoid sampling artifacts\n\trffalcon::ivec3 paddingNode = { { 1, 1, width - 2 } };\n\t_nodes.push_back(paddingNode);\n\t_data = new unsigned char[width * height * depth];\n}\n\n\nTextureAtlas::~TextureAtlas()\n{\n\tdelete [] _data;\n\t_data = nullptr;\n}\n\nint TextureAtlas::getWidth() const\n{\n\treturn _width;\n}\n\nint TextureAtlas::getHeight() const\n{\n\treturn _height;\n}\n\nint TextureAtlas::getDepth() const\n{\n\treturn _depth;\n}\n\nGLuint TextureAtlas::getGLTextureId() const\n{\n\treturn _glTextureId;\n}\n\nrffalcon::ivec4 TextureAtlas::getRegion(const int width, const int height)\n{\n\tint bestY = INT_MAX;\n\tint bestWidth = INT_MAX;\n\tint bestIndex = -1;\n\tsize_t nodeCount = _nodes.size();\n\trffalcon::ivec4 region = { { -1, -1, width, height } };\n\n\tfor (size_t index = 0; index < nodeCount; ++index)\n\t{\n\t\tint y = _fit(index, width, height);\n\t\tif (y >= 0) {\n\t\t\trffalcon::ivec3 node = _nodes[index];\n\t\t\tif (y < bestY || (y == bestY && node.width < bestWidth))\n\t\t\t{\n\t\t\t\tbestY = y;\n\t\t\t\tbestIndex = index;\n\t\t\t\tbestWidth = node.width;\n\t\t\t\tregion.x = node.x;\n\t\t\t\tregion.y = node.yNext;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (bestIndex != -1)\n\t{\n\t\t_addNode(region, bestIndex);\n\t\t_reduceNodes(bestIndex);\n\t\t_mergeNodes();\n\t}\n\n\treturn region;\n}\n\n\/\/ Add node to envelope\nvoid TextureAtlas::_addNode(rffalcon::ivec4 region, int index)\n{\n\trffalcon::ivec3 node;\n\tnode.x = region.x;\n\tnode.yNext = region.y + region.height;\n\tnode.width = region.width;\n\t_nodes.insert(_nodes.begin() + index, node);\n}\n\n\/\/ Remove nodes that are no longer part of the envelope\nvoid TextureAtlas::_reduceNodes(int startIndex)\n{\n\tfor (size_t index = startIndex + 1; index < _nodes.size(); ++index)\n\t{\n\t\trffalcon::ivec3 curNode = _nodes[index];\n\t\trffalcon::ivec3 prevNode = _nodes[index - 1];\n\t\tif (curNode.x < (prevNode.x + prevNode.width))\n\t\t{\n\t\t\t_nodes.erase(_nodes.begin() + index);\n\t\t\tint widthReduction = prevNode.x + prevNode.width - curNode.x;\n\t\t\tcurNode.width -= widthReduction;\n\t\t\tif (curNode.width <= 0)\n\t\t\t{\n\t\t\t\t--index;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurNode.x += widthReduction;\n\t\t\t\t_nodes.insert(_nodes.begin() + index, curNode);\n\t\t\t\t\/\/ reduced width of the curNode, rest of envelope will be unaffected\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ rest of envelope unaffected\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/ Merge adjacent nodes on the envelope that have the same yNext value\nvoid TextureAtlas::_mergeNodes()\n{\n\tfor (size_t index = 0; index < _nodes.size() - 1; ++index)\n\t{\n\t\trffalcon::ivec3 curNode = _nodes[index];\n\t\trffalcon::ivec3 nextNode = _nodes[index + 1];\n\t\tif (curNode.yNext == nextNode.yNext)\n\t\t{\n\t\t\tcurNode.width += nextNode.width;\n\t\t\t_nodes.erase(_nodes.begin() + index + 1);\n\t\t\t--index;\n\t\t}\n\t}\n}\n\nint TextureAtlas::_fit(const int index, const int width, const int height)\n{\n\trffalcon::ivec3 node = _nodes[index];\n\tint x = node.x;\n\tint y = node.y;\n\tint widthLeft = width;\n\tint curIndex = index;\n\tint result = -1;\n\t\n\t\/\/ if adding this node left-aligned to the node at the index\n\t\/\/ would not go outside right edge of the texture\n\tif ((x + width) <= (_width - 1))\n\t{\n\t\t\/\/ move the new node's y position to the envelope\n\t\ty = node.yNext;\n\t\t\/\/ while this node might collide with the envelope in the x direction\n\t\twhile (widthLeft > 0)\n\t\t{\n\t\t\tnode = _nodes[curIndex];\n\t\t\t\/\/ if the new node collides with the envelope in the x direction\n\t\t\tif (node.yNext > y)\n\t\t\t{\n\t\t\t\t\/\/ push the new node down to the envelope\n\t\t\t\ty = node.yNext;\n\t\t\t}\n\n\t\t\t\/\/ if adding this node would not go outside the bottom edge of the texture\n\t\t\tif ((y + height) <= (_height - 1))\n\t\t\t{\n\t\t\t\twidthLeft -= node.width;\n\t\t\t\t++curIndex;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ No room to add the new node below the index node\n\t\t\t\ty = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tresult = y;\n\t}\n\n\treturn result;\n}\n\nvoid TextureAtlas::setRegion(rffalcon::ivec4 region, GlyphData glyphData)\n{\n\tint depth = getDepth();\n\tint width = getWidth();\n\tint charSize = sizeof(char);\n\tfor (int i = 0; i < glyphData.height; ++i)\n\t{\n\t\tmemcpy(_data + ((region.y + i) * width + region.x) * charSize * depth,\n\t\t\t _data + (i * glyphData.pitch * charSize), width * charSize * depth);\n\t}\n\t\n}\n\nvoid TextureAtlas::upload()\n{\n\tif (_glTextureId == 0)\n\t{\n\t\tglGenTextures(1, &_glTextureId);\n\t}\n\n\tglBindTexture(GL_TEXTURE_2D, _glTextureId);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tGLenum pixelDataType;\n\tGLint internalFormat;\n\tGLenum format;\n\tif (_depth == 4)\n\t{\n#ifdef GL_UNSIGNED_INT_8_8_8_8_REV\n\t\tpixelDataType = GL_UNSIGNED_INT_8_8_8_8_REV;\n\t\tformat = GL_BGRA;\n#else\n\t\tpixelDataType = GL_UNSIGNED_BYTE;\n\t\tformat = GL_RGBA;\n#endif\n\t\tinternalFormat = GL_RGBA;\n\t}\n\telse {\n\t\tpixelDataType = GL_UNSIGNED_BYTE;\n\t\tformat = internalFormat = (_depth == 3) ? GL_RGB : GL_RED;\n\t}\n\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat, _width, _height, 0, format, pixelDataType, _data);\n}<commit_msg>Copying texture data more correctly<commit_after>#include \"TextureAtlas.hpp\"\n#include \"vec.hpp\"\n\nusing namespace rffalcon;\n\nTextureAtlas::TextureAtlas(const int width, const int height, const int depth) \n\t: _width(width), _height(height), _depth(depth)\n{\n\t\/\/ starter node for fitting algorithm\n\t\/\/ contains padding in atlas to avoid sampling artifacts\n\trffalcon::ivec3 paddingNode = { { 1, 1, width - 2 } };\n\t_nodes.push_back(paddingNode);\n\t_data = new unsigned char[width * height * depth];\n}\n\n\nTextureAtlas::~TextureAtlas()\n{\n\tdelete [] _data;\n\t_data = nullptr;\n}\n\nint TextureAtlas::getWidth() const\n{\n\treturn _width;\n}\n\nint TextureAtlas::getHeight() const\n{\n\treturn _height;\n}\n\nint TextureAtlas::getDepth() const\n{\n\treturn _depth;\n}\n\nGLuint TextureAtlas::getGLTextureId() const\n{\n\treturn _glTextureId;\n}\n\nrffalcon::ivec4 TextureAtlas::getRegion(const int width, const int height)\n{\n\tint bestY = INT_MAX;\n\tint bestWidth = INT_MAX;\n\tint bestIndex = -1;\n\tsize_t nodeCount = _nodes.size();\n\trffalcon::ivec4 region = { { -1, -1, width, height } };\n\n\tfor (size_t index = 0; index < nodeCount; ++index)\n\t{\n\t\tint y = _fit(index, width, height);\n\t\tif (y >= 0) {\n\t\t\trffalcon::ivec3 node = _nodes[index];\n\t\t\tif (y < bestY || (y == bestY && node.width < bestWidth))\n\t\t\t{\n\t\t\t\tbestY = y;\n\t\t\t\tbestIndex = index;\n\t\t\t\tbestWidth = node.width;\n\t\t\t\tregion.x = node.x;\n\t\t\t\tregion.y = node.yNext;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (bestIndex != -1)\n\t{\n\t\t_addNode(region, bestIndex);\n\t\t_reduceNodes(bestIndex);\n\t\t_mergeNodes();\n\t}\n\n\treturn region;\n}\n\n\/\/ Add node to envelope\nvoid TextureAtlas::_addNode(rffalcon::ivec4 region, int index)\n{\n\trffalcon::ivec3 node;\n\tnode.x = region.x;\n\tnode.yNext = region.y + region.height;\n\tnode.width = region.width;\n\t_nodes.insert(_nodes.begin() + index, node);\n}\n\n\/\/ Remove nodes that are no longer part of the envelope\nvoid TextureAtlas::_reduceNodes(int startIndex)\n{\n\tfor (size_t index = startIndex + 1; index < _nodes.size(); ++index)\n\t{\n\t\trffalcon::ivec3 curNode = _nodes[index];\n\t\trffalcon::ivec3 prevNode = _nodes[index - 1];\n\t\tif (curNode.x < (prevNode.x + prevNode.width))\n\t\t{\n\t\t\t_nodes.erase(_nodes.begin() + index);\n\t\t\tint widthReduction = prevNode.x + prevNode.width - curNode.x;\n\t\t\tcurNode.width -= widthReduction;\n\t\t\tif (curNode.width <= 0)\n\t\t\t{\n\t\t\t\t--index;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurNode.x += widthReduction;\n\t\t\t\t_nodes.insert(_nodes.begin() + index, curNode);\n\t\t\t\t\/\/ reduced width of the curNode, rest of envelope will be unaffected\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ rest of envelope unaffected\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/ Merge adjacent nodes on the envelope that have the same yNext value\nvoid TextureAtlas::_mergeNodes()\n{\n\tfor (size_t index = 0; index < _nodes.size() - 1; ++index)\n\t{\n\t\trffalcon::ivec3 curNode = _nodes[index];\n\t\trffalcon::ivec3 nextNode = _nodes[index + 1];\n\t\tif (curNode.yNext == nextNode.yNext)\n\t\t{\n\t\t\tcurNode.width += nextNode.width;\n\t\t\t_nodes.erase(_nodes.begin() + index + 1);\n\t\t\t--index;\n\t\t}\n\t}\n}\n\nint TextureAtlas::_fit(const int index, const int width, const int height)\n{\n\trffalcon::ivec3 node = _nodes[index];\n\tint x = node.x;\n\tint y = node.y;\n\tint widthLeft = width;\n\tint curIndex = index;\n\tint result = -1;\n\t\n\t\/\/ if adding this node left-aligned to the node at the index\n\t\/\/ would not go outside right edge of the texture\n\tif ((x + width) <= (_width - 1))\n\t{\n\t\t\/\/ move the new node's y position to the envelope\n\t\ty = node.yNext;\n\t\t\/\/ while this node might collide with the envelope in the x direction\n\t\twhile (widthLeft > 0)\n\t\t{\n\t\t\tnode = _nodes[curIndex];\n\t\t\t\/\/ if the new node collides with the envelope in the x direction\n\t\t\tif (node.yNext > y)\n\t\t\t{\n\t\t\t\t\/\/ push the new node down to the envelope\n\t\t\t\ty = node.yNext;\n\t\t\t}\n\n\t\t\t\/\/ if adding this node would not go outside the bottom edge of the texture\n\t\t\tif ((y + height) <= (_height - 1))\n\t\t\t{\n\t\t\t\twidthLeft -= node.width;\n\t\t\t\t++curIndex;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ No room to add the new node below the index node\n\t\t\t\ty = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tresult = y;\n\t}\n\n\treturn result;\n}\n\nvoid TextureAtlas::setRegion(rffalcon::ivec4 region, GlyphData glyphData)\n{\n\tint depth = getDepth();\n\tint charSize = sizeof(char);\n\tfor (int i = 0; i < glyphData.height; ++i)\n\t{\n\t\tmemcpy(_data + ((region.y + i) * getWidth() + region.x) * charSize * depth,\n\t\t\t glyphData.buffer + (i * glyphData.pitch * charSize), glyphData.width * charSize * depth);\n\t}\n\t\n}\n\nvoid TextureAtlas::upload()\n{\n\tif (_glTextureId == 0)\n\t{\n\t\tglGenTextures(1, &_glTextureId);\n\t}\n\n\tglBindTexture(GL_TEXTURE_2D, _glTextureId);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tGLenum pixelDataType;\n\tGLint internalFormat;\n\tGLenum format;\n\tif (_depth == 4)\n\t{\n#ifdef GL_UNSIGNED_INT_8_8_8_8_REV\n\t\tpixelDataType = GL_UNSIGNED_INT_8_8_8_8_REV;\n\t\tformat = GL_BGRA;\n#else\n\t\tpixelDataType = GL_UNSIGNED_BYTE;\n\t\tformat = GL_RGBA;\n#endif\n\t\tinternalFormat = GL_RGBA;\n\t}\n\telse {\n\t\tpixelDataType = GL_UNSIGNED_BYTE;\n\t\tformat = internalFormat = (_depth == 3) ? GL_RGB : GL_RED;\n\t}\n\n\tglTexImage2D(GL_TEXTURE_2D, 0, internalFormat, _width, _height, 0, format, pixelDataType, _data);\n}<|endoftext|>"} {"text":"<commit_before>\/\/===-- dfsan.cc ----------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of DataFlowSanitizer.\n\/\/\n\/\/ DataFlowSanitizer runtime. This file defines the public interface to\n\/\/ DataFlowSanitizer as well as the definition of certain runtime functions\n\/\/ called automatically by the compiler (specifically the instrumentation pass\n\/\/ in llvm\/lib\/Transforms\/Instrumentation\/DataFlowSanitizer.cpp).\n\/\/\n\/\/ The public interface is defined in include\/sanitizer\/dfsan_interface.h whose\n\/\/ functions are prefixed dfsan_ while the compiler interface functions are\n\/\/ prefixed __dfsan_.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer\/dfsan_interface.h\"\n#include \"sanitizer_common\/sanitizer_atomic.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n\n#include \"dfsan\/dfsan.h\"\n\nusing namespace __dfsan;\n\ntypedef atomic_uint16_t atomic_dfsan_label;\nstatic const dfsan_label kInitializingLabel = -1;\n\nstatic const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8);\n\nstatic atomic_dfsan_label __dfsan_last_label;\nstatic dfsan_label_info __dfsan_label_info[kNumLabels];\n\nSANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_retval_tls;\nSANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_arg_tls[64];\n\n\/\/ On Linux\/x86_64, memory is laid out as follows:\n\/\/\n\/\/ +--------------------+ 0x800000000000 (top of memory)\n\/\/ | application memory |\n\/\/ +--------------------+ 0x700000008000 (kAppAddr)\n\/\/ | |\n\/\/ | unused |\n\/\/ | |\n\/\/ +--------------------+ 0x200200000000 (kUnusedAddr)\n\/\/ | union table |\n\/\/ +--------------------+ 0x200000000000 (kUnionTableAddr)\n\/\/ | shadow memory |\n\/\/ +--------------------+ 0x000000010000 (kShadowAddr)\n\/\/ | reserved by kernel |\n\/\/ +--------------------+ 0x000000000000\n\/\/\n\/\/ To derive a shadow memory address from an application memory address,\n\/\/ bits 44-46 are cleared to bring the address into the range\n\/\/ [0x000000008000,0x100000000000). Then the address is shifted left by 1 to\n\/\/ account for the double byte representation of shadow labels and move the\n\/\/ address into the shadow memory range. See the function shadow_for below.\n\ntypedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels];\n\nstatic const uptr kShadowAddr = 0x10000;\nstatic const uptr kUnionTableAddr = 0x200000000000;\nstatic const uptr kUnusedAddr = kUnionTableAddr + sizeof(dfsan_union_table_t);\nstatic const uptr kAppAddr = 0x700000008000;\n\nstatic atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) {\n return &(*(dfsan_union_table_t *) kUnionTableAddr)[l1][l2];\n}\n\n\/\/ Resolves the union of two unequal labels. Nonequality is a precondition for\n\/\/ this function (the instrumentation pass inlines the equality test).\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) {\n DCHECK_NE(l1, l2);\n\n if (l1 == 0)\n return l2;\n if (l2 == 0)\n return l1;\n\n if (l1 > l2)\n Swap(l1, l2);\n\n atomic_dfsan_label *table_ent = union_table(l1, l2);\n \/\/ We need to deal with the case where two threads concurrently request\n \/\/ a union of the same pair of labels. If the table entry is uninitialized,\n \/\/ (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel\n \/\/ (i.e. -1) to mark that we are initializing it.\n dfsan_label label = 0;\n if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel,\n memory_order_acquire)) {\n \/\/ Check whether l2 subsumes l1. We don't need to check whether l1\n \/\/ subsumes l2 because we are guaranteed here that l1 < l2, and (at least\n \/\/ in the cases we are interested in) a label may only subsume labels\n \/\/ created earlier (i.e. with a lower numerical value).\n if (__dfsan_label_info[l2].l1 == l1 ||\n __dfsan_label_info[l2].l2 == l1) {\n label = l2;\n } else {\n label =\n atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;\n CHECK_NE(label, kInitializingLabel);\n __dfsan_label_info[label].l1 = l1;\n __dfsan_label_info[label].l2 = l2;\n }\n atomic_store(table_ent, label, memory_order_release);\n } else if (label == kInitializingLabel) {\n \/\/ Another thread is initializing the entry. Wait until it is finished.\n do {\n internal_sched_yield();\n label = atomic_load(table_ent, memory_order_acquire);\n } while (label == kInitializingLabel);\n }\n return label;\n}\n\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label __dfsan_union_load(dfsan_label *ls, size_t n) {\n dfsan_label label = ls[0];\n for (size_t i = 1; i != n; ++i) {\n dfsan_label next_label = ls[i];\n if (label != next_label)\n label = __dfsan_union(label, next_label);\n }\n return label;\n}\n\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\nvoid *__dfsan_memcpy(void *dest, const void *src, size_t n) {\n dfsan_label *sdest = shadow_for(dest), *ssrc = shadow_for((void *)src);\n internal_memcpy((void *)sdest, (void *)ssrc, n * sizeof(dfsan_label));\n return internal_memcpy(dest, src, n);\n}\n\n\/\/ Like __dfsan_union, but for use from the client or custom functions. Hence\n\/\/ the equality comparison is done here before calling __dfsan_union.\nSANITIZER_INTERFACE_ATTRIBUTE dfsan_label\ndfsan_union(dfsan_label l1, dfsan_label l2) {\n if (l1 == l2)\n return l1;\n return __dfsan_union(l1, l2);\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label dfsan_create_label(const char *desc, void *userdata) {\n dfsan_label label =\n atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;\n CHECK_NE(label, kInitializingLabel);\n __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0;\n __dfsan_label_info[label].desc = desc;\n __dfsan_label_info[label].userdata = userdata;\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return label;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid dfsan_set_label(dfsan_label label, void *addr, size_t size) {\n for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)\n *labelp = label;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid dfsan_add_label(dfsan_label label, void *addr, size_t size) {\n for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)\n if (*labelp != label)\n *labelp = __dfsan_union(*labelp, label);\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_get_label(long data) {\n \/\/ The label for 'data' is implicitly passed by the instrumentation pass in\n \/\/ the first element of __dfsan_arg_tls. So we can just return it.\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return __dfsan_arg_tls[0];\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nconst struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return &__dfsan_label_info[label];\n}\n\nint dfsan_has_label(dfsan_label label, dfsan_label elem) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n if (label == elem)\n return true;\n const dfsan_label_info *info = dfsan_get_label_info(label);\n if (info->l1 != 0) {\n return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem);\n } else {\n return false;\n }\n}\n\ndfsan_label dfsan_has_label_with_desc(dfsan_label label, const char *desc) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n const dfsan_label_info *info = dfsan_get_label_info(label);\n if (info->l1 != 0) {\n return dfsan_has_label_with_desc(info->l1, desc) ||\n dfsan_has_label_with_desc(info->l2, desc);\n } else {\n return internal_strcmp(desc, info->desc) == 0;\n }\n}\n\n#ifdef DFSAN_NOLIBC\nextern \"C\" void dfsan_init() {\n#else\nstatic void dfsan_init(int argc, char **argv, char **envp) {\n#endif\n MmapFixedNoReserve(kShadowAddr, kUnusedAddr - kShadowAddr);\n\n \/\/ Protect the region of memory we don't use, to preserve the one-to-one\n \/\/ mapping from application to shadow memory. But if ASLR is disabled, Linux\n \/\/ will load our executable in the middle of our unused region. This mostly\n \/\/ works so long as the program doesn't use too much memory. We support this\n \/\/ case by disabling memory protection when ASLR is disabled.\n uptr init_addr = (uptr)&dfsan_init;\n if (!(init_addr >= kUnusedAddr && init_addr < kAppAddr))\n Mprotect(kUnusedAddr, kAppAddr - kUnusedAddr);\n}\n\n#ifndef DFSAN_NOLIBC\n__attribute__((section(\".preinit_array\"), used))\nstatic void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init;\n#endif\n<commit_msg>[dfsan] Remove the unused __dfsan_memcpy function.<commit_after>\/\/===-- dfsan.cc ----------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of DataFlowSanitizer.\n\/\/\n\/\/ DataFlowSanitizer runtime. This file defines the public interface to\n\/\/ DataFlowSanitizer as well as the definition of certain runtime functions\n\/\/ called automatically by the compiler (specifically the instrumentation pass\n\/\/ in llvm\/lib\/Transforms\/Instrumentation\/DataFlowSanitizer.cpp).\n\/\/\n\/\/ The public interface is defined in include\/sanitizer\/dfsan_interface.h whose\n\/\/ functions are prefixed dfsan_ while the compiler interface functions are\n\/\/ prefixed __dfsan_.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer\/dfsan_interface.h\"\n#include \"sanitizer_common\/sanitizer_atomic.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n\n#include \"dfsan\/dfsan.h\"\n\nusing namespace __dfsan;\n\ntypedef atomic_uint16_t atomic_dfsan_label;\nstatic const dfsan_label kInitializingLabel = -1;\n\nstatic const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8);\n\nstatic atomic_dfsan_label __dfsan_last_label;\nstatic dfsan_label_info __dfsan_label_info[kNumLabels];\n\nSANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_retval_tls;\nSANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_arg_tls[64];\n\n\/\/ On Linux\/x86_64, memory is laid out as follows:\n\/\/\n\/\/ +--------------------+ 0x800000000000 (top of memory)\n\/\/ | application memory |\n\/\/ +--------------------+ 0x700000008000 (kAppAddr)\n\/\/ | |\n\/\/ | unused |\n\/\/ | |\n\/\/ +--------------------+ 0x200200000000 (kUnusedAddr)\n\/\/ | union table |\n\/\/ +--------------------+ 0x200000000000 (kUnionTableAddr)\n\/\/ | shadow memory |\n\/\/ +--------------------+ 0x000000010000 (kShadowAddr)\n\/\/ | reserved by kernel |\n\/\/ +--------------------+ 0x000000000000\n\/\/\n\/\/ To derive a shadow memory address from an application memory address,\n\/\/ bits 44-46 are cleared to bring the address into the range\n\/\/ [0x000000008000,0x100000000000). Then the address is shifted left by 1 to\n\/\/ account for the double byte representation of shadow labels and move the\n\/\/ address into the shadow memory range. See the function shadow_for below.\n\ntypedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels];\n\nstatic const uptr kShadowAddr = 0x10000;\nstatic const uptr kUnionTableAddr = 0x200000000000;\nstatic const uptr kUnusedAddr = kUnionTableAddr + sizeof(dfsan_union_table_t);\nstatic const uptr kAppAddr = 0x700000008000;\n\nstatic atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) {\n return &(*(dfsan_union_table_t *) kUnionTableAddr)[l1][l2];\n}\n\n\/\/ Resolves the union of two unequal labels. Nonequality is a precondition for\n\/\/ this function (the instrumentation pass inlines the equality test).\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) {\n DCHECK_NE(l1, l2);\n\n if (l1 == 0)\n return l2;\n if (l2 == 0)\n return l1;\n\n if (l1 > l2)\n Swap(l1, l2);\n\n atomic_dfsan_label *table_ent = union_table(l1, l2);\n \/\/ We need to deal with the case where two threads concurrently request\n \/\/ a union of the same pair of labels. If the table entry is uninitialized,\n \/\/ (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel\n \/\/ (i.e. -1) to mark that we are initializing it.\n dfsan_label label = 0;\n if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel,\n memory_order_acquire)) {\n \/\/ Check whether l2 subsumes l1. We don't need to check whether l1\n \/\/ subsumes l2 because we are guaranteed here that l1 < l2, and (at least\n \/\/ in the cases we are interested in) a label may only subsume labels\n \/\/ created earlier (i.e. with a lower numerical value).\n if (__dfsan_label_info[l2].l1 == l1 ||\n __dfsan_label_info[l2].l2 == l1) {\n label = l2;\n } else {\n label =\n atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;\n CHECK_NE(label, kInitializingLabel);\n __dfsan_label_info[label].l1 = l1;\n __dfsan_label_info[label].l2 = l2;\n }\n atomic_store(table_ent, label, memory_order_release);\n } else if (label == kInitializingLabel) {\n \/\/ Another thread is initializing the entry. Wait until it is finished.\n do {\n internal_sched_yield();\n label = atomic_load(table_ent, memory_order_acquire);\n } while (label == kInitializingLabel);\n }\n return label;\n}\n\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label __dfsan_union_load(dfsan_label *ls, size_t n) {\n dfsan_label label = ls[0];\n for (size_t i = 1; i != n; ++i) {\n dfsan_label next_label = ls[i];\n if (label != next_label)\n label = __dfsan_union(label, next_label);\n }\n return label;\n}\n\n\/\/ Like __dfsan_union, but for use from the client or custom functions. Hence\n\/\/ the equality comparison is done here before calling __dfsan_union.\nSANITIZER_INTERFACE_ATTRIBUTE dfsan_label\ndfsan_union(dfsan_label l1, dfsan_label l2) {\n if (l1 == l2)\n return l1;\n return __dfsan_union(l1, l2);\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\ndfsan_label dfsan_create_label(const char *desc, void *userdata) {\n dfsan_label label =\n atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1;\n CHECK_NE(label, kInitializingLabel);\n __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0;\n __dfsan_label_info[label].desc = desc;\n __dfsan_label_info[label].userdata = userdata;\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return label;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid dfsan_set_label(dfsan_label label, void *addr, size_t size) {\n for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)\n *labelp = label;\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nvoid dfsan_add_label(dfsan_label label, void *addr, size_t size) {\n for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp)\n if (*labelp != label)\n *labelp = __dfsan_union(*labelp, label);\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_get_label(long data) {\n \/\/ The label for 'data' is implicitly passed by the instrumentation pass in\n \/\/ the first element of __dfsan_arg_tls. So we can just return it.\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return __dfsan_arg_tls[0];\n}\n\nSANITIZER_INTERFACE_ATTRIBUTE\nconst struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n return &__dfsan_label_info[label];\n}\n\nint dfsan_has_label(dfsan_label label, dfsan_label elem) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n if (label == elem)\n return true;\n const dfsan_label_info *info = dfsan_get_label_info(label);\n if (info->l1 != 0) {\n return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem);\n } else {\n return false;\n }\n}\n\ndfsan_label dfsan_has_label_with_desc(dfsan_label label, const char *desc) {\n __dfsan_retval_tls = 0; \/\/ Ensures return value is unlabelled in the caller.\n const dfsan_label_info *info = dfsan_get_label_info(label);\n if (info->l1 != 0) {\n return dfsan_has_label_with_desc(info->l1, desc) ||\n dfsan_has_label_with_desc(info->l2, desc);\n } else {\n return internal_strcmp(desc, info->desc) == 0;\n }\n}\n\n#ifdef DFSAN_NOLIBC\nextern \"C\" void dfsan_init() {\n#else\nstatic void dfsan_init(int argc, char **argv, char **envp) {\n#endif\n MmapFixedNoReserve(kShadowAddr, kUnusedAddr - kShadowAddr);\n\n \/\/ Protect the region of memory we don't use, to preserve the one-to-one\n \/\/ mapping from application to shadow memory. But if ASLR is disabled, Linux\n \/\/ will load our executable in the middle of our unused region. This mostly\n \/\/ works so long as the program doesn't use too much memory. We support this\n \/\/ case by disabling memory protection when ASLR is disabled.\n uptr init_addr = (uptr)&dfsan_init;\n if (!(init_addr >= kUnusedAddr && init_addr < kAppAddr))\n Mprotect(kUnusedAddr, kAppAddr - kUnusedAddr);\n}\n\n#ifndef DFSAN_NOLIBC\n__attribute__((section(\".preinit_array\"), used))\nstatic void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init;\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"time.h\"\n#include <string>\n#include \"novoht.h\"\n#include <cstdlib>\n#include <cstddef>\n#include <sys\/time.h>\/\/\n\/\/#include \"meta.pb.h\"\n#define KEY_LEN 32\n#define VAL_LEN 128\nusing namespace std;\nstruct timeval tp;\ndouble diffclock(clock_t clock1, clock_t clock2){\n double clock_ts=clock1-clock2;\n double diffms=(clock_ts*1000)\/CLOCKS_PER_SEC;\n return diffms;\n}\ndouble getTime_usec() {\n gettimeofday(&tp, NULL);\n return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);\n}\nstring randomString(int len) {\n string s(len, ' ');\n srand(\/*getpid()*\/ clock() + getTime_usec());\n static const char alphanum[] = \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n for (int i = 0; i < len; ++i) {\n s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n }\n return s;\n}\ndouble testInsert(NoVoHT &map, string keys[], string vals[], int l){\n int fails =0;\n cout << \"0\\% Complete\\r\";\n cout.flush();\n clock_t a=clock();\n for (int t = 0; t<l; t++){\n fails += map.put(keys[t], vals[t]);\n if ((t+1)%10000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not inserted\" << endl;\n return diffclock(b,a);\n ;\n}\ndouble testGet(NoVoHT &map, string keys[], string vals[], int l){\n int fails = 0;\n cout << \"0\\% Complete\\r\";\n clock_t a=clock();\n for (int t=0; t<l; t++){\n if (!map.get(keys[t])) fails++;\n else if (map.get(keys[t])->compare(vals[t]) != 0)fails++;\n if ((t+1)%10000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not found\" << endl;\n return diffclock(b,a);\n}\ndouble testRemove(NoVoHT &map, string keys[], int l){\n int fails = 0;\n cout << \"0\\% Complete\\r\";\n clock_t a=clock();\n for (int t=0; t<l; t++){\n map.remove(keys[t]);\n if ((t+1)%10000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not found\" << endl;\n return diffclock(b,a);\n}\nint main(int argc, char *argv[]){\n cout << \"\\nInitializing key-value pairs for testing\\n\";\n cout << \"0\\%\\r\";\n int size = atoi(argv[1]);\n string* keys = new string[size];\n string* vals = new string[size];\n \/*for (int t=0;\n t<size;\n t++){\n Package package, package_ret;\n string key = randomString(25);\n \/\/as keypackage.set_virtualpath(key);\n package.set_isdir(true);\n package.set_replicano(5);\n package.set_operation(3);\n package.set_realfullpath(\"Some-Real-longer-longer-and-longer-Paths--------\");\n package.add_listitem(\"item-----1\");\n package.add_listitem(\"item-----2\");\n package.add_listitem(\"item-----3\");\n package.add_listitem(\"item-----4\");\n package.add_listitem(\"item-----5\");\n string value = package.SerializeAsString();\n keys[t] = key;\n vals[t] = value;\n }\n *\/\n for (int t=0; t<size; t++){\n keys[t] = randomString(KEY_LEN);\n vals[t] = randomString(VAL_LEN);\n if(t%1000 == 0)cout << t*100\/size << \"\\%\\r\";\n }\n cout << \"Done\\n\" << endl;\n NoVoHT map (\"fbench.data\", 1000000, 10000);\n \/\/NoVoHT map (\"\", 10000000, -1);\n \/\/NoVoHT map (\"\", 1000000, 10000, .7);\n \/\/NoVoHT map (\"\", 1000000, -1);\n \/\/NoVoHT map (\"\/dev\/shm\/fbench.data\", 1000000, -1);\n double ins, ret, rem;\n cout << \"Testing Insertion: Inserting \" << size << \" elements\" << endl;\n ins = testInsert(map, keys,vals,size);\n cout << \"Testing Retrieval: Retrieving \" << size << \" elements\" << endl;\n ret = testGet(map,keys,vals,size);\n cout << \"Testing Removal: Removing \" << size << \" elements\" << endl;\n rem = testRemove(map,keys,size);\n cout << \"\\nInsertion done in \" << ins << \" milliseconds\" << endl;\n cout << \"Retrieval done in \" << ret << \" milliseconds\" << endl;\n cout << \"Removal done in \" << rem << \" milliseconds\" << endl;\n delete [] keys;\n delete [] vals;\n return 0;\n}\n\n<commit_msg>\tmodified: fbench.cxx<commit_after>#include <iostream>\n#include \"time.h\"\n#include <string>\n#include \"novoht.h\"\n#include <cstdlib>\n#include <cstddef>\n#include <sys\/time.h>\/\/\n\/\/#include \"meta.pb.h\"\n#define KEY_LEN 32\n#define VAL_LEN 128\nusing namespace std;\nstruct timeval tp;\ndouble diffclock(clock_t clock1, clock_t clock2){\n double clock_ts=clock1-clock2;\n double diffms=(clock_ts*1000)\/CLOCKS_PER_SEC;\n return diffms;\n}\ndouble getTime_usec() {\n gettimeofday(&tp, NULL);\n return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);\n}\nstring randomString(int len) {\n string s(len, ' ');\n srand(\/*getpid()*\/ clock() + getTime_usec());\n static const char alphanum[] = \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n for (int i = 0; i < len; ++i) {\n s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n }\n return s;\n}\ndouble testInsert(NoVoHT &map, string keys[], string vals[], int l){\n int fails =0;\n cout << \"0\\% Complete\\r\";\n cout.flush();\n clock_t a=clock();\n for (int t = 0; t<l; t++){\n fails += map.put(keys[t], vals[t]);\n if ((t+1)%1000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not inserted\" << endl;\n return diffclock(b,a);\n ;\n}\ndouble testGet(NoVoHT &map, string keys[], string vals[], int l){\n int fails = 0;\n cout << \"0\\% Complete\\r\";\n clock_t a=clock();\n for (int t=0; t<l; t++){\n if (!map.get(keys[t])) fails++;\n else if (map.get(keys[t])->compare(vals[t]) != 0)fails++;\n if ((t+1)%1000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not found\" << endl;\n return diffclock(b,a);\n}\ndouble testRemove(NoVoHT &map, string keys[], int l){\n int fails = 0;\n cout << \"0\\% Complete\\r\";\n clock_t a=clock();\n for (int t=0; t<l; t++){\n map.remove(keys[t]);\n if ((t+1)%1000 == 0)cout << t*100\/l << \"\\% Complete\\r\";\n }\n clock_t b=clock();\n cout << \"100\\% Complete with \" << fails << \" not found\" << endl;\n return diffclock(b,a);\n}\nint main(int argc, char *argv[]){\n cout << \"\\nInitializing key-value pairs for testing\\n\";\n cout << \"0\\%\\r\";\n int size = atoi(argv[1]);\n string* keys = new string[size];\n string* vals = new string[size];\n \/*for (int t=0;\n t<size;\n t++){\n Package package, package_ret;\n string key = randomString(25);\n \/\/as keypackage.set_virtualpath(key);\n package.set_isdir(true);\n package.set_replicano(5);\n package.set_operation(3);\n package.set_realfullpath(\"Some-Real-longer-longer-and-longer-Paths--------\");\n package.add_listitem(\"item-----1\");\n package.add_listitem(\"item-----2\");\n package.add_listitem(\"item-----3\");\n package.add_listitem(\"item-----4\");\n package.add_listitem(\"item-----5\");\n string value = package.SerializeAsString();\n keys[t] = key;\n vals[t] = value;\n }\n *\/\n for (int t=0; t<size; t++){\n keys[t] = randomString(KEY_LEN);\n vals[t] = randomString(VAL_LEN);\n if(t%1000 == 0)cout << t*100\/size << \"\\%\\r\";\n }\n cout << \"Done\\n\" << endl;\n NoVoHT map (\"fbench.data\", 1000000, 10000);\n \/\/NoVoHT map (\"\", 10000000, -1);\n \/\/NoVoHT map (\"\", 1000000, 10000, .7);\n \/\/NoVoHT map (\"\", 1000000, -1);\n \/\/NoVoHT map (\"\/dev\/shm\/fbench.data\", 1000000, -1);\n double ins, ret, rem;\n cout << \"Testing Insertion: Inserting \" << size << \" elements\" << endl;\n ins = testInsert(map, keys,vals,size);\n cout << \"Testing Retrieval: Retrieving \" << size << \" elements\" << endl;\n ret = testGet(map,keys,vals,size);\n cout << \"Testing Removal: Removing \" << size << \" elements\" << endl;\n rem = testRemove(map,keys,size);\n cout << \"\\nInsertion done in \" << ins << \" milliseconds\" << endl;\n cout << \"Retrieval done in \" << ret << \" milliseconds\" << endl;\n cout << \"Removal done in \" << rem << \" milliseconds\" << endl;\n delete [] keys;\n delete [] vals;\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <QQuickWindow>\n#include <QDebug>\n\n#include \"myfilesavedialog.h\"\n\nMyFileSaveDialog::MyFileSaveDialog(QQuickItem *parent) :\n QQuickItem(parent)\n , m_modality(Qt::WindowModal)\n , m_options(QSharedPointer<QFileDialogOptions>(new QFileDialogOptions()))\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n qDebug() << \"Working with Qt 5.2\";\n#else\n qDebug() << \"Working with Qt 5.1\";\n#endif\n\n m_dlgHelper = init_helper();\n\n connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));\n connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));\n}\n\nMyFileSaveDialog::~MyFileSaveDialog()\n{\n if (m_dlgHelper)\n m_dlgHelper->hide();\n delete m_dlgHelper;\n}\n\nQUrl MyFileSaveDialog::fileUrl() const\n{\n return fileUrl_;\n}\n\nvoid MyFileSaveDialog::setFileUrl(QUrl fileUrl)\n{\n if (fileUrl_ != fileUrl)\n {\n fileUrl_ = fileUrl;\n emit fileUrlChanged();\n }\n}\n\nQString MyFileSaveDialog::filename() const\n{\n return filename_;\n}\n\nvoid MyFileSaveDialog::setFilename(QString filename)\n{\n if (filename_ != filename)\n {\n filename_ = filename;\n emit filenameChanged();\n }\n}\n\nQString MyFileSaveDialog::title() const\n{\n return title_;\n}\n\nvoid MyFileSaveDialog::setTitle(QString title)\n{\n if (title_ != title)\n {\n title_ = title;\n emit titleChanged();\n }\n}\n\nQPlatformFileDialogHelper* MyFileSaveDialog::init_helper()\n{\n m_dlgHelper = static_cast<QPlatformFileDialogHelper*>(QGuiApplicationPrivate::platformTheme()->createPlatformDialogHelper(QPlatformTheme::FileDialog));\n if (!m_dlgHelper)\n return NULL;\n\n return m_dlgHelper;\n}\n\nvoid MyFileSaveDialog::open()\n{\n QQuickItem *me = this;\n Q_ASSERT(me);\n\n QQuickItem *parent = me->parentItem();\n Q_ASSERT(parent);\n\n QQuickWindow *window = parent->window();\n Q_ASSERT(window);\n\n m_parentWindow = window;\n\n m_options->setFileMode(QFileDialogOptions::AnyFile);\n m_options->setAcceptMode(QFileDialogOptions::AcceptSave);\n m_options->setWindowTitle(title());\n\n \/*\n * Mac:\n * Set filename incl. directory via setInitiallySelectedFiles()\n *\n * Windows:\n * Set filename via setInitiallySelectedFiles() and let Windows choose the directory.\n * Default directory: C:\\\\Users\\XYZ\\Downloads\n *\n * Gnome:\n * Set directory via QPlatformFileDialogHelper::setDirectory() and leave\n * filename empty, since QGtk2FileDialogHelper can not set non-existing filenames.\n *\n *\/\n#ifdef Q_OS_MACX \/\/ Use Q_OS_MACX for Qt 5.1+ code and Q_OS_OSX for Qt 5.2+ code.\n QString initialSelection = QFileInfo(QDir::homePath(), filename()).absoluteFilePath();\n qDebug() << \"Initial file:\" << initialSelection;\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_options->setInitiallySelectedFiles(QList<QUrl>() << QUrl::fromLocalFile(initialSelection));\n #else\n m_options->setInitiallySelectedFiles(QStringList(initialSelection));\n #endif\n#endif\n#ifdef Q_OS_WIN\n qDebug() << \"Initial filename:\" << filename();\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_options->setInitiallySelectedFiles(QList<QUrl>() << QUrl::fromLocalFile(filename()));\n #else\n m_options->setInitiallySelectedFiles(QStringList(filename()));\n #endif\n#endif\n#ifdef Q_OS_LINUX\n qDebug() << \"Initial directory:\" << QDir::homePath();\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_dlgHelper->setDirectory(QUrl::fromLocalFile(QDir::homePath()));\n #else\n m_dlgHelper->setDirectory(QDir::homePath());\n #endif\n#endif\n\n m_dlgHelper->setOptions(m_options);\n m_dlgHelper->setFilter(); \/\/ applyOptions();\n\n Qt::WindowFlags flags = Qt::Dialog;\n if (!title().isEmpty()) flags |= Qt::WindowTitleHint;\n\n m_visible = m_dlgHelper->show(flags, m_modality, m_parentWindow);\n}\n\nvoid MyFileSaveDialog::close()\n{\n m_dlgHelper->hide();\n m_visible = false;\n}\n\nvoid MyFileSaveDialog::accept()\n{\n m_dlgHelper->hide();\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n QList<QUrl> selectedUrls = m_dlgHelper->selectedFiles();\n if ( selectedUrls.count() )\n {\n setFileUrl(selectedUrls.at(0));\n }\n#else\n QStringList selectedFiles = m_dlgHelper->selectedFiles();\n if ( selectedFiles.count() )\n {\n setFileUrl(QUrl::fromLocalFile(selectedFiles.at(0)));\n }\n#endif\n\n emit accepted();\n}\n\nvoid MyFileSaveDialog::reject()\n{\n m_dlgHelper->hide();\n emit rejected();\n}\n<commit_msg>Skip trivial step to get QQuickItem `this`<commit_after>#include <QQuickWindow>\n#include <QDebug>\n\n#include \"myfilesavedialog.h\"\n\nMyFileSaveDialog::MyFileSaveDialog(QQuickItem *parent) :\n QQuickItem(parent)\n , m_modality(Qt::WindowModal)\n , m_options(QSharedPointer<QFileDialogOptions>(new QFileDialogOptions()))\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n qDebug() << \"Working with Qt 5.2\";\n#else\n qDebug() << \"Working with Qt 5.1\";\n#endif\n\n m_dlgHelper = init_helper();\n\n connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));\n connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));\n}\n\nMyFileSaveDialog::~MyFileSaveDialog()\n{\n if (m_dlgHelper)\n m_dlgHelper->hide();\n delete m_dlgHelper;\n}\n\nQUrl MyFileSaveDialog::fileUrl() const\n{\n return fileUrl_;\n}\n\nvoid MyFileSaveDialog::setFileUrl(QUrl fileUrl)\n{\n if (fileUrl_ != fileUrl)\n {\n fileUrl_ = fileUrl;\n emit fileUrlChanged();\n }\n}\n\nQString MyFileSaveDialog::filename() const\n{\n return filename_;\n}\n\nvoid MyFileSaveDialog::setFilename(QString filename)\n{\n if (filename_ != filename)\n {\n filename_ = filename;\n emit filenameChanged();\n }\n}\n\nQString MyFileSaveDialog::title() const\n{\n return title_;\n}\n\nvoid MyFileSaveDialog::setTitle(QString title)\n{\n if (title_ != title)\n {\n title_ = title;\n emit titleChanged();\n }\n}\n\nQPlatformFileDialogHelper* MyFileSaveDialog::init_helper()\n{\n m_dlgHelper = static_cast<QPlatformFileDialogHelper*>(QGuiApplicationPrivate::platformTheme()->createPlatformDialogHelper(QPlatformTheme::FileDialog));\n if (!m_dlgHelper)\n return NULL;\n\n return m_dlgHelper;\n}\n\nvoid MyFileSaveDialog::open()\n{\n QQuickItem *parent = this->parentItem();\n Q_ASSERT(parent);\n\n QQuickWindow *window = parent->window();\n Q_ASSERT(window);\n\n m_parentWindow = window;\n\n m_options->setFileMode(QFileDialogOptions::AnyFile);\n m_options->setAcceptMode(QFileDialogOptions::AcceptSave);\n m_options->setWindowTitle(title());\n\n \/*\n * Mac:\n * Set filename incl. directory via setInitiallySelectedFiles()\n *\n * Windows:\n * Set filename via setInitiallySelectedFiles() and let Windows choose the directory.\n * Default directory: C:\\\\Users\\XYZ\\Downloads\n *\n * Gnome:\n * Set directory via QPlatformFileDialogHelper::setDirectory() and leave\n * filename empty, since QGtk2FileDialogHelper can not set non-existing filenames.\n *\n *\/\n#ifdef Q_OS_MACX \/\/ Use Q_OS_MACX for Qt 5.1+ code and Q_OS_OSX for Qt 5.2+ code.\n QString initialSelection = QFileInfo(QDir::homePath(), filename()).absoluteFilePath();\n qDebug() << \"Initial file:\" << initialSelection;\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_options->setInitiallySelectedFiles(QList<QUrl>() << QUrl::fromLocalFile(initialSelection));\n #else\n m_options->setInitiallySelectedFiles(QStringList(initialSelection));\n #endif\n#endif\n#ifdef Q_OS_WIN\n qDebug() << \"Initial filename:\" << filename();\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_options->setInitiallySelectedFiles(QList<QUrl>() << QUrl::fromLocalFile(filename()));\n #else\n m_options->setInitiallySelectedFiles(QStringList(filename()));\n #endif\n#endif\n#ifdef Q_OS_LINUX\n qDebug() << \"Initial directory:\" << QDir::homePath();\n #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n m_dlgHelper->setDirectory(QUrl::fromLocalFile(QDir::homePath()));\n #else\n m_dlgHelper->setDirectory(QDir::homePath());\n #endif\n#endif\n\n m_dlgHelper->setOptions(m_options);\n m_dlgHelper->setFilter(); \/\/ applyOptions();\n\n Qt::WindowFlags flags = Qt::Dialog;\n if (!title().isEmpty()) flags |= Qt::WindowTitleHint;\n\n m_visible = m_dlgHelper->show(flags, m_modality, m_parentWindow);\n}\n\nvoid MyFileSaveDialog::close()\n{\n m_dlgHelper->hide();\n m_visible = false;\n}\n\nvoid MyFileSaveDialog::accept()\n{\n m_dlgHelper->hide();\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n QList<QUrl> selectedUrls = m_dlgHelper->selectedFiles();\n if ( selectedUrls.count() )\n {\n setFileUrl(selectedUrls.at(0));\n }\n#else\n QStringList selectedFiles = m_dlgHelper->selectedFiles();\n if ( selectedFiles.count() )\n {\n setFileUrl(QUrl::fromLocalFile(selectedFiles.at(0)));\n }\n#endif\n\n emit accepted();\n}\n\nvoid MyFileSaveDialog::reject()\n{\n m_dlgHelper->hide();\n emit rejected();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef __WAND__\r\ntarget[name[figure.o] type[object]]\r\n#endif\r\n\r\n#include \"figure.h\"\r\n#include \"output.h\"\r\n#include \"macro.h\"\r\n#include \"commentprocessor.h\"\r\n\r\n#include <herbs\/intformat\/intformat.h>\r\n#include <herbs\/exceptionmissing\/exceptionmissing.h>\r\n\r\n\r\nvoid Doxymax::Figure::expand(const Macro& macro,CommentProcessor& processor)\r\n\t{\r\n\tif(macro.args.length()<3)\r\n\t\t{throw Herbs::ExceptionMissing(___FILE__,__LINE__);}\r\n\t\r\n\tHerbs::String str_out(128);\r\n\tstr_out\r\n\t\t.append(STR(\"\\\\anchor \")).append(macro.args[2]).append(CHAR(' '))\r\n\t\t.append(STR(\"<div class=\\\"image\\\">\"))\r\n\t\t.append(STR(\"<img src=\\\"\"))\r\n\t\t.append(macro.args[0]).append(CHAR('\"'));\r\n\r\n\tif(macro.args.length()>3)\r\n\t\t{\r\n\t\tstr_out.append(STR(\" width=\\\"\")).append(macro.args[3])\r\n\t\t\t.append(CHAR('\"'));\r\n\t\t}\r\n\t\r\n\tif(macro.args.length()>4)\r\n\t\t{\r\n\t\tstr_out.append(STR(\" height=\\\"\")).append(macro.args[4])\r\n\t\t\t.append(CHAR('\"'));\r\n\t\t}\r\n\t\r\n\tsize_t n=processor.labelGet(macro.args[2]);\r\n\tif(n==0)\r\n\t\t{\r\n\t\tn=processor.counterGet(STR(\"Figure\"));\r\n\t\t++n;\r\n\t\tprocessor.labelSet(macro.args[2],n);\r\n\t\t}\r\n\tstr_out.append(STR(\"\/><div class=\\\"caption\\\">Figure \"))\r\n\t\t.append(Herbs::IntFormat<size_t>(n))\r\n\t\t.append(STR(\": \"))\r\n\t\t.append(macro.args[1])\r\n\t\t.append(STR(\"<\/div><\/div>\"));\r\n\tprocessor.counterSet(STR(\"Figure\"),n);\r\n\t\r\n\tprint(str_out);\r\n\t}\r\n<commit_msg>Added hyperlink to image file in the figure macro<commit_after>#ifdef __WAND__\r\ntarget[name[figure.o] type[object]]\r\n#endif\r\n\r\n#include \"figure.h\"\r\n#include \"output.h\"\r\n#include \"macro.h\"\r\n#include \"commentprocessor.h\"\r\n\r\n#include <herbs\/intformat\/intformat.h>\r\n#include <herbs\/exceptionmissing\/exceptionmissing.h>\r\n\r\n\r\nvoid Doxymax::Figure::expand(const Macro& macro,CommentProcessor& processor)\r\n\t{\r\n\tif(macro.args.length()<3)\r\n\t\t{throw Herbs::ExceptionMissing(___FILE__,__LINE__);}\r\n\t\r\n\tHerbs::String str_out(128);\r\n\tstr_out\r\n\t\t.append(STR(\"\\\\anchor \")).append(macro.args[2]).append(CHAR(' '))\r\n\t\t.append(STR(\"<div class=\\\"image\\\">\"))\r\n\t\t.append(STR(\"<img src=\\\"\"))\r\n\t\t.append(macro.args[0]).append(CHAR('\"'));\r\n\r\n\tif(macro.args.length()>3)\r\n\t\t{\r\n\t\tstr_out.append(STR(\" width=\\\"\")).append(macro.args[3])\r\n\t\t\t.append(CHAR('\"'));\r\n\t\t}\r\n\t\r\n\tif(macro.args.length()>4)\r\n\t\t{\r\n\t\tstr_out.append(STR(\" height=\\\"\")).append(macro.args[4])\r\n\t\t\t.append(CHAR('\"'));\r\n\t\t}\r\n\t\r\n\tsize_t n=processor.labelGet(macro.args[2]);\r\n\tif(n==0)\r\n\t\t{\r\n\t\tn=processor.counterGet(STR(\"Figure\"));\r\n\t\t++n;\r\n\t\tprocessor.labelSet(macro.args[2],n);\r\n\t\t}\r\n\tstr_out.append(STR(\"\/><div class=\\\"caption\\\"><a href=\\\"\"))\r\n\t\t.append(macro.args[0]).append(STR(\"\\\">Figure \"))\r\n\t\t.append(Herbs::IntFormat<size_t>(n))\r\n\t\t.append(STR(\":<\/a> \"))\r\n\t\t.append(macro.args[1])\r\n\t\t.append(STR(\"<\/div><\/div>\"));\r\n\tprocessor.counterSet(STR(\"Figure\"),n);\r\n\t\r\n\tprint(str_out);\r\n\t}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"buildjson.hpp\"\n\n#include \"file_handler.hpp\"\n#include \"fs.hpp\"\n#include \"general_systemd.hpp\"\n#include \"prepare_systemd.hpp\"\n#include \"update_systemd.hpp\"\n\n#include <algorithm>\n#include <cstdio>\n#include <exception>\n#include <fstream>\n#include <nlohmann\/json.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <regex>\n#include <sdbusplus\/bus.hpp>\n#include <string>\n#include <vector>\n\nnamespace ipmi_flash\n{\n\nstd::unique_ptr<TriggerableActionInterface>\n buildFileSystemd(const nlohmann::json& data)\n{\n \/* This type of action requires a path and unit, and optionally a mode. *\/\n const auto& path = data.at(\"path\");\n const auto& unit = data.at(\"unit\");\n\n \/* the mode parameter is optional. *\/\n std::string systemdMode = \"replace\";\n const auto& mode = data.find(\"mode\");\n if (mode != data.end())\n {\n systemdMode = data.at(\"mode\").get<std::string>();\n }\n\n return SystemdWithStatusFile::CreateSystemdWithStatusFile(\n sdbusplus::bus::new_default(), path, unit, systemdMode);\n}\n\nstd::vector<HandlerConfig> buildHandlerFromJson(const nlohmann::json& data)\n{\n std::vector<HandlerConfig> handlers;\n\n for (const auto& item : data)\n {\n try\n {\n HandlerConfig output;\n\n \/* at() throws an exception when the key is not present. *\/\n item.at(\"blob\").get_to(output.blobId);\n\n \/* name must be: \/flash\/... *\/\n if (!std::regex_match(output.blobId, std::regex(\"^\\\\\/flash\\\\\/.+\")))\n {\n throw std::runtime_error(\"Invalid blob name: '\" +\n output.blobId +\n \"' must start with \/flash\/\");\n }\n\n \/* handler is required. *\/\n const auto& h = item.at(\"handler\");\n const std::string handlerType = h.at(\"type\");\n if (handlerType == \"file\")\n {\n const auto& path = h.at(\"path\");\n output.handler = std::make_unique<FileHandler>(path);\n }\n else\n {\n throw std::runtime_error(\"Invalid handler type: \" +\n handlerType);\n }\n\n \/* actions are required (presently). *\/\n const auto& a = item.at(\"actions\");\n std::unique_ptr<ActionPack> pack = std::make_unique<ActionPack>();\n\n \/* It hasn't been fully determined if any action being optional is\n * useful, so for now they will be required.\n * TODO: Evaluate how the behaviors change if some actions are\n * missing, does the code just assume it was successful? I would\n * think not.\n *\/\n const auto& prep = a.at(\"preparation\");\n const std::string prepareType = prep.at(\"type\");\n if (prepareType == \"systemd\")\n {\n const auto& unit = prep.at(\"unit\");\n pack->preparation = SystemdPreparation::CreatePreparation(\n sdbusplus::bus::new_default(), unit);\n }\n else\n {\n throw std::runtime_error(\"Invalid preparation type: \" +\n prepareType);\n }\n\n const auto& verify = a.at(\"verification\");\n const std::string verifyType = verify.at(\"type\");\n if (verifyType == \"fileSystemdVerify\")\n {\n pack->verification = std::move(buildFileSystemd(verify));\n }\n else\n {\n throw std::runtime_error(\"Invalid verification type:\" +\n verifyType);\n }\n\n const auto& update = a.at(\"update\");\n const std::string updateType = update.at(\"type\");\n if (updateType == \"reboot\")\n {\n static constexpr auto rebootTarget = \"reboot.target\";\n static constexpr auto rebootMode = \"replace-irreversibly\";\n pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(\n sdbusplus::bus::new_default(), rebootTarget, rebootMode);\n }\n else if (updateType == \"fileSystemdUpdate\")\n {\n pack->update = std::move(buildFileSystemd(update));\n }\n else if (updateType == \"systemd\")\n {\n const auto& unit = update.at(\"unit\");\n\n \/* the mode parameter is optional. *\/\n std::string systemdMode = \"replace\";\n const auto& mode = update.find(\"mode\");\n if (mode != update.end())\n {\n systemdMode = update.at(\"mode\").get<std::string>();\n }\n\n pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(\n sdbusplus::bus::new_default(), unit, systemdMode);\n }\n else\n {\n throw std::runtime_error(\"Invalid update type: \" + updateType);\n }\n\n output.actions = std::move(pack);\n handlers.push_back(std::move(output));\n }\n catch (const std::exception& e)\n {\n \/* TODO: Once phosphor-logging supports unit-test injection, fix\n * this to log.\n *\/\n std::fprintf(stderr,\n \"Excepted building HandlerConfig from json: %s\\n\",\n e.what());\n }\n }\n\n return handlers;\n}\n\nstd::vector<HandlerConfig> BuildHandlerConfigs(const std::string& directory)\n{\n using namespace phosphor::logging;\n\n std::vector<HandlerConfig> output;\n\n std::vector<std::string> jsonPaths = GetJsonList(directory);\n\n for (const auto& path : jsonPaths)\n {\n std::ifstream jsonFile(path);\n if (!jsonFile.is_open())\n {\n log<level::ERR>(\"Unable to open json file\",\n entry(\"PATH=%s\", path.c_str()));\n continue;\n }\n\n auto data = nlohmann::json::parse(jsonFile, nullptr, false);\n if (data.is_discarded())\n {\n log<level::ERR>(\"Parsing json failed\",\n entry(\"PATH=%s\", path.c_str()));\n continue;\n }\n\n std::vector<HandlerConfig> configs = buildHandlerFromJson(data);\n std::move(configs.begin(), configs.end(), std::back_inserter(output));\n }\n\n return output;\n}\n\n} \/\/ namespace ipmi_flash\n<commit_msg>bmc: use string literals instead of variables<commit_after>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"buildjson.hpp\"\n\n#include \"file_handler.hpp\"\n#include \"fs.hpp\"\n#include \"general_systemd.hpp\"\n#include \"prepare_systemd.hpp\"\n#include \"update_systemd.hpp\"\n\n#include <algorithm>\n#include <cstdio>\n#include <exception>\n#include <fstream>\n#include <nlohmann\/json.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <regex>\n#include <sdbusplus\/bus.hpp>\n#include <string>\n#include <vector>\n\nnamespace ipmi_flash\n{\n\nstd::unique_ptr<TriggerableActionInterface>\n buildFileSystemd(const nlohmann::json& data)\n{\n \/* This type of action requires a path and unit, and optionally a mode. *\/\n const auto& path = data.at(\"path\");\n const auto& unit = data.at(\"unit\");\n\n \/* the mode parameter is optional. *\/\n std::string systemdMode = \"replace\";\n const auto& mode = data.find(\"mode\");\n if (mode != data.end())\n {\n systemdMode = data.at(\"mode\").get<std::string>();\n }\n\n return SystemdWithStatusFile::CreateSystemdWithStatusFile(\n sdbusplus::bus::new_default(), path, unit, systemdMode);\n}\n\nstd::vector<HandlerConfig> buildHandlerFromJson(const nlohmann::json& data)\n{\n std::vector<HandlerConfig> handlers;\n\n for (const auto& item : data)\n {\n try\n {\n HandlerConfig output;\n\n \/* at() throws an exception when the key is not present. *\/\n item.at(\"blob\").get_to(output.blobId);\n\n \/* name must be: \/flash\/... *\/\n if (!std::regex_match(output.blobId, std::regex(\"^\\\\\/flash\\\\\/.+\")))\n {\n throw std::runtime_error(\"Invalid blob name: '\" +\n output.blobId +\n \"' must start with \/flash\/\");\n }\n\n \/* handler is required. *\/\n const auto& h = item.at(\"handler\");\n const std::string handlerType = h.at(\"type\");\n if (handlerType == \"file\")\n {\n const auto& path = h.at(\"path\");\n output.handler = std::make_unique<FileHandler>(path);\n }\n else\n {\n throw std::runtime_error(\"Invalid handler type: \" +\n handlerType);\n }\n\n \/* actions are required (presently). *\/\n const auto& a = item.at(\"actions\");\n std::unique_ptr<ActionPack> pack = std::make_unique<ActionPack>();\n\n \/* It hasn't been fully determined if any action being optional is\n * useful, so for now they will be required.\n * TODO: Evaluate how the behaviors change if some actions are\n * missing, does the code just assume it was successful? I would\n * think not.\n *\/\n const auto& prep = a.at(\"preparation\");\n const std::string prepareType = prep.at(\"type\");\n if (prepareType == \"systemd\")\n {\n const auto& unit = prep.at(\"unit\");\n pack->preparation = SystemdPreparation::CreatePreparation(\n sdbusplus::bus::new_default(), unit);\n }\n else\n {\n throw std::runtime_error(\"Invalid preparation type: \" +\n prepareType);\n }\n\n const auto& verify = a.at(\"verification\");\n const std::string verifyType = verify.at(\"type\");\n if (verifyType == \"fileSystemdVerify\")\n {\n pack->verification = std::move(buildFileSystemd(verify));\n }\n else\n {\n throw std::runtime_error(\"Invalid verification type:\" +\n verifyType);\n }\n\n const auto& update = a.at(\"update\");\n const std::string updateType = update.at(\"type\");\n if (updateType == \"reboot\")\n {\n pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(\n sdbusplus::bus::new_default(), \"reboot.target\",\n \"replace-irreversibly\");\n }\n else if (updateType == \"fileSystemdUpdate\")\n {\n pack->update = std::move(buildFileSystemd(update));\n }\n else if (updateType == \"systemd\")\n {\n const auto& unit = update.at(\"unit\");\n\n \/* the mode parameter is optional. *\/\n std::string systemdMode = \"replace\";\n const auto& mode = update.find(\"mode\");\n if (mode != update.end())\n {\n systemdMode = update.at(\"mode\").get<std::string>();\n }\n\n pack->update = SystemdUpdateMechanism::CreateSystemdUpdate(\n sdbusplus::bus::new_default(), unit, systemdMode);\n }\n else\n {\n throw std::runtime_error(\"Invalid update type: \" + updateType);\n }\n\n output.actions = std::move(pack);\n handlers.push_back(std::move(output));\n }\n catch (const std::exception& e)\n {\n \/* TODO: Once phosphor-logging supports unit-test injection, fix\n * this to log.\n *\/\n std::fprintf(stderr,\n \"Excepted building HandlerConfig from json: %s\\n\",\n e.what());\n }\n }\n\n return handlers;\n}\n\nstd::vector<HandlerConfig> BuildHandlerConfigs(const std::string& directory)\n{\n using namespace phosphor::logging;\n\n std::vector<HandlerConfig> output;\n\n std::vector<std::string> jsonPaths = GetJsonList(directory);\n\n for (const auto& path : jsonPaths)\n {\n std::ifstream jsonFile(path);\n if (!jsonFile.is_open())\n {\n log<level::ERR>(\"Unable to open json file\",\n entry(\"PATH=%s\", path.c_str()));\n continue;\n }\n\n auto data = nlohmann::json::parse(jsonFile, nullptr, false);\n if (data.is_discarded())\n {\n log<level::ERR>(\"Parsing json failed\",\n entry(\"PATH=%s\", path.c_str()));\n continue;\n }\n\n std::vector<HandlerConfig> configs = buildHandlerFromJson(data);\n std::move(configs.begin(), configs.end(), std::back_inserter(output));\n }\n\n return output;\n}\n\n} \/\/ namespace ipmi_flash\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#include \"..\/precompiled.hpp\"\n#include \"abstract_stream_socket.hpp\"\n#include \"socket_address.hpp\"\n#include \"..\/static\/network_driver.hpp\"\n#include \"..\/utilities.hpp\"\n\nnamespace poseidon {\n\nAbstract_Stream_Socket::\n~Abstract_Stream_Socket()\n {\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_call_stream_preshutdown_nolock()\nnoexcept\n try {\n \/\/ Call `do_stream_preshutdown_nolock()`, ignoring any exeptions.\n return this->do_stream_preshutdown_nolock();\n }\n catch(const exception& stdex) {\n POSEIDON_LOG_WARN(\"Failed to perform graceful shutdown on stream socket: $1\\n\"\n \"[exception class `$2`]\",\n stdex.what(), typeid(stdex).name());\n return io_result_eof;\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_async_shutdown_nolock()\nnoexcept\n {\n switch(this->m_cstate) {\n case connection_state_initial:\n case connection_state_connecting:\n \/\/ Shut down the connection. Discard pending data.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (not established): $1\", this);\n return io_result_eof;\n\n case connection_state_established: {\n \/\/ Ensure pending data are delivered.\n if(this->m_wqueue.size()) {\n ::shutdown(this->get_fd(), SHUT_RD);\n this->m_cstate = connection_state_closing;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSING (data pending): $1\", this);\n return io_result_not_eof;\n }\n\n \/\/ Wait for shutdown.\n auto io_res = this->do_call_stream_preshutdown_nolock();\n if(io_res != io_result_eof) {\n ::shutdown(this->get_fd(), SHUT_RD);\n this->m_cstate = connection_state_closing;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSING (preshutdown pending): $1\", this);\n return io_res;\n }\n\n \/\/ Close the connection.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (pending data clear): $1\", this);\n return io_result_eof;\n }\n\n case connection_state_closing: {\n \/\/ Ensure pending data are delivered.\n if(this->m_wqueue.size())\n return io_result_not_eof;\n\n \/\/ Wait for shutdown.\n auto io_res = this->do_call_stream_preshutdown_nolock();\n if(io_res != io_result_eof)\n return io_res;\n\n \/\/ Close the connection.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (pending data clear): $1\", this);\n return io_result_eof;\n }\n\n case connection_state_closed:\n \/\/ Do nothing.\n return io_result_eof;\n\n default:\n ROCKET_ASSERT(false);\n }\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size)\n {\n lock.assign(this->m_mutex);\n\n \/\/ If the stream is in CLOSED state, fail.\n if(this->m_cstate == connection_state_closed)\n return io_result_eof;\n\n \/\/ Try reading some bytes.\n auto io_res = this->do_stream_read_nolock(hint, size);\n if(io_res < 0)\n return io_res;\n\n if(io_res == io_result_eof) {\n this->do_async_shutdown_nolock();\n return io_result_eof;\n }\n\n \/\/ Process the data that have been read.\n lock.unlock();\n this->do_on_async_receive(hint, static_cast<size_t>(io_res));\n lock.assign(this->m_mutex);\n return io_res;\n }\n\nsize_t\nAbstract_Stream_Socket::\ndo_write_queue_size(Si_Mutex::unique_lock& lock)\nconst\n {\n lock.assign(this->m_mutex);\n\n \/\/ Get the size of pending data.\n size_t size = this->m_wqueue.size();\n if(size != 0)\n return size;\n\n \/\/ If a shutdown request is pending, report at least one byte.\n if(this->m_cstate == connection_state_closing)\n return 1;\n\n \/\/ There is nothing to write.\n return 0;\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_on_async_poll_write(Si_Mutex::unique_lock& lock, void* \/*hint*\/, size_t \/*size*\/)\n {\n lock.assign(this->m_mutex);\n\n \/\/ If the stream is in CLOSED state, fail.\n if(this->m_cstate == connection_state_closed)\n return io_result_eof;\n\n \/\/ If the stream is in CONNECTING state, mark it ESTABLISHED.\n if(this->m_cstate < connection_state_established) {\n this->m_cstate = connection_state_established;\n\n lock.unlock();\n this->do_on_async_establish();\n lock.assign(this->m_mutex);\n }\n\n \/\/ Try writing some bytes.\n size_t size = this->m_wqueue.size();\n if(size == 0) {\n if(this->m_cstate <= connection_state_established)\n return io_result_eof;\n\n \/\/ Shut down the connection completely now.\n return this->do_async_shutdown_nolock();\n }\n\n auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size);\n if(io_res < 0)\n return io_res;\n\n \/\/ Remove data that have been written.\n this->m_wqueue.discard(static_cast<size_t>(io_res));\n return io_res;\n }\n\nvoid\nAbstract_Stream_Socket::\ndo_on_async_poll_shutdown(int err)\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n this->m_cstate = connection_state_closed;\n lock.unlock();\n\n this->do_on_async_shutdown(err);\n }\n\nvoid\nAbstract_Stream_Socket::\ndo_async_connect(const Socket_Address& addr)\n {\n \/\/ Lock the stream and examine connection state.\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate != connection_state_initial)\n POSEIDON_THROW(\"another connection already in progress or established\");\n\n \/\/ Initiate the connection.\n this->do_stream_preconnect_nolock();\n\n \/\/ No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current\n \/\/ socket is set to the CONNECTING state.\n if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) {\n int err = errno;\n if(err != EINPROGRESS)\n POSEIDON_THROW(\"failed to initiate connection to '$2'\\n\"\n \"[`connect()` failed: $1]\",\n noadl::format_errno(err), addr);\n }\n this->m_cstate = connection_state_connecting;\n }\n\nSocket_Address\nAbstract_Stream_Socket::\nget_remote_address()\nconst\n {\n \/\/ Try getting the remote address.\n Socket_Address::storage_type addrst;\n Socket_Address::size_type addrlen = sizeof(addrst);\n if(::getpeername(this->get_fd(), addrst, &addrlen) != 0)\n POSEIDON_THROW(\"could not get remote socket address\\n\"\n \"[`getpeername()` failed: $1]\",\n noadl::format_errno(errno));\n return { addrst, addrlen };\n }\n\nbool\nAbstract_Stream_Socket::\nasync_send(const void* data, size_t size)\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate > connection_state_established)\n return false;\n\n \/\/ Append data to the write queue.\n this->m_wqueue.putn(static_cast<const char*>(data), size);\n lock.unlock();\n\n \/\/ Notify the driver about availability of outgoing data.\n Network_Driver::notify_writable_internal(this);\n return true;\n }\n\nbool\nAbstract_Stream_Socket::\nasync_shutdown()\nnoexcept\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate > connection_state_established)\n return false;\n\n \/\/ Initiate asynchronous shutdown.\n this->do_async_shutdown_nolock();\n lock.unlock();\n\n \/\/ Notify the driver about availability of outgoing data.\n Network_Driver::notify_writable_internal(this);\n return true;\n }\n\n} \/\/ namespace poseidon\n<commit_msg>network\/abstract_stream_socket: Add EOF log<commit_after>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#include \"..\/precompiled.hpp\"\n#include \"abstract_stream_socket.hpp\"\n#include \"socket_address.hpp\"\n#include \"..\/static\/network_driver.hpp\"\n#include \"..\/utilities.hpp\"\n\nnamespace poseidon {\n\nAbstract_Stream_Socket::\n~Abstract_Stream_Socket()\n {\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_call_stream_preshutdown_nolock()\nnoexcept\n try {\n \/\/ Call `do_stream_preshutdown_nolock()`, ignoring any exeptions.\n return this->do_stream_preshutdown_nolock();\n }\n catch(const exception& stdex) {\n POSEIDON_LOG_WARN(\"Failed to perform graceful shutdown on stream socket: $1\\n\"\n \"[exception class `$2`]\",\n stdex.what(), typeid(stdex).name());\n return io_result_eof;\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_async_shutdown_nolock()\nnoexcept\n {\n switch(this->m_cstate) {\n case connection_state_initial:\n case connection_state_connecting:\n \/\/ Shut down the connection. Discard pending data.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (not established): $1\", this);\n return io_result_eof;\n\n case connection_state_established: {\n \/\/ Ensure pending data are delivered.\n if(this->m_wqueue.size()) {\n ::shutdown(this->get_fd(), SHUT_RD);\n this->m_cstate = connection_state_closing;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSING (data pending): $1\", this);\n return io_result_not_eof;\n }\n\n \/\/ Wait for shutdown.\n auto io_res = this->do_call_stream_preshutdown_nolock();\n if(io_res != io_result_eof) {\n ::shutdown(this->get_fd(), SHUT_RD);\n this->m_cstate = connection_state_closing;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSING (preshutdown pending): $1\", this);\n return io_res;\n }\n\n \/\/ Close the connection.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (pending data clear): $1\", this);\n return io_result_eof;\n }\n\n case connection_state_closing: {\n \/\/ Ensure pending data are delivered.\n if(this->m_wqueue.size())\n return io_result_not_eof;\n\n \/\/ Wait for shutdown.\n auto io_res = this->do_call_stream_preshutdown_nolock();\n if(io_res != io_result_eof)\n return io_res;\n\n \/\/ Close the connection.\n ::shutdown(this->get_fd(), SHUT_RDWR);\n this->m_cstate = connection_state_closed;\n POSEIDON_LOG_TRACE(\"Marked stream socket as CLOSED (pending data clear): $1\", this);\n return io_result_eof;\n }\n\n case connection_state_closed:\n \/\/ Do nothing.\n return io_result_eof;\n\n default:\n ROCKET_ASSERT(false);\n }\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size)\n {\n lock.assign(this->m_mutex);\n\n \/\/ If the stream is in CLOSED state, fail.\n if(this->m_cstate == connection_state_closed)\n return io_result_eof;\n\n \/\/ Try reading some bytes.\n auto io_res = this->do_stream_read_nolock(hint, size);\n if(io_res < 0)\n return io_res;\n\n if(io_res == io_result_eof) {\n POSEIDON_LOG_TRACE(\"End of stream encountered: $1\", this);\n this->do_async_shutdown_nolock();\n return io_result_eof;\n }\n\n \/\/ Process the data that have been read.\n lock.unlock();\n this->do_on_async_receive(hint, static_cast<size_t>(io_res));\n lock.assign(this->m_mutex);\n return io_res;\n }\n\nsize_t\nAbstract_Stream_Socket::\ndo_write_queue_size(Si_Mutex::unique_lock& lock)\nconst\n {\n lock.assign(this->m_mutex);\n\n \/\/ Get the size of pending data.\n size_t size = this->m_wqueue.size();\n if(size != 0)\n return size;\n\n \/\/ If a shutdown request is pending, report at least one byte.\n if(this->m_cstate == connection_state_closing)\n return 1;\n\n \/\/ There is nothing to write.\n return 0;\n }\n\nIO_Result\nAbstract_Stream_Socket::\ndo_on_async_poll_write(Si_Mutex::unique_lock& lock, void* \/*hint*\/, size_t \/*size*\/)\n {\n lock.assign(this->m_mutex);\n\n \/\/ If the stream is in CLOSED state, fail.\n if(this->m_cstate == connection_state_closed)\n return io_result_eof;\n\n \/\/ If the stream is in CONNECTING state, mark it ESTABLISHED.\n if(this->m_cstate < connection_state_established) {\n this->m_cstate = connection_state_established;\n\n lock.unlock();\n this->do_on_async_establish();\n lock.assign(this->m_mutex);\n }\n\n \/\/ Try writing some bytes.\n size_t size = this->m_wqueue.size();\n if(size == 0) {\n if(this->m_cstate <= connection_state_established)\n return io_result_eof;\n\n \/\/ Shut down the connection completely now.\n return this->do_async_shutdown_nolock();\n }\n\n auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size);\n if(io_res < 0)\n return io_res;\n\n \/\/ Remove data that have been written.\n this->m_wqueue.discard(static_cast<size_t>(io_res));\n return io_res;\n }\n\nvoid\nAbstract_Stream_Socket::\ndo_on_async_poll_shutdown(int err)\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n this->m_cstate = connection_state_closed;\n lock.unlock();\n\n this->do_on_async_shutdown(err);\n }\n\nvoid\nAbstract_Stream_Socket::\ndo_async_connect(const Socket_Address& addr)\n {\n \/\/ Lock the stream and examine connection state.\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate != connection_state_initial)\n POSEIDON_THROW(\"another connection already in progress or established\");\n\n \/\/ Initiate the connection.\n this->do_stream_preconnect_nolock();\n\n \/\/ No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current\n \/\/ socket is set to the CONNECTING state.\n if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) {\n int err = errno;\n if(err != EINPROGRESS)\n POSEIDON_THROW(\"failed to initiate connection to '$2'\\n\"\n \"[`connect()` failed: $1]\",\n noadl::format_errno(err), addr);\n }\n this->m_cstate = connection_state_connecting;\n }\n\nSocket_Address\nAbstract_Stream_Socket::\nget_remote_address()\nconst\n {\n \/\/ Try getting the remote address.\n Socket_Address::storage_type addrst;\n Socket_Address::size_type addrlen = sizeof(addrst);\n if(::getpeername(this->get_fd(), addrst, &addrlen) != 0)\n POSEIDON_THROW(\"could not get remote socket address\\n\"\n \"[`getpeername()` failed: $1]\",\n noadl::format_errno(errno));\n return { addrst, addrlen };\n }\n\nbool\nAbstract_Stream_Socket::\nasync_send(const void* data, size_t size)\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate > connection_state_established)\n return false;\n\n \/\/ Append data to the write queue.\n this->m_wqueue.putn(static_cast<const char*>(data), size);\n lock.unlock();\n\n \/\/ Notify the driver about availability of outgoing data.\n Network_Driver::notify_writable_internal(this);\n return true;\n }\n\nbool\nAbstract_Stream_Socket::\nasync_shutdown()\nnoexcept\n {\n Si_Mutex::unique_lock lock(this->m_mutex);\n if(this->m_cstate > connection_state_established)\n return false;\n\n \/\/ Initiate asynchronous shutdown.\n this->do_async_shutdown_nolock();\n lock.unlock();\n\n \/\/ Notify the driver about availability of outgoing data.\n Network_Driver::notify_writable_internal(this);\n return true;\n }\n\n} \/\/ namespace poseidon\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#ifndef SERIALIZER_LOG_CONFIG_HPP_\n#define SERIALIZER_LOG_CONFIG_HPP_\n\n#include <string>\n\n#include \"config\/args.hpp\"\n#include \"serializer\/types.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\n\/* Configuration for the serializer that can change from run to run *\/\n\nstruct log_serializer_dynamic_config_t {\n log_serializer_dynamic_config_t() {\n gc_low_ratio = DEFAULT_GC_LOW_RATIO;\n gc_high_ratio = DEFAULT_GC_HIGH_RATIO;\n read_ahead = true;\n io_batch_factor = DEFAULT_IO_BATCH_FACTOR;\n }\n\n \/* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect\n garbage until it reaches gc_low_ratio. *\/\n double gc_low_ratio, gc_high_ratio;\n\n \/* The (minimal) batch size of i\/o requests being taken from a single i\/o account.\n It is a factor because the actual batch size is this factor multiplied by the\n i\/o priority of the account. *\/\n int32_t io_batch_factor;\n\n \/* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives *\/\n bool read_ahead;\n\n RDB_MAKE_ME_SERIALIZABLE_4(gc_low_ratio, gc_high_ratio, io_batch_factor, read_ahead);\n};\n\n\/* This is equivalent to log_serializer_static_config_t below, but is an on-disk\nstructure. Changes to this change the on-disk database format! *\/\nstruct log_serializer_on_disk_static_config_t {\n uint64_t block_size_;\n uint64_t extent_size_;\n\n \/\/ Some helpers\n uint64_t blocks_per_extent() const { return extent_size_ \/ block_size_; }\n int extent_index(int64_t offset) const { return offset \/ extent_size_; }\n\n \/\/ Minimize calls to these.\n block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); }\n uint64_t extent_size() const { return extent_size_; }\n};\n\n\/* Configuration for the serializer that is set when the database is created *\/\nstruct log_serializer_static_config_t : public log_serializer_on_disk_static_config_t {\n log_serializer_static_config_t() {\n extent_size_ = DEFAULT_EXTENT_SIZE;\n block_size_ = DEFAULT_BTREE_BLOCK_SIZE;\n }\n\n RDB_MAKE_ME_SERIALIZABLE_2(block_size_, extent_size_);\n};\n\n#endif \/* SERIALIZER_LOG_CONFIG_HPP_ *\/\n\n<commit_msg>Made extent_index return an unsigned int, not an int.<commit_after>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#ifndef SERIALIZER_LOG_CONFIG_HPP_\n#define SERIALIZER_LOG_CONFIG_HPP_\n\n#include <string>\n\n#include \"config\/args.hpp\"\n#include \"serializer\/types.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\n\/* Configuration for the serializer that can change from run to run *\/\n\nstruct log_serializer_dynamic_config_t {\n log_serializer_dynamic_config_t() {\n gc_low_ratio = DEFAULT_GC_LOW_RATIO;\n gc_high_ratio = DEFAULT_GC_HIGH_RATIO;\n read_ahead = true;\n io_batch_factor = DEFAULT_IO_BATCH_FACTOR;\n }\n\n \/* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect\n garbage until it reaches gc_low_ratio. *\/\n double gc_low_ratio, gc_high_ratio;\n\n \/* The (minimal) batch size of i\/o requests being taken from a single i\/o account.\n It is a factor because the actual batch size is this factor multiplied by the\n i\/o priority of the account. *\/\n int32_t io_batch_factor;\n\n \/* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives *\/\n bool read_ahead;\n\n RDB_MAKE_ME_SERIALIZABLE_4(gc_low_ratio, gc_high_ratio, io_batch_factor, read_ahead);\n};\n\n\/* This is equivalent to log_serializer_static_config_t below, but is an on-disk\nstructure. Changes to this change the on-disk database format! *\/\nstruct log_serializer_on_disk_static_config_t {\n uint64_t block_size_;\n uint64_t extent_size_;\n\n \/\/ Some helpers\n uint64_t blocks_per_extent() const { return extent_size_ \/ block_size_; }\n unsigned int extent_index(int64_t offset) const { return offset \/ extent_size_; }\n\n \/\/ Minimize calls to these.\n block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); }\n uint64_t extent_size() const { return extent_size_; }\n};\n\n\/* Configuration for the serializer that is set when the database is created *\/\nstruct log_serializer_static_config_t : public log_serializer_on_disk_static_config_t {\n log_serializer_static_config_t() {\n extent_size_ = DEFAULT_EXTENT_SIZE;\n block_size_ = DEFAULT_BTREE_BLOCK_SIZE;\n }\n\n RDB_MAKE_ME_SERIALIZABLE_2(block_size_, extent_size_);\n};\n\n#endif \/* SERIALIZER_LOG_CONFIG_HPP_ *\/\n\n<|endoftext|>"} {"text":"<commit_before>#include <QTimer>\n\n#include \"server-status-service.h\"\n#include \"seafile-applet.h\"\n#include \"account-mgr.h\"\n#include \"api\/api-error.h\"\n#include \"api\/requests.h\"\n\nnamespace {\n\nconst int kRefreshInterval = 3 * 60 * 1000; \/\/ 3 min\nconst int kRefreshIntervalForUnconnected = 30 * 1000; \/\/ 30 sec\n\n}\n\nSINGLETON_IMPL(ServerStatusService)\n\nServerStatusService::ServerStatusService(QObject *parent)\n : QObject(parent)\n{\n refresh_timer_ = new QTimer(this);\n refresh_unconnected_timer_ = new QTimer(this);\n connect(refresh_timer_, SIGNAL(timeout()),\n this, SLOT(refresh()));\n connect(refresh_unconnected_timer_, SIGNAL(timeout()),\n this, SLOT(refreshUnconnected()));\n refresh();\n}\n\nvoid ServerStatusService::start()\n{\n refresh_timer_->start(kRefreshInterval);\n refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);\n}\n\nvoid ServerStatusService::stop()\n{\n refresh_timer_->stop();\n refresh_unconnected_timer_->stop();\n}\n\nvoid ServerStatusService::refresh(bool only_refresh_unconnected)\n{\n const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();\n for (size_t i = 0; i < accounts.size(); i++) {\n const QUrl& url = accounts[i].serverUrl;\n if (requests_.contains(url.host())) {\n return;\n }\n\n if (!statuses_.contains(url.host())) {\n statuses_[url.host()] = ServerStatus(url, false);\n }\n\n if (only_refresh_unconnected && isServerConnected(url)) {\n return;\n }\n pingServer(url);\n }\n}\n\nvoid ServerStatusService::pingServer(const QUrl& url)\n{\n PingServerRequest *req = new PingServerRequest(url);\n connect(req, SIGNAL(success()),\n this, SLOT(onPingServerSuccess()));\n connect(req, SIGNAL(failed(const ApiError&)),\n this, SLOT(onPingServerFailed()));\n req->send();\n requests_[url.host()] = req;\n}\n\n\nvoid ServerStatusService::onPingServerSuccess()\n{\n PingServerRequest *req = (PingServerRequest *)sender();\n statuses_[req->url().host()] = ServerStatus(req->url(), true);\n emit serverStatusChanged();\n requests_.take(req->url().host())->deleteLater();\n}\n\nvoid ServerStatusService::onPingServerFailed()\n{\n PingServerRequest *req = (PingServerRequest *)sender();\n statuses_[req->url().host()] = ServerStatus(req->url(), false);\n emit serverStatusChanged();\n requests_.take(req->url().host())->deleteLater();\n}\n\nbool ServerStatusService::allServersConnected() const\n{\n foreach (const ServerStatus& status, statuses()) {\n if (!status.connected) {\n return false;\n }\n }\n\n return true;\n}\n\nbool ServerStatusService::allServersDisconnected() const\n{\n foreach (const ServerStatus& status, statuses()) {\n if (status.connected) {\n return false;\n }\n }\n\n return true;\n}\n\n\nbool ServerStatusService::isServerConnected(const QUrl& url) const\n{\n return statuses_.value(url.host()).connected;\n}\n<commit_msg>Set default server connection to true.<commit_after>#include <QTimer>\n\n#include \"server-status-service.h\"\n#include \"seafile-applet.h\"\n#include \"account-mgr.h\"\n#include \"api\/api-error.h\"\n#include \"api\/requests.h\"\n\nnamespace {\n\nconst int kRefreshInterval = 3 * 60 * 1000; \/\/ 3 min\nconst int kRefreshIntervalForUnconnected = 30 * 1000; \/\/ 30 sec\n\n}\n\nSINGLETON_IMPL(ServerStatusService)\n\nServerStatusService::ServerStatusService(QObject *parent)\n : QObject(parent)\n{\n refresh_timer_ = new QTimer(this);\n refresh_unconnected_timer_ = new QTimer(this);\n connect(refresh_timer_, SIGNAL(timeout()),\n this, SLOT(refresh()));\n connect(refresh_unconnected_timer_, SIGNAL(timeout()),\n this, SLOT(refreshUnconnected()));\n refresh();\n}\n\nvoid ServerStatusService::start()\n{\n refresh_timer_->start(kRefreshInterval);\n refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);\n}\n\nvoid ServerStatusService::stop()\n{\n refresh_timer_->stop();\n refresh_unconnected_timer_->stop();\n}\n\nvoid ServerStatusService::refresh(bool only_refresh_unconnected)\n{\n const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();\n for (size_t i = 0; i < accounts.size(); i++) {\n const QUrl& url = accounts[i].serverUrl;\n if (requests_.contains(url.host())) {\n return;\n }\n\n if (!statuses_.contains(url.host())) {\n statuses_[url.host()] = ServerStatus(url, true);\n }\n\n if (only_refresh_unconnected && isServerConnected(url)) {\n return;\n }\n pingServer(url);\n }\n}\n\nvoid ServerStatusService::pingServer(const QUrl& url)\n{\n PingServerRequest *req = new PingServerRequest(url);\n connect(req, SIGNAL(success()),\n this, SLOT(onPingServerSuccess()));\n connect(req, SIGNAL(failed(const ApiError&)),\n this, SLOT(onPingServerFailed()));\n req->send();\n requests_[url.host()] = req;\n}\n\n\nvoid ServerStatusService::onPingServerSuccess()\n{\n PingServerRequest *req = (PingServerRequest *)sender();\n statuses_[req->url().host()] = ServerStatus(req->url(), true);\n emit serverStatusChanged();\n requests_.take(req->url().host())->deleteLater();\n}\n\nvoid ServerStatusService::onPingServerFailed()\n{\n PingServerRequest *req = (PingServerRequest *)sender();\n statuses_[req->url().host()] = ServerStatus(req->url(), false);\n emit serverStatusChanged();\n requests_.take(req->url().host())->deleteLater();\n}\n\nbool ServerStatusService::allServersConnected() const\n{\n foreach (const ServerStatus& status, statuses()) {\n if (!status.connected) {\n return false;\n }\n }\n\n return true;\n}\n\nbool ServerStatusService::allServersDisconnected() const\n{\n foreach (const ServerStatus& status, statuses()) {\n if (status.connected) {\n return false;\n }\n }\n\n return true;\n}\n\n\nbool ServerStatusService::isServerConnected(const QUrl& url) const\n{\n return statuses_.value(url.host()).connected;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: SwXMLBlockImport.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 09:05:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _SW_XMLBLOCKIMPORT_HXX\n#include <SwXMLBlockImport.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX\n#include <SwXMLBlockListContext.hxx>\n#endif\n#ifndef _SW_XMLTEXTBLOCKS_HXX\n#include <SwXMLTextBlocks.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\nusing namespace ::rtl;\n\nsal_Char __READONLY_DATA sXML_np__block_list[] = \"_block-list\";\nsal_Char __READONLY_DATA sXML_np__office[] = \"_ooffice\";\nsal_Char __READONLY_DATA sXML_np__text[] = \"_otext\";\n\n\/\/ #110680#\nSwXMLBlockListImport::SwXMLBlockListImport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n SwXMLTextBlocks &rBlocks )\n: SvXMLImport( xServiceFactory, 0 ),\n rBlockList (rBlocks)\n{\n GetNamespaceMap().Add( OUString ( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__block_list ) ),\n GetXMLToken ( XML_N_BLOCK_LIST ),\n XML_NAMESPACE_BLOCKLIST );\n}\n\nSwXMLBlockListImport::~SwXMLBlockListImport ( void )\n throw ()\n{\n}\n\nSvXMLImportContext *SwXMLBlockListImport::CreateContext(\n sal_uInt16 nPrefix,\n const OUString& rLocalName,\n const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n if ( XML_NAMESPACE_BLOCKLIST == nPrefix &&\n IsXMLToken ( rLocalName, XML_BLOCK_LIST ) )\n pContext = new SwXMLBlockListContext( *this, nPrefix, rLocalName,\n xAttrList );\n else\n pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n return pContext;\n}\n\n\/\/ #110680#\nSwXMLTextBlockImport::SwXMLTextBlockImport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n SwXMLTextBlocks &rBlocks,\n String & rNewText,\n sal_Bool bNewTextOnly )\n: SvXMLImport(xServiceFactory, IMPORT_ALL ),\n rBlockList ( rBlocks ),\n bTextOnly ( bNewTextOnly ),\n m_rText ( rNewText )\n{\n GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),\n GetXMLToken(XML_N_OFFICE_OOO),\n XML_NAMESPACE_OFFICE );\n GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),\n GetXMLToken(XML_N_TEXT_OOO),\n XML_NAMESPACE_TEXT );\n}\n\nSwXMLTextBlockImport::~SwXMLTextBlockImport ( void )\n throw()\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockImport::CreateContext(\n sal_uInt16 nPrefix,\n const OUString& rLocalName,\n const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n if( XML_NAMESPACE_OFFICE == nPrefix &&\n IsXMLToken ( rLocalName, bTextOnly ? XML_DOCUMENT : XML_DOCUMENT_CONTENT ) )\n pContext = new SwXMLTextBlockDocumentContext( *this, nPrefix, rLocalName, xAttrList );\n else\n pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n return pContext;\n}\nvoid SAL_CALL SwXMLTextBlockImport::endDocument(void)\n throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException )\n{\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.664); FILE MERGED 2005\/09\/05 13:40:34 rt 1.6.664.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SwXMLBlockImport.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 04:42:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SW_XMLBLOCKIMPORT_HXX\n#include <SwXMLBlockImport.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX\n#include <SwXMLBlockListContext.hxx>\n#endif\n#ifndef _SW_XMLTEXTBLOCKS_HXX\n#include <SwXMLTextBlocks.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\nusing namespace ::rtl;\n\nsal_Char __READONLY_DATA sXML_np__block_list[] = \"_block-list\";\nsal_Char __READONLY_DATA sXML_np__office[] = \"_ooffice\";\nsal_Char __READONLY_DATA sXML_np__text[] = \"_otext\";\n\n\/\/ #110680#\nSwXMLBlockListImport::SwXMLBlockListImport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n SwXMLTextBlocks &rBlocks )\n: SvXMLImport( xServiceFactory, 0 ),\n rBlockList (rBlocks)\n{\n GetNamespaceMap().Add( OUString ( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__block_list ) ),\n GetXMLToken ( XML_N_BLOCK_LIST ),\n XML_NAMESPACE_BLOCKLIST );\n}\n\nSwXMLBlockListImport::~SwXMLBlockListImport ( void )\n throw ()\n{\n}\n\nSvXMLImportContext *SwXMLBlockListImport::CreateContext(\n sal_uInt16 nPrefix,\n const OUString& rLocalName,\n const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n if ( XML_NAMESPACE_BLOCKLIST == nPrefix &&\n IsXMLToken ( rLocalName, XML_BLOCK_LIST ) )\n pContext = new SwXMLBlockListContext( *this, nPrefix, rLocalName,\n xAttrList );\n else\n pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n return pContext;\n}\n\n\/\/ #110680#\nSwXMLTextBlockImport::SwXMLTextBlockImport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n SwXMLTextBlocks &rBlocks,\n String & rNewText,\n sal_Bool bNewTextOnly )\n: SvXMLImport(xServiceFactory, IMPORT_ALL ),\n rBlockList ( rBlocks ),\n bTextOnly ( bNewTextOnly ),\n m_rText ( rNewText )\n{\n GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),\n GetXMLToken(XML_N_OFFICE_OOO),\n XML_NAMESPACE_OFFICE );\n GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),\n GetXMLToken(XML_N_TEXT_OOO),\n XML_NAMESPACE_TEXT );\n}\n\nSwXMLTextBlockImport::~SwXMLTextBlockImport ( void )\n throw()\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockImport::CreateContext(\n sal_uInt16 nPrefix,\n const OUString& rLocalName,\n const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n if( XML_NAMESPACE_OFFICE == nPrefix &&\n IsXMLToken ( rLocalName, bTextOnly ? XML_DOCUMENT : XML_DOCUMENT_CONTENT ) )\n pContext = new SwXMLTextBlockDocumentContext( *this, nPrefix, rLocalName, xAttrList );\n else\n pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n return pContext;\n}\nvoid SAL_CALL SwXMLTextBlockImport::endDocument(void)\n throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException )\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: writerwordglue.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 06:07:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n\/\/\/ @HTML\n\n#ifndef SW_WRITERWORDGLUE\n#define SW_WRITERWORDGLUE\n\n#ifndef WW_NEEDED_CAST_HXX\n# include \"needed_cast.hxx\"\n#endif\n#ifndef WW_TYPES\n# include \"types.hxx\"\n#endif\n\nclass SwFrmFmt;\nclass SfxItemSet;\nclass SwDoc;\nclass SwTxtFmtColl;\nclass String;\nclass PoolItems;\n\nnamespace sw\n{\n namespace types\n {\n \/** A static_cast style cast for conversion of word types to writer's\n\n There are a number of places where the winword types are larger\n than the writer equivalents requiring a cast to silence warnings.\n To avoid throwing away this useful information writer_cast is used\n to identify where writer's types are smaller than word's.\n\n Based on needed_cast it will compile time assert if the cast\n becomes unnecessary at any time in the future.\n\n @tplparam\n Ret the desired return type\n\n @tplparam\n Param the type of the in param\n\n @param\n in the value to cast from Param to Ret\n\n @return in casted to type Ret\n *\/\n template<typename Ret, typename Param> Ret writer_cast(Param in)\n {\n return ww::needed_cast<Ret, Param>(in);\n }\n\n \/** A static_cast style cast for conversion of writer types to word's\n\n There are a number of places where the writer types are larger than\n the winword equivalents requiring a cast to silence warnings. To\n avoid throwing away this useful information writer_cast is used to\n identify where word's types are smaller than writers's.\n\n Based on needed_cast it will compile time assert if the cast\n becomes unnecessary at any time in the future.\n\n @tplparam\n Ret the desired return type\n\n @tplparam\n Param the type of the in param\n\n @param\n in the value to cast from Param to Ret\n\n @return in casted to type Ret\n *\/\n template<typename Ret, typename Param> Ret msword_cast(Param in)\n {\n return ww::needed_cast<Ret, Param>(in);\n }\n\n\n \/** If a page dimension is close to a standard page size, snap to it.\n\n Commonly a page dimension is slightly different from a standard\n page size, so close that its likely a rounding error after\n creeping in. Use this to snap to standard sizes when within a\n trivial distance from a standard size.\n\n @param\n nSize the dimension to test against standard dimensions\n\n @return New dimension to use, equal to nSize unless within a\n trivial amount of a standard page dimension\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n *\/\n long SnapPageDimension(long nSize) throw();\n }\n\n namespace util\n {\n \/** See if two page formats can be expressed as a single word section\n\n Word doesn't have the idea of page descriptors and follow styles\n like writer does, the only thing it has is a section with a\n different title page. The only difference of the title page from\n the rest of the section is different headers\/footers, everything\n else is the same.\n\n So this function compares two writer page fmts and sees if the\n follow frame and the title frame are the same from word persecptive\n except for the content of their headers.\n\n @return true if the rTitleFmt followed by rFollowFmt could be\n expressed in word as a single word Section with different title\n page enabled.\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n\n @see #i4320#\/#i14509#\/#i11717# for examples\n *\/\n bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt,\n const SwFrmFmt &rFollowFmt);\n\n \/** Make export a word section top\/bottom values easy\n\n The top and bottom margins in word and writer are expressed in very\n different ways. This class provides the equivalent word values for\n header\/footer distances from a given writer attrset of a page\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n *\/\n class HdFtDistanceGlue\n {\n private:\n bool mbHasHeader;\n bool mbHasFooter;\n public:\n sal_uInt16 dyaHdrTop;\n sal_uInt16 dyaHdrBottom;\n sal_uInt16 dyaTop;\n sal_uInt16 dyaBottom;\n HdFtDistanceGlue(const SfxItemSet &rPage);\n bool HasHeader() const { return mbHasHeader; }\n bool HasFooter() const { return mbHasFooter; }\n\n \/** Is the top of the page the same in both objects\n\n Ignoring the difference in header and footers, will the main\n document text have the same top\/bottom bounds in word between\n both these objects.\n\n @param\n rOther the other HdFtDistanceGlue to compare against\n\n @return true if the main text areas top and bottom is at the\n same location, false otherwise.\n *\/\n bool EqualTopBottom(const HdFtDistanceGlue &rOther) const;\n\n };\n }\n}\n\n#endif\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\n<commit_msg>INTEGRATION: CWS thaiissues (1.4.808); FILE MERGED<commit_after>\/*************************************************************************\n *\n * $RCSfile: writerwordglue.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2005-11-16 09:35:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): cmc@openoffice.org\n *\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n\/\/\/ @HTML\n\n#ifndef SW_WRITERWORDGLUE\n#define SW_WRITERWORDGLUE\n\n#ifndef WW_NEEDED_CAST_HXX\n# include \"needed_cast.hxx\"\n#endif\n#ifndef WW_TYPES\n# include \"types.hxx\"\n#endif\n\nclass SwFrmFmt;\nclass SfxItemSet;\nclass SwDoc;\nclass SwTxtFmtColl;\nclass String;\nclass PoolItems;\n\nnamespace sw\n{\n namespace types\n {\n \/** A static_cast style cast for conversion of word types to writer's\n\n There are a number of places where the winword types are larger\n than the writer equivalents requiring a cast to silence warnings.\n To avoid throwing away this useful information writer_cast is used\n to identify where writer's types are smaller than word's.\n\n Based on needed_cast it will compile time assert if the cast\n becomes unnecessary at any time in the future.\n\n @tplparam\n Ret the desired return type\n\n @tplparam\n Param the type of the in param\n\n @param\n in the value to cast from Param to Ret\n\n @return in casted to type Ret\n *\/\n template<typename Ret, typename Param> Ret writer_cast(Param in)\n {\n return ww::needed_cast<Ret, Param>(in);\n }\n\n \/** A static_cast style cast for conversion of writer types to word's\n\n There are a number of places where the writer types are larger than\n the winword equivalents requiring a cast to silence warnings. To\n avoid throwing away this useful information writer_cast is used to\n identify where word's types are smaller than writers's.\n\n Based on needed_cast it will compile time assert if the cast\n becomes unnecessary at any time in the future.\n\n @tplparam\n Ret the desired return type\n\n @tplparam\n Param the type of the in param\n\n @param\n in the value to cast from Param to Ret\n\n @return in casted to type Ret\n *\/\n template<typename Ret, typename Param> Ret msword_cast(Param in)\n {\n return ww::needed_cast<Ret, Param>(in);\n }\n\n\n \/** If a page dimension is close to a standard page size, snap to it.\n\n Commonly a page dimension is slightly different from a standard\n page size, so close that its likely a rounding error after\n creeping in. Use this to snap to standard sizes when within a\n trivial distance from a standard size.\n\n @param\n nSize the dimension to test against standard dimensions\n\n @return New dimension to use, equal to nSize unless within a\n trivial amount of a standard page dimension\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n *\/\n long SnapPageDimension(long nSize) throw();\n }\n\n namespace util\n {\n \/** See if two page formats can be expressed as a single word section\n\n Word doesn't have the idea of page descriptors and follow styles\n like writer does, the only thing it has is a section with a\n different title page. The only difference of the title page from\n the rest of the section is different headers\/footers, everything\n else is the same.\n\n So this function compares two writer page fmts and sees if the\n follow frame and the title frame are the same from word persecptive\n except for the content of their headers.\n\n @return true if the rTitleFmt followed by rFollowFmt could be\n expressed in word as a single word Section with different title\n page enabled.\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n\n @see #i4320#\/#i14509#\/#i11717# for examples\n *\/\n bool IsPlausableSingleWordSection(const SwFrmFmt &rTitleFmt,\n const SwFrmFmt &rFollowFmt);\n\n \/** Make export a word section top\/bottom values easy\n\n The top and bottom margins in word and writer are expressed in very\n different ways. This class provides the equivalent word values for\n header\/footer distances from a given writer attrset of a page\n\n @author\n <a href=\"mailto:cmc@openoffice.org\">Caolán McNamara<\/a>\n *\/\n class HdFtDistanceGlue\n {\n private:\n bool mbHasHeader;\n bool mbHasFooter;\n public:\n sal_uInt16 dyaHdrTop;\n sal_uInt16 dyaHdrBottom;\n sal_uInt16 dyaTop;\n sal_uInt16 dyaBottom;\n HdFtDistanceGlue(const SfxItemSet &rPage);\n bool HasHeader() const { return mbHasHeader; }\n bool HasFooter() const { return mbHasFooter; }\n\n \/** Is the top of the page the same in both objects\n\n Ignoring the difference in header and footers, will the main\n document text have the same top\/bottom bounds in word between\n both these objects.\n\n @param\n rOther the other HdFtDistanceGlue to compare against\n\n @return true if the main text areas top and bottom is at the\n same location, false otherwise.\n *\/\n bool EqualTopBottom(const HdFtDistanceGlue &rOther) const;\n\n };\n }\n}\n\n#endif\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>pretty it up a little<commit_after><|endoftext|>"} {"text":"<commit_before>#include <Eigen\/Dense>\n#include <Eigen\/Sparse>\n\n#include <iostream> \n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\n#include <unsupported\/Eigen\/SparseExtra>\n#include <Eigen\/Sparse>\n\n#include <omp.h>\n\n#include \"macau.h\"\n#include \"mvnormal.h\"\n#include \"utils.h\"\n#include \"latentprior.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\nvoid Macau::addPrior(ILatentPrior* prior) {\n priors.push_back( prior );\n}\n\nvoid Macau::setPrecision(double p) {\n alpha = p;\n}\n\nvoid Macau::setSamples(int b, int n) {\n burnin = b;\n nsamples = n;\n}\n\nvoid Macau::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) {\n Y.resize(nrows, ncols);\n sparseFromIJV(Y, rows, cols, values, N);\n Yt = Y.transpose();\n mean_rating = Y.sum() \/ Y.nonZeros();\n}\n\nvoid Macau::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) {\n Ytest.resize(nrows, ncols);\n sparseFromIJV(Ytest, rows, cols, values, N);\n}\n\ndouble Macau::getRmseTest() { return rmse_test; }\n\nvoid sparseFromIJV(SparseMatrix<double> &X, int* rows, int* cols, double* values, int N) {\n typedef Triplet<double> T;\n std::vector<T> tripletList;\n tripletList.reserve(N);\n for (int n = 0; n < N; n++) {\n tripletList.push_back(T(rows[n], cols[n], values[n]));\n }\n X.setFromTriplets(tripletList.begin(), tripletList.end());\n}\n\nvoid Macau::init() {\n unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();\n if (priors.size() != 2) {\n throw std::runtime_error(\"Only 2 priors are supported.\");\n }\n init_bmrng(seed1);\n MatrixXd* U = new MatrixXd(num_latent, Y.rows());\n MatrixXd* V = new MatrixXd(num_latent, Y.cols());\n U->setZero();\n V->setZero();\n samples.push_back(U);\n samples.push_back(V);\n}\n\nMacau::~Macau() {\n for (unsigned i = 0; i < samples.size(); i++) {\n delete samples[i];\n }\n}\n\ninline double sqr(double x) { return x*x; }\n\nvoid Macau::run() {\n init();\n std::cout << \"Sampling\" << endl;\n\n const int num_rows = Y.rows();\n const int num_cols = Y.cols();\n VectorXd predictions = VectorXd::Zero( Ytest.nonZeros() );\n\n auto start = tick();\n for (int i = 0; i < burnin + nsamples; i++) {\n if (i == burnin) {\n printf(\" ====== Burn-in complete, averaging samples ====== \\n\");\n }\n auto starti = tick();\n\n \/\/ sample latent vectors\n priors[0]->sample_latents(*(samples[0]), Yt, mean_rating, *(samples[1]), alpha, num_latent);\n priors[1]->sample_latents(*(samples[1]), Y, mean_rating, *(samples[0]), alpha, num_latent);\n\n \/\/ Sample hyperparams\n priors[0]->update_prior(*(samples[0]));\n priors[1]->update_prior(*(samples[1]));\n\n auto eval = eval_rmse(Ytest, (i < burnin) ? 0 : (i - burnin + 1), predictions, *(samples[1]), *(samples[0]), mean_rating);\n\n auto endi = tick();\n auto elapsed = endi - start;\n double samples_per_sec = (i + 1) * (num_rows + num_cols) \/ elapsed;\n double elapsedi = endi - starti;\n\n printf(\"Iter %d: RMSE: %4.4f\\tavg RMSE: %4.4f\\tFU(%1.3e) FV(%1.3e) [took %0.1fs, Samples\/sec: %6.1f]\\n\", i, eval.first, eval.second, samples[0]->norm(), samples[1]->norm(), elapsedi, samples_per_sec);\n rmse_test = eval.second;\n }\n}\n\nstd::pair<double,double> eval_rmse(SparseMatrix<double> & P, const int n, VectorXd & predictions, const MatrixXd &sample_m, const MatrixXd &sample_u, double mean_rating)\n{\n \/\/ TODO: parallelize\n double se = 0.0, se_avg = 0.0;\n unsigned idx = 0;\n for (int k = 0; k < P.outerSize(); ++k) {\n for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) {\n const double pred = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating;\n se += sqr(it.value() - pred);\n\n const double pred_avg = (n == 0) ? pred : (predictions[idx] + (pred - predictions[idx]) \/ n);\n se_avg += sqr(it.value() - pred_avg);\n predictions[idx++] = pred_avg;\n }\n }\n\n const unsigned N = P.nonZeros();\n const double rmse = sqrt( se \/ N );\n const double rmse_avg = sqrt( se_avg \/ N );\n return std::make_pair(rmse, rmse_avg);\n}\n<commit_msg>cleaned syntax<commit_after>#include <Eigen\/Dense>\n#include <Eigen\/Sparse>\n\n#include <iostream> \n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\n#include <unsupported\/Eigen\/SparseExtra>\n#include <Eigen\/Sparse>\n\n#include <omp.h>\n\n#include \"macau.h\"\n#include \"mvnormal.h\"\n#include \"utils.h\"\n#include \"latentprior.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\nvoid Macau::addPrior(ILatentPrior* prior) {\n priors.push_back( prior );\n}\n\nvoid Macau::setPrecision(double p) {\n alpha = p;\n}\n\nvoid Macau::setSamples(int b, int n) {\n burnin = b;\n nsamples = n;\n}\n\nvoid Macau::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) {\n Y.resize(nrows, ncols);\n sparseFromIJV(Y, rows, cols, values, N);\n Yt = Y.transpose();\n mean_rating = Y.sum() \/ Y.nonZeros();\n}\n\nvoid Macau::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) {\n Ytest.resize(nrows, ncols);\n sparseFromIJV(Ytest, rows, cols, values, N);\n}\n\ndouble Macau::getRmseTest() { return rmse_test; }\n\nvoid sparseFromIJV(SparseMatrix<double> &X, int* rows, int* cols, double* values, int N) {\n typedef Triplet<double> T;\n std::vector<T> tripletList;\n tripletList.reserve(N);\n for (int n = 0; n < N; n++) {\n tripletList.push_back(T(rows[n], cols[n], values[n]));\n }\n X.setFromTriplets(tripletList.begin(), tripletList.end());\n}\n\nvoid Macau::init() {\n unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();\n if (priors.size() != 2) {\n throw std::runtime_error(\"Only 2 priors are supported.\");\n }\n init_bmrng(seed1);\n MatrixXd* U = new MatrixXd(num_latent, Y.rows());\n MatrixXd* V = new MatrixXd(num_latent, Y.cols());\n U->setZero();\n V->setZero();\n samples.push_back(U);\n samples.push_back(V);\n}\n\nMacau::~Macau() {\n for (unsigned i = 0; i < samples.size(); i++) {\n delete samples[i];\n }\n}\n\ninline double sqr(double x) { return x*x; }\n\nvoid Macau::run() {\n init();\n std::cout << \"Sampling\" << endl;\n\n const int num_rows = Y.rows();\n const int num_cols = Y.cols();\n VectorXd predictions = VectorXd::Zero( Ytest.nonZeros() );\n\n auto start = tick();\n for (int i = 0; i < burnin + nsamples; i++) {\n if (i == burnin) {\n printf(\" ====== Burn-in complete, averaging samples ====== \\n\");\n }\n auto starti = tick();\n\n \/\/ sample latent vectors\n priors[0]->sample_latents(*samples[0], Yt, mean_rating, *samples[1], alpha, num_latent);\n priors[1]->sample_latents(*samples[1], Y, mean_rating, *samples[0], alpha, num_latent);\n\n \/\/ Sample hyperparams\n priors[0]->update_prior(*samples[0]);\n priors[1]->update_prior(*samples[1]);\n\n auto eval = eval_rmse(Ytest, (i < burnin) ? 0 : (i - burnin + 1), predictions, *samples[1], *samples[0], mean_rating);\n\n auto endi = tick();\n auto elapsed = endi - start;\n double samples_per_sec = (i + 1) * (num_rows + num_cols) \/ elapsed;\n double elapsedi = endi - starti;\n\n printf(\"Iter %d: RMSE: %4.4f\\tavg RMSE: %4.4f\\tFU(%1.3e) FV(%1.3e) [took %0.1fs, Samples\/sec: %6.1f]\\n\", i, eval.first, eval.second, samples[0]->norm(), samples[1]->norm(), elapsedi, samples_per_sec);\n rmse_test = eval.second;\n }\n}\n\nstd::pair<double,double> eval_rmse(SparseMatrix<double> & P, const int n, VectorXd & predictions, const MatrixXd &sample_m, const MatrixXd &sample_u, double mean_rating)\n{\n \/\/ TODO: parallelize\n double se = 0.0, se_avg = 0.0;\n unsigned idx = 0;\n for (int k = 0; k < P.outerSize(); ++k) {\n for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) {\n const double pred = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating;\n se += sqr(it.value() - pred);\n\n const double pred_avg = (n == 0) ? pred : (predictions[idx] + (pred - predictions[idx]) \/ n);\n se_avg += sqr(it.value() - pred_avg);\n predictions[idx++] = pred_avg;\n }\n }\n\n const unsigned N = P.nonZeros();\n const double rmse = sqrt( se \/ N );\n const double rmse_avg = sqrt( se_avg \/ N );\n return std::make_pair(rmse, rmse_avg);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the GLVis visualization tool and library. For more\n\/\/ information and source code availability see http:\/\/glvis.org.\n\/\/\n\/\/ GLVis is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef GLVIS_VSSOLUTION\n#define GLVIS_VSSOLUTION\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n\/\/ Rendering large numbers of text objects for element or vertex\n\/\/ numberings is slow. Turn it off above some entity count.\n#define MAX_RENDER_NUMBERING 1000\n\n\/\/ Visualization header file\n\nclass VisualizationSceneSolution : public VisualizationSceneScalarData\n{\nprotected:\n Vector *v_normals;\n GridFunction *rsol;\n\n int drawmesh, drawelems, drawnums;\n int displlist, linelist, lcurvelist;\n int bdrlist, drawbdr, draw_cp, cp_list;\n int e_nums_list, v_nums_list;\n \n void Init();\n\n void FindNewBox(double rx[], double ry[], double rval[]);\n\n void DrawCPLine(DenseMatrix &pointmat, Vector &values, Array<int> &ind);\n\n void GetRefinedDetJ(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr);\n\n \/\/ redefined for vector solution\n virtual void GetRefinedValues(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr);\n virtual int GetRefinedValuesAndNormals(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr,\n DenseMatrix &normals);\n\n void DrawLevelCurves(Array<int> &RG, DenseMatrix &pointmat,\n Vector &values, int sides, Array<double> &lvl,\n int flat = 0);\n\n int GetAutoRefineFactor();\n\n \/\/ Used for drawing markers for element and vertex numberings\n double GetElementLengthScale(int k);\n\npublic:\n int shading, TimesToRefine, EdgeRefineFactor;\n\n int attr_to_show, bdr_attr_to_show;\n Array<int> el_attr_to_show, bdr_el_attr_to_show;\n\n VisualizationSceneSolution();\n VisualizationSceneSolution(Mesh &m, Vector &s, Vector *normals = NULL);\n\n virtual ~VisualizationSceneSolution();\n\n void SetGridFunction(GridFunction & u) { rsol = &u; }\n\n void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,\n GridFunction *new_u = NULL);\n\n virtual void SetNewScalingFromBox();\n virtual void FindNewBox(bool prepare);\n virtual void FindNewValueRange(bool prepare);\n virtual void FindNewBoxAndValueRange(bool prepare)\n { FindNewBox(prepare); }\n virtual void FindMeshBox(bool prepare);\n\n virtual void ToggleLogscale(bool print);\n virtual void UpdateLevelLines() { PrepareLevelCurves(); }\n virtual void UpdateValueRange(bool prepare);\n\n void PrepareWithNormals();\n void PrepareFlat();\n void PrepareFlat2();\n\n virtual void PrepareLines();\n void PrepareLines2();\n void PrepareLines3();\n\n virtual void Prepare();\n void PrepareLevelCurves();\n void PrepareLevelCurves2();\n\n void PrepareBoundary();\n\n void PrepareNumbering();\n void PrepareElementNumbering();\n void PrepareElementNumbering1();\n void PrepareElementNumbering2();\n void PrepareVertexNumbering();\n void PrepareVertexNumbering1();\n void PrepareVertexNumbering2();\n\n void PrepareCP();\n\n virtual void Draw();\n\n void ToggleDrawBdr()\n { drawbdr = !drawbdr; }\n\n virtual void ToggleDrawElems();\n\n void ToggleDrawMesh() { drawmesh = (drawmesh+1)%3; }\n\n void ToggleDrawNumberings() { drawnums = (drawnums+1)%3; }\n \n virtual void SetShading(int, bool);\n void ToggleShading();\n\n void ToggleDrawCP() { draw_cp = !draw_cp; PrepareCP(); }\n\n virtual void SetRefineFactors(int, int);\n virtual void AutoRefine();\n virtual void ToggleAttributes(Array<int> &attr_list);\n};\n\nvoid DrawNumberMarker(const double x[3], double dx, int n);\n \nvoid DrawTriangle(const double pts[][3], const double cv[],\n const double minv, const double maxv);\n\nvoid DrawQuad(const double pts[][3], const double cv[],\n const double minv, const double maxv);\n\nvoid DrawPatch(const DenseMatrix &pts, Vector &vals, DenseMatrix &normals,\n const int n, const Array<int> &ind, const double minv,\n const double maxv, const int normals_opt = 0);\n\n#endif\n<commit_msg>fix prototype<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the GLVis visualization tool and library. For more\n\/\/ information and source code availability see http:\/\/glvis.org.\n\/\/\n\/\/ GLVis is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef GLVIS_VSSOLUTION\n#define GLVIS_VSSOLUTION\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n\/\/ Rendering large numbers of text objects for element or vertex\n\/\/ numberings is slow. Turn it off above some entity count.\n#define MAX_RENDER_NUMBERING 1000\n\n\/\/ Visualization header file\n\nclass VisualizationSceneSolution : public VisualizationSceneScalarData\n{\nprotected:\n Vector *v_normals;\n GridFunction *rsol;\n\n int drawmesh, drawelems, drawnums;\n int displlist, linelist, lcurvelist;\n int bdrlist, drawbdr, draw_cp, cp_list;\n int e_nums_list, v_nums_list;\n \n void Init();\n\n void FindNewBox(double rx[], double ry[], double rval[]);\n\n void DrawCPLine(DenseMatrix &pointmat, Vector &values, Array<int> &ind);\n\n void GetRefinedDetJ(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr);\n\n \/\/ redefined for vector solution\n virtual void GetRefinedValues(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr);\n virtual int GetRefinedValuesAndNormals(int i, const IntegrationRule &ir,\n Vector &vals, DenseMatrix &tr,\n DenseMatrix &normals);\n\n void DrawLevelCurves(Array<int> &RG, DenseMatrix &pointmat,\n Vector &values, int sides, Array<double> &lvl,\n int flat = 0);\n\n int GetAutoRefineFactor();\n\n \/\/ Used for drawing markers for element and vertex numberings\n double GetElementLengthScale(int k);\n\npublic:\n int shading, TimesToRefine, EdgeRefineFactor;\n\n int attr_to_show, bdr_attr_to_show;\n Array<int> el_attr_to_show, bdr_el_attr_to_show;\n\n VisualizationSceneSolution();\n VisualizationSceneSolution(Mesh &m, Vector &s, Vector *normals = NULL);\n\n virtual ~VisualizationSceneSolution();\n\n void SetGridFunction(GridFunction & u) { rsol = &u; }\n\n void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,\n GridFunction *new_u = NULL);\n\n virtual void SetNewScalingFromBox();\n virtual void FindNewBox(bool prepare);\n virtual void FindNewValueRange(bool prepare);\n virtual void FindNewBoxAndValueRange(bool prepare)\n { FindNewBox(prepare); }\n virtual void FindMeshBox(bool prepare);\n\n virtual void ToggleLogscale(bool print);\n virtual void UpdateLevelLines() { PrepareLevelCurves(); }\n virtual void UpdateValueRange(bool prepare);\n\n void PrepareWithNormals();\n void PrepareFlat();\n void PrepareFlat2();\n\n virtual void PrepareLines();\n void PrepareLines2();\n void PrepareLines3();\n\n virtual void Prepare();\n void PrepareLevelCurves();\n void PrepareLevelCurves2();\n\n void PrepareBoundary();\n\n void PrepareNumbering();\n void PrepareElementNumbering();\n void PrepareElementNumbering1();\n void PrepareElementNumbering2();\n void PrepareVertexNumbering();\n void PrepareVertexNumbering1();\n void PrepareVertexNumbering2();\n\n void PrepareCP();\n\n virtual void Draw();\n\n void ToggleDrawBdr()\n { drawbdr = !drawbdr; }\n\n virtual void ToggleDrawElems();\n\n void ToggleDrawMesh() { drawmesh = (drawmesh+1)%3; }\n\n void ToggleDrawNumberings() { drawnums = (drawnums+1)%3; }\n \n virtual void SetShading(int, bool);\n void ToggleShading();\n\n void ToggleDrawCP() { draw_cp = !draw_cp; PrepareCP(); }\n\n virtual void SetRefineFactors(int, int);\n virtual void AutoRefine();\n virtual void ToggleAttributes(Array<int> &attr_list);\n};\n\nvoid DrawNumberedMarker(const double x[3], double dx, int n);\n\nvoid DrawTriangle(const double pts[][3], const double cv[],\n const double minv, const double maxv);\n\nvoid DrawQuad(const double pts[][3], const double cv[],\n const double minv, const double maxv);\n\nvoid DrawPatch(const DenseMatrix &pts, Vector &vals, DenseMatrix &normals,\n const int n, const Array<int> &ind, const double minv,\n const double maxv, const int normals_opt = 0);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2017 nariakiiwatani\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"IPAddress.h\"\n#include \"ofConstants.h\"\n\n#if defined(TARGET_OSX) || defined(TARGET_OF_IOS) || defined(TARGET_LINUX)\n#include <ifaddrs.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <net\/if.h>\n\nusing namespace std;\n\nstd::vector<IPAddress::IPv4> IPAddress::getv4()\n{\n\tstruct ifaddrs *ifas, *ifa;\n\tif(getifaddrs(&ifas) != 0) {\n\t\treturn {};\n\t}\n\tvector<IPv4> ret;\n\tfor(ifa = ifas; ifa != nullptr; ifa=ifa->ifa_next) {\n\t\tif (ifa->ifa_addr->sa_family == AF_INET) {\n\t\t\tIPv4 result;\n\t\t\tresult.name = ifa->ifa_name;\n\t\t\tauto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {\n\t\t\t\tchar str[INET_ADDRSTRLEN] = {};\n\t\t\t\tdst_raw = ifa_addr->sin_addr.s_addr;\n\t\t\t\tinet_ntop(AF_INET, &dst_raw, str, sizeof(str));\n\t\t\t\tdst_str = str;\n\t\t\t};\n\t\t\tget_address((struct sockaddr_in *)ifa->ifa_addr, result.ip_raw, result.ip);\n\t\t\tget_address((struct sockaddr_in *)ifa->ifa_netmask, result.netmask_raw, result.netmask);\n\t\t\tif((ifa->ifa_flags & IFF_BROADCAST) != 0) {\n\t\t\t\tget_address((struct sockaddr_in *)ifa->ifa_dstaddr, result.broadcast_raw, result.broadcast);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresult.broadcast_raw = 0;\n\t\t\t\tresult.broadcast = \"\";\n\t\t\t}\n\t\t\tret.push_back(result);\n\t\t}\n\t}\n\tfreeifaddrs(ifas);\n\treturn ret;\n}\n\nbool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const\n{\n\treturn (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);\n}\n\n#else\nstd::vector<IPAddress::IPv4> IPAddress::getv4() { return {}; }\nbool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const { return false; }\n#endif\n<commit_msg>Get local IP addresses automatically on WIN32<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2017 nariakiiwatani\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"IPAddress.h\"\n#include \"ofConstants.h\"\n\n#if defined(TARGET_OSX) || defined(TARGET_OF_IOS) || defined(TARGET_LINUX)\n#include <ifaddrs.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <net\/if.h>\n\nusing namespace std;\n\nstd::vector<IPAddress::IPv4> IPAddress::getv4()\n{\n\tstruct ifaddrs *ifas, *ifa;\n\tif(getifaddrs(&ifas) != 0) {\n\t\treturn {};\n\t}\n\tvector<IPv4> ret;\n\tfor(ifa = ifas; ifa != nullptr; ifa=ifa->ifa_next) {\n\t\tif (ifa->ifa_addr->sa_family == AF_INET) {\n\t\t\tIPv4 result;\n\t\t\tresult.name = ifa->ifa_name;\n\t\t\tauto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {\n\t\t\t\tchar str[INET_ADDRSTRLEN] = {};\n\t\t\t\tdst_raw = ifa_addr->sin_addr.s_addr;\n\t\t\t\tinet_ntop(AF_INET, &dst_raw, str, sizeof(str));\n\t\t\t\tdst_str = str;\n\t\t\t};\n\t\t\tget_address((struct sockaddr_in *)ifa->ifa_addr, result.ip_raw, result.ip);\n\t\t\tget_address((struct sockaddr_in *)ifa->ifa_netmask, result.netmask_raw, result.netmask);\n\t\t\tif((ifa->ifa_flags & IFF_BROADCAST) != 0) {\n\t\t\t\tget_address((struct sockaddr_in *)ifa->ifa_dstaddr, result.broadcast_raw, result.broadcast);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresult.broadcast_raw = 0;\n\t\t\t\tresult.broadcast = \"\";\n\t\t\t}\n\t\t\tret.push_back(result);\n\t\t}\n\t}\n\tfreeifaddrs(ifas);\n\treturn ret;\n}\n\nbool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const\n{\n\treturn (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);\n}\n\n#elif defined(TARGET_WIN32)\n#include <ws2tcpip.h>\nstd::vector<IPAddress::IPv4> IPAddress::getv4()\n{\n\tWSADATA ws_data;\n\tif(WSAStartup(WINSOCK_VERSION, &ws_data) != 0) {\n\t\treturn {};\n\t}\n\n\tSOCKET socket = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);\n\tif(socket == SOCKET_ERROR) {\n\t\treturn {};\n\t}\n\n\tINTERFACE_INFO if_info[32];\n\tunsigned long num_bytes;\n\tif(WSAIoctl(socket, SIO_GET_INTERFACE_LIST, 0, 0, &if_info, sizeof(if_info), &num_bytes, 0, 0) == SOCKET_ERROR) {\n\t\treturn {};\n\t}\n\n\tvector<IPv4> ret;\n\tint num_if = num_bytes\/sizeof(INTERFACE_INFO);\n\tfor(int i = 0, num = num_bytes\/sizeof(INTERFACE_INFO); i < num; ++i) {\n\t\tINTERFACE_INFO info = if_info[i];\n\t\tu_long flags = info.iiFlags;\n\n\t\tIPv4 result;\n\t\tchar name[256];\n\t\tif(getnameinfo(&info.iiAddress.Address, sizeof(info.iiAddress.Address), name, sizeof(name), NULL, 0, NI_DGRAM) != 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.name = name;\n\t\tauto get_address = [](sockaddr_in *ifa_addr, unsigned int &dst_raw, string &dst_str) {\n\t\t\tchar str[INET_ADDRSTRLEN] = {};\n\t\t\tdst_raw = ifa_addr->sin_addr.s_addr;\n\t\t\tinet_ntop(AF_INET, &dst_raw, str, sizeof(str));\n\t\t\tdst_str = str;\n\t\t};\n\t\tget_address(&info.iiAddress.AddressIn, result.ip_raw, result.ip);\n\t\tget_address(&info.iiNetmask.AddressIn, result.netmask_raw, result.netmask);\n\t\tif((flags & IFF_BROADCAST) != 0) {\n\t\t\tget_address(&info.iiBroadcastAddress.AddressIn, result.broadcast_raw, result.broadcast);\n\t\t}\n\t\telse {\n\t\t\tresult.broadcast_raw = 0;\n\t\t\tresult.broadcast = \"\";\n\t\t}\n\t\tret.push_back(result);\n\t}\n\tWSACleanup();\n\treturn ret;\n}\nbool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const\n{\n\treturn (ip_raw&netmask_raw) == (inet_addr(hint.c_str())&netmask_raw);\n}\n#else\nstd::vector<IPAddress::IPv4> IPAddress::getv4() { return {}; }\nbool IPAddress::IPv4::isInSameNetwork(const std::string &hint) const { return false; }\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\n*\n* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without l> imitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n************************************************************************\/\n\n#include <cstdio>\n#include \"mazeprinter.h\"\n\n\nstatic char dirChars[] = \"^>v< \";\n\nvoid printNorthWalls(Maze *maze, uint16_t row) {\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n printf(\"o\");\n if (maze->hasExit(cell, NORTH)) {\n printf(\" \");\n } else {\n printf(\"---\");\n }\n }\n printf(\"o\\n\");\n}\n\nvoid printSouthWalls(Maze *maze, uint16_t row) {\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n printf(\"o\");\n if (maze->hasExit(cell, SOUTH)) {\n printf(\" \");\n } else {\n printf(\"---\");\n }\n }\n printf(\"o\\n\");\n}\n\nvoid MazePrinter::printDirs(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint8_t direction = maze->direction(cell);\n char c = ' ';\n if (direction <= WEST) {\n c = dirChars[direction];\n }\n if (cell == maze->goal()) {\n c = '*';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\nvoid MazePrinter::printVisitedDirs(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint8_t direction = maze->direction(cell);\n char c = ' ';\n if (maze->isVisited(cell) && direction <= WEST) {\n c = dirChars[direction];\n }\n if (cell == maze->goal()) {\n c = '*';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\nvoid MazePrinter::printPlain(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n \/* TODO: this is all rather messy *\/\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n char c = ' ';\n if (cell == maze->goal()) {\n c = '*';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n printf(\"\\n\");\n}\n\nvoid MazePrinter::printCDecl(Maze *maze, const char *name) {\n printf(\"\\n\\nconst uint8_t %s[] = {\\n\", name);\n for (uint16_t x = 0; x < maze->width(); x++) {\n printf(\" \");\n for (uint16_t y = 0; y < maze->width(); y++) {\n uint16_t cell = x * maze->width() + y;\n printf(\"0x%02X, \", maze->walls(cell));\n }\n printf(\"\\n\");\n }\n printf(\" };\\n\\n\");\n}\n\nvoid MazePrinter::printRawDecl(Maze *maze, const char *name) {\n printf(\"\\n\\nconst uint8_t %s[] = {\\n\", name);\n for (uint16_t x = 0; x < maze->width(); x++) {\n printf(\" \");\n for (uint16_t y = 0; y < maze->width(); y++) {\n uint16_t cell = x * maze->width() + y;\n printf(\"0x%02X, \", maze->walls(cell));\n }\n printf(\"\\n\");\n }\n printf(\" };\\n\\n\");\n}\n\nvoid MazePrinter::printCosts(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n \/* TODO: this is all rather messy *\/\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint16_t cost = maze->cost(cell);\n if (cost < MAX_COST) {\n printf(\"%3d\", cost);\n } else {\n printf(\" - \");\n }\n\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\n<commit_msg>MazePrinter plain should print 'G' in goal cells and 'S' at start<commit_after>\/************************************************************************\n*\n* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without l> imitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n************************************************************************\/\n\n#include <cstdio>\n#include \"mazeprinter.h\"\n\n\nstatic char dirChars[] = \"^>v< \";\n\nvoid printNorthWalls(Maze *maze, uint16_t row) {\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n printf(\"o\");\n if (maze->hasExit(cell, NORTH)) {\n printf(\" \");\n } else {\n printf(\"---\");\n }\n }\n printf(\"o\\n\");\n}\n\nvoid printSouthWalls(Maze *maze, uint16_t row) {\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n printf(\"o\");\n if (maze->hasExit(cell, SOUTH)) {\n printf(\" \");\n } else {\n printf(\"---\");\n }\n }\n printf(\"o\\n\");\n}\n\nvoid MazePrinter::printDirs(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint8_t direction = maze->direction(cell);\n char c = ' ';\n if (direction <= WEST) {\n c = dirChars[direction];\n }\n if (cell == maze->goal()) {\n c = '*';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\nvoid MazePrinter::printVisitedDirs(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint8_t direction = maze->direction(cell);\n char c = ' ';\n if (maze->isVisited(cell) && direction <= WEST) {\n c = dirChars[direction];\n }\n if (cell == maze->goal()) {\n c = '*';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\nvoid MazePrinter::printPlain(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n \/* TODO: this is all rather messy *\/\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n char c = ' ';\n if (cell == maze->goal()) {\n c = 'G';\n }\n if (cell == 0) {\n c = 'S';\n }\n printf(\" %c \", c);\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n printf(\"\\n\");\n}\n\nvoid MazePrinter::printCDecl(Maze *maze, const char *name) {\n printf(\"\\n\\nconst uint8_t %s[] = {\\n\", name);\n for (uint16_t x = 0; x < maze->width(); x++) {\n printf(\" \");\n for (uint16_t y = 0; y < maze->width(); y++) {\n uint16_t cell = x * maze->width() + y;\n printf(\"0x%02X, \", maze->walls(cell));\n }\n printf(\"\\n\");\n }\n printf(\" };\\n\\n\");\n}\n\nvoid MazePrinter::printRawDecl(Maze *maze, const char *name) {\n printf(\"\\n\\nconst uint8_t %s[] = {\\n\", name);\n for (uint16_t x = 0; x < maze->width(); x++) {\n printf(\" \");\n for (uint16_t y = 0; y < maze->width(); y++) {\n uint16_t cell = x * maze->width() + y;\n printf(\"0x%02X, \", maze->walls(cell));\n }\n printf(\"\\n\");\n }\n printf(\" };\\n\\n\");\n}\n\nvoid MazePrinter::printCosts(Maze *maze) {\n printf(\"\\n\");\n for (int row = static_cast<uint16_t>(maze->width() - 1); row >= 0; row--) {\n printNorthWalls(maze, row);\n \/* TODO: this is all rather messy *\/\n for (uint16_t col = 0; col < maze->width(); col++) {\n uint16_t cell = row + maze->width() * col;\n if (maze->hasExit(cell, WEST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n uint16_t cost = maze->cost(cell);\n if (cost < MAX_COST) {\n printf(\"%3d\", cost);\n } else {\n printf(\" - \");\n }\n\n }\n uint16_t cell = row + maze->width() * (maze->width() - 1);\n if (maze->hasExit(cell, EAST)) {\n printf(\" \");\n } else {\n printf(\"|\");\n }\n printf(\"\\n\");\n }\n printSouthWalls(maze, 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/lists.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/shared_ptr.hpp>\n\n#include \"SQLiteCpp\/SQLiteC++.h\"\n\nnamespace pkmn\n{\n pkmn::shared_ptr<SQLite::Database> db;\n\n void get_game_list(std::vector<std::string> &game_vec)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n game_vec.clear();\n\n std::string query_str = \"SELECT name FROM version_names\";\n SQLite::Statement query(*db, query_str.c_str());\n\n while(query.executeStep())\n {\n std::string game = query.getColumn(0);\n game_vec.push_back(game);\n }\n }\n\n void get_game_group_list(std::vector<std::string> &game_group_vec)\n {\n \/\/Must be done manually, only really used for GamesComboBox\n game_group_vec.clear();\n\n game_group_vec.push_back(\"Red\/Blue\/Green\");\n game_group_vec.push_back(\"Yellow\");\n game_group_vec.push_back(\"Gold\/Silver\");\n game_group_vec.push_back(\"Crystal\");\n game_group_vec.push_back(\"Ruby\/Sapphire\/Emerald\");\n game_group_vec.push_back(\"Fire Red\/Leaf Green\");\n game_group_vec.push_back(\"Diamond\/Pearl\");\n game_group_vec.push_back(\"Platinum\");\n game_group_vec.push_back(\"Heart Gold\/Soul Silver\");\n game_group_vec.push_back(\"Black\/White\");\n game_group_vec.push_back(\"Black 2\/White 2\");\n }\n\n void get_item_list(std::vector<std::string> &item_vec, unsigned int game)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n item_vec.clear();\n std::vector<std::string> temp_vec;\n\n unsigned int gen = database::get_generation(game);\n std::ostringstream query_stream;\n query_stream << \"SELECT name FROM item_names WHERE local_language_id=9 AND item_id IN \"\n << \"(SELECT item_id FROM item_game_indices WHERE generation_id=\" << gen;\n\n \/*\n * The database only shows which generation items come from, but it doesn't take\n * into account differences between games within a generation.\n *\/\n switch(gen)\n {\n case 1:\n {\n query_stream << \")\";\n break;\n }\n\n case 2:\n {\n std::string end = (game == Versions::CRYSTAL) ? \")\"\n : \" AND game_index NOT IN (70,115,116,129))\";\n query_stream << end;\n break;\n }\n\n case 3:\n {\n std::string end;\n switch(game)\n {\n case Versions::EMERALD:\n end = \")\";\n break;\n\n case Versions::FIRERED:\n case Versions::LEAFGREEN:\n end = \" AND game_index<=374)\";\n break;\n\n default:\n end = \" AND game_index<=348)\";\n break;\n }\n query_stream << end;\n break;\n }\n\n case 4:\n {\n std::string end;\n switch(game)\n {\n case Versions::HEARTGOLD:\n case Versions::SOULSILVER:\n end = \")\";\n break;\n\n case Versions::PLATINUM:\n end = \" AND game_index<=467)\";\n break;\n\n default:\n end = \" AND game_index<=464 AND game_index!=112)\";\n break;\n }\n query_stream << end;\n break;\n }\n\n case 5:\n {\n std::string end = (game < Versions::BLACK_2) ? \" AND game_index<=626)\"\n : \")\";\n query_stream << end;\n break;\n }\n\n default:\n query_stream << \")\";\n break;\n }\n SQLite::Statement query(*db, query_stream.str().c_str());\n while(query.executeStep()) item_vec.push_back((const char*)(query.getColumn(0)));\n }\n\n void get_pokedex_order(std::vector<std::pair<unsigned int, unsigned int> > &entry_list, unsigned int pokedex_id)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n entry_list.clear();\n std::string query_string(str(boost::format(\"SELECT species_id,pokedex_number FROM pokemon_dex_numbers WHERE pokedex_id=%d\")\n % pokedex_id));\n SQLite::Statement query(*db, query_string.c_str());\n\n while(query.executeStep()) entry_list.push_back(std::make_pair(int(query.getColumn(0)), int(query.getColumn(1))));\n }\n\n void get_pokemon_list(std::vector<std::string> &pokemon_vec, unsigned int game)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n pokemon_vec.clear();\n\n unsigned int bounds[] = {0,151,251,386,493,649,719};\n unsigned int bound = bounds[database::get_generation(game)];\n std::ostringstream query_stream;\n query_stream << \"SELECT name FROM pokemon_species_names WHERE local_language_id=9 AND pokemon_species_id<=\" << bound << std::endl;\n SQLite::Statement query(*db, query_stream.str().c_str());\n\n while(query.executeStep()) pokemon_vec.push_back((const char*)(query.getColumn(0)));\n }\n\n void get_type_list(std::vector<std::string> &type_vec, unsigned int gen)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n type_vec.clear();\n\n std::string query_string = \"SELECT name FROM type_names WHERE local_language_id=9\";\n\n SQLite::Statement type_names_query(*db, query_string.c_str());\n while(type_names_query.executeStep())\n {\n std::string type = std::string((const char*)type_names_query.getColumn(0));\n if(not (gen == 1 and (type == \"Steel\" or type == \"Dark\")) and type != \"???\" and type != \"Shadow\")\n {\n type_vec.push_back(type);\n }\n }\n }\n\n void get_ability_list(std::vector<std::string> &ability_vec, unsigned int gen)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n ability_vec.clear();\n\n std::string query_string = \"SELECT name FROM ability_names WHERE local_language_id=9\";\n SQLite::Statement query(*db, query_string.c_str());\n while(query.executeStep()) ability_vec.push_back((const char*)(db->execAndGet(query_string.c_str())));\n }\n\n void get_nature_list(std::vector<std::string> &nature_vec)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n nature_vec.clear();\n\n std::string query_str = \"SELECT name FROM nature_names\";\n SQLite::Statement query(*db, query_str.c_str());\n\n while(query.executeStep())\n {\n std::string nature = std::string((const char*)query.getColumn(0));\n nature_vec.push_back(nature);\n }\n }\n\n void get_pokemon_of_type(base_pokemon_vector &pkmn_vector, std::string type1, std::string type2, unsigned int gen, bool lax)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n pkmn_vector.clear();\n\n std::string query_string;\n std::vector<int> applicable_ids;\n int pkmn_id, type1_id, type2_id;\n\n \/\/Get type IDs\n query_string = \"SELECT type_id FROM type_names WHERE name='\" + type1 + \"'\";\n type1_id = int(db->execAndGet(query_string.c_str()));\n if(type2 != \"None\" and type2 != \"Any\")\n {\n query_string = \"SELECT type_id FROM type_names WHERE name='\" + type2 + \"'\";\n type2_id = int(db->execAndGet(query_string.c_str()));\n }\n\n if((type2 == \"None\" or type2 == \"Any\") and lax)\n {\n \/\/Get IDs of Pokémon\n query_string = \"SELECT pokemon_id FROM pokemon_types WHERE type_id=\" + to_string(type1_id);\n SQLite::Statement pokemon_types_query(*db, query_string.c_str());\n\n \/\/Get any Pokémon of specified type (by itself or paired with any other)\n while(pokemon_types_query.executeStep())\n {\n pkmn_id = pokemon_types_query.getColumn(0); \/\/pokemon_id\n\n query_string = \"SELECT species_id FROM pokemon WHERE id=\" + to_string(pkmn_id);\n int species_id = db->execAndGet(query_string.c_str());\n\n \/\/Get generation ID to restrict list\n query_string = \"SELECT generation_id FROM pokemon_species WHERE id=\" + to_string(species_id);\n int generation_id = db->execAndGet(query_string.c_str());\n if(generation_id <= gen)\n {\n applicable_ids.push_back(pkmn_id);\n }\n }\n }\n else\n {\n\n \/\/Get IDs of Pokémon matching first type\n std::vector<int> pkmn_ids;\n query_string = \"SELECT pokemon_id FROM pokemon_types WHERE type_id=\" + to_string(type1_id);\n SQLite::Statement pokemon_types_id_query(*db, query_string.c_str());\n\n while(pokemon_types_id_query.executeStep()) pkmn_ids.push_back(pokemon_types_id_query.getColumn(0));\n\n std::vector<int> to_erase;\n if(type2 == \"None\")\n {\n \/\/If only one type is specified, find number of entries with that ID and remove duplicates\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n int pkmn_count = 0; \/\/Number of types Pokémon appears in pokemon_moves\n query_string = \"SELECT type_id FROM pokemon_types WHERE pokemon_id=\" + to_string(pkmn_ids[i]);\n SQLite::Statement inner_query(*db, query_string.c_str());\n while(inner_query.executeStep()) pkmn_count++;\n\n if(pkmn_count > 1) to_erase.push_back(i);\n }\n }\n else\n {\n \/\/See if entry exists for other type, add to to_erase if not\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n query_string = \"SELECT type_id FROM pokemon_types WHERE pokemon_id=\" + to_string(pkmn_ids[i])\n + \" AND type_id=\" + to_string(type2_id);\n SQLite::Statement inner_query(*db, query_string.c_str());\n if(not inner_query.executeStep()) to_erase.push_back(i);\n }\n }\n\n \/\/Erase invalid entries\n for(unsigned int i = to_erase.size()-1; i > 0; i--) pkmn_ids.erase(pkmn_ids.begin() + to_erase[i]);\n pkmn_ids.erase(pkmn_ids.begin() + to_erase[0]);\n\n \/\/Get identifiers for remaining entries\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n query_string = \"SELECT species_id FROM pokemon WHERE id=\" + to_string(pkmn_ids[i]);\n int species_id = db->execAndGet(query_string.c_str());\n\n query_string = \"SELECT identifier FROM pokemon_species WHERE id=\" + to_string(species_id);\n std::string pkmn_name = db->execAndGet(query_string.c_str());\n\n \/\/Get generation ID to restrict list\n query_string = \"SELECT generation_id FROM pokemon_species WHERE id=\" + to_string(species_id);\n int generation_id = db->execAndGet(query_string.c_str());\n if(generation_id <= gen) applicable_ids.push_back(pkmn_ids[i]); \/\/ID's that apply to final Pokemon\n }\n }\n\n \/\/base_pokemon now takes a game ID in its constructor instead of a generation, but this\n \/\/function doesn't discriminate between games in the same generation, so this array\n \/\/guarantees that the given generation will use a game in that generation\n int game_id_from_gen[] = {0,1,4,7,13,17};\n\n for(unsigned int i = 0; i < applicable_ids.size(); i++)\n {\n \/\/Manually correct for Magnemite and Magneton in Gen 1\n int final_species_id = database::get_species_id(applicable_ids[i]);\n if(not ((database::get_species_name(final_species_id) == \"Magnemite\" or\n database::get_species_name(final_species_id) == \"Magneton\") and gen == 1))\n {\n base_pokemon::sptr b_pkmn = base_pokemon::make(database::get_species_id(applicable_ids[i]), game_id_from_gen[gen]);\n pkmn_vector.push_back(b_pkmn);\n }\n }\n }\n} \/* namespace pkmn *\/\n<commit_msg>Python stuff works, exposed lists.cpp issue<commit_after>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/lists.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/shared_ptr.hpp>\n\n#include \"SQLiteCpp\/SQLiteC++.h\"\n\nnamespace pkmn\n{\n pkmn::shared_ptr<SQLite::Database> db;\n\n void get_game_list(std::vector<std::string> &game_vec)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n game_vec.clear();\n\n std::string query_str = \"SELECT name FROM version_names\";\n SQLite::Statement query(*db, query_str.c_str());\n\n while(query.executeStep())\n {\n std::string game = query.getColumn(0);\n game_vec.push_back(game);\n }\n }\n\n void get_game_group_list(std::vector<std::string> &game_group_vec)\n {\n \/\/Must be done manually, only really used for GamesComboBox\n game_group_vec.clear();\n\n game_group_vec.push_back(\"Red\/Blue\/Green\");\n game_group_vec.push_back(\"Yellow\");\n game_group_vec.push_back(\"Gold\/Silver\");\n game_group_vec.push_back(\"Crystal\");\n game_group_vec.push_back(\"Ruby\/Sapphire\/Emerald\");\n game_group_vec.push_back(\"Fire Red\/Leaf Green\");\n game_group_vec.push_back(\"Diamond\/Pearl\");\n game_group_vec.push_back(\"Platinum\");\n game_group_vec.push_back(\"Heart Gold\/Soul Silver\");\n game_group_vec.push_back(\"Black\/White\");\n game_group_vec.push_back(\"Black 2\/White 2\");\n }\n\n void get_item_list(std::vector<std::string> &item_vec, unsigned int game)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n item_vec.clear();\n std::vector<std::string> temp_vec;\n\n unsigned int gen = database::get_generation(game);\n std::ostringstream query_stream;\n query_stream << \"SELECT name FROM item_names WHERE local_language_id=9 AND item_id IN \"\n << \"(SELECT item_id FROM item_game_indices WHERE generation_id=\" << gen;\n\n \/*\n * The database only shows which generation items come from, but it doesn't take\n * into account differences between games within a generation.\n *\/\n switch(gen)\n {\n case 1:\n {\n query_stream << \")\";\n break;\n }\n\n case 2:\n {\n std::string end = (game == Versions::CRYSTAL) ? \")\"\n : \" AND game_index NOT IN (70,115,116,129))\";\n query_stream << end;\n break;\n }\n\n case 3:\n {\n std::string end;\n switch(game)\n {\n case Versions::EMERALD:\n end = \")\";\n break;\n\n case Versions::FIRERED:\n case Versions::LEAFGREEN:\n end = \" AND game_index<=374)\";\n break;\n\n default:\n end = \" AND game_index<=348)\";\n break;\n }\n query_stream << end;\n break;\n }\n\n case 4:\n {\n std::string end;\n switch(game)\n {\n case Versions::HEARTGOLD:\n case Versions::SOULSILVER:\n end = \")\";\n break;\n\n case Versions::PLATINUM:\n end = \" AND game_index<=467)\";\n break;\n\n default:\n end = \" AND game_index<=464 AND game_index!=112)\";\n break;\n }\n query_stream << end;\n break;\n }\n\n case 5:\n {\n std::string end = (game < Versions::BLACK_2) ? \" AND game_index<=626)\"\n : \")\";\n query_stream << end;\n break;\n }\n\n default:\n query_stream << \")\";\n break;\n }\n SQLite::Statement query(*db, query_stream.str().c_str());\n while(query.executeStep()) item_vec.push_back((const char*)(query.getColumn(0)));\n }\n\n void get_pokedex_order(std::vector<std::pair<unsigned int, unsigned int> > &entry_list, unsigned int pokedex_id)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n entry_list.clear();\n std::string query_string(str(boost::format(\"SELECT species_id,pokedex_number FROM pokemon_dex_numbers WHERE pokedex_id=%d\")\n % pokedex_id));\n SQLite::Statement query(*db, query_string.c_str());\n\n while(query.executeStep()) entry_list.push_back(std::make_pair(int(query.getColumn(0)), int(query.getColumn(1))));\n }\n\n void get_pokemon_list(std::vector<std::string> &pokemon_vec, unsigned int game)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n pokemon_vec.clear();\n\n unsigned int bounds[] = {0,151,251,386,493,649,719};\n unsigned int bound = bounds[database::get_generation(game)];\n std::ostringstream query_stream;\n query_stream << \"SELECT name FROM pokemon_species_names WHERE local_language_id=9 AND pokemon_species_id<=\" << bound << std::endl;\n SQLite::Statement query(*db, query_stream.str().c_str());\n\n while(query.executeStep()) pokemon_vec.push_back((const char*)(query.getColumn(0)));\n }\n\n void get_type_list(std::vector<std::string> &type_vec, unsigned int gen)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n type_vec.clear();\n\n std::string query_string = \"SELECT name FROM type_names WHERE local_language_id=9\";\n\n SQLite::Statement type_names_query(*db, query_string.c_str());\n while(type_names_query.executeStep())\n {\n std::string type = std::string((const char*)type_names_query.getColumn(0));\n if(not (gen == 1 and (type == \"Steel\" or type == \"Dark\")) and type != \"???\" and type != \"Shadow\")\n {\n type_vec.push_back(type);\n }\n }\n }\n\n void get_ability_list(std::vector<std::string> &ability_vec, unsigned int gen)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n ability_vec.clear();\n\n std::string query_string = \"SELECT name FROM ability_names WHERE local_language_id=9\";\n SQLite::Statement query(*db, query_string.c_str());\n while(query.executeStep()) ability_vec.push_back((const char*)(query.getColumn(0)));\n }\n\n void get_nature_list(std::vector<std::string> &nature_vec)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n nature_vec.clear();\n\n std::string query_str = \"SELECT name FROM nature_names\";\n SQLite::Statement query(*db, query_str.c_str());\n\n while(query.executeStep())\n {\n std::string nature = std::string((const char*)query.getColumn(0));\n nature_vec.push_back(nature);\n }\n }\n\n void get_pokemon_of_type(base_pokemon_vector &pkmn_vector, std::string type1, std::string type2, unsigned int gen, bool lax)\n {\n if(!db) db = pkmn::shared_ptr<SQLite::Database>(new SQLite::Database(get_database_path().c_str()));\n pkmn_vector.clear();\n\n std::string query_string;\n std::vector<int> applicable_ids;\n int pkmn_id, type1_id, type2_id;\n\n \/\/Get type IDs\n query_string = \"SELECT type_id FROM type_names WHERE name='\" + type1 + \"'\";\n type1_id = int(db->execAndGet(query_string.c_str()));\n if(type2 != \"None\" and type2 != \"Any\")\n {\n query_string = \"SELECT type_id FROM type_names WHERE name='\" + type2 + \"'\";\n type2_id = int(db->execAndGet(query_string.c_str()));\n }\n\n if((type2 == \"None\" or type2 == \"Any\") and lax)\n {\n \/\/Get IDs of Pokémon\n query_string = \"SELECT pokemon_id FROM pokemon_types WHERE type_id=\" + to_string(type1_id);\n SQLite::Statement pokemon_types_query(*db, query_string.c_str());\n\n \/\/Get any Pokémon of specified type (by itself or paired with any other)\n while(pokemon_types_query.executeStep())\n {\n pkmn_id = pokemon_types_query.getColumn(0); \/\/pokemon_id\n\n query_string = \"SELECT species_id FROM pokemon WHERE id=\" + to_string(pkmn_id);\n int species_id = db->execAndGet(query_string.c_str());\n\n \/\/Get generation ID to restrict list\n query_string = \"SELECT generation_id FROM pokemon_species WHERE id=\" + to_string(species_id);\n int generation_id = db->execAndGet(query_string.c_str());\n if(generation_id <= gen)\n {\n applicable_ids.push_back(pkmn_id);\n }\n }\n }\n else\n {\n\n \/\/Get IDs of Pokémon matching first type\n std::vector<int> pkmn_ids;\n query_string = \"SELECT pokemon_id FROM pokemon_types WHERE type_id=\" + to_string(type1_id);\n SQLite::Statement pokemon_types_id_query(*db, query_string.c_str());\n\n while(pokemon_types_id_query.executeStep()) pkmn_ids.push_back(pokemon_types_id_query.getColumn(0));\n\n std::vector<int> to_erase;\n if(type2 == \"None\")\n {\n \/\/If only one type is specified, find number of entries with that ID and remove duplicates\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n int pkmn_count = 0; \/\/Number of types Pokémon appears in pokemon_moves\n query_string = \"SELECT type_id FROM pokemon_types WHERE pokemon_id=\" + to_string(pkmn_ids[i]);\n SQLite::Statement inner_query(*db, query_string.c_str());\n while(inner_query.executeStep()) pkmn_count++;\n\n if(pkmn_count > 1) to_erase.push_back(i);\n }\n }\n else\n {\n \/\/See if entry exists for other type, add to to_erase if not\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n query_string = \"SELECT type_id FROM pokemon_types WHERE pokemon_id=\" + to_string(pkmn_ids[i])\n + \" AND type_id=\" + to_string(type2_id);\n SQLite::Statement inner_query(*db, query_string.c_str());\n if(not inner_query.executeStep()) to_erase.push_back(i);\n }\n }\n\n \/\/Erase invalid entries\n for(unsigned int i = to_erase.size()-1; i > 0; i--) pkmn_ids.erase(pkmn_ids.begin() + to_erase[i]);\n pkmn_ids.erase(pkmn_ids.begin() + to_erase[0]);\n\n \/\/Get identifiers for remaining entries\n for(unsigned int i = 0; i < pkmn_ids.size(); i++)\n {\n query_string = \"SELECT species_id FROM pokemon WHERE id=\" + to_string(pkmn_ids[i]);\n int species_id = db->execAndGet(query_string.c_str());\n\n query_string = \"SELECT identifier FROM pokemon_species WHERE id=\" + to_string(species_id);\n std::string pkmn_name = db->execAndGet(query_string.c_str());\n\n \/\/Get generation ID to restrict list\n query_string = \"SELECT generation_id FROM pokemon_species WHERE id=\" + to_string(species_id);\n int generation_id = db->execAndGet(query_string.c_str());\n if(generation_id <= gen) applicable_ids.push_back(pkmn_ids[i]); \/\/ID's that apply to final Pokemon\n }\n }\n\n \/\/base_pokemon now takes a game ID in its constructor instead of a generation, but this\n \/\/function doesn't discriminate between games in the same generation, so this array\n \/\/guarantees that the given generation will use a game in that generation\n int game_id_from_gen[] = {0,1,4,7,13,17};\n\n for(unsigned int i = 0; i < applicable_ids.size(); i++)\n {\n \/\/Manually correct for Magnemite and Magneton in Gen 1\n int final_species_id = database::get_species_id(applicable_ids[i]);\n if(not ((database::get_species_name(final_species_id) == \"Magnemite\" or\n database::get_species_name(final_species_id) == \"Magneton\") and gen == 1))\n {\n base_pokemon::sptr b_pkmn = base_pokemon::make(database::get_species_id(applicable_ids[i]), game_id_from_gen[gen]);\n pkmn_vector.push_back(b_pkmn);\n }\n }\n }\n} \/* namespace pkmn *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwidget.h\"\n\nMainWidget::MainWidget(QWidget* parent)\n : QWidget(parent)\n , m_graphicWindows(&m_updateUi)\n , m_hLayout(this)\n , m_frameNumberLCD(12)\n , m_fpsLCD(12)\n , m_frameAdvanceButton(tr(\"Frame Advance\"))\n{\n this->setWindowTitle(tr(\"Blackhole Simulator 2.0 beta\"));\n\n auto container = QWidget::createWindowContainer(&m_graphicWindows);\n container->setFocusPolicy(Qt::StrongFocus);\n container->setFocus();\n container->setMinimumSize(QSize(200, 100));\n QSize screenSize = m_graphicWindows.screen()->size();\n container->setMaximumSize(screenSize);\n\n m_vLayout.setAlignment(Qt::AlignTop);\n m_hLayout.addWidget(container, Qt::AlignLeft);\n m_hLayout.addLayout(&m_vLayout);\n\n initUi();\n}\n\nvoid MainWidget::initUi()\n{\n \/\/ FPS\n auto fpsLayout = new QHBoxLayout;\n auto fpsLabel = new QLabel(tr(\"FPS\"));\n fpsLayout->addWidget(fpsLabel);\n displayStyle(m_fpsLCD);\n fpsLayout->addWidget(&m_fpsLCD);\n m_vLayout.addLayout(fpsLayout);\n connect(&m_updateUi, &UpdateUi::displayFps, this, &MainWidget::displayFPS);\n\n \/\/ Frames\n auto frameNumberLayout = new QHBoxLayout;\n auto frameNumberLabel = new QLabel(tr(\"Frames\"));\n frameNumberLayout->addWidget(frameNumberLabel);\n displayStyle(m_frameNumberLCD);\n frameNumberLayout->addWidget(&m_frameNumberLCD);\n m_vLayout.addLayout(frameNumberLayout);\n connect(&m_updateUi, &UpdateUi::displayFrameNumber, this, &MainWidget::displayFrameNumber);\n\n \/\/ Time\/Frame\n auto timePerFrameLayout = new QHBoxLayout;\n auto timePerFrameLabel = new QLabel(tr(\"Time\/Frame (s)\"));\n timePerFrameLayout->addWidget(timePerFrameLabel);\n displayStyle(m_timePerFrameValue);\n timePerFrameLayout->addWidget(&m_timePerFrameValue);\n m_vLayout.addLayout(timePerFrameLayout);\n connect(&m_updateUi, &UpdateUi::displayTimePerFrame, this, &MainWidget::displayTimePerFrame);\n\n \/\/ Simulation Time\n auto simTimeLayout = new QHBoxLayout;\n auto simTimeLabel = new QLabel(tr(\"Time\"));\n simTimeLayout->addWidget(simTimeLabel);\n displayStyle(m_simTimeValue);\n simTimeLayout->addWidget(&m_simTimeValue);\n m_vLayout.addLayout(simTimeLayout);\n\n \/\/ Start Button\n m_startButton.setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(&m_startButton);\n connect(&m_startButton, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::startSim);\n connect(&m_updateUi, &UpdateUi::updateStartButtonText, this, &MainWidget::updateStartButtonText);\n\n \/\/ Frame Advance\n m_frameAdvanceButton.setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(&m_frameAdvanceButton);\n connect(&m_frameAdvanceButton, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::frameAdvance);\n\n \/\/ Reset\n auto resetBtn = new QPushButton(tr(\"Reset\"));\n resetBtn->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(resetBtn);\n connect(resetBtn, &QPushButton::clicked, this, &MainWidget::resetInitial);\n\n \/\/ Circle strafing\n auto circleStrafingCB = new QCheckBox(tr(\"Circle strafing\"));\n circleStrafingCB->setFocusPolicy(Qt::NoFocus);\n circleStrafingCB->setChecked(false);\n m_vLayout.addWidget(circleStrafingCB);\n connect(circleStrafingCB, &QCheckBox::stateChanged, &m_graphicWindows, &GraphicWindow::circleStrafing);\n\n \/\/ Grid Lines\n auto gridLinesCB = new QCheckBox(tr(\"Grid Lines\"));\n gridLinesCB->setChecked(true);\n gridLinesCB->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(gridLinesCB);\n connect(gridLinesCB, &QCheckBox::stateChanged, &m_graphicWindows, &GraphicWindow::enableGridLines);\n\n \/\/ Line Type\n auto btnLineType = new QPushButton(tr(\"Line Type\"));\n btnLineType->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(btnLineType);\n connect(btnLineType, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::changeLinePosition);\n\n \/\/ Model Scale\n auto scaleLabel = new QLabel(tr(\"Model Scale (m):\"));\n m_vLayout.addWidget(scaleLabel);\n\n m_scaleValue.setAlignment(Qt::AlignRight);\n m_vLayout.addWidget(&m_scaleValue);\n connect(&m_updateUi, &UpdateUi::displayModelScale, this, &MainWidget::displayModelScale);\n connect(&m_scaleValue, &QLineEdit::textChanged, &m_graphicWindows, &GraphicWindow::setModelScale);\n\n m_scaleSlider.setFocusPolicy(Qt::NoFocus);\n m_scaleSlider.setOrientation(Qt::Horizontal);\n m_scaleSlider.setMinimum(0);\n m_scaleSlider.setMaximum(UpdateUi::SCALE_SLIDER_CENTER * 2);\n m_scaleSlider.setSliderPosition(UpdateUi::SCALE_SLIDER_CENTER);\n m_vLayout.addWidget(&m_scaleSlider);\n connect(&m_scaleSlider, &QSlider::sliderMoved, &m_graphicWindows, &GraphicWindow::setModelScaleInt);\n\n \/\/ Number of particles\n auto particleNumLabel = new QLabel(tr(\"Number of particles\"));\n m_vLayout.addWidget(particleNumLabel);\n displayStyle(m_particleNumValue);\n m_vLayout.addWidget(&m_particleNumValue);\n connect(&m_updateUi, &UpdateUi::displayNumberOfParticles, this, &MainWidget::displayNumberOfParticles);\n\n \/\/ Simulation Engine\n auto engineLabel = new QLabel(tr(\"Simulation Engine\"));\n m_vLayout.addWidget(engineLabel);\n displayStyle(m_engineValue);\n m_vLayout.addWidget(&m_engineValue);\n connect(&m_updateUi, &UpdateUi::displayEngineName, this, &MainWidget::displayEngineName);\n\n \/\/ Initial Condition Preset\n auto presetLabel = new QLabel(tr(\"Initial Conditions Preset\"));\n m_vLayout.addWidget(presetLabel);\n displayStyle(m_presetValue);\n m_vLayout.addWidget(&m_presetValue);\n connect(&m_updateUi, &UpdateUi::displayPresetName, this, &MainWidget::displayPresetName);\n\n \/\/ New\n auto newButton = new QPushButton(tr(\"New...\"));\n newButton->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(newButton);\n connect(newButton, &QPushButton::clicked, this, &MainWidget::showInitializerDialog);\n\n \/\/ Graph\n auto graphButton = new QPushButton(tr(\"Graph...\"));\n graphButton->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(graphButton);\n \/\/connect(newButton, &QPushButton::clicked, this, &MainWidget::showInitializerDialog);\n\n updateStartButtonText(false);\n}\n\nvoid MainWidget::displayFrameNumber(const int num)\n{\n m_frameNumberLCD.display(num);\n quint64 time = floor(m_simCondition.timePerFrame * (float)num);\n quint64 seconds = time % 60;\n quint64 remain = time \/ 60;\n quint64 minutes = remain % 60;\n remain \/= 60;\n quint64 hours = remain % 24;\n remain \/= 24;\n QString t = QString(tr(\"Day %1 %2:%3:%4\"))\n .arg(remain)\n .arg(hours, 2, 10, QChar('0'))\n .arg(minutes, 2, 10, QChar('0'))\n .arg(seconds, 2, 10, QChar('0'));\n m_simTimeValue.setText(t);\n}\n\nvoid MainWidget::displayFPS(const int fps)\n{\n m_fpsLCD.display(fps);\n}\n\nvoid MainWidget::updateStartButtonText(const bool setStop)\n{\n if (setStop) {\n m_startButton.setText(tr(\"Stop\"));\n } else {\n m_startButton.setText(tr(\"Start\"));\n }\n m_frameAdvanceButton.setDisabled(setStop);\n}\n\nvoid MainWidget::displayStyle(QLCDNumber& lcd)\n{\n lcd.setFrameStyle(QFrame::StyledPanel | QFrame::Plain);\n lcd.setSegmentStyle(QLCDNumber::Flat);\n}\n\nvoid MainWidget::displayStyle(QLabel& lbl)\n{\n lbl.setFrameStyle(QFrame::StyledPanel | QFrame::Plain);\n lbl.setAlignment(Qt::AlignRight);\n}\n\nvoid MainWidget::displayModelScale(const float val)\n{\n if (val <= 0.0f) {\n return;\n }\n bool state = m_scaleValue.blockSignals(true);\n m_scaleValue.setText(QString::number(1.0f \/ val));\n m_scaleValue.blockSignals(state);\n}\n\nvoid MainWidget::resetScaleSlider()\n{\n bool state = m_scaleSlider.blockSignals(true);\n m_scaleSlider.setSliderPosition(UpdateUi::SCALE_SLIDER_CENTER);\n m_scaleSlider.blockSignals(state);\n}\n\nvoid MainWidget::displayTimePerFrame(const float time)\n{\n m_simCondition.timePerFrame = time;\n m_timePerFrameValue.setText(QString::number(time));\n}\n\nvoid MainWidget::showInitializerDialog()\n{\n if (!m_initializerDialog) {\n m_initializerDialog = new InitializerDialog(&m_updateUi, this);\n connect(m_initializerDialog, &InitializerDialog::accepted, this, &MainWidget::acceptInitializerDialog);\n connect(&m_updateUi, &UpdateUi::applyInitialConditions, this, &MainWidget::acceptInitializerDialog);\n }\n m_initializerDialog->setValues(m_simCondition);\n\n m_initializerDialog->show();\n m_initializerDialog->raise();\n m_initializerDialog->activateWindow();\n}\n\nvoid MainWidget::acceptInitializerDialog()\n{\n m_simCondition = m_initializerDialog->simCondition();\n reset(m_simCondition);\n}\n\nvoid MainWidget::displayEngineName(const QString& name)\n{\n m_engineValue.setText(name);\n}\n\nvoid MainWidget::reset(const bhs::SimCondition& sim)\n{\n m_graphicWindows.reset(sim);\n resetScaleSlider();\n updateStartButtonText(false);\n}\n\nvoid MainWidget::displayPresetName(const QString& name)\n{\n m_presetValue.setText(name);\n}\n\nvoid MainWidget::resetInitial()\n{\n reset(m_simCondition);\n}\n\nvoid MainWidget::displayNumberOfParticles(const int num)\n{\n m_simCondition.numberOfParticles = num;\n m_particleNumValue.setText(QString::number(num));\n}\n<commit_msg>graphButton enabled false<commit_after>#include \"mainwidget.h\"\n\nMainWidget::MainWidget(QWidget* parent)\n : QWidget(parent)\n , m_graphicWindows(&m_updateUi)\n , m_hLayout(this)\n , m_frameNumberLCD(12)\n , m_fpsLCD(12)\n , m_frameAdvanceButton(tr(\"Frame Advance\"))\n{\n this->setWindowTitle(tr(\"Blackhole Simulator 2.0 beta\"));\n\n auto container = QWidget::createWindowContainer(&m_graphicWindows);\n container->setFocusPolicy(Qt::StrongFocus);\n container->setFocus();\n container->setMinimumSize(QSize(200, 100));\n QSize screenSize = m_graphicWindows.screen()->size();\n container->setMaximumSize(screenSize);\n\n m_vLayout.setAlignment(Qt::AlignTop);\n m_hLayout.addWidget(container, Qt::AlignLeft);\n m_hLayout.addLayout(&m_vLayout);\n\n initUi();\n}\n\nvoid MainWidget::initUi()\n{\n \/\/ FPS\n auto fpsLayout = new QHBoxLayout;\n auto fpsLabel = new QLabel(tr(\"FPS\"));\n fpsLayout->addWidget(fpsLabel);\n displayStyle(m_fpsLCD);\n fpsLayout->addWidget(&m_fpsLCD);\n m_vLayout.addLayout(fpsLayout);\n connect(&m_updateUi, &UpdateUi::displayFps, this, &MainWidget::displayFPS);\n\n \/\/ Frames\n auto frameNumberLayout = new QHBoxLayout;\n auto frameNumberLabel = new QLabel(tr(\"Frames\"));\n frameNumberLayout->addWidget(frameNumberLabel);\n displayStyle(m_frameNumberLCD);\n frameNumberLayout->addWidget(&m_frameNumberLCD);\n m_vLayout.addLayout(frameNumberLayout);\n connect(&m_updateUi, &UpdateUi::displayFrameNumber, this, &MainWidget::displayFrameNumber);\n\n \/\/ Time\/Frame\n auto timePerFrameLayout = new QHBoxLayout;\n auto timePerFrameLabel = new QLabel(tr(\"Time\/Frame (s)\"));\n timePerFrameLayout->addWidget(timePerFrameLabel);\n displayStyle(m_timePerFrameValue);\n timePerFrameLayout->addWidget(&m_timePerFrameValue);\n m_vLayout.addLayout(timePerFrameLayout);\n connect(&m_updateUi, &UpdateUi::displayTimePerFrame, this, &MainWidget::displayTimePerFrame);\n\n \/\/ Simulation Time\n auto simTimeLayout = new QHBoxLayout;\n auto simTimeLabel = new QLabel(tr(\"Time\"));\n simTimeLayout->addWidget(simTimeLabel);\n displayStyle(m_simTimeValue);\n simTimeLayout->addWidget(&m_simTimeValue);\n m_vLayout.addLayout(simTimeLayout);\n\n \/\/ Start Button\n m_startButton.setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(&m_startButton);\n connect(&m_startButton, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::startSim);\n connect(&m_updateUi, &UpdateUi::updateStartButtonText, this, &MainWidget::updateStartButtonText);\n\n \/\/ Frame Advance\n m_frameAdvanceButton.setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(&m_frameAdvanceButton);\n connect(&m_frameAdvanceButton, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::frameAdvance);\n\n \/\/ Reset\n auto resetBtn = new QPushButton(tr(\"Reset\"));\n resetBtn->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(resetBtn);\n connect(resetBtn, &QPushButton::clicked, this, &MainWidget::resetInitial);\n\n \/\/ Circle strafing\n auto circleStrafingCB = new QCheckBox(tr(\"Circle strafing\"));\n circleStrafingCB->setFocusPolicy(Qt::NoFocus);\n circleStrafingCB->setChecked(false);\n m_vLayout.addWidget(circleStrafingCB);\n connect(circleStrafingCB, &QCheckBox::stateChanged, &m_graphicWindows, &GraphicWindow::circleStrafing);\n\n \/\/ Grid Lines\n auto gridLinesCB = new QCheckBox(tr(\"Grid Lines\"));\n gridLinesCB->setChecked(true);\n gridLinesCB->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(gridLinesCB);\n connect(gridLinesCB, &QCheckBox::stateChanged, &m_graphicWindows, &GraphicWindow::enableGridLines);\n\n \/\/ Line Type\n auto btnLineType = new QPushButton(tr(\"Line Type\"));\n btnLineType->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(btnLineType);\n connect(btnLineType, &QPushButton::clicked, &m_graphicWindows, &GraphicWindow::changeLinePosition);\n\n \/\/ Model Scale\n auto scaleLabel = new QLabel(tr(\"Model Scale (m):\"));\n m_vLayout.addWidget(scaleLabel);\n\n m_scaleValue.setAlignment(Qt::AlignRight);\n m_vLayout.addWidget(&m_scaleValue);\n connect(&m_updateUi, &UpdateUi::displayModelScale, this, &MainWidget::displayModelScale);\n connect(&m_scaleValue, &QLineEdit::textChanged, &m_graphicWindows, &GraphicWindow::setModelScale);\n\n m_scaleSlider.setFocusPolicy(Qt::NoFocus);\n m_scaleSlider.setOrientation(Qt::Horizontal);\n m_scaleSlider.setMinimum(0);\n m_scaleSlider.setMaximum(UpdateUi::SCALE_SLIDER_CENTER * 2);\n m_scaleSlider.setSliderPosition(UpdateUi::SCALE_SLIDER_CENTER);\n m_vLayout.addWidget(&m_scaleSlider);\n connect(&m_scaleSlider, &QSlider::sliderMoved, &m_graphicWindows, &GraphicWindow::setModelScaleInt);\n\n \/\/ Number of particles\n auto particleNumLabel = new QLabel(tr(\"Number of particles\"));\n m_vLayout.addWidget(particleNumLabel);\n displayStyle(m_particleNumValue);\n m_vLayout.addWidget(&m_particleNumValue);\n connect(&m_updateUi, &UpdateUi::displayNumberOfParticles, this, &MainWidget::displayNumberOfParticles);\n\n \/\/ Simulation Engine\n auto engineLabel = new QLabel(tr(\"Simulation Engine\"));\n m_vLayout.addWidget(engineLabel);\n displayStyle(m_engineValue);\n m_vLayout.addWidget(&m_engineValue);\n connect(&m_updateUi, &UpdateUi::displayEngineName, this, &MainWidget::displayEngineName);\n\n \/\/ Initial Condition Preset\n auto presetLabel = new QLabel(tr(\"Initial Conditions Preset\"));\n m_vLayout.addWidget(presetLabel);\n displayStyle(m_presetValue);\n m_vLayout.addWidget(&m_presetValue);\n connect(&m_updateUi, &UpdateUi::displayPresetName, this, &MainWidget::displayPresetName);\n\n \/\/ New\n auto newButton = new QPushButton(tr(\"New...\"));\n newButton->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(newButton);\n connect(newButton, &QPushButton::clicked, this, &MainWidget::showInitializerDialog);\n\n \/\/ Graph\n auto graphButton = new QPushButton(tr(\"Graph...\"));\n graphButton->setEnabled(false);\n graphButton->setFocusPolicy(Qt::NoFocus);\n m_vLayout.addWidget(graphButton);\n \/\/connect(newButton, &QPushButton::clicked, this, &MainWidget::showInitializerDialog);\n\n updateStartButtonText(false);\n}\n\nvoid MainWidget::displayFrameNumber(const int num)\n{\n m_frameNumberLCD.display(num);\n quint64 time = floor(m_simCondition.timePerFrame * (float)num);\n quint64 seconds = time % 60;\n quint64 remain = time \/ 60;\n quint64 minutes = remain % 60;\n remain \/= 60;\n quint64 hours = remain % 24;\n remain \/= 24;\n QString t = QString(tr(\"Day %1 %2:%3:%4\"))\n .arg(remain)\n .arg(hours, 2, 10, QChar('0'))\n .arg(minutes, 2, 10, QChar('0'))\n .arg(seconds, 2, 10, QChar('0'));\n m_simTimeValue.setText(t);\n}\n\nvoid MainWidget::displayFPS(const int fps)\n{\n m_fpsLCD.display(fps);\n}\n\nvoid MainWidget::updateStartButtonText(const bool setStop)\n{\n if (setStop) {\n m_startButton.setText(tr(\"Stop\"));\n } else {\n m_startButton.setText(tr(\"Start\"));\n }\n m_frameAdvanceButton.setDisabled(setStop);\n}\n\nvoid MainWidget::displayStyle(QLCDNumber& lcd)\n{\n lcd.setFrameStyle(QFrame::StyledPanel | QFrame::Plain);\n lcd.setSegmentStyle(QLCDNumber::Flat);\n}\n\nvoid MainWidget::displayStyle(QLabel& lbl)\n{\n lbl.setFrameStyle(QFrame::StyledPanel | QFrame::Plain);\n lbl.setAlignment(Qt::AlignRight);\n}\n\nvoid MainWidget::displayModelScale(const float val)\n{\n if (val <= 0.0f) {\n return;\n }\n bool state = m_scaleValue.blockSignals(true);\n m_scaleValue.setText(QString::number(1.0f \/ val));\n m_scaleValue.blockSignals(state);\n}\n\nvoid MainWidget::resetScaleSlider()\n{\n bool state = m_scaleSlider.blockSignals(true);\n m_scaleSlider.setSliderPosition(UpdateUi::SCALE_SLIDER_CENTER);\n m_scaleSlider.blockSignals(state);\n}\n\nvoid MainWidget::displayTimePerFrame(const float time)\n{\n m_simCondition.timePerFrame = time;\n m_timePerFrameValue.setText(QString::number(time));\n}\n\nvoid MainWidget::showInitializerDialog()\n{\n if (!m_initializerDialog) {\n m_initializerDialog = new InitializerDialog(&m_updateUi, this);\n connect(m_initializerDialog, &InitializerDialog::accepted, this, &MainWidget::acceptInitializerDialog);\n connect(&m_updateUi, &UpdateUi::applyInitialConditions, this, &MainWidget::acceptInitializerDialog);\n }\n m_initializerDialog->setValues(m_simCondition);\n\n m_initializerDialog->show();\n m_initializerDialog->raise();\n m_initializerDialog->activateWindow();\n}\n\nvoid MainWidget::acceptInitializerDialog()\n{\n m_simCondition = m_initializerDialog->simCondition();\n reset(m_simCondition);\n}\n\nvoid MainWidget::displayEngineName(const QString& name)\n{\n m_engineValue.setText(name);\n}\n\nvoid MainWidget::reset(const bhs::SimCondition& sim)\n{\n m_graphicWindows.reset(sim);\n resetScaleSlider();\n updateStartButtonText(false);\n}\n\nvoid MainWidget::displayPresetName(const QString& name)\n{\n m_presetValue.setText(name);\n}\n\nvoid MainWidget::resetInitial()\n{\n reset(m_simCondition);\n}\n\nvoid MainWidget::displayNumberOfParticles(const int num)\n{\n m_simCondition.numberOfParticles = num;\n m_particleNumValue.setText(QString::number(num));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QFileDialog>\n#include <QFontDialog>\n#include <QImageReader>\n#include <QLabel>\n#include <QMenu>\n#include <QMessageBox>\n#include <QSettings>\n#include <QTimer>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n\nconst int maxRecentDocuments = 10;\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n setAttribute(Qt::WA_QuitOnClose);\n setWindowState(windowState() | Qt::WindowMaximized);\n setWindowTitle(appName());\n\n modeActionGroup = new QActionGroup(this);\n openFileAction = new QAction(style()->standardIcon(QStyle::SP_DialogOpenButton), QString::fromUtf8(\"Открыть файл\"), this);\n saveFileAction = new QAction(style()->standardIcon(QStyle::SP_DialogSaveButton), QString::fromUtf8(\"Сохранить файл\"), this);\n toggleEtalonModeAction = new QAction(QIcon(\":\/pictures\/etalon.png\"), QString::fromUtf8(\"Включить\/выключить режим задания эталона\"), this);\n measureSegmentLengthAction = new QAction(QIcon(\":\/pictures\/segment_length.png\"), QString::fromUtf8(\"Измерение длин отрезков\"), modeActionGroup);\n measurePolylineLengthAction = new QAction(QIcon(\":\/pictures\/polyline_length.png\"), QString::fromUtf8(\"Измерение длин кривых\"), modeActionGroup);\n measureClosedPolylineLengthAction = new QAction(QIcon(\":\/pictures\/closed_polyline_length.png\"), QString::fromUtf8(\"Измерение длин замкнутых кривых\"), modeActionGroup);\n measureRectangleAreaAction = new QAction(QIcon(\":\/pictures\/rectangle_area.png\"), QString::fromUtf8(\"Измерение площадей прямоугольников\"), modeActionGroup);\n measurePolygonAreaAction = new QAction(QIcon(\":\/pictures\/polygon_area.png\"), QString::fromUtf8(\"Измерение площадей многоугольников\"), modeActionGroup);\n toggleRulerAction = new QAction(QIcon(\":\/pictures\/toggle_ruler.png\"), QString::fromUtf8(\"Показать\/скрыть масштабную линейку\"), this);\n customizeInscriptionFontAction = new QAction(QIcon(\":\/pictures\/font.png\"), QString::fromUtf8(\"Настроить шрифт подписей\"), this);\n aboutAction = new QAction(QIcon(\":\/pictures\/about.png\"), QString::fromUtf8(\"О программе\"), this);\n\n openRecentMenu = new QMenu(this);\n openFileAction->setMenu(openRecentMenu);\n saveFileAction->setEnabled(false);\n\n toggleEtalonModeAction->setCheckable(true);\n toggleEtalonModeAction->setChecked(true);\n\n foreach (QAction* action, modeActionGroup->actions())\n action->setCheckable(true);\n measureSegmentLengthAction->setChecked(true);\n\n toggleRulerAction->setCheckable(true);\n toggleRulerAction->setChecked(true);\n\n ui->mainToolBar->addAction(openFileAction);\n ui->mainToolBar->addAction(saveFileAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleEtalonModeAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addActions(modeActionGroup->actions());\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleRulerAction);\n ui->mainToolBar->addAction(customizeInscriptionFontAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(aboutAction);\n ui->mainToolBar->setIconSize(QSize(32, 32));\n ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);\n\n QFont statusBarFont = ui->statusBar->font();\n int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; \/\/ In contrast to ``labelFont.pointSize()'' it always works\n statusBarFont.setPointSize(newSize);\n ui->statusBar->setFont(statusBarFont);\n scaleLabel = new QLabel(this);\n statusLabel = new QLabel(this);\n ui->statusBar->addPermanentWidget(scaleLabel);\n ui->statusBar->addWidget(statusLabel);\n\n canvasWidget = 0;\n\n connect(openFileAction, SIGNAL(triggered()), this, SLOT(openFile()));\n connect(saveFileAction, SIGNAL(triggered()), this, SLOT(saveFile()));\n connect(customizeInscriptionFontAction, SIGNAL(triggered()), this, SLOT(customizeInscriptionFont()));\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));\n\n connect(toggleEtalonModeAction, SIGNAL(toggled(bool)), this, SLOT(toggleEtalonDefinition(bool)));\n connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));\n\n setDrawOptionsEnabled(false);\n loadAndApplySettings();\n}\n\nMainWindow::~MainWindow()\n{\n saveSettings();\n delete ui;\n}\n\n\nQString MainWindow::companyName() const\n{\n return \"AMM Soft\";\n}\n\nQString MainWindow::appName() const\n{\n return \"AreaMeasurement\";\n}\n\nQList<int> MainWindow::appVersion() const\n{\n \/\/ TODO: Don't forget to increment it!\n return QList<int>() << 1 << 0;\n}\n\nQString MainWindow::appVersionString() const\n{\n QString versionString;\n foreach (int x, appVersion())\n versionString += QString::number(x) + '.';\n return versionString.left(versionString.length() - 1);\n}\n\n\nQFont MainWindow::getInscriptionFont() const\n{\n return inscriptionFont;\n}\n\nvoid MainWindow::setMode(ShapeType newMode)\n{\n if (canvasWidget)\n canvasWidget->setMode(newMode);\n}\n\n\nQString MainWindow::getImageFormatsFilter() const\n{\n QList<QByteArray> supportedFormatsList__ = QImageReader::supportedImageFormats();\n QSet<QString> supportedFormatsSet;\n foreach (const QByteArray& format, supportedFormatsList__)\n supportedFormatsSet.insert(QString(format).toLower());\n QStringList supportedFormatsList(supportedFormatsSet.toList());\n qSort(supportedFormatsList);\n QString allFormatsString;\n QStringList singleFormatsList;\n foreach (const QString& lowerFormat, supportedFormatsList) {\n QString upperFormat = lowerFormat.toUpper();\n allFormatsString += QString(\"*.%1 \").arg(lowerFormat);\n if (upperFormat == \"JPEG\")\n singleFormatsList += QString::fromUtf8(\"Изображения JPEG (*.jpeg *.jpg)\");\n else if (upperFormat != \"JPG\")\n singleFormatsList += QString::fromUtf8(\"Изображения %1 (*.%2)\").arg(upperFormat).arg(lowerFormat);\n }\n allFormatsString = allFormatsString.trimmed();\n return QString::fromUtf8(\"Все изображения (%1);;\").arg(allFormatsString) + singleFormatsList.join(\";;\");\n}\n\nvoid MainWindow::doOpenFile(const QString& filename)\n{\n QPixmap image;\n if (!image.load(filename)) {\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не могу открыть изображение «%1».\").arg(filename));\n return;\n }\n\n openedFile = filename;\n recentFiles.removeAll(filename);\n recentFiles.prepend(filename);\n if (recentFiles.size() > maxRecentDocuments)\n recentFiles.erase(recentFiles.begin() + maxRecentDocuments, recentFiles.end());\n updateOpenRecentMenu();\n\n toggleEtalonModeAction->setChecked(true);\n measureSegmentLengthAction->setChecked(true);\n\n delete canvasWidget;\n canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);\n ui->containingScrollArea->setWidget(canvasWidget);\n\n connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));\n canvasWidget->toggleRuler(toggleRulerAction->isChecked());\n\n saveFileAction->setEnabled(true);\n saveSettings();\n setDrawOptionsEnabled(true);\n}\n\nvoid MainWindow::doSaveFile(const QString& filename)\n{\n ASSERT_RETURN(canvasWidget);\n bool ok = canvasWidget->getModifiedImage().save(filename);\n if (ok)\n ui->statusBar->showMessage(QString::fromUtf8(\"Файл успешно сохранён\"), 5000);\n else\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не удалось записать файл «%1»!\").arg(filename));\n}\n\nvoid MainWindow::loadSettings()\n{\n QSettings settings(companyName(), appName());\n inscriptionFont = settings.value(\"Inscription Font\", QFont()).value<QFont>();\n recentFiles.clear();\n int nRecent = settings.beginReadArray(\"Recent Documents\");\n for (int i = 0; i < nRecent; ++i) {\n settings.setArrayIndex(i);\n recentFiles.append(settings.value(\"Filename\").toString());\n }\n settings.endArray();\n}\n\nvoid MainWindow::loadAndApplySettings()\n{\n loadSettings();\n updateOpenRecentMenu();\n}\n\nvoid MainWindow::saveSettings() const\n{\n QSettings settings(companyName(), appName());\n settings.clear();\n settings.setValue(\"Inscription Font\", inscriptionFont);\n settings.beginWriteArray(\"Recent Documents\");\n for (int i = 0; i < recentFiles.size(); ++i) {\n settings.setArrayIndex(i);\n settings.setValue(\"Filename\", recentFiles[i]);\n }\n settings.endArray();\n}\n\nvoid MainWindow::updateOpenRecentMenu()\n{\n openRecentMenu->clear();\n foreach (const QString& file, recentFiles)\n openRecentMenu->addAction(file, this, SLOT(openRecentFile()));\n if (openRecentMenu->isEmpty()) {\n QAction* infoAction = new QAction(QString::fromUtf8(\"Список недавно открытых документов пуст\"), openRecentMenu);\n infoAction->setEnabled(false);\n openRecentMenu->addAction(infoAction);\n }\n}\n\n\nvoid MainWindow::openFile()\n{\n QString filename = QFileDialog::getOpenFileName(this, QString::fromUtf8(\"Открыть изображение — \") + appName(),\n QString(), getImageFormatsFilter(), 0);\n if (!filename.isEmpty())\n doOpenFile(filename);\n}\n\nvoid MainWindow::openRecentFile()\n{\n QAction* triggeredAction = qobject_cast<QAction*>(sender());\n ASSERT_RETURN(triggeredAction);\n doOpenFile(triggeredAction->text());\n}\n\nvoid MainWindow::saveFile()\n{\n QString filename = QFileDialog::getSaveFileName(this, QString::fromUtf8(\"Сохранить изображение — \") + appName(),\n openedFile, getImageFormatsFilter(), 0);\n if (!filename.isEmpty())\n doSaveFile(filename);\n}\n\nvoid MainWindow::setDrawOptionsEnabled(bool enabled)\n{\n toggleEtalonModeAction->setEnabled(enabled);\n modeActionGroup ->setEnabled(enabled);\n toggleRulerAction ->setEnabled(enabled);\n}\n\nvoid MainWindow::updateMode(QAction* modeAction)\n{\n if (modeAction == measureSegmentLengthAction)\n return setMode(SEGMENT);\n if (modeAction == measurePolylineLengthAction)\n return setMode(POLYLINE);\n if (modeAction == measureClosedPolylineLengthAction)\n return setMode(CLOSED_POLYLINE);\n if (modeAction == measureRectangleAreaAction)\n return setMode(RECTANGLE);\n if (modeAction == measurePolygonAreaAction)\n return setMode(POLYGON);\n ERROR_RETURN();\n}\n\nvoid MainWindow::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n ASSERT_RETURN(canvasWidget);\n canvasWidget->toggleEtalonDefinition(isDefiningEtalon);\n toggleEtalonModeAction->setChecked(isDefiningEtalon);\n}\n\nvoid MainWindow::customizeInscriptionFont()\n{\n \/\/ TODO: Why does the dialog show wrong font for the first time?\n inscriptionFont = QFontDialog::getFont(0, inscriptionFont, this);\n if (canvasWidget)\n canvasWidget->update();\n}\n\nvoid MainWindow::showAbout()\n{\n QString aboutText = QString::fromUtf8(\"Программа %1, версия %2.\\n\\n\"\n \"Приложение предназначено для измерения длин и площадей объектов на чертежах, картах и т.д.\\n\\n\"\n \"Автор — Матвеякин Андрей.\\n\\n\"\n \"Программа распространяется бесплатно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения.\"\n ).arg(appName()).arg(appVersionString());\n QMessageBox::about(this, QString::fromUtf8(\"О программе %1\").arg(appName()), aboutText);\n}\n<commit_msg>Remove images that can't be opened from ``Recent files'' list<commit_after>#include <QFileDialog>\n#include <QFontDialog>\n#include <QImageReader>\n#include <QLabel>\n#include <QMenu>\n#include <QMessageBox>\n#include <QSettings>\n#include <QTimer>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n\nconst int maxRecentDocuments = 10;\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n setAttribute(Qt::WA_QuitOnClose);\n setWindowState(windowState() | Qt::WindowMaximized);\n setWindowTitle(appName());\n\n modeActionGroup = new QActionGroup(this);\n openFileAction = new QAction(style()->standardIcon(QStyle::SP_DialogOpenButton), QString::fromUtf8(\"Открыть файл\"), this);\n saveFileAction = new QAction(style()->standardIcon(QStyle::SP_DialogSaveButton), QString::fromUtf8(\"Сохранить файл\"), this);\n toggleEtalonModeAction = new QAction(QIcon(\":\/pictures\/etalon.png\"), QString::fromUtf8(\"Включить\/выключить режим задания эталона\"), this);\n measureSegmentLengthAction = new QAction(QIcon(\":\/pictures\/segment_length.png\"), QString::fromUtf8(\"Измерение длин отрезков\"), modeActionGroup);\n measurePolylineLengthAction = new QAction(QIcon(\":\/pictures\/polyline_length.png\"), QString::fromUtf8(\"Измерение длин кривых\"), modeActionGroup);\n measureClosedPolylineLengthAction = new QAction(QIcon(\":\/pictures\/closed_polyline_length.png\"), QString::fromUtf8(\"Измерение длин замкнутых кривых\"), modeActionGroup);\n measureRectangleAreaAction = new QAction(QIcon(\":\/pictures\/rectangle_area.png\"), QString::fromUtf8(\"Измерение площадей прямоугольников\"), modeActionGroup);\n measurePolygonAreaAction = new QAction(QIcon(\":\/pictures\/polygon_area.png\"), QString::fromUtf8(\"Измерение площадей многоугольников\"), modeActionGroup);\n toggleRulerAction = new QAction(QIcon(\":\/pictures\/toggle_ruler.png\"), QString::fromUtf8(\"Показать\/скрыть масштабную линейку\"), this);\n customizeInscriptionFontAction = new QAction(QIcon(\":\/pictures\/font.png\"), QString::fromUtf8(\"Настроить шрифт подписей\"), this);\n aboutAction = new QAction(QIcon(\":\/pictures\/about.png\"), QString::fromUtf8(\"О программе\"), this);\n\n openRecentMenu = new QMenu(this);\n openFileAction->setMenu(openRecentMenu);\n saveFileAction->setEnabled(false);\n\n toggleEtalonModeAction->setCheckable(true);\n toggleEtalonModeAction->setChecked(true);\n\n foreach (QAction* action, modeActionGroup->actions())\n action->setCheckable(true);\n measureSegmentLengthAction->setChecked(true);\n\n toggleRulerAction->setCheckable(true);\n toggleRulerAction->setChecked(true);\n\n ui->mainToolBar->addAction(openFileAction);\n ui->mainToolBar->addAction(saveFileAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleEtalonModeAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addActions(modeActionGroup->actions());\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleRulerAction);\n ui->mainToolBar->addAction(customizeInscriptionFontAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(aboutAction);\n ui->mainToolBar->setIconSize(QSize(32, 32));\n ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);\n\n QFont statusBarFont = ui->statusBar->font();\n int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; \/\/ In contrast to ``labelFont.pointSize()'' it always works\n statusBarFont.setPointSize(newSize);\n ui->statusBar->setFont(statusBarFont);\n scaleLabel = new QLabel(this);\n statusLabel = new QLabel(this);\n ui->statusBar->addPermanentWidget(scaleLabel);\n ui->statusBar->addWidget(statusLabel);\n\n canvasWidget = 0;\n\n connect(openFileAction, SIGNAL(triggered()), this, SLOT(openFile()));\n connect(saveFileAction, SIGNAL(triggered()), this, SLOT(saveFile()));\n connect(customizeInscriptionFontAction, SIGNAL(triggered()), this, SLOT(customizeInscriptionFont()));\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));\n\n connect(toggleEtalonModeAction, SIGNAL(toggled(bool)), this, SLOT(toggleEtalonDefinition(bool)));\n connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));\n\n setDrawOptionsEnabled(false);\n loadAndApplySettings();\n}\n\nMainWindow::~MainWindow()\n{\n saveSettings();\n delete ui;\n}\n\n\nQString MainWindow::companyName() const\n{\n return \"AMM Soft\";\n}\n\nQString MainWindow::appName() const\n{\n return \"AreaMeasurement\";\n}\n\nQList<int> MainWindow::appVersion() const\n{\n \/\/ TODO: Don't forget to increment it!\n return QList<int>() << 1 << 0;\n}\n\nQString MainWindow::appVersionString() const\n{\n QString versionString;\n foreach (int x, appVersion())\n versionString += QString::number(x) + '.';\n return versionString.left(versionString.length() - 1);\n}\n\n\nQFont MainWindow::getInscriptionFont() const\n{\n return inscriptionFont;\n}\n\nvoid MainWindow::setMode(ShapeType newMode)\n{\n if (canvasWidget)\n canvasWidget->setMode(newMode);\n}\n\n\nQString MainWindow::getImageFormatsFilter() const\n{\n QList<QByteArray> supportedFormatsList__ = QImageReader::supportedImageFormats();\n QSet<QString> supportedFormatsSet;\n foreach (const QByteArray& format, supportedFormatsList__)\n supportedFormatsSet.insert(QString(format).toLower());\n QStringList supportedFormatsList(supportedFormatsSet.toList());\n qSort(supportedFormatsList);\n QString allFormatsString;\n QStringList singleFormatsList;\n foreach (const QString& lowerFormat, supportedFormatsList) {\n QString upperFormat = lowerFormat.toUpper();\n allFormatsString += QString(\"*.%1 \").arg(lowerFormat);\n if (upperFormat == \"JPEG\")\n singleFormatsList += QString::fromUtf8(\"Изображения JPEG (*.jpeg *.jpg)\");\n else if (upperFormat != \"JPG\")\n singleFormatsList += QString::fromUtf8(\"Изображения %1 (*.%2)\").arg(upperFormat).arg(lowerFormat);\n }\n allFormatsString = allFormatsString.trimmed();\n return QString::fromUtf8(\"Все изображения (%1);;\").arg(allFormatsString) + singleFormatsList.join(\";;\");\n}\n\nvoid MainWindow::doOpenFile(const QString& filename)\n{\n recentFiles.removeAll(filename);\n\n QPixmap image;\n if (!image.load(filename)) {\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не могу открыть изображение «%1».\").arg(filename));\n updateOpenRecentMenu();\n return;\n }\n\n openedFile = filename;\n recentFiles.prepend(filename);\n if (recentFiles.size() > maxRecentDocuments)\n recentFiles.erase(recentFiles.begin() + maxRecentDocuments, recentFiles.end());\n updateOpenRecentMenu();\n\n toggleEtalonModeAction->setChecked(true);\n measureSegmentLengthAction->setChecked(true);\n\n delete canvasWidget;\n canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);\n ui->containingScrollArea->setWidget(canvasWidget);\n\n connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));\n canvasWidget->toggleRuler(toggleRulerAction->isChecked());\n\n saveFileAction->setEnabled(true);\n saveSettings();\n setDrawOptionsEnabled(true);\n}\n\nvoid MainWindow::doSaveFile(const QString& filename)\n{\n ASSERT_RETURN(canvasWidget);\n bool ok = canvasWidget->getModifiedImage().save(filename);\n if (ok)\n ui->statusBar->showMessage(QString::fromUtf8(\"Файл успешно сохранён\"), 5000);\n else\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не удалось записать файл «%1»!\").arg(filename));\n}\n\nvoid MainWindow::loadSettings()\n{\n QSettings settings(companyName(), appName());\n inscriptionFont = settings.value(\"Inscription Font\", QFont()).value<QFont>();\n recentFiles.clear();\n int nRecent = settings.beginReadArray(\"Recent Documents\");\n for (int i = 0; i < nRecent; ++i) {\n settings.setArrayIndex(i);\n recentFiles.append(settings.value(\"Filename\").toString());\n }\n settings.endArray();\n}\n\nvoid MainWindow::loadAndApplySettings()\n{\n loadSettings();\n updateOpenRecentMenu();\n}\n\nvoid MainWindow::saveSettings() const\n{\n QSettings settings(companyName(), appName());\n settings.clear();\n settings.setValue(\"Inscription Font\", inscriptionFont);\n settings.beginWriteArray(\"Recent Documents\");\n for (int i = 0; i < recentFiles.size(); ++i) {\n settings.setArrayIndex(i);\n settings.setValue(\"Filename\", recentFiles[i]);\n }\n settings.endArray();\n}\n\nvoid MainWindow::updateOpenRecentMenu()\n{\n openRecentMenu->clear();\n foreach (const QString& file, recentFiles)\n openRecentMenu->addAction(file, this, SLOT(openRecentFile()));\n if (openRecentMenu->isEmpty()) {\n QAction* infoAction = new QAction(QString::fromUtf8(\"Список недавно открытых документов пуст\"), openRecentMenu);\n infoAction->setEnabled(false);\n openRecentMenu->addAction(infoAction);\n }\n}\n\n\nvoid MainWindow::openFile()\n{\n QString filename = QFileDialog::getOpenFileName(this, QString::fromUtf8(\"Открыть изображение — \") + appName(),\n QString(), getImageFormatsFilter(), 0);\n if (!filename.isEmpty())\n doOpenFile(filename);\n}\n\nvoid MainWindow::openRecentFile()\n{\n QAction* triggeredAction = qobject_cast<QAction*>(sender());\n ASSERT_RETURN(triggeredAction);\n doOpenFile(triggeredAction->text());\n}\n\nvoid MainWindow::saveFile()\n{\n QString filename = QFileDialog::getSaveFileName(this, QString::fromUtf8(\"Сохранить изображение — \") + appName(),\n openedFile, getImageFormatsFilter(), 0);\n if (!filename.isEmpty())\n doSaveFile(filename);\n}\n\nvoid MainWindow::setDrawOptionsEnabled(bool enabled)\n{\n toggleEtalonModeAction->setEnabled(enabled);\n modeActionGroup ->setEnabled(enabled);\n toggleRulerAction ->setEnabled(enabled);\n}\n\nvoid MainWindow::updateMode(QAction* modeAction)\n{\n if (modeAction == measureSegmentLengthAction)\n return setMode(SEGMENT);\n if (modeAction == measurePolylineLengthAction)\n return setMode(POLYLINE);\n if (modeAction == measureClosedPolylineLengthAction)\n return setMode(CLOSED_POLYLINE);\n if (modeAction == measureRectangleAreaAction)\n return setMode(RECTANGLE);\n if (modeAction == measurePolygonAreaAction)\n return setMode(POLYGON);\n ERROR_RETURN();\n}\n\nvoid MainWindow::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n ASSERT_RETURN(canvasWidget);\n canvasWidget->toggleEtalonDefinition(isDefiningEtalon);\n toggleEtalonModeAction->setChecked(isDefiningEtalon);\n}\n\nvoid MainWindow::customizeInscriptionFont()\n{\n \/\/ TODO: Why does the dialog show wrong font for the first time?\n inscriptionFont = QFontDialog::getFont(0, inscriptionFont, this);\n if (canvasWidget)\n canvasWidget->update();\n}\n\nvoid MainWindow::showAbout()\n{\n QString aboutText = QString::fromUtf8(\"Программа %1, версия %2.\\n\\n\"\n \"Приложение предназначено для измерения длин и площадей объектов на чертежах, картах и т.д.\\n\\n\"\n \"Автор — Матвеякин Андрей.\\n\\n\"\n \"Программа распространяется бесплатно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения.\"\n ).arg(appName()).arg(appVersionString());\n QMessageBox::about(this, QString::fromUtf8(\"О программе %1\").arg(appName()), aboutText);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"graphSettingsPopup.h\"\r\n#include <QDateTime>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n#ifdef PMD_HAMP\r\n ui->pbtn_StartStop->setChecked(true);\r\n#endif\r\n\tprintf(\"This is MainWindow\\n\");\r\n\tqDebug(\"This is MainWindow via QDebug()\\n\");\r\n\r\n m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet();\r\n m_alarmBtnRedStyleSheet= \"*{border: 0px;background-image: url(:\/images\/icnBellRed.png);} *:checked{background-image:url();}\";\r\n\r\n m_graphWidget1 = new Widget(ui->graphECGWidget,this);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2 = new Widget(ui->graphABPWidget,this);\r\n m_graphWidget3 = new Widget(ui->graphPLETHWidget,this);\r\n#endif\r\n\r\n m_graphWidget1->initialized(GraphECG,3);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->initialized(GraphABP,1);\r\n m_graphWidget3->initialized(GraphPLETH,2);\r\n#endif\r\n\r\n m_selectedGraphWidget = NULL;\r\n\r\n \/\/ Set time\r\n updateTimeString();\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *timer = new QTimer(this);\r\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString()));\r\n timer->start(1000);\r\n\r\n m_timerAlarm =new QTimer (this);\r\n connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm()));\r\n m_timerAlarm->setInterval(500);\r\n m_timerAlarm->stop();\r\n\r\n m_timerDataValues = new QTimer(this);\r\n#ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH()));\r\n m_timerDataValues->setInterval(3000);\r\n #ifndef PMD_HAMP\r\n m_timerDataValues->start();\r\n #endif\r\n#endif\r\n\r\n m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68;\r\n m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119;\r\n m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79;\r\n m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99;\r\n\r\n m_cstatus=true;\r\n\r\n#ifdef PMD_MEHV\r\n m_nserver =new Server(this);\r\n m_cstatus=false;\r\n#endif\r\n\r\n#ifdef PMD_NUCLEUS\r\n m_dataSupplier=new DataSupplier(this);\r\n#endif\r\n\r\n#ifdef PMD_HAMP\r\n\tprintf(\"Creating HAMPDataSupplier\\n\");\r\n m_hampdataSupplier =new HAMPDataSupplier(this);\r\n m_cstatus=true;\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *hamptimer = new QTimer(this);\r\n connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort()));\r\n hamptimer->start(3000);\r\n\r\n#endif\r\n\r\n m_isPauseAll=false;\r\n m_isStart=true;\r\n m_isAlarmSilent=false;\r\n m_btnSilentPressed=false;\r\n\r\n m_graphSettingsPop =new GraphSettingsPopup(this);\r\n m_graphSettingsPop->hide();\r\n\r\n \/\/ Setup graph scrolling mode\r\n#ifdef ENABLE_GRAPH_SCROLLING\r\n on_pbtn_Scrolling_clicked(true);\r\n ui->pbtn_Scrolling->setChecked(true);\r\n#else\r\n on_pbtn_Scrolling_clicked(false);\r\n ui->pbtn_Scrolling->setChecked(false);\r\n#endif\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::updatePulse()\r\n{\r\n QString value=\"0\";\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n value.setNum(this->getPulseValue());\r\n }\r\n\r\n ui->labelPulse->setText(value);\r\n ui->labelPulse->repaint();\r\n}\r\n\r\nvoid MainWindow::updateABP()\r\n{\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelABP->setText(this->getABPValue());\r\n }\r\n else\r\n ui->labelABP->setText(\"0\/0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updatePLETH()\r\n{\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelSPO2->setText(this->getPLETHValue());\r\n }\r\n else\r\n ui->labelSPO2->setText(\"0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updateTimeString()\r\n{\r\n \/\/get current date and time\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mm:ss AP\");\r\n ui->labelTime->setText(dateTimeString);\r\n ui->labelTime->repaint();\r\n}\r\n\r\nint MainWindow::getPulseValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_HB_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n return m_HB_Simulate_Data[index];\r\n}\r\n\r\nQString MainWindow::getABPValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_ABP_Higher_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\/%2\").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nQString MainWindow::getPLETHValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_PLETH_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\").arg(m_PLETH_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Silent_clicked()\r\n{\r\n m_btnSilentPressed=!m_btnSilentPressed;\r\n if(m_btnSilentPressed)\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(true);\r\n ui->pbtn_ABP_Alarm->setChecked(true);\r\n ui->pbtn_spo2_Alarm->setChecked(true);\r\n m_isAlarmSilent=true;\r\n \/\/ ui->pbtn_Silent->setStyleSheet(\"*{border: 0px;background-image: url(:\/images\/btn_pressed.png);}\");\r\n }\r\n else\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(false);\r\n ui->pbtn_ABP_Alarm->setChecked(false);\r\n ui->pbtn_spo2_Alarm->setChecked(false);\r\n m_isAlarmSilent=false;\r\n \/\/ui->pbtn_Silent->setStyleSheet(\"\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_StartStop_clicked(bool checked)\r\n{\r\n\r\n#ifdef PMD_HAMP\r\n\r\n if(checked)\r\n {\r\n\t\tqDebug(\"MainWindow::on_pbtn_StartStop_clicked button pushed - %d\\n\", checked);\r\n m_isStart=false;\r\n m_timerDataValues->stop();\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=false;\r\n }\r\n else\r\n {\r\n\t\tqDebug(\"MainWindow::on_pbtn_StartStop_clicked button pushed - %d\\n\", checked);\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n m_timerDataValues->start();\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=true;\r\n\r\n }\r\n fflush(stdout);\r\n#else\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n }\r\n\r\n#endif\r\n\r\n}\r\n\r\nvoid MainWindow::on_pbtn_PauseAll_clicked(bool checked)\r\n{\r\n if(!checked)\r\n {\r\n m_isPauseAll=false;\r\n ui->pbtn_PauseAll->setText(\"Pause All\");\r\n }\r\n else\r\n {\r\n m_isPauseAll=true;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_PauseAll->setText(\"Start All\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Scrolling_clicked(bool checked)\r\n{\r\n (void)checked;\r\n#ifndef PMD_HAMP\r\n m_graphWidget1->setScrollingMode(checked);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->setScrollingMode(checked);\r\n m_graphWidget3->setScrollingMode(checked);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid MainWindow::updateTimer()\r\n{\r\n#ifdef PMD_MEHV\r\n pm_data_struct pm={0,0,0,0};\r\n dataReceived (&pm);\r\n#endif\r\n}\r\n\r\nvoid MainWindow::animateAlarm()\r\n{\r\n ui->pbtn_ABP_Alarm->toggle();\r\n ui->pbtn_ECG_Alarm->toggle();\r\n ui->pbtn_spo2_Alarm->toggle();\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::dataReceived(pm_data_struct *current)\r\n{\r\n\tqDebug(\"MainWindow::dataReceived: Entered\\n\");\r\n\tif (m_isPauseAll==false)\r\n {\r\n\t\tswitch(m_graphWidget1->getGraphType())\r\n {\r\n\r\n case GraphECG:\r\n m_graphWidget1->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget1->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget1->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n switch(m_graphWidget2->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget2->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget2->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget2->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n switch(m_graphWidget3->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget3->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget3->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget3->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n#endif\r\n }\r\n}\r\n\r\n#ifndef PMD_NUCLEUS\r\nvoid MainWindow::connectionStatus(bool status)\r\n{\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mmap\");\r\n m_cstatus=status;\r\n\r\n if(status)\r\n {\r\n ui->labelBulletText->setText(\"External system connected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(false);\r\n ui->pbtn_ECG_Alarm->setDisabled(false);\r\n ui->pbtn_spo2_Alarm->setDisabled(false);\r\n m_timerAlarm->stop();\r\n\r\n }\r\n else\r\n {\r\n ui->labelBulletText->setText(\"External system disconnected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(true);\r\n ui->pbtn_ECG_Alarm->setDisabled(true);\r\n ui->pbtn_spo2_Alarm->setDisabled(true);\r\n\r\n m_timerAlarm->start();\r\n updatePLETH();\r\n updateABP();\r\n updatePulse();\r\n }\r\n}\r\n#endif\r\n\r\nvoid MainWindow::launchGraphMenuPopup(Widget *widget)\r\n{\r\n if(m_graphSettingsPop->m_isVisible==false)\r\n {\r\n m_selectedGraphWidget=widget;\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n m_graphSettingsPop->show();\r\n }\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupOk()\r\n{\r\n if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize)\r\n {\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphABP:\r\n m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphPLETH:\r\n m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n }\r\n\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupCancel()\r\n{\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\n\r\n#ifdef PMD_HAMP\r\n\r\nvoid MainWindow::takeScreenSnapshort()\r\n{\r\n QRect r= this->rect();\r\n QPixmap pixmap=this->grab(r);\r\n QString fileName = m_hampdataSupplier->getScreenShortPath();\r\n\r\n\tqDebug(\"MainWindow::takeScreenSnapshort - fileName %s\\n\", fileName);\r\n\r\n if(pixmap.isNull()==false)\r\n pixmap.save(fileName,\"PNG\");\r\n else\r\n printf(\"pixmap is NULL\\n\");\r\n}\r\n\r\n#endif\r\n<commit_msg>test14<commit_after>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"graphSettingsPopup.h\"\r\n#include <QDateTime>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n#ifdef PMD_HAMP\r\n ui->pbtn_StartStop->setChecked(true);\r\n#endif\r\n\tqDebug(\"This is MainWindow via QDebug()\\n\");\r\n\r\n m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet();\r\n m_alarmBtnRedStyleSheet= \"*{border: 0px;background-image: url(:\/images\/icnBellRed.png);} *:checked{background-image:url();}\";\r\n\r\n m_graphWidget1 = new Widget(ui->graphECGWidget,this);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2 = new Widget(ui->graphABPWidget,this);\r\n m_graphWidget3 = new Widget(ui->graphPLETHWidget,this);\r\n#endif\r\n\r\n m_graphWidget1->initialized(GraphECG,3);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->initialized(GraphABP,1);\r\n m_graphWidget3->initialized(GraphPLETH,2);\r\n#endif\r\n\r\n m_selectedGraphWidget = NULL;\r\n\r\n \/\/ Set time\r\n updateTimeString();\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *timer = new QTimer(this);\r\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString()));\r\n timer->start(1000);\r\n\r\n m_timerAlarm =new QTimer (this);\r\n connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm()));\r\n m_timerAlarm->setInterval(500);\r\n m_timerAlarm->stop();\r\n\r\n m_timerDataValues = new QTimer(this);\r\n#ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH()));\r\n m_timerDataValues->setInterval(3000);\r\n #ifndef PMD_HAMP\r\n m_timerDataValues->start();\r\n #endif\r\n#endif\r\n\r\n m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68;\r\n m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119;\r\n m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79;\r\n m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99;\r\n\r\n m_cstatus=true;\r\n\r\n#ifdef PMD_MEHV\r\n m_nserver =new Server(this);\r\n m_cstatus=false;\r\n#endif\r\n\r\n#ifdef PMD_NUCLEUS\r\n m_dataSupplier=new DataSupplier(this);\r\n#endif\r\n\r\n#ifdef PMD_HAMP\r\n\tprintf(\"Creating HAMPDataSupplier\\n\");\r\n m_hampdataSupplier =new HAMPDataSupplier(this);\r\n m_cstatus=true;\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *hamptimer = new QTimer(this);\r\n connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort()));\r\n hamptimer->start(3000);\r\n\r\n#endif\r\n\r\n m_isPauseAll=false;\r\n m_isStart=true;\r\n m_isAlarmSilent=false;\r\n m_btnSilentPressed=false;\r\n\r\n m_graphSettingsPop =new GraphSettingsPopup(this);\r\n m_graphSettingsPop->hide();\r\n\r\n \/\/ Setup graph scrolling mode\r\n#ifdef ENABLE_GRAPH_SCROLLING\r\n on_pbtn_Scrolling_clicked(true);\r\n ui->pbtn_Scrolling->setChecked(true);\r\n#else\r\n on_pbtn_Scrolling_clicked(false);\r\n ui->pbtn_Scrolling->setChecked(false);\r\n#endif\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::updatePulse()\r\n{\r\n QString value=\"0\";\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n value.setNum(this->getPulseValue());\r\n }\r\n\r\n ui->labelPulse->setText(value);\r\n ui->labelPulse->repaint();\r\n}\r\n\r\nvoid MainWindow::updateABP()\r\n{\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelABP->setText(this->getABPValue());\r\n }\r\n else\r\n ui->labelABP->setText(\"0\/0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updatePLETH()\r\n{\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelSPO2->setText(this->getPLETHValue());\r\n }\r\n else\r\n ui->labelSPO2->setText(\"0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updateTimeString()\r\n{\r\n \/\/get current date and time\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mm:ss AP\");\r\n ui->labelTime->setText(dateTimeString);\r\n ui->labelTime->repaint();\r\n}\r\n\r\nint MainWindow::getPulseValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_HB_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n return m_HB_Simulate_Data[index];\r\n}\r\n\r\nQString MainWindow::getABPValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_ABP_Higher_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\/%2\").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nQString MainWindow::getPLETHValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_PLETH_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\").arg(m_PLETH_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Silent_clicked()\r\n{\r\n m_btnSilentPressed=!m_btnSilentPressed;\r\n if(m_btnSilentPressed)\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(true);\r\n ui->pbtn_ABP_Alarm->setChecked(true);\r\n ui->pbtn_spo2_Alarm->setChecked(true);\r\n m_isAlarmSilent=true;\r\n \/\/ ui->pbtn_Silent->setStyleSheet(\"*{border: 0px;background-image: url(:\/images\/btn_pressed.png);}\");\r\n }\r\n else\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(false);\r\n ui->pbtn_ABP_Alarm->setChecked(false);\r\n ui->pbtn_spo2_Alarm->setChecked(false);\r\n m_isAlarmSilent=false;\r\n \/\/ui->pbtn_Silent->setStyleSheet(\"\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_StartStop_clicked(bool checked)\r\n{\r\n\r\n#ifdef PMD_HAMP\r\n\r\n if(checked)\r\n {\r\n\t\tqDebug(\"MainWindow::on_pbtn_StartStop_clicked button pushed - %d\\n\", checked);\r\n m_isStart=false;\r\n m_timerDataValues->stop();\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=false;\r\n }\r\n else\r\n {\r\n\t\tqDebug(\"MainWindow::on_pbtn_StartStop_clicked button pushed - %d\\n\", checked);\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n m_timerDataValues->start();\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=true;\r\n\r\n }\r\n fflush(stdout);\r\n#else\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n }\r\n\r\n#endif\r\n\r\n}\r\n\r\nvoid MainWindow::on_pbtn_PauseAll_clicked(bool checked)\r\n{\r\n if(!checked)\r\n {\r\n m_isPauseAll=false;\r\n ui->pbtn_PauseAll->setText(\"Pause All\");\r\n }\r\n else\r\n {\r\n m_isPauseAll=true;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_PauseAll->setText(\"Start All\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Scrolling_clicked(bool checked)\r\n{\r\n (void)checked;\r\n#ifndef PMD_HAMP\r\n m_graphWidget1->setScrollingMode(checked);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->setScrollingMode(checked);\r\n m_graphWidget3->setScrollingMode(checked);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid MainWindow::updateTimer()\r\n{\r\n#ifdef PMD_MEHV\r\n pm_data_struct pm={0,0,0,0};\r\n dataReceived (&pm);\r\n#endif\r\n}\r\n\r\nvoid MainWindow::animateAlarm()\r\n{\r\n ui->pbtn_ABP_Alarm->toggle();\r\n ui->pbtn_ECG_Alarm->toggle();\r\n ui->pbtn_spo2_Alarm->toggle();\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::dataReceived(pm_data_struct *current)\r\n{\r\n\tqDebug(\"MainWindow::dataReceived: Entered\\n\");\r\n\tif (m_isPauseAll==false)\r\n {\r\n\t\tswitch(m_graphWidget1->getGraphType())\r\n {\r\n\r\n case GraphECG:\r\n m_graphWidget1->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget1->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget1->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n switch(m_graphWidget2->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget2->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget2->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget2->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n switch(m_graphWidget3->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget3->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget3->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget3->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n#endif\r\n }\r\n}\r\n\r\n#ifndef PMD_NUCLEUS\r\nvoid MainWindow::connectionStatus(bool status)\r\n{\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mmap\");\r\n m_cstatus=status;\r\n\r\n if(status)\r\n {\r\n ui->labelBulletText->setText(\"External system connected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(false);\r\n ui->pbtn_ECG_Alarm->setDisabled(false);\r\n ui->pbtn_spo2_Alarm->setDisabled(false);\r\n m_timerAlarm->stop();\r\n\r\n }\r\n else\r\n {\r\n ui->labelBulletText->setText(\"External system disconnected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(true);\r\n ui->pbtn_ECG_Alarm->setDisabled(true);\r\n ui->pbtn_spo2_Alarm->setDisabled(true);\r\n\r\n m_timerAlarm->start();\r\n updatePLETH();\r\n updateABP();\r\n updatePulse();\r\n }\r\n}\r\n#endif\r\n\r\nvoid MainWindow::launchGraphMenuPopup(Widget *widget)\r\n{\r\n if(m_graphSettingsPop->m_isVisible==false)\r\n {\r\n m_selectedGraphWidget=widget;\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n m_graphSettingsPop->show();\r\n }\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupOk()\r\n{\r\n if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize)\r\n {\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphABP:\r\n m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphPLETH:\r\n m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n }\r\n\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupCancel()\r\n{\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\n\r\n#ifdef PMD_HAMP\r\n\r\nvoid MainWindow::takeScreenSnapshort()\r\n{\r\n QRect r= this->rect();\r\n QPixmap pixmap=this->grab(r);\r\n QString fileName = m_hampdataSupplier->getScreenShortPath();\r\n\tQByteArray tmp_ba = fileName.toLatin1();\r\n\tconst char *tmp_mystr = tmp_ba.data();\r\n\r\n\tqDebug(\"MainWindow::takeScreenSnapshort - fileName %s\\n\", tmp_mystr);\r\n\r\n if(pixmap.isNull()==false)\r\n pixmap.save(fileName,\"PNG\");\r\n else\r\n printf(\"pixmap is NULL\\n\");\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <KFileItem>\n#include <KFileItemList>\n#include <KIO\/PreviewJob>\n\n#include <TelepathyQt4\/AccountManager>\n#include <TelepathyQt4\/PendingReady>\n\n\n#include \"accounts-model.h\"\n#include \"flat-model-proxy.h\"\n#include \"account-filter-model.h\"\n\n\nMainWindow::MainWindow(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::MainWindow)\n{\n Tp::registerTypes();\n\n ui->setupUi(this);\n\n KFileItem file(KUrl(\"\/home\/david\/a.png\"), \"image\/png\", KFileItem::Unknown);\n\n KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, ui->filePreviewLabel->size());\n\n ui->fileNameLabel->setText(file.name());\n ui->filePreviewLabel->setText(QString());\n\n connect(job, SIGNAL(gotPreview(KFileItem, QPixmap)),\n this, SLOT(showPreview(KFileItem, QPixmap)));\n connect(job, SIGNAL(failed(KFileItem)),\n this, SLOT(showIcon(KFileItem)));\n\n\n Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Account::FeatureCore\n << Tp::Account::FeatureAvatar\n << Tp::Account::FeatureProtocolInfo\n << Tp::Account::FeatureProfile);\n\n Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Connection::FeatureCore\n << Tp::Connection::FeatureRosterGroups\n << Tp::Connection::FeatureRoster\n << Tp::Connection::FeatureSelfContact);\n\n Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias\n << Tp::Contact::FeatureAvatarData\n << Tp::Contact::FeatureSimplePresence\n << Tp::Contact::FeatureCapabilities);\n\n Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());\n\n m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),\n accountFactory,\n connectionFactory,\n channelFactory,\n contactFactory);\n\n\n connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::showPreview(const KFileItem &file, const QPixmap &pixmap)\n{\n ui->filePreviewLabel->setMinimumSize(pixmap.size());\n ui->filePreviewLabel->setPixmap(pixmap);\n}\n\nvoid MainWindow::showIcon(const KFileItem &file)\n{\n \/\/icon is file.iconName();\n\n}\n\nvoid MainWindow::onAccountManagerReady()\n{\n AccountsModel *model = new AccountsModel(m_accountManager, this);\n FlatModelProxy *flatProxyModel = new FlatModelProxy(model);\n AccountFilterModel *filterModel = new AccountFilterModel(this);\n filterModel->setSourceModel(flatProxyModel);\n filterModel->filterOfflineUsers(true);\n ui->listView->setModel(filterModel);\n}\n<commit_msg>Fix the models by switching round the use of the flat model proxy and the filter proxy.<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <KFileItem>\n#include <KFileItemList>\n#include <KIO\/PreviewJob>\n\n#include <TelepathyQt4\/AccountManager>\n#include <TelepathyQt4\/PendingReady>\n\n\n#include \"accounts-model.h\"\n#include \"flat-model-proxy.h\"\n#include \"account-filter-model.h\"\n\n\nMainWindow::MainWindow(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::MainWindow)\n{\n Tp::registerTypes();\n\n ui->setupUi(this);\n\n KFileItem file(KUrl(\"\/home\/david\/a.png\"), \"image\/png\", KFileItem::Unknown);\n\n KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, ui->filePreviewLabel->size());\n\n ui->fileNameLabel->setText(file.name());\n ui->filePreviewLabel->setText(QString());\n\n connect(job, SIGNAL(gotPreview(KFileItem, QPixmap)),\n this, SLOT(showPreview(KFileItem, QPixmap)));\n connect(job, SIGNAL(failed(KFileItem)),\n this, SLOT(showIcon(KFileItem)));\n\n\n Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Account::FeatureCore\n << Tp::Account::FeatureAvatar\n << Tp::Account::FeatureProtocolInfo\n << Tp::Account::FeatureProfile);\n\n Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),\n Tp::Features() << Tp::Connection::FeatureCore\n << Tp::Connection::FeatureRosterGroups\n << Tp::Connection::FeatureRoster\n << Tp::Connection::FeatureSelfContact);\n\n Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias\n << Tp::Contact::FeatureAvatarData\n << Tp::Contact::FeatureSimplePresence\n << Tp::Contact::FeatureCapabilities);\n\n Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());\n\n m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),\n accountFactory,\n connectionFactory,\n channelFactory,\n contactFactory);\n\n\n connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::showPreview(const KFileItem &file, const QPixmap &pixmap)\n{\n ui->filePreviewLabel->setMinimumSize(pixmap.size());\n ui->filePreviewLabel->setPixmap(pixmap);\n}\n\nvoid MainWindow::showIcon(const KFileItem &file)\n{\n \/\/icon is file.iconName();\n\n}\n\nvoid MainWindow::onAccountManagerReady()\n{\n AccountsModel *model = new AccountsModel(m_accountManager, this);\n AccountFilterModel *filterModel = new AccountFilterModel(this);\n filterModel->setSourceModel(model);\n filterModel->filterOfflineUsers(true);\n FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel);\n\n ui->listView->setModel(flatProxyModel);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ffmpeg player output (portaudio)\n\/\/ part of MusicPlayer, https:\/\/github.com\/albertz\/music-player\n\/\/ Copyright (c) 2012, Albert Zeyer, www.az2000.de\n\/\/ All rights reserved.\n\/\/ This code is under the 2-clause BSD license, see License.txt in the root directory of this project.\n\n#include \"ffmpeg.h\"\n\n#include <portaudio.h>\n\n#ifdef __APPLE__\n\/\/ PortAudio specific Mac stuff\n#include \"pa_mac_core.h\"\n#endif\n\n\/\/ For setting the thread priority to realtime on MacOSX.\n#ifdef __APPLE__\n#include <mach\/mach_init.h>\n#include <mach\/thread_policy.h>\n#include <mach\/thread_act.h> \/\/ the doc says mach\/sched.h but that seems outdated...\n#include <pthread.h>\n#include <mach\/mach_error.h>\n#include <mach\/mach_time.h>\n#endif\nstatic void setRealtime();\n\n\n\n\nint initPlayerOutput() {\n\tPaError ret = Pa_Initialize();\n\tif(ret != paNoError)\n\t\tPy_FatalError(\"PortAudio init failed\");\n\treturn 0;\n}\n\ntemplate<typename T> struct OutPaSampleFormat{};\ntemplate<> struct OutPaSampleFormat<int16_t> {\n\tstatic const PaSampleFormat format = paInt16;\n};\ntemplate<> struct OutPaSampleFormat<float32_t> {\n\tstatic const PaSampleFormat format = paFloat32;\n};\n\n\nstruct PlayerObject::OutStream {\n\tPlayerObject* const player;\n\tPaStream* stream;\n\tbool needRealtimeReset; \/\/ PortAudio callback thread must set itself to realtime\n\n\tOutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {\n\t\tmlock(this, sizeof(*this));\n\t}\n\t~OutStream() { close(); }\n\n\tstatic int paStreamCallback(\n\t\tconst void *input, void *output,\n\t\tunsigned long frameCount,\n\t\tconst PaStreamCallbackTimeInfo* timeInfo,\n\t\tPaStreamCallbackFlags statusFlags,\n\t\tvoid *userData )\n\t{\n\t\tOutStream* outStream = (OutStream*) userData;\n\t\t\n\t\t\/\/ We must not hold the PyGIL here!\n\t\tPyScopedLock lock(outStream->player->lock);\n\t\t\n\t\tif(outStream->needRealtimeReset) {\n\t\t\toutStream->needRealtimeReset = false;\n\t\t\tsetRealtime();\n\t\t}\n\t\t\n\t\toutStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);\n\t\treturn paContinue;\n\t}\n\t\n\tbool open() {\n\t\tif(stream) close();\n\t\tassert(stream == NULL);\n\t\t\t\t\n\t\tPaStreamParameters outputParameters;\n\t\t\n#if defined(__APPLE__)\n\t\tPaMacCoreStreamInfo macInfo;\n\t\tPaMacCore_SetupStreamInfo( &macInfo,\n\t\t\tpaMacCorePlayNice | paMacCorePro );\n\t\toutputParameters.hostApiSpecificStreamInfo = &macInfo;\n#elif defined(__LINUX__)\n\t\t\/\/ TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,\n\t\t\/\/ we can call that to enable RT priority with ALSA.\n\t\t\/\/ We could check dynamically via dsym.\n\t\toutputParameters.hostApiSpecificStreamInfo = NULL;\n#else\n\t\toutputParameters.hostApiSpecificStreamInfo = NULL;\n#endif\n\t\t\n\t\toutputParameters.device = Pa_GetDefaultOutputDevice();\n\t\tif (outputParameters.device == paNoDevice) {\n\t\t\tPyErr_SetString(PyExc_RuntimeError, \"Pa_GetDefaultOutputDevice didn't returned a device\");\n\t\t\treturn false;\n\t\t}\n\t\toutputParameters.channelCount = player->outNumChannels;\n\t\toutputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;\n\t\toutputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;\n\t\t\n\t\t\/\/ Note about framesPerBuffer:\n\t\t\/\/ Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused\n\t\t\/\/ some random more or less rare cracking noises.\n\t\t\/\/ See here: https:\/\/github.com\/albertz\/music-player\/issues\/35\n\t\t\/\/ This doesn't seem to happen with paFramesPerBufferUnspecified.\n\t\t\n\t\tPaError ret = Pa_OpenStream(\n\t\t\t&stream,\n\t\t\tNULL, \/\/ no input\n\t\t\t&outputParameters,\n\t\t\tplayer->outSamplerate, \/\/ sampleRate\n\t\t\tpaFramesPerBufferUnspecified, \/\/ framesPerBuffer,\n\t\t\tpaClipOff | paDitherOff,\n\t\t\t&paStreamCallback,\n\t\t\tthis \/\/void *userData\n\t\t\t);\n\t\t\n\t\tif(ret != paNoError) {\n\t\t\tPyErr_Format(PyExc_RuntimeError, \"Pa_OpenStream failed: (err %i) %s\", ret, Pa_GetErrorText(ret));\n\t\t\tif(stream)\n\t\t\t\tclose();\n\t\t\treturn false;\n\t\t}\n\n\t\tneedRealtimeReset = true;\n\t\tPa_StartStream(stream);\n\t\treturn true;\n\t}\n\t\n\tvoid close() {\n\t\tif(this->stream == NULL) return;\n\t\t\/\/ we expect that we have the player lock here.\n\t\t\/\/ reset fader.\n\t\tplayer->fader.init(0,0);\n\t\t\/\/ we must release the player lock so that any thread-join can be done.\n\t\tPaStream* stream = NULL;\n\t\tstd::swap(stream, this->stream);\n\t\tPyScopedUnlock unlock(player->lock);\n\t\tPa_CloseStream(stream);\n\t}\n\t\n\tbool isOpen() const { return stream != NULL; }\n\t\n};\n\n\n\n\n\n\nint PlayerObject::setPlaying(bool playing) {\n\tPlayerObject* player = this;\n\tbool oldplayingstate = false;\n\tPyScopedGIL gil;\n\t{\n\t\tPyScopedGIUnlock gunlock;\n\t\t\n\t\tplayer->workerThread.start(); \/\/ if not running yet, start\n\t\tif(!player->outStream.get())\n\t\t\tplayer->outStream.reset(new OutStream(this));\n\t\tassert(player->outStream.get() != NULL);\n\t\t\n\t\tif(soundcardOutputEnabled) {\n\t\t\tif(playing && !player->outStream->stream) {\n\t\t\t\tif(!player->outStream->open())\n\t\t\t\t\tplaying = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\toldplayingstate = player->playing;\n\t\tif(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing)\n\t\t\tfader.init(playing ? 1 : -1, outSamplerate);\n\t\tplayer->playing = playing;\n\t}\n\t\n\tif(!PyErr_Occurred() && player->dict) {\n\t\tPy_INCREF(player->dict);\n\t\tPyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, \"onPlayingStateChange\");\n\t\tif(onPlayingStateChange && onPlayingStateChange != Py_None) {\n\t\t\tPy_INCREF(onPlayingStateChange);\n\t\t\t\n\t\t\tPyObject* kwargs = PyDict_New();\n\t\t\tassert(kwargs);\n\t\t\tPyDict_SetItemString_retain(kwargs, \"oldState\", PyBool_FromLong(oldplayingstate));\n\t\t\tPyDict_SetItemString_retain(kwargs, \"newState\", PyBool_FromLong(playing));\n\t\t\t\n\t\t\tPyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);\n\t\t\tPy_XDECREF(retObj);\n\t\t\t\n\t\t\t\/\/ errors are not fatal from the callback, so handle it now and go on\n\t\t\tif(PyErr_Occurred())\n\t\t\t\tPyErr_Print();\n\t\t\t\n\t\t\tPy_DECREF(kwargs);\n\t\t\tPy_DECREF(onPlayingStateChange);\n\t\t}\n\t\tPy_DECREF(player->dict);\n\t}\n\t\n\treturn PyErr_Occurred() ? -1 : 0;\n}\n\n\n\n#ifdef __APPLE__\n\/\/ https:\/\/developer.apple.com\/library\/mac\/#documentation\/Darwin\/Conceptual\/KernelProgramming\/scheduler\/scheduler.html\n\/\/ Also, from Google Native Client, osx\/nacl_thread_nice.c has some related code.\n\/\/ Or, from Google Chrome, platform_thread_mac.mm.\nvoid setRealtime() {\n\tkern_return_t ret;\n\tthread_port_t threadport = pthread_mach_thread_np(pthread_self());\n\t\n\tthread_extended_policy_data_t policy;\n\tpolicy.timeshare = 0;\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_EXTENDED_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&policy,\n\t\t\t\t\t\t\tTHREAD_EXTENDED_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n\t\n\tthread_precedence_policy_data_t precedence;\n\tprecedence.importance = 63;\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_PRECEDENCE_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&precedence,\n\t\t\t\t\t\t\tTHREAD_PRECEDENCE_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n\t\n\tmach_timebase_info_data_t tb_info;\n\tmach_timebase_info(&tb_info);\n\tdouble timeFact = ((double)tb_info.denom \/ (double)tb_info.numer) * 1000000;\n\t\n\tthread_time_constraint_policy_data_t ttcpolicy;\n\tttcpolicy.period = 2.9 * timeFact; \/\/ about 128 frames @44.1KHz\n\tttcpolicy.computation = 0.75 * 2.9 * timeFact;\n\tttcpolicy.constraint = 0.85 * 2.9 * timeFact;\n\tttcpolicy.preemptible = 1;\n\t\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_TIME_CONSTRAINT_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&ttcpolicy,\n\t\t\t\t\t\t\tTHREAD_TIME_CONSTRAINT_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n}\n#else\nvoid setRealtime() {} \/\/ not implemented yet\n#endif\n\n\n\n<commit_msg>portaudio blocking implementation<commit_after>\/\/ ffmpeg player output (portaudio)\n\/\/ part of MusicPlayer, https:\/\/github.com\/albertz\/music-player\n\/\/ Copyright (c) 2012, Albert Zeyer, www.az2000.de\n\/\/ All rights reserved.\n\/\/ This code is under the 2-clause BSD license, see License.txt in the root directory of this project.\n\n#include \"ffmpeg.h\"\n\n#include <portaudio.h>\n#include <boost\/bind.hpp>\n\n#ifdef __APPLE__\n\/\/ PortAudio specific Mac stuff\n#include \"pa_mac_core.h\"\n#endif\n\n\/\/ For setting the thread priority to realtime on MacOSX.\n#ifdef __APPLE__\n#include <mach\/mach_init.h>\n#include <mach\/thread_policy.h>\n#include <mach\/thread_act.h> \/\/ the doc says mach\/sched.h but that seems outdated...\n#include <pthread.h>\n#include <mach\/mach_error.h>\n#include <mach\/mach_time.h>\n#endif\nstatic void setRealtime();\n\n#define USE_PORTAUDIO_CALLBACK 0\n\n\nint initPlayerOutput() {\n\tPaError ret = Pa_Initialize();\n\tif(ret != paNoError)\n\t\tPy_FatalError(\"PortAudio init failed\");\n\treturn 0;\n}\n\ntemplate<typename T> struct OutPaSampleFormat{};\ntemplate<> struct OutPaSampleFormat<int16_t> {\n\tstatic const PaSampleFormat format = paInt16;\n};\ntemplate<> struct OutPaSampleFormat<float32_t> {\n\tstatic const PaSampleFormat format = paFloat32;\n};\n\n\nstruct PlayerObject::OutStream {\n\tPlayerObject* const player;\n\tPaStream* stream;\n\tbool needRealtimeReset; \/\/ PortAudio callback thread must set itself to realtime\n\n\tOutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {\n\t\tmlock(this, sizeof(*this));\n\t}\n\t~OutStream() { close(); }\n\n#if USE_PORTAUDIO_CALLBACK\n\tstatic int paStreamCallback(\n\t\tconst void *input, void *output,\n\t\tunsigned long frameCount,\n\t\tconst PaStreamCallbackTimeInfo* timeInfo,\n\t\tPaStreamCallbackFlags statusFlags,\n\t\tvoid *userData )\n\t{\n\t\tOutStream* outStream = (OutStream*) userData;\n\t\t\n\t\t\/\/ We must not hold the PyGIL here!\n\t\tPyScopedLock lock(outStream->player->lock);\n\t\t\n\t\tif(outStream->needRealtimeReset) {\n\t\t\toutStream->needRealtimeReset = false;\n\t\t\tsetRealtime();\n\t\t}\n\t\t\n\t\toutStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);\n\t\treturn paContinue;\n\t}\n#else\n\tPyThread audioThread;\n\tvoid audioThreadProc(PyMutex& threadLock, bool& stopSignal) {\n\t\twhile(true) {\n\t\t\t{\n\t\t\t\tPyScopedLock l(threadLock);\n\t\t\t\tif(stopSignal) return;\n\t\t\t}\n\n\t\t\tif(needRealtimeReset) {\n\t\t\t\tneedRealtimeReset = false;\n\t\t\t\tsetRealtime();\n\t\t\t}\n\t\t\t\n\t\t\tOUTSAMPLE_t buffer[4800 * 2]; \/\/ 100ms stereo in 48khz\n\t\t\tsize_t sampleNumOut = 0;\n\t\t\t{\n\t\t\t\tPyScopedLock lock(player->lock);\n\t\t\t\tif(stopSignal) return;\n\t\t\t\tplayer->readOutStream(buffer, sizeof(buffer)\/sizeof(OUTSAMPLE_t), NULL);\n\t\t\t}\n\t\t\t\n\t\t\tPaError ret = Pa_WriteStream(stream, buffer, sampleNumOut);\n\t\t\tif(ret == paOutputUnderflowed)\n\t\t\t\tprintf(\"warning: paOutputUnderflowed\\n\");\n\t\t}\n\t}\n#endif\n\n\tbool open() {\n\t\tif(stream) close();\n\t\tassert(stream == NULL);\n\t\t\t\t\n\t\tPaStreamParameters outputParameters;\n\t\t\n#if defined(__APPLE__)\n\t\tPaMacCoreStreamInfo macInfo;\n\t\tPaMacCore_SetupStreamInfo( &macInfo,\n\t\t\tpaMacCorePlayNice | paMacCorePro );\n\t\toutputParameters.hostApiSpecificStreamInfo = &macInfo;\n#elif defined(__LINUX__)\n\t\t\/\/ TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,\n\t\t\/\/ we can call that to enable RT priority with ALSA.\n\t\t\/\/ We could check dynamically via dsym.\n\t\toutputParameters.hostApiSpecificStreamInfo = NULL;\n#else\n\t\toutputParameters.hostApiSpecificStreamInfo = NULL;\n#endif\n\t\t\n\t\toutputParameters.device = Pa_GetDefaultOutputDevice();\n\t\tif (outputParameters.device == paNoDevice) {\n\t\t\tPyErr_SetString(PyExc_RuntimeError, \"Pa_GetDefaultOutputDevice didn't returned a device\");\n\t\t\treturn false;\n\t\t}\n\t\toutputParameters.channelCount = player->outNumChannels;\n\t\toutputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;\n\t\toutputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;\n\t\t\n\t\t\/\/ Note about framesPerBuffer:\n\t\t\/\/ Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused\n\t\t\/\/ some random more or less rare cracking noises.\n\t\t\/\/ See here: https:\/\/github.com\/albertz\/music-player\/issues\/35\n\t\t\/\/ This doesn't seem to happen with paFramesPerBufferUnspecified.\n\t\t\n\t\tPaError ret = Pa_OpenStream(\n\t\t\t&stream,\n\t\t\tNULL, \/\/ no input\n\t\t\t&outputParameters,\n\t\t\tplayer->outSamplerate, \/\/ sampleRate\n\t\t\tpaFramesPerBufferUnspecified, \/\/ framesPerBuffer,\n\t\t\tpaClipOff | paDitherOff,\n#if USE_PORTAUDIO_CALLBACK\n\t\t\t&paStreamCallback,\n#else\n\t\t\tNULL,\n#endif\n\t\t\tthis \/\/void *userData\n\t\t\t);\n\t\t\n\t\tif(ret != paNoError) {\n\t\t\tPyErr_Format(PyExc_RuntimeError, \"Pa_OpenStream failed: (err %i) %s\", ret, Pa_GetErrorText(ret));\n\t\t\tif(stream)\n\t\t\t\tclose();\n\t\t\treturn false;\n\t\t}\n\n\t\tneedRealtimeReset = true;\n\t\tPa_StartStream(stream);\n\n#if !USE_PORTAUDIO_CALLBACK\n\t\taudioThread.func = boost::bind(&OutStream::audioThreadProc, this, _1, _2);\n\t\taudioThread.start();\n#endif\n\t\treturn true;\n\t}\n\t\n\tvoid close() {\n\t\tif(this->stream == NULL) return;\n\t\t\/\/ we expect that we have the player lock here.\n\t\t\/\/ reset fader.\n\t\tplayer->fader.init(0,0);\n\t\t\/\/ we must release the player lock so that any thread-join can be done.\n\t\tPaStream* stream = NULL;\n\t\tstd::swap(stream, this->stream);\n\t\tPyScopedUnlock unlock(player->lock);\n\t\taudioThread.stop();\n\t\tPa_CloseStream(stream);\n\t}\n\t\n\tbool isOpen() const { return stream != NULL; }\n\t\n};\n\n\n\n\n\n\nint PlayerObject::setPlaying(bool playing) {\n\tPlayerObject* player = this;\n\tbool oldplayingstate = false;\n\tPyScopedGIL gil;\n\t{\n\t\tPyScopedGIUnlock gunlock;\n\t\t\n\t\tplayer->workerThread.start(); \/\/ if not running yet, start\n\t\tif(!player->outStream.get())\n\t\t\tplayer->outStream.reset(new OutStream(this));\n\t\tassert(player->outStream.get() != NULL);\n\t\t\n\t\tif(soundcardOutputEnabled) {\n\t\t\tif(playing && !player->outStream->stream) {\n\t\t\t\tif(!player->outStream->open())\n\t\t\t\t\tplaying = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\toldplayingstate = player->playing;\n\t\tif(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing)\n\t\t\tfader.init(playing ? 1 : -1, outSamplerate);\n\t\tplayer->playing = playing;\n\t}\n\t\n\tif(!PyErr_Occurred() && player->dict) {\n\t\tPy_INCREF(player->dict);\n\t\tPyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, \"onPlayingStateChange\");\n\t\tif(onPlayingStateChange && onPlayingStateChange != Py_None) {\n\t\t\tPy_INCREF(onPlayingStateChange);\n\t\t\t\n\t\t\tPyObject* kwargs = PyDict_New();\n\t\t\tassert(kwargs);\n\t\t\tPyDict_SetItemString_retain(kwargs, \"oldState\", PyBool_FromLong(oldplayingstate));\n\t\t\tPyDict_SetItemString_retain(kwargs, \"newState\", PyBool_FromLong(playing));\n\t\t\t\n\t\t\tPyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);\n\t\t\tPy_XDECREF(retObj);\n\t\t\t\n\t\t\t\/\/ errors are not fatal from the callback, so handle it now and go on\n\t\t\tif(PyErr_Occurred())\n\t\t\t\tPyErr_Print();\n\t\t\t\n\t\t\tPy_DECREF(kwargs);\n\t\t\tPy_DECREF(onPlayingStateChange);\n\t\t}\n\t\tPy_DECREF(player->dict);\n\t}\n\t\n\treturn PyErr_Occurred() ? -1 : 0;\n}\n\n\n\n#ifdef __APPLE__\n\/\/ https:\/\/developer.apple.com\/library\/mac\/#documentation\/Darwin\/Conceptual\/KernelProgramming\/scheduler\/scheduler.html\n\/\/ Also, from Google Native Client, osx\/nacl_thread_nice.c has some related code.\n\/\/ Or, from Google Chrome, platform_thread_mac.mm.\nvoid setRealtime() {\n\tkern_return_t ret;\n\tthread_port_t threadport = pthread_mach_thread_np(pthread_self());\n\t\n\tthread_extended_policy_data_t policy;\n\tpolicy.timeshare = 0;\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_EXTENDED_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&policy,\n\t\t\t\t\t\t\tTHREAD_EXTENDED_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n\t\n\tthread_precedence_policy_data_t precedence;\n\tprecedence.importance = 63;\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_PRECEDENCE_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&precedence,\n\t\t\t\t\t\t\tTHREAD_PRECEDENCE_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n\t\n\tmach_timebase_info_data_t tb_info;\n\tmach_timebase_info(&tb_info);\n\tdouble timeFact = ((double)tb_info.denom \/ (double)tb_info.numer) * 1000000;\n\t\n\tthread_time_constraint_policy_data_t ttcpolicy;\n\tttcpolicy.period = 2.9 * timeFact; \/\/ about 128 frames @44.1KHz\n\tttcpolicy.computation = 0.75 * 2.9 * timeFact;\n\tttcpolicy.constraint = 0.85 * 2.9 * timeFact;\n\tttcpolicy.preemptible = 1;\n\t\n\tret = thread_policy_set(threadport,\n\t\t\t\t\t\t\tTHREAD_TIME_CONSTRAINT_POLICY,\n\t\t\t\t\t\t\t(thread_policy_t)&ttcpolicy,\n\t\t\t\t\t\t\tTHREAD_TIME_CONSTRAINT_POLICY_COUNT);\n\tif(ret != KERN_SUCCESS) {\n\t\tfprintf(stderr, \"setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\\n\", ret, mach_error_string(ret));\n\t\treturn;\n\t}\n}\n#else\nvoid setRealtime() {} \/\/ not implemented yet\n#endif\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_OPENSL\n\n#include \"AudioDeviceSL.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n\nstatic void playerCallback(SLAndroidSimpleBufferQueueItf bufferQueue, void* context)\n{\n try\n {\n ouzel::audio::AudioDeviceSL* audioDeviceSL = reinterpret_cast<ouzel::audio::AudioDeviceSL*>(context);\n\n audioDeviceSL->enqueue(bufferQueue);\n }\n catch (const std::exception& e)\n {\n ouzel::engine->log(ouzel::Log::Level::ERR) << e.what();\n }\n}\n\nnamespace ouzel\n{\n namespace audio\n {\n AudioDeviceSL::AudioDeviceSL():\n AudioDevice(Driver::OPENSL)\n {\n const SLuint32 engineMixIIDCount = 1;\n const SLInterfaceID engineMixIID = SL_IID_ENGINE;\n const SLboolean engineMixReq = SL_BOOLEAN_TRUE;\n\n if (slCreateEngine(&engineObject, 0, nullptr, engineMixIIDCount, &engineMixIID, &engineMixReq) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL engine object\");\n\n if ((*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL engine object\");\n\n if ((*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engine) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL engine\");\n\n if ((*engine)->CreateOutputMix(engine, &outputMixObject, 0, nullptr, nullptr) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL output mix\");\n\n if ((*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL output mix\");\n\n SLDataLocator_AndroidSimpleBufferQueue location = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};\n\n SLDataFormat_PCM dataFormat;\n dataFormat.formatType = SL_DATAFORMAT_PCM;\n dataFormat.numChannels = channels;\n dataFormat.samplesPerSec = sampleRate * 1000; \/\/mHz\n dataFormat.bitsPerSample = 16;\n dataFormat.containerSize = dataFormat.bitsPerSample;\n\n switch (channels)\n {\n case 1: dataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; break;\n case 2: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; break;\n case 4: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT; break;\n case 6: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; break;\n case 7: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;\n case 8: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;\n default:\n throw SystemError(\"Invalid channel count\");\n }\n\n dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;\n\n SLDataSource dataSource = {&location, &dataFormat};\n\n SLDataLocator_OutputMix dataLocatorOut;\n dataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX;\n dataLocatorOut.outputMix = outputMixObject;\n\n SLDataSink dataSink;\n dataSink.pLocator = &dataLocatorOut;\n dataSink.pFormat = nullptr;\n\n const SLuint32 playerIIDCount = 3;\n const SLInterfaceID playerIIDs[] = {SL_IID_BUFFERQUEUE, SL_IID_PLAY, SL_IID_VOLUME};\n const SLboolean playerReqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};\n\n if ((*engine)->CreateAudioPlayer(engine, &playerObject, &dataSource, &dataSink, playerIIDCount, playerIIDs, playerReqs) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL player object\");\n\n sampleFormat = SampleFormat::SINT16;\n\n if ((*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL player object\");\n\n if ((*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &player) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL player interface\");\n\n if ((*playerObject)->GetInterface(playerObject, SL_IID_BUFFERQUEUE, &bufferQueue) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL buffer queue interface\");\n\n if ((*playerObject)->GetInterface(playerObject, SL_IID_VOLUME, &playerVolume) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL volume interface\");\n\n if ((*bufferQueue)->Clear(bufferQueue) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to clear OpenSL buffer\");\n\n if ((*bufferQueue)->RegisterCallback(bufferQueue, playerCallback, this) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to register OpenSL buffer queue callback\");\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n if ((*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size()) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to enqueue OpenSL data\");\n\n if ((*player)->SetPlayState(player, SL_PLAYSTATE_PLAYING) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to play sound\");\n }\n\n AudioDeviceSL::~AudioDeviceSL()\n {\n if (playerObject)\n (*playerObject)->Destroy(playerObject);\n\n if (outputMixObject)\n (*outputMixObject)->Destroy(outputMixObject);\n\n if (engineObject)\n (*engineObject)->Destroy(engineObject);\n }\n\n void AudioDeviceSL::enqueue(SLAndroidSimpleBufferQueueItf bufferQueue)\n {\n process();\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n if ((*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size()) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to enqueue OpenSL data\");\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\n<commit_msg>Print OpenSL error codes<commit_after>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_COMPILE_OPENSL\n\n#include \"AudioDeviceSL.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n\nstatic void playerCallback(SLAndroidSimpleBufferQueueItf bufferQueue, void* context)\n{\n try\n {\n ouzel::audio::AudioDeviceSL* audioDeviceSL = reinterpret_cast<ouzel::audio::AudioDeviceSL*>(context);\n\n audioDeviceSL->enqueue(bufferQueue);\n }\n catch (const std::exception& e)\n {\n ouzel::engine->log(ouzel::Log::Level::ERR) << e.what();\n }\n}\n\nnamespace ouzel\n{\n namespace audio\n {\n AudioDeviceSL::AudioDeviceSL():\n AudioDevice(Driver::OPENSL)\n {\n SLresult result;\n const SLuint32 engineMixIIDCount = 1;\n const SLInterfaceID engineMixIID = SL_IID_ENGINE;\n const SLboolean engineMixReq = SL_BOOLEAN_TRUE;\n\n if ((result = slCreateEngine(&engineObject, 0, nullptr, engineMixIIDCount, &engineMixIID, &engineMixReq)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL engine object, error: \" + std::to_string(result));\n\n if ((result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL engine object, error: \" + std::to_string(result));\n\n if ((result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engine)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL engine, error: \" + std::to_string(result));\n\n if ((result = (*engine)->CreateOutputMix(engine, &outputMixObject, 0, nullptr, nullptr)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL output mix, error: \" + std::to_string(result));\n\n if ((result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL output mix, error: \" + std::to_string(result));\n\n SLDataLocator_AndroidSimpleBufferQueue location = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};\n\n SLDataFormat_PCM dataFormat;\n dataFormat.formatType = SL_DATAFORMAT_PCM;\n dataFormat.numChannels = channels;\n dataFormat.samplesPerSec = sampleRate * 1000; \/\/mHz\n dataFormat.bitsPerSample = 16;\n dataFormat.containerSize = dataFormat.bitsPerSample;\n\n switch (channels)\n {\n case 1: dataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; break;\n case 2: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; break;\n case 4: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT; break;\n case 6: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; break;\n case 7: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;\n case 8: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;\n default:\n throw SystemError(\"Invalid channel count\");\n }\n\n dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;\n\n SLDataSource dataSource = {&location, &dataFormat};\n\n SLDataLocator_OutputMix dataLocatorOut;\n dataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX;\n dataLocatorOut.outputMix = outputMixObject;\n\n SLDataSink dataSink;\n dataSink.pLocator = &dataLocatorOut;\n dataSink.pFormat = nullptr;\n\n const SLuint32 playerIIDCount = 3;\n const SLInterfaceID playerIIDs[] = {SL_IID_BUFFERQUEUE, SL_IID_PLAY, SL_IID_VOLUME};\n const SLboolean playerReqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};\n\n if ((result = (*engine)->CreateAudioPlayer(engine, &playerObject, &dataSource, &dataSink, playerIIDCount, playerIIDs, playerReqs)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL player object, error: \" + std::to_string(result));\n\n sampleFormat = SampleFormat::SINT16;\n\n if ((result = (*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to create OpenSL player object, error: \" + std::to_string(result));\n\n if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &player)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL player interface, error: \" + std::to_string(result));\n\n if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_BUFFERQUEUE, &bufferQueue)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL buffer queue interface, error: \" + std::to_string(result));\n\n if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_VOLUME, &playerVolume)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to get OpenSL volume interface, error: \" + std::to_string(result));\n\n if ((result = (*bufferQueue)->Clear(bufferQueue)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to clear OpenSL buffer, error: \" + std::to_string(result));\n\n if ((result = (*bufferQueue)->RegisterCallback(bufferQueue, playerCallback, this)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to register OpenSL buffer queue callback, error: \" + std::to_string(result));\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n if ((result = (*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size())) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to enqueue OpenSL data, error: \" + std::to_string(result));\n\n if ((result = (*player)->SetPlayState(player, SL_PLAYSTATE_PLAYING)) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to play sound, error: \" + std::to_string(result));\n }\n\n AudioDeviceSL::~AudioDeviceSL()\n {\n if (playerObject)\n (*playerObject)->Destroy(playerObject);\n\n if (outputMixObject)\n (*outputMixObject)->Destroy(outputMixObject);\n\n if (engineObject)\n (*engineObject)->Destroy(engineObject);\n }\n\n void AudioDeviceSL::enqueue(SLAndroidSimpleBufferQueueItf bufferQueue)\n {\n process();\n\n getData(bufferSize \/ (channels * sizeof(int16_t)), data);\n\n SLresult result;\n if ((result = (*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size())) != SL_RESULT_SUCCESS)\n throw SystemError(\"Failed to enqueue OpenSL data, error: \" + std::to_string(result));\n }\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\n#include <cmath>\n#include <complex>\n#include <ctime>\n#include <chrono>\n#include <cassert>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <omp.h>\n#include <sched.h>\n\n#include <mpi.h>\n\n#include <thread>\n#include <stdlib.h>\n\n#include \"talshxx.hpp\"\n#ifdef _51q\n#include \"contraction_51q.h\"\n#endif\n#ifdef _bris_60\n#include \"contraction_bris_60.h\"\n#endif\n#ifdef _7x7x40\n#include \"contraction_7x7x40.h\"\n#endif\n#ifdef _8x8x32\n#include \"contraction_8x8x32.h\"\n#endif\n\nusing namespace std;\nusing namespace chrono;\n\n\nint main(int argc, char *argv[]) {\n\n\n \/\/ Three things to take as arguments: input file, output file, number of\n \/\/ amplitudes.\n\n\n \/\/ MPI\n \/\/ Initialize the MPI environment\n MPI_Init(NULL, NULL);\n\n \/\/ Get number of precesses\n int world_size;\n MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n \/\/ Get the rank of the processes\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ Get the name of the processor\n char processor_name[MPI_MAX_PROCESSOR_NAME];\n int name_len;\n MPI_Get_processor_name(processor_name, &name_len);\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Read input parameters\n if (argc<5) throw logic_error(\"ERROR: Not enough arguments.\");\n string in_filename = string(argv[1]);\n string out_filename = string(argv[2]);\n int mem_size_GB = atoi(argv[3]);\n unsigned long mem_size = mem_size_GB * size_t(1000000000);\n int num_entries = atoi(argv[4]); \/\/ How many entries from input file to run\n\n\n \/\/ Timing variables.\n high_resolution_clock::time_point t0, t1;\n high_resolution_clock::time_point t0_init_total, t0_total, t1_total;\n duration<double> span_total;\n t0 = high_resolution_clock::now();\n\n \/\/ Start here\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Process 0\n if (rank==0)\n {\n\n int entries_left = num_entries;\n vector<MPI_Request> requests(world_size, MPI_REQUEST_NULL);\n vector<string> parameter_strings(world_size);\n vector<string> input_strings(world_size);\n\n \/\/ Written?\n vector<bool> written(world_size, false);\n \/\/ Input lines\n vector<string> input_lines(num_entries);\n\n \/\/ Output file\n ofstream out_file(out_filename);\n out_file.precision(7);\n\n \/\/ Input variables (from file)\n \/\/ Open file\n auto in_file = ifstream(in_filename);\n assert(in_file.good() && \"Cannot open file.\");\n \/\/ Gotten from the file.\n \/\/ Number of arguments per amplitude and number of amplitudes per line\n int num_args, num_amps; \n \/\/ The first element should be the number of arguments per line\n in_file >> num_args;\n in_file >> num_amps;\n int batch_size = num_args-2;\n\n \/\/ Grab lines one by one\n string line;\n getline(in_file, line); \/\/ \"Read\" one line to start next from the second.\n \/\/ Send num_args\n for (int p=1; p<world_size; ++p)\n {\n MPI_Send(vector<int>({num_args,num_amps}).data(), 2, MPI_INT, p, 0,\n MPI_COMM_WORLD);\n }\n \/\/ Send second line with metadata\n if (getline(in_file, line)) if (line.size() && line[0] != '#')\n {\n for (int p=1; p<world_size; ++p)\n {\n MPI_Send(line.c_str(), line.size(), MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n parameter_strings[p] = line;\n }\n }\n\n \/\/ Read all other lines\n t0 = high_resolution_clock::now();\n int line_idx = 0;\n while (getline(in_file, line) && line_idx<num_entries) if (line.size() && line[0] != '#')\n {\n input_lines[line_idx] = line;\n ++line_idx;\n }\n in_file.close();\n line_idx = 0;\n t1 = high_resolution_clock::now();\n duration<double> span = duration_cast<duration<double>>(t1 - t0);\n cout << \"Reading took \" << span.count() << endl;\n\n \/\/ Set up for messages and storage\n vector<s_type> amplitudes_out(batch_size*num_amps*num_entries);\n vector<int> tasks_out(num_entries);\n vector<double> peak_times_out(num_entries);\n vector<string> input_strings_out(num_entries);\n int idx_entry = 0;\n \/\/ amplitudes buffer. +1 is to receive the time_largest_contraction.\n vector<s_type> amplitudes_buffer((batch_size*num_amps+1)*world_size);\n\n \/\/ BEGIN TIMER\n \/\/\/\/\/\/ MEASURE BEGIN TIMER\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Initializing started at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n t0_init_total = high_resolution_clock::now();\n }\n \/\/\/\/\/\/ END MEASURE BEGIN TIMER\n\n\n \/\/ Send messages\n while (entries_left>0)\n {\n for (int p=1; p<world_size; ++p)\n {\n if (entries_left<=0) break;\n int flag = true;\n if (requests[p]!=MPI_REQUEST_NULL) \/\/ First time is flag=true;\n {\n MPI_Request_get_status(requests[p], &flag, MPI_STATUS_IGNORE);\n if (flag)\n {\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n amplitudes_out[batch_size*num_amps*idx_entry+a] =\n amplitudes_buffer[(batch_size*num_amps+1)*p+a];\n }\n \/\/ Populate out vectors\n tasks_out[idx_entry] = p;\n input_strings_out[idx_entry] = input_strings[p];\n peak_times_out[idx_entry] =\n (double)amplitudes_buffer[(batch_size*num_amps+1)*(p+1)-1].real();\n ++idx_entry;\n \n written[p] = true;\n }\n }\n if (flag)\n {\n line = input_lines[line_idx];\n ++line_idx;\n {\n MPI_Send(line.c_str(), line.size(), MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n \n written[p] = false;\n input_strings[p] = line;\n --entries_left;\n \/\/ Time\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n \/\/ Time\n \/\/cout << span.count() << \"s. Sent batch to process \" << p\n \/\/ << \". Entries left = \" << entries_left << \"\\n\";\n MPI_Irecv(amplitudes_buffer.data()+(batch_size*num_amps+1)*(p),\n batch_size*num_amps+1, MPI_COMPLEX, p, 0,\n MPI_COMM_WORLD, &requests[p]);\n }\n }\n }\n }\n\n \/\/ Clean up\n for (int p=1; p<world_size; ++p)\n {\n int flag;\n MPI_Request_get_status(requests[p], &flag, MPI_STATUS_IGNORE);\n if (!flag || !written[p])\n {\n MPI_Wait(&requests[p], MPI_STATUS_IGNORE);\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n amplitudes_out[batch_size*num_amps*idx_entry+a] =\n amplitudes_buffer[(batch_size*num_amps+1)*p+a];\n }\n\n \/\/ Populate out vectors\n tasks_out[idx_entry] = p;\n input_strings_out[idx_entry] = input_strings[p];\n peak_times_out[idx_entry] =\n (double)amplitudes_buffer[(batch_size*num_amps+1)*(p+1)-1].real();\n ++idx_entry;\n\n written[p] = true;\n }\n \/\/ Send a dummy pointer to show that the we are done!\n MPI_Send(NULL, 0, MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n }\n\n \/\/ END TIMER\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Computation ended at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n }\n t1_total = high_resolution_clock::now();\n span_total = duration_cast<duration<double>>(t1_total - t0_init_total);\n double total_time = span_total.count();\n cout << \"Total time (s): \" << total_time << endl;\n\n \/\/ Write everything to file\n t0 = high_resolution_clock::now();\n out_file << \"\\n---------- BEGIN OUTPUT ------------\\n\";\n out_file << \"\\nTotal time (s): \" << total_time << \"\\n\\n\" << endl;\n for (int l=0; l<tasks_out.size(); ++l)\n {\n out_file << \"\\nProcess \" << tasks_out[l]\n << \": \" << parameter_strings[tasks_out[l]] << \"\\n\"\n << \"Peak time (s): \" << peak_times_out[l] << \"\\n\"\n << input_strings_out[l] << \"\\n\";\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n out_file << amplitudes_out[batch_size*num_amps*l+a].real()\n << \" \"<< amplitudes_out[batch_size*num_amps*l+a].imag()\n << \" \";\n }\n out_file << \"\\n\";\n }\n out_file << \"\\n------------ END OUTPUT ------------\\n\" << flush;\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n cout << \"Writing took \" << span.count() << endl;\n\n \/\/ Close files\n out_file.close();\n\n \/\/ Report total time\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n \/\/cout << \"Total time = \" << span.count() << endl;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Process > 0\n else\n {\n MPI_Status status;\n int length;\n string local_line;\n vector<s_type> amplitudes;\n double time_largest_contraction;\n vector<s_type> amplitudes_p_time;\n double amplitude = 0.0;\n int num_args;\n int num_amps;\n\n \/\/ get num_args\n vector<int> num_args_amps(2);\n MPI_Recv(num_args_amps.data(), 2, MPI_INT, 0, 0,\n MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n num_args = num_args_amps[0];\n num_amps = num_args_amps[1];\n \/\/ Get first string\n MPI_Probe(0, 0, MPI_COMM_WORLD, &status);\n MPI_Get_count(&status, MPI_CHAR, &length);\n char * char_ptr = new char[length];\n MPI_Recv(char_ptr, length, MPI_INT, 0, 0, MPI_COMM_WORLD,\n MPI_STATUS_IGNORE);\n local_line = string(char_ptr);\n delete[] char_ptr;\n char_ptr = nullptr;\n\n talsh::initialize(&mem_size);\n {\n Contraction contraction(local_line, num_args, num_amps);\n \/\/\/\/\/\/ MEASURE COMPUTATION BEGIN TIMER\n if (rank==1)\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Rank 1 compuatation started at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n }\n \/\/\/\/\/\/ END MEASURE COMPUTATION BEGIN TIMER\n \/\/cout << mem_size << endl << flush;\n\n bool load_circuit(true);\n t0 = high_resolution_clock::now();\n while (true)\n {\n \/\/ Start timer\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Get string\n MPI_Probe(0, 0, MPI_COMM_WORLD, &status);\n MPI_Get_count(&status, MPI_CHAR, &length);\n char_ptr = new char[length];\n if (length==0) break;\n MPI_Recv(char_ptr, length, MPI_INT, 0, 0, MPI_COMM_WORLD,\n MPI_STATUS_IGNORE);\n local_line = string(char_ptr);\n delete[] char_ptr;\n char_ptr = nullptr;\n\n \/\/ Computation\n if (load_circuit) \/\/ load only once\n {\n contraction.load_circuit(local_line);\n load_circuit = false;\n }\n contraction.contract(local_line);\n t1 = high_resolution_clock::now();\n duration<double> span = duration_cast<duration<double>>(t1 - t0);\n t0 = high_resolution_clock::now();\n \/\/cout << \"A round took \" << span.count() << \"s\" << endl;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Message back\n amplitudes = contraction.get_amplitudes();\n time_largest_contraction = contraction.get_time_largest_contraction();\n amplitudes_p_time = vector<s_type>(amplitudes);\n amplitudes_p_time.push_back(s_type(time_largest_contraction));\n MPI_Send(amplitudes_p_time.data(), amplitudes_p_time.size(),\n MPI_COMPLEX, 0, 0, MPI_COMM_WORLD);\n }\n }\n talsh::shutdown();\n\n }\n\n \/\/ Finalize the MPI environment.\n MPI_Finalize();\n\n return 0;\n} \n<commit_msg>Added barriers to measure time correctly between talsh::initialize() and talsh::shutdown()<commit_after>#include <vector>\n#include <string>\n#include <cmath>\n#include <complex>\n#include <ctime>\n#include <chrono>\n#include <cassert>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <omp.h>\n#include <sched.h>\n\n#include <mpi.h>\n\n#include <thread>\n#include <stdlib.h>\n\n#include \"talshxx.hpp\"\n#ifdef _51q\n#include \"contraction_51q.h\"\n#endif\n#ifdef _bris_60\n#include \"contraction_bris_60.h\"\n#endif\n#ifdef _7x7x40\n#include \"contraction_7x7x40.h\"\n#endif\n#ifdef _8x8x32\n#include \"contraction_8x8x32.h\"\n#endif\n\nusing namespace std;\nusing namespace chrono;\n\n\nint main(int argc, char *argv[]) {\n\n\n \/\/ Three things to take as arguments: input file, output file, number of\n \/\/ amplitudes.\n\n\n \/\/ MPI\n \/\/ Initialize the MPI environment\n MPI_Init(NULL, NULL);\n\n \/\/ Get number of precesses\n int world_size;\n MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n \/\/ Get the rank of the processes\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ Get the name of the processor\n char processor_name[MPI_MAX_PROCESSOR_NAME];\n int name_len;\n MPI_Get_processor_name(processor_name, &name_len);\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Read input parameters\n if (argc<5) throw logic_error(\"ERROR: Not enough arguments.\");\n string in_filename = string(argv[1]);\n string out_filename = string(argv[2]);\n int mem_size_GB = atoi(argv[3]);\n unsigned long mem_size = mem_size_GB * size_t(1000000000);\n int num_entries = atoi(argv[4]); \/\/ How many entries from input file to run\n\n\n \/\/ Timing variables.\n high_resolution_clock::time_point t0, t1;\n high_resolution_clock::time_point t0_init_total, t0_total, t1_total;\n duration<double> span_total;\n t0 = high_resolution_clock::now();\n\n \/\/ Start here\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Process 0\n if (rank==0)\n {\n\n int entries_left = num_entries;\n vector<MPI_Request> requests(world_size, MPI_REQUEST_NULL);\n vector<string> parameter_strings(world_size);\n vector<string> input_strings(world_size);\n\n \/\/ Written?\n vector<bool> written(world_size, false);\n \/\/ Input lines\n vector<string> input_lines(num_entries);\n\n \/\/ Output file\n ofstream out_file(out_filename);\n out_file.precision(7);\n\n \/\/ Input variables (from file)\n \/\/ Open file\n auto in_file = ifstream(in_filename);\n assert(in_file.good() && \"Cannot open file.\");\n \/\/ Gotten from the file.\n \/\/ Number of arguments per amplitude and number of amplitudes per line\n int num_args, num_amps; \n \/\/ The first element should be the number of arguments per line\n in_file >> num_args;\n in_file >> num_amps;\n int batch_size = num_args-2;\n\n \/\/ Grab lines one by one\n string line;\n getline(in_file, line); \/\/ \"Read\" one line to start next from the second.\n \/\/ Send num_args\n for (int p=1; p<world_size; ++p)\n {\n MPI_Send(vector<int>({num_args,num_amps}).data(), 2, MPI_INT, p, 0,\n MPI_COMM_WORLD);\n }\n \/\/ Send second line with metadata\n if (getline(in_file, line)) if (line.size() && line[0] != '#')\n {\n for (int p=1; p<world_size; ++p)\n {\n MPI_Send(line.c_str(), line.size(), MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n parameter_strings[p] = line;\n }\n }\n\n \/\/ Read all other lines\n t0 = high_resolution_clock::now();\n int line_idx = 0;\n while (getline(in_file, line) && line_idx<num_entries) if (line.size() && line[0] != '#')\n {\n input_lines[line_idx] = line;\n ++line_idx;\n }\n in_file.close();\n line_idx = 0;\n t1 = high_resolution_clock::now();\n duration<double> span = duration_cast<duration<double>>(t1 - t0);\n cout << \"Reading took \" << span.count() << endl;\n\n \/\/ Set up for messages and storage\n vector<s_type> amplitudes_out(batch_size*num_amps*num_entries);\n vector<int> tasks_out(num_entries);\n vector<double> peak_times_out(num_entries);\n vector<string> input_strings_out(num_entries);\n int idx_entry = 0;\n \/\/ amplitudes buffer. +1 is to receive the time_largest_contraction.\n vector<s_type> amplitudes_buffer((batch_size*num_amps+1)*world_size);\n\n \/\/ BEGIN TIMER\n \/\/\/\/\/\/ MEASURE BEGIN TIMER\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Initializing started at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n }\n \/\/\/\/\/\/ END MEASURE BEGIN TIMER\n MPI_Barrier(MPI_COMM_WORLD);\n \/\/\/\/\/\/ MEASURE COMPUTATION BEGIN TIMER\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Compuatation started at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n t0_init_total = high_resolution_clock::now();\n }\n \/\/\/\/\/\/ END MEASURE COMPUTATION BEGIN TIMER\n\n\n \/\/ Send messages\n while (entries_left>0)\n {\n for (int p=1; p<world_size; ++p)\n {\n if (entries_left<=0) break;\n int flag = true;\n if (requests[p]!=MPI_REQUEST_NULL) \/\/ First time is flag=true;\n {\n MPI_Request_get_status(requests[p], &flag, MPI_STATUS_IGNORE);\n if (flag)\n {\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n amplitudes_out[batch_size*num_amps*idx_entry+a] =\n amplitudes_buffer[(batch_size*num_amps+1)*p+a];\n }\n \/\/ Populate out vectors\n tasks_out[idx_entry] = p;\n input_strings_out[idx_entry] = input_strings[p];\n peak_times_out[idx_entry] =\n (double)amplitudes_buffer[(batch_size*num_amps+1)*(p+1)-1].real();\n ++idx_entry;\n \n written[p] = true;\n }\n }\n if (flag)\n {\n line = input_lines[line_idx];\n ++line_idx;\n {\n MPI_Send(line.c_str(), line.size(), MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n \n written[p] = false;\n input_strings[p] = line;\n --entries_left;\n \/\/ Time\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n \/\/ Time\n \/\/cout << span.count() << \"s. Sent batch to process \" << p\n \/\/ << \". Entries left = \" << entries_left << \"\\n\";\n MPI_Irecv(amplitudes_buffer.data()+(batch_size*num_amps+1)*(p),\n batch_size*num_amps+1, MPI_COMPLEX, p, 0,\n MPI_COMM_WORLD, &requests[p]);\n }\n }\n }\n }\n\n \/\/ Clean up\n for (int p=1; p<world_size; ++p)\n {\n int flag;\n MPI_Request_get_status(requests[p], &flag, MPI_STATUS_IGNORE);\n if (!flag || !written[p])\n {\n MPI_Wait(&requests[p], MPI_STATUS_IGNORE);\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n amplitudes_out[batch_size*num_amps*idx_entry+a] =\n amplitudes_buffer[(batch_size*num_amps+1)*p+a];\n }\n\n \/\/ Populate out vectors\n tasks_out[idx_entry] = p;\n input_strings_out[idx_entry] = input_strings[p];\n peak_times_out[idx_entry] =\n (double)amplitudes_buffer[(batch_size*num_amps+1)*(p+1)-1].real();\n ++idx_entry;\n\n written[p] = true;\n }\n \/\/ Send a dummy pointer to show that the we are done!\n MPI_Send(NULL, 0, MPI_CHAR, p, 0,\n MPI_COMM_WORLD);\n }\n\n \/\/ END TIMER\n MPI_Barrier(MPI_COMM_WORLD);\n {\n time_t t = time(NULL);\n tm* timePtr = localtime(&t);\n cout << \"Computation ended at: \"\n << timePtr->tm_mon << \"\/\"\n << timePtr->tm_mday << \"\/\"\n << (timePtr->tm_year)+1900 << \" \"\n << timePtr->tm_hour << \":\"\n << timePtr->tm_min << \":\"\n << timePtr->tm_sec << \"\\n\" << flush;\n }\n t1_total = high_resolution_clock::now();\n span_total = duration_cast<duration<double>>(t1_total - t0_init_total);\n double total_time = span_total.count();\n cout << \"Total time (s): \" << total_time << endl;\n\n \/\/ Write everything to file\n t0 = high_resolution_clock::now();\n out_file << \"\\n---------- BEGIN OUTPUT ------------\\n\";\n out_file << \"\\nTotal time (s): \" << total_time << \"\\n\\n\" << endl;\n for (int l=0; l<tasks_out.size(); ++l)\n {\n out_file << \"\\nProcess \" << tasks_out[l]\n << \": \" << parameter_strings[tasks_out[l]] << \"\\n\"\n << \"Peak time (s): \" << peak_times_out[l] << \"\\n\"\n << input_strings_out[l] << \"\\n\";\n for (int a=0; a<batch_size*num_amps; ++a)\n {\n out_file << amplitudes_out[batch_size*num_amps*l+a].real()\n << \" \"<< amplitudes_out[batch_size*num_amps*l+a].imag()\n << \" \";\n }\n out_file << \"\\n\";\n }\n out_file << \"\\n------------ END OUTPUT ------------\\n\" << flush;\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n cout << \"Writing took \" << span.count() << endl;\n\n \/\/ Close files\n out_file.close();\n\n \/\/ Report total time\n t1 = high_resolution_clock::now();\n span = duration_cast<duration<double>>(t1 - t0);\n \/\/cout << \"Total time = \" << span.count() << endl;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Process > 0\n else\n {\n MPI_Status status;\n int length;\n string local_line;\n vector<s_type> amplitudes;\n double time_largest_contraction;\n vector<s_type> amplitudes_p_time;\n double amplitude = 0.0;\n int num_args;\n int num_amps;\n\n \/\/ get num_args\n vector<int> num_args_amps(2);\n MPI_Recv(num_args_amps.data(), 2, MPI_INT, 0, 0,\n MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n num_args = num_args_amps[0];\n num_amps = num_args_amps[1];\n \/\/ Get first string\n MPI_Probe(0, 0, MPI_COMM_WORLD, &status);\n MPI_Get_count(&status, MPI_CHAR, &length);\n char * char_ptr = new char[length];\n MPI_Recv(char_ptr, length, MPI_INT, 0, 0, MPI_COMM_WORLD,\n MPI_STATUS_IGNORE);\n local_line = string(char_ptr);\n delete[] char_ptr;\n char_ptr = nullptr;\n\n talsh::initialize(&mem_size);\n MPI_Barrier(MPI_COMM_WORLD);\n {\n Contraction contraction(local_line, num_args, num_amps);\n \/\/cout << mem_size << endl << flush;\n\n bool load_circuit(true);\n t0 = high_resolution_clock::now();\n while (true)\n {\n \/\/ Start timer\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Get string\n MPI_Probe(0, 0, MPI_COMM_WORLD, &status);\n MPI_Get_count(&status, MPI_CHAR, &length);\n char_ptr = new char[length];\n if (length==0) break;\n MPI_Recv(char_ptr, length, MPI_INT, 0, 0, MPI_COMM_WORLD,\n MPI_STATUS_IGNORE);\n local_line = string(char_ptr);\n delete[] char_ptr;\n char_ptr = nullptr;\n\n \/\/ Computation\n if (load_circuit) \/\/ load only once\n {\n contraction.load_circuit(local_line);\n load_circuit = false;\n }\n contraction.contract(local_line);\n t1 = high_resolution_clock::now();\n duration<double> span = duration_cast<duration<double>>(t1 - t0);\n t0 = high_resolution_clock::now();\n \/\/cout << \"A round took \" << span.count() << \"s\" << endl;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Message back\n amplitudes = contraction.get_amplitudes();\n time_largest_contraction = contraction.get_time_largest_contraction();\n amplitudes_p_time = vector<s_type>(amplitudes);\n amplitudes_p_time.push_back(s_type(time_largest_contraction));\n MPI_Send(amplitudes_p_time.data(), amplitudes_p_time.size(),\n MPI_COMPLEX, 0, 0, MPI_COMM_WORLD);\n }\n }\n MPI_Barrier(MPI_COMM_WORLD);\n talsh::shutdown();\n\n }\n\n \/\/ Finalize the MPI environment.\n MPI_Finalize();\n\n return 0;\n} \n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n#include <gtest\/gtest.h>\n\n#include \"packager\/base\/file_util.h\"\n#include \"packager\/media\/file\/file.h\"\n\nnamespace {\nconst int kDataSize = 1024;\nconst char* kTestLocalFileName = \"\/tmp\/local_file_test\";\n}\n\nnamespace edash_packager {\nnamespace media {\n\nclass LocalFileTest : public testing::Test {\n protected:\n virtual void SetUp() {\n data_.resize(kDataSize);\n for (int i = 0; i < kDataSize; ++i)\n data_[i] = i % 256;\n\n \/\/ Test file path for file_util API.\n test_file_path_ = base::FilePath(kTestLocalFileName);\n\n \/\/ Local file name with prefix for File API.\n local_file_name_ = kLocalFilePrefix;\n local_file_name_ += kTestLocalFileName;\n }\n\n virtual void TearDown() {\n \/\/ Remove test file if created.\n base::DeleteFile(base::FilePath(kTestLocalFileName), false);\n }\n\n std::string data_;\n base::FilePath test_file_path_;\n std::string local_file_name_;\n};\n\nTEST_F(LocalFileTest, ReadNotExist) {\n \/\/ Remove test file if it exists.\n base::DeleteFile(base::FilePath(kTestLocalFileName), false);\n ASSERT_TRUE(File::Open(local_file_name_.c_str(), \"r\") == NULL);\n}\n\nTEST_F(LocalFileTest, Size) {\n ASSERT_EQ(kDataSize,\n file_util::WriteFile(test_file_path_, data_.data(), kDataSize));\n ASSERT_EQ(kDataSize, File::GetFileSize(local_file_name_.c_str()));\n}\n\nTEST_F(LocalFileTest, Write) {\n \/\/ Write file using File API.\n File* file = File::Open(local_file_name_.c_str(), \"w\");\n ASSERT_TRUE(file != NULL);\n EXPECT_EQ(kDataSize, file->Write(&data_[0], kDataSize));\n EXPECT_EQ(kDataSize, file->Size());\n EXPECT_TRUE(file->Close());\n\n \/\/ Read file using file_util API.\n std::string read_data(kDataSize, 0);\n ASSERT_EQ(kDataSize,\n base::ReadFile(test_file_path_, &read_data[0], kDataSize));\n\n \/\/ Compare data written and read.\n EXPECT_EQ(data_, read_data);\n}\n\nTEST_F(LocalFileTest, Read_And_Eof) {\n \/\/ Write file using file_util API.\n ASSERT_EQ(kDataSize,\n file_util::WriteFile(test_file_path_, data_.data(), kDataSize));\n\n \/\/ Read file using File API.\n File* file = File::Open(local_file_name_.c_str(), \"r\");\n ASSERT_TRUE(file != NULL);\n\n \/\/ Read half of the file.\n const int kFirstReadBytes = kDataSize \/ 2;\n std::string read_data(kFirstReadBytes + kDataSize, 0);\n EXPECT_EQ(kFirstReadBytes, file->Read(&read_data[0], kFirstReadBytes));\n\n \/\/ Read the remaining half of the file and verify EOF.\n EXPECT_EQ(kDataSize - kFirstReadBytes,\n file->Read(&read_data[kFirstReadBytes], kDataSize));\n uint8_t single_byte;\n EXPECT_EQ(0, file->Read(&single_byte, sizeof(single_byte)));\n EXPECT_TRUE(file->Close());\n\n \/\/ Compare data written and read.\n read_data.resize(kDataSize);\n EXPECT_EQ(data_, read_data);\n}\n\nTEST_F(LocalFileTest, WriteRead) {\n \/\/ Write file using File API, using file name directly (without prefix).\n File* file = File::Open(kTestLocalFileName, \"w\");\n ASSERT_TRUE(file != NULL);\n EXPECT_EQ(kDataSize, file->Write(&data_[0], kDataSize));\n EXPECT_EQ(kDataSize, file->Size());\n EXPECT_TRUE(file->Close());\n\n \/\/ Read file using File API, using local file prefix + file name.\n file = File::Open(local_file_name_.c_str(), \"r\");\n ASSERT_TRUE(file != NULL);\n\n \/\/ Read half of the file and verify that Eof is not true.\n std::string read_data(kDataSize, 0);\n EXPECT_EQ(kDataSize, file->Read(&read_data[0], kDataSize));\n EXPECT_TRUE(file->Close());\n\n \/\/ Compare data written and read.\n EXPECT_EQ(data_, read_data);\n}\n\n} \/\/ namespace media\n} \/\/ namespace edash_packager\n<commit_msg>Change LocalFileTest to use CreateTemporaryFile<commit_after>\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n#include <gtest\/gtest.h>\n\n#include \"packager\/base\/file_util.h\"\n#include \"packager\/media\/file\/file.h\"\n\nnamespace {\nconst int kDataSize = 1024;\n}\n\nnamespace edash_packager {\nnamespace media {\n\nclass LocalFileTest : public testing::Test {\n protected:\n virtual void SetUp() {\n data_.resize(kDataSize);\n for (int i = 0; i < kDataSize; ++i)\n data_[i] = i % 256;\n\n \/\/ Test file path for file_util API.\n ASSERT_TRUE(base::CreateTemporaryFile(&test_file_path_));\n local_file_name_no_prefix_ = test_file_path_.value();\n\n \/\/ Local file name with prefix for File API.\n local_file_name_ = kLocalFilePrefix;\n local_file_name_ += local_file_name_no_prefix_;\n }\n\n virtual void TearDown() {\n \/\/ Remove test file if created.\n base::DeleteFile(base::FilePath(local_file_name_no_prefix_), false);\n }\n\n std::string data_;\n\n \/\/ Path to the temporary file for this test.\n base::FilePath test_file_path_;\n \/\/ Same as |test_file_path_| but in string form.\n std::string local_file_name_no_prefix_;\n\n \/\/ Same as |local_file_name_no_prefix_| but with the file prefix.\n std::string local_file_name_;\n};\n\nTEST_F(LocalFileTest, ReadNotExist) {\n \/\/ Remove test file if it exists.\n base::DeleteFile(base::FilePath(local_file_name_no_prefix_), false);\n ASSERT_TRUE(File::Open(local_file_name_.c_str(), \"r\") == NULL);\n}\n\nTEST_F(LocalFileTest, Size) {\n ASSERT_EQ(kDataSize,\n file_util::WriteFile(test_file_path_, data_.data(), kDataSize));\n ASSERT_EQ(kDataSize, File::GetFileSize(local_file_name_.c_str()));\n}\n\nTEST_F(LocalFileTest, Write) {\n \/\/ Write file using File API.\n File* file = File::Open(local_file_name_.c_str(), \"w\");\n ASSERT_TRUE(file != NULL);\n EXPECT_EQ(kDataSize, file->Write(&data_[0], kDataSize));\n EXPECT_EQ(kDataSize, file->Size());\n EXPECT_TRUE(file->Close());\n\n \/\/ Read file using file_util API.\n std::string read_data(kDataSize, 0);\n ASSERT_EQ(kDataSize,\n base::ReadFile(test_file_path_, &read_data[0], kDataSize));\n\n \/\/ Compare data written and read.\n EXPECT_EQ(data_, read_data);\n}\n\nTEST_F(LocalFileTest, Read_And_Eof) {\n \/\/ Write file using file_util API.\n ASSERT_EQ(kDataSize,\n file_util::WriteFile(test_file_path_, data_.data(), kDataSize));\n\n \/\/ Read file using File API.\n File* file = File::Open(local_file_name_.c_str(), \"r\");\n ASSERT_TRUE(file != NULL);\n\n \/\/ Read half of the file.\n const int kFirstReadBytes = kDataSize \/ 2;\n std::string read_data(kFirstReadBytes + kDataSize, 0);\n EXPECT_EQ(kFirstReadBytes, file->Read(&read_data[0], kFirstReadBytes));\n\n \/\/ Read the remaining half of the file and verify EOF.\n EXPECT_EQ(kDataSize - kFirstReadBytes,\n file->Read(&read_data[kFirstReadBytes], kDataSize));\n uint8_t single_byte;\n EXPECT_EQ(0, file->Read(&single_byte, sizeof(single_byte)));\n EXPECT_TRUE(file->Close());\n\n \/\/ Compare data written and read.\n read_data.resize(kDataSize);\n EXPECT_EQ(data_, read_data);\n}\n\nTEST_F(LocalFileTest, WriteRead) {\n \/\/ Write file using File API, using file name directly (without prefix).\n File* file = File::Open(local_file_name_no_prefix_.c_str(), \"w\");\n ASSERT_TRUE(file != NULL);\n EXPECT_EQ(kDataSize, file->Write(&data_[0], kDataSize));\n EXPECT_EQ(kDataSize, file->Size());\n EXPECT_TRUE(file->Close());\n\n \/\/ Read file using File API, using local file prefix + file name.\n file = File::Open(local_file_name_.c_str(), \"r\");\n ASSERT_TRUE(file != NULL);\n\n \/\/ Read half of the file and verify that Eof is not true.\n std::string read_data(kDataSize, 0);\n EXPECT_EQ(kDataSize, file->Read(&read_data[0], kDataSize));\n EXPECT_TRUE(file->Close());\n\n \/\/ Compare data written and read.\n EXPECT_EQ(data_, read_data);\n}\n\n} \/\/ namespace media\n} \/\/ namespace edash_packager\n<|endoftext|>"} {"text":"<commit_before>\/\/ Implementation of functions declared in FLUID designer\n\n#include <iostream>\n#include <fstream>\n#include <thread>\n#include <chrono>\n\n#include <FL\/Fl.H>\n\n#include \"configuration.h\"\n#include \"gnss_transceiver.h\"\n#include \"ui.h\"\n\n\nvoid Ui::apply_settings()\n{\n Configuration conf{transceiver_->config()};\n try {\n conf.device_id = std::stoul(text_device_id->value());\n conf.gnss_port = text_gnss_port->value();\n conf.use_msg_rmc = check_rmc->value();\n conf.use_msg_gga = check_gga->value();\n conf.use_msg_gsv = check_gsv->value();\n conf.use_msg_other = check_other->value();\n conf.trans_ip = text_trans_ip->value();\n conf.trans_port = std::stoul(text_trans_port->value());\n conf.recv_ip = text_recv_ip->value();\n conf.recv_port = std::stoul(text_recv_port->value());\n transceiver_->set_config(conf);\n }\n catch (const std::invalid_argument& e) {\n std::cerr << \"Error applying settings: \" << e.what()\n << \"\\nSettings were not applied.\" << std::endl;\n }\n catch (const std::out_of_range& e) {\n std::cerr << \"Error applying settings: \" << e.what()\n << \"\\nSettings were not applied.\" << std::endl;\n }\n}\n\n\nvoid Ui::load_settings()\n{\n auto& conf = transceiver_->config();\n text_device_id->value(std::to_string(conf.device_id).c_str());\n text_gnss_port->value(conf.gnss_port.c_str());\n check_rmc->value(conf.use_msg_rmc);\n check_gga->value(conf.use_msg_gga);\n check_gsv->value(conf.use_msg_gsv);\n check_other->value(conf.use_msg_other);\n text_trans_ip->value(conf.trans_ip.c_str());\n text_trans_port->value(std::to_string(conf.trans_port).c_str());\n text_recv_ip->value(conf.recv_ip.c_str());\n text_recv_port->value(std::to_string(conf.recv_port).c_str());\n}\n\n\nvoid Ui::button_start_clicked()\n{\n if (button_start->value()) {\n \/\/ Make sure transceiver isn't running\n if (transceiver_->is_active()) {\n std::cerr << \"Transceiver already running!\" << std::endl;\n button_start->value(1);\n }\n else {\n std::string filename;\n if (choice_mode->value() > 0) {\n auto t = std::chrono::high_resolution_clock::now().time_since_epoch();\n filename = std::string(\"logs\/log_\") + std::to_string(t.count()) + \".csv\";\n }\n switch (choice_mode->value()) {\n case 0: transceiver_->start_gnss_transmitter(); break;\n case 1: transceiver_->start_gnss_receiver(filename); break;\n case 2: transceiver_->start_gnss_logger(filename); break;\n }\n button_start->label(\"Stop\");\n last_count_ = 0;\n Fl::add_timeout(1.0, &Ui::update_status_callback, this);\n }\n }\n else {\n transceiver_->stop();\n button_start->label(\"Start\");\n Fl::remove_timeout(&Ui::update_status_callback, this);\n }\n}\n\n\nvoid Ui::button_apply_clicked()\n{\n apply_settings();\n}\n\n\nvoid Ui::button_sync_time_clicked()\n{\n \/\/ Rough time sync via NTP\n std::cout << \"Syncing time, please wait...\" << std::endl;\n std::thread t{[]{ system(\"sudo service ntp stop && sudo ntpd -gq && sudo service ntp start\"); }};\n t.detach();\n}\n\n\nvoid Ui::update_status_callback(void* p)\n{\n auto* ui = reinterpret_cast<Ui*>(p);\n ui->update_status();\n Fl::repeat_timeout(1.0, &Ui::update_status_callback, ui);\n}\n\n\nvoid Ui::update_status()\n{\n \/\/ Rate (intented to be in hz) only works when UI is updated each second\n auto count = transceiver_->activity_count();\n auto rate = count - last_count_;\n last_count_ = count;\n\n text_rate->value(std::to_string(rate).c_str());\n text_total->value(std::to_string(count).c_str());\n}\n<commit_msg>Added check to prevent time sync while running<commit_after>\/\/ Implementation of functions declared in FLUID designer\n\n#include <iostream>\n#include <fstream>\n#include <thread>\n#include <chrono>\n\n#include <FL\/Fl.H>\n\n#include \"configuration.h\"\n#include \"gnss_transceiver.h\"\n#include \"ui.h\"\n\n\nvoid Ui::apply_settings()\n{\n Configuration conf{transceiver_->config()};\n try {\n conf.device_id = std::stoul(text_device_id->value());\n conf.gnss_port = text_gnss_port->value();\n conf.use_msg_rmc = check_rmc->value();\n conf.use_msg_gga = check_gga->value();\n conf.use_msg_gsv = check_gsv->value();\n conf.use_msg_other = check_other->value();\n conf.trans_ip = text_trans_ip->value();\n conf.trans_port = std::stoul(text_trans_port->value());\n conf.recv_ip = text_recv_ip->value();\n conf.recv_port = std::stoul(text_recv_port->value());\n transceiver_->set_config(conf);\n }\n catch (const std::invalid_argument& e) {\n std::cerr << \"Error applying settings: \" << e.what()\n << \"\\nSettings were not applied.\" << std::endl;\n }\n catch (const std::out_of_range& e) {\n std::cerr << \"Error applying settings: \" << e.what()\n << \"\\nSettings were not applied.\" << std::endl;\n }\n}\n\n\nvoid Ui::load_settings()\n{\n auto& conf = transceiver_->config();\n text_device_id->value(std::to_string(conf.device_id).c_str());\n text_gnss_port->value(conf.gnss_port.c_str());\n check_rmc->value(conf.use_msg_rmc);\n check_gga->value(conf.use_msg_gga);\n check_gsv->value(conf.use_msg_gsv);\n check_other->value(conf.use_msg_other);\n text_trans_ip->value(conf.trans_ip.c_str());\n text_trans_port->value(std::to_string(conf.trans_port).c_str());\n text_recv_ip->value(conf.recv_ip.c_str());\n text_recv_port->value(std::to_string(conf.recv_port).c_str());\n}\n\n\nvoid Ui::button_start_clicked()\n{\n if (button_start->value()) {\n \/\/ Make sure transceiver isn't running\n if (transceiver_->is_active()) {\n std::cerr << \"Transceiver already running!\" << std::endl;\n button_start->value(1);\n }\n else {\n std::string filename;\n if (choice_mode->value() > 0) {\n auto t = std::chrono::high_resolution_clock::now().time_since_epoch();\n filename = std::string(\"logs\/log_\") + std::to_string(t.count()) + \".csv\";\n }\n switch (choice_mode->value()) {\n case 0: transceiver_->start_gnss_transmitter(); break;\n case 1: transceiver_->start_gnss_receiver(filename); break;\n case 2: transceiver_->start_gnss_logger(filename); break;\n }\n button_start->label(\"Stop\");\n last_count_ = 0;\n Fl::add_timeout(1.0, &Ui::update_status_callback, this);\n }\n }\n else {\n transceiver_->stop();\n button_start->label(\"Start\");\n Fl::remove_timeout(&Ui::update_status_callback, this);\n }\n}\n\n\nvoid Ui::button_apply_clicked()\n{\n apply_settings();\n}\n\n\nvoid Ui::button_sync_time_clicked()\n{\n \/\/ This is just for convenience and not intented as a proper time sync method\n if (!transceiver_->is_active()) {\n \/\/ Rough time sync via NTP\n std::cout << \"Syncing time, please wait...\" << std::endl;\n std::thread t{[]{ system(\"sudo service ntp stop && sudo ntpd -gq && sudo service ntp start\"); }};\n t.detach();\n }\n else std::cerr << \"Can't sync time while transceiver is running!\" << std::endl;\n}\n\n\nvoid Ui::update_status_callback(void* p)\n{\n auto* ui = reinterpret_cast<Ui*>(p);\n ui->update_status();\n Fl::repeat_timeout(1.0, &Ui::update_status_callback, ui);\n}\n\n\nvoid Ui::update_status()\n{\n \/\/ Rate (intented to be in hz) only works when UI is updated each second\n auto count = transceiver_->activity_count();\n auto rate = count - last_count_;\n last_count_ = count;\n\n text_rate->value(std::to_string(rate).c_str());\n text_total->value(std::to_string(count).c_str());\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix tools\/string.hxx remnants<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>logging<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: formula.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:26:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_FORMULA_HXX\n#define SC_FORMULA_HXX\n\n#ifndef SC_ANYREFDG_HXX\n#include \"anyrefdg.hxx\"\n#endif\n\n#ifndef SC_FUNCUTL_HXX\n#include \"funcutl.hxx\"\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\" \/\/ ScAddress\n#endif\n\n#ifndef _STDCTRL_HXX \/\/autogen\n#include <svtools\/stdctrl.hxx>\n#endif\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _SV_GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n\n#ifndef _SVEDIT_HXX \/\/autogen\n#include <svtools\/svmedit.hxx>\n#endif\n\n#ifndef _SV_TABPAGE_HXX \/\/autogen\n#include <vcl\/tabpage.hxx>\n#endif\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n\n#ifndef _SV_TABCTRL_HXX \/\/autogen\n#include <vcl\/tabctrl.hxx>\n#endif\n\n#ifndef SC_PARAWIN_HXX\n#include \"parawin.hxx\"\n#endif\n\n#ifndef _SVTREEBOX_HXX \/\/autogen\n#include <svtools\/svtreebx.hxx>\n#endif\n\n#ifndef SC_COMPILER_HXX\n#include \"compiler.hxx\"\n#endif\n\n#ifndef SC_CELL_HXX\n#include \"cell.hxx\"\n#endif\n\n#ifndef SC_FUNCPAGE_HXX\n#include \"funcpage.hxx\"\n#endif\n\n#ifndef SC_STRUCTPG_HXX\n#include \"structpg.hxx\"\n#endif\n\nclass ScViewData;\nclass ScDocument;\nclass ScFuncDesc;\nclass ScInputHandler;\nclass ScDocShell;\n\n\/\/============================================================================\n\nenum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };\n\n\/\/============================================================================\n\ntypedef ScTabViewShell* PtrTabViewShell;\n\n\/\/============================================================================\n\n\/\/============================================================================\n\nclass ScFormulaDlg : public ScAnyRefDlg\n{\npublic:\n ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,\n Window* pParent, ScViewData* pViewData );\n ~ScFormulaDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pRefDoc );\n virtual BOOL IsRefInputMode() const;\n virtual BOOL IsDocAllowed(SfxObjectShell* pDocSh) const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n\n TabControl aTabCtrl;\n GroupBox aGbEdit; \/\/! MUST be placed before aScParaWin for initializing\n ScParaWin aScParaWin;\n FixedText aFtHeadLine;\n FixedInfo aFtFuncName;\n FixedInfo aFtFuncDesc;\n\n FixedText aFtEditName;\n \/\/FixedInfo aFtEditDesc;\n\n FixedText aFtResult;\n ValWnd aWndResult;\n\n FixedText aFtFormula;\n ScEditBox aMEFormula;\n\n CheckBox aBtnMatrix;\n HelpButton aBtnHelp;\n CancelButton aBtnCancel;\n\n PushButton aBtnBackward;\n PushButton aBtnForward;\n OKButton aBtnEnd;\n\n ScRefEdit aEdRef;\n ScRefButton aRefBtn;\n\n FixedText aFtFormResult;\n ValWnd aWndFormResult;\n\n ScRefEdit* pTheRefEdit;\n ScRefButton* pTheRefButton;\n ScFuncPage* pScFuncPage;\n ScStructPage* pScStructPage;\n ScFormulaCell* pCell;\n ScCompiler* pComp;\n ScTokenArray* pScTokA;\n String aOldFormula;\n BOOL bStructUpdate;\n MultiLineEdit* pMEdit;\n BOOL bUserMatrixFlag;\n Timer aTimer;\n\n const String aTitle1;\n const String aTitle2;\n const String aTxtEnd;\n const String aTxtOk; \/\/ hinter aBtnEnd\n\n ULONG nOldHelp;\n ULONG nOldUnique;\n ULONG nActivWinId;\n BOOL bIsShutDown;\n\n\n\n Font aFntBold;\n Font aFntLight;\n USHORT nEdFocus;\n\/\/ Selection theCurSel;\n BOOL bEditFlag;\n const ScFuncDesc* pFuncDesc;\n USHORT nArgs;\n String** pArgArr;\n Selection aFuncSel;\n\n static ScDocument* pDoc;\n static ScAddress aCursorPos;\n\nprotected:\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );\n virtual void RefInputDone( BOOL bForced = FALSE );\n ULONG FindFocusWin(Window *pWin);\n void SetFocusWin(Window *pWin,ULONG nUniqueId);\n String RepairFormula(const String& aFormula);\n void SaveLRUEntry(const ScFuncDesc* pFuncDesc);\n void HighlightFunctionParas(const String& aFormula);\n\nprivate:\n\n BOOL IsInputHdl(ScInputHandler* pHdl);\n ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);\n\n void MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,\n ScTokenArray* pScTokA,ScCompiler* pComp);\n\n void ClearAllParas();\n void DeleteArgs();\n void FillDialog(BOOL nFlag=TRUE);\n void EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );\n void EditThisFunc(xub_StrLen nFStart);\n void EditFuncParas(xub_StrLen nEditPos);\n\n\n void UpdateArgInput( USHORT nOffset, USHORT nInput );\n BOOL CalcValue( const String& rStrExp, String& rStrResult );\n BOOL CalcStruct( const String& rStrExp);\n\n void UpdateValues();\n void SaveArg( USHORT nEd );\n void UpdateSelection();\n void DoEnter( BOOL bOk );\n void UpdateFunctionDesc();\n void ResizeArgArr( const ScFuncDesc* pNewFunc );\n void FillListboxes();\n void FillControls();\n\n xub_StrLen GetFunctionPos(xub_StrLen nPos);\n void UpdateTokenArray( const String& rStrExp);\n\n ScRefEdit* GetCurrRefEdit();\n\n DECL_LINK( ScrollHdl, ScParaWin* );\n DECL_LINK( ModifyHdl, ScParaWin* );\n DECL_LINK( FxHdl, ScParaWin* );\n\n DECL_LINK( MatrixHdl, CheckBox *);\n DECL_LINK( FormulaHdl, MultiLineEdit* );\n DECL_LINK( FormulaCursorHdl, ScEditBox*);\n DECL_LINK( BtnHdl, PushButton* );\n DECL_LINK( GetEdFocusHdl, ArgInput* );\n DECL_LINK( GetFxFocusHdl, ArgInput* );\n DECL_LINK( DblClkHdl, ScFuncPage* );\n DECL_LINK( FuncSelHdl, ScFuncPage*);\n DECL_LINK( StructSelHdl, ScStructPage * );\n DECL_LINK( UpdateFocusHdl, Timer*);\n};\n\n\n\n#endif \/\/ SC_CRNRDLG_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.700); FILE MERGED 2008\/04\/01 15:30:53 thb 1.4.700.3: #i85898# Stripping all external header guards 2008\/04\/01 12:36:45 thb 1.4.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:15:41 rt 1.4.700.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: formula.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_FORMULA_HXX\n#define SC_FORMULA_HXX\n\n#include \"anyrefdg.hxx\"\n#include \"funcutl.hxx\"\n#include \"global.hxx\" \/\/ ScAddress\n#include <svtools\/stdctrl.hxx>\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n#include <vcl\/group.hxx>\n#include <svtools\/svmedit.hxx>\n#include <vcl\/tabpage.hxx>\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n#include <vcl\/tabctrl.hxx>\n#include \"parawin.hxx\"\n#include <svtools\/svtreebx.hxx>\n#include \"compiler.hxx\"\n#include \"cell.hxx\"\n#include \"funcpage.hxx\"\n#include \"structpg.hxx\"\n\nclass ScViewData;\nclass ScDocument;\nclass ScFuncDesc;\nclass ScInputHandler;\nclass ScDocShell;\n\n\/\/============================================================================\n\nenum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };\n\n\/\/============================================================================\n\ntypedef ScTabViewShell* PtrTabViewShell;\n\n\/\/============================================================================\n\n\/\/============================================================================\n\nclass ScFormulaDlg : public ScAnyRefDlg\n{\npublic:\n ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,\n Window* pParent, ScViewData* pViewData );\n ~ScFormulaDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pRefDoc );\n virtual BOOL IsRefInputMode() const;\n virtual BOOL IsDocAllowed(SfxObjectShell* pDocSh) const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n\n TabControl aTabCtrl;\n GroupBox aGbEdit; \/\/! MUST be placed before aScParaWin for initializing\n ScParaWin aScParaWin;\n FixedText aFtHeadLine;\n FixedInfo aFtFuncName;\n FixedInfo aFtFuncDesc;\n\n FixedText aFtEditName;\n \/\/FixedInfo aFtEditDesc;\n\n FixedText aFtResult;\n ValWnd aWndResult;\n\n FixedText aFtFormula;\n ScEditBox aMEFormula;\n\n CheckBox aBtnMatrix;\n HelpButton aBtnHelp;\n CancelButton aBtnCancel;\n\n PushButton aBtnBackward;\n PushButton aBtnForward;\n OKButton aBtnEnd;\n\n ScRefEdit aEdRef;\n ScRefButton aRefBtn;\n\n FixedText aFtFormResult;\n ValWnd aWndFormResult;\n\n ScRefEdit* pTheRefEdit;\n ScRefButton* pTheRefButton;\n ScFuncPage* pScFuncPage;\n ScStructPage* pScStructPage;\n ScFormulaCell* pCell;\n ScCompiler* pComp;\n ScTokenArray* pScTokA;\n String aOldFormula;\n BOOL bStructUpdate;\n MultiLineEdit* pMEdit;\n BOOL bUserMatrixFlag;\n Timer aTimer;\n\n const String aTitle1;\n const String aTitle2;\n const String aTxtEnd;\n const String aTxtOk; \/\/ hinter aBtnEnd\n\n ULONG nOldHelp;\n ULONG nOldUnique;\n ULONG nActivWinId;\n BOOL bIsShutDown;\n\n\n\n Font aFntBold;\n Font aFntLight;\n USHORT nEdFocus;\n\/\/ Selection theCurSel;\n BOOL bEditFlag;\n const ScFuncDesc* pFuncDesc;\n USHORT nArgs;\n String** pArgArr;\n Selection aFuncSel;\n\n static ScDocument* pDoc;\n static ScAddress aCursorPos;\n\nprotected:\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n virtual void RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );\n virtual void RefInputDone( BOOL bForced = FALSE );\n ULONG FindFocusWin(Window *pWin);\n void SetFocusWin(Window *pWin,ULONG nUniqueId);\n String RepairFormula(const String& aFormula);\n void SaveLRUEntry(const ScFuncDesc* pFuncDesc);\n void HighlightFunctionParas(const String& aFormula);\n\nprivate:\n\n BOOL IsInputHdl(ScInputHandler* pHdl);\n ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);\n\n void MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,\n ScTokenArray* pScTokA,ScCompiler* pComp);\n\n void ClearAllParas();\n void DeleteArgs();\n void FillDialog(BOOL nFlag=TRUE);\n void EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );\n void EditThisFunc(xub_StrLen nFStart);\n void EditFuncParas(xub_StrLen nEditPos);\n\n\n void UpdateArgInput( USHORT nOffset, USHORT nInput );\n BOOL CalcValue( const String& rStrExp, String& rStrResult );\n BOOL CalcStruct( const String& rStrExp);\n\n void UpdateValues();\n void SaveArg( USHORT nEd );\n void UpdateSelection();\n void DoEnter( BOOL bOk );\n void UpdateFunctionDesc();\n void ResizeArgArr( const ScFuncDesc* pNewFunc );\n void FillListboxes();\n void FillControls();\n\n xub_StrLen GetFunctionPos(xub_StrLen nPos);\n void UpdateTokenArray( const String& rStrExp);\n\n ScRefEdit* GetCurrRefEdit();\n\n DECL_LINK( ScrollHdl, ScParaWin* );\n DECL_LINK( ModifyHdl, ScParaWin* );\n DECL_LINK( FxHdl, ScParaWin* );\n\n DECL_LINK( MatrixHdl, CheckBox *);\n DECL_LINK( FormulaHdl, MultiLineEdit* );\n DECL_LINK( FormulaCursorHdl, ScEditBox*);\n DECL_LINK( BtnHdl, PushButton* );\n DECL_LINK( GetEdFocusHdl, ArgInput* );\n DECL_LINK( GetFxFocusHdl, ArgInput* );\n DECL_LINK( DblClkHdl, ScFuncPage* );\n DECL_LINK( FuncSelHdl, ScFuncPage*);\n DECL_LINK( StructSelHdl, ScStructPage * );\n DECL_LINK( UpdateFocusHdl, Timer*);\n};\n\n\n\n#endif \/\/ SC_CRNRDLG_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"serialport.h\"\n#include <list>\n#include \"win\/disphelper.h\"\n\n#include \"win\/stdafx.h\"\n#include \"win\/enumser.h\"\n\n#ifdef WIN32\n\nstd::list<int> g_closingHandles;\nint bufferSize;\nvoid ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) {\n switch(errorCode) {\n case ERROR_FILE_NOT_FOUND:\n sprintf(errorStr, \"%s: File not found\", prefix);\n break;\n case ERROR_INVALID_HANDLE:\n sprintf(errorStr, \"%s: Invalid handle\", prefix);\n break;\n case ERROR_ACCESS_DENIED:\n sprintf(errorStr, \"%s: Access denied\", prefix);\n break;\n case ERROR_OPERATION_ABORTED:\n sprintf(errorStr, \"%s: operation aborted\", prefix);\n break;\n default:\n sprintf(errorStr, \"%s: Unknown error code %d\", prefix, errorCode);\n break;\n }\n}\n\nvoid EIO_Open(uv_work_t* req) {\n OpenBaton* data = static_cast<OpenBaton*>(req->data);\n\n HANDLE file = CreateFile(\n data->path,\n GENERIC_READ | GENERIC_WRITE,\n 0,\n NULL,\n OPEN_EXISTING,\n FILE_FLAG_OVERLAPPED,\n NULL);\n if (file == INVALID_HANDLE_VALUE) {\n DWORD errorCode = GetLastError();\n char temp[100];\n sprintf(temp, \"Opening %s\", data->path);\n ErrorCodeToString(temp, errorCode, data->errorString);\n return;\n }\n\n bufferSize = data->bufferSize;\n\n DCB dcb = { 0 };\n dcb.DCBlength = sizeof(DCB);\n if(!BuildCommDCB(\"9600,n,8,1\", &dcb)) {\n ErrorCodeToString(\"BuildCommDCB\", GetLastError(), data->errorString);\n return;\n }\n\n dcb.fBinary = true;\n dcb.BaudRate = data->baudRate;\n dcb.ByteSize = data->dataBits;\n switch(data->parity) {\n case SERIALPORT_PARITY_NONE:\n dcb.Parity = NOPARITY;\n break;\n case SERIALPORT_PARITY_MARK:\n dcb.Parity = MARKPARITY;\n break;\n case SERIALPORT_PARITY_EVEN:\n dcb.Parity = EVENPARITY;\n break;\n case SERIALPORT_PARITY_ODD:\n dcb.Parity = ODDPARITY;\n break;\n case SERIALPORT_PARITY_SPACE:\n dcb.Parity = SPACEPARITY;\n break;\n }\n switch(data->stopBits) {\n case SERIALPORT_STOPBITS_ONE:\n dcb.StopBits = ONESTOPBIT;\n break;\n case SERIALPORT_STOPBITS_ONE_FIVE:\n dcb.StopBits = ONE5STOPBITS;\n break;\n case SERIALPORT_STOPBITS_TWO:\n dcb.StopBits = TWOSTOPBITS;\n break;\n }\n\n if(!SetCommState(file, &dcb)) {\n ErrorCodeToString(\"SetCommState\", GetLastError(), data->errorString);\n return;\n }\n\n \/\/ Set the com port read\/write timeouts\n DWORD serialBitsPerByte = 8\/*std data bits*\/ + 1\/*start bit*\/;\n serialBitsPerByte += (data->parity == SERIALPORT_PARITY_NONE ) ? 0 : 1;\n serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;\n DWORD msPerByte = (data->baudRate > 0) ?\n ((1000 * serialBitsPerByte + data->baudRate - 1) \/ data->baudRate) :\n 1;\n if (msPerByte < 1) {\n msPerByte = 1;\n }\n COMMTIMEOUTS commTimeouts = {0};\n commTimeouts.ReadIntervalTimeout = msPerByte; \/\/ Minimize chance of concatenating of separate serial port packets on read\n commTimeouts.ReadTotalTimeoutMultiplier = 0; \/\/ Do not allow big read timeout when big read buffer used\n commTimeouts.ReadTotalTimeoutConstant = 1000; \/\/ Total read timeout (period of read loop)\n commTimeouts.WriteTotalTimeoutConstant = 1000; \/\/ Const part of write timeout\n commTimeouts.WriteTotalTimeoutMultiplier = msPerByte; \/\/ Variable part of write timeout (per byte)\n if(!SetCommTimeouts(file, &commTimeouts)) {\n ErrorCodeToString(\"SetCommTimeouts\", GetLastError(), data->errorString);\n return;\n }\n\n \/\/ Remove garbage data in RX\/TX queues\n PurgeComm(file, PURGE_RXCLEAR); \n PurgeComm(file, PURGE_TXCLEAR);\n\n data->result = (int)file;\n}\n\nstruct WatchPortBaton {\npublic:\n HANDLE fd;\n DWORD bytesRead;\n char buffer[100];\n char errorString[1000];\n DWORD errorCode;\n bool disconnected;\n v8::Persistent<v8::Value> dataCallback;\n v8::Persistent<v8::Value> errorCallback;\n v8::Persistent<v8::Value> disconnectedCallback;\n};\n\nvoid EIO_WatchPort(uv_work_t* req) {\n WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);\n data->bytesRead = 0;\n data->disconnected = false;\n\n \/\/ Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout\n \/\/ Event MUST be used if program has several simultaneous asynchronous operations\n \/\/ on the same handle (i.e. ReadFile and WriteFile)\n HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);\n\n while(true) {\n OVERLAPPED ov = {0};\n ov.hEvent = hEvent;\n\n \/\/ Start read operation - synchrounous or asynchronous\n DWORD bytesReadSync = 0;\n if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {\n data->errorCode = GetLastError();\n if(data->errorCode != ERROR_IO_PENDING) {\n \/\/ Read operation error\n if(data->errorCode == ERROR_OPERATION_ABORTED) {\n data->disconnected = true;\n }\n else {\n ErrorCodeToString(\"Reading from COM port (ReadFile)\", data->errorCode, data->errorString);\n }\n break;\n }\n\n \/\/ Read operation is asynchronous and is pending\n \/\/ We MUST wait for operation completion before deallocation of OVERLAPPED struct\n \/\/ or read data buffer\n\n \/\/ Wait for async read operation completion or timeout\n DWORD bytesReadAsync = 0;\n if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {\n \/\/ Read operation error\n data->errorCode = GetLastError();\n if(data->errorCode == ERROR_OPERATION_ABORTED) {\n data->disconnected = true;\n }\n else {\n ErrorCodeToString(\"Reading from COM port (GetOverlappedResult)\", data->errorCode, data->errorString);\n }\n break;\n }\n else {\n \/\/ Read operation completed asynchronously\n data->bytesRead = bytesReadAsync;\n }\n }\n else {\n \/\/ Read operation completed synchronously\n data->bytesRead = bytesReadSync;\n }\n\n \/\/ Return data received if any\n if(data->bytesRead > 0) {\n break;\n }\n }\n\n CloseHandle(hEvent);\n}\n\nbool IsClosingHandle(int fd) {\n for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); it++) {\n if(fd == *it) {\n g_closingHandles.remove(fd);\n return true;\n }\n }\n return false;\n}\n\nvoid EIO_AfterWatchPort(uv_work_t* req) {\n WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);\n if(data->disconnected) {\n v8::Handle<v8::Value> argv[1];\n v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv);\n goto cleanup;\n }\n\n if(data->bytesRead > 0) {\n v8::Handle<v8::Value> argv[1];\n argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_;\n v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);\n } else if(data->errorCode > 0) {\n if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) {\n goto cleanup;\n } else {\n v8::Handle<v8::Value> argv[1];\n argv[0] = v8::Exception::Error(v8::String::New(data->errorString));\n v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);\n Sleep(100); \/\/ prevent the errors from occurring too fast\n }\n }\n AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback);\n\ncleanup:\n data->dataCallback.Dispose();\n data->errorCallback.Dispose();\n delete data;\n delete req;\n}\n\nvoid AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) {\n WatchPortBaton* baton = new WatchPortBaton();\n memset(baton, 0, sizeof(WatchPortBaton));\n baton->fd = (HANDLE)fd;\n baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback);\n baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback);\n baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback);\n\n uv_work_t* req = new uv_work_t();\n req->data = baton;\n\n uv_queue_work(uv_default_loop(), req, EIO_WatchPort, EIO_AfterWatchPort);\n}\n\nvoid EIO_Write(uv_work_t* req) {\n QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data);\n WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton);\n data->result = 0;\n\n OVERLAPPED ov = {0};\n \/\/ Event used by GetOverlappedResult(..., TRUE) to wait for outgoing data or timeout\n \/\/ Event MUST be used if program has several simultaneous asynchronous operations\n \/\/ on the same handle (i.e. ReadFile and WriteFile)\n ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);\n\n \/\/ Start write operation - synchrounous or asynchronous\n DWORD bytesWrittenSync = 0;\n if(!WriteFile((HANDLE)data->fd, data->bufferData, data->bufferLength, &bytesWrittenSync, &ov)) {\n DWORD lastError = GetLastError();\n if(lastError != ERROR_IO_PENDING) {\n \/\/ Write operation error\n ErrorCodeToString(\"Writing to COM port (WriteFile)\", lastError, data->errorString);\n }\n else {\n \/\/ Write operation is asynchronous and is pending\n \/\/ We MUST wait for operation completion before deallocation of OVERLAPPED struct\n \/\/ or write data buffer\n\n \/\/ Wait for async write operation completion or timeout\n DWORD bytesWrittenAsync = 0;\n if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWrittenAsync, TRUE)) {\n \/\/ Write operation error\n DWORD lastError = GetLastError();\n ErrorCodeToString(\"Writing to COM port (GetOverlappedResult)\", lastError, data->errorString);\n }\n else {\n \/\/ Write operation completed asynchronously\n data->result = bytesWrittenAsync;\n }\n }\n }\n else {\n \/\/ Write operation completed synchronously\n data->result = bytesWrittenSync;\n }\n\n CloseHandle(ov.hEvent);\n}\n\nvoid EIO_Close(uv_work_t* req) {\n CloseBaton* data = static_cast<CloseBaton*>(req->data);\n\n g_closingHandles.push_back(data->fd);\n if(!CloseHandle((HANDLE)data->fd)) {\n ErrorCodeToString(\"closing connection\", GetLastError(), data->errorString);\n return;\n }\n}\n\n\/*\n * listComPorts.c -- list COM ports\n *\n * http:\/\/github.com\/todbot\/usbSearch\/\n *\n * 2012, Tod E. Kurt, http:\/\/todbot.com\/blog\/\n *\n *\n * Uses DispHealper : http:\/\/disphelper.sourceforge.net\/\n *\n * Notable VIDs & PIDs combos:\n * VID 0403 - FTDI\n * \n * VID 0403 \/ PID 6001 - Arduino Diecimila\n *\n *\/\nvoid EIO_List(uv_work_t* req) {\n ListBaton* data = static_cast<ListBaton*>(req->data);\n\n {\n DISPATCH_OBJ(wmiSvc);\n DISPATCH_OBJ(colDevices);\n\n dhInitialize(TRUE);\n dhToggleExceptions(TRUE);\n \n dhGetObject(L\"winmgmts:{impersonationLevel=impersonate}!\\\\\\\\.\\\\root\\\\cimv2\", NULL, &wmiSvc);\n dhGetValue(L\"%o\", &colDevices, wmiSvc, L\".ExecQuery(%S)\", L\"Select * from Win32_PnPEntity\");\n\n int port_count = 0;\n FOR_EACH(objDevice, colDevices, NULL) {\n char* name = NULL;\n char* pnpid = NULL;\n char* manu = NULL;\n char* match;\n\n dhGetValue(L\"%s\", &name, objDevice, L\".Name\");\n dhGetValue(L\"%s\", &pnpid, objDevice, L\".PnPDeviceID\");\n \n if( (match = strstr( name, \"(COM\" )) != NULL ) { \/\/ look for \"(COM23)\"\n \/\/ 'Manufacturuer' can be null, so only get it if we need it\n dhGetValue(L\"%s\", &manu, objDevice, L\".Manufacturer\");\n port_count++;\n char* comname = strtok( match, \"()\");\n ListResultItem* resultItem = new ListResultItem();\n resultItem->comName = comname;\n resultItem->manufacturer = manu;\n resultItem->pnpId = pnpid;\n data->results.push_back(resultItem);\n dhFreeString(manu);\n }\n \n dhFreeString(name);\n dhFreeString(pnpid);\n } NEXT(objDevice);\n \n SAFE_RELEASE(colDevices);\n SAFE_RELEASE(wmiSvc);\n \n dhUninitialize(TRUE);\n }\n\n std::vector<UINT> ports;\n if (CEnumerateSerial::UsingQueryDosDevice(ports))\n {\n for (size_t i = 0; i < ports.size(); i++)\n {\n char comname[64] = { 0 };\n sprintf(comname, \"COM%u\", ports[i]);\n bool bFound = false;\n for (std::list<ListResultItem*>::iterator ri = data->results.begin(); ri != data->results.end(); ri++)\n {\n if (stricmp((*ri)->comName.c_str(), comname) == 0)\n {\n bFound = true;\n break;\n }\n }\n if (!bFound)\n {\n ListResultItem* resultItem = new ListResultItem();\n resultItem->comName = comname;\n resultItem->manufacturer = \"\";\n resultItem->pnpId = \"\";\n data->results.push_back(resultItem);\n }\n }\n }\n}\n\nvoid EIO_Flush(uv_work_t* req) {\n FlushBaton* data = static_cast<FlushBaton*>(req->data);\n\n if(!FlushFileBuffers((HANDLE)data->fd)) {\n ErrorCodeToString(\"flushing connection\", GetLastError(), data->errorString);\n return;\n }\n}\n\n#endif\n<commit_msg>increase buffer size<commit_after>\n#include \"serialport.h\"\n#include <list>\n#include \"win\/disphelper.h\"\n\n#include \"win\/stdafx.h\"\n#include \"win\/enumser.h\"\n\n#ifdef WIN32\n\n#define MAX_BUFFER_SIZE 1000\n\nstd::list<int> g_closingHandles;\nint bufferSize;\nvoid ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) {\n switch(errorCode) {\n case ERROR_FILE_NOT_FOUND:\n sprintf(errorStr, \"%s: File not found\", prefix);\n break;\n case ERROR_INVALID_HANDLE:\n sprintf(errorStr, \"%s: Invalid handle\", prefix);\n break;\n case ERROR_ACCESS_DENIED:\n sprintf(errorStr, \"%s: Access denied\", prefix);\n break;\n case ERROR_OPERATION_ABORTED:\n sprintf(errorStr, \"%s: operation aborted\", prefix);\n break;\n default:\n sprintf(errorStr, \"%s: Unknown error code %d\", prefix, errorCode);\n break;\n }\n}\n\nvoid EIO_Open(uv_work_t* req) {\n OpenBaton* data = static_cast<OpenBaton*>(req->data);\n\n HANDLE file = CreateFile(\n data->path,\n GENERIC_READ | GENERIC_WRITE,\n 0,\n NULL,\n OPEN_EXISTING,\n FILE_FLAG_OVERLAPPED,\n NULL);\n if (file == INVALID_HANDLE_VALUE) {\n DWORD errorCode = GetLastError();\n char temp[100];\n sprintf(temp, \"Opening %s\", data->path);\n ErrorCodeToString(temp, errorCode, data->errorString);\n return;\n }\n\n bufferSize = data->bufferSize;\n if(bufferSize > MAX_BUFFER_SIZE) {\n bufferSize = MAX_BUFFER_SIZE;\n }\n\n DCB dcb = { 0 };\n dcb.DCBlength = sizeof(DCB);\n if(!BuildCommDCB(\"9600,n,8,1\", &dcb)) {\n ErrorCodeToString(\"BuildCommDCB\", GetLastError(), data->errorString);\n return;\n }\n\n dcb.fBinary = true;\n dcb.BaudRate = data->baudRate;\n dcb.ByteSize = data->dataBits;\n switch(data->parity) {\n case SERIALPORT_PARITY_NONE:\n dcb.Parity = NOPARITY;\n break;\n case SERIALPORT_PARITY_MARK:\n dcb.Parity = MARKPARITY;\n break;\n case SERIALPORT_PARITY_EVEN:\n dcb.Parity = EVENPARITY;\n break;\n case SERIALPORT_PARITY_ODD:\n dcb.Parity = ODDPARITY;\n break;\n case SERIALPORT_PARITY_SPACE:\n dcb.Parity = SPACEPARITY;\n break;\n }\n switch(data->stopBits) {\n case SERIALPORT_STOPBITS_ONE:\n dcb.StopBits = ONESTOPBIT;\n break;\n case SERIALPORT_STOPBITS_ONE_FIVE:\n dcb.StopBits = ONE5STOPBITS;\n break;\n case SERIALPORT_STOPBITS_TWO:\n dcb.StopBits = TWOSTOPBITS;\n break;\n }\n\n if(!SetCommState(file, &dcb)) {\n ErrorCodeToString(\"SetCommState\", GetLastError(), data->errorString);\n return;\n }\n\n \/\/ Set the com port read\/write timeouts\n DWORD serialBitsPerByte = 8\/*std data bits*\/ + 1\/*start bit*\/;\n serialBitsPerByte += (data->parity == SERIALPORT_PARITY_NONE ) ? 0 : 1;\n serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;\n DWORD msPerByte = (data->baudRate > 0) ?\n ((1000 * serialBitsPerByte + data->baudRate - 1) \/ data->baudRate) :\n 1;\n if (msPerByte < 1) {\n msPerByte = 1;\n }\n COMMTIMEOUTS commTimeouts = {0};\n commTimeouts.ReadIntervalTimeout = msPerByte; \/\/ Minimize chance of concatenating of separate serial port packets on read\n commTimeouts.ReadTotalTimeoutMultiplier = 0; \/\/ Do not allow big read timeout when big read buffer used\n commTimeouts.ReadTotalTimeoutConstant = 1000; \/\/ Total read timeout (period of read loop)\n commTimeouts.WriteTotalTimeoutConstant = 1000; \/\/ Const part of write timeout\n commTimeouts.WriteTotalTimeoutMultiplier = msPerByte; \/\/ Variable part of write timeout (per byte)\n if(!SetCommTimeouts(file, &commTimeouts)) {\n ErrorCodeToString(\"SetCommTimeouts\", GetLastError(), data->errorString);\n return;\n }\n\n \/\/ Remove garbage data in RX\/TX queues\n PurgeComm(file, PURGE_RXCLEAR); \n PurgeComm(file, PURGE_TXCLEAR);\n\n data->result = (int)file;\n}\n\nstruct WatchPortBaton {\npublic:\n HANDLE fd;\n DWORD bytesRead;\n char buffer[MAX_BUFFER_SIZE];\n char errorString[1000];\n DWORD errorCode;\n bool disconnected;\n v8::Persistent<v8::Value> dataCallback;\n v8::Persistent<v8::Value> errorCallback;\n v8::Persistent<v8::Value> disconnectedCallback;\n};\n\nvoid EIO_WatchPort(uv_work_t* req) {\n WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);\n data->bytesRead = 0;\n data->disconnected = false;\n\n \/\/ Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout\n \/\/ Event MUST be used if program has several simultaneous asynchronous operations\n \/\/ on the same handle (i.e. ReadFile and WriteFile)\n HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);\n\n while(true) {\n OVERLAPPED ov = {0};\n ov.hEvent = hEvent;\n\n \/\/ Start read operation - synchrounous or asynchronous\n DWORD bytesReadSync = 0;\n if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {\n data->errorCode = GetLastError();\n if(data->errorCode != ERROR_IO_PENDING) {\n \/\/ Read operation error\n if(data->errorCode == ERROR_OPERATION_ABORTED) {\n data->disconnected = true;\n }\n else {\n ErrorCodeToString(\"Reading from COM port (ReadFile)\", data->errorCode, data->errorString);\n }\n break;\n }\n\n \/\/ Read operation is asynchronous and is pending\n \/\/ We MUST wait for operation completion before deallocation of OVERLAPPED struct\n \/\/ or read data buffer\n\n \/\/ Wait for async read operation completion or timeout\n DWORD bytesReadAsync = 0;\n if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {\n \/\/ Read operation error\n data->errorCode = GetLastError();\n if(data->errorCode == ERROR_OPERATION_ABORTED) {\n data->disconnected = true;\n }\n else {\n ErrorCodeToString(\"Reading from COM port (GetOverlappedResult)\", data->errorCode, data->errorString);\n }\n break;\n }\n else {\n \/\/ Read operation completed asynchronously\n data->bytesRead = bytesReadAsync;\n }\n }\n else {\n \/\/ Read operation completed synchronously\n data->bytesRead = bytesReadSync;\n }\n\n \/\/ Return data received if any\n if(data->bytesRead > 0) {\n break;\n }\n }\n\n CloseHandle(hEvent);\n}\n\nbool IsClosingHandle(int fd) {\n for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); it++) {\n if(fd == *it) {\n g_closingHandles.remove(fd);\n return true;\n }\n }\n return false;\n}\n\nvoid EIO_AfterWatchPort(uv_work_t* req) {\n WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);\n if(data->disconnected) {\n v8::Handle<v8::Value> argv[1];\n v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv);\n goto cleanup;\n }\n\n if(data->bytesRead > 0) {\n v8::Handle<v8::Value> argv[1];\n argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_;\n v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);\n } else if(data->errorCode > 0) {\n if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) {\n goto cleanup;\n } else {\n v8::Handle<v8::Value> argv[1];\n argv[0] = v8::Exception::Error(v8::String::New(data->errorString));\n v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);\n Sleep(100); \/\/ prevent the errors from occurring too fast\n }\n }\n AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback);\n\ncleanup:\n data->dataCallback.Dispose();\n data->errorCallback.Dispose();\n delete data;\n delete req;\n}\n\nvoid AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) {\n WatchPortBaton* baton = new WatchPortBaton();\n memset(baton, 0, sizeof(WatchPortBaton));\n baton->fd = (HANDLE)fd;\n baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback);\n baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback);\n baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback);\n\n uv_work_t* req = new uv_work_t();\n req->data = baton;\n\n uv_queue_work(uv_default_loop(), req, EIO_WatchPort, EIO_AfterWatchPort);\n}\n\nvoid EIO_Write(uv_work_t* req) {\n QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data);\n WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton);\n data->result = 0;\n\n OVERLAPPED ov = {0};\n \/\/ Event used by GetOverlappedResult(..., TRUE) to wait for outgoing data or timeout\n \/\/ Event MUST be used if program has several simultaneous asynchronous operations\n \/\/ on the same handle (i.e. ReadFile and WriteFile)\n ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);\n\n \/\/ Start write operation - synchrounous or asynchronous\n DWORD bytesWrittenSync = 0;\n if(!WriteFile((HANDLE)data->fd, data->bufferData, data->bufferLength, &bytesWrittenSync, &ov)) {\n DWORD lastError = GetLastError();\n if(lastError != ERROR_IO_PENDING) {\n \/\/ Write operation error\n ErrorCodeToString(\"Writing to COM port (WriteFile)\", lastError, data->errorString);\n }\n else {\n \/\/ Write operation is asynchronous and is pending\n \/\/ We MUST wait for operation completion before deallocation of OVERLAPPED struct\n \/\/ or write data buffer\n\n \/\/ Wait for async write operation completion or timeout\n DWORD bytesWrittenAsync = 0;\n if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWrittenAsync, TRUE)) {\n \/\/ Write operation error\n DWORD lastError = GetLastError();\n ErrorCodeToString(\"Writing to COM port (GetOverlappedResult)\", lastError, data->errorString);\n }\n else {\n \/\/ Write operation completed asynchronously\n data->result = bytesWrittenAsync;\n }\n }\n }\n else {\n \/\/ Write operation completed synchronously\n data->result = bytesWrittenSync;\n }\n\n CloseHandle(ov.hEvent);\n}\n\nvoid EIO_Close(uv_work_t* req) {\n CloseBaton* data = static_cast<CloseBaton*>(req->data);\n\n g_closingHandles.push_back(data->fd);\n if(!CloseHandle((HANDLE)data->fd)) {\n ErrorCodeToString(\"closing connection\", GetLastError(), data->errorString);\n return;\n }\n}\n\n\/*\n * listComPorts.c -- list COM ports\n *\n * http:\/\/github.com\/todbot\/usbSearch\/\n *\n * 2012, Tod E. Kurt, http:\/\/todbot.com\/blog\/\n *\n *\n * Uses DispHealper : http:\/\/disphelper.sourceforge.net\/\n *\n * Notable VIDs & PIDs combos:\n * VID 0403 - FTDI\n * \n * VID 0403 \/ PID 6001 - Arduino Diecimila\n *\n *\/\nvoid EIO_List(uv_work_t* req) {\n ListBaton* data = static_cast<ListBaton*>(req->data);\n\n {\n DISPATCH_OBJ(wmiSvc);\n DISPATCH_OBJ(colDevices);\n\n dhInitialize(TRUE);\n dhToggleExceptions(TRUE);\n \n dhGetObject(L\"winmgmts:{impersonationLevel=impersonate}!\\\\\\\\.\\\\root\\\\cimv2\", NULL, &wmiSvc);\n dhGetValue(L\"%o\", &colDevices, wmiSvc, L\".ExecQuery(%S)\", L\"Select * from Win32_PnPEntity\");\n\n int port_count = 0;\n FOR_EACH(objDevice, colDevices, NULL) {\n char* name = NULL;\n char* pnpid = NULL;\n char* manu = NULL;\n char* match;\n\n dhGetValue(L\"%s\", &name, objDevice, L\".Name\");\n dhGetValue(L\"%s\", &pnpid, objDevice, L\".PnPDeviceID\");\n \n if( (match = strstr( name, \"(COM\" )) != NULL ) { \/\/ look for \"(COM23)\"\n \/\/ 'Manufacturuer' can be null, so only get it if we need it\n dhGetValue(L\"%s\", &manu, objDevice, L\".Manufacturer\");\n port_count++;\n char* comname = strtok( match, \"()\");\n ListResultItem* resultItem = new ListResultItem();\n resultItem->comName = comname;\n resultItem->manufacturer = manu;\n resultItem->pnpId = pnpid;\n data->results.push_back(resultItem);\n dhFreeString(manu);\n }\n \n dhFreeString(name);\n dhFreeString(pnpid);\n } NEXT(objDevice);\n \n SAFE_RELEASE(colDevices);\n SAFE_RELEASE(wmiSvc);\n \n dhUninitialize(TRUE);\n }\n\n std::vector<UINT> ports;\n if (CEnumerateSerial::UsingQueryDosDevice(ports))\n {\n for (size_t i = 0; i < ports.size(); i++)\n {\n char comname[64] = { 0 };\n sprintf(comname, \"COM%u\", ports[i]);\n bool bFound = false;\n for (std::list<ListResultItem*>::iterator ri = data->results.begin(); ri != data->results.end(); ri++)\n {\n if (stricmp((*ri)->comName.c_str(), comname) == 0)\n {\n bFound = true;\n break;\n }\n }\n if (!bFound)\n {\n ListResultItem* resultItem = new ListResultItem();\n resultItem->comName = comname;\n resultItem->manufacturer = \"\";\n resultItem->pnpId = \"\";\n data->results.push_back(resultItem);\n }\n }\n }\n}\n\nvoid EIO_Flush(uv_work_t* req) {\n FlushBaton* data = static_cast<FlushBaton*>(req->data);\n\n if(!FlushFileBuffers((HANDLE)data->fd)) {\n ErrorCodeToString(\"flushing connection\", GetLastError(), data->errorString);\n return;\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/common\/stats_timer.hpp\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2014 Thomas Keh <thomas.keh@student.kit.edu>\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_COMMON_STATS_TIMER_HEADER\n#define C7A_COMMON_STATS_TIMER_HEADER\n\n#include <cassert>\n#include <chrono>\n#include <memory>\n#include <ostream>\n\nnamespace c7a {\nnamespace common {\n\n\/*!\n * This class provides a statistical stop watch timer that can easily be\n * deactivated using a boolean template switch.\n *\n * It uses std::chrono to get the current time when start() is called. Then,\n * after some processing, the function stop() functions can be called, or\n * seconds() and other accessors can be called directly.\n *\/\ntemplate <bool Active = true>\nclass StatsTimer\n{ };\n\nusing TimerPtr = std::shared_ptr<StatsTimer<true> >;\ntemplate <>\nclass StatsTimer<true>\n{\npublic:\n typedef std::chrono::steady_clock steady_clock;\n typedef std::chrono::steady_clock::time_point time_point;\n\n typedef std::chrono::microseconds duration;\n\nprotected:\n \/\/! boolean whether the timer is currently running\n bool running_;\n\n \/\/! total accumulated time in microseconds.\n duration accumulated_;\n\n \/\/! last start time of the stop watch\n time_point last_start_;\n\npublic:\n \/\/! Initialize and optionally immediately start the timer\n explicit StatsTimer(bool start_immediately = false)\n : running_(false),\n accumulated_() {\n if (start_immediately) Start();\n }\n\n \/\/! Whether the timer is real\n bool Real() const { return true; }\n\n \/\/! start timer\n void Start() {\n assert(!running_);\n running_ = true;\n last_start_ = steady_clock::now();\n }\n\n \/\/! stop timer\n void Stop() {\n assert(running_);\n running_ = false;\n accumulated_ += std::chrono::duration_cast<duration>(\n steady_clock::now() - last_start_);\n }\n\n \/\/! return accumulated time\n void Reset() {\n accumulated_ = duration(0);\n last_start_ = steady_clock::now();\n }\n\n \/\/! return currently accumulated time\n duration Accumulated() const {\n duration d = accumulated_;\n\n if (running_)\n d += std::chrono::duration_cast<duration>(\n steady_clock::now() - last_start_);\n\n return d;\n }\n\n \/\/! return currently accumulated time in microseconds\n std::chrono::microseconds::rep Microseconds() const {\n return std::chrono::duration_cast<std::chrono::microseconds>(\n Accumulated()).count();\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::milliseconds::rep Milliseconds() const {\n return std::chrono::duration_cast<std::chrono::milliseconds>(\n Accumulated()).count();\n }\n\n \/\/! return currently accumulated time in seconds\n std::chrono::seconds::rep Seconds() const {\n return std::chrono::duration_cast<std::chrono::seconds>(\n Accumulated()).count();\n }\n\n \/\/! accumulate elapsed time from another timer\n StatsTimer& operator += (const StatsTimer& tm) {\n accumulated_ += tm.accumulated_;\n return *this;\n }\n\n \/\/! direct <<-operator for ostream. Can be used for printing with std::cout.\n friend std::ostream& operator << (std::ostream& os, const StatsTimer& t) {\n return os << t.Microseconds() << \"us\";\n }\n};\n\ntemplate <>\nclass StatsTimer<false>\n{\npublic:\n typedef std::chrono::steady_clock steady_clock;\n typedef std::chrono::steady_clock::time_point time_point;\n\n typedef std::chrono::microseconds duration;\n\npublic:\n \/\/! Initialize and optionally immediately start the timer\n explicit StatsTimer(bool = false)\n { }\n\n \/\/! Whether the timer is real\n bool Real() const { return false; }\n\n \/\/! start timer\n void Start()\n { }\n\n \/\/! stop timer\n void Stop()\n { }\n\n \/\/! return accumulated time\n void Reset()\n { }\n\n \/\/! return currently accumulated time\n duration Accumulated() const {\n return duration();\n }\n\n \/\/! return currently accumulated time in microseconds\n std::chrono::microseconds::rep Microseconds() const {\n return 0;\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::milliseconds::rep Milliseconds() const {\n return 0;\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::seconds::rep Seconds() const {\n return 0;\n }\n\n \/\/! accumulate elapsed time from another timer\n StatsTimer& operator += (const StatsTimer&) {\n return *this;\n }\n\n \/\/! direct <<-operator for ostream. Can be used for printing with std::cout.\n friend std::ostream& operator << (std::ostream& os, const StatsTimer&) {\n return os << \"<invalid>\" << \"ms\";\n }\n};\n\n} \/\/ namespace common\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_COMMON_STATS_TIMER_HEADER\n\n\/******************************************************************************\/\n<commit_msg>StatsTimer::operator<< prints only Micrsecond value without 'us'. This is better for SqlPlotTools<commit_after>\/*******************************************************************************\n * c7a\/common\/stats_timer.hpp\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2014 Thomas Keh <thomas.keh@student.kit.edu>\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_COMMON_STATS_TIMER_HEADER\n#define C7A_COMMON_STATS_TIMER_HEADER\n\n#include <cassert>\n#include <chrono>\n#include <memory>\n#include <ostream>\n\nnamespace c7a {\nnamespace common {\n\n\/*!\n * This class provides a statistical stop watch timer that can easily be\n * deactivated using a boolean template switch.\n *\n * It uses std::chrono to get the current time when start() is called. Then,\n * after some processing, the function stop() functions can be called, or\n * seconds() and other accessors can be called directly.\n *\/\ntemplate <bool Active = true>\nclass StatsTimer\n{ };\n\nusing TimerPtr = std::shared_ptr<StatsTimer<true> >;\ntemplate <>\nclass StatsTimer<true>\n{\npublic:\n typedef std::chrono::steady_clock steady_clock;\n typedef std::chrono::steady_clock::time_point time_point;\n\n typedef std::chrono::microseconds duration;\n\nprotected:\n \/\/! boolean whether the timer is currently running\n bool running_;\n\n \/\/! total accumulated time in microseconds.\n duration accumulated_;\n\n \/\/! last start time of the stop watch\n time_point last_start_;\n\npublic:\n \/\/! Initialize and optionally immediately start the timer\n explicit StatsTimer(bool start_immediately = false)\n : running_(false),\n accumulated_() {\n if (start_immediately) Start();\n }\n\n \/\/! Whether the timer is real\n bool Real() const { return true; }\n\n \/\/! start timer\n void Start() {\n assert(!running_);\n running_ = true;\n last_start_ = steady_clock::now();\n }\n\n \/\/! stop timer\n void Stop() {\n assert(running_);\n running_ = false;\n accumulated_ += std::chrono::duration_cast<duration>(\n steady_clock::now() - last_start_);\n }\n\n \/\/! return accumulated time\n void Reset() {\n accumulated_ = duration(0);\n last_start_ = steady_clock::now();\n }\n\n \/\/! return currently accumulated time\n duration Accumulated() const {\n duration d = accumulated_;\n\n if (running_)\n d += std::chrono::duration_cast<duration>(\n steady_clock::now() - last_start_);\n\n return d;\n }\n\n \/\/! return currently accumulated time in microseconds\n std::chrono::microseconds::rep Microseconds() const {\n return std::chrono::duration_cast<std::chrono::microseconds>(\n Accumulated()).count();\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::milliseconds::rep Milliseconds() const {\n return std::chrono::duration_cast<std::chrono::milliseconds>(\n Accumulated()).count();\n }\n\n \/\/! return currently accumulated time in seconds\n std::chrono::seconds::rep Seconds() const {\n return std::chrono::duration_cast<std::chrono::seconds>(\n Accumulated()).count();\n }\n\n \/\/! accumulate elapsed time from another timer\n StatsTimer& operator += (const StatsTimer& tm) {\n accumulated_ += tm.accumulated_;\n return *this;\n }\n\n \/\/! direct <<-operator for ostream. Can be used for printing with std::cout.\n friend std::ostream& operator << (std::ostream& os, const StatsTimer& t) {\n return os << t.Microseconds();\n }\n};\n\ntemplate <>\nclass StatsTimer<false>\n{\npublic:\n typedef std::chrono::steady_clock steady_clock;\n typedef std::chrono::steady_clock::time_point time_point;\n\n typedef std::chrono::microseconds duration;\n\npublic:\n \/\/! Initialize and optionally immediately start the timer\n explicit StatsTimer(bool = false)\n { }\n\n \/\/! Whether the timer is real\n bool Real() const { return false; }\n\n \/\/! start timer\n void Start()\n { }\n\n \/\/! stop timer\n void Stop()\n { }\n\n \/\/! return accumulated time\n void Reset()\n { }\n\n \/\/! return currently accumulated time\n duration Accumulated() const {\n return duration();\n }\n\n \/\/! return currently accumulated time in microseconds\n std::chrono::microseconds::rep Microseconds() const {\n return 0;\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::milliseconds::rep Milliseconds() const {\n return 0;\n }\n\n \/\/! return currently accumulated time in milliseconds\n std::chrono::seconds::rep Seconds() const {\n return 0;\n }\n\n \/\/! accumulate elapsed time from another timer\n StatsTimer& operator += (const StatsTimer&) {\n return *this;\n }\n\n \/\/! direct <<-operator for ostream. Can be used for printing with std::cout.\n friend std::ostream& operator << (std::ostream& os, const StatsTimer&) {\n return os << \"<invalid>\";\n }\n};\n\n} \/\/ namespace common\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_COMMON_STATS_TIMER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Akregator.\n\n Copyright (C) 2004 Teemu Rytilahti <tpr@d5k.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <kaction.h>\n#include <kapplication.h>\n#include <kfiledialog.h>\n#include <khtmlview.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kprocess.h>\n#include <krun.h>\n#include <kshell.h>\n#include <kurl.h>\n#include <kparts\/browserextension.h>\n\n#include <qaccel.h>\n#include <qclipboard.h>\n#include <qpaintdevicemetrics.h>\n\n#include \"viewer.h\"\n#include \"akregator_run.h\"\n#include \"akregatorconfig.h\"\n\nusing namespace Akregator;\n\nViewer::Viewer(QWidget *parent, const char *name)\n : KHTMLPart(parent, name), m_url(0)\n{\n setZoomFactor(100);\n setJScriptEnabled(true);\n setJavaEnabled(true);\n setMetaRefreshEnabled(true);\n setPluginsEnabled(true);\n setDNDEnabled(true);\n setAutoloadImages(true);\n setStatusMessagesEnabled(true);\n\n \/\/ change the cursor when loading stuff...\n connect( this, SIGNAL(started(KIO::Job *)),\n this, SLOT(slotStarted(KIO::Job *)));\n connect( this, SIGNAL(completed()),\n this, SLOT(slotCompleted()));\n\n connect( browserExtension(), SIGNAL(openURLRequestDelayed(const KURL&, const KParts::URLArgs&)), this, SLOT(slotOpenURLRequest(const KURL&, const KParts::URLArgs& )) );\n\n connect( browserExtension(),\n\nSIGNAL(popupMenu (KXMLGUIClient*, const QPoint&, const KURL&, const\n KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)), this, SLOT(slotPopupMenu(KXMLGUIClient*, const QPoint&, const KURL&, const\n KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)));\n\n KStdAction::print(this, SLOT(slotPrint()), actionCollection(), \"viewer_print\");\n KStdAction::copy(this, SLOT(slotCopy()), actionCollection(), \"viewer_copy\");\n \n new KAction( i18n(\"&Increase Font Sizes\"), \"viewmag+\", \"Ctrl+Plus\", this, SLOT(slotZoomIn()), actionCollection(), \"incFontSizes\" );\n new KAction( i18n(\"&Decrease Font Sizes\"), \"viewmag-\", \"Ctrl+Minus\", this, SLOT(slotZoomOut()), actionCollection(), \"decFontSizes\" );\n\n connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged()));\n\n new KAction(i18n(\"Copy &Link Address\"), \"\", 0,\n this, SLOT(slotCopyLinkAddress()),\n actionCollection(), \"copylinkaddress\");\n new KAction(i18n(\"&Save Link As...\"), \"\", 0,\n this, SLOT(slotSaveLinkAs()),\n actionCollection(), \"savelinkas\");\n}\n\nViewer::~Viewer()\n{}\n\nbool Viewer::openURL(const KURL &url)\n{\n new Akregator::BrowserRun(this, (QWidget*)parent(), this, url, browserExtension()->urlArgs());\n emit started(0);\n return true;\n}\n\n\nbool Viewer::closeURL()\n{\n emit browserExtension()->loadingProgress(-1);\n emit canceled(QString::null);\n return KHTMLPart::closeURL();\n}\n\nint Viewer::pointsToPixel(int pointSize) const\n{\n const QPaintDeviceMetrics metrics(view());\n return ( pointSize * metrics.logicalDpiY() + 36 ) \/ 72 ;\n}\n\nvoid Viewer::displayInExternalBrowser(const KURL &url, const QString &mimetype)\n{\n if (!url.isValid()) return;\n if (Settings::externalBrowserUseKdeDefault())\n {\n if (mimetype.isEmpty()) \n kapp->invokeBrowser(url.url(), \"0\");\n else\n KRun::runURL(url, mimetype, false, false);\n }\n else\n {\n QString cmd = Settings::externalBrowserCustomCommand();\n QString urlStr = url.url();\n cmd.replace(QRegExp(\"%u\"), urlStr);\n KProcess *proc = new KProcess;\n QStringList cmdAndArgs = KShell::splitArgs(cmd);\n *proc << cmdAndArgs;\n proc->start(KProcess::DontCare);\n delete proc;\n }\n}\n\n\nvoid Viewer::slotOpenURLRequest(const KURL& url, const KParts::URLArgs& args)\n{\n m_url = url;\n browserExtension()->setURLArgs(args);\n if (args.frameName == \"_blank\") \/\/ apparently this indicates that the MMB was pressed...\n {\n switch (Settings::mMBBehaviour())\n {\n case Settings::EnumMMBBehaviour::OpenInExternalBrowser:\n slotOpenLinkInBrowser();\n break;\n case Settings::EnumMMBBehaviour::OpenInBackground:\n slotOpenLinkInBackgroundTab();\n break;\n default:\n slotOpenLinkInForegroundTab();\n break;\n }\n }\n else \/\/ LMB:\n {\n switch (Settings::lMBBehaviour())\n {\n case Settings::EnumLMBBehaviour::OpenInExternalBrowser:\n slotOpenLinkInBrowser();\n break;\n case Settings::EnumLMBBehaviour::OpenInBackground:\n slotOpenLinkInBackgroundTab();\n break;\n default:\n slotOpenLinkInForegroundTab();\n break;\n }\n }\n}\n\nvoid Viewer::slotPopupMenu(KXMLGUIClient*, const QPoint& p, const KURL& kurl, const KParts::URLArgs&, KParts::BrowserExtension::PopupFlags kpf, mode_t)\n{\n const bool isLink = (kpf & KParts::BrowserExtension::ShowNavigationItems) == 0;\n\n QString url = kurl.url();\n \n if (!isLink)\n return;\n m_url = url;\n KPopupMenu popup;\n \n if (isLink)\n {\n popup.insertItem(SmallIcon(\"tab_new\"), i18n(\"Open Link in New &Tab\"), this, SLOT(slotOpenLinkInForegroundTab()));\n popup.insertItem(SmallIcon(\"window_new\"), i18n(\"Open Link in External &Browser\"), this, SLOT(slotOpenLinkInBrowser()));\n popup.insertSeparator();\n action(\"savelinkas\")->plug(&popup);\n action(\"copylinkaddress\")->plug(&popup);\n }\n else\n {\n action(\"viewer_copy\")->plug(&popup);\n popup.insertSeparator();\n action(\"viewer_print\")->plug(&popup);\n KAction *ac = action(\"setEncoding\");\n if (ac)\n ac->plug(&popup);\n }\n popup.exec(p);\n}\n\n\/\/ taken from KDevelop\nvoid Viewer::slotCopy()\n{\n QString text = selectedText();\n text.replace( QChar( 0xa0 ), ' ' );\n QClipboard *cb = QApplication::clipboard();\n disconnect( cb, SIGNAL( selectionChanged() ), this, SLOT( slotClearSelection() ) );\n cb->setText(text);\n connect( cb, SIGNAL( selectionChanged() ), this, SLOT( slotClearSelection() ) );\n}\n\nvoid Viewer::slotCopyLinkAddress()\n{\n if(m_url.isEmpty()) return;\n QClipboard *cb = QApplication::clipboard();\n cb->setText(m_url.prettyURL(), QClipboard::Clipboard);\n cb->setText(m_url.prettyURL(), QClipboard::Selection);\n}\n\nvoid Viewer::slotSelectionChanged()\n{\n action(\"viewer_copy\")->setEnabled(!selectedText().isEmpty());\n}\n\nvoid Viewer::slotOpenLinkInternal()\n{\n openURL(m_url);\n}\n\nvoid Viewer::slotOpenLinkInForegroundTab()\n{\n emit urlClicked(m_url, false);\n}\n\nvoid Viewer::slotOpenLinkInBackgroundTab()\n{\n emit urlClicked(m_url, true);\n}\n\nvoid Viewer::slotOpenLinkInBrowser()\n{\n displayInExternalBrowser(m_url, QString::null);\n}\n\nvoid Viewer::slotSaveLinkAs()\n{\n KURL tmp( m_url );\n\n if ( tmp.fileName(false).isEmpty() )\n tmp.setFileName( \"index.html\" );\n KParts::BrowserRun::simpleSave(tmp, tmp.fileName());\n}\n\nvoid Viewer::slotStarted(KIO::Job *)\n{\n widget()->setCursor( waitCursor );\n}\n\nvoid Viewer::slotCompleted()\n{\n widget()->unsetCursor();\n}\n\nvoid Viewer::slotScrollUp()\n{\n view()->scrollBy(0,-10);\n}\n\nvoid Viewer::slotScrollDown()\n{\n view()->scrollBy(0,10);\n}\n\nvoid Viewer::slotZoomIn()\n{\n int zf = zoomFactor();\n if (zf < 100)\n {\n zf = zf - (zf % 20) + 20;\n setZoomFactor(zf);\n }\n else\n {\n zf = zf - (zf % 50) + 50;\n setZoomFactor(zf < 300 ? zf : 300);\n }\n}\n\nvoid Viewer::slotZoomOut()\n{\n int zf = zoomFactor();\n if (zf <= 100)\n {\n zf = zf - (zf % 20) - 20;\n setZoomFactor(zf > 20 ? zf : 20);\n }\n else\n {\n zf = zf - (zf % 50) - 50;\n setZoomFactor(zf);\n }\n}\n\nvoid Viewer::slotSetZoomFactor(int percent)\n{\n setZoomFactor(percent);\n}\n\n\/\/ some code taken from KDevelop (lib\/widgets\/kdevhtmlpart.cpp)\nvoid Viewer::slotPrint( )\n{\n view()->print();\n}\n\n\nvoid Viewer::setSafeMode()\n{\n setJScriptEnabled(false);\n setJavaEnabled(false);\n setMetaRefreshEnabled(false);\n setPluginsEnabled(false);\n setDNDEnabled(true);\n setAutoloadImages(true);\n setStatusMessagesEnabled(false);\n}\n\n#include \"viewer.moc\"\n\n\/\/ vim: set et ts=4 sts=4 sw=4:\n<commit_msg>show context menus correctly for selections and !isLink case<commit_after>\/*\n This file is part of Akregator.\n\n Copyright (C) 2004 Teemu Rytilahti <tpr@d5k.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <kaction.h>\n#include <kapplication.h>\n#include <kfiledialog.h>\n#include <khtmlview.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <kprocess.h>\n#include <krun.h>\n#include <kshell.h>\n#include <kurl.h>\n#include <kparts\/browserextension.h>\n\n#include <qaccel.h>\n#include <qclipboard.h>\n#include <qpaintdevicemetrics.h>\n\n#include \"viewer.h\"\n#include \"akregator_run.h\"\n#include \"akregatorconfig.h\"\n\nusing namespace Akregator;\n\nViewer::Viewer(QWidget *parent, const char *name)\n : KHTMLPart(parent, name), m_url(0)\n{\n setZoomFactor(100);\n setJScriptEnabled(true);\n setJavaEnabled(true);\n setMetaRefreshEnabled(true);\n setPluginsEnabled(true);\n setDNDEnabled(true);\n setAutoloadImages(true);\n setStatusMessagesEnabled(true);\n\n \/\/ change the cursor when loading stuff...\n connect( this, SIGNAL(started(KIO::Job *)),\n this, SLOT(slotStarted(KIO::Job *)));\n connect( this, SIGNAL(completed()),\n this, SLOT(slotCompleted()));\n\n connect( browserExtension(), SIGNAL(openURLRequestDelayed(const KURL&, const KParts::URLArgs&)), this, SLOT(slotOpenURLRequest(const KURL&, const KParts::URLArgs& )) );\n\n connect( browserExtension(),\n\nSIGNAL(popupMenu (KXMLGUIClient*, const QPoint&, const KURL&, const\n KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)), this, SLOT(slotPopupMenu(KXMLGUIClient*, const QPoint&, const KURL&, const\n KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)));\n\n KStdAction::print(this, SLOT(slotPrint()), actionCollection(), \"viewer_print\");\n KStdAction::copy(this, SLOT(slotCopy()), actionCollection(), \"viewer_copy\");\n \n new KAction( i18n(\"&Increase Font Sizes\"), \"viewmag+\", \"Ctrl+Plus\", this, SLOT(slotZoomIn()), actionCollection(), \"incFontSizes\" );\n new KAction( i18n(\"&Decrease Font Sizes\"), \"viewmag-\", \"Ctrl+Minus\", this, SLOT(slotZoomOut()), actionCollection(), \"decFontSizes\" );\n\n connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged()));\n\n new KAction(i18n(\"Copy &Link Address\"), \"\", 0,\n this, SLOT(slotCopyLinkAddress()),\n actionCollection(), \"copylinkaddress\");\n new KAction(i18n(\"&Save Link As...\"), \"\", 0,\n this, SLOT(slotSaveLinkAs()),\n actionCollection(), \"savelinkas\");\n}\n\nViewer::~Viewer()\n{}\n\nbool Viewer::openURL(const KURL &url)\n{\n new Akregator::BrowserRun(this, (QWidget*)parent(), this, url, browserExtension()->urlArgs());\n emit started(0);\n return true;\n}\n\n\nbool Viewer::closeURL()\n{\n emit browserExtension()->loadingProgress(-1);\n emit canceled(QString::null);\n return KHTMLPart::closeURL();\n}\n\nint Viewer::pointsToPixel(int pointSize) const\n{\n const QPaintDeviceMetrics metrics(view());\n return ( pointSize * metrics.logicalDpiY() + 36 ) \/ 72 ;\n}\n\nvoid Viewer::displayInExternalBrowser(const KURL &url, const QString &mimetype)\n{\n if (!url.isValid()) return;\n if (Settings::externalBrowserUseKdeDefault())\n {\n if (mimetype.isEmpty()) \n kapp->invokeBrowser(url.url(), \"0\");\n else\n KRun::runURL(url, mimetype, false, false);\n }\n else\n {\n QString cmd = Settings::externalBrowserCustomCommand();\n QString urlStr = url.url();\n cmd.replace(QRegExp(\"%u\"), urlStr);\n KProcess *proc = new KProcess;\n QStringList cmdAndArgs = KShell::splitArgs(cmd);\n *proc << cmdAndArgs;\n proc->start(KProcess::DontCare);\n delete proc;\n }\n}\n\n\nvoid Viewer::slotOpenURLRequest(const KURL& url, const KParts::URLArgs& args)\n{\n m_url = url;\n browserExtension()->setURLArgs(args);\n if (args.frameName == \"_blank\") \/\/ apparently this indicates that the MMB was pressed...\n {\n switch (Settings::mMBBehaviour())\n {\n case Settings::EnumMMBBehaviour::OpenInExternalBrowser:\n slotOpenLinkInBrowser();\n break;\n case Settings::EnumMMBBehaviour::OpenInBackground:\n slotOpenLinkInBackgroundTab();\n break;\n default:\n slotOpenLinkInForegroundTab();\n break;\n }\n }\n else \/\/ LMB:\n {\n switch (Settings::lMBBehaviour())\n {\n case Settings::EnumLMBBehaviour::OpenInExternalBrowser:\n slotOpenLinkInBrowser();\n break;\n case Settings::EnumLMBBehaviour::OpenInBackground:\n slotOpenLinkInBackgroundTab();\n break;\n default:\n slotOpenLinkInForegroundTab();\n break;\n }\n }\n}\n\nvoid Viewer::slotPopupMenu(KXMLGUIClient*, const QPoint& p, const KURL& kurl, const KParts::URLArgs&, KParts::BrowserExtension::PopupFlags kpf, mode_t)\n{\n const bool isLink = (kpf & KParts::BrowserExtension::ShowNavigationItems) == 0;\n const bool isSelection = (kpf & KParts::BrowserExtension::ShowTextSelectionItems) != 0;\n \n QString url = kurl.url();\n \n m_url = url;\n KPopupMenu popup;\n \n if (isLink && !isSelection)\n {\n popup.insertItem(SmallIcon(\"tab_new\"), i18n(\"Open Link in New &Tab\"), this, SLOT(slotOpenLinkInForegroundTab()));\n popup.insertItem(SmallIcon(\"window_new\"), i18n(\"Open Link in External &Browser\"), this, SLOT(slotOpenLinkInBrowser()));\n popup.insertSeparator();\n action(\"savelinkas\")->plug(&popup);\n action(\"copylinkaddress\")->plug(&popup);\n }\n else\n {\n if (isSelection)\n {\n action(\"viewer_copy\")->plug(&popup);\n popup.insertSeparator();\n }\n action(\"viewer_print\")->plug(&popup);\n KAction *ac = action(\"setEncoding\");\n if (ac)\n ac->plug(&popup);\n }\n popup.exec(p);\n}\n\n\/\/ taken from KDevelop\nvoid Viewer::slotCopy()\n{\n QString text = selectedText();\n text.replace( QChar( 0xa0 ), ' ' );\n QClipboard *cb = QApplication::clipboard();\n disconnect( cb, SIGNAL( selectionChanged() ), this, SLOT( slotClearSelection() ) );\n cb->setText(text);\n connect( cb, SIGNAL( selectionChanged() ), this, SLOT( slotClearSelection() ) );\n}\n\nvoid Viewer::slotCopyLinkAddress()\n{\n if(m_url.isEmpty()) return;\n QClipboard *cb = QApplication::clipboard();\n cb->setText(m_url.prettyURL(), QClipboard::Clipboard);\n cb->setText(m_url.prettyURL(), QClipboard::Selection);\n}\n\nvoid Viewer::slotSelectionChanged()\n{\n action(\"viewer_copy\")->setEnabled(!selectedText().isEmpty());\n}\n\nvoid Viewer::slotOpenLinkInternal()\n{\n openURL(m_url);\n}\n\nvoid Viewer::slotOpenLinkInForegroundTab()\n{\n emit urlClicked(m_url, false);\n}\n\nvoid Viewer::slotOpenLinkInBackgroundTab()\n{\n emit urlClicked(m_url, true);\n}\n\nvoid Viewer::slotOpenLinkInBrowser()\n{\n displayInExternalBrowser(m_url, QString::null);\n}\n\nvoid Viewer::slotSaveLinkAs()\n{\n KURL tmp( m_url );\n\n if ( tmp.fileName(false).isEmpty() )\n tmp.setFileName( \"index.html\" );\n KParts::BrowserRun::simpleSave(tmp, tmp.fileName());\n}\n\nvoid Viewer::slotStarted(KIO::Job *)\n{\n widget()->setCursor( waitCursor );\n}\n\nvoid Viewer::slotCompleted()\n{\n widget()->unsetCursor();\n}\n\nvoid Viewer::slotScrollUp()\n{\n view()->scrollBy(0,-10);\n}\n\nvoid Viewer::slotScrollDown()\n{\n view()->scrollBy(0,10);\n}\n\nvoid Viewer::slotZoomIn()\n{\n int zf = zoomFactor();\n if (zf < 100)\n {\n zf = zf - (zf % 20) + 20;\n setZoomFactor(zf);\n }\n else\n {\n zf = zf - (zf % 50) + 50;\n setZoomFactor(zf < 300 ? zf : 300);\n }\n}\n\nvoid Viewer::slotZoomOut()\n{\n int zf = zoomFactor();\n if (zf <= 100)\n {\n zf = zf - (zf % 20) - 20;\n setZoomFactor(zf > 20 ? zf : 20);\n }\n else\n {\n zf = zf - (zf % 50) - 50;\n setZoomFactor(zf);\n }\n}\n\nvoid Viewer::slotSetZoomFactor(int percent)\n{\n setZoomFactor(percent);\n}\n\n\/\/ some code taken from KDevelop (lib\/widgets\/kdevhtmlpart.cpp)\nvoid Viewer::slotPrint( )\n{\n view()->print();\n}\n\n\nvoid Viewer::setSafeMode()\n{\n setJScriptEnabled(false);\n setJavaEnabled(false);\n setMetaRefreshEnabled(false);\n setPluginsEnabled(false);\n setDNDEnabled(true);\n setAutoloadImages(true);\n setStatusMessagesEnabled(false);\n}\n\n#include \"viewer.moc\"\n\n\/\/ vim: set et ts=4 sts=4 sw=4:\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n\/\/ Disable \"'this': used in base member initializer list\"\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning(disable: 4355)\n#endif\n\n#include \"sessionservice.hpp\"\n#include \"servicedirectoryclient.hpp\"\n#include \"objectregistrar.hpp\"\n#include \"remoteobject_p.hpp\"\n\nqiLogCategory(\"qimessaging.sessionservice\");\n\nnamespace qi {\n\n inline void sessionServiceWaitBarrier(Session_Service* ptr) {\n ptr->_destructionBarrier.setValue(0);\n }\n Session_Service::Session_Service(TransportSocketCache *socketCache, ServiceDirectoryClient *sdClient, ObjectRegistrar *server)\n : _socketCache(socketCache)\n , _sdClient(sdClient)\n , _server(server)\n , _self(this, sessionServiceWaitBarrier) \/\/ create a shared_ptr so that shared_from_this works\n {\n _linkServiceRemoved = _sdClient->serviceRemoved.connect(boost::bind<void>(&Session_Service::onServiceRemoved, this, _1, _2));\n }\n\n Session_Service::~Session_Service()\n {\n _sdClient->serviceRemoved.disconnect(_linkServiceRemoved);\n _self.reset(); \/\/ now existing weak_ptrs cannot from this cannot be locked\n _destructionBarrier.future().wait();\n close();\n }\n\n void Session_Service::onServiceRemoved(const unsigned int &index, const std::string &service) {\n qiLogVerbose() << \"Remote Service Removed:\" << service << \" #\" << index;\n removeService(service);\n }\n\n void Session_Service::removeService(const std::string &service) {\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(service);\n if (it != _remoteObjects.end()) {\n qiLogVerbose() << \"Session: Removing cached RemoteObject \" << service;\n _remoteObjects.erase(it);\n }\n }\n }\n\n void Session_Service::close() {\n \/\/cleanup all RemoteObject\n \/\/they are not valid anymore after this function\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.begin();\n for (; it != _remoteObjects.end(); ++it) {\n reinterpret_cast<RemoteObject*>(it->second->value)->close();\n }\n _remoteObjects.clear();\n }\n }\n\n ServiceRequest *Session_Service::serviceRequest(long requestId)\n {\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n {\n std::map<int, ServiceRequest*>::iterator it;\n\n it = _requests.find(requestId);\n if (it == _requests.end()) {\n qiLogVerbose() << \"qi.session.service(): No matching request for id(\" << requestId << \").\";\n return 0;\n }\n return it->second;\n }\n }\n\n static void deleteLater(qi::RemoteObject *remote) {\n delete remote;\n }\n\n void Session_Service::removeRequest(long requestId)\n {\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n qi::RemoteObject *remote = 0;\n ServiceRequest *sr = 0;\n {\n std::map<int, ServiceRequest*>::iterator it;\n\n it = _requests.find(requestId);\n if (it == _requests.end()) {\n qiLogVerbose() << \"qi.session.service(): No matching request for id(\" << requestId << \").\";\n return;\n }\n if (it->second) {\n remote = it->second->remoteObject;\n it->second->remoteObject = 0;\n }\n sr = it->second;\n it->second = 0;\n _requests.erase(it);\n }\n \/\/we do not call delete on RemoteObject, because remoteObject->close disconnect onMessagePending,\n \/\/which is the signal we are coming from. (when called from onRemoteObjectComplete)\n \/\/delete later as a workaround.\n qi::getDefaultNetworkEventLoop()->post(boost::bind(&deleteLater, remote));\n delete sr;\n }\n\n void Session_Service::onTransportSocketResult(qi::Future<TransportSocketPtr> value, long requestId) {\n qiLogDebug() << \"Got transport socket for service\";\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n\n if (value.hasError()) {\n sr->promise.setError(value.error());\n removeRequest(requestId);\n return;\n }\n\n sr->remoteObject = new qi::RemoteObject(sr->serviceId, value.value());\n\n \/\/ask the remoteObject to fetch the metaObject\n qi::Future<void> fut = sr->remoteObject->fetchMetaObject();\n fut.connect(boost::bind<void>(&Session_Service::onRemoteObjectComplete, this, _1, requestId));\n }\n\n void Session_Service::onRemoteObjectComplete(qi::Future<void> future, long requestId) {\n qiLogDebug() << \"Got metaobject\";\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n\n if (future.hasError()) {\n sr->promise.setError(future.error());\n removeRequest(requestId);\n return;\n }\n\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(sr->name);\n if (it != _remoteObjects.end()) {\n \/\/another object have been registered before us, return it\n \/\/the new socket will be closed when the request is deleted\n qiLogVerbose() << \"A request for the service \" << sr->name << \" have been discarded, \"\n << \"the remoteobject on the service was already available.\";\n sr->promise.setValue(it->second);\n } else {\n\n AnyObject o = makeDynamicAnyObject(sr->remoteObject);\n \/\/register the remote object in the cache\n _remoteObjects[sr->name] = o;\n sr->promise.setValue(o);\n sr->remoteObject = 0;\n }\n }\n\n removeRequest(requestId);\n }\n\n inline void onServiceInfoResultIfExists(Session_Service* s, qi::Future<qi::ServiceInfo> f,\n long requestId, std::string protocol, boost::weak_ptr<Session_Service> self)\n {\n boost::shared_ptr<Session_Service> sself = self.lock();\n if (sself)\n sself->onServiceInfoResult(f, requestId, protocol);\n }\n\n \/\/ We received a ServiceInfo, and want to establish a connection\n void Session_Service::onServiceInfoResult(qi::Future<qi::ServiceInfo> result, long requestId, std::string protocol) {\n qiLogDebug() << \"Got serviceinfo message\";\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n if (result.hasError()) {\n sr->promise.setError(result.error());\n removeRequest(requestId);\n return;\n }\n const qi::ServiceInfo &si = result.value();\n sr->serviceId = si.serviceId();\n \/\/empty serviceInfo\n if (!si.endpoints().size()) {\n std::stringstream ss;\n ss << \"No endpoints returned for service:\" << sr->name << \" (id:\" << sr->serviceId << \")\";\n qiLogVerbose() << ss.str();\n sr->promise.setError(ss.str());\n removeRequest(requestId);\n return;\n }\n\n if (protocol != \"\")\n {\n std::vector<qi::Url>::const_iterator it = si.endpoints().begin();\n\n for (;\n it != si.endpoints().end() && it->protocol() != protocol;\n it++)\n {\n continue;\n }\n\n if (it == si.endpoints().end())\n {\n std::stringstream ss;\n ss << \"No \" << protocol << \" endpoint available for service:\" << sr->name << \" (id:\" << sr->serviceId << \")\";\n qiLogVerbose(\"session.service\") << ss.str();\n sr->promise.setError(ss.str());\n }\n }\n\n qiLogDebug() << \"Requesting socket from cache\";\n qi::Future<qi::TransportSocketPtr> fut = _socketCache->socket(si, protocol);\n fut.connect(boost::bind<void>(&Session_Service::onTransportSocketResult, this, _1, requestId));\n }\n\n qi::Future<qi::AnyObject> Session_Service::service(const std::string &service,\n const std::string &protocol)\n {\n qi::Future<qi::AnyObject> result;\n if (protocol == \"\" || protocol == \"local\") {\n \/\/qiLogError() << \"service is not implemented for local service, it always return a remote service\";\n \/\/look for local object registered in the server\n qi::AnyObject go = _server->registeredServiceObject(service);\n if (go)\n return qi::Future<qi::AnyObject>(go);\n if (protocol == \"local\") {\n qi::Promise<qi::AnyObject> prom;\n prom.setError(std::string(\"No local object found for \") + service);\n return prom.future();\n }\n }\n\n \/\/look for already registered remote objects\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(service);\n if (it != _remoteObjects.end()) {\n return qi::Future<qi::AnyObject>(it->second);\n }\n }\n\n {\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n std::map<int, ServiceRequest*>::const_iterator it;\n for (it = _requests.begin(); it != _requests.end(); ++it)\n {\n if (it->second->name == service)\n {\n return it->second->promise.future();\n }\n }\n }\n\n qi::Future<qi::ServiceInfo> fut = _sdClient->service(service);\n ServiceRequest *rq = new ServiceRequest(service);\n long requestId = ++_requestsIndex;\n\n {\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n _requests[requestId] = rq;\n }\n result = rq->promise.future();\n \/\/rq is not valid anymore after addCallbacks, because it could have been handled and cleaned\n fut.connect(boost::bind<void>(&onServiceInfoResultIfExists, this, _1, requestId, protocol, boost::weak_ptr<Session_Service>(_self)));\n return result;\n }\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n<commit_msg>sessionservice: fix a deadlock<commit_after>\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n\/\/ Disable \"'this': used in base member initializer list\"\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning(disable: 4355)\n#endif\n\n#include \"sessionservice.hpp\"\n#include \"servicedirectoryclient.hpp\"\n#include \"objectregistrar.hpp\"\n#include \"remoteobject_p.hpp\"\n\nqiLogCategory(\"qimessaging.sessionservice\");\n\nnamespace qi {\n\n inline void sessionServiceWaitBarrier(Session_Service* ptr) {\n ptr->_destructionBarrier.setValue(0);\n }\n Session_Service::Session_Service(TransportSocketCache *socketCache, ServiceDirectoryClient *sdClient, ObjectRegistrar *server)\n : _socketCache(socketCache)\n , _sdClient(sdClient)\n , _server(server)\n , _self(this, sessionServiceWaitBarrier) \/\/ create a shared_ptr so that shared_from_this works\n {\n _linkServiceRemoved = _sdClient->serviceRemoved.connect(boost::bind<void>(&Session_Service::onServiceRemoved, this, _1, _2));\n }\n\n Session_Service::~Session_Service()\n {\n _sdClient->serviceRemoved.disconnect(_linkServiceRemoved);\n _self.reset(); \/\/ now existing weak_ptrs cannot from this cannot be locked\n _destructionBarrier.future().wait();\n close();\n }\n\n void Session_Service::onServiceRemoved(const unsigned int &index, const std::string &service) {\n qiLogVerbose() << \"Remote Service Removed:\" << service << \" #\" << index;\n removeService(service);\n }\n\n void Session_Service::removeService(const std::string &service) {\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(service);\n if (it != _remoteObjects.end()) {\n qiLogVerbose() << \"Session: Removing cached RemoteObject \" << service;\n _remoteObjects.erase(it);\n }\n }\n }\n\n void Session_Service::close() {\n \/\/cleanup all RemoteObject\n \/\/they are not valid anymore after this function\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.begin();\n for (; it != _remoteObjects.end(); ++it) {\n reinterpret_cast<RemoteObject*>(it->second->value)->close();\n }\n _remoteObjects.clear();\n }\n }\n\n ServiceRequest *Session_Service::serviceRequest(long requestId)\n {\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n {\n std::map<int, ServiceRequest*>::iterator it;\n\n it = _requests.find(requestId);\n if (it == _requests.end()) {\n qiLogVerbose() << \"qi.session.service(): No matching request for id(\" << requestId << \").\";\n return 0;\n }\n return it->second;\n }\n }\n\n static void deleteLater(qi::RemoteObject *remote) {\n delete remote;\n }\n\n void Session_Service::removeRequest(long requestId)\n {\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n qi::RemoteObject *remote = 0;\n ServiceRequest *sr = 0;\n {\n std::map<int, ServiceRequest*>::iterator it;\n\n it = _requests.find(requestId);\n if (it == _requests.end()) {\n qiLogVerbose() << \"qi.session.service(): No matching request for id(\" << requestId << \").\";\n return;\n }\n if (it->second) {\n remote = it->second->remoteObject;\n it->second->remoteObject = 0;\n }\n sr = it->second;\n it->second = 0;\n _requests.erase(it);\n }\n \/\/we do not call delete on RemoteObject, because remoteObject->close disconnect onMessagePending,\n \/\/which is the signal we are coming from. (when called from onRemoteObjectComplete)\n \/\/delete later as a workaround.\n qi::getDefaultNetworkEventLoop()->post(boost::bind(&deleteLater, remote));\n delete sr;\n }\n\n void Session_Service::onTransportSocketResult(qi::Future<TransportSocketPtr> value, long requestId) {\n qiLogDebug() << \"Got transport socket for service\";\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n\n if (value.hasError()) {\n sr->promise.setError(value.error());\n removeRequest(requestId);\n return;\n }\n\n sr->remoteObject = new qi::RemoteObject(sr->serviceId, value.value());\n\n \/\/ask the remoteObject to fetch the metaObject\n qi::Future<void> fut = sr->remoteObject->fetchMetaObject();\n fut.connect(boost::bind<void>(&Session_Service::onRemoteObjectComplete, this, _1, requestId));\n }\n\n void Session_Service::onRemoteObjectComplete(qi::Future<void> future, long requestId) {\n qiLogDebug() << \"Got metaobject\";\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n\n if (future.hasError()) {\n sr->promise.setError(future.error());\n removeRequest(requestId);\n return;\n }\n\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(sr->name);\n if (it != _remoteObjects.end()) {\n \/\/another object have been registered before us, return it\n \/\/the new socket will be closed when the request is deleted\n qiLogVerbose() << \"A request for the service \" << sr->name << \" have been discarded, \"\n << \"the remoteobject on the service was already available.\";\n sr->promise.setValue(it->second);\n } else {\n\n AnyObject o = makeDynamicAnyObject(sr->remoteObject);\n \/\/register the remote object in the cache\n _remoteObjects[sr->name] = o;\n sr->promise.setValue(o);\n sr->remoteObject = 0;\n }\n }\n\n removeRequest(requestId);\n }\n\n inline void onServiceInfoResultIfExists(Session_Service* s, qi::Future<qi::ServiceInfo> f,\n long requestId, std::string protocol, boost::weak_ptr<Session_Service> self)\n {\n boost::shared_ptr<Session_Service> sself = self.lock();\n if (sself)\n sself->onServiceInfoResult(f, requestId, protocol);\n }\n\n \/\/ We received a ServiceInfo, and want to establish a connection\n void Session_Service::onServiceInfoResult(qi::Future<qi::ServiceInfo> result, long requestId, std::string protocol) {\n qiLogDebug() << \"Got serviceinfo message\";\n {\n boost::recursive_mutex::scoped_lock sl(_requestsMutex);\n ServiceRequest *sr = serviceRequest(requestId);\n if (!sr)\n return;\n if (result.hasError()) {\n sr->promise.setError(result.error());\n removeRequest(requestId);\n return;\n }\n const qi::ServiceInfo &si = result.value();\n sr->serviceId = si.serviceId();\n \/\/empty serviceInfo\n if (!si.endpoints().size()) {\n std::stringstream ss;\n ss << \"No endpoints returned for service:\" << sr->name << \" (id:\" << sr->serviceId << \")\";\n qiLogVerbose() << ss.str();\n sr->promise.setError(ss.str());\n removeRequest(requestId);\n return;\n }\n\n if (protocol != \"\")\n {\n std::vector<qi::Url>::const_iterator it = si.endpoints().begin();\n\n for (;\n it != si.endpoints().end() && it->protocol() != protocol;\n it++)\n {\n continue;\n }\n\n if (it == si.endpoints().end())\n {\n std::stringstream ss;\n ss << \"No \" << protocol << \" endpoint available for service:\" << sr->name << \" (id:\" << sr->serviceId << \")\";\n qiLogVerbose(\"session.service\") << ss.str();\n sr->promise.setError(ss.str());\n }\n }\n }\n qiLogDebug() << \"Requesting socket from cache\";\n qi::Future<qi::TransportSocketPtr> fut = _socketCache->socket(result.value(), protocol);\n fut.connect(boost::bind<void>(&Session_Service::onTransportSocketResult, this, _1, requestId));\n }\n\n qi::Future<qi::AnyObject> Session_Service::service(const std::string &service,\n const std::string &protocol)\n {\n qi::Future<qi::AnyObject> result;\n if (protocol == \"\" || protocol == \"local\") {\n \/\/qiLogError() << \"service is not implemented for local service, it always return a remote service\";\n \/\/look for local object registered in the server\n qi::AnyObject go = _server->registeredServiceObject(service);\n if (go)\n return qi::Future<qi::AnyObject>(go);\n if (protocol == \"local\") {\n qi::Promise<qi::AnyObject> prom;\n prom.setError(std::string(\"No local object found for \") + service);\n return prom.future();\n }\n }\n\n \/\/look for already registered remote objects\n {\n boost::mutex::scoped_lock sl(_remoteObjectsMutex);\n RemoteObjectMap::iterator it = _remoteObjects.find(service);\n if (it != _remoteObjects.end()) {\n return qi::Future<qi::AnyObject>(it->second);\n }\n }\n\n {\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n std::map<int, ServiceRequest*>::const_iterator it;\n for (it = _requests.begin(); it != _requests.end(); ++it)\n {\n if (it->second->name == service)\n {\n return it->second->promise.future();\n }\n }\n }\n\n qi::Future<qi::ServiceInfo> fut = _sdClient->service(service);\n ServiceRequest *rq = new ServiceRequest(service);\n long requestId = ++_requestsIndex;\n\n {\n boost::recursive_mutex::scoped_lock l(_requestsMutex);\n _requests[requestId] = rq;\n }\n result = rq->promise.future();\n \/\/rq is not valid anymore after addCallbacks, because it could have been handled and cleaned\n fut.connect(boost::bind<void>(&onServiceInfoResultIfExists, this, _1, requestId, protocol, boost::weak_ptr<Session_Service>(_self)));\n return result;\n }\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * simulation.cpp\n *\n * Created on: Nov 23, 2014\n * Author: tony\n *\/\n\n#include <iostream>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::flush;\nusing std::string;\n\n#include <sim\/simulation.h>\n\n\n\n\nsimulation::simulation(const unsigned int type, const unsigned int n,\n\t\tconst double* par, const string folder, const string fpre) :\n\t\t\t\t\t\t\t\tsim_type( type ),\n\t\t\t\t\t\t\t\tnCell( n ),\n\t\t\t\t\t\t\t\tfolderName(folder){\n\tmycells = new cellmodel::Cells( nCell, this , par );\n\tif (nCell==1) {\n\t\tnCellOutputs = 1;\n\t\tnCellsToOutput = new unsigned int[nCellOutputs];\n\t\tnCellsToOutput[0] = 0;\n\t\tfiles = new filesStruct(folder, fpre, 1 );\n\t} else {\n\t\tnCellOutputs = 5;\n\t\tnCellsToOutput = new unsigned int[nCellOutputs];\n\t\tnCellsToOutput[0] = 0;\n\t\tnCellsToOutput[1] = nCell\/(nCellOutputs-1);\n\t\tfor (unsigned int i=2; i<nCellOutputs-1; i++)\n\t\t\tnCellsToOutput[i] = nCellsToOutput[i-1] + nCellsToOutput[1];\n\t\tnCellsToOutput[nCellOutputs-1] = nCell-1;\n\t\tfiles = new filesStruct(folder, fpre, nCellOutputs \/* # of cell files *\/);\n\t}\n\t\/\/ The next line assumes all cells have the same number of states\n\tconst unsigned int nstates = mycells->getNstates();\n\tneqns = nstates * nCell;\n\tYold\t= new double[neqns];\n\tYnew\t= new double[neqns];\n}\n\nsimulation::~simulation(){\n\t\/\/ Deallocate work space\n\tdelete[] Yold;\n\tdelete[] Ynew;\n\n\tdelete[] nCellsToOutput;\n\tdelete files;\n\tdelete mycells;\n}\n\nvoid simulation::SetInitialConditions(){\n\t\/\/ Load in initial conditions for each cell in the array\n\tmycells->SetInitialConditions();\n\n\tswitch (sim_type){\n\tcase 0:\n\t\t\/\/ Sim type 0 is for initial conditions set in code - no file read.\n\t\tbreak;\n\tcase 1:\n\t\t\/\/ Read in file containing state of 1 cell\n\t\t\/\/ Sim type 1 typically uses the state of a single cell to set\n\t\t\/\/ the states of all the cells in a cable\n\t\t\/\/ We need to set the initial conditions first - done above - and then\n\t\t\/\/ reset the values using the data from the input file\n\t\t\/\/ This is because we use references in the Cell class\/struct\n\t\t\/\/ Reading references from the input file does not work.\n\t\treadsinglecell( );\n\t\tbreak;\n\tcase 2:\n\t\t\/\/ Sim type 2 starts up from last cable state - read in the\n\t\t\/\/ states of all cells from a file\n\t\treadcells( );\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\t\/\/ Get a complete copy of all the state variables of all the cells\n\tmycells->getStateFromCells( Yold );\n}\n\n\n\nvoid simulation::printcellAux(ofstream& of, const double t, Cell& c) {\n\tof << t << \", \"\n\t\t\t<< c.getV() << \", \" << c.getI_K1() << \", \" << c.getI_Na() << \", \"\n\t\t\t<< c.getI_axnm1() << \", \" << c.getI_axnp1() << \", \" << c.getI_axial()\n\t\t\t<< endl;\n}\n\nvoid simulation::printcellEAD(ofstream& of, Cell& c, Cell& c2, int r, int p, double S1) {\n\tdouble th_diff = 0;\n\tif (r == 0)\n\t\tth_diff = 1000 * 0.01 \/ (c.t_thr - c2.t_thr);\n\telse\n\t\tth_diff = 1000 * 0.01 \/ (c2.t_thr - c.t_thr); \/\/ special case for Cell[0]\n\n\tof << c.t_min << \", \" << c.V_min << \", \" << c.t_thr << \", \" << c.V_thr\n\t\t\t<< \", \" << c.t_max << \", \" << c.V_max << \", \" << c.t_90 << \", \"\n\t\t\t<< c.V_90 << \", \" << c.t_EAD << \", \" << c.V_EAD << \", \" << c.t_EAD2\n\t\t\t<< \", \" << c.V_EAD2 << \", \" << c.L_EAD << \", \" << c.APD_90 << \", \"\n\t\t\t<< c.DI << \", \" << p << \", \" << S1 << \" , \" << th_diff << \", \"\n\t\t\t<< c.peak_slope << endl;\n}\n\n\/*\n * savecells\n *\/\nvoid simulation::savecells( ) {\n\t\/\/ if n == 1 --> save a single cell state\n\t\/\/ n > 1 --> save multiple cells state\n\tconst unsigned int ncells = mycells->getNcells();\n\tconst char *f = (ncells==1)\t? (folderName + \"\/\" + cellstateFileName).c_str()\n\t\t\t\t\t\t\t\t: (folderName + \"\/\" + stateFileName).c_str();\n\tcout << \" Writing to: \" << f << \". \";\n\tFILE *fp = fopen(f, \"wb\");\n\tint nw=0;\n\tfor (unsigned int i = 0; i < ncells; i++) {\n\t\tCell temp = mycells->getCell( i );\n\t\tnw += fwrite(temp.state, sizeof(Cell::state), 1, fp);\n\t}\n\tfclose(fp);\n\tstd::cout << \" Wrote state of \" << nw << \" cell(s)\" << std::endl << flush;\n}\n\nvoid simulation::readcells( ) {\n\tconst char *f = (folderName + \"\/\" + stateFileName).c_str();\n\tconst unsigned int ncells = mycells->getNcells();\n\n\tcout << \" Reading data for \" << ncells << \" cells from \" << f << \".\";\n\tFILE *fp = fopen(f, \"r\");\n\tint nr = 0;\n\tunsigned int ntotal = 0;\n\t\/\/ References are messed up after reading structs from a file\n\tfor (unsigned int i = 0; i < ncells; i++) {\n\t\tCell temp;\n\t\tnr = fread(temp.state, sizeof(Cell::state), 1, fp);\n\t\tif (nr <= 0)\n\t\t\tbreak;\n\t\tmycells->copyCell( i, temp);\n\t\tntotal++;\n\t}\n\tfclose(fp);\n\tif (ntotal < ncells)\n\t\tcout << \" --> Read \" << nr << \" cells. \";\n\tcout << \" Done reading.\" << endl << flush;\n}\n\nvoid simulation::readsinglecell( ) {\n\tconst char *f = (folderName + \"\/\" + cellstateFileName).c_str();\n\tconst unsigned int ncells = mycells->getNcells();\n\n\tcout << \" Reading data for \" << ncells << \" cells from \" << f << \".\";\n\tFILE *fp = fopen(f, \"r\");\n\tCell temp;\n\tint nr = fread(temp.state, sizeof(Cell::state), 1, fp);\n\tswitch (nr){\n\tcase 0:\n\t\tcout << \" --> Could not read cell state!!! \";\n\t\tbreak;\n\tcase 1:\n\t\tcout << \" --> Read single cell state. \";\n\t\tmycells->copyCells( temp );\n\t\tbreak;\n\tdefault:\n\t\tcout << \" --> fread returned: \" << nr << \", cell state not changed.\";\n\t\tbreak;\n\t}\n\tfclose(fp);\n\tcout << \" Done setting cell states from file.\" << endl << flush;\n}\n\n\n\nvoid simulation::printEverything(const double time, const int cycle,\n\t\t\t\t\t const double interval, const int S2_cycle,\n\t\t\t\t\t int& counter ){\n\tcounter++;\n\tif ((counter % counterupdates) == 0) {\n\t\tcout << \".\";\n\t\t\/\/ Print auxilliary variables\n\t\tif ((counter % (printtimeupdate*counterupdates)) == 0){\n\t\t\t\/\/This file will have voltages against time for each cell\n\t\t\tmycells->printV( files->result, time );\n\t\t\tif (printMarkovIts)\n\t\t\t\tprintMarkovIterations( time );\n\n\t\t\t\/\/This file prints The Markov States for cell 50\n\t\t\tif (cycle > printMarkovStatesAfterCycle) {\n\t\t\t\tmycells->printNacell( files->Na, time, nCell\/2 );\n\t\t\t}\n\n\t\t\tcout << \"t=\" << time << \"msec\" << endl;\n\t\t\tfor (unsigned int i=0; i<nCellOutputs; i++){\n\t\t\t\tCell c = mycells->getCell( nCellsToOutput[i] );\n\t\t\t\tprintcellAux( *(files->cellAuxFs[ i ]), time, c );\n\t\t\t}\n\n\t\t\t\/* Used to be:\n\t\t\tCell c0 = mycells->getCell( n0p00 );\n\t\t\tprintcellAux( *(files->First), time, c0 );\n\t\t\tif (n0p25 > n0p00){\n\t\t\t\tCell c25 = mycells->getCell( n0p25 );\n\t\t\t\tprintcellAux( *(files->Quarter), time, c25 );\n\t\t\t\tif (n0p50 > n0p25){\n\t\t\t\t\tCell c50 = mycells->getCell( n0p50 );\n\t\t\t\t\tprintcellAux( *(files->Midpoint), time, c50 );\n\t\t\t\t\tif (n0p75 > n0p50){\n\t\t\t\t\t\tCell c75 = mycells->getCell( n0p75 );\n\t\t\t\t\t\tprintcellAux( *(files->Three4ths), time, c75 );\n\t\t\t\t\t\tif (n1p00 > n0p75){\n\t\t\t\t\t\t\tCell c99 = mycells->getCell( n1p00 );\n\t\t\t\t\t\t\tprintcellAux( *(files->Last), time, c99 );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t*\/\n\t\t}\n\n\t\tif ( (counter % (printCycleUpdate*printtimeupdate*counterupdates)) == 0){\n\t\t\tswitch (sim_type){\n\t\t\tcase 0:\n\t\t\t\tcout << \"Non-paced simulation, t=\" << time << \" end time= \";\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\t\tcout << \"Paced simulation, cycle: \" << cycle << \" of \" << MaxNumberOfBeats\n\t\t\t\t\t\t<< \", t=\" << time << \", this interval= \";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcounter = 0;\n\t\t\tcout << interval << \", [drug] is \" << drug << endl;\n\t\t}\n\t\tcout << flush;\n\t}\n\n\n\tif ( nCell > 1 ){\n\t\t\/\/This file is for individual cells that calculates all of the min, max, V_90 parameters.\n\t\tbool isPrintingNeeded = mycells->isPrintingNeeded();\n\t\tif (isPrintingNeeded) {\n\t\t\tmycells->printThreshold( 50, cycle );\n\n\t\t\tfor (unsigned int i=0; i<nCellOutputs; i++){\n\t\t\t\tunsigned int cellout = nCellsToOutput[i];\n\t\t\t\tunsigned int cellnext = 1;\n\t\t\t\tint flag = 0;\n\t\t\t\tif (nCellsToOutput[i] == 0 ){\n\t\t\t\t\t\/\/ For the 0th cell, the adjacent one is 1\n\t\t\t\t\tcellnext = nCellsToOutput[i] + 1;\n\t\t\t\t\tflag = 1;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ For the other cells, the adjacent one is the one before it\n\t\t\t\t\tcellnext = nCellsToOutput[i] - 1;\n\t\t\t\t}\n\n\t\t\t\tCell c = mycells->getCell( cellout );\n\t\t\t\tCell cadj = mycells->getCell( cellnext );\n\n\t\t\t\tprintcellEAD( *(files->EADFs[ i ]), c, cadj, flag, cellout, cycle );\n\t\t\t}\n\n\t\t\t\/* Used to be\n\t\t\tCell c0 = mycells->getCell( n0p00 );\n\t\t\tCell c1 = mycells->getCell( n0p00+1 );\n\t\t\tprintcell( *(files->EAD00), c0, c1, 1, 0, cycle );\n\t\t\tCell c25 = mycells->getCell( n0p25 );\n\t\t\tCell c24 = mycells->getCell( n0p25-1 );\n\t\t\tprintcell( *(files->EAD25), c25, c24, 0, 25, cycle );\n\t\t\tCell c50 = mycells->getCell( n0p50 );\n\t\t\tCell c49 = mycells->getCell( n0p50-1 );\n\t\t\tprintcell( *(files->EAD50), c50, c49, 0, 50, cycle );\n\t\t\tCell c75 = mycells->getCell( n0p75 );\n\t\t\tCell c74 = mycells->getCell( n0p75-1 );\n\t\t\tprintcell( *(files->EAD75), c75, c74, 0, 75, cycle );\n\t\t\tCell c99 = mycells->getCell( n1p00 );\n\t\t\tCell c98 = mycells->getCell( n1p00-1 );\n\t\t\tprintcell( *(files->EAD99), c99, c98, 0, nCell-1, cycle );\n\t\t\t*\/\n\n\t\t\tmycells->resetPrintFlag();\n\t\t\tisPrintingNeeded = false;\n\t\t} \/\/ End of individual result files\n\t}\n}\n\nbool simulation::step( const double told, const double tnew ){\n\tconst bool success = solve->step( told, tnew, Yold, Ynew );\n\tif (success) {\n\t\tif (solve->isInplace()) {\n\t\t\t\/\/ Get a copy of all the state variables of all the cells\n\t\t\tmycells->getStateFromCells( Yold );\n\t\t} else {\n\t\t\t\/\/ Update the old state to have the new values\n\t\t\tfor (unsigned int i=0; i<neqns; i++)\n\t\t\t\tYold[i] = Ynew[i];\n\t\t}\n\t}\n\treturn success;\n}\n\nvoid simulation::printCV(const double time, const int cycle){\n\tif ( nCell > 1 ){\n\t\tmycells->printCV( files->CV, cycle );\n\t}\n}\nvoid simulation::printMarkovIterations( const double t ){\n\tconst unsigned int ncells = mycells->getNcells();\n\t\/\/ find middle cell\n\tconst unsigned int middlecell = ncells\/2;\n\tCell c = mycells->getCell( middlecell);\n\/\/MarkovIterations should be in the rushlarsen object\n\t*(files->MarkovIterations) << t <<\", \" << c.MarkovIterations\n\t\t\t\t\t\t << \", \" << c.MarkovIterationError << endl;\n\t\/\/ reset markov iteration count\n}\n<commit_msg>Fixed up simulation.cpp<commit_after>\/*\n * simulation.cpp\n *\n * Created on: Nov 23, 2014\n * Author: tony\n *\/\n\n#include <iostream>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::flush;\nusing std::string;\n\n#include <sim\/simulation.h>\n\n\n\n\nsimulation::simulation(const unsigned int type, const unsigned int n,\n\t\tconst double* par, const string folder, const string fpre) :\n\t\t\t\t\t\t\t\tsim_type( type ),\n\t\t\t\t\t\t\t\tnCell( n ),\n\t\t\t\t\t\t\t\tfolderName(folder){\n\tmycells = new cellmodel::Cells( nCell, this , par );\n\tif (nCell==1) {\n\t\tnCellOutputs = 1;\n\t\tnCellsToOutput = new unsigned int[nCellOutputs];\n\t\tnCellsToOutput[0] = 0;\n\t\tfiles = new filesStruct(folder, fpre, 1 );\n\t} else {\n\t\tnCellOutputs = 5;\n\t\tnCellsToOutput = new unsigned int[nCellOutputs];\n\t\tnCellsToOutput[0] = 0;\n\t\tnCellsToOutput[1] = nCell\/(nCellOutputs-1);\n\t\tfor (unsigned int i=2; i<nCellOutputs-1; i++)\n\t\t\tnCellsToOutput[i] = nCellsToOutput[i-1] + nCellsToOutput[1];\n\t\tnCellsToOutput[nCellOutputs-1] = nCell-1;\n\t\tfiles = new filesStruct(folder, fpre, nCellOutputs \/* # of cell files *\/);\n\t}\n\t\/\/ The next line assumes all cells have the same number of states\n\tconst unsigned int nstates = mycells->getNstates();\n\tneqns = nstates * nCell;\n\tYold\t= new double[neqns];\n\tYnew\t= new double[neqns];\n}\n\nsimulation::~simulation(){\n\t\/\/ Deallocate work space\n\tdelete[] Yold;\n\tdelete[] Ynew;\n\n\tdelete[] nCellsToOutput;\n\tdelete files;\n\tdelete mycells;\n}\n\nvoid simulation::SetInitialConditions(){\n\t\/\/ Load in initial conditions for each cell in the array\n\tmycells->SetInitialConditions();\n\n\tswitch (sim_type){\n\tcase 0:\n\t\t\/\/ Sim type 0 is for initial conditions set in code - no file read.\n\t\tbreak;\n\tcase 1:\n\t\t\/\/ Read in file containing state of 1 cell\n\t\t\/\/ Sim type 1 typically uses the state of a single cell to set\n\t\t\/\/ the states of all the cells in a cable\n\t\t\/\/ We need to set the initial conditions first - done above - and then\n\t\t\/\/ reset the values using the data from the input file\n\t\t\/\/ This is because we use references in the Cell class\/struct\n\t\t\/\/ Reading references from the input file does not work.\n\t\treadsinglecell( );\n\t\tbreak;\n\tcase 2:\n\t\t\/\/ Sim type 2 starts up from last cable state - read in the\n\t\t\/\/ states of all cells from a file\n\t\treadcells( );\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\t\/\/ Get a complete copy of all the state variables of all the cells\n\tmycells->getStateFromCells( Yold );\n}\n\n\n\nvoid simulation::printcellAux(ofstream& of, const double t, Cell& c) {\n\tof << t << \", \"\n\t\t\t<< c.getV() << \", \" << c.getI_K1() << \", \" << c.getI_Na() << \", \"\n\t\t\t<< c.getI_axnm1() << \", \" << c.getI_axnp1() << \", \" << c.getI_axial()\n\t\t\t<< endl;\n}\n\nvoid simulation::printcellEAD(ofstream& of, Cell& c, Cell& c2, int r, int p, double S1) {\n\tdouble th_diff = 0;\n\tif (r == 0)\n\t\tth_diff = 1000 * 0.01 \/ (c.t_thr - c2.t_thr);\n\telse\n\t\tth_diff = 1000 * 0.01 \/ (c2.t_thr - c.t_thr); \/\/ special case for Cell[0]\n\n\tof << c.t_min << \", \" << c.V_min << \", \" << c.t_thr << \", \" << c.V_thr\n\t\t\t<< \", \" << c.t_max << \", \" << c.V_max << \", \" << c.t_90 << \", \"\n\t\t\t<< c.V_90 << \", \" << c.t_EAD << \", \" << c.V_EAD << \", \" << c.t_EAD2\n\t\t\t<< \", \" << c.V_EAD2 << \", \" << c.L_EAD << \", \" << c.APD_90 << \", \"\n\t\t\t<< c.DI << \", \" << p << \", \" << S1 << \" , \" << th_diff << \", \"\n\t\t\t<< c.peak_slope << endl;\n}\n\n\/*\n * savecells\n *\/\nvoid simulation::savecells( ) {\n\t\/\/ if n == 1 --> save a single cell state\n\t\/\/ n > 1 --> save multiple cells state\n\tconst unsigned int ncells = mycells->getNcells();\n\t\/\/ The following two lines resulted in f pointing to an empty string\n\t\/\/const char *f = (ncells==1)\t? (folderName + \"\/\" + cellstateFileName).c_str()\n\t\/\/\t\t\t\t\t\t\t: (folderName + \"\/\" + stateFileName).c_str();\n\n\tstring f = (ncells==1)\t? (folderName + \"\/\" + cellstateFileName)\n\t\t\t\t\t\t\t\t\t: (folderName + \"\/\" + stateFileName);\n\n\tcout << \" Writing to: \" << f << \". \" << flush;\n\tFILE *fp = fopen(f.c_str(), \"wb\");\n\tint nw=0;\n\tfor (unsigned int i = 0; i < ncells; i++) {\n\t\tCell temp = mycells->getCell( i );\n\t\tnw += fwrite(temp.state, sizeof(Cell::state), 1, fp);\n\t}\n\tfclose(fp);\n\tstd::cout << \" Wrote state of \" << nw << \" cell(s)\" << std::endl << flush;\n}\n\nvoid simulation::readcells( ) {\n\t\/\/ The next line resulted in f pointing to an empty string\n\t\/\/ const char *f = (folderName + \"\/\" + cellstateFileName).c_str();\n\tstring f = folderName + \"\/\" + cellstateFileName;\n\tconst unsigned int ncells = mycells->getNcells();\n\n\tcout << \" Reading data for \" << ncells << \" cells from \" << f << \".\";\n\tFILE *fp = fopen(f.c_str(), \"r\");\n\tint nr = 0;\n\tunsigned int ntotal = 0;\n\t\/\/ References are messed up after reading structs from a file\n\tfor (unsigned int i = 0; i < ncells; i++) {\n\t\tCell temp;\n\t\tnr = fread(temp.state, sizeof(Cell::state), 1, fp);\n\t\tif (nr <= 0)\n\t\t\tbreak;\n\t\tmycells->copyCell( i, temp);\n\t\tntotal++;\n\t}\n\tfclose(fp);\n\tif (ntotal < ncells)\n\t\tcout << \" --> Read \" << nr << \" cells. \";\n\tcout << \" Done reading.\" << endl << flush;\n}\n\nvoid simulation::readsinglecell( ) {\n\tstring f = folderName + \"\/\" + cellstateFileName;\n\tconst unsigned int ncells = mycells->getNcells();\n\n\tcout << \" Reading data for \" << ncells << \" cells from \" << f << \".\";\n\tFILE *fp = fopen(f.c_str(), \"r\");\n\tCell temp;\n\tint nr = fread(temp.state, sizeof(Cell::state), 1, fp);\n\tswitch (nr){\n\tcase 0:\n\t\tcout << \" --> Could not read cell state!!! \";\n\t\tbreak;\n\tcase 1:\n\t\tcout << \" --> Read single cell state. \";\n\t\tmycells->copyCells( temp );\n\t\tbreak;\n\tdefault:\n\t\tcout << \" --> fread returned: \" << nr << \", cell state not changed.\";\n\t\tbreak;\n\t}\n\tfclose(fp);\n\tcout << \" Done setting cell states from file.\" << endl << flush;\n}\n\n\n\nvoid simulation::printEverything(const double time, const int cycle,\n\t\t\t\t\t const double interval, const int S2_cycle,\n\t\t\t\t\t int& counter ){\n\tcounter++;\n\tif ((counter % counterupdates) == 0) {\n\t\tcout << \".\";\n\t\t\/\/ Print auxilliary variables\n\t\tif ((counter % (printtimeupdate*counterupdates)) == 0){\n\t\t\t\/\/This file will have voltages against time for each cell\n\t\t\tmycells->printV( files->result, time );\n\t\t\tif (printMarkovIts)\n\t\t\t\tprintMarkovIterations( time );\n\n\t\t\t\/\/This file prints The Markov States for cell 50\n\t\t\tif (cycle > printMarkovStatesAfterCycle) {\n\t\t\t\tmycells->printNacell( files->Na, time, nCell\/2 );\n\t\t\t}\n\n\t\t\tcout << \"t=\" << time << \"msec\" << endl;\n\t\t\tfor (unsigned int i=0; i<nCellOutputs; i++){\n\t\t\t\tCell c = mycells->getCell( nCellsToOutput[i] );\n\t\t\t\tprintcellAux( *(files->cellAuxFs[ i ]), time, c );\n\t\t\t}\n\n\t\t\t\/* Used to be:\n\t\t\tCell c0 = mycells->getCell( n0p00 );\n\t\t\tprintcellAux( *(files->First), time, c0 );\n\t\t\tif (n0p25 > n0p00){\n\t\t\t\tCell c25 = mycells->getCell( n0p25 );\n\t\t\t\tprintcellAux( *(files->Quarter), time, c25 );\n\t\t\t\tif (n0p50 > n0p25){\n\t\t\t\t\tCell c50 = mycells->getCell( n0p50 );\n\t\t\t\t\tprintcellAux( *(files->Midpoint), time, c50 );\n\t\t\t\t\tif (n0p75 > n0p50){\n\t\t\t\t\t\tCell c75 = mycells->getCell( n0p75 );\n\t\t\t\t\t\tprintcellAux( *(files->Three4ths), time, c75 );\n\t\t\t\t\t\tif (n1p00 > n0p75){\n\t\t\t\t\t\t\tCell c99 = mycells->getCell( n1p00 );\n\t\t\t\t\t\t\tprintcellAux( *(files->Last), time, c99 );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t*\/\n\t\t}\n\n\t\tif ( (counter % (printCycleUpdate*printtimeupdate*counterupdates)) == 0){\n\t\t\tswitch (sim_type){\n\t\t\tcase 0:\n\t\t\t\tcout << \"Non-paced simulation, t=\" << time << \" end time= \";\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\t\tcout << \"Paced simulation, cycle: \" << cycle << \" of \" << MaxNumberOfBeats\n\t\t\t\t\t\t<< \", t=\" << time << \", this interval= \";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcounter = 0;\n\t\t\tcout << interval << \", [drug] is \" << drug << endl;\n\t\t}\n\t\tcout << flush;\n\t}\n\n\n\tif ( nCell > 1 ){\n\t\t\/\/This file is for individual cells that calculates all of the min, max, V_90 parameters.\n\t\tbool isPrintingNeeded = mycells->isPrintingNeeded();\n\t\tif (isPrintingNeeded) {\n\t\t\tmycells->printThreshold( 50, cycle );\n\n\t\t\tfor (unsigned int i=0; i<nCellOutputs; i++){\n\t\t\t\tunsigned int cellout = nCellsToOutput[i];\n\t\t\t\tunsigned int cellnext = 1;\n\t\t\t\tint flag = 0;\n\t\t\t\tif (nCellsToOutput[i] == 0 ){\n\t\t\t\t\t\/\/ For the 0th cell, the adjacent one is 1\n\t\t\t\t\tcellnext = nCellsToOutput[i] + 1;\n\t\t\t\t\tflag = 1;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ For the other cells, the adjacent one is the one before it\n\t\t\t\t\tcellnext = nCellsToOutput[i] - 1;\n\t\t\t\t}\n\n\t\t\t\tCell c = mycells->getCell( cellout );\n\t\t\t\tCell cadj = mycells->getCell( cellnext );\n\n\t\t\t\tprintcellEAD( *(files->EADFs[ i ]), c, cadj, flag, cellout, cycle );\n\t\t\t}\n\n\t\t\t\/* Used to be\n\t\t\tCell c0 = mycells->getCell( n0p00 );\n\t\t\tCell c1 = mycells->getCell( n0p00+1 );\n\t\t\tprintcell( *(files->EAD00), c0, c1, 1, 0, cycle );\n\t\t\tCell c25 = mycells->getCell( n0p25 );\n\t\t\tCell c24 = mycells->getCell( n0p25-1 );\n\t\t\tprintcell( *(files->EAD25), c25, c24, 0, 25, cycle );\n\t\t\tCell c50 = mycells->getCell( n0p50 );\n\t\t\tCell c49 = mycells->getCell( n0p50-1 );\n\t\t\tprintcell( *(files->EAD50), c50, c49, 0, 50, cycle );\n\t\t\tCell c75 = mycells->getCell( n0p75 );\n\t\t\tCell c74 = mycells->getCell( n0p75-1 );\n\t\t\tprintcell( *(files->EAD75), c75, c74, 0, 75, cycle );\n\t\t\tCell c99 = mycells->getCell( n1p00 );\n\t\t\tCell c98 = mycells->getCell( n1p00-1 );\n\t\t\tprintcell( *(files->EAD99), c99, c98, 0, nCell-1, cycle );\n\t\t\t*\/\n\n\t\t\tmycells->resetPrintFlag();\n\t\t\tisPrintingNeeded = false;\n\t\t} \/\/ End of individual result files\n\t}\n}\n\nbool simulation::step( const double told, const double tnew ){\n\tconst bool success = solve->step( told, tnew, Yold, Ynew );\n\tif (success) {\n\t\tif (solve->isInplace()) {\n\t\t\t\/\/ Get a copy of all the state variables of all the cells\n\t\t\tmycells->getStateFromCells( Yold );\n\t\t} else {\n\t\t\t\/\/ Update the old state to have the new values\n\t\t\tfor (unsigned int i=0; i<neqns; i++)\n\t\t\t\tYold[i] = Ynew[i];\n\t\t}\n\t}\n\treturn success;\n}\n\nvoid simulation::printCV(const double time, const int cycle){\n\tif ( nCell > 1 ){\n\t\tmycells->printCV( files->CV, cycle );\n\t}\n}\nvoid simulation::printMarkovIterations( const double t ){\n\tconst unsigned int ncells = mycells->getNcells();\n\t\/\/ find middle cell\n\tconst unsigned int middlecell = ncells\/2;\n\tCell c = mycells->getCell( middlecell);\n\/\/MarkovIterations should be in the rushlarsen object\n\t*(files->MarkovIterations) << t <<\", \" << c.MarkovIterations\n\t\t\t\t\t\t << \", \" << c.MarkovIterationError << endl;\n\t\/\/ reset markov iteration count\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2014 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : support\/thread.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"support\/thread.hpp\"\n\n\/\/ includes, system\n\n#define GLIBCXX_NO_CODECVT 20131212\n\n#if !defined(__GLIBCXX__) || (defined(__GLIBCXX__) && (__GLIBCXX__ > GLIBCXX_NO_CODECVT))\n# include <codecvt> \/\/ std::codecvt_utf8<>\n#endif\n\n#include <locale> \/\/ std::wstring_convert<>\n\n\/\/ includes, project\n\n\/\/ #include <>\n\n#define UKACHULLDCS_USE_TRACE\n#undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\nnamespace support {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n std::string\n wstring_to_string(std::wstring const& a)\n {\n TRACE(\"support::wstring_to_string\");\n\n#if defined(__GLIBCXX__) && (__GLIBCXX__ <= GLIBCXX_NO_CODECVT)\n return std::string(a.begin(), a.end());\n#else\n return std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(a);\n#endif\n }\n \n std::wstring\n string_to_wstring(std::string const& a)\n {\n TRACE(\"support::string_to_wstring\");\n \n return std::wstring(a.begin(), a.end());\n }\n \n} \/\/ namespace support {\n<commit_msg>fixed: typo<commit_after>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2014 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : support\/string.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"support\/thread.hpp\"\n\n\/\/ includes, system\n\n#define GLIBCXX_NO_CODECVT 20131212\n\n#if !defined(__GLIBCXX__) || (defined(__GLIBCXX__) && (__GLIBCXX__ > GLIBCXX_NO_CODECVT))\n# include <codecvt> \/\/ std::codecvt_utf8<>\n#endif\n\n#include <locale> \/\/ std::wstring_convert<>\n\n\/\/ includes, project\n\n\/\/ #include <>\n\n#define UKACHULLDCS_USE_TRACE\n#undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\nnamespace support {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n std::string\n wstring_to_string(std::wstring const& a)\n {\n TRACE(\"support::wstring_to_string\");\n\n#if defined(__GLIBCXX__) && (__GLIBCXX__ <= GLIBCXX_NO_CODECVT)\n return std::string(a.begin(), a.end());\n#else\n return std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(a);\n#endif\n }\n \n std::wstring\n string_to_wstring(std::string const& a)\n {\n TRACE(\"support::string_to_wstring\");\n \n return std::wstring(a.begin(), a.end());\n }\n \n} \/\/ namespace support {\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef FORWARDER_HPP\n# define FORWARDER_HPP\n\n#include <cassert>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n template<typename T>\n forwarder(T&& f) : stub_(invoker_stub<T>)\n {\n static_assert(sizeof(T) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n using functor_type = typename ::std::decay<T>::type;\n new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<forwarder, typename ::std::decay<T>::type>{}\n >::type\n >\n forwarder& operator=(T&& f)\n {\n static_assert(sizeof(T) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n using functor_type = typename ::std::decay<T>::type;\n new (&store_) functor_type(::std::forward<T>(f));\n\n stub_ = invoker_stub<functor_type>;\n\n return *this;\n }\n\n R operator() (A... args) const\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\nprivate:\n template <typename U>\n static R invoker_stub(void const* const ptr, A&&... args)\n {\n return (*static_cast<U const*>(ptr))(::std::forward<A>(args)...);\n }\n\n R (*stub_)(void const*, A&&...){};\n\n typename ::std::aligned_storage<sizeof(::std::uintptr_t)>::type store_;\n};\n\n}\n\n#endif \/\/ FORWARDER_HPP\n<commit_msg>some fixes<commit_after>#pragma once\n#ifndef FORWARDER_HPP\n# define FORWARDER_HPP\n\n#include <cassert>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n template<typename T> forwarder(T&& f) { *this = ::std::forward<T>(f); }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<forwarder, typename ::std::decay<T>::type>{}\n >::type\n >\n forwarder& operator=(T&& f)\n {\n static_assert(sizeof(T) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n using functor_type = typename ::std::decay<T>::type;\n new (&store_) functor_type(::std::forward<T>(f));\n\n stub_ = invoker_stub<functor_type>;\n\n return *this;\n }\n\n R operator() (A... args) const\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\nprivate:\n template <typename U>\n static R invoker_stub(void const* const ptr, A&&... args)\n {\n return (*static_cast<U const*>(ptr))(::std::forward<A>(args)...);\n }\n\n R (*stub_)(void const*, A&&...){};\n\n typename ::std::aligned_storage<sizeof(::std::uintptr_t)>::type store_;\n};\n\n}\n\n#endif \/\/ FORWARDER_HPP\n<|endoftext|>"} {"text":"<commit_before>\n#include <stdio.h>\n#include <string>\n#include \"statesaver.h\"\n\nusing namespace std;\nStateSaver::StateSaver(QMTopology& qmtop)\n{}\n\n\/\/void StateSaver::Open(string file)\nvoid StateSaver::Open(string file, bool bAppend)\n{\n \/\/_out = fopen(file.c_str(), bAppend ? \"at\" : \"wt\");\n ofstream _out(file.c_str(), ios::binary|ios::out);\n \/\/_out = datafile(datafile.c_str(), ios::binary|ios::out);\n}\n\nvoid StateSaver::Close()\n{\n _out.close();\n}\n\nvoid StateSaver::Write_QMBeads(QMTopology *top)\n{ QMTopology *qmtop = top;\n for(BeadContainer::iterator iter=qmtop->Beads().begin();\n iter!=qmtop->Beads().end(); ++iter) {\n QMBead *bi = dynamic_cast<QMBead*>(*iter);\n\n string crg_unit_name = bi->GetCrgUnit()->GetType()->GetName();\n unsigned short len_name = crg_unit_name.length();\n int ipos=bi->getiPos();\n string type=bi->getType()->getName();\n unsigned short len_type = type.length();\n int symmetry=bi->getSymmetry();\n string bead_name=bi->getName();\n unsigned short len_bead_name = bead_name.length();\n int res_number=bi->getResnr();\n double mass=bi->getM();\n double charge=bi->getQ();\n vec r = bi->getPos();\n vec u = bi->getU();\n vec v = bi->getV();\n\n \/\/writing all out\n _out.write((char *) &len_name, sizeof(len_name));\n cout<<\"We have\"<<len_name<<\"letters in the name\\n\";\n _out.write((char *) crg_unit_name.c_str(), sizeof(crg_unit_name));\n _out.write((char *) &ipos, sizeof(ipos));\n _out.write((char *) &len_type, sizeof(len_type));\n _out.write((char *) type.c_str(), sizeof(type));\n _out.write((char *) &symmetry, sizeof(symmetry));\n _out.write((char *) &len_bead_name, sizeof(len_bead_name));\n _out.write((char *) bead_name.c_str(), sizeof(bead_name));\n _out.write((char *) &res_number, sizeof(len_bead_name));\n _out.write((char *) &mass, sizeof(mass));\n _out.write((char *) &charge, sizeof(charge));\n _out.write((char *) &r, sizeof(r));\n _out.write((char *) &u, sizeof(u));\n _out.write((char *) &v, sizeof(v));\n }\n\n \/\/ fflush(_out);\n}\n\n\/*VICTOR:\nvoid PDBWriter::Open(string file, bool bAppend)\n{\n _out = fopen(file.c_str(), bAppend ? \"at\" : \"wt\");\n}\n\nvoid PDBWriter::Close()\n{\n fclose(_out);\n}\n\nvoid PDBWriter::Write(Topology *conf)\n{\n Topology *top = conf;\n fprintf(_out, \"MODEL %4d\\n\", conf->getStep());\n for(BeadContainer::iterator iter=conf->Beads().begin();\n iter!=conf->Beads().end(); ++iter) {\n Bead *bi = *iter;\n vec r = bi->getPos();\n fprintf(_out,\n \"ATOM %5d %4s %3s %1s%4d %8.3f%8.3f%8.3f%6.2f%6.2f\\n\",\n (bi->getId()+1)%100000, \/\/ atom serial number\n bi->getName().c_str(), \/\/ atom name\n top->getResidue(bi->getResnr())->getName().c_str(), \/\/ residue name\n \" \", \/\/ chain identifier 1 char\n bi->getResnr()+1, \/\/ residue sequence number\n 10.*r.x(), 10.*r.y(), 10.*r.z(),\n bi->getQ(), bi->getM()); \/\/ is this correct??\n\n if(bi->getSymmetry()>=2) {\n vec ru = 0.1*bi->getU() + r;\n\n fprintf(_out,\n \"HETATM%5d %4s %3s %1s%4d %8.3f%8.3f%8.4f%6.2f%6.2f\\n\",\n bi->getId()+1, \/\/ atom serial number\n bi->getName().c_str(), \/\/ atom name\n \"REU\", \/\/ residue name\n \" \", \/\/ chain identifier 1 char\n bi->getResnr()+1, \/\/ residue sequence number\n 10.*ru.x(), 10.*ru.y(), 10.*ru.z(),\n 0., 0.); \/\/ is this correct??\n }\n if(bi->getSymmetry()>=3) {\n vec rv = 0.1*bi->getV() + r;\n fprintf(_out,\n \"HETATM%5d %4s %3s %1s%4d %8.3f%8.3f%8.4f%6.2f%6.2f\\n\",\n bi->getId()+1, \/\/ atom serial number\n bi->getName().c_str(), \/\/ atom name\n \"REV\", \/\/ residue name\n \" \", \/\/ chain identifier 1 char\n bi->getResnr()+1, \/\/ residue sequence number\n 10.*rv.x(), 10.*rv.y(), 10.*rv.z(),\n 0.,0.);\n }\n }\n fprintf(_out, \"ENDMDL\\n\");\n fflush(_out);\n}*\/\n<commit_msg>better statesaver.cc<commit_after>\n#include <stdio.h>\n#include <string>\n#include \"statesaver.h\"\n\nusing namespace std;\n\nStateSaver::StateSaver(QMTopology &qmtop) {\n _qmtop = &qmtop;\n}\n\n\/\/void StateSaver::Open(string file)\n\nvoid StateSaver::Save(string file, bool bAppend) {\n \/\/_out = fopen(file.c_str(), bAppend ? \"at\" : \"wt\");\n _out.open(file.c_str(), ios::out | ios::binary);\n Write_QMBeads();\n \/\/Write NBL\n _out.close();\n \/\/_out = datafile(datafile.c_str(), ios::binary|ios::out);\n}\n\nvoid StateSaver::Write_QMBeads() {\n assert(_out.is_open());\n\n write<unsigned long>(_qmtop->BeadCount());\n for (BeadContainer::iterator iter = _qmtop->Beads().begin();\n iter != _qmtop->Beads().end(); ++iter) {\n QMBead *bi = dynamic_cast<QMBead*> (*iter);\n\n write<byte_t > (bi->getSymmetry());\n write<string > (bi->getName());\n write<string > (bi->getType()->getName());\n write<int>(bi->getResnr());\n write<double>(bi->getM());\n write<double>(bi->getQ());\n\n write<string > (bi->GetCrgUnit()->GetType()->GetName());\n write<unsigned short>(bi->getiPos());\n write<vec > (bi->getPos());\n write<vec > (bi->getU());\n write<vec > (bi->getV());\n }\n\n\n}\n\nvoid StateSaver::Load(string file) {\n _qmtop->Cleanup();\n _in.open(file.c_str(), ios::in | ios::binary);\n Read_QMBeads();\n \/\/Read NBL\n _in.close();\n}\n\nvoid StateSaver::Read_QMBeads() {\n assert(_in.is_open());\n \n unsigned long nr_qmbeads = read<unsigned long>();\n cout << \"Total number of QMBeads is \" << nr_qmbeads << \"\\n\";\n for (unsigned long i = 0; i < 1; i++) {\n\n byte_t symmetry = read<byte_t> ();\n string bead_name = read<string> ();\n string type_name = read<string> ();\n BeadType *type = _qmtop->GetOrCreateBeadType(type_name);\n int resnr = read<int>();\n double M = read<double>();\n double Q = read<double>();\n\n string crg_unit_name = read<string> ();\n unsigned short ipos = read<unsigned short>();\n vec Pos = read<vec> ();\n vec U = read<vec> ();\n vec V = read<vec> ();\n\n cout << \"Bead Symmetry \" << symmetry << \"\\n\";\n cout << \"Bead Name \" << bead_name << \"\\n\";\n cout << \"Bead Type \" << type_name << \"\\n\";\n cout << \"Residue Number \" << resnr << \"\\n\";\n cout << \"Bead Mass \" << M << \"\\n\";\n cout << \"Bead Charge \" << Q << \"\\n\";\n\n Bead *bead = _qmtop->CreateBead(symmetry, bead_name, type, resnr, M, Q);\n int molid = bead->getMolecule()->getId();\n string molandtype = lexical_cast<string > (molid) + \":\" + crg_unit_name;\n cout << \"molandtype \" << molandtype << \"\\n\";\n \/\/ CrgUnit * acrg = GetCrgUnitByName(molandtype);\n \/\/ if(acrg == NULL)\n \/\/ acrg = CreateCrgUnit(molandtype, crg_unit_name, molid);\n\n \/\/ bead->setCrg(acrg);\n \/\/ bead->setPos(ipos);\n bead->setPos(Pos);\n bead->setU(U);\n bead->setV(V);\n\n cout << \"The charge unit is called \" << crg_unit_name << \"\\n\";\n cout << \"This bead is at int position \" << ipos << \"\\n\";\n cout << \"This bead hast position \" << U << \"\\n\";\n cout << \"This bead has U \" << U << \"\\n\";\n cout << \"This bead has V \" << V << \"\\n\";\n _in.close();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <vector>\n#include <string>\n#include <cstdio>\n\n#include <boost\/foreach.hpp>\n#include <boost\/regex.hpp>\n\n#include <OpenImageIO\/dassert.h>\n#include <OpenImageIO\/sysutil.h>\n#include <OpenImageIO\/timer.h>\n#include <OpenImageIO\/thread.h>\n\n#include \"oslexec_pvt.h\"\n\nOSL_NAMESPACE_ENTER\n\nstatic mutex buffered_errors_mutex;\n\n\n\nShadingContext::ShadingContext (ShadingSystemImpl &shadingsys,\n PerThreadInfo *threadinfo)\n : m_shadingsys(shadingsys), m_renderer(m_shadingsys.renderer()),\n m_attribs(NULL), m_max_warnings(shadingsys.max_warnings_per_thread()), m_dictionary(NULL), m_next_failed_attrib(0)\n{\n m_shadingsys.m_stat_contexts += 1;\n m_threadinfo = threadinfo ? threadinfo : shadingsys.get_perthread_info ();\n}\n\n\n\nShadingContext::~ShadingContext ()\n{\n process_errors ();\n m_shadingsys.m_stat_contexts -= 1;\n for (RegexMap::iterator it = m_regex_map.begin(); it != m_regex_map.end(); ++it) {\n delete it->second;\n }\n free_dict_resources ();\n}\n\n\n\nbool\nShadingContext::execute (ShaderGroup &sgroup, ShaderGlobals &ssg, bool run)\n{\n m_attribs = &sgroup;\n\n \/\/ Optimize if we haven't already\n if (sgroup.nlayers()) {\n sgroup.start_running ();\n if (! sgroup.optimized()) {\n shadingsys().optimize_group (sgroup);\n if (shadingsys().m_greedyjit && shadingsys().m_groups_to_compile_count) {\n \/\/ If we are greedily JITing, optimize\/JIT everything now\n shadingsys().optimize_all_groups ();\n }\n }\n if (sgroup.does_nothing())\n return false;\n } else {\n \/\/ empty shader - nothing to do!\n return false;\n }\n\n int profile = shadingsys().m_profile;\n OIIO::Timer timer (profile);\n\n \/\/ Allocate enough space on the heap\n size_t heap_size_needed = sgroup.llvm_groupdata_size();\n if (heap_size_needed > m_heap.size()) {\n if (shadingsys().debug())\n info (\" ShadingContext %p growing heap to %llu\",\n this, (unsigned long long) heap_size_needed);\n m_heap.resize (heap_size_needed);\n }\n \/\/ Zero out the heap memory we will be using\n if (shadingsys().m_clearmemory)\n memset (&m_heap[0], 0, heap_size_needed);\n\n \/\/ Set up closure storage\n m_closure_pool.clear();\n\n \/\/ Clear the message blackboard\n m_messages.clear ();\n\n \/\/ Clear miscellaneous scratch space\n m_scratch_pool.clear ();\n\n \/\/ Zero out stats for this execution\n clear_runtime_stats ();\n\n if (run) {\n ssg.context = this;\n ssg.renderer = renderer();\n ssg.Ci = NULL;\n RunLLVMGroupFunc run_func = sgroup.llvm_compiled_version();\n DASSERT (run_func);\n DASSERT (sgroup.llvm_groupdata_size() <= m_heap.size());\n run_func (&ssg, &m_heap[0]);\n }\n\n \/\/ Process any queued up error messages, warnings, printfs from shaders\n process_errors ();\n\n record_runtime_stats (); \/\/ Transfer runtime stats to the shadingsys\n if (profile) {\n long long ticks = timer.ticks();\n shadingsys().m_stat_total_shading_time_ticks += ticks;\n sgroup.m_stat_total_shading_time_ticks += ticks;\n }\n\n return true;\n}\n\n\n\nvoid\nShadingContext::record_error (ErrorHandler::ErrCode code,\n const std::string &text) const\n{\n m_buffered_errors.push_back (ErrorItem(code,text));\n \/\/ If we aren't buffering, just process immediately\n if (! shadingsys().m_buffer_printf)\n process_errors ();\n}\n\n\n\nvoid\nShadingContext::process_errors () const\n{\n size_t nerrors = m_buffered_errors.size();\n if (! nerrors)\n return;\n\n \/\/ Use a mutex to make sure output from different threads stays\n \/\/ together, at least for one shader invocation, rather than being\n \/\/ interleaved with other threads.\n lock_guard lock (buffered_errors_mutex);\n\n for (size_t i = 0; i < nerrors; ++i) {\n switch (m_buffered_errors[i].first) {\n case ErrorHandler::EH_MESSAGE :\n case ErrorHandler::EH_DEBUG :\n shadingsys().message (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_INFO :\n shadingsys().info (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_WARNING :\n shadingsys().warning (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_ERROR :\n case ErrorHandler::EH_SEVERE :\n shadingsys().error (m_buffered_errors[i].second);\n break;\n default:\n break;\n }\n }\n m_buffered_errors.clear();\n}\n\n\n\nSymbol *\nShadingContext::symbol (ustring layername, ustring symbolname)\n{\n ShaderGroup &sgroup (*attribs());\n int nlayers = sgroup.nlayers ();\n if (sgroup.llvm_compiled_version()) {\n for (int layer = nlayers-1; layer >= 0; --layer) {\n ShaderInstance *inst (sgroup[layer]);\n if (layername.size() && layername != inst->layername())\n continue; \/\/ They asked for a specific layer and this isn't it\n int symidx = inst->findsymbol (symbolname);\n if (symidx >= 0)\n return inst->symbol (symidx);\n }\n }\n return NULL;\n}\n\n\n\nvoid *\nShadingContext::symbol_data (Symbol &sym)\n{\n ShaderGroup &sgroup (*attribs());\n if (! sgroup.llvm_compiled_version())\n return NULL; \/\/ can't retrieve symbol if we didn't JIT and runit\n\n if (sym.dataoffset() >= 0 && (int)m_heap.size() > sym.dataoffset()) {\n \/\/ lives on the heap\n return &m_heap[sym.dataoffset()];\n }\n\n \/\/ doesn't live on the heap\n if ((sym.symtype() == SymTypeParam || sym.symtype() == SymTypeOutputParam) &&\n (sym.valuesource() == Symbol::DefaultVal || sym.valuesource() == Symbol::InstanceVal)) {\n ASSERT (sym.data());\n return sym.data() ? sym.data() : NULL;\n }\n\n return NULL; \/\/ not something we can retrieve\n}\n\n\n\nconst boost::regex &\nShadingContext::find_regex (ustring r)\n{\n RegexMap::const_iterator found = m_regex_map.find (r);\n if (found != m_regex_map.end())\n return *found->second;\n \/\/ otherwise, it wasn't found, add it\n m_regex_map[r] = new boost::regex(r.c_str());\n m_shadingsys.m_stat_regexes += 1;\n \/\/ std::cerr << \"Made new regex for \" << r << \"\\n\";\n return *m_regex_map[r];\n}\n\n\n\nbool\nShadingContext::osl_get_attribute (ShaderGlobals *sg, void *objdata,\n int dest_derivs,\n ustring obj_name, ustring attr_name,\n int array_lookup, int index,\n TypeDesc attr_type, void *attr_dest)\n{\n#if 0\n \/\/ Change the #if's below if you want to\n OIIO::Timer timer;\n#endif\n bool ok;\n\n for (int i = 0; i < FAILED_ATTRIBS; ++i) {\n if ((obj_name || m_failed_attribs[i].objdata == objdata) &&\n m_failed_attribs[i].attr_name == attr_name &&\n m_failed_attribs[i].obj_name == obj_name &&\n m_failed_attribs[i].attr_type == attr_type &&\n m_failed_attribs[i].array_lookup == array_lookup &&\n m_failed_attribs[i].index == index &&\n m_failed_attribs[i].objdata) {\n#if 0\n double time = timer();\n shadingsys().m_stat_getattribute_time += time;\n shadingsys().m_stat_getattribute_fail_time += time;\n shadingsys().m_stat_getattribute_calls += 1;\n#endif\n return false;\n }\n }\n\n if (array_lookup)\n ok = renderer()->get_array_attribute (sg, dest_derivs,\n obj_name, attr_type,\n attr_name, index, attr_dest);\n else\n ok = renderer()->get_attribute (sg, dest_derivs,\n obj_name, attr_type,\n attr_name, attr_dest);\n if (!ok) {\n int i = m_next_failed_attrib;\n m_failed_attribs[i].objdata = objdata;\n m_failed_attribs[i].obj_name = obj_name;\n m_failed_attribs[i].attr_name = attr_name;\n m_failed_attribs[i].attr_type = attr_type;\n m_failed_attribs[i].array_lookup = array_lookup;\n m_failed_attribs[i].index = index;\n m_next_failed_attrib = (i == FAILED_ATTRIBS-1) ? 0 : (i+1);\n }\n\n#if 0\n double time = timer();\n shadingsys().m_stat_getattribute_time += time;\n if (!ok)\n shadingsys().m_stat_getattribute_fail_time += time;\n shadingsys().m_stat_getattribute_calls += 1;\n#endif\n\/\/ std::cout << \"getattribute! '\" << obj_name << \"' \" << attr_name << ' ' << attr_type.c_str() << \" ok=\" << ok << \", objdata was \" << objdata << \"\\n\";\n return ok;\n}\n\n\n\nOSL_SHADEOP void\nosl_incr_layers_executed (ShaderGlobals *sg)\n{\n ShadingContext *ctx = (ShadingContext *)sg->context;\n ctx->incr_layers_executed ();\n}\n\n\nOSL_NAMESPACE_EXIT\n<commit_msg>Avoid incrementing profile related stats on every execution if profiling is disabled This fixes a performance regression that is particularly noticeable for small shaders executed from many threads<commit_after>\/*\nCopyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <vector>\n#include <string>\n#include <cstdio>\n\n#include <boost\/foreach.hpp>\n#include <boost\/regex.hpp>\n\n#include <OpenImageIO\/dassert.h>\n#include <OpenImageIO\/sysutil.h>\n#include <OpenImageIO\/timer.h>\n#include <OpenImageIO\/thread.h>\n\n#include \"oslexec_pvt.h\"\n\nOSL_NAMESPACE_ENTER\n\nstatic mutex buffered_errors_mutex;\n\n\n\nShadingContext::ShadingContext (ShadingSystemImpl &shadingsys,\n PerThreadInfo *threadinfo)\n : m_shadingsys(shadingsys), m_renderer(m_shadingsys.renderer()),\n m_attribs(NULL), m_max_warnings(shadingsys.max_warnings_per_thread()), m_dictionary(NULL), m_next_failed_attrib(0)\n{\n m_shadingsys.m_stat_contexts += 1;\n m_threadinfo = threadinfo ? threadinfo : shadingsys.get_perthread_info ();\n}\n\n\n\nShadingContext::~ShadingContext ()\n{\n process_errors ();\n m_shadingsys.m_stat_contexts -= 1;\n for (RegexMap::iterator it = m_regex_map.begin(); it != m_regex_map.end(); ++it) {\n delete it->second;\n }\n free_dict_resources ();\n}\n\n\n\nbool\nShadingContext::execute (ShaderGroup &sgroup, ShaderGlobals &ssg, bool run)\n{\n m_attribs = &sgroup;\n\n \/\/ Optimize if we haven't already\n if (sgroup.nlayers()) {\n sgroup.start_running ();\n if (! sgroup.optimized()) {\n shadingsys().optimize_group (sgroup);\n if (shadingsys().m_greedyjit && shadingsys().m_groups_to_compile_count) {\n \/\/ If we are greedily JITing, optimize\/JIT everything now\n shadingsys().optimize_all_groups ();\n }\n }\n if (sgroup.does_nothing())\n return false;\n } else {\n \/\/ empty shader - nothing to do!\n return false;\n }\n\n int profile = shadingsys().m_profile;\n OIIO::Timer timer (profile);\n\n \/\/ Allocate enough space on the heap\n size_t heap_size_needed = sgroup.llvm_groupdata_size();\n if (heap_size_needed > m_heap.size()) {\n if (shadingsys().debug())\n info (\" ShadingContext %p growing heap to %llu\",\n this, (unsigned long long) heap_size_needed);\n m_heap.resize (heap_size_needed);\n }\n \/\/ Zero out the heap memory we will be using\n if (shadingsys().m_clearmemory)\n memset (&m_heap[0], 0, heap_size_needed);\n\n \/\/ Set up closure storage\n m_closure_pool.clear();\n\n \/\/ Clear the message blackboard\n m_messages.clear ();\n\n \/\/ Clear miscellaneous scratch space\n m_scratch_pool.clear ();\n\n \/\/ Zero out stats for this execution\n clear_runtime_stats ();\n\n if (run) {\n ssg.context = this;\n ssg.renderer = renderer();\n ssg.Ci = NULL;\n RunLLVMGroupFunc run_func = sgroup.llvm_compiled_version();\n DASSERT (run_func);\n DASSERT (sgroup.llvm_groupdata_size() <= m_heap.size());\n run_func (&ssg, &m_heap[0]);\n }\n\n \/\/ Process any queued up error messages, warnings, printfs from shaders\n process_errors ();\n\n if (profile) {\n record_runtime_stats (); \/\/ Transfer runtime stats to the shadingsys\n long long ticks = timer.ticks();\n shadingsys().m_stat_total_shading_time_ticks += ticks;\n sgroup.m_stat_total_shading_time_ticks += ticks;\n }\n\n return true;\n}\n\n\n\nvoid\nShadingContext::record_error (ErrorHandler::ErrCode code,\n const std::string &text) const\n{\n m_buffered_errors.push_back (ErrorItem(code,text));\n \/\/ If we aren't buffering, just process immediately\n if (! shadingsys().m_buffer_printf)\n process_errors ();\n}\n\n\n\nvoid\nShadingContext::process_errors () const\n{\n size_t nerrors = m_buffered_errors.size();\n if (! nerrors)\n return;\n\n \/\/ Use a mutex to make sure output from different threads stays\n \/\/ together, at least for one shader invocation, rather than being\n \/\/ interleaved with other threads.\n lock_guard lock (buffered_errors_mutex);\n\n for (size_t i = 0; i < nerrors; ++i) {\n switch (m_buffered_errors[i].first) {\n case ErrorHandler::EH_MESSAGE :\n case ErrorHandler::EH_DEBUG :\n shadingsys().message (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_INFO :\n shadingsys().info (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_WARNING :\n shadingsys().warning (m_buffered_errors[i].second);\n break;\n case ErrorHandler::EH_ERROR :\n case ErrorHandler::EH_SEVERE :\n shadingsys().error (m_buffered_errors[i].second);\n break;\n default:\n break;\n }\n }\n m_buffered_errors.clear();\n}\n\n\n\nSymbol *\nShadingContext::symbol (ustring layername, ustring symbolname)\n{\n ShaderGroup &sgroup (*attribs());\n int nlayers = sgroup.nlayers ();\n if (sgroup.llvm_compiled_version()) {\n for (int layer = nlayers-1; layer >= 0; --layer) {\n ShaderInstance *inst (sgroup[layer]);\n if (layername.size() && layername != inst->layername())\n continue; \/\/ They asked for a specific layer and this isn't it\n int symidx = inst->findsymbol (symbolname);\n if (symidx >= 0)\n return inst->symbol (symidx);\n }\n }\n return NULL;\n}\n\n\n\nvoid *\nShadingContext::symbol_data (Symbol &sym)\n{\n ShaderGroup &sgroup (*attribs());\n if (! sgroup.llvm_compiled_version())\n return NULL; \/\/ can't retrieve symbol if we didn't JIT and runit\n\n if (sym.dataoffset() >= 0 && (int)m_heap.size() > sym.dataoffset()) {\n \/\/ lives on the heap\n return &m_heap[sym.dataoffset()];\n }\n\n \/\/ doesn't live on the heap\n if ((sym.symtype() == SymTypeParam || sym.symtype() == SymTypeOutputParam) &&\n (sym.valuesource() == Symbol::DefaultVal || sym.valuesource() == Symbol::InstanceVal)) {\n ASSERT (sym.data());\n return sym.data() ? sym.data() : NULL;\n }\n\n return NULL; \/\/ not something we can retrieve\n}\n\n\n\nconst boost::regex &\nShadingContext::find_regex (ustring r)\n{\n RegexMap::const_iterator found = m_regex_map.find (r);\n if (found != m_regex_map.end())\n return *found->second;\n \/\/ otherwise, it wasn't found, add it\n m_regex_map[r] = new boost::regex(r.c_str());\n m_shadingsys.m_stat_regexes += 1;\n \/\/ std::cerr << \"Made new regex for \" << r << \"\\n\";\n return *m_regex_map[r];\n}\n\n\n\nbool\nShadingContext::osl_get_attribute (ShaderGlobals *sg, void *objdata,\n int dest_derivs,\n ustring obj_name, ustring attr_name,\n int array_lookup, int index,\n TypeDesc attr_type, void *attr_dest)\n{\n#if 0\n \/\/ Change the #if's below if you want to\n OIIO::Timer timer;\n#endif\n bool ok;\n\n for (int i = 0; i < FAILED_ATTRIBS; ++i) {\n if ((obj_name || m_failed_attribs[i].objdata == objdata) &&\n m_failed_attribs[i].attr_name == attr_name &&\n m_failed_attribs[i].obj_name == obj_name &&\n m_failed_attribs[i].attr_type == attr_type &&\n m_failed_attribs[i].array_lookup == array_lookup &&\n m_failed_attribs[i].index == index &&\n m_failed_attribs[i].objdata) {\n#if 0\n double time = timer();\n shadingsys().m_stat_getattribute_time += time;\n shadingsys().m_stat_getattribute_fail_time += time;\n shadingsys().m_stat_getattribute_calls += 1;\n#endif\n return false;\n }\n }\n\n if (array_lookup)\n ok = renderer()->get_array_attribute (sg, dest_derivs,\n obj_name, attr_type,\n attr_name, index, attr_dest);\n else\n ok = renderer()->get_attribute (sg, dest_derivs,\n obj_name, attr_type,\n attr_name, attr_dest);\n if (!ok) {\n int i = m_next_failed_attrib;\n m_failed_attribs[i].objdata = objdata;\n m_failed_attribs[i].obj_name = obj_name;\n m_failed_attribs[i].attr_name = attr_name;\n m_failed_attribs[i].attr_type = attr_type;\n m_failed_attribs[i].array_lookup = array_lookup;\n m_failed_attribs[i].index = index;\n m_next_failed_attrib = (i == FAILED_ATTRIBS-1) ? 0 : (i+1);\n }\n\n#if 0\n double time = timer();\n shadingsys().m_stat_getattribute_time += time;\n if (!ok)\n shadingsys().m_stat_getattribute_fail_time += time;\n shadingsys().m_stat_getattribute_calls += 1;\n#endif\n\/\/ std::cout << \"getattribute! '\" << obj_name << \"' \" << attr_name << ' ' << attr_type.c_str() << \" ok=\" << ok << \", objdata was \" << objdata << \"\\n\";\n return ok;\n}\n\n\n\nOSL_SHADEOP void\nosl_incr_layers_executed (ShaderGlobals *sg)\n{\n ShadingContext *ctx = (ShadingContext *)sg->context;\n ctx->incr_layers_executed ();\n}\n\n\nOSL_NAMESPACE_EXIT\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2014, Fengping Bao <jamol@live.com>\r\n *\r\n * Permission to use, copy, modify, and\/or distribute this software for any\r\n * purpose with or without fee is hereby granted, provided that the above\r\n * copyright notice and this permission notice appear in all copies.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\r\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\r\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\r\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\r\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\r\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\r\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r\n *\/\r\n\r\n#ifdef KUMA_HAS_OPENSSL\r\n\r\n#include \"OpenSslLib.h\"\r\n#include \"util\/kmtrace.h\"\r\n#include \"util\/util.h\"\r\n\r\n#include <string>\r\n#include <thread>\r\n#include <sstream>\r\n\r\nKUMA_NS_BEGIN\r\n\r\nSSL_CTX* OpenSslLib::ssl_ctx_client_ = NULL;\r\nSSL_CTX* OpenSslLib::ssl_ctx_server_ = NULL;\r\nstd::mutex* OpenSslLib::ssl_locks_ = NULL;\r\n\r\nbool OpenSslLib::init(const char* path)\r\n{\r\n if(ssl_ctx_client_ || ssl_ctx_server_) {\r\n return true;\r\n }\r\n \r\n std::string cert_path;\r\n if(path == NULL) {\r\n cert_path = getCurrentModulePath();\r\n } else {\r\n cert_path = path;\r\n if(cert_path.empty()) {\r\n cert_path = getCurrentModulePath();\r\n } else if(cert_path.at(cert_path.length() - 1) != PATH_SEPARATOR) {\r\n cert_path += PATH_SEPARATOR;\r\n }\r\n }\r\n \r\n std::string server_cert_file = cert_path + \"server.cer\";\r\n std::string server_key_file = cert_path + \"server.key\";\r\n std::string client_cert_file;\/\/ = cert_path + \"cleint.cer\";\r\n std::string client_key_file;\/\/ = cert_path + \"client.key\";\r\n std::string ca_cert_file = cert_path + \"ca.cer\";\r\n \r\n SSL_library_init();\r\n \/\/OpenSSL_add_all_algorithms();\r\n SSL_load_error_strings();\r\n \r\n bool server_ctx_ok = false;\r\n bool client_ctx_ok = false;\r\n do {\r\n ssl_ctx_server_ = SSL_CTX_new(SSLv23_server_method());\r\n if(NULL == ssl_ctx_server_) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_new failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n \r\n if(!server_cert_file.empty() && !server_key_file.empty()) {\r\n if(SSL_CTX_use_certificate_file(ssl_ctx_server_, server_cert_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_certificate_file failed, file=\"<<server_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_use_PrivateKey_file(ssl_ctx_server_, server_key_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_PrivateKey_file failed, file:\"<<server_key_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_check_private_key(ssl_ctx_server_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_check_private_key failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n }\r\n \r\n \/*\r\n SSL_CTX_set_verify(ssl_ctx_client_, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback);\r\n app_verify_arg arg0;\r\n SSL_CTX_set_cert_verify_callback(ssl_ctx_server_, appVerifyCallback, &arg0);\r\n \r\n int session_id_context = 1;\r\n if(SSL_CTX_set_session_id_context(ssl_ctx_server_, (unsigned char *)&session_id_context, sizeof(session_id_context)) != 1)\r\n {\r\n }\r\n *\/\r\n server_ctx_ok = true;\r\n } while(0);\r\n \r\n do {\r\n ssl_ctx_client_ = SSL_CTX_new(SSLv23_client_method());\r\n if(NULL == ssl_ctx_client_) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_new failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n \r\n \/\/ set AES256_SHA cipher for client.\r\n \/\/if(SSL_CTX_set_cipher_list(ssl_ctx_client_,\"AES256-SHA\") != 1)\r\n \/\/{\r\n \/\/\tKUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_set_cipher_list failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n \/\/}\r\n \r\n if(!client_cert_file.empty() && !client_key_file.empty()) {\r\n if(SSL_CTX_use_certificate_file(ssl_ctx_client_, client_cert_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_certificate_file failed, file=\"<<client_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_use_PrivateKey_file(ssl_ctx_client_, client_key_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_PrivateKey_file failed, file=\"<<client_key_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_check_private_key(ssl_ctx_client_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_check_private_key failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n }\r\n \r\n if(!ca_cert_file.empty() &&\r\n SSL_CTX_load_verify_locations(ssl_ctx_client_, ca_cert_file.c_str(), NULL) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_load_verify_locations failed, file=\"<<ca_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_set_default_verify_paths(ssl_ctx_client_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_set_default_verify_paths failed, err=\"\r\n <<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n SSL_CTX_set_verify(ssl_ctx_client_, SSL_VERIFY_PEER, verifyCallback);\r\n \/\/app_verify_arg arg1;\r\n \/\/SSL_CTX_set_cert_verify_callback(ssl_ctx_client_, appVerifyCallback, &arg1);\r\n client_ctx_ok = true;\r\n } while(0);\r\n \r\n if(!server_ctx_ok && ssl_ctx_server_) {\r\n SSL_CTX_free(ssl_ctx_server_);\r\n ssl_ctx_server_ = NULL;\r\n }\r\n if(!client_ctx_ok && ssl_ctx_client_) {\r\n SSL_CTX_free(ssl_ctx_client_);\r\n ssl_ctx_client_ = NULL;\r\n }\r\n if(!server_ctx_ok && !client_ctx_ok) {\r\n return false;\r\n }\r\n \r\n ssl_locks_ = new std::mutex[CRYPTO_num_locks()];\r\n CRYPTO_set_id_callback(threadIdCallback);\r\n CRYPTO_set_locking_callback(lockingCallback);\r\n \r\n \/\/ PRNG\r\n RAND_poll();\r\n while(RAND_status() == 0) {\r\n unsigned short rand_ret = rand() % 65536;\r\n RAND_seed(&rand_ret, sizeof(rand_ret));\r\n }\r\n \r\n return true;\r\n}\r\n\r\nvoid OpenSslLib::fini()\r\n{\r\n \r\n}\r\n\r\nstruct app_verify_arg\r\n{\r\n char *string;\r\n int app_verify;\r\n int allow_proxy_certs;\r\n char *proxy_auth;\r\n char *proxy_cond;\r\n};\r\n\r\nint OpenSslLib::verifyCallback(int ok, X509_STORE_CTX *ctx)\r\n{\r\n if(NULL == ctx) {\r\n return -1;\r\n }\r\n if(ctx->current_cert) {\r\n char *s, buf[1024];\r\n s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert), buf, sizeof(buf));\r\n if(s != NULL) {\r\n if(ok) {\r\n KUMA_INFOTRACE(\"verifyCallback ok, depth=\"<<ctx->error_depth<<\", subject=\"<<buf);\r\n if(X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf))) {\r\n KUMA_INFOTRACE(\"verifyCallback, issuer=\"<<buf);\r\n }\r\n } else {\r\n KUMA_ERRTRACE(\"verifyCallback failed, depth=\"<<ctx->error_depth\r\n <<\", err=\"<<ctx->error<<\", subject=\"<<buf);\r\n }\r\n }\r\n }\r\n \r\n if (0 == ok) {\r\n KUMA_INFOTRACE(\"verifyCallback, err=\"<<X509_verify_cert_error_string(ctx->error));\r\n switch (ctx->error)\r\n {\r\n \/\/case X509_V_ERR_CERT_NOT_YET_VALID:\r\n \/\/case X509_V_ERR_CERT_HAS_EXPIRED:\r\n case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\r\n KUMA_INFOTRACE(\"verifyCallback, ... ignored, err=\"<<ctx->error);\r\n ok = 1;\r\n break;\r\n }\r\n }\r\n \r\n return ok;\r\n}\r\n\r\nint OpenSslLib::appVerifyCallback(X509_STORE_CTX *ctx, void *arg)\r\n{\r\n if(!ctx || !arg) {\r\n return -1;\r\n }\r\n \r\n int ok = 1;\r\n struct app_verify_arg *cb_arg = (struct app_verify_arg *)arg;\r\n \r\n if (cb_arg->app_verify) {\r\n char *s = NULL, buf[256];\r\n if(ctx->cert) {\r\n s = X509_NAME_oneline(X509_get_subject_name(ctx->cert), buf, 256);\r\n }\r\n if(s != NULL) {\r\n KUMA_INFOTRACE(\"appVerifyCallback, depth=\"<<ctx->error_depth<<\", \"<<buf);\r\n }\r\n return 1;\r\n }\r\n \r\n ok = X509_verify_cert(ctx);\r\n \r\n return ok;\r\n}\r\n\r\nunsigned long OpenSslLib::threadIdCallback(void)\r\n{\r\n#if 0\r\n unsigned long ret = 0;\r\n std::thread::id thread_id = std::this_thread::get_id();\r\n std::stringstream ss;\r\n ss << thread_id;\r\n ss >> ret;\r\n return ret;\r\n#else\r\n return getCurrentThreadId();\r\n#endif\r\n}\r\n\r\nvoid OpenSslLib::lockingCallback(int mode, int n, const char *file, int line)\r\n{\r\n if (mode & CRYPTO_LOCK) {\r\n ssl_locks_[n].lock();\r\n }\r\n else {\r\n ssl_locks_[n].unlock();\r\n }\r\n}\r\n\r\nKUMA_NS_END\r\n\r\n#endif \/\/ KUMA_HAS_OPENSSL\r\n<commit_msg>disable SSLv2<commit_after>\/* Copyright (c) 2014, Fengping Bao <jamol@live.com>\r\n *\r\n * Permission to use, copy, modify, and\/or distribute this software for any\r\n * purpose with or without fee is hereby granted, provided that the above\r\n * copyright notice and this permission notice appear in all copies.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\r\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\r\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\r\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\r\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\r\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\r\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r\n *\/\r\n\r\n#ifdef KUMA_HAS_OPENSSL\r\n\r\n#include \"OpenSslLib.h\"\r\n#include \"util\/kmtrace.h\"\r\n#include \"util\/util.h\"\r\n\r\n#include <string>\r\n#include <thread>\r\n#include <sstream>\r\n\r\nKUMA_NS_BEGIN\r\n\r\nSSL_CTX* OpenSslLib::ssl_ctx_client_ = NULL;\r\nSSL_CTX* OpenSslLib::ssl_ctx_server_ = NULL;\r\nstd::mutex* OpenSslLib::ssl_locks_ = NULL;\r\n\r\nbool OpenSslLib::init(const char* path)\r\n{\r\n if(ssl_ctx_client_ || ssl_ctx_server_) {\r\n return true;\r\n }\r\n \r\n std::string cert_path;\r\n if(path == NULL) {\r\n cert_path = getCurrentModulePath();\r\n } else {\r\n cert_path = path;\r\n if(cert_path.empty()) {\r\n cert_path = getCurrentModulePath();\r\n } else if(cert_path.at(cert_path.length() - 1) != PATH_SEPARATOR) {\r\n cert_path += PATH_SEPARATOR;\r\n }\r\n }\r\n \r\n std::string server_cert_file = cert_path + \"server.cer\";\r\n std::string server_key_file = cert_path + \"server.key\";\r\n std::string client_cert_file;\/\/ = cert_path + \"cleint.cer\";\r\n std::string client_key_file;\/\/ = cert_path + \"client.key\";\r\n std::string ca_cert_file = cert_path + \"ca.cer\";\r\n \r\n SSL_library_init();\r\n \/\/OpenSSL_add_all_algorithms();\r\n SSL_load_error_strings();\r\n \r\n bool server_ctx_ok = false;\r\n bool client_ctx_ok = false;\r\n do {\r\n ssl_ctx_server_ = SSL_CTX_new(SSLv23_server_method());\r\n if(NULL == ssl_ctx_server_) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_new failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n \r\n \/\/const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;\r\n \/\/SSL_CTX_set_options(ssl_ctx_server_, flags);\r\n SSL_CTX_set_options(ssl_ctx_server_, SSL_OP_NO_SSLv2);\r\n \r\n if(!server_cert_file.empty() && !server_key_file.empty()) {\r\n if(SSL_CTX_use_certificate_file(ssl_ctx_server_, server_cert_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_certificate_file failed, file=\"<<server_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_use_PrivateKey_file(ssl_ctx_server_, server_key_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_PrivateKey_file failed, file:\"<<server_key_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_check_private_key(ssl_ctx_server_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_check_private_key failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n }\r\n \r\n \/*\r\n SSL_CTX_set_verify(ssl_ctx_client_, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback);\r\n app_verify_arg arg0;\r\n SSL_CTX_set_cert_verify_callback(ssl_ctx_server_, appVerifyCallback, &arg0);\r\n \r\n int session_id_context = 1;\r\n if(SSL_CTX_set_session_id_context(ssl_ctx_server_, (unsigned char *)&session_id_context, sizeof(session_id_context)) != 1)\r\n {\r\n }\r\n *\/\r\n server_ctx_ok = true;\r\n } while(0);\r\n \r\n do {\r\n ssl_ctx_client_ = SSL_CTX_new(SSLv23_client_method());\r\n if(NULL == ssl_ctx_client_) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_new failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n \r\n SSL_CTX_set_verify(ssl_ctx_client_, SSL_VERIFY_PEER, verifyCallback);\r\n \/\/SSL_CTX_set_verify_depth(ssl_ctx_client_, 4);\r\n \/\/app_verify_arg arg1;\r\n \/\/SSL_CTX_set_cert_verify_callback(ssl_ctx_client_, appVerifyCallback, &arg1);\r\n \r\n \/\/const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;\r\n \/\/SSL_CTX_set_options(ssl_ctx_client_, flags);\r\n SSL_CTX_set_options(ssl_ctx_client_, SSL_OP_NO_SSLv2);\r\n \r\n \/\/ set AES256_SHA cipher for client.\r\n \/\/if(SSL_CTX_set_cipher_list(ssl_ctx_client_,\"AES256-SHA\") != 1)\r\n \/\/{\r\n \/\/\tKUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_set_cipher_list failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n \/\/}\r\n \r\n if(!client_cert_file.empty() && !client_key_file.empty()) {\r\n if(SSL_CTX_use_certificate_file(ssl_ctx_client_, client_cert_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_certificate_file failed, file=\"<<client_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_use_PrivateKey_file(ssl_ctx_client_, client_key_file.c_str(), SSL_FILETYPE_PEM) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_use_PrivateKey_file failed, file=\"<<client_key_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_check_private_key(ssl_ctx_client_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_check_private_key failed, err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n }\r\n \r\n if(!ca_cert_file.empty() &&\r\n SSL_CTX_load_verify_locations(ssl_ctx_client_, ca_cert_file.c_str(), NULL) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_load_verify_locations failed, file=\"<<ca_cert_file\r\n <<\", err=\"<<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n if(SSL_CTX_set_default_verify_paths(ssl_ctx_client_) != 1) {\r\n KUMA_WARNTRACE(\"OpenSslLib::init, SSL_CTX_set_default_verify_paths failed, err=\"\r\n <<ERR_reason_error_string(ERR_get_error()));\r\n break;\r\n }\r\n client_ctx_ok = true;\r\n } while(0);\r\n \r\n if(!server_ctx_ok && ssl_ctx_server_) {\r\n SSL_CTX_free(ssl_ctx_server_);\r\n ssl_ctx_server_ = NULL;\r\n }\r\n if(!client_ctx_ok && ssl_ctx_client_) {\r\n SSL_CTX_free(ssl_ctx_client_);\r\n ssl_ctx_client_ = NULL;\r\n }\r\n if(!server_ctx_ok && !client_ctx_ok) {\r\n return false;\r\n }\r\n \r\n ssl_locks_ = new std::mutex[CRYPTO_num_locks()];\r\n CRYPTO_set_id_callback(threadIdCallback);\r\n CRYPTO_set_locking_callback(lockingCallback);\r\n \r\n \/\/ PRNG\r\n RAND_poll();\r\n while(RAND_status() == 0) {\r\n unsigned short rand_ret = rand() % 65536;\r\n RAND_seed(&rand_ret, sizeof(rand_ret));\r\n }\r\n \r\n return true;\r\n}\r\n\r\nvoid OpenSslLib::fini()\r\n{\r\n \r\n}\r\n\r\nstruct app_verify_arg\r\n{\r\n char *string;\r\n int app_verify;\r\n int allow_proxy_certs;\r\n char *proxy_auth;\r\n char *proxy_cond;\r\n};\r\n\r\nint OpenSslLib::verifyCallback(int ok, X509_STORE_CTX *ctx)\r\n{\r\n if(NULL == ctx) {\r\n return -1;\r\n }\r\n if(ctx->current_cert) {\r\n char *s, buf[1024];\r\n s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert), buf, sizeof(buf));\r\n if(s != NULL) {\r\n if(ok) {\r\n KUMA_INFOTRACE(\"verifyCallback ok, depth=\"<<ctx->error_depth<<\", subject=\"<<buf);\r\n if(X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, sizeof(buf))) {\r\n KUMA_INFOTRACE(\"verifyCallback, issuer=\"<<buf);\r\n }\r\n } else {\r\n KUMA_ERRTRACE(\"verifyCallback failed, depth=\"<<ctx->error_depth\r\n <<\", err=\"<<ctx->error<<\", subject=\"<<buf);\r\n }\r\n }\r\n }\r\n \r\n if (0 == ok) {\r\n KUMA_INFOTRACE(\"verifyCallback, err=\"<<X509_verify_cert_error_string(ctx->error));\r\n switch (ctx->error)\r\n {\r\n \/\/case X509_V_ERR_CERT_NOT_YET_VALID:\r\n \/\/case X509_V_ERR_CERT_HAS_EXPIRED:\r\n case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\r\n KUMA_INFOTRACE(\"verifyCallback, ... ignored, err=\"<<ctx->error);\r\n ok = 1;\r\n break;\r\n }\r\n }\r\n \r\n return ok;\r\n}\r\n\r\nint OpenSslLib::appVerifyCallback(X509_STORE_CTX *ctx, void *arg)\r\n{\r\n if(!ctx || !arg) {\r\n return -1;\r\n }\r\n \r\n int ok = 1;\r\n struct app_verify_arg *cb_arg = (struct app_verify_arg *)arg;\r\n \r\n if (cb_arg->app_verify) {\r\n char *s = NULL, buf[256];\r\n if(ctx->cert) {\r\n s = X509_NAME_oneline(X509_get_subject_name(ctx->cert), buf, 256);\r\n }\r\n if(s != NULL) {\r\n KUMA_INFOTRACE(\"appVerifyCallback, depth=\"<<ctx->error_depth<<\", \"<<buf);\r\n }\r\n return 1;\r\n }\r\n \r\n ok = X509_verify_cert(ctx);\r\n \r\n return ok;\r\n}\r\n\r\nunsigned long OpenSslLib::threadIdCallback(void)\r\n{\r\n#if 0\r\n unsigned long ret = 0;\r\n std::thread::id thread_id = std::this_thread::get_id();\r\n std::stringstream ss;\r\n ss << thread_id;\r\n ss >> ret;\r\n return ret;\r\n#else\r\n return getCurrentThreadId();\r\n#endif\r\n}\r\n\r\nvoid OpenSslLib::lockingCallback(int mode, int n, const char *file, int line)\r\n{\r\n if (mode & CRYPTO_LOCK) {\r\n ssl_locks_[n].lock();\r\n }\r\n else {\r\n ssl_locks_[n].unlock();\r\n }\r\n}\r\n\r\nKUMA_NS_END\r\n\r\n#endif \/\/ KUMA_HAS_OPENSSL\r\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n Copyright 2007 Albert Strasheim <fullung@gmail.com>\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n*\/\r\n\r\n#include <boost\/python\/class.hpp>\r\n\r\n#include <cms\/StreamMessage.h>\r\n\r\nnamespace py = boost::python;\r\n\r\nusing cms::StreamMessage;\r\nusing cms::Message;\r\n\r\nvoid export_StreamMessage()\r\n{\r\n py::class_<StreamMessage, py::bases<Message>, boost::noncopyable>(\"StreamMessage\", py::no_init);\r\n}\r\n<commit_msg>Wrapped easy parts of StreamMessage.<commit_after>\/*\r\n Copyright 2007 Albert Strasheim <fullung@gmail.com>\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n*\/\r\n\r\n#include <boost\/python\/class.hpp>\r\n\r\n#include <cms\/StreamMessage.h>\r\n\r\nnamespace py = boost::python;\r\n\r\nusing cms::StreamMessage;\r\nusing cms::Message;\r\n\r\nvoid export_StreamMessage()\r\n{\r\n py::class_<StreamMessage, py::bases<Message>, boost::noncopyable>(\"StreamMessage\", py::no_init)\r\n .def(\"readBoolean\", &StreamMessage::readBoolean)\r\n .def(\"writeBoolean\", &StreamMessage::writeBoolean)\r\n .def(\"readByte\", &StreamMessage::readByte)\r\n .def(\"writeByte\", &StreamMessage::writeByte)\r\n#if 0\r\n .def(\"readBytes\", &StreamMessage::readBytes)\r\n .def(\"writeBytes\", &StreamMessage::writeBytes)\r\n#endif\r\n .def(\"readChar\", &StreamMessage::readChar)\r\n .def(\"writeChar\", &StreamMessage::writeChar)\r\n .def(\"readFloat\", &StreamMessage::readFloat)\r\n .def(\"writeFloat\", &StreamMessage::writeFloat)\r\n .def(\"readDouble\", &StreamMessage::readDouble)\r\n .def(\"writeDouble\", &StreamMessage::writeDouble)\r\n .def(\"readShort\", &StreamMessage::readShort)\r\n .def(\"writeShort\", &StreamMessage::writeShort)\r\n .def(\"readUnsignedShort\", &StreamMessage::readUnsignedShort)\r\n .def(\"writeUnsignedShort\", &StreamMessage::writeUnsignedShort)\r\n .def(\"readInt\", &StreamMessage::readInt)\r\n .def(\"writeInt\", &StreamMessage::writeInt)\r\n .def(\"readLong\", &StreamMessage::readLong)\r\n .def(\"writeLong\", &StreamMessage::writeLong)\r\n .def(\"readString\", &StreamMessage::readString)\r\n .def(\"writeString\", &StreamMessage::writeString)\r\n ;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <test\/fuzz\/fuzz.h>\n\n#include <cstdint>\n#include <unistd.h>\n#include <vector>\n\nstatic bool read_stdin(std::vector<uint8_t>& data)\n{\n uint8_t buffer[1024];\n ssize_t length = 0;\n while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer + length);\n\n if (data.size() > (1 << 20)) return false;\n }\n return length == 0;\n}\n\n\/\/ Default initialization: Override using a non-weak initialize().\n__attribute__((weak)) void initialize()\n{\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n const std::vector<uint8_t> input(data, data + size);\n test_one_input(input);\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n initialize();\n return 0;\n}\n\n\/\/ Disabled under WIN32 due to clash with Cygwin's WinMain.\n#ifndef WIN32\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak))\n#endif\nint\nmain(int argc, char** argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n while (__AFL_LOOP(1000)) {\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n test_one_input(buffer);\n }\n#else\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n test_one_input(buffer);\n#endif\n return 0;\n}\n<commit_msg>tests: Remove Cygwin WinMain workaround<commit_after>\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <test\/fuzz\/fuzz.h>\n\n#include <cstdint>\n#include <unistd.h>\n#include <vector>\n\nstatic bool read_stdin(std::vector<uint8_t>& data)\n{\n uint8_t buffer[1024];\n ssize_t length = 0;\n while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) {\n data.insert(data.end(), buffer, buffer + length);\n\n if (data.size() > (1 << 20)) return false;\n }\n return length == 0;\n}\n\n\/\/ Default initialization: Override using a non-weak initialize().\n__attribute__((weak)) void initialize()\n{\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n const std::vector<uint8_t> input(data, data + size);\n test_one_input(input);\n return 0;\n}\n\n\/\/ This function is used by libFuzzer\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n initialize();\n return 0;\n}\n\n\/\/ Declare main(...) \"weak\" to allow for libFuzzer linking. libFuzzer provides\n\/\/ the main(...) function.\n__attribute__((weak)) int main(int argc, char** argv)\n{\n initialize();\n#ifdef __AFL_INIT\n \/\/ Enable AFL deferred forkserver mode. Requires compilation using\n \/\/ afl-clang-fast++. See fuzzing.md for details.\n __AFL_INIT();\n#endif\n\n#ifdef __AFL_LOOP\n \/\/ Enable AFL persistent mode. Requires compilation using afl-clang-fast++.\n \/\/ See fuzzing.md for details.\n while (__AFL_LOOP(1000)) {\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n continue;\n }\n test_one_input(buffer);\n }\n#else\n std::vector<uint8_t> buffer;\n if (!read_stdin(buffer)) {\n return 0;\n }\n test_one_input(buffer);\n#endif\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/platform\/file_system.h\"\n\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <deque>\n#include <string>\n#include <utility>\n#include <vector>\n\n#if defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n#include <fnmatch.h>\n#else\n#include \"tensorflow\/core\/platform\/regexp.h\"\n#endif \/\/ defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/platform.h\"\n#include \"tensorflow\/core\/platform\/scanner.h\"\n#include \"tensorflow\/core\/platform\/str_util.h\"\n#include \"tensorflow\/core\/platform\/strcat.h\"\n\nnamespace tensorflow {\n\nbool FileSystem::Match(const string& filename, const string& pattern) {\n#if defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n \/\/ We avoid relying on RE2 on mobile platforms, because it incurs a\n \/\/ significant binary size increase.\n \/\/ For POSIX platforms, there is no need to depend on RE2 if `fnmatch` can be\n \/\/ used safely.\n return fnmatch(pattern.c_str(), filename.c_str(), FNM_PATHNAME) == 0;\n#else\n string regexp(pattern);\n regexp = str_util::StringReplace(regexp, \"*\", \"[^\/]*\", true);\n regexp = str_util::StringReplace(regexp, \"?\", \".\", true);\n regexp = str_util::StringReplace(regexp, \"(\", \"\\\\(\", true);\n regexp = str_util::StringReplace(regexp, \")\", \"\\\\)\", true);\n return RE2::FullMatch(filename, regexp);\n#endif \/\/ defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n}\n\nstring FileSystem::TranslateName(const string& name) const {\n \/\/ If the name is empty, CleanPath returns \".\" which is incorrect and\n \/\/ we should return the empty path instead.\n if (name.empty()) return name;\n\n \/\/ Otherwise, properly separate the URI components and clean the path one\n StringPiece scheme, host, path;\n this->ParseURI(name, &scheme, &host, &path);\n\n \/\/ If `path` becomes empty, return `\/` (`file:\/\/` should be `\/`), not `.`.\n if (path.empty()) return \"\/\";\n\n return this->CleanPath(path);\n}\n\nStatus FileSystem::IsDirectory(const string& name) {\n \/\/ Check if path exists.\n TF_RETURN_IF_ERROR(FileExists(name));\n FileStatistics stat;\n TF_RETURN_IF_ERROR(Stat(name, &stat));\n if (stat.is_directory) {\n return Status::OK();\n }\n return Status(tensorflow::error::FAILED_PRECONDITION, \"Not a directory\");\n}\n\nStatus FileSystem::HasAtomicMove(const string& path, bool* has_atomic_move) {\n *has_atomic_move = true;\n return Status::OK();\n}\n\nvoid FileSystem::FlushCaches() {}\n\nbool FileSystem::FilesExist(const std::vector<string>& files,\n std::vector<Status>* status) {\n bool result = true;\n for (const auto& file : files) {\n Status s = FileExists(file);\n result &= s.ok();\n if (status != nullptr) {\n status->push_back(s);\n } else if (!result) {\n \/\/ Return early since there is no need to check other files.\n return false;\n }\n }\n return result;\n}\n\nStatus FileSystem::DeleteRecursively(const string& dirname,\n int64* undeleted_files,\n int64* undeleted_dirs) {\n CHECK_NOTNULL(undeleted_files);\n CHECK_NOTNULL(undeleted_dirs);\n\n *undeleted_files = 0;\n *undeleted_dirs = 0;\n \/\/ Make sure that dirname exists;\n Status exists_status = FileExists(dirname);\n if (!exists_status.ok()) {\n (*undeleted_dirs)++;\n return exists_status;\n }\n\n \/\/ If given path to a single file, we should just delete it.\n if (!IsDirectory(dirname).ok()) {\n Status delete_root_status = DeleteFile(dirname);\n if (!delete_root_status.ok()) (*undeleted_files)++;\n return delete_root_status;\n }\n\n std::deque<string> dir_q; \/\/ Queue for the BFS\n std::vector<string> dir_list; \/\/ List of all dirs discovered\n dir_q.push_back(dirname);\n Status ret; \/\/ Status to be returned.\n \/\/ Do a BFS on the directory to discover all the sub-directories. Remove all\n \/\/ children that are files along the way. Then cleanup and remove the\n \/\/ directories in reverse order.;\n while (!dir_q.empty()) {\n string dir = dir_q.front();\n dir_q.pop_front();\n dir_list.push_back(dir);\n std::vector<string> children;\n \/\/ GetChildren might fail if we don't have appropriate permissions.\n Status s = GetChildren(dir, &children);\n ret.Update(s);\n if (!s.ok()) {\n (*undeleted_dirs)++;\n continue;\n }\n for (const string& child : children) {\n const string child_path = this->JoinPath(dir, child);\n \/\/ If the child is a directory add it to the queue, otherwise delete it.\n if (IsDirectory(child_path).ok()) {\n dir_q.push_back(child_path);\n } else {\n \/\/ Delete file might fail because of permissions issues or might be\n \/\/ unimplemented.\n Status del_status = DeleteFile(child_path);\n ret.Update(del_status);\n if (!del_status.ok()) {\n (*undeleted_files)++;\n }\n }\n }\n }\n \/\/ Now reverse the list of directories and delete them. The BFS ensures that\n \/\/ we can delete the directories in this order.\n std::reverse(dir_list.begin(), dir_list.end());\n for (const string& dir : dir_list) {\n \/\/ Delete dir might fail because of permissions issues or might be\n \/\/ unimplemented.\n Status s = DeleteDir(dir);\n ret.Update(s);\n if (!s.ok()) {\n (*undeleted_dirs)++;\n }\n }\n return ret;\n}\n\nStatus FileSystem::RecursivelyCreateDir(const string& dirname) {\n StringPiece scheme, host, remaining_dir;\n this->ParseURI(dirname, &scheme, &host, &remaining_dir);\n std::vector<StringPiece> sub_dirs;\n while (!remaining_dir.empty()) {\n std::string current_entry = this->CreateURI(scheme, host, remaining_dir);\n Status exists_status = FileExists(current_entry);\n if (exists_status.ok()) {\n \/\/ FileExists cannot differentiate between existence of a file or a\n \/\/ directory, hence we need an additional test as we must not assume that\n \/\/ a path to a file is a path to a parent directory.\n Status directory_status = IsDirectory(current_entry);\n if (directory_status.ok()) {\n break; \/\/ We need to start creating directories from here.\n } else if (directory_status.code() == tensorflow::error::UNIMPLEMENTED) {\n return directory_status;\n } else {\n return errors::FailedPrecondition(remaining_dir, \" is not a directory\");\n }\n }\n if (exists_status.code() != error::Code::NOT_FOUND) {\n return exists_status;\n }\n \/\/ Basename returns \"\" for \/ ending dirs.\n if (!str_util::EndsWith(remaining_dir, \"\/\")) {\n sub_dirs.push_back(this->Basename(remaining_dir));\n }\n remaining_dir = this->Dirname(remaining_dir);\n }\n\n \/\/ sub_dirs contains all the dirs to be created but in reverse order.\n std::reverse(sub_dirs.begin(), sub_dirs.end());\n\n \/\/ Now create the directories.\n string built_path(remaining_dir);\n for (const StringPiece sub_dir : sub_dirs) {\n built_path = this->JoinPath(built_path, sub_dir);\n Status status = CreateDir(this->CreateURI(scheme, host, built_path));\n if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {\n return status;\n }\n }\n return Status::OK();\n}\n\nStatus FileSystem::CopyFile(const string& src, const string& target) {\n return FileSystemCopyFile(this, src, this, target);\n}\n\nchar FileSystem::Separator() const { return '\/'; }\n\nstring FileSystem::JoinPathImpl(std::initializer_list<StringPiece> paths) {\n string result;\n\n for (StringPiece path : paths) {\n if (path.empty()) continue;\n\n if (result.empty()) {\n result = string(path);\n continue;\n }\n\n if (result[result.size() - 1] == '\/') {\n if (this->IsAbsolutePath(path)) {\n strings::StrAppend(&result, path.substr(1));\n } else {\n strings::StrAppend(&result, path);\n }\n } else {\n if (this->IsAbsolutePath(path)) {\n strings::StrAppend(&result, path);\n } else {\n strings::StrAppend(&result, \"\/\", path);\n }\n }\n }\n\n return result;\n}\n\nstd::pair<StringPiece, StringPiece> FileSystem::SplitPath(\n StringPiece uri) const {\n StringPiece scheme, host, path;\n ParseURI(uri, &scheme, &host, &path);\n\n size_t pos = path.rfind(this->Separator());\n\n \/\/ Our code assumes it is written for linux too many times. So, for windows\n \/\/ also check for '\/'\n#ifdef PLATFORM_WINDOWS\n size_t pos2 = path.rfind('\/');\n \/\/ Pick the max value that is not string::npos.\n if (pos == string::npos) {\n pos = pos2;\n } else {\n if (pos2 != string::npos) {\n pos = pos > pos2 ? pos : pos2;\n }\n }\n#endif\n\n \/\/ Handle the case with no SEP in 'path'.\n if (pos == StringPiece::npos)\n return std::make_pair(StringPiece(uri.begin(), host.end() - uri.begin()),\n path);\n\n \/\/ Handle the case with a single leading '\/' in 'path'.\n if (pos == 0)\n return std::make_pair(\n StringPiece(uri.begin(), path.begin() + 1 - uri.begin()),\n StringPiece(path.data() + 1, path.size() - 1));\n\n return std::make_pair(\n StringPiece(uri.begin(), path.begin() + pos - uri.begin()),\n StringPiece(path.data() + pos + 1, path.size() - (pos + 1)));\n}\n\nbool FileSystem::IsAbsolutePath(StringPiece path) const {\n return !path.empty() && path[0] == '\/';\n}\n\nStringPiece FileSystem::Dirname(StringPiece path) const {\n return this->SplitPath(path).first;\n}\n\nStringPiece FileSystem::Basename(StringPiece path) const {\n return this->SplitPath(path).second;\n}\n\nStringPiece FileSystem::Extension(StringPiece path) const {\n StringPiece basename = this->Basename(path);\n\n int pos = basename.rfind('.');\n if (static_cast<size_t>(pos) == StringPiece::npos) {\n return StringPiece(path.data() + path.size(), 0);\n } else {\n return StringPiece(path.data() + pos + 1, path.size() - (pos + 1));\n }\n}\n\nstring FileSystem::CleanPath(StringPiece unclean_path) const {\n string path(unclean_path);\n const char* src = path.c_str();\n string::iterator dst = path.begin();\n\n \/\/ Check for absolute path and determine initial backtrack limit.\n const bool is_absolute_path = *src == '\/';\n if (is_absolute_path) {\n *dst++ = *src++;\n while (*src == '\/') ++src;\n }\n string::const_iterator backtrack_limit = dst;\n\n \/\/ Process all parts\n while (*src) {\n bool parsed = false;\n\n if (src[0] == '.') {\n \/\/ 1dot \".<whateverisnext>\", check for END or SEP.\n if (src[1] == '\/' || !src[1]) {\n if (*++src) {\n ++src;\n }\n parsed = true;\n } else if (src[1] == '.' && (src[2] == '\/' || !src[2])) {\n \/\/ 2dot END or SEP (\"..\" | \"..\/<whateverisnext>\").\n src += 2;\n if (dst != backtrack_limit) {\n \/\/ We can backtrack the previous part\n for (--dst; dst != backtrack_limit && dst[-1] != '\/'; --dst) {\n \/\/ Empty.\n }\n } else if (!is_absolute_path) {\n \/\/ Failed to backtrack and we can't skip it either. Rewind and copy.\n src -= 2;\n *dst++ = *src++;\n *dst++ = *src++;\n if (*src) {\n *dst++ = *src;\n }\n \/\/ We can never backtrack over a copied \"..\/\" part so set new limit.\n backtrack_limit = dst;\n }\n if (*src) {\n ++src;\n }\n parsed = true;\n }\n }\n\n \/\/ If not parsed, copy entire part until the next SEP or EOS.\n if (!parsed) {\n while (*src && *src != '\/') {\n *dst++ = *src++;\n }\n if (*src) {\n *dst++ = *src++;\n }\n }\n\n \/\/ Skip consecutive SEP occurrences\n while (*src == '\/') {\n ++src;\n }\n }\n\n \/\/ Calculate and check the length of the cleaned path.\n string::difference_type path_length = dst - path.begin();\n if (path_length != 0) {\n \/\/ Remove trailing '\/' except if it is root path (\"\/\" ==> path_length := 1)\n if (path_length > 1 && path[path_length - 1] == '\/') {\n --path_length;\n }\n path.resize(path_length);\n } else {\n \/\/ The cleaned path is empty; assign \".\" as per the spec.\n path.assign(1, '.');\n }\n return path;\n}\n\nvoid FileSystem::ParseURI(StringPiece remaining, StringPiece* scheme,\n StringPiece* host, StringPiece* path) const {\n \/\/ 0. Parse scheme\n \/\/ Make sure scheme matches [a-zA-Z][0-9a-zA-Z.]*\n \/\/ TODO(keveman): Allow \"+\" and \"-\" in the scheme.\n \/\/ Keep URI pattern in tensorboard\/backend\/server.py updated accordingly\n if (!strings::Scanner(remaining)\n .One(strings::Scanner::LETTER)\n .Many(strings::Scanner::LETTER_DIGIT_DOT)\n .StopCapture()\n .OneLiteral(\":\/\/\")\n .GetResult(&remaining, scheme)) {\n \/\/ If there's no scheme, assume the entire string is a path.\n *scheme = StringPiece(remaining.begin(), 0);\n *host = StringPiece(remaining.begin(), 0);\n *path = remaining;\n return;\n }\n\n \/\/ 1. Parse host\n if (!strings::Scanner(remaining).ScanUntil('\/').GetResult(&remaining, host)) {\n \/\/ No path, so the rest of the URI is the host.\n *host = remaining;\n *path = StringPiece(remaining.end(), 0);\n return;\n }\n\n \/\/ 2. The rest is the path\n *path = remaining;\n}\n\nstring FileSystem::CreateURI(StringPiece scheme, StringPiece host,\n StringPiece path) const {\n if (scheme.empty()) {\n return string(path);\n }\n return strings::StrCat(scheme, \":\/\/\", host, path);\n}\n\n} \/\/ namespace tensorflow\n<commit_msg>Update file_system.cc<commit_after>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/platform\/file_system.h\"\n\n#include <sys\/stat.h>\n\n#include <algorithm>\n#include <deque>\n#include <string>\n#include <utility>\n#include <vector>\n\n#if defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n#include <fnmatch.h>\n#else\n#include \"tensorflow\/core\/platform\/regexp.h\"\n#endif \/\/ defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/platform.h\"\n#include \"tensorflow\/core\/platform\/scanner.h\"\n#include \"tensorflow\/core\/platform\/str_util.h\"\n#include \"tensorflow\/core\/platform\/strcat.h\"\n\nnamespace tensorflow {\n\nbool FileSystem::Match(const string& filename, const string& pattern) {\n#if defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n \/\/ We avoid relying on RE2 on mobile platforms, because it incurs a\n \/\/ significant binary size increase.\n \/\/ For POSIX platforms, there is no need to depend on RE2 if `fnmatch` can be\n \/\/ used safely.\n return fnmatch(pattern.c_str(), filename.c_str(), FNM_PATHNAME) == 0;\n#else\n string regexp(pattern);\n regexp = str_util::StringReplace(regexp, \"*\", \"[^\/]*\", true);\n regexp = str_util::StringReplace(regexp, \"?\", \".\", true);\n regexp = str_util::StringReplace(regexp, \"(\", \"\\\\(\", true);\n regexp = str_util::StringReplace(regexp, \")\", \"\\\\)\", true);\n return RE2::FullMatch(filename, regexp);\n#endif \/\/ defined(PLATFORM_POSIX) || defined(IS_MOBILE_PLATFORM)\n}\n\nstring FileSystem::TranslateName(const string& name) const {\n \/\/ If the name is empty, CleanPath returns \".\" which is incorrect and\n \/\/ we should return the empty path instead.\n if (name.empty()) return name;\n\n \/\/ Otherwise, properly separate the URI components and clean the path one\n StringPiece scheme, host, path;\n this->ParseURI(name, &scheme, &host, &path);\n\n \/\/ If `path` becomes empty, return `\/` (`file:\/\/` should be `\/`), not `.`.\n if (path.empty()) return \"\/\";\n\n return this->CleanPath(path);\n}\n\nStatus FileSystem::IsDirectory(const string& name) {\n \/\/ Check if path exists.\n TF_RETURN_IF_ERROR(FileExists(name));\n FileStatistics stat;\n TF_RETURN_IF_ERROR(Stat(name, &stat));\n if (stat.is_directory) {\n return Status::OK();\n }\n return Status(tensorflow::error::FAILED_PRECONDITION, \"Not a directory\");\n}\n\nStatus FileSystem::HasAtomicMove(const string& path, bool* has_atomic_move) {\n *has_atomic_move = true;\n return Status::OK();\n}\n\nvoid FileSystem::FlushCaches() {}\n\nbool FileSystem::FilesExist(const std::vector<string>& files,\n std::vector<Status>* status) {\n bool result = true;\n for (const auto& file : files) {\n Status s = FileExists(file);\n result &= s.ok();\n if (status != nullptr) {\n status->push_back(s);\n } else if (!result) {\n \/\/ Return early since there is no need to check other files.\n return false;\n }\n }\n return result;\n}\n\nStatus FileSystem::DeleteRecursively(const string& dirname,\n int64* undeleted_files,\n int64* undeleted_dirs) {\n CHECK_NOTNULL(undeleted_files);\n CHECK_NOTNULL(undeleted_dirs);\n\n *undeleted_files = 0;\n *undeleted_dirs = 0;\n \/\/ Make sure that dirname exists;\n Status exists_status = FileExists(dirname);\n if (!exists_status.ok()) {\n (*undeleted_dirs)++;\n return exists_status;\n }\n\n \/\/ If given path to a single file, we should just delete it.\n if (!IsDirectory(dirname).ok()) {\n Status delete_root_status = DeleteFile(dirname);\n if (!delete_root_status.ok()) (*undeleted_files)++;\n return delete_root_status;\n }\n\n std::deque<string> dir_q; \/\/ Queue for the BFS\n std::vector<string> dir_list; \/\/ List of all dirs discovered\n dir_q.push_back(dirname);\n Status ret; \/\/ Status to be returned.\n \/\/ Do a BFS on the directory to discover all the sub-directories. Remove all\n \/\/ children that are files along the way. Then cleanup and remove the\n \/\/ directories in reverse order.;\n while (!dir_q.empty()) {\n string dir = dir_q.front();\n dir_q.pop_front();\n dir_list.push_back(dir);\n std::vector<string> children;\n \/\/ GetChildren might fail if we don't have appropriate permissions.\n Status s = GetChildren(dir, &children);\n ret.Update(s);\n if (!s.ok()) {\n (*undeleted_dirs)++;\n continue;\n }\n for (const string& child : children) {\n const string child_path = this->JoinPath(dir, child);\n \/\/ If the child is a directory add it to the queue, otherwise delete it.\n if (IsDirectory(child_path).ok()) {\n dir_q.push_back(child_path);\n } else {\n \/\/ Delete file might fail because of permissions issues or might be\n \/\/ unimplemented.\n Status del_status = DeleteFile(child_path);\n ret.Update(del_status);\n if (!del_status.ok()) {\n (*undeleted_files)++;\n }\n }\n }\n }\n \/\/ Now reverse the list of directories and delete them. The BFS ensures that\n \/\/ we can delete the directories in this order.\n std::reverse(dir_list.begin(), dir_list.end());\n for (const string& dir : dir_list) {\n \/\/ Delete dir might fail because of permissions issues or might be\n \/\/ unimplemented.\n Status s = DeleteDir(dir);\n ret.Update(s);\n if (!s.ok()) {\n (*undeleted_dirs)++;\n }\n }\n return ret;\n}\n\nStatus FileSystem::RecursivelyCreateDir(const string& dirname) {\n StringPiece scheme, host, remaining_dir;\n this->ParseURI(dirname, &scheme, &host, &remaining_dir);\n std::vector<StringPiece> sub_dirs;\n while (!remaining_dir.empty()) {\n std::string current_entry = this->CreateURI(scheme, host, remaining_dir);\n Status exists_status = FileExists(current_entry);\n if (exists_status.ok()) {\n \/\/ FileExists cannot differentiate between existence of a file or a\n \/\/ directory, hence we need an additional test as we must not assume that\n \/\/ a path to a file is a path to a parent directory.\n Status directory_status = IsDirectory(current_entry);\n if (directory_status.ok()) {\n break; \/\/ We need to start creating directories from here.\n } else if (directory_status.code() == tensorflow::error::UNIMPLEMENTED) {\n return directory_status;\n } else {\n return errors::FailedPrecondition(remaining_dir, \" is not a directory\");\n }\n }\n if (exists_status.code() != error::Code::NOT_FOUND) {\n return exists_status;\n }\n \/\/ Basename returns \"\" for \/ ending dirs.\n if (!str_util::EndsWith(remaining_dir, \"\/\")) {\n sub_dirs.push_back(this->Basename(remaining_dir));\n }\n remaining_dir = this->Dirname(remaining_dir);\n }\n\n \/\/ sub_dirs contains all the dirs to be created but in reverse order.\n std::reverse(sub_dirs.begin(), sub_dirs.end());\n\n \/\/ Now create the directories.\n string built_path(remaining_dir);\n for (const StringPiece sub_dir : sub_dirs) {\n built_path = this->JoinPath(built_path, sub_dir);\n Status status = CreateDir(this->CreateURI(scheme, host, built_path));\n if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {\n return status;\n }\n }\n return Status::OK();\n}\n\nStatus FileSystem::CopyFile(const string& src, const string& target) {\n return FileSystemCopyFile(this, src, this, target);\n}\n\nchar FileSystem::Separator() const { return '\/'; }\n\nstring FileSystem::JoinPathImpl(std::initializer_list<StringPiece> paths) {\n string result;\n\n for (StringPiece path : paths) {\n if (path.empty()) continue;\n\n if (result.empty()) {\n result = string(path);\n continue;\n }\n\n if (result[result.size() - 1] == '\/') {\n if (this->IsAbsolutePath(path)) {\n strings::StrAppend(&result, path.substr(1));\n } else {\n strings::StrAppend(&result, path);\n }\n } else {\n if (this->IsAbsolutePath(path)) {\n strings::StrAppend(&result, path);\n } else {\n strings::StrAppend(&result, \"\/\", path);\n }\n }\n }\n\n return result;\n}\n\nstd::pair<StringPiece, StringPiece> FileSystem::SplitPath(\n StringPiece uri) const {\n StringPiece scheme, host, path;\n ParseURI(uri, &scheme, &host, &path);\n\n size_t pos = path.rfind(this->Separator());\n\n \/\/ Our code assumes it is written for linux too many times. So, for windows\n \/\/ also check for '\/'\n#ifdef PLATFORM_WINDOWS\n size_t pos2 = path.rfind('\/');\n \/\/ Pick the max value that is not string::npos.\n if (pos == string::npos) {\n pos = pos2;\n } else {\n if (pos2 != string::npos) {\n pos = pos > pos2 ? pos : pos2;\n }\n }\n#endif\n\n \/\/ Handle the case with no SEP in 'path'.\n if (pos == StringPiece::npos)\n return std::make_pair(StringPiece(uri.begin(), host.end() - uri.begin()),\n path);\n\n \/\/ Handle the case with a single leading '\/' in 'path'.\n if (pos == 0)\n return std::make_pair(\n StringPiece(uri.begin(), path.begin() + 1 - uri.begin()),\n StringPiece(path.data() + 1, path.size() - 1));\n\n return std::make_pair(\n StringPiece(uri.begin(), path.begin() + pos - uri.begin()),\n StringPiece(path.data() + pos + 1, path.size() - (pos + 1)));\n}\n\nbool FileSystem::IsAbsolutePath(StringPiece path) const {\n return !path.empty() && path[0] == '\/';\n}\n\nStringPiece FileSystem::Dirname(StringPiece path) const {\n return this->SplitPath(path).first;\n}\n\nStringPiece FileSystem::Basename(StringPiece path) const {\n return this->SplitPath(path).second;\n}\n\nStringPiece FileSystem::Extension(StringPiece path) const {\n StringPiece basename = this->Basename(path);\n\n size_t pos = basename.rfind('.');\n if (pos == StringPiece::npos) {\n return StringPiece(path.data() + path.size(), 0);\n } else {\n return StringPiece(path.data() + pos + 1, path.size() - (pos + 1));\n }\n}\n\nstring FileSystem::CleanPath(StringPiece unclean_path) const {\n string path(unclean_path);\n const char* src = path.c_str();\n string::iterator dst = path.begin();\n\n \/\/ Check for absolute path and determine initial backtrack limit.\n const bool is_absolute_path = *src == '\/';\n if (is_absolute_path) {\n *dst++ = *src++;\n while (*src == '\/') ++src;\n }\n string::const_iterator backtrack_limit = dst;\n\n \/\/ Process all parts\n while (*src) {\n bool parsed = false;\n\n if (src[0] == '.') {\n \/\/ 1dot \".<whateverisnext>\", check for END or SEP.\n if (src[1] == '\/' || !src[1]) {\n if (*++src) {\n ++src;\n }\n parsed = true;\n } else if (src[1] == '.' && (src[2] == '\/' || !src[2])) {\n \/\/ 2dot END or SEP (\"..\" | \"..\/<whateverisnext>\").\n src += 2;\n if (dst != backtrack_limit) {\n \/\/ We can backtrack the previous part\n for (--dst; dst != backtrack_limit && dst[-1] != '\/'; --dst) {\n \/\/ Empty.\n }\n } else if (!is_absolute_path) {\n \/\/ Failed to backtrack and we can't skip it either. Rewind and copy.\n src -= 2;\n *dst++ = *src++;\n *dst++ = *src++;\n if (*src) {\n *dst++ = *src;\n }\n \/\/ We can never backtrack over a copied \"..\/\" part so set new limit.\n backtrack_limit = dst;\n }\n if (*src) {\n ++src;\n }\n parsed = true;\n }\n }\n\n \/\/ If not parsed, copy entire part until the next SEP or EOS.\n if (!parsed) {\n while (*src && *src != '\/') {\n *dst++ = *src++;\n }\n if (*src) {\n *dst++ = *src++;\n }\n }\n\n \/\/ Skip consecutive SEP occurrences\n while (*src == '\/') {\n ++src;\n }\n }\n\n \/\/ Calculate and check the length of the cleaned path.\n string::difference_type path_length = dst - path.begin();\n if (path_length != 0) {\n \/\/ Remove trailing '\/' except if it is root path (\"\/\" ==> path_length := 1)\n if (path_length > 1 && path[path_length - 1] == '\/') {\n --path_length;\n }\n path.resize(path_length);\n } else {\n \/\/ The cleaned path is empty; assign \".\" as per the spec.\n path.assign(1, '.');\n }\n return path;\n}\n\nvoid FileSystem::ParseURI(StringPiece remaining, StringPiece* scheme,\n StringPiece* host, StringPiece* path) const {\n \/\/ 0. Parse scheme\n \/\/ Make sure scheme matches [a-zA-Z][0-9a-zA-Z.]*\n \/\/ TODO(keveman): Allow \"+\" and \"-\" in the scheme.\n \/\/ Keep URI pattern in tensorboard\/backend\/server.py updated accordingly\n if (!strings::Scanner(remaining)\n .One(strings::Scanner::LETTER)\n .Many(strings::Scanner::LETTER_DIGIT_DOT)\n .StopCapture()\n .OneLiteral(\":\/\/\")\n .GetResult(&remaining, scheme)) {\n \/\/ If there's no scheme, assume the entire string is a path.\n *scheme = StringPiece(remaining.begin(), 0);\n *host = StringPiece(remaining.begin(), 0);\n *path = remaining;\n return;\n }\n\n \/\/ 1. Parse host\n if (!strings::Scanner(remaining).ScanUntil('\/').GetResult(&remaining, host)) {\n \/\/ No path, so the rest of the URI is the host.\n *host = remaining;\n *path = StringPiece(remaining.end(), 0);\n return;\n }\n\n \/\/ 2. The rest is the path\n *path = remaining;\n}\n\nstring FileSystem::CreateURI(StringPiece scheme, StringPiece host,\n StringPiece path) const {\n if (scheme.empty()) {\n return string(path);\n }\n return strings::StrCat(scheme, \":\/\/\", host, path);\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"pow.h\"\n#include \"random.h\"\n#include \"util.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n\/* Test calculation of next difficulty target with no constraints applying *\/\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1261130161; \/\/ Block #30240\n CBlockIndex pindexLast;\n pindexLast.nHeight = 32255;\n pindexLast.nTime = 1262152739; \/\/ Block #32255\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);\n}\n\n\/* Test the constraint on the upper bound for next work *\/\nBOOST_AUTO_TEST_CASE(get_next_work_pow_limit)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1231006505; \/\/ Block #0\n CBlockIndex pindexLast;\n pindexLast.nHeight = 2015;\n pindexLast.nTime = 1233061996; \/\/ Block #2015\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00ffff);\n}\n\n\/* Test the constraint on the lower bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1279008237; \/\/ Block #66528\n CBlockIndex pindexLast;\n pindexLast.nHeight = 68543;\n pindexLast.nTime = 1279297671; \/\/ Block #68543\n pindexLast.nBits = 0x1c05a3f4;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fd);\n}\n\n\/* Test the constraint on the upper bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1263163443; \/\/ NOTE: Not an actual block time\n CBlockIndex pindexLast;\n pindexLast.nHeight = 46367;\n pindexLast.nTime = 1269211443; \/\/ Block #46367\n pindexLast.nBits = 0x1c387f6f;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n std::vector<CBlockIndex> blocks(10000);\n for (int i = 0; i < 10000; i++) {\n blocks[i].pprev = i ? &blocks[i - 1] : NULL;\n blocks[i].nHeight = i;\n blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;\n blocks[i].nBits = 0x207fffff; \/* target 0x7fffff000... *\/\n blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);\n }\n\n for (int j = 0; j < 1000; j++) {\n CBlockIndex *p1 = &blocks[GetRand(10000)];\n CBlockIndex *p2 = &blocks[GetRand(10000)];\n CBlockIndex *p3 = &blocks[GetRand(10000)];\n\n int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);\n BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n }\n}\n\nstatic CBlockIndex GetBlockIndex(CBlockIndex *pindexPrev, int64_t nTimeInterval, uint32_t nBits) {\n CBlockIndex block;\n block.pprev = pindexPrev;\n block.nHeight = pindexPrev->nHeight + 1;\n block.nTime = pindexPrev->nTime + nTimeInterval;\n block.nBits = nBits;\n\n return block;\n}\n\nBOOST_AUTO_TEST_CASE(retargeting_test) {\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params ¶ms = Params().GetConsensus();\n\n std::vector<CBlockIndex> blocks(1013);\n\n \/\/ Genesis block?\n blocks[0] = CBlockIndex();\n blocks[0].nHeight = 0;\n blocks[0].nTime = 1269211443;\n blocks[0].nBits = 0x207fffff;\n\n \/\/ Pile up some blocks.\n for (size_t i = 1; i < 1000; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], params.nPowTargetSpacing, 0x207fffff);\n }\n\n CBlockHeader blkHeaderDummy;\n\n \/\/ We start getting 2h blocks time. For the first 5 blocks, it doesn't\n \/\/ matter as the MTP is not affected. For the next 5 block, MTP difference\n \/\/ increases but stays bellow 12h.\n for (size_t i = 1000; i < 1010; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 2 * 3600, 0x207fffff);\n BOOST_CHECK_EQUAL(\n GetNextWorkRequired(&blocks[i], &blkHeaderDummy, params),\n 0x207fffff);\n }\n\n \/\/ Now we expect the difficulty to decrease.\n blocks[1010] = GetBlockIndex(&blocks[1009], 2 * 3600, 0x207fffff);\n BOOST_CHECK_EQUAL(\n GetNextWorkRequired(&blocks[1010], &blkHeaderDummy, params),\n 0x1d00ffff);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Make sure the unit test doesn't depend on config options<commit_after>\/\/ Copyright (c) 2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"pow.h\"\n#include \"random.h\"\n#include \"util.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\n\nBOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)\n\n\/* Test calculation of next difficulty target with no constraints applying *\/\nBOOST_AUTO_TEST_CASE(get_next_work)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1261130161; \/\/ Block #30240\n CBlockIndex pindexLast;\n pindexLast.nHeight = 32255;\n pindexLast.nTime = 1262152739; \/\/ Block #32255\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);\n}\n\n\/* Test the constraint on the upper bound for next work *\/\nBOOST_AUTO_TEST_CASE(get_next_work_pow_limit)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1231006505; \/\/ Block #0\n CBlockIndex pindexLast;\n pindexLast.nHeight = 2015;\n pindexLast.nTime = 1233061996; \/\/ Block #2015\n pindexLast.nBits = 0x1d00ffff;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00ffff);\n}\n\n\/* Test the constraint on the lower bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1279008237; \/\/ Block #66528\n CBlockIndex pindexLast;\n pindexLast.nHeight = 68543;\n pindexLast.nTime = 1279297671; \/\/ Block #68543\n pindexLast.nBits = 0x1c05a3f4;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fd);\n}\n\n\/* Test the constraint on the upper bound for actual time taken *\/\nBOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n int64_t nLastRetargetTime = 1263163443; \/\/ NOTE: Not an actual block time\n CBlockIndex pindexLast;\n pindexLast.nHeight = 46367;\n pindexLast.nTime = 1269211443; \/\/ Block #46367\n pindexLast.nBits = 0x1c387f6f;\n BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);\n}\n\nBOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)\n{\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params& params = Params().GetConsensus();\n\n std::vector<CBlockIndex> blocks(10000);\n for (int i = 0; i < 10000; i++) {\n blocks[i].pprev = i ? &blocks[i - 1] : NULL;\n blocks[i].nHeight = i;\n blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;\n blocks[i].nBits = 0x207fffff; \/* target 0x7fffff000... *\/\n blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);\n }\n\n for (int j = 0; j < 1000; j++) {\n CBlockIndex *p1 = &blocks[GetRand(10000)];\n CBlockIndex *p2 = &blocks[GetRand(10000)];\n CBlockIndex *p3 = &blocks[GetRand(10000)];\n\n int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);\n BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());\n }\n}\n\nstatic CBlockIndex GetBlockIndex(CBlockIndex *pindexPrev, int64_t nTimeInterval, uint32_t nBits) {\n CBlockIndex block;\n block.pprev = pindexPrev;\n block.nHeight = pindexPrev->nHeight + 1;\n block.nTime = pindexPrev->nTime + nTimeInterval;\n block.nBits = nBits;\n\n return block;\n}\n\nBOOST_AUTO_TEST_CASE(retargeting_test) {\n SelectParams(CBaseChainParams::MAIN);\n const Consensus::Params ¶ms = Params().GetConsensus();\n\n std::vector<CBlockIndex> blocks(1013);\n\n \/\/ Genesis block?\n blocks[0] = CBlockIndex();\n blocks[0].nHeight = 0;\n blocks[0].nTime = 1269211443;\n blocks[0].nBits = 0x207fffff;\n\n \/\/ Pile up some blocks.\n for (size_t i = 1; i < 1000; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], params.nPowTargetSpacing, 0x207fffff);\n }\n\n CBlockHeader blkHeaderDummy;\n\n \/\/ We start getting 2h blocks time. For the first 5 blocks, it doesn't\n \/\/ matter as the MTP is not affected. For the next 5 block, MTP difference\n \/\/ increases but stays below 12h.\n for (size_t i = 1000; i < 1010; i++) {\n blocks[i] = GetBlockIndex(&blocks[i - 1], 2 * 3600, 0x207fffff);\n BOOST_CHECK_EQUAL(\n GetNextWorkRequired(&blocks[i], &blkHeaderDummy, params), 0x207fffff);\n }\n\n \/\/ turn UAHF off.\n mapArgs[\"-uahfstarttime\"] = \"0\";\n MockApplication::doInit();\n \/\/ unchanged.\n blocks[1010] = GetBlockIndex(&blocks[1009], 2 * 3600, 0x207fffff);\n BOOST_CHECK_EQUAL(GetNextWorkRequired(&blocks[1010], &blkHeaderDummy, params), 0x207fffff);\n\n \/\/ turn it on.\n mapArgs[\"-uahfstarttime\"] = \"1501590000\";\n MockApplication::doInit();\n \/\/ Now we expect the difficulty to decrease.\n blocks[1010] = GetBlockIndex(&blocks[1009], 2 * 3600, 0x207fffff);\n BOOST_CHECK_EQUAL(GetNextWorkRequired(&blocks[1010], &blkHeaderDummy, params), 0x1d00ffff);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\nusing namespace json_spirit;\n\nArray\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n Array result;\n result.push_back(nRequired);\n Array addresses;\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nValue CallRPC(string args)\n{\n vector<string> vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n Array params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n Value result = (*method)(params, false);\n return result;\n }\n catch (Object& objError)\n {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(rpc_tests)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n Value r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n Value r;\n \/\/ input is a 1-of-2 multisig (so is output):\n string prevout =\n \"[{\\\"txid\\\":\\\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\\\",\"\n \"\\\"redeemScript\\\":\\\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\\\":11}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\\\"\";\n string privkey2 = \"\\\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(0LL), false), \"0.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(1LL), false), \"0.00000001\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(17622195LL), false), \"0.17622195\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(50000000LL), false), \"0.50000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(89898989LL), false), \"0.89898989\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(100000000LL), false), \"1.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999990LL), false), \"20999999.99999990\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999999LL), false), \"20999999.99999999\");\n}\n\nstatic Value ValueFromString(const std::string &str)\n{\n Value value;\n BOOST_CHECK(read_string(str, value));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(json_parse_errors)\n{\n Value value;\n \/\/ Valid\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0\"), value), true);\n \/\/ Valid, with trailing whitespace\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0 \"), value), true);\n \/\/ Invalid, initial garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"[1.0\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"a1.0\"), value), false);\n \/\/ Invalid, trailing garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0sds\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0]\"), value), false);\n \/\/ BTC addresses should fail parsing\n BOOST_CHECK_EQUAL(read_string(std::string(\"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL\"), value), false);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>fix rpc_tests.cpp<commit_after>\/\/ Copyright (c) 2012-2013 The Bitcoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n\n#include \"base58.h\"\n#include \"netbase.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/test\/unit_test.hpp>\n\nusing namespace std;\nusing namespace json_spirit;\n\nArray\ncreateArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)\n{\n Array result;\n result.push_back(nRequired);\n Array addresses;\n if (address1) addresses.push_back(address1);\n if (address2) addresses.push_back(address2);\n result.push_back(addresses);\n return result;\n}\n\nValue CallRPC(string args)\n{\n vector<string> vArgs;\n boost::split(vArgs, args, boost::is_any_of(\" \\t\"));\n string strMethod = vArgs[0];\n vArgs.erase(vArgs.begin());\n Array params = RPCConvertValues(strMethod, vArgs);\n\n rpcfn_type method = tableRPC[strMethod]->actor;\n try {\n Value result = (*method)(params, false);\n return result;\n }\n catch (Object& objError)\n {\n throw runtime_error(find_value(objError, \"message\").get_str());\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(rpc_tests)\n\nBOOST_AUTO_TEST_CASE(rpc_rawparams)\n{\n \/\/ Test raw transaction API argument handling\n Value r;\n\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction not_hex\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction null null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction not_array\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] []\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction {} {}\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(\"createrawtransaction [] {}\"));\n BOOST_CHECK_THROW(CallRPC(\"createrawtransaction [] {} extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"decoderawtransaction DEADBEEF\"), runtime_error);\n string rawtx = \"0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000\";\n BOOST_CHECK_NO_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx));\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"version\").get_int(), 1);\n BOOST_CHECK_EQUAL(find_value(r.get_obj(), \"locktime\").get_int(), 0);\n BOOST_CHECK_THROW(r = CallRPC(string(\"decoderawtransaction \")+rawtx+\" extra\"), runtime_error);\n\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"signrawtransaction ff00\"), runtime_error);\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null NONE|ANYONECANPAY\"));\n BOOST_CHECK_NO_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" [] [] NONE|ANYONECANPAY\"));\n BOOST_CHECK_THROW(CallRPC(string(\"signrawtransaction \")+rawtx+\" null null badenum\"), runtime_error);\n\n \/\/ Only check failure cases for sendrawtransaction, there's no network to send to...\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction null\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(\"sendrawtransaction DEADBEEF\"), runtime_error);\n BOOST_CHECK_THROW(CallRPC(string(\"sendrawtransaction \")+rawtx+\" extra\"), runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_rawsign)\n{\n Value r;\n \/\/ input is a 1-of-2 multisig (so is output):\n string prevout =\n \"[{\\\"txid\\\":\\\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\\\",\"\n \"\\\"vout\\\":1,\\\"scriptPubKey\\\":\\\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\\\",\"\n \"\\\"redeemScript\\\":\\\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\\\"}]\";\n r = CallRPC(string(\"createrawtransaction \")+prevout+\" \"+\n \"{\\\"7iYoULd4BAqRsRt1UbD5qqna88JvKRU3SL\\\":11}\");\n string notsigned = r.get_str();\n string privkey1 = \"\\\"XEwTRsCX3CiWSQf8YmKMTeb84KyTbibkUv9mDTZHQ5MwuKG2ZzES\\\"\";\n string privkey2 = \"\\\"XDmZ7LjGd94Q81eUBjb2h6uV5Y14s7fmeXWEGYabfBJP8RVpprBu\\\"\";\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == false);\n r = CallRPC(string(\"signrawtransaction \")+notsigned+\" \"+prevout+\" \"+\"[\"+privkey1+\",\"+privkey2+\"]\");\n BOOST_CHECK(find_value(r.get_obj(), \"complete\").get_bool() == true);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_format_monetary_values)\n{\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(0LL), false), \"0.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(1LL), false), \"0.00000001\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(17622195LL), false), \"0.17622195\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(50000000LL), false), \"0.50000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(89898989LL), false), \"0.89898989\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(100000000LL), false), \"1.00000000\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999990LL), false), \"20999999.99999990\");\n BOOST_CHECK_EQUAL(write_string(ValueFromAmount(2099999999999999LL), false), \"20999999.99999999\");\n}\n\nstatic Value ValueFromString(const std::string &str)\n{\n Value value;\n BOOST_CHECK(read_string(str, value));\n return value;\n}\n\nBOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)\n{\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.00000001\")), 1LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.17622195\")), 17622195LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.5\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.50000000\")), 50000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"0.89898989\")), 89898989LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"1.00000000\")), 100000000LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.9999999\")), 2099999999999990LL);\n BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString(\"20999999.99999999\")), 2099999999999999LL);\n}\n\nBOOST_AUTO_TEST_CASE(json_parse_errors)\n{\n Value value;\n \/\/ Valid\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0\"), value), true);\n \/\/ Valid, with trailing whitespace\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0 \"), value), true);\n \/\/ Invalid, initial garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"[1.0\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"a1.0\"), value), false);\n \/\/ Invalid, trailing garbage\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0sds\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"1.0]\"), value), false);\n \/\/ BTC addresses should fail parsing\n BOOST_CHECK_EQUAL(read_string(std::string(\"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W\"), value), false);\n BOOST_CHECK_EQUAL(read_string(std::string(\"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL\"), value), false);\n}\n\nBOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)\n{\n \/\/ Check IPv4 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"1.2.3.4\")).ToString(), \"1.2.3.4\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ Check IPv6 addresses\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::1\")).ToString(), \"::1\");\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"123:4567:89ab:cdef:123:4567:89ab:cdef\")).ToString(),\n \"123:4567:89ab:cdef:123:4567:89ab:cdef\");\n \/\/ v4 compatible must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::0:127.0.0.1\")).ToString(), \"127.0.0.1\");\n \/\/ v4 mapped must be interpreted as IPv4\n BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string(\"::ffff:127.0.0.1\")).ToString(), \"127.0.0.1\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*\n* TLS Client\n* (C) 2004-2011 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include <botan\/tls_client.h>\n#include <botan\/internal\/tls_session_key.h>\n#include <botan\/internal\/tls_handshake_state.h>\n#include <botan\/internal\/stl_util.h>\n#include <botan\/rsa.h>\n#include <botan\/dsa.h>\n#include <botan\/dh.h>\n\nnamespace Botan {\n\n\/*\n* TLS Client Constructor\n*\/\nTLS_Client::TLS_Client(std::tr1::function<void (const byte[], size_t)> output_fn,\n std::tr1::function<void (const byte[], size_t, u16bit)> proc_fn,\n std::tr1::function<bool (const TLS_Session&)> handshake_fn,\n TLS_Session_Manager& session_manager,\n Credentials_Manager& creds,\n const TLS_Policy& policy,\n RandomNumberGenerator& rng,\n const std::string& hostname) :\n TLS_Channel(output_fn, proc_fn, handshake_fn),\n policy(policy),\n rng(rng),\n session_manager(session_manager),\n creds(creds)\n {\n writer.set_version(SSL_V3);\n\n state = new Handshake_State;\n state->set_expected_next(SERVER_HELLO);\n\n const std::string srp_identifier = creds.srp_identifier(\"tls-client\", hostname);\n\n if(hostname != \"\")\n {\n TLS_Session session_info;\n if(session_manager.load_from_host_info(hostname, 0, session_info))\n {\n if(session_info.srp_identifier() == srp_identifier)\n {\n state->client_hello = new Client_Hello(\n writer,\n state->hash,\n rng,\n session_info);\n\n state->resume_master_secret = session_info.master_secret();\n }\n }\n }\n\n if(!state->client_hello) \/\/ not resuming\n {\n state->client_hello = new Client_Hello(\n writer,\n state->hash,\n policy,\n rng,\n secure_renegotiation.for_client_hello(),\n hostname,\n srp_identifier);\n }\n\n secure_renegotiation.update(state->client_hello);\n }\n\n\/*\n* Send a new client hello to renegotiate\n*\/\nvoid TLS_Client::renegotiate()\n {\n if(state)\n return; \/\/ currently in handshake\n\n state = new Handshake_State;\n state->set_expected_next(SERVER_HELLO);\n\n state->client_hello = new Client_Hello(writer, state->hash, policy, rng,\n secure_renegotiation.for_client_hello());\n\n secure_renegotiation.update(state->client_hello);\n }\n\n\/*\n* Process a handshake message\n*\/\nvoid TLS_Client::process_handshake_msg(Handshake_Type type,\n const MemoryRegion<byte>& contents)\n {\n if(state == 0)\n throw Unexpected_Message(\"Unexpected handshake message from server\");\n\n if(type == HELLO_REQUEST)\n {\n Hello_Request hello_request(contents);\n\n \/\/ Ignore request entirely if we are currently negotiating a handshake\n if(state->client_hello)\n return;\n\n if(!secure_renegotiation.supported() && policy.require_secure_renegotiation())\n {\n delete state;\n state = 0;\n\n \/\/ RFC 5746 section 4.2\n alert(WARNING, NO_RENEGOTIATION);\n return;\n }\n\n state->set_expected_next(SERVER_HELLO);\n state->client_hello = new Client_Hello(writer, state->hash, policy, rng,\n secure_renegotiation.for_client_hello());\n\n secure_renegotiation.update(state->client_hello);\n\n return;\n }\n\n state->confirm_transition_to(type);\n\n if(type != HANDSHAKE_CCS && type != FINISHED)\n state->hash.update(type, contents);\n\n if(type == SERVER_HELLO)\n {\n state->server_hello = new Server_Hello(contents);\n\n if(!state->client_hello->offered_suite(state->server_hello->ciphersuite()))\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad ciphersuite\");\n }\n\n if(!value_exists(state->client_hello->compression_methods(),\n state->server_hello->compression_method()))\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad compression method\");\n }\n\n state->version = state->server_hello->version();\n\n writer.set_version(state->version);\n reader.set_version(state->version);\n\n secure_renegotiation.update(state->server_hello);\n\n state->suite = TLS_Cipher_Suite(state->server_hello->ciphersuite());\n\n if(!state->server_hello->session_id().empty() &&\n (state->server_hello->session_id() == state->client_hello->session_id()))\n {\n \/\/ successful resumption\n\n \/*\n * In this case, we offered the original session and the server\n * must resume with it\n *\/\n if(state->server_hello->version() != state->client_hello->version())\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Server resumed session but with wrong version\");\n\n state->keys = SessionKeys(state->suite, state->version,\n state->resume_master_secret,\n state->client_hello->random(),\n state->server_hello->random(),\n true);\n\n state->set_expected_next(HANDSHAKE_CCS);\n }\n else\n {\n \/\/ new session\n\n if(state->version > state->client_hello->version())\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad version\");\n }\n\n if(state->version < policy.min_version())\n {\n throw TLS_Exception(PROTOCOL_VERSION,\n \"TLS_Client: Server is too old for specified policy\");\n }\n\n if(state->suite.sig_type() != TLS_ALGO_SIGNER_ANON)\n {\n state->set_expected_next(CERTIFICATE);\n }\n else if(state->suite.kex_type() != TLS_ALGO_KEYEXCH_NOKEX)\n {\n state->set_expected_next(SERVER_KEX);\n }\n else\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n }\n }\n }\n else if(type == CERTIFICATE)\n {\n if(state->suite.kex_type() != TLS_ALGO_KEYEXCH_NOKEX)\n {\n state->set_expected_next(SERVER_KEX);\n }\n else\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n }\n\n state->server_certs = new Certificate(contents);\n\n peer_certs = state->server_certs->cert_chain();\n if(peer_certs.size() == 0)\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: No certificates sent by server\");\n\n if(!policy.check_cert(peer_certs))\n throw TLS_Exception(BAD_CERTIFICATE,\n \"TLS_Client: Server certificate is not valid\");\n\n state->kex_pub = peer_certs[0].subject_public_key();\n\n bool is_dsa = false, is_rsa = false;\n\n if(dynamic_cast<DSA_PublicKey*>(state->kex_pub))\n is_dsa = true;\n else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub))\n is_rsa = true;\n else\n throw TLS_Exception(UNSUPPORTED_CERTIFICATE,\n \"Unknown key type received in server kex\");\n\n if((is_dsa && state->suite.sig_type() != TLS_ALGO_SIGNER_DSA) ||\n (is_rsa && state->suite.sig_type() != TLS_ALGO_SIGNER_RSA))\n throw TLS_Exception(ILLEGAL_PARAMETER,\n \"Certificate key type did not match ciphersuite\");\n }\n else if(type == SERVER_KEX)\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n\n state->server_kex = new Server_Key_Exchange(contents);\n\n if(state->kex_pub)\n delete state->kex_pub;\n\n state->kex_pub = state->server_kex->key();\n\n bool is_dh = false, is_rsa = false;\n\n if(dynamic_cast<DH_PublicKey*>(state->kex_pub))\n is_dh = true;\n else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub))\n is_rsa = true;\n else\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Unknown key type received in server kex\");\n\n if((is_dh && state->suite.kex_type() != TLS_ALGO_KEYEXCH_DH) ||\n (is_rsa && state->suite.kex_type() != TLS_ALGO_KEYEXCH_RSA))\n throw TLS_Exception(ILLEGAL_PARAMETER,\n \"Certificate key type did not match ciphersuite\");\n\n if(state->suite.sig_type() != TLS_ALGO_SIGNER_ANON)\n {\n if(!state->server_kex->verify(peer_certs[0],\n state->client_hello->random(),\n state->server_hello->random()))\n throw TLS_Exception(DECRYPT_ERROR,\n \"Bad signature on server key exchange\");\n }\n }\n else if(type == CERTIFICATE_REQUEST)\n {\n state->set_expected_next(SERVER_HELLO_DONE);\n state->cert_req = new Certificate_Req(contents);\n }\n else if(type == SERVER_HELLO_DONE)\n {\n state->set_expected_next(HANDSHAKE_CCS);\n\n state->server_hello_done = new Server_Hello_Done(contents);\n\n if(state->received_handshake_msg(CERTIFICATE_REQUEST))\n {\n std::vector<Certificate_Type> types =\n state->cert_req->acceptable_types();\n\n std::vector<X509_Certificate> client_certs =\n creds.cert_chain(\"\", \/\/ use types here\n \"tls-client\",\n state->client_hello->sni_hostname());\n\n state->client_certs = new Certificate(writer,\n state->hash,\n client_certs);\n }\n\n state->client_kex =\n new Client_Key_Exchange(writer, state->hash, rng,\n state->kex_pub, state->version,\n state->client_hello->version());\n\n if(state->received_handshake_msg(CERTIFICATE_REQUEST) &&\n !state->client_certs->empty())\n {\n Private_Key* private_key =\n creds.private_key_for(state->client_certs->cert_chain()[0],\n \"tls-client\",\n state->client_hello->sni_hostname());\n\n state->client_verify = new Certificate_Verify(writer, state->hash,\n rng, private_key);\n }\n\n state->keys = SessionKeys(state->suite, state->version,\n state->client_kex->pre_master_secret(),\n state->client_hello->random(),\n state->server_hello->random());\n\n writer.send(CHANGE_CIPHER_SPEC, 1);\n\n writer.activate(state->suite, state->keys, CLIENT);\n\n state->client_finished = new Finished(writer, state->hash,\n state->version, CLIENT,\n state->keys.master_secret());\n }\n else if(type == HANDSHAKE_CCS)\n {\n state->set_expected_next(FINISHED);\n\n reader.activate(state->suite, state->keys, CLIENT);\n }\n else if(type == FINISHED)\n {\n state->set_expected_next(HELLO_REQUEST);\n\n state->server_finished = new Finished(contents);\n\n if(!state->server_finished->verify(state->keys.master_secret(),\n state->version, state->hash, SERVER))\n throw TLS_Exception(DECRYPT_ERROR,\n \"Finished message didn't verify\");\n\n state->hash.update(type, contents);\n\n if(!state->client_finished) \/\/ session resume case\n {\n writer.send(CHANGE_CIPHER_SPEC, 1);\n\n writer.activate(state->suite, state->keys, CLIENT);\n\n state->client_finished = new Finished(writer, state->hash,\n state->version, CLIENT,\n state->keys.master_secret());\n }\n\n TLS_Session session_info(\n state->server_hello->session_id(),\n state->keys.master_secret(),\n state->server_hello->version(),\n state->server_hello->ciphersuite(),\n state->server_hello->compression_method(),\n CLIENT,\n secure_renegotiation.supported(),\n state->server_hello->fragment_size(),\n peer_certs,\n state->client_hello->sni_hostname(),\n \"\"\n );\n\n bool save_session = true;\n\n if(handshake_fn)\n save_session = handshake_fn(session_info);\n\n if(save_session)\n session_manager.save(session_info);\n\n secure_renegotiation.update(state->client_finished, state->server_finished);\n\n delete state;\n state = 0;\n handshake_completed = true;\n }\n else\n throw Unexpected_Message(\"Unknown handshake message received\");\n }\n\n}\n<commit_msg>Assume handshake_fn exists<commit_after>\/*\n* TLS Client\n* (C) 2004-2011 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include <botan\/tls_client.h>\n#include <botan\/internal\/tls_session_key.h>\n#include <botan\/internal\/tls_handshake_state.h>\n#include <botan\/internal\/stl_util.h>\n#include <botan\/rsa.h>\n#include <botan\/dsa.h>\n#include <botan\/dh.h>\n\nnamespace Botan {\n\n\/*\n* TLS Client Constructor\n*\/\nTLS_Client::TLS_Client(std::tr1::function<void (const byte[], size_t)> output_fn,\n std::tr1::function<void (const byte[], size_t, u16bit)> proc_fn,\n std::tr1::function<bool (const TLS_Session&)> handshake_fn,\n TLS_Session_Manager& session_manager,\n Credentials_Manager& creds,\n const TLS_Policy& policy,\n RandomNumberGenerator& rng,\n const std::string& hostname) :\n TLS_Channel(output_fn, proc_fn, handshake_fn),\n policy(policy),\n rng(rng),\n session_manager(session_manager),\n creds(creds)\n {\n writer.set_version(SSL_V3);\n\n state = new Handshake_State;\n state->set_expected_next(SERVER_HELLO);\n\n const std::string srp_identifier = creds.srp_identifier(\"tls-client\", hostname);\n\n if(hostname != \"\")\n {\n TLS_Session session_info;\n if(session_manager.load_from_host_info(hostname, 0, session_info))\n {\n if(session_info.srp_identifier() == srp_identifier)\n {\n state->client_hello = new Client_Hello(\n writer,\n state->hash,\n rng,\n session_info);\n\n state->resume_master_secret = session_info.master_secret();\n }\n }\n }\n\n if(!state->client_hello) \/\/ not resuming\n {\n state->client_hello = new Client_Hello(\n writer,\n state->hash,\n policy,\n rng,\n secure_renegotiation.for_client_hello(),\n hostname,\n srp_identifier);\n }\n\n secure_renegotiation.update(state->client_hello);\n }\n\n\/*\n* Send a new client hello to renegotiate\n*\/\nvoid TLS_Client::renegotiate()\n {\n if(state)\n return; \/\/ currently in handshake\n\n state = new Handshake_State;\n state->set_expected_next(SERVER_HELLO);\n\n state->client_hello = new Client_Hello(writer, state->hash, policy, rng,\n secure_renegotiation.for_client_hello());\n\n secure_renegotiation.update(state->client_hello);\n }\n\n\/*\n* Process a handshake message\n*\/\nvoid TLS_Client::process_handshake_msg(Handshake_Type type,\n const MemoryRegion<byte>& contents)\n {\n if(state == 0)\n throw Unexpected_Message(\"Unexpected handshake message from server\");\n\n if(type == HELLO_REQUEST)\n {\n Hello_Request hello_request(contents);\n\n \/\/ Ignore request entirely if we are currently negotiating a handshake\n if(state->client_hello)\n return;\n\n if(!secure_renegotiation.supported() && policy.require_secure_renegotiation())\n {\n delete state;\n state = 0;\n\n \/\/ RFC 5746 section 4.2\n alert(WARNING, NO_RENEGOTIATION);\n return;\n }\n\n state->set_expected_next(SERVER_HELLO);\n state->client_hello = new Client_Hello(writer, state->hash, policy, rng,\n secure_renegotiation.for_client_hello());\n\n secure_renegotiation.update(state->client_hello);\n\n return;\n }\n\n state->confirm_transition_to(type);\n\n if(type != HANDSHAKE_CCS && type != FINISHED)\n state->hash.update(type, contents);\n\n if(type == SERVER_HELLO)\n {\n state->server_hello = new Server_Hello(contents);\n\n if(!state->client_hello->offered_suite(state->server_hello->ciphersuite()))\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad ciphersuite\");\n }\n\n if(!value_exists(state->client_hello->compression_methods(),\n state->server_hello->compression_method()))\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad compression method\");\n }\n\n state->version = state->server_hello->version();\n\n writer.set_version(state->version);\n reader.set_version(state->version);\n\n secure_renegotiation.update(state->server_hello);\n\n state->suite = TLS_Cipher_Suite(state->server_hello->ciphersuite());\n\n if(!state->server_hello->session_id().empty() &&\n (state->server_hello->session_id() == state->client_hello->session_id()))\n {\n \/\/ successful resumption\n\n \/*\n * In this case, we offered the original session and the server\n * must resume with it\n *\/\n if(state->server_hello->version() != state->client_hello->version())\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Server resumed session but with wrong version\");\n\n state->keys = SessionKeys(state->suite, state->version,\n state->resume_master_secret,\n state->client_hello->random(),\n state->server_hello->random(),\n true);\n\n state->set_expected_next(HANDSHAKE_CCS);\n }\n else\n {\n \/\/ new session\n\n if(state->version > state->client_hello->version())\n {\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: Server replied with bad version\");\n }\n\n if(state->version < policy.min_version())\n {\n throw TLS_Exception(PROTOCOL_VERSION,\n \"TLS_Client: Server is too old for specified policy\");\n }\n\n if(state->suite.sig_type() != TLS_ALGO_SIGNER_ANON)\n {\n state->set_expected_next(CERTIFICATE);\n }\n else if(state->suite.kex_type() != TLS_ALGO_KEYEXCH_NOKEX)\n {\n state->set_expected_next(SERVER_KEX);\n }\n else\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n }\n }\n }\n else if(type == CERTIFICATE)\n {\n if(state->suite.kex_type() != TLS_ALGO_KEYEXCH_NOKEX)\n {\n state->set_expected_next(SERVER_KEX);\n }\n else\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n }\n\n state->server_certs = new Certificate(contents);\n\n peer_certs = state->server_certs->cert_chain();\n if(peer_certs.size() == 0)\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"TLS_Client: No certificates sent by server\");\n\n if(!policy.check_cert(peer_certs))\n throw TLS_Exception(BAD_CERTIFICATE,\n \"TLS_Client: Server certificate is not valid\");\n\n state->kex_pub = peer_certs[0].subject_public_key();\n\n bool is_dsa = false, is_rsa = false;\n\n if(dynamic_cast<DSA_PublicKey*>(state->kex_pub))\n is_dsa = true;\n else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub))\n is_rsa = true;\n else\n throw TLS_Exception(UNSUPPORTED_CERTIFICATE,\n \"Unknown key type received in server kex\");\n\n if((is_dsa && state->suite.sig_type() != TLS_ALGO_SIGNER_DSA) ||\n (is_rsa && state->suite.sig_type() != TLS_ALGO_SIGNER_RSA))\n throw TLS_Exception(ILLEGAL_PARAMETER,\n \"Certificate key type did not match ciphersuite\");\n }\n else if(type == SERVER_KEX)\n {\n state->set_expected_next(CERTIFICATE_REQUEST); \/\/ optional\n state->set_expected_next(SERVER_HELLO_DONE);\n\n state->server_kex = new Server_Key_Exchange(contents);\n\n if(state->kex_pub)\n delete state->kex_pub;\n\n state->kex_pub = state->server_kex->key();\n\n bool is_dh = false, is_rsa = false;\n\n if(dynamic_cast<DH_PublicKey*>(state->kex_pub))\n is_dh = true;\n else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub))\n is_rsa = true;\n else\n throw TLS_Exception(HANDSHAKE_FAILURE,\n \"Unknown key type received in server kex\");\n\n if((is_dh && state->suite.kex_type() != TLS_ALGO_KEYEXCH_DH) ||\n (is_rsa && state->suite.kex_type() != TLS_ALGO_KEYEXCH_RSA))\n throw TLS_Exception(ILLEGAL_PARAMETER,\n \"Certificate key type did not match ciphersuite\");\n\n if(state->suite.sig_type() != TLS_ALGO_SIGNER_ANON)\n {\n if(!state->server_kex->verify(peer_certs[0],\n state->client_hello->random(),\n state->server_hello->random()))\n throw TLS_Exception(DECRYPT_ERROR,\n \"Bad signature on server key exchange\");\n }\n }\n else if(type == CERTIFICATE_REQUEST)\n {\n state->set_expected_next(SERVER_HELLO_DONE);\n state->cert_req = new Certificate_Req(contents);\n }\n else if(type == SERVER_HELLO_DONE)\n {\n state->set_expected_next(HANDSHAKE_CCS);\n\n state->server_hello_done = new Server_Hello_Done(contents);\n\n if(state->received_handshake_msg(CERTIFICATE_REQUEST))\n {\n std::vector<Certificate_Type> types =\n state->cert_req->acceptable_types();\n\n std::vector<X509_Certificate> client_certs =\n creds.cert_chain(\"\", \/\/ use types here\n \"tls-client\",\n state->client_hello->sni_hostname());\n\n state->client_certs = new Certificate(writer,\n state->hash,\n client_certs);\n }\n\n state->client_kex =\n new Client_Key_Exchange(writer, state->hash, rng,\n state->kex_pub, state->version,\n state->client_hello->version());\n\n if(state->received_handshake_msg(CERTIFICATE_REQUEST) &&\n !state->client_certs->empty())\n {\n Private_Key* private_key =\n creds.private_key_for(state->client_certs->cert_chain()[0],\n \"tls-client\",\n state->client_hello->sni_hostname());\n\n state->client_verify = new Certificate_Verify(writer, state->hash,\n rng, private_key);\n }\n\n state->keys = SessionKeys(state->suite, state->version,\n state->client_kex->pre_master_secret(),\n state->client_hello->random(),\n state->server_hello->random());\n\n writer.send(CHANGE_CIPHER_SPEC, 1);\n\n writer.activate(state->suite, state->keys, CLIENT);\n\n state->client_finished = new Finished(writer, state->hash,\n state->version, CLIENT,\n state->keys.master_secret());\n }\n else if(type == HANDSHAKE_CCS)\n {\n state->set_expected_next(FINISHED);\n\n reader.activate(state->suite, state->keys, CLIENT);\n }\n else if(type == FINISHED)\n {\n state->set_expected_next(HELLO_REQUEST);\n\n state->server_finished = new Finished(contents);\n\n if(!state->server_finished->verify(state->keys.master_secret(),\n state->version, state->hash, SERVER))\n throw TLS_Exception(DECRYPT_ERROR,\n \"Finished message didn't verify\");\n\n state->hash.update(type, contents);\n\n if(!state->client_finished) \/\/ session resume case\n {\n writer.send(CHANGE_CIPHER_SPEC, 1);\n\n writer.activate(state->suite, state->keys, CLIENT);\n\n state->client_finished = new Finished(writer, state->hash,\n state->version, CLIENT,\n state->keys.master_secret());\n }\n\n TLS_Session session_info(\n state->server_hello->session_id(),\n state->keys.master_secret(),\n state->server_hello->version(),\n state->server_hello->ciphersuite(),\n state->server_hello->compression_method(),\n CLIENT,\n secure_renegotiation.supported(),\n state->server_hello->fragment_size(),\n peer_certs,\n state->client_hello->sni_hostname(),\n \"\"\n );\n\n if(handshake_fn(session_info))\n session_manager.save(session_info);\n\n secure_renegotiation.update(state->client_finished, state->server_finished);\n\n delete state;\n state = 0;\n handshake_completed = true;\n }\n else\n throw Unexpected_Message(\"Unknown handshake message received\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"benchmark.hpp\"\n#include <array>\n#include <sstream>\n#include <algorithm>\nextern \"C\"\n{\n#include <omp.h>\n}\n#include \"parameter.hpp\"\n#include \"mpi.hpp\"\n#include \"..\/misc\/allocator.hpp\"\n#include \"..\/misc\/time.hpp\"\n#include \"communicator.hpp\"\n#include \"connection.hpp\"\n#include \"sendwindow.hpp\"\n#include \"recvwindow.hpp\"\n\nvoid runBenchmark(int argc, char **argv)\n{\n \/\/ Default options\n int dim = 1;\n std::vector<int> geom;\n std::vector<int> periodic;\n std::uint64_t maxIter = 1e4;\n std::uint64_t overallSize = 1024 * 1024 * 1024;\n std::uint32_t minMsgSize = 0;\n std::uint32_t maxMsgSize = 128 * 1024;\n std::uint32_t deltaMsgSize = 4 * 1024;\n bool bufferedSend = false;\n bool bufferedRecv = false;\n\n \/\/ Get additional parameter options\n parameterOption(argv, argv + argc, \"--dim\", dim); \n geom.resize(dim, 0);\n periodic.resize(dim, 1);\n parameterOption(argv, argv + argc, \"--geom\", geom);\n parameterOption(argv, argv + argc, \"--periodic\", periodic);\n parameterOption<std::uint64_t>(argv, argv + argc, \"--maxIter\", maxIter);\n parameterOption<std::uint64_t>(argv, argv + argc, \"--overallSize\",\n overallSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--minMsgSize\",\n minMsgSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--maxMsgSize\",\n maxMsgSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--deltaMsgSize\",\n deltaMsgSize);\n if(parameterExists(argv, argv + argc, \"--bufferedSend\"))\n {\n bufferedSend = true;\n }\n if(parameterExists(argv, argv + argc, \"--bufferedRecv\"))\n {\n bufferedRecv = true;\n }\n std::string benchmark;\n parameterOption<std::string>(argv, argv + argc, \"--benchmark\", benchmark);\n if(benchmark != \"exchange\" and benchmark != \"sendrecv\")\n {\n printUsage();\n }\n\n \/\/ Prepare benchmark environment\n pMR::Communicator communicator(MPI_COMM_WORLD, geom, periodic);\n \n \/\/ Establish connections\n std::vector<pMR::Connection> connections;\n\n for(int n = 0; n != communicator.dimensions(); ++n)\n {\n if(communicator.size(n) > 1)\n {\n if(communicator.coordinate(n) % 2 == 1)\n {\n connections.emplace_back(communicator.getNeighbor(n, -1));\n connections.emplace_back(communicator.getNeighbor(n, +1));\n }\n else\n {\n connections.emplace_back(communicator.getNeighbor(n, +1));\n connections.emplace(connections.end() - 1,\n communicator.getNeighbor(n, -1));\n }\n }\n }\n\n \/\/ Print Benchmark Information\n printMaster(\"Benchmark: \", benchmark);\n printMaster(\"Processes: \", communicator.size());\n printMaster(\"Dimensions: \", static_cast<int>(connections.size()\/2), \"\/\",\n communicator.dimensions());\n printMaster(\"Topology: \", communicator.topology());\n printMaster(\"Periodic: \", communicator.periodic());\n printMaster(\"BufferedSend:\", bufferedSend);\n printMaster(\"BufferedRecv:\", bufferedRecv);\n printMaster();\n \n printMaster(\" MPIRank Size[By] Iteration Time\/It[s] Bandwidth[MB\/s]\");\n\n \/\/ Loop Message Sizes\n auto msgSize = minMsgSize;\n while(msgSize <= maxMsgSize)\n {\n std::vector<std::vector<char, pMR::AlignedAllocator<char>>>\n sendBuffers, recvBuffers;\n std::vector<pMR::SendWindow<char>> sendWindows;\n std::vector<pMR::RecvWindow<char>> recvWindows;\n \n \/\/ Create Buffers and Windows\n for(decltype(connections.size()) c = 0; c != connections.size(); ++c)\n {\n sendBuffers.emplace_back(msgSize);\n if(bufferedSend)\n {\n sendWindows.emplace_back(connections[c], msgSize);\n }\n else\n {\n sendWindows.emplace_back(connections[c],\n sendBuffers.back().data(), msgSize);\n }\n\n if(benchmark == \"sendrecv\")\n {\n ++c;\n }\n\n recvBuffers.emplace_back(msgSize);\n if(bufferedRecv)\n {\n recvWindows.emplace_back(connections[c], msgSize);\n }\n else\n {\n recvWindows.emplace_back(connections[c],\n recvBuffers.back().data(), msgSize);\n }\n }\n\n \/\/ Increment msgSize for next loop\n msgSize += deltaMsgSize;\n\n \/\/ Go to next loop if nothing to do\n if(sendWindows.size() == 0 and recvWindows.size() == 0)\n {\n continue;\n }\n\n \/\/ Calculate iterations count\n auto iter = maxIter;\n if(msgSize)\n {\n iter = std::min(iter, overallSize \/ msgSize \/\n static_cast<std::uint64_t>(sendWindows.size()));\n }\n\n double time = -pMR::getTimeInSeconds();\n for(decltype(iter) i = 0; i != iter; ++i)\n {\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.init();\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.init();\n }\n if(bufferedSend)\n {\n for(decltype(sendWindows.size()) s = 0; s != sendWindows.size();\n ++s)\n {\n sendWindows[s].insert(sendBuffers[s].cbegin());\n }\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.post();\n }\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.post();\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.wait();\n }\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.wait();\n }\n if(bufferedRecv)\n {\n for(decltype(recvWindows.size()) r = 0; r != recvWindows.size();\n ++r)\n {\n recvWindows[r].extract(recvBuffers[r].begin());\n }\n }\n }\n time += pMR::getTimeInSeconds();\n pMR::print(static_cast<std::uint32_t>(getRank(MPI_COMM_WORLD)),\n msgSize, iter, time \/ iter,\n msgSize * iter * sendWindows.size() \/ time \/ 1024 \/ 1024 );\n }\n\n \/\/ Exit application\n finalize();\n}\n<commit_msg>Use unsigned char to allocate plain memory<commit_after>#include \"benchmark.hpp\"\n#include <array>\n#include <sstream>\n#include <algorithm>\nextern \"C\"\n{\n#include <omp.h>\n}\n#include \"parameter.hpp\"\n#include \"mpi.hpp\"\n#include \"..\/misc\/allocator.hpp\"\n#include \"..\/misc\/time.hpp\"\n#include \"communicator.hpp\"\n#include \"connection.hpp\"\n#include \"sendwindow.hpp\"\n#include \"recvwindow.hpp\"\n\nvoid runBenchmark(int argc, char **argv)\n{\n \/\/ Default options\n int dim = 1;\n std::vector<int> geom;\n std::vector<int> periodic;\n std::uint64_t maxIter = 1e4;\n std::uint64_t overallSize = 1024 * 1024 * 1024;\n std::uint32_t minMsgSize = 0;\n std::uint32_t maxMsgSize = 128 * 1024;\n std::uint32_t deltaMsgSize = 4 * 1024;\n bool bufferedSend = false;\n bool bufferedRecv = false;\n\n \/\/ Get additional parameter options\n parameterOption(argv, argv + argc, \"--dim\", dim); \n geom.resize(dim, 0);\n periodic.resize(dim, 1);\n parameterOption(argv, argv + argc, \"--geom\", geom);\n parameterOption(argv, argv + argc, \"--periodic\", periodic);\n parameterOption<std::uint64_t>(argv, argv + argc, \"--maxIter\", maxIter);\n parameterOption<std::uint64_t>(argv, argv + argc, \"--overallSize\",\n overallSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--minMsgSize\",\n minMsgSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--maxMsgSize\",\n maxMsgSize);\n parameterOption<std::uint32_t>(argv, argv + argc, \"--deltaMsgSize\",\n deltaMsgSize);\n if(parameterExists(argv, argv + argc, \"--bufferedSend\"))\n {\n bufferedSend = true;\n }\n if(parameterExists(argv, argv + argc, \"--bufferedRecv\"))\n {\n bufferedRecv = true;\n }\n std::string benchmark;\n parameterOption<std::string>(argv, argv + argc, \"--benchmark\", benchmark);\n if(benchmark != \"exchange\" and benchmark != \"sendrecv\")\n {\n printUsage();\n }\n\n \/\/ Prepare benchmark environment\n pMR::Communicator communicator(MPI_COMM_WORLD, geom, periodic);\n \n \/\/ Establish connections\n std::vector<pMR::Connection> connections;\n\n for(int n = 0; n != communicator.dimensions(); ++n)\n {\n if(communicator.size(n) > 1)\n {\n if(communicator.coordinate(n) % 2 == 1)\n {\n connections.emplace_back(communicator.getNeighbor(n, -1));\n connections.emplace_back(communicator.getNeighbor(n, +1));\n }\n else\n {\n connections.emplace_back(communicator.getNeighbor(n, +1));\n connections.emplace(connections.end() - 1,\n communicator.getNeighbor(n, -1));\n }\n }\n }\n\n \/\/ Print Benchmark Information\n printMaster(\"Benchmark: \", benchmark);\n printMaster(\"Processes: \", communicator.size());\n printMaster(\"Dimensions: \", static_cast<int>(connections.size()\/2), \"\/\",\n communicator.dimensions());\n printMaster(\"Topology: \", communicator.topology());\n printMaster(\"Periodic: \", communicator.periodic());\n printMaster(\"BufferedSend:\", bufferedSend);\n printMaster(\"BufferedRecv:\", bufferedRecv);\n printMaster();\n \n printMaster(\" MPIRank Size[By] Iteration Time\/It[s] Bandwidth[MB\/s]\");\n\n \/\/ Loop Message Sizes\n auto msgSize = minMsgSize;\n while(msgSize <= maxMsgSize)\n {\n std::vector<std::vector<unsigned char, pMR::AlignedAllocator<unsigned char>>>\n sendBuffers, recvBuffers;\n std::vector<pMR::SendWindow<unsigned char>> sendWindows;\n std::vector<pMR::RecvWindow<unsigned char>> recvWindows;\n \n \/\/ Create Buffers and Windows\n for(decltype(connections.size()) c = 0; c != connections.size(); ++c)\n {\n sendBuffers.emplace_back(msgSize);\n if(bufferedSend)\n {\n sendWindows.emplace_back(connections[c], msgSize);\n }\n else\n {\n sendWindows.emplace_back(connections[c],\n sendBuffers.back().data(), msgSize);\n }\n\n if(benchmark == \"sendrecv\")\n {\n ++c;\n }\n\n recvBuffers.emplace_back(msgSize);\n if(bufferedRecv)\n {\n recvWindows.emplace_back(connections[c], msgSize);\n }\n else\n {\n recvWindows.emplace_back(connections[c],\n recvBuffers.back().data(), msgSize);\n }\n }\n\n \/\/ Increment msgSize for next loop\n msgSize += deltaMsgSize;\n\n \/\/ Go to next loop if nothing to do\n if(sendWindows.size() == 0 and recvWindows.size() == 0)\n {\n continue;\n }\n\n \/\/ Calculate iterations count\n auto iter = maxIter;\n if(msgSize)\n {\n iter = std::min(iter, overallSize \/ msgSize \/\n static_cast<std::uint64_t>(sendWindows.size()));\n }\n\n double time = -pMR::getTimeInSeconds();\n for(decltype(iter) i = 0; i != iter; ++i)\n {\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.init();\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.init();\n }\n if(bufferedSend)\n {\n for(decltype(sendWindows.size()) s = 0; s != sendWindows.size();\n ++s)\n {\n sendWindows[s].insert(sendBuffers[s].cbegin());\n }\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.post();\n }\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.post();\n }\n for(auto &sendWindow : sendWindows)\n {\n sendWindow.wait();\n }\n for(auto &recvWindow : recvWindows)\n {\n recvWindow.wait();\n }\n if(bufferedRecv)\n {\n for(decltype(recvWindows.size()) r = 0; r != recvWindows.size();\n ++r)\n {\n recvWindows[r].extract(recvBuffers[r].begin());\n }\n }\n }\n time += pMR::getTimeInSeconds();\n pMR::print(static_cast<std::uint32_t>(getRank(MPI_COMM_WORLD)),\n msgSize, iter, time \/ iter,\n msgSize * iter * sendWindows.size() \/ time \/ 1024 \/ 1024 );\n }\n\n \/\/ Exit application\n finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * Paraver Main Computing Library *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <type_traits>\n\n#include \"tracebodyio_v1.h\"\n\nusing namespace std;\n\nstring TraceBodyIO_v1::multiEventLine;\nTraceBodyIO_v1::TMultiEventCommonInfo TraceBodyIO_v1::multiEventCommonInfo =\n { nullptr, (TThreadOrder)0, (TCPUOrder)0, (TRecordTime)0 };\n\nstring TraceBodyIO_v1::line;\nostringstream TraceBodyIO_v1::ostr;\n\n\/\/ Optimization on conversion string to numbers, but with no error control\n\/\/#define USE_ATOLL\n\/\/ Even more optimization using custom function instead of atoll with error checking\n#define USE_PRV_ATOLL\nconstexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end )\n{\n return true;\n}\n\ntemplate <typename T, typename... Targs>\nbool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end, T& result, Targs&... Fargs )\n{\n T tmp = 0;\n bool neg = false;\n\n if( it == end )\n return false;\n\n if( *it == '-' )\n {\n neg = true;\n ++it;\n }\n\n if( neg && is_unsigned<T>::value )\n return false;\n\n while( *it >= '0' && *it <= '9' )\n {\n tmp = ( tmp * 10 ) + ( *it - '0' );\n ++it;\n }\n\n if( neg )\n result = -tmp;\n else\n result = tmp;\n\n if( it == end )\n return sizeof...( Targs ) == 0;\n\n return prv_atoll_v( ++it, end, Fargs... );\n}\n\nTraceBodyIO_v1::TraceBodyIO_v1( Trace* trace )\n: whichTrace( trace )\n{}\n\nbool TraceBodyIO_v1::ordered() const\n{\n return false;\n}\n\nvoid TraceBodyIO_v1::read( TraceStream *file, MemoryBlocks& records,\n unordered_set<TState>& states, unordered_set<TEventType>& events,\n MetadataManager& traceInfo ) const\n{\n file->getline( line );\n\n if ( line.size() == 0 )\n return;\n\n switch ( line[0] )\n {\n case CommentRecord:\n readTraceInfo( line, traceInfo );\n break;\n\n case StateRecord:\n readState( line, records, states );\n break;\n\n case EventRecord:\n readEvent( line, records, events );\n break;\n\n case CommRecord:\n readComm( line, records );\n break;\n\n case GlobalCommRecord:\n \/\/readGlobalComm( line, records );\n break;\n\n default:\n cerr << \"TraceBodyIO_v1::read()\" << endl;\n cerr << \"Unkwnown record type.\" << endl;\n break;\n };\n}\n\nvoid TraceBodyIO_v1::bufferWrite( fstream& whichStream, bool writeReady, bool lineClear ) const\n{\n if ( writeReady )\n {\n whichStream << line << '\\n';\n if ( lineClear )\n line.clear();\n }\n}\n\n\nvoid TraceBodyIO_v1::write( fstream& whichStream,\n const KTrace& whichTrace,\n MemoryTrace::iterator *record,\n PRV_INT32 numIter ) const\n{\n bool writeReady = false;\n TRecordType type = record->getType();\n line.clear();\n\n if ( type == EMPTYREC )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n }\n else\n {\n if ( type & STATE )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n writeReady = writeState( whichTrace, record );\n }\n else if ( type & EVENT )\n {\n if ( !sameMultiEvent( record ) )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n\n multiEventCommonInfo.myStream = &whichStream;\n multiEventCommonInfo.cpu = record->getCPU();\n multiEventCommonInfo.thread = record->getThread();\n multiEventCommonInfo.time = record->getTime();\n\n multiEventLine.clear();\n }\n\n appendEvent( record );\n }\n else if ( type & COMM )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n\n writeReady = writeComm( whichTrace, record );\n }\n else if ( type & GLOBCOMM )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n\n writeReady = writeGlobalComm( whichTrace, record );\n }\n else if ( type & RSEND || type & RRECV )\n writeReady = false;\n else\n {\n writeReady = false;\n cerr << \"TraceBodyIO_v1::write()\" << endl;\n cerr << \"Unkwnown record type in memory.\" << endl;\n }\n\n bufferWrite( whichStream, writeReady, false );\n }\n}\n\n\nvoid TraceBodyIO_v1::writeCommInfo( fstream& whichStream,\n const KTrace& whichTrace,\n PRV_INT32 numIter ) const\n{}\n\n\/**********************\n Read line functions\n***********************\/\ninline void TraceBodyIO_v1::readTraceInfo( const std::string& line, MetadataManager& traceInfo ) const\n{\n traceInfo.NewMetadata( line );\n \/\/ dummy set also to false if it is a comment\n}\n\ninline void TraceBodyIO_v1::readState( const string& line, MemoryBlocks& records,\n unordered_set<TState>& states ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime time;\n TRecordTime endtime;\n TState state;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )\n {\n cerr << \"Error reading state record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n if( !prv_atoll_v( it, line.cend(), endtime, state ) )\n {\n cerr << \"Error reading state record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newRecord();\n records.setType( STATE + BEGIN );\n records.setTime( time );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setState( state );\n records.setStateEndTime( endtime );\n\n if ( endtime != -1 )\n {\n records.newRecord();\n records.setType( STATE + END );\n records.setTime( endtime );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setState( state );\n records.setStateEndTime( time );\n }\n\n states.insert( state );\n}\n\n\ninline void TraceBodyIO_v1::readEvent( const string& line, MemoryBlocks& records,\n unordered_set<TEventType>& events ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime time;\n TEventType eventtype;\n TEventValue eventvalue;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )\n {\n cerr << \"Error reading event record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n while ( it != line.end() )\n {\n if( !prv_atoll_v( it, line.cend(), eventtype, eventvalue ) )\n {\n cerr << \"Error reading event record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newRecord();\n records.setType( EVENT );\n records.setTime( time );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setEventType( eventtype );\n records.setEventValue( eventvalue );\n\n events.insert( eventtype );\n }\n}\n\n\ninline void TraceBodyIO_v1::readComm( const string& line, MemoryBlocks& records ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime logSend;\n TRecordTime phySend;\n TRecordTime logReceive;\n TRecordTime phyReceive;\n TCPUOrder remoteCPU;\n TApplOrder remoteAppl;\n TTaskOrder remoteTask;\n TThreadOrder remoteThread;\n TCommSize commSize;\n TCommTag commTag;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, logSend ) )\n {\n cerr << \"Error reading communication record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n if( !prv_atoll_v( it, line.cend(), phySend, remoteCPU, remoteAppl, remoteTask, remoteThread, logReceive, phyReceive, commSize, commTag ) )\n {\n cerr << \"Error reading communication record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newComm();\n records.setSenderCPU( CPU );\n records.setSenderThread( appl - 1, task - 1, thread - 1 );\n records.setReceiverCPU( remoteCPU );\n records.setReceiverThread( remoteAppl - 1, remoteTask - 1, remoteThread - 1 );\n records.setLogicalSend( logSend );\n records.setPhysicalSend( phySend );\n records.setLogicalReceive( logReceive );\n records.setPhysicalReceive( phyReceive );\n records.setCommSize( commSize );\n records.setCommTag( commTag );\n}\n\n\ninline void TraceBodyIO_v1::readGlobalComm( const string& line, MemoryBlocks& records ) const\n{}\n\n\ninline bool TraceBodyIO_v1::readCommon( string::const_iterator& it,\n const string::const_iterator& end,\n TCPUOrder& CPU,\n TApplOrder& appl,\n TTaskOrder& task,\n TThreadOrder& thread,\n TRecordTime& time ) const\n{\n bool result;\n\n result = prv_atoll_v( it, end, CPU, appl, task, thread, time );\n\n if ( !resourceModel->isValidGlobalCPU( CPU ) )\n return false;\n\n if ( !processModel->isValidThread( appl - 1, task - 1, thread - 1 ) )\n return false;\n\n return true;\n}\n\n\n\/**************************\n Write records functions\n***************************\/\nbool TraceBodyIO_v1::writeState( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n if ( record->getType() & END )\n return false;\n\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n ostr << StateRecord << ':';\n writeCommon( ostr, whichTrace, record );\n ostr << record->getStateEndTime() << ':' << record->getState();\n\n line += ostr.str();\n return true;\n}\n\n\nbool TraceBodyIO_v1::writePendingMultiEvent( const KTrace& whichTrace ) const\n{\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n\n bool writeLine = !multiEventLine.empty();\n\n if ( writeLine )\n {\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n ostr << EventRecord << ':';\n ostr << multiEventCommonInfo.cpu << ':';\n\n whichTrace.getThreadLocation( multiEventCommonInfo.thread, appl, task, thread );\n ostr << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';\n\n ostr << multiEventCommonInfo.time << ':';\n ostr << multiEventLine;\n\n line += ostr.str();\n\n bufferWrite( *multiEventCommonInfo.myStream, true );\n\n multiEventCommonInfo.myStream = nullptr;\n multiEventCommonInfo.cpu = 0;\n multiEventCommonInfo.thread = 0;\n multiEventCommonInfo.time = 0;\n\n multiEventLine.clear();\n }\n\n return false;\n}\n\n\nvoid TraceBodyIO_v1::appendEvent( const MemoryTrace::iterator *record ) const\n{\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n if ( !multiEventLine.empty() )\n ostr << ':';\n\n ostr << record->getEventType() << ':' << record->getEventValueAsIs();\n\n multiEventLine += ostr.str();\n}\n\n\nbool TraceBodyIO_v1::writeComm( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n TCommID commID;\n TApplOrder recvAppl;\n TTaskOrder recvTask;\n TThreadOrder recvThread;\n\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n if ( !( record->getType() == ( COMM + LOG + SEND ) ) )\n return false;\n\n commID = record->getCommIndex();\n\n ostr << CommRecord << ':';\n writeCommon( ostr, whichTrace, record );\n ostr << whichTrace.getPhysicalSend( commID ) << ':';\n if ( whichTrace.existResourceInfo() )\n ostr << whichTrace.getReceiverCPU( commID ) << ':';\n else\n ostr << '0' << ':';\n whichTrace.getThreadLocation( whichTrace.getReceiverThread( commID ),\n recvAppl, recvTask, recvThread );\n ostr << recvAppl + 1 << ':' << recvTask + 1 << ':' << recvThread + 1 << ':';\n ostr << whichTrace.getLogicalReceive( commID ) << ':';\n ostr << whichTrace.getPhysicalReceive( commID ) << ':';\n\n ostr << whichTrace.getCommSize( commID ) << ':';\n ostr << whichTrace.getCommTag( commID );\n\n line += ostr.str();\n return true;\n}\n\n\nbool TraceBodyIO_v1::writeGlobalComm( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n return true;\n}\n\n\nvoid TraceBodyIO_v1::writeCommon( ostringstream& line,\n const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n\n if ( whichTrace.existResourceInfo() )\n line << record->getCPU() << ':';\n else\n line << '0' << ':';\n\n whichTrace.getThreadLocation( record->getThread(), appl, task, thread );\n line << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';\n line << record->getTime() << ':';\n}\n\n\nbool TraceBodyIO_v1::sameMultiEvent( const MemoryTrace::iterator *record ) const\n{\n return ( multiEventCommonInfo.cpu == record->getCPU() &&\n multiEventCommonInfo.thread == record->getThread() &&\n multiEventCommonInfo.time == record->getTime() );\n}\n<commit_msg>Small improvements to prv_atoll_v<commit_after>\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * Paraver Main Computing Library *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <type_traits>\n\n#include \"tracebodyio_v1.h\"\n\nusing namespace std;\n\nstring TraceBodyIO_v1::multiEventLine;\nTraceBodyIO_v1::TMultiEventCommonInfo TraceBodyIO_v1::multiEventCommonInfo =\n { nullptr, (TThreadOrder)0, (TCPUOrder)0, (TRecordTime)0 };\n\nstring TraceBodyIO_v1::line;\nostringstream TraceBodyIO_v1::ostr;\n\n\/\/ Optimization on conversion string to numbers, but with no error control\n\/\/#define USE_ATOLL\n\/\/ Even more optimization using custom function instead of atoll with error checking\n#define USE_PRV_ATOLL\nconstexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end )\n{\n return true;\n}\n\ntemplate <typename T, typename... Targs>\nbool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end, T& result, Targs&... Fargs )\n{\n result = 0;\n bool negative = false;\n\n if( it == end )\n return false;\n\n if( *it == '-' )\n {\n if( is_unsigned<T>::value )\n return false;\n negative = true;\n ++it;\n }\n\n while( *it >= '0' && *it <= '9' )\n {\n result = ( result * 10 ) + ( *it - '0' );\n ++it;\n }\n\n result = negative ? -result : result;\n\n if( it == end )\n return sizeof...( Targs ) == 0;\n\n return prv_atoll_v( ++it, end, Fargs... );\n}\n\nTraceBodyIO_v1::TraceBodyIO_v1( Trace* trace )\n: whichTrace( trace )\n{}\n\nbool TraceBodyIO_v1::ordered() const\n{\n return false;\n}\n\nvoid TraceBodyIO_v1::read( TraceStream *file, MemoryBlocks& records,\n unordered_set<TState>& states, unordered_set<TEventType>& events,\n MetadataManager& traceInfo ) const\n{\n file->getline( line );\n\n if ( line.size() == 0 )\n return;\n\n switch ( line[0] )\n {\n case CommentRecord:\n readTraceInfo( line, traceInfo );\n break;\n\n case StateRecord:\n readState( line, records, states );\n break;\n\n case EventRecord:\n readEvent( line, records, events );\n break;\n\n case CommRecord:\n readComm( line, records );\n break;\n\n case GlobalCommRecord:\n \/\/readGlobalComm( line, records );\n break;\n\n default:\n cerr << \"TraceBodyIO_v1::read()\" << endl;\n cerr << \"Unkwnown record type.\" << endl;\n break;\n };\n}\n\nvoid TraceBodyIO_v1::bufferWrite( fstream& whichStream, bool writeReady, bool lineClear ) const\n{\n if ( writeReady )\n {\n whichStream << line << '\\n';\n if ( lineClear )\n line.clear();\n }\n}\n\n\nvoid TraceBodyIO_v1::write( fstream& whichStream,\n const KTrace& whichTrace,\n MemoryTrace::iterator *record,\n PRV_INT32 numIter ) const\n{\n bool writeReady = false;\n TRecordType type = record->getType();\n line.clear();\n\n if ( type == EMPTYREC )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n }\n else\n {\n if ( type & STATE )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n writeReady = writeState( whichTrace, record );\n }\n else if ( type & EVENT )\n {\n if ( !sameMultiEvent( record ) )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n\n multiEventCommonInfo.myStream = &whichStream;\n multiEventCommonInfo.cpu = record->getCPU();\n multiEventCommonInfo.thread = record->getThread();\n multiEventCommonInfo.time = record->getTime();\n\n multiEventLine.clear();\n }\n\n appendEvent( record );\n }\n else if ( type & COMM )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n\n writeReady = writeComm( whichTrace, record );\n }\n else if ( type & GLOBCOMM )\n {\n writeReady = writePendingMultiEvent( whichTrace );\n bufferWrite( whichStream, writeReady );\n\n writeReady = writeGlobalComm( whichTrace, record );\n }\n else if ( type & RSEND || type & RRECV )\n writeReady = false;\n else\n {\n writeReady = false;\n cerr << \"TraceBodyIO_v1::write()\" << endl;\n cerr << \"Unkwnown record type in memory.\" << endl;\n }\n\n bufferWrite( whichStream, writeReady, false );\n }\n}\n\n\nvoid TraceBodyIO_v1::writeCommInfo( fstream& whichStream,\n const KTrace& whichTrace,\n PRV_INT32 numIter ) const\n{}\n\n\/**********************\n Read line functions\n***********************\/\ninline void TraceBodyIO_v1::readTraceInfo( const std::string& line, MetadataManager& traceInfo ) const\n{\n traceInfo.NewMetadata( line );\n \/\/ dummy set also to false if it is a comment\n}\n\ninline void TraceBodyIO_v1::readState( const string& line, MemoryBlocks& records,\n unordered_set<TState>& states ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime time;\n TRecordTime endtime;\n TState state;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )\n {\n cerr << \"Error reading state record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n if( !prv_atoll_v( it, line.cend(), endtime, state ) )\n {\n cerr << \"Error reading state record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newRecord();\n records.setType( STATE + BEGIN );\n records.setTime( time );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setState( state );\n records.setStateEndTime( endtime );\n\n if ( endtime != -1 )\n {\n records.newRecord();\n records.setType( STATE + END );\n records.setTime( endtime );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setState( state );\n records.setStateEndTime( time );\n }\n\n states.insert( state );\n}\n\n\ninline void TraceBodyIO_v1::readEvent( const string& line, MemoryBlocks& records,\n unordered_set<TEventType>& events ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime time;\n TEventType eventtype;\n TEventValue eventvalue;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )\n {\n cerr << \"Error reading event record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n while ( it != line.end() )\n {\n if( !prv_atoll_v( it, line.cend(), eventtype, eventvalue ) )\n {\n cerr << \"Error reading event record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newRecord();\n records.setType( EVENT );\n records.setTime( time );\n records.setCPU( CPU );\n records.setThread( appl - 1, task - 1, thread - 1 );\n records.setEventType( eventtype );\n records.setEventValue( eventvalue );\n\n events.insert( eventtype );\n }\n}\n\n\ninline void TraceBodyIO_v1::readComm( const string& line, MemoryBlocks& records ) const\n{\n TCPUOrder CPU;\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n TRecordTime logSend;\n TRecordTime phySend;\n TRecordTime logReceive;\n TRecordTime phyReceive;\n TCPUOrder remoteCPU;\n TApplOrder remoteAppl;\n TTaskOrder remoteTask;\n TThreadOrder remoteThread;\n TCommSize commSize;\n TCommTag commTag;\n\n auto it = line.begin() + 2;\n\n \/\/ Read the common info\n if ( !readCommon( it, line.cend(), CPU, appl, task, thread, logSend ) )\n {\n cerr << \"Error reading communication record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n if( !prv_atoll_v( it, line.cend(), phySend, remoteCPU, remoteAppl, remoteTask, remoteThread, logReceive, phyReceive, commSize, commTag ) )\n {\n cerr << \"Error reading communication record.\" << endl;\n cerr << line << endl;\n return;\n }\n\n records.newComm();\n records.setSenderCPU( CPU );\n records.setSenderThread( appl - 1, task - 1, thread - 1 );\n records.setReceiverCPU( remoteCPU );\n records.setReceiverThread( remoteAppl - 1, remoteTask - 1, remoteThread - 1 );\n records.setLogicalSend( logSend );\n records.setPhysicalSend( phySend );\n records.setLogicalReceive( logReceive );\n records.setPhysicalReceive( phyReceive );\n records.setCommSize( commSize );\n records.setCommTag( commTag );\n}\n\n\ninline void TraceBodyIO_v1::readGlobalComm( const string& line, MemoryBlocks& records ) const\n{}\n\n\ninline bool TraceBodyIO_v1::readCommon( string::const_iterator& it,\n const string::const_iterator& end,\n TCPUOrder& CPU,\n TApplOrder& appl,\n TTaskOrder& task,\n TThreadOrder& thread,\n TRecordTime& time ) const\n{\n bool result;\n\n result = prv_atoll_v( it, end, CPU, appl, task, thread, time );\n\n if ( !resourceModel->isValidGlobalCPU( CPU ) )\n return false;\n\n if ( !processModel->isValidThread( appl - 1, task - 1, thread - 1 ) )\n return false;\n\n return true;\n}\n\n\n\/**************************\n Write records functions\n***************************\/\nbool TraceBodyIO_v1::writeState( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n if ( record->getType() & END )\n return false;\n\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n ostr << StateRecord << ':';\n writeCommon( ostr, whichTrace, record );\n ostr << record->getStateEndTime() << ':' << record->getState();\n\n line += ostr.str();\n return true;\n}\n\n\nbool TraceBodyIO_v1::writePendingMultiEvent( const KTrace& whichTrace ) const\n{\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n\n bool writeLine = !multiEventLine.empty();\n\n if ( writeLine )\n {\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n ostr << EventRecord << ':';\n ostr << multiEventCommonInfo.cpu << ':';\n\n whichTrace.getThreadLocation( multiEventCommonInfo.thread, appl, task, thread );\n ostr << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';\n\n ostr << multiEventCommonInfo.time << ':';\n ostr << multiEventLine;\n\n line += ostr.str();\n\n bufferWrite( *multiEventCommonInfo.myStream, true );\n\n multiEventCommonInfo.myStream = nullptr;\n multiEventCommonInfo.cpu = 0;\n multiEventCommonInfo.thread = 0;\n multiEventCommonInfo.time = 0;\n\n multiEventLine.clear();\n }\n\n return false;\n}\n\n\nvoid TraceBodyIO_v1::appendEvent( const MemoryTrace::iterator *record ) const\n{\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n if ( !multiEventLine.empty() )\n ostr << ':';\n\n ostr << record->getEventType() << ':' << record->getEventValueAsIs();\n\n multiEventLine += ostr.str();\n}\n\n\nbool TraceBodyIO_v1::writeComm( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n TCommID commID;\n TApplOrder recvAppl;\n TTaskOrder recvTask;\n TThreadOrder recvThread;\n\n ostr.clear();\n ostr.str( \"\" );\n ostr << fixed;\n ostr << dec;\n ostr.precision( 0 );\n\n if ( !( record->getType() == ( COMM + LOG + SEND ) ) )\n return false;\n\n commID = record->getCommIndex();\n\n ostr << CommRecord << ':';\n writeCommon( ostr, whichTrace, record );\n ostr << whichTrace.getPhysicalSend( commID ) << ':';\n if ( whichTrace.existResourceInfo() )\n ostr << whichTrace.getReceiverCPU( commID ) << ':';\n else\n ostr << '0' << ':';\n whichTrace.getThreadLocation( whichTrace.getReceiverThread( commID ),\n recvAppl, recvTask, recvThread );\n ostr << recvAppl + 1 << ':' << recvTask + 1 << ':' << recvThread + 1 << ':';\n ostr << whichTrace.getLogicalReceive( commID ) << ':';\n ostr << whichTrace.getPhysicalReceive( commID ) << ':';\n\n ostr << whichTrace.getCommSize( commID ) << ':';\n ostr << whichTrace.getCommTag( commID );\n\n line += ostr.str();\n return true;\n}\n\n\nbool TraceBodyIO_v1::writeGlobalComm( const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n return true;\n}\n\n\nvoid TraceBodyIO_v1::writeCommon( ostringstream& line,\n const KTrace& whichTrace,\n const MemoryTrace::iterator *record ) const\n{\n TApplOrder appl;\n TTaskOrder task;\n TThreadOrder thread;\n\n if ( whichTrace.existResourceInfo() )\n line << record->getCPU() << ':';\n else\n line << '0' << ':';\n\n whichTrace.getThreadLocation( record->getThread(), appl, task, thread );\n line << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';\n line << record->getTime() << ':';\n}\n\n\nbool TraceBodyIO_v1::sameMultiEvent( const MemoryTrace::iterator *record ) const\n{\n return ( multiEventCommonInfo.cpu == record->getCPU() &&\n multiEventCommonInfo.thread == record->getThread() &&\n multiEventCommonInfo.time == record->getTime() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#include <almath\/types\/alpose2d.h>\n#include <cmath>\n#include <stdexcept>\n#include <iostream>\n\nnamespace AL {\n namespace Math {\n\n Pose2D::Pose2D():x(0.0f), y(0.0f), theta(0.0f) {}\n\n Pose2D::Pose2D(float pInit):x(pInit), y(pInit), theta(pInit) {}\n\n Pose2D::Pose2D(\n float pX,\n float pY,\n float pTheta):\n x(pX),\n y(pY),\n theta(pTheta) {}\n\n Pose2D::Pose2D (const std::vector<float>& pFloats)\n {\n if (pFloats.size() == 3)\n {\n x = pFloats[0];\n y = pFloats[1];\n theta = pFloats[2];\n }\n else\n {\n std::cerr << \"ALMath: WARNING: \"\n << \"Pose2D constructor call with a wrong size of vector. \"\n << \"Size expected: 3. Size given: \" << pFloats.size() << \". \"\n << \"Pose2D is set to default value.\" << std::endl;\n\n x = 0.0f;\n y = 0.0f;\n theta = 0.0f;\n }\n }\n\n Pose2D Pose2D::operator+ (const Pose2D& pPos2) const\n {\n Pose2D res;\n res.x = x + pPos2.x;\n res.y = y + pPos2.y;\n res.theta = theta + pPos2.theta;\n return res;\n }\n\n Pose2D Pose2D::operator- (const Pose2D& pPos2) const\n {\n Pose2D res;\n res.x = x - pPos2.x;\n res.y = y - pPos2.y;\n res.theta = theta - pPos2.theta;\n return res;\n }\n\n Pose2D Pose2D::operator+ () const\n {\n Pose2D res;\n res.x = x;\n res.y = y;\n res.theta = theta;\n return res;\n }\n\n Pose2D Pose2D::operator- () const\n {\n Pose2D res;\n res.x = -x;\n res.y = -y;\n res.theta = -theta;\n return res;\n }\n\n Pose2D Pose2D::operator* (const Pose2D& pPos2) const\n {\n Pose2D pOut;\n pOut.x = x + cosf(theta) * pPos2.x - sinf(theta) * pPos2.y;\n pOut.y = y + sinf(theta) * pPos2.x + cosf(theta) * pPos2.y;\n pOut.theta = theta + pPos2.theta;\n\n return pOut;\n }\n\n Pose2D& Pose2D::operator*= (const Pose2D& pPos2)\n {\n if (this == &pPos2)\n {\n return *this *= Pose2D(pPos2);\n }\n\n x += cosf(theta) * pPos2.x - sinf(theta) * pPos2.y;\n y += sinf(theta) * pPos2.x + cosf(theta) * pPos2.y;\n theta += pPos2.theta;\n\n return *this;\n }\n\n Pose2D& Pose2D::operator+= (const Pose2D& pPos2)\n {\n x += pPos2.x;\n y += pPos2.y;\n theta += pPos2.theta;\n return *this;\n }\n\n Pose2D& Pose2D::operator-= (const Pose2D& pPos2)\n {\n x -= pPos2.x;\n y -= pPos2.y;\n theta -= pPos2.theta;\n return *this;\n }\n\n bool Pose2D::operator==(const Pose2D& pPos2) const\n {\n return (x == pPos2.x &&\n y == pPos2.y &&\n theta == pPos2.theta);\n }\n\n bool Pose2D::operator!=(const Pose2D& pPos2) const\n {\n return ! (*this==pPos2);\n }\n\n float Pose2D::distanceSquared(const Pose2D& pPos) const\n {\n return Math::distanceSquared(*this, pPos);\n }\n\n float Pose2D::distance(const Pose2D& pPos2) const\n {\n return Math::distance(*this, pPos2);\n }\n\n Pose2D Pose2D::operator* (float pVal) const\n {\n Pose2D res;\n res.x = x * pVal;\n res.y = y * pVal;\n res.theta = theta * pVal;\n return res;\n }\n\n Pose2D Pose2D::operator\/ (float pVal) const\n {\n if (pVal == 0.0f)\n {\n throw std::runtime_error(\n \"ALPose2D: operator\/ Division by zeros.\");\n }\n return *this * (1.0f\/pVal);\n }\n\n Pose2D& Pose2D::operator*= (const float pVal)\n {\n x *= pVal;\n y *= pVal;\n theta *= pVal;\n return *this;\n }\n\n Pose2D& Pose2D::operator\/= (float pVal)\n {\n if (pVal == 0.0f)\n {\n throw std::runtime_error(\n \"ALPose2D: operator\/= Division by zeros.\");\n }\n *this *= (1.0f\/pVal);\n return *this;\n }\n\n Pose2D Pose2D::diff(const Pose2D& pPos2) const\n {\n return Math::pose2dDiff(*this, pPos2);\n }\n\n std::vector<float> Pose2D::toVector() const\n {\n std::vector<float> returnVector(3, 0.0f);\n\n returnVector[0] = x;\n returnVector[1] = y;\n returnVector[2] = theta;\n\n return returnVector;\n }\n\n float distanceSquared(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n return (pPos1.x-pPos2.x)*(pPos1.x-pPos2.x)+(pPos1.y-pPos2.y)*(pPos1.y-pPos2.y);\n }\n\n float distance(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n return sqrtf(distanceSquared(pPos1, pPos2));\n }\n\n\n bool Pose2D::isNear(\n const Pose2D& pPos2,\n const float& pEpsilon) const\n {\n return (fabsf(x - pPos2.x) <= pEpsilon &&\n fabsf(y - pPos2.y) <= pEpsilon &&\n fabsf(theta - pPos2.theta) <= pEpsilon);\n }\n\n Pose2D Pose2D::inverse() const\n {\n return Math::pose2DInverse(*this);\n }\n\n void pose2DInverse(\n const Pose2D& pIn,\n Pose2D& pOut)\n {\n pOut.theta = -pIn.theta;\n\n float cos = cosf(pOut.theta);\n float sin = sinf(pOut.theta);\n\n pOut.x = -( pIn.x*cos - pIn.y*sin);\n pOut.y = -( pIn.y*cos + pIn.x*sin);\n }\n\n void pose2dInvertInPlace(Pose2D& pPos)\n {\n pPos.theta = -pPos.theta;\n\n float cos = cosf(pPos.theta);\n float sin = sinf(pPos.theta);\n float x = pPos.x;\n\n pPos.x = -(x*cos - pPos.y*sin);\n pPos.y = -(pPos.y*cos + x*sin);\n }\n\n Pose2D pose2dDiff(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n Pose2D result = pPos1;\n\n pose2dInvertInPlace(result);\n result *= pPos2;\n return result;\n }\n\n Pose2D pose2DInverse(const Pose2D& pIn)\n {\n Pose2D pOut;\n pose2DInverse(pIn, pOut);\n return pOut;\n }\n\n Pose2D pinv(const Pose2D& pPos)\n {\n Pose2D result = pPos;\n pose2dInvertInPlace(result);\n return result;\n }\n\n\n } \/\/ end namespace math\n} \/\/ end namespace AL\n<commit_msg>POSE2D: Factoring pose2DInverse function.<commit_after>\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#include <almath\/types\/alpose2d.h>\n#include <cmath>\n#include <stdexcept>\n#include <iostream>\n\nnamespace AL {\n namespace Math {\n\n Pose2D::Pose2D():x(0.0f), y(0.0f), theta(0.0f) {}\n\n Pose2D::Pose2D(float pInit):x(pInit), y(pInit), theta(pInit) {}\n\n Pose2D::Pose2D(\n float pX,\n float pY,\n float pTheta):\n x(pX),\n y(pY),\n theta(pTheta) {}\n\n Pose2D::Pose2D (const std::vector<float>& pFloats)\n {\n if (pFloats.size() == 3)\n {\n x = pFloats[0];\n y = pFloats[1];\n theta = pFloats[2];\n }\n else\n {\n std::cerr << \"ALMath: WARNING: \"\n << \"Pose2D constructor call with a wrong size of vector. \"\n << \"Size expected: 3. Size given: \" << pFloats.size() << \". \"\n << \"Pose2D is set to default value.\" << std::endl;\n\n x = 0.0f;\n y = 0.0f;\n theta = 0.0f;\n }\n }\n\n Pose2D Pose2D::operator+ (const Pose2D& pPos2) const\n {\n Pose2D res;\n res.x = x + pPos2.x;\n res.y = y + pPos2.y;\n res.theta = theta + pPos2.theta;\n return res;\n }\n\n Pose2D Pose2D::operator- (const Pose2D& pPos2) const\n {\n Pose2D res;\n res.x = x - pPos2.x;\n res.y = y - pPos2.y;\n res.theta = theta - pPos2.theta;\n return res;\n }\n\n Pose2D Pose2D::operator+ () const\n {\n Pose2D res;\n res.x = x;\n res.y = y;\n res.theta = theta;\n return res;\n }\n\n Pose2D Pose2D::operator- () const\n {\n Pose2D res;\n res.x = -x;\n res.y = -y;\n res.theta = -theta;\n return res;\n }\n\n Pose2D Pose2D::operator* (const Pose2D& pPos2) const\n {\n Pose2D pOut;\n pOut.x = x + cosf(theta) * pPos2.x - sinf(theta) * pPos2.y;\n pOut.y = y + sinf(theta) * pPos2.x + cosf(theta) * pPos2.y;\n pOut.theta = theta + pPos2.theta;\n\n return pOut;\n }\n\n Pose2D& Pose2D::operator*= (const Pose2D& pPos2)\n {\n if (this == &pPos2)\n {\n return *this *= Pose2D(pPos2);\n }\n\n x += cosf(theta) * pPos2.x - sinf(theta) * pPos2.y;\n y += sinf(theta) * pPos2.x + cosf(theta) * pPos2.y;\n theta += pPos2.theta;\n\n return *this;\n }\n\n Pose2D& Pose2D::operator+= (const Pose2D& pPos2)\n {\n x += pPos2.x;\n y += pPos2.y;\n theta += pPos2.theta;\n return *this;\n }\n\n Pose2D& Pose2D::operator-= (const Pose2D& pPos2)\n {\n x -= pPos2.x;\n y -= pPos2.y;\n theta -= pPos2.theta;\n return *this;\n }\n\n bool Pose2D::operator==(const Pose2D& pPos2) const\n {\n return (x == pPos2.x &&\n y == pPos2.y &&\n theta == pPos2.theta);\n }\n\n bool Pose2D::operator!=(const Pose2D& pPos2) const\n {\n return ! (*this==pPos2);\n }\n\n float Pose2D::distanceSquared(const Pose2D& pPos) const\n {\n return Math::distanceSquared(*this, pPos);\n }\n\n float Pose2D::distance(const Pose2D& pPos2) const\n {\n return Math::distance(*this, pPos2);\n }\n\n Pose2D Pose2D::operator* (float pVal) const\n {\n Pose2D res;\n res.x = x * pVal;\n res.y = y * pVal;\n res.theta = theta * pVal;\n return res;\n }\n\n Pose2D Pose2D::operator\/ (float pVal) const\n {\n if (pVal == 0.0f)\n {\n throw std::runtime_error(\n \"ALPose2D: operator\/ Division by zeros.\");\n }\n return *this * (1.0f\/pVal);\n }\n\n Pose2D& Pose2D::operator*= (const float pVal)\n {\n x *= pVal;\n y *= pVal;\n theta *= pVal;\n return *this;\n }\n\n Pose2D& Pose2D::operator\/= (float pVal)\n {\n if (pVal == 0.0f)\n {\n throw std::runtime_error(\n \"ALPose2D: operator\/= Division by zeros.\");\n }\n *this *= (1.0f\/pVal);\n return *this;\n }\n\n Pose2D Pose2D::diff(const Pose2D& pPos2) const\n {\n return Math::pose2dDiff(*this, pPos2);\n }\n\n std::vector<float> Pose2D::toVector() const\n {\n std::vector<float> returnVector(3, 0.0f);\n\n returnVector[0] = x;\n returnVector[1] = y;\n returnVector[2] = theta;\n\n return returnVector;\n }\n\n float distanceSquared(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n return (pPos1.x-pPos2.x)*(pPos1.x-pPos2.x)+(pPos1.y-pPos2.y)*(pPos1.y-pPos2.y);\n }\n\n float distance(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n return sqrtf(distanceSquared(pPos1, pPos2));\n }\n\n\n bool Pose2D::isNear(\n const Pose2D& pPos2,\n const float& pEpsilon) const\n {\n return (fabsf(x - pPos2.x) <= pEpsilon &&\n fabsf(y - pPos2.y) <= pEpsilon &&\n fabsf(theta - pPos2.theta) <= pEpsilon);\n }\n\n Pose2D Pose2D::inverse() const\n {\n return Math::pose2DInverse(*this);\n }\n\n void pose2DInverse(\n const Pose2D& pIn,\n Pose2D& pOut)\n {\n pOut = pIn;\n pose2dInvertInPlace(pOut);\n }\n\n void pose2dInvertInPlace(Pose2D& pPos)\n {\n pPos.theta = -pPos.theta;\n\n float cos = cosf(pPos.theta);\n float sin = sinf(pPos.theta);\n float x = pPos.x;\n\n pPos.x = -(x*cos - pPos.y*sin);\n pPos.y = -(pPos.y*cos + x*sin);\n }\n\n Pose2D pose2dDiff(\n const Pose2D& pPos1,\n const Pose2D& pPos2)\n {\n Pose2D result = pPos1;\n\n pose2dInvertInPlace(result);\n result *= pPos2;\n return result;\n }\n\n Pose2D pose2DInverse(const Pose2D& pIn)\n {\n Pose2D pOut;\n pose2DInverse(pIn, pOut);\n return pOut;\n }\n\n Pose2D pinv(const Pose2D& pPos)\n {\n Pose2D result = pPos;\n pose2dInvertInPlace(result);\n return result;\n }\n\n\n } \/\/ end namespace math\n} \/\/ end namespace AL\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 1998-2001, The University of Queensland\n * Copyright (C) 2001, Sun Microsystems, Inc\n * Copyright (C) 2002, Trent Waddington\n *\n * See the file \"LICENSE.TERMS\" for information on usage and\n * redistribution of this file, and for a DISCLAIMER OF ALL\n * WARRANTIES.\n *\n *\/\n\n\/*==============================================================================\n * FILE: njmcDecoder.cc\n * OVERVIEW: This file contains the machine independent\n * decoding functionality.\n *\n * $Revision$\n *============================================================================*\/ \n\/*\n * 27 Apr 02 - Mike: Mods for boomerang\n *\/\n\n#include <assert.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1200\n#pragma warning(disable:4786)\n#endif\n\n#include <stdarg.h> \/\/ For varargs\n#include \"rtl.h\"\n#include \"decoder.h\"\n#include \"exp.h\"\n#include \"register.h\"\n#include \"cfg.h\"\n#include \"proc.h\"\n#include \"prog.h\"\n#include \"BinaryFile.h\"\n#include \"boomerang.h\"\n\/\/ For some reason, MSVC 5.00 complains about use of undefined types a lot\n#if defined(_MSC_VER) && _MSC_VER <= 1100\n#include \"signature.h\"\t\t\/\/ For MSVC 5.00\n#endif\n\n\/**********************************\n * NJMCDecoder methods.\n **********************************\/ \n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::NJMCDecoder\n * OVERVIEW: \n * PARAMETERS: None\n * RETURNS: N\/A\n *============================================================================*\/\nNJMCDecoder::NJMCDecoder()\n{}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::instantiate\n * OVERVIEW: Given an instruction name and a variable list of SemStr's\n * representing the actual operands of the instruction, use the\n * RTL template dictionary to return the instantiated RTL\n * representing the semantics of the instruction.\n * PARAMETERS: name - instruction name\n * ... - Semantic String ptrs representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nstd::list<Statement*>* NJMCDecoder::instantiate(ADDRESS pc, const char* name,\n ...) {\n \/\/ Get the signature of the instruction and extract its parts\n std::pair<std::string,unsigned> sig = RTLDict.getSignature(name);\n std::string opcode = sig.first;\n unsigned numOperands = sig.second;\n\n \/\/ Put the operands into an vector\n std::vector<Exp*> actuals(numOperands);\n va_list args;\n va_start(args,name);\n for (unsigned i = 0; i < numOperands; i++)\n actuals[i] = va_arg(args,Exp*);\n va_end(args);\n\n if (Boomerang::get()->debugDecoder) {\n \/\/ Display a disassembly of this instruction if requested\n std::cout << std::hex << pc << std::dec << \": \" << name << \" \";\n for (std::vector<Exp*>::iterator itd = actuals.begin();\n itd != actuals.end(); itd++) {\n (*itd)->print(std::cout);\n if (itd != actuals.end()-1)\n std::cout << \", \";\n }\n std::cout << std::endl;\n }\n\n std::list<Statement*>* instance = RTLDict.instantiateRTL(opcode,actuals);\n\n \/\/ Delete the memory used for the actuals\n for (std::vector<Exp*>::iterator it = actuals.begin();\n it != actuals.end(); it++)\n delete *it;\n\n return instance;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::instantiateNamedParam\n * OVERVIEW: Similarly to the above, given a parameter name\n * and a list of Exp*'s representing sub-parameters,\n * return a fully substituted Exp for the whole expression\n * NOTE: Caller must delete result\n * PARAMETERS: name - parameter name\n * ... - Exp* representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nExp* NJMCDecoder::instantiateNamedParam(char* name, ...) {\n if (RTLDict.ParamSet.find(name) == RTLDict.ParamSet.end()) {\n std::cerr << \"No entry for named parameter '\" << name << \"'\\n\";\n return 0;\n }\n assert(RTLDict.DetParamMap.find(name) != RTLDict.DetParamMap.end());\n ParamEntry &ent = RTLDict.DetParamMap[name];\n if (ent.kind != PARAM_ASGN && ent.kind != PARAM_LAMBDA ) {\n std::cerr << \"Attempt to instantiate expressionless parameter '\" << name\n << \"'\\n\";\n return 0;\n }\n \/\/ Start with the RHS\n assert(ent.asgn->getKind() == STMT_ASSIGN);\n Exp* result = ent.asgn->getRight()->clone();\n\n va_list args;\n va_start(args,name);\n for( std::list<std::string>::iterator it = ent.params.begin();\n it != ent.params.end(); it++ ) {\n Exp* formal = new Unary(opParam, new Const((char*)it->c_str()));\n Exp* actual = va_arg(args, Exp*);\n bool change;\n result = result->searchReplaceAll(formal, actual, change);\n delete formal;\n }\n return result;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::substituteCallArgs\n * OVERVIEW: In the event that it's necessary to synthesize the call of\n * a named parameter generated with instantiateNamedParam(),\n * this substituteCallArgs() will substitute the arguments that\n * follow into the expression.\n * NOTE: Should only be used after instantiateNamedParam(name, ..);\n * NOTE: exp (the pointer) could be changed\n * PARAMETERS: name - parameter name\n * exp - expression to instantiate into\n * ... - Exp* representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nvoid NJMCDecoder::substituteCallArgs(char *name, Exp*& exp, ...)\n{\n if (RTLDict.ParamSet.find(name) == RTLDict.ParamSet.end()) {\n std::cerr << \"No entry for named parameter '\" << name << \"'\\n\";\n return;\n }\n ParamEntry &ent = RTLDict.DetParamMap[name];\n \/*if (ent.kind != PARAM_ASGN && ent.kind != PARAM_LAMBDA) {\n std::cerr << \"Attempt to instantiate expressionless parameter '\" << name << \"'\\n\";\n return;\n }*\/\n \n va_list args;\n va_start(args, exp);\n for (std::list<std::string>::iterator it = ent.funcParams.begin();\n it != ent.funcParams.end(); it++) {\n Exp* formal = new Unary(opParam, new Const((char*)it->c_str()));\n Exp* actual = va_arg(args, Exp*);\n bool change;\n exp = exp->searchReplaceAll(formal, actual, change);\n delete formal;\n }\n}\n\n\/*==============================================================================\n * FUNCTION: DecodeResult::reset\n * OVERVIEW: Resets the fields of a DecodeResult to their default values.\n * PARAMETERS: <none>\n * RETURNS: <nothing>\n *============================================================================*\/\nvoid DecodeResult::reset()\n{\n numBytes = 0;\n type = NCT;\n valid = true;\n rtl = NULL;\n forceOutEdge = 0; \n}\n\n\/*==============================================================================\n * These are functions used to decode instruction operands into\n * Exp*s.\n *============================================================================*\/\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::dis_Reg\n * OVERVIEW: Converts a numbered register to a suitable expression.\n * PARAMETERS: reg - the register number, e.g. 0 for eax\n * RETURNS: the Exp* for the register NUMBER (e.g. \"int 36\" for %f4)\n *============================================================================*\/\nExp* NJMCDecoder::dis_Reg(int regNum)\n{\n Exp* expr = Location::regOf(regNum);\n return expr;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::dis_Num\n * OVERVIEW: Converts a number to a Exp* expression.\n * PARAMETERS: num - a number\n * RETURNS: the Exp* representation of the given number\n *============================================================================*\/\nExp* NJMCDecoder::dis_Num(unsigned num)\n{\n Exp* expr = new Const((int)num);\n return expr;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::unconditionalJump\n * OVERVIEW: Process an unconditional jump instruction\n * Also check if the destination is a label\n * PARAMETERS: <none>\n * RETURNS: the reference to the RTLInstDict object\n *============================================================================*\/\nvoid NJMCDecoder::unconditionalJump(const char* name, int size,\n ADDRESS relocd, \/*UserProc* proc,*\/ int delta, ADDRESS pc, std::list<Statement*>* stmts,\n DecodeResult& result) {\n result.rtl = new RTL(pc, stmts);\n result.numBytes = size;\n GotoStatement* jump = new GotoStatement();\n jump->setDest(relocd-delta);\n result.rtl->appendStmt(jump);\n SHOW_ASM(name<<\" \"<<relocd)\n}\n\n<commit_msg>A few improvements to debugging (-dd)<commit_after>\/*\n * Copyright (C) 1998-2001, The University of Queensland\n * Copyright (C) 2001, Sun Microsystems, Inc\n * Copyright (C) 2002, Trent Waddington\n *\n * See the file \"LICENSE.TERMS\" for information on usage and\n * redistribution of this file, and for a DISCLAIMER OF ALL\n * WARRANTIES.\n *\n *\/\n\n\/*==============================================================================\n * FILE: njmcDecoder.cc\n * OVERVIEW: This file contains the machine independent\n * decoding functionality.\n *\n * $Revision$\n *============================================================================*\/ \n\/*\n * 27 Apr 02 - Mike: Mods for boomerang\n *\/\n\n#include <assert.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1200\n#pragma warning(disable:4786)\n#endif\n\n#include <stdarg.h> \/\/ For varargs\n#include \"rtl.h\"\n#include \"decoder.h\"\n#include \"exp.h\"\n#include \"register.h\"\n#include \"cfg.h\"\n#include \"proc.h\"\n#include \"prog.h\"\n#include \"BinaryFile.h\"\n#include \"boomerang.h\"\n\/\/ For some reason, MSVC 5.00 complains about use of undefined types a lot\n#if defined(_MSC_VER) && _MSC_VER <= 1100\n#include \"signature.h\"\t\t\/\/ For MSVC 5.00\n#endif\n\n\/**********************************\n * NJMCDecoder methods.\n **********************************\/ \n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::NJMCDecoder\n * OVERVIEW: \n * PARAMETERS: None\n * RETURNS: N\/A\n *============================================================================*\/\nNJMCDecoder::NJMCDecoder()\n{}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::instantiate\n * OVERVIEW: Given an instruction name and a variable list of SemStr's\n * representing the actual operands of the instruction, use the\n * RTL template dictionary to return the instantiated RTL\n * representing the semantics of the instruction.\n * PARAMETERS: name - instruction name\n * ... - Semantic String ptrs representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nstd::list<Statement*>* NJMCDecoder::instantiate(ADDRESS pc, const char* name,\n ...) {\n \/\/ Get the signature of the instruction and extract its parts\n std::pair<std::string,unsigned> sig = RTLDict.getSignature(name);\n std::string opcode = sig.first;\n unsigned numOperands = sig.second;\n\n \/\/ Put the operands into a vector\n std::vector<Exp*> actuals(numOperands);\n va_list args;\n va_start(args,name);\n for (unsigned i = 0; i < numOperands; i++)\n actuals[i] = va_arg(args,Exp*);\n va_end(args);\n\n if (DEBUG_DECODER) {\n \/\/ Display a disassembly of this instruction if requested\n std::cout << std::hex << pc << std::dec << \": \" << name << \" \";\n for (std::vector<Exp*>::iterator itd = actuals.begin();\n itd != actuals.end(); itd++) {\n (*itd)->print(std::cout);\n if (itd != actuals.end()-1)\n std::cout << \", \";\n }\n std::cout << std::endl;\n }\n\n std::list<Statement*>* instance = RTLDict.instantiateRTL(opcode, actuals);\n\n return instance;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::instantiateNamedParam\n * OVERVIEW: Similarly to the above, given a parameter name\n * and a list of Exp*'s representing sub-parameters,\n * return a fully substituted Exp for the whole expression\n * NOTE: Caller must delete result\n * PARAMETERS: name - parameter name\n * ... - Exp* representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nExp* NJMCDecoder::instantiateNamedParam(char* name, ...) {\n if (RTLDict.ParamSet.find(name) == RTLDict.ParamSet.end()) {\n std::cerr << \"No entry for named parameter '\" << name << \"'\\n\";\n return 0;\n }\n assert(RTLDict.DetParamMap.find(name) != RTLDict.DetParamMap.end());\n ParamEntry &ent = RTLDict.DetParamMap[name];\n if (ent.kind != PARAM_ASGN && ent.kind != PARAM_LAMBDA ) {\n std::cerr << \"Attempt to instantiate expressionless parameter '\" << name\n << \"'\\n\";\n return 0;\n }\n \/\/ Start with the RHS\n assert(ent.asgn->getKind() == STMT_ASSIGN);\n Exp* result = ent.asgn->getRight()->clone();\n\n va_list args;\n va_start(args,name);\n for( std::list<std::string>::iterator it = ent.params.begin();\n it != ent.params.end(); it++ ) {\n Exp* formal = new Unary(opParam, new Const((char*)it->c_str()));\n Exp* actual = va_arg(args, Exp*);\n bool change;\n result = result->searchReplaceAll(formal, actual, change);\n delete formal;\n }\n return result;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::substituteCallArgs\n * OVERVIEW: In the event that it's necessary to synthesize the call of\n * a named parameter generated with instantiateNamedParam(),\n * this substituteCallArgs() will substitute the arguments that\n * follow into the expression.\n * NOTE: Should only be used after instantiateNamedParam(name, ..);\n * NOTE: exp (the pointer) could be changed\n * PARAMETERS: name - parameter name\n * exp - expression to instantiate into\n * ... - Exp* representing actual operands\n * RETURNS: an instantiated list of Exps\n *============================================================================*\/\nvoid NJMCDecoder::substituteCallArgs(char *name, Exp*& exp, ...)\n{\n if (RTLDict.ParamSet.find(name) == RTLDict.ParamSet.end()) {\n std::cerr << \"No entry for named parameter '\" << name << \"'\\n\";\n return;\n }\n ParamEntry &ent = RTLDict.DetParamMap[name];\n \/*if (ent.kind != PARAM_ASGN && ent.kind != PARAM_LAMBDA) {\n std::cerr << \"Attempt to instantiate expressionless parameter '\" << name << \"'\\n\";\n return;\n }*\/\n \n va_list args;\n va_start(args, exp);\n for (std::list<std::string>::iterator it = ent.funcParams.begin();\n it != ent.funcParams.end(); it++) {\n Exp* formal = new Unary(opParam, new Const((char*)it->c_str()));\n Exp* actual = va_arg(args, Exp*);\n bool change;\n exp = exp->searchReplaceAll(formal, actual, change);\n delete formal;\n }\n}\n\n\/*==============================================================================\n * FUNCTION: DecodeResult::reset\n * OVERVIEW: Resets the fields of a DecodeResult to their default values.\n * PARAMETERS: <none>\n * RETURNS: <nothing>\n *============================================================================*\/\nvoid DecodeResult::reset()\n{\n numBytes = 0;\n type = NCT;\n valid = true;\n rtl = NULL;\n forceOutEdge = 0; \n}\n\n\/*==============================================================================\n * These are functions used to decode instruction operands into\n * Exp*s.\n *============================================================================*\/\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::dis_Reg\n * OVERVIEW: Converts a numbered register to a suitable expression.\n * PARAMETERS: reg - the register number, e.g. 0 for eax\n * RETURNS: the Exp* for the register NUMBER (e.g. \"int 36\" for %f4)\n *============================================================================*\/\nExp* NJMCDecoder::dis_Reg(int regNum)\n{\n Exp* expr = Location::regOf(regNum);\n return expr;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::dis_Num\n * OVERVIEW: Converts a number to a Exp* expression.\n * PARAMETERS: num - a number\n * RETURNS: the Exp* representation of the given number\n *============================================================================*\/\nExp* NJMCDecoder::dis_Num(unsigned num)\n{\n Exp* expr = new Const((int)num);\n return expr;\n}\n\n\/*==============================================================================\n * FUNCTION: NJMCDecoder::unconditionalJump\n * OVERVIEW: Process an unconditional jump instruction\n * Also check if the destination is a label\n * PARAMETERS: <none>\n * RETURNS: the reference to the RTLInstDict object\n *============================================================================*\/\nvoid NJMCDecoder::unconditionalJump(const char* name, int size,\n ADDRESS relocd, \/*UserProc* proc,*\/ int delta, ADDRESS pc, std::list<Statement*>* stmts,\n DecodeResult& result) {\n result.rtl = new RTL(pc, stmts);\n result.numBytes = size;\n GotoStatement* jump = new GotoStatement();\n jump->setDest(relocd-delta);\n result.rtl->appendStmt(jump);\n SHOW_ASM(name<<\" \"<<relocd)\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"net.hpp\"\n#include <gio\/gio.h>\n#include <iostream>\n\nstruct network_provider_backend\n{\n \/* setup backend AND initially populate the connection info, then set updated = true *\/\n virtual bool create(connection_info *store) = 0;\n \/* called by the thread starter, see network_widget source code *\/\n virtual void thread_loop() = 0;\n\n virtual ~network_provider_backend() = 0;\n};\n\nnetwork_provider_backend::~network_provider_backend()\n{\n}\n\nstatic void\non_wifi_properties_changed (GDBusProxy *proxy,\n GVariant *changed_properties,\n const gchar* const *invalidated_properties,\n gpointer user_data)\n{\n connection_info *info = (connection_info*) user_data;\n if (g_variant_n_children(changed_properties) > 0)\n {\n GVariantIter *iter;\n g_variant_get(changed_properties, \"a{sv}\", &iter);\n\n const gchar *key;\n GVariant *value;\n while (g_variant_iter_loop(iter, \"{&sv}\", &key, &value))\n {\n if (std::string(key) == \"Strength\")\n {\n info->mutex.lock();\n info->strength = g_variant_get_byte(value);\n info->updated = true;\n info->mutex.unlock();\n }\n }\n\n g_variant_iter_free(iter);\n }\n}\n\nusing updater_callback = std::function<void()>;\n\nstatic void\non_nm_properties_changed (GDBusProxy *proxy,\n GVariant *changed_properties,\n const gchar* const *invalidated_properties,\n gpointer user_data)\n{\n updater_callback *callback = (updater_callback*) user_data;\n if (g_variant_n_children(changed_properties) > 0)\n {\n GVariantIter *iter;\n g_variant_get(changed_properties, \"a{sv}\", &iter);\n\n const gchar *key;\n GVariant *value;\n while (g_variant_iter_loop(iter, \"{&sv}\", &key, &value))\n {\n if (std::string(key) == \"PrimaryConnection\")\n (*callback)();\n }\n\n g_variant_iter_free(iter);\n }\n}\n\nstruct network_manager_provider : public network_provider_backend\n{\n connection_info *info;\n GDBusConnection *dbus_connection;\n GDBusProxy *nm_proxy;\n\n#define NM_DBUS_NAME \"org.freedesktop.NetworkManager\"\n\n bool setup_dbus_connection()\n {\n GError *error = NULL;\n dbus_connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);\n\n if (!dbus_connection)\n {\n std::cerr << \"Failed to connect to system bus: \"\n << error->message << std::endl;\n return false;\n }\n\n nm_proxy = g_dbus_proxy_new_sync(dbus_connection,\n G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n \"\/org\/freedesktop\/NetworkManager\",\n \"org.freedesktop.NetworkManager\",\n NULL, &error);\n\n return true;\n }\n\n GDBusProxy* current_specific_proxy = NULL;\n\n void load_wifi_data(const gchar *ap)\n {\n GError *error = NULL;\n current_specific_proxy =\n g_dbus_proxy_new_sync(dbus_connection, G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n ap,\n \"org.freedesktop.NetworkManager.AccessPoint\",\n NULL, &error);\n\n if (!current_specific_proxy)\n {\n std::cerr << \"Failed to obtain AP info: \" << error->message << std::endl;\n return;\n }\n\n GVariant *gv = g_dbus_proxy_get_cached_property(current_specific_proxy, \"Strength\");\n\n info->mutex.lock();\n info->strength = g_variant_get_byte(gv);\n info->updated = true;\n info->mutex.unlock();\n\n g_variant_unref(gv);\n\n g_signal_connect(current_specific_proxy, \"g-properties-changed\",\n G_CALLBACK(on_wifi_properties_changed), info);\n }\n\n void load_bluetooth_data(const gchar *dev)\n {\n info->mutex.lock();\n \/* TODO: implement *\/\n }\n\n void load_ethernet_data(const gchar *dev)\n {\n info->mutex.lock();\n\n info->icon = \"none\";\n info->strength = 100;\n info->name = \"Ethernet\";\n\n info->updated = true;\n info->mutex.unlock();\n }\n\n void active_connection_updated()\n {\n GVariant *gv = g_dbus_proxy_get_cached_property(\n nm_proxy, \"PrimaryConnection\");\n\n gsize n;\n const gchar *active_connection = g_variant_get_string(gv, &n);\n\n \/* no active connection *\/\n if (std::string(active_connection) == \"\/\")\n {\n info->mutex.lock();\n info->name = \"No network\";\n info->updated = true;\n info->strength = 0;\n info->mutex.unlock();\n\n return;\n }\n\n GError *error = NULL;\n GDBusProxy *aconn_proxy =\n g_dbus_proxy_new_sync(dbus_connection,\n G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n active_connection,\n \"org.freedesktop.NetworkManager.Connection.Active\",\n NULL, &error);\n\n if (!aconn_proxy)\n {\n std::cerr << \"Failed to get active connection: \" << error->message << std::endl;\n return;\n }\n\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"Type\");\n std::string type = g_variant_get_string(gv, &n);\n\n g_variant_unref(gv);\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"Id\");\n\n info->mutex.lock();\n info->name = g_variant_get_string(gv, &n);\n info->mutex.unlock();\n\n g_variant_unref(gv);\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"SpecificObject\");\n const gchar *object = g_variant_get_string(gv, &n);\n\n if (current_specific_proxy)\n g_object_unref(current_specific_proxy);\n\n if (type == \"bluetooth\")\n {\n load_bluetooth_data(object);\n } else if (type.find(\"ethernet\") != std::string::npos)\n {\n load_ethernet_data(object);\n } else if (type.find(\"wireless\") != std::string::npos)\n {\n load_wifi_data(object);\n }\n\n g_variant_unref(gv);\n g_object_unref(aconn_proxy);\n }\n\n void load_initial_connection_info()\n {\n \/* don't have to lock mutex, as we are still in the main thread *\/\n info->updated = true;\n info->icon = info->name = \"none\";\n info->strength = 0;\n\n active_connection_updated();\n }\n\n bool create(connection_info *info)\n {\n this->info = info;\n\n if (!setup_dbus_connection())\n return false;\n\n load_initial_connection_info();\n return true;\n }\n\n void thread_loop()\n {\n updater_callback callback =\n std::bind(std::mem_fn(&network_manager_provider::active_connection_updated), this);\n\n g_signal_connect(nm_proxy, \"g-properties-changed\",\n G_CALLBACK(on_nm_properties_changed), &callback);\n\n GMainLoop *loop = g_main_loop_new(NULL, false);\n g_main_loop_run(loop);\n\n g_main_loop_unref(loop);\n g_object_unref(nm_proxy);\n }\n\n ~network_manager_provider()\n {\n }\n};\n\nvoid network_widget::create()\n{\n backend = new network_manager_provider();\n if (!backend->create(&connection))\n {\n delete backend;\n backend = nullptr;\n return;\n }\n\n updater_thread = std::thread([=] () { backend->thread_loop(); });\n\n cairo_set_font_size(cr, font_size);\n cairo_set_font_face(cr, cairo_font_face);\n}\n\nbool network_widget::update()\n{\n bool result;\n connection.mutex.lock();\n result = connection.updated;\n connection.mutex.unlock();\n return result;\n}\n\nvoid network_widget::repaint()\n{\n constexpr wayfire_color color_good = {0, 1, 0, 1},\n color_avg = {1, 1, 0.3, 1},\n color_bad = {1, 0, 0, 1};\n\n cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);\n render_rounded_rectangle(cr, center_x - max_w \/ 2, 0, max_w, panel_h, 7,\n widget::background_color.r, widget::background_color.g,\n widget::background_color.b, widget::background_color.a);\n\n cairo_set_operator(cr, CAIRO_OPERATOR_ATOP);\n\n std::string text;\n wayfire_color color;\n\n connection.mutex.lock();\n\n text = connection.name;\n if (connection.strength >= 50)\n color = color_good;\n else if (connection.strength > 30)\n color = color_avg;\n else\n color = color_bad;\n connection.updated = false;\n\n connection.mutex.unlock();\n\n\n cairo_text_extents_t te;\n cairo_text_extents(cr, text.c_str(), &te);\n\n double x = 0, y = font_size;\n cairo_set_source_rgba(cr, color.r, color.g, color.b, color.a);\n\n x = center_x + max_w \/ 2 - te.width;\n\n cairo_move_to(cr, x, y);\n cairo_show_text(cr, text.c_str());\n}\n<commit_msg>shell: interpolate network color according to signal strength<commit_after>#include \"net.hpp\"\n#include <gio\/gio.h>\n#include <iostream>\n\nstruct network_provider_backend\n{\n \/* setup backend AND initially populate the connection info, then set updated = true *\/\n virtual bool create(connection_info *store) = 0;\n \/* called by the thread starter, see network_widget source code *\/\n virtual void thread_loop() = 0;\n\n virtual ~network_provider_backend() = 0;\n};\n\nnetwork_provider_backend::~network_provider_backend()\n{\n}\n\nstatic void\non_wifi_properties_changed (GDBusProxy *proxy,\n GVariant *changed_properties,\n const gchar* const *invalidated_properties,\n gpointer user_data)\n{\n connection_info *info = (connection_info*) user_data;\n if (g_variant_n_children(changed_properties) > 0)\n {\n GVariantIter *iter;\n g_variant_get(changed_properties, \"a{sv}\", &iter);\n\n const gchar *key;\n GVariant *value;\n while (g_variant_iter_loop(iter, \"{&sv}\", &key, &value))\n {\n if (std::string(key) == \"Strength\")\n {\n info->mutex.lock();\n info->strength = g_variant_get_byte(value);\n info->updated = true;\n info->mutex.unlock();\n }\n }\n\n g_variant_iter_free(iter);\n }\n}\n\nusing updater_callback = std::function<void()>;\n\nstatic void\non_nm_properties_changed (GDBusProxy *proxy,\n GVariant *changed_properties,\n const gchar* const *invalidated_properties,\n gpointer user_data)\n{\n updater_callback *callback = (updater_callback*) user_data;\n if (g_variant_n_children(changed_properties) > 0)\n {\n GVariantIter *iter;\n g_variant_get(changed_properties, \"a{sv}\", &iter);\n\n const gchar *key;\n GVariant *value;\n while (g_variant_iter_loop(iter, \"{&sv}\", &key, &value))\n {\n if (std::string(key) == \"PrimaryConnection\")\n (*callback)();\n }\n\n g_variant_iter_free(iter);\n }\n}\n\nstruct network_manager_provider : public network_provider_backend\n{\n connection_info *info;\n GDBusConnection *dbus_connection;\n GDBusProxy *nm_proxy;\n\n#define NM_DBUS_NAME \"org.freedesktop.NetworkManager\"\n\n bool setup_dbus_connection()\n {\n GError *error = NULL;\n dbus_connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);\n\n if (!dbus_connection)\n {\n std::cerr << \"Failed to connect to system bus: \"\n << error->message << std::endl;\n return false;\n }\n\n nm_proxy = g_dbus_proxy_new_sync(dbus_connection,\n G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n \"\/org\/freedesktop\/NetworkManager\",\n \"org.freedesktop.NetworkManager\",\n NULL, &error);\n\n return true;\n }\n\n GDBusProxy* current_specific_proxy = NULL;\n\n void load_wifi_data(const gchar *ap)\n {\n GError *error = NULL;\n current_specific_proxy =\n g_dbus_proxy_new_sync(dbus_connection, G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n ap,\n \"org.freedesktop.NetworkManager.AccessPoint\",\n NULL, &error);\n\n if (!current_specific_proxy)\n {\n std::cerr << \"Failed to obtain AP info: \" << error->message << std::endl;\n return;\n }\n\n GVariant *gv = g_dbus_proxy_get_cached_property(current_specific_proxy, \"Strength\");\n\n info->mutex.lock();\n info->strength = g_variant_get_byte(gv);\n info->updated = true;\n info->mutex.unlock();\n\n g_variant_unref(gv);\n\n g_signal_connect(current_specific_proxy, \"g-properties-changed\",\n G_CALLBACK(on_wifi_properties_changed), info);\n }\n\n void load_bluetooth_data(const gchar *dev)\n {\n info->mutex.lock();\n \/* TODO: implement *\/\n }\n\n void load_ethernet_data(const gchar *dev)\n {\n info->mutex.lock();\n\n info->icon = \"none\";\n info->strength = 100;\n info->name = \"Ethernet\";\n\n info->updated = true;\n info->mutex.unlock();\n }\n\n void active_connection_updated()\n {\n GVariant *gv = g_dbus_proxy_get_cached_property(\n nm_proxy, \"PrimaryConnection\");\n\n gsize n;\n const gchar *active_connection = g_variant_get_string(gv, &n);\n\n \/* no active connection *\/\n if (std::string(active_connection) == \"\/\")\n {\n info->mutex.lock();\n info->name = \"No network\";\n info->updated = true;\n info->strength = 0;\n info->mutex.unlock();\n\n return;\n }\n\n GError *error = NULL;\n GDBusProxy *aconn_proxy =\n g_dbus_proxy_new_sync(dbus_connection,\n G_DBUS_PROXY_FLAGS_NONE, NULL,\n NM_DBUS_NAME,\n active_connection,\n \"org.freedesktop.NetworkManager.Connection.Active\",\n NULL, &error);\n\n if (!aconn_proxy)\n {\n std::cerr << \"Failed to get active connection: \" << error->message << std::endl;\n return;\n }\n\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"Type\");\n std::string type = g_variant_get_string(gv, &n);\n\n g_variant_unref(gv);\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"Id\");\n\n info->mutex.lock();\n info->name = g_variant_get_string(gv, &n);\n info->mutex.unlock();\n\n g_variant_unref(gv);\n gv = g_dbus_proxy_get_cached_property(aconn_proxy, \"SpecificObject\");\n const gchar *object = g_variant_get_string(gv, &n);\n\n if (current_specific_proxy)\n g_object_unref(current_specific_proxy);\n\n if (type == \"bluetooth\")\n {\n load_bluetooth_data(object);\n } else if (type.find(\"ethernet\") != std::string::npos)\n {\n load_ethernet_data(object);\n } else if (type.find(\"wireless\") != std::string::npos)\n {\n load_wifi_data(object);\n }\n\n g_variant_unref(gv);\n g_object_unref(aconn_proxy);\n }\n\n void load_initial_connection_info()\n {\n \/* don't have to lock mutex, as we are still in the main thread *\/\n info->updated = true;\n info->icon = info->name = \"none\";\n info->strength = 0;\n\n active_connection_updated();\n }\n\n bool create(connection_info *info)\n {\n this->info = info;\n\n if (!setup_dbus_connection())\n return false;\n\n load_initial_connection_info();\n return true;\n }\n\n void thread_loop()\n {\n updater_callback callback =\n std::bind(std::mem_fn(&network_manager_provider::active_connection_updated), this);\n\n g_signal_connect(nm_proxy, \"g-properties-changed\",\n G_CALLBACK(on_nm_properties_changed), &callback);\n\n GMainLoop *loop = g_main_loop_new(NULL, false);\n g_main_loop_run(loop);\n\n g_main_loop_unref(loop);\n g_object_unref(nm_proxy);\n }\n\n ~network_manager_provider()\n {\n }\n};\n\nvoid network_widget::create()\n{\n backend = new network_manager_provider();\n if (!backend->create(&connection))\n {\n delete backend;\n backend = nullptr;\n return;\n }\n\n updater_thread = std::thread([=] () { backend->thread_loop(); });\n\n cairo_set_font_size(cr, font_size);\n cairo_set_font_face(cr, cairo_font_face);\n}\n\nbool network_widget::update()\n{\n bool result;\n connection.mutex.lock();\n result = connection.updated;\n connection.mutex.unlock();\n return result;\n}\n\ninline wayfire_color interpolate_color(wayfire_color start, wayfire_color end, float a)\n{\n wayfire_color r;\n r.r = start.r * a + end.r * (1. - a);\n r.g = start.g * a + end.g * (1. - a);\n r.b = start.b * a + end.b * (1. - a);\n r.a = start.a * a + end.a * (1. - a);\n\n return r;\n}\n\nvoid network_widget::repaint()\n{\n constexpr wayfire_color color_good = {0, 1, 0, 1},\n color_avg = {1, 1, 0.3, 1},\n color_bad = {1, 0, 0, 1};\n\n cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);\n render_rounded_rectangle(cr, center_x - max_w \/ 2, 0, max_w, panel_h, 7,\n widget::background_color.r, widget::background_color.g,\n widget::background_color.b, widget::background_color.a);\n\n cairo_set_operator(cr, CAIRO_OPERATOR_ATOP);\n\n std::string text;\n wayfire_color color;\n\n connection.mutex.lock();\n\n#define STRENGTH_GOOD 40\n#define STRENGTH_AVG 25\n\n text = connection.name;\n if (connection.strength >= STRENGTH_GOOD)\n color = interpolate_color(color_good, color_avg,\n (connection.strength - STRENGTH_GOOD) * 1.0 \/ (100 - STRENGTH_GOOD));\n else if (connection.strength >= STRENGTH_AVG)\n color = interpolate_color(color_avg, color_bad,\n (connection.strength - STRENGTH_AVG) * 1.0 \/ (STRENGTH_GOOD - STRENGTH_AVG));\n else\n color = color_bad;\n\n connection.updated = false;\n connection.mutex.unlock();\n\n\n cairo_text_extents_t te;\n cairo_text_extents(cr, text.c_str(), &te);\n\n double x = 0, y = font_size;\n cairo_set_source_rgba(cr, color.r, color.g, color.b, color.a);\n\n x = center_x + max_w \/ 2 - te.width;\n\n cairo_move_to(cr, x, y);\n cairo_show_text(cr, text.c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"udp_connection.h\"\n#include \"global_include.h\"\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <errno.h>\n#include <cassert>\n\nnamespace dronelink {\n\nUdpConnection::UdpConnection(DroneLinkImpl *parent,\n int local_port_number) :\n Connection(parent),\n _local_port_number(local_port_number),\n _should_exit(false)\n{\n if (_local_port_number == 0) {\n _local_port_number = DEFAULT_UDP_LOCAL_PORT;\n }\n}\n\nUdpConnection::~UdpConnection()\n{\n \/\/ If no one explicitly called stop before, we should at least do it.\n stop();\n}\n\nbool UdpConnection::is_ok() const\n{\n return true;\n}\n\nDroneLink::ConnectionResult UdpConnection::start()\n{\n if (!start_mavlink_receiver()) {\n return DroneLink::ConnectionResult::CONNECTIONS_EXHAUSTED;\n }\n\n DroneLink::ConnectionResult ret = setup_port();\n if (ret != DroneLink::ConnectionResult::SUCCESS) {\n return ret;\n }\n\n start_recv_thread();\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nDroneLink::ConnectionResult UdpConnection::setup_port()\n{\n _socket_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\n if (_socket_fd < 0) {\n Debug() << \"socket error\" << strerror(errno);\n return DroneLink::ConnectionResult::SOCKET_ERROR;\n }\n\n struct sockaddr_in addr;\n memset((char *)&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(_local_port_number);\n addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\n if (bind(_socket_fd, (sockaddr *)&addr, sizeof(addr)) != 0) {\n Debug() << \"bind error: \" << strerror(errno);\n return DroneLink::ConnectionResult::BIND_ERROR;\n }\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nvoid UdpConnection::start_recv_thread()\n{\n _recv_thread = new std::thread(receive, this);\n}\n\nDroneLink::ConnectionResult UdpConnection::stop()\n{\n _should_exit = true;\n\n \/\/ This interrupts a recv\/recvfrom call.\n shutdown(_socket_fd, SHUT_RDWR);\n\n if (_recv_thread) {\n _recv_thread->join();\n delete _recv_thread;\n _recv_thread = nullptr;\n }\n\n close(_socket_fd);\n\n \/\/ We need to stop this after stopping the receive thread, otherwise\n \/\/ it can happen that we interfere with the parsing of a message.\n stop_mavlink_receiver();\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nbool UdpConnection::send_message(const mavlink_message_t &message)\n{\n if (_remote_ip.empty()) {\n Debug() << \"Remote IP unknown\";\n return false;\n }\n\n if (_remote_port_number == 0) {\n Debug() << \"Remote port unknown\";\n return false;\n }\n\n struct sockaddr_in dest_addr;\n memset((char *)&dest_addr, 0, sizeof(dest_addr));\n dest_addr.sin_family = AF_INET;\n inet_pton(AF_INET, _remote_ip.c_str(), &dest_addr.sin_addr.s_addr);\n\n dest_addr.sin_port = htons(_remote_port_number);\n\n uint8_t buffer[MAVLINK_MAX_PACKET_LEN];\n uint16_t buffer_len = mavlink_msg_to_send_buffer(buffer, &message);\n\n \/\/ TODO: remove this assert again\n assert(buffer_len <= MAVLINK_MAX_PACKET_LEN);\n\n int send_len = sendto(_socket_fd, buffer, buffer_len, 0,\n (const sockaddr *)&dest_addr, sizeof(dest_addr));\n\n if (send_len != buffer_len) {\n Debug() << \"sendto failure: \" << strerror(errno);\n return false;\n }\n\n return true;\n}\n\nvoid UdpConnection::receive(UdpConnection *parent)\n{\n \/\/ Enough for MTU 1500 bytes.\n char buffer[2048];\n\n while (!parent->_should_exit) {\n\n struct sockaddr_in src_addr = {};\n socklen_t src_addr_len = sizeof(src_addr);\n int recv_len = recvfrom(parent->_socket_fd, buffer, sizeof(buffer), 0,\n (struct sockaddr *)&src_addr, &src_addr_len);\n\n if (recv_len == 0) {\n \/\/ This can happen when shutdown is called on the socket,\n \/\/ therefore we check _should_exit again.\n continue;\n }\n\n if (recv_len < 0) {\n Debug() << \"recvfrom error: \" << strerror(errno);\n continue;\n }\n\n int new_remote_port_number = ntohs(src_addr.sin_port);\n std::string new_remote_ip(inet_ntoa(src_addr.sin_addr));\n\n \/\/ TODO make calls to remote threadsafe.\n\n if (parent->_remote_ip.empty()) {\n\n if (parent->_remote_port_number == 0 ||\n parent->_remote_port_number == new_remote_port_number) {\n \/\/ Set IP if we don't know it yet.\n parent->_remote_ip = new_remote_ip;\n parent->_remote_port_number = new_remote_port_number;\n\n Debug() << \"Partner IP: \" << parent->_remote_ip\n << \":\" << parent->_remote_port_number;\n\n } else {\n\n Debug() << \"Ignoring message from remote port \" << new_remote_port_number\n << \" instead of \" << parent->_remote_port_number;\n continue;\n }\n\n } else if (parent->_remote_ip.compare(new_remote_ip) != 0) {\n Debug() << \"Ignoring message from IP: \" << new_remote_ip;\n continue;\n\n } else {\n if (parent->_remote_port_number != new_remote_port_number) {\n Debug() << \"Ignoring message from remote port \" << new_remote_port_number\n << \" instead of \" << parent->_remote_port_number;\n continue;\n }\n }\n\n parent->_mavlink_receiver->set_new_datagram(buffer, recv_len);\n\n \/\/ Parse all mavlink messages in one datagram. Once exhausted, we'll exit while.\n while (parent->_mavlink_receiver->parse_message()) {\n parent->receive_message(parent->_mavlink_receiver->get_last_message());\n }\n }\n}\n\n\n} \/\/ namespace dronelink\n<commit_msg>udp_connection: another cleanup fix<commit_after>#include \"udp_connection.h\"\n#include \"global_include.h\"\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <errno.h>\n#include <cassert>\n\nnamespace dronelink {\n\nUdpConnection::UdpConnection(DroneLinkImpl *parent,\n int local_port_number) :\n Connection(parent),\n _local_port_number(local_port_number),\n _should_exit(false)\n{\n if (_local_port_number == 0) {\n _local_port_number = DEFAULT_UDP_LOCAL_PORT;\n }\n}\n\nUdpConnection::~UdpConnection()\n{\n \/\/ If no one explicitly called stop before, we should at least do it.\n stop();\n}\n\nbool UdpConnection::is_ok() const\n{\n return true;\n}\n\nDroneLink::ConnectionResult UdpConnection::start()\n{\n if (!start_mavlink_receiver()) {\n return DroneLink::ConnectionResult::CONNECTIONS_EXHAUSTED;\n }\n\n DroneLink::ConnectionResult ret = setup_port();\n if (ret != DroneLink::ConnectionResult::SUCCESS) {\n return ret;\n }\n\n start_recv_thread();\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nDroneLink::ConnectionResult UdpConnection::setup_port()\n{\n _socket_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\n if (_socket_fd < 0) {\n Debug() << \"socket error\" << strerror(errno);\n return DroneLink::ConnectionResult::SOCKET_ERROR;\n }\n\n struct sockaddr_in addr;\n memset((char *)&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(_local_port_number);\n addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\n if (bind(_socket_fd, (sockaddr *)&addr, sizeof(addr)) != 0) {\n Debug() << \"bind error: \" << strerror(errno);\n return DroneLink::ConnectionResult::BIND_ERROR;\n }\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nvoid UdpConnection::start_recv_thread()\n{\n _recv_thread = new std::thread(receive, this);\n}\n\nDroneLink::ConnectionResult UdpConnection::stop()\n{\n _should_exit = true;\n\n \/\/ This should interrupt a recv\/recvfrom call.\n shutdown(_socket_fd, SHUT_RDWR);\n\n \/\/ But on Mac, closing is also needed to stop blocking recv\/recvfrom.\n close(_socket_fd);\n\n if (_recv_thread) {\n _recv_thread->join();\n delete _recv_thread;\n _recv_thread = nullptr;\n }\n\n \/\/ We need to stop this after stopping the receive thread, otherwise\n \/\/ it can happen that we interfere with the parsing of a message.\n stop_mavlink_receiver();\n\n return DroneLink::ConnectionResult::SUCCESS;\n}\n\nbool UdpConnection::send_message(const mavlink_message_t &message)\n{\n if (_remote_ip.empty()) {\n Debug() << \"Remote IP unknown\";\n return false;\n }\n\n if (_remote_port_number == 0) {\n Debug() << \"Remote port unknown\";\n return false;\n }\n\n struct sockaddr_in dest_addr;\n memset((char *)&dest_addr, 0, sizeof(dest_addr));\n dest_addr.sin_family = AF_INET;\n inet_pton(AF_INET, _remote_ip.c_str(), &dest_addr.sin_addr.s_addr);\n\n dest_addr.sin_port = htons(_remote_port_number);\n\n uint8_t buffer[MAVLINK_MAX_PACKET_LEN];\n uint16_t buffer_len = mavlink_msg_to_send_buffer(buffer, &message);\n\n \/\/ TODO: remove this assert again\n assert(buffer_len <= MAVLINK_MAX_PACKET_LEN);\n\n int send_len = sendto(_socket_fd, buffer, buffer_len, 0,\n (const sockaddr *)&dest_addr, sizeof(dest_addr));\n\n if (send_len != buffer_len) {\n Debug() << \"sendto failure: \" << strerror(errno);\n return false;\n }\n\n return true;\n}\n\nvoid UdpConnection::receive(UdpConnection *parent)\n{\n \/\/ Enough for MTU 1500 bytes.\n char buffer[2048];\n\n while (!parent->_should_exit) {\n\n struct sockaddr_in src_addr = {};\n socklen_t src_addr_len = sizeof(src_addr);\n int recv_len = recvfrom(parent->_socket_fd, buffer, sizeof(buffer), 0,\n (struct sockaddr *)&src_addr, &src_addr_len);\n\n if (recv_len == 0) {\n \/\/ This can happen when shutdown is called on the socket,\n \/\/ therefore we check _should_exit again.\n continue;\n }\n\n if (recv_len < 0) {\n \/\/ This happens on desctruction when close(_socket_fd) is called,\n \/\/ therefore be quiet.\n \/\/Debug() << \"recvfrom error: \" << strerror(errno);\n continue;\n }\n\n int new_remote_port_number = ntohs(src_addr.sin_port);\n std::string new_remote_ip(inet_ntoa(src_addr.sin_addr));\n\n \/\/ TODO make calls to remote threadsafe.\n\n if (parent->_remote_ip.empty()) {\n\n if (parent->_remote_port_number == 0 ||\n parent->_remote_port_number == new_remote_port_number) {\n \/\/ Set IP if we don't know it yet.\n parent->_remote_ip = new_remote_ip;\n parent->_remote_port_number = new_remote_port_number;\n\n Debug() << \"Partner IP: \" << parent->_remote_ip\n << \":\" << parent->_remote_port_number;\n\n } else {\n\n Debug() << \"Ignoring message from remote port \" << new_remote_port_number\n << \" instead of \" << parent->_remote_port_number;\n continue;\n }\n\n } else if (parent->_remote_ip.compare(new_remote_ip) != 0) {\n Debug() << \"Ignoring message from IP: \" << new_remote_ip;\n continue;\n\n } else {\n if (parent->_remote_port_number != new_remote_port_number) {\n Debug() << \"Ignoring message from remote port \" << new_remote_port_number\n << \" instead of \" << parent->_remote_port_number;\n continue;\n }\n }\n\n parent->_mavlink_receiver->set_new_datagram(buffer, recv_len);\n\n \/\/ Parse all mavlink messages in one datagram. Once exhausted, we'll exit while.\n while (parent->_mavlink_receiver->parse_message()) {\n parent->receive_message(parent->_mavlink_receiver->get_last_message());\n }\n }\n}\n\n\n} \/\/ namespace dronelink\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CustomVar.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 24.02.10.\n * code under LGPL\n *\n *\/\n\n#include \"CustomVar.h\"\n#include \"CBytestream.h\"\n#include \"Debug.h\"\n#include \"game\/Attr.h\"\n#include \"util\/macros.h\"\n\nCustomVar* CustomVar::copy() const {\n\t\/\/ this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual\n\tassert( thisRef.classId != ClassId(-1) );\n\tconst ClassInfo* classInfo = getClassInfo(thisRef.classId);\n\tassert( classInfo != NULL );\n\tBaseObject* obj = classInfo->createInstance();\n\tassert( obj != NULL );\n\tCustomVar* v = dynamic_cast<BaseObject*>(obj);\n\tassert( v != NULL );\n\tv->copyFrom(*this);\n\treturn v;\n}\n\nbool CustomVar::operator==(const CustomVar& v) const {\n\tif( thisRef.classId != v.thisRef.classId ) return false;\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value != (*a)->get(&v)) return false;\n\t}\n\n\treturn true;\n}\n\nbool CustomVar::operator<(const CustomVar& v) const {\n\tif( thisRef.classId != v.thisRef.classId )\n\t\treturn thisRef.classId < v.thisRef.classId;\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value != (*a)->get(&v))\n\t\t\treturn value < (*a)->get(&v);\n\t}\n\n\treturn true;\n}\n\nvoid CustomVar::copyFrom(const CustomVar& v) {\n\tassert( thisRef.classId != ClassId(-1) );\n\tassert( v.thisRef.classId != ClassId(-1) );\n\tassert( thisRef.classId == v.thisRef.classId );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(&v);\n\t\tif(value == (*a)->get(this)) continue;\n\t\t(*a)->set(this, value);\n\t}\n}\n\nvoid CustomVar::fromScriptVar(const ScriptVar_t& v) {\n\tif(v.isCustomType()\n\t\t\t&& v.customVar()->thisRef.classId != ClassId(-1)\n\t\t\t&& v.customVar()->thisRef.classId == thisRef.classId\n\t)\n\t\tcopyFrom(*v.customVar());\n\telse\n\t\tfromString(v.toString());\n}\n\nResult CustomVar::ToBytestream( CBytestream* bs ) const {\n\tassert( thisRef.classId != ClassId(-1) );\n\tbs->writeInt16(thisRef.classId);\n\treturn toBytestream(bs);\n}\n\nResult CustomVar::toBytestream(CBytestream *bs) const {\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value == (*a)->defaultValue) continue;\n\t\tbs->writeInt16((*a)->objTypeId);\n\t\tbs->writeInt16((*a)->attrId);\n\t\tbs->writeVar(value);\n\t}\n\tbs->writeInt16(ClassId(-1));\n\n\treturn true;\n}\n\nResult CustomVar::fromBytestream(CBytestream *bs) {\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tResult r = true;\n\twhile(true) {\n\t\tAttribRef a;\n\t\ta.objTypeId = bs->readInt16();\n\t\tif(a.objTypeId == ClassId(-1)) break;\n\t\ta.attrId = bs->readInt16();\n\t\tconst AttrDesc* attrDesc = a.getAttrDesc();\n\t\tif(attrDesc == NULL) {\n\t\t\terrors << \"CustomVar::fromBytestream: unknown attrib \" << a.objTypeId << \":\" << a.attrId << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"unknown attrib\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst ClassInfo* classInfo = getClassInfo(a.objTypeId);\n\t\tif(classInfo == NULL) {\n\t\t\terrors << \"CustomVar::fromBytestream: unknown class for attrib \" << a.description() << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"unknown class\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!classInfo->isTypeOf(a.objTypeId)) {\n\t\t\terrors << \"CustomVar::fromBytestream: attrib \" << a.description() << \" does not belong to class \" << classInfo->name << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"invalid attrib for class\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tScriptVar_t var;\n\t\tbs->readVar(var);\n\t\tattrDesc->set(this, var);\n\t}\n\n\treturn r;\n}\n\nCustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {\n\tClassId classId = bs->readInt16();\n\tconst ClassInfo* classInfo = getClassInfo(classId);\n\tif(classInfo == NULL) {\n\t\terrors << \"CustomVar::FromBytestream: class ID \" << classId << \" unknown\" << endl;\n\t\treturn NULL;\n\t}\n\n\tif(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {\n\t\terrors << \"CustomVar::FromBytestream: class \" << classInfo->name << \" is not a CustomVar\" << endl;\n\t\treturn NULL;\n\t}\n\n\tif(classInfo->id == LuaID<CustomVar>::value) {\n\t\terrors << \"CustomVar::FromBytestream: class \" << classInfo->name << \" is abstract\" << endl;\n\t\treturn NULL;\n\t}\n\n\tCustomVar::Ref obj = (CustomVar*) classInfo->createInstance();\n\tif(!obj) {\n\t\terrors << \"CustomVar::FromBytestream: couldn't create instance of \" << classInfo->name << endl;\n\t\treturn NULL;\n\t}\n\n\tif(NegResult r = obj->fromBytestream(bs)) {\n\t\terrors << \"CustomVar::FromBytestream: error while reading \" << classInfo->name << \" instance: \" << r.res.humanErrorMsg << endl;\n\t\t\/\/ continue anyway, maybe we have some useful data\n\t}\n\n\treturn obj;\n}\n\n\/\/ We cannot use the REGISTER_CLASS macro because we cannot instantiate it.\nstatic bool registerClass_CustomVar() {\n\tClassInfo i;\n\ti.id = LuaID<CustomVar>::value;\n\ti.name = \"CustomVar\";\n\ti.memSize = sizeof(CustomVar);\n\tregisterClass(i);\n\treturn true;\n}\nstatic bool registerClass_CustomVar_init = registerClass_CustomVar();\n<commit_msg>small fix<commit_after>\/*\n * CustomVar.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 24.02.10.\n * code under LGPL\n *\n *\/\n\n#include \"CustomVar.h\"\n#include \"CBytestream.h\"\n#include \"Debug.h\"\n#include \"game\/Attr.h\"\n#include \"util\/macros.h\"\n\nCustomVar* CustomVar::copy() const {\n\t\/\/ this copy() relies on the ClassInfo. otherwise it cannot work. provide your own in this case, it's virtual\n\tassert( thisRef.classId != ClassId(-1) );\n\tconst ClassInfo* classInfo = getClassInfo(thisRef.classId);\n\tassert( classInfo != NULL );\n\tBaseObject* obj = classInfo->createInstance();\n\tassert( obj != NULL );\n\tCustomVar* v = dynamic_cast<CustomVar*>(obj);\n\tassert( v != NULL );\n\tv->copyFrom(*this);\n\treturn v;\n}\n\nbool CustomVar::operator==(const CustomVar& v) const {\n\tif( thisRef.classId != v.thisRef.classId ) return false;\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value != (*a)->get(&v)) return false;\n\t}\n\n\treturn true;\n}\n\nbool CustomVar::operator<(const CustomVar& v) const {\n\tif( thisRef.classId != v.thisRef.classId )\n\t\treturn thisRef.classId < v.thisRef.classId;\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value != (*a)->get(&v))\n\t\t\treturn value < (*a)->get(&v);\n\t}\n\n\treturn true;\n}\n\nvoid CustomVar::copyFrom(const CustomVar& v) {\n\tassert( thisRef.classId != ClassId(-1) );\n\tassert( v.thisRef.classId != ClassId(-1) );\n\tassert( thisRef.classId == v.thisRef.classId );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(&v);\n\t\tif(value == (*a)->get(this)) continue;\n\t\t(*a)->set(this, value);\n\t}\n}\n\nvoid CustomVar::fromScriptVar(const ScriptVar_t& v) {\n\tif(v.isCustomType()\n\t\t\t&& v.customVar()->thisRef.classId != ClassId(-1)\n\t\t\t&& v.customVar()->thisRef.classId == thisRef.classId\n\t)\n\t\tcopyFrom(*v.customVar());\n\telse\n\t\tfromString(v.toString());\n}\n\nResult CustomVar::ToBytestream( CBytestream* bs ) const {\n\tassert( thisRef.classId != ClassId(-1) );\n\tbs->writeInt16(thisRef.classId);\n\treturn toBytestream(bs);\n}\n\nResult CustomVar::toBytestream(CBytestream *bs) const {\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tstd::vector<const AttrDesc*> attribs = getAttrDescs(thisRef.classId, true);\n\tforeach(a, attribs) {\n\t\tScriptVar_t value = (*a)->get(this);\n\t\tif(value == (*a)->defaultValue) continue;\n\t\tbs->writeInt16((*a)->objTypeId);\n\t\tbs->writeInt16((*a)->attrId);\n\t\tbs->writeVar(value);\n\t}\n\tbs->writeInt16(ClassId(-1));\n\n\treturn true;\n}\n\nResult CustomVar::fromBytestream(CBytestream *bs) {\n\tassert( thisRef.classId != ClassId(-1) );\n\n\tResult r = true;\n\twhile(true) {\n\t\tAttribRef a;\n\t\ta.objTypeId = bs->readInt16();\n\t\tif(a.objTypeId == ClassId(-1)) break;\n\t\ta.attrId = bs->readInt16();\n\t\tconst AttrDesc* attrDesc = a.getAttrDesc();\n\t\tif(attrDesc == NULL) {\n\t\t\terrors << \"CustomVar::fromBytestream: unknown attrib \" << a.objTypeId << \":\" << a.attrId << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"unknown attrib\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst ClassInfo* classInfo = getClassInfo(a.objTypeId);\n\t\tif(classInfo == NULL) {\n\t\t\terrors << \"CustomVar::fromBytestream: unknown class for attrib \" << a.description() << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"unknown class\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!classInfo->isTypeOf(a.objTypeId)) {\n\t\t\terrors << \"CustomVar::fromBytestream: attrib \" << a.description() << \" does not belong to class \" << classInfo->name << \" for object \" << thisRef.description() << endl;\n\t\t\t\/\/ try to continue\n\t\t\tr = \"invalid attrib for class\";\n\t\t\tbs->SkipVar();\n\t\t\tcontinue;\n\t\t}\n\n\t\tScriptVar_t var;\n\t\tbs->readVar(var);\n\t\tattrDesc->set(this, var);\n\t}\n\n\treturn r;\n}\n\nCustomVar::Ref CustomVar::FromBytestream( CBytestream* bs ) {\n\tClassId classId = bs->readInt16();\n\tconst ClassInfo* classInfo = getClassInfo(classId);\n\tif(classInfo == NULL) {\n\t\terrors << \"CustomVar::FromBytestream: class ID \" << classId << \" unknown\" << endl;\n\t\treturn NULL;\n\t}\n\n\tif(!classInfo->isTypeOf(LuaID<CustomVar>::value)) {\n\t\terrors << \"CustomVar::FromBytestream: class \" << classInfo->name << \" is not a CustomVar\" << endl;\n\t\treturn NULL;\n\t}\n\n\tif(classInfo->id == LuaID<CustomVar>::value) {\n\t\terrors << \"CustomVar::FromBytestream: class \" << classInfo->name << \" is abstract\" << endl;\n\t\treturn NULL;\n\t}\n\n\tCustomVar::Ref obj = (CustomVar*) classInfo->createInstance();\n\tif(!obj) {\n\t\terrors << \"CustomVar::FromBytestream: couldn't create instance of \" << classInfo->name << endl;\n\t\treturn NULL;\n\t}\n\n\tif(NegResult r = obj->fromBytestream(bs)) {\n\t\terrors << \"CustomVar::FromBytestream: error while reading \" << classInfo->name << \" instance: \" << r.res.humanErrorMsg << endl;\n\t\t\/\/ continue anyway, maybe we have some useful data\n\t}\n\n\treturn obj;\n}\n\n\/\/ We cannot use the REGISTER_CLASS macro because we cannot instantiate it.\nstatic bool registerClass_CustomVar() {\n\tClassInfo i;\n\ti.id = LuaID<CustomVar>::value;\n\ti.name = \"CustomVar\";\n\ti.memSize = sizeof(CustomVar);\n\tregisterClass(i);\n\treturn true;\n}\nstatic bool registerClass_CustomVar_init = registerClass_CustomVar();\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file util.h\n *\n * \\brief Utilities for the IEGen project\n *\n * \\date Started: 9\/13\/2010, but has been completely rewritten\n * # $Revision:: 622 $: last committed revision\n * # $Date:: 2013-01-18 13:11:32 -0#$: date of last committed revision\n * # $Author:: cathie $: author of last committed revision\n *\n * \\authors\n *\n * Copyright (c) 2012, Colorado State University <br>\n * All rights reserved. <br>\n * See ..\/..\/COPYING for details. <br>\n *\/\n\n#include \"jsonHelper.h\"\n\n\/\/using jsoncons::json;\n\/\/using namespace iegenlib;\n\n\/\/ Reads a list of UFCs from a json structure and stores them in the environment \nvoid addUFCs(json &ufcs){\n\n for (size_t j = 0; j < ufcs[\"UFS\"].size(); ++j){\n\n bool bijective = false;\n if( ufcs[\"UFS\"][j][\"Bijective\"].as<string>() == string(\"true\") ){\n bijective = true;\n }\n iegenlib::MonotonicType monotonicity = iegenlib::Monotonic_NONE;\n if(ufcs[\"UFS\"][j][\"Monotonicity\"].as<string>() == \n string(\"Monotonic_Nondecreasing\")){\n monotonicity = iegenlib::Monotonic_Nondecreasing;\n } else if(ufcs[\"UFS\"][j][\"Monotonicity\"].as<string>() == \n string(\"Monotonic_Increasing\")){\n monotonicity = iegenlib::Monotonic_Increasing;\n }\n\n iegenlib::appendCurrEnv(ufcs[\"UFS\"][j][\"Name\"].as<string>(),\/\/ Name\n new Set(ufcs[\"UFS\"][j][\"Domain\"].as<string>()), \/\/ Domain \n new Set(ufcs[\"UFS\"][j][\"Range\"].as<string>()), \/\/ Range\n bijective, \/\/ Bijective?\n monotonicity \/\/ Monotonicity?\n );\n }\n}\n\n\n\/\/ Reads a list of universially quantified constraints from a json structure\n\/\/ and stores them in the environment\nvoid addUniQuantRules(json &uqCons){\n\n UniQuantRule *uqRule;\n for (size_t j = 0; j < uqCons.size(); ++j){\n\n \/\/ forall e1, e2, ... : p => q\n uqRule = new UniQuantRule(uqCons[j][\"Type\"].as<string>(), \n uqCons[j][\"UniQuantVar\"].as<string>(), \n uqCons[j][\"p\"].as<string>(), uqCons[j][\"q\"].as<string>());\n currentEnv.addUniQuantRule( uqRule );\n }\n}\n\n\/\/ Reads iterators that we should not project from a json sructure\nvoid notProjectIters(Relation* rel, std::set<int> ¶llelTvs, json &np){\n\n iegenlib::TupleDecl td = rel->getTupleDecl();\n for (size_t j = 0; j < np.size(); ++j){\n string tvS = np[j].as<string>();\n int tvN = -1;\n for (unsigned int c = 0 ; c < td.getSize() ; c++){\n if( tvS == td.elemToString(c) ){\n tvN = c;\n break;\n }\n }\n parallelTvs.insert( tvN );\n }\n}\n<commit_msg>Adding notProjectIters for iegen::Set<commit_after>\/*!\n * \\file util.h\n *\n * \\brief Utilities for the IEGen project\n *\n * \\date Started: 9\/13\/2010, but has been completely rewritten\n * # $Revision:: 622 $: last committed revision\n * # $Date:: 2013-01-18 13:11:32 -0#$: date of last committed revision\n * # $Author:: cathie $: author of last committed revision\n *\n * \\authors\n *\n * Copyright (c) 2012, Colorado State University <br>\n * All rights reserved. <br>\n * See ..\/..\/COPYING for details. <br>\n *\/\n\n#include \"jsonHelper.h\"\n\n\/\/using jsoncons::json;\n\/\/using namespace iegenlib;\n\n\/\/ Reads a list of UFCs from a json structure and stores them in the environment \nvoid addUFCs(json &ufcs){\n\n for (size_t j = 0; j < ufcs[\"UFS\"].size(); ++j){\n\n bool bijective = false;\n if( ufcs[\"UFS\"][j][\"Bijective\"].as<string>() == string(\"true\") ){\n bijective = true;\n }\n iegenlib::MonotonicType monotonicity = iegenlib::Monotonic_NONE;\n if(ufcs[\"UFS\"][j][\"Monotonicity\"].as<string>() == \n string(\"Monotonic_Nondecreasing\")){\n monotonicity = iegenlib::Monotonic_Nondecreasing;\n } else if(ufcs[\"UFS\"][j][\"Monotonicity\"].as<string>() == \n string(\"Monotonic_Increasing\")){\n monotonicity = iegenlib::Monotonic_Increasing;\n }\n\n iegenlib::appendCurrEnv(ufcs[\"UFS\"][j][\"Name\"].as<string>(),\/\/ Name\n new Set(ufcs[\"UFS\"][j][\"Domain\"].as<string>()), \/\/ Domain \n new Set(ufcs[\"UFS\"][j][\"Range\"].as<string>()), \/\/ Range\n bijective, \/\/ Bijective?\n monotonicity \/\/ Monotonicity?\n );\n }\n}\n\n\n\/\/ Reads a list of universially quantified constraints from a json structure\n\/\/ and stores them in the environment\nvoid addUniQuantRules(json &uqCons){\n\n UniQuantRule *uqRule;\n for (size_t j = 0; j < uqCons.size(); ++j){\n\n \/\/ forall e1, e2, ... : p => q\n uqRule = new UniQuantRule(uqCons[j][\"Type\"].as<string>(), \n uqCons[j][\"UniQuantVar\"].as<string>(), \n uqCons[j][\"p\"].as<string>(), uqCons[j][\"q\"].as<string>());\n currentEnv.addUniQuantRule( uqRule );\n }\n}\n\n\/\/ Reads iterators that we should not project from a json sructure\nvoid notProjectIters(Relation* rel, std::set<int> ¶llelTvs, json &np){\n\n iegenlib::TupleDecl td = rel->getTupleDecl();\n for (size_t j = 0; j < np.size(); ++j){\n string tvS = np[j].as<string>();\n int tvN = -1;\n for (unsigned int c = 0 ; c < td.getSize() ; c++){\n if( tvS == td.elemToString(c) ){\n tvN = c;\n break;\n }\n }\n parallelTvs.insert( tvN );\n }\n}\n\n\/\/ Reads iterators that we should not project from a json sructure\nvoid notProjectIters(Set* s, std::set<int> ¶llelTvs, json &np){\n\n iegenlib::TupleDecl td = s->getTupleDecl();\n for (size_t j = 0; j < np.size(); ++j){\n string tvS = np[j].as<string>();\n int tvN = -1;\n for (unsigned int c = 0 ; c < td.getSize() ; c++){\n if( tvS == td.elemToString(c) ){\n tvN = c;\n break;\n }\n }\n parallelTvs.insert( tvN );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)\n#include <windows.h>\n#endif\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include \"util\/exception.h\"\n#include \"util\/sstream.h\"\n#include \"util\/name.h\"\n#include \"util\/optional.h\"\n#include \"util\/realpath.h\"\n#include \"util\/lean_path.h\"\n\n#ifndef LEAN_DEFAULT_MODULE_FILE_NAME\n#define LEAN_DEFAULT_MODULE_FILE_NAME \"default\"\n#endif\n\nnamespace lean {\nfile_not_found_exception::file_not_found_exception(std::string const & fname):\n exception(sstream() << \"file '\" << fname << \"' not found in the LEAN_PATH\"),\n m_fname(fname) {}\n\nstatic std::string * g_default_file_name = nullptr;\n\nbool is_directory(char const * pathname) {\n struct stat info;\n if (stat(pathname, &info) != 0 )\n return false; \/\/ failed to access pathname\n return info.st_mode & S_IFDIR;\n}\n\n#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)\n\/\/ Windows version\nstatic char g_path_sep = ';';\nstatic char g_path_alt_sep = ':';\nstatic char g_sep = '\\\\';\nstatic char g_bad_sep = '\/';\nstatic std::string get_exe_location() {\n HMODULE hModule = GetModuleHandleW(NULL);\n WCHAR path[MAX_PATH];\n GetModuleFileNameW(hModule, path, MAX_PATH);\n std::wstring pathstr(path);\n return std::string(pathstr.begin(), pathstr.end());\n}\nbool is_path_sep(char c) { return c == g_path_sep || c == g_path_alt_sep; }\n#elif defined(__APPLE__)\n\/\/ OSX version\n#include <mach-o\/dyld.h>\n#include <limits.h>\n#include <stdlib.h>\nstatic char g_path_sep = ':';\nstatic char g_sep = '\/';\nstatic char g_bad_sep = '\\\\';\nstatic std::string get_exe_location() {\n char buf1[PATH_MAX];\n char buf2[PATH_MAX];\n uint32_t bufsize = PATH_MAX;\n if (_NSGetExecutablePath(buf1, &bufsize) != 0)\n throw exception(\"failed to locate Lean executable location\");\n if (!realpath(buf1, buf2))\n throw exception(\"failed to resolve symbolic links in \" + std::string(buf1));\n return std::string(buf2);\n}\nbool is_path_sep(char c) { return c == g_path_sep; }\n#else\n\/\/ Linux version\n#include <unistd.h>\n#include <string.h>\n#include <limits.h> \/\/ NOLINT\n#include <stdio.h>\nstatic char g_path_sep = ':';\nstatic char g_sep = '\/';\nstatic char g_bad_sep = '\\\\';\nstatic std::string get_exe_location() {\n char path[PATH_MAX];\n char dest[PATH_MAX];\n memset(dest, 0, PATH_MAX);\n pid_t pid = getpid();\n snprintf(path, PATH_MAX, \"\/proc\/%d\/exe\", pid);\n if (readlink(path, dest, PATH_MAX) == -1) {\n throw exception(\"failed to locate Lean executable location\");\n } else {\n return std::string(dest);\n }\n}\nbool is_path_sep(char c) { return c == g_path_sep; }\n#endif\n\nstd::string normalize_path(std::string f) {\n for (auto & c : f) {\n if (c == g_bad_sep)\n c = g_sep;\n }\n return f;\n}\n\nstd::string get_path(std::string f) {\n while (true) {\n if (f.empty())\n throw exception(\"failed to locate Lean executable location\");\n if (f.back() == g_sep) {\n f.pop_back();\n return f;\n }\n f.pop_back();\n }\n}\n\nstatic std::string * g_lean_path = nullptr;\nstatic std::vector<std::string> * g_lean_path_vector = nullptr;\n\nvoid init_lean_path(bool use_hott) {\n#if defined(LEAN_EMSCRIPTEN)\n *g_lean_path = \"\/library\";\n g_lean_path_vector->push_back(*g_lean_path);\n#else\n char * r = nullptr;\n if (use_hott)\n r = getenv(\"HLEAN_PATH\");\n else\n r = getenv(\"LEAN_PATH\");\n if (r == nullptr) {\n std::string exe_path = get_path(get_exe_location());\n if (use_hott)\n *g_lean_path = exe_path + g_sep + \"..\" + g_sep + \"hott\";\n else\n *g_lean_path = exe_path + g_sep + \"..\" + g_sep + \"library\";\n *g_lean_path += g_path_sep;\n *g_lean_path += exe_path + g_sep + \"..\" + g_sep + \"lib\" + g_sep + \"lean\";\n *g_lean_path += g_path_sep;\n *g_lean_path += \".\";\n } else {\n *g_lean_path = r;\n }\n g_lean_path_vector->clear();\n *g_lean_path = normalize_path(*g_lean_path);\n unsigned i = 0;\n unsigned j = 0;\n unsigned sz = g_lean_path->size();\n for (; j < sz; j++) {\n if (is_path_sep((*g_lean_path)[j])) {\n if (j > i)\n g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));\n i = j + 1;\n }\n }\n if (j > i)\n g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));\n#endif\n}\n\nstatic char g_sep_str[2];\n\nvoid initialize_lean_path(bool use_hott) {\n g_default_file_name = new std::string(LEAN_DEFAULT_MODULE_FILE_NAME);\n g_lean_path = new std::string();\n g_lean_path_vector = new std::vector<std::string>();\n g_sep_str[0] = g_sep;\n g_sep_str[1] = 0;\n init_lean_path(use_hott);\n}\n\nvoid finalize_lean_path() {\n delete g_lean_path_vector;\n delete g_lean_path;\n delete g_default_file_name;\n}\n\nbool has_file_ext(std::string const & fname, char const * ext) {\n unsigned ext_len = strlen(ext);\n return fname.size() > ext_len && fname.substr(fname.size() - ext_len, ext_len) == ext;\n}\n\nbool is_hlean_file(std::string const & fname) {\n return has_file_ext(fname, \".hlean\");\n}\n\nbool is_lean_file(std::string const & fname) {\n return has_file_ext(fname, \".lean\");\n}\n\nbool is_olean_file(std::string const & fname) {\n return has_file_ext(fname, \".olean\");\n}\n\nbool is_lua_file(std::string const & fname) {\n return has_file_ext(fname, \".lua\");\n}\n\nbool is_known_file_ext(std::string const & fname) {\n return is_lean_file(fname) || is_hlean_file(fname) || is_olean_file(fname) || is_lua_file(fname);\n}\n\noptional<std::string> check_file_core(std::string file, char const * ext) {\n if (ext)\n file += ext;\n std::ifstream ifile(file);\n if (ifile)\n return optional<std::string>(lrealpath(file.c_str()));\n else\n return optional<std::string>();\n}\n\noptional<std::string> check_file(std::string const & path, std::string const & fname, char const * ext = nullptr) {\n std::string file = path + g_sep + fname;\n if (is_directory(file.c_str())) {\n std::string default_file = file + g_sep + *g_default_file_name;\n if (auto r1 = check_file_core(default_file, ext)) {\n if (auto r2 = check_file_core(file, ext))\n throw exception(sstream() << \"ambiguous import, it can be '\" << *r1 << \"' or '\" << *r2 << \"'\");\n return r1;\n }\n }\n return check_file_core(file, ext);\n}\n\nstd::string name_to_file(name const & fname) {\n return fname.to_string(g_sep_str);\n}\n\nstd::string find_file(std::string fname, std::initializer_list<char const *> const & extensions) {\n bool is_known = is_known_file_ext(fname);\n fname = normalize_path(fname);\n for (auto path : *g_lean_path_vector) {\n if (is_known) {\n if (auto r = check_file(path, fname))\n return *r;\n } else {\n for (auto ext : extensions) {\n if (auto r = check_file(path, fname, ext))\n return *r;\n }\n }\n }\n throw file_not_found_exception(fname);\n}\n\nstd::string find_file(std::string const & base, optional<unsigned> const & rel, name const & fname,\n std::initializer_list<char const *> const & extensions) {\n if (!rel) {\n return find_file(fname.to_string(g_sep_str), extensions);\n } else {\n auto path = base;\n for (unsigned i = 0; i < *rel; i++) {\n path += g_sep;\n path += \"..\";\n }\n for (auto ext : extensions) {\n if (auto r = check_file(path, fname.to_string(g_sep_str), ext))\n return *r;\n }\n throw file_not_found_exception(fname.to_string());\n }\n}\n\nstd::string find_file(std::string const & base, optional<unsigned> const & k, name const & fname, char const * ext) {\n return find_file(base, k, fname, {ext});\n}\n\nstd::string find_file(std::string fname) {\n return find_file(fname, {\".olean\", \".lean\", \".lua\"});\n}\n\nstd::string find_file(name const & fname) {\n return find_file(fname.to_string(g_sep_str));\n}\n\nstd::string find_file(name const & fname, std::initializer_list<char const *> const & exts) {\n return find_file(fname.to_string(g_sep_str), exts);\n}\n\nchar const * get_lean_path() {\n return g_lean_path->c_str();\n}\n\nvoid display_path(std::ostream & out, std::string const & fname) {\n out << fname;\n}\n\nstd::string dirname(char const * fname) {\n if (fname == nullptr)\n return \".\";\n std::string nfname = normalize_path(std::string(fname));\n fname = nfname.c_str();\n unsigned i = 0;\n unsigned last_sep = 0;\n bool found_sep = false;\n char const * it = fname;\n while (*it) {\n if (*it == g_sep) {\n found_sep = true;\n last_sep = i;\n }\n ++i;\n ++it;\n }\n if (!found_sep) {\n return \".\";\n } else {\n std::string r;\n for (unsigned i = 0; i < last_sep; i++)\n r.push_back(fname[i]);\n return r;\n }\n}\n\nstd::string path_append(char const * p1, char const * p2) {\n std::string r(p1);\n r += g_sep;\n r += p2;\n return r;\n}\n}\n<commit_msg>fix(util\/lean_path): memory leak<commit_after>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)\n#include <windows.h>\n#endif\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include \"util\/exception.h\"\n#include \"util\/sstream.h\"\n#include \"util\/name.h\"\n#include \"util\/optional.h\"\n#include \"util\/realpath.h\"\n#include \"util\/lean_path.h\"\n\n#ifndef LEAN_DEFAULT_MODULE_FILE_NAME\n#define LEAN_DEFAULT_MODULE_FILE_NAME \"default\"\n#endif\n\nnamespace lean {\nfile_not_found_exception::file_not_found_exception(std::string const & fname):\n exception(sstream() << \"file '\" << fname << \"' not found in the LEAN_PATH\"),\n m_fname(fname) {}\n\nstatic std::string * g_default_file_name = nullptr;\nstatic std::string * g_lean_path = nullptr;\nstatic std::vector<std::string> * g_lean_path_vector = nullptr;\n\nbool is_directory(char const * pathname) {\n struct stat info;\n if (stat(pathname, &info) != 0 )\n return false; \/\/ failed to access pathname\n return info.st_mode & S_IFDIR;\n}\n\n#if defined(LEAN_WINDOWS) && !defined(LEAN_CYGWIN)\n\/\/ Windows version\nstatic char g_path_sep = ';';\nstatic char g_path_alt_sep = ':';\nstatic char g_sep = '\\\\';\nstatic char g_bad_sep = '\/';\nstatic std::string get_exe_location() {\n HMODULE hModule = GetModuleHandleW(NULL);\n WCHAR path[MAX_PATH];\n GetModuleFileNameW(hModule, path, MAX_PATH);\n std::wstring pathstr(path);\n return std::string(pathstr.begin(), pathstr.end());\n}\nbool is_path_sep(char c) { return c == g_path_sep || c == g_path_alt_sep; }\n#elif defined(__APPLE__)\n\/\/ OSX version\n#include <mach-o\/dyld.h>\n#include <limits.h>\n#include <stdlib.h>\nstatic char g_path_sep = ':';\nstatic char g_sep = '\/';\nstatic char g_bad_sep = '\\\\';\nstatic std::string get_exe_location() {\n char buf1[PATH_MAX];\n char buf2[PATH_MAX];\n uint32_t bufsize = PATH_MAX;\n if (_NSGetExecutablePath(buf1, &bufsize) != 0)\n throw exception(\"failed to locate Lean executable location\");\n if (!realpath(buf1, buf2))\n throw exception(\"failed to resolve symbolic links in \" + std::string(buf1));\n return std::string(buf2);\n}\nbool is_path_sep(char c) { return c == g_path_sep; }\n#else\n\/\/ Linux version\n#include <unistd.h>\n#include <string.h>\n#include <limits.h> \/\/ NOLINT\n#include <stdio.h>\nstatic char g_path_sep = ':';\nstatic char g_sep = '\/';\nstatic char g_bad_sep = '\\\\';\nstatic std::string get_exe_location() {\n char path[PATH_MAX];\n char dest[PATH_MAX];\n memset(dest, 0, PATH_MAX);\n pid_t pid = getpid();\n snprintf(path, PATH_MAX, \"\/proc\/%d\/exe\", pid);\n if (readlink(path, dest, PATH_MAX) == -1) {\n throw exception(\"failed to locate Lean executable location\");\n } else {\n return std::string(dest);\n }\n}\nbool is_path_sep(char c) { return c == g_path_sep; }\n#endif\n\nstd::string normalize_path(std::string f) {\n for (auto & c : f) {\n if (c == g_bad_sep)\n c = g_sep;\n }\n return f;\n}\n\nstd::string get_path(std::string f) {\n while (true) {\n if (f.empty())\n throw exception(\"failed to locate Lean executable location\");\n if (f.back() == g_sep) {\n f.pop_back();\n return f;\n }\n f.pop_back();\n }\n}\n\nvoid init_lean_path(bool use_hott) {\n#if defined(LEAN_EMSCRIPTEN)\n *g_lean_path = \"\/library\";\n g_lean_path_vector->push_back(*g_lean_path);\n#else\n char * r = nullptr;\n if (use_hott)\n r = getenv(\"HLEAN_PATH\");\n else\n r = getenv(\"LEAN_PATH\");\n if (r == nullptr) {\n std::string exe_path = get_path(get_exe_location());\n if (use_hott)\n *g_lean_path = exe_path + g_sep + \"..\" + g_sep + \"hott\";\n else\n *g_lean_path = exe_path + g_sep + \"..\" + g_sep + \"library\";\n *g_lean_path += g_path_sep;\n *g_lean_path += exe_path + g_sep + \"..\" + g_sep + \"lib\" + g_sep + \"lean\";\n *g_lean_path += g_path_sep;\n *g_lean_path += \".\";\n } else {\n *g_lean_path = r;\n }\n g_lean_path_vector->clear();\n *g_lean_path = normalize_path(*g_lean_path);\n unsigned i = 0;\n unsigned j = 0;\n unsigned sz = g_lean_path->size();\n for (; j < sz; j++) {\n if (is_path_sep((*g_lean_path)[j])) {\n if (j > i)\n g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));\n i = j + 1;\n }\n }\n if (j > i)\n g_lean_path_vector->push_back(g_lean_path->substr(i, j - i));\n#endif\n}\n\nstatic char g_sep_str[2];\n\nvoid initialize_lean_path(bool use_hott) {\n if (g_default_file_name != nullptr)\n finalize_lean_path();\n g_default_file_name = new std::string(LEAN_DEFAULT_MODULE_FILE_NAME);\n g_lean_path = new std::string();\n g_lean_path_vector = new std::vector<std::string>();\n g_sep_str[0] = g_sep;\n g_sep_str[1] = 0;\n init_lean_path(use_hott);\n}\n\nvoid finalize_lean_path() {\n delete g_lean_path_vector;\n delete g_lean_path;\n delete g_default_file_name;\n}\n\nbool has_file_ext(std::string const & fname, char const * ext) {\n unsigned ext_len = strlen(ext);\n return fname.size() > ext_len && fname.substr(fname.size() - ext_len, ext_len) == ext;\n}\n\nbool is_hlean_file(std::string const & fname) {\n return has_file_ext(fname, \".hlean\");\n}\n\nbool is_lean_file(std::string const & fname) {\n return has_file_ext(fname, \".lean\");\n}\n\nbool is_olean_file(std::string const & fname) {\n return has_file_ext(fname, \".olean\");\n}\n\nbool is_lua_file(std::string const & fname) {\n return has_file_ext(fname, \".lua\");\n}\n\nbool is_known_file_ext(std::string const & fname) {\n return is_lean_file(fname) || is_hlean_file(fname) || is_olean_file(fname) || is_lua_file(fname);\n}\n\noptional<std::string> check_file_core(std::string file, char const * ext) {\n if (ext)\n file += ext;\n std::ifstream ifile(file);\n if (ifile)\n return optional<std::string>(lrealpath(file.c_str()));\n else\n return optional<std::string>();\n}\n\noptional<std::string> check_file(std::string const & path, std::string const & fname, char const * ext = nullptr) {\n std::string file = path + g_sep + fname;\n if (is_directory(file.c_str())) {\n std::string default_file = file + g_sep + *g_default_file_name;\n if (auto r1 = check_file_core(default_file, ext)) {\n if (auto r2 = check_file_core(file, ext))\n throw exception(sstream() << \"ambiguous import, it can be '\" << *r1 << \"' or '\" << *r2 << \"'\");\n return r1;\n }\n }\n return check_file_core(file, ext);\n}\n\nstd::string name_to_file(name const & fname) {\n return fname.to_string(g_sep_str);\n}\n\nstd::string find_file(std::string fname, std::initializer_list<char const *> const & extensions) {\n bool is_known = is_known_file_ext(fname);\n fname = normalize_path(fname);\n for (auto path : *g_lean_path_vector) {\n if (is_known) {\n if (auto r = check_file(path, fname))\n return *r;\n } else {\n for (auto ext : extensions) {\n if (auto r = check_file(path, fname, ext))\n return *r;\n }\n }\n }\n throw file_not_found_exception(fname);\n}\n\nstd::string find_file(std::string const & base, optional<unsigned> const & rel, name const & fname,\n std::initializer_list<char const *> const & extensions) {\n if (!rel) {\n return find_file(fname.to_string(g_sep_str), extensions);\n } else {\n auto path = base;\n for (unsigned i = 0; i < *rel; i++) {\n path += g_sep;\n path += \"..\";\n }\n for (auto ext : extensions) {\n if (auto r = check_file(path, fname.to_string(g_sep_str), ext))\n return *r;\n }\n throw file_not_found_exception(fname.to_string());\n }\n}\n\nstd::string find_file(std::string const & base, optional<unsigned> const & k, name const & fname, char const * ext) {\n return find_file(base, k, fname, {ext});\n}\n\nstd::string find_file(std::string fname) {\n return find_file(fname, {\".olean\", \".lean\", \".lua\"});\n}\n\nstd::string find_file(name const & fname) {\n return find_file(fname.to_string(g_sep_str));\n}\n\nstd::string find_file(name const & fname, std::initializer_list<char const *> const & exts) {\n return find_file(fname.to_string(g_sep_str), exts);\n}\n\nchar const * get_lean_path() {\n return g_lean_path->c_str();\n}\n\nvoid display_path(std::ostream & out, std::string const & fname) {\n out << fname;\n}\n\nstd::string dirname(char const * fname) {\n if (fname == nullptr)\n return \".\";\n std::string nfname = normalize_path(std::string(fname));\n fname = nfname.c_str();\n unsigned i = 0;\n unsigned last_sep = 0;\n bool found_sep = false;\n char const * it = fname;\n while (*it) {\n if (*it == g_sep) {\n found_sep = true;\n last_sep = i;\n }\n ++i;\n ++it;\n }\n if (!found_sep) {\n return \".\";\n } else {\n std::string r;\n for (unsigned i = 0; i < last_sep; i++)\n r.push_back(fname[i]);\n return r;\n }\n}\n\nstd::string path_append(char const * p1, char const * p2) {\n std::string r(p1);\n r += g_sep;\n r += p2;\n return r;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuoutl.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 18:53:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fuoutl.hxx\"\n\n#include <svx\/outliner.hxx>\n\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuOutline, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuOutline::FuOutline (\n ViewShell* pViewShell,\n ::sd::Window* pWindow,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewShell, pWindow, pView, pDoc, rReq),\n pOutlineViewShell (static_cast<OutlineViewShell*>(pViewShell)),\n pOutlineView (static_cast<OutlineView*>(pView))\n{\n}\n\nFunctionReference FuOutline::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuOutline( pViewSh, pWin, pView, pDoc, rReq ) );\n return xFunc;\n}\n\n\/*************************************************************************\n|*\n|* Command, weiterleiten an OutlinerView\n|*\n\\************************************************************************\/\n\nBOOL FuOutline::Command(const CommandEvent& rCEvt)\n{\n BOOL bResult = FALSE;\n\n OutlinerView* pOlView =\n static_cast<OutlineView*>(pView)->GetViewByWindow(pWindow);\n DBG_ASSERT (pOlView, \"keine OutlinerView gefunden\");\n\n if (pOlView)\n {\n pOlView->Command(rCEvt); \/\/ liefert leider keinen Returnwert\n bResult = TRUE;\n }\n return bResult;\n}\n\nvoid FuOutline::ScrollStart()\n{\n}\n\nvoid FuOutline::ScrollEnd()\n{\n}\n\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.38); FILE MERGED 2006\/11\/22 12:41:54 cl 1.5.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuoutl.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 17:21:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fuoutl.hxx\"\n\n#include <svx\/outliner.hxx>\n\n#ifndef SD_OUTLINE_VIEW_HXX\n#include \"OutlineView.hxx\"\n#endif\n#ifndef SD_OUTLINE_VIEW_SHELL_HXX\n#include \"OutlineViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n\nnamespace sd {\n\nTYPEINIT1( FuOutline, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuOutline::FuOutline (\n ViewShell* pViewShell,\n ::sd::Window* pWindow,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewShell, pWindow, pView, pDoc, rReq),\n pOutlineViewShell (static_cast<OutlineViewShell*>(pViewShell)),\n pOutlineView (static_cast<OutlineView*>(pView))\n{\n}\n\nFunctionReference FuOutline::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuOutline( pViewSh, pWin, pView, pDoc, rReq ) );\n return xFunc;\n}\n\n\/*************************************************************************\n|*\n|* Command, weiterleiten an OutlinerView\n|*\n\\************************************************************************\/\n\nBOOL FuOutline::Command(const CommandEvent& rCEvt)\n{\n BOOL bResult = FALSE;\n\n OutlinerView* pOlView =\n static_cast<OutlineView*>(mpView)->GetViewByWindow(mpWindow);\n DBG_ASSERT (pOlView, \"keine OutlinerView gefunden\");\n\n if (pOlView)\n {\n pOlView->Command(rCEvt); \/\/ liefert leider keinen Returnwert\n bResult = TRUE;\n }\n return bResult;\n}\n\nvoid FuOutline::ScrollStart()\n{\n}\n\nvoid FuOutline::ScrollEnd()\n{\n}\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>#include \"selfdrive\/ui\/soundd\/sound.h\"\n\n#include <QAudio>\n#include <QAudioDeviceInfo>\n#include <QDebug>\n\n#include \"cereal\/messaging\/messaging.h\"\n#include \"selfdrive\/common\/util.h\"\n\n\/\/ TODO: detect when we can't play sounds\n\/\/ TODO: detect when we can't display the UI\n\nSound::Sound(QObject *parent) : sm({\"carState\", \"controlsState\", \"deviceState\"}) {\n qInfo() << \"default audio device: \" << QAudioDeviceInfo::defaultOutputDevice().deviceName();\n\n for (auto &[alert, fn, loops] : sound_list) {\n QSoundEffect *s = new QSoundEffect(this);\n QObject::connect(s, &QSoundEffect::statusChanged, [=]() {\n assert(s->status() != QSoundEffect::Error);\n });\n s->setVolume(Hardware::MIN_VOLUME);\n s->setSource(QUrl::fromLocalFile(\"..\/..\/assets\/sounds\/\" + fn));\n sounds[alert] = {s, loops};\n }\n\n QTimer *timer = new QTimer(this);\n QObject::connect(timer, &QTimer::timeout, this, &Sound::update);\n timer->start(1000 \/ UI_FREQ);\n};\n\nvoid Sound::update() {\n const bool started_prev = sm[\"deviceState\"].getDeviceState().getStarted();\n sm.update(0);\n\n const bool started = sm[\"deviceState\"].getDeviceState().getStarted();\n if (started && !started_prev) {\n started_frame = sm.frame;\n }\n\n \/\/ no sounds while offroad\n \/\/ also no sounds if nothing is alive in case thermald crashes while offroad\n const bool crashed = (sm.frame - std::max(sm.rcv_frame(\"deviceState\"), sm.rcv_frame(\"controlsState\"))) > 10*UI_FREQ;\n if (!started || crashed) {\n setAlert({});\n return;\n }\n\n \/\/ scale volume with speed\n if (sm.updated(\"carState\")) {\n float volume = util::map_val(sm[\"carState\"].getCarState().getVEgo(), 11.f, 20.f, 0.f, 1.0f);\n volume = QAudio::convertVolume(volume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale);\n volume = util::map_val(volume, 0.f, 1.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);\n for (auto &[s, loops] : sounds) {\n s->setVolume(std::round(100 * volume) \/ 100);\n }\n }\n\n setAlert(Alert::get(sm, started_frame));\n}\n\nvoid Sound::setAlert(const Alert &alert) {\n if (!current_alert.equal(alert)) {\n current_alert = alert;\n \/\/ stop sounds\n for (auto &[s, loops] : sounds) {\n \/\/ Only stop repeating sounds\n if (s->loopsRemaining() > 1 || s->loopsRemaining() == QSoundEffect::Infinite) {\n s->stop();\n }\n }\n\n \/\/ play sound\n if (alert.sound != AudibleAlert::NONE) {\n auto &[s, loops] = sounds[alert.sound];\n s->setLoopCount(loops);\n s->play();\n }\n }\n}\n<commit_msg>soundd: use setLoopCount(0) to stop repeating sound (#23076)<commit_after>#include \"selfdrive\/ui\/soundd\/sound.h\"\n\n#include <QAudio>\n#include <QAudioDeviceInfo>\n#include <QDebug>\n\n#include \"cereal\/messaging\/messaging.h\"\n#include \"selfdrive\/common\/util.h\"\n\n\/\/ TODO: detect when we can't play sounds\n\/\/ TODO: detect when we can't display the UI\n\nSound::Sound(QObject *parent) : sm({\"carState\", \"controlsState\", \"deviceState\"}) {\n qInfo() << \"default audio device: \" << QAudioDeviceInfo::defaultOutputDevice().deviceName();\n\n for (auto &[alert, fn, loops] : sound_list) {\n QSoundEffect *s = new QSoundEffect(this);\n QObject::connect(s, &QSoundEffect::statusChanged, [=]() {\n assert(s->status() != QSoundEffect::Error);\n });\n s->setVolume(Hardware::MIN_VOLUME);\n s->setSource(QUrl::fromLocalFile(\"..\/..\/assets\/sounds\/\" + fn));\n sounds[alert] = {s, loops};\n }\n\n QTimer *timer = new QTimer(this);\n QObject::connect(timer, &QTimer::timeout, this, &Sound::update);\n timer->start(1000 \/ UI_FREQ);\n};\n\nvoid Sound::update() {\n const bool started_prev = sm[\"deviceState\"].getDeviceState().getStarted();\n sm.update(0);\n\n const bool started = sm[\"deviceState\"].getDeviceState().getStarted();\n if (started && !started_prev) {\n started_frame = sm.frame;\n }\n\n \/\/ no sounds while offroad\n \/\/ also no sounds if nothing is alive in case thermald crashes while offroad\n const bool crashed = (sm.frame - std::max(sm.rcv_frame(\"deviceState\"), sm.rcv_frame(\"controlsState\"))) > 10*UI_FREQ;\n if (!started || crashed) {\n setAlert({});\n return;\n }\n\n \/\/ scale volume with speed\n if (sm.updated(\"carState\")) {\n float volume = util::map_val(sm[\"carState\"].getCarState().getVEgo(), 11.f, 20.f, 0.f, 1.0f);\n volume = QAudio::convertVolume(volume, QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale);\n volume = util::map_val(volume, 0.f, 1.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);\n for (auto &[s, loops] : sounds) {\n s->setVolume(std::round(100 * volume) \/ 100);\n }\n }\n\n setAlert(Alert::get(sm, started_frame));\n}\n\nvoid Sound::setAlert(const Alert &alert) {\n if (!current_alert.equal(alert)) {\n current_alert = alert;\n \/\/ stop sounds\n for (auto &[s, loops] : sounds) {\n \/\/ Only stop repeating sounds\n if (s->loopsRemaining() > 1 || s->loopsRemaining() == QSoundEffect::Infinite) {\n s->setLoopCount(0);\n }\n }\n\n \/\/ play sound\n if (alert.sound != AudibleAlert::NONE) {\n auto &[s, loops] = sounds[alert.sound];\n s->setLoopCount(loops);\n s->play();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"remoting\/jingle_glue\/jingle_channel.h\"\n#include \"remoting\/jingle_glue\/jingle_thread.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/libjingle\/source\/talk\/base\/stream.h\"\n\nusing testing::_;\nusing testing::Return;\nusing testing::Mock;\nusing testing::SetArgumentPointee;\n\nnamespace remoting {\n\nnamespace {\n\/\/ Size of test buffer in bytes.\nconst size_t kBufferSize = 100;\n} \/\/ namespace\n\nclass MockCallback : public JingleChannel::Callback {\n public:\n MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));\n MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,\n scoped_refptr<media::DataBuffer>));\n};\n\nclass MockStream : public talk_base::StreamInterface {\n public:\n virtual ~MockStream() {}\n MOCK_CONST_METHOD0(GetState, talk_base::StreamState());\n\n MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));\n MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,\n size_t*, int*));\n MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));\n MOCK_METHOD0(Close, void());\n\n MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));\n MOCK_METHOD2(PostEvent, void(int, int));\n};\n\nTEST(JingleChannelTest, Init) {\n JingleThread thread;\n\n MockStream* stream = new MockStream();\n MockCallback callback;\n\n EXPECT_CALL(*stream, GetState())\n .Times(1)\n .WillRepeatedly(Return(talk_base::SS_OPENING));\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))\n .Times(1);\n\n thread.Start();\n\n EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());\n channel->Init(&thread, stream, \"user@domain.com\");\n EXPECT_EQ(JingleChannel::CONNECTING, channel->state());\n channel->state_ = JingleChannel::CLOSED;\n\n thread.Stop();\n}\n\nTEST(JingleChannelTest, Write) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);\n data->SetDataSize(kBufferSize);\n\n EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),\n kBufferSize, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),\n Return(talk_base::SR_SUCCESS)));\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n thread.Start();\n channel->Write(data);\n thread.Stop();\n channel->state_ = JingleChannel::CLOSED;\n}\n\nTEST(JingleChannelTest, Read) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);\n data->SetDataSize(kBufferSize);\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))\n .Times(1);\n\n EXPECT_CALL(*stream, GetAvailable(_))\n .WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),\n Return(true)))\n .WillOnce(DoAll(SetArgumentPointee<0>(0),\n Return(true)));\n\n EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),\n Return(talk_base::SR_SUCCESS)));\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n thread.Start();\n channel->OnStreamEvent(stream, talk_base::SE_READ, 0);\n thread.Stop();\n channel->state_ = JingleChannel::CLOSED;\n}\n\nTEST(JingleChannelTest, Close) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n EXPECT_CALL(*stream, Close())\n .Times(1);\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n thread.Start();\n channel->Close();\n thread.Stop();\n}\n\n} \/\/ namespace remoting\n<commit_msg>Fixed GMock warning about unexpected call in remoting_unittests. BUG=None TEST=unittests<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"media\/base\/data_buffer.h\"\n#include \"remoting\/jingle_glue\/jingle_channel.h\"\n#include \"remoting\/jingle_glue\/jingle_thread.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/libjingle\/source\/talk\/base\/stream.h\"\n\nusing testing::_;\nusing testing::Return;\nusing testing::Mock;\nusing testing::SetArgumentPointee;\n\nnamespace remoting {\n\nnamespace {\n\/\/ Size of test buffer in bytes.\nconst size_t kBufferSize = 100;\n} \/\/ namespace\n\nclass MockCallback : public JingleChannel::Callback {\n public:\n MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));\n MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,\n scoped_refptr<media::DataBuffer>));\n};\n\nclass MockStream : public talk_base::StreamInterface {\n public:\n virtual ~MockStream() {}\n MOCK_CONST_METHOD0(GetState, talk_base::StreamState());\n\n MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));\n MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,\n size_t*, int*));\n MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));\n MOCK_METHOD0(Close, void());\n\n MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));\n MOCK_METHOD2(PostEvent, void(int, int));\n};\n\nTEST(JingleChannelTest, Init) {\n JingleThread thread;\n\n MockStream* stream = new MockStream();\n MockCallback callback;\n\n EXPECT_CALL(*stream, GetState())\n .Times(1)\n .WillRepeatedly(Return(talk_base::SS_OPENING));\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))\n .Times(1);\n\n thread.Start();\n\n EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());\n channel->Init(&thread, stream, \"user@domain.com\");\n EXPECT_EQ(JingleChannel::CONNECTING, channel->state());\n channel->state_ = JingleChannel::CLOSED;\n\n thread.Stop();\n}\n\nTEST(JingleChannelTest, Write) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);\n data->SetDataSize(kBufferSize);\n\n EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),\n kBufferSize, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),\n Return(talk_base::SR_SUCCESS)));\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n thread.Start();\n channel->Write(data);\n thread.Stop();\n channel->state_ = JingleChannel::CLOSED;\n}\n\nTEST(JingleChannelTest, Read) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);\n data->SetDataSize(kBufferSize);\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))\n .Times(1);\n\n EXPECT_CALL(*stream, GetAvailable(_))\n .WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),\n Return(true)))\n .WillOnce(DoAll(SetArgumentPointee<0>(0),\n Return(true)));\n\n EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))\n .WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),\n Return(talk_base::SR_SUCCESS)));\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n thread.Start();\n channel->OnStreamEvent(stream, talk_base::SE_READ, 0);\n thread.Stop();\n channel->state_ = JingleChannel::CLOSED;\n}\n\nTEST(JingleChannelTest, Close) {\n JingleThread thread;\n MockStream* stream = new MockStream(); \/\/ Freed by the channel.\n MockCallback callback;\n\n EXPECT_CALL(*stream, Close())\n .Times(1);\n\n scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);\n\n channel->thread_ = &thread;\n channel->stream_.reset(stream);\n channel->state_ = JingleChannel::OPEN;\n\n EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CLOSED))\n .Times(1);\n\n thread.Start();\n channel->Close();\n thread.Stop();\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"base\/mappable.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/linear_map.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"geometry\/sign.hpp\"\n#include \"gtest\/gtest_prod.h\"\n#include \"serialization\/geometry.pb.h\"\n\nnamespace principia {\nnamespace geometry {\n\ntemplate<typename FromFrame, typename ToFrame>\nclass OrthogonalMap;\n\n\/\/ A permutation of the coordinates. Obviously not coordinate-free, but\n\/\/ practical. There are no precision losses when composing or applying\n\/\/ permutations.\ntemplate<typename FromFrame, typename ToFrame>\nclass Permutation : public LinearMap<FromFrame, ToFrame> {\n \/\/ Declare shorter names for the protocol buffer enums.\n static int const EVEN = serialization::Permutation::EVEN;\n static int const ODD = serialization::Permutation::ODD;\n static int const X = serialization::Permutation::X;\n static int const Y = serialization::Permutation::Y;\n static int const Z = serialization::Permutation::Z;\n static int const INDEX = serialization::Permutation::INDEX;\n public:\n \/\/ Danger, Will Robinson! This enum is stored in the serialized\n \/\/ representation. Any change to the formulae below is likely to make it\n \/\/ impossible to read existing files.\n enum CoordinatePermutation {\n XYZ = EVEN + (X << X * 2) + (Y << Y * 2) + (Z << Z * 2) + (0 << INDEX),\n YZX = EVEN + (Y << X * 2) + (Z << Y * 2) + (X << Z * 2) + (1 << INDEX),\n ZXY = EVEN + (Z << X * 2) + (X << Y * 2) + (Y << Z * 2) + (2 << INDEX),\n XZY = ODD + (X << X * 2) + (Z << Y * 2) + (Y << Z * 2) + (3 << INDEX),\n ZYX = ODD + (Z << X * 2) + (Y << Y * 2) + (X << Z * 2) + (4 << INDEX),\n YXZ = ODD + (Y << X * 2) + (X << Y * 2) + (Z << Z * 2) + (5 << INDEX)\n };\n\n explicit Permutation(CoordinatePermutation const coordinate_permutation);\n ~Permutation() override = default;\n\n Sign Determinant() const override;\n\n Permutation<ToFrame, FromFrame> Inverse() const;\n\n template<typename Scalar>\n Vector<Scalar, ToFrame> operator()(\n Vector<Scalar, FromFrame> const& vector) const;\n\n template<typename Scalar>\n Bivector<Scalar, ToFrame> operator()(\n Bivector<Scalar, FromFrame> const& bivector) const;\n\n template<typename Scalar>\n Trivector<Scalar, ToFrame> operator()(\n Trivector<Scalar, FromFrame> const& trivector) const;\n\n template<typename T>\n typename base::Mappable<Permutation, T>::type operator()(T const& t) const;\n\n OrthogonalMap<FromFrame, ToFrame> Forget() const;\n\n static Permutation Identity();\n\n void WriteToMessage(not_null<serialization::LinearMap*> const message) const;\n static Permutation ReadFromMessage(serialization::LinearMap const& message);\n\n void WriteToMessage(\n not_null<serialization::Permutation*> const message) const;\n static Permutation ReadFromMessage(serialization::Permutation const& message);\n\n private:\n template<typename Scalar>\n R3Element<Scalar> operator()(R3Element<Scalar> const& r3_element) const;\n\n CoordinatePermutation coordinate_permutation_;\n\n template<typename From, typename Through, typename To>\n friend Permutation<From, To> operator*(\n Permutation<Through, To> const& left,\n Permutation<From, Through> const& right);\n\n \/\/ As much as I dislike FRIEND_TEST(), it seems like the most convenient way\n \/\/ to access the above operator.\n FRIEND_TEST(PermutationTest, Identity);\n FRIEND_TEST(PermutationTest, XYZ);\n FRIEND_TEST(PermutationTest, YZX);\n FRIEND_TEST(PermutationTest, ZXY);\n FRIEND_TEST(PermutationTest, XZY);\n FRIEND_TEST(PermutationTest, ZYX);\n FRIEND_TEST(PermutationTest, YXZ);\n};\n\ntemplate<typename FromFrame, typename ThroughFrame, typename ToFrame>\nPermutation<FromFrame, ToFrame> operator*(\n Permutation<ThroughFrame, ToFrame> const& left,\n Permutation<FromFrame, ThroughFrame> const& right);\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n\n#include \"geometry\/permutation_body.hpp\"\n<commit_msg>Lint.<commit_after>#pragma once\n\n#include \"base\/mappable.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/linear_map.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"geometry\/sign.hpp\"\n#include \"gtest\/gtest_prod.h\"\n#include \"serialization\/geometry.pb.h\"\n\nnamespace principia {\nnamespace geometry {\n\ntemplate<typename FromFrame, typename ToFrame>\nclass OrthogonalMap;\n\n\/\/ A permutation of the coordinates. Obviously not coordinate-free, but\n\/\/ practical. There are no precision losses when composing or applying\n\/\/ permutations.\ntemplate<typename FromFrame, typename ToFrame>\nclass Permutation : public LinearMap<FromFrame, ToFrame> {\n \/\/ Declare shorter names for the protocol buffer enums.\n static int const EVEN = serialization::Permutation::EVEN;\n static int const ODD = serialization::Permutation::ODD;\n static int const X = serialization::Permutation::X;\n static int const Y = serialization::Permutation::Y;\n static int const Z = serialization::Permutation::Z;\n static int const INDEX = serialization::Permutation::INDEX;\n\n public:\n \/\/ Danger, Will Robinson! This enum is stored in the serialized\n \/\/ representation. Any change to the formulae below is likely to make it\n \/\/ impossible to read existing files.\n enum CoordinatePermutation {\n XYZ = EVEN + (X << X * 2) + (Y << Y * 2) + (Z << Z * 2) + (0 << INDEX),\n YZX = EVEN + (Y << X * 2) + (Z << Y * 2) + (X << Z * 2) + (1 << INDEX),\n ZXY = EVEN + (Z << X * 2) + (X << Y * 2) + (Y << Z * 2) + (2 << INDEX),\n XZY = ODD + (X << X * 2) + (Z << Y * 2) + (Y << Z * 2) + (3 << INDEX),\n ZYX = ODD + (Z << X * 2) + (Y << Y * 2) + (X << Z * 2) + (4 << INDEX),\n YXZ = ODD + (Y << X * 2) + (X << Y * 2) + (Z << Z * 2) + (5 << INDEX)\n };\n\n explicit Permutation(CoordinatePermutation const coordinate_permutation);\n ~Permutation() override = default;\n\n Sign Determinant() const override;\n\n Permutation<ToFrame, FromFrame> Inverse() const;\n\n template<typename Scalar>\n Vector<Scalar, ToFrame> operator()(\n Vector<Scalar, FromFrame> const& vector) const;\n\n template<typename Scalar>\n Bivector<Scalar, ToFrame> operator()(\n Bivector<Scalar, FromFrame> const& bivector) const;\n\n template<typename Scalar>\n Trivector<Scalar, ToFrame> operator()(\n Trivector<Scalar, FromFrame> const& trivector) const;\n\n template<typename T>\n typename base::Mappable<Permutation, T>::type operator()(T const& t) const;\n\n OrthogonalMap<FromFrame, ToFrame> Forget() const;\n\n static Permutation Identity();\n\n void WriteToMessage(not_null<serialization::LinearMap*> const message) const;\n static Permutation ReadFromMessage(serialization::LinearMap const& message);\n\n void WriteToMessage(\n not_null<serialization::Permutation*> const message) const;\n static Permutation ReadFromMessage(serialization::Permutation const& message);\n\n private:\n template<typename Scalar>\n R3Element<Scalar> operator()(R3Element<Scalar> const& r3_element) const;\n\n CoordinatePermutation coordinate_permutation_;\n\n template<typename From, typename Through, typename To>\n friend Permutation<From, To> operator*(\n Permutation<Through, To> const& left,\n Permutation<From, Through> const& right);\n\n \/\/ As much as I dislike FRIEND_TEST(), it seems like the most convenient way\n \/\/ to access the above operator.\n FRIEND_TEST(PermutationTest, Identity);\n FRIEND_TEST(PermutationTest, XYZ);\n FRIEND_TEST(PermutationTest, YZX);\n FRIEND_TEST(PermutationTest, ZXY);\n FRIEND_TEST(PermutationTest, XZY);\n FRIEND_TEST(PermutationTest, ZYX);\n FRIEND_TEST(PermutationTest, YXZ);\n};\n\ntemplate<typename FromFrame, typename ThroughFrame, typename ToFrame>\nPermutation<FromFrame, ToFrame> operator*(\n Permutation<ThroughFrame, ToFrame> const& left,\n Permutation<FromFrame, ThroughFrame> const& right);\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n\n#include \"geometry\/permutation_body.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include <QtCore\/QStringList>\n#include <QtCore\/QUuid>\n#include <QtCore\/QVariant>\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlError>\n#include <QtSql\/QSqlQuery>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"imapparser.h\"\n#include \"fetchquery.h\"\n#include \"response.h\"\n\n#include \"fetch.h\"\n\nusing namespace Akonadi;\n\nFetch::Fetch()\n : Handler()\n{\n}\n\nFetch::~Fetch()\n{\n}\n\nbool Fetch::handleLine( const QByteArray& line )\n{\n Response response;\n response.setUntagged();\n\n int start = line.indexOf( ' ' ); \/\/ skip tag\n\n FetchQuery fetchQuery;\n if ( !fetchQuery.parse( line.mid( start + 1 ) ) ) {\n response.setTag( tag() );\n response.setError();\n response.setString( \"Syntax error\" );\n\n emit responseAvailable( response );\n deleteLater();\n\n return true;\n }\n\n DataStore *store = connection()->storageBackend();\n\n QList<PimItem> pimItems;\n if ( connection()->selectedLocation().id() == -1 ) {\n pimItems = store->fetchMatchingPimItemsByUID( fetchQuery );\n } else {\n if ( fetchQuery.isUidFetch() ) {\n pimItems = store->fetchMatchingPimItemsByUID( fetchQuery, connection()->selectedLocation() ) ;\n } else {\n pimItems = store->fetchMatchingPimItemsBySequenceNumbers( fetchQuery, connection()->selectedLocation() );\n }\n }\n\n for ( int i = 0; i < pimItems.count(); ++i ) {\n response.setUntagged();\n response.setString( buildResponse( pimItems[ i ], fetchQuery ) );\n emit responseAvailable( response );\n }\n\n response.setTag( tag() );\n response.setSuccess();\n\n if ( fetchQuery.isUidFetch() )\n response.setString( \"UID FETCH completed\" );\n else\n response.setString( \"FETCH completed\" );\n\n emit responseAvailable( response );\n\n deleteLater();\n\n return true;\n}\n\nQByteArray Fetch::buildResponse( const PimItem &item, const FetchQuery &fetchQuery )\n{\n QList<QByteArray> attributes;\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Envelope ) ) {\n attributes.append( \"ENVELOPE \" + buildEnvelope( item, fetchQuery ) );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Flags ) ) {\n QList<Flag> flagList = item.flags();\n\n QList<QByteArray> flags;\n for ( int i = 0; i < flagList.count(); ++i )\n flags.append( flagList[ i ].name().toUtf8() );\n\n MimeType mimeType = item.mimeType();\n flags.append( \"\\\\MimeTypes[\" + mimeType.name().toUtf8() + ']' );\n\n attributes.append( \"FLAGS (\" + ImapParser::join( flags, \" \" ) + ')' );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::InternalDate ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822 ) ||\n fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Text ) ||\n fetchQuery.hasAttributeType( FetchQuery::Attribute::Body ) ) {\n attributes.append( \"RFC822 {\" + QByteArray::number( item.data().length() ) +\n \"}\\r\\n\" + item.data() );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Header ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Size ) ) {\n attributes.append( \"RFC822.SIZE \" + QByteArray::number( item.data().length() ) );\n }\n\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Body_Structure ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Uid ) || fetchQuery.isUidFetch() ) {\n attributes.append( \"UID \" + QByteArray::number( item.id() ) );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RemoteId ) ) {\n attributes.append( \"REMOTEID \" + item.remoteId() );\n }\n\n QByteArray attributesString;\n for ( int i = 0; i < attributes.count(); ++i ) {\n if ( i != 0 )\n attributesString += ' ' + attributes[ i ];\n else\n attributesString += attributes[ i ];\n }\n\n int itemPosition = connection()->storageBackend()->pimItemPosition( item );\n\n if ( attributes.isEmpty() )\n return QByteArray::number( itemPosition ) + \" FETCH\";\n else\n return QByteArray::number( itemPosition ) + \" FETCH (\" + attributesString + ')';\n}\n\n\/\/ FIXME build from database\nQByteArray Fetch::buildEnvelope( const PimItem&, const FetchQuery& )\n{\n const QByteArray date( \"\\\"Wed, 1 Feb 2006 13:37:19 UT\\\"\" );\n const QByteArray subject( \"\\\"IMPORTANT: Akonadi Test\\\"\" );\n const QByteArray from( \"\\\"Tobias Koenig\\\" NIL \\\"tokoe\\\" \\\"kde.org\\\"\" );\n const QByteArray sender = from;\n const QByteArray replyTo( \"NIL\" );\n const QByteArray to( \"\\\"Ingo Kloecker\\\" NIL \\\"kloecker\\\" \\\"kde.org\\\"\" );\n const QByteArray cc( \"NIL\" );\n const QByteArray bcc( \"NIL\" );\n const QByteArray inReplyTo( \"NIL\" );\n const QByteArray messageId( '<' + QUuid::createUuid().toString().toLatin1() + \"@server.kde.org>\" );\n\n return QByteArray( '('+date+' '+subject+\" ((\"+from+\")) ((\"+sender+\")) \"+replyTo+\" ((\"+to+\")) \"+cc+' '+bcc+' '+inReplyTo+' '+messageId+')' );\n}\n<commit_msg>Get rid of some unecessary ugly IMAP compatibility hack.<commit_after>\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include <QtCore\/QStringList>\n#include <QtCore\/QUuid>\n#include <QtCore\/QVariant>\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlError>\n#include <QtSql\/QSqlQuery>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"imapparser.h\"\n#include \"fetchquery.h\"\n#include \"response.h\"\n\n#include \"fetch.h\"\n\nusing namespace Akonadi;\n\nFetch::Fetch()\n : Handler()\n{\n}\n\nFetch::~Fetch()\n{\n}\n\nbool Fetch::handleLine( const QByteArray& line )\n{\n Response response;\n response.setUntagged();\n\n int start = line.indexOf( ' ' ); \/\/ skip tag\n\n FetchQuery fetchQuery;\n if ( !fetchQuery.parse( line.mid( start + 1 ) ) ) {\n response.setTag( tag() );\n response.setError();\n response.setString( \"Syntax error\" );\n\n emit responseAvailable( response );\n deleteLater();\n\n return true;\n }\n\n DataStore *store = connection()->storageBackend();\n\n QList<PimItem> pimItems;\n if ( connection()->selectedLocation().id() == -1 ) {\n pimItems = store->fetchMatchingPimItemsByUID( fetchQuery );\n } else {\n if ( fetchQuery.isUidFetch() ) {\n pimItems = store->fetchMatchingPimItemsByUID( fetchQuery, connection()->selectedLocation() ) ;\n } else {\n pimItems = store->fetchMatchingPimItemsBySequenceNumbers( fetchQuery, connection()->selectedLocation() );\n }\n }\n\n for ( int i = 0; i < pimItems.count(); ++i ) {\n response.setUntagged();\n response.setString( buildResponse( pimItems[ i ], fetchQuery ) );\n emit responseAvailable( response );\n }\n\n response.setTag( tag() );\n response.setSuccess();\n\n if ( fetchQuery.isUidFetch() )\n response.setString( \"UID FETCH completed\" );\n else\n response.setString( \"FETCH completed\" );\n\n emit responseAvailable( response );\n\n deleteLater();\n\n return true;\n}\n\nQByteArray Fetch::buildResponse( const PimItem &item, const FetchQuery &fetchQuery )\n{\n QList<QByteArray> attributes;\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Envelope ) ) {\n attributes.append( \"ENVELOPE \" + buildEnvelope( item, fetchQuery ) );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Flags ) ) {\n QList<Flag> flagList = item.flags();\n\n QList<QByteArray> flags;\n for ( int i = 0; i < flagList.count(); ++i )\n flags.append( flagList[ i ].name().toUtf8() );\n\n MimeType mimeType = item.mimeType();\n attributes.append( \"MIMETYPE \\\"\" + mimeType.name().toUtf8() + \"\\\"\" );\n\n attributes.append( \"FLAGS (\" + ImapParser::join( flags, \" \" ) + ')' );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::InternalDate ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822 ) ||\n fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Text ) ||\n fetchQuery.hasAttributeType( FetchQuery::Attribute::Body ) ) {\n attributes.append( \"RFC822 {\" + QByteArray::number( item.data().length() ) +\n \"}\\r\\n\" + item.data() );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Header ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RFC822_Size ) ) {\n attributes.append( \"RFC822.SIZE \" + QByteArray::number( item.data().length() ) );\n }\n\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Body_Structure ) ) {\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::Uid ) || fetchQuery.isUidFetch() ) {\n attributes.append( \"UID \" + QByteArray::number( item.id() ) );\n }\n\n if ( fetchQuery.hasAttributeType( FetchQuery::Attribute::RemoteId ) ) {\n attributes.append( \"REMOTEID \" + item.remoteId() );\n }\n\n QByteArray attributesString;\n for ( int i = 0; i < attributes.count(); ++i ) {\n if ( i != 0 )\n attributesString += ' ' + attributes[ i ];\n else\n attributesString += attributes[ i ];\n }\n\n int itemPosition = connection()->storageBackend()->pimItemPosition( item );\n\n if ( attributes.isEmpty() )\n return QByteArray::number( itemPosition ) + \" FETCH\";\n else\n return QByteArray::number( itemPosition ) + \" FETCH (\" + attributesString + ')';\n}\n\n\/\/ FIXME build from database\nQByteArray Fetch::buildEnvelope( const PimItem&, const FetchQuery& )\n{\n const QByteArray date( \"\\\"Wed, 1 Feb 2006 13:37:19 UT\\\"\" );\n const QByteArray subject( \"\\\"IMPORTANT: Akonadi Test\\\"\" );\n const QByteArray from( \"\\\"Tobias Koenig\\\" NIL \\\"tokoe\\\" \\\"kde.org\\\"\" );\n const QByteArray sender = from;\n const QByteArray replyTo( \"NIL\" );\n const QByteArray to( \"\\\"Ingo Kloecker\\\" NIL \\\"kloecker\\\" \\\"kde.org\\\"\" );\n const QByteArray cc( \"NIL\" );\n const QByteArray bcc( \"NIL\" );\n const QByteArray inReplyTo( \"NIL\" );\n const QByteArray messageId( '<' + QUuid::createUuid().toString().toLatin1() + \"@server.kde.org>\" );\n\n return QByteArray( '('+date+' '+subject+\" ((\"+from+\")) ((\"+sender+\")) \"+replyTo+\" ((\"+to+\")) \"+cc+' '+bcc+' '+inReplyTo+' '+messageId+')' );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: appquit.cxx,v $\n *\n * $Revision: 1.24 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 19:53:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BASMGR_HXX \/\/autogen\n#include <basic\/basmgr.hxx>\n#endif\n#ifndef _SB_SBSTAR_HXX \/\/autogen\n#include <basic\/sbstar.hxx>\n#endif\n\n#ifdef WIN\n#define _TL_LANG_SPECIAL\n#endif\n\n#ifndef _SVDDE_HXX \/\/autogen\n#include <svtools\/svdde.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SFXENUMITEM_HXX\n#include <svtools\/eitem.hxx>\n#endif\n\n#include <svtools\/inethist.hxx>\n#include <svtools\/saveopt.hxx>\n\n#pragma hdrstop\n\n#include \"app.hrc\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"appdata.hxx\"\n#include \"viewsh.hxx\"\n#include \"dispatch.hxx\"\n#include \"printer.hxx\"\n#include \"plugobj.hxx\"\n#include \"arrdecl.hxx\"\n#include \"sfxresid.hxx\"\n#include \"newhdl.hxx\"\n#include \"cfgmgr.hxx\"\n#include \"accmgr.hxx\"\n#include \"event.hxx\"\n#include \"macrconf.hxx\"\n#include \"mnumgr.hxx\"\n#include \"imgmgr.hxx\"\n#include \"templdlg.hxx\"\n#include \"tbxconf.hxx\"\n#include \"msgpool.hxx\"\n#include \"frameobj.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"appimp.hxx\"\n#include \"sfxlocal.hrc\"\n#include \"dataurl.hxx\"\n#include \"fcontnr.hxx\"\n#include \"nochaos.hxx\"\n#include \"appuno.hxx\"\n#include \"doctempl.hxx\"\n#include \"viewfrm.hxx\"\n#include \"bmkmenu.hxx\"\n#include \"objsh.hxx\"\n#include \"dlgcont.hxx\"\n#include \"scriptcont.hxx\"\n#include <svtools\/misccfg.hxx>\n#include \"docfac.hxx\"\n\n#ifndef PRODUCT\nDECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )\nSV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);\n#endif\n\n\/\/===================================================================\n\/*\nvoid SfxApplication::Quit()\n{\n QueryExit_Impl();\n}\n*\/\n\/\/--------------------------------------------------------------------\nBOOL SfxApplication::QueryExit_Impl()\n\n\/* [Beschreibung]\n\n Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder\n der Printer einer SfxViewShell einen laufenden Druckjob hat.\n\n [Anmerkung]\n\n Wenn diese aus StarView stammende virtuelle Methode vom Applikations-\n entwickler \"uberladen wird, mu\"s diese SfxApplication::QueryExit() rufen\n und falls diese FALSE zur\"uckgibt, ebenfalls FALSE zur\"uckgeben.\n*\/\n\n{\n SaveConfiguration();\n BOOL bQuit = TRUE;\n\n\/*\n BOOL bPrinting = FALSE;\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n bPrinting = pPrinter && pPrinter->IsPrinting();\n }\n\n if ( bPrinting )\n {\n \/\/ Benutzer fragen, ob abgebrochen werden soll\n if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )\n {\n \/\/ alle Jobs canceln\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n if ( pPrinter && pPrinter->IsPrinting() )\n pPrinter->AbortJob();\n }\n\n \/\/ da das Canceln asynchron ist, Quit erstmal wieder verlassen\n GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );\n DBG_TRACE( \"QueryExit => FALSE (printing)\" );\n return FALSE;\n }\n }\n*\/\n \/\/ alles canceln was zu canceln ist\n GetCancelManager()->Cancel(TRUE);\n\n\/*\n SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();\n if ( bQuit )\n {\n \/\/ Jetzt zur Sicherheit auch hidden Frames abr\"aumen\n SfxViewFrame::CloseHiddenFrames_Impl();\n pLastDocSh = SfxObjectShell::GetFirst();\n }\n*\/\n \/\/ will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?\n if ( !bQuit )\n {\n \/\/ nicht wirklich beenden, nur minimieren\n pAppData_Impl->bOLEResize = TRUE;\n InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );\n aInfoBox.Execute();\n DBG_TRACE( \"QueryExit => FALSE (in use)\" );\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/-------------------------------------------------------------------------\n\nvoid SfxApplication::Deinitialize()\n{\n if ( bDowning )\n return;\n\n \/\/ Falls man nochmal beim Runterfahren in ein Reschedule l\"auft\n pAppData_Impl->EndListening( *this );\n if ( pAppData_Impl->pCancelMgr )\n pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );\n\n \/\/!Wait();\n StarBASIC::Stop();\n\n \/\/ ggf. BASIC speichern\n if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )\n SaveBasicManager();\n\n SaveBasicContainer();\n SaveDialogContainer();\n\n bDowning = TRUE; \/\/ wegen Timer aus DecAliveCount und QueryExit\n\n DELETEZ( pAppData_Impl->pTemplates );\n\n DELETEZ(pImp->pTemplateDlg);\n SetViewFrame(0);\n bDowning = FALSE;\n DBG_ASSERT( !SfxViewFrame::GetFirst(),\n \"existing SfxViewFrame after Execute\" );\n DBG_ASSERT( !SfxObjectShell::GetFirst(),\n \"existing SfxObjectShell after Execute\" );\n pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );\n pAppDispat->Flush();\n bDowning = TRUE;\n pAppDispat->DoDeactivate_Impl( TRUE );\n\n INetURLHistory::Delete();\n\n \/\/ call derived application-exit\n bInExit = TRUE;\n Exit();\n\n \/\/ Controller u.\"a. freigeben\n \/\/ dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden\n DELETEZ(pMenuMgr);\n DELETEZ(pAcceleratorMgr);\n SfxObjectFactory::ClearAll_Impl();\n DELETEZ( pImp->pBasicMgr );\n if( pImp->pBasicLibContainer )\n pImp->pBasicLibContainer->release();\n if( pImp->pDialogLibContainer )\n pImp->pDialogLibContainer->release();\n\n bInExit = FALSE;\n\n DBG_ASSERT( pViewFrame == 0, \"active foreign ViewFrame\" );\n\n delete[] pInterfaces, pInterfaces = 0;\n DELETEZ(pImageMgr);\n\n \/\/ free administration managers\n DELETEZ(pImp->pAutoSaveTimer);\n DELETEZ(pAppDispat);\n SfxResId::DeleteResMgr();\n DELETEZ(pImp->pOfaResMgr);\n\n \/\/ ab hier d\"urfen keine SvObjects mehr existieren\n DELETEX(pAppData_Impl->pMatcher);\n DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);\n DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);\n\n delete pAppData_Impl->pLabelResMgr;\n\n#ifndef PRODUCT\n DELETEX(pSlotPool);\n DELETEX(pAppData_Impl->pEventConfig);\n DELETEX(pAppData_Impl->pMiscConfig);\n SfxMacroConfig::Release_Impl();\n DELETEX(pAppData_Impl->pVerbs);\n DELETEX(pAppData_Impl->pFactArr);\n DELETEX(pAppData_Impl->pInitLinkList);\n#endif\n\n#ifndef PRODUCT\n DELETEX(pImp->pTbxCtrlFac);\n DELETEX(pImp->pStbCtrlFac);\n DELETEX(pImp->pMenuCtrlFac);\n DELETEX(pImp->pEventHdl);\n SfxNewHdl::Delete();\n DELETEX(pImp->pAutoSaveTimer);\n DELETEX(pImp->pViewFrames);\n DELETEX(pImp->pViewShells);\n DELETEX(pImp->pObjShells);\n#endif\n\n NoChaos::ReleaseItemPool();\n pAppData_Impl->pPool = NULL;\n}\n<commit_msg>INTEGRATION: CWS ooo20040329 (1.24.62); FILE MERGED 2004\/03\/18 10:31:52 waratah 1.24.62.1: :#i1858# exclude pragma hdrstop by bracketting for gcc<commit_after>\/*************************************************************************\n *\n * $RCSfile: appquit.cxx,v $\n *\n * $Revision: 1.25 $\n *\n * last change: $Author: svesik $ $Date: 2004-04-21 13:03:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BASMGR_HXX \/\/autogen\n#include <basic\/basmgr.hxx>\n#endif\n#ifndef _SB_SBSTAR_HXX \/\/autogen\n#include <basic\/sbstar.hxx>\n#endif\n\n#ifdef WIN\n#define _TL_LANG_SPECIAL\n#endif\n\n#ifndef _SVDDE_HXX \/\/autogen\n#include <svtools\/svdde.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SFXENUMITEM_HXX\n#include <svtools\/eitem.hxx>\n#endif\n\n#include <svtools\/inethist.hxx>\n#include <svtools\/saveopt.hxx>\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n#include \"app.hrc\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"appdata.hxx\"\n#include \"viewsh.hxx\"\n#include \"dispatch.hxx\"\n#include \"printer.hxx\"\n#include \"plugobj.hxx\"\n#include \"arrdecl.hxx\"\n#include \"sfxresid.hxx\"\n#include \"newhdl.hxx\"\n#include \"cfgmgr.hxx\"\n#include \"accmgr.hxx\"\n#include \"event.hxx\"\n#include \"macrconf.hxx\"\n#include \"mnumgr.hxx\"\n#include \"imgmgr.hxx\"\n#include \"templdlg.hxx\"\n#include \"tbxconf.hxx\"\n#include \"msgpool.hxx\"\n#include \"frameobj.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"appimp.hxx\"\n#include \"sfxlocal.hrc\"\n#include \"dataurl.hxx\"\n#include \"fcontnr.hxx\"\n#include \"nochaos.hxx\"\n#include \"appuno.hxx\"\n#include \"doctempl.hxx\"\n#include \"viewfrm.hxx\"\n#include \"bmkmenu.hxx\"\n#include \"objsh.hxx\"\n#include \"dlgcont.hxx\"\n#include \"scriptcont.hxx\"\n#include <svtools\/misccfg.hxx>\n#include \"docfac.hxx\"\n\n#ifndef PRODUCT\nDECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )\nSV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);\n#endif\n\n\/\/===================================================================\n\/*\nvoid SfxApplication::Quit()\n{\n QueryExit_Impl();\n}\n*\/\n\/\/--------------------------------------------------------------------\nBOOL SfxApplication::QueryExit_Impl()\n\n\/* [Beschreibung]\n\n Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder\n der Printer einer SfxViewShell einen laufenden Druckjob hat.\n\n [Anmerkung]\n\n Wenn diese aus StarView stammende virtuelle Methode vom Applikations-\n entwickler \"uberladen wird, mu\"s diese SfxApplication::QueryExit() rufen\n und falls diese FALSE zur\"uckgibt, ebenfalls FALSE zur\"uckgeben.\n*\/\n\n{\n SaveConfiguration();\n BOOL bQuit = TRUE;\n\n\/*\n BOOL bPrinting = FALSE;\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n bPrinting = pPrinter && pPrinter->IsPrinting();\n }\n\n if ( bPrinting )\n {\n \/\/ Benutzer fragen, ob abgebrochen werden soll\n if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )\n {\n \/\/ alle Jobs canceln\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n if ( pPrinter && pPrinter->IsPrinting() )\n pPrinter->AbortJob();\n }\n\n \/\/ da das Canceln asynchron ist, Quit erstmal wieder verlassen\n GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );\n DBG_TRACE( \"QueryExit => FALSE (printing)\" );\n return FALSE;\n }\n }\n*\/\n \/\/ alles canceln was zu canceln ist\n GetCancelManager()->Cancel(TRUE);\n\n\/*\n SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();\n if ( bQuit )\n {\n \/\/ Jetzt zur Sicherheit auch hidden Frames abr\"aumen\n SfxViewFrame::CloseHiddenFrames_Impl();\n pLastDocSh = SfxObjectShell::GetFirst();\n }\n*\/\n \/\/ will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?\n if ( !bQuit )\n {\n \/\/ nicht wirklich beenden, nur minimieren\n pAppData_Impl->bOLEResize = TRUE;\n InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );\n aInfoBox.Execute();\n DBG_TRACE( \"QueryExit => FALSE (in use)\" );\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/-------------------------------------------------------------------------\n\nvoid SfxApplication::Deinitialize()\n{\n if ( bDowning )\n return;\n\n \/\/ Falls man nochmal beim Runterfahren in ein Reschedule l\"auft\n pAppData_Impl->EndListening( *this );\n if ( pAppData_Impl->pCancelMgr )\n pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );\n\n \/\/!Wait();\n StarBASIC::Stop();\n\n \/\/ ggf. BASIC speichern\n if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )\n SaveBasicManager();\n\n SaveBasicContainer();\n SaveDialogContainer();\n\n bDowning = TRUE; \/\/ wegen Timer aus DecAliveCount und QueryExit\n\n DELETEZ( pAppData_Impl->pTemplates );\n\n DELETEZ(pImp->pTemplateDlg);\n SetViewFrame(0);\n bDowning = FALSE;\n DBG_ASSERT( !SfxViewFrame::GetFirst(),\n \"existing SfxViewFrame after Execute\" );\n DBG_ASSERT( !SfxObjectShell::GetFirst(),\n \"existing SfxObjectShell after Execute\" );\n pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );\n pAppDispat->Flush();\n bDowning = TRUE;\n pAppDispat->DoDeactivate_Impl( TRUE );\n\n INetURLHistory::Delete();\n\n \/\/ call derived application-exit\n bInExit = TRUE;\n Exit();\n\n \/\/ Controller u.\"a. freigeben\n \/\/ dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden\n DELETEZ(pMenuMgr);\n DELETEZ(pAcceleratorMgr);\n SfxObjectFactory::ClearAll_Impl();\n DELETEZ( pImp->pBasicMgr );\n if( pImp->pBasicLibContainer )\n pImp->pBasicLibContainer->release();\n if( pImp->pDialogLibContainer )\n pImp->pDialogLibContainer->release();\n\n bInExit = FALSE;\n\n DBG_ASSERT( pViewFrame == 0, \"active foreign ViewFrame\" );\n\n delete[] pInterfaces, pInterfaces = 0;\n DELETEZ(pImageMgr);\n\n \/\/ free administration managers\n DELETEZ(pImp->pAutoSaveTimer);\n DELETEZ(pAppDispat);\n SfxResId::DeleteResMgr();\n DELETEZ(pImp->pOfaResMgr);\n\n \/\/ ab hier d\"urfen keine SvObjects mehr existieren\n DELETEX(pAppData_Impl->pMatcher);\n DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);\n DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);\n\n delete pAppData_Impl->pLabelResMgr;\n\n#ifndef PRODUCT\n DELETEX(pSlotPool);\n DELETEX(pAppData_Impl->pEventConfig);\n DELETEX(pAppData_Impl->pMiscConfig);\n SfxMacroConfig::Release_Impl();\n DELETEX(pAppData_Impl->pVerbs);\n DELETEX(pAppData_Impl->pFactArr);\n DELETEX(pAppData_Impl->pInitLinkList);\n#endif\n\n#ifndef PRODUCT\n DELETEX(pImp->pTbxCtrlFac);\n DELETEX(pImp->pStbCtrlFac);\n DELETEX(pImp->pMenuCtrlFac);\n DELETEX(pImp->pEventHdl);\n SfxNewHdl::Delete();\n DELETEX(pImp->pAutoSaveTimer);\n DELETEX(pImp->pViewFrames);\n DELETEX(pImp->pViewShells);\n DELETEX(pImp->pObjShells);\n#endif\n\n NoChaos::ReleaseItemPool();\n pAppData_Impl->pPool = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tplcitem.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:14:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _TPLCITEM_HXX\n#define _TPLCITEM_HXX\n\n#include \"ctrlitem.hxx\"\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n\nclass SfxCommonTemplateDialog_Impl;\n\nclass SfxTemplateControllerItem: public SfxControllerItem {\n SfxCommonTemplateDialog_Impl &rTemplateDlg;\n BYTE nWaterCanState;\n long nUserEventId;\n\n DECL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,\n SfxTemplateControllerItem*);\n\nprotected:\n virtual void StateChanged( USHORT, SfxItemState, const SfxPoolItem* pState );\n\npublic:\n SfxTemplateControllerItem( USHORT nId, SfxCommonTemplateDialog_Impl &rDlg, SfxBindings &);\n ~SfxTemplateControllerItem();\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.520); FILE MERGED 2007\/06\/04 13:34:58 vg 1.4.520.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tplcitem.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 23:29:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _TPLCITEM_HXX\n#define _TPLCITEM_HXX\n\n#include <sfx2\/ctrlitem.hxx>\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n\nclass SfxCommonTemplateDialog_Impl;\n\nclass SfxTemplateControllerItem: public SfxControllerItem {\n SfxCommonTemplateDialog_Impl &rTemplateDlg;\n BYTE nWaterCanState;\n long nUserEventId;\n\n DECL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,\n SfxTemplateControllerItem*);\n\nprotected:\n virtual void StateChanged( USHORT, SfxItemState, const SfxPoolItem* pState );\n\npublic:\n SfxTemplateControllerItem( USHORT nId, SfxCommonTemplateDialog_Impl &rDlg, SfxBindings &);\n ~SfxTemplateControllerItem();\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include \"config.h\"\n#include \"slaveunit.h\"\n#include \"common\/filesystem.h\"\n#include \"common\/logger.h\"\n\n\nint main(int argc, const char* argv[])\n{\n\tusing Airwave::FileSystem;\n\n\tloggerInit(HOST_BASENAME);\n\n\tLOG(\"Starting Airwave slave unit %s\", PROJECT_VERSION);\n\n\tif(argc != 3) {\n\t\tLOG(\"Usage: %s <VST plugin path> <control port id>\", argv[0]);\n\t\tloggerFree();\n\t\treturn -1;\n\t}\n\n\tloggerSetSenderId(FileSystem::baseName(argv[1]));\n\n\tAirwave::SlaveUnit slaveUnit;\n\tif(!slaveUnit.initialize(argv[1], atoi(argv[2]))) {\n\t\tLOG(\"Unable to initialize slave unit.\");\n\t\tloggerFree();\n\t\treturn -2;\n\t}\n\n\tLOG(\"Slave unit initialized, starting to process events.\");\n\n\twhile(slaveUnit.processRequest()) {\n\t\tMSG message;\n\n\t\tif(PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {\n\t\t\tTranslateMessage(&message);\n\t\t\tDispatchMessage(&message);\n\t\t}\n\t}\n\n\tLOG(\"Slave unit terminated.\");\n\tloggerFree();\n\treturn 0;\n}\n<commit_msg>Improve window events handling<commit_after>#include <cstdlib>\n#include \"config.h\"\n#include \"slaveunit.h\"\n#include \"common\/filesystem.h\"\n#include \"common\/logger.h\"\n\n\nint main(int argc, const char* argv[])\n{\n\tusing Airwave::FileSystem;\n\n\tloggerInit(HOST_BASENAME);\n\n\tLOG(\"Starting Airwave slave unit %s\", PROJECT_VERSION);\n\n\tif(argc != 3) {\n\t\tLOG(\"Usage: %s <VST plugin path> <control port id>\", argv[0]);\n\t\tloggerFree();\n\t\treturn -1;\n\t}\n\n\tloggerSetSenderId(FileSystem::baseName(argv[1]));\n\n\tAirwave::SlaveUnit slaveUnit;\n\tif(!slaveUnit.initialize(argv[1], atoi(argv[2]))) {\n\t\tLOG(\"Unable to initialize slave unit.\");\n\t\tloggerFree();\n\t\treturn -2;\n\t}\n\n\tLOG(\"Slave unit initialized, starting to process events.\");\n\n\twhile(slaveUnit.processRequest()) {\n\t\tMSG message;\n\n\t\twhile(PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {\n\t\t\tTranslateMessage(&message);\n\t\t\tDispatchMessage(&message);\n\t\t}\n\t}\n\n\tLOG(\"Slave unit terminated.\");\n\tloggerFree();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string> \n#include \"include\/Options.hpp\"\n#include \"include\/Cluster.hpp\"\n\/\/#include \"Driver\/DissectionSolver.hpp\"\nint main(int argc, char *argv[]){\n\n\n std::cout << argv[0] << std::endl;\n Options options;\n int n_subdomOnCluster = 8;\n std::string path2data = \"..\/data\";\n options.set_values(n_subdomOnCluster, path2data);\n\n Cluster cluster(options);\n std::cout << \"----------------- done -----------------\\n\" ;\n return 0;\n}\n<commit_msg>htfeti.cpp: cleaning<commit_after>#include <iostream>\n#include <string> \n#include \"include\/Options.hpp\"\n#include \"include\/Cluster.hpp\"\n\/\/#include \"Driver\/DissectionSolver.hpp\"\nint main(int argc, char *argv[]){\n std::cout << argv[0] << std::endl;\n Options options;\n int n_subdomOnCluster = 8;\n std::string path2data = \"..\/data\";\n options.set_values(n_subdomOnCluster, path2data);\n\n Cluster cluster(options);\n std::cout << \"----------------- done -----------------\\n\" ;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by malek on 3\/20\/18.\n\/\/\n\n#include <cuda_runtime.h>\n#include <cstdint>\n#include <iostream>\n\nusing size_type = uint64_t;\n\nnamespace {\n inline void handle_cuda_error(cudaError_t e)\n {\n if (e != cudaError_t::cudaSuccess)\n {\n std::cerr << cudaGetErrorString(e) << std::endl;\n exit(1);\n }\n\n }\n}\n\nextern \"C\"\nint tiramisu_cuda_memcpy_to_device(void * to, void * from, uint64_t size)\n{\n handle_cuda_error(cudaMemcpy(to, from, size, cudaMemcpyKind::cudaMemcpyHostToDevice));\n return 0;\n}\n\nextern \"C\"\nint tiramisu_cuda_memcpy_to_host(void * to, void * from, uint64_t size)\n{\n handle_cuda_error(cudaMemcpy(to, from, size, cudaMemcpyKind::cudaMemcpyDeviceToHost));\n return 0;\n}\n\nextern \"C\"\nvoid * tiramisu_cuda_malloc(uint64_t size)\n{\n void * result;\n handle_cuda_error(cudaMalloc(&result, size));\n return result;\n}\n\nextern \"C\"\nint tiramisu_cuda_free(void * ptr)\n{\n handle_cuda_error(cudaFree(ptr));\n return 0;\n}\n<commit_msg>more helpful debugging for cuda wrappers<commit_after>\/\/\n\/\/ Created by malek on 3\/20\/18.\n\/\/\n\n#include <cuda_runtime.h>\n#include <cstdint>\n#include <iostream>\n\nusing size_type = uint64_t;\n\nnamespace {\n inline void handle_cuda_error(cudaError_t e, const std::string & function_name)\n {\n if (e != cudaError_t::cudaSuccess)\n {\n std::cerr << \"Error at \" << function_name << \": \" << cudaGetErrorString(e) << std::endl;\n exit(1);\n }\n\n }\n}\n\nextern \"C\"\nint tiramisu_cuda_memcpy_to_device(void * to, void * from, uint64_t size)\n{\n handle_cuda_error(cudaMemcpy(to, from, size, cudaMemcpyKind::cudaMemcpyHostToDevice), __FUNCTION__);\n return 0;\n}\n\nextern \"C\"\nint tiramisu_cuda_memcpy_to_host(void * to, void * from, uint64_t size)\n{\n handle_cuda_error(cudaMemcpy(to, from, size, cudaMemcpyKind::cudaMemcpyDeviceToHost), __FUNCTION__);\n return 0;\n}\n\nextern \"C\"\nvoid * tiramisu_cuda_malloc(uint64_t size)\n{\n void * result;\n handle_cuda_error(cudaMalloc(&result, size), __FUNCTION__);\n return result;\n}\n\nextern \"C\"\nint tiramisu_cuda_free(void * ptr)\n{\n handle_cuda_error(cudaFree(ptr), __FUNCTION__);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014, Andrea Del Prete, LAAS-CNRS\n *\n * This file is part of sot-torque-control.\n * sot-torque-control is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n * sot-torque-control is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details. You should\n * have received a copy of the GNU Lesser General Public License along\n * with sot-torque-control. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n\n#include <pinocchio\/fwd.hpp>\n\n#include <boost\/property_tree\/ptree.hpp>\n\n#include <dynamic-graph\/all-commands.h>\n#include <dynamic-graph\/factory.h>\n#include <sot\/core\/debug.hh>\n#include <sot\/core\/exception-tools.hh>\n#include <sot\/core\/parameter-server.hh>\n\nnamespace dynamicgraph {\nnamespace sot {\nnamespace dynamicgraph = ::dynamicgraph;\nusing namespace dynamicgraph;\nusing namespace dynamicgraph::command;\nusing namespace std;\n\n\/\/ Size to be aligned \"-------------------------------------------------------\"\n#define PROFILE_PWM_DESIRED_COMPUTATION \\\n \"Control manager \"\n#define PROFILE_DYNAMIC_GRAPH_PERIOD \\\n \"Control period \"\n\n#define INPUT_SIGNALS\n#define OUTPUT_SIGNALS\n\n\/\/\/ Define EntityClassName here rather than in the header file\n\/\/\/ so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION.\ntypedef ParameterServer EntityClassName;\n\n\/* --- DG FACTORY ---------------------------------------------------- *\/\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(ParameterServer, \"ParameterServer\");\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- CONSTRUCTION -------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\nParameterServer::ParameterServer(const std::string &name)\n : Entity(name), m_robot_util(RefVoidRobotUtil()), m_initSucceeded(false),\n m_emergency_stop_triggered(false), m_is_first_iter(true), m_iter(0),\n m_sleep_time(0.0) {\n\n \/\/~ Entity::signalRegistration( INPUT_SIGNALS << OUTPUT_SIGNALS);\n\n \/* Commands. *\/\n addCommand(\"init\",\n makeCommandVoid3(*this, &ParameterServer::init,\n docCommandVoid3(\"Initialize the entity.\",\n \"Time period in seconds (double)\",\n \"URDF file path (string)\",\n \"Robot reference (string)\")));\n addCommand(\n \"init_simple\",\n makeCommandVoid1(*this, &ParameterServer::init_simple,\n docCommandVoid1(\"Initialize the entity.\",\n \"Time period in seconds (double)\")));\n\n addCommand(\"setNameToId\",\n makeCommandVoid2(*this, &ParameterServer::setNameToId,\n docCommandVoid2(\"Set map for a name to an Id\",\n \"(string) joint name\",\n \"(double) joint id\")));\n\n addCommand(\n \"setForceNameToForceId\",\n makeCommandVoid2(\n *this, &ParameterServer::setForceNameToForceId,\n docCommandVoid2(\n \"Set map from a force sensor name to a force sensor Id\",\n \"(string) force sensor name\", \"(double) force sensor id\")));\n\n addCommand(\"setJointLimitsFromId\",\n makeCommandVoid3(\n *this, &ParameterServer::setJointLimitsFromId,\n docCommandVoid3(\"Set the joint limits for a given joint ID\",\n \"(double) joint id\", \"(double) lower limit\",\n \"(double) uppper limit\")));\n\n addCommand(\n \"setForceLimitsFromId\",\n makeCommandVoid3(\n *this, &ParameterServer::setForceLimitsFromId,\n docCommandVoid3(\"Set the force limits for a given force sensor ID\",\n \"(double) force sensor id\", \"(double) lower limit\",\n \"(double) uppper limit\")));\n\n addCommand(\n \"setJointsUrdfToSot\",\n makeCommandVoid1(*this, &ParameterServer::setJoints,\n docCommandVoid1(\"Map Joints From URDF to SoT.\",\n \"Vector of integer for mapping\")));\n\n addCommand(\n \"setRightFootSoleXYZ\",\n makeCommandVoid1(*this, &ParameterServer::setRightFootSoleXYZ,\n docCommandVoid1(\"Set the right foot sole 3d position.\",\n \"Vector of 3 doubles\")));\n addCommand(\n \"setRightFootForceSensorXYZ\",\n makeCommandVoid1(*this, &ParameterServer::setRightFootForceSensorXYZ,\n docCommandVoid1(\"Set the right foot sensor 3d position.\",\n \"Vector of 3 doubles\")));\n\n addCommand(\"setFootFrameName\",\n makeCommandVoid2(\n *this, &ParameterServer::setFootFrameName,\n docCommandVoid2(\"Set the Frame Name for the Foot Name.\",\n \"(string) Foot name\", \"(string) Frame name\")));\n addCommand(\"setHandFrameName\",\n makeCommandVoid2(\n *this, &ParameterServer::setHandFrameName,\n docCommandVoid2(\"Set the Frame Name for the Hand Name.\",\n \"(string) Hand name\", \"(string) Frame name\")));\n addCommand(\"setImuJointName\",\n makeCommandVoid1(\n *this, &ParameterServer::setImuJointName,\n docCommandVoid1(\"Set the Joint Name wich IMU is attached to.\",\n \"(string) Joint name\")));\n addCommand(\"displayRobotUtil\",\n makeCommandVoid0(\n *this, &ParameterServer::displayRobotUtil,\n docCommandVoid0(\"Display the current robot util data set.\")));\n\n addCommand(\n \"setParameterBool\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<bool>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\", \"(bool) ParameterValue\")));\n addCommand(\n \"setParameterInt\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<int>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\", \"(int) ParameterValue\")));\n addCommand(\"setParameterDbl\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<double>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\",\n \"(double) ParameterValue\")));\n\n addCommand(\"setParameter\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<std::string>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\",\n \"(string) ParameterValue\")));\n\n addCommand(\n \"getParameter\",\n makeCommandReturnType1(*this, &ParameterServer::getParameter<std::string>,\n docCommandReturnType1<std::string>(\n \"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(string) ParameterName\")));\n\n addCommand(\n \"getParameterInt\",\n makeCommandReturnType1(\n *this, &ParameterServer::getParameter<int>,\n docCommandReturnType1<int>(\"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(int) ParameterName\")));\n\n addCommand(\n \"getParameterDbl\",\n makeCommandReturnType1(*this, &ParameterServer::getParameter<double>,\n docCommandReturnType1<double>(\n \"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(double) ParameterName\")));\n\n addCommand(\n \"getParameterBool\",\n makeCommandReturnType1(\n *this, &ParameterServer::getParameter<bool>,\n docCommandReturnType1<bool>(\"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(string) ParameterName\")));\n}\n\nvoid ParameterServer::init_simple(const double &dt) {\n\n if (dt <= 0.0)\n return SEND_MSG(\"Timestep must be positive\", MSG_TYPE_ERROR);\n\n m_dt = dt;\n\n m_emergency_stop_triggered = false;\n m_initSucceeded = true;\n\n std::string localName(\"robot\");\n std::shared_ptr<std::vector<std::string> > listOfRobots =\n sot::getListOfRobots();\n\n if (listOfRobots->size() == 1)\n localName = (*listOfRobots)[0];\n else {\n std::ostringstream oss;\n oss << \"No robot registered in the parameter server list\";\n oss << \" listOfRobots->size: \" << listOfRobots->size();\n throw ExceptionTools(ExceptionTools::ErrorCodeEnum::PARAMETER_SERVER,\n oss.str());\n }\n\n if (!isNameInRobotUtil(localName)) {\n m_robot_util = createRobotUtil(localName);\n } else {\n m_robot_util = getRobotUtil(localName);\n }\n\n addCommand(\n \"getJointsUrdfToSot\",\n makeDirectGetter(*this, &m_robot_util->m_dgv_urdf_to_sot,\n docDirectSetter(\"Display map Joints From URDF to SoT.\",\n \"Vector of integer for mapping\")));\n}\n\nvoid ParameterServer::init(const double &dt, const std::string &urdfFile,\n const std::string &robotRef) {\n if (dt <= 0.0)\n return SEND_MSG(\"Timestep must be positive\", MSG_TYPE_ERROR);\n m_dt = dt;\n m_emergency_stop_triggered = false;\n m_initSucceeded = true;\n\n std::string localName(robotRef);\n if (!isNameInRobotUtil(localName)) {\n m_robot_util = createRobotUtil(localName);\n } else {\n m_robot_util = getRobotUtil(localName);\n }\n\n m_robot_util->m_urdf_filename = urdfFile;\n}\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- SIGNALS ------------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\n\n\/* --- COMMANDS ---------------------------------------------------------- *\/\n\nvoid ParameterServer::setNameToId(const std::string &jointName,\n const double &jointId) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set joint name from joint id before initialization!\");\n return;\n }\n m_robot_util->set_name_to_id(jointName, static_cast<Index>(jointId));\n}\n\nvoid ParameterServer::setJointLimitsFromId(const double &jointId,\n const double &lq, const double &uq) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set joints limits from joint id before initialization!\");\n return;\n }\n\n m_robot_util->set_joint_limits_for_id((Index)jointId, lq, uq);\n}\n\nvoid ParameterServer::setForceLimitsFromId(const double &jointId,\n const dynamicgraph::Vector &lq,\n const dynamicgraph::Vector &uq) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set force limits from force id before initialization!\");\n return;\n }\n\n m_robot_util->m_force_util.set_force_id_to_limits((Index)jointId, lq, uq);\n}\n\nvoid ParameterServer::setForceNameToForceId(const std::string &forceName,\n const double &forceId) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set force sensor name from force sensor id \"\n \" before initialization!\");\n return;\n }\n\n m_robot_util->m_force_util.set_name_to_force_id(forceName,\n static_cast<Index>(forceId));\n}\n\nvoid ParameterServer::setJoints(const dynamicgraph::Vector &urdf_to_sot) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set mapping to sot before initialization!\");\n return;\n }\n m_robot_util->set_urdf_to_sot(urdf_to_sot);\n}\n\nvoid ParameterServer::setRightFootSoleXYZ(const dynamicgraph::Vector &xyz) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set right foot sole XYZ before initialization!\");\n return;\n }\n\n m_robot_util->m_foot_util.m_Right_Foot_Sole_XYZ = xyz;\n}\n\nvoid ParameterServer::setRightFootForceSensorXYZ(\n const dynamicgraph::Vector &xyz) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set right foot force sensor XYZ before initialization!\");\n return;\n }\n\n m_robot_util->m_foot_util.m_Right_Foot_Force_Sensor_XYZ = xyz;\n}\n\nvoid ParameterServer::setFootFrameName(const std::string &FootName,\n const std::string &FrameName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set foot frame name!\");\n return;\n }\n if (FootName == \"Left\")\n m_robot_util->m_foot_util.m_Left_Foot_Frame_Name = FrameName;\n else if (FootName == \"Right\")\n m_robot_util->m_foot_util.m_Right_Foot_Frame_Name = FrameName;\n else\n SEND_WARNING_STREAM_MSG(\"Did not understand the foot name !\" + FootName);\n}\n\nvoid ParameterServer::setHandFrameName(const std::string& HandName, const std::string& FrameName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set hand frame name!\");\n return;\n }\n if (HandName == \"Left\")\n m_robot_util->m_hand_util.m_Left_Hand_Frame_Name = FrameName;\n else if (HandName == \"Right\")\n m_robot_util->m_hand_util.m_Right_Hand_Frame_Name = FrameName;\n else\n SEND_WARNING_STREAM_MSG(\"Did not understand the hand name !\" + HandName);\n}\n\nvoid ParameterServer::setImuJointName(const std::string &JointName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set IMU joint name!\");\n return;\n }\n m_robot_util->m_imu_joint_name = JointName;\n}\n\nvoid ParameterServer::displayRobotUtil() { m_robot_util->display(std::cout); }\n\n\/* --- PROTECTED MEMBER METHODS\n * ---------------------------------------------------------- *\/\n\nbool ParameterServer::convertJointNameToJointId(const std::string &name,\n unsigned int &id) {\n \/\/ Check if the joint name exists\n sot::Index jid = m_robot_util->get_id_from_name(name);\n if (jid < 0) {\n SEND_MSG(\"The specified joint name does not exist: \" + name,\n MSG_TYPE_ERROR);\n std::stringstream ss;\n for (long unsigned int it = 0; it < m_robot_util->m_nbJoints; it++)\n ss << m_robot_util->get_name_from_id(it) << \", \";\n SEND_MSG(\"Possible joint names are: \" + ss.str(), MSG_TYPE_INFO);\n return false;\n }\n id = (unsigned int)jid;\n return true;\n}\n\nbool ParameterServer::isJointInRange(unsigned int id, double q) {\n const JointLimits &JL = m_robot_util->get_joint_limits_from_id((Index)id);\n\n double jl = JL.lower;\n if (q < jl) {\n SEND_MSG(\"Desired joint angle \" + toString(q) +\n \" is smaller than lower limit: \" + toString(jl),\n MSG_TYPE_ERROR);\n return false;\n }\n double ju = JL.upper;\n if (q > ju) {\n SEND_MSG(\"Desired joint angle \" + toString(q) +\n \" is larger than upper limit: \" + toString(ju),\n MSG_TYPE_ERROR);\n return false;\n }\n return true;\n}\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- ENTITY -------------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\n\nvoid ParameterServer::display(std::ostream &os) const {\n os << \"ParameterServer \" << getName();\n}\n} \/\/ namespace sot\n} \/\/ namespace dynamicgraph\n<commit_msg>Update src\/tools\/parameter-server.cpp<commit_after>\/*\n * Copyright 2014, Andrea Del Prete, LAAS-CNRS\n *\n * This file is part of sot-torque-control.\n * sot-torque-control is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n * sot-torque-control is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details. You should\n * have received a copy of the GNU Lesser General Public License along\n * with sot-torque-control. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n\n#include <pinocchio\/fwd.hpp>\n\n#include <boost\/property_tree\/ptree.hpp>\n\n#include <dynamic-graph\/all-commands.h>\n#include <dynamic-graph\/factory.h>\n#include <sot\/core\/debug.hh>\n#include <sot\/core\/exception-tools.hh>\n#include <sot\/core\/parameter-server.hh>\n\nnamespace dynamicgraph {\nnamespace sot {\nnamespace dynamicgraph = ::dynamicgraph;\nusing namespace dynamicgraph;\nusing namespace dynamicgraph::command;\nusing namespace std;\n\n\/\/ Size to be aligned \"-------------------------------------------------------\"\n#define PROFILE_PWM_DESIRED_COMPUTATION \\\n \"Control manager \"\n#define PROFILE_DYNAMIC_GRAPH_PERIOD \\\n \"Control period \"\n\n#define INPUT_SIGNALS\n#define OUTPUT_SIGNALS\n\n\/\/\/ Define EntityClassName here rather than in the header file\n\/\/\/ so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION.\ntypedef ParameterServer EntityClassName;\n\n\/* --- DG FACTORY ---------------------------------------------------- *\/\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(ParameterServer, \"ParameterServer\");\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- CONSTRUCTION -------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\nParameterServer::ParameterServer(const std::string &name)\n : Entity(name), m_robot_util(RefVoidRobotUtil()), m_initSucceeded(false),\n m_emergency_stop_triggered(false), m_is_first_iter(true), m_iter(0),\n m_sleep_time(0.0) {\n\n \/\/~ Entity::signalRegistration( INPUT_SIGNALS << OUTPUT_SIGNALS);\n\n \/* Commands. *\/\n addCommand(\"init\",\n makeCommandVoid3(*this, &ParameterServer::init,\n docCommandVoid3(\"Initialize the entity.\",\n \"Time period in seconds (double)\",\n \"URDF file path (string)\",\n \"Robot reference (string)\")));\n addCommand(\n \"init_simple\",\n makeCommandVoid1(*this, &ParameterServer::init_simple,\n docCommandVoid1(\"Initialize the entity.\",\n \"Time period in seconds (double)\")));\n\n addCommand(\"setNameToId\",\n makeCommandVoid2(*this, &ParameterServer::setNameToId,\n docCommandVoid2(\"Set map for a name to an Id\",\n \"(string) joint name\",\n \"(double) joint id\")));\n\n addCommand(\n \"setForceNameToForceId\",\n makeCommandVoid2(\n *this, &ParameterServer::setForceNameToForceId,\n docCommandVoid2(\n \"Set map from a force sensor name to a force sensor Id\",\n \"(string) force sensor name\", \"(double) force sensor id\")));\n\n addCommand(\"setJointLimitsFromId\",\n makeCommandVoid3(\n *this, &ParameterServer::setJointLimitsFromId,\n docCommandVoid3(\"Set the joint limits for a given joint ID\",\n \"(double) joint id\", \"(double) lower limit\",\n \"(double) uppper limit\")));\n\n addCommand(\n \"setForceLimitsFromId\",\n makeCommandVoid3(\n *this, &ParameterServer::setForceLimitsFromId,\n docCommandVoid3(\"Set the force limits for a given force sensor ID\",\n \"(double) force sensor id\", \"(double) lower limit\",\n \"(double) uppper limit\")));\n\n addCommand(\n \"setJointsUrdfToSot\",\n makeCommandVoid1(*this, &ParameterServer::setJoints,\n docCommandVoid1(\"Map Joints From URDF to SoT.\",\n \"Vector of integer for mapping\")));\n\n addCommand(\n \"setRightFootSoleXYZ\",\n makeCommandVoid1(*this, &ParameterServer::setRightFootSoleXYZ,\n docCommandVoid1(\"Set the right foot sole 3d position.\",\n \"Vector of 3 doubles\")));\n addCommand(\n \"setRightFootForceSensorXYZ\",\n makeCommandVoid1(*this, &ParameterServer::setRightFootForceSensorXYZ,\n docCommandVoid1(\"Set the right foot sensor 3d position.\",\n \"Vector of 3 doubles\")));\n\n addCommand(\"setFootFrameName\",\n makeCommandVoid2(\n *this, &ParameterServer::setFootFrameName,\n docCommandVoid2(\"Set the Frame Name for the Foot Name.\",\n \"(string) Foot name\", \"(string) Frame name\")));\n addCommand(\"setHandFrameName\",\n makeCommandVoid2(\n *this, &ParameterServer::setHandFrameName,\n docCommandVoid2(\"Set the Frame Name for the Hand Name.\",\n \"(string) Hand name\", \"(string) Frame name\")));\n addCommand(\"setImuJointName\",\n makeCommandVoid1(\n *this, &ParameterServer::setImuJointName,\n docCommandVoid1(\"Set the Joint Name wich IMU is attached to.\",\n \"(string) Joint name\")));\n addCommand(\"displayRobotUtil\",\n makeCommandVoid0(\n *this, &ParameterServer::displayRobotUtil,\n docCommandVoid0(\"Display the current robot util data set.\")));\n\n addCommand(\n \"setParameterBool\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<bool>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\", \"(bool) ParameterValue\")));\n addCommand(\n \"setParameterInt\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<int>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\", \"(int) ParameterValue\")));\n addCommand(\"setParameterDbl\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<double>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\",\n \"(double) ParameterValue\")));\n\n addCommand(\"setParameter\",\n makeCommandVoid2(\n *this, &ParameterServer::setParameter<std::string>,\n docCommandVoid2(\"Set a parameter named ParameterName to value \"\n \"ParameterValue (string format).\",\n \"(string) ParameterName\",\n \"(string) ParameterValue\")));\n\n addCommand(\n \"getParameter\",\n makeCommandReturnType1(*this, &ParameterServer::getParameter<std::string>,\n docCommandReturnType1<std::string>(\n \"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(string) ParameterName\")));\n\n addCommand(\n \"getParameterInt\",\n makeCommandReturnType1(\n *this, &ParameterServer::getParameter<int>,\n docCommandReturnType1<int>(\"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(int) ParameterName\")));\n\n addCommand(\n \"getParameterDbl\",\n makeCommandReturnType1(*this, &ParameterServer::getParameter<double>,\n docCommandReturnType1<double>(\n \"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(double) ParameterName\")));\n\n addCommand(\n \"getParameterBool\",\n makeCommandReturnType1(\n *this, &ParameterServer::getParameter<bool>,\n docCommandReturnType1<bool>(\"Return the parameter value for parameter\"\n \" named ParameterName.\",\n \"(string) ParameterName\")));\n}\n\nvoid ParameterServer::init_simple(const double &dt) {\n\n if (dt <= 0.0)\n return SEND_MSG(\"Timestep must be positive\", MSG_TYPE_ERROR);\n\n m_dt = dt;\n\n m_emergency_stop_triggered = false;\n m_initSucceeded = true;\n\n std::string localName(\"robot\");\n std::shared_ptr<std::vector<std::string> > listOfRobots =\n sot::getListOfRobots();\n\n if (listOfRobots->size() == 1)\n localName = (*listOfRobots)[0];\n else {\n std::ostringstream oss;\n oss << \"No robot registered in the parameter server list\";\n oss << \" listOfRobots->size: \" << listOfRobots->size();\n throw ExceptionTools(ExceptionTools::ErrorCodeEnum::PARAMETER_SERVER,\n oss.str());\n }\n\n if (!isNameInRobotUtil(localName)) {\n m_robot_util = createRobotUtil(localName);\n } else {\n m_robot_util = getRobotUtil(localName);\n }\n\n addCommand(\n \"getJointsUrdfToSot\",\n makeDirectGetter(*this, &m_robot_util->m_dgv_urdf_to_sot,\n docDirectSetter(\"Display map Joints From URDF to SoT.\",\n \"Vector of integer for mapping\")));\n}\n\nvoid ParameterServer::init(const double &dt, const std::string &urdfFile,\n const std::string &robotRef) {\n if (dt <= 0.0)\n return SEND_MSG(\"Timestep must be positive\", MSG_TYPE_ERROR);\n m_dt = dt;\n m_emergency_stop_triggered = false;\n m_initSucceeded = true;\n\n std::string localName(robotRef);\n if (!isNameInRobotUtil(localName)) {\n m_robot_util = createRobotUtil(localName);\n } else {\n m_robot_util = getRobotUtil(localName);\n }\n\n m_robot_util->m_urdf_filename = urdfFile;\n}\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- SIGNALS ------------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\n\n\/* --- COMMANDS ---------------------------------------------------------- *\/\n\nvoid ParameterServer::setNameToId(const std::string &jointName,\n const double &jointId) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set joint name from joint id before initialization!\");\n return;\n }\n m_robot_util->set_name_to_id(jointName, static_cast<Index>(jointId));\n}\n\nvoid ParameterServer::setJointLimitsFromId(const double &jointId,\n const double &lq, const double &uq) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set joints limits from joint id before initialization!\");\n return;\n }\n\n m_robot_util->set_joint_limits_for_id((Index)jointId, lq, uq);\n}\n\nvoid ParameterServer::setForceLimitsFromId(const double &jointId,\n const dynamicgraph::Vector &lq,\n const dynamicgraph::Vector &uq) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set force limits from force id before initialization!\");\n return;\n }\n\n m_robot_util->m_force_util.set_force_id_to_limits((Index)jointId, lq, uq);\n}\n\nvoid ParameterServer::setForceNameToForceId(const std::string &forceName,\n const double &forceId) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set force sensor name from force sensor id \"\n \" before initialization!\");\n return;\n }\n\n m_robot_util->m_force_util.set_name_to_force_id(forceName,\n static_cast<Index>(forceId));\n}\n\nvoid ParameterServer::setJoints(const dynamicgraph::Vector &urdf_to_sot) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set mapping to sot before initialization!\");\n return;\n }\n m_robot_util->set_urdf_to_sot(urdf_to_sot);\n}\n\nvoid ParameterServer::setRightFootSoleXYZ(const dynamicgraph::Vector &xyz) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set right foot sole XYZ before initialization!\");\n return;\n }\n\n m_robot_util->m_foot_util.m_Right_Foot_Sole_XYZ = xyz;\n}\n\nvoid ParameterServer::setRightFootForceSensorXYZ(\n const dynamicgraph::Vector &xyz) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\n \"Cannot set right foot force sensor XYZ before initialization!\");\n return;\n }\n\n m_robot_util->m_foot_util.m_Right_Foot_Force_Sensor_XYZ = xyz;\n}\n\nvoid ParameterServer::setFootFrameName(const std::string &FootName,\n const std::string &FrameName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set foot frame name!\");\n return;\n }\n if (FootName == \"Left\")\n m_robot_util->m_foot_util.m_Left_Foot_Frame_Name = FrameName;\n else if (FootName == \"Right\")\n m_robot_util->m_foot_util.m_Right_Foot_Frame_Name = FrameName;\n else\n SEND_WARNING_STREAM_MSG(\"Did not understand the foot name !\" + FootName);\n}\n\nvoid ParameterServer::setHandFrameName(const std::string& HandName, const std::string& FrameName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set hand frame name!\");\n return;\n }\n if (HandName == \"Left\")\n m_robot_util->m_hand_util.m_Left_Hand_Frame_Name = FrameName;\n else if (HandName == \"Right\")\n m_robot_util->m_hand_util.m_Right_Hand_Frame_Name = FrameName;\n else\n SEND_WARNING_STREAM_MSG(\"Available hand names are 'Left' and 'Right', not '\" + HandName + \"' !\");\n}\n\nvoid ParameterServer::setImuJointName(const std::string &JointName) {\n if (!m_initSucceeded) {\n SEND_WARNING_STREAM_MSG(\"Cannot set IMU joint name!\");\n return;\n }\n m_robot_util->m_imu_joint_name = JointName;\n}\n\nvoid ParameterServer::displayRobotUtil() { m_robot_util->display(std::cout); }\n\n\/* --- PROTECTED MEMBER METHODS\n * ---------------------------------------------------------- *\/\n\nbool ParameterServer::convertJointNameToJointId(const std::string &name,\n unsigned int &id) {\n \/\/ Check if the joint name exists\n sot::Index jid = m_robot_util->get_id_from_name(name);\n if (jid < 0) {\n SEND_MSG(\"The specified joint name does not exist: \" + name,\n MSG_TYPE_ERROR);\n std::stringstream ss;\n for (long unsigned int it = 0; it < m_robot_util->m_nbJoints; it++)\n ss << m_robot_util->get_name_from_id(it) << \", \";\n SEND_MSG(\"Possible joint names are: \" + ss.str(), MSG_TYPE_INFO);\n return false;\n }\n id = (unsigned int)jid;\n return true;\n}\n\nbool ParameterServer::isJointInRange(unsigned int id, double q) {\n const JointLimits &JL = m_robot_util->get_joint_limits_from_id((Index)id);\n\n double jl = JL.lower;\n if (q < jl) {\n SEND_MSG(\"Desired joint angle \" + toString(q) +\n \" is smaller than lower limit: \" + toString(jl),\n MSG_TYPE_ERROR);\n return false;\n }\n double ju = JL.upper;\n if (q > ju) {\n SEND_MSG(\"Desired joint angle \" + toString(q) +\n \" is larger than upper limit: \" + toString(ju),\n MSG_TYPE_ERROR);\n return false;\n }\n return true;\n}\n\n\/* ------------------------------------------------------------------- *\/\n\/* --- ENTITY -------------------------------------------------------- *\/\n\/* ------------------------------------------------------------------- *\/\n\nvoid ParameterServer::display(std::ostream &os) const {\n os << \"ParameterServer \" << getName();\n}\n} \/\/ namespace sot\n} \/\/ namespace dynamicgraph\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <vector>\n\n#include \"unittest\/gtest.hpp\"\n\n#include \"btree\/node.hpp\"\n#include \"btree\/leaf_node.hpp\"\n\nnamespace unittest {\n\n\/\/ TODO: This is rather duplicative of fsck::check_value.\nvoid expect_valid_value_shallowly(const btree_value *value) {\n EXPECT_TRUE(!(value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)));\n\n size_t size = value->value_size();\n\n if (value->is_large()) {\n EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE);\n\n \/\/ This isn't fsck, we can't follow large buf pointers.\n } else {\n EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE);\n }\n}\n\n\/\/ TODO: This is rather duplicative of fsck::check_subtree_leaf_node.\nvoid verify(block_size_t block_size, const leaf_node_t *buf) {\n\n ASSERT_LE(offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2, buf->frontmost_offset);\n ASSERT_LE(buf->frontmost_offset, block_size.value());\n\n std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs);\n std::sort(offsets.begin(), offsets.end());\n\n uint16_t expected = buf->frontmost_offset;\n for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) {\n ASSERT_LE(expected, block_size.value());\n ASSERT_EQ(expected, *p);\n expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p));\n }\n ASSERT_EQ(block_size.value(), expected);\n\n const btree_key *last_key = NULL;\n for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) {\n const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p);\n if (last_key != NULL) {\n const btree_key *next_key = &pair->key;\n EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0);\n last_key = next_key;\n }\n expect_valid_value_shallowly(pair->value());\n }\n}\n\nTEST(LeafNodeTest, Offsets) {\n \/\/ Check leaf_node_t.\n EXPECT_EQ(0, offsetof(leaf_node_t, magic));\n EXPECT_EQ(4, offsetof(leaf_node_t, times));\n EXPECT_EQ(12, offsetof(leaf_node_t, npairs));\n EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset));\n EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets));\n EXPECT_EQ(16, sizeof(leaf_node_t));\n\n\n \/\/ Check leaf_timestamps_t, since that's specifically part of leaf_node_t.\n EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified));\n EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier));\n\n \/\/ Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format.\n EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES);\n\n EXPECT_EQ(8, sizeof(leaf_timestamps_t));\n\n\n \/\/ Check btree_leaf_pair.\n EXPECT_EQ(0, offsetof(btree_leaf_pair, key));\n\n btree_leaf_pair p;\n p.key.size = 173;\n EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p));\n}\n\nclass Value {\npublic:\n Value(const std::string& data = \"\", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0)\n : mcflags_(mcflags), cas_(cas), exptime_(exptime),\n has_cas_(has_cas)\n data_(data) { }\n\n void WriteBtreeValue(btree_value *out) const {\n out->size = 0;\n ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);\n out->value_size(data_.size());\n out->set_mcflags(mcflags_);\n out->set_exptime(exptime_);\n if (has_cas_) {\n out->set_cas(cas_);\n }\n }\n\n static Value Make(const btree_value *v) {\n ASSERT_FALSE(v->is_large());\n return Value(std::string(v->value(), v->value() + v->value_size()),\n v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime());\n }\n\n bool operator==(const Value& rhs) {\n return mcflags_ == rhs.mcflags_\n && exptime_ == rhs.exptime_\n && data_ == rhs.data_\n && has_cas_ == rhs.has_cas_\n && (has_cas_ ? cas_ == rhs.cas_ : true);\n }\n\nprivate:\n mcflags_t mcflags_;\n cas_t cas_;\n exptime_t exptime_;\n bool has_cas_;\n std::string data_;\n};\n\ntemplate <int block_size>\nclass LeafNodeGrinder {\n typedef std::map<std::string, Value> expected_t;\n expected_t expected;\n leaf_node_t *node;\n\n void insert(const std::string& k, const Value& v) {\n std::pair<expected_t::iterator, bool> res = expected.insert(k, v);\n if (!res.second) {\n res.first->second = v;\n }\n\n \n\n\n }\n\n\n\n};\n\n\n\n\n\nblock_size_t make_bs() {\n \/\/ TODO: Test weird block sizes.\n return block_size_t::unsafe_make(4096);\n}\n\nleaf_node_t *malloc_leaf_node(block_size_t bs) {\n return reinterpret_cast<leaf_node_t *>(malloc(bs.value()));\n}\n\nbtree_key *malloc_key(const char *s) {\n size_t origlen = strlen(s);\n EXPECT_LE(origlen, MAX_KEY_SIZE);\n\n size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE);\n btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len));\n k->size = len;\n memcpy(k->contents, s, len);\n return k;\n}\n\nbtree_value *malloc_value(const char *s) {\n size_t origlen = strlen(s);\n EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE);\n\n size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE);\n\n btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len));\n v->size = len;\n v->metadata_flags = 0;\n memcpy(v->value(), s, len);\n return v;\n}\n\nTEST(LeafNodeTest, Initialization) {\n block_size_t bs = make_bs();\n leaf_node_t *node = malloc_leaf_node(bs);\n\n leaf_node_handler::init(bs, node, repli_timestamp::invalid);\n verify(bs, node);\n free(node);\n}\n\n\/\/ Runs an InsertLookupRemove test with key and value.\nvoid InsertLookupRemoveHelper(const char *key, const char *value) {\n block_size_t bs = make_bs();\n leaf_node_t *node = malloc_leaf_node(bs);\n\n leaf_node_handler::init(bs, node, repli_timestamp::invalid);\n verify(bs, node);\n\n btree_key *k = malloc_key(key);\n btree_value *v = malloc_value(value);\n\n ASSERT_TRUE(leaf_node_handler::insert(bs, node, k, v, repli_timestamp::invalid));\n verify(bs, node);\n ASSERT_EQ(1, node->npairs);\n\n union {\n byte readval_padding[MAX_TOTAL_NODE_CONTENTS_SIZE + sizeof(btree_value)];\n btree_value readval;\n };\n\n (void)readval_padding;\n\n ASSERT_TRUE(leaf_node_handler::lookup(node, k, &readval));\n\n ASSERT_EQ(0, memcmp(v, &readval, v->full_size()));\n\n leaf_node_handler::remove(bs, node, k);\n verify(bs, node);\n ASSERT_EQ(0, node->npairs);\n\n free(k);\n free(v);\n free(node);\n}\n\nTEST(LeafNodeTest, ElementaryInsertLookupRemove) {\n InsertLookupRemoveHelper(\"the_key\", \"the_value\");\n}\nTEST(LeafNodeTest, EmptyValueInsertLookupRemove) {\n InsertLookupRemoveHelper(\"the_key\", \"\");\n}\nTEST(LeafNodeTest, EmptyKeyInsertLookupRemove) {\n InsertLookupRemoveHelper(\"\", \"the_value\");\n}\nTEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) {\n InsertLookupRemoveHelper(\"\", \"\");\n}\n\n\n} \/\/ namespace unittest\n\n<commit_msg>Some more changes to leaf_node_test.cc<commit_after>#include <algorithm>\n#include <vector>\n\n#include \"unittest\/gtest.hpp\"\n\n#include \"btree\/node.hpp\"\n#include \"btree\/leaf_node.hpp\"\n\nnamespace unittest {\n\n\/\/ TODO: This is rather duplicative of fsck::check_value.\nvoid expect_valid_value_shallowly(const btree_value *value) {\n EXPECT_TRUE(!(value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)));\n\n size_t size = value->value_size();\n\n if (value->is_large()) {\n EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE);\n\n \/\/ This isn't fsck, we can't follow large buf pointers.\n } else {\n EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE);\n }\n}\n\n\/\/ TODO: This is rather duplicative of fsck::check_subtree_leaf_node.\nvoid verify(block_size_t block_size, const leaf_node_t *buf) {\n\n ASSERT_LE(offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2, buf->frontmost_offset);\n ASSERT_LE(buf->frontmost_offset, block_size.value());\n\n std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs);\n std::sort(offsets.begin(), offsets.end());\n\n uint16_t expected = buf->frontmost_offset;\n for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) {\n ASSERT_LE(expected, block_size.value());\n ASSERT_EQ(expected, *p);\n expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p));\n }\n ASSERT_EQ(block_size.value(), expected);\n\n const btree_key *last_key = NULL;\n for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) {\n const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p);\n if (last_key != NULL) {\n const btree_key *next_key = &pair->key;\n EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0);\n last_key = next_key;\n }\n expect_valid_value_shallowly(pair->value());\n }\n}\n\nTEST(LeafNodeTest, Offsets) {\n \/\/ Check leaf_node_t.\n EXPECT_EQ(0, offsetof(leaf_node_t, magic));\n EXPECT_EQ(4, offsetof(leaf_node_t, times));\n EXPECT_EQ(12, offsetof(leaf_node_t, npairs));\n EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset));\n EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets));\n EXPECT_EQ(16, sizeof(leaf_node_t));\n\n\n \/\/ Check leaf_timestamps_t, since that's specifically part of leaf_node_t.\n EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified));\n EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier));\n\n \/\/ Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format.\n EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES);\n\n EXPECT_EQ(8, sizeof(leaf_timestamps_t));\n\n\n \/\/ Check btree_leaf_pair.\n EXPECT_EQ(0, offsetof(btree_leaf_pair, key));\n\n btree_leaf_pair p;\n p.key.size = 173;\n EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p));\n}\n\nclass Value {\npublic:\n Value(const std::string& data = \"\", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0)\n : mcflags_(mcflags), cas_(cas), exptime_(exptime),\n has_cas_(has_cas)\n data_(data) {\n ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);\n }\n\n void WriteBtreeValue(btree_value *out) const {\n out->size = 0;\n ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);\n out->value_size(data_.size());\n out->set_mcflags(mcflags_);\n out->set_exptime(exptime_);\n if (has_cas_) {\n out->set_cas(cas_);\n }\n }\n\n static Value Make(const btree_value *v) {\n ASSERT_FALSE(v->is_large());\n return Value(std::string(v->value(), v->value() + v->value_size()),\n v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime());\n }\n\n bool operator==(const Value& rhs) {\n return mcflags_ == rhs.mcflags_\n && exptime_ == rhs.exptime_\n && data_ == rhs.data_\n && has_cas_ == rhs.has_cas_\n && (has_cas_ ? cas_ == rhs.cas_ : true);\n }\n\n int full_size() const {\n return sizeof(btree_value) + (mcflags_ ? sizeof(mcflags_t) : 0) + (has_cas_ ? sizeof(cas_t) : 0)\n + (exptime_ ? sizeof(exptime_t) : 0) + data_.size();\n }\n\nprivate:\n mcflags_t mcflags_;\n cas_t cas_;\n exptime_t exptime_;\n bool has_cas_;\n std::string data_;\n};\n\nclass StackKey {\npublic:\n explicit StackKey(const std::string& key) {\n ASSERT_LE(key.size(), MAX_KEY_SIZE);\n keyval.size = key.size();\n memcpy(keyval.contents, key.c_str(), key.size());\n }\n\n const btree_key *look() const {\n return &keyval;\n }\n\nprivate:\n union {\n byte keyval_padding[sizeof(btree_key) + MAX_KEY_SIZE];\n btree_key keyval;\n };\n};\n\nclass StackValue {\npublic:\n explicit StackValue(const Value& value) {\n value.WriteBtreeValue(&val);\n }\n const btree_value *look() const {\n return &val;\n }\nprivate:\n union {\n byte val_padding[sizeof(btree_value) + MAX_TOTAL_NODE_CONTENTS_SIZE];\n btree_value val;\n };\n};\n\ntemplate <int block_size>\nclass LeafNodeGrinder {\n block_size_t bs;\n typedef std::map<std::string, Value> expected_t;\n expected_t expected;\n int expected_free_space;\n leaf_node_t *node;\n\n void insert(const std::string& k, const Value& v) {\n if (expected_free_space < sizeof(*node->pair_offsets) + v.full_size()) {\n StackKey skey(k);\n StackValue sval(v);\n ASSERT_FALSE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid));\n verify(bs, node, expected_free_space);\n }\n\n std::pair<expected_t::iterator, bool> res = expected.insert(k, v);\n if (res.second) {\n \/\/ The key didn't previously exist.\n expected_free_space -= v.full_size() + sizeof(*node->pair_offsets);\n } else {\n \/\/ The key previously existed.\n expected_free_space += res.first->second.full_size();\n expected_free_space -= v.full_size();\n res.first->second = v;\n }\n\n verify(bs, node, expected_free_space);\n }\n\n void remove(const std::string& k) {\n expected_t::iterator p = expected.find(k);\n if (p != expected.end()) {\n \n\n\n }\n\n }\n\n\n\n};\n\n\n\n\n\nblock_size_t make_bs() {\n \/\/ TODO: Test weird block sizes.\n return block_size_t::unsafe_make(4096);\n}\n\nleaf_node_t *malloc_leaf_node(block_size_t bs) {\n return reinterpret_cast<leaf_node_t *>(malloc(bs.value()));\n}\n\nbtree_key *malloc_key(const char *s) {\n size_t origlen = strlen(s);\n EXPECT_LE(origlen, MAX_KEY_SIZE);\n\n size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE);\n btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len));\n k->size = len;\n memcpy(k->contents, s, len);\n return k;\n}\n\nbtree_value *malloc_value(const char *s) {\n size_t origlen = strlen(s);\n EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE);\n\n size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE);\n\n btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len));\n v->size = len;\n v->metadata_flags = 0;\n memcpy(v->value(), s, len);\n return v;\n}\n\nTEST(LeafNodeTest, Initialization) {\n block_size_t bs = make_bs();\n leaf_node_t *node = malloc_leaf_node(bs);\n\n leaf_node_handler::init(bs, node, repli_timestamp::invalid);\n verify(bs, node);\n free(node);\n}\n\n\/\/ Runs an InsertLookupRemove test with key and value.\nvoid InsertLookupRemoveHelper(const char *key, const char *value) {\n block_size_t bs = make_bs();\n leaf_node_t *node = malloc_leaf_node(bs);\n\n leaf_node_handler::init(bs, node, repli_timestamp::invalid);\n verify(bs, node);\n\n btree_key *k = malloc_key(key);\n btree_value *v = malloc_value(value);\n\n ASSERT_TRUE(leaf_node_handler::insert(bs, node, k, v, repli_timestamp::invalid));\n verify(bs, node);\n ASSERT_EQ(1, node->npairs);\n\n union {\n byte readval_padding[MAX_TOTAL_NODE_CONTENTS_SIZE + sizeof(btree_value)];\n btree_value readval;\n };\n\n (void)readval_padding;\n\n ASSERT_TRUE(leaf_node_handler::lookup(node, k, &readval));\n\n ASSERT_EQ(0, memcmp(v, &readval, v->full_size()));\n\n leaf_node_handler::remove(bs, node, k);\n verify(bs, node);\n ASSERT_EQ(0, node->npairs);\n\n free(k);\n free(v);\n free(node);\n}\n\nTEST(LeafNodeTest, ElementaryInsertLookupRemove) {\n InsertLookupRemoveHelper(\"the_key\", \"the_value\");\n}\nTEST(LeafNodeTest, EmptyValueInsertLookupRemove) {\n InsertLookupRemoveHelper(\"the_key\", \"\");\n}\nTEST(LeafNodeTest, EmptyKeyInsertLookupRemove) {\n InsertLookupRemoveHelper(\"\", \"the_value\");\n}\nTEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) {\n InsertLookupRemoveHelper(\"\", \"\");\n}\n\n\n} \/\/ namespace unittest\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2003-2014 Max Kellermann <max@duempel.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef FOREIGN_FIFO_BUFFER_HXX\n#define FOREIGN_FIFO_BUFFER_HXX\n\n#include \"WritableBuffer.hxx\"\n\n#include <utility>\n#include <algorithm>\n\n#include <cstddef>\n\n#include <assert.h>\n\n\/**\n * A first-in-first-out buffer: you can append data at the end, and\n * read data from the beginning. This class automatically shifts the\n * buffer as needed. It is not thread safe.\n *\n * This class does not manage buffer memory. It will not allocate or\n * free any memory, it only manages the contents of an existing buffer\n * given to the constructor.\n *\/\ntemplate<typename T>\nclass ForeignFifoBuffer {\npublic:\n\ttypedef size_t size_type;\n\ttypedef WritableBuffer<T> Range;\n\ttypedef typename Range::pointer_type pointer_type;\n\ttypedef typename Range::const_pointer_type const_pointer_type;\n\nprotected:\n\tsize_type head, tail, capacity;\n\tT *data;\n\npublic:\n\texplicit constexpr ForeignFifoBuffer(std::nullptr_t n)\n\t\t:head(0), tail(0), capacity(0), data(n) {}\n\n\tconstexpr ForeignFifoBuffer(T *_data, size_type _capacity)\n\t\t:head(0), tail(0), capacity(_capacity), data(_data) {}\n\n\tForeignFifoBuffer(ForeignFifoBuffer &&src)\n\t\t:head(src.head), tail(src.tail),\n\t\t capacity(src.capacity), data(src.data) {\n\t\tsrc.SetNull();\n\t}\n\n\tForeignFifoBuffer &operator=(ForeignFifoBuffer &&src) {\n\t\thead = src.head;\n\t\ttail = src.tail;\n\t\tcapacity = src.capacity;\n\t\tdata = src.data;\n\t\tsrc.SetNull();\n\t\treturn *this;\n\t}\n\n\tconstexpr bool IsNull() const {\n\t\treturn data == nullptr;\n\t}\n\n\tconstexpr bool IsDefined() const {\n\t\treturn !IsNull();\n\t}\n\n\tT *GetBuffer() {\n\t\treturn data;\n\t}\n\n\tconstexpr size_type GetCapacity() const {\n\t\treturn capacity;\n\t}\n\n\tvoid SetNull() {\n\t\thead = tail = 0;\n\t\tcapacity = 0;\n\t\tdata = nullptr;\n\t}\n\n\tvoid SetBuffer(T *_data, size_type _capacity) {\n\t\tassert(_data != nullptr);\n\t\tassert(_capacity > 0);\n\n\t\thead = tail = 0;\n\t\tcapacity = _capacity;\n\t\tdata = _data;\n\t}\n\n\tvoid MoveBuffer(T *new_data, size_type new_capacity) {\n\t\tassert(new_capacity >= tail - head);\n\n\t\tstd::move(data + head, data + tail, new_data);\n\t\tdata = new_data;\n\t\tcapacity = new_capacity;\n\t\ttail -= head;\n\t\thead = 0;\n\t}\n\n\tvoid Clear() {\n\t\thead = tail = 0;\n\t}\n\n\tconstexpr bool IsEmpty() const {\n\t\treturn head == tail;\n\t}\n\n\tconstexpr bool IsFull() const {\n\t\treturn head == 0 && tail == capacity;\n\t}\n\n\t\/**\n\t * Prepares writing. Returns a buffer range which may be written.\n\t * When you are finished, call append().\n\t *\/\n\tRange Write() {\n\t\tShift();\n\t\treturn Range(data + tail, capacity - tail);\n\t}\n\n\tbool WantWrite(size_type n) {\n\t\tif (tail + n <= capacity)\n\t\t\t\/* enough space after the tail *\/\n\t\t\treturn true;\n\n\t\tconst size_type in_use = tail - head;\n\t\tconst size_type required_capacity = in_use + n;\n\t\tif (required_capacity > capacity)\n\t\t\treturn false;\n\n\t\tShift();\n\t\tassert(tail + n <= capacity);\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Expands the tail of the buffer, after data has been written to\n\t * the buffer returned by write().\n\t *\/\n\tvoid Append(size_type n) {\n\t\tassert(tail <= capacity);\n\t\tassert(n <= capacity);\n\t\tassert(tail + n <= capacity);\n\n\t\ttail += n;\n\t}\n\n\tconstexpr size_type GetAvailable() const {\n\t\treturn tail - head;\n\t}\n\n\t\/**\n\t * Return a buffer range which may be read. The buffer pointer is\n\t * writable, to allow modifications while parsing.\n\t *\/\n\tconstexpr Range Read() const {\n\t\treturn Range(data + head, tail - head);\n\t}\n\n\t\/**\n\t * Marks a chunk as consumed.\n\t *\/\n\tvoid Consume(size_type n) {\n\t\tassert(tail <= capacity);\n\t\tassert(head <= tail);\n\t\tassert(n <= tail);\n\t\tassert(head + n <= tail);\n\n\t\thead += n;\n\t}\n\n\tsize_type Read(pointer_type p, size_type n) {\n\t\tauto range = Read();\n\t\tif (n > range.size)\n\t\t\tn = range.size;\n\t\tstd::copy_n(range.data, n, p);\n\t\tConsume(n);\n\t\treturn n;\n\t}\n\n\t\/**\n\t * Move as much data as possible from the specified buffer.\n\t *\n\t * @return the number of items moved\n\t *\/\n\tsize_type MoveFrom(ForeignFifoBuffer<T> &src) {\n\t\tauto r = src.Read();\n\t\tauto w = Write();\n\t\tsize_t n = std::min(r.size, w.size);\n\n\t\tstd::move(r.data, r.data + n, w.data);\n\t\tAppend(n);\n\t\tsrc.Consume(n);\n\t\treturn n;\n\t}\n\nprotected:\n\tvoid Shift() {\n\t\tif (head == 0)\n\t\t\treturn;\n\n\t\tassert(head <= capacity);\n\t\tassert(tail <= capacity);\n\t\tassert(tail >= head);\n\n\t\tstd::move(data + head, data + tail, data);\n\n\t\ttail -= head;\n\t\thead = 0;\n\t}\n};\n\n#endif\n<commit_msg>util\/ForeignFifoBuffer: add method Swap()<commit_after>\/*\n * Copyright (C) 2003-2014 Max Kellermann <max@duempel.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef FOREIGN_FIFO_BUFFER_HXX\n#define FOREIGN_FIFO_BUFFER_HXX\n\n#include \"WritableBuffer.hxx\"\n\n#include <utility>\n#include <algorithm>\n\n#include <cstddef>\n\n#include <assert.h>\n\n\/**\n * A first-in-first-out buffer: you can append data at the end, and\n * read data from the beginning. This class automatically shifts the\n * buffer as needed. It is not thread safe.\n *\n * This class does not manage buffer memory. It will not allocate or\n * free any memory, it only manages the contents of an existing buffer\n * given to the constructor.\n *\/\ntemplate<typename T>\nclass ForeignFifoBuffer {\npublic:\n\ttypedef size_t size_type;\n\ttypedef WritableBuffer<T> Range;\n\ttypedef typename Range::pointer_type pointer_type;\n\ttypedef typename Range::const_pointer_type const_pointer_type;\n\nprotected:\n\tsize_type head, tail, capacity;\n\tT *data;\n\npublic:\n\texplicit constexpr ForeignFifoBuffer(std::nullptr_t n)\n\t\t:head(0), tail(0), capacity(0), data(n) {}\n\n\tconstexpr ForeignFifoBuffer(T *_data, size_type _capacity)\n\t\t:head(0), tail(0), capacity(_capacity), data(_data) {}\n\n\tForeignFifoBuffer(ForeignFifoBuffer &&src)\n\t\t:head(src.head), tail(src.tail),\n\t\t capacity(src.capacity), data(src.data) {\n\t\tsrc.SetNull();\n\t}\n\n\tForeignFifoBuffer &operator=(ForeignFifoBuffer &&src) {\n\t\thead = src.head;\n\t\ttail = src.tail;\n\t\tcapacity = src.capacity;\n\t\tdata = src.data;\n\t\tsrc.SetNull();\n\t\treturn *this;\n\t}\n\n\tvoid Swap(ForeignFifoBuffer<T> &other) {\n\t\tstd::swap(head, other.head);\n\t\tstd::swap(tail, other.tail);\n\t\tstd::swap(capacity, other.capacity);\n\t\tstd::swap(data, other.data);\n\t}\n\n\tconstexpr bool IsNull() const {\n\t\treturn data == nullptr;\n\t}\n\n\tconstexpr bool IsDefined() const {\n\t\treturn !IsNull();\n\t}\n\n\tT *GetBuffer() {\n\t\treturn data;\n\t}\n\n\tconstexpr size_type GetCapacity() const {\n\t\treturn capacity;\n\t}\n\n\tvoid SetNull() {\n\t\thead = tail = 0;\n\t\tcapacity = 0;\n\t\tdata = nullptr;\n\t}\n\n\tvoid SetBuffer(T *_data, size_type _capacity) {\n\t\tassert(_data != nullptr);\n\t\tassert(_capacity > 0);\n\n\t\thead = tail = 0;\n\t\tcapacity = _capacity;\n\t\tdata = _data;\n\t}\n\n\tvoid MoveBuffer(T *new_data, size_type new_capacity) {\n\t\tassert(new_capacity >= tail - head);\n\n\t\tstd::move(data + head, data + tail, new_data);\n\t\tdata = new_data;\n\t\tcapacity = new_capacity;\n\t\ttail -= head;\n\t\thead = 0;\n\t}\n\n\tvoid Clear() {\n\t\thead = tail = 0;\n\t}\n\n\tconstexpr bool IsEmpty() const {\n\t\treturn head == tail;\n\t}\n\n\tconstexpr bool IsFull() const {\n\t\treturn head == 0 && tail == capacity;\n\t}\n\n\t\/**\n\t * Prepares writing. Returns a buffer range which may be written.\n\t * When you are finished, call append().\n\t *\/\n\tRange Write() {\n\t\tShift();\n\t\treturn Range(data + tail, capacity - tail);\n\t}\n\n\tbool WantWrite(size_type n) {\n\t\tif (tail + n <= capacity)\n\t\t\t\/* enough space after the tail *\/\n\t\t\treturn true;\n\n\t\tconst size_type in_use = tail - head;\n\t\tconst size_type required_capacity = in_use + n;\n\t\tif (required_capacity > capacity)\n\t\t\treturn false;\n\n\t\tShift();\n\t\tassert(tail + n <= capacity);\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Expands the tail of the buffer, after data has been written to\n\t * the buffer returned by write().\n\t *\/\n\tvoid Append(size_type n) {\n\t\tassert(tail <= capacity);\n\t\tassert(n <= capacity);\n\t\tassert(tail + n <= capacity);\n\n\t\ttail += n;\n\t}\n\n\tconstexpr size_type GetAvailable() const {\n\t\treturn tail - head;\n\t}\n\n\t\/**\n\t * Return a buffer range which may be read. The buffer pointer is\n\t * writable, to allow modifications while parsing.\n\t *\/\n\tconstexpr Range Read() const {\n\t\treturn Range(data + head, tail - head);\n\t}\n\n\t\/**\n\t * Marks a chunk as consumed.\n\t *\/\n\tvoid Consume(size_type n) {\n\t\tassert(tail <= capacity);\n\t\tassert(head <= tail);\n\t\tassert(n <= tail);\n\t\tassert(head + n <= tail);\n\n\t\thead += n;\n\t}\n\n\tsize_type Read(pointer_type p, size_type n) {\n\t\tauto range = Read();\n\t\tif (n > range.size)\n\t\t\tn = range.size;\n\t\tstd::copy_n(range.data, n, p);\n\t\tConsume(n);\n\t\treturn n;\n\t}\n\n\t\/**\n\t * Move as much data as possible from the specified buffer.\n\t *\n\t * @return the number of items moved\n\t *\/\n\tsize_type MoveFrom(ForeignFifoBuffer<T> &src) {\n\t\tauto r = src.Read();\n\t\tauto w = Write();\n\t\tsize_t n = std::min(r.size, w.size);\n\n\t\tstd::move(r.data, r.data + n, w.data);\n\t\tAppend(n);\n\t\tsrc.Consume(n);\n\t\treturn n;\n\t}\n\nprotected:\n\tvoid Shift() {\n\t\tif (head == 0)\n\t\t\treturn;\n\n\t\tassert(head <= capacity);\n\t\tassert(tail <= capacity);\n\t\tassert(tail >= head);\n\n\t\tstd::move(data + head, data + tail, data);\n\n\t\ttail -= head;\n\t\thead = 0;\n\t}\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/ozone\/platform\/cast\/overlay_manager_cast.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"chromecast\/media\/base\/media_message_loop.h\"\n#include \"chromecast\/public\/cast_media_shlib.h\"\n#include \"chromecast\/public\/graphics_types.h\"\n#include \"chromecast\/public\/video_plane.h\"\n#include \"ui\/gfx\/geometry\/rect_conversions.h\"\n#include \"ui\/ozone\/public\/overlay_candidates_ozone.h\"\n\nnamespace ui {\nnamespace {\n\n\/\/ Helper class for calling VideoPlane::SetGeometry with rate-limiting.\n\/\/ SetGeometry can take on the order of 100ms to run in some implementations\n\/\/ and can be called on the order of 20x \/ second (as fast as graphics frames\n\/\/ are produced). This creates an ever-growing backlog of tasks on the media\n\/\/ thread.\n\/\/ This class measures the time taken to run SetGeometry to determine a\n\/\/ reasonable frequency at which to call it. Excess calls are coalesced\n\/\/ to just set the most recent geometry.\nclass RateLimitedSetVideoPlaneGeometry\n : public base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry> {\n public:\n RateLimitedSetVideoPlaneGeometry(\n const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)\n : pending_display_rect_(0, 0, 0, 0),\n pending_set_geometry_(false),\n min_calling_interval_ms_(0),\n sample_counter_(0),\n task_runner_(task_runner) {}\n\n void SetGeometry(\n const chromecast::RectF& display_rect,\n chromecast::media::VideoPlane::CoordinateType coordinate_type,\n chromecast::media::VideoPlane::Transform transform) {\n DCHECK(task_runner_->BelongsToCurrentThread());\n\n base::TimeTicks now = base::TimeTicks::Now();\n base::TimeDelta elapsed = now - last_set_geometry_time_;\n\n if (elapsed < base::TimeDelta::FromMilliseconds(min_calling_interval_ms_)) {\n if (!pending_set_geometry_) {\n pending_set_geometry_ = true;\n\n task_runner_->PostDelayedTask(\n FROM_HERE,\n base::Bind(\n &RateLimitedSetVideoPlaneGeometry::ApplyPendingSetGeometry,\n this),\n base::TimeDelta::FromMilliseconds(2 * min_calling_interval_ms_));\n }\n\n pending_display_rect_ = display_rect;\n pending_coordinate_type_ = coordinate_type;\n pending_transform_ = transform;\n return;\n }\n last_set_geometry_time_ = now;\n\n chromecast::media::VideoPlane* video_plane =\n chromecast::media::CastMediaShlib::GetVideoPlane();\n CHECK(video_plane);\n base::TimeTicks start = base::TimeTicks::Now();\n video_plane->SetGeometry(display_rect, coordinate_type, transform);\n\n base::TimeDelta set_geometry_time = base::TimeTicks::Now() - start;\n UpdateAverageTime(set_geometry_time.InMilliseconds());\n }\n\n private:\n friend class base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry>;\n ~RateLimitedSetVideoPlaneGeometry() {}\n\n void UpdateAverageTime(int64 sample) {\n const size_t kSampleCount = 5;\n if (samples_.size() < kSampleCount)\n samples_.push_back(sample);\n else\n samples_[sample_counter_++ % kSampleCount] = sample;\n int64 total = 0;\n for (int64 s : samples_)\n total += s;\n min_calling_interval_ms_ = 2 * total \/ samples_.size();\n }\n\n void ApplyPendingSetGeometry() {\n if (pending_set_geometry_) {\n pending_set_geometry_ = false;\n SetGeometry(pending_display_rect_, pending_coordinate_type_,\n pending_transform_);\n }\n }\n\n chromecast::RectF pending_display_rect_;\n chromecast::media::VideoPlane::CoordinateType pending_coordinate_type_;\n chromecast::media::VideoPlane::Transform pending_transform_;\n bool pending_set_geometry_;\n base::TimeTicks last_set_geometry_time_;\n\n \/\/ Don't call SetGeometry faster than this interval.\n int64 min_calling_interval_ms_;\n\n \/\/ Min calling interval is computed as double average of last few time samples\n \/\/ (i.e. allow at least as much time between calls as the call itself takes).\n std::vector<int64> samples_;\n size_t sample_counter_;\n\n scoped_refptr<base::SingleThreadTaskRunner> task_runner_;\n\n DISALLOW_COPY_AND_ASSIGN(RateLimitedSetVideoPlaneGeometry);\n};\n\n\/\/ Translates a gfx::OverlayTransform into a VideoPlane::Transform.\n\/\/ Could be just a lookup table once we have unit tests for this code\n\/\/ to ensure it stays in sync with OverlayTransform.\nchromecast::media::VideoPlane::Transform ConvertTransform(\n gfx::OverlayTransform transform) {\n switch (transform) {\n case gfx::OVERLAY_TRANSFORM_NONE:\n return chromecast::media::VideoPlane::TRANSFORM_NONE;\n case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:\n return chromecast::media::VideoPlane::FLIP_HORIZONTAL;\n case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:\n return chromecast::media::VideoPlane::FLIP_VERTICAL;\n case gfx::OVERLAY_TRANSFORM_ROTATE_90:\n return chromecast::media::VideoPlane::ROTATE_90;\n case gfx::OVERLAY_TRANSFORM_ROTATE_180:\n return chromecast::media::VideoPlane::ROTATE_180;\n case gfx::OVERLAY_TRANSFORM_ROTATE_270:\n return chromecast::media::VideoPlane::ROTATE_270;\n default:\n NOTREACHED();\n return chromecast::media::VideoPlane::TRANSFORM_NONE;\n }\n}\n\nbool ExactlyEqual(const chromecast::RectF& r1, const chromecast::RectF& r2) {\n return r1.x == r2.x && r1.y == r2.y && r1.width == r2.width &&\n r1.height == r2.height;\n}\n\nclass OverlayCandidatesCast : public OverlayCandidatesOzone {\n public:\n OverlayCandidatesCast()\n : media_task_runner_(\n chromecast::media::MediaMessageLoop::GetTaskRunner()),\n transform_(gfx::OVERLAY_TRANSFORM_INVALID),\n display_rect_(0, 0, 0, 0),\n video_plane_wrapper_(\n new RateLimitedSetVideoPlaneGeometry(media_task_runner_)) {}\n\n void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces) override;\n\n private:\n scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;\n gfx::OverlayTransform transform_;\n chromecast::RectF display_rect_;\n scoped_refptr<RateLimitedSetVideoPlaneGeometry> video_plane_wrapper_;\n};\n\nvoid OverlayCandidatesCast::CheckOverlaySupport(\n OverlaySurfaceCandidateList* surfaces) {\n for (auto& candidate : *surfaces) {\n if (candidate.plane_z_order != -1)\n continue;\n\n candidate.overlay_handled = true;\n\n \/\/ Compositor requires all overlay rectangles to have integer coords\n candidate.display_rect = gfx::ToEnclosedRect(candidate.display_rect);\n\n chromecast::RectF display_rect(\n candidate.display_rect.x(), candidate.display_rect.y(),\n candidate.display_rect.width(), candidate.display_rect.height());\n\n \/\/ Update video plane geometry + transform to match compositor quad.\n \/\/ This must be done on media thread - and no point doing if it hasn't\n \/\/ changed.\n if (candidate.transform != transform_ ||\n !ExactlyEqual(display_rect, display_rect_)) {\n transform_ = candidate.transform;\n display_rect_ = display_rect;\n\n media_task_runner_->PostTask(\n FROM_HERE,\n base::Bind(\n &RateLimitedSetVideoPlaneGeometry::SetGeometry,\n video_plane_wrapper_, display_rect,\n chromecast::media::VideoPlane::COORDINATE_TYPE_GRAPHICS_PLANE,\n ConvertTransform(candidate.transform)));\n }\n return;\n }\n}\n\n} \/\/ namespace\n\nOverlayManagerCast::OverlayManagerCast() {\n}\n\nOverlayManagerCast::~OverlayManagerCast() {\n}\n\nscoped_ptr<OverlayCandidatesOzone> OverlayManagerCast::CreateOverlayCandidates(\n gfx::AcceleratedWidget w) {\n return make_scoped_ptr(new OverlayCandidatesCast());\n}\n\nbool OverlayManagerCast::CanShowPrimaryPlaneAsOverlay() {\n return false;\n}\n\n} \/\/ namespace ui\n<commit_msg>ozone: Don't implicitly convert Rect to RectF.<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/ozone\/platform\/cast\/overlay_manager_cast.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"chromecast\/media\/base\/media_message_loop.h\"\n#include \"chromecast\/public\/cast_media_shlib.h\"\n#include \"chromecast\/public\/graphics_types.h\"\n#include \"chromecast\/public\/video_plane.h\"\n#include \"ui\/gfx\/geometry\/rect_conversions.h\"\n#include \"ui\/ozone\/public\/overlay_candidates_ozone.h\"\n\nnamespace ui {\nnamespace {\n\n\/\/ Helper class for calling VideoPlane::SetGeometry with rate-limiting.\n\/\/ SetGeometry can take on the order of 100ms to run in some implementations\n\/\/ and can be called on the order of 20x \/ second (as fast as graphics frames\n\/\/ are produced). This creates an ever-growing backlog of tasks on the media\n\/\/ thread.\n\/\/ This class measures the time taken to run SetGeometry to determine a\n\/\/ reasonable frequency at which to call it. Excess calls are coalesced\n\/\/ to just set the most recent geometry.\nclass RateLimitedSetVideoPlaneGeometry\n : public base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry> {\n public:\n RateLimitedSetVideoPlaneGeometry(\n const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)\n : pending_display_rect_(0, 0, 0, 0),\n pending_set_geometry_(false),\n min_calling_interval_ms_(0),\n sample_counter_(0),\n task_runner_(task_runner) {}\n\n void SetGeometry(\n const chromecast::RectF& display_rect,\n chromecast::media::VideoPlane::CoordinateType coordinate_type,\n chromecast::media::VideoPlane::Transform transform) {\n DCHECK(task_runner_->BelongsToCurrentThread());\n\n base::TimeTicks now = base::TimeTicks::Now();\n base::TimeDelta elapsed = now - last_set_geometry_time_;\n\n if (elapsed < base::TimeDelta::FromMilliseconds(min_calling_interval_ms_)) {\n if (!pending_set_geometry_) {\n pending_set_geometry_ = true;\n\n task_runner_->PostDelayedTask(\n FROM_HERE,\n base::Bind(\n &RateLimitedSetVideoPlaneGeometry::ApplyPendingSetGeometry,\n this),\n base::TimeDelta::FromMilliseconds(2 * min_calling_interval_ms_));\n }\n\n pending_display_rect_ = display_rect;\n pending_coordinate_type_ = coordinate_type;\n pending_transform_ = transform;\n return;\n }\n last_set_geometry_time_ = now;\n\n chromecast::media::VideoPlane* video_plane =\n chromecast::media::CastMediaShlib::GetVideoPlane();\n CHECK(video_plane);\n base::TimeTicks start = base::TimeTicks::Now();\n video_plane->SetGeometry(display_rect, coordinate_type, transform);\n\n base::TimeDelta set_geometry_time = base::TimeTicks::Now() - start;\n UpdateAverageTime(set_geometry_time.InMilliseconds());\n }\n\n private:\n friend class base::RefCountedThreadSafe<RateLimitedSetVideoPlaneGeometry>;\n ~RateLimitedSetVideoPlaneGeometry() {}\n\n void UpdateAverageTime(int64 sample) {\n const size_t kSampleCount = 5;\n if (samples_.size() < kSampleCount)\n samples_.push_back(sample);\n else\n samples_[sample_counter_++ % kSampleCount] = sample;\n int64 total = 0;\n for (int64 s : samples_)\n total += s;\n min_calling_interval_ms_ = 2 * total \/ samples_.size();\n }\n\n void ApplyPendingSetGeometry() {\n if (pending_set_geometry_) {\n pending_set_geometry_ = false;\n SetGeometry(pending_display_rect_, pending_coordinate_type_,\n pending_transform_);\n }\n }\n\n chromecast::RectF pending_display_rect_;\n chromecast::media::VideoPlane::CoordinateType pending_coordinate_type_;\n chromecast::media::VideoPlane::Transform pending_transform_;\n bool pending_set_geometry_;\n base::TimeTicks last_set_geometry_time_;\n\n \/\/ Don't call SetGeometry faster than this interval.\n int64 min_calling_interval_ms_;\n\n \/\/ Min calling interval is computed as double average of last few time samples\n \/\/ (i.e. allow at least as much time between calls as the call itself takes).\n std::vector<int64> samples_;\n size_t sample_counter_;\n\n scoped_refptr<base::SingleThreadTaskRunner> task_runner_;\n\n DISALLOW_COPY_AND_ASSIGN(RateLimitedSetVideoPlaneGeometry);\n};\n\n\/\/ Translates a gfx::OverlayTransform into a VideoPlane::Transform.\n\/\/ Could be just a lookup table once we have unit tests for this code\n\/\/ to ensure it stays in sync with OverlayTransform.\nchromecast::media::VideoPlane::Transform ConvertTransform(\n gfx::OverlayTransform transform) {\n switch (transform) {\n case gfx::OVERLAY_TRANSFORM_NONE:\n return chromecast::media::VideoPlane::TRANSFORM_NONE;\n case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:\n return chromecast::media::VideoPlane::FLIP_HORIZONTAL;\n case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:\n return chromecast::media::VideoPlane::FLIP_VERTICAL;\n case gfx::OVERLAY_TRANSFORM_ROTATE_90:\n return chromecast::media::VideoPlane::ROTATE_90;\n case gfx::OVERLAY_TRANSFORM_ROTATE_180:\n return chromecast::media::VideoPlane::ROTATE_180;\n case gfx::OVERLAY_TRANSFORM_ROTATE_270:\n return chromecast::media::VideoPlane::ROTATE_270;\n default:\n NOTREACHED();\n return chromecast::media::VideoPlane::TRANSFORM_NONE;\n }\n}\n\nbool ExactlyEqual(const chromecast::RectF& r1, const chromecast::RectF& r2) {\n return r1.x == r2.x && r1.y == r2.y && r1.width == r2.width &&\n r1.height == r2.height;\n}\n\nclass OverlayCandidatesCast : public OverlayCandidatesOzone {\n public:\n OverlayCandidatesCast()\n : media_task_runner_(\n chromecast::media::MediaMessageLoop::GetTaskRunner()),\n transform_(gfx::OVERLAY_TRANSFORM_INVALID),\n display_rect_(0, 0, 0, 0),\n video_plane_wrapper_(\n new RateLimitedSetVideoPlaneGeometry(media_task_runner_)) {}\n\n void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces) override;\n\n private:\n scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;\n gfx::OverlayTransform transform_;\n chromecast::RectF display_rect_;\n scoped_refptr<RateLimitedSetVideoPlaneGeometry> video_plane_wrapper_;\n};\n\nvoid OverlayCandidatesCast::CheckOverlaySupport(\n OverlaySurfaceCandidateList* surfaces) {\n for (auto& candidate : *surfaces) {\n if (candidate.plane_z_order != -1)\n continue;\n\n candidate.overlay_handled = true;\n\n \/\/ Compositor requires all overlay rectangles to have integer coords.\n candidate.display_rect =\n gfx::RectF(gfx::ToEnclosedRect(candidate.display_rect));\n\n chromecast::RectF display_rect(\n candidate.display_rect.x(), candidate.display_rect.y(),\n candidate.display_rect.width(), candidate.display_rect.height());\n\n \/\/ Update video plane geometry + transform to match compositor quad.\n \/\/ This must be done on media thread - and no point doing if it hasn't\n \/\/ changed.\n if (candidate.transform != transform_ ||\n !ExactlyEqual(display_rect, display_rect_)) {\n transform_ = candidate.transform;\n display_rect_ = display_rect;\n\n media_task_runner_->PostTask(\n FROM_HERE,\n base::Bind(\n &RateLimitedSetVideoPlaneGeometry::SetGeometry,\n video_plane_wrapper_, display_rect,\n chromecast::media::VideoPlane::COORDINATE_TYPE_GRAPHICS_PLANE,\n ConvertTransform(candidate.transform)));\n }\n return;\n }\n}\n\n} \/\/ namespace\n\nOverlayManagerCast::OverlayManagerCast() {\n}\n\nOverlayManagerCast::~OverlayManagerCast() {\n}\n\nscoped_ptr<OverlayCandidatesOzone> OverlayManagerCast::CreateOverlayCandidates(\n gfx::AcceleratedWidget w) {\n return make_scoped_ptr(new OverlayCandidatesCast());\n}\n\nbool OverlayManagerCast::CanShowPrimaryPlaneAsOverlay() {\n return false;\n}\n\n} \/\/ namespace ui\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file drawRRT.cpp\n * @author Can Erdogan\n * @date Feb 24, 2013\n * @brief Visualizes 2D and 3D rrts with gnuplot.\n *\/\n\n#include \"planning\/PathPlanner.h\"\n#include \"..\/unittests\/TestHelpers.h\" \/\/ TODO: Fix this hack\n#include \"simulation\/World.h\"\n\nusing namespace std;\nusing namespace planning;\nusing namespace simulation;\n\n\/* ********************************************************************************************* *\/\ninline void saveLine (char* l1, char* l2, size_t off, const VectorXd& n1, const VectorXd& n2) {\n\tif(n1.size() == 2) {\n\t\tsprintf(l1 + off, \"%+02.3lf %+02.3lf \", n1(0), n1(1));\n\t\tsprintf(l2 + off, \"%+02.3lf %+02.3lf \", n2(0), n2(1));\n\t}\n\telse if(n1.size() == 3) {\n\t\tsprintf(l1 + off, \"%+02.3lf %+02.3lf %+02.3lf \", n1(0), n1(1), n1(2));\n\t\tsprintf(l2 + off, \"%+02.3lf %+02.3lf %+02.3lf \", n2(0), n2(1), n2(2));\n\t}\n}\n\n\/* ********************************************************************************************* *\/\ninline void drawLine (FILE* f, size_t numDofs, const char* color, size_t i, bool last = false) {\n\tif(numDofs == 2) {\n\t\tfprintf(f, \"\\\".data\\\" u %lu:%lu with linespoints notitle ps 1 pt 6 lc rgb '#%s'%s \", \n\t\t\t2*i+1, 2*i+2, color, (last ? \"\" : \",\"));\n\t}\n\telse if (numDofs == 3) {\n\t\tfprintf(f, \"\\\".data\\\" u %lu:%lu:%lu with linespoints notitle ps 1 pt 6 lc rgb '#%s'%s \", \n\t\t\t3*i+1, 3*i+2, 3*i+3, color, (last ? \"\" : \",\"));\n\t}\n}\n\n\/* ********************************************************************************************* *\/\nvoid draw (const RRT* t1, const RRT* t2) {\n\n\t\/\/ Check the size of a data point - we can only visualize 2 or 3\n\tsize_t numDofs = t1->ndim;\n\tif((numDofs != 2) && (numDofs != 3)) return;\n\n\t\/\/ ====================================================================\n\t\/\/ Write the data to a file\n\n\t\/\/ File contains two lines, one for each endpoint of an edge\n\tFILE* data = fopen(\".data\", \"w\");\n\tsize_t step = numDofs * 7;\t\t\t\t\t\t\t\t\t\t\t\/\/ 7 characters per double\n\tsize_t numEdges1 = (t1->configVector.size() - 1);\n\tsize_t numEdges2 = ((t2 == NULL) ? 0 : t2->configVector.size() - 1);\n\tchar* line1 = new char[(numEdges1 + numEdges2 + 5) * step];\n\tchar* line2 = new char[(numEdges1 + numEdges2 + 5) * step];\n\n\t\/\/ Write each node and its parent in the respective lines\n\tsize_t lineIndex = 0;\n\tconst RRT* trees [2] = {t1, t2};\n\tfor(size_t t = 0; t < 2; t++) {\n\n\t\t\/\/ Skip the tree if not there\n\t\tif(trees[t] == NULL) continue;\n\n\t\t\/\/ Draw the edges\n\t\tsize_t numEdges = trees[t]->configVector.size() - 1;\n\t\tfor(size_t i = 0; i < numEdges; i++, lineIndex += step) {\n\t\t\tconst VectorXd& node = *trees[t]->configVector[i + 1];\n\t\t\tconst VectorXd& parent = *trees[t]->configVector[trees[t]->parentVector[i + 1]];\n\t\t\tsaveLine(line1, line2, lineIndex, node, parent);\n\t\t}\n\t}\n\n\t\/\/ Print the start to draw with a special color (we draw a 0 length edge)\n\tconst VectorXd& goal = *t1->configVector[0];\n\tsaveLine(line1, line2, lineIndex, goal, goal);\n\tlineIndex += step;\n\n\t\/\/ Write the lines to the file\n\tfprintf(data, \"%s\\n\", line1);\n\tfprintf(data, \"%s\\n\", line2);\n\tfclose(data);\n\n\tdelete[] line1;\n\tdelete[] line2;\n\n\t\/\/ ====================================================================\n\t\/\/ Run gnuplot with the pipe call\n\n\t\/\/ Open gnuplot in a shell terminal\n\tFILE* gnuplot;\n\tgnuplot = fopen(\".gnuplot\", \"w\");\n\n\t\/\/ Set options\n\tfprintf(gnuplot, \"\");\n\tfprintf(gnuplot, \"set terminal wxt size 600,600;\\n\");\n\tfprintf(gnuplot, \"set xrange [-3.14:3.14];\\n\");\n\tfprintf(gnuplot, \"set yrange [-3.14:3.14];\\n\");\n\tfprintf(gnuplot, \"set size ratio -1;\\n\");\n\tif(numDofs == 3) {\n\t\tfprintf(gnuplot, \"set zrange [-3.14:3.14];\\n\");\n\t\tfprintf(gnuplot, \"set xyplane at -3.14;\\n\");\n\t}\n\n\t\/\/ Draw the edges in the file but leave the last edge to draw a special color for the goal\n\tfprintf(gnuplot, \"%s \", ((numDofs == 2) ? \"plot\" : \"splot\"));\n\tfor(size_t i = 0; i < numEdges1; i++) \n\t\tdrawLine(gnuplot, numDofs, \"0000ff\", i);\n\tfor(size_t i = 0; i < numEdges2; i++) \n\t\tdrawLine(gnuplot, numDofs, \"00ffff\", i + numEdges1);\n\t\n\t\/\/ Draw the goal point (fake edge)\n\tdrawLine(gnuplot, numDofs, \"00ff00\", numEdges1 + numEdges2, true); \n\n\t\/\/ Close the pipe\n\tfprintf(gnuplot, \"\\n\");\n\tfprintf(gnuplot, \"\\n\");\n\tfclose(gnuplot);\n\n\t\/\/ Make the system call\n\tint status = system(\"gnuplot -persist .gnuplot\");\n\tassert((status != -1) && \"Error in system call in RRT::draw()\");\n}\n\n\/\/\/ Visualizes a 3D RRT\nvoid drawThreeLink () {\n\n \/\/ Create a robot and a world\n const double l1 = 1.5, l2 = 1.0, l3 = 0.5;\n SkeletonDynamics* r = createThreeLinkRobot(Vector3d(0.3, 0.3, l1), DOF_ROLL, Vector3d(0.3, 0.3, l2), DOF_ROLL, \n\t\t\tVector3d(0.3, 0.3, l3), DOF_ROLL);\n World w;\n w.addSkeleton(r);\n\n \/\/ Create a path planner and feed it an unfeasible goal to grow the RRT freely\n PathPlanner <> planner (w, false, false, 1e-1, 1e3, 0.0);\n vector <int> links;\n links.push_back(0);\n links.push_back(1);\n links.push_back(2);\n list <VectorXd> path;\n planner.planPath(0, links, Vector3d(-M_PI+0.1, -M_PI+0.1, -M_PI+0.1), Vector3d(M_PI-0.1, M_PI-0.1, M_PI+0.1),\n \t\t\tpath);\n\n \/\/ Print the nodes\n RRT* rrt = planner.start_rrt;\n draw(rrt, NULL);\n}\n\n\/\/\/ Visualizes a 2D RRT\nvoid drawTwoLink () {\n\n \/\/ Create a robot and a world\n const double l1 = 1.5, l2 = 1.0;\n SkeletonDynamics* r = createTwoLinkRobot(Vector3d(0.3, 0.3, l1), DOF_ROLL, Vector3d(0.3, 0.3, l2), DOF_ROLL);\n World w;\n w.addSkeleton(r);\n\n \/\/ Create a path planner and feed it an unfeasible goal to grow the RRT freely\n PathPlanner <> planner (w, false, false, 1e-1, 1e3, 0.0);\n vector <int> links;\n links.push_back(0);\n links.push_back(1);\n list <VectorXd> path;\n planner.planPath(0, links, Vector2d(-M_PI+0.1, -M_PI+0.1), Vector2d(M_PI-0.1, M_PI-0.1), path);\n\n \/\/ Print the nodes\n RRT* rrt = planner.start_rrt;\n draw(rrt, NULL);\n\n}\n\n\/\/\/ The main thread\nint main () {\n\tdrawTwoLink();\n\tdrawThreeLink();\n}\n<commit_msg>Fix segmentation fault in drawRRT app<commit_after>\/**\n * @file drawRRT.cpp\n * @author Can Erdogan\n * @date Feb 24, 2013\n * @brief Visualizes 2D and 3D rrts with gnuplot.\n *\/\n\n#include \"planning\/PathPlanner.h\"\n#include \"..\/unittests\/TestHelpers.h\" \/\/ TODO: Fix this hack\n#include \"simulation\/World.h\"\n\nusing namespace std;\nusing namespace planning;\nusing namespace simulation;\n\n\/* ********************************************************************************************* *\/\ninline void saveLine (char* l1, char* l2, size_t off, const VectorXd& n1, const VectorXd& n2) {\n\tif(n1.size() == 2) {\n\t\tsprintf(l1 + off, \"%+02.3lf %+02.3lf \", n1(0), n1(1));\n\t\tsprintf(l2 + off, \"%+02.3lf %+02.3lf \", n2(0), n2(1));\n\t}\n\telse if(n1.size() == 3) {\n\t\tsprintf(l1 + off, \"%+02.3lf %+02.3lf %+02.3lf \", n1(0), n1(1), n1(2));\n\t\tsprintf(l2 + off, \"%+02.3lf %+02.3lf %+02.3lf \", n2(0), n2(1), n2(2));\n\t}\n}\n\n\/* ********************************************************************************************* *\/\ninline void drawLine (FILE* f, size_t numDofs, const char* color, size_t i, bool last = false) {\n\tif(numDofs == 2) {\n\t\tfprintf(f, \"\\\".data\\\" u %lu:%lu with linespoints notitle ps 1 pt 6 lc rgb '#%s'%s \", \n\t\t\t2*i+1, 2*i+2, color, (last ? \"\" : \",\"));\n\t}\n\telse if (numDofs == 3) {\n\t\tfprintf(f, \"\\\".data\\\" u %lu:%lu:%lu with linespoints notitle ps 1 pt 6 lc rgb '#%s'%s \", \n\t\t\t3*i+1, 3*i+2, 3*i+3, color, (last ? \"\" : \",\"));\n\t}\n}\n\n\/* ********************************************************************************************* *\/\nvoid draw (const RRT* t1, const RRT* t2) {\n\n\t\/\/ Check the size of a data point - we can only visualize 2 or 3\n\tsize_t numDofs = t1->ndim;\n\tif((numDofs != 2) && (numDofs != 3)) return;\n\n\t\/\/ ====================================================================\n\t\/\/ Write the data to a file\n\n\t\/\/ File contains two lines, one for each endpoint of an edge\n\tFILE* data = fopen(\".data\", \"w\");\n\tsize_t step = numDofs * 7;\t\t\t\t\t\t\t\t\t\t\t\/\/ 7 characters per double\n\tsize_t numEdges1 = (t1->configVector.size() - 1);\n\tsize_t numEdges2 = ((t2 == NULL) ? 0 : t2->configVector.size() - 1);\n\tchar* line1 = new char[(numEdges1 + numEdges2 + 5) * step];\n\tchar* line2 = new char[(numEdges1 + numEdges2 + 5) * step];\n\n\t\/\/ Write each node and its parent in the respective lines\n\tsize_t lineIndex = 0;\n\tconst RRT* trees [2] = {t1, t2};\n\tfor(size_t t = 0; t < 2; t++) {\n\n\t\t\/\/ Skip the tree if not there\n\t\tif(trees[t] == NULL) continue;\n\n\t\t\/\/ Draw the edges\n\t\tsize_t numEdges = trees[t]->configVector.size() - 1;\n\t\tfor(size_t i = 0; i < numEdges; i++, lineIndex += step) {\n\t\t\tconst VectorXd& node = *trees[t]->configVector[i + 1];\n\t\t\tconst VectorXd& parent = *trees[t]->configVector[trees[t]->parentVector[i + 1]];\n\t\t\tsaveLine(line1, line2, lineIndex, node, parent);\n\t\t}\n\t}\n\n\t\/\/ Print the start to draw with a special color (we draw a 0 length edge)\n\tconst VectorXd& goal = *t1->configVector[0];\n\tsaveLine(line1, line2, lineIndex, goal, goal);\n\tlineIndex += step;\n\n\t\/\/ Write the lines to the file\n\tfprintf(data, \"%s\\n\", line1);\n\tfprintf(data, \"%s\\n\", line2);\n\tfclose(data);\n\n\tdelete[] line1;\n\tdelete[] line2;\n\n\t\/\/ ====================================================================\n\t\/\/ Run gnuplot with the pipe call\n\n\t\/\/ Open gnuplot in a shell terminal\n\tFILE* gnuplot;\n\tgnuplot = fopen(\".gnuplot\", \"w\");\n\n\t\/\/ Set options\n\tfprintf(gnuplot, \"\");\n\tfprintf(gnuplot, \"set terminal wxt size 600,600;\\n\");\n\tfprintf(gnuplot, \"set xrange [-3.14:3.14];\\n\");\n\tfprintf(gnuplot, \"set yrange [-3.14:3.14];\\n\");\n\tfprintf(gnuplot, \"set size ratio -1;\\n\");\n\tif(numDofs == 3) {\n\t\tfprintf(gnuplot, \"set zrange [-3.14:3.14];\\n\");\n\t\tfprintf(gnuplot, \"set xyplane at -3.14;\\n\");\n\t}\n\n\t\/\/ Draw the edges in the file but leave the last edge to draw a special color for the goal\n\tfprintf(gnuplot, \"%s \", ((numDofs == 2) ? \"plot\" : \"splot\"));\n\tfor(size_t i = 0; i < numEdges1; i++) \n\t\tdrawLine(gnuplot, numDofs, \"0000ff\", i);\n\tfor(size_t i = 0; i < numEdges2; i++) \n\t\tdrawLine(gnuplot, numDofs, \"00ffff\", i + numEdges1);\n\t\n\t\/\/ Draw the goal point (fake edge)\n\tdrawLine(gnuplot, numDofs, \"00ff00\", numEdges1 + numEdges2, true); \n\n\t\/\/ Close the pipe\n\tfprintf(gnuplot, \"\\n\");\n\tfprintf(gnuplot, \"\\n\");\n\tfclose(gnuplot);\n\n\t\/\/ Make the system call\n\tint status = system(\"gnuplot -persist .gnuplot\");\n\tassert((status != -1) && \"Error in system call in RRT::draw()\");\n}\n\n\/\/\/ Visualizes a 3D RRT\nvoid drawThreeLink () {\n\n \/\/ Create a robot and a world\n const double l1 = 1.5, l2 = 1.0, l3 = 0.5;\n SkeletonDynamics* r = createThreeLinkRobot(Vector3d(0.3, 0.3, l1), DOF_ROLL, Vector3d(0.3, 0.3, l2), DOF_ROLL, \n\t\t\tVector3d(0.3, 0.3, l3), DOF_ROLL);\n World w;\n w.addSkeleton(r);\n\n \/\/ Create a path planner and feed it an unfeasible goal to grow the RRT freely\n PathPlanner <> planner (w, false, false, 1e-1, 1e3, 0.0);\n vector <int> links;\n links.push_back(0);\n links.push_back(1);\n links.push_back(2);\n list <VectorXd> path;\n planner.planPath(r, links, Vector3d(-M_PI+0.1, -M_PI+0.1, -M_PI+0.1), Vector3d(M_PI-0.1, M_PI-0.1, M_PI+0.1),\n \t\t\tpath);\n\n \/\/ Print the nodes\n RRT* rrt = planner.start_rrt;\n draw(rrt, NULL);\n}\n\n\/\/\/ Visualizes a 2D RRT\nvoid drawTwoLink () {\n\n \/\/ Create a robot and a world\n const double l1 = 1.5, l2 = 1.0;\n SkeletonDynamics* r = createTwoLinkRobot(Vector3d(0.3, 0.3, l1), DOF_ROLL, Vector3d(0.3, 0.3, l2), DOF_ROLL);\n World w;\n w.addSkeleton(r);\n\n \/\/ Create a path planner and feed it an unfeasible goal to grow the RRT freely\n PathPlanner <> planner (w, false, false, 1e-1, 1e3, 0.0);\n vector <int> links;\n links.push_back(0);\n links.push_back(1);\n list <VectorXd> path;\n planner.planPath(r, links, Vector2d(-M_PI+0.1, -M_PI+0.1), Vector2d(M_PI-0.1, M_PI-0.1), path);\n\n \/\/ Print the nodes\n RRT* rrt = planner.start_rrt;\n draw(rrt, NULL);\n\n}\n\n\/\/\/ The main thread\nint main () {\n\tdrawTwoLink();\n\tdrawThreeLink();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include namespace \"miniwin.h\"\nusing namespace miniwin;\nusing namespace std;\n\n\/\/Curve Level 0 -\n\/\/Curve Level 1 -^-\n\nstruct Punto \n{\n\tfloat x, y;\n};\n\n\/\/\nPunto rotar(const Punto& p, const Punto& cen, float da) {\n\tfloat dx = p.x - cen.x, dy = p.y - cen.y;\n\tfloat r = sqrt(dx*dx + dy*dy);\n\tfloat a = atan2(dy, dx);\n\ta -= da;\n\tPunto q = { cen.x + r * cos(a + da), cen.y + r * sin(a) };\n\treturn q;\n}\n\nPunto intermedio(const Punto& a, const Punto& b, float t) {\n\tPunto p = { a.x * (1-t) + b.x * t, a.y * (1-t) + b.y * t};\n}\n\nvoid Vonkoch(const Punto& p0, const Punto& p4, int nivel) {\n\tPunto p[5] = { p0, p0, p0, p0, p4};\n\tp[1] = intermedio(p[0], p[4], 1.0\/3.0);\n\tp[3] = intermedio(p[0], p[4], 2.0\/3.0);\n\tp[2] = rotar(p[3], p[1]. M_PI \/ 3.0);\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tlinea(p[i].x, p[i].y, p[i+1].x, p[i+1].y);\n\t}\n}\n\nint main()\n{\n\tvredimensiona(1260,440);\n\tPunto p0 = { 1240, 420}, p4 = { 1220. 420 };\n\tVonkoch(p0, p4, 1);\n\trefresca();\n\treturn 0;\n}<commit_msg>the method 'Vonkoch' is added new changes<commit_after>#include <cmath>\n#include namespace \"miniwin.h\"\nusing namespace miniwin;\nusing namespace std;\n\n\/\/Curve Level 0 -\n\/\/Curve Level 1 -^-\n\nstruct Punto \n{\n\tfloat x, y;\n};\n\n\/\/\nPunto rotar(const Punto& p, const Punto& cen, float da) {\n\tfloat dx = p.x - cen.x, dy = p.y - cen.y;\n\tfloat r = sqrt(dx*dx + dy*dy);\n\tfloat a = atan2(dy, dx);\n\ta -= da;\n\tPunto q = { cen.x + r * cos(a + da), cen.y + r * sin(a) };\n\treturn q;\n}\n\nPunto intermedio(const Punto& a, const Punto& b, float t) {\n\tPunto p = { a.x * (1-t) + b.x * t, a.y * (1-t) + b.y * t};\n}\n\nvoid Vonkoch(const Punto& p0, const Punto& p4, int nivel) {\n\tif(nivel <= 0) {\n\t\tlinea(p0.x, p0.y, p4.x, p4.y);\n\t} else {\n\t\tPunto p[5] = { p0, p0, p0, p0, p4};\n\t\tp[1] = intermedio(p[0], p[4], 1.0\/3.0);\n\t\tp[3] = intermedio(p[0], p[4], 2.0\/3.0);\n\t\tp[2] = rotar(p[3], p[1]. M_PI \/ 3.0);\n\t\tfor (int i = 0; i < 4; ++i)\n\t\t{\n\t\t\tif (nivel <= 1) {\n\t\t\t\tlinea(p[i].x, p[i].y, p[i+1].x, p[i+1].y);\n\t\t\t} else {\n\t\t\t\tVonkoch(p[i], p[i+1], nivel - 1);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main()\n{\n\tvredimensiona(1260,440);\n\tPunto p0 = { 1240, 420}, p4 = { 1220. 420 };\n\tVonkoch(p0, p4, 1);\n\trefresca();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2011, NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the names of NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT\n * HOLDERBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE\n *\/\n\n#include <Block.hpp>\n#include <BlockFactory.hpp>\n#include <cstdio>\n#include <Tweet.hpp>\n#include <vector>\n#include <WordRecord.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#ifdef _USE_JSMN_LIBRARY\n#include <jsmn.h>\n#endif\n#include <stdlib.h>\n#include <string.h>\n\nnamespace blockmon\n{\n\n \/**\n * Implements a block that receives tweets\n *\/\n class TweetFinder: public Block\n {\n private:\n int m_msg_recv;\n unsigned int m_reset;\n uint32_t m_msg_type;\n int num_gates;\n long sentMessages;\n long sentTuple;\n long ignored;\n int m_ingate_id;\n int *m_outgate_ids;\n std::vector<std::shared_ptr< WordRecord > > hashtag_batch;\n struct timeval lasttime;\n std::hash<std::string> hash_fn;\n long receivedTweets;\n timeval firsttime;\n #define ALLOC_TOKEN 10\n int allocated_tokens;\n #ifdef _USE_JSMN_LIBRARY\n jsmn_parser parser;\n jsmntok_t *tokens;\n #endif\n long hashtag_found;\n long tweet_found;\n public:\n\n \/**\n * @brief Constructor\n * @param name The name of the packet counter block\n * @param invocation Invocation type of the block (Indirect, Direct, Async)\n *\/\n TweetFinder(const std::string &name, invocation_type invocation)\n : Block(name, invocation),\n m_ingate_id(register_input_gate(\"in_word\")),\n receivedTweets(0),\n allocated_tokens(0),\n #ifdef \/* Copyright (c) 2011, NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni, Institut\n * Telecom\/Telecom Bretagne, ETH Zürich, INVEA-TECH a.s. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the names of NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni, Institut Telecom\/Telecom\n * Bretagne, ETH Zürich, INVEA-TECH a.s. nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT\n * HOLDERBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE\n *\/_USE_JSMN_LIBRARY\n tokens(NULL),\n #endif\n hashtag_found(0),\n tweet_found(0)\n {\n m_reset = 0;\n m_msg_type = type_to_id<Tweet>::id();\n }\n\n \/**\n * @brief Destructor\n *\/\n ~TweetFinder() {}\n\n \/**\n * @brief Configures the block.\n * @param n The configuration parameters\n *\/\n void _configure(const pugi::xml_node& n)\n {\n #ifndef _USE_JSMN_LIBRARY\n throw std::runtime_error(\"Twitter Trending was compiled without JSMN parser\");\n #endif\n \n pugi::xml_node gates_node=n.child(\"gates\");\n if(!gates_node)\n throw std::runtime_error(\"TweetFinder: missing node gates\");\n std::string gates_s=gates_node.attribute(\"number\").value();\n if(!gates_s.length())\n throw std::runtime_error(\"TweetFinder: missing attribute number\");\n \n num_gates = atoi(gates_s.c_str());\n std::string outgate_basename = \"out_hash\";\n m_outgate_ids = new int[num_gates];\n for(int i=0; i<num_gates; i++) {\n std::string ogate = outgate_basename + boost::lexical_cast<std::string>(i);\n m_outgate_ids[i] = register_output_gate(ogate.c_str());\n std::shared_ptr< WordRecord > m(new WordRecord());\n hashtag_batch.push_back(m);\n }\n }\n\n \/**\n * @brief Initialize the block\n *\/\n void _initialize()\n {}\n\n \/**\n * If the message received is not of type RawPacket throw an exception,\n * otherwise count it\n * @param m The message\n * @param index The index of the gate the message came on\n *\/\n void _receive_msg(std::shared_ptr<const Msg>&& m, int \/* index *\/)\n {\n if(m->type() != m_msg_type ) {\n throw std::runtime_error(\"TweetFinder::wrong message type\");\n }\n\n \n if(receivedTweets == 0) {\n gettimeofday(&firsttime, NULL);\n }\n\n #ifdef _USE_JSMN_LIBRARY\n const Tweet* msg_ptr = static_cast<const Tweet *>(m.get());\n\n \/\/ Parse the tweet\n jsmn_init(&parser);\n while(1) {\n const char* buf = msg_ptr->get_tweet().c_str();\n int r = jsmn_parse(&parser, buf, tokens, allocated_tokens);\n if(r == JSMN_SUCCESS) {\n \/\/ now loop to find the \"text\" part\n \/\/ we check one token over two, for every JSMN_STRING check if it\n \/\/ contains \"text\"\n if(tokens[0].type != JSMN_OBJECT) {\n ignored++;\n \/\/std::cerr << \"No object found in tweet\" << std::endl;\n break;\n }\n\n int size = tokens[0].size;\n\n int jj;\n for(jj = 0; jj < size; jj += 2) {\n if(tokens[1 + jj].type == JSMN_STRING && tokens[2 + jj].type == JSMN_STRING) {\n if(!strncmp(buf + tokens[1 + jj].start, \"text\", 4)) {\n tweet_found++;\n char tmpbuf[16384];\n int jcn;\n for(jcn = tokens[2 + jj].start; jcn < tokens[2 + jj].end; jcn++) {\n if(buf[jcn] == '#') {\n break;\n }\n }\n if(jcn < tokens[2 + jj].end) {\n hashtag_found++;\n int jcn_start = jcn;\n jcn++;\n int hashtag_len = 1;\n while(jcn < tokens[2 + jj].end) {\n if(!isalnum(buf[jcn]))\n break;\n jcn++;\n hashtag_len++;\n }\n strncpy(tmpbuf, buf + jcn_start, hashtag_len);\n tmpbuf[hashtag_len] = 0;\n size_t val_hash = hash_fn((tmpbuf));\n int ogate = val_hash % num_gates;\n hashtag_batch[ogate]->add_word(std::string(tmpbuf));\n#define BATH_SIZE 200\n if(hashtag_batch[ogate]->get_word_number() >= BATH_SIZE) {\n sentTuple++;\n sentMessages += BATH_SIZE;\n send_out_through(move(hashtag_batch[ogate]), m_outgate_ids[ogate]);\n std::shared_ptr< WordRecord > m(new WordRecord());\n hashtag_batch.at(ogate) = m;\n }\n\n }\n break;\n }\n }\n }\n break;\n } else if(r == JSMN_ERROR_NOMEM) {\n std::cerr << \"Reallocating tokens\" << std::endl;\n allocated_tokens += ALLOC_TOKEN;\n tokens = (jsmntok_t*) realloc(tokens, sizeof(jsmntok_t) * allocated_tokens);\n if(tokens == NULL) {\n throw std::runtime_error(\"Can not allocate memory\\n\");\n }\n continue;\n } else if(r == JSMN_ERROR_INVAL) {\n break;\n } else if(r == JSMN_ERROR_PART) {\n break;\n } else {\n throw std::runtime_error(\"Unknown error from jsmn\\n\");\n }\n }\n #endif\n \n receivedTweets++;\n m_msg_recv++;\n }\n };\n REGISTER_BLOCK(TweetFinder, \"TweetFinder\");\n}\n<commit_msg>Cleanup<commit_after>\/* Copyright (c) 2011, NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the names of NEC Europe Ltd, Consorzio Nazionale\n * Interuniversitario per le Telecomunicazioni nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT\n * HOLDERBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE\n *\/\n\n#include <Block.hpp>\n#include <BlockFactory.hpp>\n#include <cstdio>\n#include <Tweet.hpp>\n#include <vector>\n#include <WordRecord.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#ifdef _USE_JSMN_LIBRARY\n#include <jsmn.h>\n#endif\n#include <stdlib.h>\n#include <string.h>\n\nnamespace blockmon\n{\n\n \/**\n * Implements a block that receives tweets\n *\/\n class TweetFinder: public Block\n {\n private:\n int m_msg_recv;\n unsigned int m_reset;\n uint32_t m_msg_type;\n int num_gates;\n long sentMessages;\n long sentTuple;\n long ignored;\n int m_ingate_id;\n int *m_outgate_ids;\n std::vector<std::shared_ptr< WordRecord > > hashtag_batch;\n struct timeval lasttime;\n std::hash<std::string> hash_fn;\n long receivedTweets;\n timeval firsttime;\n #define ALLOC_TOKEN 10\n int allocated_tokens;\n #ifdef _USE_JSMN_LIBRARY\n jsmn_parser parser;\n jsmntok_t *tokens;\n #endif\n long hashtag_found;\n long tweet_found;\n public:\n\n \/**\n * @brief Constructor\n * @param name The name of the packet counter block\n * @param invocation Invocation type of the block (Indirect, Direct, Async)\n *\/\n TweetFinder(const std::string &name, invocation_type invocation)\n : Block(name, invocation),\n m_ingate_id(register_input_gate(\"in_word\")),\n receivedTweets(0),\n allocated_tokens(0),\n #ifdef _USE_JSMN_LIBRARY\n tokens(NULL),\n #endif\n hashtag_found(0),\n tweet_found(0)\n {\n m_reset = 0;\n m_msg_type = type_to_id<Tweet>::id();\n }\n\n \/**\n * @brief Destructor\n *\/\n ~TweetFinder() {}\n\n \/**\n * @brief Configures the block.\n * @param n The configuration parameters\n *\/\n void _configure(const pugi::xml_node& n)\n {\n #ifndef _USE_JSMN_LIBRARY\n throw std::runtime_error(\"Twitter Trending was compiled without JSMN parser\");\n #endif\n \n pugi::xml_node gates_node=n.child(\"gates\");\n if(!gates_node)\n throw std::runtime_error(\"TweetFinder: missing node gates\");\n std::string gates_s=gates_node.attribute(\"number\").value();\n if(!gates_s.length())\n throw std::runtime_error(\"TweetFinder: missing attribute number\");\n \n num_gates = atoi(gates_s.c_str());\n std::string outgate_basename = \"out_hash\";\n m_outgate_ids = new int[num_gates];\n for(int i=0; i<num_gates; i++) {\n std::string ogate = outgate_basename + boost::lexical_cast<std::string>(i);\n m_outgate_ids[i] = register_output_gate(ogate.c_str());\n std::shared_ptr< WordRecord > m(new WordRecord());\n hashtag_batch.push_back(m);\n }\n }\n\n \/**\n * @brief Initialize the block\n *\/\n void _initialize()\n {}\n\n \/**\n * If the message received is not of type RawPacket throw an exception,\n * otherwise count it\n * @param m The message\n * @param index The index of the gate the message came on\n *\/\n void _receive_msg(std::shared_ptr<const Msg>&& m, int \/* index *\/)\n {\n if(m->type() != m_msg_type ) {\n throw std::runtime_error(\"TweetFinder::wrong message type\");\n }\n\n \n if(receivedTweets == 0) {\n gettimeofday(&firsttime, NULL);\n }\n\n #ifdef _USE_JSMN_LIBRARY\n const Tweet* msg_ptr = static_cast<const Tweet *>(m.get());\n\n \/\/ Parse the tweet\n jsmn_init(&parser);\n while(1) {\n const char* buf = msg_ptr->get_tweet().c_str();\n int r = jsmn_parse(&parser, buf, tokens, allocated_tokens);\n if(r == JSMN_SUCCESS) {\n \/\/ now loop to find the \"text\" part\n \/\/ we check one token over two, for every JSMN_STRING check if it\n \/\/ contains \"text\"\n if(tokens[0].type != JSMN_OBJECT) {\n ignored++;\n \/\/std::cerr << \"No object found in tweet\" << std::endl;\n break;\n }\n\n int size = tokens[0].size;\n\n int jj;\n for(jj = 0; jj < size; jj += 2) {\n if(tokens[1 + jj].type == JSMN_STRING && tokens[2 + jj].type == JSMN_STRING) {\n if(!strncmp(buf + tokens[1 + jj].start, \"text\", 4)) {\n tweet_found++;\n char tmpbuf[16384];\n int jcn;\n for(jcn = tokens[2 + jj].start; jcn < tokens[2 + jj].end; jcn++) {\n if(buf[jcn] == '#') {\n break;\n }\n }\n if(jcn < tokens[2 + jj].end) {\n hashtag_found++;\n int jcn_start = jcn;\n jcn++;\n int hashtag_len = 1;\n while(jcn < tokens[2 + jj].end) {\n if(!isalnum(buf[jcn]))\n break;\n jcn++;\n hashtag_len++;\n }\n strncpy(tmpbuf, buf + jcn_start, hashtag_len);\n tmpbuf[hashtag_len] = 0;\n size_t val_hash = hash_fn((tmpbuf));\n int ogate = val_hash % num_gates;\n hashtag_batch[ogate]->add_word(std::string(tmpbuf));\n#define BATH_SIZE 200\n if(hashtag_batch[ogate]->get_word_number() >= BATH_SIZE) {\n sentTuple++;\n sentMessages += BATH_SIZE;\n send_out_through(move(hashtag_batch[ogate]), m_outgate_ids[ogate]);\n std::shared_ptr< WordRecord > m(new WordRecord());\n hashtag_batch.at(ogate) = m;\n }\n\n }\n break;\n }\n }\n }\n break;\n } else if(r == JSMN_ERROR_NOMEM) {\n std::cerr << \"Reallocating tokens\" << std::endl;\n allocated_tokens += ALLOC_TOKEN;\n tokens = (jsmntok_t*) realloc(tokens, sizeof(jsmntok_t) * allocated_tokens);\n if(tokens == NULL) {\n throw std::runtime_error(\"Can not allocate memory\\n\");\n }\n continue;\n } else if(r == JSMN_ERROR_INVAL) {\n break;\n } else if(r == JSMN_ERROR_PART) {\n break;\n } else {\n throw std::runtime_error(\"Unknown error from jsmn\\n\");\n }\n }\n #endif\n \n receivedTweets++;\n m_msg_recv++;\n }\n };\n REGISTER_BLOCK(TweetFinder, \"TweetFinder\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmdir.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-04-11 15:54:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SVX_FRMDIR_HXX\n#define _SVX_FRMDIR_HXX\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Defines possible text directions in frames. *\/\nenum SvxFrameDirection\n{\n \/** Horizontal, from left to right, from top to bottom\n (typical for western languages). *\/\n FRMDIR_HORI_LEFT_TOP,\n\n \/** Horizontal, from right to left, from top to bottom\n (typical for ararbic\/hebrew languages). *\/\n FRMDIR_HORI_RIGHT_TOP,\n\n \/** Vertical, from top to bottom, from right to left\n (typical for asian languages). *\/\n FRMDIR_VERT_TOP_RIGHT,\n\n \/** Vertical, from top to bottom, from left to right\n (typical for mongol language). *\/\n FRMDIR_VERT_TOP_LEFT,\n\n \/** Use the value from the environment, can only be used in frames. *\/\n FRMDIR_ENVIRONMENT\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n#endif \/\/ #ifndef _SVX_FRMDIR_HXX\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.466); FILE MERGED 2008\/03\/31 14:18:12 rt 1.2.466.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmdir.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SVX_FRMDIR_HXX\n#define _SVX_FRMDIR_HXX\n\n\/\/ ----------------------------------------------------------------------------\n\n\/** Defines possible text directions in frames. *\/\nenum SvxFrameDirection\n{\n \/** Horizontal, from left to right, from top to bottom\n (typical for western languages). *\/\n FRMDIR_HORI_LEFT_TOP,\n\n \/** Horizontal, from right to left, from top to bottom\n (typical for ararbic\/hebrew languages). *\/\n FRMDIR_HORI_RIGHT_TOP,\n\n \/** Vertical, from top to bottom, from right to left\n (typical for asian languages). *\/\n FRMDIR_VERT_TOP_RIGHT,\n\n \/** Vertical, from top to bottom, from left to right\n (typical for mongol language). *\/\n FRMDIR_VERT_TOP_LEFT,\n\n \/** Use the value from the environment, can only be used in frames. *\/\n FRMDIR_ENVIRONMENT\n};\n\n\/\/ ----------------------------------------------------------------------------\n\n#endif \/\/ #ifndef _SVX_FRMDIR_HXX\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"dire_maul.h\"\n#include \"InstanceScript.h\"\n#include \"ScriptMgr.h\"\n\nclass instance_dire_maul : public InstanceMapScript\n{\npublic:\n instance_dire_maul() : InstanceMapScript(\"instance_dire_maul\", 429) { }\n\n struct instance_dire_maul_InstanceMapScript : public InstanceScript\n {\n instance_dire_maul_InstanceMapScript(Map* map) : InstanceScript(map) { }\n\n void Initialize() override\n {\n _eastWingProgress = 0;\n _westWingProgress = 0;\n _pylonsState = 0;\n _northWingProgress = 0;\n _northWingBosses = 0;\n }\n\n void OnCreatureCreate(Creature* creature) override\n {\n switch (creature->GetEntry())\n {\n case NPC_IMMOL_THAR:\n _immoltharGUID = creature->GetGUID();\n break;\n case NPC_HIGHBORNE_SUMMONER:\n if (_pylonsState == ALL_PYLONS_OFF)\n creature->DespawnOrUnsummon(5000);\n break;\n }\n }\n\n void OnGameObjectCreate(GameObject* gameobject) override\n {\n switch (gameobject->GetEntry())\n {\n case GO_DIRE_MAUL_FORCE_FIELD:\n if (_pylonsState == ALL_PYLONS_OFF)\n gameobject->SetGoState(GO_STATE_ACTIVE);\n break;\n case GO_GORDOK_TRIBUTE:\n {\n uint32 fullLootMode = 0x3F;\n for (uint32 i = 0; i < _northWingBosses; ++i)\n fullLootMode >>= 1;\n\n gameobject->SetLootMode(fullLootMode);\n break;\n }\n }\n }\n\n void SetData(uint32 type, uint32 data) override\n {\n switch (type)\n {\n case TYPE_EAST_WING_PROGRESS:\n _eastWingProgress = data;\n instance->LoadGrid(-56.59f, -269.12f);\n break;\n case TYPE_WEST_WING_PROGRESS:\n _westWingProgress = data;\n instance->LoadGrid(132.626f, 625.913f);\n break;\n case TYPE_NORTH_WING_PROGRESS:\n _northWingProgress = data;\n break;\n case TYPE_NORTH_WING_BOSSES:\n _northWingBosses |= (1 << _northWingBosses);\n break;\n case TYPE_PYLONS_STATE:\n if (_pylonsState & data)\n return;\n _pylonsState |= data;\n if (_pylonsState == ALL_PYLONS_OFF) \/\/ all five active, 31\n {\n instance->LoadGrid(-38.08f, 812.44f);\n if (Creature* immol = instance->GetCreature(_immoltharGUID))\n {\n immol->setActive(true);\n immol->GetAI()->SetData(1, 1);\n }\n }\n break;\n }\n\n SaveToDB();\n }\n\n uint32 GetData(uint32 type) const override\n {\n if (type == TYPE_EAST_WING_PROGRESS)\n return _eastWingProgress;\n else if (type == TYPE_WEST_WING_PROGRESS)\n return _westWingProgress;\n else if (type == TYPE_NORTH_WING_PROGRESS)\n return _northWingProgress;\n\n return 0;\n }\n\n std::string GetSaveData() override\n {\n std::ostringstream saveStream;\n saveStream << \"D M \" << _eastWingProgress << ' ' << _westWingProgress << ' ' << _pylonsState << ' ' << _northWingProgress << ' ' << _northWingBosses;\n return saveStream.str();\n }\n\n void Load(const char* in) override\n {\n if (!in)\n return;\n\n char dataHead1, dataHead2;\n std::istringstream loadStream(in);\n loadStream >> dataHead1 >> dataHead2;\n if (dataHead1 == 'D' && dataHead2 == 'M')\n {\n loadStream >> _eastWingProgress;\n loadStream >> _westWingProgress;\n loadStream >> _pylonsState;\n loadStream >> _northWingProgress;\n loadStream >> _northWingBosses;\n }\n }\n\n private:\n uint32 _eastWingProgress;\n uint32 _westWingProgress;\n uint32 _pylonsState;\n uint32 _northWingProgress;\n uint32 _northWingBosses;\n\n ObjectGuid _immoltharGUID;\n };\n\n InstanceScript* GetInstanceScript(InstanceMap* map) const override\n {\n return new instance_dire_maul_InstanceMapScript(map);\n }\n};\n\nvoid AddSC_instance_dire_maul()\n{\n new instance_dire_maul();\n}\n<commit_msg>fix(Scripts\/DireMaul): immolthar and adds are now immune to combat until the pylons are activated (#9007)<commit_after>\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"dire_maul.h\"\n#include \"InstanceScript.h\"\n#include \"ScriptMgr.h\"\n\nclass instance_dire_maul : public InstanceMapScript\n{\npublic:\n instance_dire_maul() : InstanceMapScript(\"instance_dire_maul\", 429) { }\n\n struct instance_dire_maul_InstanceMapScript : public InstanceScript\n {\n instance_dire_maul_InstanceMapScript(Map* map) : InstanceScript(map) { }\n\n void Initialize() override\n {\n _eastWingProgress = 0;\n _westWingProgress = 0;\n _pylonsState = 0;\n _northWingProgress = 0;\n _northWingBosses = 0;\n HighborneSummoners.clear();\n }\n\n void OnCreatureCreate(Creature* creature) override\n {\n switch (creature->GetEntry())\n {\n case NPC_IMMOL_THAR:\n _immoltharGUID = creature->GetGUID();\n if (_pylonsState == ALL_PYLONS_OFF)\n {\n creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);\n }\n else\n {\n creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);\n }\n break;\n case NPC_HIGHBORNE_SUMMONER:\n if (_pylonsState == ALL_PYLONS_OFF)\n {\n creature->DespawnOrUnsummon(5000);\n }\n else\n {\n creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);\n }\n HighborneSummoners.push_back(creature->GetGUID());\n break;\n }\n }\n\n void OnGameObjectCreate(GameObject* gameobject) override\n {\n switch (gameobject->GetEntry())\n {\n case GO_DIRE_MAUL_FORCE_FIELD:\n if (_pylonsState == ALL_PYLONS_OFF)\n gameobject->SetGoState(GO_STATE_ACTIVE);\n break;\n case GO_GORDOK_TRIBUTE:\n {\n uint32 fullLootMode = 0x3F;\n for (uint32 i = 0; i < _northWingBosses; ++i)\n fullLootMode >>= 1;\n\n gameobject->SetLootMode(fullLootMode);\n break;\n }\n }\n }\n\n void SetData(uint32 type, uint32 data) override\n {\n switch (type)\n {\n case TYPE_EAST_WING_PROGRESS:\n _eastWingProgress = data;\n instance->LoadGrid(-56.59f, -269.12f);\n break;\n case TYPE_WEST_WING_PROGRESS:\n _westWingProgress = data;\n instance->LoadGrid(132.626f, 625.913f);\n break;\n case TYPE_NORTH_WING_PROGRESS:\n _northWingProgress = data;\n break;\n case TYPE_NORTH_WING_BOSSES:\n _northWingBosses |= (1 << _northWingBosses);\n break;\n case TYPE_PYLONS_STATE:\n if (_pylonsState & data)\n return;\n _pylonsState |= data;\n if (_pylonsState == ALL_PYLONS_OFF) \/\/ all five active, 31\n {\n instance->LoadGrid(-38.08f, 812.44f);\n if (Creature* immol = instance->GetCreature(_immoltharGUID))\n {\n immol->setActive(true);\n immol->GetAI()->SetData(1, 1);\n immol->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);\n }\n for (const auto& guid : HighborneSummoners)\n {\n if (Creature* summoner = instance->GetCreature(guid))\n {\n summoner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);\n }\n }\n }\n break;\n }\n\n SaveToDB();\n }\n\n uint32 GetData(uint32 type) const override\n {\n if (type == TYPE_EAST_WING_PROGRESS)\n return _eastWingProgress;\n else if (type == TYPE_WEST_WING_PROGRESS)\n return _westWingProgress;\n else if (type == TYPE_NORTH_WING_PROGRESS)\n return _northWingProgress;\n\n return 0;\n }\n\n std::string GetSaveData() override\n {\n std::ostringstream saveStream;\n saveStream << \"D M \" << _eastWingProgress << ' ' << _westWingProgress << ' ' << _pylonsState << ' ' << _northWingProgress << ' ' << _northWingBosses;\n return saveStream.str();\n }\n\n void Load(const char* in) override\n {\n if (!in)\n return;\n\n char dataHead1, dataHead2;\n std::istringstream loadStream(in);\n loadStream >> dataHead1 >> dataHead2;\n if (dataHead1 == 'D' && dataHead2 == 'M')\n {\n loadStream >> _eastWingProgress;\n loadStream >> _westWingProgress;\n loadStream >> _pylonsState;\n loadStream >> _northWingProgress;\n loadStream >> _northWingBosses;\n }\n }\n\n private:\n uint32 _eastWingProgress;\n uint32 _westWingProgress;\n uint32 _pylonsState;\n uint32 _northWingProgress;\n uint32 _northWingBosses;\n\n ObjectGuid _immoltharGUID;\n std::vector<ObjectGuid> HighborneSummoners;\n };\n\n InstanceScript* GetInstanceScript(InstanceMap* map) const override\n {\n return new instance_dire_maul_InstanceMapScript(map);\n }\n};\n\nvoid AddSC_instance_dire_maul()\n{\n new instance_dire_maul();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The GraphicsFuzz Project Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Entry point on Android\n\n#include <android_native_app_glue.h>\n#include \"vulkan_worker.h\"\n#include \"platform.h\"\n\n#include <assert.h>\n#include <string>\n#include <sstream>\n#include <iostream>\n\ntypedef struct AppData {\n VulkanWorker *vulkan_worker;\n PlatformData *platform_data;\n FILE *vertex_file;\n FILE *fragment_file;\n FILE *uniform_file;\n} AppData;\n\nvoid ProcessAppCmd (struct android_app *app, int32_t cmd) {\n AppData *app_data = (AppData *)app->userData;\n switch (cmd) {\n case APP_CMD_INIT_WINDOW:\n if (FLAGS_info) {\n log(\"DUMP INFO\");\n VulkanWorker::DumpWorkerInfo(\"\/sdcard\/graphicsfuzz\/worker_info.json\");\n ANativeActivity_finish(app->activity);\n break;\n }\n\n if (app_data->vulkan_worker == NULL) {\n log(\"Create vulkan worker\");\n assert(app->window != nullptr);\n app_data->platform_data->window = app->window;\n app_data->vulkan_worker = new VulkanWorker(app_data->platform_data);\n assert(app_data->vertex_file != nullptr);\n assert(app_data->fragment_file != nullptr);\n assert(app_data->uniform_file != nullptr);\n app_data->vulkan_worker->Render(app_data->vertex_file, app_data->fragment_file, app_data->uniform_file, FLAGS_skip_render);\n ANativeActivity_finish(app->activity);\n }\n break;\n\n case APP_CMD_PAUSE:\n case APP_CMD_STOP:\n case APP_CMD_DESTROY:\n ANativeActivity_finish(app->activity);\n break;\n }\n return;\n}\n\nint32_t ProcessInputEvent (struct android_app *app, AInputEvent *event) {\n return 0;\n}\n\n\/\/ Extract command line arguments from the extra of Android intent:\n\/\/ adb shell am start -n <...> -e gfz \"'list of arguments to be extracted'\"\n\/\/ Note the quoting: from host terminal adb command, we need to double-escape\n\/\/ the extra args string, as it is first quoted by host terminal emulator\n\/\/ (e.g. bash), then it must be quoted for the on-device shell.\nvoid GetGflagsArgs(struct android_app* state, int *argc, char ***argv) {\n assert(argc != nullptr);\n assert(argv != nullptr);\n assert(*argv == nullptr);\n\n \/\/ The extra flag to indicate GraphicsFuzz arguments\n const char *intent_flag = \"gfz\";\n\n JavaVM* java_vm = state->activity->vm;\n JNIEnv* jni_env;\n assert(java_vm->AttachCurrentThread(&jni_env, nullptr) == JNI_OK);\n jobject activity_clazz = state->activity->clazz;\n jmethodID get_intent_method_id = jni_env->GetMethodID(jni_env->GetObjectClass(activity_clazz), \"getIntent\", \"()Landroid\/content\/Intent;\");\n jobject intent = jni_env->CallObjectMethod(activity_clazz, get_intent_method_id);\n jmethodID get_string_extra_method_id = jni_env->GetMethodID(jni_env->GetObjectClass(intent), \"getStringExtra\", \"(Ljava\/lang\/String;)Ljava\/lang\/String;\");\n jvalue get_string_extra_args;\n get_string_extra_args.l = jni_env->NewStringUTF(intent_flag);\n jstring extra_jstring = static_cast<jstring>(jni_env->CallObjectMethodA(intent, get_string_extra_method_id, &get_string_extra_args));\n\n std::string extra_string;\n if (extra_jstring) {\n const char* extra_cstr = jni_env->GetStringUTFChars(extra_jstring, nullptr);\n log(\"EXTRA_CSTR: %s\", extra_cstr);\n extra_string = extra_cstr;\n jni_env->ReleaseStringUTFChars(extra_jstring, extra_cstr);\n jni_env->DeleteLocalRef(extra_jstring);\n }\n\n jni_env->DeleteLocalRef(get_string_extra_args.l);\n jni_env->DeleteLocalRef(intent);\n java_vm->DetachCurrentThread();\n\n \/\/ Prepare arguments with a value for argv[0], as gflags expects\n std::vector<std::string> args;\n args.push_back(\"android_vkworker\"); \/\/ required but ignored by gflags\n\n \/\/ Split extra_string\n std::stringstream ss(extra_string);\n std::string arg;\n while (std::getline(ss, arg, ' ')) {\n if (!arg.empty()) {\n args.push_back(arg);\n }\n }\n\n \/\/ Convert to argc\/argv, as gflags expects\n *argc = (int)(args.size());\n *argv = (char **)malloc(*argc * sizeof(char *));\n assert(*argv != nullptr);\n for (int i = 0; i < *argc; i++) {\n (*argv)[i] = strdup(args[i].c_str());\n }\n}\n\nvoid FreeGflagsArgs(int argc, char **argv) {\n for (int i = 0; i < argc; i++) {\n free(argv[i]);\n }\n free(argv);\n}\n\nvoid android_main(struct android_app* state) {\n\n \/\/ New default values\n FLAGS_sanity_before = \"\/sdcard\/graphicsfuzz\/sanity_before.png\";\n FLAGS_sanity_after = \"\/sdcard\/graphicsfuzz\/sanity_after.png\";\n FLAGS_png_template = \"\/sdcard\/graphicsfuzz\/image\";\n\n int argc = 0;\n char **argv = nullptr;\n GetGflagsArgs(state, &argc, &argv);\n gflags::SetUsageMessage(\"GraphicsFuzz Vulkan worker http:\/\/github.com\/google\/graphicsfuzz\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n AppData *app_data = new AppData;\n app_data->vulkan_worker = nullptr;\n state->userData = (void *)app_data;\n\n PlatformData platform_data = {};\n \/\/ state->window will be ready later, when processing APP_CMD_INIT_WINDOW in processAppCmd()\n app_data->platform_data = &platform_data;\n\n \/\/ Android: setup main callbacks\n state->onAppCmd = ProcessAppCmd;\n state->onInputEvent = ProcessInputEvent;\n\n if (!FLAGS_info) {\n log(\"NOT DUMP INFO\");\n app_data->vertex_file = fopen(\"\/sdcard\/graphicsfuzz\/test.vert.spv\", \"r\");\n assert(app_data->vertex_file != nullptr);\n\n app_data->fragment_file = fopen(\"\/sdcard\/graphicsfuzz\/test.frag.spv\", \"r\");\n assert(app_data->fragment_file != nullptr);\n\n app_data->uniform_file = fopen(\"\/sdcard\/graphicsfuzz\/test.json\", \"r\");\n assert(app_data->uniform_file != nullptr);\n }\n\n \/\/ Android: loop on things to do\n while (1) {\n int events;\n int timeoutMillis = 0;\n struct android_poll_source *source;\n\n while ((ALooper_pollOnce(timeoutMillis, nullptr, &events, (void **)&source)) >= 0) {\n\n if (source != nullptr) {\n source->process(state, source);\n }\n\n if (state->destroyRequested != 0) {\n \/\/ Terminate\n if (app_data->vulkan_worker != nullptr) {\n delete app_data->vulkan_worker;\n }\n if (app_data->vertex_file != nullptr) {\n fclose(app_data->vertex_file);\n }\n if (app_data->fragment_file != nullptr) {\n fclose(app_data->fragment_file);\n }\n if (app_data->uniform_file != nullptr) {\n fclose(app_data->uniform_file);\n }\n delete app_data;\n\n log(\"\\nANDROID TERMINATE OK\\n\");\n\n FILE *done = fopen(\"\/sdcard\/graphicsfuzz\/DONE\", \"w\");\n assert(done != nullptr);\n fprintf(done, \"DONE\\n\");\n fclose(done);\n\n FreeGflagsArgs(argc, argv);\n\n return;\n }\n }\n }\n}\n<commit_msg>Reset command line flags default values in Android (#128)<commit_after>\/\/ Copyright 2018 The GraphicsFuzz Project Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Entry point on Android\n\n#include <android_native_app_glue.h>\n#include \"vulkan_worker.h\"\n#include \"platform.h\"\n\n#include <assert.h>\n#include <string>\n#include <sstream>\n#include <iostream>\n\ntypedef struct AppData {\n VulkanWorker *vulkan_worker;\n PlatformData *platform_data;\n FILE *vertex_file;\n FILE *fragment_file;\n FILE *uniform_file;\n} AppData;\n\nvoid ProcessAppCmd (struct android_app *app, int32_t cmd) {\n AppData *app_data = (AppData *)app->userData;\n switch (cmd) {\n case APP_CMD_INIT_WINDOW:\n if (FLAGS_info) {\n log(\"DUMP INFO\");\n VulkanWorker::DumpWorkerInfo(\"\/sdcard\/graphicsfuzz\/worker_info.json\");\n ANativeActivity_finish(app->activity);\n break;\n }\n\n if (app_data->vulkan_worker == NULL) {\n log(\"Create vulkan worker\");\n assert(app->window != nullptr);\n app_data->platform_data->window = app->window;\n app_data->vulkan_worker = new VulkanWorker(app_data->platform_data);\n assert(app_data->vertex_file != nullptr);\n assert(app_data->fragment_file != nullptr);\n assert(app_data->uniform_file != nullptr);\n app_data->vulkan_worker->Render(app_data->vertex_file, app_data->fragment_file, app_data->uniform_file, FLAGS_skip_render);\n ANativeActivity_finish(app->activity);\n }\n break;\n\n case APP_CMD_PAUSE:\n case APP_CMD_STOP:\n case APP_CMD_DESTROY:\n ANativeActivity_finish(app->activity);\n break;\n }\n return;\n}\n\nint32_t ProcessInputEvent (struct android_app *app, AInputEvent *event) {\n return 0;\n}\n\n\/\/ Extract command line arguments from the extra of Android intent:\n\/\/ adb shell am start -n <...> -e gfz \"'list of arguments to be extracted'\"\n\/\/ Note the quoting: from host terminal adb command, we need to double-escape\n\/\/ the extra args string, as it is first quoted by host terminal emulator\n\/\/ (e.g. bash), then it must be quoted for the on-device shell.\nvoid GetGflagsArgs(struct android_app* state, int *argc, char ***argv) {\n assert(argc != nullptr);\n assert(argv != nullptr);\n assert(*argv == nullptr);\n\n \/\/ The extra flag to indicate GraphicsFuzz arguments\n const char *intent_flag = \"gfz\";\n\n JavaVM* java_vm = state->activity->vm;\n JNIEnv* jni_env;\n assert(java_vm->AttachCurrentThread(&jni_env, nullptr) == JNI_OK);\n jobject activity_clazz = state->activity->clazz;\n jmethodID get_intent_method_id = jni_env->GetMethodID(jni_env->GetObjectClass(activity_clazz), \"getIntent\", \"()Landroid\/content\/Intent;\");\n jobject intent = jni_env->CallObjectMethod(activity_clazz, get_intent_method_id);\n jmethodID get_string_extra_method_id = jni_env->GetMethodID(jni_env->GetObjectClass(intent), \"getStringExtra\", \"(Ljava\/lang\/String;)Ljava\/lang\/String;\");\n jvalue get_string_extra_args;\n get_string_extra_args.l = jni_env->NewStringUTF(intent_flag);\n jstring extra_jstring = static_cast<jstring>(jni_env->CallObjectMethodA(intent, get_string_extra_method_id, &get_string_extra_args));\n\n std::string extra_string;\n if (extra_jstring) {\n const char* extra_cstr = jni_env->GetStringUTFChars(extra_jstring, nullptr);\n log(\"EXTRA_CSTR: %s\", extra_cstr);\n extra_string = extra_cstr;\n jni_env->ReleaseStringUTFChars(extra_jstring, extra_cstr);\n jni_env->DeleteLocalRef(extra_jstring);\n }\n\n jni_env->DeleteLocalRef(get_string_extra_args.l);\n jni_env->DeleteLocalRef(intent);\n java_vm->DetachCurrentThread();\n\n \/\/ Prepare arguments with a value for argv[0], as gflags expects\n std::vector<std::string> args;\n args.push_back(\"android_vkworker\"); \/\/ required but ignored by gflags\n\n \/\/ Split extra_string\n std::stringstream ss(extra_string);\n std::string arg;\n while (std::getline(ss, arg, ' ')) {\n if (!arg.empty()) {\n args.push_back(arg);\n }\n }\n\n \/\/ Convert to argc\/argv, as gflags expects\n *argc = (int)(args.size());\n *argv = (char **)malloc(*argc * sizeof(char *));\n assert(*argv != nullptr);\n for (int i = 0; i < *argc; i++) {\n (*argv)[i] = strdup(args[i].c_str());\n }\n}\n\nvoid FreeGflagsArgs(int argc, char **argv) {\n for (int i = 0; i < argc; i++) {\n free(argv[i]);\n }\n free(argv);\n}\n\nvoid android_main(struct android_app* state) {\n\n \/\/ Reset all default values, as any change may survive the exiting of this\n \/\/ android_main() function and still be set when android_main() is called\n \/\/ again.\n FLAGS_sanity_before = \"\/sdcard\/graphicsfuzz\/sanity_before.png\";\n FLAGS_sanity_after = \"\/sdcard\/graphicsfuzz\/sanity_after.png\";\n FLAGS_png_template = \"\/sdcard\/graphicsfuzz\/image\";\n FLAGS_info = false;\n FLAGS_skip_render = false;\n FLAGS_num_render = 3;\n\n int argc = 0;\n char **argv = nullptr;\n GetGflagsArgs(state, &argc, &argv);\n gflags::SetUsageMessage(\"GraphicsFuzz Vulkan worker http:\/\/github.com\/google\/graphicsfuzz\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n AppData *app_data = new AppData;\n app_data->vulkan_worker = nullptr;\n state->userData = (void *)app_data;\n\n PlatformData platform_data = {};\n \/\/ state->window will be ready later, when processing APP_CMD_INIT_WINDOW in processAppCmd()\n app_data->platform_data = &platform_data;\n\n \/\/ Android: setup main callbacks\n state->onAppCmd = ProcessAppCmd;\n state->onInputEvent = ProcessInputEvent;\n\n if (!FLAGS_info) {\n log(\"NOT DUMP INFO\");\n app_data->vertex_file = fopen(\"\/sdcard\/graphicsfuzz\/test.vert.spv\", \"r\");\n assert(app_data->vertex_file != nullptr);\n\n app_data->fragment_file = fopen(\"\/sdcard\/graphicsfuzz\/test.frag.spv\", \"r\");\n assert(app_data->fragment_file != nullptr);\n\n app_data->uniform_file = fopen(\"\/sdcard\/graphicsfuzz\/test.json\", \"r\");\n assert(app_data->uniform_file != nullptr);\n }\n\n \/\/ Android: loop on things to do\n while (1) {\n int events;\n int timeoutMillis = 0;\n struct android_poll_source *source;\n\n while ((ALooper_pollOnce(timeoutMillis, nullptr, &events, (void **)&source)) >= 0) {\n\n if (source != nullptr) {\n source->process(state, source);\n }\n\n if (state->destroyRequested != 0) {\n \/\/ Terminate\n if (app_data->vulkan_worker != nullptr) {\n delete app_data->vulkan_worker;\n }\n if (app_data->vertex_file != nullptr) {\n fclose(app_data->vertex_file);\n }\n if (app_data->fragment_file != nullptr) {\n fclose(app_data->fragment_file);\n }\n if (app_data->uniform_file != nullptr) {\n fclose(app_data->uniform_file);\n }\n delete app_data;\n\n log(\"\\nANDROID TERMINATE OK\\n\");\n\n FILE *done = fopen(\"\/sdcard\/graphicsfuzz\/DONE\", \"w\");\n assert(done != nullptr);\n fprintf(done, \"DONE\\n\");\n fclose(done);\n\n FreeGflagsArgs(argc, argv);\n\n return;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test libc++'s implementation of align_val_t, and the relevant new\/delete\n\/\/ overloads in all dialects when -faligned-allocation is present.\n\n\/\/ Libc++ defers to the underlying MSVC library to provide the new\/delete\n\/\/ definitions, which does not yet provide aligned allocation\n\/\/ XFAIL: LIBCXX-WINDOWS-FIXME\n\n\/\/ AppleClang 10 (and older) will trigger an availability error when the deployment\n\/\/ target does not support aligned allocation, even if we pass `-faligned-allocation`.\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.13\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.12\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.11\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.10\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.9\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.8\n\/\/ XFAIL: apple-clang-10 && availability=macosx10.7\n\n\/\/ The dylibs shipped before macosx10.14 do not contain the aligned allocation\n\/\/ functions, so trying to force using those with -faligned-allocation results\n\/\/ in a link error.\n\/\/ XFAIL: with_system_cxx_lib=macosx10.13\n\/\/ XFAIL: with_system_cxx_lib=macosx10.12\n\/\/ XFAIL: with_system_cxx_lib=macosx10.11\n\/\/ XFAIL: with_system_cxx_lib=macosx10.10\n\/\/ XFAIL: with_system_cxx_lib=macosx10.9\n\/\/ XFAIL: with_system_cxx_lib=macosx10.8\n\/\/ XFAIL: with_system_cxx_lib=macosx10.7\n\n\/\/ The test will fail on deployment targets that do not support sized deallocation.\n\/\/ XFAIL: availability=macosx10.11\n\/\/ XFAIL: availability=macosx10.10\n\/\/ XFAIL: availability=macosx10.9\n\/\/ XFAIL: availability=macosx10.8\n\/\/ XFAIL: availability=macosx10.7\n\n\/\/ XFAIL: sanitizer-new-delete, ubsan\n\n\/\/ GCC doesn't support the aligned-allocation flags.\n\/\/ XFAIL: gcc\n\n\/\/ RUN: %build -faligned-allocation -fsized-deallocation\n\/\/ RUN: %run\n\/\/ RUN: %build -faligned-allocation -fno-sized-deallocation -DNO_SIZE\n\/\/ RUN: %run\n\/\/ RUN: %build -fno-aligned-allocation -fsized-deallocation -DNO_ALIGN\n\/\/ RUN: %run\n\/\/ RUN: %build -fno-aligned-allocation -fno-sized-deallocation -DNO_ALIGN -DNO_SIZE\n\/\/ RUN: %run\n\n#include <new>\n#include <typeinfo>\n#include <string>\n#include <cassert>\n\n#include \"test_macros.h\"\n\nstruct alloc_stats {\n alloc_stats() { reset(); }\n\n int aligned_sized_called;\n int aligned_called;\n int sized_called;\n int plain_called;\n int last_size;\n int last_align;\n\n void reset() {\n aligned_sized_called = aligned_called = sized_called = plain_called = 0;\n last_align = last_size = -1;\n }\n\n bool expect_plain() const {\n assert(aligned_sized_called == 0);\n assert(aligned_called == 0);\n assert(sized_called == 0);\n assert(last_size == -1);\n assert(last_align == -1);\n return plain_called == 1;\n }\n\n bool expect_size(int n) const {\n assert(plain_called == 0);\n assert(aligned_sized_called == 0);\n assert(aligned_called == 0);\n assert(last_size == n);\n assert(last_align == -1);\n return sized_called == 1;\n }\n\n bool expect_align(int a) const {\n assert(plain_called == 0);\n assert(aligned_sized_called == 0);\n assert(sized_called == 0);\n assert(last_size == -1);\n assert(last_align == a);\n return aligned_called == 1;\n }\n\n bool expect_size_align(int n, int a) const {\n assert(plain_called == 0);\n assert(sized_called == 0);\n assert(aligned_called == 0);\n assert(last_size == n);\n assert(last_align == a);\n return aligned_sized_called == 1;\n }\n};\nalloc_stats stats;\n\nvoid operator delete(void* p)TEST_NOEXCEPT {\n ::free(p);\n stats.plain_called++;\n stats.last_size = stats.last_align = -1;\n}\n\n#ifndef NO_SIZE\nvoid operator delete(void* p, size_t n)TEST_NOEXCEPT {\n ::free(p);\n stats.sized_called++;\n stats.last_size = n;\n stats.last_align = -1;\n}\n#endif\n\n#ifndef NO_ALIGN\nvoid operator delete(void* p, std::align_val_t a)TEST_NOEXCEPT {\n ::free(p);\n stats.aligned_called++;\n stats.last_align = static_cast<int>(a);\n stats.last_size = -1;\n}\n\nvoid operator delete(void* p, size_t n, std::align_val_t a)TEST_NOEXCEPT {\n ::free(p);\n stats.aligned_sized_called++;\n stats.last_align = static_cast<int>(a);\n stats.last_size = n;\n}\n#endif\n\nvoid test_libcpp_dealloc() {\n void* p = nullptr;\n size_t over_align_val = TEST_ALIGNOF(std::max_align_t) * 2;\n size_t under_align_val = TEST_ALIGNOF(int);\n size_t with_size_val = 2;\n\n {\n std::__libcpp_deallocate_unsized(p, under_align_val);\n assert(stats.expect_plain());\n }\n stats.reset();\n\n#if defined(NO_SIZE) && defined(NO_ALIGN)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_plain());\n }\n stats.reset();\n#elif defined(NO_SIZE)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_align(over_align_val));\n }\n stats.reset();\n#elif defined(NO_ALIGN)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_size(with_size_val));\n }\n stats.reset();\n#else\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_size_align(with_size_val, over_align_val));\n }\n stats.reset();\n {\n std::__libcpp_deallocate_unsized(p, over_align_val);\n assert(stats.expect_align(over_align_val));\n }\n stats.reset();\n {\n std::__libcpp_deallocate(p, with_size_val, under_align_val);\n assert(stats.expect_size(with_size_val));\n }\n stats.reset();\n#endif\n}\n\nstruct TEST_ALIGNAS(128) AlignedType {\n AlignedType() : elem(0) {}\n TEST_ALIGNAS(128) char elem;\n};\n\nvoid test_allocator_and_new_match() {\n stats.reset();\n#if defined(NO_SIZE) && defined(NO_ALIGN)\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_plain());\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_plain());\n }\n stats.reset();\n#elif defined(NO_SIZE)\n stats.reset();\n#if TEST_STD_VER >= 11\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_plain());\n }\n#endif\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_align(TEST_ALIGNOF(AlignedType)));\n }\n stats.reset();\n#elif defined(NO_ALIGN)\n stats.reset();\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_size(sizeof(int)));\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_size(sizeof(AlignedType)));\n }\n stats.reset();\n#else\n stats.reset();\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_size(sizeof(int)));\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_size_align(sizeof(AlignedType),\n TEST_ALIGNOF(AlignedType)));\n }\n stats.reset();\n#endif\n}\n\nint main() {\n test_libcpp_dealloc();\n test_allocator_and_new_match();\n}\n<commit_msg>[libcxx] Remove outdated XFAILs for aligned deallocation<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test libc++'s implementation of align_val_t, and the relevant new\/delete\n\/\/ overloads in all dialects when -faligned-allocation is present.\n\n\/\/ Libc++ defers to the underlying MSVC library to provide the new\/delete\n\/\/ definitions, which does not yet provide aligned allocation\n\/\/ XFAIL: LIBCXX-WINDOWS-FIXME\n\n\/\/ The dylibs shipped before macosx10.14 do not contain the aligned allocation\n\/\/ functions, so trying to force using those with -faligned-allocation results\n\/\/ in a link error.\n\/\/ XFAIL: with_system_cxx_lib=macosx10.13\n\/\/ XFAIL: with_system_cxx_lib=macosx10.12\n\/\/ XFAIL: with_system_cxx_lib=macosx10.11\n\/\/ XFAIL: with_system_cxx_lib=macosx10.10\n\/\/ XFAIL: with_system_cxx_lib=macosx10.9\n\/\/ XFAIL: with_system_cxx_lib=macosx10.8\n\/\/ XFAIL: with_system_cxx_lib=macosx10.7\n\n\/\/ The test will fail on deployment targets that do not support sized deallocation.\n\/\/ XFAIL: availability=macosx10.11\n\/\/ XFAIL: availability=macosx10.10\n\/\/ XFAIL: availability=macosx10.9\n\/\/ XFAIL: availability=macosx10.8\n\/\/ XFAIL: availability=macosx10.7\n\n\/\/ XFAIL: sanitizer-new-delete, ubsan\n\n\/\/ GCC doesn't support the aligned-allocation flags.\n\/\/ XFAIL: gcc\n\n\/\/ RUN: %build -faligned-allocation -fsized-deallocation\n\/\/ RUN: %run\n\/\/ RUN: %build -faligned-allocation -fno-sized-deallocation -DNO_SIZE\n\/\/ RUN: %run\n\/\/ RUN: %build -fno-aligned-allocation -fsized-deallocation -DNO_ALIGN\n\/\/ RUN: %run\n\/\/ RUN: %build -fno-aligned-allocation -fno-sized-deallocation -DNO_ALIGN -DNO_SIZE\n\/\/ RUN: %run\n\n#include <new>\n#include <typeinfo>\n#include <string>\n#include <cassert>\n\n#include \"test_macros.h\"\n\nstruct alloc_stats {\n alloc_stats() { reset(); }\n\n int aligned_sized_called;\n int aligned_called;\n int sized_called;\n int plain_called;\n int last_size;\n int last_align;\n\n void reset() {\n aligned_sized_called = aligned_called = sized_called = plain_called = 0;\n last_align = last_size = -1;\n }\n\n bool expect_plain() const {\n assert(aligned_sized_called == 0);\n assert(aligned_called == 0);\n assert(sized_called == 0);\n assert(last_size == -1);\n assert(last_align == -1);\n return plain_called == 1;\n }\n\n bool expect_size(int n) const {\n assert(plain_called == 0);\n assert(aligned_sized_called == 0);\n assert(aligned_called == 0);\n assert(last_size == n);\n assert(last_align == -1);\n return sized_called == 1;\n }\n\n bool expect_align(int a) const {\n assert(plain_called == 0);\n assert(aligned_sized_called == 0);\n assert(sized_called == 0);\n assert(last_size == -1);\n assert(last_align == a);\n return aligned_called == 1;\n }\n\n bool expect_size_align(int n, int a) const {\n assert(plain_called == 0);\n assert(sized_called == 0);\n assert(aligned_called == 0);\n assert(last_size == n);\n assert(last_align == a);\n return aligned_sized_called == 1;\n }\n};\nalloc_stats stats;\n\nvoid operator delete(void* p)TEST_NOEXCEPT {\n ::free(p);\n stats.plain_called++;\n stats.last_size = stats.last_align = -1;\n}\n\n#ifndef NO_SIZE\nvoid operator delete(void* p, size_t n)TEST_NOEXCEPT {\n ::free(p);\n stats.sized_called++;\n stats.last_size = n;\n stats.last_align = -1;\n}\n#endif\n\n#ifndef NO_ALIGN\nvoid operator delete(void* p, std::align_val_t a)TEST_NOEXCEPT {\n ::free(p);\n stats.aligned_called++;\n stats.last_align = static_cast<int>(a);\n stats.last_size = -1;\n}\n\nvoid operator delete(void* p, size_t n, std::align_val_t a)TEST_NOEXCEPT {\n ::free(p);\n stats.aligned_sized_called++;\n stats.last_align = static_cast<int>(a);\n stats.last_size = n;\n}\n#endif\n\nvoid test_libcpp_dealloc() {\n void* p = nullptr;\n size_t over_align_val = TEST_ALIGNOF(std::max_align_t) * 2;\n size_t under_align_val = TEST_ALIGNOF(int);\n size_t with_size_val = 2;\n\n {\n std::__libcpp_deallocate_unsized(p, under_align_val);\n assert(stats.expect_plain());\n }\n stats.reset();\n\n#if defined(NO_SIZE) && defined(NO_ALIGN)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_plain());\n }\n stats.reset();\n#elif defined(NO_SIZE)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_align(over_align_val));\n }\n stats.reset();\n#elif defined(NO_ALIGN)\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_size(with_size_val));\n }\n stats.reset();\n#else\n {\n std::__libcpp_deallocate(p, with_size_val, over_align_val);\n assert(stats.expect_size_align(with_size_val, over_align_val));\n }\n stats.reset();\n {\n std::__libcpp_deallocate_unsized(p, over_align_val);\n assert(stats.expect_align(over_align_val));\n }\n stats.reset();\n {\n std::__libcpp_deallocate(p, with_size_val, under_align_val);\n assert(stats.expect_size(with_size_val));\n }\n stats.reset();\n#endif\n}\n\nstruct TEST_ALIGNAS(128) AlignedType {\n AlignedType() : elem(0) {}\n TEST_ALIGNAS(128) char elem;\n};\n\nvoid test_allocator_and_new_match() {\n stats.reset();\n#if defined(NO_SIZE) && defined(NO_ALIGN)\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_plain());\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_plain());\n }\n stats.reset();\n#elif defined(NO_SIZE)\n stats.reset();\n#if TEST_STD_VER >= 11\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_plain());\n }\n#endif\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_align(TEST_ALIGNOF(AlignedType)));\n }\n stats.reset();\n#elif defined(NO_ALIGN)\n stats.reset();\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_size(sizeof(int)));\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_size(sizeof(AlignedType)));\n }\n stats.reset();\n#else\n stats.reset();\n {\n int* x = new int(42);\n delete x;\n assert(stats.expect_size(sizeof(int)));\n }\n stats.reset();\n {\n AlignedType* a = new AlignedType();\n delete a;\n assert(stats.expect_size_align(sizeof(AlignedType),\n TEST_ALIGNOF(AlignedType)));\n }\n stats.reset();\n#endif\n}\n\nint main() {\n test_libcpp_dealloc();\n test_allocator_and_new_match();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"..\/io.h\"\n#include \"..\/directory.h\"\n#include \"..\/..\/core\/slist.h\"\n#include \"info.h\"\n#include \"..\/file.h\"\n\n\n\nnamespace Yuni\n{\nnamespace IO\n{\nnamespace Directory\n{\n\n\n\tnamespace \/\/ anonymous\n\t{\n\n\t\tstruct InfoItem\n\t\t{\n\t\t\tbool isFile;\n\t\t\tuint64 size;\n\t\t\tString filename;\n\t\t};\n\t\ttypedef LinkedList<InfoItem> List;\n\n\t} \/\/ anonymous namespace\n\n\n\n\tbool Copy(const AnyString& src, const AnyString& dst, bool recursive,\n\t\tbool overwrite, const IO::Directory::CopyOnUpdateBind& onUpdate)\n\t{\n\t\t\/\/ normalize paths\n\t\tString fsrc;\n\t\tIO::Normalize(fsrc, src);\n\t\tif (fsrc.empty())\n\t\t\treturn false;\n\n\t\tString fdst;\n\t\tIO::Normalize(fdst, dst);\n\n\t\t\/\/ The list of files to copy\n\t\tList list;\n\t\tuint64 totalSize = 0;\n\n\t\t\/\/ Adding the target folder, to create it if required\n\t\tif (not onUpdate(cpsGatheringInformation, fdst, fdst, 0, 1))\n\t\t\treturn false;\n\t\tIO::Directory::Create(fdst);\n\n\t\t{\n\t\t\tIO::Directory::Info info(fsrc);\n\t\t\tif (recursive)\n\t\t\t{\n\t\t\t\tconst IO::Directory::Info::recursive_iterator& end = info.recursive_end();\n\t\t\t\tfor (IO::Directory::Info::recursive_iterator i = info.recursive_begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tlist.push_back();\n\t\t\t\t\tInfoItem& info = list.back();\n\t\t\t\t\tinfo.filename = i.filename();\n\t\t\t\t\tinfo.isFile = i.isFile();\n\t\t\t\t\ttotalSize += i.size();\n\t\t\t\t\tif (!onUpdate(cpsGatheringInformation, *i, *i, 0, list.size()))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst IO::Directory::Info::recursive_iterator& end = info.recursive_end();\n\t\t\t\tfor (IO::Directory::Info::recursive_iterator i = info.recursive_begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tlist.push_back();\n\t\t\t\t\tInfoItem& info = list.back();\n\t\t\t\t\tinfo.filename = i.filename();\n\t\t\t\t\tinfo.isFile = i.isFile();\n\t\t\t\t\ttotalSize += i.size();\n\n\t\t\t\t\tif (!onUpdate(cpsGatheringInformation, i.filename(), i.filename(), 0, list.size()))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tuint64 current = 0;\n\t\t\/\/ A temporary string\n\t\tString tmp;\n\n\t\t\/\/ Streams : in the worst scenario, the last file to copy will be closed\n\t\t\/\/ at the end of this routine\n\t\t\/\/ Stream on the source file\n\t\tIO::File::Stream fromFile;\n\t\t\/\/ Stream on the target file\n\t\tIO::File::Stream toFile;\n\n\t\t\/\/ A temporary buffer for copying files' contents\n\t\t\/\/ 16k seems to be a good choice (better than smaller block size when used\n\t\t\/\/ in Virtual Machines)\n\t\tenum { bufferSize = 8192 };\n\t\tchar* buffer = new char[bufferSize];\n\n\t\t\/\/ reduce overhead brought by `onUpdate`\n\t\tuint skip = 8;\n\n\t\tconst List::const_iterator end = list.end();\n\t\tfor (List::const_iterator i = list.begin(); i != end; ++i)\n\t\t{\n\t\t\t\/\/ alias to the current information block\n\t\t\tconst InfoItem& info = *i;\n\n\t\t\t\/\/ Address of the target file\n\t\t\ttmp = fdst; \/\/ without any OS-dependant separator\n\t\t\tif (fsrc.size() < info.filename.size())\n\t\t\t\ttmp.append(info.filename.c_str() + fsrc.size(), info.filename.size() - fsrc.size());\n\n\t\t\tif (not info.isFile)\n\t\t\t{\n\t\t\t\t\/\/ The target file is actually a folder\n\t\t\t\t\/\/ We have to create it before copying its content\n\t\t\t\tif (!onUpdate(cpsCopying, info.filename, tmp, current, totalSize)\n\t\t\t\t\t|| !IO::Directory::Create(tmp))\n\t\t\t\t{\n\t\t\t\t\tdelete[] buffer;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ The target file is a real file (and not a folder)\n\t\t\t\t\/\/ Checking first for overwritting\n\t\t\t\tif (not overwrite && IO::Exists(tmp))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/ Try to open the source file\n\t\t\t\t\/\/ The previous opened source file will be closed here\n\t\t\t\tif (fromFile.open(info.filename, IO::OpenMode::read))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Try to open for writing the target file\n\t\t\t\t\t\/\/ The previous opened target file will be closed here\n\t\t\t\t\tif (toFile.open(tmp, IO::OpenMode::write | IO::OpenMode::truncate))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ reading the whole source file\n\t\t\t\t\t\tuint64 numRead;\n\t\t\t\t\t\twhile ((numRead = fromFile.read(buffer, bufferSize)) != 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ progression\n\t\t\t\t\t\t\tcurrent += numRead;\n\n\t\t\t\t\t\t\t\/\/ Trying to copy the block which has just been read\n\t\t\t\t\t\t\tif (numRead != toFile.write((const char*)buffer, numRead))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdelete[] buffer;\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ Notify the user from time to time about the progression\n\t\t\t\t\t\t\tif (!--skip)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!onUpdate(cpsCopying, info.filename, tmp, current, totalSize))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdelete[] buffer;\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tskip = 8;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \/\/ read\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdelete[] buffer;\n\n\t\treturn true;\n\t}\n\n\n\n\n\n} \/\/ namespace Directory\n} \/\/ namespace IO\n} \/\/ namespace Yuni\n\n<commit_msg>IO::Directory::Copy: several optimization<commit_after>\n#include \"..\/io.h\"\n#include \"..\/directory.h\"\n#include \"info.h\"\n#include \"..\/file.h\"\n\n\n\nnamespace Yuni\n{\nnamespace IO\n{\nnamespace Directory\n{\n\n\n\tnamespace \/\/ anonymous\n\t{\n\n\t\tstruct InfoItem\n\t\t{\n\t\t\tbool isFile;\n\t\t\tuint64 size;\n\t\t\tString filename;\n\t\t};\n\t\ttypedef std::vector<InfoItem> List;\n\n\t} \/\/ anonymous namespace\n\n\n\n\tbool Copy(const AnyString& src, const AnyString& dst, bool recursive, bool overwrite,\n\t\tconst IO::Directory::CopyOnUpdateBind& onUpdate)\n\t{\n\t\t\/\/ normalize paths\n\t\tString fsrc;\n\t\tIO::Normalize(fsrc, src);\n\t\tif (fsrc.empty())\n\t\t\treturn false;\n\n\t\tString fdst;\n\t\tIO::Normalize(fdst, dst);\n\n\t\t\/\/ Adding the target folder, to create it if required\n\t\tif (not onUpdate(cpsGatheringInformation, fdst, fdst, 0, 1))\n\t\t\treturn false;\n\n\t\tif (not IO::Directory::Create(fdst))\n\t\t\treturn false;\n\n\t\t\/\/ The list of files to copy\n\t\tList list;\n\t\tlist.reserve(512);\n\t\t\/\/ the total number of bytes to copy\n\t\tuint64 totalSize = 0;\n\n\n\t\t\/\/ get the complete list of all files to copy and all folders to create\n\t\t{\n\t\t\tIO::Directory::Info info(fsrc);\n\t\t\tif (recursive)\n\t\t\t{\n\t\t\t\tconst IO::Directory::Info::recursive_iterator& end = info.recursive_end();\n\t\t\t\tfor (IO::Directory::Info::recursive_iterator i = info.recursive_begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tlist.resize(list.size() + 1);\n\t\t\t\t\tInfoItem& info = list.back();\n\t\t\t\t\tinfo.filename = i.filename();\n\t\t\t\t\tinfo.isFile = i.isFile();\n\t\t\t\t\ttotalSize += i.size();\n\t\t\t\t\tif (not onUpdate(cpsGatheringInformation, *i, *i, 0, list.size()))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst IO::Directory::Info::iterator& end = info.end();\n\t\t\t\tfor (IO::Directory::Info::iterator i = info.begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tlist.resize(list.size() + 1);\n\t\t\t\t\tInfoItem& info = list.back();\n\t\t\t\t\tinfo.filename = i.filename();\n\t\t\t\t\tinfo.isFile = i.isFile();\n\t\t\t\t\ttotalSize += i.size();\n\n\t\t\t\t\tif (not onUpdate(cpsGatheringInformation, i.filename(), i.filename(), 0, list.size()))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (list.empty())\n\t\t\treturn true;\n\n\n\t\tuint64 current = 0;\n\t\t\/\/ A temporary string\n\t\tString tmp;\n\t\ttmp.reserve(1024);\n\n\t\t\/\/ Streams : in the worst scenario, the last file to copy will be closed\n\t\t\/\/ at the end of this routine\n\t\t\/\/ Stream on the source file\n\t\tIO::File::Stream fromFile;\n\t\t\/\/ Stream on the target file\n\t\tIO::File::Stream toFile;\n\n\t\t\/\/ A temporary buffer for copying files' contents\n\t\t\/\/ 16k seems to be a good choice (better than smaller block size when used\n\t\t\/\/ in Virtual Machines)\n\t\tenum { bufferSize = 8192 };\n\t\tchar* const buffer = new char[(uint) bufferSize];\n\n\t\t\/\/ reduce overhead brought by `onUpdate`\n\t\tenum { maxSkip = 6 };\n\t\tuint skip = (uint) maxSkip;\n\t\t\/\/ result\n\t\tbool success = true;\n\n\t\tconst List::const_iterator end = list.end();\n\t\tfor (List::const_iterator i = list.begin(); i != end; ++i)\n\t\t{\n\t\t\t\/\/ alias to the current information block\n\t\t\tconst InfoItem& info = *i;\n\n\t\t\t\/\/ Address of the target file\n\t\t\ttmp = fdst; \/\/ without any OS-dependant separator\n\t\t\tif (fsrc.size() < info.filename.size())\n\t\t\t\ttmp.append(info.filename.c_str() + fsrc.size(), info.filename.size() - fsrc.size());\n\n\t\t\tif (not info.isFile)\n\t\t\t{\n\t\t\t\t\/\/ The target file is actually a folder - must be created before copying its content\n\t\t\t\tif (not onUpdate(cpsCopying, info.filename, tmp, current, totalSize) or not IO::Directory::Create(tmp))\n\t\t\t\t{\n\t\t\t\t\tsuccess = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ The target file is a real file (and not a folder)\n\t\t\t\t\/\/ Checking first for overwritting\n\t\t\t\tif (not overwrite && IO::Exists(tmp))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/ Try to open the source file\n\t\t\t\t\/\/ The previous opened source file will be closed here\n\t\t\t\tif (fromFile.open(info.filename, IO::OpenMode::read))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Try to open for writing the target file\n\t\t\t\t\t\/\/ The previous opened target file will be closed here\n\t\t\t\t\tif (toFile.open(tmp, IO::OpenMode::write | IO::OpenMode::truncate))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ reading the whole source file\n\t\t\t\t\t\tuint64 numRead;\n\t\t\t\t\t\twhile ((numRead = fromFile.read(buffer, (uint) bufferSize)) > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ progression\n\t\t\t\t\t\t\tcurrent += numRead;\n\n\t\t\t\t\t\t\t\/\/ Trying to copy the block which has just been read\n\t\t\t\t\t\t\tif (numRead != toFile.write((const char*)buffer, numRead))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsuccess = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ Notify the user from time to time about the progression\n\t\t\t\t\t\t\tif (0 == --skip)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (not onUpdate(cpsCopying, info.filename, tmp, current, totalSize))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsuccess = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tskip = (uint) maxSkip;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \/\/ read\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsuccess = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsuccess = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdelete[] buffer;\n\n\t\treturn success;\n\t}\n\n\n\n\n\n} \/\/ namespace Directory\n} \/\/ namespace IO\n} \/\/ namespace Yuni\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n#ident \"Copyright (c) 2007-2012 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n#include <toku_portability.h>\n#include \"test.h\"\n#include \"minicron.h\"\n#include <unistd.h>\n\n#include <string.h>\n#include <stdlib.h>\n\nstatic double\ntdiff (struct timeval *a, struct timeval *b) {\n return (a->tv_sec-b->tv_sec) + (a->tv_usec-b->tv_usec)*1e-6;\n}\n\nstruct timeval starttime;\nstatic double elapsed (void) {\n struct timeval now;\n gettimeofday(&now, 0);\n return tdiff(&now, &starttime);\n}\n\nstatic int \n#ifndef GCOV\n__attribute__((__noreturn__))\n#endif\nnever_run (void *a) {\n assert(a==0);\n assert(0);\n#if TOKU_WINDOWS || defined(GCOV)\n return 0; \/\/ICC ignores the noreturn attribute.\n#endif\n}\n\n\/\/ Can we start something with period=0 (the function should never run) and shut it down.\nstatic void*\ntest1 (void* v)\n{\n struct minicron m;\n int r = toku_minicron_setup(&m, 0, never_run, 0); assert(r==0);\n sleep(1);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\n\/\/ Can we start something with period=10 and shut it down after 2 seconds (the function should never run) .\nstatic void*\ntest2 (void* v)\n{\n struct minicron m;\n int r = toku_minicron_setup(&m, 10, never_run, 0); assert(r==0);\n sleep(2);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\nstruct tenx {\n struct timeval tv;\n int counter;\n};\n\nstatic int\nrun_5x (void *v) {\n struct tenx *CAST_FROM_VOIDP(tx, v);\n struct timeval now;\n gettimeofday(&now, 0);\n double diff = tdiff(&now, &tx->tv);\n if (verbose) printf(\"T=%f tx->counter=%d\\n\", diff, tx->counter);\n \/\/ We only verify that the timer was not premature. \n \/\/ Sometimes it will be delayed, but there's no good way to test it and nothing we can do about it.\n if (!(diff>0.5 + tx->counter)) {\n printf(\"T=%f tx->counter=%d\\n\", diff, tx->counter);\n assert(0);\n }\n tx->counter++;\n return 0;\n}\n\n\/\/ Start something with period=1 and run it a few times\nstatic void*\ntest3 (void* v)\n{\n struct minicron m;\n struct tenx tx;\n gettimeofday(&tx.tv, 0);\n tx.counter=0;\n int r = toku_minicron_setup(&m, 1, run_5x, &tx); assert(r==0);\n sleep(5);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(tx.counter>=4 && tx.counter<=5); \/\/ after 5 seconds it could have run 4 or 5 times.\n return v;\n}\n\nstatic int\nrun_3sec (void *v) {\n if (verbose) printf(\"start3sec at %.6f\\n\", elapsed());\n int *CAST_FROM_VOIDP(counter, v);\n (*counter)++;\n sleep(3);\n if (verbose) printf(\"end3sec at %.6f\\n\", elapsed());\n return 0;\n}\n\n\/\/ make sure that if f is really slow that it doesn't run too many times\nstatic void*\ntest4 (void *v) {\n struct minicron m;\n int counter = 0;\n int r = toku_minicron_setup(&m, 2, run_3sec, &counter); assert(r==0);\n sleep(9);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(counter==2);\n return v;\n}\n\nstatic void*\ntest5 (void *v) {\n struct minicron m;\n int counter = 0;\n int r = toku_minicron_setup(&m, 10, run_3sec, &counter); assert(r==0);\n r = toku_minicron_change_period(&m, 2); assert(r==0);\n sleep(9);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(counter==2);\n return v;\n}\n\nstatic void*\ntest6 (void *v) {\n struct minicron m;\n int r = toku_minicron_setup(&m, 5, never_run, 0); assert(r==0);\n r = toku_minicron_change_period(&m, 0); assert(r==0);\n sleep(7);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\ntypedef void*(*ptf)(void*);\nint\ntest_main (int argc, const char *argv[]) {\n default_parse_args(argc,argv);\n gettimeofday(&starttime, 0);\n\n ptf testfuns[] = {test1, test2, test3,\n\t\t test4,\n\t\t test5,\n\t\t test6\n };\n#define N (sizeof(testfuns)\/sizeof(testfuns[0]))\n toku_pthread_t tests[N];\n\n unsigned int i;\n for (i=0; i<N; i++) {\n\tint r=toku_pthread_create(tests+i, 0, testfuns[i], 0);\n\tassert(r==0);\n }\n for (i=0; i<N; i++) {\n\tvoid *v;\n\tint r=toku_pthread_join(tests[i], &v);\n\tassert(r==0);\n\tassert(v==0);\n }\n return 0;\n}\n<commit_msg>refs #5507 fix minicron-test<commit_after>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n#ident \"Copyright (c) 2007-2012 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n#include <toku_portability.h>\n#include \"test.h\"\n#include \"minicron.h\"\n#include <unistd.h>\n\n#include <string.h>\n#include <stdlib.h>\n\nstatic double\ntdiff (struct timeval *a, struct timeval *b) {\n return (a->tv_sec-b->tv_sec) + (a->tv_usec-b->tv_usec)*1e-6;\n}\n\nstruct timeval starttime;\nstatic double elapsed (void) {\n struct timeval now;\n gettimeofday(&now, 0);\n return tdiff(&now, &starttime);\n}\n\nstatic int \n#ifndef GCOV\n__attribute__((__noreturn__))\n#endif\nnever_run (void *a) {\n assert(a==0);\n assert(0);\n#if TOKU_WINDOWS || defined(GCOV)\n return 0; \/\/ICC ignores the noreturn attribute.\n#endif\n}\n\n\/\/ Can we start something with period=0 (the function should never run) and shut it down.\nstatic void*\ntest1 (void* v)\n{\n struct minicron m;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 0, never_run, 0); assert(r==0);\n sleep(1);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\n\/\/ Can we start something with period=10 and shut it down after 2 seconds (the function should never run) .\nstatic void*\ntest2 (void* v)\n{\n struct minicron m;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 10, never_run, 0); assert(r==0);\n sleep(2);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\nstruct tenx {\n struct timeval tv;\n int counter;\n};\n\nstatic int\nrun_5x (void *v) {\n struct tenx *CAST_FROM_VOIDP(tx, v);\n struct timeval now;\n gettimeofday(&now, 0);\n double diff = tdiff(&now, &tx->tv);\n if (verbose) printf(\"T=%f tx->counter=%d\\n\", diff, tx->counter);\n \/\/ We only verify that the timer was not premature. \n \/\/ Sometimes it will be delayed, but there's no good way to test it and nothing we can do about it.\n if (!(diff>0.5 + tx->counter)) {\n printf(\"T=%f tx->counter=%d\\n\", diff, tx->counter);\n assert(0);\n }\n tx->counter++;\n return 0;\n}\n\n\/\/ Start something with period=1 and run it a few times\nstatic void*\ntest3 (void* v)\n{\n struct minicron m;\n struct tenx tx;\n gettimeofday(&tx.tv, 0);\n tx.counter=0;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 1, run_5x, &tx); assert(r==0);\n sleep(5);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(tx.counter>=4 && tx.counter<=5); \/\/ after 5 seconds it could have run 4 or 5 times.\n return v;\n}\n\nstatic int\nrun_3sec (void *v) {\n if (verbose) printf(\"start3sec at %.6f\\n\", elapsed());\n int *CAST_FROM_VOIDP(counter, v);\n (*counter)++;\n sleep(3);\n if (verbose) printf(\"end3sec at %.6f\\n\", elapsed());\n return 0;\n}\n\n\/\/ make sure that if f is really slow that it doesn't run too many times\nstatic void*\ntest4 (void *v) {\n struct minicron m;\n int counter = 0;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 2, run_3sec, &counter); assert(r==0);\n sleep(9);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(counter==2);\n return v;\n}\n\nstatic void*\ntest5 (void *v) {\n struct minicron m;\n int counter = 0;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 10, run_3sec, &counter); assert(r==0);\n r = toku_minicron_change_period(&m, 2); assert(r==0);\n sleep(9);\n r = toku_minicron_shutdown(&m); assert(r==0);\n assert(counter==2);\n return v;\n}\n\nstatic void*\ntest6 (void *v) {\n struct minicron m;\n ZERO_STRUCT(m);\n int r = toku_minicron_setup(&m, 5, never_run, 0); assert(r==0);\n r = toku_minicron_change_period(&m, 0); assert(r==0);\n sleep(7);\n r = toku_minicron_shutdown(&m); assert(r==0);\n return v;\n}\n\ntypedef void*(*ptf)(void*);\nint\ntest_main (int argc, const char *argv[]) {\n default_parse_args(argc,argv);\n gettimeofday(&starttime, 0);\n\n ptf testfuns[] = {test1, test2, test3,\n\t\t test4,\n\t\t test5,\n\t\t test6\n };\n#define N (sizeof(testfuns)\/sizeof(testfuns[0]))\n toku_pthread_t tests[N];\n\n unsigned int i;\n for (i=0; i<N; i++) {\n\tint r=toku_pthread_create(tests+i, 0, testfuns[i], 0);\n\tassert(r==0);\n }\n for (i=0; i<N; i++) {\n\tvoid *v;\n\tint r=toku_pthread_join(tests[i], &v);\n\tassert(r==0);\n\tassert(v==0);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n Copyright (c) 2017 Leandro T. C. Melo (ltcmelo@gmail.com)\n\n This library is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by the Free\n Software Foundation; either version 2.1 of the License, or (at your option)\n any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n for more details.\n\n You should have received a copy of the GNU Lesser General Public License along\n with this library; if not, write to the Free Software Foundation, Inc., 51\n Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *****************************************************************************\/\n\n#include \"StdLibIndex.h\"\n#include \"Control.h\"\n#include <algorithm>\n#include <iterator>\n#include <unordered_set>\n\nusing namespace psyche;\nusing namespace CPlusPlus;\n\n\/\/ C89\/90\nconst StdLibIndex::Index StdLibIndex::c89idx_\n {\n { \"assert.h\",\n {\n { \"assert\", SymbolKind::Value }\n }\n },\n { \"errno.h\",\n {\n { \"errno\", SymbolKind::Value }\n }\n },\n { \"ctype.h\",\n {\n { \"isalnum\", SymbolKind::Value },\n { \"isalpha\", SymbolKind::Value },\n { \"islower\", SymbolKind::Value },\n { \"isupper\", SymbolKind::Value },\n { \"isdigit\", SymbolKind::Value },\n { \"isxdigit\", SymbolKind::Value },\n { \"iscntrl\", SymbolKind::Value },\n { \"isgraph\", SymbolKind::Value },\n { \"isspace\", SymbolKind::Value },\n { \"isprint\", SymbolKind::Value },\n { \"ispunch\", SymbolKind::Value },\n { \"tolower\", SymbolKind::Value },\n { \"toupper\", SymbolKind::Value }\n }\n },\n { \"stdlib.h\",\n {\n { \"atof\", SymbolKind::Value },\n { \"atoi\", SymbolKind::Value },\n { \"atol\", SymbolKind::Value },\n { \"strtol\", SymbolKind::Value },\n { \"strtoul\", SymbolKind::Value },\n { \"strtod\", SymbolKind::Value }\n }\n },\n { \"string.h\",\n {\n { \"strcpy\", SymbolKind::Value },\n { \"strncpy\", SymbolKind::Value },\n { \"strcat\", SymbolKind::Value },\n { \"strncat\", SymbolKind::Value },\n { \"strxfrm\", SymbolKind::Value },\n { \"strlen\", SymbolKind::Value },\n { \"strcmp\", SymbolKind::Value },\n { \"strncmp\", SymbolKind::Value },\n { \"strcoll\", SymbolKind::Value },\n { \"strchr\", SymbolKind::Value },\n { \"strspn\", SymbolKind::Value },\n { \"strcspn\", SymbolKind::Value }\n }\n }\n };\n\n\/\/ C99\nconst StdLibIndex::Index StdLibIndex::c99idx_\n {\n { \"ctype.h\",\n {\n { \"isblank\", SymbolKind::Value }\n }\n },\n { \"stdlib.h\",\n {\n { \"atoll\", SymbolKind::Value },\n { \"strtoll\", SymbolKind::Value },\n { \"strtoull\", SymbolKind::Value },\n { \"strtof\", SymbolKind::Value },\n { \"strtold\", SymbolKind::Value }\n }\n }\n };\n\n\/\/ C11\nconst StdLibIndex::Index StdLibIndex::c11idx_\n {\n { \"assert.h\",\n {\n { \"static_assert\", SymbolKind::Value }\n }\n },\n { \"errno.h\",\n {\n { \"errno_t\", SymbolKind::Type }\n }\n },\n { \"string.h\",\n {\n { \"strcpy_s\", SymbolKind::Value },\n { \"strncpy_s\", SymbolKind::Value },\n { \"strcat_s\", SymbolKind::Value },\n { \"strncat_s\", SymbolKind::Value },\n { \"strnlen_s\", SymbolKind::Value }\n }\n }\n };\n\n\nStdLibIndex::StdLibIndex(StdLibVersion std)\n : std_(std)\n{}\n\nstd::vector<std::string> StdLibIndex::inspect(const Control& control) const\n{\n std::unordered_set<std::string> deps;\n\n auto f = [&deps, &control] (const Index& idx) {\n for (const auto& v : idx) {\n if (deps.count(v.first)) \/\/ Maybe the header has already been inserted.\n continue;\n for (const auto& s : v.second) {\n if (control.findIdentifier(s.first, strlen(s.first))) {\n deps.insert(v.first);\n break;\n }\n }\n }\n };\n\n f(c89idx_);\n if (std_ == StdLibVersion::C99)\n f(c99idx_);\n if (std_ == StdLibVersion::C11)\n f(c11idx_);\n\n std::vector<std::string> v;\n std::move(deps.begin(), deps.end(), std::back_inserter(v));\n return v;\n}\n<commit_msg>Add missing header<commit_after>\/******************************************************************************\n Copyright (c) 2017 Leandro T. C. Melo (ltcmelo@gmail.com)\n\n This library is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by the Free\n Software Foundation; either version 2.1 of the License, or (at your option)\n any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n for more details.\n\n You should have received a copy of the GNU Lesser General Public License along\n with this library; if not, write to the Free Software Foundation, Inc., 51\n Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *****************************************************************************\/\n\n#include \"StdLibIndex.h\"\n#include \"Control.h\"\n#include <algorithm>\n#include <cstring>\n#include <iterator>\n#include <unordered_set>\n\nusing namespace psyche;\nusing namespace CPlusPlus;\n\n\/\/ C89\/90\nconst StdLibIndex::Index StdLibIndex::c89idx_\n {\n { \"assert.h\",\n {\n { \"assert\", SymbolKind::Value }\n }\n },\n { \"errno.h\",\n {\n { \"errno\", SymbolKind::Value }\n }\n },\n { \"ctype.h\",\n {\n { \"isalnum\", SymbolKind::Value },\n { \"isalpha\", SymbolKind::Value },\n { \"islower\", SymbolKind::Value },\n { \"isupper\", SymbolKind::Value },\n { \"isdigit\", SymbolKind::Value },\n { \"isxdigit\", SymbolKind::Value },\n { \"iscntrl\", SymbolKind::Value },\n { \"isgraph\", SymbolKind::Value },\n { \"isspace\", SymbolKind::Value },\n { \"isprint\", SymbolKind::Value },\n { \"ispunch\", SymbolKind::Value },\n { \"tolower\", SymbolKind::Value },\n { \"toupper\", SymbolKind::Value }\n }\n },\n { \"stdlib.h\",\n {\n { \"atof\", SymbolKind::Value },\n { \"atoi\", SymbolKind::Value },\n { \"atol\", SymbolKind::Value },\n { \"strtol\", SymbolKind::Value },\n { \"strtoul\", SymbolKind::Value },\n { \"strtod\", SymbolKind::Value }\n }\n },\n { \"string.h\",\n {\n { \"strcpy\", SymbolKind::Value },\n { \"strncpy\", SymbolKind::Value },\n { \"strcat\", SymbolKind::Value },\n { \"strncat\", SymbolKind::Value },\n { \"strxfrm\", SymbolKind::Value },\n { \"strlen\", SymbolKind::Value },\n { \"strcmp\", SymbolKind::Value },\n { \"strncmp\", SymbolKind::Value },\n { \"strcoll\", SymbolKind::Value },\n { \"strchr\", SymbolKind::Value },\n { \"strspn\", SymbolKind::Value },\n { \"strcspn\", SymbolKind::Value }\n }\n }\n };\n\n\/\/ C99\nconst StdLibIndex::Index StdLibIndex::c99idx_\n {\n { \"ctype.h\",\n {\n { \"isblank\", SymbolKind::Value }\n }\n },\n { \"stdlib.h\",\n {\n { \"atoll\", SymbolKind::Value },\n { \"strtoll\", SymbolKind::Value },\n { \"strtoull\", SymbolKind::Value },\n { \"strtof\", SymbolKind::Value },\n { \"strtold\", SymbolKind::Value }\n }\n }\n };\n\n\/\/ C11\nconst StdLibIndex::Index StdLibIndex::c11idx_\n {\n { \"assert.h\",\n {\n { \"static_assert\", SymbolKind::Value }\n }\n },\n { \"errno.h\",\n {\n { \"errno_t\", SymbolKind::Type }\n }\n },\n { \"string.h\",\n {\n { \"strcpy_s\", SymbolKind::Value },\n { \"strncpy_s\", SymbolKind::Value },\n { \"strcat_s\", SymbolKind::Value },\n { \"strncat_s\", SymbolKind::Value },\n { \"strnlen_s\", SymbolKind::Value }\n }\n }\n };\n\n\nStdLibIndex::StdLibIndex(StdLibVersion std)\n : std_(std)\n{}\n\nstd::vector<std::string> StdLibIndex::inspect(const Control& control) const\n{\n std::unordered_set<std::string> deps;\n\n auto f = [&deps, &control] (const Index& idx) {\n for (const auto& v : idx) {\n if (deps.count(v.first)) \/\/ Maybe the header has already been inserted.\n continue;\n for (const auto& s : v.second) {\n if (control.findIdentifier(s.first, strlen(s.first))) {\n deps.insert(v.first);\n break;\n }\n }\n }\n };\n\n f(c89idx_);\n if (std_ == StdLibVersion::C99)\n f(c99idx_);\n if (std_ == StdLibVersion::C11)\n f(c11idx_);\n\n std::vector<std::string> v;\n std::move(deps.begin(), deps.end(), std::back_inserter(v));\n return v;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstring>\n#include \"vrambatcher.h\"\nPoke::Poke() : size(0), mode(PM_NOOP) {}\nPoke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) {\n}\nPoke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) {\n}\nPoke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) {\n}\nPoke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) {\n}\nPoke::~Poke() {\n\tswitch(mode) {\n\t\tcase PM_DMA:\n\t\tcase PM_MEMCPY:\n\t\t\tvaluePtr.~unique_ptr();\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid Poke::Perform() {\n\tswitch(mode) {\n\t\tcase PM_NOOP:\n\t\tbreak;\n\t\tcase PM_INT:\n\t\t\tswitch(size) {\n\t\t\t\tcase sizeof(uint8_t):\n\t\t\t\t\t*((volatile uint8_t*)addr)=value8;\n\t\t\t\tbreak;\n\t\t\t\tcase sizeof(uint16_t):\n\t\t\t\t\t*((volatile uint16_t*)addr)=value16;\n\t\t\t\tbreak;\n\t\t\t\tcase sizeof(uint32_t):\n\t\t\t\t\t*((volatile uint32_t*)addr)=value32;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\t\tcase PM_BITFIELD:\n\t\tbreak;\n\t\tcase PM_DMA:\n\t\tbreak;\n\t\tcase PM_MEMCPY:\n\t\tbreak;\n\t\t\n\t}\n}\n\nPokeChainLink::PokeChainLink() {}\nPokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {}\nPokeChainLink::~PokeChainLink() {}\n\nvoid VramBatcher::AddPoke(int line, uint8_t val, volatile uint8_t *addr) {\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, uint16_t val, volatile uint16_t *addr){\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, uint32_t val, volatile uint32_t *addr){\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, std::unique_ptr<uint8_t[]> &&data, size_t dataSize, hwPtr addr){\n\tAddPoke(line,Poke(std::move(data),dataSize,addr));\n}\nvoid VramBatcher::AddPoke(int line, Poke&& p) {\n\tPokeChainLink *l=new PokeChainLink(std::move(p),std::move(lineEntries[line]));\n\tlineEntries[line]=std::unique_ptr<PokeChainLink>(l);\n}\n\nvoid VramBatcher::Clear() {\n\tfor(int line=0;line<SCREEN_HEIGHT;++line) {\n\t\tlineEntries[line].reset();\n\t}\n}\n\nvoid VramBatcher::ApplyPokesForLine(int line) {\n\tfor(PokeChainLink *pPtr=lineEntries[line].get();pPtr!=nullptr;pPtr=pPtr->next.get()) {\n\t\tpPtr->poke.Perform();\n\t}\n}<commit_msg>Implement PM_MEMCPY<commit_after>#include <algorithm>\n#include <cstring>\n#include \"vrambatcher.h\"\nPoke::Poke() : size(0), mode(PM_NOOP) {}\nPoke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) {\n}\nPoke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) {\n}\nPoke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) {\n}\nPoke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) {\n}\nPoke::~Poke() {\n\tswitch(mode) {\n\t\tcase PM_DMA:\n\t\tcase PM_MEMCPY:\n\t\t\tvaluePtr.~unique_ptr();\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid Poke::Perform() {\n\tswitch(mode) {\n\t\tcase PM_NOOP:\n\t\tbreak;\n\t\tcase PM_INT:\n\t\t\tswitch(size) {\n\t\t\t\tcase sizeof(uint8_t):\n\t\t\t\t\t*((volatile uint8_t*)addr)=value8;\n\t\t\t\tbreak;\n\t\t\t\tcase sizeof(uint16_t):\n\t\t\t\t\t*((volatile uint16_t*)addr)=value16;\n\t\t\t\tbreak;\n\t\t\t\tcase sizeof(uint32_t):\n\t\t\t\t\t*((volatile uint32_t*)addr)=value32;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\t\tcase PM_BITFIELD:\n\t\tbreak;\n\t\tcase PM_DMA:\n\t\tbreak;\n\t\tcase PM_MEMCPY: {\n\t\t\tvolatile uint8_t *dst=valuePtr.get();\n\t\t\tstd::copy(dst,dst+size,(uint8_t *)addr);\n\t\t} break;\n\t\t\n\t}\n}\n\nPokeChainLink::PokeChainLink() {}\nPokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {}\nPokeChainLink::~PokeChainLink() {}\n\nvoid VramBatcher::AddPoke(int line, uint8_t val, volatile uint8_t *addr) {\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, uint16_t val, volatile uint16_t *addr){\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, uint32_t val, volatile uint32_t *addr){\n\tAddPoke(line,Poke(val,addr));\n}\nvoid VramBatcher::AddPoke(int line, std::unique_ptr<uint8_t[]> &&data, size_t dataSize, hwPtr addr){\n\tAddPoke(line,Poke(std::move(data),dataSize,addr));\n}\nvoid VramBatcher::AddPoke(int line, Poke&& p) {\n\tPokeChainLink *l=new PokeChainLink(std::move(p),std::move(lineEntries[line]));\n\tlineEntries[line]=std::unique_ptr<PokeChainLink>(l);\n}\n\nvoid VramBatcher::Clear() {\n\tfor(int line=0;line<SCREEN_HEIGHT;++line) {\n\t\tlineEntries[line].reset();\n\t}\n}\n\nvoid VramBatcher::ApplyPokesForLine(int line) {\n\tfor(PokeChainLink *pPtr=lineEntries[line].get();pPtr!=nullptr;pPtr=pPtr->next.get()) {\n\t\tpPtr->poke.Perform();\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/============================================================================\n\/\/ Name : IEffect.cpp\n\/\/ Author : Duarte Peixinho\n\/\/ Version :\n\/\/ Copyright : ;)\n\/\/ Description : Effect Interface\n\/\/============================================================================\n\n#include <Pyros3D\/Rendering\/PostEffects\/Effects\/IEffect.h>\n\nnamespace p3d {\n\n IEffect::IEffect(const uint32 Width, const uint32 Height) \n {\n \n \/\/ Reset Handles\n positionHandle = texcoordHandle = -2;\n \n \/\/ Initialize Shaders\n shader = new Shader();\n \n \/\/ Set Vertex Shader\n \/\/ Because its always the same\n VertexShaderString = \n \"attribute vec3 aPosition;\\n\"\n \"attribute vec2 aTexcoord;\\n\"\n \"varying vec2 vTexcoord;\\n\"\n \"void main() {\\n\"\n \"gl_Position = vec4(aPosition,1.0);\\n\"\n \"vTexcoord = aTexcoord;\\n\"\n \"}\\n\";\n \n \/\/ Reset\n TextureUnits = 0;\n\n\t\t\/\/ Set FrameBuffers\n\t\tfbo = new FrameBuffer();\n\t\t\n\t\tattachment = new Texture();\n\t\tattachment->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGBA, Width, Height);\n\t\tattachment->SetRepeat(TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge);\n\t\tfbo->Init(FrameBufferAttachmentFormat::Color_Attachment0, TextureType::Texture, attachment);\n\n\t\tthis->Width = Width;\n\t\tthis->Height = Height;\n \n }\n\n void IEffect::UseRTT(const uint32 RTT)\n {\n \/\/ Set Textures\n if (RTT & RTT::Color) UseColor();\n if (RTT & RTT::LastRTT) UseLastRTT();\n if (RTT & RTT::Depth) UseDepth(); \n }\n \n void IEffect::CompileShaders()\n {\n shader->LoadShaderText(VertexShaderString);\n shader->CompileShader(ShaderType::VertexShader);\n\n shader->LoadShaderText(FragmentShaderString);\n shader->CompileShader(ShaderType::FragmentShader);\n\n\t\tshader->LinkProgram();\n }\n \n IEffect::~IEffect() \n\t{\n\t\tshader->DeleteShader();\n\t\tdelete shader;\n\t\tdelete fbo;\n\t\tdelete attachment;\n }\n\n Uniform* IEffect::AddUniform(const Uniform &Data)\n {\n\t\tfor (std::list<__UniformPostProcess>::iterator i = Uniforms.begin(); i != Uniforms.end(); i++)\n\t\t{\n\t\t\tif ((*i).uniform.NameID == Data.NameID)\n\t\t\t{\n\t\t\t\tUniforms.erase(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tUniforms.push_back(__UniformPostProcess(Data));\n\t\treturn &Uniforms.back().uniform;\n }\n\n void IEffect::UseColor()\n {\n Uniform Color;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n Color.Name = toSTR.str();\n Color.Type = Uniforms::DataType::Int;\n Color.Usage = Uniforms::PostEffects::Other;\n Color.SetValue(&TextureUnits);\n AddUniform(Color);\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::Color, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseDepth()\n {\n Uniform Depth;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n Depth.Name = toSTR.str();\n Depth.Type = Uniforms::DataType::Int;\n Depth.Usage = Uniforms::PostEffects::Other;\n Depth.SetValue(&TextureUnits);\n AddUniform(Depth);\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::Depth, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseLastRTT()\n { \n Uniform RTT;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n RTT.Name = toSTR.str();\n RTT.Type = Uniforms::DataType::Int;\n RTT.Usage = Uniforms::PostEffects::Other;\n RTT.SetValue(&TextureUnits);\n AddUniform(RTT);\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::LastRTT, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseCustomTexture(Texture* texture)\n { \n Uniform CustomTexture;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n CustomTexture.Name = toSTR.str();\n CustomTexture.Type = Uniforms::DataType::Int;\n CustomTexture.Usage = Uniforms::PostEffects::Other;\n CustomTexture.SetValue(&TextureUnits);\n AddUniform(CustomTexture);\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(texture, RTT::CustomTexture, TextureUnits));\n \n TextureUnits++;\n }\n \n void IEffect::Resize(const uint32 width, const uint32 height)\n {\n \/\/ Save Dimensions\n Width = width;\n Height = height;\n\t\tfbo->Resize(width, height);\n }\n \n const uint32 IEffect::GetWidth() const\n {\n return Width;\n }\n const uint32 IEffect::GetHeight() const\n {\n return Height;\n }\n}<commit_msg>Fixed Depth Of Field<commit_after>\/\/============================================================================\n\/\/ Name : IEffect.cpp\n\/\/ Author : Duarte Peixinho\n\/\/ Version :\n\/\/ Copyright : ;)\n\/\/ Description : Effect Interface\n\/\/============================================================================\n\n#include <Pyros3D\/Rendering\/PostEffects\/Effects\/IEffect.h>\n\nnamespace p3d {\n\n IEffect::IEffect(const uint32 Width, const uint32 Height) \n {\n \n \/\/ Reset Handles\n positionHandle = texcoordHandle = -2;\n \n \/\/ Initialize Shaders\n shader = new Shader();\n \n \/\/ Set Vertex Shader\n \/\/ Because its always the same\n VertexShaderString = \n \"attribute vec3 aPosition;\\n\"\n \"attribute vec2 aTexcoord;\\n\"\n \"varying vec2 vTexcoord;\\n\"\n \"void main() {\\n\"\n \"gl_Position = vec4(aPosition,1.0);\\n\"\n \"vTexcoord = aTexcoord;\\n\"\n \"}\\n\";\n \n \/\/ Reset\n TextureUnits = 0;\n\n\t\t\/\/ Set FrameBuffers\n\t\tfbo = new FrameBuffer();\n\t\t\n\t\tattachment = new Texture();\n\t\tattachment->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGBA, Width, Height);\n\t\tattachment->SetRepeat(TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge);\n\t\tfbo->Init(FrameBufferAttachmentFormat::Color_Attachment0, TextureType::Texture, attachment);\n\n\t\tthis->Width = Width;\n\t\tthis->Height = Height;\n \n }\n\n void IEffect::UseRTT(const uint32 RTT)\n {\n \/\/ Set Textures\n if (RTT & RTT::Color) UseColor();\n if (RTT & RTT::LastRTT) UseLastRTT();\n if (RTT & RTT::Depth) UseDepth(); \n }\n \n void IEffect::CompileShaders()\n {\n shader->LoadShaderText(VertexShaderString);\n shader->CompileShader(ShaderType::VertexShader);\n\n shader->LoadShaderText(FragmentShaderString);\n shader->CompileShader(ShaderType::FragmentShader);\n\n\t\tshader->LinkProgram();\n }\n \n IEffect::~IEffect() \n\t{\n\t\tshader->DeleteShader();\n\t\tdelete shader;\n\t\tdelete fbo;\n\t\tdelete attachment;\n }\n\n Uniform* IEffect::AddUniform(const Uniform &Data)\n {\n\t\tfor (std::list<__UniformPostProcess>::iterator i = Uniforms.begin(); i != Uniforms.end(); i++)\n\t\t{\n\t\t\tif ((*i).uniform.NameID == Data.NameID)\n\t\t\t{\n\t\t\t\tUniforms.erase(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tUniforms.push_back(__UniformPostProcess(Data));\n\t\treturn &Uniforms.back().uniform;\n }\n\n void IEffect::UseColor()\n {\n Uniform Color;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n AddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::Color, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseDepth()\n {\n Uniform Depth;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n\t\tAddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::Depth, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseLastRTT()\n { \n Uniform RTT;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n\t\tAddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(RTT::LastRTT, TextureUnits));\n \n TextureUnits++;\n }\n void IEffect::UseCustomTexture(Texture* texture)\n { \n Uniform CustomTexture;\n std::ostringstream toSTR; toSTR << \"uTex\" << TextureUnits;\n\t\tAddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));\n \n \/\/ Set RTT Order\n RTTOrder.push_back(RTT::Info(texture, RTT::CustomTexture, TextureUnits));\n \n TextureUnits++;\n }\n \n void IEffect::Resize(const uint32 width, const uint32 height)\n {\n \/\/ Save Dimensions\n Width = width;\n Height = height;\n\t\tfbo->Resize(width, height);\n }\n \n const uint32 IEffect::GetWidth() const\n {\n return Width;\n }\n const uint32 IEffect::GetHeight() const\n {\n return Height;\n }\n}<|endoftext|>"} {"text":"<commit_before>#include <deal.II\/base\/quadrature_lib.h>\n#include <deal.II\/base\/timer.h>\n#include <deal.II\/dofs\/dof_handler.h>\n#include <deal.II\/dofs\/dof_tools.h>\n#include <deal.II\/fe\/fe_q.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/lac\/dynamic_sparsity_pattern.h>\n#include <deal.II\/lac\/linear_operator.h>\n#include <deal.II\/lac\/sparse_matrix.h>\n#include <deal.II\/lac\/vector.h>\n#include <deal.II\/numerics\/matrix_tools.h>\n\n#include <iostream>\n\nusing namespace dealii;\n\nint main(int argc, char *argv[])\n{\n if (argc != 3)\n throw ExcMessage(\"Invalid number of command line parameters\");\n unsigned int refinement = std::atoi(argv[1]);\n unsigned int reps = std::atoi(argv[2]);\n\n Triangulation<2> triangulation;\n GridGenerator::hyper_cube(triangulation);\n triangulation.refine_global(refinement);\n\n FE_Q<2> fe(1);\n DoFHandler<2> dof_handler;\n dof_handler.initialize(triangulation, fe);\n\n std::cout << \"n: \" << dof_handler.n_dofs() << std::endl;\n std::cout << \"reps: \" << reps << std::endl;\n\n DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n SparsityPattern sparsity_pattern;\n sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n\n SparseMatrix<double> matrix;\n matrix.reinit(sparsity_pattern);\n\n QGauss<2> quadrature(2);\n MatrixCreator::create_laplace_matrix(dof_handler, quadrature, matrix);\n\n Vector<double> x(dof_handler.n_dofs());\n for (unsigned int i = 0; i < x.size(); ++i)\n x(i) = i;\n\n TimerOutput timer(std::cout, TimerOutput::summary, TimerOutput::wall_times);\n\n timer.enter_subsection (\"raw\");\n Vector<double> tmp(dof_handler.n_dofs());\n for (unsigned int i = 0; i < reps; ++i)\n {\n matrix.vmult(tmp, x);\n x = tmp;\n x \/= x.l2_norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << \"DEBUG\" << std::endl;\n std::cout << x << std::endl;\n#endif\n\n for (unsigned int i = 0; i < x.size(); ++i)\n x[i] = i;\n\n timer.enter_subsection (\"linear_operator\");\n const auto op = linear_operator(matrix);\n for (unsigned int i = 0; i < reps; ++i)\n {\n op.vmult(x, x);\n x \/= x.l2_norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << x << std::endl;\n#endif\n}\n<commit_msg>Added sparse matrix 01 with Eigen and Blaze<commit_after>#include <deal.II\/base\/quadrature_lib.h>\n#include <deal.II\/base\/timer.h>\n#include <deal.II\/dofs\/dof_handler.h>\n#include <deal.II\/dofs\/dof_tools.h>\n#include <deal.II\/fe\/fe_q.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/lac\/dynamic_sparsity_pattern.h>\n#include <deal.II\/lac\/linear_operator.h>\n#include <deal.II\/lac\/sparse_matrix.h>\n#include <deal.II\/lac\/vector.h>\n#include <deal.II\/numerics\/matrix_tools.h>\n\n\/\/ Blaze include. All in one.\n#include <blaze\/Math.h>\n#include \"blaze_plugin.h\"\n\n#define EIGEN_MATRIX_PLUGIN \"eigen_plugin.h\"\n#include <Eigen\/Dense>\n#include <Eigen\/Sparse>\n\n\n\n#include <iostream>\n\nusing namespace dealii;\n\nint main(int argc, char *argv[])\n{\n if (argc != 3)\n throw ExcMessage(\"Invalid number of command line parameters\");\n unsigned int refinement = std::atoi(argv[1]);\n unsigned int reps = std::atoi(argv[2]);\n\n Triangulation<2> triangulation;\n GridGenerator::hyper_cube(triangulation);\n triangulation.refine_global(refinement);\n\n FE_Q<2> fe(1);\n DoFHandler<2> dof_handler;\n dof_handler.initialize(triangulation, fe);\n\n std::cout << \"n: \" << dof_handler.n_dofs() << std::endl;\n std::cout << \"reps: \" << reps << std::endl;\n\n DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);\n SparsityPattern sparsity_pattern;\n sparsity_pattern.copy_from(dynamic_sparsity_pattern);\n\n SparseMatrix<double> matrix;\n matrix.reinit(sparsity_pattern);\n\n QGauss<2> quadrature(2);\n MatrixCreator::create_laplace_matrix(dof_handler, quadrature, matrix);\n\n Vector<double> x(dof_handler.n_dofs());\n for (unsigned int i = 0; i < x.size(); ++i)\n x(i) = i;\n\n TimerOutput timer(std::cout, TimerOutput::summary, TimerOutput::wall_times);\n\n timer.enter_subsection (\"dealii_raw\");\n Vector<double> tmp(dof_handler.n_dofs());\n for (unsigned int i = 0; i < reps; ++i)\n {\n matrix.vmult(tmp, x);\n x = tmp;\n x \/= x.l2_norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << \"DEBUG\" << std::endl;\n std::cout << x << std::endl;\n#endif\n\n for (unsigned int i = 0; i < x.size(); ++i)\n x[i] = i;\n\n timer.enter_subsection (\"dealii_lo\");\n const auto op = linear_operator(matrix);\n for (unsigned int i = 0; i < reps; ++i)\n {\n op.vmult(x, x);\n x \/= x.l2_norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << x << std::endl;\n#endif\n\n \/\/ Now copy the sparse matrix to eigen and blaze\n blaze::CompressedMatrix<double, blaze::rowMajor> Bmatrix(dof_handler.n_dofs(), dof_handler.n_dofs());\n Eigen::SparseMatrix<double, Eigen::RowMajor> Ematrix(dof_handler.n_dofs(), dof_handler.n_dofs());\n\n typedef Eigen::Matrix<double, Eigen::Dynamic, 1, Eigen::ColMajor> EVector;\n \n Bmatrix.reserve(matrix.n_nonzero_elements());\n Ematrix.reserve(matrix.n_nonzero_elements());\n\n auto n = dof_handler.n_dofs();\n \n for(unsigned int i=0; i<n; ++i) {\n for(auto it = matrix.begin(i); it != matrix.end(i); ++it) {\n Bmatrix.append(i, it->column(), it->value());\n Ematrix.insert(i, it->column()) = it->value();\n }\n Bmatrix.finalize(i);\n }\n Ematrix.makeCompressed();\n\n \/\/ And create two vectors\n BVector Bxx(n);\n EVector Ex(n);\n\n auto &Bx = static_cast<BVector::T&>(Bxx);\n \n \/\/ ============================================================ Blaze Raw \n for (unsigned int i = 0; i < x.size(); ++i)\n Bx[i] = i;\n\n timer.enter_subsection (\"blaze_raw\");\n for (unsigned int i = 0; i < reps; ++i)\n {\n Bx = Bmatrix*Bx;\n Bx \/= std::sqrt(blaze::trans(Bx)*Bx);\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << Bx << std::endl;\n#endif\n\n \n \/\/ ============================================================ Eigen Raw \n for (unsigned int i = 0; i < x.size(); ++i)\n Ex[i] = i;\n\n timer.enter_subsection (\"eigen_raw\");\n for (unsigned int i = 0; i < reps; ++i)\n {\n Ex = Ematrix*Ex;\n Ex \/= Ex.norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << Ex << std::endl;\n#endif\n\n \n \/\/ ============================================================ Blaze LO\n \n LinearOperator<BVector, BVector> Blo;\n\n Blo.vmult = [&Bmatrix] (BVector &d, const BVector &s) {\n static_cast<BVector::T&>(d) = Bmatrix*s;\n };\n\n \n for (unsigned int i = 0; i < x.size(); ++i)\n Bx[i] = i;\n\n timer.enter_subsection (\"blaze_lo\");\n for (unsigned int i = 0; i < reps; ++i)\n {\n Blo.vmult(Bxx,Bxx);\n Bx \/= std::sqrt(blaze::trans(Bx)*Bx);\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << Bx << std::endl;\n#endif\n\n \n \/\/ ============================================================ Eigen LO\n \n LinearOperator<EVector, EVector> Elo;\n \n Elo.vmult = [&Ematrix] (EVector &d, const EVector &s) {\n d = Ematrix*s;\n };\n\n \n for (unsigned int i = 0; i < x.size(); ++i)\n Ex[i] = i;\n\n timer.enter_subsection (\"eigen_lo\");\n for (unsigned int i = 0; i < reps; ++i)\n {\n Elo.vmult(Ex,Ex);\n Ex \/= Ex.norm();\n }\n timer.leave_subsection();\n\n#ifdef DEBUG\n std::cout << Ex << std::endl;\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n copyright : (C) 2004 by Allan Sandfeld Jensen\n email : kde@carewolf.com\n ***************************************************************************\/\n\n\/***************************************************************************\n * This library is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http:\/\/www.mozilla.org\/MPL\/ *\n ***************************************************************************\/\n\n#include <tbytevectorlist.h>\n#include <tdebug.h>\n\n#include \"apeitem.h\"\n\nusing namespace TagLib;\nusing namespace APE;\n\nclass APE::Item::ItemPrivate\n{\npublic:\n ItemPrivate() :\n type(Text),\n readOnly(false) {}\n\n Item::ItemTypes type;\n String key;\n ByteVector value;\n StringList text;\n bool readOnly;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public members\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAPE::Item::Item() :\n d(new ItemPrivate())\n{\n}\n\nAPE::Item::Item(const String &key, const String &value) :\n d(new ItemPrivate())\n{\n d->key = key;\n d->text.append(value);\n}\n\nAPE::Item::Item(const String &key, const StringList &values) :\n d(new ItemPrivate())\n{\n d->key = key;\n d->text = values;\n}\n\nAPE::Item::Item(const String &key, const ByteVector &value, bool binary) :\n d(new ItemPrivate())\n{\n d->key = key;\n if(binary) {\n d->type = Binary;\n d->value = value;\n }\n else {\n d->text.append(value);\n }\n}\n\nAPE::Item::Item(const Item &item) :\n d(new ItemPrivate(*item.d))\n{\n}\n\nAPE::Item::~Item()\n{\n delete d;\n}\n\nItem &APE::Item::operator=(const Item &item)\n{\n Item(item).swap(*this);\n return *this;\n}\n\nvoid APE::Item::swap(Item &item)\n{\n using std::swap;\n\n swap(d, item.d);\n}\n\nvoid APE::Item::setReadOnly(bool readOnly)\n{\n d->readOnly = readOnly;\n}\n\nbool APE::Item::isReadOnly() const\n{\n return d->readOnly;\n}\n\nvoid APE::Item::setType(APE::Item::ItemTypes val)\n{\n d->type = val;\n}\n\nAPE::Item::ItemTypes APE::Item::type() const\n{\n return d->type;\n}\n\nString APE::Item::key() const\n{\n return d->key;\n}\n\nByteVector APE::Item::binaryData() const\n{\n return d->value;\n}\n\nvoid APE::Item::setBinaryData(const ByteVector &value)\n{\n d->type = Binary;\n d->value = value;\n d->text.clear();\n}\n\nByteVector APE::Item::value() const\n{\n \/\/ This seems incorrect as it won't be actually rendering the value to keep it\n \/\/ up to date.\n\n return d->value;\n}\n\nvoid APE::Item::setKey(const String &key)\n{\n d->key = key;\n}\n\nvoid APE::Item::setValue(const String &value)\n{\n d->type = Text;\n d->text = value;\n d->value.clear();\n}\n\nvoid APE::Item::setValues(const StringList &value)\n{\n d->type = Text;\n d->text = value;\n d->value.clear();\n}\n\nvoid APE::Item::appendValue(const String &value)\n{\n d->type = Text;\n d->text.append(value);\n d->value.clear();\n}\n\nvoid APE::Item::appendValues(const StringList &values)\n{\n d->type = Text;\n d->text.append(values);\n d->value.clear();\n}\n\nint APE::Item::size() const\n{\n int result = 8 + d->key.size() + 1;\n switch(d->type) {\n case Text:\n if(!d->text.isEmpty()) {\n StringList::ConstIterator it = d->text.begin();\n\n result += it->data(String::UTF8).size();\n it++;\n for(; it != d->text.end(); ++it)\n result += 1 + it->data(String::UTF8).size();\n }\n break;\n\n case Binary:\n case Locator:\n result += d->value.size();\n break;\n }\n return result;\n}\n\nStringList APE::Item::toStringList() const\n{\n return d->text;\n}\n\nStringList APE::Item::values() const\n{\n return d->text;\n}\n\nString APE::Item::toString() const\n{\n if(d->type == Text && !isEmpty())\n return d->text.front();\n else\n return String();\n}\n\nbool APE::Item::isEmpty() const\n{\n switch(d->type) {\n case Text:\n if(d->text.isEmpty())\n return true;\n if(d->text.size() == 1 && d->text.front().isEmpty())\n return true;\n return false;\n case Binary:\n case Locator:\n return d->value.isEmpty();\n default:\n return false;\n }\n}\n\nvoid APE::Item::parse(const ByteVector &data)\n{\n \/\/ 11 bytes is the minimum size for an APE item\n\n if(data.size() < 11) {\n debug(\"APE::Item::parse() -- no data in item\");\n return;\n }\n\n const unsigned int valueLength = data.toUInt(0, false);\n const unsigned int flags = data.toUInt(4, false);\n\n \/\/ An item key can contain ASCII characters from 0x20 up to 0x7E, not UTF-8.\n \/\/ We assume that the validity of the given key has been checked.\n\n d->key = String(&data[8], String::Latin1);\n\n const ByteVector value = data.mid(8 + d->key.size() + 1, valueLength);\n\n setReadOnly(flags & 1);\n setType(ItemTypes((flags >> 1) & 3));\n\n if(Text == d->type)\n d->text = StringList(ByteVectorList::split(value, '\\0'), String::UTF8);\n else\n d->value = value;\n}\n\nByteVector APE::Item::render() const\n{\n ByteVector data;\n unsigned int flags = ((d->readOnly) ? 1 : 0) | (d->type << 1);\n ByteVector value;\n\n if(isEmpty())\n return data;\n\n if(d->type == Text) {\n StringList::ConstIterator it = d->text.begin();\n\n value.append(it->data(String::UTF8));\n it++;\n for(; it != d->text.end(); ++it) {\n value.append('\\0');\n value.append(it->data(String::UTF8));\n }\n d->value = value;\n }\n else\n value.append(d->value);\n\n data.append(ByteVector::fromUInt(value.size(), false));\n data.append(ByteVector::fromUInt(flags, false));\n data.append(d->key.data(String::Latin1));\n data.append(ByteVector('\\0'));\n data.append(value);\n\n return data;\n}\n<commit_msg>clang-tidy: simplify boolean return<commit_after>\/***************************************************************************\n copyright : (C) 2004 by Allan Sandfeld Jensen\n email : kde@carewolf.com\n ***************************************************************************\/\n\n\/***************************************************************************\n * This library is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http:\/\/www.mozilla.org\/MPL\/ *\n ***************************************************************************\/\n\n#include <tbytevectorlist.h>\n#include <tdebug.h>\n\n#include \"apeitem.h\"\n\nusing namespace TagLib;\nusing namespace APE;\n\nclass APE::Item::ItemPrivate\n{\npublic:\n ItemPrivate() :\n type(Text),\n readOnly(false) {}\n\n Item::ItemTypes type;\n String key;\n ByteVector value;\n StringList text;\n bool readOnly;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public members\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAPE::Item::Item() :\n d(new ItemPrivate())\n{\n}\n\nAPE::Item::Item(const String &key, const String &value) :\n d(new ItemPrivate())\n{\n d->key = key;\n d->text.append(value);\n}\n\nAPE::Item::Item(const String &key, const StringList &values) :\n d(new ItemPrivate())\n{\n d->key = key;\n d->text = values;\n}\n\nAPE::Item::Item(const String &key, const ByteVector &value, bool binary) :\n d(new ItemPrivate())\n{\n d->key = key;\n if(binary) {\n d->type = Binary;\n d->value = value;\n }\n else {\n d->text.append(value);\n }\n}\n\nAPE::Item::Item(const Item &item) :\n d(new ItemPrivate(*item.d))\n{\n}\n\nAPE::Item::~Item()\n{\n delete d;\n}\n\nItem &APE::Item::operator=(const Item &item)\n{\n Item(item).swap(*this);\n return *this;\n}\n\nvoid APE::Item::swap(Item &item)\n{\n using std::swap;\n\n swap(d, item.d);\n}\n\nvoid APE::Item::setReadOnly(bool readOnly)\n{\n d->readOnly = readOnly;\n}\n\nbool APE::Item::isReadOnly() const\n{\n return d->readOnly;\n}\n\nvoid APE::Item::setType(APE::Item::ItemTypes val)\n{\n d->type = val;\n}\n\nAPE::Item::ItemTypes APE::Item::type() const\n{\n return d->type;\n}\n\nString APE::Item::key() const\n{\n return d->key;\n}\n\nByteVector APE::Item::binaryData() const\n{\n return d->value;\n}\n\nvoid APE::Item::setBinaryData(const ByteVector &value)\n{\n d->type = Binary;\n d->value = value;\n d->text.clear();\n}\n\nByteVector APE::Item::value() const\n{\n \/\/ This seems incorrect as it won't be actually rendering the value to keep it\n \/\/ up to date.\n\n return d->value;\n}\n\nvoid APE::Item::setKey(const String &key)\n{\n d->key = key;\n}\n\nvoid APE::Item::setValue(const String &value)\n{\n d->type = Text;\n d->text = value;\n d->value.clear();\n}\n\nvoid APE::Item::setValues(const StringList &value)\n{\n d->type = Text;\n d->text = value;\n d->value.clear();\n}\n\nvoid APE::Item::appendValue(const String &value)\n{\n d->type = Text;\n d->text.append(value);\n d->value.clear();\n}\n\nvoid APE::Item::appendValues(const StringList &values)\n{\n d->type = Text;\n d->text.append(values);\n d->value.clear();\n}\n\nint APE::Item::size() const\n{\n int result = 8 + d->key.size() + 1;\n switch(d->type) {\n case Text:\n if(!d->text.isEmpty()) {\n StringList::ConstIterator it = d->text.begin();\n\n result += it->data(String::UTF8).size();\n it++;\n for(; it != d->text.end(); ++it)\n result += 1 + it->data(String::UTF8).size();\n }\n break;\n\n case Binary:\n case Locator:\n result += d->value.size();\n break;\n }\n return result;\n}\n\nStringList APE::Item::toStringList() const\n{\n return d->text;\n}\n\nStringList APE::Item::values() const\n{\n return d->text;\n}\n\nString APE::Item::toString() const\n{\n if(d->type == Text && !isEmpty())\n return d->text.front();\n else\n return String();\n}\n\nbool APE::Item::isEmpty() const\n{\n switch(d->type) {\n case Text:\n if(d->text.isEmpty())\n return true;\n return d->text.size() == 1 && d->text.front().isEmpty();\n case Binary:\n case Locator:\n return d->value.isEmpty();\n default:\n return false;\n }\n}\n\nvoid APE::Item::parse(const ByteVector &data)\n{\n \/\/ 11 bytes is the minimum size for an APE item\n\n if(data.size() < 11) {\n debug(\"APE::Item::parse() -- no data in item\");\n return;\n }\n\n const unsigned int valueLength = data.toUInt(0, false);\n const unsigned int flags = data.toUInt(4, false);\n\n \/\/ An item key can contain ASCII characters from 0x20 up to 0x7E, not UTF-8.\n \/\/ We assume that the validity of the given key has been checked.\n\n d->key = String(&data[8], String::Latin1);\n\n const ByteVector value = data.mid(8 + d->key.size() + 1, valueLength);\n\n setReadOnly(flags & 1);\n setType(ItemTypes((flags >> 1) & 3));\n\n if(Text == d->type)\n d->text = StringList(ByteVectorList::split(value, '\\0'), String::UTF8);\n else\n d->value = value;\n}\n\nByteVector APE::Item::render() const\n{\n ByteVector data;\n unsigned int flags = ((d->readOnly) ? 1 : 0) | (d->type << 1);\n ByteVector value;\n\n if(isEmpty())\n return data;\n\n if(d->type == Text) {\n StringList::ConstIterator it = d->text.begin();\n\n value.append(it->data(String::UTF8));\n it++;\n for(; it != d->text.end(); ++it) {\n value.append('\\0');\n value.append(it->data(String::UTF8));\n }\n d->value = value;\n }\n else\n value.append(d->value);\n\n data.append(ByteVector::fromUInt(value.size(), false));\n data.append(ByteVector::fromUInt(flags, false));\n data.append(d->key.data(String::Latin1));\n data.append(ByteVector('\\0'));\n data.append(value);\n\n return data;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.10 2002\/12\/06 16:49:47 peiyongz\n * $XERCESCROOT\/msg created as home directory for message files.\n *\n * Revision 1.9 2002\/12\/04 18:03:13 peiyongz\n * use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME\n * undefined\n *\n * Revision 1.8 2002\/12\/02 21:58:43 peiyongz\n * nls support\n *\n * Revision 1.7 2002\/11\/12 17:27:12 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/05 16:54:46 peiyongz\n * Using XERCESC_NLS_HOME\n *\n * Revision 1.5 2002\/11\/04 15:10:41 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/09\/24 19:58:33 tng\n * Performance: use XMLString::equals instead of XMLString::compareString\n *\n * Revision 1.3 2002\/09\/23 21:05:40 peiyongz\n * remove debugging code\n *\n * Revision 1.2 2002\/09\/23 21:03:06 peiyongz\n * Build MsgCatalog on Solaris\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:21 peiyongz\n * sane_include\n *\n * Revision 1.7 2001\/10\/09 12:19:44 tng\n * Leak fix: can call transcode directly instead of using copyString.\n *\n * Revision 1.6 2000\/07\/25 22:28:40 aruna1\n * Char definitions in XMLUni moved to XMLUniDefs\n *\n * Revision 1.5 2000\/03\/02 19:55:16 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:22 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/05 22:00:22 aruna1\n * Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants\n *\n * Revision 1.2 1999\/12\/23 01:43:37 aruna1\n * MsgCatalog support added for solaris\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:16 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:45:27 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/XMLUni.hpp>\n#include \"MsgCatalogLoader.hpp\"\n#include \"XMLMsgCat_Ids.hpp\"\n\n#include <locale.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nMsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)\n:fCatalogHandle(0)\n,fMsgSet(0)\n{\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/\/ Prepare the path info\n char catpath[1024];\n memset(catpath, 0, sizeof catpath);\n char *nlsHome = getenv(\"XERCESC_NLS_HOME\");\n if (nlsHome)\n {\n strcpy(catpath, nlsHome);\n strcat(catpath, \"\/\");\n }\n else\n {\n char *altHome = getenv(\"XERCESCROOT\");\n if (altHome)\n {\n strcpy(catpath, altHome);\n strcat(catpath, \"\/msg\/\");\n }\n }\n\n \/\/ Prepare user-specified locale specific cat file\n char catuser[1024];\n memset(catuser, 0, sizeof catuser);\n strcpy(catuser, catpath);\n strcat(catuser, \"XMLMessages_\");\n strcat(catuser, XMLMsgLoader::getLocale());\n strcat(catuser, \".cat\");\n \n char catdefault[1024];\n memset(catdefault, 0, sizeof catdefault);\n strcpy(catdefault, catpath);\n strcat(catdefault, \"XMLMessages_en_US.cat\");\n\n \/**\n * To open user-specified locale specific cat file\n * and default cat file if necessary\n *\/\n if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&\n ((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )\n {\n \/\/ Probably have to call panic here\n printf(\"Could not open catalog:\\n %s\\n or %s\\n\", catuser, catdefault);\n exit(1);\n }\n\n if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))\n fMsgSet = CatId_XMLErrs;\n else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))\n fMsgSet = CatId_XMLExcepts;\n else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))\n fMsgSet = CatId_XMLValid;\n else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))\n fMsgSet = CatId_XMLDOMMsg;\n}\n\nMsgCatalogLoader::~MsgCatalogLoader()\n{\n catclose(fCatalogHandle);\t\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n char msgString[100];\n sprintf(msgString, \"Could not find message ID %d from message set %d\\n\", msgToLoad, fMsgSet);\n char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);\n\n \/\/ catgets returns a pointer to msgString if it fails to locate the message\n \/\/ from the message catalog\n if (XMLString::equals(catMessage, msgString))\n return false;\n else\n {\n XMLString::transcode(catMessage, toFill, maxChars);\n return true;\n }\n\t\n}\n\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<commit_msg>MsgCatalog file name changed.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.11 2002\/12\/12 16:46:18 peiyongz\n * MsgCatalog file name changed.\n *\n * Revision 1.10 2002\/12\/06 16:49:47 peiyongz\n * $XERCESCROOT\/msg created as home directory for message files.\n *\n * Revision 1.9 2002\/12\/04 18:03:13 peiyongz\n * use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME\n * undefined\n *\n * Revision 1.8 2002\/12\/02 21:58:43 peiyongz\n * nls support\n *\n * Revision 1.7 2002\/11\/12 17:27:12 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/05 16:54:46 peiyongz\n * Using XERCESC_NLS_HOME\n *\n * Revision 1.5 2002\/11\/04 15:10:41 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/09\/24 19:58:33 tng\n * Performance: use XMLString::equals instead of XMLString::compareString\n *\n * Revision 1.3 2002\/09\/23 21:05:40 peiyongz\n * remove debugging code\n *\n * Revision 1.2 2002\/09\/23 21:03:06 peiyongz\n * Build MsgCatalog on Solaris\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:21 peiyongz\n * sane_include\n *\n * Revision 1.7 2001\/10\/09 12:19:44 tng\n * Leak fix: can call transcode directly instead of using copyString.\n *\n * Revision 1.6 2000\/07\/25 22:28:40 aruna1\n * Char definitions in XMLUni moved to XMLUniDefs\n *\n * Revision 1.5 2000\/03\/02 19:55:16 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:22 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/05 22:00:22 aruna1\n * Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants\n *\n * Revision 1.2 1999\/12\/23 01:43:37 aruna1\n * MsgCatalog support added for solaris\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:16 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:45:27 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/XMLUni.hpp>\n#include \"MsgCatalogLoader.hpp\"\n#include \"XMLMsgCat_Ids.hpp\"\n\n#include <locale.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nMsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)\n:fCatalogHandle(0)\n,fMsgSet(0)\n{\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)\n && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/\/ Prepare the path info\n char catpath[1024];\n memset(catpath, 0, sizeof catpath);\n char *nlsHome = getenv(\"XERCESC_NLS_HOME\");\n if (nlsHome)\n {\n strcpy(catpath, nlsHome);\n strcat(catpath, \"\/\");\n }\n else\n {\n char *altHome = getenv(\"XERCESCROOT\");\n if (altHome)\n {\n strcpy(catpath, altHome);\n strcat(catpath, \"\/msg\/\");\n }\n }\n\n \/\/ Prepare user-specified locale specific cat file\n char catuser[1024];\n memset(catuser, 0, sizeof catuser);\n strcpy(catuser, catpath);\n strcat(catuser, \"XercesMessages_\");\n strcat(catuser, XMLMsgLoader::getLocale());\n strcat(catuser, \".cat\");\n \n char catdefault[1024];\n memset(catdefault, 0, sizeof catdefault);\n strcpy(catdefault, catpath);\n strcat(catdefault, \"XercesMessages_en_US.cat\");\n\n \/**\n * To open user-specified locale specific cat file\n * and default cat file if necessary\n *\/\n if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&\n ((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )\n {\n \/\/ Probably have to call panic here\n printf(\"Could not open catalog:\\n %s\\n or %s\\n\", catuser, catdefault);\n exit(1);\n }\n\n if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))\n fMsgSet = CatId_XMLErrs;\n else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))\n fMsgSet = CatId_XMLExcepts;\n else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))\n fMsgSet = CatId_XMLValid;\n else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))\n fMsgSet = CatId_XMLDOMMsg;\n}\n\nMsgCatalogLoader::~MsgCatalogLoader()\n{\n catclose(fCatalogHandle);\t\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n char msgString[100];\n sprintf(msgString, \"Could not find message ID %d from message set %d\\n\", msgToLoad, fMsgSet);\n char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);\n\n \/\/ catgets returns a pointer to msgString if it fails to locate the message\n \/\/ from the message catalog\n if (XMLString::equals(catMessage, msgString))\n return false;\n else\n {\n XMLString::transcode(catMessage, toFill, maxChars);\n return true;\n }\n\t\n}\n\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <stdio.h>\n#include <xercesc\/util\/OutOfMemoryException.hpp>\n#include <xercesc\/util\/XMLUTF8Transcoder.hpp>\n#include <xercesc\/validators\/datatype\/AnyURIDatatypeValidator.hpp>\n#include <xercesc\/validators\/datatype\/InvalidDatatypeFacetException.hpp>\n#include <xercesc\/validators\/datatype\/InvalidDatatypeValueException.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nAnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)\n:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)\n{}\n\nAnyURIDatatypeValidator::~AnyURIDatatypeValidator()\n{ \n}\n\nAnyURIDatatypeValidator::AnyURIDatatypeValidator(\n DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager)\n:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)\n{\n init(enums, manager);\n}\n\nDatatypeValidator* AnyURIDatatypeValidator::newInstance(\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager)\n{\n return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Utilities\n\/\/ ---------------------------------------------------------------------------\n\nvoid AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content\n , MemoryManager* const manager)\n{\n bool validURI = true;\n\n \/\/ check 3.2.17.c0 must: URI (rfc 2396\/2723)\n try\n {\n \/\/ Support for relative URLs\n \/\/ According to Java 1.1: URLs may also be specified with a\n \/\/ String and the URL object that it is related to.\n \/\/\n const unsigned int len = XMLString::stringLen(content);\n if (len)\n { \n \/\/ Encode special characters using XLink 5.4 algorithm\n XMLCh* encoded = (XMLCh*)manager->allocate((len*3+1) * sizeof(XMLCh));\n ArrayJanitor<XMLCh> encodedJan(encoded);\n encode(content, len, encoded, manager);\n validURI = XMLUri::isValidURI(true, encoded, true); \n }\n }\n catch(const OutOfMemoryException&)\n {\n throw;\n }\n catch (...)\n {\n ThrowXMLwithMemMgr1(InvalidDatatypeValueException\n , XMLExcepts::VALUE_URI_Malformed\n , content\n , manager);\n }\n \n if (!validURI) {\n ThrowXMLwithMemMgr1(InvalidDatatypeValueException\n , XMLExcepts::VALUE_URI_Malformed\n , content\n , manager);\n }\n}\n\n\/***\n * To encode special characters in anyURI, by using %HH to represent\n * special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', etc.\n * and non-ASCII characters (whose value >= 128).\n ***\/\nvoid AnyURIDatatypeValidator::encode(const XMLCh* const content, const XMLSize_t len, XMLCh* encoded, MemoryManager* const manager)\n{\n static const bool needEscapeMap[] = {\n true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , \/* 0x00 to 0x0F need escape *\/\n true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , \/* 0x10 to 0x1F need escape *\/\n true , false, true , false, false, false, false, false, false, false, false, false, false, false, false, false, \/* 0x20:' ', 0x22:'\"' *\/\n false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, \/* 0x3C:'<', 0x3E:'>' *\/\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,\n false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, \/* 0x5C:'\\\\', 0x5E:'^' *\/\n true , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, \/* 0x60:'`' *\/\n false, false, false, false, false, false, false, false, false, false, false, true , true , true , true , true \/* 0x7B:'{', 0x7C:'|', 0x7D:'}', 0x7E:'~', 0x7F:DEL *\/\n };\n\n int bufferIndex = 0;\n\n \/\/ For each character in content\n XMLSize_t i;\n for (i = 0; i < len; i++)\n {\n int ch = (int)content[i];\n \/\/ If it's not an ASCII character, break here, and use UTF-8 encoding\n if (ch >= 128)\n break;\n\n if (needEscapeMap[ch])\n {\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", ch);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else\n {\n encoded[bufferIndex++] = (XMLCh)ch;\n }\n }\n\n \/\/ we saw some non-ascii character\n if (i < len) {\n \/\/ get UTF-8 bytes for the remaining sub-string\n const XMLCh* remContent = (XMLCh*)&content[i];\n const XMLSize_t remContentLen = len - i;\n XMLByte* UTF8Byte = (XMLByte*)manager->allocate((remContentLen*4+1) * sizeof(XMLByte));\n XMLSize_t charsEaten;\n\n XMLUTF8Transcoder transcoder(XMLUni::fgUTF8EncodingString, remContentLen*4+1, manager);\n transcoder.transcodeTo(remContent, remContentLen, UTF8Byte, remContentLen*4, charsEaten, XMLTranscoder::UnRep_RepChar);\n assert(charsEaten == remContentLen);\n\n XMLSize_t j;\n for (j = 0; j < remContentLen; j++) {\n XMLByte b = UTF8Byte[j];\n \/\/ for non-ascii character: make it positive, then escape\n if (b < 0) {\n int ch = b + 256;\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", ch);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else if (needEscapeMap[b])\n {\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", b);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else\n {\n encoded[bufferIndex++] = (XMLCh)b;\n }\n }\n manager->deallocate(UTF8Byte);\n }\n\n encoded[bufferIndex] = (XMLCh)0;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)\n\nvoid AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)\n{\n AbstractStringValidator::serialize(serEng);\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file AnyURIDatatypeValidator.cpp\n *\/\n<commit_msg>Pass in memory manager to janitor.<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <stdio.h>\n#include <xercesc\/util\/OutOfMemoryException.hpp>\n#include <xercesc\/util\/XMLUTF8Transcoder.hpp>\n#include <xercesc\/validators\/datatype\/AnyURIDatatypeValidator.hpp>\n#include <xercesc\/validators\/datatype\/InvalidDatatypeFacetException.hpp>\n#include <xercesc\/validators\/datatype\/InvalidDatatypeValueException.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nAnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)\n:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)\n{}\n\nAnyURIDatatypeValidator::~AnyURIDatatypeValidator()\n{ \n}\n\nAnyURIDatatypeValidator::AnyURIDatatypeValidator(\n DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager)\n:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)\n{\n init(enums, manager);\n}\n\nDatatypeValidator* AnyURIDatatypeValidator::newInstance(\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager)\n{\n return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Utilities\n\/\/ ---------------------------------------------------------------------------\n\nvoid AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content\n , MemoryManager* const manager)\n{\n bool validURI = true;\n\n \/\/ check 3.2.17.c0 must: URI (rfc 2396\/2723)\n try\n {\n \/\/ Support for relative URLs\n \/\/ According to Java 1.1: URLs may also be specified with a\n \/\/ String and the URL object that it is related to.\n \/\/\n const unsigned int len = XMLString::stringLen(content);\n if (len)\n { \n \/\/ Encode special characters using XLink 5.4 algorithm\n XMLCh* encoded = (XMLCh*)manager->allocate((len*3+1) * sizeof(XMLCh));\n ArrayJanitor<XMLCh> encodedJan(encoded, manager);\n encode(content, len, encoded, manager);\n validURI = XMLUri::isValidURI(true, encoded, true); \n }\n }\n catch(const OutOfMemoryException&)\n {\n throw;\n }\n catch (...)\n {\n ThrowXMLwithMemMgr1(InvalidDatatypeValueException\n , XMLExcepts::VALUE_URI_Malformed\n , content\n , manager);\n }\n \n if (!validURI) {\n ThrowXMLwithMemMgr1(InvalidDatatypeValueException\n , XMLExcepts::VALUE_URI_Malformed\n , content\n , manager);\n }\n}\n\n\/***\n * To encode special characters in anyURI, by using %HH to represent\n * special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', etc.\n * and non-ASCII characters (whose value >= 128).\n ***\/\nvoid AnyURIDatatypeValidator::encode(const XMLCh* const content, const XMLSize_t len, XMLCh* encoded, MemoryManager* const manager)\n{\n static const bool needEscapeMap[] = {\n true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , \/* 0x00 to 0x0F need escape *\/\n true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , \/* 0x10 to 0x1F need escape *\/\n true , false, true , false, false, false, false, false, false, false, false, false, false, false, false, false, \/* 0x20:' ', 0x22:'\"' *\/\n false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, \/* 0x3C:'<', 0x3E:'>' *\/\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,\n false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, \/* 0x5C:'\\\\', 0x5E:'^' *\/\n true , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, \/* 0x60:'`' *\/\n false, false, false, false, false, false, false, false, false, false, false, true , true , true , true , true \/* 0x7B:'{', 0x7C:'|', 0x7D:'}', 0x7E:'~', 0x7F:DEL *\/\n };\n\n int bufferIndex = 0;\n\n \/\/ For each character in content\n XMLSize_t i;\n for (i = 0; i < len; i++)\n {\n int ch = (int)content[i];\n \/\/ If it's not an ASCII character, break here, and use UTF-8 encoding\n if (ch >= 128)\n break;\n\n if (needEscapeMap[ch])\n {\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", ch);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else\n {\n encoded[bufferIndex++] = (XMLCh)ch;\n }\n }\n\n \/\/ we saw some non-ascii character\n if (i < len) {\n \/\/ get UTF-8 bytes for the remaining sub-string\n const XMLCh* remContent = (XMLCh*)&content[i];\n const XMLSize_t remContentLen = len - i;\n XMLByte* UTF8Byte = (XMLByte*)manager->allocate((remContentLen*4+1) * sizeof(XMLByte));\n XMLSize_t charsEaten;\n\n XMLUTF8Transcoder transcoder(XMLUni::fgUTF8EncodingString, remContentLen*4+1, manager);\n transcoder.transcodeTo(remContent, remContentLen, UTF8Byte, remContentLen*4, charsEaten, XMLTranscoder::UnRep_RepChar);\n assert(charsEaten == remContentLen);\n\n XMLSize_t j;\n for (j = 0; j < remContentLen; j++) {\n XMLByte b = UTF8Byte[j];\n \/\/ for non-ascii character: make it positive, then escape\n if (b < 0) {\n int ch = b + 256;\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", ch);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else if (needEscapeMap[b])\n {\n char tempStr[2] = \"\\0\";\n sprintf(tempStr, \"%02X\", b);\n encoded[bufferIndex++] = '%';\n encoded[bufferIndex++] = (XMLCh)tempStr[0];\n encoded[bufferIndex++] = (XMLCh)tempStr[1];\n }\n else\n {\n encoded[bufferIndex++] = (XMLCh)b;\n }\n }\n manager->deallocate(UTF8Byte);\n }\n\n encoded[bufferIndex] = (XMLCh)0;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)\n\nvoid AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)\n{\n AbstractStringValidator::serialize(serEng);\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file AnyURIDatatypeValidator.cpp\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ Commandline tool to unpack audioproc debug files.\n\/\/\n\/\/ The debug files are dumped as protobuf blobs. For analysis, it's necessary\n\/\/ to unpack the file into its component parts: audio and other data.\n\n#include <stdio.h>\n\n#include \"gflags\/gflags.h\"\n#include \"webrtc\/audio_processing\/debug.pb.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/modules\/audio_processing\/test\/test_utils.h\"\n#include \"webrtc\/typedefs.h\"\n\n\/\/ TODO(andrew): unpack more of the data.\nDEFINE_string(input_file, \"input\", \"The name of the input stream file.\");\nDEFINE_string(output_file, \"ref_out\",\n \"The name of the reference output stream file.\");\nDEFINE_string(reverse_file, \"reverse\",\n \"The name of the reverse input stream file.\");\nDEFINE_string(delay_file, \"delay.int32\", \"The name of the delay file.\");\nDEFINE_string(drift_file, \"drift.int32\", \"The name of the drift file.\");\nDEFINE_string(level_file, \"level.int32\", \"The name of the level file.\");\nDEFINE_string(keypress_file, \"keypress.bool\", \"The name of the keypress file.\");\nDEFINE_string(settings_file, \"settings.txt\", \"The name of the settings file.\");\nDEFINE_bool(full, false,\n \"Unpack the full set of files (normally not needed).\");\nDEFINE_bool(raw, false, \"Write raw data instead of a WAV file.\");\n\nnamespace webrtc {\n\nusing audioproc::Event;\nusing audioproc::ReverseStream;\nusing audioproc::Stream;\nusing audioproc::Init;\n\nvoid WriteData(const void* data, size_t size, FILE* file,\n const std::string& filename) {\n if (fwrite(data, size, 1, file) != 1) {\n printf(\"Error when writing to %s\\n\", filename.c_str());\n exit(1);\n }\n}\n\nint do_main(int argc, char* argv[]) {\n std::string program_name = argv[0];\n std::string usage = \"Commandline tool to unpack audioproc debug files.\\n\"\n \"Example usage:\\n\" + program_name + \" debug_dump.pb\\n\";\n google::SetUsageMessage(usage);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc < 2) {\n printf(\"%s\", google::ProgramUsage());\n return 1;\n }\n\n FILE* debug_file = OpenFile(argv[1], \"rb\");\n\n Event event_msg;\n int frame_count = 0;\n int reverse_samples_per_channel = 0;\n int input_samples_per_channel = 0;\n int output_samples_per_channel = 0;\n int num_reverse_channels = 0;\n int num_input_channels = 0;\n int num_output_channels = 0;\n rtc::scoped_ptr<WavWriter> reverse_wav_file;\n rtc::scoped_ptr<WavWriter> input_wav_file;\n rtc::scoped_ptr<WavWriter> output_wav_file;\n rtc::scoped_ptr<RawFile> reverse_raw_file;\n rtc::scoped_ptr<RawFile> input_raw_file;\n rtc::scoped_ptr<RawFile> output_raw_file;\n while (ReadMessageFromFile(debug_file, &event_msg)) {\n if (event_msg.type() == Event::REVERSE_STREAM) {\n if (!event_msg.has_reverse_stream()) {\n printf(\"Corrupt input file: ReverseStream missing.\\n\");\n return 1;\n }\n\n const ReverseStream msg = event_msg.reverse_stream();\n if (msg.has_data()) {\n if (FLAGS_raw && !reverse_raw_file) {\n reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + \".pcm\"));\n }\n \/\/ TODO(aluebs): Replace \"num_reverse_channels *\n \/\/ reverse_samples_per_channel\" with \"msg.data().size() \/\n \/\/ sizeof(int16_t)\" and so on when this fix in audio_processing has made\n \/\/ it into stable: https:\/\/webrtc-codereview.appspot.com\/15299004\/\n WriteIntData(reinterpret_cast<const int16_t*>(msg.data().data()),\n num_reverse_channels * reverse_samples_per_channel,\n reverse_wav_file.get(),\n reverse_raw_file.get());\n } else if (msg.channel_size() > 0) {\n if (FLAGS_raw && !reverse_raw_file) {\n reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_reverse_channels]);\n for (int i = 0; i < num_reverse_channels; ++i) {\n data[i] = reinterpret_cast<const float*>(msg.channel(i).data());\n }\n WriteFloatData(data.get(),\n reverse_samples_per_channel,\n num_reverse_channels,\n reverse_wav_file.get(),\n reverse_raw_file.get());\n }\n } else if (event_msg.type() == Event::STREAM) {\n frame_count++;\n if (!event_msg.has_stream()) {\n printf(\"Corrupt input file: Stream missing.\\n\");\n return 1;\n }\n\n const Stream msg = event_msg.stream();\n if (msg.has_input_data()) {\n if (FLAGS_raw && !input_raw_file) {\n input_raw_file.reset(new RawFile(FLAGS_input_file + \".pcm\"));\n }\n WriteIntData(reinterpret_cast<const int16_t*>(msg.input_data().data()),\n num_input_channels * input_samples_per_channel,\n input_wav_file.get(),\n input_raw_file.get());\n } else if (msg.input_channel_size() > 0) {\n if (FLAGS_raw && !input_raw_file) {\n input_raw_file.reset(new RawFile(FLAGS_input_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_input_channels]);\n for (int i = 0; i < num_input_channels; ++i) {\n data[i] = reinterpret_cast<const float*>(msg.input_channel(i).data());\n }\n WriteFloatData(data.get(),\n input_samples_per_channel,\n num_input_channels,\n input_wav_file.get(),\n input_raw_file.get());\n }\n\n if (msg.has_output_data()) {\n if (FLAGS_raw && !output_raw_file) {\n output_raw_file.reset(new RawFile(FLAGS_output_file + \".pcm\"));\n }\n WriteIntData(reinterpret_cast<const int16_t*>(msg.output_data().data()),\n num_output_channels * output_samples_per_channel,\n output_wav_file.get(),\n output_raw_file.get());\n } else if (msg.output_channel_size() > 0) {\n if (FLAGS_raw && !output_raw_file) {\n output_raw_file.reset(new RawFile(FLAGS_output_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_output_channels]);\n for (int i = 0; i < num_output_channels; ++i) {\n data[i] =\n reinterpret_cast<const float*>(msg.output_channel(i).data());\n }\n WriteFloatData(data.get(),\n output_samples_per_channel,\n num_output_channels,\n output_wav_file.get(),\n output_raw_file.get());\n }\n\n if (FLAGS_full) {\n if (msg.has_delay()) {\n static FILE* delay_file = OpenFile(FLAGS_delay_file, \"wb\");\n int32_t delay = msg.delay();\n WriteData(&delay, sizeof(delay), delay_file, FLAGS_delay_file);\n }\n\n if (msg.has_drift()) {\n static FILE* drift_file = OpenFile(FLAGS_drift_file, \"wb\");\n int32_t drift = msg.drift();\n WriteData(&drift, sizeof(drift), drift_file, FLAGS_drift_file);\n }\n\n if (msg.has_level()) {\n static FILE* level_file = OpenFile(FLAGS_level_file, \"wb\");\n int32_t level = msg.level();\n WriteData(&level, sizeof(level), level_file, FLAGS_level_file);\n }\n\n if (msg.has_keypress()) {\n static FILE* keypress_file = OpenFile(FLAGS_keypress_file, \"wb\");\n bool keypress = msg.keypress();\n WriteData(&keypress, sizeof(keypress), keypress_file,\n FLAGS_keypress_file);\n }\n }\n } else if (event_msg.type() == Event::INIT) {\n if (!event_msg.has_init()) {\n printf(\"Corrupt input file: Init missing.\\n\");\n return 1;\n }\n\n static FILE* settings_file = OpenFile(FLAGS_settings_file, \"wb\");\n const Init msg = event_msg.init();\n \/\/ These should print out zeros if they're missing.\n fprintf(settings_file, \"Init at frame: %d\\n\", frame_count);\n int input_sample_rate = msg.sample_rate();\n fprintf(settings_file, \" Input sample rate: %d\\n\", input_sample_rate);\n int output_sample_rate = msg.output_sample_rate();\n fprintf(settings_file, \" Output sample rate: %d\\n\", output_sample_rate);\n int reverse_sample_rate = msg.reverse_sample_rate();\n fprintf(settings_file,\n \" Reverse sample rate: %d\\n\",\n reverse_sample_rate);\n num_input_channels = msg.num_input_channels();\n fprintf(settings_file, \" Input channels: %d\\n\", num_input_channels);\n num_output_channels = msg.num_output_channels();\n fprintf(settings_file, \" Output channels: %d\\n\", num_output_channels);\n num_reverse_channels = msg.num_reverse_channels();\n fprintf(settings_file, \" Reverse channels: %d\\n\", num_reverse_channels);\n\n fprintf(settings_file, \"\\n\");\n\n if (reverse_sample_rate == 0) {\n reverse_sample_rate = input_sample_rate;\n }\n if (output_sample_rate == 0) {\n output_sample_rate = input_sample_rate;\n }\n\n reverse_samples_per_channel = reverse_sample_rate \/ 100;\n input_samples_per_channel = input_sample_rate \/ 100;\n output_samples_per_channel = output_sample_rate \/ 100;\n\n if (!FLAGS_raw) {\n \/\/ The WAV files need to be reset every time, because they cant change\n \/\/ their sample rate or number of channels.\n reverse_wav_file.reset(new WavWriter(FLAGS_reverse_file + \".wav\",\n reverse_sample_rate,\n num_reverse_channels));\n input_wav_file.reset(new WavWriter(FLAGS_input_file + \".wav\",\n input_sample_rate,\n num_input_channels));\n output_wav_file.reset(new WavWriter(FLAGS_output_file + \".wav\",\n output_sample_rate,\n num_output_channels));\n }\n }\n }\n\n return 0;\n}\n\n} \/\/ namespace webrtc\n\nint main(int argc, char* argv[]) {\n return webrtc::do_main(argc, argv);\n}\n<commit_msg>audio_processing\/tests: Adds a flag to unpack input data to text file<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ Commandline tool to unpack audioproc debug files.\n\/\/\n\/\/ The debug files are dumped as protobuf blobs. For analysis, it's necessary\n\/\/ to unpack the file into its component parts: audio and other data.\n\n#include <stdio.h>\n\n#include \"gflags\/gflags.h\"\n#include \"webrtc\/audio_processing\/debug.pb.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/modules\/audio_processing\/test\/test_utils.h\"\n#include \"webrtc\/typedefs.h\"\n\n\/\/ TODO(andrew): unpack more of the data.\nDEFINE_string(input_file, \"input\", \"The name of the input stream file.\");\nDEFINE_string(output_file, \"ref_out\",\n \"The name of the reference output stream file.\");\nDEFINE_string(reverse_file, \"reverse\",\n \"The name of the reverse input stream file.\");\nDEFINE_string(delay_file, \"delay.int32\", \"The name of the delay file.\");\nDEFINE_string(drift_file, \"drift.int32\", \"The name of the drift file.\");\nDEFINE_string(level_file, \"level.int32\", \"The name of the level file.\");\nDEFINE_string(keypress_file, \"keypress.bool\", \"The name of the keypress file.\");\nDEFINE_string(settings_file, \"settings.txt\", \"The name of the settings file.\");\nDEFINE_bool(full, false,\n \"Unpack the full set of files (normally not needed).\");\nDEFINE_bool(raw, false, \"Write raw data instead of a WAV file.\");\nDEFINE_bool(text,\n false,\n \"Write non-audio files as text files instead of binary files.\");\n\nnamespace webrtc {\n\nusing audioproc::Event;\nusing audioproc::ReverseStream;\nusing audioproc::Stream;\nusing audioproc::Init;\n\nvoid WriteData(const void* data, size_t size, FILE* file,\n const std::string& filename) {\n if (fwrite(data, size, 1, file) != 1) {\n printf(\"Error when writing to %s\\n\", filename.c_str());\n exit(1);\n }\n}\n\nint do_main(int argc, char* argv[]) {\n std::string program_name = argv[0];\n std::string usage = \"Commandline tool to unpack audioproc debug files.\\n\"\n \"Example usage:\\n\" + program_name + \" debug_dump.pb\\n\";\n google::SetUsageMessage(usage);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc < 2) {\n printf(\"%s\", google::ProgramUsage());\n return 1;\n }\n\n FILE* debug_file = OpenFile(argv[1], \"rb\");\n\n Event event_msg;\n int frame_count = 0;\n int reverse_samples_per_channel = 0;\n int input_samples_per_channel = 0;\n int output_samples_per_channel = 0;\n int num_reverse_channels = 0;\n int num_input_channels = 0;\n int num_output_channels = 0;\n rtc::scoped_ptr<WavWriter> reverse_wav_file;\n rtc::scoped_ptr<WavWriter> input_wav_file;\n rtc::scoped_ptr<WavWriter> output_wav_file;\n rtc::scoped_ptr<RawFile> reverse_raw_file;\n rtc::scoped_ptr<RawFile> input_raw_file;\n rtc::scoped_ptr<RawFile> output_raw_file;\n while (ReadMessageFromFile(debug_file, &event_msg)) {\n if (event_msg.type() == Event::REVERSE_STREAM) {\n if (!event_msg.has_reverse_stream()) {\n printf(\"Corrupt input file: ReverseStream missing.\\n\");\n return 1;\n }\n\n const ReverseStream msg = event_msg.reverse_stream();\n if (msg.has_data()) {\n if (FLAGS_raw && !reverse_raw_file) {\n reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + \".pcm\"));\n }\n \/\/ TODO(aluebs): Replace \"num_reverse_channels *\n \/\/ reverse_samples_per_channel\" with \"msg.data().size() \/\n \/\/ sizeof(int16_t)\" and so on when this fix in audio_processing has made\n \/\/ it into stable: https:\/\/webrtc-codereview.appspot.com\/15299004\/\n WriteIntData(reinterpret_cast<const int16_t*>(msg.data().data()),\n num_reverse_channels * reverse_samples_per_channel,\n reverse_wav_file.get(),\n reverse_raw_file.get());\n } else if (msg.channel_size() > 0) {\n if (FLAGS_raw && !reverse_raw_file) {\n reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_reverse_channels]);\n for (int i = 0; i < num_reverse_channels; ++i) {\n data[i] = reinterpret_cast<const float*>(msg.channel(i).data());\n }\n WriteFloatData(data.get(),\n reverse_samples_per_channel,\n num_reverse_channels,\n reverse_wav_file.get(),\n reverse_raw_file.get());\n }\n } else if (event_msg.type() == Event::STREAM) {\n frame_count++;\n if (!event_msg.has_stream()) {\n printf(\"Corrupt input file: Stream missing.\\n\");\n return 1;\n }\n\n const Stream msg = event_msg.stream();\n if (msg.has_input_data()) {\n if (FLAGS_raw && !input_raw_file) {\n input_raw_file.reset(new RawFile(FLAGS_input_file + \".pcm\"));\n }\n WriteIntData(reinterpret_cast<const int16_t*>(msg.input_data().data()),\n num_input_channels * input_samples_per_channel,\n input_wav_file.get(),\n input_raw_file.get());\n } else if (msg.input_channel_size() > 0) {\n if (FLAGS_raw && !input_raw_file) {\n input_raw_file.reset(new RawFile(FLAGS_input_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_input_channels]);\n for (int i = 0; i < num_input_channels; ++i) {\n data[i] = reinterpret_cast<const float*>(msg.input_channel(i).data());\n }\n WriteFloatData(data.get(),\n input_samples_per_channel,\n num_input_channels,\n input_wav_file.get(),\n input_raw_file.get());\n }\n\n if (msg.has_output_data()) {\n if (FLAGS_raw && !output_raw_file) {\n output_raw_file.reset(new RawFile(FLAGS_output_file + \".pcm\"));\n }\n WriteIntData(reinterpret_cast<const int16_t*>(msg.output_data().data()),\n num_output_channels * output_samples_per_channel,\n output_wav_file.get(),\n output_raw_file.get());\n } else if (msg.output_channel_size() > 0) {\n if (FLAGS_raw && !output_raw_file) {\n output_raw_file.reset(new RawFile(FLAGS_output_file + \".float\"));\n }\n rtc::scoped_ptr<const float* []> data(\n new const float* [num_output_channels]);\n for (int i = 0; i < num_output_channels; ++i) {\n data[i] =\n reinterpret_cast<const float*>(msg.output_channel(i).data());\n }\n WriteFloatData(data.get(),\n output_samples_per_channel,\n num_output_channels,\n output_wav_file.get(),\n output_raw_file.get());\n }\n\n if (FLAGS_full) {\n if (msg.has_delay()) {\n static FILE* delay_file = OpenFile(FLAGS_delay_file, \"wb\");\n int32_t delay = msg.delay();\n if (FLAGS_text) {\n fprintf(delay_file, \"%d\\n\", delay);\n } else {\n WriteData(&delay, sizeof(delay), delay_file, FLAGS_delay_file);\n }\n }\n\n if (msg.has_drift()) {\n static FILE* drift_file = OpenFile(FLAGS_drift_file, \"wb\");\n int32_t drift = msg.drift();\n if (FLAGS_text) {\n fprintf(drift_file, \"%d\\n\", drift);\n } else {\n WriteData(&drift, sizeof(drift), drift_file, FLAGS_drift_file);\n }\n }\n\n if (msg.has_level()) {\n static FILE* level_file = OpenFile(FLAGS_level_file, \"wb\");\n int32_t level = msg.level();\n if (FLAGS_text) {\n fprintf(level_file, \"%d\\n\", level);\n } else {\n WriteData(&level, sizeof(level), level_file, FLAGS_level_file);\n }\n }\n\n if (msg.has_keypress()) {\n static FILE* keypress_file = OpenFile(FLAGS_keypress_file, \"wb\");\n bool keypress = msg.keypress();\n if (FLAGS_text) {\n fprintf(keypress_file, \"%d\\n\", keypress);\n } else {\n WriteData(&keypress, sizeof(keypress), keypress_file,\n FLAGS_keypress_file);\n }\n }\n }\n } else if (event_msg.type() == Event::INIT) {\n if (!event_msg.has_init()) {\n printf(\"Corrupt input file: Init missing.\\n\");\n return 1;\n }\n\n static FILE* settings_file = OpenFile(FLAGS_settings_file, \"wb\");\n const Init msg = event_msg.init();\n \/\/ These should print out zeros if they're missing.\n fprintf(settings_file, \"Init at frame: %d\\n\", frame_count);\n int input_sample_rate = msg.sample_rate();\n fprintf(settings_file, \" Input sample rate: %d\\n\", input_sample_rate);\n int output_sample_rate = msg.output_sample_rate();\n fprintf(settings_file, \" Output sample rate: %d\\n\", output_sample_rate);\n int reverse_sample_rate = msg.reverse_sample_rate();\n fprintf(settings_file,\n \" Reverse sample rate: %d\\n\",\n reverse_sample_rate);\n num_input_channels = msg.num_input_channels();\n fprintf(settings_file, \" Input channels: %d\\n\", num_input_channels);\n num_output_channels = msg.num_output_channels();\n fprintf(settings_file, \" Output channels: %d\\n\", num_output_channels);\n num_reverse_channels = msg.num_reverse_channels();\n fprintf(settings_file, \" Reverse channels: %d\\n\", num_reverse_channels);\n\n fprintf(settings_file, \"\\n\");\n\n if (reverse_sample_rate == 0) {\n reverse_sample_rate = input_sample_rate;\n }\n if (output_sample_rate == 0) {\n output_sample_rate = input_sample_rate;\n }\n\n reverse_samples_per_channel = reverse_sample_rate \/ 100;\n input_samples_per_channel = input_sample_rate \/ 100;\n output_samples_per_channel = output_sample_rate \/ 100;\n\n if (!FLAGS_raw) {\n \/\/ The WAV files need to be reset every time, because they cant change\n \/\/ their sample rate or number of channels.\n reverse_wav_file.reset(new WavWriter(FLAGS_reverse_file + \".wav\",\n reverse_sample_rate,\n num_reverse_channels));\n input_wav_file.reset(new WavWriter(FLAGS_input_file + \".wav\",\n input_sample_rate,\n num_input_channels));\n output_wav_file.reset(new WavWriter(FLAGS_output_file + \".wav\",\n output_sample_rate,\n num_output_channels));\n }\n }\n }\n\n return 0;\n}\n\n} \/\/ namespace webrtc\n\nint main(int argc, char* argv[]) {\n return webrtc::do_main(argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ansi_display_driver.hpp\"\n\n#include \"document\/code_line_element.hpp\"\n#include \"tools\/ansi_wrapper.hpp\"\n\n#include <iostream>\nusing namespace std;\n\ntypedef AnsiWrapper::Color Color;\n\nvoid AnsiDisplayDriver::display(Document * doc) {\n\tdisplay(doc, cout);\n}\n\nvoid AnsiDisplayDriver::display(Document * doc, ostream & output) {\n\tParagraph *p(nullptr);\n\tLineElement *l(nullptr);\n\tCodeLineElement *code_le(nullptr);\n\n\tAnsiWrapper wrapper(output);\n\n\tfor (size_t i(0); i < doc->size(); ++i) {\n\t\tp = (*doc)[i];\n\t\tswitch (p->level()) {\n\t\t\tcase Paragraph::Level::Title1:\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\twrapper.underline();\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::Title2:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::Quote:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\twrapper.reverse();\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::UList1:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Cyan);\n\t\t\t\twrapper << \"* \";\n\t\t\t\twrapper.reset();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\twrapper << \" \";\n\t\t\t\tbreak;\n\n\t\t}\n\t\tfor (size_t j(0); j < p->size(); ++j) {\n\t\t\tl = (*p)[j];\n\t\t\tcode_le = dynamic_cast<CodeLineElement*>(l);\n\n\t\t\tif (code_le) {\n\t\t\t\twrapper.reverse();\n\t\t\t}\n\n\t\t\twrapper << l->content();\n\t\t\t\n\t\t\twrapper.reset();\n\n\t\t}\n\t\twrapper.reset();\n\t\twrapper << endl;\n\t}\n}\n\n<commit_msg>Add Title3 to AnsiDisplayDriver<commit_after>#include \"ansi_display_driver.hpp\"\n\n#include \"document\/code_line_element.hpp\"\n#include \"tools\/ansi_wrapper.hpp\"\n\n#include <iostream>\nusing namespace std;\n\ntypedef AnsiWrapper::Color Color;\n\nvoid AnsiDisplayDriver::display(Document * doc) {\n\tdisplay(doc, cout);\n}\n\nvoid AnsiDisplayDriver::display(Document * doc, ostream & output) {\n\tParagraph *p(nullptr);\n\tLineElement *l(nullptr);\n\tCodeLineElement *code_le(nullptr);\n\n\tAnsiWrapper wrapper(output);\n\n\tfor (size_t i(0); i < doc->size(); ++i) {\n\t\tp = (*doc)[i];\n\t\tswitch (p->level()) {\n\t\t\tcase Paragraph::Level::Title1:\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\twrapper.underline();\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::Title2:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::Title3:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::Quote:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Blue);\n\t\t\t\twrapper.reverse();\n\t\t\t\tbreak;\n\t\t\tcase Paragraph::Level::UList1:\n\t\t\t\twrapper << \" \";\n\t\t\t\twrapper.fg(Color::Cyan);\n\t\t\t\twrapper << \"* \";\n\t\t\t\twrapper.reset();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\twrapper << \" \";\n\t\t\t\tbreak;\n\n\t\t}\n\t\tfor (size_t j(0); j < p->size(); ++j) {\n\t\t\tl = (*p)[j];\n\t\t\tcode_le = dynamic_cast<CodeLineElement*>(l);\n\n\t\t\tif (code_le) {\n\t\t\t\twrapper.reverse();\n\t\t\t}\n\n\t\t\twrapper << l->content();\n\t\t\t\n\t\t\twrapper.reset();\n\n\t\t}\n\t\twrapper.reset();\n\t\twrapper << endl;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/filters\/ffmpeg_video_decode_engine.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/task.h\"\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/limits.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"media\/ffmpeg\/ffmpeg_common.h\"\n#include \"media\/ffmpeg\/ffmpeg_util.h\"\n#include \"media\/filters\/ffmpeg_demuxer.h\"\n\nnamespace media {\n\nFFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine()\n : codec_context_(NULL),\n av_stream_(NULL),\n event_handler_(NULL) {\n}\n\nFFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() {\n}\n\nvoid FFmpegVideoDecodeEngine::Initialize(\n MessageLoop* message_loop,\n VideoDecodeEngine::EventHandler* event_handler,\n const VideoCodecConfig& config) {\n \/\/ Always try to use three threads for video decoding. There is little reason\n \/\/ not to since current day CPUs tend to be multi-core and we measured\n \/\/ performance benefits on older machines such as P4s with hyperthreading.\n \/\/\n \/\/ Handling decoding on separate threads also frees up the pipeline thread to\n \/\/ continue processing. Although it'd be nice to have the option of a single\n \/\/ decoding thread, FFmpeg treats having one thread the same as having zero\n \/\/ threads (i.e., avcodec_decode_video() will execute on the calling thread).\n \/\/ Yet another reason for having three threads :)\n static const int kDecodeThreads = 3;\n static const int kMaxDecodeThreads = 16;\n\n\n av_stream_ = static_cast<AVStream*>(config.opaque_context_);\n codec_context_ = av_stream_->codec;\n codec_context_->flags2 |= CODEC_FLAG2_FAST; \/\/ Enable faster H264 decode.\n \/\/ Enable motion vector search (potentially slow), strong deblocking filter\n \/\/ for damaged macroblocks, and set our error detection sensitivity.\n codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;\n codec_context_->error_recognition = FF_ER_CAREFUL;\n\n AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);\n\n \/\/ TODO(fbarchard): Improve thread logic based on size \/ codec.\n int decode_threads = kDecodeThreads;\n\n const CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));\n if ((!threads.empty() &&\n !base::StringToInt(threads, &decode_threads)) ||\n decode_threads < 0 || decode_threads > kMaxDecodeThreads) {\n decode_threads = kDecodeThreads;\n }\n\n \/\/ We don't allocate AVFrame on the stack since different versions of FFmpeg\n \/\/ may change the size of AVFrame, causing stack corruption. The solution is\n \/\/ to let FFmpeg allocate the structure via avcodec_alloc_frame().\n av_frame_.reset(avcodec_alloc_frame());\n VideoCodecInfo info;\n info.success_ = false;\n info.provides_buffers_ = false;\n info.stream_info_.surface_type_ = VideoFrame::TYPE_SYSTEM_MEMORY;\n info.stream_info_.surface_format_ = GetSurfaceFormat();\n info.stream_info_.surface_width_ = config.width_;\n info.stream_info_.surface_height_ = config.height_;\n if (codec &&\n avcodec_thread_init(codec_context_, decode_threads) >= 0 &&\n avcodec_open(codec_context_, codec) >= 0 &&\n av_frame_.get()) {\n info.success_ = true;\n }\n#if !defined(FF_THREAD_FRAME)\n#pragma message (\"Warning: Not building with FFmpeg MT.\")\n#else\n#pragma message (\"Building with FFmpeg MT.\")\n#endif\n event_handler_ = event_handler;\n event_handler_->OnInitializeComplete(info);\n}\n\n\/\/ TODO(fbarchard): Find way to remove this memcpy of the entire image.\nstatic void CopyPlane(size_t plane,\n scoped_refptr<VideoFrame> video_frame,\n const AVFrame* frame) {\n DCHECK_EQ(video_frame->width() % 2, 0u);\n const uint8* source = frame->data[plane];\n const size_t source_stride = frame->linesize[plane];\n uint8* dest = video_frame->data(plane);\n const size_t dest_stride = video_frame->stride(plane);\n size_t bytes_per_line = video_frame->width();\n size_t copy_lines = video_frame->height();\n if (plane != VideoFrame::kYPlane) {\n bytes_per_line \/= 2;\n if (video_frame->format() == VideoFrame::YV12) {\n copy_lines = (copy_lines + 1) \/ 2;\n }\n }\n DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride);\n for (size_t i = 0; i < copy_lines; ++i) {\n memcpy(dest, source, bytes_per_line);\n source += source_stride;\n dest += dest_stride;\n }\n}\n\nvoid FFmpegVideoDecodeEngine::EmptyThisBuffer(\n scoped_refptr<Buffer> buffer) {\n DecodeFrame(buffer);\n}\n\nvoid FFmpegVideoDecodeEngine::FillThisBuffer(scoped_refptr<VideoFrame> frame) {\n scoped_refptr<Buffer> buffer;\n event_handler_->OnEmptyBufferCallback(buffer);\n}\n\n\/\/ Try to decode frame when both input and output are ready.\nvoid FFmpegVideoDecodeEngine::DecodeFrame(scoped_refptr<Buffer> buffer) {\n scoped_refptr<VideoFrame> video_frame;\n\n \/\/ Create a packet for input data.\n \/\/ Due to FFmpeg API changes we no longer have const read-only pointers.\n AVPacket packet;\n av_init_packet(&packet);\n packet.data = const_cast<uint8*>(buffer->GetData());\n packet.size = buffer->GetDataSize();\n\n \/\/ Let FFmpeg handle presentation timestamp reordering.\n codec_context_->reordered_opaque = buffer->GetTimestamp().InMicroseconds();\n\n \/\/ This is for codecs not using get_buffer to initialize\n \/\/ |av_frame_->reordered_opaque|\n av_frame_->reordered_opaque = codec_context_->reordered_opaque;\n\n int frame_decoded = 0;\n int result = avcodec_decode_video2(codec_context_,\n av_frame_.get(),\n &frame_decoded,\n &packet);\n\n \/\/ Log the problem if we can't decode a video frame and exit early.\n if (result < 0) {\n LOG(INFO) << \"Error decoding a video frame with timestamp: \"\n << buffer->GetTimestamp().InMicroseconds() << \" us\"\n << \" , duration: \"\n << buffer->GetDuration().InMicroseconds() << \" us\"\n << \" , packet size: \"\n << buffer->GetDataSize() << \" bytes\";\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ If frame_decoded == 0, then no frame was produced.\n if (frame_decoded == 0) {\n if (buffer->IsEndOfStream()) \/\/ We had started flushing.\n event_handler_->OnFillBufferCallback(video_frame);\n else\n event_handler_->OnEmptyBufferCallback(buffer);\n return;\n }\n\n \/\/ TODO(fbarchard): Work around for FFmpeg http:\/\/crbug.com\/27675\n \/\/ The decoder is in a bad state and not decoding correctly.\n \/\/ Checking for NULL avoids a crash in CopyPlane().\n if (!av_frame_->data[VideoFrame::kYPlane] ||\n !av_frame_->data[VideoFrame::kUPlane] ||\n !av_frame_->data[VideoFrame::kVPlane]) {\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ Determine timestamp and calculate the duration based on the repeat picture\n \/\/ count. According to FFmpeg docs, the total duration can be calculated as\n \/\/ follows:\n \/\/ duration = (1 \/ fps) + (repeat_pict) \/ (2 * fps)\n \/\/ = (2 + repeat_pict) \/ (2 * fps)\n DCHECK_LE(av_frame_->repeat_pict, 2); \/\/ Sanity check.\n \/\/ Even frame rate is fixed, for some streams and codecs, the value of\n \/\/ |codec_context_->time_base| and |av_stream_->time_base| are not the\n \/\/ inverse of the |av_stream_->r_frame_rate|. They use 1 milli-second as\n \/\/ time-base units and use increment of av_packet->pts which is not one.\n \/\/ Use the inverse of |av_stream_->r_frame_rate| instead of time_base.\n AVRational doubled_time_base;\n doubled_time_base.den = av_stream_->r_frame_rate.num;\n doubled_time_base.num = av_stream_->r_frame_rate.den;\n doubled_time_base.den *= 2;\n\n base::TimeDelta timestamp =\n base::TimeDelta::FromMicroseconds(av_frame_->reordered_opaque);\n base::TimeDelta duration =\n ConvertTimestamp(doubled_time_base, 2 + av_frame_->repeat_pict);\n\n VideoFrame::CreateFrame(GetSurfaceFormat(),\n codec_context_->width,\n codec_context_->height,\n timestamp,\n duration,\n &video_frame);\n if (!video_frame.get()) {\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ Copy the frame data since FFmpeg reuses internal buffers for AVFrame\n \/\/ output, meaning the data is only valid until the next\n \/\/ avcodec_decode_video() call.\n \/\/ TODO(scherkus): figure out pre-allocation\/buffer cycling scheme.\n \/\/ TODO(scherkus): is there a cleaner way to figure out the # of planes?\n CopyPlane(VideoFrame::kYPlane, video_frame.get(), av_frame_.get());\n CopyPlane(VideoFrame::kUPlane, video_frame.get(), av_frame_.get());\n CopyPlane(VideoFrame::kVPlane, video_frame.get(), av_frame_.get());\n\n event_handler_->OnFillBufferCallback(video_frame);\n}\n\nvoid FFmpegVideoDecodeEngine::Uninitialize() {\n \/\/ TODO(jiesun): Release buffers when we support buffer recycling.\n event_handler_->OnUninitializeComplete();\n}\n\nvoid FFmpegVideoDecodeEngine::Flush() {\n avcodec_flush_buffers(codec_context_);\n event_handler_->OnFlushComplete();\n}\n\nvoid FFmpegVideoDecodeEngine::Seek() {\n event_handler_->OnSeekComplete();\n}\n\nVideoFrame::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const {\n \/\/ J (Motion JPEG) versions of YUV are full range 0..255.\n \/\/ Regular (MPEG) YUV is 16..240.\n \/\/ For now we will ignore the distinction and treat them the same.\n switch (codec_context_->pix_fmt) {\n case PIX_FMT_YUV420P:\n case PIX_FMT_YUVJ420P:\n return VideoFrame::YV12;\n break;\n case PIX_FMT_YUV422P:\n case PIX_FMT_YUVJ422P:\n return VideoFrame::YV16;\n break;\n default:\n \/\/ TODO(scherkus): More formats here?\n return VideoFrame::INVALID;\n }\n}\n\n} \/\/ namespace media\n<commit_msg>remove pragma message to fix build issue BUG=none TEST=none<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/filters\/ffmpeg_video_decode_engine.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/task.h\"\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/limits.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"media\/ffmpeg\/ffmpeg_common.h\"\n#include \"media\/ffmpeg\/ffmpeg_util.h\"\n#include \"media\/filters\/ffmpeg_demuxer.h\"\n\nnamespace media {\n\nFFmpegVideoDecodeEngine::FFmpegVideoDecodeEngine()\n : codec_context_(NULL),\n av_stream_(NULL),\n event_handler_(NULL) {\n}\n\nFFmpegVideoDecodeEngine::~FFmpegVideoDecodeEngine() {\n}\n\nvoid FFmpegVideoDecodeEngine::Initialize(\n MessageLoop* message_loop,\n VideoDecodeEngine::EventHandler* event_handler,\n const VideoCodecConfig& config) {\n \/\/ Always try to use three threads for video decoding. There is little reason\n \/\/ not to since current day CPUs tend to be multi-core and we measured\n \/\/ performance benefits on older machines such as P4s with hyperthreading.\n \/\/\n \/\/ Handling decoding on separate threads also frees up the pipeline thread to\n \/\/ continue processing. Although it'd be nice to have the option of a single\n \/\/ decoding thread, FFmpeg treats having one thread the same as having zero\n \/\/ threads (i.e., avcodec_decode_video() will execute on the calling thread).\n \/\/ Yet another reason for having three threads :)\n static const int kDecodeThreads = 3;\n static const int kMaxDecodeThreads = 16;\n\n\n av_stream_ = static_cast<AVStream*>(config.opaque_context_);\n codec_context_ = av_stream_->codec;\n codec_context_->flags2 |= CODEC_FLAG2_FAST; \/\/ Enable faster H264 decode.\n \/\/ Enable motion vector search (potentially slow), strong deblocking filter\n \/\/ for damaged macroblocks, and set our error detection sensitivity.\n codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;\n codec_context_->error_recognition = FF_ER_CAREFUL;\n\n AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);\n\n \/\/ TODO(fbarchard): Improve thread logic based on size \/ codec.\n int decode_threads = kDecodeThreads;\n\n const CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));\n if ((!threads.empty() &&\n !base::StringToInt(threads, &decode_threads)) ||\n decode_threads < 0 || decode_threads > kMaxDecodeThreads) {\n decode_threads = kDecodeThreads;\n }\n\n \/\/ We don't allocate AVFrame on the stack since different versions of FFmpeg\n \/\/ may change the size of AVFrame, causing stack corruption. The solution is\n \/\/ to let FFmpeg allocate the structure via avcodec_alloc_frame().\n av_frame_.reset(avcodec_alloc_frame());\n VideoCodecInfo info;\n info.success_ = false;\n info.provides_buffers_ = false;\n info.stream_info_.surface_type_ = VideoFrame::TYPE_SYSTEM_MEMORY;\n info.stream_info_.surface_format_ = GetSurfaceFormat();\n info.stream_info_.surface_width_ = config.width_;\n info.stream_info_.surface_height_ = config.height_;\n if (codec &&\n avcodec_thread_init(codec_context_, decode_threads) >= 0 &&\n avcodec_open(codec_context_, codec) >= 0 &&\n av_frame_.get()) {\n info.success_ = true;\n }\n event_handler_ = event_handler;\n event_handler_->OnInitializeComplete(info);\n}\n\n\/\/ TODO(fbarchard): Find way to remove this memcpy of the entire image.\nstatic void CopyPlane(size_t plane,\n scoped_refptr<VideoFrame> video_frame,\n const AVFrame* frame) {\n DCHECK_EQ(video_frame->width() % 2, 0u);\n const uint8* source = frame->data[plane];\n const size_t source_stride = frame->linesize[plane];\n uint8* dest = video_frame->data(plane);\n const size_t dest_stride = video_frame->stride(plane);\n size_t bytes_per_line = video_frame->width();\n size_t copy_lines = video_frame->height();\n if (plane != VideoFrame::kYPlane) {\n bytes_per_line \/= 2;\n if (video_frame->format() == VideoFrame::YV12) {\n copy_lines = (copy_lines + 1) \/ 2;\n }\n }\n DCHECK(bytes_per_line <= source_stride && bytes_per_line <= dest_stride);\n for (size_t i = 0; i < copy_lines; ++i) {\n memcpy(dest, source, bytes_per_line);\n source += source_stride;\n dest += dest_stride;\n }\n}\n\nvoid FFmpegVideoDecodeEngine::EmptyThisBuffer(\n scoped_refptr<Buffer> buffer) {\n DecodeFrame(buffer);\n}\n\nvoid FFmpegVideoDecodeEngine::FillThisBuffer(scoped_refptr<VideoFrame> frame) {\n scoped_refptr<Buffer> buffer;\n event_handler_->OnEmptyBufferCallback(buffer);\n}\n\n\/\/ Try to decode frame when both input and output are ready.\nvoid FFmpegVideoDecodeEngine::DecodeFrame(scoped_refptr<Buffer> buffer) {\n scoped_refptr<VideoFrame> video_frame;\n\n \/\/ Create a packet for input data.\n \/\/ Due to FFmpeg API changes we no longer have const read-only pointers.\n AVPacket packet;\n av_init_packet(&packet);\n packet.data = const_cast<uint8*>(buffer->GetData());\n packet.size = buffer->GetDataSize();\n\n \/\/ Let FFmpeg handle presentation timestamp reordering.\n codec_context_->reordered_opaque = buffer->GetTimestamp().InMicroseconds();\n\n \/\/ This is for codecs not using get_buffer to initialize\n \/\/ |av_frame_->reordered_opaque|\n av_frame_->reordered_opaque = codec_context_->reordered_opaque;\n\n int frame_decoded = 0;\n int result = avcodec_decode_video2(codec_context_,\n av_frame_.get(),\n &frame_decoded,\n &packet);\n\n \/\/ Log the problem if we can't decode a video frame and exit early.\n if (result < 0) {\n LOG(INFO) << \"Error decoding a video frame with timestamp: \"\n << buffer->GetTimestamp().InMicroseconds() << \" us\"\n << \" , duration: \"\n << buffer->GetDuration().InMicroseconds() << \" us\"\n << \" , packet size: \"\n << buffer->GetDataSize() << \" bytes\";\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ If frame_decoded == 0, then no frame was produced.\n if (frame_decoded == 0) {\n if (buffer->IsEndOfStream()) \/\/ We had started flushing.\n event_handler_->OnFillBufferCallback(video_frame);\n else\n event_handler_->OnEmptyBufferCallback(buffer);\n return;\n }\n\n \/\/ TODO(fbarchard): Work around for FFmpeg http:\/\/crbug.com\/27675\n \/\/ The decoder is in a bad state and not decoding correctly.\n \/\/ Checking for NULL avoids a crash in CopyPlane().\n if (!av_frame_->data[VideoFrame::kYPlane] ||\n !av_frame_->data[VideoFrame::kUPlane] ||\n !av_frame_->data[VideoFrame::kVPlane]) {\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ Determine timestamp and calculate the duration based on the repeat picture\n \/\/ count. According to FFmpeg docs, the total duration can be calculated as\n \/\/ follows:\n \/\/ duration = (1 \/ fps) + (repeat_pict) \/ (2 * fps)\n \/\/ = (2 + repeat_pict) \/ (2 * fps)\n DCHECK_LE(av_frame_->repeat_pict, 2); \/\/ Sanity check.\n \/\/ Even frame rate is fixed, for some streams and codecs, the value of\n \/\/ |codec_context_->time_base| and |av_stream_->time_base| are not the\n \/\/ inverse of the |av_stream_->r_frame_rate|. They use 1 milli-second as\n \/\/ time-base units and use increment of av_packet->pts which is not one.\n \/\/ Use the inverse of |av_stream_->r_frame_rate| instead of time_base.\n AVRational doubled_time_base;\n doubled_time_base.den = av_stream_->r_frame_rate.num;\n doubled_time_base.num = av_stream_->r_frame_rate.den;\n doubled_time_base.den *= 2;\n\n base::TimeDelta timestamp =\n base::TimeDelta::FromMicroseconds(av_frame_->reordered_opaque);\n base::TimeDelta duration =\n ConvertTimestamp(doubled_time_base, 2 + av_frame_->repeat_pict);\n\n VideoFrame::CreateFrame(GetSurfaceFormat(),\n codec_context_->width,\n codec_context_->height,\n timestamp,\n duration,\n &video_frame);\n if (!video_frame.get()) {\n \/\/ TODO(jiesun): call event_handler_->OnError() instead.\n event_handler_->OnFillBufferCallback(video_frame);\n return;\n }\n\n \/\/ Copy the frame data since FFmpeg reuses internal buffers for AVFrame\n \/\/ output, meaning the data is only valid until the next\n \/\/ avcodec_decode_video() call.\n \/\/ TODO(scherkus): figure out pre-allocation\/buffer cycling scheme.\n \/\/ TODO(scherkus): is there a cleaner way to figure out the # of planes?\n CopyPlane(VideoFrame::kYPlane, video_frame.get(), av_frame_.get());\n CopyPlane(VideoFrame::kUPlane, video_frame.get(), av_frame_.get());\n CopyPlane(VideoFrame::kVPlane, video_frame.get(), av_frame_.get());\n\n event_handler_->OnFillBufferCallback(video_frame);\n}\n\nvoid FFmpegVideoDecodeEngine::Uninitialize() {\n \/\/ TODO(jiesun): Release buffers when we support buffer recycling.\n event_handler_->OnUninitializeComplete();\n}\n\nvoid FFmpegVideoDecodeEngine::Flush() {\n avcodec_flush_buffers(codec_context_);\n event_handler_->OnFlushComplete();\n}\n\nvoid FFmpegVideoDecodeEngine::Seek() {\n event_handler_->OnSeekComplete();\n}\n\nVideoFrame::Format FFmpegVideoDecodeEngine::GetSurfaceFormat() const {\n \/\/ J (Motion JPEG) versions of YUV are full range 0..255.\n \/\/ Regular (MPEG) YUV is 16..240.\n \/\/ For now we will ignore the distinction and treat them the same.\n switch (codec_context_->pix_fmt) {\n case PIX_FMT_YUV420P:\n case PIX_FMT_YUVJ420P:\n return VideoFrame::YV12;\n break;\n case PIX_FMT_YUV422P:\n case PIX_FMT_YUVJ422P:\n return VideoFrame::YV16;\n break;\n default:\n \/\/ TODO(scherkus): More formats here?\n return VideoFrame::INVALID;\n }\n}\n\n} \/\/ namespace media\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <sstream>\n#include <vector>\n\n#include \"Tools\/Exception\/exception.hpp\"\n\n#include \"Sparse_matrix.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::tools;\n\nSparse_matrix\n::Sparse_matrix(const size_t n_rows, const size_t n_cols)\n: Matrix(n_rows, n_cols),\n row_to_cols(n_rows),\n col_to_rows(n_cols)\n{\n}\n\nbool Sparse_matrix\n::at(const size_t row_index, const size_t col_index) const\n{\n\tauto it = std::find(this->row_to_cols[row_index].begin(), this->row_to_cols[row_index].end(), col_index);\n\treturn (it != this->row_to_cols[row_index].end());\n}\n\nvoid Sparse_matrix\n::add_connection(const size_t row_index, const size_t col_index)\n{\n\tcheck_indexes(row_index, col_index);\n\n\tif (at(row_index, col_index))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"('row_index';'col_index') connection already exists ('row_index' = \" << row_index\n\t\t << \", 'col_index' = \" << col_index << \").\";\n\t\tthrow runtime_error(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tthis->row_to_cols[row_index].push_back(col_index);\n\tthis->col_to_rows[col_index].push_back(row_index);\n\n\tthis->rows_max_degree = std::max(get_rows_max_degree(), row_to_cols[row_index].size());\n\tthis->cols_max_degree = std::max(get_cols_max_degree(), col_to_rows[col_index].size());\n\n\tthis->n_connections++;\n}\n\nvoid Sparse_matrix\n::rm_connection(const size_t row_index, const size_t col_index)\n{\n\tcheck_indexes(row_index, col_index);\n\n\t\/\/ delete the link in the row_to_cols vector\n\tbool row_found = false;\n\tauto itr = std::find(this->row_to_cols[row_index].begin(), this->row_to_cols[row_index].end(), col_index);\n\tif (itr != this->row_to_cols[row_index].end())\n\t{\n\t\trow_found = true;\n\t\titr = this->row_to_cols[row_index].erase(itr);\n\n\t\t\/\/ check if need to reduce the rows max degree\n\t\tif (this->row_to_cols[row_index].size() == (this->rows_max_degree-1))\n\t\t{\n\t\t\tbool found = false;\n\t\t\tfor (auto i = this->row_to_cols.begin(); i != this->row_to_cols.end(); i++ )\n\t\t\t\tif (i->size() == this->rows_max_degree)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tif (!found)\n\t\t\t\tthis->rows_max_degree--;\n\t\t}\n\t}\n\n\t\/\/ delete the link in the col_to_rows vector\n\tbool col_found = false;\n\tauto itc = std::find(this->col_to_rows[col_index].begin(), this->col_to_rows[col_index].end(), row_index);\n\tif (itc != this->col_to_rows[col_index].end())\n\t{\n\t\tcol_found = true;\n\t\tthis->col_to_rows[col_index].erase(itc);\n\n\t\t\/\/ check if need to reduce the cols max degree\n\t\tif (this->col_to_rows[col_index].size() == (this->cols_max_degree-1))\n\t\t{\n\t\t\tbool found = false;\n\t\t\tfor (auto i = this->col_to_rows.begin(); i != this->col_to_rows.end(); i++ )\n\t\t\t\tif (i->size() == this->cols_max_degree)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tif (!found)\n\t\t\t\tthis->cols_max_degree--;\n\t\t}\n\t}\n\n\tif (row_found != col_found)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"The connection has been found only in one of the two vectors 'row_to_cols' and 'col_to_rows' \"\n\t\t << \"('row_index' = \" << row_index << \", 'col_index' = \" << col_index\n\t\t << \", found in row = \" << std::boolalpha << row_found\n\t\t << \", found in col = \" << col_found << std::noboolalpha << \").\";\n\t\tthrow tools::runtime_error(__FILE__, __LINE__, __func__, message.str());\n\t}\n\telse if (row_found && col_found)\n\t\tthis->n_connections--;\n\t\/\/ else the connection has not been found\n}\n\nvoid Sparse_matrix\n::parse_connections()\n{\n\tthis->n_connections = std::accumulate(row_to_cols.begin(), row_to_cols.end(), (size_t)0,\n\t [](size_t init, const std::vector<size_t>& a){ return init + a.size();});\n\n\tthis->rows_max_degree = std::max_element(row_to_cols.begin(), row_to_cols.end(),\n\t [](const std::vector<size_t>& a, const std::vector<size_t>& b){ return a.size() < b.size();})\n\t ->size();\n\tthis->cols_max_degree = std::max_element(col_to_rows.begin(), col_to_rows.end(),\n\t [](const std::vector<size_t>& a, const std::vector<size_t>& b){ return a.size() < b.size();})\n\t ->size();\n}\n\nvoid Sparse_matrix\n::self_resize(const size_t n_rows, const size_t n_cols, Origin o)\n{\n\t*this = this->resize(n_rows, n_rows, o);\n}\n\nSparse_matrix Sparse_matrix\n::resize(const size_t n_rows, const size_t n_cols, Origin o) const\n{\n\tSparse_matrix resized(n_rows, n_cols);\n\n\t\/\/ const auto min_r = std::min(n_rows, get_n_rows());\n\tconst auto min_c = std::min(n_cols, get_n_cols());\n\t\/\/ const auto diff_r = get_n_rows() - min_r;\n\tconst auto diff_c = get_n_cols() - min_c;\n\tconst auto diff_n_rows = (int)n_rows - (int)get_n_rows();\n\tconst auto diff_n_cols = (int)n_cols - (int)get_n_cols();\n\n\tswitch(o)\n\t{\n\t\tcase Origin::TOP_LEFT:\n\t\t{\n\t\t\tfor (size_t c = 0; c < min_c; c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = c;\n\t\t\t\t\tconst auto row_index = col_to_rows[c][r];\n\t\t\t\t\tif (row_index < n_rows)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::TOP_RIGHT:\n\t\t{\n\t\t\tfor (size_t c = diff_c; c < get_n_cols(); c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = diff_n_cols + c;\n\t\t\t\t\tconst auto row_index = col_to_rows[c][r];\n\t\t\t\t\tif (row_index < n_rows)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::BOTTOM_LEFT:\n\t\t{\n\t\t\tfor (size_t c = 0; c < min_c; c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = c;\n\t\t\t\t\tconst auto row_index = diff_n_rows + (int)col_to_rows[c][r];\n\t\t\t\t\tif (row_index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::BOTTOM_RIGHT:\n\t\t{\n\t\t\tfor (size_t c = diff_c; c < get_n_cols(); c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = diff_n_cols + c;\n\t\t\t\t\tconst auto row_index = diff_n_rows + (int)col_to_rows[c][r];\n\t\t\t\t\tif (row_index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tresized.parse_connections();\n\n\treturn resized;\n}\n\nSparse_matrix Sparse_matrix\n::transpose() const\n{\n\tSparse_matrix trans(*this);\n\n\ttrans.self_transpose();\n\n\treturn trans;\n}\n\nvoid Sparse_matrix\n::self_transpose()\n{\n\tMatrix::self_transpose();\n\n\tstd::swap(row_to_cols, col_to_rows);\n}\n\nSparse_matrix Sparse_matrix\n::turn(Way w) const\n{\n\tSparse_matrix turned(*this);\n\n\tturned.self_turn(w);\n\n\treturn turned;\n}\n\nvoid Sparse_matrix\n::sort_cols_per_density(Sort order)\n{\n\tswitch(order)\n\t{\n\t\tcase Sort::ASCENDING:\n\t\t\tstd::sort(this->col_to_rows.begin(), this->col_to_rows.end(),\n\t\t\t [](const std::vector<size_t> &i1, const std::vector<size_t> &i2) { return i1.size() < i2.size(); });\n\t\tbreak;\n\t\tcase Sort::DESCENDING:\n\t\t\tstd::sort(this->col_to_rows.begin(), this->col_to_rows.end(),\n\t\t [](const std::vector<size_t> &i1, const std::vector<size_t> &i2) { return i1.size() > i2.size(); });\n\t\tbreak;\n\t}\n\n\tfor (auto &r : this->row_to_cols)\n\t\tr.clear();\n\tfor (size_t i = 0; i < this->col_to_rows.size(); i++)\n\t\tfor (size_t j = 0; j < this->col_to_rows[i].size(); j++)\n\t\t\tthis->row_to_cols[this->col_to_rows[i][j]].push_back(i);\n}\n\nvoid Sparse_matrix\n::print(bool transpose, std::ostream& os) const\n{\n\tif (transpose)\n\t{\n\t\tstd::vector<unsigned> rows(get_n_rows(), 0);\n\n\t\tfor (auto& col : this->col_to_rows)\n\t\t{\n\t\t\t\/\/ set the ones\n\t\t\tfor (auto& row : col)\n\t\t\t\trows[row] = 1;\n\n\t\t\tfor (auto& row : rows)\n\t\t\t\tos << row << \" \";\n\n\t\t\tos << std::endl;\n\n\t\t\t\/\/ reset the ones\n\t\t\tfor (auto& row : col)\n\t\t\t\trows[row] = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::vector<unsigned> columns(get_n_cols(), 0);\n\n\t\tfor (auto& row : this->row_to_cols)\n\t\t{\n\t\t\t\/\/ set the ones\n\t\t\tfor (auto& col : row)\n\t\t\t\tcolumns[col] = 1;\n\n\t\t\tfor (auto& col : columns)\n\t\t\t\tos << col << \" \";\n\n\t\t\tos << std::endl;\n\n\t\t\t\/\/ reset the ones\n\t\t\tfor (auto& col : row)\n\t\t\t\tcolumns[col] = 0;\n\t\t}\n\t}\n}\n\nSparse_matrix Sparse_matrix\n::identity(const size_t n_rows, const size_t n_cols)\n{\n\tSparse_matrix mat(n_rows, n_cols);\n\tauto shortest_side = std::min(n_rows, n_cols);\n\n\tfor (size_t i = 0; i < shortest_side; i++)\n\t\tmat.add_connection(i,i);\n\n\treturn mat;\n}\n\nSparse_matrix Sparse_matrix\n::zero(const size_t n_rows, const size_t n_cols)\n{\n\treturn Sparse_matrix(n_rows, n_cols);\n}<commit_msg>Add 'numeric' include for windows compilo<commit_after>#include <string>\n#include <sstream>\n#include <vector>\n#include <numeric>\n\n#include \"Tools\/Exception\/exception.hpp\"\n\n#include \"Sparse_matrix.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::tools;\n\nSparse_matrix\n::Sparse_matrix(const size_t n_rows, const size_t n_cols)\n: Matrix(n_rows, n_cols),\n row_to_cols(n_rows),\n col_to_rows(n_cols)\n{\n}\n\nbool Sparse_matrix\n::at(const size_t row_index, const size_t col_index) const\n{\n\tauto it = std::find(this->row_to_cols[row_index].begin(), this->row_to_cols[row_index].end(), col_index);\n\treturn (it != this->row_to_cols[row_index].end());\n}\n\nvoid Sparse_matrix\n::add_connection(const size_t row_index, const size_t col_index)\n{\n\tcheck_indexes(row_index, col_index);\n\n\tif (at(row_index, col_index))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"('row_index';'col_index') connection already exists ('row_index' = \" << row_index\n\t\t << \", 'col_index' = \" << col_index << \").\";\n\t\tthrow runtime_error(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tthis->row_to_cols[row_index].push_back(col_index);\n\tthis->col_to_rows[col_index].push_back(row_index);\n\n\tthis->rows_max_degree = std::max(get_rows_max_degree(), row_to_cols[row_index].size());\n\tthis->cols_max_degree = std::max(get_cols_max_degree(), col_to_rows[col_index].size());\n\n\tthis->n_connections++;\n}\n\nvoid Sparse_matrix\n::rm_connection(const size_t row_index, const size_t col_index)\n{\n\tcheck_indexes(row_index, col_index);\n\n\t\/\/ delete the link in the row_to_cols vector\n\tbool row_found = false;\n\tauto itr = std::find(this->row_to_cols[row_index].begin(), this->row_to_cols[row_index].end(), col_index);\n\tif (itr != this->row_to_cols[row_index].end())\n\t{\n\t\trow_found = true;\n\t\titr = this->row_to_cols[row_index].erase(itr);\n\n\t\t\/\/ check if need to reduce the rows max degree\n\t\tif (this->row_to_cols[row_index].size() == (this->rows_max_degree-1))\n\t\t{\n\t\t\tbool found = false;\n\t\t\tfor (auto i = this->row_to_cols.begin(); i != this->row_to_cols.end(); i++ )\n\t\t\t\tif (i->size() == this->rows_max_degree)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tif (!found)\n\t\t\t\tthis->rows_max_degree--;\n\t\t}\n\t}\n\n\t\/\/ delete the link in the col_to_rows vector\n\tbool col_found = false;\n\tauto itc = std::find(this->col_to_rows[col_index].begin(), this->col_to_rows[col_index].end(), row_index);\n\tif (itc != this->col_to_rows[col_index].end())\n\t{\n\t\tcol_found = true;\n\t\tthis->col_to_rows[col_index].erase(itc);\n\n\t\t\/\/ check if need to reduce the cols max degree\n\t\tif (this->col_to_rows[col_index].size() == (this->cols_max_degree-1))\n\t\t{\n\t\t\tbool found = false;\n\t\t\tfor (auto i = this->col_to_rows.begin(); i != this->col_to_rows.end(); i++ )\n\t\t\t\tif (i->size() == this->cols_max_degree)\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tif (!found)\n\t\t\t\tthis->cols_max_degree--;\n\t\t}\n\t}\n\n\tif (row_found != col_found)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"The connection has been found only in one of the two vectors 'row_to_cols' and 'col_to_rows' \"\n\t\t << \"('row_index' = \" << row_index << \", 'col_index' = \" << col_index\n\t\t << \", found in row = \" << std::boolalpha << row_found\n\t\t << \", found in col = \" << col_found << std::noboolalpha << \").\";\n\t\tthrow tools::runtime_error(__FILE__, __LINE__, __func__, message.str());\n\t}\n\telse if (row_found && col_found)\n\t\tthis->n_connections--;\n\t\/\/ else the connection has not been found\n}\n\nvoid Sparse_matrix\n::parse_connections()\n{\n\tthis->n_connections = std::accumulate(row_to_cols.begin(), row_to_cols.end(), (size_t)0,\n\t [](size_t init, const std::vector<size_t>& a){ return init + a.size();});\n\n\tthis->rows_max_degree = std::max_element(row_to_cols.begin(), row_to_cols.end(),\n\t [](const std::vector<size_t>& a, const std::vector<size_t>& b){ return a.size() < b.size();})\n\t ->size();\n\tthis->cols_max_degree = std::max_element(col_to_rows.begin(), col_to_rows.end(),\n\t [](const std::vector<size_t>& a, const std::vector<size_t>& b){ return a.size() < b.size();})\n\t ->size();\n}\n\nvoid Sparse_matrix\n::self_resize(const size_t n_rows, const size_t n_cols, Origin o)\n{\n\t*this = this->resize(n_rows, n_rows, o);\n}\n\nSparse_matrix Sparse_matrix\n::resize(const size_t n_rows, const size_t n_cols, Origin o) const\n{\n\tSparse_matrix resized(n_rows, n_cols);\n\n\t\/\/ const auto min_r = std::min(n_rows, get_n_rows());\n\tconst auto min_c = std::min(n_cols, get_n_cols());\n\t\/\/ const auto diff_r = get_n_rows() - min_r;\n\tconst auto diff_c = get_n_cols() - min_c;\n\tconst auto diff_n_rows = (int)n_rows - (int)get_n_rows();\n\tconst auto diff_n_cols = (int)n_cols - (int)get_n_cols();\n\n\tswitch(o)\n\t{\n\t\tcase Origin::TOP_LEFT:\n\t\t{\n\t\t\tfor (size_t c = 0; c < min_c; c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = c;\n\t\t\t\t\tconst auto row_index = col_to_rows[c][r];\n\t\t\t\t\tif (row_index < n_rows)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::TOP_RIGHT:\n\t\t{\n\t\t\tfor (size_t c = diff_c; c < get_n_cols(); c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = diff_n_cols + c;\n\t\t\t\t\tconst auto row_index = col_to_rows[c][r];\n\t\t\t\t\tif (row_index < n_rows)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::BOTTOM_LEFT:\n\t\t{\n\t\t\tfor (size_t c = 0; c < min_c; c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = c;\n\t\t\t\t\tconst auto row_index = diff_n_rows + (int)col_to_rows[c][r];\n\t\t\t\t\tif (row_index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase Origin::BOTTOM_RIGHT:\n\t\t{\n\t\t\tfor (size_t c = diff_c; c < get_n_cols(); c++)\n\t\t\t\tfor (size_t r = 0; r < col_to_rows[c].size(); r++)\n\t\t\t\t{\n\t\t\t\t\tconst auto col_index = diff_n_cols + c;\n\t\t\t\t\tconst auto row_index = diff_n_rows + (int)col_to_rows[c][r];\n\t\t\t\t\tif (row_index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresized.row_to_cols[row_index].push_back(col_index);\n\t\t\t\t\t\tresized.col_to_rows[col_index].push_back(row_index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tresized.parse_connections();\n\n\treturn resized;\n}\n\nSparse_matrix Sparse_matrix\n::transpose() const\n{\n\tSparse_matrix trans(*this);\n\n\ttrans.self_transpose();\n\n\treturn trans;\n}\n\nvoid Sparse_matrix\n::self_transpose()\n{\n\tMatrix::self_transpose();\n\n\tstd::swap(row_to_cols, col_to_rows);\n}\n\nSparse_matrix Sparse_matrix\n::turn(Way w) const\n{\n\tSparse_matrix turned(*this);\n\n\tturned.self_turn(w);\n\n\treturn turned;\n}\n\nvoid Sparse_matrix\n::sort_cols_per_density(Sort order)\n{\n\tswitch(order)\n\t{\n\t\tcase Sort::ASCENDING:\n\t\t\tstd::sort(this->col_to_rows.begin(), this->col_to_rows.end(),\n\t\t\t [](const std::vector<size_t> &i1, const std::vector<size_t> &i2) { return i1.size() < i2.size(); });\n\t\tbreak;\n\t\tcase Sort::DESCENDING:\n\t\t\tstd::sort(this->col_to_rows.begin(), this->col_to_rows.end(),\n\t\t [](const std::vector<size_t> &i1, const std::vector<size_t> &i2) { return i1.size() > i2.size(); });\n\t\tbreak;\n\t}\n\n\tfor (auto &r : this->row_to_cols)\n\t\tr.clear();\n\tfor (size_t i = 0; i < this->col_to_rows.size(); i++)\n\t\tfor (size_t j = 0; j < this->col_to_rows[i].size(); j++)\n\t\t\tthis->row_to_cols[this->col_to_rows[i][j]].push_back(i);\n}\n\nvoid Sparse_matrix\n::print(bool transpose, std::ostream& os) const\n{\n\tif (transpose)\n\t{\n\t\tstd::vector<unsigned> rows(get_n_rows(), 0);\n\n\t\tfor (auto& col : this->col_to_rows)\n\t\t{\n\t\t\t\/\/ set the ones\n\t\t\tfor (auto& row : col)\n\t\t\t\trows[row] = 1;\n\n\t\t\tfor (auto& row : rows)\n\t\t\t\tos << row << \" \";\n\n\t\t\tos << std::endl;\n\n\t\t\t\/\/ reset the ones\n\t\t\tfor (auto& row : col)\n\t\t\t\trows[row] = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::vector<unsigned> columns(get_n_cols(), 0);\n\n\t\tfor (auto& row : this->row_to_cols)\n\t\t{\n\t\t\t\/\/ set the ones\n\t\t\tfor (auto& col : row)\n\t\t\t\tcolumns[col] = 1;\n\n\t\t\tfor (auto& col : columns)\n\t\t\t\tos << col << \" \";\n\n\t\t\tos << std::endl;\n\n\t\t\t\/\/ reset the ones\n\t\t\tfor (auto& col : row)\n\t\t\t\tcolumns[col] = 0;\n\t\t}\n\t}\n}\n\nSparse_matrix Sparse_matrix\n::identity(const size_t n_rows, const size_t n_cols)\n{\n\tSparse_matrix mat(n_rows, n_cols);\n\tauto shortest_side = std::min(n_rows, n_cols);\n\n\tfor (size_t i = 0; i < shortest_side; i++)\n\t\tmat.add_connection(i,i);\n\n\treturn mat;\n}\n\nSparse_matrix Sparse_matrix\n::zero(const size_t n_rows, const size_t n_cols)\n{\n\treturn Sparse_matrix(n_rows, n_cols);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Program.cpp (Oclgrind)\n\/\/ Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith,\n\/\/ University of Bristol. All rights reserved.\n\/\/\n\/\/ This program is provided under a three-clause BSD license. For full\n\/\/ license terms please see the LICENSE file distributed with this\n\/\/ source code.\n\n#include \"common.h\"\n#include <fstream>\n\n#include \"llvm\/Assembly\/AssemblyAnnotationWriter.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include <clang\/CodeGen\/CodeGenAction.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n\n#include \"Kernel.h\"\n#include \"Program.h\"\n#include \"WorkItem.h\"\n\n#define ENV_DUMP \"OCLGRIND_DUMP_TEMPS\"\n#define CL_DUMP_NAME \"\/tmp\/oclgrind_%lX.cl\"\n#define IR_DUMP_NAME \"\/tmp\/oclgrind_%lX.s\"\n#define BC_DUMP_NAME \"\/tmp\/oclgrind_%lX.bc\"\n\n#if defined(_WIN32)\n#define REMAP_DIR \"Z:\/remapped\/\"\n#else\n#define REMAP_DIR \"\/remapped\/\"\n#endif\n\n#define REMAP_INPUT \"input.cl\"\n#define CLC_H_PATH REMAP_DIR\"clc.h\"\nextern const char CLC_H_DATA[];\n\nusing namespace spirsim;\nusing namespace std;\n\nProgram::Program(llvm::Module *module)\n : m_module(module)\n{\n m_action = NULL;\n m_buildLog = \"\";\n m_buildOptions = \"\";\n m_buildStatus = CL_BUILD_SUCCESS;\n m_uid = generateUID();\n}\n\nProgram::Program(const string& source)\n{\n m_source = source;\n m_module = NULL;\n m_action = NULL;\n m_buildLog = \"\";\n m_buildOptions = \"\";\n m_buildStatus = CL_BUILD_NONE;\n m_uid = 0;\n}\n\nProgram::~Program()\n{\n WorkItem::InterpreterCache::clear(m_uid);\n\n if (m_module)\n {\n delete m_module;\n }\n\n if (m_action)\n {\n delete m_action;\n }\n}\n\nbool Program::build(const char *options, list<Header> headers)\n{\n m_buildStatus = CL_BUILD_IN_PROGRESS;\n m_buildOptions = options ? options : \"\";\n\n \/\/ Create build log\n m_buildLog = \"\";\n llvm::raw_string_ostream buildLog(m_buildLog);\n\n \/\/ Do nothing if program was created with binary\n if (m_source.empty() && m_module)\n {\n m_buildStatus = CL_BUILD_SUCCESS;\n return true;\n }\n\n if (m_module)\n {\n delete m_module;\n m_module = NULL;\n\n WorkItem::InterpreterCache::clear(m_uid);\n }\n\n \/\/ Assign a new UID to this program\n m_uid = generateUID();\n\n \/\/ Set compiler arguments\n vector<const char*> args;\n args.push_back(\"-D cl_khr_fp64\");\n args.push_back(\"-cl-kernel-arg-info\");\n args.push_back(\"-triple\");\n args.push_back(\"spir64-unknown-unknown\");\n args.push_back(\"-g\");\n\n \/\/ Disable optimizations by default due to bugs in Khronos SPIR generator\n bool optimize = false;\n args.push_back(\"-O0\");\n\n \/\/ Add OpenCL build options\n if (options)\n {\n char *_options = strdup(options);\n char *opt = strtok(_options, \" \");\n while (opt)\n {\n \/\/ Ignore options that break PCH\n if (strcmp(opt, \"-cl-fast-relaxed-math\") != 0 &&\n strcmp(opt, \"-cl-single-precision-constant\") != 0)\n {\n args.push_back(opt);\n\n \/\/ Check for optimization flags\n if (strncmp(opt, \"-O\", 2) == 0)\n {\n if (strcmp(opt, \"-O0\") == 0)\n {\n optimize = false;\n }\n else\n {\n optimize = true;\n }\n }\n }\n opt = strtok(NULL, \" \");\n }\n }\n\n \/\/ Select precompiled header\n const char *pch = NULL;\n if (optimize)\n {\n pch = INSTALL_ROOT\"\/include\/spirsim\/clc.pch\";\n }\n else\n {\n pch = INSTALL_ROOT\"\/include\/spirsim\/clc.noopt.pch\";\n }\n\n \/\/ Use precompiled header if it exists, otherwise fall back to embedded clc.h\n ifstream pchfile(pch);\n if (pchfile.good())\n {\n args.push_back(\"-include-pch\");\n args.push_back(pch);\n }\n else\n {\n args.push_back(\"-include\");\n args.push_back(CLC_H_PATH);\n buildLog << \"WARNING: Unable to find precompiled header.\\n\";\n }\n pchfile.close();\n\n \/\/ Append input file to arguments (remapped later)\n args.push_back(REMAP_INPUT);\n\n \/\/ Create diagnostics engine\n clang::DiagnosticOptions *diagOpts = new clang::DiagnosticOptions();\n llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(\n new clang::DiagnosticIDs());\n clang::TextDiagnosticPrinter diagConsumer(buildLog, diagOpts);\n clang::DiagnosticsEngine diags(diagID, diagOpts, &diagConsumer, false);\n\n \/\/ Create compiler invocation\n llvm::OwningPtr<clang::CompilerInvocation> invocation(\n new clang::CompilerInvocation);\n clang::CompilerInvocation::CreateFromArgs(*invocation,\n &args[0], &args[0] + args.size(),\n diags);\n\n \/\/ Create compiler instance\n clang::CompilerInstance compiler;\n compiler.setInvocation(invocation.take());\n\n \/\/ Remap include files\n llvm::MemoryBuffer *buffer;\n compiler.getHeaderSearchOpts().AddPath(REMAP_DIR, clang::frontend::Quoted,\n false, false, false);\n list<Header>::iterator itr;\n for (itr = headers.begin(); itr != headers.end(); itr++)\n {\n buffer = llvm::MemoryBuffer::getMemBuffer(itr->second->m_source, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(REMAP_DIR + itr->first,\n buffer);\n }\n\n \/\/ Remap clc.h\n buffer = llvm::MemoryBuffer::getMemBuffer(CLC_H_DATA, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(CLC_H_PATH, buffer);\n\n \/\/ Remap input file\n buffer = llvm::MemoryBuffer::getMemBuffer(m_source, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(REMAP_INPUT, buffer);\n\n \/\/ Prepare diagnostics\n compiler.createDiagnostics(args.size(), &args[0], &diagConsumer, false);\n if (!compiler.hasDiagnostics())\n {\n m_buildStatus = CL_BUILD_ERROR;\n return false;\n }\n\n \/\/ Compile\n llvm::LLVMContext& context = llvm::getGlobalContext();\n clang::CodeGenAction *action = new clang::EmitLLVMOnlyAction(&context);\n\n if (compiler.ExecuteAction(*action))\n {\n \/\/ Retrieve module\n m_action = new llvm::OwningPtr<clang::CodeGenAction>(action);\n m_module = action->takeModule();\n m_buildStatus = CL_BUILD_SUCCESS;\n }\n else\n {\n m_buildStatus = CL_BUILD_ERROR;\n }\n\n \/\/ Dump temps if required\n const char *keepTempsEnv = getenv(ENV_DUMP);\n if (keepTempsEnv && strcmp(keepTempsEnv, \"1\") == 0)\n {\n \/\/ Construct unique filenames\n char *tempCL = new char[strlen(CL_DUMP_NAME) + 17];\n char *tempIR = new char[strlen(IR_DUMP_NAME) + 17];\n char *tempBC = new char[strlen(BC_DUMP_NAME) + 17];\n sprintf(tempCL, CL_DUMP_NAME, m_uid);\n sprintf(tempIR, IR_DUMP_NAME, m_uid);\n sprintf(tempBC, BC_DUMP_NAME, m_uid);\n\n \/\/ Dump source\n ofstream cl;\n cl.open(tempCL);\n cl << m_source;\n cl.close();\n\n if (m_buildStatus == CL_BUILD_SUCCESS)\n {\n \/\/ Dump IR\n string err;\n llvm::raw_fd_ostream ir(tempIR, err);\n llvm::AssemblyAnnotationWriter asmWriter;\n m_module->print(ir, &asmWriter);\n ir.close();\n\n \/\/ Dump bitcode\n llvm::raw_fd_ostream bc(tempBC, err);\n llvm::WriteBitcodeToFile(m_module, bc);\n bc.close();\n }\n\n delete[] tempCL;\n delete[] tempIR;\n delete[] tempBC;\n }\n\n return m_buildStatus == CL_BUILD_SUCCESS;\n}\n\nProgram* Program::createFromBitcode(const unsigned char *bitcode,\n size_t length)\n{\n \/\/ Load bitcode from file\n llvm::MemoryBuffer *buffer;\n llvm::StringRef data((const char*)bitcode, length);\n buffer = llvm::MemoryBuffer::getMemBuffer(data, \"\", false);\n if (!buffer)\n {\n return NULL;\n }\n\n \/\/ Parse bitcode into IR module\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = ParseBitcodeFile(buffer, context);\n if (!module)\n {\n return NULL;\n }\n\n return new Program(module);\n}\n\nProgram* Program::createFromBitcodeFile(const string filename)\n{\n \/\/ Load bitcode from file\n llvm::OwningPtr<llvm::MemoryBuffer> buffer;\n if (llvm::MemoryBuffer::getFile(filename, buffer))\n {\n return NULL;\n }\n\n \/\/ Parse bitcode into IR module\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = ParseBitcodeFile(buffer.get(), context);\n if (!module)\n {\n return NULL;\n }\n\n return new Program(module);\n}\n\nProgram* Program::createFromPrograms(list<const Program*> programs)\n{\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = new llvm::Module(\"oclgrind_linked\", context);\n llvm::Linker linker(\"oclgrind\", module);\n\n \/\/ Link modules\n list<const Program*>::iterator itr;\n for (itr = programs.begin(); itr != programs.end(); itr++)\n {\n if (linker.LinkInModule(CloneModule((*itr)->m_module)))\n {\n return NULL;\n }\n }\n\n return new Program(linker.releaseModule());\n}\n\nKernel* Program::createKernel(const string name)\n{\n \/\/ Iterate over functions in module to find kernel\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n \/\/ Check kernel name\n if (funcItr->getName().str() != name)\n continue;\n\n function = funcItr;\n break;\n }\n if (function == NULL)\n {\n return NULL;\n }\n\n \/\/ Assign identifiers to unnamed temporaries\n llvm::FunctionPass *instNamer = llvm::createInstructionNamerPass();\n instNamer->runOnFunction(*((llvm::Function*)function));\n delete instNamer;\n\n try\n {\n return new Kernel(*this, function, m_module);\n }\n catch (FatalError& err)\n {\n cerr << endl << \"OCLGRIND FATAL ERROR \"\n << \"(\" << err.getFile() << \":\" << err.getLine() << \")\"\n << endl << err.what()\n << endl << \"When creating kernel '\" << name << \"'\"\n << endl;\n return NULL;\n }\n}\n\nunsigned char* Program::getBinary() const\n{\n if (!m_module)\n {\n return NULL;\n }\n\n std::string str;\n llvm::raw_string_ostream stream(str);\n llvm::WriteBitcodeToFile(m_module, stream);\n stream.str();\n unsigned char *bitcode = new unsigned char[str.length()];\n memcpy(bitcode, str.c_str(), str.length());\n return bitcode;\n}\n\nsize_t Program::getBinarySize() const\n{\n if (!m_module)\n {\n return 0;\n }\n\n std::string str;\n llvm::raw_string_ostream stream(str);\n llvm::WriteBitcodeToFile(m_module, stream);\n stream.str();\n return str.length();\n}\n\nconst string& Program::getBuildLog() const\n{\n return m_buildLog;\n}\n\nconst string& Program::getBuildOptions() const\n{\n return m_buildOptions;\n}\n\nunsigned int Program::getBuildStatus() const\n{\n return m_buildStatus;\n}\n\nunsigned long Program::generateUID() const\n{\n srand(now());\n return rand();\n}\n\nlist<string> Program::getKernelNames() const\n{\n list<string> names;\n\n \/\/ Iterate over functions in module to find kernels\n unsigned int num = 0;\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL)\n {\n names.push_back(funcItr->getName().str());\n }\n }\n\n return names;\n}\n\nunsigned int Program::getNumKernels() const\n{\n assert(m_module != NULL);\n\n \/\/ Iterate over functions in module to find kernels\n unsigned int num = 0;\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL)\n {\n num++;\n }\n }\n\n return num;\n}\n\nconst string& Program::getSource() const\n{\n return m_source;\n}\n\nunsigned long Program::getUID() const\n{\n return m_uid;\n}\n<commit_msg>Using %TEMP% for dumping build output on Windows.<commit_after>\/\/ Program.cpp (Oclgrind)\n\/\/ Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith,\n\/\/ University of Bristol. All rights reserved.\n\/\/\n\/\/ This program is provided under a three-clause BSD license. For full\n\/\/ license terms please see the LICENSE file distributed with this\n\/\/ source code.\n\n#include \"common.h\"\n#include <fstream>\n\n#include \"llvm\/Assembly\/AssemblyAnnotationWriter.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include <clang\/CodeGen\/CodeGenAction.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n\n#include \"Kernel.h\"\n#include \"Program.h\"\n#include \"WorkItem.h\"\n\n#define ENV_DUMP \"OCLGRIND_DUMP_TEMPS\"\n#define CL_DUMP_NAME \"\/tmp\/oclgrind_%lX.cl\"\n#define IR_DUMP_NAME \"\/tmp\/oclgrind_%lX.s\"\n#define BC_DUMP_NAME \"\/tmp\/oclgrind_%lX.bc\"\n\n#if defined(_WIN32)\n#define REMAP_DIR \"Z:\/remapped\/\"\n#else\n#define REMAP_DIR \"\/remapped\/\"\n#endif\n\n#define REMAP_INPUT \"input.cl\"\n#define CLC_H_PATH REMAP_DIR\"clc.h\"\nextern const char CLC_H_DATA[];\n\nusing namespace spirsim;\nusing namespace std;\n\nProgram::Program(llvm::Module *module)\n : m_module(module)\n{\n m_action = NULL;\n m_buildLog = \"\";\n m_buildOptions = \"\";\n m_buildStatus = CL_BUILD_SUCCESS;\n m_uid = generateUID();\n}\n\nProgram::Program(const string& source)\n{\n m_source = source;\n m_module = NULL;\n m_action = NULL;\n m_buildLog = \"\";\n m_buildOptions = \"\";\n m_buildStatus = CL_BUILD_NONE;\n m_uid = 0;\n}\n\nProgram::~Program()\n{\n WorkItem::InterpreterCache::clear(m_uid);\n\n if (m_module)\n {\n delete m_module;\n }\n\n if (m_action)\n {\n delete m_action;\n }\n}\n\nbool Program::build(const char *options, list<Header> headers)\n{\n m_buildStatus = CL_BUILD_IN_PROGRESS;\n m_buildOptions = options ? options : \"\";\n\n \/\/ Create build log\n m_buildLog = \"\";\n llvm::raw_string_ostream buildLog(m_buildLog);\n\n \/\/ Do nothing if program was created with binary\n if (m_source.empty() && m_module)\n {\n m_buildStatus = CL_BUILD_SUCCESS;\n return true;\n }\n\n if (m_module)\n {\n delete m_module;\n m_module = NULL;\n\n WorkItem::InterpreterCache::clear(m_uid);\n }\n\n \/\/ Assign a new UID to this program\n m_uid = generateUID();\n\n \/\/ Set compiler arguments\n vector<const char*> args;\n args.push_back(\"-D cl_khr_fp64\");\n args.push_back(\"-cl-kernel-arg-info\");\n args.push_back(\"-triple\");\n args.push_back(\"spir64-unknown-unknown\");\n args.push_back(\"-g\");\n\n \/\/ Disable optimizations by default due to bugs in Khronos SPIR generator\n bool optimize = false;\n args.push_back(\"-O0\");\n\n \/\/ Add OpenCL build options\n if (options)\n {\n char *_options = strdup(options);\n char *opt = strtok(_options, \" \");\n while (opt)\n {\n \/\/ Ignore options that break PCH\n if (strcmp(opt, \"-cl-fast-relaxed-math\") != 0 &&\n strcmp(opt, \"-cl-single-precision-constant\") != 0)\n {\n args.push_back(opt);\n\n \/\/ Check for optimization flags\n if (strncmp(opt, \"-O\", 2) == 0)\n {\n if (strcmp(opt, \"-O0\") == 0)\n {\n optimize = false;\n }\n else\n {\n optimize = true;\n }\n }\n }\n opt = strtok(NULL, \" \");\n }\n }\n\n \/\/ Select precompiled header\n const char *pch = NULL;\n if (optimize)\n {\n pch = INSTALL_ROOT\"\/include\/spirsim\/clc.pch\";\n }\n else\n {\n pch = INSTALL_ROOT\"\/include\/spirsim\/clc.noopt.pch\";\n }\n\n \/\/ Use precompiled header if it exists, otherwise fall back to embedded clc.h\n ifstream pchfile(pch);\n if (pchfile.good())\n {\n args.push_back(\"-include-pch\");\n args.push_back(pch);\n }\n else\n {\n args.push_back(\"-include\");\n args.push_back(CLC_H_PATH);\n buildLog << \"WARNING: Unable to find precompiled header.\\n\";\n }\n pchfile.close();\n\n \/\/ Append input file to arguments (remapped later)\n args.push_back(REMAP_INPUT);\n\n \/\/ Create diagnostics engine\n clang::DiagnosticOptions *diagOpts = new clang::DiagnosticOptions();\n llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(\n new clang::DiagnosticIDs());\n clang::TextDiagnosticPrinter diagConsumer(buildLog, diagOpts);\n clang::DiagnosticsEngine diags(diagID, diagOpts, &diagConsumer, false);\n\n \/\/ Create compiler invocation\n llvm::OwningPtr<clang::CompilerInvocation> invocation(\n new clang::CompilerInvocation);\n clang::CompilerInvocation::CreateFromArgs(*invocation,\n &args[0], &args[0] + args.size(),\n diags);\n\n \/\/ Create compiler instance\n clang::CompilerInstance compiler;\n compiler.setInvocation(invocation.take());\n\n \/\/ Remap include files\n llvm::MemoryBuffer *buffer;\n compiler.getHeaderSearchOpts().AddPath(REMAP_DIR, clang::frontend::Quoted,\n false, false, false);\n list<Header>::iterator itr;\n for (itr = headers.begin(); itr != headers.end(); itr++)\n {\n buffer = llvm::MemoryBuffer::getMemBuffer(itr->second->m_source, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(REMAP_DIR + itr->first,\n buffer);\n }\n\n \/\/ Remap clc.h\n buffer = llvm::MemoryBuffer::getMemBuffer(CLC_H_DATA, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(CLC_H_PATH, buffer);\n\n \/\/ Remap input file\n buffer = llvm::MemoryBuffer::getMemBuffer(m_source, \"\", false);\n compiler.getPreprocessorOpts().addRemappedFile(REMAP_INPUT, buffer);\n\n \/\/ Prepare diagnostics\n compiler.createDiagnostics(args.size(), &args[0], &diagConsumer, false);\n if (!compiler.hasDiagnostics())\n {\n m_buildStatus = CL_BUILD_ERROR;\n return false;\n }\n\n \/\/ Compile\n llvm::LLVMContext& context = llvm::getGlobalContext();\n clang::CodeGenAction *action = new clang::EmitLLVMOnlyAction(&context);\n\n if (compiler.ExecuteAction(*action))\n {\n \/\/ Retrieve module\n m_action = new llvm::OwningPtr<clang::CodeGenAction>(action);\n m_module = action->takeModule();\n m_buildStatus = CL_BUILD_SUCCESS;\n }\n else\n {\n m_buildStatus = CL_BUILD_ERROR;\n }\n\n \/\/ Dump temps if required\n const char *keepTempsEnv = getenv(ENV_DUMP);\n if (keepTempsEnv && strcmp(keepTempsEnv, \"1\") == 0)\n {\n \/\/ Temporary directory\n#if defined(_WIN32)\n const char *tmpdir = getenv(\"TEMP\");\n#else\n const char *tmpdir = \"\/tmp\";\n#endif\n\n \/\/ Construct unique output filenames\n size_t sz = snprintf(NULL, 0, \"%s\/oclgrind_%lX.XX\", tmpdir, m_uid) + 1;\n char *tempCL = new char[sz];\n char *tempIR = new char[sz];\n char *tempBC = new char[sz];\n sprintf(tempCL, \"%s\/oclgrind_%lX.cl\", tmpdir, m_uid);\n sprintf(tempIR, \"%s\/oclgrind_%lX.ll\", tmpdir, m_uid);\n sprintf(tempBC, \"%s\/oclgrind_%lX.bc\", tmpdir, m_uid);\n\n \/\/ Dump source\n ofstream cl;\n cl.open(tempCL);\n cl << m_source;\n cl.close();\n\n if (m_buildStatus == CL_BUILD_SUCCESS)\n {\n \/\/ Dump IR\n string err;\n llvm::raw_fd_ostream ir(tempIR, err);\n llvm::AssemblyAnnotationWriter asmWriter;\n m_module->print(ir, &asmWriter);\n ir.close();\n\n \/\/ Dump bitcode\n llvm::raw_fd_ostream bc(tempBC, err);\n llvm::WriteBitcodeToFile(m_module, bc);\n bc.close();\n }\n\n delete[] tempCL;\n delete[] tempIR;\n delete[] tempBC;\n }\n\n return m_buildStatus == CL_BUILD_SUCCESS;\n}\n\nProgram* Program::createFromBitcode(const unsigned char *bitcode,\n size_t length)\n{\n \/\/ Load bitcode from file\n llvm::MemoryBuffer *buffer;\n llvm::StringRef data((const char*)bitcode, length);\n buffer = llvm::MemoryBuffer::getMemBuffer(data, \"\", false);\n if (!buffer)\n {\n return NULL;\n }\n\n \/\/ Parse bitcode into IR module\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = ParseBitcodeFile(buffer, context);\n if (!module)\n {\n return NULL;\n }\n\n return new Program(module);\n}\n\nProgram* Program::createFromBitcodeFile(const string filename)\n{\n \/\/ Load bitcode from file\n llvm::OwningPtr<llvm::MemoryBuffer> buffer;\n if (llvm::MemoryBuffer::getFile(filename, buffer))\n {\n return NULL;\n }\n\n \/\/ Parse bitcode into IR module\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = ParseBitcodeFile(buffer.get(), context);\n if (!module)\n {\n return NULL;\n }\n\n return new Program(module);\n}\n\nProgram* Program::createFromPrograms(list<const Program*> programs)\n{\n llvm::LLVMContext& context = llvm::getGlobalContext();\n llvm::Module *module = new llvm::Module(\"oclgrind_linked\", context);\n llvm::Linker linker(\"oclgrind\", module);\n\n \/\/ Link modules\n list<const Program*>::iterator itr;\n for (itr = programs.begin(); itr != programs.end(); itr++)\n {\n if (linker.LinkInModule(CloneModule((*itr)->m_module)))\n {\n return NULL;\n }\n }\n\n return new Program(linker.releaseModule());\n}\n\nKernel* Program::createKernel(const string name)\n{\n \/\/ Iterate over functions in module to find kernel\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n \/\/ Check kernel name\n if (funcItr->getName().str() != name)\n continue;\n\n function = funcItr;\n break;\n }\n if (function == NULL)\n {\n return NULL;\n }\n\n \/\/ Assign identifiers to unnamed temporaries\n llvm::FunctionPass *instNamer = llvm::createInstructionNamerPass();\n instNamer->runOnFunction(*((llvm::Function*)function));\n delete instNamer;\n\n try\n {\n return new Kernel(*this, function, m_module);\n }\n catch (FatalError& err)\n {\n cerr << endl << \"OCLGRIND FATAL ERROR \"\n << \"(\" << err.getFile() << \":\" << err.getLine() << \")\"\n << endl << err.what()\n << endl << \"When creating kernel '\" << name << \"'\"\n << endl;\n return NULL;\n }\n}\n\nunsigned char* Program::getBinary() const\n{\n if (!m_module)\n {\n return NULL;\n }\n\n std::string str;\n llvm::raw_string_ostream stream(str);\n llvm::WriteBitcodeToFile(m_module, stream);\n stream.str();\n unsigned char *bitcode = new unsigned char[str.length()];\n memcpy(bitcode, str.c_str(), str.length());\n return bitcode;\n}\n\nsize_t Program::getBinarySize() const\n{\n if (!m_module)\n {\n return 0;\n }\n\n std::string str;\n llvm::raw_string_ostream stream(str);\n llvm::WriteBitcodeToFile(m_module, stream);\n stream.str();\n return str.length();\n}\n\nconst string& Program::getBuildLog() const\n{\n return m_buildLog;\n}\n\nconst string& Program::getBuildOptions() const\n{\n return m_buildOptions;\n}\n\nunsigned int Program::getBuildStatus() const\n{\n return m_buildStatus;\n}\n\nunsigned long Program::generateUID() const\n{\n srand(now());\n return rand();\n}\n\nlist<string> Program::getKernelNames() const\n{\n list<string> names;\n\n \/\/ Iterate over functions in module to find kernels\n unsigned int num = 0;\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL)\n {\n names.push_back(funcItr->getName().str());\n }\n }\n\n return names;\n}\n\nunsigned int Program::getNumKernels() const\n{\n assert(m_module != NULL);\n\n \/\/ Iterate over functions in module to find kernels\n unsigned int num = 0;\n llvm::Function *function = NULL;\n llvm::Module::iterator funcItr;\n for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++)\n {\n if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL)\n {\n num++;\n }\n }\n\n return num;\n}\n\nconst string& Program::getSource() const\n{\n return m_source;\n}\n\nunsigned long Program::getUID() const\n{\n return m_uid;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: \tql.cpp\n\/\/ Author: \t\tChristopher Goes\n\/\/ Course: \t\tCS 404 Machine Learning and Data Mining\n\/\/ Semester: \tSpring 2016\n\/\/ Description:\tAssignment 6: Q-learning Mountain Car\n\/\/ Github:\t\thttps:\/\/github.com\/GhostofGoes\/cgoes-cs404\n\n#include <iostream>\n#include <cmath>\n#include \"mat.h\"\n\nusing namespace std;\n\n#define DEBUG 0\n\n\/\/ Reward: +1 at goal, -1 not at goal\n\/\/ action(t) = 1 forward, action(t) = 0 coast, action(t) = -1 reverse\n\/\/ bound enforces −1.2 ≤ xt+1 ≤ 0.8 and −0.07 ≤ vt+1 ≤ 0.07\n\ndouble v( double currVel, double action, double currPos ); \t\/\/ vt+1 = bound(vt + 0.001at − 0.0025 cos(3xt))\ndouble x( double currPos, double newVel ); \t\t\t\t\t\/\/ xt+1 = bound(xt + vt+1)\ndouble clampX( double x );\ndouble clampY( double y );\n\nint main() {\n\t\n\tint goal = 0.8;\t\t\/\/ Where we wan to be at the end of the insanity\n\tint numRows = 15; \t\/\/ velocity: \tsteps of 0.01\n\tint numCols = 41; \t\/\/ position: \tsteps of 0.05\n\tMatrix a[3];\t\t\/\/ actions:\t\tforward = 1, coast = 0, reverse = -1\n\t\n\tdouble vel = 0.0;\t\/\/ velocity: \tsteps of 0.01\n\tdouble pos = 0.0;\t\/\/ position: \tsteps of 0.05\n\t\n\t\/\/ The third dimension: actions. Thanks matt. \n\ta[0] = new Matrix(numRows, numCols, \"reverse\");\n\ta[1] = new Matrix(numRows, numCols, \"coast\");\t\n\ta[2] = new Matrix(numRows, numCols, \"forward\");\n\t\n\tfor( Matrix &mat : a ) \/\/ Initialize Q-matricies to -1, 0, or 1\n\t\tmat.randInt(-1, 1);\n\t\n\t\n\n\t\/\/ Output: 3 Q-matricies to \"run a mountain car\"\n\tfor( Matrix &mat : a )\n\t\tmat.write();\n\t\n\treturn(0);\n}\n\n\/\/ vt+1 = bound(vt + 0.001at − 0.0025 cos(3xt))\ndouble v( double currVel, double action, double currPos )\n{\n\tdouble newVel = currVel;\n\tnewVel += 0.001 * action;\n\tnewVel -= 0.0025 * cos(3.0 * currPos);\n\treturn clampY(newVel);\n}\n\n\/\/ xt+1 = bound(xt + vt+1)\ndouble x( double currPos, double newVel )\n{\n\treturn clampX(currPos + newVel);\n}\n\n\/\/ −1.2 ≤ xt+1 ≤ 0.8\ndouble clampX( double x )\n{\n\treturn x > 0.8 ? 0.8 : x < -1.2 ? -1.2 : x;\n}\n\n\/\/ −0.07 ≤ vt+1 ≤ 0.07\ndouble clampY( double y )\n{\n\treturn y > 0.07 ? 0.07 : y < -0.07 ? -0.07 : y;\n}<commit_msg>now there is Q and R lol<commit_after>\/\/ Filename: \tql.cpp\n\/\/ Author: \t\tChristopher Goes\n\/\/ Course: \t\tCS 404 Machine Learning and Data Mining\n\/\/ Semester: \tSpring 2016\n\/\/ Description:\tAssignment 6: Q-learning Mountain Car\n\/\/ Github:\t\thttps:\/\/github.com\/GhostofGoes\/cgoes-cs404\n\n#include <iostream>\n#include <cmath>\n#include \"mat.h\"\n\nusing namespace std;\n\n#define DEBUG 0\n\n\/\/ Reward: +1 at goal, -1 not at goal\n\/\/ action(t) = 1 forward, action(t) = 0 coast, action(t) = -1 reverse\n\/\/ bound enforces −1.2 ≤ xt+1 ≤ 0.8 and −0.07 ≤ vt+1 ≤ 0.07\n\nint next( double pos, double vel, double action );\ndouble v( double currVel, double action, double currPos ); \t\/\/ vt+1 = bound(vt + 0.001at − 0.0025 cos(3xt))\ndouble x( double currPos, double newVel ); \t\t\t\t\t\/\/ xt+1 = bound(xt + vt+1)\ndouble clampX( double x );\ndouble clampY( double y );\nMatrix r[3]; \/\/ reward matrix that has our \"environment\" state\nMatrix q[3]; \/\/ path matrix\n\nint main() {\n\t\n\tint numEpisodes = 0;\n\tint goal = 0.8;\t\t\/\/ Where we want to be at the end of this insanity\n\tint numRows = 15; \t\/\/ velocity: \tsteps of 0.01\n\tint numCols = 41; \t\/\/ position: \tsteps of 0.05\n\t\n\tdouble currVel = 0.0, currPos = 0.0; \t\/\/ current state\n\tdouble newVel = 0.0, newPos = 0.0;\t\t\/\/ new state\n\tdouble action = 0; \t\/\/ actions:\tforward = 1, coast = 0, reverse = -1\n\t\n\tr[0] = new Matrix(numRows, numCols, \"reverse\");\n\tr[1] = new Matrix(numRows, numCols, \"coast\");\t\n\tr[2] = new Matrix(numRows, numCols, \"forward\");\n\tfor( Matrix &mat : r ) \/\/ Initialize state to -1, 0, or 1\n\t\tmat.randInt(-1, 1);\n\t\n\tq[0] = new Matrix(numRows, numCols, \"reverse\");\n\tq[1] = new Matrix(numRows, numCols, \"coast\");\t\n\tq[2] = new Matrix(numRows, numCols, \"forward\");\t\n\tfor( Matrix &mat : q )\n\t\tmat.constant(0.0); \/\/ zero out path matrix\n\t\n\t\n\t\n\t\n\n\t\/\/ Output: 3 Q-matricies to \"run a mountain car\"\n\tfor( Matrix &mat : q )\n\t\tmat.write();\n\t\n\treturn(0);\n}\n\nint next( double pos, double vel, int action )\n{\n\t\n}\n\n\n\/\/ vt+1 = bound(vt + 0.001at − 0.0025 cos(3xt))\ndouble v( double currVel, double action, double currPos )\n{\n\tdouble newVel = currVel;\n\tnewVel += 0.001 * action;\n\tnewVel -= 0.0025 * cos(3.0 * currPos);\n\treturn clampY(newVel);\n}\n\n\/\/ xt+1 = bound(xt + vt+1)\ndouble x( double currPos, double newVel )\n{\n\treturn clampX(currPos + newVel);\n}\n\n\/\/ −1.2 ≤ xt+1 ≤ 0.8\ndouble clampX( double x )\n{\n\treturn x > 0.8 ? 0.8 : x < -1.2 ? -1.2 : x;\n}\n\n\/\/ −0.07 ≤ vt+1 ≤ 0.07\ndouble clampY( double y )\n{\n\treturn y > 0.07 ? 0.07 : y < -0.07 ? -0.07 : y;\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRegularPolygonSource.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkRegularPolygonSource.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkMath.h\"\n\nvtkCxxRevisionMacro(vtkRegularPolygonSource, \"1.1\");\nvtkStandardNewMacro(vtkRegularPolygonSource);\n\nvtkRegularPolygonSource::vtkRegularPolygonSource()\n{\n this->NumberOfSides = 6;\n this->Center[0] = 0.0; this->Center[1] = 0.0; this->Center[2] = 0.0;\n this->Normal[0] = 0.0; this->Normal[1] = 0.0; this->Normal[2] = 1.0;\n this->Radius = 0.5;\n this->GeneratePolygon = 1;\n this->GeneratePolyline = 1;\n\n this->SetNumberOfInputPorts(0);\n}\n\nint vtkRegularPolygonSource::RequestInformation(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n \/\/ get the info object\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),-1);\n\n return 1;\n}\n\nint vtkRegularPolygonSource::RequestData(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n \/\/ Get the info object\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n \/\/ Get the output\n vtkPolyData *output = vtkPolyData::SafeDownCast(\n outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ We only produce one piece\n if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)\n {\n return 1;\n }\n\n double x[3], r[3];\n int i, j, numPts=this->NumberOfSides;\n vtkPoints *newPoints; \n vtkCellArray *newPoly;\n vtkCellArray *newLine;\n \n \/\/ Prepare to produce the output; create the connectivity array(s)\n newPoints = vtkPoints::New();\n newPoints->Allocate(numPts);\n\n if ( this->GeneratePolyline )\n {\n newLine = vtkCellArray::New();\n newLine->Allocate(newLine->EstimateSize(1,numPts));\n newLine->InsertNextCell(numPts+1);\n for (i=0; i<numPts; i++)\n {\n newLine->InsertCellPoint(i);\n }\n newLine->InsertCellPoint(0); \/\/close the polyline\n output->SetLines(newLine);\n newLine->Delete();\n }\n \n if ( this->GeneratePolygon )\n {\n newPoly = vtkCellArray::New();\n newPoly->Allocate(newPoly->EstimateSize(1,numPts));\n newPoly->InsertNextCell(numPts);\n for (i=0; i<numPts; i++)\n {\n newPoly->InsertCellPoint(i);\n }\n output->SetPolys(newPoly);\n newPoly->Delete();\n }\n \n \/\/ Produce a unit vector in the plane of the polygon (i.e., perpendicular\n \/\/ to the normal)\n double n[3], axis[3], p[3];\n\n \/\/ Make sure the polygon normal is a unit vector\n n[0] = this->Normal[0];\n n[1] = this->Normal[1];\n n[2] = this->Normal[2];\n if ( vtkMath::Normalize(n) == 0.0 )\n {\n n[0] = 0.0;\n n[1] = 0.0;\n n[2] = 1.0;\n }\n\n \/\/ Cross with unit axis vectors and eventually find vector in the polygon plane\n int foundPlaneVector = 0;\n axis[0] = 1.0;\n axis[1] = 0.0;\n axis[2] = 0.0;\n vtkMath::Cross(n,axis,p);\n if ( vtkMath::Normalize(p) > 1.0E-3 )\n {\n foundPlaneVector = 1;\n }\n if ( ! foundPlaneVector )\n {\n axis[0] = 0.0;\n axis[1] = 1.0;\n axis[2] = 0.0;\n vtkMath::Cross(n,axis,p);\n if ( vtkMath::Normalize(p) > 1.0E-3 )\n {\n foundPlaneVector = 1;\n }\n }\n if ( ! foundPlaneVector )\n {\n axis[0] = 0.0;\n axis[1] = 0.0;\n axis[2] = 1.0;\n vtkMath::Cross(n,axis,p);\n vtkMath::Normalize(p);\n }\n\n \/\/ Now run around normal vector to produce polygon points.\n double theta = 2.0 * vtkMath::DoublePi() \/ numPts;\n for (j=0; j<numPts; j++)\n {\n for (i=0; i<3; i++)\n {\n r[i] = p[i]*cos((double)j*theta) + n[i]*sin((double)j*theta);\n x[i] = this->Center[i] + this->Radius * r[i];\n }\n newPoints->InsertNextPoint(x);\n }\n\n output->SetPoints(newPoints);\n newPoints->Delete();\n\n return 1;\n}\n\nvoid vtkRegularPolygonSource::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Number of Sides: \" << this->NumberOfSides << \"\\n\";\n\n os << indent << \"Center: (\" << this->Center[0] << \", \"\n << this->Center[1] << \", \"\n << this->Center[2] << \")\\n\";\n\n os << indent << \"Normal: (\" << this->Normal[0] << \", \"\n << this->Normal[1] << \", \"\n << this->Normal[2] << \")\\n\";\n\n os << indent << \"Radius: \" << this->Radius << \"\\n\";\n\n os << indent << \"Generate Polygon: \" << (this->GeneratePolygon ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Generate Polyline: \" << (this->GeneratePolyline ? \"On\\n\" : \"Off\\n\");\n\n}\n<commit_msg>ENH:Better generation of polygon points<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkRegularPolygonSource.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkRegularPolygonSource.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkMath.h\"\n\nvtkCxxRevisionMacro(vtkRegularPolygonSource, \"1.2\");\nvtkStandardNewMacro(vtkRegularPolygonSource);\n\nvtkRegularPolygonSource::vtkRegularPolygonSource()\n{\n this->NumberOfSides = 6;\n this->Center[0] = 0.0; this->Center[1] = 0.0; this->Center[2] = 0.0;\n this->Normal[0] = 0.0; this->Normal[1] = 0.0; this->Normal[2] = 1.0;\n this->Radius = 0.5;\n this->GeneratePolygon = 1;\n this->GeneratePolyline = 1;\n\n this->SetNumberOfInputPorts(0);\n}\n\nint vtkRegularPolygonSource::RequestInformation(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n \/\/ get the info object\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),-1);\n\n return 1;\n}\n\nint vtkRegularPolygonSource::RequestData(\n vtkInformation *vtkNotUsed(request),\n vtkInformationVector **vtkNotUsed(inputVector),\n vtkInformationVector *outputVector)\n{\n \/\/ Get the info object\n vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n \/\/ Get the output\n vtkPolyData *output = vtkPolyData::SafeDownCast(\n outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ We only produce one piece\n if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)\n {\n return 1;\n }\n\n double x[3], r[3];\n int i, j, numPts=this->NumberOfSides;\n vtkPoints *newPoints; \n vtkCellArray *newPoly;\n vtkCellArray *newLine;\n \n \/\/ Prepare to produce the output; create the connectivity array(s)\n newPoints = vtkPoints::New();\n newPoints->Allocate(numPts);\n\n if ( this->GeneratePolyline )\n {\n newLine = vtkCellArray::New();\n newLine->Allocate(newLine->EstimateSize(1,numPts));\n newLine->InsertNextCell(numPts+1);\n for (i=0; i<numPts; i++)\n {\n newLine->InsertCellPoint(i);\n }\n newLine->InsertCellPoint(0); \/\/close the polyline\n output->SetLines(newLine);\n newLine->Delete();\n }\n \n if ( this->GeneratePolygon )\n {\n newPoly = vtkCellArray::New();\n newPoly->Allocate(newPoly->EstimateSize(1,numPts));\n newPoly->InsertNextCell(numPts);\n for (i=0; i<numPts; i++)\n {\n newPoly->InsertCellPoint(i);\n }\n output->SetPolys(newPoly);\n newPoly->Delete();\n }\n \n \/\/ Produce a unit vector in the plane of the polygon (i.e., perpendicular\n \/\/ to the normal)\n double n[3], axis[3], px[3], py[3];\n\n \/\/ Make sure the polygon normal is a unit vector\n n[0] = this->Normal[0];\n n[1] = this->Normal[1];\n n[2] = this->Normal[2];\n if ( vtkMath::Normalize(n) == 0.0 )\n {\n n[0] = 0.0;\n n[1] = 0.0;\n n[2] = 1.0;\n }\n\n \/\/ Cross with unit axis vectors and eventually find vector in the polygon plane\n int foundPlaneVector = 0;\n axis[0] = 1.0;\n axis[1] = 0.0;\n axis[2] = 0.0;\n vtkMath::Cross(n,axis,px);\n if ( vtkMath::Normalize(px) > 1.0E-3 )\n {\n foundPlaneVector = 1;\n }\n if ( ! foundPlaneVector )\n {\n axis[0] = 0.0;\n axis[1] = 1.0;\n axis[2] = 0.0;\n vtkMath::Cross(n,axis,px);\n if ( vtkMath::Normalize(px) > 1.0E-3 )\n {\n foundPlaneVector = 1;\n }\n }\n if ( ! foundPlaneVector )\n {\n axis[0] = 0.0;\n axis[1] = 0.0;\n axis[2] = 1.0;\n vtkMath::Cross(n,axis,px);\n vtkMath::Normalize(px);\n }\n vtkMath::Cross(px,n,py); \/\/created two orthogonal axes in the polygon plane, px & py\n\n \/\/ Now run around normal vector to produce polygon points.\n double theta = 2.0 * vtkMath::DoublePi() \/ numPts;\n for (j=0; j<numPts; j++)\n {\n for (i=0; i<3; i++)\n {\n r[i] = px[i]*cos((double)j*theta) + py[i]*sin((double)j*theta);\n x[i] = this->Center[i] + this->Radius * r[i];\n }\n newPoints->InsertNextPoint(x);\n }\n\n output->SetPoints(newPoints);\n newPoints->Delete();\n\n return 1;\n}\n\nvoid vtkRegularPolygonSource::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Number of Sides: \" << this->NumberOfSides << \"\\n\";\n\n os << indent << \"Center: (\" << this->Center[0] << \", \"\n << this->Center[1] << \", \"\n << this->Center[2] << \")\\n\";\n\n os << indent << \"Normal: (\" << this->Normal[0] << \", \"\n << this->Normal[1] << \", \"\n << this->Normal[2] << \")\\n\";\n\n os << indent << \"Radius: \" << this->Radius << \"\\n\";\n\n os << indent << \"Generate Polygon: \" << (this->GeneratePolygon ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Generate Polyline: \" << (this->GeneratePolyline ? \"On\\n\" : \"Off\\n\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: asyncTaskBase.cxx\n\/\/ Created by: drose (09Feb10)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"asyncTaskBase.h\"\n#include \"thread.h\"\n#include \"atomicAdjust.h\"\n\nTypeHandle AsyncTaskBase::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::Constructor\n\/\/ Access: Protected\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAsyncTaskBase::\nAsyncTaskBase() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::Destructor\n\/\/ Access: Published, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAsyncTaskBase::\n~AsyncTaskBase() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::record_task\n\/\/ Access: Protected\n\/\/ Description: Indicates that this task is now the current task\n\/\/ running on the indicated thread, presumably the\n\/\/ current thread.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AsyncTaskBase::\nrecord_task(Thread *current_thread) {\n nassertv(current_thread->_current_task == NULL);\n\n void *result = AtomicAdjust::compare_and_exchange_ptr\n ((void * TVOLATILE &)current_thread->_current_task,\n (void *)NULL, (void *)this);\n\n \/\/ If the return value is other than NULL, someone else must have\n \/\/ assigned the task first, in another thread. That shouldn't be\n \/\/ possible.\n nassertv(result == NULL);\n nassertv(current_thread->_current_task == this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::clear_task\n\/\/ Access: Protected\n\/\/ Description: Indicates that this task is no longer running on the\n\/\/ indicated thread.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AsyncTaskBase::\nclear_task(Thread *current_thread) {\n nassertv(current_thread->_current_task == this);\n\n void *result = AtomicAdjust::compare_and_exchange_ptr\n ((void * TVOLATILE &)current_thread->_current_task,\n (void *)this, (void *)NULL);\n\n \/\/ If the return value is other than this, someone else must have\n \/\/ assigned the task first, in another thread. That shouldn't be\n \/\/ possible.\n nassertv(result == this);\n nassertv(current_thread->_current_task == NULL);\n}\n<commit_msg>protect against gcc compiler bugs in general<commit_after>\/\/ Filename: asyncTaskBase.cxx\n\/\/ Created by: drose (09Feb10)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"asyncTaskBase.h\"\n#include \"thread.h\"\n#include \"atomicAdjust.h\"\n\nTypeHandle AsyncTaskBase::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::Constructor\n\/\/ Access: Protected\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAsyncTaskBase::\nAsyncTaskBase() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::Destructor\n\/\/ Access: Published, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAsyncTaskBase::\n~AsyncTaskBase() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::record_task\n\/\/ Access: Protected\n\/\/ Description: Indicates that this task is now the current task\n\/\/ running on the indicated thread, presumably the\n\/\/ current thread.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AsyncTaskBase::\nrecord_task(Thread *current_thread) {\n nassertv(current_thread->_current_task == NULL);\n\n void *result = AtomicAdjust::compare_and_exchange_ptr\n ((void * TVOLATILE &)current_thread->_current_task,\n (void *)NULL, (void *)this);\n\n \/\/ If the return value is other than NULL, someone else must have\n \/\/ assigned the task first, in another thread. That shouldn't be\n \/\/ possible.\n\n \/\/ But different versions of gcc appear to have problems compiling these\n \/\/ assertions correctly.\n#ifndef __GNUC__\n nassertv(result == NULL);\n nassertv(current_thread->_current_task == this);\n#endif \/\/ __GNUC__\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: AsyncTaskBase::clear_task\n\/\/ Access: Protected\n\/\/ Description: Indicates that this task is no longer running on the\n\/\/ indicated thread.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AsyncTaskBase::\nclear_task(Thread *current_thread) {\n nassertv(current_thread->_current_task == this);\n\n void *result = AtomicAdjust::compare_and_exchange_ptr\n ((void * TVOLATILE &)current_thread->_current_task,\n (void *)this, (void *)NULL);\n\n \/\/ If the return value is other than this, someone else must have\n \/\/ assigned the task first, in another thread. That shouldn't be\n \/\/ possible.\n\n \/\/ But different versions of gcc appear to have problems compiling these\n \/\/ assertions correctly.\n#ifndef __GNUC__\n nassertv(result == this);\n nassertv(current_thread->_current_task == NULL);\n#endif \/\/ __GNUC__\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ clang-format off\n{{#global}}\n#include <SoftwareSerial.h>\n{{\/global}}\n\/\/ clang-format on\n\nclass SoftwareUart : public Uart {\nprivate:\n SoftwareSerial _serial;\n uint8_t _rx;\n uint8_t _tx;\n\npublic:\n SoftwareUart(uint8_t rx, uint8_t tx, long baud = 9600)\n : Uart(baud)\n , _serial(rx, tx) {\n _rx = rx;\n _tx = tx;\n }\n\n void begin();\n void end();\n void flush();\n\n bool available() {\n return (bool)_serial.available();\n }\n\n bool writeByte(uint8_t byte) {\n return (bool)_serial.write(byte);\n }\n\n bool readByte(uint8_t* out) {\n int data = _serial.read();\n if (data == -1)\n return false;\n *out = data;\n return true;\n }\n\n uint8_t getRX() {\n return _rx;\n }\n\n uint8_t getTX() {\n return _tx;\n }\n\n SoftwareSerial* toSoftwareSerial() {\n return &_serial;\n }\n};\n\nvoid SoftwareUart::begin() {\n _started = true;\n _serial.begin(getBaudRate());\n};\nvoid SoftwareUart::end() {\n _started = false;\n _serial.end();\n};\nvoid SoftwareUart::flush() {\n _serial.flush();\n}\n\nstruct State {\n uint8_t mem[sizeof(SoftwareUart)];\n SoftwareUart* uart;\n};\n\n\/\/ clang-format off\n{{ GENERATED_CODE }}\n\/\/ clang-format on\n\nvoid evaluate(Context ctx) {\n auto state = getState(ctx);\n\n if (isSettingUp()) {\n uint8_t rx = getValue<input_RX>(ctx);\n uint8_t tx = getValue<input_TX>(ctx);\n long baud = (long)getValue<input_BAUD>(ctx);\n state->uart = new (state->mem) SoftwareUart(rx, tx, baud);\n emitValue<output_UART>(ctx, state->uart);\n }\n\n if (isInputDirty<input_INIT>(ctx)) {\n state->uart->begin();\n emitValue<output_DONE>(ctx, 1);\n }\n}\n<commit_msg>tweak(stdlib): explicitly convert int to uint8_t when reading byte in xod\/uart\/soft-uart<commit_after>\/\/ clang-format off\n{{#global}}\n#include <SoftwareSerial.h>\n{{\/global}}\n\/\/ clang-format on\n\nclass SoftwareUart : public Uart {\nprivate:\n SoftwareSerial _serial;\n uint8_t _rx;\n uint8_t _tx;\n\npublic:\n SoftwareUart(uint8_t rx, uint8_t tx, long baud = 9600)\n : Uart(baud)\n , _serial(rx, tx) {\n _rx = rx;\n _tx = tx;\n }\n\n void begin();\n void end();\n void flush();\n\n bool available() {\n return (bool)_serial.available();\n }\n\n bool writeByte(uint8_t byte) {\n return (bool)_serial.write(byte);\n }\n\n bool readByte(uint8_t* out) {\n int data = _serial.read();\n if (data == -1)\n return false;\n *out = (uint8_t)data;\n return true;\n }\n\n uint8_t getRX() {\n return _rx;\n }\n\n uint8_t getTX() {\n return _tx;\n }\n\n SoftwareSerial* toSoftwareSerial() {\n return &_serial;\n }\n};\n\nvoid SoftwareUart::begin() {\n _started = true;\n _serial.begin(getBaudRate());\n};\nvoid SoftwareUart::end() {\n _started = false;\n _serial.end();\n};\nvoid SoftwareUart::flush() {\n _serial.flush();\n}\n\nstruct State {\n uint8_t mem[sizeof(SoftwareUart)];\n SoftwareUart* uart;\n};\n\n\/\/ clang-format off\n{{ GENERATED_CODE }}\n\/\/ clang-format on\n\nvoid evaluate(Context ctx) {\n auto state = getState(ctx);\n\n if (isSettingUp()) {\n uint8_t rx = getValue<input_RX>(ctx);\n uint8_t tx = getValue<input_TX>(ctx);\n long baud = (long)getValue<input_BAUD>(ctx);\n state->uart = new (state->mem) SoftwareUart(rx, tx, baud);\n emitValue<output_UART>(ctx, state->uart);\n }\n\n if (isInputDirty<input_INIT>(ctx)) {\n state->uart->begin();\n emitValue<output_DONE>(ctx, 1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"openmc\/tallies\/trigger.h\"\n\n#include <cmath>\n#include <sstream>\n#include <utility> \/\/ for std::pair\n\n#include \"openmc\/capi.h\"\n#include \"openmc\/constants.h\"\n#include \"openmc\/error.h\"\n#include \"openmc\/reaction.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/tallies\/tally.h\"\n\nnamespace openmc {\n\n\/\/==============================================================================\n\/\/ Global variable definitions\n\/\/==============================================================================\n\nnamespace settings {\n KTrigger keff_trigger;\n}\n\n\/\/==============================================================================\n\/\/ Non-member functions\n\/\/==============================================================================\n\nstd::pair<double, double>\nget_tally_uncertainty(int i_tally, int score_index, int filter_index)\n{\n const auto& tally {model::tallies[i_tally]};\n\n auto sum = tally->results_(filter_index, score_index, RESULT_SUM);\n auto sum_sq = tally->results_(filter_index, score_index, RESULT_SUM_SQ);\n\n int n = tally->n_realizations_;\n auto mean = sum \/ n;\n double std_dev = std::sqrt((sum_sq\/n - mean*mean) \/ (n-1));\n double rel_err = (mean != 0.) ? std_dev \/ std::abs(mean) : 0.;\n\n return {std_dev, rel_err};\n}\n\n\/\/! Find the limiting limiting tally trigger.\n\/\/\n\/\/! param[out] ratio The uncertainty\/threshold ratio for the most limiting\n\/\/! tally trigger\n\/\/! param[out] tally_id The ID number of the most limiting tally\n\/\/! param[out] score The most limiting tally score bin\n\nvoid\ncheck_tally_triggers(double& ratio, int& tally_id, int& score)\n{\n ratio = 0.;\n for (auto i_tally = 0; i_tally < model::tallies.size(); ++i_tally) {\n const Tally& t {*model::tallies[i_tally]};\n\n \/\/ Ignore tallies with less than two realizations.\n if (t.n_realizations_ < 2) continue;\n\n for (const auto& trigger : t.triggers_) {\n const auto& results = t.results_;\n for (auto filter_index = 0; filter_index < results.shape()[0];\n ++filter_index) {\n for (auto score_index = 0; score_index < results.shape()[1];\n ++score_index) {\n \/\/ Compute the tally uncertainty metrics.\n auto uncert_pair = get_tally_uncertainty(i_tally, score_index,\n filter_index);\n double std_dev = uncert_pair.first;\n double rel_err = uncert_pair.second;\n\n \/\/ Pick out the relevant uncertainty metric for this trigger.\n double uncertainty;\n switch (trigger.metric) {\n case TriggerMetric::variance:\n uncertainty = std_dev * std_dev;\n break;\n case TriggerMetric::standard_deviation:\n uncertainty = std_dev;\n break;\n case TriggerMetric::relative_error:\n uncertainty = rel_err;\n break;\n case TriggerMetric::not_active:\n uncertainty = 0.0;\n break;\n }\n\n \/\/ Compute the uncertainty \/ threshold ratio.\n double this_ratio = uncertainty \/ trigger.threshold;\n if (trigger.metric == TriggerMetric::variance) {\n this_ratio = std::sqrt(ratio);\n }\n\n \/\/ If this is the most uncertain value, set the output variables.\n if (this_ratio > ratio) {\n ratio = this_ratio;\n score = t.scores_[trigger.score_index];\n tally_id = t.id_;\n }\n }\n }\n }\n }\n}\n\n\/\/! Compute the uncertainty\/threshold ratio for the eigenvalue trigger.\n\ndouble\ncheck_keff_trigger()\n{\n if (settings::run_mode != RUN_MODE_EIGENVALUE) return 0.;\n\n double k_combined[2];\n openmc_get_keff(k_combined);\n\n double uncertainty = 0.;\n switch (settings::keff_trigger.metric) {\n case TriggerMetric::variance:\n uncertainty = k_combined[1] * k_combined[1];\n break;\n case TriggerMetric::standard_deviation:\n uncertainty = k_combined[1];\n break;\n case TriggerMetric::relative_error:\n uncertainty = k_combined[1] \/ k_combined[0];\n break;\n case TriggerMetric::not_active:\n break;\n }\n\n double ratio = uncertainty \/ settings::keff_trigger.threshold;\n if (settings::keff_trigger.metric == TriggerMetric::variance)\n ratio = std::sqrt(ratio);\n return ratio;\n}\n\n\/\/! See if tally and eigenvalue uncertainties are under trigger thresholds.\n\nvoid\ncheck_triggers()\n{\n \/\/ Make some aliases.\n const auto current_batch {simulation::current_batch};\n const auto n_batches {settings::n_batches};\n const auto interval {settings::trigger_batch_interval};\n\n \/\/ See if the current batch is one for which the triggers must be checked.\n if (!settings::trigger_on) return;\n if (current_batch < n_batches) return;\n if (((current_batch - n_batches) % interval) != 0) return;\n\n \/\/ Check the eigenvalue and tally triggers.\n double keff_ratio = check_keff_trigger();\n double tally_ratio;\n int tally_id, score;\n check_tally_triggers(tally_ratio, tally_id, score);\n\n \/\/ If all the triggers are satisfied, alert the user and return.\n if (std::max(keff_ratio, tally_ratio) <= 1.) {\n simulation::satisfy_triggers = true;\n write_message(\"Triggers satisfied for batch \"\n + std::to_string(current_batch), 7);\n return;\n }\n\n \/\/ At least one trigger is unsatisfied. Let the user know which one.\n simulation::satisfy_triggers = false;\n std::stringstream msg;\n msg << \"Triggers unsatisfied, max unc.\/thresh. is \";\n if (keff_ratio >= tally_ratio) {\n msg << keff_ratio << \" for eigenvalue\";\n } else {\n msg << tally_ratio << \" for \" << reaction_name(score) << \" in tally \"\n << tally_id;\n }\n write_message(msg, 7);\n\n \/\/ Estimate batches til triggers are satisfied.\n if (settings::trigger_predict) {\n \/\/ This calculation assumes tally variance is proportional to 1\/N where N is\n \/\/ the number of batches.\n auto max_ratio = std::max(keff_ratio, tally_ratio);\n auto n_active = current_batch - settings::n_inactive;\n auto n_pred_batches = static_cast<int>(n_active * max_ratio * max_ratio)\n + settings::n_inactive + 1;\n\n std::stringstream msg;\n msg << \"The estimated number of batches is \" << n_pred_batches;\n if (n_pred_batches > settings::n_max_batches) {\n msg << \" --- greater than max batches\";\n warning(msg);\n } else {\n write_message(msg, 7);\n }\n }\n}\n\n} \/\/ namespace openmc\n<commit_msg>stop division by zero in keff trigger if no trigger given<commit_after>#include \"openmc\/tallies\/trigger.h\"\n\n#include <cmath>\n#include <sstream>\n#include <utility> \/\/ for std::pair\n\n#include \"openmc\/capi.h\"\n#include \"openmc\/constants.h\"\n#include \"openmc\/error.h\"\n#include \"openmc\/reaction.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/tallies\/tally.h\"\n\nnamespace openmc {\n\n\/\/==============================================================================\n\/\/ Global variable definitions\n\/\/==============================================================================\n\nnamespace settings {\n KTrigger keff_trigger;\n}\n\n\/\/==============================================================================\n\/\/ Non-member functions\n\/\/==============================================================================\n\nstd::pair<double, double>\nget_tally_uncertainty(int i_tally, int score_index, int filter_index)\n{\n const auto& tally {model::tallies[i_tally]};\n\n auto sum = tally->results_(filter_index, score_index, RESULT_SUM);\n auto sum_sq = tally->results_(filter_index, score_index, RESULT_SUM_SQ);\n\n int n = tally->n_realizations_;\n auto mean = sum \/ n;\n double std_dev = std::sqrt((sum_sq\/n - mean*mean) \/ (n-1));\n double rel_err = (mean != 0.) ? std_dev \/ std::abs(mean) : 0.;\n\n return {std_dev, rel_err};\n}\n\n\/\/! Find the limiting limiting tally trigger.\n\/\/\n\/\/! param[out] ratio The uncertainty\/threshold ratio for the most limiting\n\/\/! tally trigger\n\/\/! param[out] tally_id The ID number of the most limiting tally\n\/\/! param[out] score The most limiting tally score bin\n\nvoid\ncheck_tally_triggers(double& ratio, int& tally_id, int& score)\n{\n ratio = 0.;\n for (auto i_tally = 0; i_tally < model::tallies.size(); ++i_tally) {\n const Tally& t {*model::tallies[i_tally]};\n\n \/\/ Ignore tallies with less than two realizations.\n if (t.n_realizations_ < 2) continue;\n\n for (const auto& trigger : t.triggers_) {\n const auto& results = t.results_;\n for (auto filter_index = 0; filter_index < results.shape()[0];\n ++filter_index) {\n for (auto score_index = 0; score_index < results.shape()[1];\n ++score_index) {\n \/\/ Compute the tally uncertainty metrics.\n auto uncert_pair = get_tally_uncertainty(i_tally, score_index,\n filter_index);\n double std_dev = uncert_pair.first;\n double rel_err = uncert_pair.second;\n\n \/\/ Pick out the relevant uncertainty metric for this trigger.\n double uncertainty;\n switch (trigger.metric) {\n case TriggerMetric::variance:\n uncertainty = std_dev * std_dev;\n break;\n case TriggerMetric::standard_deviation:\n uncertainty = std_dev;\n break;\n case TriggerMetric::relative_error:\n uncertainty = rel_err;\n break;\n case TriggerMetric::not_active:\n uncertainty = 0.0;\n break;\n }\n\n \/\/ Compute the uncertainty \/ threshold ratio.\n double this_ratio = uncertainty \/ trigger.threshold;\n if (trigger.metric == TriggerMetric::variance) {\n this_ratio = std::sqrt(ratio);\n }\n\n \/\/ If this is the most uncertain value, set the output variables.\n if (this_ratio > ratio) {\n ratio = this_ratio;\n score = t.scores_[trigger.score_index];\n tally_id = t.id_;\n }\n }\n }\n }\n }\n}\n\n\/\/! Compute the uncertainty\/threshold ratio for the eigenvalue trigger.\n\ndouble\ncheck_keff_trigger()\n{\n if (settings::run_mode != RUN_MODE_EIGENVALUE) return 0.0;\n\n double k_combined[2];\n openmc_get_keff(k_combined);\n\n double uncertainty = 0.;\n switch (settings::keff_trigger.metric) {\n case TriggerMetric::variance:\n uncertainty = k_combined[1] * k_combined[1];\n break;\n case TriggerMetric::standard_deviation:\n uncertainty = k_combined[1];\n break;\n case TriggerMetric::relative_error:\n uncertainty = k_combined[1] \/ k_combined[0];\n break;\n default:\n \/\/ If it's an unrecognized TriggerMetric or no keff trigger is on,\n \/\/ return 0 to stop division by zero where \"ratio\" is calculated.\n return 0.0;\n }\n\n double ratio = uncertainty \/ settings::keff_trigger.threshold;\n if (settings::keff_trigger.metric == TriggerMetric::variance)\n ratio = std::sqrt(ratio);\n return ratio;\n}\n\n\/\/! See if tally and eigenvalue uncertainties are under trigger thresholds.\n\nvoid\ncheck_triggers()\n{\n \/\/ Make some aliases.\n const auto current_batch {simulation::current_batch};\n const auto n_batches {settings::n_batches};\n const auto interval {settings::trigger_batch_interval};\n\n \/\/ See if the current batch is one for which the triggers must be checked.\n if (!settings::trigger_on) return;\n if (current_batch < n_batches) return;\n if (((current_batch - n_batches) % interval) != 0) return;\n\n \/\/ Check the eigenvalue and tally triggers.\n double keff_ratio = check_keff_trigger();\n double tally_ratio;\n int tally_id, score;\n check_tally_triggers(tally_ratio, tally_id, score);\n\n \/\/ If all the triggers are satisfied, alert the user and return.\n if (std::max(keff_ratio, tally_ratio) <= 1.) {\n simulation::satisfy_triggers = true;\n write_message(\"Triggers satisfied for batch \"\n + std::to_string(current_batch), 7);\n return;\n }\n\n \/\/ At least one trigger is unsatisfied. Let the user know which one.\n simulation::satisfy_triggers = false;\n std::stringstream msg;\n msg << \"Triggers unsatisfied, max unc.\/thresh. is \";\n if (keff_ratio >= tally_ratio) {\n msg << keff_ratio << \" for eigenvalue\";\n } else {\n msg << tally_ratio << \" for \" << reaction_name(score) << \" in tally \"\n << tally_id;\n }\n write_message(msg, 7);\n\n \/\/ Estimate batches til triggers are satisfied.\n if (settings::trigger_predict) {\n \/\/ This calculation assumes tally variance is proportional to 1\/N where N is\n \/\/ the number of batches.\n auto max_ratio = std::max(keff_ratio, tally_ratio);\n auto n_active = current_batch - settings::n_inactive;\n auto n_pred_batches = static_cast<int>(n_active * max_ratio * max_ratio)\n + settings::n_inactive + 1;\n\n std::stringstream msg;\n msg << \"The estimated number of batches is \" << n_pred_batches;\n if (n_pred_batches > settings::n_max_batches) {\n msg << \" --- greater than max batches\";\n warning(msg);\n } else {\n write_message(msg, 7);\n }\n }\n}\n\n} \/\/ namespace openmc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * mpu6050_node.cpp\n * Copyright (c) 2017, Robot Mitya.\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Robot Mitya nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Created on: Dec 3, 2017\n * Author: Dmitry Dzakhov\n *\/\n\n#include <ros\/ros.h>\n#include <sensor_msgs\/Imu.h>\n#include \"std_msgs\/String.h\"\n#include <wiringPi.h>\n#include <wiringPiI2C.h>\n#include \"consts.h\"\n#include \"mpu6050_helper.h\"\n#include \"madgwick.h\"\n\n#define VALUES_TO_CALIBRATE 1000\n\nclass Mpu6050Node\n{\npublic:\n Mpu6050Node();\n void readImuData(float *vX, float *vY, float *vZ, float *aX, float *aY, float *aZ);\n bool performingCalibration(float vX, float vY, float vZ);\n\n void fillImuMessage(const sensor_msgs::ImuPtr& msg, float vX, float vY, float vZ, float aX, float aY, float aZ);\n void publishImuMessage(const sensor_msgs::ImuPtr& msg);\nprivate:\n int i2cAddress_;\n int fileDescriptor_;\n uint8_t buffer_[14];\n float gyroFactor_;\n\n float readWord2c(int addr);\n\n \/\/ Topic RM_IMU_TOPIC_NAME ('imu') publisher:\n ros::Publisher imuPublisher_;\n\n ros::Subscriber imuInputSubscriber_;\n void imuInputCallback(const std_msgs::StringConstPtr& msg);\n\n MpuHelper mpuHelper_;\n\n ros::Time prevStamp_;\n uint32_t prevSeq_;\n MadgwickImu madgwick_;\n\n uint32_t seq_;\n};\n\nconst int PWR_MGMT_1 = 0x6B;\n\nMpu6050Node::Mpu6050Node()\n{\n ros::NodeHandle privateNodeHandle(\"~\");\n privateNodeHandle.param(\"i2c_address\", i2cAddress_, 0x68);\n\/\/ privateNodeHandle.\n\n \/\/ Connect to device.\n fileDescriptor_ = wiringPiI2CSetup(i2cAddress_);\n if (fileDescriptor_ == -1)\n {\n ROS_ERROR(\"No i2c device found?\");\n return;\n }\n \/\/ Device starts in sleep mode so wake it up.\n wiringPiI2CWriteReg16(fileDescriptor_, PWR_MGMT_1, 0);\n\n ros::NodeHandle nodeHandle(RM_NAMESPACE);\n imuPublisher_ = nodeHandle.advertise<sensor_msgs::Imu>(RM_HEAD_IMU_OUTPUT_TOPIC_NAME, 100);\n\n imuInputSubscriber_ = nodeHandle.subscribe(RM_HEAD_IMU_INPUT_TOPIC_NAME, 10, &Mpu6050Node::imuInputCallback, this);\n\n seq_ = 0;\n gyroFactor_ = 3.141592654f \/ 180 \/ 131;\n\n prevStamp_ = ros::Time::now();\n prevSeq_ = 0;\n madgwick_.center();\n}\n\nfloat Mpu6050Node::readWord2c(int addr)\n{\n uint16_t val = wiringPiI2CReadReg16(fileDescriptor_, addr);\n uint16_t swappedVal = (val >> 8) | (val << 8);\n return float((swappedVal >= 0x8000) ? -((65535 - swappedVal) + 1) : swappedVal);\n}\n\nvoid Mpu6050Node::readImuData(float *vX, float *vY, float *vZ, float *aX, float *aY, float *aZ)\n{\n \/\/ Read gyroscope values.\n \/\/ At default sensitivity of 250deg\/s we need to scale by 131.\n *vX = -readWord2c(0x47) * gyroFactor_; \/\/ -z (caused by chip orientation in robot)\n *vY = readWord2c(0x45) * gyroFactor_; \/\/ y\n *vZ = readWord2c(0x43) * gyroFactor_; \/\/ x (caused by chip orientation in robot)\n\n \/\/ Read accelerometer values.\n \/\/ At default sensitivity of 2g we need to scale by 16384.\n \/\/ Note: at \"level\" x = y = 0 but z = 1 (i.e. gravity)\n \/\/ But! Imu message documentations say acceleration should be in m\/2 so need to *9.807\n const float la_rescale = 16384.0 \/ 9.807;\n *aX = -readWord2c(0x3f) \/ la_rescale; \/\/ -z (caused by chip orientation in robot)\n *aY = readWord2c(0x3d) \/ la_rescale; \/\/ y\n *aZ = readWord2c(0x3b) \/ la_rescale; \/\/ x (caused by chip orientation in robot)\n\n mpuHelper_.correctMpuData(vX, vY, vZ);\n}\n\nvoid Mpu6050Node::fillImuMessage(const sensor_msgs::ImuPtr& msg, float vX, float vY, float vZ, float aX, float aY, float aZ)\n{\n msg->header.stamp = ros::Time::now();\n msg->header.seq = seq_++;\n msg->header.frame_id = '0'; \/\/ no frame\n\n msg->angular_velocity.x = vX;\n msg->angular_velocity.y = vY;\n msg->angular_velocity.z = vZ;\n\n msg->linear_acceleration.x = aX;\n msg->linear_acceleration.y = aY;\n msg->linear_acceleration.z = aZ;\n\n ros::Duration deltaTime = msg->header.stamp - prevStamp_;\n prevStamp_ = msg->header.stamp;\n madgwick_.update(deltaTime.toSec(), vX, vY, vZ, aX, aY, aZ);\n\n tf2Scalar qX, qY, qZ, qW;\n madgwick_.getQuaternion(qX, qY, qZ, qW);\n msg->orientation.x = qX;\n msg->orientation.y = qY;\n msg->orientation.z = qZ;\n msg->orientation.w = qW;\n}\n\nvoid Mpu6050Node::publishImuMessage(const sensor_msgs::ImuPtr& msg)\n{\n imuPublisher_.publish(msg);\n}\n\nvoid Mpu6050Node::imuInputCallback(const std_msgs::StringConstPtr& msg)\n{\n if (msg->data.compare(\"calibrate\") == 0)\n {\n ROS_INFO(\"Starting to calibrate head IMU...\");\n mpuHelper_.startCalibration();\n madgwick_.center();\n }\n else if (msg->data.compare(\"center\") == 0)\n {\n ROS_INFO(\"Center head IMU...\");\n madgwick_.center();\n }\n else if (msg->data.compare(\"configuration\") == 0)\n {\n uint8_t gyroConfig = wiringPiI2CReadReg8(fileDescriptor_, 27);\n uint8_t accConfig = wiringPiI2CReadReg8(fileDescriptor_, 28);\n ROS_INFO(\"GYRO_CONFIG (register 27) = %d ACCEL_CONFIG (register 28) = %d\", gyroConfig, accConfig);\n }\n else\n {\n ROS_ERROR(\"%s.%s: Unknown command \\\"%s\\\"\", RM_MPU6050_NODE_NAME, RM_HEAD_IMU_INPUT_TOPIC_NAME, msg->data.c_str());\n }\n}\n\nbool Mpu6050Node::performingCalibration(float vX, float vY, float vZ)\n{\n return mpuHelper_.processCalibration(vX, vY, vZ);\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, RM_MPU6050_NODE_NAME);\n\n Mpu6050Node mpu6050Node;\n sensor_msgs::ImuPtr imuPrt(new sensor_msgs::Imu());\n\n float vX, vY, vZ, aX, aY, aZ;\n ros::Rate rate(50); \/\/ hz\n while(ros::ok())\n {\n mpu6050Node.readImuData(&vX, &vY, &vZ, &aX, &aY, &aZ);\n\n if (!mpu6050Node.performingCalibration(vX, vY, vZ))\n {\n mpu6050Node.fillImuMessage(imuPrt, vX, vY, vZ, aX, aY, aZ);\n mpu6050Node.publishImuMessage(imuPrt);\n }\n\n ros::spinOnce();\n rate.sleep();\n }\n return 0;\n}\n<commit_msg>#12 IMU: mpu6050_node calibration fix<commit_after>\/*\n * mpu6050_node.cpp\n * Copyright (c) 2017, Robot Mitya.\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Robot Mitya nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Created on: Dec 3, 2017\n * Author: Dmitry Dzakhov\n *\/\n\n#include <ros\/ros.h>\n#include <sensor_msgs\/Imu.h>\n#include \"std_msgs\/String.h\"\n#include <wiringPi.h>\n#include <wiringPiI2C.h>\n#include \"consts.h\"\n#include \"mpu6050_helper.h\"\n#include \"madgwick.h\"\n\n#define VALUES_TO_CALIBRATE 1000\n\nclass Mpu6050Node\n{\npublic:\n Mpu6050Node();\n void readImuData(float *vX, float *vY, float *vZ, float *aX, float *aY, float *aZ);\n bool performingCalibration(float vX, float vY, float vZ);\n\n void fillImuMessage(const sensor_msgs::ImuPtr& msg, float vX, float vY, float vZ, float aX, float aY, float aZ);\n void publishImuMessage(const sensor_msgs::ImuPtr& msg);\n void center();\nprivate:\n int i2cAddress_;\n int fileDescriptor_;\n uint8_t buffer_[14];\n float gyroFactor_;\n\n float readWord2c(int addr);\n\n \/\/ Topic RM_IMU_TOPIC_NAME ('imu') publisher:\n ros::Publisher imuPublisher_;\n\n ros::Subscriber imuInputSubscriber_;\n void imuInputCallback(const std_msgs::StringConstPtr& msg);\n\n MpuHelper mpuHelper_;\n\n ros::Time prevStamp_;\n uint32_t prevSeq_;\n MadgwickImu madgwick_;\n\n uint32_t seq_;\n};\n\nconst int PWR_MGMT_1 = 0x6B;\n\nMpu6050Node::Mpu6050Node()\n{\n ros::NodeHandle privateNodeHandle(\"~\");\n privateNodeHandle.param(\"i2c_address\", i2cAddress_, 0x68);\n\/\/ privateNodeHandle.\n\n \/\/ Connect to device.\n fileDescriptor_ = wiringPiI2CSetup(i2cAddress_);\n if (fileDescriptor_ == -1)\n {\n ROS_ERROR(\"No i2c device found?\");\n return;\n }\n \/\/ Device starts in sleep mode so wake it up.\n wiringPiI2CWriteReg16(fileDescriptor_, PWR_MGMT_1, 0);\n\n ros::NodeHandle nodeHandle(RM_NAMESPACE);\n imuPublisher_ = nodeHandle.advertise<sensor_msgs::Imu>(RM_HEAD_IMU_OUTPUT_TOPIC_NAME, 100);\n\n imuInputSubscriber_ = nodeHandle.subscribe(RM_HEAD_IMU_INPUT_TOPIC_NAME, 10, &Mpu6050Node::imuInputCallback, this);\n\n seq_ = 0;\n gyroFactor_ = 3.141592654f \/ 180 \/ 131;\n\n prevStamp_ = ros::Time::now();\n prevSeq_ = 0;\n madgwick_.center();\n}\n\nfloat Mpu6050Node::readWord2c(int addr)\n{\n uint16_t val = wiringPiI2CReadReg16(fileDescriptor_, addr);\n uint16_t swappedVal = (val >> 8) | (val << 8);\n return float((swappedVal >= 0x8000) ? -((65535 - swappedVal) + 1) : swappedVal);\n}\n\nvoid Mpu6050Node::readImuData(float *vX, float *vY, float *vZ, float *aX, float *aY, float *aZ)\n{\n \/\/ Read gyroscope values.\n \/\/ At default sensitivity of 250deg\/s we need to scale by 131.\n *vX = -readWord2c(0x47) * gyroFactor_; \/\/ -z (caused by chip orientation in robot)\n *vY = readWord2c(0x45) * gyroFactor_; \/\/ y\n *vZ = readWord2c(0x43) * gyroFactor_; \/\/ x (caused by chip orientation in robot)\n\n \/\/ Read accelerometer values.\n \/\/ At default sensitivity of 2g we need to scale by 16384.\n \/\/ Note: at \"level\" x = y = 0 but z = 1 (i.e. gravity)\n \/\/ But! Imu message documentations say acceleration should be in m\/2 so need to *9.807\n const float la_rescale = 16384.0 \/ 9.807;\n *aX = -readWord2c(0x3f) \/ la_rescale; \/\/ -z (caused by chip orientation in robot)\n *aY = readWord2c(0x3d) \/ la_rescale; \/\/ y\n *aZ = readWord2c(0x3b) \/ la_rescale; \/\/ x (caused by chip orientation in robot)\n\n mpuHelper_.correctMpuData(vX, vY, vZ);\n}\n\nvoid Mpu6050Node::fillImuMessage(const sensor_msgs::ImuPtr& msg, float vX, float vY, float vZ, float aX, float aY, float aZ)\n{\n msg->header.stamp = ros::Time::now();\n msg->header.seq = seq_++;\n msg->header.frame_id = '0'; \/\/ no frame\n\n msg->angular_velocity.x = vX;\n msg->angular_velocity.y = vY;\n msg->angular_velocity.z = vZ;\n\n msg->linear_acceleration.x = aX;\n msg->linear_acceleration.y = aY;\n msg->linear_acceleration.z = aZ;\n\n ros::Duration deltaTime = msg->header.stamp - prevStamp_;\n prevStamp_ = msg->header.stamp;\n madgwick_.update(deltaTime.toSec(), vX, vY, vZ, aX, aY, aZ);\n\n tf2Scalar qX, qY, qZ, qW;\n madgwick_.getQuaternion(qX, qY, qZ, qW);\n msg->orientation.x = qX;\n msg->orientation.y = qY;\n msg->orientation.z = qZ;\n msg->orientation.w = qW;\n}\n\nvoid Mpu6050Node::publishImuMessage(const sensor_msgs::ImuPtr& msg)\n{\n imuPublisher_.publish(msg);\n}\n\nvoid Mpu6050Node::imuInputCallback(const std_msgs::StringConstPtr& msg)\n{\n if (msg->data.compare(\"calibrate\") == 0)\n {\n ROS_INFO(\"Starting to calibrate head IMU...\");\n mpuHelper_.startCalibration();\n \/\/madgwick_.center();\n }\n else if (msg->data.compare(\"center\") == 0)\n {\n ROS_INFO(\"Center head IMU...\");\n madgwick_.center();\n }\n else if (msg->data.compare(\"configuration\") == 0)\n {\n uint8_t gyroConfig = wiringPiI2CReadReg8(fileDescriptor_, 27);\n uint8_t accConfig = wiringPiI2CReadReg8(fileDescriptor_, 28);\n ROS_INFO(\"GYRO_CONFIG (register 27) = %d ACCEL_CONFIG (register 28) = %d\", gyroConfig, accConfig);\n }\n else\n {\n ROS_ERROR(\"%s.%s: Unknown command \\\"%s\\\"\", RM_MPU6050_NODE_NAME, RM_HEAD_IMU_INPUT_TOPIC_NAME, msg->data.c_str());\n }\n}\n\nbool Mpu6050Node::performingCalibration(float vX, float vY, float vZ)\n{\n return mpuHelper_.processCalibration(vX, vY, vZ);\n}\n\nvoid Mpu6050Node::center()\n{\n madgwick_.center();\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, RM_MPU6050_NODE_NAME);\n\n Mpu6050Node mpu6050Node;\n sensor_msgs::ImuPtr imuPrt(new sensor_msgs::Imu());\n\n float vX, vY, vZ, aX, aY, aZ;\n ros::Rate rate(50); \/\/ hz\n bool prevPerformingCalibration = false;\n bool performingCalibration;\n while(ros::ok())\n {\n mpu6050Node.readImuData(&vX, &vY, &vZ, &aX, &aY, &aZ);\n\n performingCalibration = mpu6050Node.performingCalibration(vX, vY, vZ);\n if (!performingCalibration)\n {\n mpu6050Node.fillImuMessage(imuPrt, vX, vY, vZ, aX, aY, aZ);\n mpu6050Node.publishImuMessage(imuPrt);\n }\n else if (prevPerformingCalibration && !performingCalibration)\n {\n \/\/ Calibration is over:\n mpu6050Node.center();\n }\n prevPerformingCalibration = performingCalibration;\n\n ros::spinOnce();\n rate.sleep();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2005-2006 Allen Winter <winter@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QCursor>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QVBoxLayout>\n#include <QGridLayout>\n#include <QEvent>\n\n\n#include <kdialog.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kmenu.h>\n#include <kstandarddirs.h>\n#include <kurllabel.h>\n\n#include <kcal\/calendar.h>\n#include <kcal\/resourcecalendar.h>\n#include <kcal\/resourcelocal.h>\n#include <kcal\/todo.h>\n#include <kcal\/incidenceformatter.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include \"core.h\"\n#include \"plugin.h\"\n#include \"todoplugin.h\"\n\n#include \"korganizer\/stdcalendar.h\"\n#include \"korganizer\/koglobals.h\"\n#include \"korganizer\/incidencechanger.h\"\n\n#include \"todosummarywidget.h\"\n#include \"korganizerinterface.h\"\n\nTodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin,\n QWidget *parent )\n : Kontact::Summary( parent ), mPlugin( plugin )\n{\n QVBoxLayout *mainLayout = new QVBoxLayout( this );\n mainLayout->setSpacing( 3 );\n mainLayout->setMargin( 3 );\n\n QPixmap icon =\n KIconLoader::global()->loadIcon( \"view-pim-tasks\",\n KIconLoader::Desktop, KIconLoader::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Pending To-dos\" ) );\n mainLayout->addWidget( header );\n\n mLayout = new QGridLayout();\n mainLayout->addItem( mLayout );\n mLayout->setSpacing( 3 );\n mLayout->setRowStretch( 6, 1 );\n\n mCalendar = KOrg::StdCalendar::self();\n mCalendar->load();\n\n connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );\n connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),\n SLOT( updateView() ) );\n\n updateView();\n}\n\nTodoSummaryWidget::~TodoSummaryWidget()\n{\n}\n\nvoid TodoSummaryWidget::updateView()\n{\n qDeleteAll( mLabels );\n mLabels.clear();\n\n KConfig _config( \"kcmtodosummaryrc\" );\n KConfigGroup config(&_config, \"Days\" );\n int mDaysToGo = config.readEntry( \"DaysToShow\", 7 );\n\n config.changeGroup( \"Hide\" );\n mHideInProgress = config.readEntry( \"InProgress\", false );\n mHideOverdue = config.readEntry( \"Overdue\", false );\n mHideCompleted = config.readEntry( \"Completed\", true );\n mHideOpenEnded = config.readEntry( \"OpenEnded\", true );\n mHideNotStarted = config.readEntry( \"NotStarted\", false );\n\n \/\/ for each todo,\n \/\/ if it passes the filter, append to a list\n \/\/ else continue\n \/\/ sort todolist by summary\n \/\/ sort todolist by priority\n \/\/ sort todolist by due-date\n \/\/ print todolist\n\n \/\/ the filter is created by the configuration summary options, but includes\n \/\/ days to go before to-do is due\n \/\/ which types of to-dos to hide\n\n KCal::Todo::List prList;\n\n Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) {\n if ( todo->hasDueDate() ) {\n int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n if ( daysTo >= mDaysToGo )\n continue;\n }\n\n if ( mHideOverdue && overdue( todo ) )\n continue;\n if ( mHideInProgress && inProgress( todo ) )\n continue;\n if ( mHideCompleted && completed( todo ) )\n continue;\n if ( mHideOpenEnded && openEnded( todo ) )\n continue;\n if ( mHideNotStarted && notStarted( todo ) )\n continue;\n\n prList.append( todo );\n }\n if ( !prList.isEmpty() ) {\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortSummary,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortPriority,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortDueDate,\n KCal::SortDirectionAscending );\n }\n\n \/\/ The to-do print consists of the following fields:\n \/\/ icon:due date:days-to-go:priority:summary:status\n \/\/ where,\n \/\/ the icon is the typical to-do icon\n \/\/ the due date it the to-do due date\n \/\/ the days-to-go\/past is the #days until\/since the to-do is due\n \/\/ this field is left blank if the to-do is open-ended\n \/\/ the priority is the to-do priority\n \/\/ the summary is the to-do summary\n \/\/ the status is comma-separated list of:\n \/\/ overdue\n \/\/ in-progress (started, or >0% completed)\n \/\/ complete (100% completed)\n \/\/ open-ended\n \/\/ not-started (no start date and 0% completed)\n\n \/\/ No reason to show the date year\n QString savefmt = KGlobal::locale()->dateFormat();\n KGlobal::locale()->setDateFormat( KGlobal::locale()->\n dateFormat().replace( 'Y', ' ' ) );\n\n int counter = 0;\n QLabel *label = 0;\n\n if ( !prList.isEmpty() ) {\n\n KIconLoader loader( \"korganizer\" );\n QPixmap pm = loader.loadIcon( \"view-calendar-tasks\", KIconLoader::Small );\n\n QString str;\n\n Q_FOREACH ( KCal::Todo *todo, prList ) {\n bool makeBold = false;\n int daysTo = -1;\n\n \/\/ Icon label\n label = new QLabel( this );\n label->setPixmap( pm );\n label->setMaximumWidth( label->minimumSizeHint().width() );\n mLayout->addWidget( label, counter, 0 );\n mLabels.append( label );\n\n \/\/ Due date label\n str = \"\";\n if ( todo->hasDueDate() ) {\n daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n\n if ( daysTo == 0 ) {\n makeBold = true;\n str = i18n( \"Today\" );\n } else if ( daysTo == 1 ) {\n str = i18n( \"Tomorrow\" );\n } else {\n str = KGlobal::locale()->formatDate( todo->dtDue().date() );\n }\n }\n\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 1 );\n mLabels.append( label );\n if ( makeBold ) {\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n }\n\n \/\/ Days togo\/ago label\n str = \"\";\n if ( todo->hasDueDate() ) {\n if ( daysTo > 0 ) {\n str = i18np( \"in 1 day\", \"in %1 days\", daysTo );\n } else if ( daysTo < 0 ) {\n str = i18np( \"1 day ago\", \"%1 days ago\", -daysTo );\n } else{\n str = i18n( \"due\" );\n }\n }\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 2 );\n mLabels.append( label );\n\n \/\/ Priority label\n str = '[' + QString::number( todo->priority() ) + ']';\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 3 );\n mLabels.append( label );\n\n \/\/ Summary label\n str = todo->summary();\n if ( todo->relatedTo() ) { \/\/ show parent only, not entire ancestry\n str = todo->relatedTo()->summary() + ':' + str;\n }\n\n KUrlLabel *urlLabel = new KUrlLabel( this );\n urlLabel->setText( str );\n urlLabel->setUrl( todo->uid() );\n urlLabel->installEventFilter( this );\n urlLabel->setTextFormat( Qt::RichText );\n mLayout->addWidget( urlLabel, counter, 4 );\n mLabels.append( urlLabel );\n\n connect( urlLabel, SIGNAL( leftClickedUrl( const QString& ) ),\n this, SLOT( viewTodo( const QString& ) ) );\n connect( urlLabel, SIGNAL( rightClickedUrl( const QString& ) ),\n this, SLOT( popupMenu( const QString& ) ) );\n\n QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) );\n if ( !tipText.isEmpty() ) {\n urlLabel->setToolTip( tipText );\n }\n\n \/\/ State text label\n str = stateStr( todo );\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 5 );\n mLabels.append( label );\n\n counter++;\n }\n } \/\/foreach\n\n if ( counter == 0 ) {\n QLabel *noTodos = new QLabel(\n i18np( \"No pending to-dos due within the next day\",\n \"No pending to-dos due within the next %1 days\",\n mDaysToGo ), this );\n noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );\n mLayout->addWidget( noTodos, 0, 2 );\n mLabels.append( noTodos );\n }\n\n Q_FOREACH( label, mLabels )\n label->show();\n\n KGlobal::locale()->setDateFormat( savefmt );\n}\n\nvoid TodoSummaryWidget::viewTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence( uid );\n}\n\nvoid TodoSummaryWidget::removeTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.deleteIncidence( uid, false );\n}\n\nvoid TodoSummaryWidget::completeTodo( const QString &uid )\n{\n KCal::Todo *todo = mCalendar->todo( uid );\n IncidenceChanger *changer = new IncidenceChanger( mCalendar, this );\n if ( !todo->isReadOnly() && changer->beginChange( todo ) ) {\n KCal::Todo *oldTodo = todo->clone();\n todo->setCompleted( KDateTime::currentLocalDateTime() );\n changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED );\n changer->endChange( todo );\n delete oldTodo;\n updateView();\n }\n}\n\nvoid TodoSummaryWidget::popupMenu( const QString &uid )\n{\n KMenu popup( this );\n QAction *editIt = popup.addAction( i18n( \"&Edit To-do...\" ) );\n QAction *delIt = popup.addAction( i18n( \"&Delete To-do\" ) );\n delIt->setIcon( KIconLoader::global()->\n loadIcon( \"edit-delete\", KIconLoader::Small) );\n QAction *doneIt = 0;\n KCal::Todo *todo = mCalendar->todo( uid );\n if ( !todo->isCompleted() ) {\n doneIt = popup.addAction( i18n( \"&Mark To-do Completed\" ) );\n doneIt->setIcon( KIconLoader::global()->\n loadIcon( \"task-complete\", KIconLoader::Small) );\n }\n \/\/ TODO: add icons to the menu actions\n\n const QAction *selectedAction = popup.exec( QCursor::pos() );\n if ( selectedAction == editIt ) {\n viewTodo( uid );\n } else if ( selectedAction == delIt ) {\n removeTodo( uid );\n } else if ( doneIt && selectedAction == doneIt ) {\n completeTodo( uid );\n }\n}\n\nbool TodoSummaryWidget::eventFilter( QObject *obj, QEvent* e )\n{\n if ( obj->inherits( \"KUrlLabel\" ) ) {\n KUrlLabel* label = static_cast<KUrlLabel*>( obj );\n if ( e->type() == QEvent::Enter )\n emit message( i18n( \"Edit To-do: \\\"%1\\\"\", label->text() ) );\n if ( e->type() == QEvent::Leave )\n emit message( QString::null );\t\/\/krazy:exclude=nullstrassign for old broken gcc\n }\n\n return Kontact::Summary::eventFilter( obj, e );\n}\n\nQStringList TodoSummaryWidget::configModules() const\n{\n return QStringList( \"kcmtodosummary.desktop\" );\n}\n\nbool TodoSummaryWidget::overdue( KCal::Todo *todo )\n{\n if ( todo->hasDueDate() && !todo->isCompleted() &&\n todo->dtDue().date() < QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::starts( KCal::Todo *todo )\n{\n if ( todo->hasStartDate() &&\n todo->dtStart().date() == QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::completed( KCal::Todo *todo )\n{\n return todo->isCompleted();\n}\n\nbool TodoSummaryWidget::openEnded( KCal::Todo *todo )\n{\n if ( !todo->hasDueDate() && !todo->isCompleted() )\n return true;\n else\n return false;\n}\n\nbool TodoSummaryWidget::inProgress( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return true;\n\n if ( todo->hasStartDate() && todo->hasDueDate() &&\n todo->dtStart().date() < QDate::currentDate() &&\n QDate::currentDate() < todo->dtDue().date() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::notStarted( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return false;\n\n if ( !todo->hasStartDate() )\n return false;\n\n if ( todo->dtStart().date() >= QDate::currentDate() )\n return false;\n\n return true;\n}\n\nconst QString TodoSummaryWidget::stateStr( KCal::Todo *todo )\n{\n QString str1, str2;\n\n if ( openEnded( todo ) ) {\n str1 = i18n( \"open-ended\" );\n } else if ( overdue( todo ) ) {\n str1 = i18n( \"overdue\" );\n } else if ( starts( todo ) ) {\n str1 = i18n( \"starts today\" );\n }\n\n if ( notStarted( todo ) ) {\n str2 += i18n( \"not-started\" );\n } else if ( completed( todo ) ) {\n str2 += i18n( \"completed\" );\n } else if ( inProgress( todo ) ) {\n str2 += i18n( \"in-progress \" );\n str2 += \" (\" + QString::number( todo->percentComplete() ) + \"%)\";\n }\n\n if ( !str1.isEmpty() && !str2.isEmpty() )\n str1 += i18nc( \"Separator for status like this: overdue, completed\", \",\" );\n\n return str1 + str2;\n}\n\n#include \"todosummarywidget.moc\"\n<commit_msg>QDate::currentDate().daysTo( todo->dtDue().date() ) returns negative number if the due date is invalid, thus the summary displays 2,451,561 days due. http:\/\/img515.imageshack.us\/my.php?image=todonoduedateed3.png<commit_after>\/*\n This file is part of Kontact.\n Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2005-2006 Allen Winter <winter@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include <QCursor>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QVBoxLayout>\n#include <QGridLayout>\n#include <QEvent>\n\n\n#include <kdialog.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kparts\/part.h>\n#include <kmenu.h>\n#include <kstandarddirs.h>\n#include <kurllabel.h>\n\n#include <kcal\/calendar.h>\n#include <kcal\/resourcecalendar.h>\n#include <kcal\/resourcelocal.h>\n#include <kcal\/todo.h>\n#include <kcal\/incidenceformatter.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include \"core.h\"\n#include \"plugin.h\"\n#include \"todoplugin.h\"\n\n#include \"korganizer\/stdcalendar.h\"\n#include \"korganizer\/koglobals.h\"\n#include \"korganizer\/incidencechanger.h\"\n\n#include \"todosummarywidget.h\"\n#include \"korganizerinterface.h\"\n\nTodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin,\n QWidget *parent )\n : Kontact::Summary( parent ), mPlugin( plugin )\n{\n QVBoxLayout *mainLayout = new QVBoxLayout( this );\n mainLayout->setSpacing( 3 );\n mainLayout->setMargin( 3 );\n\n QPixmap icon =\n KIconLoader::global()->loadIcon( \"view-pim-tasks\",\n KIconLoader::Desktop, KIconLoader::SizeMedium );\n QWidget *header = createHeader( this, icon, i18n( \"Pending To-dos\" ) );\n mainLayout->addWidget( header );\n\n mLayout = new QGridLayout();\n mainLayout->addItem( mLayout );\n mLayout->setSpacing( 3 );\n mLayout->setRowStretch( 6, 1 );\n\n mCalendar = KOrg::StdCalendar::self();\n mCalendar->load();\n\n connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );\n connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),\n SLOT( updateView() ) );\n\n updateView();\n}\n\nTodoSummaryWidget::~TodoSummaryWidget()\n{\n}\n\nvoid TodoSummaryWidget::updateView()\n{\n qDeleteAll( mLabels );\n mLabels.clear();\n\n KConfig _config( \"kcmtodosummaryrc\" );\n KConfigGroup config(&_config, \"Days\" );\n int mDaysToGo = config.readEntry( \"DaysToShow\", 7 );\n\n config.changeGroup( \"Hide\" );\n mHideInProgress = config.readEntry( \"InProgress\", false );\n mHideOverdue = config.readEntry( \"Overdue\", false );\n mHideCompleted = config.readEntry( \"Completed\", true );\n mHideOpenEnded = config.readEntry( \"OpenEnded\", true );\n mHideNotStarted = config.readEntry( \"NotStarted\", false );\n\n \/\/ for each todo,\n \/\/ if it passes the filter, append to a list\n \/\/ else continue\n \/\/ sort todolist by summary\n \/\/ sort todolist by priority\n \/\/ sort todolist by due-date\n \/\/ print todolist\n\n \/\/ the filter is created by the configuration summary options, but includes\n \/\/ days to go before to-do is due\n \/\/ which types of to-dos to hide\n\n KCal::Todo::List prList;\n\n Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) {\n if ( todo->hasDueDate() ) {\n int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n if ( daysTo >= mDaysToGo )\n continue;\n }\n\n if ( mHideOverdue && overdue( todo ) )\n continue;\n if ( mHideInProgress && inProgress( todo ) )\n continue;\n if ( mHideCompleted && completed( todo ) )\n continue;\n if ( mHideOpenEnded && openEnded( todo ) )\n continue;\n if ( mHideNotStarted && notStarted( todo ) )\n continue;\n\n prList.append( todo );\n }\n if ( !prList.isEmpty() ) {\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortSummary,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortPriority,\n KCal::SortDirectionAscending );\n prList = KCal::Calendar::sortTodos( &prList,\n KCal::TodoSortDueDate,\n KCal::SortDirectionAscending );\n }\n\n \/\/ The to-do print consists of the following fields:\n \/\/ icon:due date:days-to-go:priority:summary:status\n \/\/ where,\n \/\/ the icon is the typical to-do icon\n \/\/ the due date it the to-do due date\n \/\/ the days-to-go\/past is the #days until\/since the to-do is due\n \/\/ this field is left blank if the to-do is open-ended\n \/\/ the priority is the to-do priority\n \/\/ the summary is the to-do summary\n \/\/ the status is comma-separated list of:\n \/\/ overdue\n \/\/ in-progress (started, or >0% completed)\n \/\/ complete (100% completed)\n \/\/ open-ended\n \/\/ not-started (no start date and 0% completed)\n\n \/\/ No reason to show the date year\n QString savefmt = KGlobal::locale()->dateFormat();\n KGlobal::locale()->setDateFormat( KGlobal::locale()->\n dateFormat().replace( 'Y', ' ' ) );\n\n int counter = 0;\n QLabel *label = 0;\n\n if ( !prList.isEmpty() ) {\n\n KIconLoader loader( \"korganizer\" );\n QPixmap pm = loader.loadIcon( \"view-calendar-tasks\", KIconLoader::Small );\n\n QString str;\n\n Q_FOREACH ( KCal::Todo *todo, prList ) {\n bool makeBold = false;\n int daysTo = -1;\n\n \/\/ Icon label\n label = new QLabel( this );\n label->setPixmap( pm );\n label->setMaximumWidth( label->minimumSizeHint().width() );\n mLayout->addWidget( label, counter, 0 );\n mLabels.append( label );\n\n \/\/ Due date label\n str = \"\";\n if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) {\n daysTo = QDate::currentDate().daysTo( todo->dtDue().date() );\n\n if ( daysTo == 0 ) {\n makeBold = true;\n str = i18n( \"Today\" );\n } else if ( daysTo == 1 ) {\n str = i18n( \"Tomorrow\" );\n } else {\n str = KGlobal::locale()->formatDate( todo->dtDue().date() );\n }\n }\n\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 1 );\n mLabels.append( label );\n if ( makeBold ) {\n QFont font = label->font();\n font.setBold( true );\n label->setFont( font );\n }\n\n \/\/ Days togo\/ago label\n str = \"\";\n if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) {\n if ( daysTo > 0 ) {\n str = i18np( \"in 1 day\", \"in %1 days\", daysTo );\n } else if ( daysTo < 0 ) {\n str = i18np( \"1 day ago\", \"%1 days ago\", -daysTo );\n } else{\n str = i18n( \"due\" );\n }\n }\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 2 );\n mLabels.append( label );\n\n \/\/ Priority label\n str = '[' + QString::number( todo->priority() ) + ']';\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 3 );\n mLabels.append( label );\n\n \/\/ Summary label\n str = todo->summary();\n if ( todo->relatedTo() ) { \/\/ show parent only, not entire ancestry\n str = todo->relatedTo()->summary() + ':' + str;\n }\n\n KUrlLabel *urlLabel = new KUrlLabel( this );\n urlLabel->setText( str );\n urlLabel->setUrl( todo->uid() );\n urlLabel->installEventFilter( this );\n urlLabel->setTextFormat( Qt::RichText );\n mLayout->addWidget( urlLabel, counter, 4 );\n mLabels.append( urlLabel );\n\n connect( urlLabel, SIGNAL( leftClickedUrl( const QString& ) ),\n this, SLOT( viewTodo( const QString& ) ) );\n connect( urlLabel, SIGNAL( rightClickedUrl( const QString& ) ),\n this, SLOT( popupMenu( const QString& ) ) );\n\n QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) );\n if ( !tipText.isEmpty() ) {\n urlLabel->setToolTip( tipText );\n }\n\n \/\/ State text label\n str = stateStr( todo );\n label = new QLabel( str, this );\n label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );\n mLayout->addWidget( label, counter, 5 );\n mLabels.append( label );\n\n counter++;\n }\n } \/\/foreach\n\n if ( counter == 0 ) {\n QLabel *noTodos = new QLabel(\n i18np( \"No pending to-dos due within the next day\",\n \"No pending to-dos due within the next %1 days\",\n mDaysToGo ), this );\n noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );\n mLayout->addWidget( noTodos, 0, 2 );\n mLabels.append( noTodos );\n }\n\n Q_FOREACH( label, mLabels )\n label->show();\n\n KGlobal::locale()->setDateFormat( savefmt );\n}\n\nvoid TodoSummaryWidget::viewTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.editIncidence( uid );\n}\n\nvoid TodoSummaryWidget::removeTodo( const QString &uid )\n{\n mPlugin->core()->selectPlugin( \"kontact_todoplugin\" );\/\/ensure loaded\n OrgKdeKorganizerKorganizerInterface korganizer( \"org.kde.korganizer\", \"\/Korganizer\", QDBusConnection::sessionBus());\n korganizer.deleteIncidence( uid, false );\n}\n\nvoid TodoSummaryWidget::completeTodo( const QString &uid )\n{\n KCal::Todo *todo = mCalendar->todo( uid );\n IncidenceChanger *changer = new IncidenceChanger( mCalendar, this );\n if ( !todo->isReadOnly() && changer->beginChange( todo ) ) {\n KCal::Todo *oldTodo = todo->clone();\n todo->setCompleted( KDateTime::currentLocalDateTime() );\n changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED );\n changer->endChange( todo );\n delete oldTodo;\n updateView();\n }\n}\n\nvoid TodoSummaryWidget::popupMenu( const QString &uid )\n{\n KMenu popup( this );\n QAction *editIt = popup.addAction( i18n( \"&Edit To-do...\" ) );\n QAction *delIt = popup.addAction( i18n( \"&Delete To-do\" ) );\n delIt->setIcon( KIconLoader::global()->\n loadIcon( \"edit-delete\", KIconLoader::Small) );\n QAction *doneIt = 0;\n KCal::Todo *todo = mCalendar->todo( uid );\n if ( !todo->isCompleted() ) {\n doneIt = popup.addAction( i18n( \"&Mark To-do Completed\" ) );\n doneIt->setIcon( KIconLoader::global()->\n loadIcon( \"task-complete\", KIconLoader::Small) );\n }\n \/\/ TODO: add icons to the menu actions\n\n const QAction *selectedAction = popup.exec( QCursor::pos() );\n if ( selectedAction == editIt ) {\n viewTodo( uid );\n } else if ( selectedAction == delIt ) {\n removeTodo( uid );\n } else if ( doneIt && selectedAction == doneIt ) {\n completeTodo( uid );\n }\n}\n\nbool TodoSummaryWidget::eventFilter( QObject *obj, QEvent* e )\n{\n if ( obj->inherits( \"KUrlLabel\" ) ) {\n KUrlLabel* label = static_cast<KUrlLabel*>( obj );\n if ( e->type() == QEvent::Enter )\n emit message( i18n( \"Edit To-do: \\\"%1\\\"\", label->text() ) );\n if ( e->type() == QEvent::Leave )\n emit message( QString::null );\t\/\/krazy:exclude=nullstrassign for old broken gcc\n }\n\n return Kontact::Summary::eventFilter( obj, e );\n}\n\nQStringList TodoSummaryWidget::configModules() const\n{\n return QStringList( \"kcmtodosummary.desktop\" );\n}\n\nbool TodoSummaryWidget::overdue( KCal::Todo *todo )\n{\n if ( todo->hasDueDate() && !todo->isCompleted() &&\n todo->dtDue().date() < QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::starts( KCal::Todo *todo )\n{\n if ( todo->hasStartDate() &&\n todo->dtStart().date() == QDate::currentDate() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::completed( KCal::Todo *todo )\n{\n return todo->isCompleted();\n}\n\nbool TodoSummaryWidget::openEnded( KCal::Todo *todo )\n{\n if ( !todo->hasDueDate() && !todo->isCompleted() )\n return true;\n else\n return false;\n}\n\nbool TodoSummaryWidget::inProgress( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return true;\n\n if ( todo->hasStartDate() && todo->hasDueDate() &&\n todo->dtStart().date() < QDate::currentDate() &&\n QDate::currentDate() < todo->dtDue().date() )\n return true;\n\n return false;\n}\n\nbool TodoSummaryWidget::notStarted( KCal::Todo *todo )\n{\n if ( todo->percentComplete() > 0 )\n return false;\n\n if ( !todo->hasStartDate() )\n return false;\n\n if ( todo->dtStart().date() >= QDate::currentDate() )\n return false;\n\n return true;\n}\n\nconst QString TodoSummaryWidget::stateStr( KCal::Todo *todo )\n{\n QString str1, str2;\n\n if ( openEnded( todo ) ) {\n str1 = i18n( \"open-ended\" );\n } else if ( overdue( todo ) ) {\n str1 = i18n( \"overdue\" );\n } else if ( starts( todo ) ) {\n str1 = i18n( \"starts today\" );\n }\n\n if ( notStarted( todo ) ) {\n str2 += i18n( \"not-started\" );\n } else if ( completed( todo ) ) {\n str2 += i18n( \"completed\" );\n } else if ( inProgress( todo ) ) {\n str2 += i18n( \"in-progress \" );\n str2 += \" (\" + QString::number( todo->percentComplete() ) + \"%)\";\n }\n\n if ( !str1.isEmpty() && !str2.isEmpty() )\n str1 += i18nc( \"Separator for status like this: overdue, completed\", \",\" );\n\n return str1 + str2;\n}\n\n#include \"todosummarywidget.moc\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update hashing<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <cstdint>\n#include <algorithm>\n#include \"error.hpp\"\n\nnamespace spn {\n\textern none_t none;\n\ttemplate <class T>\n\tstruct _OptionalBuff {\n\t\tuint8_t _buffer[sizeof(T)];\n\n\t\t_OptionalBuff() = default;\n\t\ttemplate <class T2>\n\t\t_OptionalBuff(T2&& t) {\n\t\t\toperator=(std::forward<T2>(t));\n\t\t}\n\t\ttemplate <class T2>\n\t\tvoid operator = (T2&& t) {\n\t\t\tnew(_buffer) T(std::forward<T2>(t));\n\t\t}\n\t\tT& castT() { return *reinterpret_cast<T*>(_buffer); }\n\t\tconst T& castCT() const { return *reinterpret_cast<const T*>(_buffer); }\n\t\tvoid dtor() { castT().~T(); }\n\t};\n\n\ttemplate <class T>\n\tstruct _OptionalBuff<T&> {\n\t\tT*\t\t_buffer;\n\n\t\t_OptionalBuff() = default;\n\t\t_OptionalBuff(T* t): _buffer(t) {}\n\t\ttemplate <class T2>\n\t\t_OptionalBuff(T2&& t): _buffer(&t) {}\n\t\tvoid operator = (T&& t) { _buffer = &t; }\n\t\tvoid operator = (T& t) { _buffer = &t; }\n\t\tT& castT() { return *_buffer; }\n\t\tconst T& castCT() const { return *_buffer; }\n\t\tvoid dtor() {}\n\t};\n\ttemplate <class T>\n\tstruct _OptionalBuff<T*> {\n\t\tT*\t\t_buffer;\n\n\t\t_OptionalBuff() = default;\n\t\t_OptionalBuff(T* t): _buffer(t) {}\n\t\tvoid operator = (T* t) { _buffer = t; }\n\t\tT*& castT() { return _buffer; }\n\t\tconst T*& castCT() const { return _buffer; }\n\t\tvoid dtor() {}\n\t};\n\t\/\/! noseq_listでboost::optionalを使おうとしたらよくわからないエラーが出たので自作してしまった\n\ttemplate <class T>\n\tclass Optional {\n\t\tprivate:\n\t\t\t_OptionalBuff<T> _buffer;\n\t\t\tbool\t_bInit;\n\n\t\t\tvoid t__release() noexcept {\n\t\t\t\t_buffer.dtor();\n\t\t\t\t_bInit = false;\n\t\t\t}\n\t\t\tvoid _release() noexcept {\n\t\t\t\tif(_bInit)\n\t\t\t\t\tt__release();\n\t\t\t}\n\n\t\tpublic:\n\t\t\tconst static struct _AsInitialized {} AsInitialized;\n\t\t\t\/\/! コンストラクタは呼ばないけど初期化された物として扱う\n\t\t\t\/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる *\/\n\t\t\tOptional(_AsInitialized): _bInit(true) {}\n\n\t\t\tOptional(): _bInit(false) {}\n\t\t\tOptional(none_t): _bInit(false) {}\n\t\t\tOptional(const Optional<T>& t): _bInit(t) {\n\t\t\t\tif(t)\n\t\t\t\t\t_buffer = t._buffer.castCT();\n\t\t\t}\n\t\t\tOptional(Optional<T>&& t): _bInit(t) {\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = std::move(t._buffer.castT());\n\t\t\t\t\tt.t__release();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tOptional(T2&& t, typename std::enable_if<!std::is_same<typename std::decay<T2>::type, Optional<T>>::value>::type* = nullptr): _buffer(std::forward<T2>(t)), _bInit(true) {}\n\t\t\t~Optional() {\n\t\t\t\t_release();\n\t\t\t}\n\n\t\t\tdecltype(_buffer.castT()) get() {\n\t\t\t\tAssert(Trap, *this, \"optional: bad_get\")\n\t\t\t\treturn _buffer.castT();\n\t\t\t}\n\t\t\tdecltype(_buffer.castCT()) get() const {\n\t\t\t\treturn _buffer.castCT();\n\t\t\t}\n\t\t\tdecltype(_buffer.castT()) operator * () {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(_buffer.castCT()) operator * () const {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\toperator bool () const {\n\t\t\t\treturn _bInit;\n\t\t\t}\n\n\t\t\ttypename std::add_pointer<decltype(_buffer.castT())>::type operator -> () {\n\t\t\t\treturn &_buffer.castT();\n\t\t\t}\n\t\t\ttypename std::add_pointer<decltype(_buffer.castCT())>::type operator -> () const {\n\t\t\t\treturn &_buffer.castCT();\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tOptional& operator = (T2&& t) {\n\t\t\t\t_release();\n\t\t\t\t_buffer = std::forward<T2>(t);\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (none_t) noexcept {\n\t\t\t\t_release();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (const Optional<T>& t) {\n\t\t\t\t_release();\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = t._buffer.castT();\n\t\t\t\t\t_bInit = true;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (Optional<T>&& t) {\n\t\t\t\t_release();\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = std::move(t._buffer.castT());\n\t\t\t\t\tt.t__release();\n\t\t\t\t\t_bInit = true;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (_AsInitialized) noexcept {\n\t\t\t\t_release();\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t};\n\ttemplate <class T>\n\tconst typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};\n}\n<commit_msg>optionalバッファのアラインメント調整<commit_after>#pragma once\n#include <cstdint>\n#include <algorithm>\n#include \"error.hpp\"\n#include \"bits.hpp\"\n\nnamespace spn {\n\tstruct alignas(16) Align128 {};\n\tstruct alignas(32) Align256 {};\n\tstruct alignas(64) Align512 {};\n\tusing CTAlign = CType<uint8_t, uint16_t, uint32_t, uint64_t, Align128, Align256, Align512>;\n\ttemplate <int NByte, int AByte>\n\tstruct AlignedBuff {\n\t\tusing AlignType = typename CTAlign::template At<CTBit::MSB_N<AByte>::result>::type;\n\t\tunion {\n\t\t\tuint8_t \t_buffer[NByte];\n\t\t\tAlignType\t_align_dummy;\n\t\t};\n\t};\n\n\textern none_t none;\n\ttemplate <class T>\n\tstruct _OptionalBuff : AlignedBuff<sizeof(T), std::alignment_of<T>::value> {\n\t\tusing base = AlignedBuff<sizeof(T), std::alignment_of<T>::value>;\n\n\t\t_OptionalBuff() = default;\n\t\ttemplate <class T2>\n\t\t_OptionalBuff(T2&& t) {\n\t\t\toperator=(std::forward<T2>(t));\n\t\t}\n\t\ttemplate <class T2>\n\t\tvoid operator = (T2&& t) {\n\t\t\tnew(base::_buffer) T(std::forward<T2>(t));\n\t\t}\n\t\tT& castT() { return *reinterpret_cast<T*>(base::_buffer); }\n\t\tconst T& castCT() const { return *reinterpret_cast<const T*>(base::_buffer); }\n\t\tvoid dtor() { castT().~T(); }\n\t};\n\n\ttemplate <class T>\n\tstruct _OptionalBuff<T&> {\n\t\tT*\t\t_buffer;\n\n\t\t_OptionalBuff() = default;\n\t\t_OptionalBuff(T* t): _buffer(t) {}\n\t\ttemplate <class T2>\n\t\t_OptionalBuff(T2&& t): _buffer(&t) {}\n\t\tvoid operator = (T&& t) { _buffer = &t; }\n\t\tvoid operator = (T& t) { _buffer = &t; }\n\t\tT& castT() { return *_buffer; }\n\t\tconst T& castCT() const { return *_buffer; }\n\t\tvoid dtor() {}\n\t};\n\ttemplate <class T>\n\tstruct _OptionalBuff<T*> {\n\t\tT*\t\t_buffer;\n\n\t\t_OptionalBuff() = default;\n\t\t_OptionalBuff(T* t): _buffer(t) {}\n\t\tvoid operator = (T* t) { _buffer = t; }\n\t\tT*& castT() { return _buffer; }\n\t\tconst T*& castCT() const { return _buffer; }\n\t\tvoid dtor() {}\n\t};\n\t\/\/! noseq_listでboost::optionalを使おうとしたらよくわからないエラーが出たので自作してしまった\n\ttemplate <class T>\n\tclass Optional {\n\t\tprivate:\n\t\t\t_OptionalBuff<T> _buffer;\n\t\t\tbool\t_bInit;\n\n\t\t\tvoid t__release() noexcept {\n\t\t\t\t_buffer.dtor();\n\t\t\t\t_bInit = false;\n\t\t\t}\n\t\t\tvoid _release() noexcept {\n\t\t\t\tif(_bInit)\n\t\t\t\t\tt__release();\n\t\t\t}\n\n\t\tpublic:\n\t\t\tconst static struct _AsInitialized {} AsInitialized;\n\t\t\t\/\/! コンストラクタは呼ばないけど初期化された物として扱う\n\t\t\t\/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる *\/\n\t\t\tOptional(_AsInitialized): _bInit(true) {}\n\n\t\t\tOptional(): _bInit(false) {}\n\t\t\tOptional(none_t): _bInit(false) {}\n\t\t\tOptional(const Optional<T>& t): _bInit(t) {\n\t\t\t\tif(t)\n\t\t\t\t\t_buffer = t._buffer.castCT();\n\t\t\t}\n\t\t\tOptional(Optional<T>&& t): _bInit(t) {\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = std::move(t._buffer.castT());\n\t\t\t\t\tt.t__release();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tOptional(T2&& t, typename std::enable_if<!std::is_same<typename std::decay<T2>::type, Optional<T>>::value>::type* = nullptr): _buffer(std::forward<T2>(t)), _bInit(true) {}\n\t\t\t~Optional() {\n\t\t\t\t_release();\n\t\t\t}\n\n\t\t\tdecltype(_buffer.castT()) get() {\n\t\t\t\tAssert(Trap, *this, \"optional: bad_get\")\n\t\t\t\treturn _buffer.castT();\n\t\t\t}\n\t\t\tdecltype(_buffer.castCT()) get() const {\n\t\t\t\treturn _buffer.castCT();\n\t\t\t}\n\t\t\tdecltype(_buffer.castT()) operator * () {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(_buffer.castCT()) operator * () const {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\toperator bool () const {\n\t\t\t\treturn _bInit;\n\t\t\t}\n\n\t\t\ttypename std::add_pointer<decltype(_buffer.castT())>::type operator -> () {\n\t\t\t\treturn &_buffer.castT();\n\t\t\t}\n\t\t\ttypename std::add_pointer<decltype(_buffer.castCT())>::type operator -> () const {\n\t\t\t\treturn &_buffer.castCT();\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tOptional& operator = (T2&& t) {\n\t\t\t\t_release();\n\t\t\t\t_buffer = std::forward<T2>(t);\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (none_t) noexcept {\n\t\t\t\t_release();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (const Optional<T>& t) {\n\t\t\t\t_release();\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = t._buffer.castT();\n\t\t\t\t\t_bInit = true;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (Optional<T>&& t) {\n\t\t\t\t_release();\n\t\t\t\tif(t) {\n\t\t\t\t\t_buffer = std::move(t._buffer.castT());\n\t\t\t\t\tt.t__release();\n\t\t\t\t\t_bInit = true;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tOptional& operator = (_AsInitialized) noexcept {\n\t\t\t\t_release();\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t};\n\ttemplate <class T>\n\tconst typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ main.cpp\n\/\/ main entry point\n\n\/\/ Copyright 2015 Matthew Chandler\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include <random>\n\n#include <gtkmm\/application.h>\n\n#include \"maze.hpp\"\n\n\/\/ global prng\nthread_local std::random_device rng;\nthread_local std::mt19937 prng;\n\nint main(int argc, char * argv[])\n{\n prng.seed(rng());\n\n \/\/ create app and window objects\n Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, \"org.matt.mazegen\",\n Gio::APPLICATION_NON_UNIQUE | Gio::APPLICATION_HANDLES_OPEN);\n\n Maze maze(32, 32);\n\n return app->run(maze);\n}\n<commit_msg>fix prng seeding for mingw<commit_after>\/\/ main.cpp\n\/\/ main entry point\n\n\/\/ Copyright 2015 Matthew Chandler\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include <random>\n#ifdef __MINGW32__\n #include <ctime>\n#endif\n\n#include <gtkmm\/application.h>\n\n#include \"maze.hpp\"\n\n#ifndef __MINGW32__\n thread_local std::random_device rng;\n#endif\nthread_local std::mt19937 prng;\n\nint main(int argc, char * argv[])\n{\n \/\/ random_device curently not working in windows GCC\n #ifdef __MINGW32__\n prng.seed(time(NULL));\n #else\n prng.seed(rng());\n #endif\n\n \/\/ create app and window objects\n Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, \"org.matt.mazegen\",\n Gio::APPLICATION_NON_UNIQUE | Gio::APPLICATION_HANDLES_OPEN);\n\n Maze maze(32, 32);\n\n return app->run(maze);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"time.h\"\n#include <string>\n#include \"phashmap.h\"\n#include <cstdlib>\n#include <cstddef>\n#include <sys\/time.h>\n#define KEY_LEN 32\n#define VAL_LEN 128\nusing namespace std;\nstruct timeval tp;\n\ndouble diffclock(clock_t clock1, clock_t clock2){\n double clock_ts=clock1-clock2;\n double diffms=(clock_ts*1000)\/CLOCKS_PER_SEC;\n return diffms;\n}\n\ndouble getTime_usec() {\n gettimeofday(&tp, NULL);\n return static_cast<double>(tp.tv_sec) * 1E6\n + static_cast<double>(tp.tv_usec);\n}\n\n\nstring randomString(int len) {\n string s(len, ' ');\n srand(\/*getpid()*\/ clock() + getTime_usec());\n static const char alphanum[] = \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n for (int i = 0; i < len; ++i) {\n s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n }\n return s;\n}\ndouble testInsert(phashmap &map, string keys[], string vals[], int l){\n clock_t a=clock();\n for (int t = 0; t<l; t++){\n map.put(keys[t], vals[t]);\n }\n clock_t b=clock();\n return diffclock(b,a);;\n}\n\ndouble testGet(phashmap &map, string keys[], string vals[], int l){\n clock_t a=clock();\n for (int t=0; t<l; t++){\n if (map.get(keys[t])->compare(vals[t]) != 0)\n cerr << \"Get Failed\" << endl;\n }\n clock_t b=clock();\n return diffclock(b,a);\n}\n\ndouble testRemove(phashmap &map, string keys[], int l){\n clock_t a=clock();\n for (int t=0; t<l; t++){\n map.remove(keys[t]);\n }\n clock_t b=clock();\n return diffclock(b,a);\n}\nint main(int argc, char *argv[]){\n cout << \"\\nInitializing key-value pairs for testing\\n\" << endl;\n int size = atoi(argv[1]);\n string* keys = new string[size];\n string* vals = new string[size];\n for (int t=0; t<size; t++){\n keys[t] = randomString(KEY_LEN);\n vals[t] = randomString(VAL_LEN);\n }\n phashmap map (\"fbench.data\", 1000000, 10000, .7);\n \/\/phashmap map (\"\", 1000000, 10000, .7);\n \/\/phashmap map (\"fbench.data\", 1000000, -1);\n double ins, ret, rem;\n cout << \"Testing Insertion: Inserting \" << size << \" elements\" << endl;\n ins = testInsert(map, keys,vals,size);\n cout << \"Testing Retrieval: Retrieving \" << size << \" elements\" << endl;\n ret = testGet(map,keys,vals,size);\n cout << \"Testing Removal: Removing \" << size << \" elements\" << endl;\n rem = testRemove(map,keys,size);\n cout << \"\\nInsertion done in \" << ins << \" milliseconds\" << endl;\n cout << \"Retrieval done in \" << ret << \" milliseconds\" << endl;\n cout << \"Removal done in \" << rem << \" milliseconds\" << endl;\n\n return 0;\n}\n<commit_msg>\tmodified: fbench.cxx<commit_after>#include <iostream>\n#include \"time.h\"\n#include <string>\n#include \"phashmap.h\"\n#include <cstdlib>\n#include <cstddef>\n#include <sys\/time.h>\n#define KEY_LEN 32\n#define VAL_LEN 128\nusing namespace std;\nstruct timeval tp;\n\ndouble diffclock(clock_t clock1, clock_t clock2){\n double clock_ts=clock1-clock2;\n double diffms=(clock_ts*1000)\/CLOCKS_PER_SEC;\n return diffms;\n}\n\ndouble getTime_usec() {\n gettimeofday(&tp, NULL);\n return static_cast<double>(tp.tv_sec) * 1E6\n + static_cast<double>(tp.tv_usec);\n}\n\n\nstring randomString(int len) {\n string s(len, ' ');\n srand(\/*getpid()*\/ clock() + getTime_usec());\n static const char alphanum[] = \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n for (int i = 0; i < len; ++i) {\n s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n }\n return s;\n}\ndouble testInsert(phashmap &map, string keys[], string vals[], int l){\n clock_t a=clock();\n for (int t = 0; t<l; t++){\n map.put(keys[t], vals[t]);\n }\n clock_t b=clock();\n return diffclock(b,a);;\n}\n\ndouble testGet(phashmap &map, string keys[], string vals[], int l){\n clock_t a=clock();\n for (int t=0; t<l; t++){\n if (map.get(keys[t])->compare(vals[t]) != 0)\n cerr << \"Get Failed\" << endl;\n }\n clock_t b=clock();\n return diffclock(b,a);\n}\n\ndouble testRemove(phashmap &map, string keys[], int l){\n clock_t a=clock();\n for (int t=0; t<l; t++){\n map.remove(keys[t]);\n }\n clock_t b=clock();\n return diffclock(b,a);\n}\nint main(int argc, char *argv[]){\n cout << \"\\nInitializing key-value pairs for testing\\n\" << endl;\n int size = atoi(argv[1]);\n string* keys = new string[size];\n string* vals = new string[size];\n for (int t=0; t<size; t++){\n keys[t] = randomString(KEY_LEN);\n vals[t] = randomString(VAL_LEN);\n }\n phashmap map (\"\/dev\/shm\/fbench.data\", 1000000, 10000, .7);\n \/\/phashmap map (\"\", 1000000, 10000, .7);\n \/\/phashmap map (\"fbench.data\", 1000000, -1);\n double ins, ret, rem;\n cout << \"Testing Insertion: Inserting \" << size << \" elements\" << endl;\n ins = testInsert(map, keys,vals,size);\n cout << \"Testing Retrieval: Retrieving \" << size << \" elements\" << endl;\n ret = testGet(map,keys,vals,size);\n cout << \"Testing Removal: Removing \" << size << \" elements\" << endl;\n rem = testRemove(map,keys,size);\n cout << \"\\nInsertion done in \" << ins << \" milliseconds\" << endl;\n cout << \"Retrieval done in \" << ret << \" milliseconds\" << endl;\n cout << \"Removal done in \" << rem << \" milliseconds\" << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <vector>\n\n#include <iterator>\n\n#include \"acmacs-base\/date.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson::inline v2\n{\n class value;\n}\n\nnamespace acmacs::time_series::inline v2\n{\n struct slot\n {\n date::year_month_day first, after_last;\n constexpr bool operator==(const slot& rhs) const { return first == rhs.first && after_last == rhs.after_last; }\n };\n\n using series = std::vector<slot>;\n\n enum class interval { year, month, week, day };\n\n interval interval_from_string(std::string_view interval_name);\n\n struct parameters\n {\n date::year_month_day first, after_last; \/\/ {date::invalid_date()};\n interval intervl{interval::month};\n size_t number_of_intervals{1};\n };\n\n series make(const parameters& param);\n series make(const rjson::value& source, const parameters& default_param);\n inline series make(date::year_month_day first, date::year_month_day after_last) { return make(parameters{first, after_last}); }\n inline series make(std::string_view first, std::string_view after_last) { return make(parameters{date::from_string(first, date::allow_incomplete::yes), date::from_string(after_last, date::allow_incomplete::yes)}); }\n\n std::string text_name(const slot& a_slot);\n std::string numeric_name(const slot& a_slot);\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate <> struct fmt::formatter<acmacs::time_series::series>\n{\n template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }\n template <typename FormatContext> auto format(const acmacs::time_series::series& series, FormatContext& ctx)\n {\n format_to(ctx.out(), \"time-series{{\");\n for (const auto& slot : series)\n format_to(ctx.out(), \" {}..{}\", slot.first, slot.after_last);\n return format_to(ctx.out(), \"}}\");\n }\n};\n\ntemplate <> struct fmt::formatter<acmacs::time_series::interval> : fmt::formatter<std::string> {\n template <typename FormatCtx> auto format(const acmacs::time_series::interval& intervl, FormatCtx& ctx)\n {\n switch (intervl) {\n case acmacs::time_series::v2::interval::year:\n return fmt::formatter<std::string>::format(\"year\", ctx);\n case acmacs::time_series::v2::interval::month:\n return fmt::formatter<std::string>::format(\"month\", ctx);\n case acmacs::time_series::v2::interval::week:\n return fmt::formatter<std::string>::format(\"week\", ctx);\n case acmacs::time_series::v2::interval::day:\n return fmt::formatter<std::string>::format(\"day\", ctx);\n }\n }\n};\n\ntemplate <> struct fmt::formatter<acmacs::time_series::parameters>\n{\n template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }\n template <typename FormatContext> auto format(const acmacs::time_series::parameters& param, FormatContext& ctx)\n {\n return format_to(ctx.out(), \"time-series{{{} .. {}, {}:{}}}\", param.first, param.after_last, param.intervl, param.number_of_intervals);\n }\n};\n\n\/\/ ======================================================================\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/ class TimeSeriesIterator : public std::iterator<std::input_iterator_tag, date::year_month_day, date::year_month_day, const date::year_month_day*, date::year_month_day>\n\/\/ {\n\/\/ public:\n\/\/ TimeSeriesIterator(const TimeSeriesIterator&) = default;\n\/\/ virtual ~TimeSeriesIterator() = default;\n\n\/\/ bool operator==(const TimeSeriesIterator& other) const { return mDate == other.mDate; }\n\/\/ bool operator!=(const TimeSeriesIterator& other) const {return !(*this == other);}\n\/\/ TimeSeriesIterator& operator++() { mDate = next(); return *this; }\n\/\/ reference operator*() const { return mDate; }\n\/\/ pointer operator->() const { return &mDate; }\n\n\/\/ virtual date::year_month_day next() const = 0;\n\/\/ virtual std::string numeric_name() const = 0;\n\/\/ virtual std::string text_name() const { return numeric_name(); }\n\n\/\/ std::string first_date() const { return date::year4_month2_day2(mDate); }\n\/\/ std::string after_last_date() const { return date::year4_month2_day2(next()); }\n\n\/\/ protected:\n\/\/ inline TimeSeriesIterator(const date::year_month_day& d) : mDate(d) {}\n\/\/ date::year_month_day mDate;\n\n\/\/ }; \/\/ class TimeSeriesIterator\n\n\/\/ \/\/ ----------------------------------------------------------------------\n\n\/\/ class MonthlyTimeSeries\n\/\/ {\n\/\/ public:\n\/\/ MonthlyTimeSeries(const date::year_month_day& aStart, const date::year_month_day& aEnd) : mStart(date::beginning_of_month(aStart)), mEnd(date::beginning_of_month(aEnd)) {}\n\/\/ MonthlyTimeSeries(std::string_view aStart, std::string_view aEnd) : mStart(date::beginning_of_month(date::from_string(aStart))), mEnd(date::beginning_of_month(date::from_string(aEnd))) {}\n\n\/\/ int number_of_months() const { return date::months_between_dates(mStart, mEnd); }\n\n\/\/ class Iterator : public TimeSeriesIterator\n\/\/ {\n\/\/ public:\n\/\/ virtual date::year_month_day next() const { return date::next_month(mDate); }\n\/\/ virtual std::string numeric_name() const { return date::year4_month2(mDate); }\n\/\/ virtual std::string text_name() const { return date::monthtext_year(mDate); }\n\n\/\/ private:\n\/\/ friend class MonthlyTimeSeries;\n\/\/ Iterator(const date::year_month_day& d) : TimeSeriesIterator(d) {}\n\/\/ };\n\n\/\/ Iterator begin() const { return mStart; }\n\/\/ Iterator end() const { return mEnd; }\n\n\/\/ const auto& m_start() const { return mStart; }\n\/\/ const auto& m_end() const { return mEnd; }\n\n\/\/ private:\n\/\/ date::year_month_day mStart, mEnd;\n\n\/\/ }; \/\/ class MonthlyTimeSeries\n\n\/\/ template <> struct fmt::formatter<MonthlyTimeSeries> : fmt::formatter<std::string> {\n\/\/ template <typename FormatCtx> auto format(const MonthlyTimeSeries& ts, FormatCtx& ctx) { return fmt::formatter<std::string>::format(fmt::format(\"{}..{} ({})\", ts.m_start(), ts.m_end(), ts.number_of_months()), ctx); }\n\/\/ };\n\n\/\/ \/\/ ----------------------------------------------------------------------\n\n\/\/ class YearlyTimeSeries\n\/\/ {\n\/\/ public:\n\/\/ YearlyTimeSeries(const date::year_month_day& aStart, const date::year_month_day& aEnd) : mStart(date::beginning_of_year(aStart)), mEnd(date::beginning_of_year(aEnd)) {}\n\/\/ YearlyTimeSeries(std::string_view aStart, std::string_view aEnd) : mStart(date::beginning_of_year(date::from_string(aStart))), mEnd(date::beginning_of_year(date::from_string(aEnd))) {}\n\n\/\/ int number_of_years() const { return years_between_dates(mStart, mEnd); }\n\n\/\/ class Iterator : public TimeSeriesIterator\n\/\/ {\n\/\/ public:\n\/\/ virtual date::year_month_day next() const { return date::next_year(mDate); }\n\/\/ virtual std::string numeric_name() const { return date::year_4(mDate); }\n\n\/\/ private:\n\/\/ friend class YearlyTimeSeries;\n\/\/ Iterator(const date::year_month_day& d) : TimeSeriesIterator(d) {}\n\/\/ };\n\n\/\/ Iterator begin() const { return mStart; }\n\/\/ Iterator end() const { return mEnd; }\n\n\/\/ const auto& m_start() const { return mStart; }\n\/\/ const auto& m_end() const { return mEnd; }\n\n\/\/ private:\n\/\/ date::year_month_day mStart, mEnd;\n\n\/\/ }; \/\/ class YearlyTimeSeries\n\n\/\/ template <> struct fmt::formatter<YearlyTimeSeries> : fmt::formatter<std::string> {\n\/\/ template <typename FormatCtx> auto format(const YearlyTimeSeries& ts, FormatCtx& ctx) { return fmt::formatter<std::string>::format(fmt::format(\"{}..{} ({})\", ts.m_start(), ts.m_end(), ts.number_of_years()), ctx); }\n\/\/ };\n\n\/\/ \/\/ ----------------------------------------------------------------------\n\n\/\/ class WeeklyTimeSeries\n\/\/ {\n\/\/ public:\n\/\/ \/\/ WeeklyTimeSeries() {}\n\/\/ WeeklyTimeSeries(const date::year_month_day& aStart, const date::year_month_day& aEnd) : mStart(date::beginning_of_week(aStart)), mEnd(date::beginning_of_week(aEnd)) {}\n\/\/ WeeklyTimeSeries(std::string_view aStart, std::string_view aEnd) : mStart(date::beginning_of_week(date::from_string(aStart))), mEnd(date::beginning_of_week(date::from_string(aEnd))) {}\n\n\/\/ int number_of_weeks() const { return weeks_between_dates(mStart, mEnd); }\n\n\/\/ class Iterator : public TimeSeriesIterator\n\/\/ {\n\/\/ public:\n\/\/ virtual date::year_month_day next() const { return date::next_week(mDate); }\n\/\/ virtual std::string numeric_name() const { return date::display(mDate); }\n\n\/\/ private:\n\/\/ friend class WeeklyTimeSeries;\n\/\/ Iterator(const date::year_month_day& d) : TimeSeriesIterator(d) {}\n\/\/ };\n\n\/\/ Iterator begin() const { return mStart; }\n\/\/ Iterator end() const { return mEnd; }\n\n\/\/ const auto& m_start() const { return mStart; }\n\/\/ const auto& m_end() const { return mEnd; }\n\n\/\/ private:\n\/\/ date::year_month_day mStart, mEnd;\n\n\/\/ }; \/\/ class WeeklyTimeSeries\n\n\/\/ template <> struct fmt::formatter<WeeklyTimeSeries> : fmt::formatter<std::string> {\n\/\/ template <typename FormatCtx> auto format(const WeeklyTimeSeries& ts, FormatCtx& ctx) { return fmt::formatter<std::string>::format(fmt::format(\"{}..{} ({})\", ts.m_start(), ts.m_end(), ts.number_of_weeks()), ctx); }\n\/\/ };\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>old time series stuff removed<commit_after>#pragma once\n\n#include <vector>\n\n#include <iterator>\n\n#include \"acmacs-base\/date.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace rjson::inline v2\n{\n class value;\n}\n\nnamespace acmacs::time_series::inline v2\n{\n struct slot\n {\n date::year_month_day first, after_last;\n constexpr bool operator==(const slot& rhs) const { return first == rhs.first && after_last == rhs.after_last; }\n };\n\n using series = std::vector<slot>;\n\n enum class interval { year, month, week, day };\n\n interval interval_from_string(std::string_view interval_name);\n\n struct parameters\n {\n date::year_month_day first, after_last; \/\/ {date::invalid_date()};\n interval intervl{interval::month};\n size_t number_of_intervals{1};\n };\n\n series make(const parameters& param);\n series make(const rjson::value& source, const parameters& default_param);\n inline series make(date::year_month_day first, date::year_month_day after_last) { return make(parameters{first, after_last}); }\n inline series make(std::string_view first, std::string_view after_last) { return make(parameters{date::from_string(first, date::allow_incomplete::yes), date::from_string(after_last, date::allow_incomplete::yes)}); }\n\n std::string text_name(const slot& a_slot);\n std::string numeric_name(const slot& a_slot);\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate <> struct fmt::formatter<acmacs::time_series::series>\n{\n template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }\n template <typename FormatContext> auto format(const acmacs::time_series::series& series, FormatContext& ctx)\n {\n format_to(ctx.out(), \"time-series{{\");\n for (const auto& slot : series)\n format_to(ctx.out(), \" {}..{}\", slot.first, slot.after_last);\n return format_to(ctx.out(), \"}}\");\n }\n};\n\ntemplate <> struct fmt::formatter<acmacs::time_series::interval> : fmt::formatter<std::string> {\n template <typename FormatCtx> auto format(const acmacs::time_series::interval& intervl, FormatCtx& ctx)\n {\n switch (intervl) {\n case acmacs::time_series::v2::interval::year:\n return fmt::formatter<std::string>::format(\"year\", ctx);\n case acmacs::time_series::v2::interval::month:\n return fmt::formatter<std::string>::format(\"month\", ctx);\n case acmacs::time_series::v2::interval::week:\n return fmt::formatter<std::string>::format(\"week\", ctx);\n case acmacs::time_series::v2::interval::day:\n return fmt::formatter<std::string>::format(\"day\", ctx);\n }\n }\n};\n\ntemplate <> struct fmt::formatter<acmacs::time_series::parameters>\n{\n template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }\n template <typename FormatContext> auto format(const acmacs::time_series::parameters& param, FormatContext& ctx)\n {\n return format_to(ctx.out(), \"time-series{{{} .. {}, {}:{}}}\", param.first, param.after_last, param.intervl, param.number_of_intervals);\n }\n};\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <cstring>\n#include <cpr\/cpr.h>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <sstream>\n#include <tw\/oauth.h>\n#include <unordered_map>\n\n#ifdef __linux__\n# include <stdlib.h>\n# include <unistd.h>\n#endif\n\n#ifdef _WIN32\n# include <Windows.h>\n#endif\n\n#include <utils.h>\n\n#define MAX_PATH_LEN 8192\n\nstatic std::unordered_map<std::string, std::string> configs = {\n\t{ \"giveaway\", \"\/giveaway\" },\n\t{ \"twitter\", \"\/twitter\" },\n\t{ \"config\", \"\/config\" },\n\t{ \"submit\", \"\/submitted\" },\n};\n\nstatic const std::string PB = \"https:\/\/ptpb.pw\/\";\n\nbool utils::startsWith(const std::string &str, const std::string &prefix)\n{\n\treturn str.find(prefix) == 0;\n}\n\nbool utils::endsWith(const std::string &str, const std::string &suffix)\n{\n\treturn str.find(suffix) == str.length() - suffix.length();\n}\n\nstd::vector<std::string> &utils::split(const std::string &str,\n\t\tchar delim, std::vector<std::string> &elems)\n{\n\tstd::stringstream ss(str);\n\tstd::string item;\n\twhile (std::getline(ss, item, delim)) {\n\t\tif (!item.empty())\n\t\t\telems.push_back(item);\n\t}\n\treturn elems;\n}\n\nstd::string utils::formatInteger(std::string integer)\n{\n\tint pos = integer.length() - 3;\n\tif (pos < 1)\n\t\treturn integer;\n\twhile (pos > 0) {\n\t\tinteger.insert(pos, \",\");\n\t\tpos -= 3;\n\t}\n\treturn integer;\n}\n\n#ifdef _WIN32\nstatic std::string configdir_win()\n{\n\tchar buf[MAX_PATH_LEN];\n\tint bytes;\n\n\tif (!(bytes = GetModuleFileName(NULL, buf, sizeof(buf)))) {\n\t\tstd::cerr << \"could not get current directory\" << std::endl;\n\t\treturn \"\";\n\t}\n\n\t\/* strip filename from path *\/\n\tstd::string path(buf);\n\tpath = path.substr(0, path.find_last_of(\"\\\\\"));\n\n\treturn path;\n}\n#endif\n\n#ifdef __linux__\nstatic std::string configdir_unix()\n{\n\tchar *h;\n\tif (!(h= getenv(\"HOME\"))) {\n\t\tstd::cerr << \"could not read $HOME\" << std::endl;\n\t\treturn \"\";\n\t}\n\treturn std::string(h) + \"\/.lynxbot\";\n}\n#endif\n\nstd::string utils::configdir()\n{\n#ifdef __linux__\n\treturn configdir_unix();\n#endif\n#ifdef _WIN32\n\treturn configdir_win();\n#endif\n}\n\nstd::string utils::config(const std::string &cfg)\n{\n\tstd::string path = \"\";\n\tif (configs.find(cfg) != configs.end()) {\n\t\tpath += configs[cfg];\n#ifdef _WIN32\n\t\tstd::replace(path.begin(), path.end(), '\/', '\\\\');\n\t\tif (cfg != \"twitter\")\n\t\t\tpath += \".txt\";\n#endif\n\t}\n\treturn path;\n}\n\nbool utils::readJSON(const std::string &filename, Json::Value &val)\n{\n\tJson::Reader reader;\n\tstd::ifstream fileStream(configdir() + \"\/json\/\" + filename,\n\t\tstd::ifstream::binary);\n\n\tif (!reader.parse(fileStream, val)) {\n\t\tstd::cerr << reader.getFormattedErrorMessages() << std::endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid utils::writeJSON(const std::string &filename, Json::Value &val)\n{\n\tstd::ofstream ofile(configdir() + \"\/json\/\" + filename);\n\tJson::StyledWriter sw;\n\tofile << sw.write(val);\n\tofile.close();\n}\n\nbool utils::parseBool(bool &b, const std::string &s, std::string &err)\n{\n\tif (s == \"true\") {\n\t\tb = true;\n\t\treturn true;\n\t}\n\tif (s == \"false\") {\n\t\tb = false;\n\t\treturn true;\n\t}\n\terr = \"invalid setting -- \" + s;\n\treturn false;\n}\n\nbool utils::parseInt(uint32_t &i, const std::string &s, std::string &err)\n{\n\ttry {\n\t\ti = std::stoi(s);\n\t\treturn true;\n\t} catch (std::invalid_argument) {\n\t\terr = \"invalid number -- \" + s;\n\t\treturn false;\n\t}\n}\n\n#define MIN\t 60\n#define HOUR\t 3600\n#define DAY\t 86400\n\n\/* conv_time: convert t to days, hours, minutes and seconds *\/\nstd::string utils::conv_time(time_t t)\n{\n\ttime_t d, h, m;\n\tstd::string out;\n\n\td = t \/ DAY;\n\tt %= DAY;\n\th = t \/ HOUR;\n\tt %= HOUR;\n\tm = t \/ MIN;\n\tt %= MIN;\n\n\tif (d)\n\t\tout += std::to_string(d) + \" day\" + (d == 1 ? \"\" : \"s\") + \", \";\n\tif (h)\n\t\tout += std::to_string(h) + \" hour\" + (h == 1 ? \"\" : \"s\") + \", \";\n\tif (m)\n\t\tout += std::to_string(m) + \" minute\" + (m == 1 ? \"\" : \"s\")\n\t\t\t+ \" and \";\n\tout += std::to_string(t) + \" second\" + (t == 1 ? \"\" : \"s\");\n\treturn out;\n}\n\n\/* getamt: read number from string num into amt *\/\nbool utils::readnum(char *num, int64_t *amt)\n{\n\tsize_t last;\n\tint64_t n, mult;\n\n\tlast = strlen(num) - 1;\n\tmult = 1;\n\tif (num[last] == 'k' || num[last] == 'm' || num[last] == 'b') {\n\t\tswitch (num[last]) {\n\t\tcase 'k':\n\t\t\tmult = 1000;\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\tmult = 1000000;\n\t\t\tbreak;\n\t\tcase 'b':\n\t\t\tmult = 1000000000;\n\t\t\tbreak;\n\t\t}\n\t\tnum[last] = '\\0';\n\t}\n\n\tn = 0;\n\tfor (; *num; ++num) {\n\t\tif (*num < '0' || *num > '9')\n\t\t\treturn false;\n\t\tn = 10 * n + (*num - '0');\n\t}\n\t*amt = n * mult;\n\treturn true;\n}\n\n\/* upload: upload s to ptpb.pw *\/\nstd::string utils::upload(const std::string &s)\n{\n\tcpr::Response resp;\n\tsize_t i;\n\tstd::string url;\n\n\tresp = cpr::Post(cpr::Url(PB), cpr::Body(\"c=\" + tw::pencode(s, \"\\n\")));\n\n\tif ((i = resp.text.find(\"url:\")) == std::string::npos)\n\t\treturn \"failed to upload\";\n\n\turl = resp.text.substr(i + 5);\n\tif ((i = url.find('\\n')) != std::string::npos)\n\t\turl = url.substr(0, i);\n\n\treturn url;\n}\n\n\/* map of html encoded characters *\/\nstatic std::unordered_map<std::string, char> encoded = {\n\t{ \"amp\", '&' },\n\t{ \"gt\", '>' },\n\t{ \"lt\", '<' },\n\t{ \"quot\", '\"' }\n};\n\n\/* decode: decode html encoded string *\/\nstd::string utils::decode(const std::string &s)\n{\n\tsize_t i;\n\tstd::string out, enc;\n\n\tfor (i = 0; i < s.length(); ++i) {\n\t\tif (s[i] == '&') {\n\t\t\tenc.clear();\n\t\t\tfor (++i; s[i] != ';'; ++i)\n\t\t\t\tenc += s[i];\n\t\t\tout += encoded[enc];\n\t\t\tcontinue;\n\t\t}\n\t\tout += s[i] == '\\n' ? ' ' : s[i];\n\t}\n\treturn out;\n}\n\n\/* parse_time: extract time and date from ftime *\/\nstd::string utils::parse_time(const std::string &ftime, bool since)\n{\n\tstd::tm tm, curr;\n\ttime_t t, now;\n\tstd::ostringstream out;\n\tstd::istringstream ss(ftime);\n\n#ifdef __linux__\n\tss.imbue(std::locale(\"en_US.utf-8\"));\n#endif\n#ifdef _WIN32\n\tss.imbue(std::locale(\"en-US\"));\n#endif\n\tss >> std::get_time(&tm, \"%Y-%m-%dT%H:%M:%S\");\n\ttm.tm_isdst = 0;\n\tt = std::mktime(&tm);\n\n\tnow = time(NULL);\n\tcurr = *std::gmtime(&now);\n\tcurr.tm_isdst = 0;\n\tnow = std::mktime(&curr);\n\n\tout << utils::conv_time(now - t);\n\tif (since) {\n\t\tout << \" (since \";\n\t\tout << std::put_time(&tm, \"%H:%M:%S UTC, %d %b %Y\") << \")\";\n\t}\n\n\treturn out.str();\n}\n<commit_msg>Change to gmtime_s for windows<commit_after>#include <algorithm>\n#include <cstring>\n#include <cpr\/cpr.h>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <locale>\n#include <sstream>\n#include <tw\/oauth.h>\n#include <unordered_map>\n\n#ifdef __linux__\n# include <stdlib.h>\n# include <unistd.h>\n#endif\n\n#ifdef _WIN32\n# include <Windows.h>\n#endif\n\n#include <utils.h>\n\n#define MAX_PATH_LEN 8192\n\nstatic std::unordered_map<std::string, std::string> configs = {\n\t{ \"giveaway\", \"\/giveaway\" },\n\t{ \"twitter\", \"\/twitter\" },\n\t{ \"config\", \"\/config\" },\n\t{ \"submit\", \"\/submitted\" },\n};\n\nstatic const std::string PB = \"https:\/\/ptpb.pw\/\";\n\nbool utils::startsWith(const std::string &str, const std::string &prefix)\n{\n\treturn str.find(prefix) == 0;\n}\n\nbool utils::endsWith(const std::string &str, const std::string &suffix)\n{\n\treturn str.find(suffix) == str.length() - suffix.length();\n}\n\nstd::vector<std::string> &utils::split(const std::string &str,\n\t\tchar delim, std::vector<std::string> &elems)\n{\n\tstd::stringstream ss(str);\n\tstd::string item;\n\twhile (std::getline(ss, item, delim)) {\n\t\tif (!item.empty())\n\t\t\telems.push_back(item);\n\t}\n\treturn elems;\n}\n\nstd::string utils::formatInteger(std::string integer)\n{\n\tint pos = integer.length() - 3;\n\tif (pos < 1)\n\t\treturn integer;\n\twhile (pos > 0) {\n\t\tinteger.insert(pos, \",\");\n\t\tpos -= 3;\n\t}\n\treturn integer;\n}\n\n#ifdef _WIN32\nstatic std::string configdir_win()\n{\n\tchar buf[MAX_PATH_LEN];\n\tint bytes;\n\n\tif (!(bytes = GetModuleFileName(NULL, buf, sizeof(buf)))) {\n\t\tstd::cerr << \"could not get current directory\" << std::endl;\n\t\treturn \"\";\n\t}\n\n\t\/* strip filename from path *\/\n\tstd::string path(buf);\n\tpath = path.substr(0, path.find_last_of(\"\\\\\"));\n\n\treturn path;\n}\n#endif\n\n#ifdef __linux__\nstatic std::string configdir_unix()\n{\n\tchar *h;\n\tif (!(h= getenv(\"HOME\"))) {\n\t\tstd::cerr << \"could not read $HOME\" << std::endl;\n\t\treturn \"\";\n\t}\n\treturn std::string(h) + \"\/.lynxbot\";\n}\n#endif\n\nstd::string utils::configdir()\n{\n#ifdef __linux__\n\treturn configdir_unix();\n#endif\n#ifdef _WIN32\n\treturn configdir_win();\n#endif\n}\n\nstd::string utils::config(const std::string &cfg)\n{\n\tstd::string path = \"\";\n\tif (configs.find(cfg) != configs.end()) {\n\t\tpath += configs[cfg];\n#ifdef _WIN32\n\t\tstd::replace(path.begin(), path.end(), '\/', '\\\\');\n\t\tif (cfg != \"twitter\")\n\t\t\tpath += \".txt\";\n#endif\n\t}\n\treturn path;\n}\n\nbool utils::readJSON(const std::string &filename, Json::Value &val)\n{\n\tJson::Reader reader;\n\tstd::ifstream fileStream(configdir() + \"\/json\/\" + filename,\n\t\tstd::ifstream::binary);\n\n\tif (!reader.parse(fileStream, val)) {\n\t\tstd::cerr << reader.getFormattedErrorMessages() << std::endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid utils::writeJSON(const std::string &filename, Json::Value &val)\n{\n\tstd::ofstream ofile(configdir() + \"\/json\/\" + filename);\n\tJson::StyledWriter sw;\n\tofile << sw.write(val);\n\tofile.close();\n}\n\nbool utils::parseBool(bool &b, const std::string &s, std::string &err)\n{\n\tif (s == \"true\") {\n\t\tb = true;\n\t\treturn true;\n\t}\n\tif (s == \"false\") {\n\t\tb = false;\n\t\treturn true;\n\t}\n\terr = \"invalid setting -- \" + s;\n\treturn false;\n}\n\nbool utils::parseInt(uint32_t &i, const std::string &s, std::string &err)\n{\n\ttry {\n\t\ti = std::stoi(s);\n\t\treturn true;\n\t} catch (std::invalid_argument) {\n\t\terr = \"invalid number -- \" + s;\n\t\treturn false;\n\t}\n}\n\n#define MIN\t 60\n#define HOUR\t 3600\n#define DAY\t 86400\n\n\/* conv_time: convert t to days, hours, minutes and seconds *\/\nstd::string utils::conv_time(time_t t)\n{\n\ttime_t d, h, m;\n\tstd::string out;\n\n\td = t \/ DAY;\n\tt %= DAY;\n\th = t \/ HOUR;\n\tt %= HOUR;\n\tm = t \/ MIN;\n\tt %= MIN;\n\n\tif (d)\n\t\tout += std::to_string(d) + \" day\" + (d == 1 ? \"\" : \"s\") + \", \";\n\tif (h)\n\t\tout += std::to_string(h) + \" hour\" + (h == 1 ? \"\" : \"s\") + \", \";\n\tif (m)\n\t\tout += std::to_string(m) + \" minute\" + (m == 1 ? \"\" : \"s\")\n\t\t\t+ \" and \";\n\tout += std::to_string(t) + \" second\" + (t == 1 ? \"\" : \"s\");\n\treturn out;\n}\n\n\/* getamt: read number from string num into amt *\/\nbool utils::readnum(char *num, int64_t *amt)\n{\n\tsize_t last;\n\tint64_t n, mult;\n\n\tlast = strlen(num) - 1;\n\tmult = 1;\n\tif (num[last] == 'k' || num[last] == 'm' || num[last] == 'b') {\n\t\tswitch (num[last]) {\n\t\tcase 'k':\n\t\t\tmult = 1000;\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\tmult = 1000000;\n\t\t\tbreak;\n\t\tcase 'b':\n\t\t\tmult = 1000000000;\n\t\t\tbreak;\n\t\t}\n\t\tnum[last] = '\\0';\n\t}\n\n\tn = 0;\n\tfor (; *num; ++num) {\n\t\tif (*num < '0' || *num > '9')\n\t\t\treturn false;\n\t\tn = 10 * n + (*num - '0');\n\t}\n\t*amt = n * mult;\n\treturn true;\n}\n\n\/* upload: upload s to ptpb.pw *\/\nstd::string utils::upload(const std::string &s)\n{\n\tcpr::Response resp;\n\tsize_t i;\n\tstd::string url;\n\n\tresp = cpr::Post(cpr::Url(PB), cpr::Body(\"c=\" + tw::pencode(s, \"\\n\")));\n\n\tif ((i = resp.text.find(\"url:\")) == std::string::npos)\n\t\treturn \"failed to upload\";\n\n\turl = resp.text.substr(i + 5);\n\tif ((i = url.find('\\n')) != std::string::npos)\n\t\turl = url.substr(0, i);\n\n\treturn url;\n}\n\n\/* map of html encoded characters *\/\nstatic std::unordered_map<std::string, char> encoded = {\n\t{ \"amp\", '&' },\n\t{ \"gt\", '>' },\n\t{ \"lt\", '<' },\n\t{ \"quot\", '\"' }\n};\n\n\/* decode: decode html encoded string *\/\nstd::string utils::decode(const std::string &s)\n{\n\tsize_t i;\n\tstd::string out, enc;\n\n\tfor (i = 0; i < s.length(); ++i) {\n\t\tif (s[i] == '&') {\n\t\t\tenc.clear();\n\t\t\tfor (++i; s[i] != ';'; ++i)\n\t\t\t\tenc += s[i];\n\t\t\tout += encoded[enc];\n\t\t\tcontinue;\n\t\t}\n\t\tout += s[i] == '\\n' ? ' ' : s[i];\n\t}\n\treturn out;\n}\n\n\/* parse_time: extract time and date from ftime *\/\nstd::string utils::parse_time(const std::string &ftime, bool since)\n{\n\tstd::tm tm, curr;\n\ttime_t t, now;\n\tstd::ostringstream out;\n\tstd::istringstream ss(ftime);\n\n#ifdef __linux__\n\tss.imbue(std::locale(\"en_US.utf-8\"));\n#endif\n#ifdef _WIN32\n\tss.imbue(std::locale(\"en-US\"));\n#endif\n\tss >> std::get_time(&tm, \"%Y-%m-%dT%H:%M:%S\");\n\ttm.tm_isdst = 0;\n\tt = std::mktime(&tm);\n\n\tnow = time(NULL);\n#ifdef __linux__\n\tcurr = *std::gmtime(&now);\n#endif\n#ifdef _WIN32\n\tgmtime_s(&curr, &now);\n#endif\n\tcurr.tm_isdst = 0;\n\tnow = std::mktime(&curr);\n\n\tout << utils::conv_time(now - t);\n\tif (since) {\n\t\tout << \" (since \";\n\t\tout << std::put_time(&tm, \"%H:%M:%S UTC, %d %b %Y\") << \")\";\n\t}\n\n\treturn out.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \"ngraph\/op\/extractimagepatches.hpp\"\n#include \"ngraph\/attribute_visitor.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\n\/\/ ExtractImagePatches v3\n\nconstexpr NodeTypeInfo op::v3::ExtractImagePatches::type_info;\n\nop::v3::ExtractImagePatches::ExtractImagePatches(const Output<Node>& image,\n const Shape& sizes,\n const Strides& strides,\n const Shape& rates,\n const PadType& auto_pad)\n : Op({image})\n , m_patch_sizes(sizes)\n , m_patch_movement_strides(strides)\n , m_patch_selection_rates(rates)\n , m_padding(auto_pad)\n{\n constructor_validate_and_infer_types();\n}\n\nvoid op::v3::ExtractImagePatches::validate_and_infer_types()\n{\n const PartialShape input_Pshape = get_input_partial_shape(0);\n\n NODE_VALIDATION_CHECK(this,\n get_input_element_type(0).is_dynamic() ||\n get_input_element_type(0).is_integral_number(),\n \"input tensor must be an integral number.\");\n NODE_VALIDATION_CHECK(this, input_Pshape.rank() == 4, \"input tensor must be 4D tensor.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_sizes.size() == 2,\n \"Attribute sizes should be in [size_rows, size_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_movement_strides.size() == 2,\n \"Attribute strides should be in [stride_rows, stride_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_movement_strides[0] > 0 && m_patch_movement_strides[1] > 0,\n \"Attribute strides should be strictly greater than zeros in values.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_selection_rates.size() == 2,\n \"Attribute rates should be in [rate_rows, rate_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_selection_rates[0] > 0 && m_patch_selection_rates[1] > 0,\n \"Attribute rates should be strictly greater than zeros in values.\");\n\n NODE_VALIDATION_CHECK(\n this,\n m_padding == PadType::VALID || m_padding == PadType::SAME_LOWER ||\n m_padding == PadType::SAME_UPPER,\n \"Attribute padding should be in either valid or same_lower or same_upper.\");\n\n if (input_Pshape[1].is_dynamic() || input_Pshape[2].is_dynamic() ||\n input_Pshape[3].is_dynamic())\n {\n set_input_is_relevant_to_shape(0);\n auto output_Pshape = PartialShape::dynamic(4);\n set_output_type(0, get_input_element_type(0), output_Pshape);\n }\n else\n {\n int32_t input_depth = input_Pshape[1].get_length();\n int32_t input_rows = input_Pshape[2].get_length();\n int32_t input_cols = input_Pshape[3].get_length();\n int32_t out_rows(0);\n int32_t out_cols(0);\n\n if (input_rows == 0 || input_cols == 0)\n {\n out_rows = 0;\n out_cols = 0;\n }\n else if (m_padding == PadType::VALID)\n {\n out_rows = (((input_rows) -\n static_cast<int32_t>(m_patch_selection_rates[0]) *\n (static_cast<int32_t>(m_patch_sizes[0]) - 1) -\n 1) \/\n m_patch_movement_strides[0]) +\n 1;\n out_cols = (((input_cols) -\n static_cast<int32_t>(m_patch_selection_rates[1]) *\n (static_cast<int32_t>(m_patch_sizes[1]) - 1) -\n 1) \/\n m_patch_movement_strides[1]) +\n 1;\n }\n else\n {\n out_rows = 1 + (((input_rows)-1) \/ m_patch_movement_strides[0]);\n out_cols = 1 + (((input_cols)-1) \/ m_patch_movement_strides[1]);\n }\n\n if (out_rows < 0)\n out_rows = 0;\n if (out_cols < 0)\n out_cols = 0;\n\n ngraph::Dimension::value_type out_depth_cast = static_cast<ngraph::Dimension::value_type>(\n input_depth * m_patch_sizes[0] * m_patch_sizes[1]);\n ngraph::Dimension::value_type out_rows_cast =\n static_cast<ngraph::Dimension::value_type>(out_rows);\n ngraph::Dimension::value_type out_cols_cast =\n static_cast<ngraph::Dimension::value_type>(out_cols);\n\n PartialShape output_Pshape;\n if (input_Pshape[0].is_dynamic())\n {\n output_Pshape =\n PartialShape{input_Pshape[0], out_depth_cast, out_rows_cast, out_cols_cast};\n }\n else\n {\n ngraph::Dimension::value_type input_batch_cast =\n static_cast<ngraph::Dimension::value_type>(input_Pshape[0].get_length());\n output_Pshape =\n PartialShape{input_batch_cast, out_depth_cast, out_rows_cast, out_cols_cast};\n }\n\n if (input_rows == 0 || input_cols == 0)\n {\n output_Pshape = input_Pshape;\n }\n\n set_output_type(0, get_input_element_type(0), output_Pshape);\n }\n}\n\nbool op::v3::ExtractImagePatches::visit_attributes(AttributeVisitor& visitor)\n{\n visitor.on_attribute(\"sizes\", m_patch_sizes);\n visitor.on_attribute(\"strides\", m_patch_movement_strides);\n visitor.on_attribute(\"rates\", m_patch_selection_rates);\n visitor.on_attribute(\"auto_pad\", m_padding);\n return true;\n}\n\nshared_ptr<Node>\n op::v3::ExtractImagePatches::clone_with_new_inputs(const OutputVector& new_args) const\n{\n check_new_args_count(this, new_args);\n return make_shared<op::v3::ExtractImagePatches>(new_args.at(0),\n m_patch_sizes,\n m_patch_movement_strides,\n m_patch_selection_rates,\n m_padding);\n}\n<commit_msg>fixing bug for data input (#4786)<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \"ngraph\/op\/extractimagepatches.hpp\"\n#include \"ngraph\/attribute_visitor.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\n\/\/ ExtractImagePatches v3\n\nconstexpr NodeTypeInfo op::v3::ExtractImagePatches::type_info;\n\nop::v3::ExtractImagePatches::ExtractImagePatches(const Output<Node>& image,\n const Shape& sizes,\n const Strides& strides,\n const Shape& rates,\n const PadType& auto_pad)\n : Op({image})\n , m_patch_sizes(sizes)\n , m_patch_movement_strides(strides)\n , m_patch_selection_rates(rates)\n , m_padding(auto_pad)\n{\n constructor_validate_and_infer_types();\n}\n\nvoid op::v3::ExtractImagePatches::validate_and_infer_types()\n{\n const PartialShape input_Pshape = get_input_partial_shape(0);\n\n NODE_VALIDATION_CHECK(this, input_Pshape.rank() == 4, \"input tensor must be 4D tensor.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_sizes.size() == 2,\n \"Attribute sizes should be in [size_rows, size_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_movement_strides.size() == 2,\n \"Attribute strides should be in [stride_rows, stride_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_movement_strides[0] > 0 && m_patch_movement_strides[1] > 0,\n \"Attribute strides should be strictly greater than zeros in values.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_selection_rates.size() == 2,\n \"Attribute rates should be in [rate_rows, rate_cols] format.\");\n\n NODE_VALIDATION_CHECK(this,\n m_patch_selection_rates[0] > 0 && m_patch_selection_rates[1] > 0,\n \"Attribute rates should be strictly greater than zeros in values.\");\n\n NODE_VALIDATION_CHECK(\n this,\n m_padding == PadType::VALID || m_padding == PadType::SAME_LOWER ||\n m_padding == PadType::SAME_UPPER,\n \"Attribute padding should be in either valid or same_lower or same_upper.\");\n\n if (input_Pshape[1].is_dynamic() || input_Pshape[2].is_dynamic() ||\n input_Pshape[3].is_dynamic())\n {\n set_input_is_relevant_to_shape(0);\n auto output_Pshape = PartialShape::dynamic(4);\n set_output_type(0, get_input_element_type(0), output_Pshape);\n }\n else\n {\n int32_t input_depth = input_Pshape[1].get_length();\n int32_t input_rows = input_Pshape[2].get_length();\n int32_t input_cols = input_Pshape[3].get_length();\n int32_t out_rows(0);\n int32_t out_cols(0);\n\n if (input_rows == 0 || input_cols == 0)\n {\n out_rows = 0;\n out_cols = 0;\n }\n else if (m_padding == PadType::VALID)\n {\n out_rows = (((input_rows) -\n static_cast<int32_t>(m_patch_selection_rates[0]) *\n (static_cast<int32_t>(m_patch_sizes[0]) - 1) -\n 1) \/\n m_patch_movement_strides[0]) +\n 1;\n out_cols = (((input_cols) -\n static_cast<int32_t>(m_patch_selection_rates[1]) *\n (static_cast<int32_t>(m_patch_sizes[1]) - 1) -\n 1) \/\n m_patch_movement_strides[1]) +\n 1;\n }\n else\n {\n out_rows = 1 + (((input_rows)-1) \/ m_patch_movement_strides[0]);\n out_cols = 1 + (((input_cols)-1) \/ m_patch_movement_strides[1]);\n }\n\n if (out_rows < 0)\n out_rows = 0;\n if (out_cols < 0)\n out_cols = 0;\n\n ngraph::Dimension::value_type out_depth_cast = static_cast<ngraph::Dimension::value_type>(\n input_depth * m_patch_sizes[0] * m_patch_sizes[1]);\n ngraph::Dimension::value_type out_rows_cast =\n static_cast<ngraph::Dimension::value_type>(out_rows);\n ngraph::Dimension::value_type out_cols_cast =\n static_cast<ngraph::Dimension::value_type>(out_cols);\n\n PartialShape output_Pshape;\n if (input_Pshape[0].is_dynamic())\n {\n output_Pshape =\n PartialShape{input_Pshape[0], out_depth_cast, out_rows_cast, out_cols_cast};\n }\n else\n {\n ngraph::Dimension::value_type input_batch_cast =\n static_cast<ngraph::Dimension::value_type>(input_Pshape[0].get_length());\n output_Pshape =\n PartialShape{input_batch_cast, out_depth_cast, out_rows_cast, out_cols_cast};\n }\n\n if (input_rows == 0 || input_cols == 0)\n {\n output_Pshape = input_Pshape;\n }\n\n set_output_type(0, get_input_element_type(0), output_Pshape);\n }\n}\n\nbool op::v3::ExtractImagePatches::visit_attributes(AttributeVisitor& visitor)\n{\n visitor.on_attribute(\"sizes\", m_patch_sizes);\n visitor.on_attribute(\"strides\", m_patch_movement_strides);\n visitor.on_attribute(\"rates\", m_patch_selection_rates);\n visitor.on_attribute(\"auto_pad\", m_padding);\n return true;\n}\n\nshared_ptr<Node>\n op::v3::ExtractImagePatches::clone_with_new_inputs(const OutputVector& new_args) const\n{\n check_new_args_count(this, new_args);\n return make_shared<op::v3::ExtractImagePatches>(new_args.at(0),\n m_patch_sizes,\n m_patch_movement_strides,\n m_patch_selection_rates,\n m_padding);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Transport PK\n\n Copyright 2010-201x held jointly by LANS\/LANL, LBNL, and PNNL.\n Amanzi is released under the three-clause BSD License.\n The terms of use and \"as is\" disclaimer for this license are\n provided in the top-level COPYRIGHT file.\n\n Author: Konstantin Lipnikov (lipnikov@lanl.gov)\n*\/\n\n#include <algorithm>\n\n#include \"ReconstructionCellGrad.hh\"\n#include \"OperatorDefs.hh\"\n#include \"transport_ats.hh\"\n\nnamespace Amanzi {\nnamespace Transport {\n\n\/* *******************************************************************\n * Routine takes a parallel overlapping vector C and returns a parallel\n * overlapping vector F(C).\n ****************************************************************** *\/\nvoid Transport_ATS::FunctionalTimeDerivative(double t,\n const Epetra_Vector& component,\n Epetra_Vector& f_component)\n{\n \/\/ distribute vector\n auto component_tmp = Teuchos::rcp(new Epetra_Vector(component));\n component_tmp->Import(component, tcc->importer(\"cell\"), Insert);\n\n Teuchos::ParameterList recon_list = plist_->sublist(\"reconstruction\");\n lifting_->Init(recon_list);\n lifting_->Compute(component_tmp);\n\n \/\/ extract boundary conditions for the current component\n std::vector<int> bc_model(nfaces_wghost, Operators::OPERATOR_BC_NONE);\n std::vector<double> bc_value(nfaces_wghost);\n\n for (int m = 0; m < bcs_.size(); m++) {\n std::vector<int>& tcc_index = bcs_[m]->tcc_index();\n int ncomp = tcc_index.size();\n\n for (int i = 0; i < ncomp; i++) {\n if (current_component_ == tcc_index[i]) {\n for (auto it = bcs_[m]->begin(); it != bcs_[m]->end(); ++it) {\n int f = it->first;\n std::vector<double>& values = it->second;\n\n bc_model[f] = Operators::OPERATOR_BC_DIRICHLET;\n bc_value[f] = values[i];\n }\n }\n }\n }\n\n limiter_->Init(recon_list, flux_);\n limiter_->ApplyLimiter(component_tmp, 0, lifting_, bc_model, bc_value);\n lifting_->data()->ScatterMasterToGhosted(\"cell\");\n\n \/\/ ADVECTIVE FLUXES\n \/\/ We assume that limiters made their job up to round-off errors.\n \/\/ Min-max condition will enforce robustness w.r.t. these errors.\n\n f_component.PutScalar(0.0);\n for (int f = 0; f < nfaces_wghost; f++) { \/\/ loop over master and slave faces\n int c1 = (*upwind_cell_)[f];\n int c2 = (*downwind_cell_)[f];\n\n double u1, u2, umin, umax;\n if (c1 >= 0 && c2 >= 0) {\n u1 = component[c1];\n u2 = component[c2];\n umin = std::min(u1, u2);\n umax = std::max(u1, u2);\n } else if (c1 >= 0) {\n u1 = u2 = umin = umax = component[c1];\n } else if (c2 >= 0) {\n u1 = u2 = umin = umax = component[c2];\n }\n\n double u = fabs((*flux_)[0][f]);\n const AmanziGeometry::Point& xf = mesh_->face_centroid(f);\n\n double upwind_tcc, tcc_flux;\n if (c1 >= 0 && c1 < ncells_owned && c2 >= 0 && c2 < ncells_owned) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n f_component[c2] += tcc_flux;\n\n } else if (c1 >= 0 && c1 < ncells_owned && (c2 >= ncells_owned || c2 < 0)) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n\n } else if (c1 >= 0 && c1 < ncells_owned && (c2 < 0)) {\n upwind_tcc = component[c1];\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n\n } else if (c1 >= ncells_owned && c2 >= 0 && c2 < ncells_owned) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c2] += tcc_flux;\n }\n }\n\n \/\/ process external sources\n if (srcs_.size() != 0) {\n ComputeAddSourceTerms(t, 1., f_component, current_component_, current_component_);\n }\n\n\n for (int c = 0; c < ncells_owned; c++) { \/\/ calculate conservative quantatity\n double vol_phi_ws_den = mesh_->cell_volume(c) * (*phi_)[0][c] * (*ws_current)[0][c] * (*mol_dens_current)[0][c];\n if ((*ws_current)[0][c] < 1e-12)\n vol_phi_ws_den = mesh_->cell_volume(c) * (*phi_)[0][c] * (*ws_next)[0][c] * (*mol_dens_next)[0][c];\n\n if (vol_phi_ws_den > water_tolerance_){\n f_component[c] \/= vol_phi_ws_den;\n }\n }\n\n \/\/ BOUNDARY CONDITIONS for ADVECTION\n for (int m = 0; m < bcs_.size(); m++) {\n std::vector<int>& tcc_index = bcs_[m]->tcc_index();\n int ncomp = tcc_index.size();\n\n for (int i = 0; i < ncomp; i++) {\n if (current_component_ == tcc_index[i]) {\n for (auto it = bcs_[m]->begin(); it != bcs_[m]->end(); ++it) {\n int f = it->first;\n std::vector<double>& values = it->second;\n int c2 = (*downwind_cell_)[f];\n\n if (c2 >= 0 && f < nfaces_owned) {\n double u = fabs((*flux_)[0][f]);\n double vol_phi_ws_den = mesh_->cell_volume(c2) * (*phi_)[0][c2] * (*ws_current)[0][c2] * (*mol_dens_current)[0][c2];\n if ((*ws_current)[0][c2] < 1e-12)\n vol_phi_ws_den = mesh_->cell_volume(c2) * (*phi_)[0][c2] * (*ws_next)[0][c2] * (*mol_dens_next)[0][c2];\n\n double tcc_flux = u * values[i];\n if (vol_phi_ws_den > water_tolerance_ ){\n f_component[c2] += tcc_flux \/ vol_phi_ws_den;\n }\n }\n }\n }\n }\n }\n}\n\n\n\n} \/\/ namespace Transport\n} \/\/ namespace Amanzi\n\n\n<commit_msg>Fixed a parallel bug in transport.<commit_after>\/*\n Transport PK\n\n Copyright 2010-201x held jointly by LANS\/LANL, LBNL, and PNNL.\n Amanzi is released under the three-clause BSD License.\n The terms of use and \"as is\" disclaimer for this license are\n provided in the top-level COPYRIGHT file.\n\n Author: Konstantin Lipnikov (lipnikov@lanl.gov)\n*\/\n\n#include <algorithm>\n\n#include \"ReconstructionCellGrad.hh\"\n#include \"OperatorDefs.hh\"\n#include \"transport_ats.hh\"\n\nnamespace Amanzi {\nnamespace Transport {\n\n\/* *******************************************************************\n * Routine takes a parallel overlapping vector C and returns a parallel\n * overlapping vector F(C).\n ****************************************************************** *\/\nvoid Transport_ATS::FunctionalTimeDerivative(double t,\n const Epetra_Vector& component,\n Epetra_Vector& f_component)\n{\n \/\/ distribute vector\n auto component_tmp = Teuchos::rcp(new Epetra_Vector(component));\n component_tmp->Import(component, tcc->importer(\"cell\"), Insert);\n\n Teuchos::ParameterList recon_list = plist_->sublist(\"reconstruction\");\n lifting_->Init(recon_list);\n lifting_->Compute(component_tmp);\n\n \/\/ extract boundary conditions for the current component\n std::vector<int> bc_model(nfaces_wghost, Operators::OPERATOR_BC_NONE);\n std::vector<double> bc_value(nfaces_wghost);\n\n for (int m = 0; m < bcs_.size(); m++) {\n std::vector<int>& tcc_index = bcs_[m]->tcc_index();\n int ncomp = tcc_index.size();\n\n for (int i = 0; i < ncomp; i++) {\n if (current_component_ == tcc_index[i]) {\n for (auto it = bcs_[m]->begin(); it != bcs_[m]->end(); ++it) {\n int f = it->first;\n std::vector<double>& values = it->second;\n\n bc_model[f] = Operators::OPERATOR_BC_DIRICHLET;\n bc_value[f] = values[i];\n }\n }\n }\n }\n\n limiter_->Init(recon_list, flux_);\n limiter_->ApplyLimiter(component_tmp, 0, lifting_, bc_model, bc_value);\n lifting_->data()->ScatterMasterToGhosted(\"cell\");\n\n \/\/ ADVECTIVE FLUXES\n \/\/ We assume that limiters made their job up to round-off errors.\n \/\/ Min-max condition will enforce robustness w.r.t. these errors.\n\n f_component.PutScalar(0.0);\n for (int f = 0; f < nfaces_wghost; f++) { \/\/ loop over master and slave faces\n int c1 = (*upwind_cell_)[f];\n int c2 = (*downwind_cell_)[f];\n\n double u1, u2, umin, umax;\n if (c1 >= 0 && c2 >= 0) {\n u1 = (*component_tmp)[c1];\n u2 = (*component_tmp)[c2];\n umin = std::min(u1, u2);\n umax = std::max(u1, u2);\n } else if (c1 >= 0) {\n u1 = u2 = umin = umax = (*component_tmp)[c1];\n } else if (c2 >= 0) {\n u1 = u2 = umin = umax = (*component_tmp)[c2];\n }\n\n double u = fabs((*flux_)[0][f]);\n const AmanziGeometry::Point& xf = mesh_->face_centroid(f);\n\n double upwind_tcc, tcc_flux;\n if (c1 >= 0 && c1 < ncells_owned && c2 >= 0 && c2 < ncells_owned) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n f_component[c2] += tcc_flux;\n\n } else if (c1 >= 0 && c1 < ncells_owned && (c2 >= ncells_owned || c2 < 0)) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n\n } else if (c1 >= 0 && c1 < ncells_owned && (c2 < 0)) {\n upwind_tcc = component[c1];\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c1] -= tcc_flux;\n\n } else if (c1 >= ncells_owned && c2 >= 0 && c2 < ncells_owned) {\n upwind_tcc = limiter_->getValue(c1, xf);\n upwind_tcc = std::max(upwind_tcc, umin);\n upwind_tcc = std::min(upwind_tcc, umax);\n\n tcc_flux = u * upwind_tcc;\n f_component[c2] += tcc_flux;\n }\n }\n\n \/\/ process external sources\n if (srcs_.size() != 0) {\n ComputeAddSourceTerms(t, 1., f_component, current_component_, current_component_);\n }\n\n\n for (int c = 0; c < ncells_owned; c++) { \/\/ calculate conservative quantatity\n double vol_phi_ws_den = mesh_->cell_volume(c) * (*phi_)[0][c] * (*ws_current)[0][c] * (*mol_dens_current)[0][c];\n if ((*ws_current)[0][c] < 1e-12)\n vol_phi_ws_den = mesh_->cell_volume(c) * (*phi_)[0][c] * (*ws_next)[0][c] * (*mol_dens_next)[0][c];\n\n if (vol_phi_ws_den > water_tolerance_){\n f_component[c] \/= vol_phi_ws_den;\n }\n }\n\n \/\/ BOUNDARY CONDITIONS for ADVECTION\n for (int m = 0; m < bcs_.size(); m++) {\n std::vector<int>& tcc_index = bcs_[m]->tcc_index();\n int ncomp = tcc_index.size();\n\n for (int i = 0; i < ncomp; i++) {\n if (current_component_ == tcc_index[i]) {\n for (auto it = bcs_[m]->begin(); it != bcs_[m]->end(); ++it) {\n int f = it->first;\n std::vector<double>& values = it->second;\n int c2 = (*downwind_cell_)[f];\n\n if (c2 >= 0 && f < nfaces_owned) {\n double u = fabs((*flux_)[0][f]);\n double vol_phi_ws_den = mesh_->cell_volume(c2) * (*phi_)[0][c2] * (*ws_current)[0][c2] * (*mol_dens_current)[0][c2];\n if ((*ws_current)[0][c2] < 1e-12)\n vol_phi_ws_den = mesh_->cell_volume(c2) * (*phi_)[0][c2] * (*ws_next)[0][c2] * (*mol_dens_next)[0][c2];\n\n double tcc_flux = u * values[i];\n if (vol_phi_ws_den > water_tolerance_ ){\n f_component[c2] += tcc_flux \/ vol_phi_ws_den;\n }\n }\n }\n }\n }\n }\n}\n\n\n\n} \/\/ namespace Transport\n} \/\/ namespace Amanzi\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <mutex>\n\n\/\/ struct once_flag;\n\n\/\/ constexpr once_flag();\n\n#include <mutex>\n\nint main()\n{\n std::once_flag f;\n}\n<commit_msg>noexcept and constexpr applied to <mutex>.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <mutex>\n\n\/\/ struct once_flag;\n\n\/\/ constexpr once_flag() noexcept;\n\n#include <mutex>\n\nint main()\n{\n {\n std::once_flag f;\n }\n#ifndef _LIBCPP_HAS_NO_CONSTEXPR\n {\n constexpr std::once_flag f;\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR\n#define MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR\n#include <mjolnir\/core\/RandomNumberGenerator.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/ForceField.hpp>\n#include <mjolnir\/core\/constants.hpp>\n\nnamespace mjolnir\n{\n\n\/\/ Simple underdamped Langevin integrator.\n\/\/ The implementation is based on the article written by J. D. Honeycutt and\n\/\/ D. Thirumalai (1992) Biopolymers and also the article written by Z. Guo and\n\/\/ D. Thirumalai (1995) Biopolymers. Same algorithm used as default Langevin\n\/\/ integrator in CafeMol that is developed by H. Kenzaki et al., (2011) JCTC.\ntemplate<typename traitsT>\nclass UnderdampedLangevinStepper\n{\n public:\n typedef traitsT traits_type;\n typedef System<traits_type> system_type;\n typedef ForceField<traits_type> forcefield_type;\n typedef RandomNumberGenerator<traits_type> rng_type;\n typedef typename traits_type::boundary_type boundary_type;\n typedef typename traits_type::real_type real_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n\n struct parameter_set\n {\n real_type gamma;\n real_type sqrt_gamma_over_mass;\n coordinate_type accel;\n };\n\n public:\n\n UnderdampedLangevinStepper(const real_type dt,\n std::vector<real_type> gamma, rng_type&& rng)\n : dt_(dt), halfdt_(dt \/ 2), halfdt2_(dt * dt \/ 2),\n rng_(std::move(rng)),\n sqrt_gamma_over_mass_(gamma.size()),\n acceleration_(gamma.size())\n {\n gammas_ = std::move(gamma);\n }\n ~UnderdampedLangevinStepper() = default;\n\n void initialize(system_type& sys, forcefield_type& ff);\n real_type step(const real_type time, system_type& sys, forcefield_type& ff);\n\n real_type delta_t() const noexcept {return dt_;}\n void set_delta_t(const real_type dt) noexcept\n {\n dt_ = dt; halfdt_ = dt \/ 2; halfdt2_ = dt * dt \/ 2;\n }\n\n void update(const system_type& sys)\n {\n if(!sys.has_attribute(\"temperature\"))\n {\n throw std::out_of_range(\"mjolnir::UnderdampedLangevinStepper: \"\n \"Langevin Integrator requires reference temperature, but \"\n \"`temperature` is not found in `system.attribute`.\");\n }\n\n this->temperature_ = sys.attribute(\"temperature\");\n this->noise_coef_ = std::sqrt(2 * physics::constants<real_type>::kB() *\n this->temperature_ \/ dt_);\n }\n\n private:\n\n coordinate_type gen_gaussian_vec(const real_type coef)\n {\n return coordinate_type(this->rng_.gaussian(0.0, coef),\n this->rng_.gaussian(0.0, coef),\n this->rng_.gaussian(0.0, coef));\n }\n\n private:\n real_type dt_;\n real_type halfdt_;\n real_type halfdt2_;\n real_type temperature_;\n real_type noise_coef_;\n rng_type rng_;\n\n std::vector<real_type> gammas_;\n std::vector<real_type> sqrt_gamma_over_mass_;\n std::vector<coordinate_type> acceleration_;\n};\n\ntemplate<typename traitsT>\nvoid UnderdampedLangevinStepper<traitsT>::initialize(\n system_type& system, forcefield_type& ff)\n{\n \/\/ initialize temperature and noise intensity\n this->update(system);\n\n for(std::size_t i=0; i<system.size(); ++i)\n {\n system.force(i) = coordinate_type(0, 0, 0);\n }\n system.largest_displacement() = real_type(0.0);\n ff.calc_force(system);\n\n for(std::size_t i=0; i<system.size(); ++i)\n {\n const auto rmass = system.rmass(i);\n const auto& force = system.force(i);\n\n sqrt_gamma_over_mass_[i] = std::sqrt(gammas_[i] * rmass);\n acceleration_[i] = force * rmass +\n this->gen_gaussian_vec(this->noise_coef_ * sqrt_gamma_over_mass_[i]);\n }\n return;\n}\n\ntemplate<typename traitsT>\ntypename UnderdampedLangevinStepper<traitsT>::real_type\nUnderdampedLangevinStepper<traitsT>::step(\n const real_type time, system_type& sys, forcefield_type& ff)\n{\n real_type largest_disp2 = real_type(0.0);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n auto& p = sys.position(i); \/\/ position of i-th particle\n auto& v = sys.velocity(i); \/\/ ditto\n auto& f = sys.force(i); \/\/ ditto\n const auto& a = this->acceleration_[i];\n auto gamma = this->gammas_[i];\n\n const real_type gamma_dt_over_2 = gamma * halfdt_;\n const real_type one_minus_gamma_dt_over_2 = 1 - gamma_dt_over_2;\n\n const auto displacement =\n (dt_ * one_minus_gamma_dt_over_2) * v + halfdt2_ * a;\n\n p = sys.adjust_position(p + displacement);\n\n v *= one_minus_gamma_dt_over_2 * (one_minus_gamma_dt_over_2 *\n one_minus_gamma_dt_over_2 + gamma_dt_over_2);\n v += (halfdt_ * one_minus_gamma_dt_over_2) * a;\n\n f = coordinate_type(0, 0, 0);\n\n largest_disp2 = std::max(largest_disp2, length_sq(displacement));\n }\n sys.largest_displacement() = std::sqrt(largest_disp2); \/\/ use in neighbor list\n\n \/\/ calc f(t+dt)\n ff.calc_force(sys);\n\n \/\/ calc a(t+dt) and v(t+dt), generate noise\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto rm = sys.rmass(i);\n auto& v = sys.velocity(i);\n const auto& f = sys.force(i);\n auto& a = this->acceleration_[i];\n\n a = f * rm + gen_gaussian_vec(noise_coef_ * sqrt_gamma_over_mass_[i]);\n v += halfdt_ * (1 - gammas_[i] * halfdt_) * a;\n }\n\n return time + dt_;\n}\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR *\/\n<commit_msg>add an accessor to UnderdampedLangevin<commit_after>#ifndef MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR\n#define MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR\n#include <mjolnir\/core\/RandomNumberGenerator.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/ForceField.hpp>\n#include <mjolnir\/core\/constants.hpp>\n\nnamespace mjolnir\n{\n\n\/\/ Simple underdamped Langevin integrator.\n\/\/ The implementation is based on the article written by J. D. Honeycutt and\n\/\/ D. Thirumalai (1992) Biopolymers and also the article written by Z. Guo and\n\/\/ D. Thirumalai (1995) Biopolymers. Same algorithm used as default Langevin\n\/\/ integrator in CafeMol that is developed by H. Kenzaki et al., (2011) JCTC.\ntemplate<typename traitsT>\nclass UnderdampedLangevinStepper\n{\n public:\n typedef traitsT traits_type;\n typedef System<traits_type> system_type;\n typedef ForceField<traits_type> forcefield_type;\n typedef RandomNumberGenerator<traits_type> rng_type;\n typedef typename traits_type::boundary_type boundary_type;\n typedef typename traits_type::real_type real_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n\n struct parameter_set\n {\n real_type gamma;\n real_type sqrt_gamma_over_mass;\n coordinate_type accel;\n };\n\n public:\n\n UnderdampedLangevinStepper(const real_type dt,\n std::vector<real_type> gamma, rng_type&& rng)\n : dt_(dt), halfdt_(dt \/ 2), halfdt2_(dt * dt \/ 2),\n rng_(std::move(rng)),\n sqrt_gamma_over_mass_(gamma.size()),\n acceleration_(gamma.size())\n {\n gammas_ = std::move(gamma);\n }\n ~UnderdampedLangevinStepper() = default;\n\n void initialize(system_type& sys, forcefield_type& ff);\n real_type step(const real_type time, system_type& sys, forcefield_type& ff);\n\n real_type delta_t() const noexcept {return dt_;}\n void set_delta_t(const real_type dt) noexcept\n {\n dt_ = dt; halfdt_ = dt \/ 2; halfdt2_ = dt * dt \/ 2;\n }\n\n void update(const system_type& sys)\n {\n if(!sys.has_attribute(\"temperature\"))\n {\n throw std::out_of_range(\"mjolnir::UnderdampedLangevinStepper: \"\n \"Langevin Integrator requires reference temperature, but \"\n \"`temperature` is not found in `system.attribute`.\");\n }\n\n this->temperature_ = sys.attribute(\"temperature\");\n this->noise_coef_ = std::sqrt(2 * physics::constants<real_type>::kB() *\n this->temperature_ \/ dt_);\n }\n\n std::vector<real_type> const& parameters() const noexcept {return gammas_;}\n\n private:\n\n coordinate_type gen_gaussian_vec(const real_type coef)\n {\n return coordinate_type(this->rng_.gaussian(0.0, coef),\n this->rng_.gaussian(0.0, coef),\n this->rng_.gaussian(0.0, coef));\n }\n\n private:\n real_type dt_;\n real_type halfdt_;\n real_type halfdt2_;\n real_type temperature_;\n real_type noise_coef_;\n rng_type rng_;\n\n std::vector<real_type> gammas_;\n std::vector<real_type> sqrt_gamma_over_mass_;\n std::vector<coordinate_type> acceleration_;\n};\n\ntemplate<typename traitsT>\nvoid UnderdampedLangevinStepper<traitsT>::initialize(\n system_type& system, forcefield_type& ff)\n{\n \/\/ initialize temperature and noise intensity\n this->update(system);\n\n for(std::size_t i=0; i<system.size(); ++i)\n {\n system.force(i) = coordinate_type(0, 0, 0);\n }\n system.largest_displacement() = real_type(0.0);\n ff.calc_force(system);\n\n for(std::size_t i=0; i<system.size(); ++i)\n {\n const auto rmass = system.rmass(i);\n const auto& force = system.force(i);\n\n sqrt_gamma_over_mass_[i] = std::sqrt(gammas_[i] * rmass);\n acceleration_[i] = force * rmass +\n this->gen_gaussian_vec(this->noise_coef_ * sqrt_gamma_over_mass_[i]);\n }\n return;\n}\n\ntemplate<typename traitsT>\ntypename UnderdampedLangevinStepper<traitsT>::real_type\nUnderdampedLangevinStepper<traitsT>::step(\n const real_type time, system_type& sys, forcefield_type& ff)\n{\n real_type largest_disp2 = real_type(0.0);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n auto& p = sys.position(i); \/\/ position of i-th particle\n auto& v = sys.velocity(i); \/\/ ditto\n auto& f = sys.force(i); \/\/ ditto\n const auto& a = this->acceleration_[i];\n auto gamma = this->gammas_[i];\n\n const real_type gamma_dt_over_2 = gamma * halfdt_;\n const real_type one_minus_gamma_dt_over_2 = 1 - gamma_dt_over_2;\n\n const auto displacement =\n (dt_ * one_minus_gamma_dt_over_2) * v + halfdt2_ * a;\n\n p = sys.adjust_position(p + displacement);\n\n v *= one_minus_gamma_dt_over_2 * (one_minus_gamma_dt_over_2 *\n one_minus_gamma_dt_over_2 + gamma_dt_over_2);\n v += (halfdt_ * one_minus_gamma_dt_over_2) * a;\n\n f = coordinate_type(0, 0, 0);\n\n largest_disp2 = std::max(largest_disp2, length_sq(displacement));\n }\n sys.largest_displacement() = std::sqrt(largest_disp2); \/\/ use in neighbor list\n\n \/\/ calc f(t+dt)\n ff.calc_force(sys);\n\n \/\/ calc a(t+dt) and v(t+dt), generate noise\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto rm = sys.rmass(i);\n auto& v = sys.velocity(i);\n const auto& f = sys.force(i);\n auto& a = this->acceleration_[i];\n\n a = f * rm + gen_gaussian_vec(noise_coef_ * sqrt_gamma_over_mass_[i]);\n v += halfdt_ * (1 - gammas_[i] * halfdt_) * a;\n }\n\n return time + dt_;\n}\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ packet_manager_test.cpp\n\/\/\n\/\/ Identification: test\/wire\/packet_manager_test.cpp\n\/\/\n\/\/ Copyright (c) 2016-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/harness.h\"\n#include \"gtest\/gtest.h\"\n#include \"common\/logger.h\"\n#include \"wire\/libevent_server.h\"\n#include <pqxx\/pqxx> \/* libpqxx is used to instantiate C++ client *\/\n\n#define NUM_THREADS 1\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Packet Manager Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass PacketManagerTests : public PelotonTest {};\n\nstatic void *LaunchServer(peloton::wire::LibeventServer libeventserver) {\n try {\n libeventserver.StartServer();\n } catch (peloton::ConnectionException exception) {\n LOG_INFO(\"[LaunchServer] exception in thread\");\n }\n return NULL;\n}\n\n\/**\n * Simple select query test\n *\/\nstatic void *SimpleQueryTest(void *) {\n try {\n pqxx::connection C(\n \"host=127.0.0.1 port=15721 user=postgres sslmode=disable\");\n LOG_INFO(\"[SimpleQueryTest] Connected to %s\", C.dbname());\n pqxx::work W(C);\n\n peloton::wire::LibeventSocket *conn =\n peloton::wire::LibeventServer::GetConn(\n peloton::wire::LibeventServer::recent_connfd);\n\n EXPECT_EQ(conn->pkt_manager.is_started, true);\n EXPECT_EQ(conn->state, peloton::wire::CONN_READ);\n \/\/ create table and insert some data\n W.exec(\"DROP TABLE IF EXISTS employee;\");\n W.exec(\"CREATE TABLE employee(id INT, name VARCHAR(100));\");\n W.exec(\"INSERT INTO employee VALUES (1, 'Han LI');\");\n W.exec(\"INSERT INTO employee VALUES (2, 'Shaokun ZOU');\");\n W.exec(\"INSERT INTO employee VALUES (3, 'Yilei CHU');\");\n\n pqxx::result R = W.exec(\"SELECT name FROM employee where id=1;\");\n\n EXPECT_EQ(R.size(), 1);\n LOG_INFO(\"[SimpleQueryTest] Found %lu employees\", R.size());\n W.commit();\n } catch (const std::exception &e) {\n LOG_INFO(\"[SimpleQueryTest] Exception occurred\");\n }\n\n LOG_INFO(\"[SimpleQueryTest] Client has closed\");\n return NULL;\n}\n\n\/**\n * named prepare statement without parameters\n * TODO: add prepare's parameters when parser team fix the bug\n *\/\n\nstatic void *PrepareStatementTest(void *) {\n try {\n pqxx::connection C(\n \"host=127.0.0.1 port=15721 user=postgres sslmode=disable\");\n LOG_INFO(\"[PrepareStatementTest] Connected to %s\", C.dbname());\n pqxx::work W(C);\n \n peloton::wire::LibeventSocket *conn =\n peloton::wire::LibeventServer::GetConn(\n peloton::wire::LibeventServer::recent_connfd);\n\n \/\/ create table and insert some data\n W.exec(\"DROP TABLE IF EXISTS employee;\");\n W.exec(\"CREATE TABLE employee(id INT, name VARCHAR(100));\");\n W.exec(\"INSERT INTO employee VALUES (1, 'Han LI');\");\n W.exec(\"INSERT INTO employee VALUES (2, 'Shaokun ZOU');\");\n W.exec(\"INSERT INTO employee VALUES (3, 'Yilei CHU');\");\n\n \/\/ test prepare statement\n C.prepare(\"searchstmt\",\"SELECT name FROM employee WHERE id=1;\");\n \/\/ invocation as in variable binding\n pqxx::result R = W.prepared(\"searchstmt\").exec();\n W.commit();\n\n \/\/ test prepared statement already in statement cache\n\/\/ LOG_INFO(\"[Prepare statement cache] %d\",conn->pkt_manager.ExistCachedStatement(\"searchstmt\"));\n EXPECT_TRUE(conn->pkt_manager.ExistCachedStatement(\"searchstmt\"));\n\n LOG_INFO(\"Prepare statement search result:%lu\",R.size());\n } catch (const std::exception &e) {\n LOG_INFO(\"[PrepareStatementTest] Exception occurred\");\n }\n\n LOG_INFO(\"[PrepareStatementTest] Client has closed\");\n return NULL;\n}\n\n\/**\n * Use std::thread to initiate peloton server and pqxx client in separate\n * threads\n * Simple query test to guarantee both sides run correctly\n * Callback method to close server after client finishes\n *\/\nTEST_F(PacketManagerTests, SimpleQueryTest) {\n peloton::PelotonInit::Initialize();\n LOG_INFO(\"Server initialized\");\n peloton::wire::LibeventServer libeventserver;\n std::thread serverThread(LaunchServer, libeventserver);\n while (!libeventserver.is_started) {\n sleep(1);\n }\n\n \/* server & client running correctly *\/\n SimpleQueryTest(NULL);\n\n \/* TODO: monitor packet_manager's status when receiving prepare statement from\n * client *\/\n \/\/ PrepareStatementTest(NULL);\n\n libeventserver.CloseServer();\n serverThread.join();\n LOG_INFO(\"Thread has joined\");\n peloton::PelotonInit::Shutdown();\n LOG_INFO(\"Peloton has shut down\\n\");\n}\n\nTEST_F(PacketManagerTests, PrepareStatementTest) {\n peloton::PelotonInit::Initialize();\n LOG_INFO(\"Server initialized\");\n peloton::wire::LibeventServer libeventserver;\n std::thread serverThread(LaunchServer, libeventserver);\n while (!libeventserver.is_started) {\n sleep(1);\n }\n\n PrepareStatementTest(NULL);\n\n libeventserver.CloseServer();\n serverThread.join();\n LOG_INFO(\"Thread has joined\");\n peloton::PelotonInit::Shutdown();\n LOG_INFO(\"Peloton has shut down\\n\");\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n<commit_msg>add rollback test<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ packet_manager_test.cpp\n\/\/\n\/\/ Identification: test\/wire\/packet_manager_test.cpp\n\/\/\n\/\/ Copyright (c) 2016-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/harness.h\"\n#include \"gtest\/gtest.h\"\n#include \"common\/logger.h\"\n#include \"wire\/libevent_server.h\"\n#include <pqxx\/pqxx> \/* libpqxx is used to instantiate C++ client *\/\n\n#define NUM_THREADS 1\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Packet Manager Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass PacketManagerTests : public PelotonTest {};\n\nstatic void *LaunchServer(peloton::wire::LibeventServer libeventserver) {\n try {\n libeventserver.StartServer();\n } catch (peloton::ConnectionException exception) {\n LOG_INFO(\"[LaunchServer] exception in thread\");\n }\n return NULL;\n}\n\n\/**\n * Simple select query test\n *\/\nstatic void *SimpleQueryTest(void *) {\n try {\n pqxx::connection C(\n \"host=127.0.0.1 port=15721 user=postgres sslmode=disable\");\n LOG_INFO(\"[SimpleQueryTest] Connected to %s\", C.dbname());\n pqxx::work W(C);\n\n peloton::wire::LibeventSocket *conn =\n peloton::wire::LibeventServer::GetConn(\n peloton::wire::LibeventServer::recent_connfd);\n\n EXPECT_EQ(conn->pkt_manager.is_started, true);\n EXPECT_EQ(conn->state, peloton::wire::CONN_READ);\n \/\/ create table and insert some data\n W.exec(\"DROP TABLE IF EXISTS employee;\");\n W.exec(\"CREATE TABLE employee(id INT, name VARCHAR(100));\");\n W.exec(\"INSERT INTO employee VALUES (1, 'Han LI');\");\n W.exec(\"INSERT INTO employee VALUES (2, 'Shaokun ZOU');\");\n W.exec(\"INSERT INTO employee VALUES (3, 'Yilei CHU');\");\n\n pqxx::result R = W.exec(\"SELECT name FROM employee where id=1;\");\n\n EXPECT_EQ(R.size(), 1);\n LOG_INFO(\"[SimpleQueryTest] Found %lu employees\", R.size());\n W.commit();\n } catch (const std::exception &e) {\n LOG_INFO(\"[SimpleQueryTest] Exception occurred\");\n }\n\n LOG_INFO(\"[SimpleQueryTest] Client has closed\");\n return NULL;\n}\n\n\/**\n * named prepare statement without parameters\n * TODO: add prepare's parameters when parser team fix the bug\n *\/\n\nstatic void *PrepareStatementTest(void *) {\n try {\n pqxx::connection C(\n \"host=127.0.0.1 port=15721 user=postgres sslmode=disable\");\n LOG_INFO(\"[PrepareStatementTest] Connected to %s\", C.dbname());\n pqxx::work W(C);\n \n peloton::wire::LibeventSocket *conn =\n peloton::wire::LibeventServer::GetConn(\n peloton::wire::LibeventServer::recent_connfd);\n\n \/\/ create table and insert some data\n W.exec(\"DROP TABLE IF EXISTS employee;\");\n W.exec(\"CREATE TABLE employee(id INT, name VARCHAR(100));\");\n W.exec(\"INSERT INTO employee VALUES (1, 'Han LI');\");\n W.exec(\"INSERT INTO employee VALUES (2, 'Shaokun ZOU');\");\n W.exec(\"INSERT INTO employee VALUES (3, 'Yilei CHU');\");\n\n \/\/ test prepare statement\n C.prepare(\"searchstmt\",\"SELECT name FROM employee WHERE id=1;\");\n \/\/ invocation as in variable binding\n pqxx::result R = W.prepared(\"searchstmt\").exec();\n W.commit();\n\n \/\/ test prepared statement already in statement cache\n\/\/ LOG_INFO(\"[Prepare statement cache] %d\",conn->pkt_manager.ExistCachedStatement(\"searchstmt\"));\n EXPECT_TRUE(conn->pkt_manager.ExistCachedStatement(\"searchstmt\"));\n\n LOG_INFO(\"Prepare statement search result:%lu\",R.size());\n } catch (const std::exception &e) {\n LOG_INFO(\"[PrepareStatementTest] Exception occurred\");\n }\n\n LOG_INFO(\"[PrepareStatementTest] Client has closed\");\n return NULL;\n}\n\n\/**\n * rollback test\n *\/\nstatic void *RollbackTest(void *) {\n try {\n pqxx::connection C(\n \"host=127.0.0.1 port=15721 user=postgres sslmode=disable\");\n LOG_INFO(\"[RollbackTest] Connected to %s\", C.dbname());\n pqxx::work W(C);\n\n peloton::wire::LibeventSocket *conn =\n peloton::wire::LibeventServer::GetConn(\n peloton::wire::LibeventServer::recent_connfd);\n\n EXPECT_EQ(conn->pkt_manager.is_started, true);\n EXPECT_EQ(conn->state, peloton::wire::CONN_READ);\n \/\/ create table and insert some data\n W.exec(\"DROP TABLE IF EXISTS employee;\");\n W.exec(\"CREATE TABLE employee(id INT, name VARCHAR(100));\");\n w.abort();\n\n \/\/ W.exec(\"INSERT INTO employee VALUES (1, 'Han LI');\");\n \/\/ W.exec(\"INSERT INTO employee VALUES (2, 'Shaokun ZOU');\");\n \/\/ W.exec(\"INSERT INTO employee VALUES (3, 'Yilei CHU');\");\n\n pqxx::result R = W.exec(\"SELECT name FROM employee where id=1;\");\n\n EXPECT_EQ(R.size(), 1);\n LOG_INFO(\"[RollbackTest] Found %lu employees\", R.size());\n W.commit();\n } catch (const std::exception &e) {\n LOG_INFO(\"[RollbackTest] Exception occurred\");\n }\n\n LOG_INFO(\"[RollbackTest] Client has closed\");\n return NULL;\n}\n\n\n\/**\n * Use std::thread to initiate peloton server and pqxx client in separate\n * threads\n * Simple query test to guarantee both sides run correctly\n * Callback method to close server after client finishes\n *\/\nTEST_F(PacketManagerTests, SimpleQueryTest) {\n peloton::PelotonInit::Initialize();\n LOG_INFO(\"Server initialized\");\n peloton::wire::LibeventServer libeventserver;\n std::thread serverThread(LaunchServer, libeventserver);\n while (!libeventserver.is_started) {\n sleep(1);\n }\n\n \/* server & client running correctly *\/\n SimpleQueryTest(NULL);\n\n \/* TODO: monitor packet_manager's status when receiving prepare statement from\n * client *\/\n \/\/ PrepareStatementTest(NULL);\n\n libeventserver.CloseServer();\n serverThread.join();\n LOG_INFO(\"Thread has joined\");\n peloton::PelotonInit::Shutdown();\n LOG_INFO(\"Peloton has shut down\\n\");\n}\n\nTEST_F(PacketManagerTests, PrepareStatementTest) {\n peloton::PelotonInit::Initialize();\n LOG_INFO(\"Server initialized\");\n peloton::wire::LibeventServer libeventserver;\n std::thread serverThread(LaunchServer, libeventserver);\n while (!libeventserver.is_started) {\n sleep(1);\n }\n\n PrepareStatementTest(NULL);\n\n libeventserver.CloseServer();\n serverThread.join();\n LOG_INFO(\"Thread has joined\");\n peloton::PelotonInit::Shutdown();\n LOG_INFO(\"Peloton has shut down\\n\");\n}\n\n\nTEST_F(PacketManagerTests, RollbackTest) {\n peloton::PelotonInit::Initialize();\n LOG_INFO(\"Server initialized\");\n peloton::wire::LibeventServer libeventserver;\n std::thread serverThread(LaunchServer, libeventserver);\n while (!libeventserver.is_started) {\n sleep(1);\n }\n\n RollbackTest(NULL);\n\n libeventserver.CloseServer();\n serverThread.join();\n LOG_INFO(\"Thread has joined\");\n peloton::PelotonInit::Shutdown();\n LOG_INFO(\"Peloton has shut down\\n\");\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file VM.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"VM.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\n\nvoid VM::reset(u256 _gas)\n{\n\tm_gas = _gas;\n\tm_curPC = 0;\n\tm_jumpDests.reset();\n}\n<commit_msg>Build fix.<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file VM.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"VM.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\n\nvoid VM::reset(u256 _gas)\n{\n\tm_gas = _gas;\n\tm_curPC = 0;\n\tm_jumpDests.clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/base\/io\/ivfsequencevolumereader.h>\n#include <modules\/base\/io\/ivfvolumewriter.h>\n#include <inviwo\/core\/util\/filesystem.h>\n\nnamespace inviwo {\nIvfSequenceVolumeReader::IvfSequenceVolumeReader() {\n addExtension({\"ivfs\", \"Sequence of Inviwo ivf volumes\"});\n}\n\nstd::shared_ptr<VolumeSequence> IvfSequenceVolumeReader::readData(const std::string &filePath) {\n std::string fileName = filePath;\n if (!filesystem::fileExists(fileName)) {\n std::string newPath = filesystem::addBasePath(fileName);\n\n if (filesystem::fileExists(newPath)) {\n fileName = newPath;\n } else {\n throw DataReaderException(\"Error could not find input file: \" + fileName, IvwContext);\n }\n }\n\n auto volumes = std::make_shared<VolumeSequence>();\n\n auto dir = filesystem::getFileDirectory(fileName);\n\n std::vector<std::string> filenames;\n Deserializer d(fileName);\n d.deserialize(\"volumes\", filenames , \"volume\");\n for (auto filename : filenames) {\n auto abs = filesystem::cleanupPath( dir + \"\/\" + filename);\n volumes->push_back(reader_.readData(abs));\n }\n\n return volumes;\n}\n\n} \/\/ namespace inviwo\n<commit_msg>Base: Added missing include<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/base\/io\/ivfsequencevolumereader.h>\n#include <modules\/base\/io\/ivfvolumewriter.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/io\/datareaderexception.h>\n\nnamespace inviwo {\nIvfSequenceVolumeReader::IvfSequenceVolumeReader() {\n addExtension({\"ivfs\", \"Sequence of Inviwo ivf volumes\"});\n}\n\nstd::shared_ptr<VolumeSequence> IvfSequenceVolumeReader::readData(const std::string &filePath) {\n std::string fileName = filePath;\n if (!filesystem::fileExists(fileName)) {\n std::string newPath = filesystem::addBasePath(fileName);\n\n if (filesystem::fileExists(newPath)) {\n fileName = newPath;\n } else {\n throw DataReaderException(\"Error could not find input file: \" + fileName, IvwContext);\n }\n }\n\n auto volumes = std::make_shared<VolumeSequence>();\n\n auto dir = filesystem::getFileDirectory(fileName);\n\n std::vector<std::string> filenames;\n Deserializer d(fileName);\n d.deserialize(\"volumes\", filenames , \"volume\");\n for (auto filename : filenames) {\n auto abs = filesystem::cleanupPath( dir + \"\/\" + filename);\n volumes->push_back(reader_.readData(abs));\n }\n\n return volumes;\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2011 The Avalon Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by the Apache License 2.0\n\/\/ that can be found in the LICENSE file.\n\/\/\n\/\/ Main loop for helmsman: open client sockets to wind and imu, server\n\/\/ socket for helsman clients (e.g. the skipper and sysmon) and shovel\n\/\/ data between all open file descriptors and the main controller.\n\/\/\n\n#include <errno.h>\n#include <math.h>\n#include <signal.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"proto\/rudder.h\"\n#include \"proto\/wind.h\"\n#include \"proto\/imu.h\"\n#include \"proto\/helmsman.h\"\n#include \"proto\/remote.h\"\n#include \"proto\/skipper_input.h\"\n\n#include \"common\/convert.h\"\n#include \"common\/unknown.h\"\n#include \"sampling_period.h\"\n#include \"ship_control.h\"\n\nextern int debug;\n\n\/\/ -----------------------------------------------------------------------------\nnamespace {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Together with getopt in main, this is our minimalistic UI\n\/\/ -----------------------------------------------------------------------------\n\n\/\/const char* version = \"$Id: $\";\nconst char* argv0;\nint verbose = 0;\n\nvoid crash(const char* fmt, ...) {\n va_list ap;\n char buf[1000];\n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n if (debug)\n fprintf(stderr, \"%s:%s%s%s\\n\", argv0, buf,\n (errno) ? \": \" : \"\",\n (errno) ? strerror(errno):\"\" );\n else\n syslog(LOG_CRIT, \"%s%s%s\\n\", buf,\n (errno) ? \": \" : \"\",\n (errno) ? strerror(errno):\"\" );\n exit(1);\n va_end(ap);\n return;\n}\n\nstatic void fault(int i) { crash(\"fault\"); }\n\nvoid usage(void) {\n fprintf(stderr,\n \"usage: [plug \/path\/to\/bus] %s [options]\\n\"\n \"options:\\n\"\n \"\\t-d debug (don't go daemon, don't syslog)\\n\"\n , argv0);\n exit(2);\n}\n\n\nstatic void set_fd(fd_set* s, int* maxfd, FILE* f) {\n int fd = fileno(f);\n FD_SET(fd, s);\n if (*maxfd < fd) *maxfd = fd;\n}\n\nuint64_t now_ms() {\n timeval tv;\n if (gettimeofday(&tv, NULL) < 0) crash(\"gettimeofday\");\n uint64_t ms1 = tv.tv_sec; ms1 *= 1000;\n uint64_t ms2 = tv.tv_usec; ms2 \/= 1000;\n return ms1 + ms2;\n}\n\nuint64_t now_micros() {\n timeval tv;\n if (gettimeofday(&tv, NULL) < 0) crash(\"gettimeofday\");\n return tv.tv_sec * 1000000LL + tv.tv_usec;\n}\n\nuint64_t nanos_to_wait(uint64_t last_controller_call_micros) {\n uint64_t now = now_micros();\n const uint64_t period = 100000LL;\n uint64_t timeout = last_controller_call_micros + period > now ?\n last_controller_call_micros + period - now :\n 0;\n return 1000 * timeout;\n}\n\nvoid HandleRemoteControl(RemoteProto remote, int* control_mode) {\n if (remote.command != *control_mode)\n fprintf(stderr, \"Helmsman switched to control mode %d\\n\", remote.command);\n switch (remote.command) {\n case kNormalControlMode:\n *control_mode = remote.command;\n ShipControl::Normal();\n break;\n case kDockingControlMode:\n *control_mode = remote.command;\n ShipControl::Docking();\n break;\n case kBrakeControlMode:\n case kPowerShutdownMode:\n *control_mode = remote.command;\n ShipControl::Brake();\n break;\n case kOverrideSkipperMode:\n *control_mode = remote.command;\n ShipControl::Normal();\n break;\n default:\n fprintf(stderr, \"Illegal remote control\");\n }\n}\n\n} \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Main.\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, char* argv[]) {\n\n int ch;\n argv0 = strrchr(argv[0], '\/');\n if (argv0) ++argv0; else argv0 = argv[0];\n\n while ((ch = getopt(argc, argv, \"dhv\")) != -1){\n switch (ch) {\n case 'd': ++debug; break;\n case 'v': ++verbose; break;\n case 'h':\n default:\n usage();\n }\n }\n\n argv += optind;\n argc -= optind;\n\n if (argc != 0) usage();\n\n setlinebuf(stdout);\n\n if (!debug) openlog(argv0, LOG_PERROR, LOG_LOCAL0);\n\n if (signal(SIGBUS, fault) == SIG_ERR) crash(\"signal(SIGBUS)\");\n if (signal(SIGSEGV, fault) == SIG_ERR) crash(\"signal(SIGSEGV)\");\n if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) crash(\"signal\");\n\n if (debug) {\n fprintf(stderr, \"Helmsman started\\n\");\n } else {\n daemon(0,0);\n char* path_to_pidfile = NULL;\n asprintf(&path_to_pidfile, \"\/var\/run\/%s.pid\", argv0);\n FILE* pidfile = fopen(path_to_pidfile, \"w\");\n if(!pidfile) crash(\"writing pidfile (%s)\", path_to_pidfile);\n fprintf(pidfile, \"%d\\n\", getpid());\n fclose(pidfile);\n free(path_to_pidfile);\n\n syslog(LOG_INFO, \"Helmsman started\");\n }\n\n ControllerInput ctrl_in;\n\n int nn = 0;\n\n struct WindProto wind = INIT_WINDPROTO;\n struct RudderProto sts = INIT_RUDDERPROTO;\n struct IMUProto imu = INIT_IMUPROTO;\n struct HelmsmanCtlProto ctl = INIT_HELMSMANCTLPROTO;\n struct RemoteProto remote = INIT_REMOTEPROTO;\n ctrl_in.alpha_star_rad = Deg2Rad(225); \/\/ Going SouthWest is a good guess (and breaks up a deadlock)\n int control_mode = kNormalControlMode;\n int loops = 0;\n uint64_t last_run_micros = 0;\n\n\n while (!feof(stdin)) {\n\n if (ferror(stdin)) clearerr(stdin);\n\n struct timespec timeout = { 0, nanos_to_wait(last_run_micros) }; \/\/ Run ship cotroller exactly once every 100ms\n fd_set rfds;\n int max_fd = -1;\n FD_ZERO(&rfds);\n set_fd(&rfds, &max_fd, stdin);\n\n sigset_t empty_mask;\n sigemptyset(&empty_mask);\n int r = pselect(max_fd + 1, &rfds, NULL, NULL, &timeout, &empty_mask);\n if (r == -1 && errno != EINTR) crash(\"pselect\");\n\n if (debug>2) fprintf(stderr, \"Woke up %d\\n\", r);\n\n if (FD_ISSET(fileno(stdin), &rfds)) {\n char line[1024];\n if (!fgets(line, sizeof line, stdin))\n crash(\"Error reading stdin\");\n\n if (sscanf(line, IFMT_WINDPROTO(&wind, &nn)) > 0) {\n ctrl_in.wind.Reset();\n ctrl_in.wind.alpha_deg = SymmetricDeg(NormalizeDeg(wind.angle_deg));\n ctrl_in.wind.mag_kn = MeterPerSecondToKnots(wind.speed_m_s);\n\n } else if (sscanf(line, IFMT_IMUPROTO(&imu, &nn)) > 0) {\n ctrl_in.imu.Reset();\n ctrl_in.imu.temperature_c = imu.temp_c;\n\n ctrl_in.imu.acceleration.x_m_s2 = imu.acc_x_m_s2;\n ctrl_in.imu.acceleration.y_m_s2 = imu.acc_y_m_s2;\n ctrl_in.imu.acceleration.z_m_s2 = imu.acc_z_m_s2;\n\n ctrl_in.imu.gyro.omega_x_rad_s = imu.gyr_x_rad_s;\n ctrl_in.imu.gyro.omega_y_rad_s = imu.gyr_y_rad_s;\n ctrl_in.imu.gyro.omega_z_rad_s = imu.gyr_z_rad_s;\n\n ctrl_in.imu.attitude.phi_x_rad = Deg2Rad(imu.roll_deg);\n ctrl_in.imu.attitude.phi_y_rad = Deg2Rad(imu.pitch_deg);\n ctrl_in.imu.attitude.phi_z_rad = SymmetricRad(NormalizeRad(Deg2Rad(imu.yaw_deg)));\n\n ctrl_in.imu.position.latitude_deg = imu.lat_deg;\n ctrl_in.imu.position.longitude_deg = imu.lng_deg;\n ctrl_in.imu.position.altitude_m = imu.alt_m;\n\n ctrl_in.imu.velocity.x_m_s = imu.vel_x_m_s;\n ctrl_in.imu.velocity.y_m_s = imu.vel_y_m_s;\n ctrl_in.imu.velocity.z_m_s = imu.vel_z_m_s;\n\n ctrl_in.imu.speed_m_s = sqrt(imu.vel_x_m_s * imu.vel_x_m_s +\n imu.vel_y_m_s * imu.vel_y_m_s);\n\n } else if (sscanf(line, IFMT_RUDDERPROTO_STS(&sts, &nn)) > 0) {\n ctrl_in.drives.gamma_rudder_left_rad = Deg2Rad(sts.rudder_l_deg);\n ctrl_in.drives.gamma_rudder_right_rad = Deg2Rad(sts.rudder_r_deg);\n ctrl_in.drives.gamma_sail_rad = Deg2Rad(sts.sail_deg);\n ctrl_in.drives.homed_rudder_left = !isnan(sts.rudder_l_deg);\n ctrl_in.drives.homed_rudder_right = !isnan(sts.rudder_r_deg);\n ctrl_in.drives.homed_sail = !isnan(sts.sail_deg);\n\n } else if (sscanf(line, IFMT_HELMSMANCTLPROTO(&ctl, &nn)) > 0) {\n if (control_mode != kOverrideSkipperMode &&\n !isnan(ctl.alpha_star_deg))\n ctrl_in.alpha_star_rad = Deg2Rad(ctl.alpha_star_deg);\n } else if (sscanf(line, IFMT_REMOTEPROTO(&remote, &nn)) > 0) {\n HandleRemoteControl(remote, &control_mode);\n if (control_mode == kOverrideSkipperMode)\n ctrl_in.alpha_star_rad = Deg2Rad(remote.alpha_star_deg);\n }\n }\n\n if (nanos_to_wait(last_run_micros) > 100)\n continue;\n ControllerOutput ctrl_out;\n last_run_micros = now_micros();\n ShipControl::Run(ctrl_in, &ctrl_out);\n struct RudderProto ctl = {\n now_ms(),\n Rad2Deg(ctrl_out.drives_reference.gamma_rudder_star_left_rad),\n Rad2Deg(ctrl_out.drives_reference.gamma_rudder_star_right_rad),\n Rad2Deg(ctrl_out.drives_reference.gamma_sail_star_rad) };\n printf(OFMT_RUDDERPROTO_CTL(ctl, &nn));\n\n if (loops == 0) {\n struct SkipperInputProto to_skipper = {\n now_ms(),\n ctrl_out.skipper_input.longitude_deg,\n ctrl_out.skipper_input.latitude_deg,\n ctrl_out.skipper_input.angle_true_deg,\n ctrl_out.skipper_input.mag_true_kn\n };\n printf(OFMT_SKIPPER_INPUTPROTO(to_skipper, &nn));\n }\n \/*\n if (loops == 5) {\n struct HelmsmanStatus = {\n Rad2Deg(ctrl_in.alpha_star_rad)\n };\n printf(OFMT_HELMSMAN_STATUSPROTO);\n *\/\n loops = loops == 9 ? 0 : loops+1;\n\n\n } \/\/ for ever\n\n crash(\"Main loop exit\");\n\n return 0;\n}\n\n<commit_msg>component: Speed is x-component of the ships speed vector.<commit_after>\/\/ Copyright 2011 The Avalon Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by the Apache License 2.0\n\/\/ that can be found in the LICENSE file.\n\/\/\n\/\/ Main loop for helmsman: open client sockets to wind and imu, server\n\/\/ socket for helsman clients (e.g. the skipper and sysmon) and shovel\n\/\/ data between all open file descriptors and the main controller.\n\/\/\n\n#include <errno.h>\n#include <math.h>\n#include <signal.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <syslog.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"proto\/rudder.h\"\n#include \"proto\/wind.h\"\n#include \"proto\/imu.h\"\n#include \"proto\/helmsman.h\"\n#include \"proto\/remote.h\"\n#include \"proto\/skipper_input.h\"\n\n#include \"common\/convert.h\"\n#include \"common\/unknown.h\"\n#include \"sampling_period.h\"\n#include \"ship_control.h\"\n\nextern int debug;\n\n\/\/ -----------------------------------------------------------------------------\nnamespace {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Together with getopt in main, this is our minimalistic UI\n\/\/ -----------------------------------------------------------------------------\n\n\/\/const char* version = \"$Id: $\";\nconst char* argv0;\nint verbose = 0;\n\nvoid crash(const char* fmt, ...) {\n va_list ap;\n char buf[1000];\n va_start(ap, fmt);\n vsnprintf(buf, sizeof(buf), fmt, ap);\n if (debug)\n fprintf(stderr, \"%s:%s%s%s\\n\", argv0, buf,\n (errno) ? \": \" : \"\",\n (errno) ? strerror(errno):\"\" );\n else\n syslog(LOG_CRIT, \"%s%s%s\\n\", buf,\n (errno) ? \": \" : \"\",\n (errno) ? strerror(errno):\"\" );\n exit(1);\n va_end(ap);\n return;\n}\n\nstatic void fault(int i) { crash(\"fault\"); }\n\nvoid usage(void) {\n fprintf(stderr,\n \"usage: [plug \/path\/to\/bus] %s [options]\\n\"\n \"options:\\n\"\n \"\\t-d debug (don't go daemon, don't syslog)\\n\"\n , argv0);\n exit(2);\n}\n\n\nstatic void set_fd(fd_set* s, int* maxfd, FILE* f) {\n int fd = fileno(f);\n FD_SET(fd, s);\n if (*maxfd < fd) *maxfd = fd;\n}\n\nuint64_t now_ms() {\n timeval tv;\n if (gettimeofday(&tv, NULL) < 0) crash(\"gettimeofday\");\n uint64_t ms1 = tv.tv_sec; ms1 *= 1000;\n uint64_t ms2 = tv.tv_usec; ms2 \/= 1000;\n return ms1 + ms2;\n}\n\nuint64_t now_micros() {\n timeval tv;\n if (gettimeofday(&tv, NULL) < 0) crash(\"gettimeofday\");\n return tv.tv_sec * 1000000LL + tv.tv_usec;\n}\n\nuint64_t nanos_to_wait(uint64_t last_controller_call_micros) {\n uint64_t now = now_micros();\n const uint64_t period = 100000LL;\n uint64_t timeout = last_controller_call_micros + period > now ?\n last_controller_call_micros + period - now :\n 0;\n return 1000 * timeout;\n}\n\nvoid HandleRemoteControl(RemoteProto remote, int* control_mode) {\n if (remote.command != *control_mode)\n fprintf(stderr, \"Helmsman switched to control mode %d\\n\", remote.command);\n switch (remote.command) {\n case kNormalControlMode:\n *control_mode = remote.command;\n ShipControl::Normal();\n break;\n case kDockingControlMode:\n *control_mode = remote.command;\n ShipControl::Docking();\n break;\n case kBrakeControlMode:\n case kPowerShutdownMode:\n *control_mode = remote.command;\n ShipControl::Brake();\n break;\n case kOverrideSkipperMode:\n *control_mode = remote.command;\n ShipControl::Normal();\n break;\n default:\n fprintf(stderr, \"Illegal remote control\");\n }\n}\n\n} \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Main.\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, char* argv[]) {\n\n int ch;\n argv0 = strrchr(argv[0], '\/');\n if (argv0) ++argv0; else argv0 = argv[0];\n\n while ((ch = getopt(argc, argv, \"dhv\")) != -1){\n switch (ch) {\n case 'd': ++debug; break;\n case 'v': ++verbose; break;\n case 'h':\n default:\n usage();\n }\n }\n\n argv += optind;\n argc -= optind;\n\n if (argc != 0) usage();\n\n setlinebuf(stdout);\n\n if (!debug) openlog(argv0, LOG_PERROR, LOG_LOCAL0);\n\n if (signal(SIGBUS, fault) == SIG_ERR) crash(\"signal(SIGBUS)\");\n if (signal(SIGSEGV, fault) == SIG_ERR) crash(\"signal(SIGSEGV)\");\n if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) crash(\"signal\");\n\n if (debug) {\n fprintf(stderr, \"Helmsman started\\n\");\n } else {\n daemon(0,0);\n char* path_to_pidfile = NULL;\n asprintf(&path_to_pidfile, \"\/var\/run\/%s.pid\", argv0);\n FILE* pidfile = fopen(path_to_pidfile, \"w\");\n if(!pidfile) crash(\"writing pidfile (%s)\", path_to_pidfile);\n fprintf(pidfile, \"%d\\n\", getpid());\n fclose(pidfile);\n free(path_to_pidfile);\n\n syslog(LOG_INFO, \"Helmsman started\");\n }\n\n ControllerInput ctrl_in;\n\n int nn = 0;\n\n struct WindProto wind = INIT_WINDPROTO;\n struct RudderProto sts = INIT_RUDDERPROTO;\n struct IMUProto imu = INIT_IMUPROTO;\n struct HelmsmanCtlProto ctl = INIT_HELMSMANCTLPROTO;\n struct RemoteProto remote = INIT_REMOTEPROTO;\n ctrl_in.alpha_star_rad = Deg2Rad(225); \/\/ Going SouthWest is a good guess (and breaks up a deadlock)\n int control_mode = kNormalControlMode;\n int loops = 0;\n uint64_t last_run_micros = 0;\n\n\n while (!feof(stdin)) {\n\n if (ferror(stdin)) clearerr(stdin);\n\n struct timespec timeout = { 0, nanos_to_wait(last_run_micros) }; \/\/ Run ship cotroller exactly once every 100ms\n fd_set rfds;\n int max_fd = -1;\n FD_ZERO(&rfds);\n set_fd(&rfds, &max_fd, stdin);\n\n sigset_t empty_mask;\n sigemptyset(&empty_mask);\n int r = pselect(max_fd + 1, &rfds, NULL, NULL, &timeout, &empty_mask);\n if (r == -1 && errno != EINTR) crash(\"pselect\");\n\n if (debug>2) fprintf(stderr, \"Woke up %d\\n\", r);\n\n if (FD_ISSET(fileno(stdin), &rfds)) {\n char line[1024];\n if (!fgets(line, sizeof line, stdin))\n crash(\"Error reading stdin\");\n\n if (sscanf(line, IFMT_WINDPROTO(&wind, &nn)) > 0) {\n ctrl_in.wind.Reset();\n ctrl_in.wind.alpha_deg = SymmetricDeg(NormalizeDeg(wind.angle_deg));\n ctrl_in.wind.mag_kn = MeterPerSecondToKnots(wind.speed_m_s);\n\n } else if (sscanf(line, IFMT_IMUPROTO(&imu, &nn)) > 0) {\n ctrl_in.imu.Reset();\n ctrl_in.imu.temperature_c = imu.temp_c;\n\n ctrl_in.imu.acceleration.x_m_s2 = imu.acc_x_m_s2;\n ctrl_in.imu.acceleration.y_m_s2 = imu.acc_y_m_s2;\n ctrl_in.imu.acceleration.z_m_s2 = imu.acc_z_m_s2;\n\n ctrl_in.imu.gyro.omega_x_rad_s = imu.gyr_x_rad_s;\n ctrl_in.imu.gyro.omega_y_rad_s = imu.gyr_y_rad_s;\n ctrl_in.imu.gyro.omega_z_rad_s = imu.gyr_z_rad_s;\n\n ctrl_in.imu.attitude.phi_x_rad = Deg2Rad(imu.roll_deg);\n ctrl_in.imu.attitude.phi_y_rad = Deg2Rad(imu.pitch_deg);\n ctrl_in.imu.attitude.phi_z_rad = SymmetricRad(NormalizeRad(Deg2Rad(imu.yaw_deg)));\n\n ctrl_in.imu.position.latitude_deg = imu.lat_deg;\n ctrl_in.imu.position.longitude_deg = imu.lng_deg;\n ctrl_in.imu.position.altitude_m = imu.alt_m;\n\n ctrl_in.imu.velocity.x_m_s = imu.vel_x_m_s;\n ctrl_in.imu.velocity.y_m_s = imu.vel_y_m_s;\n ctrl_in.imu.velocity.z_m_s = imu.vel_z_m_s;\n\n ctrl_in.imu.speed_m_s = imu.vel_x_m_s;\n\n } else if (sscanf(line, IFMT_RUDDERPROTO_STS(&sts, &nn)) > 0) {\n ctrl_in.drives.gamma_rudder_left_rad = Deg2Rad(sts.rudder_l_deg);\n ctrl_in.drives.gamma_rudder_right_rad = Deg2Rad(sts.rudder_r_deg);\n ctrl_in.drives.gamma_sail_rad = Deg2Rad(sts.sail_deg);\n ctrl_in.drives.homed_rudder_left = !isnan(sts.rudder_l_deg);\n ctrl_in.drives.homed_rudder_right = !isnan(sts.rudder_r_deg);\n ctrl_in.drives.homed_sail = !isnan(sts.sail_deg);\n\n } else if (sscanf(line, IFMT_HELMSMANCTLPROTO(&ctl, &nn)) > 0) {\n if (control_mode != kOverrideSkipperMode &&\n !isnan(ctl.alpha_star_deg))\n ctrl_in.alpha_star_rad = Deg2Rad(ctl.alpha_star_deg);\n } else if (sscanf(line, IFMT_REMOTEPROTO(&remote, &nn)) > 0) {\n HandleRemoteControl(remote, &control_mode);\n if (control_mode == kOverrideSkipperMode)\n ctrl_in.alpha_star_rad = Deg2Rad(remote.alpha_star_deg);\n }\n }\n\n if (nanos_to_wait(last_run_micros) > 100)\n continue;\n ControllerOutput ctrl_out;\n last_run_micros = now_micros();\n ShipControl::Run(ctrl_in, &ctrl_out);\n struct RudderProto ctl = {\n now_ms(),\n Rad2Deg(ctrl_out.drives_reference.gamma_rudder_star_left_rad),\n Rad2Deg(ctrl_out.drives_reference.gamma_rudder_star_right_rad),\n Rad2Deg(ctrl_out.drives_reference.gamma_sail_star_rad) };\n printf(OFMT_RUDDERPROTO_CTL(ctl, &nn));\n\n if (loops == 0) {\n struct SkipperInputProto to_skipper = {\n now_ms(),\n ctrl_out.skipper_input.longitude_deg,\n ctrl_out.skipper_input.latitude_deg,\n ctrl_out.skipper_input.angle_true_deg,\n ctrl_out.skipper_input.mag_true_kn\n };\n printf(OFMT_SKIPPER_INPUTPROTO(to_skipper, &nn));\n }\n \/*\n if (loops == 5) {\n struct HelmsmanStatus = {\n Rad2Deg(ctrl_in.alpha_star_rad)\n };\n printf(OFMT_HELMSMAN_STATUSPROTO);\n *\/\n loops = loops == 9 ? 0 : loops+1;\n\n\n } \/\/ for ever\n\n crash(\"Main loop exit\");\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"hex_map.h\"\n\n#include <array>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include \"asdf_multiplat\/data\/gl_resources.h\"\n#include \"asdf_multiplat\/data\/content_manager.h\"\n\nusing namespace std;\nusing namespace glm;\n\nnamespace asdf\n{\n using namespace util;\n using namespace data;\n \nnamespace hexmap\n{\nnamespace ui\n{\n \/\/const glm::vec4 grid_color(0.0f, 0.0f, 0.0f, 1.0f);\n const glm::vec4 grid_color(1.0f, 1.0f, 1.0f, 1.0f);\n constexpr float grid_overlay_thickness = 2.0f;\n\n constexpr char terrain_types_json_filename[] = \"terrain_types.json\";\n\n constexpr int apply_hexagon_textures = 1;\n\n\n gl_vertex_spec_<vertex_attrib::position3_t\/*, vertex_attrib::color_t*\/> hexagon_vertex_t::vertex_spec;\n\n\n hex_map_t::hex_map_t(data::hex_map_t& _map_data)\n : map_data(_map_data)\n {\n shader = Content.create_shader(\"hexmap\", 330);\n spritebatch.spritebatch_shader = Content.shaders[\"spritebatch\"];\n\n std::vector<hexagon_vertex_t> verts(6);\n\n for(size_t i = 0; i < 6; ++i)\n {\n verts[i].position.x = hexagon_points[i*3 + 0];\n verts[i].position.y = hexagon_points[i*3 + 1];\n verts[i].position.z = hexagon_points[i*3 + 2];\n\n \/\/verts[i].color = grid_color;\n }\n\n hexagon.initialize(shader);\n hexagon.set_data(verts);\n hexagon.draw_mode = GL_LINE_LOOP;\n \n ASSERT(!CheckGLError(), \"\");\n GL_State->bind(hexagons_vao);\n\n GL_State->bind(hexagon.vbo);\n hexagon_vertex_t::vertex_spec.set_vertex_attribs(shader);\n ASSERT(!CheckGLError(), \"Error setting vertex attributes\");\n\n GL_State->bind(hex_gl_data);\n GLint attrib_loc = glGetAttribLocation(shader->shader_program_id, \"TileID\");\n glEnableVertexAttribArray(attrib_loc); \/\/tell the location\n glVertexAttribIPointer(attrib_loc, 1, GL_UNSIGNED_INT, sizeof(data::hex_tile_id_t), 0); \/\/ must use Atrib ** I ** for unsigned int to be used as a uint in glsl\n glVertexAttribDivisor(attrib_loc, 1); \/\/second arg is 1, which means the vertex buffer for hexagon tile ID is incremented every instance, instead of every vertex\n\n GL_State->unbind_vao();\n\n ASSERT(!CheckGLError(), \"\");\n\n std::array<glm::vec4, num_tile_colors> colors =\n {\n COLOR_RED\n , COLOR_GREEN\n , COLOR_BLUE\n , COLOR_CYAN\n , COLOR_YELLOW\n , COLOR_MAGENTA\n , COLOR_TEAL\n , COLOR_ORANGE\n , COLOR_LIGHTGREY\n , COLOR_GREY\n };\n\n set_tile_colors(colors);\n ASSERT(!CheckGLError(), \"\");\n\n\n auto dir = find_folder(\"data\");\n ASSERT(dir.length() > 0, \"Could not find data folder\");\n\n auto terrain_types_json_filepath = dir + \"\/\" + string(terrain_types_json_filename);\n terrain_bank.load_from_file(terrain_types_json_filepath);\n \n\n objects_atlas = make_unique<texture_atlas_t>(string(dir + \"\/..\/assets\/Objects\/objects_atlas_data.json\"));\n\n spline_renderer.init(Content.create_shader(\"spline\", \"spline\", 330));\n spline_renderer.spline_list = &map_data.splines;\n }\n\n void hex_map_t::set_tile_colors(std::array<glm::vec4, num_tile_colors> const& colors)\n {\n GL_State->bind(shader);\n glUniform4fv(shader->uniform(\"TileColors[0]\"), num_tile_colors, reinterpret_cast<const GLfloat*>(colors.data()));\n ASSERT(!CheckGLError(), \"\");\n }\n\n\n void hex_map_t::update(float dt)\n {\n camera_controller.update(dt);\n camera.position = camera_controller.position;\n }\n\n void hex_map_t::render()\n {\n ASSERT(map_data.hex_grid.chunks.size(), \"\");\n ASSERT(map_data.hex_grid.chunks[0].size(), \"\");\n\n shader->world_matrix = glm::mat4();\n shader->view_matrix = camera.view_matrix();\n shader->projection_matrix = camera.projection_ortho();\n \n GL_State->bind(shader);\n glUniform1i(shader->uniform(\"ApplyTexture\"), apply_hexagon_textures);\n\n map_data.hex_grid.for_each_chunk( [this](data::hex_grid_chunk_t& chunk) -> void\n {\n render_chunk(chunk);\n });\n\n \n glUniform1i(shader->uniform(\"ApplyTexture\"), 0); \/\/turn of textures for the grid\n render_grid_overlay(map_data.hex_grid.size);\n \n\n render_map_objects();\n\n render_splines();\n\n\n \/\/TEST\n \/\/ re-importing every frame so I can capture it with nvidia's gfx debugger\n \/\/ GL_State->bind(texture_bank.atlas_fbo);\n \/\/ glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n \/\/ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ auto dir = find_folder(\"data\");\n \/\/ auto imported_textures_json_filepath = dir + \"\/\" + string(imported_textures_json_filename);\n \/\/ texture_bank.saved_textures.clear(); \/\/reset so I'm not infinitely piling stuff on\n \/\/ texture_bank.load_from_list_file(imported_textures_json_filepath);\n \/\/ glBindTexture(GL_TEXTURE_2D, texture_bank.atlas_texture.texture_id);\n \/\/---\n }\n\n void hex_map_t::on_event(SDL_Event* event)\n {\n camera_controller.on_event(event);\n camera.position = camera_controller.position;\n }\n\n\n\n void hex_map_t::render_chunk(data::hex_grid_chunk_t const& chunk)\n {\n GL_State->bind(hexagons_vao);\n\n hex_gl_data.set_data(chunk);\n\n float chunk_width_cells = hex_width_d4 * 3 * chunk.allocated_size.x;\n float chunk_height_cells = hex_height * chunk.allocated_size.y;\n\n shader->world_matrix[3][0] = chunk.position.x * chunk_width_cells;\n shader->world_matrix[3][1] = chunk.position.y * chunk_height_cells;\n shader->update_wvp_uniform();\n\n glUniform4f(shader->uniform(\"Color\"), 1.0f, 1.0f, 1.0f, 1.0f);\n\n glBindTexture(GL_TEXTURE_2D, terrain_bank.atlas_texture.texture_id);\n\n render_hexagons(chunk.size, GL_TRIANGLE_FAN);\n GL_State->unbind_vao();\n }\n\n void hex_map_t::render_grid_overlay(glm::uvec2 grid_size)\n {\n GL_State->bind(shader);\n GL_State->bind(hexagon.vao);\n\n glLineWidth(grid_overlay_thickness);\n\n shader->world_matrix[3][0] = 0.0f;\n shader->world_matrix[3][1] = 0.0f;\n shader->update_wvp_uniform();\n\n glUniform4fv( shader->uniform(\"Color\"), 1, glm::value_ptr(grid_color) );\n\n render_hexagons(grid_size, hexagon.draw_mode);\n GL_State->unbind_vao();\n }\n\n void hex_map_t::render_hexagons(glm::uvec2 grid_size, GLuint draw_mode)\n {\n auto loc = shader->uniform(\"CHUNK_HEIGHT\");\n glUniform1i(loc, grid_size.y);\n\n size_t n = grid_size.x * grid_size.y;\n glDrawArraysInstanced(draw_mode, 0, 6, n); \/\/start at 0th, draw 6 points per shape, draw (width\/2)\n }\n\n void hex_map_t::render_map_objects()\n {\n spritebatch.begin(shader->view_matrix, shader->projection_matrix);\n\n for(auto& obj : map_data.objects)\n {\n ASSERT(obj.id < objects_atlas->atlas_entries.size(), \"object ID does not exist in atlas\");\n auto const& atlas_entry = objects_atlas->atlas_entries[obj.id];\n\n rect_t src_rect(atlas_entry.top_left_px.x, atlas_entry.top_left_px.y, atlas_entry.size_px.x, atlas_entry.size_px.y);\n auto sprite_scale = obj.scale * glm::vec2(units_per_px);\n\n spritebatch.draw(objects_atlas->atlas_texture, obj.position, src_rect, obj.color, sprite_scale, obj.rotation);\n }\n\n spritebatch.end();\n }\n\n void hex_map_t::render_splines()\n {\n ASSERT(spline_renderer.shader, \"spline shader required to render splines\");\n\n auto& sr_s = spline_renderer.shader;\n sr_s->view_matrix = shader->view_matrix;\n sr_s->projection_matrix = shader->projection_matrix;\n\n spline_renderer.rebuild_if_dirty();\n spline_renderer.render();\n }\n\n\n\n void hex_buffer_data_t::set_data(data::hex_grid_chunk_t const& chunk)\n {\n \/\/std::array<data::hex_tile_id_t, data::max_chunk_width * data::max_chunk_height> cell_data;\n std::vector<data::hex_tile_id_t> cell_data(chunk.size.x * chunk.size.y);\n\n for(size_t x = 0; x < chunk.size.x; ++x)\n {\n for(size_t y = 0; y < chunk.size.y; ++y)\n {\n \/\/cell_data[x*chunk.size.y + y] = rand() % 10;\n \/\/cell_data[x*chunk.size.y + y] = chunk.position.x + abs(chunk.position.y); \/\/set id to chunk pos for debugging chunks\n\n cell_data[x*chunk.size.y + y] = chunk.cells[x][y].tile_id;\n }\n }\n\n GL_State->bind(*this);\n GL_State->buffer_data(*this, (cell_data.size() * sizeof(data::hex_tile_id_t)), reinterpret_cast<GLvoid*>(cell_data.data()) );\n\n ASSERT(!CheckGLError(), \"Error setting hexagon buffer data\");\n }\n}\n}\n}<commit_msg>WIP opengl 3.0 compatability<commit_after>#include \"stdafx.h\"\n#include \"hex_map.h\"\n\n#include <array>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include \"asdf_multiplat\/data\/gl_resources.h\"\n#include \"asdf_multiplat\/data\/content_manager.h\"\n\nusing namespace std;\nusing namespace glm;\n\nnamespace asdf\n{\n using namespace util;\n using namespace data;\n \nnamespace hexmap\n{\nnamespace ui\n{\n \/\/const glm::vec4 grid_color(0.0f, 0.0f, 0.0f, 1.0f);\n const glm::vec4 grid_color(1.0f, 1.0f, 1.0f, 1.0f);\n constexpr float grid_overlay_thickness = 2.0f;\n\n constexpr char terrain_types_json_filename[] = \"terrain_types.json\";\n\n constexpr int apply_hexagon_textures = 1;\n\n\n gl_vertex_spec_<vertex_attrib::position3_t\/*, vertex_attrib::color_t*\/> hexagon_vertex_t::vertex_spec;\n\n\n hex_map_t::hex_map_t(data::hex_map_t& _map_data)\n : map_data(_map_data)\n {\n \/\/\/ FIXME opengl shader compatability\n \/\/shader = Content.create_shader(\"hexmap\", 330);\n shader = Content.create_shader(\"hexmap\", 130);\n spritebatch.spritebatch_shader = Content.shaders[\"spritebatch\"];\n\n std::vector<hexagon_vertex_t> verts(6);\n\n for(size_t i = 0; i < 6; ++i)\n {\n verts[i].position.x = hexagon_points[i*3 + 0];\n verts[i].position.y = hexagon_points[i*3 + 1];\n verts[i].position.z = hexagon_points[i*3 + 2];\n\n \/\/verts[i].color = grid_color;\n }\n\n hexagon.initialize(shader);\n hexagon.set_data(verts);\n hexagon.draw_mode = GL_LINE_LOOP;\n \n ASSERT(!CheckGLError(), \"\");\n GL_State->bind(hexagons_vao);\n\n GL_State->bind(hexagon.vbo);\n hexagon_vertex_t::vertex_spec.set_vertex_attribs(shader);\n ASSERT(!CheckGLError(), \"Error setting vertex attributes\");\n\n GL_State->bind(hex_gl_data);\n GLint attrib_loc = glGetAttribLocation(shader->shader_program_id, \"TileID\");\n glEnableVertexAttribArray(attrib_loc); \/\/tell the location\n\n \/\/FIXME OpenGL Compatability\n glVertexAttribIPointer(attrib_loc, 1, GL_UNSIGNED_INT, sizeof(data::hex_tile_id_t), 0); \/\/ must use Atrib ** I ** for unsigned int to be used as a uint in glsl\n \/\/glVertexAttribDivisor(attrib_loc, 1); \/\/second arg is 1, which means the vertex buffer for hexagon tile ID is incremented every instance, instead of every vertex\n glVertexAttribDivisorARB(attrib_loc, 1);\n\n GL_State->unbind_vao();\n\n ASSERT(!CheckGLError(), \"\");\n\n std::array<glm::vec4, num_tile_colors> colors =\n {\n COLOR_RED\n , COLOR_GREEN\n , COLOR_BLUE\n , COLOR_CYAN\n , COLOR_YELLOW\n , COLOR_MAGENTA\n , COLOR_TEAL\n , COLOR_ORANGE\n , COLOR_LIGHTGREY\n , COLOR_GREY\n };\n\n set_tile_colors(colors);\n ASSERT(!CheckGLError(), \"\");\n\n\n auto dir = find_folder(\"data\");\n ASSERT(dir.length() > 0, \"Could not find data folder\");\n\n auto terrain_types_json_filepath = dir + \"\/\" + string(terrain_types_json_filename);\n terrain_bank.load_from_file(terrain_types_json_filepath);\n \n\n objects_atlas = make_unique<texture_atlas_t>(string(dir + \"\/..\/assets\/Objects\/objects_atlas_data.json\"));\n\n \/\/\/ FIXME OpenGL Compatability\n \/\/spline_renderer.init(Content.create_shader(\"spline\", \"spline\", 330));\n spline_renderer.init(Content.create_shader(\"spline\", \"spline\", 130));\n spline_renderer.spline_list = &map_data.splines;\n }\n\n void hex_map_t::set_tile_colors(std::array<glm::vec4, num_tile_colors> const& colors)\n {\n GL_State->bind(shader);\n glUniform4fv(shader->uniform(\"TileColors[0]\"), num_tile_colors, reinterpret_cast<const GLfloat*>(colors.data()));\n ASSERT(!CheckGLError(), \"\");\n }\n\n\n void hex_map_t::update(float dt)\n {\n camera_controller.update(dt);\n camera.position = camera_controller.position;\n }\n\n void hex_map_t::render()\n {\n ASSERT(map_data.hex_grid.chunks.size(), \"\");\n ASSERT(map_data.hex_grid.chunks[0].size(), \"\");\n\n shader->world_matrix = glm::mat4();\n shader->view_matrix = camera.view_matrix();\n shader->projection_matrix = camera.projection_ortho();\n \n GL_State->bind(shader);\n glUniform1i(shader->uniform(\"ApplyTexture\"), apply_hexagon_textures);\n\n map_data.hex_grid.for_each_chunk( [this](data::hex_grid_chunk_t& chunk) -> void\n {\n render_chunk(chunk);\n });\n\n \n glUniform1i(shader->uniform(\"ApplyTexture\"), 0); \/\/turn of textures for the grid\n render_grid_overlay(map_data.hex_grid.size);\n \n\n render_map_objects();\n\n render_splines();\n\n\n \/\/TEST\n \/\/ re-importing every frame so I can capture it with nvidia's gfx debugger\n \/\/ GL_State->bind(texture_bank.atlas_fbo);\n \/\/ glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n \/\/ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ auto dir = find_folder(\"data\");\n \/\/ auto imported_textures_json_filepath = dir + \"\/\" + string(imported_textures_json_filename);\n \/\/ texture_bank.saved_textures.clear(); \/\/reset so I'm not infinitely piling stuff on\n \/\/ texture_bank.load_from_list_file(imported_textures_json_filepath);\n \/\/ glBindTexture(GL_TEXTURE_2D, texture_bank.atlas_texture.texture_id);\n \/\/---\n }\n\n void hex_map_t::on_event(SDL_Event* event)\n {\n camera_controller.on_event(event);\n camera.position = camera_controller.position;\n }\n\n\n\n void hex_map_t::render_chunk(data::hex_grid_chunk_t const& chunk)\n {\n GL_State->bind(hexagons_vao);\n\n hex_gl_data.set_data(chunk);\n\n float chunk_width_cells = hex_width_d4 * 3 * chunk.allocated_size.x;\n float chunk_height_cells = hex_height * chunk.allocated_size.y;\n\n shader->world_matrix[3][0] = chunk.position.x * chunk_width_cells;\n shader->world_matrix[3][1] = chunk.position.y * chunk_height_cells;\n shader->update_wvp_uniform();\n\n glUniform4f(shader->uniform(\"Color\"), 1.0f, 1.0f, 1.0f, 1.0f);\n\n glBindTexture(GL_TEXTURE_2D, terrain_bank.atlas_texture.texture_id);\n\n render_hexagons(chunk.size, GL_TRIANGLE_FAN);\n GL_State->unbind_vao();\n }\n\n void hex_map_t::render_grid_overlay(glm::uvec2 grid_size)\n {\n GL_State->bind(shader);\n GL_State->bind(hexagon.vao);\n\n glLineWidth(grid_overlay_thickness);\n\n shader->world_matrix[3][0] = 0.0f;\n shader->world_matrix[3][1] = 0.0f;\n shader->update_wvp_uniform();\n\n glUniform4fv( shader->uniform(\"Color\"), 1, glm::value_ptr(grid_color) );\n\n render_hexagons(grid_size, hexagon.draw_mode);\n GL_State->unbind_vao();\n }\n\n void hex_map_t::render_hexagons(glm::uvec2 grid_size, GLuint draw_mode)\n {\n auto loc = shader->uniform(\"CHUNK_HEIGHT\");\n glUniform1i(loc, grid_size.y);\n\n size_t n = grid_size.x * grid_size.y;\n\n \/\/\/FIXME OpenGL Compatability\n if(GLEW_VERSION_3_1)\n {\n glDrawArraysInstanced(draw_mode, 0, 6, n); \/\/start at 0th, draw 6 points per shape, draw (width\/2)\n }\n else\n {\n glDrawArrays(draw_mode, 0, 6);\n }\n \n }\n\n void hex_map_t::render_map_objects()\n {\n spritebatch.begin(shader->view_matrix, shader->projection_matrix);\n\n for(auto& obj : map_data.objects)\n {\n ASSERT(obj.id < objects_atlas->atlas_entries.size(), \"object ID does not exist in atlas\");\n auto const& atlas_entry = objects_atlas->atlas_entries[obj.id];\n\n rect_t src_rect(atlas_entry.top_left_px.x, atlas_entry.top_left_px.y, atlas_entry.size_px.x, atlas_entry.size_px.y);\n auto sprite_scale = obj.scale * glm::vec2(units_per_px);\n\n spritebatch.draw(objects_atlas->atlas_texture, obj.position, src_rect, obj.color, sprite_scale, obj.rotation);\n }\n\n spritebatch.end();\n }\n\n void hex_map_t::render_splines()\n {\n ASSERT(spline_renderer.shader, \"spline shader required to render splines\");\n\n auto& sr_s = spline_renderer.shader;\n sr_s->view_matrix = shader->view_matrix;\n sr_s->projection_matrix = shader->projection_matrix;\n\n spline_renderer.rebuild_if_dirty();\n spline_renderer.render();\n }\n\n\n\n void hex_buffer_data_t::set_data(data::hex_grid_chunk_t const& chunk)\n {\n \/\/std::array<data::hex_tile_id_t, data::max_chunk_width * data::max_chunk_height> cell_data;\n std::vector<data::hex_tile_id_t> cell_data(chunk.size.x * chunk.size.y);\n\n for(size_t x = 0; x < chunk.size.x; ++x)\n {\n for(size_t y = 0; y < chunk.size.y; ++y)\n {\n \/\/cell_data[x*chunk.size.y + y] = rand() % 10;\n \/\/cell_data[x*chunk.size.y + y] = chunk.position.x + abs(chunk.position.y); \/\/set id to chunk pos for debugging chunks\n\n cell_data[x*chunk.size.y + y] = chunk.cells[x][y].tile_id;\n }\n }\n\n GL_State->bind(*this);\n GL_State->buffer_data(*this, (cell_data.size() * sizeof(data::hex_tile_id_t)), reinterpret_cast<GLvoid*>(cell_data.data()) );\n\n ASSERT(!CheckGLError(), \"Error setting hexagon buffer data\");\n }\n}\n}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2000 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT) && !defined(macintosh)\n#ident \"$Id: link_const.cc,v 1.11 2001\/08\/25 23:50:03 steve Exp $\"\n#endif\n\n# include \"config.h\"\n\n# include \"netlist.h\"\n# include \"netmisc.h\"\n\n\/*\n * Scan the link for drivers. If there are only constant drivers, then\n * the nexus has a known constant value. If there is a supply net,\n * then the nexus again has a known constant value.\n *\/\nbool link_drivers_constant(const Link&lnk)\n{\n const Nexus*nex = lnk.nexus();\n bool flag = true;\n\n for (const Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\t const NetNet*sig;\n\n\t if (cur == &lnk)\n\t\t continue;\n\t if (cur->get_dir() == Link::INPUT)\n\t\t continue;\n\n\t \/* If this is an input or inout port of a root module,\n\t\t then the is probably not a constant value. I\n\t\t certainly don't know what the value is, anyhow. This\n\t\t can happen in cases like this:\n\n\t\t module main(sig);\n\t\t input sig;\n\t\t endmodule\n\n\t\t If main is a root module (it has no parent) then sig\n\t\t is not constant because it connects to an unspecified\n\t\t outside world. *\/\n\n\t if (sig = dynamic_cast<const NetNet*>(cur->get_obj())) do {\n\t\t if (sig->port_type() == NetNet::NOT_A_PORT)\n\t\t\tbreak;\n\n\t\t if (sig->port_type() == NetNet::POUTPUT)\n\t\t\tbreak;\n\n\t\t if (sig->scope()->parent())\n\t\t\tbreak;\n\n\t\t flag = false;\n\t } while(0);\n\n\n\t \/* If the link is PASSIVE then it doesn't count as a\n\t\t driver if its initial value is Vz. PASSIVE nodes\n\t\t include wires and tri nets. *\/\n\t if (cur->get_dir() == Link::PASSIVE)\n\t\t continue;\n\n\t if (! dynamic_cast<const NetConst*>(cur->get_obj()))\n\t\t flag = false;\n\n\t \/* If there is a supply net, then this nexus will have a\n\t\t constant value independent of any drivers. *\/\n\t if (const NetNet*sig = dynamic_cast<const NetNet*>(cur->get_obj()))\n\t\t switch (sig->type()) {\n\t\t case NetNet::SUPPLY0:\n\t\t case NetNet::SUPPLY1:\n\t\t\treturn true;\n\t\t default:\n\t\t\tbreak;\n\t\t }\n }\n\n return flag;\n}\n\nverinum::V driven_value(const Link&lnk)\n{\n verinum::V val = lnk.get_init();\n\n const Nexus*nex = lnk.nexus();\n for (const Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\n\t const NetConst*obj;\n\t const NetNet*sig;\n\t if (obj = dynamic_cast<const NetConst*>(cur->get_obj())) {\n\t\t val = obj->value(cur->get_pin());\n\n\t } else if (sig = dynamic_cast<const NetNet*>(cur->get_obj())) {\n\n\t\t if (sig->type() == NetNet::SUPPLY0)\n\t\t\treturn verinum::V0;\n\n\t\t if (sig->type() == NetNet::SUPPLY1)\n\t\t\treturn verinum::V1;\n\t }\n }\n\n return val;\n}\n\n\/*\n * $Log: link_const.cc,v $\n * Revision 1.11 2001\/08\/25 23:50:03 steve\n * Change the NetAssign_ class to refer to the signal\n * instead of link into the netlist. This is faster\n * and uses less space. Make the NetAssignNB carry\n * the delays instead of the NetAssign_ lval objects.\n *\n * Change the vvp code generator to support multiple\n * l-values, i.e. concatenations of part selects.\n *\n * Revision 1.10 2001\/07\/25 03:10:49 steve\n * Create a config.h.in file to hold all the config\n * junk, and support gcc 3.0. (Stephan Boettcher)\n *\n * Revision 1.9 2001\/07\/07 03:01:37 steve\n * Detect and make available to t-dll the right shift.\n *\n * Revision 1.8 2001\/02\/16 03:27:07 steve\n * links to root inputs are not constant.\n *\n * Revision 1.7 2000\/11\/20 01:41:12 steve\n * Whoops, return the calculated constant value rom driven_value.\n *\n * Revision 1.6 2000\/11\/20 00:58:40 steve\n * Add support for supply nets (PR#17)\n *\n * Revision 1.5 2000\/07\/14 06:12:57 steve\n * Move inital value handling from NetNet to Nexus\n * objects. This allows better propogation of inital\n * values.\n *\n * Clean up constant propagation a bit to account\n * for regs that are not really values.\n *\n * Revision 1.4 2000\/06\/25 19:59:42 steve\n * Redesign Links to include the Nexus class that\n * carries properties of the connected set of links.\n *\n * Revision 1.3 2000\/05\/14 17:55:04 steve\n * Support initialization of FF Q value.\n *\n * Revision 1.2 2000\/05\/07 04:37:56 steve\n * Carry strength values from Verilog source to the\n * pform and netlist for gates.\n *\n * Change vvm constants to use the driver_t to drive\n * a constant value. This works better if there are\n * multiple drivers on a signal.\n *\n * Revision 1.1 2000\/04\/20 00:28:03 steve\n * Catch some simple identity compareoptimizations.\n *\n *\/\n\n<commit_msg> Shuffle link_drivers_constant for speed.<commit_after>\/*\n * Copyright (c) 2000 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT) && !defined(macintosh)\n#ident \"$Id: link_const.cc,v 1.12 2002\/06\/19 04:18:46 steve Exp $\"\n#endif\n\n# include \"config.h\"\n\n# include \"netlist.h\"\n# include \"netmisc.h\"\n\n\/*\n * Scan the link for drivers. If there are only constant drivers, then\n * the nexus has a known constant value. If there is a supply net,\n * then the nexus again has a known constant value.\n *\/\nbool link_drivers_constant(const Link&lnk)\n{\n const Nexus*nex = lnk.nexus();\n\n for (const Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\t const NetNet*sig;\n\t Link::DIR cur_dir;\n\n\t if (cur == &lnk)\n\t\t continue;\n\n\t cur_dir = cur->get_dir();\n\t if (cur_dir == Link::INPUT)\n\t\t continue;\n\n\t \/* If this is an input or inout port of a root module,\n\t\t then the is probably not a constant value. I\n\t\t certainly don't know what the value is, anyhow. This\n\t\t can happen in cases like this:\n\n\t\t module main(sig);\n\t\t input sig;\n\t\t endmodule\n\n\t\t If main is a root module (it has no parent) then sig\n\t\t is not constant because it connects to an unspecified\n\t\t outside world. *\/\n\n\t if (cur_dir == Link::PASSIVE) {\n\t\t \n\t\t const NetObj*obj = cur->get_obj();\n\t\t if (obj->scope()->parent() != 0)\n\t\t\tcontinue;\n\n\t\t sig = dynamic_cast<const NetNet*>(cur->get_obj());\n\t\t assert(sig);\n\n\t\t if (sig->port_type() == NetNet::NOT_A_PORT)\n\t\t\tcontinue;\n\n\t\t if (sig->port_type() == NetNet::POUTPUT)\n\t\t\tcontinue;\n\n\t\t return false;\n\n\t }\n\n\t if (! dynamic_cast<const NetConst*>(cur->get_obj()))\n\t\t return false;\n\n\t \/* If there is a supply net, then this nexus will have a\n\t\t constant value independent of any drivers. *\/\n\t if (const NetNet*sig = dynamic_cast<const NetNet*>(cur->get_obj()))\n\t\t switch (sig->type()) {\n\t\t case NetNet::SUPPLY0:\n\t\t case NetNet::SUPPLY1:\n\t\t\treturn true;\n\t\t default:\n\t\t\tbreak;\n\t\t }\n }\n\n return true;\n}\n\nverinum::V driven_value(const Link&lnk)\n{\n verinum::V val = lnk.get_init();\n\n const Nexus*nex = lnk.nexus();\n for (const Link*cur = nex->first_nlink()\n\t\t ; cur ; cur = cur->next_nlink()) {\n\n\t const NetConst*obj;\n\t const NetNet*sig;\n\t if (obj = dynamic_cast<const NetConst*>(cur->get_obj())) {\n\t\t val = obj->value(cur->get_pin());\n\n\t } else if (sig = dynamic_cast<const NetNet*>(cur->get_obj())) {\n\n\t\t if (sig->type() == NetNet::SUPPLY0)\n\t\t\treturn verinum::V0;\n\n\t\t if (sig->type() == NetNet::SUPPLY1)\n\t\t\treturn verinum::V1;\n\t }\n }\n\n return val;\n}\n\n\/*\n * $Log: link_const.cc,v $\n * Revision 1.12 2002\/06\/19 04:18:46 steve\n * Shuffle link_drivers_constant for speed.\n *\n * Revision 1.11 2001\/08\/25 23:50:03 steve\n * Change the NetAssign_ class to refer to the signal\n * instead of link into the netlist. This is faster\n * and uses less space. Make the NetAssignNB carry\n * the delays instead of the NetAssign_ lval objects.\n *\n * Change the vvp code generator to support multiple\n * l-values, i.e. concatenations of part selects.\n *\n * Revision 1.10 2001\/07\/25 03:10:49 steve\n * Create a config.h.in file to hold all the config\n * junk, and support gcc 3.0. (Stephan Boettcher)\n *\n * Revision 1.9 2001\/07\/07 03:01:37 steve\n * Detect and make available to t-dll the right shift.\n *\n * Revision 1.8 2001\/02\/16 03:27:07 steve\n * links to root inputs are not constant.\n *\n * Revision 1.7 2000\/11\/20 01:41:12 steve\n * Whoops, return the calculated constant value rom driven_value.\n *\n * Revision 1.6 2000\/11\/20 00:58:40 steve\n * Add support for supply nets (PR#17)\n *\n * Revision 1.5 2000\/07\/14 06:12:57 steve\n * Move inital value handling from NetNet to Nexus\n * objects. This allows better propogation of inital\n * values.\n *\n * Clean up constant propagation a bit to account\n * for regs that are not really values.\n *\n * Revision 1.4 2000\/06\/25 19:59:42 steve\n * Redesign Links to include the Nexus class that\n * carries properties of the connected set of links.\n *\n * Revision 1.3 2000\/05\/14 17:55:04 steve\n * Support initialization of FF Q value.\n *\n * Revision 1.2 2000\/05\/07 04:37:56 steve\n * Carry strength values from Verilog source to the\n * pform and netlist for gates.\n *\n * Change vvm constants to use the driver_t to drive\n * a constant value. This works better if there are\n * multiple drivers on a signal.\n *\n * Revision 1.1 2000\/04\/20 00:28:03 steve\n * Catch some simple identity compareoptimizations.\n *\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_FILTER_H_\n#define ITER_FILTER_H_\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n \/\/ Forward declarations of Filter and filter\n template <typename FilterFunc, typename Container>\n class Filter;\n\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(FilterFunc, Container&&);\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc, std::initializer_list<T>);\n\n template <typename FilterFunc, typename Container>\n class Filter {\n private:\n Container container;\n FilterFunc filter_func;\n\n \/\/ The filter function is the only thing allowed to create a Filter\n friend Filter filter<FilterFunc, Container>(FilterFunc, Container&&);\n\n template <typename FF, typename T>\n friend Filter<FF, std::initializer_list<T>> filter(\n FF, std::initializer_list<T>);\n\n \/\/ Value constructor for use only in the filter function\n Filter(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward<Container>(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n class Iterator : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>> {\n protected:\n using Holder = DerefHolder<iterator_deref<Container>>;\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ increment until the iterator points to is true on the\n \/\/ predicate. Called by constructor and operator++\n void skip_failures() {\n while (this->sub_iter != this->sub_end\n && !(*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(iterator_type<Container> iter, iterator_type<Container> end,\n FilterFunc& in_filter_func)\n : sub_iter{iter}, sub_end{end}, filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_failures();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n this->skip_failures();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n };\n\n \/\/ Helper function to instantiate a Filter\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward<Container>(container)};\n }\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc filter_func, std::initializer_list<T> il) {\n return {filter_func, std::move(il)};\n }\n\n namespace detail {\n\n template <typename T>\n bool boolean_cast(const T& t) {\n return bool(t);\n }\n\n template <typename Container>\n class BoolTester {\n public:\n bool operator()(const iterator_deref<Container> item) const {\n return bool(item);\n }\n };\n }\n\n template <typename Container>\n auto filter(Container&& container) -> decltype(filter(\n detail::BoolTester<Container>(), std::forward<Container>(container))) {\n return filter(\n detail::BoolTester<Container>(), std::forward<Container>(container));\n }\n\n template <typename T>\n auto filter(std::initializer_list<T> il) -> decltype(\n filter(detail::BoolTester<std::initializer_list<T>>(), std::move(il))) {\n return filter(\n detail::BoolTester<std::initializer_list<T>>(), std::move(il));\n }\n}\n\n#endif\n<commit_msg>moves Filtered into impl { }<commit_after>#ifndef ITER_FILTER_H_\n#define ITER_FILTER_H_\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n namespace impl {\n template <typename FilterFunc, typename Container>\n class Filtered;\n }\n\n template <typename FilterFunc, typename Container>\n impl::Filtered<FilterFunc, Container> filter(FilterFunc, Container&&);\n\n template <typename FilterFunc, typename T>\n impl::Filtered<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc, std::initializer_list<T>);\n}\n\ntemplate <typename FilterFunc, typename Container>\nclass iter::impl::Filtered {\n private:\n Container container;\n FilterFunc filter_func;\n\n \/\/ The filter function is the only thing allowed to create a Filtered\n friend Filtered iter::filter<FilterFunc, Container>(FilterFunc, Container&&);\n\n template <typename FF, typename T>\n friend Filtered<FF, std::initializer_list<T>> iter::filter(\n FF, std::initializer_list<T>);\n\n \/\/ Value constructor for use only in the filter function\n Filtered(FilterFunc in_filter_func, Container&& in_container)\n : container(std::forward<Container>(in_container)),\n filter_func(in_filter_func) {}\n\n public:\n class Iterator : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>> {\n protected:\n using Holder = DerefHolder<iterator_deref<Container>>;\n iterator_type<Container> sub_iter;\n iterator_type<Container> sub_end;\n Holder item;\n FilterFunc* filter_func;\n\n void inc_sub_iter() {\n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n }\n\n \/\/ increment until the iterator points to is true on the\n \/\/ predicate. Called by constructor and operator++\n void skip_failures() {\n while (this->sub_iter != this->sub_end\n && !(*this->filter_func)(this->item.get())) {\n this->inc_sub_iter();\n }\n }\n\n public:\n Iterator(iterator_type<Container> iter, iterator_type<Container> end,\n FilterFunc& in_filter_func)\n : sub_iter{iter}, sub_end{end}, filter_func(&in_filter_func) {\n if (this->sub_iter != this->sub_end) {\n this->item.reset(*this->sub_iter);\n }\n this->skip_failures();\n }\n\n typename Holder::reference operator*() {\n return this->item.get();\n }\n\n typename Holder::pointer operator->() {\n return this->item.get_ptr();\n }\n\n Iterator& operator++() {\n this->inc_sub_iter();\n this->skip_failures();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->container),\n this->filter_func};\n }\n};\n\ntemplate <typename FilterFunc, typename Container>\niter::impl::Filtered<FilterFunc, Container> iter::filter(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward<Container>(container)};\n}\n\ntemplate <typename FilterFunc, typename T>\niter::impl::Filtered<FilterFunc, std::initializer_list<T>> iter::filter(\n FilterFunc filter_func, std::initializer_list<T> il) {\n return {filter_func, std::move(il)};\n}\n\nnamespace iter {\n namespace detail {\n\n template <typename T>\n bool boolean_cast(const T& t) {\n return bool(t);\n }\n\n template <typename Container>\n class BoolTester {\n public:\n bool operator()(const iterator_deref<Container> item) const {\n return bool(item);\n }\n };\n }\n\n template <typename Container>\n auto filter(Container&& container) -> decltype(filter(\n detail::BoolTester<Container>(), std::forward<Container>(container))) {\n return filter(\n detail::BoolTester<Container>(), std::forward<Container>(container));\n }\n\n template <typename T>\n auto filter(std::initializer_list<T> il) -> decltype(\n filter(detail::BoolTester<std::initializer_list<T>>(), std::move(il))) {\n return filter(\n detail::BoolTester<std::initializer_list<T>>(), std::move(il));\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n *\n * Data Differential YATL (i.e. libtest) library\n *\n * Copyright (C) 2012 Data Differential, http:\/\/datadifferential.com\/\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <config.h>\n#include <libtest\/common.h>\n\n#include <cstdlib>\n#include <unistd.h>\n\nnamespace libtest {\n\nbool has_libmemcached(void)\n{\n if (HAVE_LIBMEMCACHED)\n {\n return true;\n }\n\n return false;\n}\n\nbool has_libdrizzle(void)\n{\n if (HAVE_LIBDRIZZLE)\n {\n return true;\n }\n\n return false;\n}\n\nbool has_postgres_support(void)\n{\n if (getenv(\"POSTGES_IS_RUNNING_AND_SETUP\"))\n {\n if (HAVE_LIBPQ)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\nbool has_gearmand()\n{\n if (HAVE_GEARMAND_BINARY)\n {\n std::stringstream arg_buffer;\n\n if (getenv(\"PWD\"))\n {\n arg_buffer << getenv(\"PWD\");\n arg_buffer << \"\/\";\n }\n arg_buffer << GEARMAND_BINARY;\n\n if (access(arg_buffer.str().c_str(), X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_drizzled()\n{\n if (HAVE_DRIZZLED_BINARY)\n {\n if (access(DRIZZLED_BINARY, X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_memcached()\n{\n if (HAVE_MEMCACHED_BINARY)\n {\n std::stringstream arg_buffer;\n\n if (getenv(\"PWD\") and strcmp(MEMCACHED_BINARY, \"memcached\/memcached\") == 0)\n {\n arg_buffer << getenv(\"PWD\");\n arg_buffer << \"\/\";\n }\n arg_buffer << MEMCACHED_BINARY;\n\n if (access(arg_buffer.str().c_str(), X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_memcached_sasl()\n{\n if (HAVE_MEMCACHED_SASL_BINARY)\n {\n if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/ namespace libtest\n<commit_msg>Make sure that gearman, is libtool'ized correctly.<commit_after>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n *\n * Data Differential YATL (i.e. libtest) library\n *\n * Copyright (C) 2012 Data Differential, http:\/\/datadifferential.com\/\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <config.h>\n#include <libtest\/common.h>\n\n#include <cstdlib>\n#include <unistd.h>\n\nnamespace libtest {\n\nbool has_libmemcached(void)\n{\n if (HAVE_LIBMEMCACHED)\n {\n return true;\n }\n\n return false;\n}\n\nbool has_libdrizzle(void)\n{\n if (HAVE_LIBDRIZZLE)\n {\n return true;\n }\n\n return false;\n}\n\nbool has_postgres_support(void)\n{\n if (getenv(\"POSTGES_IS_RUNNING_AND_SETUP\"))\n {\n if (HAVE_LIBPQ)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\nbool has_gearmand()\n{\n if (HAVE_GEARMAND_BINARY)\n {\n std::stringstream arg_buffer;\n\n if (getenv(\"PWD\") and strcmp(MEMCACHED_BINARY, \"gearmand\/gearmand\") == 0)\n {\n arg_buffer << getenv(\"PWD\");\n arg_buffer << \"\/\";\n }\n arg_buffer << GEARMAND_BINARY;\n\n if (access(arg_buffer.str().c_str(), X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_drizzled()\n{\n if (HAVE_DRIZZLED_BINARY)\n {\n if (access(DRIZZLED_BINARY, X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_memcached()\n{\n if (HAVE_MEMCACHED_BINARY)\n {\n std::stringstream arg_buffer;\n\n if (getenv(\"PWD\") and strcmp(MEMCACHED_BINARY, \"memcached\/memcached\") == 0)\n {\n arg_buffer << getenv(\"PWD\");\n arg_buffer << \"\/\";\n }\n arg_buffer << MEMCACHED_BINARY;\n\n if (access(arg_buffer.str().c_str(), X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool has_memcached_sasl()\n{\n if (HAVE_MEMCACHED_SASL_BINARY)\n {\n if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)\n {\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/ namespace libtest\n<|endoftext|>"} {"text":"<commit_before>#include \"parse.hpp\"\n\n#include \"sexpr.hpp\"\n#include \"syntax.hpp\"\n\nnamespace lisp {\n\n parse::any<sexpr> parser() {\n \n using namespace parse;\n\n const auto alpha = debug(\"alpha\") >>= chr<std::isalpha>();\n const auto alnum = debug(\"alnum\") >>= chr<std::isalnum>();\n const auto space = debug(\"space\") >>= chr<std::isspace>();\n \n const auto dquote = chr('\"');\n \n \/\/ const auto endl = chr('\\n');\n \/\/ const auto comment = (chr(';'), kleene(!endl), endl);\n\n const auto as_sexpr = cast<sexpr>();\n \n const auto real = debug(\"real\") >>= \n lit<lisp::real>() >> as_sexpr;\n \n const auto integer = debug(\"integer\") >>=\n lit<lisp::integer>() >> as_sexpr;\n \n const auto symbol = debug(\"symbol\") >>=\n no_skip(alpha >> [alnum](char first) {\n return *alnum >> [first](std::deque<char>&& chars) {\n chars.emplace_front(first);\n const lisp::string str(chars.begin(), chars.end());\n return pure<sexpr>( lisp::symbol(str) );\n };\n });\n \n const auto string = debug(\"string\") >>=\n no_skip( (dquote, *!dquote) >> [dquote](std::deque<char>&& chars) {\n ref<lisp::string> str = make_ref<lisp::string>(chars.begin(), chars.end());\n return dquote, pure<sexpr>(str);\n });\n \n const auto atom = debug(\"atom\") >>=\n string | symbol | integer | real;\n \n struct expr_tag;\n rec<sexpr, expr_tag> expr;\n \n const auto list = debug(\"list\") >>=\n no_skip( (chr('('), *space, expr % +space) >> [space](std::deque<sexpr>&& terms) {\n return *space, chr(')'), pure<sexpr>(lisp::make_list<sexpr>(terms.begin(), terms.end()));\n });\n\n const auto quote = chr('\\'');\n const auto quoted_expr = no_skip(quote >> then(expr) >> [](sexpr&& e) {\n return pure<sexpr>( lisp::symbol(kw::quote) >>= e >>= sexpr::list() );\n });\n \n expr = debug(\"expr\") >>=\n atom | list | quoted_expr;\n \n return expr;\n }\n\n}\n<commit_msg>fixed grammar for reals<commit_after>#include \"parse.hpp\"\n\n#include \"sexpr.hpp\"\n#include \"syntax.hpp\"\n\nnamespace lisp {\n\n parse::any<sexpr> parser() {\n \n using namespace parse;\n\n const auto alpha = debug(\"alpha\") >>= chr<std::isalpha>();\n const auto alnum = debug(\"alnum\") >>= chr<std::isalnum>();\n const auto space = debug(\"space\") >>= chr<std::isspace>();\n \n const auto dquote = chr('\"');\n \n \/\/ const auto endl = chr('\\n');\n \/\/ const auto comment = (chr(';'), kleene(!endl), endl);\n\n const auto as_sexpr = cast<sexpr>();\n \n const auto real = debug(\"real\") >>= \n lit<lisp::real>() >> as_sexpr;\n \n const auto integer = debug(\"integer\") >>=\n lit<lisp::integer>() >> as_sexpr;\n \n const auto symbol = debug(\"symbol\") >>=\n no_skip(alpha >> [alnum](char first) {\n return *alnum >> [first](std::deque<char>&& chars) {\n chars.emplace_front(first);\n const lisp::string str(chars.begin(), chars.end());\n return pure<sexpr>( lisp::symbol(str) );\n };\n });\n \n const auto string = debug(\"string\") >>=\n no_skip( (dquote, *!dquote) >> [dquote](std::deque<char>&& chars) {\n ref<lisp::string> str = make_ref<lisp::string>(chars.begin(), chars.end());\n return dquote, pure<sexpr>(str);\n });\n \n const auto atom = debug(\"atom\") >>=\n string | symbol | real | integer;\n \n struct expr_tag;\n rec<sexpr, expr_tag> expr;\n \n const auto list = debug(\"list\") >>=\n no_skip( (chr('('), *space, expr % +space) >> [space](std::deque<sexpr>&& terms) {\n return *space, chr(')'), pure<sexpr>(lisp::make_list<sexpr>(terms.begin(), terms.end()));\n });\n\n const auto quote = chr('\\'');\n const auto quoted_expr = no_skip(quote >> then(expr) >> [](sexpr&& e) {\n return pure<sexpr>( lisp::symbol(kw::quote) >>= e >>= sexpr::list() );\n });\n \n expr = debug(\"expr\") >>=\n atom | list | quoted_expr;\n \n return expr;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use these files except in compliance with the License. You may obtain\n\/\/ a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"pch.h\"\n\n#include \"CanvasAnimatedControl.h\"\n#include \"CanvasGameLoop.h\"\n\nusing namespace ::ABI::Microsoft::Graphics::Canvas;\nusing namespace ::ABI::Microsoft::Graphics::Canvas::UI;\nusing namespace ::ABI::Microsoft::Graphics::Canvas::UI::Xaml;\nusing namespace ::Microsoft::WRL::Wrappers;\n\nclass CanvasAnimatedControlAdapter : public BaseControlAdapter<CanvasAnimatedControlTraits>,\n public std::enable_shared_from_this<CanvasAnimatedControlAdapter>\n{\n ComPtr<IThreadPoolStatics> m_threadPoolStatics;\n ComPtr<ICanvasSwapChainFactory> m_canvasSwapChainFactory;\n std::shared_ptr<CanvasSwapChainPanelAdapter> m_canvasSwapChainPanelAdapter;\n ComPtr<IActivationFactory> m_canvasSwapChainPanelActivationFactory;\n\npublic:\n CanvasAnimatedControlAdapter(IThreadPoolStatics* threadPoolStatics)\n : m_threadPoolStatics(threadPoolStatics) \n , m_canvasSwapChainPanelAdapter(std::make_shared<CanvasSwapChainPanelAdapter>()) \n {\n auto& module = Module<InProc>::GetModule();\n\n ComPtr<IActivationFactory> swapChainActivationFactory;\n\n ThrowIfFailed(module.GetActivationFactory(\n HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasSwapChain).Get(),\n &swapChainActivationFactory));\n\n m_canvasSwapChainFactory = As<ICanvasSwapChainFactory>(swapChainActivationFactory);\n\n ThrowIfFailed(module.GetActivationFactory(\n HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_UI_Xaml_CanvasSwapChainPanel).Get(),\n &m_canvasSwapChainPanelActivationFactory));\n } \n\n virtual ComPtr<CanvasSwapChainPanel> CreateCanvasSwapChainPanel() override\n {\n ComPtr<IInspectable> canvasSwapChainPanelInspectable;\n ThrowIfFailed(m_canvasSwapChainPanelActivationFactory->ActivateInstance(&canvasSwapChainPanelInspectable));\n\n auto canvasSwapChainPanel = As<ICanvasSwapChainPanel>(canvasSwapChainPanelInspectable);\n\n return static_cast<CanvasSwapChainPanel*>(canvasSwapChainPanel.Get());\n }\n\n virtual ComPtr<CanvasSwapChain> CreateCanvasSwapChain(\n ICanvasDevice* device,\n float width,\n float height,\n float dpi,\n CanvasAlphaMode alphaMode) override\n {\n ComPtr<ICanvasSwapChain> swapChain;\n\n ThrowIfFailed(m_canvasSwapChainFactory->CreateWithAllOptions(\n As<ICanvasResourceCreator>(device).Get(),\n width, \n height, \n dpi,\n PIXEL_FORMAT(B8G8R8A8UIntNormalized),\n 2, \n alphaMode,\n &swapChain));\n\n return static_cast<CanvasSwapChain*>(swapChain.Get());\n }\n\n virtual std::shared_ptr<CanvasGameLoop> CreateAndStartGameLoop(ComPtr<ISwapChainPanel> swapChainPanel, ComPtr<AnimatedControlInput> input) override\n {\n \/\/\n \/\/ This needs to start a new thread and, while executing code on that\n \/\/ thread, then get a CoreDispatcher set up on that thread, and then, on\n \/\/ the original thread, create a CanvasGameLoop that has access to that\n \/\/ dispatcher.\n \/\/\n\n class GameLoopStartup\n {\n \/\/ This mutex & condition variable are used to block the incoming\n \/\/ thread while waiting for the game loop thread to start up and set\n \/\/ the dispatcher.\n std::mutex m_mutex;\n std::condition_variable m_conditionVariable;\n \n ComPtr<ICoreDispatcher> m_dispatcher;\n\n public:\n void SetDispatcher(ICoreDispatcher* dispatcher)\n {\n Lock lock(m_mutex);\n m_dispatcher = dispatcher;\n lock.unlock();\n m_conditionVariable.notify_one();\n }\n\n void NotifyOne()\n {\n m_conditionVariable.notify_one();\n }\n\n ComPtr<ICoreDispatcher> WaitAndGetDispatcher(IAsyncAction* action)\n {\n auto info = As<IAsyncInfo>(action);\n\n Lock lock(m_mutex);\n m_conditionVariable.wait(lock,\n [&]\n {\n if (m_dispatcher)\n {\n \/\/ The dispatcher has been sent to us; we're done\n return true;\n }\n \n AsyncStatus status;\n ThrowIfFailed(info->get_Status(&status));\n\n switch (status)\n {\n case AsyncStatus::Started:\n \/\/ We're still waiting to find out\n return false;\n\n case AsyncStatus::Error:\n {\n HRESULT hr = S_OK;\n ThrowIfFailed(info->get_ErrorCode(&hr));\n ThrowHR(hr);\n }\n\n case AsyncStatus::Completed:\n return true;\n\n default:\n ThrowHR(E_UNEXPECTED);\n }\n });\n\n \/\/ We should only get here if the dispatcher was actually set.\n \/\/ All other cases should have resulted in an exception.\n assert(m_dispatcher);\n return m_dispatcher;\n }\n };\n\n auto gameLoopStartup = std::make_shared<GameLoopStartup>();\n\n auto startThreadHandler = Callback<AddFtmBase<IWorkItemHandler>::Type>(\n [=](IAsyncAction*) mutable\n {\n return ExceptionBoundary(\n [&]\n {\n auto notifyWarden = MakeScopeWarden([&] { gameLoopStartup->NotifyOne(); });\n\n auto dispatcher = CreateCoreDispatcher(swapChainPanel.Get());\n\n \/\/ Now notify the original thread that we've got the\n \/\/ dispatcher\n gameLoopStartup->SetDispatcher(dispatcher.Get());\n notifyWarden.Dismiss();\n gameLoopStartup.reset();\n\n \/\/ At this point the original thread is likely to go\n \/\/ about its business - so we cannot access anything we\n \/\/ captured by reference from it.\n \/\/\n \/\/ Which is ok, because all we want to do here is to\n \/\/ start processing events.\n\n ThrowIfFailed(dispatcher->ProcessEvents(CoreProcessEventsOption_ProcessUntilQuit));\n });\n });\n CheckMakeResult(startThreadHandler);\n\n auto action = StartThread(std::move(startThreadHandler));\n auto dispatcher = gameLoopStartup->WaitAndGetDispatcher(action.Get());\n\n return std::make_shared<CanvasGameLoop>(std::move(action), std::move(dispatcher), input);\n }\n\n static ComPtr<ICoreDispatcher> CreateCoreDispatcher(ISwapChainPanel* swapChainPanel)\n {\n \/\/ We do a little dance here to create the dispatcher.\n \/\/ We first create a core independent input source,\n \/\/ which will create a dispatcher. We then discard the\n \/\/ input source we created.\n ComPtr<ICoreInputSourceBase> inputSource;\n ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(\n CoreInputDeviceTypes_Touch | CoreInputDeviceTypes_Pen | CoreInputDeviceTypes_Mouse, \n &inputSource));\n\n ComPtr<ICoreDispatcher> dispatcher;\n ThrowIfFailed(inputSource->get_Dispatcher(&dispatcher));\n\n ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(\n CoreInputDeviceTypes_None,\n &inputSource));\n\n return dispatcher;\n }\n\n\n ComPtr<IAsyncAction> StartThread(ComPtr<IWorkItemHandler>&& handler)\n {\n ComPtr<IAsyncAction> action;\n ThrowIfFailed(m_threadPoolStatics->RunWithPriorityAndOptionsAsync(\n handler.Get(),\n WorkItemPriority_Normal,\n WorkItemOptions_TimeSliced,\n &action));\n\n return action; \n }\n\n virtual ComPtr<IInspectable> CreateSwapChainPanel(IInspectable* canvasSwapChainPanel) override\n {\n return m_canvasSwapChainPanelAdapter->CreateSwapChainPanel(canvasSwapChainPanel);\n }\n\n virtual void Sleep(DWORD timeInMs) override\n {\n ::Sleep(timeInMs);\n }\n\n virtual LARGE_INTEGER GetPerformanceCounter() override\n {\n LARGE_INTEGER counter;\n if (QueryPerformanceCounter(&counter) == 0)\n {\n ThrowHR(E_FAIL);\n }\n return counter;\n }\n\n virtual LARGE_INTEGER GetPerformanceFrequency() override\n {\n LARGE_INTEGER frequency;\n if (QueryPerformanceFrequency(&frequency) == 0)\n {\n ThrowHR(E_FAIL);\n }\n return frequency;\n }\n};\n\n\nnamespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace UI { namespace Xaml\n{\n\n std::shared_ptr<ICanvasAnimatedControlAdapter> CreateCanvasAnimatedControlAdapter()\n {\n ComPtr<IThreadPoolStatics> threadPoolStatics;\n ThrowIfFailed(GetActivationFactory(\n HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(),\n &threadPoolStatics));\n\n return std::make_shared<CanvasAnimatedControlAdapter>(threadPoolStatics.Get());\n }\n\n} } } } } }<commit_msg>Pull GameLoopStartup out of CanvasAnimatedControlAdapter::CreateAndStartGameLoop<commit_after>\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use these files except in compliance with the License. You may obtain\n\/\/ a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"pch.h\"\n\n#include \"CanvasAnimatedControl.h\"\n#include \"CanvasGameLoop.h\"\n\nusing namespace ::ABI::Microsoft::Graphics::Canvas;\nusing namespace ::ABI::Microsoft::Graphics::Canvas::UI;\nusing namespace ::ABI::Microsoft::Graphics::Canvas::UI::Xaml;\nusing namespace ::Microsoft::WRL::Wrappers;\n\n\/\/\n\/\/ Helper for CreateAndStartGameLoop, tracks state shared between the UI thread\n\/\/ and the newly created game loop thread. The game loop thread needs to\n\/\/ communicate back the ICoreDispatcher.\n\/\/\nclass GameLoopStartup\n{\n \/\/ This mutex & condition variable are used to block the incoming\n \/\/ thread while waiting for the game loop thread to start up and set\n \/\/ the dispatcher.\n std::mutex m_mutex;\n std::condition_variable m_conditionVariable;\n \n ComPtr<ICoreDispatcher> m_dispatcher;\n\npublic:\n void SetDispatcher(ICoreDispatcher* dispatcher)\n {\n Lock lock(m_mutex);\n m_dispatcher = dispatcher;\n lock.unlock();\n m_conditionVariable.notify_one();\n }\n\n void NotifyOne()\n {\n m_conditionVariable.notify_one();\n }\n\n ComPtr<ICoreDispatcher> WaitAndGetDispatcher(IAsyncAction* action)\n {\n auto info = As<IAsyncInfo>(action);\n\n Lock lock(m_mutex);\n m_conditionVariable.wait(lock,\n [&]\n {\n if (m_dispatcher)\n {\n \/\/ The dispatcher has been sent to us; we're done\n return true;\n }\n \n AsyncStatus status;\n ThrowIfFailed(info->get_Status(&status));\n\n switch (status)\n {\n case AsyncStatus::Started:\n \/\/ We're still waiting to find out\n return false;\n\n case AsyncStatus::Error:\n {\n HRESULT hr = S_OK;\n ThrowIfFailed(info->get_ErrorCode(&hr));\n ThrowHR(hr);\n }\n\n case AsyncStatus::Completed:\n return true;\n\n default:\n ThrowHR(E_UNEXPECTED);\n }\n });\n\n \/\/ We should only get here if the dispatcher was actually set.\n \/\/ All other cases should have resulted in an exception.\n assert(m_dispatcher);\n return m_dispatcher;\n }\n};\n\n\/\/\n\/\/ Creates a CoreDispatcher for the current thread.\n\/\/\n\/\/ We do a little dance here to create the dispatcher. We first create a core\n\/\/ independent input source (via the swapChainPanel), which will create a\n\/\/ dispatcher. We then discard the input source we created.\n\/\/\nstatic ComPtr<ICoreDispatcher> CreateCoreDispatcher(ISwapChainPanel* swapChainPanel)\n{\n ComPtr<ICoreInputSourceBase> inputSource;\n ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(\n CoreInputDeviceTypes_Touch | CoreInputDeviceTypes_Pen | CoreInputDeviceTypes_Mouse, \n &inputSource));\n\n ComPtr<ICoreDispatcher> dispatcher;\n ThrowIfFailed(inputSource->get_Dispatcher(&dispatcher));\n\n ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(\n CoreInputDeviceTypes_None,\n &inputSource));\n\n return dispatcher;\n}\n\n\/\/\n\/\/ CanvasAnimatedControlAdapter\n\/\/\n\nclass CanvasAnimatedControlAdapter : public BaseControlAdapter<CanvasAnimatedControlTraits>,\n public std::enable_shared_from_this<CanvasAnimatedControlAdapter>\n{\n ComPtr<IThreadPoolStatics> m_threadPoolStatics;\n ComPtr<ICanvasSwapChainFactory> m_canvasSwapChainFactory;\n std::shared_ptr<CanvasSwapChainPanelAdapter> m_canvasSwapChainPanelAdapter;\n ComPtr<IActivationFactory> m_canvasSwapChainPanelActivationFactory;\n\npublic:\n CanvasAnimatedControlAdapter(IThreadPoolStatics* threadPoolStatics)\n : m_threadPoolStatics(threadPoolStatics) \n , m_canvasSwapChainPanelAdapter(std::make_shared<CanvasSwapChainPanelAdapter>()) \n {\n auto& module = Module<InProc>::GetModule();\n\n ComPtr<IActivationFactory> swapChainActivationFactory;\n\n ThrowIfFailed(module.GetActivationFactory(\n HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasSwapChain).Get(),\n &swapChainActivationFactory));\n\n m_canvasSwapChainFactory = As<ICanvasSwapChainFactory>(swapChainActivationFactory);\n\n ThrowIfFailed(module.GetActivationFactory(\n HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_UI_Xaml_CanvasSwapChainPanel).Get(),\n &m_canvasSwapChainPanelActivationFactory));\n } \n\n virtual ComPtr<CanvasSwapChainPanel> CreateCanvasSwapChainPanel() override\n {\n ComPtr<IInspectable> canvasSwapChainPanelInspectable;\n ThrowIfFailed(m_canvasSwapChainPanelActivationFactory->ActivateInstance(&canvasSwapChainPanelInspectable));\n\n auto canvasSwapChainPanel = As<ICanvasSwapChainPanel>(canvasSwapChainPanelInspectable);\n\n return static_cast<CanvasSwapChainPanel*>(canvasSwapChainPanel.Get());\n }\n\n virtual ComPtr<CanvasSwapChain> CreateCanvasSwapChain(\n ICanvasDevice* device,\n float width,\n float height,\n float dpi,\n CanvasAlphaMode alphaMode) override\n {\n ComPtr<ICanvasSwapChain> swapChain;\n\n ThrowIfFailed(m_canvasSwapChainFactory->CreateWithAllOptions(\n As<ICanvasResourceCreator>(device).Get(),\n width, \n height, \n dpi,\n PIXEL_FORMAT(B8G8R8A8UIntNormalized),\n 2, \n alphaMode,\n &swapChain));\n\n return static_cast<CanvasSwapChain*>(swapChain.Get());\n }\n\n virtual std::shared_ptr<CanvasGameLoop> CreateAndStartGameLoop(ComPtr<ISwapChainPanel> swapChainPanel, ComPtr<AnimatedControlInput> input) override\n {\n \/\/\n \/\/ This needs to start a new thread and, while executing code on that\n \/\/ thread, then get a CoreDispatcher set up on that thread, and then, on\n \/\/ the original thread, create a CanvasGameLoop that has access to that\n \/\/ dispatcher.\n \/\/\n\n auto gameLoopStartup = std::make_shared<GameLoopStartup>();\n\n auto startThreadHandler = Callback<AddFtmBase<IWorkItemHandler>::Type>(\n [=](IAsyncAction*) mutable\n {\n return ExceptionBoundary(\n [&]\n {\n auto notifyWarden = MakeScopeWarden([&] { gameLoopStartup->NotifyOne(); });\n\n auto dispatcher = CreateCoreDispatcher(swapChainPanel.Get());\n\n \/\/ Now notify the original thread that we've got the\n \/\/ dispatcher\n gameLoopStartup->SetDispatcher(dispatcher.Get());\n notifyWarden.Dismiss();\n gameLoopStartup.reset();\n\n \/\/ At this point the original thread is likely to go\n \/\/ about its business - so we cannot access anything we\n \/\/ captured by reference from it.\n \/\/\n \/\/ Which is ok, because all we want to do here is to\n \/\/ start processing events.\n\n ThrowIfFailed(dispatcher->ProcessEvents(CoreProcessEventsOption_ProcessUntilQuit));\n });\n });\n CheckMakeResult(startThreadHandler);\n\n auto action = StartThread(std::move(startThreadHandler));\n auto dispatcher = gameLoopStartup->WaitAndGetDispatcher(action.Get());\n\n return std::make_shared<CanvasGameLoop>(std::move(action), std::move(dispatcher), input);\n }\n\n virtual ComPtr<IInspectable> CreateSwapChainPanel(IInspectable* canvasSwapChainPanel) override\n {\n return m_canvasSwapChainPanelAdapter->CreateSwapChainPanel(canvasSwapChainPanel);\n }\n\n virtual void Sleep(DWORD timeInMs) override\n {\n ::Sleep(timeInMs);\n }\n\n virtual LARGE_INTEGER GetPerformanceCounter() override\n {\n LARGE_INTEGER counter;\n if (QueryPerformanceCounter(&counter) == 0)\n {\n ThrowHR(E_FAIL);\n }\n return counter;\n }\n\n virtual LARGE_INTEGER GetPerformanceFrequency() override\n {\n LARGE_INTEGER frequency;\n if (QueryPerformanceFrequency(&frequency) == 0)\n {\n ThrowHR(E_FAIL);\n }\n return frequency;\n }\n\nprivate:\n ComPtr<IAsyncAction> StartThread(ComPtr<IWorkItemHandler>&& handler)\n {\n ComPtr<IAsyncAction> action;\n ThrowIfFailed(m_threadPoolStatics->RunWithPriorityAndOptionsAsync(\n handler.Get(),\n WorkItemPriority_Normal,\n WorkItemOptions_TimeSliced,\n &action));\n\n return action; \n }\n};\n\n\nnamespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace UI { namespace Xaml\n{\n\n std::shared_ptr<ICanvasAnimatedControlAdapter> CreateCanvasAnimatedControlAdapter()\n {\n ComPtr<IThreadPoolStatics> threadPoolStatics;\n ThrowIfFailed(GetActivationFactory(\n HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(),\n &threadPoolStatics));\n\n return std::make_shared<CanvasAnimatedControlAdapter>(threadPoolStatics.Get());\n }\n\n} } } } } }<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: PageHeaderFooterContext.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX\n#include \"PageHeaderFooterContext.hxx\"\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX\n#include \"PagePropertySetContext.hxx\"\n#endif\n\nusing namespace com::sun::star;\nusing ::xmloff::token::IsXMLToken;\nusing ::xmloff::token::XML_PROPERTIES;\n\n\/\/------------------------------------------------------------------\n\nPageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport,\n USHORT nPrfx,\n const rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList,\n ::std::vector< XMLPropertyState > & rTempProperties,\n const UniReference < SvXMLImportPropertyMapper > &rTempMap,\n sal_Int32 nStart, sal_Int32 nEnd,\n const sal_Bool bTempHeader ) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n rProperties(rTempProperties),\n rMap(rTempMap),\n nStartIndex(nStart),\n nEndIndex(nEnd)\n{\n bHeader = bTempHeader;\n}\n\nPageHeaderFooterContext::~PageHeaderFooterContext()\n{\n}\n\nSvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix,\n const rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_PROPERTIES ) )\n {\n PageContextType aType = Header;\n if (!bHeader)\n aType = Footer;\n pContext = new PagePropertySetContext( GetImport(), nPrefix,\n rLName, xAttrList,\n rProperties,\n rMap, nStartIndex, nEndIndex, aType);\n }\n\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );\n\n return pContext;\n}\n\nvoid PageHeaderFooterContext::EndElement()\n{\n}\n\n<commit_msg>INTEGRATION: CWS oasis (1.4.276); FILE MERGED 2004\/04\/21 07:27:22 mib 1.4.276.2: - separated attribute lists for <*-properties> elements on import (#i20153#) - replaced \"style:text-backgroubnd-color\" with \"fo:background-color\" 2004\/04\/07 11:49:55 mib 1.4.276.1: splitted <properties><commit_after>\/*************************************************************************\n *\n * $RCSfile: PageHeaderFooterContext.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 08:19:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX\n#include \"PageHeaderFooterContext.hxx\"\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include \"xmltoken.hxx\"\n#endif\n#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX\n#include \"PagePropertySetContext.hxx\"\n#endif\n\nusing namespace com::sun::star;\nusing ::xmloff::token::IsXMLToken;\nusing ::xmloff::token::XML_HEADER_FOOTER_PROPERTIES;\n\n\/\/------------------------------------------------------------------\n\nPageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport,\n USHORT nPrfx,\n const rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList,\n ::std::vector< XMLPropertyState > & rTempProperties,\n const UniReference < SvXMLImportPropertyMapper > &rTempMap,\n sal_Int32 nStart, sal_Int32 nEnd,\n const sal_Bool bTempHeader ) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n rProperties(rTempProperties),\n rMap(rTempMap),\n nStartIndex(nStart),\n nEndIndex(nEnd)\n{\n bHeader = bTempHeader;\n}\n\nPageHeaderFooterContext::~PageHeaderFooterContext()\n{\n}\n\nSvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix,\n const rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_HEADER_FOOTER_PROPERTIES ) )\n {\n PageContextType aType = Header;\n if (!bHeader)\n aType = Footer;\n pContext = new PagePropertySetContext( GetImport(), nPrefix,\n rLName, xAttrList,\n XML_TYPE_PROP_HEADER_FOOTER,\n rProperties,\n rMap, nStartIndex, nEndIndex, aType);\n }\n\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );\n\n return pContext;\n}\n\nvoid PageHeaderFooterContext::EndElement()\n{\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLTextListAutoStylePool.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 18:46:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _CNTRSRT_HXX\n#include <svtools\/cntnrsrt.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_\n#include <com\/sun\/star\/ucb\/XAnyCompareFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_\n#include <com\/sun\/star\/container\/XNamed.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_\n#include <com\/sun\/star\/container\/XIndexReplace.hpp>\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLNUME_HXX\n#include \"xmlnume.hxx\"\n#endif\n#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX\n#include \"XMLTextListAutoStylePool.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::style;\n\n\nint XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,\n const OUString& r2 )\n{\n return (int)r1.compareTo( r2 );\n}\n\nDECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,\n OUString )\nIMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,\n OUString,\n XMLTextListAutoStylePoolNameCmp_Impl )\n\nclass XMLTextListAutoStylePoolEntry_Impl\n{\n OUString sName;\n OUString sInternalName;\n Reference < XIndexReplace > xNumRules;\n sal_uInt32 nPos;\n sal_Bool bIsNamed;\n\n\npublic:\n\n XMLTextListAutoStylePoolEntry_Impl(\n sal_uInt32 nPos,\n const Reference < XIndexReplace > & rNumRules,\n XMLTextListAutoStylePoolNames_Impl& rNames,\n const OUString& rPrefix,\n sal_uInt32& rName );\n\n XMLTextListAutoStylePoolEntry_Impl(\n const Reference < XIndexReplace > & rNumRules ) :\n xNumRules( rNumRules ),\n nPos( 0 ),\n bIsNamed( sal_False )\n {\n Reference < XNamed > xNamed( xNumRules, UNO_QUERY );\n if( xNamed.is() )\n {\n sInternalName = xNamed->getName();\n bIsNamed = sal_True;\n }\n }\n\n XMLTextListAutoStylePoolEntry_Impl(\n const OUString& rInternalName ) :\n sInternalName( rInternalName ),\n nPos( 0 ),\n bIsNamed( sal_True )\n {\n }\n\n const OUString& GetName() const { return sName; }\n const OUString& GetInternalName() const { return sInternalName; }\n const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }\n sal_uInt32 GetPos() const { return nPos; }\n sal_Bool IsNamed() const { return bIsNamed; }\n};\n\nXMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(\n sal_uInt32 nP,\n const Reference < XIndexReplace > & rNumRules,\n XMLTextListAutoStylePoolNames_Impl& rNames,\n const OUString& rPrefix,\n sal_uInt32& rName ) :\n xNumRules( rNumRules ),\n nPos( nP ),\n bIsNamed( sal_False )\n{\n Reference < XNamed > xNamed( xNumRules, UNO_QUERY );\n if( xNamed.is() )\n {\n sInternalName = xNamed->getName();\n bIsNamed = sal_True;\n }\n\n \/\/ create a name that hasn't been used before. The created name has not\n \/\/ to be added to the array, because it will never tried again\n OUStringBuffer sBuffer( 7 );\n do\n {\n rName++;\n sBuffer.append( rPrefix );\n sBuffer.append( (sal_Int32)rName );\n sName = sBuffer.makeStringAndClear();\n }\n while( rNames.Seek_Entry( &sName, 0 ) );\n}\n\nint XMLTextListAutoStylePoolEntryCmp_Impl(\n const XMLTextListAutoStylePoolEntry_Impl& r1,\n const XMLTextListAutoStylePoolEntry_Impl& r2 )\n{\n int nRet;\n if( r1.IsNamed() )\n {\n if( r2.IsNamed() )\n nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());\n else\n nRet = -1;\n }\n else\n {\n if( r2.IsNamed() )\n nRet = 1;\n else\n nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());\n }\n\n return nRet;\n}\n\ntypedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;\nDECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,\n XMLTextListAutoStylePoolEntry_Impl )\nIMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,\n XMLTextListAutoStylePoolEntry_Impl,\n XMLTextListAutoStylePoolEntryCmp_Impl )\n\nXMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :\n rExport( rExp ),\n sPrefix( RTL_CONSTASCII_USTRINGPARAM(\"L\") ),\n pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),\n pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),\n nName( 0 )\n{\n Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );\n if( xCompareFac.is() )\n mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( \"NumberingRules\" ) ) );\n}\n\nXMLTextListAutoStylePool::~XMLTextListAutoStylePool()\n{\n delete pPool;\n delete pNames;\n}\n\nvoid XMLTextListAutoStylePool::RegisterName( const OUString& rName )\n{\n OUString *pName = new OUString( rName );\n if( !pNames->Insert( pName ) )\n delete pName;\n}\n\nsal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const\n{\n return pNames->Seek_Entry( &rName, 0 );\n}\n\nsal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const\n{\n ULONG nPos;\n if( !pEntry->IsNamed() && mxNumRuleCompare.is() )\n {\n const sal_uInt32 nCount = pPool->Count();\n\n uno::Any aAny1, aAny2;\n aAny1 <<= pEntry->GetNumRules();\n\n for( nPos = 0; nPos < nCount; nPos++ )\n {\n aAny2 <<= pPool->GetObject(nPos)->GetNumRules();\n\n if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )\n return nPos;\n }\n }\n else if( pPool->Seek_Entry( pEntry, &nPos ) )\n {\n return nPos;\n }\n\n return (sal_uInt32)-1;\n}\n\nOUString XMLTextListAutoStylePool::Add(\n const Reference < XIndexReplace > & rNumRules )\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );\n\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n {\n sName = pPool->GetObject( nPos )->GetName();\n }\n else\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry =\n new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),\n rNumRules, *pNames, sPrefix,\n nName );\n pPool->Insert( pEntry );\n sName = pEntry->GetName();\n }\n\n return sName;\n}\n\n::rtl::OUString XMLTextListAutoStylePool::Find(\n const Reference < XIndexReplace > & rNumRules ) const\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );\n\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n sName = pPool->GetObject( nPos )->GetName();\n\n return sName;\n}\n\n::rtl::OUString XMLTextListAutoStylePool::Find(\n const OUString& rInternalName ) const\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n sName = pPool->GetObject( nPos )->GetName();\n\n return sName;\n}\n\nvoid XMLTextListAutoStylePool::exportXML() const\n{\n sal_uInt32 nCount = pPool->Count();\n if( !nCount )\n return;\n\n XMLTextListAutoStylePoolEntry_Impl **aExpEntries =\n new XMLTextListAutoStylePoolEntryPtr[nCount];\n\n sal_uInt32 i;\n for( i=0; i < nCount; i++ )\n {\n aExpEntries[i] = 0;\n }\n for( i=0; i < nCount; i++ )\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);\n DBG_ASSERT( pEntry->GetPos() < nCount, \"Illegal pos\" );\n aExpEntries[pEntry->GetPos()] = pEntry;\n }\n\n SvxXMLNumRuleExport aNumRuleExp( rExport );\n\n for( i=0; i < nCount; i++ )\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];\n aNumRuleExp.exportNumberingRule( pEntry->GetName(),\n pEntry->GetNumRules() );\n }\n delete [] aExpEntries;\n}\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.34); FILE MERGED 2006\/09\/01 18:00:07 kaib 1.7.34.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLTextListAutoStylePool.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 11:13:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _CNTRSRT_HXX\n#include <svtools\/cntnrsrt.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_\n#include <com\/sun\/star\/ucb\/XAnyCompareFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_\n#include <com\/sun\/star\/container\/XNamed.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_\n#include <com\/sun\/star\/container\/XIndexReplace.hpp>\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLNUME_HXX\n#include \"xmlnume.hxx\"\n#endif\n#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX\n#include \"XMLTextListAutoStylePool.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::style;\n\n\nint XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,\n const OUString& r2 )\n{\n return (int)r1.compareTo( r2 );\n}\n\nDECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,\n OUString )\nIMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,\n OUString,\n XMLTextListAutoStylePoolNameCmp_Impl )\n\nclass XMLTextListAutoStylePoolEntry_Impl\n{\n OUString sName;\n OUString sInternalName;\n Reference < XIndexReplace > xNumRules;\n sal_uInt32 nPos;\n sal_Bool bIsNamed;\n\n\npublic:\n\n XMLTextListAutoStylePoolEntry_Impl(\n sal_uInt32 nPos,\n const Reference < XIndexReplace > & rNumRules,\n XMLTextListAutoStylePoolNames_Impl& rNames,\n const OUString& rPrefix,\n sal_uInt32& rName );\n\n XMLTextListAutoStylePoolEntry_Impl(\n const Reference < XIndexReplace > & rNumRules ) :\n xNumRules( rNumRules ),\n nPos( 0 ),\n bIsNamed( sal_False )\n {\n Reference < XNamed > xNamed( xNumRules, UNO_QUERY );\n if( xNamed.is() )\n {\n sInternalName = xNamed->getName();\n bIsNamed = sal_True;\n }\n }\n\n XMLTextListAutoStylePoolEntry_Impl(\n const OUString& rInternalName ) :\n sInternalName( rInternalName ),\n nPos( 0 ),\n bIsNamed( sal_True )\n {\n }\n\n const OUString& GetName() const { return sName; }\n const OUString& GetInternalName() const { return sInternalName; }\n const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }\n sal_uInt32 GetPos() const { return nPos; }\n sal_Bool IsNamed() const { return bIsNamed; }\n};\n\nXMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(\n sal_uInt32 nP,\n const Reference < XIndexReplace > & rNumRules,\n XMLTextListAutoStylePoolNames_Impl& rNames,\n const OUString& rPrefix,\n sal_uInt32& rName ) :\n xNumRules( rNumRules ),\n nPos( nP ),\n bIsNamed( sal_False )\n{\n Reference < XNamed > xNamed( xNumRules, UNO_QUERY );\n if( xNamed.is() )\n {\n sInternalName = xNamed->getName();\n bIsNamed = sal_True;\n }\n\n \/\/ create a name that hasn't been used before. The created name has not\n \/\/ to be added to the array, because it will never tried again\n OUStringBuffer sBuffer( 7 );\n do\n {\n rName++;\n sBuffer.append( rPrefix );\n sBuffer.append( (sal_Int32)rName );\n sName = sBuffer.makeStringAndClear();\n }\n while( rNames.Seek_Entry( &sName, 0 ) );\n}\n\nint XMLTextListAutoStylePoolEntryCmp_Impl(\n const XMLTextListAutoStylePoolEntry_Impl& r1,\n const XMLTextListAutoStylePoolEntry_Impl& r2 )\n{\n int nRet;\n if( r1.IsNamed() )\n {\n if( r2.IsNamed() )\n nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());\n else\n nRet = -1;\n }\n else\n {\n if( r2.IsNamed() )\n nRet = 1;\n else\n nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());\n }\n\n return nRet;\n}\n\ntypedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;\nDECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,\n XMLTextListAutoStylePoolEntry_Impl )\nIMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,\n XMLTextListAutoStylePoolEntry_Impl,\n XMLTextListAutoStylePoolEntryCmp_Impl )\n\nXMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :\n rExport( rExp ),\n sPrefix( RTL_CONSTASCII_USTRINGPARAM(\"L\") ),\n pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),\n pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),\n nName( 0 )\n{\n Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );\n if( xCompareFac.is() )\n mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( \"NumberingRules\" ) ) );\n}\n\nXMLTextListAutoStylePool::~XMLTextListAutoStylePool()\n{\n delete pPool;\n delete pNames;\n}\n\nvoid XMLTextListAutoStylePool::RegisterName( const OUString& rName )\n{\n OUString *pName = new OUString( rName );\n if( !pNames->Insert( pName ) )\n delete pName;\n}\n\nsal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const\n{\n return pNames->Seek_Entry( &rName, 0 );\n}\n\nsal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const\n{\n ULONG nPos;\n if( !pEntry->IsNamed() && mxNumRuleCompare.is() )\n {\n const sal_uInt32 nCount = pPool->Count();\n\n uno::Any aAny1, aAny2;\n aAny1 <<= pEntry->GetNumRules();\n\n for( nPos = 0; nPos < nCount; nPos++ )\n {\n aAny2 <<= pPool->GetObject(nPos)->GetNumRules();\n\n if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )\n return nPos;\n }\n }\n else if( pPool->Seek_Entry( pEntry, &nPos ) )\n {\n return nPos;\n }\n\n return (sal_uInt32)-1;\n}\n\nOUString XMLTextListAutoStylePool::Add(\n const Reference < XIndexReplace > & rNumRules )\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );\n\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n {\n sName = pPool->GetObject( nPos )->GetName();\n }\n else\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry =\n new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),\n rNumRules, *pNames, sPrefix,\n nName );\n pPool->Insert( pEntry );\n sName = pEntry->GetName();\n }\n\n return sName;\n}\n\n::rtl::OUString XMLTextListAutoStylePool::Find(\n const Reference < XIndexReplace > & rNumRules ) const\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );\n\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n sName = pPool->GetObject( nPos )->GetName();\n\n return sName;\n}\n\n::rtl::OUString XMLTextListAutoStylePool::Find(\n const OUString& rInternalName ) const\n{\n OUString sName;\n XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );\n sal_uInt32 nPos = Find( &aTmp );\n if( nPos != (sal_uInt32)-1 )\n sName = pPool->GetObject( nPos )->GetName();\n\n return sName;\n}\n\nvoid XMLTextListAutoStylePool::exportXML() const\n{\n sal_uInt32 nCount = pPool->Count();\n if( !nCount )\n return;\n\n XMLTextListAutoStylePoolEntry_Impl **aExpEntries =\n new XMLTextListAutoStylePoolEntryPtr[nCount];\n\n sal_uInt32 i;\n for( i=0; i < nCount; i++ )\n {\n aExpEntries[i] = 0;\n }\n for( i=0; i < nCount; i++ )\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);\n DBG_ASSERT( pEntry->GetPos() < nCount, \"Illegal pos\" );\n aExpEntries[pEntry->GetPos()] = pEntry;\n }\n\n SvxXMLNumRuleExport aNumRuleExp( rExport );\n\n for( i=0; i < nCount; i++ )\n {\n XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];\n aNumRuleExp.exportNumberingRule( pEntry->GetName(),\n pEntry->GetNumRules() );\n }\n delete [] aExpEntries;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"common_headers.h\"\n\n#include \"tests\/common.h\"\n#include \"branch.h\"\n#include \"operations.h\"\n#include \"term.h\"\n#include \"term_list.h\"\n#include \"term_namespace.h\"\n#include \"term_set.h\"\n#include \"value_map.h\"\n\nnamespace circa {\nnamespace container_tests {\n\nvoid test_set()\n{\n TermSet set;\n\n Term* term1 = new Term();\n\n test_assert(!set.contains(term1));\n test_assert(set.count() == 0);\n\n set.add(term1);\n\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n set.add(term1);\n\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n Term* term2 = new Term();\n set.add(term2);\n\n test_assert(set.contains(term2));\n test_assert(set.count() == 2);\n\n set.remove(term1);\n\n test_assert(!set.contains(term1));\n test_assert(set.count() == 1);\n\n set.remove(term2);\n\n test_assert(!set.contains(term2));\n test_assert(set.count() == 0);\n\n set.add(term1);\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n \/*TermMap remap;\n remap[term1] = term2;\n set.remapPointers(remap);\n test_assert(set.contains(term2));\n test_assert(set.count() == 1);*\/\n}\n\nvoid test_namespace()\n{\n TermNamespace nspace;\n Term *term = new Term();\n\n nspace.bind(term, \"a\");\n test_assert(nspace.contains(\"a\"));\n test_assert(nspace[\"a\"] == term);\n\n Term *term2 = new Term();\n TermMap remap;\n remap[term] = term2;\n nspace.remapPointers(remap);\n test_assert(nspace[\"a\"] == term2);\n\n test_assert(nspace.contains(\"a\"));\n remap[term2] = NULL;\n nspace.remapPointers(remap);\n test_assert(!nspace.contains(\"a\"));\n}\n\nvoid test_list()\n{\n TermList list;\n Term* term = new Term();\n Term* term2 = new Term();\n\n test_assert(list.count() == 0);\n\n list.append(term);\n list.append(term2);\n test_assert(list.count() == 2);\n test_assert(list[0] == term);\n test_assert(list[1] == term2);\n\n Term* term3 = new Term();\n TermMap remap;\n remap[term] = term3;\n list.remapPointers(remap);\n test_assert(list.count() == 2);\n test_assert(list[0] == term3);\n test_assert(list[1] == term2);\n\n list.clear();\n\n test_assert(list.count() == 0);\n}\n\nvoid value_map()\n{\n Branch branch;\n ValueMap map;\n\n Term* two = constant_int(&branch, 2);\n Term* hi = constant_string(&branch, \"hi\");\n\n map.set(two, hi);\n\n\n\n\n\n}\n\n} \/\/ namespace container_tests\n\nvoid register_container_tests()\n{\n REGISTER_TEST_CASE(container_tests::test_set);\n REGISTER_TEST_CASE(container_tests::test_namespace);\n REGISTER_TEST_CASE(container_tests::test_list);\n REGISTER_TEST_CASE(container_tests::value_map);\n}\n\n} \/\/ namespace circa\n<commit_msg>Added container_tests::value_map<commit_after>\n#include \"common_headers.h\"\n\n#include \"tests\/common.h\"\n#include \"branch.h\"\n#include \"builtins.h\"\n#include \"operations.h\"\n#include \"term.h\"\n#include \"term_list.h\"\n#include \"term_namespace.h\"\n#include \"term_set.h\"\n#include \"value_map.h\"\n\nnamespace circa {\nnamespace container_tests {\n\nvoid test_set()\n{\n TermSet set;\n\n Term* term1 = new Term();\n\n test_assert(!set.contains(term1));\n test_assert(set.count() == 0);\n\n set.add(term1);\n\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n set.add(term1);\n\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n Term* term2 = new Term();\n set.add(term2);\n\n test_assert(set.contains(term2));\n test_assert(set.count() == 2);\n\n set.remove(term1);\n\n test_assert(!set.contains(term1));\n test_assert(set.count() == 1);\n\n set.remove(term2);\n\n test_assert(!set.contains(term2));\n test_assert(set.count() == 0);\n\n set.add(term1);\n test_assert(set.contains(term1));\n test_assert(set.count() == 1);\n\n \/*TermMap remap;\n remap[term1] = term2;\n set.remapPointers(remap);\n test_assert(set.contains(term2));\n test_assert(set.count() == 1);*\/\n}\n\nvoid test_namespace()\n{\n TermNamespace nspace;\n Term *term = new Term();\n\n nspace.bind(term, \"a\");\n test_assert(nspace.contains(\"a\"));\n test_assert(nspace[\"a\"] == term);\n\n Term *term2 = new Term();\n TermMap remap;\n remap[term] = term2;\n nspace.remapPointers(remap);\n test_assert(nspace[\"a\"] == term2);\n\n test_assert(nspace.contains(\"a\"));\n remap[term2] = NULL;\n nspace.remapPointers(remap);\n test_assert(!nspace.contains(\"a\"));\n}\n\nvoid test_list()\n{\n TermList list;\n Term* term = new Term();\n Term* term2 = new Term();\n\n test_assert(list.count() == 0);\n\n list.append(term);\n list.append(term2);\n test_assert(list.count() == 2);\n test_assert(list[0] == term);\n test_assert(list[1] == term2);\n\n Term* term3 = new Term();\n TermMap remap;\n remap[term] = term3;\n list.remapPointers(remap);\n test_assert(list.count() == 2);\n test_assert(list[0] == term3);\n test_assert(list[1] == term2);\n\n list.clear();\n\n test_assert(list.count() == 0);\n}\n\nvoid value_map()\n{\n Branch branch;\n ValueMap map;\n\n Term* two = constant_int(&branch, 2);\n Term* another_two = constant_int(&branch, 2);\n Term* hi = constant_string(&branch, \"hi\");\n\n map.set(two, hi);\n\n \/\/ Change our version of hi to verify that ValueMap has made a duplicate\n as_string(hi) = \"hello\";\n\n test_assert(as_string(map.findValueForKey(another_two)) == \"hi\");\n}\n\n} \/\/ namespace container_tests\n\nvoid register_container_tests()\n{\n REGISTER_TEST_CASE(container_tests::test_set);\n REGISTER_TEST_CASE(container_tests::test_namespace);\n REGISTER_TEST_CASE(container_tests::test_list);\n REGISTER_TEST_CASE(container_tests::value_map);\n}\n\n} \/\/ namespace circa\n<|endoftext|>"} {"text":"<commit_before>\/* \n* Copyright (C) 2010 Toni Gundogdu.\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"config.h\"\n\n#include <ctime>\n\n#include <boost\/foreach.hpp>\n#include <boost\/random.hpp>\n\n#include <curl\/curl.h>\n\n#ifndef foreach\n#define foreach BOOST_FOREACH\n#endif\n\n#include \"cclive\/application.h\"\n#include \"cclive\/get.h\"\n#include \"cclive\/error.h\"\n#include \"cclive\/log.h\"\n#include \"cclive\/wait.h\"\n#include \"cclive\/background.h\"\n\nnamespace cclive {\n\nstatic boost::mt19937 _rng;\n\nstatic void\nrand_decor () {\n\n boost::uniform_int<> r(2,5);\n\n boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);\n\n const int n = v();\n\n for (int i=0; i<n; ++i) cclive::log << \".\";\n}\n\nstatic void\nhandle_fetch (const quvi_word type, void*) {\n rand_decor();\n if (type == QUVISTATUSTYPE_DONE)\n cclive::log << \" \";\n}\n\nstatic void\nhandle_verify (const quvi_word type) {\n rand_decor();\n if (type == QUVISTATUSTYPE_DONE)\n cclive::log << \"done.\\n\";\n}\n\nstatic int\nstatus_callback (long param, void *ptr) {\n\n const quvi_word status = quvi_loword(param);\n const quvi_word type = quvi_hiword(param);\n\n switch (status) {\n case QUVISTATUS_FETCH : handle_fetch (type,ptr); break;\n case QUVISTATUS_VERIFY: handle_verify(type); break;\n }\n\n cclive::log << std::flush;\n\n return QUVI_OK;\n}\n\ntemplate<class Iterator>\nstatic Iterator\nmake_unique (Iterator first, Iterator last) {\n while (first != last) {\n Iterator next (first);\n last = std::remove (++next, last, *first);\n first = next;\n }\n return last;\n}\n\nstatic void\nprint_quvi_error (const quvicpp::error& e)\n { std::clog << \"libquvi: error: \" << e.what() << std::endl; }\n\nstatic void\nprint_error (const std::exception& e)\n { std::clog << \"error: \" << e.what() << std::endl; }\n\n\nextern char LICENSE[]; \/\/ cclive\/license.cpp\n\nint\napplication::exec (int argc, char **argv) {\n\n try { _opts.exec(argc,argv); }\n\n catch (const std::exception& e) {\n print_error (e);\n return invalid_option;\n }\n\n const boost::program_options::variables_map map = _opts.map();\n\n \/\/ Dump and terminate options.\n\n if (map.count(\"help\")) {\n std::clog << _opts;\n return ok;\n }\n\n if (map.count(\"version\")) {\n std::clog\n << \"cclive version \"\n << VERSION_LONG\n << \"\\n\"\n << \"libquvi version \"\n << quvi_version (QUVI_VERSION_LONG)\n << std::endl;\n return ok;\n }\n\n if (map.count(\"license\")) {\n std::clog << LICENSE << std::endl;\n return ok;\n }\n\n \/\/ Set up quvicpp.\n\n quvicpp::query query; \/\/ Throws quvicpp::error caught in main.cpp .\n\n if (map.count(\"support\")) {\n std::clog << quvicpp::support_to_s (query.support ()) << std::flush;\n return ok;\n }\n\n \/\/ Parse input.\n\n std::vector<std::string> input;\n\n if (map.count(\"url\"))\n input = map[\"url\"].as< std::vector<std::string> >();\n else\n _read_stdin (input);\n\n \/\/ Remove duplicates.\n\n input.erase (make_unique (input.begin(), input.end()), input.end());\n\n \/\/ Turn on libcurl verbose output.\n\n if (map.count(\"verbose-libcurl\"))\n curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L);\n\n \/\/ Set up quvicpp.\n\n _tweak_curl_opts(query,map);\n\n quvicpp::options qopts;\n qopts.statusfunc (status_callback);\n qopts.format (map[\"format\"].as<std::string>());\n\n \/\/ Seed random generator.\n\n _rng.seed ( static_cast<unsigned int>(std::time(0)) );\n\n \/\/ Omit flag.\n\n bool omit = map.count (\"quiet\");\n\n \/\/ Go to background.\n\n if (map.count (\"background\")) {\n\n \/\/ Throws std::runtime_error if fails.\n\n cclive::go_background (map[\"log-file\"].as<std::string>(), omit);\n }\n\n \/\/ Omit std output. Note that --background flips this above.\n\n cclive::log.push (cclive::omit_sink (omit));\n\n \/\/ For each input URL.\n\n const size_t n = input.size();\n size_t i = 0;\n\n const int max_retries = map[\"max-retries\"].as<int>();\n const int retry_wait = map[\"retry-wait\"].as<int>();\n\n foreach(std::string url, input) {\n\n ++i;\n\n try {\n\n int retry = 0;\n\n while (retry <= max_retries) {\n\n if (retry > 0) {\n\n std::clog\n << \"Retrying \"\n << retry\n << \" of \"\n << max_retries\n << \" ... \"\n << std::flush;\n\n cclive::wait (retry_wait);\n }\n\n ++retry;\n\n if (n > 1)\n cclive::log << \"(\" << i << \" of \" << n << \") \";\n\n cclive::log << \"Checking \";\n\n quvicpp::video v;\n\n try { v = query.parse (url, qopts); }\n\n catch (const quvicpp::error& e) {\n\n const long resp_code = e.response_code ();\n\n if (resp_code >= 400 && resp_code <= 500)\n throw e;\n\n else {\n\n print_quvi_error (e);\n\n continue; \/\/ Retry.\n }\n\n }\n\n cclive::get (query, v, _opts);\n\n break; \/\/ Stop retrying.\n }\n\n }\n\n catch (const quvicpp::error& e)\n { print_quvi_error (e); }\n\n catch (const std::runtime_error& e)\n { print_error (e); }\n\n }\n\n return ok;\n}\n\nvoid\napplication::_read_stdin (std::vector<std::string>& dst) {\n\n std::string s;\n char ch = 0;\n\n while (std::cin.get(ch))\n s += ch;\n\n std::istringstream iss(s);\n std::copy(\n std::istream_iterator<std::string >(iss),\n std::istream_iterator<std::string >(),\n std::back_inserter<std::vector<std::string> >(dst)\n );\n}\n\nvoid\napplication::_tweak_curl_opts (\n const quvicpp::query& query,\n const boost::program_options::variables_map& map)\n{\n CURL *curl = query.curlHandle();\n\n curl_easy_setopt(curl, CURLOPT_USERAGENT,\n map[\"agent\"].as<std::string>().c_str());\n\n if (map.count(\"verbose-curl\"))\n curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\n if (map.count(\"proxy\")) {\n curl_easy_setopt(curl, CURLOPT_PROXY,\n map[\"proxy\"].as<std::string>().c_str());\n }\n\n if (map.count(\"no-proxy\"))\n curl_easy_setopt(curl, CURLOPT_PROXY, \"\");\n\n if (map.count(\"throttle\")) {\n curl_off_t limit = map[\"throttle\"].as<int>()*1024;\n curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);\n }\n\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,\n map[\"connect-timeout\"].as<int>());\n}\n\n} \/\/ End namespace.\n\n\n<commit_msg>check for quvi_code, put into wrapper functions.<commit_after>\/* \n* Copyright (C) 2010 Toni Gundogdu.\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"config.h\"\n\n#include <ctime>\n\n#include <boost\/foreach.hpp>\n#include <boost\/random.hpp>\n\n#include <curl\/curl.h>\n\n#ifndef foreach\n#define foreach BOOST_FOREACH\n#endif\n\n#include \"cclive\/application.h\"\n#include \"cclive\/get.h\"\n#include \"cclive\/error.h\"\n#include \"cclive\/log.h\"\n#include \"cclive\/wait.h\"\n#include \"cclive\/background.h\"\n\nnamespace cclive {\n\nstatic boost::mt19937 _rng;\n\nstatic void\nrand_decor () {\n\n boost::uniform_int<> r(2,5);\n\n boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);\n\n const int n = v();\n\n for (int i=0; i<n; ++i) cclive::log << \".\";\n}\n\nstatic void\nhandle_fetch (const quvi_word type, void*) {\n rand_decor();\n if (type == QUVISTATUSTYPE_DONE)\n cclive::log << \" \";\n}\n\nstatic void\nhandle_verify (const quvi_word type) {\n rand_decor();\n if (type == QUVISTATUSTYPE_DONE)\n cclive::log << \"done.\\n\";\n}\n\nstatic int\nstatus_callback (long param, void *ptr) {\n\n const quvi_word status = quvi_loword(param);\n const quvi_word type = quvi_hiword(param);\n\n switch (status) {\n case QUVISTATUS_FETCH : handle_fetch (type,ptr); break;\n case QUVISTATUS_VERIFY: handle_verify(type); break;\n }\n\n cclive::log << std::flush;\n\n return QUVI_OK;\n}\n\ntemplate<class Iterator>\nstatic Iterator\nmake_unique (Iterator first, Iterator last) {\n while (first != last) {\n Iterator next (first);\n last = std::remove (++next, last, *first);\n first = next;\n }\n return last;\n}\n\nstatic void\nprint_retrying (\n const int retry,\n const int max_retries,\n const int retry_wait)\n{\n if (retry > 0) {\n\n std::clog\n << \"Retrying \"\n << retry\n << \" of \"\n << max_retries\n << \" ... \"\n << std::flush;\n\n cclive::wait (retry_wait);\n }\n}\n\nstatic void\nprint_checking (const int i, const int n) {\n\n if (n > 1)\n cclive::log << \"(\" << i << \" of \" << n << \") \";\n\n cclive::log << \"Checking \";\n}\n\nstatic void\nprint_quvi_error (const quvicpp::error& e)\n { std::clog << \"libquvi: error: \" << e.what() << std::endl; }\n\nstatic void\nprint_error (const std::exception& e)\n { std::clog << \"error: \" << e.what() << std::endl; }\n\nstatic void\ncheck_quvi_error (const quvicpp::error& e) {\n\n const long resp_code = e.response_code ();\n\n if (resp_code >= 400 && resp_code <= 500)\n throw e;\n\n else {\n\n switch (e.quvi_code ()) {\n\n case QUVI_CURL:\n print_quvi_error (e);\n break; \/\/ Retry.\n\n default:\n throw e;\n }\n\n }\n\n}\n\nextern char LICENSE[]; \/\/ cclive\/license.cpp\n\nint\napplication::exec (int argc, char **argv) {\n\n try { _opts.exec(argc,argv); }\n\n catch (const std::exception& e) {\n print_error (e);\n return invalid_option;\n }\n\n const boost::program_options::variables_map map = _opts.map();\n\n \/\/ Dump and terminate options.\n\n if (map.count(\"help\")) {\n std::clog << _opts;\n return ok;\n }\n\n if (map.count(\"version\")) {\n std::clog\n << \"cclive version \"\n << VERSION_LONG\n << \"\\n\"\n << \"libquvi version \"\n << quvi_version (QUVI_VERSION_LONG)\n << std::endl;\n return ok;\n }\n\n if (map.count(\"license\")) {\n std::clog << LICENSE << std::endl;\n return ok;\n }\n\n \/\/ Set up quvicpp.\n\n quvicpp::query query; \/\/ Throws quvicpp::error caught in main.cpp .\n\n if (map.count(\"support\")) {\n std::clog << quvicpp::support_to_s (query.support ()) << std::flush;\n return ok;\n }\n\n \/\/ Parse input.\n\n std::vector<std::string> input;\n\n if (map.count(\"url\"))\n input = map[\"url\"].as< std::vector<std::string> >();\n else\n _read_stdin (input);\n\n \/\/ Remove duplicates.\n\n input.erase (make_unique (input.begin(), input.end()), input.end());\n\n \/\/ Turn on libcurl verbose output.\n\n if (map.count(\"verbose-libcurl\"))\n curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L);\n\n \/\/ Set up quvicpp.\n\n _tweak_curl_opts(query,map);\n\n quvicpp::options qopts;\n qopts.statusfunc (status_callback);\n qopts.format (map[\"format\"].as<std::string>());\n\n \/\/ Seed random generator.\n\n _rng.seed ( static_cast<unsigned int>(std::time(0)) );\n\n \/\/ Omit flag.\n\n bool omit = map.count (\"quiet\");\n\n \/\/ Go to background.\n\n if (map.count (\"background\")) {\n\n \/\/ Throws std::runtime_error if fails.\n\n cclive::go_background (map[\"log-file\"].as<std::string>(), omit);\n }\n\n \/\/ Omit std output. Note that --background flips this above.\n\n cclive::log.push (cclive::omit_sink (omit));\n\n \/\/ For each input URL.\n\n const size_t n = input.size();\n size_t i = 0;\n\n const int max_retries = map[\"max-retries\"].as<int>();\n const int retry_wait = map[\"retry-wait\"].as<int>();\n\n foreach(std::string url, input) {\n\n ++i;\n\n try {\n\n int retry = 0;\n\n while (retry <= max_retries) {\n\n print_retrying (retry, max_retries, retry_wait);\n\n ++retry;\n\n print_checking (i, n);\n\n quvicpp::video v;\n\n try\n { v = query.parse (url, qopts); }\n\n catch (const quvicpp::error& e)\n { check_quvi_error (e); }\n\n cclive::get (query, v, _opts);\n\n break; \/\/ Stop retrying.\n }\n }\n\n catch (const quvicpp::error& e)\n { print_quvi_error (e); }\n\n catch (const std::runtime_error& e)\n { print_error (e); }\n }\n\n return ok;\n}\n\nvoid\napplication::_read_stdin (std::vector<std::string>& dst) {\n\n std::string s;\n char ch = 0;\n\n while (std::cin.get(ch))\n s += ch;\n\n std::istringstream iss(s);\n std::copy(\n std::istream_iterator<std::string >(iss),\n std::istream_iterator<std::string >(),\n std::back_inserter<std::vector<std::string> >(dst)\n );\n}\n\nvoid\napplication::_tweak_curl_opts (\n const quvicpp::query& query,\n const boost::program_options::variables_map& map)\n{\n CURL *curl = query.curlHandle();\n\n curl_easy_setopt(curl, CURLOPT_USERAGENT,\n map[\"agent\"].as<std::string>().c_str());\n\n if (map.count(\"verbose-curl\"))\n curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\n if (map.count(\"proxy\")) {\n curl_easy_setopt(curl, CURLOPT_PROXY,\n map[\"proxy\"].as<std::string>().c_str());\n }\n\n if (map.count(\"no-proxy\"))\n curl_easy_setopt(curl, CURLOPT_PROXY, \"\");\n\n if (map.count(\"throttle\")) {\n curl_off_t limit = map[\"throttle\"].as<int>()*1024;\n curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);\n }\n\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,\n map[\"connect-timeout\"].as<int>());\n}\n\n} \/\/ End namespace.\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n * @file Spectrogram.cpp\r\n *\r\n * Spectrogram calculation.\r\n *\r\n * This file is part of the Aquila DSP library.\r\n * Aquila is free software, licensed under the MIT\/X11 License. A copy of\r\n * the license is provided with the library in the LICENSE file.\r\n *\r\n * @package Aquila\r\n * @version 3.0.0-dev\r\n * @author Zbigniew Siciarz\r\n * @date 2007-2010\r\n * @license http:\/\/www.opensource.org\/licenses\/mit-license.php MIT\r\n * @since 3.0.0\r\n *\/\r\n\r\n#include \"Spectrogram.h\"\r\n#include \"OouraFft.h\"\r\n#include \"..\/source\/Frame.h\"\r\n\r\nnamespace Aquila\r\n{\r\n Spectrogram::Spectrogram(FramesCollection& frames):\r\n m_frameCount(frames.count()),\r\n m_spectrumSize(frames.getSamplesPerFrame()),\r\n m_fft(new OouraFft(m_spectrumSize)),\r\n m_data(new SpectrogramDataType(m_frameCount))\r\n {\r\n std::size_t i = 0;\r\n ComplexType* spectrumArray = new ComplexType[m_spectrumSize];\r\n for (FramesCollection::iterator iFrame = frames.begin(); iFrame != frames.end(); ++iFrame, ++i)\r\n {\r\n \/\/ a reference to ease typing\r\n SpectrumType& frameSpectrum = (*m_data)[i];\r\n m_fft->fft(iFrame->toArray(), spectrumArray);\r\n frameSpectrum.assign(spectrumArray, spectrumArray + m_spectrumSize);\r\n }\r\n delete [] spectrumArray;\r\n }\r\n}\r\n<commit_msg>Fixed accumulating of spectrum data in the temporary array.<commit_after>\/**\r\n * @file Spectrogram.cpp\r\n *\r\n * Spectrogram calculation.\r\n *\r\n * This file is part of the Aquila DSP library.\r\n * Aquila is free software, licensed under the MIT\/X11 License. A copy of\r\n * the license is provided with the library in the LICENSE file.\r\n *\r\n * @package Aquila\r\n * @version 3.0.0-dev\r\n * @author Zbigniew Siciarz\r\n * @date 2007-2010\r\n * @license http:\/\/www.opensource.org\/licenses\/mit-license.php MIT\r\n * @since 3.0.0\r\n *\/\r\n\r\n#include \"Spectrogram.h\"\r\n#include \"OouraFft.h\"\r\n#include \"..\/source\/Frame.h\"\r\n#include <cstring> \/\/ for memset\r\n\r\nnamespace Aquila\r\n{\r\n Spectrogram::Spectrogram(FramesCollection& frames):\r\n m_frameCount(frames.count()),\r\n m_spectrumSize(frames.getSamplesPerFrame()),\r\n m_fft(new OouraFft(m_spectrumSize)),\r\n m_data(new SpectrogramDataType(m_frameCount))\r\n {\r\n std::size_t i = 0;\r\n\r\n ComplexType* spectrumArray = new ComplexType[m_spectrumSize];\r\n for (FramesCollection::iterator iFrame = frames.begin(); iFrame != frames.end(); ++iFrame, ++i)\r\n {\r\n \/\/ a reference to ease typing\r\n SpectrumType& frameSpectrum = (*m_data)[i];\r\n std::memset(spectrumArray, 0, m_spectrumSize * sizeof(ComplexType));\r\n m_fft->fft(iFrame->toArray(), spectrumArray);\r\n frameSpectrum.assign(spectrumArray, spectrumArray + m_spectrumSize);\r\n }\r\n delete [] spectrumArray;\r\n\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.\n\n\/** metric_space.cc\n Jeremy Barnes, 25 April 2015\n Copyright (c) 2015 Datacratic Inc. All rights reserved.\n\n Create a metric space.\n*\/\n\n#include \"metric_space.h\"\n#include \"mldb\/jml\/stats\/distribution_simd.h\"\n#include \"ml\/value_descriptions.h\"\n#include \"mldb\/types\/basic_value_descriptions.h\"\n#include \"mldb\/types\/distribution_description.h\"\n#include \"mldb\/http\/http_exception.h\"\n#include \"mldb\/base\/exc_assert.h\"\n\nusing namespace std;\n\n\nnamespace Datacratic {\nnamespace MLDB {\n\nDEFINE_ENUM_DESCRIPTION(MetricSpace);\n\nMetricSpaceDescription::\nMetricSpaceDescription()\n{\n addValue(\"none\", METRIC_NONE, \"No metric is chosen. This will cause an error.\");\n addValue(\"euclidean\", METRIC_EUCLIDEAN, \"Use Euclidian distance for metric. \"\n \"This is a good choice for geometric embeddings like the t-SNE \"\n \"algorithm.\");\n addValue(\"cosine\", METRIC_COSINE, \"Use cosine distance for metric. This is \"\n \"a good choice for normalized and high-dimensional embeddings like the SVD)\");\n}\n\n\n\/*****************************************************************************\/\n\/* DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nDistanceMetric *\nDistanceMetric::\ncreate(MetricSpace space)\n{\n switch (space) {\n case METRIC_NONE:\n throw HttpReturnException(400, \"No metric space was specified\");\n case METRIC_EUCLIDEAN:\n return new EuclideanDistanceMetric();\n case METRIC_COSINE:\n return new CosineDistanceMetric();\n default:\n throw HttpReturnException(400, \"Unknown distance metric space \"\n + to_string(space));\n }\n}\n\n\n\/*****************************************************************************\/\n\/* EUCLIDEAN DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nvoid\nEuclideanDistanceMetric::\naddRow(int rowNum, const ML::distribution<float> & coords)\n{\n \/\/cerr << \"addRow \" << rowNum << endl;\n ExcAssertEqual(rowNum, sum_dist.size());\n sum_dist.push_back(coords.dotprod(coords));\n ExcAssert(isfinite(sum_dist.back()));\n}\n\nfloat\nEuclideanDistanceMetric::\ncalc(const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2)\n{\n return (coords2 - coords1).two_norm();\n}\n\nfloat\nEuclideanDistanceMetric::\ndist(int rowNum1, int rowNum2,\n const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2) const\n{\n ExcAssertEqual(coords1.size(), coords2.size());\n\n if (rowNum1 == -1 || rowNum2 == -1) {\n return calc(coords1, coords2);\n }\n\n \/\/ Make sure dist(x,y) == dist(y,x) irrespective of rounding\n if (rowNum2 < rowNum1)\n return dist(rowNum2, rowNum1, coords2, coords1);\n\n \/\/ Make sure dist(x,x) == 0 irrespective of rounding\n if (rowNum1 == rowNum2)\n return 0.0;\n\n \/* Given two points x and y, whose coordinates are coords[x] and\n coords[y], this will calculate the euclidian distance\n ||x - y|| = sqrt(sum_i (x[i] - y[i])^2)\n = sqrt(sum_i (x[i]^2 + y[i]^2 - 2 x[i]y[i]) )\n = sqrt(sum_i x[i]^2 + sum_i y[i]^2 - 2 sum x[i]y[i])\n = sqrt(||x||^2 + ||y||^2 - 2 x . y)\n \n Must satisfy the triangle inequality, so the sqrt is important. We\n also take pains to ensure that dist(x,y) === dist(y,x) *exactly*,\n and that dist(x,x) == 0.\n *\/\n \n \/\/ Use the optimized version, since we know the sum\n float dpResult = -2.0 * ML::SIMD::vec_dotprod_dp(&coords1[0],\n &coords2[0],\n coords1.size());\n ExcAssert(isfinite(dpResult));\n\n\n\n float distSquared = dpResult + sum_dist.at(rowNum1) + sum_dist.at(rowNum2);\n ExcAssert(isfinite(distSquared));\n\n \/\/ Deal with rounding errors\n if (distSquared < 0.0)\n distSquared = 0.0;\n\n return sqrtf(distSquared);\n}\n\n\n\/*****************************************************************************\/\n\/* COSINE DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nvoid\nCosineDistanceMetric::\naddRow(int rowNum, const ML::distribution<float> & coords)\n{\n ExcAssertEqual(rowNum, two_norm_recip.size());\n float twonorm = coords.two_norm();\n\n \/\/ If it's zero, we store the non-finite reciprocal, and the distance\n \/\/ it and any vector with a finite reciprocal is 1.\n\n if (twonorm == 0.0) {\n two_norm_recip.push_back(1.0 \/ 0.0);\n return;\n throw HttpReturnException(400, \"Attempt to add zero magnitude vector to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm);\n }\n\n if (!isfinite(twonorm))\n throw HttpReturnException(400, \"Attempt to add vector with non-finite two norm \"\n \"to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm);\n float recip = 1.0 \/ twonorm;\n if (!isfinite(recip))\n throw HttpReturnException(400, \"Attempt to add vector with non-finite two norm reciprocal \"\n \"to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm,\n \"recip\", recip);\n \n two_norm_recip.push_back(recip);\n}\n\nfloat\nCosineDistanceMetric::\ncalc(const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2)\n{\n if ((coords1 == coords2).all())\n return 0.0;\n\n double norm1 = coords1.two_norm();\n double norm2 = coords2.two_norm();\n\n if (norm1 == 0.0 && norm2 == 0.0) {\n return 0.0;\n }\n \n if (norm1 == 0.0 || norm2 == 0.0) {\n return 1.0;\n\n throw HttpReturnException(400, \"Error: can't calculate cosine distance between \"\n \"zero length vectors\",\n \"vec1\", coords1,\n \"vec2\", coords2,\n \"vec1norm\", norm1,\n \"vec2norm\", norm2);\n }\n \n return std::max(1 - (coords1.dotprod(coords2) \/ (norm1 * norm2)), 0.0);\n}\n\nfloat\nCosineDistanceMetric::\ndist(int rowNum1, int rowNum2,\n const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2) const\n{\n ExcAssertEqual(coords1.size(), coords2.size());\n\n if (rowNum1 == -1 || rowNum2 == -1) {\n return calc(coords1, coords2);\n }\n\n \/\/ Make sure dist(x,y) == dist(y,x) irrespective of rounding\n if (rowNum2 < rowNum1)\n return dist(rowNum2, rowNum1, coords2, coords1);\n\n \/\/ Make sure dist(x,x) == 0 irrespective of rounding\n if (rowNum1 == rowNum2)\n return 0.0;\n\n if (!isfinite(two_norm_recip.at(rowNum1))\n && !isfinite(two_norm_recip.at(rowNum2))) {\n return 0.0;\n }\n if (!isfinite(two_norm_recip.at(rowNum1))\n || !isfinite(two_norm_recip.at(rowNum2))) {\n return 1.0;\n }\n\n float result = 1.0 - coords1.dotprod(coords2) * two_norm_recip.at(rowNum1) * two_norm_recip.at(rowNum2);\n if (result < 0.0) {\n result = 0.0;\n#if 0\n cerr << \"rowNum1 = \" << rowNum1 << endl;\n cerr << \"rowNum2 = \" << rowNum2 << endl;\n cerr << \"coords1 = \" << coords1 << endl;\n cerr << \"coords2 = \" << coords2 << endl;\n cerr << \"result = \" << result << endl;\n#endif\n }\n\n ExcAssert(isfinite(result));\n ExcAssertGreaterEqual(result, 0.0);\n\n return result;\n}\n\n\n} \/\/ namespace Datacratic\n} \/\/ namespace MLDB\n\n<commit_msg>[Trivial] typo in description of cosine distance<commit_after>\/\/ This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.\n\n\/** metric_space.cc\n Jeremy Barnes, 25 April 2015\n Copyright (c) 2015 Datacratic Inc. All rights reserved.\n\n Create a metric space.\n*\/\n\n#include \"metric_space.h\"\n#include \"mldb\/jml\/stats\/distribution_simd.h\"\n#include \"ml\/value_descriptions.h\"\n#include \"mldb\/types\/basic_value_descriptions.h\"\n#include \"mldb\/types\/distribution_description.h\"\n#include \"mldb\/http\/http_exception.h\"\n#include \"mldb\/base\/exc_assert.h\"\n\nusing namespace std;\n\n\nnamespace Datacratic {\nnamespace MLDB {\n\nDEFINE_ENUM_DESCRIPTION(MetricSpace);\n\nMetricSpaceDescription::\nMetricSpaceDescription()\n{\n addValue(\"none\", METRIC_NONE, \"No metric is chosen. This will cause an error.\");\n addValue(\"euclidean\", METRIC_EUCLIDEAN, \"Use Euclidian distance for metric. \"\n \"This is a good choice for geometric embeddings like the t-SNE \"\n \"algorithm.\");\n addValue(\"cosine\", METRIC_COSINE, \"Use cosine distance for metric. This is \"\n \"a good choice for normalized and high-dimensional embeddings like the SVD.\");\n}\n\n\n\/*****************************************************************************\/\n\/* DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nDistanceMetric *\nDistanceMetric::\ncreate(MetricSpace space)\n{\n switch (space) {\n case METRIC_NONE:\n throw HttpReturnException(400, \"No metric space was specified\");\n case METRIC_EUCLIDEAN:\n return new EuclideanDistanceMetric();\n case METRIC_COSINE:\n return new CosineDistanceMetric();\n default:\n throw HttpReturnException(400, \"Unknown distance metric space \"\n + to_string(space));\n }\n}\n\n\n\/*****************************************************************************\/\n\/* EUCLIDEAN DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nvoid\nEuclideanDistanceMetric::\naddRow(int rowNum, const ML::distribution<float> & coords)\n{\n \/\/cerr << \"addRow \" << rowNum << endl;\n ExcAssertEqual(rowNum, sum_dist.size());\n sum_dist.push_back(coords.dotprod(coords));\n ExcAssert(isfinite(sum_dist.back()));\n}\n\nfloat\nEuclideanDistanceMetric::\ncalc(const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2)\n{\n return (coords2 - coords1).two_norm();\n}\n\nfloat\nEuclideanDistanceMetric::\ndist(int rowNum1, int rowNum2,\n const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2) const\n{\n ExcAssertEqual(coords1.size(), coords2.size());\n\n if (rowNum1 == -1 || rowNum2 == -1) {\n return calc(coords1, coords2);\n }\n\n \/\/ Make sure dist(x,y) == dist(y,x) irrespective of rounding\n if (rowNum2 < rowNum1)\n return dist(rowNum2, rowNum1, coords2, coords1);\n\n \/\/ Make sure dist(x,x) == 0 irrespective of rounding\n if (rowNum1 == rowNum2)\n return 0.0;\n\n \/* Given two points x and y, whose coordinates are coords[x] and\n coords[y], this will calculate the euclidian distance\n ||x - y|| = sqrt(sum_i (x[i] - y[i])^2)\n = sqrt(sum_i (x[i]^2 + y[i]^2 - 2 x[i]y[i]) )\n = sqrt(sum_i x[i]^2 + sum_i y[i]^2 - 2 sum x[i]y[i])\n = sqrt(||x||^2 + ||y||^2 - 2 x . y)\n \n Must satisfy the triangle inequality, so the sqrt is important. We\n also take pains to ensure that dist(x,y) === dist(y,x) *exactly*,\n and that dist(x,x) == 0.\n *\/\n \n \/\/ Use the optimized version, since we know the sum\n float dpResult = -2.0 * ML::SIMD::vec_dotprod_dp(&coords1[0],\n &coords2[0],\n coords1.size());\n ExcAssert(isfinite(dpResult));\n\n\n\n float distSquared = dpResult + sum_dist.at(rowNum1) + sum_dist.at(rowNum2);\n ExcAssert(isfinite(distSquared));\n\n \/\/ Deal with rounding errors\n if (distSquared < 0.0)\n distSquared = 0.0;\n\n return sqrtf(distSquared);\n}\n\n\n\/*****************************************************************************\/\n\/* COSINE DISTANCE METRIC *\/\n\/*****************************************************************************\/\n\nvoid\nCosineDistanceMetric::\naddRow(int rowNum, const ML::distribution<float> & coords)\n{\n ExcAssertEqual(rowNum, two_norm_recip.size());\n float twonorm = coords.two_norm();\n\n \/\/ If it's zero, we store the non-finite reciprocal, and the distance\n \/\/ it and any vector with a finite reciprocal is 1.\n\n if (twonorm == 0.0) {\n two_norm_recip.push_back(1.0 \/ 0.0);\n return;\n throw HttpReturnException(400, \"Attempt to add zero magnitude vector to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm);\n }\n\n if (!isfinite(twonorm))\n throw HttpReturnException(400, \"Attempt to add vector with non-finite two norm \"\n \"to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm);\n float recip = 1.0 \/ twonorm;\n if (!isfinite(recip))\n throw HttpReturnException(400, \"Attempt to add vector with non-finite two norm reciprocal \"\n \"to cosine distance\",\n \"coords\", coords,\n \"twoNorm\", twonorm,\n \"recip\", recip);\n \n two_norm_recip.push_back(recip);\n}\n\nfloat\nCosineDistanceMetric::\ncalc(const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2)\n{\n if ((coords1 == coords2).all())\n return 0.0;\n\n double norm1 = coords1.two_norm();\n double norm2 = coords2.two_norm();\n\n if (norm1 == 0.0 && norm2 == 0.0) {\n return 0.0;\n }\n \n if (norm1 == 0.0 || norm2 == 0.0) {\n return 1.0;\n\n throw HttpReturnException(400, \"Error: can't calculate cosine distance between \"\n \"zero length vectors\",\n \"vec1\", coords1,\n \"vec2\", coords2,\n \"vec1norm\", norm1,\n \"vec2norm\", norm2);\n }\n \n return std::max(1 - (coords1.dotprod(coords2) \/ (norm1 * norm2)), 0.0);\n}\n\nfloat\nCosineDistanceMetric::\ndist(int rowNum1, int rowNum2,\n const ML::distribution<float> & coords1,\n const ML::distribution<float> & coords2) const\n{\n ExcAssertEqual(coords1.size(), coords2.size());\n\n if (rowNum1 == -1 || rowNum2 == -1) {\n return calc(coords1, coords2);\n }\n\n \/\/ Make sure dist(x,y) == dist(y,x) irrespective of rounding\n if (rowNum2 < rowNum1)\n return dist(rowNum2, rowNum1, coords2, coords1);\n\n \/\/ Make sure dist(x,x) == 0 irrespective of rounding\n if (rowNum1 == rowNum2)\n return 0.0;\n\n if (!isfinite(two_norm_recip.at(rowNum1))\n && !isfinite(two_norm_recip.at(rowNum2))) {\n return 0.0;\n }\n if (!isfinite(two_norm_recip.at(rowNum1))\n || !isfinite(two_norm_recip.at(rowNum2))) {\n return 1.0;\n }\n\n float result = 1.0 - coords1.dotprod(coords2) * two_norm_recip.at(rowNum1) * two_norm_recip.at(rowNum2);\n if (result < 0.0) {\n result = 0.0;\n#if 0\n cerr << \"rowNum1 = \" << rowNum1 << endl;\n cerr << \"rowNum2 = \" << rowNum2 << endl;\n cerr << \"coords1 = \" << coords1 << endl;\n cerr << \"coords2 = \" << coords2 << endl;\n cerr << \"result = \" << result << endl;\n#endif\n }\n\n ExcAssert(isfinite(result));\n ExcAssertGreaterEqual(result, 0.0);\n\n return result;\n}\n\n\n} \/\/ namespace Datacratic\n} \/\/ namespace MLDB\n\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE test_math\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"..\/defines.h\"\n#include \"..\/math\/size.h\"\n\nUSING_NAMESPACE(sway)\n\nBOOST_AUTO_TEST_SUITE(test_suite_size)\nBOOST_AUTO_TEST_CASE(test_size)\n{\n\tmath::TSize<s32> size (1, 2);\n BOOST_CHECK_EQUAL(size.getW(), 1);\n\tBOOST_CHECK_EQUAL(size.getH(), 2);\n\tBOOST_CHECK_EQUAL(size, math::TSize<s32>(1, 2));\n}\nBOOST_AUTO_TEST_SUITE_END()<commit_msg>Добавлено несколько тестов<commit_after>#define BOOST_TEST_MODULE MathTestModule\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"..\/defines.h\"\n#include \"..\/math\/size.h\"\n\nUSING_NAMESPACE(sway)\n\nBOOST_AUTO_TEST_SUITE(TSizeTestSuite)\n\n\/*!\n * Убеждаемся, что конструктор по умолчанию приводит все компоненты к нулю.\n *\/\nBOOST_AUTO_TEST_CASE(DefaultConstructor)\n{\n\tconst math::TSize<s32> size;\n\n\tBOOST_CHECK_EQUAL(size.getW(), 0);\n\tBOOST_CHECK_EQUAL(size.getH(), 0);\n}\n\n\/*!\n * Убеждаемся, что конструктор устанавливает все значения компонентов в те, \n * которые были заданы.\n *\/\nBOOST_AUTO_TEST_CASE(ComponentConstructor)\n{\n\tconst s32 w = 1, h = 2;\n\tconst math::TSize<s32> size(w, h);\n\n\tBOOST_CHECK_EQUAL(size.getW(), w);\n\tBOOST_CHECK_EQUAL(size.getH(), h);\n}\n\nBOOST_AUTO_TEST_CASE(ScalarConstructor)\n{\n\tconst s32 w = 1, h = 2;\n\tconst math::TSize<s32> size(math::TSize<s32>(w, h));\n\n\tBOOST_CHECK_EQUAL(size.getW(), w);\n\tBOOST_CHECK_EQUAL(size.getH(), h);\n}\n\n\/*!\n * Тест для оператора равенства.\n *\/\nBOOST_AUTO_TEST_CASE(EqualityOperator1)\n{\n\tconst math::TSize<s32> size1(0, 0), size2(0, 0);\n\n\tBOOST_CHECK_EQUAL(size1 == size2, true);\n}\n\n\/*!\n * Тест для оператора равенства.\n *\/\nBOOST_AUTO_TEST_CASE(EqualityOperator2)\n{\n\tconst math::TSize<s32> size1(1, 0), size2(0, 0);\n\n\tBOOST_CHECK_EQUAL(size1 == size2, false);\n}\n\n\/*!\n * Тест для оператора равенства.\n *\/\nBOOST_AUTO_TEST_CASE(EqualityOperator3)\n{\n\tconst math::TSize<s32> size1(0, 0), size2(0, 2);\n\n\tBOOST_CHECK_EQUAL(size1 == size2, false);\n}\n\nBOOST_AUTO_TEST_CASE(EqualityOperator4)\n{\n\tconst math::TSize<s32> size (1, 2);\n\t\n\tBOOST_CHECK_EQUAL(size, math::TSize<s32>(1, 2));\n}\n\n\/*!\n * Тест для оператора неравенства.\n *\/\nBOOST_AUTO_TEST_CASE(NonEqualityOperator1)\n{\n\tconst math::TSize<s32> size1(1, 2), size2(1, 2);\n\n\tBOOST_CHECK_EQUAL(size1 != size2, false);\n}\n\n\/*!\n * Тест для оператора неравенства.\n *\/\nBOOST_AUTO_TEST_CASE(NonEqualityOperator2)\n{\n\tconst math::TSize<s32> size1(1, 2), size2(0, 2);\n\n\tBOOST_CHECK_EQUAL(size1 != size2, true);\n}\n\n\/*!\n * Тест для оператора неравенства.\n *\/\nBOOST_AUTO_TEST_CASE(NonEqualityOperator3)\n{\n\tconst math::TSize<s32> size1(1, 2), size2(1, 0);\n\n\tBOOST_CHECK_EQUAL(size1 != size2, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2018 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE table_test\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <exception>\n#include <iostream>\n#include <votca\/tools\/table.h>\n\nusing namespace std;\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(table_test)\n\nBOOST_AUTO_TEST_CASE(create_test) { Table tb; }\n\nBOOST_AUTO_TEST_CASE(size_test) {\n Table tb;\n BOOST_CHECK_EQUAL(tb.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(pushback_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n BOOST_CHECK_EQUAL(tb.size(), 10);\n}\n\nBOOST_AUTO_TEST_CASE(xy_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n\n auto x_v = tb.x();\n auto y_v = tb.y();\n for (int i = 0; i < 10; ++i) {\n int x = i;\n int y = 2 * x;\n BOOST_CHECK_EQUAL(static_cast<int>(x_v(i)),\n static_cast<int>(tb.x(i)));\n BOOST_CHECK_EQUAL(static_cast<int>(y_v(i)),\n static_cast<int>(tb.y(i)));\n BOOST_CHECK_EQUAL(x, static_cast<int>(tb.x(i)));\n BOOST_CHECK_EQUAL(y, static_cast<int>(tb.y(i)));\n BOOST_CHECK_EQUAL(x, static_cast<int>(x_v(i)));\n BOOST_CHECK_EQUAL(y, static_cast<int>(y_v(i)));\n }\n}\n\nBOOST_AUTO_TEST_CASE(getMinMax_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n \n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMinX()), 0);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMaxX()), 9);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMinY()), 0);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMaxY()), 18);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Added extra tests<commit_after>\/*\n * Copyright 2009-2018 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE table_test\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <exception>\n#include <iostream>\n#include <votca\/tools\/table.h>\n\nusing namespace std;\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(table_test)\n\nBOOST_AUTO_TEST_CASE(create_test) { \n Table tb;\n Table tb2(tb);\n}\n\nBOOST_AUTO_TEST_CASE(size_test) {\n Table tb;\n BOOST_CHECK_EQUAL(tb.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(pushback_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n BOOST_CHECK_EQUAL(tb.size(), 10);\n}\n\nBOOST_AUTO_TEST_CASE(resize_test){\n Table tb;\n tb.resize(0);\n tb.resize(10);\n\n bool error_thrown = false;\n try {\n tb.resize(-5);\n }catch(...){\n error_thrown = true;\n }\n BOOST_CHECK(error_thrown);\n}\n\nBOOST_AUTO_TEST_CASE(xy_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n\n auto x_v = tb.x();\n auto y_v = tb.y();\n for (int i = 0; i < 10; ++i) {\n int x = i;\n int y = 2 * x;\n BOOST_CHECK_EQUAL(static_cast<int>(x_v(i)),\n static_cast<int>(tb.x(i)));\n BOOST_CHECK_EQUAL(static_cast<int>(y_v(i)),\n static_cast<int>(tb.y(i)));\n BOOST_CHECK_EQUAL(x, static_cast<int>(tb.x(i)));\n BOOST_CHECK_EQUAL(y, static_cast<int>(tb.y(i)));\n BOOST_CHECK_EQUAL(x, static_cast<int>(x_v(i)));\n BOOST_CHECK_EQUAL(y, static_cast<int>(y_v(i)));\n }\n}\n\nBOOST_AUTO_TEST_CASE(getMinMax_test) {\n Table tb;\n for (double x = 0; x < 10; ++x) {\n double y = 2 * x;\n tb.push_back(x, y);\n }\n \n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMinX()), 0);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMaxX()), 9);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMinY()), 0);\n BOOST_CHECK_EQUAL(static_cast<int>(tb.getMaxY()), 18);\n}\n\nBOOST_AUTO_TEST_CASE(generate_grid_spacing_test){\n Table tb;\n double min_v = 1.2;\n double max_v = 2.0;\n\n tb.GenerateGridSpacing(min_v,max_v,0.2);\n\n BOOST_CHECK_EQUAL(tb.size(),5);\n BOOST_CHECK_EQUAL(static_cast<int>(round(tb.getMinX()*10)),12); \n BOOST_CHECK_EQUAL(static_cast<int>(round(tb.getMaxX()*10)),20); \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"Textbox.h\"\n#include <cstring>\n#include <cstdlib>\n#include \"utility\/misc.h\"\n#include \"input\/Input.h\"\n\nusing WalrusRPG::MAGIC_TOKEN;\nusing WalrusRPG::COMMAND_LEGNTH;\nusing WalrusRPG::Textbox;\nusing WalrusRPG::TextboxState;\nusing WalrusRPG::TextboxChar;\nusing WalrusRPG::Graphics::Font;\nusing WalrusRPG::Graphics::CharacterParameters;\nusing WalrusRPG::Graphics::Pixel;\nusing WalrusRPG::Input::Key;\nusing WalrusRPG::Utils::Rect;\n\nnamespace\n{\n \/**\n * This is a replacment of strlen to allow skipping tokens as they might\n * contain null-terminating characters, making strlen stop earlier than\n * planned.\n *\/\n signed strlen_tokens(const char *str)\n {\n signed len = 0;\n for (; str[len]; ++len)\n {\n if (str[len] == MAGIC_TOKEN)\n len += COMMAND_LEGNTH;\n }\n return len;\n }\n}\n\nTextbox::Textbox(Rect dimensions, Font fnt)\n : fnt(fnt), buffer(0), buffer_index(-1), global_string_offset(0),\n current_color(0, 0, 0), letter_wait(0), letter_wait_cooldown(10),\n dimensions(dimensions), state(Waiting)\n{\n}\n\nTextbox::Textbox(Font fnt) : Textbox({4, 4, 220, 32}, fnt)\n{\n}\n\nTextbox::~Textbox()\n{\n}\n\nvoid Textbox::set_text(char *new_text)\n{\n \/\/ Clearing the state variables.\n letter_wait = 0;\n letter_wait_cooldown = 10;\n buffer_index = -1;\n global_string_offset = 0;\n nb_line_to_update = 0;\n for (unsigned i = 0; i < nb_lines; ++i)\n {\n line_nb_characters[i] = 0;\n line_widths[i] = 0;\n }\n\n buffer.clear();\n \/\/ Parsing the passed string into a token list.\n \/\/ TODO?: Convert the vector into a dynamically allocated array?\n for (signed i = 0; i < strlen_tokens(new_text); ++i)\n {\n TextboxChar t;\n if (new_text[i] == MAGIC_TOKEN)\n {\n t.c = MAGIC_TOKEN;\n t.routine = new_text[i + 1];\n t.arg1 = new_text[i + 2];\n t.arg2 = new_text[i + 3];\n t.arg3 = new_text[i + 4];\n i += COMMAND_LEGNTH;\n }\n else\n {\n t.c = new_text[i];\n t.routine = 0;\n t.arg1 = 0;\n t.arg2 = 0;\n t.arg3 = 0;\n }\n buffer.push_back(t);\n }\n state = Updating;\n}\n\n\/**\n * Makes the text box advance of one or more characters\/tokens.\n *\/\nvoid Textbox::add_letter(unsigned nb_letters)\n{\n if (state != Updating || buffer.size() <= 0)\n return;\n\n \/\/ Mmh, you who enters here, try to forget how the core logic is programmed.\n \/\/ Myself don't have a frigging clue on how to clean it but it *works*.\n \/\/ If you ever clean it, I'll be eternally thankful :-°\n for (unsigned i = 0;\n (i < nb_letters) &&\n (buffer_index < 0 || buffer_index < static_cast<signed>(buffer.size()) - 1);\n ++i)\n {\n \/\/ As the index starts with -1, increment it before doing anything.\n ++buffer_index;\n \/\/ Parsing commands.\n if (buffer[buffer_index].c == MAGIC_TOKEN)\n {\n switch (buffer[buffer_index].routine)\n {\n \/\/ wait a bit\n case 0x81:\n letter_wait = buffer[buffer_index].arg1;\n break;\n }\n line_nb_characters[nb_line_to_update]++;\n }\n else\n {\n \/\/ The frigging static cast...\n CharacterParameters &p =\n fnt.chars[static_cast<signed>(buffer[buffer_index].c)];\n TextboxChar &t = buffer[buffer_index];\n \/\/ Manual line-return.\n if (t.c == '\\n')\n {\n if (nb_line_to_update + 1 >= nb_lines)\n {\n \/\/ No need to go back in the array. Just have to go forward.\n line_nb_characters[nb_line_to_update]++;\n state = Full;\n return;\n }\n nb_line_to_update++;\n }\n \/\/ If adding the character would make the line too big for the text_box\n if (line_widths[nb_line_to_update] + p.dimensions.width + 1 >\n dimensions.width)\n {\n if (nb_line_to_update + 1 >= nb_lines)\n {\n \/\/ Here to avoid getting to lose that character (or the last ones)\n \/\/ We have to put the reading head one character backwards.\n --buffer_index;\n state = Full;\n return;\n }\n nb_line_to_update++;\n }\n \/\/ Just adding the correct space width\n if (t.c == ' ')\n line_widths[nb_line_to_update] += fnt.space_width;\n else\n line_widths[nb_line_to_update] += p.dimensions.width + 1;\n \/\/ Putting the parsed character in the current text line.\n line_nb_characters[nb_line_to_update]++;\n }\n }\n \/\/ Check if the text box finished its work\n if (buffer_index >= static_cast<signed>(buffer.size() - 1))\n {\n state = Done;\n }\n \/\/ You prefer having to wait for characters, no?\n letter_wait = letter_wait_cooldown;\n}\n\nvoid Textbox::update(unsigned dt)\n{\n \/\/ Small state machine.\n switch (state)\n {\n case Waiting:\n return;\n break;\n case Updating:\n \/\/ Time-based update.\n if ((buffer_index >= 0) &&\n (buffer_index >= static_cast<signed>(buffer.size())))\n return;\n letter_wait -= dt;\n if (letter_wait <= 0)\n {\n unsigned add = (-letter_wait) \/ letter_wait_cooldown + 1;\n add_letter(add);\n }\n break;\n case Full:\n \/\/ TODO?: Change the trigger (button) into something else (like a function)?\n if (key_pressed(Key::K_A))\n {\n for (unsigned i = 0; i < nb_lines - 1; ++i)\n global_string_offset += line_nb_characters[i];\n\n line_widths[0] = line_widths[nb_lines - 1];\n line_nb_characters[0] = line_nb_characters[nb_lines - 1];\n\n for (unsigned i = 1; i < nb_lines; ++i)\n {\n line_widths[i] = 0;\n line_nb_characters[i] = 0;\n }\n nb_line_to_update = 1;\n state = Updating;\n }\n default:\n break;\n }\n}\n\nvoid Textbox::render(unsigned dt)\n{\n UNUSED(dt);\n if (buffer_index < 0)\n return;\n \/\/ TODO : store the last character's color to correctly reapply it if a line return\n \/\/ happens?\n current_color = 0xFFFF;\n put_rectangle(dimensions, Graphics::Black);\n unsigned global_index = global_string_offset;\n for (unsigned l = 0; l < nb_lines; l++)\n {\n unsigned cur_x = dimensions.x;\n unsigned cur_y = dimensions.y + l * fnt.baseline;\n for (unsigned line_index = 0; line_index < line_nb_characters[l]; ++line_index)\n {\n TextboxChar b = buffer[global_index + line_index];\n char c = b.c;\n if (c == MAGIC_TOKEN)\n {\n switch (b.routine)\n {\n \/\/ Change current color\n case 0x01:\n current_color = ((b.arg1 << 8) + b.arg2);\n break;\n }\n continue;\n }\n fnt.draw(cur_x, cur_y, c, current_color);\n \/\/ *shrugs*\n if (c == '\\n')\n continue;\n else if (c == ' ')\n cur_x += fnt.space_width;\n else\n cur_x += fnt.chars[static_cast<signed>(c)].dimensions.width + 1;\n }\n global_index += line_nb_characters[l];\n }\n \/\/ State indicator.\n Pixel indicator_color = Graphics::Black;\n if (state == Full)\n indicator_color = Graphics::Red;\n else if (state == Done)\n indicator_color = Graphics::Blue;\n\n if (indicator_color != Graphics::Black)\n put_rectangle({dimensions.x + static_cast<signed>(dimensions.width) - 3,\n dimensions.y + static_cast<signed>(dimensions.height) - 3, 3, 3},\n indicator_color);\n}<commit_msg>Added a small detail.<commit_after>#include \"Textbox.h\"\n#include <cstring>\n#include <cstdlib>\n#include \"utility\/misc.h\"\n#include \"input\/Input.h\"\n\nusing WalrusRPG::MAGIC_TOKEN;\nusing WalrusRPG::COMMAND_LEGNTH;\nusing WalrusRPG::Textbox;\nusing WalrusRPG::TextboxState;\nusing WalrusRPG::TextboxChar;\nusing WalrusRPG::Graphics::Font;\nusing WalrusRPG::Graphics::CharacterParameters;\nusing WalrusRPG::Graphics::Pixel;\nusing WalrusRPG::Input::Key;\nusing WalrusRPG::Utils::Rect;\n\nnamespace\n{\n \/**\n * This is a replacment of strlen to allow skipping tokens as they might\n * contain null-terminating characters, making strlen stop earlier than\n * planned.\n *\/\n signed strlen_tokens(const char *str)\n {\n signed len = 0;\n for (; str[len]; ++len)\n {\n if (str[len] == MAGIC_TOKEN)\n len += COMMAND_LEGNTH;\n }\n return len;\n }\n}\n\nTextbox::Textbox(Rect dimensions, Font fnt)\n : fnt(fnt), buffer(0), buffer_index(-1), global_string_offset(0),\n current_color(0, 0, 0), letter_wait(0), letter_wait_cooldown(10),\n dimensions(dimensions), state(Waiting)\n{\n}\n\nTextbox::Textbox(Font fnt) : Textbox({4, 4, 220, 32}, fnt)\n{\n}\n\nTextbox::~Textbox()\n{\n}\n\nvoid Textbox::set_text(char *new_text)\n{\n \/\/ Clearing the state variables.\n letter_wait = 0;\n letter_wait_cooldown = 10;\n buffer_index = -1;\n global_string_offset = 0;\n nb_line_to_update = 0;\n for (unsigned i = 0; i < nb_lines; ++i)\n {\n line_nb_characters[i] = 0;\n line_widths[i] = 0;\n }\n\n buffer.clear();\n \/\/ Parsing the passed string into a token list.\n \/\/ TODO?: Convert the vector into a dynamically allocated array?\n for (signed i = 0; i < strlen_tokens(new_text); ++i)\n {\n TextboxChar t;\n if (new_text[i] == MAGIC_TOKEN)\n {\n t.c = MAGIC_TOKEN;\n t.routine = new_text[i + 1];\n t.arg1 = new_text[i + 2];\n t.arg2 = new_text[i + 3];\n t.arg3 = new_text[i + 4];\n i += COMMAND_LEGNTH;\n }\n else\n {\n t.c = new_text[i];\n t.routine = 0;\n t.arg1 = 0;\n t.arg2 = 0;\n t.arg3 = 0;\n }\n buffer.push_back(t);\n }\n state = Updating;\n}\n\n\/**\n * Makes the text box advance of one or more characters\/tokens.\n *\/\nvoid Textbox::add_letter(unsigned nb_letters)\n{\n if (state != Updating || buffer.size() <= 0)\n return;\n\n \/\/ Mmh, you who enters here, try to forget how the core logic is programmed.\n \/\/ Myself don't have a frigging clue on how to clean it but it *works*.\n \/\/ If you ever clean it, I'll be eternally thankful :-°\n \/\/ Actually, it works as it does right now, but the signedness is messy as hell\n \/\/ and changing it would most likely break it everywhere.\n for (unsigned i = 0;\n (i < nb_letters) &&\n (buffer_index < 0 || buffer_index < static_cast<signed>(buffer.size()) - 1);\n ++i)\n {\n \/\/ As the index starts with -1, increment it before doing anything.\n ++buffer_index;\n \/\/ Parsing commands.\n if (buffer[buffer_index].c == MAGIC_TOKEN)\n {\n switch (buffer[buffer_index].routine)\n {\n \/\/ wait a bit\n case 0x81:\n letter_wait = buffer[buffer_index].arg1;\n break;\n }\n line_nb_characters[nb_line_to_update]++;\n }\n else\n {\n \/\/ The frigging static cast...\n CharacterParameters &p =\n fnt.chars[static_cast<signed>(buffer[buffer_index].c)];\n TextboxChar &t = buffer[buffer_index];\n \/\/ Manual line-return.\n if (t.c == '\\n')\n {\n if (nb_line_to_update + 1 >= nb_lines)\n {\n \/\/ No need to go back in the array. Just have to go forward.\n line_nb_characters[nb_line_to_update]++;\n state = Full;\n return;\n }\n nb_line_to_update++;\n }\n \/\/ If adding the character would make the line too big for the text_box\n if (line_widths[nb_line_to_update] + p.dimensions.width + 1 >\n dimensions.width)\n {\n if (nb_line_to_update + 1 >= nb_lines)\n {\n \/\/ Here to avoid getting to lose that character (or the last ones)\n \/\/ We have to put the reading head one character backwards.\n --buffer_index;\n state = Full;\n return;\n }\n nb_line_to_update++;\n }\n \/\/ Just adding the correct space width\n if (t.c == ' ')\n line_widths[nb_line_to_update] += fnt.space_width;\n else\n line_widths[nb_line_to_update] += p.dimensions.width + 1;\n \/\/ Putting the parsed character in the current text line.\n line_nb_characters[nb_line_to_update]++;\n }\n }\n \/\/ Check if the text box finished its work\n if (buffer_index >= static_cast<signed>(buffer.size() - 1))\n {\n state = Done;\n }\n \/\/ You prefer having to wait for characters, no?\n letter_wait = letter_wait_cooldown;\n}\n\nvoid Textbox::update(unsigned dt)\n{\n \/\/ Small state machine.\n switch (state)\n {\n case Waiting:\n return;\n break;\n case Updating:\n \/\/ Time-based update.\n if ((buffer_index >= 0) &&\n (buffer_index >= static_cast<signed>(buffer.size())))\n return;\n letter_wait -= dt;\n if (letter_wait <= 0)\n {\n unsigned add = (-letter_wait) \/ letter_wait_cooldown + 1;\n add_letter(add);\n }\n break;\n case Full:\n \/\/ TODO?: Change the trigger (button) into something else (like a function)?\n if (key_pressed(Key::K_A))\n {\n for (unsigned i = 0; i < nb_lines - 1; ++i)\n global_string_offset += line_nb_characters[i];\n\n line_widths[0] = line_widths[nb_lines - 1];\n line_nb_characters[0] = line_nb_characters[nb_lines - 1];\n\n for (unsigned i = 1; i < nb_lines; ++i)\n {\n line_widths[i] = 0;\n line_nb_characters[i] = 0;\n }\n nb_line_to_update = 1;\n state = Updating;\n }\n default:\n break;\n }\n}\n\nvoid Textbox::render(unsigned dt)\n{\n UNUSED(dt);\n if (buffer_index < 0)\n return;\n \/\/ TODO : store the last character's color to correctly reapply it if a line return\n \/\/ happens?\n current_color = 0xFFFF;\n put_rectangle(dimensions, Graphics::Black);\n unsigned global_index = global_string_offset;\n for (unsigned l = 0; l < nb_lines; l++)\n {\n unsigned cur_x = dimensions.x;\n unsigned cur_y = dimensions.y + l * fnt.baseline;\n for (unsigned line_index = 0; line_index < line_nb_characters[l]; ++line_index)\n {\n TextboxChar b = buffer[global_index + line_index];\n char c = b.c;\n if (c == MAGIC_TOKEN)\n {\n switch (b.routine)\n {\n \/\/ Change current color\n case 0x01:\n current_color = ((b.arg1 << 8) + b.arg2);\n break;\n }\n continue;\n }\n fnt.draw(cur_x, cur_y, c, current_color);\n \/\/ *shrugs*\n if (c == '\\n')\n continue;\n else if (c == ' ')\n cur_x += fnt.space_width;\n else\n cur_x += fnt.chars[static_cast<signed>(c)].dimensions.width + 1;\n }\n global_index += line_nb_characters[l];\n }\n \/\/ State indicator.\n Pixel indicator_color = Graphics::Black;\n if (state == Full)\n indicator_color = Graphics::Red;\n else if (state == Done)\n indicator_color = Graphics::Blue;\n\n if (indicator_color != Graphics::Black)\n put_rectangle({dimensions.x + static_cast<signed>(dimensions.width) - 3,\n dimensions.y + static_cast<signed>(dimensions.height) - 3, 3, 3},\n indicator_color);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: ooiEnergy.C,v 1.11 2000\/09\/20 07:11:39 oliver Exp $\n\n#include <BALL\/SOLVATION\/ooiEnergy.h>\n\n\n#include <BALL\/common.h>\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/COMMON\/exception.h>\n#include <BALL\/DATATYPE\/hashGrid.h>\n#include <BALL\/DATATYPE\/string.h>\n#include <BALL\/DATATYPE\/stringHashMap.h>\n#include <BALL\/STRUCTURE\/geometricProperties.h>\n#include <BALL\/KERNEL\/atom.h>\n#include <BALL\/KERNEL\/bond.h>\n#include <BALL\/STRUCTURE\/numericalSAS.h>\n#include <BALL\/FORMAT\/parameters.h>\n#include <BALL\/FORMAT\/parameterSection.h>\n#include <BALL\/MOLMEC\/COMMON\/typeRuleProcessor.h>\n\n#define OOI_PARAMETER_FILENAME \"solvation\/Ooi.ini\"\n\n\/\/#define BALL_DEBUG_OOI\n\nusing namespace std;\n\nnamespace BALL \n{\n\n\tnamespace OoiEnergy\n\t{\n\t\tbool is_initialized = false;\n\n\t\t\/\/ a hash map to convert names to Ooi types\n\t\tStringHashMap<Atom::Type> type_map;\n\n\t\t\/\/ a type rule assignment processor\n\t\tTypeRuleProcessor type_rule;\n\n\t\t\/\/ free energy is calculated as\n\t\t\/\/ dG = \\sum_i g_i A_i\n\t\t\/\/ where A_i is the atomic solvent accesible surface\n\t\t\/\/ area. The atomic radii are taken from the vector radius below.\n\t\tvector<float> radius;\n\t\tvector<float> g;\n\n\t\t\/\/ read the parameter files for calculateOoiEnergy \n\t\t\/\/ and set up the basic data structures\n\t\tvoid init()\n\t\t{\n\t\t\t\/\/ extract the parameters from the file\n\t\t\tPath path;\n\t\t\tString filename = path.find(OOI_PARAMETER_FILENAME);\n\t\t\tif (filename == \"\")\n\t\t\t{\n\t\t\t\tfilename = OOI_PARAMETER_FILENAME;\n\t\t\t}\n\t\t\tParameters parameters(filename);\n\n\t\t\tParameterSection parameter_section;\n\t\t\tif (!parameter_section.extractSection(parameters, \"OoiParameters\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot find section [OoiParameters] in file \"\n\t\t\t\t\t<< parameters.getFilename() << \".\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!parameter_section.hasVariable(\"g\") || !parameter_section.hasVariable(\"radius\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"OoiEnergy: section [OoiTypes] of file \" \n\t\t\t\t\t<< parameters.getFilename() << \" requires at least the columns 'g' and 'radius'.\" << endl;\n\t\t\t\treturn;\n\t\t\t}\t\t\t\t\t\t\t\n\n\t\t\tParameterSection type_section;\n\t\t\tif (!type_section.extractSection(parameters, \"OoiTypes\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot find section [OoiTypes] in file \"\n\t\t\t\t\t<< parameters.getFilename() << \".\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!type_section.hasVariable(\"type\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"OoiEnergy: section [OoiTypes] of file \" \n\t\t\t\t\t<< parameters.getFilename() << \" does not contain a variable column 'type'.\" << endl;\n\t\t\t\treturn;\n\t\t\t}\t\t\t\n\n\t\t\t\/\/ extract the parameters for each type\n\t\t\t\/\/ \n\t\t\tPosition radius_column = parameter_section.getColumnIndex(\"radius\");\n\t\t\tPosition g_column = parameter_section.getColumnIndex(\"g\");\n\t\t\tIndex max_index = -1;\n\t\t\tSize i;\n\t\t\tfor (i = 1; i <= parameter_section.getNumberOfKeys(); i++)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tString index_str(parameter_section.getKey(i));\n\t\t\t\tIndex index;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tindex = index_str.trim().toInt();\n\t\t\t\t\tif (index < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tLog.error() << \"calculateOoiEnergy: illegal atom type index: \" << index << endl;\n\t\t\t\t\t} \n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tif (index > max_index)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmax_index = index;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t\tcatch (Exception::InvalidFormat)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot convert to a number: \" << index_str << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (max_index < 0)\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: could not find any atom type in file \"\n\t\t\t\t\t\t\t\t\t << parameters.getFilename() << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ resize the vectors to hold all indices\n\t\t\tradius.resize((Size)max_index + 1);\n\t\t\tg.resize((Size)max_index + 1);\n\n\t\t\t\/\/ and read all values from the parameter section\n\t\t\tfor (i = 1; i <= parameter_section.getNumberOfKeys(); i++)\n\t\t\t{\n\t\t\t\tString index_str(parameter_section.getKey(i));\n\t\t\t\tIndex index;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tindex = index_str.trim().toInt();\n\n\t\t\t\t\t\/\/ we ignore illegal (negative) indices\n\t\t\t\t\tif (index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tradius[index] = parameter_section.getValue(i, radius_column).toFloat();\n\t\t\t\t\t\tg[index] = parameter_section.getValue(i, g_column).toFloat();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception::InvalidFormat)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot convert to a number: \" << index_str << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ extract all known types by iterating over all keys\n\t\t \/\/ and construct the hash map type_map\n\t\t\tPosition type_column = type_section.getColumnIndex(\"type\");\n\t\t\tfor (i = 1; i <= type_section.getNumberOfKeys(); i++)\n\t\t\t{\n\t\t\t\t\/\/ retrieve the type and check for validity\n\t\t\t\tString index_str(type_section.getValue(i, type_column));\n\t\t\t\tAtom::Type type = index_str.trim().toInt();\n\t\t\t\tif (type >= (Atom::Type)radius.size())\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: illegal atom type: \" << type << \" while reading parameter file.\" << endl;\n\t\t\t\t} \n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tindex_str = type_section.getValue(i, type_column);\n\t\t\t\t\ttype_map.insert(type_section.getKey(i), (Atom::Type)index_str.trim().toInt());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ set up the type rule processor\n\t\t\t\/\/ from the rules in the INI file\n\t\t\ttype_rule.initialize(parameters.getParameterFile(), \"TypeRules\");\n\n\t\t\t\/\/ we're done with the initialization\n\t\t\tis_initialized = true;\n\t\t}\n\t}\n\n\tdouble calculateOoiEnergy(AtomContainer& atoms) \n\t{\n\t\tusing namespace OoiEnergy;\n\n\t\t\/\/ read and interpret the parameters \n\t\t\/\/ this is only done the first time calculateOoiEnergy is called\n\t\tif (!is_initialized)\n\t\t{\n\t\t\tinit();\n\t\t\tif (!is_initialized)\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ assign radii and atom types for all atoms\n\t\tAtomIterator atom_it = atoms.beginAtom();\n\t\tfor (; +atom_it; ++atom_it) \n\t\t{\n\t\t\t\/\/ construct correct name, <RESNAME>:<ATOMNAME>\n\t\t\tString atom_name = atom_it->getFullName();\n\t\t\t\n\t\t\t\/\/ get the atom type from hash table\n\t\t\t\/\/ first, try a direct match\n\t\t\tAtom::Type atom_type = -1;\n\t\t\tif (type_map.has(atom_name))\n\t\t\t{\n\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\tatom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);\n\t\t\t\tif (type_map.has(atom_name))\n\t\t\t\t{\n\t\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t\t} \n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\t\/\/ try wildcard match\n\t\t\t\t\tatom_name = \"*:\" + atom_it->getName();\n\t\t\t\t\tif (type_map.has(atom_name))\n\t\t\t\t\t{\n\t\t\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ if the atom type could not be determined, complain\n\t\t\tif (atom_type < 0)\n\t\t\t{\n\t\t\t\t\/\/ try to apply the type rule processor\n\t\t\t\tatom_it->setType(-1);\n\t\t\t\ttype_rule(*atom_it);\n\t\t\t\tatom_type = atom_it->getType();\n\t\t\t}\n\n\t\t\tif (atom_type < 0)\n\t\t\t{\n\t\t\t\tLog.warn() << \"calculateOOIEnergy: did not find a suitable type for \" << atom_it->getFullName() << endl;\n\n\t\t\t\t\/\/ ignore this atom....\n\t\t\t\tatom_it->setType(-1);\n\t\t\t\tatom_it->setRadius(0.0);\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\t\/\/ assign type and radius\n\t\t\t\tatom_it->setType(atom_type);\n\t\t\t\tatom_it->setRadius(radius[atom_type]);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ calculate the atomic SAS areas\n\t\t\/\/ atom_SAS_areas hashes the atom pointer to the\n\t\t\/\/ surface area (in Angstrom^2)\n\t\tHashMap<Atom*,float> atom_SAS_areas;\n\t\tcalculateSASAtomAreas(atoms, atom_SAS_areas, 1.4, 1888);\n\n\t\t\/\/ iterate over all atoms and add up the energies\n\t\tfloat energy = 0.0;\n\t\tfor (atom_it = atoms.beginAtom(); +atom_it; ++atom_it) \n\t\t{\n\t\t\t\n\t\t\tif (atom_SAS_areas.has(&*atom_it))\n\t\t\t{\n\t\t\t\tAtom::Type atom_type = atom_it->getType();\n\t\t\t\tif (atom_type >= 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ add the energy contribution of the atom\n\t\t\t\t\tfloat tmp = atom_SAS_areas[&*atom_it] * g[atom_type];\n\t\t\t\t\tenergy += tmp;\n\n\t\t\t\t\t#ifdef BALL_DEBUG_OOI\n\t\t\t\t\t\tLog.info() << atom_it->getFullName() << \" A = \" << atom_SAS_areas[&*atom_it] \n \t\t\t\t\t\t\t\t\t << \" E = \" << tmp << \" kJ\/mol\" << endl;\n\t\t\t\t\t#endif\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t}\n\n\t\t\/\/ we're done.\n\t\treturn energy;\n\t}\n\n} \/\/ namespace BALL\n<commit_msg>massive cosmetic changes fixed: now starting at the first key<commit_after>\/\/ $Id: ooiEnergy.C,v 1.12 2001\/05\/05 21:11:46 amoll Exp $\n\n#include <BALL\/SOLVATION\/ooiEnergy.h>\n\n#include <BALL\/common.h>\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/COMMON\/exception.h>\n#include <BALL\/DATATYPE\/hashGrid.h>\n#include <BALL\/DATATYPE\/string.h>\n#include <BALL\/DATATYPE\/stringHashMap.h>\n#include <BALL\/STRUCTURE\/geometricProperties.h>\n#include <BALL\/KERNEL\/atom.h>\n#include <BALL\/KERNEL\/bond.h>\n#include <BALL\/STRUCTURE\/numericalSAS.h>\n#include <BALL\/FORMAT\/parameters.h>\n#include <BALL\/FORMAT\/parameterSection.h>\n#include <BALL\/MOLMEC\/COMMON\/typeRuleProcessor.h>\n\n#define OOI_PARAMETER_FILENAME \"solvation\/Ooi.ini\"\n\n\/\/#define BALL_DEBUG_OOI\n\nusing namespace std;\n\nnamespace BALL \n{\n\tnamespace OoiEnergy\n\t{\n\t\tbool is_initialized = false;\n\n\t\t\/\/ a hash map to convert names to Ooi types\n\t\tStringHashMap<Atom::Type> type_map;\n\n\t\t\/\/ a type rule assignment processor\n\t\tTypeRuleProcessor type_rule;\n\n\t\t\/\/ free energy is calculated as\n\t\t\/\/ dG = \\sum_i g_i A_i\n\t\t\/\/ where A_i is the atomic solvent accesible surface\n\t\t\/\/ area. The atomic radii are taken from the vector radius below.\n\t\tvector<float> radius;\n\t\tvector<float> g;\n\n\t\t\/\/ read the parameter files for calculateOoiEnergy \n\t\t\/\/ and set up the basic data structures\n\t\tvoid init()\n\t\t{\n\t\t\t\/\/ extract the parameters from the file\n\t\t\tPath path;\n\t\t\tString filename = path.find(OOI_PARAMETER_FILENAME);\n\t\t\tif (filename == \"\")\n\t\t\t{\n\t\t\t\tfilename = OOI_PARAMETER_FILENAME;\n\t\t\t}\n\t\t\tParameters parameters(filename);\n\n\t\t\tParameterSection parameter_section;\n\t\t\tif (!parameter_section.extractSection(parameters, \"OoiParameters\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot find section [OoiParameters] in file \"\n\t\t\t\t\t\t\t\t\t\t<< parameters.getFilename() << \".\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!parameter_section.hasVariable(\"g\") || !parameter_section.hasVariable(\"radius\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"OoiEnergy: section [OoiTypes] of file \" \n\t\t\t\t\t\t\t\t\t\t<< parameters.getFilename() \n\t\t\t\t\t\t\t\t\t\t<< \" requires at least the columns 'g' and 'radius'.\" << endl;\n\t\t\t\treturn;\n\t\t\t}\t\t\t\t\t\t\t\n\n\t\t\tParameterSection type_section;\n\t\t\tif (!type_section.extractSection(parameters, \"OoiTypes\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot find section [OoiTypes] in file \"\n\t\t\t\t\t\t\t\t\t\t<< parameters.getFilename() << \".\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!type_section.hasVariable(\"type\"))\n\t\t\t{\n\t\t\t\tLog.error() << \"OoiEnergy: section [OoiTypes] of file \" \n\t\t\t\t\t\t\t\t\t\t<< parameters.getFilename() \n\t\t\t\t\t\t\t\t\t\t<< \" does not contain a variable column 'type'.\" << endl;\n\t\t\t\treturn;\n\t\t\t}\t\t\t\n\n\t\t\t\/\/ extract the parameters for each type\n\t\t\tPosition radius_column = parameter_section.getColumnIndex(\"radius\");\n\t\t\tPosition g_column = parameter_section.getColumnIndex(\"g\");\n\t\t\tIndex max_index = -1;\n\t\t\tfor (Size i = 0; i < parameter_section.getNumberOfKeys(); i++)\n\t\t\t{\t\t\t\n\t\t\t\tString index_str(parameter_section.getKey(i));\n\t\t\t\tIndex index;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tindex = index_str.trim().toInt();\n\t\t\t\t} \n\t\t\t\tcatch (Exception::InvalidFormat)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot convert to a number: \" << index_str << endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (index < 0)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: illegal atom type index: \" << index << endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t} \n\n\t\t\t\tif (index > max_index)\n\t\t\t\t{\n\t\t\t\t\tmax_index = index;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (max_index < 0)\n\t\t\t{\n\t\t\t\tLog.error() << \"calculateOoiEnergy: could not find any atom type in file \"\n\t\t\t\t\t\t\t\t\t << parameters.getFilename() << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ resize the vectors to hold all indices\n\t\t\tradius.resize((Size)max_index + 1);\n\t\t\tg.resize((Size)max_index + 1);\n\n\t\t\t\/\/ and read all values from the parameter section\n\t\t\tfor (Size i = 0; i < parameter_section.getNumberOfKeys(); i++)\n\t\t\t{\n\t\t\t\tString index_str(parameter_section.getKey(i));\n\t\t\t\tIndex index;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tindex = index_str.trim().toInt();\n\n\t\t\t\t\t\/\/ we ignore illegal (negative) indices\n\t\t\t\t\tif (index >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tradius[index] = parameter_section.getValue(i, radius_column).toFloat();\n\t\t\t\t\t\tg[index] = parameter_section.getValue(i, g_column).toFloat();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception::InvalidFormat)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot convert to a number: \" << index_str << endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ extract all known types by iterating over all keys\n\t\t \/\/ and construct the hash map type_map\n\t\t\tPosition type_column = type_section.getColumnIndex(\"type\");\n\t\t\tfor (Size i = 0; i < type_section.getNumberOfKeys(); i++)\n\t\t\t{\n\t\t\t\t\/\/ retrieve the type and check for validity\n\t\t\t\tString index_str(type_section.getValue(i, type_column));\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tAtom::Type type = index_str.trim().toInt();\n\t\t\t\t\tif (type >= (Atom::Type)radius.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tLog.error() << \"calculateOoiEnergy: illegal atom type: \" << type \n\t\t\t\t\t\t\t\t\t\t\t\t<< \" while reading parameter file.\" << endl;\n\t\t\t\t\t} \n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tindex_str = type_section.getValue(i, type_column);\n\t\t\t\t\t\ttype_map.insert(type_section.getKey(i), (Atom::Type)index_str.trim().toInt());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (Exception::InvalidFormat)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"calculateOoiEnergy: cannot convert to a number: \" << index_str << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ set up the type rule processor\n\t\t\t\/\/ from the rules in the INI file\n\t\t\ttype_rule.initialize(parameters.getParameterFile(), \"TypeRules\");\n\n\t\t\t\/\/ we're done with the initialization\n\t\t\tis_initialized = true;\n\t\t}\n\t}\n\n\tdouble calculateOoiEnergy(AtomContainer& atoms) \n\t{\n\t\tusing namespace OoiEnergy;\n\n\t\t\/\/ read and interpret the parameters \n\t\t\/\/ this is only done the first time calculateOoiEnergy is called\n\t\tif (!is_initialized)\n\t\t{\n\t\t\tinit();\n\t\t\tif (!is_initialized)\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/ assign radii and atom types for all atoms\n\t\tAtomIterator atom_it = atoms.beginAtom();\n\t\tfor (; +atom_it; ++atom_it) \n\t\t{\n\t\t\t\/\/ construct correct name, <RESNAME>:<ATOMNAME>\n\t\t\tString atom_name = atom_it->getFullName();\n\t\t\t\n\t\t\t\/\/ get the atom type from hash table\n\t\t\t\/\/ first, try a direct match\n\t\t\tAtom::Type atom_type = -1;\n\t\t\tif (type_map.has(atom_name))\n\t\t\t{\n\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\tatom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);\n\t\t\t\tif (type_map.has(atom_name))\n\t\t\t\t{\n\t\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t\t} \n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\t\/\/ try wildcard match\n\t\t\t\t\tatom_name = \"*:\" + atom_it->getName();\n\t\t\t\t\tif (type_map.has(atom_name))\n\t\t\t\t\t{\n\t\t\t\t\t\tatom_type = type_map[atom_name];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ if the atom type could not be determined, complain\n\t\t\tif (atom_type < 0)\n\t\t\t{\n\t\t\t\t\/\/ try to apply the type rule processor\n\t\t\t\tatom_it->setType(-1);\n\t\t\t\ttype_rule(*atom_it);\n\t\t\t\tatom_type = atom_it->getType();\n\t\t\t}\n\n\t\t\tif (atom_type < 0)\n\t\t\t{\n\t\t\t\tLog.warn() << \"calculateOOIEnergy: did not find a suitable type for \" \n\t\t\t\t\t\t\t\t\t << atom_it->getFullName() << endl;\n\n\t\t\t\t\/\/ ignore this atom....\n\t\t\t\tatom_it->setType(-1);\n\t\t\t\tatom_it->setRadius(0.0);\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\t\/\/ assign type and radius\n\t\t\t\tatom_it->setType(atom_type);\n\t\t\t\tatom_it->setRadius(radius[atom_type]);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ calculate the atomic SAS areas\n\t\t\/\/ atom_SAS_areas hashes the atom pointer to the\n\t\t\/\/ surface area (in Angstrom^2)\n\t\tHashMap<Atom*,float> atom_SAS_areas;\n\t\tcalculateSASAtomAreas(atoms, atom_SAS_areas, 1.4, 1888);\n\n\t\t\/\/ iterate over all atoms and add up the energies\n\t\tfloat energy = 0.0;\n\t\tfor (atom_it = atoms.beginAtom(); +atom_it; ++atom_it) \n\t\t{\n\t\t\tif (atom_SAS_areas.has(&*atom_it))\n\t\t\t{\n\t\t\t\tAtom::Type atom_type = atom_it->getType();\n\t\t\t\tif (atom_type >= 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ add the energy contribution of the atom\n\t\t\t\t\tfloat tmp = atom_SAS_areas[&*atom_it] * g[atom_type];\n\t\t\t\t\tenergy += tmp;\n\n\t\t\t\t\t#ifdef BALL_DEBUG_OOI\n\t\t\t\t\t\tLog.info() << atom_it->getFullName() << \" A = \" << atom_SAS_areas[&*atom_it] \n \t\t\t\t\t\t\t\t\t << \" E = \" << tmp << \" kJ\/mol\" << endl;\n\t\t\t\t\t#endif\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t}\n\n\t\t\/\/ we're done.\n\t\treturn energy;\n\t}\n\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"<commit_before>\/*\n @ Kingsley Chen\n*\/\n\n#include \"kbase\\guid.h\"\n\n#include <objbase.h>\n\n#include <array>\n#include <cassert>\n\n#include \"kbase\\strings\\string_piece.h\"\n#include \"kbase\\strings\\sys_string_encoding_conversions.h\"\n\nnamespace kbase {\n\nstd::string GenerateGUID()\n{\n GUID guid;\n auto rv = CoCreateGuid(&guid);\n assert(SUCCEEDED(rv));\n if (!SUCCEEDED(rv)) {\n return std::string();\n }\n\n const int kGUIDSize = 40;\n std::array<wchar_t, kGUIDSize> guid_str;\n int count_written = StringFromGUID2(guid, guid_str.data(), kGUIDSize);\n\n \/\/ Since GUID contains ASCII-only characters, it is safe to do this conversion.\n \/\/ Strips off { and }.\n return count_written ?\n WideToASCII(WStringPiece(guid_str.data() + 1, count_written - 3)) :\n std::string();\n}\n\n} \/\/ namespace kbase<commit_msg>GUID: IsGUIDValid working on<commit_after>\/*\n @ Kingsley Chen\n*\/\n\n#include \"kbase\\guid.h\"\n\n#include <objbase.h>\n\n#include <array>\n#include <cassert>\n\n#include \"kbase\\strings\\string_piece.h\"\n#include \"kbase\\strings\\sys_string_encoding_conversions.h\"\n\nnamespace kbase {\n\nstd::string GenerateGUID()\n{\n GUID guid;\n auto rv = CoCreateGuid(&guid);\n assert(SUCCEEDED(rv));\n if (!SUCCEEDED(rv)) {\n return std::string();\n }\n\n const int kGUIDStrSize = 40;\n std::array<wchar_t, kGUIDStrSize> guid_str;\n int count_written = StringFromGUID2(guid, guid_str.data(), kGUIDStrSize);\n\n \/\/ Since GUID contains ASCII-only characters, it is safe to do this conversion.\n \/\/ Strips off { and }.\n return count_written ?\n WideToASCII(WStringPiece(guid_str.data() + 1, count_written - 3)) :\n std::string();\n}\n\nbool IsGUIDValid(const std::string& guid)\n{\n \/\/ Without { prepended and } appended.\n const size_t kGUIDSize = 36;\n if (guid.length() != kGUIDSize) {\n return false;\n }\n\n for (size_t i = 0; i < guid.length(); ++i) {\n if (i == 8 || i == 13 || i == 18 || i == 23) {\n \n }\n }\n}\n\n} \/\/ namespace kbase<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/map\/relative_map\/navigation_lane.h\"\n\n#include <limits>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n\nnamespace apollo {\nnamespace relative_map {\n\nusing apollo::common::VehicleStateProvider;\nusing apollo::common::util::DistanceXY;\nusing apollo::perception::PerceptionObstacles;\n\nNavigationLane::NavigationLane(const NavigationLaneConfig& config)\n : config_(config) {}\n\nvoid NavigationLane::SetConfig(const NavigationLaneConfig& config) {\n config_ = config;\n}\n\nbool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {\n \/\/ udpate perception_obstacles_\n perception_obstacles_ = perception_obstacles;\n if (!perception_obstacles.has_lane_marker()) {\n AERROR << \"No lane marker in perception_obstacles.\";\n return false;\n }\n\n \/\/ update adc_state_ from VehicleStateProvider\n adc_state_ = VehicleStateProvider::instance()->vehicle_state();\n\n navigation_path_.Clear();\n auto* path = navigation_path_.mutable_path();\n const auto& lane_marker = perception_obstacles_.lane_marker();\n\n if (std::fmin(lane_marker.left_lane_marker().quality(),\n lane_marker.right_lane_marker().quality()) >\n config_.min_lane_marker_quality()) {\n ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);\n } else if (navigation_info_.navigation_path_size() > 0) {\n ConvertNavigationLineToPath(path);\n } else {\n AERROR << \"Navigation Path is empty because neither lane markers nor \"\n \"navigation line are available.\";\n }\n\n return true;\n}\n\ndouble NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,\n const double c2, const double c3,\n const double z) const {\n return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;\n}\n\nvoid NavigationLane::ConvertNavigationLineToPath(common::Path* path) {\n CHECK_NOTNULL(path);\n if (navigation_info_.navigation_path_size() == 0 ||\n !navigation_info_.navigation_path(0).has_path() ||\n navigation_info_.navigation_path(0).path().path_point_size() == 0) {\n \/\/ path is empty\n return;\n }\n path->set_name(\"Path from navigation.\");\n UpdateProjectionIndex();\n\n \/\/ TODO(All): support multiple navigation path\n \/\/ currently, only 1 navigation path is supported\n const auto& navigation_path = navigation_info_.navigation_path(0).path();\n int curr_project_index = last_project_index_;\n\n \/\/ offset between the current vehicle state and navigation line\n const double dx = -navigation_path.path_point(curr_project_index).x();\n const double dy = -navigation_path.path_point(curr_project_index).y();\n for (int i = curr_project_index; i < navigation_path.path_point_size(); ++i) {\n auto* point = path->add_path_point();\n point->CopyFrom(navigation_path.path_point(i));\n\n \/\/ shift to (0, 0)\n double emu_x = point->x() + dx;\n double emu_y = point->y() + dy;\n\n double flu_x = 0.0;\n double flu_y = 0.0;\n common::math::RotateAxis(adc_state_.heading(), emu_x, emu_y, &flu_x,\n &flu_y);\n\n point->set_x(flu_x);\n point->set_y(flu_y);\n const double accumulated_s =\n navigation_path.path_point(i).s() -\n navigation_path.path_point(curr_project_index).s();\n point->set_s(accumulated_s);\n }\n\n \/\/ set left\/right width invalid as no width info from navigation line\n left_width_ = -1.0;\n right_width_ = -1.0;\n}\n\n\/\/ project adc_state_ onto path\nvoid NavigationLane::UpdateProjectionIndex() {\n \/\/ TODO(All): support multiple navigation path\n \/\/ currently, only 1 navigation path is supported\n const auto& path = navigation_info_.navigation_path(0).path();\n int index = 0;\n double min_d = std::numeric_limits<double>::max();\n for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {\n const double d = DistanceXY(adc_state_, path.path_point(i));\n if (d < min_d) {\n min_d = d;\n index = i;\n }\n const double kMaxDistance = 50.0;\n if (d > kMaxDistance) {\n break;\n }\n }\n last_project_index_ = index;\n}\n\nvoid NavigationLane::ConvertLaneMarkerToPath(\n const perception::LaneMarkers& lane_marker, common::Path* path) {\n CHECK_NOTNULL(path);\n\n path->set_name(\"Path from lane markers.\");\n const auto& left_lane = lane_marker.left_lane_marker();\n const auto& right_lane = lane_marker.right_lane_marker();\n\n const double unit_z = 1.0;\n if (left_lane.view_range() > right_lane.view_range()) {\n const double x_l_0 = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), 0.0);\n\n double accumulated_s = 0.0;\n for (double z = 0; z <= left_lane.view_range(); z += unit_z) {\n const double x_l = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);\n\n if (left_width_ < 0.0) {\n left_width_ = std::fabs(x_l);\n }\n if (right_width_ < 0.0) {\n right_width_ = left_width_;\n }\n\n double x1 = z;\n \/\/ TODO(All): use more precise method to shift y\n double y1 = std::fabs(x_l) - std::fabs(x_l_0);\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n\n if (path->path_point_size() > 1) {\n auto& pre_point = path->path_point(path->path_point_size() - 2);\n accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());\n }\n }\n } else {\n const double x_r_0 = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), 0.0);\n double accumulated_s = 0.0;\n for (double z = 0; z <= right_lane.view_range(); z += unit_z) {\n const double x_r = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);\n\n if (right_width_ < 0.0) {\n right_width_ = left_width_;\n }\n if (left_width_ < 0.0) {\n left_width_ = right_width_;\n }\n\n double x1 = z;\n \/\/ TODO(All): use more precise method to shift y\n double y1 = -std::fabs(x_r) + std::fabs(x_r_0);\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n\n if (path->path_point_size() > 1) {\n auto& pre_point = path->path_point(path->path_point_size() - 2);\n accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());\n }\n }\n }\n}\n\n} \/\/ namespace relative_map\n} \/\/ namespace apollo\n<commit_msg>Navigation: set max navigation lane length to 100m<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/map\/relative_map\/navigation_lane.h\"\n\n#include <limits>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n\nnamespace apollo {\nnamespace relative_map {\n\nusing apollo::common::VehicleStateProvider;\nusing apollo::common::util::DistanceXY;\nusing apollo::perception::PerceptionObstacles;\n\nNavigationLane::NavigationLane(const NavigationLaneConfig& config)\n : config_(config) {}\n\nvoid NavigationLane::SetConfig(const NavigationLaneConfig& config) {\n config_ = config;\n}\n\nbool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {\n \/\/ udpate perception_obstacles_\n perception_obstacles_ = perception_obstacles;\n if (!perception_obstacles.has_lane_marker()) {\n AERROR << \"No lane marker in perception_obstacles.\";\n return false;\n }\n\n \/\/ update adc_state_ from VehicleStateProvider\n adc_state_ = VehicleStateProvider::instance()->vehicle_state();\n\n navigation_path_.Clear();\n auto* path = navigation_path_.mutable_path();\n const auto& lane_marker = perception_obstacles_.lane_marker();\n\n if (std::fmin(lane_marker.left_lane_marker().quality(),\n lane_marker.right_lane_marker().quality()) >\n config_.min_lane_marker_quality()) {\n ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);\n } else if (navigation_info_.navigation_path_size() > 0) {\n ConvertNavigationLineToPath(path);\n } else {\n AERROR << \"Navigation Path is empty because neither lane markers nor \"\n \"navigation line are available.\";\n }\n\n return true;\n}\n\ndouble NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,\n const double c2, const double c3,\n const double z) const {\n return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;\n}\n\nvoid NavigationLane::ConvertNavigationLineToPath(common::Path* path) {\n CHECK_NOTNULL(path);\n if (navigation_info_.navigation_path_size() == 0 ||\n !navigation_info_.navigation_path(0).has_path() ||\n navigation_info_.navigation_path(0).path().path_point_size() == 0) {\n \/\/ path is empty\n return;\n }\n path->set_name(\"Path from navigation.\");\n UpdateProjectionIndex();\n\n \/\/ TODO(All): support multiple navigation path\n \/\/ currently, only 1 navigation path is supported\n const auto& navigation_path = navigation_info_.navigation_path(0).path();\n int curr_project_index = last_project_index_;\n\n \/\/ offset between the current vehicle state and navigation line\n const double dx = -navigation_path.path_point(curr_project_index).x();\n const double dy = -navigation_path.path_point(curr_project_index).y();\n for (int i = curr_project_index; i < navigation_path.path_point_size(); ++i) {\n auto* point = path->add_path_point();\n point->CopyFrom(navigation_path.path_point(i));\n\n \/\/ shift to (0, 0)\n double emu_x = point->x() + dx;\n double emu_y = point->y() + dy;\n\n double flu_x = 0.0;\n double flu_y = 0.0;\n common::math::RotateAxis(adc_state_.heading(), emu_x, emu_y, &flu_x,\n &flu_y);\n\n point->set_x(flu_x);\n point->set_y(flu_y);\n const double accumulated_s =\n navigation_path.path_point(i).s() -\n navigation_path.path_point(curr_project_index).s();\n point->set_s(accumulated_s);\n\n constexpr double kMaxAccumulatedS = 100.0;\n if (accumulated_s > kMaxAccumulatedS) {\n break;\n }\n }\n\n \/\/ set left\/right width invalid as no width info from navigation line\n left_width_ = -1.0;\n right_width_ = -1.0;\n}\n\n\/\/ project adc_state_ onto path\nvoid NavigationLane::UpdateProjectionIndex() {\n \/\/ TODO(All): support multiple navigation path\n \/\/ currently, only 1 navigation path is supported\n const auto& path = navigation_info_.navigation_path(0).path();\n int index = 0;\n double min_d = std::numeric_limits<double>::max();\n for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {\n const double d = DistanceXY(adc_state_, path.path_point(i));\n if (d < min_d) {\n min_d = d;\n index = i;\n }\n const double kMaxDistance = 50.0;\n if (d > kMaxDistance) {\n break;\n }\n }\n last_project_index_ = index;\n}\n\nvoid NavigationLane::ConvertLaneMarkerToPath(\n const perception::LaneMarkers& lane_marker, common::Path* path) {\n CHECK_NOTNULL(path);\n\n path->set_name(\"Path from lane markers.\");\n const auto& left_lane = lane_marker.left_lane_marker();\n const auto& right_lane = lane_marker.right_lane_marker();\n\n const double unit_z = 1.0;\n if (left_lane.view_range() > right_lane.view_range()) {\n const double x_l_0 = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), 0.0);\n\n double accumulated_s = 0.0;\n for (double z = 0; z <= left_lane.view_range(); z += unit_z) {\n const double x_l = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);\n\n if (left_width_ < 0.0) {\n left_width_ = std::fabs(x_l);\n }\n if (right_width_ < 0.0) {\n right_width_ = left_width_;\n }\n\n double x1 = z;\n \/\/ TODO(All): use more precise method to shift y\n double y1 = std::fabs(x_l) - std::fabs(x_l_0);\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n\n if (path->path_point_size() > 1) {\n auto& pre_point = path->path_point(path->path_point_size() - 2);\n accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());\n }\n }\n } else {\n const double x_r_0 = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), 0.0);\n double accumulated_s = 0.0;\n for (double z = 0; z <= right_lane.view_range(); z += unit_z) {\n const double x_r = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);\n\n if (right_width_ < 0.0) {\n right_width_ = left_width_;\n }\n if (left_width_ < 0.0) {\n left_width_ = right_width_;\n }\n\n double x1 = z;\n \/\/ TODO(All): use more precise method to shift y\n double y1 = -std::fabs(x_r) + std::fabs(x_r_0);\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n\n if (path->path_point_size() > 1) {\n auto& pre_point = path->path_point(path->path_point_size() - 2);\n accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y());\n }\n }\n }\n}\n\n} \/\/ namespace relative_map\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/map\/relative_map\/navigation_lane.h\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n\nnamespace apollo {\nnamespace relative_map {\nnamespace {\n\ndouble GetDistance(const common::VehicleState& adc_state,\n const common::PathPoint& p) {\n return std::hypot(adc_state.x() - p.x(), adc_state.y() - p.y());\n}\n}\nusing apollo::perception::PerceptionObstacles;\nusing apollo::common::VehicleStateProvider;\n\nbool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {\n \/\/ udpate perception_obstacles_\n perception_obstacles_ = perception_obstacles;\n if (!perception_obstacles.has_lane_marker()) {\n AERROR << \"No lane marker in perception_obstacles.\";\n return false;\n }\n\n \/\/ update adc_state_ from VehicleStateProvider\n adc_state_ = VehicleStateProvider::instance()->vehicle_state();\n\n navigation_path_.Clear();\n auto* path = navigation_path_.mutable_path();\n const auto& lane_marker = perception_obstacles_.lane_marker();\n\n const double kQualityThreshold = 0.5;\n if (navigation_info_.navigation_path_size() > 0 &&\n std::fmax(lane_marker.left_lane_marker().quality(),\n lane_marker.right_lane_marker().quality()) <\n kQualityThreshold) {\n ConvertNavigationLineToPath();\n } else {\n ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);\n }\n return true;\n}\n\ndouble NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,\n const double c2, const double c3,\n const double z) const {\n return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;\n}\n\nvoid NavigationLane::ConvertNavigationLineToPath() {\n if (navigation_info_.navigation_path_size() == 0 ||\n !navigation_info_.navigation_path(0).has_path() ||\n navigation_info_.navigation_path(0).path().path_point_size() == 0) {\n \/\/ path is empty\n return;\n }\n navigation_path_.Clear();\n auto* curr_path = navigation_path_.mutable_path();\n UpdateProjectionIndex();\n\n \/\/ TODO(All): support multiple navigation path\n \/\/ only support 1 navigation path\n const auto& path = navigation_info_.navigation_path(0).path();\n int curr_project_index = last_project_index_;\n for (int i = curr_project_index; i < path.path_point_size(); ++i) {\n auto* point = curr_path->add_path_point();\n point->CopyFrom(path.path_point(i));\n const double accumulated_s =\n path.path_point(i).s() - path.path_point(curr_project_index).s();\n point->set_s(accumulated_s);\n }\n}\n\n\/\/ project adc_state_ onto path\nvoid NavigationLane::UpdateProjectionIndex() {\n \/\/ TODO(All): support multiple navigation path\n \/\/ only support 1 navigation path\n const auto& path = navigation_info_.navigation_path(0).path();\n int index = 0;\n double min_d = std::numeric_limits<double>::max();\n for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {\n const double d = GetDistance(adc_state_, path.path_point(i));\n if (d < min_d) {\n min_d = d;\n index = i;\n }\n const double kMaxDistance = 50.0;\n if (d > kMaxDistance) {\n break;\n }\n }\n last_project_index_ = index;\n}\n\nvoid NavigationLane::ConvertLaneMarkerToPath(\n const perception::LaneMarkers& lane_marker, common::Path* path) {\n const auto& left_lane = lane_marker.left_lane_marker();\n const auto& right_lane = lane_marker.right_lane_marker();\n\n const double unit_z = 1.0;\n double accumulated_s = 0.0;\n for (double z = 0;\n z <= std::fmin(left_lane.view_range(), right_lane.view_range());\n z += unit_z) {\n const double x_l = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);\n const double x_r = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);\n\n double x1 = 0.0;\n double y1 = 0.0;\n \/\/ rotate from vehicle axis to x-y axis\n common::math::RotateAxis(-adc_state_.heading(), z, (x_l + x_r) \/ 2.0, &x1,\n &y1);\n\n \/\/ shift to get point on x-y axis\n x1 += adc_state_.x();\n y1 += adc_state_.y();\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n accumulated_s += std::hypot(x1, y1);\n }\n}\n\n} \/\/ namespace relative_map\n} \/\/ namespace apollo\n<commit_msg>Update navigation_lane.cc<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/map\/relative_map\/navigation_lane.h\"\n\n#include <limits>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n\nnamespace apollo {\nnamespace relative_map {\nnamespace {\n\ndouble GetDistance(const common::VehicleState& adc_state,\n const common::PathPoint& p) {\n return std::hypot(adc_state.x() - p.x(), adc_state.y() - p.y());\n}\n}\nusing apollo::perception::PerceptionObstacles;\nusing apollo::common::VehicleStateProvider;\n\nbool NavigationLane::Update(const PerceptionObstacles& perception_obstacles) {\n \/\/ udpate perception_obstacles_\n perception_obstacles_ = perception_obstacles;\n if (!perception_obstacles.has_lane_marker()) {\n AERROR << \"No lane marker in perception_obstacles.\";\n return false;\n }\n\n \/\/ update adc_state_ from VehicleStateProvider\n adc_state_ = VehicleStateProvider::instance()->vehicle_state();\n\n navigation_path_.Clear();\n auto* path = navigation_path_.mutable_path();\n const auto& lane_marker = perception_obstacles_.lane_marker();\n\n const double kQualityThreshold = 0.5;\n if (navigation_info_.navigation_path_size() > 0 &&\n std::fmax(lane_marker.left_lane_marker().quality(),\n lane_marker.right_lane_marker().quality()) <\n kQualityThreshold) {\n ConvertNavigationLineToPath();\n } else {\n ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), path);\n }\n return true;\n}\n\ndouble NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1,\n const double c2, const double c3,\n const double z) const {\n return c3 * std::pow(z, 3) + c2 * std::pow(z, 2) + c1 * z + c0;\n}\n\nvoid NavigationLane::ConvertNavigationLineToPath() {\n if (navigation_info_.navigation_path_size() == 0 ||\n !navigation_info_.navigation_path(0).has_path() ||\n navigation_info_.navigation_path(0).path().path_point_size() == 0) {\n \/\/ path is empty\n return;\n }\n navigation_path_.Clear();\n auto* curr_path = navigation_path_.mutable_path();\n UpdateProjectionIndex();\n\n \/\/ TODO(All): support multiple navigation path\n \/\/ only support 1 navigation path\n const auto& path = navigation_info_.navigation_path(0).path();\n int curr_project_index = last_project_index_;\n for (int i = curr_project_index; i < path.path_point_size(); ++i) {\n auto* point = curr_path->add_path_point();\n point->CopyFrom(path.path_point(i));\n const double accumulated_s =\n path.path_point(i).s() - path.path_point(curr_project_index).s();\n point->set_s(accumulated_s);\n }\n}\n\n\/\/ project adc_state_ onto path\nvoid NavigationLane::UpdateProjectionIndex() {\n \/\/ TODO(All): support multiple navigation path\n \/\/ only support 1 navigation path\n const auto& path = navigation_info_.navigation_path(0).path();\n int index = 0;\n double min_d = std::numeric_limits<double>::max();\n for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) {\n const double d = GetDistance(adc_state_, path.path_point(i));\n if (d < min_d) {\n min_d = d;\n index = i;\n }\n const double kMaxDistance = 50.0;\n if (d > kMaxDistance) {\n break;\n }\n }\n last_project_index_ = index;\n}\n\nvoid NavigationLane::ConvertLaneMarkerToPath(\n const perception::LaneMarkers& lane_marker, common::Path* path) {\n const auto& left_lane = lane_marker.left_lane_marker();\n const auto& right_lane = lane_marker.right_lane_marker();\n\n const double unit_z = 1.0;\n double accumulated_s = 0.0;\n for (double z = 0;\n z <= std::fmin(left_lane.view_range(), right_lane.view_range());\n z += unit_z) {\n const double x_l = EvaluateCubicPolynomial(\n left_lane.c0_position(), left_lane.c1_heading_angle(),\n left_lane.c2_curvature(), left_lane.c3_curvature_derivative(), z);\n const double x_r = EvaluateCubicPolynomial(\n right_lane.c0_position(), right_lane.c1_heading_angle(),\n right_lane.c2_curvature(), right_lane.c3_curvature_derivative(), z);\n\n double x1 = 0.0;\n double y1 = 0.0;\n \/\/ rotate from vehicle axis to x-y axis\n common::math::RotateAxis(-adc_state_.heading(), z, (x_l + x_r) \/ 2.0, &x1,\n &y1);\n\n \/\/ shift to get point on x-y axis\n x1 += adc_state_.x();\n y1 += adc_state_.y();\n\n auto* point = path->add_path_point();\n point->set_x(x1);\n point->set_y(y1);\n point->set_s(accumulated_s);\n accumulated_s += std::hypot(x1, y1);\n }\n}\n\n} \/\/ namespace relative_map\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lib\/ReaderWriter\/PECOFF\/PECOFFLinkingContext.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Atoms.h\"\n#include \"GroupedSectionsPass.h\"\n#include \"IdataPass.h\"\n#include \"LinkerGeneratedSymbolFile.h\"\n\n#include \"lld\/Core\/PassManager.h\"\n#include \"lld\/Passes\/LayoutPass.h\"\n#include \"lld\/Passes\/RoundTripNativePass.h\"\n#include \"lld\/Passes\/RoundTripYAMLPass.h\"\n#include \"lld\/ReaderWriter\/PECOFFLinkingContext.h\"\n#include \"lld\/ReaderWriter\/Reader.h\"\n#include \"lld\/ReaderWriter\/Simple.h\"\n#include \"lld\/ReaderWriter\/Writer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#include <bitset>\n#include <set>\n\nnamespace lld {\n\nnamespace {} \/\/ anonymous namespace\n\nbool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) {\n if (_stackReserve < _stackCommit) {\n diagnostics << \"Invalid stack size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _stackCommit\n << \" and \" << _stackReserve << \".\\n\";\n return false;\n }\n\n if (_heapReserve < _heapCommit) {\n diagnostics << \"Invalid heap size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _heapCommit\n << \" and \" << _heapReserve << \".\\n\";\n return false;\n }\n\n \/\/ It's an error if the base address is not multiple of 64K.\n if (_baseAddress & 0xffff) {\n diagnostics << \"Base address have to be multiple of 64K, but got \"\n << _baseAddress << \"\\n\";\n return false;\n }\n\n std::bitset<64> alignment(_sectionDefaultAlignment);\n if (alignment.count() != 1) {\n diagnostics << \"Section alignment must be a power of 2, but got \"\n << _sectionDefaultAlignment << \"\\n\";\n return false;\n }\n\n \/\/ Architectures other than i386 is not supported yet.\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) {\n diagnostics << \"Machine type other than x86 is not supported.\\n\";\n return false;\n }\n\n _reader = createReaderPECOFF(*this);\n _writer = createWriterPECOFF(*this);\n return true;\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const {\n if (entrySymbolName().empty())\n return nullptr;\n std::unique_ptr<SimpleFile> entryFile(\n new SimpleFile(*this, \"command line option \/entry\"));\n entryFile->addAtom(\n *(new (_allocator) SimpleUndefinedAtom(*entryFile, entrySymbolName())));\n return std::move(entryFile);\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const {\n if (_initialUndefinedSymbols.empty())\n return nullptr;\n std::unique_ptr<SimpleFile> undefinedSymFile(\n new SimpleFile(*this, \"command line option \/c (or) \/include\"));\n for (auto undefSymStr : _initialUndefinedSymbols)\n undefinedSymFile->addAtom(*(new (_allocator) SimpleUndefinedAtom(\n *undefinedSymFile, undefSymStr)));\n return std::move(undefinedSymFile);\n}\n\nbool PECOFFLinkingContext::createImplicitFiles(\n std::vector<std::unique_ptr<File> > &) const {\n std::unique_ptr<SimpleFileNode> fileNode(\n new SimpleFileNode(\"Implicit Files\"));\n std::unique_ptr<File> linkerGeneratedSymFile(\n new coff::LinkerGeneratedSymbolFile(*this));\n fileNode->appendInputFile(std::move(linkerGeneratedSymFile));\n inputGraph().insertOneElementAt(std::move(fileNode),\n InputGraph::Position::END);\n return true;\n}\n\n\/\/\/ Returns the section name in the resulting executable.\n\/\/\/\n\/\/\/ Sections in object files are usually output to the executable with the same\n\/\/\/ name, but you can rename by command line option. \/merge:from=to makes the\n\/\/\/ linker to combine \"from\" section contents to \"to\" section in the\n\/\/\/ executable. We have a mapping for the renaming. This method looks up the\n\/\/\/ table and returns a new section name if renamed.\nStringRef\nPECOFFLinkingContext::getFinalSectionName(StringRef sectionName) const {\n auto it = _renamedSections.find(sectionName);\n if (it == _renamedSections.end())\n return sectionName;\n return getFinalSectionName(it->second);\n}\n\n\/\/\/ Adds a mapping to the section renaming table. This method will be used for\n\/\/\/ \/merge command line option.\nbool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics,\n StringRef from, StringRef to) {\n auto it = _renamedSections.find(from);\n if (it != _renamedSections.end()) {\n if (it->second == to)\n \/\/ There's already the same mapping.\n return true;\n diagnostics << \"Section \\\"\" << from << \"\\\" is already mapped to \\\"\"\n << it->second << \", so it cannot be mapped to \\\"\" << to << \"\\\".\";\n return true;\n }\n\n \/\/ Add a mapping, and check if there's no cycle in the renaming mapping. The\n \/\/ cycle detection algorithm we use here is naive, but that's OK because the\n \/\/ number of mapping is usually less than 10.\n _renamedSections[from] = to;\n for (auto elem : _renamedSections) {\n StringRef sectionName = elem.first;\n std::set<StringRef> visited;\n visited.insert(sectionName);\n for (;;) {\n auto it = _renamedSections.find(sectionName);\n if (it == _renamedSections.end())\n break;\n if (visited.count(it->second)) {\n diagnostics << \"\/merge:\" << from << \"=\" << to << \" makes a cycle\";\n return false;\n }\n sectionName = it->second;\n visited.insert(sectionName);\n }\n }\n return true;\n}\n\n\/\/\/ Try to find the input library file from the search paths and append it to\n\/\/\/ the input file list. Returns true if the library file is found.\nStringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const {\n \/\/ Current directory always takes precedence over the search paths.\n if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename))\n return filename;\n \/\/ Iterate over the search paths.\n for (StringRef dir : _inputSearchPaths) {\n SmallString<128> path = dir;\n llvm::sys::path::append(path, filename);\n if (llvm::sys::fs::exists(path.str()))\n return allocateString(path.str());\n }\n return filename;\n}\n\nWriter &PECOFFLinkingContext::writer() const { return *_writer; }\n\nErrorOr<Reference::Kind>\nPECOFFLinkingContext::relocKindFromString(StringRef str) const {\n#define LLD_CASE(name) .Case(#name, llvm::COFF::name)\n int32_t ret = llvm::StringSwitch<int32_t>(str)\n LLD_CASE(IMAGE_REL_I386_ABSOLUTE)\n LLD_CASE(IMAGE_REL_I386_DIR32)\n LLD_CASE(IMAGE_REL_I386_DIR32NB)\n LLD_CASE(IMAGE_REL_I386_REL32)\n .Default(-1);\n#undef LLD_CASE\n if (ret == -1)\n return make_error_code(YamlReaderError::illegal_value);\n return ret;\n}\n\nErrorOr<std::string>\nPECOFFLinkingContext::stringFromRelocKind(Reference::Kind kind) const {\n switch (kind) {\n#define LLD_CASE(name) \\\n case llvm::COFF::name: \\\n return std::string(#name);\n\n LLD_CASE(IMAGE_REL_I386_ABSOLUTE)\n LLD_CASE(IMAGE_REL_I386_DIR32)\n LLD_CASE(IMAGE_REL_I386_DIR32NB)\n LLD_CASE(IMAGE_REL_I386_REL32)\n#undef LLD_CASE\n }\n return make_error_code(YamlReaderError::illegal_value);\n}\n\nvoid PECOFFLinkingContext::addPasses(PassManager &pm) {\n pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass()));\n pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new LayoutPass()));\n}\n} \/\/ end namespace lld\n<commit_msg>rename local variable to avoid shadowing warning<commit_after>\/\/===- lib\/ReaderWriter\/PECOFF\/PECOFFLinkingContext.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Atoms.h\"\n#include \"GroupedSectionsPass.h\"\n#include \"IdataPass.h\"\n#include \"LinkerGeneratedSymbolFile.h\"\n\n#include \"lld\/Core\/PassManager.h\"\n#include \"lld\/Passes\/LayoutPass.h\"\n#include \"lld\/Passes\/RoundTripNativePass.h\"\n#include \"lld\/Passes\/RoundTripYAMLPass.h\"\n#include \"lld\/ReaderWriter\/PECOFFLinkingContext.h\"\n#include \"lld\/ReaderWriter\/Reader.h\"\n#include \"lld\/ReaderWriter\/Simple.h\"\n#include \"lld\/ReaderWriter\/Writer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#include <bitset>\n#include <set>\n\nnamespace lld {\n\nnamespace {} \/\/ anonymous namespace\n\nbool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) {\n if (_stackReserve < _stackCommit) {\n diagnostics << \"Invalid stack size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _stackCommit\n << \" and \" << _stackReserve << \".\\n\";\n return false;\n }\n\n if (_heapReserve < _heapCommit) {\n diagnostics << \"Invalid heap size: reserve size must be equal to or \"\n << \"greater than commit size, but got \" << _heapCommit\n << \" and \" << _heapReserve << \".\\n\";\n return false;\n }\n\n \/\/ It's an error if the base address is not multiple of 64K.\n if (_baseAddress & 0xffff) {\n diagnostics << \"Base address have to be multiple of 64K, but got \"\n << _baseAddress << \"\\n\";\n return false;\n }\n\n std::bitset<64> alignment(_sectionDefaultAlignment);\n if (alignment.count() != 1) {\n diagnostics << \"Section alignment must be a power of 2, but got \"\n << _sectionDefaultAlignment << \"\\n\";\n return false;\n }\n\n \/\/ Architectures other than i386 is not supported yet.\n if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) {\n diagnostics << \"Machine type other than x86 is not supported.\\n\";\n return false;\n }\n\n _reader = createReaderPECOFF(*this);\n _writer = createWriterPECOFF(*this);\n return true;\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const {\n if (entrySymbolName().empty())\n return nullptr;\n std::unique_ptr<SimpleFile> entryFile(\n new SimpleFile(*this, \"command line option \/entry\"));\n entryFile->addAtom(\n *(new (_allocator) SimpleUndefinedAtom(*entryFile, entrySymbolName())));\n return std::move(entryFile);\n}\n\nstd::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const {\n if (_initialUndefinedSymbols.empty())\n return nullptr;\n std::unique_ptr<SimpleFile> undefinedSymFile(\n new SimpleFile(*this, \"command line option \/c (or) \/include\"));\n for (auto undefSymStr : _initialUndefinedSymbols)\n undefinedSymFile->addAtom(*(new (_allocator) SimpleUndefinedAtom(\n *undefinedSymFile, undefSymStr)));\n return std::move(undefinedSymFile);\n}\n\nbool PECOFFLinkingContext::createImplicitFiles(\n std::vector<std::unique_ptr<File> > &) const {\n std::unique_ptr<SimpleFileNode> fileNode(\n new SimpleFileNode(\"Implicit Files\"));\n std::unique_ptr<File> linkerGeneratedSymFile(\n new coff::LinkerGeneratedSymbolFile(*this));\n fileNode->appendInputFile(std::move(linkerGeneratedSymFile));\n inputGraph().insertOneElementAt(std::move(fileNode),\n InputGraph::Position::END);\n return true;\n}\n\n\/\/\/ Returns the section name in the resulting executable.\n\/\/\/\n\/\/\/ Sections in object files are usually output to the executable with the same\n\/\/\/ name, but you can rename by command line option. \/merge:from=to makes the\n\/\/\/ linker to combine \"from\" section contents to \"to\" section in the\n\/\/\/ executable. We have a mapping for the renaming. This method looks up the\n\/\/\/ table and returns a new section name if renamed.\nStringRef\nPECOFFLinkingContext::getFinalSectionName(StringRef sectionName) const {\n auto it = _renamedSections.find(sectionName);\n if (it == _renamedSections.end())\n return sectionName;\n return getFinalSectionName(it->second);\n}\n\n\/\/\/ Adds a mapping to the section renaming table. This method will be used for\n\/\/\/ \/merge command line option.\nbool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics,\n StringRef from, StringRef to) {\n auto it = _renamedSections.find(from);\n if (it != _renamedSections.end()) {\n if (it->second == to)\n \/\/ There's already the same mapping.\n return true;\n diagnostics << \"Section \\\"\" << from << \"\\\" is already mapped to \\\"\"\n << it->second << \", so it cannot be mapped to \\\"\" << to << \"\\\".\";\n return true;\n }\n\n \/\/ Add a mapping, and check if there's no cycle in the renaming mapping. The\n \/\/ cycle detection algorithm we use here is naive, but that's OK because the\n \/\/ number of mapping is usually less than 10.\n _renamedSections[from] = to;\n for (auto elem : _renamedSections) {\n StringRef sectionName = elem.first;\n std::set<StringRef> visited;\n visited.insert(sectionName);\n for (;;) {\n auto pos = _renamedSections.find(sectionName);\n if (pos == _renamedSections.end())\n break;\n if (visited.count(pos->second)) {\n diagnostics << \"\/merge:\" << from << \"=\" << to << \" makes a cycle\";\n return false;\n }\n sectionName = pos->second;\n visited.insert(sectionName);\n }\n }\n return true;\n}\n\n\/\/\/ Try to find the input library file from the search paths and append it to\n\/\/\/ the input file list. Returns true if the library file is found.\nStringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const {\n \/\/ Current directory always takes precedence over the search paths.\n if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename))\n return filename;\n \/\/ Iterate over the search paths.\n for (StringRef dir : _inputSearchPaths) {\n SmallString<128> path = dir;\n llvm::sys::path::append(path, filename);\n if (llvm::sys::fs::exists(path.str()))\n return allocateString(path.str());\n }\n return filename;\n}\n\nWriter &PECOFFLinkingContext::writer() const { return *_writer; }\n\nErrorOr<Reference::Kind>\nPECOFFLinkingContext::relocKindFromString(StringRef str) const {\n#define LLD_CASE(name) .Case(#name, llvm::COFF::name)\n int32_t ret = llvm::StringSwitch<int32_t>(str)\n LLD_CASE(IMAGE_REL_I386_ABSOLUTE)\n LLD_CASE(IMAGE_REL_I386_DIR32)\n LLD_CASE(IMAGE_REL_I386_DIR32NB)\n LLD_CASE(IMAGE_REL_I386_REL32)\n .Default(-1);\n#undef LLD_CASE\n if (ret == -1)\n return make_error_code(YamlReaderError::illegal_value);\n return ret;\n}\n\nErrorOr<std::string>\nPECOFFLinkingContext::stringFromRelocKind(Reference::Kind kind) const {\n switch (kind) {\n#define LLD_CASE(name) \\\n case llvm::COFF::name: \\\n return std::string(#name);\n\n LLD_CASE(IMAGE_REL_I386_ABSOLUTE)\n LLD_CASE(IMAGE_REL_I386_DIR32)\n LLD_CASE(IMAGE_REL_I386_DIR32NB)\n LLD_CASE(IMAGE_REL_I386_REL32)\n#undef LLD_CASE\n }\n return make_error_code(YamlReaderError::illegal_value);\n}\n\nvoid PECOFFLinkingContext::addPasses(PassManager &pm) {\n pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass()));\n pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this)));\n pm.add(std::unique_ptr<Pass>(new LayoutPass()));\n}\n} \/\/ end namespace lld\n<|endoftext|>"} {"text":"<commit_before>\/\/===- EdgeProfiling.cpp - Insert counters for edge profiling -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass instruments the specified program with counters for edge profiling.\n\/\/ Edge profiling can give a reasonable approximation of the hot paths through a\n\/\/ program, and is used for a wide variety of program transformations.\n\/\/\n\/\/ Note that this implementation is very naive. We insert a counter for *every*\n\/\/ edge in the program, instead of using control flow information to prune the\n\/\/ number of counters inserted.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ProfilingUtils.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Streams.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Instrumentation.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n class VISIBILITY_HIDDEN EdgeProfiler : public ModulePass {\n bool runOnModule(Module &M);\n public:\n static char ID; \/\/ Pass identification, replacement for typeid\n EdgeProfiler() : ModulePass((intptr_t)&ID) {}\n };\n\n char EdgeProfiler::ID = 0;\n RegisterPass<EdgeProfiler> X(\"insert-edge-profiling\",\n \"Insert instrumentation for edge profiling\");\n}\n\nModulePass *llvm::createEdgeProfilerPass() { return new EdgeProfiler(); }\n\nbool EdgeProfiler::runOnModule(Module &M) {\n Function *Main = M.getFunction(\"main\");\n if (Main == 0) {\n cerr << \"WARNING: cannot insert edge profiling into a module\"\n << \" with no main function!\\n\";\n return false; \/\/ No main, no instrumentation!\n }\n\n std::set<BasicBlock*> BlocksToInstrument;\n unsigned NumEdges = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {\n \/\/ Keep track of which blocks need to be instrumented. We don't want to\n \/\/ instrument blocks that are added as the result of breaking critical\n \/\/ edges!\n BlocksToInstrument.insert(BB);\n NumEdges += BB->getTerminator()->getNumSuccessors();\n }\n\n const Type *ATy = ArrayType::get(Type::Int32Ty, NumEdges);\n GlobalVariable *Counters =\n new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,\n Constant::getNullValue(ATy), \"EdgeProfCounters\", &M);\n\n \/\/ Instrument all of the edges...\n unsigned i = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n if (BlocksToInstrument.count(BB)) { \/\/ Don't instrument inserted blocks\n \/\/ Okay, we have to add a counter of each outgoing edge. If the\n \/\/ outgoing edge is not critical don't split it, just insert the counter\n \/\/ in the source or destination of the edge.\n TerminatorInst *TI = BB->getTerminator();\n for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {\n \/\/ If the edge is critical, split it.\n SplitCriticalEdge(TI, s, this);\n\n \/\/ Okay, we are guaranteed that the edge is no longer critical. If we\n \/\/ only have a single successor, insert the counter in this block,\n \/\/ otherwise insert it in the successor block.\n if (TI->getNumSuccessors() == 0) {\n \/\/ Insert counter at the start of the block\n IncrementCounterInBlock(BB, i++, Counters);\n } else {\n \/\/ Insert counter at the start of the block\n IncrementCounterInBlock(TI->getSuccessor(s), i++, Counters);\n }\n }\n }\n\n \/\/ Add the initialization call to main.\n InsertProfilingInitCall(Main, \"llvm_start_edge_profiling\", Counters);\n return true;\n}\n\n<commit_msg>Fix for edge profiling, patch by 'Marc' for PR1857<commit_after>\/\/===- EdgeProfiling.cpp - Insert counters for edge profiling -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass instruments the specified program with counters for edge profiling.\n\/\/ Edge profiling can give a reasonable approximation of the hot paths through a\n\/\/ program, and is used for a wide variety of program transformations.\n\/\/\n\/\/ Note that this implementation is very naive. We insert a counter for *every*\n\/\/ edge in the program, instead of using control flow information to prune the\n\/\/ number of counters inserted.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ProfilingUtils.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Streams.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Instrumentation.h\"\n#include <set>\nusing namespace llvm;\n\nnamespace {\n class VISIBILITY_HIDDEN EdgeProfiler : public ModulePass {\n bool runOnModule(Module &M);\n public:\n static char ID; \/\/ Pass identification, replacement for typeid\n EdgeProfiler() : ModulePass((intptr_t)&ID) {}\n };\n\n char EdgeProfiler::ID = 0;\n RegisterPass<EdgeProfiler> X(\"insert-edge-profiling\",\n \"Insert instrumentation for edge profiling\");\n}\n\nModulePass *llvm::createEdgeProfilerPass() { return new EdgeProfiler(); }\n\nbool EdgeProfiler::runOnModule(Module &M) {\n Function *Main = M.getFunction(\"main\");\n if (Main == 0) {\n cerr << \"WARNING: cannot insert edge profiling into a module\"\n << \" with no main function!\\n\";\n return false; \/\/ No main, no instrumentation!\n }\n\n std::set<BasicBlock*> BlocksToInstrument;\n unsigned NumEdges = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {\n \/\/ Keep track of which blocks need to be instrumented. We don't want to\n \/\/ instrument blocks that are added as the result of breaking critical\n \/\/ edges!\n BlocksToInstrument.insert(BB);\n NumEdges += BB->getTerminator()->getNumSuccessors();\n }\n\n const Type *ATy = ArrayType::get(Type::Int32Ty, NumEdges);\n GlobalVariable *Counters =\n new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,\n Constant::getNullValue(ATy), \"EdgeProfCounters\", &M);\n\n \/\/ Instrument all of the edges...\n unsigned i = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n if (BlocksToInstrument.count(BB)) { \/\/ Don't instrument inserted blocks\n \/\/ Okay, we have to add a counter of each outgoing edge. If the\n \/\/ outgoing edge is not critical don't split it, just insert the counter\n \/\/ in the source or destination of the edge.\n TerminatorInst *TI = BB->getTerminator();\n for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {\n \/\/ If the edge is critical, split it.\n SplitCriticalEdge(TI, s, this);\n\n \/\/ Okay, we are guaranteed that the edge is no longer critical. If we\n \/\/ only have a single successor, insert the counter in this block,\n \/\/ otherwise insert it in the successor block.\n if (TI->getNumSuccessors() == 1) {\n \/\/ Insert counter at the start of the block\n IncrementCounterInBlock(BB, i++, Counters);\n } else {\n \/\/ Insert counter at the start of the block\n IncrementCounterInBlock(TI->getSuccessor(s), i++, Counters);\n }\n }\n }\n\n \/\/ Add the initialization call to main.\n InsertProfilingInitCall(Main, \"llvm_start_edge_profiling\", Counters);\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"generated\/cpp\/SQLite3Base.h\"\n#include \"json\/JSONIterator.h\"\n#include \"db\/DBAdapter.h\"\n#include \"common\/RhodesApp.h\"\n\nextern \"C\" {\nint rho_db_open(const char* szDBPath, const char* szDBPartition, void** ppDB);\nint rho_db_close(void* pDB);\nint rho_db_startTransaction(void* pDB);\nint rho_db_commitTransaction(void* pDB);\nint rho_db_rollbackTransaction(void* pDB);\nint rho_db_is_ui_waitfordb(void* pDB);\nvoid rho_db_lock(void* pDB);\nvoid rho_db_unlock(void* pDB);\nint rho_db_is_table_exist(void* pDB, const char* szTableName);\nunsigned long rb_c_impl_SQLite3_execute(int argc, unsigned long *argv, void* pDB);\n};\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"SQLite3\"\n\nnamespace rho {\nnamespace database {\n\nusing namespace rho::apiGenerator;\nusing namespace rho::common;\n\nclass CSQLite3Impl: public CSQLite3Base\n{\npublic:\n\n virtual void open( const rho::String& dbPath, const rho::String& dbPartition, rho::apiGenerator::CMethodResult& oResult);\n virtual void close(rho::apiGenerator::CMethodResult& oResult);\n virtual void startTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void commitTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void rollbackTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void lockDb(rho::apiGenerator::CMethodResult& oResult);\n virtual void unlockDb(rho::apiGenerator::CMethodResult& oResult);\n\tvirtual void doImport(const rho::String& zipName, rho::apiGenerator::CMethodResult& oResult);\n\tvirtual void doExport(rho::apiGenerator::CMethodResult& oResult);\n virtual void destroyTables(const rho::Vector<rho::String>& include, const rho::Vector<rho::String>& exclude, rho::apiGenerator::CMethodResult& oResult);\n virtual void isTableExist( const rho::String& tableName, rho::apiGenerator::CMethodResult& oResult);\n virtual void isUiWaitForDb(rho::apiGenerator::CMethodResult& oResult);\n\tvoid* getDb() const {return m_pDB;}\n\nprivate:\n\tvoid* m_pDB;\n\n};\n\nvoid CSQLite3Impl::open( const rho::String& dbPath, const rho::String& dbPartition, rho::apiGenerator::CMethodResult& oResult)\n{\n\tm_pDB = NULL;\n\trho_db_open(dbPath.c_str(), dbPartition.c_str(), &m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::close(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_close(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::startTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_startTransaction(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::commitTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_commitTransaction(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::rollbackTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n rho_db_rollbackTransaction(m_pDB);\n}\n\nvoid CSQLite3Impl::lockDb(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_lock(m_pDB);\n}\n\nvoid CSQLite3Impl::unlockDb(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_unlock(m_pDB);\n}\n\nvoid CSQLite3Impl::destroyTables(const rho::Vector<rho::String>& include, const rho::Vector<rho::String>& exclude, rho::apiGenerator::CMethodResult& oResult)\n{\n rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n db.destroy_tables(include,exclude);\n}\n\nvoid CSQLite3Impl::isTableExist( const rho::String& tableName, rho::apiGenerator::CMethodResult& oResult)\n{\n\tint result;\n\t\n\tresult = rho_db_is_table_exist(m_pDB, tableName.c_str());\n\toResult.set(result ? true : false);\n}\n\nvoid CSQLite3Impl::isUiWaitForDb( rho::apiGenerator::CMethodResult& oResult)\n{\n\tint result;\n\t\n\tresult = rho_db_is_ui_waitfordb(m_pDB);\n\toResult.set(result ? true : false);\n}\n\nvoid CSQLite3Impl::doImport(const rho::String& zipName, rho::apiGenerator::CMethodResult& oResult)\n{\n\trho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n\tbool bRes = db.importDatabase(zipName);\n oResult.set(bRes);\n}\n\nvoid CSQLite3Impl::doExport(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n String strRes = db.exportDatabase();\n oResult.set(strRes);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass CSQLite3SingletonImpl: public CSQLite3SingletonBase\n{\npublic:\n};\n\nclass CSQLite3Factory: public CSQLite3FactoryBase\n{\npublic:\n ~CSQLite3Factory(){}\n\n ISQLite3Singleton* createModuleSingleton()\n { \n return new CSQLite3SingletonImpl(); \n }\n\n virtual ISQLite3* createModuleByID(const rho::String& strID){ return new CSQLite3Impl(); };\n};\n\n}\n}\n\nextern \"C\" void Init_SQLite3()\n{\n rho::database::CSQLite3Factory::setInstance( new rho::database::CSQLite3Factory() );\n\n RHODESAPP().getExtManager().requireRubyFile(\"Database\");\n\n rho::database::Init_SQLite3_API();\n}\n\nextern \"C\" unsigned long rb_impl_SQLite3_execute(int argc, unsigned long *argv, rho::database::ISQLite3* pObj)\n{\n void* pDB = static_cast<rho::database::CSQLite3Impl*>(pObj)->getDb();\n return rb_c_impl_SQLite3_execute(argc, argv, pDB);\n}\n\nrho::String js_SQLite3_execute(rho::json::CJSONArray& argv, const rho::String& strObjID)\n{\n \/\/TODO: js_Database_execute\n return \"{}\";\n}\n<commit_msg>api: database: support js execute<commit_after>#include \"generated\/cpp\/SQLite3Base.h\"\n#include \"json\/JSONIterator.h\"\n#include \"db\/DBAdapter.h\"\n#include \"common\/RhodesApp.h\"\n#include \"statistic\/RhoProfiler.h\"\n#include \"common\/StringConverter.h\"\n\nextern \"C\" {\nint rho_db_open(const char* szDBPath, const char* szDBPartition, void** ppDB);\nint rho_db_close(void* pDB);\nint rho_db_startTransaction(void* pDB);\nint rho_db_commitTransaction(void* pDB);\nint rho_db_rollbackTransaction(void* pDB);\nint rho_db_is_ui_waitfordb(void* pDB);\nvoid rho_db_lock(void* pDB);\nvoid rho_db_unlock(void* pDB);\nint rho_db_is_table_exist(void* pDB, const char* szTableName);\nunsigned long rb_c_impl_SQLite3_execute(int argc, unsigned long *argv, void* pDB);\n\nvoid* rho_db_get_handle(void* pDB);\nint rho_db_prepare_statement(void* pDB, const char* szSql, int nByte, sqlite3_stmt **ppStmt);\n\n};\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"SQLite3\"\n\nnamespace rho {\nnamespace database {\n\nusing namespace rho::apiGenerator;\nusing namespace rho::common;\n\nclass CSQLite3Impl: public CSQLite3Base\n{\npublic:\n\n virtual void open( const rho::String& dbPath, const rho::String& dbPartition, rho::apiGenerator::CMethodResult& oResult);\n virtual void close(rho::apiGenerator::CMethodResult& oResult);\n virtual void startTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void commitTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void rollbackTransaction(rho::apiGenerator::CMethodResult& oResult);\n virtual void lockDb(rho::apiGenerator::CMethodResult& oResult);\n virtual void unlockDb(rho::apiGenerator::CMethodResult& oResult);\n\tvirtual void doImport(const rho::String& zipName, rho::apiGenerator::CMethodResult& oResult);\n\tvirtual void doExport(rho::apiGenerator::CMethodResult& oResult);\n virtual void destroyTables(const rho::Vector<rho::String>& include, const rho::Vector<rho::String>& exclude, rho::apiGenerator::CMethodResult& oResult);\n virtual void isTableExist( const rho::String& tableName, rho::apiGenerator::CMethodResult& oResult);\n virtual void isUiWaitForDb(rho::apiGenerator::CMethodResult& oResult);\n\tvoid* getDb() const {return m_pDB;}\n\nprivate:\n\tvoid* m_pDB;\n\n};\n\nvoid CSQLite3Impl::open( const rho::String& dbPath, const rho::String& dbPartition, rho::apiGenerator::CMethodResult& oResult)\n{\n\tm_pDB = NULL;\n\trho_db_open(dbPath.c_str(), dbPartition.c_str(), &m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::close(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_close(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::startTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_startTransaction(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::commitTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_commitTransaction(m_pDB);\n \/\/TODO: process errors\n}\n\nvoid CSQLite3Impl::rollbackTransaction(rho::apiGenerator::CMethodResult& oResult)\n{\n rho_db_rollbackTransaction(m_pDB);\n}\n\nvoid CSQLite3Impl::lockDb(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_lock(m_pDB);\n}\n\nvoid CSQLite3Impl::unlockDb(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_db_unlock(m_pDB);\n}\n\nvoid CSQLite3Impl::destroyTables(const rho::Vector<rho::String>& include, const rho::Vector<rho::String>& exclude, rho::apiGenerator::CMethodResult& oResult)\n{\n rho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n db.destroy_tables(include,exclude);\n}\n\nvoid CSQLite3Impl::isTableExist( const rho::String& tableName, rho::apiGenerator::CMethodResult& oResult)\n{\n\tint result;\n\t\n\tresult = rho_db_is_table_exist(m_pDB, tableName.c_str());\n\toResult.set(result ? true : false);\n}\n\nvoid CSQLite3Impl::isUiWaitForDb( rho::apiGenerator::CMethodResult& oResult)\n{\n\tint result;\n\t\n\tresult = rho_db_is_ui_waitfordb(m_pDB);\n\toResult.set(result ? true : false);\n}\n\nvoid CSQLite3Impl::doImport(const rho::String& zipName, rho::apiGenerator::CMethodResult& oResult)\n{\n\trho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n\tbool bRes = db.importDatabase(zipName);\n oResult.set(bRes);\n}\n\nvoid CSQLite3Impl::doExport(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho::db::CDBAdapter& db = *((rho::db::CDBAdapter*)m_pDB);\n String strRes = db.exportDatabase();\n oResult.set(strRes);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass CSQLite3SingletonImpl: public CSQLite3SingletonBase\n{\npublic:\n};\n\nclass CSQLite3Factory: public CSQLite3FactoryBase\n{\npublic:\n ~CSQLite3Factory(){}\n\n ISQLite3Singleton* createModuleSingleton()\n { \n return new CSQLite3SingletonImpl(); \n }\n\n virtual ISQLite3* createModuleByID(const rho::String& strID){ return new CSQLite3Impl(); };\n};\n\n}\n}\n\nextern \"C\" void Init_SQLite3()\n{\n rho::database::CSQLite3Factory::setInstance( new rho::database::CSQLite3Factory() );\n\n RHODESAPP().getExtManager().requireRubyFile(\"Database\");\n\n rho::database::Init_SQLite3_API();\n}\n\nextern \"C\" unsigned long rb_impl_SQLite3_execute(int argc, unsigned long *argv, rho::database::ISQLite3* pObj)\n{\n void* pDB = static_cast<rho::database::CSQLite3Impl*>(pObj)->getDb();\n return rb_c_impl_SQLite3_execute(argc, argv, pDB);\n}\n\nusing namespace rho;\nusing namespace rho::common;\nusing namespace rho::json;\n\nrho::String js_SQLite3_execute(CJSONArray& argv, const rho::String& strObjID)\n{\n rho::database::ISQLite3* pObj = rho::database::CSQLite3FactoryBase::getInstance()->getModuleByID(strObjID);\n void* pDB = static_cast<rho::database::CSQLite3Impl*>(pObj)->getDb();\n\n sqlite3 * db = NULL;\n\tvoid **ppDB = &pDB;\t\t\n\tsqlite3_stmt *statement = NULL;\n\tconst char* sql = NULL;\n\tVector< rho::Hashtable<rho::String, rho::String> > arRes;\n rho::apiGenerator::CMethodResult oResult;\n\n\tint nRes = 0;\n char * szErrMsg = 0;\n int is_batch = 0;\n\n\tdb = (sqlite3 *)rho_db_get_handle(*ppDB);\n sql = argv[0].getString();\n is_batch = argv[1].getBoolean();\n\n RAWTRACE1(\"db_execute: %s\", sql);\n\n PROF_START_CREATED(\"SQLITE\");\n if ( is_batch )\n {\n PROF_START_CREATED(\"SQLITE_EXEC\");\n\n rho_db_lock(*ppDB);\n nRes = sqlite3_exec(db, sql, NULL, NULL, &szErrMsg);\n rho_db_unlock(*ppDB);\n\n PROF_STOP(\"SQLITE_EXEC\");\n }\n else\n {\n rho_db_lock(*ppDB);\n PROF_START_CREATED(\"SQLITE_PREPARE\");\n nRes = rho_db_prepare_statement(*ppDB, sql, -1, &statement);\n PROF_STOP(\"SQLITE_PREPARE\");\n if ( nRes != SQLITE_OK)\n {\n szErrMsg = (char *)sqlite3_errmsg(db);\n rho_db_unlock(*ppDB);\n\n oResult.setArgError( String(\"could not prepare statement: \") + convertToStringA(nRes) + \"; Message: \" + (szErrMsg?szErrMsg:\"\"));\n return oResult.toJSON();\n }\n\n if ( argv.getSize() > 2 && argv[2].isArray() )\n {\n int i = 0;\n CJSONArray args( argv[2] );\n \n for( ; i < args.getSize(); i++ )\n {\n CJSONEntry arg = args[i];\n if ( arg.isNull() )\n {\n sqlite3_bind_null(statement, i+1);\n continue;\n }\n\n if ( arg.isString() )\n sqlite3_bind_text(statement, i+1, arg.getString(), strlen(arg.getString()), SQLITE_TRANSIENT);\n else if (arg.isFloat())\n sqlite3_bind_double(statement, i+1, arg.getDouble() );\n else if (arg.isInteger())\n sqlite3_bind_int64(statement, i+1, arg.getUInt64() );\n else if (arg.isBoolean())\n sqlite3_bind_int(statement, i+1, arg.getBoolean() ? 1 : 0 );\n else\n\t\t\t\t{\n sqlite3_reset(statement);\n\n oResult.setArgError( String(\"Unsupported argument type. Argument number: \") + convertToStringA(i));\n return oResult.toJSON();\n\t\t\t\t}\n }\n }\n\n PROF_START_CREATED(\"SQLITE_EXEC\");\n nRes = sqlite3_step(statement);\n PROF_STOP(\"SQLITE_EXEC\");\n\n\t while( nRes== SQLITE_ROW ) \n {\n\t\t int nCount = sqlite3_data_count(statement);\n\t\t int nCol = 0;\n rho::Hashtable<rho::String, rho::String> hashRec;\n\n\t\t for(;nCol<nCount;nCol++)\n {\n\t\t\t int nColType = sqlite3_column_type(statement,nCol);\n\t\t\t const char* szColName = sqlite3_column_name(statement,nCol);\n String colValue;\n \t\t\t\n\t\t\t switch(nColType)\n {\n\t\t\t\t case SQLITE_NULL:\n\t\t\t\t\t break;\n case SQLITE_FLOAT:\n {\n double dVal = sqlite3_column_double(statement, nCol);\n colValue = convertToStringA(dVal);\n break;\n }\n case SQLITE_INTEGER:\n {\n sqlite_int64 nVal = sqlite3_column_int64(statement, nCol);\n colValue = convertToStringA(nVal);\n break;\n }\n\t\t\t\t default:{\n sqlite3_value * sqlValue = sqlite3_column_value(statement, nCol);\n int nLen = sqlite3_value_bytes(sqlValue);\n const char* szValue = (const char *)sqlite3_value_text(sqlValue);\n\t\t\t\t\t colValue = String(szValue, nLen);\n\t\t\t\t\t break;\n\t\t\t\t }\n\t\t\t }\n \t\t\t\n hashRec[szColName] = colValue;\n\t\t }\n\n arRes.addElement( hashRec );\n\n PROF_START_CREATED(\"SQLITE_EXEC\");\n nRes = sqlite3_step(statement);\n PROF_STOP(\"SQLITE_EXEC\");\n\n\t }\n\n rho_db_unlock(*ppDB);\n\n }\n\n if ( statement )\n sqlite3_reset(statement);\n\n PROF_STOP(\"SQLITE\");\n\n if ( nRes != SQLITE_OK && nRes != SQLITE_ROW && nRes != SQLITE_DONE )\n {\n if ( !szErrMsg )\n szErrMsg = (char*)sqlite3_errmsg(db);\n\n oResult.setError( String(\"could not execute statement: \") + convertToStringA(nRes) + \"; Message: \" + (szErrMsg?szErrMsg:\"\"));\n return oResult.toJSON();\n }\n\n \/\/TODO: set result\n \/\/oResult.set(arRes);\n\n return oResult.toJSON();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This is free and unencumbered software released into the public domain.\n\/\/ For more information, please refer to <http:\/\/unlicense.org\/>\n\n#include \"transmissionline\/cable.h\"\n\nCableComponent::CableComponent() {\n coefficient_expansion_linear_thermal = -999999;\n coefficients_polynomial_creep = std::vector<double>(5, 0);\n coefficients_polynomial_loadstrain = std::vector<double>(5, 0);\n load_limit_polynomial_creep = -999999;\n load_limit_polynomial_loadstrain = -999999;\n modulus_compression_elastic_area = -999999;\n modulus_tension_elastic_area = -999999;\n}\n\nCableComponent::~CableComponent() {}\n\nbool CableComponent::Validate(const bool& is_included_warnings,\n std::list<std::string>* messages_error) const {\n bool is_valid = true;\n\n \/\/ validate coefficient-expansion-thermal-linear\n if (coefficient_expansion_linear_thermal <= -0.005\n || 0.005 < coefficient_expansion_linear_thermal) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid coefficient of \"\n \"thermal expansion\");\n }\n }\n\n \/\/ validate coefficients-polynomial-creep\n if (coefficients_polynomial_creep.size() != 5) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid creep coefficients\");\n }\n\n \/\/ validate coefficients-polynomial-loadstrain\n if (coefficients_polynomial_loadstrain.size() != 5) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid load-strain \"\n \"coefficients\");\n }\n\n \/\/ validate load-limit-polynomial-creep\n if (load_limit_polynomial_creep < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid creep polynomial \"\n \"limit\");\n }\n }\n\n \/\/ validate load-limit-polynomial-loadstrain\n if (load_limit_polynomial_loadstrain < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid load-strain \"\n \"polynomial limit\");\n }\n }\n\n \/\/ validate modulus-compression-elastic-area\n if (modulus_compression_elastic_area < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT- Invalid compression elastic \"\n \"area modulus\");\n }\n }\n\n \/\/ validate modulus-tension-elastic-area\n if (modulus_tension_elastic_area < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"COMPONENT | CABLE - Invalid tension elastic \"\n \"area modulus\");\n }\n }\n\n \/\/return validation status\n return is_valid;\n}\n\nCable::Cable() {\n area_electrical = -999999;\n area_physical = -999999;\n diameter = -999999;\n name = \"\";\n strength_rated = -999999;\n temperature_properties_components = -999999;\n type_construction = \"\";\n weight_unit = -999999;\n}\n\nCable::~Cable() {}\n\nbool Cable::Validate(const bool& is_included_warnings,\n std::list<std::string>* messages_error) const {\n bool is_valid = true;\n\n \/\/ validate area-electrical\n if (area_electrical < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid electrical area\");\n }\n }\n\n \/\/ validate area-physical\n if (area_physical < 0) {\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid physical area\");\n }\n }\n\n \/\/ validate component-core\n component_core.Validate(is_included_warnings, messages_error);\n\n \/\/ validate component-shell\n component_shell.Validate(is_included_warnings, messages_error);\n\n \/\/ validate diameter\n if (diameter <= 0\n || (3 < diameter && is_included_warnings == true)) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid diameter\");\n }\n }\n\n \/\/ validate name\n \/\/ nothing to validate\n\n \/\/ validate strength-rated\n if (strength_rated < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid rated strength\");\n }\n }\n\n \/\/ validate temperature-component-properties\n if (temperature_properties_components < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid component properties \"\n \"temperature\");\n }\n }\n\n \/\/ validate type-construction\n \/\/ nothing to validate\n\n \/\/ validate type-polynomial-active\n if (type_polynomial_active != CablePolynomialType::kCreep\n || type_polynomial_active != CablePolynomialType::kLoadStrain) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid active polynomial type\");\n }\n }\n\n \/\/ validate weight-unit\n if (weight_unit <= 0\n || (10 < weight_unit && is_included_warnings == true)) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid unit weight\");\n }\n }\n\n \/\/ return validation status\n return is_valid;\n}\n<commit_msg>Fix for Cable validation function when validating active polynomial type.<commit_after>\/\/ This is free and unencumbered software released into the public domain.\n\/\/ For more information, please refer to <http:\/\/unlicense.org\/>\n\n#include \"transmissionline\/cable.h\"\n\nCableComponent::CableComponent() {\n coefficient_expansion_linear_thermal = -999999;\n coefficients_polynomial_creep = std::vector<double>(5, 0);\n coefficients_polynomial_loadstrain = std::vector<double>(5, 0);\n load_limit_polynomial_creep = -999999;\n load_limit_polynomial_loadstrain = -999999;\n modulus_compression_elastic_area = -999999;\n modulus_tension_elastic_area = -999999;\n}\n\nCableComponent::~CableComponent() {}\n\nbool CableComponent::Validate(const bool& is_included_warnings,\n std::list<std::string>* messages_error) const {\n bool is_valid = true;\n\n \/\/ validate coefficient-expansion-thermal-linear\n if (coefficient_expansion_linear_thermal <= -0.005\n || 0.005 < coefficient_expansion_linear_thermal) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid coefficient of \"\n \"thermal expansion\");\n }\n }\n\n \/\/ validate coefficients-polynomial-creep\n if (coefficients_polynomial_creep.size() != 5) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid creep coefficients\");\n }\n\n \/\/ validate coefficients-polynomial-loadstrain\n if (coefficients_polynomial_loadstrain.size() != 5) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid load-strain \"\n \"coefficients\");\n }\n\n \/\/ validate load-limit-polynomial-creep\n if (load_limit_polynomial_creep < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid creep polynomial \"\n \"limit\");\n }\n }\n\n \/\/ validate load-limit-polynomial-loadstrain\n if (load_limit_polynomial_loadstrain < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT - Invalid load-strain \"\n \"polynomial limit\");\n }\n }\n\n \/\/ validate modulus-compression-elastic-area\n if (modulus_compression_elastic_area < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE COMPONENT- Invalid compression elastic \"\n \"area modulus\");\n }\n }\n\n \/\/ validate modulus-tension-elastic-area\n if (modulus_tension_elastic_area < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"COMPONENT | CABLE - Invalid tension elastic \"\n \"area modulus\");\n }\n }\n\n \/\/return validation status\n return is_valid;\n}\n\nCable::Cable() {\n area_electrical = -999999;\n area_physical = -999999;\n diameter = -999999;\n name = \"\";\n strength_rated = -999999;\n temperature_properties_components = -999999;\n type_construction = \"\";\n weight_unit = -999999;\n}\n\nCable::~Cable() {}\n\nbool Cable::Validate(const bool& is_included_warnings,\n std::list<std::string>* messages_error) const {\n bool is_valid = true;\n\n \/\/ validate area-electrical\n if (area_electrical < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid electrical area\");\n }\n }\n\n \/\/ validate area-physical\n if (area_physical < 0) {\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid physical area\");\n }\n }\n\n \/\/ validate component-core\n component_core.Validate(is_included_warnings, messages_error);\n\n \/\/ validate component-shell\n component_shell.Validate(is_included_warnings, messages_error);\n\n \/\/ validate diameter\n if (diameter <= 0\n || (3 < diameter && is_included_warnings == true)) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid diameter\");\n }\n }\n\n \/\/ validate name\n \/\/ nothing to validate\n\n \/\/ validate strength-rated\n if (strength_rated < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid rated strength\");\n }\n }\n\n \/\/ validate temperature-component-properties\n if (temperature_properties_components < 0) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid component properties \"\n \"temperature\");\n }\n }\n\n \/\/ validate type-construction\n \/\/ nothing to validate\n\n \/\/ validate type-polynomial-active\n if (type_polynomial_active != CablePolynomialType::kCreep\n && type_polynomial_active != CablePolynomialType::kLoadStrain) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid active polynomial type\");\n }\n }\n\n \/\/ validate weight-unit\n if (weight_unit <= 0\n || (10 < weight_unit && is_included_warnings == true)) {\n\n is_valid = false;\n if (messages_error != nullptr) {\n messages_error->push_back(\"CABLE - Invalid unit weight\");\n }\n }\n\n \/\/ return validation status\n return is_valid;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RndSmoothCircleIC.h\"\n\ntemplate<>\nInputParameters validParams<RndSmoothCircleIC>()\n{\n InputParameters params = validParams<InitialCondition>();\n params.addRequiredParam<Real>(\"x1\", \"The x coordinate of the circle center\");\n params.addRequiredParam<Real>(\"y1\", \"The y coordinate of the circle center\");\n params.addParam<Real>(\"z1\", 0.0, \"The z coordinate of the circle center\");\n \n params.addRequiredParam<Real>(\"mx_invalue\", \"The max variable value inside the circle\");\n params.addRequiredParam<Real>(\"mx_outvalue\", \"The max variable value outside the circle\");\n params.addRequiredParam<Real>(\"mn_invalue\", \"The min variable value inside the circle\");\n params.addRequiredParam<Real>(\"mn_outvalue\", \"The min variable value outside the circle\");\n params.addRequiredParam<Real>(\"radius\", \"The radius of a circle\");\n \n params.addParam<unsigned int>(\"seed\", 12345, \"Seed value for the random number generator\");\n return params;\n}\n\nRndSmoothCircleIC::RndSmoothCircleIC(const std::string & name,\n InputParameters parameters)\n :InitialCondition(name, parameters),\n _x1(parameters.get<Real>(\"x1\")),\n _y1(parameters.get<Real>(\"y1\")),\n _z1(parameters.get<Real>(\"z1\")),\n _mx_invalue(parameters.get<Real>(\"mx_invalue\")),\n _mn_invalue(parameters.get<Real>(\"mn_invalue\")),\n _mx_outvalue(parameters.get<Real>(\"mx_outvalue\")),\n _mn_outvalue(parameters.get<Real>(\"mn_outvalue\")),\n _range_invalue(_mx_invalue - _mn_invalue),\n _range_outvalue(_mx_outvalue - _mn_outvalue),\n _radius(parameters.get<Real>(\"radius\")),\n _center(_x1,_y1,_z1)\n{\n mooseAssert(_range_invalue > 0.0, \"Inside Min > Max for RndSmoothCircleIC!\");\n mooseAssert(_range_outvalue > 0.0, \"Outside Min > Max for RndSmoothCircleIC!\");\n Moose::seed(getParam<unsigned int>(\"seed\"));\n}\n\nReal\nRndSmoothCircleIC::value(const Point & p)\n{\n Real value = 0.0;\n \n Real rad = 0.0;\n \n for(unsigned int i=0; i<LIBMESH_DIM; i++) \n rad += (p(i)-_center(i)) * (p(i)-_center(i));\n\n rad = sqrt(rad);\n \n \/\/Random number between 0 and 1\n Real rand_num = Moose::rand();\n \n if (rad <= _radius)\n value = _mn_invalue + rand_num*(_range_invalue);\n else if (rad < 1.5*_radius)\n {\n Real av_invalue = (_mn_invalue + _mx_invalue)\/2.0;\n Real av_outvalue = (_mn_outvalue + _mx_outvalue)\/2.0;\n value = av_outvalue + (av_invalue-av_outvalue)*(1+cos((rad-_radius)\/_radius*2.0*3.14159))\/2.0;\n }\n else\n value = _mx_outvalue + rand_num*(_range_outvalue);\n\n return value;\n \n}\n\n \n\n\n \n<commit_msg>r3329 dd8cd9ef-2931-0410-98ca-75ad22d19dd1<commit_after>#include \"RndSmoothCircleIC.h\"\n\ntemplate<>\nInputParameters validParams<RndSmoothCircleIC>()\n{\n InputParameters params = validParams<InitialCondition>();\n params.addRequiredParam<Real>(\"x1\", \"The x coordinate of the circle center\");\n params.addRequiredParam<Real>(\"y1\", \"The y coordinate of the circle center\");\n params.addParam<Real>(\"z1\", 0.0, \"The z coordinate of the circle center\");\n \n params.addRequiredParam<Real>(\"mx_invalue\", \"The max variable value inside the circle\");\n params.addRequiredParam<Real>(\"mx_outvalue\", \"The max variable value outside the circle\");\n params.addRequiredParam<Real>(\"mn_invalue\", \"The min variable value inside the circle\");\n params.addRequiredParam<Real>(\"mn_outvalue\", \"The min variable value outside the circle\");\n params.addRequiredParam<Real>(\"radius\", \"The radius of a circle\");\n \n params.addParam<unsigned int>(\"seed\", 12345, \"Seed value for the random number generator\");\n return params;\n}\n\nRndSmoothCircleIC::RndSmoothCircleIC(const std::string & name,\n InputParameters parameters)\n :InitialCondition(name, parameters),\n _x1(parameters.get<Real>(\"x1\")),\n _y1(parameters.get<Real>(\"y1\")),\n _z1(parameters.get<Real>(\"z1\")),\n _mx_invalue(parameters.get<Real>(\"mx_invalue\")),\n _mn_invalue(parameters.get<Real>(\"mn_invalue\")),\n _mx_outvalue(parameters.get<Real>(\"mx_outvalue\")),\n _mn_outvalue(parameters.get<Real>(\"mn_outvalue\")),\n _range_invalue(_mx_invalue - _mn_invalue),\n _range_outvalue(_mx_outvalue - _mn_outvalue),\n _radius(parameters.get<Real>(\"radius\")),\n _center(_x1,_y1,_z1)\n{\n mooseAssert(_range_invalue >= 0.0, \"Inside Min > Max for RndSmoothCircleIC!\");\n mooseAssert(_range_outvalue >= 0.0, \"Outside Min > Max for RndSmoothCircleIC!\");\n Moose::seed(getParam<unsigned int>(\"seed\"));\n}\n\nReal\nRndSmoothCircleIC::value(const Point & p)\n{\n Real value = 0.0;\n \n Real rad = 0.0;\n \n for(unsigned int i=0; i<LIBMESH_DIM; i++) \n rad += (p(i)-_center(i)) * (p(i)-_center(i));\n\n rad = sqrt(rad);\n \n \/\/Random number between 0 and 1\n Real rand_num = Moose::rand();\n \n if (rad <= _radius)\n value = _mn_invalue + rand_num*(_range_invalue);\n else if (rad < 1.5*_radius)\n {\n Real av_invalue = (_mn_invalue + _mx_invalue)\/2.0;\n Real av_outvalue = (_mn_outvalue + _mx_outvalue)\/2.0;\n value = av_outvalue + (av_invalue-av_outvalue)*(1+cos((rad-_radius)\/_radius*2.0*3.14159))\/2.0;\n }\n else\n value = _mx_outvalue + rand_num*(_range_outvalue);\n\n return value;\n \n}\n\n \n\n\n \n<|endoftext|>"} {"text":"<commit_before>#include <CQTitleBar.h>\n\n#include <QPainter>\n#include <QStylePainter>\n#include <QStyleOptionToolButton>\n\n\/\/ create title bar\nCQTitleBar::\nCQTitleBar(Qt::Orientation orient, QWidget *parent) :\n QWidget(parent), title_(), icon_(), orient_(orient), border_(2),\n bgColor_(160,160,160), barColor_(120,120,120), buttons_()\n{\n setObjectName(\"title\");\n}\n\n\/\/ create title bar (swapped args)\nCQTitleBar::\nCQTitleBar(QWidget *parent, Qt::Orientation orient) :\n QWidget(parent), title_(), icon_(), orient_(orient), border_(2),\n bgColor_(160,160,160), barColor_(120,120,120), buttons_()\n{\n setObjectName(\"title\");\n}\n\n\/\/ set title\nvoid\nCQTitleBar::\nsetTitle(const QString &title)\n{\n title_ = title;\n\n if (isVisible())\n update();\n}\n\n\/\/ set icon\nvoid\nCQTitleBar::\nsetIcon(const QIcon &icon)\n{\n icon_ = icon;\n\n if (isVisible())\n update();\n}\n\n\/\/ set orientation\nvoid\nCQTitleBar::\nsetOrientation(Qt::Orientation orient)\n{\n orient_ = orient;\n\n if (isVisible())\n updateLayout();\n}\n\n\/\/ set border\nvoid\nCQTitleBar::\nsetBorder(int border)\n{\n border_ = border;\n\n if (isVisible())\n updateLayout();\n}\n\n\/\/ set background color\nvoid\nCQTitleBar::\nsetBackgroundColor(const QColor &color)\n{\n bgColor_ = color;\n\n if (isVisible())\n update();\n}\n\n\/\/ set title bar line color\nvoid\nCQTitleBar::\nsetBarColor(const QColor &color)\n{\n barColor_ = color;\n\n if (isVisible())\n update();\n}\n\n\/\/ add icon button\nCQTitleBarButton *\nCQTitleBar::\naddButton(const QIcon &icon)\n{\n CQTitleBarButton *button = new CQTitleBarButton;\n\n button->setIcon(icon);\n\n addButton(button);\n\n return button;\n}\n\n\/\/ add button widget\nvoid\nCQTitleBar::\naddButton(CQTitleBarButton *button)\n{\n button->setParent(this);\n\n button->setTitleBar(this);\n\n buttons_.push_back(button);\n\n updateLayout();\n}\n\n\/\/ handle show event\nvoid\nCQTitleBar::\nshowEvent(QShowEvent *)\n{\n updateLayout();\n}\n\n\/\/ handle paint event\nvoid\nCQTitleBar::\npaintEvent(QPaintEvent *)\n{\n int b = border();\n int b1 = std::max(b, 1);\n\n QPainter p(this);\n\n QColor bgColor = this->backgroundColor();\n\n p.fillRect(rect(), bgColor);\n\n QColor barColor = this->barColor();\n\n drawTitleBarLines(&p, rect(), barColor);\n\n QIcon icon = this->icon();\n QString title = this->title();\n\n int x = 0;\n\n if (orientation() == Qt::Horizontal) {\n if (! icon.isNull()) {\n int ps = height() - 2*b1;\n\n p.fillRect(QRect(x, 0, ps + 2*b1, height()), bgColor);\n\n p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps)));\n\n x += ps + 2*b1;\n }\n\n if (! title.isEmpty()) {\n QFontMetrics fm(font());\n\n int tw = fm.width(title);\n int th = fm.boundingRect(title).height();\n\n p.fillRect(QRect(x, 0, tw + 8, height()), bgColor);\n\n p.setPen(palette().color(QPalette::Text));\n\n p.drawText(x + 2, (height() - th)\/2 + fm.ascent(), title);\n }\n }\n else {\n int y = height() - 1;\n\n if (! icon.isNull()) {\n int ps = width() - 2*b1;\n\n p.fillRect(QRect(0, y - ps - 2*b1, width(), ps + 2*b1), bgColor);\n\n p.save();\n\n p.translate(0, height());\n p.rotate(-90);\n\n \/\/p.drawPixmap(2, y - ps - 2, icon.pixmap(QSize(ps,ps)));\n p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps)));\n\n p.restore();\n\n y -= ps + 2*b1;\n x += ps + 2*b1;\n }\n\n if (! title.isEmpty()) {\n QFontMetrics fm(font());\n\n int tw = fm.width(title);\n int th = fm.boundingRect(title).height();\n\n p.save();\n\n p.fillRect(QRect(0, y - tw - 8, width(), tw + 8), bgColor);\n\n p.setPen(palette().color(QPalette::Text));\n\n p.translate(0, height());\n p.rotate(-90);\n\n p.drawText(x + 2, (width() - th)\/2 + fm.ascent(), title);\n\n p.restore();\n }\n }\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n if (orientation() == Qt::Horizontal)\n p.fillRect(QRect(width() - nb*bw, 0, nb*bw, height()), bgColor);\n else\n p.fillRect(QRect(0, 0, width(), nb*bw), bgColor);\n}\n\n\/\/ handle resize event\nvoid\nCQTitleBar::\nresizeEvent(QResizeEvent *)\n{\n updateLayout();\n}\n\n\/\/ update layout\nvoid\nCQTitleBar::\nupdateLayout()\n{\n if (! isVisible()) return;\n\n int b = border();\n int b1 = std::max(b, 1);\n\n QFontMetrics fm(font());\n\n if (orientation() == Qt::Horizontal) {\n setFixedHeight(fm.height() + 2*b);\n setMinimumWidth(0); setMaximumWidth(QWIDGETSIZE_MAX);\n }\n else {\n setFixedWidth(fm.height() + 2*b);\n setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX);\n }\n\n \/\/------\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = buttons_.size();\n\n int pos = (orientation() == Qt::Horizontal ? width() - 2 : 2);\n\n for (int i = nb - 1; i >= 0; --i) {\n CQTitleBarButton *button = buttons_[i];\n\n if (! button->isVisible())\n continue;\n\n if (orientation() == Qt::Horizontal) {\n int dh = height() - button->height();\n\n button->move(pos - bw, dh\/2);\n\n pos -= bw;\n }\n else {\n int dw = width() - button->width();\n\n button->move(dw\/2, pos);\n\n pos += bw;\n }\n }\n}\n\n\/\/ draw title lines\nvoid\nCQTitleBar::\ndrawTitleBarLines(QPainter *p, const QRect &r, const QColor &c)\n{\n p->setPen(c);\n\n if (orientation() == Qt::Horizontal) {\n int left = r.left () + 2;\n int right = r.right() - 2;\n\n int y = r.center().y() - 3;\n\n for (int i = 0; i < 4; ++i) {\n int y1 = y + 2*i;\n\n p->drawLine(left, y1, right, y1);\n }\n }\n else {\n int top = r.top () + 2;\n int bottom = r.bottom() - 2;\n\n int x = r.center().x() - 3;\n\n for (int i = 0; i < 4; ++i) {\n int x1 = x + 2*i;\n\n p->drawLine(x1, top, x1, bottom);\n }\n }\n}\n\n\/\/ check if point inside title (not in button area)\nbool\nCQTitleBar::\ninsideTitle(const QPoint &pos) const\n{\n int b = border();\n int b1 = std::max(b, 1);\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n if (orientation() == Qt::Horizontal)\n return (pos.x() < width() - nb*bw - 2*b1);\n else\n return (pos.y() > nb*bw + 2*b1);\n}\n\n\/\/ return size hint\nQSize\nCQTitleBar::\nsizeHint() const\n{\n int b = border();\n\n QFontMetrics fm(font());\n\n int h = fm.height() + 2*b;\n int w = 0;\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n w += nb*h;\n\n if (! icon().isNull()) w += h;\n\n if (! title().isEmpty())\n w += fm.width(title());\n\n w = std::max(w, h);\n\n if (orientation() != Qt::Horizontal)\n std::swap(w, h);\n\n return QSize(w, h);\n}\n\n\/\/ return minimum size hint\nQSize\nCQTitleBar::\nminimumSizeHint() const\n{\n int b = border();\n\n QFontMetrics fm(font());\n\n int w, h;\n\n if (orientation() == Qt::Horizontal) {\n h = fm.height() + 2*b;\n w = h;\n }\n else {\n w = fm.height() + 2*b;\n h = w;\n }\n\n return QSize(w, h);\n}\n\n\/\/------\n\n\/\/ create title button\nCQTitleBarButton::\nCQTitleBarButton(QWidget *parent) :\n QToolButton(parent), bar_(0)\n{\n setObjectName(\"button\");\n\n setIconSize(QSize(10,10));\n\n setAutoRaise(true);\n\n setFocusPolicy(Qt::NoFocus);\n\n setCursor(Qt::ArrowCursor);\n}\n\n\/\/ handle draw\nvoid\nCQTitleBarButton::\npaintEvent(QPaintEvent *)\n{\n QStylePainter p(this);\n\n QStyleOptionToolButton opt;\n\n#if 0\n opt.initFrom(this);\n\n opt.iconSize = iconSize(); \/\/default value\n\n opt.icon = icon();\n\n if (isDown())\n opt.state |= QStyle::State_Sunken;\n else\n opt.state |= QStyle::State_Raised;\n\n opt.state |= QStyle::State_AutoRaise;\n\n opt.subControls = QStyle::SC_ToolButton;\n\n if (isDown())\n opt.activeSubControls = QStyle::SC_ToolButton;\n else\n opt.activeSubControls = QStyle::SC_None;\n\n opt.features = QStyleOptionToolButton::None;\n\n opt.toolButtonStyle = Qt::ToolButtonIconOnly;\n\n opt.pos = pos();\n opt.font = font();\n#else\n initStyleOption(&opt);\n#endif\n\n if (bar_ && bar_->orientation() == Qt::Vertical) {\n p.translate(0, height());\n p.rotate(-90);\n }\n\n p.drawComplexControl(QStyle::CC_ToolButton, opt);\n}\n<commit_msg>new files<commit_after>#include <CQTitleBar.h>\n\n#include <QPainter>\n#include <QStylePainter>\n#include <QStyleOptionToolButton>\n\n\/\/ create title bar\nCQTitleBar::\nCQTitleBar(Qt::Orientation orient, QWidget *parent) :\n QWidget(parent), title_(), icon_(), orient_(orient), border_(2),\n bgColor_(160,160,160), barColor_(120,120,120), buttons_()\n{\n setObjectName(\"title\");\n}\n\n\/\/ create title bar (swapped args)\nCQTitleBar::\nCQTitleBar(QWidget *parent, Qt::Orientation orient) :\n QWidget(parent), title_(), icon_(), orient_(orient), border_(2),\n bgColor_(160,160,160), barColor_(120,120,120), buttons_()\n{\n setObjectName(\"title\");\n}\n\n\/\/ set title\nvoid\nCQTitleBar::\nsetTitle(const QString &title)\n{\n title_ = title;\n\n if (isVisible())\n update();\n}\n\n\/\/ set icon\nvoid\nCQTitleBar::\nsetIcon(const QIcon &icon)\n{\n icon_ = icon;\n\n if (isVisible())\n update();\n}\n\n\/\/ set orientation\nvoid\nCQTitleBar::\nsetOrientation(Qt::Orientation orient)\n{\n orient_ = orient;\n\n if (isVisible())\n updateLayout();\n}\n\n\/\/ set border\nvoid\nCQTitleBar::\nsetBorder(int border)\n{\n border_ = border;\n\n if (isVisible())\n updateLayout();\n}\n\n\/\/ set background color\nvoid\nCQTitleBar::\nsetBackgroundColor(const QColor &color)\n{\n bgColor_ = color;\n\n if (isVisible())\n update();\n}\n\n\/\/ set title bar line color\nvoid\nCQTitleBar::\nsetBarColor(const QColor &color)\n{\n barColor_ = color;\n\n if (isVisible())\n update();\n}\n\n\/\/ add icon button\nCQTitleBarButton *\nCQTitleBar::\naddButton(const QIcon &icon)\n{\n CQTitleBarButton *button = new CQTitleBarButton;\n\n button->setIcon(icon);\n\n addButton(button);\n\n return button;\n}\n\n\/\/ add button widget\nvoid\nCQTitleBar::\naddButton(CQTitleBarButton *button)\n{\n button->setParent(this);\n\n button->setTitleBar(this);\n\n buttons_.push_back(button);\n\n updateLayout();\n}\n\n\/\/ handle show event\nvoid\nCQTitleBar::\nshowEvent(QShowEvent *)\n{\n updateLayout();\n}\n\n\/\/ handle paint event\nvoid\nCQTitleBar::\npaintEvent(QPaintEvent *)\n{\n int b = border();\n int b1 = std::max(b, 1);\n\n QPainter p(this);\n\n QColor bgColor = this->backgroundColor();\n\n p.fillRect(rect(), bgColor);\n\n QColor barColor = this->barColor();\n\n drawTitleBarLines(&p, rect(), barColor);\n\n QIcon icon = this->icon();\n QString title = this->title();\n\n int x = 0;\n\n if (orientation() == Qt::Horizontal) {\n if (! icon.isNull()) {\n int ps = height() - 2*b1;\n\n p.fillRect(QRect(x, 0, ps + 2*b1, height()), bgColor);\n\n p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps)));\n\n x += ps + 2*b1;\n }\n\n if (! title.isEmpty()) {\n QFontMetrics fm(font());\n\n int tw = fm.width(title);\n int th = fm.boundingRect(title).height();\n\n p.fillRect(QRect(x, 0, tw + 8, height()), bgColor);\n\n p.setPen(palette().color(QPalette::Text));\n\n p.drawText(x + 2, (height() - th)\/2 + fm.ascent(), title);\n }\n }\n else {\n int y = height() - 1;\n\n if (! icon.isNull()) {\n int ps = width() - 2*b1;\n\n p.fillRect(QRect(0, y - ps - 2*b1, width(), ps + 2*b1), bgColor);\n\n p.save();\n\n p.translate(0, height());\n p.rotate(-90);\n\n \/\/p.drawPixmap(2, y - ps - 2, icon.pixmap(QSize(ps,ps)));\n p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps)));\n\n p.restore();\n\n y -= ps + 2*b1;\n x += ps + 2*b1;\n }\n\n if (! title.isEmpty()) {\n QFontMetrics fm(font());\n\n int tw = fm.width(title);\n int th = fm.boundingRect(title).height();\n\n p.save();\n\n p.fillRect(QRect(0, y - tw - 8, width(), tw + 8), bgColor);\n\n p.setPen(palette().color(QPalette::Text));\n\n p.translate(0, height());\n p.rotate(-90);\n\n p.drawText(x + 2, (width() - th)\/2 + fm.ascent(), title);\n\n p.restore();\n }\n }\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n if (orientation() == Qt::Horizontal)\n p.fillRect(QRect(width() - nb*bw, 0, nb*bw, height()), bgColor);\n else\n p.fillRect(QRect(0, 0, width(), nb*bw), bgColor);\n}\n\n\/\/ handle resize event\nvoid\nCQTitleBar::\nresizeEvent(QResizeEvent *)\n{\n updateLayout();\n}\n\n\/\/ update layout\nvoid\nCQTitleBar::\nupdateLayout()\n{\n if (! isVisible()) return;\n\n int b = border();\n int b1 = std::max(b, 1);\n\n QFontMetrics fm(font());\n\n if (orientation() == Qt::Horizontal) {\n setFixedHeight(fm.height() + 2*b);\n setMinimumWidth(0); setMaximumWidth(QWIDGETSIZE_MAX);\n }\n else {\n setFixedWidth(fm.height() + 2*b);\n setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX);\n }\n\n \/\/------\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = int(buttons_.size());\n\n int pos = (orientation() == Qt::Horizontal ? width() - 2 : 2);\n\n for (int i = nb - 1; i >= 0; --i) {\n auto *button = buttons_[uint(i)];\n\n if (! button->isVisible())\n continue;\n\n if (orientation() == Qt::Horizontal) {\n int dh = height() - button->height();\n\n button->move(pos - bw, dh\/2);\n\n pos -= bw;\n }\n else {\n int dw = width() - button->width();\n\n button->move(dw\/2, pos);\n\n pos += bw;\n }\n }\n}\n\n\/\/ draw title lines\nvoid\nCQTitleBar::\ndrawTitleBarLines(QPainter *p, const QRect &r, const QColor &c)\n{\n p->setPen(c);\n\n if (orientation() == Qt::Horizontal) {\n int left = r.left () + 2;\n int right = r.right() - 2;\n\n int y = r.center().y() - 3;\n\n for (int i = 0; i < 4; ++i) {\n int y1 = y + 2*i;\n\n p->drawLine(left, y1, right, y1);\n }\n }\n else {\n int top = r.top () + 2;\n int bottom = r.bottom() - 2;\n\n int x = r.center().x() - 3;\n\n for (int i = 0; i < 4; ++i) {\n int x1 = x + 2*i;\n\n p->drawLine(x1, top, x1, bottom);\n }\n }\n}\n\n\/\/ check if point inside title (not in button area)\nbool\nCQTitleBar::\ninsideTitle(const QPoint &pos) const\n{\n int b = border();\n int b1 = std::max(b, 1);\n\n int bw = (orientation() == Qt::Horizontal ? height() - 2*b1 : width() - 2*b1);\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n if (orientation() == Qt::Horizontal)\n return (pos.x() < width() - nb*bw - 2*b1);\n else\n return (pos.y() > nb*bw + 2*b1);\n}\n\n\/\/ return size hint\nQSize\nCQTitleBar::\nsizeHint() const\n{\n int b = border();\n\n QFontMetrics fm(font());\n\n int h = fm.height() + 2*b;\n int w = 0;\n\n int nb = 0;\n\n for (uint i = 0; i < buttons_.size(); ++i)\n if (buttons_[i]->isVisible())\n ++nb;\n\n w += nb*h;\n\n if (! icon().isNull()) w += h;\n\n if (! title().isEmpty())\n w += fm.width(title());\n\n w = std::max(w, h);\n\n if (orientation() != Qt::Horizontal)\n std::swap(w, h);\n\n return QSize(w, h);\n}\n\n\/\/ return minimum size hint\nQSize\nCQTitleBar::\nminimumSizeHint() const\n{\n int b = border();\n\n QFontMetrics fm(font());\n\n int w, h;\n\n if (orientation() == Qt::Horizontal) {\n h = fm.height() + 2*b;\n w = h;\n }\n else {\n w = fm.height() + 2*b;\n h = w;\n }\n\n return QSize(w, h);\n}\n\n\/\/------\n\n\/\/ create title button\nCQTitleBarButton::\nCQTitleBarButton(QWidget *parent) :\n QToolButton(parent), bar_(0)\n{\n setObjectName(\"button\");\n\n setIconSize(QSize(10,10));\n\n setAutoRaise(true);\n\n setFocusPolicy(Qt::NoFocus);\n\n setCursor(Qt::ArrowCursor);\n}\n\n\/\/ handle draw\nvoid\nCQTitleBarButton::\npaintEvent(QPaintEvent *)\n{\n QStylePainter p(this);\n\n QStyleOptionToolButton opt;\n\n#if 0\n opt.initFrom(this);\n\n opt.iconSize = iconSize(); \/\/default value\n\n opt.icon = icon();\n\n if (isDown())\n opt.state |= QStyle::State_Sunken;\n else\n opt.state |= QStyle::State_Raised;\n\n opt.state |= QStyle::State_AutoRaise;\n\n opt.subControls = QStyle::SC_ToolButton;\n\n if (isDown())\n opt.activeSubControls = QStyle::SC_ToolButton;\n else\n opt.activeSubControls = QStyle::SC_None;\n\n opt.features = QStyleOptionToolButton::None;\n\n opt.toolButtonStyle = Qt::ToolButtonIconOnly;\n\n opt.pos = pos();\n opt.font = font();\n#else\n initStyleOption(&opt);\n#endif\n\n if (bar_ && bar_->orientation() == Qt::Vertical) {\n p.translate(0, height());\n p.rotate(-90);\n }\n\n p.drawComplexControl(QStyle::CC_ToolButton, opt);\n}\n<|endoftext|>"} {"text":"<commit_before>#include\"..\/header\/thread\/CSemaphore.hpp\"\n#include<atomic>\n#include<condition_variable>\n#include<mutex>\nusing namespace std;\n\nnamespace nThread\n{\n\tclass CSemaphore::Impl\n\t{\n\t\tatomic<CSemaphore::size_type> count_;\n\t\tcondition_variable cv_;\n\t\tmutex mut_;\n\tpublic:\n\t\tImpl(CSemaphore::size_type);\n\t\tinline CSemaphore::size_type count() const noexcept\n\t\t{\n\t\t\treturn count_;\n\t\t}\n\t\tvoid signal();\n\t\tvoid wait();\n\t};\n\n\tCSemaphore::Impl::Impl(const CSemaphore::size_type count)\n\t\t:count_{count}{}\n\n\tvoid CSemaphore::Impl::signal()\n\t{\n\t\tif(!count_++)\n\t\t{\n\t\t\tlock_guard<mutex> lock{mut_};\n\t\t\tcv_.notify_all();\n\t\t}\n\t}\n\n\tvoid CSemaphore::Impl::wait()\n\t{\n\t\tunique_lock<mutex> lock{mut_};\n\t\tcv_.wait(lock,[this]() noexcept{return count();});\n\t\t--count_;\n\t}\n\n\tCSemaphore::CSemaphore()\n\t\t:CSemaphore{0}{}\n\n\tCSemaphore::CSemaphore(const CSemaphore::size_type count)\n\t\t:impl_{count}{}\n\n\tCSemaphore::size_type CSemaphore::count() const noexcept\n\t{\n\t\treturn impl_.get().count();\n\t}\n\n\tvoid CSemaphore::signal()\n\t{\n\t\timpl_.get().signal();\n\t}\n\n\tvoid CSemaphore::wait()\n\t{\n\t\timpl_.get().wait();\n\t}\n\n\tCSemaphore::~CSemaphore(){}\n\n\tclass CReaders_Writers_Problem::Impl\n\t{\n\t\tatomic<CSemaphore::size_type> count_;\n\t\tCSemaphore use_,wait_,writing_;\n\tpublic:\n\t\tImpl();\n\t\tvoid readBegin();\n\t\tvoid readEnd();\n\t\tvoid writeBegin();\n\t\tinline void writeEnd()\n\t\t{\n\t\t\tuse_.signal();\n\t\t}\n\t};\n\n\tCReaders_Writers_Problem::Impl::Impl()\n\t\t:count_{0},use_{1},wait_{1},writing_{1}{}\n\n\tvoid CReaders_Writers_Problem::Impl::readBegin()\n\t{\n\t\twait_.wait();\n\t\twriting_.wait();\t\/\/must\n\t\tif(++count_==1)\n\t\t\tuse_.wait();\n\t\twait_.signal();\n\t\twriting_.signal();\t\/\/can this line put prior to wait_.signal()?\n\t}\n\n\tvoid CReaders_Writers_Problem::Impl::readEnd()\n\t{\n\t\t\/\/writing_.wait();\t\/\/atomic is enough, I think\n\t\tif(!--count_)\n\t\t\tuse_.signal();\n\t\t\/\/writing_.signal();\t\/\/atomic is enough, I think\n\t}\n\n\tvoid CReaders_Writers_Problem::Impl::writeBegin()\n\t{\n\t\twait_.wait();\n\t\tuse_.wait();\n\t\twait_.signal();\n\t}\n\n\tCReaders_Writers_Problem::CReaders_Writers_Problem(){}\n\n\tvoid CReaders_Writers_Problem::readBegin()\n\t{\n\t\timpl_.get().readBegin();\n\t}\n\n\tvoid CReaders_Writers_Problem::readEnd()\n\t{\n\t\timpl_.get().readEnd();\n\t}\n\n\tvoid CReaders_Writers_Problem::writeBegin()\n\t{\n\t\timpl_.get().writeBegin();\n\t}\n\n\tvoid CReaders_Writers_Problem::writeEnd()\n\t{\n\t\timpl_.get().writeEnd();\n\t}\n\n\tCReaders_Writers_Problem::~CReaders_Writers_Problem(){}\n}<commit_msg>use =default<commit_after>#include\"..\/header\/thread\/CSemaphore.hpp\"\n#include<atomic>\n#include<condition_variable>\n#include<mutex>\nusing namespace std;\n\nnamespace nThread\n{\n\tclass CSemaphore::Impl\n\t{\n\t\tatomic<CSemaphore::size_type> count_;\n\t\tcondition_variable cv_;\n\t\tmutex mut_;\n\tpublic:\n\t\tImpl(CSemaphore::size_type);\n\t\tinline CSemaphore::size_type count() const noexcept\n\t\t{\n\t\t\treturn count_;\n\t\t}\n\t\tvoid signal();\n\t\tvoid wait();\n\t};\n\n\tCSemaphore::Impl::Impl(const CSemaphore::size_type count)\n\t\t:count_{count}{}\n\n\tvoid CSemaphore::Impl::signal()\n\t{\n\t\tif(!count_++)\n\t\t{\n\t\t\tlock_guard<mutex> lock{mut_};\n\t\t\tcv_.notify_all();\n\t\t}\n\t}\n\n\tvoid CSemaphore::Impl::wait()\n\t{\n\t\tunique_lock<mutex> lock{mut_};\n\t\tcv_.wait(lock,[this]() noexcept{return count();});\n\t\t--count_;\n\t}\n\n\tCSemaphore::CSemaphore()\n\t\t:CSemaphore{0}{}\n\n\tCSemaphore::CSemaphore(const CSemaphore::size_type count)\n\t\t:impl_{count}{}\n\n\tCSemaphore::size_type CSemaphore::count() const noexcept\n\t{\n\t\treturn impl_.get().count();\n\t}\n\n\tvoid CSemaphore::signal()\n\t{\n\t\timpl_.get().signal();\n\t}\n\n\tvoid CSemaphore::wait()\n\t{\n\t\timpl_.get().wait();\n\t}\n\n\tCSemaphore::~CSemaphore()=default;\n\n\tclass CReaders_Writers_Problem::Impl\n\t{\n\t\tatomic<CSemaphore::size_type> count_;\n\t\tCSemaphore use_,wait_,writing_;\n\tpublic:\n\t\tImpl();\n\t\tvoid readBegin();\n\t\tvoid readEnd();\n\t\tvoid writeBegin();\n\t\tinline void writeEnd()\n\t\t{\n\t\t\tuse_.signal();\n\t\t}\n\t};\n\n\tCReaders_Writers_Problem::Impl::Impl()\n\t\t:count_{0},use_{1},wait_{1},writing_{1}{}\n\n\tvoid CReaders_Writers_Problem::Impl::readBegin()\n\t{\n\t\twait_.wait();\n\t\twriting_.wait();\t\/\/must\n\t\tif(++count_==1)\n\t\t\tuse_.wait();\n\t\twait_.signal();\n\t\twriting_.signal();\t\/\/can this line put prior to wait_.signal()?\n\t}\n\n\tvoid CReaders_Writers_Problem::Impl::readEnd()\n\t{\n\t\t\/\/writing_.wait();\t\/\/atomic is enough, I think\n\t\tif(!--count_)\n\t\t\tuse_.signal();\n\t\t\/\/writing_.signal();\t\/\/atomic is enough, I think\n\t}\n\n\tvoid CReaders_Writers_Problem::Impl::writeBegin()\n\t{\n\t\twait_.wait();\n\t\tuse_.wait();\n\t\twait_.signal();\n\t}\n\n\tCReaders_Writers_Problem::CReaders_Writers_Problem()=default;\n\n\tvoid CReaders_Writers_Problem::readBegin()\n\t{\n\t\timpl_.get().readBegin();\n\t}\n\n\tvoid CReaders_Writers_Problem::readEnd()\n\t{\n\t\timpl_.get().readEnd();\n\t}\n\n\tvoid CReaders_Writers_Problem::writeBegin()\n\t{\n\t\timpl_.get().writeBegin();\n\t}\n\n\tvoid CReaders_Writers_Problem::writeEnd()\n\t{\n\t\timpl_.get().writeEnd();\n\t}\n\n\tCReaders_Writers_Problem::~CReaders_Writers_Problem()=default;\n}<|endoftext|>"} {"text":"<commit_before>#include \"types.h\"\n#include \"multiboot.hh\"\n#include \"kernel.hh\"\n#include \"spinlock.h\"\n#include \"kalloc.hh\"\n#include \"cpu.hh\"\n#include \"amd64.h\"\n#include \"hwvm.hh\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"apic.hh\"\n#include \"codex.hh\"\n#include \"mfs.hh\"\n\nvoid initpic(void);\nvoid initextpic(void);\nvoid inituart(void);\nvoid inituartcons(void);\nvoid initcga(void);\nvoid initconsole(void);\nvoid initpg(void);\nvoid cleanuppg(void);\nvoid inittls(struct cpu *);\nvoid initnmi(void);\nvoid initcodex(void);\nvoid inittrap(void);\nvoid initseg(struct cpu *);\nvoid initphysmem(paddr mbaddr);\nvoid initpercpu(void);\nvoid initkalloc(void);\nvoid initz(void);\nvoid initrcu(void);\nvoid initproc(void);\nvoid initinode(void);\nvoid initdisk(void);\nvoid inituser(void);\nvoid initsamp(void);\nvoid inite1000(void);\nvoid initpci(void);\nvoid initnet(void);\nvoid initsched(void);\nvoid initlockstat(void);\nvoid initwq(void);\nvoid initidle(void);\nvoid initcpprt(void);\nvoid initfutex(void);\nvoid initcmdline(void);\nvoid initdistref(void);\nvoid initrefcache(void);\nvoid initacpitables(void);\nvoid initnuma(void);\nvoid initcpus(void);\nvoid initlapic(void);\nvoid initiommu(void);\nvoid initacpi(void);\nvoid initwd(void);\nvoid initdev(void);\nvoid idleloop(void);\n\n#define IO_RTC 0x70\n\nstatic std::atomic<int> bstate;\nstatic cpuid_t bcpuid;\n\nvoid\nmpboot(void)\n{\n initseg(&cpus[bcpuid]);\n inittls(&cpus[bcpuid]); \/\/ Requires initseg\n initpg();\n\n \/\/ Call per-CPU static initializers. This is the per-CPU equivalent\n \/\/ of the init_array calls in cmain.\n extern void (*__percpuinit_array_start[])(size_t);\n extern void (*__percpuinit_array_end[])(size_t);\n for (size_t i = 0; i < __percpuinit_array_end - __percpuinit_array_start; i++)\n (*__percpuinit_array_start[i])(bcpuid);\n\n initlapic();\n initsamp();\n initidle();\n initnmi();\n initwd(); \/\/ Requires initnmi\n bstate.store(1);\n idleloop();\n}\n\nstatic void\nwarmreset(u32 addr)\n{\n volatile u16 *wrv;\n\n \/\/ \"The BSP must initialize CMOS shutdown code to 0AH\n \/\/ and the warm reset vector (DWORD based at 40:67) to point at\n \/\/ the AP startup code prior to the [universal startup algorithm].\"\n outb(IO_RTC, 0xF); \/\/ offset 0xF is shutdown code\n outb(IO_RTC+1, 0x0A);\n wrv = (u16*)p2v(0x40<<4 | 0x67); \/\/ Warm reset vector\n wrv[0] = 0;\n wrv[1] = addr >> 4;\n}\n\nstatic void\nrstrreset(void)\n{\n volatile u16 *wrv;\n\n \/\/ Paranoid: set warm reset code and vector back to defaults\n outb(IO_RTC, 0xF);\n outb(IO_RTC+1, 0);\n wrv = (u16*)p2v(0x40<<4 | 0x67);\n wrv[0] = 0;\n wrv[1] = 0;\n}\n\nstatic void\nbootothers(void)\n{\n extern u8 _bootother_start[];\n extern u64 _bootother_size;\n extern void (*apstart)(void);\n char *stack;\n u8 *code;\n\n \/\/ Write bootstrap code to unused memory at 0x7000.\n \/\/ The linker has placed the image of bootother.S in\n \/\/ _binary_bootother_start.\n code = (u8*) p2v(0x7000);\n memmove(code, _bootother_start, _bootother_size);\n\n for (int i = 0; i < ncpu; ++i) {\n if(i == myid()) \/\/ We've started already.\n continue;\n struct cpu *c = &cpus[i];\n\n warmreset(v2p(code));\n\n \/\/ Tell bootother.S what stack to use and the address of apstart;\n \/\/ it expects to find these two addresses stored just before\n \/\/ its first instruction.\n stack = (char*) ksalloc(slab_stack);\n *(u32*)(code-4) = (u32)v2p(&apstart);\n *(u64*)(code-12) = (u64)stack + KSTACKSIZE;\n \/\/ bootother.S sets this to 0x0a55face early on\n *(u32*)(code-64) = 0;\n\n bstate.store(0);\n bcpuid = c->id;\n lapic->start_ap(c, v2p(code));\n#if CODEX\n codex_magic_action_run_thread_create(c->id);\n#endif\n \/\/ Wait for cpu to finish mpmain()\n while(bstate.load() == 0)\n ;\n rstrreset();\n }\n}\n\nvoid\ncmain(u64 mbmagic, u64 mbaddr)\n{\n extern u64 cpuhz;\n\n \/\/ Make cpus[0] work. CPU 0's percpu data is pre-allocated directly\n \/\/ in the image. *cpu and such won't work until we inittls.\n percpu_offsets[0] = __percpu_start;\n\n inituart();\n initphysmem(mbaddr);\n initpg(); \/\/ Requires initphysmem\n inithz(); \/\/ CPU Hz, microdelay\n initseg(&cpus[0]);\n inittls(&cpus[0]); \/\/ Requires initseg\n\n initacpitables(); \/\/ Requires initpg, inittls\n initlapic(); \/\/ Requires initpg\n initnuma(); \/\/ Requires initacpitables, initlapic\n initpercpu(); \/\/ Requires initnuma\n initcpus(); \/\/ Requires initnuma, initpercpu,\n \/\/ suggests initacpitables\n\n initpic(); \/\/ interrupt controller\n initiommu(); \/\/ Requires initlapic\n initextpic(); \/\/ Requires initpic\n \/\/ Interrupt routing is now configured\n\n inituartcons(); \/\/ Requires interrupt routing\n initcga();\n\n \/\/ Some global constructors require mycpu()->id (via myid()) which\n \/\/ we setup in inittls. (Note that gcc 4.7 eliminated the .ctors\n \/\/ section entirely, but gcc has supported .init_array for some\n \/\/ time.) Note that this will implicitly initialize CPU 0's per-CPU\n \/\/ objects as well.\n extern void (*__init_array_start[])(int, char **, char **);\n extern void (*__init_array_end[])(int, char **, char **);\n for (size_t i = 0; i < __init_array_end - __init_array_start; i++)\n (*__init_array_start[i])(0, nullptr, nullptr);\n\n inittrap();\n initcmdline();\n initkalloc();\n initwq(); \/\/ (after kalloc)\n initz(); \/\/ (after wq)\n initproc(); \/\/ process table\n initsched(); \/\/ scheduler run queues\n initidle();\n initgc(); \/\/ gc epochs and threads\n initdistref(); \/\/ distref collector thread\n initrefcache(); \/\/ Requires initsched\n initdisk(); \/\/ disk\n initinode(); \/\/ inode cache\n initconsole();\n initfutex();\n initsamp();\n initlockstat();\n initacpi(); \/\/ Requires initacpitables, initkalloc?\n inite1000(); \/\/ Before initpci\n initpci(); \/\/ Suggests initacpi\n initnet();\n initdev(); \/\/ Misc \/dev nodes\n\n if (VERBOSE)\n cprintf(\"ncpu %d %lu MHz\\n\", ncpu, cpuhz \/ 1000000);\n\n inituser(); \/\/ first user process\n initnmi();\n\n \/\/ XXX hack until mnodes can load from disk\n extern void mfsload();\n mfsload();\n\n#if CODEX\n initcodex();\n#endif\n bootothers(); \/\/ start other processors\n cleanuppg(); \/\/ Requires bootothers\n initcpprt();\n initwd(); \/\/ Requires initnmi\n\n idleloop();\n\n panic(\"Unreachable\");\n}\n\nvoid\nhalt(void)\n{\n acpi_power_off();\n\n for (;;);\n}\n<commit_msg>another codex hint<commit_after>#include \"types.h\"\n#include \"multiboot.hh\"\n#include \"kernel.hh\"\n#include \"spinlock.h\"\n#include \"kalloc.hh\"\n#include \"cpu.hh\"\n#include \"amd64.h\"\n#include \"hwvm.hh\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"apic.hh\"\n#include \"codex.hh\"\n#include \"mfs.hh\"\n\nvoid initpic(void);\nvoid initextpic(void);\nvoid inituart(void);\nvoid inituartcons(void);\nvoid initcga(void);\nvoid initconsole(void);\nvoid initpg(void);\nvoid cleanuppg(void);\nvoid inittls(struct cpu *);\nvoid initnmi(void);\nvoid initcodex(void);\nvoid inittrap(void);\nvoid initseg(struct cpu *);\nvoid initphysmem(paddr mbaddr);\nvoid initpercpu(void);\nvoid initkalloc(void);\nvoid initz(void);\nvoid initrcu(void);\nvoid initproc(void);\nvoid initinode(void);\nvoid initdisk(void);\nvoid inituser(void);\nvoid initsamp(void);\nvoid inite1000(void);\nvoid initpci(void);\nvoid initnet(void);\nvoid initsched(void);\nvoid initlockstat(void);\nvoid initwq(void);\nvoid initidle(void);\nvoid initcpprt(void);\nvoid initfutex(void);\nvoid initcmdline(void);\nvoid initdistref(void);\nvoid initrefcache(void);\nvoid initacpitables(void);\nvoid initnuma(void);\nvoid initcpus(void);\nvoid initlapic(void);\nvoid initiommu(void);\nvoid initacpi(void);\nvoid initwd(void);\nvoid initdev(void);\nvoid idleloop(void);\n\n#define IO_RTC 0x70\n\nstatic std::atomic<int> bstate;\nstatic cpuid_t bcpuid;\n\nvoid\nmpboot(void)\n{\n initseg(&cpus[bcpuid]);\n inittls(&cpus[bcpuid]); \/\/ Requires initseg\n initpg();\n\n \/\/ Call per-CPU static initializers. This is the per-CPU equivalent\n \/\/ of the init_array calls in cmain.\n extern void (*__percpuinit_array_start[])(size_t);\n extern void (*__percpuinit_array_end[])(size_t);\n for (size_t i = 0; i < __percpuinit_array_end - __percpuinit_array_start; i++)\n (*__percpuinit_array_start[i])(bcpuid);\n\n initlapic();\n initsamp();\n initidle();\n initnmi();\n initwd(); \/\/ Requires initnmi\n bstate.store(1);\n idleloop();\n}\n\nstatic void\nwarmreset(u32 addr)\n{\n volatile u16 *wrv;\n\n \/\/ \"The BSP must initialize CMOS shutdown code to 0AH\n \/\/ and the warm reset vector (DWORD based at 40:67) to point at\n \/\/ the AP startup code prior to the [universal startup algorithm].\"\n outb(IO_RTC, 0xF); \/\/ offset 0xF is shutdown code\n outb(IO_RTC+1, 0x0A);\n wrv = (u16*)p2v(0x40<<4 | 0x67); \/\/ Warm reset vector\n wrv[0] = 0;\n wrv[1] = addr >> 4;\n}\n\nstatic void\nrstrreset(void)\n{\n volatile u16 *wrv;\n\n \/\/ Paranoid: set warm reset code and vector back to defaults\n outb(IO_RTC, 0xF);\n outb(IO_RTC+1, 0);\n wrv = (u16*)p2v(0x40<<4 | 0x67);\n wrv[0] = 0;\n wrv[1] = 0;\n}\n\nstatic void\nbootothers(void)\n{\n extern u8 _bootother_start[];\n extern u64 _bootother_size;\n extern void (*apstart)(void);\n char *stack;\n u8 *code;\n\n \/\/ Write bootstrap code to unused memory at 0x7000.\n \/\/ The linker has placed the image of bootother.S in\n \/\/ _binary_bootother_start.\n code = (u8*) p2v(0x7000);\n memmove(code, _bootother_start, _bootother_size);\n\n for (int i = 0; i < ncpu; ++i) {\n if(i == myid()) \/\/ We've started already.\n continue;\n struct cpu *c = &cpus[i];\n\n warmreset(v2p(code));\n\n \/\/ Tell bootother.S what stack to use and the address of apstart;\n \/\/ it expects to find these two addresses stored just before\n \/\/ its first instruction.\n stack = (char*) ksalloc(slab_stack);\n *(u32*)(code-4) = (u32)v2p(&apstart);\n *(u64*)(code-12) = (u64)stack + KSTACKSIZE;\n \/\/ bootother.S sets this to 0x0a55face early on\n *(u32*)(code-64) = 0;\n\n bstate.store(0);\n bcpuid = c->id;\n lapic->start_ap(c, v2p(code));\n#if CODEX\n codex_magic_action_run_thread_create(c->id);\n#endif\n \/\/ Wait for cpu to finish mpmain()\n while(bstate.load() == 0)\n nop_pause();\n rstrreset();\n }\n}\n\nvoid\ncmain(u64 mbmagic, u64 mbaddr)\n{\n extern u64 cpuhz;\n\n \/\/ Make cpus[0] work. CPU 0's percpu data is pre-allocated directly\n \/\/ in the image. *cpu and such won't work until we inittls.\n percpu_offsets[0] = __percpu_start;\n\n inituart();\n initphysmem(mbaddr);\n initpg(); \/\/ Requires initphysmem\n inithz(); \/\/ CPU Hz, microdelay\n initseg(&cpus[0]);\n inittls(&cpus[0]); \/\/ Requires initseg\n\n initacpitables(); \/\/ Requires initpg, inittls\n initlapic(); \/\/ Requires initpg\n initnuma(); \/\/ Requires initacpitables, initlapic\n initpercpu(); \/\/ Requires initnuma\n initcpus(); \/\/ Requires initnuma, initpercpu,\n \/\/ suggests initacpitables\n\n initpic(); \/\/ interrupt controller\n initiommu(); \/\/ Requires initlapic\n initextpic(); \/\/ Requires initpic\n \/\/ Interrupt routing is now configured\n\n inituartcons(); \/\/ Requires interrupt routing\n initcga();\n\n \/\/ Some global constructors require mycpu()->id (via myid()) which\n \/\/ we setup in inittls. (Note that gcc 4.7 eliminated the .ctors\n \/\/ section entirely, but gcc has supported .init_array for some\n \/\/ time.) Note that this will implicitly initialize CPU 0's per-CPU\n \/\/ objects as well.\n extern void (*__init_array_start[])(int, char **, char **);\n extern void (*__init_array_end[])(int, char **, char **);\n for (size_t i = 0; i < __init_array_end - __init_array_start; i++)\n (*__init_array_start[i])(0, nullptr, nullptr);\n\n inittrap();\n initcmdline();\n initkalloc();\n initwq(); \/\/ (after kalloc)\n initz(); \/\/ (after wq)\n initproc(); \/\/ process table\n initsched(); \/\/ scheduler run queues\n initidle();\n initgc(); \/\/ gc epochs and threads\n initdistref(); \/\/ distref collector thread\n initrefcache(); \/\/ Requires initsched\n initdisk(); \/\/ disk\n initinode(); \/\/ inode cache\n initconsole();\n initfutex();\n initsamp();\n initlockstat();\n initacpi(); \/\/ Requires initacpitables, initkalloc?\n inite1000(); \/\/ Before initpci\n initpci(); \/\/ Suggests initacpi\n initnet();\n initdev(); \/\/ Misc \/dev nodes\n\n if (VERBOSE)\n cprintf(\"ncpu %d %lu MHz\\n\", ncpu, cpuhz \/ 1000000);\n\n inituser(); \/\/ first user process\n initnmi();\n\n \/\/ XXX hack until mnodes can load from disk\n extern void mfsload();\n mfsload();\n\n#if CODEX\n initcodex();\n#endif\n bootothers(); \/\/ start other processors\n cleanuppg(); \/\/ Requires bootothers\n initcpprt();\n initwd(); \/\/ Requires initnmi\n\n idleloop();\n\n panic(\"Unreachable\");\n}\n\nvoid\nhalt(void)\n{\n acpi_power_off();\n\n for (;;);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef __TEST__\n#include \"ArrayTest.h\"\n\nArrayTest::ArrayTest( ) :\n allocator( Rumia::Allocator( ) ),\n arr( Rumia::Array<int>( allocator ) ),\n objArr( Rumia::Array<SomeClass>( allocator ) )\n{\n}\n\nArrayTest::~ArrayTest( )\n{\n}\n\nvoid ArrayTest::SetUp( )\n{\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n arr.PushBack( 4 );\n} \n\nvoid ArrayTest::TearDown( )\n{\n arr.Clear( );\n objArr.Clear( );\n}\n\nTEST_F( ArrayTest, Reserve )\n{\n EXPECT_EQ( arr.GetCapacity( ), 4 );\n arr.Reserve( 8 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n \/\/ arr.Reserve( 4 ); \/\/ it going to make assertion\n}\n\nTEST_F( ArrayTest, Resize )\n{\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.Resize( 5 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n arr.Resize( 4 );\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.Resize( 5, 999 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.At( 4 ), 999 );\n}\n\nTEST_F( ArrayTest, PushBack )\n{\n EXPECT_EQ( arr.At( 0 ), 1 );\n EXPECT_EQ( arr.At( 1 ), 2 );\n EXPECT_EQ( arr.At( 2 ), 3 );\n EXPECT_EQ( arr.At( 3 ), 4 );\n EXPECT_EQ( arr.GetCapacity( ), 4 );\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.PushBack( 5 );\n EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n EXPECT_FALSE( arr.GetCapacity( ) == arr.GetSize( ) );\n}\n\nTEST_F( ArrayTest, PopBack )\n{\n EXPECT_EQ( arr.PopBack( ), 4 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.PopBack( ), 3);\n EXPECT_EQ( arr.GetSize( ), 2 );\n EXPECT_EQ( arr.PopBack( ), 2 );\n EXPECT_EQ( arr.GetSize( ), 1 );\n EXPECT_EQ( arr.PopBack( ), 1 );\n EXPECT_EQ( arr.GetSize( ), 0 );\n}\n\nTEST_F( ArrayTest, Emplace )\n{\n arr.Emplace( 5 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Emplace( 6 );\n EXPECT_EQ( arr.GetSize( ), 6 );\n EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 6 );\n}\n\nTEST_F( ArrayTest, Insert )\n{\n arr.Insert( 0, -1 );\n EXPECT_EQ( arr.At( 0 ), -1 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Insert( arr.GetSize( ) - 1, 1001 );\n EXPECT_EQ( arr.At( ( arr.GetSize( ) - 2 ) ), 1001 );\n}\n\nTEST_F( ArrayTest, IsEmpty )\n{\n EXPECT_TRUE( !arr.IsEmpty( ) );\n arr.PopBack( );\n arr.PopBack( );\n arr.PopBack( );\n arr.PopBack( );\n EXPECT_TRUE( arr.IsEmpty( ) );\n}\n\nTEST_F( ArrayTest, IsFull )\n{\n EXPECT_TRUE( arr.IsFull( ) );\n arr.PopBack( );\n EXPECT_FALSE( arr.IsFull( ) );\n arr.PushBack( 4 );\n arr.PushBack( -1 );\n EXPECT_FALSE( arr.IsFull( ) );\n}\n\nTEST_F( ArrayTest, Clear )\n{\n arr.Clear( false );\n EXPECT_TRUE( arr.IsEmpty( ) );\n arr.Clear( true );\n EXPECT_EQ( arr.GetCapacity( ), 0 );\n}\n\nTEST_F( ArrayTest, Copy )\n{\n Rumia::Array<int> copyConstructorObj{ arr };\n EXPECT_EQ( copyConstructorObj.PopBack( ), 4 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 3 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 2 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 1 );\n copyConstructorObj.PushBack( 999 );\n \/\/ arr and copyConstructorObj is not a same object!\n EXPECT_EQ( arr.PopBack( ), 4);\n\n Rumia::Array<int> anotherCopy{ allocator };\n anotherCopy = arr;\n EXPECT_EQ( anotherCopy.PopBack( ), 3 );\n EXPECT_EQ( anotherCopy.PopBack( ), 2 );\n EXPECT_EQ( anotherCopy.PopBack( ), 1 );\n EXPECT_TRUE( anotherCopy.IsEmpty( ) );\n}\n\nTEST_F( ArrayTest, Move )\n{\n Rumia::Array<int> movedObj( std::move( arr ) );\n EXPECT_TRUE( arr.IsEmpty( ) );\n EXPECT_EQ( movedObj.PopBack( ), 4 );\n EXPECT_EQ( movedObj.PopBack( ), 3 );\n\n Rumia::Array<int> anotherMovedObj{ allocator };\n EXPECT_TRUE( anotherMovedObj.IsEmpty( ) );\n anotherMovedObj = std::move( movedObj );\n EXPECT_FALSE( anotherMovedObj.IsEmpty( ) );\n EXPECT_TRUE( movedObj.IsEmpty( ) );\n EXPECT_EQ( anotherMovedObj.PopBack( ), 2 );\n EXPECT_EQ( anotherMovedObj.PopBack( ), 1 );\n}\n\nTEST_F( ArrayTest, ObjectMove )\n{\n SomeClass obj{ 30 };\n objArr.PushBack( obj );\n EXPECT_EQ( objArr.PopBack( ).m_data, 30 );\n EXPECT_EQ( obj.m_data, 30 );\n objArr.PushBack( std::move( obj ) );\n EXPECT_EQ( objArr.PopBack( ).m_data, 30 );\n EXPECT_EQ( obj.m_data, -1 );\n}\n\nTEST_F( ArrayTest, IndexOf )\n{\n EXPECT_EQ( arr.IndexOf( 1 ), 0 );\n EXPECT_EQ( arr.IndexOf( 2 ), 1 );\n EXPECT_EQ( arr.IndexOf( 3 ), 2 );\n EXPECT_EQ( arr.IndexOf( 4 ), 3 );\n EXPECT_EQ( arr.IndexOf( 9999 ), arr.GetSize( ) );\n}\n\nTEST_F( ArrayTest, EraseAt )\n{\n arr.EraseAt( 1 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.At( 1 ), 3 );\n EXPECT_EQ( arr.At( 2 ), 4 );\n}\n\nTEST_F( ArrayTest, Erase )\n{\n arr.Erase( 2 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.At( 1 ), 3 );\n EXPECT_EQ( arr.At( 2 ), 4 );\n EXPECT_EQ( arr.IndexOf( 2 ), arr.GetSize( ) );\n arr.Erase( 999 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.Erase( arr.begin( ) );\n EXPECT_EQ( 2, arr.At( 0 ) );\n}\n\nTEST_F( ArrayTest, FindIf )\n{\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n\n int FoundData = ( *arr.FindIf( [ ]( int Data )->bool { return ( Data == 2 ); } ) );\n EXPECT_EQ( FoundData, 2 );\n}\n\nTEST_F( ArrayTest, ConstItr )\n{\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n\n int Counter = 1;\n for ( auto itr = arr.cbegin( ); itr != arr.cend( ); ++itr )\n {\n EXPECT_EQ( ( *itr ), Counter );\n ++Counter;\n }\n}\n\nTEST_F( ArrayTest, Shrink )\n{\n arr.Clear( );\n arr.PushBack( 1 ); \/\/ Capacity 2\n arr.PushBack( 2 ); \n arr.PushBack( 3 ); \/\/ Capacity 4\n arr.PushBack( 4 );\n arr.PushBack( 5 ); \/\/ Capacity 8\n\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Shrink( );\n EXPECT_EQ( arr.GetCapacity( ), 5 );\n EXPECT_EQ( arr[ 4 ], 5 );\n}\n\n#endif<commit_msg>Added erase itr in loop test case<commit_after>#ifdef __TEST__\n#include \"ArrayTest.h\"\n\nArrayTest::ArrayTest( ) :\n allocator( Rumia::Allocator( ) ),\n arr( Rumia::Array<int>( allocator ) ),\n objArr( Rumia::Array<SomeClass>( allocator ) )\n{\n}\n\nArrayTest::~ArrayTest( )\n{\n}\n\nvoid ArrayTest::SetUp( )\n{\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n arr.PushBack( 4 );\n} \n\nvoid ArrayTest::TearDown( )\n{\n arr.Clear( );\n objArr.Clear( );\n}\n\nTEST_F( ArrayTest, Reserve )\n{\n EXPECT_EQ( arr.GetCapacity( ), 4 );\n arr.Reserve( 8 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n \/\/ arr.Reserve( 4 ); \/\/ it going to make assertion\n}\n\nTEST_F( ArrayTest, Resize )\n{\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.Resize( 5 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n arr.Resize( 4 );\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.Resize( 5, 999 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.At( 4 ), 999 );\n}\n\nTEST_F( ArrayTest, PushBack )\n{\n EXPECT_EQ( arr.At( 0 ), 1 );\n EXPECT_EQ( arr.At( 1 ), 2 );\n EXPECT_EQ( arr.At( 2 ), 3 );\n EXPECT_EQ( arr.At( 3 ), 4 );\n EXPECT_EQ( arr.GetCapacity( ), 4 );\n EXPECT_EQ( arr.GetSize( ), 4 );\n arr.PushBack( 5 );\n EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n EXPECT_FALSE( arr.GetCapacity( ) == arr.GetSize( ) );\n}\n\nTEST_F( ArrayTest, PopBack )\n{\n EXPECT_EQ( arr.PopBack( ), 4 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.PopBack( ), 3);\n EXPECT_EQ( arr.GetSize( ), 2 );\n EXPECT_EQ( arr.PopBack( ), 2 );\n EXPECT_EQ( arr.GetSize( ), 1 );\n EXPECT_EQ( arr.PopBack( ), 1 );\n EXPECT_EQ( arr.GetSize( ), 0 );\n}\n\nTEST_F( ArrayTest, Emplace )\n{\n arr.Emplace( 5 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Emplace( 6 );\n EXPECT_EQ( arr.GetSize( ), 6 );\n EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 6 );\n}\n\nTEST_F( ArrayTest, Insert )\n{\n arr.Insert( 0, -1 );\n EXPECT_EQ( arr.At( 0 ), -1 );\n EXPECT_EQ( arr.GetSize( ), 5 );\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Insert( arr.GetSize( ) - 1, 1001 );\n EXPECT_EQ( arr.At( ( arr.GetSize( ) - 2 ) ), 1001 );\n}\n\nTEST_F( ArrayTest, IsEmpty )\n{\n EXPECT_TRUE( !arr.IsEmpty( ) );\n arr.PopBack( );\n arr.PopBack( );\n arr.PopBack( );\n arr.PopBack( );\n EXPECT_TRUE( arr.IsEmpty( ) );\n}\n\nTEST_F( ArrayTest, IsFull )\n{\n EXPECT_TRUE( arr.IsFull( ) );\n arr.PopBack( );\n EXPECT_FALSE( arr.IsFull( ) );\n arr.PushBack( 4 );\n arr.PushBack( -1 );\n EXPECT_FALSE( arr.IsFull( ) );\n}\n\nTEST_F( ArrayTest, Clear )\n{\n arr.Clear( false );\n EXPECT_TRUE( arr.IsEmpty( ) );\n arr.Clear( true );\n EXPECT_EQ( arr.GetCapacity( ), 0 );\n}\n\nTEST_F( ArrayTest, Copy )\n{\n Rumia::Array<int> copyConstructorObj{ arr };\n EXPECT_EQ( copyConstructorObj.PopBack( ), 4 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 3 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 2 );\n EXPECT_EQ( copyConstructorObj.PopBack( ), 1 );\n copyConstructorObj.PushBack( 999 );\n \/\/ arr and copyConstructorObj is not a same object!\n EXPECT_EQ( arr.PopBack( ), 4);\n\n Rumia::Array<int> anotherCopy{ allocator };\n anotherCopy = arr;\n EXPECT_EQ( anotherCopy.PopBack( ), 3 );\n EXPECT_EQ( anotherCopy.PopBack( ), 2 );\n EXPECT_EQ( anotherCopy.PopBack( ), 1 );\n EXPECT_TRUE( anotherCopy.IsEmpty( ) );\n}\n\nTEST_F( ArrayTest, Move )\n{\n Rumia::Array<int> movedObj( std::move( arr ) );\n EXPECT_TRUE( arr.IsEmpty( ) );\n EXPECT_EQ( movedObj.PopBack( ), 4 );\n EXPECT_EQ( movedObj.PopBack( ), 3 );\n\n Rumia::Array<int> anotherMovedObj{ allocator };\n EXPECT_TRUE( anotherMovedObj.IsEmpty( ) );\n anotherMovedObj = std::move( movedObj );\n EXPECT_FALSE( anotherMovedObj.IsEmpty( ) );\n EXPECT_TRUE( movedObj.IsEmpty( ) );\n EXPECT_EQ( anotherMovedObj.PopBack( ), 2 );\n EXPECT_EQ( anotherMovedObj.PopBack( ), 1 );\n}\n\nTEST_F( ArrayTest, ObjectMove )\n{\n SomeClass obj{ 30 };\n objArr.PushBack( obj );\n EXPECT_EQ( objArr.PopBack( ).m_data, 30 );\n EXPECT_EQ( obj.m_data, 30 );\n objArr.PushBack( std::move( obj ) );\n EXPECT_EQ( objArr.PopBack( ).m_data, 30 );\n EXPECT_EQ( obj.m_data, -1 );\n}\n\nTEST_F( ArrayTest, IndexOf )\n{\n EXPECT_EQ( arr.IndexOf( 1 ), 0 );\n EXPECT_EQ( arr.IndexOf( 2 ), 1 );\n EXPECT_EQ( arr.IndexOf( 3 ), 2 );\n EXPECT_EQ( arr.IndexOf( 4 ), 3 );\n EXPECT_EQ( arr.IndexOf( 9999 ), arr.GetSize( ) );\n}\n\nTEST_F( ArrayTest, EraseAt )\n{\n arr.EraseAt( 1 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.At( 1 ), 3 );\n EXPECT_EQ( arr.At( 2 ), 4 );\n}\n\nTEST_F( ArrayTest, Erase )\n{\n arr.Erase( 2 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n EXPECT_EQ( arr.At( 1 ), 3 );\n EXPECT_EQ( arr.At( 2 ), 4 );\n EXPECT_EQ( arr.IndexOf( 2 ), arr.GetSize( ) );\n arr.Erase( 999 );\n EXPECT_EQ( arr.GetSize( ), 3 );\n\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.Erase( arr.begin( ) );\n EXPECT_EQ( 2, arr.At( 0 ) );\n\n arr.Clear( );\n arr.PushBack( 3 );\n arr.PushBack( 2 );\n arr.PushBack( 1 );\n\n for ( auto itr = arr.begin( ); itr != arr.end( ); ++itr )\n {\n if ( ( *itr ) == 2 )\n {\n arr.Erase( itr );\n }\n }\n\n EXPECT_EQ( 1, arr[ 1 ] );\n EXPECT_EQ( 3, ( *arr.begin( ) ) );\n}\n\nTEST_F( ArrayTest, FindIf )\n{\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n\n int FoundData = ( *arr.FindIf( [ ]( int Data )->bool { return ( Data == 2 ); } ) );\n EXPECT_EQ( FoundData, 2 );\n}\n\nTEST_F( ArrayTest, ConstItr )\n{\n arr.Clear( );\n arr.PushBack( 1 );\n arr.PushBack( 2 );\n arr.PushBack( 3 );\n\n int Counter = 1;\n for ( auto itr = arr.cbegin( ); itr != arr.cend( ); ++itr )\n {\n EXPECT_EQ( ( *itr ), Counter );\n ++Counter;\n }\n}\n\nTEST_F( ArrayTest, Shrink )\n{\n arr.Clear( );\n arr.PushBack( 1 ); \/\/ Capacity 2\n arr.PushBack( 2 ); \n arr.PushBack( 3 ); \/\/ Capacity 4\n arr.PushBack( 4 );\n arr.PushBack( 5 ); \/\/ Capacity 8\n\n EXPECT_EQ( arr.GetCapacity( ), 8 );\n arr.Shrink( );\n EXPECT_EQ( arr.GetCapacity( ), 5 );\n EXPECT_EQ( arr[ 4 ], 5 );\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include \"AliTPCPreprocessor.h\"\n#include \"AliShuttleInterface.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n#include \"AliTPCSensorTempArray.h\"\n#include \"AliTPCDBPressure.h\"\n#include \"AliTPCROC.h\"\n#include \"AliTPCCalROC.h\"\n#include \"AliTPCCalPad.h\"\n#include \"AliTPCCalibPedestal.h\"\n\n#include <TTimeStamp.h>\n\nconst Int_t kValCutTemp = 100; \/\/ discard temperatures > 100 degrees\nconst Int_t kDiffCutTemp = 5;\t \/\/ discard temperature differences > 5 degrees\nconst TString kPedestalRunType = \"PEDESTAL_RUN\"; \/\/ pedestal run identifier\n\n\/\/\n\/\/ This class is the SHUTTLE preprocessor for the TPC detector.\n\/\/ It contains several components, this far the part containing\n\/\/ temperatures is implemented\n\/\/\n\nClassImp(AliTPCPreprocessor)\n\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor::AliTPCPreprocessor(AliShuttleInterface* shuttle) :\n AliPreprocessor(\"TPC\",shuttle),\n fTemp(0), fPressure(0), fConfigOK(kTRUE), fROC(0)\n{\n \/\/ constructor\n fROC = AliTPCROC::Instance();\n}\n\/\/______________________________________________________________________________________________\n\/\/ AliTPCPreprocessor::AliTPCPreprocessor(const AliTPCPreprocessor& org) :\n\/\/ AliPreprocessor(org),\n\/\/ fTemp(0), fPressure(0), fConfigOK(kTRUE)\n\/\/ {\n\/\/ \/\/ copy constructor not implemented\n\/\/ \/\/ -- missing underlying copy constructor in AliPreprocessor\n\/\/\n\/\/ Fatal(\"AliTPCPreprocessor\", \"copy constructor not implemented\");\n\/\/\n\/\/ \/\/ fTemp = new AliTPCSensorTempArray(*(org.fTemp));\n\/\/ }\n\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor::~AliTPCPreprocessor()\n{\n \/\/ destructor\n\n delete fTemp;\n delete fPressure;\n}\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor& AliTPCPreprocessor::operator = (const AliTPCPreprocessor& )\n{\n Fatal(\"operator =\", \"assignment operator not implemented\");\n return *this;\n}\n\n\n\/\/______________________________________________________________________________________________\nvoid AliTPCPreprocessor::Initialize(Int_t run, UInt_t startTime,\n\tUInt_t endTime)\n{\n \/\/ Creates AliTestDataDCS object\n\n AliPreprocessor::Initialize(run, startTime, endTime);\n\n\tAliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run,\n\t\tTTimeStamp(startTime).AsString(),\n\t\tTTimeStamp(endTime).AsString()));\n\n \/\/ Temperature sensors\n\n TTree *confTree = 0;\n\tAliCDBEntry* entry = GetFromOCDB(\"Config\", \"Temperature\");\n if (entry) confTree = (TTree*) entry->GetObject();\n if ( confTree==0 ) {\n AliError(Form(\"Temperature Config OCDB entry missing.\\n\"));\n Log(\"AliTPCPreprocsessor: Temperature Config OCDB entry missing.\\n\");\n\t fConfigOK = kFALSE;\n\t return;\n }\n fTemp = new AliTPCSensorTempArray(fStartTime, fEndTime, confTree);\n\tfTemp->SetValCut(kValCutTemp);\n\tfTemp->SetDiffCut(kDiffCutTemp);\n\n \/\/ Pressure sensors\n\n confTree=0;\n\tentry=0;\n\tentry = GetFromOCDB(\"Config\", \"Pressure\");\n if (entry) confTree = (TTree*) entry->GetObject();\n if ( confTree==0 ) {\n AliError(Form(\"Pressure Config OCDB entry missing.\\n\"));\n Log(\"AliTPCPreprocsessor: Pressure Config OCDB entry missing.\\n\");\n\t fConfigOK = kFALSE;\n\t return;\n }\n\tfPressure = new AliDCSSensorArray(fStartTime, fEndTime, confTree);\n\n}\n\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::Process(TMap* dcsAliasMap)\n{\n \/\/ Fills data into TPC calibrations objects\n\n \/\/ Amanda servers provide information directly through dcsAliasMap\n\n if (!dcsAliasMap) return 9;\n if (!fConfigOK) return 9;\n\n TString runType = GetRunType();\n\n \/\/ Temperature sensors are processed by AliTPCCalTemp\n\n\n UInt_t tempResult = MapTemperature(dcsAliasMap);\n UInt_t result=tempResult;\n\n \/\/ Pressure sensors\n\n UInt_t pressureResult = MapPressure(dcsAliasMap);\n result += pressureResult;\n\n \/\/ Other calibration information will be retrieved through FXS files\n \/\/ examples:\n \/\/ TList* fileSourcesDAQ = GetFile(AliShuttleInterface::kDAQ, \"pedestals\");\n \/\/ const char* fileNamePed = GetFile(AliShuttleInterface::kDAQ, \"pedestals\", \"LDC1\");\n \/\/\n \/\/ TList* fileSourcesHLT = GetFile(AliShuttleInterface::kHLT, \"calib\");\n \/\/ const char* fileNameHLT = GetFile(AliShuttleInterface::kHLT, \"calib\", \"LDC1\");\n\n\n if(runType == kPedestalRunType) {\n UInt_t pedestalResult = ExtractPedestals();\n result += pedestalResult;\n }\n\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::MapTemperature(TMap* dcsAliasMap)\n{\n\n \/\/ extract DCS temperature maps. Perform fits to save space\n\n UInt_t result=0;\n TMap *map = fTemp->ExtractDCS(dcsAliasMap);\n if (map) {\n fTemp->MakeSplineFit(map);\n AliInfo(Form(\"Temperature values extracted, fits performed.\\n\"));\n } else {\n AliError(Form(\"No temperature map extracted.\\n\"));\n Log(\"AliTPCPreprocsessor: no temperature map extracted. \\n\");\n result=9;\n }\n delete map;\n \/\/ Now store the final CDB file\n\n if ( result == 0 ) {\n AliCDBMetaData metaData;\n\tmetaData.SetBeamPeriod(0);\n\tmetaData.SetResponsible(\"Haavard Helstrup\");\n\tmetaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n\tBool_t storeOK = Store(\"Calib\", \"Temperature\", fTemp, &metaData, 0, kFALSE);\n if ( !storeOK ) result=1;\n\n }\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::MapPressure(TMap* dcsAliasMap)\n{\n\n \/\/ extract DCS temperature maps. Perform fits to save space\n\n UInt_t result=0;\n TMap *map = fPressure->ExtractDCS(dcsAliasMap);\n if (map) {\n fPressure->MakeSplineFit(map);\n AliInfo(Form(\"Pressure values extracted, fits performed.\\n\"));\n } else {\n AliError(Form(\"No atmospheric pressure map extracted.\\n\"));\n Log(\"AliTPCPreprocsessor: no atmospheric pressure map extracted. \\n\");\n result=9;\n }\n delete map;\n \/\/ Now store the final CDB file\n\n if ( result == 0 ) {\n AliCDBMetaData metaData;\n\tmetaData.SetBeamPeriod(0);\n\tmetaData.SetResponsible(\"Haavard Helstrup\");\n\tmetaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n\tBool_t storeOK = Store(\"Calib\", \"Pressure\", fPressure, &metaData, 0, 0);\n if ( !storeOK ) result=1;\n\n }\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::ExtractPedestals()\n{\n \/\/\n \/\/ Read pedestal file from file exchage server\n \/\/ Keep original entry from OCDB in case no new pedestals are available\n \/\/\n AliTPCCalPad *calPadPed=0;\n AliCDBEntry* entry = GetFromOCDB(\"Calib\", \"Pedestals\");\n if (entry) calPadPed = (AliTPCCalPad*)entry->GetObject();\n if ( calPadPed==NULL ) {\n AliWarning(Form(\"No previous TPC pedestal entry available.\\n\"));\n Log(\"AliTPCPreprocsessor: No previous TPC pedestal entry available.\\n\");\n calPadPed = new AliTPCCalPad();\n }\n\n UInt_t result=0;\n\n Int_t nSectors = fROC->GetNSectors();\n TList* list = GetFileSources(AliShuttleInterface::kDAQ,\"pedestals\");\n if (list) {\n\n\/\/ loop through all files from LDCs\n\n UInt_t index = 0;\n while (list->At(index)!=NULL) {\n TObjString* fileNameEntry = (TObjString*) list->At(index);\n if (fileNameEntry!=NULL) {\n TString fileName = GetFile(AliShuttleInterface::kDAQ, \"pedestals\",\n\t fileNameEntry->GetString().Data());\n TFile *f = TFile::Open(fileName);\n AliTPCCalibPedestal *calPed;\n\tf->GetObject(\"AliTPCCalibPedestal\",calPed);\n\n \/\/ replace entries for the sectors available in the present file\n\n for (Int_t sector=0; sector<=nSectors; sector++) {\n AliTPCCalROC *roc=calPed->GetCalRocPedestal(sector, kFALSE);\n if ( roc ) calPadPed->SetCalROC(roc,sector);\n }\n }\n ++index;\n } \/\/ while(list)\n\/\/\n\/\/ Store updated pedestal entry to OCDB\n\/\/\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Haavard Helstrup\");\n metaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n Bool_t storeOK = Store(\"Calib\", \"Pedestals\", calPadPed, &metaData, 0, kTRUE);\n if ( !storeOK ) result=1;\n\n } \/\/ if(list)\n return result;\n}\n<commit_msg>Wrong constructor called (Haavard)<commit_after>\/**************************************************************************\n * Copyright(c) 2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n#include \"AliTPCPreprocessor.h\"\n#include \"AliShuttleInterface.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n#include \"AliTPCSensorTempArray.h\"\n#include \"AliTPCROC.h\"\n#include \"AliTPCCalROC.h\"\n#include \"AliTPCCalPad.h\"\n#include \"AliTPCCalibPedestal.h\"\n#include \"TFile.h\"\n\n#include <TTimeStamp.h>\n\nconst Int_t kValCutTemp = 100; \/\/ discard temperatures > 100 degrees\nconst Int_t kDiffCutTemp = 5;\t \/\/ discard temperature differences > 5 degrees\nconst TString kPedestalRunType = \"PEDESTAL_RUN\"; \/\/ pedestal run identifier\n\n\/\/\n\/\/ This class is the SHUTTLE preprocessor for the TPC detector.\n\/\/ It contains several components, this far the part containing\n\/\/ temperatures is implemented\n\/\/\n\nClassImp(AliTPCPreprocessor)\n\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor::AliTPCPreprocessor(AliShuttleInterface* shuttle) :\n AliPreprocessor(\"TPC\",shuttle),\n fTemp(0), fPressure(0), fConfigOK(kTRUE), fROC(0)\n{\n \/\/ constructor\n fROC = AliTPCROC::Instance();\n}\n\/\/______________________________________________________________________________________________\n\/\/ AliTPCPreprocessor::AliTPCPreprocessor(const AliTPCPreprocessor& org) :\n\/\/ AliPreprocessor(org),\n\/\/ fTemp(0), fPressure(0), fConfigOK(kTRUE)\n\/\/ {\n\/\/ \/\/ copy constructor not implemented\n\/\/ \/\/ -- missing underlying copy constructor in AliPreprocessor\n\/\/\n\/\/ Fatal(\"AliTPCPreprocessor\", \"copy constructor not implemented\");\n\/\/\n\/\/ \/\/ fTemp = new AliTPCSensorTempArray(*(org.fTemp));\n\/\/ }\n\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor::~AliTPCPreprocessor()\n{\n \/\/ destructor\n\n delete fTemp;\n delete fPressure;\n}\n\/\/______________________________________________________________________________________________\nAliTPCPreprocessor& AliTPCPreprocessor::operator = (const AliTPCPreprocessor& )\n{\n Fatal(\"operator =\", \"assignment operator not implemented\");\n return *this;\n}\n\n\n\/\/______________________________________________________________________________________________\nvoid AliTPCPreprocessor::Initialize(Int_t run, UInt_t startTime,\n\tUInt_t endTime)\n{\n \/\/ Creates AliTestDataDCS object\n\n AliPreprocessor::Initialize(run, startTime, endTime);\n\n\tAliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run,\n\t\tTTimeStamp(startTime).AsString(),\n\t\tTTimeStamp(endTime).AsString()));\n\n \/\/ Temperature sensors\n\n TTree *confTree = 0;\n\tAliCDBEntry* entry = GetFromOCDB(\"Config\", \"Temperature\");\n if (entry) confTree = (TTree*) entry->GetObject();\n if ( confTree==0 ) {\n AliError(Form(\"Temperature Config OCDB entry missing.\\n\"));\n Log(\"AliTPCPreprocsessor: Temperature Config OCDB entry missing.\\n\");\n\t fConfigOK = kFALSE;\n\t return;\n }\n fTemp = new AliTPCSensorTempArray(fStartTime, fEndTime, confTree);\n\tfTemp->SetValCut(kValCutTemp);\n\tfTemp->SetDiffCut(kDiffCutTemp);\n\n \/\/ Pressure sensors\n\n confTree=0;\n\tentry=0;\n\tentry = GetFromOCDB(\"Config\", \"Pressure\");\n if (entry) confTree = (TTree*) entry->GetObject();\n if ( confTree==0 ) {\n AliError(Form(\"Pressure Config OCDB entry missing.\\n\"));\n Log(\"AliTPCPreprocsessor: Pressure Config OCDB entry missing.\\n\");\n\t fConfigOK = kFALSE;\n\t return;\n }\n\tfPressure = new AliDCSSensorArray(fStartTime, fEndTime, confTree);\n\n}\n\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::Process(TMap* dcsAliasMap)\n{\n \/\/ Fills data into TPC calibrations objects\n\n \/\/ Amanda servers provide information directly through dcsAliasMap\n\n if (!dcsAliasMap) return 9;\n if (!fConfigOK) return 9;\n\n TString runType = GetRunType();\n\n \/\/ Temperature sensors are processed by AliTPCCalTemp\n\n\n UInt_t tempResult = MapTemperature(dcsAliasMap);\n UInt_t result=tempResult;\n\n \/\/ Pressure sensors\n\n UInt_t pressureResult = MapPressure(dcsAliasMap);\n result += pressureResult;\n\n \/\/ Other calibration information will be retrieved through FXS files\n \/\/ examples:\n \/\/ TList* fileSourcesDAQ = GetFile(AliShuttleInterface::kDAQ, \"pedestals\");\n \/\/ const char* fileNamePed = GetFile(AliShuttleInterface::kDAQ, \"pedestals\", \"LDC1\");\n \/\/\n \/\/ TList* fileSourcesHLT = GetFile(AliShuttleInterface::kHLT, \"calib\");\n \/\/ const char* fileNameHLT = GetFile(AliShuttleInterface::kHLT, \"calib\", \"LDC1\");\n\n\n if(runType == kPedestalRunType) {\n UInt_t pedestalResult = ExtractPedestals();\n result += pedestalResult;\n }\n\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::MapTemperature(TMap* dcsAliasMap)\n{\n\n \/\/ extract DCS temperature maps. Perform fits to save space\n\n UInt_t result=0;\n TMap *map = fTemp->ExtractDCS(dcsAliasMap);\n if (map) {\n fTemp->MakeSplineFit(map);\n AliInfo(Form(\"Temperature values extracted, fits performed.\\n\"));\n } else {\n AliError(Form(\"No temperature map extracted.\\n\"));\n Log(\"AliTPCPreprocsessor: no temperature map extracted. \\n\");\n result=9;\n }\n delete map;\n \/\/ Now store the final CDB file\n\n if ( result == 0 ) {\n AliCDBMetaData metaData;\n\tmetaData.SetBeamPeriod(0);\n\tmetaData.SetResponsible(\"Haavard Helstrup\");\n\tmetaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n\tBool_t storeOK = Store(\"Calib\", \"Temperature\", fTemp, &metaData, 0, kFALSE);\n if ( !storeOK ) result=1;\n\n }\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::MapPressure(TMap* dcsAliasMap)\n{\n\n \/\/ extract DCS temperature maps. Perform fits to save space\n\n UInt_t result=0;\n TMap *map = fPressure->ExtractDCS(dcsAliasMap);\n if (map) {\n fPressure->MakeSplineFit(map);\n AliInfo(Form(\"Pressure values extracted, fits performed.\\n\"));\n } else {\n AliError(Form(\"No atmospheric pressure map extracted.\\n\"));\n Log(\"AliTPCPreprocsessor: no atmospheric pressure map extracted. \\n\");\n result=9;\n }\n delete map;\n \/\/ Now store the final CDB file\n\n if ( result == 0 ) {\n AliCDBMetaData metaData;\n\tmetaData.SetBeamPeriod(0);\n\tmetaData.SetResponsible(\"Haavard Helstrup\");\n\tmetaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n\tBool_t storeOK = Store(\"Calib\", \"Pressure\", fPressure, &metaData, 0, 0);\n if ( !storeOK ) result=1;\n\n }\n\n return result;\n}\n\/\/______________________________________________________________________________________________\nUInt_t AliTPCPreprocessor::ExtractPedestals()\n{\n \/\/\n \/\/ Read pedestal file from file exchage server\n \/\/ Keep original entry from OCDB in case no new pedestals are available\n \/\/\n AliTPCCalPad *calPadPed=0;\n AliCDBEntry* entry = GetFromOCDB(\"Calib\", \"Pedestals\");\n if (entry) calPadPed = (AliTPCCalPad*)entry->GetObject();\n if ( calPadPed==NULL ) {\n AliWarning(Form(\"No previous TPC pedestal entry available.\\n\"));\n Log(\"AliTPCPreprocsessor: No previous TPC pedestal entry available.\\n\");\n calPadPed = new AliTPCCalPad(\"pedestals\",\"pedestals\");\n }\n\n UInt_t result=0;\n\n Int_t nSectors = fROC->GetNSectors();\n TList* list = GetFileSources(AliShuttleInterface::kDAQ,\"pedestals\");\n if (list) {\n\n\/\/ loop through all files from LDCs\n\n UInt_t index = 0;\n while (list->At(index)!=NULL) {\n TObjString* fileNameEntry = (TObjString*) list->At(index);\n if (fileNameEntry!=NULL) {\n TString fileName = GetFile(AliShuttleInterface::kDAQ, \"pedestals\",\n\t fileNameEntry->GetString().Data());\n TFile *f = TFile::Open(fileName);\n AliTPCCalibPedestal *calPed;\n\tf->GetObject(\"AliTPCCalibPedestal\",calPed);\n\n \/\/ replace entries for the sectors available in the present file\n\n for (Int_t sector=0; sector<=nSectors; sector++) {\n AliTPCCalROC *roc=calPed->GetCalRocPedestal(sector, kFALSE);\n if ( roc ) calPadPed->SetCalROC(roc,sector);\n }\n }\n ++index;\n } \/\/ while(list)\n\/\/\n\/\/ Store updated pedestal entry to OCDB\n\/\/\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Haavard Helstrup\");\n metaData.SetComment(\"Preprocessor AliTPC data base entries.\");\n\n Bool_t storeOK = Store(\"Calib\", \"Pedestals\", calPadPed, &metaData, 0, kTRUE);\n if ( !storeOK ) result=1;\n\n } \/\/ if(list)\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- AsmWriterInst.h - Classes encapsulating a printable inst -----------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These classes implement a parser for assembly strings.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmWriterInst.h\"\n#include \"CodeGenTarget.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n\nusing namespace llvm;\n\nstatic bool isIdentChar(char C) {\n return (C >= 'a' && C <= 'z') ||\n (C >= 'A' && C <= 'Z') ||\n (C >= '0' && C <= '9') ||\n C == '_';\n}\n\nstd::string AsmWriterOperand::getCode() const {\n if (OperandType == isLiteralTextOperand) {\n if (Str.size() == 1)\n return \"O << '\" + Str + \"'; \";\n return \"O << \\\"\" + Str + \"\\\"; \";\n }\n\n if (OperandType == isLiteralStatementOperand)\n return Str;\n\n std::string Result = Str + \"(MI\";\n if (MIOpNo != ~0U)\n Result += \", \" + utostr(MIOpNo);\n Result += \", O\";\n if (!MiModifier.empty())\n Result += \", \\\"\" + MiModifier + '\"';\n return Result + \"); \";\n}\n\n\/\/\/ ParseAsmString - Parse the specified Instruction's AsmString into this\n\/\/\/ AsmWriterInst.\n\/\/\/\nAsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI,\n unsigned Variant,\n int FirstOperandColumn,\n int OperandSpacing) {\n this->CGI = &CGI;\n\n \/\/ This is the number of tabs we've seen if we're doing columnar layout.\n unsigned CurColumn = 0;\n\n\n \/\/ NOTE: Any extensions to this code need to be mirrored in the\n \/\/ AsmPrinter::printInlineAsm code that executes as compile time (assuming\n \/\/ that inline asm strings should also get the new feature)!\n std::string AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, Variant);\n std::string::size_type LastEmitted = 0;\n while (LastEmitted != AsmString.size()) {\n std::string::size_type DollarPos =\n AsmString.find_first_of(\"$\\\\\", LastEmitted);\n if (DollarPos == std::string::npos) DollarPos = AsmString.size();\n\n \/\/ Emit a constant string fragment.\n if (DollarPos != LastEmitted) {\n for (; LastEmitted != DollarPos; ++LastEmitted)\n switch (AsmString[LastEmitted]) {\n case '\\n':\n AddLiteralString(\"\\\\n\");\n break;\n case '\\t':\n \/\/ If the asm writer is not using a columnar layout, \\t is not\n \/\/ magic.\n if (FirstOperandColumn == -1 || OperandSpacing == -1) {\n AddLiteralString(\"\\\\t\");\n } else {\n \/\/ We recognize a tab as an operand delimeter.\n unsigned DestColumn = FirstOperandColumn +\n CurColumn++ * OperandSpacing;\n Operands.push_back(\n AsmWriterOperand(\n \"O.PadToColumn(\" +\n utostr(DestColumn) + \");\\n\",\n AsmWriterOperand::isLiteralStatementOperand));\n }\n break;\n case '\"':\n AddLiteralString(\"\\\\\\\"\");\n break;\n case '\\\\':\n AddLiteralString(\"\\\\\\\\\");\n break;\n default:\n AddLiteralString(std::string(1, AsmString[LastEmitted]));\n break;\n }\n } else if (AsmString[DollarPos] == '\\\\') {\n if (DollarPos+1 != AsmString.size()) {\n if (AsmString[DollarPos+1] == 'n') {\n AddLiteralString(\"\\\\n\");\n } else if (AsmString[DollarPos+1] == 't') {\n \/\/ If the asm writer is not using a columnar layout, \\t is not\n \/\/ magic.\n if (FirstOperandColumn == -1 || OperandSpacing == -1) {\n AddLiteralString(\"\\\\t\");\n break;\n }\n\n \/\/ We recognize a tab as an operand delimeter.\n unsigned DestColumn = FirstOperandColumn +\n CurColumn++ * OperandSpacing;\n Operands.push_back(\n AsmWriterOperand(\"O.PadToColumn(\" + utostr(DestColumn) + \");\\n\",\n AsmWriterOperand::isLiteralStatementOperand));\n break;\n } else if (std::string(\"${|}\\\\\").find(AsmString[DollarPos+1])\n != std::string::npos) {\n AddLiteralString(std::string(1, AsmString[DollarPos+1]));\n } else {\n PrintFatalError(\"Non-supported escaped character found in instruction '\" +\n CGI.TheDef->getName() + \"'!\");\n }\n LastEmitted = DollarPos+2;\n continue;\n }\n } else if (DollarPos+1 != AsmString.size() &&\n AsmString[DollarPos+1] == '$') {\n AddLiteralString(\"$\"); \/\/ \"$$\" -> $\n LastEmitted = DollarPos+2;\n } else {\n \/\/ Get the name of the variable.\n std::string::size_type VarEnd = DollarPos+1;\n\n \/\/ handle ${foo}bar as $foo by detecting whether the character following\n \/\/ the dollar sign is a curly brace. If so, advance VarEnd and DollarPos\n \/\/ so the variable name does not contain the leading curly brace.\n bool hasCurlyBraces = false;\n if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {\n hasCurlyBraces = true;\n ++DollarPos;\n ++VarEnd;\n }\n\n while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))\n ++VarEnd;\n std::string VarName(AsmString.begin()+DollarPos+1,\n AsmString.begin()+VarEnd);\n\n \/\/ Modifier - Support ${foo:modifier} syntax, where \"modifier\" is passed\n \/\/ into printOperand. Also support ${:feature}, which is passed into\n \/\/ PrintSpecial.\n std::string Modifier;\n\n \/\/ In order to avoid starting the next string at the terminating curly\n \/\/ brace, advance the end position past it if we found an opening curly\n \/\/ brace.\n if (hasCurlyBraces) {\n if (VarEnd >= AsmString.size())\n PrintFatalError(\"Reached end of string before terminating curly brace in '\"\n + CGI.TheDef->getName() + \"'\");\n\n \/\/ Look for a modifier string.\n if (AsmString[VarEnd] == ':') {\n ++VarEnd;\n if (VarEnd >= AsmString.size())\n PrintFatalError(\"Reached end of string before terminating curly brace in '\"\n + CGI.TheDef->getName() + \"'\");\n\n unsigned ModifierStart = VarEnd;\n while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))\n ++VarEnd;\n Modifier = std::string(AsmString.begin()+ModifierStart,\n AsmString.begin()+VarEnd);\n if (Modifier.empty())\n PrintFatalError(\"Bad operand modifier name in '\"+ CGI.TheDef->getName() + \"'\");\n }\n\n if (AsmString[VarEnd] != '}')\n PrintFatalError(\"Variable name beginning with '{' did not end with '}' in '\"\n + CGI.TheDef->getName() + \"'\");\n ++VarEnd;\n }\n if (VarName.empty() && Modifier.empty())\n PrintFatalError(\"Stray '$' in '\" + CGI.TheDef->getName() +\n \"' asm string, maybe you want $$?\");\n\n if (VarName.empty()) {\n \/\/ Just a modifier, pass this into PrintSpecial.\n Operands.push_back(AsmWriterOperand(\"PrintSpecial\",\n ~0U,\n ~0U,\n Modifier));\n } else {\n \/\/ Otherwise, normal operand.\n unsigned OpNo = CGI.Operands.getOperandNamed(VarName);\n CGIOperandList::OperandInfo OpInfo = CGI.Operands[OpNo];\n\n unsigned MIOp = OpInfo.MIOperandNo;\n Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,\n OpNo, MIOp, Modifier));\n }\n LastEmitted = VarEnd;\n }\n }\n\n Operands.push_back(AsmWriterOperand(\"return;\",\n AsmWriterOperand::isLiteralStatementOperand));\n}\n\n\/\/\/ MatchesAllButOneOp - If this instruction is exactly identical to the\n\/\/\/ specified instruction except for one differing operand, return the differing\n\/\/\/ operand number. If more than one operand mismatches, return ~1, otherwise\n\/\/\/ if the instructions are identical return ~0.\nunsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{\n if (Operands.size() != Other.Operands.size()) return ~1;\n\n unsigned MismatchOperand = ~0U;\n for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n if (Operands[i] != Other.Operands[i]) {\n if (MismatchOperand != ~0U) \/\/ Already have one mismatch?\n return ~1U;\n else\n MismatchOperand = i;\n }\n }\n return MismatchOperand;\n}\n<commit_msg>Remove 'else' after 'return'. No functional change.<commit_after>\/\/===- AsmWriterInst.h - Classes encapsulating a printable inst -----------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These classes implement a parser for assembly strings.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmWriterInst.h\"\n#include \"CodeGenTarget.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n\nusing namespace llvm;\n\nstatic bool isIdentChar(char C) {\n return (C >= 'a' && C <= 'z') ||\n (C >= 'A' && C <= 'Z') ||\n (C >= '0' && C <= '9') ||\n C == '_';\n}\n\nstd::string AsmWriterOperand::getCode() const {\n if (OperandType == isLiteralTextOperand) {\n if (Str.size() == 1)\n return \"O << '\" + Str + \"'; \";\n return \"O << \\\"\" + Str + \"\\\"; \";\n }\n\n if (OperandType == isLiteralStatementOperand)\n return Str;\n\n std::string Result = Str + \"(MI\";\n if (MIOpNo != ~0U)\n Result += \", \" + utostr(MIOpNo);\n Result += \", O\";\n if (!MiModifier.empty())\n Result += \", \\\"\" + MiModifier + '\"';\n return Result + \"); \";\n}\n\n\/\/\/ ParseAsmString - Parse the specified Instruction's AsmString into this\n\/\/\/ AsmWriterInst.\n\/\/\/\nAsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI,\n unsigned Variant,\n int FirstOperandColumn,\n int OperandSpacing) {\n this->CGI = &CGI;\n\n \/\/ This is the number of tabs we've seen if we're doing columnar layout.\n unsigned CurColumn = 0;\n\n\n \/\/ NOTE: Any extensions to this code need to be mirrored in the\n \/\/ AsmPrinter::printInlineAsm code that executes as compile time (assuming\n \/\/ that inline asm strings should also get the new feature)!\n std::string AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, Variant);\n std::string::size_type LastEmitted = 0;\n while (LastEmitted != AsmString.size()) {\n std::string::size_type DollarPos =\n AsmString.find_first_of(\"$\\\\\", LastEmitted);\n if (DollarPos == std::string::npos) DollarPos = AsmString.size();\n\n \/\/ Emit a constant string fragment.\n if (DollarPos != LastEmitted) {\n for (; LastEmitted != DollarPos; ++LastEmitted)\n switch (AsmString[LastEmitted]) {\n case '\\n':\n AddLiteralString(\"\\\\n\");\n break;\n case '\\t':\n \/\/ If the asm writer is not using a columnar layout, \\t is not\n \/\/ magic.\n if (FirstOperandColumn == -1 || OperandSpacing == -1) {\n AddLiteralString(\"\\\\t\");\n } else {\n \/\/ We recognize a tab as an operand delimeter.\n unsigned DestColumn = FirstOperandColumn +\n CurColumn++ * OperandSpacing;\n Operands.push_back(\n AsmWriterOperand(\n \"O.PadToColumn(\" +\n utostr(DestColumn) + \");\\n\",\n AsmWriterOperand::isLiteralStatementOperand));\n }\n break;\n case '\"':\n AddLiteralString(\"\\\\\\\"\");\n break;\n case '\\\\':\n AddLiteralString(\"\\\\\\\\\");\n break;\n default:\n AddLiteralString(std::string(1, AsmString[LastEmitted]));\n break;\n }\n } else if (AsmString[DollarPos] == '\\\\') {\n if (DollarPos+1 != AsmString.size()) {\n if (AsmString[DollarPos+1] == 'n') {\n AddLiteralString(\"\\\\n\");\n } else if (AsmString[DollarPos+1] == 't') {\n \/\/ If the asm writer is not using a columnar layout, \\t is not\n \/\/ magic.\n if (FirstOperandColumn == -1 || OperandSpacing == -1) {\n AddLiteralString(\"\\\\t\");\n break;\n }\n\n \/\/ We recognize a tab as an operand delimeter.\n unsigned DestColumn = FirstOperandColumn +\n CurColumn++ * OperandSpacing;\n Operands.push_back(\n AsmWriterOperand(\"O.PadToColumn(\" + utostr(DestColumn) + \");\\n\",\n AsmWriterOperand::isLiteralStatementOperand));\n break;\n } else if (std::string(\"${|}\\\\\").find(AsmString[DollarPos+1])\n != std::string::npos) {\n AddLiteralString(std::string(1, AsmString[DollarPos+1]));\n } else {\n PrintFatalError(\"Non-supported escaped character found in instruction '\" +\n CGI.TheDef->getName() + \"'!\");\n }\n LastEmitted = DollarPos+2;\n continue;\n }\n } else if (DollarPos+1 != AsmString.size() &&\n AsmString[DollarPos+1] == '$') {\n AddLiteralString(\"$\"); \/\/ \"$$\" -> $\n LastEmitted = DollarPos+2;\n } else {\n \/\/ Get the name of the variable.\n std::string::size_type VarEnd = DollarPos+1;\n\n \/\/ handle ${foo}bar as $foo by detecting whether the character following\n \/\/ the dollar sign is a curly brace. If so, advance VarEnd and DollarPos\n \/\/ so the variable name does not contain the leading curly brace.\n bool hasCurlyBraces = false;\n if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {\n hasCurlyBraces = true;\n ++DollarPos;\n ++VarEnd;\n }\n\n while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))\n ++VarEnd;\n std::string VarName(AsmString.begin()+DollarPos+1,\n AsmString.begin()+VarEnd);\n\n \/\/ Modifier - Support ${foo:modifier} syntax, where \"modifier\" is passed\n \/\/ into printOperand. Also support ${:feature}, which is passed into\n \/\/ PrintSpecial.\n std::string Modifier;\n\n \/\/ In order to avoid starting the next string at the terminating curly\n \/\/ brace, advance the end position past it if we found an opening curly\n \/\/ brace.\n if (hasCurlyBraces) {\n if (VarEnd >= AsmString.size())\n PrintFatalError(\"Reached end of string before terminating curly brace in '\"\n + CGI.TheDef->getName() + \"'\");\n\n \/\/ Look for a modifier string.\n if (AsmString[VarEnd] == ':') {\n ++VarEnd;\n if (VarEnd >= AsmString.size())\n PrintFatalError(\"Reached end of string before terminating curly brace in '\"\n + CGI.TheDef->getName() + \"'\");\n\n unsigned ModifierStart = VarEnd;\n while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))\n ++VarEnd;\n Modifier = std::string(AsmString.begin()+ModifierStart,\n AsmString.begin()+VarEnd);\n if (Modifier.empty())\n PrintFatalError(\"Bad operand modifier name in '\"+ CGI.TheDef->getName() + \"'\");\n }\n\n if (AsmString[VarEnd] != '}')\n PrintFatalError(\"Variable name beginning with '{' did not end with '}' in '\"\n + CGI.TheDef->getName() + \"'\");\n ++VarEnd;\n }\n if (VarName.empty() && Modifier.empty())\n PrintFatalError(\"Stray '$' in '\" + CGI.TheDef->getName() +\n \"' asm string, maybe you want $$?\");\n\n if (VarName.empty()) {\n \/\/ Just a modifier, pass this into PrintSpecial.\n Operands.push_back(AsmWriterOperand(\"PrintSpecial\",\n ~0U,\n ~0U,\n Modifier));\n } else {\n \/\/ Otherwise, normal operand.\n unsigned OpNo = CGI.Operands.getOperandNamed(VarName);\n CGIOperandList::OperandInfo OpInfo = CGI.Operands[OpNo];\n\n unsigned MIOp = OpInfo.MIOperandNo;\n Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,\n OpNo, MIOp, Modifier));\n }\n LastEmitted = VarEnd;\n }\n }\n\n Operands.push_back(AsmWriterOperand(\"return;\",\n AsmWriterOperand::isLiteralStatementOperand));\n}\n\n\/\/\/ MatchesAllButOneOp - If this instruction is exactly identical to the\n\/\/\/ specified instruction except for one differing operand, return the differing\n\/\/\/ operand number. If more than one operand mismatches, return ~1, otherwise\n\/\/\/ if the instructions are identical return ~0.\nunsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{\n if (Operands.size() != Other.Operands.size()) return ~1;\n\n unsigned MismatchOperand = ~0U;\n for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n if (Operands[i] != Other.Operands[i]) {\n if (MismatchOperand != ~0U) \/\/ Already have one mismatch?\n return ~1U;\n MismatchOperand = i;\n }\n }\n return MismatchOperand;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"eval.hpp\"\n\n#include <functional>\n#include <stdexcept>\n\n#include \"ast.hpp\"\n#include \"hamt.hpp\"\n#include \"symbol.hpp\"\n#include \"common.hpp\"\n\nnamespace eval {\n\nusing table_type = hamt::map<symbol, value>;\n\n\n\n\ntemplate<class T>\nusing monad = std::function<T(const table_type&)>;\n\nstatic monad<value> compile(ast::expr self);\n\ntemplate<class T>\nstatic monad<value> compile(T self) {\n throw std::runtime_error(\"unimplemented compile: \" + std::string(typeid(T).name()));\n}\n\nstatic monad<value> compile(ast::lit self) {\n return match(self, [](auto self) -> monad<value> {\n return [=](const auto&) { return self; };\n });\n}\n\nstruct closure {\n table_type env;\n symbol arg;\n monad<value> body;\n};\n\nstatic monad<value> compile(ast::abs self) {\n return [body = compile(self.body),\n arg = self.arg.name](const auto& env) {\n return closure{env, arg, body};\n };\n}\n\n\nstatic monad<value> compile(ast::app self) {\n const auto func = compile(self.func);\n const auto arg = compile(self.arg); \n \n return [=](const auto& env) {\n const value f = func(env);\n const closure& c = f.template get<closure>();\n return c.body(c.env.set(c.arg, arg(env)));\n };\n}\n\n\nstatic monad<value> compile(ast::var self) {\n return [name=self.name](const auto& env) {\n return env.get(name);\n };\n}\n\n\nstatic monad<value> compile(ast::cond self) {\n return [pred=compile(self.pred),\n conseq=compile(self.conseq),\n alt=compile(self.alt)](const auto& env) {\n if(pred(env).template get<bool>()) {\n return conseq(env);\n } else {\n return alt(env);\n }\n };\n}\n\nstruct def {\n symbol name;\n monad<value> code;\n};\n\nstatic monad<value> compile(ast::let self) {\n const auto defs = map(self.defs, [](ast::def self) {\n return def{self.name, compile(self.value)};\n });\n\n const auto body = compile(self.body);\n \n return [=](auto env) {\n for(auto&& def: defs) {\n env = env.set(def.name, def.code(env));\n }\n\n return body(env);\n };\n}\n\n\nstruct record {\n using attrs_type = hamt::map<symbol, value>;\n attrs_type attrs;\n};\n\nstatic monad<value> compile(ast::record self) {\n const auto defs = map(self.attrs, [](ast::def self) {\n return def{self.name, compile(self.value)};\n });\n\n return [defs](const auto& env) {\n record res;\n for(auto&& attr: defs) {\n res.attrs = std::move(res.attrs).set(attr.name, attr.code(env));\n }\n return res;\n };\n}\n\n\nstatic monad<value> compile(ast::attr self) {\n auto arg = compile(self.arg);\n auto name = self.name;\n return [=](const auto& env) {\n return arg(env).template get<record>().attrs.get(name);\n };\n}\n\n\nstd::string value::show() const {\n return match(*this,\n [](bool self) -> std::string { return self ? \"true\" : \"false\"; },\n [](long self) { return std::to_string(self); },\n [](double self) { return std::to_string(self); },\n [](std::string self) { return quote(self); },\n [](record self) {\n std::stringstream ss;\n ss << \"(record\";\n\n self.attrs.iter([&](symbol name, value val) {\n ss << \" (\" << name << \" \" << val.show() << \")\";\n });\n\n ss << \")\";\n\n \/\/ TODO abbreviate if too long\n return ss.str();\n },\n [](closure self) { return std::string(\"#closure\"); });\n}\n\n\nstatic monad<value> compile(ast::expr self) {\n return match(self, [](auto self) { return compile(self); });\n}\n\nstatic value wrap(value self) { return self; }\n\ntemplate<class Func>\nstatic closure wrap(Func func) {\n const symbol arg = \"__arg__\";\n return {{}, arg, [=](const auto& env) {\n return wrap(func(env.get(arg)));\n }};\n}\n\n\nstruct environment {\n table_type table;\n\n template<class T>\n void def(symbol name, T value) {\n table = table.set(name, wrap(value));\n }\n};\n\n\nvalue run(std::shared_ptr<environment> env, const ast::expr& self) {\n return compile(self)(env->table);\n}\n\n\nstd::shared_ptr<environment> make_environment() {\n auto res = std::make_shared<environment>();\n\n res->def(\"eq\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() == y.get<long>();\n };\n });\n\n res->def(\"add\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() + y.get<long>();\n };\n });\n\n res->def(\"sub\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() - y.get<long>();\n };\n });\n\n res->def(\"mul\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() * y.get<long>();\n };\n });\n \n \n return res;\n}\n\n\n} \/\/ namespace eval\n\n\n<commit_msg>eval recursive functions<commit_after>#include \"eval.hpp\"\n\n#include <functional>\n#include <stdexcept>\n\n#include \"ast.hpp\"\n#include \"hamt.hpp\"\n#include \"symbol.hpp\"\n#include \"common.hpp\"\n\nnamespace eval {\n\nusing table_type = hamt::map<symbol, value>;\n\n\n\n\ntemplate<class T>\nusing monad = std::function<T(const table_type&)>;\n\nstatic monad<value> compile(ast::expr self);\n\ntemplate<class T>\nstatic monad<value> compile(T self) {\n throw std::runtime_error(\"unimplemented compile: \" + std::string(typeid(T).name()));\n}\n\nstatic monad<value> compile(ast::lit self) {\n return match(self, [](auto self) -> monad<value> {\n return [=](const auto&) { return self; };\n });\n}\n\nstruct closure {\n table_type env;\n symbol arg;\n monad<value> body;\n mutable symbol self = \"__self__\";\n};\n\nstatic symbol gensym(std::string prefix) {\n static std::size_t index = 0;\n symbol res = (prefix + std::to_string(index++)).c_str();\n return res;\n}\n\nstatic monad<value> compile(ast::abs self) {\n return [body = compile(self.body),\n arg = self.arg.name](const auto& env) {\n return closure{env, arg, body};\n };\n}\n\n\nstatic monad<value> compile(ast::app self) {\n const auto func = compile(self.func);\n const auto arg = compile(self.arg); \n \n return [=](const auto& env) {\n value f = func(env);\n const closure& c = f.template get<closure>();\n auto sub = c.env.set(c.arg, arg(env));\n\n \/\/ TODO only if needed\n sub = sub.set(c.self, std::move(f));\n return c.body(sub);\n };\n}\n\n\nstatic monad<value> compile(ast::var self) {\n return [name=self.name](const auto& env) {\n return env.get(name);\n };\n}\n\n\nstatic monad<value> compile(ast::cond self) {\n return [pred=compile(self.pred),\n conseq=compile(self.conseq),\n alt=compile(self.alt)](const auto& env) {\n if(pred(env).template get<bool>()) {\n return conseq(env);\n } else {\n return alt(env);\n }\n };\n}\n\nstruct def {\n symbol name;\n monad<value> code;\n};\n\nstatic monad<value> compile(ast::let self) {\n const auto defs = map(self.defs, [](ast::def self) {\n return def{self.name, compile(self.value)};\n });\n\n const auto body = compile(self.body);\n \n return [=](auto env) {\n for(auto&& def: defs) {\n value v = def.code(env);\n if(auto c = v.template cast<closure>()) {\n c->self = def.name;\n }\n env = env.set(def.name, std::move(v));\n }\n\n return body(env);\n };\n}\n\n\nstruct record {\n using attrs_type = hamt::map<symbol, value>;\n attrs_type attrs;\n};\n\nstatic monad<value> compile(ast::record self) {\n const auto defs = map(self.attrs, [](ast::def self) {\n return def{self.name, compile(self.value)};\n });\n\n return [defs](const auto& env) {\n record res;\n for(auto&& attr: defs) {\n res.attrs = std::move(res.attrs).set(attr.name, attr.code(env));\n }\n return res;\n };\n}\n\n\nstatic monad<value> compile(ast::attr self) {\n auto arg = compile(self.arg);\n auto name = self.name;\n return [=](const auto& env) {\n return arg(env).template get<record>().attrs.get(name);\n };\n}\n\n\nstd::string value::show() const {\n return match(*this,\n [](bool self) -> std::string { return self ? \"true\" : \"false\"; },\n [](long self) { return std::to_string(self); },\n [](double self) { return std::to_string(self); },\n [](std::string self) { return quote(self); },\n [](record self) {\n std::stringstream ss;\n ss << \"(record\";\n\n self.attrs.iter([&](symbol name, value val) {\n ss << \" (\" << name << \" \" << val.show() << \")\";\n });\n\n ss << \")\";\n\n \/\/ TODO abbreviate if too long\n return ss.str();\n },\n [](closure self) { return std::string(\"#closure\"); });\n}\n\n\nstatic monad<value> compile(ast::expr self) {\n return match(self, [](auto self) { return compile(self); });\n}\n\nstatic value wrap(value self) { return self; }\n\ntemplate<class Func>\nstatic closure wrap(Func func) {\n const symbol arg = \"__arg__\";\n return {{}, arg, [=](const auto& env) {\n return wrap(func(env.get(arg)));\n }};\n}\n\n\nstruct environment {\n table_type table;\n\n template<class T>\n void def(symbol name, T value) {\n table = table.set(name, wrap(value));\n }\n};\n\n\nvalue run(std::shared_ptr<environment> env, const ast::expr& self) {\n return compile(self)(env->table);\n}\n\n\nstd::shared_ptr<environment> make_environment() {\n auto res = std::make_shared<environment>();\n\n res->def(\"eq\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() == y.get<long>();\n };\n });\n\n res->def(\"add\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() + y.get<long>();\n };\n });\n\n res->def(\"sub\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() - y.get<long>();\n };\n });\n\n res->def(\"mul\", [=](value x) {\n return [=](value y) -> value {\n return x.get<long>() * y.get<long>();\n };\n });\n \n \n return res;\n}\n\n\n} \/\/ namespace eval\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- sanitizer_symbolizer_mac.cc ---------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is shared between various sanitizers' runtime libraries.\n\/\/\n\/\/ Implementation of Mac-specific \"atos\" symbolizer.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_platform.h\"\n#if SANITIZER_MAC\n\n#include \"sanitizer_allocator_internal.h\"\n#include \"sanitizer_mac.h\"\n#include \"sanitizer_symbolizer_mac.h\"\n\nnamespace __sanitizer {\n\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <util.h>\n\nbool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {\n Dl_info info;\n int result = dladdr((const void *)addr, &info);\n if (!result) return false;\n const char *demangled = DemangleCXXABI(info.dli_sname);\n stack->info.function = demangled ? internal_strdup(demangled) : nullptr;\n return true;\n}\n\nbool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) {\n Dl_info info;\n int result = dladdr((const void *)addr, &info);\n if (!result) return false;\n const char *demangled = DemangleCXXABI(info.dli_sname);\n datainfo->name = internal_strdup(demangled);\n datainfo->start = (uptr)info.dli_saddr;\n return true;\n}\n\nclass AtosSymbolizerProcess : public SymbolizerProcess {\n public:\n explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid)\n : SymbolizerProcess(path, \/*use_forkpty*\/ true) {\n \/\/ Put the string command line argument in the object so that it outlives\n \/\/ the call to GetArgV.\n internal_snprintf(pid_str_, sizeof(pid_str_), \"%d\", parent_pid);\n }\n\n private:\n bool ReachedEndOfOutput(const char *buffer, uptr length) const override {\n return (length >= 1 && buffer[length - 1] == '\\n');\n }\n\n void GetArgV(const char *path_to_binary,\n const char *(&argv)[kArgVMax]) const override {\n int i = 0;\n argv[i++] = path_to_binary;\n argv[i++] = \"-p\";\n argv[i++] = &pid_str_[0];\n if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) {\n \/\/ On Mavericks atos prints a deprecation warning which we suppress by\n \/\/ passing -d. The warning isn't present on other OSX versions, even the\n \/\/ newer ones.\n argv[i++] = \"-d\";\n }\n argv[i++] = nullptr;\n }\n\n char pid_str_[16];\n};\n\nstatic const char *kAtosErrorMessages[] = {\n \"atos cannot examine process\",\n \"unable to get permission to examine process\",\n \"An admin user name and password is required\",\n \"could not load inserted library\",\n \"architecture mismatch between analysis process\",\n};\n\nstatic bool IsAtosErrorMessage(const char *str) {\n for (uptr i = 0; i < ARRAY_SIZE(kAtosErrorMessages); i++) {\n if (internal_strstr(str, kAtosErrorMessages[i])) {\n return true;\n }\n }\n return false;\n}\n\nstatic bool ParseCommandOutput(const char *str, uptr addr, char **out_name,\n char **out_module, char **out_file, uptr *line,\n uptr *start_address) {\n \/\/ Trim ending newlines.\n char *trim;\n ExtractTokenUpToDelimiter(str, \"\\n\", &trim);\n\n \/\/ The line from `atos` is in one of these formats:\n \/\/ myfunction (in library.dylib) (sourcefile.c:17)\n \/\/ myfunction (in library.dylib) + 0x1fe\n \/\/ myfunction (in library.dylib) + 15\n \/\/ 0xdeadbeef (in library.dylib) + 0x1fe\n \/\/ 0xdeadbeef (in library.dylib) + 15\n \/\/ 0xdeadbeef (in library.dylib)\n \/\/ 0xdeadbeef\n\n if (IsAtosErrorMessage(trim)) {\n Report(\"atos returned an error: %s\\n\", trim);\n InternalFree(trim);\n return false;\n }\n\n const char *rest = trim;\n char *symbol_name;\n rest = ExtractTokenUpToDelimiter(rest, \" (in \", &symbol_name);\n if (internal_strncmp(symbol_name, \"0x\", 2) != 0)\n *out_name = symbol_name;\n else\n InternalFree(symbol_name);\n rest = ExtractTokenUpToDelimiter(rest, \") \", out_module);\n\n if (rest[0] == '(') {\n if (out_file) {\n rest++;\n rest = ExtractTokenUpToDelimiter(rest, \":\", out_file);\n char *extracted_line_number;\n rest = ExtractTokenUpToDelimiter(rest, \")\", &extracted_line_number);\n if (line) *line = (uptr)internal_atoll(extracted_line_number);\n InternalFree(extracted_line_number);\n }\n } else if (rest[0] == '+') {\n rest += 2;\n uptr offset = internal_atoll(rest);\n if (start_address) *start_address = addr - offset;\n }\n\n InternalFree(trim);\n return true;\n}\n\nAtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator)\n : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {}\n\nbool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {\n if (!process_) return false;\n char command[32];\n internal_snprintf(command, sizeof(command), \"0x%zx\\n\", addr);\n const char *buf = process_->SendCommand(command);\n if (!buf) return false;\n uptr line;\n if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module,\n &stack->info.file, &line, nullptr)) {\n process_ = nullptr;\n return false;\n }\n stack->info.line = (int)line;\n return true;\n}\n\nbool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {\n if (!process_) return false;\n char command[32];\n internal_snprintf(command, sizeof(command), \"0x%zx\\n\", addr);\n const char *buf = process_->SendCommand(command);\n if (!buf) return false;\n if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr,\n nullptr, &info->start)) {\n process_ = nullptr;\n return false;\n }\n return true;\n}\n\n} \/\/ namespace __sanitizer\n\n#endif \/\/ SANITIZER_MAC\n<commit_msg>[sanitizer] Detect an invalid answer in AtosSymbolizer<commit_after>\/\/===-- sanitizer_symbolizer_mac.cc ---------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is shared between various sanitizers' runtime libraries.\n\/\/\n\/\/ Implementation of Mac-specific \"atos\" symbolizer.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_platform.h\"\n#if SANITIZER_MAC\n\n#include \"sanitizer_allocator_internal.h\"\n#include \"sanitizer_mac.h\"\n#include \"sanitizer_symbolizer_mac.h\"\n\nnamespace __sanitizer {\n\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <util.h>\n\nbool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {\n Dl_info info;\n int result = dladdr((const void *)addr, &info);\n if (!result) return false;\n const char *demangled = DemangleCXXABI(info.dli_sname);\n stack->info.function = demangled ? internal_strdup(demangled) : nullptr;\n return true;\n}\n\nbool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) {\n Dl_info info;\n int result = dladdr((const void *)addr, &info);\n if (!result) return false;\n const char *demangled = DemangleCXXABI(info.dli_sname);\n datainfo->name = internal_strdup(demangled);\n datainfo->start = (uptr)info.dli_saddr;\n return true;\n}\n\nclass AtosSymbolizerProcess : public SymbolizerProcess {\n public:\n explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid)\n : SymbolizerProcess(path, \/*use_forkpty*\/ true) {\n \/\/ Put the string command line argument in the object so that it outlives\n \/\/ the call to GetArgV.\n internal_snprintf(pid_str_, sizeof(pid_str_), \"%d\", parent_pid);\n }\n\n private:\n bool ReachedEndOfOutput(const char *buffer, uptr length) const override {\n return (length >= 1 && buffer[length - 1] == '\\n');\n }\n\n void GetArgV(const char *path_to_binary,\n const char *(&argv)[kArgVMax]) const override {\n int i = 0;\n argv[i++] = path_to_binary;\n argv[i++] = \"-p\";\n argv[i++] = &pid_str_[0];\n if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) {\n \/\/ On Mavericks atos prints a deprecation warning which we suppress by\n \/\/ passing -d. The warning isn't present on other OSX versions, even the\n \/\/ newer ones.\n argv[i++] = \"-d\";\n }\n argv[i++] = nullptr;\n }\n\n char pid_str_[16];\n};\n\nstatic const char *kAtosErrorMessages[] = {\n \"atos cannot examine process\",\n \"unable to get permission to examine process\",\n \"An admin user name and password is required\",\n \"could not load inserted library\",\n \"architecture mismatch between analysis process\",\n};\n\nstatic bool IsAtosErrorMessage(const char *str) {\n for (uptr i = 0; i < ARRAY_SIZE(kAtosErrorMessages); i++) {\n if (internal_strstr(str, kAtosErrorMessages[i])) {\n return true;\n }\n }\n return false;\n}\n\nstatic bool ParseCommandOutput(const char *str, uptr addr, char **out_name,\n char **out_module, char **out_file, uptr *line,\n uptr *start_address) {\n \/\/ Trim ending newlines.\n char *trim;\n ExtractTokenUpToDelimiter(str, \"\\n\", &trim);\n\n \/\/ The line from `atos` is in one of these formats:\n \/\/ myfunction (in library.dylib) (sourcefile.c:17)\n \/\/ myfunction (in library.dylib) + 0x1fe\n \/\/ myfunction (in library.dylib) + 15\n \/\/ 0xdeadbeef (in library.dylib) + 0x1fe\n \/\/ 0xdeadbeef (in library.dylib) + 15\n \/\/ 0xdeadbeef (in library.dylib)\n \/\/ 0xdeadbeef\n\n if (IsAtosErrorMessage(trim)) {\n Report(\"atos returned an error: %s\\n\", trim);\n InternalFree(trim);\n return false;\n }\n\n const char *rest = trim;\n char *symbol_name;\n rest = ExtractTokenUpToDelimiter(rest, \" (in \", &symbol_name);\n if (rest[0] == '\\0') {\n InternalFree(symbol_name);\n InternalFree(trim);\n return false;\n }\n\n if (internal_strncmp(symbol_name, \"0x\", 2) != 0)\n *out_name = symbol_name;\n else\n InternalFree(symbol_name);\n rest = ExtractTokenUpToDelimiter(rest, \") \", out_module);\n\n if (rest[0] == '(') {\n if (out_file) {\n rest++;\n rest = ExtractTokenUpToDelimiter(rest, \":\", out_file);\n char *extracted_line_number;\n rest = ExtractTokenUpToDelimiter(rest, \")\", &extracted_line_number);\n if (line) *line = (uptr)internal_atoll(extracted_line_number);\n InternalFree(extracted_line_number);\n }\n } else if (rest[0] == '+') {\n rest += 2;\n uptr offset = internal_atoll(rest);\n if (start_address) *start_address = addr - offset;\n }\n\n InternalFree(trim);\n return true;\n}\n\nAtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator)\n : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {}\n\nbool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {\n if (!process_) return false;\n char command[32];\n internal_snprintf(command, sizeof(command), \"0x%zx\\n\", addr);\n const char *buf = process_->SendCommand(command);\n if (!buf) return false;\n uptr line;\n if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module,\n &stack->info.file, &line, nullptr)) {\n process_ = nullptr;\n return false;\n }\n stack->info.line = (int)line;\n return true;\n}\n\nbool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {\n if (!process_) return false;\n char command[32];\n internal_snprintf(command, sizeof(command), \"0x%zx\\n\", addr);\n const char *buf = process_->SendCommand(command);\n if (!buf) return false;\n if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr,\n nullptr, &info->start)) {\n process_ = nullptr;\n return false;\n }\n return true;\n}\n\n} \/\/ namespace __sanitizer\n\n#endif \/\/ SANITIZER_MAC\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <list>\n#include <string>\n#include <ctime>\n#include \"jsoncpp\/json.h\"\n\nusing namespace std;\n\nconst int MAX_N = 25;\nconst int dx[4] = {-1, 0, 1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\nbool invalid[MAX_N][MAX_N];\nint n, m;\n\nstruct Point {\n\tint x, y;\n\tPoint(const int &_x, const int &_y)\n\t\t: x(_x), y(_y)\n\t{}\n};\n\nlist<Point> snake[2]; \/\/ 0ʾԼߣ1ʾԷ\nint possibleDire[10];\nint posCount;\n\nbool whetherGrow(int num) \/\/غǷ\n{\n\tif (num <= 9) return true;\n\tif ((num - 9) % 3 == 0) return true;\n\treturn false;\n}\n\nvoid deleteEnd(int id) \/\/ɾβ\n{\n\tsnake[id].pop_back();\n}\n\nvoid move(int id, int dire, int num) \/\/Ϊid߳direƶһ\n{\n\tPoint p = *(snake[id].begin());\n\tint x = p.x + dx[dire];\n\tint y = p.y + dy[dire];\n\tsnake[id].push_front(Point(x, y));\n\tif (!whetherGrow(num))\n\t\tdeleteEnd(id);\n}\nvoid outputSnakeBody(int id) \/\/\n{\n\tcout << \"Snake No.\" << id << endl;\n\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter)\n\t\tcout << iter->x << \" \" << iter->y << endl;\n\tcout << endl;\n}\n\nbool isInBody(int x, int y) \/\/ж(x,y)λǷ\n{\n\tfor (int id = 0; id <= 1; id++)\n\t\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter)\n\t\t\tif (x == iter->x && y == iter->y)\n\t\t\t\treturn true;\n\treturn false;\n}\n\nbool validDirection(int id, int k) \/\/жϵǰƶһǷϷ\n{\n\tPoint p = *(snake[id].begin());\n\tint x = p.x + dx[k];\n\tint y = p.y + dy[k];\n\tif (x > n || y > m || x < 1 || y < 1) return false;\n\tif (invalid[x][y]) return false;\n\tif (isInBody(x, y)) return false;\n\treturn true;\n}\n\nint canPass[MAX_N][MAX_N] = {0};\n\nvoid MaintainMap()\n{\n\t\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfor (int j = 1; j <= m; ++j) {\n\t\t\tif (invalid[i][j]) {\n\t\t\t\tcanPass[i][j] = 100000;\n\t\t\t} else {\n\t\t\t\tcanPass[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int id = 0; id <= 1; id++) {\n\t\tint len = 1;\n\t\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter, ++len) {\n\t\t\tcanPass[iter->x][iter->y] = len;\n\t\t}\n\t}\n}\n\nint BFS(const int &sX, const int &sY)\n{\n\tbool vis[MAX_N][MAX_N] = {0};\n\tvector<Point> que;\n\tque.push_back(Point(sX, sY));\n\tvis[sX][sY] = true;\n\tfor (int i = 0; i < que.size(); ++i) {\n\t\tint uX = que[i].x;\n\t\tint uY = que[i].y;\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tint tX = uX + dx[i];\n\t\t\tint tY = uY + dy[i];\n\t\t\tif (tX > n || tY > m || tX < 1 || tY < 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (canPass[tX][tY]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!vis[tX][tY]) {\n\t\t\t\tvis[tX][tY] = true;\n\t\t\t\tque.push_back(Point(tX, tY));\n\t\t\t}\n\t\t}\n\t}\n\treturn que.size();\n}\n\nint CurHeadDirection(int id)\n{\n\tlist<Point>::iterator iter = snake[id].begin();\n\tPoint head = *iter++;\n\tPoint next = *iter;\n\tif (head.x == next.x) {\n\t\tif (head.y == next.y + 1) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn 3;\n\t\t}\n\t} else {\n\t\tif (head.x == next.y + 1) {\n\t\t\treturn 2;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n}\n\nint MakeDecision(Json::Value &ret)\n{\n\tMaintainMap();\n\tvector<int> consider;\n\tint bestCnt = 0;\n\tint headX = snake[0].begin()->x;\n\tint headY = snake[0].begin()->y;\n\tfor (int dir = 0; dir < 4; ++dir) {\n\t\tif (validDirection(0, dir)) {\n\t\t\tint sX = headX + dx[dir];\n\t\t\tint sY = headY + dy[dir];\n\t\t\tint result = BFS(sX, sY);\n\t\t\tret[\"response\"][\"debug\"][char(dir + '0')][\"result\"] = result;\n\t\t\tif (bestCnt < result) {\n\t\t\t\tconsider.clear();\n\t\t\t\tconsider.push_back(dir);\n\t\t\t\tbestCnt = result;\n\t\t\t} else if (bestCnt == result) {\n\t\t\t\tconsider.push_back(dir);\n\t\t\t}\n\t\t}\n\t}\n\tint cur = CurHeadDirection(0);\n\tif (consider.size() > 1) {\n\t\tfor (int i = 0; i < consider.size(); ++i) {\n\t\t\tif (consider[i] == cur) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn consider[i];\n\t\t}\n\t}\n\treturn consider.front();\n}\n\nint main()\n{\n\tmemset(invalid, 0, sizeof(invalid));\n\tstring str;\n\tstring temp;\n\twhile (getline(cin, temp))\n\t\tstr += temp;\n\n\tJson::Reader reader;\n\tJson::Value input;\n\treader.parse(str, input);\n\n\tn = input[\"requests\"][(Json::Value::UInt) 0][\"height\"].asInt(); \/\/̸߶\n\tm = input[\"requests\"][(Json::Value::UInt) 0][\"width\"].asInt(); \/\/̿\n\n\tint x = input[\"requests\"][(Json::Value::UInt) 0][\"x\"].asInt(); \/\/߳ʼϢ\n\tif (x == 1) {\n\t\tsnake[0].push_front(Point(1, 1));\n\t\tsnake[1].push_front(Point(n, m));\n\t} else {\n\t\tsnake[1].push_front(Point(1, 1));\n\t\tsnake[0].push_front(Point(n, m));\n\t}\n\t\/\/ͼеϰ\n\tint obsCount = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"].size();\n\n\tfor (int i = 0; i < obsCount; i++) {\n\t\tint ox = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"][(Json::Value::UInt) i][\"x\"].asInt();\n\t\tint oy = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"][(Json::Value::UInt) i][\"y\"].asInt();\n\t\tinvalid[ox][oy] = 1;\n\t}\n\n\t\/\/ʷϢֳָ\n\tint total = input[\"responses\"].size();\n\n\tint dire;\n\tfor (int i = 0; i < total; i++) {\n\t\tdire = input[\"responses\"][i][\"direction\"].asInt();\n\t\tmove(0, dire, i);\n\n\t\tdire = input[\"requests\"][i + 1][\"direction\"].asInt();\n\t\tmove(1, dire, i);\n\t}\n\n\tif (!whetherGrow(total)) \/\/ غ\n\t{\n\t\tdeleteEnd(0);\n\t\tdeleteEnd(1);\n\t}\n\n\tJson::Value ret;\n\tret[\"response\"][\"direction\"] = MakeDecision(ret);\n\n\tJson::FastWriter writer;\n\tcout << writer.write(ret) << endl;\n\n\treturn 0;\n}<commit_msg>use a stupid method to make decision<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <sstream>\n#include <list>\n#include <queue>\n#include <string>\n#include <ctime>\n#include \"jsoncpp\/json.h\"\n\nusing namespace std;\n\nconst int MAX_N = 25;\nconst int dx[4] = {-1, 0, 1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\nbool invalid[MAX_N][MAX_N];\nint n, m;\n\nstruct Point {\n\tint x, y;\n\tPoint(const int &_x, const int &_y)\n\t\t: x(_x), y(_y)\n\t{}\n};\n\nlist<Point> snake[2]; \/\/ 0ʾԼߣ1ʾԷ\nint possibleDire[10];\nint posCount;\n\nbool whetherGrow(int num) \/\/غǷ\n{\n\tif (num <= 9) return true;\n\tif ((num - 9) % 3 == 0) return true;\n\treturn false;\n}\n\nvoid deleteEnd(int id) \/\/ɾβ\n{\n\tsnake[id].pop_back();\n}\n\nvoid move(int id, int dire, int num) \/\/Ϊid߳direƶһ\n{\n\tPoint p = *(snake[id].begin());\n\tint x = p.x + dx[dire];\n\tint y = p.y + dy[dire];\n\tsnake[id].push_front(Point(x, y));\n\tif (!whetherGrow(num))\n\t\tdeleteEnd(id);\n}\nvoid outputSnakeBody(int id) \/\/\n{\n\tcout << \"Snake No.\" << id << endl;\n\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter)\n\t\tcout << iter->x << \" \" << iter->y << endl;\n\tcout << endl;\n}\n\nbool isInBody(int x, int y) \/\/ж(x,y)λǷ\n{\n\tfor (int id = 0; id <= 1; id++)\n\t\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter)\n\t\t\tif (x == iter->x && y == iter->y)\n\t\t\t\treturn true;\n\treturn false;\n}\n\nbool validDirection(int id, int k) \/\/жϵǰƶһǷϷ\n{\n\tPoint p = *(snake[id].begin());\n\tint x = p.x + dx[k];\n\tint y = p.y + dy[k];\n\tif (x > n || y > m || x < 1 || y < 1) return false;\n\tif (invalid[x][y]) return false;\n\tif (isInBody(x, y)) return false;\n\treturn true;\n}\n\nint canPass[MAX_N][MAX_N] = {0};\n\nvoid MaintainMap()\n{\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfor (int j = 1; j <= m; ++j) {\n\t\t\tif (invalid[i][j]) {\n\t\t\t\tcanPass[i][j] = 100000;\n\t\t\t} else {\n\t\t\t\tcanPass[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int id = 0; id <= 1; id++) {\n\t\tint len = 1;\n\t\tfor (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) {\n\t\t\tcanPass[iter->x][iter->y] = len++;\n\t\t}\n\t}\n}\n\nint BFS(const int &sX, const int &sY)\n{\n\tbool vis[MAX_N][MAX_N] = {0};\n\tqueue<Point> que;\n\tque.push(Point(sX, sY));\n\tvis[sX][sY] = true;\n\tint cnt = 1;\n\twhile (!que.empty()) {\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tint tX = que.front().x + dx[i];\n\t\t\tint tY = que.front().y + dy[i];\n\t\t\tif (tX < 1 || tY < 1 || tX > n || tY > m || canPass[tX][tY] > 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!vis[tX][tY]) {\n\t\t\t\tvis[tX][tY] = true;\n\t\t\t\t++cnt;\n\t\t\t\tque.push(Point(tX, tY));\n\t\t\t}\n\t\t}\n\t\tque.pop();\n\t}\n\treturn cnt;\n}\n\nint CurHeadDirection(int id)\n{\n\tlist<Point>::iterator iter = snake[id].begin();\n\tPoint head = *iter++;\n\tPoint next = *iter;\n\tif (head.x == next.x) {\n\t\tif (head.y == next.y + 1) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn 3;\n\t\t}\n\t} else {\n\t\tif (head.x == next.y + 1) {\n\t\t\treturn 2;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n}\n\nint MakeDecision(Json::Value &ret)\n{\n\tMaintainMap();\n\tvector<int> consider;\n\tint bestCnt = 0;\n\tint headX = snake[0].begin()->x;\n\tint headY = snake[0].begin()->y;\n\tint cnt = 0;\n\tfor (int dir = 0; dir < 4; ++dir) {\n\t\tif (validDirection(0, dir)) {\n\t\t\tint sX = headX + dx[dir];\n\t\t\tint sY = headY + dy[dir];\n\t\t\tint result = BFS(sX, sY);\n\t\t\tostringstream oss;\n\t\t\toss << \"BFS at (\" << sX << \",\" << sY << \") with empty unit \" << result;\n\t\t\tret[\"response\"][\"debug\"][cnt++] = oss.str().c_str();\n\t\t\tif (bestCnt < result) {\n\t\t\t\tconsider.clear();\n\t\t\t\tconsider.push_back(dir);\n\t\t\t\tbestCnt = result;\n\t\t\t} else if (bestCnt == result) {\n\t\t\t\tconsider.push_back(dir);\n\t\t\t}\n\t\t}\n\t}\n\tsrand((unsigned)time(NULL));\n\treturn consider[rand() % consider.size()];\n}\n\nint main()\n{\n\tmemset(invalid, 0, sizeof(invalid));\n\tstring str;\n\tstring temp;\n\twhile (getline(cin, temp))\n\t\tstr += temp;\n\n\tJson::Reader reader;\n\tJson::Value input;\n\treader.parse(str, input);\n\n\tn = input[\"requests\"][(Json::Value::UInt) 0][\"height\"].asInt(); \/\/̸߶\n\tm = input[\"requests\"][(Json::Value::UInt) 0][\"width\"].asInt(); \/\/̿\n\n\tint x = input[\"requests\"][(Json::Value::UInt) 0][\"x\"].asInt(); \/\/߳ʼϢ\n\tif (x == 1) {\n\t\tsnake[0].push_front(Point(1, 1));\n\t\tsnake[1].push_front(Point(n, m));\n\t} else {\n\t\tsnake[1].push_front(Point(1, 1));\n\t\tsnake[0].push_front(Point(n, m));\n\t}\n\t\/\/ͼеϰ\n\tint obsCount = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"].size();\n\n\tfor (int i = 0; i < obsCount; i++) {\n\t\tint ox = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"][(Json::Value::UInt) i][\"x\"].asInt();\n\t\tint oy = input[\"requests\"][(Json::Value::UInt) 0][\"obstacle\"][(Json::Value::UInt) i][\"y\"].asInt();\n\t\tinvalid[ox][oy] = 1;\n\t}\n\n\t\/\/ʷϢֳָ\n\tint total = input[\"responses\"].size();\n\n\tint dire;\n\tfor (int i = 0; i < total; i++) {\n\t\tdire = input[\"responses\"][i][\"direction\"].asInt();\n\t\tmove(0, dire, i);\n\n\t\tdire = input[\"requests\"][i + 1][\"direction\"].asInt();\n\t\tmove(1, dire, i);\n\t}\n\n\tif (!whetherGrow(total)) \/\/ غ\n\t{\n\t\tdeleteEnd(0);\n\t\tdeleteEnd(1);\n\t}\n\n\tJson::Value ret;\n\tret[\"response\"][\"direction\"] = MakeDecision(ret);\n\n\tJson::FastWriter writer;\n\tcout << writer.write(ret) << endl;\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Renderer.cpp\n * BasicScreenObject_Test\n *\n * Created by Matthias Rohrbach 2 on 12.06.12.\n * Copyright 2012 rob & rose grafik. All rights reserved.\n *\n *\/\n\n#include \"Renderer.h\"\n\nRenderer::Renderer(){\n\tmyname\t\t\t=\"Renderer\";\n\tnextPickingName\t= 100;\n\tcursorsize\t\t= 10;\n\tmaxcursors\t\t= 20;\n\tcaptureincrement= 2;\n\tmapsampling\t\t= 2;\n\t\n\ttouchtomouse = true;\n\tmousetotouch = true;\n\tmousetouchid = -1;\n\t\n\tcurrentviewport\t= ofRectangle(0,0,0,0);\n\t\n\tbTuioSetup\t\t\t= false;\n\tbColorPickerSetup\t= false;\n\tisRenderer\t\t\t= true;\n\tdrawcursors\t\t\t= true;\n}\n\n\nRenderer::~Renderer(){\n\n}\n\n\nvoid Renderer::setup(){\n\t\n\tofAddListener(ofEvents().mousePressed, this, &Renderer::mousePressed);\n\tofAddListener(ofEvents().mouseDragged, this, &Renderer::mouseDragged);\n\tofAddListener(ofEvents().mouseReleased, this, &Renderer::mouseReleased);\n\t\n\tofAddListener(ofEvents().touchDown,this,&Renderer::tuioAdded);\n\tofAddListener(ofEvents().touchUp,this,&Renderer::tuioRemoved);\n\tofAddListener(ofEvents().touchMoved,this,&Renderer::tuioUpdated);\n}\n\n\nvoid Renderer::setupColorPicker(float _width, float _height, float _sampling, float _increment){\t\n\t\n\tBasicScreenObject::setSize(_width,_height);\n\tmapsampling\t\t\t= _sampling;\n\tcaptureincrement\t= _increment;\n\tmapscale\t\t\t= 1.0f\/(float)mapsampling;\n\t\n\tofFbo::Settings s;\n\t\n\ts.width\t\t\t\t= getWidth()\/mapsampling;\n\ts.height\t\t\t= getHeight()\/mapsampling;\n\ts.internalformat\t= GL_RGB;\n\ts.useDepth\t\t\t= true;\n\t\n\tpickingmap.allocate(s );\n\tmaxbounds = ofRectangle ( 0 , 0 , pickingmap.getWidth()-1 , pickingmap.getHeight()-1 ) ;\n\tcamera.setupPerspective();\n\t\n\tbColorPickerSetup=true;\n}\n\n\nvoid Renderer::update(){\n\t\n\tTweener.update();\n\n\tif(bColorPickerSetup){\n\t\t\n\t\tbool waslighting = glIsEnabled(GL_LIGHTING);\n\t\tif(waslighting){\n\t\t\tglDisable(GL_LIGHTING);\n\t\t}\n\t\t\n\t\tif(ofGetFrameNum() % captureincrement==0){\n\t\t\tpickingmap.begin();\n\t\t\t\n\t\t\tofClear(0);\n\t\t\tofPushMatrix() ;\n\t\t\tofScale( mapscale , mapscale , mapscale) ;\t\t\n\t\t\tBasicScreenObject::drawForPicking();\t\n\t\t\tofPopMatrix();\n\t\t\t\n\t\t\tpickingmap.end();\t\t\n\t\t\tpickingmap.readToPixels(mapPixels);\n\t\t}\n\t\t\n\t\tif(waslighting){\n\t\t\tglEnable(GL_LIGHTING);\n\t\t}\n\t}\n}\n\nvoid Renderer::draw(){\n\t\n\tcurrentviewport = ofGetCurrentViewport();\n\tcamera.begin();\n\tBasicScreenObject::draw();\n\tcamera.end();\n\tif (drawcursors) drawCursors();\n}\n\n\nvoid Renderer::_draw(){\t\t\n\t\n}\n\nvoid Renderer::startTuio(int _port) {\n\tport = _port;\n\ttuio.connect(_port);\n\tbTuioSetup = true;\n}\n\n\nvoid Renderer::tuioAdded(ofTouchEventArgs & _cursor) {\t\n\t\n\tif (touchtomouse && mousetouchid==-1) {\n\t\tmousetouchid = _cursor.id;\n\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mousePressed, mouseEventArgs );\n\t\t\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_ADD);\n}\n\nvoid Renderer::tuioRemoved(ofTouchEventArgs & _cursor){\n\t\n\tif (touchtomouse && mousetouchid==_cursor.id) {\n\t\tmousetouchid = -1;\n\t\t\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mouseReleased , mouseEventArgs );\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_REMOVE);\n}\n\nvoid Renderer::tuioUpdated(ofTouchEventArgs & _cursor){\n\t\n\tif (touchtomouse && mousetouchid==_cursor.id) {\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mouseDragged, mouseEventArgs );\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_UPDATE);\n}\n\nvoid Renderer::mousePressed(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_ADD);\n\t\t}\n\t}\n}\n\nvoid Renderer::mouseReleased(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_REMOVE);\n\t\t}\n\t}\n}\n\nvoid Renderer::mouseDragged(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_UPDATE);\n\t\t}\n\t}\n}\n\n\nvoid Renderer::notifyObjects(float _screenx, float _screeny,int _fingerid, int _action){\n\t\n\tmtRay ray;\n\tray.pos = camera.screenToWorld(ofVec3f(_screenx,_screeny,-1),currentviewport);\n\tray.dir = camera.screenToWorld(ofVec3f(_screenx,_screeny,1), currentviewport)-ray.pos;\n\tray.screenpos.set(_screenx, _screeny);\n\t\n\t\n\tBasicInteractiveObject* overobj=(BasicInteractiveObject*)getObjectAt(_screenx, _screeny);\n\t\n\tfor(int i=0;i<pickingObjects.size();i++){\n\t\tBasicInteractiveObject* obj =(BasicInteractiveObject*) pickingObjects[i];\n\t\tif (obj != NULL && obj!=overobj) {\n\t\t\tswitch (_action) {\n\t\t\t\tcase (MT_ADD) : {\n\t\t\t\t\tobj->touchDownOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase (MT_UPDATE) : {\n\t\t\t\t\tobj->touchMovedOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase (MT_REMOVE) : {\n\t\t\t\t\tobj->touchUpOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(overobj!=NULL){\n\t\tswitch (_action) {\n\t\t\tcase (MT_ADD) : {\n\t\t\t\toverobj->touchDownOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase (MT_UPDATE) : {\n\t\t\t\toverobj->touchMovedOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase (MT_REMOVE) : {\n\t\t\t\toverobj->touchUpOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\t\n\t}\n\t\n\tlastinteraction=ofGetElapsedTimeMillis();\n}\n\n\n \nvoid Renderer::drawMap() {\n\tofSetColor(255, 255, 255);\n\tpickingmap.draw(0, 0,pickingmap.getWidth(),pickingmap.getHeight());\n}\n\nvoid Renderer::drawCursors(){\n\n\t\n\t\n\tofEnableAlphaBlending();\n\tglBlendFunc(GL_ONE, GL_ONE);\n\t\n\tif(bTuioSetup){\n\t\tstd::list<TuioCursor*> cursorList = tuio.client->getTuioCursors();\n\t\tstd::list<TuioCursor*>::iterator tit;\n\t\ttuio.client->lockCursorList();\n\t\t\n\t\tfor (tit = cursorList.begin(); tit != cursorList.end(); tit++) {\n\t\t\tTuioCursor * cur = (*tit);\n\t\t\tglColor3f(0.1,0.1, 0.1);\n\t\t\tfor(int i = 0; i < 5; i++){\n\t\t\t\tofEllipse(cur->getX()*ofGetWidth(),\n\t\t\t\t\t\t cur->getY()*ofGetHeight(),\n\t\t\t\t\t\t 20.0+i*i,\n\t\t\t\t\t\t 20.0+i*i);\n\t\t\t}\n\t\t}\n\t\ttuio.client->unlockCursorList();\n\t}\n\t\n\tif (mousetotouch) {\n\t\tif (ofGetMousePressed()) {\n\t\t\tglColor3f(0.1,0.1, 0.1);\n\t\t\tfor(int i = 0; i < 5; i++){\n\t\t\t\tofEllipse(ofGetMouseX(),\n\t\t\t\t\t\t ofGetMouseY(),\n\t\t\t\t\t\t 20.0+i*i,\n\t\t\t\t\t\t 20.0+i*i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tglBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n}\n\nBasicScreenObject* Renderer::getObjectAt(float _screenx, float _screeny){\n\tint fbox\t=_screenx\/mapsampling;\n\tint fboy\t=_screeny\/mapsampling;\n\tfbox\t\t= ofClamp(fbox, 0, maxbounds.width);\n\tfboy\t\t= ofClamp(fboy, 0, maxbounds.height);\n\t\n\tint index\t= (fbox + fboy * pickingmap.getWidth()) * 3 ;\n\t\n\tofColor\tfboc\t\t\t= ofColor( mapPixels[index] , mapPixels[index + 1] , mapPixels[index + 2] );\n\tGLint pickingName\t\t= colorToPickingName(fboc);\n\tBasicScreenObject* obj\t= NULL;\n\t\n\tif (pickingObjects.find(pickingName) != pickingObjects.end()) {\n\t\tobj = pickingObjects[pickingName];\n\t}\t\n\treturn obj;\t\n}\n\nGLuint Renderer::getNextPickingName(BasicInteractiveObject* _object) {\n\tGLuint np = ++nextPickingName;\n\tpickingObjects[np] = _object;\n\treturn np;\n}\n\nlong Renderer::lastInteractionMillis(){\n\treturn lastinteraction;\n}\n\nvoid Renderer::isDrawCursors(bool _drawCursors) {\n\tdrawcursors = _drawCursors;\n}\n\n<commit_msg>some performance tests in renderer…<commit_after>\/*\n * Renderer.cpp\n * BasicScreenObject_Test\n *\n * Created by Matthias Rohrbach 2 on 12.06.12.\n * Copyright 2012 rob & rose grafik. All rights reserved.\n *\n *\/\n\n#include \"Renderer.h\"\n\nRenderer::Renderer(){\n\tmyname\t\t\t=\"Renderer\";\n\tnextPickingName\t= 100;\n\tcursorsize\t\t= 10;\n\tmaxcursors\t\t= 20;\n\tcaptureincrement= 2;\n\tmapsampling\t\t= 2;\n\t\n\ttouchtomouse = true;\n\tmousetotouch = true;\n\tmousetouchid = -1;\n\t\n\tcurrentviewport\t= ofRectangle(0,0,0,0);\n\t\n\tbTuioSetup\t\t\t= false;\n\tbColorPickerSetup\t= false;\n\tisRenderer\t\t\t= true;\n\tdrawcursors\t\t\t= true;\n}\n\n\nRenderer::~Renderer(){\n\n}\n\n\nvoid Renderer::setup(){\n\t\n\tofAddListener(ofEvents().mousePressed, this, &Renderer::mousePressed);\n\tofAddListener(ofEvents().mouseDragged, this, &Renderer::mouseDragged);\n\tofAddListener(ofEvents().mouseReleased, this, &Renderer::mouseReleased);\n\t\n\tofAddListener(ofEvents().touchDown,this,&Renderer::tuioAdded);\n\tofAddListener(ofEvents().touchUp,this,&Renderer::tuioRemoved);\n\tofAddListener(ofEvents().touchMoved,this,&Renderer::tuioUpdated);\n}\n\n\nvoid Renderer::setupColorPicker(float _width, float _height, float _sampling, float _increment){\t\n\t\n\tBasicScreenObject::setSize(_width,_height);\n\tmapsampling\t\t\t= _sampling;\n\tcaptureincrement\t= _increment;\n\tmapscale\t\t\t= 1.0f\/(float)mapsampling;\n\t\n\tofFbo::Settings s;\n\t\n\ts.width\t\t\t\t= getWidth() \/ mapsampling;\n\ts.height\t\t\t= getHeight() \/ mapsampling;\n\t\/\/s.internalformat\t= GL_LUMINANCE32F_ARB;\n\ts.internalformat\t= GL_RGB; \/\/ would be much faster using GL_LUMINANCE or GL_LUMINANCE32F_ARB (32bit resolution should be enough);\n\ts.useDepth\t\t\t= true;\n\t\n\tpickingmap.allocate(s );\n\tmaxbounds = ofRectangle ( 0 , 0 , pickingmap.getWidth()-1 , pickingmap.getHeight()-1 ) ;\n\tcamera.setupPerspective();\n\t\n\tbColorPickerSetup=true;\n}\n\n\nvoid Renderer::update(){\n\t\/\/int startTime = ofGetElapsedTimeMillis();\n\t\n\tTweener.update();\n\n\tif(bColorPickerSetup){\n\t\t\n\t\tbool waslighting = glIsEnabled(GL_LIGHTING);\n\t\tif(waslighting){\n\t\t\tglDisable(GL_LIGHTING);\n\t\t}\n\t\t\n\t\tif(ofGetFrameNum() % captureincrement==0){\n\t\t\tpickingmap.begin();\n\t\t\t\n\t\t\tofClear(0);\n\t\t\tofPushMatrix() ;\n\t\t\tofScale( mapscale , mapscale , mapscale) ;\t\t\n\t\t\tBasicScreenObject::drawForPicking();\t\n\t\t\tofPopMatrix();\n\t\t\t\n\t\t\tpickingmap.end();\t\t\n\t\t\tpickingmap.readToPixels(mapPixels);\t\t\t\t\t\/\/ < takes 20ms for rgb fbo. 1ms for GL_LUMINANCE\n\t\t\t\/\/ofLog(OF_LOG_NOTICE, ofToString(mapPixels.size()));\n\t\t}\n\t\t\n\t\tif(waslighting){\n\t\t\tglEnable(GL_LIGHTING);\n\t\t}\n\t}\n\n\t\/\/ofLog(OF_LOG_NOTICE, \"update: \" + ofToString(ofGetElapsedTimeMillis()-startTime));\n}\n\nvoid Renderer::draw(){\n\t\n\t\/\/int startTime = ofGetElapsedTimeMillis();\n\t\n\tcurrentviewport = ofGetCurrentViewport();\n\tcamera.begin();\n\tBasicScreenObject::draw();\n\tcamera.end();\n\tif (drawcursors) drawCursors();\n\t\n\t\/\/ofLog(OF_LOG_NOTICE, \"draw: \" + ofToString(ofGetElapsedTimeMillis()-startTime));\n}\n\n\nvoid Renderer::_draw(){\t\t\n\t\n}\n\nvoid Renderer::startTuio(int _port) {\n\tport = _port;\n\ttuio.connect(_port);\n\tbTuioSetup = true;\n}\n\n\nvoid Renderer::tuioAdded(ofTouchEventArgs & _cursor) {\t\n\t\n\tif (touchtomouse && mousetouchid==-1) {\n\t\tmousetouchid = _cursor.id;\n\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mousePressed, mouseEventArgs );\n\t\t\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_ADD);\n}\n\nvoid Renderer::tuioRemoved(ofTouchEventArgs & _cursor){\n\t\n\tif (touchtomouse && mousetouchid==_cursor.id) {\n\t\tmousetouchid = -1;\n\t\t\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mouseReleased , mouseEventArgs );\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_REMOVE);\n}\n\nvoid Renderer::tuioUpdated(ofTouchEventArgs & _cursor){\n\t\n\tif (touchtomouse && mousetouchid==_cursor.id) {\n\t\tstatic ofMouseEventArgs mouseEventArgs;\n\t\tmouseEventArgs.x = _cursor.x*ofGetWidth();\n\t\tmouseEventArgs.y = _cursor.y*ofGetHeight();\n\t\tmouseEventArgs.button = 1;\n\t\tlastfakemouseevent = &mouseEventArgs;\n\t\tofNotifyEvent( ofEvents().mouseDragged, mouseEventArgs );\n\t}\n\t\n\tnotifyObjects(_cursor.x*ofGetWidth(), _cursor.y*ofGetHeight(), _cursor.id, MT_UPDATE);\n}\n\nvoid Renderer::mousePressed(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_ADD);\n\t\t}\n\t}\n}\n\nvoid Renderer::mouseReleased(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_REMOVE);\n\t\t}\n\t}\n}\n\nvoid Renderer::mouseDragged(ofMouseEventArgs& _cursor){\n\tif (mousetotouch) {\n\t\t\/\/ ignore this mouse-event, if it was created by emulating a mouse-event from a touch\n\t\tif (lastfakemouseevent != &_cursor) {\n\t\t\tnotifyObjects(_cursor.x, _cursor.y, -1, MT_UPDATE);\n\t\t}\n\t}\n}\n\n\nvoid Renderer::notifyObjects(float _screenx, float _screeny,int _fingerid, int _action){\n\t\n\tmtRay ray;\n\tray.pos = camera.screenToWorld(ofVec3f(_screenx,_screeny,-1),currentviewport);\n\tray.dir = camera.screenToWorld(ofVec3f(_screenx,_screeny,1), currentviewport)-ray.pos;\n\tray.screenpos.set(_screenx, _screeny);\n\t\n\t\n\tBasicInteractiveObject* overobj=(BasicInteractiveObject*)getObjectAt(_screenx, _screeny);\n\t\n\tfor(int i=0;i<pickingObjects.size();i++){\n\t\tBasicInteractiveObject* obj =(BasicInteractiveObject*) pickingObjects[i];\n\t\tif (obj != NULL && obj!=overobj) {\n\t\t\tswitch (_action) {\n\t\t\t\tcase (MT_ADD) : {\n\t\t\t\t\tobj->touchDownOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase (MT_UPDATE) : {\n\t\t\t\t\tobj->touchMovedOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase (MT_REMOVE) : {\n\t\t\t\t\tobj->touchUpOutside(ray,_fingerid);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(overobj!=NULL){\n\t\tswitch (_action) {\n\t\t\tcase (MT_ADD) : {\n\t\t\t\toverobj->touchDownOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase (MT_UPDATE) : {\n\t\t\t\toverobj->touchMovedOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase (MT_REMOVE) : {\n\t\t\t\toverobj->touchUpOnMe(ray,_fingerid);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\t\n\t}\n\t\n\tlastinteraction=ofGetElapsedTimeMillis();\n}\n\n\n \nvoid Renderer::drawMap() {\n\tofSetColor(255, 255, 255);\n\tpickingmap.draw(0, 0,pickingmap.getWidth(),pickingmap.getHeight());\n}\n\nvoid Renderer::drawCursors(){\n\n\t\n\t\n\tofEnableAlphaBlending();\n\tglBlendFunc(GL_ONE, GL_ONE);\n\t\n\tif(bTuioSetup){\n\t\tstd::list<TuioCursor*> cursorList = tuio.client->getTuioCursors();\n\t\tstd::list<TuioCursor*>::iterator tit;\n\t\ttuio.client->lockCursorList();\n\t\t\n\t\tfor (tit = cursorList.begin(); tit != cursorList.end(); tit++) {\n\t\t\tTuioCursor * cur = (*tit);\n\t\t\tglColor3f(0.1,0.1, 0.1);\n\t\t\tfor(int i = 0; i < 5; i++){\n\t\t\t\tofEllipse(cur->getX()*ofGetWidth(),\n\t\t\t\t\t\t cur->getY()*ofGetHeight(),\n\t\t\t\t\t\t 20.0+i*i,\n\t\t\t\t\t\t 20.0+i*i);\n\t\t\t}\n\t\t}\n\t\ttuio.client->unlockCursorList();\n\t}\n\t\n\tif (mousetotouch) {\n\t\tif (ofGetMousePressed()) {\n\t\t\tglColor3f(0.1,0.1, 0.1);\n\t\t\tfor(int i = 0; i < 5; i++){\n\t\t\t\tofEllipse(ofGetMouseX(),\n\t\t\t\t\t\t ofGetMouseY(),\n\t\t\t\t\t\t 20.0+i*i,\n\t\t\t\t\t\t 20.0+i*i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tglBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n}\n\nBasicScreenObject* Renderer::getObjectAt(float _screenx, float _screeny){\n\tint fbox\t=_screenx\/mapsampling;\n\tint fboy\t=_screeny\/mapsampling;\n\tfbox\t\t= ofClamp(fbox, 0, maxbounds.width);\n\tfboy\t\t= ofClamp(fboy, 0, maxbounds.height);\n\t\n\tint index\t= (fbox + fboy * pickingmap.getWidth()) * 3 ;\n\t\/\/int index\t= (fbox + fboy * pickingmap.getWidth());\n\t\n\tofColor\tfboc\t\t\t= ofColor( mapPixels[index] , mapPixels[index + 1] , mapPixels[index + 2] );\n\t\/\/ofColor\tfboc\t\t\t= ofColor( mapPixels[index] , mapPixels[index] , mapPixels[index] );\n\tGLint pickingName\t\t= colorToPickingName(fboc);\n\tBasicScreenObject* obj\t= NULL;\n\t\n\tif (pickingObjects.find(pickingName) != pickingObjects.end()) {\n\t\tobj = pickingObjects[pickingName];\n\t}\t\n\treturn obj;\t\n}\n\nGLuint Renderer::getNextPickingName(BasicInteractiveObject* _object) {\n\tGLuint np = ++nextPickingName;\n\tpickingObjects[np] = _object;\n\treturn np;\n}\n\nlong Renderer::lastInteractionMillis(){\n\treturn lastinteraction;\n}\n\nvoid Renderer::isDrawCursors(bool _drawCursors) {\n\tdrawcursors = _drawCursors;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"logreader.h\"\n\n\nLogreader::Logreader(QString filename, QString address, quint16 port){\n if (address == \"127.0.0.1\") {\n this->address = new QHostAddress(QHostAddress::LocalHost);\n } else {\n this->address = new QHostAddress(address);\n }\n this->port = port;\n this->log = new QFile(filename);\n\n if (this->log->open(QIODevice::ReadOnly)) {\n qDebug() << \"File: \" << filename << \"successfuly opened.\" << \"\\n\";\n } else {\n qDebug() << \"Opening file\" << filename << \"failed.\" << \"\\n\";\n }\n}\n\nLogreader::Logreader(QString filename, QHostAddress address, quint16 port){\n this->address = &address;\n this->port = port;\n\n this->log = new QFile(filename);\n\n if (this->log->open(QIODevice::ReadOnly)) {\n qDebug() << \"File: \" << filename << \"successfuly opened.\" << \"\\n\";\n } else {\n qDebug() << \"Opening file\" << filename << \"failed.\" << \"\\n\";\n }\n}\n\nQString Logreader::getLine(){\n return this->line;\n}\n\nint Logreader::readAndTransmit(){\n QString fileLine;\n QString parsedFileLine;\n fileLine = readDataFromFile();\n parsedFileLine = parseData(fileLine);\n transmitData(parsedFileLine);\n qDebug() << parsedFileLine;\n counter++;\n if (counter==2){\n packetno ++;\n counter = 0;\n }\n if (packetno > 2){\n packetno = 0;\n }\n return 0;\n}\n\nQString Logreader::readDataFromFile(){\n QString fileLine;\n if ((log->isReadable()) && (!log->atEnd())){\n fileLine = this->log->readLine();\n } else if (!log->isReadable()) {\n qDebug() << \"File \" << this->filename << \" is not readable.\\n\";\n } else if (log->atEnd()) {\n log->seek(0);\n }\n return fileLine;\n}\n\nQString Logreader::parseData(QString fileLine){\n QList<QString> parsingData;\n QString parsedFileLine;\n QString processData;\n\n processData.clear();\n parsingData.clear();\n parsedFileLine.clear();\n\n foreach (QChar var, fileLine) {\n if ((var != ';')&& (var != '\\r')){\n processData.append(var);\n } else if ((var == ';')|| (var == '\\r')){\n parsingData.append(processData);\n processData.clear();\n }\n }\n\n \/\/ Chain for transmission assembly\n \/\/ TODO: Complete the parsed string and include a clause which will change the string to a status once in a while.\n if (!parsingData.isEmpty()) {\n switch (packetno){\n case 0:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"LAT\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(0));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(1));\n parsedFileLine.append(',');\n parsedFileLine.append(\"LON\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(2));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(3));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n case 1:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"VLC\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(5));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ENG\");\n parsedFileLine.append(\"LS\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"xxx\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACX\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(6));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACY\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(7));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACZ\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(8));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n case 2:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"HDG\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(4));\n parsedFileLine.append(',');\n parsedFileLine.append(\"HDT\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"xxx\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACP\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(9));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACW\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(10));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACR\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(11));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n default: parsedFileLine.append(\"error\");\n }\n }\n\n return parsedFileLine;\n}\n\nvoid Logreader::transmitData(QString inString){\n transmitter.writeDatagram(inString.toLatin1(), *this->address, port);\n}\n\nQString Logreader::checksum(QByteArray inData){\n QString table = \"0123456789ABCDEF\";\n char result[2];\n QString outChecksum;\n\n unsigned char checksum = 0x00;\n\n\n for (int i = 1; i < inData.length()-1; i++) {\n if (inData.at(i)=='*') {\n break;\n }\n checksum ^= (unsigned char) inData.at(i);\n }\n\n result[1] = table.at(checksum&0x0F).toLatin1();\n result[0] = table.at((checksum>>4)&0x0F).toLatin1();\n outChecksum.insert(0,result[0]);\n outChecksum.insert(1,result[1]);\n return outChecksum;\n}\n\nQString Logreader::checksum(QString inData){\n return checksum(inData.toLatin1());\n}\n<commit_msg>added parsing sentence for data with no fake log<commit_after>#include \"logreader.h\"\n\n\nLogreader::Logreader(QString filename, QString address, quint16 port){\n if (address == \"127.0.0.1\") {\n this->address = new QHostAddress(QHostAddress::LocalHost);\n } else {\n this->address = new QHostAddress(address);\n }\n this->port = port;\n this->log = new QFile(filename);\n\n if (this->log->open(QIODevice::ReadOnly)) {\n qDebug() << \"File: \" << filename << \"successfuly opened.\" << \"\\n\";\n } else {\n qDebug() << \"Opening file\" << filename << \"failed.\" << \"\\n\";\n }\n}\n\nLogreader::Logreader(QString filename, QHostAddress address, quint16 port){\n this->address = &address;\n this->port = port;\n\n this->log = new QFile(filename);\n\n if (this->log->open(QIODevice::ReadOnly)) {\n qDebug() << \"File: \" << filename << \"successfuly opened.\" << \"\\n\";\n } else {\n qDebug() << \"Opening file\" << filename << \"failed.\" << \"\\n\";\n }\n}\n\nQString Logreader::getLine(){\n return this->line;\n}\n\nint Logreader::readAndTransmit(){\n QString fileLine;\n QString parsedFileLine;\n fileLine = readDataFromFile();\n parsedFileLine = parseData(fileLine);\n transmitData(parsedFileLine);\n qDebug() << parsedFileLine;\n counter++;\n if (counter==2){\n packetno ++;\n counter = 0;\n }\n if (packetno > 2){\n packetno = 0;\n }\n return 0;\n}\n\nQString Logreader::readDataFromFile(){\n QString fileLine;\n if ((log->isReadable()) && (!log->atEnd())){\n fileLine = this->log->readLine();\n } else if (!log->isReadable()) {\n qDebug() << \"File \" << this->filename << \" is not readable.\\n\";\n } else if (log->atEnd()) {\n log->seek(0);\n }\n return fileLine;\n}\n\nQString Logreader::parseData(QString fileLine){\n QList<QString> parsingData;\n QString parsedFileLine;\n QString processData;\n\n processData.clear();\n parsingData.clear();\n parsedFileLine.clear();\n\n foreach (QChar var, fileLine) {\n if ((var != ';')&& (var != '\\r')){\n processData.append(var);\n } else if ((var == ';')|| (var == '\\r')){\n parsingData.append(processData);\n processData.clear();\n }\n }\n\n \/\/ Chain for transmission assembly\n \/\/ TODO: Complete the parsed string and include a clause which will change the string to a status once in a while.\n if (!parsingData.isEmpty()) {\n switch (packetno){\n case 0:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"LAT\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(0));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(1));\n parsedFileLine.append(',');\n parsedFileLine.append(\"LON\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(2));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(3));\n \/*parsedFileLine.append(\"LATDG\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(LATDEG));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(LATMINS));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(LATSEC));*\/\n \/\/code above has no fake log\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n case 1:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"VLC\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(5));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ENG\");\n parsedFileLine.append(\"LS\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"xxx\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACX\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(6));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACY\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(7));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACZ\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(8));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n case 2:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"HDG\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(4));\n parsedFileLine.append(',');\n parsedFileLine.append(\"HDT\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"xxx\");\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACP\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(9));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACW\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(10));\n parsedFileLine.append(',');\n parsedFileLine.append(\"ACR\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(11));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n \/*case 3:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"LDR\");\n parsedFileLine.append(',');\n for (int i = 1; i<17;i++){\n parsedFileLine.append(parsingData.at(i));\n }\n parsedFileLine.append(\"HP\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(PHDG));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(PHPTH));\n parsedFileLine.append(',');\n parsedFileLine.append(\"HPF\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(FREQ));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;\n case 4:parsedFileLine.append(\"$MSG,\");\n parsedFileLine.append(\"GPS\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(1\/0));\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(1\/0)));\n parsedFileLine.append(',');\n parsedFileLine.append(\"IMU\");\n parsedFileLine.append(',');\n parsedFileLine.append(parsingData.at(1\/0)));\n parsedFileLine.append('*');\n parsedFileLine.append(checksum(parsedFileLine));\n parsedFileLine.append('\\r');\n parsedFileLine.append('\\n'); break;*\/\n \/\/NO FAKE LOG\n\n default: parsedFileLine.append(\"error\");\n }\n }\n\n return parsedFileLine;\n}\n\nvoid Logreader::transmitData(QString inString){\n transmitter.writeDatagram(inString.toLatin1(), *this->address, port);\n}\n\nQString Logreader::checksum(QByteArray inData){\n QString table = \"0123456789ABCDEF\";\n char result[2];\n QString outChecksum;\n\n unsigned char checksum = 0x00;\n\n\n for (int i = 1; i < inData.length()-1; i++) {\n if (inData.at(i)=='*') {\n break;\n }\n checksum ^= (unsigned char) inData.at(i);\n }\n\n result[1] = table.at(checksum&0x0F).toLatin1();\n result[0] = table.at((checksum>>4)&0x0F).toLatin1();\n outChecksum.insert(0,result[0]);\n outChecksum.insert(1,result[1]);\n return outChecksum;\n}\n\nQString Logreader::checksum(QString inData){\n return checksum(inData.toLatin1());\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"FaceMapper.hpp\"\n#include \"Utilities.hpp\"\n#include \"opencv2\/calib3d.hpp\"\n#include \"opencv2\/highgui.hpp\"\n\n#include <cstdlib>\n\nusing namespace std;\nusing namespace cv;\n\nnamespace YerFace {\n\nFaceMapper::FaceMapper(FrameDerivatives *myFrameDerivatives, FaceTracker *myFaceTracker) {\n\tframeDerivatives = myFrameDerivatives;\n\tif(frameDerivatives == NULL) {\n\t\tthrow invalid_argument(\"frameDerivatives cannot be NULL\");\n\t}\n\tfaceTracker = myFaceTracker;\n\tif(faceTracker == NULL) {\n\t\tthrow invalid_argument(\"faceTracker cannot be NULL\");\n\t}\n\n\tmarkerSeparator = new MarkerSeparator(frameDerivatives, faceTracker);\n\n\tmarkerEyelidLeftTop = new MarkerTracker(EyelidLeftTop, this);\n\tmarkerEyelidRightTop = new MarkerTracker(EyelidRightTop, this);\n\tmarkerEyelidLeftBottom = new MarkerTracker(EyelidLeftBottom, this);\n\tmarkerEyelidRightBottom = new MarkerTracker(EyelidRightBottom, this);\n\n\tmarkerEyebrowLeftInner = new MarkerTracker(EyebrowLeftInner, this);\n\tmarkerEyebrowRightInner = new MarkerTracker(EyebrowRightInner, this);\n\tmarkerEyebrowLeftMiddle = new MarkerTracker(EyebrowLeftMiddle, this);\n\tmarkerEyebrowRightMiddle = new MarkerTracker(EyebrowRightMiddle, this);\n\tmarkerEyebrowLeftOuter = new MarkerTracker(EyebrowLeftOuter, this);\n\tmarkerEyebrowRightOuter = new MarkerTracker(EyebrowRightOuter, this);\n\n\tmarkerCheekLeft = new MarkerTracker(CheekLeft, this);\n\tmarkerCheekRight = new MarkerTracker(CheekRight, this);\n\t\n\tmarkerJaw = new MarkerTracker(Jaw, this);\n\n\tmarkerLipsLeftCorner = new MarkerTracker(LipsLeftCorner, this);\n\tmarkerLipsRightCorner = new MarkerTracker(LipsRightCorner, this);\n\n\tmarkerLipsLeftTop = new MarkerTracker(LipsLeftTop, this);\n\tmarkerLipsRightTop = new MarkerTracker(LipsRightTop, this);\n\n\tmarkerLipsLeftBottom = new MarkerTracker(LipsLeftBottom, this);\n\tmarkerLipsRightBottom = new MarkerTracker(LipsRightBottom, this);\n\t\n\tfprintf(stderr, \"FaceMapper object constructed and ready to go!\\n\");\n}\n\nFaceMapper::~FaceMapper() {\n\tfprintf(stderr, \"FaceMapper object destructing...\\n\");\n\t\/\/Make a COPY of the vector, because otherwise it will change size out from under us while we are iterating.\n\tvector<MarkerTracker *> markerTrackersSnapshot = vector<MarkerTracker *>(*MarkerTracker::getMarkerTrackers());\n\tsize_t markerTrackersCount = markerTrackersSnapshot.size();\n\tfor(size_t i = 0; i < markerTrackersCount; i++) {\n\t\tif(markerTrackersSnapshot[i] != NULL) {\n\t\t\tdelete markerTrackersSnapshot[i];\n\t\t}\n\t}\n\tdelete markerSeparator;\n}\n\nvoid FaceMapper::processCurrentFrame(void) {\n\n\tfacialFeatures = faceTracker->getFacialFeatures();\n\tcalculateEyeRects();\n\tmarkerSeparator->processCurrentFrame();\n\n\tmarkerJaw->processCurrentFrame();\n\n\tmarkerEyelidLeftTop->processCurrentFrame();\n\tmarkerEyelidLeftBottom->processCurrentFrame();\n\tmarkerEyebrowLeftInner->processCurrentFrame();\n\tmarkerEyebrowLeftMiddle->processCurrentFrame();\n\tmarkerEyebrowLeftOuter->processCurrentFrame();\n\tmarkerCheekLeft->processCurrentFrame();\n\tmarkerLipsLeftCorner->processCurrentFrame();\n\tmarkerLipsLeftTop->processCurrentFrame();\n\tmarkerLipsLeftBottom->processCurrentFrame();\n\n\tmarkerEyelidRightTop->processCurrentFrame();\n\tmarkerEyelidRightBottom->processCurrentFrame();\n\tmarkerEyebrowRightInner->processCurrentFrame();\n\tmarkerEyebrowRightMiddle->processCurrentFrame();\n\tmarkerEyebrowRightOuter->processCurrentFrame();\n\tmarkerCheekRight->processCurrentFrame();\n\tmarkerLipsRightCorner->processCurrentFrame();\n\tmarkerLipsRightTop->processCurrentFrame();\n\tmarkerLipsRightBottom->processCurrentFrame();\n\/*\n\t\/\/\/\/ FIXME FIXME FIXME \/\/\/\/\n\tFacialCameraModel cameraModel = faceTracker->getFacialCameraModel();\n\tMat frame = frameDerivatives->getPreviewFrame();\n\tFacialPose facialPose = faceTracker->getFacialPose();\n\tPoint3d planePoint = Point3d(facialPose.translationVector.at<double>(0), facialPose.translationVector.at<double>(1), facialPose.translationVector.at<double>(2));\n\tMat planeNormalMat = (Mat_<double>(3, 1) << 0.0, 0.0, 1.0);\n\tplaneNormalMat = facialPose.rotationMatrix * planeNormalMat;\n\tVec3d planeNormal = Vec3d(planeNormalMat.at<double>(0), planeNormalMat.at<double>(1), planeNormalMat.at<double>(2));\n\n\tvector<MarkerTracker *> *markerTrackers = MarkerTracker::getMarkerTrackers();\n\tsize_t markerTrackersCount = (*markerTrackers).size();\n\tfor(size_t i = 0; i < markerTrackersCount; i++) {\n\t\tMarkerPoint tempPoint = (*markerTrackers)[i]->getMarkerPoint();\n\t\tMat homogeneousPoint = (Mat_<double>(3,1) << tempPoint.point.x, tempPoint.point.y, 1.0);\n\t\tMat worldPoint = cameraModel.cameraMatrix.inv() * homogeneousPoint;\n\n\t\tPoint3d intersection;\n\t\tPoint3d rayOrigin = Point3d(0,0,0);\n\t\tVec3d rayVector = Vec3d(worldPoint.at<double>(0), worldPoint.at<double>(1), worldPoint.at<double>(2));\n\t\tif(!Utilities::rayPlaneIntersection(intersection, rayOrigin, rayVector, planePoint, planeNormal)) {\n\t\t\tfprintf(stderr, \"INTERSECTION FAILED!!!\\n\");\n\t\t} else {\n\t\t\tMat markerMat = (Mat_<double>(3, 1) << intersection.x, intersection.y, intersection.z);\n\t\t\tmarkerMat = markerMat - facialPose.translationVector;\n\t\t\tmarkerMat = facialPose.rotationMatrix.inv() * markerMat;\n\n\t\t\tcout << \"****************RECOVERED MARKER POSITION::: \" << markerMat << \"\\n\";\n\n\t\t\tstd::vector<Point3d> rayViz3d(2);\n\t\t\tstd::vector<Point2d> rayViz2d;\n\t\t\trayViz3d[0] = intersection;\n\t\t\trayViz3d[1] = Point3d(markerMat.at<double>(0), markerMat.at<double>(1), markerMat.at<double>(2) + 500);\n\t\t\tMat tempRotationVector = (Mat_<double>(3, 1) << 0, 0, 0);\n\t\t\tMat tempTranslationVector = (Mat_<double>(3, 1) << 0, 0, 0);\n\t\t\tprojectPoints(rayViz3d, tempRotationVector, tempTranslationVector, cameraModel.cameraMatrix, cameraModel.distortionCoefficients, rayViz2d);\n\t\t\tline(frame, rayViz2d[0], rayViz2d[1], Scalar(0, 0, 255), 1);\n\t\t}\n\t}\n\t\/\/\/\/ END FIXME \/\/\/\/\n*\/\n}\n\nvoid FaceMapper::renderPreviewHUD(bool verbose) {\n\tMat frame = frameDerivatives->getPreviewFrame();\n\tif(verbose) {\n\t\tmarkerSeparator->renderPreviewHUD(true);\n\n\t\tif(leftEyeRect.set) {\n\t\t\trectangle(frame, leftEyeRect.rect, Scalar(0, 0, 255));\n\t\t}\n\t\tif(rightEyeRect.set) {\n\t\t\trectangle(frame, rightEyeRect.rect, Scalar(0, 0, 255));\n\t\t}\n\t}\n\tSize frameSize = frame.size();\n\tdouble previewRatio = 1.25, previewWidthPercentage = 0.2, previewCenterHeightPercentage = 0.2; \/\/ FIXME - magic numbers\n\tRect2d previewRect;\n\tpreviewRect.width = frameSize.width * previewWidthPercentage;\n\tpreviewRect.height = previewRect.width * previewRatio;\n\tpreviewRect.x = frameSize.width - previewRect.width;\n\tpreviewRect.y = frameSize.height - previewRect.height;\n\tPoint2d previewCenter = Utilities::centerRect(previewRect);\n\tpreviewCenter.y -= previewRect.height * previewCenterHeightPercentage;\n\tdouble previewPointScale = previewRect.width \/ 200;\n\trectangle(frame, previewRect, Scalar(10, 10, 10), CV_FILLED);\n\tvector<MarkerTracker *> *markerTrackers = MarkerTracker::getMarkerTrackers();\n\tsize_t markerTrackersCount = (*markerTrackers).size();\n\tfor(size_t i = 0; i < markerTrackersCount; i++) {\n\t\t(*markerTrackers)[i]->renderPreviewHUD(verbose);\n\n\t\tMarkerPoint markerPoint = (*markerTrackers)[i]->getMarkerPoint();\n\t\tPoint2d previewPoint = Point2d(\n\t\t\t\t(markerPoint.point3d.x * previewPointScale) + previewCenter.x,\n\t\t\t\t(markerPoint.point3d.y * previewPointScale) + previewCenter.y);\n\t\tUtilities::drawX(frame, previewPoint, Scalar(255, 255, 255));\n\t}\n}\n\nFrameDerivatives *FaceMapper::getFrameDerivatives(void) {\n\treturn frameDerivatives;\n}\n\nFaceTracker *FaceMapper::getFaceTracker(void) {\n\treturn faceTracker;\n}\n\nMarkerSeparator *FaceMapper::getMarkerSeparator(void) {\n\treturn markerSeparator;\n}\n\nEyeRect FaceMapper::getLeftEyeRect(void) {\n\treturn leftEyeRect;\n}\n\nEyeRect FaceMapper::getRightEyeRect(void) {\n\treturn rightEyeRect;\n}\n\nvoid FaceMapper::calculateEyeRects(void) {\n\tPoint2d pointA, pointB;\n\tdouble dist;\n\n\tleftEyeRect.set = false;\n\trightEyeRect.set = false;\n\n\tif(!facialFeatures.set) {\n\t\treturn;\n\t}\n\n\tpointA = facialFeatures.eyeLeftInnerCorner;\n\tpointB = facialFeatures.eyeLeftOuterCorner;\n\tdist = Utilities::lineDistance(pointA, pointB);\n\tleftEyeRect.rect.x = pointA.x;\n\tleftEyeRect.rect.y = ((pointA.y + pointB.y) \/ 2.0) - (dist \/ 2.0);\n\tleftEyeRect.rect.width = dist;\n\tleftEyeRect.rect.height = dist;\n\tleftEyeRect.rect = Utilities::insetBox(leftEyeRect.rect, 1.25); \/\/ FIXME - magic numbers\n\tleftEyeRect.set = true;\n\n\tpointA = facialFeatures.eyeRightOuterCorner;\n\tpointB = facialFeatures.eyeRightInnerCorner;\n\tdist = Utilities::lineDistance(pointA, pointB);\n\trightEyeRect.rect.x = pointA.x;\n\trightEyeRect.rect.y = ((pointA.y + pointB.y) \/ 2.0) - (dist \/ 2.0);\n\trightEyeRect.rect.width = dist;\n\trightEyeRect.rect.height = dist;\n\trightEyeRect.rect = Utilities::insetBox(rightEyeRect.rect, 1.25); \/\/ FIXME - magic numbers\n\trightEyeRect.set = true;\n}\n\n}; \/\/namespace YerFace\n<commit_msg>remove a bunch of useless experimental code<commit_after>\n#include \"FaceMapper.hpp\"\n#include \"Utilities.hpp\"\n#include \"opencv2\/calib3d.hpp\"\n#include \"opencv2\/highgui.hpp\"\n\n#include <cstdlib>\n\nusing namespace std;\nusing namespace cv;\n\nnamespace YerFace {\n\nFaceMapper::FaceMapper(FrameDerivatives *myFrameDerivatives, FaceTracker *myFaceTracker) {\n\tframeDerivatives = myFrameDerivatives;\n\tif(frameDerivatives == NULL) {\n\t\tthrow invalid_argument(\"frameDerivatives cannot be NULL\");\n\t}\n\tfaceTracker = myFaceTracker;\n\tif(faceTracker == NULL) {\n\t\tthrow invalid_argument(\"faceTracker cannot be NULL\");\n\t}\n\n\tmarkerSeparator = new MarkerSeparator(frameDerivatives, faceTracker);\n\n\tmarkerEyelidLeftTop = new MarkerTracker(EyelidLeftTop, this);\n\tmarkerEyelidRightTop = new MarkerTracker(EyelidRightTop, this);\n\tmarkerEyelidLeftBottom = new MarkerTracker(EyelidLeftBottom, this);\n\tmarkerEyelidRightBottom = new MarkerTracker(EyelidRightBottom, this);\n\n\tmarkerEyebrowLeftInner = new MarkerTracker(EyebrowLeftInner, this);\n\tmarkerEyebrowRightInner = new MarkerTracker(EyebrowRightInner, this);\n\tmarkerEyebrowLeftMiddle = new MarkerTracker(EyebrowLeftMiddle, this);\n\tmarkerEyebrowRightMiddle = new MarkerTracker(EyebrowRightMiddle, this);\n\tmarkerEyebrowLeftOuter = new MarkerTracker(EyebrowLeftOuter, this);\n\tmarkerEyebrowRightOuter = new MarkerTracker(EyebrowRightOuter, this);\n\n\tmarkerCheekLeft = new MarkerTracker(CheekLeft, this);\n\tmarkerCheekRight = new MarkerTracker(CheekRight, this);\n\t\n\tmarkerJaw = new MarkerTracker(Jaw, this);\n\n\tmarkerLipsLeftCorner = new MarkerTracker(LipsLeftCorner, this);\n\tmarkerLipsRightCorner = new MarkerTracker(LipsRightCorner, this);\n\n\tmarkerLipsLeftTop = new MarkerTracker(LipsLeftTop, this);\n\tmarkerLipsRightTop = new MarkerTracker(LipsRightTop, this);\n\n\tmarkerLipsLeftBottom = new MarkerTracker(LipsLeftBottom, this);\n\tmarkerLipsRightBottom = new MarkerTracker(LipsRightBottom, this);\n\t\n\tfprintf(stderr, \"FaceMapper object constructed and ready to go!\\n\");\n}\n\nFaceMapper::~FaceMapper() {\n\tfprintf(stderr, \"FaceMapper object destructing...\\n\");\n\t\/\/Make a COPY of the vector, because otherwise it will change size out from under us while we are iterating.\n\tvector<MarkerTracker *> markerTrackersSnapshot = vector<MarkerTracker *>(*MarkerTracker::getMarkerTrackers());\n\tsize_t markerTrackersCount = markerTrackersSnapshot.size();\n\tfor(size_t i = 0; i < markerTrackersCount; i++) {\n\t\tif(markerTrackersSnapshot[i] != NULL) {\n\t\t\tdelete markerTrackersSnapshot[i];\n\t\t}\n\t}\n\tdelete markerSeparator;\n}\n\nvoid FaceMapper::processCurrentFrame(void) {\n\n\tfacialFeatures = faceTracker->getFacialFeatures();\n\tcalculateEyeRects();\n\tmarkerSeparator->processCurrentFrame();\n\n\tmarkerJaw->processCurrentFrame();\n\n\tmarkerEyelidLeftTop->processCurrentFrame();\n\tmarkerEyelidLeftBottom->processCurrentFrame();\n\tmarkerEyebrowLeftInner->processCurrentFrame();\n\tmarkerEyebrowLeftMiddle->processCurrentFrame();\n\tmarkerEyebrowLeftOuter->processCurrentFrame();\n\tmarkerCheekLeft->processCurrentFrame();\n\tmarkerLipsLeftCorner->processCurrentFrame();\n\tmarkerLipsLeftTop->processCurrentFrame();\n\tmarkerLipsLeftBottom->processCurrentFrame();\n\n\tmarkerEyelidRightTop->processCurrentFrame();\n\tmarkerEyelidRightBottom->processCurrentFrame();\n\tmarkerEyebrowRightInner->processCurrentFrame();\n\tmarkerEyebrowRightMiddle->processCurrentFrame();\n\tmarkerEyebrowRightOuter->processCurrentFrame();\n\tmarkerCheekRight->processCurrentFrame();\n\tmarkerLipsRightCorner->processCurrentFrame();\n\tmarkerLipsRightTop->processCurrentFrame();\n\tmarkerLipsRightBottom->processCurrentFrame();\n}\n\nvoid FaceMapper::renderPreviewHUD(bool verbose) {\n\tMat frame = frameDerivatives->getPreviewFrame();\n\tif(verbose) {\n\t\tmarkerSeparator->renderPreviewHUD(true);\n\n\t\tif(leftEyeRect.set) {\n\t\t\trectangle(frame, leftEyeRect.rect, Scalar(0, 0, 255));\n\t\t}\n\t\tif(rightEyeRect.set) {\n\t\t\trectangle(frame, rightEyeRect.rect, Scalar(0, 0, 255));\n\t\t}\n\t}\n\tSize frameSize = frame.size();\n\tdouble previewRatio = 1.25, previewWidthPercentage = 0.2, previewCenterHeightPercentage = 0.2; \/\/ FIXME - magic numbers\n\tRect2d previewRect;\n\tpreviewRect.width = frameSize.width * previewWidthPercentage;\n\tpreviewRect.height = previewRect.width * previewRatio;\n\tpreviewRect.x = frameSize.width - previewRect.width;\n\tpreviewRect.y = frameSize.height - previewRect.height;\n\tPoint2d previewCenter = Utilities::centerRect(previewRect);\n\tpreviewCenter.y -= previewRect.height * previewCenterHeightPercentage;\n\tdouble previewPointScale = previewRect.width \/ 200;\n\trectangle(frame, previewRect, Scalar(10, 10, 10), CV_FILLED);\n\tvector<MarkerTracker *> *markerTrackers = MarkerTracker::getMarkerTrackers();\n\tsize_t markerTrackersCount = (*markerTrackers).size();\n\tfor(size_t i = 0; i < markerTrackersCount; i++) {\n\t\t(*markerTrackers)[i]->renderPreviewHUD(verbose);\n\n\t\tMarkerPoint markerPoint = (*markerTrackers)[i]->getMarkerPoint();\n\t\tPoint2d previewPoint = Point2d(\n\t\t\t\t(markerPoint.point3d.x * previewPointScale) + previewCenter.x,\n\t\t\t\t(markerPoint.point3d.y * previewPointScale) + previewCenter.y);\n\t\tUtilities::drawX(frame, previewPoint, Scalar(255, 255, 255));\n\t}\n}\n\nFrameDerivatives *FaceMapper::getFrameDerivatives(void) {\n\treturn frameDerivatives;\n}\n\nFaceTracker *FaceMapper::getFaceTracker(void) {\n\treturn faceTracker;\n}\n\nMarkerSeparator *FaceMapper::getMarkerSeparator(void) {\n\treturn markerSeparator;\n}\n\nEyeRect FaceMapper::getLeftEyeRect(void) {\n\treturn leftEyeRect;\n}\n\nEyeRect FaceMapper::getRightEyeRect(void) {\n\treturn rightEyeRect;\n}\n\nvoid FaceMapper::calculateEyeRects(void) {\n\tPoint2d pointA, pointB;\n\tdouble dist;\n\n\tleftEyeRect.set = false;\n\trightEyeRect.set = false;\n\n\tif(!facialFeatures.set) {\n\t\treturn;\n\t}\n\n\tpointA = facialFeatures.eyeLeftInnerCorner;\n\tpointB = facialFeatures.eyeLeftOuterCorner;\n\tdist = Utilities::lineDistance(pointA, pointB);\n\tleftEyeRect.rect.x = pointA.x;\n\tleftEyeRect.rect.y = ((pointA.y + pointB.y) \/ 2.0) - (dist \/ 2.0);\n\tleftEyeRect.rect.width = dist;\n\tleftEyeRect.rect.height = dist;\n\tleftEyeRect.rect = Utilities::insetBox(leftEyeRect.rect, 1.25); \/\/ FIXME - magic numbers\n\tleftEyeRect.set = true;\n\n\tpointA = facialFeatures.eyeRightOuterCorner;\n\tpointB = facialFeatures.eyeRightInnerCorner;\n\tdist = Utilities::lineDistance(pointA, pointB);\n\trightEyeRect.rect.x = pointA.x;\n\trightEyeRect.rect.y = ((pointA.y + pointB.y) \/ 2.0) - (dist \/ 2.0);\n\trightEyeRect.rect.width = dist;\n\trightEyeRect.rect.height = dist;\n\trightEyeRect.rect = Utilities::insetBox(rightEyeRect.rect, 1.25); \/\/ FIXME - magic numbers\n\trightEyeRect.set = true;\n}\n\n}; \/\/namespace YerFace\n<|endoftext|>"} {"text":"<commit_before>#include \"GameObject.h\"\n\nvoid GameObject::load(const int x, const int y, const int width, const int height) {\n\tm_iX = x;\n\tm_iY = y;\n\tm_iWidth = width;\n\tm_iHeight = height;\n}\n\nvoid GameObject::setTexture(const std::string textureID, int nbFrames) {\n\tm_iCurrentRow = 1;\n\tm_iCurrentFrame = 1;\n\tm_iNbFrames = nbFrames;\n\tm_sTextureID = textureID;\n}\n\nvoid GameObject::setTextureRow(const int currentRow) {\n\tm_iCurrentRow = currentRow;\n}\n\nvoid GameObject::update() {\n\n}\n\nvoid GameObject::render() {\n\n}\n\nvoid GameObject::clean() {\n\n}\n\n<commit_msg>Frames updated in the GameObject::update method<commit_after>#include \"GameObject.h\"\n\nvoid GameObject::load(const int x, const int y, const int width, const int height) {\n\tm_iX = x;\n\tm_iY = y;\n\tm_iWidth = width;\n\tm_iHeight = height;\n}\n\nvoid GameObject::setTexture(const std::string textureID, int nbFrames) {\n\tm_iCurrentRow = 1;\n\tm_iCurrentFrame = 1;\n\tm_iNbFrames = nbFrames;\n\tm_sTextureID = textureID;\n}\n\nvoid GameObject::setTextureRow(const int currentRow) {\n\tm_iCurrentRow = currentRow;\n}\n\nvoid GameObject::update() {\n\tm_iCurrentFrame = int(((SDL_GetTicks() \/ 100) % m_iNbFrames));\n}\n\nvoid GameObject::render() {\n\n}\n\nvoid GameObject::clean() {\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Unit tests for libkvkontakte.\n * Copyright (C) 2015 Alexander Potashev <aspotashev@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"test_userinfo.h\"\n\n#include <libkvkontakte\/userinfofulljob.h>\n\n#include <qtest_kde.h>\n\n#include <QtCore\/QList>\n\nusing namespace Vkontakte;\n\nTestUserInfo::TestUserInfo()\n : VkTestBase()\n{\n}\n\nvoid TestUserInfo::initTestCase()\n{\n authenticate();\n}\n\nvoid TestUserInfo::testUserInfoJob()\n{\n Vkontakte::UserInfoJob* const job = new Vkontakte::UserInfoJob(\n accessToken(), 1);\n\n job->exec();\n\n QList<UserInfoPtr> res = job->userInfo();\n QCOMPARE(res.size(), 1);\n\n UserInfoPtr user = res.first();\n QCOMPARE(user->domain(), QString(\"durov\"));\n QCOMPARE(user->firstName(), QString::fromUtf8(\"Павел\"));\n}\n\nvoid TestUserInfo::testUserInfoFullJob()\n{\n Vkontakte::UserInfoFullJob* const job = new Vkontakte::UserInfoFullJob(\n accessToken(), 1, true, true);\n\n job->exec();\n\n QList<UserInfoPtr> res = job->userInfo();\n QCOMPARE(res.size(), 1);\n\n UserInfoPtr user = res.first();\n QCOMPARE(user->domain(), QString(\"durov\"));\n QCOMPARE(user->firstName(), QString::fromUtf8(\"Павел\"));\n QCOMPARE(user->countryString(), QString::fromUtf8(\"Россия\"));\n QCOMPARE(user->cityString(), QString::fromUtf8(\"Санкт-Петербург\"));\n}\n\nQTEST_KDEMAIN(TestUserInfo, GUI)\n#include \"test_userinfo.moc\"\n<commit_msg>test_userinfo: Verify successful completion of jobs<commit_after>\/*\n * Unit tests for libkvkontakte.\n * Copyright (C) 2015 Alexander Potashev <aspotashev@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"test_userinfo.h\"\n\n#include <libkvkontakte\/userinfofulljob.h>\n\n#include <qtest_kde.h>\n\n#include <QtCore\/QList>\n\nusing namespace Vkontakte;\n\nTestUserInfo::TestUserInfo()\n : VkTestBase()\n{\n}\n\nvoid TestUserInfo::initTestCase()\n{\n authenticate();\n}\n\nvoid TestUserInfo::testUserInfoJob()\n{\n Vkontakte::UserInfoJob* const job = new Vkontakte::UserInfoJob(\n accessToken(), 1);\n job->exec();\n QVERIFY(!job->error());\n\n QList<UserInfoPtr> res = job->userInfo();\n QCOMPARE(res.size(), 1);\n\n UserInfoPtr user = res.first();\n QCOMPARE(user->domain(), QString(\"durov\"));\n QCOMPARE(user->firstName(), QString::fromUtf8(\"Павел\"));\n}\n\nvoid TestUserInfo::testUserInfoFullJob()\n{\n Vkontakte::UserInfoFullJob* const job = new Vkontakte::UserInfoFullJob(\n accessToken(), 1, true, true);\n job->exec();\n QVERIFY(!job->error());\n\n QList<UserInfoPtr> res = job->userInfo();\n QCOMPARE(res.size(), 1);\n\n UserInfoPtr user = res.first();\n QCOMPARE(user->domain(), QString(\"durov\"));\n QCOMPARE(user->firstName(), QString::fromUtf8(\"Павел\"));\n QCOMPARE(user->countryString(), QString::fromUtf8(\"Россия\"));\n QCOMPARE(user->cityString(), QString::fromUtf8(\"Санкт-Петербург\"));\n}\n\nQTEST_KDEMAIN(TestUserInfo, GUI)\n#include \"test_userinfo.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"x86_64-Codegen.h\"\n#include \"ASTNode.h\"\n#include \"lib\/Runtime.h\"\n#include \"Internal.h\"\n#include <stdexcept>\n#include <vector>\nusing namespace std;\n\n#define __ m_Asm->\n#define e__ entry_asm->\n\nnamespace snow {\nnamespace x86_64 {\n\t\/\/ stack_frame->`member'\n\t#define GET_STACK(member) (Address(rbp, (-(int)sizeof(StackFrame))+(int)offsetof(StackFrame, member)))\n\t\n\t\/\/ temporaries[id]\n\t#define GET_TEMPORARY(id) (Address(rbp, (-(int)sizeof(StackFrame))-(sizeof(VALUE)*(id+1))))\n\t\n\t\/\/ reg[index] (reg must contain a pointer to an array of values)\n\t#define GET_ARRAY_PTR(reg, index) (Address((reg), index * sizeof(VALUE)))\n\t\t\n\tstatic const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };\n\tstatic const uint64_t num_arg_regs = 6;\n\t\n\tCodegen::Codegen(ast::FunctionDefinition& def) :\n\t\tsnow::Codegen(def),\n\t\tm_NumLocals(0),\n\t\tm_NumStackArguments(0),\n\t\tm_NumTemporaries(0) {\n\t\tm_LocalMap = new LocalMap;\n\t\tm_Asm = new x86_64::Assembler;\n\t\tm_Return = new Label;\n\t}\n\t\n\tuint64_t Codegen::reserve_temporary() {\n\t\tif (m_FreeTemporaries.size() > 0) {\n\t\t\tuint64_t t = m_FreeTemporaries.back();\n\t\t\tm_FreeTemporaries.pop_back();\n\t\t\treturn t;\n\t\t}\n\t\treturn m_NumTemporaries++;\n\t}\n\t\n\tvoid Codegen::free_temporary(uint64_t id) {\n\t\tm_FreeTemporaries.push_back(id);\n\t}\n\t\n\tvoid Codegen::get_local(uint64_t id, const Register& reg) {\n\t\t__ mov(GET_STACK(locals), reg);\n\t\t__ mov(GET_ARRAY_PTR(reg, id), reg);\n\t}\n\t\n\tvoid Codegen::set_local(const Register& reg, uint64_t id, const Register& tmp) {\n\t\tassert(reg != tmp && \"Cannot use source register as temporary storage!\");\n\t\t__ mov(GET_STACK(locals), tmp);\n\t\t__ mov(reg, GET_ARRAY_PTR(tmp, id));\n\t}\n\t\n\tHandle<CompiledCode> Codegen::compile() {\n\t\tRefPtr<x86_64::Assembler> entry_asm = new x86_64::Assembler;\n\t\t__ subasm(entry_asm);\n\t\t\n\t\tif (m_Def.arguments.size() > 0) {\n\t\t\t__ comment(\"copy arguments to locals\");\n\t\t\t__ mov(GET_STACK(arguments), r8);\n\t\t\t__ mov(GET_STACK(locals), r9);\n\t\t\tsize_t i = 0;\n\t\t\tfor each (iter, m_Def.arguments) {\n\t\t\t\tauto local = m_LocalMap->define_local((*iter)->name);\n\t\t\t\t__ mov(GET_ARRAY_PTR(r8, i), rax);\n\t\t\t\t__ mov(rax, GET_ARRAY_PTR(r9, local));\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t__ comment(\"function body\");\n\t\tcompile(*m_Def.sequence);\n\t\t\n\t\tuint64_t return_temporary = reserve_temporary();\n\t\t__ comment(\"function exit\");\n\t\t__ bind(m_Return);\n\t\t__ mov(rax, GET_TEMPORARY(return_temporary));\n\t\t__ call(\"snow_leave_scope\");\n\t\t__ mov(GET_TEMPORARY(return_temporary), rax);\n\t\t__ leave();\n\t\t__ ret();\n\t\t\n\t\t\/\/ Compile the function entry, now that we know all the locals and\n\t\t\/\/ temporaries.\n\t\t{\n\t\t\te__ comment(\"function entry\");\n\t\t\tint stack_size = sizeof(StackFrame) + sizeof(VALUE)*(m_NumTemporaries + m_NumStackArguments);\n\t\t\t\/\/ maintain 16-byte stack alignment\n\t\t\tstack_size += stack_size % 16;\n\t\t\te__ enter(stack_size);\n\t\t\t\n\t\t\te__ mov(rbp, rsi);\n\t\t\te__ sub(sizeof(StackFrame), rsi);\n\t\t\te__ call(\"snow_enter_scope\");\n\t\t}\n\t\t\n\t\tHandle<CompiledCode> code = __ compile();\n\t\tcode->set_local_map(m_LocalMap);\n\t\tfor each (iter, m_Related) {\n\t\t\tcode->add_related(*iter);\n\t\t}\n\t\treturn code;\n\t}\n\t\n\tvoid Codegen::compile(ast::Literal& literal) {\n\t\t__ comment(std::string(\"literal: `\") + literal.string + std::string(\"'\"));\n\t\tusing ast::Literal;\n\t\t\n\t\tconst char* str = literal.string.c_str();\n\t\t\n\t\tVALUE val = nil();\n\t\t\n\t\tswitch (literal.type) {\n\t\t\tcase Literal::INTEGER_DEC_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 10));\n\t\t\t\tbreak;\n\t\t\tcase Literal::INTEGER_HEX_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 16));\n\t\t\t\tbreak;\n\t\t\tcase Literal::INTEGER_BIN_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 2));\n\t\t\t\tbreak;\n\t\t\tcase Literal::FLOAT_TYPE:\n\t\t\t\t\/\/ TODO: Doubles\n\t\t\t\tval = value(strtof(str, NULL));\n\t\t\t\tbreak;\n\t\t\tcase Literal::STRING_TYPE:\n\t\t\t\tval = create_string(str);\n\t\t\t\tbreak;\n\t\t\tcase Literal::TRUE_TYPE:\n\t\t\t\tval = value(true);\n\t\t\t\tbreak;\n\t\t\tcase Literal::FALSE_TYPE:\n\t\t\t\tval = value(false);\n\t\t\t\tbreak;\n\t\t\tcase Literal::NIL_TYPE:\n\t\t\t\tval = nil();\n break;\n\t\t}\n\n\t\t__ mov(val, rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::Identifier& id) {\n\t\t__ comment(std::string(\"identifier: `\") + id.name + std::string(\"'\"));\n\t\tif (m_LocalMap->has_local(id.name)) {\n\t\t\t\/\/ It's a local from current scope...\n\t\t\tget_local(m_LocalMap->local(id.name), rax);\n\t\t} else {\n\t\t\t\/\/ THE PAIN! It's from a parent scope...\n\t\t\t__ mov(rbp, rdi);\n\t\t\t__ sub(sizeof(StackFrame), rdi);\n\t\t\t\/\/ TODO\/XXX: Symbol storage -- id.name is freed at some point.\n\t\t\t__ mov(id.name.c_str(), rsi);\n\t\t\t__ mov(id.quiet, rdx);\n\t\t\t__ call(\"snow_get_local\");\n\t\t}\n\t}\n\n\tvoid Codegen::compile(ast::Sequence& seq) {\n\t\tfor each (iter, seq.nodes) {\n\t\t\t(*iter)->compile(*this);\n\t\t}\n\t}\n\n\tvoid Codegen::compile(ast::FunctionDefinition& def) {\n\t\t__ comment(\"function definition\");\n\t\tRefPtr<Codegen> codegen = new Codegen(def);\n\t\tHandle<CompiledCode> code = codegen->compile();\n\t\tm_Related.push_back(code);\n\t\tVALUE func = new(kMalloc) Function(*code);\n\t\t__ mov(func, rdi);\n\t\t__ mov(GET_STACK(scope), rsi);\n\t\t__ call(\"snow_set_parent_scope\");\n\t\t__ mov(func, rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::Return& ret) {\n\t\t__ comment(\"return\");\n\t\tif (ret.expression)\n\t\t\tret.expression->compile(*this);\n\t\telse\n\t\t\t__ clear(rax);\n\t\t__ jmp(m_Return);\n\t}\n\n\tvoid Codegen::compile(ast::Assignment& assign) {\n\t\tuint64_t l;\n\t\tif (m_LocalMap->has_local(assign.identifier->name))\n\t\t\tl = m_LocalMap->local(assign.identifier->name);\n\t\telse\n\t\t\tl = m_LocalMap->define_local(assign.identifier->name);\n\t\t\n\t\tassign.expression->compile(*this);\n\t\t__ comment(std::string(\"assignment: \") + assign.identifier->name);\n\t\tset_local(rax, l);\n\t}\n\n\tvoid Codegen::compile(ast::IfCondition& cond) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"if cond\");\n\t\tcond.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, after);\n\t\t__ comment(\"if body\");\n\t\tcond.if_true->compile(*this);\n\t\t__ bind(after);\n\t}\n\n\tvoid Codegen::compile(ast::IfElseCondition& cond) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> if_true = new Label;\n\t\tRefPtr<Label> if_false = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"if-else cond\");\n\t\tcond.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, if_false);\n\t\t__ bind(if_true);\n\t\t__ comment(\"if true\");\n\t\tcond.if_true->compile(*this);\n\t\t__ jmp(after);\n\t\t__ bind(if_false);\n\t\t__ comment(\"if false\");\n\t\tcond.if_false->compile(*this);\n\t\t__ bind(after);\n\t}\n\n\tvoid Codegen::compile(ast::Call& call) {\n\t\tauto self_tmp = reserve_temporary();\n\t\t\n\t\t__ comment(\"self for call\");\n\t\tcall.self->compile(*this);\n\t\t__ mov(rax, GET_TEMPORARY(self_tmp));\n\t\t\n\t\t\/\/ evaluate arguments and store temporaries\n\t\tauto num_args = call.arguments->length();\n\t\tuint64_t args_tmp[num_args];\n\t\tsize_t i = 0;\n\t\tfor each (arg_iter, call.arguments->nodes) {\n\t\t\targs_tmp[i] = reserve_temporary();\n\t\t\t__ comment(string_printf(\"argument %d\", i));\n\t\t\t(*arg_iter)->compile(*this);\n\t\t\t__ mov(rax, GET_TEMPORARY(args_tmp[i]));\n\t\t\t++i;\n\t\t}\n\t\t\n\t\tauto function_tmp = self_tmp;\n\t\tif (call.member) {\n\t\t\t__ comment(\"method call\");\n\t\t\tfunction_tmp = reserve_temporary();\n\t\t\t__ mov(GET_TEMPORARY(self_tmp), rdi);\n\t\t\t__ mov(call.member->name.c_str(), rsi);\n\t\t\t__ call(\"snow_get\");\n\t\t\t__ mov(rax, GET_TEMPORARY(function_tmp));\n\t\t\t__ mov(GET_TEMPORARY(self_tmp), rdi);\n\t\t} else {\n\t\t\t__ comment(\"closure call\");\n\t\t\t__ clear(rdi); \/\/ \"self\" is NULL for closures\n\t\t}\n\t\t\n\t\t__ mov(GET_TEMPORARY(function_tmp), rsi);\n\t\t__ mov(num_args, rdx);\n\t\t\n\t\tfor (size_t i = 0; i < num_args; ++i) {\n\t\t\tconst size_t arg_offset = i + 3;\n\t\t\t\n\t\t\tif (arg_offset < num_arg_regs) {\n\t\t\t\t__ mov(GET_TEMPORARY(args_tmp[i]), *arg_regs[arg_offset]);\n\t\t\t} else {\n\t\t\t\tconst size_t stack_offset = arg_offset - num_arg_regs;\n\t\t\t\tif (m_NumStackArguments < stack_offset)\n\t\t\t\t\tm_NumStackArguments = stack_offset;\n\t\t\t\t__ mov(GET_TEMPORARY(args_tmp[i]), rax);\n\t\t\t\t\/\/ XXX: Can this be done without SIB?\n\t\t\t\t__ mov(stack_offset, rbx);\n\t\t\t\t__ mov(rax, SIB(rsp, rbx, SIB::SCALE_8));\n\t\t\t}\n\t\t\t\n\t\t\tfree_temporary(args_tmp[i]);\n\t\t}\n\t\t\n\t\tif (self_tmp == function_tmp)\n\t\t\tfree_temporary(self_tmp);\n\t\telse {\n\t\t\tfree_temporary(self_tmp);\n\t\t\tfree_temporary(function_tmp);\n\t\t}\n\t\t\n\t\t\n\t\t\/\/ finally!\n\t\t__ clear(rax);\n\t\t__ call(\"snow_call\");\n\t}\n\t\n\tvoid Codegen::compile(ast::Get& get) {\n\t\t__ comment(\"get `\" + get.member->name + \"'\");\n\t\tget.self->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ mov(get.member->name.c_str(), rsi);\n\t\t__ call(\"snow_get\");\n\t}\n\t\n\tvoid Codegen::compile(ast::Set& set) {\n\t\t__ comment(\"set `\" + set.member->name + \"'\");\n\t\tset.expression->compile(*this);\n\t\tauto tmp = reserve_temporary();\n\t\t__ mov(rax, GET_TEMPORARY(tmp));\n\t\tset.self->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ mov(set.member->name.c_str(), rsi);\n\t\t__ mov(GET_TEMPORARY(tmp), rdx);\n\t\t__ call(\"snow_set\");\n\t\tfree_temporary(tmp);\n\t}\n\n\tvoid Codegen::compile(ast::Loop& loop) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> body = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"loop cond\");\n\t\tloop.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, after);\n\t\t__ bind(body);\n\t\t__ comment(\"loop body\");\n\t\tloop.while_true->compile(*this);\n\t\t__ jmp(test_cond);\n\t\t__ bind(after);\n\t}\n\t\n\tvoid Codegen::compile(ast::Self&) {\n\t\t__ mov(GET_STACK(self), rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::It&) {\n\t\t__ mov(GET_STACK(it), rax);\n\t}\n}\n}\n<commit_msg>string literals are now allocated by the kMalloc allocator, so they won't ever be deleted.<commit_after>#include \"x86_64-Codegen.h\"\n#include \"ASTNode.h\"\n#include \"lib\/Runtime.h\"\n#include \"lib\/SnowString.h\"\n#include \"Internal.h\"\n#include <stdexcept>\n#include <vector>\nusing namespace std;\n\n#define __ m_Asm->\n#define e__ entry_asm->\n\nnamespace snow {\nnamespace x86_64 {\n\t\/\/ stack_frame->`member'\n\t#define GET_STACK(member) (Address(rbp, (-(int)sizeof(StackFrame))+(int)offsetof(StackFrame, member)))\n\t\n\t\/\/ temporaries[id]\n\t#define GET_TEMPORARY(id) (Address(rbp, (-(int)sizeof(StackFrame))-(sizeof(VALUE)*(id+1))))\n\t\n\t\/\/ reg[index] (reg must contain a pointer to an array of values)\n\t#define GET_ARRAY_PTR(reg, index) (Address((reg), index * sizeof(VALUE)))\n\t\t\n\tstatic const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 };\n\tstatic const uint64_t num_arg_regs = 6;\n\t\n\tCodegen::Codegen(ast::FunctionDefinition& def) :\n\t\tsnow::Codegen(def),\n\t\tm_NumLocals(0),\n\t\tm_NumStackArguments(0),\n\t\tm_NumTemporaries(0) {\n\t\tm_LocalMap = new LocalMap;\n\t\tm_Asm = new x86_64::Assembler;\n\t\tm_Return = new Label;\n\t}\n\t\n\tuint64_t Codegen::reserve_temporary() {\n\t\tif (m_FreeTemporaries.size() > 0) {\n\t\t\tuint64_t t = m_FreeTemporaries.back();\n\t\t\tm_FreeTemporaries.pop_back();\n\t\t\treturn t;\n\t\t}\n\t\treturn m_NumTemporaries++;\n\t}\n\t\n\tvoid Codegen::free_temporary(uint64_t id) {\n\t\tm_FreeTemporaries.push_back(id);\n\t}\n\t\n\tvoid Codegen::get_local(uint64_t id, const Register& reg) {\n\t\t__ mov(GET_STACK(locals), reg);\n\t\t__ mov(GET_ARRAY_PTR(reg, id), reg);\n\t}\n\t\n\tvoid Codegen::set_local(const Register& reg, uint64_t id, const Register& tmp) {\n\t\tassert(reg != tmp && \"Cannot use source register as temporary storage!\");\n\t\t__ mov(GET_STACK(locals), tmp);\n\t\t__ mov(reg, GET_ARRAY_PTR(tmp, id));\n\t}\n\t\n\tHandle<CompiledCode> Codegen::compile() {\n\t\tRefPtr<x86_64::Assembler> entry_asm = new x86_64::Assembler;\n\t\t__ subasm(entry_asm);\n\t\t\n\t\tif (m_Def.arguments.size() > 0) {\n\t\t\t__ comment(\"copy arguments to locals\");\n\t\t\t__ mov(GET_STACK(arguments), r8);\n\t\t\t__ mov(GET_STACK(locals), r9);\n\t\t\tsize_t i = 0;\n\t\t\tfor each (iter, m_Def.arguments) {\n\t\t\t\tauto local = m_LocalMap->define_local((*iter)->name);\n\t\t\t\t__ mov(GET_ARRAY_PTR(r8, i), rax);\n\t\t\t\t__ mov(rax, GET_ARRAY_PTR(r9, local));\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t__ comment(\"function body\");\n\t\tcompile(*m_Def.sequence);\n\t\t\n\t\tuint64_t return_temporary = reserve_temporary();\n\t\t__ comment(\"function exit\");\n\t\t__ bind(m_Return);\n\t\t__ mov(rax, GET_TEMPORARY(return_temporary));\n\t\t__ call(\"snow_leave_scope\");\n\t\t__ mov(GET_TEMPORARY(return_temporary), rax);\n\t\t__ leave();\n\t\t__ ret();\n\t\t\n\t\t\/\/ Compile the function entry, now that we know all the locals and\n\t\t\/\/ temporaries.\n\t\t{\n\t\t\te__ comment(\"function entry\");\n\t\t\tint stack_size = sizeof(StackFrame) + sizeof(VALUE)*(m_NumTemporaries + m_NumStackArguments);\n\t\t\t\/\/ maintain 16-byte stack alignment\n\t\t\tstack_size += stack_size % 16;\n\t\t\te__ enter(stack_size);\n\t\t\t\n\t\t\te__ mov(rbp, rsi);\n\t\t\te__ sub(sizeof(StackFrame), rsi);\n\t\t\te__ call(\"snow_enter_scope\");\n\t\t}\n\t\t\n\t\tHandle<CompiledCode> code = __ compile();\n\t\tcode->set_local_map(m_LocalMap);\n\t\tfor each (iter, m_Related) {\n\t\t\tcode->add_related(*iter);\n\t\t}\n\t\treturn code;\n\t}\n\t\n\tvoid Codegen::compile(ast::Literal& literal) {\n\t\t__ comment(std::string(\"literal: `\") + literal.string + std::string(\"'\"));\n\t\tusing ast::Literal;\n\t\t\n\t\tconst char* str = literal.string.c_str();\n\t\t\n\t\tVALUE val = nil();\n\t\t\n\t\tswitch (literal.type) {\n\t\t\tcase Literal::INTEGER_DEC_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 10));\n\t\t\t\tbreak;\n\t\t\tcase Literal::INTEGER_HEX_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 16));\n\t\t\t\tbreak;\n\t\t\tcase Literal::INTEGER_BIN_TYPE:\n\t\t\t\tval = value(strtoll(str, NULL, 2));\n\t\t\t\tbreak;\n\t\t\tcase Literal::FLOAT_TYPE:\n\t\t\t\t\/\/ TODO: Doubles\n\t\t\t\tval = value(strtof(str, NULL));\n\t\t\t\tbreak;\n\t\t\tcase Literal::STRING_TYPE:\n\t\t\t\tval = new(kMalloc) String(str);\n\t\t\t\tbreak;\n\t\t\tcase Literal::TRUE_TYPE:\n\t\t\t\tval = value(true);\n\t\t\t\tbreak;\n\t\t\tcase Literal::FALSE_TYPE:\n\t\t\t\tval = value(false);\n\t\t\t\tbreak;\n\t\t\tcase Literal::NIL_TYPE:\n\t\t\t\tval = nil();\n break;\n\t\t}\n\n\t\t__ mov(val, rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::Identifier& id) {\n\t\t__ comment(std::string(\"identifier: `\") + id.name + std::string(\"'\"));\n\t\tif (m_LocalMap->has_local(id.name)) {\n\t\t\t\/\/ It's a local from current scope...\n\t\t\tget_local(m_LocalMap->local(id.name), rax);\n\t\t} else {\n\t\t\t\/\/ THE PAIN! It's from a parent scope...\n\t\t\t__ mov(rbp, rdi);\n\t\t\t__ sub(sizeof(StackFrame), rdi);\n\t\t\t\/\/ TODO\/XXX: Symbol storage -- id.name is freed at some point.\n\t\t\t__ mov(id.name.c_str(), rsi);\n\t\t\t__ mov(id.quiet, rdx);\n\t\t\t__ call(\"snow_get_local\");\n\t\t}\n\t}\n\n\tvoid Codegen::compile(ast::Sequence& seq) {\n\t\tfor each (iter, seq.nodes) {\n\t\t\t(*iter)->compile(*this);\n\t\t}\n\t}\n\n\tvoid Codegen::compile(ast::FunctionDefinition& def) {\n\t\t__ comment(\"function definition\");\n\t\tRefPtr<Codegen> codegen = new Codegen(def);\n\t\tHandle<CompiledCode> code = codegen->compile();\n\t\tm_Related.push_back(code);\n\t\tVALUE func = new(kMalloc) Function(*code);\n\t\t__ mov(func, rdi);\n\t\t__ mov(GET_STACK(scope), rsi);\n\t\t__ call(\"snow_set_parent_scope\");\n\t\t__ mov(func, rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::Return& ret) {\n\t\t__ comment(\"return\");\n\t\tif (ret.expression)\n\t\t\tret.expression->compile(*this);\n\t\telse\n\t\t\t__ clear(rax);\n\t\t__ jmp(m_Return);\n\t}\n\n\tvoid Codegen::compile(ast::Assignment& assign) {\n\t\tuint64_t l;\n\t\tif (m_LocalMap->has_local(assign.identifier->name))\n\t\t\tl = m_LocalMap->local(assign.identifier->name);\n\t\telse\n\t\t\tl = m_LocalMap->define_local(assign.identifier->name);\n\t\t\n\t\tassign.expression->compile(*this);\n\t\t__ comment(std::string(\"assignment: \") + assign.identifier->name);\n\t\tset_local(rax, l);\n\t}\n\n\tvoid Codegen::compile(ast::IfCondition& cond) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"if cond\");\n\t\tcond.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, after);\n\t\t__ comment(\"if body\");\n\t\tcond.if_true->compile(*this);\n\t\t__ bind(after);\n\t}\n\n\tvoid Codegen::compile(ast::IfElseCondition& cond) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> if_true = new Label;\n\t\tRefPtr<Label> if_false = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"if-else cond\");\n\t\tcond.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, if_false);\n\t\t__ bind(if_true);\n\t\t__ comment(\"if true\");\n\t\tcond.if_true->compile(*this);\n\t\t__ jmp(after);\n\t\t__ bind(if_false);\n\t\t__ comment(\"if false\");\n\t\tcond.if_false->compile(*this);\n\t\t__ bind(after);\n\t}\n\n\tvoid Codegen::compile(ast::Call& call) {\n\t\tauto self_tmp = reserve_temporary();\n\t\t\n\t\t__ comment(\"self for call\");\n\t\tcall.self->compile(*this);\n\t\t__ mov(rax, GET_TEMPORARY(self_tmp));\n\t\t\n\t\t\/\/ evaluate arguments and store temporaries\n\t\tauto num_args = call.arguments->length();\n\t\tuint64_t args_tmp[num_args];\n\t\tsize_t i = 0;\n\t\tfor each (arg_iter, call.arguments->nodes) {\n\t\t\targs_tmp[i] = reserve_temporary();\n\t\t\t__ comment(string_printf(\"argument %d\", i));\n\t\t\t(*arg_iter)->compile(*this);\n\t\t\t__ mov(rax, GET_TEMPORARY(args_tmp[i]));\n\t\t\t++i;\n\t\t}\n\t\t\n\t\tauto function_tmp = self_tmp;\n\t\tif (call.member) {\n\t\t\t__ comment(\"method call\");\n\t\t\tfunction_tmp = reserve_temporary();\n\t\t\t__ mov(GET_TEMPORARY(self_tmp), rdi);\n\t\t\t__ mov(call.member->name.c_str(), rsi);\n\t\t\t__ call(\"snow_get\");\n\t\t\t__ mov(rax, GET_TEMPORARY(function_tmp));\n\t\t\t__ mov(GET_TEMPORARY(self_tmp), rdi);\n\t\t} else {\n\t\t\t__ comment(\"closure call\");\n\t\t\t__ clear(rdi); \/\/ \"self\" is NULL for closures\n\t\t}\n\t\t\n\t\t__ mov(GET_TEMPORARY(function_tmp), rsi);\n\t\t__ mov(num_args, rdx);\n\t\t\n\t\tfor (size_t i = 0; i < num_args; ++i) {\n\t\t\tconst size_t arg_offset = i + 3;\n\t\t\t\n\t\t\tif (arg_offset < num_arg_regs) {\n\t\t\t\t__ mov(GET_TEMPORARY(args_tmp[i]), *arg_regs[arg_offset]);\n\t\t\t} else {\n\t\t\t\tconst size_t stack_offset = arg_offset - num_arg_regs;\n\t\t\t\tif (m_NumStackArguments < stack_offset)\n\t\t\t\t\tm_NumStackArguments = stack_offset;\n\t\t\t\t__ mov(GET_TEMPORARY(args_tmp[i]), rax);\n\t\t\t\t\/\/ XXX: Can this be done without SIB?\n\t\t\t\t__ mov(stack_offset, rbx);\n\t\t\t\t__ mov(rax, SIB(rsp, rbx, SIB::SCALE_8));\n\t\t\t}\n\t\t\t\n\t\t\tfree_temporary(args_tmp[i]);\n\t\t}\n\t\t\n\t\tif (self_tmp == function_tmp)\n\t\t\tfree_temporary(self_tmp);\n\t\telse {\n\t\t\tfree_temporary(self_tmp);\n\t\t\tfree_temporary(function_tmp);\n\t\t}\n\t\t\n\t\t\n\t\t\/\/ finally!\n\t\t__ clear(rax);\n\t\t__ call(\"snow_call\");\n\t}\n\t\n\tvoid Codegen::compile(ast::Get& get) {\n\t\t__ comment(\"get `\" + get.member->name + \"'\");\n\t\tget.self->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ mov(get.member->name.c_str(), rsi);\n\t\t__ call(\"snow_get\");\n\t}\n\t\n\tvoid Codegen::compile(ast::Set& set) {\n\t\t__ comment(\"set `\" + set.member->name + \"'\");\n\t\tset.expression->compile(*this);\n\t\tauto tmp = reserve_temporary();\n\t\t__ mov(rax, GET_TEMPORARY(tmp));\n\t\tset.self->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ mov(set.member->name.c_str(), rsi);\n\t\t__ mov(GET_TEMPORARY(tmp), rdx);\n\t\t__ call(\"snow_set\");\n\t\tfree_temporary(tmp);\n\t}\n\n\tvoid Codegen::compile(ast::Loop& loop) {\n\t\tRefPtr<Label> test_cond = new Label;\n\t\tRefPtr<Label> body = new Label;\n\t\tRefPtr<Label> after = new Label;\n\t\t\n\t\t__ bind(test_cond);\n\t\t__ comment(\"loop cond\");\n\t\tloop.expression->compile(*this);\n\t\t__ mov(rax, rdi);\n\t\t__ call(\"snow_eval_truth\");\n\t\t__ cmp(0, rax);\n\t\t__ j(CC_EQUAL, after);\n\t\t__ bind(body);\n\t\t__ comment(\"loop body\");\n\t\tloop.while_true->compile(*this);\n\t\t__ jmp(test_cond);\n\t\t__ bind(after);\n\t}\n\t\n\tvoid Codegen::compile(ast::Self&) {\n\t\t__ mov(GET_STACK(self), rax);\n\t}\n\t\n\tvoid Codegen::compile(ast::It&) {\n\t\t__ mov(GET_STACK(it), rax);\n\t}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/gpu\/texture_info.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <cstring>\n\n#include \"third_party\/xxhash\/xxhash.h\"\n#include \"xenia\/base\/math.h\"\n\nnamespace xe {\nnamespace gpu {\n\nusing namespace xe::gpu::xenos;\n\nbool TextureInfo::Prepare(const xe_gpu_texture_fetch_t& fetch,\n TextureInfo* out_info) {\n std::memset(out_info, 0, sizeof(TextureInfo));\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/cc308051(v=vs.85).aspx\n \/\/ a2xx_sq_surfaceformat\n auto& info = *out_info;\n info.guest_address = fetch.address << 12;\n\n info.dimension = static_cast<Dimension>(fetch.dimension);\n info.width = info.height = info.depth = 0;\n switch (info.dimension) {\n case Dimension::k1D:\n info.dimension = Dimension::k2D;\n info.width = fetch.size_1d.width;\n info.height = 1;\n break;\n case Dimension::k2D:\n info.width = fetch.size_2d.width;\n info.height = fetch.size_2d.height;\n break;\n case Dimension::k3D:\n info.width = fetch.size_3d.width;\n info.height = fetch.size_3d.height;\n info.depth = fetch.size_3d.depth;\n break;\n case Dimension::kCube:\n info.width = fetch.size_stack.width;\n info.height = fetch.size_stack.height;\n info.depth = fetch.size_stack.depth;\n break;\n }\n info.texture_format = static_cast<TextureFormat>(fetch.format);\n info.endianness = static_cast<Endian>(fetch.endianness);\n info.is_tiled = fetch.tiled;\n info.has_packed_mips = fetch.packed_mips;\n info.input_length = 0; \/\/ Populated below.\n\n if (info.format_info()->format == TextureFormat::kUnknown) {\n assert_true(\"Unsupported texture format\");\n return false;\n }\n\n \/\/ Must be called here when we know the format.\n switch (info.dimension) {\n case Dimension::k1D: {\n assert_always();\n } break;\n case Dimension::k2D: {\n info.CalculateTextureSizes2D(fetch.size_2d.width + 1,\n fetch.size_2d.height + 1);\n } break;\n case Dimension::k3D: {\n \/\/ TODO(benvanik): calculate size.\n return false;\n }\n case Dimension::kCube: {\n info.CalculateTextureSizesCube(fetch.size_stack.width + 1,\n fetch.size_stack.height + 1,\n fetch.size_stack.depth + 1);\n } break;\n }\n\n return true;\n}\n\nbool TextureInfo::PrepareResolve(uint32_t physical_address,\n TextureFormat texture_format, Endian endian,\n uint32_t width, uint32_t height,\n TextureInfo* out_info) {\n std::memset(out_info, 0, sizeof(TextureInfo));\n auto& info = *out_info;\n info.guest_address = physical_address;\n info.dimension = Dimension::k2D;\n assert_true(width > 0);\n assert_true(height > 0);\n info.width = width - 1;\n info.height = height - 1;\n info.texture_format = texture_format;\n info.endianness = endian;\n info.is_tiled = true;\n info.has_packed_mips = false;\n info.input_length = 0;\n\n if (info.format_info()->format == TextureFormat::kUnknown) {\n assert_true(\"Unsupported texture format\");\n return false;\n }\n\n info.CalculateTextureSizes2D(width, height);\n return true;\n}\n\nvoid TextureInfo::CalculateTextureSizes2D(uint32_t width, uint32_t height) {\n size_2d.logical_width = width;\n size_2d.logical_height = height;\n\n \/\/ Here be dragons. The values here are used in texture_cache.cc to copy\n \/\/ images and create GL textures. Changes here will impact that code.\n \/\/ TODO(benvanik): generic texture copying utility.\n\n auto format = format_info();\n\n \/\/ w\/h in blocks.\n uint32_t block_width =\n xe::round_up(size_2d.logical_width, format->block_width) \/\n format->block_width;\n uint32_t block_height =\n xe::round_up(size_2d.logical_height, format->block_height) \/\n format->block_height;\n\n \/\/ Tiles are 32x32 blocks. The pitch of all textures must a multiple of tile\n \/\/ dimensions.\n uint32_t tile_width = xe::round_up(block_width, 32) \/ 32;\n size_2d.block_width = tile_width * 32;\n size_2d.block_height = block_height;\n\n uint32_t bytes_per_block =\n format->block_width * format->block_height * format->bits_per_pixel \/ 8;\n uint32_t byte_pitch = size_2d.block_width * bytes_per_block;\n\n uint32_t texel_width;\n if (!is_tiled) {\n \/\/ Each row must be a multiple of 256 in linear textures.\n byte_pitch = xe::round_up(byte_pitch, 256);\n texel_width = (byte_pitch \/ bytes_per_block) * format->block_width;\n } else {\n texel_width = size_2d.block_width * format->block_width;\n }\n\n size_2d.input_width = texel_width;\n size_2d.input_height = size_2d.block_height * format->block_height;\n size_2d.input_pitch = byte_pitch;\n\n input_length = size_2d.input_pitch * size_2d.block_height;\n}\n\nvoid TextureInfo::CalculateTextureSizesCube(uint32_t width, uint32_t height,\n uint32_t depth) {\n assert_true(depth == 6);\n size_cube.logical_width = width;\n size_cube.logical_height = height;\n\n auto format = format_info();\n\n \/\/ w\/h in blocks must be a multiple of block size.\n uint32_t block_width =\n xe::round_up(size_cube.logical_width, format->block_width) \/\n format->block_width;\n uint32_t block_height =\n xe::round_up(size_cube.logical_height, format->block_height) \/\n format->block_height;\n\n \/\/ Tiles are 32x32 blocks. All textures must be multiples of tile dimensions.\n uint32_t tile_width = xe::round_up(block_width, 32) \/ 32;\n uint32_t tile_height = xe::round_up(block_height, 32) \/ 32;\n size_cube.block_width = tile_width * 32;\n size_cube.block_height = tile_height * 32;\n\n uint32_t bytes_per_block =\n format->block_width * format->block_height * format->bits_per_pixel \/ 8;\n uint32_t byte_pitch = size_cube.block_width * bytes_per_block;\n\n uint32_t texel_width;\n if (!is_tiled) {\n \/\/ Each row must be a multiple of 256 in linear textures.\n byte_pitch = xe::round_up(byte_pitch, 256);\n texel_width = (byte_pitch \/ bytes_per_block) * format->block_width;\n } else {\n texel_width = size_cube.block_width * format->block_width;\n }\n\n size_cube.input_width = texel_width;\n size_cube.input_height = size_cube.block_height * format->block_height;\n size_cube.input_pitch = byte_pitch;\n\n size_cube.input_face_length = size_cube.input_pitch * size_cube.block_height;\n input_length = size_cube.input_face_length * 6;\n}\n\nbool TextureInfo::GetPackedTileOffset(const TextureInfo& texture_info,\n uint32_t* out_offset_x,\n uint32_t* out_offset_y) {\n \/\/ Tile size is 32x32, and once textures go <=16 they are packed into a\n \/\/ single tile together. The math here is insane. Most sourced\n \/\/ from graph paper and looking at dds dumps.\n \/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n \/\/ 0 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 1 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 2 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 3 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 4 x +.....8x8.....+ +............16x16............+\n \/\/ 5 +.....8x8.....+ +............16x16............+\n \/\/ 6 +.....8x8.....+ +............16x16............+\n \/\/ 7 +.....8x8.....+ +............16x16............+\n \/\/ 8 2x2 +............16x16............+\n \/\/ 9 2x2 +............16x16............+\n \/\/ 0 +............16x16............+\n \/\/ ... .....\n \/\/ This only works for square textures, or textures that are some non-pot\n \/\/ <= square. As soon as the aspect ratio goes weird, the textures start to\n \/\/ stretch across tiles.\n \/\/ if (tile_aligned(w) > tile_aligned(h)) {\n \/\/ \/\/ wider than tall, so packed horizontally\n \/\/ } else if (tile_aligned(w) < tile_aligned(h)) {\n \/\/ \/\/ taller than wide, so packed vertically\n \/\/ } else {\n \/\/ square\n \/\/ }\n \/\/ It's important to use logical sizes here, as the input sizes will be\n \/\/ for the entire packed tile set, not the actual texture.\n \/\/ The minimum dimension is what matters most: if either width or height\n \/\/ is <= 16 this mode kicks in.\n\n if (std::min(texture_info.size_2d.logical_width,\n texture_info.size_2d.logical_height) > 16) {\n \/\/ Too big, not packed.\n *out_offset_x = 0;\n *out_offset_y = 0;\n return false;\n }\n\n if (xe::log2_ceil(texture_info.size_2d.logical_width) >\n xe::log2_ceil(texture_info.size_2d.logical_height)) {\n \/\/ Wider than tall. Laid out vertically.\n *out_offset_x = 0;\n *out_offset_y = 16;\n } else {\n \/\/ Taller than wide. Laid out horizontally.\n *out_offset_x = 16;\n *out_offset_y = 0;\n }\n *out_offset_x \/= texture_info.format_info()->block_width;\n *out_offset_y \/= texture_info.format_info()->block_height;\n return true;\n}\n\n\/\/ https:\/\/github.com\/BinomialLLC\/crunch\/blob\/ea9b8d8c00c8329791256adafa8cf11e4e7942a2\/inc\/crn_decomp.h#L4108\nuint32_t TextureInfo::TiledOffset2DOuter(uint32_t y, uint32_t width,\n uint32_t log_bpp) {\n uint32_t macro = ((y >> 5) * (width >> 5)) << (log_bpp + 7);\n uint32_t micro = ((y & 6) << 2) << log_bpp;\n return macro + ((micro & ~15) << 1) + (micro & 15) +\n ((y & 8) << (3 + log_bpp)) + ((y & 1) << 4);\n}\n\nuint32_t TextureInfo::TiledOffset2DInner(uint32_t x, uint32_t y, uint32_t bpp,\n uint32_t base_offset) {\n uint32_t macro = (x >> 5) << (bpp + 7);\n uint32_t micro = (x & 7) << bpp;\n uint32_t offset = base_offset + (macro + ((micro & ~15) << 1) + (micro & 15));\n return ((offset & ~511) << 3) + ((offset & 448) << 2) + (offset & 63) +\n ((y & 16) << 7) + (((((y & 8) >> 2) + (x >> 3)) & 3) << 6);\n}\n\nuint64_t TextureInfo::hash() const {\n return XXH64(this, sizeof(TextureInfo), 0);\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xe\n<commit_msg>[GPU] Log attempts to fetch unsupported texture formats<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/gpu\/texture_info.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <cstring>\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/math.h\"\n\n#include \"third_party\/xxhash\/xxhash.h\"\n\nnamespace xe {\nnamespace gpu {\n\nusing namespace xe::gpu::xenos;\n\nbool TextureInfo::Prepare(const xe_gpu_texture_fetch_t& fetch,\n TextureInfo* out_info) {\n std::memset(out_info, 0, sizeof(TextureInfo));\n\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/cc308051(v=vs.85).aspx\n \/\/ a2xx_sq_surfaceformat\n auto& info = *out_info;\n info.guest_address = fetch.address << 12;\n\n info.dimension = static_cast<Dimension>(fetch.dimension);\n info.width = info.height = info.depth = 0;\n switch (info.dimension) {\n case Dimension::k1D:\n info.dimension = Dimension::k2D;\n info.width = fetch.size_1d.width;\n info.height = 1;\n break;\n case Dimension::k2D:\n info.width = fetch.size_2d.width;\n info.height = fetch.size_2d.height;\n break;\n case Dimension::k3D:\n info.width = fetch.size_3d.width;\n info.height = fetch.size_3d.height;\n info.depth = fetch.size_3d.depth;\n break;\n case Dimension::kCube:\n info.width = fetch.size_stack.width;\n info.height = fetch.size_stack.height;\n info.depth = fetch.size_stack.depth;\n break;\n }\n info.texture_format = static_cast<TextureFormat>(fetch.format);\n info.endianness = static_cast<Endian>(fetch.endianness);\n info.is_tiled = fetch.tiled;\n info.has_packed_mips = fetch.packed_mips;\n info.input_length = 0; \/\/ Populated below.\n\n if (info.format_info()->format == TextureFormat::kUnknown) {\n XELOGE(\"Attempting to fetch from unsupported texture format %d\",\n info.texture_format);\n return false;\n }\n\n \/\/ Must be called here when we know the format.\n switch (info.dimension) {\n case Dimension::k1D: {\n assert_always();\n } break;\n case Dimension::k2D: {\n info.CalculateTextureSizes2D(fetch.size_2d.width + 1,\n fetch.size_2d.height + 1);\n } break;\n case Dimension::k3D: {\n \/\/ TODO(benvanik): calculate size.\n return false;\n }\n case Dimension::kCube: {\n info.CalculateTextureSizesCube(fetch.size_stack.width + 1,\n fetch.size_stack.height + 1,\n fetch.size_stack.depth + 1);\n } break;\n }\n\n return true;\n}\n\nbool TextureInfo::PrepareResolve(uint32_t physical_address,\n TextureFormat texture_format, Endian endian,\n uint32_t width, uint32_t height,\n TextureInfo* out_info) {\n std::memset(out_info, 0, sizeof(TextureInfo));\n auto& info = *out_info;\n info.guest_address = physical_address;\n info.dimension = Dimension::k2D;\n assert_true(width > 0);\n assert_true(height > 0);\n info.width = width - 1;\n info.height = height - 1;\n info.texture_format = texture_format;\n info.endianness = endian;\n info.is_tiled = true;\n info.has_packed_mips = false;\n info.input_length = 0;\n\n if (info.format_info()->format == TextureFormat::kUnknown) {\n assert_true(\"Unsupported texture format\");\n return false;\n }\n\n info.CalculateTextureSizes2D(width, height);\n return true;\n}\n\nvoid TextureInfo::CalculateTextureSizes2D(uint32_t width, uint32_t height) {\n size_2d.logical_width = width;\n size_2d.logical_height = height;\n\n \/\/ Here be dragons. The values here are used in texture_cache.cc to copy\n \/\/ images and create GL textures. Changes here will impact that code.\n \/\/ TODO(benvanik): generic texture copying utility.\n\n auto format = format_info();\n\n \/\/ w\/h in blocks.\n uint32_t block_width =\n xe::round_up(size_2d.logical_width, format->block_width) \/\n format->block_width;\n uint32_t block_height =\n xe::round_up(size_2d.logical_height, format->block_height) \/\n format->block_height;\n\n \/\/ Tiles are 32x32 blocks. The pitch of all textures must a multiple of tile\n \/\/ dimensions.\n uint32_t tile_width = xe::round_up(block_width, 32) \/ 32;\n size_2d.block_width = tile_width * 32;\n size_2d.block_height = block_height;\n\n uint32_t bytes_per_block =\n format->block_width * format->block_height * format->bits_per_pixel \/ 8;\n uint32_t byte_pitch = size_2d.block_width * bytes_per_block;\n\n uint32_t texel_width;\n if (!is_tiled) {\n \/\/ Each row must be a multiple of 256 in linear textures.\n byte_pitch = xe::round_up(byte_pitch, 256);\n texel_width = (byte_pitch \/ bytes_per_block) * format->block_width;\n } else {\n texel_width = size_2d.block_width * format->block_width;\n }\n\n size_2d.input_width = texel_width;\n size_2d.input_height = size_2d.block_height * format->block_height;\n size_2d.input_pitch = byte_pitch;\n\n input_length = size_2d.input_pitch * size_2d.block_height;\n}\n\nvoid TextureInfo::CalculateTextureSizesCube(uint32_t width, uint32_t height,\n uint32_t depth) {\n assert_true(depth == 6);\n size_cube.logical_width = width;\n size_cube.logical_height = height;\n\n auto format = format_info();\n\n \/\/ w\/h in blocks must be a multiple of block size.\n uint32_t block_width =\n xe::round_up(size_cube.logical_width, format->block_width) \/\n format->block_width;\n uint32_t block_height =\n xe::round_up(size_cube.logical_height, format->block_height) \/\n format->block_height;\n\n \/\/ Tiles are 32x32 blocks. All textures must be multiples of tile dimensions.\n uint32_t tile_width = xe::round_up(block_width, 32) \/ 32;\n uint32_t tile_height = xe::round_up(block_height, 32) \/ 32;\n size_cube.block_width = tile_width * 32;\n size_cube.block_height = tile_height * 32;\n\n uint32_t bytes_per_block =\n format->block_width * format->block_height * format->bits_per_pixel \/ 8;\n uint32_t byte_pitch = size_cube.block_width * bytes_per_block;\n\n uint32_t texel_width;\n if (!is_tiled) {\n \/\/ Each row must be a multiple of 256 in linear textures.\n byte_pitch = xe::round_up(byte_pitch, 256);\n texel_width = (byte_pitch \/ bytes_per_block) * format->block_width;\n } else {\n texel_width = size_cube.block_width * format->block_width;\n }\n\n size_cube.input_width = texel_width;\n size_cube.input_height = size_cube.block_height * format->block_height;\n size_cube.input_pitch = byte_pitch;\n\n size_cube.input_face_length = size_cube.input_pitch * size_cube.block_height;\n input_length = size_cube.input_face_length * 6;\n}\n\nbool TextureInfo::GetPackedTileOffset(const TextureInfo& texture_info,\n uint32_t* out_offset_x,\n uint32_t* out_offset_y) {\n \/\/ Tile size is 32x32, and once textures go <=16 they are packed into a\n \/\/ single tile together. The math here is insane. Most sourced\n \/\/ from graph paper and looking at dds dumps.\n \/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n \/\/ 0 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 1 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 2 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 3 +.4x4.+ +.....8x8.....+ +............16x16............+\n \/\/ 4 x +.....8x8.....+ +............16x16............+\n \/\/ 5 +.....8x8.....+ +............16x16............+\n \/\/ 6 +.....8x8.....+ +............16x16............+\n \/\/ 7 +.....8x8.....+ +............16x16............+\n \/\/ 8 2x2 +............16x16............+\n \/\/ 9 2x2 +............16x16............+\n \/\/ 0 +............16x16............+\n \/\/ ... .....\n \/\/ This only works for square textures, or textures that are some non-pot\n \/\/ <= square. As soon as the aspect ratio goes weird, the textures start to\n \/\/ stretch across tiles.\n \/\/ if (tile_aligned(w) > tile_aligned(h)) {\n \/\/ \/\/ wider than tall, so packed horizontally\n \/\/ } else if (tile_aligned(w) < tile_aligned(h)) {\n \/\/ \/\/ taller than wide, so packed vertically\n \/\/ } else {\n \/\/ square\n \/\/ }\n \/\/ It's important to use logical sizes here, as the input sizes will be\n \/\/ for the entire packed tile set, not the actual texture.\n \/\/ The minimum dimension is what matters most: if either width or height\n \/\/ is <= 16 this mode kicks in.\n\n if (std::min(texture_info.size_2d.logical_width,\n texture_info.size_2d.logical_height) > 16) {\n \/\/ Too big, not packed.\n *out_offset_x = 0;\n *out_offset_y = 0;\n return false;\n }\n\n if (xe::log2_ceil(texture_info.size_2d.logical_width) >\n xe::log2_ceil(texture_info.size_2d.logical_height)) {\n \/\/ Wider than tall. Laid out vertically.\n *out_offset_x = 0;\n *out_offset_y = 16;\n } else {\n \/\/ Taller than wide. Laid out horizontally.\n *out_offset_x = 16;\n *out_offset_y = 0;\n }\n *out_offset_x \/= texture_info.format_info()->block_width;\n *out_offset_y \/= texture_info.format_info()->block_height;\n return true;\n}\n\n\/\/ https:\/\/github.com\/BinomialLLC\/crunch\/blob\/ea9b8d8c00c8329791256adafa8cf11e4e7942a2\/inc\/crn_decomp.h#L4108\nuint32_t TextureInfo::TiledOffset2DOuter(uint32_t y, uint32_t width,\n uint32_t log_bpp) {\n uint32_t macro = ((y >> 5) * (width >> 5)) << (log_bpp + 7);\n uint32_t micro = ((y & 6) << 2) << log_bpp;\n return macro + ((micro & ~15) << 1) + (micro & 15) +\n ((y & 8) << (3 + log_bpp)) + ((y & 1) << 4);\n}\n\nuint32_t TextureInfo::TiledOffset2DInner(uint32_t x, uint32_t y, uint32_t bpp,\n uint32_t base_offset) {\n uint32_t macro = (x >> 5) << (bpp + 7);\n uint32_t micro = (x & 7) << bpp;\n uint32_t offset = base_offset + (macro + ((micro & ~15) << 1) + (micro & 15));\n return ((offset & ~511) << 3) + ((offset & 448) << 2) + (offset & 63) +\n ((y & 16) << 7) + (((((y & 8) >> 2) + (x >> 3)) & 3) << 6);\n}\n\nuint64_t TextureInfo::hash() const {\n return XXH64(this, sizeof(TextureInfo), 0);\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xe\n<|endoftext|>"} {"text":"<commit_before>\/\/===- unittests\/StaticAnalyzer\/SymbolReaperTest.cpp ----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugReporter.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugType.h\"\n#include \"clang\/CrossTU\/CrossTranslationUnit.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ExprEngine.h\"\n#include \"clang\/StaticAnalyzer\/Frontend\/AnalysisConsumer.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace clang {\nnamespace ento {\nnamespace {\n\nusing namespace ast_matchers;\n\n\/\/ A re-usable consumer that constructs ExprEngine out of CompilerInvocation.\n\/\/ TODO: Actually re-use it when we write our second test.\nclass ExprEngineConsumer : public ASTConsumer {\nprotected:\n CompilerInstance &C;\n\nprivate:\n \/\/ We need to construct all of these in order to construct ExprEngine.\n CheckerManager ChkMgr;\n cross_tu::CrossTranslationUnitContext CTU;\n PathDiagnosticConsumers Consumers;\n AnalysisManager AMgr;\n SetOfConstDecls VisitedCallees;\n FunctionSummariesTy FS;\n\nprotected:\n ExprEngine Eng;\n\n \/\/ Find a declaration in the current AST by name. This has nothing to do\n \/\/ with ExprEngine but turns out to be handy.\n \/\/ TODO: There's probably a better place for it.\n template <typename T>\n const T *findDeclByName(const Decl *Where, StringRef Name) {\n auto Matcher = decl(hasDescendant(namedDecl(hasName(Name)).bind(\"d\")));\n auto Matches = match(Matcher, *Where, Eng.getContext());\n assert(Matches.size() == 1 && \"Ambiguous name!\");\n const T *Node = selectFirst<T>(\"d\", Matches);\n assert(Node && \"Name not found!\");\n return Node;\n }\n\npublic:\n ExprEngineConsumer(CompilerInstance &C)\n : C(C), ChkMgr(C.getASTContext(), *C.getAnalyzerOpts()), CTU(C),\n Consumers(),\n AMgr(C.getASTContext(), C.getDiagnostics(), Consumers,\n CreateRegionStoreManager, CreateRangeConstraintManager, &ChkMgr,\n *C.getAnalyzerOpts()),\n VisitedCallees(), FS(),\n Eng(CTU, AMgr, &VisitedCallees, &FS, ExprEngine::Inline_Regular) {}\n};\n\nclass SuperRegionLivenessConsumer : public ExprEngineConsumer {\n void performTest(const Decl *D) {\n const auto *FD = findDeclByName<FieldDecl>(D, \"x\");\n const auto *VD = findDeclByName<VarDecl>(D, \"s\");\n assert(FD && VD);\n\n \/\/ The variable must belong to a stack frame,\n \/\/ otherwise SymbolReaper would think it's a global.\n const StackFrameContext *SFC =\n Eng.getAnalysisDeclContextManager().getStackFrame(D);\n\n \/\/ Create regions for 's' and 's.x'.\n const VarRegion *VR = Eng.getRegionManager().getVarRegion(VD, SFC);\n const FieldRegion *FR = Eng.getRegionManager().getFieldRegion(FD, VR);\n\n \/\/ Pass a null location context to the SymbolReaper so that\n \/\/ it was thinking that the variable is dead.\n SymbolReaper SymReaper((StackFrameContext *)nullptr, (Stmt *)nullptr,\n Eng.getSymbolManager(), Eng.getStoreManager());\n\n SymReaper.markLive(FR);\n EXPECT_TRUE(SymReaper.isLiveRegion(VR));\n }\n\npublic:\n SuperRegionLivenessConsumer(CompilerInstance &C) : ExprEngineConsumer(C) {}\n ~SuperRegionLivenessConsumer() override {}\n\n bool HandleTopLevelDecl(DeclGroupRef DG) override {\n for (const auto *D : DG)\n performTest(D);\n return true;\n }\n};\n\nclass SuperRegionLivenessAction: public ASTFrontendAction {\npublic:\n SuperRegionLivenessAction() {}\n std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,\n StringRef File) override {\n auto Consumer = llvm::make_unique<SuperRegionLivenessConsumer>(Compiler);\n return Consumer;\n }\n};\n\n\/\/ Test that marking s.x as live would also make s live.\nTEST(SymbolReaper, SuperRegionLiveness) {\n EXPECT_TRUE(tooling::runToolOnCode(new SuperRegionLivenessAction,\n \"void foo() { struct S { int x; } s; }\"));\n}\n\n} \/\/ namespace\n} \/\/ namespace ento\n} \/\/ namespace clang\n<commit_msg>[analyzer] A speculative fix for buildbot failures in the new SymbolReaperTest.<commit_after>\/\/===- unittests\/StaticAnalyzer\/SymbolReaperTest.cpp ----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugReporter.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugType.h\"\n#include \"clang\/CrossTU\/CrossTranslationUnit.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ExprEngine.h\"\n#include \"clang\/StaticAnalyzer\/Frontend\/AnalysisConsumer.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace clang {\nnamespace ento {\nnamespace {\n\nusing namespace ast_matchers;\n\n\/\/ A re-usable consumer that constructs ExprEngine out of CompilerInvocation.\n\/\/ TODO: Actually re-use it when we write our second test.\nclass ExprEngineConsumer : public ASTConsumer {\nprotected:\n CompilerInstance &C;\n\nprivate:\n \/\/ We need to construct all of these in order to construct ExprEngine.\n CheckerManager ChkMgr;\n cross_tu::CrossTranslationUnitContext CTU;\n PathDiagnosticConsumers Consumers;\n AnalysisManager AMgr;\n SetOfConstDecls VisitedCallees;\n FunctionSummariesTy FS;\n\nprotected:\n ExprEngine Eng;\n\n \/\/ Find a declaration in the current AST by name. This has nothing to do\n \/\/ with ExprEngine but turns out to be handy.\n \/\/ TODO: There's probably a better place for it.\n template <typename T>\n const T *findDeclByName(const Decl *Where, StringRef Name) {\n auto Matcher = decl(hasDescendant(namedDecl(hasName(Name)).bind(\"d\")));\n auto Matches = match(Matcher, *Where, Eng.getContext());\n assert(Matches.size() == 1 && \"Ambiguous name!\");\n const T *Node = selectFirst<T>(\"d\", Matches);\n assert(Node && \"Name not found!\");\n return Node;\n }\n\npublic:\n ExprEngineConsumer(CompilerInstance &C)\n : C(C), ChkMgr(C.getASTContext(), *C.getAnalyzerOpts()), CTU(C),\n Consumers(),\n AMgr(C.getASTContext(), C.getDiagnostics(), Consumers,\n CreateRegionStoreManager, CreateRangeConstraintManager, &ChkMgr,\n *C.getAnalyzerOpts()),\n VisitedCallees(), FS(),\n Eng(CTU, AMgr, &VisitedCallees, &FS, ExprEngine::Inline_Regular) {}\n};\n\nclass SuperRegionLivenessConsumer : public ExprEngineConsumer {\n void performTest(const Decl *D) {\n const auto *FD = findDeclByName<FieldDecl>(D, \"x\");\n const auto *VD = findDeclByName<VarDecl>(D, \"s\");\n assert(FD && VD);\n\n \/\/ The variable must belong to a stack frame,\n \/\/ otherwise SymbolReaper would think it's a global.\n const StackFrameContext *SFC =\n Eng.getAnalysisDeclContextManager().getStackFrame(D);\n\n \/\/ Create regions for 's' and 's.x'.\n const VarRegion *VR = Eng.getRegionManager().getVarRegion(VD, SFC);\n const FieldRegion *FR = Eng.getRegionManager().getFieldRegion(FD, VR);\n\n \/\/ Pass a null location context to the SymbolReaper so that\n \/\/ it was thinking that the variable is dead.\n SymbolReaper SymReaper((StackFrameContext *)nullptr, (Stmt *)nullptr,\n Eng.getSymbolManager(), Eng.getStoreManager());\n\n SymReaper.markLive(FR);\n EXPECT_TRUE(SymReaper.isLiveRegion(VR));\n }\n\npublic:\n SuperRegionLivenessConsumer(CompilerInstance &C) : ExprEngineConsumer(C) {}\n ~SuperRegionLivenessConsumer() override {}\n\n bool HandleTopLevelDecl(DeclGroupRef DG) override {\n for (const auto *D : DG)\n performTest(D);\n return true;\n }\n};\n\nclass SuperRegionLivenessAction: public ASTFrontendAction {\npublic:\n SuperRegionLivenessAction() {}\n std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,\n StringRef File) override {\n return llvm::make_unique<SuperRegionLivenessConsumer>(Compiler);\n }\n};\n\n\/\/ Test that marking s.x as live would also make s live.\nTEST(SymbolReaper, SuperRegionLiveness) {\n EXPECT_TRUE(tooling::runToolOnCode(new SuperRegionLivenessAction,\n \"void foo() { struct S { int x; } s; }\"));\n}\n\n} \/\/ namespace\n} \/\/ namespace ento\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"<commit_before>#include<iostream>\n#include<SDL2\/SDL.h>\n\nSDL_Window *window = nullptr;\nSDL_Renderer *renderer = nullptr;\n\nint main(int argc, char **args)\n{\n if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {\n std::cout << \"SDL_Init Error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n const char windowTitle[] = \"Chapter 1: Setting up SDL\";\n window = SDL_CreateWindow(windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);\n\n if (window == nullptr) {\n std::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n renderer = SDL_CreateRenderer(window, -1, 0);\n\n SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\n SDL_RenderClear(renderer);\n\n SDL_RenderPresent(renderer);\n\n SDL_Delay(5000);\n\n SDL_Quit();\n\n return 0;\n}\n<commit_msg>Modified std::cout to std::cerr in error messages.<commit_after>#include<iostream>\n#include<SDL2\/SDL.h>\n\nSDL_Window *window = nullptr;\nSDL_Renderer *renderer = nullptr;\n\nint main(int argc, char **args)\n{\n if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {\n std::cerr << \"SDL_Init Error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n const char windowTitle[] = \"Chapter 1: Setting up SDL\";\n window = SDL_CreateWindow(windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);\n\n if (window == nullptr) {\n std::cerr << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n return 1;\n }\n\n renderer = SDL_CreateRenderer(window, -1, 0);\n\n SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\n SDL_RenderClear(renderer);\n\n SDL_RenderPresent(renderer);\n\n SDL_Delay(5000);\n\n SDL_Quit();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2021 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"d3d12_test.h\"\n\nRD_TEST(D3D12_Parameter_Zoo, D3D12GraphicsTest)\n{\n static constexpr const char *Description =\n \"General tests of parameters known to cause problems - e.g. optional values that should be \"\n \"ignored, edge cases, special values, etc.\";\n\n std::string pixel = R\"EOSHADER(\n\nTexture2D<float> empty : register(t50);\n\nfloat4 main() : SV_Target0\n{\n\treturn float4(0, 1, 0, 1) + empty.Load(int3(0,0,0));\n}\n\n)EOSHADER\";\n\n int main()\n {\n \/\/ initialise, create window, create device, etc\n if(!Init())\n return 3;\n\n ID3DBlobPtr vsblob = Compile(D3DDefaultVertex, \"main\", \"vs_4_0\");\n ID3DBlobPtr psblob = Compile(pixel, \"main\", \"ps_4_0\");\n\n uint32_t indices[1024 \/ 4] = {0, 1, 2};\n\n ID3D12ResourcePtr vb = MakeBuffer().Data(DefaultTri);\n ID3D12ResourcePtr ib = MakeBuffer().Data(indices);\n\n ID3D12RootSignaturePtr sig = MakeSig({\n \/\/ table that's larger than the descriptor heap we'll bind\n tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 50, 999, 0),\n });\n\n ResourceBarrier(vb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);\n\n D3D12PSOCreator psoCreator = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n psoCreator.GraphicsDesc.StreamOutput.NumEntries = 0;\n psoCreator.GraphicsDesc.StreamOutput.pSODeclaration = (D3D12_SO_DECLARATION_ENTRY *)0x3456;\n psoCreator.GraphicsDesc.StreamOutput.NumStrides = 0xcccccccc;\n psoCreator.GraphicsDesc.StreamOutput.pBufferStrides = (UINT *)0x1234;\n\n ID3D12RootSignaturePtr duplicateSig = MakeSig(\n {\n cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0),\n constParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 1, 1),\n },\n D3D12_ROOT_SIGNATURE_FLAG_NONE);\n\n ID3D12DescriptorHeapPtr descHeap;\n\n {\n D3D12_DESCRIPTOR_HEAP_DESC desc;\n desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;\n desc.NodeMask = 1;\n desc.NumDescriptors = 4;\n desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;\n CHECK_HR(dev->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&descHeap));\n }\n\n D3D12_GPU_DESCRIPTOR_HANDLE descGPUHandle = descHeap->GetGPUDescriptorHandleForHeapStart();\n\n D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};\n srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;\n srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;\n srvDesc.Texture2D.MipLevels = 1;\n\n dev->CreateShaderResourceView(NULL, &srvDesc, descHeap->GetCPUDescriptorHandleForHeapStart());\n\n ID3D12PipelineStatePtr pso = psoCreator;\n\n \/\/ if D3D12.4 (??) is available, use different interfaces\n if(dev4)\n {\n GPUSync();\n\n D3D12_RESOURCE_DESC desc;\n desc.Alignment = 0;\n desc.DepthOrArraySize = 1;\n desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;\n desc.Flags = D3D12_RESOURCE_FLAG_NONE;\n desc.Format = DXGI_FORMAT_UNKNOWN;\n desc.Height = 1;\n desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;\n desc.Width = sizeof(DefaultTri);\n desc.MipLevels = 1;\n desc.SampleDesc.Count = 1;\n desc.SampleDesc.Quality = 0;\n\n D3D12_HEAP_DESC heapDesc;\n heapDesc.SizeInBytes = 4096;\n heapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;\n heapDesc.Alignment = 0;\n heapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;\n heapDesc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;\n heapDesc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;\n heapDesc.Properties.CreationNodeMask = 1;\n heapDesc.Properties.VisibleNodeMask = 1;\n\n CHECK_HR(dev4->CreateCommittedResource1(&heapDesc.Properties, D3D12_HEAP_FLAG_NONE, &desc,\n D3D12_RESOURCE_STATE_COMMON, NULL, NULL,\n __uuidof(ID3D12Resource), (void **)&vb));\n\n SetBufferData(vb, D3D12_RESOURCE_STATE_COMMON, (const byte *)DefaultTri, sizeof(DefaultTri));\n\n ID3D12Heap1Ptr heap;\n CHECK_HR(dev4->CreateHeap1(&heapDesc, NULL, __uuidof(ID3D12Heap1), (void **)&heap));\n\n desc.Width = sizeof(indices);\n\n CHECK_HR(dev4->CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, NULL,\n __uuidof(ID3D12Resource), (void **)&ib));\n\n SetBufferData(ib, D3D12_RESOURCE_STATE_COMMON, (const byte *)indices, sizeof(indices));\n }\n\n ID3D12ResourcePtr rtvtex = MakeTexture(DXGI_FORMAT_R32G32B32A32_FLOAT, 4, 4)\n .RTV()\n .InitialState(D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n ID3D12CommandSignaturePtr cmdsig = MakeCommandSig(NULL, {vbArg(0), drawArg()});\n ID3D12ResourcePtr argBuf = MakeBuffer().Upload().Size(1024);\n\n while(Running())\n {\n ID3D12GraphicsCommandListPtr cmd = GetCommandBuffer();\n\n Reset(cmd);\n\n ID3D12DebugCommandListPtr debug = cmd;\n\n ID3D12ResourcePtr bb = StartUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n \/\/ force duplicate signature to be used\n cmd->SetGraphicsRootSignature(duplicateSig);\n\n if(debug)\n debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_RENDER_TARGET, 0);\n\n D3D12_CPU_DESCRIPTOR_HANDLE rtv =\n MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(0);\n\n ClearRenderTargetView(cmd, rtv, {1.0f, 0.0f, 1.0f, 1.0f});\n\n cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n cmd->SetDescriptorHeaps(1, &descHeap.GetInterfacePtr());\n\n IASetVertexBuffer(cmd, vb, sizeof(DefaultA2V), 0);\n D3D12_INDEX_BUFFER_VIEW view;\n view.BufferLocation = ib->GetGPUVirtualAddress();\n view.Format = DXGI_FORMAT_R32_UINT;\n view.SizeInBytes = 1024;\n cmd->IASetIndexBuffer(&view);\n cmd->SetPipelineState(pso);\n cmd->SetGraphicsRootSignature(sig);\n cmd->SetGraphicsRootDescriptorTable(0, descGPUHandle);\n\n RSSetViewport(cmd, {0.0f, 0.0f, (float)screenWidth, (float)screenHeight, 0.0f, 1.0f});\n RSSetScissorRect(cmd, {0, 0, screenWidth, screenHeight});\n\n \/\/ trash slots 3 and 4\n D3D12_CPU_DESCRIPTOR_HANDLE rtv3 = MakeRTV(rtvtex).CreateCPU(3);\n D3D12_CPU_DESCRIPTOR_HANDLE rtv4 = MakeRTV(rtvtex).CreateCPU(4);\n\n \/\/ write the proper RTV to slot 3\n MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(3);\n\n \/\/ copy to slot 4\n dev->CopyDescriptorsSimple(1, rtv4, rtv3, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);\n\n \/\/ bind from slot 4\n cmd->OMSetRenderTargets(1, &rtv4, FALSE, NULL);\n\n \/\/ trash RTV slots 3 and 4 again\n MakeRTV(rtvtex).CreateCPU(3);\n MakeRTV(rtvtex).CreateCPU(4);\n\n setMarker(cmd, \"Color Draw\");\n\n cmd->DrawIndexedInstanced(3, 1, 0, 0, 0);\n\n setMarker(cmd, \"Empty indirect execute\");\n\n cmd->ExecuteIndirect(cmdsig, 0, argBuf, 0, NULL, 0);\n\n FinishUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n if(debug)\n {\n BOOL wrong = debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_COPY_DEST, 0);\n BOOL right = debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_PRESENT, 0);\n\n if(wrong == TRUE)\n TEST_WARN(\"Didn't get the expected return value from AssertResourceState(COPY_DEST)\");\n if(right == FALSE)\n TEST_WARN(\"Didn't get the expected return value from AssertResourceState(PRESENT)\");\n }\n\n cmd->Close();\n\n Submit({cmd});\n\n Present();\n }\n\n return 0;\n }\n};\n\nREGISTER_TEST();\n<commit_msg>Test stream-created PSOs create correctly<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2021 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"d3d12_test.h\"\n\nRD_TEST(D3D12_Parameter_Zoo, D3D12GraphicsTest)\n{\n static constexpr const char *Description =\n \"General tests of parameters known to cause problems - e.g. optional values that should be \"\n \"ignored, edge cases, special values, etc.\";\n\n std::string pixel = R\"EOSHADER(\n\nTexture2D<float> empty : register(t50);\n\nfloat4 main() : SV_Target0\n{\n\treturn float4(0, 1, 0, 1) + empty.Load(int3(0,0,0));\n}\n\n)EOSHADER\";\n\n int main()\n {\n \/\/ initialise, create window, create device, etc\n if(!Init())\n return 3;\n\n ID3DBlobPtr vsblob = Compile(D3DDefaultVertex, \"main\", \"vs_4_0\");\n ID3DBlobPtr psblob = Compile(pixel, \"main\", \"ps_4_0\");\n\n uint32_t indices[1024 \/ 4] = {0, 1, 2};\n\n ID3D12ResourcePtr vb = MakeBuffer().Data(DefaultTri);\n ID3D12ResourcePtr ib = MakeBuffer().Data(indices);\n\n ID3D12RootSignaturePtr sig = MakeSig({\n \/\/ table that's larger than the descriptor heap we'll bind\n tableParam(D3D12_SHADER_VISIBILITY_PIXEL, D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 50, 999, 0),\n });\n\n ResourceBarrier(vb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);\n\n D3D12PSOCreator psoCreator = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n psoCreator.GraphicsDesc.StreamOutput.NumEntries = 0;\n psoCreator.GraphicsDesc.StreamOutput.pSODeclaration = (D3D12_SO_DECLARATION_ENTRY *)0x3456;\n psoCreator.GraphicsDesc.StreamOutput.NumStrides = 0xcccccccc;\n psoCreator.GraphicsDesc.StreamOutput.pBufferStrides = (UINT *)0x1234;\n\n ID3D12RootSignaturePtr duplicateSig = MakeSig(\n {\n cbvParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 0),\n constParam(D3D12_SHADER_VISIBILITY_PIXEL, 0, 1, 1),\n },\n D3D12_ROOT_SIGNATURE_FLAG_NONE);\n\n ID3D12DescriptorHeapPtr descHeap;\n\n {\n D3D12_DESCRIPTOR_HEAP_DESC desc;\n desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;\n desc.NodeMask = 1;\n desc.NumDescriptors = 4;\n desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;\n CHECK_HR(dev->CreateDescriptorHeap(&desc, __uuidof(ID3D12DescriptorHeap), (void **)&descHeap));\n }\n\n D3D12_GPU_DESCRIPTOR_HANDLE descGPUHandle = descHeap->GetGPUDescriptorHandleForHeapStart();\n\n D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};\n srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;\n srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;\n srvDesc.Texture2D.MipLevels = 1;\n\n dev->CreateShaderResourceView(NULL, &srvDesc, descHeap->GetCPUDescriptorHandleForHeapStart());\n\n ID3D12PipelineStatePtr pso = psoCreator;\n ID3D12PipelineStatePtr pso2;\n\n if(dev2)\n {\n struct StreamStructBase\n {\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE rootsig_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE;\n UINT padding0;\n ID3D12RootSignature *pRootSignature;\n\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE vs_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS;\n UINT padding1;\n D3D12_SHADER_BYTECODE vs = {};\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE ps_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS;\n UINT padding2;\n D3D12_SHADER_BYTECODE ps = {};\n\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE input_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT;\n D3D12_INPUT_LAYOUT_DESC InputLayout;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE mask_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK;\n UINT SampleMask;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE dsv_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT;\n DXGI_FORMAT DSVFormat;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE blend_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND;\n D3D12_BLEND_DESC BlendState;\n UINT padding3;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE rast_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER;\n D3D12_RASTERIZER_DESC RasterizerState;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE depth_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL;\n D3D12_DEPTH_STENCIL_DESC DepthStencilState;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE prim_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY;\n D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType;\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE rtv_type =\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS;\n D3D12_RT_FORMAT_ARRAY RTVFormats;\n };\n\n struct StreamStructMesh : StreamStructBase\n {\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE as_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS;\n UINT padding3;\n D3D12_SHADER_BYTECODE as = {};\n D3D12_PIPELINE_STATE_SUBOBJECT_TYPE ms_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS;\n UINT padding4;\n D3D12_SHADER_BYTECODE ms = {};\n } streamStruct;\n\n streamStruct.InputLayout = psoCreator.GraphicsDesc.InputLayout;\n streamStruct.pRootSignature = psoCreator.GraphicsDesc.pRootSignature;\n streamStruct.vs = psoCreator.GraphicsDesc.VS;\n streamStruct.ps = psoCreator.GraphicsDesc.PS;\n streamStruct.SampleMask = psoCreator.GraphicsDesc.SampleMask;\n streamStruct.DSVFormat = psoCreator.GraphicsDesc.DSVFormat;\n streamStruct.BlendState = psoCreator.GraphicsDesc.BlendState;\n streamStruct.RasterizerState = psoCreator.GraphicsDesc.RasterizerState;\n streamStruct.DepthStencilState = psoCreator.GraphicsDesc.DepthStencilState;\n streamStruct.PrimitiveTopologyType = psoCreator.GraphicsDesc.PrimitiveTopologyType;\n memcpy(&streamStruct.RTVFormats.RTFormats, &psoCreator.GraphicsDesc.RTVFormats,\n sizeof(D3D12_RT_FORMAT_ARRAY));\n streamStruct.RTVFormats.NumRenderTargets = 1;\n\n D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {};\n streamDesc.pPipelineStateSubobjectStream = &streamStruct;\n streamDesc.SizeInBytes = sizeof(StreamStructMesh);\n\n \/\/ if the device understands the options7 query we assume it can handle mesh shader structs?\n HRESULT hr = dev2->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &opts7, sizeof(opts7));\n if(hr != S_OK)\n {\n streamDesc.SizeInBytes = sizeof(StreamStructBase);\n }\n\n hr = dev2->CreatePipelineState(&streamDesc, __uuidof(ID3D12PipelineState), (void **)&pso2);\n\n TEST_ASSERT(hr == S_OK, \"Pipe created\");\n }\n\n \/\/ if D3D12.4 (??) is available, use different interfaces\n if(dev4)\n {\n GPUSync();\n\n D3D12_RESOURCE_DESC desc;\n desc.Alignment = 0;\n desc.DepthOrArraySize = 1;\n desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;\n desc.Flags = D3D12_RESOURCE_FLAG_NONE;\n desc.Format = DXGI_FORMAT_UNKNOWN;\n desc.Height = 1;\n desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;\n desc.Width = sizeof(DefaultTri);\n desc.MipLevels = 1;\n desc.SampleDesc.Count = 1;\n desc.SampleDesc.Quality = 0;\n\n D3D12_HEAP_DESC heapDesc;\n heapDesc.SizeInBytes = 4096;\n heapDesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;\n heapDesc.Alignment = 0;\n heapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;\n heapDesc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;\n heapDesc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;\n heapDesc.Properties.CreationNodeMask = 1;\n heapDesc.Properties.VisibleNodeMask = 1;\n\n CHECK_HR(dev4->CreateCommittedResource1(&heapDesc.Properties, D3D12_HEAP_FLAG_NONE, &desc,\n D3D12_RESOURCE_STATE_COMMON, NULL, NULL,\n __uuidof(ID3D12Resource), (void **)&vb));\n\n SetBufferData(vb, D3D12_RESOURCE_STATE_COMMON, (const byte *)DefaultTri, sizeof(DefaultTri));\n\n ID3D12Heap1Ptr heap;\n CHECK_HR(dev4->CreateHeap1(&heapDesc, NULL, __uuidof(ID3D12Heap1), (void **)&heap));\n\n desc.Width = sizeof(indices);\n\n CHECK_HR(dev4->CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, NULL,\n __uuidof(ID3D12Resource), (void **)&ib));\n\n SetBufferData(ib, D3D12_RESOURCE_STATE_COMMON, (const byte *)indices, sizeof(indices));\n }\n\n ID3D12ResourcePtr rtvtex = MakeTexture(DXGI_FORMAT_R32G32B32A32_FLOAT, 4, 4)\n .RTV()\n .InitialState(D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n ID3D12CommandSignaturePtr cmdsig = MakeCommandSig(NULL, {vbArg(0), drawArg()});\n ID3D12ResourcePtr argBuf = MakeBuffer().Upload().Size(1024);\n\n while(Running())\n {\n ID3D12GraphicsCommandListPtr cmd = GetCommandBuffer();\n\n Reset(cmd);\n\n ID3D12DebugCommandListPtr debug = cmd;\n\n ID3D12ResourcePtr bb = StartUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n \/\/ force duplicate signature to be used\n cmd->SetGraphicsRootSignature(duplicateSig);\n\n if(debug)\n debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_RENDER_TARGET, 0);\n\n D3D12_CPU_DESCRIPTOR_HANDLE rtv =\n MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(0);\n\n ClearRenderTargetView(cmd, rtv, {1.0f, 0.0f, 1.0f, 1.0f});\n\n cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n cmd->SetDescriptorHeaps(1, &descHeap.GetInterfacePtr());\n\n IASetVertexBuffer(cmd, vb, sizeof(DefaultA2V), 0);\n D3D12_INDEX_BUFFER_VIEW view;\n view.BufferLocation = ib->GetGPUVirtualAddress();\n view.Format = DXGI_FORMAT_R32_UINT;\n view.SizeInBytes = 1024;\n cmd->IASetIndexBuffer(&view);\n if(pso2)\n cmd->SetPipelineState(pso2);\n cmd->SetPipelineState(pso);\n cmd->SetGraphicsRootSignature(sig);\n cmd->SetGraphicsRootDescriptorTable(0, descGPUHandle);\n\n RSSetViewport(cmd, {0.0f, 0.0f, (float)screenWidth, (float)screenHeight, 0.0f, 1.0f});\n RSSetScissorRect(cmd, {0, 0, screenWidth, screenHeight});\n\n \/\/ trash slots 3 and 4\n D3D12_CPU_DESCRIPTOR_HANDLE rtv3 = MakeRTV(rtvtex).CreateCPU(3);\n D3D12_CPU_DESCRIPTOR_HANDLE rtv4 = MakeRTV(rtvtex).CreateCPU(4);\n\n \/\/ write the proper RTV to slot 3\n MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(3);\n\n \/\/ copy to slot 4\n dev->CopyDescriptorsSimple(1, rtv4, rtv3, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);\n\n \/\/ bind from slot 4\n cmd->OMSetRenderTargets(1, &rtv4, FALSE, NULL);\n\n \/\/ trash RTV slots 3 and 4 again\n MakeRTV(rtvtex).CreateCPU(3);\n MakeRTV(rtvtex).CreateCPU(4);\n\n setMarker(cmd, \"Color Draw\");\n\n cmd->DrawIndexedInstanced(3, 1, 0, 0, 0);\n\n setMarker(cmd, \"Empty indirect execute\");\n\n cmd->ExecuteIndirect(cmdsig, 0, argBuf, 0, NULL, 0);\n\n FinishUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n if(debug)\n {\n BOOL wrong = debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_COPY_DEST, 0);\n BOOL right = debug->AssertResourceState(bb, D3D12_RESOURCE_STATE_PRESENT, 0);\n\n if(wrong == TRUE)\n TEST_WARN(\"Didn't get the expected return value from AssertResourceState(COPY_DEST)\");\n if(right == FALSE)\n TEST_WARN(\"Didn't get the expected return value from AssertResourceState(PRESENT)\");\n }\n\n cmd->Close();\n\n Submit({cmd});\n\n Present();\n }\n\n return 0;\n }\n};\n\nREGISTER_TEST();\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/ Author: Toby D. Young, Polish Academy of Sciences, 2008-2013\n\/\/\n\/\/ Copyright (C) 2009-2013 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/lac\/slepc_solver.h>\n\n#ifdef DEAL_II_USE_SLEPC\n\n# include <deal.II\/lac\/petsc_matrix_base.h>\n# include <deal.II\/lac\/petsc_vector_base.h>\n# include <deal.II\/lac\/petsc_vector.h>\n# include <deal.II\/lac\/slepc_spectral_transformation.h>\n\n# include <cmath>\n# include <vector>\n\n# include <petscversion.h>\n# include <slepcversion.h>\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace SLEPcWrappers\n{\n\n SolverBase::SolverData::~SolverData ()\n {\n \/\/ Destroy the solver object.\n#if DEAL_II_PETSC_VERSION_LT(3,2,0)\n int ierr = EPSDestroy (eps);\n#else\n int ierr = EPSDestroy (&eps);\n#endif\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n SolverBase::SolverBase (SolverControl &cn,\n const MPI_Comm &mpi_communicator)\n :\n solver_control (cn),\n mpi_communicator (mpi_communicator),\n set_which (EPS_LARGEST_MAGNITUDE),\n opA (NULL), opB (NULL),\n initial_vector (NULL),\n transformation (NULL)\n {}\n\n SolverBase::~SolverBase ()\n {}\n\n void\n SolverBase::set_matrices (const PETScWrappers::MatrixBase &A)\n {\n \/\/ standard eigenspectrum problem\n opA = &A;\n opB = NULL;\n }\n\n void\n SolverBase::set_matrices (const PETScWrappers::MatrixBase &A,\n const PETScWrappers::MatrixBase &B)\n {\n \/\/ generalized eigenspectrum problem\n opA = &A;\n opB = &B;\n }\n\n void\n SolverBase::set_initial_vector (const PETScWrappers::VectorBase &this_initial_vector)\n {\n initial_vector = (&this_initial_vector);\n }\n\n void\n SolverBase::set_transformation (SLEPcWrappers::TransformationBase &this_transformation)\n {\n transformation = &this_transformation;\n }\n\n void\n SolverBase::set_which_eigenpairs (const EPSWhich eps_which)\n {\n set_which = eps_which;\n }\n\n void\n SolverBase::solve (const unsigned int n_eigenvectors, unsigned int *n_converged)\n {\n int ierr;\n\n AssertThrow (solver_data.get() == 0, ExcSLEPcWrappersUsageError());\n solver_data.reset (new SolverData());\n\n \/\/ create eigensolver context and set operators\n ierr = EPSCreate (mpi_communicator, &solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set eigenspectrum problem type (general\/standard)\n AssertThrow (opA, ExcSLEPcWrappersUsageError());\n if (opB)\n ierr = EPSSetOperators (solver_data->eps, *opA, *opB);\n else\n ierr = EPSSetOperators (solver_data->eps, *opA, PETSC_NULL);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set the initial vector(s) if any\n if (initial_vector && initial_vector->size() != 0)\n {\n\n#if DEAL_II_PETSC_VERSION_LT(3,1,0)\n ierr = EPSSetInitialVector (solver_data->eps, *initial_vector);\n#else\n Vec this_vector = *initial_vector;\n ierr = EPSSetInitialSpace (solver_data->eps, 1, &this_vector);\n#endif\n\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/\/ set transformation type if any\n if (transformation)\n transformation->set_context(solver_data->eps);\n\n \/\/ set runtime options\n set_solver_type (solver_data->eps);\n\n \/\/ set which portion of the eigenspectrum to solve for\n ierr = EPSSetWhichEigenpairs (solver_data->eps, set_which);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set number of eigenvectors to compute\n ierr = EPSSetDimensions (solver_data->eps, n_eigenvectors,\n PETSC_DECIDE, PETSC_DECIDE);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set the solve options to the eigenvalue problem solver context\n ierr = EPSSetFromOptions (solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ solve the eigensystem\n ierr = EPSSolve (solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ get number of converged eigenstates\n ierr = EPSGetConverged (solver_data->eps,\n#ifdef PETSC_USE_64BIT_INDICES\n reinterpret_cast<PetscInt *>(n_converged));\n#else\n reinterpret_cast<int *>(n_converged));\n#endif\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n void\n SolverBase::get_eigenpair (const unsigned int index,\n#ifndef PETSC_USE_COMPLEX\n double &kr,\n#else\n std::complex<double> &kr,\n#endif\n PETScWrappers::VectorBase &vr)\n {\n AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError());\n\n \/\/ get converged eigenpair\n int ierr = EPSGetEigenpair (solver_data->eps, index,\n &kr, PETSC_NULL, vr, PETSC_NULL);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n\n void\n SolverBase::reset ()\n {\n AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError());\n\n \/\/ destroy solver object.\n solver_data.reset ();\n }\n\n EPS *\n SolverBase::get_EPS ()\n {\n if (solver_data.get() == 0)\n return NULL;\n\n return &solver_data->eps;\n }\n\n \/* ---------------------- SolverControls ----------------------- *\/\n SolverControl &\n SolverBase::control () const\n {\n return solver_control;\n }\n\n int\n SolverBase::convergence_test (EPS \/*eps*\/,\n#ifdef PETSC_USE_64BIT_INDICES\n const PetscInt iteration,\n#else\n const int iteration,\n#endif\n const PetscReal residual_norm,\n EPSConvergedReason *reason,\n void *solver_control_x)\n {\n SolverControl &solver_control\n = *reinterpret_cast<SolverControl *>(solver_control_x);\n\n const SolverControl::State state\n = solver_control.check (iteration, residual_norm);\n\n switch (state)\n {\n case ::dealii::SolverControl::iterate:\n *reason = EPS_CONVERGED_ITERATING;\n break;\n\n case ::dealii::SolverControl::success:\n *reason = static_cast<EPSConvergedReason>(1);\n break;\n\n case ::dealii::SolverControl::failure:\n if (solver_control.last_step() > solver_control.max_steps())\n *reason = EPS_DIVERGED_ITS;\n else\n *reason = EPS_DIVERGED_BREAKDOWN;\n break;\n\n default:\n Assert (false, ExcNotImplemented());\n }\n\n \/\/ return without failure.\n return 0;\n }\n\n \/* ---------------------- SolverKrylovSchur ------------------------ *\/\n SolverKrylovSchur::SolverKrylovSchur (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverKrylovSchur::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSKRYLOVSCHUR));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances(eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ---------------------- SolverArnoldi ------------------------ *\/\n SolverArnoldi::AdditionalData::\n AdditionalData (const bool delayed_reorthogonalization)\n :\n delayed_reorthogonalization (delayed_reorthogonalization)\n {}\n\n SolverArnoldi::SolverArnoldi (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverArnoldi::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSARNOLDI));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances(eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ if requested, set delayed reorthogonalization in the Arnoldi\n \/\/ iteration.\n if (additional_data.delayed_reorthogonalization)\n {\n ierr = EPSArnoldiSetDelayed (eps, PETSC_TRUE);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n }\n\n \/* ---------------------- Lanczos ------------------------ *\/\n SolverLanczos::SolverLanczos (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverLanczos::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSLANCZOS));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ----------------------- Power ------------------------- *\/\n SolverPower::SolverPower (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverPower::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSPOWER));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ---------------- Generalized Davidson ----------------- *\/\n SolverGeneralizedDavidson::SolverGeneralizedDavidson (SolverControl &cn,\n\t\t\t\t\t\t\tconst MPI_Comm &mpi_communicator,\n\t\t\t\t\t\t\tconst AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverGeneralizedDavidson::set_solver_type (EPS &eps) const\n {\n#if DEAL_II_PETSC_VERSION_GTE(3,1,0)\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSGD));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n#else\n \/\/ PETSc\/SLEPc version must be > 3.1.0 (supress compiler warning\n \/\/ by performing a void operation on eps).\n Assert (false,\n ExcMessage (\"Your SLEPc installation does not include a copy of the \"\n \"Generalized Davidson solver. A SLEPc version > 3.1.0 is required.\"));\n Assert (eps, ExcSLEPcWrappersUsageError());\n#endif\n }\n\n \/* ------------------ Jacobi Davidson -------------------- *\/\n SolverJacobiDavidson::SolverJacobiDavidson (SolverControl &cn,\n\t\t\t\t\t const MPI_Comm &mpi_communicator,\n\t\t\t\t\t const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverJacobiDavidson::set_solver_type (EPS &eps) const\n {\n#if DEAL_II_PETSC_VERSION_GTE(3,1,0)\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSJD));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n#else\n \/\/ PETSc\/SLEPc version must be > 3.1.0 (supress compiler warning\n \/\/ by performing a void operation on eps).\n Assert ((false),\n ExcMessage (\"Your SLEPc installation does not include a copy of the \"\n \"Jacobi-Davidson solver. A SLEPc version > 3.1.0 is required.\"));\n Assert (eps, ExcSLEPcWrappersUsageError());\n#endif\n }\n\n}\n\nDEAL_II_NAMESPACE_CLOSE\n\n#else\n\n\/\/ On gcc2.95 on Alpha OSF1, the native assembler does not like empty\n\/\/ files, so provide some dummy code\nnamespace\n{\n void dummy () {}\n}\n#endif \/\/ DEAL_II_USE_SLEPC\n\n<commit_msg>Use void() not Assert(NULL) to supress compiler warning.<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/ Author: Toby D. Young, Polish Academy of Sciences, 2008-2013\n\/\/\n\/\/ Copyright (C) 2009-2013 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/lac\/slepc_solver.h>\n\n#ifdef DEAL_II_USE_SLEPC\n\n# include <deal.II\/lac\/petsc_matrix_base.h>\n# include <deal.II\/lac\/petsc_vector_base.h>\n# include <deal.II\/lac\/petsc_vector.h>\n# include <deal.II\/lac\/slepc_spectral_transformation.h>\n\n# include <cmath>\n# include <vector>\n\n# include <petscversion.h>\n# include <slepcversion.h>\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace SLEPcWrappers\n{\n\n SolverBase::SolverData::~SolverData ()\n {\n \/\/ Destroy the solver object.\n#if DEAL_II_PETSC_VERSION_LT(3,2,0)\n int ierr = EPSDestroy (eps);\n#else\n int ierr = EPSDestroy (&eps);\n#endif\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n SolverBase::SolverBase (SolverControl &cn,\n const MPI_Comm &mpi_communicator)\n :\n solver_control (cn),\n mpi_communicator (mpi_communicator),\n set_which (EPS_LARGEST_MAGNITUDE),\n opA (NULL), opB (NULL),\n initial_vector (NULL),\n transformation (NULL)\n {}\n\n SolverBase::~SolverBase ()\n {}\n\n void\n SolverBase::set_matrices (const PETScWrappers::MatrixBase &A)\n {\n \/\/ standard eigenspectrum problem\n opA = &A;\n opB = NULL;\n }\n\n void\n SolverBase::set_matrices (const PETScWrappers::MatrixBase &A,\n const PETScWrappers::MatrixBase &B)\n {\n \/\/ generalized eigenspectrum problem\n opA = &A;\n opB = &B;\n }\n\n void\n SolverBase::set_initial_vector (const PETScWrappers::VectorBase &this_initial_vector)\n {\n initial_vector = (&this_initial_vector);\n }\n\n void\n SolverBase::set_transformation (SLEPcWrappers::TransformationBase &this_transformation)\n {\n transformation = &this_transformation;\n }\n\n void\n SolverBase::set_which_eigenpairs (const EPSWhich eps_which)\n {\n set_which = eps_which;\n }\n\n void\n SolverBase::solve (const unsigned int n_eigenvectors, unsigned int *n_converged)\n {\n int ierr;\n\n AssertThrow (solver_data.get() == 0, ExcSLEPcWrappersUsageError());\n solver_data.reset (new SolverData());\n\n \/\/ create eigensolver context and set operators\n ierr = EPSCreate (mpi_communicator, &solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set eigenspectrum problem type (general\/standard)\n AssertThrow (opA, ExcSLEPcWrappersUsageError());\n if (opB)\n ierr = EPSSetOperators (solver_data->eps, *opA, *opB);\n else\n ierr = EPSSetOperators (solver_data->eps, *opA, PETSC_NULL);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set the initial vector(s) if any\n if (initial_vector && initial_vector->size() != 0)\n {\n\n#if DEAL_II_PETSC_VERSION_LT(3,1,0)\n ierr = EPSSetInitialVector (solver_data->eps, *initial_vector);\n#else\n Vec this_vector = *initial_vector;\n ierr = EPSSetInitialSpace (solver_data->eps, 1, &this_vector);\n#endif\n\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/\/ set transformation type if any\n if (transformation)\n transformation->set_context(solver_data->eps);\n\n \/\/ set runtime options\n set_solver_type (solver_data->eps);\n\n \/\/ set which portion of the eigenspectrum to solve for\n ierr = EPSSetWhichEigenpairs (solver_data->eps, set_which);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set number of eigenvectors to compute\n ierr = EPSSetDimensions (solver_data->eps, n_eigenvectors,\n PETSC_DECIDE, PETSC_DECIDE);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ set the solve options to the eigenvalue problem solver context\n ierr = EPSSetFromOptions (solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ solve the eigensystem\n ierr = EPSSolve (solver_data->eps);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ get number of converged eigenstates\n ierr = EPSGetConverged (solver_data->eps,\n#ifdef PETSC_USE_64BIT_INDICES\n reinterpret_cast<PetscInt *>(n_converged));\n#else\n reinterpret_cast<int *>(n_converged));\n#endif\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n void\n SolverBase::get_eigenpair (const unsigned int index,\n#ifndef PETSC_USE_COMPLEX\n double &kr,\n#else\n std::complex<double> &kr,\n#endif\n PETScWrappers::VectorBase &vr)\n {\n AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError());\n\n \/\/ get converged eigenpair\n int ierr = EPSGetEigenpair (solver_data->eps, index,\n &kr, PETSC_NULL, vr, PETSC_NULL);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n\n void\n SolverBase::reset ()\n {\n AssertThrow (solver_data.get() != 0, ExcSLEPcWrappersUsageError());\n\n \/\/ destroy solver object.\n solver_data.reset ();\n }\n\n EPS *\n SolverBase::get_EPS ()\n {\n if (solver_data.get() == 0)\n return NULL;\n\n return &solver_data->eps;\n }\n\n \/* ---------------------- SolverControls ----------------------- *\/\n SolverControl &\n SolverBase::control () const\n {\n return solver_control;\n }\n\n int\n SolverBase::convergence_test (EPS \/*eps*\/,\n#ifdef PETSC_USE_64BIT_INDICES\n const PetscInt iteration,\n#else\n const int iteration,\n#endif\n const PetscReal residual_norm,\n EPSConvergedReason *reason,\n void *solver_control_x)\n {\n SolverControl &solver_control\n = *reinterpret_cast<SolverControl *>(solver_control_x);\n\n const SolverControl::State state\n = solver_control.check (iteration, residual_norm);\n\n switch (state)\n {\n case ::dealii::SolverControl::iterate:\n *reason = EPS_CONVERGED_ITERATING;\n break;\n\n case ::dealii::SolverControl::success:\n *reason = static_cast<EPSConvergedReason>(1);\n break;\n\n case ::dealii::SolverControl::failure:\n if (solver_control.last_step() > solver_control.max_steps())\n *reason = EPS_DIVERGED_ITS;\n else\n *reason = EPS_DIVERGED_BREAKDOWN;\n break;\n\n default:\n Assert (false, ExcNotImplemented());\n }\n\n \/\/ return without failure.\n return 0;\n }\n\n \/* ---------------------- SolverKrylovSchur ------------------------ *\/\n SolverKrylovSchur::SolverKrylovSchur (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverKrylovSchur::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSKRYLOVSCHUR));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances(eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ---------------------- SolverArnoldi ------------------------ *\/\n SolverArnoldi::AdditionalData::\n AdditionalData (const bool delayed_reorthogonalization)\n :\n delayed_reorthogonalization (delayed_reorthogonalization)\n {}\n\n SolverArnoldi::SolverArnoldi (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverArnoldi::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSARNOLDI));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances(eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ if requested, set delayed reorthogonalization in the Arnoldi\n \/\/ iteration.\n if (additional_data.delayed_reorthogonalization)\n {\n ierr = EPSArnoldiSetDelayed (eps, PETSC_TRUE);\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n }\n\n \/* ---------------------- Lanczos ------------------------ *\/\n SolverLanczos::SolverLanczos (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverLanczos::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSLANCZOS));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ----------------------- Power ------------------------- *\/\n SolverPower::SolverPower (SolverControl &cn,\n const MPI_Comm &mpi_communicator,\n const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverPower::set_solver_type (EPS &eps) const\n {\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSPOWER));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n }\n\n \/* ---------------- Generalized Davidson ----------------- *\/\n SolverGeneralizedDavidson::SolverGeneralizedDavidson (SolverControl &cn,\n\t\t\t\t\t\t\tconst MPI_Comm &mpi_communicator,\n\t\t\t\t\t\t\tconst AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverGeneralizedDavidson::set_solver_type (EPS &eps) const\n {\n#if DEAL_II_PETSC_VERSION_GTE(3,1,0)\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSGD));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n#else\n \/\/ Supress compiler warnings about unused paameters.\n (void) eps;\n\n \/\/ PETSc\/SLEPc version must be > 3.1.0.\n Assert (false,\n ExcMessage (\"Your SLEPc installation does not include a copy of the \"\n \"Generalized Davidson solver. A SLEPc version > 3.1.0 is required.\"));\n#endif\n }\n\n \/* ------------------ Jacobi Davidson -------------------- *\/\n SolverJacobiDavidson::SolverJacobiDavidson (SolverControl &cn,\n\t\t\t\t\t const MPI_Comm &mpi_communicator,\n\t\t\t\t\t const AdditionalData &data)\n :\n SolverBase (cn, mpi_communicator),\n additional_data (data)\n {}\n\n void\n SolverJacobiDavidson::set_solver_type (EPS &eps) const\n {\n#if DEAL_II_PETSC_VERSION_GTE(3,1,0)\n int ierr;\n ierr = EPSSetType (eps, const_cast<char *>(EPSJD));\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n\n \/\/ hand over the absolute tolerance and the maximum number of\n \/\/ iteration steps to the SLEPc convergence criterion.\n ierr = EPSSetTolerances (eps, this->solver_control.tolerance(),\n this->solver_control.max_steps());\n AssertThrow (ierr == 0, ExcSLEPcError(ierr));\n#else\n \/\/ Supress compiler warnings about unused paameters.\n (void) eps;\n\n \/\/ PETSc\/SLEPc version must be > 3.1.0.\n Assert ((false),\n ExcMessage (\"Your SLEPc installation does not include a copy of the \"\n \"Jacobi-Davidson solver. A SLEPc version > 3.1.0 is required.\"));\n#endif\n }\n\n}\n\nDEAL_II_NAMESPACE_CLOSE\n\n#else\n\n\/\/ On gcc2.95 on Alpha OSF1, the native assembler does not like empty\n\/\/ files, so provide some dummy code\nnamespace\n{\n void dummy () {}\n}\n#endif \/\/ DEAL_II_USE_SLEPC\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <vcl\/IconThemeSelector.hxx>\n\n#include <vcl\/IconThemeScanner.hxx>\n#include <vcl\/IconThemeInfo.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n\nclass IconThemeSelectorTest : public CppUnit::TestFixture\n{\n void\n OxygenThemeIsReturnedForKde4Desktop();\n\n void\n TangoThemeIsReturnedForGtkDesktop();\n\n void\n ThemeIsOverriddenByPreferredTheme();\n\n void\n ThemeIsOverriddenByHighContrastMode();\n\n void\n NotInstalledThemeDoesNotOverride();\n\n void\n InstalledThemeIsFound();\n\n void\n FirstThemeIsReturnedIfRequestedThemeIsNotFound();\n\n void\n FallbackThemeIsReturnedForEmptyInput();\n\n void\n DifferentPreferredThemesAreInequal();\n\n void\n DifferentHighContrastModesAreInequal();\n\n static std::vector<vcl::IconThemeInfo>\n GetFakeInstalledThemes();\n\n \/\/ Adds code needed to register the test suite\n CPPUNIT_TEST_SUITE(IconThemeSelectorTest);\n\n CPPUNIT_TEST(OxygenThemeIsReturnedForKde4Desktop);\n CPPUNIT_TEST(TangoThemeIsReturnedForGtkDesktop);\n CPPUNIT_TEST(ThemeIsOverriddenByPreferredTheme);\n CPPUNIT_TEST(ThemeIsOverriddenByHighContrastMode);\n CPPUNIT_TEST(NotInstalledThemeDoesNotOverride);\n CPPUNIT_TEST(InstalledThemeIsFound);\n CPPUNIT_TEST(FirstThemeIsReturnedIfRequestedThemeIsNotFound);\n CPPUNIT_TEST(FallbackThemeIsReturnedForEmptyInput);\n CPPUNIT_TEST(DifferentPreferredThemesAreInequal);\n CPPUNIT_TEST(DifferentHighContrastModesAreInequal);\n\n \/\/ End of test suite definition\n\n\n CPPUNIT_TEST_SUITE_END();\n};\n\n\/*static*\/ std::vector<vcl::IconThemeInfo>\nIconThemeSelectorTest::GetFakeInstalledThemes()\n{\n std::vector<vcl::IconThemeInfo> r;\n vcl::IconThemeInfo a{};\n a.mThemeId = \"tango\";\n r.push_back(a);\n a.mThemeId = \"oxygen\";\n r.push_back(a);\n a.mThemeId = vcl::IconThemeSelector::HIGH_CONTRAST_ICON_THEME_ID;\n r.push_back(a);\n return r;\n}\n\nvoid\nIconThemeSelectorTest::OxygenThemeIsReturnedForKde4Desktop()\n{\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n vcl::IconThemeSelector s;\n OUString r = s.SelectIconThemeForDesktopEnvironment(themes, \"kde4\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is returned for kde4 desktop\", OUString(\"oxygen\"), r);\n}\n\nvoid\nIconThemeSelectorTest::TangoThemeIsReturnedForGtkDesktop()\n{\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n vcl::IconThemeSelector s;\n OUString r = s.SelectIconThemeForDesktopEnvironment(themes, \"gtk\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is returned for kde4 desktop\", OUString(\"tango\"), r);\n}\n\nvoid\nIconThemeSelectorTest::ThemeIsOverriddenByPreferredTheme()\n{\n vcl::IconThemeSelector s;\n OUString preferred(\"oxygen\");\n s.SetPreferredIconTheme(preferred);\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconThemeForDesktopEnvironment(themes, \"gtk\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is overridden by oxygen\", preferred, selected);\n}\n\nvoid\nIconThemeSelectorTest::ThemeIsOverriddenByHighContrastMode()\n{\n vcl::IconThemeSelector s;\n s.SetUseHighContrastTheme(true);\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"tango\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is overridden by high contrast mode\",\n vcl::IconThemeSelector::HIGH_CONTRAST_ICON_THEME_ID, selected);\n s.SetUseHighContrastTheme(false);\n selected = s.SelectIconTheme(themes, \"tango\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is no longer overridden by high contrast mode\",\n OUString(\"tango\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::NotInstalledThemeDoesNotOverride()\n{\n vcl::IconThemeSelector s;\n s.SetPreferredIconTheme(\"oxygen_katze\");\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is not overridden by 'oxygen_katze'\", OUString(\"oxygen\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::InstalledThemeIsFound()\n{\n vcl::IconThemeSelector s;\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is found\", OUString(\"oxygen\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::FirstThemeIsReturnedIfRequestedThemeIsNotFound()\n{\n vcl::IconThemeSelector s;\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen_katze\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is found\", themes.front().GetThemeId(), selected);\n}\n\nvoid\nIconThemeSelectorTest::FallbackThemeIsReturnedForEmptyInput()\n{\n vcl::IconThemeSelector s;\n OUString selected = s.SelectIconTheme(std::vector<vcl::IconThemeInfo>{}, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"fallback is returned for empty input\",\n vcl::IconThemeSelector::FALLBACK_ICON_THEME_ID, selected);\n}\n\nvoid\nIconThemeSelectorTest::DifferentHighContrastModesAreInequal()\n{\n vcl::IconThemeSelector s1;\n vcl::IconThemeSelector s2;\n s1.SetUseHighContrastTheme(true);\n s2.SetUseHighContrastTheme(false);\n bool equal = (s1 == s2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Different high contrast modes are detected as inequal\", false, equal);\n}\n\nvoid\nIconThemeSelectorTest::DifferentPreferredThemesAreInequal()\n{\n vcl::IconThemeSelector s1;\n vcl::IconThemeSelector s2;\n s1.SetPreferredIconTheme(\"oxygen\");\n s2.SetUseHighContrastTheme(\"katze\");\n bool equal = (s1 == s2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Different preferred themes are detected as inequal\", false, equal);\n}\n\n\n\/\/ Put the test suite in the registry\nCPPUNIT_TEST_SUITE_REGISTRATION(IconThemeSelectorTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>WaE: implicit conversion of literal of type 'const char *' to 'bool'<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <vcl\/IconThemeSelector.hxx>\n\n#include <vcl\/IconThemeScanner.hxx>\n#include <vcl\/IconThemeInfo.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n\nclass IconThemeSelectorTest : public CppUnit::TestFixture\n{\n void\n OxygenThemeIsReturnedForKde4Desktop();\n\n void\n TangoThemeIsReturnedForGtkDesktop();\n\n void\n ThemeIsOverriddenByPreferredTheme();\n\n void\n ThemeIsOverriddenByHighContrastMode();\n\n void\n NotInstalledThemeDoesNotOverride();\n\n void\n InstalledThemeIsFound();\n\n void\n FirstThemeIsReturnedIfRequestedThemeIsNotFound();\n\n void\n FallbackThemeIsReturnedForEmptyInput();\n\n void\n DifferentPreferredThemesAreInequal();\n\n void\n DifferentHighContrastModesAreInequal();\n\n static std::vector<vcl::IconThemeInfo>\n GetFakeInstalledThemes();\n\n \/\/ Adds code needed to register the test suite\n CPPUNIT_TEST_SUITE(IconThemeSelectorTest);\n\n CPPUNIT_TEST(OxygenThemeIsReturnedForKde4Desktop);\n CPPUNIT_TEST(TangoThemeIsReturnedForGtkDesktop);\n CPPUNIT_TEST(ThemeIsOverriddenByPreferredTheme);\n CPPUNIT_TEST(ThemeIsOverriddenByHighContrastMode);\n CPPUNIT_TEST(NotInstalledThemeDoesNotOverride);\n CPPUNIT_TEST(InstalledThemeIsFound);\n CPPUNIT_TEST(FirstThemeIsReturnedIfRequestedThemeIsNotFound);\n CPPUNIT_TEST(FallbackThemeIsReturnedForEmptyInput);\n CPPUNIT_TEST(DifferentPreferredThemesAreInequal);\n CPPUNIT_TEST(DifferentHighContrastModesAreInequal);\n\n \/\/ End of test suite definition\n\n\n CPPUNIT_TEST_SUITE_END();\n};\n\n\/*static*\/ std::vector<vcl::IconThemeInfo>\nIconThemeSelectorTest::GetFakeInstalledThemes()\n{\n std::vector<vcl::IconThemeInfo> r;\n vcl::IconThemeInfo a{};\n a.mThemeId = \"tango\";\n r.push_back(a);\n a.mThemeId = \"oxygen\";\n r.push_back(a);\n a.mThemeId = vcl::IconThemeSelector::HIGH_CONTRAST_ICON_THEME_ID;\n r.push_back(a);\n return r;\n}\n\nvoid\nIconThemeSelectorTest::OxygenThemeIsReturnedForKde4Desktop()\n{\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n vcl::IconThemeSelector s;\n OUString r = s.SelectIconThemeForDesktopEnvironment(themes, \"kde4\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is returned for kde4 desktop\", OUString(\"oxygen\"), r);\n}\n\nvoid\nIconThemeSelectorTest::TangoThemeIsReturnedForGtkDesktop()\n{\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n vcl::IconThemeSelector s;\n OUString r = s.SelectIconThemeForDesktopEnvironment(themes, \"gtk\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is returned for kde4 desktop\", OUString(\"tango\"), r);\n}\n\nvoid\nIconThemeSelectorTest::ThemeIsOverriddenByPreferredTheme()\n{\n vcl::IconThemeSelector s;\n OUString preferred(\"oxygen\");\n s.SetPreferredIconTheme(preferred);\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconThemeForDesktopEnvironment(themes, \"gtk\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is overridden by oxygen\", preferred, selected);\n}\n\nvoid\nIconThemeSelectorTest::ThemeIsOverriddenByHighContrastMode()\n{\n vcl::IconThemeSelector s;\n s.SetUseHighContrastTheme(true);\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"tango\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is overridden by high contrast mode\",\n vcl::IconThemeSelector::HIGH_CONTRAST_ICON_THEME_ID, selected);\n s.SetUseHighContrastTheme(false);\n selected = s.SelectIconTheme(themes, \"tango\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'tango' theme is no longer overridden by high contrast mode\",\n OUString(\"tango\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::NotInstalledThemeDoesNotOverride()\n{\n vcl::IconThemeSelector s;\n s.SetPreferredIconTheme(\"oxygen_katze\");\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is not overridden by 'oxygen_katze'\", OUString(\"oxygen\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::InstalledThemeIsFound()\n{\n vcl::IconThemeSelector s;\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is found\", OUString(\"oxygen\"), selected);\n}\n\nvoid\nIconThemeSelectorTest::FirstThemeIsReturnedIfRequestedThemeIsNotFound()\n{\n vcl::IconThemeSelector s;\n std::vector<vcl::IconThemeInfo> themes = GetFakeInstalledThemes();\n OUString selected = s.SelectIconTheme(themes, \"oxygen_katze\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"'oxygen' theme is found\", themes.front().GetThemeId(), selected);\n}\n\nvoid\nIconThemeSelectorTest::FallbackThemeIsReturnedForEmptyInput()\n{\n vcl::IconThemeSelector s;\n OUString selected = s.SelectIconTheme(std::vector<vcl::IconThemeInfo>{}, \"oxygen\");\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"fallback is returned for empty input\",\n vcl::IconThemeSelector::FALLBACK_ICON_THEME_ID, selected);\n}\n\nvoid\nIconThemeSelectorTest::DifferentHighContrastModesAreInequal()\n{\n vcl::IconThemeSelector s1;\n vcl::IconThemeSelector s2;\n s1.SetUseHighContrastTheme(true);\n s2.SetUseHighContrastTheme(false);\n bool equal = (s1 == s2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Different high contrast modes are detected as inequal\", false, equal);\n}\n\nvoid\nIconThemeSelectorTest::DifferentPreferredThemesAreInequal()\n{\n vcl::IconThemeSelector s1;\n vcl::IconThemeSelector s2;\n s1.SetPreferredIconTheme(\"oxygen\");\n s2.SetUseHighContrastTheme(true);\n bool equal = (s1 == s2);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Different preferred themes are detected as inequal\", false, equal);\n}\n\n\n\/\/ Put the test suite in the registry\nCPPUNIT_TEST_SUITE_REGISTRATION(IconThemeSelectorTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Copyright © 2012 Intel Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Author: Benjamin Segovia <benjamin.segovia@intel.com>\n *\/\n\n\/**\n * \\file lowering.cpp\n * \\author Benjamin Segovia <benjamin.segovia@intel.com>\n *\/\n\n#include \"ir\/context.hpp\"\n#include \"ir\/value.hpp\"\n#include \"ir\/liveness.hpp\"\n#include \"sys\/set.hpp\"\n\nnamespace gbe {\nnamespace ir {\n\n \/*! Small helper class to lower return instructions *\/\n class ContextReturn : public Context\n {\n public:\n \/*! Initialize a context dedicated to return instruction lowering *\/\n ContextReturn(Unit &unit) : Context(unit) {\n this->usedLabels = GBE_NEW_NO_ARG(vector<uint8_t>);\n }\n \/*! Lower the return instruction to gotos for the given function *\/\n void lower(const std::string &functionName);\n };\n\n void ContextReturn::lower(const std::string &functionName) {\n if ((this->fn = unit.getFunction(functionName)) == NULL)\n return;\n\n \/\/ Append a new block at the end of the function with a return instruction:\n \/\/ the only one we are going to have\n this->bb = &this->fn->getBottomBlock();\n const LabelIndex index = this->label();\n this->LABEL(index);\n const BasicBlock *lastBlock = this->bb;\n this->RET();\n\n \/\/ Now traverse all instructions and replace all returns by GOTO index\n fn->foreachInstruction([&](Instruction &insn) {\n if (insn.getParent() == lastBlock) return; \/\/ This is the last block\n if (insn.getOpcode() != OP_RET) return;\n const Instruction bra = ir::BRA(index);\n bra.replace(&insn);\n });\n }\n\n void lowerReturn(Unit &unit, const std::string &functionName) {\n ContextReturn ctx(unit);\n ctx.lower(functionName);\n }\n\n \/*! Characterizes how the argument is used (directly read, indirectly read,\n * written)\n *\/\n enum ArgUse {\n ARG_DIRECT_READ = 0,\n ARG_INDIRECT_READ = 1,\n ARG_WRITTEN = 2\n };\n\n \/*! Just to book keep the sequence of instructions that directly load an input\n * argument\n *\/\n struct LoadAddImm {\n Instruction *load; \/\/!< Load from the argument\n Instruction *add; \/\/!< Can be NULL if we only have load(arg)\n Instruction *loadImm; \/\/!< Can also be NULL\n uint64_t offset; \/\/!< Offset where to load in the structure\n uint32_t argID; \/\/!< Associated function argument\n };\n\n \/*! List of direct loads *\/\n typedef vector<LoadAddImm> LoadAddImmSeq;\n\n \/*! Helper class to lower function arguments if required *\/\n class FunctionArgumentLowerer : public Context\n {\n public:\n \/*! Build the helper structure *\/\n FunctionArgumentLowerer(Unit &unit);\n \/*! Free everything we needed *\/\n virtual ~FunctionArgumentLowerer(void);\n \/*! Perform all function arguments substitution if needed *\/\n void lower(const std::string &name);\n \/*! Lower the given function argument accesses *\/\n void lower(uint32_t argID);\n \/*! Build the constant push for the function *\/\n void buildConstantPush(void);\n \/*! Inspect the given function argument to see how it is used. If this is\n * direct loads only, we also output the list of instructions used for each\n * load\n *\/\n ArgUse getArgUse(uint32_t argID);\n \/*! Recursively look if there is a store in the given use *\/\n bool useStore(const ValueDef &def, set<const Instruction*> &visited);\n \/*! Look if the pointer use only load with immediate offsets *\/\n bool matchLoadAddImm(uint32_t argID);\n Liveness *liveness; \/\/!< To compute the function graph\n FunctionDAG *dag; \/\/!< Contains complete dependency information\n LoadAddImmSeq seq; \/\/!< All the direct loads\n };\n\n INLINE uint64_t getOffsetFromImm(const Immediate &imm) {\n switch (imm.type) {\n \/\/ bit-cast these ones\n case TYPE_DOUBLE:\n case TYPE_FLOAT:\n case TYPE_S64:\n case TYPE_U64:\n case TYPE_U32:\n case TYPE_U16:\n case TYPE_U8: return imm.data.u64;\n \/\/ sign extend these ones\n case TYPE_S32: return int64_t(imm.data.s32);\n case TYPE_S16: return int64_t(imm.data.s16);\n case TYPE_S8: return int64_t(imm.data.s8);\n case TYPE_BOOL:\n case TYPE_HALF: NOT_SUPPORTED; return 0;\n }\n return 0;\n }\n\n bool matchLoad(Instruction *insn,\n Instruction *add,\n Instruction *loadImm,\n uint64_t offset,\n uint32_t argID,\n LoadAddImm &loadAddImm)\n {\n const Opcode opcode = insn->getOpcode();\n\n if (opcode == OP_LOAD) {\n LoadInstruction *load = cast<LoadInstruction>(insn);\n if (load->getAddressSpace() != MEM_PRIVATE)\n return false;\n loadAddImm.load = insn;\n loadAddImm.add = add;\n loadAddImm.loadImm = loadImm;\n loadAddImm.offset = offset;\n loadAddImm.argID = argID;\n return true;\n } else\n return false;\n }\n\n\n FunctionArgumentLowerer::FunctionArgumentLowerer(Unit &unit) :\n Context(unit), liveness(NULL), dag(NULL) {}\n FunctionArgumentLowerer::~FunctionArgumentLowerer(void) {\n GBE_SAFE_DELETE(dag);\n GBE_SAFE_DELETE(liveness);\n }\n\n void FunctionArgumentLowerer::lower(const std::string &functionName) {\n if ((this->fn = unit.getFunction(functionName)) == NULL)\n return;\n GBE_SAFE_DELETE(dag);\n GBE_SAFE_DELETE(liveness);\n this->liveness = GBE_NEW(ir::Liveness, *fn);\n this->dag = GBE_NEW(ir::FunctionDAG, *this->liveness);\n\n \/\/ Process all structure arguments and find all the direct loads we can\n \/\/ replace\n const uint32_t argNum = fn->argNum();\n for (uint32_t argID = 0; argID < argNum; ++argID) {\n FunctionArgument &arg = fn->getArg(argID);\n if (arg.type != FunctionArgument::STRUCTURE) continue;\n this->lower(argID);\n }\n\n \/\/ Build the constant push description and remove the instruction that\n \/\/ therefore become useless\n this->buildConstantPush();\n }\n\n\/\/ Remove all the given instructions from the stream (if dead)\n#define REMOVE_INSN(WHICH) \\\n for (const auto &loadAddImm : seq) { \\\n Instruction *WHICH = loadAddImm.WHICH; \\\n if (WHICH == NULL) continue; \\\n const UseSet &useSet = dag->getUse(WHICH, 0); \\\n bool isDead = true; \\\n for (auto use : useSet) { \\\n if (dead.contains(use->getInstruction()) == false) { \\\n isDead = false; \\\n break; \\\n } \\\n } \\\n if (isDead) { \\\n dead.insert(WHICH); \\\n WHICH->remove(); \\\n } \\\n }\n\n void FunctionArgumentLowerer::buildConstantPush(void)\n {\n if (seq.size() == 0)\n return;\n\n \/\/ Track instructions we remove to recursively kill them properly\n set<const Instruction*> dead;\n\n \/\/ The argument location we already pushed (since the same argument location\n \/\/ can be used several times)\n set<PushLocation> inserted;\n for (const auto &loadAddImm : seq) {\n LoadInstruction *load = cast<LoadInstruction>(loadAddImm.load);\n const uint32_t valueNum = load->getValueNum();\n for (uint32_t valueID = 0; valueID < valueNum; ++valueID) {\n const Type type = load->getValueType();\n const RegisterFamily family = getFamily(type);\n const uint32_t size = getFamilySize(family);\n const uint32_t offset = loadAddImm.offset + valueID * size;\n const PushLocation argLocation(*fn, loadAddImm.argID, offset);\n if (inserted.contains(argLocation))\n continue;\n Register pushed;\n const Register reg = load->getValue(valueID);\n if (offset != 0) {\n pushed = fn->newRegister(family);\n this->appendPushedConstant(pushed, argLocation);\n } else {\n pushed = fn->getArg(loadAddImm.argID).reg;\n }\n\n \/\/ TODO the MOV instruction can be most of the time avoided if the\n \/\/ register is never written. We must however support the register\n \/\/ replacement in the instruction interface to be able to patch all the\n \/\/ instruction that uses \"reg\"\n const Instruction mov = ir::MOV(type, reg, pushed);\n mov.replace(load);\n dead.insert(load);\n }\n }\n\n \/\/ Remove all unused adds and load immediates\n REMOVE_INSN(add)\n REMOVE_INSN(loadImm)\n }\n\n#undef REMOVE_INSN\n\n bool FunctionArgumentLowerer::useStore(const ValueDef &def, set<const Instruction*> &visited)\n {\n const UseSet &useSet = dag->getUse(def);\n for (const auto &use : useSet) {\n const Instruction *insn = use->getInstruction();\n const uint32_t srcID = use->getSrcID();\n const Opcode opcode = insn->getOpcode();\n if (visited.contains(insn)) continue;\n visited.insert(insn);\n if (opcode == OP_STORE && srcID == StoreInstruction::addressIndex)\n return true;\n if (insn->isMemberOf<UnaryInstruction>() == false &&\n insn->isMemberOf<BinaryInstruction>() == false)\n continue;\n else {\n const uint32_t dstNum = insn->getDstNum();\n for (uint32_t dstID = 0; dstID < dstNum; ++dstID)\n if (this->useStore(ValueDef(insn, dstID), visited) == true)\n return true;\n }\n }\n return false;\n }\n\n bool FunctionArgumentLowerer::matchLoadAddImm(uint32_t argID)\n {\n const FunctionArgument &arg = fn->getArg(argID);\n LoadAddImmSeq tmpSeq;\n\n \/\/ Inspect all uses of the function argument pointer\n const UseSet &useSet = dag->getUse(&arg);\n for (auto use : useSet) {\n Instruction *insn = const_cast<Instruction*>(use->getInstruction());\n const Opcode opcode = insn->getOpcode();\n\n \/\/ load dst arg\n LoadAddImm loadAddImm;\n if (matchLoad(insn, NULL, NULL, 0, argID, loadAddImm)) {\n tmpSeq.push_back(loadAddImm);\n continue;\n }\n\n \/\/ add.ptr_type dst ptr other\n if (opcode != OP_ADD) return false;\n BinaryInstruction *add = cast<BinaryInstruction>(insn);\n const Type addType = add->getType();\n const RegisterFamily family = getFamily(addType);\n if (family != unit.getPointerFamily()) return false;\n if (addType == TYPE_FLOAT) return false;\n\n \/\/ step 1 -> check that the other source comes from a load immediate\n const uint32_t srcID = use->getSrcID();\n const uint32_t otherID = srcID ^ 1;\n const DefSet &defSet = dag->getDef(insn, otherID);\n const uint32_t defNum = defSet.size();\n if (defNum == 0 || defNum > 1) continue; \/\/ undefined or more than one def\n const ValueDef *otherDef = *defSet.begin();\n if (otherDef->getType() != ValueDef::DEF_INSN_DST) return false;\n Instruction *otherInsn = const_cast<Instruction*>(otherDef->getInstruction());\n if (otherInsn->getOpcode() != OP_LOADI) return false;\n LoadImmInstruction *loadImm = cast<LoadImmInstruction>(otherInsn);\n const Immediate imm = loadImm->getImmediate();\n const uint64_t offset = getOffsetFromImm(imm);\n\n \/\/ step 2 -> check that the results of the add are loads from private\n \/\/ memory\n const UseSet &addUseSet = dag->getUse(add, 0);\n for (auto addUse : addUseSet) {\n Instruction *insn = const_cast<Instruction*>(addUse->getInstruction());\n\n \/\/ We finally find something like load dst arg+imm\n LoadAddImm loadAddImm;\n if (matchLoad(insn, add, loadImm, offset, argID, loadAddImm)) {\n tmpSeq.push_back(loadAddImm);\n continue;\n }\n }\n }\n\n \/\/ OK, the argument only need direct loads. We can now append all the\n \/\/ direct load definitions we found\n for (const auto &loadImmSeq : tmpSeq)\n seq.push_back(loadImmSeq);\n return true;\n }\n\n ArgUse FunctionArgumentLowerer::getArgUse(uint32_t argID)\n {\n FunctionArgument &arg = fn->getArg(argID);\n\n \/\/ case 1 - we may store something to the structure argument\n set<const Instruction*> visited;\n if (this->useStore(ValueDef(&arg), visited))\n return ARG_WRITTEN;\n\n \/\/ case 2 - we look for the patterns: LOAD(ptr) or LOAD(ptr+imm)\n if (this->matchLoadAddImm(argID))\n return ARG_DIRECT_READ;\n\n \/\/ case 3 - LOAD(ptr+runtime_value)\n return ARG_INDIRECT_READ;\n }\n\n void FunctionArgumentLowerer::lower(uint32_t argID) {\n IF_DEBUG(const ArgUse argUse = )this->getArgUse(argID);\n#if GBE_DEBUG\n GBE_ASSERTM(argUse != ARG_WRITTEN,\n \"TODO A store to a structure argument \"\n \"(i.e. not a char\/short\/int\/float argument) has been found. \"\n \"This is not supported yet\");\n GBE_ASSERTM(argUse != ARG_INDIRECT_READ,\n \"TODO Only direct loads of structure arguments are \"\n \"supported now\");\n#endif \/* GBE_DEBUG *\/\n }\n\n void lowerFunctionArguments(Unit &unit, const std::string &functionName) {\n FunctionArgumentLowerer lowerer(unit);\n lowerer.lower(functionName);\n }\n\n} \/* namespace ir *\/\n} \/* namespace gbe *\/\n\n<commit_msg>Fix a build pushMap bug.<commit_after>\/* \n * Copyright © 2012 Intel Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Author: Benjamin Segovia <benjamin.segovia@intel.com>\n *\/\n\n\/**\n * \\file lowering.cpp\n * \\author Benjamin Segovia <benjamin.segovia@intel.com>\n *\/\n\n#include \"ir\/context.hpp\"\n#include \"ir\/value.hpp\"\n#include \"ir\/liveness.hpp\"\n#include \"sys\/set.hpp\"\n\nnamespace gbe {\nnamespace ir {\n\n \/*! Small helper class to lower return instructions *\/\n class ContextReturn : public Context\n {\n public:\n \/*! Initialize a context dedicated to return instruction lowering *\/\n ContextReturn(Unit &unit) : Context(unit) {\n this->usedLabels = GBE_NEW_NO_ARG(vector<uint8_t>);\n }\n \/*! Lower the return instruction to gotos for the given function *\/\n void lower(const std::string &functionName);\n };\n\n void ContextReturn::lower(const std::string &functionName) {\n if ((this->fn = unit.getFunction(functionName)) == NULL)\n return;\n\n \/\/ Append a new block at the end of the function with a return instruction:\n \/\/ the only one we are going to have\n this->bb = &this->fn->getBottomBlock();\n const LabelIndex index = this->label();\n this->LABEL(index);\n const BasicBlock *lastBlock = this->bb;\n this->RET();\n\n \/\/ Now traverse all instructions and replace all returns by GOTO index\n fn->foreachInstruction([&](Instruction &insn) {\n if (insn.getParent() == lastBlock) return; \/\/ This is the last block\n if (insn.getOpcode() != OP_RET) return;\n const Instruction bra = ir::BRA(index);\n bra.replace(&insn);\n });\n }\n\n void lowerReturn(Unit &unit, const std::string &functionName) {\n ContextReturn ctx(unit);\n ctx.lower(functionName);\n }\n\n \/*! Characterizes how the argument is used (directly read, indirectly read,\n * written)\n *\/\n enum ArgUse {\n ARG_DIRECT_READ = 0,\n ARG_INDIRECT_READ = 1,\n ARG_WRITTEN = 2\n };\n\n \/*! Just to book keep the sequence of instructions that directly load an input\n * argument\n *\/\n struct LoadAddImm {\n Instruction *load; \/\/!< Load from the argument\n Instruction *add; \/\/!< Can be NULL if we only have load(arg)\n Instruction *loadImm; \/\/!< Can also be NULL\n uint64_t offset; \/\/!< Offset where to load in the structure\n uint32_t argID; \/\/!< Associated function argument\n };\n\n \/*! List of direct loads *\/\n typedef vector<LoadAddImm> LoadAddImmSeq;\n\n \/*! Helper class to lower function arguments if required *\/\n class FunctionArgumentLowerer : public Context\n {\n public:\n \/*! Build the helper structure *\/\n FunctionArgumentLowerer(Unit &unit);\n \/*! Free everything we needed *\/\n virtual ~FunctionArgumentLowerer(void);\n \/*! Perform all function arguments substitution if needed *\/\n void lower(const std::string &name);\n \/*! Lower the given function argument accesses *\/\n void lower(uint32_t argID);\n \/*! Build the constant push for the function *\/\n void buildConstantPush(void);\n \/*! Inspect the given function argument to see how it is used. If this is\n * direct loads only, we also output the list of instructions used for each\n * load\n *\/\n ArgUse getArgUse(uint32_t argID);\n \/*! Recursively look if there is a store in the given use *\/\n bool useStore(const ValueDef &def, set<const Instruction*> &visited);\n \/*! Look if the pointer use only load with immediate offsets *\/\n bool matchLoadAddImm(uint32_t argID);\n Liveness *liveness; \/\/!< To compute the function graph\n FunctionDAG *dag; \/\/!< Contains complete dependency information\n LoadAddImmSeq seq; \/\/!< All the direct loads\n };\n\n INLINE uint64_t getOffsetFromImm(const Immediate &imm) {\n switch (imm.type) {\n \/\/ bit-cast these ones\n case TYPE_DOUBLE:\n case TYPE_FLOAT:\n case TYPE_S64:\n case TYPE_U64:\n case TYPE_U32:\n case TYPE_U16:\n case TYPE_U8: return imm.data.u64;\n \/\/ sign extend these ones\n case TYPE_S32: return int64_t(imm.data.s32);\n case TYPE_S16: return int64_t(imm.data.s16);\n case TYPE_S8: return int64_t(imm.data.s8);\n case TYPE_BOOL:\n case TYPE_HALF: NOT_SUPPORTED; return 0;\n }\n return 0;\n }\n\n bool matchLoad(Instruction *insn,\n Instruction *add,\n Instruction *loadImm,\n uint64_t offset,\n uint32_t argID,\n LoadAddImm &loadAddImm)\n {\n const Opcode opcode = insn->getOpcode();\n\n if (opcode == OP_LOAD) {\n LoadInstruction *load = cast<LoadInstruction>(insn);\n if (load->getAddressSpace() != MEM_PRIVATE)\n return false;\n loadAddImm.load = insn;\n loadAddImm.add = add;\n loadAddImm.loadImm = loadImm;\n loadAddImm.offset = offset;\n loadAddImm.argID = argID;\n return true;\n } else\n return false;\n }\n\n\n FunctionArgumentLowerer::FunctionArgumentLowerer(Unit &unit) :\n Context(unit), liveness(NULL), dag(NULL) {}\n FunctionArgumentLowerer::~FunctionArgumentLowerer(void) {\n GBE_SAFE_DELETE(dag);\n GBE_SAFE_DELETE(liveness);\n }\n\n void FunctionArgumentLowerer::lower(const std::string &functionName) {\n if ((this->fn = unit.getFunction(functionName)) == NULL)\n return;\n GBE_SAFE_DELETE(dag);\n GBE_SAFE_DELETE(liveness);\n this->liveness = GBE_NEW(ir::Liveness, *fn);\n this->dag = GBE_NEW(ir::FunctionDAG, *this->liveness);\n\n \/\/ Process all structure arguments and find all the direct loads we can\n \/\/ replace\n const uint32_t argNum = fn->argNum();\n for (uint32_t argID = 0; argID < argNum; ++argID) {\n FunctionArgument &arg = fn->getArg(argID);\n if (arg.type != FunctionArgument::STRUCTURE) continue;\n this->lower(argID);\n }\n\n \/\/ Build the constant push description and remove the instruction that\n \/\/ therefore become useless\n this->buildConstantPush();\n }\n\n\/\/ Remove all the given instructions from the stream (if dead)\n#define REMOVE_INSN(WHICH) \\\n for (const auto &loadAddImm : seq) { \\\n Instruction *WHICH = loadAddImm.WHICH; \\\n if (WHICH == NULL) continue; \\\n const UseSet &useSet = dag->getUse(WHICH, 0); \\\n bool isDead = true; \\\n for (auto use : useSet) { \\\n if (dead.contains(use->getInstruction()) == false) { \\\n isDead = false; \\\n break; \\\n } \\\n } \\\n if (isDead) { \\\n dead.insert(WHICH); \\\n WHICH->remove(); \\\n } \\\n }\n\n void FunctionArgumentLowerer::buildConstantPush(void)\n {\n if (seq.size() == 0)\n return;\n\n \/\/ Track instructions we remove to recursively kill them properly\n set<const Instruction*> dead;\n\n \/\/ The argument location we already pushed (since the same argument location\n \/\/ can be used several times)\n set<PushLocation> inserted;\n for (const auto &loadAddImm : seq) {\n LoadInstruction *load = cast<LoadInstruction>(loadAddImm.load);\n const uint32_t valueNum = load->getValueNum();\n for (uint32_t valueID = 0; valueID < valueNum; ++valueID) {\n const Type type = load->getValueType();\n const RegisterFamily family = getFamily(type);\n const uint32_t size = getFamilySize(family);\n const uint32_t offset = loadAddImm.offset + valueID * size;\n const PushLocation argLocation(*fn, loadAddImm.argID, offset);\n if (inserted.contains(argLocation))\n continue;\n Register pushed;\n const Register reg = load->getValue(valueID);\n if (offset != 0) {\n pushed = fn->newRegister(family);\n this->appendPushedConstant(pushed, argLocation);\n inserted.insert(argLocation);\n } else {\n pushed = fn->getArg(loadAddImm.argID).reg;\n }\n\n \/\/ TODO the MOV instruction can be most of the time avoided if the\n \/\/ register is never written. We must however support the register\n \/\/ replacement in the instruction interface to be able to patch all the\n \/\/ instruction that uses \"reg\"\n const Instruction mov = ir::MOV(type, reg, pushed);\n mov.replace(load);\n dead.insert(load);\n }\n }\n\n \/\/ Remove all unused adds and load immediates\n REMOVE_INSN(add)\n REMOVE_INSN(loadImm)\n }\n\n#undef REMOVE_INSN\n\n bool FunctionArgumentLowerer::useStore(const ValueDef &def, set<const Instruction*> &visited)\n {\n const UseSet &useSet = dag->getUse(def);\n for (const auto &use : useSet) {\n const Instruction *insn = use->getInstruction();\n const uint32_t srcID = use->getSrcID();\n const Opcode opcode = insn->getOpcode();\n if (visited.contains(insn)) continue;\n visited.insert(insn);\n if (opcode == OP_STORE && srcID == StoreInstruction::addressIndex)\n return true;\n if (insn->isMemberOf<UnaryInstruction>() == false &&\n insn->isMemberOf<BinaryInstruction>() == false)\n continue;\n else {\n const uint32_t dstNum = insn->getDstNum();\n for (uint32_t dstID = 0; dstID < dstNum; ++dstID)\n if (this->useStore(ValueDef(insn, dstID), visited) == true)\n return true;\n }\n }\n return false;\n }\n\n bool FunctionArgumentLowerer::matchLoadAddImm(uint32_t argID)\n {\n const FunctionArgument &arg = fn->getArg(argID);\n LoadAddImmSeq tmpSeq;\n\n \/\/ Inspect all uses of the function argument pointer\n const UseSet &useSet = dag->getUse(&arg);\n for (auto use : useSet) {\n Instruction *insn = const_cast<Instruction*>(use->getInstruction());\n const Opcode opcode = insn->getOpcode();\n\n \/\/ load dst arg\n LoadAddImm loadAddImm;\n if (matchLoad(insn, NULL, NULL, 0, argID, loadAddImm)) {\n tmpSeq.push_back(loadAddImm);\n continue;\n }\n\n \/\/ add.ptr_type dst ptr other\n if (opcode != OP_ADD) return false;\n BinaryInstruction *add = cast<BinaryInstruction>(insn);\n const Type addType = add->getType();\n const RegisterFamily family = getFamily(addType);\n if (family != unit.getPointerFamily()) return false;\n if (addType == TYPE_FLOAT) return false;\n\n \/\/ step 1 -> check that the other source comes from a load immediate\n const uint32_t srcID = use->getSrcID();\n const uint32_t otherID = srcID ^ 1;\n const DefSet &defSet = dag->getDef(insn, otherID);\n const uint32_t defNum = defSet.size();\n if (defNum == 0 || defNum > 1) continue; \/\/ undefined or more than one def\n const ValueDef *otherDef = *defSet.begin();\n if (otherDef->getType() != ValueDef::DEF_INSN_DST) return false;\n Instruction *otherInsn = const_cast<Instruction*>(otherDef->getInstruction());\n if (otherInsn->getOpcode() != OP_LOADI) return false;\n LoadImmInstruction *loadImm = cast<LoadImmInstruction>(otherInsn);\n const Immediate imm = loadImm->getImmediate();\n const uint64_t offset = getOffsetFromImm(imm);\n\n \/\/ step 2 -> check that the results of the add are loads from private\n \/\/ memory\n const UseSet &addUseSet = dag->getUse(add, 0);\n for (auto addUse : addUseSet) {\n Instruction *insn = const_cast<Instruction*>(addUse->getInstruction());\n\n \/\/ We finally find something like load dst arg+imm\n LoadAddImm loadAddImm;\n if (matchLoad(insn, add, loadImm, offset, argID, loadAddImm)) {\n tmpSeq.push_back(loadAddImm);\n continue;\n }\n }\n }\n\n \/\/ OK, the argument only need direct loads. We can now append all the\n \/\/ direct load definitions we found\n for (const auto &loadImmSeq : tmpSeq)\n seq.push_back(loadImmSeq);\n return true;\n }\n\n ArgUse FunctionArgumentLowerer::getArgUse(uint32_t argID)\n {\n FunctionArgument &arg = fn->getArg(argID);\n\n \/\/ case 1 - we may store something to the structure argument\n set<const Instruction*> visited;\n if (this->useStore(ValueDef(&arg), visited))\n return ARG_WRITTEN;\n\n \/\/ case 2 - we look for the patterns: LOAD(ptr) or LOAD(ptr+imm)\n if (this->matchLoadAddImm(argID))\n return ARG_DIRECT_READ;\n\n \/\/ case 3 - LOAD(ptr+runtime_value)\n return ARG_INDIRECT_READ;\n }\n\n void FunctionArgumentLowerer::lower(uint32_t argID) {\n IF_DEBUG(const ArgUse argUse = )this->getArgUse(argID);\n#if GBE_DEBUG\n GBE_ASSERTM(argUse != ARG_WRITTEN,\n \"TODO A store to a structure argument \"\n \"(i.e. not a char\/short\/int\/float argument) has been found. \"\n \"This is not supported yet\");\n GBE_ASSERTM(argUse != ARG_INDIRECT_READ,\n \"TODO Only direct loads of structure arguments are \"\n \"supported now\");\n#endif \/* GBE_DEBUG *\/\n }\n\n void lowerFunctionArguments(Unit &unit, const std::string &functionName) {\n FunctionArgumentLowerer lowerer(unit);\n lowerer.lower(functionName);\n }\n\n} \/* namespace ir *\/\n} \/* namespace gbe *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_HXX_INTERNAL\n #error \"Please #include <abaclade.hxx> instead of this file\"\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals\n\nnamespace abc {\n\n\/*! DOC:3549 Enumeration classes\n\nAbaclade features support for advanced enumeration classes. These are the features that set them\napart from C++11 “enum class” enumerations:\n\n• Strong typing: constants from one enumeration are not implicitly converted to a different\n enumeration type;\n• Scoped constants: the enumeration members are members of the enumeration class, not of its\n containing scope; different classes can therefore use constants of the same name because their\n usage will need to be qualified with the enumeration type name;\n• Conversion from\/to string: instances of an Abaclade enumeration class can be serialized and\n de-serialized as strings with no additional code.\n\nThe ABC_ENUM() macro declares an enumeration class containing the members provided as a list.\n\nThe name provided to ABC_ENUM() is associated to a C++ class, not the C++ enum; the latter is\navailable through the former, as in as my_enum::enum_type; there should little to no need to ever\ndirectly refer to the C++ enum type.\n\nThis design is loosely based on <http:\/\/www.python.org\/dev\/peps\/pep-0435\/>.\n*\/\n\n\/*! Implementation of the various ABC_ENUM() flavors.\n\n@param name\n Name of the enumeration type.\n@param cMembers\n Count of members of the enumeration.\n@param members\n C++ enum members.\n@param arrayitems\n Internal name\/value array items.\n@param othermembers\n Additional members to be injected as-is at the beginning of the class.\n*\/\n#define _ABC_ENUM_IMPL(name, cMembers, members, arrayitems, othermembers) \\\n class ABC_CPP_CAT(_, name, _e) { \\\n othermembers \\\n \\\n public: \\\n \/*! Publicly-accessible enumerated constants. *\/ \\\n enum enum_type { \\\n members \\\n }; \\\n \\\n \/*! Returns a pointer to the name\/value map to be used by abc::enum_impl. *\/ \\\n static ::abc::detail::enum_member const * _get_map() { \\\n static ::abc::detail::enum_member const sc_map[] = { \\\n arrayitems \\\n { nullptr, 0, 0 } \\\n }; \\\n return sc_map; \\\n } \\\n \\\n protected: \\\n \/*! Number of members specified for the enum. *\/ \\\n static std::size_t const smc_cMembers = cMembers; \\\n }; \\\n typedef ::abc::enum_impl<ABC_CPP_CAT(_, name, _e)> name\n\n\/*! Expands into an enum name\/value assignment.\n\n@param name\n Name of the enumeration constant. The associated value is incremental in the ABC_ENUM, just like\n in C++ enums.\n*\/\n#define _ABC_ENUM_MEMBER(name) \\\n name = __COUNTER__ - smc_iBase,\n\n\/*! Expands into an enum name\/value assignment.\n\n@param name\n Name of the enumeration constant.\n@param value\n Value of the enumeration constant.\n*\/\n#define _ABC_ENUM_MEMBER_PAIR(name, value) \\\n name = value,\n\n\/*! Expands into an abc::detail::enum_member initializer.\n\n@param name\n Name of the enumeration constant.\n*\/\n#define _ABC_ENUM_MEMBER_ARRAY_ITEM(name) \\\n { \\\n ABC_SL(ABC_CPP_TOSTRING(name)), \\\n static_cast<unsigned short>(ABC_COUNTOF(ABC_CPP_TOSTRING(name)) - 1 \/*NUL*\/), \\\n name \\\n },\n\n\/*! Expands into _ABC_ENUM_MEMBER_ARRAY_ITEM().\n\n@param name\n Name of the enumeration constant.\n@param value\n Value of the enumeration constant. Not used.\n*\/\n#define _ABC_ENUM_MEMBER_PAIR_ARRAY_ITEM(name, value) \\\n _ABC_ENUM_MEMBER_ARRAY_ITEM(name)\n\n\/*! Defines an enumeration class as a specialization of abc::enum_impl. See [DOC:3549 Enumeration\nclasses] for more information.\n\nTODO: support for bit-field enumerations? Allow logical operation, smart conversion to\/from string,\netc.\n\n@param name\n Name of the enumeration type.\n@param ...\n Sequence of (name, value) pairs; these will be the members of the underlying C++ enum,\n name::enum_type.\n*\/\n#define ABC_ENUM(name, ...) \\\n _ABC_ENUM_IMPL( \\\n name, \\\n ABC_CPP_LIST_COUNT(__VA_ARGS__), \\\n ABC_CPP_TUPLELIST_WALK(_ABC_ENUM_MEMBER_PAIR, __VA_ARGS__), \\\n ABC_CPP_TUPLELIST_WALK(_ABC_ENUM_MEMBER_PAIR_ARRAY_ITEM, __VA_ARGS__), \\\n \\\n public: \\\n )\n\n\/*! Defines an enumeration class as a specialization of abc::enum_impl. See [DOC:3549 Enumeration\nclasses] for more information. Similar to ABC_ENUM(), except the members are listed individually and\ntheir values cannot be explicitly specified; for example:\n\n ABC_ENUM_AUTO_VALUES(myenum, item1, item2, item3);\n\n@param name\n Name of the enumeration type.\n@param ...\n Sequence of member names; these will be the members of the underlying C++ enum, name::enum_type.\n Their values will start from 0 and increase by 1 for each member.\n*\/\n#define ABC_ENUM_AUTO_VALUES(name, ...) \\\n _ABC_ENUM_IMPL( \\\n name, \\\n ABC_CPP_LIST_COUNT(__VA_ARGS__), \\\n ABC_CPP_LIST_WALK(_ABC_ENUM_MEMBER, __VA_ARGS__), \\\n ABC_CPP_LIST_WALK(_ABC_ENUM_MEMBER_ARRAY_ITEM, __VA_ARGS__), \\\n \\\n private: \\\n static int const smc_iBase = __COUNTER__ + 1; \\\n )\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::detail::enum_member\n\nnamespace abc {\nnamespace detail {\n\n\/\/! Enumeration member (name\/value pair).\nstruct ABACLADE_SYM enum_member {\n \/\/! Name.\n char_t const * pszName;\n \/\/! Size of *pszName, in characters.\n unsigned short cchName;\n \/\/! Value.\n int iValue;\n\n \/*! Finds and returns the member associated to the specified enumerated value or name. If no\n match is found, an exception will be throw.\n\n @param pem\n Pointer to the first item in the enumeration members array; the last item in the array has a\n nullptr name string pointer.\n @param iValue\n Value of the constant to search for.\n @param sName\n Name of the constant to search for.\n @return\n Pointer to the matching name\/value pair.\n *\/\n static enum_member const * find_in_map(enum_member const * pem, int iValue);\n static enum_member const * find_in_map(enum_member const * pem, istr const & sName);\n};\n\n} \/\/namespace detail\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::enum_impl\n\nnamespace abc {\n\n\/\/! Implementation of enumeration classes.\ntemplate <class T>\nclass enum_impl : public T {\npublic:\n \/\/! Underlying C++ eunm type.\n typedef typename T::enum_type enum_type;\n\n \/*! Constructor.\n\n @param e\n Source value.\n @param iValue\n Integer value to be converted to enum_type. If i has a value not in enum_type, an exception\n will be thrown.\n @param sName\n String to be converted to enum_type. If this does not match exactly the name of one of the\n members of enum_type, an exception of type abc::domain_error will be thrown.\n *\/\n enum_impl() {\n }\n enum_impl(enum_type e) :\n m_e(e) {\n }\n enum_impl(enum_impl const & e) :\n m_e(e.m_e) {\n }\n \/\/ Conversion from integer.\n explicit enum_impl(int iValue) :\n m_e(static_cast<enum_type>(detail::enum_member::find_in_map(T::_get_map(), iValue)->iValue)) {\n }\n \/\/ Conversion from string.\n explicit enum_impl(istr const & sName) :\n m_e(static_cast<enum_type>(detail::enum_member::find_in_map(T::_get_map(), sName)->iValue)) {\n }\n\n \/*! Assignment operator.\n\n @param e\n Source value.\n @return\n *this.\n *\/\n enum_impl & operator=(enum_impl const & e) {\n m_e = e.m_e;\n return *this;\n }\n enum_impl & operator=(enum_type e) {\n m_e = e;\n return *this;\n }\n\n \/*! Returns the current base enumerated value.\n\n @return\n Current value.\n *\/\n enum_type base() const {\n return m_e;\n }\n\n \/*! Returns the name of the current enumerated value.\n\n @return\n Name of the current value.\n *\/\n istr name() const;\n\n \/*! Returns the count of members in the enumeration.\n\n @return\n Member count.\n *\/\n static std::size_t size() {\n return T::smc_cMembers;\n }\n\nprotected:\n \/*! Returns a pointer to the name\/value pair for the current value.\n\n @return\n Pointer to the name\/value pair for the current value.\n *\/\n detail::enum_member const * _member() const {\n return detail::enum_member::find_in_map(T::_get_map(), m_e);\n }\n\npublic:\n \/*! Count of the members of the enumeration. Same as the value returned by size(), but this can\n be used in constant contexts, such as the size of an array.\n *\/\n static std::size_t const size_const = T::smc_cMembers;\n\nprivate:\n \/\/! Enumerated value.\n enum_type m_e;\n};\n\n\/\/ Relational operators.\n#define ABC_RELOP_IMPL(op) \\\n template <class T> \\\n inline bool operator op(enum_impl<T> const & e1, enum_impl<T> const & e2) { \\\n return e1.base() op e2.base(); \\\n } \\\n template <class T> \\\n inline bool operator op(enum_impl<T> const & e1, typename enum_impl<T>::enum_type e2) { \\\n return e1.base() op e2; \\\n } \\\n template <class T> \\\n inline bool operator op(typename enum_impl<T>::enum_type e1, enum_impl<T> const & e2) { \\\n return e1 op e2.base(); \\\n }\nABC_RELOP_IMPL(==)\nABC_RELOP_IMPL(!=)\nABC_RELOP_IMPL(>)\nABC_RELOP_IMPL(>=)\nABC_RELOP_IMPL(<)\nABC_RELOP_IMPL(<=)\n#undef ABC_RELOP_IMPL\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Change DOC:3549 into enumeration_classes page<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014, 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_HXX_INTERNAL\n #error \"Please #include <abaclade.hxx> instead of this file\"\n#endif\n\n\/*! @file\nFacilities to create smart enumerations, as described in @ref enumeration_classes\n*\/\n\/*! @page enumeration_classes Enumeration classes\nSupport for advanced enumeration classes. These are the features that set them apart from C++11\n“enum class” enumerations:\n\n• Strong typing: constants from one enumeration are not implicitly converted to a different\n enumeration type;\n• Scoped constants: the enumeration members are members of the enumeration class, not of its\n containing scope; different classes can therefore use constants of the same name because their\n usage will need to be qualified with the enumeration type name;\n• Conversion from\/to string: instances of an Abaclade enumeration class can be serialized and\n de-serialized as strings with no additional code.\n\nThe ABC_ENUM() macro declares an enumeration class containing the members provided as a list;\nABC_ENUM_AUTO_VALUES() behaves like a C++ enum lacking explicit enumerated values.\n\nThe name provided to ABC_ENUM() is associated to a C++ class, not the C++ enum; the latter is\navailable through the former, as in as my_enum::enum_type; there should little to no need to ever\ndirectly refer to the C++ enum type.\n\nThis design is loosely based on <http:\/\/www.python.org\/dev\/peps\/pep-0435\/>.\n*\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals\n\nnamespace abc {\n\n\/\/! @cond\n\n\/*! Implementation of the various ABC_ENUM*() flavors.\n\n@param name\n Name of the enumeration type.\n@param cMembers\n Count of members of the enumeration.\n@param members\n C++ enum members.\n@param arrayitems\n Internal name\/value array items.\n@param othermembers\n Additional members to be injected as-is at the beginning of the class.\n*\/\n#define _ABC_ENUM_IMPL(name, cMembers, members, arrayitems, othermembers) \\\n class ABC_CPP_CAT(_, name, _e) { \\\n othermembers \\\n \\\n public: \\\n \/*! Publicly-accessible enumerated constants. *\/ \\\n enum enum_type { \\\n members \\\n }; \\\n \\\n \/*! Returns a pointer to the name\/value map to be used by abc::enum_impl. *\/ \\\n static ::abc::detail::enum_member const * _get_map() { \\\n static ::abc::detail::enum_member const sc_map[] = { \\\n arrayitems \\\n { nullptr, 0, 0 } \\\n }; \\\n return sc_map; \\\n } \\\n \\\n protected: \\\n \/*! Number of members specified for the enum. *\/ \\\n static std::size_t const smc_cMembers = cMembers; \\\n }; \\\n typedef ::abc::enum_impl<ABC_CPP_CAT(_, name, _e)> name\n\n\/*! Expands into an enum name\/value assignment.\n\n@param name\n Name of the enumeration constant. The associated value is incremental in the ABC_ENUM, just like\n in C++ enums.\n*\/\n#define _ABC_ENUM_MEMBER(name) \\\n name = __COUNTER__ - smc_iBase,\n\n\/*! Expands into an enum name\/value assignment.\n\n@param name\n Name of the enumeration constant.\n@param value\n Value of the enumeration constant.\n*\/\n#define _ABC_ENUM_MEMBER_PAIR(name, value) \\\n name = value,\n\n\/*! Expands into an abc::detail::enum_member initializer.\n\n@param name\n Name of the enumeration constant.\n*\/\n#define _ABC_ENUM_MEMBER_ARRAY_ITEM(name) \\\n { \\\n ABC_SL(ABC_CPP_TOSTRING(name)), \\\n static_cast<unsigned short>(ABC_COUNTOF(ABC_CPP_TOSTRING(name)) - 1 \/*NUL*\/), \\\n name \\\n },\n\n\/*! Expands into _ABC_ENUM_MEMBER_ARRAY_ITEM().\n\n@param name\n Name of the enumeration constant.\n@param value\n Value of the enumeration constant. Not used.\n*\/\n#define _ABC_ENUM_MEMBER_PAIR_ARRAY_ITEM(name, value) \\\n _ABC_ENUM_MEMBER_ARRAY_ITEM(name)\n\n\/\/! @endcond\n\n\/*! Defines an enumeration class as a specialization of abc::enum_impl. See @ref enumeration_classes\nfor more information.\n\nTODO: support for bit-field enumerations? Allow logical operation, smart conversion to\/from string,\netc.\n\n@param name\n Name of the enumeration type.\n@param ...\n Sequence of (name, value) pairs; these will be the members of the underlying C++ enum,\n name::enum_type.\n*\/\n#define ABC_ENUM(name, ...) \\\n _ABC_ENUM_IMPL( \\\n name, \\\n ABC_CPP_LIST_COUNT(__VA_ARGS__), \\\n ABC_CPP_TUPLELIST_WALK(_ABC_ENUM_MEMBER_PAIR, __VA_ARGS__), \\\n ABC_CPP_TUPLELIST_WALK(_ABC_ENUM_MEMBER_PAIR_ARRAY_ITEM, __VA_ARGS__), \\\n \\\n public: \\\n )\n\n\/*! Defines an enumeration class as a specialization of abc::enum_impl. See @ref enumeration_classes\nfor more information. Similar to ABC_ENUM(), except the members are listed individually and their\nvalues cannot be explicitly specified; for example:\n\n ABC_ENUM_AUTO_VALUES(myenum, item1, item2, item3);\n\n@param name\n Name of the enumeration type.\n@param ...\n Sequence of member names; these will be the members of the underlying C++ enum, name::enum_type.\n Their values will start from 0 and increase by 1 for each member.\n*\/\n#define ABC_ENUM_AUTO_VALUES(name, ...) \\\n _ABC_ENUM_IMPL( \\\n name, \\\n ABC_CPP_LIST_COUNT(__VA_ARGS__), \\\n ABC_CPP_LIST_WALK(_ABC_ENUM_MEMBER, __VA_ARGS__), \\\n ABC_CPP_LIST_WALK(_ABC_ENUM_MEMBER_ARRAY_ITEM, __VA_ARGS__), \\\n \\\n private: \\\n static int const smc_iBase = __COUNTER__ + 1; \\\n )\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::detail::enum_member\n\nnamespace abc {\nnamespace detail {\n\n\/\/! Enumeration member (name\/value pair).\nstruct ABACLADE_SYM enum_member {\n \/\/! Name.\n char_t const * pszName;\n \/\/! Size of *pszName, in characters.\n unsigned short cchName;\n \/\/! Value.\n int iValue;\n\n \/*! Finds and returns the member associated to the specified enumerated value or name. If no\n match is found, an exception will be throw.\n\n @param pem\n Pointer to the first item in the enumeration members array; the last item in the array has a\n nullptr name string pointer.\n @param iValue\n Value of the constant to search for.\n @param sName\n Name of the constant to search for.\n @return\n Pointer to the matching name\/value pair.\n *\/\n static enum_member const * find_in_map(enum_member const * pem, int iValue);\n static enum_member const * find_in_map(enum_member const * pem, istr const & sName);\n};\n\n} \/\/namespace detail\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::enum_impl\n\nnamespace abc {\n\n\/\/! Implementation of enumeration classes.\ntemplate <class T>\nclass enum_impl : public T {\npublic:\n \/\/! Underlying C++ eunm type.\n typedef typename T::enum_type enum_type;\n\n \/*! Constructor.\n\n @param e\n Source value.\n @param iValue\n Integer value to be converted to enum_type. If i has a value not in enum_type, an exception\n will be thrown.\n @param sName\n String to be converted to enum_type. If this does not match exactly the name of one of the\n members of enum_type, an exception of type abc::domain_error will be thrown.\n *\/\n enum_impl() {\n }\n enum_impl(enum_type e) :\n m_e(e) {\n }\n enum_impl(enum_impl const & e) :\n m_e(e.m_e) {\n }\n \/\/ Conversion from integer.\n explicit enum_impl(int iValue) :\n m_e(static_cast<enum_type>(detail::enum_member::find_in_map(T::_get_map(), iValue)->iValue)) {\n }\n \/\/ Conversion from string.\n explicit enum_impl(istr const & sName) :\n m_e(static_cast<enum_type>(detail::enum_member::find_in_map(T::_get_map(), sName)->iValue)) {\n }\n\n \/*! Assignment operator.\n\n @param e\n Source value.\n @return\n *this.\n *\/\n enum_impl & operator=(enum_impl const & e) {\n m_e = e.m_e;\n return *this;\n }\n enum_impl & operator=(enum_type e) {\n m_e = e;\n return *this;\n }\n\n \/*! Returns the current base enumerated value.\n\n @return\n Current value.\n *\/\n enum_type base() const {\n return m_e;\n }\n\n \/*! Returns the name of the current enumerated value.\n\n @return\n Name of the current value.\n *\/\n istr name() const;\n\n \/*! Returns the count of members in the enumeration.\n\n @return\n Member count.\n *\/\n static std::size_t size() {\n return T::smc_cMembers;\n }\n\nprotected:\n \/*! Returns a pointer to the name\/value pair for the current value.\n\n @return\n Pointer to the name\/value pair for the current value.\n *\/\n detail::enum_member const * _member() const {\n return detail::enum_member::find_in_map(T::_get_map(), m_e);\n }\n\npublic:\n \/*! Count of the members of the enumeration. Same as the value returned by size(), but this can\n be used in constant contexts, such as the size of an array.\n *\/\n static std::size_t const size_const = T::smc_cMembers;\n\nprivate:\n \/\/! Enumerated value.\n enum_type m_e;\n};\n\n\/\/ Relational operators.\n#define ABC_RELOP_IMPL(op) \\\n template <class T> \\\n inline bool operator op(enum_impl<T> const & e1, enum_impl<T> const & e2) { \\\n return e1.base() op e2.base(); \\\n } \\\n template <class T> \\\n inline bool operator op(enum_impl<T> const & e1, typename enum_impl<T>::enum_type e2) { \\\n return e1.base() op e2; \\\n } \\\n template <class T> \\\n inline bool operator op(typename enum_impl<T>::enum_type e1, enum_impl<T> const & e2) { \\\n return e1 op e2.base(); \\\n }\nABC_RELOP_IMPL(==)\nABC_RELOP_IMPL(!=)\nABC_RELOP_IMPL(>)\nABC_RELOP_IMPL(>=)\nABC_RELOP_IMPL(<)\nABC_RELOP_IMPL(<=)\n#undef ABC_RELOP_IMPL\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ version.hpp\n\/\/ ***********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/ \n\n#pragma once\n\n#if !defined(AEGIS_VERSION_LONG)\n#define AEGIS_VERSION_LONG 0x00010400\n#define AEGIS_VERSION_SHORT 010400\n#define AEGIS_VERSION_TEXT \"aegis.cpp 1.4.0 2018\/10\/20\"\n\n#define AEGIS_VERSION_MAJOR ((AEGIS_VERSION_LONG & 0x00ff0000) >> 16)\n#define AEGIS_VERSION_MINOR ((AEGIS_VERSION_LONG & 0x0000ff00) >> 8)\n#define AEGIS_VERSION_PATCH (AEGIS_VERSION_LONG & 0x000000ff)\n#endif\n<commit_msg>Version bump<commit_after>\/\/\n\/\/ version.hpp\n\/\/ ***********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/ \n\n#pragma once\n\n#if !defined(AEGIS_VERSION_LONG)\n#define AEGIS_VERSION_LONG 0x00020000\n#define AEGIS_VERSION_SHORT 020000\n#define AEGIS_VERSION_TEXT \"aegis.cpp 2.0.0 2019\/2\/3\"\n\n#define AEGIS_VERSION_MAJOR ((AEGIS_VERSION_LONG & 0x00ff0000) >> 16)\n#define AEGIS_VERSION_MINOR ((AEGIS_VERSION_LONG & 0x0000ff00) >> 8)\n#define AEGIS_VERSION_PATCH (AEGIS_VERSION_LONG & 0x000000ff)\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <ostream>\n#include \"athena\/Types.hpp\"\n\n#define FMT_STRING_ALIAS 1\n#define FMT_ENFORCE_COMPILE_STRING 1\n#define FMT_USE_GRISU 0\n#include <fmt\/format.h>\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4996)\n\n#if defined(WINAPI_FAMILY) && WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP\n#define WINDOWS_STORE 1\n#else\n#define WINDOWS_STORE 0\n#endif\n\n#include <sys\/stat.h>\n\n#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)\n#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)\n#endif\n\n#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)\n#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)\n#endif\n\n#if !defined(S_ISLNK)\n#define S_ISLNK(m) 0\n#endif\n\n#define PRISize \"Iu\"\n\n#else\n\n#define PRISize \"zu\"\n\n#endif\n\/\/ clang-format off\n#ifndef AT_PRETTY_FUNCTION\n# if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)\n# define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__\n# elif defined(__FUNCSIG__)\n# define AT_PRETTY_FUNCTION __FUNCSIG__\n# elif defined(__FUNCTION__)\n# define AT_PRETTY_FUNCTION __FUNCTION__\n# elif defined(__FUNC__)\n# define AT_PRETTY_FUNCTION __FUNC__\n# elif defined(__func__)\n# define AT_PRETTY_FUNCTION __func__\n# else\n# define AT_PRETTY_FUNCTION \"<unknown>\"\n# endif\n#endif\n\/\/ clang-format on\n\n#if defined(GEKKO) || defined(__SWITCH__)\n#include \"gekko_support.h\"\ntypedef struct stat atStat64_t;\n#define atStat64 stat\n#elif _WIN32\ntypedef struct _stat64 atStat64_t;\n#define atStat64 _stat64\n#elif __APPLE__ || __FreeBSD__\ntypedef struct stat atStat64_t;\n#define atStat64 stat\n#else\ntypedef struct stat64 atStat64_t;\n#define atStat64 stat64\n#endif\n\n#ifndef BLOCKSZ\n#define BLOCKSZ 512\n#endif\n\n#define ROUND_UP_256(val) (((val) + 255) & ~255)\n#define ROUND_UP_64(val) (((val) + 63) & ~63)\n#define ROUND_UP_32(val) (((val) + 31) & ~31)\n#define ROUND_UP_16(val) (((val) + 15) & ~15)\n#define ROUND_UP_8(val) (((val) + 7) & ~7)\n#define ROUND_UP_4(val) (((val) + 3) & ~3)\n\n#define _XSTR(s) _STR(s)\n#define _STR(s) #s\n\n#ifndef ENABLE_BITWISE_ENUM\n#define ENABLE_BITWISE_ENUM(type) \\\n constexpr type operator|(type a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(static_cast<T>(a) | static_cast<T>(b)); \\\n } \\\n constexpr type operator&(type a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(static_cast<T>(a) & static_cast<T>(b)); \\\n } \\\n constexpr type& operator|=(type& a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n a = type(static_cast<T>(a) | static_cast<T>(b)); \\\n return a; \\\n } \\\n constexpr type& operator&=(type& a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n a = type(static_cast<T>(a) & static_cast<T>(b)); \\\n return a; \\\n } \\\n constexpr type operator~(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(~static_cast<T>(key)); \\\n } \\\n constexpr bool True(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return static_cast<T>(key) != 0; \\\n } \\\n constexpr bool False(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return static_cast<T>(key) == 0; \\\n }\n#endif\n\nnamespace athena {\nnamespace error {\nenum class Level { Message, Warning, Error, Fatal };\n}\nenum class SeekOrigin { Begin, Current, End };\n\nenum class Endian { Little, Big };\n\nnamespace io {\ntemplate <Endian DNAE>\nstruct DNA;\ntemplate <Endian DNAE>\nstruct DNAV;\n\ntemplate <class T>\nusing __IsDNARecord = std::disjunction<std::is_base_of<DNA<Endian::Big>, T>, std::is_base_of<DNA<Endian::Little>, T>>;\ntemplate <class T>\nconstexpr bool __IsDNARecord_v = __IsDNARecord<T>::value;\n\ntemplate <class T>\nusing __IsDNAVRecord =\n std::disjunction<std::is_base_of<DNAV<Endian::Big>, T>, std::is_base_of<DNAV<Endian::Little>, T>>;\ntemplate <class T>\nconstexpr bool __IsDNAVRecord_v = __IsDNAVRecord<T>::value;\n} \/\/ namespace io\n} \/\/ namespace athena\n\ntypedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* \/*file*\/, const char*, int \/*line*\/,\n fmt::string_view fmt, fmt::format_args args);\n\natEXCEPTION_HANDLER atGetExceptionHandler();\n\/**\n * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,\n * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.\n *\/\nvoid atSetExceptionHandler(atEXCEPTION_HANDLER func);\n\nstd::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);\nstd::ostream& operator<<(std::ostream& os, const athena::Endian& endian);\n\ntemplate <typename First, typename... Rest>\nconstexpr auto __FIRST_ARG__(First first, Rest...) { return first; }\ntemplate <typename S, typename... Args>\nauto __make_args_checked__(const S& format_str, Args&&... args) {\n return fmt::internal::make_args_checked<Args...>(format_str, std::forward<Args>(args)...);\n}\n\n#ifndef NDEBUG\n#define atDebug(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n#else\n#define atDebug(...)\n#endif\n\n#define atMessage(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n\n#define atWarning(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) { \\\n __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } \\\n } while (0)\n\n#define atError(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n\n#define atFatal(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n<commit_msg>Global: Remove compatibility formatting define for size_t<commit_after>#pragma once\n\n#include <ostream>\n#include \"athena\/Types.hpp\"\n\n#define FMT_STRING_ALIAS 1\n#define FMT_ENFORCE_COMPILE_STRING 1\n#define FMT_USE_GRISU 0\n#include <fmt\/format.h>\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4996)\n\n#if defined(WINAPI_FAMILY) && WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP\n#define WINDOWS_STORE 1\n#else\n#define WINDOWS_STORE 0\n#endif\n\n#include <sys\/stat.h>\n\n#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)\n#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)\n#endif\n\n#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)\n#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)\n#endif\n\n#if !defined(S_ISLNK)\n#define S_ISLNK(m) 0\n#endif\n#endif \/\/ _MSC_VER\n\n\/\/ clang-format off\n#ifndef AT_PRETTY_FUNCTION\n# if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)\n# define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__\n# elif defined(__FUNCSIG__)\n# define AT_PRETTY_FUNCTION __FUNCSIG__\n# elif defined(__FUNCTION__)\n# define AT_PRETTY_FUNCTION __FUNCTION__\n# elif defined(__FUNC__)\n# define AT_PRETTY_FUNCTION __FUNC__\n# elif defined(__func__)\n# define AT_PRETTY_FUNCTION __func__\n# else\n# define AT_PRETTY_FUNCTION \"<unknown>\"\n# endif\n#endif\n\/\/ clang-format on\n\n#if defined(GEKKO) || defined(__SWITCH__)\n#include \"gekko_support.h\"\ntypedef struct stat atStat64_t;\n#define atStat64 stat\n#elif _WIN32\ntypedef struct _stat64 atStat64_t;\n#define atStat64 _stat64\n#elif __APPLE__ || __FreeBSD__\ntypedef struct stat atStat64_t;\n#define atStat64 stat\n#else\ntypedef struct stat64 atStat64_t;\n#define atStat64 stat64\n#endif\n\n#ifndef BLOCKSZ\n#define BLOCKSZ 512\n#endif\n\n#define ROUND_UP_256(val) (((val) + 255) & ~255)\n#define ROUND_UP_64(val) (((val) + 63) & ~63)\n#define ROUND_UP_32(val) (((val) + 31) & ~31)\n#define ROUND_UP_16(val) (((val) + 15) & ~15)\n#define ROUND_UP_8(val) (((val) + 7) & ~7)\n#define ROUND_UP_4(val) (((val) + 3) & ~3)\n\n#define _XSTR(s) _STR(s)\n#define _STR(s) #s\n\n#ifndef ENABLE_BITWISE_ENUM\n#define ENABLE_BITWISE_ENUM(type) \\\n constexpr type operator|(type a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(static_cast<T>(a) | static_cast<T>(b)); \\\n } \\\n constexpr type operator&(type a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(static_cast<T>(a) & static_cast<T>(b)); \\\n } \\\n constexpr type& operator|=(type& a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n a = type(static_cast<T>(a) | static_cast<T>(b)); \\\n return a; \\\n } \\\n constexpr type& operator&=(type& a, type b) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n a = type(static_cast<T>(a) & static_cast<T>(b)); \\\n return a; \\\n } \\\n constexpr type operator~(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return type(~static_cast<T>(key)); \\\n } \\\n constexpr bool True(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return static_cast<T>(key) != 0; \\\n } \\\n constexpr bool False(type key) noexcept { \\\n using T = std::underlying_type_t<type>; \\\n return static_cast<T>(key) == 0; \\\n }\n#endif\n\nnamespace athena {\nnamespace error {\nenum class Level { Message, Warning, Error, Fatal };\n}\nenum class SeekOrigin { Begin, Current, End };\n\nenum class Endian { Little, Big };\n\nnamespace io {\ntemplate <Endian DNAE>\nstruct DNA;\ntemplate <Endian DNAE>\nstruct DNAV;\n\ntemplate <class T>\nusing __IsDNARecord = std::disjunction<std::is_base_of<DNA<Endian::Big>, T>, std::is_base_of<DNA<Endian::Little>, T>>;\ntemplate <class T>\nconstexpr bool __IsDNARecord_v = __IsDNARecord<T>::value;\n\ntemplate <class T>\nusing __IsDNAVRecord =\n std::disjunction<std::is_base_of<DNAV<Endian::Big>, T>, std::is_base_of<DNAV<Endian::Little>, T>>;\ntemplate <class T>\nconstexpr bool __IsDNAVRecord_v = __IsDNAVRecord<T>::value;\n} \/\/ namespace io\n} \/\/ namespace athena\n\ntypedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* \/*file*\/, const char*, int \/*line*\/,\n fmt::string_view fmt, fmt::format_args args);\n\natEXCEPTION_HANDLER atGetExceptionHandler();\n\/**\n * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,\n * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.\n *\/\nvoid atSetExceptionHandler(atEXCEPTION_HANDLER func);\n\nstd::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);\nstd::ostream& operator<<(std::ostream& os, const athena::Endian& endian);\n\ntemplate <typename First, typename... Rest>\nconstexpr auto __FIRST_ARG__(First first, Rest...) { return first; }\ntemplate <typename S, typename... Args>\nauto __make_args_checked__(const S& format_str, Args&&... args) {\n return fmt::internal::make_args_checked<Args...>(format_str, std::forward<Args>(args)...);\n}\n\n#ifndef NDEBUG\n#define atDebug(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n#else\n#define atDebug(...)\n#endif\n\n#define atMessage(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n\n#define atWarning(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) { \\\n __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } \\\n } while (0)\n\n#define atError(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n\n#define atFatal(...) \\\n do { \\\n atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \\\n if (__handler) \\\n __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__), \\\n __make_args_checked__(__VA_ARGS__)); \\\n } while (0)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/defaults.h\"\n\nnamespace browser_defaults {\n\n#if defined(OS_CHROMEOS)\n\n\/\/ Make the regular omnibox text two points larger than the nine-point font\n\/\/ used in the tab strip (11pt \/ 72pt\/in * 96px\/in = 14.667px).\nconst int kAutocompleteEditFontPixelSize = 15;\n\nconst int kAutocompleteEditFontPixelSizeInPopup = 10;\n\nconst SessionStartupPref::Type kDefaultSessionStartupType =\n SessionStartupPref::LAST;\nconst int kMiniTabWidth = 64;\nconst bool kCanToggleSystemTitleBar = false;\nconst bool kRestorePopups = true;\nconst bool kShowImportOnBookmarkBar = false;\nconst bool kShowExitMenuItem = true;\nconst bool kOSSupportsOtherBrowsers = false;\nconst bool kDownloadPageHasShowInFolder = true;\nconst bool kSizeTabButtonToTopOfTabStrip = true;\nconst bool kBootstrapSyncAuthentication = true;\nconst bool kShowOtherBrowsersInAboutMemory = false;\nconst bool kAlwaysOpenIncognitoWindow = true;\nconst bool kShowCancelButtonInTaskManager = true;\n\n#elif defined(TOOLKIT_USES_GTK)\n\n\/\/ 14px = 10.5pt @ 96dpi.\nconst int kAutocompleteEditFontPixelSize = 14;\n\n\/\/ On Windows, popup windows' location text uses a font 5\/6 the size of\n\/\/ that in a regular window, which we duplicate here for GTK.\nconst int kAutocompleteEditFontPixelSizeInPopup =\n kAutocompleteEditFontPixelSize * 5.0 \/ 6.0;\n\n#if defined(TOOLKIT_VIEWS)\nconst bool kCanToggleSystemTitleBar = false;\n#else\nconst bool kCanToggleSystemTitleBar = true;\n#endif\n\n#endif\n\n#if !defined(OS_CHROMEOS)\n\nconst SessionStartupPref::Type kDefaultSessionStartupType =\n SessionStartupPref::DEFAULT;\nconst int kMiniTabWidth = 56;\nconst bool kRestorePopups = false;\nconst bool kShowImportOnBookmarkBar = true;\nconst bool kDownloadPageHasShowInFolder = true;\n#if defined(OS_MACOSX)\nconst bool kShowExitMenuItem = false;\n#else\nconst bool kShowExitMenuItem = true;\n#endif\nconst bool kOSSupportsOtherBrowsers = true;\nconst bool kSizeTabButtonToTopOfTabStrip = false;\nconst bool kBootstrapSyncAuthentication = false;\nconst bool kShowOtherBrowsersInAboutMemory = true;\nconst bool kAlwaysOpenIncognitoWindow = false;\nconst bool kShowCancelButtonInTaskManager = false;\n#endif\n\n#if defined(OS_MACOSX)\nconst bool kBrowserAliveWithNoWindows = true;\n#else\nconst bool kBrowserAliveWithNoWindows = false;\n#endif\n\n#ifdef TOUCH_UI\nconst int kBookmarkBarHeight = 50;\nconst int kNewtabBookmarkBarHeight = 72;\n#else\nconst int kBookmarkBarHeight = 28;\nconst int kNewtabBookmarkBarHeight = 57;\n#endif\n\n#ifdef TOUCH_UI\nconst ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =\n ui::ResourceBundle::LargeBoldFont;\n#else\nconst ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =\n ui::ResourceBundle::BoldFont;\n#endif\n\n#ifdef TOUCH_UI\nconst int kInfoBarBorderPaddingVertical = 12;\n#else\nconst int kInfoBarBorderPaddingVertical = 5;\n#endif\n\nbool bookmarks_enabled = true;\n\nbool skip_restore = false;\n\nbool enable_help_app = true;\n\n} \/\/ namespace browser_defaults\n<commit_msg>Do not restore popups on ChromeOS<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/defaults.h\"\n\nnamespace browser_defaults {\n\n#if defined(OS_CHROMEOS)\n\n\/\/ Make the regular omnibox text two points larger than the nine-point font\n\/\/ used in the tab strip (11pt \/ 72pt\/in * 96px\/in = 14.667px).\nconst int kAutocompleteEditFontPixelSize = 15;\n\nconst int kAutocompleteEditFontPixelSizeInPopup = 10;\n\nconst SessionStartupPref::Type kDefaultSessionStartupType =\n SessionStartupPref::LAST;\nconst int kMiniTabWidth = 64;\nconst bool kCanToggleSystemTitleBar = false;\nconst bool kRestorePopups = false;\nconst bool kShowImportOnBookmarkBar = false;\nconst bool kShowExitMenuItem = true;\nconst bool kOSSupportsOtherBrowsers = false;\nconst bool kDownloadPageHasShowInFolder = true;\nconst bool kSizeTabButtonToTopOfTabStrip = true;\nconst bool kBootstrapSyncAuthentication = true;\nconst bool kShowOtherBrowsersInAboutMemory = false;\nconst bool kAlwaysOpenIncognitoWindow = true;\nconst bool kShowCancelButtonInTaskManager = true;\n\n#elif defined(TOOLKIT_USES_GTK)\n\n\/\/ 14px = 10.5pt @ 96dpi.\nconst int kAutocompleteEditFontPixelSize = 14;\n\n\/\/ On Windows, popup windows' location text uses a font 5\/6 the size of\n\/\/ that in a regular window, which we duplicate here for GTK.\nconst int kAutocompleteEditFontPixelSizeInPopup =\n kAutocompleteEditFontPixelSize * 5.0 \/ 6.0;\n\n#if defined(TOOLKIT_VIEWS)\nconst bool kCanToggleSystemTitleBar = false;\n#else\nconst bool kCanToggleSystemTitleBar = true;\n#endif\n\n#endif\n\n#if !defined(OS_CHROMEOS)\n\nconst SessionStartupPref::Type kDefaultSessionStartupType =\n SessionStartupPref::DEFAULT;\nconst int kMiniTabWidth = 56;\nconst bool kRestorePopups = false;\nconst bool kShowImportOnBookmarkBar = true;\nconst bool kDownloadPageHasShowInFolder = true;\n#if defined(OS_MACOSX)\nconst bool kShowExitMenuItem = false;\n#else\nconst bool kShowExitMenuItem = true;\n#endif\nconst bool kOSSupportsOtherBrowsers = true;\nconst bool kSizeTabButtonToTopOfTabStrip = false;\nconst bool kBootstrapSyncAuthentication = false;\nconst bool kShowOtherBrowsersInAboutMemory = true;\nconst bool kAlwaysOpenIncognitoWindow = false;\nconst bool kShowCancelButtonInTaskManager = false;\n#endif\n\n#if defined(OS_MACOSX)\nconst bool kBrowserAliveWithNoWindows = true;\n#else\nconst bool kBrowserAliveWithNoWindows = false;\n#endif\n\n#ifdef TOUCH_UI\nconst int kBookmarkBarHeight = 50;\nconst int kNewtabBookmarkBarHeight = 72;\n#else\nconst int kBookmarkBarHeight = 28;\nconst int kNewtabBookmarkBarHeight = 57;\n#endif\n\n#ifdef TOUCH_UI\nconst ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =\n ui::ResourceBundle::LargeBoldFont;\n#else\nconst ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =\n ui::ResourceBundle::BoldFont;\n#endif\n\n#ifdef TOUCH_UI\nconst int kInfoBarBorderPaddingVertical = 12;\n#else\nconst int kInfoBarBorderPaddingVertical = 5;\n#endif\n\nbool bookmarks_enabled = true;\n\nbool skip_restore = false;\n\nbool enable_help_app = true;\n\n} \/\/ namespace browser_defaults\n<|endoftext|>"} {"text":"<commit_before>#ifndef OSRM_BASE64_HPP\n#define OSRM_BASE64_HPP\n\n#include <string>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n\n#include <cstddef>\n#include <climits>\n\n#include <boost\/archive\/iterators\/binary_from_base64.hpp>\n#include <boost\/archive\/iterators\/base64_from_binary.hpp>\n#include <boost\/archive\/iterators\/transform_width.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/range\/algorithm\/copy.hpp>\n\n\/\/ RFC 4648 \"The Base16, Base32, and Base64 Data Encodings\"\n\/\/ See: https:\/\/tools.ietf.org\/html\/rfc4648\n\nnamespace detail\n{\n\/\/ The C++ standard guarantees none of this by default, but we need it in the following.\nstatic_assert(CHAR_BIT == 8u, \"we assume a byte holds 8 bits\");\nstatic_assert(sizeof(char) == 1u, \"we assume a char is one byte large\");\n\nusing Base64FromBinary = boost::archive::iterators::base64_from_binary<\n boost::archive::iterators::transform_width<const char *, \/\/ sequence of chars\n 6, \/\/ get view of 6 bit\n 8 \/\/ from sequence of 8 bit\n >>;\n\nusing BinaryFromBase64 = boost::archive::iterators::transform_width<\n boost::archive::iterators::binary_from_base64<std::string::const_iterator>,\n 8, \/\/ get a view of 8 bit\n 6 \/\/ from a sequence of 6 bit\n >;\n} \/\/ ns detail\n\nnamespace osrm\n{\nnamespace engine\n{\n\n\/\/ Encoding Implementation\n\n\/\/ Encodes a chunk of memory to Base64.\ninline std::string encodeBase64(const unsigned char *first, std::size_t size)\n{\n std::vector<unsigned char> bytes{first, first + size};\n BOOST_ASSERT(!bytes.empty());\n\n std::size_t bytes_to_pad{0};\n\n while (bytes.size() % 3 != 0)\n {\n bytes_to_pad += 1;\n bytes.push_back(0);\n }\n\n BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);\n BOOST_ASSERT_MSG(0 == bytes.size() % 3, \"base64 input data size is not a multiple of 3\");\n\n std::string encoded{detail::Base64FromBinary{bytes.data()},\n detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};\n\n return encoded.append(bytes_to_pad, '=');\n}\n\n\/\/ C++11 standard 3.9.1\/1: Plain char, signed char, and unsigned char are three distinct types\n\n\/\/ Overload for signed char catches (not only but also) C-string literals.\ninline std::string encodeBase64(const signed char *first, std::size_t size)\n{\n return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);\n}\n\n\/\/ Overload for char catches (not only but also) C-string literals.\ninline std::string encodeBase64(const char *first, std::size_t size)\n{\n return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);\n}\n\n\/\/ Convenience specialization, encoding from string instead of byte-dumping it.\ninline std::string encodeBase64(const std::string &x) { return encodeBase64(x.data(), x.size()); }\n\n\/\/ Encode any sufficiently trivial object to Base64.\ntemplate <typename T> std::string encodeBase64Bytewise(const T &x)\n{\n#if not defined __GNUC__ or __GNUC__ > 4\n static_assert(std::is_trivially_copyable<T>::value, \"requires a trivially copyable type\");\n#endif\n\n return encodeBase64(reinterpret_cast<const unsigned char *>(&x), sizeof(T));\n}\n\n\/\/ Decoding Implementation\n\n\/\/ Decodes into a chunk of memory that is at least as large as the input.\ntemplate <typename OutputIter> void decodeBase64(const std::string &encoded, OutputIter out)\n{\n auto unpadded = encoded;\n\n const auto num_padded = std::count(begin(encoded), end(encoded), '=');\n std::replace(begin(unpadded), end(unpadded), '=', 'A'); \/\/ A_64 == \\0\n\n std::string decoded{detail::BinaryFromBase64{begin(unpadded)},\n detail::BinaryFromBase64{begin(unpadded) + unpadded.length()}};\n\n decoded.erase(end(decoded) - num_padded, end(decoded));\n std::copy(begin(decoded), end(decoded), out);\n}\n\n\/\/ Convenience specialization, filling string instead of byte-dumping into it.\ninline std::string decodeBase64(const std::string &encoded)\n{\n std::string rv;\n\n decodeBase64(encoded, std::back_inserter(rv));\n\n return rv;\n}\n\n\/\/ Decodes from Base 64 to any sufficiently trivial object.\ntemplate <typename T> T decodeBase64Bytewise(const std::string &encoded)\n{\n#if not defined __GNUC__ or __GNUC__ > 4\n static_assert(std::is_trivially_copyable<T>::value, \"requires a trivially copyable type\");\n#endif\n\n T x;\n\n decodeBase64(encoded, reinterpret_cast<unsigned char *>(&x));\n\n return x;\n}\n\n} \/\/ ns engine\n} \/\/ ns osrm\n\n#endif \/* OSRM_BASE64_HPP *\/\n<commit_msg>Move detail:: to osrm::detail::<commit_after>#ifndef OSRM_BASE64_HPP\n#define OSRM_BASE64_HPP\n\n#include <string>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n\n#include <cstddef>\n#include <climits>\n\n#include <boost\/archive\/iterators\/binary_from_base64.hpp>\n#include <boost\/archive\/iterators\/base64_from_binary.hpp>\n#include <boost\/archive\/iterators\/transform_width.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/range\/algorithm\/copy.hpp>\n\nnamespace osrm\n{\n\n\/\/ RFC 4648 \"The Base16, Base32, and Base64 Data Encodings\"\n\/\/ See: https:\/\/tools.ietf.org\/html\/rfc4648\n\nnamespace detail\n{\n\/\/ The C++ standard guarantees none of this by default, but we need it in the following.\nstatic_assert(CHAR_BIT == 8u, \"we assume a byte holds 8 bits\");\nstatic_assert(sizeof(char) == 1u, \"we assume a char is one byte large\");\n\nusing Base64FromBinary = boost::archive::iterators::base64_from_binary<\n boost::archive::iterators::transform_width<const char *, \/\/ sequence of chars\n 6, \/\/ get view of 6 bit\n 8 \/\/ from sequence of 8 bit\n >>;\n\nusing BinaryFromBase64 = boost::archive::iterators::transform_width<\n boost::archive::iterators::binary_from_base64<std::string::const_iterator>,\n 8, \/\/ get a view of 8 bit\n 6 \/\/ from a sequence of 6 bit\n >;\n} \/\/ ns detail\nnamespace engine\n{\n\n\/\/ Encoding Implementation\n\n\/\/ Encodes a chunk of memory to Base64.\ninline std::string encodeBase64(const unsigned char *first, std::size_t size)\n{\n std::vector<unsigned char> bytes{first, first + size};\n BOOST_ASSERT(!bytes.empty());\n\n std::size_t bytes_to_pad{0};\n\n while (bytes.size() % 3 != 0)\n {\n bytes_to_pad += 1;\n bytes.push_back(0);\n }\n\n BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);\n BOOST_ASSERT_MSG(0 == bytes.size() % 3, \"base64 input data size is not a multiple of 3\");\n\n std::string encoded{detail::Base64FromBinary{bytes.data()},\n detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};\n\n return encoded.append(bytes_to_pad, '=');\n}\n\n\/\/ C++11 standard 3.9.1\/1: Plain char, signed char, and unsigned char are three distinct types\n\n\/\/ Overload for signed char catches (not only but also) C-string literals.\ninline std::string encodeBase64(const signed char *first, std::size_t size)\n{\n return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);\n}\n\n\/\/ Overload for char catches (not only but also) C-string literals.\ninline std::string encodeBase64(const char *first, std::size_t size)\n{\n return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);\n}\n\n\/\/ Convenience specialization, encoding from string instead of byte-dumping it.\ninline std::string encodeBase64(const std::string &x) { return encodeBase64(x.data(), x.size()); }\n\n\/\/ Encode any sufficiently trivial object to Base64.\ntemplate <typename T> std::string encodeBase64Bytewise(const T &x)\n{\n#if not defined __GNUC__ or __GNUC__ > 4\n static_assert(std::is_trivially_copyable<T>::value, \"requires a trivially copyable type\");\n#endif\n\n return encodeBase64(reinterpret_cast<const unsigned char *>(&x), sizeof(T));\n}\n\n\/\/ Decoding Implementation\n\n\/\/ Decodes into a chunk of memory that is at least as large as the input.\ntemplate <typename OutputIter> void decodeBase64(const std::string &encoded, OutputIter out)\n{\n auto unpadded = encoded;\n\n const auto num_padded = std::count(begin(encoded), end(encoded), '=');\n std::replace(begin(unpadded), end(unpadded), '=', 'A'); \/\/ A_64 == \\0\n\n std::string decoded{detail::BinaryFromBase64{begin(unpadded)},\n detail::BinaryFromBase64{begin(unpadded) + unpadded.length()}};\n\n decoded.erase(end(decoded) - num_padded, end(decoded));\n std::copy(begin(decoded), end(decoded), out);\n}\n\n\/\/ Convenience specialization, filling string instead of byte-dumping into it.\ninline std::string decodeBase64(const std::string &encoded)\n{\n std::string rv;\n\n decodeBase64(encoded, std::back_inserter(rv));\n\n return rv;\n}\n\n\/\/ Decodes from Base 64 to any sufficiently trivial object.\ntemplate <typename T> T decodeBase64Bytewise(const std::string &encoded)\n{\n#if not defined __GNUC__ or __GNUC__ > 4\n static_assert(std::is_trivially_copyable<T>::value, \"requires a trivially copyable type\");\n#endif\n\n T x;\n\n decodeBase64(encoded, reinterpret_cast<unsigned char *>(&x));\n\n return x;\n}\n\n} \/\/ ns engine\n} \/\/ ns osrm\n\n#endif \/* OSRM_BASE64_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <algorithm>\n\n#include \"..\/config.hpp\"\n#include \"..\/traits_lite.hpp\"\n\n#include \"std\/mmul.hpp\"\n#include \"std\/strassen_mmul.hpp\"\n#include \"blas\/gemm.hpp\"\n#include \"eblas\/gemm.hpp\"\n\nnamespace etl {\n\nnamespace detail {\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct mm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct is_fast_dgemm : cpp::and_c<cpp::not_c<is_cblas_enabled>, all_double_precision<A, B, C>, all_dma<A, B, C>> {};\n\ntemplate<typename A, typename B, typename C>\nstruct is_fast_sgemm : cpp::and_c<cpp::not_c<is_cblas_enabled>, all_single_precision<A, B, C>, all_dma<A, B, C>> {};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::eblas::fast_dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::eblas::fast_sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct is_blas_dgemm : cpp::and_c<is_cblas_enabled, all_double_precision<A, B, C>, all_dma<A, B, C>> {};\n\ntemplate<typename A, typename B, typename C>\nstruct is_blas_sgemm : cpp::and_c<is_cblas_enabled, all_single_precision<A, B, C>, all_dma<A, B, C>> {};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct strassen_mm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::strassen_mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct vm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::vm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct mv_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::mv_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<commit_msg>Refactorings<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <algorithm>\n\n#include \"..\/config.hpp\"\n#include \"..\/traits_lite.hpp\"\n\n#include \"std\/mmul.hpp\"\n#include \"std\/strassen_mmul.hpp\"\n#include \"blas\/gemm.hpp\"\n#include \"eblas\/gemm.hpp\"\n\nnamespace etl {\n\nnamespace detail {\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct mm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nusing is_fast_dgemm = cpp::and_c<cpp::not_c<is_cblas_enabled>, all_double_precision<A, B, C>, all_dma<A, B, C>>;\n\ntemplate<typename A, typename B, typename C>\nusing is_fast_sgemm = cpp::and_c<cpp::not_c<is_cblas_enabled>, all_single_precision<A, B, C>, all_dma<A, B, C>>;\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::eblas::fast_dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::eblas::fast_sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nusing is_blas_dgemm = cpp::and_c<is_cblas_enabled, all_double_precision<A, B, C>, all_dma<A, B, C>>;\n\ntemplate<typename A, typename B, typename C>\nusing is_blas_sgemm = cpp::and_c<is_cblas_enabled, all_single_precision<A, B, C>, all_dma<A, B, C>>;\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct strassen_mm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::strassen_mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct vm_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::vm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C, typename Enable = void>\nstruct mv_mul_impl {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::standard::mv_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::dgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\ntemplate<typename A, typename B, typename C>\nstruct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {\n static void apply(A&& a, B&& b, C&& c){\n etl::impl::blas::sgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));\n }\n};\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before>#ifndef INFO_ITERATOR_HPP\n#define INFO_ITERATOR_HPP\n\n\n#include <cstddef>\n#include <iterator>\n\n\nnamespace shadow\n{\nclass reflection_manager;\n\n\ntemplate <class InfoType, class ProxyType>\nclass indexed_info_iterator_\n{\npublic:\n typedef ProxyType value_type;\n typedef std::ptrdiff_t difference_type;\n typedef ProxyType reference;\n typedef ProxyType pointer;\n typedef std::random_access_iterator_tag iterator_category;\n\npublic:\n indexed_info_iterator_()\n : current_index_(0), index_buffer_(nullptr), data_buffer_(nullptr)\n {\n }\n\n indexed_info_iterator_(std::size_t current_index,\n const std::size_t* index_buffer,\n InfoType* data_buffer,\n const reflection_manager* manager)\n : current_index_(current_index),\n index_buffer_(index_buffer),\n data_buffer_(data_buffer),\n manager_(manager)\n {\n }\n\npublic:\n ProxyType operator*() const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_],\n manager_);\n }\n\n ProxyType operator->() const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_],\n manager_);\n }\n\n ProxyType operator[](difference_type n) const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_ + n],\n manager_);\n }\n\n indexed_info_iterator_& operator++()\n {\n ++current_index_;\n return *this;\n }\n\n indexed_info_iterator_ operator++(int)\n {\n auto temp = *this;\n ++(*this);\n return temp;\n }\n\n indexed_info_iterator_& operator--()\n {\n --current_index_;\n return *this;\n }\n\n indexed_info_iterator_ operator--(int)\n {\n auto temp = *this;\n --(*this);\n return temp;\n }\n\n indexed_info_iterator_&\n operator+=(difference_type n)\n {\n current_index_ += n;\n return *this;\n }\n\n indexed_info_iterator_&\n operator-=(difference_type n)\n {\n current_index_ -= n;\n return *this;\n }\n\n indexed_info_iterator_\n operator+(difference_type n) const\n {\n return indexed_info_iterator_(\n current_index_ + n, index_buffer_, data_buffer_, manager_);\n }\n\n indexed_info_iterator_\n operator-(difference_type n) const\n {\n return indexed_info_iterator_(\n current_index_ - n, index_buffer_, data_buffer_, manager_);\n }\n\n difference_type\n operator-(const indexed_info_iterator_& other) const\n {\n return current_index_ - other.current_index_;\n }\n\n friend indexed_info_iterator_\n operator+(difference_type lhs, const indexed_info_iterator_& rhs)\n {\n return rhs + lhs;\n }\n\n bool\n operator==(const indexed_info_iterator_& other) const\n {\n return current_index_ == other.current_index_;\n }\n\n bool\n operator!=(const indexed_info_iterator_& other) const\n {\n return current_index_ != other.current_index_;\n }\n\n bool\n operator<(const indexed_info_iterator_& other) const\n {\n return current_index_ < other.current_index_;\n }\n\n bool\n operator>(const indexed_info_iterator_& other) const\n {\n return current_index_ > other.current_index_;\n }\n\n bool\n operator<=(const indexed_info_iterator_& other) const\n {\n return current_index_ <= other.current_index_;\n }\n\n bool\n operator>=(const indexed_info_iterator_& other) const\n {\n return current_index_ >= other.current_index_;\n }\n\nprivate:\n std::size_t current_index_;\n const std::size_t* index_buffer_;\n InfoType* data_buffer_;\n const reflection_manager* manager_;\n};\n\n\ntemplate <class InfoType, class ProxyType>\nclass info_iterator_\n{\npublic:\n typedef ProxyType value_type;\n typedef typename std::iterator_traits<const InfoType*>::difference_type\n difference_type;\n typedef ProxyType reference;\n typedef ProxyType pointer;\n typedef typename std::iterator_traits<const InfoType*>::iterator_category\n iterator_category;\n\npublic:\n info_iterator_() = default;\n\n\n info_iterator_(const InfoType* current, const reflection_manager* manager)\n : current_(current), manager_(manager)\n {\n }\n\npublic:\n ProxyType operator*() const\n {\n return ProxyType(current_, manager_);\n }\n\n ProxyType operator->() const\n {\n return ProxyType(current_, manager_);\n }\n\n ProxyType operator[](difference_type n) const\n {\n return ProxyType(current_ + n, manager_);\n }\n\n info_iterator_& operator++()\n {\n ++current_;\n return *this;\n }\n\n info_iterator_ operator++(int)\n {\n auto temp = *this;\n ++(*this);\n return temp;\n }\n\n info_iterator_& operator--()\n {\n --current_;\n return *this;\n }\n\n info_iterator_ operator--(int)\n {\n auto temp = *this;\n --(*this);\n return temp;\n }\n\n info_iterator_&\n operator+=(difference_type n)\n {\n current_ += n;\n return *this;\n }\n\n info_iterator_&\n operator-=(difference_type n)\n {\n current_ -= n;\n return *this;\n }\n\n info_iterator_\n operator+(difference_type n) const\n {\n return info_iterator_(current_ + n, manager_);\n }\n\n info_iterator_\n operator-(difference_type n) const\n {\n return info_iterator_(current_ - n, manager_);\n }\n\n difference_type\n operator-(const info_iterator_& other) const\n {\n return current_ - other.current_;\n }\n\n friend info_iterator_\n operator+(difference_type lhs, const info_iterator_& rhs)\n {\n return rhs + lhs;\n }\n\n bool\n operator==(const info_iterator_& other) const\n {\n return current_ == other.current_;\n }\n\n bool\n operator!=(const info_iterator_& other) const\n {\n return current_ != other.current_;\n }\n\n bool\n operator<(const info_iterator_& other) const\n {\n return current_ < other.current_;\n }\n\n bool\n operator>(const info_iterator_& other) const\n {\n return current_ > other.current_;\n }\n\n bool\n operator<=(const info_iterator_& other) const\n {\n return current_ <= other.current_;\n }\n\n bool\n operator>=(const info_iterator_& other) const\n {\n return current_ >= other.current_;\n }\n\nprivate:\n InfoType* current_;\n const reflection_manager* manager_;\n};\n} \/\/ namespace shadow\n\n\nnamespace std\n{\n\/\/ specialize std::iterator_traits for info_iterator_\n\ntemplate <class InfoType, class ProxyType>\nstruct iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>\n{\n typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type\n value_type;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::difference_type\n difference_type;\n typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference\n reference;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category\n iterator_category;\n};\n\ntemplate <class InfoType, class ProxyType>\nstruct iterator_traits<shadow::indexed_info_iterator_<InfoType, ProxyType>>\n{\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::value_type\n value_type;\n\n typedef typename shadow::indexed_info_iterator_<InfoType,\n ProxyType>::difference_type\n difference_type;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::reference\n reference;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::pointer\n pointer;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType,\n ProxyType>::iterator_category\n iterator_category;\n};\n} \/\/ namespace std\n\n#endif\n<commit_msg>Fix missing initialization of field manager_ in indexed_info_iterator_. \tmodified: include\/info_iterator.hpp<commit_after>#ifndef INFO_ITERATOR_HPP\n#define INFO_ITERATOR_HPP\n\n\n#include <cstddef>\n#include <iterator>\n\n\nnamespace shadow\n{\nclass reflection_manager;\n\n\ntemplate <class InfoType, class ProxyType>\nclass indexed_info_iterator_\n{\npublic:\n typedef ProxyType value_type;\n typedef std::ptrdiff_t difference_type;\n typedef ProxyType reference;\n typedef ProxyType pointer;\n typedef std::random_access_iterator_tag iterator_category;\n\npublic:\n indexed_info_iterator_()\n : current_index_(0),\n index_buffer_(nullptr),\n data_buffer_(nullptr),\n manager_(nullptr)\n {\n }\n\n indexed_info_iterator_(std::size_t current_index,\n const std::size_t* index_buffer,\n InfoType* data_buffer,\n const reflection_manager* manager)\n : current_index_(current_index),\n index_buffer_(index_buffer),\n data_buffer_(data_buffer),\n manager_(manager)\n {\n }\n\npublic:\n ProxyType operator*() const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_],\n manager_);\n }\n\n ProxyType operator->() const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_],\n manager_);\n }\n\n ProxyType operator[](difference_type n) const\n {\n return ProxyType(data_buffer_ + index_buffer_[current_index_ + n],\n manager_);\n }\n\n indexed_info_iterator_& operator++()\n {\n ++current_index_;\n return *this;\n }\n\n indexed_info_iterator_ operator++(int)\n {\n auto temp = *this;\n ++(*this);\n return temp;\n }\n\n indexed_info_iterator_& operator--()\n {\n --current_index_;\n return *this;\n }\n\n indexed_info_iterator_ operator--(int)\n {\n auto temp = *this;\n --(*this);\n return temp;\n }\n\n indexed_info_iterator_&\n operator+=(difference_type n)\n {\n current_index_ += n;\n return *this;\n }\n\n indexed_info_iterator_&\n operator-=(difference_type n)\n {\n current_index_ -= n;\n return *this;\n }\n\n indexed_info_iterator_\n operator+(difference_type n) const\n {\n return indexed_info_iterator_(\n current_index_ + n, index_buffer_, data_buffer_, manager_);\n }\n\n indexed_info_iterator_\n operator-(difference_type n) const\n {\n return indexed_info_iterator_(\n current_index_ - n, index_buffer_, data_buffer_, manager_);\n }\n\n difference_type\n operator-(const indexed_info_iterator_& other) const\n {\n return current_index_ - other.current_index_;\n }\n\n friend indexed_info_iterator_\n operator+(difference_type lhs, const indexed_info_iterator_& rhs)\n {\n return rhs + lhs;\n }\n\n bool\n operator==(const indexed_info_iterator_& other) const\n {\n return current_index_ == other.current_index_;\n }\n\n bool\n operator!=(const indexed_info_iterator_& other) const\n {\n return current_index_ != other.current_index_;\n }\n\n bool\n operator<(const indexed_info_iterator_& other) const\n {\n return current_index_ < other.current_index_;\n }\n\n bool\n operator>(const indexed_info_iterator_& other) const\n {\n return current_index_ > other.current_index_;\n }\n\n bool\n operator<=(const indexed_info_iterator_& other) const\n {\n return current_index_ <= other.current_index_;\n }\n\n bool\n operator>=(const indexed_info_iterator_& other) const\n {\n return current_index_ >= other.current_index_;\n }\n\nprivate:\n std::size_t current_index_;\n const std::size_t* index_buffer_;\n InfoType* data_buffer_;\n const reflection_manager* manager_;\n};\n\n\ntemplate <class InfoType, class ProxyType>\nclass info_iterator_\n{\npublic:\n typedef ProxyType value_type;\n typedef typename std::iterator_traits<const InfoType*>::difference_type\n difference_type;\n typedef ProxyType reference;\n typedef ProxyType pointer;\n typedef typename std::iterator_traits<const InfoType*>::iterator_category\n iterator_category;\n\npublic:\n info_iterator_() = default;\n\n\n info_iterator_(const InfoType* current, const reflection_manager* manager)\n : current_(current), manager_(manager)\n {\n }\n\npublic:\n ProxyType operator*() const\n {\n return ProxyType(current_, manager_);\n }\n\n ProxyType operator->() const\n {\n return ProxyType(current_, manager_);\n }\n\n ProxyType operator[](difference_type n) const\n {\n return ProxyType(current_ + n, manager_);\n }\n\n info_iterator_& operator++()\n {\n ++current_;\n return *this;\n }\n\n info_iterator_ operator++(int)\n {\n auto temp = *this;\n ++(*this);\n return temp;\n }\n\n info_iterator_& operator--()\n {\n --current_;\n return *this;\n }\n\n info_iterator_ operator--(int)\n {\n auto temp = *this;\n --(*this);\n return temp;\n }\n\n info_iterator_&\n operator+=(difference_type n)\n {\n current_ += n;\n return *this;\n }\n\n info_iterator_&\n operator-=(difference_type n)\n {\n current_ -= n;\n return *this;\n }\n\n info_iterator_\n operator+(difference_type n) const\n {\n return info_iterator_(current_ + n, manager_);\n }\n\n info_iterator_\n operator-(difference_type n) const\n {\n return info_iterator_(current_ - n, manager_);\n }\n\n difference_type\n operator-(const info_iterator_& other) const\n {\n return current_ - other.current_;\n }\n\n friend info_iterator_\n operator+(difference_type lhs, const info_iterator_& rhs)\n {\n return rhs + lhs;\n }\n\n bool\n operator==(const info_iterator_& other) const\n {\n return current_ == other.current_;\n }\n\n bool\n operator!=(const info_iterator_& other) const\n {\n return current_ != other.current_;\n }\n\n bool\n operator<(const info_iterator_& other) const\n {\n return current_ < other.current_;\n }\n\n bool\n operator>(const info_iterator_& other) const\n {\n return current_ > other.current_;\n }\n\n bool\n operator<=(const info_iterator_& other) const\n {\n return current_ <= other.current_;\n }\n\n bool\n operator>=(const info_iterator_& other) const\n {\n return current_ >= other.current_;\n }\n\nprivate:\n InfoType* current_;\n const reflection_manager* manager_;\n};\n} \/\/ namespace shadow\n\n\nnamespace std\n{\n\/\/ specialize std::iterator_traits for info_iterator_\n\ntemplate <class InfoType, class ProxyType>\nstruct iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>\n{\n typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type\n value_type;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::difference_type\n difference_type;\n typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference\n reference;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;\n typedef\n typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category\n iterator_category;\n};\n\ntemplate <class InfoType, class ProxyType>\nstruct iterator_traits<shadow::indexed_info_iterator_<InfoType, ProxyType>>\n{\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::value_type\n value_type;\n\n typedef typename shadow::indexed_info_iterator_<InfoType,\n ProxyType>::difference_type\n difference_type;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::reference\n reference;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType, ProxyType>::pointer\n pointer;\n\n typedef\n typename shadow::indexed_info_iterator_<InfoType,\n ProxyType>::iterator_category\n iterator_category;\n};\n} \/\/ namespace std\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qversitresourcehandler.h\"\n#include \"qversitproperty.h\"\n#include \"qversitdefaultresourcehandler_p.h\"\n#include \"qversitdefs_p.h\"\n#include <QFile>\n\nQTM_USE_NAMESPACE\n\n\/*!\n * \\class QVersitResourceHandler\n *\n * \\brief The QVersitResourceHandler class is an interface for clients wishing to implement custom\n * behaviour for loading and saving files to disk when exporting and importing, respectively.\n *\n * \\ingroup versit\n *\n * \\sa QVersitContactImporter\n * \\sa QVersitContactExporter\n *\n * \\fn virtual bool QVersitResourceHandler::saveResource(const QByteArray& contents, const QVersitProperty& property, QString* location) = 0;\n * Saves the binary data \\a contents to a file on a persistent storage medium.\n *\n * \\a property holds the QVersitProperty which is the context in which the binary is coming from.\n * The QVersitResourceHandler can use this, for example, to determine file extension it should choose.\n * \\a *filename is filled with the contents of the file.\n * Returns true on success, false on failure.\n *\n *\n * \\fn virtual bool QVersitResourceHandler::loadResource(const QString& location, QByteArray* contents, QString* mimeType) = 0;\n * Loads a file from \\a location.\n *\n * \\a *contents is filled with the contents of the file and \\a *mimeType is set to the MIME\n * type that it is determined to be.\n * Returns true on success, false on failure.\n*\/\n\nQVersitDefaultResourceHandler::QVersitDefaultResourceHandler()\n : d(new QVersitDefaultResourceHandlerPrivate)\n{\n \/\/ File extension mappings\n int fileExtensionCount = sizeof(versitFileExtensionMappings)\/sizeof(VersitMapping);\n for (int i = 0; i < fileExtensionCount; i++) {\n d->mFileExtensionMapping.insert(\n QLatin1String(versitFileExtensionMappings[i].contactString),\n QLatin1String(versitFileExtensionMappings[i].versitString));\n }\n}\n\nQVersitDefaultResourceHandler::~QVersitDefaultResourceHandler()\n{\n delete d;\n}\n\n\/*!\n * Default resource loader.\n * Loads file from given \\a location into \\a contents and returns true if successful.\n * Does not set \\a mimeType.\n *\/\nbool QVersitDefaultResourceHandler::loadResource(const QString& location,\n QByteArray* contents,\n QString* mimeType)\n{\n QString extension = location.split(QLatin1Char('.')).last().toLower();\n *mimeType = d->mFileExtensionMapping.value(extension);\n if (location.isEmpty())\n return false;\n QFile file(location);\n file.open(QIODevice::ReadOnly);\n if (!file.isReadable())\n return false;\n *contents = file.readAll();\n return contents->size() > 0;\n}\n\n\/*!\n * Default resource saver.\n * Does nothing and returns false. By default, resources aren't persisted because we don't know\n * when it is safe to remove them.\n *\/\nbool QVersitDefaultResourceHandler::saveResource(const QByteArray& contents,\n const QVersitProperty& property,\n QString* location)\n{\n Q_UNUSED(contents)\n Q_UNUSED(property)\n Q_UNUSED(location)\n return false;\n}\n<commit_msg>Add back documentation to refer to the after-freeze API change.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qversitresourcehandler.h\"\n#include \"qversitproperty.h\"\n#include \"qversitdefaultresourcehandler_p.h\"\n#include \"qversitdefs_p.h\"\n#include <QFile>\n\nQTM_USE_NAMESPACE\n\n\/*!\n * \\class QVersitResourceHandler\n *\n * \\brief The QVersitResourceHandler class is an interface for clients wishing to implement custom\n * behaviour for loading and saving files to disk when exporting and importing, respectively.\n *\n * \\ingroup versit\n *\n * \\sa QVersitContactImporter\n * \\sa QVersitContactExporter\n *\n * \\fn virtual bool QVersitResourceHandler::saveResource(const QByteArray& contents, const QVersitProperty& property, QString* location) = 0;\n * Saves the binary data \\a contents to a file on a persistent storage medium.\n *\n * \\a property holds the QVersitProperty which is the context in which the binary is coming from.\n * The QVersitResourceHandler can use this, for example, to determine file extension it should choose.\n * \\a *filename is filled with the contents of the file.\n * Returns true on success, false on failure.\n *\n *\n * \\fn virtual bool QVersitResourceHandler::loadResource(const QString& location, QByteArray* contents, QString* mimeType) = 0;\n * Loads a file from \\a location.\n *\n * \\a *contents is filled with the contents of the file and \\a *mimeType is set to the MIME\n * type that it is determined to be.\n * Returns true on success, false on failure.\n*\/\n\nQVersitDefaultResourceHandler::QVersitDefaultResourceHandler()\n : d(new QVersitDefaultResourceHandlerPrivate)\n{\n \/\/ File extension mappings\n int fileExtensionCount = sizeof(versitFileExtensionMappings)\/sizeof(VersitMapping);\n for (int i = 0; i < fileExtensionCount; i++) {\n d->mFileExtensionMapping.insert(\n QLatin1String(versitFileExtensionMappings[i].contactString),\n QLatin1String(versitFileExtensionMappings[i].versitString));\n }\n}\n\nQVersitDefaultResourceHandler::~QVersitDefaultResourceHandler()\n{\n delete d;\n}\n\n\/*!\n * Default resource loader.\n * Loads file from given \\a location into \\a contents and returns true if successful.\n * Sets the \\a mimeType based on the file extension.\n *\/\nbool QVersitDefaultResourceHandler::loadResource(const QString& location,\n QByteArray* contents,\n QString* mimeType)\n{\n QString extension = location.split(QLatin1Char('.')).last().toLower();\n *mimeType = d->mFileExtensionMapping.value(extension);\n if (location.isEmpty())\n return false;\n QFile file(location);\n file.open(QIODevice::ReadOnly);\n if (!file.isReadable())\n return false;\n *contents = file.readAll();\n return contents->size() > 0;\n}\n\n\/*!\n * Default resource saver.\n * Does nothing and returns false. By default, resources aren't persisted because we don't know\n * when it is safe to remove them.\n *\/\nbool QVersitDefaultResourceHandler::saveResource(const QByteArray& contents,\n const QVersitProperty& property,\n QString* location)\n{\n Q_UNUSED(contents)\n Q_UNUSED(property)\n Q_UNUSED(location)\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Claire Xenia Wolf <claire@yosyshq.com>\n * Copyright (C) 2020 Pepijn de Vos <pepijn@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#ifdef MAIN_EXECUTABLE\n\n#include <fstream>\n#include <regex>\n#include \"command.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"timing.h\"\n\nUSING_NEXTPNR_NAMESPACE\n\nclass GowinCommandHandler : public CommandHandler\n{\n public:\n GowinCommandHandler(int argc, char **argv);\n virtual ~GowinCommandHandler(){};\n std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override;\n void setupArchContext(Context *ctx) override{};\n void customAfterLoad(Context *ctx) override;\n\n protected:\n po::options_description getArchOptions() override;\n};\n\nGowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}\n\npo::options_description GowinCommandHandler::getArchOptions()\n{\n po::options_description specific(\"Architecture specific options\");\n specific.add_options()(\"device\", po::value<std::string>(), \"device name\");\n specific.add_options()(\"cst\", po::value<std::string>(), \"physical constraints file\");\n return specific;\n}\n\nstd::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values)\n{\n std::regex devicere = std::regex(\"GW1N([A-Z]*)-(LV|UV|UX)([0-9])(C?)([A-Z]{2}[0-9]+)(C[0-9]\/I[0-9])\");\n std::smatch match;\n std::string device = vm[\"device\"].as<std::string>();\n if (!std::regex_match(device, match, devicere)) {\n log_error(\"Invalid device %s\\n\", device.c_str());\n }\n ArchArgs chipArgs;\n char buf[36];\n snprintf(buf, 36, \"GW1N%s-%s%s\", match[1].str().c_str(), match[3].str().c_str(), match[4].str().c_str());\n chipArgs.device = buf;\n \/\/ GW1N and GW1NR variants share the same database.\n \/\/ Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank.\n \/\/ However, it appears that the S series with embedded ARM core are unique silicon.\n if(match[1].str() == \"S\") {\n snprintf(buf, 36, \"GW1NS-%s\", match[3].str().c_str());\n } else {\n snprintf(buf, 36, \"GW1N-%s\", match[3].str().c_str());\n }\n chipArgs.family = buf;\n chipArgs.package = match[5];\n chipArgs.speed = match[6];\n return std::unique_ptr<Context>(new Context(chipArgs));\n}\n\nvoid GowinCommandHandler::customAfterLoad(Context *ctx)\n{\n if (vm.count(\"cst\")) {\n std::string filename = vm[\"cst\"].as<std::string>();\n std::ifstream in(filename);\n if (!in)\n log_error(\"Failed to open input CST file %s.\\n\", filename.c_str());\n ctx->read_cst(in);\n }\n}\n\nint main(int argc, char *argv[])\n{\n GowinCommandHandler handler(argc, argv);\n return handler.exec();\n}\n#endif\n<commit_msg>clangformat<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Claire Xenia Wolf <claire@yosyshq.com>\n * Copyright (C) 2020 Pepijn de Vos <pepijn@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#ifdef MAIN_EXECUTABLE\n\n#include <fstream>\n#include <regex>\n#include \"command.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"timing.h\"\n\nUSING_NEXTPNR_NAMESPACE\n\nclass GowinCommandHandler : public CommandHandler\n{\n public:\n GowinCommandHandler(int argc, char **argv);\n virtual ~GowinCommandHandler(){};\n std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override;\n void setupArchContext(Context *ctx) override{};\n void customAfterLoad(Context *ctx) override;\n\n protected:\n po::options_description getArchOptions() override;\n};\n\nGowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}\n\npo::options_description GowinCommandHandler::getArchOptions()\n{\n po::options_description specific(\"Architecture specific options\");\n specific.add_options()(\"device\", po::value<std::string>(), \"device name\");\n specific.add_options()(\"cst\", po::value<std::string>(), \"physical constraints file\");\n return specific;\n}\n\nstd::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values)\n{\n std::regex devicere = std::regex(\"GW1N([A-Z]*)-(LV|UV|UX)([0-9])(C?)([A-Z]{2}[0-9]+)(C[0-9]\/I[0-9])\");\n std::smatch match;\n std::string device = vm[\"device\"].as<std::string>();\n if (!std::regex_match(device, match, devicere)) {\n log_error(\"Invalid device %s\\n\", device.c_str());\n }\n ArchArgs chipArgs;\n char buf[36];\n snprintf(buf, 36, \"GW1N%s-%s%s\", match[1].str().c_str(), match[3].str().c_str(), match[4].str().c_str());\n chipArgs.device = buf;\n \/\/ GW1N and GW1NR variants share the same database.\n \/\/ Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank.\n \/\/ However, it appears that the S series with embedded ARM core are unique silicon.\n if (match[1].str() == \"S\") {\n snprintf(buf, 36, \"GW1NS-%s\", match[3].str().c_str());\n } else {\n snprintf(buf, 36, \"GW1N-%s\", match[3].str().c_str());\n }\n chipArgs.family = buf;\n chipArgs.package = match[5];\n chipArgs.speed = match[6];\n return std::unique_ptr<Context>(new Context(chipArgs));\n}\n\nvoid GowinCommandHandler::customAfterLoad(Context *ctx)\n{\n if (vm.count(\"cst\")) {\n std::string filename = vm[\"cst\"].as<std::string>();\n std::ifstream in(filename);\n if (!in)\n log_error(\"Failed to open input CST file %s.\\n\", filename.c_str());\n ctx->read_cst(in);\n }\n}\n\nint main(int argc, char *argv[])\n{\n GowinCommandHandler handler(argc, argv);\n return handler.exec();\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2014, Peter G. Baum\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gpio.h\"\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <string>\n#include <stdexcept>\n#include <map>\n#include <cstring>\n#include <cassert>\n\n#define SYSFS_GPIO_DIR \"\/sys\/class\/gpio\/\"\n\nnamespace\n{\n struct Comp\n {\n bool operator()( const char *a, const char *b ) const\n {\n return strcmp( a, b ) < 0;\n }\n };\n\n const std::map<const char *,int, Comp> nameMap =\n {\n { \"P8.3\", 32 + 6 },\n { \"P8.4\", 32 + 7 },\n { \"P8.5\", 32 + 2 },\n { \"P8.6\", 32 + 3 },\n { \"P8.7\", 64 + 2 },\n { \"P8.8\", 64 + 3 },\n { \"P8.9\", 64 + 5 },\n { \"P8.10\", 64 + 4 },\n { \"P8.11\", 32 + 13 },\n { \"P8.12\", 32 + 12 },\n { \"P8.13\", 0 + 23 },\n { \"P8.14\", 0 + 26 },\n { \"P8.15\", 32 + 15 },\n { \"P8.16\", 32 + 14 },\n { \"P8.17\", 0 + 27 },\n { \"P8.18\", 64 + 1 },\n { \"P8.19\", 0 + 22 },\n { \"P8.20\", 32 + 31 },\n { \"P8.21\", 32 + 30 },\n { \"P8.22\", 32 + 5 },\n { \"P8.23\", 32 + 4 },\n { \"P8.24\", 32 + 1 },\n { \"P8.25\", 32 + 0 },\n { \"P8.26\", 32 + 29 },\n { \"P8.27\", 64 + 22 },\n { \"P8.28\", 64 + 24 },\n { \"P8.29\", 64 + 23 },\n { \"P8.30\", 64 + 25 },\n { \"P8.31\", 0 + 10 },\n { \"P8.32\", 0 + 11 },\n { \"P8.33\", 0 + 9 },\n { \"P8.34\", 64 + 17 },\n { \"P8.35\", 0 + 8 },\n { \"P8.36\", 64 + 16 },\n { \"P8.37\", 64 + 14 },\n { \"P8.38\", 64 + 15 },\n { \"P8.39\", 64 + 12 },\n { \"P8.40\", 64 + 13 },\n { \"P8.41\", 64 + 10 },\n { \"P8.42\", 64 + 11 },\n { \"P8.43\", 64 + 8 },\n { \"P8.44\", 64 + 9 },\n { \"P8.45\", 64 + 6 },\n { \"P8.46\", 64 + 7 },\n { \"P9.11\", 0 + 30 },\n { \"P9.12\", 32 + 28 },\n { \"P9.13\", 0 + 31 },\n { \"P9.14\", 32 + 18 },\n { \"P9.15\", 32 + 16 },\n { \"P9.16\", 32 + 19 },\n { \"P9.17\", 0 + 5 },\n { \"P9.18\", 0 + 4 },\n { \"P9.19\", 0 + 13 },\n { \"P9.20\", 0 + 12 },\n { \"P9.21\", 0 + 3 },\n { \"P9.22\", 0 + 2 },\n { \"P9.23\", 32 + 17 },\n { \"P9.24\", 0 + 15 },\n { \"P9.25\", 96 + 21 },\n { \"P9.26\", 0 + 14 },\n { \"P9.27\", 96 + 19 },\n { \"P9.28\", 96 + 17 },\n { \"P9.29\", 96 + 15 },\n { \"P9.30\", 96 + 16 },\n { \"P9.31\", 96 + 14 },\n \/\/ LEDs\n { \"USR0\", 32 + 21 },\n { \"USR1\", 32 + 22 },\n { \"USR2\", 32 + 23 },\n { \"USR3\", 32 + 24 },\n };\n\n int getNumberFromName( const char *name )\n {\n if( strncmp( name, \"GPIO\", 4 ) == 0 )\n {\n const int bank = atoi( name + 4 );\n const char *p = strchr( name, '_' );\n if( p == nullptr )\n throw std::invalid_argument( \"Invalid GPIO name\" );\n const int num = atoi( p + 1 );\n return bank * 32 + num;\n }\n auto p( nameMap.find( name ) );\n if( p == nameMap.end() )\n throw std::invalid_argument( \"Invalid header name\" );\n return p->second;\n }\n}\n\n\nGPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )\n{\n int fd = open( SYSFS_GPIO_DIR \"export\", O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n\n fd = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio ) + \"\/direction\").c_str(), O_WRONLY );\n if( fd < 0 )\n {\n close();\n throw std::invalid_argument( strerror( errno ) );\n }\n switch( direction )\n {\n case LOW: write( fd, \"low\", 4 ); break;\n case HIGH: write( fd, \"high\", 5 ); break;\n case IN: write( fd, \"in\", 3 ); break;\n case OUT: write( fd, \"out\", 4 ); break;\n default: throw std::invalid_argument( \"GPIO direction\" );\n }\n ::close( fd );\n}\n\nint GPIO::getNum( ) const\n{\n return gpio;\n}\n\nvoid GPIO::close( )\n{\n int fd = open( SYSFS_GPIO_DIR \"unexport\", O_WRONLY );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n}\n\nGPIO::~GPIO( )\n{\n try\n {\n close();\n }\n catch( ... )\n {\n }\n}\n\nGPO::GPO( int gpio_, bool val ) : gpio( gpio_, val ? GPIO::HIGH : GPIO::LOW )\n{\n const std::string path( SYSFS_GPIO_DIR \"gpio\" );\n fd = open( (path + std::to_string( gpio_ ) + \"\/value\").c_str(),\n O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPO::GPO( const char *name, bool val ) : GPO( getNumberFromName( name ), val )\n{\n}\n\nGPO::~GPO( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPO::set( bool val )\n{\n write( fd, val ? \"1\": \"0\", 2 );\n}\n\nvoid GPO::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n\nGPI::GPI( int gpio_ ) : gpio( gpio_, GPIO::IN )\n{\n const std::string path( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio_ ) + \"\/value\");\n fd = open( path.c_str(), O_RDONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPI::GPI( const char *name ) : GPI( getNumberFromName( name ) )\n{\n}\n\nGPI::~GPI( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPI::setEdge( int edge )\n{\n const int ff = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio.getNum() ) + \"\/edge\" ).c_str(), O_WRONLY );\n if( ff < 0 )\n throw std::invalid_argument( strerror( errno ) );\n switch( edge )\n {\n case NONE: write( ff, \"none\", 5 ); break;\n case RISING: write( ff, \"rising\", 7 ); break;\n case FALLING: write( ff, \"falling\", 8 ); break;\n case BOTH: write( ff, \"both\", 5 ); break;\n default: ::close( ff );\n throw std::invalid_argument( \"GPI::setEdge()\" );\n }\n ::close( ff );\n}\n\nbool GPI::wait( )\n{\n struct pollfd fdset[1];\n fdset[0].fd = fd;\n fdset[0].events = POLLPRI;\n\n switch( poll( fdset, 1, -1 ) )\n {\n case 1: assert( fdset[0].revents & POLLPRI );\n return get();\n default:\n throw std::runtime_error( \"poll failed\" );\n }\n}\n\nbool GPI::get( )\n{\n char buf;\n if( lseek( fd, 0, SEEK_SET ) != 0\n || read( fd, &buf, 1 ) != 1 )\n throw std::invalid_argument( strerror( errno ) );\n return buf == '1';\n}\n\nvoid GPI::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n<commit_msg>GPIO: use unnamed tmp variable<commit_after>\/*\nCopyright (c) 2014, Peter G. Baum\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"gpio.h\"\n#include <unistd.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <string>\n#include <stdexcept>\n#include <map>\n#include <cstring>\n#include <cassert>\n\n#define SYSFS_GPIO_DIR \"\/sys\/class\/gpio\/\"\n\nnamespace\n{\n struct Comp\n {\n bool operator()( const char *a, const char *b ) const\n {\n return strcmp( a, b ) < 0;\n }\n };\n\n const std::map<const char *,int, Comp> nameMap =\n {\n { \"P8.3\", 32 + 6 },\n { \"P8.4\", 32 + 7 },\n { \"P8.5\", 32 + 2 },\n { \"P8.6\", 32 + 3 },\n { \"P8.7\", 64 + 2 },\n { \"P8.8\", 64 + 3 },\n { \"P8.9\", 64 + 5 },\n { \"P8.10\", 64 + 4 },\n { \"P8.11\", 32 + 13 },\n { \"P8.12\", 32 + 12 },\n { \"P8.13\", 0 + 23 },\n { \"P8.14\", 0 + 26 },\n { \"P8.15\", 32 + 15 },\n { \"P8.16\", 32 + 14 },\n { \"P8.17\", 0 + 27 },\n { \"P8.18\", 64 + 1 },\n { \"P8.19\", 0 + 22 },\n { \"P8.20\", 32 + 31 },\n { \"P8.21\", 32 + 30 },\n { \"P8.22\", 32 + 5 },\n { \"P8.23\", 32 + 4 },\n { \"P8.24\", 32 + 1 },\n { \"P8.25\", 32 + 0 },\n { \"P8.26\", 32 + 29 },\n { \"P8.27\", 64 + 22 },\n { \"P8.28\", 64 + 24 },\n { \"P8.29\", 64 + 23 },\n { \"P8.30\", 64 + 25 },\n { \"P8.31\", 0 + 10 },\n { \"P8.32\", 0 + 11 },\n { \"P8.33\", 0 + 9 },\n { \"P8.34\", 64 + 17 },\n { \"P8.35\", 0 + 8 },\n { \"P8.36\", 64 + 16 },\n { \"P8.37\", 64 + 14 },\n { \"P8.38\", 64 + 15 },\n { \"P8.39\", 64 + 12 },\n { \"P8.40\", 64 + 13 },\n { \"P8.41\", 64 + 10 },\n { \"P8.42\", 64 + 11 },\n { \"P8.43\", 64 + 8 },\n { \"P8.44\", 64 + 9 },\n { \"P8.45\", 64 + 6 },\n { \"P8.46\", 64 + 7 },\n { \"P9.11\", 0 + 30 },\n { \"P9.12\", 32 + 28 },\n { \"P9.13\", 0 + 31 },\n { \"P9.14\", 32 + 18 },\n { \"P9.15\", 32 + 16 },\n { \"P9.16\", 32 + 19 },\n { \"P9.17\", 0 + 5 },\n { \"P9.18\", 0 + 4 },\n { \"P9.19\", 0 + 13 },\n { \"P9.20\", 0 + 12 },\n { \"P9.21\", 0 + 3 },\n { \"P9.22\", 0 + 2 },\n { \"P9.23\", 32 + 17 },\n { \"P9.24\", 0 + 15 },\n { \"P9.25\", 96 + 21 },\n { \"P9.26\", 0 + 14 },\n { \"P9.27\", 96 + 19 },\n { \"P9.28\", 96 + 17 },\n { \"P9.29\", 96 + 15 },\n { \"P9.30\", 96 + 16 },\n { \"P9.31\", 96 + 14 },\n \/\/ LEDs\n { \"USR0\", 32 + 21 },\n { \"USR1\", 32 + 22 },\n { \"USR2\", 32 + 23 },\n { \"USR3\", 32 + 24 },\n };\n\n int getNumberFromName( const char *name )\n {\n if( strncmp( name, \"GPIO\", 4 ) == 0 )\n {\n const int bank = atoi( name + 4 );\n const char *p = strchr( name, '_' );\n if( p == nullptr )\n throw std::invalid_argument( \"Invalid GPIO name\" );\n const int num = atoi( p + 1 );\n return bank * 32 + num;\n }\n auto p( nameMap.find( name ) );\n if( p == nameMap.end() )\n throw std::invalid_argument( \"Invalid header name\" );\n return p->second;\n }\n}\n\n\nGPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )\n{\n int fd = open( SYSFS_GPIO_DIR \"export\", O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n\n fd = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio ) + \"\/direction\").c_str(), O_WRONLY );\n if( fd < 0 )\n {\n close();\n throw std::invalid_argument( strerror( errno ) );\n }\n switch( direction )\n {\n case LOW: write( fd, \"low\", 4 ); break;\n case HIGH: write( fd, \"high\", 5 ); break;\n case IN: write( fd, \"in\", 3 ); break;\n case OUT: write( fd, \"out\", 4 ); break;\n default: throw std::invalid_argument( \"GPIO direction\" );\n }\n ::close( fd );\n}\n\nint GPIO::getNum( ) const\n{\n return gpio;\n}\n\nvoid GPIO::close( )\n{\n int fd = open( SYSFS_GPIO_DIR \"unexport\", O_WRONLY );\n std::string str = std::to_string( gpio );\n write( fd, str.c_str(), str.size() + 1 );\n ::close( fd );\n}\n\nGPIO::~GPIO( )\n{\n try\n {\n close();\n }\n catch( ... )\n {\n }\n}\n\nGPO::GPO( int gpio_, bool val ) : gpio( gpio_, val ? GPIO::HIGH : GPIO::LOW )\n{\n fd = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio_ ) + \"\/value\" ).c_str(), O_WRONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPO::GPO( const char *name, bool val ) : GPO( getNumberFromName( name ), val )\n{\n}\n\nGPO::~GPO( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPO::set( bool val )\n{\n write( fd, val ? \"1\": \"0\", 2 );\n}\n\nvoid GPO::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n\nGPI::GPI( int gpio_ ) : gpio( gpio_, GPIO::IN )\n{\n fd = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio_ ) + \"\/value\" ).c_str(), O_RDONLY );\n if( fd < 0 )\n throw std::invalid_argument( strerror( errno ) );\n}\n\nGPI::GPI( const char *name ) : GPI( getNumberFromName( name ) )\n{\n}\n\nGPI::~GPI( )\n{\n if( fd > 0 )\n close();\n}\n\nvoid GPI::setEdge( int edge )\n{\n const int ff = open( ( std::string( SYSFS_GPIO_DIR \"gpio\" )\n + std::to_string( gpio.getNum() ) + \"\/edge\" ).c_str(), O_WRONLY );\n if( ff < 0 )\n throw std::invalid_argument( strerror( errno ) );\n switch( edge )\n {\n case NONE: write( ff, \"none\", 5 ); break;\n case RISING: write( ff, \"rising\", 7 ); break;\n case FALLING: write( ff, \"falling\", 8 ); break;\n case BOTH: write( ff, \"both\", 5 ); break;\n default: ::close( ff );\n throw std::invalid_argument( \"GPI::setEdge()\" );\n }\n ::close( ff );\n}\n\nbool GPI::wait( )\n{\n struct pollfd fdset[1];\n fdset[0].fd = fd;\n fdset[0].events = POLLPRI;\n\n switch( poll( fdset, 1, -1 ) )\n {\n case 1: assert( fdset[0].revents & POLLPRI );\n return get();\n default:\n throw std::runtime_error( \"poll failed\" );\n }\n}\n\nbool GPI::get( )\n{\n char buf;\n if( lseek( fd, 0, SEEK_SET ) != 0\n || read( fd, &buf, 1 ) != 1 )\n throw std::invalid_argument( strerror( errno ) );\n return buf == '1';\n}\n\nvoid GPI::close( )\n{\n ::close( fd );\n fd = 0;\n gpio.close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: itemholder1.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2007-07-26 08:44:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#include \"itemholder1.hxx\"\n\n\/\/-----------------------------------------------\n\/\/ includes\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n#include <svtools\/accelcfg.hxx>\n#include <svtools\/addxmltostorageoptions.hxx>\n#include <cacheoptions.hxx>\n#include <svtools\/cmdoptions.hxx>\n#include <svtools\/compatibility.hxx>\n#include <svtools\/defaultoptions.hxx>\n#include <svtools\/dynamicmenuoptions.hxx>\n#include <eventcfg.hxx>\n#include <svtools\/extendedsecurityoptions.hxx>\n#include <fltrcfg.hxx>\n#include <svtools\/fontoptions.hxx>\n#include <svtools\/historyoptions.hxx>\n#include <svtools\/inetoptions.hxx>\n#include <svtools\/internaloptions.hxx>\n#include <javaoptions.hxx>\n#include <svtools\/lingucfg.hxx>\n#include <svtools\/localisationoptions.hxx>\n#include <svtools\/menuoptions.hxx>\n#include <svtools\/moduleoptions.hxx>\n#include <svtools\/options3d.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <svtools\/printwarningoptions.hxx>\n#include <regoptions.hxx>\n#include <svtools\/optionsdlg.hxx>\n#include <svtools\/saveopt.hxx>\n#include <searchopt.hxx>\n#include <svtools\/securityoptions.hxx>\n#include <svtools\/sourceviewconfig.hxx>\n#include <svtools\/startoptions.hxx>\n#include <svtools\/viewoptions.hxx>\n#include <svtools\/workingsetoptions.hxx>\n#include <xmlaccelcfg.hxx>\n#include <svtools\/options.hxx>\n\n\/\/-----------------------------------------------\n\/\/ namespaces\n\nnamespace css = ::com::sun::star;\n\n\/\/-----------------------------------------------\n\/\/ declarations\n\n\/\/-----------------------------------------------\nItemHolder1::ItemHolder1()\n : ItemHolderMutexBase()\n{\n try\n {\n css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();\n css::uno::Reference< css::lang::XComponent > xCfg(\n xSMGR->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\")),\n css::uno::UNO_QUERY);\n if (xCfg.is())\n xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this));\n }\n\/\/ #i37892 got errorhandling from ConfigManager::GetConfigurationProvider()\n#ifdef DBG_UTIL\n catch(css::uno::Exception& rEx)\n {\n static sal_Bool bMessage = sal_True;\n if(bMessage)\n {\n bMessage = sal_False;\n ::rtl::OString sMsg(\"CreateInstance with arguments exception: \");\n sMsg += ::rtl::OString(rEx.Message.getStr(),\n rEx.Message.getLength(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, sMsg.getStr());\n }\n }\n#else\n catch(css::uno::Exception&){}\n#endif\n}\n\n\/\/-----------------------------------------------\nItemHolder1::~ItemHolder1()\n{\n impl_releaseAllItems();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::holdConfigItem(EItem eItem)\n{\n static ItemHolder1* pHolder = new ItemHolder1();\n pHolder->impl_addItem(eItem);\n}\n\n\/\/-----------------------------------------------\nvoid SAL_CALL ItemHolder1::disposing(const css::lang::EventObject&)\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::uno::XInterface > xSelfHold(static_cast< css::lang::XEventListener* >(this), css::uno::UNO_QUERY);\n impl_releaseAllItems();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_addItem(EItem eItem)\n{\n ::osl::ResettableMutexGuard aLock(m_aLock);\n\n TItems::const_iterator pIt;\n for ( pIt = m_lItems.begin();\n pIt != m_lItems.end() ;\n ++pIt )\n {\n const TItemInfo& rInfo = *pIt;\n if (rInfo.eItem == eItem)\n return;\n }\n\n TItemInfo aNewItem;\n aNewItem.eItem = eItem;\n impl_newItem(aNewItem);\n if (aNewItem.pItem)\n m_lItems.push_back(aNewItem);\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_releaseAllItems()\n{\n ::osl::ResettableMutexGuard aLock(m_aLock);\n\n TItems::iterator pIt;\n for ( pIt = m_lItems.begin();\n pIt != m_lItems.end() ;\n ++pIt )\n {\n TItemInfo& rInfo = *pIt;\n impl_deleteItem(rInfo);\n }\n m_lItems.clear();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_newItem(TItemInfo& rItem)\n{\n switch(rItem.eItem)\n {\n case E_ACCELCFG :\n rItem.pItem = new SvtAcceleratorConfiguration();\n break;\n\n case E_ADDXMLTOSTORAGEOPTIONS :\n rItem.pItem = new SvtAddXMLToStorageOptions();\n break;\n\n case E_CMDOPTIONS :\n rItem.pItem = new SvtCommandOptions();\n break;\n\n case E_COMPATIBILITY :\n rItem.pItem = new SvtCompatibilityOptions();\n break;\n\n case E_DEFAULTOPTIONS :\n rItem.pItem = new SvtDefaultOptions();\n break;\n\n case E_DYNAMICMENUOPTIONS :\n rItem.pItem = new SvtDynamicMenuOptions();\n break;\n\n case E_EVENTCFG :\n \/\/rItem.pItem = new GlobalEventConfig();\n break;\n\n case E_EXTENDEDSECURITYOPTIONS :\n rItem.pItem = new SvtExtendedSecurityOptions();\n break;\n\n case E_FLTRCFG :\n\/\/ no ref count rItem.pItem = new SvtFilterOptions();\n break;\n\n case E_FONTOPTIONS :\n rItem.pItem = new SvtFontOptions();\n break;\n\n case E_HISTORYOPTIONS :\n rItem.pItem = new SvtHistoryOptions();\n break;\n\n case E_INETOPTIONS :\n rItem.pItem = new SvtInetOptions();\n break;\n\n case E_INTERNALOPTIONS :\n rItem.pItem = new SvtInternalOptions();\n break;\n\n case E_JAVAOPTIONS :\n\/\/ no ref count rItem.pItem = new SvtJavaOptions();\n break;\n\n case E_LINGUCFG :\n rItem.pItem = new SvtLinguConfig();\n break;\n\n case E_LOCALISATIONOPTIONS :\n rItem.pItem = new SvtLocalisationOptions();\n break;\n\n case E_MENUOPTIONS :\n rItem.pItem = new SvtMenuOptions();\n break;\n\n case E_MODULEOPTIONS :\n rItem.pItem = new SvtModuleOptions();\n break;\n\n case E_OPTIONSDLGOPTIONS :\n rItem.pItem = new SvtOptionsDialogOptions();\n break;\n\n case E_OPTIONS3D :\n rItem.pItem = new SvtOptions3D();\n break;\n\n case E_PATHOPTIONS :\n rItem.pItem = new SvtPathOptions();\n break;\n\n case E_PRINTWARNINGOPTIONS :\n rItem.pItem = new SvtPrintWarningOptions();\n break;\n\n case E_REGOPTIONS :\n\/\/ no ref count rItem.pItem = new ::svt::RegOptions();\n break;\n\n case E_SAVEOPTIONS :\n rItem.pItem = new SvtSaveOptions();\n break;\n\n case E_SEARCHOPT :\n\/\/ no ref count rItem.pItem = new SvtSearchOptions();\n break;\n\n case E_SECURITYOPTIONS :\n rItem.pItem = new SvtSecurityOptions();\n break;\n\n case E_SOURCEVIEWCONFIG :\n rItem.pItem = new ::svt::SourceViewConfig();\n break;\n\n case E_STARTOPTIONS :\n rItem.pItem = new SvtStartOptions();\n break;\n\n case E_VIEWOPTIONS_DIALOG :\n rItem.pItem = new SvtViewOptions(E_DIALOG, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_TABDIALOG :\n rItem.pItem = new SvtViewOptions(E_TABDIALOG, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_TABPAGE :\n rItem.pItem = new SvtViewOptions(E_TABPAGE, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_WINDOW :\n rItem.pItem = new SvtViewOptions(E_WINDOW, ::rtl::OUString());\n break;\n\n case E_WORKINGSETOPTIONS :\n rItem.pItem = new SvtWorkingSetOptions();\n break;\n\n case E_XMLACCELCFG :\n \/\/ ??? TODO\n break;\n default:\n OSL_ASSERT( \"unknown item type\" );\n break;\n }\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_deleteItem(TItemInfo& rItem)\n{\n if (rItem.pItem)\n {\n delete rItem.pItem;\n rItem.pItem = 0;\n }\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.12.210); FILE MERGED 2008\/04\/01 15:44:47 thb 1.12.210.3: #i85898# Stripping all external header guards 2008\/04\/01 12:43:24 thb 1.12.210.2: #i85898# Stripping all external header guards 2008\/03\/31 13:01:25 rt 1.12.210.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: itemholder1.cxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#include \"itemholder1.hxx\"\n\n\/\/-----------------------------------------------\n\/\/ includes\n#include <comphelper\/processfactory.hxx>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n\n#include <svtools\/accelcfg.hxx>\n#include <svtools\/addxmltostorageoptions.hxx>\n#include <cacheoptions.hxx>\n#include <svtools\/cmdoptions.hxx>\n#include <svtools\/compatibility.hxx>\n#include <svtools\/defaultoptions.hxx>\n#include <svtools\/dynamicmenuoptions.hxx>\n#include <eventcfg.hxx>\n#include <svtools\/extendedsecurityoptions.hxx>\n#include <fltrcfg.hxx>\n#include <svtools\/fontoptions.hxx>\n#include <svtools\/historyoptions.hxx>\n#include <svtools\/inetoptions.hxx>\n#include <svtools\/internaloptions.hxx>\n#include <javaoptions.hxx>\n#include <svtools\/lingucfg.hxx>\n#include <svtools\/localisationoptions.hxx>\n#include <svtools\/menuoptions.hxx>\n#include <svtools\/moduleoptions.hxx>\n#include <svtools\/options3d.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <svtools\/printwarningoptions.hxx>\n#include <regoptions.hxx>\n#include <svtools\/optionsdlg.hxx>\n#include <svtools\/saveopt.hxx>\n#include <searchopt.hxx>\n#include <svtools\/securityoptions.hxx>\n#include <svtools\/sourceviewconfig.hxx>\n#include <svtools\/startoptions.hxx>\n#include <svtools\/viewoptions.hxx>\n#include <svtools\/workingsetoptions.hxx>\n#include <xmlaccelcfg.hxx>\n#include <svtools\/options.hxx>\n\n\/\/-----------------------------------------------\n\/\/ namespaces\n\nnamespace css = ::com::sun::star;\n\n\/\/-----------------------------------------------\n\/\/ declarations\n\n\/\/-----------------------------------------------\nItemHolder1::ItemHolder1()\n : ItemHolderMutexBase()\n{\n try\n {\n css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();\n css::uno::Reference< css::lang::XComponent > xCfg(\n xSMGR->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\")),\n css::uno::UNO_QUERY);\n if (xCfg.is())\n xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this));\n }\n\/\/ #i37892 got errorhandling from ConfigManager::GetConfigurationProvider()\n#ifdef DBG_UTIL\n catch(css::uno::Exception& rEx)\n {\n static sal_Bool bMessage = sal_True;\n if(bMessage)\n {\n bMessage = sal_False;\n ::rtl::OString sMsg(\"CreateInstance with arguments exception: \");\n sMsg += ::rtl::OString(rEx.Message.getStr(),\n rEx.Message.getLength(),\n RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, sMsg.getStr());\n }\n }\n#else\n catch(css::uno::Exception&){}\n#endif\n}\n\n\/\/-----------------------------------------------\nItemHolder1::~ItemHolder1()\n{\n impl_releaseAllItems();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::holdConfigItem(EItem eItem)\n{\n static ItemHolder1* pHolder = new ItemHolder1();\n pHolder->impl_addItem(eItem);\n}\n\n\/\/-----------------------------------------------\nvoid SAL_CALL ItemHolder1::disposing(const css::lang::EventObject&)\n throw(css::uno::RuntimeException)\n{\n css::uno::Reference< css::uno::XInterface > xSelfHold(static_cast< css::lang::XEventListener* >(this), css::uno::UNO_QUERY);\n impl_releaseAllItems();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_addItem(EItem eItem)\n{\n ::osl::ResettableMutexGuard aLock(m_aLock);\n\n TItems::const_iterator pIt;\n for ( pIt = m_lItems.begin();\n pIt != m_lItems.end() ;\n ++pIt )\n {\n const TItemInfo& rInfo = *pIt;\n if (rInfo.eItem == eItem)\n return;\n }\n\n TItemInfo aNewItem;\n aNewItem.eItem = eItem;\n impl_newItem(aNewItem);\n if (aNewItem.pItem)\n m_lItems.push_back(aNewItem);\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_releaseAllItems()\n{\n ::osl::ResettableMutexGuard aLock(m_aLock);\n\n TItems::iterator pIt;\n for ( pIt = m_lItems.begin();\n pIt != m_lItems.end() ;\n ++pIt )\n {\n TItemInfo& rInfo = *pIt;\n impl_deleteItem(rInfo);\n }\n m_lItems.clear();\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_newItem(TItemInfo& rItem)\n{\n switch(rItem.eItem)\n {\n case E_ACCELCFG :\n rItem.pItem = new SvtAcceleratorConfiguration();\n break;\n\n case E_ADDXMLTOSTORAGEOPTIONS :\n rItem.pItem = new SvtAddXMLToStorageOptions();\n break;\n\n case E_CMDOPTIONS :\n rItem.pItem = new SvtCommandOptions();\n break;\n\n case E_COMPATIBILITY :\n rItem.pItem = new SvtCompatibilityOptions();\n break;\n\n case E_DEFAULTOPTIONS :\n rItem.pItem = new SvtDefaultOptions();\n break;\n\n case E_DYNAMICMENUOPTIONS :\n rItem.pItem = new SvtDynamicMenuOptions();\n break;\n\n case E_EVENTCFG :\n \/\/rItem.pItem = new GlobalEventConfig();\n break;\n\n case E_EXTENDEDSECURITYOPTIONS :\n rItem.pItem = new SvtExtendedSecurityOptions();\n break;\n\n case E_FLTRCFG :\n\/\/ no ref count rItem.pItem = new SvtFilterOptions();\n break;\n\n case E_FONTOPTIONS :\n rItem.pItem = new SvtFontOptions();\n break;\n\n case E_HISTORYOPTIONS :\n rItem.pItem = new SvtHistoryOptions();\n break;\n\n case E_INETOPTIONS :\n rItem.pItem = new SvtInetOptions();\n break;\n\n case E_INTERNALOPTIONS :\n rItem.pItem = new SvtInternalOptions();\n break;\n\n case E_JAVAOPTIONS :\n\/\/ no ref count rItem.pItem = new SvtJavaOptions();\n break;\n\n case E_LINGUCFG :\n rItem.pItem = new SvtLinguConfig();\n break;\n\n case E_LOCALISATIONOPTIONS :\n rItem.pItem = new SvtLocalisationOptions();\n break;\n\n case E_MENUOPTIONS :\n rItem.pItem = new SvtMenuOptions();\n break;\n\n case E_MODULEOPTIONS :\n rItem.pItem = new SvtModuleOptions();\n break;\n\n case E_OPTIONSDLGOPTIONS :\n rItem.pItem = new SvtOptionsDialogOptions();\n break;\n\n case E_OPTIONS3D :\n rItem.pItem = new SvtOptions3D();\n break;\n\n case E_PATHOPTIONS :\n rItem.pItem = new SvtPathOptions();\n break;\n\n case E_PRINTWARNINGOPTIONS :\n rItem.pItem = new SvtPrintWarningOptions();\n break;\n\n case E_REGOPTIONS :\n\/\/ no ref count rItem.pItem = new ::svt::RegOptions();\n break;\n\n case E_SAVEOPTIONS :\n rItem.pItem = new SvtSaveOptions();\n break;\n\n case E_SEARCHOPT :\n\/\/ no ref count rItem.pItem = new SvtSearchOptions();\n break;\n\n case E_SECURITYOPTIONS :\n rItem.pItem = new SvtSecurityOptions();\n break;\n\n case E_SOURCEVIEWCONFIG :\n rItem.pItem = new ::svt::SourceViewConfig();\n break;\n\n case E_STARTOPTIONS :\n rItem.pItem = new SvtStartOptions();\n break;\n\n case E_VIEWOPTIONS_DIALOG :\n rItem.pItem = new SvtViewOptions(E_DIALOG, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_TABDIALOG :\n rItem.pItem = new SvtViewOptions(E_TABDIALOG, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_TABPAGE :\n rItem.pItem = new SvtViewOptions(E_TABPAGE, ::rtl::OUString());\n break;\n\n case E_VIEWOPTIONS_WINDOW :\n rItem.pItem = new SvtViewOptions(E_WINDOW, ::rtl::OUString());\n break;\n\n case E_WORKINGSETOPTIONS :\n rItem.pItem = new SvtWorkingSetOptions();\n break;\n\n case E_XMLACCELCFG :\n \/\/ ??? TODO\n break;\n default:\n OSL_ASSERT( \"unknown item type\" );\n break;\n }\n}\n\n\/\/-----------------------------------------------\nvoid ItemHolder1::impl_deleteItem(TItemInfo& rItem)\n{\n if (rItem.pItem)\n {\n delete rItem.pItem;\n rItem.pItem = 0;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ grindtrick import pstream\n\/\/ grindtrick import boost_locale\n\/\/ grindtrick import boost_filesystem\n\/\/ grindtrick import boost_system\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <vector>\n#include <regex>\n#include <set>\n#include <boost\/range\/algorithm\/count_if.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/algorithm\/string\/erase.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/locale\/encoding.hpp>\n#include <boost\/filesystem.hpp>\n\n#include <pstream.h>\n\nusing namespace boost::property_tree;\nusing namespace boost::locale::conv;\nusing namespace boost::algorithm;\nusing namespace boost::range;\nusing namespace boost::filesystem;\nusing namespace std;\n\n#include \"base64.cpp\"\n\nwstring g_sphere_tag;\n\nwstring const SUBJECT_FIELD_NAME(L\"Sujet\");\nwstring const TAG_FIELD_NAME(L\"\\u00C9tiquettes\");\n\nclass check_error\n{\npublic:\n check_error(wstring const & msg) : msg_(msg) {}\n\n wstring msg_;\n\n wstring user_message() const\n {\n return msg_;\n }\n};\n\nwstring to_markdown(wstring const & content)\n{\n \/\/wofstream ifs(\"to_markdown_input\");\n \/\/ifs << content;\n\n using namespace redi;\n\n vector<string> args;\n args.push_back(\"node\");\n args.push_back(\"to_markdown.js\");\n\n pstream in(\"node\", args, pstreambuf::pstdin | pstreambuf::pstdout);\n\n string utf8 = utf_to_utf<char, wchar_t>(content.c_str());\n\n in << utf8;\n\n peof(in); \/\/ close stdin so client knows to finish\n\n \/\/ofstream of(\"to_markdown_result\");\n\n string line;\n string markdown;\n while( getline(in, line) )\n {\n markdown = markdown + line + \"\\n\";\n \/\/of << line << '\\n';\n } \n\n auto r = utf_to_utf<wchar_t, char>(markdown.c_str());\n\n replace_all(r, L\" \", L\" \");\n\n return r;\n}\n\nclass Attachment\n{\npublic:\n wstring data_;\n wstring encoding_;\n wstring filename_;\n};\n\nclass Note\n{\npublic:\n wstring title_;\n wstring content_;\n set<wstring> tags_;\n wstring project_;\n vector<Attachment> attachments_;\n};\n\nAttachment resource(wptree const & pt)\n{\n Attachment a;\n\n auto data_node = pt.get_child(L\"data\");\n\n a.data_ = data_node.get_value<wstring>();\n\n for(auto v: data_node)\n {\n if( v.first == L\"<xmlattr>\" )\n {\n for(auto v: v.second)\n {\n if( v.first == L\"encoding\" )\n {\n a.encoding_ = v.second.get_value<wstring>();\n }\n }\n }\n }\n\n auto opt_res_attr = pt.get_child_optional(L\"resource-attributes\");\n if( opt_res_attr )\n {\n auto res_attr = *opt_res_attr;\n auto opt_fn = res_attr.get_optional<wstring>(L\"file-name\");\n if( opt_fn ) a.filename_ = *opt_fn;\n }\n\n return a;\n}\n\nbool is_valid_fn_char(wchar_t c)\n{\n if( c < 32 ) return false;\n wstring invalids = L\"<>:\\\"\/\\\\|?*.\";\n if( count(invalids.begin(), invalids.end(), c) != 0 ) return false;\n return true;\n}\n\nvoid check_for_valid_tag(wstring const & t)\n{\n if( t.empty() ) throw check_error(L\"tag cannot be empty string\");\n if( count( t.begin(), t.end(), L'#' ) != 0 ) throw check_error(L\"Evernote tag cannot contain hash\");\n if( count_if( t, iswspace ) ) throw check_error(L\"tag must be a single word\");\n if( ! all_of(t.begin(), t.end(), is_valid_fn_char) ) throw check_error(L\"tag contains invalid characters\");\n}\n\nvoid repair_title(wstring & t)\n{\n wstring r;\n copy_if(t.begin(), t.end(), back_inserter(r), is_valid_fn_char);\n t = r;\n trim(t);\n}\n\nvoid check_for_valid_title(wstring const & t)\n{\n if( ! all_of(t.begin(), t.end(), is_valid_fn_char) ) throw check_error(L\"title contains invalid characters\");\n}\n\nvoid write_attachment(boost::filesystem::wpath const & annex_path, Attachment const & a, int & counter)\n{\n auto afn = a.filename_;\n\n if( afn.empty() )\n {\n wostringstream afn_os;\n afn_os << setw(5) << setfill(L'0') << counter;\n ++ counter;\n afn = afn_os.str();\n }\n\n boost::filesystem::wpath path = annex_path \/ afn;\n\n if( a.encoding_ != L\"base64\" )\n {\n throw check_error(L\"unsupported attachment encoding: \" + a.encoding_);\n }\n\n string data;\n data.resize(a.data_.size());\n\n \/*\n Note: copy wchar_t down to char. This is OK\n because the string is base64 encoded data, so\n no character is beyond 127.\n *\/\n copy(a.data_.begin(), a.data_.end(), data.begin());\n \n erase_all(data, \"\\n\");\n erase_all(data, \"\\r\");\n\n auto dec = b64decode(data);\n auto fn = path.string<string>();\n std::ofstream os(fn, ios::binary);\n os.exceptions(~ios::goodbit);\n os << dec;\n}\n\nvoid write_note(Note const & n)\n{\n wstring wfn = g_sphere_tag + L\" \" + n.project_ + L\" \" + n.title_ + L\".md\";\n string fn = from_utf(wfn, \"UTF-8\") ;\n\n std::wofstream os(fn);\n\n os << SUBJECT_FIELD_NAME << \": \" << n.title_ << '\\n';\n\n os << TAG_FIELD_NAME << \": \";\n\n for(auto t: n.tags_)\n {\n os << L'#' << t << L' ';\n }\n os << '\\n';\n\n os << '\\n';\n\n os << n.content_;\n\n if( !n.attachments_.empty() )\n {\n boost::filesystem::wpath note_fn(wfn);\n boost::filesystem::wpath annex_fn = note_fn.stem().wstring() + L\".annexes\";\n create_directory(annex_fn);\n int counter = 1;\n for(auto a: n.attachments_)\n {\n write_attachment(annex_fn, a, counter);\n }\n }\n}\n\nvoid note(wptree const & pt)\n{\n Note n;\n\n for(auto v: pt)\n {\n if( v.first == L\"title\" )\n {\n n.title_ = v.second.get_value<wstring>();\n trim(n.title_);\n repair_title(n.title_);\n check_for_valid_title(n.title_);\n }\n else if( v.first == L\"content\")\n {\n wstring en_note = v.second.get_value<wstring>();\n \/\/ en_note is a full XML document.\n \/\/ The HTML of the note is inside the <en-note> tag.\n\n wptree en_note_ptree;\n wistringstream is(en_note);\n read_xml(is, en_note_ptree);\n\n auto enote = en_note_ptree.get_child(L\"en-note\");\n\n wostringstream os;\n write_xml(os, enote);\n \n n.content_ = to_markdown( os.str() );\n\n \/\/ TODO: sometimes, there is a surrounding <pre>\n \/\/ tag. Useless. Please remove.\n }\n else if( v.first == L\"tag\")\n {\n auto tag = v.second.get_value<wstring>();\n trim(tag);\n check_for_valid_tag(tag);\n n.tags_.insert(tag);\n }\n else if( v.first == L\"resource\")\n {\n n.attachments_.push_back( resource(v.second) );\n }\n }\n\n n.tags_.insert(g_sphere_tag);\n\n n.project_ = L\"imported\";\n for(auto v: n.tags_)\n {\n if( v != g_sphere_tag )\n {\n n.project_ = v;\n break;\n }\n }\n\n n.tags_.insert(L\"imported\");\n\n write_note(n);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/ Load the system locale.\n setlocale(LC_ALL, \"\");\n\n\n try\n {\n g_sphere_tag = L\"inro\";\n\n if( argc >= 2 ) \n {\n g_sphere_tag = to_utf<wchar_t>(argv[1], \"UTF-8\");\n }\n\n regex wc(\"[0-9]*\\\\.xml\");\n smatch mo;\n\n for(auto e: directory_iterator(\".\"))\n {\n if( !is_regular_file(e) ) continue;\n\n string fn = e.path().filename().string();\n\n if( !regex_match(fn, mo, wc) ) continue;\n\n std::wifstream note_file(e.path().string());\n note_file.exceptions(~ios::goodbit);\n\n wptree pt;\n read_xml(note_file, pt);\n\n cout << fn << '\\n';\n\n try\n {\n note(pt);\n remove(e.path());\n }\n catch(exception const & ex)\n {\n cerr << \"exception: \" << ex.what() << '\\n';\n }\n catch(check_error const & ex)\n {\n wcerr << fn << \": \" << ex.user_message() << '\\n';\n }\n }\n } \n catch(exception const & ex)\n {\n cerr << \"exception: \" << ex.what() << '\\n';\n return 1;\n }\n catch(check_error const & ex)\n {\n wcerr << ex.user_message() << '\\n';\n return 1;\n }\n \n return 0;\n}\n<commit_msg>Remove <pre> tags.<commit_after>\n\/\/ grindtrick import pstream\n\/\/ grindtrick import boost_locale\n\/\/ grindtrick import boost_filesystem\n\/\/ grindtrick import boost_system\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <fstream>\n#include <vector>\n#include <regex>\n#include <set>\n#include <boost\/range\/algorithm\/count_if.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/algorithm\/string\/erase.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/locale\/encoding.hpp>\n#include <boost\/filesystem.hpp>\n\n#include <pstream.h>\n\nusing namespace boost::property_tree;\nusing namespace boost::locale::conv;\nusing namespace boost::algorithm;\nusing namespace boost::range;\nusing namespace boost::filesystem;\nusing namespace std;\n\n#include \"base64.cpp\"\n\nwstring g_sphere_tag;\n\nwstring const SUBJECT_FIELD_NAME(L\"Sujet\");\nwstring const TAG_FIELD_NAME(L\"\\u00C9tiquettes\");\n\nclass check_error\n{\npublic:\n check_error(wstring const & msg) : msg_(msg) {}\n\n wstring msg_;\n\n wstring user_message() const\n {\n return msg_;\n }\n};\n\nwstring to_markdown(wstring const & content)\n{\n \/\/wofstream ifs(\"to_markdown_input\");\n \/\/ifs << content;\n\n using namespace redi;\n\n vector<string> args;\n args.push_back(\"node\");\n args.push_back(\"to_markdown.js\");\n\n pstream in(\"node\", args, pstreambuf::pstdin | pstreambuf::pstdout);\n\n string utf8 = utf_to_utf<char, wchar_t>(content.c_str());\n\n in << utf8;\n\n peof(in); \/\/ close stdin so client knows to finish\n\n \/\/ofstream of(\"to_markdown_result\");\n\n string line;\n string markdown;\n while( getline(in, line) )\n {\n markdown = markdown + line + \"\\n\";\n \/\/of << line << '\\n';\n } \n\n auto r = utf_to_utf<wchar_t, char>(markdown.c_str());\n\n replace_all(r, L\" \", L\" \");\n\n return r;\n}\n\nclass Attachment\n{\npublic:\n wstring data_;\n wstring encoding_;\n wstring filename_;\n};\n\nclass Note\n{\npublic:\n wstring title_;\n wstring content_;\n set<wstring> tags_;\n wstring project_;\n vector<Attachment> attachments_;\n};\n\nAttachment resource(wptree const & pt)\n{\n Attachment a;\n\n auto data_node = pt.get_child(L\"data\");\n\n a.data_ = data_node.get_value<wstring>();\n\n for(auto v: data_node)\n {\n if( v.first == L\"<xmlattr>\" )\n {\n for(auto v: v.second)\n {\n if( v.first == L\"encoding\" )\n {\n a.encoding_ = v.second.get_value<wstring>();\n }\n }\n }\n }\n\n auto opt_res_attr = pt.get_child_optional(L\"resource-attributes\");\n if( opt_res_attr )\n {\n auto res_attr = *opt_res_attr;\n auto opt_fn = res_attr.get_optional<wstring>(L\"file-name\");\n if( opt_fn ) a.filename_ = *opt_fn;\n }\n\n return a;\n}\n\nbool is_valid_fn_char(wchar_t c)\n{\n if( c < 32 ) return false;\n wstring invalids = L\"<>:\\\"\/\\\\|?*.\";\n if( count(invalids.begin(), invalids.end(), c) != 0 ) return false;\n return true;\n}\n\nvoid check_for_valid_tag(wstring const & t)\n{\n if( t.empty() ) throw check_error(L\"tag cannot be empty string\");\n if( count( t.begin(), t.end(), L'#' ) != 0 ) throw check_error(L\"Evernote tag cannot contain hash\");\n if( count_if( t, iswspace ) ) throw check_error(L\"tag must be a single word\");\n if( ! all_of(t.begin(), t.end(), is_valid_fn_char) ) throw check_error(L\"tag contains invalid characters\");\n}\n\nvoid repair_title(wstring & t)\n{\n wstring r;\n copy_if(t.begin(), t.end(), back_inserter(r), is_valid_fn_char);\n t = r;\n trim(t);\n}\n\nvoid check_for_valid_title(wstring const & t)\n{\n if( ! all_of(t.begin(), t.end(), is_valid_fn_char) ) throw check_error(L\"title contains invalid characters\");\n}\n\nvoid write_attachment(boost::filesystem::wpath const & annex_path, Attachment const & a, int & counter)\n{\n auto afn = a.filename_;\n\n if( afn.empty() )\n {\n wostringstream afn_os;\n afn_os << setw(5) << setfill(L'0') << counter;\n ++ counter;\n afn = afn_os.str();\n }\n\n boost::filesystem::wpath path = annex_path \/ afn;\n\n if( a.encoding_ != L\"base64\" )\n {\n throw check_error(L\"unsupported attachment encoding: \" + a.encoding_);\n }\n\n string data;\n data.resize(a.data_.size());\n\n \/*\n Note: copy wchar_t down to char. This is OK\n because the string is base64 encoded data, so\n no character is beyond 127.\n *\/\n copy(a.data_.begin(), a.data_.end(), data.begin());\n \n erase_all(data, \"\\n\");\n erase_all(data, \"\\r\");\n\n auto dec = b64decode(data);\n auto fn = path.string<string>();\n std::ofstream os(fn, ios::binary);\n os.exceptions(~ios::goodbit);\n os << dec;\n}\n\nvoid write_note(Note const & n)\n{\n wstring wfn = g_sphere_tag + L\" \" + n.project_ + L\" \" + n.title_ + L\".md\";\n string fn = from_utf(wfn, \"UTF-8\") ;\n\n std::wofstream os(fn);\n\n os << SUBJECT_FIELD_NAME << \": \" << n.title_ << '\\n';\n\n os << TAG_FIELD_NAME << \": \";\n\n for(auto t: n.tags_)\n {\n os << L'#' << t << L' ';\n }\n os << '\\n';\n\n os << '\\n';\n\n os << n.content_;\n\n if( !n.attachments_.empty() )\n {\n boost::filesystem::wpath note_fn(wfn);\n boost::filesystem::wpath annex_fn = note_fn.stem().wstring() + L\".annexes\";\n create_directory(annex_fn);\n int counter = 1;\n for(auto a: n.attachments_)\n {\n write_attachment(annex_fn, a, counter);\n }\n }\n}\n\nvoid note(wptree const & pt)\n{\n Note n;\n\n for(auto v: pt)\n {\n if( v.first == L\"title\" )\n {\n n.title_ = v.second.get_value<wstring>();\n trim(n.title_);\n repair_title(n.title_);\n check_for_valid_title(n.title_);\n }\n else if( v.first == L\"content\")\n {\n wstring en_note = v.second.get_value<wstring>();\n \/\/ en_note is a full XML document.\n \/\/ The HTML of the note is inside the <en-note> tag.\n\n wptree en_note_ptree;\n wistringstream is(en_note);\n read_xml(is, en_note_ptree);\n\n auto enote = en_note_ptree.get_child(L\"en-note\");\n\n auto pre_opt = enote.get_child_optional(L\"pre\");\n if( pre_opt )\n {\n n.content_ = (*pre_opt).get_value<wstring>();\n }\n else\n {\n wostringstream os;\n write_xml(os, enote);\n \n n.content_ = to_markdown( os.str() );\n }\n }\n else if( v.first == L\"tag\")\n {\n auto tag = v.second.get_value<wstring>();\n trim(tag);\n check_for_valid_tag(tag);\n n.tags_.insert(tag);\n }\n else if( v.first == L\"resource\")\n {\n n.attachments_.push_back( resource(v.second) );\n }\n }\n\n n.tags_.insert(g_sphere_tag);\n\n n.project_ = L\"imported\";\n for(auto v: n.tags_)\n {\n if( v != g_sphere_tag )\n {\n n.project_ = v;\n break;\n }\n }\n\n n.tags_.insert(L\"imported\");\n\n write_note(n);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/ Load the system locale.\n setlocale(LC_ALL, \"\");\n\n\n try\n {\n g_sphere_tag = L\"inro\";\n\n if( argc >= 2 ) \n {\n g_sphere_tag = to_utf<wchar_t>(argv[1], \"UTF-8\");\n }\n\n regex wc(\"[0-9]*\\\\.xml\");\n smatch mo;\n\n for(auto e: directory_iterator(\".\"))\n {\n if( !is_regular_file(e) ) continue;\n\n string fn = e.path().filename().string();\n\n if( !regex_match(fn, mo, wc) ) continue;\n\n std::wifstream note_file(e.path().string());\n note_file.exceptions(~ios::goodbit);\n\n wptree pt;\n read_xml(note_file, pt);\n\n cout << fn << '\\n';\n\n try\n {\n note(pt);\n remove(e.path());\n }\n catch(exception const & ex)\n {\n cerr << \"exception: \" << ex.what() << '\\n';\n }\n catch(check_error const & ex)\n {\n wcerr << fn << \": \" << ex.user_message() << '\\n';\n }\n }\n } \n catch(exception const & ex)\n {\n cerr << \"exception: \" << ex.what() << '\\n';\n return 1;\n }\n catch(check_error const & ex)\n {\n wcerr << ex.user_message() << '\\n';\n return 1;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file main.cpp\n *\/\n\n#include <DBHandler\/HeaderFiles\/DBHandler.h>\n#include <JPetManager\/JPetManager.h>\n#include <JPetTaskLoader\/JPetTaskLoader.h>\n#include \"TaskA.h\"\n#include \"TimeCalibLoader.h\"\n#include \"SignalFinder.h\"\n#include \"HitFinder.h\"\n#include \"TaskC2.h\"\n#include \"TaskD.h\"\n#include \"TaskE.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n DB::SERVICES::DBHandler::createDBConnection(\"..\/DBConfig\/configDB.cfg\");\n JPetManager& manager = JPetManager::getManager();\n manager.parseCmdLine(argc, argv);\n\n \/\/ Here create all analysis modules to be used:\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"hld\",\n \"tslot.raw\",\n new TaskA(\"TaskA: Unp to Timewindow\",\n \"Process unpacked HLD file into a tree of JPetTimeWindow objects\")\n );\n });\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"tslot.raw\", \"tslot_calib.raw\",\n new TimeCalibLoader(\"Apply time corrections from prepared calibrations\",\n \"Apply time corrections from prepared calibrations\"));\n });\n manager.registerTask([]() {\n return new JPetTaskLoader(\"tslot_calib.raw\",\n \"raw.sig\",\n new SignalFinder(\"SignalFinder: Create Raw Sigs\",\n \"Create Raw Signals, optional draw TOTs per THR\",\n true)\n );\n });\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"raw.sig\",\n \"phys.sig\",\n new TaskC2(\"SignalPhysTransform: Create Phys Sigs\",\n \"Create Phys Signals, \")\n );\n });\n\n \/\/manager.registerTask([]() {\n \/\/return new JPetTaskLoader(\"phys_sig\", \"hits\",\n \/\/new HitFinder(\"Module: Pair signals\",\n \/\/\"Create hits from physical signals from both ends of scintilators\"));\n \/\/});\n\n\n \/\/ manager.registerTask([](){\n \/\/ return new JPetTaskLoader(\"phys.hit\", \"phys.hit.means\",\n \/\/ \t\t\t\tnew TaskD(\"Module D: Make histograms for hits\",\n \/\/ \t\t\t\t\t \"Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module\"));\n \/\/ });\n\n\n \/\/ manager.registerTask([](){\n \/\/ return new JPetTaskLoader(\"phys.hit.means\", \"phys.hit.coincplots\",\n \/\/ \t\t\t\tnew TaskE(\"Module E: Filter hits\",\n \/\/ \t\t\t\t\t \"Pass only hits with time diffrerence close to the peak\"));\n \/\/ });\n\n manager.run();\n}\n<commit_msg>Activate taks chain till hit findiing in main.cpp<commit_after>\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file main.cpp\n *\/\n\n#include <DBHandler\/HeaderFiles\/DBHandler.h>\n#include <JPetManager\/JPetManager.h>\n#include <JPetTaskLoader\/JPetTaskLoader.h>\n#include \"TaskA.h\"\n#include \"TimeCalibLoader.h\"\n#include \"SignalFinder.h\"\n#include \"HitFinder.h\"\n#include \"TaskC2.h\"\n#include \"TaskD.h\"\n#include \"TaskE.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n \/\/DB::SERVICES::DBHandler::createDBConnection(\"..\/DBConfig\/configDB.cfg\");\n JPetManager& manager = JPetManager::getManager();\n manager.parseCmdLine(argc, argv);\n\n \/\/ Here create all analysis modules to be used:\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"hld\",\n \"tslot.raw\",\n new TaskA(\"TaskA: Unp to Timewindow\",\n \"Process unpacked HLD file into a tree of JPetTimeWindow objects\")\n );\n });\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"tslot.raw\", \"tslot_calib.raw\",\n new TimeCalibLoader(\"Apply time corrections from prepared calibrations\",\n \"Apply time corrections from prepared calibrations\"));\n });\n manager.registerTask([]() {\n return new JPetTaskLoader(\"tslot_calib.raw\",\n \"raw.sig\",\n new SignalFinder(\"SignalFinder: Create Raw Sigs\",\n \"Create Raw Signals, optional draw TOTs per THR\",\n true)\n );\n });\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"raw.sig\",\n \"phys.sig\",\n new TaskC2(\"SignalPhysTransform: Create Phys Sigs\",\n \"Create Phys Signals, \")\n );\n });\n\n manager.registerTask([]() {\n return new JPetTaskLoader(\"phys.sig\", \"hits\",\n new HitFinder(\"Module: Pair signals\",\n \"Create hits from physical signals from both ends of scintilators\"));\n });\n\n\n \/\/ manager.registerTask([](){\n \/\/ return new JPetTaskLoader(\"phys.hit\", \"phys.hit.means\",\n \/\/ \t\t\t\tnew TaskD(\"Module D: Make histograms for hits\",\n \/\/ \t\t\t\t\t \"Only make timeDiff histos and produce mean timeDiff value for each threshold and slot to be used by the next module\"));\n \/\/ });\n\n\n \/\/ manager.registerTask([](){\n \/\/ return new JPetTaskLoader(\"phys.hit.means\", \"phys.hit.coincplots\",\n \/\/ \t\t\t\tnew TaskE(\"Module E: Filter hits\",\n \/\/ \t\t\t\t\t \"Pass only hits with time diffrerence close to the peak\"));\n \/\/ });\n\n manager.run();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <exception>\n\n#include \"Record.h\"\n#include \"Constants.h\"\n#include \"JobOutputStream.h\"\n#include \"SplitJobOutputStream.h\"\n\nusing namespace std;\n\nclass InvalidScanFileException:public exception{\npublic:\n\tInvalidScanFileException(string s){message=s;}\n\t~InvalidScanFileException() throw() {}\n\t const char* what() const throw() {return message.c_str();}\nprivate:\n\t\tstring message;\n};\n\nint main(int argc, char** argv)\n{\n\tstring freshScanPath=\"\";\n\tstring staleScanPath=\"\";\n\tstring outputDirPath=\"\";\n\n\t\/\/get command line args\n\tfor(int i=1; i<argc; i++)\n\t{\n\t\tif(i<argc-1){\n\t\t\tif(string(argv[i])==\"-n\"){\n\t\t\t\ti++;\n\t\t\t\tfreshScanPath = argv[i];\n\t\t\t}\n\t\t\telse if(string(argv[i])==\"-o\"){\n\t\t\t\ti++;\n\t\t\t\tstaleScanPath = argv[i];\n\t\t\t}\n\t\t\telse if(string(argv[i])==\"-f\"){\n\t\t\t\ti++;\n\t\t\t\toutputDirPath = argv[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcerr<<\"Invalid Option:\"<<argv[i]<<endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t\/\/error checking\n\tif(freshScanPath==\"\"||staleScanPath==\"\"||outputDirPath==\"\"){\n\t\tif(freshScanPath==\"\"){\n\t\t\tcerr<<\"Specify up-to-date scan with -n [file]\"<<endl;\n\t\t}\n\t\tif(staleScanPath==\"\"){\n\t\t\tcerr<<\"Specify out-of-date scan with -o [file]\"<<endl;\n\t\t}\n\t\tif(outputDirPath==\"\"){\n\t\t\tcerr<<\"Specify output directory with -f [directory]\"<<endl;\n\t\t}\n\t\treturn 1;\n\t}\n\n\t\/\/instantiate all objects\n\tfstream freshScan(freshScanPath.c_str(),ios::in);\n\tfstream staleScan(staleScanPath.c_str(),ios::in);\n\n\t\/\/error checking\n\tif(!freshScan.good() || !staleScan.good())\n\t{\n\t\tif(!staleScan.good()){\n\t\t\tcerr<<\"File path:\"<<staleScanPath<<\" is inaccessable.\"<<endl;\n\t\t}\n\t\tif(!freshScan.good()){\n\t\t\tcerr<<\"File path:\"<<freshScanPath<<\" is inaccessable.\"<<endl;\n\t\t}\n\t\treturn 2;\n\t}\n\n\ttry{\n\t\tJobOutputStream createDirs(\"C\",outputDirPath);\n\t\tJobOutputStream removeDirs(\"R\",outputDirPath);\n\t\tSplitJobOutputStream createFiles(\"A\",outputDirPath);\n\t\tSplitJobOutputStream removeFiles(\"D\",outputDirPath);\n\t\tSplitJobOutputStream modifyFiles(\"M\",outputDirPath);\n\t\tSplitJobOutputStream modifyDirs(\"Y\",outputDirPath);\n\t\tJobOutputStream buildLinks(\"L\",outputDirPath);\n\n\t\tRecord freshRec, staleRec;\n\t\tstring tmp;\n\t\t\n\t\twhile(freshScan && staleScan){\n\t\t\tif(freshRec.isValid() && staleRec.isValid()){\n\n\t\t\t\tif(freshRec==staleRec){\n\n\t\t\t\t\tif(freshRec.getType() == Record::Link){\n\t\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\t\t}\n\t\t\t\t\telse if(freshRec.isModified(staleRec)){\n\t\t\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\t\t\tmodifyDirs.writeRecord(freshRec);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmodifyFiles.writeRecord(freshRec);\n\t\t\t\t\t}\n\n\t\t\t\t\tfreshRec.invalidate();\n\t\t\t\t\tstaleRec.invalidate();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if(freshRec < staleRec){\n\t\t\t\t\t\/\/record has been added\n\t\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\t\tcreateDirs.writeRecord(freshRec);\n\t\t\t\t\telse if(freshRec.getType() == Record::Link)\n\t\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\t\telse\n\t\t\t\t\t\tcreateFiles.writeRecord(freshRec);\n\t\t\t\t\tfreshRec.invalidate();\n\t\t\t\t}\n\t\t\t\telse{ \/\/staleRec < freshRec\n\t\t\t\t\t\/\/record has been removed\n\t\t\t\t\tif(staleRec.getType() == Record::Directory)\n\t\t\t\t\t\tremoveDirs.writeRecord(staleRec);\n\t\t\t\t\telse\n\t\t\t\t\t\tremoveFiles.writeRecord(staleRec);\n\t\t\t\t\tstaleRec.invalidate();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/get new records\n\t\t\tif(!freshRec.isValid()){\n\t\t\t\tstring oldPath = freshRec[PATH];\n\t\t\t\tgetline(freshScan,tmp);\n\t\t\t\tfreshRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&freshRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(\"|\"+freshScanPath+\":\"+freshRec[PATH]+\":\"+tmp+\"|\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!staleRec.isValid()){\n\t\t\t\tstring oldPath = staleRec[PATH];\n\t\t\t\tgetline(staleScan,tmp);\n\t\t\t\tstaleRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&staleRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(\"|\"+staleScanPath+\":\"+staleRec[PATH]+\":\"+tmp+\"|\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\/\/while both inputs are valid\n\n\t\t\/\/get any remaining fresh records\n\t\twhile(freshScan){\n\t\t\tif(freshRec.isValid()){\n\t\t\t\t\/\/record has been added\n\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\tcreateDirs.writeRecord(freshRec);\n\t\t\t\telse if(freshRec.getType() == Record::Link)\n\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\telse\n\t\t\t\t\tcreateFiles.writeRecord(freshRec);\n\t\t\t\tfreshRec.invalidate();\n\t\t\t}\n\t\t\t\n\t\t\tif(!freshRec.isValid()){\n\t\t\t\tstring oldPath = freshRec[PATH];\n\t\t\t\tgetline(freshScan,tmp);\n\t\t\t\tfreshRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&freshRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(\"|\"+freshScanPath+\":\"+freshRec[PATH]+\":\"+tmp+\"|\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/get any remaining stale records\n\t\twhile(staleScan){\n\t\t\tif(staleRec.isValid()){\n\t\t\t\t\/\/record has been removed\n\t\t\t\tif(staleRec.getType() == Record::Directory)\n\t\t\t\t\tremoveDirs.writeRecord(staleRec);\n\t\t\t\telse\n\t\t\t\t\tremoveFiles.writeRecord(staleRec);\n\t\t\t\tstaleRec.invalidate();\n\t\t\t}\n\t\t\tif(!staleRec.isValid()){\n\t\t\t\tstring oldPath = staleRec[PATH];\n\t\t\t\tgetline(staleScan,tmp);\n\t\t\t\tstaleRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&staleRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(\"|\"+staleScanPath+\":\"+staleRec[PATH]+\":\"+tmp+\"|\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\n\t}catch(OutputFailedToOpenException e){\n\t\tcerr<<\"Output path:\"<<outputDirPath<<\" is inaccessable.\"<<endl;\n\t\treturn 3;\n\t}catch(IsModRanOnNERecException e){\n\t\tcerr<<\"One of the scan files is invalid.\"<<endl;\n\t\treturn 4;\n\t}catch(InvalidScanFileException e){\n\t\tcerr<<\"Scan file:\"<<e.what()<<\" is not sorted by path.\"<<endl;\n\t\treturn 5;\n\t}catch(exception e){\n\t\tcerr<<e.what()<<endl;\n\t\treturn 999;\n\t}\n\t\n\treturn 0;\n}\n\n<commit_msg>better error detection<commit_after>#include <iostream>\n#include <fstream>\n#include <exception>\n\n#include \"Record.h\"\n#include \"Constants.h\"\n#include \"JobOutputStream.h\"\n#include \"SplitJobOutputStream.h\"\n\nusing namespace std;\n\nclass InvalidScanFileException:public exception{\npublic:\n\tInvalidScanFileException(string s){message=s;}\n\t~InvalidScanFileException() throw() {}\n\t const char* what() const throw() {return message.c_str();}\nprivate:\n\t\tstring message;\n};\n\nint main(int argc, char** argv)\n{\n\tstring freshScanPath=\"\";\n\tstring staleScanPath=\"\";\n\tstring outputDirPath=\"\";\n\n\t\/\/get command line args\n\tfor(int i=1; i<argc; i++)\n\t{\n\t\tif(i<argc-1){\n\t\t\tif(string(argv[i])==\"-n\"){\n\t\t\t\ti++;\n\t\t\t\tfreshScanPath = argv[i];\n\t\t\t}\n\t\t\telse if(string(argv[i])==\"-o\"){\n\t\t\t\ti++;\n\t\t\t\tstaleScanPath = argv[i];\n\t\t\t}\n\t\t\telse if(string(argv[i])==\"-f\"){\n\t\t\t\ti++;\n\t\t\t\toutputDirPath = argv[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcerr<<\"Invalid Option:\"<<argv[i]<<endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\n\t\/\/error checking\n\tif(freshScanPath==\"\"||staleScanPath==\"\"||outputDirPath==\"\"){\n\t\tif(freshScanPath==\"\"){\n\t\t\tcerr<<\"Specify up-to-date scan with -n [file]\"<<endl;\n\t\t}\n\t\tif(staleScanPath==\"\"){\n\t\t\tcerr<<\"Specify out-of-date scan with -o [file]\"<<endl;\n\t\t}\n\t\tif(outputDirPath==\"\"){\n\t\t\tcerr<<\"Specify output directory with -f [directory]\"<<endl;\n\t\t}\n\t\treturn 1;\n\t}\n\n\t\/\/instantiate all objects\n\tfstream freshScan(freshScanPath.c_str(),ios::in);\n\tfstream staleScan(staleScanPath.c_str(),ios::in);\n\n\t\/\/error checking\n\tif(!freshScan.good() || !staleScan.good())\n\t{\n\t\tif(!staleScan.good()){\n\t\t\tcerr<<\"File path:\"<<staleScanPath<<\" is inaccessable.\"<<endl;\n\t\t}\n\t\tif(!freshScan.good()){\n\t\t\tcerr<<\"File path:\"<<freshScanPath<<\" is inaccessable.\"<<endl;\n\t\t}\n\t\treturn 2;\n\t}\n\t\n\ttry{\n\t\tJobOutputStream createDirs(\"C\",outputDirPath);\n\t\tJobOutputStream removeDirs(\"R\",outputDirPath);\n\t\tSplitJobOutputStream createFiles(\"A\",outputDirPath);\n\t\tSplitJobOutputStream removeFiles(\"D\",outputDirPath);\n\t\tSplitJobOutputStream modifyFiles(\"M\",outputDirPath);\n\t\tSplitJobOutputStream modifyDirs(\"Y\",outputDirPath);\n\t\tJobOutputStream buildLinks(\"L\",outputDirPath);\n\n\t\tRecord freshRec, staleRec;\n\t\tstring tmp;\n\t\t\n\t\twhile(freshScan && staleScan){\n\t\t\tif(freshRec.isValid() && staleRec.isValid()){\n\n\t\t\t\tif(freshRec==staleRec){\n\n\t\t\t\t\tif(freshRec.getType() == Record::Link){\n\t\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\t\t}\n\t\t\t\t\telse if(freshRec.isModified(staleRec)){\n\t\t\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\t\t\tmodifyDirs.writeRecord(freshRec);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmodifyFiles.writeRecord(freshRec);\n\t\t\t\t\t}\n\n\t\t\t\t\tfreshRec.invalidate();\n\t\t\t\t\tstaleRec.invalidate();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse if(freshRec < staleRec){\n\t\t\t\t\t\/\/record has been added\n\t\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\t\tcreateDirs.writeRecord(freshRec);\n\t\t\t\t\telse if(freshRec.getType() == Record::Link)\n\t\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\t\telse\n\t\t\t\t\t\tcreateFiles.writeRecord(freshRec);\n\t\t\t\t\tfreshRec.invalidate();\n\t\t\t\t}\n\t\t\t\telse{ \/\/staleRec < freshRec\n\t\t\t\t\t\/\/record has been removed\n\t\t\t\t\tif(staleRec.getType() == Record::Directory)\n\t\t\t\t\t\tremoveDirs.writeRecord(staleRec);\n\t\t\t\t\telse\n\t\t\t\t\t\tremoveFiles.writeRecord(staleRec);\n\t\t\t\t\tstaleRec.invalidate();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/get new records\n\t\t\tif(!freshRec.isValid()){\n\t\t\t\tstring oldPath = freshRec[PATH];\n\t\t\t\tgetline(freshScan,tmp);\n\t\t\t\tfreshRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&freshRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(freshScanPath+\"\\t\"+freshRec[PATH]+\"\\t\"+oldPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!staleRec.isValid()){\n\t\t\t\tstring oldPath = staleRec[PATH];\n\t\t\t\tgetline(staleScan,tmp);\n\t\t\t\tstaleRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&staleRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(staleScanPath+\"\\t\"+staleRec[PATH]+\"\\t\"+oldPath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\/\/while both inputs are valid\n\n\t\t\/\/get any remaining fresh records\n\t\twhile(freshScan){\n\t\t\tif(freshRec.isValid()){\n\t\t\t\t\/\/record has been added\n\t\t\t\tif(freshRec.getType() == Record::Directory)\n\t\t\t\t\tcreateDirs.writeRecord(freshRec);\n\t\t\t\telse if(freshRec.getType() == Record::Link)\n\t\t\t\t\tbuildLinks.writeRecord(freshRec);\n\t\t\t\telse\n\t\t\t\t\tcreateFiles.writeRecord(freshRec);\n\t\t\t\tfreshRec.invalidate();\n\t\t\t}\n\t\t\t\n\t\t\tif(!freshRec.isValid()){\n\t\t\t\tstring oldPath = freshRec[PATH];\n\t\t\t\tgetline(freshScan,tmp);\n\t\t\t\tfreshRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&freshRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(freshScanPath+\"\\t\"+freshRec[PATH]+\"\\t\"+oldPath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/get any remaining stale records\n\t\twhile(staleScan){\n\t\t\tif(staleRec.isValid()){\n\t\t\t\t\/\/record has been removed\n\t\t\t\tif(staleRec.getType() == Record::Directory)\n\t\t\t\t\tremoveDirs.writeRecord(staleRec);\n\t\t\t\telse\n\t\t\t\t\tremoveFiles.writeRecord(staleRec);\n\t\t\t\tstaleRec.invalidate();\n\t\t\t}\n\t\t\tif(!staleRec.isValid()){\n\t\t\t\tstring oldPath = staleRec[PATH];\n\t\t\t\tgetline(staleScan,tmp);\n\t\t\t\tstaleRec.init(tmp);\n\t\t\t\tif(oldPath!=\"\" &&staleRec[PATH]<oldPath){\n\t\t\t\t\tthrow InvalidScanFileException(staleScanPath+\"\\t\"+staleRec[PATH]+\"\\t\"+oldPath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\n\t}catch(OutputFailedToOpenException e){\n\t\tcerr<<\"Output path:\"<<outputDirPath<<\" is inaccessable.\"<<endl;\n\t\treturn 3;\n\t}catch(IsModRanOnNERecException e){\n\t\tcerr<<\"One of the scan files is invalid.\"<<endl;\n\t\treturn 4;\n\t}catch(InvalidScanFileException e){\n\t\tcerr<<\"Scan file:\"<<e.what()<<\" is not sorted by path.\"<<endl;\n\t\treturn 5;\n\t}catch(exception e){\n\t\tcerr<<e.what()<<endl;\n\t\treturn 999;\n\t}\n\t\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"multishard_mutation_query.hh\"\n#include \"schema_registry.hh\"\n#include \"tests\/cql_test_env.hh\"\n#include \"tests\/eventually.hh\"\n#include \"tests\/cql_assertions.hh\"\n#include \"tests\/mutation_assertions.hh\"\n#include \"tests\/test_table.hh\"\n\n#include <seastar\/testing\/thread_test_case.hh>\n\n#include <experimental\/source_location>\n\nconst sstring KEYSPACE_NAME = \"multishard_mutation_query_test\";\n\nstatic uint64_t aggregate_querier_cache_stat(distributed<database>& db, uint64_t query::querier_cache::stats::*stat) {\n return map_reduce(boost::irange(0u, smp::count), [stat, &db] (unsigned shard) {\n return db.invoke_on(shard, [stat] (database& local_db) {\n auto& stats = local_db.get_querier_cache_stats();\n return stats.*stat;\n });\n }, 0, std::plus<size_t>()).get0();\n}\n\nstatic void check_cache_population(distributed<database>& db, size_t queriers,\n std::experimental::source_location sl = std::experimental::source_location::current()) {\n BOOST_TEST_MESSAGE(format(\"{}() called from {}() {}:{:d}\", __FUNCTION__, sl.function_name(), sl.file_name(), sl.line()));\n\n parallel_for_each(boost::irange(0u, smp::count), [queriers, &db] (unsigned shard) {\n return db.invoke_on(shard, [queriers] (database& local_db) {\n auto& stats = local_db.get_querier_cache_stats();\n BOOST_REQUIRE_EQUAL(stats.population, queriers);\n });\n }).get0();\n}\n\nstatic void require_eventually_empty_caches(distributed<database>& db,\n std::experimental::source_location sl = std::experimental::source_location::current()) {\n BOOST_TEST_MESSAGE(format(\"{}() called from {}() {}:{:d}\", __FUNCTION__, sl.function_name(), sl.file_name(), sl.line()));\n\n auto aggregated_population_is_zero = [&] () mutable {\n return aggregate_querier_cache_stat(db, &query::querier_cache::stats::population) == 0;\n };\n BOOST_REQUIRE(eventually_true(aggregated_population_is_zero));\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_abandoned_read) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, _] = test::create_test_table(env, KEYSPACE_NAME, \"test_abandoned_read\");\n (void)_;\n\n auto cmd = query::read_command(s->id(), s->version(), s->full_slice(), 7, gc_clock::now(), std::nullopt, query::max_partitions,\n utils::make_random_uuid(), true);\n\n query_mutations_on_all_shards(env.db(), s, cmd, {query::full_partition_range}, nullptr, std::numeric_limits<uint64_t>::max()).get();\n\n check_cache_population(env.db(), 1);\n\n sleep(2s).get();\n\n require_eventually_empty_caches(env.db());\n\n return make_ready_future<>();\n }).get();\n}\n\nstatic std::vector<mutation> read_all_partitions_one_by_one(distributed<database>& db, schema_ptr s, std::vector<dht::decorated_key> pkeys) {\n const auto& partitioner = dht::global_partitioner();\n std::vector<mutation> results;\n results.reserve(pkeys.size());\n\n for (const auto& pkey : pkeys) {\n const auto res = db.invoke_on(partitioner.shard_of(pkey.token()), [gs = global_schema_ptr(s), &pkey] (database& db) {\n return async([s = gs.get(), &pkey, &db] () mutable {\n auto accounter = db.get_result_memory_limiter().new_mutation_read(std::numeric_limits<size_t>::max()).get0();\n const auto cmd = query::read_command(s->id(), s->version(), s->full_slice(), query::max_rows);\n const auto range = dht::partition_range::make_singular(pkey);\n return make_foreign(std::make_unique<reconcilable_result>(\n db.query_mutations(std::move(s), cmd, range, std::move(accounter), nullptr).get0()));\n });\n }).get0();\n\n BOOST_REQUIRE_EQUAL(res->partitions().size(), 1);\n results.emplace_back(res->partitions().front().mut().unfreeze(s));\n }\n\n return results;\n}\n\nusing stateful_query = bool_class<class stateful>;\n\nstatic std::pair<std::vector<mutation>, size_t>\nread_all_partitions_with_paged_scan(distributed<database>& db, schema_ptr s, size_t page_size, stateful_query is_stateful,\n const std::function<void(size_t)>& page_hook) {\n const auto max_size = std::numeric_limits<uint64_t>::max();\n const auto query_uuid = is_stateful ? utils::make_random_uuid() : utils::UUID{};\n std::vector<mutation> results;\n auto cmd = query::read_command(s->id(), s->version(), s->full_slice(), page_size, gc_clock::now(), std::nullopt, query::max_partitions,\n query_uuid, true);\n\n \/\/ First page is special, needs to have `is_first_page` set.\n {\n auto res = query_mutations_on_all_shards(db, s, cmd, {query::full_partition_range}, nullptr, max_size).get0();\n for (auto& part : res->partitions()) {\n results.emplace_back(part.mut().unfreeze(s));\n }\n cmd.is_first_page = false;\n }\n\n size_t nrows = page_size;\n unsigned npages = 0;\n\n \/\/ Rest of the pages.\n \/\/ Loop until a page turns up with less rows than the limit.\n while (nrows == page_size) {\n page_hook(npages);\n if (is_stateful) {\n BOOST_REQUIRE(aggregate_querier_cache_stat(db, &query::querier_cache::stats::lookups) >= npages);\n }\n\n const auto& last_pkey = results.back().decorated_key();\n const auto& last_ckey = results.back().partition().clustered_rows().rbegin()->key();\n auto pkrange = dht::partition_range::make_starting_with(dht::partition_range::bound(last_pkey, true));\n auto ckrange = query::clustering_range::make_starting_with(query::clustering_range::bound(last_ckey, false));\n if (const auto& sr = cmd.slice.get_specific_ranges(); sr) {\n cmd.slice.clear_range(*s, sr->pk());\n }\n cmd.slice.set_range(*s, last_pkey.key(), {ckrange});\n\n auto res = query_mutations_on_all_shards(db, s, cmd, {pkrange}, nullptr, max_size).get0();\n\n if (res->partitions().empty()) {\n nrows = 0;\n } else {\n auto it = res->partitions().begin();\n auto end = res->partitions().end();\n auto first_mut = it->mut().unfreeze(s);\n\n nrows = first_mut.live_row_count();\n\n \/\/ The first partition of the new page may overlap with the last\n \/\/ partition of the last page.\n if (results.back().decorated_key().equal(*s, first_mut.decorated_key())) {\n results.back().apply(std::move(first_mut));\n } else {\n results.emplace_back(std::move(first_mut));\n }\n ++it;\n for (;it != end; ++it) {\n auto mut = it->mut().unfreeze(s);\n nrows += mut.live_row_count();\n results.emplace_back(std::move(mut));\n }\n }\n\n ++npages;\n }\n\n return std::pair(results, npages);\n}\n\nvoid check_results_are_equal(std::vector<mutation>& results1, std::vector<mutation>& results2) {\n BOOST_REQUIRE_EQUAL(results1.size(), results2.size());\n\n auto mut_less = [] (const mutation& a, const mutation& b) {\n return a.decorated_key().less_compare(*a.schema(), b.decorated_key());\n };\n boost::sort(results1, mut_less);\n boost::sort(results2, mut_less);\n for (unsigned i = 0; i < results1.size(); ++i) {\n BOOST_TEST_MESSAGE(format(\"Comparing mutation #{:d}\", i));\n assert_that(results2[i]).is_equal_to(results1[i]);\n }\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_read_all) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, pkeys] = test::create_test_table(env, KEYSPACE_NAME, \"test_read_all\");\n\n \/\/ First read all partition-by-partition (not paged).\n auto results1 = read_all_partitions_one_by_one(env.db(), s, pkeys);\n\n \/\/ Then do a paged range-query, with reader caching\n auto results2 = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::yes, [&] (size_t) {\n check_cache_population(env.db(), 1);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), 0);\n }).first;\n\n check_results_are_equal(results1, results2);\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::time_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::resource_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::memory_based_evictions), 0);\n\n require_eventually_empty_caches(env.db());\n\n \/\/ Then do a paged range-query, without reader caching\n auto results3 = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::no, [&] (size_t) {\n check_cache_population(env.db(), 0);\n }).first;\n\n check_results_are_equal(results1, results3);\n\n return make_ready_future<>();\n }).get();\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_evict_a_shard_reader_on_each_page) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, pkeys] = test::create_test_table(env, KEYSPACE_NAME, \"test_evict_a_shard_reader_on_each_page\");\n\n \/\/ First read all partition-by-partition (not paged).\n auto results1 = read_all_partitions_one_by_one(env.db(), s, pkeys);\n\n \/\/ Then do a paged range-query\n auto [results2, npages] = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::yes, [&] (size_t page) {\n check_cache_population(env.db(), 1);\n\n env.db().invoke_on(page % smp::count, [&] (database& db) {\n db.get_querier_cache().evict_one();\n }).get();\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), page);\n });\n\n check_results_are_equal(results1, results2);\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::time_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::resource_based_evictions), npages);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::memory_based_evictions), 0);\n\n require_eventually_empty_caches(env.db());\n\n return make_ready_future<>();\n }).get();\n}\n<commit_msg>tests\/multishard_mutation_query_test: refactor read_all_partitions_with_paged_scan()<commit_after>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"multishard_mutation_query.hh\"\n#include \"schema_registry.hh\"\n#include \"tests\/cql_test_env.hh\"\n#include \"tests\/eventually.hh\"\n#include \"tests\/cql_assertions.hh\"\n#include \"tests\/mutation_assertions.hh\"\n#include \"tests\/test_table.hh\"\n\n#include <seastar\/testing\/thread_test_case.hh>\n\n#include <experimental\/source_location>\n\nconst sstring KEYSPACE_NAME = \"multishard_mutation_query_test\";\n\nstatic uint64_t aggregate_querier_cache_stat(distributed<database>& db, uint64_t query::querier_cache::stats::*stat) {\n return map_reduce(boost::irange(0u, smp::count), [stat, &db] (unsigned shard) {\n return db.invoke_on(shard, [stat] (database& local_db) {\n auto& stats = local_db.get_querier_cache_stats();\n return stats.*stat;\n });\n }, 0, std::plus<size_t>()).get0();\n}\n\nstatic void check_cache_population(distributed<database>& db, size_t queriers,\n std::experimental::source_location sl = std::experimental::source_location::current()) {\n BOOST_TEST_MESSAGE(format(\"{}() called from {}() {}:{:d}\", __FUNCTION__, sl.function_name(), sl.file_name(), sl.line()));\n\n parallel_for_each(boost::irange(0u, smp::count), [queriers, &db] (unsigned shard) {\n return db.invoke_on(shard, [queriers] (database& local_db) {\n auto& stats = local_db.get_querier_cache_stats();\n BOOST_REQUIRE_EQUAL(stats.population, queriers);\n });\n }).get0();\n}\n\nstatic void require_eventually_empty_caches(distributed<database>& db,\n std::experimental::source_location sl = std::experimental::source_location::current()) {\n BOOST_TEST_MESSAGE(format(\"{}() called from {}() {}:{:d}\", __FUNCTION__, sl.function_name(), sl.file_name(), sl.line()));\n\n auto aggregated_population_is_zero = [&] () mutable {\n return aggregate_querier_cache_stat(db, &query::querier_cache::stats::population) == 0;\n };\n BOOST_REQUIRE(eventually_true(aggregated_population_is_zero));\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_abandoned_read) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, _] = test::create_test_table(env, KEYSPACE_NAME, \"test_abandoned_read\");\n (void)_;\n\n auto cmd = query::read_command(s->id(), s->version(), s->full_slice(), 7, gc_clock::now(), std::nullopt, query::max_partitions,\n utils::make_random_uuid(), true);\n\n query_mutations_on_all_shards(env.db(), s, cmd, {query::full_partition_range}, nullptr, std::numeric_limits<uint64_t>::max()).get();\n\n check_cache_population(env.db(), 1);\n\n sleep(2s).get();\n\n require_eventually_empty_caches(env.db());\n\n return make_ready_future<>();\n }).get();\n}\n\nstatic std::vector<mutation> read_all_partitions_one_by_one(distributed<database>& db, schema_ptr s, std::vector<dht::decorated_key> pkeys) {\n const auto& partitioner = dht::global_partitioner();\n std::vector<mutation> results;\n results.reserve(pkeys.size());\n\n for (const auto& pkey : pkeys) {\n const auto res = db.invoke_on(partitioner.shard_of(pkey.token()), [gs = global_schema_ptr(s), &pkey] (database& db) {\n return async([s = gs.get(), &pkey, &db] () mutable {\n auto accounter = db.get_result_memory_limiter().new_mutation_read(std::numeric_limits<size_t>::max()).get0();\n const auto cmd = query::read_command(s->id(), s->version(), s->full_slice(), query::max_rows);\n const auto range = dht::partition_range::make_singular(pkey);\n return make_foreign(std::make_unique<reconcilable_result>(\n db.query_mutations(std::move(s), cmd, range, std::move(accounter), nullptr).get0()));\n });\n }).get0();\n\n BOOST_REQUIRE_EQUAL(res->partitions().size(), 1);\n results.emplace_back(res->partitions().front().mut().unfreeze(s));\n }\n\n return results;\n}\n\nusing stateful_query = bool_class<class stateful>;\n\nstatic std::pair<std::vector<mutation>, size_t>\nread_partitions_with_paged_scan(distributed<database>& db, schema_ptr s, uint32_t page_size, uint64_t max_size, stateful_query is_stateful,\n const dht::partition_range& range, const query::partition_slice& slice, const std::function<void(size_t)>& page_hook = {}) {\n const auto query_uuid = is_stateful ? utils::make_random_uuid() : utils::UUID{};\n std::vector<mutation> results;\n auto cmd = query::read_command(s->id(), s->version(), slice, page_size, gc_clock::now(), std::nullopt, query::max_partitions, query_uuid, true);\n\n bool has_more = true;\n\n \/\/ First page is special, needs to have `is_first_page` set.\n {\n auto res = query_mutations_on_all_shards(db, s, cmd, {range}, nullptr, max_size).get0();\n for (auto& part : res->partitions()) {\n auto mut = part.mut().unfreeze(s);\n results.emplace_back(std::move(mut));\n }\n cmd.is_first_page = false;\n has_more = !res->partitions().empty();\n }\n\n if (!has_more) {\n return std::pair(results, 1);\n }\n\n unsigned npages = 0;\n\n const auto last_ckey_of = [] (const mutation& mut) -> std::optional<clustering_key> {\n if (mut.partition().clustered_rows().empty()) {\n return std::nullopt;\n }\n return mut.partition().clustered_rows().rbegin()->key();\n };\n\n auto last_pkey = results.back().decorated_key();\n auto last_ckey = last_ckey_of(results.back());\n\n \/\/ Rest of the pages. Loop until an empty page turns up. Not very\n \/\/ sophisticated but simple and safe.\n while (has_more) {\n if (page_hook) {\n page_hook(npages);\n }\n\n ++npages;\n\n auto pkrange = dht::partition_range(dht::partition_range::bound(last_pkey, last_ckey.has_value()), range.end());\n\n if (last_ckey) {\n auto ckranges = cmd.slice.default_row_ranges();\n query::trim_clustering_row_ranges_to(*s, ckranges, *last_ckey);\n cmd.slice.clear_range(*s, last_pkey.key());\n cmd.slice.clear_ranges();\n cmd.slice.set_range(*s, last_pkey.key(), std::move(ckranges));\n }\n\n auto res = query_mutations_on_all_shards(db, s, cmd, {pkrange}, nullptr, max_size).get0();\n\n if (is_stateful) {\n BOOST_REQUIRE(aggregate_querier_cache_stat(db, &query::querier_cache::stats::lookups) >= npages);\n }\n\n if (!res->partitions().empty()) {\n auto it = res->partitions().begin();\n auto end = res->partitions().end();\n auto first_mut = it->mut().unfreeze(s);\n\n last_pkey = first_mut.decorated_key();\n last_ckey = last_ckey_of(first_mut);\n\n \/\/ The first partition of the new page may overlap with the last\n \/\/ partition of the last page.\n if (results.back().decorated_key().equal(*s, first_mut.decorated_key())) {\n results.back().apply(std::move(first_mut));\n } else {\n results.emplace_back(std::move(first_mut));\n }\n ++it;\n for (;it != end; ++it) {\n auto mut = it->mut().unfreeze(s);\n last_pkey = mut.decorated_key();\n last_ckey = last_ckey_of(mut);\n results.emplace_back(std::move(mut));\n }\n }\n\n has_more = !res->partitions().empty();\n }\n\n return std::pair(results, npages);\n}\n\nstatic std::pair<std::vector<mutation>, size_t>\nread_all_partitions_with_paged_scan(distributed<database>& db, schema_ptr s, uint32_t page_size, stateful_query is_stateful,\n const std::function<void(size_t)>& page_hook) {\n return read_partitions_with_paged_scan(db, s, page_size, std::numeric_limits<uint64_t>::max(), is_stateful, query::full_partition_range,\n s->full_slice(), page_hook);\n}\n\nvoid check_results_are_equal(std::vector<mutation>& results1, std::vector<mutation>& results2) {\n BOOST_REQUIRE_EQUAL(results1.size(), results2.size());\n\n auto mut_less = [] (const mutation& a, const mutation& b) {\n return a.decorated_key().less_compare(*a.schema(), b.decorated_key());\n };\n boost::sort(results1, mut_less);\n boost::sort(results2, mut_less);\n for (unsigned i = 0; i < results1.size(); ++i) {\n BOOST_TEST_MESSAGE(format(\"Comparing mutation #{:d}\", i));\n assert_that(results2[i]).is_equal_to(results1[i]);\n }\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_read_all) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, pkeys] = test::create_test_table(env, KEYSPACE_NAME, \"test_read_all\");\n\n \/\/ First read all partition-by-partition (not paged).\n auto results1 = read_all_partitions_one_by_one(env.db(), s, pkeys);\n\n \/\/ Then do a paged range-query, with reader caching\n auto results2 = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::yes, [&] (size_t) {\n check_cache_population(env.db(), 1);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), 0);\n }).first;\n\n check_results_are_equal(results1, results2);\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::time_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::resource_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::memory_based_evictions), 0);\n\n require_eventually_empty_caches(env.db());\n\n \/\/ Then do a paged range-query, without reader caching\n auto results3 = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::no, [&] (size_t) {\n check_cache_population(env.db(), 0);\n }).first;\n\n check_results_are_equal(results1, results3);\n\n return make_ready_future<>();\n }).get();\n}\n\n\/\/ Best run with SMP>=2\nSEASTAR_THREAD_TEST_CASE(test_evict_a_shard_reader_on_each_page) {\n do_with_cql_env([] (cql_test_env& env) -> future<> {\n using namespace std::chrono_literals;\n\n env.db().invoke_on_all([] (database& db) {\n db.set_querier_cache_entry_ttl(2s);\n }).get();\n\n auto [s, pkeys] = test::create_test_table(env, KEYSPACE_NAME, \"test_evict_a_shard_reader_on_each_page\");\n\n \/\/ First read all partition-by-partition (not paged).\n auto results1 = read_all_partitions_one_by_one(env.db(), s, pkeys);\n\n \/\/ Then do a paged range-query\n auto [results2, npages] = read_all_partitions_with_paged_scan(env.db(), s, 4, stateful_query::yes, [&] (size_t page) {\n check_cache_population(env.db(), 1);\n\n env.db().invoke_on(page % smp::count, [&] (database& db) {\n db.get_querier_cache().evict_one();\n }).get();\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::misses), page);\n });\n\n check_results_are_equal(results1, results2);\n\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::drops), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::time_based_evictions), 0);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::resource_based_evictions), npages);\n BOOST_REQUIRE_EQUAL(aggregate_querier_cache_stat(env.db(), &query::querier_cache::stats::memory_based_evictions), 0);\n\n require_eventually_empty_caches(env.db());\n\n return make_ready_future<>();\n }).get();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n#include \"utils\/fb_utilities.hh\"\n#include \"locator\/network_topology_strategy.hh\"\n#include \"tests\/test-utils.hh\"\n#include \"core\/sstring.hh\"\n#include \"log.hh\"\n#include <vector>\n#include <string>\n#include <map>\n#include <iostream>\n#include <sstream>\n\nstatic logging::logger nlogger(\"NetworkTopologyStrategyLogger\");\n\nusing namespace locator;\n\nstruct ring_point {\n double point;\n inet_address host;\n};\n\nvoid print_natural_endpoints(double point, const std::vector<inet_address> v) {\n nlogger.debug(\"Natural endpoints for a token {}:\", point);\n std::string str;\n std::ostringstream strm(str);\n\n for (auto& addr : v) {\n strm<<addr<<\" \";\n }\n\n nlogger.debug(\"{}\", strm.str());\n}\n\nvoid strategy_sanity_check(\n abstract_replication_strategy* ars_ptr,\n const std::map<sstring, sstring>& options) {\n\n network_topology_strategy* nts_ptr =\n dynamic_cast<network_topology_strategy*>(ars_ptr);\n\n \/\/\n \/\/ Check that both total and per-DC RFs in options match the corresponding\n \/\/ value in the strategy object.\n \/\/\n size_t total_rf = 0;\n for (auto& val : options) {\n size_t rf = std::stol(val.second);\n BOOST_CHECK(nts_ptr->get_replication_factor(val.first) == rf);\n\n total_rf += rf;\n }\n\n BOOST_CHECK(ars_ptr->get_replication_factor() == total_rf);\n}\n\nvoid endpoints_check(\n abstract_replication_strategy* ars_ptr,\n std::vector<inet_address>& endpoints) {\n\n \/\/ Check the total RF\n BOOST_CHECK(endpoints.size() == ars_ptr->get_replication_factor());\n\n \/\/ Check the uniqueness\n std::unordered_set<inet_address> ep_set(endpoints.begin(), endpoints.end());\n BOOST_CHECK(endpoints.size() == ep_set.size());\n\n \/\/ Check the per-DC RF\n auto& snitch = i_endpoint_snitch::get_local_snitch_ptr();\n std::unordered_map<sstring, size_t> dc_rf;\n for (auto ep : endpoints) {\n sstring dc = snitch->get_datacenter(ep);\n\n auto rf = dc_rf.find(dc);\n if (rf == dc_rf.end()) {\n dc_rf[dc] = 1;\n } else {\n rf->second++;\n }\n }\n\n network_topology_strategy* nts_ptr =\n dynamic_cast<network_topology_strategy*>(ars_ptr);\n for (auto& rf : dc_rf) {\n BOOST_CHECK(rf.second == nts_ptr->get_replication_factor(rf.first));\n }\n}\n\nauto d2t = [](double d) {\n unsigned long l = net::hton(static_cast<unsigned long>(d*(std::numeric_limits<unsigned long>::max())));\n std::array<char, 8> a;\n memcpy(a.data(), &l, 8);\n return a;\n};\n\n\/**\n * Check the get_natural_endpoints() output for tokens between every two\n * adjacent ring points.\n * @param ring_points ring description\n * @param options strategy options\n * @param ars_ptr strategy object\n *\/\nvoid full_ring_check(const std::vector<ring_point>& ring_points,\n const std::map<sstring, sstring>& options,\n abstract_replication_strategy* ars_ptr) {\n strategy_sanity_check(ars_ptr, options);\n\n for (auto& rp : ring_points) {\n double cur_point1 = rp.point - 0.5;\n token t1({dht::token::kind::key,\n {(int8_t*)d2t(cur_point1 \/ ring_points.size()).data(), 8}});\n uint64_t cache_hit_count = ars_ptr->get_cache_hits_count();\n auto endpoints1 = ars_ptr->get_natural_endpoints(t1);\n\n endpoints_check(ars_ptr, endpoints1);\n \/\/ validate that the result hasn't been taken from the cache\n BOOST_CHECK(cache_hit_count == ars_ptr->get_cache_hits_count());\n\n print_natural_endpoints(cur_point1, endpoints1);\n\n \/\/\n \/\/ Check a different endpoint in the same range as t1 and validate that\n \/\/ the endpoints has been taken from the cache and that the output is\n \/\/ identical to the one not taken from the cache.\n \/\/\n cache_hit_count = ars_ptr->get_cache_hits_count();\n double cur_point2 = rp.point - 0.2;\n token t2({dht::token::kind::key,\n {(int8_t*)d2t(cur_point2 \/ ring_points.size()).data(), 8}});\n auto endpoints2 = ars_ptr->get_natural_endpoints(t2);\n\n endpoints_check(ars_ptr, endpoints2);\n BOOST_CHECK(cache_hit_count + 1 == ars_ptr->get_cache_hits_count());\n BOOST_CHECK(endpoints1 == endpoints2);\n }\n}\n\nfuture<> simple_test() {\n utils::fb_utilities::set_broadcast_address(gms::inet_address(\"localhost\"));\n utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address(\"localhost\"));\n\n \/\/ Create the RackInferringSnitch\n return i_endpoint_snitch::create_snitch(\"RackInferringSnitch\").then(\n [] {\n\n lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();\n std::vector<ring_point> ring_points = {\n { 1.0, inet_address(\"192.100.10.1\") },\n { 2.0, inet_address(\"192.101.10.1\") },\n { 3.0, inet_address(\"192.102.10.1\") },\n { 4.0, inet_address(\"192.100.20.1\") },\n { 5.0, inet_address(\"192.101.20.1\") },\n { 6.0, inet_address(\"192.102.20.1\") },\n { 7.0, inet_address(\"192.100.30.1\") },\n { 8.0, inet_address(\"192.101.30.1\") },\n { 9.0, inet_address(\"192.102.30.1\") },\n { 10.0, inet_address(\"192.102.40.1\") },\n { 11.0, inet_address(\"192.102.40.2\") }\n };\n \/\/ Initialize the token_metadata\n for (unsigned i = 0; i < ring_points.size(); i++) {\n tm->update_normal_token(\n {dht::token::kind::key,\n {(int8_t*)d2t(ring_points[i].point \/ ring_points.size()).data(), 8}\n },\n ring_points[i].host);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create the replication strategy\n std::map<sstring, sstring> options323 = {\n {\"100\", \"3\"},\n {\"101\", \"2\"},\n {\"102\", \"3\"}\n };\n\n auto ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, options323);\n\n auto ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, options323, ars_ptr);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create the replication strategy\n std::map<sstring, sstring> options320 = {\n {\"100\", \"3\"},\n {\"101\", \"2\"},\n {\"102\", \"0\"}\n };\n\n ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, options320);\n\n ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, options320, ars_ptr);\n\n \/\/\n \/\/ Check cache invalidation: invalidate the cache and run a full ring\n \/\/ check once again. If cache is not properly invalidated one of the\n \/\/ points will be taken from the cache when it shouldn't and the\n \/\/ corresponding check will fail.\n \/\/\n tm->invalidate_cached_rings();\n full_ring_check(ring_points, options320, ars_ptr);\n\n return i_endpoint_snitch::stop_snitch();\n });\n}\n\nfuture<> heavy_origin_test() {\n utils::fb_utilities::set_broadcast_address(gms::inet_address(\"localhost\"));\n utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address(\"localhost\"));\n\n \/\/ Create the RackInferringSnitch\n return i_endpoint_snitch::create_snitch(\"RackInferringSnitch\").then(\n [] {\n std::vector<int> dc_racks = {2, 4, 8};\n std::vector<int> dc_endpoints = {128, 256, 512};\n std::vector<int> dc_replication = {2, 6, 6};\n\n lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();\n std::map<sstring, sstring> config_options;\n std::unordered_map<inet_address, std::unordered_set<token>> tokens;\n std::vector<ring_point> ring_points;\n\n size_t total_eps = 0;\n for (size_t dc = 0; dc < dc_racks.size(); ++dc) {\n for (int rack = 0; rack < dc_racks[dc]; ++rack) {\n total_eps += dc_endpoints[dc]\/dc_racks[dc];\n }\n }\n\n int total_rf = 0;\n double token_point = 1.0;\n for (size_t dc = 0; dc < dc_racks.size(); ++dc) {\n total_rf += dc_replication[dc];\n config_options.emplace(to_sstring(dc),\n to_sstring(dc_replication[dc]));\n for (int rack = 0; rack < dc_racks[dc]; ++rack) {\n for (int ep = 1; ep <= dc_endpoints[dc]\/dc_racks[dc]; ++ep) {\n\n \/\/ 10.dc.rack.ep\n int32_t ip = 0x0a000000 + ((int8_t)dc << 16) +\n ((int8_t)rack << 8) + (int8_t)ep;\n inet_address address(ip);\n ring_point rp = {token_point, address};\n\n ring_points.emplace_back(rp);\n tokens[address].emplace(token{dht::token::kind::key,\n {(int8_t*)d2t(token_point \/ total_eps).data(), 8}});\n\n nlogger.debug(\"adding node {} at {}\", address, token_point);\n\n token_point++;\n }\n }\n }\n\n tm->update_normal_tokens(tokens);\n\n auto ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, config_options);\n\n auto ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, config_options, ars_ptr);\n\n return i_endpoint_snitch::stop_snitch();\n });\n}\n\n\nSEASTAR_TEST_CASE(NetworkTopologyStrategy_simple) {\n return simple_test();\n}\n\nSEASTAR_TEST_CASE(NetworkTopologyStrategy_heavy) {\n return heavy_origin_test();\n}\n<commit_msg>tests: network_topology_strategy_test: peel off redundant parentheses around token initializer<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n#include \"utils\/fb_utilities.hh\"\n#include \"locator\/network_topology_strategy.hh\"\n#include \"tests\/test-utils.hh\"\n#include \"core\/sstring.hh\"\n#include \"log.hh\"\n#include <vector>\n#include <string>\n#include <map>\n#include <iostream>\n#include <sstream>\n\nstatic logging::logger nlogger(\"NetworkTopologyStrategyLogger\");\n\nusing namespace locator;\n\nstruct ring_point {\n double point;\n inet_address host;\n};\n\nvoid print_natural_endpoints(double point, const std::vector<inet_address> v) {\n nlogger.debug(\"Natural endpoints for a token {}:\", point);\n std::string str;\n std::ostringstream strm(str);\n\n for (auto& addr : v) {\n strm<<addr<<\" \";\n }\n\n nlogger.debug(\"{}\", strm.str());\n}\n\nvoid strategy_sanity_check(\n abstract_replication_strategy* ars_ptr,\n const std::map<sstring, sstring>& options) {\n\n network_topology_strategy* nts_ptr =\n dynamic_cast<network_topology_strategy*>(ars_ptr);\n\n \/\/\n \/\/ Check that both total and per-DC RFs in options match the corresponding\n \/\/ value in the strategy object.\n \/\/\n size_t total_rf = 0;\n for (auto& val : options) {\n size_t rf = std::stol(val.second);\n BOOST_CHECK(nts_ptr->get_replication_factor(val.first) == rf);\n\n total_rf += rf;\n }\n\n BOOST_CHECK(ars_ptr->get_replication_factor() == total_rf);\n}\n\nvoid endpoints_check(\n abstract_replication_strategy* ars_ptr,\n std::vector<inet_address>& endpoints) {\n\n \/\/ Check the total RF\n BOOST_CHECK(endpoints.size() == ars_ptr->get_replication_factor());\n\n \/\/ Check the uniqueness\n std::unordered_set<inet_address> ep_set(endpoints.begin(), endpoints.end());\n BOOST_CHECK(endpoints.size() == ep_set.size());\n\n \/\/ Check the per-DC RF\n auto& snitch = i_endpoint_snitch::get_local_snitch_ptr();\n std::unordered_map<sstring, size_t> dc_rf;\n for (auto ep : endpoints) {\n sstring dc = snitch->get_datacenter(ep);\n\n auto rf = dc_rf.find(dc);\n if (rf == dc_rf.end()) {\n dc_rf[dc] = 1;\n } else {\n rf->second++;\n }\n }\n\n network_topology_strategy* nts_ptr =\n dynamic_cast<network_topology_strategy*>(ars_ptr);\n for (auto& rf : dc_rf) {\n BOOST_CHECK(rf.second == nts_ptr->get_replication_factor(rf.first));\n }\n}\n\nauto d2t = [](double d) {\n unsigned long l = net::hton(static_cast<unsigned long>(d*(std::numeric_limits<unsigned long>::max())));\n std::array<char, 8> a;\n memcpy(a.data(), &l, 8);\n return a;\n};\n\n\/**\n * Check the get_natural_endpoints() output for tokens between every two\n * adjacent ring points.\n * @param ring_points ring description\n * @param options strategy options\n * @param ars_ptr strategy object\n *\/\nvoid full_ring_check(const std::vector<ring_point>& ring_points,\n const std::map<sstring, sstring>& options,\n abstract_replication_strategy* ars_ptr) {\n strategy_sanity_check(ars_ptr, options);\n\n for (auto& rp : ring_points) {\n double cur_point1 = rp.point - 0.5;\n token t1{dht::token::kind::key,\n {(int8_t*)d2t(cur_point1 \/ ring_points.size()).data(), 8}};\n uint64_t cache_hit_count = ars_ptr->get_cache_hits_count();\n auto endpoints1 = ars_ptr->get_natural_endpoints(t1);\n\n endpoints_check(ars_ptr, endpoints1);\n \/\/ validate that the result hasn't been taken from the cache\n BOOST_CHECK(cache_hit_count == ars_ptr->get_cache_hits_count());\n\n print_natural_endpoints(cur_point1, endpoints1);\n\n \/\/\n \/\/ Check a different endpoint in the same range as t1 and validate that\n \/\/ the endpoints has been taken from the cache and that the output is\n \/\/ identical to the one not taken from the cache.\n \/\/\n cache_hit_count = ars_ptr->get_cache_hits_count();\n double cur_point2 = rp.point - 0.2;\n token t2{dht::token::kind::key,\n {(int8_t*)d2t(cur_point2 \/ ring_points.size()).data(), 8}};\n auto endpoints2 = ars_ptr->get_natural_endpoints(t2);\n\n endpoints_check(ars_ptr, endpoints2);\n BOOST_CHECK(cache_hit_count + 1 == ars_ptr->get_cache_hits_count());\n BOOST_CHECK(endpoints1 == endpoints2);\n }\n}\n\nfuture<> simple_test() {\n utils::fb_utilities::set_broadcast_address(gms::inet_address(\"localhost\"));\n utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address(\"localhost\"));\n\n \/\/ Create the RackInferringSnitch\n return i_endpoint_snitch::create_snitch(\"RackInferringSnitch\").then(\n [] {\n\n lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();\n std::vector<ring_point> ring_points = {\n { 1.0, inet_address(\"192.100.10.1\") },\n { 2.0, inet_address(\"192.101.10.1\") },\n { 3.0, inet_address(\"192.102.10.1\") },\n { 4.0, inet_address(\"192.100.20.1\") },\n { 5.0, inet_address(\"192.101.20.1\") },\n { 6.0, inet_address(\"192.102.20.1\") },\n { 7.0, inet_address(\"192.100.30.1\") },\n { 8.0, inet_address(\"192.101.30.1\") },\n { 9.0, inet_address(\"192.102.30.1\") },\n { 10.0, inet_address(\"192.102.40.1\") },\n { 11.0, inet_address(\"192.102.40.2\") }\n };\n \/\/ Initialize the token_metadata\n for (unsigned i = 0; i < ring_points.size(); i++) {\n tm->update_normal_token(\n {dht::token::kind::key,\n {(int8_t*)d2t(ring_points[i].point \/ ring_points.size()).data(), 8}\n },\n ring_points[i].host);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create the replication strategy\n std::map<sstring, sstring> options323 = {\n {\"100\", \"3\"},\n {\"101\", \"2\"},\n {\"102\", \"3\"}\n };\n\n auto ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, options323);\n\n auto ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, options323, ars_ptr);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create the replication strategy\n std::map<sstring, sstring> options320 = {\n {\"100\", \"3\"},\n {\"101\", \"2\"},\n {\"102\", \"0\"}\n };\n\n ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, options320);\n\n ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, options320, ars_ptr);\n\n \/\/\n \/\/ Check cache invalidation: invalidate the cache and run a full ring\n \/\/ check once again. If cache is not properly invalidated one of the\n \/\/ points will be taken from the cache when it shouldn't and the\n \/\/ corresponding check will fail.\n \/\/\n tm->invalidate_cached_rings();\n full_ring_check(ring_points, options320, ars_ptr);\n\n return i_endpoint_snitch::stop_snitch();\n });\n}\n\nfuture<> heavy_origin_test() {\n utils::fb_utilities::set_broadcast_address(gms::inet_address(\"localhost\"));\n utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address(\"localhost\"));\n\n \/\/ Create the RackInferringSnitch\n return i_endpoint_snitch::create_snitch(\"RackInferringSnitch\").then(\n [] {\n std::vector<int> dc_racks = {2, 4, 8};\n std::vector<int> dc_endpoints = {128, 256, 512};\n std::vector<int> dc_replication = {2, 6, 6};\n\n lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();\n std::map<sstring, sstring> config_options;\n std::unordered_map<inet_address, std::unordered_set<token>> tokens;\n std::vector<ring_point> ring_points;\n\n size_t total_eps = 0;\n for (size_t dc = 0; dc < dc_racks.size(); ++dc) {\n for (int rack = 0; rack < dc_racks[dc]; ++rack) {\n total_eps += dc_endpoints[dc]\/dc_racks[dc];\n }\n }\n\n int total_rf = 0;\n double token_point = 1.0;\n for (size_t dc = 0; dc < dc_racks.size(); ++dc) {\n total_rf += dc_replication[dc];\n config_options.emplace(to_sstring(dc),\n to_sstring(dc_replication[dc]));\n for (int rack = 0; rack < dc_racks[dc]; ++rack) {\n for (int ep = 1; ep <= dc_endpoints[dc]\/dc_racks[dc]; ++ep) {\n\n \/\/ 10.dc.rack.ep\n int32_t ip = 0x0a000000 + ((int8_t)dc << 16) +\n ((int8_t)rack << 8) + (int8_t)ep;\n inet_address address(ip);\n ring_point rp = {token_point, address};\n\n ring_points.emplace_back(rp);\n tokens[address].emplace(token{dht::token::kind::key,\n {(int8_t*)d2t(token_point \/ total_eps).data(), 8}});\n\n nlogger.debug(\"adding node {} at {}\", address, token_point);\n\n token_point++;\n }\n }\n }\n\n tm->update_normal_tokens(tokens);\n\n auto ars_uptr = abstract_replication_strategy::create_replication_strategy(\n \"test keyspace\", \"NetworkTopologyStrategy\", *tm, config_options);\n\n auto ars_ptr = ars_uptr.get();\n\n full_ring_check(ring_points, config_options, ars_ptr);\n\n return i_endpoint_snitch::stop_snitch();\n });\n}\n\n\nSEASTAR_TEST_CASE(NetworkTopologyStrategy_simple) {\n return simple_test();\n}\n\nSEASTAR_TEST_CASE(NetworkTopologyStrategy_heavy) {\n return heavy_origin_test();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <shogun\/lib\/config.h>\n#ifdef HAVE_EIGEN3\n\n#include <shogun\/labels\/RegressionLabels.h>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/kernel\/GaussianKernel.h>\n#include <shogun\/regression\/GaussianProcessRegression.h>\n#include <shogun\/regression\/gp\/ExactInferenceMethod.h>\n#include <shogun\/regression\/gp\/ZeroMean.h>\n#include <shogun\/regression\/gp\/GaussianLikelihood.h>\n#include <gtest\/gtest.h>\n\nusing namespace shogun;\n\nTEST(GaussianProcessRegression,apply_regression)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329 *\/\n\tSGVector<float64_t> prediction_vector=predictions->get_labels();\n\tEXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression,apply_regression_larger_test)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\tindex_t n_test=5;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n_test);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\tX_test[2]=2.7;\n\tX_test[2]=3.1;\n\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329\n 0.373048041692408\n 0.253688340068952 *\/\n\tSGVector<float64_t> prediction_vector=predictions->get_labels();\n\/\/\tEXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);\n\/\/\tEXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);\n\/\/\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);\n\/\/\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.373048041692408), 10E-15);\n\/\/\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.253688340068952), 10E-15);\n\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression, get_mean_vector)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329 *\/\n\tSGVector<float64_t> mean_vector=gpr->get_mean_vector();\n\tEXPECT_LE(CMath::abs(mean_vector[0]-0.221198406887592), 10E-15);\n\tEXPECT_LE(CMath::abs(mean_vector[1]-0.537437461176145), 10E-15);\n\tEXPECT_LE(CMath::abs(mean_vector[2]-0.431605035301329), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression, get_covariance_vector)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* s2 =\n\n 1.426104216614624\n 1.416896787316447\n 1.535464779087576 *\/\n\tSGVector<float64_t> covariance_vector=gpr->get_covariance_vector();\n\tEXPECT_LE(CMath::abs(covariance_vector[0]-1.426104216614624), 10E-15);\n\tEXPECT_LE(CMath::abs(covariance_vector[1]-1.416896787316447), 10E-15);\n\tEXPECT_LE(CMath::abs(covariance_vector[2]-1.535464779087576), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\n#endif\n<commit_msg>fixed memory errors and added asserts again<commit_after>#include <shogun\/lib\/config.h>\n#ifdef HAVE_EIGEN3\n\n#include <shogun\/labels\/RegressionLabels.h>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/kernel\/GaussianKernel.h>\n#include <shogun\/regression\/GaussianProcessRegression.h>\n#include <shogun\/regression\/gp\/ExactInferenceMethod.h>\n#include <shogun\/regression\/gp\/ZeroMean.h>\n#include <shogun\/regression\/gp\/GaussianLikelihood.h>\n#include <gtest\/gtest.h>\n\nusing namespace shogun;\n\nTEST(GaussianProcessRegression,apply_regression)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329 *\/\n\tSGVector<float64_t> prediction_vector=predictions->get_labels();\n\tEXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression,apply_regression_larger_test)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\tindex_t n_test=5;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n_test);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\tX_test[3]=2.7;\n\tX_test[4]=3.1;\n\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329\n 0.373048041692408\n 0.253688340068952 *\/\n\tSGVector<float64_t> prediction_vector=predictions->get_labels();\n\tEXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.373048041692408), 10E-15);\n\tEXPECT_LE(CMath::abs(prediction_vector[2]-0.253688340068952), 10E-15);\n\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression, get_mean_vector)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* m =\n\n 0.221198406887592\n 0.537437461176145\n 0.431605035301329 *\/\n\tSGVector<float64_t> mean_vector=gpr->get_mean_vector();\n\tEXPECT_LE(CMath::abs(mean_vector[0]-0.221198406887592), 10E-15);\n\tEXPECT_LE(CMath::abs(mean_vector[1]-0.537437461176145), 10E-15);\n\tEXPECT_LE(CMath::abs(mean_vector[2]-0.431605035301329), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\nTEST(GaussianProcessRegression, get_covariance_vector)\n{\n\t\/* create some easy regression data: 1d noisy sine wave *\/\n\tindex_t n=3;\n\n\tSGMatrix<float64_t> X(1, n);\n\tSGMatrix<float64_t> X_test(1, n);\n\tSGVector<float64_t> Y(n);\n\n\tX[0]=0;\n\tX[1]=1.1;\n\tX[2]=2.2;\n\n\tX_test[0]=0.3;\n\tX_test[1]=1.3;\n\tX_test[2]=2.5;\n\n\tfor (index_t i=0; i<n; ++i)\n\t{\n\t\tY[i]=CMath::sin(X(0, i));\n\t}\n\n\t\/* shogun representation *\/\n\tCDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);\n\tCDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);\n\tCRegressionLabels* label_train=new CRegressionLabels(Y);\n\n\t\/* specity GPR with exact inference *\/\n\tfloat64_t sigma=1;\n\tfloat64_t shogun_sigma=sigma*sigma*2;\n\tCGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);\n\tCZeroMean* mean=new CZeroMean();\n\tCGaussianLikelihood* lik=new CGaussianLikelihood();\n\tlik->set_sigma(1);\n\tCExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,\n\t\t\tmean, label_train, lik);\n\tCGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,\n\t\t\tfeat_train, label_train);\n\n\t\/* perform inference *\/\n\tgpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);\n\tCRegressionLabels* predictions=gpr->apply_regression(feat_test);\n\n\t\/* do some checks against gpml toolbox*\/\n\n\t\/* s2 =\n\n 1.426104216614624\n 1.416896787316447\n 1.535464779087576 *\/\n\tSGVector<float64_t> covariance_vector=gpr->get_covariance_vector();\n\tEXPECT_LE(CMath::abs(covariance_vector[0]-1.426104216614624), 10E-15);\n\tEXPECT_LE(CMath::abs(covariance_vector[1]-1.416896787316447), 10E-15);\n\tEXPECT_LE(CMath::abs(covariance_vector[2]-1.535464779087576), 10E-15);\n\n\tSG_UNREF(predictions);\n\tSG_UNREF(gpr);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"tree.hh\"\n#include \"tree-entry.hh\"\n\nnamespace mimosa\n{\n namespace git\n {\n Tree::Tree(git_repository * repo,\n const git_oid * id)\n : tree_(nullptr)\n {\n git_tree_lookup(&tree_, repo, id);\n }\n\n Tree::Tree(git_repository * repo,\n const git_oid * id,\n const std::string & directory)\n : tree_(nullptr)\n {\n if (directory.empty()) {\n git_tree_lookup(&tree_, repo, id);\n return;\n }\n\n Tree root(repo, id);\n TreeEntry entry;\n if (git_tree_entry_bypath(entry.ref(), root, directory.c_str()))\n return;\n\n if (git_tree_entry_type(entry) != GIT_OBJ_TREE)\n return;\n\n git_tree_lookup(&tree_, repo, git_tree_entry_id(entry));\n }\n\n Tree::~Tree()\n {\n git_tree_free(tree_);\n }\n }\n}\n<commit_msg>git::Tree: allow null id, to have a null tree<commit_after>#include \"tree.hh\"\n#include \"tree-entry.hh\"\n\nnamespace mimosa\n{\n namespace git\n {\n Tree::Tree(git_repository * repo,\n const git_oid * id)\n : tree_(nullptr)\n {\n if (id)\n git_tree_lookup(&tree_, repo, id);\n }\n\n Tree::Tree(git_repository * repo,\n const git_oid * id,\n const std::string & directory)\n : tree_(nullptr)\n {\n if (directory.empty()) {\n git_tree_lookup(&tree_, repo, id);\n return;\n }\n\n Tree root(repo, id);\n TreeEntry entry;\n if (git_tree_entry_bypath(entry.ref(), root, directory.c_str()))\n return;\n\n if (git_tree_entry_type(entry) != GIT_OBJ_TREE)\n return;\n\n git_tree_lookup(&tree_, repo, git_tree_entry_id(entry));\n }\n\n Tree::~Tree()\n {\n git_tree_free(tree_);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"networkregistrationstub.h\"\n\n#include <QStringList>\n#include <QDebug>\n\nnamespace Cellular\n{\n\nstatic NetworkRegistration::Mode currentMode = NetworkRegistration::Automatic;\n\nAvailableOperator::AvailableOperator(const QString &mnc, const QString &mcc, const QString &name,\n AvailableOperator::Availability availability, QObject *parent) :\n QObject(parent)\n{\n setMnc(mnc);\n setMcc(mcc);\n setName(name);\n setAvailability(availability);\n}\n\nAvailableOperator::~AvailableOperator()\n{\n}\n\nvoid AvailableOperator::setMnc(const QString &mnc)\n{\n currentMnc = mnc;\n}\n\nvoid AvailableOperator::setMcc(const QString &mcc)\n{\n currentMcc = mcc;\n}\n\nvoid AvailableOperator::setName(const QString &name)\n{\n currentName = name;\n}\n\nvoid AvailableOperator::setAvailability(AvailableOperator::Availability availability)\n{\n currentAvailibility = availability;\n}\n\nQString AvailableOperator::mnc() const\n{\n return currentMnc;\n}\n\nQString AvailableOperator::mcc() const\n{\n return currentMcc;\n}\n\nQString AvailableOperator::name() const\n{\n return currentName;\n}\n\nAvailableOperator::Availability AvailableOperator::availability() const\n{\n return currentAvailibility;\n}\n\nNetworkRegistration::NetworkRegistration(QObject *parent) :\n QObject(parent), \n success(true),\n networkOperator(NULL)\n{\n}\n\nNetworkRegistration::~NetworkRegistration()\n{\n for(int i=0; i<operators.size(); ++i) {\n AvailableOperator *oper = operators.at(i);\n delete oper;\n oper = NULL;\n }\n}\n\nvoid NetworkRegistration::init(NetworkOperator *networkOperator)\n{\n this->networkOperator = networkOperator;\n}\n\nNetworkRegistration::Mode NetworkRegistration::mode() const\n{\n return currentMode;\n}\n\nvoid NetworkRegistration::selectOperator()\n{\n currentMode = NetworkRegistration::Automatic; \n emit selectionCompleted(true, QString(\"\"));\n}\n\nvoid NetworkRegistration::selectOperator(const QString &mnc, const QString &mcc)\n{\n currentMode = NetworkRegistration::Manual;\n for(int i=0; i<operators.size(); ++i) { \n if(operators.at(i)->mnc() == mnc && operators.at(i)->mcc() == mcc) {\n operators.at(i)->setAvailability(AvailableOperator::Current);\n if(networkOperator != NULL) {\n networkOperator->setName(operators.at(i)->name());\n networkOperator->setMnc(operators.at(i)->mnc());\n networkOperator->setMcc(operators.at(i)->mcc());\n }\n }\n else\n operators.at(i)->setAvailability(AvailableOperator::Available);\n }\n\n emit selectionCompleted(true, QString(\"\"));\n}\n\nvoid NetworkRegistration::queryAvailableOperators()\n{\n for(int i=0; i<names.size(); ++i)\n this->addOperator(names.at(i), mncs.at(i), mccs.at(i), availabilities.at(i));\n\n if(success)\n emit availableOperators(true, operators, QString(\"\"));\n else\n emit availableOperators(false, operators, QString(\"empty\"));\n}\n\nvoid NetworkRegistration::addOperator(const QString &name, const QString &mnc, const QString &mcc, AvailableOperator::Availability availability)\n{\n operators << new AvailableOperator(mnc, mcc, name, availability);\n}\n\nvoid NetworkRegistration::setQuerySuccess(bool success)\n{\n this->success = success;\n}\n\n}\n<commit_msg>remove needless lines<commit_after>#include \"networkregistrationstub.h\"\n\n#include <QStringList>\n#include <QDebug>\n\nnamespace Cellular\n{\n\nstatic NetworkRegistration::Mode currentMode = NetworkRegistration::Automatic;\n\nAvailableOperator::AvailableOperator(const QString &mnc, const QString &mcc, const QString &name,\n AvailableOperator::Availability availability, QObject *parent) :\n QObject(parent)\n{\n setMnc(mnc);\n setMcc(mcc);\n setName(name);\n setAvailability(availability);\n}\n\nAvailableOperator::~AvailableOperator()\n{\n}\n\nvoid AvailableOperator::setMnc(const QString &mnc)\n{\n currentMnc = mnc;\n}\n\nvoid AvailableOperator::setMcc(const QString &mcc)\n{\n currentMcc = mcc;\n}\n\nvoid AvailableOperator::setName(const QString &name)\n{\n currentName = name;\n}\n\nvoid AvailableOperator::setAvailability(AvailableOperator::Availability availability)\n{\n currentAvailibility = availability;\n}\n\nQString AvailableOperator::mnc() const\n{\n return currentMnc;\n}\n\nQString AvailableOperator::mcc() const\n{\n return currentMcc;\n}\n\nQString AvailableOperator::name() const\n{\n return currentName;\n}\n\nAvailableOperator::Availability AvailableOperator::availability() const\n{\n return currentAvailibility;\n}\n\nNetworkRegistration::NetworkRegistration(QObject *parent) :\n QObject(parent), \n success(true),\n networkOperator(NULL)\n{\n}\n\nNetworkRegistration::~NetworkRegistration()\n{\n for(int i=0; i<operators.size(); ++i) {\n AvailableOperator *oper = operators.at(i);\n delete oper;\n oper = NULL;\n }\n}\n\nvoid NetworkRegistration::init(NetworkOperator *networkOperator)\n{\n this->networkOperator = networkOperator;\n}\n\nNetworkRegistration::Mode NetworkRegistration::mode() const\n{\n return currentMode;\n}\n\nvoid NetworkRegistration::selectOperator()\n{\n currentMode = NetworkRegistration::Automatic; \n emit selectionCompleted(true, QString(\"\"));\n}\n\nvoid NetworkRegistration::selectOperator(const QString &mnc, const QString &mcc)\n{\n currentMode = NetworkRegistration::Manual;\n for(int i=0; i<operators.size(); ++i) { \n if(operators.at(i)->mnc() == mnc && operators.at(i)->mcc() == mcc) {\n operators.at(i)->setAvailability(AvailableOperator::Current);\n if(networkOperator != NULL) {\n networkOperator->setName(operators.at(i)->name());\n networkOperator->setMnc(operators.at(i)->mnc());\n networkOperator->setMcc(operators.at(i)->mcc());\n }\n }\n else\n operators.at(i)->setAvailability(AvailableOperator::Available);\n }\n\n emit selectionCompleted(true, QString(\"\"));\n}\n\nvoid NetworkRegistration::queryAvailableOperators()\n{ \n if(success)\n emit availableOperators(true, operators, QString(\"\"));\n else\n emit availableOperators(false, operators, QString(\"empty\"));\n}\n\nvoid NetworkRegistration::addOperator(const QString &name, const QString &mnc, const QString &mcc, AvailableOperator::Availability availability)\n{\n operators << new AvailableOperator(mnc, mcc, name, availability);\n}\n\nvoid NetworkRegistration::setQuerySuccess(bool success)\n{\n this->success = success;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: test_getopt.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 03:50:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef SOLARIS\n#include <sys\/time.h>\n#endif\n\n#ifdef WNT\n\/\/ #define UNDER_WINDOWS_DEBUGGING\n\/\/ Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.\n#ifdef UNDER_WINDOWS_DEBUGGING\n#include <tools\/presys.h>\n#include <windows.h>\n#include <tools\/postsys.h>\n\n#define VCL_NEED_BASETSD\n\n#endif \/* UNDER_WINDOWS_DEBUGGING *\/\n#endif \/* WNT *\/\n\n#include <iostream>\n#include <vector>\n\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n\n#include \"filehelper.hxx\"\n#include \"getopt.hxx\"\n\n\/\/ #include <osl\/time.h>\n\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\n\/**\n * display usage screen\n *\/\n\nvoid usage()\n{\n fprintf( stdout,\n \"USAGE: testshl shlname [-boom][-verbose][-log][-his][-msg]\\n\" );\n exit(0);\n}\n\n\/\/ ----------------------------------- Main -----------------------------------\n#if (defined UNX) || (defined OS2)\nint main( int argc, char* argv[] )\n#else\nint _cdecl main( int argc, char* argv[] )\n#endif\n{\n static char* optionSet[] = {\n \"-boom, stop near error position, exception only\",\n \"-mode=s, the output mode, emacs, xml, old. Default is -mode old\",\n \"-logPath=s, destination path for logging\",\n \"-tc=s@, name(s) of testcase(s) to generate\",\n \"-h:s, display help or help on option\",\n \"-help:s, see -h\",\n NULL\n };\n\n GetOpt opt( argv, optionSet );\n\n \/\/ someone indicates that he needs help\n if ( opt.hasOpt( \"-h\" ) || opt.hasOpt( \"-help\" ) )\n {\n opt.showUsage();\n \/\/ exit(0);\n }\n\n \/\/ get path for logging stuff..\n rtl::OString logPth;\n \/\/ ...if available\n if ( opt.hasOpt( \"-logPth\" ))\n {\n logPth = opt.getOpt( \"-logPth\" );\n }\n\n rtl::OString param;\n if ( ! opt.getParams().empty() ) {\n param = opt.getFirstParam();\n\n std::cout << \"all non '-' Parameter values\" << std::endl;\n\n vector<rtl::OString>& aVec = opt.getParams();\n for(vector<rtl::OString>::const_iterator it = aVec.begin();\n it != aVec.end();\n ++it)\n {\n std::cout << (*it).getStr() << std::endl;\n }\n }\n\n if ( opt.hasOpt(\"-tc\"))\n {\n std::cout << \"Parameter -tc\" << std::endl;\n vector<rtl::OString>& aVec = opt.getOptVec( \"-tc\" );\n\n for(vector<rtl::OString>::const_iterator it = aVec.begin();\n it != aVec.end();\n ++it)\n {\n std::cout << (*it).getStr() << std::endl;\n }\n }\n\n return 0;\n}\n\n<commit_msg>INTEGRATION: CWS rpt23fix02 (1.3.24); FILE MERGED 2007\/07\/23 11:15:59 lla 1.3.24.1: #i79902# make demos buildable<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: test_getopt.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2007-08-03 10:17:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef SOLARIS\n#include <sys\/time.h>\n#endif\n\n#ifdef WNT\n\/\/ #define UNDER_WINDOWS_DEBUGGING\n\/\/ Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.\n#ifdef UNDER_WINDOWS_DEBUGGING\n#include <tools\/presys.h>\n#include <windows.h>\n#include <tools\/postsys.h>\n\n#define VCL_NEED_BASETSD\n\n#endif \/* UNDER_WINDOWS_DEBUGGING *\/\n#endif \/* WNT *\/\n\n#include <iostream>\n#include <vector>\n\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n\n#include \"filehelper.hxx\"\n#include \"getopt.hxx\"\n\n\/\/ #include <osl\/time.h>\n\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\n\/**\n * display usage screen\n *\/\n\nvoid usage()\n{\n fprintf( stdout,\n \"USAGE: testshl shlname [-boom][-verbose][-log][-his][-msg]\\n\" );\n exit(0);\n}\n\n\/\/ ----------------------------------- Main -----------------------------------\n#if (defined UNX) || (defined OS2)\nint main( int argc, char* argv[] )\n#else\nint _cdecl main( int argc, char* argv[] )\n#endif\n{\n (void) argc;\n static char const* optionSet[] = {\n \"-boom, stop near error position, exception only\",\n \"-mode=s, the output mode, emacs, xml, old. Default is -mode old\",\n \"-logPath=s, destination path for logging\",\n \"-tc=s@, name(s) of testcase(s) to generate\",\n \"-h:s, display help or help on option\",\n \"-help:s, see -h\",\n NULL\n };\n\n GetOpt opt( argv, optionSet );\n\n \/\/ someone indicates that he needs help\n if ( opt.hasOpt( \"-h\" ) || opt.hasOpt( \"-help\" ) )\n {\n opt.showUsage();\n \/\/ exit(0);\n }\n\n \/\/ get path for logging stuff..\n rtl::OString logPth;\n \/\/ ...if available\n if ( opt.hasOpt( \"-logPth\" ))\n {\n logPth = opt.getOpt( \"-logPth\" );\n }\n\n rtl::OString param;\n if ( ! opt.getParams().empty() ) {\n param = opt.getFirstParam();\n\n std::cout << \"all non '-' Parameter values\" << std::endl;\n\n vector<rtl::OString>& aVec = opt.getParams();\n for(vector<rtl::OString>::const_iterator it = aVec.begin();\n it != aVec.end();\n ++it)\n {\n std::cout << (*it).getStr() << std::endl;\n }\n }\n\n if ( opt.hasOpt(\"-tc\"))\n {\n std::cout << \"Parameter -tc\" << std::endl;\n vector<rtl::OString>& aVec = opt.getOptVec( \"-tc\" );\n\n for(vector<rtl::OString>::const_iterator it = aVec.begin();\n it != aVec.end();\n ++it)\n {\n std::cout << (*it).getStr() << std::endl;\n }\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2008, Massachusetts Institute of Technology \/\/\n\/\/ Copyright (c) 2013, Giulio Paci <giuliopaci@gmail.com> \/\/\n\/\/ All rights reserved. \/\/\n\/\/ \/\/\n\/\/ Redistribution and use in source and binary forms, with or without \/\/\n\/\/ modification, are permitted provided that the following conditions are \/\/\n\/\/ met: \/\/\n\/\/ \/\/\n\/\/ * Redistributions of source code must retain the above copyright \/\/\n\/\/ notice, this list of conditions and the following disclaimer. \/\/\n\/\/ \/\/\n\/\/ * Redistributions in binary form must reproduce the above \/\/\n\/\/ copyright notice, this list of conditions and the following \/\/\n\/\/ disclaimer in the documentation and\/or other materials provided \/\/\n\/\/ with the distribution. \/\/\n\/\/ \/\/\n\/\/ * Neither the name of the Massachusetts Institute of Technology \/\/\n\/\/ nor the names of its contributors may be used to endorse or \/\/\n\/\/ promote products derived from this software without specific \/\/\n\/\/ prior written permission. \/\/\n\/\/ \/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \/\/\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \/\/\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR \/\/\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \/\/\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \/\/\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \/\/\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \/\/\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \/\/\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \/\/\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \/\/\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Logger.h\"\n#include \"RefCounter.h\"\n\nnamespace mitlm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n_RefCounter RefCounter;\n\n_RefCounter::~_RefCounter() {\n if (!_map.empty()) {\n Logger::Error(1, \"-- RefCounter----------\\n\");\n\tunordered_map<unsigned long, int>::const_iterator it;\n for (it = _map.begin(); it != _map.end(); ++it)\n Logger::Error(1, \"map[%p] = %i\\n\", (void *)it->first, it->second);\n Logger::Error(1, \"-----------------------\\n\\n\");\n }\n}\n\n}\n<commit_msg>Change unsigned long to const void* in RefCounter.cpp.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2008, Massachusetts Institute of Technology \/\/\n\/\/ Copyright (c) 2013, Giulio Paci <giuliopaci@gmail.com> \/\/\n\/\/ All rights reserved. \/\/\n\/\/ \/\/\n\/\/ Redistribution and use in source and binary forms, with or without \/\/\n\/\/ modification, are permitted provided that the following conditions are \/\/\n\/\/ met: \/\/\n\/\/ \/\/\n\/\/ * Redistributions of source code must retain the above copyright \/\/\n\/\/ notice, this list of conditions and the following disclaimer. \/\/\n\/\/ \/\/\n\/\/ * Redistributions in binary form must reproduce the above \/\/\n\/\/ copyright notice, this list of conditions and the following \/\/\n\/\/ disclaimer in the documentation and\/or other materials provided \/\/\n\/\/ with the distribution. \/\/\n\/\/ \/\/\n\/\/ * Neither the name of the Massachusetts Institute of Technology \/\/\n\/\/ nor the names of its contributors may be used to endorse or \/\/\n\/\/ promote products derived from this software without specific \/\/\n\/\/ prior written permission. \/\/\n\/\/ \/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \/\/\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \/\/\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR \/\/\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \/\/\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \/\/\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \/\/\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \/\/\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \/\/\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \/\/\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \/\/\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Logger.h\"\n#include \"RefCounter.h\"\n\nnamespace mitlm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n_RefCounter RefCounter;\n\n_RefCounter::~_RefCounter() {\n if (!_map.empty()) {\n Logger::Error(1, \"-- RefCounter----------\\n\");\n\tunordered_map<const void*, int>::const_iterator it;\n for (it = _map.begin(); it != _map.end(); ++it)\n Logger::Error(1, \"map[%p] = %i\\n\", (void *)it->first, it->second);\n Logger::Error(1, \"-----------------------\\n\\n\");\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2016 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util_debug.h\"\n\n#include <stdlib.h>\n\n#include \"util_logging.h\"\n#include \"util_string.h\"\n\nCCL_NAMESPACE_BEGIN\n\nDebugFlags::CPU::CPU()\n : avx2(true),\n avx(true),\n sse41(true),\n sse3(true),\n sse2(true)\n{\n\treset();\n}\n\nvoid DebugFlags::CPU::reset()\n{\n#define STRINGIFY(x) #x\n#define CHECK_CPU_FLAGS(flag, env) \\\n\tdo { \\\n\t\tflag = (getenv(env) == NULL); \\\n\t\tif(!flag) { \\\n\t\t\tVLOG(1) << \"Disabling \" << STRINGIFY(flag) << \" instruction set.\"; \\\n\t\t} \\\n\t} while(0)\n\n\tCHECK_CPU_FLAGS(avx2, \"CYCLES_CPU_NO_AVX2\");\n\tCHECK_CPU_FLAGS(avx, \"CYCLES_CPU_NO_AVX\");\n\tCHECK_CPU_FLAGS(sse41, \"CYCLES_CPU_NO_SSE41\");\n\tCHECK_CPU_FLAGS(sse3, \"CYCLES_CPU_NO_SSE3\");\n\tCHECK_CPU_FLAGS(sse2, \"CYCLES_CPU_NO_SSE2\");\n\n#undef STRINGIFY\n#undef CHECK_CPU_FLAGS\n}\n\nDebugFlags::OpenCL::OpenCL()\n : device_type(DebugFlags::OpenCL::DEVICE_ALL),\n kernel_type(DebugFlags::OpenCL::KERNEL_DEFAULT),\n debug(false)\n{\n\treset();\n}\n\nvoid DebugFlags::OpenCL::reset()\n{\n\t\/* Initialize device type from environment variables. *\/\n\tdevice_type = DebugFlags::OpenCL::DEVICE_ALL;\n\tchar *device = getenv(\"CYCLES_OPENCL_TEST\");\n\tif(device) {\n\t\tif(strcmp(device, \"NONE\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_NONE;\n\t\t}\n\t\telse if(strcmp(device, \"ALL\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_ALL;\n\t\t}\n\t\telse if(strcmp(device, \"DEFAULT\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_DEFAULT;\n\t\t}\n\t\telse if(strcmp(device, \"CPU\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_CPU;\n\t\t}\n\t\telse if(strcmp(device, \"GPU\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_GPU;\n\t\t}\n\t\telse if(strcmp(device, \"ACCELERATOR\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;\n\t\t}\n\t}\n\t\/* Initialize kernel type from environment variables. *\/\n\tkernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;\n\tif(getenv(\"CYCLES_OPENCL_MEGA_KERNEL_TEST\") != NULL) {\n\t\tkernel_type = DebugFlags::OpenCL::KERNEL_MEGA;\n\t}\n\telse if(getenv(\"CYCLES_OPENCL_SPLITKERNEL_TEST\") != NULL) {\n\t\tkernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;\n\t}\n\t\/* Initialize other flags from environment variables. *\/\n\tdebug = (getenv(\"CYCLES_OPENCL_DEBUG\") != NULL);\n}\n\nDebugFlags::DebugFlags()\n{\n\t\/* Nothing for now. *\/\n}\n\nvoid DebugFlags::reset()\n{\n\tcpu.reset();\n\topencl.reset();\n}\n\nstd::ostream& operator <<(std::ostream &os,\n const DebugFlagsRef debug_flags)\n{\n\tos << \"CPU flags:\\n\"\n\t << \" AVX2 : \" << string_from_bool(debug_flags.cpu.avx2) << \"\\n\"\n\t << \" AVX : \" << string_from_bool(debug_flags.cpu.avx) << \"\\n\"\n\t << \" SSE4.1 : \" << string_from_bool(debug_flags.cpu.sse41) << \"\\n\"\n\t << \" SSE3 : \" << string_from_bool(debug_flags.cpu.sse3) << \"\\n\"\n\t << \" SSE2 : \" << string_from_bool(debug_flags.cpu.sse2) << \"\\n\";\n\n\tconst char *opencl_device_type,\n\t *opencl_kernel_type;\n\tswitch(debug_flags.opencl.device_type) {\n\t\tcase DebugFlags::OpenCL::DEVICE_NONE:\n\t\t\topencl_device_type = \"NONE\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_ALL:\n\t\t\topencl_device_type = \"ALL\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_DEFAULT:\n\t\t\topencl_device_type = \"DEFAULT\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_CPU:\n\t\t\topencl_device_type = \"CPU\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_GPU:\n\t\t\topencl_device_type = \"GPU\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_ACCELERATOR:\n\t\t\topencl_device_type = \"ACCELERATOR\";\n\t\t\tbreak;\n\t}\n\tswitch(debug_flags.opencl.kernel_type) {\n\t\tcase DebugFlags::OpenCL::KERNEL_DEFAULT:\n\t\t\topencl_kernel_type = \"DEFAULT\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::KERNEL_MEGA:\n\t\t\topencl_kernel_type = \"MEGA\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::KERNEL_SPLIT:\n\t\t\topencl_kernel_type = \"SPLIT\";\n\t\t\tbreak;\n\t}\n\tos << \"OpenCL flags:\\n\"\n\t << \" Device type : \" << opencl_device_type << \"\\n\"\n\t << \" Kernel type : \" << opencl_kernel_type << \"\\n\"\n\t << \" Debug : \" << string_from_bool(debug_flags.opencl.debug)\n\t << \"\\n\";\n\treturn os;\n}\n\nCCL_NAMESPACE_END\n<commit_msg>One more attempt to fix issue mentioned in previous commit<commit_after>\/*\n * Copyright 2011-2016 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util_debug.h\"\n\n#include <stdlib.h>\n\n#include \"util_logging.h\"\n#include \"util_string.h\"\n\nCCL_NAMESPACE_BEGIN\n\nDebugFlags::CPU::CPU()\n : avx2(true),\n avx(true),\n sse41(true),\n sse3(true),\n sse2(true)\n{\n\treset();\n}\n\nvoid DebugFlags::CPU::reset()\n{\n#define STRINGIFY(x) #x\n#define CHECK_CPU_FLAGS(flag, env) \\\n\tdo { \\\n\t\tflag = (getenv(env) == NULL); \\\n\t\tif(!flag) { \\\n\t\t\tVLOG(1) << \"Disabling \" << STRINGIFY(flag) << \" instruction set.\"; \\\n\t\t} \\\n\t} while(0)\n\n\tCHECK_CPU_FLAGS(avx2, \"CYCLES_CPU_NO_AVX2\");\n\tCHECK_CPU_FLAGS(avx, \"CYCLES_CPU_NO_AVX\");\n\tCHECK_CPU_FLAGS(sse41, \"CYCLES_CPU_NO_SSE41\");\n\tCHECK_CPU_FLAGS(sse3, \"CYCLES_CPU_NO_SSE3\");\n\tCHECK_CPU_FLAGS(sse2, \"CYCLES_CPU_NO_SSE2\");\n\n#undef STRINGIFY\n#undef CHECK_CPU_FLAGS\n}\n\nDebugFlags::OpenCL::OpenCL()\n : device_type(DebugFlags::OpenCL::DEVICE_ALL),\n kernel_type(DebugFlags::OpenCL::KERNEL_DEFAULT),\n debug(false)\n{\n\treset();\n}\n\nvoid DebugFlags::OpenCL::reset()\n{\n\t\/* Initialize device type from environment variables. *\/\n\tdevice_type = DebugFlags::OpenCL::DEVICE_ALL;\n\tchar *device = getenv(\"CYCLES_OPENCL_TEST\");\n\tif(device) {\n\t\tif(strcmp(device, \"NONE\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_NONE;\n\t\t}\n\t\telse if(strcmp(device, \"ALL\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_ALL;\n\t\t}\n\t\telse if(strcmp(device, \"DEFAULT\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_DEFAULT;\n\t\t}\n\t\telse if(strcmp(device, \"CPU\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_CPU;\n\t\t}\n\t\telse if(strcmp(device, \"GPU\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_GPU;\n\t\t}\n\t\telse if(strcmp(device, \"ACCELERATOR\") == 0) {\n\t\t\tdevice_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;\n\t\t}\n\t}\n\t\/* Initialize kernel type from environment variables. *\/\n\tkernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;\n\tif(getenv(\"CYCLES_OPENCL_MEGA_KERNEL_TEST\") != NULL) {\n\t\tkernel_type = DebugFlags::OpenCL::KERNEL_MEGA;\n\t}\n\telse if(getenv(\"CYCLES_OPENCL_SPLIT_KERNEL_TEST\") != NULL) {\n\t\tkernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;\n\t}\n\t\/* Initialize other flags from environment variables. *\/\n\tdebug = (getenv(\"CYCLES_OPENCL_DEBUG\") != NULL);\n}\n\nDebugFlags::DebugFlags()\n{\n\t\/* Nothing for now. *\/\n}\n\nvoid DebugFlags::reset()\n{\n\tcpu.reset();\n\topencl.reset();\n}\n\nstd::ostream& operator <<(std::ostream &os,\n const DebugFlagsRef debug_flags)\n{\n\tos << \"CPU flags:\\n\"\n\t << \" AVX2 : \" << string_from_bool(debug_flags.cpu.avx2) << \"\\n\"\n\t << \" AVX : \" << string_from_bool(debug_flags.cpu.avx) << \"\\n\"\n\t << \" SSE4.1 : \" << string_from_bool(debug_flags.cpu.sse41) << \"\\n\"\n\t << \" SSE3 : \" << string_from_bool(debug_flags.cpu.sse3) << \"\\n\"\n\t << \" SSE2 : \" << string_from_bool(debug_flags.cpu.sse2) << \"\\n\";\n\n\tconst char *opencl_device_type,\n\t *opencl_kernel_type;\n\tswitch(debug_flags.opencl.device_type) {\n\t\tcase DebugFlags::OpenCL::DEVICE_NONE:\n\t\t\topencl_device_type = \"NONE\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_ALL:\n\t\t\topencl_device_type = \"ALL\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_DEFAULT:\n\t\t\topencl_device_type = \"DEFAULT\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_CPU:\n\t\t\topencl_device_type = \"CPU\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_GPU:\n\t\t\topencl_device_type = \"GPU\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::DEVICE_ACCELERATOR:\n\t\t\topencl_device_type = \"ACCELERATOR\";\n\t\t\tbreak;\n\t}\n\tswitch(debug_flags.opencl.kernel_type) {\n\t\tcase DebugFlags::OpenCL::KERNEL_DEFAULT:\n\t\t\topencl_kernel_type = \"DEFAULT\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::KERNEL_MEGA:\n\t\t\topencl_kernel_type = \"MEGA\";\n\t\t\tbreak;\n\t\tcase DebugFlags::OpenCL::KERNEL_SPLIT:\n\t\t\topencl_kernel_type = \"SPLIT\";\n\t\t\tbreak;\n\t}\n\tos << \"OpenCL flags:\\n\"\n\t << \" Device type : \" << opencl_device_type << \"\\n\"\n\t << \" Kernel type : \" << opencl_kernel_type << \"\\n\"\n\t << \" Debug : \" << string_from_bool(debug_flags.opencl.debug)\n\t << \"\\n\";\n\treturn os;\n}\n\nCCL_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2017 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n * Alexandre Fernandez <nerf@boboop.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Directory.h\"\n\n#include <cstring>\n#include <stdexcept>\n#include <system_error>\n\n#ifdef _WIN32\n# include <windows.h>\n#else\n# include <cerrno>\n# include <sys\/types.h>\n# include <sys\/stat.h>\n#endif\n\nnamespace medialibrary\n{\n\nnamespace utils\n{\n\nnamespace fs\n{\n\nnamespace\n{\n const auto ERR_FS_OBJECT_ACCESS = \"Error accessing file-system object at \";\n}\n\nbool isDirectory( const std::string& path )\n{\n#ifdef _WIN32\n auto attr = GetFileAttributes( path.c_str() );\n if ( attr == INVALID_FILE_ATTRIBUTES )\n {\n DWORD errVal = GetLastError();\n std::error_code ec( errVal, std::system_category() );\n throw std::system_error( ec, ERR_FS_OBJECT_ACCESS + path );\n }\n return attr & FILE_ATTRIBUTE_DIRECTORY;\n#else\n struct stat s;\n if ( lstat( path.c_str(), &s ) != 0 )\n throw std::system_error( errno, std::system_category(), ERR_FS_OBJECT_ACCESS + path );\n return S_ISDIR( s.st_mode );\n#endif\n}\n\n}\n\n}\n\n}<commit_msg>utils: Fix win32 build<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2017 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n * Alexandre Fernandez <nerf@boboop.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Directory.h\"\n\n#include <cstring>\n#include <stdexcept>\n#include <system_error>\n\n#ifdef _WIN32\n# include <windows.h>\n#else\n# include <cerrno>\n# include <sys\/types.h>\n# include <sys\/stat.h>\n#endif\n\nnamespace medialibrary\n{\n\nnamespace utils\n{\n\nnamespace fs\n{\n\nnamespace\n{\n const auto ERR_FS_OBJECT_ACCESS = \"Error accessing file-system object at \";\n}\n\nbool isDirectory( const std::string& path )\n{\n#ifdef _WIN32\n auto wpath = charset::ToWide( path.c_str() );\n auto attr = GetFileAttributes( wpath.get() );\n if ( attr == INVALID_FILE_ATTRIBUTES )\n {\n DWORD errVal = GetLastError();\n std::error_code ec( errVal, std::system_category() );\n throw std::system_error( ec, ERR_FS_OBJECT_ACCESS + path );\n }\n return attr & FILE_ATTRIBUTE_DIRECTORY;\n#else\n struct stat s;\n if ( lstat( path.c_str(), &s ) != 0 )\n throw std::system_error( errno, std::system_category(), ERR_FS_OBJECT_ACCESS + path );\n return S_ISDIR( s.st_mode );\n#endif\n}\n\n}\n\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\n#include <ionCore.h>\n#include <catch.hpp>\n\n\nclass Component\n{};\n\nclass AComponent : public Component\n{};\n\nclass BComponent : public Component\n{};\n\nclass CComponent : public AComponent\n{};\n\nTEST_CASE(\"IEntity::AddComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(B == Entity->AddComponent(B));\n\tREQUIRE(C == Entity->AddComponent(C));\n\tREQUIRE(A2 == Entity->AddComponent(A2));\n}\n\nTEST_CASE(\"IEntity::GetComponentCount\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(B);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(C);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n\tEntity->AddComponent(A2);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 3);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n}\n<commit_msg>Finish ionComponent tests<commit_after>\n#include <ionCore.h>\n#include <catch.hpp>\n\n\nclass Component\n{};\n\nclass AComponent : public Component\n{\npublic:\n\tbool foo()\n\t{\n\t\treturn true;\n\t}\n};\n\nclass BComponent : public Component\n{};\n\nclass CComponent : public AComponent\n{};\n\nTEST_CASE(\"IEntity::AddComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(B == Entity->AddComponent(B));\n\tREQUIRE(C == Entity->AddComponent(C));\n\tREQUIRE(A2 == Entity->AddComponent(A2));\n}\n\nTEST_CASE(\"IEntity::GetComponentCount\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(B);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(C);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n\tEntity->AddComponent(A2);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 3);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n}\n\ntemplate <typename TComponent>\nbool CheckRangeEquals(pair<typename multimap<Type, TComponent *>::iterator, typename multimap<Type, TComponent *>::iterator> const Iterators, std::initializer_list<TComponent *> const & List)\n{\n\tauto it = Iterators.first;\n\tauto jt = List.begin();\n\tfor (; it != Iterators.second && jt != List.end(); ++ it, ++ jt)\n\t{\n\t\tif (it->second != *jt)\n\t\t\treturn false;\n\t}\n\n\tif (it != Iterators.second || jt != List.end())\n\t\treturn false;\n\n\treturn true;\n}\n\nTEST_CASE(\"IEntity::GetComponents\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));\n\tEntity->AddComponent(A);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));\n\tEntity->AddComponent(A);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));\n\tEntity->AddComponent(B);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));\n\tEntity->AddComponent(C);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {C}));\n\tEntity->AddComponent(A2);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A, A2}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {C}));\n}\n\nTEST_CASE(\"IEntity::ExpectSingleComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent(), * ATest = nullptr;\n\tBComponent * B = new BComponent(), * BTest = nullptr;\n\tCComponent * C = new CComponent(), * CTest = nullptr;\n\tAComponent * A2 = new CComponent(), * A2Test = nullptr;\n\n\tREQUIRE(Entity->ExpectSingleComponent(ATest) == 0);\n\tREQUIRE(! ATest);\n\tREQUIRE(Entity->ExpectSingleComponent(BTest) == 0);\n\tREQUIRE(! BTest);\n\tREQUIRE(Entity->ExpectSingleComponent(CTest) == 0);\n\tREQUIRE(! CTest);\n\n\tEntity->AddComponent(A);\n\n\tREQUIRE(Entity->ExpectSingleComponent(ATest) == 1);\n\tREQUIRE(ATest == A);\n\tREQUIRE(Entity->ExpectSingleComponent(BTest) == 0);\n\tREQUIRE(! BTest);\n\tREQUIRE(Entity->ExpectSingleComponent(CTest) == 0);\n\tREQUIRE(! CTest);\n\n\tEntity->AddComponent(A);\n\tATest = nullptr;\n\n\tREQUIRE(Entity->ExpectSingleComponent(ATest) == 2);\n\tREQUIRE(ATest == A);\n\tREQUIRE(Entity->ExpectSingleComponent(BTest) == 0);\n\tREQUIRE(! BTest);\n\tREQUIRE(Entity->ExpectSingleComponent(CTest) == 0);\n\tREQUIRE(! CTest);\n\n\tEntity->AddComponent(B);\n\tEntity->AddComponent(C);\n\tEntity->AddComponent(A2);\n\tATest = nullptr;\n\n\tREQUIRE(Entity->ExpectSingleComponent(ATest) == 3);\n\tREQUIRE(ATest == A);\n\tREQUIRE(Entity->ExpectSingleComponent(BTest) == 1);\n\tREQUIRE(BTest == B);\n\tREQUIRE(Entity->ExpectSingleComponent(CTest) == 1);\n\tREQUIRE(CTest == C);\n}\n\nTEST_CASE(\"IEntity::RequireSingleComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * ATest = nullptr;\n\tBComponent * BTest = nullptr;\n\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 0);\n\tATest = Entity->RequireSingleComponent<AComponent>();\n\tREQUIRE(ATest);\n\tREQUIRE(ATest->foo());\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));\n\tREQUIRE(ATest == Entity->RequireSingleComponent<AComponent>());\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));\n\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tBTest = Entity->RequireSingleComponent<BComponent>();\n\tREQUIRE(BTest);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {BTest}));\n\tREQUIRE(BTest == Entity->RequireSingleComponent<BComponent>());\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));\n\tREQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {BTest}));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include <iostream>\n#include <stdio.h>\n#include \"nameserver\/logdb.h\"\n\nnamespace baidu {\nnamespace bfs {\n\nvoid DumpMarker(char* path) {\n FILE* fp = fopen(path, \"r\");\n MarkerEntry mark;\n std::string data;\n int64_t v;\n while (true) {\n int ret = LogDB::ReadOne(fp, &data);\n if (ret == 0) break;\n if (ret < 0) {\n std::cerr << \"DumpMarker failed while reading\" << std::endl;\n return;\n }\n LogDB::DecodeMarker(data, &mark);\n memcpy(&v, &(mark.value[0]), 8);\n std::cout << mark.key << \"\\t->\\t\" << v << \" ---- \" << mark.value << std::endl;\n }\n fclose(fp);\n}\n\nvoid DumpLog(char* path) {\n FILE* fp = fopen(path, \"r\");\n std::string data;\n int64_t i = 0;\n while (true) {\n int ret = LogDB::ReadOne(fp, &data);\n if(ret == 0) break;\n if(ret < 0 ) {\n std::cerr << \"DumpLog failed while reading\" << std::endl;\n return;\n }\n std::cout << i << \"\\t->\\t\" << data << std::endl;\n ++i;\n }\n fclose(fp);\n}\n\nvoid DumpIdx(char* path) {\n FILE* fp = fopen(path, \"r\");\n char buf[16];\n int64_t index, offset;\n while (true) {\n int ret = fread(buf, 1, 16, fp);\n if (ret == 0) break;\n if (ret < 0) {\n std::cerr << \"DumpIdx failed while reading\" << std::endl;\n return;\n }\n memcpy(&index, buf, 8);\n memcpy(&offset, buf + 8, 8);\n std::cout << index << \"\\t->\\t\" << offset << std::endl;\n }\n fclose(fp);\n}\n\n} \/\/ namespace bfs\n} \/\/ namespace baidu\n\nint main(int argc, char* argv[]) {\n std::string path(argv[1]);\n if (path.find(\".mak\") != std::string::npos || \"marker.tmp\" == path) {\n baidu::bfs::DumpMarker(argv[1]);\n } else if (path.find(\".log\") != std::string::npos) {\n baidu::bfs::DumpLog(argv[1]);\n } else if (path.find(\".idx\") != std::string::npos) {\n baidu::bfs::DumpIdx(argv[1]);\n }\n}\n<commit_msg>add performance test in logdb_dump<commit_after>\/\/ Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include <iostream>\n#include <stdio.h>\n\n#include <common\/timer.h>\n#include <common\/thread.h>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/bind.hpp>\n#include \"nameserver\/logdb.h\"\n\nnamespace baidu {\nnamespace bfs {\n\nvoid DumpMarker(char* path) {\n FILE* fp = fopen(path, \"r\");\n MarkerEntry mark;\n std::string data;\n int64_t v;\n while (true) {\n int ret = LogDB::ReadOne(fp, &data);\n if (ret == 0) break;\n if (ret < 0) {\n std::cerr << \"DumpMarker failed while reading\" << std::endl;\n return;\n }\n LogDB::DecodeMarker(data, &mark);\n memcpy(&v, &(mark.value[0]), 8);\n std::cout << mark.key << \"\\t->\\t\" << v << \" ---- \" << mark.value << std::endl;\n }\n fclose(fp);\n}\n\nvoid DumpLog(char* path) {\n FILE* fp = fopen(path, \"r\");\n std::string data;\n int64_t i = 0;\n while (true) {\n int ret = LogDB::ReadOne(fp, &data);\n if(ret == 0) break;\n if(ret < 0 ) {\n std::cerr << \"DumpLog failed while reading\" << std::endl;\n return;\n }\n std::cout << i << \"\\t->\\t\" << data << std::endl;\n ++i;\n }\n fclose(fp);\n}\n\nvoid DumpIdx(char* path) {\n FILE* fp = fopen(path, \"r\");\n char buf[16];\n int64_t index, offset;\n while (true) {\n int ret = fread(buf, 1, 16, fp);\n if (ret == 0) break;\n if (ret < 0) {\n std::cerr << \"DumpIdx failed while reading\" << std::endl;\n return;\n }\n memcpy(&index, buf, 8);\n memcpy(&offset, buf + 8, 8);\n std::cout << index << \"\\t->\\t\" << offset << std::endl;\n }\n fclose(fp);\n}\n\nvoid WriteHelper(int start, int end, const std::string& str, LogDB* logdb) {\n for (int i = start; i < end; ++i) {\n logdb->Write(i, str);\n }\n std::cerr << common::timer::get_micros() << std::endl;\n}\n\nvoid ReadHelper(int start, int end, const std::string& str, LogDB* logdb) {\n std::string res;\n for (int i = start; i < end; ++i) {\n logdb->Read(i, &res);\n assert(res == str);\n }\n std::cerr << common::timer::get_micros() << std::endl;\n}\n\nvoid Test(int n, int l) {\n LogDB* logdb;\n LogDB::Open(\".\/dbtest\", DBOption(), &logdb);\n\n int64_t start = common::timer::get_micros();\n std::string str(l, 'a');\n WriteHelper(0, n, str, logdb);\n int64_t now = common::timer::get_micros();\n double rate = double(n) \/ double(now - start);\n std::cerr << rate * 1000000.0 << std::endl;\n\n start = common::timer::get_micros();\n common::Thread w;\n w.Start(boost::bind(&WriteHelper, n, n + n, str, logdb));\n common::Thread r;\n r.Start(boost::bind(&ReadHelper, 0, n, str, logdb));\n w.Join();\n r.Join();\n now = common::timer::get_micros();\n rate = double(n) \/ double(now - start);\n std::cerr << rate * 1000000.0 << std::endl;\n\n \/\/system(\"rm -rf .\/dbtest\");\n}\n\n} \/\/ namespace bfs\n} \/\/ namespace baidu\n\nint main(int argc, char* argv[]) {\n std::string path(argv[1]);\n if (path.find(\".mak\") != std::string::npos || \"marker.tmp\" == path) {\n baidu::bfs::DumpMarker(argv[1]);\n } else if (path.find(\".log\") != std::string::npos) {\n baidu::bfs::DumpLog(argv[1]);\n } else if (path.find(\".idx\") != std::string::npos) {\n baidu::bfs::DumpIdx(argv[1]);\n } else if (path == \"test\") {\n std::string n(argv[2]);\n std::string l(argv[3]);\n baidu::bfs::Test(boost::lexical_cast<int>(n), boost::lexical_cast<int>(l));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"v4l2_utils.h\"\n\n#include \"v4l2_property_mapping.h\"\n#include \"utils.h\"\n#include \"logging.h\"\n\n#if HAVE_UDEV\n#include <libudev.h>\n#endif\n\n#include <glob.h>\n\n#include <vector>\n#include <algorithm>\n\nusing namespace tcam;\n\n\nuint32_t tcam::convert_v4l2_flags (uint32_t v4l2_flags)\n{\n uint32_t internal_flags = 0;\n\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_DISABLED))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_DISABLED);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_GRABBED))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_GRABBED);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_READ_ONLY))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_READ_ONLY);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_UPDATE))\n {}\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_INACTIVE))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_INACTIVE);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_SLIDER))\n {}\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_WRITE_ONLY))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_WRITE_ONLY);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_VOLATILE))\n {}\n \/\/ if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_HAS_PAYLOAD))\n \/\/ {}\n\n return internal_flags;\n}\n\n\nstatic TCAM_PROPERTY_ID find_mapping (int v4l2_id)\n{\n auto f = [v4l2_id] (int p)\n {\n if (v4l2_id == p)\n return true;\n return false;\n };\n\n for (const auto& m : v4l2_mappings)\n {\n auto match = std::find_if(m.v4l2_id.begin(), m.v4l2_id.end(), f);\n\n if (match != m.v4l2_id.end())\n return m.id;\n }\n return TCAM_PROPERTY_INVALID;\n}\n\n\nstd::shared_ptr<Property> tcam::create_property (int fd,\n struct v4l2_queryctrl* queryctrl,\n struct v4l2_ext_control* ctrl,\n std::shared_ptr<PropertyImpl> impl)\n{\n\n \/\/ assure we have the typ\n Property::VALUE_TYPE type;\n\n switch (queryctrl->type)\n {\n case V4L2_CTRL_TYPE_BOOLEAN:\n {\n type = Property::BOOLEAN;\n break;\n }\n case V4L2_CTRL_TYPE_INTEGER:\n {\n type = Property::INTEGER;\n break;\n }\n case V4L2_CTRL_TYPE_STRING:\n {\n type = Property::STRING;\n break;\n }\n case V4L2_CTRL_TYPE_INTEGER_MENU:\n {\n type = Property::ENUM;\n break;\n }\n case V4L2_CTRL_TYPE_BUTTON:\n {\n type = Property::BUTTON;\n break;\n }\n default:\n {\n type = Property::UNDEFINED;\n break;\n }\n }\n\n auto prop_id = find_mapping (ctrl->id);\n\n auto ctrl_m = get_control_reference(prop_id);\n\n TCAM_PROPERTY_TYPE type_to_use;\n tcam_device_property cp = {};\n\n if (ctrl_m.id == TCAM_PROPERTY_INVALID)\n {\n tcam_log(TCAM_LOG_WARNING, \"Unable to find std property. Passing raw property identifier through. '%s'(%x)\", (char*)queryctrl->name, queryctrl->id);\n \/\/ pass through and do not associate with anything existing\n type_to_use = value_type_to_ctrl_type(type);\n memcpy(cp.name, (char*)queryctrl->name, sizeof(cp.name));\n cp.type = value_type_to_ctrl_type(type);\n \/\/ generate id so that identfication of passed through properties is guaranteed\n cp.id = generate_unique_property_id();\n }\n else\n {\n type_to_use = ctrl_m.type_to_use;\n cp = create_empty_property(ctrl_m.id);\n }\n\n uint32_t flags = convert_v4l2_flags(queryctrl->flags);\n\n switch (type_to_use)\n {\n case TCAM_PROPERTY_TYPE_BOOLEAN:\n {\n if (queryctrl->default_value == 0)\n {\n cp.value.b.default_value = false;\n }\n else if (queryctrl->default_value > 0)\n {\n cp.value.b.default_value = true;\n }\n else\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Boolean '%s' has impossible default value: %d Setting to false\",\n cp.name,\n queryctrl->default_value);\n cp.value.b.default_value = false;\n }\n\n if (ctrl->value == 0)\n {\n cp.value.b.value = false;\n }\n else if (ctrl->value > 0)\n {\n cp.value.b.value = true;\n }\n else\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Boolean '%s' has impossible value: %d Setting to false\",\n cp.name,\n ctrl->value);\n cp.value.b.value = false;\n }\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyBoolean(impl, cp, type));\n }\n case TCAM_PROPERTY_TYPE_INTEGER:\n {\n cp.value.i.min = queryctrl->minimum;\n cp.value.i.max = queryctrl->maximum;\n cp.value.i.step = queryctrl->step;\n\n if (cp.value.i.min > cp.value.i.max)\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Range boundaries for property '%s' are faulty. Ignoring property as a precaution.\",\n cp.name);\n return nullptr;\n }\n\n if (cp.value.i.step == 0)\n {\n tcam_log(TCAM_LOG_WARNING,\n \"Detected stepsize 0 for property %s. Setting to 1.\",\n cp.name);\n\n cp.value.i.step = 1;\n }\n\n cp.value.i.default_value = queryctrl->default_value;\n cp.value.i.value = ctrl->value;\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyInteger(impl, cp, type));\n }\n \/\/ case TCAM_CTRL_TYPE_DOUBLE:\n \/\/ {\n \/\/ Does not exist in v4l2\n \/\/ }\n case TCAM_PROPERTY_TYPE_STRING:\n {\n memcpy(cp.value.s.value,(char*)queryctrl->name, sizeof(cp.value.s.value));\n memcpy(cp.value.s.default_value, (char*)queryctrl->name, sizeof(cp.value.s.default_value));\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyString(impl, cp, type));\n }\n case TCAM_PROPERTY_TYPE_ENUMERATION:\n {\n cp.value.i.min = queryctrl->minimum;\n cp.value.i.max = queryctrl->maximum;\n cp.value.i.step = 0;\n cp.value.i.default_value = queryctrl->default_value;\n cp.value.i.value = ctrl->value;\n cp.flags = flags;\n\n struct v4l2_querymenu qmenu = {};\n\n qmenu.id = queryctrl->id;\n\n std::map<std::string, int> m;\n\n for (int i = 0; i <= queryctrl->maximum; i++)\n {\n qmenu.index = i;\n if (tcam_xioctl(fd, VIDIOC_QUERYMENU, &qmenu))\n continue;\n\n std::string map_string((char*) qmenu.name);\n m.emplace(map_string, i);\n }\n\n return std::make_shared<Property>(PropertyEnumeration(impl, cp, m, type));\n }\n case TCAM_PROPERTY_TYPE_BUTTON:\n {\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyButton(impl, cp, type));\n }\n default:\n {\n std::string s = \"Unknown V4L2 Control type: \";\n s.append((char*)queryctrl->name);\n tcam_log(TCAM_LOG_ERROR, s.c_str());\n break;\n }\n }\n return nullptr;\n}\n\n\nstd::vector<DeviceInfo> tcam::get_v4l2_device_list ()\n{\n std::vector<DeviceInfo> device_list;\n\n struct udev* udev = udev_new();\n if (!udev)\n {\n return device_list;\n }\n\n \/* Create a list of the devices in the 'video4linux' subsystem. *\/\n struct udev_enumerate* enumerate = udev_enumerate_new(udev);\n udev_enumerate_add_match_subsystem(enumerate, \"video4linux\");\n udev_enumerate_scan_devices(enumerate);\n struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);\n struct udev_list_entry* dev_list_entry;\n\n udev_list_entry_foreach(dev_list_entry, devices)\n {\n const char* path;\n char needed_path[100];\n\n \/* Get the filename of the \/sys entry for the device\n and create a udev_device object (dev) representing it *\/\n path = udev_list_entry_get_name(dev_list_entry);\n struct udev_device* dev = udev_device_new_from_syspath(udev, path);\n\n \/* The device pointed to by dev contains information about\n the hidraw device. In order to get information about the\n USB device, get the parent device with the\n subsystem\/devtype pair of \"usb\"\/\"usb_device\". This will\n be several levels up the tree, but the function will find\n it.*\/\n\n \/* we need to copy the devnode (\/dev\/videoX) before the path\n is changed to the path of the usb device behind it (\/sys\/class\/....) *\/\n strcpy(needed_path, udev_device_get_devnode(dev));\n\n struct udev_device* parent_device = udev_device_get_parent_with_subsystem_devtype(dev, \"usb\", \"usb_device\");\n\n \/* skip this device if we can't get the usb parent *\/\n if (!parent_device)\n {\n continue;\n }\n\n \/* From here, we can call get_sysattr_value() for each file\n in the device's \/sys entry. The strings passed into these\n functions (idProduct, idVendor, serial, etc.) correspond\n directly to the files in the directory which represents\n the USB device. Note that USB strings are Unicode, UCS2\n encoded, but the strings returned from\n udev_device_get_sysattr_value() are UTF-8 encoded. *\/\n\n static const char* TCAM_VENDOR_ID_STRING = \"199e\";\n\n if (strcmp(udev_device_get_sysattr_value(parent_device, \"idVendor\"), TCAM_VENDOR_ID_STRING) == 0)\n {\n tcam_device_info info = {};\n info.type = TCAM_DEVICE_TYPE_V4L2;\n strncpy(info.identifier, needed_path, sizeof(info.identifier));\n\n if (udev_device_get_sysattr_value(parent_device, \"idProduct\") != NULL)\n {\n strncpy(info.additional_identifier, udev_device_get_sysattr_value(parent_device, \"idProduct\"), sizeof(info.additional_identifier));\n }\n\n if (udev_device_get_sysattr_value(parent_device, \"product\") != NULL)\n strncpy(info.name, udev_device_get_sysattr_value(parent_device, \"product\"), sizeof(info.name));\n else\n memcpy(info.name, \"\\0\", sizeof(info.name));\n\n if (udev_device_get_sysattr_value(parent_device, \"serial\") != NULL)\n {\n std::string tmp = udev_device_get_sysattr_value(parent_device, \"serial\");\n tmp.erase(remove_if(tmp.begin(), tmp.end(), isspace), tmp.end());\n strncpy(info.serial_number, tmp.c_str(), sizeof(info.serial_number));\n }\n else\n {\n memcpy(info.serial_number, \"\\0\", sizeof(info.serial_number));\n }\n device_list.push_back(DeviceInfo(info));\n }\n\n udev_device_unref(dev);\n }\n\n \/* Free the enumerator object *\/\n udev_enumerate_unref(enumerate);\n\n udev_unref(udev);\n\n return device_list;\n}\n<commit_msg>Add missing switch case<commit_after>\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"v4l2_utils.h\"\n\n#include \"v4l2_property_mapping.h\"\n#include \"utils.h\"\n#include \"logging.h\"\n\n#if HAVE_UDEV\n#include <libudev.h>\n#endif\n\n#include <glob.h>\n\n#include <vector>\n#include <algorithm>\n\nusing namespace tcam;\n\n\nuint32_t tcam::convert_v4l2_flags (uint32_t v4l2_flags)\n{\n uint32_t internal_flags = 0;\n\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_DISABLED))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_DISABLED);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_GRABBED))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_GRABBED);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_READ_ONLY))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_READ_ONLY);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_UPDATE))\n {}\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_INACTIVE))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_INACTIVE);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_SLIDER))\n {}\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_WRITE_ONLY))\n {\n internal_flags = set_bit(internal_flags, TCAM_PROPERTY_FLAG_WRITE_ONLY);\n }\n if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_VOLATILE))\n {}\n \/\/ if (is_bit_set(v4l2_flags, V4L2_CTRL_FLAG_HAS_PAYLOAD))\n \/\/ {}\n\n return internal_flags;\n}\n\n\nstatic TCAM_PROPERTY_ID find_mapping (int v4l2_id)\n{\n auto f = [v4l2_id] (int p)\n {\n if (v4l2_id == p)\n return true;\n return false;\n };\n\n for (const auto& m : v4l2_mappings)\n {\n auto match = std::find_if(m.v4l2_id.begin(), m.v4l2_id.end(), f);\n\n if (match != m.v4l2_id.end())\n return m.id;\n }\n return TCAM_PROPERTY_INVALID;\n}\n\n\nstd::shared_ptr<Property> tcam::create_property (int fd,\n struct v4l2_queryctrl* queryctrl,\n struct v4l2_ext_control* ctrl,\n std::shared_ptr<PropertyImpl> impl)\n{\n\n \/\/ assure we have the typ\n Property::VALUE_TYPE type;\n\n switch (queryctrl->type)\n {\n case V4L2_CTRL_TYPE_BOOLEAN:\n {\n type = Property::BOOLEAN;\n break;\n }\n case V4L2_CTRL_TYPE_INTEGER:\n {\n type = Property::INTEGER;\n break;\n }\n case V4L2_CTRL_TYPE_STRING:\n {\n type = Property::STRING;\n break;\n }\n case V4L2_CTRL_TYPE_INTEGER_MENU:\n case V4L2_CTRL_TYPE_MENU:\n {\n type = Property::ENUM;\n break;\n }\n case V4L2_CTRL_TYPE_BUTTON:\n {\n type = Property::BUTTON;\n break;\n }\n default:\n {\n type = Property::UNDEFINED;\n break;\n }\n }\n\n auto prop_id = find_mapping (ctrl->id);\n\n auto ctrl_m = get_control_reference(prop_id);\n\n TCAM_PROPERTY_TYPE type_to_use;\n tcam_device_property cp = {};\n\n if (ctrl_m.id == TCAM_PROPERTY_INVALID)\n {\n tcam_log(TCAM_LOG_WARNING, \"Unable to find std property. Passing raw property identifier through. '%s'(%x)\", (char*)queryctrl->name, queryctrl->id);\n \/\/ pass through and do not associate with anything existing\n type_to_use = value_type_to_ctrl_type(type);\n memcpy(cp.name, (char*)queryctrl->name, sizeof(cp.name));\n cp.type = value_type_to_ctrl_type(type);\n \/\/ generate id so that identfication of passed through properties is guaranteed\n cp.id = generate_unique_property_id();\n }\n else\n {\n type_to_use = ctrl_m.type_to_use;\n cp = create_empty_property(ctrl_m.id);\n }\n\n uint32_t flags = convert_v4l2_flags(queryctrl->flags);\n\n switch (type_to_use)\n {\n case TCAM_PROPERTY_TYPE_BOOLEAN:\n {\n if (queryctrl->default_value == 0)\n {\n cp.value.b.default_value = false;\n }\n else if (queryctrl->default_value > 0)\n {\n cp.value.b.default_value = true;\n }\n else\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Boolean '%s' has impossible default value: %d Setting to false\",\n cp.name,\n queryctrl->default_value);\n cp.value.b.default_value = false;\n }\n\n if (ctrl->value == 0)\n {\n cp.value.b.value = false;\n }\n else if (ctrl->value > 0)\n {\n cp.value.b.value = true;\n }\n else\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Boolean '%s' has impossible value: %d Setting to false\",\n cp.name,\n ctrl->value);\n cp.value.b.value = false;\n }\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyBoolean(impl, cp, type));\n }\n case TCAM_PROPERTY_TYPE_INTEGER:\n {\n cp.value.i.min = queryctrl->minimum;\n cp.value.i.max = queryctrl->maximum;\n cp.value.i.step = queryctrl->step;\n\n if (cp.value.i.min > cp.value.i.max)\n {\n tcam_log(TCAM_LOG_ERROR,\n \"Range boundaries for property '%s' are faulty. Ignoring property as a precaution.\",\n cp.name);\n return nullptr;\n }\n\n if (cp.value.i.step == 0)\n {\n tcam_log(TCAM_LOG_WARNING,\n \"Detected stepsize 0 for property %s. Setting to 1.\",\n cp.name);\n\n cp.value.i.step = 1;\n }\n\n cp.value.i.default_value = queryctrl->default_value;\n cp.value.i.value = ctrl->value;\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyInteger(impl, cp, type));\n }\n \/\/ case TCAM_CTRL_TYPE_DOUBLE:\n \/\/ {\n \/\/ Does not exist in v4l2\n \/\/ }\n case TCAM_PROPERTY_TYPE_STRING:\n {\n memcpy(cp.value.s.value,(char*)queryctrl->name, sizeof(cp.value.s.value));\n memcpy(cp.value.s.default_value, (char*)queryctrl->name, sizeof(cp.value.s.default_value));\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyString(impl, cp, type));\n }\n case TCAM_PROPERTY_TYPE_ENUMERATION:\n {\n cp.value.i.min = queryctrl->minimum;\n cp.value.i.max = queryctrl->maximum;\n cp.value.i.step = 0;\n cp.value.i.default_value = queryctrl->default_value;\n cp.value.i.value = ctrl->value;\n cp.flags = flags;\n\n struct v4l2_querymenu qmenu = {};\n\n qmenu.id = queryctrl->id;\n\n std::map<std::string, int> m;\n\n for (int i = 0; i <= queryctrl->maximum; i++)\n {\n qmenu.index = i;\n if (tcam_xioctl(fd, VIDIOC_QUERYMENU, &qmenu))\n continue;\n\n std::string map_string((char*) qmenu.name);\n m.emplace(map_string, i);\n }\n\n return std::make_shared<Property>(PropertyEnumeration(impl, cp, m, type));\n }\n case TCAM_PROPERTY_TYPE_BUTTON:\n {\n cp.flags = flags;\n\n return std::make_shared<Property>(PropertyButton(impl, cp, type));\n }\n default:\n {\n std::string s = \"Unknown V4L2 Control type: \";\n s.append((char*)queryctrl->name);\n tcam_log(TCAM_LOG_ERROR, s.c_str());\n break;\n }\n }\n return nullptr;\n}\n\n\nstd::vector<DeviceInfo> tcam::get_v4l2_device_list ()\n{\n std::vector<DeviceInfo> device_list;\n\n struct udev* udev = udev_new();\n if (!udev)\n {\n return device_list;\n }\n\n \/* Create a list of the devices in the 'video4linux' subsystem. *\/\n struct udev_enumerate* enumerate = udev_enumerate_new(udev);\n udev_enumerate_add_match_subsystem(enumerate, \"video4linux\");\n udev_enumerate_scan_devices(enumerate);\n struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);\n struct udev_list_entry* dev_list_entry;\n\n udev_list_entry_foreach(dev_list_entry, devices)\n {\n const char* path;\n char needed_path[100];\n\n \/* Get the filename of the \/sys entry for the device\n and create a udev_device object (dev) representing it *\/\n path = udev_list_entry_get_name(dev_list_entry);\n struct udev_device* dev = udev_device_new_from_syspath(udev, path);\n\n \/* The device pointed to by dev contains information about\n the hidraw device. In order to get information about the\n USB device, get the parent device with the\n subsystem\/devtype pair of \"usb\"\/\"usb_device\". This will\n be several levels up the tree, but the function will find\n it.*\/\n\n \/* we need to copy the devnode (\/dev\/videoX) before the path\n is changed to the path of the usb device behind it (\/sys\/class\/....) *\/\n strcpy(needed_path, udev_device_get_devnode(dev));\n\n struct udev_device* parent_device = udev_device_get_parent_with_subsystem_devtype(dev, \"usb\", \"usb_device\");\n\n \/* skip this device if we can't get the usb parent *\/\n if (!parent_device)\n {\n continue;\n }\n\n \/* From here, we can call get_sysattr_value() for each file\n in the device's \/sys entry. The strings passed into these\n functions (idProduct, idVendor, serial, etc.) correspond\n directly to the files in the directory which represents\n the USB device. Note that USB strings are Unicode, UCS2\n encoded, but the strings returned from\n udev_device_get_sysattr_value() are UTF-8 encoded. *\/\n\n static const char* TCAM_VENDOR_ID_STRING = \"199e\";\n\n if (strcmp(udev_device_get_sysattr_value(parent_device, \"idVendor\"), TCAM_VENDOR_ID_STRING) == 0)\n {\n tcam_device_info info = {};\n info.type = TCAM_DEVICE_TYPE_V4L2;\n strncpy(info.identifier, needed_path, sizeof(info.identifier));\n\n if (udev_device_get_sysattr_value(parent_device, \"idProduct\") != NULL)\n {\n strncpy(info.additional_identifier, udev_device_get_sysattr_value(parent_device, \"idProduct\"), sizeof(info.additional_identifier));\n }\n\n if (udev_device_get_sysattr_value(parent_device, \"product\") != NULL)\n strncpy(info.name, udev_device_get_sysattr_value(parent_device, \"product\"), sizeof(info.name));\n else\n memcpy(info.name, \"\\0\", sizeof(info.name));\n\n if (udev_device_get_sysattr_value(parent_device, \"serial\") != NULL)\n {\n std::string tmp = udev_device_get_sysattr_value(parent_device, \"serial\");\n tmp.erase(remove_if(tmp.begin(), tmp.end(), isspace), tmp.end());\n strncpy(info.serial_number, tmp.c_str(), sizeof(info.serial_number));\n }\n else\n {\n memcpy(info.serial_number, \"\\0\", sizeof(info.serial_number));\n }\n device_list.push_back(DeviceInfo(info));\n }\n\n udev_device_unref(dev);\n }\n\n \/* Free the enumerator object *\/\n udev_enumerate_unref(enumerate);\n\n udev_unref(udev);\n\n return device_list;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"model.h\"\n\n#include <QDebug>\n\n#include <sstream>\n\nusing namespace std;\n\nnamespace {\nQString generateSummary(const AccumulatedTraceData& data)\n{\n stringstream stream;\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"<qt>\"\n << \"<strong>total runtime<\/strong>: \" << fixed << totalTimeS << \"s.<br\/>\"\n << \"<strong>bytes allocated in total<\/strong> (ignoring deallocations): \" << formatBytes(data.totalAllocated)\n << \" (\" << formatBytes(data.totalAllocated \/ totalTimeS) << \"\/s)<br\/>\"\n << \"<strong>calls to allocation functions<\/strong>: \" << data.totalAllocations\n << \" (\" << size_t(data.totalAllocations \/ totalTimeS) << \"\/s)<br\/>\"\n << \"<strong>peak heap memory consumption<\/strong>: \" << formatBytes(data.peak) << \"<br\/>\"\n << \"<strong>total memory leaked<\/strong>: \" << formatBytes(data.leaked) << \"<br\/>\";\n stream << \"<\/qt>\";\n return QString::fromStdString(stream.str());\n}\n\nint parentRow(const QModelIndex& child)\n{\n return child.isValid() ? static_cast<int>(child.internalId()) : -1;\n}\n\n}\n\nModel::Model(QObject* parent)\n{\n\n}\n\nModel::~Model()\n{\n}\n\nQVariant Model::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (orientation != Qt::Horizontal || role != Qt::DisplayRole || section < 0 || section >= NUM_COLUMNS) {\n return QVariant();\n }\n switch (static_cast<Columns>(section)) {\n case FileColumn:\n return tr(\"File\");\n case FunctionColumn:\n return tr(\"Function\");\n case ModuleColumn:\n return tr(\"Module\");\n case AllocationsColumn:\n return tr(\"Allocations\");\n case PeakColumn:\n return tr(\"Peak\");\n case LeakedColumn:\n return tr(\"Leaked\");\n case AllocatedColumn:\n return tr(\"Allocated\");\n case NUM_COLUMNS:\n break;\n }\n return QVariant();\n}\n\nQVariant Model::data(const QModelIndex& index, int role) const\n{\n if (index.row() < 0 || index.row() > m_data.mergedAllocations.size()\n || index.column() < 0 || index.column() > NUM_COLUMNS)\n {\n return QVariant();\n }\n const auto parent = index.parent();\n if (parent.isValid()) {\n \/\/ child level\n if (parent.parent().isValid()) {\n return QVariant();\n }\n const auto& allocation = m_data.mergedAllocations[parent.row()];\n const auto& trace = allocation.traces[index.row()];\n\n if (role == Qt::DisplayRole) {\n return allocationData(trace, m_data.findTrace(trace.traceIndex).ipIndex, static_cast<Columns>(index.column()));\n } else if (role == Qt::ToolTipRole) {\n stringstream stream;\n m_data.printBacktrace(trace.traceIndex, stream);\n return QString::fromStdString(stream.str());\n }\n return QVariant();\n }\n\n \/\/ top-level\n const auto& allocation = m_data.mergedAllocations[index.row()];\n if (role == Qt::DisplayRole) {\n return allocationData(allocation, allocation.ipIndex, static_cast<Columns>(index.column()));\n }\n return QVariant();\n}\n\nQModelIndex Model::index(int row, int column, const QModelIndex& parent) const\n{\n if (row < 0 || column < 0 || column >= NUM_COLUMNS || row >= rowCount(parent)) {\n return QModelIndex();\n }\n return createIndex(row, column, static_cast<quintptr>(parent.row()));\n}\n\nQModelIndex Model::parent(const QModelIndex& child) const\n{\n const auto parent = parentRow(child);\n if (parent == -1) {\n return QModelIndex();\n } else {\n return createIndex(parent, 0, -1);\n }\n}\n\nint Model::rowCount(const QModelIndex& parent) const\n{\n if (parent.isValid()) {\n if (parent.column() != 0 || parent.row() < 0 || parent.row() >= m_data.mergedAllocations.size()\n || parentRow(parent) != -1)\n {\n return 0;\n } else {\n return m_data.mergedAllocations[parent.row()].traces.size();\n }\n }\n return m_data.mergedAllocations.size();\n}\n\nint Model::columnCount(const QModelIndex& \/*parent*\/) const\n{\n return NUM_COLUMNS;\n}\n\nvoid Model::loadFile(const QString& file)\n{\n beginResetModel();\n m_data.read(file.toStdString());\n endResetModel();\n emit dataReady(generateSummary(m_data));\n}\n\nQVariant Model::allocationData(const AllocationData& allocation, const IpIndex& ipIndex, Columns column) const\n{\n switch (column) {\n case AllocationsColumn:\n return static_cast<quint64>(allocation.allocations);\n case PeakColumn:\n return static_cast<quint64>(allocation.peak);\n case LeakedColumn:\n return static_cast<quint64>(allocation.leaked);\n case AllocatedColumn:\n return static_cast<quint64>(allocation.allocated);\n case FileColumn:\n case ModuleColumn:\n case FunctionColumn: {\n const auto& ip = m_data.findIp(ipIndex);\n if (column == FunctionColumn) {\n if (ip.functionIndex) {\n return QString::fromStdString(m_data.prettyFunction(m_data.stringify(ip.functionIndex)));\n } else {\n return QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16);\n }\n } else if (column == ModuleColumn) {\n return QString::fromStdString(m_data.stringify(ip.moduleIndex));\n } else if (ip.fileIndex) {\n auto file = QString::fromStdString(m_data.stringify(ip.fileIndex));\n return file + QLatin1Char(':') + QString::number(ip.line);\n } else {\n return QString();\n }\n break;\n }\n case NUM_COLUMNS:\n break;\n }\n return QVariant();\n}<commit_msg>Deduplicate shown functions by skipping first, merged, level.<commit_after>\/*\n * Copyright 2015 Milian Wolff <mail@milianw.de>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"model.h\"\n\n#include <QDebug>\n\n#include <sstream>\n\nusing namespace std;\n\nnamespace {\nQString generateSummary(const AccumulatedTraceData& data)\n{\n stringstream stream;\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"<qt>\"\n << \"<strong>total runtime<\/strong>: \" << fixed << totalTimeS << \"s.<br\/>\"\n << \"<strong>bytes allocated in total<\/strong> (ignoring deallocations): \" << formatBytes(data.totalAllocated)\n << \" (\" << formatBytes(data.totalAllocated \/ totalTimeS) << \"\/s)<br\/>\"\n << \"<strong>calls to allocation functions<\/strong>: \" << data.totalAllocations\n << \" (\" << size_t(data.totalAllocations \/ totalTimeS) << \"\/s)<br\/>\"\n << \"<strong>peak heap memory consumption<\/strong>: \" << formatBytes(data.peak) << \"<br\/>\"\n << \"<strong>total memory leaked<\/strong>: \" << formatBytes(data.leaked) << \"<br\/>\";\n stream << \"<\/qt>\";\n return QString::fromStdString(stream.str());\n}\n\nint parentRow(const QModelIndex& child)\n{\n return child.isValid() ? static_cast<int>(child.internalId()) : -1;\n}\n\n}\n\nModel::Model(QObject* parent)\n{\n\n}\n\nModel::~Model()\n{\n}\n\nQVariant Model::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (orientation != Qt::Horizontal || role != Qt::DisplayRole || section < 0 || section >= NUM_COLUMNS) {\n return QVariant();\n }\n switch (static_cast<Columns>(section)) {\n case FileColumn:\n return tr(\"File\");\n case FunctionColumn:\n return tr(\"Function\");\n case ModuleColumn:\n return tr(\"Module\");\n case AllocationsColumn:\n return tr(\"Allocations\");\n case PeakColumn:\n return tr(\"Peak\");\n case LeakedColumn:\n return tr(\"Leaked\");\n case AllocatedColumn:\n return tr(\"Allocated\");\n case NUM_COLUMNS:\n break;\n }\n return QVariant();\n}\n\nQVariant Model::data(const QModelIndex& index, int role) const\n{\n if (index.row() < 0 || index.row() > m_data.mergedAllocations.size()\n || index.column() < 0 || index.column() > NUM_COLUMNS)\n {\n return QVariant();\n }\n const auto parent = index.parent();\n if (parent.isValid()) {\n \/\/ child level\n if (parent.parent().isValid()) {\n return QVariant();\n }\n const auto& allocation = m_data.mergedAllocations[parent.row()];\n const auto& trace = allocation.traces[index.row()];\n\n if (role == Qt::DisplayRole) {\n auto node = m_data.findTrace(trace.traceIndex);\n \/\/ skip first level, it is duplicated on the top-level\n node = m_data.findTrace(node.parentIndex);\n return allocationData(trace, node.ipIndex, static_cast<Columns>(index.column()));\n } else if (role == Qt::ToolTipRole) {\n stringstream stream;\n m_data.printBacktrace(trace.traceIndex, stream);\n return QString::fromStdString(stream.str());\n }\n return QVariant();\n }\n\n \/\/ top-level\n const auto& allocation = m_data.mergedAllocations[index.row()];\n if (role == Qt::DisplayRole) {\n return allocationData(allocation, allocation.ipIndex, static_cast<Columns>(index.column()));\n }\n return QVariant();\n}\n\nQModelIndex Model::index(int row, int column, const QModelIndex& parent) const\n{\n if (row < 0 || column < 0 || column >= NUM_COLUMNS || row >= rowCount(parent)) {\n return QModelIndex();\n }\n return createIndex(row, column, static_cast<quintptr>(parent.row()));\n}\n\nQModelIndex Model::parent(const QModelIndex& child) const\n{\n const auto parent = parentRow(child);\n if (parent == -1) {\n return QModelIndex();\n } else {\n return createIndex(parent, 0, -1);\n }\n}\n\nint Model::rowCount(const QModelIndex& parent) const\n{\n if (parent.isValid()) {\n if (parent.column() != 0 || parent.row() < 0 || parent.row() >= m_data.mergedAllocations.size()\n || parentRow(parent) != -1)\n {\n return 0;\n } else {\n return m_data.mergedAllocations[parent.row()].traces.size();\n }\n }\n return m_data.mergedAllocations.size();\n}\n\nint Model::columnCount(const QModelIndex& \/*parent*\/) const\n{\n return NUM_COLUMNS;\n}\n\nvoid Model::loadFile(const QString& file)\n{\n beginResetModel();\n m_data.read(file.toStdString());\n endResetModel();\n emit dataReady(generateSummary(m_data));\n}\n\nQVariant Model::allocationData(const AllocationData& allocation, const IpIndex& ipIndex, Columns column) const\n{\n switch (column) {\n case AllocationsColumn:\n return static_cast<quint64>(allocation.allocations);\n case PeakColumn:\n return static_cast<quint64>(allocation.peak);\n case LeakedColumn:\n return static_cast<quint64>(allocation.leaked);\n case AllocatedColumn:\n return static_cast<quint64>(allocation.allocated);\n case FileColumn:\n case ModuleColumn:\n case FunctionColumn: {\n const auto& ip = m_data.findIp(ipIndex);\n if (column == FunctionColumn) {\n if (ip.functionIndex) {\n return QString::fromStdString(m_data.prettyFunction(m_data.stringify(ip.functionIndex)));\n } else {\n return QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16);\n }\n } else if (column == ModuleColumn) {\n return QString::fromStdString(m_data.stringify(ip.moduleIndex));\n } else if (ip.fileIndex) {\n auto file = QString::fromStdString(m_data.stringify(ip.fileIndex));\n return file + QLatin1Char(':') + QString::number(ip.line);\n } else {\n return QString();\n }\n break;\n }\n case NUM_COLUMNS:\n break;\n }\n return QVariant();\n}<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n#include \"SmartViewPane.h\"\r\n#include \"String.h\"\r\n#include \"SmartView\/SmartView.h\"\r\n\r\nstatic wstring CLASS = L\"SmartViewPane\";\r\n\r\nSmartViewPane* SmartViewPane::Create(UINT uidLabel)\r\n{\r\n\tauto pane = new SmartViewPane();\r\n\tif (pane)\r\n\t{\r\n\t\tpane->SetLabel(uidLabel, true);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nSmartViewPane::SmartViewPane()\r\n{\r\n\tm_TextPane.m_bMultiline = true;\r\n\tm_TextPane.SetLabel(NULL, true);\r\n\tm_bHasData = false;\r\n\tm_bDoDropDown = true;\r\n\tm_bReadOnly = true;\r\n}\r\n\r\nbool SmartViewPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_SMARTVIEWPANE == vType || DropDownPane::IsType(vType);\r\n}\r\n\r\nULONG SmartViewPane::GetFlags()\r\n{\r\n\treturn DropDownPane::GetFlags() | vpCollapsible;\r\n}\r\n\r\nvoid SmartViewPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tfor (auto smartViewParserType : SmartViewParserTypeArray)\r\n\t{\r\n\t\tInsertDropString(smartViewParserType.lpszName, smartViewParserType.ulValue);\r\n\t}\r\n\r\n\tCreateControl(iControl, pParent, hdc);\r\n\r\n\tDropDownPane::Initialize(0, pParent, hdc);\r\n\r\n\t\/\/ Passing a control # of 1 gives us a built in margin\r\n\tm_TextPane.Initialize(1, pParent, hdc);\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nint SmartViewPane::GetFixedHeight()\r\n{\r\n\tif (!m_bDoDropDown && !m_bHasData) return 0;\r\n\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\t\/\/ Our expand\/collapse button\r\n\tiHeight += m_iButtonHeight;\r\n\t\/\/ Control label will be next to this\r\n\r\n\tif (m_bDoDropDown && !m_bCollapsed)\r\n\t{\r\n\t\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\t\tiHeight += m_TextPane.GetFixedHeight();\r\n\t}\r\n\r\n\treturn iHeight;\r\n}\r\n\r\nint SmartViewPane::GetLines()\r\n{\r\n\tauto iStructType = GetDropDownSelectionValue();\r\n\tif (!m_bCollapsed && (m_bHasData || iStructType))\r\n\t{\r\n\t\treturn m_TextPane.GetLines();\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nvoid SmartViewPane::SetWindowPos(int x, int y, int width, int height)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (!m_bDoDropDown && !m_bHasData)\r\n\t{\r\n\t\tEC_B(m_CollapseButton.ShowWindow(SW_HIDE));\r\n\t\tEC_B(m_Label.ShowWindow(SW_HIDE));\r\n\t\tEC_B(m_DropDown.ShowWindow(SW_HIDE));\r\n\t\tm_TextPane.ShowWindow(SW_HIDE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tEC_B(m_CollapseButton.ShowWindow(SW_SHOW));\r\n\t\tEC_B(m_Label.ShowWindow(SW_SHOW));\r\n\t}\r\n\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\theight -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tViewPane::SetWindowPos(x, y, width, height);\r\n\r\n\ty += m_iLabelHeight + m_iSmallHeightMargin;\r\n\theight -= m_iButtonHeight + m_iSmallHeightMargin;\r\n\r\n\tif (m_bCollapsed)\r\n\t{\r\n\t\tEC_B(m_DropDown.ShowWindow(SW_HIDE));\r\n\t\tm_TextPane.ShowWindow(SW_HIDE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (m_bDoDropDown)\r\n\t\t{\r\n\t\t\tEC_B(m_DropDown.ShowWindow(SW_SHOW));\r\n\t\t\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n\r\n\t\t\ty += m_iEditHeight;\r\n\t\t\theight -= m_iEditHeight;\r\n\t\t}\r\n\r\n\t\tm_TextPane.ShowWindow(SW_SHOW);\r\n\t\tm_TextPane.SetWindowPos(x, y, width, height);\r\n\t}\r\n}\r\n\r\nvoid SmartViewPane::SetMargins(\r\n\tint iMargin,\r\n\tint iSideMargin,\r\n\tint iLabelHeight, \/\/ Height of the label\r\n\tint iSmallHeightMargin,\r\n\tint iLargeHeightMargin,\r\n\tint iButtonHeight, \/\/ Height of buttons below the control\r\n\tint iEditHeight) \/\/ height of an edit control\r\n{\r\n\tm_TextPane.SetMargins(iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight);\r\n\tViewPane::SetMargins(iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight);\r\n}\r\n\r\nvoid SmartViewPane::SetStringW(wstring szMsg)\r\n{\r\n\tif (!szMsg.empty())\r\n\t{\r\n\t\tm_bHasData = true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_bHasData = false;\r\n\t}\r\n\r\n\tm_TextPane.SetStringW(szMsg);\r\n}\r\n\r\nvoid SmartViewPane::DisableDropDown()\r\n{\r\n\tm_bDoDropDown = false;\r\n}\r\n\r\nvoid SmartViewPane::SetParser(__ParsingTypeEnum iParser)\r\n{\r\n\tfor (size_t iDropNum = 0; iDropNum < SmartViewParserTypeArray.size(); iDropNum++)\r\n\t{\r\n\t\tif (iParser == static_cast<__ParsingTypeEnum>(SmartViewParserTypeArray[iDropNum].ulValue))\r\n\t\t{\r\n\t\t\tSetSelection(iDropNum);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SmartViewPane::Parse(SBinary myBin)\r\n{\r\n\tauto iStructType = static_cast<__ParsingTypeEnum>(GetDropDownSelectionValue());\r\n\tauto szSmartView = InterpretBinaryAsString(myBin, iStructType, nullptr);\r\n\r\n\tm_bHasData = !szSmartView.empty();\r\n\tSetStringW(szSmartView);\r\n}\r\n<commit_msg>Error opening SV pane<commit_after>#include \"stdafx.h\"\r\n#include \"SmartViewPane.h\"\r\n#include \"String.h\"\r\n#include \"SmartView\/SmartView.h\"\r\n\r\nstatic wstring CLASS = L\"SmartViewPane\";\r\n\r\nSmartViewPane* SmartViewPane::Create(UINT uidLabel)\r\n{\r\n\tauto pane = new SmartViewPane();\r\n\tif (pane)\r\n\t{\r\n\t\tpane->SetLabel(uidLabel, true);\r\n\t}\r\n\r\n\treturn pane;\r\n}\r\n\r\nSmartViewPane::SmartViewPane()\r\n{\r\n\tm_TextPane.m_bMultiline = true;\r\n\tm_TextPane.SetLabel(NULL, true);\r\n\tm_bHasData = false;\r\n\tm_bDoDropDown = true;\r\n\tm_bReadOnly = true;\r\n}\r\n\r\nbool SmartViewPane::IsType(__ViewTypes vType)\r\n{\r\n\treturn CTRL_SMARTVIEWPANE == vType || DropDownPane::IsType(vType);\r\n}\r\n\r\nULONG SmartViewPane::GetFlags()\r\n{\r\n\treturn DropDownPane::GetFlags() | vpCollapsible;\r\n}\r\n\r\nvoid SmartViewPane::Initialize(int \/*iControl*\/, _In_ CWnd* pParent, _In_ HDC hdc)\r\n{\r\n\tfor (auto smartViewParserType : SmartViewParserTypeArray)\r\n\t{\r\n\t\tInsertDropString(smartViewParserType.lpszName, smartViewParserType.ulValue);\r\n\t}\r\n\r\n\tDropDownPane::Initialize(0, pParent, hdc);\r\n\tm_TextPane.Initialize(1, pParent, hdc);\r\n\r\n\tm_bInitialized = true;\r\n}\r\n\r\nint SmartViewPane::GetFixedHeight()\r\n{\r\n\tif (!m_bDoDropDown && !m_bHasData) return 0;\r\n\r\n\tauto iHeight = 0;\r\n\r\n\tif (0 != m_iControl) iHeight += m_iSmallHeightMargin; \/\/ Top margin\r\n\r\n\t\/\/ Our expand\/collapse button\r\n\tiHeight += m_iButtonHeight;\r\n\t\/\/ Control label will be next to this\r\n\r\n\tif (m_bDoDropDown && !m_bCollapsed)\r\n\t{\r\n\t\tiHeight += m_iEditHeight; \/\/ Height of the dropdown\r\n\t\tiHeight += m_TextPane.GetFixedHeight();\r\n\t}\r\n\r\n\treturn iHeight;\r\n}\r\n\r\nint SmartViewPane::GetLines()\r\n{\r\n\tauto iStructType = GetDropDownSelectionValue();\r\n\tif (!m_bCollapsed && (m_bHasData || iStructType))\r\n\t{\r\n\t\treturn m_TextPane.GetLines();\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nvoid SmartViewPane::SetWindowPos(int x, int y, int width, int height)\r\n{\r\n\tauto hRes = S_OK;\r\n\tif (!m_bDoDropDown && !m_bHasData)\r\n\t{\r\n\t\tEC_B(m_CollapseButton.ShowWindow(SW_HIDE));\r\n\t\tEC_B(m_Label.ShowWindow(SW_HIDE));\r\n\t\tEC_B(m_DropDown.ShowWindow(SW_HIDE));\r\n\t\tm_TextPane.ShowWindow(SW_HIDE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tEC_B(m_CollapseButton.ShowWindow(SW_SHOW));\r\n\t\tEC_B(m_Label.ShowWindow(SW_SHOW));\r\n\t}\r\n\r\n\tif (0 != m_iControl)\r\n\t{\r\n\t\ty += m_iSmallHeightMargin;\r\n\t\theight -= m_iSmallHeightMargin;\r\n\t}\r\n\r\n\tViewPane::SetWindowPos(x, y, width, height);\r\n\r\n\ty += m_iLabelHeight + m_iSmallHeightMargin;\r\n\theight -= m_iButtonHeight + m_iSmallHeightMargin;\r\n\r\n\tif (m_bCollapsed)\r\n\t{\r\n\t\tEC_B(m_DropDown.ShowWindow(SW_HIDE));\r\n\t\tm_TextPane.ShowWindow(SW_HIDE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (m_bDoDropDown)\r\n\t\t{\r\n\t\t\tEC_B(m_DropDown.ShowWindow(SW_SHOW));\r\n\t\t\tEC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));\r\n\r\n\t\t\ty += m_iEditHeight;\r\n\t\t\theight -= m_iEditHeight;\r\n\t\t}\r\n\r\n\t\tm_TextPane.ShowWindow(SW_SHOW);\r\n\t\tm_TextPane.SetWindowPos(x, y, width, height);\r\n\t}\r\n}\r\n\r\nvoid SmartViewPane::SetMargins(\r\n\tint iMargin,\r\n\tint iSideMargin,\r\n\tint iLabelHeight, \/\/ Height of the label\r\n\tint iSmallHeightMargin,\r\n\tint iLargeHeightMargin,\r\n\tint iButtonHeight, \/\/ Height of buttons below the control\r\n\tint iEditHeight) \/\/ height of an edit control\r\n{\r\n\tm_TextPane.SetMargins(iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight);\r\n\tViewPane::SetMargins(iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight);\r\n}\r\n\r\nvoid SmartViewPane::SetStringW(wstring szMsg)\r\n{\r\n\tif (!szMsg.empty())\r\n\t{\r\n\t\tm_bHasData = true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_bHasData = false;\r\n\t}\r\n\r\n\tm_TextPane.SetStringW(szMsg);\r\n}\r\n\r\nvoid SmartViewPane::DisableDropDown()\r\n{\r\n\tm_bDoDropDown = false;\r\n}\r\n\r\nvoid SmartViewPane::SetParser(__ParsingTypeEnum iParser)\r\n{\r\n\tfor (size_t iDropNum = 0; iDropNum < SmartViewParserTypeArray.size(); iDropNum++)\r\n\t{\r\n\t\tif (iParser == static_cast<__ParsingTypeEnum>(SmartViewParserTypeArray[iDropNum].ulValue))\r\n\t\t{\r\n\t\t\tSetSelection(iDropNum);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SmartViewPane::Parse(SBinary myBin)\r\n{\r\n\tauto iStructType = static_cast<__ParsingTypeEnum>(GetDropDownSelectionValue());\r\n\tauto szSmartView = InterpretBinaryAsString(myBin, iStructType, nullptr);\r\n\r\n\tm_bHasData = !szSmartView.empty();\r\n\tSetStringW(szSmartView);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*! \\file ospDVR.cpp A GLUT-based viewer for Wavefront OBJ files *\/\n\n\/\/ viewer widget\n#include \"..\/..\/apps\/util\/glut3D\/glut3D.h\"\n\/\/ ospray, for rendering\n#include \"ospray\/ospray.h\"\n\nnamespace ospray {\n using std::cout;\n using std::endl;\n\n const char *renderType = \"dvr_ispc\";\n\n \/*! \\page volview_notes_on_volume_interface Internal Notes on Volume Interface\n\n Right now i'm using a trivially simple interface to ospray's\n volume code by simply passing filename and dimensions right into\n the ospray volume object, which then does its own parsing *inside*\n ospray. this is, however, not as it should eventually be - to be\n fixed! *\/\n\n void error(const std::string &vol)\n {\n cout << \"ospray::ospDVR fatal error : \" << vol << endl;\n cout << endl;\n cout << \"Proper usage: \" << endl;\n cout << \" .\/ospDVR <sizex> <sizey> <sizez> volFile.raw\" << std::endl;\n cout << endl;\n exit(1);\n }\n\n using ospray::glut3D::Glut3DWidget;\n\n \/\/! volume viewer widget. \n \/*! \\internal Note that all handling of camera is almost exactly\n similar to the code in msgView; might make sense to move that into\n a common class! *\/\n struct VolumeViewer : public Glut3DWidget {\n \/*! construct volume from file name and dimensions \\see volview_notes_on_volume_interface *\/\n VolumeViewer(const vec3i dims, const std::string &fileName, int resampleSize=0) \n : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE),\n fb(NULL), renderer(NULL), volume(NULL), \n dims(dims), fileName(fileName), resampleSize(resampleSize)\n {\n camera = ospNewCamera(\"perspective\");\n Assert2(camera,\"could not create camera\");\n ospSet3f(camera,\"pos\",-1,1,-1);\n ospSet3f(camera,\"dir\",+1,-1,+1);\n ospCommit(camera);\n ospCommit(camera);\n\n volume = ospNewVolume(\"naive32-uint8\");\n Assert(volume && \"null volume handle\");\n ospSet3i(volume,\"dimensions\",dims.x,dims.y,dims.z);\n \/\/ ospSet3i(volume,\"resample_dimensions\",resampleSize,resampleSize,resampleSize);\n ospSetString(volume,\"filename\",fileName.c_str());\n ospCommit(volume);\n\n renderer = ospNewRenderer(renderType);\n Assert2(renderer,\"could not create renderer\");\n ospSetParam(renderer,\"volume\",volume);\n ospSetParam(renderer,\"camera\",camera);\n ospCommit(renderer);\n\n };\n virtual void reshape(const ospray::vec2i &newSize) \n {\n Glut3DWidget::reshape(newSize);\n if (fb) ospFreeFrameBuffer(fb);\n fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8);\n ospSetf(camera,\"aspect\",viewPort.aspect);\n ospCommit(camera);\n }\n\n virtual void display() \n {\n if (!fb || !renderer) return;\n\n if (viewPort.modified) {\n Assert2(camera,\"ospray camera is null\");\n \n \/\/ PRINT(viewPort);\n \n ospSetVec3f(camera,\"pos\",viewPort.from);\n ospSetVec3f(camera,\"dir\",viewPort.at-viewPort.from);\n ospSetVec3f(camera,\"up\",viewPort.up);\n ospSetf(camera,\"aspect\",viewPort.aspect);\n ospCommit(camera);\n viewPort.modified = false;\n }\n\n fps.startRender();\n ospRenderFrame(fb,renderer);\n fps.doneRender();\n \n ucharFB = (unsigned int *)ospMapFrameBuffer(fb);\n frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR;\n Glut3DWidget::display();\n \n ospUnmapFrameBuffer(ucharFB,fb);\n \n char title[1000];\n \n sprintf(title,\"Test04: GlutWidget+ospray API rest (%f fps)\",\n fps.getFPS());\n setTitle(title);\n forceRedraw();\n }\n\n std::string fileName; \/*! volume file name \\see volview_notes_on_volume_interface *\/\n vec3i dims; \/*! volume dimensions \\see volview_notes_on_volume_interface *\/\n OSPVolume volume;\n OSPFrameBuffer fb;\n OSPRenderer renderer;\n OSPCamera camera;\n int resampleSize;\n ospray::glut3D::FPSCounter fps;\n };\n\n void ospDVRMain(int &ac, const char **&av)\n {\n ospLoadModule(\"dvr\");\n\n if (ac < 5) \n error(\"no input scene specified (or done so in wrong format)\");\n \n vec3i volDims;\n std::string volFileName;\n int resample = 0;\n\n for (int i=1;i<ac;i++) {\n std::string arg = av[i];\n if (arg[0] != '-') {\n volDims.x = atoi(av[i+0]);\n volDims.y = atoi(av[i+1]);\n volDims.z = atoi(av[i+2]);\n volFileName = av[i+3];\n i += 3;\n } else if (arg == \"--resample\") {\n \/\/ resample volume to this size\n resample = atoi(av[++i]);\n } else if (arg == \"--ispc\") {\n \/\/ resample volume to this size\n renderType = \"dvr_ispc\";\n } else if (arg == \"--scalar\") {\n \/\/ resample volume to this size\n renderType = \"dvr_scalar\";\n } else \n throw std::runtime_error(\"unknown parameter \"+arg);\n }\n \/\/ const vec3i volDims(atoi(av[1]),\n \/\/ atoi(av[2]),\n \/\/ atoi(av[3]));\n \/\/ const std::string volFileName = av[4];\n \n \/\/ -------------------------------------------------------\n \/\/ create viewer window\n \/\/ -------------------------------------------------------\n VolumeViewer window(volDims,volFileName,resample);\n window.create(\"ospDVR: OSPRay miniature DVR volume viewer\");\n printf(\"Viewer created. Press 'Q' to quit.\\n\");\n window.setWorldBounds(box3f(vec3f(0.f),vec3f(1.f)));\n \/\/ window.setWorldBounds(box3f(vec3f(0.f),vec3f(resample?vec3i(resample):volDims)));\n ospray::glut3D::runGLUT();\n }\n}\n\nint main(int ac, const char **av)\n{\n ospInit(&ac,av);\n ospray::glut3D::initGLUT(&ac,av);\n ospray::ospDVRMain(ac,av);\n}\n<commit_msg>setting stepsize automatically based on volume dims<commit_after>\/*! \\file ospDVR.cpp A GLUT-based viewer for Wavefront OBJ files *\/\n\n\/\/ viewer widget\n#include \"..\/..\/apps\/util\/glut3D\/glut3D.h\"\n\/\/ ospray, for rendering\n#include \"ospray\/ospray.h\"\n\nnamespace ospray {\n using std::cout;\n using std::endl;\n\n const char *renderType = \"dvr_ispc\";\n\n \/*! \\page volview_notes_on_volume_interface Internal Notes on Volume Interface\n\n Right now i'm using a trivially simple interface to ospray's\n volume code by simply passing filename and dimensions right into\n the ospray volume object, which then does its own parsing *inside*\n ospray. this is, however, not as it should eventually be - to be\n fixed! *\/\n\n void error(const std::string &vol)\n {\n cout << \"ospray::ospDVR fatal error : \" << vol << endl;\n cout << endl;\n cout << \"Proper usage: \" << endl;\n cout << \" .\/ospDVR <sizex> <sizey> <sizez> volFile.raw\" << std::endl;\n cout << endl;\n exit(1);\n }\n\n using ospray::glut3D::Glut3DWidget;\n\n \/\/! volume viewer widget. \n \/*! \\internal Note that all handling of camera is almost exactly\n similar to the code in msgView; might make sense to move that into\n a common class! *\/\n struct VolumeViewer : public Glut3DWidget {\n \/*! construct volume from file name and dimensions \\see volview_notes_on_volume_interface *\/\n VolumeViewer(const vec3i dims, const std::string &fileName, int resampleSize=0) \n : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE),\n fb(NULL), renderer(NULL), volume(NULL), \n dims(dims), fileName(fileName), resampleSize(resampleSize)\n {\n camera = ospNewCamera(\"perspective\");\n Assert2(camera,\"could not create camera\");\n ospSet3f(camera,\"pos\",-1,1,-1);\n ospSet3f(camera,\"dir\",+1,-1,+1);\n ospCommit(camera);\n ospCommit(camera);\n\n volume = ospNewVolume(\"naive32-uint8\");\n Assert(volume && \"null volume handle\");\n ospSet3i(volume,\"dimensions\",dims.x,dims.y,dims.z);\n \/\/ ospSet3i(volume,\"resample_dimensions\",resampleSize,resampleSize,resampleSize);\n ospSetString(volume,\"filename\",fileName.c_str());\n ospCommit(volume);\n\n renderer = ospNewRenderer(renderType);\n ospSet1f(renderer,\"dt\",0.5f\/std::max(dims.x,std::max(dims.y,dims.z)));\n\n Assert2(renderer,\"could not create renderer\");\n ospSetParam(renderer,\"volume\",volume);\n ospSetParam(renderer,\"camera\",camera);\n ospCommit(renderer);\n\n };\n virtual void reshape(const ospray::vec2i &newSize) \n {\n Glut3DWidget::reshape(newSize);\n if (fb) ospFreeFrameBuffer(fb);\n fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8);\n ospSetf(camera,\"aspect\",viewPort.aspect);\n ospCommit(camera);\n }\n\n virtual void display() \n {\n if (!fb || !renderer) return;\n\n if (viewPort.modified) {\n Assert2(camera,\"ospray camera is null\");\n \n \/\/ PRINT(viewPort);\n \n ospSetVec3f(camera,\"pos\",viewPort.from);\n ospSetVec3f(camera,\"dir\",viewPort.at-viewPort.from);\n ospSetVec3f(camera,\"up\",viewPort.up);\n ospSetf(camera,\"aspect\",viewPort.aspect);\n ospCommit(camera);\n viewPort.modified = false;\n }\n\n fps.startRender();\n ospRenderFrame(fb,renderer);\n fps.doneRender();\n \n ucharFB = (unsigned int *)ospMapFrameBuffer(fb);\n frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR;\n Glut3DWidget::display();\n \n ospUnmapFrameBuffer(ucharFB,fb);\n \n char title[1000];\n \n sprintf(title,\"Test04: GlutWidget+ospray API rest (%f fps)\",\n fps.getFPS());\n setTitle(title);\n forceRedraw();\n }\n\n std::string fileName; \/*! volume file name \\see volview_notes_on_volume_interface *\/\n vec3i dims; \/*! volume dimensions \\see volview_notes_on_volume_interface *\/\n OSPVolume volume;\n OSPFrameBuffer fb;\n OSPRenderer renderer;\n OSPCamera camera;\n int resampleSize;\n ospray::glut3D::FPSCounter fps;\n };\n\n void ospDVRMain(int &ac, const char **&av)\n {\n ospLoadModule(\"dvr\");\n\n if (ac < 5) \n error(\"no input scene specified (or done so in wrong format)\");\n \n vec3i volDims;\n std::string volFileName;\n int resample = 0;\n\n for (int i=1;i<ac;i++) {\n std::string arg = av[i];\n if (arg[0] != '-') {\n volDims.x = atoi(av[i+0]);\n volDims.y = atoi(av[i+1]);\n volDims.z = atoi(av[i+2]);\n volFileName = av[i+3];\n i += 3;\n } else if (arg == \"--resample\") {\n \/\/ resample volume to this size\n resample = atoi(av[++i]);\n } else if (arg == \"--ispc\") {\n \/\/ resample volume to this size\n renderType = \"dvr_ispc\";\n } else if (arg == \"--scalar\") {\n \/\/ resample volume to this size\n renderType = \"dvr_scalar\";\n } else \n throw std::runtime_error(\"unknown parameter \"+arg);\n }\n \/\/ const vec3i volDims(atoi(av[1]),\n \/\/ atoi(av[2]),\n \/\/ atoi(av[3]));\n \/\/ const std::string volFileName = av[4];\n \n \/\/ -------------------------------------------------------\n \/\/ create viewer window\n \/\/ -------------------------------------------------------\n VolumeViewer window(volDims,volFileName,resample);\n window.create(\"ospDVR: OSPRay miniature DVR volume viewer\");\n printf(\"Viewer created. Press 'Q' to quit.\\n\");\n window.setWorldBounds(box3f(vec3f(0.f),vec3f(1.f)));\n \/\/ window.setWorldBounds(box3f(vec3f(0.f),vec3f(resample?vec3i(resample):volDims)));\n ospray::glut3D::runGLUT();\n }\n}\n\nint main(int ac, const char **av)\n{\n ospInit(&ac,av);\n ospray::glut3D::initGLUT(&ac,av);\n ospray::ospDVRMain(ac,av);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * LinuxFileMonitor.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/system\/FileMonitor.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Error.hpp>\n#include <core\/FileInfo.hpp>\n\n#include <core\/system\/FileScanner.hpp>\n#include <core\/system\/System.hpp>\n\n#include \"FileMonitorImpl.hpp\"\n\nnamespace core {\nnamespace system {\nnamespace file_monitor {\n\nnamespace {\n\n\n\n} \/\/ anonymous namespace\n\nnamespace detail {\n\n\/\/ register a new file monitor\nHandle registerMonitor(const core::FilePath& filePath,\n bool recursive,\n const Callbacks& callbacks)\n{\n return Handle();\n}\n\n\/\/ unregister a file monitor\nvoid unregisterMonitor(Handle handle)\n{\n\n}\n\nvoid run(const boost::function<void()>& checkForInput)\n{\n\n}\n\nvoid stop()\n{\n\n}\n\n} \/\/ namespace detail\n} \/\/ namespace file_monitor\n} \/\/ namespace system\n} \/\/ namespace core \n\n \n\n\n\n<commit_msg>add todos<commit_after>\/*\n * LinuxFileMonitor.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/system\/FileMonitor.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Error.hpp>\n#include <core\/FileInfo.hpp>\n\n#include <core\/system\/FileScanner.hpp>\n#include <core\/system\/System.hpp>\n\n#include \"FileMonitorImpl.hpp\"\n\n\/\/ TODO: investigate parallel package (multicore) interactions with file monitor\n\n\/\/ TODO: should we be using lstat64?\n\nnamespace core {\nnamespace system {\nnamespace file_monitor {\n\nnamespace {\n\n\n\n} \/\/ anonymous namespace\n\nnamespace detail {\n\n\/\/ register a new file monitor\nHandle registerMonitor(const core::FilePath& filePath,\n bool recursive,\n const Callbacks& callbacks)\n{\n return Handle();\n}\n\n\/\/ unregister a file monitor\nvoid unregisterMonitor(Handle handle)\n{\n\n}\n\nvoid run(const boost::function<void()>& checkForInput)\n{\n\n}\n\nvoid stop()\n{\n\n}\n\n} \/\/ namespace detail\n} \/\/ namespace file_monitor\n} \/\/ namespace system\n} \/\/ namespace core \n\n \n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2018 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include \"xversionmessage.h\"\n#include \"hashwrapper.h\"\n#include \"random.h\"\n#include \"streams.h\"\n#include \"util.h\"\n\n\nbool xversion_deterministic_hashing = false;\n\nXMapSaltedHasher::XMapSaltedHasher()\n : k0(xversion_deterministic_hashing ? 0x1122334455667788UL : GetRand(std::numeric_limits<uint64_t>::max())),\n k1(xversion_deterministic_hashing ? 0x99aabbccddeeff00UL : GetRand(std::numeric_limits<uint64_t>::max()))\n{\n}\n\nuint64_t XMapSaltedHasher::operator()(const uint64_t key) const\n{\n CSipHasher hasher(k0, k1);\n return hasher.Write(key).Finalize();\n}\n\nuint64_t CXVersionMessage::as_u64c(const uint64_t k) const\n{\n if (xmap.count(k) == 0)\n return 0;\n LOCK(cacheProtector);\n if (cache_u64c.count(k) == 0)\n {\n const std::vector<uint8_t> &vec = xmap.at(k);\n uint64_t v = 0;\n try\n {\n CDataStream s(vec, SER_NETWORK, PROTOCOL_VERSION);\n s >> COMPACTSIZE(v);\n }\n catch (...)\n {\n LOG(NET, \"Error reading extended configuration key %016llx as u64c. Assuming zero.\\n\", k);\n v = 0;\n }\n cache_u64c[k] = v;\n }\n return cache_u64c.at(k);\n}\n\nvoid CXVersionMessage::set_u64c(const uint64_t key, const uint64_t val)\n{\n CDataStream s(SER_NETWORK, PROTOCOL_VERSION);\n s << COMPACTSIZE(val);\n\n std::vector<uint8_t> vec;\n vec.insert(vec.begin(), s.begin(), s.end());\n xmap[key] = vec;\n LOCK(cacheProtector);\n cache_u64c[key] = val;\n}\n<commit_msg>move lock before count to solve potential segfault issue where map can be read and written to at the same time<commit_after>\/\/ Copyright (C) 2018 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include \"xversionmessage.h\"\n#include \"hashwrapper.h\"\n#include \"random.h\"\n#include \"streams.h\"\n#include \"util.h\"\n\n\nbool xversion_deterministic_hashing = false;\n\nXMapSaltedHasher::XMapSaltedHasher()\n : k0(xversion_deterministic_hashing ? 0x1122334455667788UL : GetRand(std::numeric_limits<uint64_t>::max())),\n k1(xversion_deterministic_hashing ? 0x99aabbccddeeff00UL : GetRand(std::numeric_limits<uint64_t>::max()))\n{\n}\n\nuint64_t XMapSaltedHasher::operator()(const uint64_t key) const\n{\n CSipHasher hasher(k0, k1);\n return hasher.Write(key).Finalize();\n}\n\nuint64_t CXVersionMessage::as_u64c(const uint64_t k) const\n{\n LOCK(cacheProtector);\n if (xmap.count(k) == 0)\n return 0;\n if (cache_u64c.count(k) == 0)\n {\n const std::vector<uint8_t> &vec = xmap.at(k);\n uint64_t v = 0;\n try\n {\n CDataStream s(vec, SER_NETWORK, PROTOCOL_VERSION);\n s >> COMPACTSIZE(v);\n }\n catch (...)\n {\n LOG(NET, \"Error reading extended configuration key %016llx as u64c. Assuming zero.\\n\", k);\n v = 0;\n }\n cache_u64c[k] = v;\n }\n return cache_u64c.at(k);\n}\n\nvoid CXVersionMessage::set_u64c(const uint64_t key, const uint64_t val)\n{\n CDataStream s(SER_NETWORK, PROTOCOL_VERSION);\n s << COMPACTSIZE(val);\n\n std::vector<uint8_t> vec;\n vec.insert(vec.begin(), s.begin(), s.end());\n xmap[key] = vec;\n LOCK(cacheProtector);\n cache_u64c[key] = val;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __PROCESS_PROCESS_HPP__\n#define __PROCESS_PROCESS_HPP__\n\n#include <stdint.h>\n#include <pthread.h>\n\n#include <map>\n#include <queue>\n\n#include <process\/address.hpp>\n#include <process\/clock.hpp>\n#include <process\/event.hpp>\n#include <process\/filter.hpp>\n#include <process\/http.hpp>\n#include <process\/message.hpp>\n#include <process\/mime.hpp>\n#include <process\/pid.hpp>\n\n#include <stout\/duration.hpp>\n#include <stout\/lambda.hpp>\n#include <stout\/option.hpp>\n#include <stout\/thread.hpp>\n\nnamespace process {\n\nclass ProcessBase : public EventVisitor\n{\npublic:\n explicit ProcessBase(const std::string& id = \"\");\n\n virtual ~ProcessBase();\n\n UPID self() const { return pid; }\n\nprotected:\n \/\/ Invoked when an event is serviced.\n virtual void serve(const Event& event)\n {\n event.visit(this);\n }\n\n \/\/ Callbacks used to visit (i.e., handle) a specific event.\n virtual void visit(const MessageEvent& event);\n virtual void visit(const DispatchEvent& event);\n virtual void visit(const HttpEvent& event);\n virtual void visit(const ExitedEvent& event);\n virtual void visit(const TerminateEvent& event);\n\n \/\/ Invoked when a process gets spawned.\n virtual void initialize() {}\n\n \/\/ Invoked when a process is terminated (unless visit is overriden).\n virtual void finalize() {}\n\n \/\/ Invoked when a linked process has exited (see link).\n virtual void exited(const UPID& pid) {}\n\n \/\/ Invoked when a linked process can no longer be monitored (see link).\n virtual void lost(const UPID& pid) {}\n\n \/\/ Puts a message at front of queue.\n void inject(\n const UPID& from,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n \/\/ Sends a message with data to PID.\n void send(\n const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n \/\/ Links with the specified PID. Linking with a process from within\n \/\/ the same \"operating system process\" is gauranteed to give you\n \/\/ perfect monitoring of that process. However, linking with a\n \/\/ process on another machine might result in receiving lost\n \/\/ callbacks due to the nature of a distributed environment.\n UPID link(const UPID& pid);\n\n \/\/ The default visit implementation for message events invokes\n \/\/ installed message handlers, or delegates the message to another\n \/\/ process (a delegate can be installed below but a message handler\n \/\/ always takes precedence over delegating). A message handler is\n \/\/ any function which takes two arguments, the \"from\" pid and the\n \/\/ message body.\n typedef lambda::function<void(const UPID&, const std::string&)>\n MessageHandler;\n\n \/\/ Setup a handler for a message.\n void install(\n const std::string& name,\n const MessageHandler& handler)\n {\n handlers.message[name] = handler;\n }\n\n template <typename T>\n void install(\n const std::string& name,\n void (T::*method)(const UPID&, const std::string&))\n {\n \/\/ Note that we use dynamic_cast here so a process can use\n \/\/ multiple inheritance if it sees so fit (e.g., to implement\n \/\/ multiple callback interfaces).\n MessageHandler handler =\n lambda::bind(method, dynamic_cast<T*>(this), lambda::_1, lambda::_2);\n install(name, handler);\n }\n\n \/\/ Delegate incoming message's with the specified name to pid.\n void delegate(const std::string& name, const UPID& pid)\n {\n delegates[name] = pid;\n }\n\n \/\/ The default visit implementation for HTTP events invokes\n \/\/ installed HTTP handlers. A HTTP handler is any function which\n \/\/ takes an http::Request object and returns an http::Response.\n typedef lambda::function<Future<http::Response>(const http::Request&)>\n HttpRequestHandler;\n\n \/\/ Setup a handler for an HTTP request.\n void route(\n const std::string& name,\n const Option<std::string>& help,\n const HttpRequestHandler& handler);\n\n template <typename T>\n void route(\n const std::string& name,\n const Option<std::string>& help,\n Future<http::Response> (T::*method)(const http::Request&))\n {\n \/\/ Note that we use dynamic_cast here so a process can use\n \/\/ multiple inheritance if it sees so fit (e.g., to implement\n \/\/ multiple callback interfaces).\n HttpRequestHandler handler =\n lambda::bind(method, dynamic_cast<T*>(this), lambda::_1);\n route(name, help, handler);\n }\n\n \/\/ Provide the static asset(s) at the specified _absolute_ path for\n \/\/ the specified name. For example, assuming the process named\n \/\/ \"server\" invoked 'provide(\"name\", \"path\")' then an HTTP request\n \/\/ for '\/server\/name' would return the asset found at 'path'. If the\n \/\/ specified path is a directory then an HTTP request for\n \/\/ '\/server\/name\/file' would return the asset found at\n \/\/ '\/path\/file'. The 'Content-Type' header of the HTTP response will\n \/\/ be set to the specified type given the file extension (you can\n \/\/ manipulate this via the optional 'types' parameter).\n void provide(\n const std::string& name,\n const std::string& path,\n const std::map<std::string, std::string>& types = mime::types)\n {\n \/\/ TODO(benh): Check that name is only alphanumeric (i.e., has no\n \/\/ '\/') and that path is absolute.\n Asset asset;\n asset.path = path;\n asset.types = types;\n assets[name] = asset;\n }\n\n void lock()\n {\n pthread_mutex_lock(&m);\n }\n\n void unlock()\n {\n pthread_mutex_unlock(&m);\n }\n\n template<typename T>\n size_t eventCount()\n {\n size_t count = 0U;\n\n lock();\n count = std::count_if(events.begin(), events.end(), isEventType<T>);\n unlock();\n\n return count;\n }\n\nprivate:\n friend class SocketManager;\n friend class ProcessManager;\n friend class ProcessReference;\n friend void* schedule(void*);\n\n \/\/ Process states.\n enum {\n BOTTOM,\n READY,\n RUNNING,\n BLOCKED,\n TERMINATING,\n TERMINATED\n } state;\n\n template<typename T>\n static bool isEventType(const Event* event)\n {\n return event->is<T>();\n }\n\n \/\/ Mutex protecting internals.\n \/\/ TODO(benh): Consider replacing with a spinlock, on multi-core systems.\n pthread_mutex_t m;\n\n \/\/ Enqueue the specified message, request, or function call.\n void enqueue(Event* event, bool inject = false);\n\n \/\/ Delegates for messages.\n std::map<std::string, UPID> delegates;\n\n \/\/ Handlers for messages and HTTP requests.\n struct {\n std::map<std::string, MessageHandler> message;\n std::map<std::string, HttpRequestHandler> http;\n } handlers;\n\n \/\/ Definition of a static asset.\n struct Asset\n {\n std::string path;\n std::map<std::string, std::string> types;\n };\n\n \/\/ Static assets(s) to provide.\n std::map<std::string, Asset> assets;\n\n \/\/ Queue of received events, requires lock()ed access!\n std::deque<Event*> events;\n\n \/\/ Active references.\n int refs;\n\n \/\/ Process PID.\n UPID pid;\n};\n\n\ntemplate <typename T>\nclass Process : public virtual ProcessBase {\npublic:\n virtual ~Process() {}\n\n \/\/ Returns pid of process; valid even before calling spawn.\n PID<T> self() const { return PID<T>(dynamic_cast<const T*>(this)); }\n\nprotected:\n \/\/ Useful typedefs for dispatch\/delay\/defer to self()\/this.\n typedef T Self;\n typedef T This;\n};\n\n\n\/**\n * Initialize the library. Note that libprocess uses Google's glog and\n * you can specify options for it (e.g., a logging directory) via\n * environment variables (see the glog documentation for more\n * information).\n *\n * @param delegate process to receive root HTTP requests\n *\/\nvoid initialize(const std::string& delegate = \"\");\n\n\n\/**\n * Clean up the library.\n *\/\nvoid finalize();\n\n\n\/**\n * Returns the socket address associated with this instance of the library.\n *\/\nnetwork::Address address();\n\n\n\/**\n * Spawn a new process.\n *\n * @param process process to be spawned\n * @param manage boolean whether process should get garbage collected\n *\/\nUPID spawn(ProcessBase* process, bool manage = false);\n\ninline UPID spawn(ProcessBase& process, bool manage = false)\n{\n return spawn(&process, manage);\n}\n\ntemplate <typename T>\nPID<T> spawn(T* t, bool manage = false)\n{\n \/\/ We save the pid before spawn is called because it's possible that\n \/\/ the process has already been deleted after spawn returns (e.g.,\n \/\/ if 'manage' is true).\n PID<T> pid(t);\n\n if (!spawn(static_cast<ProcessBase*>(t), manage)) {\n return PID<T>();\n }\n\n return pid;\n}\n\ntemplate <typename T>\nPID<T> spawn(T& t, bool manage = false)\n{\n return spawn(&t, manage);\n}\n\n\n\/**\n * Send a TERMINATE message to a process, injecting the message ahead\n * of all other messages queued up for that process if requested. Note\n * that currently terminate only works for local processes (in the\n * future we plan to make this more explicit via the use of a PID\n * instead of a UPID).\n *\n * @param inject if true message will be put on front of message queue\n *\/\nvoid terminate(const UPID& pid, bool inject = true);\nvoid terminate(const ProcessBase& process, bool inject = true);\nvoid terminate(const ProcessBase* process, bool inject = true);\n\n\n\/**\n * Wait for process to exit no more than specified seconds (returns\n * true if actually waited on a process).\n *\n * @param PID id of the process\n * @param secs max time to wait, 0 implies wait for ever\n *\/\nbool wait(const UPID& pid, const Duration& duration = Seconds(-1));\nbool wait(const ProcessBase& process, const Duration& duration = Seconds(-1));\nbool wait(const ProcessBase* process, const Duration& duration = Seconds(-1));\n\n\n\/**\n * Sends a message with data without a return address.\n *\n * @param to receiver\n * @param name message name\n * @param data data to send (gets copied)\n * @param length length of data\n *\/\nvoid post(const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n\nvoid post(const UPID& from,\n const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n\n\/\/ Inline implementations of above.\ninline void terminate(const ProcessBase& process, bool inject)\n{\n terminate(process.self(), inject);\n}\n\n\ninline void terminate(const ProcessBase* process, bool inject)\n{\n terminate(process->self(), inject);\n}\n\n\ninline bool wait(const ProcessBase& process, const Duration& duration)\n{\n return process::wait(process.self(), duration); \/\/ Explicit to disambiguate.\n}\n\n\ninline bool wait(const ProcessBase* process, const Duration& duration)\n{\n return process::wait(process->self(), duration); \/\/ Explicit to disambiguate.\n}\n\n\n\/\/ Per thread process pointer. The extra level of indirection from\n\/\/ _process_ to __process__ is used in order to take advantage of the\n\/\/ ThreadLocal operators without needing the extra dereference.\nextern ThreadLocal<ProcessBase>* _process_;\n\n#define __process__ (*_process_)\n\n\/\/ NOTE: Methods in this namespace should only be used in tests to\n\/\/ inject arbitrary events.\nnamespace inject {\n\/\/ Simulates disconnection of the link between 'from' and 'to' by\n\/\/ sending an 'ExitedEvent' to 'to'.\nbool exited(const UPID& from, const UPID& to);\n} \/\/ namespace inject {\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_PROCESS_HPP__\n<commit_msg>Fix typo in comment.<commit_after>#ifndef __PROCESS_PROCESS_HPP__\n#define __PROCESS_PROCESS_HPP__\n\n#include <stdint.h>\n#include <pthread.h>\n\n#include <map>\n#include <queue>\n\n#include <process\/address.hpp>\n#include <process\/clock.hpp>\n#include <process\/event.hpp>\n#include <process\/filter.hpp>\n#include <process\/http.hpp>\n#include <process\/message.hpp>\n#include <process\/mime.hpp>\n#include <process\/pid.hpp>\n\n#include <stout\/duration.hpp>\n#include <stout\/lambda.hpp>\n#include <stout\/option.hpp>\n#include <stout\/thread.hpp>\n\nnamespace process {\n\nclass ProcessBase : public EventVisitor\n{\npublic:\n explicit ProcessBase(const std::string& id = \"\");\n\n virtual ~ProcessBase();\n\n UPID self() const { return pid; }\n\nprotected:\n \/\/ Invoked when an event is serviced.\n virtual void serve(const Event& event)\n {\n event.visit(this);\n }\n\n \/\/ Callbacks used to visit (i.e., handle) a specific event.\n virtual void visit(const MessageEvent& event);\n virtual void visit(const DispatchEvent& event);\n virtual void visit(const HttpEvent& event);\n virtual void visit(const ExitedEvent& event);\n virtual void visit(const TerminateEvent& event);\n\n \/\/ Invoked when a process gets spawned.\n virtual void initialize() {}\n\n \/\/ Invoked when a process is terminated (unless visit is overriden).\n virtual void finalize() {}\n\n \/\/ Invoked when a linked process has exited (see link).\n virtual void exited(const UPID& pid) {}\n\n \/\/ Invoked when a linked process can no longer be monitored (see link).\n virtual void lost(const UPID& pid) {}\n\n \/\/ Puts a message at front of queue.\n void inject(\n const UPID& from,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n \/\/ Sends a message with data to PID.\n void send(\n const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n \/\/ Links with the specified PID. Linking with a process from within\n \/\/ the same \"operating system process\" is guaranteed to give you\n \/\/ perfect monitoring of that process. However, linking with a\n \/\/ process on another machine might result in receiving lost\n \/\/ callbacks due to the nature of a distributed environment.\n UPID link(const UPID& pid);\n\n \/\/ The default visit implementation for message events invokes\n \/\/ installed message handlers, or delegates the message to another\n \/\/ process (a delegate can be installed below but a message handler\n \/\/ always takes precedence over delegating). A message handler is\n \/\/ any function which takes two arguments, the \"from\" pid and the\n \/\/ message body.\n typedef lambda::function<void(const UPID&, const std::string&)>\n MessageHandler;\n\n \/\/ Setup a handler for a message.\n void install(\n const std::string& name,\n const MessageHandler& handler)\n {\n handlers.message[name] = handler;\n }\n\n template <typename T>\n void install(\n const std::string& name,\n void (T::*method)(const UPID&, const std::string&))\n {\n \/\/ Note that we use dynamic_cast here so a process can use\n \/\/ multiple inheritance if it sees so fit (e.g., to implement\n \/\/ multiple callback interfaces).\n MessageHandler handler =\n lambda::bind(method, dynamic_cast<T*>(this), lambda::_1, lambda::_2);\n install(name, handler);\n }\n\n \/\/ Delegate incoming message's with the specified name to pid.\n void delegate(const std::string& name, const UPID& pid)\n {\n delegates[name] = pid;\n }\n\n \/\/ The default visit implementation for HTTP events invokes\n \/\/ installed HTTP handlers. A HTTP handler is any function which\n \/\/ takes an http::Request object and returns an http::Response.\n typedef lambda::function<Future<http::Response>(const http::Request&)>\n HttpRequestHandler;\n\n \/\/ Setup a handler for an HTTP request.\n void route(\n const std::string& name,\n const Option<std::string>& help,\n const HttpRequestHandler& handler);\n\n template <typename T>\n void route(\n const std::string& name,\n const Option<std::string>& help,\n Future<http::Response> (T::*method)(const http::Request&))\n {\n \/\/ Note that we use dynamic_cast here so a process can use\n \/\/ multiple inheritance if it sees so fit (e.g., to implement\n \/\/ multiple callback interfaces).\n HttpRequestHandler handler =\n lambda::bind(method, dynamic_cast<T*>(this), lambda::_1);\n route(name, help, handler);\n }\n\n \/\/ Provide the static asset(s) at the specified _absolute_ path for\n \/\/ the specified name. For example, assuming the process named\n \/\/ \"server\" invoked 'provide(\"name\", \"path\")' then an HTTP request\n \/\/ for '\/server\/name' would return the asset found at 'path'. If the\n \/\/ specified path is a directory then an HTTP request for\n \/\/ '\/server\/name\/file' would return the asset found at\n \/\/ '\/path\/file'. The 'Content-Type' header of the HTTP response will\n \/\/ be set to the specified type given the file extension (you can\n \/\/ manipulate this via the optional 'types' parameter).\n void provide(\n const std::string& name,\n const std::string& path,\n const std::map<std::string, std::string>& types = mime::types)\n {\n \/\/ TODO(benh): Check that name is only alphanumeric (i.e., has no\n \/\/ '\/') and that path is absolute.\n Asset asset;\n asset.path = path;\n asset.types = types;\n assets[name] = asset;\n }\n\n void lock()\n {\n pthread_mutex_lock(&m);\n }\n\n void unlock()\n {\n pthread_mutex_unlock(&m);\n }\n\n template<typename T>\n size_t eventCount()\n {\n size_t count = 0U;\n\n lock();\n count = std::count_if(events.begin(), events.end(), isEventType<T>);\n unlock();\n\n return count;\n }\n\nprivate:\n friend class SocketManager;\n friend class ProcessManager;\n friend class ProcessReference;\n friend void* schedule(void*);\n\n \/\/ Process states.\n enum {\n BOTTOM,\n READY,\n RUNNING,\n BLOCKED,\n TERMINATING,\n TERMINATED\n } state;\n\n template<typename T>\n static bool isEventType(const Event* event)\n {\n return event->is<T>();\n }\n\n \/\/ Mutex protecting internals.\n \/\/ TODO(benh): Consider replacing with a spinlock, on multi-core systems.\n pthread_mutex_t m;\n\n \/\/ Enqueue the specified message, request, or function call.\n void enqueue(Event* event, bool inject = false);\n\n \/\/ Delegates for messages.\n std::map<std::string, UPID> delegates;\n\n \/\/ Handlers for messages and HTTP requests.\n struct {\n std::map<std::string, MessageHandler> message;\n std::map<std::string, HttpRequestHandler> http;\n } handlers;\n\n \/\/ Definition of a static asset.\n struct Asset\n {\n std::string path;\n std::map<std::string, std::string> types;\n };\n\n \/\/ Static assets(s) to provide.\n std::map<std::string, Asset> assets;\n\n \/\/ Queue of received events, requires lock()ed access!\n std::deque<Event*> events;\n\n \/\/ Active references.\n int refs;\n\n \/\/ Process PID.\n UPID pid;\n};\n\n\ntemplate <typename T>\nclass Process : public virtual ProcessBase {\npublic:\n virtual ~Process() {}\n\n \/\/ Returns pid of process; valid even before calling spawn.\n PID<T> self() const { return PID<T>(dynamic_cast<const T*>(this)); }\n\nprotected:\n \/\/ Useful typedefs for dispatch\/delay\/defer to self()\/this.\n typedef T Self;\n typedef T This;\n};\n\n\n\/**\n * Initialize the library. Note that libprocess uses Google's glog and\n * you can specify options for it (e.g., a logging directory) via\n * environment variables (see the glog documentation for more\n * information).\n *\n * @param delegate process to receive root HTTP requests\n *\/\nvoid initialize(const std::string& delegate = \"\");\n\n\n\/**\n * Clean up the library.\n *\/\nvoid finalize();\n\n\n\/**\n * Returns the socket address associated with this instance of the library.\n *\/\nnetwork::Address address();\n\n\n\/**\n * Spawn a new process.\n *\n * @param process process to be spawned\n * @param manage boolean whether process should get garbage collected\n *\/\nUPID spawn(ProcessBase* process, bool manage = false);\n\ninline UPID spawn(ProcessBase& process, bool manage = false)\n{\n return spawn(&process, manage);\n}\n\ntemplate <typename T>\nPID<T> spawn(T* t, bool manage = false)\n{\n \/\/ We save the pid before spawn is called because it's possible that\n \/\/ the process has already been deleted after spawn returns (e.g.,\n \/\/ if 'manage' is true).\n PID<T> pid(t);\n\n if (!spawn(static_cast<ProcessBase*>(t), manage)) {\n return PID<T>();\n }\n\n return pid;\n}\n\ntemplate <typename T>\nPID<T> spawn(T& t, bool manage = false)\n{\n return spawn(&t, manage);\n}\n\n\n\/**\n * Send a TERMINATE message to a process, injecting the message ahead\n * of all other messages queued up for that process if requested. Note\n * that currently terminate only works for local processes (in the\n * future we plan to make this more explicit via the use of a PID\n * instead of a UPID).\n *\n * @param inject if true message will be put on front of message queue\n *\/\nvoid terminate(const UPID& pid, bool inject = true);\nvoid terminate(const ProcessBase& process, bool inject = true);\nvoid terminate(const ProcessBase* process, bool inject = true);\n\n\n\/**\n * Wait for process to exit no more than specified seconds (returns\n * true if actually waited on a process).\n *\n * @param PID id of the process\n * @param secs max time to wait, 0 implies wait for ever\n *\/\nbool wait(const UPID& pid, const Duration& duration = Seconds(-1));\nbool wait(const ProcessBase& process, const Duration& duration = Seconds(-1));\nbool wait(const ProcessBase* process, const Duration& duration = Seconds(-1));\n\n\n\/**\n * Sends a message with data without a return address.\n *\n * @param to receiver\n * @param name message name\n * @param data data to send (gets copied)\n * @param length length of data\n *\/\nvoid post(const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n\nvoid post(const UPID& from,\n const UPID& to,\n const std::string& name,\n const char* data = NULL,\n size_t length = 0);\n\n\n\/\/ Inline implementations of above.\ninline void terminate(const ProcessBase& process, bool inject)\n{\n terminate(process.self(), inject);\n}\n\n\ninline void terminate(const ProcessBase* process, bool inject)\n{\n terminate(process->self(), inject);\n}\n\n\ninline bool wait(const ProcessBase& process, const Duration& duration)\n{\n return process::wait(process.self(), duration); \/\/ Explicit to disambiguate.\n}\n\n\ninline bool wait(const ProcessBase* process, const Duration& duration)\n{\n return process::wait(process->self(), duration); \/\/ Explicit to disambiguate.\n}\n\n\n\/\/ Per thread process pointer. The extra level of indirection from\n\/\/ _process_ to __process__ is used in order to take advantage of the\n\/\/ ThreadLocal operators without needing the extra dereference.\nextern ThreadLocal<ProcessBase>* _process_;\n\n#define __process__ (*_process_)\n\n\/\/ NOTE: Methods in this namespace should only be used in tests to\n\/\/ inject arbitrary events.\nnamespace inject {\n\/\/ Simulates disconnection of the link between 'from' and 'to' by\n\/\/ sending an 'ExitedEvent' to 'to'.\nbool exited(const UPID& from, const UPID& to);\n} \/\/ namespace inject {\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_PROCESS_HPP__\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"global_config.hpp\"\n\nnamespace mocc {\n\n inline bool fp_equiv_ulp(float_t v1, float_t v2) {\n int i1 = *(int*) &v1;\n if (i1 < 0) {\n i1 = 0x80000000 - i1;\n }\n int i2 = *(int*) &v2;\n if (i2 < 0) {\n i2 = 0x80000000 - i2;\n }\n\n return abs(i1 - i2) < 100; \n }\n\n inline bool fp_equiv_rel(float_t v1, float_t v2) {\n return fabs(v1-v2)\/fabs(v1) < FLOAT_EPS;\n }\n inline bool fp_equiv_abs(float_t v1, float_t v2) {\n return fabs(v1-v2) < FLOAT_EPS;\n }\n}\n<commit_msg>Add inclusion for cmath in fp_utils.hpp<commit_after>#pragma once\n#include <cmath>\n\n#include \"global_config.hpp\"\n\nnamespace mocc {\n\n inline bool fp_equiv_ulp(float_t v1, float_t v2) {\n int i1 = *(int*) &v1;\n if (i1 < 0) {\n i1 = 0x80000000 - i1;\n }\n int i2 = *(int*) &v2;\n if (i2 < 0) {\n i2 = 0x80000000 - i2;\n }\n\n return abs(i1 - i2) < 100; \n }\n\n inline bool fp_equiv_rel(float_t v1, float_t v2) {\n return fabs(v1-v2)\/fabs(v1) < FLOAT_EPS;\n }\n inline bool fp_equiv_abs(float_t v1, float_t v2) {\n return fabs(v1-v2) < FLOAT_EPS;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/include\/InputManager.hpp\"\n\nInputManager::InputManager( sf::Event* event, sf::RenderWindow* window ) {\n this->event = event;\n this->window = window;\n}\n\nbool InputManager::keyPressed( const sf::Event::KeyEvent key ) {\n return event->type == sf::Event::KeyPressed && event->key.code == key.code;\n}\n\nbool InputManager::keyPressed( const std::vector< sf::Event::KeyEvent > keys ) {\n for( sf::Event::KeyEvent key : keys ) {\n if( keyPressed( key ) ) {\n return true;\n }\n }\n\n return false;\n}\n\nbool InputManager::keyReleased( const sf::Event::KeyEvent key ) {\n return event->type == sf::Event::KeyReleased && event->key.code == key.code;\n}\n\nbool InputManager::keyReleased( const std::vector< sf::Event::KeyEvent > keys ) {\n for( sf::Event::KeyEvent key : keys ) {\n if( keyReleased( key ) ) {\n return true;\n }\n }\n\n return false;\n}\n\nbool InputManager::isSpriteClicked( const sf::Mouse::Button& button, const sf::Sprite& sprite ) {\n if( sf::Mouse::isButtonPressed( button ) ) {\n if( sprite.getGlobalBounds().contains(\n sf::Vector2< float >( sf::Mouse::getPosition( *window ) ) ) ) {\n return true;\n }\n }\n\n return false;\n}\n<commit_msg>Melhorada a checagem do clique<commit_after>#include \"..\/..\/include\/InputManager.hpp\"\n#include \"..\/..\/include\/Collision.hpp\"\n\nInputManager::InputManager( sf::Event* event, sf::RenderWindow* window ) {\n this->event = event;\n this->window = window;\n}\n\nbool InputManager::keyPressed( const sf::Event::KeyEvent key ) {\n return event->type == sf::Event::KeyPressed && event->key.code == key.code;\n}\n\nbool InputManager::keyPressed( const std::vector< sf::Event::KeyEvent > keys ) {\n for( sf::Event::KeyEvent key : keys ) {\n if( keyPressed( key ) ) {\n return true;\n }\n }\n\n return false;\n}\n\nbool InputManager::keyReleased( const sf::Event::KeyEvent key ) {\n return event->type == sf::Event::KeyReleased && event->key.code == key.code;\n}\n\nbool InputManager::keyReleased( const std::vector< sf::Event::KeyEvent > keys ) {\n for( sf::Event::KeyEvent key : keys ) {\n if( keyReleased( key ) ) {\n return true;\n }\n }\n\n return false;\n}\n\nbool InputManager::isSpriteClicked( const sf::Mouse::Button& button, const sf::Sprite& sprite ) {\n if( sf::Mouse::isButtonPressed( button ) ) {\n sf::Vector2< float > vector( sf::Mouse::getPosition( *window ) );\n\n if( Collision::VectorPerfectTest( sprite, vector ) ) {\n return true;\n }\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n *\r\n * C R I S S C R O S S\r\n * A multi purpose cross platform library.\r\n * formerly Codename \"Technetium\"\r\n * project started August 14, 2006\r\n *\r\n * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net> and Rudolf Olah <omouse@gmail.com>.\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without modification, are\r\n * permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this list\r\n * of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice, this\r\n * list of conditions and the following disclaimer in the documentation and\/or other\r\n * materials provided with the distribution.\r\n * * Neither the name of Uplink Laboratories nor the names of its contributors may be\r\n * used to endorse or promote products derived from this software without specific\r\n * prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\r\n * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\r\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"universal_include.h\"\r\n#include \"core_exception.h\"\r\n#include \"core_io.h\"\r\n#include \"core_debug.h\"\r\n\r\n#include \"datastructures\/rbtree.h\"\r\n\r\nCoreIO *g_stderr;\r\nCoreIO *g_stdout;\r\n\r\n#ifdef DETECT_MEMORY_LEAKS\r\n\r\nusing namespace std;\r\n\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n_CrtMemState s1, s2, s3;\r\n#endif\r\n\r\nvoid ParseMemoryLeakFile ( char *_inputFilename, char *_outputFilename )\r\n{\r\n\r\n \/\/\r\n \/\/ Start up\r\n \/\/\r\n\r\n RedBlackTree <int, char *> combined;\r\n RedBlackTree <int, char *> frequency;\r\n int unrecognised = 0;\r\n\r\n \/\/\r\n \/\/ Open the file and start parsing\r\n \/\/\r\n\r\n std::ifstream memoryfile ( _inputFilename );\r\n\r\n while ( !memoryfile.eof () ) \r\n {\r\n char thisline [256];\r\n memoryfile.getline ( thisline, 256 );\r\n\r\n if ( !strncmp ( thisline, \" Data:\", 6 ) == 0 && \/\/ This line is a data line - useless to us\r\n strchr ( thisline, ':' ) ) { \/\/ This line does not have a source file location - useless to us\r\n\r\n \/\/ Get the size\r\n\r\n char *lastcomma = strrchr ( thisline, ',' );\r\n char *ssize = lastcomma+2;\r\n int size;\r\n char unused [32];\r\n sscanf ( ssize, \"%d %s\", &size, unused );\r\n\r\n \/\/ Get the source file name\r\n\r\n char *sourcelocation = thisline;\r\n char *colon = strrchr ( thisline, ':' );\r\n *(colon-1) = '\\x0';\r\n \r\n \/\/ Put the result into our BTree\r\n\r\n RedBlackTree <int, char *>::nodeType *btree = combined.findNode ( sourcelocation );\r\n if ( btree ) ((int) btree->data) += size;\r\n else combined.PutData ( sourcelocation, size );\r\n \r\n RedBlackTree <int, char *>::nodeType *freq = frequency.findNode ( sourcelocation );\r\n if ( freq ) ((int) freq->data) ++;\r\n else frequency.PutData ( sourcelocation, 1 );\r\n\r\n }\r\n else \r\n {\r\n char *lastcomma = strrchr ( thisline, ',' );\r\n \r\n if ( lastcomma ) \r\n {\r\n\r\n char *ssize = lastcomma+2;\r\n int size;\r\n char unused [32];\r\n sscanf ( ssize, \"%d %s\", &size, unused );\r\n\r\n unrecognised += size;\r\n }\r\n }\r\n }\r\n\r\n memoryfile.close ();\r\n\r\n \r\n \/\/\r\n \/\/ Sort the results into a list\r\n \/\/\r\n\r\n DArray <int> *sizes = combined.ConvertToDArray ();\r\n DArray <char *> *sources = combined.ConvertIndexToDArray ();\r\n LList <char *> sorted;\r\n int totalsize = 0;\r\n\r\n for ( int i = 0; i < sources->Size (); ++i )\r\n {\r\n char *newsource = sources->GetData (i);\r\n int newsize = sizes->GetData (i);\r\n totalsize += newsize;\r\n bool inserted = false;\r\n\r\n for ( int j = 0; j < sorted.Size (); ++j ) {\r\n\r\n char *existingsource = sorted.GetData (j);\r\n int existingsize = combined.GetData ( existingsource );\r\n\r\n if ( newsize <= existingsize ) {\r\n\r\n sorted.PutDataAtIndex ( newsource, j );\r\n inserted = true;\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n if ( !inserted ) sorted.PutDataAtEnd ( newsource );\r\n }\r\n\r\n\r\n \/\/\r\n \/\/ Open the output file\r\n \/\/\r\n\r\n FILE *output = fopen( _outputFilename, \"wt\" );\r\n\r\n \/\/\r\n \/\/ Print out our sorted list\r\n \/\/ \r\n\r\n fprintf ( output, \"Total recognised memory leaks : %d Kbytes\\n\", int(totalsize\/1024) );\r\n fprintf ( output, \"Total unrecognised memory leaks : %d Kbytes\\n\\n\", int(unrecognised\/1024) );\r\n \r\n for ( int k = sorted.Size () - 1; k >= 0; --k ) \r\n {\r\n\r\n char *source = sorted.GetData (k);\r\n int size = combined.GetData ( source );\r\n int freq = frequency.GetData ( source );\r\n\r\n if( size > 2048 )\r\n {\r\n fprintf ( output, \"%-95s (%d Kbytes in %d leaks)\\n\", source, int(size\/1024), freq );\r\n }\r\n else\r\n {\r\n fprintf ( output, \"%-95s (%d bytes in %d leaks)\\n\", source, size, freq );\r\n }\r\n }\r\n\r\n\r\n \/\/\r\n \/\/ Clear up\r\n\r\n fclose( output );\r\n\r\n delete sources;\r\n delete sizes;\r\n}\r\n\r\n\r\nvoid AppPrintMemoryLeaks( char *_filename )\r\n{\r\n \/\/\r\n \/\/ Print all raw memory leak data to a temporary file\r\n\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemCheckpoint ( &s2 );\r\n#endif\r\n\r\n char tmpFilename[512];\r\n sprintf( tmpFilename, \"%s.tmp\", _filename );\r\n\r\n OFSTRUCT ofstruct;\r\n HFILE file = OpenFile ( tmpFilename,\r\n &ofstruct,\r\n OF_CREATE );\r\n \r\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\r\n _CrtSetReportFile(_CRT_WARN, (_HFILE)file);\r\n\r\n\t_CrtDumpMemoryLeaks ();\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemDifference ( &s3, &s1, &s2 );\r\n\t_CrtMemDumpStatistics ( &s3 );\r\n#endif\r\n\r\n _lclose ( file );\r\n\r\n\r\n \/\/\r\n \/\/ Parse the temp file into a sensible format\r\n\r\n ParseMemoryLeakFile( tmpFilename, _filename );\r\n\r\n\r\n\r\n \/\/\r\n \/\/ Delete the temporary file\r\n\r\n#ifdef TARGET_OS_WINDOWS\r\n DeleteFile( tmpFilename );\r\n#else\r\n\tunlink( tmpFilename );\r\n#endif\r\n \r\n}\r\n#endif\r\n\r\n\r\n#if 0\r\nint APIENTRY WinMain(HINSTANCE hInstance,\r\n HINSTANCE hPrevInstance,\r\n LPSTR lpCmdLine,\r\n int nCmdShow)\r\n{\r\n#else\r\nint main ( int argc, char **argv )\r\n{\r\n#endif\r\n\t\/* TODO: Get proper command line parameters for Windows apps *\/\r\n\tint retval = 0;\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemCheckpoint ( &s1 );\r\n#endif\r\n\tg_stderr = new CoreIO ( stderr );\r\n\tg_stdout = new CoreIO ( stdout );\r\n#ifdef ENABLE_CREDITS\r\n\tg_stdout->WriteLine ( \"Powered by CrissCross, http:\/\/www.uplinklabs.net\/crisscross\/\" );\r\n\tg_stdout->WriteLine ( \"(c) 2006 by Steven Noonan <steven@uplinklabs.net> and Rudolf Olah <omouse@gmail.com>\" );\r\n\tg_stdout->WriteLine ();\r\n#endif\r\n\ttry {\r\n#if 0\r\n\t\tretval = RunApplication ( 0, NULL );\r\n#else\r\n\t\tretval = RunApplication ( argc, argv );\r\n#endif\r\n\t}\r\n\tcatch ( CoreException *E )\r\n\t{\r\n\t\tg_stderr->WriteLine (\r\n\t\t\t\"\\nA CoreException has been raised.\\n\\tFile: %s\\n\\tLine: %d\\n\\tDescription: %s\\n\",\r\n\t\t\tE->ShowFile(), E->ShowLine(), E->ShowReason()\r\n\t\t);\r\n\t\treturn -1;\r\n\t}\r\n\tcatch ( char *_exception )\r\n\t{\r\n\t\tg_stderr->WriteLine ( \"An unknown exception has been raised:\\n\\tDescription: %s\", _exception );\t\r\n\t\treturn -2;\r\n\t}\r\n\tdelete g_stderr;\r\n\tdelete g_stdout;\r\n#ifdef DETECT_MEMORY_LEAKS\r\n\tAppPrintMemoryLeaks ( \"memleak.txt\" );\r\n#endif\r\n\treturn retval;\r\n}\r\n<commit_msg>Fix for the credits to show nicely on Win32 consoles as well.<commit_after>\/*\r\n *\r\n * C R I S S C R O S S\r\n * A multi purpose cross platform library.\r\n * formerly Codename \"Technetium\"\r\n * project started August 14, 2006\r\n *\r\n * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net> and Rudolf Olah <omouse@gmail.com>.\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without modification, are\r\n * permitted provided that the following conditions are met:\r\n *\r\n * * Redistributions of source code must retain the above copyright notice, this list\r\n * of conditions and the following disclaimer.\r\n * * Redistributions in binary form must reproduce the above copyright notice, this\r\n * list of conditions and the following disclaimer in the documentation and\/or other\r\n * materials provided with the distribution.\r\n * * Neither the name of Uplink Laboratories nor the names of its contributors may be\r\n * used to endorse or promote products derived from this software without specific\r\n * prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\r\n * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\r\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"universal_include.h\"\r\n#include \"core_exception.h\"\r\n#include \"core_io.h\"\r\n#include \"core_debug.h\"\r\n\r\n#include \"datastructures\/rbtree.h\"\r\n\r\nCoreIO *g_stderr;\r\nCoreIO *g_stdout;\r\n\r\n#ifdef DETECT_MEMORY_LEAKS\r\n\r\nusing namespace std;\r\n\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n_CrtMemState s1, s2, s3;\r\n#endif\r\n\r\nvoid ParseMemoryLeakFile ( char *_inputFilename, char *_outputFilename )\r\n{\r\n\r\n \/\/\r\n \/\/ Start up\r\n \/\/\r\n\r\n RedBlackTree <int, char *> combined;\r\n RedBlackTree <int, char *> frequency;\r\n int unrecognised = 0;\r\n\r\n \/\/\r\n \/\/ Open the file and start parsing\r\n \/\/\r\n\r\n std::ifstream memoryfile ( _inputFilename );\r\n\r\n while ( !memoryfile.eof () ) \r\n {\r\n char thisline [256];\r\n memoryfile.getline ( thisline, 256 );\r\n\r\n if ( !strncmp ( thisline, \" Data:\", 6 ) == 0 && \/\/ This line is a data line - useless to us\r\n strchr ( thisline, ':' ) ) { \/\/ This line does not have a source file location - useless to us\r\n\r\n \/\/ Get the size\r\n\r\n char *lastcomma = strrchr ( thisline, ',' );\r\n char *ssize = lastcomma+2;\r\n int size;\r\n char unused [32];\r\n sscanf ( ssize, \"%d %s\", &size, unused );\r\n\r\n \/\/ Get the source file name\r\n\r\n char *sourcelocation = thisline;\r\n char *colon = strrchr ( thisline, ':' );\r\n *(colon-1) = '\\x0';\r\n \r\n \/\/ Put the result into our BTree\r\n\r\n RedBlackTree <int, char *>::nodeType *btree = combined.findNode ( sourcelocation );\r\n if ( btree ) ((int) btree->data) += size;\r\n else combined.PutData ( sourcelocation, size );\r\n \r\n RedBlackTree <int, char *>::nodeType *freq = frequency.findNode ( sourcelocation );\r\n if ( freq ) ((int) freq->data) ++;\r\n else frequency.PutData ( sourcelocation, 1 );\r\n\r\n }\r\n else \r\n {\r\n char *lastcomma = strrchr ( thisline, ',' );\r\n \r\n if ( lastcomma ) \r\n {\r\n\r\n char *ssize = lastcomma+2;\r\n int size;\r\n char unused [32];\r\n sscanf ( ssize, \"%d %s\", &size, unused );\r\n\r\n unrecognised += size;\r\n }\r\n }\r\n }\r\n\r\n memoryfile.close ();\r\n\r\n \r\n \/\/\r\n \/\/ Sort the results into a list\r\n \/\/\r\n\r\n DArray <int> *sizes = combined.ConvertToDArray ();\r\n DArray <char *> *sources = combined.ConvertIndexToDArray ();\r\n LList <char *> sorted;\r\n int totalsize = 0;\r\n\r\n for ( int i = 0; i < sources->Size (); ++i )\r\n {\r\n char *newsource = sources->GetData (i);\r\n int newsize = sizes->GetData (i);\r\n totalsize += newsize;\r\n bool inserted = false;\r\n\r\n for ( int j = 0; j < sorted.Size (); ++j ) {\r\n\r\n char *existingsource = sorted.GetData (j);\r\n int existingsize = combined.GetData ( existingsource );\r\n\r\n if ( newsize <= existingsize ) {\r\n\r\n sorted.PutDataAtIndex ( newsource, j );\r\n inserted = true;\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n if ( !inserted ) sorted.PutDataAtEnd ( newsource );\r\n }\r\n\r\n\r\n \/\/\r\n \/\/ Open the output file\r\n \/\/\r\n\r\n FILE *output = fopen( _outputFilename, \"wt\" );\r\n\r\n \/\/\r\n \/\/ Print out our sorted list\r\n \/\/ \r\n\r\n fprintf ( output, \"Total recognised memory leaks : %d Kbytes\\n\", int(totalsize\/1024) );\r\n fprintf ( output, \"Total unrecognised memory leaks : %d Kbytes\\n\\n\", int(unrecognised\/1024) );\r\n \r\n for ( int k = sorted.Size () - 1; k >= 0; --k ) \r\n {\r\n\r\n char *source = sorted.GetData (k);\r\n int size = combined.GetData ( source );\r\n int freq = frequency.GetData ( source );\r\n\r\n if( size > 2048 )\r\n {\r\n fprintf ( output, \"%-95s (%d Kbytes in %d leaks)\\n\", source, int(size\/1024), freq );\r\n }\r\n else\r\n {\r\n fprintf ( output, \"%-95s (%d bytes in %d leaks)\\n\", source, size, freq );\r\n }\r\n }\r\n\r\n\r\n \/\/\r\n \/\/ Clear up\r\n\r\n fclose( output );\r\n\r\n delete sources;\r\n delete sizes;\r\n}\r\n\r\n\r\nvoid AppPrintMemoryLeaks( char *_filename )\r\n{\r\n \/\/\r\n \/\/ Print all raw memory leak data to a temporary file\r\n\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemCheckpoint ( &s2 );\r\n#endif\r\n\r\n char tmpFilename[512];\r\n sprintf( tmpFilename, \"%s.tmp\", _filename );\r\n\r\n OFSTRUCT ofstruct;\r\n HFILE file = OpenFile ( tmpFilename,\r\n &ofstruct,\r\n OF_CREATE );\r\n \r\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\r\n _CrtSetReportFile(_CRT_WARN, (_HFILE)file);\r\n\r\n\t_CrtDumpMemoryLeaks ();\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemDifference ( &s3, &s1, &s2 );\r\n\t_CrtMemDumpStatistics ( &s3 );\r\n#endif\r\n\r\n _lclose ( file );\r\n\r\n\r\n \/\/\r\n \/\/ Parse the temp file into a sensible format\r\n\r\n ParseMemoryLeakFile( tmpFilename, _filename );\r\n\r\n\r\n\r\n \/\/\r\n \/\/ Delete the temporary file\r\n\r\n#ifdef TARGET_OS_WINDOWS\r\n DeleteFile( tmpFilename );\r\n#else\r\n\tunlink( tmpFilename );\r\n#endif\r\n \r\n}\r\n#endif\r\n\r\n\r\n#if 0\r\nint APIENTRY WinMain(HINSTANCE hInstance,\r\n HINSTANCE hPrevInstance,\r\n LPSTR lpCmdLine,\r\n int nCmdShow)\r\n{\r\n#else\r\nint main ( int argc, char **argv )\r\n{\r\n#endif\r\n\t\/* TODO: Get proper command line parameters for Windows apps *\/\r\n\tint retval = 0;\r\n#ifdef ENABLE_MEMLEAK_STATS\r\n\t_CrtMemCheckpoint ( &s1 );\r\n#endif\r\n\tg_stderr = new CoreIO ( stderr );\r\n\tg_stdout = new CoreIO ( stdout );\r\n#ifdef ENABLE_CREDITS\r\n\tg_stdout->WriteLine ( \"Powered by CrissCross, http:\/\/www.uplinklabs.net\/crisscross\/\" );\r\n\tg_stdout->WriteLine ( \"(c) 2006 by Steven Noonan <steven@uplinklabs.net>\" );\r\n\tg_stdout->WriteLine ( \" and Rudolf Olah <omouse@gmail.com>\" );\r\n\tg_stdout->WriteLine ();\r\n#endif\r\n\ttry {\r\n#if 0\r\n\t\tretval = RunApplication ( 0, NULL );\r\n#else\r\n\t\tretval = RunApplication ( argc, argv );\r\n#endif\r\n\t}\r\n\tcatch ( CoreException *E )\r\n\t{\r\n\t\tg_stderr->WriteLine (\r\n\t\t\t\"\\nA CoreException has been raised.\\n\\tFile: %s\\n\\tLine: %d\\n\\tDescription: %s\\n\",\r\n\t\t\tE->ShowFile(), E->ShowLine(), E->ShowReason()\r\n\t\t);\r\n\t\treturn -1;\r\n\t}\r\n\tcatch ( char *_exception )\r\n\t{\r\n\t\tg_stderr->WriteLine ( \"An unknown exception has been raised:\\n\\tDescription: %s\", _exception );\t\r\n\t\treturn -2;\r\n\t}\r\n\tdelete g_stderr;\r\n\tdelete g_stdout;\r\n#ifdef DETECT_MEMORY_LEAKS\r\n\tAppPrintMemoryLeaks ( \"memleak.txt\" );\r\n#endif\r\n\treturn retval;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"helpers.hpp\"\n\n#include <cstddef>\n#include <string>\n\n#include <bsoncxx\/test_util\/catch.hh>\n#include <mongocxx\/client.hpp>\n#include <mongocxx\/instance.hpp>\n#include <mongocxx\/options\/ssl.hpp>\n#include <mongocxx\/pool.hpp>\n#include <mongocxx\/private\/libmongoc.hh>\n\nnamespace {\nusing namespace mongocxx;\n\nTEST_CASE(\"a pool is created with the correct MongoDB URI\", \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n bool destroy_called = false;\n client_pool_destroy->interpose([&](::mongoc_client_pool_t*) { destroy_called = true; });\n\n std::string expected_uri(\"mongodb:\/\/mongodb.example.com:9999\");\n uri mongodb_uri{expected_uri};\n\n std::string actual_uri{};\n bool new_called = false;\n\n client_pool_new->interpose([&](const mongoc_uri_t* uri) {\n new_called = true;\n actual_uri = mongoc_uri_get_string(uri);\n return nullptr;\n });\n\n {\n pool p{mongodb_uri};\n\n REQUIRE(new_called);\n REQUIRE(expected_uri == actual_uri);\n\n REQUIRE(!destroy_called);\n }\n\n REQUIRE(destroy_called);\n}\n\n#if defined(MONGOCXX_ENABLE_SSL) && defined(MONGOC_ENABLE_SSL)\nTEST_CASE(\n \"If we pass an engaged SSL options struct to the pool class, we will use it to configure the \"\n \"underlying mongoc pool\",\n \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n const std::string pem_file = \"foo\";\n const std::string pem_password = \"bar\";\n const std::string ca_file = \"baz\";\n const std::string ca_dir = \"garply\";\n const std::string crl_file = \"crl_file\";\n const bool allow_invalid_certificates = true;\n\n bool set_ssl_opts_called = false;\n options::ssl ssl_opts;\n ssl_opts.pem_file(pem_file);\n ssl_opts.pem_password(pem_password);\n ssl_opts.ca_file(ca_file);\n ssl_opts.ca_dir(ca_dir);\n ssl_opts.crl_file(crl_file);\n ssl_opts.allow_invalid_certificates(allow_invalid_certificates);\n\n ::mongoc_ssl_opt_t interposed = {};\n\n client_pool_set_ssl_opts->interpose(\n [&](::mongoc_client_pool_t*, const ::mongoc_ssl_opt_t* opts) {\n set_ssl_opts_called = true;\n interposed = *opts;\n });\n\n pool p{uri{\"mongodb:\/\/mongodb.example.com:9999\/?ssl=true\"},\n options::client().ssl_opts(ssl_opts)};\n\n REQUIRE(set_ssl_opts_called);\n REQUIRE(interposed.pem_file == pem_file);\n REQUIRE(interposed.pem_pwd == pem_password);\n REQUIRE(interposed.ca_file == ca_file);\n REQUIRE(interposed.ca_dir == ca_dir);\n REQUIRE(interposed.crl_file == crl_file);\n REQUIRE(interposed.weak_cert_validation == allow_invalid_certificates);\n}\n#endif\n\nTEST_CASE(\"calling acquire on a pool returns an entry that manages its client\", \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n bool pop_called = false;\n client_pool_pop->interpose([&](::mongoc_client_pool_t*) {\n pop_called = true;\n return nullptr;\n });\n\n bool push_called = false;\n client_pool_push->interpose(\n [&](::mongoc_client_pool_t*, ::mongoc_client_t*) { push_called = true; });\n\n SECTION(\"entry releases its client at end of scope\") {\n {\n pool p{};\n auto client = p.acquire();\n\n REQUIRE(pop_called);\n REQUIRE(!push_called);\n }\n\n REQUIRE(push_called);\n }\n\n SECTION(\"entry releases its client when set to nullptr\") {\n pool p{};\n auto client = p.acquire();\n\n REQUIRE(pop_called);\n REQUIRE(!push_called);\n client = nullptr;\n REQUIRE(push_called);\n }\n}\n\nTEST_CASE(\n \"try_acquire returns an engaged stdx::optional<entry> if mongoc_client_pool_try_pop \"\n \"returns a non-null pointer\",\n \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n \/\/ libstdc++ before GCC 4.9 places max_align_t in the wrong\n \/\/ namespace. Use a limited scope 'using namespace std' to name it\n \/\/ in a way that always works.\n auto dummy_address = []() {\n using namespace std;\n return max_align_t{};\n }();\n\n bool try_pop_called = false;\n\n mongoc_client_t* fake = reinterpret_cast<mongoc_client_t*>(&dummy_address);\n\n client_pool_try_pop->interpose([&](::mongoc_client_pool_t*) {\n try_pop_called = true;\n return fake;\n });\n\n {\n pool p{};\n auto client = p.try_acquire();\n\n REQUIRE(!!client);\n REQUIRE(try_pop_called);\n }\n}\n\nTEST_CASE(\n \"try_acquire returns a disengaged stdx::optional<entry> if mongoc_client_pool_try_pop \"\n \"returns a null pointer\",\n \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n client_pool_try_pop->interpose([](::mongoc_client_pool_t*) { return nullptr; });\n\n {\n pool p{};\n auto client = p.try_acquire();\n REQUIRE(!client);\n }\n}\n} \/\/ namespace\n<commit_msg>CXX-1595 Don't rely on max_align_t in test<commit_after>\/\/ Copyright 2015 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"helpers.hpp\"\n\n#include <cstddef>\n#include <string>\n\n#include <bsoncxx\/test_util\/catch.hh>\n#include <mongocxx\/client.hpp>\n#include <mongocxx\/instance.hpp>\n#include <mongocxx\/options\/ssl.hpp>\n#include <mongocxx\/pool.hpp>\n#include <mongocxx\/private\/libmongoc.hh>\n\nnamespace {\nusing namespace mongocxx;\n\nTEST_CASE(\"a pool is created with the correct MongoDB URI\", \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n bool destroy_called = false;\n client_pool_destroy->interpose([&](::mongoc_client_pool_t*) { destroy_called = true; });\n\n std::string expected_uri(\"mongodb:\/\/mongodb.example.com:9999\");\n uri mongodb_uri{expected_uri};\n\n std::string actual_uri{};\n bool new_called = false;\n\n client_pool_new->interpose([&](const mongoc_uri_t* uri) {\n new_called = true;\n actual_uri = mongoc_uri_get_string(uri);\n return nullptr;\n });\n\n {\n pool p{mongodb_uri};\n\n REQUIRE(new_called);\n REQUIRE(expected_uri == actual_uri);\n\n REQUIRE(!destroy_called);\n }\n\n REQUIRE(destroy_called);\n}\n\n#if defined(MONGOCXX_ENABLE_SSL) && defined(MONGOC_ENABLE_SSL)\nTEST_CASE(\n \"If we pass an engaged SSL options struct to the pool class, we will use it to configure the \"\n \"underlying mongoc pool\",\n \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n const std::string pem_file = \"foo\";\n const std::string pem_password = \"bar\";\n const std::string ca_file = \"baz\";\n const std::string ca_dir = \"garply\";\n const std::string crl_file = \"crl_file\";\n const bool allow_invalid_certificates = true;\n\n bool set_ssl_opts_called = false;\n options::ssl ssl_opts;\n ssl_opts.pem_file(pem_file);\n ssl_opts.pem_password(pem_password);\n ssl_opts.ca_file(ca_file);\n ssl_opts.ca_dir(ca_dir);\n ssl_opts.crl_file(crl_file);\n ssl_opts.allow_invalid_certificates(allow_invalid_certificates);\n\n ::mongoc_ssl_opt_t interposed = {};\n\n client_pool_set_ssl_opts->interpose(\n [&](::mongoc_client_pool_t*, const ::mongoc_ssl_opt_t* opts) {\n set_ssl_opts_called = true;\n interposed = *opts;\n });\n\n pool p{uri{\"mongodb:\/\/mongodb.example.com:9999\/?ssl=true\"},\n options::client().ssl_opts(ssl_opts)};\n\n REQUIRE(set_ssl_opts_called);\n REQUIRE(interposed.pem_file == pem_file);\n REQUIRE(interposed.pem_pwd == pem_password);\n REQUIRE(interposed.ca_file == ca_file);\n REQUIRE(interposed.ca_dir == ca_dir);\n REQUIRE(interposed.crl_file == crl_file);\n REQUIRE(interposed.weak_cert_validation == allow_invalid_certificates);\n}\n#endif\n\nTEST_CASE(\"calling acquire on a pool returns an entry that manages its client\", \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n bool pop_called = false;\n client_pool_pop->interpose([&](::mongoc_client_pool_t*) {\n pop_called = true;\n return nullptr;\n });\n\n bool push_called = false;\n client_pool_push->interpose(\n [&](::mongoc_client_pool_t*, ::mongoc_client_t*) { push_called = true; });\n\n SECTION(\"entry releases its client at end of scope\") {\n {\n pool p{};\n auto client = p.acquire();\n\n REQUIRE(pop_called);\n REQUIRE(!push_called);\n }\n\n REQUIRE(push_called);\n }\n\n SECTION(\"entry releases its client when set to nullptr\") {\n pool p{};\n auto client = p.acquire();\n\n REQUIRE(pop_called);\n REQUIRE(!push_called);\n client = nullptr;\n REQUIRE(push_called);\n }\n}\n\nTEST_CASE(\"try_acquire returns an engaged stdx::optional<entry>\", \"[pool]\") {\n instance::current();\n pool p{};\n auto client = p.try_acquire();\n REQUIRE(!!client);\n}\n\nTEST_CASE(\n \"try_acquire returns a disengaged stdx::optional<entry> if mongoc_client_pool_try_pop \"\n \"returns a null pointer\",\n \"[pool]\") {\n MOCK_POOL\n\n instance::current();\n\n client_pool_try_pop->interpose([](::mongoc_client_pool_t*) { return nullptr; });\n\n {\n pool p{};\n auto client = p.try_acquire();\n REQUIRE(!client);\n }\n}\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <sys\/time.h>\n#include <sys\/resource.h>\n#include <sys\/signal.h>\n#include <thread>\n\n#include <google\/gflags.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/host_port.h>\n#include <grpc++\/config.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/status.h>\n#include \"test\/core\/util\/grpc_profiler.h\"\n#include \"test\/cpp\/qps\/qpstest.pb.h\"\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/log.h>\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_int32(port, 0, \"Server port.\");\n\nusing grpc::Server;\nusing grpc::ServerBuilder;\nusing grpc::ServerContext;\nusing grpc::testing::Payload;\nusing grpc::testing::PayloadType;\nusing grpc::testing::ServerStats;\nusing grpc::testing::SimpleRequest;\nusing grpc::testing::SimpleResponse;\nusing grpc::testing::StatsRequest;\nusing grpc::testing::TestService;\nusing grpc::Status;\n\nstatic bool got_sigint = false;\n\nstatic void sigint_handler(int x) { got_sigint = 1; }\n\nstatic double time_double(struct timeval* tv) {\n return tv->tv_sec + 1e-6 * tv->tv_usec;\n}\n\nstatic bool SetPayload(PayloadType type, int size, Payload* payload) {\n PayloadType response_type = type;\n \/\/ TODO(yangg): Support UNCOMPRESSABLE payload.\n if (type != PayloadType::COMPRESSABLE) {\n return false;\n }\n payload->set_type(response_type);\n std::unique_ptr<char[]> body(new char[size]());\n payload->set_body(body.get(), size);\n return true;\n}\n\nnamespace {\n\nclass TestServiceImpl final : public TestService::Service {\n public:\n Status CollectServerStats(ServerContext* context, const StatsRequest*,\n ServerStats* response) {\n struct rusage usage;\n struct timeval tv;\n gettimeofday(&tv, NULL);\n getrusage(RUSAGE_SELF, &usage);\n response->set_time_now(time_double(&tv));\n response->set_time_user(time_double(&usage.ru_utime));\n response->set_time_system(time_double(&usage.ru_stime));\n return Status::OK;\n }\n Status UnaryCall(ServerContext* context, const SimpleRequest* request,\n SimpleResponse* response) {\n if (request->has_response_size() && request->response_size() > 0) {\n if (!SetPayload(request->response_type(), request->response_size(),\n response->mutable_payload())) {\n return Status(grpc::StatusCode::INTERNAL, \"Error creating payload.\");\n }\n }\n return Status::OK;\n }\n};\n\n} \/\/ namespace\n\nstatic void RunServer() {\n char* server_address = NULL;\n gpr_join_host_port(&server_address, \"::\", FLAGS_port);\n\n TestServiceImpl service;\n\n SimpleRequest request;\n SimpleResponse response;\n\n ServerBuilder builder;\n builder.AddPort(server_address);\n builder.RegisterService(service.service());\n std::unique_ptr<Server> server(builder.BuildAndStart());\n gpr_log(GPR_INFO, \"Server listening on %s\\n\", server_address);\n\n grpc_profiler_start(\"qps_server.prof\");\n\n while (!got_sigint) {\n std::this_thread::sleep_for(std::chrono::seconds(5));\n }\n\n grpc_profiler_stop();\n\n gpr_free(server_address);\n}\n\nint main(int argc, char** argv) {\n grpc_init();\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n signal(SIGINT, sigint_handler);\n \n GPR_ASSERT(FLAGS_port != 0);\n GPR_ASSERT(!FLAGS_enable_ssl);\n RunServer();\n\n grpc_shutdown();\n return 0;\n}\n\n<commit_msg>Allow varying number of server threads via command line flag<commit_after>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <sys\/time.h>\n#include <sys\/resource.h>\n#include <sys\/signal.h>\n#include <thread>\n\n#include <google\/gflags.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/host_port.h>\n#include <grpc++\/config.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/status.h>\n#include \"src\/cpp\/server\/thread_pool.h\"\n#include \"test\/core\/util\/grpc_profiler.h\"\n#include \"test\/cpp\/qps\/qpstest.pb.h\"\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/log.h>\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_int32(port, 0, \"Server port.\");\nDEFINE_int32(server_threads, 4, \"Number of server threads.\");\n\nusing grpc::Server;\nusing grpc::ServerBuilder;\nusing grpc::ServerContext;\nusing grpc::ThreadPool;\nusing grpc::testing::Payload;\nusing grpc::testing::PayloadType;\nusing grpc::testing::ServerStats;\nusing grpc::testing::SimpleRequest;\nusing grpc::testing::SimpleResponse;\nusing grpc::testing::StatsRequest;\nusing grpc::testing::TestService;\nusing grpc::Status;\n\nstatic bool got_sigint = false;\n\nstatic void sigint_handler(int x) { got_sigint = 1; }\n\nstatic double time_double(struct timeval* tv) {\n return tv->tv_sec + 1e-6 * tv->tv_usec;\n}\n\nstatic bool SetPayload(PayloadType type, int size, Payload* payload) {\n PayloadType response_type = type;\n \/\/ TODO(yangg): Support UNCOMPRESSABLE payload.\n if (type != PayloadType::COMPRESSABLE) {\n return false;\n }\n payload->set_type(response_type);\n std::unique_ptr<char[]> body(new char[size]());\n payload->set_body(body.get(), size);\n return true;\n}\n\nnamespace {\n\nclass TestServiceImpl final : public TestService::Service {\n public:\n Status CollectServerStats(ServerContext* context, const StatsRequest*,\n ServerStats* response) {\n struct rusage usage;\n struct timeval tv;\n gettimeofday(&tv, NULL);\n getrusage(RUSAGE_SELF, &usage);\n response->set_time_now(time_double(&tv));\n response->set_time_user(time_double(&usage.ru_utime));\n response->set_time_system(time_double(&usage.ru_stime));\n return Status::OK;\n }\n Status UnaryCall(ServerContext* context, const SimpleRequest* request,\n SimpleResponse* response) {\n if (request->has_response_size() && request->response_size() > 0) {\n if (!SetPayload(request->response_type(), request->response_size(),\n response->mutable_payload())) {\n return Status(grpc::StatusCode::INTERNAL, \"Error creating payload.\");\n }\n }\n return Status::OK;\n }\n};\n\n} \/\/ namespace\n\nstatic void RunServer() {\n char* server_address = NULL;\n gpr_join_host_port(&server_address, \"::\", FLAGS_port);\n\n TestServiceImpl service;\n\n SimpleRequest request;\n SimpleResponse response;\n\n ServerBuilder builder;\n builder.AddPort(server_address);\n builder.RegisterService(service.service());\n\n ThreadPool *pool = new ThreadPool(FLAGS_server_threads);\n builder.SetThreadPool(pool);\n\n std::unique_ptr<Server> server(builder.BuildAndStart());\n gpr_log(GPR_INFO, \"Server listening on %s\\n\", server_address);\n\n grpc_profiler_start(\"qps_server.prof\");\n\n while (!got_sigint) {\n std::this_thread::sleep_for(std::chrono::seconds(5));\n }\n\n grpc_profiler_stop();\n\n delete pool;\n gpr_free(server_address);\n}\n\nint main(int argc, char** argv) {\n grpc_init();\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n signal(SIGINT, sigint_handler);\n \n GPR_ASSERT(FLAGS_port != 0);\n GPR_ASSERT(!FLAGS_enable_ssl);\n RunServer();\n\n grpc_shutdown();\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <map>\n#include <stack>\n#include <string>\n\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"kern\/kernel_stats.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/sw_context.hh\"\n#include \"targetarch\/isa_traits.hh\"\n#include \"targetarch\/osfpal.hh\"\n#include \"targetarch\/syscalls.hh\"\n\nusing namespace std;\nusing namespace Stats;\n\nclass KSData\n{\n private:\n string _name;\n ExecContext *xc;\n BaseCPU *cpu;\n\n public:\n KSData(ExecContext *_xc, BaseCPU *_cpu)\n : xc(_xc), cpu(_cpu), iplLast(0), iplLastTick(0), lastUser(false),\n lastModeTick(0)\n {}\n\n const string &name() { return _name; }\n void regStats(const string &name);\n\n public:\n Scalar<> _arm;\n Scalar<> _quiesce;\n Scalar<> _ivlb;\n Scalar<> _ivle;\n Scalar<> _hwrei;\n\n Vector<> _iplCount;\n Vector<> _iplGood;\n Vector<> _iplTicks;\n Formula _iplUsed;\n\n Vector<> _callpal;\n Vector<> _syscall;\n Vector<> _faults;\n\n Vector<> _mode;\n Vector<> _modeGood;\n Formula _modeFraction;\n Vector<> _modeTicks;\n\n Scalar<> _swap_context;\n\n private:\n int iplLast;\n Tick iplLastTick;\n\n bool lastUser;\n Tick lastModeTick;\n\n public:\n void swpipl(int ipl);\n void mode(bool user);\n void callpal(int code);\n};\n\nKernelStats::KernelStats(ExecContext *xc, BaseCPU *cpu)\n{ data = new KSData(xc, cpu); }\n\nKernelStats::~KernelStats()\n{ delete data; }\n\nvoid\nKernelStats::regStats(const string &name)\n{ data->regStats(name); }\n\nvoid\nKSData::regStats(const string &name)\n{\n _name = name;\n\n _arm\n .name(name + \".inst.arm\")\n .desc(\"number of arm instructions executed\")\n ;\n\n _quiesce\n .name(name + \".inst.quiesce\")\n .desc(\"number of quiesce instructions executed\")\n ;\n\n _ivlb\n .name(name + \".inst.ivlb\")\n .desc(\"number of ivlb instructions executed\")\n ;\n\n _ivle\n .name(name + \".inst.ivle\")\n .desc(\"number of ivle instructions executed\")\n ;\n\n _hwrei\n .name(name + \".inst.hwrei\")\n .desc(\"number of hwrei instructions executed\")\n ;\n\n _iplCount\n .init(32)\n .name(name + \".ipl_count\")\n .desc(\"number of times we switched to this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplGood\n .init(32)\n .name(name + \".ipl_good\")\n .desc(\"number of times we switched to this ipl from a different ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplTicks\n .init(32)\n .name(name + \".ipl_ticks\")\n .desc(\"number of cycles we spent at this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplUsed\n .name(name + \".ipl_used\")\n .desc(\"fraction of swpipl calls that actually changed the ipl\")\n .flags(total | nozero | nonan)\n ;\n\n _iplUsed = _iplGood \/ _iplCount;\n\n _callpal\n .init(256)\n .name(name + \".callpal\")\n .desc(\"number of callpals executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 0; i < PAL::NumCodes; ++i) {\n const char *str = PAL::name(i);\n if (str)\n _callpal.subname(i, str);\n }\n\n _syscall\n .init(SystemCalls<Tru64>::Number)\n .name(name + \".syscall\")\n .desc(\"number of syscalls executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {\n const char *str = SystemCalls<Tru64>::name(i);\n if (str) {\n _syscall.subname(i, str);\n }\n }\n\n _faults\n .init(Num_Faults)\n .name(name + \".faults\")\n .desc(\"number of faults\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 1; i < Num_Faults; ++i) {\n const char *str = FaultName(i);\n if (str)\n _faults.subname(i, str);\n }\n\n _mode\n .init(2)\n .name(name + \".mode_switch\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"number of protection mode switches\")\n ;\n\n _modeGood\n .init(2)\n ;\n\n _modeFraction\n .name(name + \".mode_switch_good\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"fraction of useful protection mode switches\")\n .flags(total)\n ;\n _modeFraction = _modeGood \/ _mode;\n\n _modeTicks\n .init(2)\n .name(name + \".mode_ticks\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"number of ticks spent at the given mode\")\n .flags(pdf)\n ;\n\n _swap_context\n .name(name + \".swap_context\")\n .desc(\"number of times the context was actually changed\")\n ;\n}\n\nvoid\nKernelStats::arm()\n{ data->_arm++; }\n\nvoid\nKernelStats::quiesce()\n{ data->_quiesce++; }\n\nvoid\nKernelStats::ivlb()\n{ data->_ivlb++; }\n\nvoid\nKernelStats::ivle()\n{ data->_ivle++; }\n\nvoid\nKernelStats::hwrei()\n{ data->_hwrei++; }\n\nvoid\nKernelStats::fault(Fault fault)\n{ data->_faults[fault]++; }\n\nvoid\nKernelStats::swpipl(int ipl)\n{ data->swpipl(ipl); }\n\nvoid\nKernelStats::mode(bool user)\n{ data->mode(user); }\n\nvoid\nKernelStats::context(Addr old_pcbb, Addr new_pcbb)\n{ data->_swap_context++; }\n\nvoid\nKernelStats::callpal(int code)\n{ data->callpal(code); }\n\n\nvoid\nKSData::swpipl(int ipl)\n{\n assert(ipl >= 0 && ipl <= 0x1f && \"invalid IPL\\n\");\n\n _iplCount[ipl]++;\n\n if (ipl == iplLast)\n return;\n\n _iplGood[ipl]++;\n _iplTicks[iplLast] += curTick - iplLastTick;\n iplLastTick = curTick;\n iplLast = ipl;\n}\n\nvoid\nKSData::mode(bool user)\n{\n _mode[user]++;\n if (user == lastUser)\n return;\n\n _modeGood[user]++;\n _modeTicks[lastUser] += curTick - lastModeTick;\n\n lastModeTick = curTick;\n lastUser = user;\n\n if (xc->system->bin) {\n if (!xc->swCtx || xc->swCtx->callStack.empty()) {\n if (user)\n xc->system->User->activate();\n else\n xc->system->Kernel->activate();\n }\n }\n}\n\nvoid\nKSData::callpal(int code)\n{\n if (!PAL::name(code))\n return;\n\n _callpal[code]++;\n\n switch (code) {\n case PAL::callsys:\n {\n int number = xc->regs.intRegFile[0];\n if (SystemCalls<Tru64>::validSyscallNumber(number)) {\n int cvtnum = SystemCalls<Tru64>::convert(number);\n _syscall[cvtnum]++;\n }\n }\n break;\n }\n\n if (code == PAL::swpctx) {\n SWContext *out = xc->swCtx;\n System *sys = xc->system;\n if (!sys->bin)\n return;\n DPRINTF(TCPIP, \"swpctx event\\n\");\n if (out) {\n DPRINTF(TCPIP, \"swapping context out with this stack!\\n\");\n xc->system->dumpState(xc);\n Addr oldPCB = xc->regs.ipr[TheISA::IPR_PALtemp23];\n\n if (out->callStack.empty()) {\n DPRINTF(TCPIP, \"but removing it, cuz empty!\\n\");\n SWContext *find = sys->findContext(oldPCB);\n if (find) {\n assert(sys->findContext(oldPCB) == out);\n sys->remContext(oldPCB);\n }\n delete out;\n } else {\n DPRINTF(TCPIP, \"switching out context with pcb %#x, top fn %s\\n\",\n oldPCB, out->callStack.top()->name);\n if (!sys->findContext(oldPCB)) {\n if (!sys->addContext(oldPCB, out))\n panic(\"could not add context\");\n }\n }\n }\n\n Addr newPCB = xc->regs.intRegFile[16];\n SWContext *in = sys->findContext(newPCB);\n xc->swCtx = in;\n\n if (in) {\n assert(!in->callStack.empty() &&\n \"should not be switching in empty context\");\n DPRINTF(TCPIP, \"swapping context in with this callstack!\\n\");\n xc->system->dumpState(xc);\n sys->remContext(newPCB);\n fnCall *top = in->callStack.top();\n DPRINTF(TCPIP, \"switching in to pcb %#x, %s\\n\", newPCB, top->name);\n assert(top->myBin && \"should not switch to context with no Bin\");\n top->myBin->activate();\n } else {\n sys->Kernel->activate();\n }\n DPRINTF(TCPIP, \"end swpctx\\n\");\n }\n}\n<commit_msg>name this stat since it makes life easier with the mysql stuff<commit_after>\/*\n * Copyright (c) 2003 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <map>\n#include <stack>\n#include <string>\n\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"kern\/kernel_stats.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/sw_context.hh\"\n#include \"targetarch\/isa_traits.hh\"\n#include \"targetarch\/osfpal.hh\"\n#include \"targetarch\/syscalls.hh\"\n\nusing namespace std;\nusing namespace Stats;\n\nclass KSData\n{\n private:\n string _name;\n ExecContext *xc;\n BaseCPU *cpu;\n\n public:\n KSData(ExecContext *_xc, BaseCPU *_cpu)\n : xc(_xc), cpu(_cpu), iplLast(0), iplLastTick(0), lastUser(false),\n lastModeTick(0)\n {}\n\n const string &name() { return _name; }\n void regStats(const string &name);\n\n public:\n Scalar<> _arm;\n Scalar<> _quiesce;\n Scalar<> _ivlb;\n Scalar<> _ivle;\n Scalar<> _hwrei;\n\n Vector<> _iplCount;\n Vector<> _iplGood;\n Vector<> _iplTicks;\n Formula _iplUsed;\n\n Vector<> _callpal;\n Vector<> _syscall;\n Vector<> _faults;\n\n Vector<> _mode;\n Vector<> _modeGood;\n Formula _modeFraction;\n Vector<> _modeTicks;\n\n Scalar<> _swap_context;\n\n private:\n int iplLast;\n Tick iplLastTick;\n\n bool lastUser;\n Tick lastModeTick;\n\n public:\n void swpipl(int ipl);\n void mode(bool user);\n void callpal(int code);\n};\n\nKernelStats::KernelStats(ExecContext *xc, BaseCPU *cpu)\n{ data = new KSData(xc, cpu); }\n\nKernelStats::~KernelStats()\n{ delete data; }\n\nvoid\nKernelStats::regStats(const string &name)\n{ data->regStats(name); }\n\nvoid\nKSData::regStats(const string &name)\n{\n _name = name;\n\n _arm\n .name(name + \".inst.arm\")\n .desc(\"number of arm instructions executed\")\n ;\n\n _quiesce\n .name(name + \".inst.quiesce\")\n .desc(\"number of quiesce instructions executed\")\n ;\n\n _ivlb\n .name(name + \".inst.ivlb\")\n .desc(\"number of ivlb instructions executed\")\n ;\n\n _ivle\n .name(name + \".inst.ivle\")\n .desc(\"number of ivle instructions executed\")\n ;\n\n _hwrei\n .name(name + \".inst.hwrei\")\n .desc(\"number of hwrei instructions executed\")\n ;\n\n _iplCount\n .init(32)\n .name(name + \".ipl_count\")\n .desc(\"number of times we switched to this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplGood\n .init(32)\n .name(name + \".ipl_good\")\n .desc(\"number of times we switched to this ipl from a different ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplTicks\n .init(32)\n .name(name + \".ipl_ticks\")\n .desc(\"number of cycles we spent at this ipl\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n _iplUsed\n .name(name + \".ipl_used\")\n .desc(\"fraction of swpipl calls that actually changed the ipl\")\n .flags(total | nozero | nonan)\n ;\n\n _iplUsed = _iplGood \/ _iplCount;\n\n _callpal\n .init(256)\n .name(name + \".callpal\")\n .desc(\"number of callpals executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 0; i < PAL::NumCodes; ++i) {\n const char *str = PAL::name(i);\n if (str)\n _callpal.subname(i, str);\n }\n\n _syscall\n .init(SystemCalls<Tru64>::Number)\n .name(name + \".syscall\")\n .desc(\"number of syscalls executed\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {\n const char *str = SystemCalls<Tru64>::name(i);\n if (str) {\n _syscall.subname(i, str);\n }\n }\n\n _faults\n .init(Num_Faults)\n .name(name + \".faults\")\n .desc(\"number of faults\")\n .flags(total | pdf | nozero | nonan)\n ;\n\n for (int i = 1; i < Num_Faults; ++i) {\n const char *str = FaultName(i);\n if (str)\n _faults.subname(i, str);\n }\n\n _mode\n .init(2)\n .name(name + \".mode_switch\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"number of protection mode switches\")\n ;\n\n _modeGood\n .init(2)\n .name(name + \".mode_good\")\n ;\n\n _modeFraction\n .name(name + \".mode_switch_good\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"fraction of useful protection mode switches\")\n .flags(total)\n ;\n _modeFraction = _modeGood \/ _mode;\n\n _modeTicks\n .init(2)\n .name(name + \".mode_ticks\")\n .subname(0, \"kernel\")\n .subname(1, \"user\")\n .desc(\"number of ticks spent at the given mode\")\n .flags(pdf)\n ;\n\n _swap_context\n .name(name + \".swap_context\")\n .desc(\"number of times the context was actually changed\")\n ;\n}\n\nvoid\nKernelStats::arm()\n{ data->_arm++; }\n\nvoid\nKernelStats::quiesce()\n{ data->_quiesce++; }\n\nvoid\nKernelStats::ivlb()\n{ data->_ivlb++; }\n\nvoid\nKernelStats::ivle()\n{ data->_ivle++; }\n\nvoid\nKernelStats::hwrei()\n{ data->_hwrei++; }\n\nvoid\nKernelStats::fault(Fault fault)\n{ data->_faults[fault]++; }\n\nvoid\nKernelStats::swpipl(int ipl)\n{ data->swpipl(ipl); }\n\nvoid\nKernelStats::mode(bool user)\n{ data->mode(user); }\n\nvoid\nKernelStats::context(Addr old_pcbb, Addr new_pcbb)\n{ data->_swap_context++; }\n\nvoid\nKernelStats::callpal(int code)\n{ data->callpal(code); }\n\n\nvoid\nKSData::swpipl(int ipl)\n{\n assert(ipl >= 0 && ipl <= 0x1f && \"invalid IPL\\n\");\n\n _iplCount[ipl]++;\n\n if (ipl == iplLast)\n return;\n\n _iplGood[ipl]++;\n _iplTicks[iplLast] += curTick - iplLastTick;\n iplLastTick = curTick;\n iplLast = ipl;\n}\n\nvoid\nKSData::mode(bool user)\n{\n _mode[user]++;\n if (user == lastUser)\n return;\n\n _modeGood[user]++;\n _modeTicks[lastUser] += curTick - lastModeTick;\n\n lastModeTick = curTick;\n lastUser = user;\n\n if (xc->system->bin) {\n if (!xc->swCtx || xc->swCtx->callStack.empty()) {\n if (user)\n xc->system->User->activate();\n else\n xc->system->Kernel->activate();\n }\n }\n}\n\nvoid\nKSData::callpal(int code)\n{\n if (!PAL::name(code))\n return;\n\n _callpal[code]++;\n\n switch (code) {\n case PAL::callsys:\n {\n int number = xc->regs.intRegFile[0];\n if (SystemCalls<Tru64>::validSyscallNumber(number)) {\n int cvtnum = SystemCalls<Tru64>::convert(number);\n _syscall[cvtnum]++;\n }\n }\n break;\n }\n\n if (code == PAL::swpctx) {\n SWContext *out = xc->swCtx;\n System *sys = xc->system;\n if (!sys->bin)\n return;\n DPRINTF(TCPIP, \"swpctx event\\n\");\n if (out) {\n DPRINTF(TCPIP, \"swapping context out with this stack!\\n\");\n xc->system->dumpState(xc);\n Addr oldPCB = xc->regs.ipr[TheISA::IPR_PALtemp23];\n\n if (out->callStack.empty()) {\n DPRINTF(TCPIP, \"but removing it, cuz empty!\\n\");\n SWContext *find = sys->findContext(oldPCB);\n if (find) {\n assert(sys->findContext(oldPCB) == out);\n sys->remContext(oldPCB);\n }\n delete out;\n } else {\n DPRINTF(TCPIP, \"switching out context with pcb %#x, top fn %s\\n\",\n oldPCB, out->callStack.top()->name);\n if (!sys->findContext(oldPCB)) {\n if (!sys->addContext(oldPCB, out))\n panic(\"could not add context\");\n }\n }\n }\n\n Addr newPCB = xc->regs.intRegFile[16];\n SWContext *in = sys->findContext(newPCB);\n xc->swCtx = in;\n\n if (in) {\n assert(!in->callStack.empty() &&\n \"should not be switching in empty context\");\n DPRINTF(TCPIP, \"swapping context in with this callstack!\\n\");\n xc->system->dumpState(xc);\n sys->remContext(newPCB);\n fnCall *top = in->callStack.top();\n DPRINTF(TCPIP, \"switching in to pcb %#x, %s\\n\", newPCB, top->name);\n assert(top->myBin && \"should not switch to context with no Bin\");\n top->myBin->activate();\n } else {\n sys->Kernel->activate();\n }\n DPRINTF(TCPIP, \"end swpctx\\n\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"includes\/MainWindow.hpp\"\n#include \"includes\/ThemeManager.hpp\"\n\n#include <QMenu>\n#include <QMenuBar>\n#include <QMessageBox>\n#include <QInputDialog>\n#include <QFileDialog>\n#include <QTextStream>\n#include <QStandardPaths>\n#include <QDir>\n\nconst unsigned int THEME_V0 = 1;\nconst unsigned int THEME_V1 = 2;\n\nMainWindow::MainWindow(QWidget * parent) : \n\tQMainWindow(parent)\n{\n\tcreateMenus();\n\tresize(1024, 768);\n\n\tconnect(m_newThm, &QAction::triggered, this, &MainWindow::newThm);\n\tconnect(m_openThm, &QAction::triggered, this, &MainWindow::openThm);\n\tconnect(m_saveThm, &QAction::triggered, this, &MainWindow::saveThm);\n\tconnect(m_saveThmAs, &QAction::triggered, this, &MainWindow::saveThmAs);\n\t\n\tconnect(m_newToolBar, &QAction::triggered, this, &MainWindow::createNewToolBar);\n\n\tm_saveThm->setShortcut(QKeySequence::Save);\n\tm_saveThmAs->setShortcuts(QKeySequence::SaveAs);\n\n\/\/\tQMessageBox::information(this, \"DEBUG\", QStandardPaths::writableLocation(QStandardPaths::TempLocation));\n}\n\nMainWindow::~MainWindow()\n{\n\t\/\/ Empty\n}\n\nvoid MainWindow::createMenus()\n{\n\tQMenu *fileMenu = menuBar()->addMenu(tr(\"&Fichier\"));\n\n\tfileMenu->addAction(m_newThm);\n\tfileMenu->addAction(m_openThm);\n\tfileMenu->addSeparator();\n\tfileMenu->addAction(m_saveThm);\n\tfileMenu->addAction(m_saveThmAs);\n\tm_saveThm->setEnabled(false);\n\tm_saveThmAs->setEnabled(false);\n\n\tQMenu *themeMenu = menuBar()->addMenu(tr(\"&Thèmes\"));\n\n\tthemeMenu->addAction(m_newToolBar);\n\tm_newToolBar->setEnabled(false);\n}\n\nvoid MainWindow::createActions()\n{\n\t\tm_backAction->setIcon(QIcon(m_thmPath + \"back.png\"));\n\t\tm_backAction->setObjectName(\"back\");\n\t\tm_editableAction.insert(\"back\", m_backAction);\n\t\tm_nextAction->setIcon(QIcon(m_thmPath + \"next.png\"));\n\t\tm_nextAction->setObjectName(\"next\");\n\t\tm_editableAction.insert(\"next\", m_nextAction);\n\t\tm_homeAction->setIcon(QIcon(m_thmPath + \"home.png\"));\n\t\tm_homeAction->setObjectName(\"home\");\n\t\tm_editableAction.insert(\"home\", m_homeAction);\n\t\tm_refreshOrStopAction->setIcon(QIcon(m_thmPath + \"refresh.png\"));\n\t\tm_refreshOrStopAction->setObjectName(\"refresh\");\n\t\tm_editableAction.insert(\"refresh\", m_refreshOrStopAction);\n\t\tm_goAction->setIcon(QIcon(m_thmPath + \"go.png\"));\n\t\tm_goAction->setObjectName(\"go\");\n\t\tm_editableAction.insert(\"go\", m_goAction);\n\t\tm_searchAction->setIcon(QIcon(m_thmPath + \"search.png\"));\n\t\tm_searchAction->setObjectName(\"search\");\n\t\tm_editableAction.insert(\"search\", m_searchAction);\n\t\tm_sowHistory->setIcon(QIcon(m_thmPath + \"history.png\"));\n\t\tm_sowHistory->setObjectName(\"history\");\n\t\tm_editableAction.insert(\"history\", m_sowHistory);\n\t\tm_preferencesAction->setIcon(QIcon(m_thmPath + \"preferences.png\"));\n\t\tm_preferencesAction->setObjectName(\"preferences\");\n\t\tm_editableAction.insert(\"preferences\", m_preferencesAction);\n\t\tm_addBookmarksAction->setIcon(QIcon(m_thmPath + \"addFavoris.png\"));\n\t\tm_addBookmarksAction->setObjectName(\"addBookmarks\");\n\t\tm_editableAction.insert(\"addBookmarks\", m_addBookmarksAction);\n\t\tm_bookmarsManagerAction->setIcon(QIcon(m_thmPath + \"favoris.png\"));\n\t\tm_bookmarsManagerAction->setObjectName(\"bookmarksManager\");\n\t\tm_editableAction.insert(\"bookmarksManager\", m_bookmarsManagerAction);\n\t\tm_newTabAction->setIcon(QIcon(m_thmPath + \"newTab.png\"));\n\t\tm_newTabAction->setObjectName(\"newTab\");\n\t\tm_editableAction.insert(\"newTab\", m_newTabAction);\n\t\tm_newWindowAction->setIcon(QIcon(m_thmPath + \"newWindow.png\"));\n\t\tm_newWindowAction->setObjectName(\"newWindow\");\n\t\tm_editableAction.insert(\"newWindow\", m_newWindowAction);\n\t\tm_exitAction->setIcon(QIcon(m_thmPath + \"exit.png\"));\n\n\n}\n\nvoid MainWindow::loadToolBar(QString & filePath)\n{\n\tQFile file{ filePath };\n\n\tif (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"Impossible d'ouvrir le thème de la barre d'outils\"));\n\t}\n\n\tQTextStream in{ &file };\n\n\tunsigned version{ 0 };\n\tin >> version;\n\n\tunsigned nbreToolBar{ 0 };\n\tswitch (version)\n\t{\n\tcase THEME_V0:\n\t\tin >> nbreToolBar;\n\n\t\tfor (size_t i{ 0 }; i < nbreToolBar; ++i) {\n\t\t\tToolBar *newToolBar{ addNewToolBar() };\n\t\t\tnewToolBar->loadToolBarV0(in);\n\t\t}\n\t\tbreak;\n\tcase THEME_V1:\n\t\tin >> nbreToolBar;\n\n\t\tfor (size_t i{ 0 }; i < nbreToolBar; ++i) {\n\t\t\tm_toolBars.push_back(new ToolBar(this));\n\t\t\tconnect(m_toolBars[i], &ToolBar::topLevelChanged, this, &MainWindow::unsaveThm);\n\t\t\tm_toolBars[i]->loadToolBarV1(in);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"La version \") + QString::number(version) + tr(\" est inconnue\"));\n\t\tbreak;\n\t}\n}\n\nToolBar *MainWindow::addNewToolBar(Qt::ToolBarArea area)\n{\n\tToolBar *newToolBar{ new ToolBar(this) };\n\tm_toolBars.push_back(newToolBar);\n\taddToolBar(area, newToolBar);\n\n\tconnect(newToolBar, &ToolBar::topLevelChanged, this, &MainWindow::unsaveThm);\n\n\treturn newToolBar;\n}\n\nvoid MainWindow::createNewToolBar()\n{\n\tQToolBar *newToolBar{ addNewToolBar() };\n}\n\nvoid MainWindow::deleteToolBar(ToolBar *toolBar)\n{\n\tremoveToolBar(toolBar);\n\tm_toolBars.remove(m_toolBars.indexOf(toolBar));\n}\n\nvoid MainWindow::newThm()\n{\n\tbool ok{ false };\n\tm_thmName = QInputDialog::getText(this, tr(\"Nom du thème\"), tr(\"Entrez le nom du thème\"), QLineEdit::Normal, QString(), &ok);\n\n\tif (ok && !m_thmName.isEmpty()) {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\n\t\tm_thmPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + \"\/SNThemeEditor\/\" + m_thmName + \"\/\";\n\t\tQDir *themePath{ new QDir(m_thmPath) };\n\t\tthemePath->mkpath(m_thmPath);\n\t\tcopyDir(\"SIcons\", themePath->absolutePath());\n\t\tToolBar *default = addNewToolBar();\n\t\tcreateActions();\n\n\t\tthmSaved = false;\n\t\tm_saveThm->setEnabled(true);\n\t\tm_saveThmAs->setEnabled(true);\n\t\tm_newToolBar->setEnabled(true);\n\t}\n}\n\nvoid MainWindow::openThm()\n{\n\tQString filePath{ QFileDialog::getOpenFileName(this, tr(\"Ouvrir un thème\"), QString(), \"Sielo Thèmes (*.snthm)\") };\n\n\tif (!filePath.isEmpty()) {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\n\t\tQFileInfo thmInfo{ filePath };\n\t\tm_thmPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + \"\/SNThemeEditor\/\" + thmInfo.baseName() + \"\/\";\n\t\tm_savedThmPath = filePath;\n\t\tQDir *themePath{ new QDir(m_thmPath) };\n\t\tthemePath->mkpath(m_thmPath);\n\t\tThemeManager::decompressTheme(filePath, themePath->absolutePath());\n\n\t\tloadToolBar(QString(m_thmPath + \"toolBar.txt\"));\n\t\tcreateActions();\n\t\tm_saveThm->setEnabled(true);\n\t\tm_saveThmAs->setEnabled(true);\n\t\tm_newToolBar->setEnabled(true);\n\t}\n}\n\nvoid MainWindow::saveThm()\n{\n\tQString version{ \"2\" };\n\tQString toolBarNumber{ QString::number(m_toolBars.size()) };\n\n\tif (m_savedThmPath.isEmpty()) {\n\t\tm_savedThmPath = QFileDialog::getSaveFileName(this, tr(\"Sauvegarde du thème\"), QString(), \"Sielo Thème (*.snthm)\");\n\n\t\tif (m_savedThmPath.isEmpty()) \n\t\t\treturn;\n\t}\n\tQFile toolBarTxt{ m_thmPath + \"toolBar.txt\" };\n\tif (!toolBarTxt.open(QIODevice::WriteOnly | QIODevice::Text)) {\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"Impossible de sauvegarder le thème\"));\n\t\treturn;\n\t}\n\n\tQTextStream out{&toolBarTxt};\n\tout << version << ' ' << toolBarNumber << ' ';\n\tfor (int i{ 0 }; i < m_toolBars.size(); ++i) {\n\t\tToolBar *toolBar{ m_toolBars[i] };\n\t\tif (toolBarArea(toolBar) == Qt::TopToolBarArea)\n\t\t\tout << \"top \";\n\t\telse if (toolBarArea(toolBar) == Qt::BottomToolBarArea)\n\t\t\tout << \"bottom \";\n\t\telse if (toolBarArea(toolBar) == Qt::LeftToolBarArea)\n\t\t\tout << \"left \";\n\t\telse if (toolBarArea(toolBar) == Qt::RightToolBarArea)\n\t\t\tout << \"right \";\n\n\t\tout << QString::number(toolBar->iconSize) << ' ';\n\t\tout << QString::number(toolBar->itemInToolBar.size()) << ' ';\n\n\t\tfor (int j{ 0 }; j < toolBar->itemInToolBar.size(); ++j)\n\t\t\tout << toolBar->itemInToolBar[j]->objectName() << ' ';\n\t}\n\n\ttoolBarTxt.close();\n\n\tThemeManager::compressTheme(m_thmPath, m_savedThmPath);\n\tthmSaved = true;\n}\n\nvoid MainWindow::saveThmAs()\n{\n\tQString newThmPath = QFileDialog::getSaveFileName(this, tr(\"Sauvegarde du thème\"), QString(), \"Sielo Thème (*.snthm)\");\n\n\tif (newThmPath.isEmpty()) \n\t\treturn;\n\telse {\n\t\tm_savedThmPath = newThmPath;\n\t\tsaveThm();\n\t}\n}\n\nvoid MainWindow::closeThm()\n{\n\tfor (int i{ 0 }; i < m_toolBars.size(); ++i) \n\t\tremoveToolBar(m_toolBars[i]);\n\n\tm_toolBars.clear();\n\tm_editableAction.clear();\n\n\tQDir themePath{ m_thmPath };\n\tthemePath.removeRecursively();\n\n\tthmSaved = true;\n\tm_savePath = QString();\n\tm_thmPath = QString();\n\tm_thmName = QString();\n\tm_savedThmPath = QString();\n}\n\nvoid MainWindow::unsaveThm()\n{\n\tthmSaved = false;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent * event)\n{\n\tif (!thmSaved) {\n\t\tQMessageBox::StandardButton save = QMessageBox::question(this, tr(\"Sauvegarder\"), tr(\"Voulez vous sauvegarder le thème\"), QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Close);\n\t\t\n\t\tif (save == QMessageBox::Save) {\n\t\t\tsaveThm();\n\t\t\tcloseThm();\n\t\t\tevent->accept();\n\t\t}\n\t\telse if (save == QMessageBox::Close) {\n\t\t\tcloseThm();\n\t\t\tevent->accept();\n\t\t}\n\t\telse\n\t\t\tevent->ignore();\n\t}\n\telse {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\t\tevent->accept();\n\t}\n}\n\nvoid MainWindow::copyDir(QString src, QString dst)\n{\n\tQDir dir(src);\n\tif (!dir.exists())\n\t\treturn;\n\n\tforeach(QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {\n\t\tQString dst_path = dst + QDir::separator() + d;\n\t\tdir.mkpath(dst_path);\n\t\tcopyDir(src + QDir::separator() + d, dst_path);\n\t}\n\n\tforeach(QString f, dir.entryList(QDir::Files)) {\n\t\tQFile::copy(src + QDir::separator() + f, dst + QDir::separator() + f);\n\t}\n}<commit_msg>Set shortcuts<commit_after>#include \"includes\/MainWindow.hpp\"\n#include \"includes\/ThemeManager.hpp\"\n\n#include <QMenu>\n#include <QMenuBar>\n#include <QMessageBox>\n#include <QInputDialog>\n#include <QFileDialog>\n#include <QTextStream>\n#include <QStandardPaths>\n#include <QDir>\n\nconst unsigned int THEME_V0 = 1;\nconst unsigned int THEME_V1 = 2;\n\nMainWindow::MainWindow(QWidget * parent) : \n\tQMainWindow(parent)\n{\n\tcreateMenus();\n\tresize(1024, 768);\n\n\tconnect(m_newThm, &QAction::triggered, this, &MainWindow::newThm);\n\tconnect(m_openThm, &QAction::triggered, this, &MainWindow::openThm);\n\tconnect(m_saveThm, &QAction::triggered, this, &MainWindow::saveThm);\n\tconnect(m_saveThmAs, &QAction::triggered, this, &MainWindow::saveThmAs);\n\t\n\tconnect(m_newToolBar, &QAction::triggered, this, &MainWindow::createNewToolBar);\n\n\tm_newThm->setShortcut(QKeySequence::New);\n\tm_openThm->setShortcut(QKeySequence::Open);\n\tm_saveThm->setShortcut(QKeySequence::Save);\n\tm_saveThmAs->setShortcuts(QKeySequence::SaveAs);\n\n\tm_newToolBar->setShortcut(QKeySequence(\"Ctrl+T\"));\n\n\/\/\tQMessageBox::information(this, \"DEBUG\", QStandardPaths::writableLocation(QStandardPaths::TempLocation));\n}\n\nMainWindow::~MainWindow()\n{\n\t\/\/ Empty\n}\n\nvoid MainWindow::createMenus()\n{\n\tQMenu *fileMenu = menuBar()->addMenu(tr(\"&Fichier\"));\n\n\tfileMenu->addAction(m_newThm);\n\tfileMenu->addAction(m_openThm);\n\tfileMenu->addSeparator();\n\tfileMenu->addAction(m_saveThm);\n\tfileMenu->addAction(m_saveThmAs);\n\tm_saveThm->setEnabled(false);\n\tm_saveThmAs->setEnabled(false);\n\n\tQMenu *themeMenu = menuBar()->addMenu(tr(\"&Thèmes\"));\n\n\tthemeMenu->addAction(m_newToolBar);\n\tm_newToolBar->setEnabled(false);\n}\n\nvoid MainWindow::createActions()\n{\n\t\tm_backAction->setIcon(QIcon(m_thmPath + \"back.png\"));\n\t\tm_backAction->setObjectName(\"back\");\n\t\tm_editableAction.insert(\"back\", m_backAction);\n\t\tm_nextAction->setIcon(QIcon(m_thmPath + \"next.png\"));\n\t\tm_nextAction->setObjectName(\"next\");\n\t\tm_editableAction.insert(\"next\", m_nextAction);\n\t\tm_homeAction->setIcon(QIcon(m_thmPath + \"home.png\"));\n\t\tm_homeAction->setObjectName(\"home\");\n\t\tm_editableAction.insert(\"home\", m_homeAction);\n\t\tm_refreshOrStopAction->setIcon(QIcon(m_thmPath + \"refresh.png\"));\n\t\tm_refreshOrStopAction->setObjectName(\"refresh\");\n\t\tm_editableAction.insert(\"refresh\", m_refreshOrStopAction);\n\t\tm_goAction->setIcon(QIcon(m_thmPath + \"go.png\"));\n\t\tm_goAction->setObjectName(\"go\");\n\t\tm_editableAction.insert(\"go\", m_goAction);\n\t\tm_searchAction->setIcon(QIcon(m_thmPath + \"search.png\"));\n\t\tm_searchAction->setObjectName(\"search\");\n\t\tm_editableAction.insert(\"search\", m_searchAction);\n\t\tm_sowHistory->setIcon(QIcon(m_thmPath + \"history.png\"));\n\t\tm_sowHistory->setObjectName(\"history\");\n\t\tm_editableAction.insert(\"history\", m_sowHistory);\n\t\tm_preferencesAction->setIcon(QIcon(m_thmPath + \"preferences.png\"));\n\t\tm_preferencesAction->setObjectName(\"preferences\");\n\t\tm_editableAction.insert(\"preferences\", m_preferencesAction);\n\t\tm_addBookmarksAction->setIcon(QIcon(m_thmPath + \"addFavoris.png\"));\n\t\tm_addBookmarksAction->setObjectName(\"addBookmarks\");\n\t\tm_editableAction.insert(\"addBookmarks\", m_addBookmarksAction);\n\t\tm_bookmarsManagerAction->setIcon(QIcon(m_thmPath + \"favoris.png\"));\n\t\tm_bookmarsManagerAction->setObjectName(\"bookmarksManager\");\n\t\tm_editableAction.insert(\"bookmarksManager\", m_bookmarsManagerAction);\n\t\tm_newTabAction->setIcon(QIcon(m_thmPath + \"newTab.png\"));\n\t\tm_newTabAction->setObjectName(\"newTab\");\n\t\tm_editableAction.insert(\"newTab\", m_newTabAction);\n\t\tm_newWindowAction->setIcon(QIcon(m_thmPath + \"newWindow.png\"));\n\t\tm_newWindowAction->setObjectName(\"newWindow\");\n\t\tm_editableAction.insert(\"newWindow\", m_newWindowAction);\n\t\tm_exitAction->setIcon(QIcon(m_thmPath + \"exit.png\"));\n\n\n}\n\nvoid MainWindow::loadToolBar(QString & filePath)\n{\n\tQFile file{ filePath };\n\n\tif (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"Impossible d'ouvrir le thème de la barre d'outils\"));\n\t}\n\n\tQTextStream in{ &file };\n\n\tunsigned version{ 0 };\n\tin >> version;\n\n\tunsigned nbreToolBar{ 0 };\n\tswitch (version)\n\t{\n\tcase THEME_V0:\n\t\tin >> nbreToolBar;\n\n\t\tfor (size_t i{ 0 }; i < nbreToolBar; ++i) {\n\t\t\tToolBar *newToolBar{ addNewToolBar() };\n\t\t\tnewToolBar->loadToolBarV0(in);\n\t\t}\n\t\tbreak;\n\tcase THEME_V1:\n\t\tin >> nbreToolBar;\n\n\t\tfor (size_t i{ 0 }; i < nbreToolBar; ++i) {\n\t\t\tm_toolBars.push_back(new ToolBar(this));\n\t\t\tconnect(m_toolBars[i], &ToolBar::topLevelChanged, this, &MainWindow::unsaveThm);\n\t\t\tm_toolBars[i]->loadToolBarV1(in);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"La version \") + QString::number(version) + tr(\" est inconnue\"));\n\t\tbreak;\n\t}\n}\n\nToolBar *MainWindow::addNewToolBar(Qt::ToolBarArea area)\n{\n\tToolBar *newToolBar{ new ToolBar(this) };\n\tm_toolBars.push_back(newToolBar);\n\taddToolBar(area, newToolBar);\n\n\tconnect(newToolBar, &ToolBar::topLevelChanged, this, &MainWindow::unsaveThm);\n\n\treturn newToolBar;\n}\n\nvoid MainWindow::createNewToolBar()\n{\n\tQToolBar *newToolBar{ addNewToolBar() };\n}\n\nvoid MainWindow::deleteToolBar(ToolBar *toolBar)\n{\n\tremoveToolBar(toolBar);\n\tm_toolBars.remove(m_toolBars.indexOf(toolBar));\n}\n\nvoid MainWindow::newThm()\n{\n\tbool ok{ false };\n\tm_thmName = QInputDialog::getText(this, tr(\"Nom du thème\"), tr(\"Entrez le nom du thème\"), QLineEdit::Normal, QString(), &ok);\n\n\tif (ok && !m_thmName.isEmpty()) {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\n\t\tm_thmPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + \"\/SNThemeEditor\/\" + m_thmName + \"\/\";\n\t\tQDir *themePath{ new QDir(m_thmPath) };\n\t\tthemePath->mkpath(m_thmPath);\n\t\tcopyDir(\"SIcons\", themePath->absolutePath());\n\t\tToolBar *default = addNewToolBar();\n\t\tcreateActions();\n\n\t\tthmSaved = false;\n\t\tm_saveThm->setEnabled(true);\n\t\tm_saveThmAs->setEnabled(true);\n\t\tm_newToolBar->setEnabled(true);\n\t}\n}\n\nvoid MainWindow::openThm()\n{\n\tQString filePath{ QFileDialog::getOpenFileName(this, tr(\"Ouvrir un thème\"), QString(), \"Sielo Thèmes (*.snthm)\") };\n\n\tif (!filePath.isEmpty()) {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\n\t\tQFileInfo thmInfo{ filePath };\n\t\tm_thmPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + \"\/SNThemeEditor\/\" + thmInfo.baseName() + \"\/\";\n\t\tm_savedThmPath = filePath;\n\t\tQDir *themePath{ new QDir(m_thmPath) };\n\t\tthemePath->mkpath(m_thmPath);\n\t\tThemeManager::decompressTheme(filePath, themePath->absolutePath());\n\n\t\tloadToolBar(QString(m_thmPath + \"toolBar.txt\"));\n\t\tcreateActions();\n\t\tm_saveThm->setEnabled(true);\n\t\tm_saveThmAs->setEnabled(true);\n\t\tm_newToolBar->setEnabled(true);\n\t}\n}\n\nvoid MainWindow::saveThm()\n{\n\tQString version{ \"2\" };\n\tQString toolBarNumber{ QString::number(m_toolBars.size()) };\n\n\tif (m_savedThmPath.isEmpty()) {\n\t\tm_savedThmPath = QFileDialog::getSaveFileName(this, tr(\"Sauvegarde du thème\"), QString(), \"Sielo Thème (*.snthm)\");\n\n\t\tif (m_savedThmPath.isEmpty()) \n\t\t\treturn;\n\t}\n\tQFile toolBarTxt{ m_thmPath + \"toolBar.txt\" };\n\tif (!toolBarTxt.open(QIODevice::WriteOnly | QIODevice::Text)) {\n\t\tQMessageBox::critical(this, tr(\"Erreur\"), tr(\"Impossible de sauvegarder le thème\"));\n\t\treturn;\n\t}\n\n\tQTextStream out{&toolBarTxt};\n\tout << version << ' ' << toolBarNumber << ' ';\n\tfor (int i{ 0 }; i < m_toolBars.size(); ++i) {\n\t\tToolBar *toolBar{ m_toolBars[i] };\n\t\tif (toolBarArea(toolBar) == Qt::TopToolBarArea)\n\t\t\tout << \"top \";\n\t\telse if (toolBarArea(toolBar) == Qt::BottomToolBarArea)\n\t\t\tout << \"bottom \";\n\t\telse if (toolBarArea(toolBar) == Qt::LeftToolBarArea)\n\t\t\tout << \"left \";\n\t\telse if (toolBarArea(toolBar) == Qt::RightToolBarArea)\n\t\t\tout << \"right \";\n\n\t\tout << QString::number(toolBar->iconSize) << ' ';\n\t\tout << QString::number(toolBar->itemInToolBar.size()) << ' ';\n\n\t\tfor (int j{ 0 }; j < toolBar->itemInToolBar.size(); ++j)\n\t\t\tout << toolBar->itemInToolBar[j]->objectName() << ' ';\n\t}\n\n\ttoolBarTxt.close();\n\n\tThemeManager::compressTheme(m_thmPath, m_savedThmPath);\n\tthmSaved = true;\n}\n\nvoid MainWindow::saveThmAs()\n{\n\tQString newThmPath = QFileDialog::getSaveFileName(this, tr(\"Sauvegarde du thème\"), QString(), \"Sielo Thème (*.snthm)\");\n\n\tif (newThmPath.isEmpty()) \n\t\treturn;\n\telse {\n\t\tm_savedThmPath = newThmPath;\n\t\tsaveThm();\n\t}\n}\n\nvoid MainWindow::closeThm()\n{\n\tfor (int i{ 0 }; i < m_toolBars.size(); ++i) \n\t\tremoveToolBar(m_toolBars[i]);\n\n\tm_toolBars.clear();\n\tm_editableAction.clear();\n\n\tQDir themePath{ m_thmPath };\n\tthemePath.removeRecursively();\n\n\tthmSaved = true;\n\tm_savePath = QString();\n\tm_thmPath = QString();\n\tm_thmName = QString();\n\tm_savedThmPath = QString();\n}\n\nvoid MainWindow::unsaveThm()\n{\n\tthmSaved = false;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent * event)\n{\n\tif (!thmSaved) {\n\t\tQMessageBox::StandardButton save = QMessageBox::question(this, tr(\"Sauvegarder\"), tr(\"Voulez vous sauvegarder le thème\"), QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Close);\n\t\t\n\t\tif (save == QMessageBox::Save) {\n\t\t\tsaveThm();\n\t\t\tcloseThm();\n\t\t\tevent->accept();\n\t\t}\n\t\telse if (save == QMessageBox::Close) {\n\t\t\tcloseThm();\n\t\t\tevent->accept();\n\t\t}\n\t\telse\n\t\t\tevent->ignore();\n\t}\n\telse {\n\t\tif (!m_thmPath.isEmpty())\n\t\t\tcloseThm();\n\t\tevent->accept();\n\t}\n}\n\nvoid MainWindow::copyDir(QString src, QString dst)\n{\n\tQDir dir(src);\n\tif (!dir.exists())\n\t\treturn;\n\n\tforeach(QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {\n\t\tQString dst_path = dst + QDir::separator() + d;\n\t\tdir.mkpath(dst_path);\n\t\tcopyDir(src + QDir::separator() + d, dst_path);\n\t}\n\n\tforeach(QString f, dir.entryList(QDir::Files)) {\n\t\tQFile::copy(src + QDir::separator() + f, dst + QDir::separator() + f);\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"timer.hpp\"\n#include \"scheduler.hpp\"\n#include \"logging.hpp\"\n#include \"kernel.hpp\" \/\/suspend_boot\n\n#include \"drivers\/pit.hpp\"\n#include \"drivers\/hpet.hpp\"\n\n#include \"fs\/sysfs.hpp\"\n\nnamespace {\n\nuint64_t _timer_ticks = 0;\nuint64_t _timer_seconds = 0;\nuint64_t _timer_milliseconds = 0;\nuint64_t _timer_frequency = 0;\n\n\/\/TODO The uptime in seconds with HPET is not correct\nstd::string sysfs_uptime(){\n return std::to_string(timer::seconds());\n}\n\nbool find_hw_timer(){\n if(hpet::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install HPET driver\\n\");\n }\n\n if(pit::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install PIT driver\\n\");\n }\n\n return false;\n}\n\n} \/\/End of anonymous namespace\n\nvoid timer::install(){\n if(!find_hw_timer()){\n logging::logf(logging::log_level::ERROR, \"Unable to install any timer driver\\n\");\n suspend_boot();\n }\n\n sysfs::set_dynamic_value(\"\/sys\/\", \"uptime\", &sysfs_uptime);\n}\n\nvoid timer::tick(){\n ++_timer_ticks;\n\n scheduler::tick();\n\n if(_timer_ticks % frequency() == 0){\n ++_timer_seconds;\n }\n\n if(_timer_ticks % (frequency() \/ 1000) == 0){\n ++_timer_milliseconds;\n }\n}\n\nuint64_t timer::ticks(){\n return _timer_ticks;\n}\n\nuint64_t timer::seconds(){\n return _timer_seconds;\n}\n\nuint64_t timer::milliseconds(){\n return _timer_milliseconds;\n}\n\nuint64_t timer::frequency(){\n return _timer_frequency;\n}\n\nvoid timer::frequency(uint64_t freq){\n auto old_frequency = _timer_frequency;\n\n _timer_frequency = freq;\n\n logging::logf(logging::log_level::DEBUG, \"timer: Frequency set to %u Hz\\n\", freq);\n\n scheduler::frequency_updated(old_frequency, _timer_frequency);\n}\n<commit_msg>Cleanup<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"timer.hpp\"\n#include \"scheduler.hpp\"\n#include \"logging.hpp\"\n#include \"kernel.hpp\" \/\/suspend_boot\n\n#include \"drivers\/pit.hpp\"\n#include \"drivers\/hpet.hpp\"\n\n#include \"fs\/sysfs.hpp\"\n\nnamespace {\n\nvolatile uint64_t _timer_ticks = 0;\nvolatile uint64_t _timer_seconds = 0;\nvolatile uint64_t _timer_milliseconds = 0;\nuint64_t _timer_frequency = 0;\n\n\/\/TODO The uptime in seconds with HPET is not correct\nstd::string sysfs_uptime(){\n return std::to_string(timer::seconds());\n}\n\nbool find_hw_timer(){\n if(hpet::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install HPET driver\\n\");\n }\n\n if(pit::install()){\n return true;\n } else {\n logging::logf(logging::log_level::DEBUG, \"timer: Unable to install PIT driver\\n\");\n }\n\n return false;\n}\n\n} \/\/End of anonymous namespace\n\nvoid timer::install(){\n if(!find_hw_timer()){\n logging::logf(logging::log_level::ERROR, \"Unable to install any timer driver\\n\");\n suspend_boot();\n }\n\n sysfs::set_dynamic_value(\"\/sys\/\", \"uptime\", &sysfs_uptime);\n}\n\nvoid timer::tick(){\n ++_timer_ticks;\n\n scheduler::tick();\n\n if(_timer_ticks % frequency() == 0){\n ++_timer_seconds;\n }\n\n if(_timer_ticks % (frequency() \/ 1000) == 0){\n ++_timer_milliseconds;\n }\n}\n\nuint64_t timer::ticks(){\n return _timer_ticks;\n}\n\nuint64_t timer::seconds(){\n return _timer_seconds;\n}\n\nuint64_t timer::milliseconds(){\n return _timer_milliseconds;\n}\n\nuint64_t timer::frequency(){\n return _timer_frequency;\n}\n\nvoid timer::frequency(uint64_t freq){\n auto old_frequency = _timer_frequency;\n\n _timer_frequency = freq;\n\n logging::logf(logging::log_level::DEBUG, \"timer: Frequency set to %u Hz\\n\", freq);\n\n scheduler::frequency_updated(old_frequency, _timer_frequency);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------\n\/\/ Copyright 2016 Ontario Institute for Cancer Research\n\/\/ Written by Matei David (matei.david@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\n\/\/\n\/\/ Getopt\n\/\/\n#define SUBPROGRAM \"extract\"\n#define LOG_FACILITY SUBPROGRAM\n\n#include <iostream>\n#include <sstream>\n#include <getopt.h>\n\n#include \"nanopolish_read_db.h\"\n#include \"nanopolish_extract.h\"\n#include \"nanopolish_common.h\"\n#include \"fs_support.hpp\"\n#include \"logger.hpp\"\n#include \"alg.hpp\"\n\nstatic const char *EXTRACT_VERSION_MESSAGE =\nSUBPROGRAM \" Version \" PACKAGE_VERSION \"\\n\"\n\"Written by Jared Simpson.\\n\"\n\"\\n\"\n\"Copyright 2015 Ontario Institute for Cancer Research\\n\";\n\nstatic const char *EXTRACT_USAGE_MESSAGE =\n\"Usage: \" PACKAGE_NAME \" \" SUBPROGRAM \" [OPTIONS] <fast5|dir>...\\n\"\n\"Extract reads in fasta format\\n\"\n\"\\n\"\n\" --help display this help and exit\\n\"\n\" --version display version\\n\"\n\" -v, --verbose display verbose output\\n\"\n\" -r, --recurse recurse into subdirectories\\n\"\n\" -q, --fastq extract fastq (default: fasta)\\n\"\n\" -t, --type=TYPE read type: template, complement, 2d, 2d-or-template, any\\n\"\n\" (default: 2d-or-template)\\n\"\n\" -b, --basecaller=NAME[:VERSION] consider only data produced by basecaller NAME,\\n\"\n\" optionally with given exact VERSION\\n\"\n\" -o, --output=FILE write output to FILE (default: stdout)\\n\"\n\"\\nReport bugs to \" PACKAGE_BUGREPORT \"\\n\\n\";\n\nnamespace opt\n{\n static unsigned int verbose = 0;\n static bool recurse = false;\n static std::string read_type = \"2d-or-template\";\n static std::string basecaller_name;\n static std::string basecaller_version;\n static bool fastq = false;\n static std::string output_file;\n static std::deque< std::string > paths;\n static unsigned total_files_count = 0;\n static unsigned total_files_used_count = 0;\n}\nstatic std::ostream* os_p;\n\nstd::vector< std::pair< unsigned, std::string > >\nget_preferred_basecall_groups(const fast5::File& f)\n{\n bool have_2d = false;\n std::vector< std::pair< unsigned, std::string > > res;\n \/\/ check 2d\n if (opt::read_type == \"any\"\n or opt::read_type == \"2d\"\n or opt::read_type == \"2d-or-template\")\n {\n const auto& gr_l = f.get_basecall_strand_group_list(2);\n for (const auto& gr : gr_l)\n {\n auto bcd = f.get_basecall_group_description(gr);\n \/\/ Never use minknow basecalls\n if(bcd.name == \"minknow\") {\n continue;\n }\n\n if (not opt::basecaller_name.empty())\n {\n if ((bcd.name != opt::basecaller_name) or\n (not opt::basecaller_version.empty() and\n bcd.version != opt::basecaller_version))\n {\n continue;\n }\n }\n\n if (f.have_basecall_fastq(2, gr)\n and f.have_basecall_events(0, gr)\n and f.have_basecall_events(1, gr))\n {\n have_2d = true;\n res.push_back(std::make_pair(2, gr));\n if (opt::read_type != \"any\")\n {\n break;\n }\n }\n }\n }\n \/\/ check 1d\n for (unsigned st = 0; st < 2; ++st)\n {\n if (opt::read_type == \"any\"\n or (st == 0\n and (opt::read_type == \"template\"\n or (not have_2d and opt::read_type == \"2d-or-template\")))\n or (st == 1\n and opt::read_type == \"complement\"))\n {\n const auto& gr_l = f.get_basecall_strand_group_list(st);\n for (const auto& gr : gr_l)\n {\n auto bcd = f.get_basecall_group_description(gr);\n \/\/ Never use minknow basecalls\n if(bcd.name == \"minknow\") {\n continue;\n }\n\n if (not opt::basecaller_name.empty())\n {\n if ((bcd.name != opt::basecaller_name) or\n (not opt::basecaller_version.empty() and\n bcd.version != opt::basecaller_version))\n {\n continue;\n }\n }\n if (f.have_basecall_fastq(st, gr)\n and f.have_basecall_events(st, gr))\n {\n res.push_back(std::make_pair(st, gr));\n if (opt::read_type != \"any\")\n {\n break;\n }\n }\n }\n }\n }\n LOG(debug)\n << \"preferred_groups: \"\n << alg::os_join(res, \", \", [] (const decltype(res)::value_type& p) {\n std::ostringstream oss;\n oss << \"(\" << p.first << \":\" << p.second << \")\";\n return oss.str();\n })\n << \"\\n\";\n return res;\n} \/\/ get_preferred_basecall_groups\n\nvoid process_file(const std::string& fn)\n{\n LOG(debug) << fn << \"\\n\";\n auto pos = fn.find_last_of('\/');\n std::string base_fn = (pos != std::string::npos? fn.substr(pos + 1) : fn);\n if (base_fn.substr(base_fn.size() - 6) == \".fast5\")\n {\n base_fn.resize(base_fn.size() - 6);\n }\n fast5::File f;\n do\n {\n try\n {\n \/\/ open file\n f.open(fn);\n ++opt::total_files_count;\n \/\/ get preferred basecall groups\n auto l = get_preferred_basecall_groups(f);\n if (l.empty())\n {\n LOG(info) << \"file [\" << fn << \"]: no basecalling data suitable for nanoplish\\n\";\n return;\n }\n ++opt::total_files_used_count;\n const auto& p = l.front();\n \/\/ get and parse fastq\n auto fq = f.get_basecall_fastq(p.first, p.second);\n auto fq_a = f.split_fq(fq);\n \/\/ construct name\n std::string name;\n std::istringstream(fq_a[0]) >> name;\n std::replace(name.begin(), name.end(), ':', '_');\n name += \":\" + p.second + \":\";\n if (p.first == 0)\n {\n name += \"template\";\n }\n else if (p.first == 1)\n {\n name += \"complement\";\n }\n else\n {\n name += \"2d\";\n }\n if (not opt::fastq)\n {\n (*os_p)\n << \">\" << name << \" \" << base_fn << \" \" << fn << \"\\n\"\n << fq_a[1] << \"\\n\";\n }\n else\n {\n (*os_p)\n << \"@\" << name << \" \" << base_fn << \" \" << fn << \"\\n\"\n << fq_a[1] << \"\\n\"\n << \"+\" << fq_a[2] << \"\\n\"\n << fq_a[3] << \"\\n\";\n }\n }\n catch (hdf5_tools::Exception& e)\n {\n LOG(warning) << fn << \": HDF5 error: \" << e.what() << \"\\n\";\n }\n } while (false);\n} \/\/ process_file\n\nvoid process_path(const std::string& path)\n{\n LOG(info) << path << \"\\n\";\n if (is_directory(path))\n {\n auto dir_list = list_directory(path);\n for (const auto& fn : dir_list)\n {\n if (fn == \".\" or fn == \"..\") continue;\n std::string full_fn = path + \"\/\" + fn;\n if (is_directory(full_fn))\n {\n if (opt::recurse)\n {\n opt::paths.push_back(full_fn);\n }\n else\n {\n LOG(info) << \"ignoring_subdir: \" << full_fn << \"\\n\";\n }\n }\n else if (fast5::File::is_valid_file(full_fn))\n {\n process_file(full_fn);\n }\n else\n {\n LOG(info) << \"ignoring_file: \" << full_fn << \"\\n\";\n }\n }\n }\n else \/\/ not is_directory; must be a fast5 file\n {\n if (fast5::File::is_valid_file(path))\n {\n process_file(path);\n }\n else\n {\n LOG(error) << \"path [\" << path << \"] is neither a fast5 file nor a directory\\n\";\n exit(EXIT_FAILURE);\n }\n }\n} \/\/ process_path\n\nstatic const char* shortopts = \"vrqt:o:b:\";\n\nenum {\n OPT_HELP = 1,\n OPT_VERSION,\n OPT_LOG_LEVEL,\n};\n\nstatic const struct option longopts[] = {\n { \"help\", no_argument, NULL, OPT_HELP },\n { \"version\", no_argument, NULL, OPT_VERSION },\n { \"log-level\", required_argument, NULL, OPT_LOG_LEVEL },\n { \"verbose\", no_argument, NULL, 'v' },\n { \"recurse\", no_argument, NULL, 'r' },\n { \"fastq\", no_argument, NULL, 'q' },\n { \"type\", required_argument, NULL, 't' },\n { \"output\", required_argument, NULL, 'o' },\n { \"basecaller\", required_argument, NULL, 'b' },\n { NULL, 0, NULL, 0 }\n};\n\nvoid parse_extract_options(int argc, char** argv)\n{\n bool die = false;\n std::vector< std::string> log_level;\n for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {\n std::istringstream arg(optarg != NULL ? optarg : \"\");\n switch (c) {\n case OPT_HELP:\n std::cout << EXTRACT_USAGE_MESSAGE;\n exit(EXIT_SUCCESS);\n case OPT_VERSION:\n std::cout << EXTRACT_VERSION_MESSAGE;\n exit(EXIT_SUCCESS);\n case OPT_LOG_LEVEL:\n log_level.push_back(arg.str());\n break;\n case 'v': opt::verbose++; break;\n case 'r': opt::recurse = true; break;\n case 'q': opt::fastq = true; break;\n case 't': arg >> opt::read_type; break;\n case 'o': arg >> opt::output_file; break;\n case 'b':\n arg >> opt::basecaller_name;\n auto i = opt::basecaller_name.find(':');\n if (i != std::string::npos)\n {\n opt::basecaller_version = opt::basecaller_name.substr(i + 1);\n opt::basecaller_name.resize(i);\n }\n break;\n }\n }\n \/\/ set log levels\n auto default_level = (int)logger::warning + opt::verbose;\n logger::Logger::set_default_level(default_level);\n logger::Logger::set_levels_from_options(log_level, &std::clog);\n \/\/ parse paths to process\n while (optind < argc)\n {\n std::string path = argv[optind++];\n while (path.size() > 1 and path[path.size() - 1] == '\/')\n {\n path.resize(path.size() - 1);\n }\n opt::paths.push_back(path);\n }\n if (opt::paths.empty())\n {\n std::cerr << SUBPROGRAM \": no paths to process\\n\";\n die = true;\n }\n \/\/ check read type\n if (not (opt::read_type == \"template\"\n or opt::read_type == \"complement\"\n or opt::read_type == \"2d\"\n or opt::read_type == \"2d-or-template\"\n or opt::read_type == \"any\"))\n {\n std::cerr << SUBPROGRAM \": invalid read type: \" << opt::read_type << \"\\n\";\n die = true;\n }\n \/\/ die if errors\n if (die)\n {\n std::cerr << \"\\n\" << EXTRACT_USAGE_MESSAGE;\n exit(EXIT_FAILURE);\n }\n LOG(info) << \"paths: \" << alg::os_join(opt::paths, \" \") << \"\\n\";\n LOG(info) << \"recurse: \" << (opt::recurse? \"yes\" : \"no\") << \"\\n\";\n LOG(info) << \"read_type: \" << opt::read_type << \"\\n\";\n LOG(info) << \"basecaller_name: \" << opt::basecaller_name << \"\\n\";\n LOG(info) << \"basecaller_version: \" << opt::basecaller_version << \"\\n\";\n}\n\nint extract_main(int argc, char** argv)\n{\n parse_extract_options(argc, argv);\n\n \/\/ Iterate over fast5 collection extracting the sequence reads\n \/\/ We do this in a block so the file is automatically closed\n \/\/ when ofs goes out of scope.\n {\n std::ofstream ofs;\n if (not opt::output_file.empty())\n {\n ofs.open(opt::output_file);\n os_p = &ofs;\n }\n else\n {\n os_p = &std::cout;\n }\n for (unsigned i = 0; i < opt::paths.size(); ++i)\n {\n process_path(opt::paths[i]);\n }\n }\n\n \/\/ Build the ReadDB from the output file\n ReadDB read_db;\n read_db.build(opt::output_file);\n\n std::clog << \"[extract] found \" << opt::total_files_count\n << \" files, extracted \" << opt::total_files_used_count\n << \" reads\\n\";\n return 0;\n}\n<commit_msg>make the -o option to extract mandatory<commit_after>\/\/---------------------------------------------------------\n\/\/ Copyright 2016 Ontario Institute for Cancer Research\n\/\/ Written by Matei David (matei.david@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\n\/\/\n\/\/ Getopt\n\/\/\n#define SUBPROGRAM \"extract\"\n#define LOG_FACILITY SUBPROGRAM\n\n#include <iostream>\n#include <sstream>\n#include <getopt.h>\n\n#include \"nanopolish_read_db.h\"\n#include \"nanopolish_extract.h\"\n#include \"nanopolish_common.h\"\n#include \"fs_support.hpp\"\n#include \"logger.hpp\"\n#include \"alg.hpp\"\n\nstatic const char *EXTRACT_VERSION_MESSAGE =\nSUBPROGRAM \" Version \" PACKAGE_VERSION \"\\n\"\n\"Written by Jared Simpson.\\n\"\n\"\\n\"\n\"Copyright 2015 Ontario Institute for Cancer Research\\n\";\n\nstatic const char *EXTRACT_USAGE_MESSAGE =\n\"Usage: \" PACKAGE_NAME \" \" SUBPROGRAM \" [OPTIONS] <fast5|dir>...\\n\"\n\"Extract reads in fasta format\\n\"\n\"\\n\"\n\" --help display this help and exit\\n\"\n\" --version display version\\n\"\n\" -v, --verbose display verbose output\\n\"\n\" -r, --recurse recurse into subdirectories\\n\"\n\" -q, --fastq extract fastq (default: fasta)\\n\"\n\" -t, --type=TYPE read type: template, complement, 2d, 2d-or-template, any\\n\"\n\" (default: 2d-or-template)\\n\"\n\" -b, --basecaller=NAME[:VERSION] consider only data produced by basecaller NAME,\\n\"\n\" optionally with given exact VERSION\\n\"\n\" -o, --output=FILE write output to FILE\\n\"\n\"\\nReport bugs to \" PACKAGE_BUGREPORT \"\\n\\n\";\n\nnamespace opt\n{\n static unsigned int verbose = 0;\n static bool recurse = false;\n static std::string read_type = \"2d-or-template\";\n static std::string basecaller_name;\n static std::string basecaller_version;\n static bool fastq = false;\n static std::string output_file;\n static std::deque< std::string > paths;\n static unsigned total_files_count = 0;\n static unsigned total_files_used_count = 0;\n}\nstatic std::ostream* os_p;\n\nstd::vector< std::pair< unsigned, std::string > >\nget_preferred_basecall_groups(const fast5::File& f)\n{\n bool have_2d = false;\n std::vector< std::pair< unsigned, std::string > > res;\n \/\/ check 2d\n if (opt::read_type == \"any\"\n or opt::read_type == \"2d\"\n or opt::read_type == \"2d-or-template\")\n {\n const auto& gr_l = f.get_basecall_strand_group_list(2);\n for (const auto& gr : gr_l)\n {\n auto bcd = f.get_basecall_group_description(gr);\n \/\/ Never use minknow basecalls\n if(bcd.name == \"minknow\") {\n continue;\n }\n\n if (not opt::basecaller_name.empty())\n {\n if ((bcd.name != opt::basecaller_name) or\n (not opt::basecaller_version.empty() and\n bcd.version != opt::basecaller_version))\n {\n continue;\n }\n }\n\n if (f.have_basecall_fastq(2, gr)\n and f.have_basecall_events(0, gr)\n and f.have_basecall_events(1, gr))\n {\n have_2d = true;\n res.push_back(std::make_pair(2, gr));\n if (opt::read_type != \"any\")\n {\n break;\n }\n }\n }\n }\n \/\/ check 1d\n for (unsigned st = 0; st < 2; ++st)\n {\n if (opt::read_type == \"any\"\n or (st == 0\n and (opt::read_type == \"template\"\n or (not have_2d and opt::read_type == \"2d-or-template\")))\n or (st == 1\n and opt::read_type == \"complement\"))\n {\n const auto& gr_l = f.get_basecall_strand_group_list(st);\n for (const auto& gr : gr_l)\n {\n auto bcd = f.get_basecall_group_description(gr);\n \/\/ Never use minknow basecalls\n if(bcd.name == \"minknow\") {\n continue;\n }\n\n if (not opt::basecaller_name.empty())\n {\n if ((bcd.name != opt::basecaller_name) or\n (not opt::basecaller_version.empty() and\n bcd.version != opt::basecaller_version))\n {\n continue;\n }\n }\n if (f.have_basecall_fastq(st, gr)\n and f.have_basecall_events(st, gr))\n {\n res.push_back(std::make_pair(st, gr));\n if (opt::read_type != \"any\")\n {\n break;\n }\n }\n }\n }\n }\n LOG(debug)\n << \"preferred_groups: \"\n << alg::os_join(res, \", \", [] (const decltype(res)::value_type& p) {\n std::ostringstream oss;\n oss << \"(\" << p.first << \":\" << p.second << \")\";\n return oss.str();\n })\n << \"\\n\";\n return res;\n} \/\/ get_preferred_basecall_groups\n\nvoid process_file(const std::string& fn)\n{\n LOG(debug) << fn << \"\\n\";\n auto pos = fn.find_last_of('\/');\n std::string base_fn = (pos != std::string::npos? fn.substr(pos + 1) : fn);\n if (base_fn.substr(base_fn.size() - 6) == \".fast5\")\n {\n base_fn.resize(base_fn.size() - 6);\n }\n fast5::File f;\n do\n {\n try\n {\n \/\/ open file\n f.open(fn);\n ++opt::total_files_count;\n \/\/ get preferred basecall groups\n auto l = get_preferred_basecall_groups(f);\n if (l.empty())\n {\n LOG(info) << \"file [\" << fn << \"]: no basecalling data suitable for nanoplish\\n\";\n return;\n }\n ++opt::total_files_used_count;\n const auto& p = l.front();\n \/\/ get and parse fastq\n auto fq = f.get_basecall_fastq(p.first, p.second);\n auto fq_a = f.split_fq(fq);\n \/\/ construct name\n std::string name;\n std::istringstream(fq_a[0]) >> name;\n std::replace(name.begin(), name.end(), ':', '_');\n name += \":\" + p.second + \":\";\n if (p.first == 0)\n {\n name += \"template\";\n }\n else if (p.first == 1)\n {\n name += \"complement\";\n }\n else\n {\n name += \"2d\";\n }\n if (not opt::fastq)\n {\n (*os_p)\n << \">\" << name << \" \" << base_fn << \" \" << fn << \"\\n\"\n << fq_a[1] << \"\\n\";\n }\n else\n {\n (*os_p)\n << \"@\" << name << \" \" << base_fn << \" \" << fn << \"\\n\"\n << fq_a[1] << \"\\n\"\n << \"+\" << fq_a[2] << \"\\n\"\n << fq_a[3] << \"\\n\";\n }\n }\n catch (hdf5_tools::Exception& e)\n {\n LOG(warning) << fn << \": HDF5 error: \" << e.what() << \"\\n\";\n }\n } while (false);\n} \/\/ process_file\n\nvoid process_path(const std::string& path)\n{\n LOG(info) << path << \"\\n\";\n if (is_directory(path))\n {\n auto dir_list = list_directory(path);\n for (const auto& fn : dir_list)\n {\n if (fn == \".\" or fn == \"..\") continue;\n std::string full_fn = path + \"\/\" + fn;\n if (is_directory(full_fn))\n {\n if (opt::recurse)\n {\n opt::paths.push_back(full_fn);\n }\n else\n {\n LOG(info) << \"ignoring_subdir: \" << full_fn << \"\\n\";\n }\n }\n else if (fast5::File::is_valid_file(full_fn))\n {\n process_file(full_fn);\n }\n else\n {\n LOG(info) << \"ignoring_file: \" << full_fn << \"\\n\";\n }\n }\n }\n else \/\/ not is_directory; must be a fast5 file\n {\n if (fast5::File::is_valid_file(path))\n {\n process_file(path);\n }\n else\n {\n LOG(error) << \"path [\" << path << \"] is neither a fast5 file nor a directory\\n\";\n exit(EXIT_FAILURE);\n }\n }\n} \/\/ process_path\n\nstatic const char* shortopts = \"vrqt:o:b:\";\n\nenum {\n OPT_HELP = 1,\n OPT_VERSION,\n OPT_LOG_LEVEL,\n};\n\nstatic const struct option longopts[] = {\n { \"help\", no_argument, NULL, OPT_HELP },\n { \"version\", no_argument, NULL, OPT_VERSION },\n { \"log-level\", required_argument, NULL, OPT_LOG_LEVEL },\n { \"verbose\", no_argument, NULL, 'v' },\n { \"recurse\", no_argument, NULL, 'r' },\n { \"fastq\", no_argument, NULL, 'q' },\n { \"type\", required_argument, NULL, 't' },\n { \"output\", required_argument, NULL, 'o' },\n { \"basecaller\", required_argument, NULL, 'b' },\n { NULL, 0, NULL, 0 }\n};\n\nvoid parse_extract_options(int argc, char** argv)\n{\n bool die = false;\n std::vector< std::string> log_level;\n for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {\n std::istringstream arg(optarg != NULL ? optarg : \"\");\n switch (c) {\n case OPT_HELP:\n std::cout << EXTRACT_USAGE_MESSAGE;\n exit(EXIT_SUCCESS);\n case OPT_VERSION:\n std::cout << EXTRACT_VERSION_MESSAGE;\n exit(EXIT_SUCCESS);\n case OPT_LOG_LEVEL:\n log_level.push_back(arg.str());\n break;\n case 'v': opt::verbose++; break;\n case 'r': opt::recurse = true; break;\n case 'q': opt::fastq = true; break;\n case 't': arg >> opt::read_type; break;\n case 'o': arg >> opt::output_file; break;\n case 'b':\n arg >> opt::basecaller_name;\n auto i = opt::basecaller_name.find(':');\n if (i != std::string::npos)\n {\n opt::basecaller_version = opt::basecaller_name.substr(i + 1);\n opt::basecaller_name.resize(i);\n }\n break;\n }\n }\n \/\/ set log levels\n auto default_level = (int)logger::warning + opt::verbose;\n logger::Logger::set_default_level(default_level);\n logger::Logger::set_levels_from_options(log_level, &std::clog);\n\n if(opt::output_file.empty()) {\n std::cerr << SUBPROGRAM \": an output file (-o) is required\\n\";\n die = true;\n }\n\n \/\/ parse paths to process\n while (optind < argc)\n {\n std::string path = argv[optind++];\n while (path.size() > 1 and path[path.size() - 1] == '\/')\n {\n path.resize(path.size() - 1);\n }\n opt::paths.push_back(path);\n }\n\n if (opt::paths.empty())\n {\n std::cerr << SUBPROGRAM \": no paths to process\\n\";\n die = true;\n }\n\n \/\/ check read type\n if (not (opt::read_type == \"template\"\n or opt::read_type == \"complement\"\n or opt::read_type == \"2d\"\n or opt::read_type == \"2d-or-template\"\n or opt::read_type == \"any\"))\n {\n std::cerr << SUBPROGRAM \": invalid read type: \" << opt::read_type << \"\\n\";\n die = true;\n }\n\n \/\/ die if errors\n if (die)\n {\n std::cerr << \"\\n\" << EXTRACT_USAGE_MESSAGE;\n exit(EXIT_FAILURE);\n }\n\n LOG(info) << \"paths: \" << alg::os_join(opt::paths, \" \") << \"\\n\";\n LOG(info) << \"recurse: \" << (opt::recurse? \"yes\" : \"no\") << \"\\n\";\n LOG(info) << \"read_type: \" << opt::read_type << \"\\n\";\n LOG(info) << \"basecaller_name: \" << opt::basecaller_name << \"\\n\";\n LOG(info) << \"basecaller_version: \" << opt::basecaller_version << \"\\n\";\n}\n\nint extract_main(int argc, char** argv)\n{\n parse_extract_options(argc, argv);\n\n \/\/ Iterate over fast5 collection extracting the sequence reads\n \/\/ We do this in a block so the file is automatically closed\n \/\/ when ofs goes out of scope.\n {\n std::ofstream ofs;\n ofs.open(opt::output_file);\n os_p = &ofs;\n\n for (unsigned i = 0; i < opt::paths.size(); ++i)\n {\n process_path(opt::paths[i]);\n }\n }\n\n \/\/ Build the ReadDB from the output file\n ReadDB read_db;\n read_db.build(opt::output_file);\n read_db.save();\n\n std::clog << \"[extract] found \" << opt::total_files_count\n << \" files, extracted \" << opt::total_files_used_count\n << \" reads\\n\";\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ dixon\n\/\/\n\/\/ Created by Tobias Wood on 25\/03\/2014.\n\/\/\n\/\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include \"Eigen\/Dense\"\n\n#include \"Nifti\/Nifti.h\"\n#include \"QUIT\/Volume.h\"\n#include \"QUIT\/ThreadPool.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: dixon [options] magnitude phase \\n\\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message\\n\\\n\t--verbose, -v : Print more information\\n\\\n\t--out, -o path : Add a prefix to the output filenames\\n\"\n};\n\nstatic bool verbose = false;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{0, 0, 0, 0}\n};\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv)\n{\n\t\/\/**************************************************************************\n\t\/\/ Argument Processing\n\t\/\/**************************************************************************\n\tNifti maskFile;\n\tMultiArray<int8_t, 3> maskVol;\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"hvm:o:\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'v': verbose = true; break;\n\t\t\tcase 'm':\n\t\t\t\tcout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tmaskFile.open(optarg, Nifti::Mode::Read);\n\t\t\t\tmaskVol.resize(maskFile.dims());\n\t\t\t\tmaskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\toutPrefix = optarg;\n\t\t\t\tcout << \"Output prefix will be: \" << outPrefix << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\t\/\/**************************************************************************\n\t#pragma mark Gather data\n\t\/\/**************************************************************************\n\tif ((argc - optind) != 2) {\n\t\tcout << \"Requires 1 magnitude file and 1 phase file with 3 echos each as input.\" << endl << usage << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcout << \"Opening magnitude file: \" << argv[optind] << endl;\n\tNifti inputFile;\n\tinputFile.open(argv[optind++], Nifti::Mode::Read);\n\tNifti templateFile(inputFile, 1);\n\tMultiArray<float, 4> mag{inputFile.dims()};\n\tinputFile.readVolumes(mag.begin(), mag.end());\n\tinputFile.close();\n\n\tcout << \"Opening phase file: \" << argv[optind] << endl;\n\tinputFile.open(argv[optind++], Nifti::Mode::Read);\n\tMultiArray<float, 4> phase{inputFile.dims()};\n\tinputFile.readVolumes(phase.begin(), phase.end());\n\tif (!templateFile.matchesSpace(inputFile) || (maskFile.isOpen() && !templateFile.matchesSpace(maskFile))) {\n\t\tcerr << \"Input file dimensions or orientations do not match.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tinputFile.close();\n\n\tNifti::ArrayXs dims = templateFile.dims().head(3);\n\tMultiArray<float, 3> Wv(dims), Fv(dims), Av(dims);\n\t\/\/**************************************************************************\n\t\/\/ Do the fitting\n\t\/\/**************************************************************************\n\tThreadPool pool;\n\tcout << \"Starting processing...\" << endl;\n\tauto S0 = mag.slice<3>({0,0,0,0},{-1,-1,-1,0});\n\tauto S1 = mag.slice<3>({0,0,0,1},{-1,-1,-1,0});\n\tauto S2 = mag.slice<3>({0,0,0,2},{-1,-1,-1,0});\n\tauto phi0 = phase.slice<3>({0,0,0,0},{-1,-1,-1,0});\n\tauto phi1 = phase.slice<3>({0,0,0,1},{-1,-1,-1,0});\n\tauto phi2 = phase.slice<3>({0,0,0,2},{-1,-1,-1,0});\n\tfor (size_t k = 0; k < S0.dims()[2]; k++) {\n\t\tclock_t loopStart;\n\t\t\/\/ Read in data\n\t\tif (verbose)\n\t\t\tcout << \"Starting slice \" << k << \"...\" << flush;\n\t\tloopStart = clock();\n\t\tatomic<int> voxCount{0};\n\t\t\/\/cout << endl << I0s << endl << I1s << endl << I2s << endl;\n\t\t\/\/cout << Ws << endl << Fs << endl << As << endl;\n\t\tfunction<void (const size_t)> processVox = [&] (const size_t j) {\n\t\t\tfor (size_t i = 0; i < S0.dims()[0]; i++)\n\t\t\t\tif (!maskFile.isOpen() || maskVol[{i,j,k}]) {\n\t\t\t\t\t\/\/ From Ma et al JMR 1997\n\t\t\t\t\tAv[{i,j,k}] = sqrt(S2[{i,j,k}] \/ S0[{i,j,k}]);\n\t\t\t\t\tfloat phi = (phi2[{i,j,k}] - phi0[{i,j,k}]) \/ 2.;\n\t\t\t\t\tfloat psi = cos((phi1[{i,j,k}] - phi0[{i,j,k}]) - phi);\n\t\t\t\t\tfloat frac = S1[{i,j,k}] \/ sqrt(S0[{i,j,k}]*S2[{i,j,k}]);\n\t\t\t\t\tWv[{i,j,k}] = (1 + psi * frac) * S0[{i,j,k}] \/ 2.;\n\t\t\t\t\tFv[{i,j,k}] = (1 - psi * frac) * S0[{i,j,k}] \/ 2.;\n\t\t\t\t}\n\t\t};\n\t\tpool.for_loop(processVox, S0.dims()[1]);\n\t\t\n\t\tif (verbose) {\n\t\t\tclock_t loopEnd = clock();\n\t\t\tif (voxCount > 0)\n\t\t\t\tcout << voxCount << \" unmasked voxels, CPU time per voxel was \"\n\t\t\t\t << ((loopEnd - loopStart) \/ ((float)voxCount * CLOCKS_PER_SEC)) << \" s, \";\n\t\t\tcout << \"finished.\" << endl;\n\t\t}\n\t}\n\n\tif (verbose)\n\t\tcout << \"Writing results.\" << endl;\n\ttemplateFile.open(outPrefix + \"W.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Wv.begin(), Wv.end());\n\ttemplateFile.close();\n\ttemplateFile.open(outPrefix + \"F.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Fv.begin(), Fv.end());\n\ttemplateFile.close();\n\ttemplateFile.open(outPrefix + \"A.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Av.begin(), Av.end());\n\ttemplateFile.close();\n\tcout << \"All done.\" << endl;\n\texit(EXIT_SUCCESS);\n}\n\n<commit_msg>Updated to use complex division instead of phase subtraction, improves artefact suppresion.<commit_after>\/\/\n\/\/ main.cpp\n\/\/ dixon\n\/\/\n\/\/ Created by Tobias Wood on 25\/03\/2014.\n\/\/\n\/\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include \"Eigen\/Dense\"\n\n#include \"Nifti\/Nifti.h\"\n#include \"QUIT\/Volume.h\"\n#include \"QUIT\/ThreadPool.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: dixon [options] input \\n\\\n\\\nInput must be complex valued.\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message\\n\\\n\t--verbose, -v : Print more information\\n\\\n\t--out, -o path : Add a prefix to the output filenames\\n\"\n};\n\nstatic bool verbose = false;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{0, 0, 0, 0}\n};\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv)\n{\n\t\/\/**************************************************************************\n\t\/\/ Argument Processing\n\t\/\/**************************************************************************\n\tNifti maskFile;\n\tMultiArray<int8_t, 3> maskVol;\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"hvm:o:\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'v': verbose = true; break;\n\t\t\tcase 'm':\n\t\t\t\tcout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tmaskFile.open(optarg, Nifti::Mode::Read);\n\t\t\t\tmaskVol.resize(maskFile.dims());\n\t\t\t\tmaskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\toutPrefix = optarg;\n\t\t\t\tcout << \"Output prefix will be: \" << outPrefix << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\t\/\/**************************************************************************\n\t#pragma mark Gather data\n\t\/\/**************************************************************************\n\tif ((argc - optind) != 1) {\n\t\tcout << \"Requires 1 complex-valued file with 3 echos each as input.\" << endl << usage << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tcout << \"Opening magnitude file: \" << argv[optind] << endl;\n\tNifti inputFile;\n\tinputFile.open(argv[optind++], Nifti::Mode::Read);\n\tNifti templateFile(inputFile, 1);\n\tMultiArray<complex<float>, 4> data{inputFile.dims()};\n\tinputFile.readVolumes(data.begin(), data.end());\n\tinputFile.close();\n\tif (maskFile.isOpen() && !templateFile.matchesSpace(maskFile)) {\n\t\tcerr << \"Mask file dimensions or orientations do not match input.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tNifti::ArrayXs dims = templateFile.dims().head(3);\n\tMultiArray<float, 3> Wv(dims), Fv(dims), Av(dims);\n\t\/\/**************************************************************************\n\t\/\/ Do the fitting\n\t\/\/**************************************************************************\n\tThreadPool pool;\n\tcout << \"Starting processing...\" << endl;\n\tauto S0 = data.slice<3>({0,0,0,0},{-1,-1,-1,0});\n\tauto S1 = data.slice<3>({0,0,0,1},{-1,-1,-1,0});\n\tauto S2 = data.slice<3>({0,0,0,2},{-1,-1,-1,0});\n\t\/\/auto phi0 = phase.slice<3>({0,0,0,0},{-1,-1,-1,0});\n\t\/\/auto phi1 = phase.slice<3>({0,0,0,1},{-1,-1,-1,0});\n\t\/\/auto phi2 = phase.slice<3>({0,0,0,2},{-1,-1,-1,0});\n\tfor (size_t k = 0; k < dims[2]; k++) {\n\t\tclock_t loopStart;\n\t\t\/\/ Read in data\n\t\tif (verbose)\n\t\t\tcout << \"Starting slice \" << k << \"...\" << flush;\n\t\tloopStart = clock();\n\t\tatomic<int> voxCount{0};\n\t\t\/\/cout << endl << I0s << endl << I1s << endl << I2s << endl;\n\t\t\/\/cout << Ws << endl << Fs << endl << As << endl;\n\t\tfunction<void (const size_t)> processVox = [&] (const size_t j) {\n\t\t\tfor (size_t i = 0; i < dims[0]; i++)\n\t\t\t\tif (!maskFile.isOpen() || maskVol[{i,j,k}]) {\n\t\t\t\t\t\/\/ From Ma et al JMR 1997\n\t\t\t\t\tAv[{i,j,k}] = sqrt(abs(S2[{i,j,k}]) \/ abs(S0[{i,j,k}]));\n\t\t\t\t\tfloat phi = arg(S2[{i,j,k}] \/ S0[{i,j,k}]) \/ 2.;\n\t\t\t\t\tfloat psi = cos(arg(S1[{i,j,k}] \/ S0[{i,j,k}]) - phi);\n\t\t\t\t\tfloat frac = abs(S1[{i,j,k}]) \/ sqrt(abs(S0[{i,j,k}])*abs(S2[{i,j,k}]));\n\t\t\t\t\tWv[{i,j,k}] = (1 + psi * frac) * abs(S0[{i,j,k}]) \/ 2.;\n\t\t\t\t\tFv[{i,j,k}] = (1 - psi * frac) * abs(S0[{i,j,k}]) \/ 2.;\n\t\t\t\t}\n\t\t};\n\t\tpool.for_loop(processVox, dims[1]);\n\t\t\n\t\tif (verbose) {\n\t\t\tclock_t loopEnd = clock();\n\t\t\tif (voxCount > 0)\n\t\t\t\tcout << voxCount << \" unmasked voxels, CPU time per voxel was \"\n\t\t\t\t << ((loopEnd - loopStart) \/ ((float)voxCount * CLOCKS_PER_SEC)) << \" s, \";\n\t\t\tcout << \"finished.\" << endl;\n\t\t}\n\t}\n\n\tif (verbose)\n\t\tcout << \"Writing results.\" << endl;\n\ttemplateFile.setDatatype(Nifti::DataType::FLOAT32);\n\ttemplateFile.open(outPrefix + \"W.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Wv.begin(), Wv.end());\n\ttemplateFile.close();\n\ttemplateFile.open(outPrefix + \"F.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Fv.begin(), Fv.end());\n\ttemplateFile.close();\n\ttemplateFile.open(outPrefix + \"A.nii.gz\", Nifti::Mode::Write);\n\ttemplateFile.writeVolumes(Av.begin(), Av.end());\n\ttemplateFile.close();\n\tcout << \"All done.\" << endl;\n\texit(EXIT_SUCCESS);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <QtCore\/QCoreApplication>\n#include <iostream>\n#include <string>\n\nbool isUniqueChar1(const std::string &str);\nbool isUniqueChar2(const std::string &str);\nbool isUniqueChar3(const std::string &str);\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n\n std::string str1 = \"just one.\";\n if ( isUniqueChar1(str1) )\n {\n std::cout << str1 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str1 << \" hasn't all unique characters.\" << std::endl;\n }\n\n std::string str2 = \"I am hahaya.\";\n if ( isUniqueChar2(str2) )\n {\n std::cout << str2 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str2 << \" hasn't all unique characters.\" << std::endl;\n }\n\n std::string str3 = \"abcdefg\";\n if ( isUniqueChar3(str3) )\n {\n std::cout << str3 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str3 << \" hasn't all unique characters.\" << std::endl;\n }\n\n return a.exec();\n}\n\n\/\/stringеַȫΪASCIIʱ(ⷨһ)\nbool isUniqueChar1(const std::string &str)\n{\n bool char_set[256];\n memset( char_set, 0, sizeof(char_set) ); \/\/뽫λófalse\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)str.at(i);\n if ( char_set[value] )\n {\n return false;\n }\n char_set[value] = true;\n }\n return true;\n}\n\n\/\/stringеַȫΪASCIIʱ(ⷨ)\nbool isUniqueChar2(const std::string &str)\n{\n int checker[8];\n memset(checker, 0, sizeof(checker)); \/\/뽫λó0\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)str.at(i);\n int row = value\/32;\n int colunm = value%32;\n if ( checker[row] & (1<<colunm) )\n {\n return false;\n }\n checker[row] |= (1<<colunm);\n }\n return true;\n}\n\n\/\/stringеַȫΪĸʱ(ֻ'a' - 'z')\nbool isUniqueChar3(const std::string &str)\n{\n int checker = 0; \/\/뽫λó0\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)(str.at(i) - 'a' );\n if ( checker & (1<<value) )\n {\n return false;\n }\n checker |= (1<<value);\n }\n return true;\n}\n<commit_msg>add solution for qution 1.1<commit_after>#include <iostream>\n#include <string>\n\nbool isUniqueChar1(const std::string &str);\nbool isUniqueChar2(const std::string &str);\nbool isUniqueChar3(const std::string &str);\n\nint main(int argc, char *argv[])\n{\n std::string str1 = \"just one.\";\n if ( isUniqueChar1(str1) )\n {\n std::cout << str1 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str1 << \" hasn't all unique characters.\" << std::endl;\n }\n\n std::string str2 = \"I am hahaya.\";\n if ( isUniqueChar2(str2) )\n {\n std::cout << str2 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str2 << \" hasn't all unique characters.\" << std::endl;\n }\n\n std::string str3 = \"abcdefg\";\n if ( isUniqueChar3(str3) )\n {\n std::cout << str3 << \" has all unique characters.\" << std::endl;\n }\n else\n {\n std::cout << str3 << \" hasn't all unique characters.\" << std::endl;\n }\n\n return 0;\n}\n\n\/\/stringеַȫΪASCIIʱ(ⷨһ)\nbool isUniqueChar1(const std::string &str)\n{\n bool char_set[256];\n memset( char_set, 0, sizeof(char_set) ); \/\/뽫λófalse\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)str.at(i);\n if ( char_set[value] )\n {\n return false;\n }\n char_set[value] = true;\n }\n return true;\n}\n\n\/\/stringеַȫΪASCIIʱ(ⷨ)\nbool isUniqueChar2(const std::string &str)\n{\n int checker[8];\n memset(checker, 0, sizeof(checker)); \/\/뽫λó0\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)str.at(i);\n int row = value\/32;\n int colunm = value%32;\n if ( checker[row] & (1<<colunm) )\n {\n return false;\n }\n checker[row] |= (1<<colunm);\n }\n return true;\n}\n\n\/\/stringеַȫΪĸʱ(ֻ'a' - 'z')\nbool isUniqueChar3(const std::string &str)\n{\n int checker = 0; \/\/뽫λó0\n\n for ( unsigned int i = 0; i < str.length(); ++i )\n {\n int value = (int)(str.at(i) - 'a' );\n if ( checker & (1<<value) )\n {\n return false;\n }\n checker |= (1<<value);\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Arm.cpp\n *\n * Created on: Jan 13, 2011\n * Author: Nick Alberts\n *\/\n\n#include \"Arm.h\"\n#include \"diag\/diagnostics_center.h\"\n#include \"Math.h\"\n\/**\n * This function runs in the control thread, and continually sets the motors to the correct speed.\n * The speed is determined by the difference in angle divided by a constant.\n *\/\nvoid Arm::control_arm_motor( void *object )\n{\n\tArm *instance = (Arm *) object;\n\tinstance->upperArmAngle = instance->GetTilt();\n\n\t\/\/ Runs when the difference in angles is large enough\n\t\/\/TODO: fix kCloseEnough with real value\n\twhile ( fabs( instance->upperArmAngle - instance->arm_control_angle ) < kCloseEnough )\n\t{\n\t\t\/\/ Conversion factor is from clicks to angles and k is to fix the angle\n\t\tinstance->upperArmAngle = instance->GetTilt();\n\t\tinstance->armMotor.Set( ( instance->arm_control_angle - instance->upperArmAngle ) \/ 500.0 );\n\t}\n\n\tinstance->armMotor.Set( 0.0 );\n}\n\n\n\/\/ TODO: needs actual arguments and ports\n\/**\n * constructor for arm class\n *\/\nArm::Arm():\n\tarmMotor( 4 ),\n\tarmSolenoidRaise( 1 ),\n\tarmSolenoidLower( 2 ),\n\tarmEncoder( 4,5 ),\n\tarm_control_thread(new nr::conc::thread::function_entry( Arm::control_arm_motor ) )\n\n{\n\tlowerArm = false;\n\t\n\tnr::diag::diagnostics_center& diag = nr::diag::diagnostics_center::get_shared_instance();\n\tdiag.register_device( new nr::diag::observable_speed_controller( armMotor ), \"Arm Motor\" );\n\tdiag.register_device( new nr::diag::observable_encoder( armEncoder ), \"Arm Encoder\" );\n}\n\/**\n * THis function sets the lower arm to a boolean position value:true corresponds to raised and false corresponds to lower\n *\/\nvoid Arm::SetLowerArm( bool position )\n{\n\n\tif ( (! lowerArm && position) )\n\t{\n\t\t\/\/fires the arm solenoid\n\t\tarmSolenoidRaise.Set( true );\n\t\tarmSolenoidLower.Set( false );\n\t\tlowerArm=true;\n\t}\n\n\telse if ( lowerArm && ! position )\n\t{\n\t\tarmSolenoidLower.Set( true );\n\t\tarmSolenoidRaise.Set( false );\n\t\tlowerArm=false;\n\t}\n}\n\nvoid Arm::SetUpperArm( double angle )\n{\n\t\/\/ TODO: Constants and real angle factors\n\tif ( ! arm_control_mutex.trylock() )\n\t{\n\t\tarm_control_thread.Stop();\n\t}\n\tarm_control_thread.Start( (void *) this );\n\tarm_control_angle = angle;\n}\n\n\/\/ TODO: fix this for real values with actual correction value\ndouble Arm::GetTilt()\n{\n\treturn armEncoder.Get();\n}\n<commit_msg>Case-sensitivity in includes\\!<commit_after>\/*\n * Arm.cpp\n *\n * Created on: Jan 13, 2011\n * Author: Nick Alberts\n *\/\n\n#include \"Arm.h\"\n#include \"diag\/diagnostics_center.h\"\n#include <math.h>\n\/**\n * This function runs in the control thread, and continually sets the motors to the correct speed.\n * The speed is determined by the difference in angle divided by a constant.\n *\/\nvoid Arm::control_arm_motor( void *object )\n{\n\tArm *instance = (Arm *) object;\n\tinstance->upperArmAngle = instance->GetTilt();\n\n\t\/\/ Runs when the difference in angles is large enough\n\t\/\/TODO: fix kCloseEnough with real value\n\twhile ( fabs( instance->upperArmAngle - instance->arm_control_angle ) < kCloseEnough )\n\t{\n\t\t\/\/ Conversion factor is from clicks to angles and k is to fix the angle\n\t\tinstance->upperArmAngle = instance->GetTilt();\n\t\tinstance->armMotor.Set( ( instance->arm_control_angle - instance->upperArmAngle ) \/ 500.0 );\n\t}\n\n\tinstance->armMotor.Set( 0.0 );\n}\n\n\n\/\/ TODO: needs actual arguments and ports\n\/**\n * constructor for arm class\n *\/\nArm::Arm():\n\tarmMotor( 4 ),\n\tarmSolenoidRaise( 1 ),\n\tarmSolenoidLower( 2 ),\n\tarmEncoder( 4,5 ),\n\tarm_control_thread(new nr::conc::thread::function_entry( Arm::control_arm_motor ) )\n\n{\n\tlowerArm = false;\n\t\n\tnr::diag::diagnostics_center& diag = nr::diag::diagnostics_center::get_shared_instance();\n\tdiag.register_device( new nr::diag::observable_speed_controller( armMotor ), \"Arm Motor\" );\n\tdiag.register_device( new nr::diag::observable_encoder( armEncoder ), \"Arm Encoder\" );\n}\n\/**\n * THis function sets the lower arm to a boolean position value:true corresponds to raised and false corresponds to lower\n *\/\nvoid Arm::SetLowerArm( bool position )\n{\n\n\tif ( (! lowerArm && position) )\n\t{\n\t\t\/\/fires the arm solenoid\n\t\tarmSolenoidRaise.Set( true );\n\t\tarmSolenoidLower.Set( false );\n\t\tlowerArm=true;\n\t}\n\n\telse if ( lowerArm && ! position )\n\t{\n\t\tarmSolenoidLower.Set( true );\n\t\tarmSolenoidRaise.Set( false );\n\t\tlowerArm=false;\n\t}\n}\n\nvoid Arm::SetUpperArm( double angle )\n{\n\t\/\/ TODO: Constants and real angle factors\n\tif ( ! arm_control_mutex.trylock() )\n\t{\n\t\tarm_control_thread.Stop();\n\t}\n\tarm_control_thread.Start( (void *) this );\n\tarm_control_angle = angle;\n}\n\n\/\/ TODO: fix this for real values with actual correction value\ndouble Arm::GetTilt()\n{\n\treturn armEncoder.Get();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \"ngraph\/distributed.hpp\"\n#include \"ngraph\/distributed\/mlsl.hpp\"\n#include \"ngraph\/distributed\/null.hpp\"\n#include \"ngraph\/distributed\/open_mpi.hpp\"\n#include \"ngraph\/log.hpp\"\n\nusing namespace ngraph;\n\nstd::ostream& reduction::operator<<(std::ostream& out, const reduction::Type& obj)\n{\n#if !(defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ == 8))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic error \"-Wswitch\"\n#pragma GCC diagnostic error \"-Wswitch-enum\"\n#endif\n switch (obj)\n {\n case reduction::Type::SUM: out << \"SUM\"; break;\n case reduction::Type::PROD: out << \"PROD\"; break;\n case reduction::Type::MIN: out << \"MIN\"; break;\n case reduction::Type::MAX: out << \"MAX\"; break;\n }\n#if !(defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 8)\n#pragma GCC diagnostic pop\n#endif\n return out;\n};\n\nstatic std::unique_ptr<DistributedInterface> s_distributed_interface;\n\nvoid ngraph::set_distributed_interface(std::unique_ptr<DistributedInterface> distributed_interface)\n{\n NGRAPH_DEBUG << \"Setting distributed interfsce to: \" << distributed_interface->get_name();\n s_distributed_interface = std::move(distributed_interface);\n}\n\nDistributedInterface* ngraph::get_distributed_interface()\n{\n if (0 == s_distributed_interface)\n {\n#ifdef NGRAPH_DISTRIBUTED_OMPI_ENABLE\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::OpenMPIDistributedInterface()));\n#elif defined(NGRAPH_DISTRIBUTED_MLSL_ENABLE)\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::MLSLDistributedInterface()));\n#else\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::NullDistributedInterface()));\n#endif\n }\n return s_distributed_interface.get();\n}\n<commit_msg>fix spelling error<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include \"ngraph\/distributed.hpp\"\n#include \"ngraph\/distributed\/mlsl.hpp\"\n#include \"ngraph\/distributed\/null.hpp\"\n#include \"ngraph\/distributed\/open_mpi.hpp\"\n#include \"ngraph\/log.hpp\"\n\nusing namespace ngraph;\n\nstd::ostream& reduction::operator<<(std::ostream& out, const reduction::Type& obj)\n{\n#if !(defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ == 8))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic error \"-Wswitch\"\n#pragma GCC diagnostic error \"-Wswitch-enum\"\n#endif\n switch (obj)\n {\n case reduction::Type::SUM: out << \"SUM\"; break;\n case reduction::Type::PROD: out << \"PROD\"; break;\n case reduction::Type::MIN: out << \"MIN\"; break;\n case reduction::Type::MAX: out << \"MAX\"; break;\n }\n#if !(defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 8)\n#pragma GCC diagnostic pop\n#endif\n return out;\n};\n\nstatic std::unique_ptr<DistributedInterface> s_distributed_interface;\n\nvoid ngraph::set_distributed_interface(std::unique_ptr<DistributedInterface> distributed_interface)\n{\n NGRAPH_DEBUG << \"Setting distributed interface to: \" << distributed_interface->get_name();\n s_distributed_interface = std::move(distributed_interface);\n}\n\nDistributedInterface* ngraph::get_distributed_interface()\n{\n if (0 == s_distributed_interface)\n {\n#ifdef NGRAPH_DISTRIBUTED_OMPI_ENABLE\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::OpenMPIDistributedInterface()));\n#elif defined(NGRAPH_DISTRIBUTED_MLSL_ENABLE)\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::MLSLDistributedInterface()));\n#else\n set_distributed_interface(std::unique_ptr<DistributedInterface>(\n new ngraph::distributed::NullDistributedInterface()));\n#endif\n }\n return s_distributed_interface.get();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"LED.h\"\n\n#define NUM_OF_LED 2\n#define NUM_OF_PINS 2\n\nAdafruit_NeoPixel AN_LED = Adafruit_NeoPixel(NUM_OF_LED, NUM_OF_PINS, NEO_RGB + NEO_KHZ800);\n\n\/\/ must initialize with begin() and show()\n\n\n\/\/ void Dot::debug_show() {\n\/\/ printf(\"(%d, %d)\\n\", this->x, this->y);\n\/\/ };\n\nbool LEDClass::on(){\n AN_LED.setPixelColor(led_num_, red_, green_, blue_);\n AN_LED.show();\n \n status_ = true;\n\n return status_;\n}\n\nbool LEDClass::off(){\n AN_LED.setPixelColor(led_num_, 0x000000);\n status_ = false;\n\n return status_;\n}\n\n\/\/ bool LEDClass::getStatus(){\n\/\/ return status_;\n\/\/ }\n\/\/ \n\/\/ void LEDClass::color(float hue){\n\/\/ color(led_num_, hue);\n\/\/ \n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::color(uint8_t r, uint8_t g, uint8_t b){\n\/\/ red_ = r;\n\/\/ green_ = g;\n\/\/ blue_ = b;\n\/\/ \n\/\/ SetHLSFromRGB();\n\/\/ }\n\/\/ \n\/\/ void brightness(double brightness){\n\/\/ brightness_ = brightness;\n\/\/ \n\/\/ SetRGBFromHLS(); \n\/\/ }\n\/\/ \n\/\/ void saturation(double saturation){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::randomcolor(){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::SetHLSFromRGB(){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::SetRGBFromHLS(){\n\/\/ double max, min;\n\/\/ if (brightness_ < 0.5) {\n\/\/ max = 255 * l * (saturation_ + 1);\n\/\/ min = 255 * l * (s - 1);\n\/\/ } else {\n\/\/ max = 255 * (l + (1 - l) * s);\n\/\/ min = 255 * (l - (1 - l) * s);\n\/\/ }\n\/\/ \n\/\/ if (h < 60) {\n\/\/ red_ = max;\n\/\/ green_ = (h \/ 60) * (max - min) + min;\n\/\/ blue_ = min;\n\/\/ } else if (h < 120) {\n\/\/ red_ = ((120 - h) \/ 60) * (max - min) + min;\n\/\/ green_ = max;\n\/\/ blue_ = min;\n\/\/ } else if (h < 180) {\n\/\/ red_ = min;\n\/\/ green_ = max;\n\/\/ blue_ = ((h - 120) \/ 60) * (max - min) + min;\n\/\/ } else if (h < 240) {\n\/\/ red_ = min;\n\/\/ green_ = ((240 - h) \/ 60) * (max - min) + min;\n\/\/ blue_ = max;\n\/\/ } else if (h < 300) {\n\/\/ red_ = ((h - 240) \/ 60) * (max - min) + min;\n\/\/ green_ = min;\n\/\/ blue_ = max;\n\/\/ } else {\n\/\/ red_ = max;\n\/\/ green_ = min;\n\/\/ blue_ = ((360-h) \/ 60) * (max - min) + min;\n\/\/ }\n\/\/ }\n\/\/ \n\/\/ \n\/\/ \n\/\/ \n\/\/ \n\/\/ void color_update_hsl(int led) {\n\/\/ double s = led_saturation[led-1];\n\/\/ double l = led_brightness[led-1];\n\/\/ double h = led_hue[led-1] * 360; \/\/ 0 - 360\n\/\/ \n\/\/ double max, min;\n\/\/ if (l < 0.5) {\n\/\/ max = 255 * l * (s + 1);\n\/\/ min = 255 * l * (s - 1);\n\/\/ } else {\n\/\/ max = 255 * (l + (1 - l) * s);\n\/\/ min = 255 * (l - (1 - l) * s);\n\/\/ }\n\/\/ \n\/\/ uint8_t r, g, b;\n\/\/ \n\/\/ if (h < 60) {\n\/\/ r = max;\n\/\/ g = (h \/ 60) * (max - min) + min;\n\/\/ b = min;\n\/\/ } else if (h < 120) {\n\/\/ r = ((120 - h) \/ 60) * (max - min) + min;\n\/\/ g = max;\n\/\/ b = min;\n\/\/ } else if (h < 180) {\n\/\/ r = min;\n\/\/ g = max;\n\/\/ b = ((h - 120) \/ 60) * (max - min) + min;\n\/\/ } else if (h < 240) {\n\/\/ r = min;\n\/\/ g = ((240 - h) \/ 60) * (max - min) + min;\n\/\/ b = max;\n\/\/ } else if (h < 300) {\n\/\/ r = ((h - 240) \/ 60) * (max - min) + min;\n\/\/ g = min;\n\/\/ b = max;\n\/\/ } else {\n\/\/ r = max;\n\/\/ g = min;\n\/\/ b = ((360-h) \/ 60) * (max - min) + min;\n\/\/ }\n\/\/ \n\/\/ uint32_t rgb = Adafruit_NeoPixel::Color(r, g, b);\n\/\/ \/\/ Serial.println(rgb, HEX);\n\/\/ led_colors[led-1] = rgb;\n\/\/ \n\/\/ }<commit_msg>remove old function<commit_after>#include \"LED.h\"\n\n#define NUM_OF_LED 2\n#define NUM_OF_PINS 2\n\nAdafruit_NeoPixel AN_LED = Adafruit_NeoPixel(NUM_OF_LED, NUM_OF_PINS, NEO_RGB + NEO_KHZ800);\n\n\/\/ must initialize with begin() and show()\n\n\n\/\/ void Dot::debug_show() {\n\/\/ printf(\"(%d, %d)\\n\", this->x, this->y);\n\/\/ };\n\nbool LEDClass::on(){\n AN_LED.setPixelColor(led_num_, red_, green_, blue_);\n AN_LED.show();\n \n status_ = true;\n\n return status_;\n}\n\nbool LEDClass::off(){\n AN_LED.setPixelColor(led_num_, 0x000000);\n status_ = false;\n\n return status_;\n}\n\n\/\/ bool LEDClass::getStatus(){\n\/\/ return status_;\n\/\/ }\n\/\/ \n\/\/ void LEDClass::color(float hue){\n\/\/ color(led_num_, hue);\n\/\/ \n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::color(uint8_t r, uint8_t g, uint8_t b){\n\/\/ red_ = r;\n\/\/ green_ = g;\n\/\/ blue_ = b;\n\/\/ \n\/\/ SetHLSFromRGB();\n\/\/ }\n\/\/ \n\/\/ void brightness(double brightness){\n\/\/ brightness_ = brightness;\n\/\/ \n\/\/ SetRGBFromHLS(); \n\/\/ }\n\/\/ \n\/\/ void saturation(double saturation){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::randomcolor(){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::SetHLSFromRGB(){\n\/\/ \n\/\/ }\n\/\/ \n\/\/ void LEDClass::SetRGBFromHLS(){\n\/\/ double max, min;\n\/\/ if (brightness_ < 0.5) {\n\/\/ max = 255 * l * (saturation_ + 1);\n\/\/ min = 255 * l * (s - 1);\n\/\/ } else {\n\/\/ max = 255 * (l + (1 - l) * s);\n\/\/ min = 255 * (l - (1 - l) * s);\n\/\/ }\n\/\/ \n\/\/ if (h < 60) {\n\/\/ red_ = max;\n\/\/ green_ = (h \/ 60) * (max - min) + min;\n\/\/ blue_ = min;\n\/\/ } else if (h < 120) {\n\/\/ red_ = ((120 - h) \/ 60) * (max - min) + min;\n\/\/ green_ = max;\n\/\/ blue_ = min;\n\/\/ } else if (h < 180) {\n\/\/ red_ = min;\n\/\/ green_ = max;\n\/\/ blue_ = ((h - 120) \/ 60) * (max - min) + min;\n\/\/ } else if (h < 240) {\n\/\/ red_ = min;\n\/\/ green_ = ((240 - h) \/ 60) * (max - min) + min;\n\/\/ blue_ = max;\n\/\/ } else if (h < 300) {\n\/\/ red_ = ((h - 240) \/ 60) * (max - min) + min;\n\/\/ green_ = min;\n\/\/ blue_ = max;\n\/\/ } else {\n\/\/ red_ = max;\n\/\/ green_ = min;\n\/\/ blue_ = ((360-h) \/ 60) * (max - min) + min;\n\/\/ }\n\/\/ }\n\/\/ \n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <boost\/bind.hpp>\n#include <boost\/format.hpp>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n#include <kernel\/userver.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/object.hh>\n#include <object\/string.hh>\n#include <object\/symbols.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (const objects_type& args)\n {\n runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();\n\n check_arg_count(args.size() - 1, 1, 2);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check<Float>(args[1]);\n const rFloat& arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::numeric_cast<int>(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\trunner::raise_bad_integer_error(arg1->value_get());\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n type_check<String>(args[2]);\n const rString& arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n const std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (const objects_type& args)\n {\n static boost::format uid(\"0x%x\");\n check_arg_count(args.size() - 1, 0);\n return\n new String(str(uid % reinterpret_cast<long long>(args[0].get())));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_EQ_EQ(const objects_type& args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n check_arg_count(args.size() - 1, 1);\n return args[0]->call(SYMBOL(EQ_EQ_EQ), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_EQ_EQ_EQ(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check<List>(args[1]);\n const rList& arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1\n || arg1->value_get().front() != args[0])\n RAISE(\"first argument must be `[this]'\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (const objects_type& args)\n {\n runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();\n\n check_arg_count(args.size() - 1, 1);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n const rObject& message = call_message->slot_get(SYMBOL(message));\n type_check<String>(message);\n const libport::Symbol msg(message->as<String>()->value_get());\n const rObject& target = args[0];\n const rObject& code = target->slot_get(msg);\n call_message->slot_update(SYMBOL(code), code);\n call_message->slot_update(SYMBOL(target), target);\n \/\/ FIXME: Sanity checks on the call message are probably required\n return r.apply_call_message(code, msg, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb) \\\n static rObject \\\n object_class_ ## Verb ## Proto ( \\\n const objects_type& args) \\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 1); \\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0]->urbi_protos_get ();\n }\n\n \/\/\/ Add a prototype\n static bool\n proto_add(List::value_type& protos, const rObject& proto)\n {\n protos.push_back(proto);\n return false;\n }\n\n \/\/\/ Recursively get protos list\n static rObject\n object_class_allProtos(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));\n return new List(res);\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n template <typename F>\n static inline void for_all_slot_names(const rObject& o, F f)\n {\n for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());\n slot != o->slots_get().end(o.get());\n ++slot)\n f(slot->first.second);\n }\n\n static void\n add_as_rString(List::value_type& l, libport::Symbol slot_name)\n {\n l.push_back(new String(slot_name));\n }\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n const rObject& obj = args[0];\n\n List::value_type l;\n for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));\n return new List(l);\n }\n\n \/\/\/ Recursive list of slot names.\n\n static void\n maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,\n\t libport::Symbol slot_name)\n {\n if (!libport::has(control, slot_name))\n {\n control.push_back(slot_name);\n l.push_back(new String(slot_name));\n }\n }\n\n static rObject\n object_class_allSlotNames(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n std::vector<libport::Symbol> slot_names;\n List::value_type res;\n objects_type protos =\n object_class_allProtos(args)->as<List>()->value_get();\n foreach (const rObject& proto, protos)\n {\n for_all_slot_names(proto, boost::bind(&maybe_add,\n\t\t\t\t\t boost::ref(slot_names),\n\t\t\t\t\t boost::ref(res),\n\t\t\t\t\t _1));\n }\n return new List(res);\n }\n\n static bool\n object_class_isA(rObject self, rObject proto)\n {\n return is_a(self, proto);\n }\n\n static bool\n object_class_hasLocalSlot(rObject self, const libport::Symbol& slot)\n {\n return self->local_slot_get(slot);\n }\n\n void\n object_class_initialize ()\n {\n Object::proto->slot_set(SYMBOL(isA),\n make_primitive(object_class_isA));\n Object::proto->slot_set(SYMBOL(hasLocalSlot),\n make_primitive(&object_class_hasLocalSlot));\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name) \\\n Object::proto->slot_set(SYMBOL(Name), new Primitive(object_class_##Name), true)\n\n DECLARE(addProto);\n DECLARE(allProtos);\n DECLARE(allSlotNames);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(init);\n DECLARE(EQ_EQ_EQ);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(EQ_EQ);\n DECLARE(slotNames);\n DECLARE(uid);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n Object::proto->slot_set(SYMBOL(Name), make_primitive(Code))\n\n DECLARE(createSlot, &Object::urbi_createSlot);\n DECLARE(getProperty, &Object::property_get);\n DECLARE(getSlot, &Object::urbi_getSlot);\n DECLARE(hasProperty, &Object::property_has);\n DECLARE(hasSlot, &Object::slot_has);\n DECLARE(locateSlot, &Object::urbi_locateSlot);\n DECLARE(setProperty, &Object::property_set);\n DECLARE(setSlot, &Object::urbi_setSlot);\n DECLARE(setConstSlot, &Object::urbi_setConstSlot);\n DECLARE(removeProperty, &Object::property_remove);\n DECLARE(removeSlot, &Object::urbi_removeSlot);\n DECLARE(updateSlot, &Object::urbi_updateSlot);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<commit_msg>style changes.<commit_after>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <boost\/bind.hpp>\n#include <boost\/format.hpp>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n#include <kernel\/userver.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/object.hh>\n#include <object\/string.hh>\n#include <object\/symbols.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (const objects_type& args)\n {\n runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();\n\n check_arg_count(args.size() - 1, 1, 2);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check<Float>(args[1]);\n const rFloat& arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::numeric_cast<int>(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\trunner::raise_bad_integer_error(arg1->value_get());\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n type_check<String>(args[2]);\n const rString& arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n const std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (const objects_type& args)\n {\n static boost::format uid(\"0x%x\");\n check_arg_count(args.size() - 1, 0);\n return\n new String(str(uid % reinterpret_cast<long long>(args[0].get())));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_EQ_EQ(const objects_type& args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n check_arg_count(args.size() - 1, 1);\n return args[0]->call(SYMBOL(EQ_EQ_EQ), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_EQ_EQ_EQ(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check<List>(args[1]);\n const rList& arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1\n || arg1->value_get().front() != args[0])\n RAISE(\"first argument must be `[this]'\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (const objects_type& args)\n {\n runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();\n\n check_arg_count(args.size() - 1, 1);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n const rObject& message = call_message->slot_get(SYMBOL(message));\n type_check<String>(message);\n const libport::Symbol msg(message->as<String>()->value_get());\n const rObject& target = args[0];\n const rObject& code = target->slot_get(msg);\n call_message->slot_update(SYMBOL(code), code);\n call_message->slot_update(SYMBOL(target), target);\n \/\/ FIXME: Sanity checks on the call message are probably required\n return r.apply_call_message(code, msg, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb) \\\n static rObject \\\n object_class_ ## Verb ## Proto ( \\\n const objects_type& args) \\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 1); \\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0]->urbi_protos_get ();\n }\n\n \/\/\/ Add a prototype\n static bool\n proto_add(List::value_type& protos, const rObject& proto)\n {\n protos.push_back(proto);\n return false;\n }\n\n \/\/\/ Recursively get protos list\n static rObject\n object_class_allProtos(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));\n return new List(res);\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n template <typename F>\n static inline void for_all_slot_names(const rObject& o, F f)\n {\n for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());\n slot != o->slots_get().end(o.get());\n ++slot)\n f(slot->first.second);\n }\n\n static void\n add_as_rString(List::value_type& l, libport::Symbol slot_name)\n {\n l.push_back(new String(slot_name));\n }\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n const rObject& obj = args[0];\n\n List::value_type l;\n for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));\n return new List(l);\n }\n\n \/\/\/ Recursive list of slot names.\n static void\n maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,\n\t libport::Symbol slot_name)\n {\n if (!libport::has(control, slot_name))\n {\n control.push_back(slot_name);\n l.push_back(new String(slot_name));\n }\n }\n\n static rObject\n object_class_allSlotNames(const objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n std::vector<libport::Symbol> slot_names;\n List::value_type res;\n objects_type protos =\n object_class_allProtos(args)->as<List>()->value_get();\n foreach (const rObject& proto, protos)\n {\n for_all_slot_names(proto, boost::bind(&maybe_add,\n\t\t\t\t\t boost::ref(slot_names),\n\t\t\t\t\t boost::ref(res),\n\t\t\t\t\t _1));\n }\n return new List(res);\n }\n\n static bool\n object_class_isA(rObject self, rObject proto)\n {\n return is_a(self, proto);\n }\n\n static bool\n object_class_hasLocalSlot(rObject self, const libport::Symbol& slot)\n {\n return self->local_slot_get(slot);\n }\n\n void\n object_class_initialize()\n {\n Object::proto->slot_set(SYMBOL(isA),\n make_primitive(object_class_isA));\n Object::proto->slot_set(SYMBOL(hasLocalSlot),\n make_primitive(&object_class_hasLocalSlot));\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name) \\\n Object::proto->slot_set(SYMBOL(Name), new Primitive(object_class_##Name), true)\n\n DECLARE(addProto);\n DECLARE(allProtos);\n DECLARE(allSlotNames);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(init);\n DECLARE(EQ_EQ_EQ);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(EQ_EQ);\n DECLARE(slotNames);\n DECLARE(uid);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n Object::proto->slot_set(SYMBOL(Name), make_primitive(&Object::Code))\n\n DECLARE(createSlot , urbi_createSlot);\n DECLARE(getProperty , property_get);\n DECLARE(getSlot , urbi_getSlot);\n DECLARE(hasProperty , property_has);\n DECLARE(hasSlot , slot_has);\n DECLARE(locateSlot , urbi_locateSlot);\n DECLARE(removeProperty , property_remove);\n DECLARE(removeSlot , urbi_removeSlot);\n DECLARE(setConstSlot , urbi_setConstSlot);\n DECLARE(setProperty , property_set);\n DECLARE(setSlot , urbi_setSlot);\n DECLARE(updateSlot , urbi_updateSlot);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n\n#include <object\/cxx-primitive.hh>\n#include <object\/float-class.hh>\n#include <object\/global-class.hh>\n#include <object\/list-class.hh>\n#include <object\/object-class.hh>\n#include <object\/object.hh>\n#include <object\/string-class.hh>\n\n#include <runner\/call.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n rObject object_class;\n\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT_RANGE(1, 3);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check<Float>(args[1], SYMBOL(dump));\n rFloat arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::ufloat_to_int(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\tthrow BadInteger(arg1->value_get(), SYMBOL(dump));\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n rString arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get().name_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, r, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (runner::Runner&, objects_type args)\n {\n static boost::format uid(\"0x%x\");\n CHECK_ARG_COUNT(1);\n return\n new String(libport::Symbol\n (str(uid % reinterpret_cast<long long>(args[0].get()))));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_sameAs(runner::Runner& r, objects_type args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n CHECK_ARG_COUNT (2);\n return urbi_call(r, args[0], SYMBOL(memSameAs), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_memSameAs(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n type_check<List>(args[1], SYMBOL(apply));\n rList arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0])\n throw PrimitiveError(SYMBOL(apply), \"first argument must be [this]\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n rObject message = call_message->slot_get(SYMBOL(message));\n type_check<String>(message, SYMBOL(callMessage));\n libport::Symbol msg = message->as<String>()->value_get();\n rObject code = args[0]->slot_get(msg);\n call_message->slot_update(r, SYMBOL(code), code);\n \/\/ FIXME: Sanity checks on the call message are probably required\n objects_type self;\n self.push_back(args[0]);\n return r.apply(code, msg, self, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb)\t\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n object_class_ ## Verb ## Proto (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT(2);\t\t\t\t\t\t\t\\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n return args[0]->urbi_protos_get ();\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n rObject obj = args[0];\n\n List::value_type l;\n for (Object::slots_implem::iterator slot = obj->slots_get().begin(obj.get());\n slot != obj->slots_get().end(obj.get());\n ++slot)\n l.push_back (new String(slot->first.second));\n\n return new List(l);\n }\n\n \/\/\/ Get a slot content.\n static rObject\n object_class_getSlot (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n rObject obj = args[0];\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return obj->slot_get(arg1->value_get());\n }\n\n \/\/ self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).\n static rObject\n object_class_getLazyLocalSlot (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (4);\n\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n Object::key_type slot_name = arg1->value_get ();\n\n \/\/ If the slot already exists, return its content.\n if (rObject slot = args[0]->own_slot_get (slot_name))\n return slot;\n\n \/\/ The slot doesn't exist. Should we create it?\n if (is_true (args[3], SYMBOL(getLazyLocalSlot)))\n args[0]->slot_set (slot_name, args[2]);\n\n \/\/ Return the default value for this slot.\n return args[2];\n }\n\n \/\/\/ Remove a slot.\n static rObject\n object_class_removeSlot (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n rObject obj = args[0];\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n obj->slot_remove(arg1->value_get());\n return obj;\n }\n\n \/\/\/ Locate a slot.\n static rObject\n object_class_locateSlot (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n\n rObject o = args[0]->slot_locate(arg1->value_get());\n return o ? o : nil_class;\n }\n\n static rObject\n object_class_setSlot (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(arg1->value_get (), args[2]);\n return args[2];\n }\n\n static rObject\n object_class_updateSlot (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return args[0]->slot_update(r, arg1->value_get (), args[2]);\n }\n\n static rObject\n object_class_changeSlot (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_update(r, arg1->value_get (), args[2], false);\n return args[2];\n }\n\n static rObject\n object_class_isA(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n return new Float(is_a(args[0], args[1])? 1.0:0.0);\n }\n\n void\n object_class_initialize ()\n {\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(object, Name)\n\n DECLARE(addProto);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(changeSlot);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(getLazyLocalSlot);\n DECLARE(getSlot);\n DECLARE(init);\n DECLARE(isA);\n DECLARE(locateSlot);\n DECLARE(memSameAs);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(removeSlot);\n DECLARE(sameAs);\n DECLARE(setSlot);\n DECLARE(slotNames);\n DECLARE(uid);\n DECLARE(updateSlot);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))\n\n DECLARE(getProperty, &Object::property_get);\n DECLARE(hasProperty, &Object::property_has);\n DECLARE(hasSlot, &Object::slot_has);\n DECLARE(setProperty, &Object::property_set);\n DECLARE(removeProperty, &Object::property_remove);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<commit_msg>Take arguments by ref in object primitives.<commit_after>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n\n#include <object\/cxx-primitive.hh>\n#include <object\/float-class.hh>\n#include <object\/global-class.hh>\n#include <object\/list-class.hh>\n#include <object\/object-class.hh>\n#include <object\/object.hh>\n#include <object\/string-class.hh>\n\n#include <runner\/call.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n rObject object_class;\n\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT (1);\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT (1);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (runner::Runner& r, objects_type& args)\n {\n CHECK_ARG_COUNT_RANGE(1, 3);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check<Float>(args[1], SYMBOL(dump));\n rFloat arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::ufloat_to_int(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\tthrow BadInteger(arg1->value_get(), SYMBOL(dump));\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n rString arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get().name_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, r, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (runner::Runner&, objects_type& args)\n {\n static boost::format uid(\"0x%x\");\n CHECK_ARG_COUNT(1);\n return\n new String(libport::Symbol\n (str(uid % reinterpret_cast<long long>(args[0].get()))));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_sameAs(runner::Runner& r, objects_type& args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n CHECK_ARG_COUNT (2);\n return urbi_call(r, args[0], SYMBOL(memSameAs), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_memSameAs(runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT (2);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(2);\n type_check<List>(args[1], SYMBOL(apply));\n rList arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0])\n throw PrimitiveError(SYMBOL(apply), \"first argument must be [this]\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (runner::Runner& r, objects_type& args)\n {\n CHECK_ARG_COUNT (2);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n rObject message = call_message->slot_get(SYMBOL(message));\n type_check<String>(message, SYMBOL(callMessage));\n libport::Symbol msg = message->as<String>()->value_get();\n rObject code = args[0]->slot_get(msg);\n call_message->slot_update(r, SYMBOL(code), code);\n \/\/ FIXME: Sanity checks on the call message are probably required\n objects_type self;\n self.push_back(args[0]);\n return r.apply(code, msg, self, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb)\t\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n object_class_ ## Verb ## Proto (runner::Runner&, objects_type& args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT(2);\t\t\t\t\t\t\t\\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(1);\n return args[0]->urbi_protos_get ();\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(1);\n rObject obj = args[0];\n\n List::value_type l;\n for (Object::slots_implem::iterator slot = obj->slots_get().begin(obj.get());\n slot != obj->slots_get().end(obj.get());\n ++slot)\n l.push_back (new String(slot->first.second));\n\n return new List(l);\n }\n\n \/\/\/ Get a slot content.\n static rObject\n object_class_getSlot (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(2);\n rObject obj = args[0];\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return obj->slot_get(arg1->value_get());\n }\n\n \/\/ self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).\n static rObject\n object_class_getLazyLocalSlot (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT (4);\n\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n Object::key_type slot_name = arg1->value_get ();\n\n \/\/ If the slot already exists, return its content.\n if (rObject slot = args[0]->own_slot_get (slot_name))\n return slot;\n\n \/\/ The slot doesn't exist. Should we create it?\n if (is_true (args[3], SYMBOL(getLazyLocalSlot)))\n args[0]->slot_set (slot_name, args[2]);\n\n \/\/ Return the default value for this slot.\n return args[2];\n }\n\n \/\/\/ Remove a slot.\n static rObject\n object_class_removeSlot (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(2);\n rObject obj = args[0];\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n obj->slot_remove(arg1->value_get());\n return obj;\n }\n\n \/\/\/ Locate a slot.\n static rObject\n object_class_locateSlot (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(2);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n\n rObject o = args[0]->slot_locate(arg1->value_get());\n return o ? o : nil_class;\n }\n\n static rObject\n object_class_setSlot (runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(arg1->value_get (), args[2]);\n return args[2];\n }\n\n static rObject\n object_class_updateSlot (runner::Runner& r, objects_type& args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return args[0]->slot_update(r, arg1->value_get (), args[2]);\n }\n\n static rObject\n object_class_changeSlot (runner::Runner& r, objects_type& args)\n {\n CHECK_ARG_COUNT(3);\n rString arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_update(r, arg1->value_get (), args[2], false);\n return args[2];\n }\n\n static rObject\n object_class_isA(runner::Runner&, objects_type& args)\n {\n CHECK_ARG_COUNT (2);\n return new Float(is_a(args[0], args[1])? 1.0:0.0);\n }\n\n void\n object_class_initialize ()\n {\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(object, Name)\n\n DECLARE(addProto);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(changeSlot);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(getLazyLocalSlot);\n DECLARE(getSlot);\n DECLARE(init);\n DECLARE(isA);\n DECLARE(locateSlot);\n DECLARE(memSameAs);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(removeSlot);\n DECLARE(sameAs);\n DECLARE(setSlot);\n DECLARE(slotNames);\n DECLARE(uid);\n DECLARE(updateSlot);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))\n\n DECLARE(getProperty, &Object::property_get);\n DECLARE(hasProperty, &Object::property_has);\n DECLARE(hasSlot, &Object::slot_has);\n DECLARE(setProperty, &Object::property_set);\n DECLARE(removeProperty, &Object::property_remove);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>#include \"TileLoader.h\"\n\n#include <cmath>\n\n#include <QtCore\/QTime>\n#include <QtCore\/QVector>\n\n#include \"katlasdirs.h\"\n#include \"TextureTile.h\"\n\n#include <QtCore\/QDebug>\n\nTileLoader::TileLoader( const QString& theme ){\n\n\tsetMap( theme );\n}\n\nvoid TileLoader::setMap( const QString& theme ){\n\/\/\tInitialize map theme.\n\tm_theme = theme;\n\n\tm_tile = new TextureTile( 0, 0, 0, m_theme );\n\n\/\/\tWe assume that all tiles have the same size. TODO: check to be safe\n\tm_tileWidth = m_tile->rawtile()->width();\n\tm_tileHeight = m_tile->rawtile()->height();\n\n\tdelete m_tile;\n}\n\nvoid TileLoader::resetTilehash(){\n\n\tQHash<int, TextureTile*>::const_iterator it = m_tileHash.constBegin();\n\twhile (it != m_tileHash.constEnd()) {\n\t\tm_tileHash.value(it.key())->setUsed( false );\n\t\t++it;\n\t}\n}\n\nvoid TileLoader::cleanupTilehash(){\n\/\/\tMake sure that tiles which haven't been used during the last\n\/\/\trendering of the map at all get removed from the tile hash.\n\n\tQHashIterator<int, TextureTile*> it(m_tileHash);\n\twhile (it.hasNext()) {\n\t\tit.next();\n\t\tif ((it.value())->used() == false){\n\/\/\t\t\tqDebug(\"Removing \" + QString::number(it.key()).toLatin1());\n\t\t\tdelete m_tileHash.value(it.key());\n\t\t\tm_tileHash.remove(it.key());\t\n\t\t}\n\t}\n}\n\nvoid TileLoader::flush(){\n\/\/\tRemove all m_tiles from m_tileHash\n\tQHash <int, TextureTile*>::const_iterator it;\n\tfor( it = m_tileHash.begin(); it != m_tileHash.constEnd(); it++ ) \n\t\tdelete (*it);\n\tm_tileHash.clear();\n}\n\n\nTextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel ){\n\/\/\tChoosing the correct m_tile via Lng\/Lat info \n\n\tm_tileId = (tilx *1000) + tily;\n\n\t\/\/ If the m_tile hasn't been loaded into the m_tileHash yet, then do so\n\tif (!m_tileHash.contains( m_tileId )){\t\n\t\tm_tile = new TextureTile(tilx, tily, tileLevel, m_theme);\n\t\tm_tileHash[m_tileId] = m_tile;\n\t}\n\t\/\/ otherwise pick the correct one from the hash\n\telse {\n\t\tm_tile=m_tileHash.value(m_tileId);\n\t\tif (!m_tile->used()){\n\t\t\tm_tile->setUsed(true);\n\t\t\tm_tileHash[m_tileId]=m_tile;\n\t\t}\n\t}\n\n\treturn m_tile;\n}\n\nint TileLoader::levelToRow( int level ){\n\treturn (int)pow( 2.0, (double)( level ) );\n}\n\nint TileLoader::levelToColumn( int level ){\n\treturn (int)pow( 2.0, (double)( level + 1 ) );\n}\n\nint TileLoader::rowToLevel( int row ){\n\treturn (int)( log( row ) \/ log( 2 ) );\n}\n\nint TileLoader::columnToLevel( int column ){\n\treturn (int)( log( column \/ 2 ) \/ log( 2 ) );\n}\n\nint TileLoader::maxCompleteTileLevel( const QString& theme ){\n\n\tbool noerr = true; \n\n\tint tilelevel = -1;\n\tint trylevel = 0;\n\n\/\/\tif ( m_bitmaplayer.type.toLower() == \"bitmap\" ){\n\twhile ( noerr == true ){\n\t\tint nmaxit = TileLoader::levelToRow( trylevel );\n\t\tfor ( int n=0; n < nmaxit; n++) {\n\t\t\tint mmaxit = TileLoader::levelToColumn( trylevel );\n\t\t\tfor ( int m=0; m < mmaxit; m++){\n\t\t\t\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\/%2\/%3\/%3_%4.jpg\").arg(theme).arg( trylevel ).arg( n, 4, 10, QChar('0') ).arg( m, 4, 10, QChar('0') ) );\n\/\/\t\t\t\tqDebug() << tilepath;\n\t\t\t\tnoerr = QFile::exists( tilepath );\n\t\t\t\tif ( noerr == false ) break; \n\t\t\t}\n\t\t\tif ( noerr == false ) break; \n\t\t}\t\n\n\t\tif ( noerr == true) tilelevel = trylevel;\n\t\ttrylevel++;\n\t}\n\n\tif ( tilelevel == -1 ){\n\t\tqDebug(\"No Tiles Found!\");\n\t}\n\n\tqDebug() << \"Detected maximum complete tile level: \" << tilelevel;\n\n\treturn tilelevel;\n}\n\nint TileLoader::maxPartialTileLevel( const QString& theme ){\n\n\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\").arg(theme) );\n\tQStringList leveldirs = ( QDir( tilepath ) ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );\n\n\tint maxtilelevel = -1;\n\n\tQString str;\n\tbool ok = true;\n\n\tQStringList::const_iterator constIterator;\n\tfor (constIterator = leveldirs.constBegin(); constIterator != leveldirs.constEnd();\n\t\t++constIterator){\n\t\tint value = (*constIterator).toInt( &ok, 10 );\n\/\/\t\tqDebug() << \"Value: \" << value << \"Ok: \" << ok;\n\t\tif ( ok && value > maxtilelevel ) maxtilelevel = value;\n\t}\n\n\tqDebug() << \"Detected maximum tile level that contains data: \" << maxtilelevel;\n\n\treturn maxtilelevel;\n}\n\nbool TileLoader::baseTilesAvailable( const QString& theme ){\n\n\tbool noerr = true; \n\n\tint n = 0;\n\n\t\/\/ Check whether the two tiles from the lowest texture level are available\n\n\tfor ( int m = 0; m < 2; ++m ){\n\t\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\/%2\/%3\/%3_%4.jpg\").arg(theme).arg( 0 ).arg( 0, 4, 10, QChar('0') ).arg( m, 4, 10, QChar('0') ) );\n\n\t\tnoerr = QFile::exists( tilepath );\n\n\t\tif ( noerr == false ) break; \n\t}\n\n\/\/\tqDebug() << \"Mandatory most basic tile level is fully available: \" << noerr;\n\n\treturn noerr;\n}\n<commit_msg>woops, forgot to add \"flush()\" to setMap while deleting setTexLevel during clean up<commit_after>#include \"TileLoader.h\"\n\n#include <cmath>\n\n#include <QtCore\/QTime>\n#include <QtCore\/QVector>\n\n#include \"katlasdirs.h\"\n#include \"TextureTile.h\"\n\n#include <QtCore\/QDebug>\n\nTileLoader::TileLoader( const QString& theme ){\n\n\tsetMap( theme );\n}\n\nvoid TileLoader::setMap( const QString& theme ){\n\/\/\tInitialize map theme.\n flush();\n\n\tm_theme = theme;\n\n\tm_tile = new TextureTile( 0, 0, 0, m_theme );\n\n\/\/\tWe assume that all tiles have the same size. TODO: check to be safe\n\tm_tileWidth = m_tile->rawtile()->width();\n\tm_tileHeight = m_tile->rawtile()->height();\n\n\tdelete m_tile;\n}\n\nvoid TileLoader::resetTilehash(){\n\n\tQHash<int, TextureTile*>::const_iterator it = m_tileHash.constBegin();\n\twhile (it != m_tileHash.constEnd()) {\n\t\tm_tileHash.value(it.key())->setUsed( false );\n\t\t++it;\n\t}\n}\n\nvoid TileLoader::cleanupTilehash(){\n\/\/\tMake sure that tiles which haven't been used during the last\n\/\/\trendering of the map at all get removed from the tile hash.\n\n\tQHashIterator<int, TextureTile*> it(m_tileHash);\n\twhile (it.hasNext()) {\n\t\tit.next();\n\t\tif ((it.value())->used() == false){\n\/\/\t\t\tqDebug(\"Removing \" + QString::number(it.key()).toLatin1());\n\t\t\tdelete m_tileHash.value(it.key());\n\t\t\tm_tileHash.remove(it.key());\t\n\t\t}\n\t}\n}\n\nvoid TileLoader::flush(){\n\/\/\tRemove all m_tiles from m_tileHash\n\tQHash <int, TextureTile*>::const_iterator it;\n\tfor( it = m_tileHash.begin(); it != m_tileHash.constEnd(); it++ ) \n\t\tdelete (*it);\n\tm_tileHash.clear();\n}\n\n\nTextureTile* TileLoader::loadTile( int tilx, int tily, int tileLevel ){\n\/\/\tChoosing the correct m_tile via Lng\/Lat info \n\n\tm_tileId = (tilx *1000) + tily;\n\n\t\/\/ If the m_tile hasn't been loaded into the m_tileHash yet, then do so\n\tif (!m_tileHash.contains( m_tileId )){\t\n\t\tm_tile = new TextureTile(tilx, tily, tileLevel, m_theme);\n\t\tm_tileHash[m_tileId] = m_tile;\n\t}\n\t\/\/ otherwise pick the correct one from the hash\n\telse {\n\t\tm_tile=m_tileHash.value(m_tileId);\n\t\tif (!m_tile->used()){\n\t\t\tm_tile->setUsed(true);\n\t\t\tm_tileHash[m_tileId]=m_tile;\n\t\t}\n\t}\n\n\treturn m_tile;\n}\n\nint TileLoader::levelToRow( int level ){\n\treturn (int)pow( 2.0, (double)( level ) );\n}\n\nint TileLoader::levelToColumn( int level ){\n\treturn (int)pow( 2.0, (double)( level + 1 ) );\n}\n\nint TileLoader::rowToLevel( int row ){\n\treturn (int)( log( row ) \/ log( 2 ) );\n}\n\nint TileLoader::columnToLevel( int column ){\n\treturn (int)( log( column \/ 2 ) \/ log( 2 ) );\n}\n\nint TileLoader::maxCompleteTileLevel( const QString& theme ){\n\n\tbool noerr = true; \n\n\tint tilelevel = -1;\n\tint trylevel = 0;\n\n\/\/\tif ( m_bitmaplayer.type.toLower() == \"bitmap\" ){\n\twhile ( noerr == true ){\n\t\tint nmaxit = TileLoader::levelToRow( trylevel );\n\t\tfor ( int n=0; n < nmaxit; n++) {\n\t\t\tint mmaxit = TileLoader::levelToColumn( trylevel );\n\t\t\tfor ( int m=0; m < mmaxit; m++){\n\t\t\t\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\/%2\/%3\/%3_%4.jpg\").arg(theme).arg( trylevel ).arg( n, 4, 10, QChar('0') ).arg( m, 4, 10, QChar('0') ) );\n\/\/\t\t\t\tqDebug() << tilepath;\n\t\t\t\tnoerr = QFile::exists( tilepath );\n\t\t\t\tif ( noerr == false ) break; \n\t\t\t}\n\t\t\tif ( noerr == false ) break; \n\t\t}\t\n\n\t\tif ( noerr == true) tilelevel = trylevel;\n\t\ttrylevel++;\n\t}\n\n\tif ( tilelevel == -1 ){\n\t\tqDebug(\"No Tiles Found!\");\n\t}\n\n\tqDebug() << \"Detected maximum complete tile level: \" << tilelevel;\n\n\treturn tilelevel;\n}\n\nint TileLoader::maxPartialTileLevel( const QString& theme ){\n\n\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\").arg(theme) );\n\tQStringList leveldirs = ( QDir( tilepath ) ).entryList( QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );\n\n\tint maxtilelevel = -1;\n\n\tQString str;\n\tbool ok = true;\n\n\tQStringList::const_iterator constIterator;\n\tfor (constIterator = leveldirs.constBegin(); constIterator != leveldirs.constEnd();\n\t\t++constIterator){\n\t\tint value = (*constIterator).toInt( &ok, 10 );\n\/\/\t\tqDebug() << \"Value: \" << value << \"Ok: \" << ok;\n\t\tif ( ok && value > maxtilelevel ) maxtilelevel = value;\n\t}\n\n\tqDebug() << \"Detected maximum tile level that contains data: \" << maxtilelevel;\n\n\treturn maxtilelevel;\n}\n\nbool TileLoader::baseTilesAvailable( const QString& theme ){\n\n\tbool noerr = true; \n\n\tint n = 0;\n\n\t\/\/ Check whether the two tiles from the lowest texture level are available\n\n\tfor ( int m = 0; m < 2; ++m ){\n\t\tQString tilepath = KAtlasDirs::path( QString(\"maps\/earth\/%1\/%2\/%3\/%3_%4.jpg\").arg(theme).arg( 0 ).arg( 0, 4, 10, QChar('0') ).arg( m, 4, 10, QChar('0') ) );\n\n\t\tnoerr = QFile::exists( tilepath );\n\n\t\tif ( noerr == false ) break; \n\t}\n\n\/\/\tqDebug() << \"Mandatory most basic tile level is fully available: \" << noerr;\n\n\treturn noerr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hyperdlg.cxx,v $\n *\n * $Revision: 1.21 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 07:34:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _SV_SETTINGS_HXX\n#include <vcl\/settings.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX\n#include <svtools\/viewoptions.hxx>\n#endif\n#ifndef _CUI_TAB_HYPERLINK_HXX \/\/CHINA001\n#include \"cuihyperdlg.hxx\" \/\/CHINA001\n#endif \/\/CHINA001\n#include \"hyperdlg.hxx\"\n#include \"svxdlg.hxx\" \/\/CHINA001\n\n#include <sfx2\/app.hxx>\n\n#include \"hyperdlg.hrc\"\n\n\n\/\/########################################################################\n\/\/# #\n\/\/# Childwindow-Wrapper-Class #\n\/\/# #\n\/\/########################################################################\n\nSFX_IMPL_CHILDWINDOW(SvxHlinkDlgWrapper, SID_HYPERLINK_DIALOG)\n\n\/\/ -----------------------------------------------------------------------\n\nstruct MyStruct\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;\n SfxChildWinFactory* pFact;\n sal_Bool bHideNotDelete;\n sal_Bool bVisible;\n sal_Bool bHideAtToggle;\n SfxModule* pContextModule;\n SfxWorkWindow* pWorkWin;\n};\n\nSvxHlinkDlgWrapper::SvxHlinkDlgWrapper( Window* _pParent, USHORT nId,\n SfxBindings* pBindings,\n SfxChildWinInfo* pInfo ) :\n SfxChildWindow( _pParent, nId ),\n\n mpDlg( NULL )\n\n{\n \/\/CHINA001 pWindow = new SvxHpLinkDlg( _pParent, pBindings );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n DBG_ASSERT(pFact, \"Dialogdiet fail!\");\/\/CHINA001\n mpDlg = pFact->CreateSvxHpLinkDlg( _pParent, pBindings, SID_HYPERLINK_DIALOG );\n DBG_ASSERT(mpDlg, \"Dialogdiet fail!\");\/\/CHINA001\n pWindow = mpDlg->GetWindow();\n ((MyStruct*)pImp)->bVisible = FALSE;\n\n if ( pInfo->aSize.Width() != 0 && pInfo->aSize.Height() != 0 )\n {\n Size aParentSize( SFX_APP()->GetTopWindow()->GetSizePixel() );\n Size aDlgSize ( GetSizePixel () );\n\n if( aParentSize.Width() < pInfo->aPos.X() )\n pInfo->aPos.setX( aParentSize.Width()-aDlgSize.Width() < long(0.1*aParentSize.Width()) ?\n long(0.1*aParentSize.Width()) : aParentSize.Width()-aDlgSize.Width() );\n if( aParentSize.Height() < pInfo->aPos. Y() )\n pInfo->aPos.setY( aParentSize.Height()-aDlgSize.Height() < long(0.1*aParentSize.Height()) ?\n long(0.1*aParentSize.Height()) : aParentSize.Height()-aDlgSize.Height() );\n\n pWindow->SetPosPixel( pInfo->aPos );\n }\n\n eChildAlignment = SFX_ALIGN_NOALIGNMENT;\n\n SetHideNotDelete( TRUE );\n}\n\nSfxChildWinInfo SvxHlinkDlgWrapper::GetInfo() const\n{\n return SfxChildWindow::GetInfo();\n}\n\nsal_Bool SvxHlinkDlgWrapper::QueryClose()\n{\n return mpDlg ? mpDlg->QueryClose() : sal_True;\n}\n\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.21.50); FILE MERGED 2007\/06\/04 13:26:19 vg 1.21.50.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hyperdlg.cxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 17:12:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _SV_SETTINGS_HXX\n#include <vcl\/settings.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX\n#include <svtools\/viewoptions.hxx>\n#endif\n#ifndef _CUI_TAB_HYPERLINK_HXX \/\/CHINA001\n#include \"cuihyperdlg.hxx\" \/\/CHINA001\n#endif \/\/CHINA001\n#include \"hyperdlg.hxx\"\n#include <svx\/svxdlg.hxx> \/\/CHINA001\n\n#include <sfx2\/app.hxx>\n\n#include \"hyperdlg.hrc\"\n\n\n\/\/########################################################################\n\/\/# #\n\/\/# Childwindow-Wrapper-Class #\n\/\/# #\n\/\/########################################################################\n\nSFX_IMPL_CHILDWINDOW(SvxHlinkDlgWrapper, SID_HYPERLINK_DIALOG)\n\n\/\/ -----------------------------------------------------------------------\n\nstruct MyStruct\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;\n SfxChildWinFactory* pFact;\n sal_Bool bHideNotDelete;\n sal_Bool bVisible;\n sal_Bool bHideAtToggle;\n SfxModule* pContextModule;\n SfxWorkWindow* pWorkWin;\n};\n\nSvxHlinkDlgWrapper::SvxHlinkDlgWrapper( Window* _pParent, USHORT nId,\n SfxBindings* pBindings,\n SfxChildWinInfo* pInfo ) :\n SfxChildWindow( _pParent, nId ),\n\n mpDlg( NULL )\n\n{\n \/\/CHINA001 pWindow = new SvxHpLinkDlg( _pParent, pBindings );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n DBG_ASSERT(pFact, \"Dialogdiet fail!\");\/\/CHINA001\n mpDlg = pFact->CreateSvxHpLinkDlg( _pParent, pBindings, SID_HYPERLINK_DIALOG );\n DBG_ASSERT(mpDlg, \"Dialogdiet fail!\");\/\/CHINA001\n pWindow = mpDlg->GetWindow();\n ((MyStruct*)pImp)->bVisible = FALSE;\n\n if ( pInfo->aSize.Width() != 0 && pInfo->aSize.Height() != 0 )\n {\n Size aParentSize( SFX_APP()->GetTopWindow()->GetSizePixel() );\n Size aDlgSize ( GetSizePixel () );\n\n if( aParentSize.Width() < pInfo->aPos.X() )\n pInfo->aPos.setX( aParentSize.Width()-aDlgSize.Width() < long(0.1*aParentSize.Width()) ?\n long(0.1*aParentSize.Width()) : aParentSize.Width()-aDlgSize.Width() );\n if( aParentSize.Height() < pInfo->aPos. Y() )\n pInfo->aPos.setY( aParentSize.Height()-aDlgSize.Height() < long(0.1*aParentSize.Height()) ?\n long(0.1*aParentSize.Height()) : aParentSize.Height()-aDlgSize.Height() );\n\n pWindow->SetPosPixel( pInfo->aPos );\n }\n\n eChildAlignment = SFX_ALIGN_NOALIGNMENT;\n\n SetHideNotDelete( TRUE );\n}\n\nSfxChildWinInfo SvxHlinkDlgWrapper::GetInfo() const\n{\n return SfxChildWindow::GetInfo();\n}\n\nsal_Bool SvxHlinkDlgWrapper::QueryClose()\n{\n return mpDlg ? mpDlg->QueryClose() : sal_True;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Copyright (c) 2017 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"infill.h\"\n#include \"LayerPlan.h\"\n#include \"sliceDataStorage.h\"\n#include \"TopSurface.h\"\n\nnamespace cura\n{\n\nTopSurface::TopSurface()\n{\n \/\/Do nothing. Areas stays empty.\n}\n\nvoid TopSurface::setAreasFromMeshAndLayerNumber(SliceMeshStorage& mesh, size_t layer_number)\n{\n \/\/The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.\n Polygons mesh_above;\n if (layer_number < mesh.layers.size() - 1)\n {\n mesh_above = mesh.layers[layer_number + 1].getOutlines();\n } \/\/If this is the top-most layer, mesh_above stays empty.\n\n areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);\n}\n\nbool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer) const\n{\n if (areas.empty())\n {\n return false; \/\/Nothing to do.\n }\n \/\/Generate the lines to cover the surface.\n const EFillMethod pattern = mesh.settings.get<EFillMethod>(\"ironing_pattern\");\n const bool zig_zaggify_infill = pattern == EFillMethod::ZIG_ZAG;\n constexpr bool connect_polygons = false; \/\/ midway connections can make the surface less smooth\n const coord_t line_spacing = mesh.settings.get<coord_t>(\"ironing_line_spacing\");\n const coord_t line_width = line_config.getLineWidth();\n const std::vector<AngleDegrees>& top_most_skin_angles = (mesh.settings.get<size_t>(\"roofing_layer_count\") > 0) ? mesh.roofing_angles : mesh.skin_angles;\n assert(top_most_skin_angles.size() > 0);\n const AngleDegrees direction = top_most_skin_angles[layer.getLayerNr() % top_most_skin_angles.size()] + AngleDegrees(90.0); \/\/Always perpendicular to the skin lines.\n constexpr coord_t infill_overlap = 0;\n constexpr int infill_multiplier = 1;\n constexpr coord_t shift = 0;\n const Ratio ironing_flow = mesh.settings.get<Ratio>(\"ironing_flow\");\n\n coord_t ironing_inset = -mesh.settings.get<coord_t>(\"ironing_inset\");\n if (pattern == EFillMethod::ZIG_ZAG && ironing_inset == 0)\n {\n \/\/Compensate for the outline_offset decrease that takes place when using the infill generator to generate ironing with the zigzag pattern\n const Ratio width_scale = (float)mesh.settings.get<coord_t>(\"layer_height\") \/ mesh.settings.get<coord_t>(\"infill_sparse_thickness\");\n ironing_inset += width_scale * line_width \/ 2;\n \/\/Align the edge of the ironing line with the edge of the outer wall\n ironing_inset -= ironing_flow * line_width \/ 2;\n }\n else if (pattern == EFillMethod::CONCENTRIC)\n {\n \/\/Counteract the outline_offset increase that takes place when using the infill generator to generate ironing with the concentric pattern\n ironing_inset += line_spacing - line_width \/ 2;\n \/\/Align the edge of the ironing line with the edge of the outer wall\n ironing_inset -= ironing_flow * line_width \/ 2;\n }\n const coord_t outline_offset = ironing_inset;\n\n Infill infill_generator(pattern, zig_zaggify_infill, connect_polygons, areas, outline_offset, line_width, line_spacing, infill_overlap, infill_multiplier, direction, layer.z - 10, shift);\n Polygons ironing_polygons;\n Polygons ironing_lines;\n infill_generator.generate(ironing_polygons, ironing_lines);\n\n if (ironing_polygons.empty() && ironing_lines.empty())\n {\n return false; \/\/Nothing to do.\n }\n\n layer.mode_skip_agressive_merge = true;\n\n bool added = false;\n if (!ironing_polygons.empty())\n {\n constexpr bool force_comb_retract = false;\n layer.addTravel(ironing_polygons[0][0], force_comb_retract);\n layer.addPolygonsByOptimizer(ironing_polygons, line_config, nullptr, ZSeamConfig());\n added = true;\n }\n\n if (!ironing_lines.empty())\n {\n if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG)\n {\n \/\/Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams.\n const AABB bounding_box(areas);\n PointMatrix rotate(-direction + 90);\n const Point center = bounding_box.getMiddle();\n const Point far_away = rotate.apply(Point(0, vSize(bounding_box.max - center) * 100)); \/\/Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre.\n \/\/Two options to start, both perpendicular to the ironing lines. Which is closer?\n const Point front_side = PolygonUtils::findNearestVert(center + far_away, areas).p();\n const Point back_side = PolygonUtils::findNearestVert(center - far_away, areas).p();\n if (vSize2(layer.getLastPlannedPositionOrStartingPosition() - front_side) < vSize2(layer.getLastPlannedPositionOrStartingPosition() - back_side))\n {\n layer.addTravel(front_side);\n }\n else\n {\n layer.addTravel(back_side);\n }\n }\n\n layer.addLinesByOptimizer(ironing_lines, line_config, SpaceFillType::PolyLines);\n added = true;\n }\n\n layer.mode_skip_agressive_merge = false;\n return added;\n}\n\n}\n<commit_msg>Apply corrections in zigzag ironing pattern even if inset != 0<commit_after>\/\/Copyright (c) 2017 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"infill.h\"\n#include \"LayerPlan.h\"\n#include \"sliceDataStorage.h\"\n#include \"TopSurface.h\"\n\nnamespace cura\n{\n\nTopSurface::TopSurface()\n{\n \/\/Do nothing. Areas stays empty.\n}\n\nvoid TopSurface::setAreasFromMeshAndLayerNumber(SliceMeshStorage& mesh, size_t layer_number)\n{\n \/\/The top surface is all parts of the mesh where there's no mesh above it, so find the layer above it first.\n Polygons mesh_above;\n if (layer_number < mesh.layers.size() - 1)\n {\n mesh_above = mesh.layers[layer_number + 1].getOutlines();\n } \/\/If this is the top-most layer, mesh_above stays empty.\n\n areas = mesh.layers[layer_number].getOutlines().difference(mesh_above);\n}\n\nbool TopSurface::ironing(const SliceMeshStorage& mesh, const GCodePathConfig& line_config, LayerPlan& layer) const\n{\n if (areas.empty())\n {\n return false; \/\/Nothing to do.\n }\n \/\/Generate the lines to cover the surface.\n const EFillMethod pattern = mesh.settings.get<EFillMethod>(\"ironing_pattern\");\n const bool zig_zaggify_infill = pattern == EFillMethod::ZIG_ZAG;\n constexpr bool connect_polygons = false; \/\/ midway connections can make the surface less smooth\n const coord_t line_spacing = mesh.settings.get<coord_t>(\"ironing_line_spacing\");\n const coord_t line_width = line_config.getLineWidth();\n const std::vector<AngleDegrees>& top_most_skin_angles = (mesh.settings.get<size_t>(\"roofing_layer_count\") > 0) ? mesh.roofing_angles : mesh.skin_angles;\n assert(top_most_skin_angles.size() > 0);\n const AngleDegrees direction = top_most_skin_angles[layer.getLayerNr() % top_most_skin_angles.size()] + AngleDegrees(90.0); \/\/Always perpendicular to the skin lines.\n constexpr coord_t infill_overlap = 0;\n constexpr int infill_multiplier = 1;\n constexpr coord_t shift = 0;\n const Ratio ironing_flow = mesh.settings.get<Ratio>(\"ironing_flow\");\n\n coord_t ironing_inset = -mesh.settings.get<coord_t>(\"ironing_inset\");\n if (pattern == EFillMethod::ZIG_ZAG)\n {\n \/\/Compensate for the outline_offset decrease that takes place when using the infill generator to generate ironing with the zigzag pattern\n const Ratio width_scale = (float)mesh.settings.get<coord_t>(\"layer_height\") \/ mesh.settings.get<coord_t>(\"infill_sparse_thickness\");\n ironing_inset += width_scale * line_width \/ 2;\n \/\/Align the edge of the ironing line with the edge of the outer wall\n ironing_inset -= ironing_flow * line_width \/ 2;\n }\n else if (pattern == EFillMethod::CONCENTRIC)\n {\n \/\/Counteract the outline_offset increase that takes place when using the infill generator to generate ironing with the concentric pattern\n ironing_inset += line_spacing - line_width \/ 2;\n \/\/Align the edge of the ironing line with the edge of the outer wall\n ironing_inset -= ironing_flow * line_width \/ 2;\n }\n const coord_t outline_offset = ironing_inset;\n\n Infill infill_generator(pattern, zig_zaggify_infill, connect_polygons, areas, outline_offset, line_width, line_spacing, infill_overlap, infill_multiplier, direction, layer.z - 10, shift);\n Polygons ironing_polygons;\n Polygons ironing_lines;\n infill_generator.generate(ironing_polygons, ironing_lines);\n\n if (ironing_polygons.empty() && ironing_lines.empty())\n {\n return false; \/\/Nothing to do.\n }\n\n layer.mode_skip_agressive_merge = true;\n\n bool added = false;\n if (!ironing_polygons.empty())\n {\n constexpr bool force_comb_retract = false;\n layer.addTravel(ironing_polygons[0][0], force_comb_retract);\n layer.addPolygonsByOptimizer(ironing_polygons, line_config, nullptr, ZSeamConfig());\n added = true;\n }\n\n if (!ironing_lines.empty())\n {\n if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG)\n {\n \/\/Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams.\n const AABB bounding_box(areas);\n PointMatrix rotate(-direction + 90);\n const Point center = bounding_box.getMiddle();\n const Point far_away = rotate.apply(Point(0, vSize(bounding_box.max - center) * 100)); \/\/Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre.\n \/\/Two options to start, both perpendicular to the ironing lines. Which is closer?\n const Point front_side = PolygonUtils::findNearestVert(center + far_away, areas).p();\n const Point back_side = PolygonUtils::findNearestVert(center - far_away, areas).p();\n if (vSize2(layer.getLastPlannedPositionOrStartingPosition() - front_side) < vSize2(layer.getLastPlannedPositionOrStartingPosition() - back_side))\n {\n layer.addTravel(front_side);\n }\n else\n {\n layer.addTravel(back_side);\n }\n }\n\n layer.addLinesByOptimizer(ironing_lines, line_config, SpaceFillType::PolyLines);\n added = true;\n }\n\n layer.mode_skip_agressive_merge = false;\n return added;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transfrm.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 15:36:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_TRANSFRM_HXX\n#define _SVX_TRANSFRM_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include \"dlgctrl.hxx\"\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\nclass SdrView;\n\n\/*************************************************************************\n|*\n|* Transform-Tab-Dialog\n|*\n\\************************************************************************\/\n\n\/** put this into the nAnchorTypes parameter of the SvxTransformTabDialog c'tor\n to disable the size controls *\/\nconst USHORT SVX_OBJ_NORESIZE = 0x0100;\n\n\/** put this into the nAnchorTypes parameter of the SvxTransformTabDialog c'tor\n to disable the protect controls *\/\nconst USHORT SVX_OBJ_NOPROTECT = 0x0200;\n\nclass SvxTransformTabDialog : public SfxTabDialog\n{\nprivate:\n const SdrView* pView;\n\n USHORT nAnchorCtrls;\n Link aValidateLink;\n\n virtual void PageCreated( USHORT nId, SfxTabPage &rPage );\n\npublic:\n\n SvxTransformTabDialog( Window* pParent, const SfxItemSet* pAttr,\n const SdrView* pView,\n USHORT nAnchorTypes = 0);\n ~SvxTransformTabDialog();\n\n \/\/link for the Writer to validate positions\n void SetValidateFramePosLink( const Link& rLink );\n};\n\n\/*************************************************************************\n|*\n|* position and size tab page\n|*\n\\************************************************************************\/\n\nclass SvxPositionSizeTabPage : public SvxTabPage\n{\nprivate:\n \/\/ position\n FixedLine maFlPosition;\n FixedText maFtPosX;\n MetricField maMtrPosX;\n FixedText maFtPosY;\n MetricField maMtrPosY;\n FixedText maFtPosReference;\n SvxRectCtl maCtlPos;\n\n \/\/ size\n FixedLine maFlSize;\n FixedText maFtWidth;\n MetricField maMtrWidth;\n FixedText maFtHeight;\n MetricField maMtrHeight;\n CheckBox maCbxScale;\n FixedText maFtSizeReference;\n SvxRectCtl maCtlSize;\n\n \/\/ protect\n FixedLine maFlProtect;\n TriStateBox maTsbPosProtect;\n TriStateBox maTsbSizeProtect;\n\n \/\/ adjust\n FixedLine maFlAdjust;\n TriStateBox maTsbAutoGrowWidth;\n TriStateBox maTsbAutoGrowHeight;\n\n FixedLine maFlDivider;\n\nprivate:\n const SfxItemSet& mrOutAttrs;\n\n const SdrView* mpView;\n Rectangle maRect;\n Rectangle maWorkArea;\n\n Point maAnchorPos;\n SfxMapUnit mePoolUnit;\n FieldUnit meDlgUnit;\n MapUnit meMapUnit;\n TriState mnProtectSizeState;\n bool mbPageDisabled;\n bool mbProtectDisabled;\n bool mbSizeDisabled;\n\n \/\/ frome size\n UINT32 mlOldWidth;\n UINT32 mlOldHeight;\n RECT_POINT meRP;\n\n \/\/------------------------------------\n#if _SOLAR__PRIVATE\n DECL_LINK( ChangePosProtectHdl, void * );\n DECL_LINK( ChangeSizeProtectHdl, void * );\n DECL_LINK( ChangePosXHdl, void * );\n DECL_LINK( ChangePosYHdl, void * );\n\/\/ DECL_LINK( SetAnchorHdl, ListBox * );\n\/\/ DECL_LINK( SetOrientHdl, ListBox * );\n\n void SetMinMaxPosition();\n void GetTopLeftPosition( long& rX, long& rY, const Rectangle& rRect );\n#endif\n\n#if _SOLAR__PRIVATE\n DECL_LINK( ChangeWidthHdl, void * );\n DECL_LINK( ChangeHeightHdl, void * );\n DECL_LINK( ClickSizeProtectHdl, void * );\n DECL_LINK( ClickAutoHdl, void * );\n\n void DisableSizeControls();\n void SetMaxSize( Rectangle aRect );\n Rectangle GetRect();\n#endif\n\npublic:\n SvxPositionSizeTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { mpView = pSdrView; }\n\n\/\/ void ShowAnchorCtrls(USHORT nAnchorCtrls); \/\/ Writer-spezifische Controls anzeigen\n virtual void FillUserData();\n\n void DisableResize();\n void DisableProtect();\n};\n\n\/*************************************************************************\n|*\n|* Drehwinkel-Tab-Page\n|*\n\\************************************************************************\/\nclass SvxAngleTabPage : public SvxTabPage\n{\nprivate:\n FixedLine aFlPosition;\n FixedText aFtPosX;\n MetricField aMtrPosX;\n FixedText aFtPosY;\n MetricField aMtrPosY;\n FixedText aFtPosPresets;\n SvxRectCtl aCtlRect;\n\n FixedLine aFlAngle;\n FixedText aFtAngle;\n MetricField aMtrAngle;\n FixedText aFtAnglePresets;\n SvxRectCtl aCtlAngle;\n\n const SfxItemSet& rOutAttrs;\n\n const SdrView* pView;\n Rectangle aRect;\n\n Point aAnchorPos;\n SfxMapUnit ePoolUnit;\n FieldUnit eDlgUnit;\n MapUnit eMapUnit;\n \/\/------------------------------------\n#if _SOLAR__PRIVATE\n DECL_LINK( ModifiedHdl, void * );\n#endif\npublic:\n SvxAngleTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { pView = pSdrView; }\n};\n\n\/*************************************************************************\n|*\n|* Schraegstellen\/Eckenradius-Tab-Page\n|*\n\\************************************************************************\/\nclass SvxSlantTabPage : public SvxTabPage\n{\nprivate:\n FixedLine aFlRadius;\n FixedText aFtRadius;\n MetricField aMtrRadius;\n \/\/TriStateBox aTsbVertical;\n FixedLine aFlAngle;\n FixedText aFtAngle;\n MetricField aMtrAngle;\n \/\/SvxRectCtl aCtlAngle;\n\n const SfxItemSet& rOutAttrs;\n\n const SdrView* pView;\n Rectangle aRect;\n\n SfxMapUnit ePoolUnit;\n FieldUnit eDlgUnit;\n MapUnit eMapUnit;\n \/\/------------------------------------\npublic:\n SvxSlantTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { pView = pSdrView; }\n};\n\n\n\n#endif \/\/ _SVX_TRANSFRM_HXX\n\n<commit_msg>INTEGRATION: CWS sb59 (1.6.62); FILE MERGED 2006\/08\/03 13:51:38 cl 1.6.62.1: removed compiler warnings<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transfrm.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 12:32:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_TRANSFRM_HXX\n#define _SVX_TRANSFRM_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include \"dlgctrl.hxx\"\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\nclass SdrView;\n\n\/*************************************************************************\n|*\n|* Transform-Tab-Dialog\n|*\n\\************************************************************************\/\n\n\/** put this into the nAnchorTypes parameter of the SvxTransformTabDialog c'tor\n to disable the size controls *\/\nconst USHORT SVX_OBJ_NORESIZE = 0x0100;\n\n\/** put this into the nAnchorTypes parameter of the SvxTransformTabDialog c'tor\n to disable the protect controls *\/\nconst USHORT SVX_OBJ_NOPROTECT = 0x0200;\n\nclass SvxTransformTabDialog : public SfxTabDialog\n{\nprivate:\n const SdrView* pView;\n\n USHORT nAnchorCtrls;\n Link aValidateLink;\n\n virtual void PageCreated( USHORT nId, SfxTabPage &rPage );\n\npublic:\n\n SvxTransformTabDialog( Window* pParent, const SfxItemSet* pAttr,\n const SdrView* pView,\n USHORT nAnchorTypes = 0);\n ~SvxTransformTabDialog();\n\n \/\/link for the Writer to validate positions\n void SetValidateFramePosLink( const Link& rLink );\n};\n\n\/*************************************************************************\n|*\n|* position and size tab page\n|*\n\\************************************************************************\/\n\nclass SvxPositionSizeTabPage : public SvxTabPage\n{\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\nprivate:\n \/\/ position\n FixedLine maFlPosition;\n FixedText maFtPosX;\n MetricField maMtrPosX;\n FixedText maFtPosY;\n MetricField maMtrPosY;\n FixedText maFtPosReference;\n SvxRectCtl maCtlPos;\n\n \/\/ size\n FixedLine maFlSize;\n FixedText maFtWidth;\n MetricField maMtrWidth;\n FixedText maFtHeight;\n MetricField maMtrHeight;\n CheckBox maCbxScale;\n FixedText maFtSizeReference;\n SvxRectCtl maCtlSize;\n\n \/\/ protect\n FixedLine maFlProtect;\n TriStateBox maTsbPosProtect;\n TriStateBox maTsbSizeProtect;\n\n \/\/ adjust\n FixedLine maFlAdjust;\n TriStateBox maTsbAutoGrowWidth;\n TriStateBox maTsbAutoGrowHeight;\n\n FixedLine maFlDivider;\n\nprivate:\n const SfxItemSet& mrOutAttrs;\n\n const SdrView* mpView;\n Rectangle maRect;\n Rectangle maWorkArea;\n\n Point maAnchorPos;\n SfxMapUnit mePoolUnit;\n FieldUnit meDlgUnit;\n MapUnit meMapUnit;\n TriState mnProtectSizeState;\n bool mbPageDisabled;\n bool mbProtectDisabled;\n bool mbSizeDisabled;\n\n \/\/ frome size\n UINT32 mlOldWidth;\n UINT32 mlOldHeight;\n RECT_POINT meRP;\n\n \/\/------------------------------------\n#if _SOLAR__PRIVATE\n DECL_LINK( ChangePosProtectHdl, void * );\n DECL_LINK( ChangeSizeProtectHdl, void * );\n DECL_LINK( ChangePosXHdl, void * );\n DECL_LINK( ChangePosYHdl, void * );\n\/\/ DECL_LINK( SetAnchorHdl, ListBox * );\n\/\/ DECL_LINK( SetOrientHdl, ListBox * );\n\n void SetMinMaxPosition();\n void GetTopLeftPosition( long& rX, long& rY, const Rectangle& rRect );\n#endif\n\n#if _SOLAR__PRIVATE\n DECL_LINK( ChangeWidthHdl, void * );\n DECL_LINK( ChangeHeightHdl, void * );\n DECL_LINK( ClickSizeProtectHdl, void * );\n DECL_LINK( ClickAutoHdl, void * );\n\n void DisableSizeControls();\n void SetMaxSize( Rectangle aRect );\n Rectangle GetRect();\n#endif\n\npublic:\n SvxPositionSizeTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { mpView = pSdrView; }\n\n\/\/ void ShowAnchorCtrls(USHORT nAnchorCtrls); \/\/ Writer-spezifische Controls anzeigen\n virtual void FillUserData();\n\n void DisableResize();\n void DisableProtect();\n};\n\n\/*************************************************************************\n|*\n|* Drehwinkel-Tab-Page\n|*\n\\************************************************************************\/\nclass SvxAngleTabPage : public SvxTabPage\n{\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\nprivate:\n FixedLine aFlPosition;\n FixedText aFtPosX;\n MetricField aMtrPosX;\n FixedText aFtPosY;\n MetricField aMtrPosY;\n FixedText aFtPosPresets;\n SvxRectCtl aCtlRect;\n\n FixedLine aFlAngle;\n FixedText aFtAngle;\n MetricField aMtrAngle;\n FixedText aFtAnglePresets;\n SvxRectCtl aCtlAngle;\n\n const SfxItemSet& rOutAttrs;\n\n const SdrView* pView;\n Rectangle aRect;\n\n Point aAnchorPos;\n SfxMapUnit ePoolUnit;\n FieldUnit eDlgUnit;\n MapUnit eMapUnit;\n \/\/------------------------------------\n#if _SOLAR__PRIVATE\n DECL_LINK( ModifiedHdl, void * );\n#endif\npublic:\n SvxAngleTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { pView = pSdrView; }\n};\n\n\/*************************************************************************\n|*\n|* Schraegstellen\/Eckenradius-Tab-Page\n|*\n\\************************************************************************\/\nclass SvxSlantTabPage : public SvxTabPage\n{\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\nprivate:\n FixedLine aFlRadius;\n FixedText aFtRadius;\n MetricField aMtrRadius;\n \/\/TriStateBox aTsbVertical;\n FixedLine aFlAngle;\n FixedText aFtAngle;\n MetricField aMtrAngle;\n \/\/SvxRectCtl aCtlAngle;\n\n const SfxItemSet& rOutAttrs;\n\n const SdrView* pView;\n Rectangle aRect;\n\n SfxMapUnit ePoolUnit;\n FieldUnit eDlgUnit;\n MapUnit eMapUnit;\n \/\/------------------------------------\npublic:\n SvxSlantTabPage( Window* pParent, const SfxItemSet& rInAttrs );\n\n static SfxTabPage* Create( Window*, const SfxItemSet& );\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet( SfxItemSet& );\n virtual void Reset( const SfxItemSet & );\n\n virtual void ActivatePage( const SfxItemSet& rSet );\n virtual int DeactivatePage( SfxItemSet* pSet );\n\n virtual void PointChanged( Window* pWindow, RECT_POINT eRP );\n\n void Construct();\n void SetView( const SdrView* pSdrView ) { pView = pSdrView; }\n};\n\n\n\n#endif \/\/ _SVX_TRANSFRM_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** V4l2Device.cpp\n** \n** -------------------------------------------------------------------------*\/\n\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n\/\/ libv4l2\n#include <linux\/videodev2.h>\n\n#include \"logger.h\"\n\n#include \"V4l2Device.h\"\n\n\/\/ -----------------------------------------\n\/\/ V4L2Device\n\/\/ -----------------------------------------\nV4l2Device::V4l2Device(const V4L2DeviceParameters& params, v4l2_buf_type deviceType) : m_params(params), m_fd(-1), m_deviceType(deviceType), m_bufferSize(0), m_format(0)\n{\n}\n\nV4l2Device::~V4l2Device() \n{\n\tthis->close();\n}\n\nvoid V4l2Device::close() \n{\n\tif (m_fd != -1) \t\t\n\t\t::close(m_fd);\n\t\n\tm_fd = -1;\n}\n\n\/\/ query current format\nvoid V4l2Device::queryFormat()\n{\n\tstruct v4l2_format fmt;\n\tmemset(&fmt,0,sizeof(fmt));\n\tfmt.type = m_deviceType;\n\tif (0 == ioctl(m_fd,VIDIOC_G_FMT,&fmt)) \n\t{\n\t\tm_format = fmt.fmt.pix.pixelformat;\n\t\tm_width = fmt.fmt.pix.width;\n\t\tm_height = fmt.fmt.pix.height;\n\t\tm_bufferSize = fmt.fmt.pix.sizeimage;\n\t}\n}\n\n\/\/ intialize the V4L2 connection\nbool V4l2Device::init(unsigned int mandatoryCapabilities)\n{\n struct stat sb;\n if ( (stat(m_params.m_devName.c_str(), &sb)==0) && ((sb.st_mode & S_IFMT) == S_IFCHR) )\n {\n\t\tif (initdevice(m_params.m_devName.c_str(), mandatoryCapabilities) == -1)\n\t\t{\n\t\t\tLOG(ERROR) << \"Cannot init device:\" << m_params.m_devName;\n\t\t}\n\t}\n\telse\n\t{\n \/\/ open a normal file\n m_fd = open(m_params.m_devName.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);\n\t}\n\treturn (m_fd!=-1);\n}\n\n\/\/ intialize the V4L2 device\nint V4l2Device::initdevice(const char *dev_name, unsigned int mandatoryCapabilities)\n{\n\tm_fd = open(dev_name, O_RDWR | O_NONBLOCK);\n\tif (m_fd < 0) \n\t{\n\t\tLOG(ERROR) << \"Cannot open device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\tif (checkCapabilities(m_fd,mandatoryCapabilities) !=0)\n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\t\n\tif (configureFormat(m_fd) !=0) \n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\tif (configureParam(m_fd) !=0)\n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\t\n\treturn m_fd;\n}\n\n\/\/ check needed V4L2 capabilities\nint V4l2Device::checkCapabilities(int fd, unsigned int mandatoryCapabilities)\n{\n\tstruct v4l2_capability cap;\n\tmemset(&(cap), 0, sizeof(cap));\n\tif (-1 == ioctl(fd, VIDIOC_QUERYCAP, &cap)) \n\t{\n\t\tLOG(ERROR) << \"Cannot get capabilities for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\treturn -1;\n\t}\n\tLOG(NOTICE) << \"driver:\" << cap.driver << \" capabilities:\" << std::hex << cap.capabilities << \" mandatory:\" << mandatoryCapabilities << std::dec;\n\t\t\n\tif ((cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) LOG(NOTICE) << m_params.m_devName << \" support output\";\n\tif ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) LOG(NOTICE) << m_params.m_devName << \" support capture\";\n\n\tif ((cap.capabilities & V4L2_CAP_READWRITE)) LOG(NOTICE) << m_params.m_devName << \" support read\/write\";\n\tif ((cap.capabilities & V4L2_CAP_STREAMING)) LOG(NOTICE) << m_params.m_devName << \" support streaming\";\n\n\tif ((cap.capabilities & V4L2_CAP_TIMEPERFRAME)) LOG(NOTICE) << m_params.m_devName << \" support timeperframe\"; \n\t\n\tif ( (cap.capabilities & mandatoryCapabilities) != mandatoryCapabilities )\n\t{\n\t\tLOG(ERROR) << \"Mandatory capability not available for device:\" << m_params.m_devName;\n\t\treturn -1;\n\t}\n\t\n\treturn 0;\n}\n\nstd::string fourcc(unsigned int format)\n{\n\tchar formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff), (char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };\n\treturn std::string(formatArray, strlen(formatArray));\n}\n\n\/\/ configure capture format \nint V4l2Device::configureFormat(int fd)\n{\n\t\/\/ get current configuration\n\tthis->queryFormat();\t\t\n\tLOG(NOTICE) << m_params.m_devName << \":\" << fourcc(m_format) << \" size:\" << m_width << \"x\" << m_height;\n\n\tunsigned int width = m_width;\n\tunsigned int height = m_height;\n\tif (m_params.m_width != 0) {\n\t\twidth= m_params.m_width;\n\t}\n\tif (m_params.m_height != 0) {\n\t\theight= m_params.m_height;\n\t}\t\n\tif (m_params.m_formatList.size()==0) {\n\t\tm_params.m_formatList.push_back(m_format);\n\t}\n\n\t\/\/ try to set format, widht, height\n\tstd::list<unsigned int>::iterator it;\n\tfor (it = m_params.m_formatList.begin(); it != m_params.m_formatList.end(); ++it) {\n\t\tunsigned int format = *it;\n\t\tif ( (format == m_format) && (width == m_width) && (height == m_height) ) {\n\t\t\t\/\/ format is the current one\n\t\t\treturn 0;\n\t\t}\n\t\telse if (this->configureFormat(fd, format, width, height)==0) {\n\t\t\t\/\/ format has been set\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -1;\n}\n\n\/\/ configure capture format \nint V4l2Device::configureFormat(int fd, unsigned int format, unsigned int width, unsigned int height)\n{\n\tstruct v4l2_format fmt;\t\t\t\n\tmemset(&(fmt), 0, sizeof(fmt));\n\tfmt.type = m_deviceType;\n\tfmt.fmt.pix.width = width;\n\tfmt.fmt.pix.height = height;\n\tfmt.fmt.pix.pixelformat = format;\n\tfmt.fmt.pix.field = V4L2_FIELD_ANY;\n\t\n\tif (ioctl(fd, VIDIOC_S_FMT, &fmt) == -1)\n\t{\n\t\tLOG(ERROR) << \"Cannot set format for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\treturn -1;\n\t}\t\t\t\n\tif (fmt.fmt.pix.pixelformat != format) \n\t{\n\t\tLOG(ERROR) << \"Cannot set pixelformat to:\" << fourcc(format) << \" format is:\" << fourcc(fmt.fmt.pix.pixelformat);\n\t\treturn -1;\n\t}\n\tif ((fmt.fmt.pix.width != width) || (fmt.fmt.pix.height != height))\n\t{\n\t\tLOG(WARN) << \"Cannot set size width:\" << fmt.fmt.pix.width << \" height:\" << fmt.fmt.pix.height;\n\t}\n\t\n\tm_format = fmt.fmt.pix.pixelformat;\n\tm_width = fmt.fmt.pix.width;\n\tm_height = fmt.fmt.pix.height;\t\t\n\tm_bufferSize = fmt.fmt.pix.sizeimage;\n\t\n\tLOG(NOTICE) << m_params.m_devName << \":\" << fourcc(m_format) << \" size:\" << m_params.m_width << \"x\" << m_params.m_height << \" bufferSize:\" << m_bufferSize;\n\t\n\treturn 0;\n}\n\n\/\/ configure capture FPS \nint V4l2Device::configureParam(int fd)\n{\n\tif (m_params.m_fps!=0)\n\t{\n\t\tstruct v4l2_streamparm param;\t\t\t\n\t\tmemset(&(param), 0, sizeof(param));\n\t\tparam.type = m_deviceType;\n\t\tparam.parm.capture.timeperframe.numerator = 1;\n\t\tparam.parm.capture.timeperframe.denominator = m_params.m_fps;\n\n\t\tif (ioctl(fd, VIDIOC_S_PARM, ¶m) == -1)\n\t\t{\n\t\t\tLOG(WARN) << \"Cannot set param for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\t}\n\t\n\t\tLOG(NOTICE) << \"fps:\" << param.parm.capture.timeperframe.numerator << \"\/\" << param.parm.capture.timeperframe.denominator;\n\t\tLOG(NOTICE) << \"nbBuffer:\" << param.parm.capture.readbuffers;\n\t}\n\t\n\treturn 0;\n}\n\n\n<commit_msg>fix log of width & height<commit_after>\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** V4l2Device.cpp\n** \n** -------------------------------------------------------------------------*\/\n\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n\/\/ libv4l2\n#include <linux\/videodev2.h>\n\n#include \"logger.h\"\n\n#include \"V4l2Device.h\"\n\n\/\/ -----------------------------------------\n\/\/ V4L2Device\n\/\/ -----------------------------------------\nV4l2Device::V4l2Device(const V4L2DeviceParameters& params, v4l2_buf_type deviceType) : m_params(params), m_fd(-1), m_deviceType(deviceType), m_bufferSize(0), m_format(0)\n{\n}\n\nV4l2Device::~V4l2Device() \n{\n\tthis->close();\n}\n\nvoid V4l2Device::close() \n{\n\tif (m_fd != -1) \t\t\n\t\t::close(m_fd);\n\t\n\tm_fd = -1;\n}\n\n\/\/ query current format\nvoid V4l2Device::queryFormat()\n{\n\tstruct v4l2_format fmt;\n\tmemset(&fmt,0,sizeof(fmt));\n\tfmt.type = m_deviceType;\n\tif (0 == ioctl(m_fd,VIDIOC_G_FMT,&fmt)) \n\t{\n\t\tm_format = fmt.fmt.pix.pixelformat;\n\t\tm_width = fmt.fmt.pix.width;\n\t\tm_height = fmt.fmt.pix.height;\n\t\tm_bufferSize = fmt.fmt.pix.sizeimage;\n\t}\n}\n\n\/\/ intialize the V4L2 connection\nbool V4l2Device::init(unsigned int mandatoryCapabilities)\n{\n struct stat sb;\n if ( (stat(m_params.m_devName.c_str(), &sb)==0) && ((sb.st_mode & S_IFMT) == S_IFCHR) )\n {\n\t\tif (initdevice(m_params.m_devName.c_str(), mandatoryCapabilities) == -1)\n\t\t{\n\t\t\tLOG(ERROR) << \"Cannot init device:\" << m_params.m_devName;\n\t\t}\n\t}\n\telse\n\t{\n \/\/ open a normal file\n m_fd = open(m_params.m_devName.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);\n\t}\n\treturn (m_fd!=-1);\n}\n\n\/\/ intialize the V4L2 device\nint V4l2Device::initdevice(const char *dev_name, unsigned int mandatoryCapabilities)\n{\n\tm_fd = open(dev_name, O_RDWR | O_NONBLOCK);\n\tif (m_fd < 0) \n\t{\n\t\tLOG(ERROR) << \"Cannot open device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\tif (checkCapabilities(m_fd,mandatoryCapabilities) !=0)\n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\t\n\tif (configureFormat(m_fd) !=0) \n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\tif (configureParam(m_fd) !=0)\n\t{\n\t\tthis->close();\n\t\treturn -1;\n\t}\n\t\n\treturn m_fd;\n}\n\n\/\/ check needed V4L2 capabilities\nint V4l2Device::checkCapabilities(int fd, unsigned int mandatoryCapabilities)\n{\n\tstruct v4l2_capability cap;\n\tmemset(&(cap), 0, sizeof(cap));\n\tif (-1 == ioctl(fd, VIDIOC_QUERYCAP, &cap)) \n\t{\n\t\tLOG(ERROR) << \"Cannot get capabilities for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\treturn -1;\n\t}\n\tLOG(NOTICE) << \"driver:\" << cap.driver << \" capabilities:\" << std::hex << cap.capabilities << \" mandatory:\" << mandatoryCapabilities << std::dec;\n\t\t\n\tif ((cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) LOG(NOTICE) << m_params.m_devName << \" support output\";\n\tif ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) LOG(NOTICE) << m_params.m_devName << \" support capture\";\n\n\tif ((cap.capabilities & V4L2_CAP_READWRITE)) LOG(NOTICE) << m_params.m_devName << \" support read\/write\";\n\tif ((cap.capabilities & V4L2_CAP_STREAMING)) LOG(NOTICE) << m_params.m_devName << \" support streaming\";\n\n\tif ((cap.capabilities & V4L2_CAP_TIMEPERFRAME)) LOG(NOTICE) << m_params.m_devName << \" support timeperframe\"; \n\t\n\tif ( (cap.capabilities & mandatoryCapabilities) != mandatoryCapabilities )\n\t{\n\t\tLOG(ERROR) << \"Mandatory capability not available for device:\" << m_params.m_devName;\n\t\treturn -1;\n\t}\n\t\n\treturn 0;\n}\n\nstd::string fourcc(unsigned int format)\n{\n\tchar formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff), (char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };\n\treturn std::string(formatArray, strlen(formatArray));\n}\n\n\/\/ configure capture format \nint V4l2Device::configureFormat(int fd)\n{\n\t\/\/ get current configuration\n\tthis->queryFormat();\t\t\n\tLOG(NOTICE) << m_params.m_devName << \":\" << fourcc(m_format) << \" size:\" << m_width << \"x\" << m_height;\n\n\tunsigned int width = m_width;\n\tunsigned int height = m_height;\n\tif (m_params.m_width != 0) {\n\t\twidth= m_params.m_width;\n\t}\n\tif (m_params.m_height != 0) {\n\t\theight= m_params.m_height;\n\t}\t\n\tif (m_params.m_formatList.size()==0) {\n\t\tm_params.m_formatList.push_back(m_format);\n\t}\n\n\t\/\/ try to set format, widht, height\n\tstd::list<unsigned int>::iterator it;\n\tfor (it = m_params.m_formatList.begin(); it != m_params.m_formatList.end(); ++it) {\n\t\tunsigned int format = *it;\n\t\tif ( (format == m_format) && (width == m_width) && (height == m_height) ) {\n\t\t\t\/\/ format is the current one\n\t\t\treturn 0;\n\t\t}\n\t\telse if (this->configureFormat(fd, format, width, height)==0) {\n\t\t\t\/\/ format has been set\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -1;\n}\n\n\/\/ configure capture format \nint V4l2Device::configureFormat(int fd, unsigned int format, unsigned int width, unsigned int height)\n{\n\tstruct v4l2_format fmt;\t\t\t\n\tmemset(&(fmt), 0, sizeof(fmt));\n\tfmt.type = m_deviceType;\n\tfmt.fmt.pix.width = width;\n\tfmt.fmt.pix.height = height;\n\tfmt.fmt.pix.pixelformat = format;\n\tfmt.fmt.pix.field = V4L2_FIELD_ANY;\n\t\n\tif (ioctl(fd, VIDIOC_S_FMT, &fmt) == -1)\n\t{\n\t\tLOG(ERROR) << \"Cannot set format for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\treturn -1;\n\t}\t\t\t\n\tif (fmt.fmt.pix.pixelformat != format) \n\t{\n\t\tLOG(ERROR) << \"Cannot set pixelformat to:\" << fourcc(format) << \" format is:\" << fourcc(fmt.fmt.pix.pixelformat);\n\t\treturn -1;\n\t}\n\tif ((fmt.fmt.pix.width != width) || (fmt.fmt.pix.height != height))\n\t{\n\t\tLOG(WARN) << \"Cannot set size width:\" << fmt.fmt.pix.width << \" height:\" << fmt.fmt.pix.height;\n\t}\n\t\n\tm_format = fmt.fmt.pix.pixelformat;\n\tm_width = fmt.fmt.pix.width;\n\tm_height = fmt.fmt.pix.height;\t\t\n\tm_bufferSize = fmt.fmt.pix.sizeimage;\n\t\n\tLOG(NOTICE) << m_params.m_devName << \":\" << fourcc(m_format) << \" size:\" << m_width << \"x\" << m_height << \" bufferSize:\" << m_bufferSize;\n\t\n\treturn 0;\n}\n\n\/\/ configure capture FPS \nint V4l2Device::configureParam(int fd)\n{\n\tif (m_params.m_fps!=0)\n\t{\n\t\tstruct v4l2_streamparm param;\t\t\t\n\t\tmemset(&(param), 0, sizeof(param));\n\t\tparam.type = m_deviceType;\n\t\tparam.parm.capture.timeperframe.numerator = 1;\n\t\tparam.parm.capture.timeperframe.denominator = m_params.m_fps;\n\n\t\tif (ioctl(fd, VIDIOC_S_PARM, ¶m) == -1)\n\t\t{\n\t\t\tLOG(WARN) << \"Cannot set param for device:\" << m_params.m_devName << \" \" << strerror(errno);\n\t\t}\n\t\n\t\tLOG(NOTICE) << \"fps:\" << param.parm.capture.timeperframe.numerator << \"\/\" << param.parm.capture.timeperframe.denominator;\n\t\tLOG(NOTICE) << \"nbBuffer:\" << param.parm.capture.readbuffers;\n\t}\n\t\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"http_headers.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"lease.hxx\"\n#include \"direct.hxx\"\n#include \"PInstance.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/HeadIstream.hxx\"\n#include \"istream\/BlockIstream.hxx\"\n#include \"istream\/istream_catch.hxx\"\n#include \"istream\/Sink.hxx\"\n#include \"fb_pool.hxx\"\n#include \"fs\/FilteredSocket.hxx\"\n#include \"net\/UniqueSocketDescriptor.hxx\"\n#include \"system\/Error.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/PrintException.hxx\"\n\n#include <functional>\n\n#include <stdio.h>\n#include <stdlib.h>\n\nclass Server final\n : HttpServerConnectionHandler, Lease, BufferedSocketHandler\n{\n struct pool *pool;\n\n HttpServerConnection *connection = nullptr;\n\n std::function<void(HttpServerRequest &request,\n CancellablePointer &cancel_ptr)> request_handler;\n\n FilteredSocket client_fs;\n\n bool client_fs_released = false;\n\npublic:\n Server(struct pool &_pool, EventLoop &event_loop);\n\n ~Server() noexcept {\n CheckCloseConnection();\n }\n\n struct pool &GetPool() noexcept {\n return *pool;\n }\n\n template<typename T>\n void SetRequestHandler(T &&handler) noexcept {\n request_handler = std::forward<T>(handler);\n }\n\n void CloseConnection() noexcept {\n http_server_connection_close(connection);\n connection = nullptr;\n }\n\n void CheckCloseConnection() noexcept {\n if (connection != nullptr)\n CloseConnection();\n }\n\n void SendRequest(http_method_t method, const char *uri,\n HttpHeaders &&headers,\n UnusedIstreamPtr body, bool expect_100,\n HttpResponseHandler &handler,\n CancellablePointer &cancel_ptr) noexcept {\n http_client_request(*pool, client_fs, *this,\n \"foo\",\n method, uri, std::move(headers),\n std::move(body), expect_100,\n handler, cancel_ptr);\n }\n\n void CloseClientSocket() noexcept {\n if (client_fs.IsValid() && client_fs.IsConnected()) {\n client_fs.Close();\n client_fs.Destroy();\n }\n }\n\nprivate:\n \/* virtual methods from class HttpServerConnectionHandler *\/\n void HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr) noexcept override;\n\n void LogHttpRequest(HttpServerRequest &,\n http_status_t, int64_t,\n uint64_t, uint64_t) noexcept override {}\n\n void HttpConnectionError(std::exception_ptr e) noexcept override;\n void HttpConnectionClosed() noexcept override;\n\n \/* virtual methods from class Lease *\/\n void ReleaseLease(bool reuse) noexcept override {\n client_fs_released = true;\n\n if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {\n client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);\n client_fs.UnscheduleWrite();\n } else {\n CloseClientSocket();\n }\n }\n\n \/* virtual methods from class BufferedSocketHandler *\/\n BufferedResult OnBufferedData() override {\n fprintf(stderr, \"unexpected data in idle TCP connection\");\n CloseClientSocket();\n return BufferedResult::CLOSED;\n }\n\n bool OnBufferedClosed() noexcept override {\n CloseClientSocket();\n return false;\n }\n\n gcc_noreturn\n bool OnBufferedWrite() override {\n \/* should never be reached because we never schedule\n writing *\/\n gcc_unreachable();\n }\n\n void OnBufferedError(std::exception_ptr e) noexcept override {\n PrintException(e);\n CloseClientSocket();\n }\n};\n\nclass Client final : HttpResponseHandler, IstreamSink {\n CancellablePointer client_cancel_ptr;\n\n std::exception_ptr response_error;\n std::string response_body;\n http_status_t status{};\n\n bool response_eof = false;\n\npublic:\n void SendRequest(Server &server,\n http_method_t method, const char *uri,\n HttpHeaders &&headers,\n UnusedIstreamPtr body, bool expect_100=false) noexcept {\n server.SendRequest(method, uri, std::move(headers),\n std::move(body), expect_100,\n *this, client_cancel_ptr);\n }\n\n bool IsClientDone() const noexcept {\n return response_error || response_eof;\n }\n\n void RethrowResponseError() const {\n if (response_error)\n std::rethrow_exception(response_error);\n }\n\nprivate:\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t _status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override {\n status = _status;\n\n (void)headers;\n\n IstreamSink::SetInput(std::move(body));\n input.Read();\n }\n\n void OnHttpError(std::exception_ptr ep) noexcept override {\n response_error = std::move(ep);\n }\n\n \/* virtual methods from class IstreamHandler *\/\n\n size_t OnData(const void *data, size_t length) override {\n response_body.append((const char *)data, length);\n return length;\n }\n\n void OnEof() noexcept override {\n IstreamSink::ClearInput();\n response_eof = true;\n }\n\n void OnError(std::exception_ptr ep) noexcept override {\n IstreamSink::ClearInput();\n response_error = std::move(ep);\n }\n};\n\nServer::Server(struct pool &_pool, EventLoop &event_loop)\n :pool(pool_new_libc(&_pool, \"catch\")),\n client_fs(event_loop)\n{\n UniqueSocketDescriptor client_socket, server_socket;\n if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,\n client_socket, server_socket))\n throw MakeErrno(\"socketpair() failed\");\n\n connection = http_server_connection_new(pool, event_loop,\n std::move(server_socket),\n FdType::FD_SOCKET,\n nullptr,\n nullptr, nullptr,\n true, *this);\n\n client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);\n\n pool_unref(pool);\n}\n\nstatic std::exception_ptr\ncatch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept\n{\n PrintException(ep);\n return {};\n}\n\nvoid\nServer::HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr) noexcept\n{\n request_handler(request, cancel_ptr);\n}\n\nvoid\nServer::HttpConnectionError(std::exception_ptr e) noexcept\n{\n connection = nullptr;\n\n PrintException(e);\n}\n\nvoid\nServer::HttpConnectionClosed() noexcept\n{\n connection = nullptr;\n}\n\nstatic void\ntest_catch(EventLoop &event_loop, struct pool *_pool)\n{\n Server server(*_pool, event_loop);\n\n server.SetRequestHandler([&server](HttpServerRequest &request, CancellablePointer &) noexcept {\n http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),\n istream_catch_new(&request.pool,\n std::move(request.body),\n catch_callback, nullptr));\n server.CloseConnection();\n });\n\n Client client;\n\n client.SendRequest(server,\n HTTP_METHOD_POST, \"\/\", HttpHeaders(server.GetPool()),\n istream_head_new(server.GetPool(),\n istream_block_new(server.GetPool()),\n 1024, true));\n\n while (!client.IsClientDone())\n event_loop.LoopOnce();\n\n server.CloseClientSocket();\n client.RethrowResponseError();\n\n event_loop.Dispatch();\n}\n\nint\nmain(int argc, char **argv) noexcept\ntry {\n (void)argc;\n (void)argv;\n\n direct_global_init();\n const ScopeFbPoolInit fb_pool_init;\n PInstance instance;\n\n test_catch(instance.event_loop, instance.root_pool);\n} catch (...) {\n PrintException(std::current_exception());\n return EXIT_FAILURE;\n}\n<commit_msg>test\/t_http_server: auto-close the HTTP client socket<commit_after>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"http_headers.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"lease.hxx\"\n#include \"direct.hxx\"\n#include \"PInstance.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/HeadIstream.hxx\"\n#include \"istream\/BlockIstream.hxx\"\n#include \"istream\/istream_catch.hxx\"\n#include \"istream\/Sink.hxx\"\n#include \"fb_pool.hxx\"\n#include \"fs\/FilteredSocket.hxx\"\n#include \"net\/UniqueSocketDescriptor.hxx\"\n#include \"system\/Error.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/PrintException.hxx\"\n\n#include <functional>\n\n#include <stdio.h>\n#include <stdlib.h>\n\nclass Server final\n : HttpServerConnectionHandler, Lease, BufferedSocketHandler\n{\n struct pool *pool;\n\n HttpServerConnection *connection = nullptr;\n\n std::function<void(HttpServerRequest &request,\n CancellablePointer &cancel_ptr)> request_handler;\n\n FilteredSocket client_fs;\n\n bool client_fs_released = false;\n\npublic:\n Server(struct pool &_pool, EventLoop &event_loop);\n\n ~Server() noexcept {\n CloseClientSocket();\n CheckCloseConnection();\n }\n\n struct pool &GetPool() noexcept {\n return *pool;\n }\n\n template<typename T>\n void SetRequestHandler(T &&handler) noexcept {\n request_handler = std::forward<T>(handler);\n }\n\n void CloseConnection() noexcept {\n http_server_connection_close(connection);\n connection = nullptr;\n }\n\n void CheckCloseConnection() noexcept {\n if (connection != nullptr)\n CloseConnection();\n }\n\n void SendRequest(http_method_t method, const char *uri,\n HttpHeaders &&headers,\n UnusedIstreamPtr body, bool expect_100,\n HttpResponseHandler &handler,\n CancellablePointer &cancel_ptr) noexcept {\n http_client_request(*pool, client_fs, *this,\n \"foo\",\n method, uri, std::move(headers),\n std::move(body), expect_100,\n handler, cancel_ptr);\n }\n\n void CloseClientSocket() noexcept {\n if (client_fs.IsValid() && client_fs.IsConnected()) {\n client_fs.Close();\n client_fs.Destroy();\n }\n }\n\nprivate:\n \/* virtual methods from class HttpServerConnectionHandler *\/\n void HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr) noexcept override;\n\n void LogHttpRequest(HttpServerRequest &,\n http_status_t, int64_t,\n uint64_t, uint64_t) noexcept override {}\n\n void HttpConnectionError(std::exception_ptr e) noexcept override;\n void HttpConnectionClosed() noexcept override;\n\n \/* virtual methods from class Lease *\/\n void ReleaseLease(bool reuse) noexcept override {\n client_fs_released = true;\n\n if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {\n client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);\n client_fs.UnscheduleWrite();\n } else {\n CloseClientSocket();\n }\n }\n\n \/* virtual methods from class BufferedSocketHandler *\/\n BufferedResult OnBufferedData() override {\n fprintf(stderr, \"unexpected data in idle TCP connection\");\n CloseClientSocket();\n return BufferedResult::CLOSED;\n }\n\n bool OnBufferedClosed() noexcept override {\n CloseClientSocket();\n return false;\n }\n\n gcc_noreturn\n bool OnBufferedWrite() override {\n \/* should never be reached because we never schedule\n writing *\/\n gcc_unreachable();\n }\n\n void OnBufferedError(std::exception_ptr e) noexcept override {\n PrintException(e);\n CloseClientSocket();\n }\n};\n\nclass Client final : HttpResponseHandler, IstreamSink {\n CancellablePointer client_cancel_ptr;\n\n std::exception_ptr response_error;\n std::string response_body;\n http_status_t status{};\n\n bool response_eof = false;\n\npublic:\n void SendRequest(Server &server,\n http_method_t method, const char *uri,\n HttpHeaders &&headers,\n UnusedIstreamPtr body, bool expect_100=false) noexcept {\n server.SendRequest(method, uri, std::move(headers),\n std::move(body), expect_100,\n *this, client_cancel_ptr);\n }\n\n bool IsClientDone() const noexcept {\n return response_error || response_eof;\n }\n\n void RethrowResponseError() const {\n if (response_error)\n std::rethrow_exception(response_error);\n }\n\nprivate:\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t _status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override {\n status = _status;\n\n (void)headers;\n\n IstreamSink::SetInput(std::move(body));\n input.Read();\n }\n\n void OnHttpError(std::exception_ptr ep) noexcept override {\n response_error = std::move(ep);\n }\n\n \/* virtual methods from class IstreamHandler *\/\n\n size_t OnData(const void *data, size_t length) override {\n response_body.append((const char *)data, length);\n return length;\n }\n\n void OnEof() noexcept override {\n IstreamSink::ClearInput();\n response_eof = true;\n }\n\n void OnError(std::exception_ptr ep) noexcept override {\n IstreamSink::ClearInput();\n response_error = std::move(ep);\n }\n};\n\nServer::Server(struct pool &_pool, EventLoop &event_loop)\n :pool(pool_new_libc(&_pool, \"catch\")),\n client_fs(event_loop)\n{\n UniqueSocketDescriptor client_socket, server_socket;\n if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,\n client_socket, server_socket))\n throw MakeErrno(\"socketpair() failed\");\n\n connection = http_server_connection_new(pool, event_loop,\n std::move(server_socket),\n FdType::FD_SOCKET,\n nullptr,\n nullptr, nullptr,\n true, *this);\n\n client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);\n\n pool_unref(pool);\n}\n\nstatic std::exception_ptr\ncatch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept\n{\n PrintException(ep);\n return {};\n}\n\nvoid\nServer::HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr) noexcept\n{\n request_handler(request, cancel_ptr);\n}\n\nvoid\nServer::HttpConnectionError(std::exception_ptr e) noexcept\n{\n connection = nullptr;\n\n PrintException(e);\n}\n\nvoid\nServer::HttpConnectionClosed() noexcept\n{\n connection = nullptr;\n}\n\nstatic void\ntest_catch(EventLoop &event_loop, struct pool *_pool)\n{\n Server server(*_pool, event_loop);\n\n server.SetRequestHandler([&server](HttpServerRequest &request, CancellablePointer &) noexcept {\n http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),\n istream_catch_new(&request.pool,\n std::move(request.body),\n catch_callback, nullptr));\n server.CloseConnection();\n });\n\n Client client;\n\n client.SendRequest(server,\n HTTP_METHOD_POST, \"\/\", HttpHeaders(server.GetPool()),\n istream_head_new(server.GetPool(),\n istream_block_new(server.GetPool()),\n 1024, true));\n\n while (!client.IsClientDone())\n event_loop.LoopOnce();\n\n server.CloseClientSocket();\n client.RethrowResponseError();\n\n event_loop.Dispatch();\n}\n\nint\nmain(int argc, char **argv) noexcept\ntry {\n (void)argc;\n (void)argv;\n\n direct_global_init();\n const ScopeFbPoolInit fb_pool_init;\n PInstance instance;\n\n test_catch(instance.event_loop, instance.root_pool);\n} catch (...) {\n PrintException(std::current_exception());\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_headers.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_block.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_catch.hxx\"\n#include \"istream\/istream_socketpair.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/sink_null.hxx\"\n#include \"fb_pool.hxx\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <event.h>\n\nstatic GError *\ncatch_callback(GError *error, gcc_unused void *ctx)\n{\n fprintf(stderr, \"%s\\n\", error->message);\n g_error_free(error);\n return nullptr;\n}\n\nstatic void\ncatch_close_request(struct http_server_request *request, void *ctx,\n struct async_operation_ref *async_ref gcc_unused)\n{\n (void)ctx;\n\n http_server_response(request, HTTP_STATUS_OK, HttpHeaders(),\n istream_catch_new(request->pool, request->body,\n catch_callback, nullptr));\n http_server_connection_close(request->connection);\n}\n\nstatic void\ncatch_close_error(GError *error, void *ctx)\n{\n (void)ctx;\n\n g_printerr(\"%s\\n\", error->message);\n g_error_free(error);\n}\n\nstatic void\ncatch_close_free(void *ctx)\n{\n (void)ctx;\n}\n\nstatic const struct http_server_connection_handler catch_close_handler = {\n .request = catch_close_request,\n .error = catch_close_error,\n .free = catch_close_free,\n};\n\nstatic void\ntest_catch(struct pool *pool)\n{\n int fd;\n struct http_server_connection *connection;\n\n pool = pool_new_libc(pool, \"catch\");\n\n struct istream *request =\n istream_cat_new(pool,\n istream_string_new(pool,\n \"POST \/ HTTP\/1.1\\r\\nContent-Length: 1024\\r\\n\\r\\nfoo\"),\n istream_block_new(*pool),\n nullptr);\n struct istream *sock = istream_socketpair_new(pool, request, &fd);\n sink_null_new(sock);\n\n http_server_connection_new(pool, fd, FdType::FD_SOCKET, nullptr, nullptr,\n nullptr, nullptr,\n true, &catch_close_handler, nullptr,\n &connection);\n pool_unref(pool);\n\n event_dispatch();\n}\n\nint main(int argc, char **argv) {\n struct event_base *event_base;\n struct pool *pool;\n\n (void)argc;\n (void)argv;\n\n direct_global_init();\n event_base = event_init();\n fb_pool_init(false);\n\n pool = pool_new_libc(nullptr, \"root\");\n\n test_catch(pool);\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n\n fb_pool_deinit();\n event_base_free(event_base);\n direct_global_deinit();\n}\n<commit_msg>test\/t_http_server: initialise \"log\" attribute<commit_after>#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_headers.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_block.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_catch.hxx\"\n#include \"istream\/istream_socketpair.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/sink_null.hxx\"\n#include \"fb_pool.hxx\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <event.h>\n\nstatic GError *\ncatch_callback(GError *error, gcc_unused void *ctx)\n{\n fprintf(stderr, \"%s\\n\", error->message);\n g_error_free(error);\n return nullptr;\n}\n\nstatic void\ncatch_close_request(struct http_server_request *request, void *ctx,\n struct async_operation_ref *async_ref gcc_unused)\n{\n (void)ctx;\n\n http_server_response(request, HTTP_STATUS_OK, HttpHeaders(),\n istream_catch_new(request->pool, request->body,\n catch_callback, nullptr));\n http_server_connection_close(request->connection);\n}\n\nstatic void\ncatch_close_error(GError *error, void *ctx)\n{\n (void)ctx;\n\n g_printerr(\"%s\\n\", error->message);\n g_error_free(error);\n}\n\nstatic void\ncatch_close_free(void *ctx)\n{\n (void)ctx;\n}\n\nstatic const struct http_server_connection_handler catch_close_handler = {\n .request = catch_close_request,\n .log = nullptr,\n .error = catch_close_error,\n .free = catch_close_free,\n};\n\nstatic void\ntest_catch(struct pool *pool)\n{\n int fd;\n struct http_server_connection *connection;\n\n pool = pool_new_libc(pool, \"catch\");\n\n struct istream *request =\n istream_cat_new(pool,\n istream_string_new(pool,\n \"POST \/ HTTP\/1.1\\r\\nContent-Length: 1024\\r\\n\\r\\nfoo\"),\n istream_block_new(*pool),\n nullptr);\n struct istream *sock = istream_socketpair_new(pool, request, &fd);\n sink_null_new(sock);\n\n http_server_connection_new(pool, fd, FdType::FD_SOCKET, nullptr, nullptr,\n nullptr, nullptr,\n true, &catch_close_handler, nullptr,\n &connection);\n pool_unref(pool);\n\n event_dispatch();\n}\n\nint main(int argc, char **argv) {\n struct event_base *event_base;\n struct pool *pool;\n\n (void)argc;\n (void)argv;\n\n direct_global_init();\n event_base = event_init();\n fb_pool_init(false);\n\n pool = pool_new_libc(nullptr, \"root\");\n\n test_catch(pool);\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n\n fb_pool_deinit();\n event_base_free(event_base);\n direct_global_deinit();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"istream\/istream_tee.hxx\"\n#include \"istream\/istream_delayed.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/sink_close.hxx\"\n#include \"istream\/sink_gstring.hxx\"\n#include \"async.hxx\"\n#include \"event\/Event.hxx\"\n\n#include <glib.h>\n\n#include <string.h>\n\nstruct Context {\n GString *value = nullptr;\n\n bool eof = false, aborted = false;\n};\n\nstruct BlockContext final : Context, IstreamHandler {\n \/* istream handler *\/\n\n size_t OnData(gcc_unused const void *data, gcc_unused size_t length) override {\n \/\/ block\n return 0;\n }\n\n void OnEof() override {\n eof = true;\n }\n\n void OnError(GError *error) override {\n g_error_free(error);\n aborted = true;\n }\n};\n\n\/*\n * tests\n *\n *\/\n\nstatic void\nbuffer_callback(GString *value, GError *error, void *_ctx)\n{\n auto *ctx = (Context *)_ctx;\n\n assert(value != nullptr);\n assert(error == nullptr);\n\n ctx->value = value;\n}\n\nstatic void\ntest_block1(struct pool *pool)\n{\n BlockContext ctx;\n struct async_operation_ref async_ref;\n\n Istream *delayed = istream_delayed_new(pool);\n Istream *tee = istream_tee_new(*pool, *delayed, false, false);\n Istream *second = &istream_tee_second(*tee);\n\n tee->SetHandler(ctx);\n\n sink_gstring_new(*pool, *second, buffer_callback, (Context *)&ctx, async_ref);\n assert(ctx.value == nullptr);\n\n \/* the input (istream_delayed) blocks *\/\n second->Read();\n assert(ctx.value == nullptr);\n\n \/* feed data into input *\/\n istream_delayed_set(*delayed, *istream_string_new(pool, \"foo\"));\n assert(ctx.value == nullptr);\n\n \/* the first output (block_istream_handler) blocks *\/\n second->Read();\n assert(ctx.value == nullptr);\n\n \/* close the blocking output, this should release the \"tee\"\n object and restart reading (into the second output) *\/\n assert(!ctx.aborted && !ctx.eof);\n istream_free(&tee);\n assert(!ctx.aborted && !ctx.eof);\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n}\n\nstatic void\ntest_close_data(struct pool *pool)\n{\n Context ctx;\n struct async_operation_ref async_ref;\n\n Istream *tee =\n istream_tee_new(*pool, *istream_string_new(pool, \"foo\"), false, false);\n\n sink_close_new(*pool, *tee);\n Istream *second = &istream_tee_second(*tee);\n\n sink_gstring_new(*pool, *second, buffer_callback, &ctx, async_ref);\n assert(ctx.value == nullptr);\n\n second->Read();\n\n \/* at this point, sink_close has closed itself, and istream_tee\n should have passed the data to the sink_gstring *\/\n\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n}\n\n\/**\n * Close the second output after data has been consumed only by the\n * first output. This verifies that istream_tee's \"skip\" attribute is\n * obeyed properly.\n *\/\nstatic void\ntest_close_skipped(struct pool *pool)\n{\n Context ctx;\n struct async_operation_ref async_ref;\n\n Istream *input = istream_string_new(pool, \"foo\");\n Istream *tee = istream_tee_new(*pool, *input, false, false);\n sink_gstring_new(*pool, *tee, buffer_callback, &ctx, async_ref);\n\n Istream *second = &istream_tee_second(*tee);\n sink_close_new(*pool, *second);\n\n assert(ctx.value == nullptr);\n\n input->Read();\n\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n}\n\n\n\/*\n * main\n *\n *\/\n\n\nint main(int argc, char **argv) {\n struct pool *root_pool;\n\n (void)argc;\n (void)argv;\n\n EventBase event_base;\n root_pool = pool_new_libc(nullptr, \"root\");\n\n \/* run test suite *\/\n\n test_block1(root_pool);\n test_close_data(root_pool);\n test_close_skipped(root_pool);\n\n \/* cleanup *\/\n\n pool_unref(root_pool);\n pool_commit();\n\n pool_recycler_clear();\n}\n<commit_msg>test\/t_istream_tee: add child pools<commit_after>#include \"istream\/istream_tee.hxx\"\n#include \"istream\/istream_delayed.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/sink_close.hxx\"\n#include \"istream\/sink_gstring.hxx\"\n#include \"async.hxx\"\n#include \"event\/Event.hxx\"\n\n#include <glib.h>\n\n#include <string.h>\n\nstruct Context {\n GString *value = nullptr;\n\n bool eof = false, aborted = false;\n};\n\nstruct BlockContext final : Context, IstreamHandler {\n \/* istream handler *\/\n\n size_t OnData(gcc_unused const void *data, gcc_unused size_t length) override {\n \/\/ block\n return 0;\n }\n\n void OnEof() override {\n eof = true;\n }\n\n void OnError(GError *error) override {\n g_error_free(error);\n aborted = true;\n }\n};\n\n\/*\n * tests\n *\n *\/\n\nstatic void\nbuffer_callback(GString *value, GError *error, void *_ctx)\n{\n auto *ctx = (Context *)_ctx;\n\n assert(value != nullptr);\n assert(error == nullptr);\n\n ctx->value = value;\n}\n\nstatic void\ntest_block1(struct pool *pool)\n{\n BlockContext ctx;\n struct async_operation_ref async_ref;\n\n pool = pool_new_libc(nullptr, \"test\");\n\n Istream *delayed = istream_delayed_new(pool);\n Istream *tee = istream_tee_new(*pool, *delayed, false, false);\n Istream *second = &istream_tee_second(*tee);\n\n tee->SetHandler(ctx);\n\n sink_gstring_new(*pool, *second, buffer_callback, (Context *)&ctx, async_ref);\n assert(ctx.value == nullptr);\n\n pool_unref(pool);\n\n \/* the input (istream_delayed) blocks *\/\n second->Read();\n assert(ctx.value == nullptr);\n\n \/* feed data into input *\/\n istream_delayed_set(*delayed, *istream_string_new(pool, \"foo\"));\n assert(ctx.value == nullptr);\n\n \/* the first output (block_istream_handler) blocks *\/\n second->Read();\n assert(ctx.value == nullptr);\n\n \/* close the blocking output, this should release the \"tee\"\n object and restart reading (into the second output) *\/\n assert(!ctx.aborted && !ctx.eof);\n istream_free(&tee);\n assert(!ctx.aborted && !ctx.eof);\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n\n pool_commit();\n}\n\nstatic void\ntest_close_data(struct pool *pool)\n{\n Context ctx;\n struct async_operation_ref async_ref;\n\n pool = pool_new_libc(nullptr, \"test\");\n Istream *tee =\n istream_tee_new(*pool, *istream_string_new(pool, \"foo\"), false, false);\n\n sink_close_new(*pool, *tee);\n Istream *second = &istream_tee_second(*tee);\n\n sink_gstring_new(*pool, *second, buffer_callback, &ctx, async_ref);\n assert(ctx.value == nullptr);\n\n pool_unref(pool);\n\n second->Read();\n\n \/* at this point, sink_close has closed itself, and istream_tee\n should have passed the data to the sink_gstring *\/\n\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n\n pool_commit();\n}\n\n\/**\n * Close the second output after data has been consumed only by the\n * first output. This verifies that istream_tee's \"skip\" attribute is\n * obeyed properly.\n *\/\nstatic void\ntest_close_skipped(struct pool *pool)\n{\n Context ctx;\n struct async_operation_ref async_ref;\n\n pool = pool_new_libc(nullptr, \"test\");\n Istream *input = istream_string_new(pool, \"foo\");\n Istream *tee = istream_tee_new(*pool, *input, false, false);\n sink_gstring_new(*pool, *tee, buffer_callback, &ctx, async_ref);\n\n Istream *second = &istream_tee_second(*tee);\n sink_close_new(*pool, *second);\n pool_unref(pool);\n\n assert(ctx.value == nullptr);\n\n input->Read();\n\n assert(ctx.value != nullptr);\n assert(strcmp(ctx.value->str, \"foo\") == 0);\n g_string_free(ctx.value, true);\n\n pool_commit();\n}\n\n\n\/*\n * main\n *\n *\/\n\n\nint main(int argc, char **argv) {\n struct pool *root_pool;\n\n (void)argc;\n (void)argv;\n\n EventBase event_base;\n root_pool = pool_new_libc(nullptr, \"root\");\n\n \/* run test suite *\/\n\n test_block1(root_pool);\n test_close_data(root_pool);\n test_close_skipped(root_pool);\n\n \/* cleanup *\/\n\n pool_unref(root_pool);\n pool_commit();\n\n pool_recycler_clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * spatializer.cpp: sound reverberation\n *****************************************************************************\n * Copyright (C) 2004, 2006, 2007 the VideoLAN team\n *\n * Google Summer of Code 2007\n *\n * Authors: Biodun Osunkunle <biodun@videolan.org>\n *\n * Mentor : Jean-Baptiste Kempf <jb@videolan.org>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n\/*****************************************************************************\n * Preamble\n *****************************************************************************\/\n#include <stdlib.h> \/* malloc(), free() *\/\n#include <math.h>\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <vlc_common.h>\n#include <vlc_plugin.h>\n#include \"vlc_aout.h\"\n#include \"revmodel.hpp\"\n#define SPAT_AMP 0.3\n\/*****************************************************************************\n * Module descriptor\n *****************************************************************************\/\nstatic int Open ( vlc_object_t * );\nstatic void Close( vlc_object_t * );\n\n#define ROOMSIZE_TEXT N_(\"Room size\")\n#define ROOMSIZE_LONGTEXT N_(\"Defines the virtual surface of the room\" \\\n \"emulated by the filter.\" )\n\n#define WIDTH_TEXT N_(\"Room width\")\n#define WIDTH_LONGTEXT N_(\"Width of the virtual room\")\n\n#define WET_TEXT \"\"\n#define WET_LONGTEXT \"\"\n\n#define DRY_TEXT \"\"\n#define DRY_LONGTEXT \"\"\n\n#define DAMP_TEXT \"\"\n#define DAMP_LONGTEXT \"\"\n\nvlc_module_begin ()\n set_description( N_(\"spatializer\") )\n set_shortname( N_(\"spatializer\" ) )\n set_capability( \"audio filter\", 0 )\n set_category( CAT_AUDIO )\n set_subcategory( SUBCAT_AUDIO_AFILTER )\n\n set_callbacks( Open, Close )\n add_shortcut( \"spatializer\" )\n add_float( \"Roomsize\", 1.05, NULL, ROOMSIZE_TEXT,ROOMSIZE_LONGTEXT, true)\n add_float( \"Width\", 10.0, NULL, WIDTH_TEXT,WIDTH_LONGTEXT, true)\n add_float( \"Wet\", 3.0, NULL, WET_TEXT,WET_LONGTEXT, true)\n add_float( \"Dry\", 2.0, NULL, DRY_TEXT,DRY_LONGTEXT, true)\n add_float( \"Damp\", 1.0, NULL, DAMP_TEXT,DAMP_LONGTEXT, true)\nvlc_module_end ()\n\n\/*****************************************************************************\n * Local prototypes\n *****************************************************************************\/\ntypedef struct aout_filter_sys_t\n{\n vlc_mutex_t lock;\n revmodel *p_reverbm;\n\n} aout_filter_sys_t;\n\nclass CLocker\n{\npublic:\n CLocker( vlc_mutex_t *p_lock ) : p_lock(p_lock) {\n vlc_mutex_lock( p_lock );\n }\n virtual ~CLocker() {\n vlc_mutex_unlock( p_lock );\n }\nprivate:\n vlc_mutex_t *p_lock;\n};\n\nstatic const char *psz_control_names[] =\n{\n \"Roomsize\", \"Width\" , \"Wet\", \"Dry\", \"Damp\"\n};\nstatic void DoWork( aout_instance_t *, aout_filter_t *,\n aout_buffer_t *, aout_buffer_t * );\n\nstatic int SpatInit( aout_filter_t *);\nstatic void SpatFilter( aout_instance_t *,aout_filter_t *, float *, float *,\n int, int );\nstatic void SpatClean( aout_filter_t * );\nstatic int RoomCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int WetCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int DryCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int DampCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int WidthCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\n\n\/*****************************************************************************\n * Open:\n *****************************************************************************\/\nstatic int Open( vlc_object_t *p_this )\n{\n aout_filter_t *p_filter = (aout_filter_t *)p_this;\n aout_filter_sys_t *p_sys;\n bool b_fit = true;\n msg_Dbg(p_this, \"Opening filter spatializer %s %s %d\\n\", __FILE__,__func__,__LINE__);\n\n if( p_filter->input.i_format != VLC_FOURCC('f','l','3','2' ) ||\n p_filter->output.i_format != VLC_FOURCC('f','l','3','2') )\n {\n b_fit = false;\n p_filter->input.i_format = VLC_FOURCC('f','l','3','2');\n p_filter->output.i_format = VLC_FOURCC('f','l','3','2');\n msg_Warn( p_filter, \"bad input or output format\" );\n }\n if ( !AOUT_FMTS_SIMILAR( &p_filter->input, &p_filter->output ) )\n {\n b_fit = false;\n memcpy( &p_filter->output, &p_filter->input,\n sizeof(audio_sample_format_t) );\n msg_Warn( p_filter, \"input and output formats are not similar\" );\n }\n\n if ( ! b_fit )\n {\n return VLC_EGENERIC;\n }\n\n p_filter->pf_do_work = DoWork;\n p_filter->b_in_place = true;\n\n \/* Allocate structure *\/\n p_sys = p_filter->p_sys = (aout_filter_sys_t*)malloc( sizeof( aout_filter_sys_t ) );\n if( !p_sys )\n return VLC_ENOMEM;\n\n vlc_mutex_init( &p_sys->lock );\n p_sys->p_reverbm = new revmodel();\n p_sys->p_reverbm->setroomsize(1.05);\n p_sys->p_reverbm->setwet(10.0f);\n p_sys->p_reverbm->setdry(1.0f);\n p_sys->p_reverbm->setdamp(0.3);\n p_sys->p_reverbm->setwidth(0.9);\n SpatInit( p_filter);\n\n return VLC_SUCCESS;\n}\n\n\/*****************************************************************************\n * Close: close the plugin\n *****************************************************************************\/\nstatic void Close( vlc_object_t *p_this )\n{\n aout_filter_t *p_filter = (aout_filter_t *)p_this;\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n SpatClean( p_filter );\n delete p_sys->p_reverbm;\n vlc_mutex_destroy( &p_sys->lock );\n free( p_sys );\n msg_Dbg(p_this, \"Closing filter spatializer %s %s %d\\n\", __FILE__,__func__,__LINE__);\n}\n\n\/*****************************************************************************\n * DoWork: process samples buffer\n *****************************************************************************\/\nstatic void DoWork( aout_instance_t * p_aout, aout_filter_t * p_filter,\n aout_buffer_t * p_in_buf, aout_buffer_t * p_out_buf )\n{\n p_out_buf->i_nb_samples = p_in_buf->i_nb_samples;\n p_out_buf->i_nb_bytes = p_in_buf->i_nb_bytes;\n\n SpatFilter( p_aout, p_filter, (float*)p_out_buf->p_buffer,\n (float*)p_in_buf->p_buffer, p_in_buf->i_nb_samples,\n aout_FormatNbChannels( &p_filter->input ) );\n}\n\nstatic int SpatInit( aout_filter_t *p_filter )\n{\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n int i, ch;\n vlc_value_t val1, val2, val3, val4, val5;\n aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;\n\n for( i = 0; i < 5 ; i ++ )\n var_Create( p_aout, psz_control_names[i], VLC_VAR_FLOAT\n | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );\n\n \/* Get initial values *\/\n var_Get( p_aout, psz_control_names[0], &val1 );\n var_Get( p_aout, psz_control_names[1], &val2 );\n var_Get( p_aout, psz_control_names[2], &val3 );\n var_Get( p_aout, psz_control_names[3], &val4 );\n var_Get( p_aout, psz_control_names[4], &val5);\n\n RoomCallback( VLC_OBJECT( p_aout ), NULL, val1, val1, p_sys );\n WidthCallback( VLC_OBJECT( p_aout ), NULL, val2, val2, p_sys );\n WetCallback( VLC_OBJECT( p_aout ), NULL, val3, val3, p_sys );\n DryCallback( VLC_OBJECT( p_aout ), NULL, val4, val4, p_sys );\n DampCallback( VLC_OBJECT( p_aout ), NULL, val5, val5, p_sys );\n\n msg_Dbg( p_filter, \"%f\", val1.f_float );\n \/* Add our own callbacks *\/\n var_AddCallback( p_aout, psz_control_names[0], RoomCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[1], WidthCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[2], WetCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[3], DryCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[4], DampCallback, p_sys );\n\n return VLC_SUCCESS;\n}\n\nstatic void SpatFilter( aout_instance_t *p_aout,\n aout_filter_t *p_filter, float *out, float *in,\n int i_samples, int i_channels )\n{\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n CLocker locker( &p_sys->lock );\n\n int i, ch, j;\n for( i = 0; i < i_samples; i++ )\n {\n for( ch = 0 ; ch < 2; ch++)\n {\n in[ch] = in[ch] * SPAT_AMP;\n }\n p_sys->p_reverbm->processreplace( in, out , 1, i_channels);\n in += i_channels;\n out += i_channels;\n }\n}\n\nstatic void SpatClean( aout_filter_t *p_filter )\n{\n aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n\n var_DelCallback( p_aout, psz_control_names[0], RoomCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[1], WidthCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[2], WetCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[3], DryCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[4], DampCallback, p_sys );\n}\n\n\/*****************************************************************************\n * Variables callbacks\n *****************************************************************************\/\n\nstatic int RoomCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setroomsize(newval.f_float);\n msg_Dbg (p_this,\"room callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\n\nstatic int WidthCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setwidth(newval.f_float);\n msg_Dbg (p_this,\"width callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int WetCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setwet(newval.f_float);\n msg_Dbg (p_this,\"wet callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int DryCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setdry(newval.f_float);\n msg_Dbg (p_this,\"dry callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int DampCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setdamp(newval.f_float);\n msg_Dbg (p_this, \"damp callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\n\n<commit_msg>Fixed spatializer compilation.<commit_after>\/*****************************************************************************\n * spatializer.cpp: sound reverberation\n *****************************************************************************\n * Copyright (C) 2004, 2006, 2007 the VideoLAN team\n *\n * Google Summer of Code 2007\n *\n * Authors: Biodun Osunkunle <biodun@videolan.org>\n *\n * Mentor : Jean-Baptiste Kempf <jb@videolan.org>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n\/*****************************************************************************\n * Preamble\n *****************************************************************************\/\n#include <stdlib.h> \/* malloc(), free() *\/\n#include <math.h>\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include <vlc_common.h>\n#include <vlc_plugin.h>\n#include \"vlc_aout.h\"\n#include \"revmodel.hpp\"\n#define SPAT_AMP 0.3\n\/*****************************************************************************\n * Module descriptor\n *****************************************************************************\/\nstatic int Open ( vlc_object_t * );\nstatic void Close( vlc_object_t * );\n\n#define ROOMSIZE_TEXT N_(\"Room size\")\n#define ROOMSIZE_LONGTEXT N_(\"Defines the virtual surface of the room\" \\\n \"emulated by the filter.\" )\n\n#define WIDTH_TEXT N_(\"Room width\")\n#define WIDTH_LONGTEXT N_(\"Width of the virtual room\")\n\n#define WET_TEXT \"\"\n#define WET_LONGTEXT \"\"\n\n#define DRY_TEXT \"\"\n#define DRY_LONGTEXT \"\"\n\n#define DAMP_TEXT \"\"\n#define DAMP_LONGTEXT \"\"\n\nvlc_module_begin ()\n set_description( N_(\"spatializer\") )\n set_shortname( N_(\"spatializer\" ) )\n set_capability( \"audio filter\", 0 )\n set_category( CAT_AUDIO )\n set_subcategory( SUBCAT_AUDIO_AFILTER )\n\n set_callbacks( Open, Close )\n add_shortcut( \"spatializer\" )\n add_float( \"Roomsize\", 1.05, NULL, ROOMSIZE_TEXT,ROOMSIZE_LONGTEXT, true)\n add_float( \"Width\", 10.0, NULL, WIDTH_TEXT,WIDTH_LONGTEXT, true)\n add_float( \"Wet\", 3.0, NULL, WET_TEXT,WET_LONGTEXT, true)\n add_float( \"Dry\", 2.0, NULL, DRY_TEXT,DRY_LONGTEXT, true)\n add_float( \"Damp\", 1.0, NULL, DAMP_TEXT,DAMP_LONGTEXT, true)\nvlc_module_end ()\n\n\/*****************************************************************************\n * Local prototypes\n *****************************************************************************\/\nstruct aout_filter_sys_t\n{\n vlc_mutex_t lock;\n revmodel *p_reverbm;\n\n};\n\nclass CLocker\n{\npublic:\n CLocker( vlc_mutex_t *p_lock ) : p_lock(p_lock) {\n vlc_mutex_lock( p_lock );\n }\n virtual ~CLocker() {\n vlc_mutex_unlock( p_lock );\n }\nprivate:\n vlc_mutex_t *p_lock;\n};\n\nstatic const char *psz_control_names[] =\n{\n \"Roomsize\", \"Width\" , \"Wet\", \"Dry\", \"Damp\"\n};\nstatic void DoWork( aout_instance_t *, aout_filter_t *,\n aout_buffer_t *, aout_buffer_t * );\n\nstatic int SpatInit( aout_filter_t *);\nstatic void SpatFilter( aout_instance_t *,aout_filter_t *, float *, float *,\n int, int );\nstatic void SpatClean( aout_filter_t * );\nstatic int RoomCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int WetCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int DryCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int DampCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\nstatic int WidthCallback ( vlc_object_t *, char const *,\n vlc_value_t, vlc_value_t, void * );\n\n\/*****************************************************************************\n * Open:\n *****************************************************************************\/\nstatic int Open( vlc_object_t *p_this )\n{\n aout_filter_t *p_filter = (aout_filter_t *)p_this;\n aout_filter_sys_t *p_sys;\n bool b_fit = true;\n msg_Dbg(p_this, \"Opening filter spatializer %s %s %d\\n\", __FILE__,__func__,__LINE__);\n\n if( p_filter->input.i_format != VLC_FOURCC('f','l','3','2' ) ||\n p_filter->output.i_format != VLC_FOURCC('f','l','3','2') )\n {\n b_fit = false;\n p_filter->input.i_format = VLC_FOURCC('f','l','3','2');\n p_filter->output.i_format = VLC_FOURCC('f','l','3','2');\n msg_Warn( p_filter, \"bad input or output format\" );\n }\n if ( !AOUT_FMTS_SIMILAR( &p_filter->input, &p_filter->output ) )\n {\n b_fit = false;\n memcpy( &p_filter->output, &p_filter->input,\n sizeof(audio_sample_format_t) );\n msg_Warn( p_filter, \"input and output formats are not similar\" );\n }\n\n if ( ! b_fit )\n {\n return VLC_EGENERIC;\n }\n\n p_filter->pf_do_work = DoWork;\n p_filter->b_in_place = true;\n\n \/* Allocate structure *\/\n p_sys = p_filter->p_sys = (aout_filter_sys_t*)malloc( sizeof( aout_filter_sys_t ) );\n if( !p_sys )\n return VLC_ENOMEM;\n\n vlc_mutex_init( &p_sys->lock );\n p_sys->p_reverbm = new revmodel();\n p_sys->p_reverbm->setroomsize(1.05);\n p_sys->p_reverbm->setwet(10.0f);\n p_sys->p_reverbm->setdry(1.0f);\n p_sys->p_reverbm->setdamp(0.3);\n p_sys->p_reverbm->setwidth(0.9);\n SpatInit( p_filter);\n\n return VLC_SUCCESS;\n}\n\n\/*****************************************************************************\n * Close: close the plugin\n *****************************************************************************\/\nstatic void Close( vlc_object_t *p_this )\n{\n aout_filter_t *p_filter = (aout_filter_t *)p_this;\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n SpatClean( p_filter );\n delete p_sys->p_reverbm;\n vlc_mutex_destroy( &p_sys->lock );\n free( p_sys );\n msg_Dbg(p_this, \"Closing filter spatializer %s %s %d\\n\", __FILE__,__func__,__LINE__);\n}\n\n\/*****************************************************************************\n * DoWork: process samples buffer\n *****************************************************************************\/\nstatic void DoWork( aout_instance_t * p_aout, aout_filter_t * p_filter,\n aout_buffer_t * p_in_buf, aout_buffer_t * p_out_buf )\n{\n p_out_buf->i_nb_samples = p_in_buf->i_nb_samples;\n p_out_buf->i_nb_bytes = p_in_buf->i_nb_bytes;\n\n SpatFilter( p_aout, p_filter, (float*)p_out_buf->p_buffer,\n (float*)p_in_buf->p_buffer, p_in_buf->i_nb_samples,\n aout_FormatNbChannels( &p_filter->input ) );\n}\n\nstatic int SpatInit( aout_filter_t *p_filter )\n{\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n int i, ch;\n vlc_value_t val1, val2, val3, val4, val5;\n aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;\n\n for( i = 0; i < 5 ; i ++ )\n var_Create( p_aout, psz_control_names[i], VLC_VAR_FLOAT\n | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );\n\n \/* Get initial values *\/\n var_Get( p_aout, psz_control_names[0], &val1 );\n var_Get( p_aout, psz_control_names[1], &val2 );\n var_Get( p_aout, psz_control_names[2], &val3 );\n var_Get( p_aout, psz_control_names[3], &val4 );\n var_Get( p_aout, psz_control_names[4], &val5);\n\n RoomCallback( VLC_OBJECT( p_aout ), NULL, val1, val1, p_sys );\n WidthCallback( VLC_OBJECT( p_aout ), NULL, val2, val2, p_sys );\n WetCallback( VLC_OBJECT( p_aout ), NULL, val3, val3, p_sys );\n DryCallback( VLC_OBJECT( p_aout ), NULL, val4, val4, p_sys );\n DampCallback( VLC_OBJECT( p_aout ), NULL, val5, val5, p_sys );\n\n msg_Dbg( p_filter, \"%f\", val1.f_float );\n \/* Add our own callbacks *\/\n var_AddCallback( p_aout, psz_control_names[0], RoomCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[1], WidthCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[2], WetCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[3], DryCallback, p_sys );\n var_AddCallback( p_aout, psz_control_names[4], DampCallback, p_sys );\n\n return VLC_SUCCESS;\n}\n\nstatic void SpatFilter( aout_instance_t *p_aout,\n aout_filter_t *p_filter, float *out, float *in,\n int i_samples, int i_channels )\n{\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n CLocker locker( &p_sys->lock );\n\n int i, ch, j;\n for( i = 0; i < i_samples; i++ )\n {\n for( ch = 0 ; ch < 2; ch++)\n {\n in[ch] = in[ch] * SPAT_AMP;\n }\n p_sys->p_reverbm->processreplace( in, out , 1, i_channels);\n in += i_channels;\n out += i_channels;\n }\n}\n\nstatic void SpatClean( aout_filter_t *p_filter )\n{\n aout_instance_t *p_aout = (aout_instance_t *)p_filter->p_parent;\n aout_filter_sys_t *p_sys = p_filter->p_sys;\n\n var_DelCallback( p_aout, psz_control_names[0], RoomCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[1], WidthCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[2], WetCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[3], DryCallback, p_sys );\n var_DelCallback( p_aout, psz_control_names[4], DampCallback, p_sys );\n}\n\n\/*****************************************************************************\n * Variables callbacks\n *****************************************************************************\/\n\nstatic int RoomCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setroomsize(newval.f_float);\n msg_Dbg (p_this,\"room callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\n\nstatic int WidthCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setwidth(newval.f_float);\n msg_Dbg (p_this,\"width callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int WetCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setwet(newval.f_float);\n msg_Dbg (p_this,\"wet callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int DryCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setdry(newval.f_float);\n msg_Dbg (p_this,\"dry callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\nstatic int DampCallback( vlc_object_t *p_this, char const *psz_cmd,\n vlc_value_t oldval, vlc_value_t newval, void *p_data )\n{\n aout_filter_sys_t *p_sys = (aout_filter_sys_t*)p_data;\n CLocker locker( &p_sys->lock );\n\n p_sys->p_reverbm->setdamp(newval.f_float);\n msg_Dbg (p_this, \"damp callback %3.1f %s %s %d\\n\", newval.f_float, __FILE__,__func__,__LINE__);\n return VLC_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ kmidentity.cpp\n\n#include \"kmidentity.h\"\n#include \"kfileio.h\"\n#include \"kmfolder.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmkernel.h\"\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kurl.h>\n#include <klocale.h>\n#include <ktempfile.h>\n#include <kmessagebox.h>\n#include <kprocess.h>\n#include <kconfig.h>\n\n#include <qstringlist.h>\n#include <qfileinfo.h>\n#include <qdatastream.h>\n\n#include <pwd.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <errno.h>\n#include <assert.h>\n\nSignature::Signature()\n : mType( Disabled )\n{\n\n}\n\nSignature::Signature( const QString & text )\n : mText( text ),\n mType( Inlined )\n{\n\n}\n\nSignature::Signature( const QString & url, bool isExecutable )\n : mUrl( url ),\n mType( isExecutable ? FromCommand : FromFile )\n{\n}\n\nbool Signature::operator==( const Signature & other ) const {\n if ( mType != other.mType ) return false;\n switch ( mType ) {\n case Inlined: return mText == other.mText;\n case FromFile:\n case FromCommand: return mUrl == other.mUrl;\n default:\n case Disabled: return true;\n }\n}\n\nQString Signature::rawText( bool * ok ) const\n{\n switch ( mType ) {\n case Disabled:\n if ( ok ) *ok = true;\n return QString::null;\n case Inlined:\n if ( ok ) *ok = true;\n return mText;\n case FromFile:\n return textFromFile( ok );\n case FromCommand:\n return textFromCommand( ok );\n };\n kdFatal( 5006 ) << \"Signature::type() returned unknown value!\" << endl;\n return QString::null; \/\/ make compiler happy\n}\n\nQString Signature::textFromCommand( bool * ok ) const\n{\n assert( mType == FromCommand );\n\n \/\/ handle pathological cases:\n if ( mUrl.isEmpty() ) {\n if ( ok ) *ok = true;\n return QString::null;\n }\n\n \/\/ create a shell process:\n#if KDE_VERSION >= 305\n KProcess proc;\n proc.setUseShell(true);\n#else\n KShellProcess proc;\n#endif\n proc << mUrl;\n\n \/\/ let the kernel collect the output for us:\n QObject::connect( &proc, SIGNAL(receivedStdout(KProcess*,char*,int)),\n\t\t kernel, SLOT(slotCollectStdOut(KProcess*,char*,int)) );\n\n \/\/ run the process:\n int rc = 0;\n if ( !proc.start( KProcess::Block, KProcess::Stdout ) )\n rc = -1;\n else\n rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ;\n\n \/\/ get output:\n QByteArray output = kernel->getCollectedStdOut( &proc );\n\n \/\/ handle errors, if any:\n if ( rc != 0 ) {\n if ( ok ) *ok = false;\n QString wmsg = i18n(\"Failed to execute signature script\\n%1:\\n%2\")\n .arg( mUrl ).arg( strerror(rc) );\n KMessageBox::error(0, wmsg);\n return QString::null;\n }\n\n \/\/ no errors:\n if ( ok ) *ok = true;\n \/\/ ### hmm, should we allow other encodings, too?\n return QString::fromLocal8Bit( output.data(), output.size() );\n}\n\nQString Signature::textFromFile( bool * ok ) const\n{\n assert( mType == FromFile );\n\n \/\/ ### FIXME: Use KIO::NetAccess to download non-local files!\n if ( !KURL(mUrl).isLocalFile() && !(QFileInfo(mUrl).isRelative()\n\t\t\t\t\t&& QFileInfo(mUrl).exists()) ) {\n kdDebug( 5006 ) << \"Signature::textFromFile: non-local URLs are unsupported\" << endl;\n if ( ok ) *ok = false;\n return QString::null;\n }\n if ( ok ) *ok = true;\n \/\/ ### hmm, should we allow other encodings, too?\n return QString::fromLocal8Bit( kFileToString( mUrl ) );\n}\n\nQString Signature::withSeparator( bool * ok ) const\n{\n bool internalOK = false;\n QString signature = rawText( &internalOK );\n if ( !internalOK ) {\n if ( ok ) *ok = false;\n return QString::null;\n }\n if ( ok ) *ok = true;\n if ( signature.isEmpty() ) return signature; \/\/ don't add a separator in this case\n if ( signature.startsWith( QString::fromLatin1(\"-- \\n\") ) ||\n signature.find( QString::fromLatin1(\"\\n-- \\n\") ) != -1 )\n \/\/ already have signature separator:\n return signature;\n else\n \/\/ need to prepend one:\n return QString::fromLatin1(\"-- \\n\") + signature;\n}\n\n\nvoid Signature::setUrl( const QString & url, bool isExecutable )\n{\n mUrl = url;\n mType = isExecutable ? FromCommand : FromFile ;\n}\n\n\/\/ config keys and values:\nstatic const char * sigTypeKey = \"Signature Type\";\nstatic const char * sigTypeInlineValue = \"inline\";\nstatic const char * sigTypeFileValue = \"file\";\nstatic const char * sigTypeCommandValue = \"command\";\nstatic const char * sigTypeDisabledValue = \"disabled\";\nstatic const char * sigTextKey = \"Inline Signature\";\nstatic const char * sigFileKey = \"Signature File\";\nstatic const char * sigCommandKey = \"Signature Command\";\n\nvoid Signature::readConfig( const KConfigBase * config )\n{\n QString sigType = config->readEntry( sigTypeKey );\n if ( sigType == sigTypeInlineValue ) {\n mType = Inlined;\n mText = config->readEntry( sigTextKey );\n } else if ( sigType == sigTypeFileValue ) {\n mType = FromFile;\n mUrl = config->readEntry( sigFileKey );\n } else if ( sigType == sigTypeCommandValue ) {\n mType = FromCommand;\n mUrl = config->readEntry( sigCommandKey );\n } else {\n mType = Disabled;\n }\n}\n\nvoid Signature::writeConfig( KConfigBase * config ) const\n{\n switch ( mType ) {\n case Inlined:\n config->writeEntry( sigTypeKey, sigTypeInlineValue );\n config->writeEntry( sigTextKey, mText );\n break;\n case FromFile:\n config->writeEntry( sigTypeKey, sigTypeFileValue );\n config->writeEntry( sigFileKey, mUrl );\n break;\n case FromCommand:\n config->writeEntry( sigTypeKey, sigTypeCommandValue );\n config->writeEntry( sigCommandKey, mUrl );\n break;\n case Disabled:\n config->writeEntry( sigTypeKey, sigTypeDisabledValue );\n default: ;\n }\n}\n\nQDataStream & operator<<( QDataStream & stream, const Signature & sig ) {\n return stream << static_cast<Q_UINT8>(sig.mType)\n\t\t<< sig.mUrl\n\t\t<< sig.mText;\n}\n\nQDataStream & operator>>( QDataStream & stream, Signature & sig ) {\n Q_UINT8 s;\n stream >> s\n >> sig.mUrl\n >> sig.mText;\n sig.mType = static_cast<Signature::Type>(s);\n return stream;\n}\n\nKMIdentity KMIdentity::null;\n\nbool KMIdentity::isNull() const {\n return mIdentity.isNull() && mFullName.isNull() && mEmailAddr.isNull() &&\n mOrganization.isNull() && mReplyToAddr.isNull() && mBcc.isNull() && \n mVCardFile.isNull() &&\n mPgpIdentity.isNull() && mFcc.isNull() && mDrafts.isNull() &&\n mTransport.isNull() && mSignature.type() == Signature::Disabled;\n}\n\nbool KMIdentity::operator==( const KMIdentity & other ) const {\n return mUoid == other.mUoid &&\n mIdentity == other.mIdentity && mFullName == other.mFullName &&\n mEmailAddr == other.mEmailAddr && mOrganization == other.mOrganization &&\n mReplyToAddr == other.mReplyToAddr && mBcc == other.mBcc &&\n mVCardFile == other.mVCardFile &&\n mPgpIdentity == other.mPgpIdentity && mFcc == other.mFcc &&\n mDrafts == other.mDrafts && mTransport == other.mTransport &&\n mSignature == other.mSignature;\n}\n\nKMIdentity::KMIdentity( const QString & id, const QString & fullName,\n\t\t\tconst QString & emailAddr, const QString & organization,\n\t\t\tconst QString & replyToAddr )\n : mUoid( 0 ), mIdentity( id ), mFullName( fullName ),\n mEmailAddr( emailAddr ), mOrganization( organization ),\n mReplyToAddr( replyToAddr ), mIsDefault( false )\n{\n\n}\n\nKMIdentity::~KMIdentity()\n{\n}\n\n\nvoid KMIdentity::readConfig( const KConfigBase * config )\n{\n mUoid = config->readUnsignedNumEntry(\"uoid\",0);\n\n mIdentity = config->readEntry(\"Identity\");\n mFullName = config->readEntry(\"Name\");\n mEmailAddr = config->readEntry(\"Email Address\");\n mVCardFile = config->readEntry(\"VCardFile\");\n mOrganization = config->readEntry(\"Organization\");\n mPgpIdentity = config->readEntry(\"Default PGP Key\").local8Bit();\n mReplyToAddr = config->readEntry(\"Reply-To Address\");\n mBcc = config->readEntry(\"Bcc\");\n mFcc = config->readEntry(\"Fcc\");\n mDrafts = config->readEntry(\"Drafts\");\n mTransport = config->readEntry(\"Transport\");\n\n mSignature.readConfig( config );\n kdDebug() << \"KMIdentity::readConfig(): UOID = \" << mUoid\n\t << \" for identity named \\\"\" << mIdentity << \"\\\"\" << endl;\n}\n\n\nvoid KMIdentity::writeConfig( KConfigBase * config ) const\n{\n config->writeEntry(\"uoid\", mUoid);\n\n config->writeEntry(\"Identity\", mIdentity);\n config->writeEntry(\"Name\", mFullName);\n config->writeEntry(\"Organization\", mOrganization);\n config->writeEntry(\"Default PGP Key\", mPgpIdentity.data());\n config->writeEntry(\"Email Address\", mEmailAddr);\n config->writeEntry(\"Reply-To Address\", mReplyToAddr);\n config->writeEntry(\"Bcc\", mBcc);\n config->writeEntry(\"VCardFile\", mVCardFile);\n config->writeEntry(\"Transport\", mTransport);\n config->writeEntry(\"Fcc\", mFcc);\n config->writeEntry(\"Drafts\", mDrafts);\n\n mSignature.writeConfig( config );\n}\n\nQDataStream & operator<<( QDataStream & stream, const KMIdentity & i ) {\n return stream << static_cast<Q_UINT32>(i.uoid())\n\t\t<< i.identityName()\n\t\t<< i.fullName()\n\t\t<< i.organization()\n\t\t<< i.pgpIdentity()\n\t\t<< i.emailAddr()\n\t\t<< i.replyToAddr()\n\t\t<< i.bcc()\n\t\t<< i.vCardFile()\n\t\t<< i.transport()\n\t\t<< i.fcc()\n\t\t<< i.drafts()\n\t\t<< i.mSignature;\n}\n\nQDataStream & operator>>( QDataStream & stream, KMIdentity & i ) {\n#if 1 \/\/ why doesn't it work like for Q_UINT8 above???\n Q_UINT32 uoid;\n stream >> uoid;\n i.mUoid = uoid;\n return stream\n#else\n return stream >> (Q_UINT32)i.mUoid\n#endif\n\t\t>> i.mIdentity\n\t\t>> i.mFullName\n\t\t>> i.mOrganization\n\t\t>> i.mPgpIdentity\n\t\t>> i.mEmailAddr\n\t\t>> i.mReplyToAddr\n\t\t>> i.mBcc\n\t\t>> i.mVCardFile\n\t\t>> i.mTransport\n\t\t>> i.mFcc\n\t\t>> i.mDrafts\n\t\t>> i.mSignature;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KMIdentity::mailingAllowed() const\n{\n return !mEmailAddr.isEmpty();\n}\n\n\nvoid KMIdentity::setIsDefault( bool flag ) {\n mIsDefault = flag;\n}\n\nvoid KMIdentity::setIdentityName( const QString & name ) {\n mIdentity = name;\n}\n\nvoid KMIdentity::setFullName(const QString &str)\n{\n mFullName = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setOrganization(const QString &str)\n{\n mOrganization = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setPgpIdentity(const QCString &str)\n{\n mPgpIdentity = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setEmailAddr(const QString &str)\n{\n mEmailAddr = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setVCardFile(const QString &str)\n{\n mVCardFile = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMIdentity::fullEmailAddr(void) const\n{\n if (mFullName.isEmpty()) return mEmailAddr;\n\n const QString specials(\"()<>@,.;:[]\");\n\n QString result;\n\n \/\/ add DQUOTE's if necessary:\n bool needsQuotes=false;\n for (unsigned int i=0; i < mFullName.length(); i++) {\n if ( specials.contains( mFullName[i] ) )\n needsQuotes = true;\n else if ( mFullName[i] == '\\\\' || mFullName[i] == '\"' ) {\n needsQuotes = true;\n result += '\\\\';\n }\n result += mFullName[i];\n }\n\n if (needsQuotes) {\n result.insert(0,'\"');\n result += '\"';\n }\n\n result += \" <\" + mEmailAddr + '>';\n\n return result;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setReplyToAddr(const QString& str)\n{\n mReplyToAddr = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setSignatureFile(const QString &str)\n{\n mSignature.setUrl( str, signatureIsCommand() );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setSignatureInlineText(const QString &str )\n{\n mSignature.setText( str );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setTransport(const QString &str)\n{\n mTransport = str;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setFcc(const QString &str)\n{\n mFcc = str;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setDrafts(const QString &str)\n{\n mDrafts = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMIdentity::signatureText( bool * ok ) const\n{\n bool internalOK = false;\n QString signatureText = mSignature.withSeparator( &internalOK );\n if ( internalOK ) {\n if ( ok ) *ok=true;\n return signatureText;\n }\n\n \/\/ OK, here comes the funny part. The call to\n \/\/ Signature::withSeparator() failed, so we should probably fix the\n \/\/ cause:\n if ( ok ) *ok = false;\n return QString::null;\n\n#if 0 \/\/ ### FIXME: error handling\n if (mSignatureFile.endsWith(\"|\"))\n {\n }\n else\n {\n }\n#endif\n\n return QString::null;\n}\n<commit_msg>Fix bug 50022: kmail warning on no sent-mail folder unneeded and annoying<commit_after>\/\/ kmidentity.cpp\n\n#include \"kmidentity.h\"\n#include \"kfileio.h\"\n#include \"kmfolder.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmkernel.h\"\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kurl.h>\n#include <klocale.h>\n#include <ktempfile.h>\n#include <kmessagebox.h>\n#include <kprocess.h>\n#include <kconfig.h>\n\n#include <qstringlist.h>\n#include <qfileinfo.h>\n#include <qdatastream.h>\n\n#include <pwd.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <errno.h>\n#include <assert.h>\n\nSignature::Signature()\n : mType( Disabled )\n{\n\n}\n\nSignature::Signature( const QString & text )\n : mText( text ),\n mType( Inlined )\n{\n\n}\n\nSignature::Signature( const QString & url, bool isExecutable )\n : mUrl( url ),\n mType( isExecutable ? FromCommand : FromFile )\n{\n}\n\nbool Signature::operator==( const Signature & other ) const {\n if ( mType != other.mType ) return false;\n switch ( mType ) {\n case Inlined: return mText == other.mText;\n case FromFile:\n case FromCommand: return mUrl == other.mUrl;\n default:\n case Disabled: return true;\n }\n}\n\nQString Signature::rawText( bool * ok ) const\n{\n switch ( mType ) {\n case Disabled:\n if ( ok ) *ok = true;\n return QString::null;\n case Inlined:\n if ( ok ) *ok = true;\n return mText;\n case FromFile:\n return textFromFile( ok );\n case FromCommand:\n return textFromCommand( ok );\n };\n kdFatal( 5006 ) << \"Signature::type() returned unknown value!\" << endl;\n return QString::null; \/\/ make compiler happy\n}\n\nQString Signature::textFromCommand( bool * ok ) const\n{\n assert( mType == FromCommand );\n\n \/\/ handle pathological cases:\n if ( mUrl.isEmpty() ) {\n if ( ok ) *ok = true;\n return QString::null;\n }\n\n \/\/ create a shell process:\n#if KDE_VERSION >= 305\n KProcess proc;\n proc.setUseShell(true);\n#else\n KShellProcess proc;\n#endif\n proc << mUrl;\n\n \/\/ let the kernel collect the output for us:\n QObject::connect( &proc, SIGNAL(receivedStdout(KProcess*,char*,int)),\n\t\t kernel, SLOT(slotCollectStdOut(KProcess*,char*,int)) );\n\n \/\/ run the process:\n int rc = 0;\n if ( !proc.start( KProcess::Block, KProcess::Stdout ) )\n rc = -1;\n else\n rc = ( proc.normalExit() ) ? proc.exitStatus() : -1 ;\n\n \/\/ get output:\n QByteArray output = kernel->getCollectedStdOut( &proc );\n\n \/\/ handle errors, if any:\n if ( rc != 0 ) {\n if ( ok ) *ok = false;\n QString wmsg = i18n(\"Failed to execute signature script\\n%1:\\n%2\")\n .arg( mUrl ).arg( strerror(rc) );\n KMessageBox::error(0, wmsg);\n return QString::null;\n }\n\n \/\/ no errors:\n if ( ok ) *ok = true;\n \/\/ ### hmm, should we allow other encodings, too?\n return QString::fromLocal8Bit( output.data(), output.size() );\n}\n\nQString Signature::textFromFile( bool * ok ) const\n{\n assert( mType == FromFile );\n\n \/\/ ### FIXME: Use KIO::NetAccess to download non-local files!\n if ( !KURL(mUrl).isLocalFile() && !(QFileInfo(mUrl).isRelative()\n\t\t\t\t\t&& QFileInfo(mUrl).exists()) ) {\n kdDebug( 5006 ) << \"Signature::textFromFile: non-local URLs are unsupported\" << endl;\n if ( ok ) *ok = false;\n return QString::null;\n }\n if ( ok ) *ok = true;\n \/\/ ### hmm, should we allow other encodings, too?\n return QString::fromLocal8Bit( kFileToString( mUrl ) );\n}\n\nQString Signature::withSeparator( bool * ok ) const\n{\n bool internalOK = false;\n QString signature = rawText( &internalOK );\n if ( !internalOK ) {\n if ( ok ) *ok = false;\n return QString::null;\n }\n if ( ok ) *ok = true;\n if ( signature.isEmpty() ) return signature; \/\/ don't add a separator in this case\n if ( signature.startsWith( QString::fromLatin1(\"-- \\n\") ) ||\n signature.find( QString::fromLatin1(\"\\n-- \\n\") ) != -1 )\n \/\/ already have signature separator:\n return signature;\n else\n \/\/ need to prepend one:\n return QString::fromLatin1(\"-- \\n\") + signature;\n}\n\n\nvoid Signature::setUrl( const QString & url, bool isExecutable )\n{\n mUrl = url;\n mType = isExecutable ? FromCommand : FromFile ;\n}\n\n\/\/ config keys and values:\nstatic const char * sigTypeKey = \"Signature Type\";\nstatic const char * sigTypeInlineValue = \"inline\";\nstatic const char * sigTypeFileValue = \"file\";\nstatic const char * sigTypeCommandValue = \"command\";\nstatic const char * sigTypeDisabledValue = \"disabled\";\nstatic const char * sigTextKey = \"Inline Signature\";\nstatic const char * sigFileKey = \"Signature File\";\nstatic const char * sigCommandKey = \"Signature Command\";\n\nvoid Signature::readConfig( const KConfigBase * config )\n{\n QString sigType = config->readEntry( sigTypeKey );\n if ( sigType == sigTypeInlineValue ) {\n mType = Inlined;\n mText = config->readEntry( sigTextKey );\n } else if ( sigType == sigTypeFileValue ) {\n mType = FromFile;\n mUrl = config->readEntry( sigFileKey );\n } else if ( sigType == sigTypeCommandValue ) {\n mType = FromCommand;\n mUrl = config->readEntry( sigCommandKey );\n } else {\n mType = Disabled;\n }\n}\n\nvoid Signature::writeConfig( KConfigBase * config ) const\n{\n switch ( mType ) {\n case Inlined:\n config->writeEntry( sigTypeKey, sigTypeInlineValue );\n config->writeEntry( sigTextKey, mText );\n break;\n case FromFile:\n config->writeEntry( sigTypeKey, sigTypeFileValue );\n config->writeEntry( sigFileKey, mUrl );\n break;\n case FromCommand:\n config->writeEntry( sigTypeKey, sigTypeCommandValue );\n config->writeEntry( sigCommandKey, mUrl );\n break;\n case Disabled:\n config->writeEntry( sigTypeKey, sigTypeDisabledValue );\n default: ;\n }\n}\n\nQDataStream & operator<<( QDataStream & stream, const Signature & sig ) {\n return stream << static_cast<Q_UINT8>(sig.mType)\n\t\t<< sig.mUrl\n\t\t<< sig.mText;\n}\n\nQDataStream & operator>>( QDataStream & stream, Signature & sig ) {\n Q_UINT8 s;\n stream >> s\n >> sig.mUrl\n >> sig.mText;\n sig.mType = static_cast<Signature::Type>(s);\n return stream;\n}\n\nKMIdentity KMIdentity::null;\n\nbool KMIdentity::isNull() const {\n return mIdentity.isNull() && mFullName.isNull() && mEmailAddr.isNull() &&\n mOrganization.isNull() && mReplyToAddr.isNull() && mBcc.isNull() && \n mVCardFile.isNull() &&\n mPgpIdentity.isNull() && mFcc.isNull() && mDrafts.isNull() &&\n mTransport.isNull() && mSignature.type() == Signature::Disabled;\n}\n\nbool KMIdentity::operator==( const KMIdentity & other ) const {\n return mUoid == other.mUoid &&\n mIdentity == other.mIdentity && mFullName == other.mFullName &&\n mEmailAddr == other.mEmailAddr && mOrganization == other.mOrganization &&\n mReplyToAddr == other.mReplyToAddr && mBcc == other.mBcc &&\n mVCardFile == other.mVCardFile &&\n mPgpIdentity == other.mPgpIdentity && mFcc == other.mFcc &&\n mDrafts == other.mDrafts && mTransport == other.mTransport &&\n mSignature == other.mSignature;\n}\n\nKMIdentity::KMIdentity( const QString & id, const QString & fullName,\n\t\t\tconst QString & emailAddr, const QString & organization,\n\t\t\tconst QString & replyToAddr )\n : mUoid( 0 ), mIdentity( id ), mFullName( fullName ),\n mEmailAddr( emailAddr ), mOrganization( organization ),\n mReplyToAddr( replyToAddr ), mIsDefault( false )\n{\n\n}\n\nKMIdentity::~KMIdentity()\n{\n}\n\n\nvoid KMIdentity::readConfig( const KConfigBase * config )\n{\n mUoid = config->readUnsignedNumEntry(\"uoid\",0);\n\n mIdentity = config->readEntry(\"Identity\");\n mFullName = config->readEntry(\"Name\");\n mEmailAddr = config->readEntry(\"Email Address\");\n mVCardFile = config->readEntry(\"VCardFile\");\n mOrganization = config->readEntry(\"Organization\");\n mPgpIdentity = config->readEntry(\"Default PGP Key\").local8Bit();\n mReplyToAddr = config->readEntry(\"Reply-To Address\");\n mBcc = config->readEntry(\"Bcc\");\n mFcc = config->readEntry(\"Fcc\", \"sent-mail\");\n mDrafts = config->readEntry(\"Drafts\", \"drafts\");\n mTransport = config->readEntry(\"Transport\");\n\n mSignature.readConfig( config );\n kdDebug() << \"KMIdentity::readConfig(): UOID = \" << mUoid\n\t << \" for identity named \\\"\" << mIdentity << \"\\\"\" << endl;\n}\n\n\nvoid KMIdentity::writeConfig( KConfigBase * config ) const\n{\n config->writeEntry(\"uoid\", mUoid);\n\n config->writeEntry(\"Identity\", mIdentity);\n config->writeEntry(\"Name\", mFullName);\n config->writeEntry(\"Organization\", mOrganization);\n config->writeEntry(\"Default PGP Key\", mPgpIdentity.data());\n config->writeEntry(\"Email Address\", mEmailAddr);\n config->writeEntry(\"Reply-To Address\", mReplyToAddr);\n config->writeEntry(\"Bcc\", mBcc);\n config->writeEntry(\"VCardFile\", mVCardFile);\n config->writeEntry(\"Transport\", mTransport);\n config->writeEntry(\"Fcc\", mFcc);\n config->writeEntry(\"Drafts\", mDrafts);\n\n mSignature.writeConfig( config );\n}\n\nQDataStream & operator<<( QDataStream & stream, const KMIdentity & i ) {\n return stream << static_cast<Q_UINT32>(i.uoid())\n\t\t<< i.identityName()\n\t\t<< i.fullName()\n\t\t<< i.organization()\n\t\t<< i.pgpIdentity()\n\t\t<< i.emailAddr()\n\t\t<< i.replyToAddr()\n\t\t<< i.bcc()\n\t\t<< i.vCardFile()\n\t\t<< i.transport()\n\t\t<< i.fcc()\n\t\t<< i.drafts()\n\t\t<< i.mSignature;\n}\n\nQDataStream & operator>>( QDataStream & stream, KMIdentity & i ) {\n#if 1 \/\/ why doesn't it work like for Q_UINT8 above???\n Q_UINT32 uoid;\n stream >> uoid;\n i.mUoid = uoid;\n return stream\n#else\n return stream >> (Q_UINT32)i.mUoid\n#endif\n\t\t>> i.mIdentity\n\t\t>> i.mFullName\n\t\t>> i.mOrganization\n\t\t>> i.mPgpIdentity\n\t\t>> i.mEmailAddr\n\t\t>> i.mReplyToAddr\n\t\t>> i.mBcc\n\t\t>> i.mVCardFile\n\t\t>> i.mTransport\n\t\t>> i.mFcc\n\t\t>> i.mDrafts\n\t\t>> i.mSignature;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KMIdentity::mailingAllowed() const\n{\n return !mEmailAddr.isEmpty();\n}\n\n\nvoid KMIdentity::setIsDefault( bool flag ) {\n mIsDefault = flag;\n}\n\nvoid KMIdentity::setIdentityName( const QString & name ) {\n mIdentity = name;\n}\n\nvoid KMIdentity::setFullName(const QString &str)\n{\n mFullName = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setOrganization(const QString &str)\n{\n mOrganization = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setPgpIdentity(const QCString &str)\n{\n mPgpIdentity = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setEmailAddr(const QString &str)\n{\n mEmailAddr = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setVCardFile(const QString &str)\n{\n mVCardFile = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMIdentity::fullEmailAddr(void) const\n{\n if (mFullName.isEmpty()) return mEmailAddr;\n\n const QString specials(\"()<>@,.;:[]\");\n\n QString result;\n\n \/\/ add DQUOTE's if necessary:\n bool needsQuotes=false;\n for (unsigned int i=0; i < mFullName.length(); i++) {\n if ( specials.contains( mFullName[i] ) )\n needsQuotes = true;\n else if ( mFullName[i] == '\\\\' || mFullName[i] == '\"' ) {\n needsQuotes = true;\n result += '\\\\';\n }\n result += mFullName[i];\n }\n\n if (needsQuotes) {\n result.insert(0,'\"');\n result += '\"';\n }\n\n result += \" <\" + mEmailAddr + '>';\n\n return result;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setReplyToAddr(const QString& str)\n{\n mReplyToAddr = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setSignatureFile(const QString &str)\n{\n mSignature.setUrl( str, signatureIsCommand() );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setSignatureInlineText(const QString &str )\n{\n mSignature.setText( str );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setTransport(const QString &str)\n{\n mTransport = str;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setFcc(const QString &str)\n{\n mFcc = str;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMIdentity::setDrafts(const QString &str)\n{\n mDrafts = str;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMIdentity::signatureText( bool * ok ) const\n{\n bool internalOK = false;\n QString signatureText = mSignature.withSeparator( &internalOK );\n if ( internalOK ) {\n if ( ok ) *ok=true;\n return signatureText;\n }\n\n \/\/ OK, here comes the funny part. The call to\n \/\/ Signature::withSeparator() failed, so we should probably fix the\n \/\/ cause:\n if ( ok ) *ok = false;\n return QString::null;\n\n#if 0 \/\/ ### FIXME: error handling\n if (mSignatureFile.endsWith(\"|\"))\n {\n }\n else\n {\n }\n#endif\n\n return QString::null;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (C) Bernd Johannes Wuebben\n wuebben@math.cornell.edu\n wuebben@kde.org\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*******************************************************************\/\n\n#include \"knotesapp.h\"\n#include \"knoteconfigdlg.h\"\n\n#include <kapp.h>\n#include <kwin.h>\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kstddirs.h>\n#include <kpopupmenu.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <ksimpleconfig.h>\n\n#include <qdir.h>\n#include <qfont.h>\n\nKNotesApp::KNotesApp()\n : KSystemTray()\n{\n \/\/create the dock widget....\n setPixmap( KGlobal::iconLoader()->loadIcon( \"knotes\", KIcon::Small ) );\n\n m_note_menu = new KPopupMenu( this );\n connect( m_note_menu, SIGNAL( aboutToShow() ),\n this, SLOT( slotPrepareNoteMenu() ) );\n connect( m_note_menu, SIGNAL( activated(int) ),\n this, SLOT( slotToNote(int) ) );\n\n KPopupMenu* menu = contextMenu();\n menu->insertItem( i18n(\"New Note\"), this, SLOT(slotNewNote(int)) );\n menu->insertItem( i18n(\"Preferences...\"), this, SLOT(slotPreferences(int)) );\n menu->insertItem( i18n(\"Notes\"), m_note_menu );\n\n \/\/initialize saved notes, if none create a note...\n QString str_notedir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n QDir notedir( str_notedir );\n QStringList notes = notedir.entryList( QDir::Files, QDir::Name ); \/\/doesn't list hidden files\n\n for( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )\n {\n QString configfile = notedir.absFilePath( *i );\n KSimpleConfig* tmp = new KSimpleConfig( configfile );\n tmp->setGroup( \"General\" );\n int version = tmp->readNumEntry( \"version\", 1 );\n delete tmp;\n\n KNote* tmpnote = new KNote( configfile, version == 1 );\n\n connect( tmpnote, SIGNAL( sigRenamed(QString&, QString&) ),\n this, SLOT ( slotNoteRenamed(QString&, QString&) ) );\n connect( tmpnote, SIGNAL( sigNewNote(int) ),\n this, SLOT ( slotNewNote(int) ) );\n connect( tmpnote, SIGNAL( sigKilled(QString) ),\n this, SLOT ( slotNoteKilled(QString) ) );\n m_NoteList.insert( tmpnote->getName(), tmpnote );\n }\n\n if( m_NoteList.count() == 0 && !kapp->isRestored() )\n slotNewNote();\n}\n\n\nKNotesApp::~KNotesApp()\n{\n delete m_note_menu;\n m_NoteList.clear();\n}\n\nvoid KNotesApp::copyDefaultConfig( QString& sc_filename, QString& newname )\n{\n QString defaultsfile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n KSimpleConfig defaults( defaultsfile );\n KSimpleConfig sc( sc_filename );\n\n sc.setGroup( \"Display\" );\n defaults.setGroup( \"Display\" );\n\n uint width = defaults.readUnsignedNumEntry( \"width\", 200 );\n uint height = defaults.readUnsignedNumEntry( \"height\", 200 );\n QColor bgc = defaults.readColorEntry( \"bgcolor\", &(Qt::yellow) );\n QColor fgc = defaults.readColorEntry( \"fgcolor\", &(Qt::black) );\n\n sc.writeEntry( \"width\", width );\n sc.writeEntry( \"height\", height );\n sc.writeEntry( \"bgcolor\", bgc );\n sc.writeEntry( \"fgcolor\", fgc );\n\n sc.setGroup( \"Editor\" );\n defaults.setGroup( \"Editor\" );\n\n uint tabsize = defaults.readUnsignedNumEntry( \"tabsize\", 4 );\n bool indent = defaults.readBoolEntry( \"autoindent\", true );\n\n sc.writeEntry( \"tabsize\", tabsize );\n sc.writeEntry( \"autoindent\", indent );\n\n QFont def_font( \"helvetica\" );\n QFont currfont = defaults.readFontEntry( \"font\", &def_font );\n sc.writeEntry( \"font\", currfont );\n\n sc.setGroup( \"Actions\" );\n defaults.setGroup( \"Actions\" );\n\n QString mailstr = defaults.readEntry( \"mail\", \"kmail --msg %f\" );\n QString printstr = defaults.readEntry( \"print\", \"a2ps -P %p -1 --center-title=%t --underlay=KDE %f\" );\n\n sc.writeEntry( \"mail\", mailstr );\n sc.writeEntry( \"print\", printstr );\n\n sc.setGroup( \"General\" );\n sc.writeEntry( \"version\", 2 );\n\n sc.setGroup( \"Data\" );\n sc.writeEntry( \"name\", newname );\n\n \/\/ TODO: write default entries for the group \"WindowDisplay\"\n\n sc.sync();\n}\n\nvoid KNotesApp::slotNewNote( int \/*id*\/ )\n{\n QString datadir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n\n \/\/find a new appropriate id for the new note...\n QString thename, configfile;\n QDir appdir( datadir );\n\n for( int i = 1; ; i++ )\n {\n thename = QString( \"KNote %1\" ).arg(i);\n\n if( !appdir.exists( thename ) )\n {\n configfile = appdir.absFilePath( thename );\n break;\n }\n }\n\n copyDefaultConfig( configfile, thename );\n\n KNote* newnote = new KNote( configfile );\n connect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),\n this, SLOT( slotNoteRenamed(QString&, QString&) ) );\n connect( newnote, SIGNAL( sigNewNote(int) ),\n this, SLOT( slotNewNote(int) ) );\n connect( newnote, SIGNAL( sigKilled(QString) ),\n this, SLOT( slotNoteKilled(QString) ) );\n\n m_NoteList.insert( thename, newnote );\n}\n\nvoid KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )\n{\n KNote* tmp = m_NoteList[oldname];\n m_NoteList.insert( newname, tmp );\n m_NoteList.remove( oldname );\n}\n\nvoid KNotesApp::slotNoteKilled( QString name )\n{\n m_NoteList.remove( name );\n}\n\nvoid KNotesApp::slotPreferences( int )\n{\n \/\/launch preferences dialog...\n KNoteConfigDlg tmpconfig( \"knotesrc\", i18n(\"KNotes Defaults\") );\n tmpconfig.exec();\n}\n\nvoid KNotesApp::slotToNote( int id )\n{\n \/\/tell the WM to give this note focus\n QString name = m_note_menu->text( id );\n\n \/\/if it's already showing, we need to change to its desktop\n \/\/and give it focus\n KNote* tmpnote = m_NoteList[name];\n if( !tmpnote->isHidden() )\n {\n KWin::setActiveWindow(tmpnote->winId());\n tmpnote->setFocus();\n }\n else\n {\n \/\/if not show it on the current desktop\n tmpnote->show();\n tmpnote->slotToDesktop( KWin::currentDesktop() );\n KWin::setActiveWindow(tmpnote->winId());\n tmpnote->setFocus();\n }\n}\n\nvoid KNotesApp::slotPrepareNoteMenu()\n{\n \/\/find all notes- get their names and put them into the menu\n m_note_menu->clear();\n\n QDictIterator<KNote> it( m_NoteList );\n int id = 0;\n while( it.current() )\n {\n m_note_menu->insertItem( it.currentKey() );\n ++id;\n ++it;\n }\n}\n\nvoid KNotesApp::slotSaveNotes()\n{\n \/\/save all the notes...\n QDictIterator<KNote> it( m_NoteList );\n for( ; it.current(); ++it )\n {\n it.current()->saveData();\n it.current()->saveConfig();\n it.current()->saveDisplayConfig();\n }\n}\n\nvoid KNotesApp::mouseReleaseEvent( QMouseEvent * e)\n{\n if ( rect().contains( e->pos() ) && e->button() == LeftButton )\n {\n slotPrepareNoteMenu();\n if( m_note_menu->count() > 0 )\n m_note_menu->popup( e->globalPos() );\n return;\n }\n}\n\n\n#include \"knotesapp.moc\"\n<commit_msg>+ SetBackgroundMode(X11ParentRelative);<commit_after>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (C) Bernd Johannes Wuebben\n wuebben@math.cornell.edu\n wuebben@kde.org\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*******************************************************************\/\n\n#include \"knotesapp.h\"\n#include \"knoteconfigdlg.h\"\n\n#include <kapp.h>\n#include <kwin.h>\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kstddirs.h>\n#include <kpopupmenu.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <ksimpleconfig.h>\n\n#include <qdir.h>\n#include <qfont.h>\n\nKNotesApp::KNotesApp()\n : KSystemTray()\n{\n \/\/create the dock widget....\n setPixmap( KGlobal::iconLoader()->loadIcon( \"knotes\", KIcon::Small ) );\n\n m_note_menu = new KPopupMenu( this );\n connect( m_note_menu, SIGNAL( aboutToShow() ),\n this, SLOT( slotPrepareNoteMenu() ) );\n connect( m_note_menu, SIGNAL( activated(int) ),\n this, SLOT( slotToNote(int) ) );\n\n KPopupMenu* menu = contextMenu();\n menu->insertItem( i18n(\"New Note\"), this, SLOT(slotNewNote(int)) );\n menu->insertItem( i18n(\"Preferences...\"), this, SLOT(slotPreferences(int)) );\n menu->insertItem( i18n(\"Notes\"), m_note_menu );\n\n \/\/initialize saved notes, if none create a note...\n QString str_notedir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n QDir notedir( str_notedir );\n QStringList notes = notedir.entryList( QDir::Files, QDir::Name ); \/\/doesn't list hidden files\n\n for( QStringList::Iterator i = notes.begin(); i != notes.end(); ++i )\n {\n QString configfile = notedir.absFilePath( *i );\n KSimpleConfig* tmp = new KSimpleConfig( configfile );\n tmp->setGroup( \"General\" );\n int version = tmp->readNumEntry( \"version\", 1 );\n delete tmp;\n\n KNote* tmpnote = new KNote( configfile, version == 1 );\n\n connect( tmpnote, SIGNAL( sigRenamed(QString&, QString&) ),\n this, SLOT ( slotNoteRenamed(QString&, QString&) ) );\n connect( tmpnote, SIGNAL( sigNewNote(int) ),\n this, SLOT ( slotNewNote(int) ) );\n connect( tmpnote, SIGNAL( sigKilled(QString) ),\n this, SLOT ( slotNoteKilled(QString) ) );\n m_NoteList.insert( tmpnote->getName(), tmpnote );\n }\n\n if( m_NoteList.count() == 0 && !kapp->isRestored() )\n slotNewNote();\n\n setBackgroundMode(X11ParentRelative);\n}\n\n\nKNotesApp::~KNotesApp()\n{\n delete m_note_menu;\n m_NoteList.clear();\n}\n\nvoid KNotesApp::copyDefaultConfig( QString& sc_filename, QString& newname )\n{\n QString defaultsfile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n KSimpleConfig defaults( defaultsfile );\n KSimpleConfig sc( sc_filename );\n\n sc.setGroup( \"Display\" );\n defaults.setGroup( \"Display\" );\n\n uint width = defaults.readUnsignedNumEntry( \"width\", 200 );\n uint height = defaults.readUnsignedNumEntry( \"height\", 200 );\n QColor bgc = defaults.readColorEntry( \"bgcolor\", &(Qt::yellow) );\n QColor fgc = defaults.readColorEntry( \"fgcolor\", &(Qt::black) );\n\n sc.writeEntry( \"width\", width );\n sc.writeEntry( \"height\", height );\n sc.writeEntry( \"bgcolor\", bgc );\n sc.writeEntry( \"fgcolor\", fgc );\n\n sc.setGroup( \"Editor\" );\n defaults.setGroup( \"Editor\" );\n\n uint tabsize = defaults.readUnsignedNumEntry( \"tabsize\", 4 );\n bool indent = defaults.readBoolEntry( \"autoindent\", true );\n\n sc.writeEntry( \"tabsize\", tabsize );\n sc.writeEntry( \"autoindent\", indent );\n\n QFont def_font( \"helvetica\" );\n QFont currfont = defaults.readFontEntry( \"font\", &def_font );\n sc.writeEntry( \"font\", currfont );\n\n sc.setGroup( \"Actions\" );\n defaults.setGroup( \"Actions\" );\n\n QString mailstr = defaults.readEntry( \"mail\", \"kmail --msg %f\" );\n QString printstr = defaults.readEntry( \"print\", \"a2ps -P %p -1 --center-title=%t --underlay=KDE %f\" );\n\n sc.writeEntry( \"mail\", mailstr );\n sc.writeEntry( \"print\", printstr );\n\n sc.setGroup( \"General\" );\n sc.writeEntry( \"version\", 2 );\n\n sc.setGroup( \"Data\" );\n sc.writeEntry( \"name\", newname );\n\n \/\/ TODO: write default entries for the group \"WindowDisplay\"\n\n sc.sync();\n}\n\nvoid KNotesApp::slotNewNote( int \/*id*\/ )\n{\n QString datadir = KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" );\n\n \/\/find a new appropriate id for the new note...\n QString thename, configfile;\n QDir appdir( datadir );\n\n for( int i = 1; ; i++ )\n {\n thename = QString( \"KNote %1\" ).arg(i);\n\n if( !appdir.exists( thename ) )\n {\n configfile = appdir.absFilePath( thename );\n break;\n }\n }\n\n copyDefaultConfig( configfile, thename );\n\n KNote* newnote = new KNote( configfile );\n connect( newnote, SIGNAL( sigRenamed(QString&, QString&) ),\n this, SLOT( slotNoteRenamed(QString&, QString&) ) );\n connect( newnote, SIGNAL( sigNewNote(int) ),\n this, SLOT( slotNewNote(int) ) );\n connect( newnote, SIGNAL( sigKilled(QString) ),\n this, SLOT( slotNoteKilled(QString) ) );\n\n m_NoteList.insert( thename, newnote );\n}\n\nvoid KNotesApp::slotNoteRenamed( QString& oldname, QString& newname )\n{\n KNote* tmp = m_NoteList[oldname];\n m_NoteList.insert( newname, tmp );\n m_NoteList.remove( oldname );\n}\n\nvoid KNotesApp::slotNoteKilled( QString name )\n{\n m_NoteList.remove( name );\n}\n\nvoid KNotesApp::slotPreferences( int )\n{\n \/\/launch preferences dialog...\n KNoteConfigDlg tmpconfig( \"knotesrc\", i18n(\"KNotes Defaults\") );\n tmpconfig.exec();\n}\n\nvoid KNotesApp::slotToNote( int id )\n{\n \/\/tell the WM to give this note focus\n QString name = m_note_menu->text( id );\n\n \/\/if it's already showing, we need to change to its desktop\n \/\/and give it focus\n KNote* tmpnote = m_NoteList[name];\n if( !tmpnote->isHidden() )\n {\n KWin::setActiveWindow(tmpnote->winId());\n tmpnote->setFocus();\n }\n else\n {\n \/\/if not show it on the current desktop\n tmpnote->show();\n tmpnote->slotToDesktop( KWin::currentDesktop() );\n KWin::setActiveWindow(tmpnote->winId());\n tmpnote->setFocus();\n }\n}\n\nvoid KNotesApp::slotPrepareNoteMenu()\n{\n \/\/find all notes- get their names and put them into the menu\n m_note_menu->clear();\n\n QDictIterator<KNote> it( m_NoteList );\n int id = 0;\n while( it.current() )\n {\n m_note_menu->insertItem( it.currentKey() );\n ++id;\n ++it;\n }\n}\n\nvoid KNotesApp::slotSaveNotes()\n{\n \/\/save all the notes...\n QDictIterator<KNote> it( m_NoteList );\n for( ; it.current(); ++it )\n {\n it.current()->saveData();\n it.current()->saveConfig();\n it.current()->saveDisplayConfig();\n }\n}\n\nvoid KNotesApp::mouseReleaseEvent( QMouseEvent * e)\n{\n if ( rect().contains( e->pos() ) && e->button() == LeftButton )\n {\n slotPrepareNoteMenu();\n if( m_note_menu->count() > 0 )\n m_note_menu->popup( e->globalPos() );\n return;\n }\n}\n\n\n#include \"knotesapp.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n *\/\n\n#include \"Logic\/NodeType.h\"\n#include \"Logic\/NodeFactory.h\"\n#include \"Kommon\/Utils.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include \"CV.h\"\n\nclass GrayToRgbNodeType : public NodeType\n{\npublic:\n GrayToRgbNodeType()\n {\n addInput(\"Gray\", ENodeFlowDataType::Image);\n addOutput(\"Color\", ENodeFlowDataType::ImageRgb);\n setDescription(\"Converts gray 1-channel image to 3-channel image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageRgb();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n if(input.channels() == 3)\n {\n \/\/ no-op\n output = input;\n }\n else\n {\n if(input.data == output.data)\n output = cv::Mat();\n \/\/ Do stuff\n cv::cvtColor(input, output, CV_GRAY2BGR);\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n};\n\nclass RgbToGrayNodeType : public NodeType\n{\npublic:\n RgbToGrayNodeType()\n {\n addInput(\"Color\", ENodeFlowDataType::Image);\n addOutput(\"Gray\", ENodeFlowDataType::ImageMono);\n setDescription(\"Converts color 3-channel image to 1-channel gray image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageMono();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n if(input.channels() == 1)\n {\n \/\/no-op\n output = input;\n }\n else\n {\n if(input.data == output.data)\n output = cv::Mat();\n \/\/ Do stuff\n cv::cvtColor(input, output, CV_BGR2GRAY);\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n};\n\nclass BayerToGrayNodeType : public NodeType\n{\npublic:\n BayerToGrayNodeType()\n : _BayerCode(cvu::EBayerCode::RG)\n {\n addInput(\"Input\", ENodeFlowDataType::ImageMono);\n addOutput(\"Output\", ENodeFlowDataType::ImageMono);\n addProperty(\"Bayer format\", _BayerCode)\n .setUiHints(\"item: BG, item: GB, item: RG, item: GR\");\n setDescription(\"Performs demosaicing from Bayer pattern image to gray-scale image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImageMono();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageMono();\n\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n \n \/\/ Do stuff\n cv::cvtColor(input, output, cvu::bayerCodeGray(_BayerCode.toEnum().cast<cvu::EBayerCode>()));\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<cvu::EBayerCode> _BayerCode;\n};\n\nclass BayerToRgbNodeType : public NodeType\n{\npublic:\n BayerToRgbNodeType()\n : _redGain(1.0)\n , _greenGain(1.0)\n , _blueGain(1.0)\n , _BayerCode(cvu::EBayerCode::RG)\n {\n addInput(\"Input\", ENodeFlowDataType::ImageMono);\n addOutput(\"Output\", ENodeFlowDataType::ImageRgb);\n addProperty(\"Bayer format\", _BayerCode)\n .setUiHints(\"item: BG, item: GB, item: RG, item: GR\");\n addProperty(\"Red gain\", _redGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n addProperty(\"Green gain\", _greenGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n addProperty(\"Blue gain\", _blueGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n setDescription(\"Performs demosaicing from Bayer pattern image to RGB image.\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImageMono();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageRgb();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n \n \/\/ Do stuff\n cv::cvtColor(input, output, cvu::bayerCodeRgb(_BayerCode.toEnum().cast<cvu::EBayerCode>()));\n\n if(!fcmp(_redGain.toDouble(), 1.0)\n || !fcmp(_greenGain.toDouble(), 1.0) \n || !fcmp(_blueGain.toDouble(), 1.0))\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range) \n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n cv::Vec3b rgb = output.at<cv::Vec3b>(y, x);\n rgb[0] = cv::saturate_cast<uchar>(rgb[0] * _blueGain);\n rgb[1] = cv::saturate_cast<uchar>(rgb[1] * _greenGain);\n rgb[2] = cv::saturate_cast<uchar>(rgb[2] * _redGain);\n output.at<cv::Vec3b>(y, x) = rgb;\n }\n }\n });\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<double> _redGain;\n TypedNodeProperty<double> _greenGain;\n TypedNodeProperty<double> _blueGain;\n TypedNodeProperty<cvu::EBayerCode> _BayerCode;\n};\n\nclass ContrastAndBrightnessNodeType : public NodeType\n{\npublic:\n ContrastAndBrightnessNodeType()\n : _gain(1.0)\n , _bias(0)\n {\n addInput(\"Input\", ENodeFlowDataType::Image);\n addOutput(\"Output\", ENodeFlowDataType::Image);\n addProperty(\"Gain\", _gain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 16.0))\n .setUiHints(\"min:0.0, max:16.0\");\n addProperty(\"Bias\", _bias)\n .setValidator(make_validator<InclRangePropertyValidator<int>>(-255, 255))\n .setUiHints(\"min:-255, max:255\");\n setDescription(\"Adjusts contrast and brightness of input image.\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImage();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n \/\/ Do stuff\n if(!fcmp(_gain.toDouble(), 1.0) || _bias != 0)\n {\n output = cv::Mat(input.size(), input.type());\n\n if(input.channels() == 1)\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range)\n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n output.at<uchar>(y, x) = cv::saturate_cast<uchar>(\n _gain * input.at<uchar>(y, x) + _bias);\n }\n }\n });\n }\n else if(input.channels() == 3)\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range)\n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n cv::Vec3b rgb = input.at<cv::Vec3b>(y, x);\n rgb[0] = cv::saturate_cast<uchar>(_gain * rgb[0] + _bias);\n rgb[1] = cv::saturate_cast<uchar>(_gain * rgb[1] + _bias);\n rgb[2] = cv::saturate_cast<uchar>(_gain * rgb[2] + _bias);\n output.at<cv::Vec3b>(y, x) = rgb;\n }\n }\n });\n }\n }\n else\n {\n output = input;\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprotected:\n TypedNodeProperty<double> _gain;\n TypedNodeProperty<int> _bias;\n};\n\nREGISTER_NODE(\"Format conversion\/Contrast & brightness\", ContrastAndBrightnessNodeType)\nREGISTER_NODE(\"Format conversion\/Gray de-bayer\", BayerToGrayNodeType)\nREGISTER_NODE(\"Format conversion\/RGB de-bayer\", BayerToRgbNodeType)\nREGISTER_NODE(\"Format conversion\/Gray to RGB\", GrayToRgbNodeType)\nREGISTER_NODE(\"Format conversion\/RGB to gray\", RgbToGrayNodeType)\n<commit_msg>added channels splitter\/merger node type<commit_after>\/*\n * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n *\/\n\n#include \"Logic\/NodeType.h\"\n#include \"Logic\/NodeFactory.h\"\n#include \"Kommon\/Utils.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include \"CV.h\"\n\nclass GrayToRgbNodeType : public NodeType\n{\npublic:\n GrayToRgbNodeType()\n {\n addInput(\"Gray\", ENodeFlowDataType::Image);\n addOutput(\"Color\", ENodeFlowDataType::ImageRgb);\n setDescription(\"Converts gray 1-channel image to 3-channel image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageRgb();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n if(input.channels() == 3)\n {\n \/\/ no-op\n output = input;\n }\n else\n {\n if(input.data == output.data)\n output = cv::Mat();\n \/\/ Do stuff\n cv::cvtColor(input, output, CV_GRAY2BGR);\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n};\n\nclass RgbToGrayNodeType : public NodeType\n{\npublic:\n RgbToGrayNodeType()\n {\n addInput(\"Color\", ENodeFlowDataType::Image);\n addOutput(\"Gray\", ENodeFlowDataType::ImageMono);\n setDescription(\"Converts color 3-channel image to 1-channel gray image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageMono();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n if(input.channels() == 1)\n {\n \/\/no-op\n output = input;\n }\n else\n {\n if(input.data == output.data)\n output = cv::Mat();\n \/\/ Do stuff\n cv::cvtColor(input, output, CV_BGR2GRAY);\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n};\n\nclass BayerToGrayNodeType : public NodeType\n{\npublic:\n BayerToGrayNodeType()\n : _BayerCode(cvu::EBayerCode::RG)\n {\n addInput(\"Input\", ENodeFlowDataType::ImageMono);\n addOutput(\"Output\", ENodeFlowDataType::ImageMono);\n addProperty(\"Bayer format\", _BayerCode)\n .setUiHints(\"item: BG, item: GB, item: RG, item: GR\");\n setDescription(\"Performs demosaicing from Bayer pattern image to gray-scale image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImageMono();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageMono();\n\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n \n \/\/ Do stuff\n cv::cvtColor(input, output, cvu::bayerCodeGray(_BayerCode.toEnum().cast<cvu::EBayerCode>()));\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<cvu::EBayerCode> _BayerCode;\n};\n\nclass BayerToRgbNodeType : public NodeType\n{\npublic:\n BayerToRgbNodeType()\n : _redGain(1.0)\n , _greenGain(1.0)\n , _blueGain(1.0)\n , _BayerCode(cvu::EBayerCode::RG)\n {\n addInput(\"Input\", ENodeFlowDataType::ImageMono);\n addOutput(\"Output\", ENodeFlowDataType::ImageRgb);\n addProperty(\"Bayer format\", _BayerCode)\n .setUiHints(\"item: BG, item: GB, item: RG, item: GR\");\n addProperty(\"Red gain\", _redGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n addProperty(\"Green gain\", _greenGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n addProperty(\"Blue gain\", _blueGain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 4.0))\n .setUiHints(\"min:0.0, max:4.0, step:0.001\");\n setDescription(\"Performs demosaicing from Bayer pattern image to RGB image.\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImageMono();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImageRgb();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n \n \/\/ Do stuff\n cv::cvtColor(input, output, cvu::bayerCodeRgb(_BayerCode.toEnum().cast<cvu::EBayerCode>()));\n\n if(!fcmp(_redGain.toDouble(), 1.0)\n || !fcmp(_greenGain.toDouble(), 1.0) \n || !fcmp(_blueGain.toDouble(), 1.0))\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range) \n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n cv::Vec3b rgb = output.at<cv::Vec3b>(y, x);\n rgb[0] = cv::saturate_cast<uchar>(rgb[0] * _blueGain);\n rgb[1] = cv::saturate_cast<uchar>(rgb[1] * _greenGain);\n rgb[2] = cv::saturate_cast<uchar>(rgb[2] * _redGain);\n output.at<cv::Vec3b>(y, x) = rgb;\n }\n }\n });\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<double> _redGain;\n TypedNodeProperty<double> _greenGain;\n TypedNodeProperty<double> _blueGain;\n TypedNodeProperty<cvu::EBayerCode> _BayerCode;\n};\n\nclass ContrastAndBrightnessNodeType : public NodeType\n{\npublic:\n ContrastAndBrightnessNodeType()\n : _gain(1.0)\n , _bias(0)\n {\n addInput(\"Input\", ENodeFlowDataType::Image);\n addOutput(\"Output\", ENodeFlowDataType::Image);\n addProperty(\"Gain\", _gain)\n .setValidator(make_validator<InclRangePropertyValidator<double>>(0.0, 16.0))\n .setUiHints(\"min:0.0, max:16.0\");\n addProperty(\"Bias\", _bias)\n .setValidator(make_validator<InclRangePropertyValidator<int>>(-255, 255))\n .setUiHints(\"min:-255, max:255\");\n setDescription(\"Adjusts contrast and brightness of input image.\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImage();\n \/\/ Acquire output sockets\n cv::Mat& output = writer.acquireSocket(0).getImage();\n\n \/\/ Validate inputs\n if(input.empty())\n return ExecutionStatus(EStatus::Ok);\n\n \/\/ Do stuff\n if(!fcmp(_gain.toDouble(), 1.0) || _bias != 0)\n {\n output = cv::Mat(input.size(), input.type());\n\n if(input.channels() == 1)\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range)\n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n output.at<uchar>(y, x) = cv::saturate_cast<uchar>(\n _gain * input.at<uchar>(y, x) + _bias);\n }\n }\n });\n }\n else if(input.channels() == 3)\n {\n cvu::parallel_for(cv::Range(0, output.rows), [&](const cv::Range& range)\n {\n for(int y = range.start; y < range.end; ++y)\n {\n for(int x = 0; x < output.cols; ++x)\n {\n cv::Vec3b rgb = input.at<cv::Vec3b>(y, x);\n rgb[0] = cv::saturate_cast<uchar>(_gain * rgb[0] + _bias);\n rgb[1] = cv::saturate_cast<uchar>(_gain * rgb[1] + _bias);\n rgb[2] = cv::saturate_cast<uchar>(_gain * rgb[2] + _bias);\n output.at<cv::Vec3b>(y, x) = rgb;\n }\n }\n });\n }\n }\n else\n {\n output = input;\n }\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprotected:\n TypedNodeProperty<double> _gain;\n TypedNodeProperty<int> _bias;\n};\n\nenum class EColourSpace\n{\n Rgb,\n Xyz,\n YCrCb,\n Hsv,\n Lab,\n Hls,\n Luv\n};\n\nclass ChannelSplitterNodeType : public NodeType\n{\npublic:\n ChannelSplitterNodeType()\n : _colourSpace(EColourSpace::Rgb)\n {\n addInput(\"Image\", ENodeFlowDataType::ImageRgb);\n addOutput(\"1st\", ENodeFlowDataType::ImageMono);\n addOutput(\"2nd\", ENodeFlowDataType::ImageMono);\n addOutput(\"3rd\", ENodeFlowDataType::ImageMono);\n addProperty(\"Colour space\", _colourSpace)\n .setUiHints(\"item: RGB, item: CIE 1931 XYZ, item: YCrCb, \"\n \"item: HSV, item: CIELAB, item: HLS, item: CIELUV\");\n setDescription(\"Splits colour image into three separate images\/channels\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& input = reader.readSocket(0).getImageRgb();\n \/\/ Acquire output sockets\n cv::Mat& first = writer.acquireSocket(0).getImageMono();\n cv::Mat& second = writer.acquireSocket(1).getImageMono();\n cv::Mat& third = writer.acquireSocket(2).getImageMono();\n cv::Mat tmp;\n int dstCode = -1;\n\n switch (_colourSpace.cast_value<Enum>().cast<EColourSpace>())\n {\n case EColourSpace::Rgb:\n dstCode = -1;\n break;\n case EColourSpace::Xyz:\n dstCode = CV_BGR2XYZ;\n break;\n case EColourSpace::YCrCb:\n dstCode = CV_BGR2YCrCb;\n break;\n case EColourSpace::Hsv:\n dstCode = CV_BGR2HSV;\n break;\n case EColourSpace::Lab:\n dstCode = CV_BGR2Lab;\n break;\n case EColourSpace::Hls:\n dstCode = CV_BGR2HLS;\n break;\n case EColourSpace::Luv:\n dstCode = CV_BGR2Luv;\n break;\n default:\n return ExecutionStatus(EStatus::Error, \"Wrong color space value\");\n }\n\n if (dstCode > 0)\n cv::cvtColor(input, tmp, dstCode);\n else\n tmp = input;\n\n std::vector<cv::Mat> channels;\n cv::split(tmp, channels);\n\n first = channels.at(0);\n second = channels.at(1);\n third = channels.at(2);\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<EColourSpace> _colourSpace;\n};\n\nclass ChannelMergerNodeType : public NodeType\n{\npublic:\n ChannelMergerNodeType()\n : _colourSpace(EColourSpace::Rgb)\n {\n addInput(\"1st\", ENodeFlowDataType::ImageMono);\n addInput(\"2nd\", ENodeFlowDataType::ImageMono);\n addInput(\"3rd\", ENodeFlowDataType::ImageMono);\n addOutput(\"Image\", ENodeFlowDataType::ImageRgb);\n addProperty(\"Colour space\", _colourSpace)\n .setUiHints(\"item: RGB, item: CIE 1931 XYZ, item: YCrCb, \"\n \"item: HSV, item: CIELAB, item: HLS, item: CIELUV\");\n setDescription(\"Merges three separate images\/channels into a final colour image\");\n }\n\n ExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n {\n \/\/ Read input sockets\n const cv::Mat& first = reader.readSocket(0).getImageMono();\n const cv::Mat& second = reader.readSocket(1).getImageMono();\n const cv::Mat& third = reader.readSocket(2).getImageMono();\n \/\/ Acquire output sockets\n cv::Mat& dst = writer.acquireSocket(0).getImageRgb();\n\n \/\/ basic check\n if (first.size != second.size || first.size != third.size)\n return ExecutionStatus(EStatus::Error, \"Channels have different sizes\");\n\n cv::Mat tmp;\n std::vector<cv::Mat> channels = {first, second, third};\n cv::merge(channels, tmp);\n\n int dstCode = -1;\n\n switch (_colourSpace.cast_value<Enum>().cast<EColourSpace>())\n {\n case EColourSpace::Rgb:\n dstCode = -1;\n break;\n case EColourSpace::Xyz:\n dstCode = CV_XYZ2BGR;\n break;\n case EColourSpace::YCrCb:\n dstCode = CV_YCrCb2BGR;\n break;\n case EColourSpace::Hsv:\n dstCode = CV_HSV2BGR;\n break;\n case EColourSpace::Lab:\n dstCode = CV_Lab2BGR;\n break;\n case EColourSpace::Hls:\n dstCode = CV_HLS2BGR;\n break;\n case EColourSpace::Luv:\n dstCode = CV_Luv2BGR;\n break;\n default:\n return ExecutionStatus(EStatus::Error, \"Wrong color space value\");\n }\n\n if (dstCode > 0)\n cv::cvtColor(tmp, dst, dstCode);\n else\n dst = tmp;\n\n return ExecutionStatus(EStatus::Ok);\n }\n\nprivate:\n TypedNodeProperty<EColourSpace> _colourSpace;\n};\n\nREGISTER_NODE(\"Format conversion\/Channel merger\", ChannelMergerNodeType);\nREGISTER_NODE(\"Format conversion\/Channel splitter\", ChannelSplitterNodeType);\nREGISTER_NODE(\"Format conversion\/Contrast & brightness\", ContrastAndBrightnessNodeType)\nREGISTER_NODE(\"Format conversion\/Gray de-bayer\", BayerToGrayNodeType)\nREGISTER_NODE(\"Format conversion\/RGB de-bayer\", BayerToRgbNodeType)\nREGISTER_NODE(\"Format conversion\/Gray to RGB\", GrayToRgbNodeType)\nREGISTER_NODE(\"Format conversion\/RGB to gray\", RgbToGrayNodeType)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016-2016, Roland Bock\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"compare.h\"\n#include \"Sample.h\"\n#include <sqlpp11\/sqlpp11.h>\n\n#include <iostream>\n\nSQLPP_ALIAS_PROVIDER(cheese);\n\nint As(int, char* [])\n{\n const auto foo = test::TabFoo{};\n const auto bar = test::TabBar{};\n\n compare(__LINE__, foo.omega.as(cheese), \"tab_foo.omega AS cheese\");\n compare(__LINE__, (foo.omega + 17).as(cheese), \"(tab_foo.omega+17) AS cheese\");\n compare(__LINE__, (foo.omega - 17).as(cheese), \"(tab_foo.omega-17) AS cheese\");\n compare(__LINE__, (foo.omega - uint32_t(17)).as(cheese), \"(tab_foo.omega-17) AS cheese\");\n compare(__LINE__, (foo.omega - bar.alpha).as(cheese), \"(tab_foo.omega-tab_bar.alpha) AS cheese\");\n compare(__LINE__, (count(foo.omega) - bar.alpha).as(cheese), \"(COUNT(tab_foo.omega)-tab_bar.alpha) AS cheese\");\n compare(__LINE__, (count(foo.omega) - uint32_t(17)).as(cheese), \"(COUNT(tab_foo.omega)-17) AS cheese\");\n\n \/\/ Auto alias\n compare(__LINE__, select(max(bar.alpha)), \"SELECT MAX(tab_bar.alpha) AS max_\");\n compare(__LINE__, select(max(bar.alpha).as(cheese)), \"SELECT MAX(tab_bar.alpha) AS cheese\");\n compare(__LINE__, select(max(bar.alpha)).from(bar).unconditionally().as(cheese),\n \"(SELECT MAX(tab_bar.alpha) AS max_ FROM tab_bar) AS cheese\");\n compare(__LINE__, select(max(bar.alpha)).from(bar).unconditionally().as(cheese).max, \"cheese.max_\");\n\n return 0;\n}\n<commit_msg>Remove superfluous semicolon<commit_after>\/*\n * Copyright (c) 2016-2016, Roland Bock\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"compare.h\"\n#include \"Sample.h\"\n#include <sqlpp11\/sqlpp11.h>\n\n#include <iostream>\n\nSQLPP_ALIAS_PROVIDER(cheese)\n\nint As(int, char* [])\n{\n const auto foo = test::TabFoo{};\n const auto bar = test::TabBar{};\n\n compare(__LINE__, foo.omega.as(cheese), \"tab_foo.omega AS cheese\");\n compare(__LINE__, (foo.omega + 17).as(cheese), \"(tab_foo.omega+17) AS cheese\");\n compare(__LINE__, (foo.omega - 17).as(cheese), \"(tab_foo.omega-17) AS cheese\");\n compare(__LINE__, (foo.omega - uint32_t(17)).as(cheese), \"(tab_foo.omega-17) AS cheese\");\n compare(__LINE__, (foo.omega - bar.alpha).as(cheese), \"(tab_foo.omega-tab_bar.alpha) AS cheese\");\n compare(__LINE__, (count(foo.omega) - bar.alpha).as(cheese), \"(COUNT(tab_foo.omega)-tab_bar.alpha) AS cheese\");\n compare(__LINE__, (count(foo.omega) - uint32_t(17)).as(cheese), \"(COUNT(tab_foo.omega)-17) AS cheese\");\n\n \/\/ Auto alias\n compare(__LINE__, select(max(bar.alpha)), \"SELECT MAX(tab_bar.alpha) AS max_\");\n compare(__LINE__, select(max(bar.alpha).as(cheese)), \"SELECT MAX(tab_bar.alpha) AS cheese\");\n compare(__LINE__, select(max(bar.alpha)).from(bar).unconditionally().as(cheese),\n \"(SELECT MAX(tab_bar.alpha) AS max_ FROM tab_bar) AS cheese\");\n compare(__LINE__, select(max(bar.alpha)).from(bar).unconditionally().as(cheese).max, \"cheese.max_\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* featureSelector.C\n * \n * Copyright (C) 2009 Marcel Schumann\n * \n * This file is part of QuEasy -- A Toolbox for Automated QSAR Model\n * Construction and Validation.\n * QuEasy is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * QuEasy is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fstream>\n#include <BALL\/QSAR\/registry.h>\n#include <BALL\/QSAR\/featureSelection.h>\n#include <BALL\/QSAR\/configIO.h>\n\nusing namespace BALL::QSAR;\nusing namespace BALL;\n\nvoid startFeatureSelection(std::ifstream& in, QSARData* q, String* data_filename)\n{\n\tFeatureSelectionConfiguration conf = ConfigIO::readFeatureSelectionConfiguration(&in);\n\t\t\n\tif(conf.done) return; \/\/ stop processing this section\n\t\t\n\tbool created_data_object=0;\n\tif(q==NULL || data_filename==NULL || conf.data_file!=*data_filename)\n\t{\n\t\tif(q==NULL)\n\t\t{\n\t\t\tq = new QSARData;\n\t\t\tcreated_data_object=1;\n\t\t}\n\t\tq->readFromFile(conf.data_file);\n\t\tif(data_filename) *data_filename = conf.data_file;\n\t}\n\telse\n\t{\n\t\tstd::cout<<\"[FeatureSelector debug-info:] QSARData object for file \"<<conf.data_file<<\" already in memory; not reading it again.\"<<std::endl;\n\t}\n\t\n\tRegistry reg;\n\tModel* m;\n\tString model_type;\t\n\t\t\n\tstd::ifstream model_input(conf.model.c_str()); \/\/ read model-abbreviation\n\tif(!model_input)\n\t{\n\t\tstd::cout<<\"Error: Model-file '\"<<conf.model<<\"' does not exist!!\"<<std::endl;\n\t\treturn;\n\t}\n\tstd::getline(model_input,model_type);\n\tstd::getline(model_input,model_type);\n\tmodel_type = model_type.getField(0,\"\\t\");\n\tmodel_input.close();\n\t\t\n\tRegistryEntry* entry = reg.getEntry(model_type);\n\tbool regression = entry->regression;\n\t\t\t\t\n\tif(!entry->kernel)\n\t{\n\t\tm = (*entry->create)(*q);\n\t}\n\telse\n\t{\t\n\t\t\/\/ parameters irrelevant; will be overwritten by those read from file\n\t\tm = (*entry->createKernel1)(*q,1,1, -1);\n\t}\n\t\t\t\n\t\n\tstd::cout<<\" using \"<<conf.statistic_name<<\" to assess qualitiy of the model ... \"<<std::endl;\n\tm->model_val->selectStat(conf.statistic);\n\t\t\n\tm->readFromFile(conf.model.c_str());\n\tFeatureSelection fs(*m);\n\tif(conf.quality_increase_cutoff!=-1)\n\t{\n\t\tfs.setQualityIncreaseCutoff(conf.quality_increase_cutoff);\n\t}\t\t\n\tif(conf.remove_correlated || conf.feat_type==0)\n\t{\n\t\tfs.removeHighlyCorrelatedFeatures(conf.cor_threshold);\n\t}\t\t\n\tif(conf.feat_type==1)\n\t{\n\t\tfs.forwardSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==2)\n\t{\n\t\tfs.backwardSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==3)\n\t{\n\t\tfs.stepwiseSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==4)\n\t{\n\t\tfs.removeLowResponseCorrelation(conf.cor_threshold);\n\t}\n\telse if(conf.feat_type==6)\n\t{\n\t\tfs.twinScan(conf.k_fold,conf.opt);\n\t}\n\tif(conf.opt_model_after_fs)\n\t{\n\t\tm->optimizeParameters(conf.opt_k_fold);\n\t}\n\tKernelModel* km = dynamic_cast<KernelModel*>(m);\n\tif(km && conf.opt_kernel_after_fs)\n\t{\n\t\t\/\/\/ search locally around current kernel parameters\n\t\ttry\n\t\t{\n\t\t\t\/\/ specifing start-values for grid search now obsolete; grid search will automatically search locally around current kernel parameter(s)\n\t\t\tkm->kernel->gridSearch(conf.grid_search_stepwidth, conf.grid_search_steps,conf.grid_search_recursions,conf.opt_k_fold,conf.opt\/*,start_par1,start_par2*\/);\n\t\t}\n\t\tcatch(BALL::Exception::GeneralException e)\n\t\t{\n\t\t\tstd::cout<<e.getName()<<\" : \"<<e.getMessage()<<std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\t\t\n\tm->readTrainingData();\n\tm->train(); \n\tm->saveToFile(conf.output);\n\t\n\tif(created_data_object) delete q;\n\tdelete m;\n}\n\n\n#ifndef EXT_MAIN\nint main(int argc, char* argv[])\n{ \n\tif(argc<2)\n\t{\n\t\tstd::cout<<\"Please specify configuration file!\"<<std::endl;\n\t\treturn 0;\n\t}\n\t\n\tstd::ifstream in(argv[1]);\n\tif(!in)\n\t{\n\t\tstd::cout<<\"Configuration file '\"<<argv[1]<<\"' not found!\"<<std::endl;\n\t\treturn 0;\n\t}\n\tString line;\n\t\n\tfor(int i=0;!in.eof();i++) \/\/ read ALL FeatureSelector sections\n\t{\n\t\tfor(int j=0;!in.eof();j++) \/\/ skip everthing until the beginning of the next FeatureSelector-section\n\t\t{\n\t\t\tstd::getline(in,line);\n\t\t\tif(!line.hasPrefix(\"[FeatureSelector]\")) continue;\n\t\t\telse break;\n\t\t}\n\t\tif(!line.hasPrefix(\"[FeatureSelector]\")) break; \/\/ there are no (more) FS-sections!\n\t\tConfigIO::putbackLine(&in,line);\n\t\t\n\t\tstartFeatureSelection(in, NULL, NULL);\n\t}\n}\n#endif\n<commit_msg>Clarified licence<commit_after>#include <fstream>\n#include <BALL\/QSAR\/registry.h>\n#include <BALL\/QSAR\/featureSelection.h>\n#include <BALL\/QSAR\/configIO.h>\n\nusing namespace BALL::QSAR;\nusing namespace BALL;\n\nvoid startFeatureSelection(std::ifstream& in, QSARData* q, String* data_filename)\n{\n\tFeatureSelectionConfiguration conf = ConfigIO::readFeatureSelectionConfiguration(&in);\n\t\t\n\tif(conf.done) return; \/\/ stop processing this section\n\t\t\n\tbool created_data_object=0;\n\tif(q==NULL || data_filename==NULL || conf.data_file!=*data_filename)\n\t{\n\t\tif(q==NULL)\n\t\t{\n\t\t\tq = new QSARData;\n\t\t\tcreated_data_object=1;\n\t\t}\n\t\tq->readFromFile(conf.data_file);\n\t\tif(data_filename) *data_filename = conf.data_file;\n\t}\n\telse\n\t{\n\t\tstd::cout<<\"[FeatureSelector debug-info:] QSARData object for file \"<<conf.data_file<<\" already in memory; not reading it again.\"<<std::endl;\n\t}\n\t\n\tRegistry reg;\n\tModel* m;\n\tString model_type;\t\n\t\t\n\tstd::ifstream model_input(conf.model.c_str()); \/\/ read model-abbreviation\n\tif(!model_input)\n\t{\n\t\tstd::cout<<\"Error: Model-file '\"<<conf.model<<\"' does not exist!!\"<<std::endl;\n\t\treturn;\n\t}\n\tstd::getline(model_input,model_type);\n\tstd::getline(model_input,model_type);\n\tmodel_type = model_type.getField(0,\"\\t\");\n\tmodel_input.close();\n\t\t\n\tRegistryEntry* entry = reg.getEntry(model_type);\n\tbool regression = entry->regression;\n\t\t\t\t\n\tif(!entry->kernel)\n\t{\n\t\tm = (*entry->create)(*q);\n\t}\n\telse\n\t{\t\n\t\t\/\/ parameters irrelevant; will be overwritten by those read from file\n\t\tm = (*entry->createKernel1)(*q,1,1, -1);\n\t}\n\t\t\t\n\t\n\tstd::cout<<\" using \"<<conf.statistic_name<<\" to assess qualitiy of the model ... \"<<std::endl;\n\tm->model_val->selectStat(conf.statistic);\n\t\t\n\tm->readFromFile(conf.model.c_str());\n\tFeatureSelection fs(*m);\n\tif(conf.quality_increase_cutoff!=-1)\n\t{\n\t\tfs.setQualityIncreaseCutoff(conf.quality_increase_cutoff);\n\t}\t\t\n\tif(conf.remove_correlated || conf.feat_type==0)\n\t{\n\t\tfs.removeHighlyCorrelatedFeatures(conf.cor_threshold);\n\t}\t\t\n\tif(conf.feat_type==1)\n\t{\n\t\tfs.forwardSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==2)\n\t{\n\t\tfs.backwardSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==3)\n\t{\n\t\tfs.stepwiseSelection(conf.k_fold,conf.opt);\n\t}\n\telse if(conf.feat_type==4)\n\t{\n\t\tfs.removeLowResponseCorrelation(conf.cor_threshold);\n\t}\n\telse if(conf.feat_type==6)\n\t{\n\t\tfs.twinScan(conf.k_fold,conf.opt);\n\t}\n\tif(conf.opt_model_after_fs)\n\t{\n\t\tm->optimizeParameters(conf.opt_k_fold);\n\t}\n\tKernelModel* km = dynamic_cast<KernelModel*>(m);\n\tif(km && conf.opt_kernel_after_fs)\n\t{\n\t\t\/\/\/ search locally around current kernel parameters\n\t\ttry\n\t\t{\n\t\t\t\/\/ specifing start-values for grid search now obsolete; grid search will automatically search locally around current kernel parameter(s)\n\t\t\tkm->kernel->gridSearch(conf.grid_search_stepwidth, conf.grid_search_steps,conf.grid_search_recursions,conf.opt_k_fold,conf.opt\/*,start_par1,start_par2*\/);\n\t\t}\n\t\tcatch(BALL::Exception::GeneralException e)\n\t\t{\n\t\t\tstd::cout<<e.getName()<<\" : \"<<e.getMessage()<<std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\t\t\n\tm->readTrainingData();\n\tm->train(); \n\tm->saveToFile(conf.output);\n\t\n\tif(created_data_object) delete q;\n\tdelete m;\n}\n\n\n#ifndef EXT_MAIN\nint main(int argc, char* argv[])\n{ \n\tif(argc<2)\n\t{\n\t\tstd::cout<<\"Please specify configuration file!\"<<std::endl;\n\t\treturn 0;\n\t}\n\t\n\tstd::ifstream in(argv[1]);\n\tif(!in)\n\t{\n\t\tstd::cout<<\"Configuration file '\"<<argv[1]<<\"' not found!\"<<std::endl;\n\t\treturn 0;\n\t}\n\tString line;\n\t\n\tfor(int i=0;!in.eof();i++) \/\/ read ALL FeatureSelector sections\n\t{\n\t\tfor(int j=0;!in.eof();j++) \/\/ skip everthing until the beginning of the next FeatureSelector-section\n\t\t{\n\t\t\tstd::getline(in,line);\n\t\t\tif(!line.hasPrefix(\"[FeatureSelector]\")) continue;\n\t\t\telse break;\n\t\t}\n\t\tif(!line.hasPrefix(\"[FeatureSelector]\")) break; \/\/ there are no (more) FS-sections!\n\t\tConfigIO::putbackLine(&in,line);\n\t\t\n\t\tstartFeatureSelection(in, NULL, NULL);\n\t}\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef GNR_DBG_HPP\n# define GNR_DBG_HPP\n# pragma once\n\n#include <cstdlib> \/\/ abort\n#include <iostream>\n\nnamespace gnr\n{\n\n#ifdef NDEBUG\nstatic struct\n{\n template <typename U>\n auto& operator<<(U&&) const noexcept\n {\n return *this;\n }\n} const dbg;\n\n#else\nstatic constexpr auto& dbg(std::cout);\n#endif \/\/ NDEBUG\n\n[[noreturn]] inline std::ostream& abort(std::ostream& os)\n{\n os << std::endl;\n std::abort();\n}\n\n}\n\n#endif \/\/ GNR_DBG_HPP\n<commit_msg>some fixes<commit_after>#ifndef GNR_DBG_HPP\n# define GNR_DBG_HPP\n# pragma once\n\n#include <cstdlib> \/\/ abort\n#include <iostream>\n\nnamespace gnr\n{\n\n#ifdef NDEBUG\nstatic struct\n{\n template <typename U>\n auto& operator<<(U&&) const noexcept\n {\n return *this;\n }\n} const dbg;\n\n#else\nstatic constexpr auto& dbg(std::cout);\n#endif \/\/ NDEBUG\n\n[[noreturn]] inline std::ostream& abort(std::ostream& os) noexcept\n{\n std::abort();\n}\n\n}\n\n#endif \/\/ GNR_DBG_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2022 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"smart_card_connector_app\/src\/application.h\"\n\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <queue>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include <winscard.h>\n\n#include <google_smart_card_common\/messaging\/typed_message_router.h>\n#include <google_smart_card_common\/multi_string.h>\n#include <google_smart_card_common\/unique_ptr_utils.h>\n#include <google_smart_card_common\/value.h>\n\n#include \"common\/cpp\/src\/public\/testing_global_context.h\"\n#include \"smart_card_connector_app\/src\/testing_smart_card_simulation.h\"\n\n#ifdef __native_client__\n#include <google_smart_card_common\/nacl_io_utils.h>\n#endif \/\/ __native_client__\n\nusing testing::ElementsAre;\n\nnamespace google_smart_card {\n\nnamespace {\n\n\/\/ Records reader_* messages sent to JS and allows to inspect them in tests.\nclass ReaderNotificationObserver final {\n public:\n void Init(TestingGlobalContext& global_context) {\n for (const auto* event_name : {\"reader_init_add\", \"reader_finish_add\"}) {\n global_context.RegisterMessageHandler(\n event_name,\n std::bind(&ReaderNotificationObserver::OnMessageToJs, this,\n event_name, \/*request_payload=*\/std::placeholders::_1,\n \/*request_id=*\/std::placeholders::_2));\n }\n }\n\n \/\/ Extracts the next recorded notification, in the format \"<event>:<reader>\"\n \/\/ (for simplifying test assertions).\n std::string Pop() {\n std::unique_lock<std::mutex> lock(mutex_);\n GOOGLE_SMART_CARD_CHECK(!recorded_notifications_.empty());\n std::string next = std::move(recorded_notifications_.front());\n recorded_notifications_.pop();\n return next;\n }\n\n private:\n void OnMessageToJs(const std::string& event_name,\n Value message_data,\n optional<RequestId> \/*request_id*\/) {\n std::string notification =\n event_name + \":\" +\n message_data.GetDictionaryItem(\"readerName\")->GetString();\n\n std::unique_lock<std::mutex> lock(mutex_);\n recorded_notifications_.push(notification);\n }\n\n std::mutex mutex_;\n std::queue<std::string> recorded_notifications_;\n};\n\n} \/\/ namespace\n\nclass SmartCardConnectorApplicationTest : public ::testing::Test {\n protected:\n SmartCardConnectorApplicationTest() {\n#ifdef __native_client__\n \/\/ Make resource files accessible.\n MountNaclIoFolders();\n#endif \/\/ __native_client__\n SetUpUsbSimulation();\n reader_notification_observer_.Init(global_context_);\n }\n\n ~SmartCardConnectorApplicationTest() { application_->ShutDownAndWait(); }\n\n void StartApplication() {\n \/\/ Set up the expectation on the first C++-to-JS message.\n auto pcsc_lite_ready_message_waiter = global_context_.CreateMessageWaiter(\n \/*awaited_message_type=*\/\"pcsc_lite_ready\");\n \/\/ Set up the expectation for the application to run the provided callback.\n ::testing::MockFunction<void()> background_initialization_callback;\n EXPECT_CALL(background_initialization_callback, Call());\n \/\/ Create the application, which spawns the background initialization\n \/\/ thread.\n application_ = MakeUnique<Application>(\n &global_context_, &typed_message_router_,\n background_initialization_callback.AsStdFunction());\n \/\/ Wait until the daemon's background thread completes the initialization\n \/\/ and notifies the JS side.\n pcsc_lite_ready_message_waiter->Wait();\n EXPECT_TRUE(pcsc_lite_ready_message_waiter->value().StrictlyEquals(\n Value(Value::Type::kDictionary)));\n }\n\n \/\/ Enables the specified fake USB devices.\n void SetUsbDevices(\n const std::vector<TestingSmartCardSimulation::Device>& devices) {\n smart_card_simulation_.SetDevices(devices);\n }\n\n ReaderNotificationObserver& reader_notification_observer() {\n return reader_notification_observer_;\n }\n\n private:\n void SetUpUsbSimulation() {\n global_context_.RegisterRequestHandler(\n TestingSmartCardSimulation::kRequesterName,\n std::bind(&TestingSmartCardSimulation::OnRequestToJs,\n &smart_card_simulation_,\n \/*request_payload=*\/std::placeholders::_1,\n \/*request_id=*\/std::placeholders::_2));\n }\n\n TypedMessageRouter typed_message_router_;\n TestingSmartCardSimulation smart_card_simulation_{&typed_message_router_};\n ReaderNotificationObserver reader_notification_observer_;\n TestingGlobalContext global_context_{&typed_message_router_};\n std::unique_ptr<Application> application_;\n};\n\nTEST_F(SmartCardConnectorApplicationTest, SmokeTest) {\n StartApplication();\n}\n\n\/\/ Test a PC\/SC-Lite context can be established and freed, via direct C function\n\/\/ calls `SCardEstablishContext()` and `SCardReleaseContext()`.\n\/\/ This is an extended version of the \"smoke test\" as it verifies the daemon\n\/\/ successfully started and replies to calls sent over (fake) sockets.\nTEST_F(SmartCardConnectorApplicationTest, InternalApiContextEstablishing) {\n \/\/ Arrange:\n\n StartApplication();\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n EXPECT_NE(scard_context, 0);\n\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n}\n\n\/\/ Test a single reader is successfully initialized by PC\/SC-Lite and is\n\/\/ returned via the direct C function call `SCardListReaders()`.\nTEST_F(SmartCardConnectorApplicationTest, InternalApiSingleDeviceListing) {\n \/\/ Arrange:\n\n TestingSmartCardSimulation::Device device;\n device.id = 123;\n device.type = TestingSmartCardSimulation::DeviceType::kGemaltoPcTwinReader;\n SetUsbDevices({device});\n\n StartApplication();\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_init_add:Gemalto PC Twin Reader\");\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_finish_add:Gemalto PC Twin Reader\");\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n\n DWORD readers_size = 0;\n EXPECT_EQ(SCardListReaders(scard_context, \/*mszGroups=*\/nullptr,\n \/*mszReaders=*\/nullptr, &readers_size),\n SCARD_S_SUCCESS);\n EXPECT_GT(readers_size, 0U);\n\n std::string readers_multistring;\n readers_multistring.resize(readers_size);\n EXPECT_EQ(SCardListReaders(scard_context, \/*mszGroups=*\/nullptr,\n &readers_multistring[0], &readers_size),\n SCARD_S_SUCCESS);\n EXPECT_EQ(readers_size, readers_multistring.size());\n\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n\n \/\/ Assert:\n\n EXPECT_THAT(ExtractMultiStringElements(readers_multistring),\n ElementsAre(\"Gemalto PC Twin Reader 00 00\"));\n}\n\n} \/\/ namespace google_smart_card\n<commit_msg>Tests connector adding\/removing reader (#638)<commit_after>\/\/ Copyright 2022 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"smart_card_connector_app\/src\/application.h\"\n\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <queue>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include <winscard.h>\n\n#include <google_smart_card_common\/messaging\/typed_message_router.h>\n#include <google_smart_card_common\/multi_string.h>\n#include <google_smart_card_common\/unique_ptr_utils.h>\n#include <google_smart_card_common\/value.h>\n\n#include \"common\/cpp\/src\/public\/testing_global_context.h\"\n#include \"smart_card_connector_app\/src\/testing_smart_card_simulation.h\"\n\n#ifdef __native_client__\n#include <google_smart_card_common\/nacl_io_utils.h>\n#endif \/\/ __native_client__\n\nusing testing::ElementsAre;\nusing testing::IsEmpty;\n\nnamespace google_smart_card {\n\nnamespace {\n\n\/\/ Records reader_* messages sent to JS and allows to inspect them in tests.\nclass ReaderNotificationObserver final {\n public:\n void Init(TestingGlobalContext& global_context) {\n for (const auto* event_name :\n {\"reader_init_add\", \"reader_finish_add\", \"reader_remove\"}) {\n global_context.RegisterMessageHandler(\n event_name,\n std::bind(&ReaderNotificationObserver::OnMessageToJs, this,\n event_name, \/*request_payload=*\/std::placeholders::_1,\n \/*request_id=*\/std::placeholders::_2));\n }\n }\n\n \/\/ Extracts the next recorded notification, in the format \"<event>:<reader>\"\n \/\/ (for simplifying test assertions).\n std::string Pop() {\n std::unique_lock<std::mutex> lock(mutex_);\n GOOGLE_SMART_CARD_CHECK(!recorded_notifications_.empty());\n std::string next = std::move(recorded_notifications_.front());\n recorded_notifications_.pop();\n return next;\n }\n\n \/\/ Same as `Pop()`, but waits if there's no notification to return.\n std::string WaitAndPop() {\n std::unique_lock<std::mutex> lock(mutex_);\n condition_.wait(lock, [&] {\n return !recorded_notifications_.empty();\n });\n std::string next = std::move(recorded_notifications_.front());\n recorded_notifications_.pop();\n return next;\n }\n\n \/\/ Returns whether there's a notification to return.\n bool Empty() const {\n std::unique_lock<std::mutex> lock(mutex_);\n return recorded_notifications_.empty();\n }\n\n private:\n void OnMessageToJs(const std::string& event_name,\n Value message_data,\n optional<RequestId> \/*request_id*\/) {\n std::string notification =\n event_name + \":\" +\n message_data.GetDictionaryItem(\"readerName\")->GetString();\n\n std::unique_lock<std::mutex> lock(mutex_);\n recorded_notifications_.push(notification);\n condition_.notify_one();\n }\n\n \/\/ Mutable to allow locking in const methods.\n mutable std::mutex mutex_;\n std::condition_variable condition_;\n std::queue<std::string> recorded_notifications_;\n};\n\nstd::vector<std::string> DirectCallSCardListReaders(\n SCARDCONTEXT scard_context) {\n DWORD readers_size = 0;\n LONG return_code = SCardListReaders(scard_context, \/*mszGroups=*\/nullptr,\n \/*mszReaders=*\/nullptr, &readers_size);\n if (return_code == SCARD_E_NO_READERS_AVAILABLE)\n return {};\n EXPECT_EQ(return_code, SCARD_S_SUCCESS);\n EXPECT_GT(readers_size, 0U);\n\n std::string readers_multistring;\n readers_multistring.resize(readers_size);\n EXPECT_EQ(SCardListReaders(scard_context, \/*mszGroups=*\/nullptr,\n &readers_multistring[0], &readers_size),\n SCARD_S_SUCCESS);\n EXPECT_EQ(readers_size, readers_multistring.size());\n\n return ExtractMultiStringElements(readers_multistring);\n}\n\n} \/\/ namespace\n\nclass SmartCardConnectorApplicationTest : public ::testing::Test {\n protected:\n SmartCardConnectorApplicationTest() {\n#ifdef __native_client__\n \/\/ Make resource files accessible.\n MountNaclIoFolders();\n#endif \/\/ __native_client__\n SetUpUsbSimulation();\n reader_notification_observer_.Init(global_context_);\n }\n\n ~SmartCardConnectorApplicationTest() { application_->ShutDownAndWait(); }\n\n void StartApplication() {\n \/\/ Set up the expectation on the first C++-to-JS message.\n auto pcsc_lite_ready_message_waiter = global_context_.CreateMessageWaiter(\n \/*awaited_message_type=*\/\"pcsc_lite_ready\");\n \/\/ Set up the expectation for the application to run the provided callback.\n ::testing::MockFunction<void()> background_initialization_callback;\n EXPECT_CALL(background_initialization_callback, Call());\n \/\/ Create the application, which spawns the background initialization\n \/\/ thread.\n application_ = MakeUnique<Application>(\n &global_context_, &typed_message_router_,\n background_initialization_callback.AsStdFunction());\n \/\/ Wait until the daemon's background thread completes the initialization\n \/\/ and notifies the JS side.\n pcsc_lite_ready_message_waiter->Wait();\n EXPECT_TRUE(pcsc_lite_ready_message_waiter->value().StrictlyEquals(\n Value(Value::Type::kDictionary)));\n }\n\n \/\/ Enables the specified fake USB devices.\n void SetUsbDevices(\n const std::vector<TestingSmartCardSimulation::Device>& devices) {\n smart_card_simulation_.SetDevices(devices);\n }\n\n ReaderNotificationObserver& reader_notification_observer() {\n return reader_notification_observer_;\n }\n\n private:\n void SetUpUsbSimulation() {\n global_context_.RegisterRequestHandler(\n TestingSmartCardSimulation::kRequesterName,\n std::bind(&TestingSmartCardSimulation::OnRequestToJs,\n &smart_card_simulation_,\n \/*request_payload=*\/std::placeholders::_1,\n \/*request_id=*\/std::placeholders::_2));\n }\n\n TypedMessageRouter typed_message_router_;\n TestingSmartCardSimulation smart_card_simulation_{&typed_message_router_};\n ReaderNotificationObserver reader_notification_observer_;\n TestingGlobalContext global_context_{&typed_message_router_};\n std::unique_ptr<Application> application_;\n};\n\nTEST_F(SmartCardConnectorApplicationTest, SmokeTest) {\n StartApplication();\n}\n\n\/\/ Test a PC\/SC-Lite context can be established and freed, via direct C function\n\/\/ calls `SCardEstablishContext()` and `SCardReleaseContext()`.\n\/\/ This is an extended version of the \"smoke test\" as it verifies the daemon\n\/\/ successfully started and replies to calls sent over (fake) sockets.\nTEST_F(SmartCardConnectorApplicationTest, InternalApiContextEstablishing) {\n \/\/ Arrange:\n\n StartApplication();\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n EXPECT_NE(scard_context, 0);\n\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n}\n\n\/\/ Test a single reader is successfully initialized by PC\/SC-Lite and is\n\/\/ returned via the direct C function call `SCardListReaders()`.\nTEST_F(SmartCardConnectorApplicationTest, InternalApiSingleDeviceListing) {\n \/\/ Arrange:\n\n TestingSmartCardSimulation::Device device;\n device.id = 123;\n device.type = TestingSmartCardSimulation::DeviceType::kGemaltoPcTwinReader;\n SetUsbDevices({device});\n\n StartApplication();\n \/\/ No need to wait here, since the notifications for the initially present\n \/\/ devices are sent during the startup.\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_init_add:Gemalto PC Twin Reader\");\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_finish_add:Gemalto PC Twin Reader\");\n EXPECT_TRUE(reader_notification_observer().Empty());\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n std::vector<std::string> readers = DirectCallSCardListReaders(scard_context);\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n\n \/\/ Assert:\n\n EXPECT_THAT(readers, ElementsAre(\"Gemalto PC Twin Reader 00 00\"));\n}\n\nTEST_F(SmartCardConnectorApplicationTest,\n InternalApiGetStatusChangeDeviceAppearing) {\n \/\/ Arrange:\n\n \/\/ Start with an empty list of readers.\n StartApplication();\n EXPECT_TRUE(reader_notification_observer().Empty());\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n EXPECT_TRUE(DirectCallSCardListReaders(scard_context).empty());\n\n \/\/ Simulate connecting a reader.\n TestingSmartCardSimulation::Device device;\n device.id = 123;\n device.type = TestingSmartCardSimulation::DeviceType::kGemaltoPcTwinReader;\n SetUsbDevices({device});\n\n \/\/ Wait until PC\/SC reports a change in the list of readers.\n std::vector<SCARD_READERSTATE> reader_states(1);\n reader_states[0].szReader = R\"(\\\\?PnP?\\Notification)\";\n reader_states[0].dwCurrentState = SCARD_STATE_UNAWARE;\n EXPECT_EQ(SCardGetStatusChange(scard_context, \/*dwTimeout=*\/INFINITE,\n reader_states.data(), reader_states.size()),\n SCARD_S_SUCCESS);\n\n std::vector<std::string> readers = DirectCallSCardListReaders(scard_context);\n\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n\n \/\/ Assert:\n\n EXPECT_THAT(readers, ElementsAre(\"Gemalto PC Twin Reader 00 00\"));\n EXPECT_EQ(reader_notification_observer().WaitAndPop(),\n \"reader_init_add:Gemalto PC Twin Reader\");\n EXPECT_EQ(reader_notification_observer().WaitAndPop(),\n \"reader_finish_add:Gemalto PC Twin Reader\");\n EXPECT_TRUE(reader_notification_observer().Empty());\n}\n\nTEST_F(SmartCardConnectorApplicationTest,\n InternalApiGetStatusChangeDeviceRemoving) {\n \/\/ Arrange:\n\n \/\/ Start with a single reader.\n TestingSmartCardSimulation::Device device;\n device.id = 123;\n device.type = TestingSmartCardSimulation::DeviceType::kGemaltoPcTwinReader;\n SetUsbDevices({device});\n\n StartApplication();\n \/\/ No need to wait here, since the notifications for the initially present\n \/\/ devices are sent during the startup.\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_init_add:Gemalto PC Twin Reader\");\n EXPECT_EQ(reader_notification_observer().Pop(),\n \"reader_finish_add:Gemalto PC Twin Reader\");\n EXPECT_TRUE(reader_notification_observer().Empty());\n\n \/\/ Act:\n\n SCARDCONTEXT scard_context = 0;\n EXPECT_EQ(SCardEstablishContext(SCARD_SCOPE_SYSTEM, \/*pvReserved1=*\/nullptr,\n \/*pvReserved2=*\/nullptr, &scard_context),\n SCARD_S_SUCCESS);\n\n EXPECT_THAT(DirectCallSCardListReaders(scard_context),\n ElementsAre(\"Gemalto PC Twin Reader 00 00\"));\n\n \/\/ Simulate disconnecting the reader.\n SetUsbDevices({});\n\n \/\/ Wait until PC\/SC reports a change in the list of readers.\n std::vector<SCARD_READERSTATE> reader_states(1);\n reader_states[0].szReader = R\"(\\\\?PnP?\\Notification)\";\n reader_states[0].dwCurrentState = SCARD_STATE_UNAWARE;\n EXPECT_EQ(SCardGetStatusChange(scard_context, \/*dwTimeout=*\/INFINITE,\n reader_states.data(), reader_states.size()),\n SCARD_S_SUCCESS);\n\n std::vector<std::string> readers = DirectCallSCardListReaders(scard_context);\n\n EXPECT_EQ(SCardReleaseContext(scard_context), SCARD_S_SUCCESS);\n\n \/\/ Assert:\n\n EXPECT_THAT(readers, IsEmpty());\n EXPECT_EQ(reader_notification_observer().WaitAndPop(),\n \"reader_remove:Gemalto PC Twin Reader\");\n EXPECT_TRUE(reader_notification_observer().Empty());\n}\n\n} \/\/ namespace google_smart_card\n<|endoftext|>"} {"text":"<commit_before>#include \"SegmentationCostFunction.h\"\n#include <imageprocessing\/ConnectedComponent.h>\n#include <sopnet\/segments\/EndSegment.h>\n#include <sopnet\/segments\/ContinuationSegment.h>\n#include <sopnet\/segments\/BranchSegment.h>\n#include <sopnet\/slices\/Slice.h>\n#include <util\/ProgramOptions.h>\n\nlogger::LogChannel segmentationcostfunctionlog(\"segmentationcostfunctionlog\", \"[SegmentationCostFunction] \");\n\nutil::ProgramOption optionInvertMembraneMaps(\n\t\tutil::_module = \"sopnet\",\n\t\tutil::_long_name = \"invertMembraneMaps\",\n\t\tutil::_description_text = \"Invert the meaning of the membrane map. The default \"\n\t\t \"(not inverting) is: bright pixel = hight membrane probability.\");\n\nSegmentationCostFunction::SegmentationCostFunction() :\n\t_costFunction(boost::make_shared<costs_function_type>(boost::bind(&SegmentationCostFunction::costs, this, _1, _2, _3, _4))) {\n\n\tregisterInput(_membranes, \"membranes\");\n\tregisterInput(_parameters, \"parameters\");\n\n\tregisterOutput(_costFunction, \"cost function\");\n}\n\nvoid\nSegmentationCostFunction::updateOutputs() {\n\n\t\/\/ nothing to do here\n}\n\nvoid\nSegmentationCostFunction::costs(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches,\n\t\tstd::vector<double>& segmentCosts) {\n\n\tsegmentCosts.resize(ends.size() + continuations.size() + branches.size(), 0);\n\n\tif (_segmentationCosts.size() != segmentCosts.size() ||\n\t _parameters->priorForeground != _prevParameters.priorForeground) {\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog)\n\t\t\t\t<< \"updating segmentation costs (number of segments: \"\n\t\t\t\t<< segmentCosts.size() << \", number of cached values \"\n\t\t\t\t<< _segmentationCosts.size() << \")\" << std::endl;\n\n\t\t_segmentationCosts.clear();\n\t\t_segmentationCosts.reserve(ends.size() + continuations.size() + branches.size());\n\n\t\tcomputeSegmentationCosts(ends, continuations, branches);\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog)\n\t\t\t\t<< \"computed \" << _segmentationCosts.size() << \" segmentation cost values\" << std::endl;\n\t}\n\n\tif (_boundaryLengths.size() != segmentCosts.size()) {\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog) << \"updating boundary lengths...\" << std::endl;\n\n\t\t_boundaryLengths.clear();\n\t\t_boundaryLengths.reserve(ends.size() + continuations.size() + branches.size());\n\n\t\tcomputeBoundaryLengths(ends, continuations, branches);\n\t}\n\n\t_prevParameters = *_parameters;\n\n\tunsigned int i = 0;\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCosts(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches) {\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends)\n\t\tcomputeSegmentationCost(*end);\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations)\n\t\tcomputeSegmentationCost(*continuation);\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches)\n\t\tcomputeSegmentationCost(*branch);\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLengths(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches) {\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends)\n\t\tcomputeBoundaryLength(*end);\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations)\n\t\tcomputeBoundaryLength(*continuation);\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches)\n\t\tcomputeBoundaryLength(*branch);\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const EndSegment& end) {\n\n\t_segmentationCosts.push_back(computeSegmentationCost(*end.getSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const ContinuationSegment& continuation) {\n\n\t_segmentationCosts.push_back(\n\t\t\tcomputeSegmentationCost(*continuation.getSourceSlice()) +\n\t\t\tcomputeSegmentationCost(*continuation.getTargetSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const BranchSegment& branch) {\n\n\t_segmentationCosts.push_back(\n\t\t\tcomputeSegmentationCost(*branch.getSourceSlice()) +\n\t\t\tcomputeSegmentationCost(*branch.getTargetSlice1()) +\n\t\t\tcomputeSegmentationCost(*branch.getTargetSlice2()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const EndSegment& end) {\n\n\t_boundaryLengths.push_back(computeBoundaryLength(*end.getSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const ContinuationSegment& continuation) {\n\n\t_boundaryLengths.push_back(\n\t\t\tcomputeBoundaryLength(*continuation.getSourceSlice()) +\n\t\t\tcomputeBoundaryLength(*continuation.getTargetSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const BranchSegment& branch) {\n\n\t_boundaryLengths.push_back(\n\t\t\tcomputeBoundaryLength(*branch.getSourceSlice()) +\n\t\t\tcomputeBoundaryLength(*branch.getTargetSlice1()) +\n\t\t\tcomputeBoundaryLength(*branch.getTargetSlice2()));\n}\n\ndouble\nSegmentationCostFunction::computeSegmentationCost(const Slice& slice) {\n\n\tif (_sliceSegmentationCosts.count(slice.getId()))\n\t\treturn _sliceSegmentationCosts[slice.getId()];\n\n\tunsigned int section = slice.getSection();\n\n\tdouble costs = 0.0;\n\n\t\/\/ for each pixel in the slice\n\tforeach (const util::point<unsigned int>& pixel, slice.getComponent()->getPixels()) {\n\n\t\t\/\/ get the membrane data probability p(x|y=membrane)\n\t\tdouble probMembrane = (*(*_membranes)[section])(pixel.x, pixel.y)\/255.0;\n\n\t\tif (optionInvertMembraneMaps)\n\t\t\tprobMembrane = 1.0 - probMembrane;\n\n\t\t\/\/ get the neuron data probability p(x|y=neuron)\n\t\tdouble probNeuron = 1.0 - probMembrane;\n\n\t\t\/\/ multiply both with the respective prior p(y)\n\t\tprobMembrane *= (1.0 - _parameters->priorForeground);\n\t\tprobNeuron *= _parameters->priorForeground;\n\n\t\t\/\/ normalize both probabilities, so that we get p(y|x)\n\t\tprobMembrane \/= probMembrane + probNeuron;\n\t\tprobNeuron \/= probMembrane + probNeuron;\n\n\t\t\/\/ ensure numerical stability\n\t\tprobMembrane = std::max(0.0001, std::min(0.9999, probMembrane));\n\t\tprobNeuron = std::max(0.0001, std::min(0.9999, probNeuron));\n\n\t\t\/\/ compute the corresponding costs\n\t\tdouble costsMembrane = -log(probMembrane);\n\t\tdouble costsNeuron = -log(probNeuron);\n\n\t\t\/\/ costs for accepting the segmentation is the cost difference between\n\t\t\/\/ segmenting the region as background and segmenting the region as\n\t\t\/\/ foreground\n\t\tcosts += costsNeuron - costsMembrane;\n\t}\n\n\t_sliceSegmentationCosts[slice.getId()] = costs;\n\n\treturn costs;\n}\n\nunsigned int\nSegmentationCostFunction::computeBoundaryLength(const Slice& slice) {\n\n\tif (_sliceBoundaryLengths.count(slice.getId()))\n\t\treturn _sliceBoundaryLengths[slice.getId()];\n\n\tboost::shared_ptr<ConnectedComponent> component = slice.getComponent();\n\n\tunsigned int width = (unsigned int)(component->getBoundingBox().width() + 1);\n\tunsigned int height = (unsigned int)(component->getBoundingBox().height() + 1);\n\tunsigned int offsetX = (unsigned int)component->getBoundingBox().minX;\n\tunsigned int offsetY = (unsigned int)component->getBoundingBox().minY;\n\n\tstd::vector<bool> pixels(width*height, false);\n\n\tforeach (const util::point<unsigned int>& p, component->getPixels()) {\n\n\t\tunsigned int x = p.x - offsetX;\n\t\tunsigned int y = p.y - offsetY;\n\n\t\tpixels[x + y*width] = true;\n\t}\n\n\tunsigned int boundaryLength = 0;\n\n\tforeach (const util::point<unsigned int>& p, component->getPixels()) {\n\n\t\t\/\/ for neighborhood testing with offset\n\t\tunsigned int x = p.x - offsetX;\n\t\tunsigned int y = p.y - offsetY;\n\n\t\t\/\/ left\n\t\tif (x == 0 || !pixels[(x - 1) + y*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ right\n\t\tif (x == width - 1 || !pixels[(x + 1) + y*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ top\n\t\tif (y == 0 || !pixels[x + (y - 1)*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ bottom\n\t\tif (y == height - 1 || !pixels[x + (y + 1)*width])\n\t\t\tboundaryLength++;\n\t}\n\n\t_sliceBoundaryLengths[slice.getId()] = boundaryLength;\n\n\treturn boundaryLength;\n}\n<commit_msg>bugfix: segmentation costs assumed wrongly membrane intensities in [0, 255]<commit_after>#include \"SegmentationCostFunction.h\"\n#include <imageprocessing\/ConnectedComponent.h>\n#include <sopnet\/segments\/EndSegment.h>\n#include <sopnet\/segments\/ContinuationSegment.h>\n#include <sopnet\/segments\/BranchSegment.h>\n#include <sopnet\/slices\/Slice.h>\n#include <util\/ProgramOptions.h>\n\nlogger::LogChannel segmentationcostfunctionlog(\"segmentationcostfunctionlog\", \"[SegmentationCostFunction] \");\n\nutil::ProgramOption optionInvertMembraneMaps(\n\t\tutil::_module = \"sopnet\",\n\t\tutil::_long_name = \"invertMembraneMaps\",\n\t\tutil::_description_text = \"Invert the meaning of the membrane map. The default \"\n\t\t \"(not inverting) is: bright pixel = hight membrane probability.\");\n\nSegmentationCostFunction::SegmentationCostFunction() :\n\t_costFunction(boost::make_shared<costs_function_type>(boost::bind(&SegmentationCostFunction::costs, this, _1, _2, _3, _4))) {\n\n\tregisterInput(_membranes, \"membranes\");\n\tregisterInput(_parameters, \"parameters\");\n\n\tregisterOutput(_costFunction, \"cost function\");\n}\n\nvoid\nSegmentationCostFunction::updateOutputs() {\n\n\t\/\/ nothing to do here\n}\n\nvoid\nSegmentationCostFunction::costs(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches,\n\t\tstd::vector<double>& segmentCosts) {\n\n\tsegmentCosts.resize(ends.size() + continuations.size() + branches.size(), 0);\n\n\tif (_segmentationCosts.size() != segmentCosts.size() ||\n\t _parameters->priorForeground != _prevParameters.priorForeground) {\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog)\n\t\t\t\t<< \"updating segmentation costs (number of segments: \"\n\t\t\t\t<< segmentCosts.size() << \", number of cached values \"\n\t\t\t\t<< _segmentationCosts.size() << \")\" << std::endl;\n\n\t\t_sliceSegmentationCosts.clear();\n\t\t_segmentationCosts.clear();\n\t\t_segmentationCosts.reserve(ends.size() + continuations.size() + branches.size());\n\n\t\tcomputeSegmentationCosts(ends, continuations, branches);\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog)\n\t\t\t\t<< \"computed \" << _segmentationCosts.size() << \" segmentation cost values\" << std::endl;\n\t}\n\n\tif (_boundaryLengths.size() != segmentCosts.size()) {\n\n\t\tLOG_DEBUG(segmentationcostfunctionlog) << \"updating boundary lengths...\" << std::endl;\n\n\t\t_boundaryLengths.clear();\n\t\t_boundaryLengths.reserve(ends.size() + continuations.size() + branches.size());\n\n\t\tcomputeBoundaryLengths(ends, continuations, branches);\n\t}\n\n\t_prevParameters = *_parameters;\n\n\tunsigned int i = 0;\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches) {\n\n\t\tsegmentCosts[i] += _parameters->weight*(_segmentationCosts[i] + _parameters->weightPotts*_boundaryLengths[i]);\n\n\t\ti++;\n\t}\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCosts(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches) {\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends)\n\t\tcomputeSegmentationCost(*end);\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations)\n\t\tcomputeSegmentationCost(*continuation);\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches)\n\t\tcomputeSegmentationCost(*branch);\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLengths(\n\t\tconst std::vector<boost::shared_ptr<EndSegment> >& ends,\n\t\tconst std::vector<boost::shared_ptr<ContinuationSegment> >& continuations,\n\t\tconst std::vector<boost::shared_ptr<BranchSegment> >& branches) {\n\n\tforeach (boost::shared_ptr<EndSegment> end, ends)\n\t\tcomputeBoundaryLength(*end);\n\n\tforeach (boost::shared_ptr<ContinuationSegment> continuation, continuations)\n\t\tcomputeBoundaryLength(*continuation);\n\n\tforeach (boost::shared_ptr<BranchSegment> branch, branches)\n\t\tcomputeBoundaryLength(*branch);\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const EndSegment& end) {\n\n\t_segmentationCosts.push_back(computeSegmentationCost(*end.getSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const ContinuationSegment& continuation) {\n\n\t_segmentationCosts.push_back(\n\t\t\tcomputeSegmentationCost(*continuation.getSourceSlice()) +\n\t\t\tcomputeSegmentationCost(*continuation.getTargetSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeSegmentationCost(const BranchSegment& branch) {\n\n\t_segmentationCosts.push_back(\n\t\t\tcomputeSegmentationCost(*branch.getSourceSlice()) +\n\t\t\tcomputeSegmentationCost(*branch.getTargetSlice1()) +\n\t\t\tcomputeSegmentationCost(*branch.getTargetSlice2()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const EndSegment& end) {\n\n\t_boundaryLengths.push_back(computeBoundaryLength(*end.getSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const ContinuationSegment& continuation) {\n\n\t_boundaryLengths.push_back(\n\t\t\tcomputeBoundaryLength(*continuation.getSourceSlice()) +\n\t\t\tcomputeBoundaryLength(*continuation.getTargetSlice()));\n}\n\nvoid\nSegmentationCostFunction::computeBoundaryLength(const BranchSegment& branch) {\n\n\t_boundaryLengths.push_back(\n\t\t\tcomputeBoundaryLength(*branch.getSourceSlice()) +\n\t\t\tcomputeBoundaryLength(*branch.getTargetSlice1()) +\n\t\t\tcomputeBoundaryLength(*branch.getTargetSlice2()));\n}\n\ndouble\nSegmentationCostFunction::computeSegmentationCost(const Slice& slice) {\n\n\tif (_sliceSegmentationCosts.count(slice.getId()))\n\t\treturn _sliceSegmentationCosts[slice.getId()];\n\n\tunsigned int section = slice.getSection();\n\n\tdouble costs = 0.0;\n\n\t\/\/ for each pixel in the slice\n\tforeach (const util::point<unsigned int>& pixel, slice.getComponent()->getPixels()) {\n\n\t\t\/\/ get the membrane data probability p(x|y=membrane)\n\t\tdouble probMembrane = (*(*_membranes)[section])(pixel.x, pixel.y);\n\n\t\tif (optionInvertMembraneMaps)\n\t\t\tprobMembrane = 1.0 - probMembrane;\n\n\t\t\/\/ get the neuron data probability p(x|y=neuron)\n\t\tdouble probNeuron = 1.0 - probMembrane;\n\n\t\t\/\/ multiply both with the respective prior p(y)\n\t\tprobMembrane *= (1.0 - _parameters->priorForeground);\n\t\tprobNeuron *= _parameters->priorForeground;\n\n\t\t\/\/ normalize both probabilities, so that we get p(y|x)\n\t\tprobMembrane \/= probMembrane + probNeuron;\n\t\tprobNeuron \/= probMembrane + probNeuron;\n\n\t\t\/\/ ensure numerical stability\n\t\tprobMembrane = std::max(0.0001, std::min(0.9999, probMembrane));\n\t\tprobNeuron = std::max(0.0001, std::min(0.9999, probNeuron));\n\n\t\t\/\/ compute the corresponding costs\n\t\tdouble costsMembrane = -log(probMembrane);\n\t\tdouble costsNeuron = -log(probNeuron);\n\n\t\t\/\/ costs for accepting the segmentation is the cost difference between\n\t\t\/\/ segmenting the region as background and segmenting the region as\n\t\t\/\/ foreground\n\t\tcosts += costsNeuron - costsMembrane;\n\t}\n\n\t_sliceSegmentationCosts[slice.getId()] = costs;\n\n\treturn costs;\n}\n\nunsigned int\nSegmentationCostFunction::computeBoundaryLength(const Slice& slice) {\n\n\tif (_sliceBoundaryLengths.count(slice.getId()))\n\t\treturn _sliceBoundaryLengths[slice.getId()];\n\n\tboost::shared_ptr<ConnectedComponent> component = slice.getComponent();\n\n\tunsigned int width = (unsigned int)(component->getBoundingBox().width() + 1);\n\tunsigned int height = (unsigned int)(component->getBoundingBox().height() + 1);\n\tunsigned int offsetX = (unsigned int)component->getBoundingBox().minX;\n\tunsigned int offsetY = (unsigned int)component->getBoundingBox().minY;\n\n\tstd::vector<bool> pixels(width*height, false);\n\n\tforeach (const util::point<unsigned int>& p, component->getPixels()) {\n\n\t\tunsigned int x = p.x - offsetX;\n\t\tunsigned int y = p.y - offsetY;\n\n\t\tpixels[x + y*width] = true;\n\t}\n\n\tunsigned int boundaryLength = 0;\n\n\tforeach (const util::point<unsigned int>& p, component->getPixels()) {\n\n\t\t\/\/ for neighborhood testing with offset\n\t\tunsigned int x = p.x - offsetX;\n\t\tunsigned int y = p.y - offsetY;\n\n\t\t\/\/ left\n\t\tif (x == 0 || !pixels[(x - 1) + y*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ right\n\t\tif (x == width - 1 || !pixels[(x + 1) + y*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ top\n\t\tif (y == 0 || !pixels[x + (y - 1)*width])\n\t\t\tboundaryLength++;\n\n\t\t\/\/ bottom\n\t\tif (y == height - 1 || !pixels[x + (y + 1)*width])\n\t\t\tboundaryLength++;\n\t}\n\n\t_sliceBoundaryLengths[slice.getId()] = boundaryLength;\n\n\treturn boundaryLength;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include <cfloat>\n\n#include <SDL.h>\n\n#include \"compiler.h\"\n#include \"TCPServer.hpp\"\n\n#ifdef _WINDOWS\n#include <tchar.h>\nint wmain(int argc, _TCHAR* argv[]) {\n#else\nint main(int argc, char** argv) {\n#endif\n\n\t\/\/ defaults\n\tunsigned int port = 60601;\n\t\n\t\/\/ command line params\n\tif (argc >= 2) {\n\t\tport = atoi(argv[1]);\n\t}\n\n\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER) != 0) {\n\t\tstd::cout << \"SDL_Init Error: \" << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"hello sdl\" << std::endl;\n\n\tSDL_Window* windowHandle = SDL_CreateWindow(\"Hello World!\", 100, 100, 640, 480, SDL_WINDOW_SHOWN);\n\t\n\tif (windowHandle == nullptr) {\n\t\tstd::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ setup joysticks\n\tSDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, \"1\");\n\n\n bool dirty = false;\n unsigned int numJoysticks = SDL_NumJoysticks();\n\n\tauto numAxes = new unsigned int[numJoysticks];\n\tauto numButtons = new unsigned int[numJoysticks];\n\t\n int activeJoystick = 0; \/\/ starting with 0\n\tstd::cout << numJoysticks << \" joystic(s) found.\" << std::endl;\n \n\tfor (unsigned int i = 0; i < numJoysticks; i++)\n\t{\n\t\tnumAxes[i] = 0;\n\t\tnumButtons[i] = 0;\n\n\t\tSDL_Joystick* stick = SDL_JoystickOpen(i);\n\n\t\tif (stick) {\n\t printf(\"Opened Joystick 0\\n\");\n\t printf(\"Name: %s\\n\", SDL_JoystickNameForIndex(i));\n\t \/\/ printf(\"Devise GUID: %s\\n\", SDL_JoystickGetGUIDString(i));\n\t printf(\"Number of Axes: %d\\n\", SDL_JoystickNumAxes(stick));\n\t printf(\"Number of Buttons: %d\\n\", SDL_JoystickNumButtons(stick));\n\t printf(\"Number of Balls: %d\\n\", SDL_JoystickNumBalls(stick));\n \n numAxes[i] = SDL_JoystickNumAxes(stick);\n numButtons[i] = SDL_JoystickNumButtons(stick);\n\t } else {\n\t printf(\"Couldn't open Joystick 0\\n\");\n\t }\n\t}\n \n\n auto axesBuffer = new float*[numJoysticks];\n auto buttonsBuffer = new float*[numJoysticks];\n\n for (unsigned int i = 0; i < numJoysticks; i++)\n {\n \taxesBuffer[i] = new float[numAxes[i]];\n \tfor (unsigned int j = 0; j < numAxes[i]; j++)\n\t {\n\t axesBuffer[i][j] = 0;\n\t }\n\t \n\t buttonsBuffer[i] = new float[numButtons[i]];\n\t for (unsigned int j = 0; j < numButtons[i]; j++)\n\t {\n\t\t\tbuttonsBuffer[i][j] = 0;\n\t }\t\n }\n \n\n \n \n \n \/\/ setup networking\n boost::asio::io_service io_service;\n TCPServer server(io_service, 60601);\n \n \n auto lastFrame = 0.0f;\n auto minFrameDelta = FLT_MAX;\n auto maxFrameDelta = 0.0f;\n\n\t\/\/ run!\n std::cout << \"entering main loop\" << std::endl;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n\tbool running = true;\n\twhile (running)\n\t{\n try\n {\n io_service.poll();\n }\n catch (std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n\t\tSDL_JoystickUpdate();\n\n\t\tSDL_Event e;\n\t\twhile (SDL_PollEvent(&e))\n {\n\t\t\tif (e.type == SDL_QUIT)\n\t\t\t{\n\t\t\t\trunning = false;\n\t\t\t}\n else if (e.type == SDL_KEYDOWN)\n {\n if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_LEFT)\n {\n activeJoystick = (activeJoystick - 1) % numJoysticks;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n }\n if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_RIGHT)\n {\n activeJoystick = (activeJoystick + 1) % numJoysticks;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n }\n }\n\t\t\telse if (e.type == SDL_JOYAXISMOTION)\n\t\t\t{\n if (e.jaxis.which == activeJoystick)\n {\n\t\t\t\t\tfloat oldValue = axesBuffer[activeJoystick][e.jaxis.axis];\n\t\t\t\t\tfloat newValue = (float)e.jaxis.value \/ (float)(0xffff \/ 2);\n\n\t\t\t\t\tdirty = dirty || (oldValue != newValue);\n\n\t\t\t\t\taxesBuffer[activeJoystick][e.jaxis.axis] = newValue;\n\t\t\t\t}\n }\n else if (e.type == SDL_JOYBUTTONDOWN)\n\t\t\t{\n\t\t\t\tif (e.jaxis.which == activeJoystick)\n {\n\t\t\t\t\tdirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 1.0f);\n\t buttonsBuffer[activeJoystick][e.jbutton.button] = 1.0f;\n\t }\n\t\t\t}\n else if (e.type == SDL_JOYBUTTONUP)\n\t\t\t{\n if (e.jaxis.which == activeJoystick)\n {\n\t dirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 0.0f);\n\t buttonsBuffer[activeJoystick][e.jbutton.button] = 0.0f;\n\t }\n\t\t\t}\n\t\t}\n \n \/\/ transfer frame\n float time = (float)SDL_GetTicks() \/ 1000.0f;\n\n if (dirty)\n {\n for (unsigned int i = 0; i < numAxes[activeJoystick]; i++)\n {\n std::stringstream sstr;\n sstr << \"axis-\" << i;\n \n server.inputAnalog(sstr.str(), axesBuffer[activeJoystick][i], time, -1.0f, 1.0f);\n }\n \n for (unsigned int i = 0; i < numButtons[activeJoystick]; i++)\n {\n std::stringstream sstr;\n sstr << \"button-\" << i;\n \n server.inputDigital(sstr.str(), buttonsBuffer[activeJoystick][i], time);\n }\n \n auto dt = time - lastFrame;\n minFrameDelta = std::min(minFrameDelta, dt);\n maxFrameDelta = std::max(maxFrameDelta, dt);\n std::cout << \"dt: \" << dt * 1000 << \"ms, min dt: \" << minFrameDelta * 1000 << \"ms, max dt: \" << maxFrameDelta << std::endl;\n \n\t\t\tlastFrame = time;\n }\n \n dirty = false;\n\n \/\/ deschedule this thread to save some resources...\n \/\/ time passed to the function is lower bound\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t}\n\n\tSDL_Quit();\n\treturn 0;\n}\n\n\n<commit_msg>input-logger: quit if no controller found on startup<commit_after>#include <iostream>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include <cfloat>\n\n#include <SDL.h>\n\n#include \"compiler.h\"\n#include \"TCPServer.hpp\"\n\n#ifdef _WINDOWS\n#include <tchar.h>\nint wmain(int argc, _TCHAR* argv[]) {\n#else\nint main(int argc, char** argv) {\n#endif\n\n\t\/\/ defaults\n\tunsigned int port = 60601;\n\t\n\t\/\/ command line params\n\tif (argc >= 2) {\n\t\tport = atoi(argv[1]);\n\t}\n\n\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER) != 0) {\n\t\tstd::cout << \"SDL_Init Error: \" << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"hello sdl\" << std::endl;\n\n\tSDL_Window* windowHandle = SDL_CreateWindow(\"Hello World!\", 100, 100, 640, 480, SDL_WINDOW_SHOWN);\n\t\n\tif (windowHandle == nullptr) {\n\t\tstd::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ setup joysticks\n\tSDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, \"1\");\n\n\n bool dirty = false;\n unsigned int numJoysticks = SDL_NumJoysticks();\n\n\tauto numAxes = new unsigned int[numJoysticks];\n\tauto numButtons = new unsigned int[numJoysticks];\n\t\n int activeJoystick = 0; \/\/ starting with 0\n\tstd::cout << numJoysticks << \" joystic(s) found.\" << std::endl;\n\n\tif (numJoysticks == 0)\n\t{\n\t\tstd::cout << \"quitting...\" << std::endl;\n\t\treturn 1;\n\t}\n \n\tfor (unsigned int i = 0; i < numJoysticks; i++)\n\t{\n\t\tnumAxes[i] = 0;\n\t\tnumButtons[i] = 0;\n\n\t\tSDL_Joystick* stick = SDL_JoystickOpen(i);\n\n\t\tif (stick) {\n\t printf(\"Opened Joystick 0\\n\");\n\t printf(\"Name: %s\\n\", SDL_JoystickNameForIndex(i));\n\t \/\/ printf(\"Devise GUID: %s\\n\", SDL_JoystickGetGUIDString(i));\n\t printf(\"Number of Axes: %d\\n\", SDL_JoystickNumAxes(stick));\n\t printf(\"Number of Buttons: %d\\n\", SDL_JoystickNumButtons(stick));\n\t printf(\"Number of Balls: %d\\n\", SDL_JoystickNumBalls(stick));\n \n numAxes[i] = SDL_JoystickNumAxes(stick);\n numButtons[i] = SDL_JoystickNumButtons(stick);\n\t } else {\n\t printf(\"Couldn't open Joystick 0\\n\");\n\t }\n\t}\n \n\n auto axesBuffer = new float*[numJoysticks];\n auto buttonsBuffer = new float*[numJoysticks];\n\n for (unsigned int i = 0; i < numJoysticks; i++)\n {\n \taxesBuffer[i] = new float[numAxes[i]];\n \tfor (unsigned int j = 0; j < numAxes[i]; j++)\n\t {\n\t axesBuffer[i][j] = 0;\n\t }\n\t \n\t buttonsBuffer[i] = new float[numButtons[i]];\n\t for (unsigned int j = 0; j < numButtons[i]; j++)\n\t {\n\t\t\tbuttonsBuffer[i][j] = 0;\n\t }\t\n }\n \n\n \n \n \n \/\/ setup networking\n boost::asio::io_service io_service;\n TCPServer server(io_service, 60601);\n \n \n auto lastFrame = 0.0f;\n auto minFrameDelta = FLT_MAX;\n auto maxFrameDelta = 0.0f;\n\n\t\/\/ run!\n std::cout << \"entering main loop\" << std::endl;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n\tbool running = true;\n\twhile (running)\n\t{\n try\n {\n io_service.poll();\n }\n catch (std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n\t\tSDL_JoystickUpdate();\n\n\t\tSDL_Event e;\n\t\twhile (SDL_PollEvent(&e))\n {\n\t\t\tif (e.type == SDL_QUIT)\n\t\t\t{\n\t\t\t\trunning = false;\n\t\t\t}\n else if (e.type == SDL_KEYDOWN)\n {\n if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_LEFT)\n {\n activeJoystick = (activeJoystick - 1) % numJoysticks;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n }\n if (e.key.state == SDL_PRESSED && e.key.keysym.scancode == SDL_SCANCODE_RIGHT)\n {\n activeJoystick = (activeJoystick + 1) % numJoysticks;\n std::cout << \"active joystic is: \" << activeJoystick << std::endl;\n }\n }\n\t\t\telse if (e.type == SDL_JOYAXISMOTION)\n\t\t\t{\n if (e.jaxis.which == activeJoystick)\n {\n\t\t\t\t\tfloat oldValue = axesBuffer[activeJoystick][e.jaxis.axis];\n\t\t\t\t\tfloat newValue = (float)e.jaxis.value \/ (float)(0xffff \/ 2);\n\n\t\t\t\t\tdirty = dirty || (oldValue != newValue);\n\n\t\t\t\t\taxesBuffer[activeJoystick][e.jaxis.axis] = newValue;\n\t\t\t\t}\n }\n else if (e.type == SDL_JOYBUTTONDOWN)\n\t\t\t{\n\t\t\t\tif (e.jaxis.which == activeJoystick)\n {\n\t\t\t\t\tdirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 1.0f);\n\t buttonsBuffer[activeJoystick][e.jbutton.button] = 1.0f;\n\t }\n\t\t\t}\n else if (e.type == SDL_JOYBUTTONUP)\n\t\t\t{\n if (e.jaxis.which == activeJoystick)\n {\n\t dirty = dirty || (buttonsBuffer[activeJoystick][e.jbutton.button] != 0.0f);\n\t buttonsBuffer[activeJoystick][e.jbutton.button] = 0.0f;\n\t }\n\t\t\t}\n\t\t}\n \n \/\/ transfer frame\n float time = (float)SDL_GetTicks() \/ 1000.0f;\n\n if (dirty)\n {\n for (unsigned int i = 0; i < numAxes[activeJoystick]; i++)\n {\n std::stringstream sstr;\n sstr << \"axis-\" << i;\n \n server.inputAnalog(sstr.str(), axesBuffer[activeJoystick][i], time, -1.0f, 1.0f);\n }\n \n for (unsigned int i = 0; i < numButtons[activeJoystick]; i++)\n {\n std::stringstream sstr;\n sstr << \"button-\" << i;\n \n server.inputDigital(sstr.str(), buttonsBuffer[activeJoystick][i], time);\n }\n \n auto dt = time - lastFrame;\n minFrameDelta = std::min(minFrameDelta, dt);\n maxFrameDelta = std::max(maxFrameDelta, dt);\n std::cout << \"dt: \" << dt * 1000 << \"ms, min dt: \" << minFrameDelta * 1000 << \"ms, max dt: \" << maxFrameDelta << std::endl;\n \n\t\t\tlastFrame = time;\n }\n \n dirty = false;\n\n \/\/ deschedule this thread to save some resources...\n \/\/ time passed to the function is lower bound\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t}\n\n\tSDL_Quit();\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/net\/net_dispatcher.hpp\n *\n * Asynchronous callback wrapper around select(), epoll(), or other kernel-level\n * dispatchers.\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_NET_NET_DISPATCHER_HEADER\n#define C7A_NET_NET_DISPATCHER_HEADER\n\n#include <c7a\/net\/net_connection.hpp>\n#include <c7a\/net\/buffer.hpp>\n#include <c7a\/net\/lowlevel\/socket.hpp>\n#include <c7a\/net\/lowlevel\/select_dispatcher.hpp>\n\/\/#include <c7a\/net\/lowlevel\/epoll-dispatcher.hpp>\n\n#include <string>\n#include <deque>\n#include <queue>\n#include <ctime>\n\nnamespace c7a {\nnamespace net {\n\/\/! \\addtogroup net Network Communication\n\/\/! \\{\n\n\/**\n * NetDispatcher is a high level wrapper for asynchronous callback\n * processing.. One can register NetConnection objects for readability and\n * writability checks, buffered reads and writes with completion callbacks, and\n * also timer functions.\n *\/\nclass NetDispatcher {\n static const bool debug = false;\n\nprotected:\n \/\/! switch between different low-level dispatchers\n typedef lowlevel::SelectDispatcher<NetConnection&> Dispatcher;\n \/\/typedef lowlevel::EPollDispatcher Dispatcher;\n\n \/\/! import into class namespace\n typedef lowlevel::Socket Socket;\n\npublic:\n \/\/! \\name Timeout Callbacks\n \/\/! \\{\n\n \/\/! callback signature for timer events\n typedef std::function<bool ()> TimerCallback;\n\n \/\/! Register a relative timeout callback\n void AddRelativeTimeout(double timeout, const TimerCallback& cb) {\n timer_pq_.emplace(GetClock() + timeout, timeout, cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name NetConnection Callbacks\n \/\/! \\{\n\n \/\/! callback signature for socket readable\/writable events\n typedef std::function<bool (NetConnection&)> ConnectionCallback;\n\n \/\/! Register a buffered read callback and a default exception callback.\n void AddRead(NetConnection& c, const ConnectionCallback& read_cb) {\n return dispatcher_.AddRead(c.GetSocket().fd(), c, read_cb);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddWrite(NetConnection& c, const ConnectionCallback& write_cb) {\n return dispatcher_.AddWrite(c.GetSocket().fd(), c, write_cb);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddReadWrite(\n NetConnection& c,\n const ConnectionCallback& read_cb, const ConnectionCallback& write_cb) {\n return dispatcher_.AddReadWrite(\n c.GetSocket().fd(), c, read_cb, write_cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name Asynchronous Data Reader\/Writer Callbacks\n \/\/! \\{\n\n \/\/! callback signature for async read callbacks, they may acquire the buffer\n typedef std::function<void (NetConnection& c,\n Buffer&& buffer)> AsyncReadCallback;\n\n \/\/! asynchronously read n bytes and deliver them to the callback\n virtual void AsyncRead(NetConnection& c, size_t n,\n AsyncReadCallback done_cb) {\n LOG << \"async read on read dispatcher\";\n if (n == 0) {\n if (done_cb) done_cb(c, Buffer());\n return;\n }\n\n \/\/ add new async reader object\n async_read_.emplace_back(n, done_cb);\n\n \/\/ register read callback\n AsyncReadBuffer& arb = async_read_.back();\n AddRead(c, [&arb](NetConnection& c) { return arb(c); });\n }\n\n \/\/! callback signature for async write callbacks\n typedef std::function<void (NetConnection&)> AsyncWriteCallback;\n\n \/\/! asynchronously write buffer and callback when delivered. The buffer is\n \/\/! MOVED into the async writer.\n void AsyncWrite(NetConnection& c, Buffer&& buffer,\n AsyncWriteCallback done_cb = nullptr) {\n if (buffer.size() == 0) {\n if (done_cb) done_cb(c);\n return;\n }\n\n \/\/ add new async writer object\n async_write_.emplace_back(std::move(buffer), done_cb);\n\n \/\/ register write callback\n AsyncWriteBuffer& awb = async_write_.back();\n AddWrite(c, [&awb](NetConnection& c) { return awb(c); });\n }\n\n \/\/! asynchronously write buffer and callback when delivered. COPIES the data\n \/\/! into a Buffer!\n void AsyncWriteCopy(NetConnection& c, const void* buffer, size_t size,\n AsyncWriteCallback done_cb = NULL) {\n return AsyncWrite(c, Buffer(buffer, size), done_cb);\n }\n\n \/\/! asynchronously write buffer and callback when delivered. COPIES the data\n \/\/! into a Buffer!\n void AsyncWriteCopy(NetConnection& c, const std::string& str,\n AsyncWriteCallback done_cb = NULL) {\n return AsyncWriteCopy(c, str.data(), str.size(), done_cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name Dispatch\n \/\/! \\{\n\n \/\/! dispatch one or more events\n void Dispatch(bool quit_when_empty = false) {\n \/\/ process timer events that lie in the past\n double now = GetClock();\n\n while (!timer_pq_.empty() && timer_pq_.top().next_timeout <= now)\n {\n const Timer& top = timer_pq_.top();\n if (top.cb()) {\n \/\/ requeue timeout event again.\n timer_pq_.emplace(top.next_timeout + top.timeout,\n top.timeout, top.cb);\n }\n timer_pq_.pop();\n }\n\n \/\/ calculate time until next timer event\n if (timer_pq_.empty()) {\n if (quit_when_empty) return;\n dispatcher_.Dispatch(INFINITY);\n }\n else {\n dispatcher_.Dispatch(timer_pq_.top().next_timeout - now);\n }\n }\n\n \/\/! \\}\n\nprotected:\n \/\/! get a current monotonic clock\n static double GetClock() {\n struct timespec ts;\n ::clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec + ts.tv_nsec * 1e-9;\n }\n\n \/\/! low-level file descriptor async processing\n Dispatcher dispatcher_;\n\n \/\/! struct for timer callbacks\n struct Timer\n {\n \/\/! timepoint of next timeout\n double next_timeout;\n \/\/! relative timeout for restarting\n double timeout;\n \/\/! callback\n TimerCallback cb;\n\n Timer(double _next_timeout, double _timeout, const TimerCallback& _cb)\n : next_timeout(_next_timeout), timeout(_timeout), cb(_cb)\n { }\n\n bool operator < (const Timer& b) const\n { return next_timeout < b.next_timeout; }\n };\n\n \/\/! priority queue of timer callbacks\n typedef std::priority_queue<Timer> TimerPQ;\n\n \/\/! priority queue of timer callbacks, obviously kept in timeout\n \/\/! order. Currently not addressable.\n TimerPQ timer_pq_;\n\n \/**************************************************************************\/\n\n class AsyncReadBuffer {\n public:\n \/\/! Construct buffered reader with callback\n AsyncReadBuffer(size_t buffer_size, const AsyncReadCallback& callback)\n : callback_(callback),\n buffer_(buffer_size)\n { }\n\n \/\/! Should be called when the socket is readable\n bool operator () (NetConnection& c) {\n int r = c.GetSocket().recv_one(\n buffer_.data() + size_, buffer_.size() - size_);\n\n if (r < 0)\n throw Exception(\"AsyncReadBuffer() error in recv\", errno);\n\n size_ += r;\n\n if (size_ == buffer_.size()) {\n if (callback_) callback_(c, std::move(buffer_));\n return false;\n }\n else {\n return true;\n }\n }\n\n private:\n \/\/! total size currently read\n size_t size_ = 0;\n\n \/\/! functional object to call once data is complete\n AsyncReadCallback callback_;\n\n \/\/! Receive buffer\n Buffer buffer_;\n };\n\n \/\/! deque of asynchronous readers\n std::deque<AsyncReadBuffer> async_read_;\n\n \/**************************************************************************\/\n\n class AsyncWriteBuffer {\n public:\n \/\/! Construct buffered writer with callback\n AsyncWriteBuffer(Buffer&& buffer,\n const AsyncWriteCallback& callback)\n : callback_(callback),\n buffer_(std::move(buffer))\n { }\n\n \/\/! Should be called when the socket is writable\n bool operator () (NetConnection& c) {\n int r = c.GetSocket().send_one(\n buffer_.data() + size_, buffer_.size() - size_);\n\n if (r < 0)\n throw Exception(\"AsyncWriteBuffer() error in send\", errno);\n\n size_ += r;\n\n if (size_ == buffer_.size()) {\n if (callback_) callback_(c);\n return false;\n }\n else {\n return true;\n }\n }\n\n private:\n \/\/! total size currently written\n size_t size_ = 0;\n\n \/\/! functional object to call once data is complete\n AsyncWriteCallback callback_;\n\n \/\/! Receive buffer\n Buffer buffer_;\n };\n\n \/\/! deque of asynchronous writers\n std::deque<AsyncWriteBuffer> async_write_;\n\n \/**************************************************************************\/\n\n \/\/! Default exception handler\n static bool ExceptionCallback(NetConnection& s) {\n \/\/ exception on listen socket ?\n throw Exception(\n \"NetDispatcher() exception on socket fd \"\n + std::to_string(s.GetSocket().fd()) + \"!\", errno);\n }\n};\n\n\/\/! \\}\n} \/\/ namespace net\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_NET_DISPATCHER_HEADER\n\n\/******************************************************************************\/\n<commit_msg>remove nasty dispatcher exit hack<commit_after>\/*******************************************************************************\n * c7a\/net\/net_dispatcher.hpp\n *\n * Asynchronous callback wrapper around select(), epoll(), or other kernel-level\n * dispatchers.\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_NET_NET_DISPATCHER_HEADER\n#define C7A_NET_NET_DISPATCHER_HEADER\n\n#include <c7a\/net\/net_connection.hpp>\n#include <c7a\/net\/buffer.hpp>\n#include <c7a\/net\/lowlevel\/socket.hpp>\n#include <c7a\/net\/lowlevel\/select_dispatcher.hpp>\n\/\/#include <c7a\/net\/lowlevel\/epoll-dispatcher.hpp>\n\n#include <string>\n#include <deque>\n#include <queue>\n#include <ctime>\n\nnamespace c7a {\nnamespace net {\n\/\/! \\addtogroup net Network Communication\n\/\/! \\{\n\n\/**\n * NetDispatcher is a high level wrapper for asynchronous callback\n * processing.. One can register NetConnection objects for readability and\n * writability checks, buffered reads and writes with completion callbacks, and\n * also timer functions.\n *\/\nclass NetDispatcher {\n static const bool debug = false;\n\nprotected:\n \/\/! switch between different low-level dispatchers\n typedef lowlevel::SelectDispatcher<NetConnection&> Dispatcher;\n \/\/typedef lowlevel::EPollDispatcher Dispatcher;\n\n \/\/! import into class namespace\n typedef lowlevel::Socket Socket;\n\npublic:\n \/\/! \\name Timeout Callbacks\n \/\/! \\{\n\n \/\/! callback signature for timer events\n typedef std::function<bool ()> TimerCallback;\n\n \/\/! Register a relative timeout callback\n void AddRelativeTimeout(double timeout, const TimerCallback& cb) {\n timer_pq_.emplace(GetClock() + timeout, timeout, cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name NetConnection Callbacks\n \/\/! \\{\n\n \/\/! callback signature for socket readable\/writable events\n typedef std::function<bool (NetConnection&)> ConnectionCallback;\n\n \/\/! Register a buffered read callback and a default exception callback.\n void AddRead(NetConnection& c, const ConnectionCallback& read_cb) {\n return dispatcher_.AddRead(c.GetSocket().fd(), c, read_cb);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddWrite(NetConnection& c, const ConnectionCallback& write_cb) {\n return dispatcher_.AddWrite(c.GetSocket().fd(), c, write_cb);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddReadWrite(\n NetConnection& c,\n const ConnectionCallback& read_cb, const ConnectionCallback& write_cb) {\n return dispatcher_.AddReadWrite(\n c.GetSocket().fd(), c, read_cb, write_cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name Asynchronous Data Reader\/Writer Callbacks\n \/\/! \\{\n\n \/\/! callback signature for async read callbacks, they may acquire the buffer\n typedef std::function<void (NetConnection& c,\n Buffer&& buffer)> AsyncReadCallback;\n\n \/\/! asynchronously read n bytes and deliver them to the callback\n virtual void AsyncRead(NetConnection& c, size_t n,\n AsyncReadCallback done_cb) {\n LOG << \"async read on read dispatcher\";\n if (n == 0) {\n if (done_cb) done_cb(c, Buffer());\n return;\n }\n\n \/\/ add new async reader object\n async_read_.emplace_back(n, done_cb);\n\n \/\/ register read callback\n AsyncReadBuffer& arb = async_read_.back();\n AddRead(c, [&arb](NetConnection& c) { return arb(c); });\n }\n\n \/\/! callback signature for async write callbacks\n typedef std::function<void (NetConnection&)> AsyncWriteCallback;\n\n \/\/! asynchronously write buffer and callback when delivered. The buffer is\n \/\/! MOVED into the async writer.\n void AsyncWrite(NetConnection& c, Buffer&& buffer,\n AsyncWriteCallback done_cb = nullptr) {\n if (buffer.size() == 0) {\n if (done_cb) done_cb(c);\n return;\n }\n\n \/\/ add new async writer object\n async_write_.emplace_back(std::move(buffer), done_cb);\n\n \/\/ register write callback\n AsyncWriteBuffer& awb = async_write_.back();\n AddWrite(c, [&awb](NetConnection& c) { return awb(c); });\n }\n\n \/\/! asynchronously write buffer and callback when delivered. COPIES the data\n \/\/! into a Buffer!\n void AsyncWriteCopy(NetConnection& c, const void* buffer, size_t size,\n AsyncWriteCallback done_cb = NULL) {\n return AsyncWrite(c, Buffer(buffer, size), done_cb);\n }\n\n \/\/! asynchronously write buffer and callback when delivered. COPIES the data\n \/\/! into a Buffer!\n void AsyncWriteCopy(NetConnection& c, const std::string& str,\n AsyncWriteCallback done_cb = NULL) {\n return AsyncWriteCopy(c, str.data(), str.size(), done_cb);\n }\n\n \/\/! \\}\n\n \/\/! \\name Dispatch\n \/\/! \\{\n\n \/\/! dispatch one or more events\n void Dispatch() {\n \/\/ process timer events that lie in the past\n double now = GetClock();\n\n while (!timer_pq_.empty() && timer_pq_.top().next_timeout <= now)\n {\n const Timer& top = timer_pq_.top();\n if (top.cb()) {\n \/\/ requeue timeout event again.\n timer_pq_.emplace(top.next_timeout + top.timeout,\n top.timeout, top.cb);\n }\n timer_pq_.pop();\n }\n\n \/\/ calculate time until next timer event\n if (timer_pq_.empty()) {\n dispatcher_.Dispatch(INFINITY);\n }\n else {\n dispatcher_.Dispatch(timer_pq_.top().next_timeout - now);\n }\n }\n\n \/\/! \\}\n\nprotected:\n \/\/! get a current monotonic clock\n static double GetClock() {\n struct timespec ts;\n ::clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec + ts.tv_nsec * 1e-9;\n }\n\n \/\/! low-level file descriptor async processing\n Dispatcher dispatcher_;\n\n \/\/! struct for timer callbacks\n struct Timer\n {\n \/\/! timepoint of next timeout\n double next_timeout;\n \/\/! relative timeout for restarting\n double timeout;\n \/\/! callback\n TimerCallback cb;\n\n Timer(double _next_timeout, double _timeout, const TimerCallback& _cb)\n : next_timeout(_next_timeout), timeout(_timeout), cb(_cb)\n { }\n\n bool operator < (const Timer& b) const\n { return next_timeout < b.next_timeout; }\n };\n\n \/\/! priority queue of timer callbacks\n typedef std::priority_queue<Timer> TimerPQ;\n\n \/\/! priority queue of timer callbacks, obviously kept in timeout\n \/\/! order. Currently not addressable.\n TimerPQ timer_pq_;\n\n \/**************************************************************************\/\n\n class AsyncReadBuffer {\n public:\n \/\/! Construct buffered reader with callback\n AsyncReadBuffer(size_t buffer_size, const AsyncReadCallback& callback)\n : callback_(callback),\n buffer_(buffer_size)\n { }\n\n \/\/! Should be called when the socket is readable\n bool operator () (NetConnection& c) {\n int r = c.GetSocket().recv_one(\n buffer_.data() + size_, buffer_.size() - size_);\n\n if (r < 0)\n throw Exception(\"AsyncReadBuffer() error in recv\", errno);\n\n size_ += r;\n\n if (size_ == buffer_.size()) {\n if (callback_) callback_(c, std::move(buffer_));\n return false;\n }\n else {\n return true;\n }\n }\n\n private:\n \/\/! total size currently read\n size_t size_ = 0;\n\n \/\/! functional object to call once data is complete\n AsyncReadCallback callback_;\n\n \/\/! Receive buffer\n Buffer buffer_;\n };\n\n \/\/! deque of asynchronous readers\n std::deque<AsyncReadBuffer> async_read_;\n\n \/**************************************************************************\/\n\n class AsyncWriteBuffer {\n public:\n \/\/! Construct buffered writer with callback\n AsyncWriteBuffer(Buffer&& buffer,\n const AsyncWriteCallback& callback)\n : callback_(callback),\n buffer_(std::move(buffer))\n { }\n\n \/\/! Should be called when the socket is writable\n bool operator () (NetConnection& c) {\n int r = c.GetSocket().send_one(\n buffer_.data() + size_, buffer_.size() - size_);\n\n if (r < 0)\n throw Exception(\"AsyncWriteBuffer() error in send\", errno);\n\n size_ += r;\n\n if (size_ == buffer_.size()) {\n if (callback_) callback_(c);\n return false;\n }\n else {\n return true;\n }\n }\n\n private:\n \/\/! total size currently written\n size_t size_ = 0;\n\n \/\/! functional object to call once data is complete\n AsyncWriteCallback callback_;\n\n \/\/! Receive buffer\n Buffer buffer_;\n };\n\n \/\/! deque of asynchronous writers\n std::deque<AsyncWriteBuffer> async_write_;\n\n \/**************************************************************************\/\n\n \/\/! Default exception handler\n static bool ExceptionCallback(NetConnection& s) {\n \/\/ exception on listen socket ?\n throw Exception(\n \"NetDispatcher() exception on socket fd \"\n + std::to_string(s.GetSocket().fd()) + \"!\", errno);\n }\n};\n\n\/\/! \\}\n} \/\/ namespace net\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_NET_DISPATCHER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include <set>\n#include <algorithm>\n#include <numeric>\n\n#include \"Mesh2D.hh\"\n#include \"Mesh3D.hh\"\n\nnamespace Amanzi {\nnamespace AmanziGeometry {\n\nMesh3D::Mesh3D(const Mesh2D * const m_, int n_layers) :\n m(m_),\n current_layer(0),\n total_layers(n_layers),\n datum(m_->datum)\n{\n \/\/ reserve\/allocate space\n Point d(3);\n int n_nodes = m->nnodes*(n_layers+1);\n coords.reserve(n_nodes);\n \n int n_cells = n_layers * m->ncells;\n cell2face.reserve(n_cells);\n\n int n_faces = n_layers * m->nfaces\n + (n_layers+1)*m->ncells;\n face2node.reserve(n_faces);\n\n \/\/ copy the top surface coords\n coords.insert(coords.end(), m->coords.begin(), m->coords.end());\n\n \/\/ create the top layer of faces\n face2node.insert(face2node.end(), m->cell2node.begin(),\n m->cell2node.end());\n up_faces.resize(face2node.size());\n std::iota(up_faces.begin(), up_faces.end(), 0);\n up_nodes.resize(coords.size());\n std::iota(up_nodes.begin(), up_nodes.end(), 0);\n dn_nodes = up_nodes;\n dn_faces = up_faces;\n\n \/\/ create the \"bottom\" sideset\n std::vector<int> bottom_c(m->ncells, -1);\n std::vector<int> bottom_f(m->ncells, 1);\n side_sets.emplace_back(std::make_pair(bottom_c,bottom_f));\n side_sets_id.push_back(1);\n \n \/\/ create the \"surface\" sideset\n side_sets.emplace_back(std::piecewise_construct,\n std::forward_as_tuple(m->ncells, -1),\n std::forward_as_tuple(m->ncells, 0));\n side_sets_id.push_back(2);\n\n \/\/ create an empty \"sides\" sideset\n side_sets.emplace_back(std::make_pair(std::vector<int>(), std::vector<int>()));\n side_sets_id.push_back(3);\n}\n\n\nvoid\nMesh3D::extrude(const std::vector<double>& dz,\n const std::vector<int>& block_ids_) {\n ASSERT(dz.size() == m->coords.size());\n ASSERT(block_ids_.size() == m->cell2node.size());\n\n auto this_layer_sides = std::vector<int>(m->face2node.size(), -1);\n auto node_differs = [this](int n) {return this->dn_nodes[n] != this->up_nodes[n];};\n \n \/\/ shift the up-node coordinates by dz\n for (int n=0; n!=dz.size(); ++n) {\n if (dz[n] > 0.) {\n Point nc(coords[up_nodes[n]]);\n nc[2] -= dz[n];\n coords.emplace_back(std::move(nc));\n dn_nodes[n] = coords.size()-1;\n }\n }\n\n \/\/ add cells, faces\n for (int c=0; c!=m->ncells; ++c) {\n if (std::any_of(m->cell2node[c].begin(), m->cell2node[c].end(),\n node_differs)) {\n \/\/ add the bottom face\n std::vector<int> dn_face;\n for (auto n : m->cell2node[c]) dn_face.emplace_back(dn_nodes[n]);\n int my_dn_f = face2node.size();\n face2node.emplace_back(std::move(dn_face));\n dn_faces[c] = my_dn_f;\n\n \/\/ push back a cell containing the up, dn faces\n auto cell_faces = std::vector<int>{up_faces[c], dn_faces[c]};\n int my_c = cell2face.size();\n\n \/\/ if this is the top cell, put it into the surface side set\n if (side_sets[1].first[c] < 0) side_sets[1].first[c] = my_c;\n \/\/ put this cell into the bottom side set -- will be overwritten if any lower\n side_sets[0].first[c] = my_c;\n\n \/\/ add faces for the sides as needed\n for (auto sf : m->cell2face[c]) {\n int my_f = this_layer_sides[sf];\n\n if (std::any_of(m->face2node[sf].begin(), m->face2node[sf].end(),\n node_differs)) {\n if (my_f < 0) {\n \/\/ may need to create the face\n my_f = face2node.size();\n auto side_nodes = std::vector<int>{ up_nodes[m->face2node[sf][0]], \n up_nodes[m->face2node[sf][1]] };\n if (node_differs(m->face2node[sf][1])) side_nodes.push_back(dn_nodes[m->face2node[sf][1]]);\n if (node_differs(m->face2node[sf][0])) side_nodes.push_back(dn_nodes[m->face2node[sf][0]]);\n face2node.emplace_back(std::move(side_nodes));\n cell_faces.push_back(my_f);\n this_layer_sides[sf] = my_f;\n\n \/\/ check if this is a boundary side, and add it to the side_set if so\n if (m->side_face_counts[sf] == 1) {\n side_sets[2].first.push_back(my_c);\n side_sets[2].second.push_back(cell_faces.size() - 1);\n }\n \n } else {\n \/\/ no need to create the face, but the cell still needs to know it\n cell_faces.push_back(my_f);\n }\n\n }\n }\n\n \/\/ finally add the cell, including a block id\n cell2face.emplace_back(std::move(cell_faces));\n block_ids.push_back(block_ids_[c]);\n }\n }\n\n \/\/ increment the layer metadata\n current_layer++;\n up_nodes = dn_nodes;\n up_faces = dn_faces;\n\n ASSERT(block_ids.size() == cell2face.size());\n std::cout << \"POST-Extruding: currently \" << cell2face.size() << \" cells and \" << face2node.size() << \" faces.\" << std::endl;\n\n}\n\nvoid\nMesh3D::finish() {\n \/\/ flip the bottom faces for proper outward orientation\n for (auto f : dn_faces)\n std::reverse(face2node[f].begin(), face2node[f].end());\n\n \/\/ move the 2d cell sets to face sets on the surface\n std::set<int> set_ids;\n for (auto& part : m->cell_sets) {\n set_ids.insert(part.begin(), part.end());\n }\n\n for (int sid : set_ids) {\n std::vector<int> set_cells;\n for (auto& part : m->cell_sets) {\n for (int c=0; c!=part.size(); ++c) {\n if (part[c] == sid) {\n set_cells.push_back(side_sets[1].first[c]);\n }\n }\n }\n std::vector<int> set_faces(set_cells.size(), 0);\n side_sets.emplace_back(std::make_pair(std::move(set_cells),\n std::move(set_faces)));\n side_sets_id.push_back(sid);\n }\n\n \/\/ check side sets\n std::vector<int> side_face_counts(face2node.size(), 0);\n for (auto& c : cell2face)\n for (auto& f : c)\n side_face_counts[f]++;\n \n for (int lcv_s=0; lcv_s!=side_sets.size(); ++lcv_s) {\n auto& fs = side_sets[lcv_s]; \n for (int i=0; i!=side_sets[lcv_s].first.size(); ++i) {\n int c = fs.first[i];\n int fi = fs.second[i];\n int f = cell2face[c][fi];\n if (side_face_counts[f] != 1) {\n std::cout << \"Face Set \" << side_sets_id[lcv_s] << \": face = \" << f << \" (\" << c << \",\" << fi << \") has been counted \" << side_face_counts[f] << \" times (should be 1)!\" << std::endl;\n }\n }\n }\n}\n\n\n}\n}\n<commit_msg>extra assertions for error checking<commit_after>#include <set>\n#include <algorithm>\n#include <numeric>\n\n#include \"Mesh2D.hh\"\n#include \"Mesh3D.hh\"\n\nnamespace Amanzi {\nnamespace AmanziGeometry {\n\nMesh3D::Mesh3D(const Mesh2D * const m_, int n_layers) :\n m(m_),\n current_layer(0),\n total_layers(n_layers),\n datum(m_->datum)\n{\n \/\/ reserve\/allocate space\n Point d(3);\n int n_nodes = m->nnodes*(n_layers+1);\n coords.reserve(n_nodes);\n \n int n_cells = n_layers * m->ncells;\n cell2face.reserve(n_cells);\n\n int n_faces = n_layers * m->nfaces\n + (n_layers+1)*m->ncells;\n face2node.reserve(n_faces);\n\n \/\/ copy the top surface coords\n coords.insert(coords.end(), m->coords.begin(), m->coords.end());\n\n \/\/ create the top layer of faces\n face2node.insert(face2node.end(), m->cell2node.begin(),\n m->cell2node.end());\n up_faces.resize(face2node.size());\n std::iota(up_faces.begin(), up_faces.end(), 0);\n up_nodes.resize(coords.size());\n std::iota(up_nodes.begin(), up_nodes.end(), 0);\n dn_nodes = up_nodes;\n dn_faces = up_faces;\n\n \/\/ create the \"bottom\" sideset\n std::vector<int> bottom_c(m->ncells, -1);\n std::vector<int> bottom_f(m->ncells, 1);\n side_sets.emplace_back(std::make_pair(bottom_c,bottom_f));\n side_sets_id.push_back(1);\n \n \/\/ create the \"surface\" sideset\n side_sets.emplace_back(std::piecewise_construct,\n std::forward_as_tuple(m->ncells, -1),\n std::forward_as_tuple(m->ncells, 0));\n side_sets_id.push_back(2);\n\n \/\/ create an empty \"sides\" sideset\n side_sets.emplace_back(std::make_pair(std::vector<int>(), std::vector<int>()));\n side_sets_id.push_back(3);\n}\n\n\nvoid\nMesh3D::extrude(const std::vector<double>& dz,\n const std::vector<int>& block_ids_) {\n ASSERT(dz.size() == m->coords.size());\n ASSERT(block_ids_.size() == m->cell2node.size());\n\n auto this_layer_sides = std::vector<int>(m->face2node.size(), -1);\n auto node_differs = [this](int n) {return this->dn_nodes[n] != this->up_nodes[n];};\n auto node_same_horiz = [this](int n) {return coords[this->dn_nodes[n]][0] == coords[this->up_nodes[n]][0]\n && coords[this->dn_nodes[n]][1] == coords[this->up_nodes[n]][1];};\n \n \/\/ shift the up-node coordinates by dz\n for (int n=0; n!=dz.size(); ++n) {\n if (dz[n] > 0.) {\n Point nc(coords[up_nodes[n]]);\n nc[2] -= dz[n];\n coords.emplace_back(std::move(nc));\n dn_nodes[n] = coords.size()-1;\n }\n }\n\n \/\/ add cells, faces\n for (int c=0; c!=m->ncells; ++c) {\n if (std::any_of(m->cell2node[c].begin(), m->cell2node[c].end(),\n node_differs)) {\n \/\/ add the bottom face\n std::vector<int> dn_face;\n for (auto n : m->cell2node[c]) dn_face.emplace_back(dn_nodes[n]);\n int my_dn_f = face2node.size();\n face2node.emplace_back(std::move(dn_face));\n dn_faces[c] = my_dn_f;\n\n \/\/ push back a cell containing the up, dn faces\n auto cell_faces = std::vector<int>{up_faces[c], dn_faces[c]};\n int my_c = cell2face.size();\n\n \/\/ if this is the top cell, put it into the surface side set\n if (side_sets[1].first[c] < 0) side_sets[1].first[c] = my_c;\n \/\/ put this cell into the bottom side set -- will be overwritten if any lower\n side_sets[0].first[c] = my_c;\n\n \/\/ add faces for the sides as needed\n for (auto sf : m->cell2face[c]) {\n int my_f = this_layer_sides[sf];\n\n ASSERT(node_same_horiz(m->face2node[sf][0]));\n ASSERT(node_same_horiz(m->face2node[sf][1]));\n \n if (std::any_of(m->face2node[sf].begin(), m->face2node[sf].end(),\n node_differs)) {\n if (my_f < 0) {\n \/\/ may need to create the face\n my_f = face2node.size();\n auto side_nodes = std::vector<int>{ up_nodes[m->face2node[sf][0]], \n up_nodes[m->face2node[sf][1]] };\n if (node_differs(m->face2node[sf][1])) side_nodes.push_back(dn_nodes[m->face2node[sf][1]]);\n if (node_differs(m->face2node[sf][0])) side_nodes.push_back(dn_nodes[m->face2node[sf][0]]);\n face2node.emplace_back(std::move(side_nodes));\n cell_faces.push_back(my_f);\n this_layer_sides[sf] = my_f;\n\n \/\/ check if this is a boundary side, and add it to the side_set if so\n if (m->side_face_counts[sf] == 1) {\n side_sets[2].first.push_back(my_c);\n side_sets[2].second.push_back(cell_faces.size() - 1);\n }\n \n } else {\n \/\/ no need to create the face, but the cell still needs to know it\n cell_faces.push_back(my_f);\n }\n\n }\n }\n\n \/\/ finally add the cell, including a block id\n cell2face.emplace_back(std::move(cell_faces));\n block_ids.push_back(block_ids_[c]);\n }\n }\n\n \/\/ increment the layer metadata\n current_layer++;\n up_nodes = dn_nodes;\n up_faces = dn_faces;\n\n ASSERT(block_ids.size() == cell2face.size());\n std::cout << \"POST-Extruding: currently \" << cell2face.size() << \" cells and \" << face2node.size() << \" faces.\" << std::endl;\n\n}\n\nvoid\nMesh3D::finish() {\n \/\/ flip the bottom faces for proper outward orientation\n for (auto f : dn_faces)\n std::reverse(face2node[f].begin(), face2node[f].end());\n\n \/\/ move the 2d cell sets to face sets on the surface\n std::set<int> set_ids;\n for (auto& part : m->cell_sets) {\n set_ids.insert(part.begin(), part.end());\n }\n\n for (int sid : set_ids) {\n std::vector<int> set_cells;\n for (auto& part : m->cell_sets) {\n for (int c=0; c!=part.size(); ++c) {\n if (part[c] == sid) {\n set_cells.push_back(side_sets[1].first[c]);\n }\n }\n }\n std::vector<int> set_faces(set_cells.size(), 0);\n side_sets.emplace_back(std::make_pair(std::move(set_cells),\n std::move(set_faces)));\n side_sets_id.push_back(sid);\n }\n\n \/\/ check side sets\n std::vector<int> side_face_counts(face2node.size(), 0);\n for (auto& c : cell2face)\n for (auto& f : c)\n side_face_counts[f]++;\n \n for (int lcv_s=0; lcv_s!=side_sets.size(); ++lcv_s) {\n auto& fs = side_sets[lcv_s]; \n for (int i=0; i!=side_sets[lcv_s].first.size(); ++i) {\n int c = fs.first[i];\n int fi = fs.second[i];\n int f = cell2face[c][fi];\n if (side_face_counts[f] != 1) {\n std::cout << \"Face Set \" << side_sets_id[lcv_s] << \": face = \" << f << \" (\" << c << \",\" << fi << \") has been counted \" << side_face_counts[f] << \" times (should be 1)!\" << std::endl;\n }\n }\n }\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- DWARFDebugRanges.cpp ------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFDebugRanges.h\"\n#include \"DWARFUnit.h\"\n#include \"SymbolFileDWARF.h\"\n#include \"lldb\/Utility\/Stream.h\"\n#include <assert.h>\n\nusing namespace lldb_private;\nusing namespace std;\n\nstatic dw_addr_t GetBaseAddressMarker(uint32_t addr_size) {\n switch(addr_size) {\n case 2:\n return 0xffff;\n case 4:\n return 0xffffffff;\n case 8:\n return 0xffffffffffffffff;\n }\n llvm_unreachable(\"GetBaseAddressMarker unsupported address size.\");\n}\n\nDWARFDebugRanges::DWARFDebugRanges() : m_range_map() {}\n\nvoid DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data) {\n DWARFRangeList range_list;\n lldb::offset_t offset = 0;\n dw_offset_t debug_ranges_offset = offset;\n while (Extract(dwarf2Data, &offset, range_list)) {\n range_list.Sort();\n m_range_map[debug_ranges_offset] = range_list;\n debug_ranges_offset = offset;\n }\n}\n\nbool DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data,\n lldb::offset_t *offset_ptr,\n DWARFRangeList &range_list) {\n range_list.Clear();\n\n lldb::offset_t range_offset = *offset_ptr;\n const DWARFDataExtractor &debug_ranges_data =\n dwarf2Data->get_debug_ranges_data();\n uint32_t addr_size = debug_ranges_data.GetAddressByteSize();\n dw_addr_t base_addr = 0;\n dw_addr_t base_addr_marker = GetBaseAddressMarker(addr_size);\n\n while (\n debug_ranges_data.ValidOffsetForDataOfSize(*offset_ptr, 2 * addr_size)) {\n dw_addr_t begin = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n dw_addr_t end = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n\n if (!begin && !end) {\n \/\/ End of range list\n break;\n }\n\n if (begin == base_addr_marker) {\n base_addr = end;\n continue;\n }\n\n \/\/ Filter out empty ranges\n if (begin < end)\n range_list.Append(DWARFRangeList::Entry(begin + base_addr, end - begin));\n }\n\n \/\/ Make sure we consumed at least something\n return range_offset != *offset_ptr;\n}\n\nvoid DWARFDebugRanges::Dump(Stream &s,\n const DWARFDataExtractor &debug_ranges_data,\n lldb::offset_t *offset_ptr,\n dw_addr_t cu_base_addr) {\n uint32_t addr_size = s.GetAddressByteSize();\n\n dw_addr_t base_addr = cu_base_addr;\n while (\n debug_ranges_data.ValidOffsetForDataOfSize(*offset_ptr, 2 * addr_size)) {\n dw_addr_t begin = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n dw_addr_t end = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n \/\/ Extend 4 byte addresses that consists of 32 bits of 1's to be 64 bits of\n \/\/ ones\n if (begin == 0xFFFFFFFFull && addr_size == 4)\n begin = LLDB_INVALID_ADDRESS;\n\n s.Indent();\n if (begin == 0 && end == 0) {\n s.PutCString(\" End\");\n break;\n } else if (begin == LLDB_INVALID_ADDRESS) {\n \/\/ A base address selection entry\n base_addr = end;\n s.Address(base_addr, sizeof(dw_addr_t), \" Base address = \");\n } else {\n \/\/ Convert from offset to an address\n dw_addr_t begin_addr = begin + base_addr;\n dw_addr_t end_addr = end + base_addr;\n\n s.AddressRange(begin_addr, end_addr, sizeof(dw_addr_t), NULL);\n }\n }\n}\n\nbool DWARFDebugRanges::FindRanges(const DWARFUnit *cu,\n dw_offset_t debug_ranges_offset,\n DWARFRangeList &range_list) const {\n dw_addr_t debug_ranges_address = cu->GetRangesBase() + debug_ranges_offset;\n range_map_const_iterator pos = m_range_map.find(debug_ranges_address);\n if (pos != m_range_map.end()) {\n range_list = pos->second;\n\n \/\/ All DW_AT_ranges are relative to the base address of the compile\n \/\/ unit. We add the compile unit base address to make sure all the\n \/\/ addresses are properly fixed up.\n range_list.Slide(cu->GetBaseAddress());\n return true;\n }\n return false;\n}\n\nbool DWARFDebugRngLists::ExtractRangeList(\n const DWARFDataExtractor &data, uint8_t addrSize,\n lldb::offset_t *offset_ptr, std::vector<RngListEntry> &rangeList) {\n rangeList.clear();\n\n bool error = false;\n while (!error) {\n switch (data.GetU8(offset_ptr)) {\n case DW_RLE_end_of_list:\n return true;\n\n case DW_RLE_start_length: {\n dw_addr_t begin = data.GetMaxU64(offset_ptr, addrSize);\n dw_addr_t len = data.GetULEB128(offset_ptr);\n rangeList.push_back({DW_RLE_start_length, begin, len});\n break;\n }\n\n case DW_RLE_start_end: {\n dw_addr_t begin = data.GetMaxU64(offset_ptr, addrSize);\n dw_addr_t end = data.GetMaxU64(offset_ptr, addrSize);\n rangeList.push_back({DW_RLE_start_end, begin, end});\n break;\n }\n\n case DW_RLE_base_address: {\n dw_addr_t base = data.GetMaxU64(offset_ptr, addrSize);\n rangeList.push_back({DW_RLE_base_address, base, 0});\n break;\n }\n\n case DW_RLE_offset_pair: {\n dw_addr_t begin = data.GetULEB128(offset_ptr);\n dw_addr_t end = data.GetULEB128(offset_ptr);\n rangeList.push_back({DW_RLE_offset_pair, begin, end});\n break;\n }\n\n default:\n \/\/ Next encodings are not yet supported:\n \/\/ DW_RLE_base_addressx, DW_RLE_startx_endx, DW_RLE_startx_length.\n lldbassert(0 && \"unknown range list entry encoding\");\n error = true;\n }\n }\n\n return false;\n}\n\nbool DWARFDebugRngLists::FindRanges(const DWARFUnit *cu,\n dw_offset_t debug_ranges_offset,\n DWARFRangeList &range_list) const {\n range_list.Clear();\n dw_addr_t debug_ranges_address = cu->GetRangesBase() + debug_ranges_offset;\n auto pos = m_range_map.find(debug_ranges_address);\n if (pos != m_range_map.end()) {\n dw_addr_t BaseAddr = cu->GetBaseAddress();\n for (const RngListEntry &E : pos->second) {\n switch (E.encoding) {\n case DW_RLE_start_length:\n range_list.Append(DWARFRangeList::Entry(E.value0, E.value1));\n break;\n case DW_RLE_base_address:\n BaseAddr = E.value0;\n break;\n case DW_RLE_start_end:\n range_list.Append(DWARFRangeList::Entry(E.value0, E.value1 - E.value0));\n break;\n case DW_RLE_offset_pair:\n range_list.Append(\n DWARFRangeList::Entry(BaseAddr + E.value0, E.value1 - E.value0));\n break;\n default:\n llvm_unreachable(\"unexpected encoding\");\n }\n }\n return true;\n }\n return false;\n}\n\nvoid DWARFDebugRngLists::Extract(SymbolFileDWARF *dwarf2Data) {\n const DWARFDataExtractor &data = dwarf2Data->get_debug_rnglists_data();\n lldb::offset_t offset = 0;\n\n uint64_t length = data.GetU32(&offset);\n bool isDwarf64 = false;\n if (length == 0xffffffff) {\n length = data.GetU64(&offset);\n isDwarf64 = true;\n }\n lldb::offset_t end = offset + length;\n\n \/\/ Check version.\n if (data.GetU16(&offset) < 5)\n return;\n\n uint8_t addrSize = data.GetU8(&offset);\n\n \/\/ We do not support non-zero segment selector size.\n if (data.GetU8(&offset) != 0) {\n lldbassert(0 && \"not implemented\");\n return;\n }\n\n uint32_t offsetsAmount = data.GetU32(&offset);\n for (uint32_t i = 0; i < offsetsAmount; ++i)\n Offsets.push_back(data.GetPointer(&offset));\n\n lldb::offset_t listOffset = offset;\n std::vector<RngListEntry> rangeList;\n while (offset < end && ExtractRangeList(data, addrSize, &offset, rangeList)) {\n m_range_map[listOffset] = rangeList;\n listOffset = offset;\n }\n}\n<commit_msg>[LLDB] - Removed unused variable. NFC.<commit_after>\/\/===-- DWARFDebugRanges.cpp ------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFDebugRanges.h\"\n#include \"DWARFUnit.h\"\n#include \"SymbolFileDWARF.h\"\n#include \"lldb\/Utility\/Stream.h\"\n#include <assert.h>\n\nusing namespace lldb_private;\nusing namespace std;\n\nstatic dw_addr_t GetBaseAddressMarker(uint32_t addr_size) {\n switch(addr_size) {\n case 2:\n return 0xffff;\n case 4:\n return 0xffffffff;\n case 8:\n return 0xffffffffffffffff;\n }\n llvm_unreachable(\"GetBaseAddressMarker unsupported address size.\");\n}\n\nDWARFDebugRanges::DWARFDebugRanges() : m_range_map() {}\n\nvoid DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data) {\n DWARFRangeList range_list;\n lldb::offset_t offset = 0;\n dw_offset_t debug_ranges_offset = offset;\n while (Extract(dwarf2Data, &offset, range_list)) {\n range_list.Sort();\n m_range_map[debug_ranges_offset] = range_list;\n debug_ranges_offset = offset;\n }\n}\n\nbool DWARFDebugRanges::Extract(SymbolFileDWARF *dwarf2Data,\n lldb::offset_t *offset_ptr,\n DWARFRangeList &range_list) {\n range_list.Clear();\n\n lldb::offset_t range_offset = *offset_ptr;\n const DWARFDataExtractor &debug_ranges_data =\n dwarf2Data->get_debug_ranges_data();\n uint32_t addr_size = debug_ranges_data.GetAddressByteSize();\n dw_addr_t base_addr = 0;\n dw_addr_t base_addr_marker = GetBaseAddressMarker(addr_size);\n\n while (\n debug_ranges_data.ValidOffsetForDataOfSize(*offset_ptr, 2 * addr_size)) {\n dw_addr_t begin = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n dw_addr_t end = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n\n if (!begin && !end) {\n \/\/ End of range list\n break;\n }\n\n if (begin == base_addr_marker) {\n base_addr = end;\n continue;\n }\n\n \/\/ Filter out empty ranges\n if (begin < end)\n range_list.Append(DWARFRangeList::Entry(begin + base_addr, end - begin));\n }\n\n \/\/ Make sure we consumed at least something\n return range_offset != *offset_ptr;\n}\n\nvoid DWARFDebugRanges::Dump(Stream &s,\n const DWARFDataExtractor &debug_ranges_data,\n lldb::offset_t *offset_ptr,\n dw_addr_t cu_base_addr) {\n uint32_t addr_size = s.GetAddressByteSize();\n\n dw_addr_t base_addr = cu_base_addr;\n while (\n debug_ranges_data.ValidOffsetForDataOfSize(*offset_ptr, 2 * addr_size)) {\n dw_addr_t begin = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n dw_addr_t end = debug_ranges_data.GetMaxU64(offset_ptr, addr_size);\n \/\/ Extend 4 byte addresses that consists of 32 bits of 1's to be 64 bits of\n \/\/ ones\n if (begin == 0xFFFFFFFFull && addr_size == 4)\n begin = LLDB_INVALID_ADDRESS;\n\n s.Indent();\n if (begin == 0 && end == 0) {\n s.PutCString(\" End\");\n break;\n } else if (begin == LLDB_INVALID_ADDRESS) {\n \/\/ A base address selection entry\n base_addr = end;\n s.Address(base_addr, sizeof(dw_addr_t), \" Base address = \");\n } else {\n \/\/ Convert from offset to an address\n dw_addr_t begin_addr = begin + base_addr;\n dw_addr_t end_addr = end + base_addr;\n\n s.AddressRange(begin_addr, end_addr, sizeof(dw_addr_t), NULL);\n }\n }\n}\n\nbool DWARFDebugRanges::FindRanges(const DWARFUnit *cu,\n dw_offset_t debug_ranges_offset,\n DWARFRangeList &range_list) const {\n dw_addr_t debug_ranges_address = cu->GetRangesBase() + debug_ranges_offset;\n range_map_const_iterator pos = m_range_map.find(debug_ranges_address);\n if (pos != m_range_map.end()) {\n range_list = pos->second;\n\n \/\/ All DW_AT_ranges are relative to the base address of the compile\n \/\/ unit. We add the compile unit base address to make sure all the\n \/\/ addresses are properly fixed up.\n range_list.Slide(cu->GetBaseAddress());\n return true;\n }\n return false;\n}\n\nbool DWARFDebugRngLists::ExtractRangeList(\n const DWARFDataExtractor &data, uint8_t addrSize,\n lldb::offset_t *offset_ptr, std::vector<RngListEntry> &rangeList) {\n rangeList.clear();\n\n bool error = false;\n while (!error) {\n switch (data.GetU8(offset_ptr)) {\n case DW_RLE_end_of_list:\n return true;\n\n case DW_RLE_start_length: {\n dw_addr_t begin = data.GetMaxU64(offset_ptr, addrSize);\n dw_addr_t len = data.GetULEB128(offset_ptr);\n rangeList.push_back({DW_RLE_start_length, begin, len});\n break;\n }\n\n case DW_RLE_start_end: {\n dw_addr_t begin = data.GetMaxU64(offset_ptr, addrSize);\n dw_addr_t end = data.GetMaxU64(offset_ptr, addrSize);\n rangeList.push_back({DW_RLE_start_end, begin, end});\n break;\n }\n\n case DW_RLE_base_address: {\n dw_addr_t base = data.GetMaxU64(offset_ptr, addrSize);\n rangeList.push_back({DW_RLE_base_address, base, 0});\n break;\n }\n\n case DW_RLE_offset_pair: {\n dw_addr_t begin = data.GetULEB128(offset_ptr);\n dw_addr_t end = data.GetULEB128(offset_ptr);\n rangeList.push_back({DW_RLE_offset_pair, begin, end});\n break;\n }\n\n default:\n \/\/ Next encodings are not yet supported:\n \/\/ DW_RLE_base_addressx, DW_RLE_startx_endx, DW_RLE_startx_length.\n lldbassert(0 && \"unknown range list entry encoding\");\n error = true;\n }\n }\n\n return false;\n}\n\nbool DWARFDebugRngLists::FindRanges(const DWARFUnit *cu,\n dw_offset_t debug_ranges_offset,\n DWARFRangeList &range_list) const {\n range_list.Clear();\n dw_addr_t debug_ranges_address = cu->GetRangesBase() + debug_ranges_offset;\n auto pos = m_range_map.find(debug_ranges_address);\n if (pos != m_range_map.end()) {\n dw_addr_t BaseAddr = cu->GetBaseAddress();\n for (const RngListEntry &E : pos->second) {\n switch (E.encoding) {\n case DW_RLE_start_length:\n range_list.Append(DWARFRangeList::Entry(E.value0, E.value1));\n break;\n case DW_RLE_base_address:\n BaseAddr = E.value0;\n break;\n case DW_RLE_start_end:\n range_list.Append(DWARFRangeList::Entry(E.value0, E.value1 - E.value0));\n break;\n case DW_RLE_offset_pair:\n range_list.Append(\n DWARFRangeList::Entry(BaseAddr + E.value0, E.value1 - E.value0));\n break;\n default:\n llvm_unreachable(\"unexpected encoding\");\n }\n }\n return true;\n }\n return false;\n}\n\nvoid DWARFDebugRngLists::Extract(SymbolFileDWARF *dwarf2Data) {\n const DWARFDataExtractor &data = dwarf2Data->get_debug_rnglists_data();\n lldb::offset_t offset = 0;\n\n uint64_t length = data.GetU32(&offset);\n if (length == 0xffffffff)\n length = data.GetU64(&offset);\n lldb::offset_t end = offset + length;\n\n \/\/ Check version.\n if (data.GetU16(&offset) < 5)\n return;\n\n uint8_t addrSize = data.GetU8(&offset);\n\n \/\/ We do not support non-zero segment selector size.\n if (data.GetU8(&offset) != 0) {\n lldbassert(0 && \"not implemented\");\n return;\n }\n\n uint32_t offsetsAmount = data.GetU32(&offset);\n for (uint32_t i = 0; i < offsetsAmount; ++i)\n Offsets.push_back(data.GetPointer(&offset));\n\n lldb::offset_t listOffset = offset;\n std::vector<RngListEntry> rangeList;\n while (offset < end && ExtractRangeList(data, addrSize, &offset, rangeList)) {\n m_range_map[listOffset] = rangeList;\n listOffset = offset;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016-present, Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"caffe2\/operators\/jsd_op.h\"\n\nnamespace caffe2 {\n\nnamespace {\n\nstatic constexpr float kLOG_THRESHOLD() {\n return 1e-20;\n}\n\ninline float logit(float p) {\n \/\/ it computes log(p \/ (1-p))\n \/\/ to avoid numeric issue, hard code p log(p) when p approaches 0\n float x = std::min(std::max(p, kLOG_THRESHOLD()), 1 - kLOG_THRESHOLD());\n return -log(1. \/ x - 1.);\n}\n\ninline float entropy(float p) {\n if (p < kLOG_THRESHOLD() || 1 - p < kLOG_THRESHOLD()) {\n return 0.;\n } else {\n float q = 1 - p;\n return -p * log(p) - q * log(q);\n }\n}\n} \/\/ namespace\n\ntemplate <>\nbool BernoulliJSDOp<float, CPUContext>::RunOnDevice() {\n auto& X = Input(0); \/\/ predicted probabilities\n auto& T = Input(1); \/\/ target probabilities\n auto* L = Output(0); \/\/ JSD loss output\n int N = X.size();\n CAFFE_ENFORCE_EQ(T.size(), N);\n L->Resize(N);\n auto* x_data = X.data<float>();\n auto* t_data = T.data<float>();\n auto* l_data = L->mutable_data<float>();\n for (int i = 0; i < N; i++) {\n auto p_mdl = x_data[i];\n auto p_emp = t_data[i];\n auto p_avg = (p_mdl + p_emp) \/ 2.;\n auto jsd = entropy(p_avg) - (entropy(p_mdl) + entropy(p_emp)) \/ 2.;\n l_data[i] = jsd;\n }\n return true;\n}\n\ntemplate <>\nbool BernoulliJSDGradientOp<float, CPUContext>::RunOnDevice() {\n auto& go = Input(0);\n auto& X = Input(1);\n auto& T = Input(2);\n auto* gi = Output(0);\n int N = X.size();\n gi->Resize(N);\n auto* go_data = go.data<float>();\n auto* x_data = X.data<float>();\n auto* t_data = T.data<float>();\n auto* gi_data = gi->mutable_data<float>();\n for (int i = 0; i < N; i++) {\n auto p_mdl = x_data[i];\n auto p_emp = t_data[i];\n auto p_avg = (p_mdl + p_emp) \/ 2.;\n auto g_jsd = (logit(p_mdl) - logit(p_avg)) \/ 2.;\n gi_data[i] = go_data[i] * g_jsd;\n }\n return true;\n}\nREGISTER_CPU_OPERATOR(BernoulliJSD, BernoulliJSDOp<float, CPUContext>);\nREGISTER_CPU_OPERATOR(\n BernoulliJSDGradient,\n BernoulliJSDGradientOp<float, CPUContext>);\nOPERATOR_SCHEMA(BernoulliJSD)\n .NumInputs(2)\n .NumOutputs(1)\n .SetDoc(R\"DOC(\nComputes the Jensen-Shannon divergence (JSD) between two Bernoulli distributions\nwhere each is parametrized by a single probability.\n)DOC\")\n .Input(0, \"X\", \"array of probabilities for prediction\")\n .Input(0, \"T\", \"array of probabilities for target\")\n .Output(0, \"L\", \"array of JSD losses\");\nOPERATOR_SCHEMA(BernoulliJSDGradient).NumInputs(3).NumOutputs(1);\n\nclass GetBernoulliJSDGradient : public GradientMakerBase {\n using GradientMakerBase::GradientMakerBase;\n vector<OperatorDef> GetGradientDefs() override {\n return SingleGradientDef(\n \"BernoulliJSDGradient\",\n \"\",\n vector<string>{GO(0), I(0), I(1)},\n vector<string>{GI(0)});\n }\n};\nREGISTER_GRADIENT(BernoulliJSD, GetBernoulliJSDGradient);\n\n} \/\/ namespace caffe2\n<commit_msg>[GanH\/Easy]Fix blob dim<commit_after>\/**\n * Copyright (c) 2016-present, Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"caffe2\/operators\/jsd_op.h\"\n\nnamespace caffe2 {\n\nnamespace {\n\nstatic constexpr float kLOG_THRESHOLD() {\n return 1e-20;\n}\n\ninline float logit(float p) {\n \/\/ it computes log(p \/ (1-p))\n \/\/ to avoid numeric issue, hard code p log(p) when p approaches 0\n float x = std::min(std::max(p, kLOG_THRESHOLD()), 1 - kLOG_THRESHOLD());\n return -log(1. \/ x - 1.);\n}\n\ninline float entropy(float p) {\n if (p < kLOG_THRESHOLD() || 1 - p < kLOG_THRESHOLD()) {\n return 0.;\n } else {\n float q = 1 - p;\n return -p * log(p) - q * log(q);\n }\n}\n} \/\/ namespace\n\ntemplate <>\nbool BernoulliJSDOp<float, CPUContext>::RunOnDevice() {\n auto& X = Input(0); \/\/ predicted probabilities\n auto& T = Input(1); \/\/ target probabilities\n auto* L = Output(0); \/\/ JSD loss output\n int N = X.size();\n CAFFE_ENFORCE_EQ(T.size(), N);\n L->ResizeLike(X);\n auto* x_data = X.data<float>();\n auto* t_data = T.data<float>();\n auto* l_data = L->mutable_data<float>();\n for (int i = 0; i < N; i++) {\n auto p_mdl = x_data[i];\n auto p_emp = t_data[i];\n auto p_avg = (p_mdl + p_emp) \/ 2.;\n auto jsd = entropy(p_avg) - (entropy(p_mdl) + entropy(p_emp)) \/ 2.;\n l_data[i] = jsd;\n }\n return true;\n}\n\ntemplate <>\nbool BernoulliJSDGradientOp<float, CPUContext>::RunOnDevice() {\n auto& go = Input(0);\n auto& X = Input(1);\n auto& T = Input(2);\n auto* gi = Output(0);\n int N = X.size();\n gi->ResizeLike(X);\n auto* go_data = go.data<float>();\n auto* x_data = X.data<float>();\n auto* t_data = T.data<float>();\n auto* gi_data = gi->mutable_data<float>();\n for (int i = 0; i < N; i++) {\n auto p_mdl = x_data[i];\n auto p_emp = t_data[i];\n auto p_avg = (p_mdl + p_emp) \/ 2.;\n auto g_jsd = (logit(p_mdl) - logit(p_avg)) \/ 2.;\n gi_data[i] = go_data[i] * g_jsd;\n }\n return true;\n}\nREGISTER_CPU_OPERATOR(BernoulliJSD, BernoulliJSDOp<float, CPUContext>);\nREGISTER_CPU_OPERATOR(\n BernoulliJSDGradient,\n BernoulliJSDGradientOp<float, CPUContext>);\nOPERATOR_SCHEMA(BernoulliJSD)\n .NumInputs(2)\n .NumOutputs(1)\n .SetDoc(R\"DOC(\nComputes the Jensen-Shannon divergence (JSD) between two Bernoulli distributions\nwhere each is parametrized by a single probability.\n)DOC\")\n .Input(0, \"X\", \"array of probabilities for prediction\")\n .Input(0, \"T\", \"array of probabilities for target\")\n .Output(0, \"L\", \"array of JSD losses\");\nOPERATOR_SCHEMA(BernoulliJSDGradient).NumInputs(3).NumOutputs(1);\n\nclass GetBernoulliJSDGradient : public GradientMakerBase {\n using GradientMakerBase::GradientMakerBase;\n vector<OperatorDef> GetGradientDefs() override {\n return SingleGradientDef(\n \"BernoulliJSDGradient\",\n \"\",\n vector<string>{GO(0), I(0), I(1)},\n vector<string>{GI(0)});\n }\n};\nREGISTER_GRADIENT(BernoulliJSD, GetBernoulliJSDGradient);\n\n} \/\/ namespace caffe2\n<|endoftext|>"} {"text":"<commit_before>\/*\n Colour ASCII art rendering support for Crystal Space 3D library\n Copyright (C) 2005 by dr.W.C.A. Wijngaards\n Based on aalib canvas by Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include <stdarg.h>\n#include <stdlib.h>\n#include <limits.h>\n#include \"csqint.h\"\n\n#include \"csgeom\/csrect.h\"\n#include \"csgfx\/rgbpixel.h\"\n#include \"csutil\/cfgacc.h\"\n#include \"iutil\/cfgfile.h\"\n#include \"iutil\/event.h\"\n#include \"iutil\/eventq.h\"\n#include \"iutil\/objreg.h\"\n#include \"ivaria\/reporter.h\"\n\n#include \"cscaca.h\"\n\n\/\/-------------------------------------------------------- csGraphics2DCaca ---\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_FACTORY (csGraphics2DCaca)\n\ncsGraphics2DCaca::csGraphics2DCaca (iBase *iParent) : \n scfImplementationType (this, iParent), cucul_canvas (0), dither (0),\n caca_display (0)\n{\n EventOutlet = 0;\n Memory = 0;\n}\n\ncsGraphics2DCaca::~csGraphics2DCaca (void)\n{\n Close ();\n}\n\nbool csGraphics2DCaca::Initialize (iObjectRegistry *object_reg)\n{\n if (!csGraphics2D::Initialize (object_reg))\n return false;\n\n csConfigAccess config;\n config.AddConfig(object_reg, \"\/config\/cacacanvas.cfg\");\n config.AddConfig(object_reg, \"\/config\/video.cfg\");\n\n \/\/ Load settings from config file and setup the aa_defparams structure\n HardwareCursor = config->GetBool (\"Video.SystemMouseCursor\", true);\n\n \/\/ set internal render format\n Depth = 32;\n pfmt.RedMask = 0xff << 16;\n pfmt.GreenMask = 0xff << 8;\n pfmt.BlueMask = 0xff;\n pfmt.AlphaMask = 0;\n pfmt.PalEntries = 0;\n pfmt.PixelBytes = 4;\n pfmt.complete ();\n _GetPixelAt = GetPixelAt32;\n\n \/\/ create event outlet\n csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (object_reg);\n if (q != 0)\n {\n if (!EventOutlet.IsValid())\n EventOutlet = q->CreateEventOutlet (this);\n }\n return true;\n}\n\nbool csGraphics2DCaca::Open ()\n{\n if (is_open) return true;\n\n csConfigAccess config;\n config.AddConfig(object_reg, \"\/config\/cacacanvas.cfg\");\n config.AddConfig(object_reg, \"\/config\/video.cfg\");\n\n if(config->KeyExists(\"Video.ASCII.Console.Size\"))\n CS::Utility::setenv (\"CACA_GEOMETRY\", \n config->GetStr(\"Video.ASCII.Console.Size\"), false);\n if(config->KeyExists(\"Video.ASCII.Console.Driver\"))\n CS::Utility::setenv (\"CACA_DRIVER\", \n config->GetStr(\"Video.ASCII.Console.Driver\", \"x11\"), false);\n if(config->KeyExists(\"Video.ASCII.Console.Font\"))\n CS::Utility::setenv (\"CACA_FONT\", \n config->GetStr(\"Video.ASCII.Console.Font\", \"fixed\"), false);\n \n fbWidth = config->GetInt(\"Video.Ascii.Offscreen.Width\", 320);\n fbHeight = config->GetInt(\"Video.Ascii.Offscreen.Height\", 240);\n \n cucul_canvas = cucul_create_canvas (0, 0);\n if (cucul_canvas == 0) return false;\n caca_display = caca_create_display (cucul_canvas);\n if (caca_display == 0)\n return false;\n cucul_clear_canvas (cucul_canvas);\n \n dither = cucul_create_dither (Depth, fbWidth, fbHeight, \n fbWidth*pfmt.PixelBytes, pfmt.RedMask, pfmt.GreenMask, \n pfmt.BlueMask, pfmt.AlphaMask);\n if (dither == 0)\n return false;\n if(config->KeyExists(\"Video.ASCII.Console.AntiAlias\"))\n cucul_set_dither_antialias (dither, \n config->GetStr(\"Video.ASCII.Console.AntiAlias\"));\n if(config->KeyExists(\"Video.ASCII.Console.Dither\"))\n cucul_set_dither_mode (dither, \n config->GetStr(\"Video.ASCII.Console.Dither\"));\n \n caca_set_display_title (caca_display, win_title);\n \n Memory = new unsigned char[ pfmt.PixelBytes*fbWidth*fbHeight ];\n \n\n return csGraphics2D::Open ();\n}\n\nvoid csGraphics2DCaca::Close ()\n{\n if (dither)\n {\n cucul_free_dither (dither);\n dither = 0;\n }\n if(caca_display) \n {\n caca_free_display(caca_display);\n caca_display = 0;\n }\n if (cucul_canvas)\n {\n cucul_free_canvas (cucul_canvas);\n cucul_canvas = 0;\n }\n if(Memory) delete[] Memory;\n Memory = 0;\n \n if (!is_open) return;\n csGraphics2D::Close ();\n}\n\nint csGraphics2DCaca::MapKey(int raw)\n{\n\n switch(raw)\n {\n case CACA_KEY_UNKNOWN: return 0;\n case CACA_KEY_BACKSPACE : return CSKEY_BACKSPACE;\n case CACA_KEY_TAB : return CSKEY_TAB;\n case CACA_KEY_RETURN : return CSKEY_ENTER;\n case CACA_KEY_PAUSE : return CSKEY_PAUSE;\n case CACA_KEY_ESCAPE : return CSKEY_ESC;\n case CACA_KEY_DELETE : return CSKEY_DEL;\n case CACA_KEY_UP : return CSKEY_UP;\n case CACA_KEY_DOWN : return CSKEY_DOWN;\n case CACA_KEY_LEFT : return CSKEY_LEFT;\n case CACA_KEY_RIGHT : return CSKEY_RIGHT;\n case CACA_KEY_INSERT : return CSKEY_INS;\n case CACA_KEY_HOME : return CSKEY_HOME;\n case CACA_KEY_END : return CSKEY_END;\n case CACA_KEY_PAGEUP : return CSKEY_PGUP;\n case CACA_KEY_PAGEDOWN : return CSKEY_PGDN;\n case CACA_KEY_F1 : return CSKEY_F1;\n case CACA_KEY_F2 : return CSKEY_F2;\n case CACA_KEY_F3 : return CSKEY_F3;\n case CACA_KEY_F4 : return CSKEY_F4;\n case CACA_KEY_F5 : return CSKEY_F5;\n case CACA_KEY_F6 : return CSKEY_F6;\n case CACA_KEY_F7 : return CSKEY_F7;\n case CACA_KEY_F8 : return CSKEY_F8;\n case CACA_KEY_F9 : return CSKEY_F9;\n case CACA_KEY_F10 : return CSKEY_F10;\n case CACA_KEY_F11 : return CSKEY_F11;\n case CACA_KEY_F12 : return CSKEY_F12;\n case CACA_KEY_F13 : return 0; \/\/ no CSKEY for this\n case CACA_KEY_F14 : return 0; \/\/ no CSKEY for this\n case CACA_KEY_F15 : return 0; \/\/ no CSKEY for this\n default:\n return raw;\n }\n}\n\nvoid csGraphics2DCaca::Print (csRect const* area)\n{\n cucul_dither_bitmap (cucul_canvas, 0, 0,\n cucul_get_canvas_width (cucul_canvas), \n cucul_get_canvas_height (cucul_canvas), dither, Memory);\n caca_refresh_display (caca_display);\n\n \/* Get all events from keyboard and mouse and put them into system queue *\/\n caca_event_t event;\n while (caca_get_event (caca_display, caca_event::CACA_EVENT_ANY, &event, 0))\n {\n switch(event.type)\n {\n case caca_event::CACA_EVENT_KEY_PRESS:\n case caca_event::CACA_EVENT_KEY_RELEASE:\n {\n utf32_char raw, cooked;\n if (event.data.key.utf32 != 0)\n raw = cooked = event.data.key.utf32;\n else\n raw = cooked = MapKey (event.data.key.ch);\n\tEventOutlet->Key (raw, cooked, \n\t (event.type == caca_event::CACA_EVENT_KEY_PRESS));\n }\n break;\n case caca_event::CACA_EVENT_MOUSE_PRESS:\n EventOutlet->Mouse (event.data.mouse.button- 1, true,\n caca_get_mouse_x (caca_display), caca_get_mouse_y (caca_display));\n break;\n case caca_event::CACA_EVENT_MOUSE_RELEASE:\n EventOutlet->Mouse (event.data.mouse.button - 1, false,\n caca_get_mouse_x (caca_display), caca_get_mouse_y (caca_display));\n break;\n case caca_event::CACA_EVENT_MOUSE_MOTION:\n EventOutlet->Mouse (csmbNone, false, \n event.data.mouse.x, event.data.mouse.y);\n break;\n default:\n break;\n }\n }\n}\n\nbool csGraphics2DCaca::BeginDraw ()\n{\n csGraphics2D::BeginDraw ();\n return true;\n}\n\nvoid csGraphics2DCaca::FinishDraw ()\n{\n csGraphics2D::FinishDraw ();\n}\n\nvoid csGraphics2DCaca::SetTitle(const char* title)\n{\n caca_set_display_title (caca_display, title);\n}\n<commit_msg>Missing include for setenv<commit_after>\/*\n Colour ASCII art rendering support for Crystal Space 3D library\n Copyright (C) 2005 by dr.W.C.A. Wijngaards\n Based on aalib canvas by Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include <stdarg.h>\n#include <stdlib.h>\n#include <limits.h>\n#include \"csqint.h\"\n\n#include \"csgeom\/csrect.h\"\n#include \"csgfx\/rgbpixel.h\"\n#include \"csutil\/cfgacc.h\"\n#include \"csutil\/setenv.h\"\n#include \"iutil\/cfgfile.h\"\n#include \"iutil\/event.h\"\n#include \"iutil\/eventq.h\"\n#include \"iutil\/objreg.h\"\n#include \"ivaria\/reporter.h\"\n\n#include \"cscaca.h\"\n\n\/\/-------------------------------------------------------- csGraphics2DCaca ---\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_FACTORY (csGraphics2DCaca)\n\ncsGraphics2DCaca::csGraphics2DCaca (iBase *iParent) : \n scfImplementationType (this, iParent), cucul_canvas (0), dither (0),\n caca_display (0)\n{\n EventOutlet = 0;\n Memory = 0;\n}\n\ncsGraphics2DCaca::~csGraphics2DCaca (void)\n{\n Close ();\n}\n\nbool csGraphics2DCaca::Initialize (iObjectRegistry *object_reg)\n{\n if (!csGraphics2D::Initialize (object_reg))\n return false;\n\n csConfigAccess config;\n config.AddConfig(object_reg, \"\/config\/cacacanvas.cfg\");\n config.AddConfig(object_reg, \"\/config\/video.cfg\");\n\n \/\/ Load settings from config file and setup the aa_defparams structure\n HardwareCursor = config->GetBool (\"Video.SystemMouseCursor\", true);\n\n \/\/ set internal render format\n Depth = 32;\n pfmt.RedMask = 0xff << 16;\n pfmt.GreenMask = 0xff << 8;\n pfmt.BlueMask = 0xff;\n pfmt.AlphaMask = 0;\n pfmt.PalEntries = 0;\n pfmt.PixelBytes = 4;\n pfmt.complete ();\n _GetPixelAt = GetPixelAt32;\n\n \/\/ create event outlet\n csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (object_reg);\n if (q != 0)\n {\n if (!EventOutlet.IsValid())\n EventOutlet = q->CreateEventOutlet (this);\n }\n return true;\n}\n\nbool csGraphics2DCaca::Open ()\n{\n if (is_open) return true;\n\n csConfigAccess config;\n config.AddConfig(object_reg, \"\/config\/cacacanvas.cfg\");\n config.AddConfig(object_reg, \"\/config\/video.cfg\");\n\n if(config->KeyExists(\"Video.ASCII.Console.Size\"))\n CS::Utility::setenv (\"CACA_GEOMETRY\", \n config->GetStr(\"Video.ASCII.Console.Size\"), false);\n if(config->KeyExists(\"Video.ASCII.Console.Driver\"))\n CS::Utility::setenv (\"CACA_DRIVER\", \n config->GetStr(\"Video.ASCII.Console.Driver\", \"x11\"), false);\n if(config->KeyExists(\"Video.ASCII.Console.Font\"))\n CS::Utility::setenv (\"CACA_FONT\", \n config->GetStr(\"Video.ASCII.Console.Font\", \"fixed\"), false);\n \n fbWidth = config->GetInt(\"Video.Ascii.Offscreen.Width\", 320);\n fbHeight = config->GetInt(\"Video.Ascii.Offscreen.Height\", 240);\n \n cucul_canvas = cucul_create_canvas (0, 0);\n if (cucul_canvas == 0) return false;\n caca_display = caca_create_display (cucul_canvas);\n if (caca_display == 0)\n return false;\n cucul_clear_canvas (cucul_canvas);\n \n dither = cucul_create_dither (Depth, fbWidth, fbHeight, \n fbWidth*pfmt.PixelBytes, pfmt.RedMask, pfmt.GreenMask, \n pfmt.BlueMask, pfmt.AlphaMask);\n if (dither == 0)\n return false;\n if(config->KeyExists(\"Video.ASCII.Console.AntiAlias\"))\n cucul_set_dither_antialias (dither, \n config->GetStr(\"Video.ASCII.Console.AntiAlias\"));\n if(config->KeyExists(\"Video.ASCII.Console.Dither\"))\n cucul_set_dither_mode (dither, \n config->GetStr(\"Video.ASCII.Console.Dither\"));\n \n caca_set_display_title (caca_display, win_title);\n \n Memory = new unsigned char[ pfmt.PixelBytes*fbWidth*fbHeight ];\n \n\n return csGraphics2D::Open ();\n}\n\nvoid csGraphics2DCaca::Close ()\n{\n if (dither)\n {\n cucul_free_dither (dither);\n dither = 0;\n }\n if(caca_display) \n {\n caca_free_display(caca_display);\n caca_display = 0;\n }\n if (cucul_canvas)\n {\n cucul_free_canvas (cucul_canvas);\n cucul_canvas = 0;\n }\n if(Memory) delete[] Memory;\n Memory = 0;\n \n if (!is_open) return;\n csGraphics2D::Close ();\n}\n\nint csGraphics2DCaca::MapKey(int raw)\n{\n\n switch(raw)\n {\n case CACA_KEY_UNKNOWN: return 0;\n case CACA_KEY_BACKSPACE : return CSKEY_BACKSPACE;\n case CACA_KEY_TAB : return CSKEY_TAB;\n case CACA_KEY_RETURN : return CSKEY_ENTER;\n case CACA_KEY_PAUSE : return CSKEY_PAUSE;\n case CACA_KEY_ESCAPE : return CSKEY_ESC;\n case CACA_KEY_DELETE : return CSKEY_DEL;\n case CACA_KEY_UP : return CSKEY_UP;\n case CACA_KEY_DOWN : return CSKEY_DOWN;\n case CACA_KEY_LEFT : return CSKEY_LEFT;\n case CACA_KEY_RIGHT : return CSKEY_RIGHT;\n case CACA_KEY_INSERT : return CSKEY_INS;\n case CACA_KEY_HOME : return CSKEY_HOME;\n case CACA_KEY_END : return CSKEY_END;\n case CACA_KEY_PAGEUP : return CSKEY_PGUP;\n case CACA_KEY_PAGEDOWN : return CSKEY_PGDN;\n case CACA_KEY_F1 : return CSKEY_F1;\n case CACA_KEY_F2 : return CSKEY_F2;\n case CACA_KEY_F3 : return CSKEY_F3;\n case CACA_KEY_F4 : return CSKEY_F4;\n case CACA_KEY_F5 : return CSKEY_F5;\n case CACA_KEY_F6 : return CSKEY_F6;\n case CACA_KEY_F7 : return CSKEY_F7;\n case CACA_KEY_F8 : return CSKEY_F8;\n case CACA_KEY_F9 : return CSKEY_F9;\n case CACA_KEY_F10 : return CSKEY_F10;\n case CACA_KEY_F11 : return CSKEY_F11;\n case CACA_KEY_F12 : return CSKEY_F12;\n case CACA_KEY_F13 : return 0; \/\/ no CSKEY for this\n case CACA_KEY_F14 : return 0; \/\/ no CSKEY for this\n case CACA_KEY_F15 : return 0; \/\/ no CSKEY for this\n default:\n return raw;\n }\n}\n\nvoid csGraphics2DCaca::Print (csRect const* area)\n{\n cucul_dither_bitmap (cucul_canvas, 0, 0,\n cucul_get_canvas_width (cucul_canvas), \n cucul_get_canvas_height (cucul_canvas), dither, Memory);\n caca_refresh_display (caca_display);\n\n \/* Get all events from keyboard and mouse and put them into system queue *\/\n caca_event_t event;\n while (caca_get_event (caca_display, caca_event::CACA_EVENT_ANY, &event, 0))\n {\n switch(event.type)\n {\n case caca_event::CACA_EVENT_KEY_PRESS:\n case caca_event::CACA_EVENT_KEY_RELEASE:\n {\n utf32_char raw, cooked;\n if (event.data.key.utf32 != 0)\n raw = cooked = event.data.key.utf32;\n else\n raw = cooked = MapKey (event.data.key.ch);\n\tEventOutlet->Key (raw, cooked, \n\t (event.type == caca_event::CACA_EVENT_KEY_PRESS));\n }\n break;\n case caca_event::CACA_EVENT_MOUSE_PRESS:\n EventOutlet->Mouse (event.data.mouse.button- 1, true,\n caca_get_mouse_x (caca_display), caca_get_mouse_y (caca_display));\n break;\n case caca_event::CACA_EVENT_MOUSE_RELEASE:\n EventOutlet->Mouse (event.data.mouse.button - 1, false,\n caca_get_mouse_x (caca_display), caca_get_mouse_y (caca_display));\n break;\n case caca_event::CACA_EVENT_MOUSE_MOTION:\n EventOutlet->Mouse (csmbNone, false, \n event.data.mouse.x, event.data.mouse.y);\n break;\n default:\n break;\n }\n }\n}\n\nbool csGraphics2DCaca::BeginDraw ()\n{\n csGraphics2D::BeginDraw ();\n return true;\n}\n\nvoid csGraphics2DCaca::FinishDraw ()\n{\n csGraphics2D::FinishDraw ();\n}\n\nvoid csGraphics2DCaca::SetTitle(const char* title)\n{\n caca_set_display_title (caca_display, title);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALGORITHMIC_SKIP_LIST_HPP\n#define ALGORITHMIC_SKIP_LIST_HPP\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <vector>\n\n\nnamespace algic\n{\n using std::size_t;\n\n template <class T>\n struct node;\n\n\n struct node_base\n {\n node_base(size_t height);\n virtual ~node_base();\n\n size_t height() const;\n node_base* next(size_t level) const;\n void set(size_t level, node_base* nb);\n\n void incHeight();\n\n template <class T>\n node<T>* as()\n {\n return dynamic_cast<node<T>*>(this);\n }\n\n private:\n size_t mHeight;\n node_base** mLinks;\n };\n\n\n template <class T>\n struct node : public node_base\n {\n node(size_t height, T const& t);\n node(size_t height, T&& t);\n ~node();\n\n T& value();\n T const& value() const;\n\n private:\n T* asT();\n T const* asT() const;\n\n char mData[sizeof(T)];\n };\n\n\n \/**********************************************************\/\n \/* implementations *\/\n\n \/**********************************************************\/\n \/* node_base *\/\n node_base::node_base(size_t height)\n : mHeight(height)\n , mLinks(new node_base*[mHeight])\n {\n std::fill(mLinks, mLinks + mHeight, nullptr);\n }\n\n node_base::~node_base()\n {\n delete [] mLinks;\n }\n\n size_t node_base::height() const\n {\n return mHeight;\n }\n\n node_base* node_base::next(size_t level) const\n {\n assert(level < mHeight && \"Index out of range\");\n return mLinks[level];\n }\n\n void node_base::set(size_t level, node_base* nb)\n {\n assert(level < mHeight && \"Index out of range\");\n mLinks[level] = nb;\n }\n\n void node_base::incHeight()\n {\n ++mHeight;\n node_base** newLinks = new node_base*[mHeight];\n std::copy(mLinks, mLinks + mHeight, newLinks);\n delete mLinks;\n mLinks = newLinks;\n mLinks[mHeight - 1] = nullptr;\n }\n \n\n \/**********************************************************\/\n \/* node *\/\n template <class T>\n node<T>::node(size_t height, T const& t)\n : node_base(height)\n {\n new (static_cast<void*>(mData))T(t);\n }\n\n template <class T>\n node<T>::node(size_t height, T&& t)\n : node_base(height)\n {\n new (static_cast<void*>(mData))T(std::move(t));\n }\n\n template <class T>\n node<T>::~node()\n {\n static_cast<T*>(static_cast<void*>(mData))->~T();\n }\n\n template <class T>\n T& node<T>::value()\n {\n return static_cast<T&>(*asT());\n }\n\n template <class T>\n T const& node<T>::value() const\n {\n return static_cast<T const&>(*asT());\n }\n\n template <class T>\n T* node<T>::asT()\n {\n return static_cast<T*>(static_cast<void*>(mData));\n }\n\n template <class T>\n T const* node<T>::asT() const\n {\n return static_cast<T const*>(static_cast<void*>(mData));\n }\n\n\n \/**********************************************************\/\n \/* skip_list *\/\n template <class T, class RandomGen>\n skip_list<T, RandomGen>::skip_list(RandomGen& randGen, float prob)\n : mRand(randGen)\n , mHead(new node_base(1))\n , mProb(prob)\n {\n assert(prob >= 0.0f && \"Probability can't be negative\");\n assert(prob <= 1.0f && \"Probability must be not greater than 1\");\n }\n\n template <class T, class RandomGen>\n skip_list<T, RandomGen>::~skip_list()\n {\n delete mHead;\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::insert(T const& t)\n {\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::remove(T const& t)\n {\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::contains(T const& t)\n {\n size_t const H = mHead->height();\n for (size_t lvl = H - 1; lvl >= 0; --lvl)\n {\n if (node_base* place = findPlace(t, H, lvl, mHead->next(lvl)))\n {\n if (place->as<T>()->value() == t)\n return true;\n else\n return false;\n }\n if (lvl == 0)\n break;\n }\n return false;\n }\n\n template <class T, class RandomGen>\n node_base* skip_list<T, RandomGen>::findPlace(T const& t, size_t height, size_t level, node_base* start)\n {\n if (!start)\n return nullptr;\n \n auto const& val = start->as<T>()->value();\n if (val < t)\n {\n auto res = findPlace(t, height, level, start->next(level));\n if (!res)\n {\n if (level > 0)\n return findPlace(t, height, level - 1, start);\n else\n return start;\n }\n }\n if (val > t)\n return nullptr;\n return start;\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::coin() const\n {\n return mRand() < mProb;\n }\n\n template <class T, class RandomGen>\n size_t skip_list<T, RandomGen>::multiCoin() const\n {\n size_t count{ 0 };\n while (mRand() < mProb)\n ++count;\n return count;\n }\n} \/\/ namespace algic\n\n#endif\n<commit_msg>implemented insert (does not work yet)<commit_after>#ifndef ALGORITHMIC_SKIP_LIST_HPP\n#define ALGORITHMIC_SKIP_LIST_HPP\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <functional>\n#include <list>\n#include <vector>\n\n\nnamespace algic\n{\n using std::size_t;\n\n template <class T>\n struct node;\n\n\n struct node_base\n {\n node_base(size_t height);\n virtual ~node_base();\n\n size_t height() const;\n node_base* next(size_t level) const;\n void set(size_t level, node_base* nb);\n\n void incHeight();\n\n template <class T>\n node<T>* as()\n {\n return dynamic_cast<node<T>*>(this);\n }\n\n private:\n size_t mHeight;\n node_base** mLinks;\n };\n\n\n template <class T>\n struct node : public node_base\n {\n node(size_t height, T const& t);\n node(size_t height, T&& t);\n ~node();\n\n T& value();\n T const& value() const;\n\n private:\n T* asT();\n T const* asT() const;\n\n char mData[sizeof(T)];\n };\n\n template <class T>\n bool less(node_base* node, T const& val)\n {\n if (auto tNode = node->as<T>())\n return std::less<T>()(tNode->value(), val);\n else\n return true;\n }\n\n template <class T>\n bool eq(node_base* node, T const& val)\n {\n if (auto tNode = node->as<T>())\n return std::equal_to<T>()(tNode->value(), val);\n else\n return false;\n }\n\n template <class T>\n bool gt(node_base* node, T const& val)\n {\n if (auto tNode = node->as<T>())\n return std::greater<T>()(tNode->value(), val);\n else\n return false;\n }\n\n\n\n \/**********************************************************\/\n \/* implementations *\/\n\n \/**********************************************************\/\n \/* node_base *\/\n node_base::node_base(size_t height)\n : mHeight(height)\n , mLinks(new node_base*[mHeight])\n {\n std::fill(mLinks, mLinks + mHeight, nullptr);\n }\n\n node_base::~node_base()\n {\n delete [] mLinks;\n }\n\n size_t node_base::height() const\n {\n return mHeight;\n }\n\n node_base* node_base::next(size_t level) const\n {\n assert(level < mHeight && \"Index out of range\");\n return mLinks[level];\n }\n\n void node_base::set(size_t level, node_base* nb)\n {\n assert(level < mHeight && \"Index out of range\");\n mLinks[level] = nb;\n }\n\n void node_base::incHeight()\n {\n ++mHeight;\n node_base** newLinks = new node_base*[mHeight];\n std::copy(mLinks, mLinks + mHeight, newLinks);\n delete mLinks;\n mLinks = newLinks;\n mLinks[mHeight - 1] = nullptr;\n }\n \n\n \/**********************************************************\/\n \/* node *\/\n template <class T>\n node<T>::node(size_t height, T const& t)\n : node_base(height)\n {\n new (static_cast<void*>(mData))T(t);\n }\n\n template <class T>\n node<T>::node(size_t height, T&& t)\n : node_base(height)\n {\n new (static_cast<void*>(mData))T(std::move(t));\n }\n\n template <class T>\n node<T>::~node()\n {\n static_cast<T*>(static_cast<void*>(mData))->~T();\n }\n\n template <class T>\n T& node<T>::value()\n {\n return static_cast<T&>(*asT());\n }\n\n template <class T>\n T const& node<T>::value() const\n {\n return static_cast<T const&>(*asT());\n }\n\n template <class T>\n T* node<T>::asT()\n {\n return static_cast<T*>(static_cast<void*>(mData));\n }\n\n template <class T>\n T const* node<T>::asT() const\n {\n return static_cast<T const*>(static_cast<void*>(mData));\n }\n\n\n \/**********************************************************\/\n \/* skip_list *\/\n template <class T, class RandomGen>\n skip_list<T, RandomGen>::skip_list(RandomGen& randGen, float prob)\n : mRand(randGen)\n , mHead(new node_base(1))\n , mProb(prob)\n {\n assert(prob >= 0.0f && \"Probability can't be negative\");\n assert(prob <= 1.0f && \"Probability must be not greater than 1\");\n }\n\n template <class T, class RandomGen>\n skip_list<T, RandomGen>::~skip_list()\n {\n delete mHead;\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::insert(T const& t)\n {\n size_t const H = mHead->height();\n std::vector<node_base*> visited(H, nullptr);\n\n node_base* curNode = mHead;\n int curLvl = H - 1;\n bool out = false;\n while (!out)\n {\n auto nextNode = curNode->next(curLvl);\n if (nextNode && less(nextNode, t))\n {\n curNode = nextNode;\n continue;\n }\n else if (curLvl >= 0)\n {\n visited[curLvl] = curNode;\n --curLvl;\n if (curLvl < 0)\n {\n if (nextNode && eq(nextNode, t))\n return false;\n curLvl = 0;\n out = true;\n continue;\n }\n }\n }\n\n size_t const newLvl = multiCoin();\n node_base* newNode = new node<T>(newLvl, t);\n if (newLvl > H)\n {\n mHead->incHeight();\n mHead->set(H, newNode);\n }\n\n for (size_t i = 0; i < H - 1; ++i)\n {\n newNode->set(i, visited[i]);\n visited[i]->set(i, newNode);\n }\n return true;\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::remove(T const& t)\n {\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::contains(T const& t)\n {\n size_t const H = mHead->height();\n for (size_t lvl = H - 1; lvl >= 0; --lvl)\n {\n if (node_base* place = findPlace(t, H, lvl, mHead->next(lvl)))\n {\n if (place->as<T>()->value() == t)\n return true;\n else\n return false;\n }\n if (lvl == 0)\n break;\n }\n return false;\n }\n\n template <class T, class RandomGen>\n node_base* skip_list<T, RandomGen>::findPlace(T const& t, size_t height, size_t level, node_base* start)\n {\n if (!start)\n return nullptr;\n \n if (less(start, t))\n {\n auto res = findPlace(t, height, level, start->next(level));\n if (!res)\n {\n if (level > 0)\n return findPlace(t, height, level - 1, start);\n else\n return start;\n }\n }\n if (gt(start, t))\n return nullptr;\n return start;\n }\n\n template <class T, class RandomGen>\n bool skip_list<T, RandomGen>::coin() const\n {\n return mRand() < mProb;\n }\n\n template <class T, class RandomGen>\n size_t skip_list<T, RandomGen>::multiCoin() const\n {\n size_t const maxH{ mHead->height() + 1 };\n size_t count{ 0 };\n while (mRand() < mProb)\n {\n ++count;\n if (count == maxH)\n break;\n }\n return count;\n }\n} \/\/ namespace algic\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"RpcImageServer.h\"\n#include \"ImageServerCfg.h\"\n#include \"ImageProcess.h\"\n#include \"ImageProcessTask.h\"\n#include <image-manager\/ImageServerStorage.h>\n#include <image-manager\/ImageServerRequest.h>\n#include \"errno.h\"\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/thread.hpp>\n#include <glog\/logging.h>\n\n#include <tfs_client_api.h>\n\nusing namespace tfs::client;\nusing namespace tfs::common;\n\nnamespace sf1r\n{\n\nRpcImageServer::RpcImageServer(const std::string& host, uint16_t port, uint32_t threadNum)\n : host_(host)\n , port_(port)\n , threadNum_(threadNum)\n , is_exporting_(false)\n , export_thread_(NULL)\n{\n}\n\nRpcImageServer::~RpcImageServer()\n{\n std::cout << \"~RpcImageServer()\" << std::endl;\n stop();\n}\n\nvoid RpcImageServer::start()\n{\n instance.listen(host_, port_);\n instance.start(threadNum_);\n}\n\nvoid RpcImageServer::join()\n{\n instance.join();\n}\n\nvoid RpcImageServer::run()\n{\n start();\n join();\n}\n\nvoid RpcImageServer::stop()\n{\n instance.end();\n instance.join();\n if(export_thread_)\n {\n export_thread_->interrupt();\n export_thread_->join();\n delete export_thread_;\n }\n}\n\nvoid RpcImageServer::dispatch(msgpack::rpc::request req)\n{\n try\n {\n std::string method;\n req.method().convert(&method);\n\n if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_TEST])\n {\n msgpack::type::tuple<bool> params;\n req.params().convert(¶ms);\n\n req.result(true);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_GET_IMAGE_COLOR])\n {\n msgpack::type::tuple<ImageColorData> params;\n req.params().convert(¶ms);\n ImageColorData& reqdata = params.get<0>();\n\n reqdata.success = ImageServerStorage::get()->GetImageColor(reqdata.img_file, reqdata.result_img_color);\n if(!reqdata.success)\n {\n \/\/ try to recalculate the color\n \/\/std::string picFilePath = ImageServerCfg::get()->getImageFilePath() + \"\/\" + reqdata.img_file;\n char* data = NULL;\n std::size_t datasize = 0;\n if(ImageServerStorage::get()->DownloadImageData(reqdata.img_file, data, datasize))\n {\n int indexCollection[COLOR_RET_NUM];\n bool ret = getImageColor(data, datasize, indexCollection, COLOR_RET_NUM);\n if(ret){\n std::ostringstream oss;\n for(std::size_t i = 0; i < COLOR_RET_NUM - 1; ++i)\n {\n oss << indexCollection[i] << \",\";\n }\n oss << indexCollection[COLOR_RET_NUM - 1]; \n\n reqdata.success = ImageServerStorage::get()->SetImageColor(reqdata.img_file, oss.str());\n reqdata.result_img_color = oss.str();\n \/\/LOG(INFO) << \"got request image color for fileName=\" << reqdata.img_file << \"result:\" <<\n \/\/ oss.str() << std::endl;\n }else{\n LOG(WARNING) << \"getImageColor failed imagePath=\" << reqdata.img_file << std::endl;\n reqdata.success = false;\n }\n delete[] data;\n }\n else\n {\n LOG(INFO) << \"getImage data failed while get image color imagePath=\" << reqdata.img_file << std::endl;\n reqdata.success = false;\n }\n }\n req.result(reqdata);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_UPLOAD_IMAGE])\n {\n struct timeval tv_start, tv_end;\n gettimeofday(&tv_start, NULL);\n LOG(INFO) << \"get upload request : \" << tv_start.tv_sec << endl;\n msgpack::type::tuple<UploadImageData> params;\n req.params().convert(¶ms);\n UploadImageData& reqdata = params.get<0>();\n std::string ret_file;\n if(reqdata.param_type == 0)\n {\n reqdata.success = ImageServerStorage::get()->UploadImageFile(reqdata.img_file, ret_file);\n }\n else if(reqdata.param_type == 1)\n {\n reqdata.success = ImageServerStorage::get()->UploadImageData(reqdata.img_file.data(),\n reqdata.img_file.size(), ret_file);\n }\n else\n {\n reqdata.success = false;\n }\n gettimeofday(&tv_end, NULL);\n int interval = tv_end.tv_sec - tv_start.tv_sec;\n if( interval > 1)\n LOG(WARNING) << \"upload time larger than 1s : \" << interval << endl;\n if(reqdata.success)\n {\n \/\/ write log file\n \/\/\n ofstream ofs;\n try\n {\n ofs.open(ImageServerCfg::get()->getUploadImageLog().c_str(), ofstream::app);\n ofs << ret_file.c_str() << std::endl;\n ofs.close();\n }\n catch(std::exception& e)\n {\n LOG(ERROR) << \"write upload log failed: \" << ret_file << std::endl;\n ofs.close();\n }\n }\n else\n {\n if(reqdata.param_type == 0)\n LOG(WARNING) << \"file upload failed: \" << reqdata.img_file << std::endl;\n else\n LOG(WARNING) << \"image data upload failed: \" << std::endl;\n }\n reqdata.img_file = ret_file;\n req.result(reqdata);\n gettimeofday(&tv_end, NULL);\n LOG(INFO) << \"finish upload request : \" << tv_end.tv_sec << endl;\n interval = tv_end.tv_sec - tv_start.tv_sec;\n if( interval > 1)\n LOG(WARNING) << \"upload time total larger than 1s : \" << interval << endl;\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_DELETE_IMAGE])\n {\n msgpack::type::tuple<DeleteImageData> params;\n req.params().convert(¶ms);\n DeleteImageData& reqdata = params.get<0>();\n reqdata.success = ImageServerStorage::get()->DeleteImage(reqdata.img_file);\n req.result(reqdata);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_EXPORT_IMAGE])\n {\n msgpack::type::tuple<ExportImageData> params;\n req.params().convert(¶ms);\n ExportImageData& reqdata = params.get<0>();\n req.result(reqdata);\n if(is_exporting_)\n {\n LOG(WARNING) << \"image is already exporting! Ignore any more request.\" << std::endl;\n return;\n }\n is_exporting_ = true;\n if(export_thread_)\n {\n delete export_thread_;\n }\n\n export_thread_ = new boost::thread(&RpcImageServer::exportimage, this, \n reqdata.img_log_file, reqdata.out_dir);\n\n }\n else if(method == ImageServerRequest::method_names[ImageServerRequest::METHOD_COMPUTE_IMAGE_COLOR])\n {\n msgpack::type::tuple<ComputeImageColorData> params;\n req.params().convert(¶ms);\n ComputeImageColorData& reqdata = params.get<0>();\n\n Request *image_computereq = new Request;\n image_computereq->filePath = reqdata.filepath;\n image_computereq->filetype = reqdata.filetype;\n LOG(INFO) << \"got image file color computing request:\" << reqdata.filepath << endl;\n MSG msg(image_computereq);\n reqdata.success = true;\n if(!ImageProcessTask::instance()->put(msg)){ \n LOG(ERROR) << \"failed to enqueue fileName:\" << reqdata.filepath << endl;\n reqdata.success = false;\n }\n req.result(reqdata);\n }\n else\n {\n req.error(msgpack::rpc::NO_METHOD_ERROR);\n }\n }\n catch (const msgpack::type_error& e)\n {\n req.error(msgpack::rpc::ARGUMENT_ERROR);\n }\n catch (const std::exception& e)\n {\n req.error(std::string(e.what()));\n }\n}\n\nvoid RpcImageServer::exportimage(const std::string& log_file, const std::string& outdir)\n{\n size_t total_export = 0;\n size_t failed_cnt = 0;\n ifstream ifs;\n ofstream export_log;\n struct timeval tv_start, tv_end;\n try\n {\n ifs.open(log_file.c_str(), ifstream::in);\n export_log.open((outdir + \"\/\" + std::string(\"export.log\")).c_str(), ofstream::app);\n\n gettimeofday(&tv_start, NULL);\n export_log << \" === export start: \" << tv_start.tv_sec << \" === \" << std::endl;\n while(ifs.good())\n {\n ++total_export;\n char file_name[TFS_FILE_LEN];\n ifs.getline(file_name, TFS_FILE_LEN);\n char* buffer = NULL;\n std::size_t buf_size = 0;\n bool ret = ImageServerStorage::get()->DownloadImageData(file_name, buffer, buf_size);\n if(ret)\n {\n ofstream ofs;\n try\n {\n ofs.open((outdir + \"\/\" + file_name).c_str(), ofstream::trunc);\n ofs.write(buffer, buf_size);\n }\n catch(std::exception& e)\n {\n ++failed_cnt;\n export_log << \"export failed (save data to out file error) : \" << e.what() << \",file: \" << file_name << std::endl;\n }\n if(ofs.is_open())\n ofs.close();\n delete[] buffer;\n }\n else\n {\n ++failed_cnt;\n export_log << \"export failed (download error): \" << file_name << std::endl;\n }\n boost::this_thread::interruption_point();\n }\n }\n catch(boost::thread_interrupted& )\n {\n LOG(INFO) << \"exporting aborted. \" << std::endl;\n }\n catch(std::exception& e)\n {\n LOG(WARNING) << \"exception while exporting: \" << e.what() << std::endl;\n }\n if(ifs.is_open())\n {\n ifs.close();\n }\n if(export_log.is_open())\n {\n export_log << \"export finished, total export : \" << total_export << \", failed: \" << failed_cnt << std::endl;\n gettimeofday(&tv_end, NULL);\n export_log << \" === export end: \" << tv_end.tv_sec << \" === \" << std::endl;\n export_log.close();\n }\n is_exporting_ = false;\n}\n\n}\n<commit_msg>tiny log for image server<commit_after>#include \"RpcImageServer.h\"\n#include \"ImageServerCfg.h\"\n#include \"ImageProcess.h\"\n#include \"ImageProcessTask.h\"\n#include <image-manager\/ImageServerStorage.h>\n#include <image-manager\/ImageServerRequest.h>\n#include \"errno.h\"\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/thread.hpp>\n#include <glog\/logging.h>\n\n#include <tfs_client_api.h>\n\nusing namespace tfs::client;\nusing namespace tfs::common;\n\nnamespace sf1r\n{\n\nRpcImageServer::RpcImageServer(const std::string& host, uint16_t port, uint32_t threadNum)\n : host_(host)\n , port_(port)\n , threadNum_(threadNum)\n , is_exporting_(false)\n , export_thread_(NULL)\n{\n}\n\nRpcImageServer::~RpcImageServer()\n{\n std::cout << \"~RpcImageServer()\" << std::endl;\n stop();\n}\n\nvoid RpcImageServer::start()\n{\n instance.listen(host_, port_);\n instance.start(threadNum_);\n}\n\nvoid RpcImageServer::join()\n{\n instance.join();\n}\n\nvoid RpcImageServer::run()\n{\n start();\n join();\n}\n\nvoid RpcImageServer::stop()\n{\n instance.end();\n instance.join();\n if(export_thread_)\n {\n export_thread_->interrupt();\n export_thread_->join();\n delete export_thread_;\n }\n}\n\nvoid RpcImageServer::dispatch(msgpack::rpc::request req)\n{\n try\n {\n std::string method;\n req.method().convert(&method);\n\n if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_TEST])\n {\n msgpack::type::tuple<bool> params;\n req.params().convert(¶ms);\n\n req.result(true);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_GET_IMAGE_COLOR])\n {\n msgpack::type::tuple<ImageColorData> params;\n req.params().convert(¶ms);\n ImageColorData& reqdata = params.get<0>();\n\n reqdata.success = ImageServerStorage::get()->GetImageColor(reqdata.img_file, reqdata.result_img_color);\n if(!reqdata.success)\n {\n \/\/ try to recalculate the color\n \/\/std::string picFilePath = ImageServerCfg::get()->getImageFilePath() + \"\/\" + reqdata.img_file;\n char* data = NULL;\n std::size_t datasize = 0;\n if(ImageServerStorage::get()->DownloadImageData(reqdata.img_file, data, datasize))\n {\n int indexCollection[COLOR_RET_NUM];\n bool ret = getImageColor(data, datasize, indexCollection, COLOR_RET_NUM);\n if(ret){\n std::ostringstream oss;\n for(std::size_t i = 0; i < COLOR_RET_NUM - 1; ++i)\n {\n oss << indexCollection[i] << \",\";\n }\n oss << indexCollection[COLOR_RET_NUM - 1]; \n\n reqdata.success = ImageServerStorage::get()->SetImageColor(reqdata.img_file, oss.str());\n reqdata.result_img_color = oss.str();\n \/\/LOG(INFO) << \"got request image color for fileName=\" << reqdata.img_file << \"result:\" <<\n \/\/ oss.str() << std::endl;\n }else{\n LOG(WARNING) << \"getImageColor failed imagePath=\" << reqdata.img_file << std::endl;\n reqdata.success = false;\n }\n delete[] data;\n }\n else\n {\n LOG(INFO) << \"getImage data failed while get image color imagePath=\" << reqdata.img_file << std::endl;\n reqdata.success = false;\n }\n }\n req.result(reqdata);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_UPLOAD_IMAGE])\n {\n struct timeval tv_start, tv_end;\n gettimeofday(&tv_start, NULL);\n \/\/LOG(INFO) << \"get upload request : \" << tv_start.tv_sec << endl;\n msgpack::type::tuple<UploadImageData> params;\n req.params().convert(¶ms);\n UploadImageData& reqdata = params.get<0>();\n std::string ret_file;\n if(reqdata.param_type == 0)\n {\n reqdata.success = ImageServerStorage::get()->UploadImageFile(reqdata.img_file, ret_file);\n }\n else if(reqdata.param_type == 1)\n {\n reqdata.success = ImageServerStorage::get()->UploadImageData(reqdata.img_file.data(),\n reqdata.img_file.size(), ret_file);\n }\n else\n {\n reqdata.success = false;\n }\n gettimeofday(&tv_end, NULL);\n int interval = tv_end.tv_sec - tv_start.tv_sec;\n if( interval > 1)\n LOG(WARNING) << \"upload time larger than 1s : \" << interval << endl;\n if(reqdata.success)\n {\n \/\/ write log file\n \/\/\n ofstream ofs;\n try\n {\n ofs.open(ImageServerCfg::get()->getUploadImageLog().c_str(), ofstream::app);\n ofs << ret_file.c_str() << \", time: \" << tv_end.tv_sec << std::endl;\n ofs.close();\n }\n catch(std::exception& e)\n {\n LOG(ERROR) << \"write upload log failed: \" << ret_file << std::endl;\n ofs.close();\n }\n }\n else\n {\n if(reqdata.param_type == 0)\n LOG(WARNING) << \"file upload failed: \" << reqdata.img_file << std::endl;\n else\n LOG(WARNING) << \"image data upload failed: \" << std::endl;\n }\n reqdata.img_file = ret_file;\n req.result(reqdata);\n gettimeofday(&tv_end, NULL);\n \/\/LOG(INFO) << \"finish upload request : \" << tv_end.tv_sec << endl;\n interval = tv_end.tv_sec - tv_start.tv_sec;\n if( interval > 1)\n LOG(WARNING) << \"upload time total larger than 1s : \" << interval << endl;\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_DELETE_IMAGE])\n {\n msgpack::type::tuple<DeleteImageData> params;\n req.params().convert(¶ms);\n DeleteImageData& reqdata = params.get<0>();\n reqdata.success = ImageServerStorage::get()->DeleteImage(reqdata.img_file);\n LOG(INFO) << \"delete request for : \" << reqdata.img_file << std::endl;\n req.result(reqdata);\n }\n else if (method == ImageServerRequest::method_names[ImageServerRequest::METHOD_EXPORT_IMAGE])\n {\n msgpack::type::tuple<ExportImageData> params;\n req.params().convert(¶ms);\n ExportImageData& reqdata = params.get<0>();\n req.result(reqdata);\n if(is_exporting_)\n {\n LOG(WARNING) << \"image is already exporting! Ignore any more request.\" << std::endl;\n return;\n }\n is_exporting_ = true;\n if(export_thread_)\n {\n delete export_thread_;\n }\n\n export_thread_ = new boost::thread(&RpcImageServer::exportimage, this, \n reqdata.img_log_file, reqdata.out_dir);\n\n }\n else if(method == ImageServerRequest::method_names[ImageServerRequest::METHOD_COMPUTE_IMAGE_COLOR])\n {\n msgpack::type::tuple<ComputeImageColorData> params;\n req.params().convert(¶ms);\n ComputeImageColorData& reqdata = params.get<0>();\n\n Request *image_computereq = new Request;\n image_computereq->filePath = reqdata.filepath;\n image_computereq->filetype = reqdata.filetype;\n LOG(INFO) << \"got image file color computing request:\" << reqdata.filepath << endl;\n MSG msg(image_computereq);\n reqdata.success = true;\n if(!ImageProcessTask::instance()->put(msg)){ \n LOG(ERROR) << \"failed to enqueue fileName:\" << reqdata.filepath << endl;\n reqdata.success = false;\n }\n req.result(reqdata);\n }\n else\n {\n req.error(msgpack::rpc::NO_METHOD_ERROR);\n }\n }\n catch (const msgpack::type_error& e)\n {\n req.error(msgpack::rpc::ARGUMENT_ERROR);\n }\n catch (const std::exception& e)\n {\n req.error(std::string(e.what()));\n }\n}\n\nvoid RpcImageServer::exportimage(const std::string& log_file, const std::string& outdir)\n{\n size_t total_export = 0;\n size_t failed_cnt = 0;\n ifstream ifs;\n ofstream export_log;\n struct timeval tv_start, tv_end;\n try\n {\n ifs.open(log_file.c_str(), ifstream::in);\n export_log.open((outdir + \"\/\" + std::string(\"export.log\")).c_str(), ofstream::app);\n\n gettimeofday(&tv_start, NULL);\n export_log << \" === export start: \" << tv_start.tv_sec << \" === \" << std::endl;\n while(ifs.good())\n {\n ++total_export;\n char file_name[TFS_FILE_LEN];\n ifs.getline(file_name, TFS_FILE_LEN);\n char* buffer = NULL;\n std::size_t buf_size = 0;\n bool ret = ImageServerStorage::get()->DownloadImageData(file_name, buffer, buf_size);\n if(ret)\n {\n ofstream ofs;\n try\n {\n ofs.open((outdir + \"\/\" + file_name).c_str(), ofstream::trunc);\n ofs.write(buffer, buf_size);\n }\n catch(std::exception& e)\n {\n ++failed_cnt;\n export_log << \"export failed (save data to out file error) : \" << e.what() << \",file: \" << file_name << std::endl;\n }\n if(ofs.is_open())\n ofs.close();\n delete[] buffer;\n }\n else\n {\n ++failed_cnt;\n export_log << \"export failed (download error): \" << file_name << std::endl;\n }\n boost::this_thread::interruption_point();\n }\n }\n catch(boost::thread_interrupted& )\n {\n LOG(INFO) << \"exporting aborted. \" << std::endl;\n }\n catch(std::exception& e)\n {\n LOG(WARNING) << \"exception while exporting: \" << e.what() << std::endl;\n }\n if(ifs.is_open())\n {\n ifs.close();\n }\n if(export_log.is_open())\n {\n export_log << \"export finished, total export : \" << total_export << \", failed: \" << failed_cnt << std::endl;\n gettimeofday(&tv_end, NULL);\n export_log << \" === export end: \" << tv_end.tv_sec << \" === \" << std::endl;\n export_log.close();\n }\n is_exporting_ = false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"util\/webserver.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/mem_fn.hpp>\n#include <boost\/thread\/locks.hpp>\n#include <gutil\/strings\/substitute.h>\n#include <map>\n#include <fstream>\n#include <stdio.h>\n#include <signal.h>\n#include <string>\n#include <mustache\/mustache.h>\n#include <rapidjson\/stringbuffer.h>\n#include <rapidjson\/prettywriter.h>\n\n#include \"common\/logging.h\"\n#include \"util\/cpu-info.h\"\n#include \"util\/disk-info.h\"\n#include \"util\/mem-info.h\"\n#include \"util\/os-info.h\"\n#include \"util\/url-coding.h\"\n#include \"util\/debug-util.h\"\n#include \"util\/stopwatch.h\"\n#include \"rpc\/thrift-util.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::filesystem;\nusing namespace google;\nusing namespace strings;\nusing namespace rapidjson;\nusing namespace mustache;\n\nconst char* GetDefaultDocumentRoot();\n\nDEFINE_int32(webserver_port, 25000, \"Port to start debug webserver on\");\nDEFINE_string(webserver_interface, \"\",\n \"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0\");\nDEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(),\n \"Files under <webserver_doc_root>\/www are accessible via the debug webserver. \"\n \"Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document \"\n \"root\");\nDEFINE_bool(enable_webserver_doc_root, true,\n \"If true, webserver may serve static files from the webserver_doc_root\");\n\nDEFINE_string(webserver_certificate_file, \"\",\n \"The location of the debug webserver's SSL certificate file, in .pem format. If \"\n \"empty, webserver SSL support is not enabled\");\nDEFINE_string(webserver_authentication_domain, \"\",\n \"Domain used for debug webserver authentication\");\nDEFINE_string(webserver_password_file, \"\",\n \"(Optional) Location of .htpasswd file containing user names and hashed passwords for\"\n \" debug webserver authentication\");\n\nstatic const char* DOC_FOLDER = \"\/www\/\";\nstatic const int DOC_FOLDER_LEN = strlen(DOC_FOLDER);\n\n\/\/ Easy-to-read constants for Squeasel return codes\nstatic const uint32_t PROCESSING_COMPLETE = 1;\nstatic const uint32_t NOT_PROCESSED = 0;\n\n\/\/ Standard keys in the json document sent to templates for rendering. Must be kept in\n\/\/ sync with the templates themselves.\nstatic const char* COMMON_JSON_KEY = \"__common__\";\n\n\/\/ Returns $IMPALA_HOME if set, otherwise \/tmp\/impala_www\nconst char* GetDefaultDocumentRoot() {\n stringstream ss;\n char* impala_home = getenv(\"IMPALA_HOME\");\n if (impala_home == NULL) {\n return \"\"; \/\/ Empty document root means don't serve static files\n } else {\n ss << impala_home;\n }\n\n \/\/ Deliberate memory leak, but this should be called exactly once.\n string* str = new string(ss.str());\n return str->c_str();\n}\n\nnamespace impala {\n\nconst char* Webserver::ENABLE_RAW_JSON_KEY = \"__raw__\";\n\nWebserver::Webserver() : context_(NULL) {\n http_address_ = MakeNetworkAddress(\n FLAGS_webserver_interface.empty() ? \"0.0.0.0\" : FLAGS_webserver_interface,\n FLAGS_webserver_port);\n}\n\nWebserver::Webserver(const int port) : context_(NULL) {\n http_address_ = MakeNetworkAddress(\"0.0.0.0\", port);\n}\n\nWebserver::~Webserver() {\n Stop();\n}\n\nvoid Webserver::RootHandler(const Webserver::ArgumentMap& args, Document* document) {\n document->AddMember(\"version\", GetVersionString().c_str(),\n document->GetAllocator());\n document->AddMember(\"cpu_info\", CpuInfo::DebugString().c_str(),\n document->GetAllocator());\n document->AddMember(\"mem_info\", MemInfo::DebugString().c_str(),\n document->GetAllocator());\n document->AddMember(\"disk_info\", DiskInfo::DebugString().c_str(),\n document->GetAllocator());\n document->AddMember(\"os_info\", OsInfo::DebugString().c_str(),\n document->GetAllocator());\n document->AddMember(\"pid\", getpid(), document->GetAllocator());\n}\n\nvoid Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) {\n vector<string> arg_pairs;\n split(arg_pairs, args, is_any_of(\"&\"));\n\n BOOST_FOREACH(const string& arg_pair, arg_pairs) {\n vector<string> key_value;\n split(key_value, arg_pair, is_any_of(\"=\"));\n if (key_value.empty()) continue;\n\n string key;\n if (!UrlDecode(key_value[0], &key)) continue;\n string value;\n if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : \"\"), &value)) continue;\n to_lower(key);\n (*output)[key] = value;\n }\n}\n\nbool Webserver::IsSecure() const {\n return !FLAGS_webserver_certificate_file.empty();\n}\n\nStatus Webserver::Start() {\n LOG(INFO) << \"Starting webserver on \" << http_address_;\n\n stringstream listening_spec;\n listening_spec << http_address_;\n\n if (IsSecure()) {\n LOG(INFO) << \"Webserver: Enabling HTTPS support\";\n \/\/ Squeasel makes sockets with 's' suffixes accept SSL traffic only\n listening_spec << \"s\";\n }\n string listening_str = listening_spec.str();\n vector<const char*> options;\n\n if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {\n LOG(INFO) << \"Document root: \" << FLAGS_webserver_doc_root;\n options.push_back(\"document_root\");\n options.push_back(FLAGS_webserver_doc_root.c_str());\n } else {\n LOG(INFO)<< \"Document root disabled\";\n }\n\n if (IsSecure()) {\n options.push_back(\"ssl_certificate\");\n options.push_back(FLAGS_webserver_certificate_file.c_str());\n }\n\n if (!FLAGS_webserver_authentication_domain.empty()) {\n options.push_back(\"authentication_domain\");\n options.push_back(FLAGS_webserver_authentication_domain.c_str());\n }\n\n if (!FLAGS_webserver_password_file.empty()) {\n \/\/ Squeasel doesn't log anything if it can't stat the password file (but will if it\n \/\/ can't open it, which it tries to do during a request)\n if (!exists(FLAGS_webserver_password_file)) {\n stringstream ss;\n ss << \"Webserver: Password file does not exist: \" << FLAGS_webserver_password_file;\n return Status(ss.str());\n }\n LOG(INFO) << \"Webserver: Password file is \" << FLAGS_webserver_password_file;\n options.push_back(\"global_auth_file\");\n options.push_back(FLAGS_webserver_password_file.c_str());\n }\n\n options.push_back(\"listening_ports\");\n options.push_back(listening_str.c_str());\n\n \/\/ Options must be a NULL-terminated list\n options.push_back(NULL);\n\n \/\/ squeasel ignores SIGCHLD and we need it to run kinit. This means that since\n \/\/ squeasel does not reap its own children CGI programs must be avoided.\n \/\/ Save the signal handler so we can restore it after squeasel sets it to be ignored.\n sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL);\n\n sq_callbacks callbacks;\n memset(&callbacks, 0, sizeof(callbacks));\n callbacks.begin_request = &Webserver::BeginRequestCallbackStatic;\n callbacks.log_message = &Webserver::LogMessageCallbackStatic;\n\n \/\/ To work around not being able to pass member functions as C callbacks, we store a\n \/\/ pointer to this server in the per-server state, and register a static method as the\n \/\/ default callback. That method unpacks the pointer to this and calls the real\n \/\/ callback.\n context_ = sq_start(&callbacks, reinterpret_cast<void*>(this), &options[0]);\n\n \/\/ Restore the child signal handler so wait() works properly.\n signal(SIGCHLD, sig_chld);\n\n if (context_ == NULL) {\n stringstream error_msg;\n error_msg << \"Webserver: Could not start on address \" << http_address_;\n return Status(error_msg.str());\n }\n\n UrlCallback default_callback =\n bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2);\n\n RegisterUrlCallback(\"\/\", \"root.tmpl\", default_callback);\n\n LOG(INFO) << \"Webserver started\";\n return Status::OK;\n}\n\nvoid Webserver::Stop() {\n if (context_ != NULL) {\n sq_stop(context_);\n context_ = NULL;\n }\n}\n\nvoid Webserver::GetCommonJson(Document* document) {\n DCHECK(document != NULL);\n Value obj(kObjectType);\n obj.AddMember(\"process-name\", google::ProgramInvocationShortName(),\n document->GetAllocator());\n\n Value lst(kArrayType);\n BOOST_FOREACH(const UrlHandlerMap::value_type& handler, url_handlers_) {\n if (handler.second.is_on_nav_bar()) {\n Value obj(kObjectType);\n obj.AddMember(\"link\", handler.first.c_str(), document->GetAllocator());\n obj.AddMember(\"title\", handler.first.c_str(), document->GetAllocator());\n lst.PushBack(obj, document->GetAllocator());\n }\n }\n\n obj.AddMember(\"navbar\", lst, document->GetAllocator());\n document->AddMember(COMMON_JSON_KEY, obj, document->GetAllocator());\n}\n\nint Webserver::LogMessageCallbackStatic(const struct sq_connection* connection,\n const char* message) {\n if (message != NULL) {\n LOG(INFO) << \"Webserver: \" << message;\n }\n return PROCESSING_COMPLETE;\n}\n\nint Webserver::BeginRequestCallbackStatic(struct sq_connection* connection) {\n struct sq_request_info* request_info = sq_get_request_info(connection);\n Webserver* instance = reinterpret_cast<Webserver*>(request_info->user_data);\n return instance->BeginRequestCallback(connection, request_info);\n}\n\nint Webserver::BeginRequestCallback(struct sq_connection* connection,\n struct sq_request_info* request_info) {\n if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {\n if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) {\n VLOG(2) << \"HTTP File access: \" << request_info->uri;\n \/\/ Let Squeasel deal with this request; returning NULL will fall through\n \/\/ to the default handler which will serve files.\n return NOT_PROCESSED;\n }\n }\n shared_lock<shared_mutex> lock(url_handlers_lock_);\n UrlHandlerMap::const_iterator it = url_handlers_.find(request_info->uri);\n if (it == url_handlers_.end()) {\n sq_printf(connection, \"HTTP\/1.1 404 Not Found\\r\\n\"\n \"Content-Type: text\/plain\\r\\n\\r\\n\");\n sq_printf(connection, \"No handler for URI %s\\r\\n\\r\\n\", request_info->uri);\n return PROCESSING_COMPLETE;\n }\n\n map<string, string> arguments;\n if (request_info->query_string != NULL) {\n BuildArgumentMap(request_info->query_string, &arguments);\n }\n MonotonicStopWatch sw;\n sw.Start();\n\n Document document;\n document.SetObject();\n GetCommonJson(&document);\n\n bool send_html_headers = true;\n \/\/ The output of this page is accumulated into this stringstream.\n stringstream output;\n bool raw_json = (arguments.find(\"json\") != arguments.end());\n if (raw_json) {\n \/\/ Callbacks may optionally be rendered as a text-only, pretty-printed Json document\n \/\/ (mostly for debugging or integration with third-party tools).\n StringBuffer strbuf;\n PrettyWriter<StringBuffer> writer(strbuf);\n it->second.callback()(arguments, &document);\n document.Accept(writer);\n output << strbuf.GetString();\n send_html_headers = false;\n } else {\n it->second.callback()(arguments, &document);\n if (arguments.find(\"raw\") != arguments.end()) {\n document.AddMember(ENABLE_RAW_JSON_KEY, \"true\", document.GetAllocator());\n }\n if (document.HasMember(ENABLE_RAW_JSON_KEY)) {\n send_html_headers = false;\n }\n\n const string& full_template_path =\n Substitute(\"$0\/$1\/$2\", FLAGS_webserver_doc_root, DOC_FOLDER,\n it->second.template_filename());\n ifstream tmpl(full_template_path.c_str());\n if (!tmpl.is_open()) {\n output << \"Could not open template: \" << full_template_path;\n send_html_headers = false;\n } else {\n stringstream buffer;\n buffer << tmpl.rdbuf();\n RenderTemplate(buffer.str(), Substitute(\"$0\/\", FLAGS_webserver_doc_root), document,\n &output);\n }\n }\n\n VLOG(3) << \"Rendering page \" << request_info->uri << \" took \"\n << PrettyPrinter::Print(sw.ElapsedTime(), TCounterType::CPU_TICKS);\n\n const string& str = output.str();\n \/\/ Without styling, render the page as plain text\n if (send_html_headers) {\n sq_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\", (int)str.length());\n } else {\n sq_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/plain\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\", (int)str.length());\n }\n\n \/\/ Make sure to use sq_write for printing the body; sq_printf truncates at 8kb\n sq_write(connection, str.c_str(), str.length());\n return PROCESSING_COMPLETE;\n}\n\nvoid Webserver::RegisterUrlCallback(const string& path,\n const string& template_filename, const UrlCallback& callback, bool is_on_nav_bar) {\n upgrade_lock<shared_mutex> lock(url_handlers_lock_);\n upgrade_to_unique_lock<shared_mutex> writer_lock(lock);\n DCHECK(url_handlers_.find(path) == url_handlers_.end())\n << \"Duplicate Url handler for: \" << path;\n\n url_handlers_.insert(\n make_pair(path, UrlHandler(callback, template_filename, is_on_nav_bar)));\n}\n\n}\n<commit_msg>IMPALA-1151: Fix use-after-free in webserver<commit_after>\/\/ Copyright 2012 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"util\/webserver.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/mem_fn.hpp>\n#include <boost\/thread\/locks.hpp>\n#include <gutil\/strings\/substitute.h>\n#include <map>\n#include <fstream>\n#include <stdio.h>\n#include <signal.h>\n#include <string>\n#include <mustache\/mustache.h>\n#include <rapidjson\/stringbuffer.h>\n#include <rapidjson\/prettywriter.h>\n\n#include \"common\/logging.h\"\n#include \"util\/cpu-info.h\"\n#include \"util\/disk-info.h\"\n#include \"util\/mem-info.h\"\n#include \"util\/os-info.h\"\n#include \"util\/url-coding.h\"\n#include \"util\/debug-util.h\"\n#include \"util\/stopwatch.h\"\n#include \"rpc\/thrift-util.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::filesystem;\nusing namespace google;\nusing namespace strings;\nusing namespace rapidjson;\nusing namespace mustache;\n\nconst char* GetDefaultDocumentRoot();\n\nDEFINE_int32(webserver_port, 25000, \"Port to start debug webserver on\");\nDEFINE_string(webserver_interface, \"\",\n \"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0\");\nDEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(),\n \"Files under <webserver_doc_root>\/www are accessible via the debug webserver. \"\n \"Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document \"\n \"root\");\nDEFINE_bool(enable_webserver_doc_root, true,\n \"If true, webserver may serve static files from the webserver_doc_root\");\n\nDEFINE_string(webserver_certificate_file, \"\",\n \"The location of the debug webserver's SSL certificate file, in .pem format. If \"\n \"empty, webserver SSL support is not enabled\");\nDEFINE_string(webserver_authentication_domain, \"\",\n \"Domain used for debug webserver authentication\");\nDEFINE_string(webserver_password_file, \"\",\n \"(Optional) Location of .htpasswd file containing user names and hashed passwords for\"\n \" debug webserver authentication\");\n\nstatic const char* DOC_FOLDER = \"\/www\/\";\nstatic const int DOC_FOLDER_LEN = strlen(DOC_FOLDER);\n\n\/\/ Easy-to-read constants for Squeasel return codes\nstatic const uint32_t PROCESSING_COMPLETE = 1;\nstatic const uint32_t NOT_PROCESSED = 0;\n\n\/\/ Standard keys in the json document sent to templates for rendering. Must be kept in\n\/\/ sync with the templates themselves.\nstatic const char* COMMON_JSON_KEY = \"__common__\";\n\n\/\/ Returns $IMPALA_HOME if set, otherwise \/tmp\/impala_www\nconst char* GetDefaultDocumentRoot() {\n stringstream ss;\n char* impala_home = getenv(\"IMPALA_HOME\");\n if (impala_home == NULL) {\n return \"\"; \/\/ Empty document root means don't serve static files\n } else {\n ss << impala_home;\n }\n\n \/\/ Deliberate memory leak, but this should be called exactly once.\n string* str = new string(ss.str());\n return str->c_str();\n}\n\nnamespace impala {\n\nconst char* Webserver::ENABLE_RAW_JSON_KEY = \"__raw__\";\n\nWebserver::Webserver() : context_(NULL) {\n http_address_ = MakeNetworkAddress(\n FLAGS_webserver_interface.empty() ? \"0.0.0.0\" : FLAGS_webserver_interface,\n FLAGS_webserver_port);\n}\n\nWebserver::Webserver(const int port) : context_(NULL) {\n http_address_ = MakeNetworkAddress(\"0.0.0.0\", port);\n}\n\nWebserver::~Webserver() {\n Stop();\n}\n\nvoid Webserver::RootHandler(const Webserver::ArgumentMap& args, Document* document) {\n Value version(GetVersionString().c_str(), document->GetAllocator());\n document->AddMember(\"version\", version, document->GetAllocator());\n Value cpu_info(CpuInfo::DebugString().c_str(), document->GetAllocator());\n document->AddMember(\"cpu_info\", cpu_info, document->GetAllocator());\n Value mem_info(MemInfo::DebugString().c_str(), document->GetAllocator());\n document->AddMember(\"mem_info\", mem_info, document->GetAllocator());\n Value disk_info(DiskInfo::DebugString().c_str(), document->GetAllocator());\n document->AddMember(\"disk_info\", disk_info, document->GetAllocator());\n Value os_info(OsInfo::DebugString().c_str(), document->GetAllocator());\n document->AddMember(\"os_info\", os_info, document->GetAllocator());\n document->AddMember(\"pid\", getpid(), document->GetAllocator());\n}\n\nvoid Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) {\n vector<string> arg_pairs;\n split(arg_pairs, args, is_any_of(\"&\"));\n\n BOOST_FOREACH(const string& arg_pair, arg_pairs) {\n vector<string> key_value;\n split(key_value, arg_pair, is_any_of(\"=\"));\n if (key_value.empty()) continue;\n\n string key;\n if (!UrlDecode(key_value[0], &key)) continue;\n string value;\n if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : \"\"), &value)) continue;\n to_lower(key);\n (*output)[key] = value;\n }\n}\n\nbool Webserver::IsSecure() const {\n return !FLAGS_webserver_certificate_file.empty();\n}\n\nStatus Webserver::Start() {\n LOG(INFO) << \"Starting webserver on \" << http_address_;\n\n stringstream listening_spec;\n listening_spec << http_address_;\n\n if (IsSecure()) {\n LOG(INFO) << \"Webserver: Enabling HTTPS support\";\n \/\/ Squeasel makes sockets with 's' suffixes accept SSL traffic only\n listening_spec << \"s\";\n }\n string listening_str = listening_spec.str();\n vector<const char*> options;\n\n if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {\n LOG(INFO) << \"Document root: \" << FLAGS_webserver_doc_root;\n options.push_back(\"document_root\");\n options.push_back(FLAGS_webserver_doc_root.c_str());\n } else {\n LOG(INFO)<< \"Document root disabled\";\n }\n\n if (IsSecure()) {\n options.push_back(\"ssl_certificate\");\n options.push_back(FLAGS_webserver_certificate_file.c_str());\n }\n\n if (!FLAGS_webserver_authentication_domain.empty()) {\n options.push_back(\"authentication_domain\");\n options.push_back(FLAGS_webserver_authentication_domain.c_str());\n }\n\n if (!FLAGS_webserver_password_file.empty()) {\n \/\/ Squeasel doesn't log anything if it can't stat the password file (but will if it\n \/\/ can't open it, which it tries to do during a request)\n if (!exists(FLAGS_webserver_password_file)) {\n stringstream ss;\n ss << \"Webserver: Password file does not exist: \" << FLAGS_webserver_password_file;\n return Status(ss.str());\n }\n LOG(INFO) << \"Webserver: Password file is \" << FLAGS_webserver_password_file;\n options.push_back(\"global_auth_file\");\n options.push_back(FLAGS_webserver_password_file.c_str());\n }\n\n options.push_back(\"listening_ports\");\n options.push_back(listening_str.c_str());\n\n \/\/ Options must be a NULL-terminated list\n options.push_back(NULL);\n\n \/\/ squeasel ignores SIGCHLD and we need it to run kinit. This means that since\n \/\/ squeasel does not reap its own children CGI programs must be avoided.\n \/\/ Save the signal handler so we can restore it after squeasel sets it to be ignored.\n sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL);\n\n sq_callbacks callbacks;\n memset(&callbacks, 0, sizeof(callbacks));\n callbacks.begin_request = &Webserver::BeginRequestCallbackStatic;\n callbacks.log_message = &Webserver::LogMessageCallbackStatic;\n\n \/\/ To work around not being able to pass member functions as C callbacks, we store a\n \/\/ pointer to this server in the per-server state, and register a static method as the\n \/\/ default callback. That method unpacks the pointer to this and calls the real\n \/\/ callback.\n context_ = sq_start(&callbacks, reinterpret_cast<void*>(this), &options[0]);\n\n \/\/ Restore the child signal handler so wait() works properly.\n signal(SIGCHLD, sig_chld);\n\n if (context_ == NULL) {\n stringstream error_msg;\n error_msg << \"Webserver: Could not start on address \" << http_address_;\n return Status(error_msg.str());\n }\n\n UrlCallback default_callback =\n bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2);\n\n RegisterUrlCallback(\"\/\", \"root.tmpl\", default_callback);\n\n LOG(INFO) << \"Webserver started\";\n return Status::OK;\n}\n\nvoid Webserver::Stop() {\n if (context_ != NULL) {\n sq_stop(context_);\n context_ = NULL;\n }\n}\n\nvoid Webserver::GetCommonJson(Document* document) {\n DCHECK(document != NULL);\n Value obj(kObjectType);\n obj.AddMember(\"process-name\", google::ProgramInvocationShortName(),\n document->GetAllocator());\n\n Value lst(kArrayType);\n BOOST_FOREACH(const UrlHandlerMap::value_type& handler, url_handlers_) {\n if (handler.second.is_on_nav_bar()) {\n Value obj(kObjectType);\n obj.AddMember(\"link\", handler.first.c_str(), document->GetAllocator());\n obj.AddMember(\"title\", handler.first.c_str(), document->GetAllocator());\n lst.PushBack(obj, document->GetAllocator());\n }\n }\n\n obj.AddMember(\"navbar\", lst, document->GetAllocator());\n document->AddMember(COMMON_JSON_KEY, obj, document->GetAllocator());\n}\n\nint Webserver::LogMessageCallbackStatic(const struct sq_connection* connection,\n const char* message) {\n if (message != NULL) {\n LOG(INFO) << \"Webserver: \" << message;\n }\n return PROCESSING_COMPLETE;\n}\n\nint Webserver::BeginRequestCallbackStatic(struct sq_connection* connection) {\n struct sq_request_info* request_info = sq_get_request_info(connection);\n Webserver* instance = reinterpret_cast<Webserver*>(request_info->user_data);\n return instance->BeginRequestCallback(connection, request_info);\n}\n\nint Webserver::BeginRequestCallback(struct sq_connection* connection,\n struct sq_request_info* request_info) {\n if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) {\n if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) {\n VLOG(2) << \"HTTP File access: \" << request_info->uri;\n \/\/ Let Squeasel deal with this request; returning NULL will fall through\n \/\/ to the default handler which will serve files.\n return NOT_PROCESSED;\n }\n }\n shared_lock<shared_mutex> lock(url_handlers_lock_);\n UrlHandlerMap::const_iterator it = url_handlers_.find(request_info->uri);\n if (it == url_handlers_.end()) {\n sq_printf(connection, \"HTTP\/1.1 404 Not Found\\r\\n\"\n \"Content-Type: text\/plain\\r\\n\\r\\n\");\n sq_printf(connection, \"No handler for URI %s\\r\\n\\r\\n\", request_info->uri);\n return PROCESSING_COMPLETE;\n }\n\n map<string, string> arguments;\n if (request_info->query_string != NULL) {\n BuildArgumentMap(request_info->query_string, &arguments);\n }\n MonotonicStopWatch sw;\n sw.Start();\n\n Document document;\n document.SetObject();\n GetCommonJson(&document);\n\n bool send_html_headers = true;\n \/\/ The output of this page is accumulated into this stringstream.\n stringstream output;\n bool raw_json = (arguments.find(\"json\") != arguments.end());\n if (raw_json) {\n \/\/ Callbacks may optionally be rendered as a text-only, pretty-printed Json document\n \/\/ (mostly for debugging or integration with third-party tools).\n StringBuffer strbuf;\n PrettyWriter<StringBuffer> writer(strbuf);\n it->second.callback()(arguments, &document);\n document.Accept(writer);\n output << strbuf.GetString();\n send_html_headers = false;\n } else {\n it->second.callback()(arguments, &document);\n if (arguments.find(\"raw\") != arguments.end()) {\n document.AddMember(ENABLE_RAW_JSON_KEY, \"true\", document.GetAllocator());\n }\n if (document.HasMember(ENABLE_RAW_JSON_KEY)) {\n send_html_headers = false;\n }\n\n const string& full_template_path =\n Substitute(\"$0\/$1\/$2\", FLAGS_webserver_doc_root, DOC_FOLDER,\n it->second.template_filename());\n ifstream tmpl(full_template_path.c_str());\n if (!tmpl.is_open()) {\n output << \"Could not open template: \" << full_template_path;\n send_html_headers = false;\n } else {\n stringstream buffer;\n buffer << tmpl.rdbuf();\n RenderTemplate(buffer.str(), Substitute(\"$0\/\", FLAGS_webserver_doc_root), document,\n &output);\n }\n }\n\n VLOG(3) << \"Rendering page \" << request_info->uri << \" took \"\n << PrettyPrinter::Print(sw.ElapsedTime(), TCounterType::CPU_TICKS);\n\n const string& str = output.str();\n \/\/ Without styling, render the page as plain text\n if (send_html_headers) {\n sq_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\", (int)str.length());\n } else {\n sq_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/plain\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\", (int)str.length());\n }\n\n \/\/ Make sure to use sq_write for printing the body; sq_printf truncates at 8kb\n sq_write(connection, str.c_str(), str.length());\n return PROCESSING_COMPLETE;\n}\n\nvoid Webserver::RegisterUrlCallback(const string& path,\n const string& template_filename, const UrlCallback& callback, bool is_on_nav_bar) {\n upgrade_lock<shared_mutex> lock(url_handlers_lock_);\n upgrade_to_unique_lock<shared_mutex> writer_lock(lock);\n DCHECK(url_handlers_.find(path) == url_handlers_.end())\n << \"Duplicate Url handler for: \" << path;\n\n url_handlers_.insert(\n make_pair(path, UrlHandler(callback, template_filename, is_on_nav_bar)));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/npapi\/test\/plugin_get_javascript_url_test.h\"\n\n#include \"base\/basictypes.h\"\n\n\/\/ url for \"self\".\n#define SELF_URL \"javascript:window.location+\\\"\\\"\"\n\/\/ The identifier for the self url stream.\n#define SELF_URL_STREAM_ID 1\n\n\/\/ The identifier for the fetched url stream.\n#define FETCHED_URL_STREAM_ID 2\n\n\/\/ The maximum chunk size of stream data.\n#define STREAM_CHUNK 197\n\nconst int kNPNEvaluateTimerID = 100;\nconst int kNPNEvaluateTimerElapse = 50;\n\n\nnamespace NPAPIClient {\n\nExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest(\n NPP id, NPNetscapeFuncs *host_functions)\n : PluginTest(id, host_functions),\n test_started_(false),\n#ifdef OS_WIN\n window_(NULL),\n#endif\n npn_evaluate_context_(false) {\n}\n\nNPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) {\n if (pNPWindow->window == NULL)\n return NPERR_NO_ERROR;\n\n if (!test_started_) {\n std::string url = SELF_URL;\n HostFunctions()->geturlnotify(id(), url.c_str(), \"_top\",\n reinterpret_cast<void*>(SELF_URL_STREAM_ID));\n test_started_ = true;\n\n#ifdef OS_WIN\n HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window);\n if (!::GetProp(window_handle, L\"Plugin_Instance\")) {\n \/\/ TODO: this propery leaks.\n ::SetProp(window_handle, L\"Plugin_Instance\", this);\n \/\/ We attempt to retreive the NPObject for the plugin instance identified\n \/\/ by the NPObjectLifetimeTestInstance2 class as it may not have been\n \/\/ instantiated yet.\n SetTimer(window_handle, kNPNEvaluateTimerID, kNPNEvaluateTimerElapse,\n TimerProc);\n }\n window_ = window_handle;\n#endif\n }\n\n return NPERR_NO_ERROR;\n}\n\n#ifdef OS_WIN\nvoid CALLBACK ExecuteGetJavascriptUrlTest::TimerProc(\n HWND window, UINT message, UINT timer_id, unsigned long elapsed_time) {\n ExecuteGetJavascriptUrlTest* this_instance =\n reinterpret_cast<ExecuteGetJavascriptUrlTest*>\n (::GetProp(window, L\"Plugin_Instance\"));\n\n ::RemoveProp(window, L\"Plugin_Instance\");\n\n NPObject *window_obj = NULL;\n this_instance->HostFunctions()->getvalue(this_instance->id(),\n NPNVWindowNPObject,\n &window_obj);\n if (!window_obj) {\n this_instance->SetError(\"Failed to get NPObject for plugin instance2\");\n this_instance->SignalTestCompleted();\n return;\n }\n\n std::string script = \"javascript:window.location\";\n NPString script_string;\n script_string.UTF8Characters = script.c_str();\n script_string.UTF8Length = static_cast<unsigned int>(script.length());\n NPVariant result_var;\n\n this_instance->npn_evaluate_context_ = true;\n NPError result = this_instance->HostFunctions()->evaluate(\n this_instance->id(), window_obj, &script_string, &result_var);\n this_instance->npn_evaluate_context_ = false;\n}\n#endif\n\nNPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype) {\n if (stream == NULL) {\n SetError(\"NewStream got null stream\");\n return NPERR_INVALID_PARAM;\n }\n\n if (npn_evaluate_context_) {\n SetError(\"NewStream received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n return NPERR_NO_ERROR;\n}\n\nint32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) {\n if (npn_evaluate_context_) {\n SetError(\"WriteReady received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n return STREAM_CHUNK;\n}\n\nint32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset,\n int32 len, void *buffer) {\n if (stream == NULL) {\n SetError(\"Write got null stream\");\n return -1;\n }\n if (len < 0 || len > STREAM_CHUNK) {\n SetError(\"Write got bogus stream chunk size\");\n return -1;\n }\n\n if (npn_evaluate_context_) {\n SetError(\"Write received in context of NPN_Evaluate\");\n return len;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n self_url_.append(static_cast<char*>(buffer), len);\n break;\n default:\n SetError(\"Unexpected write callback\");\n break;\n }\n \/\/ Pretend that we took all the data.\n return len;\n}\n\n\nNPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream,\n NPError reason) {\n if (stream == NULL) {\n SetError(\"NewStream got null stream\");\n return NPERR_INVALID_PARAM;\n }\n\n#ifdef OS_WIN\n KillTimer(window_, kNPNEvaluateTimerID);\n#endif\n\n if (npn_evaluate_context_) {\n SetError(\"DestroyStream received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n \/\/ don't care\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n return NPERR_NO_ERROR;\n}\n\nvoid ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason,\n void* data) {\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data),\n cast_validity_check);\n\n if (npn_evaluate_context_) {\n SetError(\"URLNotify received in context of NPN_Evaluate\");\n return;\n }\n\n unsigned long stream_id = reinterpret_cast<unsigned long>(data);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n if (strcmp(url, SELF_URL) != 0)\n SetError(\"URLNotify reported incorrect url for SELF_URL\");\n if (self_url_.empty())\n SetError(\"Failed to obtain window location.\");\n SignalTestCompleted();\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n}\n\n} \/\/ namespace NPAPIClient\n<commit_msg>Add a non-null check for a pointer to NPAPIClient::ExecuteGetJavascriptUrlTest::TimerProc BUG=106522 TEST=trybot<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/npapi\/test\/plugin_get_javascript_url_test.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n\n\/\/ url for \"self\".\n#define SELF_URL \"javascript:window.location+\\\"\\\"\"\n\/\/ The identifier for the self url stream.\n#define SELF_URL_STREAM_ID 1\n\n\/\/ The identifier for the fetched url stream.\n#define FETCHED_URL_STREAM_ID 2\n\n\/\/ The maximum chunk size of stream data.\n#define STREAM_CHUNK 197\n\nconst int kNPNEvaluateTimerID = 100;\nconst int kNPNEvaluateTimerElapse = 50;\n\n\nnamespace NPAPIClient {\n\nExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest(\n NPP id, NPNetscapeFuncs *host_functions)\n : PluginTest(id, host_functions),\n test_started_(false),\n#ifdef OS_WIN\n window_(NULL),\n#endif\n npn_evaluate_context_(false) {\n}\n\nNPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) {\n if (pNPWindow->window == NULL)\n return NPERR_NO_ERROR;\n\n if (!test_started_) {\n std::string url = SELF_URL;\n HostFunctions()->geturlnotify(id(), url.c_str(), \"_top\",\n reinterpret_cast<void*>(SELF_URL_STREAM_ID));\n test_started_ = true;\n\n#ifdef OS_WIN\n HWND window_handle = reinterpret_cast<HWND>(pNPWindow->window);\n if (!::GetProp(window_handle, L\"Plugin_Instance\")) {\n \/\/ TODO: this propery leaks.\n ::SetProp(window_handle, L\"Plugin_Instance\", this);\n \/\/ We attempt to retreive the NPObject for the plugin instance identified\n \/\/ by the NPObjectLifetimeTestInstance2 class as it may not have been\n \/\/ instantiated yet.\n SetTimer(window_handle, kNPNEvaluateTimerID, kNPNEvaluateTimerElapse,\n TimerProc);\n }\n window_ = window_handle;\n#endif\n }\n\n return NPERR_NO_ERROR;\n}\n\n#ifdef OS_WIN\nvoid CALLBACK ExecuteGetJavascriptUrlTest::TimerProc(\n HWND window, UINT message, UINT timer_id, unsigned long elapsed_time) {\n ExecuteGetJavascriptUrlTest* this_instance =\n reinterpret_cast<ExecuteGetJavascriptUrlTest*>\n (::GetProp(window, L\"Plugin_Instance\"));\n CHECK(this_instance);\n\n ::RemoveProp(window, L\"Plugin_Instance\");\n\n NPObject *window_obj = NULL;\n this_instance->HostFunctions()->getvalue(this_instance->id(),\n NPNVWindowNPObject,\n &window_obj);\n if (!window_obj) {\n this_instance->SetError(\"Failed to get NPObject for plugin instance2\");\n this_instance->SignalTestCompleted();\n return;\n }\n\n std::string script = \"javascript:window.location\";\n NPString script_string;\n script_string.UTF8Characters = script.c_str();\n script_string.UTF8Length = static_cast<unsigned int>(script.length());\n NPVariant result_var;\n\n this_instance->npn_evaluate_context_ = true;\n NPError result = this_instance->HostFunctions()->evaluate(\n this_instance->id(), window_obj, &script_string, &result_var);\n this_instance->npn_evaluate_context_ = false;\n}\n#endif\n\nNPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype) {\n if (stream == NULL) {\n SetError(\"NewStream got null stream\");\n return NPERR_INVALID_PARAM;\n }\n\n if (npn_evaluate_context_) {\n SetError(\"NewStream received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n return NPERR_NO_ERROR;\n}\n\nint32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) {\n if (npn_evaluate_context_) {\n SetError(\"WriteReady received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n return STREAM_CHUNK;\n}\n\nint32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset,\n int32 len, void *buffer) {\n if (stream == NULL) {\n SetError(\"Write got null stream\");\n return -1;\n }\n if (len < 0 || len > STREAM_CHUNK) {\n SetError(\"Write got bogus stream chunk size\");\n return -1;\n }\n\n if (npn_evaluate_context_) {\n SetError(\"Write received in context of NPN_Evaluate\");\n return len;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n self_url_.append(static_cast<char*>(buffer), len);\n break;\n default:\n SetError(\"Unexpected write callback\");\n break;\n }\n \/\/ Pretend that we took all the data.\n return len;\n}\n\n\nNPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream,\n NPError reason) {\n if (stream == NULL) {\n SetError(\"NewStream got null stream\");\n return NPERR_INVALID_PARAM;\n }\n\n#ifdef OS_WIN\n KillTimer(window_, kNPNEvaluateTimerID);\n#endif\n\n if (npn_evaluate_context_) {\n SetError(\"DestroyStream received in context of NPN_Evaluate\");\n return NPERR_NO_ERROR;\n }\n\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData),\n cast_validity_check);\n unsigned long stream_id = reinterpret_cast<unsigned long>(stream->notifyData);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n \/\/ don't care\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n return NPERR_NO_ERROR;\n}\n\nvoid ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason,\n void* data) {\n COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data),\n cast_validity_check);\n\n if (npn_evaluate_context_) {\n SetError(\"URLNotify received in context of NPN_Evaluate\");\n return;\n }\n\n unsigned long stream_id = reinterpret_cast<unsigned long>(data);\n switch (stream_id) {\n case SELF_URL_STREAM_ID:\n if (strcmp(url, SELF_URL) != 0)\n SetError(\"URLNotify reported incorrect url for SELF_URL\");\n if (self_url_.empty())\n SetError(\"Failed to obtain window location.\");\n SignalTestCompleted();\n break;\n default:\n SetError(\"Unexpected NewStream callback\");\n break;\n }\n}\n\n} \/\/ namespace NPAPIClient\n<|endoftext|>"} {"text":"<commit_before>#include \"Bombs.h\"\n#include <utils\\Log.h>\n\nBombs::Bombs(GameContext* context) : _context(context) , _world(context->world) {\n\tfloat step = TWO_PI \/ 36.0f;\n\tfor (int i = 0; i < 36; ++i) {\n\t\t_cells[i] = 0.9f + sin(step * static_cast<float>(i) * 12.0f) * 0.4f;\n\t}\n\t\/\/_texture = ds::math::buildTexture(0, 440, 60, 60);\n\t_ring_texture = ds::math::buildTexture(40, 120, 6, 6);\n\t_scale_path.add(0.0f, v2(0.1f,0.1f));\n\t_scale_path.add(0.5f, v2(1.5f,1.5f));\n\t_scale_path.add(0.75f, v2(0.75f,0.75f));\n\t_scale_path.add(1.0f, v2(1.0f,1.0f));\n}\n\n\nBombs::~Bombs() {\n}\n\n\/\/ ---------------------------------------\n\/\/ create\n\/\/ ---------------------------------------\nvoid Bombs::create() {\n\tv2 pos;\n\tpos.x = ds::math::random(200.0f, 1400.0f);\n\tpos.y = ds::math::random(200.0f, 700.0f);\n\tds::SID sid = _world->create(pos, \"Bomb\");\n\tBombData* data = (BombData*)_world->attach_data(sid, sizeof(BombData));\n\tfloat angle = ds::math::random(0.0f, TWO_PI);\n\tfloat v = ds::math::random(30.0f, 50.0f);\n\tv2 vel = ds::vector::getRadialVelocity(angle, v);\n\t_world->moveBy(sid, vel, true);\n\t_world->setRotation(sid, vel);\n\t_world->scaleByPath(sid, &_scale_path, _context->settings->bombFlashingTTL);\n\tdata->state = BombData::BS_STARTING;\n\t_context->particles->start(BOMB_STARTUP, v3(pos));\n}\n\nvoid Bombs::handleEvents(const ds::ActionEventBuffer& buffer) {\n\tfor (int i = 0; i < buffer.events.size(); ++i) {\n\t\tconst ds::ActionEvent& event = buffer.events[i];\n\t\tif (_world->contains(event.sid)) {\n\t\t\tint type = _world->getType(event.sid);\n\t\t\tif (type == OT_BOMB) {\n\t\t\t\tif (event.type == ds::AT_SCALE_BY_PATH) {\n\t\t\t\t\tBombData* data = (BombData*)_world->get_data(event.sid);\n\t\t\t\t\tassert(data != 0);\n\t\t\t\t\tdata->state = BombData::BS_ACTIVE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\/\/ ---------------------------------------\n\/\/ grab bomb\n\/\/ ---------------------------------------\nbool Bombs::grab(const v2& pos, float radius, ds::SID* id) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_ACTIVE) {\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tif (ds::math::checkCircleIntersection(_context->world_pos, radius, p, 20.0f)) {\n\t\t\t\tdata->state = BombData::BS_FOLLOWING;\n\t\t\t\t_world->stopAction(_bomb_sids[i], ds::AT_MOVE_BY);\n\t\t\t\t_world->setColor(_bomb_sids[i], ds::Color(0, 192, 32, 255));\n\t\t\t\t*id = _bomb_sids[i];\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/ ---------------------------------------\n\/\/ follow target\n\/\/ ---------------------------------------\nvoid Bombs::follow(ds::SID id, const v2& target) {\n\tif (_world->contains(id)) {\n\t\tv2 p = _world->getPosition(id);\n\t\tfloat angle = 0.0f;\n\t\tds::math::followRelative(target,p, &angle, 60.0f, 0.02f);\n\t\tv2 diff = _context->world_pos - p;\n\t\tv2 n = normalize(diff);\n\t\t_world->setPosition(id, p);\n\t\t_world->setRotation(id, ds::vector::calculateRotation(n));\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ burst\n\/\/ ---------------------------------------\nvoid Bombs::burst(ds::SID id, float direction) {\n\tif (_world->contains(id)) {\n\t\tBombData* data = (BombData*)_world->get_data(id);\n\t\tassert(data != 0);\n\t\tv2 p = _world->getPosition(id);\n\t\tv2 diff = _context->world_pos - p;\n\t\tv2 n = normalize(diff);\n\t\tfloat angle = ds::vector::calculateRotation(n);\n\t\tangle += PI;\n\t\tv2 vel = ds::vector::getRadialVelocity(angle, 100.0f);\n\t\t_world->moveBy(id,vel);\n\t\tdata->state = BombData::BS_TICKING;\n\t\tdata->timer = 0.0f;\n\t\t\/\/_world->setColor(bomb.sid, ds::Color(128, 0, 0, 255));\n\t\t_world->flashColor(id, ds::Color(138, 39, 0), ds::Color(255, 165, 130), 0.3f, -1);\n\t\t_world->setRotation(id, vel);\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ clear\n\/\/ ---------------------------------------\nvoid Bombs::clear() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\t_world->remove(_bomb_sids[i]);\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ render\n\/\/ ---------------------------------------\nvoid Bombs::render() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_TICKING) {\n\t\t\tfloat norm = data->timer \/ _context->settings->bombFlashingTTL;\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tdrawRing(p ,norm);\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ draw ring\n\/\/ ---------------------------------------\nvoid Bombs::drawRing(const v2& pos,float timer) {\n\tfloat step = TWO_PI \/ 36.0f;\n\tfloat angle = TWO_PI * timer * 0.2f;\n\tds::Color clr(230, 88, 31, 255);\n\tclr.r = 0.9 + sin(timer * PI) * 0.1f;\n\tfor (int i = 0; i < 36; ++i) {\n\t\tfloat x = pos.x + cos(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);\n\t\tfloat y = pos.y + sin(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);\n\t\tfloat d = _cells[i] + sin(timer * PI * 8.0f) * 0.4f;\n\t\tds::sprites::draw(v2(x,y), _ring_texture, 0.0f, d, d, clr);\n\t\tangle += step;\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ activate\n\/\/ ---------------------------------------\nvoid Bombs::activate() {\n\t_spawn_timer = 0.0f;\n\tclear();\n}\n\n\/\/ ---------------------------------------\n\/\/ scale gates\n\/\/ ---------------------------------------\nvoid Bombs::scaleBombs(EventBuffer* buffer, float dt) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_TICKING) {\n\t\t\tdata->timer += dt;\n\t\t\tif (data->timer >= _context->settings->bombFlashingTTL) {\n\t\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\t\t_context->particles->start(BOMB_EXPLOSION, v3(p));\n\t\t\t\t_context->particles->start(BOMB_RING_EXPLOSION, v3(p));\n\t\t\t\t_context->particles->start(BOMB_DEBRIS, v3(p));\n\t\t\t\tbuffer->add(GameEvent::GE_BOMB_EXPLODED, p);\n\t\t\t\t_world->remove(_bomb_sids[i]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ ticks\n\/\/ ---------------------------------------\nvoid Bombs::tick(EventBuffer* buffer, float dt) {\n\t\/\/ spawn\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tif (num < _context->settings->maxBombs) {\n\t\t_spawn_timer += dt;\n\t\tif (_spawn_timer > _context->settings->bombStartTTL) {\n\t\t\t_spawn_timer = 0.0f;\n\t\t\tcreate();\n\t\t}\n\t}\n\tscaleBombs(buffer, dt);\n}\n\n\/\/ ---------------------------------------\n\/\/ check interception\n\/\/ ---------------------------------------\nvoid Bombs::checkInterception(EventBuffer* buffer, const v2& pos, float radius) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_ACTIVE) {\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tif (ds::math::checkCircleIntersection(_context->world_pos, PLAYER_RADIUS, p, 20.0f)) {\n\t\t\t\tdata->state = BombData::BS_TICKING;\n\t\t\t\tdata->timer = 0.0f;\n\t\t\t\t_world->flashColor(_bomb_sids[i], ds::Color(138, 39, 0), ds::Color(255, 135, 88), 0.4f, -1);\n\t\t\t\tbuffer->add(GameEvent::GE_BOMB_ACTIVATED, p);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ kill all\n\/\/ ---------------------------------------\nvoid Bombs::killAll() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t_context->particles->start(BOMB_EXPLOSION, p);\n\t\t_world->remove(_bomb_sids[i]);\n\t}\n}<commit_msg>using particle group<commit_after>#include \"Bombs.h\"\n#include <utils\\Log.h>\n\nBombs::Bombs(GameContext* context) : _context(context) , _world(context->world) {\n\tfloat step = TWO_PI \/ 36.0f;\n\tfor (int i = 0; i < 36; ++i) {\n\t\t_cells[i] = 0.9f + sin(step * static_cast<float>(i) * 12.0f) * 0.4f;\n\t}\n\t\/\/_texture = ds::math::buildTexture(0, 440, 60, 60);\n\t_ring_texture = ds::math::buildTexture(40, 120, 6, 6);\n\t_scale_path.add(0.0f, v2(0.1f,0.1f));\n\t_scale_path.add(0.5f, v2(1.5f,1.5f));\n\t_scale_path.add(0.75f, v2(0.75f,0.75f));\n\t_scale_path.add(1.0f, v2(1.0f,1.0f));\n}\n\n\nBombs::~Bombs() {\n}\n\n\/\/ ---------------------------------------\n\/\/ create\n\/\/ ---------------------------------------\nvoid Bombs::create() {\n\tv2 pos;\n\tpos.x = ds::math::random(200.0f, 1400.0f);\n\tpos.y = ds::math::random(200.0f, 700.0f);\n\tds::SID sid = _world->create(pos, \"Bomb\");\n\tBombData* data = (BombData*)_world->attach_data(sid, sizeof(BombData));\n\tfloat angle = ds::math::random(0.0f, TWO_PI);\n\tfloat v = ds::math::random(30.0f, 50.0f);\n\tv2 vel = ds::vector::getRadialVelocity(angle, v);\n\t_world->moveBy(sid, vel, true);\n\t_world->setRotation(sid, vel);\n\t_world->scaleByPath(sid, &_scale_path, _context->settings->bombFlashingTTL);\n\tdata->state = BombData::BS_STARTING;\n\t_context->particles->start(BOMB_STARTUP, v3(pos));\n}\n\nvoid Bombs::handleEvents(const ds::ActionEventBuffer& buffer) {\n\tfor (int i = 0; i < buffer.events.size(); ++i) {\n\t\tconst ds::ActionEvent& event = buffer.events[i];\n\t\tif (_world->contains(event.sid)) {\n\t\t\tint type = _world->getType(event.sid);\n\t\t\tif (type == OT_BOMB) {\n\t\t\t\tif (event.type == ds::AT_SCALE_BY_PATH) {\n\t\t\t\t\tBombData* data = (BombData*)_world->get_data(event.sid);\n\t\t\t\t\tassert(data != 0);\n\t\t\t\t\tdata->state = BombData::BS_ACTIVE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\/\/ ---------------------------------------\n\/\/ grab bomb\n\/\/ ---------------------------------------\nbool Bombs::grab(const v2& pos, float radius, ds::SID* id) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_ACTIVE) {\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tif (ds::math::checkCircleIntersection(_context->world_pos, radius, p, 20.0f)) {\n\t\t\t\tdata->state = BombData::BS_FOLLOWING;\n\t\t\t\t_world->stopAction(_bomb_sids[i], ds::AT_MOVE_BY);\n\t\t\t\t_world->setColor(_bomb_sids[i], ds::Color(0, 192, 32, 255));\n\t\t\t\t*id = _bomb_sids[i];\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/ ---------------------------------------\n\/\/ follow target\n\/\/ ---------------------------------------\nvoid Bombs::follow(ds::SID id, const v2& target) {\n\tif (_world->contains(id)) {\n\t\tv2 p = _world->getPosition(id);\n\t\tfloat angle = 0.0f;\n\t\tds::math::followRelative(target,p, &angle, 60.0f, 0.02f);\n\t\tv2 diff = _context->world_pos - p;\n\t\tv2 n = normalize(diff);\n\t\t_world->setPosition(id, p);\n\t\t_world->setRotation(id, ds::vector::calculateRotation(n));\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ burst\n\/\/ ---------------------------------------\nvoid Bombs::burst(ds::SID id, float direction) {\n\tif (_world->contains(id)) {\n\t\tBombData* data = (BombData*)_world->get_data(id);\n\t\tassert(data != 0);\n\t\tv2 p = _world->getPosition(id);\n\t\tv2 diff = _context->world_pos - p;\n\t\tv2 n = normalize(diff);\n\t\tfloat angle = ds::vector::calculateRotation(n);\n\t\tangle += PI;\n\t\tv2 vel = ds::vector::getRadialVelocity(angle, 100.0f);\n\t\t_world->moveBy(id,vel);\n\t\tdata->state = BombData::BS_TICKING;\n\t\tdata->timer = 0.0f;\n\t\t\/\/_world->setColor(bomb.sid, ds::Color(128, 0, 0, 255));\n\t\t_world->flashColor(id, ds::Color(138, 39, 0), ds::Color(255, 165, 130), 0.3f, -1);\n\t\t_world->setRotation(id, vel);\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ clear\n\/\/ ---------------------------------------\nvoid Bombs::clear() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\t_world->remove(_bomb_sids[i]);\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ render\n\/\/ ---------------------------------------\nvoid Bombs::render() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_TICKING) {\n\t\t\tfloat norm = data->timer \/ _context->settings->bombFlashingTTL;\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tdrawRing(p ,norm);\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ draw ring\n\/\/ ---------------------------------------\nvoid Bombs::drawRing(const v2& pos,float timer) {\n\tfloat step = TWO_PI \/ 36.0f;\n\tfloat angle = TWO_PI * timer * 0.2f;\n\tds::Color clr(230, 88, 31, 255);\n\tclr.r = 0.9 + sin(timer * PI) * 0.1f;\n\tfor (int i = 0; i < 36; ++i) {\n\t\tfloat x = pos.x + cos(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);\n\t\tfloat y = pos.y + sin(angle) * BOMB_EXPLOSION_RADIUS * (1.0f + sin(timer * PI * 3.0f) * 0.1f);\n\t\tfloat d = _cells[i] + sin(timer * PI * 8.0f) * 0.4f;\n\t\tds::sprites::draw(v2(x,y), _ring_texture, 0.0f, d, d, clr);\n\t\tangle += step;\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ activate\n\/\/ ---------------------------------------\nvoid Bombs::activate() {\n\t_spawn_timer = 0.0f;\n\tclear();\n}\n\n\/\/ ---------------------------------------\n\/\/ scale gates\n\/\/ ---------------------------------------\nvoid Bombs::scaleBombs(EventBuffer* buffer, float dt) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_TICKING) {\n\t\t\tdata->timer += dt;\n\t\t\tif (data->timer >= _context->settings->bombFlashingTTL) {\n\t\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\t\t_context->particles->startGroup(1, v3(p));\n\t\t\t\tbuffer->add(GameEvent::GE_BOMB_EXPLODED, p);\n\t\t\t\t_world->remove(_bomb_sids[i]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ ticks\n\/\/ ---------------------------------------\nvoid Bombs::tick(EventBuffer* buffer, float dt) {\n\t\/\/ spawn\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tif (num < _context->settings->maxBombs) {\n\t\t_spawn_timer += dt;\n\t\tif (_spawn_timer > _context->settings->bombStartTTL) {\n\t\t\t_spawn_timer = 0.0f;\n\t\t\tcreate();\n\t\t}\n\t}\n\tscaleBombs(buffer, dt);\n}\n\n\/\/ ---------------------------------------\n\/\/ check interception\n\/\/ ---------------------------------------\nvoid Bombs::checkInterception(EventBuffer* buffer, const v2& pos, float radius) {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tBombData* data = (BombData*)_world->get_data(_bomb_sids[i]);\n\t\tassert(data != 0);\n\t\tif (data->state == BombData::BS_ACTIVE) {\n\t\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t\tif (ds::math::checkCircleIntersection(_context->world_pos, PLAYER_RADIUS, p, 20.0f)) {\n\t\t\t\tdata->state = BombData::BS_TICKING;\n\t\t\t\tdata->timer = 0.0f;\n\t\t\t\t_world->flashColor(_bomb_sids[i], ds::Color(138, 39, 0), ds::Color(255, 135, 88), 0.4f, -1);\n\t\t\t\tbuffer->add(GameEvent::GE_BOMB_ACTIVATED, p);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ---------------------------------------\n\/\/ kill all\n\/\/ ---------------------------------------\nvoid Bombs::killAll() {\n\tint num = _world->find_by_type(OT_BOMB, _bomb_sids, 16);\n\tfor (int i = 0; i < num; ++i) {\n\t\tv2 p = _world->getPosition(_bomb_sids[i]);\n\t\t_context->particles->start(BOMB_EXPLOSION, p);\n\t\t_world->remove(_bomb_sids[i]);\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ anax\n\/\/\/ An open source C++ entity system.\n\/\/\/\n\/\/\/ Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.com)\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\n#include <anax\/World.hpp>\n\n#include <algorithm>\n\n#include <anax\/Config.hpp>\n\n#include <anax\/detail\/AnaxAssert.hpp>\n#include <anax\/util\/ContainerUtils.hpp>\n\nnamespace anax\n{\n void World::SystemDeleter::operator() (detail::BaseSystem* system) const\n {\n system->m_world = nullptr;\n system->m_entities.clear();\n }\n\n World::World() : \n World(DEFAULT_ENTITY_POOL_SIZE)\n {\n }\n\n World::World(std::size_t entityPoolSize) : \n m_entityIdPool(entityPoolSize),\n m_entityAttributes(entityPoolSize)\n {\n }\n\n void World::removeAllSystems()\n {\n m_systems.clear();\n }\n\n Entity World::createEntity()\n {\n checkForResize(1);\n\n m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());\n return m_entityCache.alive.back();\n }\n\n std::vector<Entity> World::createEntities(std::size_t amount)\n {\n std::vector<Entity> temp;\n temp.reserve(amount);\n\n checkForResize(amount);\n\n for(decltype(amount) i = 0; i < amount; ++i)\n {\n Entity e{*this, m_entityIdPool.create()};\n m_entityCache.alive.push_back(e);\n temp.push_back(e);\n }\n\n return temp;\n }\n\n void World::killEntity(Entity& entity)\n {\n \/\/ deactivate the entity\n deactivateEntity(entity);\n\n \/\/ now kill the entity (add it to the killed cache)\n m_entityCache.killed.push_back(entity);\n }\n\n void World::killEntities(std::vector<Entity>& entities)\n {\n for(auto& i : entities)\n {\n killEntity(i);\n }\n }\n\n void World::activateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be activated\");\n\n m_entityCache.activated.push_back(entity);\n }\n\n void World::deactivateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be deactivated\");\n\n m_entityCache.deactivated.push_back(entity);\n }\n\n bool World::isActivated(const Entity& entity) const\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity passed to isActivated\");\n\n return m_entityAttributes.attributes[entity.getId().index].activated;\n }\n\n bool World::isValid(const anax::Entity &entity) const\n {\n return m_entityIdPool.isValid(entity.getId());\n }\n\n void World::refresh()\n {\n \/\/ go through all the activated entities from last call to refresh\n for(auto& entity : m_entityCache.activated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = true;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n\n \/\/ if the entity passes the filter the system has and is not already part of the system\n if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))\n {\n if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])\n {\n i.second->add(entity); \/\/ add it to the system\n\n util::EnsureCapacity(attribute.systems, systemIndex); \n attribute.systems[systemIndex] = true;\n }\n }\n \/\/ otherwise if the entity is within the system \n \/\/ and is not relevant to the system anymore...\n \/\/ note: the entity has already failed the filter\n else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])\n {\n \/\/ duplicate code (1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n\n \/\/ go through all the deactivated entities from last call to refresh\n for(auto& entity : m_entityCache.deactivated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = false;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n if(attribute.systems.size() <= systemIndex) continue;\n\n if(attribute.systems[systemIndex])\n {\n \/\/ duplicate code ...(1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n \/\/ go through all the killed entities from last call to refresh\n for(auto& entity : m_entityCache.killed)\n {\n \/\/ remove the entity from the alive array\n m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end()); \n\n \/\/ destroy all the components it has\n m_entityAttributes.componentStorage.removeAllComponents(entity);\n\n \/\/ remove it from the id pool\n m_entityIdPool.remove(entity.getId());\n }\n\n \/\/ clear the temp cache\n m_entityCache.clearTemp();\n }\n\n void World::clear()\n {\n removeAllSystems(); \/\/ remove the systems\n\n \/\/ clear the attributes for all the entities\n m_entityAttributes.clear();\n\n \/\/ clear the entity cache\n m_entityCache.clear();\n\n \/\/ clear the id pool\n m_entityIdPool.clear();\n }\n\n std::size_t World::getEntityCount() const\n {\n return m_entityCache.alive.size();\n }\n\n const World::EntityArray& World::getEntities() const\n {\n return m_entityCache.alive;\n }\n\n void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)\n {\n auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;\n if(newSize > m_entityIdPool.getSize())\n {\n resize(newSize);\n }\n }\n\n void World::resize(std::size_t amount)\n {\n m_entityIdPool.resize(amount);\n m_entityAttributes.resize(amount);\n }\n\n void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(!system.m_world, \"System is already contained within a World\");\n ANAX_ASSERT(m_systems.count(systemTypeId) == 0, \"System of this type is already contained within the world\");\n\n m_systems[systemTypeId].reset(&system);\n\n system.m_world = this;\n system.initialize();\n }\n\n void World::removeSystem(detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(doesSystemExist(systemTypeId), \"System does not exist in world\");\n m_systems.erase(systemTypeId);\n }\n\n bool World::doesSystemExist(detail::TypeId systemTypeId) const\n {\n return m_systems.find(systemTypeId) != m_systems.end();\n }\n\n Entity World::getEntity(std::size_t index)\n {\n return Entity{*this, m_entityIdPool.get(index)};\n }\n}\n<commit_msg>Update World.cpp<commit_after>\/\/\/\n\/\/\/ anax\n\/\/\/ An open source C++ entity system.\n\/\/\/\n\/\/\/ Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.com)\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\n#include <anax\/World.hpp>\n\n#include <algorithm>\n\n#include <anax\/Config.hpp>\n\n#include <anax\/detail\/AnaxAssert.hpp>\n#include <anax\/util\/ContainerUtils.hpp>\n\nnamespace anax\n{\n void World::SystemDeleter::operator() (detail::BaseSystem* system) const\n {\n system->m_world = nullptr;\n system->m_entities.clear();\n }\n\n World::World() : \n World(DEFAULT_ENTITY_POOL_SIZE)\n {\n }\n\n World::World(std::size_t entityPoolSize) : \n m_entityIdPool(entityPoolSize),\n m_entityAttributes(entityPoolSize)\n {\n }\n\n void World::removeAllSystems()\n {\n m_systems.clear();\n }\n\n Entity World::createEntity()\n {\n checkForResize(1);\n\n m_entityCache.alive.emplace_back(*this, m_entityIdPool.create());\n return m_entityCache.alive.back();\n }\n\n std::vector<Entity> World::createEntities(std::size_t amount)\n {\n std::vector<Entity> temp;\n temp.reserve(amount);\n\n checkForResize(amount);\n\n for(decltype(amount) i = 0; i < amount; ++i)\n {\n Entity e{*this, m_entityIdPool.create()};\n m_entityCache.alive.push_back(e);\n temp.push_back(e);\n }\n\n return temp;\n }\n\n void World::killEntity(Entity& entity)\n {\n \/\/ deactivate the entity\n deactivateEntity(entity);\n\n \/\/ now kill the entity (add it to the killed cache)\n m_entityCache.killed.push_back(entity);\n }\n\n void World::killEntities(std::vector<Entity>& entities)\n {\n for(auto& i : entities)\n {\n killEntity(i);\n }\n }\n\n void World::activateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be activated\");\n\n m_entityCache.activated.push_back(entity);\n }\n\n void World::deactivateEntity(Entity& entity)\n {\n ANAX_ASSERT(isValid(entity), \"invalid entity tried to be deactivated\");\n\n m_entityCache.deactivated.push_back(entity);\n }\n\n bool World::isActivated(const Entity& entity) const\n {\n if( isValid(entity) )\n return m_entityAttributes.attributes[entity.getId().index].activated;\n else\n return false;\n }\n\n bool World::isValid(const anax::Entity &entity) const\n {\n return m_entityIdPool.isValid(entity.getId());\n }\n\n void World::refresh()\n {\n \/\/ go through all the activated entities from last call to refresh\n for(auto& entity : m_entityCache.activated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = true;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n\n \/\/ if the entity passes the filter the system has and is not already part of the system\n if(i.second->getFilter().doesPassFilter(m_entityAttributes.componentStorage.getComponentTypeList(entity)))\n {\n if(attribute.systems.size() <= systemIndex || !attribute.systems[systemIndex])\n {\n i.second->add(entity); \/\/ add it to the system\n\n util::EnsureCapacity(attribute.systems, systemIndex); \n attribute.systems[systemIndex] = true;\n }\n }\n \/\/ otherwise if the entity is within the system \n \/\/ and is not relevant to the system anymore...\n \/\/ note: the entity has already failed the filter\n else if(attribute.systems.size() > systemIndex && attribute.systems[systemIndex])\n {\n \/\/ duplicate code (1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n\n \/\/ go through all the deactivated entities from last call to refresh\n for(auto& entity : m_entityCache.deactivated)\n {\n auto& attribute = m_entityAttributes.attributes[entity.getId().index]; \n attribute.activated = false;\n\n \/\/ loop through all the systems within the world\n for(auto& i : m_systems)\n {\n auto systemIndex = i.first;\n if(attribute.systems.size() <= systemIndex) continue;\n\n if(attribute.systems[systemIndex])\n {\n \/\/ duplicate code ...(1)\n i.second->remove(entity); \n attribute.systems[systemIndex] = false;\n }\n }\n }\n\n \/\/ go through all the killed entities from last call to refresh\n for(auto& entity : m_entityCache.killed)\n {\n \/\/ remove the entity from the alive array\n m_entityCache.alive.erase(std::remove(m_entityCache.alive.begin(), m_entityCache.alive.end(), entity), m_entityCache.alive.end()); \n\n \/\/ destroy all the components it has\n m_entityAttributes.componentStorage.removeAllComponents(entity);\n\n \/\/ remove it from the id pool\n m_entityIdPool.remove(entity.getId());\n }\n\n \/\/ clear the temp cache\n m_entityCache.clearTemp();\n }\n\n void World::clear()\n {\n removeAllSystems(); \/\/ remove the systems\n\n \/\/ clear the attributes for all the entities\n m_entityAttributes.clear();\n\n \/\/ clear the entity cache\n m_entityCache.clear();\n\n \/\/ clear the id pool\n m_entityIdPool.clear();\n }\n\n std::size_t World::getEntityCount() const\n {\n return m_entityCache.alive.size();\n }\n\n const World::EntityArray& World::getEntities() const\n {\n return m_entityCache.alive;\n }\n\n void World::checkForResize(std::size_t amountOfEntitiesToBeAllocated)\n {\n auto newSize = getEntityCount() + amountOfEntitiesToBeAllocated;\n if(newSize > m_entityIdPool.getSize())\n {\n resize(newSize);\n }\n }\n\n void World::resize(std::size_t amount)\n {\n m_entityIdPool.resize(amount);\n m_entityAttributes.resize(amount);\n }\n\n void World::addSystem(detail::BaseSystem& system, detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(!system.m_world, \"System is already contained within a World\");\n ANAX_ASSERT(m_systems.count(systemTypeId) == 0, \"System of this type is already contained within the world\");\n\n m_systems[systemTypeId].reset(&system);\n\n system.m_world = this;\n system.initialize();\n }\n\n void World::removeSystem(detail::TypeId systemTypeId)\n {\n ANAX_ASSERT(doesSystemExist(systemTypeId), \"System does not exist in world\");\n m_systems.erase(systemTypeId);\n }\n\n bool World::doesSystemExist(detail::TypeId systemTypeId) const\n {\n return m_systems.find(systemTypeId) != m_systems.end();\n }\n\n Entity World::getEntity(std::size_t index)\n {\n return Entity{*this, m_entityIdPool.get(index)};\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 1997-2019 The CSE Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file.\n\n\/\/ cndefns.h -- shared #defines for CSE code and rcdef\/cnrecs.def\n\n\/\/ #included in cnrecs.def, cndtypes.def, .\n\/\/ may be #included in cnglob.h cuz symbols defined here come out in dtypes.h, 1-94\n\n\/\/ NOTE!! These #defines cannot contain expressions (rcdef limitation)\n\n#ifndef _CNEDEFNS_H\t\t\/\/ skip duplicate includes 1-94\n#define _CNEDEFNS_H\t\t\/\/ say included\n\n\/\/------------------------------------------------ OPTIONS --------------------------------------------------\n#define AUTOSIZE\t\/\/ identifies at least code being added for autosizing, 6-95.\n\t\t\t\t\t\/\/ undefining probably won't completely undo.\n\t\t\t\t\t\/\/ later edit out defined.\n\n#undef BINRES\t\/\/ define for code to output binary results files, 11-93.\n\t\t\t\t\/\/ Implemented for NREL, but generally useful (if documented for others!).\n\n\/\/ #define SHINTERP\t\/\/ define for subhour-interpolated weather data. Used in many files. 1-95\n\t\t\t\t\t\/\/ coded out #defined 4-1-10\n\n#undef SOLAVNEND\n\t\t\t\/* undef to use subhour-average interpolated solar or hour-average solar values at all uses.\n\t\t\t Define to make use of subhour-end interpolated values for zones, average values for masses.\n\t\t\t Code for defined incomplete: surface sgdist to zone total must be reworked to use\n\t\t\t avg value for solar SGDIST'd to mass, end value for remainder going to zone, determined\n\t\t\t m-h (eg in cgsolar.cpp) cuz SGDIST sgd_FSC\/O are runtime-variable.\n\t\t\t (Present code fails (ebal errs) when SGDISTS present, eg CKENV\\S1HWN.)\n\t\t\t Could code out undefined after works and Bruce\/Phil confirm (memo NILES108.TXT).\n\t\t\t Used in cnrecs.def, cuparse.cpp, cgwthr,cgsolar,cnloads.cpp. 1-18-95. *\/\n\n\/\/--- option(s) re supporting NREL Design Tool, 1993-94\n\n\/*--- history of removal of former seasons stuff which used different (possibly smaller) sgdist f's in \"summer\".\n * #undef SEASONS 91? 92?: define for vestigial do-nothing seasons and csType, smrBeg, smrEnd, and smrTemp commands.\n *\t\t files: cnrecs, cnguts, cncult,2,3 cuparse, cgsolar, cgwthr at least.\n *\t\t 7-92: Leaving SEASONS DEFINED, redid SGDISTS and cgsolar for shades open-closed not seasons,\n *\t\t\t making seasons do nothing but $isSummer.\n *\t\t 1-93: Undefined SEASONS; put temporary warnings in cncult.cpp re seasons commands.\n *\t\t 2..3-94: All SEASONS code deleted. *\/\n\n\/\/--- following provide grep-able backtrack to deleted obsolete data and code 1-92 (some previously disabled)\n#undef OLDNV\t\/\/ cr\/hst nat vent KEEP THE CODE -- Chip says record needed\n#undef OLDFV\t\/\/ cr\/hst fan vent code\n#undef OLDCF\t\/\/ cr\/hst ceiling fan code\n\n\/\/ enhanced CSE zone models, 7-10\n#undef CZM_COMPARE\t\t\t\/\/ define to use methods identical to those in\n\t\t\t\t\t\t\t\/\/ CZM.BAS (re result comparison) 10-10\n#undef AIRNET_COMPARE\t\t\/\/ #define to use methods identical to those in\n\t\t\t\t\t\t\t\/\/ AirNet.bas (re result comparison)\n#undef CONV_ASHRAECOMPARE\n\n#undef WTHR_T24DLL\t\t\t\/\/ #define to support T24WTHR.DLL source for hourly compliance\n\t\t\t\t\t\t\t\/\/ weather data\n\n\/\/ implement zone exhaust fan, 8-10\n#define ZONE_XFAN\t\/\/ define to enable zone exhaust fan implementation, 8-10\n\t\t\t\t\t\/\/ FAN object historically in ZNISUB.xfan but previously not simulated\n\n\n#undef BUG_COLTYPECOPY\t\/\/ define to include object trap code re memcpy bug\n\t\t\t\t\t\t\/\/ associated with copying COL objects\n\t\t\t\t\t\t\/\/ File coltypebug.cse crashes.\n\t\t\t\t\t\t\/\/ Fixed (maybe) by overriding COL::CopyFrom().\n\t\t\t\t\t\t\/\/ Further research needed: why both Copy() and CopyFrom()?\n\t\t\t\t\t\t\/\/ (both use memcpy(), dangerous when object contains heap ptrs)\n\t\t\t\t\t\t\/\/ 2-24-2012\n\n#undef RSYS_FIXEDOAT\t\/\/ define to cause fixed RSYS supply air temp \/ humrat\n\t\t\t\t\t\t\/\/ (development aid)\n\n#define USE_STDLIB\t\t\/\/ re conversion to non-MFC containers\n\n#undef AUSZ_REPORTS\t\t\/\/ define to enable hourly reports during autosizing\n\t\t\t\t\t\t\/\/ Note: crude at best, use for testing only, 12-31-2012\n\n\/\/------------------------------------------------ DEFINES --------------------------------------------------\n#define MAXSUBSTEPS 120\t\t\/\/ max # of substeps per hour\n\t\t\t\t\t\t\t\/\/ limit may be less if specific items present\n\t\t\t\t\t\t\t\/\/ if DHWSYS is present, limit is 60\n\t\t\t\t\t\t\t\/\/ increase with care, trouble has been seen for higher values\n\t\t\t\t\t\t\t\/\/ e.g. 240 causes wfpak WDSUBHRFACTORS::wdsf_Setup() assert\n\t\t\t\t\t\t\t\/\/ 5-2021\n\n#define HSMXSGDIST 8\t\/\/ Max # of solar gain targets from one XSURF.\n\t\t\t\t\t\t\/\/ Need 1 per solar gain distribution. 4->5 1990, ->8 2-95.\n#define XSMXTLRB 10\t\t\/\/ Max # of layer boundary temps maintained in XSURF\n\t\t\t\t\t\t\/\/ see XSURF.xs_tLrB[]\n\n\n\/\/ terminal and mode definitions; used in cnrecs.def TU, ZNR,\n\/\/#define MAX_TUKS 3\t\/\/ max capabilities per terminal: local heat, air heat, air cool. No uses; define if needed.\n#define MAX_ZONETUS 3\t\/\/ max terminal units allowed to serve a zone: enforced during input\n#define MAX_ZONEMODES 21\t\/\/ max mdSeq[] modes pos with max TUs each with max capabilities:\n\t\t\t\t\t\t\t\/\/ need 2 per TU capability (1 at set point, 1 floating above)\n\t\t\t\t\t\t\t\/\/ + 2 per additional mode (e.g.nat vent) + 1 (low end floating)\n\t\t\t\t\t\t\t\/\/ = 2 * MAX_TUKS * MAX_ZONETUS + 3\n\n#define IVLDATADIM 4\t\t\/\/ dimension of interval data arrays\n\t\t\t\t\t\t\t\/\/ 4 = Y, M, D, H\n\t\t\t\t\t\t\t\/\/ see IvlData() template function, cnglobl.h\n\n#define RSYSMODES 3\t\t\t\/\/ # of RSYS operating modes (not including rsmOFF)\n\t\t\t\t\t\t\t\/\/ must be known in cnrecs.def\n\t\t\t\t\t\t\t\/\/ must be consistent the rsmXXX enum\n\n#define NDHWENDUSESPP 6\t\t\/\/ # of DHW end uses (for use in cnrecs.def)\n\t\t\t\t\t\t\t\/\/ must be same as C_DHWEUCH_COUNT\n\t\t\t\t\t\t\t\/\/ see also cnglob.h const int NDHWENDUSES\n#define NDHWENDUSESXPP 8\t\/\/ # of extended DHW end uses\n\t\t\t\t\t\t\t\/\/ must be same as C_DHWEUXCH_COUNT\n#define NDHWSIZEDAYS 10\t\t\/\/ # of DHW sizing design days for EcoSizer method\n\n#define ASHP_COPREG 6\t\t\/\/ select COP17\/47 regression model\n\t\t\t\t\t\t\t\/\/ 1 = original (2012?)\n\t\t\t\t\t\t\t\/\/ 2 = revised 6-3-2013\n\t\t\t\t\t\t\t\/\/ 3 = COP\/HSPF fit 6-4-2013\n\t\t\t\t\t\t\t\/\/ 4 = kwPerTon fit 6-4-2013\n\t\t\t\t\t\t\t\/\/ 5 = force COP17=1.8 at HSPF=6.8 6-4-2013\n\t\t\t\t\t\t\t\/\/ 6 = derive COP17 and COP35 so HSPF matches input\n\n#define DETAILED_TIMING\t\t\/\/ define to enable fine-grain timing\n\n#undef COMFORT_MODEL\t\t\/\/ define to include comfort model\n\t\t\t\t\t\t\t\/\/ calculation of PPD and PMV\n\n\t\t\t\t\t\t\t\/\/ initial geometry implementation, 2-2017\n\t\t\t\t\t\t\t\/\/ fixed size polygons as input convenience\n\t\t\t\t\t\t\t\/\/ using ARRAY mechanism\n\t\t\t\t\t\t\t\/\/ Note limit is due to ARRAY input only.\n#define MAX_POLYGONVERTICES 12\t\/\/ maximum number of input polygon vertices\n#define DIM_POLYGONXYZ 37\t\t\/\/ input arrays dimension\n\t\t\t\t\t\t\t\t\/\/ = MAX_POLYLPVERTICIES*3 + 1\n\n#define CRTERMAH\t\t\t\/\/ define to enable support of TERMINAL \/ AIRHANDLER model\n\t\t\t\t\t\t\t\/\/ in convective \/ radiant zones\n#undef SUPPRESS_ENBAL_CHECKS\t\/\/ define to suppress energy balance checks\n\t\t\t\t\t\t\t\t\/\/ (development aid)\n\n#endif\t\/\/ ifndef _CNEDEFNS_H\n\n\/\/ cndefns.h end\n<commit_msg>Remove autosize definition.<commit_after>\/\/ Copyright (c) 1997-2019 The CSE Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file.\n\n\/\/ cndefns.h -- shared #defines for CSE code and rcdef\/cnrecs.def\n\n\/\/ #included in cnrecs.def, cndtypes.def, .\n\/\/ may be #included in cnglob.h cuz symbols defined here come out in dtypes.h, 1-94\n\n\/\/ NOTE!! These #defines cannot contain expressions (rcdef limitation)\n\n#ifndef _CNEDEFNS_H\t\t\/\/ skip duplicate includes 1-94\n#define _CNEDEFNS_H\t\t\/\/ say included\n\n\/\/------------------------------------------------ OPTIONS --------------------------------------------------\n#undef BINRES\t\/\/ define for code to output binary results files, 11-93.\n\t\t\t\t\/\/ Implemented for NREL, but generally useful (if documented for others!).\n\n\/\/ #define SHINTERP\t\/\/ define for subhour-interpolated weather data. Used in many files. 1-95\n\t\t\t\t\t\/\/ coded out #defined 4-1-10\n\n#undef SOLAVNEND\n\t\t\t\/* undef to use subhour-average interpolated solar or hour-average solar values at all uses.\n\t\t\t Define to make use of subhour-end interpolated values for zones, average values for masses.\n\t\t\t Code for defined incomplete: surface sgdist to zone total must be reworked to use\n\t\t\t avg value for solar SGDIST'd to mass, end value for remainder going to zone, determined\n\t\t\t m-h (eg in cgsolar.cpp) cuz SGDIST sgd_FSC\/O are runtime-variable.\n\t\t\t (Present code fails (ebal errs) when SGDISTS present, eg CKENV\\S1HWN.)\n\t\t\t Could code out undefined after works and Bruce\/Phil confirm (memo NILES108.TXT).\n\t\t\t Used in cnrecs.def, cuparse.cpp, cgwthr,cgsolar,cnloads.cpp. 1-18-95. *\/\n\n\/\/--- option(s) re supporting NREL Design Tool, 1993-94\n\n\/*--- history of removal of former seasons stuff which used different (possibly smaller) sgdist f's in \"summer\".\n * #undef SEASONS 91? 92?: define for vestigial do-nothing seasons and csType, smrBeg, smrEnd, and smrTemp commands.\n *\t\t files: cnrecs, cnguts, cncult,2,3 cuparse, cgsolar, cgwthr at least.\n *\t\t 7-92: Leaving SEASONS DEFINED, redid SGDISTS and cgsolar for shades open-closed not seasons,\n *\t\t\t making seasons do nothing but $isSummer.\n *\t\t 1-93: Undefined SEASONS; put temporary warnings in cncult.cpp re seasons commands.\n *\t\t 2..3-94: All SEASONS code deleted. *\/\n\n\/\/--- following provide grep-able backtrack to deleted obsolete data and code 1-92 (some previously disabled)\n#undef OLDNV\t\/\/ cr\/hst nat vent KEEP THE CODE -- Chip says record needed\n#undef OLDFV\t\/\/ cr\/hst fan vent code\n#undef OLDCF\t\/\/ cr\/hst ceiling fan code\n\n\/\/ enhanced CSE zone models, 7-10\n#undef CZM_COMPARE\t\t\t\/\/ define to use methods identical to those in\n\t\t\t\t\t\t\t\/\/ CZM.BAS (re result comparison) 10-10\n#undef AIRNET_COMPARE\t\t\/\/ #define to use methods identical to those in\n\t\t\t\t\t\t\t\/\/ AirNet.bas (re result comparison)\n#undef CONV_ASHRAECOMPARE\n\n#undef WTHR_T24DLL\t\t\t\/\/ #define to support T24WTHR.DLL source for hourly compliance\n\t\t\t\t\t\t\t\/\/ weather data\n\n\/\/ implement zone exhaust fan, 8-10\n#define ZONE_XFAN\t\/\/ define to enable zone exhaust fan implementation, 8-10\n\t\t\t\t\t\/\/ FAN object historically in ZNISUB.xfan but previously not simulated\n\n\n#undef BUG_COLTYPECOPY\t\/\/ define to include object trap code re memcpy bug\n\t\t\t\t\t\t\/\/ associated with copying COL objects\n\t\t\t\t\t\t\/\/ File coltypebug.cse crashes.\n\t\t\t\t\t\t\/\/ Fixed (maybe) by overriding COL::CopyFrom().\n\t\t\t\t\t\t\/\/ Further research needed: why both Copy() and CopyFrom()?\n\t\t\t\t\t\t\/\/ (both use memcpy(), dangerous when object contains heap ptrs)\n\t\t\t\t\t\t\/\/ 2-24-2012\n\n#undef RSYS_FIXEDOAT\t\/\/ define to cause fixed RSYS supply air temp \/ humrat\n\t\t\t\t\t\t\/\/ (development aid)\n\n#define USE_STDLIB\t\t\/\/ re conversion to non-MFC containers\n\n#undef AUSZ_REPORTS\t\t\/\/ define to enable hourly reports during autosizing\n\t\t\t\t\t\t\/\/ Note: crude at best, use for testing only, 12-31-2012\n\n\/\/------------------------------------------------ DEFINES --------------------------------------------------\n#define MAXSUBSTEPS 120\t\t\/\/ max # of substeps per hour\n\t\t\t\t\t\t\t\/\/ limit may be less if specific items present\n\t\t\t\t\t\t\t\/\/ if DHWSYS is present, limit is 60\n\t\t\t\t\t\t\t\/\/ increase with care, trouble has been seen for higher values\n\t\t\t\t\t\t\t\/\/ e.g. 240 causes wfpak WDSUBHRFACTORS::wdsf_Setup() assert\n\t\t\t\t\t\t\t\/\/ 5-2021\n\n#define HSMXSGDIST 8\t\/\/ Max # of solar gain targets from one XSURF.\n\t\t\t\t\t\t\/\/ Need 1 per solar gain distribution. 4->5 1990, ->8 2-95.\n#define XSMXTLRB 10\t\t\/\/ Max # of layer boundary temps maintained in XSURF\n\t\t\t\t\t\t\/\/ see XSURF.xs_tLrB[]\n\n\n\/\/ terminal and mode definitions; used in cnrecs.def TU, ZNR,\n\/\/#define MAX_TUKS 3\t\/\/ max capabilities per terminal: local heat, air heat, air cool. No uses; define if needed.\n#define MAX_ZONETUS 3\t\/\/ max terminal units allowed to serve a zone: enforced during input\n#define MAX_ZONEMODES 21\t\/\/ max mdSeq[] modes pos with max TUs each with max capabilities:\n\t\t\t\t\t\t\t\/\/ need 2 per TU capability (1 at set point, 1 floating above)\n\t\t\t\t\t\t\t\/\/ + 2 per additional mode (e.g.nat vent) + 1 (low end floating)\n\t\t\t\t\t\t\t\/\/ = 2 * MAX_TUKS * MAX_ZONETUS + 3\n\n#define IVLDATADIM 4\t\t\/\/ dimension of interval data arrays\n\t\t\t\t\t\t\t\/\/ 4 = Y, M, D, H\n\t\t\t\t\t\t\t\/\/ see IvlData() template function, cnglobl.h\n\n#define RSYSMODES 3\t\t\t\/\/ # of RSYS operating modes (not including rsmOFF)\n\t\t\t\t\t\t\t\/\/ must be known in cnrecs.def\n\t\t\t\t\t\t\t\/\/ must be consistent the rsmXXX enum\n\n#define NDHWENDUSESPP 6\t\t\/\/ # of DHW end uses (for use in cnrecs.def)\n\t\t\t\t\t\t\t\/\/ must be same as C_DHWEUCH_COUNT\n\t\t\t\t\t\t\t\/\/ see also cnglob.h const int NDHWENDUSES\n#define NDHWENDUSESXPP 8\t\/\/ # of extended DHW end uses\n\t\t\t\t\t\t\t\/\/ must be same as C_DHWEUXCH_COUNT\n#define NDHWSIZEDAYS 10\t\t\/\/ # of DHW sizing design days for EcoSizer method\n\n#define ASHP_COPREG 6\t\t\/\/ select COP17\/47 regression model\n\t\t\t\t\t\t\t\/\/ 1 = original (2012?)\n\t\t\t\t\t\t\t\/\/ 2 = revised 6-3-2013\n\t\t\t\t\t\t\t\/\/ 3 = COP\/HSPF fit 6-4-2013\n\t\t\t\t\t\t\t\/\/ 4 = kwPerTon fit 6-4-2013\n\t\t\t\t\t\t\t\/\/ 5 = force COP17=1.8 at HSPF=6.8 6-4-2013\n\t\t\t\t\t\t\t\/\/ 6 = derive COP17 and COP35 so HSPF matches input\n\n#define DETAILED_TIMING\t\t\/\/ define to enable fine-grain timing\n\n#undef COMFORT_MODEL\t\t\/\/ define to include comfort model\n\t\t\t\t\t\t\t\/\/ calculation of PPD and PMV\n\n\t\t\t\t\t\t\t\/\/ initial geometry implementation, 2-2017\n\t\t\t\t\t\t\t\/\/ fixed size polygons as input convenience\n\t\t\t\t\t\t\t\/\/ using ARRAY mechanism\n\t\t\t\t\t\t\t\/\/ Note limit is due to ARRAY input only.\n#define MAX_POLYGONVERTICES 12\t\/\/ maximum number of input polygon vertices\n#define DIM_POLYGONXYZ 37\t\t\/\/ input arrays dimension\n\t\t\t\t\t\t\t\t\/\/ = MAX_POLYLPVERTICIES*3 + 1\n\n#define CRTERMAH\t\t\t\/\/ define to enable support of TERMINAL \/ AIRHANDLER model\n\t\t\t\t\t\t\t\/\/ in convective \/ radiant zones\n#undef SUPPRESS_ENBAL_CHECKS\t\/\/ define to suppress energy balance checks\n\t\t\t\t\t\t\t\t\/\/ (development aid)\n\n#endif\t\/\/ ifndef _CNEDEFNS_H\n\n\/\/ cndefns.h end\n<|endoftext|>"} {"text":"<commit_before>AliGenerator* AddMCGenPythia_He3(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 1., Int_t tune = 2,Int_t cr=1,Float_t ptWeight=0) \n{\n \/\/Add Pythia generator: pt-hard bin or min bias\n\n gSystem->Load(\"liblhapdf\");\n\n\n AliGenCocktail* gener = new AliGenCocktail();\n\n AliGenPythia *genP = NULL;\n genP = CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, tune,cr,ptWeight);\n\n \/\/ deuterons and anti-deuterons\n AliGenLightNuclei* d = new AliGenLightNuclei();\n d->SetNucleusPdgCode(AliGenLightNuclei::kDeuteron);\n d->SetCoalescenceMomentum(0.100); \/\/ default\n d->SetSpinProbability(1);\n d->UsePerEventRates();\n\n \/\/ 3He and anti-3He nuclei\n AliGenLightNuclei* he3 = new AliGenLightNuclei();\n he3->SetNucleusPdgCode(AliGenLightNuclei::kHe3Nucleus);\n he3->SetCoalescenceMomentum(0.127);\n he3->SetSpinProbability(1);\n he3->UsePerEventRates();\n\n gener->AddGenerator(genP, \"pythia8\", 1);\n gener->AddGenerator(d,\"deuteron\",1);\n gener->AddGenerator(he3,\"He3\",1);\n \n return gener;\n}\n\nAliGenPythia* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t tune, Int_t cr,Float_t ptWeight) {\n \n if(tune==3) gSystem->Load(\"libpythia6_4_28\");\n if(tune<3) gSystem->Load(\"libpythia6_4_25\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libAliPythia6\");\n\n AliGenPythia* genP = new AliGenPythia(1);\n\n \/\/ vertex position and smearing \n genP->SetVertexSmear(kPerEvent);\n\n \/\/ structure function\n \/\/ use kCTEQ5l for Perugia tunes \n \/\/ except for tunes: Perugia * (325, MRSTLO*), Perugia 6 (326, CTEQ6L), \n \/\/ Perugia 11 M (355, MRST LO**), Perugia 11 C (356, CTEQ6L1) \n genP->SetStrucFunc(kCTEQ5L); \n\n \/\/ charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb\n if(ptHardMin>0.) {\n \n genP->SetProcess(kPyJets);\n genP->SetPtHard((float)ptHardMin,(float)ptHardMax);\n if(ptWeight>0) genP->SetWeightPower(ptWeight);\n } else\n genP->SetProcess(kPyMb); \/\/ Minimum Bias \n\n \/\/ Centre of mass energy \n genP->SetEnergyCMS(e_cms); \/\/ in GeV\n \n genP->UseNewMultipleInteractionsScenario(); \/\/ for all Pythia versions >= 6.3\n\n if(tune == 0){ \/\/ tune Perugia0\n genP->SetTune(320);\n if(cr==0) genP->SetTune(324);\n }\n if(tune == 1){ \/\/ tune Perugia2010\n genP->SetTune(327);\n if(cr==0) genP->SetTune(324);\n } \n if(tune == 2){ \/\/ tune Perugia2011 ('central' Perugia 2011)\n genP->SetTune(350);\n if(cr==0) genP->SetTune(354);\n }\n if(tune == 3){ \/\/ tune Perugia2012 ('central' Perugia 2012)\n genP->SetTune(370);\n if(cr==0) genP->SetTune(375);\n }\n\n genP->Print();\n\n \n\n return genP;\n}\n<commit_msg>AliFemto: modification for PYTHIA<commit_after>AliGenerator* AddMCGenPythia_He3(Float_t e_cms = 2760., Double_t ptHardMin = 0., Double_t ptHardMax = 1., Int_t tune = 2,Int_t cr=1,Float_t ptWeight=0) \n{\n \/\/Add Pythia generator: pt-hard bin or min bias\n\n AliGenCocktail* gener = new AliGenCocktail();\n\n AliGenPythia *genP = CreatePythia6Gen(e_cms, ptHardMin, ptHardMax, tune,cr,ptWeight);\n\n \/\/ deuterons and anti-deuterons\n AliGenLightNuclei* d = new AliGenLightNuclei();\n d->SetNucleusPdgCode(AliGenLightNuclei::kDeuteron);\n d->SetCoalescenceMomentum(0.100); \/\/ default\n d->SetSpinProbability(1);\n d->UsePerEventRates();\n\n \/\/ 3He and anti-3He nuclei\n AliGenLightNuclei* he3 = new AliGenLightNuclei();\n he3->SetNucleusPdgCode(AliGenLightNuclei::kHe3Nucleus);\n he3->SetCoalescenceMomentum(0.127);\n he3->SetSpinProbability(1);\n he3->UsePerEventRates();\n\n gener->AddGenerator(genP, \"pythia8\", 1);\n gener->AddGenerator(d,\"deuteron\",1);\n gener->AddGenerator(he3,\"He3\",1);\n \n return gener;\n \/\/return genP;\n}\n\n\n\n\nAliGenerator* CreatePythia6Gen(Float_t e_cms, Int_t ptHardMin, Int_t ptHardMax, Int_t tune, Int_t cr,Float_t ptWeight) {\n\n \n if(tune==3) gSystem->Load(\"libpythia6_4_28\");\n if(tune<3) gSystem->Load(\"libpythia6_4_25\");\n gSystem->Load(\"libEGPythia6\");\n gSystem->Load(\"libAliPythia6\");\n \n\n AliGenPythia* genP = new AliGenPythia(1);\n\n \/\/ vertex position and smearing \n genP->SetVertexSmear(kPerEvent);\n\n \/\/ structure function\n \/\/ use kCTEQ5l for Perugia tunes \n \/\/ except for tunes: Perugia * (325, MRSTLO*), Perugia 6 (326, CTEQ6L), \n \/\/ Perugia 11 M (355, MRST LO**), Perugia 11 C (356, CTEQ6L1) \n genP->SetStrucFunc(kCTEQ5L); \n\n \/\/ charm, beauty, charm_unforced, beauty_unforced, jpsi, jpsi_chi, mb\n if(ptHardMin>0.) {\n \n genP->SetProcess(kPyJets);\n genP->SetPtHard((float)ptHardMin,(float)ptHardMax);\n if(ptWeight>0) genP->SetWeightPower(ptWeight);\n } else\n genP->SetProcess(kPyMb); \/\/ Minimum Bias \n\n \/\/ Centre of mass energy \n genP->SetEnergyCMS(e_cms); \/\/ in GeV\n \n \/\/genP->UseNewMultipleInteractionsScenario(); \/\/ for all Pythia versions >= 6.3\n\n if(tune == 0){ \/\/ tune Perugia0\n genP->SetTune(320);\n if(cr==0) genP->SetTune(324);\n }\n if(tune == 1){ \/\/ tune Perugia2010\n genP->SetTune(327);\n if(cr==0) genP->SetTune(324);\n } \n if(tune == 2){ \/\/ tune Perugia2011 ('central' Perugia 2011)\n genP->SetTune(350);\n if(cr==0) genP->SetTune(354);\n }\n if(tune == 3){ \/\/ tune Perugia2012 ('central' Perugia 2012)\n genP->SetTune(370);\n if(cr==0) genP->SetTune(375);\n }\n\n genP->Print();\n\n \n\n return genP;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"Utils.h\"\n#include \"Clazy.h\"\n#include \"StringUtils.h\"\n#include \"clazy_stl.h\"\n#include \"checkbase.h\"\n#include \"checkmanager.h\"\n#include \"AccessSpecifierManager.h\"\n\n#include \"clang\/Frontend\/FrontendPluginRegistry.h\"\n#include \"clang\/AST\/AST.h\"\n\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Rewrite\/Frontend\/FixItRewriter.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include <llvm\/Config\/llvm-config.h>\n\n#include <stdio.h>\n#include <sstream>\n#include <iostream>\n\nusing namespace clang;\nusing namespace std;\n\nnamespace {\n\n\nclass MyFixItOptions : public FixItOptions\n{\npublic:\n MyFixItOptions(const MyFixItOptions &other) = delete;\n MyFixItOptions(bool inplace)\n {\n InPlace = inplace;\n FixWhatYouCan = true;\n FixOnlyWarnings = true;\n Silent = false;\n }\n\n std::string RewriteFilename(const std::string &filename, int &fd) override\n {\n fd = -1;\n return InPlace ? filename : filename + \"_fixed.cpp\";\n }\n\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6\n \/\/ Clang >= 3.7 already has this member.\n \/\/ We define it for clang <= 3.6 so it builds.\n bool InPlace;\n#endif\n};\n\nstatic void manuallyPopulateParentMap(ParentMap *map, Stmt *s)\n{\n if (!s)\n return;\n\n for (Stmt *child : s->children()) {\n llvm::errs() << \"Patching \" << child->getStmtClassName() << \"\\n\";\n map->setParent(child, s);\n manuallyPopulateParentMap(map, child);\n }\n}\n\nclass LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>\n{\n LazyASTConsumer(const LazyASTConsumer &) = delete;\npublic:\n LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,\n const RegisteredCheck::List &requestedChecks, bool inplaceFixits)\n : m_ci(ci)\n , m_sm(ci.getSourceManager())\n , m_rewriter(nullptr)\n , m_parentMap(nullptr)\n , m_checkManager(checkManager)\n {\n m_createdChecks = checkManager->createChecks(requestedChecks, ci);\n if (checkManager->fixitsEnabled())\n m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));\n }\n\n ~LazyASTConsumer()\n {\n if (m_rewriter) {\n m_rewriter->WriteFixedFiles();\n delete m_rewriter;\n }\n\n delete m_parentMap;\n }\n\n void setParentMap(ParentMap *map)\n {\n assert(map && !m_parentMap);\n m_parentMap = map;\n for (auto &check : m_createdChecks)\n check->setParentMap(map);\n }\n\n bool VisitDecl(Decl *decl)\n {\n const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());\n\n#if !defined(IS_OLD_CLANG)\n if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())\n a->VisitDeclaration(decl);\n#endif\n for (const auto &check : m_createdChecks) {\n if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))\n check->VisitDeclaration(decl);\n }\n\n return true;\n }\n\n bool VisitStmt(Stmt *stm)\n {\n if (!m_parentMap) {\n if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())\n return false; \/\/ ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.\n\n setParentMap(new ParentMap(stm));\n }\n\n \/\/ Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.\n if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {\n m_parentMap->setParent(stm, lastStm);\n manuallyPopulateParentMap(m_parentMap, stm);\n }\n\n lastStm = stm;\n\n \/\/ clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration\n \/\/ So add to parent map each time we go into a different hierarchy\n if (!m_parentMap->hasParent(stm))\n m_parentMap->addStmt(stm);\n\n const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());\n for (const auto &check : m_createdChecks) {\n if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))\n check->VisitStatement(stm);\n }\n\n return true;\n }\n\n void HandleTranslationUnit(ASTContext &ctx) override\n {\n TraverseDecl(ctx.getTranslationUnitDecl());\n }\n\n Stmt *lastStm = nullptr;\n CompilerInstance &m_ci;\n const SourceManager &m_sm;\n FixItRewriter *m_rewriter;\n ParentMap *m_parentMap;\n CheckBase::List m_createdChecks;\n CheckManager *const m_checkManager;\n};\n\n}\n\nstatic bool parseArgument(const string &arg, vector<string> &args)\n{\n auto it = clazy_std::find(args, arg);\n if (it != args.end()) {\n args.erase(it, it + 1);\n return true;\n }\n\n return false;\n}\n\nstatic CheckLevel parseLevel(vector<std::string> &args)\n{\n static const vector<string> levels = { \"level0\", \"level1\", \"level2\", \"level3\", \"level4\" };\n const int numLevels = levels.size();\n for (int i = 0; i < numLevels; ++i) {\n if (parseArgument(levels.at(i), args)) {\n return static_cast<CheckLevel>(i);\n }\n }\n\n return CheckLevelUndefined;\n}\n\nstatic bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)\n{\n return c1.name < c2.name;\n}\n\nstatic bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)\n{\n if (c1.level == c2.level)\n return checkLessThan(c1, c2);\n\n return c1.level < c2.level;\n}\n\n\nClazyASTAction::ClazyASTAction()\n : PluginASTAction()\n , m_checkManager(CheckManager::instance())\n{\n}\n\nstd::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)\n{\n return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);\n}\n\nbool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)\n{\n std::vector<std::string> args = args_;\n\n if (parseArgument(\"help\", args)) {\n PrintHelp(llvm::errs());\n return true;\n }\n\n if (parseArgument(\"no-inplace-fixits\", args)) {\n \/\/ Unit-tests don't use inplace fixits\n m_inplaceFixits = false;\n }\n\n \/\/ This argument is for debugging purposes\n const bool printRequestedChecks = parseArgument(\"print-requested-checks\", args);\n\n const CheckLevel requestedLevel = parseLevel(\/*by-ref*\/args);\n if (requestedLevel != CheckLevelUndefined) {\n m_checkManager->setRequestedLevel(requestedLevel);\n }\n\n if (parseArgument(\"enable-all-fixits\", args)) {\n \/\/ This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.\n m_checkManager->enableAllFixIts();\n }\n\n if (args.size() > 1) {\n \/\/ Too many arguments.\n llvm::errs() << \"Too many arguments: \";\n for (const std::string &a : args)\n llvm::errs() << a << ' ';\n llvm::errs() << \"\\n\";\n\n PrintHelp(llvm::errs());\n return false;\n } else if (args.size() == 1) {\n vector<string> userDisabledChecks;\n m_checks = m_checkManager->checksForCommaSeparatedString(args[0], \/*by-ref=*\/userDisabledChecks);\n if (m_checks.empty()) {\n llvm::errs() << \"Could not find checks in comma separated string \" + args[0] + \"\\n\";\n PrintHelp(llvm::errs());\n return false;\n }\n }\n\n vector<string> userDisabledChecks;\n \/\/ Append checks specified from env variable\n RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(\/*by-ref*\/userDisabledChecks);\n copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));\n\n if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {\n \/\/ No check or level specified, lets use the default level\n m_checkManager->setRequestedLevel(DefaultCheckLevel);\n }\n\n \/\/ Add checks from requested level\n auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();\n clazy_std::append(checksFromRequestedLevel, m_checks);\n clazy_std::sort_and_remove_dups(m_checks, checkLessThan);\n CheckManager::removeChecksFromList(m_checks, userDisabledChecks);\n\n if (printRequestedChecks) {\n llvm::errs() << \"Requested checks: \";\n const unsigned int numChecks = m_checks.size();\n for (unsigned int i = 0; i < numChecks; ++i) {\n llvm::errs() << m_checks.at(i).name;\n const bool isLast = i == numChecks - 1;\n if (!isLast) {\n llvm::errs() << \", \";\n }\n }\n\n llvm::errs() << \"\\n\";\n }\n\n return true;\n}\n\nvoid ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)\n{\n RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);\n clazy_std::sort(checks, checkLessThanByLevel);\n\n ros << \"Available checks and FixIts:\\n\\n\";\n\n int lastPrintedLevel = -1;\n const auto numChecks = checks.size();\n for (unsigned int i = 0; i < numChecks; ++i) {\n const RegisteredCheck &check = checks[i];\n if (lastPrintedLevel < check.level) {\n lastPrintedLevel = check.level;\n\n if (check.level > 0)\n ros << \"\\n\";\n\n ros << \"- Checks from level\" << to_string(check.level) << \":\\n\";\n }\n\n auto padded = check.name;\n padded.insert(padded.end(), 39 - padded.size(), ' ');\n ros << \" - \" << check.name;\n auto fixits = m_checkManager->availableFixIts(check.name);\n if (!fixits.empty()) {\n ros << \" (\";\n bool isFirst = true;\n for (const auto& fixit : fixits) {\n if (isFirst) {\n isFirst = false;\n } else {\n ros << ',';\n }\n\n ros << fixit.name;\n }\n ros << ')';\n }\n ros << \"\\n\";\n }\n ros << \"\\nIf nothing is specified, all checks from level0 and level1 will be run.\\n\\n\";\n ros << \"To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\\n\";\n ros << \" export CLAZY_CHECKS=\\\"level0\\\"\\n\";\n ros << \" export CLAZY_CHECKS=\\\"level0,reserve-candidates,qstring-allocations\\\"\\n\";\n ros << \" export CLAZY_CHECKS=\\\"reserve-candidates\\\"\\n\\n\";\n ros << \"or pass as compiler arguments, for example:\\n\";\n ros << \" -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\\n\";\n ros << \"\\n\";\n ros << \"To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\\n\";\n ros << \" export CLAZY_FIXIT=\\\"fix-qlatin1string-allocations\\\"\\n\\n\";\n ros << \"FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\\nSpecifying a list of different FixIts is not supported.\\nBackup your code before running them.\\n\";\n}\n\nstatic FrontendPluginRegistry::Add<ClazyASTAction>\nX(\"clang-lazy\", \"clang lazy plugin\");\n<commit_msg>Allow to print help formated with markdown<commit_after>\/*\n This file is part of the clazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"Utils.h\"\n#include \"Clazy.h\"\n#include \"StringUtils.h\"\n#include \"clazy_stl.h\"\n#include \"checkbase.h\"\n#include \"checkmanager.h\"\n#include \"AccessSpecifierManager.h\"\n\n#include \"clang\/Frontend\/FrontendPluginRegistry.h\"\n#include \"clang\/AST\/AST.h\"\n\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Rewrite\/Frontend\/FixItRewriter.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include <llvm\/Config\/llvm-config.h>\n\n#include <stdio.h>\n#include <sstream>\n#include <iostream>\n\nusing namespace clang;\nusing namespace std;\n\nnamespace {\n\n\nclass MyFixItOptions : public FixItOptions\n{\npublic:\n MyFixItOptions(const MyFixItOptions &other) = delete;\n MyFixItOptions(bool inplace)\n {\n InPlace = inplace;\n FixWhatYouCan = true;\n FixOnlyWarnings = true;\n Silent = false;\n }\n\n std::string RewriteFilename(const std::string &filename, int &fd) override\n {\n fd = -1;\n return InPlace ? filename : filename + \"_fixed.cpp\";\n }\n\n#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6\n \/\/ Clang >= 3.7 already has this member.\n \/\/ We define it for clang <= 3.6 so it builds.\n bool InPlace;\n#endif\n};\n\nstatic void manuallyPopulateParentMap(ParentMap *map, Stmt *s)\n{\n if (!s)\n return;\n\n for (Stmt *child : s->children()) {\n llvm::errs() << \"Patching \" << child->getStmtClassName() << \"\\n\";\n map->setParent(child, s);\n manuallyPopulateParentMap(map, child);\n }\n}\n\nclass LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>\n{\n LazyASTConsumer(const LazyASTConsumer &) = delete;\npublic:\n LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,\n const RegisteredCheck::List &requestedChecks, bool inplaceFixits)\n : m_ci(ci)\n , m_sm(ci.getSourceManager())\n , m_rewriter(nullptr)\n , m_parentMap(nullptr)\n , m_checkManager(checkManager)\n {\n m_createdChecks = checkManager->createChecks(requestedChecks, ci);\n if (checkManager->fixitsEnabled())\n m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));\n }\n\n ~LazyASTConsumer()\n {\n if (m_rewriter) {\n m_rewriter->WriteFixedFiles();\n delete m_rewriter;\n }\n\n delete m_parentMap;\n }\n\n void setParentMap(ParentMap *map)\n {\n assert(map && !m_parentMap);\n m_parentMap = map;\n for (auto &check : m_createdChecks)\n check->setParentMap(map);\n }\n\n bool VisitDecl(Decl *decl)\n {\n const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());\n\n#if !defined(IS_OLD_CLANG)\n if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())\n a->VisitDeclaration(decl);\n#endif\n for (const auto &check : m_createdChecks) {\n if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))\n check->VisitDeclaration(decl);\n }\n\n return true;\n }\n\n bool VisitStmt(Stmt *stm)\n {\n if (!m_parentMap) {\n if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())\n return false; \/\/ ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.\n\n setParentMap(new ParentMap(stm));\n }\n\n \/\/ Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.\n if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {\n m_parentMap->setParent(stm, lastStm);\n manuallyPopulateParentMap(m_parentMap, stm);\n }\n\n lastStm = stm;\n\n \/\/ clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration\n \/\/ So add to parent map each time we go into a different hierarchy\n if (!m_parentMap->hasParent(stm))\n m_parentMap->addStmt(stm);\n\n const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());\n for (const auto &check : m_createdChecks) {\n if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))\n check->VisitStatement(stm);\n }\n\n return true;\n }\n\n void HandleTranslationUnit(ASTContext &ctx) override\n {\n TraverseDecl(ctx.getTranslationUnitDecl());\n }\n\n Stmt *lastStm = nullptr;\n CompilerInstance &m_ci;\n const SourceManager &m_sm;\n FixItRewriter *m_rewriter;\n ParentMap *m_parentMap;\n CheckBase::List m_createdChecks;\n CheckManager *const m_checkManager;\n};\n\n}\n\nstatic bool parseArgument(const string &arg, vector<string> &args)\n{\n auto it = clazy_std::find(args, arg);\n if (it != args.end()) {\n args.erase(it, it + 1);\n return true;\n }\n\n return false;\n}\n\nstatic CheckLevel parseLevel(vector<std::string> &args)\n{\n static const vector<string> levels = { \"level0\", \"level1\", \"level2\", \"level3\", \"level4\" };\n const int numLevels = levels.size();\n for (int i = 0; i < numLevels; ++i) {\n if (parseArgument(levels.at(i), args)) {\n return static_cast<CheckLevel>(i);\n }\n }\n\n return CheckLevelUndefined;\n}\n\nstatic bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)\n{\n return c1.name < c2.name;\n}\n\nstatic bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)\n{\n if (c1.level == c2.level)\n return checkLessThan(c1, c2);\n\n return c1.level < c2.level;\n}\n\n\nClazyASTAction::ClazyASTAction()\n : PluginASTAction()\n , m_checkManager(CheckManager::instance())\n{\n}\n\nstd::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)\n{\n return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);\n}\n\nbool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)\n{\n std::vector<std::string> args = args_;\n\n if (parseArgument(\"help\", args)) {\n PrintHelp(llvm::errs());\n return true;\n }\n\n if (parseArgument(\"no-inplace-fixits\", args)) {\n \/\/ Unit-tests don't use inplace fixits\n m_inplaceFixits = false;\n }\n\n \/\/ This argument is for debugging purposes\n const bool printRequestedChecks = parseArgument(\"print-requested-checks\", args);\n\n const CheckLevel requestedLevel = parseLevel(\/*by-ref*\/args);\n if (requestedLevel != CheckLevelUndefined) {\n m_checkManager->setRequestedLevel(requestedLevel);\n }\n\n if (parseArgument(\"enable-all-fixits\", args)) {\n \/\/ This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.\n m_checkManager->enableAllFixIts();\n }\n\n if (args.size() > 1) {\n \/\/ Too many arguments.\n llvm::errs() << \"Too many arguments: \";\n for (const std::string &a : args)\n llvm::errs() << a << ' ';\n llvm::errs() << \"\\n\";\n\n PrintHelp(llvm::errs());\n return false;\n } else if (args.size() == 1) {\n vector<string> userDisabledChecks;\n m_checks = m_checkManager->checksForCommaSeparatedString(args[0], \/*by-ref=*\/userDisabledChecks);\n if (m_checks.empty()) {\n llvm::errs() << \"Could not find checks in comma separated string \" + args[0] + \"\\n\";\n PrintHelp(llvm::errs());\n return false;\n }\n }\n\n vector<string> userDisabledChecks;\n \/\/ Append checks specified from env variable\n RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(\/*by-ref*\/userDisabledChecks);\n copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));\n\n if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {\n \/\/ No check or level specified, lets use the default level\n m_checkManager->setRequestedLevel(DefaultCheckLevel);\n }\n\n \/\/ Add checks from requested level\n auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();\n clazy_std::append(checksFromRequestedLevel, m_checks);\n clazy_std::sort_and_remove_dups(m_checks, checkLessThan);\n CheckManager::removeChecksFromList(m_checks, userDisabledChecks);\n\n if (printRequestedChecks) {\n llvm::errs() << \"Requested checks: \";\n const unsigned int numChecks = m_checks.size();\n for (unsigned int i = 0; i < numChecks; ++i) {\n llvm::errs() << m_checks.at(i).name;\n const bool isLast = i == numChecks - 1;\n if (!isLast) {\n llvm::errs() << \", \";\n }\n }\n\n llvm::errs() << \"\\n\";\n }\n\n return true;\n}\n\nvoid ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)\n{\n RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);\n clazy_std::sort(checks, checkLessThanByLevel);\n\n ros << \"Available checks and FixIts:\\n\\n\";\n const bool useMarkdown = getenv(\"CLAZY_HELP_USE_MARKDOWN\");\n\n int lastPrintedLevel = -1;\n const auto numChecks = checks.size();\n for (unsigned int i = 0; i < numChecks; ++i) {\n const RegisteredCheck &check = checks[i];\n const string levelStr = \"level\" + to_string(check.level);\n if (lastPrintedLevel < check.level) {\n lastPrintedLevel = check.level;\n\n if (check.level > 0)\n ros << \"\\n\";\n\n ros << \"- Checks from \" << levelStr << \":\\n\";\n }\n\n const string relativeReadmePath = levelStr + \"\/README-\" + check.name + \".md\";\n\n auto padded = check.name;\n padded.insert(padded.end(), 39 - padded.size(), ' ');\n ros << \" - \" << (useMarkdown ? \"[\" : \"\") << check.name << (useMarkdown ? \"](\" + relativeReadmePath + \")\" : \"\");\n auto fixits = m_checkManager->availableFixIts(check.name);\n if (!fixits.empty()) {\n ros << \" (\";\n bool isFirst = true;\n for (const auto& fixit : fixits) {\n if (isFirst) {\n isFirst = false;\n } else {\n ros << ',';\n }\n\n ros << fixit.name;\n }\n ros << ')';\n }\n ros << \"\\n\";\n }\n ros << \"\\nIf nothing is specified, all checks from level0 and level1 will be run.\\n\\n\";\n ros << \"To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\\n\";\n ros << \" export CLAZY_CHECKS=\\\"level0\\\"\\n\";\n ros << \" export CLAZY_CHECKS=\\\"level0,reserve-candidates,qstring-allocations\\\"\\n\";\n ros << \" export CLAZY_CHECKS=\\\"reserve-candidates\\\"\\n\\n\";\n ros << \"or pass as compiler arguments, for example:\\n\";\n ros << \" -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\\n\";\n ros << \"\\n\";\n ros << \"To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\\n\";\n ros << \" export CLAZY_FIXIT=\\\"fix-qlatin1string-allocations\\\"\\n\\n\";\n ros << \"FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\\nSpecifying a list of different FixIts is not supported.\\nBackup your code before running them.\\n\";\n}\n\nstatic FrontendPluginRegistry::Add<ClazyASTAction>\nX(\"clang-lazy\", \"clang lazy plugin\");\n<|endoftext|>"} {"text":"<commit_before>#include <catch.hpp>\n\n#include <httplib\/http\/request.hpp>\n\n#include <sstream>\n\n\nTEST_CASE(\"request's output operator outputs\", \"[http_request_t]\") {\n httplib::http_request_t request {\n \"MyMETHOD\",\n \"\/url\/path?query&arg=value#frag\",\n {13, 37},\n {\n {\"Content-Length\", {\"10\"}},\n {\"Content-Type\", {\"application\/json\"}},\n {\"Home\", {\"localhost\"}},\n {\"xxx\", {\"yyy\", \"zzz\"}}\n }\n };\n\n std::ostringstream stream;\n stream << request;\n\n std::string expected =\n \"MyMETHOD \/url\/path?query&arg=value#frag HTTP\/13.37\\r\\n\"\n \"Home: localhost\\r\\n\"\n \"Content-Length: 10\\r\\n\"\n \"Content-Type: application\/json\\r\\n\"\n \"xxx: yyy\\r\\n\"\n \"xxx: zzz\\r\\n\"\n \"\\r\\n\";\n\n REQUIRE(stream.str() == expected);\n}\n<commit_msg>One more check.<commit_after>#include <catch.hpp>\n\n#include <httplib\/http\/request.hpp>\n\n#include <sstream>\n\n\nTEST_CASE(\"request's output operator outputs\", \"[http_request_t]\") {\n httplib::http_request_t request {\n \"MyMETHOD\",\n \"\/url\/path?query&arg=value#frag\",\n {13, 37},\n {\n {\"Content-Length\", {\"10\"}},\n {\"Content-Type\", {\"application\/json\"}},\n {\"Home\", {\"localhost\"}},\n {\"xxx\", {\"yyy\", \"zzz\"}}\n }\n };\n\n std::ostringstream stream;\n stream << request;\n\n REQUIRE(static_cast<bool>(stream));\n\n std::string expected =\n \"MyMETHOD \/url\/path?query&arg=value#frag HTTP\/13.37\\r\\n\"\n \"Home: localhost\\r\\n\"\n \"Content-Length: 10\\r\\n\"\n \"Content-Type: application\/json\\r\\n\"\n \"xxx: yyy\\r\\n\"\n \"xxx: zzz\\r\\n\"\n \"\\r\\n\";\n\n REQUIRE(stream.str() == expected);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\n#include \"gUniqueGlyphIDs.h\"\n\nclass FontCacheBench : public SkBenchmark {\n enum { N = SkBENCHLOOP(50) };\npublic:\n FontCacheBench(void* param) : INHERITED(param) {\n }\n\nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return \"fontcache\";\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n const uint16_t* array = gUniqueGlyphIDs;\n while (*array != 0xFFFF) {\n const uint16_t* end = array + 1;\n while (*end != 0xFFFF) {\n end += 1;\n }\n for (int i = 0; i < N; ++i) {\n size_t len = (end - array) * sizeof(uint16_t);\n paint.measureText(array, len);\n }\n array = end + 1; \/\/ skip the sentinel\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDEF_BENCH( return new FontCacheBench(p); )\n<commit_msg>add cache efficiency test<commit_after>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\n#include \"gUniqueGlyphIDs.h\"\n#define gUniqueGlyphIDs_Sentinel 0xFFFF\n\nstatic int count_glyphs(const uint16_t start[]) {\n const uint16_t* curr = start;\n while (*curr != gUniqueGlyphIDs_Sentinel) {\n curr += 1;\n }\n return curr - start;\n}\n\nclass FontCacheBench : public SkBenchmark {\n enum {\n N = SkBENCHLOOP(50)\n };\n\npublic:\n FontCacheBench(void* param) : INHERITED(param) {}\n \nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return \"fontcache\";\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n SkPaint paint;\n this->setupPaint(&paint);\n paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n \n const uint16_t* array = gUniqueGlyphIDs;\n while (*array != gUniqueGlyphIDs_Sentinel) {\n size_t count = count_glyphs(array);\n for (int i = 0; i < N; ++i) {\n paint.measureText(array, count * sizeof(uint16_t));\n }\n array += count + 1; \/\/ skip the sentinel\n }\n }\n \nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic uint32_t rotr(uint32_t value, unsigned bits) {\n return (value >> bits) | (value << (32 - bits));\n}\n\ntypedef uint32_t (*HasherProc)(uint32_t);\n\nstatic uint32_t hasher0(uint32_t value) {\n value = value ^ (value >> 16);\n return value ^ (value >> 8);\n}\n\nstatic uint32_t hasher2(uint32_t h) {\n h ^= h >> 16;\n h *= 0x85ebca6b;\n h ^= h >> 13;\n h *= 0xc2b2ae35;\n h ^= h >> 16;\n \n h ^= (h >> 8);\n return h;\n}\n\nstatic const struct {\n const char* fName;\n HasherProc fHasher;\n} gRec[] = {\n { \"hasher0\", hasher0 },\n { \"hasher2\", hasher2 },\n};\n\n#define kMaxHashBits 12\n#define kMaxHashCount (1 << kMaxHashBits)\n\nstatic int count_collisions(const uint16_t array[], int count, HasherProc proc,\n unsigned hashMask) {\n char table[kMaxHashCount];\n sk_bzero(table, sizeof(table));\n \n int collisions = 0;\n for (int i = 0; i < count; ++i) {\n int index = proc(array[i]) & hashMask;\n collisions += table[index];\n table[index] = 1;\n }\n return collisions;\n}\n\nstatic void dump_array(const uint16_t array[], int count) {\n for (int i = 0; i < count; ++i) {\n SkDebugf(\" %d,\", array[i]);\n }\n SkDebugf(\"\\n\");\n}\n\nclass FontCacheEfficiency : public SkBenchmark {\npublic:\n FontCacheEfficiency(void* param) : INHERITED(param) {\n if (false) dump_array(NULL, 0);\n if (false) rotr(0, 0);\n }\n \nprotected:\n virtual const char* onGetName() SK_OVERRIDE {\n return \"fontefficiency\";\n }\n \n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n static bool gDone;\n if (gDone) {\n return;\n }\n gDone = true;\n\n for (int hashBits = 6; hashBits <= 12; hashBits += 1) {\n int hashMask = ((1 << hashBits) - 1);\n for (int limit = 32; limit <= 1024; limit <<= 1) {\n for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {\n int collisions = 0;\n int glyphs = 0;\n const uint16_t* array = gUniqueGlyphIDs;\n while (*array != gUniqueGlyphIDs_Sentinel) {\n int count = SkMin32(count_glyphs(array), limit);\n collisions += count_collisions(array, count, gRec[i].fHasher, hashMask);\n glyphs += count;\n array += count + 1; \/\/ skip the sentinel\n }\n SkDebugf(\"hashBits [%d] limit [%d] collisions [%d \/ %d = %1.2g%%] using %s\\n\", hashBits, limit, collisions, glyphs,\n collisions * 100.0 \/ glyphs, gRec[i].fName);\n }\n }\n }\n }\n \nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDEF_BENCH( return new FontCacheBench(p); )\n\n\/\/ undefine this to run the efficiency test\n\/\/DEF_BENCH( return new FontCacheEfficiency(p); )\n<|endoftext|>"} {"text":"<commit_before>#include \"Course.h\"\n#include <string>\nusing namespace std;\n\nCourse::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){\n\tstartTime = _startTime;\n\tendTime = _endTime;\n\tdays = _days;\n\tcourseName = _courseName;\n\tcourseLoc = _courseLoc;\n\tcourseId = _courseId;\n}\n\nint const Course::getEndTime(){\n\treturn endTime;\n}\n\nint const Course::getStartTime(){\n\treturn startTime;\n}\n\nstring const Course::getDays(){\n\treturn days;\n}\n\nstring const Course::getName(){\n\treturn courseName;\n}\n\nstring const Course::getLoc(){\n\treturn courseLoc;\n}\n\nint const Course::getId(){\n\treturn courseId;\n}\n\nvoid Course::setRating(unsigned int _rating){\n\n}\n\nint const Course::getRating(){\n\treturn 0;\n}<commit_msg>Course.it11 - pass: rating<commit_after>#include \"Course.h\"\n#include <string>\nusing namespace std;\n\nCourse::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){\n\tstartTime = _startTime;\n\tendTime = _endTime;\n\tdays = _days;\n\tcourseName = _courseName;\n\tcourseLoc = _courseLoc;\n\tcourseId = _courseId;\n}\n\nint const Course::getEndTime(){\n\treturn endTime;\n}\n\nint const Course::getStartTime(){\n\treturn startTime;\n}\n\nstring const Course::getDays(){\n\treturn days;\n}\n\nstring const Course::getName(){\n\treturn courseName;\n}\n\nstring const Course::getLoc(){\n\treturn courseLoc;\n}\n\nint const Course::getId(){\n\treturn courseId;\n}\n\nvoid Course::setRating(unsigned int _rating){\n\trating = _rating;\n}\n\nint const Course::getRating(){\n\treturn rating;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- Mutex.cpp - Mutual Exclusion Lock ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the llvm::sys::Mutex class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/Mutex.h\"\n#include \"llvm\/Config\/config.h\"\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_MUTEX_LOCK)\n\nnamespace llvm {\nusing namespace sys;\n\n#include <cassert>\n#include <pthread.h>\n#include <stdlib.h>\n\n\/\/ This variable is useful for situations where the pthread library has been\n\/\/ compiled with weak linkage for its interface symbols. This allows the\n\/\/ threading support to be turned off by simply not linking against -lpthread.\n\/\/ In that situation, the value of pthread_mutex_init will be 0 and\n\/\/ consequently pthread_enabled will be false. In such situations, all the\n\/\/ pthread operations become no-ops and the functions all return false. If\n\/\/ pthread_mutex_init does have an address, then mutex support is enabled.\n\/\/ Note: all LLVM tools will link against -lpthread if its available since it\n\/\/ is configured into the LIBS variable.\n\/\/ Note: this line of code generates a warning if pthread_mutex_init is not\n\/\/ declared with weak linkage. Its safe to ignore the warning.\nstatic const bool pthread_enabled = static_cast<bool>(pthread_mutex_init);\n\n\/\/ Construct a Mutex using pthread calls\nMutex::Mutex( bool recursive)\n : data_(0)\n{\n if (pthread_enabled)\n {\n \/\/ Declare the pthread_mutex data structures\n pthread_mutex_t* mutex =\n static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));\n pthread_mutexattr_t attr;\n\n \/\/ Initialize the mutex attributes\n int errorcode = pthread_mutexattr_init(&attr);\n assert(errorcode == 0);\n\n \/\/ Initialize the mutex as a recursive mutex, if requested, or normal\n \/\/ otherwise.\n int kind = ( recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORMAL );\n errorcode = pthread_mutexattr_settype(&attr, kind);\n assert(errorcode == 0);\n\n#ifndef __FreeBSD__\n \/\/ Make it a process local mutex\n errorcode = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);\n#endif\n\n \/\/ Initialize the mutex\n errorcode = pthread_mutex_init(mutex, &attr);\n assert(errorcode == 0);\n\n \/\/ Destroy the attributes\n errorcode = pthread_mutexattr_destroy(&attr);\n assert(errorcode == 0);\n\n \/\/ Assign the data member\n data_ = mutex;\n }\n}\n\n\/\/ Destruct a Mutex\nMutex::~Mutex()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n int errorcode = pthread_mutex_destroy(mutex);\n assert(mutex != 0);\n }\n}\n\nbool\nMutex::acquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_lock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::release()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_unlock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::tryacquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_trylock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\n}\n\n#elif defined(LLVM_ON_UNIX)\n#include \"Unix\/Mutex.inc\"\n#elif defined( LLVM_ON_WIN32)\n#include \"Win32\/Mutex.inc\"\n#else\n#warning Neither LLVM_ON_UNIX nor LLVM_ON_WIN32 was set in System\/Mutex.cpp\n#endif\n<commit_msg>Fix grammar: it's == \"it is\".<commit_after>\/\/===- Mutex.cpp - Mutual Exclusion Lock ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the llvm::sys::Mutex class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/Mutex.h\"\n#include \"llvm\/Config\/config.h\"\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_MUTEX_LOCK)\n\nnamespace llvm {\nusing namespace sys;\n\n#include <cassert>\n#include <pthread.h>\n#include <stdlib.h>\n\n\/\/ This variable is useful for situations where the pthread library has been\n\/\/ compiled with weak linkage for its interface symbols. This allows the\n\/\/ threading support to be turned off by simply not linking against -lpthread.\n\/\/ In that situation, the value of pthread_mutex_init will be 0 and\n\/\/ consequently pthread_enabled will be false. In such situations, all the\n\/\/ pthread operations become no-ops and the functions all return false. If\n\/\/ pthread_mutex_init does have an address, then mutex support is enabled.\n\/\/ Note: all LLVM tools will link against -lpthread if its available since it\n\/\/ is configured into the LIBS variable.\n\/\/ Note: this line of code generates a warning if pthread_mutex_init is not\n\/\/ declared with weak linkage. It's safe to ignore the warning.\nstatic const bool pthread_enabled = static_cast<bool>(pthread_mutex_init);\n\n\/\/ Construct a Mutex using pthread calls\nMutex::Mutex( bool recursive)\n : data_(0)\n{\n if (pthread_enabled)\n {\n \/\/ Declare the pthread_mutex data structures\n pthread_mutex_t* mutex =\n static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));\n pthread_mutexattr_t attr;\n\n \/\/ Initialize the mutex attributes\n int errorcode = pthread_mutexattr_init(&attr);\n assert(errorcode == 0);\n\n \/\/ Initialize the mutex as a recursive mutex, if requested, or normal\n \/\/ otherwise.\n int kind = ( recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORMAL );\n errorcode = pthread_mutexattr_settype(&attr, kind);\n assert(errorcode == 0);\n\n#ifndef __FreeBSD__\n \/\/ Make it a process local mutex\n errorcode = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);\n#endif\n\n \/\/ Initialize the mutex\n errorcode = pthread_mutex_init(mutex, &attr);\n assert(errorcode == 0);\n\n \/\/ Destroy the attributes\n errorcode = pthread_mutexattr_destroy(&attr);\n assert(errorcode == 0);\n\n \/\/ Assign the data member\n data_ = mutex;\n }\n}\n\n\/\/ Destruct a Mutex\nMutex::~Mutex()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n int errorcode = pthread_mutex_destroy(mutex);\n assert(mutex != 0);\n }\n}\n\nbool\nMutex::acquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_lock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::release()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_unlock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::tryacquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_trylock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\n}\n\n#elif defined(LLVM_ON_UNIX)\n#include \"Unix\/Mutex.inc\"\n#elif defined( LLVM_ON_WIN32)\n#include \"Win32\/Mutex.inc\"\n#else\n#warning Neither LLVM_ON_UNIX nor LLVM_ON_WIN32 was set in System\/Mutex.cpp\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLAutoTextEventExport.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 14:57:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLAUTOTEXTEVENTEXPORT_HXX\n#define _XMLOFF_XMLAUTOTEXTEVENTEXPORT_HXX\n\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n\n#include <set>\n\n\nnamespace rtl { class OUString; }\nnamespace com { namespace sun { namespace star {\n namespace container { class XNameAccess; }\n namespace frame { class XModel; }\n namespace lang { class XMultiServiceFactory; }\n namespace uno { template<class X> class Reference; }\n namespace uno { template<class X> class Sequence; }\n namespace uno { class XInterface; }\n namespace uno { class Exception; }\n namespace xml { namespace sax { class XDocumentHandler; } }\n} } }\n\n\n\/**\n * Component for the export of events attached to autotext blocks.\n * Via the XInitialization interface it expects up to two strings, the\n * first giving the file name (URL) of the autotext group, and the second\n * identifying the autotext. If one of the strings is not given, it\n * will export the whole group \/ all groups.\n *\/\nclass XMLAutoTextEventExport : public SvXMLExport\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::container::XNameAccess> xEvents;\n\n const ::rtl::OUString sEventType;\n const ::rtl::OUString sNone;\n\n\npublic:\n\n \/\/ #110680#\n \/\/XMLAutoTextEventExport();\n XMLAutoTextEventExport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, sal_uInt16 nFlags\n );\n\n \/\/ #110680#\n \/\/XMLAutoTextEventExport(\n \/\/ const ::rtl::OUString& rFileName,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::frame::XModel > & rModel,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::container::XNameAccess > & rEvents);\n XMLAutoTextEventExport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,\n const ::rtl::OUString& rFileName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,\n const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel,\n const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > & rEvents, sal_uInt16 nFlags);\n\n ~XMLAutoTextEventExport();\n\n \/\/ XInitialization\n virtual void SAL_CALL initialize(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Any> & rArguments )\n throw(\n ::com::sun::star::uno::Exception,\n ::com::sun::star::uno::RuntimeException);\n\nprotected:\n\n \/\/\/ export the events off all autotexts\n virtual sal_uInt32 exportDoc(\n enum ::xmloff::token::XMLTokenEnum eClass = xmloff::token::XML_TOKEN_INVALID );\n\n \/\/\/ does the document have any events ?\n sal_Bool hasEvents();\n\n \/\/\/ export the events element\n void exportEvents();\n\n\n \/\/\/ add the namespaces used by events\n \/\/\/ (to be called for the document element)\n void addNamespaces();\n\n\n \/\/ methods without content:\n virtual void _ExportMeta();\n virtual void _ExportScripts();\n virtual void _ExportFontDecls();\n virtual void _ExportStyles( sal_Bool bUsed ) ;\n virtual void _ExportAutoStyles();\n virtual void _ExportMasterStyles();\n virtual void _ExportChangeTracking();\n virtual void _ExportContent();\n};\n\n\n\n\/\/ global functions to support the component\n\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n XMLAutoTextEventExport_getSupportedServiceNames()\n throw();\n\n::rtl::OUString SAL_CALL XMLAutoTextEventExport_getImplementationName()\n throw();\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n XMLAutoTextEventExportOOO_createInstance(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > & )\n throw( ::com::sun::star::uno::Exception );\n\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n XMLAutoTextEventExportOOO_getSupportedServiceNames()\n throw();\n\n::rtl::OUString SAL_CALL XMLAutoTextEventExportOOO_getImplementationName()\n throw();\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n XMLAutoTextEventExportOOO_createInstance(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > & )\n throw( ::com::sun::star::uno::Exception );\n\n#endif\n\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.7.276); FILE MERGED 2007\/06\/04 13:23:35 vg 1.7.276.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLAutoTextEventExport.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 15:51:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLAUTOTEXTEVENTEXPORT_HXX\n#define _XMLOFF_XMLAUTOTEXTEVENTEXPORT_HXX\n\n#ifndef _XMLOFF_XMLEXP_HXX\n#include <xmloff\/xmlexp.hxx>\n#endif\n\n#include <set>\n\n\nnamespace rtl { class OUString; }\nnamespace com { namespace sun { namespace star {\n namespace container { class XNameAccess; }\n namespace frame { class XModel; }\n namespace lang { class XMultiServiceFactory; }\n namespace uno { template<class X> class Reference; }\n namespace uno { template<class X> class Sequence; }\n namespace uno { class XInterface; }\n namespace uno { class Exception; }\n namespace xml { namespace sax { class XDocumentHandler; } }\n} } }\n\n\n\/**\n * Component for the export of events attached to autotext blocks.\n * Via the XInitialization interface it expects up to two strings, the\n * first giving the file name (URL) of the autotext group, and the second\n * identifying the autotext. If one of the strings is not given, it\n * will export the whole group \/ all groups.\n *\/\nclass XMLAutoTextEventExport : public SvXMLExport\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::container::XNameAccess> xEvents;\n\n const ::rtl::OUString sEventType;\n const ::rtl::OUString sNone;\n\n\npublic:\n\n \/\/ #110680#\n \/\/XMLAutoTextEventExport();\n XMLAutoTextEventExport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, sal_uInt16 nFlags\n );\n\n \/\/ #110680#\n \/\/XMLAutoTextEventExport(\n \/\/ const ::rtl::OUString& rFileName,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::frame::XModel > & rModel,\n \/\/ const ::com::sun::star::uno::Reference<\n \/\/ ::com::sun::star::container::XNameAccess > & rEvents);\n XMLAutoTextEventExport(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,\n const ::rtl::OUString& rFileName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler,\n const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & rModel,\n const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > & rEvents, sal_uInt16 nFlags);\n\n ~XMLAutoTextEventExport();\n\n \/\/ XInitialization\n virtual void SAL_CALL initialize(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Any> & rArguments )\n throw(\n ::com::sun::star::uno::Exception,\n ::com::sun::star::uno::RuntimeException);\n\nprotected:\n\n \/\/\/ export the events off all autotexts\n virtual sal_uInt32 exportDoc(\n enum ::xmloff::token::XMLTokenEnum eClass = xmloff::token::XML_TOKEN_INVALID );\n\n \/\/\/ does the document have any events ?\n sal_Bool hasEvents();\n\n \/\/\/ export the events element\n void exportEvents();\n\n\n \/\/\/ add the namespaces used by events\n \/\/\/ (to be called for the document element)\n void addNamespaces();\n\n\n \/\/ methods without content:\n virtual void _ExportMeta();\n virtual void _ExportScripts();\n virtual void _ExportFontDecls();\n virtual void _ExportStyles( sal_Bool bUsed ) ;\n virtual void _ExportAutoStyles();\n virtual void _ExportMasterStyles();\n virtual void _ExportChangeTracking();\n virtual void _ExportContent();\n};\n\n\n\n\/\/ global functions to support the component\n\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n XMLAutoTextEventExport_getSupportedServiceNames()\n throw();\n\n::rtl::OUString SAL_CALL XMLAutoTextEventExport_getImplementationName()\n throw();\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n XMLAutoTextEventExportOOO_createInstance(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > & )\n throw( ::com::sun::star::uno::Exception );\n\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n XMLAutoTextEventExportOOO_getSupportedServiceNames()\n throw();\n\n::rtl::OUString SAL_CALL XMLAutoTextEventExportOOO_getImplementationName()\n throw();\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n XMLAutoTextEventExportOOO_createInstance(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory > & )\n throw( ::com::sun::star::uno::Exception );\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constant.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n : Name(name), Ty(checkType(ty)) {\n VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as \n \/\/ a <badref>\n \/\/\n if (Uses.begin() != Uses.end()) {\n std::cerr << \"While deleting: \" << *Ty << \"%\" << Name << \"\\n\";\n for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)\n std::cerr << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(Uses.begin() == Uses.end() &&\"Uses remain when a value is destroyed!\");\n\n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\n\n\n\nvoid Value::replaceAllUsesWith(Value *New) {\n assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n assert(New->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n while (!Uses.empty()) {\n User *Use = Uses.back();\n \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n \/\/ constant!\n if (Constant *C = dyn_cast<Constant>(Use)) {\n C->replaceUsesOfWithOnConstant(this, New);\n } else {\n Use->replaceUsesOfWith(this, New);\n }\n }\n}\n\n\/\/ uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,\n\/\/ except that it doesn't have all of the asserts. The asserts fail because we\n\/\/ are half-way done resolving types, which causes some types to exist as two\n\/\/ different Type*'s at the same time. This is a sledgehammer to work around\n\/\/ this problem.\n\/\/\nvoid Value::uncheckedReplaceAllUsesWith(Value *New) {\n while (!Uses.empty()) {\n User *Use = Uses.back();\n \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n \/\/ constant!\n if (Constant *C = dyn_cast<Constant>(Use)) {\n C->replaceUsesOfWithOnConstant(this, New, true);\n } else {\n Use->replaceUsesOfWith(this, New);\n }\n }\n}\n\n\nvoid Value::killUse(User *U) {\n assert(U != 0 && \"Null users are not allowed!\");\n unsigned i;\n\n \/\/ Scan backwards through the uses list looking for the user. We do this\n \/\/ because vectors like to be accessed on the end. This is incredibly\n \/\/ important from a performance perspective.\n for (i = Uses.size()-1; Uses[i] != U; --i)\n \/* empty *\/;\n\n assert(i < Uses.size() && \"Use not in uses list!!\");\n Uses[i] = Uses.back();\n Uses.pop_back();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n assert(!isa<Constant>(this) &&\n \"Cannot call User::replaceUsesofWith on a constant!\");\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n<commit_msg><commit_after>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constant.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n assert(Ty && \"Value defined with a null type: Error!\");\n return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n : Name(name), Ty(checkType(ty)) {\n VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG \/\/ Only in -g mode...\n \/\/ Check to make sure that there are no uses of this value that are still\n \/\/ around when the value is destroyed. If there are, then we have a dangling\n \/\/ reference and something is wrong. This code is here to print out what is\n \/\/ still being referenced. The value in question should be printed as \n \/\/ a <badref>\n \/\/\n if (Uses.begin() != Uses.end()) {\n std::cerr << \"While deleting: \" << *Ty << \"%\" << Name << \"\\n\";\n for (use_const_iterator I = Uses.begin(), E = Uses.end(); I != E; ++I)\n std::cerr << \"Use still stuck around after Def is destroyed:\"\n << **I << \"\\n\";\n }\n#endif\n assert(Uses.begin() == Uses.end() &&\"Uses remain when a value is destroyed!\");\n\n \/\/ There should be no uses of this object anymore, remove it.\n LeakDetector::removeGarbageObject(this);\n}\n\n\n\/\/ uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,\n\/\/ except that it doesn't have all of the asserts. The asserts fail because we\n\/\/ are half-way done resolving types, which causes some types to exist as two\n\/\/ different Type*'s at the same time. This is a sledgehammer to work around\n\/\/ this problem.\n\/\/\nvoid Value::uncheckedReplaceAllUsesWith(Value *New) {\n while (!Uses.empty()) {\n Use &U = Uses.back();\n \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n \/\/ constant!\n if (Constant *C = dyn_cast<Constant>(U.getUser())) {\n C->replaceUsesOfWithOnConstant(this, New);\n } else {\n U.set(New);\n }\n }\n}\n\nvoid Value::replaceAllUsesWith(Value *New) {\n assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n assert(New->getType() == getType() &&\n \"replaceAllUses of value with new value of different type!\");\n\n uncheckedReplaceAllUsesWith(New);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n if (From == To) return; \/\/ Duh what?\n\n assert(!isa<Constant>(this) &&\n \"Cannot call User::replaceUsesofWith on a constant!\");\n\n for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n if (getOperand(i) == From) { \/\/ Is This operand is pointing to oldval?\n \/\/ The side effects of this setOperand call include linking to\n \/\/ \"To\", adding \"this\" to the uses list of To, and\n \/\/ most importantly, removing \"this\" from the use list of \"From\".\n setOperand(i, To); \/\/ Fix it now...\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QImage>\n#include <QtDebug>\n#include <QDir>\n#include <QMessageBox>\n#include <qmath.h>\n#include <math.h>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n QString versionString;\n versionString.append(APP_VERSION);\n qDebug() << versionString;\n ui->labVersion->setText(\"Version: \" + versionString);\n cursor = new QCursor();\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updatePos()));\n\n scene = new QGraphicsScene(ui->graphicsView);\n ui->graphicsView->setScene(scene);\n ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n\n calc = new QPixelCalculator(this);\n\n patientInfoString = \"PatientInfo\";\n testInfoString = \"TestInfo\";\n settings = new QSettings(this);\n picIndex = 1;\n diagonalCMDouble = 1;\n\n timer->start(5);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::updatePos()\n{\n static QPoint lastCursorPosition;\n QPointF mouse = cursor->pos();\n if(lastCursorPosition != mouse) \/\/make sure someone is touching the screen\n {\n ui->graphicsView->scene()->addEllipse(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y(), 3, 3, QPen(), QBrush(Qt::red));\n lastCursorPosition = mouse.toPoint();\n dataListRaw.append(QPoint(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y()));\n }\n}\n\nvoid MainWindow::calcPPCM()\n{\n calc->calculatePPCM(this->width(), this->height(), diagonalCMDouble);\n}\n\nvoid MainWindow::on_pbCalibrate_clicked()\n{\n calcPPCM();\n\n loadSettings();\n dataListRaw.clear();\n\n if(ui->pbCalibrate->text() != \"Reset\")\n {\n ui->pbCalibrate->setText(\"Reset\");\n }\n}\n\nvoid MainWindow::drawDataFieldInformation()\n{\n scene->clear();\n scene->setSceneRect(0,0,ui->graphicsView->width(), ui->graphicsView->height());\n ui->graphicsView->resetTransform();\n\n calcPPCM();\n\n for(int i=0; i<ui->graphicsView->width();i = i + (int)calc->getPPCM())\n {\n scene->addLine(i, 0, i, ui->graphicsView->height(), QPen(QBrush(Qt::gray), 1)); \/\/vertical lines\n }\n for(int i=0; i<ui->graphicsView->height();i = i+ (int)calc->getPPCM())\n {\n scene->addLine(0, i, ui->graphicsView->width(), i, QPen(QBrush(Qt::gray), 1)); \/\/horizontal lines\n }\n\n \/\/Add date to data field\n QDate date;\n QGraphicsSimpleTextItem * dateItem = new QGraphicsSimpleTextItem;\n dateItem->setText(date.currentDate().toString(\"MMM dd yyyy\"));\n dateItem->setPos(0,0);\n scene->addItem(dateItem);\n\n \/\/Add patient info to data field\n QGraphicsSimpleTextItem * patientInfo = new QGraphicsSimpleTextItem;\n patientInfo->setText(patientInfoString);\n patientInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50, 0);\n scene->addItem(patientInfo);\n\n \/\/Add test info to data field\n QGraphicsSimpleTextItem * testInfo = new QGraphicsSimpleTextItem;\n testInfo->setText(testInfoString);\n testInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50, 0);\n scene->addItem(testInfo);\n\n \/\/Add trial (index) number\n QString trialString;\n trialString.append(\"Trial: \");\n trialString.append(QString::number(picIndex).rightJustified(2,'0'));\n QGraphicsSimpleTextItem * trialInfo = new QGraphicsSimpleTextItem;\n trialInfo->setText(trialString);\n trialInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50 + testInfo->boundingRect().width() + 50, 0);\n scene->addItem(trialInfo);\n\n QList<QGraphicsItem *> items = scene->items();\n foreach(QGraphicsItem *i, items)\n {\n i->setFlag(QGraphicsItem::ItemIgnoresTransformations);\n }\n qDebug() << \"Redrew data field static components\";\n}\n\nvoid MainWindow::on_pbSaveData_clicked()\n{\n timer->stop(); \/\/pause the data-gathering\n ui->graphicsView->viewport()->update(); \/\/update data field\n\n QDir photoDir(\"\/mnt\/sdcard\/thumbdata\");\n if(!photoDir.exists())\n {\n if(photoDir.mkdir(\"\/mnt\/sdcard\/thumbdata\") == false) \/\/if couldn't make dir\n {\n errorDialog = new ErrorDialog(this);\n errorDialog->exec();\n qDebug() << \"Error: Could not find or create the folder to save the data in.\";\n }\n }\n\n QString fileName = photoDir.absolutePath() + \"\/\" + patientInfoString + \"-\" + testInfoString + QString::number(picIndex).rightJustified(2,'0') + \".png\";\n QPixmap pixMap = QPixmap::grabWidget(ui->graphicsView);\n if(pixMap.save(fileName))\n {\n savedDialog = new SavedDialog(this);\n savedDialog->exec();\n qDebug() << \"Info: Picture saved as \" + fileName;\n }\n else\n {\n errorDialog = new ErrorDialog(this);\n errorDialog->exec();\n qDebug() << \"Error: Couldn't save the pixmap\";\n }\n\n picIndex++;\n\n timer->start(); \/\/resume the data-gathering\n}\n\nvoid MainWindow::loadSettings()\n{\n patientInfoString = settings->value(\"patientInfoString\", \"Patient Info\").toString();\n testInfoString = settings->value(\"testInfoString\", \"Test Info\").toString();\n diagonalCMDouble = settings->value(\"diagonalCM\", 1).toDouble();\n qDebug() << \"Settings loaded in MainWindow\";\n\n drawDataFieldInformation(); \/\/refresh the display to reflect updates\n}\n\nvoid MainWindow::on_pbSettings_clicked()\n{\n loadSettings(); \/\/fix CTD bug?\n settingsDialog = new SettingsDialog(patientInfoString, testInfoString, diagonalCMDouble, this);\n connect(settingsDialog, SIGNAL(patientInfo(QString)), this, SLOT(patientInfo(QString)));\n connect(settingsDialog, SIGNAL(testInfo(QString)), this, SLOT(testInfo(QString)));\n connect(settingsDialog, SIGNAL(diagonalCM(double)), this, SLOT(diagonalCM(double)));\n connect(settingsDialog, SIGNAL(accepted()), this, SLOT(resetPicIndex()));\n connect(settingsDialog, SIGNAL(accepted()), timer, SLOT(start()));\n connect(settingsDialog, SIGNAL(rejected()), timer, SLOT(start()));\n timer->stop(); \/\/pause the data-gathering\n settingsDialog->exec();\n}\n\nvoid MainWindow::resetPicIndex()\n{\n picIndex = 1; \/\/reset counter\n loadSettings(); \/\/load the settings\n qDebug() << \"Reset counter and called loadSettings()\";\n}\n\nvoid MainWindow::patientInfo(QString patient)\n{\n patientInfoString = patient;\n settings->setValue(\"patientInfoString\", patientInfoString);\n settings->sync();\n qDebug() << \"Patient info copied from Settings dialog\";\n}\n\nvoid MainWindow::testInfo(QString test)\n{\n testInfoString = test;\n settings->setValue(\"testInfoString\", testInfoString);\n settings->sync();\n qDebug() << \"Test info copied from Settings dialog\";\n}\n\nvoid MainWindow::diagonalCM(double cm)\n{\n diagonalCMDouble = cm;\n settings->setValue(\"diagonalCM\", diagonalCMDouble);\n settings->sync();\n qDebug() << \"diagonalCMDouble copied from Settings dialog\";\n}\n\nQPointF MainWindow::calcCircle()\n{\n \/\/Prep work first, including gathering of data points\n QPointF center;\n center.setX(-1);\n center.setY(-1);\n\n QPointF roughCenter;\n roughCenter.setX(-1);\n roughCenter.setY(-1);\n\n int sectionBreak = dataListRaw.count()\/10; \/\/break the datalist into 10 sections\n\n QList<QPointF> roughCenterList; \/\/hold all calculated center points\n\n qDebug() << \"---------- Starting to calculate center points ----------\";\n qDebug() << \"dataListRaw count: \" << dataListRaw.count();\n for(int i= 0; i <dataListRaw.count() - 2;i++)\n {\n qDebug() << \"Low: \" << i << \", High: \" << (i + 2);\n QPointF a = dataListRaw.at(i);\n QPointF b = dataListRaw.at(i+1);\n QPointF c = dataListRaw.at(i+2);\n if(a.x() != b.x() && b.x() != c.x() && a.x() != c.x() && a.y() != b.y() && b.y() != c.y() && a.y() != c.y())\n {\n QPointF cP = calcCenter(a,b,c);\n if(cP.x() < - 3000 || cP.x() > 3000 || cP.y() < - 3000 || cP.y() > 3000)\n {\n qDebug() << \"Ignoring centerpoint at \" << cP << \" for being too far away from a reasonable value!\";\n }\n else\n {\n roughCenterList.append(cP);\n }\n }\n }\n\n qDebug() << \"---------- Finished calculating center points ----------\";\n\n roughCenter = calcAveragePoint(roughCenterList); \/\/Calculate the rough average center point\n\n QList<QPointF> centerList;\n\n foreach(QPointF centerPoint, roughCenterList)\n {\n if(calcDistance(centerPoint, roughCenter) < 450) \/\/if the points are near the original center point\n {\n centerList.append(centerPoint);\n }\n else\n {\n qDebug() << \"Ignoring centerpoint at \" << centerPoint << \" for being too far away from the average!\";\n }\n }\n\n if(!centerList.isEmpty())\n {\n center = calcAveragePoint(centerList);\n }\n else\n {\n qDebug() << \"ERROR: Accurate center point list is empty!\";\n }\n\n \/\/Draw information on screen\n QPointF testPoint = dataListRaw.at(sectionBreak*3);\n int radius = sqrt( ((center.x() - testPoint.x()) * (center.x() - testPoint.x())) + ((center.y() - testPoint.y()) * (center.y() - testPoint.y())) );\n scene->addEllipse(center.x()-radius, center.y()-radius, 2 * radius, 2 * radius, QPen(Qt::black), QBrush(QColor(0,255,0,64)));\n\n rom.setRadius((double)radius);\n rom.setCenterPoint(center);\n\n qDebug() << \"Radius (px): \" << radius;\n qDebug() << \"PPCM: \" << calc->getPPCM();\n\n return center;\n}\n\nQPointF MainWindow::calcCenter(QPointF a, QPointF b, QPointF c)\n{\n QPointF centerTemp;\n\n qDebug() << a << \"; \" << b << \"; \" << c;\n double yDelta0 = b.y() - a.y();\n double xDelta0 = b.x() - a.x();\n double yDelta1 = c.y() - b.y();\n double xDelta1 = c.x() - b.x();\n\n double slope0 = yDelta0\/xDelta0;\n double slope1 = yDelta1\/xDelta1;\n double xD = 0;\n double yD = 0;\n\n xD = ( (slope0 * slope1 * (a.y() - c.y())) + (slope1 * (a.x() + b.x())) - (slope0 * (b.x() + c.x())) ) \/ (2.0 *(slope1 - slope0));\n yD = -1.0 * (xD - ((a.x() + b.x()) \/ 2 )) \/ slope0 + ((a.y() +b.y()) \/ 2);\n\n centerTemp.setX((int)xD);\n centerTemp.setY((int)yD);\n\n qDebug() << \"Calculated center here: \" << centerTemp;\n return centerTemp;\n}\n\ndouble MainWindow::calcROM() \/\/calculate the Range of Motion\n{\n double romDegrees = -1;\n\n calcCircle();\n\n QPointF furthestPoint = QPointF(-1, -1);\n QPoint lastPoint = QPoint(0,0);\n\n foreach(QPoint p, dataListRaw) \/\/find the furthest point down\n {\n if(p.y() >= lastPoint.y())\n {\n furthestPoint.setX(p.x());\n furthestPoint.setY(p.y());\n lastPoint = p;\n }\n else\n {\n\n }\n }\n\n scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), furthestPoint.x(), furthestPoint.y(), QPen(Qt::blue));\n qDebug() << \"Furthest Point: \" << furthestPoint;\n\n QPointF verticalPoint = rom.getCenterPoint();\n\n verticalPoint.setY(verticalPoint.y() - rom.getRadius());\n scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), verticalPoint.x(), verticalPoint.y(), QPen(Qt::blue));\n qDebug() << \"Vertical Point: \" << verticalPoint;\n\n double deltaX = verticalPoint.x() - furthestPoint.x();\n double deltaY = verticalPoint.y() - furthestPoint.y();\n\n double chordLength = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n double thetaR = qAcos( ( (chordLength * chordLength) - (2 * (rom.getRadius() * rom.getRadius())) ) \/ ( -2 * (rom.getRadius() * rom.getRadius())) );\n\n double thetaD = 180.0 * thetaR \/ M_PI;\n\n romDegrees = thetaD;\n\n qDebug() << \"Range of Motion degrees: \" << romDegrees;\n\n return romDegrees;\n}\n\nvoid MainWindow::on_pbAnalyze_clicked()\n{\n calcROM();\n}\n\ndouble MainWindow::calcDistance(QPointF a, QPointF b)\n{\n double deltaX = a.x() - b.x();\n double deltaY = a.y() - b.y();\n\n double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n return d;\n}\n\ndouble MainWindow::calcDistance(QPoint a, QPoint b)\n{\n double deltaX = (double)a.x() - (double)b.x();\n double deltaY = (double)a.y() - (double)b.y();\n\n double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n return d;\n}\n\nQPointF MainWindow::calcAveragePoint(QList<QPointF> l)\n{\n\n qDebug() << \"---------- Starting to calculate average point ----------\";\n QPointF avgPnt = QPointF(0,0);\n\n foreach(QPointF p, l)\n {\n avgPnt.setX(avgPnt.x() + p.x());\n avgPnt.setY(avgPnt.y() + p.y());\n }\n\n avgPnt.setX(avgPnt.x() \/ (double)l.count());\n avgPnt.setY(avgPnt.y() \/ (double)l.count());\n qDebug() << \"Average point: \" << avgPnt;\n qDebug() << \"---------- Calculated average point ----------\";\n return avgPnt;\n}\n<commit_msg>Trashing data points outside of the scene rect Changed error checking for center point finding<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QImage>\n#include <QtDebug>\n#include <QDir>\n#include <QMessageBox>\n#include <qmath.h>\n#include <math.h>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n QString versionString;\n versionString.append(APP_VERSION);\n qDebug() << versionString;\n ui->labVersion->setText(\"Version: \" + versionString);\n cursor = new QCursor();\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updatePos()));\n\n scene = new QGraphicsScene(ui->graphicsView);\n ui->graphicsView->setScene(scene);\n ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n\n calc = new QPixelCalculator(this);\n\n patientInfoString = \"PatientInfo\";\n testInfoString = \"TestInfo\";\n settings = new QSettings(this);\n picIndex = 1;\n diagonalCMDouble = 1;\n\n timer->start(5);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::updatePos()\n{\n static QPoint lastCursorPosition;\n QPointF mouse = cursor->pos();\n QRectF view = ui->graphicsView->sceneRect();\n if(lastCursorPosition != mouse) \/\/make sure someone is touching the screen\n {\n if(mouse.x() - ui->graphicsView->x() > view.left() && mouse.x() - ui->graphicsView->x() < view.right() && mouse.y() - ui->graphicsView->y() > view.top() && mouse.y() - ui->graphicsView->y() < view.bottom())\n {\n ui->graphicsView->scene()->addEllipse(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y(), 3, 3, QPen(), QBrush(Qt::red));\n dataListRaw.append(QPoint(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y()));\n }\n else\n {\n qDebug() << \"Touch outside of the scene view!\";\n }\n lastCursorPosition = mouse.toPoint();\n }\n}\n\nvoid MainWindow::calcPPCM()\n{\n calc->calculatePPCM(this->width(), this->height(), diagonalCMDouble);\n}\n\nvoid MainWindow::on_pbCalibrate_clicked()\n{\n calcPPCM();\n\n loadSettings();\n dataListRaw.clear();\n\n if(ui->pbCalibrate->text() != \"Reset\")\n {\n ui->pbCalibrate->setText(\"Reset\");\n }\n}\n\nvoid MainWindow::drawDataFieldInformation()\n{\n scene->clear();\n scene->setSceneRect(0,0,ui->graphicsView->width(), ui->graphicsView->height());\n ui->graphicsView->resetTransform();\n\n calcPPCM();\n\n for(int i=0; i<ui->graphicsView->width();i = i + (int)calc->getPPCM())\n {\n scene->addLine(i, 0, i, ui->graphicsView->height(), QPen(QBrush(Qt::gray), 1)); \/\/vertical lines\n }\n for(int i=0; i<ui->graphicsView->height();i = i+ (int)calc->getPPCM())\n {\n scene->addLine(0, i, ui->graphicsView->width(), i, QPen(QBrush(Qt::gray), 1)); \/\/horizontal lines\n }\n\n \/\/Add date to data field\n QDate date;\n QGraphicsSimpleTextItem * dateItem = new QGraphicsSimpleTextItem;\n dateItem->setText(date.currentDate().toString(\"MMM dd yyyy\"));\n dateItem->setPos(0,0);\n scene->addItem(dateItem);\n\n \/\/Add patient info to data field\n QGraphicsSimpleTextItem * patientInfo = new QGraphicsSimpleTextItem;\n patientInfo->setText(patientInfoString);\n patientInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50, 0);\n scene->addItem(patientInfo);\n\n \/\/Add test info to data field\n QGraphicsSimpleTextItem * testInfo = new QGraphicsSimpleTextItem;\n testInfo->setText(testInfoString);\n testInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50, 0);\n scene->addItem(testInfo);\n\n \/\/Add trial (index) number\n QString trialString;\n trialString.append(\"Trial: \");\n trialString.append(QString::number(picIndex).rightJustified(2,'0'));\n QGraphicsSimpleTextItem * trialInfo = new QGraphicsSimpleTextItem;\n trialInfo->setText(trialString);\n trialInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50 + testInfo->boundingRect().width() + 50, 0);\n scene->addItem(trialInfo);\n\n QList<QGraphicsItem *> items = scene->items();\n foreach(QGraphicsItem *i, items)\n {\n i->setFlag(QGraphicsItem::ItemIgnoresTransformations);\n }\n qDebug() << \"Redrew data field static components\";\n}\n\nvoid MainWindow::on_pbSaveData_clicked()\n{\n timer->stop(); \/\/pause the data-gathering\n ui->graphicsView->viewport()->update(); \/\/update data field\n\n QDir photoDir(\"\/mnt\/sdcard\/thumbdata\");\n if(!photoDir.exists())\n {\n if(photoDir.mkdir(\"\/mnt\/sdcard\/thumbdata\") == false) \/\/if couldn't make dir\n {\n errorDialog = new ErrorDialog(this);\n errorDialog->exec();\n qDebug() << \"Error: Could not find or create the folder to save the data in.\";\n }\n }\n\n QString fileName = photoDir.absolutePath() + \"\/\" + patientInfoString + \"-\" + testInfoString + QString::number(picIndex).rightJustified(2,'0') + \".png\";\n QPixmap pixMap = QPixmap::grabWidget(ui->graphicsView);\n if(pixMap.save(fileName))\n {\n savedDialog = new SavedDialog(this);\n savedDialog->exec();\n qDebug() << \"Info: Picture saved as \" + fileName;\n }\n else\n {\n errorDialog = new ErrorDialog(this);\n errorDialog->exec();\n qDebug() << \"Error: Couldn't save the pixmap\";\n }\n\n picIndex++;\n\n timer->start(); \/\/resume the data-gathering\n}\n\nvoid MainWindow::loadSettings()\n{\n patientInfoString = settings->value(\"patientInfoString\", \"Patient Info\").toString();\n testInfoString = settings->value(\"testInfoString\", \"Test Info\").toString();\n diagonalCMDouble = settings->value(\"diagonalCM\", 1).toDouble();\n qDebug() << \"Settings loaded in MainWindow\";\n\n drawDataFieldInformation(); \/\/refresh the display to reflect updates\n}\n\nvoid MainWindow::on_pbSettings_clicked()\n{\n loadSettings(); \/\/fix CTD bug?\n settingsDialog = new SettingsDialog(patientInfoString, testInfoString, diagonalCMDouble, this);\n connect(settingsDialog, SIGNAL(patientInfo(QString)), this, SLOT(patientInfo(QString)));\n connect(settingsDialog, SIGNAL(testInfo(QString)), this, SLOT(testInfo(QString)));\n connect(settingsDialog, SIGNAL(diagonalCM(double)), this, SLOT(diagonalCM(double)));\n connect(settingsDialog, SIGNAL(accepted()), this, SLOT(resetPicIndex()));\n connect(settingsDialog, SIGNAL(accepted()), timer, SLOT(start()));\n connect(settingsDialog, SIGNAL(rejected()), timer, SLOT(start()));\n timer->stop(); \/\/pause the data-gathering\n settingsDialog->exec();\n}\n\nvoid MainWindow::resetPicIndex()\n{\n picIndex = 1; \/\/reset counter\n loadSettings(); \/\/load the settings\n qDebug() << \"Reset counter and called loadSettings()\";\n}\n\nvoid MainWindow::patientInfo(QString patient)\n{\n patientInfoString = patient;\n settings->setValue(\"patientInfoString\", patientInfoString);\n settings->sync();\n qDebug() << \"Patient info copied from Settings dialog\";\n}\n\nvoid MainWindow::testInfo(QString test)\n{\n testInfoString = test;\n settings->setValue(\"testInfoString\", testInfoString);\n settings->sync();\n qDebug() << \"Test info copied from Settings dialog\";\n}\n\nvoid MainWindow::diagonalCM(double cm)\n{\n diagonalCMDouble = cm;\n settings->setValue(\"diagonalCM\", diagonalCMDouble);\n settings->sync();\n qDebug() << \"diagonalCMDouble copied from Settings dialog\";\n}\n\nQPointF MainWindow::calcCircle()\n{\n \/\/Prep work first, including gathering of data points\n QPointF center;\n center.setX(-1);\n center.setY(-1);\n\n QPointF roughCenter;\n roughCenter.setX(-1);\n roughCenter.setY(-1);\n\n int sectionBreak = dataListRaw.count()\/10; \/\/break the datalist into 10 sections\n\n QList<QPointF> roughCenterList; \/\/hold all calculated center points\n\n qDebug() << \"---------- Starting to calculate center points ----------\";\n qDebug() << \"dataListRaw count: \" << dataListRaw.count();\n for(int i= 0; i <dataListRaw.count() - 2;i++)\n {\n qDebug() << \"Low: \" << i << \", High: \" << (i + 2);\n QPointF a = dataListRaw.at(i);\n QPointF b = dataListRaw.at(i+1);\n QPointF c = dataListRaw.at(i+2);\n if(a.x() != b.x() && b.x() != c.x() && a.x() != c.x() && a.y() != b.y() && b.y() != c.y() && a.y() != c.y())\n {\n QPointF cP = calcCenter(a,b,c);\n if(cP.x() < - 3000 || cP.x() > 3000 || cP.y() < 0 || cP.y() > 3000)\n {\n qDebug() << \"Ignoring centerpoint at \" << cP << \" for being too far away from a reasonable value!\";\n }\n else\n {\n roughCenterList.append(cP);\n }\n }\n }\n\n qDebug() << \"---------- Finished calculating center points ----------\";\n\n roughCenter = calcAveragePoint(roughCenterList); \/\/Calculate the rough average center point\n\n QList<QPointF> centerList;\n\n foreach(QPointF centerPoint, roughCenterList)\n {\n centerList.append(centerPoint);\n }\n\n if(!centerList.isEmpty())\n {\n center = calcAveragePoint(centerList);\n }\n else\n {\n qDebug() << \"ERROR: Accurate center point list is empty!\";\n }\n\n \/\/Draw information on screen\n QPointF testPoint = dataListRaw.at(sectionBreak*3);\n int radius = sqrt( ((center.x() - testPoint.x()) * (center.x() - testPoint.x())) + ((center.y() - testPoint.y()) * (center.y() - testPoint.y())) );\n scene->addEllipse(center.x()-radius, center.y()-radius, 2 * radius, 2 * radius, QPen(Qt::black), QBrush(QColor(0,255,0,64)));\n\n rom.setRadius((double)radius);\n rom.setCenterPoint(center);\n\n qDebug() << \"Radius (px): \" << radius;\n qDebug() << \"PPCM: \" << calc->getPPCM();\n\n return center;\n}\n\nQPointF MainWindow::calcCenter(QPointF a, QPointF b, QPointF c)\n{\n QPointF centerTemp;\n\n qDebug() << a << \"; \" << b << \"; \" << c;\n double yDelta0 = b.y() - a.y();\n double xDelta0 = b.x() - a.x();\n double yDelta1 = c.y() - b.y();\n double xDelta1 = c.x() - b.x();\n\n double slope0 = yDelta0\/xDelta0;\n double slope1 = yDelta1\/xDelta1;\n double xD = 0;\n double yD = 0;\n\n xD = ( (slope0 * slope1 * (a.y() - c.y())) + (slope1 * (a.x() + b.x())) - (slope0 * (b.x() + c.x())) ) \/ (2.0 *(slope1 - slope0));\n yD = -1.0 * (xD - ((a.x() + b.x()) \/ 2 )) \/ slope0 + ((a.y() +b.y()) \/ 2);\n\n centerTemp.setX((int)xD);\n centerTemp.setY((int)yD);\n\n qDebug() << \"Calculated center here: \" << centerTemp;\n return centerTemp;\n}\n\ndouble MainWindow::calcROM() \/\/calculate the Range of Motion\n{\n double romDegrees = -1;\n\n calcCircle();\n\n QPointF furthestPoint = QPointF(-1, -1);\n QPoint lastPoint = QPoint(0,0);\n\n foreach(QPoint p, dataListRaw) \/\/find the furthest point down\n {\n if(p.y() >= lastPoint.y())\n {\n furthestPoint.setX(p.x());\n furthestPoint.setY(p.y());\n lastPoint = p;\n }\n else\n {\n\n }\n }\n\n scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), furthestPoint.x(), furthestPoint.y(), QPen(Qt::blue));\n qDebug() << \"Furthest Point: \" << furthestPoint;\n\n QPointF verticalPoint = rom.getCenterPoint();\n\n verticalPoint.setY(verticalPoint.y() - rom.getRadius());\n scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), verticalPoint.x(), verticalPoint.y(), QPen(Qt::blue));\n qDebug() << \"Vertical Point: \" << verticalPoint;\n\n double deltaX = verticalPoint.x() - furthestPoint.x();\n double deltaY = verticalPoint.y() - furthestPoint.y();\n\n double chordLength = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n double thetaR = qAcos( ( (chordLength * chordLength) - (2 * (rom.getRadius() * rom.getRadius())) ) \/ ( -2 * (rom.getRadius() * rom.getRadius())) );\n\n double thetaD = 180.0 * thetaR \/ M_PI;\n\n romDegrees = thetaD;\n\n qDebug() << \"Range of Motion degrees: \" << romDegrees;\n\n return romDegrees;\n}\n\nvoid MainWindow::on_pbAnalyze_clicked()\n{\n calcROM();\n}\n\ndouble MainWindow::calcDistance(QPointF a, QPointF b)\n{\n double deltaX = a.x() - b.x();\n double deltaY = a.y() - b.y();\n\n double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n return d;\n}\n\ndouble MainWindow::calcDistance(QPoint a, QPoint b)\n{\n double deltaX = (double)a.x() - (double)b.x();\n double deltaY = (double)a.y() - (double)b.y();\n\n double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) );\n\n return d;\n}\n\nQPointF MainWindow::calcAveragePoint(QList<QPointF> l)\n{\n\n qDebug() << \"---------- Starting to calculate average point ----------\";\n QPointF avgPnt = QPointF(0,0);\n\n foreach(QPointF p, l)\n {\n avgPnt.setX(avgPnt.x() + p.x());\n avgPnt.setY(avgPnt.y() + p.y());\n }\n\n avgPnt.setX(avgPnt.x() \/ (double)l.count());\n avgPnt.setY(avgPnt.y() \/ (double)l.count());\n qDebug() << \"Average point: \" << avgPnt;\n qDebug() << \"---------- Calculated average point ----------\";\n return avgPnt;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"lsgc.h\"\n\n#include <deal.II\/base\/quadrature_lib.h>\n\ntemplate <int dim>\nLSGC<dim>::LSGC (const dealii::ParameterHandler &prm)\n:\nAQBase<dim> (prm) {}\n\ntemplate <int dim>\nLSGC<dim>::~LSGC () {}\n\ntemplate <int dim>\nvoid LSGC<dim>::ProduceAQ () {\n AssertThrow (this->n_azi_%2==0,\n dealii::ExcMessage(\"SN order must be even numbers\"));\n AssertThrow (dim>1,\n dealii::ExcMessage(\"LSGC only exists in multi-D\"));\n\n dealii::QGauss<1> mu_quad (this->n_azi_);\n\n switch (dim) {\n case 2: {\n this->n_dir_ = this->n_azi_ * (this->n_azi_ + 2) \/\n (this->transport_model_name_==\"ep\" ? 4:2);\n this->total_angle_ = 8.0 * this->k_pi;\n break;\n }\n case 3: {\n this->n_dir_ = this->n_azi_ * (this->n_azi_ + 2) \/\n (this->transport_model_name_==\"ep\" ? 2:1);\n this->total_angle_ = 4.0 * this->k_pi *\n (this->transport_model_name_==\"ep\" ? 2.0 : 1.0);\n break;\n }\n default:\n break;\n }\n\n int n_total_azi = ((dim==3 && this->transport_model_name_!=\"ep\")?\n this->n_azi_ : this->n_azi_ \/ 2);\n for (int i=0; i<n_total_azi; ++i) {\n double mu = mu_quad.point(i)[0] * 2.0 - 1.0;\n int n_level = ((i<this->n_azi_\/2?4*(i+1):4*(this->n_azi_-i))\/\n ((dim==2&&this->transport_model_name_==\"ep\")?2:1));\n double dphi = 2.0 * this->k_pi \/\n (n_level*(this->transport_model_name_==\"ep\"?2.0:1.0));\n double w_pt = mu_quad.weight(i) * this->total_angle_ \/ n_level;\n for (int j=0; j<n_level; ++j) {\n dealii::Tensor<1, dim> omega;\n double phi = (j + 0.5) * dphi;\n omega[0] = std::sqrt (1.0 - mu * mu) * cos (phi);\n omega[1] = std::sqrt (1.0 - mu * mu) * sin (phi);\n if (dim==3)\n omega[2] = mu;\n this->wi_.push_back (w_pt);\n this->omega_i_.push_back (omega);\n }\n }\n\n AssertThrow (this->n_dir_==this->wi_.size(),\n dealii::ExcMessage(\"calculated number of angles should be the same as number of angular weights\"));\n AssertThrow (this->n_dir_==this->omega_i_.size(),\n dealii::ExcMessage(\"calculated number of angles should be the same as number of angles\"));\n\n this->n_total_ho_vars_ = this->n_dir_ * this->n_group_;\n}\n\ntemplate class LSGC<2>;\ntemplate class LSGC<3>;\n<commit_msg>address style in constructor<commit_after>#include \"lsgc.h\"\n\n#include <deal.II\/base\/quadrature_lib.h>\n\ntemplate <int dim>\nLSGC<dim>::LSGC (const dealii::ParameterHandler &prm)\n :\n AQBase<dim> (prm) {}\n\ntemplate <int dim>\nLSGC<dim>::~LSGC () {}\n\ntemplate <int dim>\nvoid LSGC<dim>::ProduceAQ () {\n AssertThrow (this->n_azi_%2==0,\n dealii::ExcMessage(\"SN order must be even numbers\"));\n AssertThrow (dim>1,\n dealii::ExcMessage(\"LSGC only exists in multi-D\"));\n\n dealii::QGauss<1> mu_quad (this->n_azi_);\n\n switch (dim) {\n case 2: {\n this->n_dir_ = this->n_azi_ * (this->n_azi_ + 2) \/\n (this->transport_model_name_==\"ep\" ? 4:2);\n this->total_angle_ = 8.0 * this->k_pi;\n break;\n }\n case 3: {\n this->n_dir_ = this->n_azi_ * (this->n_azi_ + 2) \/\n (this->transport_model_name_==\"ep\" ? 2:1);\n this->total_angle_ = 4.0 * this->k_pi *\n (this->transport_model_name_==\"ep\" ? 2.0 : 1.0);\n break;\n }\n default:\n break;\n }\n\n int n_total_azi = ((dim==3 && this->transport_model_name_!=\"ep\")?\n this->n_azi_ : this->n_azi_ \/ 2);\n for (int i=0; i<n_total_azi; ++i) {\n double mu = mu_quad.point(i)[0] * 2.0 - 1.0;\n int n_level = ((i<this->n_azi_\/2?4*(i+1):4*(this->n_azi_-i))\/\n ((dim==2&&this->transport_model_name_==\"ep\")?2:1));\n double dphi = 2.0 * this->k_pi \/\n (n_level*(this->transport_model_name_==\"ep\"?2.0:1.0));\n double w_pt = mu_quad.weight(i) * this->total_angle_ \/ n_level;\n for (int j=0; j<n_level; ++j) {\n dealii::Tensor<1, dim> omega;\n double phi = (j + 0.5) * dphi;\n omega[0] = std::sqrt (1.0 - mu * mu) * cos (phi);\n omega[1] = std::sqrt (1.0 - mu * mu) * sin (phi);\n if (dim==3)\n omega[2] = mu;\n this->wi_.push_back (w_pt);\n this->omega_i_.push_back (omega);\n }\n }\n\n AssertThrow (this->n_dir_==this->wi_.size(),\n dealii::ExcMessage(\"calculated number of angles should be the same as number of angular weights\"));\n AssertThrow (this->n_dir_==this->omega_i_.size(),\n dealii::ExcMessage(\"calculated number of angles should be the same as number of angles\"));\n\n this->n_total_ho_vars_ = this->n_dir_ * this->n_group_;\n}\n\ntemplate class LSGC<2>;\ntemplate class LSGC<3>;\n<|endoftext|>"} {"text":"<commit_before>#include \"Graph.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <set>\n#include <vector>\n#include <map>\n#include <functional>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Node of Graph\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\nvoid GraphNode::removeNeighbor(int to)\n{\n auto neighborIt = std::find(neighbors.begin(), neighbors.end(), to);\n auto edgeWeightIt = edgeWeights.begin() + (neighborIt - neighbors.begin());\n std::swap(*neighborIt, *neighbors.rbegin());\n std::swap(*edgeWeightIt, *edgeWeights.rbegin());\n neighbors.erase(neighbors.end() - 1, neighbors.end());\n edgeWeights.erase(edgeWeights.end() - 1, edgeWeights.end());\n}\n\nvoid GraphNode::addNeighbor(int to, double weight)\n{\n auto it = std::lower_bound(neighbors.begin(), neighbors.end(), to);\n if (it != neighbors.end() && *it == to)\n return;\n edgeWeights.insert(edgeWeights.begin() + (it - neighbors.begin()), weight);\n neighbors.insert(it, to);\n}\n*\/\n\n\/\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\/\/ Graph\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Graph::resize(int newNodes)\n{\n if (newNodes < int(nodes.size()))\n throw(\"Graph::resize - cannot decrease size\");\n\n if (newNodes == nodes.size())\n return;\n\n while (nodes.size() < newNodes)\n {\n nodes.push_back(std::make_shared<GraphNode>());\n }\n}\n\n\nint Graph::addNode(double weight)\n{\n nodes.emplace_back(std::make_shared<GraphNode>(weight));\n return int(nodes.size()) - 1;\n}\n\nvoid Graph::addEdge(int from, int to, double weight)\n{\n auto newEdge = std::make_shared<GraphEdge>(weight, from, to);\n edges.push_back(newEdge);\n\n nodes[from]->addEdge(newEdge);\n if (!directed)\n {\n nodes[to]->addEdge(newEdge);\n\n }\n}\n\n\nvoid Graph::removeEdge(int from, int to)\n{\n auto edge = std::find_if(edges.begin(), edges.end(),\n [&from, &to](const std::shared_ptr<GraphEdge> &e) { return e->from == from && e->to == to; });\n edges.erase(edge, edges.end());\n\n nodes[from]->removeEdge(*edge);\n if (!directed)\n {\n nodes[to]->removeEdge(*edge);\n }\n}\n\nvoid Graph::clear(bool newDirected)\n{\n directed = newDirected;\n nodes.clear();\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Input \/ Output\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Format:\n\/\/ NumberOfNodes NumberOfEdges \n\/\/ DirectedFlag WeightedNodesFlag WeightedEdgesFlag\n\/\/ If WeightedNodesFlag == 1, the node weights follow, NumberOfNodes numbers\n\/\/ else this section is omitted\n\/\/ NumberOfEdges edges follow:\n\/\/ From To [Weight]\n\/\/ Wight is omitted if NumberOfEdges == 0\n\n\/\/ Flags are 0 or 1\n\/\/ All weights are floating point numbers\n\/\/ Everything is whitespace separated\n\/\/ Indexes are 1 based.\n\n\/\/ e.g\n\/\/ 3 2 \n\/\/ 1 1 0\n\/\/ 5.4\n\/\/ 0.6\n\/\/ 1\n\/\/ 2 3\n\/\/ 3 1\n\n\/\/ 2 ----> 3 ----> 1\n\/\/ 0.6 1 5.4\n\nstd::istream &operator>>(std::istream &is, Graph &g)\n{\n \n\n int n, m;\n int directedFlag, weightedNodesFlag, weightedEdgesFlag;\n\n is >> n >> m;\n is >> directedFlag >> weightedNodesFlag >> weightedEdgesFlag;\n\n g.clear(directedFlag != 0);\n g.resize(n);\n \n g.setWeightedNodes(weightedNodesFlag != 0);\n g.setWeightedEdges(weightedEdgesFlag != 0);\n\n if (g.hasWeightedNodes())\n {\n for (auto &node : g)\n {\n double w;\n is >> w;\n node->setWeight(w);\n }\n }\n\n for (int i = 0; i < m; ++i)\n {\n int from, to;\n is >> from >> to;\n double weight = 0.0;\n if (g.hasWeightedEdges())\n {\n is >> weight;\n }\n g.addEdge(from - 1, to - 1, weight);\n }\n\n return is;\n}\n\nstd::ostream &operator<<(std::ostream &os, const Graph &g)\n{\n os << g.getNodeCount() << \" \";\n\n size_t edgesCount = 0;\n\n os << g.edges.size() << \"\\n\";\n os << g.isDirected() << \" \" << g.hasWeightedNodes() << \" \" << g.hasWeightedEdges() << \"\\n\";\n\n if (g.hasWeightedNodes())\n {\n for (const auto &node : g.nodes)\n {\n os << node->getWeight() << \"\\n\";\n }\n }\n\n for (const auto &edge : g.edges)\n {\n os << edge->from + 1 << \" \" << edge->to + 1;\n if (g.hasWeightedEdges())\n {\n os << \" \" << edge->weight;\n }\n }\n\n os << std::flush;\n\n return os;\n}\n\n\n\n<commit_msg>Fixed graph save<commit_after>#include \"Graph.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <set>\n#include <vector>\n#include <map>\n#include <functional>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Node of Graph\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\nvoid GraphNode::removeNeighbor(int to)\n{\n auto neighborIt = std::find(neighbors.begin(), neighbors.end(), to);\n auto edgeWeightIt = edgeWeights.begin() + (neighborIt - neighbors.begin());\n std::swap(*neighborIt, *neighbors.rbegin());\n std::swap(*edgeWeightIt, *edgeWeights.rbegin());\n neighbors.erase(neighbors.end() - 1, neighbors.end());\n edgeWeights.erase(edgeWeights.end() - 1, edgeWeights.end());\n}\n\nvoid GraphNode::addNeighbor(int to, double weight)\n{\n auto it = std::lower_bound(neighbors.begin(), neighbors.end(), to);\n if (it != neighbors.end() && *it == to)\n return;\n edgeWeights.insert(edgeWeights.begin() + (it - neighbors.begin()), weight);\n neighbors.insert(it, to);\n}\n*\/\n\n\/\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\/\/ Graph\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Graph::resize(int newNodes)\n{\n if (newNodes < int(nodes.size()))\n throw(\"Graph::resize - cannot decrease size\");\n\n if (newNodes == nodes.size())\n return;\n\n while (nodes.size() < newNodes)\n {\n nodes.push_back(std::make_shared<GraphNode>());\n }\n}\n\n\nint Graph::addNode(double weight)\n{\n nodes.emplace_back(std::make_shared<GraphNode>(weight));\n return int(nodes.size()) - 1;\n}\n\nvoid Graph::addEdge(int from, int to, double weight)\n{\n auto newEdge = std::make_shared<GraphEdge>(weight, from, to);\n edges.push_back(newEdge);\n\n nodes[from]->addEdge(newEdge);\n if (!directed)\n {\n nodes[to]->addEdge(newEdge);\n\n }\n}\n\n\nvoid Graph::removeEdge(int from, int to)\n{\n auto edge = std::find_if(edges.begin(), edges.end(),\n [&from, &to](const std::shared_ptr<GraphEdge> &e) { return e->from == from && e->to == to; });\n edges.erase(edge, edges.end());\n\n nodes[from]->removeEdge(*edge);\n if (!directed)\n {\n nodes[to]->removeEdge(*edge);\n }\n}\n\nvoid Graph::clear(bool newDirected)\n{\n directed = newDirected;\n nodes.clear();\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Input \/ Output\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Format:\n\/\/ NumberOfNodes NumberOfEdges \n\/\/ DirectedFlag WeightedNodesFlag WeightedEdgesFlag\n\/\/ If WeightedNodesFlag == 1, the node weights follow, NumberOfNodes numbers\n\/\/ else this section is omitted\n\/\/ NumberOfEdges edges follow:\n\/\/ From To [Weight]\n\/\/ Wight is omitted if NumberOfEdges == 0\n\n\/\/ Flags are 0 or 1\n\/\/ All weights are floating point numbers\n\/\/ Everything is whitespace separated\n\/\/ Indexes are 1 based.\n\n\/\/ e.g\n\/\/ 3 2 \n\/\/ 1 1 0\n\/\/ 5.4\n\/\/ 0.6\n\/\/ 1\n\/\/ 2 3\n\/\/ 3 1\n\n\/\/ 2 ----> 3 ----> 1\n\/\/ 0.6 1 5.4\n\nstd::istream &operator>>(std::istream &is, Graph &g)\n{\n \n\n int n, m;\n int directedFlag, weightedNodesFlag, weightedEdgesFlag;\n\n is >> n >> m;\n is >> directedFlag >> weightedNodesFlag >> weightedEdgesFlag;\n\n g.clear(directedFlag != 0);\n g.resize(n);\n \n g.setWeightedNodes(weightedNodesFlag != 0);\n g.setWeightedEdges(weightedEdgesFlag != 0);\n\n if (g.hasWeightedNodes())\n {\n for (auto &node : g)\n {\n double w;\n is >> w;\n node->setWeight(w);\n }\n }\n\n for (int i = 0; i < m; ++i)\n {\n int from, to;\n is >> from >> to;\n double weight = 0.0;\n if (g.hasWeightedEdges())\n {\n is >> weight;\n }\n g.addEdge(from - 1, to - 1, weight);\n }\n\n return is;\n}\n\nstd::ostream &operator<<(std::ostream &os, const Graph &g)\n{\n os << g.getNodeCount() << \" \";\n\n size_t edgesCount = 0;\n\n os << g.edges.size() << \"\\n\";\n os << g.isDirected() << \" \" << g.hasWeightedNodes() << \" \" << g.hasWeightedEdges() << \"\\n\";\n\n if (g.hasWeightedNodes())\n {\n for (const auto &node : g.nodes)\n {\n os << node->getWeight() << \"\\n\";\n }\n }\n\n for (const auto &edge : g.edges)\n {\n os << edge->from + 1 << \" \" << edge->to + 1;\n if (g.hasWeightedEdges())\n {\n os << \" \" << edge->weight;\n }\n os << \"\\n\";\n }\n\n os << std::flush;\n\n return os;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Graph.h\"\n#include <algorithm>\n#include <queue>\n#include <stack>\n#include <set>\nvertex* Graph::at(const std::string& name)const\n{\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n return it->second;\n }\n else throw;\n}\nstd::vector<std::string> Graph::getkeys()const\n{\n std::vector<std::string> ret;\n ret.resize(size());\n int ind = 0;\n for(auto& i : m_V)\n {\n ret[ind++] = i.first;\n }\n return ret;\n}\nGraph::Graph(const Graph& g)\n{\n std::vector<std::string> names = g.getkeys();\n for(size_t i = 0; i < g.size(); i++)\n addvertex(names[i]);\n\n for(size_t i = 0; i < m_V.size(); i++)\n {\n auto it = m_V.find(names[i]);\n vertex* tmp = g.at(names[i]);\n vertex* pIt = it->second;\n for(auto& j : tmp->adj)\n {\n \/\/1.cost\n \/\/2.vertex* in this graph\n pIt->adj.push_back(std::make_pair(j.first,\n m_V.find(j.second->name)->second));\n }\n }\n}\n\/*\n As long as there are vertexes\n change name,clean adjacency list. x\n After that create new vertexes. x\n Then fill adjacency lists.\n Clean remaining not needed vertexes x\n*\/\nGraph& Graph::operator=(const Graph& g)\n{\n int n = m_V.size() - g.size();\n \/\/\/if there are more vertexes than needed: n > 0\n \/\/\/if it is just the right size: n = 0\n \/\/\/if there are not enough vertexes: n < 0\n std::vector<std::string> names = getkeys();\n std::vector<std::string> namesTO = g.getkeys();\n if(!(n<0))\n {\n for(size_t i = 0; i < g.size(); i++)\n {\n auto it = m_V.find(names[i]);\n it->second->name = namesTO[i];\n it->second->adj.clear();\n }\n \/\/Clean remaining not needed vertexes\n for(int i = g.size(); i < n; i++)\n removevertex(names[i]);\n }\n else\n {\n for(size_t i = 0; i < g.size(); i++)\n addvertex(namesTO[i]);\n }\n \/\/Filling adjacency list\n for(size_t i = 0; i < g.size(); i++)\n {\n auto it = m_V.find(namesTO[i]);\n vertex* pIt = it->second;\n vertex* tmp = g.at(namesTO[i]);\n for(auto& j : tmp->adj)\n {\n pIt->adj.push_back(std::make_pair(j.first,\n m_V.find(j.second->name)->second));\n }\n }\n return *this;\n}\n\nGraph::~Graph()\n{\n if(!m_V.empty())\n {\n for(auto& i : m_V)\n delete i.second;\n }\n}\n\nGraph::vmap::iterator Graph::addvertex(const std::string& name)\n{\n\tauto it=m_V.find(name);\n\tif(it==m_V.end())\n\t{\n\t\tvertex *v;\n\t\tv = new vertex(name);\n\t\tm_V[name]=v;\n\t\treturn it;\n\t}\n\treturn m_V.end();\n}\n\nvoid Graph::addedge(const std::string& from, const std::string& to, int cost)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n vertex *f = (fromIt->second);\n vertex *t = (toIt->second);\n std::pair<int,vertex*> edge = std::make_pair(cost,t);\n f->degp++;\n t->degm++;\n f->adj.push_back(edge);\n }\n}\n\nvoid Graph::removevertex(const std::string& name)\n{\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n for(auto& i : m_V)\n {\n if(i.second != it->second)\n {\n vertex* v = i.second;\n for(auto& j : v->adj)\n {\n if(j.second->name == name)\n {\n removeedge(j.second->name,name);\n }\n }\n }\n }\n delete it->second;\n m_V.erase(it);\n }\n}\n\nvoid Graph::removeedge(const std::string& from, const std::string& to)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n vertex* v = fromIt->second;\n size_t i = 0;\n while(i < v->adj.size() && !(v->adj[i].second->name == to))\n i++;\n if(i < v->adj.size())\n {\n v->adj.erase(v->adj.begin()+i);\n }\n }\n}\n\nbool Graph::adjacent(const std::string& from, const std::string& to)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n for(auto& i : fromIt->second->adj)\n {\n if(i.second->name == to)\n {\n return true;\n }\n }\n }\n return false;\n}\n\nstd::vector<std::string> Graph::neighbours(const std::string& name)\n{\n auto it = m_V.find(name);\n std::vector<std::string> ret;\n if(it != m_V.end())\n {\n for(auto& i : it->second->adj)\n ret.push_back(i.second->name);\n }\n return ret;\n}\n\nstd::string Graph::bfs(const std::string& name)\n{\n std::string ret = \"\";\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n std::queue<vertex*> Queue;\n vertex* curr = it->second;\n Queue.push(curr);\n curr->visited = true;\n ret += curr->name + \" \";\n\n while(!Queue.empty())\n {\n for(auto& i : curr->adj)\n {\n if(i.second->visited == false)\n {\n Queue.push(i.second);\n i.second->visited = true;\n ret+= i.second->name + \" \";\n }\n }\n Queue.pop();\n if(!Queue.empty())\n {\n curr = Queue.front();\n }\n }\n\n for(auto& i : m_V)\n i.second->visited = false;\n }\n return ret;\n}\n\nstd::string Graph::dfs(const std::string& name, bool topo)\n{\n std::string ret = \"\";\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n std::stack<vertex*> Stack;\n vertex* curr = it->second;\n Stack.push(curr);\n curr->visited = true;\n if(!topo)\n ret += curr->name + \" \";\n\n while(!Stack.empty())\n {\n bool found = false;\n size_t i = 0;\n while(i < curr->adj.size() && !found)\n {\n if(curr->adj[i].second->visited == false)\n {\n found = true;\n curr = curr->adj[i].second;\n curr->visited = true;\n if(!topo)\n ret += curr->name + \" \";\n Stack.push(curr);\n }\n i++;\n }\n if(!found)\n {\n Stack.pop();\n if(topo)\n {\n ret += curr->name + \" \";\n }\n if(!Stack.empty())\n {\n curr = Stack.top();\n }\n }\n }\n if(topo)\n {\n std::reverse(ret.begin(),ret.end());\n ret.erase(ret.begin());\/\/remove space at the beginning\n }\n else ret.erase(ret.end()-1);\/\/remove space at the end\n for(auto& i : m_V)\n i.second->visited = false;\n }\n return ret;\n}\n\nstd::string Graph::cycle(bool& found)\n{\n std::string ret = \"\";\n return ret;\n}\n<commit_msg>Added cycle detection.<commit_after>#include \"Graph.h\"\n#include <algorithm>\n#include <queue>\n#include <stack>\n#include <set>\nvertex* Graph::at(const std::string& name)const\n{\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n return it->second;\n }\n else throw;\n}\nstd::vector<std::string> Graph::getkeys()const\n{\n std::vector<std::string> ret;\n ret.resize(size());\n int ind = 0;\n for(auto& i : m_V)\n {\n ret[ind++] = i.first;\n }\n return ret;\n}\nGraph::Graph(const Graph& g)\n{\n std::vector<std::string> names = g.getkeys();\n for(size_t i = 0; i < g.size(); i++)\n addvertex(names[i]);\n\n for(size_t i = 0; i < m_V.size(); i++)\n {\n auto it = m_V.find(names[i]);\n vertex* tmp = g.at(names[i]);\n vertex* pIt = it->second;\n for(auto& j : tmp->adj)\n {\n \/\/1.cost\n \/\/2.vertex* in this graph\n pIt->adj.push_back(std::make_pair(j.first,\n m_V.find(j.second->name)->second));\n }\n }\n}\n\/*\n As long as there are vertexes\n change name,clean adjacency list. x\n After that create new vertexes. x\n Then fill adjacency lists.\n Clean remaining not needed vertexes x\n*\/\nGraph& Graph::operator=(const Graph& g)\n{\n int n = m_V.size() - g.size();\n \/\/\/if there are more vertexes than needed: n > 0\n \/\/\/if it is just the right size: n = 0\n \/\/\/if there are not enough vertexes: n < 0\n std::vector<std::string> names = getkeys();\n std::vector<std::string> namesTO = g.getkeys();\n if(!(n<0))\n {\n for(size_t i = 0; i < g.size(); i++)\n {\n auto it = m_V.find(names[i]);\n it->second->name = namesTO[i];\n it->second->adj.clear();\n }\n \/\/Clean remaining not needed vertexes\n for(int i = g.size(); i < n; i++)\n removevertex(names[i]);\n }\n else\n {\n for(size_t i = 0; i < g.size(); i++)\n addvertex(namesTO[i]);\n }\n \/\/Filling adjacency list\n for(size_t i = 0; i < g.size(); i++)\n {\n auto it = m_V.find(namesTO[i]);\n vertex* pIt = it->second;\n vertex* tmp = g.at(namesTO[i]);\n for(auto& j : tmp->adj)\n {\n pIt->adj.push_back(std::make_pair(j.first,\n m_V.find(j.second->name)->second));\n }\n }\n return *this;\n}\n\nGraph::~Graph()\n{\n if(!m_V.empty())\n {\n for(auto& i : m_V)\n delete i.second;\n }\n}\n\nGraph::vmap::iterator Graph::addvertex(const std::string& name)\n{\n\tauto it=m_V.find(name);\n\tif(it==m_V.end())\n\t{\n\t\tvertex *v;\n\t\tv = new vertex(name);\n\t\tm_V[name]=v;\n\t\treturn it;\n\t}\n\treturn m_V.end();\n}\n\nvoid Graph::addedge(const std::string& from, const std::string& to, int cost)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n vertex *f = (fromIt->second);\n vertex *t = (toIt->second);\n std::pair<int,vertex*> edge = std::make_pair(cost,t);\n f->degp++;\n t->degm++;\n f->adj.push_back(edge);\n }\n}\n\nvoid Graph::removevertex(const std::string& name)\n{\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n for(auto& i : m_V)\n {\n if(i.second != it->second)\n {\n vertex* v = i.second;\n for(auto& j : v->adj)\n {\n if(j.second->name == name)\n {\n removeedge(j.second->name,name);\n }\n }\n }\n }\n delete it->second;\n m_V.erase(it);\n }\n}\n\nvoid Graph::removeedge(const std::string& from, const std::string& to)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n vertex* v = fromIt->second;\n size_t i = 0;\n while(i < v->adj.size() && !(v->adj[i].second->name == to))\n i++;\n if(i < v->adj.size())\n {\n v->adj.erase(v->adj.begin()+i);\n }\n }\n}\n\nbool Graph::adjacent(const std::string& from, const std::string& to)\n{\n auto fromIt = m_V.find(from);\n auto toIt = m_V.find(to);\n if(fromIt != m_V.end() && toIt != m_V.end())\n {\n for(auto& i : fromIt->second->adj)\n {\n if(i.second->name == to)\n {\n return true;\n }\n }\n }\n return false;\n}\n\nstd::vector<std::string> Graph::neighbours(const std::string& name)\n{\n auto it = m_V.find(name);\n std::vector<std::string> ret;\n if(it != m_V.end())\n {\n for(auto& i : it->second->adj)\n ret.push_back(i.second->name);\n }\n return ret;\n}\n\nstd::string Graph::bfs(const std::string& name)\n{\n std::string ret = \"\";\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n std::queue<vertex*> Queue;\n vertex* curr = it->second;\n Queue.push(curr);\n curr->visited = true;\n ret += curr->name + \" \";\n\n while(!Queue.empty())\n {\n for(auto& i : curr->adj)\n {\n if(i.second->visited == false)\n {\n Queue.push(i.second);\n i.second->visited = true;\n ret+= i.second->name + \" \";\n }\n }\n Queue.pop();\n if(!Queue.empty())\n {\n curr = Queue.front();\n }\n }\n\n for(auto& i : m_V)\n i.second->visited = false;\n }\n return ret;\n}\n\nstd::string Graph::dfs(const std::string& name, bool topo)\n{\n std::string ret = \"\";\n auto it = m_V.find(name);\n if(it != m_V.end())\n {\n std::stack<vertex*> Stack;\n vertex* curr = it->second;\n Stack.push(curr);\n curr->visited = true;\n if(!topo)\n ret += curr->name + \" \";\n\n while(!Stack.empty())\n {\n bool found = false;\n size_t i = 0;\n while(i < curr->adj.size() && !found)\n {\n if(curr->adj[i].second->visited == false)\n {\n found = true;\n curr = curr->adj[i].second;\n curr->visited = true;\n if(!topo)\n ret += curr->name + \" \";\n Stack.push(curr);\n }\n i++;\n }\n if(!found)\n {\n Stack.pop();\n if(topo)\n {\n ret += curr->name + \" \";\n }\n if(!Stack.empty())\n {\n curr = Stack.top();\n }\n }\n }\n if(topo)\n {\n std::reverse(ret.begin(),ret.end());\n ret.erase(ret.begin());\/\/remove space at the beginning\n }\n else ret.erase(ret.end()-1);\/\/remove space at the end\n for(auto& i : m_V)\n i.second->visited = false;\n }\n return ret;\n}\n\nstd::string Graph::cycle(bool& found)\n{\n std::string ret = \"\";\n std::set<vertex*> white;\n std::set<vertex*> grey;\n std::set<vertex*> black;\n std::map<vertex*,vertex*> parentMap;\n \/\/\/Init all vertexes into white\n for(auto& i : m_V)\n white.insert(i.second);\n vertex* curr = *white.begin();\n vertex* prev = nullptr;\n grey.insert(curr);\n white.erase(curr);\n parentMap[curr] = prev;\n while(black.size() != m_V.size())\n {\n found = false;\n size_t i = 0;\n while(i < curr->adj.size() && !found)\n {\n vertex* v = curr->adj[i].second;\n if(white.find(v) != white.end())\n {\n prev = curr;\n curr = v;\n grey.insert(curr);\n white.erase(curr);\n parentMap[curr] = prev;\n found = true;\n i = 0;\n }\n else if(grey.find(v) != grey.end())\n {\n found = true;\n ret += v->name + \" \" + curr->name + \" \";\n while(curr != nullptr)\n {\n curr = parentMap.find(curr)->second;\n if(curr != nullptr)\n ret += curr->name + \" \";\n }\n std::reverse(ret.begin(),ret.end());\n ret.erase(ret.begin());\n return ret;\n }\n else\n i++;\n }\n if(!found)\n {\n black.insert(curr);\n grey.erase(curr);\n prev = nullptr;\n curr = parentMap.find(curr)->second;\n if(curr == nullptr && !white.empty())\n {\n curr = *white.begin();\n grey.insert(curr);\n white.erase(curr);\n parentMap[curr] = prev;\n }\n }\n }\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"async_fsync.h\"\n\n#include \"io_utils.h\"\n#include \"manager.h\"\n\n\nstd::mutex AsyncFsync::mtx;\nstd::mutex AsyncFsync::statuses_mtx;\nstd::condition_variable AsyncFsync::wakeup_signal;\nstd::unordered_map<int, AsyncFsync::Status> AsyncFsync::statuses;\nstd::atomic<std::time_t> AsyncFsync::next_wakeup_time(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now() + 10s));\n\n\nstd::chrono::time_point<std::chrono::system_clock>\nAsyncFsync::Status::next_wakeup_time()\n{\n\treturn max_commit_time < commit_time ? max_commit_time : commit_time;\n}\n\n\nAsyncFsync::AsyncFsync(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_)\n\t: Worker(std::move(manager_), loop_),\n\t running(true)\n{\n\tL_OBJ(this, \"CREATED AUTOCOMMIT!\");\n}\n\n\nAsyncFsync::~AsyncFsync()\n{\n\tdestroy_impl();\n\n\tL_OBJ(this , \"DELETED AUTOCOMMIT!\");\n}\n\n\nvoid\nAsyncFsync::destroy_impl()\n{\n\trunning.store(false);\n\twakeup_signal.notify_all();\n}\n\n\nvoid\nAsyncFsync::shutdown_impl(time_t asap, time_t now)\n{\n\tL_OBJ(this , \"SHUTDOWN AUTOCOMMIT! (%d %d)\", asap, now);\n\n\tWorker::shutdown_impl(asap, now);\n\n\t\/\/ Call implementation directly, as we don't use a loop. Object gets\n\t\/\/ detached when run() ends:\n\n\tdestroy_impl();\n}\n\n\nvoid\nAsyncFsync::run()\n{\n\twhile (running) {\n\t\tstd::unique_lock<std::mutex> lk(AsyncFsync::mtx);\n\t\tAsyncFsync::wakeup_signal.wait_until(lk, std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()));\n\n\t\t{\n\t\t\tstd::unique_lock<std::mutex> statuses_lk(AsyncFsync::statuses_mtx);\n\n\t\t\tauto now = std::chrono::system_clock::now();\n\t\t\tAsyncFsync::next_wakeup_time.store(std::chrono::system_clock::to_time_t(now + 20s));\n\n\t\t\tfor (auto it = AsyncFsync::statuses.begin(); it != AsyncFsync::statuses.end(); ) {\n\t\t\t\tauto status = it->second;\n\t\t\t\tauto next_wakeup_time = status.next_wakeup_time();\n\t\t\t\tif (next_wakeup_time <= now) {\n\t\t\t\t\tint fd = it->first;\n\t\t\t\t\tAsyncFsync::statuses.erase(it);\n\t\t\t\t\tstatuses_lk.unlock();\n\t\t\t\t\tlk.unlock();\n\n\t\t\t\t\tswitch (status.mode) {\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tif likely(io::full_fsync(fd) == 0) {\n\t\t\t\t\t\t\t\tL_DEBUG(this, \"Async Full Fsync: %d%s\", fd, next_wakeup_time == status.max_commit_time ? \" (forced)\" : \"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tif likely(io::fsync(fd) == 0) {\n\t\t\t\t\t\t\t\tL_DEBUG(this, \"Async Fsync: %d%s\", fd, next_wakeup_time == status.max_commit_time ? \" (forced)\" : \"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tlk.lock();\n\t\t\t\t\tstatuses_lk.lock();\n\t\t\t\t\tit = AsyncFsync::statuses.begin();\n\t\t\t\t} else if (std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()) > next_wakeup_time) {\n\t\t\t\t\tAsyncFsync::next_wakeup_time.store(std::chrono::system_clock::to_time_t(next_wakeup_time));\n\t\t\t\t\t++it;\n\t\t\t\t} else {\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdetach_impl();\n}\n\n\nint\nAsyncFsync::_fsync(int fd, bool full_fsync)\n{\n\tstd::lock_guard<std::mutex> statuses_lk(AsyncFsync::statuses_mtx);\n\tAsyncFsync::Status& status = AsyncFsync::statuses[fd];\n\n\tauto now = std::chrono::system_clock::now();\n\tif (!status.mode) {\n\t\tstatus.mode = full_fsync ? 1 : 2;\n\t\tstatus.max_commit_time = now + 5s;\n\t}\n\tstatus.commit_time = now + 1s;\n\n\tif (std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()) > status.next_wakeup_time()) {\n\t\tAsyncFsync::wakeup_signal.notify_one();\n\t}\n\n\treturn 0;\n}\n<commit_msg>Async fsync time reduced<commit_after>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"async_fsync.h\"\n\n#include \"io_utils.h\"\n#include \"manager.h\"\n\n\nstd::mutex AsyncFsync::mtx;\nstd::mutex AsyncFsync::statuses_mtx;\nstd::condition_variable AsyncFsync::wakeup_signal;\nstd::unordered_map<int, AsyncFsync::Status> AsyncFsync::statuses;\nstd::atomic<std::time_t> AsyncFsync::next_wakeup_time(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now() + 10s));\n\n\nstd::chrono::time_point<std::chrono::system_clock>\nAsyncFsync::Status::next_wakeup_time()\n{\n\treturn max_commit_time < commit_time ? max_commit_time : commit_time;\n}\n\n\nAsyncFsync::AsyncFsync(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_)\n\t: Worker(std::move(manager_), loop_),\n\t running(true)\n{\n\tL_OBJ(this, \"CREATED AUTOCOMMIT!\");\n}\n\n\nAsyncFsync::~AsyncFsync()\n{\n\tdestroy_impl();\n\n\tL_OBJ(this , \"DELETED AUTOCOMMIT!\");\n}\n\n\nvoid\nAsyncFsync::destroy_impl()\n{\n\trunning.store(false);\n\twakeup_signal.notify_all();\n}\n\n\nvoid\nAsyncFsync::shutdown_impl(time_t asap, time_t now)\n{\n\tL_OBJ(this , \"SHUTDOWN AUTOCOMMIT! (%d %d)\", asap, now);\n\n\tWorker::shutdown_impl(asap, now);\n\n\t\/\/ Call implementation directly, as we don't use a loop. Object gets\n\t\/\/ detached when run() ends:\n\n\tdestroy_impl();\n}\n\n\nvoid\nAsyncFsync::run()\n{\n\twhile (running) {\n\t\tstd::unique_lock<std::mutex> lk(AsyncFsync::mtx);\n\t\tAsyncFsync::wakeup_signal.wait_until(lk, std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()));\n\n\t\t{\n\t\t\tstd::unique_lock<std::mutex> statuses_lk(AsyncFsync::statuses_mtx);\n\n\t\t\tauto now = std::chrono::system_clock::now();\n\t\t\tAsyncFsync::next_wakeup_time.store(std::chrono::system_clock::to_time_t(now + 20s));\n\n\t\t\tfor (auto it = AsyncFsync::statuses.begin(); it != AsyncFsync::statuses.end(); ) {\n\t\t\t\tauto status = it->second;\n\t\t\t\tauto next_wakeup_time = status.next_wakeup_time();\n\t\t\t\tif (next_wakeup_time <= now) {\n\t\t\t\t\tint fd = it->first;\n\t\t\t\t\tAsyncFsync::statuses.erase(it);\n\t\t\t\t\tstatuses_lk.unlock();\n\t\t\t\t\tlk.unlock();\n\n\t\t\t\t\tswitch (status.mode) {\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tif likely(io::full_fsync(fd) == 0) {\n\t\t\t\t\t\t\t\tL_DEBUG(this, \"Async Full Fsync: %d%s\", fd, next_wakeup_time == status.max_commit_time ? \" (forced)\" : \"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tif likely(io::fsync(fd) == 0) {\n\t\t\t\t\t\t\t\tL_DEBUG(this, \"Async Fsync: %d%s\", fd, next_wakeup_time == status.max_commit_time ? \" (forced)\" : \"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tlk.lock();\n\t\t\t\t\tstatuses_lk.lock();\n\t\t\t\t\tit = AsyncFsync::statuses.begin();\n\t\t\t\t} else if (std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()) > next_wakeup_time) {\n\t\t\t\t\tAsyncFsync::next_wakeup_time.store(std::chrono::system_clock::to_time_t(next_wakeup_time));\n\t\t\t\t\t++it;\n\t\t\t\t} else {\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdetach_impl();\n}\n\n\nint\nAsyncFsync::_fsync(int fd, bool full_fsync)\n{\n\tstd::lock_guard<std::mutex> statuses_lk(AsyncFsync::statuses_mtx);\n\tAsyncFsync::Status& status = AsyncFsync::statuses[fd];\n\n\tauto now = std::chrono::system_clock::now();\n\tif (!status.mode) {\n\t\tstatus.mode = full_fsync ? 1 : 2;\n\t\tstatus.max_commit_time = now + 3s;\n\t}\n\tstatus.commit_time = now + 500ms;\n\n\tif (std::chrono::system_clock::from_time_t(AsyncFsync::next_wakeup_time.load()) > status.next_wakeup_time()) {\n\t\tAsyncFsync::wakeup_signal.notify_one();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Catch\n#include <catch.hpp>\n\n\/\/ C++ Standard Library\n#include <memory>\n\n\/\/ Mantella\n#include <mantella>\n\nclass TestHillClimbing : public mant::HillClimbing {\n public:\n TestHillClimbing(\n const std::shared_ptr<mant::OptimisationProblem> optimisationProblem)\n : mant::HillClimbing(optimisationProblem),\n neighboursIndex_(0) {\n\n }\n\n void setVelocitys(\n const arma::Mat<double>& neighbours){\n neighbours_ = neighbours;\n }\n\n protected:\n\n arma::Col<double> getRandomNeighbour(const arma::Col<double>& parameter,\n const double minimalDistance,\n const double maximalDistance) override {\n return neighbours_.col(neighboursIndex_++);\n }\n\n arma::uword neighboursIndex_;\n arma::Mat<double> neighbours_;\n};\n\nTEST_CASE(\"HillClimbing\", \"\") {\n SECTION(\".setMaximalStepSize\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n mant::HillClimbing hillClimbing(optimisationProblem);\n\n SECTION(\"Test default value\"){\n \/\/TODO\n }\n\n SECTION(\"Test with parameter\") {\n \/\/TODO\n }\n }\n\n SECTION(\".optimise\") {\n \/\/ TODO\n }\n\n SECTION(\"Exception tests\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n mant::HillClimbing hillClimbing(optimisationProblem);\n\n SECTION(\"Throws an exception, if the MaximalStepSize zero\") {\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({0, 0}), std::logic_error);\n }\n\n SECTION(\"Throws an exception, if the size of MaximalStepSize is not equal to the number of dimension of the problem\") {\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100, 100, 100}), std::logic_error);\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100}), std::logic_error);\n }\n\n }\n\n SECTION(\".toString\") {\n SECTION(\"Returns the expected class name.\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n CHECK(mant::HillClimbing(optimisationProblem).toString() == \"hill_climbing\");\n }\n }\n}\n<commit_msg>Using the recently introduced getRandomNeighbour feature<commit_after>\/\/ Catch\n#include <catch.hpp>\n\n\/\/ C++ Standard Library\n#include <memory>\n\n\/\/ Mantella\n#include <mantella>\n\nclass TestHillClimbing : public mant::HillClimbing {\n public:\n TestHillClimbing(\n const std::shared_ptr<mant::OptimisationProblem> optimisationProblem)\n : mant::HillClimbing(optimisationProblem),\n neighboursIndex_(0) {\n\n }\n\n void setVelocitys(\n const arma::Mat<double>& neighbours){\n neighbours_ = neighbours;\n }\n\n protected:\n arma::Col<double> getRandomNeighbour(\n const arma::Col<double>& parameter,\n const arma::Col<double>& minimalDistance,\n const arma::Col<double>& maximalDistance) override {\n return neighbours_.col(neighboursIndex_++);\n }\n\n arma::uword neighboursIndex_;\n arma::Mat<double> neighbours_;\n};\n\nTEST_CASE(\"HillClimbing\", \"\") {\n SECTION(\".setMaximalStepSize\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n mant::HillClimbing hillClimbing(optimisationProblem);\n\n SECTION(\"Test default value\"){\n \/\/TODO\n }\n\n SECTION(\"Test with parameter\") {\n \/\/TODO\n }\n }\n\n SECTION(\".optimise\") {\n \/\/ TODO\n }\n\n SECTION(\"Exception tests\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n mant::HillClimbing hillClimbing(optimisationProblem);\n\n SECTION(\"Throws an exception, if the MaximalStepSize zero\") {\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({0, 0}), std::logic_error);\n }\n\n SECTION(\"Throws an exception, if the size of MaximalStepSize is not equal to the number of dimension of the problem\") {\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100, 100, 100}), std::logic_error);\n\/\/ CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100}), std::logic_error);\n }\n\n }\n\n SECTION(\".toString\") {\n SECTION(\"Returns the expected class name.\") {\n std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2));\n CHECK(mant::HillClimbing(optimisationProblem).toString() == \"hill_climbing\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Ali Saidi\n *\/\n\n#include \"base\/fenv.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/random.hh\"\n#include \"sim\/serialize.hh\"\n\nusing namespace std;\n\nRandom::Random()\n{\n \/\/ default random seed taken from original source\n init(5489);\n}\n\nRandom::Random(uint32_t s)\n{\n init(s);\n}\n\nRandom::Random(uint32_t init_key[], int key_length)\n{\n init(init_key, key_length);\n}\n\nRandom::~Random()\n{\n}\n\n\/\/ To preserve the uniform random distribution between min and max,\n\/\/ and allow all numbers to be represented, we generate a uniform\n\/\/ random number to the nearest power of two greater than max. If\n\/\/ this number doesn't fall between 0 and max, we try again. Anything\n\/\/ else would skew the distribution.\nuint32_t\nRandom::genrand(uint32_t max)\n{\n int log = ceilLog2(max);\n int shift = (sizeof(uint32_t) * 8 - log);\n uint32_t random;\n\n do {\n random = genrand() >> shift;\n } while (random > max);\n\n return random;\n}\n\nuint64_t\nRandom::genrand(uint64_t max)\n{\n int log = ceilLog2(max);\n int shift = (sizeof(uint64_t) * 8 - log);\n uint64_t random;\n\n do {\n random = (uint64_t)genrand() << 32 | (uint64_t)genrand();\n random = random >> shift;\n } while (random > max);\n\n return random;\n}\n\nvoid\nRandom::serialize(const string &base, ostream &os)\n{\n int length = N;\n paramOut(os, base + \".mti\", mti);\n paramOut(os, base + \".length\", length);\n arrayParamOut(os, base + \".data\", mt, length);\n}\n\nvoid\nRandom::unserialize(const string &base, Checkpoint *cp, const string §ion)\n{\n int length;\n\n paramIn(cp, section, base + \".mti\", mti);\n paramIn(cp, section, base + \".length\", length);\n if (length != N)\n panic(\"cant unserialize random number data. length != %d\\n\", length);\n\n arrayParamIn(cp, section, base + \".data\", mt, length);\n}\n\nRandom random_mt;\n<commit_msg>BASE: Fix genrand to generate both 0s and 1s when max equals one. previously was only generating 0s.<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Ali Saidi\n *\/\n\n#include \"base\/fenv.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/random.hh\"\n#include \"sim\/serialize.hh\"\n\nusing namespace std;\n\nRandom::Random()\n{\n \/\/ default random seed taken from original source\n init(5489);\n}\n\nRandom::Random(uint32_t s)\n{\n init(s);\n}\n\nRandom::Random(uint32_t init_key[], int key_length)\n{\n init(init_key, key_length);\n}\n\nRandom::~Random()\n{\n}\n\n\/\/ To preserve the uniform random distribution between min and max,\n\/\/ and allow all numbers to be represented, we generate a uniform\n\/\/ random number to the nearest power of two greater than max. If\n\/\/ this number doesn't fall between 0 and max, we try again. Anything\n\/\/ else would skew the distribution.\nuint32_t\nRandom::genrand(uint32_t max)\n{\n if (max == 0)\n return 0;\n int log = ceilLog2(max) + 1;\n int shift = (sizeof(uint32_t) * 8 - log);\n uint32_t random;\n\n do {\n random = genrand() >> shift;\n } while (random > max);\n\n return random;\n}\n\nuint64_t\nRandom::genrand(uint64_t max)\n{\n if (max == 0)\n return 0;\n int log = ceilLog2(max) + 1;\n int shift = (sizeof(uint64_t) * 8 - log);\n uint64_t random;\n\n do {\n random = (uint64_t)genrand() << 32 | (uint64_t)genrand();\n random = random >> shift;\n } while (random > max);\n\n return random;\n}\n\nvoid\nRandom::serialize(const string &base, ostream &os)\n{\n int length = N;\n paramOut(os, base + \".mti\", mti);\n paramOut(os, base + \".length\", length);\n arrayParamOut(os, base + \".data\", mt, length);\n}\n\nvoid\nRandom::unserialize(const string &base, Checkpoint *cp, const string §ion)\n{\n int length;\n\n paramIn(cp, section, base + \".mti\", mti);\n paramIn(cp, section, base + \".length\", length);\n if (length != N)\n panic(\"cant unserialize random number data. length != %d\\n\", length);\n\n arrayParamIn(cp, section, base + \".data\", mt, length);\n}\n\nRandom random_mt;\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Ali Saidi\n *\/\n\n#include \"base\/fenv.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/random.hh\"\n#include \"sim\/serialize.hh\"\n\nusing namespace std;\n\nRandom::Random()\n{\n \/\/ default random seed taken from original source\n init(5489);\n}\n\nRandom::Random(uint32_t s)\n{\n init(s);\n}\n\nRandom::Random(uint32_t init_key[], int key_length)\n{\n init(init_key, key_length);\n}\n\nRandom::~Random()\n{\n}\n\n\/\/ To preserve the uniform random distribution between min and max,\n\/\/ and allow all numbers to be represented, we generate a uniform\n\/\/ random number to the nearest power of two greater than max. If\n\/\/ this number doesn't fall between 0 and max, we try again. Anything\n\/\/ else would skew the distribution.\nuint32_t\nRandom::genrand(uint32_t max)\n{\n int log = ceilLog2(max);\n int shift = (sizeof(uint32_t) * 8 - log);\n uint32_t random;\n\n do {\n random = genrand() >> shift;\n } while (random > max);\n\n return random;\n}\n\nuint64_t\nRandom::genrand(uint64_t max)\n{\n int log = ceilLog2(max);\n int shift = (sizeof(uint64_t) * 8 - log);\n uint64_t random;\n\n do {\n random = (uint64_t)genrand() << 32 | (uint64_t)genrand();\n random = random >> shift;\n } while (random > max);\n\n return random;\n}\n\nvoid\nRandom::serialize(const string &base, ostream &os)\n{\n int length = N;\n paramOut(os, base + \".mti\", mti);\n paramOut(os, base + \".length\", length);\n arrayParamOut(os, base + \".data\", mt, length);\n}\n\nvoid\nRandom::unserialize(const string &base, Checkpoint *cp, const string §ion)\n{\n int length;\n\n paramIn(cp, section, base + \".mti\", mti);\n paramIn(cp, section, base + \".length\", length);\n if (length != N)\n panic(\"cant unserialize random number data. length != %d\\n\", length);\n\n arrayParamIn(cp, section, base + \".data\", mt, length);\n}\n\nRandom random_mt;\n<commit_msg>BASE: Fix genrand to generate both 0s and 1s when max equals one. previously was only generating 0s.<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Ali Saidi\n *\/\n\n#include \"base\/fenv.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/random.hh\"\n#include \"sim\/serialize.hh\"\n\nusing namespace std;\n\nRandom::Random()\n{\n \/\/ default random seed taken from original source\n init(5489);\n}\n\nRandom::Random(uint32_t s)\n{\n init(s);\n}\n\nRandom::Random(uint32_t init_key[], int key_length)\n{\n init(init_key, key_length);\n}\n\nRandom::~Random()\n{\n}\n\n\/\/ To preserve the uniform random distribution between min and max,\n\/\/ and allow all numbers to be represented, we generate a uniform\n\/\/ random number to the nearest power of two greater than max. If\n\/\/ this number doesn't fall between 0 and max, we try again. Anything\n\/\/ else would skew the distribution.\nuint32_t\nRandom::genrand(uint32_t max)\n{\n if (max == 0)\n return 0;\n int log = ceilLog2(max) + 1;\n int shift = (sizeof(uint32_t) * 8 - log);\n uint32_t random;\n\n do {\n random = genrand() >> shift;\n } while (random > max);\n\n return random;\n}\n\nuint64_t\nRandom::genrand(uint64_t max)\n{\n if (max == 0)\n return 0;\n int log = ceilLog2(max) + 1;\n int shift = (sizeof(uint64_t) * 8 - log);\n uint64_t random;\n\n do {\n random = (uint64_t)genrand() << 32 | (uint64_t)genrand();\n random = random >> shift;\n } while (random > max);\n\n return random;\n}\n\nvoid\nRandom::serialize(const string &base, ostream &os)\n{\n int length = N;\n paramOut(os, base + \".mti\", mti);\n paramOut(os, base + \".length\", length);\n arrayParamOut(os, base + \".data\", mt, length);\n}\n\nvoid\nRandom::unserialize(const string &base, Checkpoint *cp, const string §ion)\n{\n int length;\n\n paramIn(cp, section, base + \".mti\", mti);\n paramIn(cp, section, base + \".length\", length);\n if (length != N)\n panic(\"cant unserialize random number data. length != %d\\n\", length);\n\n arrayParamIn(cp, section, base + \".data\", mt, length);\n}\n\nRandom random_mt;\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: filedlg.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:58:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVT_FILEDLG_HXX\n#define _SVT_FILEDLG_HXX\n\n#ifndef _DIALOG_HXX\n#include <vcl\/dialog.hxx>\n#endif\n\nclass Edit;\nclass ImpSvFileDlg;\n\n\/\/ --------------\n\/\/ - SvPathDialog -\n\/\/ --------------\n\nclass PathDialog : public ModalDialog\n{\nprivate:\n friend class FileDialog; \/\/ Imp...\n\n ImpSvFileDlg* pImpFileDlg; \/\/ Implementation\n Link aOKHdlLink; \/\/ Link zum OK-Handler\n\nprotected:\n UniString aDfltExt; \/\/ Default - Extension\n\npublic:\n PathDialog( Window* pParent, WinBits nWinStyle = 0, BOOL bCreateDir = TRUE );\n ~PathDialog();\n\n virtual long OK();\n\n void SetPath( const UniString& rNewPath );\n void SetPath( const Edit& rEdit );\n UniString GetPath() const;\n\n void SetOKHdl( const Link& rLink ) { aOKHdlLink = rLink; }\n const Link& GetOKHdl() const { return aOKHdlLink; }\n\n virtual short Execute();\n};\n\n\/\/ --------------\n\/\/ - SvFileDialog -\n\/\/ --------------\n\nclass FileDialog : public PathDialog\n{\nprivate:\n Link aFileHdlLink; \/\/ Link zum FileSelect-Handler\n Link aFilterHdlLink; \/\/ Link zum FilterSelect-Handler\n\npublic:\n FileDialog( Window* pParent, WinBits nWinStyle );\n ~FileDialog();\n\n virtual void FileSelect();\n virtual void FilterSelect();\n\n void SetDefaultExt( const UniString& rExt ) { aDfltExt = rExt; }\n const UniString& GetDefaultExt() const { return aDfltExt; }\n void AddFilter( const UniString& rFilter, const UniString& rType );\n void AddFilter( const UniString& rFilter, const UniString& rType,\n const UniString& rSysType );\n void RemoveFilter( const UniString& rFilter );\n void RemoveAllFilter();\n void SetCurFilter( const UniString& rFilter );\n UniString GetCurFilter() const;\n USHORT GetFilterCount() const;\n UniString GetFilterName( USHORT nPos ) const;\n UniString GetFilterType( USHORT nPos ) const;\n\n void SetFileSelectHdl( const Link& rLink ) { aFileHdlLink = rLink; }\n const Link& GetFileSelectHdl() const { return aFileHdlLink; }\n void SetFilterSelectHdl( const Link& rLink ) { aFilterHdlLink = rLink; }\n const Link& GetFilterSelectHdl() const { return aFilterHdlLink; }\n\n void SetOkButtonText( const UniString& rText );\n void SetCancelButtonText( const UniString& rText );\n};\n\n#endif \/\/ _FILEDLG_HXX\n<commit_msg>INTEGRATION: CWS visibility03 (1.1.1.1.946); FILE MERGED 2005\/03\/24 14:13:38 mhu 1.1.1.1.946.1: #i45006# Include svtools\/(svl|svt)dllapi.h, declare symbol visibility with (SVL|SVT)_DLL(PUBLIC|PRIVATE) as appropriate; partial cleanup.<commit_after>\/*************************************************************************\n *\n * $RCSfile: filedlg.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 10:07:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVT_FILEDLG_HXX\n#define _SVT_FILEDLG_HXX\n\n#ifndef INCLUDED_SVTDLLAPI_H\n#include \"svtools\/svtdllapi.h\"\n#endif\n\n#ifndef _DIALOG_HXX\n#include <vcl\/dialog.hxx>\n#endif\n\nclass Edit;\nclass ImpSvFileDlg;\n\n\/\/ --------------\n\/\/ - SvPathDialog -\n\/\/ --------------\n\nclass SVT_DLLPUBLIC PathDialog : public ModalDialog\n{\nprivate:\n friend class FileDialog; \/\/ Imp...\n\n ImpSvFileDlg* pImpFileDlg; \/\/ Implementation\n Link aOKHdlLink; \/\/ Link zum OK-Handler\n\nprotected:\n UniString aDfltExt; \/\/ Default - Extension\n\npublic:\n PathDialog( Window* pParent, WinBits nWinStyle = 0, BOOL bCreateDir = TRUE );\n ~PathDialog();\n\n virtual long OK();\n\n void SetPath( const UniString& rNewPath );\n void SetPath( const Edit& rEdit );\n UniString GetPath() const;\n\n void SetOKHdl( const Link& rLink ) { aOKHdlLink = rLink; }\n const Link& GetOKHdl() const { return aOKHdlLink; }\n\n virtual short Execute();\n};\n\n\/\/ --------------\n\/\/ - SvFileDialog -\n\/\/ --------------\n\nclass SVT_DLLPUBLIC FileDialog : public PathDialog\n{\nprivate:\n Link aFileHdlLink; \/\/ Link zum FileSelect-Handler\n Link aFilterHdlLink; \/\/ Link zum FilterSelect-Handler\n\npublic:\n FileDialog( Window* pParent, WinBits nWinStyle );\n ~FileDialog();\n\n virtual void FileSelect();\n virtual void FilterSelect();\n\n void SetDefaultExt( const UniString& rExt ) { aDfltExt = rExt; }\n const UniString& GetDefaultExt() const { return aDfltExt; }\n void AddFilter( const UniString& rFilter, const UniString& rType );\n void AddFilter( const UniString& rFilter, const UniString& rType,\n const UniString& rSysType );\n void RemoveFilter( const UniString& rFilter );\n void RemoveAllFilter();\n void SetCurFilter( const UniString& rFilter );\n UniString GetCurFilter() const;\n USHORT GetFilterCount() const;\n UniString GetFilterName( USHORT nPos ) const;\n UniString GetFilterType( USHORT nPos ) const;\n\n void SetFileSelectHdl( const Link& rLink ) { aFileHdlLink = rLink; }\n const Link& GetFileSelectHdl() const { return aFileHdlLink; }\n void SetFilterSelectHdl( const Link& rLink ) { aFilterHdlLink = rLink; }\n const Link& GetFilterSelectHdl() const { return aFilterHdlLink; }\n\n void SetOkButtonText( const UniString& rText );\n void SetCancelButtonText( const UniString& rText );\n};\n\n#endif \/\/ _FILEDLG_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"opt\/wire\/wire_insn.h\"\n\n#include \"design\/design_util.h\"\n#include \"design\/design_tool.h\"\n#include \"iroha\/i_design.h\"\n#include \"iroha\/resource_class.h\"\n#include \"opt\/bb_set.h\"\n#include \"opt\/data_flow.h\"\n#include \"opt\/debug_annotation.h\"\n\nnamespace iroha {\nnamespace opt {\nnamespace wire {\n\nWireInsnPhase::~WireInsnPhase() {\n}\n\nPhase *WireInsnPhase::Create() {\n return new WireInsnPhase();\n}\n\nbool WireInsnPhase::ApplyForTable(ITable *table) {\n WireInsn wire_insn(table, annotation_);\n return wire_insn.Perform();\n}\n\nWireInsn::WireInsn(ITable *table, DebugAnnotation *annotation)\n : table_(table), annotation_(annotation), bset_(nullptr),\n data_flow_(nullptr) {\n}\n\nWireInsn::~WireInsn() {\n delete bset_;\n delete data_flow_;\n}\n\nbool WireInsn::Perform() {\n assign_ = DesignTool::GetResource(table_, resource::kSet);\n transition_ = DesignUtil::FindTransitionResource(table_);\n bset_ = BBSet::Create(table_, annotation_);\n data_flow_ = DataFlow::Create(bset_, annotation_);\n CollectReachingRegisters();\n for (BB *bb : bset_->bbs_) {\n BuildDependency(bb);\n }\n\n for (BB *bb : bset_->bbs_) {\n SplitInsnOutputBB(bb);\n ScanBBToMoveInsn(bb);\n }\n AddWireToRegisterAssignments();\n annotation_->DumpIntermediateTable(table_);\n return true;\n}\n\nvoid WireInsn::CollectReachingRegisters() {\n CollectUsedRegs();\n \/\/ Collect defs used somewhere in this table.\n set<RegDef *> active_defs;\n for (BB *bb : bset_->bbs_) {\n vector<RegDef *> reach_defs;\n data_flow_->GetReachDefs(bb, &reach_defs);\n auto bb_regs = used_regs_[bb];\n for (RegDef *reg_def : reach_defs) {\n if (bb_regs.find(reg_def->reg) != bb_regs.end()) {\n\tactive_defs.insert(reg_def);\n }\n }\n }\n\n for (RegDef *reg_def : active_defs) {\n PerInsn *pi = GetPerInsn(reg_def->insn);\n for (IRegister *oreg : reg_def->insn->outputs_) {\n if (oreg == reg_def->reg) {\n\t\/\/ TODO(yt76): should be reach && used.\n\t\/\/ now this just checks only the reachability.\n\tpi->output_reach_to_other_bb_.insert(oreg);\n }\n }\n }\n}\n\nvoid WireInsn::CollectUsedRegs() {\n for (IState *st : table_->states_) {\n BB *bb = bset_->state_to_bb_[st];\n for (IInsn *insn : st->insns_) {\n for (IRegister *ireg : insn->inputs_) {\n\tused_regs_[bb].insert(ireg);\n }\n }\n }\n}\n\nvoid WireInsn::BuildDependency(BB *bb) {\n map<IRegister *, IInsn *> last_def_insn;\n map<IRegister *, IInsn *> last_read_insn;\n int nth_state = 0;\n for (IState *st : bb->states_) {\n for (IInsn *insn : st->insns_) {\n PerInsn *pi = GetPerInsn(insn);\n pi->nth_state = nth_state;\n \/\/ WRITE -> READ dependency\n for (IRegister *reg : insn->inputs_) {\n BuildRWDependencyPair(insn, reg, last_def_insn);\n }\n \/\/ READ -> WRITE dependency\n for (IRegister *reg : insn->outputs_) {\n BuildRWDependencyPair(insn, reg, last_read_insn);\n }\n \/\/ Update last write\n for (IRegister *reg : insn->outputs_) {\n\tlast_def_insn[reg] = insn;\n }\n \/\/ Update last read\n for (IRegister *reg : insn->inputs_) {\n\tlast_read_insn[reg] = insn;\n }\n }\n ++nth_state;\n }\n}\n\nvoid WireInsn::BuildRWDependencyPair(IInsn *insn, IRegister *reg,\n\t\t\t\t map<IRegister *, IInsn *> &dep_map) {\n IRegister *input = reg;\n IInsn *def_insn = dep_map[input];\n if (!def_insn) {\n \/\/ not written\/read in this block.\n return;\n }\n PerInsn *pi = GetPerInsn(insn);\n pi->depending_insn_[input] = def_insn;\n \/\/ adds reverse mapping too.\n PerInsn *def_insn_pi = GetPerInsn(def_insn);\n def_insn_pi->using_insns_[input].insert(insn);\n}\n\nvoid WireInsn::SplitInsnOutputBB(BB *bb) {\n for (IState *st : bb->states_) {\n for (IInsn *insn : st->insns_) {\n \/\/ TODO(yt76): Don't touch multi cycles insns like memory ops.\n if (insn->GetResource() == assign_) {\n PerInsn *pi = GetPerInsn(insn);\n pi->is_assign = true;\n } else {\n SplitInsnOutput(insn);\n }\n }\n }\n}\n\nvoid WireInsn::SplitInsnOutput(IInsn *insn) {\n for (auto it = insn->outputs_.begin(); it != insn->outputs_.end(); ++it) {\n IRegister *reg = *it;\n if (reg->IsConst() || reg->IsStateLocal()) {\n continue;\n }\n IRegister *wire_reg =\n new IRegister(table_, reg->GetName() + \"_\" + Util::Itoa(insn->GetId()));\n wire_reg->SetStateLocal(true);\n table_->registers_.push_back(wire_reg);\n AddWireToRegMapping(insn, wire_reg, reg);\n *it = wire_reg;\n }\n}\n\nvoid WireInsn::AddWireToRegMapping(IInsn *insn, IRegister *wire,\n\t\t\t\t IRegister *reg) {\n PerInsn *pi = GetPerInsn(insn);\n pi->wire_to_register_[wire] = reg;\n pi->register_to_wire_[reg] = wire;\n}\n\nvoid WireInsn::ScanBBToMoveInsn(BB *bb) {\n for (int target = 0; target < bb->states_.size() - 1; ++target) {\n for (int pos = target + 1; pos < bb->states_.size(); ++pos) {\n vector<IInsn *> movable_insns;\n IState *src_st = bb->states_[pos];\n for (IInsn *insn : src_st->insns_) {\n\tif (CanMoveInsn(insn, bb, target)) {\n\t movable_insns.push_back(insn);\n\t}\n }\n for (IInsn *insn : movable_insns) {\n\tMoveInsn(insn, bb, target);\n }\n }\n }\n}\n\nbool WireInsn::CanMoveInsn(IInsn *insn, BB *bb, int target_pos) {\n if (insn->GetResource() == transition_) {\n return false;\n }\n IState *target_st = bb->states_[target_pos];\n if (!CanUseResourceInState(target_st, insn->GetResource())) {\n return false;\n }\n PerInsn *pi = GetPerInsn(insn);\n int max_pos = 0;\n \/\/ Check input dependency\n for (auto it : pi->depending_insn_) {\n PerInsn *src_pi = GetPerInsn(it.second);\n if (src_pi->nth_state > max_pos) {\n max_pos = src_pi->nth_state;\n }\n }\n if (max_pos <= target_pos) {\n return true;\n }\n return false;\n}\n\nvoid WireInsn::MoveInsn(IInsn *insn, BB *bb, int target_pos) {\n PerInsn *pi = GetPerInsn(insn);\n IState *src_st = bb->states_[pi->nth_state];\n IState *dst_st = bb->states_[target_pos];\n DesignTool::MoveInsn(insn, src_st, dst_st);\n pi->nth_state = target_pos;\n \/\/ for (IRegister *ireg : insn->inputs_) {\n for (auto it = insn->inputs_.begin(); it != insn->inputs_.end(); ++it) {\n IRegister *ireg = *it;\n IInsn *src_insn = pi->depending_insn_[ireg];\n if (!src_insn) {\n continue;\n }\n PerInsn *src_pi = GetPerInsn(src_insn);\n if (src_pi->nth_state < target_pos) {\n \/\/ This register was an output in previous state,\n \/\/ so the wire is not avaialble.\n continue;\n }\n IRegister *alt_input = src_pi->register_to_wire_[ireg];\n if (alt_input == nullptr && src_pi->is_assign) {\n alt_input = *(src_insn->inputs_.begin());\n }\n if (alt_input != nullptr) {\n *it = alt_input;\n }\n }\n}\n\nbool WireInsn::CanUseResourceInState(IState *st, IResource *resource) {\n for (IInsn *target_insn : st->insns_) {\n if (resource->GetClass()->IsExclusive() &&\n\tresource == target_insn->GetResource()) {\n return false;\n }\n }\n return true;\n}\n\nvoid WireInsn::AddWireToRegisterAssignments() {\n for (IState *st : table_->states_) {\n vector<IInsn *> new_assign_insn;\n for (IInsn *insn : st->insns_) {\n PerInsn *pi = GetPerInsn(insn);\n for (IRegister *maybe_wire : insn->outputs_) {\n\tIRegister *orig_reg = pi->wire_to_register_[maybe_wire];\n\tif (orig_reg) {\n\t const bool used_later = IsUsedLaterInThisBB(insn, orig_reg);\n\t const bool reach_to_other_bb =\n\t pi->output_reach_to_other_bb_.find(orig_reg) !=\n\t pi->output_reach_to_other_bb_.end();\n\t if (used_later || reach_to_other_bb) {\n\t IInsn *assign_insn = new IInsn(assign_);\n\t assign_insn->inputs_.push_back(maybe_wire);\n\t assign_insn->outputs_.push_back(orig_reg);\n\t new_assign_insn.push_back(assign_insn);\n\t }\n\t}\n }\n }\n for (IInsn *insn : new_assign_insn) {\n st->insns_.push_back(insn);\n }\n }\n}\n\nbool WireInsn::IsUsedLaterInThisBB(IInsn *insn, IRegister *output) {\n PerInsn *pi = GetPerInsn(insn);\n map<IRegister *, set<IInsn *> >::iterator it = pi->using_insns_.find(output);\n if (it == pi->using_insns_.end()) {\n return false;\n }\n set<IInsn *> &users = it->second;\n for (IInsn *insn : users) {\n PerInsn *user_pi = GetPerInsn(insn);\n if (user_pi->nth_state > pi->nth_state) {\n return true;\n }\n }\n return false;\n}\n\nWireInsn::PerInsn *WireInsn::GetPerInsn(IInsn *insn) {\n PerInsn *pi = per_insn_map_[insn];\n if (pi == nullptr) {\n pi = new PerInsn;\n per_insn_map_[insn] = pi;\n }\n return pi;\n}\n\n} \/\/ namespace wire\n} \/\/ namespace opt\n} \/\/ namespace iroha\n<commit_msg>Add a missing null check on wire_insn optimizer.<commit_after>#include \"opt\/wire\/wire_insn.h\"\n\n#include \"design\/design_util.h\"\n#include \"design\/design_tool.h\"\n#include \"iroha\/i_design.h\"\n#include \"iroha\/resource_class.h\"\n#include \"opt\/bb_set.h\"\n#include \"opt\/data_flow.h\"\n#include \"opt\/debug_annotation.h\"\n\nnamespace iroha {\nnamespace opt {\nnamespace wire {\n\nWireInsnPhase::~WireInsnPhase() {\n}\n\nPhase *WireInsnPhase::Create() {\n return new WireInsnPhase();\n}\n\nbool WireInsnPhase::ApplyForTable(ITable *table) {\n WireInsn wire_insn(table, annotation_);\n return wire_insn.Perform();\n}\n\nWireInsn::WireInsn(ITable *table, DebugAnnotation *annotation)\n : table_(table), annotation_(annotation), bset_(nullptr),\n data_flow_(nullptr) {\n}\n\nWireInsn::~WireInsn() {\n delete bset_;\n delete data_flow_;\n}\n\nbool WireInsn::Perform() {\n assign_ = DesignTool::GetResource(table_, resource::kSet);\n transition_ = DesignUtil::FindTransitionResource(table_);\n bset_ = BBSet::Create(table_, annotation_);\n data_flow_ = DataFlow::Create(bset_, annotation_);\n CollectReachingRegisters();\n for (BB *bb : bset_->bbs_) {\n BuildDependency(bb);\n }\n\n for (BB *bb : bset_->bbs_) {\n SplitInsnOutputBB(bb);\n ScanBBToMoveInsn(bb);\n }\n AddWireToRegisterAssignments();\n if (annotation_ != nullptr) {\n annotation_->DumpIntermediateTable(table_);\n }\n return true;\n}\n\nvoid WireInsn::CollectReachingRegisters() {\n CollectUsedRegs();\n \/\/ Collect defs used somewhere in this table.\n set<RegDef *> active_defs;\n for (BB *bb : bset_->bbs_) {\n vector<RegDef *> reach_defs;\n data_flow_->GetReachDefs(bb, &reach_defs);\n auto bb_regs = used_regs_[bb];\n for (RegDef *reg_def : reach_defs) {\n if (bb_regs.find(reg_def->reg) != bb_regs.end()) {\n\tactive_defs.insert(reg_def);\n }\n }\n }\n\n for (RegDef *reg_def : active_defs) {\n PerInsn *pi = GetPerInsn(reg_def->insn);\n for (IRegister *oreg : reg_def->insn->outputs_) {\n if (oreg == reg_def->reg) {\n\t\/\/ TODO(yt76): should be reach && used.\n\t\/\/ now this just checks only the reachability.\n\tpi->output_reach_to_other_bb_.insert(oreg);\n }\n }\n }\n}\n\nvoid WireInsn::CollectUsedRegs() {\n for (IState *st : table_->states_) {\n BB *bb = bset_->state_to_bb_[st];\n for (IInsn *insn : st->insns_) {\n for (IRegister *ireg : insn->inputs_) {\n\tused_regs_[bb].insert(ireg);\n }\n }\n }\n}\n\nvoid WireInsn::BuildDependency(BB *bb) {\n map<IRegister *, IInsn *> last_def_insn;\n map<IRegister *, IInsn *> last_read_insn;\n int nth_state = 0;\n for (IState *st : bb->states_) {\n for (IInsn *insn : st->insns_) {\n PerInsn *pi = GetPerInsn(insn);\n pi->nth_state = nth_state;\n \/\/ WRITE -> READ dependency\n for (IRegister *reg : insn->inputs_) {\n BuildRWDependencyPair(insn, reg, last_def_insn);\n }\n \/\/ READ -> WRITE dependency\n for (IRegister *reg : insn->outputs_) {\n BuildRWDependencyPair(insn, reg, last_read_insn);\n }\n \/\/ Update last write\n for (IRegister *reg : insn->outputs_) {\n\tlast_def_insn[reg] = insn;\n }\n \/\/ Update last read\n for (IRegister *reg : insn->inputs_) {\n\tlast_read_insn[reg] = insn;\n }\n }\n ++nth_state;\n }\n}\n\nvoid WireInsn::BuildRWDependencyPair(IInsn *insn, IRegister *reg,\n\t\t\t\t map<IRegister *, IInsn *> &dep_map) {\n IRegister *input = reg;\n IInsn *def_insn = dep_map[input];\n if (!def_insn) {\n \/\/ not written\/read in this block.\n return;\n }\n PerInsn *pi = GetPerInsn(insn);\n pi->depending_insn_[input] = def_insn;\n \/\/ adds reverse mapping too.\n PerInsn *def_insn_pi = GetPerInsn(def_insn);\n def_insn_pi->using_insns_[input].insert(insn);\n}\n\nvoid WireInsn::SplitInsnOutputBB(BB *bb) {\n for (IState *st : bb->states_) {\n for (IInsn *insn : st->insns_) {\n \/\/ TODO(yt76): Don't touch multi cycles insns like memory ops.\n if (insn->GetResource() == assign_) {\n PerInsn *pi = GetPerInsn(insn);\n pi->is_assign = true;\n } else {\n SplitInsnOutput(insn);\n }\n }\n }\n}\n\nvoid WireInsn::SplitInsnOutput(IInsn *insn) {\n for (auto it = insn->outputs_.begin(); it != insn->outputs_.end(); ++it) {\n IRegister *reg = *it;\n if (reg->IsConst() || reg->IsStateLocal()) {\n continue;\n }\n IRegister *wire_reg =\n new IRegister(table_, reg->GetName() + \"_\" + Util::Itoa(insn->GetId()));\n wire_reg->SetStateLocal(true);\n table_->registers_.push_back(wire_reg);\n AddWireToRegMapping(insn, wire_reg, reg);\n *it = wire_reg;\n }\n}\n\nvoid WireInsn::AddWireToRegMapping(IInsn *insn, IRegister *wire,\n\t\t\t\t IRegister *reg) {\n PerInsn *pi = GetPerInsn(insn);\n pi->wire_to_register_[wire] = reg;\n pi->register_to_wire_[reg] = wire;\n}\n\nvoid WireInsn::ScanBBToMoveInsn(BB *bb) {\n for (int target = 0; target < bb->states_.size() - 1; ++target) {\n for (int pos = target + 1; pos < bb->states_.size(); ++pos) {\n vector<IInsn *> movable_insns;\n IState *src_st = bb->states_[pos];\n for (IInsn *insn : src_st->insns_) {\n\tif (CanMoveInsn(insn, bb, target)) {\n\t movable_insns.push_back(insn);\n\t}\n }\n for (IInsn *insn : movable_insns) {\n\tMoveInsn(insn, bb, target);\n }\n }\n }\n}\n\nbool WireInsn::CanMoveInsn(IInsn *insn, BB *bb, int target_pos) {\n if (insn->GetResource() == transition_) {\n return false;\n }\n IState *target_st = bb->states_[target_pos];\n if (!CanUseResourceInState(target_st, insn->GetResource())) {\n return false;\n }\n PerInsn *pi = GetPerInsn(insn);\n int max_pos = 0;\n \/\/ Check input dependency\n for (auto it : pi->depending_insn_) {\n PerInsn *src_pi = GetPerInsn(it.second);\n if (src_pi->nth_state > max_pos) {\n max_pos = src_pi->nth_state;\n }\n }\n if (max_pos <= target_pos) {\n return true;\n }\n return false;\n}\n\nvoid WireInsn::MoveInsn(IInsn *insn, BB *bb, int target_pos) {\n PerInsn *pi = GetPerInsn(insn);\n IState *src_st = bb->states_[pi->nth_state];\n IState *dst_st = bb->states_[target_pos];\n DesignTool::MoveInsn(insn, src_st, dst_st);\n pi->nth_state = target_pos;\n \/\/ for (IRegister *ireg : insn->inputs_) {\n for (auto it = insn->inputs_.begin(); it != insn->inputs_.end(); ++it) {\n IRegister *ireg = *it;\n IInsn *src_insn = pi->depending_insn_[ireg];\n if (!src_insn) {\n continue;\n }\n PerInsn *src_pi = GetPerInsn(src_insn);\n if (src_pi->nth_state < target_pos) {\n \/\/ This register was an output in previous state,\n \/\/ so the wire is not avaialble.\n continue;\n }\n IRegister *alt_input = src_pi->register_to_wire_[ireg];\n if (alt_input == nullptr && src_pi->is_assign) {\n alt_input = *(src_insn->inputs_.begin());\n }\n if (alt_input != nullptr) {\n *it = alt_input;\n }\n }\n}\n\nbool WireInsn::CanUseResourceInState(IState *st, IResource *resource) {\n for (IInsn *target_insn : st->insns_) {\n if (resource->GetClass()->IsExclusive() &&\n\tresource == target_insn->GetResource()) {\n return false;\n }\n }\n return true;\n}\n\nvoid WireInsn::AddWireToRegisterAssignments() {\n for (IState *st : table_->states_) {\n vector<IInsn *> new_assign_insn;\n for (IInsn *insn : st->insns_) {\n PerInsn *pi = GetPerInsn(insn);\n for (IRegister *maybe_wire : insn->outputs_) {\n\tIRegister *orig_reg = pi->wire_to_register_[maybe_wire];\n\tif (orig_reg) {\n\t const bool used_later = IsUsedLaterInThisBB(insn, orig_reg);\n\t const bool reach_to_other_bb =\n\t pi->output_reach_to_other_bb_.find(orig_reg) !=\n\t pi->output_reach_to_other_bb_.end();\n\t if (used_later || reach_to_other_bb) {\n\t IInsn *assign_insn = new IInsn(assign_);\n\t assign_insn->inputs_.push_back(maybe_wire);\n\t assign_insn->outputs_.push_back(orig_reg);\n\t new_assign_insn.push_back(assign_insn);\n\t }\n\t}\n }\n }\n for (IInsn *insn : new_assign_insn) {\n st->insns_.push_back(insn);\n }\n }\n}\n\nbool WireInsn::IsUsedLaterInThisBB(IInsn *insn, IRegister *output) {\n PerInsn *pi = GetPerInsn(insn);\n map<IRegister *, set<IInsn *> >::iterator it = pi->using_insns_.find(output);\n if (it == pi->using_insns_.end()) {\n return false;\n }\n set<IInsn *> &users = it->second;\n for (IInsn *insn : users) {\n PerInsn *user_pi = GetPerInsn(insn);\n if (user_pi->nth_state > pi->nth_state) {\n return true;\n }\n }\n return false;\n}\n\nWireInsn::PerInsn *WireInsn::GetPerInsn(IInsn *insn) {\n PerInsn *pi = per_insn_map_[insn];\n if (pi == nullptr) {\n pi = new PerInsn;\n per_insn_map_[insn] = pi;\n }\n return pi;\n}\n\n} \/\/ namespace wire\n} \/\/ namespace opt\n} \/\/ namespace iroha\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * Extrae *\n * Instrumentation package for parallel applications *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL: https:\/\/svn.bsc.es\/repos\/ptools\/extrae\/trunk\/src\/others\/papi_best_set.c $\n | @last_commit: $Date: 2011-11-30 11:58:56 +0100 (mié, 30 nov 2011) $\n | @version: $Revision: 890 $\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n#include \"common.h\"\n\nstatic char UNUSED rcsid[] = \"$Id: papi_best_set.c 890 2011-11-30 10:58:56Z harald $\";\n\n#ifdef HAVE_STDIO_H\n# include <stdio.h>\n#endif\n#ifdef HAVE_STDLIB_H\n# include <stdlib.h>\n#endif\n#ifdef HAVE_STRING_H\n# include <string.h>\n#endif\n#ifdef HAVE_ASSERT_H\n# include <assert.h>\n#endif\n\n#include <papi.h>\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include <bitset>\n\nusing namespace std;\n\n#define MAXBITSET 128 \/\/ Increase this if you want to allow more than this value of variable counters\n\nstatic vector<string> omnipresentCounters, Counters;\n\nbool checkCounters (const vector<string> &omnicounters,\n\tconst vector<string> &counters, const bitset<MAXBITSET> &bitmask)\n{\n\tunsigned i;\n\tbool valid = true;\n\tint EventSet = PAPI_NULL;\n\n\tif (PAPI_create_eventset(&EventSet) != PAPI_OK)\n\t\treturn false;\n\n\tfor (i = 0; i < omnicounters.size() && valid; i++)\n\t\tvalid = PAPI_add_named_event (EventSet, (char*)omnicounters[i].c_str()) == PAPI_OK;\n\n\tif (!valid)\n\t{\n\t\tcerr << \"Error! Omnipresent counters cannot be added together!\" << endl;\n\t\texit (-1);\n\t}\n\n\tfor (i = 0; i < counters.size() && valid; i++)\n\t\tif (bitmask.test(i))\n\t\t\tvalid = PAPI_add_named_event (EventSet, (char*)counters[i].c_str()) == PAPI_OK;\n\n\tPAPI_cleanup_eventset (EventSet);\n\tPAPI_destroy_eventset (&EventSet);\n\n\treturn valid;\n}\n\n\/* CheckMaxEventSet\n\n Search the eventset with the maximum events added.\n Uses a bitmask to generate all the possible combinations.\n*\/\nvoid CheckMaxEventSet (unsigned neventset, const vector<string> &omnicounters,\n\tvector<string> &counters)\n{\n\tassert (counters.size() < 63); \/\/ We cannot handle values larger than 64 bits!\n\n\tbitset<MAXBITSET> bitmask (0);\n\tbitset<MAXBITSET> max_value (1ULL << counters.size());\n\tbitset<MAXBITSET> max_combination;\n\n\twhile (bitmask != max_value)\n\t{\n\t\tunsigned bitvalue = bitmask.to_ulong();\n\t\tif (bitmask.count() <= 8-omnicounters.size()) \/* Supported per Extrae *\/\n\t\t\tif (checkCounters (omnicounters, counters, bitmask))\n\t\t\t\tif (bitmask.count() > max_combination.count())\n\t\t\t\t\tmax_combination = bitmask;\n\n\t\t\/* If reached Extrae's limit, stop here *\/\n\t\tif (max_combination.count() == 8-omnicounters.size())\n\t\t\tbreak;\n#if 0\n\t\tstring mystring = bitmask.to_string<char,string::traits_type,string::allocator_type>();\n\t\tcout << \"bits: \" << mystring << endl;\n#endif\n\t\tbitmask = bitvalue+1;\n\t}\n#if 0\n\tstring mystring = max_combination.to_string<char,string::traits_type,string::allocator_type>();\n\tcout << \"max combination bits: \" << mystring << endl;\n#else\n\n\t\/* Show selected counters *\/\n\tcout << \"<!-- counter set \" << neventset << \" -->\" << endl;\n\tcout << \"<set enabled=\\\"yes\\\" domain=\\\"all\\\" changeat-time=\\\"500000us\\\">\" << endl\n\t << \" \";\n\n\tif (omnicounters.size() > 0)\n\t{\n\t\tfor (size_t i = 0; i < omnicounters.size()-1; i++)\n\t\t\tcout << omnicounters[i] << \",\";\n\t\tcout << omnicounters[omnicounters.size()-1];\n\t}\n\t\n\tif (max_combination.count() > 0)\n\t{\n\t\tif (omnicounters.size() > 0)\n\t\t\tcout << \",\";\n\n\t\tbitset<MAXBITSET> max = max_combination;\n\t\tsize_t i = 0;\n\t\twhile (i < max.size() && max.count() > 0)\n\t\t{\n\t\t\tif (max.test(i))\n\t\t\t{\n\t\t\t\tmax.flip (i);\n\t\t\t\tif (max.count() > 0)\n\t\t\t\t\tcout << counters[i] << \",\";\n\t\t\t\telse\n\t\t\t\t\tcout << counters[i];\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\n\t\t\/* Remove already used counters from the counter list *\/\n\t\tmax = max_combination;\n\t\ti = MAXBITSET-1;\n\t\twhile (1)\n\t\t{\n\t\t\tif (max.test(i))\n\t\t\t\tcounters.erase (counters.begin()+i);\n\t\t\tif (i > 0)\n\t\t\t\ti--;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tcout << endl << \"<\/set>\" << endl;\n#endif\n}\n\nvoid addCounters (char *ctr, vector<string> & counters)\n{\n\tstring s_ctr (ctr);\n\n\tsize_t position = s_ctr.find (',');\n\twhile (string::npos != position)\n\t{\n\t\tcounters.push_back (s_ctr.substr (0, position));\n\t\ts_ctr = s_ctr.substr (position+1);\n\t\tposition = s_ctr.find (',');\n\t}\n\tcounters.push_back (s_ctr);\n}\n\nunsigned dumpEventCtrInfo (const char *ctr)\n{\n\tPAPI_event_info_t info;\n\tint Event;\n\tint rc;\n\tchar EventName[PAPI_MAX_STR_LEN];\n\n\trc = PAPI_event_name_to_code ((char*)ctr, &Event);\n\tif (rc != PAPI_OK)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\n\t\/* Get the event name *\/\n\trc = PAPI_event_code_to_name (Event, EventName);\n\tif (rc != PAPI_OK)\n\t\tstrcpy (EventName, \"unknown\");\n\n\t\/* Get event info,\n\t native counters can have info.count == 0 *\/\n\trc = PAPI_get_event_info (Event, &info);\n\tif (rc != PAPI_OK)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\telse if (info.count == 0 && (Event & PAPI_NATIVE_MASK) == 0)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tcout << \"Counter \" << ctr << \" (code \" << std::hex << Event << std::dec << \"): \";\n\t\tif (Event&PAPI_NATIVE_MASK)\n\t\t\tcout << \"native\";\n\t\telse\n\t\t\tcout << \"derived\";\n\t\tif (!(Event&PAPI_NATIVE_MASK))\n\t\t\tcout << \" (depends on \" << info.count << \" native counters)\";\n\t\tcout << endl;\n\t}\n\treturn 1;\n}\n\n\nint main (int argc, char *argv[])\n{\n\tint rc;\n\tint i;\n\tvector<string> omnipresentCounters_tmp, Counters_tmp;\n\n\tif (argc < 2)\n\t{\n\t\tcerr << \"Usage for \" << basename (argv[0]) << endl << endl\n\t\t << \"{omnipresent ctr} ensures that ctr appears in every resulting group\" << endl\n\t\t << \"{omnipresent ctr1,..,ctrN} ensures that ctr1-ctrN appear in every resulting group\" << endl\n\t\t\t << \"ctr requests that ctr appears in 1 resulting group\" << endl\n\t\t\t << \"ctr1,..,ctrN requests that ctr1-ctrN appear in 1 resultign group\" << endl;\n\n\t\treturn -1;\n\t}\n\n\trc = PAPI_library_init(PAPI_VER_CURRENT);\n\tif (rc != PAPI_VER_CURRENT && rc > 0)\n\t{\n\t\tcerr << \"Error: PAPI library version mismatch!\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"This binary was built using PAPI found in \" << PAPI_HOME << endl;\n\n\ti = 1;\n\twhile (i < argc)\n\t{\n\t\tstring param = argv[i];\n\n\t\tif (param == \"omnipresent\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < argc)\n\t\t\t\taddCounters (argv[i], omnipresentCounters_tmp);\n\t\t}\n\t\telse\n\t\t\taddCounters (argv[i], Counters_tmp);\n\n\t\ti++;\n\t}\n\n\tif (omnipresentCounters.size() >= 8)\n\t{\n\t\tcerr << \"Sorry, Extrae is limited to 8 performance counters and you have requested \" << omnipresentCounters.size() << \" omnipresent counters...\" << endl;\n\t\texit (-1);\n\t}\n\n\tvector<string>::iterator it;\n\tunsigned num_events = 0;\n\tcout << endl << \"** Checking the following omnipresent counters:\" << endl;\n\tfor (it = omnipresentCounters_tmp.begin(); it != omnipresentCounters_tmp.end(); it++)\n\t\tif (dumpEventCtrInfo ((*it).c_str()))\n\t\t{\n\t\t\tomnipresentCounters.push_back (*it);\n\t\t\tnum_events++;\n\t\t}\n\tcout << endl << \"** Checking the following counters:\" << endl;\n\tfor (it = Counters_tmp.begin(); it != Counters_tmp.end(); it++)\n\t\tif (dumpEventCtrInfo ((*it).c_str()))\n\t\t{\n\t\t\tCounters.push_back (*it);\n\t\t\tnum_events++;\n\t\t}\n\n\tif (num_events == 0)\n\t{\n\t\tcout << endl <<\n\t\t \"Sorry, no hardware counters were given or the given are not available.\" << endl <<\n\t\t \"Check \" << PAPI_HOME << \"\/bin\/papi_avail or\" << endl <<\n\t\t \" \" << PAPI_HOME << \"\/bin\/papi_native_avail\" << endl <<\n\t\t \"to get a list from the available counters in the system.\" << endl;\n\t\texit (-2);\n\t}\n\telse if (num_events >= 64)\n\t{\n\t\tcerr << endl <<\n\t\t \"Sorry, we cannot handle 64 or more performance counters at this moment.\" << endl;\n\t\texit (-3);\n\t}\n\n\tcout << endl;\n\n\tsize_t ncounters, prevncounters = Counters.size();\n\tunsigned neventset = 1;\n\tdo\n\t{\n\t\tCheckMaxEventSet (neventset++, omnipresentCounters, Counters);\n\t\tncounters = Counters.size();\n\n\t\tif (prevncounters == ncounters && prevncounters > 0)\n\t\t{\n\t\t\tcout << endl <<\n\t\t\t \"Caution, for some reason the following hardware counters cannot be added in an eventset.\" << endl;\n\t\t\tfor (size_t s = 0; s < Counters.size(); s++)\n\t\t\t\tcout << Counters[i] << \" \";\n\t\t\tcout << endl;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tprevncounters = ncounters;\n\n\t} while (Counters.size() > 0);\n\n\treturn 0;\n}\n\n<commit_msg>Fix missing header Fix compilation for PAPI x, where x < 5<commit_after>\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * Extrae *\n * Instrumentation package for parallel applications *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL: https:\/\/svn.bsc.es\/repos\/ptools\/extrae\/trunk\/src\/others\/papi_best_set.c $\n | @last_commit: $Date: 2011-11-30 11:58:56 +0100 (mié, 30 nov 2011) $\n | @version: $Revision: 890 $\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n#include \"common.h\"\n\nstatic char UNUSED rcsid[] = \"$Id: papi_best_set.c 890 2011-11-30 10:58:56Z harald $\";\n\n#ifdef HAVE_STDIO_H\n# include <stdio.h>\n#endif\n#ifdef HAVE_STDLIB_H\n# include <stdlib.h>\n#endif\n#ifdef HAVE_STRING_H\n# include <string.h>\n#endif\n#ifdef HAVE_ASSERT_H\n# include <assert.h>\n#endif\n#ifdef HAVE_LIBGEN_H\n# include <libgen.h>\n#endif\n\n#include <papi.h>\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include <bitset>\n\nusing namespace std;\n\n#define MAXBITSET 128 \/\/ Increase this if you want to allow more than this value of variable counters\n\nstatic vector<string> omnipresentCounters, Counters;\n\n#if PAPI_VERSION_MAJOR(PAPI_VERSION) < 5\n\/* Provide our own PAPI_add_named_event if we're on PAPI pre-5 *\/\nstatic int PAPI_add_named_event (int EventSet, char *counter)\n{\n\tint rc;\n\tint EventCode;\n\n\tif ((rc = PAPI_event_name_to_code (counter, &EventCode)) != PAPI_OK)\n\t\treturn rc;\n\n\treturn PAPI_add_event (EventSet, EventCode);\n}\n#endif\n\nstatic bool checkCounters (const vector<string> &omnicounters,\n\tconst vector<string> &counters, const bitset<MAXBITSET> &bitmask)\n{\n\tunsigned i;\n\tbool valid = true;\n\tint EventSet = PAPI_NULL;\n\n\tif (PAPI_create_eventset(&EventSet) != PAPI_OK)\n\t\treturn false;\n\n\tfor (i = 0; i < omnicounters.size() && valid; i++)\n\t\tvalid = PAPI_add_named_event (EventSet, (char*)omnicounters[i].c_str()) == PAPI_OK;\n\n\tif (!valid)\n\t{\n\t\tcerr << \"Error! Omnipresent counters cannot be added together!\" << endl;\n\t\texit (-1);\n\t}\n\n\tfor (i = 0; i < counters.size() && valid; i++)\n\t\tif (bitmask.test(i))\n\t\t\tvalid = PAPI_add_named_event (EventSet, (char*)counters[i].c_str()) == PAPI_OK;\n\n\tPAPI_cleanup_eventset (EventSet);\n\tPAPI_destroy_eventset (&EventSet);\n\n\treturn valid;\n}\n\n\/* CheckMaxEventSet\n\n Search the eventset with the maximum events added.\n Uses a bitmask to generate all the possible combinations.\n*\/\nstatic void CheckMaxEventSet (unsigned neventset, const vector<string> &omnicounters,\n\tvector<string> &counters)\n{\n\tassert (counters.size() < 63); \/\/ We cannot handle values larger than 64 bits!\n\n\tbitset<MAXBITSET> bitmask (0);\n\tbitset<MAXBITSET> max_value (1ULL << counters.size());\n\tbitset<MAXBITSET> max_combination;\n\n\twhile (bitmask != max_value)\n\t{\n\t\tunsigned bitvalue = bitmask.to_ulong();\n\t\tif (bitmask.count() <= 8-omnicounters.size()) \/* Supported per Extrae *\/\n\t\t\tif (checkCounters (omnicounters, counters, bitmask))\n\t\t\t\tif (bitmask.count() > max_combination.count())\n\t\t\t\t\tmax_combination = bitmask;\n\n\t\t\/* If reached Extrae's limit, stop here *\/\n\t\tif (max_combination.count() == 8-omnicounters.size())\n\t\t\tbreak;\n#if 0\n\t\tstring mystring = bitmask.to_string<char,string::traits_type,string::allocator_type>();\n\t\tcout << \"bits: \" << mystring << endl;\n#endif\n\t\tbitmask = bitvalue+1;\n\t}\n#if 0\n\tstring mystring = max_combination.to_string<char,string::traits_type,string::allocator_type>();\n\tcout << \"max combination bits: \" << mystring << endl;\n#else\n\n\t\/* Show selected counters *\/\n\tcout << \"<!-- counter set \" << neventset << \" -->\" << endl;\n\tcout << \"<set enabled=\\\"yes\\\" domain=\\\"all\\\" changeat-time=\\\"500000us\\\">\" << endl\n\t << \" \";\n\n\tif (omnicounters.size() > 0)\n\t{\n\t\tfor (size_t i = 0; i < omnicounters.size()-1; i++)\n\t\t\tcout << omnicounters[i] << \",\";\n\t\tcout << omnicounters[omnicounters.size()-1];\n\t}\n\t\n\tif (max_combination.count() > 0)\n\t{\n\t\tif (omnicounters.size() > 0)\n\t\t\tcout << \",\";\n\n\t\tbitset<MAXBITSET> max = max_combination;\n\t\tsize_t i = 0;\n\t\twhile (i < max.size() && max.count() > 0)\n\t\t{\n\t\t\tif (max.test(i))\n\t\t\t{\n\t\t\t\tmax.flip (i);\n\t\t\t\tif (max.count() > 0)\n\t\t\t\t\tcout << counters[i] << \",\";\n\t\t\t\telse\n\t\t\t\t\tcout << counters[i];\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\n\t\t\/* Remove already used counters from the counter list *\/\n\t\tmax = max_combination;\n\t\ti = MAXBITSET-1;\n\t\twhile (1)\n\t\t{\n\t\t\tif (max.test(i))\n\t\t\t\tcounters.erase (counters.begin()+i);\n\t\t\tif (i > 0)\n\t\t\t\ti--;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tcout << endl << \"<\/set>\" << endl;\n#endif\n}\n\nstatic void addCounters (char *ctr, vector<string> & counters)\n{\n\tstring s_ctr (ctr);\n\n\tsize_t position = s_ctr.find (',');\n\twhile (string::npos != position)\n\t{\n\t\tcounters.push_back (s_ctr.substr (0, position));\n\t\ts_ctr = s_ctr.substr (position+1);\n\t\tposition = s_ctr.find (',');\n\t}\n\tcounters.push_back (s_ctr);\n}\n\nstatic unsigned dumpEventCtrInfo (const char *ctr)\n{\n\tPAPI_event_info_t info;\n\tint Event;\n\tint rc;\n\tchar EventName[PAPI_MAX_STR_LEN];\n\n\trc = PAPI_event_name_to_code ((char*)ctr, &Event);\n\tif (rc != PAPI_OK)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\n\t\/* Get the event name *\/\n\trc = PAPI_event_code_to_name (Event, EventName);\n\tif (rc != PAPI_OK)\n\t\tstrcpy (EventName, \"unknown\");\n\n\t\/* Get event info,\n\t native counters can have info.count == 0 *\/\n\trc = PAPI_get_event_info (Event, &info);\n\tif (rc != PAPI_OK)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\telse if (info.count == 0 && (Event & PAPI_NATIVE_MASK) == 0)\n\t{\n\t\tcout << \"Warning! Counter '\" << ctr << \"' is not available\" << endl;\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tcout << \"Counter \" << ctr << \" (code \" << std::hex << Event << std::dec << \"): \";\n\t\tif (Event&PAPI_NATIVE_MASK)\n\t\t\tcout << \"native\";\n\t\telse\n\t\t\tcout << \"derived\";\n\t\tif (!(Event&PAPI_NATIVE_MASK))\n\t\t\tcout << \" (depends on \" << info.count << \" native counters)\";\n\t\tcout << endl;\n\t}\n\treturn 1;\n}\n\n\nint main (int argc, char *argv[])\n{\n\tint rc;\n\tint i;\n\tvector<string> omnipresentCounters_tmp, Counters_tmp;\n\n\tif (argc < 2)\n\t{\n\t\tcerr << \"Usage for \" << basename (argv[0]) << endl << endl\n\t\t << \"{omnipresent ctr} ensures that ctr appears in every resulting group\" << endl\n\t\t << \"{omnipresent ctr1,..,ctrN} ensures that ctr1-ctrN appear in every resulting group\" << endl\n\t\t\t << \"ctr requests that ctr appears in 1 resulting group\" << endl\n\t\t\t << \"ctr1,..,ctrN requests that ctr1-ctrN appear in 1 resultign group\" << endl;\n\n\t\treturn -1;\n\t}\n\n\trc = PAPI_library_init(PAPI_VER_CURRENT);\n\tif (rc != PAPI_VER_CURRENT && rc > 0)\n\t{\n\t\tcerr << \"Error: PAPI library version mismatch!\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"This binary was built using PAPI found in \" << PAPI_HOME << endl;\n\n\ti = 1;\n\twhile (i < argc)\n\t{\n\t\tstring param = argv[i];\n\n\t\tif (param == \"omnipresent\")\n\t\t{\n\t\t\ti++;\n\t\t\tif (i < argc)\n\t\t\t\taddCounters (argv[i], omnipresentCounters_tmp);\n\t\t}\n\t\telse\n\t\t\taddCounters (argv[i], Counters_tmp);\n\n\t\ti++;\n\t}\n\n\tif (omnipresentCounters.size() >= 8)\n\t{\n\t\tcerr << \"Sorry, Extrae is limited to 8 performance counters and you have requested \" << omnipresentCounters.size() << \" omnipresent counters...\" << endl;\n\t\texit (-1);\n\t}\n\n\tvector<string>::iterator it;\n\tunsigned num_events = 0;\n\tcout << endl << \"** Checking the following omnipresent counters:\" << endl;\n\tfor (it = omnipresentCounters_tmp.begin(); it != omnipresentCounters_tmp.end(); it++)\n\t\tif (dumpEventCtrInfo ((*it).c_str()))\n\t\t{\n\t\t\tomnipresentCounters.push_back (*it);\n\t\t\tnum_events++;\n\t\t}\n\tcout << endl << \"** Checking the following counters:\" << endl;\n\tfor (it = Counters_tmp.begin(); it != Counters_tmp.end(); it++)\n\t\tif (dumpEventCtrInfo ((*it).c_str()))\n\t\t{\n\t\t\tCounters.push_back (*it);\n\t\t\tnum_events++;\n\t\t}\n\n\tif (num_events == 0)\n\t{\n\t\tcout << endl <<\n\t\t \"Sorry, no hardware counters were given or the given are not available.\" << endl <<\n\t\t \"Check \" << PAPI_HOME << \"\/bin\/papi_avail or\" << endl <<\n\t\t \" \" << PAPI_HOME << \"\/bin\/papi_native_avail\" << endl <<\n\t\t \"to get a list from the available counters in the system.\" << endl;\n\t\texit (-2);\n\t}\n\telse if (num_events >= 64)\n\t{\n\t\tcerr << endl <<\n\t\t \"Sorry, we cannot handle 64 or more performance counters at this moment.\" << endl;\n\t\texit (-3);\n\t}\n\n\tcout << endl;\n\n\tsize_t ncounters, prevncounters = Counters.size();\n\tunsigned neventset = 1;\n\tdo\n\t{\n\t\tCheckMaxEventSet (neventset++, omnipresentCounters, Counters);\n\t\tncounters = Counters.size();\n\n\t\tif (prevncounters == ncounters && prevncounters > 0)\n\t\t{\n\t\t\tcout << endl <<\n\t\t\t \"Caution, for some reason the following hardware counters cannot be added in an eventset.\" << endl;\n\t\t\tfor (size_t s = 0; s < Counters.size(); s++)\n\t\t\t\tcout << Counters[i] << \" \";\n\t\t\tcout << endl;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tprevncounters = ncounters;\n\n\t} while (Counters.size() > 0);\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 Michael Hansen\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE. *\/\n\n#include \"st_string.h\"\n\n#include <cstdlib>\n#include <cstring>\n\nint ST::string::to_int(int base) const noexcept\n{\n return static_cast<int>(strtol(c_str(), nullptr, base));\n}\n\nint ST::string::to_int(ST::conversion_result &result, int base) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n int value = static_cast<int>(strtol(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nunsigned int ST::string::to_uint(int base) const noexcept\n{\n return static_cast<unsigned int>(strtoul(c_str(), nullptr, base));\n}\n\nunsigned int ST::string::to_uint(ST::conversion_result &result, int base)\n const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n unsigned int value = static_cast<unsigned int>(strtoul(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nfloat ST::string::to_float() const noexcept\n{\n return static_cast<float>(strtof(c_str(), nullptr));\n}\n\nfloat ST::string::to_float(ST::conversion_result &result) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n float value = strtof(c_str(), &end);\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\ndouble ST::string::to_double() const noexcept\n{\n return strtod(c_str(), nullptr);\n}\n\ndouble ST::string::to_double(ST::conversion_result &result) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n double value = strtod(c_str(), &end);\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\n#ifdef ST_HAVE_INT64\nint64_t ST::string::to_int64(int base) const noexcept\n{\n return static_cast<int64_t>(strtoll(c_str(), nullptr, base));\n}\n\nint64_t ST::string::to_int64(ST::conversion_result &result, int base)\n const noexcept\n{\n char *end;\n int64_t value = static_cast<int64_t>(strtoll(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags = ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nuint64_t ST::string::to_uint64(int base) const noexcept\n{\n return static_cast<uint64_t>(strtoull(c_str(), nullptr, base));\n}\n\nuint64_t ST::string::to_uint64(ST::conversion_result &result, int base)\n const noexcept\n{\n char *end;\n uint64_t value = static_cast<uint64_t>(strtoull(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags = ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n#endif\n\nstatic int _compare_cs(const char *left, const char *right, size_t fsize) noexcept\n{\n return std::char_traits<char>::compare(left, right, fsize);\n}\n\nstatic int _compare_cs(const char *left, size_t lsize,\n const char *right, size_t rsize) noexcept\n{\n return ST::char_buffer::compare(left, lsize, right, rsize);\n}\n\nstatic int _compare_cs(const char *left, size_t lsize,\n const char *right, size_t rsize, size_t maxlen) noexcept\n{\n return ST::char_buffer::compare(left, lsize, right, rsize, maxlen);\n}\n\nstatic int _compare_ci(const char *left, const char *right, size_t fsize) noexcept\n{\n while (fsize--) {\n const char cl = _ST_PRIVATE::cl_fast_lower(*left++);\n const char cr = _ST_PRIVATE::cl_fast_lower(*right++);\n if (cl != cr)\n return cl - cr;\n }\n return 0;\n}\n\nstatic int _compare_ci(const char *left, size_t lsize,\n const char *right, size_t rsize) noexcept\n{\n const size_t cmplen = std::min(lsize, rsize);\n const int cmp = _compare_ci(left, right, cmplen);\n return cmp ? cmp : lsize - rsize;\n}\n\nstatic int _compare_ci(const char *left, size_t lsize,\n const char *right, size_t rsize, size_t maxlen) noexcept\n{\n lsize = std::min(lsize, maxlen);\n rsize = std::min(rsize, maxlen);\n return _compare_ci(left, lsize, right, rsize);\n}\n\nint ST::string::compare(const string &str, case_sensitivity_t cs) const noexcept\n{\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str.c_str(), str.size())\n : _compare_ci(c_str(), size(), str.c_str(), str.size());\n}\n\nint ST::string::compare(const char *str, case_sensitivity_t cs) const noexcept\n{\n const size_t rsize = str ? std::char_traits<char>::length(str) : 0;\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str ? str : \"\", rsize)\n : _compare_ci(c_str(), size(), str ? str : \"\", rsize);\n}\n\nint ST::string::compare_n(const string &str, size_t count,\n case_sensitivity_t cs) const noexcept\n{\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str.c_str(), str.size(), count)\n : _compare_ci(c_str(), size(), str.c_str(), str.size(), count);\n}\n\nint ST::string::compare_n(const char *str, size_t count,\n case_sensitivity_t cs) const noexcept\n{\n const size_t rsize = str ? std::char_traits<char>::length(str) : 0;\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str ? str : \"\", rsize, count)\n : _compare_ci(c_str(), size(), str ? str : \"\", rsize, count);\n}\n\nconst char *_ST_PRIVATE::find_cs(const char *haystack, const char *needle)\n{\n return strstr(haystack, needle);\n}\n\nconst char *_ST_PRIVATE::find_ci(const char *haystack, const char *needle)\n{\n \/\/ The \"easy\" way\n size_t sublen = std::char_traits<char>::length(needle);\n const char *cp = haystack;\n const char *ep = cp + std::char_traits<char>::length(haystack);\n while (cp + sublen <= ep) {\n if (_compare_ci(cp, needle, sublen) == 0)\n return cp;\n ++cp;\n }\n return nullptr;\n}\n\nconst char *_ST_PRIVATE::find_ci(const char *haystack, size_t size, char ch)\n{\n const char *cp = haystack;\n const char *ep = haystack + size;\n const int lch = _ST_PRIVATE::cl_fast_lower(static_cast<char>(ch));\n while (cp < ep) {\n if (_ST_PRIVATE::cl_fast_lower(*cp) == lch)\n return cp;\n ++cp;\n }\n return nullptr;\n}\n\nST_ssize_t ST::string::find(size_t start, char ch, case_sensitivity_t cs)\n const noexcept\n{\n if (start >= size())\n return -1;\n\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(c_str() + start, size() - start, ch)\n : _ST_PRIVATE::find_ci(c_str() + start, size() - start, ch);\n return cp ? (cp - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find(size_t start, const char *substr, case_sensitivity_t cs)\n const noexcept\n{\n if (!substr || !substr[0] || start >= size())\n return -1;\n\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(c_str() + start, substr)\n : _ST_PRIVATE::find_ci(c_str() + start, substr);\n return cp ? (cp - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find_last(size_t max, char ch, case_sensitivity_t cs) const noexcept\n{\n if (empty())\n return -1;\n\n const char *endp = c_str() + (max > size() ? size() : max);\n\n const char *start = c_str();\n const char *found = nullptr;\n for ( ;; ) {\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(start, endp - start, ch)\n : _ST_PRIVATE::find_ci(start, endp - start, ch);\n if (!cp || cp >= endp)\n break;\n found = cp;\n start = cp + 1;\n }\n return found ? (found - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find_last(size_t max, const char *substr, case_sensitivity_t cs)\n const noexcept\n{\n if (!substr || !substr[0] || empty())\n return -1;\n\n const char *endp = c_str() + (max > size() ? size() : max);\n\n const char *start = c_str();\n const char *found = nullptr;\n for ( ;; ) {\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(start, substr)\n : _ST_PRIVATE::find_ci(start, substr);\n if (!cp || cp >= endp)\n break;\n found = cp;\n start = cp + 1;\n }\n return found ? (found - c_str()) : -1;\n}\n\nbool ST::string::starts_with(const ST::string &prefix, case_sensitivity_t cs) const noexcept\n{\n if (prefix.size() > size())\n return false;\n return compare_n(prefix, prefix.size(), cs) == 0;\n}\n\nbool ST::string::starts_with(const char *prefix, case_sensitivity_t cs) const noexcept\n{\n size_t count = prefix ? std::char_traits<char>::length(prefix) : 0;\n if (count > size())\n return false;\n return compare_n(prefix, count, cs) == 0;\n}\n\nbool ST::string::ends_with(const ST::string &suffix, case_sensitivity_t cs) const noexcept\n{\n if (suffix.size() > size())\n return false;\n\n size_t start = size() - suffix.size();\n return (cs == case_sensitive)\n ? _compare_cs(c_str() + start, suffix.c_str(), suffix.size()) == 0\n : _compare_ci(c_str() + start, suffix.c_str(), suffix.size()) == 0;\n}\n\nbool ST::string::ends_with(const char *suffix, case_sensitivity_t cs) const noexcept\n{\n size_t count = suffix ? std::char_traits<char>::length(suffix) : 0;\n if (count > size())\n return false;\n\n size_t start = size() - count;\n return (cs == case_sensitive)\n ? _compare_cs(c_str() + start, suffix ? suffix : \"\", count) == 0\n : _compare_ci(c_str() + start, suffix ? suffix : \"\", count) == 0;\n}\n\ntemplate <size_t Size>\nstruct _fnv_constants { };\n\ntemplate <>\nstruct _fnv_constants<4>\n{\n static constexpr size_t offset_basis = 0x811c9dc5UL;\n static constexpr size_t prime = 0x01000193UL;\n};\n\ntemplate<>\nstruct _fnv_constants<8>\n{\n static constexpr size_t offset_basis = 0xcbf29ce484222325ULL;\n static constexpr size_t prime = 0x00000100000001b3ULL;\n};\n\ntypedef _fnv_constants<sizeof(size_t)> fnv_constants;\n\nsize_t ST::hash::operator()(const string &str) const noexcept\n{\n \/* FNV-1a hash. See http:\/\/isthe.com\/chongo\/tech\/comp\/fnv\/ for details *\/\n size_t hash = fnv_constants::offset_basis;\n const char *cp = str.c_str();\n const char *ep = cp + str.size();\n while (cp < ep) {\n hash ^= static_cast<size_t>(*cp++);\n hash *= fnv_constants::prime;\n }\n return hash;\n}\n\nsize_t ST::hash_i::operator()(const string &str) const noexcept\n{\n \/* FNV-1a hash. See http:\/\/isthe.com\/chongo\/tech\/comp\/fnv\/ for details *\/\n size_t hash = fnv_constants::offset_basis;\n const char *cp = str.c_str();\n const char *ep = cp + str.size();\n while (cp < ep) {\n hash ^= static_cast<size_t>(_ST_PRIVATE::cl_fast_lower(*cp++));\n hash *= fnv_constants::prime;\n }\n return hash;\n}\n<commit_msg>Avoid -Woverflow warnings when compiling on 32-bit size_t architectures.<commit_after>\/* Copyright (c) 2016 Michael Hansen\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE. *\/\n\n#include \"st_string.h\"\n\n#include <cstdlib>\n#include <cstring>\n\nint ST::string::to_int(int base) const noexcept\n{\n return static_cast<int>(strtol(c_str(), nullptr, base));\n}\n\nint ST::string::to_int(ST::conversion_result &result, int base) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n int value = static_cast<int>(strtol(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nunsigned int ST::string::to_uint(int base) const noexcept\n{\n return static_cast<unsigned int>(strtoul(c_str(), nullptr, base));\n}\n\nunsigned int ST::string::to_uint(ST::conversion_result &result, int base)\n const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n unsigned int value = static_cast<unsigned int>(strtoul(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nfloat ST::string::to_float() const noexcept\n{\n return static_cast<float>(strtof(c_str(), nullptr));\n}\n\nfloat ST::string::to_float(ST::conversion_result &result) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n float value = strtof(c_str(), &end);\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\ndouble ST::string::to_double() const noexcept\n{\n return strtod(c_str(), nullptr);\n}\n\ndouble ST::string::to_double(ST::conversion_result &result) const noexcept\n{\n if (empty()) {\n result.m_flags = ST::conversion_result::result_full_match;\n return 0;\n }\n\n char *end;\n double value = strtod(c_str(), &end);\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags |= ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\n#ifdef ST_HAVE_INT64\nint64_t ST::string::to_int64(int base) const noexcept\n{\n return static_cast<int64_t>(strtoll(c_str(), nullptr, base));\n}\n\nint64_t ST::string::to_int64(ST::conversion_result &result, int base)\n const noexcept\n{\n char *end;\n int64_t value = static_cast<int64_t>(strtoll(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags = ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n\nuint64_t ST::string::to_uint64(int base) const noexcept\n{\n return static_cast<uint64_t>(strtoull(c_str(), nullptr, base));\n}\n\nuint64_t ST::string::to_uint64(ST::conversion_result &result, int base)\n const noexcept\n{\n char *end;\n uint64_t value = static_cast<uint64_t>(strtoull(c_str(), &end, base));\n result.m_flags = 0;\n if (end != c_str())\n result.m_flags = ST::conversion_result::result_ok;\n if (end == c_str() + size())\n result.m_flags |= ST::conversion_result::result_full_match;\n return value;\n}\n#endif\n\nstatic int _compare_cs(const char *left, const char *right, size_t fsize) noexcept\n{\n return std::char_traits<char>::compare(left, right, fsize);\n}\n\nstatic int _compare_cs(const char *left, size_t lsize,\n const char *right, size_t rsize) noexcept\n{\n return ST::char_buffer::compare(left, lsize, right, rsize);\n}\n\nstatic int _compare_cs(const char *left, size_t lsize,\n const char *right, size_t rsize, size_t maxlen) noexcept\n{\n return ST::char_buffer::compare(left, lsize, right, rsize, maxlen);\n}\n\nstatic int _compare_ci(const char *left, const char *right, size_t fsize) noexcept\n{\n while (fsize--) {\n const char cl = _ST_PRIVATE::cl_fast_lower(*left++);\n const char cr = _ST_PRIVATE::cl_fast_lower(*right++);\n if (cl != cr)\n return cl - cr;\n }\n return 0;\n}\n\nstatic int _compare_ci(const char *left, size_t lsize,\n const char *right, size_t rsize) noexcept\n{\n const size_t cmplen = std::min(lsize, rsize);\n const int cmp = _compare_ci(left, right, cmplen);\n return cmp ? cmp : lsize - rsize;\n}\n\nstatic int _compare_ci(const char *left, size_t lsize,\n const char *right, size_t rsize, size_t maxlen) noexcept\n{\n lsize = std::min(lsize, maxlen);\n rsize = std::min(rsize, maxlen);\n return _compare_ci(left, lsize, right, rsize);\n}\n\nint ST::string::compare(const string &str, case_sensitivity_t cs) const noexcept\n{\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str.c_str(), str.size())\n : _compare_ci(c_str(), size(), str.c_str(), str.size());\n}\n\nint ST::string::compare(const char *str, case_sensitivity_t cs) const noexcept\n{\n const size_t rsize = str ? std::char_traits<char>::length(str) : 0;\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str ? str : \"\", rsize)\n : _compare_ci(c_str(), size(), str ? str : \"\", rsize);\n}\n\nint ST::string::compare_n(const string &str, size_t count,\n case_sensitivity_t cs) const noexcept\n{\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str.c_str(), str.size(), count)\n : _compare_ci(c_str(), size(), str.c_str(), str.size(), count);\n}\n\nint ST::string::compare_n(const char *str, size_t count,\n case_sensitivity_t cs) const noexcept\n{\n const size_t rsize = str ? std::char_traits<char>::length(str) : 0;\n return (cs == case_sensitive) ? _compare_cs(c_str(), size(), str ? str : \"\", rsize, count)\n : _compare_ci(c_str(), size(), str ? str : \"\", rsize, count);\n}\n\nconst char *_ST_PRIVATE::find_cs(const char *haystack, const char *needle)\n{\n return strstr(haystack, needle);\n}\n\nconst char *_ST_PRIVATE::find_ci(const char *haystack, const char *needle)\n{\n \/\/ The \"easy\" way\n size_t sublen = std::char_traits<char>::length(needle);\n const char *cp = haystack;\n const char *ep = cp + std::char_traits<char>::length(haystack);\n while (cp + sublen <= ep) {\n if (_compare_ci(cp, needle, sublen) == 0)\n return cp;\n ++cp;\n }\n return nullptr;\n}\n\nconst char *_ST_PRIVATE::find_ci(const char *haystack, size_t size, char ch)\n{\n const char *cp = haystack;\n const char *ep = haystack + size;\n const int lch = _ST_PRIVATE::cl_fast_lower(static_cast<char>(ch));\n while (cp < ep) {\n if (_ST_PRIVATE::cl_fast_lower(*cp) == lch)\n return cp;\n ++cp;\n }\n return nullptr;\n}\n\nST_ssize_t ST::string::find(size_t start, char ch, case_sensitivity_t cs)\n const noexcept\n{\n if (start >= size())\n return -1;\n\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(c_str() + start, size() - start, ch)\n : _ST_PRIVATE::find_ci(c_str() + start, size() - start, ch);\n return cp ? (cp - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find(size_t start, const char *substr, case_sensitivity_t cs)\n const noexcept\n{\n if (!substr || !substr[0] || start >= size())\n return -1;\n\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(c_str() + start, substr)\n : _ST_PRIVATE::find_ci(c_str() + start, substr);\n return cp ? (cp - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find_last(size_t max, char ch, case_sensitivity_t cs) const noexcept\n{\n if (empty())\n return -1;\n\n const char *endp = c_str() + (max > size() ? size() : max);\n\n const char *start = c_str();\n const char *found = nullptr;\n for ( ;; ) {\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(start, endp - start, ch)\n : _ST_PRIVATE::find_ci(start, endp - start, ch);\n if (!cp || cp >= endp)\n break;\n found = cp;\n start = cp + 1;\n }\n return found ? (found - c_str()) : -1;\n}\n\nST_ssize_t ST::string::find_last(size_t max, const char *substr, case_sensitivity_t cs)\n const noexcept\n{\n if (!substr || !substr[0] || empty())\n return -1;\n\n const char *endp = c_str() + (max > size() ? size() : max);\n\n const char *start = c_str();\n const char *found = nullptr;\n for ( ;; ) {\n const char *cp = (cs == case_sensitive)\n ? _ST_PRIVATE::find_cs(start, substr)\n : _ST_PRIVATE::find_ci(start, substr);\n if (!cp || cp >= endp)\n break;\n found = cp;\n start = cp + 1;\n }\n return found ? (found - c_str()) : -1;\n}\n\nbool ST::string::starts_with(const ST::string &prefix, case_sensitivity_t cs) const noexcept\n{\n if (prefix.size() > size())\n return false;\n return compare_n(prefix, prefix.size(), cs) == 0;\n}\n\nbool ST::string::starts_with(const char *prefix, case_sensitivity_t cs) const noexcept\n{\n size_t count = prefix ? std::char_traits<char>::length(prefix) : 0;\n if (count > size())\n return false;\n return compare_n(prefix, count, cs) == 0;\n}\n\nbool ST::string::ends_with(const ST::string &suffix, case_sensitivity_t cs) const noexcept\n{\n if (suffix.size() > size())\n return false;\n\n size_t start = size() - suffix.size();\n return (cs == case_sensitive)\n ? _compare_cs(c_str() + start, suffix.c_str(), suffix.size()) == 0\n : _compare_ci(c_str() + start, suffix.c_str(), suffix.size()) == 0;\n}\n\nbool ST::string::ends_with(const char *suffix, case_sensitivity_t cs) const noexcept\n{\n size_t count = suffix ? std::char_traits<char>::length(suffix) : 0;\n if (count > size())\n return false;\n\n size_t start = size() - count;\n return (cs == case_sensitive)\n ? _compare_cs(c_str() + start, suffix ? suffix : \"\", count) == 0\n : _compare_ci(c_str() + start, suffix ? suffix : \"\", count) == 0;\n}\n\ntemplate <typename SizeType, size_t Size = sizeof(SizeType)>\nstruct _fnv_constants { };\n\ntemplate <typename SizeType>\nstruct _fnv_constants<SizeType, 4>\n{\n static constexpr SizeType offset_basis = 0x811c9dc5UL;\n static constexpr SizeType prime = 0x01000193UL;\n};\n\ntemplate <typename SizeType>\nstruct _fnv_constants<SizeType, 8>\n{\n static constexpr SizeType offset_basis = 0xcbf29ce484222325ULL;\n static constexpr SizeType prime = 0x00000100000001b3ULL;\n};\n\ntypedef _fnv_constants<size_t> fnv_constants;\n\nsize_t ST::hash::operator()(const string &str) const noexcept\n{\n \/* FNV-1a hash. See http:\/\/isthe.com\/chongo\/tech\/comp\/fnv\/ for details *\/\n size_t hash = fnv_constants::offset_basis;\n const char *cp = str.c_str();\n const char *ep = cp + str.size();\n while (cp < ep) {\n hash ^= static_cast<size_t>(*cp++);\n hash *= fnv_constants::prime;\n }\n return hash;\n}\n\nsize_t ST::hash_i::operator()(const string &str) const noexcept\n{\n \/* FNV-1a hash. See http:\/\/isthe.com\/chongo\/tech\/comp\/fnv\/ for details *\/\n size_t hash = fnv_constants::offset_basis;\n const char *cp = str.c_str();\n const char *ep = cp + str.size();\n while (cp < ep) {\n hash ^= static_cast<size_t>(_ST_PRIVATE::cl_fast_lower(*cp++));\n hash *= fnv_constants::prime;\n }\n return hash;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) Associated Universities Inc., 2002 *\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*\n* \"@(#) $Id: contLogTestImpl.cpp,v 1.12 2008\/01\/30 11:08:07 eallaert Exp $\"\n*\n* who when what\n* -------- ---------- ----------------------------------------------\n* eallaert 2007-11-05 initial version\n*\n*\/\n \n#include <contLogTestImpl.h>\n#include <ACSErrTypeCommon.h>\n#include <loggingLogLevelDefinition.h>\n#include <loggingLogger.h>\n#include \"loggingGetLogger.h\"\n#include <iostream>\n\nACE_RCSID(contLogTest, contLogTestImpl, \"$Id: contLogTestImpl.cpp,v 1.12 2008\/01\/30 11:08:07 eallaert Exp $\")\n\n\/* ----------------------------------------------------------------*\/\nTestLogLevelsComp::TestLogLevelsComp( \n\t\t const ACE_CString &name,\n\t\t maci::ContainerServices * containerServices) :\n ACSComponentImpl(name, containerServices)\n{\n \/\/ ACS_TRACE is used for debugging purposes\n ACS_TRACE(\"::TestLogLevelsComp::TestLogLevelsComp\");\n}\n\/* ----------------------------------------------------------------*\/\nTestLogLevelsComp::~TestLogLevelsComp()\n{\n \/\/ ACS_TRACE is used for debugging purposes\n ACS_TRACE(\"::TestLogLevelsComp::~TestLogLevelsComp\");\n ACS_DEBUG_PARAM(\"::TestLogLevelsComp::~TestLogLevelsComp\", \"Destroying %s...\", name());\n}\n\/* --------------------- [ CORBA interface ] ----------------------*\/\n::contLogTest::LongSeq*\nTestLogLevelsComp::getLevels ()\n throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)\n{\n Logging::Logger *l = getLogger();\n ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);\n\tlevel->length(5);\n\n \/\/ need a way to retrieve default\/hardcoded settings, i.e. the\n \/\/ equivalent of Java's logConfig.getMinLogLevel() etc. in C++.\n\t\/\/ Hardcode these values for the time being ;-)\n\tlevel[0] = static_cast< CORBA::Long >(2);\n\tlevel[1] = static_cast< CORBA::Long >(2);\n\t\n level[3] = static_cast< CORBA::Long >(LogLevelDefinition::fromACEPriority(ACE_Log_Priority(l->getRemoteLevel())));\n level[4] = static_cast< CORBA::Long >(LogLevelDefinition::fromACEPriority(ACE_Log_Priority(l->getLocalLevel())));\n \n level[2] = (level[3] < level[4] ? level[3] : level[4]);\n\n return level._retn();\n}\n\nvoid \nTestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)\n{\n\tACE_Log_Priority p;\n\tCORBA::ULong t=0;\n\tfor (t=0; t<levels.length(); t++){\n\t\tp = LogLevelDefinition::getACELogPriority(levels[t]);\n\t\tLogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]);\n\t\tACS_SHORT_LOG((p, \"dummy log message for core level %d\/%s\", lld.getValue(), lld.getName().c_str()));\n\t}\n\t\/\/ log last message always at highest, non-OFF level (so it should get always through,\n\t\/\/ unless the central level is put to OFF).\n\tp = LogLevelDefinition::getACELogPriority(AcsLogLevels::EMERGENCY_VAL);\n\tACS_SHORT_LOG((p, \"===last log message===\"));\n\n\t\/\/ Note that these tests may be running in a container with default\n\t\/\/ settings, i.e. whereby \" immediateDispatchLevel\" can be anything,\n\t\/\/ and dispatchPacketSize as well. Empirically, in such case, \n\t\/\/ C++ seems to sends logs in packets of 5 logs, so add 4 messages to\n\t\/\/ ensure all the above logs get sent across right now.\n\tfor (int i = 0; i < 4; i++) {\n\t\tACS_SHORT_LOG((p, \"===packet fill-up message===\"));\n\t}\n \n\t\n}\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n#include <maciACSComponentDefines.h>\nMACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)\n\/* ----------------------------------------------------------------*\/\n\n\n\/*___oOo___*\/\n\n\n\n<commit_msg>Sleep 250 ms before starting to send logs.<commit_after>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) Associated Universities Inc., 2002 *\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*\n* \"@(#) $Id: contLogTestImpl.cpp,v 1.13 2008\/06\/24 13:45:46 eallaert Exp $\"\n*\n* who when what\n* -------- ---------- ----------------------------------------------\n* eallaert 2007-11-05 initial version\n*\n*\/\n \n#include <contLogTestImpl.h>\n#include <ACSErrTypeCommon.h>\n#include <loggingLogLevelDefinition.h>\n#include <loggingLogger.h>\n#include \"loggingGetLogger.h\"\n#include <iostream>\n\nACE_RCSID(contLogTest, contLogTestImpl, \"$Id: contLogTestImpl.cpp,v 1.13 2008\/06\/24 13:45:46 eallaert Exp $\")\n\n\/* ----------------------------------------------------------------*\/\nTestLogLevelsComp::TestLogLevelsComp( \n\t\t const ACE_CString &name,\n\t\t maci::ContainerServices * containerServices) :\n ACSComponentImpl(name, containerServices)\n{\n \/\/ ACS_TRACE is used for debugging purposes\n ACS_TRACE(\"::TestLogLevelsComp::TestLogLevelsComp\");\n}\n\/* ----------------------------------------------------------------*\/\nTestLogLevelsComp::~TestLogLevelsComp()\n{\n \/\/ ACS_TRACE is used for debugging purposes\n ACS_TRACE(\"::TestLogLevelsComp::~TestLogLevelsComp\");\n ACS_DEBUG_PARAM(\"::TestLogLevelsComp::~TestLogLevelsComp\", \"Destroying %s...\", name());\n}\n\/* --------------------- [ CORBA interface ] ----------------------*\/\n::contLogTest::LongSeq*\nTestLogLevelsComp::getLevels ()\n throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)\n{\n Logging::Logger *l = getLogger();\n ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);\n\tlevel->length(5);\n\n \/\/ need a way to retrieve default\/hardcoded settings, i.e. the\n \/\/ equivalent of Java's logConfig.getMinLogLevel() etc. in C++.\n\t\/\/ Hardcode these values for the time being ;-)\n\tlevel[0] = static_cast< CORBA::Long >(2);\n\tlevel[1] = static_cast< CORBA::Long >(2);\n\t\n level[3] = static_cast< CORBA::Long >(LogLevelDefinition::fromACEPriority(ACE_Log_Priority(l->getRemoteLevel())));\n level[4] = static_cast< CORBA::Long >(LogLevelDefinition::fromACEPriority(ACE_Log_Priority(l->getLocalLevel())));\n \n level[2] = (level[3] < level[4] ? level[3] : level[4]);\n\n return level._retn();\n}\n\nvoid \nTestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)\n{\n\tACE_Log_Priority p;\n\tCORBA::ULong t=0;\n\t\/\/ Give client time to start waiting for logs\n\tusleep(250000);\n\tfor (t=0; t<levels.length(); t++){\n\t\tp = LogLevelDefinition::getACELogPriority(levels[t]);\n\t\tLogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]);\n\t\tACS_SHORT_LOG((p, \"dummy log message for core level %d\/%s\", lld.getValue(), lld.getName().c_str()));\n\t}\n\t\/\/ log last message always at highest, non-OFF level (so it should get always through,\n\t\/\/ unless the central level is put to OFF).\n\tp = LogLevelDefinition::getACELogPriority(AcsLogLevels::EMERGENCY_VAL);\n\tACS_SHORT_LOG((p, \"===last log message===\"));\n\n\t\/\/ Note that these tests may be running in a container with default\n\t\/\/ settings, i.e. whereby \" immediateDispatchLevel\" can be anything,\n\t\/\/ and dispatchPacketSize as well. Empirically, in such case, \n\t\/\/ C++ seems to sends logs in packets of 5 logs, so add 4 messages to\n\t\/\/ ensure all the above logs get sent across right now.\n\tfor (int i = 0; i < 4; i++) {\n\t\tACS_SHORT_LOG((p, \"===packet fill-up message===\"));\n\t}\n \n\t\n}\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n#include <maciACSComponentDefines.h>\nMACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)\n\/* ----------------------------------------------------------------*\/\n\n\n\/*___oOo___*\/\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s\ntemplate<typename T> struct Identity {\n typedef T Type;\n};\n\nvoid f(Identity<int>::Type a) {}\nvoid f(Identity<int> a) {}\nvoid f(int& a) { }\n\ntemplate<typename T> struct A {\n A<T> *next;\n};\nvoid f(A<int>) { }\n\nstruct B { };\n\nvoid f() {\n int B::*a = 0;\n void (B::*b)() = 0;\n}\n\nnamespace EmptyNameCrash {\n struct A { A(); };\n typedef struct { A x; } B;\n B x;\n}\n\n\/\/ PR4890\nnamespace PR4890 {\n struct X {\n ~X();\n };\n\n X::~X() { }\n}\n\nnamespace VirtualDtor {\n struct Y {\n virtual ~Y();\n };\n \n Y::~Y() { }\n}\n\nnamespace VirtualBase {\n struct A { };\n struct B : virtual A { };\n\n void f() {\n B b;\n }\n}\n\nvoid foo() {\n const wchar_t c = L'x';\n wchar_t d = c;\n}\n\nnamespace b5249287 {\ntemplate <typename T> class A {\n struct B;\n};\n\nclass Cls {\n template <typename T> friend class A<T>::B;\n};\n\nCls obj;\n}\n\nnamespace pr14763 {\nstruct foo {\n foo(const foo&);\n};\n\nfoo func(foo f) {\n return f; \/\/ reference 'f' for now because otherwise we hit another bug\n}\n\n\/\/ CHECK: [[FUNC:![0-9]*]] = {{.*}} metadata !\"_ZN7pr147634funcENS_3fooE\", i32 {{[0-9]*}}, metadata [[FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]\n\/\/ CHECK: [[PR14763:![0-9]*]] = {{.*}} ; [ DW_TAG_namespace ] [pr14763]\n\/\/ CHECK: [[FOO:![0-9]*]] = metadata !{i32 {{[0-9]*}}, metadata !{{[0-9]*}}, metadata [[PR14763]], {{.*}} ; [ DW_TAG_structure_type ] [foo]\n}\n\nnamespace pr9608 { \/\/ also pr9600\nstruct incomplete;\nincomplete (*x)[3];\n\/\/ CHECK: metadata [[INCARRAYPTR:![0-9]*]], i32 0, i32 1, [3 x i8]** @_ZN6pr96081xE, null} ; [ DW_TAG_variable ] [x]\n\/\/ CHECK: [[INCARRAYPTR]] = {{.*}}metadata [[INCARRAY:![0-9]*]]} ; [ DW_TAG_pointer_type ]\n\/\/ CHECK: [[INCARRAY]] = {{.*}}metadata [[INCTYPE:![0-9]*]], metadata {{![0-9]*}}, i32 0, i32 0} ; [ DW_TAG_array_type ] [line 0, size 0, align 0, offset 0] [from incomplete]\n\/\/ CHECK: [[INCTYPE]] = {{.*}} ; [ DW_TAG_structure_type ] [incomplete]{{.*}} [fwd]\n}\n\n\/\/ For some reason the argument for PR14763 ended up all the way down here\n\/\/ CHECK: = metadata !{i32 {{[0-9]*}}, metadata [[FUNC]], {{.*}}, metadata [[FOO]], i32 8192, i32 0} ; [ DW_TAG_arg_variable ] [f]\n\nnamespace pr16214 {\nstruct a {\n int i;\n};\n\ntypedef a at;\n\nstruct b {\n};\n\ntypedef b bt;\n\nvoid func() {\n at a_inst;\n bt *b_ptr_inst;\n const bt *b_cnst_ptr_inst;\n}\n\n\/\/ CHECK: metadata [[A_MEM:![0-9]*]], i32 0, null, null} ; [ DW_TAG_structure_type ] [a]\n\/\/ CHECK: [[A_MEM]] = metadata !{metadata [[A_I:![0-9]*]], metadata !{{[0-9]*}}}\n\/\/ CHECK: [[A_I]] = {{.*}} ; [ DW_TAG_member ] [i] {{.*}} [from int]\n\/\/ CHECK: ; [ DW_TAG_structure_type ] [b] {{.*}}[fwd]\n}\n<commit_msg>Fix CodeGenCXX\/debug-info.cpp test on Windows<commit_after>\/\/ RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s\ntemplate<typename T> struct Identity {\n typedef T Type;\n};\n\nvoid f(Identity<int>::Type a) {}\nvoid f(Identity<int> a) {}\nvoid f(int& a) { }\n\ntemplate<typename T> struct A {\n A<T> *next;\n};\nvoid f(A<int>) { }\n\nstruct B { };\n\nvoid f() {\n int B::*a = 0;\n void (B::*b)() = 0;\n}\n\nnamespace EmptyNameCrash {\n struct A { A(); };\n typedef struct { A x; } B;\n B x;\n}\n\n\/\/ PR4890\nnamespace PR4890 {\n struct X {\n ~X();\n };\n\n X::~X() { }\n}\n\nnamespace VirtualDtor {\n struct Y {\n virtual ~Y();\n };\n \n Y::~Y() { }\n}\n\nnamespace VirtualBase {\n struct A { };\n struct B : virtual A { };\n\n void f() {\n B b;\n }\n}\n\nvoid foo() {\n const wchar_t c = L'x';\n wchar_t d = c;\n}\n\nnamespace b5249287 {\ntemplate <typename T> class A {\n struct B;\n};\n\nclass Cls {\n template <typename T> friend class A<T>::B;\n};\n\nCls obj;\n}\n\nnamespace pr14763 {\nstruct foo {\n foo(const foo&);\n};\n\nfoo func(foo f) {\n return f; \/\/ reference 'f' for now because otherwise we hit another bug\n}\n\n\/\/ CHECK: [[FUNC:![0-9]*]] = {{.*}} metadata !\"_ZN7pr147634funcENS_3fooE\", i32 {{[0-9]*}}, metadata [[FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]\n\/\/ CHECK: [[PR14763:![0-9]*]] = {{.*}} ; [ DW_TAG_namespace ] [pr14763]\n\/\/ CHECK: [[FOO:![0-9]*]] = metadata !{i32 {{[0-9]*}}, metadata !{{[0-9]*}}, metadata [[PR14763]], {{.*}} ; [ DW_TAG_structure_type ] [foo]\n}\n\nnamespace pr9608 { \/\/ also pr9600\nstruct incomplete;\nincomplete (*x)[3];\n\/\/ CHECK: metadata [[INCARRAYPTR:![0-9]*]], i32 0, i32 1, [3 x i8]** @_ZN6pr96081xE, null} ; [ DW_TAG_variable ] [x]\n\/\/ CHECK: [[INCARRAYPTR]] = {{.*}}metadata [[INCARRAY:![0-9]*]]} ; [ DW_TAG_pointer_type ]\n\/\/ CHECK: [[INCARRAY]] = {{.*}}metadata [[INCTYPE:![0-9]*]], metadata {{![0-9]*}}, i32 0, i32 0} ; [ DW_TAG_array_type ] [line 0, size 0, align 0, offset 0] [from incomplete]\n\/\/ CHECK: [[INCTYPE]] = {{.*}} ; [ DW_TAG_structure_type ] [incomplete]{{.*}} [fwd]\n}\n\n\/\/ For some reason the argument for PR14763 ended up all the way down here\n\/\/ CHECK: = metadata !{i32 {{[0-9]*}}, metadata [[FUNC]], {{.*}}, metadata [[FOO]], i32 {{[0-9]+}}, i32 0} ; [ DW_TAG_arg_variable ] [f]\n\nnamespace pr16214 {\nstruct a {\n int i;\n};\n\ntypedef a at;\n\nstruct b {\n};\n\ntypedef b bt;\n\nvoid func() {\n at a_inst;\n bt *b_ptr_inst;\n const bt *b_cnst_ptr_inst;\n}\n\n\/\/ CHECK: metadata [[A_MEM:![0-9]*]], i32 0, null, null} ; [ DW_TAG_structure_type ] [a]\n\/\/ CHECK: [[A_MEM]] = metadata !{metadata [[A_I:![0-9]*]], metadata !{{[0-9]*}}}\n\/\/ CHECK: [[A_I]] = {{.*}} ; [ DW_TAG_member ] [i] {{.*}} [from int]\n\/\/ CHECK: ; [ DW_TAG_structure_type ] [b] {{.*}}[fwd]\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sequence\/Tools.hpp>\n\n#include <cassert>\n\n#include <algorithm>\n\n#include <sequence\/details\/StringUtils.hpp>\n\nnamespace sequence {\n\nnamespace {\n\nbool containsPatternCharacter(CStringView str) { return str.contains('#'); }\n\nvoid replaceAll(std::string &subject, const std::string &search,\n const std::string &replace) {\n size_t pos = 0;\n while ((pos = subject.find(search, pos)) != std::string::npos) {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n}\n\n} \/\/ namespace\n\nstd::string createPattern(CStringView prefix, CStringView suffix,\n unsigned char padding) {\n if (padding > MAX_PADDING) {\n throw std::domain_error(\"padding should be <= MAX_PADDING\");\n }\n if (padding == 0) {\n padding = 1;\n }\n std::array<char, MAX_PADDING> buffer;\n std::fill(buffer.begin(), buffer.end(), PADDING_CHAR);\n return concat(prefix, CStringView(buffer.cbegin(), padding), suffix);\n}\n\nstd::pair<CStringView, CStringView> getPrefixAndSuffix(CStringView pattern) {\n const auto first = pattern.indexOf(PADDING_CHAR);\n if (first == CStringView::npos) {\n throw std::invalid_argument(\"no padding character found in pattern\");\n }\n const auto last = pattern.lastIndexOf(PADDING_CHAR);\n assert(last != CStringView::npos);\n const CStringView padding = pattern.substr(first, last - first + 1);\n if (std::any_of(padding.begin(), padding.end(),\n [](char c) { return c != PADDING_CHAR; })) {\n throw std::invalid_argument(\"multiple padding found in pattern\");\n }\n if (padding.size() > MAX_PADDING) {\n throw std::invalid_argument(\"padding too large found in pattern\");\n }\n return {pattern.substr(0, first), pattern.substr(last + 1)};\n}\n\nunsigned getPadding(CStringView pattern) {\n const auto pair = getPrefixAndSuffix(pattern);\n return pattern.size() - pair.first.size() - pair.second.size();\n}\n\nItem createSingleFile(CStringView filename) {\n if (containsPatternCharacter(filename))\n return {};\n return Item{filename.toString()};\n}\n\nItem createSequence(CStringView pattern, Index start, Index end,\n unsigned char step) {\n if (step == 0)\n return {};\n if (end < start)\n return {};\n Item item(pattern);\n item.padding = getPadding(pattern);\n item.step = step;\n item.start = start;\n item.end = end;\n return item;\n}\n\nItem createSequence(CStringView pattern, Indices indices) {\n return Item(pattern, std::move(indices));\n}\n\nstd::regex getMatcher(CStringView pattern, bool ignoreCase) {\n auto flags = std::regex_constants::ECMAScript;\n if (ignoreCase)\n flags |= std::regex_constants::icase;\n return std::regex(details::getMatcherString(pattern.toString()), flags);\n}\n\nbool match(const std::regex &matcher, const Item &candidate) {\n return std::regex_match(candidate.filename, matcher);\n}\n\nnamespace details {\nstd::string getMatcherString(std::string pattern) {\n if (pattern.empty())\n throw std::invalid_argument(\"empty pattern\");\n \/\/ replacing @ by #\n std::replace(pattern.begin(), pattern.end(), '@', '#');\n const auto padding = std::count(pattern.begin(), pattern.end(), '#');\n if (padding == 0)\n throw std::invalid_argument(\n \"pattern should contain a padding character '#' or '@'\");\n replaceAll(pattern, \".\", \"\\\\.\");\n replaceAll(pattern, \"*\", \".*\");\n if (padding == 1)\n replaceAll(pattern, \"#\", \"#+\");\n return pattern;\n}\n\n} \/\/ namespace details\n} \/\/ namespace sequence\n<commit_msg>Allow creating single file containing padding char<commit_after>#include <sequence\/Tools.hpp>\n\n#include <cassert>\n\n#include <algorithm>\n\n#include <sequence\/details\/StringUtils.hpp>\n\nnamespace sequence {\n\nnamespace {\n\nvoid replaceAll(std::string &subject, const std::string &search,\n const std::string &replace) {\n size_t pos = 0;\n while ((pos = subject.find(search, pos)) != std::string::npos) {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n}\n\n} \/\/ namespace\n\nstd::string createPattern(CStringView prefix, CStringView suffix,\n unsigned char padding) {\n if (padding > MAX_PADDING) {\n throw std::domain_error(\"padding should be <= MAX_PADDING\");\n }\n if (padding == 0) {\n padding = 1;\n }\n std::array<char, MAX_PADDING> buffer;\n std::fill(buffer.begin(), buffer.end(), PADDING_CHAR);\n return concat(prefix, CStringView(buffer.cbegin(), padding), suffix);\n}\n\nstd::pair<CStringView, CStringView> getPrefixAndSuffix(CStringView pattern) {\n const auto first = pattern.indexOf(PADDING_CHAR);\n if (first == CStringView::npos) {\n throw std::invalid_argument(\"no padding character found in pattern\");\n }\n const auto last = pattern.lastIndexOf(PADDING_CHAR);\n assert(last != CStringView::npos);\n const CStringView padding = pattern.substr(first, last - first + 1);\n if (std::any_of(padding.begin(), padding.end(),\n [](char c) { return c != PADDING_CHAR; })) {\n throw std::invalid_argument(\"multiple padding found in pattern\");\n }\n if (padding.size() > MAX_PADDING) {\n throw std::invalid_argument(\"padding too large found in pattern\");\n }\n return {pattern.substr(0, first), pattern.substr(last + 1)};\n}\n\nunsigned getPadding(CStringView pattern) {\n const auto pair = getPrefixAndSuffix(pattern);\n return pattern.size() - pair.first.size() - pair.second.size();\n}\n\nItem createSingleFile(CStringView filename) {\n return Item{filename.toString()};\n}\n\nItem createSequence(CStringView pattern, Index start, Index end,\n unsigned char step) {\n if (step == 0)\n return {};\n if (end < start)\n return {};\n Item item(pattern);\n item.padding = getPadding(pattern);\n item.step = step;\n item.start = start;\n item.end = end;\n return item;\n}\n\nItem createSequence(CStringView pattern, Indices indices) {\n return Item(pattern, std::move(indices));\n}\n\nstd::regex getMatcher(CStringView pattern, bool ignoreCase) {\n auto flags = std::regex_constants::ECMAScript;\n if (ignoreCase)\n flags |= std::regex_constants::icase;\n return std::regex(details::getMatcherString(pattern.toString()), flags);\n}\n\nbool match(const std::regex &matcher, const Item &candidate) {\n return std::regex_match(candidate.filename, matcher);\n}\n\nnamespace details {\nstd::string getMatcherString(std::string pattern) {\n if (pattern.empty())\n throw std::invalid_argument(\"empty pattern\");\n \/\/ replacing @ by #\n std::replace(pattern.begin(), pattern.end(), '@', '#');\n const auto padding = std::count(pattern.begin(), pattern.end(), '#');\n if (padding == 0)\n throw std::invalid_argument(\n \"pattern should contain a padding character '#' or '@'\");\n replaceAll(pattern, \".\", \"\\\\.\");\n replaceAll(pattern, \"*\", \".*\");\n if (padding == 1)\n replaceAll(pattern, \"#\", \"#+\");\n return pattern;\n}\n\n} \/\/ namespace details\n} \/\/ namespace sequence\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n\n#include \"Utils.h\"\n\n#if defined(__APPLE__)\n#\tinclude <sys\/select.h>\n#\tinclude <sys\/time.h>\n#\tinclude <sys\/types.h>\n#\tinclude <sys\/select.h>\n#\tinclude <unistd.h>\n#\tinclude <termios.h>\n#else\n#\tinclude <conio.h>\n#endif\n\nstd::vector<uint8_t> ReadFileAsVector( const char* FileName )\n{\n\tstd::ifstream File( FileName, std::ifstream::binary );\n\n\tFile.seekg( 0, std::ios::end );\n\tstd::streampos End = File.tellg();\n\tFile.seekg( 0, std::ios::beg );\n\tstd::streampos Start = File.tellg();\n\tsize_t Size = static_cast<size_t>( End - Start );\n\n\tstd::vector<uint8_t> Result( Size );\n\n\tFile.read( reinterpret_cast<char*>( Result.data() ), Size );\n\n\treturn Result;\n}\n\nstd::shared_ptr<clBlob> ReadFileAsBlob( const char* FileName )\n{\n\treturn std::make_shared<clBlob>( ReadFileAsVector( FileName ) );\n}\n\nint IsKeyPressed()\n{\n#if defined(_WIN32)\n\treturn _kbhit();\n#elif defined(__APPLE__)\n\tstruct termios ttystate;\n \ttcgetattr( STDIN_FILENO, &ttystate );\n\tttystate.c_lflag &= ~ICANON;\n\tttystate.c_cc[VMIN] = 1;\n\ttcsetattr( STDIN_FILENO, TCSANOW, &ttystate );\n\n\tfd_set fds;\n\tFD_ZERO( &fds );\n\tFD_SET( STDIN_FILENO, &fds );\n\tstruct timeval tv = { 0L, 0L };\n\t(void)select( STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv );\n\tbool HasKey = FD_ISSET( STDIN_FILENO, &fds );\n\treturn HasKey ? fgetc( stdin ) : 0;\n#else\n\treturn kbhit();\n#endif\n}\n<commit_msg>IsKeyPressed() eats keys<commit_after>#include <fstream>\n\n#include \"Utils.h\"\n\n#if defined(__APPLE__)\n#\tinclude <sys\/select.h>\n#\tinclude <sys\/time.h>\n#\tinclude <sys\/types.h>\n#\tinclude <sys\/select.h>\n#\tinclude <unistd.h>\n#\tinclude <termios.h>\n#else\n#\tinclude <conio.h>\n#endif\n\nstd::vector<uint8_t> ReadFileAsVector( const char* FileName )\n{\n\tstd::ifstream File( FileName, std::ifstream::binary );\n\n\tFile.seekg( 0, std::ios::end );\n\tstd::streampos End = File.tellg();\n\tFile.seekg( 0, std::ios::beg );\n\tstd::streampos Start = File.tellg();\n\tsize_t Size = static_cast<size_t>( End - Start );\n\n\tstd::vector<uint8_t> Result( Size );\n\n\tFile.read( reinterpret_cast<char*>( Result.data() ), Size );\n\n\treturn Result;\n}\n\nstd::shared_ptr<clBlob> ReadFileAsBlob( const char* FileName )\n{\n\treturn std::make_shared<clBlob>( ReadFileAsVector( FileName ) );\n}\n\nint IsKeyPressed()\n{\n#if defined(_WIN32)\n\tbool Res = _kbhit();\n\twhile (_kbhit()) getch();\n\treturn Res;\n#elif defined(__APPLE__)\n\tstruct termios ttystate;\n \ttcgetattr( STDIN_FILENO, &ttystate );\n\tttystate.c_lflag &= ~ICANON;\n\tttystate.c_cc[VMIN] = 1;\n\ttcsetattr( STDIN_FILENO, TCSANOW, &ttystate );\n\n\tfd_set fds;\n\tFD_ZERO( &fds );\n\tFD_SET( STDIN_FILENO, &fds );\n\tstruct timeval tv = { 0L, 0L };\n\t(void)select( STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv );\n\tbool HasKey = FD_ISSET( STDIN_FILENO, &fds );\n\treturn HasKey ? fgetc( stdin ) : 0;\n#else\n\tbool Res = kbhit();\n\twhile (kbhit()) getch();\n\treturn Res;\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2009, Mozilla Foundation\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n - Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n - Neither the name of the Mozilla Foundation nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ORGANISATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*\n * Utils.cpp - Generic program utility functions.\n *\n * Contributor(s): \n * Chris Pearce <chris@pearce.org.nz>\n *\/\r\n\r\n\r\n#include <ogg\/ogg.h>\r\n#include <fstream>\n#include <iostream>\n#include <assert.h>\n#include <string.h>\n#include <limits.h>\r\n#include \"Utils.hpp\"\n\r\nogg_page*\nClone(ogg_page* p)\n{\n ogg_page* q = new ogg_page();\n memcpy(q, p, sizeof(ogg_page));\n q->header = new unsigned char[p->header_len + p->body_len];\n q->body = q->header + q->header_len;\n memcpy(q->header, p->header, p->header_len);\n memcpy(q->body, p->body, p->body_len);\n assert(memcmp(p->header, q->header, q->header_len) == 0);\n assert(memcmp(p->body, q->body, q->body_len) == 0);\n assert(q->header_len == p->header_len);\n assert(q->body_len == p->body_len);\n return q;\n}\n\nvoid\nFreeClone(ogg_page* p)\n{\n delete[] p->header;\n delete p;\n}\n\n\nvoid\nWritePage(ofstream& output, const ogg_page& page) {\n output.write((const char*)page.header, page.header_len);\n output.write((const char*)page.body, page.body_len); \n}\n\n\n\/\/ Get the length in bytes of a file. 32bit only, won't work for files larger\n\/\/ than 2GB.\nogg_int64_t\nFileLength(const char* aFileName)\n{\n ifstream is;\n is.open (aFileName, ios::binary);\n is.seekg (0, ios::end);\n streampos length = is.tellg();\n is.close();\n return (ogg_int64_t)length;\n}\n\nogg_packet*\nClone(ogg_packet* p)\n{\n if (!p)\n return 0;\n ogg_packet* q = new ogg_packet();\n memcpy(q, p, sizeof(ogg_packet));\n q->packet = new unsigned char[p->bytes];\n memcpy(q->packet, p->packet, p->bytes);\n return q;\n}\n\nbool\nIsIndexPacket(ogg_packet* packet)\n{\n return packet &&\n packet->bytes >= (long)(HEADER_MAGIC_LEN + 8) &&\n memcmp(packet->packet, HEADER_MAGIC, HEADER_MAGIC_LEN) == 0;\n}\n\n\n#define FILE_BUFFER_SIZE (1024 * 1024)\n\n\/\/ Returns nuber of bytes read.\nbool ReadPage(ogg_sync_state* state,\n ogg_page* page,\n istream& stream,\n ogg_uint64_t& bytesRead)\n{\n ogg_int32_t bytes = 0;\n ogg_int32_t r = 0;\n ogg_uint64_t intialBytesRead = bytesRead;\n while ((r = ogg_sync_pageout(state, page)) != 1) {\n char* buffer = ogg_sync_buffer(state, FILE_BUFFER_SIZE);\n assert(buffer);\n stream.read(buffer, FILE_BUFFER_SIZE);\n bytes = stream.gcount();\n bytesRead += bytes;\n if (bytes == 0) {\n \/\/ End of file\n assert(stream.eof());\n if (intialBytesRead != bytesRead) {\n cerr << \"WARNING: Reached end of file, when expecting to find more data! \"\n << \"Page header may be incorrect!\" << endl;\n }\n return false;\n }\n ogg_int32_t ret = ogg_sync_wrote(state, bytes);\n assert(ret == 0);\n }\n return true;\n}\n\n\/\/ Returns nuber of bytes skipped to next page, or -1 on failure.\nint PageSeek(ogg_sync_state* state,\n ogg_page* page,\n istream& stream,\n ogg_uint64_t& bytesRead)\n{\n int retval = 0;\n ogg_int32_t bytes = 0;\n ogg_int32_t r = 0;\n ogg_uint64_t intialBytesRead = bytesRead;\n while ((r = ogg_sync_pageseek(state, page)) <= 0) {\n if (r == 0) {\n \/\/ Need to read more data to get to next page.\n char* buffer = ogg_sync_buffer(state, FILE_BUFFER_SIZE);\n assert(buffer);\n\n stream.read(buffer, FILE_BUFFER_SIZE);\n bytes = stream.gcount();\n bytesRead += bytes;\n if (bytes == 0) {\n \/\/ End of file\n assert(stream.eof());\n if (intialBytesRead != bytesRead) {\n cerr << \"WARNING: Reached end of file, when expecting to find more data! \"\n << \"Page header may be incorrect!\" << endl;\n }\n return false;\n }\n\n ogg_int32_t ret = ogg_sync_wrote(state, bytes);\n assert(ret == 0);\n } else {\n assert(r<0);\n \/\/ We skipped -r bytes reading up to next ogg page capture.\n retval += (-r);\n }\n }\n if (r == -1) {\n cout << \"ERROR: sync failure in ReadPage()\" << endl;\n return -1;\n }\n return retval;\n}\n\nbool\nIsPageAtOffset(const string& filename, ogg_int64_t offset, ogg_page* page)\n{\n ifstream file(filename.c_str(), ios::in | ios::binary);\n assert(file);\n file.seekg((ogg_int32_t)offset, ios_base::beg);\n char* buf = new char[max(page->body_len, page->header_len)];\n file.read(buf, page->header_len);\n assert(file.gcount() == page->header_len);\n if (memcmp(buf, page->header, page->header_len) != 0) {\n cerr << \"Incorrect page offset calculation for page at offset \"\n << offset << endl;\n delete[] buf;\n return false;\n }\n \n file.read(buf, page->body_len);\n assert(file.gcount() == page->body_len);\n if (memcmp(buf, page->body, page->body_len) != 0) {\n cerr << \"Incorrect page offset calculation for page at offset \"\n << offset << endl;\n delete[] buf;\n return false;\n }\n\n delete[] buf;\n return true;\n}\n\nvoid\nCopyFileData(istream& input, ostream& output, ogg_int64_t bytesToCopy)\n{\n assert(input.good());\n assert(output.good());\n \/\/ Copy data in chunks at most 1mb in size.\n assert(bytesToCopy >= 0);\n assert((ogg_int64_t)FILE_BUFFER_SIZE < (ogg_int64_t)INT_MAX);\n ogg_int32_t len = (ogg_int32_t)min(bytesToCopy, (ogg_int64_t)FILE_BUFFER_SIZE);\n char* buf = new char[len];\n ogg_int64_t bytesCopied = 0;\n while (bytesCopied != bytesToCopy) {\n ogg_int64_t remaining = bytesToCopy - bytesCopied;\n ogg_int32_t x = (ogg_int32_t)min(remaining, (ogg_int64_t)len);\n input.read(buf, x);\n assert(x == input.gcount());\n output.write(buf, x);\n bytesCopied += x;\n }\n delete[] buf;\n}\n\nogg_uint32_t\nGetChecksum(ogg_page* page)\n{\n assert(page != 0);\n assert(page->header != 0);\n assert(page->header_len > 25);\n return LEUint32(page->header + 22);\n}\n\nbool\nIsFisheadPacket(ogg_packet* packet)\n{\n return packet &&\n packet->bytes > 8 &&\n memcmp(packet->packet, \"fishead\", 8) == 0;\n}\n\nbool\nIsFisbonePacket(ogg_packet* packet)\n{\n return packet->packet &&\n packet->bytes >= 52 &&\n memcmp(packet->packet, \"fisbone\", 8) == 0;\n}\n\n\/\/ Theora version \nint TheoraVersion(th_info* info,\r\n unsigned char maj,\r\n unsigned char min,\r\n unsigned char sub)\r\n{\r\n ogg_uint32_t ver = (maj << 16) + (min << 8) + sub;\r\n ogg_uint32_t th_ver = (info->version_major << 16) +\r\n (info->version_minor << 8) +\r\n info->version_subminor;\r\n return (th_ver >= ver) ? 1 : 0;\n}\n\n\/\/ Returns the number of packets that start on a page.\nint\nCountPacketStarts(ogg_page* page)\n{\n int i;\n \/\/ If we're not continuing a packet, we're at a packet start.\n int packets_start = (ogg_page_continued(page) == 0) ? 1 : 0;\n int num_lacing_vals = page->header[26];\n unsigned char* lacing_vals = &page->header[27];\n for (i=1; i<num_lacing_vals; i++) {\n if (lacing_vals[i-1] < 0xff) {\n packets_start++;\n }\n }\n return packets_start;\n}\n\nunsigned char*\nWriteLEUint64(unsigned char* p, const ogg_uint64_t num)\n{\n ogg_int32_t i;\n ogg_uint64_t n = num;\n assert(p);\n for (i=0; i<8; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEUint64(p) == num);\n return p + 8;\n}\n\nunsigned char*\nWriteLEInt64(unsigned char* p, const ogg_int64_t num)\n{\n ogg_int64_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<8; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEInt64(p) == num);\n return p + 8;\n}\n\nunsigned char*\nWriteLEUint32(unsigned char* p, const ogg_uint32_t num)\n{\n ogg_uint32_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<4; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEUint32(p) == num);\n return p + 4;\n}\n\nunsigned char*\nWriteLEInt32(unsigned char* p, const ogg_int32_t num)\n{\n ogg_int32_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<4; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEInt32(p) == num);\n return p + 4;\n}\n\nunsigned char*\nWriteLEUint16(unsigned char* p, const ogg_uint16_t num)\n{\n ogg_uint16_t n = num;\n assert(p);\n p[0] = (unsigned char)(n & 0xff);\n p[1] = (unsigned char)((n >> 8) & 0xff);\n assert(LEUint16(p) == num);\n return p + 2;\n}\n\nogg_uint64_t\nLEUint64(unsigned char* p)\n{\n ogg_uint64_t lo = LEUint32(p);\n ogg_uint64_t hi = LEUint32(p+4);\n return lo + (hi << 32);\n}\n\nogg_int64_t\nLEInt64(unsigned char* p)\n{\n ogg_int64_t lo = LEUint32(p);\n ogg_int64_t hi = LEInt32(p+4);\n return lo + (hi << 32);\n};\n\nogg_uint32_t\nLEUint32(unsigned const char* p) {\n ogg_uint32_t i = p[0] +\n (p[1] << 8) + \n (p[2] << 16) +\n (p[3] << 24);\n return i; \n}\n\nogg_int32_t\nLEInt32(unsigned const char* p) {\n ogg_int32_t i = p[0] +\n (p[1] << 8) + \n (p[2] << 16) +\n (p[3] << 24);\n return i; \n}\n\nogg_uint16_t\nLEUint16(unsigned const char* p) {\n ogg_uint16_t i = p[0] +\n (p[1] << 8);\n return i; \n}\n\nvoid Tokenize(const string& str,\r\n vector<string>& tokens,\r\n const string& delimiter)\r\n{\r\n string::size_type matchStart = 0;\r\n string::size_type matchEnd = str.find(delimiter, matchStart);\r\n while (matchEnd != string::npos && matchStart != matchEnd)\r\n {\r\n \/\/ Found a token, add it to the vector.\r\n tokens.push_back(str.substr(matchStart, matchEnd - matchStart));\r\n matchStart = matchEnd + delimiter.size();\r\n matchEnd = str.find(delimiter, matchStart);\r\n }\r\n}\r\n\n<commit_msg>Fix cast which was causing 32 bit wrap round on seek - limiting the size of the processed movie to 2Gb.<commit_after>\/*\n Copyright (C) 2009, Mozilla Foundation\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n - Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n - Neither the name of the Mozilla Foundation nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ORGANISATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*\n * Utils.cpp - Generic program utility functions.\n *\n * Contributor(s): \n * Chris Pearce <chris@pearce.org.nz>\n *\/\r\n\r\n\r\n#include <ogg\/ogg.h>\r\n#include <fstream>\n#include <iostream>\n#include <assert.h>\n#include <string.h>\n#include <limits.h>\r\n#include \"Utils.hpp\"\n\r\nogg_page*\nClone(ogg_page* p)\n{\n ogg_page* q = new ogg_page();\n memcpy(q, p, sizeof(ogg_page));\n q->header = new unsigned char[p->header_len + p->body_len];\n q->body = q->header + q->header_len;\n memcpy(q->header, p->header, p->header_len);\n memcpy(q->body, p->body, p->body_len);\n assert(memcmp(p->header, q->header, q->header_len) == 0);\n assert(memcmp(p->body, q->body, q->body_len) == 0);\n assert(q->header_len == p->header_len);\n assert(q->body_len == p->body_len);\n return q;\n}\n\nvoid\nFreeClone(ogg_page* p)\n{\n delete[] p->header;\n delete p;\n}\n\n\nvoid\nWritePage(ofstream& output, const ogg_page& page) {\n output.write((const char*)page.header, page.header_len);\n output.write((const char*)page.body, page.body_len); \n}\n\n\n\/\/ Get the length in bytes of a file. 32bit only, won't work for files larger\n\/\/ than 2GB.\nogg_int64_t\nFileLength(const char* aFileName)\n{\n ifstream is;\n is.open (aFileName, ios::binary);\n is.seekg (0, ios::end);\n streampos length = is.tellg();\n is.close();\n return (ogg_int64_t)length;\n}\n\nogg_packet*\nClone(ogg_packet* p)\n{\n if (!p)\n return 0;\n ogg_packet* q = new ogg_packet();\n memcpy(q, p, sizeof(ogg_packet));\n q->packet = new unsigned char[p->bytes];\n memcpy(q->packet, p->packet, p->bytes);\n return q;\n}\n\nbool\nIsIndexPacket(ogg_packet* packet)\n{\n return packet &&\n packet->bytes >= (long)(HEADER_MAGIC_LEN + 8) &&\n memcmp(packet->packet, HEADER_MAGIC, HEADER_MAGIC_LEN) == 0;\n}\n\n\n#define FILE_BUFFER_SIZE (1024 * 1024)\n\n\/\/ Returns nuber of bytes read.\nbool ReadPage(ogg_sync_state* state,\n ogg_page* page,\n istream& stream,\n ogg_uint64_t& bytesRead)\n{\n ogg_int32_t bytes = 0;\n ogg_int32_t r = 0;\n ogg_uint64_t intialBytesRead = bytesRead;\n while ((r = ogg_sync_pageout(state, page)) != 1) {\n char* buffer = ogg_sync_buffer(state, FILE_BUFFER_SIZE);\n assert(buffer);\n stream.read(buffer, FILE_BUFFER_SIZE);\n bytes = stream.gcount();\n bytesRead += bytes;\n if (bytes == 0) {\n \/\/ End of file\n assert(stream.eof());\n if (intialBytesRead != bytesRead) {\n cerr << \"WARNING: Reached end of file, when expecting to find more data! \"\n << \"Page header may be incorrect!\" << endl;\n }\n return false;\n }\n ogg_int32_t ret = ogg_sync_wrote(state, bytes);\n assert(ret == 0);\n }\n return true;\n}\n\n\/\/ Returns nuber of bytes skipped to next page, or -1 on failure.\nint PageSeek(ogg_sync_state* state,\n ogg_page* page,\n istream& stream,\n ogg_uint64_t& bytesRead)\n{\n int retval = 0;\n ogg_int32_t bytes = 0;\n ogg_int32_t r = 0;\n ogg_uint64_t intialBytesRead = bytesRead;\n while ((r = ogg_sync_pageseek(state, page)) <= 0) {\n if (r == 0) {\n \/\/ Need to read more data to get to next page.\n char* buffer = ogg_sync_buffer(state, FILE_BUFFER_SIZE);\n assert(buffer);\n\n stream.read(buffer, FILE_BUFFER_SIZE);\n bytes = stream.gcount();\n bytesRead += bytes;\n if (bytes == 0) {\n \/\/ End of file\n assert(stream.eof());\n if (intialBytesRead != bytesRead) {\n cerr << \"WARNING: Reached end of file, when expecting to find more data! \"\n << \"Page header may be incorrect!\" << endl;\n }\n return false;\n }\n\n ogg_int32_t ret = ogg_sync_wrote(state, bytes);\n assert(ret == 0);\n } else {\n assert(r<0);\n \/\/ We skipped -r bytes reading up to next ogg page capture.\n retval += (-r);\n }\n }\n if (r == -1) {\n cout << \"ERROR: sync failure in ReadPage()\" << endl;\n return -1;\n }\n return retval;\n}\n\nbool\nIsPageAtOffset(const string& filename, ogg_int64_t offset, ogg_page* page)\n{\n ifstream file(filename.c_str(), ios::in | ios::binary);\n assert(file);\n file.seekg((std::streamoff)offset, ios_base::beg);\n char* buf = new char[max(page->body_len, page->header_len)];\n file.read(buf, page->header_len);\n assert(file.gcount() == page->header_len);\n if (memcmp(buf, page->header, page->header_len) != 0) {\n cerr << \"Incorrect page offset calculation for page at offset \"\n << offset << endl;\n delete[] buf;\n return false;\n }\n \n file.read(buf, page->body_len);\n assert(file.gcount() == page->body_len);\n if (memcmp(buf, page->body, page->body_len) != 0) {\n cerr << \"Incorrect page offset calculation for page at offset \"\n << offset << endl;\n delete[] buf;\n return false;\n }\n\n delete[] buf;\n return true;\n}\n\nvoid\nCopyFileData(istream& input, ostream& output, ogg_int64_t bytesToCopy)\n{\n assert(input.good());\n assert(output.good());\n \/\/ Copy data in chunks at most 1mb in size.\n assert(bytesToCopy >= 0);\n assert((ogg_int64_t)FILE_BUFFER_SIZE < (ogg_int64_t)INT_MAX);\n ogg_int32_t len = (ogg_int32_t)min(bytesToCopy, (ogg_int64_t)FILE_BUFFER_SIZE);\n char* buf = new char[len];\n ogg_int64_t bytesCopied = 0;\n while (bytesCopied != bytesToCopy) {\n ogg_int64_t remaining = bytesToCopy - bytesCopied;\n ogg_int32_t x = (ogg_int32_t)min(remaining, (ogg_int64_t)len);\n input.read(buf, x);\n assert(x == input.gcount());\n output.write(buf, x);\n bytesCopied += x;\n }\n delete[] buf;\n}\n\nogg_uint32_t\nGetChecksum(ogg_page* page)\n{\n assert(page != 0);\n assert(page->header != 0);\n assert(page->header_len > 25);\n return LEUint32(page->header + 22);\n}\n\nbool\nIsFisheadPacket(ogg_packet* packet)\n{\n return packet &&\n packet->bytes > 8 &&\n memcmp(packet->packet, \"fishead\", 8) == 0;\n}\n\nbool\nIsFisbonePacket(ogg_packet* packet)\n{\n return packet->packet &&\n packet->bytes >= 52 &&\n memcmp(packet->packet, \"fisbone\", 8) == 0;\n}\n\n\/\/ Theora version \nint TheoraVersion(th_info* info,\r\n unsigned char maj,\r\n unsigned char min,\r\n unsigned char sub)\r\n{\r\n ogg_uint32_t ver = (maj << 16) + (min << 8) + sub;\r\n ogg_uint32_t th_ver = (info->version_major << 16) +\r\n (info->version_minor << 8) +\r\n info->version_subminor;\r\n return (th_ver >= ver) ? 1 : 0;\n}\n\n\/\/ Returns the number of packets that start on a page.\nint\nCountPacketStarts(ogg_page* page)\n{\n int i;\n \/\/ If we're not continuing a packet, we're at a packet start.\n int packets_start = (ogg_page_continued(page) == 0) ? 1 : 0;\n int num_lacing_vals = page->header[26];\n unsigned char* lacing_vals = &page->header[27];\n for (i=1; i<num_lacing_vals; i++) {\n if (lacing_vals[i-1] < 0xff) {\n packets_start++;\n }\n }\n return packets_start;\n}\n\nunsigned char*\nWriteLEUint64(unsigned char* p, const ogg_uint64_t num)\n{\n ogg_int32_t i;\n ogg_uint64_t n = num;\n assert(p);\n for (i=0; i<8; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEUint64(p) == num);\n return p + 8;\n}\n\nunsigned char*\nWriteLEInt64(unsigned char* p, const ogg_int64_t num)\n{\n ogg_int64_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<8; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEInt64(p) == num);\n return p + 8;\n}\n\nunsigned char*\nWriteLEUint32(unsigned char* p, const ogg_uint32_t num)\n{\n ogg_uint32_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<4; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEUint32(p) == num);\n return p + 4;\n}\n\nunsigned char*\nWriteLEInt32(unsigned char* p, const ogg_int32_t num)\n{\n ogg_int32_t n = num;\n ogg_int32_t i;\n assert(p);\n for (i=0; i<4; i++) {\n p[i] = (unsigned char)(n & 0xff);\n n >>= 8;\n }\n assert(LEInt32(p) == num);\n return p + 4;\n}\n\nunsigned char*\nWriteLEUint16(unsigned char* p, const ogg_uint16_t num)\n{\n ogg_uint16_t n = num;\n assert(p);\n p[0] = (unsigned char)(n & 0xff);\n p[1] = (unsigned char)((n >> 8) & 0xff);\n assert(LEUint16(p) == num);\n return p + 2;\n}\n\nogg_uint64_t\nLEUint64(unsigned char* p)\n{\n ogg_uint64_t lo = LEUint32(p);\n ogg_uint64_t hi = LEUint32(p+4);\n return lo + (hi << 32);\n}\n\nogg_int64_t\nLEInt64(unsigned char* p)\n{\n ogg_int64_t lo = LEUint32(p);\n ogg_int64_t hi = LEInt32(p+4);\n return lo + (hi << 32);\n};\n\nogg_uint32_t\nLEUint32(unsigned const char* p) {\n ogg_uint32_t i = p[0] +\n (p[1] << 8) + \n (p[2] << 16) +\n (p[3] << 24);\n return i; \n}\n\nogg_int32_t\nLEInt32(unsigned const char* p) {\n ogg_int32_t i = p[0] +\n (p[1] << 8) + \n (p[2] << 16) +\n (p[3] << 24);\n return i; \n}\n\nogg_uint16_t\nLEUint16(unsigned const char* p) {\n ogg_uint16_t i = p[0] +\n (p[1] << 8);\n return i; \n}\n\nvoid Tokenize(const string& str,\r\n vector<string>& tokens,\r\n const string& delimiter)\r\n{\r\n string::size_type matchStart = 0;\r\n string::size_type matchEnd = str.find(delimiter, matchStart);\r\n while (matchEnd != string::npos && matchStart != matchEnd)\r\n {\r\n \/\/ Found a token, add it to the vector.\r\n tokens.push_back(str.substr(matchStart, matchEnd - matchStart));\r\n matchStart = matchEnd + delimiter.size();\r\n matchEnd = str.find(delimiter, matchStart);\r\n }\r\n}\r\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) Sascha Montellese\n *\n * This Program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * This Program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with cpp-signals; see the file COPYING. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <catch.hpp>\n\n#include <cpp-signal.h>\n\nclass copy_test_class : public cpp_signal<>::slot_tracker\n{\npublic:\n copy_test_class()\n : m_int(0)\n { }\n ~copy_test_class() = default;\n\n unsigned int get_int() const { return m_int; }\n inline void slot_int(int count) { m_int += count; }\n\nprivate:\n unsigned int m_int;\n};\n\nSCENARIO(\"slot-tracking classes can be copied\", \"[copy]\")\n{\n GIVEN(\"A signal and two instances of a slot-tracking class\")\n {\n copy_test_class slot;\n copy_test_class slot_copy;\n\n cpp_signal<>::signal<void(int)> signal;\n\n REQUIRE(slot.get_int() == 0);\n REQUIRE(slot_copy.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"connecting one slot to the signal and emitting the signal\")\n {\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n signal.emit(value);\n\n THEN(\"the connected (and tracked) slot is called and the unconnected slot isn't called\")\n {\n REQUIRE(slot.get_int() == value);\n REQUIRE(slot_copy.get_int() == 0);\n }\n }\n\n WHEN(\"the connected slot is copied to the unconnected slot and the signal is emitted\")\n {\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n slot_copy = slot;\n\n signal.emit(value);\n\n THEN(\"the previously connected slot is called again and the copied slot is called as well\")\n {\n REQUIRE(slot.get_int() == value);\n REQUIRE(slot_copy.get_int() == value);\n }\n }\n }\n}\n\nSCENARIO(\"signals can be copied\", \"[copy]\")\n{\n GIVEN(\"A signal and an untracked connected slot\")\n {\n int slot_count = 0;\n auto lambda = [&slot_count]() { ++slot_count; };\n\n cpp_signal<>::signal<void()> signal;\n signal.connect(lambda);\n\n REQUIRE(slot_count == 0);\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit();\n\n THEN(\"the slot is called\")\n {\n REQUIRE(slot_count == 1);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit();\n signal_copy.emit();\n\n THEN(\"the slot is called again twice\")\n {\n REQUIRE(slot_count == 2);\n }\n }\n }\n\n GIVEN(\"A signal and a tracked connected slot\")\n {\n copy_test_class slot;\n\n cpp_signal<>::signal<void(int)> signal;\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n\n REQUIRE(slot.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit(value);\n\n THEN(\"the slot is called\")\n {\n REQUIRE(slot.get_int() == value);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit(value);\n signal_copy.emit(value);\n\n THEN(\"the slot is called twice\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n }\n\n GIVEN(\"Two chained signals and a tracked connected slot\")\n {\n copy_test_class slot;\n\n cpp_signal<>::signal<void(int)> signal;\n cpp_signal<>::signal<void(int)> chained_signal;\n signal.connect(chained_signal);\n chained_signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n\n REQUIRE(slot.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit(value);\n\n THEN(\"the chainged signal is called and calls the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == value);\n }\n }\n\n WHEN(\"the chained signal is copied and the signal is emitted\")\n {\n auto chained_signal_copy = chained_signal;\n\n signal.emit(value);\n\n THEN(\"the chained signals are called and the call the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit(value);\n signal_copy.emit(value);\n\n THEN(\"the chained signals are called and the call the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n }\n}<commit_msg>c mark copy_test_class destructor noexcept override<commit_after>\/*\n * Copyright (C) Sascha Montellese\n *\n * This Program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * This Program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with cpp-signals; see the file COPYING. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <catch.hpp>\n\n#include <cpp-signal.h>\n\nclass copy_test_class : public cpp_signal<>::slot_tracker\n{\npublic:\n copy_test_class()\n : m_int(0)\n { }\n ~copy_test_class() noexcept override = default;\n\n unsigned int get_int() const { return m_int; }\n inline void slot_int(int count) { m_int += count; }\n\nprivate:\n unsigned int m_int;\n};\n\nSCENARIO(\"slot-tracking classes can be copied\", \"[copy]\")\n{\n GIVEN(\"A signal and two instances of a slot-tracking class\")\n {\n copy_test_class slot;\n copy_test_class slot_copy;\n\n cpp_signal<>::signal<void(int)> signal;\n\n REQUIRE(slot.get_int() == 0);\n REQUIRE(slot_copy.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"connecting one slot to the signal and emitting the signal\")\n {\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n signal.emit(value);\n\n THEN(\"the connected (and tracked) slot is called and the unconnected slot isn't called\")\n {\n REQUIRE(slot.get_int() == value);\n REQUIRE(slot_copy.get_int() == 0);\n }\n }\n\n WHEN(\"the connected slot is copied to the unconnected slot and the signal is emitted\")\n {\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n slot_copy = slot;\n\n signal.emit(value);\n\n THEN(\"the previously connected slot is called again and the copied slot is called as well\")\n {\n REQUIRE(slot.get_int() == value);\n REQUIRE(slot_copy.get_int() == value);\n }\n }\n }\n}\n\nSCENARIO(\"signals can be copied\", \"[copy]\")\n{\n GIVEN(\"A signal and an untracked connected slot\")\n {\n int slot_count = 0;\n auto lambda = [&slot_count]() { ++slot_count; };\n\n cpp_signal<>::signal<void()> signal;\n signal.connect(lambda);\n\n REQUIRE(slot_count == 0);\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit();\n\n THEN(\"the slot is called\")\n {\n REQUIRE(slot_count == 1);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit();\n signal_copy.emit();\n\n THEN(\"the slot is called again twice\")\n {\n REQUIRE(slot_count == 2);\n }\n }\n }\n\n GIVEN(\"A signal and a tracked connected slot\")\n {\n copy_test_class slot;\n\n cpp_signal<>::signal<void(int)> signal;\n signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n\n REQUIRE(slot.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit(value);\n\n THEN(\"the slot is called\")\n {\n REQUIRE(slot.get_int() == value);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit(value);\n signal_copy.emit(value);\n\n THEN(\"the slot is called twice\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n }\n\n GIVEN(\"Two chained signals and a tracked connected slot\")\n {\n copy_test_class slot;\n\n cpp_signal<>::signal<void(int)> signal;\n cpp_signal<>::signal<void(int)> chained_signal;\n signal.connect(chained_signal);\n chained_signal.connect<copy_test_class, ©_test_class::slot_int>(slot);\n\n REQUIRE(slot.get_int() == 0);\n\n const int value = 1;\n\n WHEN(\"the signal is emitted\")\n {\n signal.emit(value);\n\n THEN(\"the chainged signal is called and calls the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == value);\n }\n }\n\n WHEN(\"the chained signal is copied and the signal is emitted\")\n {\n auto chained_signal_copy = chained_signal;\n\n signal.emit(value);\n\n THEN(\"the chained signals are called and the call the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n\n WHEN(\"the signal is copied and both signals are emitted\")\n {\n auto signal_copy = signal;\n\n signal.emit(value);\n signal_copy.emit(value);\n\n THEN(\"the chained signals are called and the call the slot with the forwarded parameter\")\n {\n REQUIRE(slot.get_int() == 2 * value);\n }\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_PROTOBUF_HPP__\n#define __PROCESS_PROTOBUF_HPP__\n\n#include <glog\/logging.h>\n\n#include <google\/protobuf\/arena.h>\n#include <google\/protobuf\/message.h>\n#include <google\/protobuf\/repeated_field.h>\n\n#include <set>\n#include <vector>\n\n#include <process\/defer.hpp>\n#include <process\/dispatch.hpp>\n#include <process\/id.hpp>\n#include <process\/process.hpp>\n\n#include <stout\/hashmap.hpp>\n#include <stout\/lambda.hpp>\n\n\n\/\/ Provides an implementation of process::post that for a protobuf.\nnamespace process {\n\ninline void post(const process::UPID& to,\n const google::protobuf::Message& message)\n{\n std::string data;\n message.SerializeToString(&data);\n post(to, message.GetTypeName(), data.data(), data.size());\n}\n\n\ninline void post(const process::UPID& from,\n const process::UPID& to,\n const google::protobuf::Message& message)\n{\n std::string data;\n message.SerializeToString(&data);\n post(from, to, message.GetTypeName(), data.data(), data.size());\n}\n\n} \/\/ namespace process {\n\n\n\/\/ The rest of this file provides libprocess \"support\" for using\n\/\/ protocol buffers. In particular, this file defines a subclass of\n\/\/ Process (ProtobufProcess) that allows you to install protocol\n\/\/ buffer handlers in addition to normal message and HTTP\n\/\/ handlers. Install handlers can optionally take the sender's UPID\n\/\/ as their first argument.\n\/\/ Note that this header file assumes you will be linking\n\/\/ against BOTH libprotobuf and libglog.\n\nnamespace google {\nnamespace protobuf {\n\n\/\/ Type conversions helpful for changing between protocol buffer types\n\/\/ and standard C++ types (for parameters).\ntemplate <typename T>\nconst T& convert(const T& t)\n{\n return t;\n}\n\n\ntemplate <typename T>\nstd::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items)\n{\n std::vector<T> result;\n for (int i = 0; i < items.size(); i++) {\n result.push_back(items.Get(i));\n }\n\n return result;\n}\n\n} \/\/ namespace protobuf {\n} \/\/ namespace google {\n\n\ntemplate <typename T>\nclass ProtobufProcess : public process::Process<T>\n{\npublic:\n virtual ~ProtobufProcess() {}\n\nprotected:\n virtual void visit(const process::MessageEvent& event)\n {\n if (protobufHandlers.count(event.message.name) > 0) {\n from = event.message.from; \/\/ For 'reply'.\n protobufHandlers[event.message.name](\n event.message.from, event.message.body);\n from = process::UPID();\n } else {\n process::Process<T>::visit(event);\n }\n }\n\n void send(const process::UPID& to,\n const google::protobuf::Message& message)\n {\n std::string data;\n message.SerializeToString(&data);\n process::Process<T>::send(to, message.GetTypeName(),\n data.data(), data.size());\n }\n\n using process::Process<T>::send;\n\n void reply(const google::protobuf::Message& message)\n {\n CHECK(from) << \"Attempting to reply without a sender\";\n std::string data;\n message.SerializeToString(&data);\n send(from, message);\n }\n\n \/\/ Installs that take the sender as the first argument.\n template <typename M>\n void install(void (T::*method)(const process::UPID&, const M&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&handlerM<M>,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M, typename P>\n using MessageProperty = P(M::*)() const;\n\n template <typename M>\n void install(void (T::*method)(const process::UPID&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&handler0,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n void install(\n void (T::*method)(const process::UPID&, PC...),\n MessageProperty<M, P>... param)\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(static_cast<void(&)(\n T*,\n void (T::*)(const process::UPID&, PC...),\n const process::UPID&,\n const std::string&,\n MessageProperty<M, P>...)>(handlerN),\n t, method,\n lambda::_1, lambda::_2, param...);\n delete m;\n }\n\n \/\/ Installs that do not take the sender.\n template <typename M>\n void install(void (T::*method)(const M&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&_handlerM<M>,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M>\n void install(void (T::*method)())\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&_handler0,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n void install(\n void (T::*method)(PC...),\n MessageProperty<M, P>... param)\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(static_cast<void(&)(\n T*,\n void (T::*)(PC...),\n const process::UPID&,\n const std::string&,\n MessageProperty<M, P>...)>(_handlerN),\n t, method,\n lambda::_1, lambda::_2, param...);\n delete m;\n }\n\n using process::Process<T>::install;\n\nprivate:\n \/\/ Handlers that take the sender as the first argument.\n template <typename M>\n static void handlerM(\n T* t,\n void (T::*method)(const process::UPID&, const M&),\n const process::UPID& sender,\n const std::string& data)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(sender, *m);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n static void handler0(\n T* t,\n void (T::*method)(const process::UPID&),\n const process::UPID& sender,\n const std::string& data)\n {\n (t->*method)(sender);\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n static void handlerN(\n T* t,\n void (T::*method)(const process::UPID&, PC...),\n const process::UPID& sender,\n const std::string& data,\n MessageProperty<M, P>... p)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(sender, google::protobuf::convert((m->*p)())...);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n \/\/ Handlers that ignore the sender.\n template <typename M>\n static void _handlerM(\n T* t,\n void (T::*method)(const M&),\n const process::UPID&,\n const std::string& data)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(*m);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n static void _handler0(\n T* t,\n void (T::*method)(),\n const process::UPID&,\n const std::string& data)\n {\n (t->*method)();\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n static void _handlerN(\n T* t,\n void (T::*method)(PC...),\n const process::UPID&,\n const std::string& data,\n MessageProperty<M, P>... p)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(google::protobuf::convert((m->*p)())...);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n typedef lambda::function<\n void(const process::UPID&, const std::string&)> handler;\n hashmap<std::string, handler> protobufHandlers;\n\n \/\/ Sender of \"current\" message, inaccessible by subclasses.\n \/\/ This is only used for reply().\n process::UPID from;\n};\n\n\n\/\/ Implements a process for sending protobuf \"requests\" to a process\n\/\/ and waiting for a protobuf \"response\", but uses futures so that\n\/\/ this can be done without needing to implement a process.\ntemplate <typename Req, typename Res>\nclass ReqResProcess : public ProtobufProcess<ReqResProcess<Req, Res>>\n{\npublic:\n ReqResProcess(const process::UPID& _pid, const Req& _req)\n : process::ProcessBase(process::ID::generate(\"__req_res__\")),\n pid(_pid),\n req(_req)\n {\n ProtobufProcess<ReqResProcess<Req, Res>>::template\n install<Res>(&ReqResProcess<Req, Res>::response);\n }\n\n virtual ~ReqResProcess()\n {\n \/\/ Discard the promise.\n promise.discard();\n }\n\n process::Future<Res> run()\n {\n promise.future().onDiscard(defer(this, &ReqResProcess::discarded));\n\n ProtobufProcess<ReqResProcess<Req, Res>>::send(pid, req);\n\n return promise.future();\n }\n\nprivate:\n void discarded()\n {\n promise.discard();\n process::terminate(this);\n }\n\n void response(const Res& res)\n {\n promise.set(res);\n process::terminate(this);\n }\n\n const process::UPID pid;\n const Req req;\n process::Promise<Res> promise;\n};\n\n\n\/\/ Allows you to describe request\/response protocols and then use\n\/\/ those for sending requests and getting back responses.\ntemplate <typename Req, typename Res>\nstruct Protocol\n{\n process::Future<Res> operator()(\n const process::UPID& pid,\n const Req& req) const\n {\n \/\/ Help debugging by adding some \"type constraints\".\n { Req* req = nullptr; google::protobuf::Message* m = req; (void)m; }\n { Res* res = nullptr; google::protobuf::Message* m = res; (void)m; }\n\n ReqResProcess<Req, Res>* process = new ReqResProcess<Req, Res>(pid, req);\n process::spawn(process, true);\n return process::dispatch(process, &ReqResProcess<Req, Res>::run);\n }\n};\n\n#endif \/\/ __PROCESS_PROTOBUF_HPP__\n<commit_msg>Simplified RepeatedPtrField to vector conversion.<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_PROTOBUF_HPP__\n#define __PROCESS_PROTOBUF_HPP__\n\n#include <glog\/logging.h>\n\n#include <google\/protobuf\/arena.h>\n#include <google\/protobuf\/message.h>\n#include <google\/protobuf\/repeated_field.h>\n\n#include <set>\n#include <vector>\n\n#include <process\/defer.hpp>\n#include <process\/dispatch.hpp>\n#include <process\/id.hpp>\n#include <process\/process.hpp>\n\n#include <stout\/hashmap.hpp>\n#include <stout\/lambda.hpp>\n\n\n\/\/ Provides an implementation of process::post that for a protobuf.\nnamespace process {\n\ninline void post(const process::UPID& to,\n const google::protobuf::Message& message)\n{\n std::string data;\n message.SerializeToString(&data);\n post(to, message.GetTypeName(), data.data(), data.size());\n}\n\n\ninline void post(const process::UPID& from,\n const process::UPID& to,\n const google::protobuf::Message& message)\n{\n std::string data;\n message.SerializeToString(&data);\n post(from, to, message.GetTypeName(), data.data(), data.size());\n}\n\n} \/\/ namespace process {\n\n\n\/\/ The rest of this file provides libprocess \"support\" for using\n\/\/ protocol buffers. In particular, this file defines a subclass of\n\/\/ Process (ProtobufProcess) that allows you to install protocol\n\/\/ buffer handlers in addition to normal message and HTTP\n\/\/ handlers. Install handlers can optionally take the sender's UPID\n\/\/ as their first argument.\n\/\/ Note that this header file assumes you will be linking\n\/\/ against BOTH libprotobuf and libglog.\n\nnamespace google {\nnamespace protobuf {\n\n\/\/ Type conversions helpful for changing between protocol buffer types\n\/\/ and standard C++ types (for parameters).\ntemplate <typename T>\nconst T& convert(const T& t)\n{\n return t;\n}\n\n\ntemplate <typename T>\nstd::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items)\n{\n return std::vector<T>(items.begin(), items.end());\n}\n\n} \/\/ namespace protobuf {\n} \/\/ namespace google {\n\n\ntemplate <typename T>\nclass ProtobufProcess : public process::Process<T>\n{\npublic:\n virtual ~ProtobufProcess() {}\n\nprotected:\n virtual void visit(const process::MessageEvent& event)\n {\n if (protobufHandlers.count(event.message.name) > 0) {\n from = event.message.from; \/\/ For 'reply'.\n protobufHandlers[event.message.name](\n event.message.from, event.message.body);\n from = process::UPID();\n } else {\n process::Process<T>::visit(event);\n }\n }\n\n void send(const process::UPID& to,\n const google::protobuf::Message& message)\n {\n std::string data;\n message.SerializeToString(&data);\n process::Process<T>::send(to, message.GetTypeName(),\n data.data(), data.size());\n }\n\n using process::Process<T>::send;\n\n void reply(const google::protobuf::Message& message)\n {\n CHECK(from) << \"Attempting to reply without a sender\";\n std::string data;\n message.SerializeToString(&data);\n send(from, message);\n }\n\n \/\/ Installs that take the sender as the first argument.\n template <typename M>\n void install(void (T::*method)(const process::UPID&, const M&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&handlerM<M>,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M, typename P>\n using MessageProperty = P(M::*)() const;\n\n template <typename M>\n void install(void (T::*method)(const process::UPID&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&handler0,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n void install(\n void (T::*method)(const process::UPID&, PC...),\n MessageProperty<M, P>... param)\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(static_cast<void(&)(\n T*,\n void (T::*)(const process::UPID&, PC...),\n const process::UPID&,\n const std::string&,\n MessageProperty<M, P>...)>(handlerN),\n t, method,\n lambda::_1, lambda::_2, param...);\n delete m;\n }\n\n \/\/ Installs that do not take the sender.\n template <typename M>\n void install(void (T::*method)(const M&))\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&_handlerM<M>,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M>\n void install(void (T::*method)())\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(&_handler0,\n t, method,\n lambda::_1, lambda::_2);\n delete m;\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n void install(\n void (T::*method)(PC...),\n MessageProperty<M, P>... param)\n {\n google::protobuf::Message* m = new M();\n T* t = static_cast<T*>(this);\n protobufHandlers[m->GetTypeName()] =\n lambda::bind(static_cast<void(&)(\n T*,\n void (T::*)(PC...),\n const process::UPID&,\n const std::string&,\n MessageProperty<M, P>...)>(_handlerN),\n t, method,\n lambda::_1, lambda::_2, param...);\n delete m;\n }\n\n using process::Process<T>::install;\n\nprivate:\n \/\/ Handlers that take the sender as the first argument.\n template <typename M>\n static void handlerM(\n T* t,\n void (T::*method)(const process::UPID&, const M&),\n const process::UPID& sender,\n const std::string& data)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(sender, *m);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n static void handler0(\n T* t,\n void (T::*method)(const process::UPID&),\n const process::UPID& sender,\n const std::string& data)\n {\n (t->*method)(sender);\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n static void handlerN(\n T* t,\n void (T::*method)(const process::UPID&, PC...),\n const process::UPID& sender,\n const std::string& data,\n MessageProperty<M, P>... p)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(sender, google::protobuf::convert((m->*p)())...);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n \/\/ Handlers that ignore the sender.\n template <typename M>\n static void _handlerM(\n T* t,\n void (T::*method)(const M&),\n const process::UPID&,\n const std::string& data)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(*m);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n static void _handler0(\n T* t,\n void (T::*method)(),\n const process::UPID&,\n const std::string& data)\n {\n (t->*method)();\n }\n\n template <typename M,\n typename ...P, typename ...PC>\n static void _handlerN(\n T* t,\n void (T::*method)(PC...),\n const process::UPID&,\n const std::string& data,\n MessageProperty<M, P>... p)\n {\n google::protobuf::Arena arena;\n M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));\n m->ParseFromString(data);\n\n if (m->IsInitialized()) {\n (t->*method)(google::protobuf::convert((m->*p)())...);\n } else {\n LOG(WARNING) << \"Initialization errors: \"\n << m->InitializationErrorString();\n }\n }\n\n typedef lambda::function<\n void(const process::UPID&, const std::string&)> handler;\n hashmap<std::string, handler> protobufHandlers;\n\n \/\/ Sender of \"current\" message, inaccessible by subclasses.\n \/\/ This is only used for reply().\n process::UPID from;\n};\n\n\n\/\/ Implements a process for sending protobuf \"requests\" to a process\n\/\/ and waiting for a protobuf \"response\", but uses futures so that\n\/\/ this can be done without needing to implement a process.\ntemplate <typename Req, typename Res>\nclass ReqResProcess : public ProtobufProcess<ReqResProcess<Req, Res>>\n{\npublic:\n ReqResProcess(const process::UPID& _pid, const Req& _req)\n : process::ProcessBase(process::ID::generate(\"__req_res__\")),\n pid(_pid),\n req(_req)\n {\n ProtobufProcess<ReqResProcess<Req, Res>>::template\n install<Res>(&ReqResProcess<Req, Res>::response);\n }\n\n virtual ~ReqResProcess()\n {\n \/\/ Discard the promise.\n promise.discard();\n }\n\n process::Future<Res> run()\n {\n promise.future().onDiscard(defer(this, &ReqResProcess::discarded));\n\n ProtobufProcess<ReqResProcess<Req, Res>>::send(pid, req);\n\n return promise.future();\n }\n\nprivate:\n void discarded()\n {\n promise.discard();\n process::terminate(this);\n }\n\n void response(const Res& res)\n {\n promise.set(res);\n process::terminate(this);\n }\n\n const process::UPID pid;\n const Req req;\n process::Promise<Res> promise;\n};\n\n\n\/\/ Allows you to describe request\/response protocols and then use\n\/\/ those for sending requests and getting back responses.\ntemplate <typename Req, typename Res>\nstruct Protocol\n{\n process::Future<Res> operator()(\n const process::UPID& pid,\n const Req& req) const\n {\n \/\/ Help debugging by adding some \"type constraints\".\n { Req* req = nullptr; google::protobuf::Message* m = req; (void)m; }\n { Res* res = nullptr; google::protobuf::Message* m = res; (void)m; }\n\n ReqResProcess<Req, Res>* process = new ReqResProcess<Req, Res>(pid, req);\n process::spawn(process, true);\n return process::dispatch(process, &ReqResProcess<Req, Res>::run);\n }\n};\n\n#endif \/\/ __PROCESS_PROTOBUF_HPP__\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include \"JWModules.hpp\"\n#include \"dsp\/digital.hpp\"\n\nstruct XYPad : Module {\n\tenum ParamIds {\n\t\tX_POS_PARAM,\n\t\tY_POS_PARAM,\n\t\tGATE_PARAM,\n\t\tNUM_PARAMS\n\t};\n\tenum InputIds {\n\t\tNUM_INPUTS\n\t};\n\tenum OutputIds {\n\t\tX_OUTPUT,\n\t\tY_OUTPUT,\n\t\tGATE_OUTPUT,\n\t\tNUM_OUTPUTS\n\t};\n\n\tXYPad() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}\n\tvoid step();\n\n\tvoid initialize() {\n\t}\n};\n\nvoid XYPad::step() {\n\toutputs[X_OUTPUT].value = rescalef(params[X_POS_PARAM].value, 0.0, 300, 0.0, 10.0);\n\toutputs[Y_OUTPUT].value = rescalef(params[Y_POS_PARAM].value, 0.0, 300, 10.0, 0.0);\n\toutputs[GATE_OUTPUT].value = rescalef(params[GATE_PARAM].value, 0.0, 1, 0, 10.0);\n}\n\nstruct XYPadDisplay : Widget {\n\tXYPad *module;\n\tbool mouseDown = false;\n\tfloat minX = 5, minY = 5, maxX = 290, maxY = 370;\n\tXYPadDisplay() {}\n\n\tvoid setMouseDown(bool down){\n\t\tmouseDown = down;\n\t\tmodule->params[XYPad::GATE_PARAM].value = down;\n\t}\n\n\tWidget *onMouseDown(Vec pos, int button){\n\t\tsetMouseDown(true);\n\t\treturn this;\n\t}\n\n\tWidget *onMouseUp(Vec pos, int button){\n\t\tsetMouseDown(false);\n\t\treturn this;\n\t}\n\n\tWidget *onMouseMove(Vec pos, Vec mouseRel){\n\t\tif(mouseDown \n\t\t\t && pos.x > minX && pos.x < maxX\n\t\t\t && pos.y > minY && pos.y < maxY ){\n\t\t\tmodule->params[XYPad::X_POS_PARAM].value = pos.x;\n\t\t\tmodule->params[XYPad::Y_POS_PARAM].value = pos.y;\n\t\t}\n\t\treturn this;\n\t}\n\tvoid onMouseEnter() {}\n\tvoid onMouseLeave() {}\n\tvoid onDragStart() {}\n\tvoid onDragEnd() {\n\t\tsetMouseDown(false);\n\t}\n\tvoid onDragMove(Vec mouseRel) {\n\t\tif(mouseDown){\n\t\t\tfloat newX = module->params[XYPad::X_POS_PARAM].value + mouseRel.x;\n\t\t\tif(newX > minX && newX < maxX){\n\t\t\t\tmodule->params[XYPad::X_POS_PARAM].value = newX;\n\t\t\t}\n\t\t\tfloat newY = module->params[XYPad::Y_POS_PARAM].value + mouseRel.y;\n\t\t\tif(newY > minY && newY < maxY){\n\t\t\t\tmodule->params[XYPad::Y_POS_PARAM].value = newY;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid draw(NVGcontext *vg) {\n\t\tfloat ballX = module->params[XYPad::X_POS_PARAM].value;\n\t\tfloat ballY = module->params[XYPad::Y_POS_PARAM].value;\n\n\t\tnvgFillColor(vg, nvgRGB(25, 150, 252));\n\t\tnvgStrokeColor(vg, nvgRGB(25, 150, 252));\n\t\tnvgStrokeWidth(vg, 2);\n\t\t\n\t\t\/\/ nvgBeginPath(vg);\n\t\t\/\/ nvgRect(vg, 20, 20, maxY, box.size.y-40);\n\t\t\/\/ nvgStroke(vg);\n\t\t\n\t\tnvgBeginPath(vg);\n\t\tnvgCircle(vg, ballX, ballY, 10);\n\t\tif(mouseDown)nvgFill(vg);\n\t\tnvgStroke(vg);\n\t}\n};\n\nXYPadWidget::XYPadWidget() {\n\tXYPad *module = new XYPad();\n\tsetModule(module);\n\tbox.size = Vec(RACK_GRID_WIDTH*20, RACK_GRID_HEIGHT);\n\n\t{\n\t\tLightPanel *panel = new LightPanel();\n\t\tpanel->backgroundColor = nvgRGB(30, 40, 43);\n\t\tpanel->box.size = box.size;\n\t\taddChild(panel);\n\t}\n\n\t{\n\t\tXYPadDisplay *display = new XYPadDisplay();\n\t\tdisplay->module = module;\n\t\tdisplay->box.pos = Vec(0, 0);\n\t\tdisplay->box.size = Vec(box.size.x, RACK_GRID_HEIGHT);\n\t\taddChild(display);\n\t}\n\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 60, 360), module, XYPad::X_OUTPUT));\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 40, 360), module, XYPad::Y_OUTPUT));\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 20, 360), module, XYPad::GATE_OUTPUT));\n}\n\n<commit_msg>xypad<commit_after>#include <string.h>\n#include \"JWModules.hpp\"\n#include \"dsp\/digital.hpp\"\n\nstruct XYPad : Module {\n\tenum ParamIds {\n\t\tX_POS_PARAM,\n\t\tY_POS_PARAM,\n\t\tGATE_PARAM,\n\t\tNUM_PARAMS\n\t};\n\tenum InputIds {\n\t\tNUM_INPUTS\n\t};\n\tenum OutputIds {\n\t\tX_OUTPUT,\n\t\tY_OUTPUT,\n\t\tGATE_OUTPUT,\n\t\tNUM_OUTPUTS\n\t};\n\t\n\tfloat minX = 0, minY = 0, maxX = 0, maxY = 0;\n\tfloat displayWidth = 0, displayHeight = 0;\n\tfloat totalBallSize = 12;\n\t\n\tXYPad() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}\n\tvoid step();\n\tvoid initialize(){\n\t\tdefaultPos();\n\t}\n\n\tjson_t *toJson() {\n\t\tjson_t *rootJ = json_object();\n\t\tjson_object_set_new(rootJ, \"xPos\", json_real(params[X_POS_PARAM].value));\n\t\tjson_object_set_new(rootJ, \"yPos\", json_real(params[Y_POS_PARAM].value));\n\t\treturn rootJ;\n\t}\n\n\tvoid fromJson(json_t *rootJ) {\n\t\tjson_t *xPosJ = json_object_get(rootJ, \"xPos\");\n\t\tjson_t *yPosJ = json_object_get(rootJ, \"yPos\");\n\t\tif (xPosJ){ params[X_POS_PARAM].value = json_real_value(xPosJ); }\n\t\tif (yPosJ){ params[Y_POS_PARAM].value = json_real_value(yPosJ); }\n\t}\n\n\tvoid defaultPos() {\n\t\tparams[XYPad::X_POS_PARAM].value = displayWidth \/ 2.0;\n\t\tparams[XYPad::Y_POS_PARAM].value = displayHeight \/ 2.0;\t\t\n\t}\n\n\tvoid updateMinMax(){\n\t\tminX = totalBallSize;\n\t\tminY = totalBallSize;\n\t\tmaxX = displayWidth - totalBallSize;\n\t\tmaxY = displayHeight - totalBallSize;\n\n\t}\n};\n\nvoid XYPad::step() {\n\toutputs[X_OUTPUT].value = rescalef(params[X_POS_PARAM].value, minX, maxX, 0.0, 10.0);\n\toutputs[Y_OUTPUT].value = rescalef(params[Y_POS_PARAM].value, minY, maxY, 10.0, 0.0);\n\toutputs[GATE_OUTPUT].value = rescalef(params[GATE_PARAM].value, 0.0, 1.0, 0.0, 10.0);\n}\n\nstruct XYPadDisplay : Widget {\n\tXYPad *module;\n\tbool mouseDown = false;\n\tXYPadDisplay() {\n\n\t}\n\n\tvoid setMouseDown(bool down){\n\t\tmouseDown = down;\n\t\tmodule->params[XYPad::GATE_PARAM].value = down;\n\t}\n\n\tWidget *onMouseDown(Vec pos, int button){\n\t\tsetMouseDown(true);\n\t\treturn this;\n\t}\n\n\tWidget *onMouseUp(Vec pos, int button){\n\t\tsetMouseDown(false);\n\t\treturn this;\n\t}\n\n\tWidget *onMouseMove(Vec pos, Vec mouseRel){\n\t\tif(mouseDown){\n\t\t\tmodule->params[XYPad::X_POS_PARAM].value = clampf(pos.x, module->minX, module->maxX);\n\t\t\tmodule->params[XYPad::Y_POS_PARAM].value = clampf(pos.y, module->minY, module->maxY);\n\t\t}\n\t\treturn this;\n\t}\n\tvoid onMouseEnter() {}\n\tvoid onMouseLeave() {}\n\tvoid onDragStart() {}\n\tvoid onDragEnd() {\n\t\tsetMouseDown(false);\n\t}\n\tvoid onDragMove(Vec mouseRel) {\n\t\tif(mouseDown){\n\t\t\tfloat newX = module->params[XYPad::X_POS_PARAM].value + mouseRel.x;\n\t\t\tfloat newY = module->params[XYPad::Y_POS_PARAM].value + mouseRel.y;\n\t\t\tmodule->params[XYPad::X_POS_PARAM].value = clampf(newX, module->minX, module->maxX);\n\t\t\tmodule->params[XYPad::Y_POS_PARAM].value = clampf(newY, module->minY, module->maxY);\n\t\t}\n\t}\n\n\tvoid draw(NVGcontext *vg) {\n\t\tfloat ballX = module->params[XYPad::X_POS_PARAM].value;\n\t\tfloat ballY = module->params[XYPad::Y_POS_PARAM].value;\n\n\t\t\/\/background\n\t\tnvgFillColor(vg, nvgRGB(20, 30, 33));\n\t\tnvgBeginPath(vg);\n\t\tnvgRect(vg, 0, 0, box.size.x, box.size.y);\n\t\tnvgFill(vg);\n\t\t\n\t\t\/\/horizontal line\n\t\tnvgStrokeColor(vg, nvgRGB(255, 255, 255));\n\t\tnvgBeginPath(vg);\n\t\tnvgMoveTo(vg, 0, ballY);\n\t\tnvgLineTo(vg, box.size.x, ballY);\n\t\tnvgStroke(vg);\n\t\t\n\t\t\/\/vertical line\n\t\tnvgStrokeColor(vg, nvgRGB(255, 255, 255));\n\t\tnvgBeginPath(vg);\n\t\tnvgMoveTo(vg, ballX, 0);\n\t\tnvgLineTo(vg, ballX, box.size.y);\n\t\tnvgStroke(vg);\n\t\t\n\t\t\/\/ball\n\t\tnvgFillColor(vg, nvgRGB(25, 150, 252));\n\t\tnvgStrokeColor(vg, nvgRGB(25, 150, 252));\n\t\tnvgStrokeWidth(vg, 2);\n\t\tnvgBeginPath(vg);\n\t\tnvgCircle(vg, ballX, ballY, 10);\n\t\tif(mouseDown)nvgFill(vg);\n\t\tnvgStroke(vg);\n\t}\n};\n\nXYPadWidget::XYPadWidget() {\n\tXYPad *module = new XYPad();\n\tsetModule(module);\n\tbox.size = Vec(RACK_GRID_WIDTH*20, RACK_GRID_HEIGHT);\n\n\t{\n\t\tLightPanel *panel = new LightPanel();\n\t\tpanel->box.size = box.size;\n\t\taddChild(panel);\n\t}\n\n\t{\n\t\tXYPadDisplay *display = new XYPadDisplay();\n\t\tdisplay->module = module;\n\t\tdisplay->box.pos = Vec(2, 2);\n\t\tdisplay->box.size = Vec(box.size.x - 4, RACK_GRID_HEIGHT - 35);\n\t\taddChild(display);\n\n\t\tmodule->displayWidth = display->box.size.x;\n\t\tmodule->displayHeight = display->box.size.y;\n\t\tmodule->updateMinMax();\n\t\tmodule->defaultPos();\n\t}\n\n\track::Label* const titleLabel = new rack::Label;\n\ttitleLabel->box.pos = Vec(3, 350);\n\ttitleLabel->text = \"XY Pad\";\n\taddChild(titleLabel);\n\n\track::Label* const xLabel = new rack::Label;\n\txLabel->box.pos = Vec(235, 344);\n\txLabel->text = \"X\";\n\taddChild(xLabel);\n\n\track::Label* const yLabel = new rack::Label;\n\tyLabel->box.pos = Vec(255, 344);\n\tyLabel->text = \"Y\";\n\taddChild(yLabel);\n\n\track::Label* const gLabel = new rack::Label;\n\tgLabel->box.pos = Vec(275, 344);\n\tgLabel->text = \"G\";\n\taddChild(gLabel);\n\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 60, 360), module, XYPad::X_OUTPUT));\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 40, 360), module, XYPad::Y_OUTPUT));\n\taddOutput(createOutput<TinyPJ301MPort>(Vec(box.size.x - 20, 360), module, XYPad::GATE_OUTPUT));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n\n#include <vector>\n\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/common\/exceptions.hh>\n#include <dune\/stuff\/common\/parallel\/threadmanager.hh>\n#include <dune\/stuff\/common\/tmp-storage.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/grid\/walker\/functors.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localoperator\/interface.hh>\n#include <dune\/gdt\/localfunctional\/interface.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalAssembler {\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix\n{\n static_assert(\n std::is_base_of<LocalOperator::Codim0Interface<typename LocalOperatorImp::Traits>, LocalOperatorImp>::value,\n \"LocalOperatorImp has to be derived from LocalOperator::Codim0Interface!\");\n\npublic:\n typedef LocalOperatorImp LocalOperatorType;\n\n explicit Codim0Matrix(const LocalOperatorType& op)\n : localOperator_(op)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam A Traits of the SpaceInterface implementation, representing the type of ansatzSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam M Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the\n * type of systemMatrix\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class A, class EntityType, class M, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,\n Dune::Stuff::LA::MatrixInterface<M, R>& systemMatrix,\n std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,\n std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const\n {\n \/\/ check\n assert(tmpLocalMatricesContainer.size() >= 1);\n assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());\n assert(tmpIndicesContainer.size() >= 2);\n \/\/ get and clear matrix\n Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];\n localMatrix *= 0.0;\n auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];\n \/\/ apply local operator (result is in localMatrix)\n localOperator_.apply(\n testSpace.base_function_set(entity), ansatzSpace.base_function_set(entity), localMatrix, tmpOperatorMatrices);\n \/\/ write local matrix to global\n Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];\n Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];\n const size_t rows = testSpace.mapper().numDofs(entity);\n const size_t cols = ansatzSpace.mapper().numDofs(entity);\n assert(globalRows.size() >= rows);\n assert(globalCols.size() >= cols);\n testSpace.mapper().globalIndices(entity, globalRows);\n ansatzSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < rows; ++ii) {\n const auto& localRow = localMatrix[ii];\n const size_t globalII = globalRows[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n const size_t globalJJ = globalCols[jj];\n systemMatrix.add_to_entry(globalII, globalJJ, localRow[jj]);\n }\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalOperatorType& localOperator_;\n}; \/\/ class Codim0Matrix\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0Vector\n{\n static_assert(\n std::is_base_of<LocalFunctional::Codim0Interface<typename LocalFunctionalImp::Traits>, LocalFunctionalImp>::value,\n \"LocalFunctionalImp has to be derived from LocalFunctional::Codim0Interface!\");\n\npublic:\n typedef LocalFunctionalImp LocalFunctionalType;\n\n explicit Codim0Vector(const LocalFunctionalType& func)\n : localFunctional_(func)\n {\n }\n\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam V Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the\n * type of systemVector\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class EntityType, class V, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const EntityType& entity,\n Dune::Stuff::LA::VectorInterface<V, R>& systemVector,\n std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorContainer,\n Dune::DynamicVector<size_t>& tmpIndices) const\n {\n \/\/ check\n assert(tmpLocalVectorContainer.size() >= 2);\n assert(tmpLocalVectorContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalVectorContainer[1].size() >= localFunctional_.numTmpObjectsRequired());\n \/\/ get and clear vector\n auto& localVector = tmpLocalVectorContainer[0][0];\n localVector *= 0.0;\n auto& tmpFunctionalVectors = tmpLocalVectorContainer[1];\n \/\/ apply local functional (result is in localVector)\n localFunctional_.apply(testSpace.base_function_set(entity), localVector, tmpFunctionalVectors);\n \/\/ write local vector to global\n const size_t size = testSpace.mapper().numDofs(entity);\n assert(tmpIndices.size() >= size);\n testSpace.mapper().globalIndices(entity, tmpIndices);\n for (size_t ii = 0; ii < size; ++ii) {\n systemVector.add_to_entry(tmpIndices[ii], localVector[ii]);\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalFunctionalType& localFunctional_;\n}; \/\/ class Codim0Vector\n\n\ntemplate <class GridViewImp, class LocalOperatorType, class TestFunctionType, class AnsatzFunctionType, class FieldType>\nclass Codim0OperatorAccumulateFunctor : public Stuff::Grid::Functor::Codim0<GridViewImp>\n{\n static_assert(\n std::is_base_of<LocalOperator::Codim0Interface<typename LocalOperatorType::Traits>, LocalOperatorType>::value,\n \"LocalOperatorType has to be derived from LocalOperator::Codim0Interface!\");\n static_assert(Stuff::is_localizable_function<TestFunctionType>::value,\n \"TestFunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(Stuff::is_localizable_function<AnsatzFunctionType>::value,\n \"AnsatzFunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n\n typedef Stuff::Grid::Functor::Codim0<GridViewImp> BaseType;\n typedef DSC::TmpMatricesStorage<FieldType> TmpMatricesProviderType;\n\npublic:\n typedef typename BaseType::GridViewType GridViewType;\n typedef typename BaseType::EntityType EntityType;\n\n Codim0OperatorAccumulateFunctor(const GridViewType& grd_vw, const LocalOperatorType& local_op,\n const TestFunctionType& test_function, const AnsatzFunctionType& ansatz_function)\n : grid_view_(grd_vw)\n , local_operator_(local_op)\n , test_function_(test_function)\n , ansatz_function_(ansatz_function)\n , result_(0)\n , finalized_(false)\n {\n \/\/ can not use make_unique here, at least clang does not get it\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator_.numTmpObjectsRequired()}, 1, 1));\n }\n\n virtual ~Codim0OperatorAccumulateFunctor() = default;\n\n FieldType compute_locally(const EntityType& entity)\n {\n assert(tmp_storage_->matrices().size() >= 2);\n assert(tmp_storage_->matrices()[0].size() >= 1);\n auto& local_operator_result = tmp_storage_->matrices()[0][0];\n auto& tmp_matrices = tmp_storage_->matrices()[1];\n \/\/ get the local functions\n const auto local_test_function = test_function_.local_function(entity);\n const auto local_ansatz_function = ansatz_function_.local_function(entity);\n \/\/ apply the local operator\n this->local_operator_.apply(*local_test_function, *local_ansatz_function, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() >= 1);\n assert(local_operator_result.cols() >= 1);\n return local_operator_result[0][0];\n } \/\/ ... compute_locally(...)\n\n virtual void apply_local(const EntityType& entity) override\n {\n *result_ += compute_locally(entity);\n }\n\n virtual void finalize() override\n {\n if (!finalized_) {\n finalized_result_ = result_.sum();\n finalized_result_ = grid_view_.comm().sum(finalized_result_);\n finalized_ = true;\n }\n } \/\/ ... finalize(...)\n\n FieldType result() const\n {\n if (!finalized_)\n DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, \"Call finalize() first!\");\n return finalized_result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const LocalOperatorType& local_operator_;\n const TestFunctionType& test_function_;\n const AnsatzFunctionType& ansatz_function_;\n DS::PerThreadValue<FieldType> result_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool finalized_;\n FieldType finalized_result_;\n}; \/\/ class Codim0OperatorAccumulateFunctor\n\n\n} \/\/ namespace LocalAssembler\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n<commit_msg>[assembler.local.codim0] make Codim0OperatorAccumulateFunctor copyable<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n#define DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n\n#include <vector>\n\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/common\/exceptions.hh>\n#include <dune\/stuff\/common\/parallel\/threadmanager.hh>\n#include <dune\/stuff\/common\/tmp-storage.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/grid\/walker\/functors.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localoperator\/interface.hh>\n#include <dune\/gdt\/localfunctional\/interface.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalAssembler {\n\n\ntemplate <class LocalOperatorImp>\nclass Codim0Matrix\n{\n static_assert(\n std::is_base_of<LocalOperator::Codim0Interface<typename LocalOperatorImp::Traits>, LocalOperatorImp>::value,\n \"LocalOperatorImp has to be derived from LocalOperator::Codim0Interface!\");\n\npublic:\n typedef LocalOperatorImp LocalOperatorType;\n\n explicit Codim0Matrix(const LocalOperatorType& op)\n : localOperator_(op)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localOperator_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam A Traits of the SpaceInterface implementation, representing the type of ansatzSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam M Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the\n * type of systemMatrix\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class A, class EntityType, class M, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const EntityType& entity,\n Dune::Stuff::LA::MatrixInterface<M, R>& systemMatrix,\n std::vector<std::vector<Dune::DynamicMatrix<R>>>& tmpLocalMatricesContainer,\n std::vector<Dune::DynamicVector<size_t>>& tmpIndicesContainer) const\n {\n \/\/ check\n assert(tmpLocalMatricesContainer.size() >= 1);\n assert(tmpLocalMatricesContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalMatricesContainer[1].size() >= localOperator_.numTmpObjectsRequired());\n assert(tmpIndicesContainer.size() >= 2);\n \/\/ get and clear matrix\n Dune::DynamicMatrix<R>& localMatrix = tmpLocalMatricesContainer[0][0];\n localMatrix *= 0.0;\n auto& tmpOperatorMatrices = tmpLocalMatricesContainer[1];\n \/\/ apply local operator (result is in localMatrix)\n localOperator_.apply(\n testSpace.base_function_set(entity), ansatzSpace.base_function_set(entity), localMatrix, tmpOperatorMatrices);\n \/\/ write local matrix to global\n Dune::DynamicVector<size_t>& globalRows = tmpIndicesContainer[0];\n Dune::DynamicVector<size_t>& globalCols = tmpIndicesContainer[1];\n const size_t rows = testSpace.mapper().numDofs(entity);\n const size_t cols = ansatzSpace.mapper().numDofs(entity);\n assert(globalRows.size() >= rows);\n assert(globalCols.size() >= cols);\n testSpace.mapper().globalIndices(entity, globalRows);\n ansatzSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < rows; ++ii) {\n const auto& localRow = localMatrix[ii];\n const size_t globalII = globalRows[ii];\n for (size_t jj = 0; jj < cols; ++jj) {\n const size_t globalJJ = globalCols[jj];\n systemMatrix.add_to_entry(globalII, globalJJ, localRow[jj]);\n }\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalOperatorType& localOperator_;\n}; \/\/ class Codim0Matrix\n\n\ntemplate <class LocalFunctionalImp>\nclass Codim0Vector\n{\n static_assert(\n std::is_base_of<LocalFunctional::Codim0Interface<typename LocalFunctionalImp::Traits>, LocalFunctionalImp>::value,\n \"LocalFunctionalImp has to be derived from LocalFunctional::Codim0Interface!\");\n\npublic:\n typedef LocalFunctionalImp LocalFunctionalType;\n\n explicit Codim0Vector(const LocalFunctionalType& func)\n : localFunctional_(func)\n {\n }\n\n const LocalFunctionalType& localFunctional() const\n {\n return localFunctional_;\n }\n\nprivate:\n static const size_t numTmpObjectsRequired_ = 1;\n\npublic:\n std::vector<size_t> numTmpObjectsRequired() const\n {\n return {numTmpObjectsRequired_, localFunctional_.numTmpObjectsRequired()};\n }\n\n \/**\n * \\tparam T Traits of the SpaceInterface implementation, representing the type of testSpace\n * \\tparam EntityType A model of Dune::Entity< 0 >\n * \\tparam V Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the\n * type of systemVector\n * \\tparam R RangeFieldType, i.e. double\n *\/\n template <class T, class EntityType, class V, class R>\n void assembleLocal(const SpaceInterface<T>& testSpace, const EntityType& entity,\n Dune::Stuff::LA::VectorInterface<V, R>& systemVector,\n std::vector<std::vector<Dune::DynamicVector<R>>>& tmpLocalVectorContainer,\n Dune::DynamicVector<size_t>& tmpIndices) const\n {\n \/\/ check\n assert(tmpLocalVectorContainer.size() >= 2);\n assert(tmpLocalVectorContainer[0].size() >= numTmpObjectsRequired_);\n assert(tmpLocalVectorContainer[1].size() >= localFunctional_.numTmpObjectsRequired());\n \/\/ get and clear vector\n auto& localVector = tmpLocalVectorContainer[0][0];\n localVector *= 0.0;\n auto& tmpFunctionalVectors = tmpLocalVectorContainer[1];\n \/\/ apply local functional (result is in localVector)\n localFunctional_.apply(testSpace.base_function_set(entity), localVector, tmpFunctionalVectors);\n \/\/ write local vector to global\n const size_t size = testSpace.mapper().numDofs(entity);\n assert(tmpIndices.size() >= size);\n testSpace.mapper().globalIndices(entity, tmpIndices);\n for (size_t ii = 0; ii < size; ++ii) {\n systemVector.add_to_entry(tmpIndices[ii], localVector[ii]);\n } \/\/ write local matrix to global\n } \/\/ ... assembleLocal(...)\n\nprivate:\n const LocalFunctionalType& localFunctional_;\n}; \/\/ class Codim0Vector\n\n\ntemplate <class GridViewImp, class LocalOperatorType, class TestFunctionType, class AnsatzFunctionType, class FieldType>\nclass Codim0OperatorAccumulateFunctor : public Stuff::Grid::Functor::Codim0<GridViewImp>\n{\n static_assert(\n std::is_base_of<LocalOperator::Codim0Interface<typename LocalOperatorType::Traits>, LocalOperatorType>::value,\n \"LocalOperatorType has to be derived from LocalOperator::Codim0Interface!\");\n static_assert(Stuff::is_localizable_function<TestFunctionType>::value,\n \"TestFunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(Stuff::is_localizable_function<AnsatzFunctionType>::value,\n \"AnsatzFunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n\n typedef Codim0OperatorAccumulateFunctor<GridViewImp, LocalOperatorType, TestFunctionType, AnsatzFunctionType,\n FieldType> ThisType;\n typedef Stuff::Grid::Functor::Codim0<GridViewImp> BaseType;\n typedef DSC::TmpMatricesStorage<FieldType> TmpMatricesProviderType;\n\npublic:\n typedef typename BaseType::GridViewType GridViewType;\n typedef typename BaseType::EntityType EntityType;\n\n Codim0OperatorAccumulateFunctor(const GridViewType& grd_vw, const LocalOperatorType& local_op,\n const TestFunctionType& test_function, const AnsatzFunctionType& ansatz_function)\n : grid_view_(grd_vw)\n , local_operator_(local_op)\n , test_function_(test_function)\n , ansatz_function_(ansatz_function)\n , result_(0)\n , finalized_(false)\n {\n \/\/ can not use make_unique here, at least clang does not get it\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator_.numTmpObjectsRequired()}, 1, 1));\n }\n\n Codim0OperatorAccumulateFunctor(const ThisType& other)\n : grid_view_(other.grid_view_)\n , local_operator_(other.local_operator_)\n , test_function_(other.test_function_)\n , ansatz_function_(other.ansatz_function_)\n , result_(0)\n , finalized_(other.finalized_)\n {\n \/\/ can not use make_unique here, at least clang does not get it\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator_.numTmpObjectsRequired()}, 1, 1));\n result_ = other.result_;\n }\n\n virtual ~Codim0OperatorAccumulateFunctor() = default;\n\n FieldType compute_locally(const EntityType& entity)\n {\n assert(tmp_storage_->matrices().size() >= 2);\n assert(tmp_storage_->matrices()[0].size() >= 1);\n auto& local_operator_result = tmp_storage_->matrices()[0][0];\n auto& tmp_matrices = tmp_storage_->matrices()[1];\n \/\/ get the local functions\n const auto local_test_function = test_function_.local_function(entity);\n const auto local_ansatz_function = ansatz_function_.local_function(entity);\n \/\/ apply the local operator\n this->local_operator_.apply(*local_test_function, *local_ansatz_function, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() >= 1);\n assert(local_operator_result.cols() >= 1);\n return local_operator_result[0][0];\n } \/\/ ... compute_locally(...)\n\n virtual void apply_local(const EntityType& entity) override\n {\n *result_ += compute_locally(entity);\n }\n\n virtual void finalize() override\n {\n if (!finalized_) {\n finalized_result_ = result_.sum();\n finalized_result_ = grid_view_.comm().sum(finalized_result_);\n finalized_ = true;\n }\n } \/\/ ... finalize(...)\n\n FieldType result() const\n {\n if (!finalized_)\n DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, \"Call finalize() first!\");\n return finalized_result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const LocalOperatorType& local_operator_;\n const TestFunctionType& test_function_;\n const AnsatzFunctionType& ansatz_function_;\n DS::PerThreadValue<FieldType> result_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool finalized_;\n FieldType finalized_result_;\n}; \/\/ class Codim0OperatorAccumulateFunctor\n\n\n} \/\/ namespace LocalAssembler\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_ASSEMLBER_LOCAL_CODIM0_HH\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2013 Truphone\n *\/\n#include \"ListCommand.h\"\n\n#include <QString>\n#include <QList>\n#include <QObject>\n\n#include <bb\/cascades\/ListView>\n\n#include \"Connection.h\"\n\nusing bb::cascades::ListView;\n\nnamespace truphone\n{\nnamespace test\n{\nnamespace cascades\n{\n const QString ListCommand::CMD_NAME = \"list\";\n\n ListCommand::ListCommand(Connection * const socket,\n QObject* parent)\n : Command(parent),\n client(socket),\n scenePane(bb::cascades::Application::instance()->scene())\n {\n }\n\n ListCommand::~ListCommand()\n {\n }\n\n bool ListCommand::executeCommand(QStringList * const arguments)\n {\n if (arguments->size() > 1)\n {\n const QString listViewName = arguments->first();\n arguments->removeFirst();\n ListView * const listView = scenePane->findChild<ListView*>(listViewName);\n if (listView)\n {\n const QString command = arguments->first();\n arguments->removeFirst();\n if (command == \"count\")\n {\n const int s = listView->dataModel()->childCount(listView->rootIndexPath());\n this->client->write(QString::number(s).toUtf8().constData());\n this->client->write(\"\\r\\n\");\n }\n else\n {\n this->client->write(\"ERROR: Unknown list command\\r\\n\");\n }\n }\n else\n {\n this->client->write(\"ERROR: Couldn't find the listview\\r\\n\");\n }\n }\n else\n {\n this->client->write(\"ERROR: Not enough arguments, sleep <timeInMs>\\r\\n\");\n }\n return false;\n }\n\n void ListCommand::showHelp()\n {\n this->client->write(\"> list....?\\r\\n\");\n }\n} \/\/ namespace cascades\n} \/\/ namespace test\n} \/\/ namespace truphone\n<commit_msg>Fix up the list count command.<commit_after>\/**\n * Copyright 2013 Truphone\n *\/\n#include \"ListCommand.h\"\n\n#include <QString>\n#include <QList>\n#include <QObject>\n\n#include <bb\/cascades\/ListView>\n\n#include \"Connection.h\"\n\nusing bb::cascades::ListView;\n\nnamespace truphone\n{\nnamespace test\n{\nnamespace cascades\n{\n const QString ListCommand::CMD_NAME = \"list\";\n\n ListCommand::ListCommand(Connection * const socket,\n QObject* parent)\n : Command(parent),\n client(socket),\n scenePane(bb::cascades::Application::instance()->scene())\n {\n }\n\n ListCommand::~ListCommand()\n {\n }\n\n bool ListCommand::executeCommand(QStringList * const arguments)\n {\n bool ret = false;\n if (arguments->size() > 1)\n {\n const QString listViewName = arguments->first();\n arguments->removeFirst();\n ListView * const listView = scenePane->findChild<ListView*>(listViewName);\n if (listView)\n {\n const QString command = arguments->first();\n arguments->removeFirst();\n if (command == \"count\" && !arguments->isEmpty())\n {\n bool ok = false;\n const int expected = arguments->first().toInt(&ok);\n if (ok)\n {\n const int actual =\n listView->dataModel()->childCount(listView->rootIndexPath());\n ret = (actual == expected);\n }\n else\n {\n this->client->write(\"ERROR: Expected list size wasn't an integer\\r\\n\");\n }\n }\n else\n {\n this->client->write(\"ERROR: Unknown list command\\r\\n\");\n }\n }\n else\n {\n this->client->write(\"ERROR: Couldn't find the listview\\r\\n\");\n }\n }\n else\n {\n this->client->write(\"ERROR: Not enough arguments, sleep <timeInMs>\\r\\n\");\n }\n return ret;\n }\n\n void ListCommand::showHelp()\n {\n this->client->write(\"> list <list> count <expectedSize>\\r\\n\");\n }\n} \/\/ namespace cascades\n} \/\/ namespace test\n} \/\/ namespace truphone\n<|endoftext|>"} {"text":"<commit_before>#include <dune\/multiscale\/test\/test_common.hxx>\n\n#include <dune\/stuff\/functions\/global.hh>\n#include <dune\/stuff\/common\/float_cmp.hh>\n#include <dune\/gdt\/operators\/projections.hh>\n#include <dune\/gdt\/products\/l2.hh>\n#include <functional>\n#include <dune\/multiscale\/msfem\/localproblems\/localsolutionmanager.hh>\n#include <dune\/multiscale\/common\/heterogenous.hh>\n\nusing namespace Dune::GDT;\n\nstruct Projection : public GridAndSpaces {\n typedef DS::FunctionTypeGenerator<MsFEMTraits::LocalConstantFunctionType, DS::GlobalLambdaFunction>::type Lambda;\n\n LocalsolutionProxy::CorrectionsMapType fill_local_corrections(const Lambda& lambda,\n const LocalGridList& localgrid_list) {\n LocalsolutionProxy::CorrectionsMapType local_corrections;\n for (auto& coarse_entity : DSC::entityRange(coarseSpace.grid_view())) {\n LocalSolutionManager localSolManager(coarseSpace, coarse_entity, localgrid_list);\n auto& coarse_indexset = coarseSpace.grid_view().grid().leafIndexSet();\n const auto coarse_index = coarse_indexset.index(coarse_entity);\n local_corrections[coarse_index] =\n DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(localSolManager.space(), \" \");\n GDT::project(lambda, *local_corrections[coarse_index]);\n }\n return local_corrections;\n }\n\n void project() {\n LocalGridList localgrid_list(coarseSpace);\n const double constant(1);\n Lambda lambda([&](CommonTraits::DomainType \/*x*\/) { return constant;}, 0 );\n auto local_corrections = fill_local_corrections(lambda, localgrid_list);\n\n LocalsolutionProxy proxy(std::move(local_corrections), coarseSpace, localgrid_list);\n\n CommonTraits::DiscreteFunctionType fine_scale_part(fineSpace);\n MsFEMProjection::project(proxy, fine_scale_part, proxy.search());\n\n const auto norm = std::sqrt(Dune::GDT::Products::L2< CommonTraits::GridViewType >(fineSpace.grid_view())\n .induced_norm(fine_scale_part));\n EXPECT_DOUBLE_EQ(norm, constant);\n }\n};\n\nTEST_P(Projection, Project) {\n this->project();\n}\n\n\nstatic const auto common_values = CommonTraits::world_dim < 3\n \/\/ Values need to have number of elements\n ? testing::Values(p_small\/*, p_large, p_aniso, p_wover, p_fail*\/)\n : testing::Values(p_small\/*, p_minimal, p_minimal, p_minimal, p_minimal*\/);\n\nINSTANTIATE_TEST_CASE_P( TestNameB, Projection, common_values);\n\n<commit_msg>[tests] finally use the right project methods to avoid deprecation wrng<commit_after>#include <dune\/multiscale\/test\/test_common.hxx>\n\n#include <dune\/stuff\/functions\/global.hh>\n#include <dune\/stuff\/common\/float_cmp.hh>\n#include <dune\/gdt\/operators\/projections.hh>\n#include <dune\/gdt\/products\/l2.hh>\n#include <functional>\n#include <dune\/multiscale\/msfem\/localproblems\/localsolutionmanager.hh>\n#include <dune\/multiscale\/common\/heterogenous.hh>\n\nusing namespace Dune::GDT;\n\nstruct Projection : public GridAndSpaces {\n typedef DS::FunctionTypeGenerator<MsFEMTraits::LocalConstantFunctionType, DS::GlobalLambdaFunction>::type Lambda;\n\n LocalsolutionProxy::CorrectionsMapType fill_local_corrections(const Lambda& lambda,\n const LocalGridList& localgrid_list) {\n LocalsolutionProxy::CorrectionsMapType local_corrections;\n for (auto& coarse_entity : DSC::entityRange(coarseSpace.grid_view())) {\n LocalSolutionManager localSolManager(coarseSpace, coarse_entity, localgrid_list);\n auto& coarse_indexset = coarseSpace.grid_view().grid().leafIndexSet();\n const auto coarse_index = coarse_indexset.index(coarse_entity);\n local_corrections[coarse_index] =\n DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(localSolManager.space(), \" \");\n Dune::GDT::project(lambda, *local_corrections[coarse_index]);\n }\n return local_corrections;\n }\n\n void project() {\n LocalGridList localgrid_list(coarseSpace);\n const double constant(1);\n Lambda lambda([&](CommonTraits::DomainType \/*x*\/) { return constant;}, 0 );\n auto local_corrections = fill_local_corrections(lambda, localgrid_list);\n\n LocalsolutionProxy proxy(std::move(local_corrections), coarseSpace, localgrid_list);\n\n CommonTraits::DiscreteFunctionType fine_scale_part(fineSpace);\n MsFEMProjection::project(proxy, fine_scale_part, proxy.search());\n\n const auto norm = std::sqrt(Dune::GDT::Products::L2< CommonTraits::GridViewType >(fineSpace.grid_view())\n .induced_norm(fine_scale_part));\n EXPECT_DOUBLE_EQ(norm, constant);\n }\n};\n\nTEST_P(Projection, Project) {\n this->project();\n}\n\n\nstatic const auto common_values = CommonTraits::world_dim < 3\n \/\/ Values need to have number of elements\n ? testing::Values(p_small\/*, p_large, p_aniso, p_wover, p_fail*\/)\n : testing::Values(p_small\/*, p_minimal, p_minimal, p_minimal, p_minimal*\/);\n\nINSTANTIATE_TEST_CASE_P( TestNameB, Projection, common_values);\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n\/\/ -- BEGIN LICENSE BLOCK ----------------------------------------------\n\/\/ -- END LICENSE BLOCK ------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/*!\\file\n *\n * \\author Felix Mauch mauch@fzi.de\n * \\date 2019-03-11\n *\n *\/\n\/\/----------------------------------------------------------------------\n\n#include <gtest\/gtest.h>\n#include <ur_calibration\/calibration.h>\n\nnamespace\n{\nbool isApproximately(const double val1, const double val2, const double precision)\n{\n return std::abs(val1 - val2) < precision;\n}\n\ntemplate <class Scalar_, int dim_>\nvoid doubleEqVec(const Eigen::Matrix<Scalar_, dim_, 1> vec1, const Eigen::Matrix<Scalar_, dim_, 1> vec2,\n const double precision)\n{\n for (size_t i = 0; i < dim_; ++i)\n {\n EXPECT_NEAR(vec1[i], vec2[i], precision);\n }\n}\n\nTEST(UrRtdeDriver, ur10_fw_kinematics)\n{\n DHRobot my_robot;\n const double pi = std::atan(1) * 4;\n \/\/ const double pi = 1.570796327 * 2.0;\n \/\/ const double pi = M_PI;\n\n \/\/ This is an ideal UR10\n \/\/ clang-format off\n my_robot.segments_.push_back(DHSegment(0.1273 , 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0 , -0.612 , 0 , 0));\n my_robot.segments_.push_back(DHSegment(0 , -0.5723, 0 , 0.0));\n my_robot.segments_.push_back(DHSegment(0.163841, 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.1157 , 0 , 0 , -pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.0922 , 0 , 0 , 0));\n \/\/ clang-format on\n\n Calibration calibration(my_robot);\n\n Eigen::Matrix<double, 6, 1> jointvalues;\n Eigen::Vector3d expected_position;\n Eigen::Quaterniond expected_orientation;\n {\n jointvalues << 0, 0, 0, 0, 0, 0;\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n EXPECT_DOUBLE_EQ(fk(0, 3), my_robot.segments_[1].a_ + my_robot.segments_[2].a_);\n EXPECT_DOUBLE_EQ(fk(1, 3), -1 * (my_robot.segments_[3].d_ + my_robot.segments_[5].d_));\n EXPECT_DOUBLE_EQ(fk(2, 3), my_robot.segments_[0].d_ - my_robot.segments_[4].d_);\n }\n\n {\n jointvalues << M_PI_2, -M_PI_4, M_PI_2, -M_PI_4, 0, 0;\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n expected_position << my_robot.segments_[3].d_ + my_robot.segments_[5].d_,\n my_robot.segments_[1].a_ \/ std::sqrt(2) + my_robot.segments_[2].a_ \/ std::sqrt(2),\n my_robot.segments_[0].d_ - my_robot.segments_[1].a_ \/ std::sqrt(2) + my_robot.segments_[2].a_ \/ std::sqrt(2) -\n my_robot.segments_[4].d_;\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-16);\n }\n {\n jointvalues << -1.6007002035724084976209269370884, -1.7271001974688928726209269370884,\n -2.2029998938189905288709269370884, -0.80799991289247685699592693708837, 1.59510004520416259765625,\n -0.03099996248354131012092693708837;\n expected_position << -0.179925914147547, -0.606869755162764, 0.230789102067257;\n\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-10);\n }\n {\n jointvalues << 1.32645022869110107421875, 2.426007747650146484375, 5.951572895050048828125,\n 1.27409040927886962890625, -0.54105216661562138824592693708837, 0.122173048555850982666015625;\n expected_position << 0.39922988003280424074148413637886, 0.59688365069340565405298093537567,\n -0.6677819040276375961440180617501;\n\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-9);\n }\n}\n\nTEST(UrRtdeDriver, calibration)\n{\n \/\/ This test compares the forward kinematics of the model constructed from uncorrected\n \/\/ parameters with the one from the corrected parameters. They are tested against random\n \/\/ joint values and should be equal (in a numeric sense).\n\n DHRobot my_robot;\n const double pi = std::atan(1) * 4;\n\n \/\/ This is an ideal UR10\n \/\/ clang-format off\n \/\/ d, a, theta, alpha\n my_robot.segments_.push_back(DHSegment(0.1273 , 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0 , -0.612 , 0 , 0));\n my_robot.segments_.push_back(DHSegment(0 , -0.5723, 0 , 0.0));\n my_robot.segments_.push_back(DHSegment(0.163841, 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.1157 , 0 , 0 , -pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.0922 , 0 , 0 , 0));\n \/\/ clang-format on\n DHRobot my_robot_calibration;\n \/\/ clang-format off\n \/\/ d, a, theta, alpha\n my_robot_calibration.segments_.push_back(DHSegment( 0.00065609212979853 , 4.6311376834935676e-05 , -7.290070070824746e-05 , 0.000211987863869334 ));\n my_robot_calibration.segments_.push_back(DHSegment( 1.4442162376284788 , -0.00012568315331862312 , -0.01713897289704999 , -0.0072553625957652995));\n my_robot_calibration.segments_.push_back(DHSegment( 0.854147723854608 , 0.00186216581161458 , -0.03707159413492756 , -0.013483226769541364 ));\n my_robot_calibration.segments_.push_back(DHSegment(-2.2989425877563705 , 9.918593870679266e-05 , 0.054279462160583214 , 0.0013495820227329425 ));\n my_robot_calibration.segments_.push_back(DHSegment(-1.573498686836816e-05 , 4.215462720453189e-06 , 1.488984257025741e-07 , -0.001263136163679901 ));\n my_robot_calibration.segments_.push_back(DHSegment( 1.9072435590711256e-05 , 0 , 1.551499479707493e-05 , 0 ));\n \/\/ clang-format on\n\n Eigen::Matrix<double, 6, 1> jointvalues;\n jointvalues << 0, 0, 0, 0, 0, 0;\n\n for (size_t i = 0; i < 1000; ++i)\n {\n Calibration calibration(my_robot + my_robot_calibration);\n jointvalues = 2 * pi * Eigen::Matrix<double, 6, 1>::Random();\n Eigen::Matrix4d fk_orig = calibration.calcForwardKinematics(jointvalues);\n Eigen::Matrix3d rot_mat_orig = fk_orig.topLeftCorner(3, 3);\n Eigen::Quaterniond rot_orig(rot_mat_orig);\n calibration.correctChain();\n Eigen::Matrix4d fk_corrected = calibration.calcForwardKinematics(jointvalues);\n Eigen::Matrix3d rot_mat_corrected = fk_corrected.topLeftCorner(3, 3);\n Eigen::Quaterniond rot_corrected(rot_mat_corrected);\n double angle_error = std::abs(rot_orig.angularDistance(rot_corrected));\n EXPECT_NEAR(fk_orig(0, 3), fk_corrected(0, 3), 1e-12);\n EXPECT_NEAR(fk_orig(1, 3), fk_corrected(1, 3), 1e-12);\n EXPECT_NEAR(fk_orig(2, 3), fk_corrected(2, 3), 1e-12);\n EXPECT_NEAR(angle_error, 0.0, 1e-12);\n }\n}\n} \/\/ namespace\n\nint main(int argc, char* argv[])\n{\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n}\n<commit_msg>corrected default accuracy<commit_after>\/\/ this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n\/\/ -- BEGIN LICENSE BLOCK ----------------------------------------------\n\/\/ -- END LICENSE BLOCK ------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/*!\\file\n *\n * \\author Felix Mauch mauch@fzi.de\n * \\date 2019-03-11\n *\n *\/\n\/\/----------------------------------------------------------------------\n\n#include <gtest\/gtest.h>\n#include <ur_calibration\/calibration.h>\n\nnamespace\n{\nbool isApproximately(const double val1, const double val2, const double precision)\n{\n return std::abs(val1 - val2) < precision;\n}\n\ntemplate <class Scalar_, int dim_>\nvoid doubleEqVec(const Eigen::Matrix<Scalar_, dim_, 1> vec1, const Eigen::Matrix<Scalar_, dim_, 1> vec2,\n const double precision)\n{\n for (size_t i = 0; i < dim_; ++i)\n {\n EXPECT_NEAR(vec1[i], vec2[i], precision);\n }\n}\n\nTEST(UrRtdeDriver, ur10_fw_kinematics)\n{\n DHRobot my_robot;\n const double pi = std::atan(1) * 4;\n \/\/ const double pi = 1.570796327 * 2.0;\n \/\/ const double pi = M_PI;\n\n \/\/ This is an ideal UR10\n \/\/ clang-format off\n my_robot.segments_.push_back(DHSegment(0.1273 , 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0 , -0.612 , 0 , 0));\n my_robot.segments_.push_back(DHSegment(0 , -0.5723, 0 , 0.0));\n my_robot.segments_.push_back(DHSegment(0.163941, 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.1157 , 0 , 0 , -pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.0922 , 0 , 0 , 0));\n \/\/ clang-format on\n\n Calibration calibration(my_robot);\n\n Eigen::Matrix<double, 6, 1> jointvalues;\n Eigen::Vector3d expected_position;\n Eigen::Quaterniond expected_orientation;\n {\n jointvalues << 0, 0, 0, 0, 0, 0;\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n EXPECT_DOUBLE_EQ(fk(0, 3), my_robot.segments_[1].a_ + my_robot.segments_[2].a_);\n EXPECT_DOUBLE_EQ(fk(1, 3), -1 * (my_robot.segments_[3].d_ + my_robot.segments_[5].d_));\n EXPECT_DOUBLE_EQ(fk(2, 3), my_robot.segments_[0].d_ - my_robot.segments_[4].d_);\n }\n\n {\n jointvalues << M_PI_2, -M_PI_4, M_PI_2, -M_PI_4, 0, 0;\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n expected_position << my_robot.segments_[3].d_ + my_robot.segments_[5].d_,\n my_robot.segments_[1].a_ \/ std::sqrt(2) + my_robot.segments_[2].a_ \/ std::sqrt(2),\n my_robot.segments_[0].d_ - my_robot.segments_[1].a_ \/ std::sqrt(2) + my_robot.segments_[2].a_ \/ std::sqrt(2) -\n my_robot.segments_[4].d_;\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-16);\n }\n {\n jointvalues << -1.6007002035724084976209269370884, -1.7271001974688928726209269370884,\n -2.2029998938189905288709269370884, -0.80799991289247685699592693708837, 1.59510004520416259765625,\n -0.03099996248354131012092693708837;\n expected_position << -0.179925914147547, -0.606869755162764, 0.230789102067257;\n\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-10);\n }\n {\n jointvalues << 1.32645022869110107421875, 2.426007747650146484375, 5.951572895050048828125,\n 1.27409040927886962890625, -0.54105216661562138824592693708837, 0.122173048555850982666015625;\n expected_position << 0.39922988003280424074148413637886, 0.59688365069340565405298093537567,\n -0.6677819040276375961440180617501;\n\n Eigen::Matrix4d fk = calibration.calcForwardKinematics(jointvalues);\n\n doubleEqVec<double, 3>(expected_position, fk.topRightCorner(3, 1), 1e-9);\n }\n}\n\nTEST(UrRtdeDriver, calibration)\n{\n \/\/ This test compares the forward kinematics of the model constructed from uncorrected\n \/\/ parameters with the one from the corrected parameters. They are tested against random\n \/\/ joint values and should be equal (in a numeric sense).\n\n DHRobot my_robot;\n const double pi = std::atan(1) * 4;\n\n \/\/ This is an ideal UR10\n \/\/ clang-format off\n \/\/ d, a, theta, alpha\n my_robot.segments_.push_back(DHSegment(0.1273 , 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0 , -0.612 , 0 , 0));\n my_robot.segments_.push_back(DHSegment(0 , -0.5723, 0 , 0.0));\n my_robot.segments_.push_back(DHSegment(0.163941, 0 , 0 , pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.1157 , 0 , 0 , -pi \/ 2));\n my_robot.segments_.push_back(DHSegment(0.0922 , 0 , 0 , 0));\n \/\/ clang-format on\n DHRobot my_robot_calibration;\n \/\/ clang-format off\n \/\/ d, a, theta, alpha\n my_robot_calibration.segments_.push_back(DHSegment( 0.00065609212979853 , 4.6311376834935676e-05 , -7.290070070824746e-05 , 0.000211987863869334 ));\n my_robot_calibration.segments_.push_back(DHSegment( 1.4442162376284788 , -0.00012568315331862312 , -0.01713897289704999 , -0.0072553625957652995));\n my_robot_calibration.segments_.push_back(DHSegment( 0.854147723854608 , 0.00186216581161458 , -0.03707159413492756 , -0.013483226769541364 ));\n my_robot_calibration.segments_.push_back(DHSegment(-2.2989425877563705 , 9.918593870679266e-05 , 0.054279462160583214 , 0.0013495820227329425 ));\n my_robot_calibration.segments_.push_back(DHSegment(-1.573498686836816e-05 , 4.215462720453189e-06 , 1.488984257025741e-07 , -0.001263136163679901 ));\n my_robot_calibration.segments_.push_back(DHSegment( 1.9072435590711256e-05 , 0 , 1.551499479707493e-05 , 0 ));\n \/\/ clang-format on\n\n Eigen::Matrix<double, 6, 1> jointvalues;\n jointvalues << 0, 0, 0, 0, 0, 0;\n\n for (size_t i = 0; i < 1000; ++i)\n {\n Calibration calibration(my_robot + my_robot_calibration);\n jointvalues = 2 * pi * Eigen::Matrix<double, 6, 1>::Random();\n Eigen::Matrix4d fk_orig = calibration.calcForwardKinematics(jointvalues);\n Eigen::Matrix3d rot_mat_orig = fk_orig.topLeftCorner(3, 3);\n Eigen::Quaterniond rot_orig(rot_mat_orig);\n calibration.correctChain();\n Eigen::Matrix4d fk_corrected = calibration.calcForwardKinematics(jointvalues);\n Eigen::Matrix3d rot_mat_corrected = fk_corrected.topLeftCorner(3, 3);\n Eigen::Quaterniond rot_corrected(rot_mat_corrected);\n double angle_error = std::abs(rot_orig.angularDistance(rot_corrected));\n EXPECT_NEAR(fk_orig(0, 3), fk_corrected(0, 3), 1e-12);\n EXPECT_NEAR(fk_orig(1, 3), fk_corrected(1, 3), 1e-12);\n EXPECT_NEAR(fk_orig(2, 3), fk_corrected(2, 3), 1e-12);\n EXPECT_NEAR(angle_error, 0.0, 1e-12);\n }\n}\n} \/\/ namespace\n\nint main(int argc, char* argv[])\n{\n ::testing::InitGoogleTest(&argc, argv);\n\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <pcl\/features\/normal_3d.h>\n#include <pcl\/io\/pcd_io.h>\n\n#include <vtkLidarScanner.h>\n#include <vtkPolyData.h>\n#include <vtkSmartPointer.h>\n#include <vtkTransform.h>\n\n#include \"proctor\/proctor.h\"\n#include \"proctor\/scanner.h\"\n\n#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))\n#include \"SyntheticLidarScanner\/vtkRay.cxx\"\n#include \"SyntheticLidarScanner\/vtkLidarPoint.cxx\"\n#include \"SyntheticLidarScanner\/vtkLidarScanner.cxx\"\n#endif\n\n\nnamespace pcl {\n namespace proctor {\n \/** convert radians to degrees. thanks a lot, vtk *\/\n template <typename T>\n static inline T deg(T rad) {\n return rad \/ M_PI * 180;\n }\n\n \/** prepare the transform to use for a scan (camera, not object) *\/\n static vtkSmartPointer<vtkTransform> compute_transform(Scanner::Scan scan, Model &model) {\n vtkSmartPointer<vtkTransform> spt = vtkSmartPointer<vtkTransform>::New();\n spt->Translate(model.cx, model.cy, model.cz);\n spt->RotateY(-deg(scan.phi));\n spt->RotateX(-deg(scan.theta));\n spt->Translate(0, 0, Scanner::distance_multiplier * model.scale);\n spt->RotateX(-90); \/\/ the default is looking in the +y direction. rotate to -z direction.\n return spt;\n }\n\n \/** simulate lidar scanning to get a point cloud (without normals) *\/\n static PointCloud<PointXYZ>::Ptr compute_pcxyz(Model &model, vtkSmartPointer<vtkTransform> transform) {\n \/\/ TODO: investigate replacing vtkLidarScanner with vtkRenderWindow::GetZbufferData\n \/\/ I think this function leaks memory.\n PointCloud<PointXYZ>::Ptr pcxyz (new PointCloud<PointXYZ>());\n vtkLidarScanner *ls = vtkLidarScanner::New();\n vtkPolyData *pd = vtkPolyData::New();\n\n ls->SetThetaSpan(Scanner::fov_y);\n ls->SetPhiSpan(Scanner::fov_x);\n ls->SetNumberOfThetaPoints(Scanner::res_y);\n ls->SetNumberOfPhiPoints(Scanner::res_x);\n ls->SetTransform(transform);\n ls->SetInputConnection(model.mesh->GetProducerPort());\n ls->Update();\n\n ls->GetValidOutputPoints(pd);\n float (*points)[3] = reinterpret_cast<float (*)[3]>(vtkFloatArray::SafeDownCast(pd->GetPoints()->GetData())->GetPointer(0));\n int num_points = pd->GetPoints()->GetData()->GetNumberOfTuples();\n pcxyz->points.resize(num_points);\n for (int i = 0; i < num_points; i++) {\n pcxyz->points[i].x = points[i][0];\n pcxyz->points[i].y = points[i][1];\n pcxyz->points[i].z = points[i][2];\n }\n\n ls->Delete();\n pd->Delete();\n return pcxyz;\n }\n\n \/** estimate the normals of a point cloud *\/\n static PointCloud<Normal>::Ptr compute_pcn(PointCloud<PointXYZ>::ConstPtr in, float vx, float vy, float vz) {\n PointCloud<Normal>::Ptr pcn (new PointCloud<Normal>());\n NormalEstimation<PointXYZ, Normal> ne;\n search::KdTree<PointXYZ>::Ptr kdt (new search::KdTree<PointXYZ>());\n ne.setInputCloud(in);\n ne.setSearchMethod(kdt);\n ne.setKSearch(20);\n ne.setViewPoint(vx, vy, vz);\n ne.compute(*pcn);\n return pcn;\n }\n\n \/** Scanner *\/\n const float Scanner::distance_multiplier = 3.0f;\n const double Scanner::fov_x = M_PI \/ 3;\n const double Scanner::fov_y = M_PI \/ 4;\n const unsigned int Scanner::res_x = 320;\n const unsigned int Scanner::res_y = 240;\n\n PointCloud<PointNormal>::Ptr Scanner::getCloud(Scan scan, Model &model) {\n PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());\n vtkSmartPointer<vtkTransform> transform = compute_transform(scan, model);\n PointCloud<PointXYZ>::Ptr pcxyz = compute_pcxyz(model, transform);\n float v[3];\n transform->GetPosition(v);\n PointCloud<Normal>::Ptr pcn = compute_pcn(pcxyz, v[0], v[1], v[2]);\n concatenateFields(*pcxyz, *pcn, *cloud);\n return cloud;\n }\n\n PointCloud<PointNormal>::Ptr Scanner::getCloudCached(int mi, int ti, int pi, Model &model) {\n Scan scan = {\n mi,\n Proctor::theta_start + ti * Proctor::theta_step,\n Proctor::phi_start + pi * Proctor::phi_step\n };\n char name[22];\n sprintf(name, \"scan_%04d_%03.0f_%03.0f.pcd\", mi, deg(scan.theta), deg(scan.phi));\n if (ifstream(name)) {\n PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());\n io::loadPCDFile(name, *cloud);\n return cloud;\n } else {\n PointCloud<PointNormal>::Ptr cloud = getCloud(scan, Proctor::models[mi]);\n io::savePCDFileBinary(name, *cloud);\n return cloud;\n }\n }\n }\n}\n<commit_msg>made vtkLidarScanner available only in VTK 5.8<commit_after>#include <pcl\/features\/normal_3d.h>\n#include <pcl\/io\/pcd_io.h>\n\n#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))\n#include <vtkLidarScanner.h>\n#endif\n#include <vtkPolyData.h>\n#include <vtkSmartPointer.h>\n#include <vtkTransform.h>\n\n#include \"proctor\/proctor.h\"\n#include \"proctor\/scanner.h\"\n\n#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))\n#include \"SyntheticLidarScanner\/vtkRay.cxx\"\n#include \"SyntheticLidarScanner\/vtkLidarPoint.cxx\"\n#include \"SyntheticLidarScanner\/vtkLidarScanner.cxx\"\n#endif\n\n\nnamespace pcl {\n namespace proctor {\n \/** convert radians to degrees. thanks a lot, vtk *\/\n template <typename T>\n static inline T deg(T rad) {\n return rad \/ M_PI * 180;\n }\n\n \/** prepare the transform to use for a scan (camera, not object) *\/\n static vtkSmartPointer<vtkTransform> compute_transform(Scanner::Scan scan, Model &model) {\n vtkSmartPointer<vtkTransform> spt = vtkSmartPointer<vtkTransform>::New();\n spt->Translate(model.cx, model.cy, model.cz);\n spt->RotateY(-deg(scan.phi));\n spt->RotateX(-deg(scan.theta));\n spt->Translate(0, 0, Scanner::distance_multiplier * model.scale);\n spt->RotateX(-90); \/\/ the default is looking in the +y direction. rotate to -z direction.\n return spt;\n }\n\n \/** simulate lidar scanning to get a point cloud (without normals) *\/\n static PointCloud<PointXYZ>::Ptr compute_pcxyz(Model &model, vtkSmartPointer<vtkTransform> transform) {\n \/\/ TODO: investigate replacing vtkLidarScanner with vtkRenderWindow::GetZbufferData\n \/\/ I think this function leaks memory.\n PointCloud<PointXYZ>::Ptr pcxyz (new PointCloud<PointXYZ>());\n#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))\n vtkLidarScanner *ls = vtkLidarScanner::New();\n vtkPolyData *pd = vtkPolyData::New();\n\n ls->SetThetaSpan(Scanner::fov_y);\n ls->SetPhiSpan(Scanner::fov_x);\n ls->SetNumberOfThetaPoints(Scanner::res_y);\n ls->SetNumberOfPhiPoints(Scanner::res_x);\n ls->SetTransform(transform);\n ls->SetInputConnection(model.mesh->GetProducerPort());\n ls->Update();\n\n ls->GetValidOutputPoints(pd);\n float (*points)[3] = reinterpret_cast<float (*)[3]>(vtkFloatArray::SafeDownCast(pd->GetPoints()->GetData())->GetPointer(0));\n int num_points = pd->GetPoints()->GetData()->GetNumberOfTuples();\n pcxyz->points.resize(num_points);\n for (int i = 0; i < num_points; i++) {\n pcxyz->points[i].x = points[i][0];\n pcxyz->points[i].y = points[i][1];\n pcxyz->points[i].z = points[i][2];\n }\n\n ls->Delete();\n pd->Delete();\n#endif\n return pcxyz;\n }\n\n \/** estimate the normals of a point cloud *\/\n static PointCloud<Normal>::Ptr compute_pcn(PointCloud<PointXYZ>::ConstPtr in, float vx, float vy, float vz) {\n PointCloud<Normal>::Ptr pcn (new PointCloud<Normal>());\n NormalEstimation<PointXYZ, Normal> ne;\n search::KdTree<PointXYZ>::Ptr kdt (new search::KdTree<PointXYZ>());\n ne.setInputCloud(in);\n ne.setSearchMethod(kdt);\n ne.setKSearch(20);\n ne.setViewPoint(vx, vy, vz);\n ne.compute(*pcn);\n return pcn;\n }\n\n \/** Scanner *\/\n const float Scanner::distance_multiplier = 3.0f;\n const double Scanner::fov_x = M_PI \/ 3;\n const double Scanner::fov_y = M_PI \/ 4;\n const unsigned int Scanner::res_x = 320;\n const unsigned int Scanner::res_y = 240;\n\n PointCloud<PointNormal>::Ptr Scanner::getCloud(Scan scan, Model &model) {\n PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());\n vtkSmartPointer<vtkTransform> transform = compute_transform(scan, model);\n PointCloud<PointXYZ>::Ptr pcxyz = compute_pcxyz(model, transform);\n float v[3];\n transform->GetPosition(v);\n PointCloud<Normal>::Ptr pcn = compute_pcn(pcxyz, v[0], v[1], v[2]);\n concatenateFields(*pcxyz, *pcn, *cloud);\n return cloud;\n }\n\n PointCloud<PointNormal>::Ptr Scanner::getCloudCached(int mi, int ti, int pi, Model &model) {\n Scan scan = {\n mi,\n Proctor::theta_start + ti * Proctor::theta_step,\n Proctor::phi_start + pi * Proctor::phi_step\n };\n char name[22];\n sprintf(name, \"scan_%04d_%03.0f_%03.0f.pcd\", mi, deg(scan.theta), deg(scan.phi));\n if (ifstream(name)) {\n PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());\n io::loadPCDFile(name, *cloud);\n return cloud;\n } else {\n PointCloud<PointNormal>::Ptr cloud = getCloud(scan, Proctor::models[mi]);\n io::savePCDFileBinary(name, *cloud);\n return cloud;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STATIC_LINK\n#define IMPLEMENT_API\n#endif\n\n#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)\n#define NEKO_COMPATIBLE\n#endif\n\n#include <hx\/CFFI.h>\n#include <hx\/CFFIPrime.h>\n\n#include \"SamcodesChartboost.h\"\n\nusing namespace samcodeschartboost;\n\n#ifdef IPHONE\n\nAutoGCRoot* chartboostEventHandle = 0;\n\nvoid samcodeschartboost_init_chartboost(HxString appId, HxString appSignature)\n{\n\tinitChartboost(appId.c_str(), appSignature.c_str());\n}\nDEFINE_PRIME2v(samcodeschartboost_init_chartboost);\n\nvoid samcodeschartboost_set_listener(value onEvent)\n{\n\tif(chartboostEventHandle == 0) {\n\t\tchartboostEventHandle = new AutoGCRoot(onEvent);\n\t} else {\n\t\tchartboostEventHandle->set(onEvent);\n\t}\n}\nDEFINE_PRIME1v(samcodeschartboost_set_listener);\n\nvoid samcodeschartboost_show_interstitial(HxString location)\n{\n\tshowInterstitial(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_show_interstitial);\n\nvoid samcodeschartboost_cache_interstitial(HxString location)\n{\n\tcacheInterstitial(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_cache_interstitial);\n\nbool samcodeschartboost_has_interstitial(HxString location)\n{\n\treturn hasInterstitial(location.c_str());\n}\nDEFINE_PRIME1(samcodeschartboost_has_interstitial);\n\nvoid samcodeschartboost_show_rewarded_video(HxString location)\n{\n\tshowRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_show_rewarded_video);\n\nvoid samcodeschartboost_cache_rewarded_video(HxString location)\n{\n\tcacheRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_cache_rewarded_video);\n\nbool samcodeschartboost_has_rewarded_video(HxString location)\n{\n\treturn hasRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1(samcodeschartboost_has_rewarded_video);\n\nbool samcodeschartboost_is_any_view_visible()\n{\n\treturn isAnyViewVisible();\n}\nDEFINE_PRIME0(samcodeschartboost_is_any_view_visible);\n\nvoid samcodeschartboost_set_custom_id(HxString id)\n{\n\tsetCustomId(id.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_set_custom_id);\n\nHxString samcodeschartboost_get_custom_id()\n{\n\treturn HxString(getCustomId());\n}\nDEFINE_PRIME0(samcodeschartboost_get_custom_id);\n\nvoid samcodeschartboost_set_should_request_interstitials_in_first_session(bool shouldRequest)\n{\n\tsetShouldRequestInterstitialsInFirstSession(shouldRequest);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_should_request_interstitials_in_first_session);\n\nbool samcodeschartboost_get_auto_cache_ads()\n{\n\treturn getAutoCacheAds();\n}\nDEFINE_PRIME0(samcodeschartboost_get_auto_cache_ads);\n\nvoid samcodeschartboost_set_auto_cache_ads(bool autoCache)\n{\n\tsetAutoCacheAds(autoCache);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_auto_cache_ads);\n\nvoid samcodeschartboost_set_should_prefetch_video_content(bool shouldPrefetch)\n{\n\tsetShouldPrefetchVideoContent(shouldPrefetch);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_should_prefetch_video_content);\n\nHxString samcodeschartboost_get_sdk_version()\n{\n\treturn HxString(getSDKVersion());\n}\nDEFINE_PRIME0(samcodeschartboost_get_sdk_version);\n\nvoid samcodeschartboost_set_status_bar_behavior(bool shouldHide)\n{\n\tsetStatusBarBehavior(shouldHide);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_status_bar_behavior);\n\nvoid samcodeschartboost_set_muted(bool mute)\n{\n\tsetMuted(mute);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_muted);\n\nvoid samcodeschartboost_restrict_data_collection(bool shouldRestrict)\n{\n\trestrictDataCollection(shouldRestrict);\n}\nDEFINE_PRIME1v(samcodeschartboost_restrict_data_collection);\n\nint samcodeschartboost_get_pi_data_use_consent()\n{\n\treturn getPIDataUseConsent();\n}\nDEFINE_PRIME1(samcodeschartboost_get_pi_data_use_consent);\n\nvoid samcodeschartboost_set_pi_data_use_consent(int consent)\n{\n\tsetPIDataUseConsent(consent);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_pi_data_use_consent);\n\nextern \"C\" void samcodeschartboost_main()\n{\n}\nDEFINE_ENTRY_POINT(samcodeschartboost_main);\n\nextern \"C\" int samcodeschartboost_register_prims()\n{\n\treturn 0;\n}\n\nextern \"C\" void sendChartboostEvent(const char* type, const char* location, const char* uri, int reward_coins, int error, bool status)\n{\n\tif(chartboostEventHandle == 0)\n\t{\n\t\treturn;\n\t}\n\tvalue o = alloc_empty_object();\n\talloc_field(o, val_id(\"type\"), alloc_string(type));\n\talloc_field(o, val_id(\"location\"), alloc_string(location));\n\talloc_field(o, val_id(\"uri\"), alloc_string(uri));\n\talloc_field(o, val_id(\"reward_coins\"), alloc_int(reward_coins));\n\talloc_field(o, val_id(\"error\"), alloc_int(error));\n\talloc_field(o, val_id(\"status\"), alloc_bool(status));\n\tval_call1(chartboostEventHandle->get(), o);\n}\n\n#endif\n<commit_msg>And another typo fix<commit_after>#ifndef STATIC_LINK\n#define IMPLEMENT_API\n#endif\n\n#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)\n#define NEKO_COMPATIBLE\n#endif\n\n#include <hx\/CFFI.h>\n#include <hx\/CFFIPrime.h>\n\n#include \"SamcodesChartboost.h\"\n\nusing namespace samcodeschartboost;\n\n#ifdef IPHONE\n\nAutoGCRoot* chartboostEventHandle = 0;\n\nvoid samcodeschartboost_init_chartboost(HxString appId, HxString appSignature)\n{\n\tinitChartboost(appId.c_str(), appSignature.c_str());\n}\nDEFINE_PRIME2v(samcodeschartboost_init_chartboost);\n\nvoid samcodeschartboost_set_listener(value onEvent)\n{\n\tif(chartboostEventHandle == 0) {\n\t\tchartboostEventHandle = new AutoGCRoot(onEvent);\n\t} else {\n\t\tchartboostEventHandle->set(onEvent);\n\t}\n}\nDEFINE_PRIME1v(samcodeschartboost_set_listener);\n\nvoid samcodeschartboost_show_interstitial(HxString location)\n{\n\tshowInterstitial(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_show_interstitial);\n\nvoid samcodeschartboost_cache_interstitial(HxString location)\n{\n\tcacheInterstitial(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_cache_interstitial);\n\nbool samcodeschartboost_has_interstitial(HxString location)\n{\n\treturn hasInterstitial(location.c_str());\n}\nDEFINE_PRIME1(samcodeschartboost_has_interstitial);\n\nvoid samcodeschartboost_show_rewarded_video(HxString location)\n{\n\tshowRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_show_rewarded_video);\n\nvoid samcodeschartboost_cache_rewarded_video(HxString location)\n{\n\tcacheRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_cache_rewarded_video);\n\nbool samcodeschartboost_has_rewarded_video(HxString location)\n{\n\treturn hasRewardedVideo(location.c_str());\n}\nDEFINE_PRIME1(samcodeschartboost_has_rewarded_video);\n\nbool samcodeschartboost_is_any_view_visible()\n{\n\treturn isAnyViewVisible();\n}\nDEFINE_PRIME0(samcodeschartboost_is_any_view_visible);\n\nvoid samcodeschartboost_set_custom_id(HxString id)\n{\n\tsetCustomId(id.c_str());\n}\nDEFINE_PRIME1v(samcodeschartboost_set_custom_id);\n\nHxString samcodeschartboost_get_custom_id()\n{\n\treturn HxString(getCustomId());\n}\nDEFINE_PRIME0(samcodeschartboost_get_custom_id);\n\nvoid samcodeschartboost_set_should_request_interstitials_in_first_session(bool shouldRequest)\n{\n\tsetShouldRequestInterstitialsInFirstSession(shouldRequest);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_should_request_interstitials_in_first_session);\n\nbool samcodeschartboost_get_auto_cache_ads()\n{\n\treturn getAutoCacheAds();\n}\nDEFINE_PRIME0(samcodeschartboost_get_auto_cache_ads);\n\nvoid samcodeschartboost_set_auto_cache_ads(bool autoCache)\n{\n\tsetAutoCacheAds(autoCache);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_auto_cache_ads);\n\nvoid samcodeschartboost_set_should_prefetch_video_content(bool shouldPrefetch)\n{\n\tsetShouldPrefetchVideoContent(shouldPrefetch);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_should_prefetch_video_content);\n\nHxString samcodeschartboost_get_sdk_version()\n{\n\treturn HxString(getSDKVersion());\n}\nDEFINE_PRIME0(samcodeschartboost_get_sdk_version);\n\nvoid samcodeschartboost_set_status_bar_behavior(bool shouldHide)\n{\n\tsetStatusBarBehavior(shouldHide);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_status_bar_behavior);\n\nvoid samcodeschartboost_set_muted(bool mute)\n{\n\tsetMuted(mute);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_muted);\n\nvoid samcodeschartboost_restrict_data_collection(bool shouldRestrict)\n{\n\trestrictDataCollection(shouldRestrict);\n}\nDEFINE_PRIME1v(samcodeschartboost_restrict_data_collection);\n\nint samcodeschartboost_get_pi_data_use_consent()\n{\n\treturn getPIDataUseConsent();\n}\nDEFINE_PRIME0(samcodeschartboost_get_pi_data_use_consent);\n\nvoid samcodeschartboost_set_pi_data_use_consent(int consent)\n{\n\tsetPIDataUseConsent(consent);\n}\nDEFINE_PRIME1v(samcodeschartboost_set_pi_data_use_consent);\n\nextern \"C\" void samcodeschartboost_main()\n{\n}\nDEFINE_ENTRY_POINT(samcodeschartboost_main);\n\nextern \"C\" int samcodeschartboost_register_prims()\n{\n\treturn 0;\n}\n\nextern \"C\" void sendChartboostEvent(const char* type, const char* location, const char* uri, int reward_coins, int error, bool status)\n{\n\tif(chartboostEventHandle == 0)\n\t{\n\t\treturn;\n\t}\n\tvalue o = alloc_empty_object();\n\talloc_field(o, val_id(\"type\"), alloc_string(type));\n\talloc_field(o, val_id(\"location\"), alloc_string(location));\n\talloc_field(o, val_id(\"uri\"), alloc_string(uri));\n\talloc_field(o, val_id(\"reward_coins\"), alloc_int(reward_coins));\n\talloc_field(o, val_id(\"error\"), alloc_int(error));\n\talloc_field(o, val_id(\"status\"), alloc_bool(status));\n\tval_call1(chartboostEventHandle->get(), o);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"distbench_utils.h\"\n#include \"protocol_driver_allocator.h\"\n#include \"gtest\/gtest.h\"\n#include \"gtest_utils.h\"\n#include \"benchmark\/benchmark.h\"\n#include <glog\/logging.h>\n\nnamespace distbench {\n\nclass ProtocolDriverTest\n : public testing::TestWithParam<ProtocolDriverOptions> {\n};\n\nTEST_P(ProtocolDriverTest, ctor) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n}\n\nTEST_P(ProtocolDriverTest, initialize) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n}\n\nTEST_P(ProtocolDriverTest, get_addr) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(\n pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_EQ(server_rpc_count, 0);\n}\n\nTEST_P(ProtocolDriverTest, get_set_addr) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n ASSERT_EQ(server_rpc_count, 0);\n}\n\nTEST_P(ProtocolDriverTest, invoke) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->send_response();\n });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state[10];\n for (int i = 0; i < 10; ++i) {\n pd->InitiateRpc(0, &rpc_state[i], [&]() { ++client_rpc_count; });\n }\n pd->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 10);\n EXPECT_EQ(client_rpc_count, 10);\n}\n\nTEST_P(ProtocolDriverTest, self_echo) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n pd->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 1);\n EXPECT_EQ(client_rpc_count, 1);\n}\n\nTEST_P(ProtocolDriverTest, echo) {\n std::unique_ptr<ProtocolDriver> pd1 = AllocateProtocolDriver(GetParam());\n std::unique_ptr<ProtocolDriver> pd2 = AllocateProtocolDriver(GetParam());\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd2->Initialize(\"\", AllocatePort()));\n pd2->SetNumPeers(1);\n pd2->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n ASSERT_OK(pd1->Initialize(\"\", AllocatePort()));\n pd1->SetNumPeers(1);\n pd1->SetHandler([&](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n std::string addr1 = pd1->HandlePreConnect(\"\", 0).value();\n std::string addr2 = pd2->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd1->HandleConnect(addr2, 0));\n ASSERT_OK(pd2->HandleConnect(addr1, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n pd1->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd1->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 1);\n EXPECT_EQ(client_rpc_count, 1);\n}\n\nvoid Echo(benchmark::State &state, ProtocolDriverOptions opts) {\n std::unique_ptr<ProtocolDriver> pd1 = AllocateProtocolDriver(opts);\n std::unique_ptr<ProtocolDriver> pd2 = AllocateProtocolDriver(opts);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd2->Initialize(\"\", AllocatePort()));\n pd2->SetNumPeers(1);\n pd2->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n ASSERT_OK(pd1->Initialize(\"\", AllocatePort()));\n pd1->SetNumPeers(1);\n pd1->SetHandler([&](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n std::string addr1 = pd1->HandlePreConnect(\"\", 0).value();\n std::string addr2 = pd2->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd1->HandleConnect(addr2, 0));\n ASSERT_OK(pd2->HandleConnect(addr1, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n for (auto s : state) {\n pd1->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd1->ShutdownClient();\n }\n}\n\nProtocolDriverOptions GrpcOptions() {\n ProtocolDriverOptions ret;\n ret.set_protocol_name(\"grpc\");\n return ret;\n}\n\nProtocolDriverOptions GrpcCallbackOptions() {\n ProtocolDriverOptions ret;\n ret.set_protocol_name(\"grpc_async_callback\");\n return ret;\n}\n\nvoid BM_GrpcEcho(benchmark::State &state) {\n Echo(state, GrpcOptions());\n}\n\nvoid BM_GrpcCallbackEcho(benchmark::State &state) {\n Echo(state, GrpcCallbackOptions());\n}\n\nBENCHMARK(BM_GrpcEcho);\nBENCHMARK(BM_GrpcCallbackEcho);\n\nINSTANTIATE_TEST_SUITE_P(\n ProtocolDriverTests, ProtocolDriverTest,\n testing::Values(GrpcOptions(), GrpcCallbackOptions()));\n\n} \/\/ namespace distbench\n<commit_msg>temp disable GrpcCallbackOptions unit test<commit_after>\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"distbench_utils.h\"\n#include \"protocol_driver_allocator.h\"\n#include \"gtest\/gtest.h\"\n#include \"gtest_utils.h\"\n#include \"benchmark\/benchmark.h\"\n#include <glog\/logging.h>\n\nnamespace distbench {\n\nclass ProtocolDriverTest\n : public testing::TestWithParam<ProtocolDriverOptions> {\n};\n\nTEST_P(ProtocolDriverTest, ctor) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n}\n\nTEST_P(ProtocolDriverTest, initialize) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n}\n\nTEST_P(ProtocolDriverTest, get_addr) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(\n pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_EQ(server_rpc_count, 0);\n}\n\nTEST_P(ProtocolDriverTest, get_set_addr) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) { ++server_rpc_count; });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n ASSERT_EQ(server_rpc_count, 0);\n}\n\nTEST_P(ProtocolDriverTest, invoke) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->send_response();\n });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state[10];\n for (int i = 0; i < 10; ++i) {\n pd->InitiateRpc(0, &rpc_state[i], [&]() { ++client_rpc_count; });\n }\n pd->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 10);\n EXPECT_EQ(client_rpc_count, 10);\n}\n\nTEST_P(ProtocolDriverTest, self_echo) {\n std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(GetParam());\n pd->SetNumPeers(1);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd->Initialize(\"\", AllocatePort()));\n pd->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n std::string addr = pd->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd->HandleConnect(addr, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n pd->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 1);\n EXPECT_EQ(client_rpc_count, 1);\n}\n\nTEST_P(ProtocolDriverTest, echo) {\n std::unique_ptr<ProtocolDriver> pd1 = AllocateProtocolDriver(GetParam());\n std::unique_ptr<ProtocolDriver> pd2 = AllocateProtocolDriver(GetParam());\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd2->Initialize(\"\", AllocatePort()));\n pd2->SetNumPeers(1);\n pd2->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n ASSERT_OK(pd1->Initialize(\"\", AllocatePort()));\n pd1->SetNumPeers(1);\n pd1->SetHandler([&](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n std::string addr1 = pd1->HandlePreConnect(\"\", 0).value();\n std::string addr2 = pd2->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd1->HandleConnect(addr2, 0));\n ASSERT_OK(pd2->HandleConnect(addr1, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n pd1->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd1->ShutdownClient();\n EXPECT_EQ(server_rpc_count, 1);\n EXPECT_EQ(client_rpc_count, 1);\n}\n\nvoid Echo(benchmark::State &state, ProtocolDriverOptions opts) {\n std::unique_ptr<ProtocolDriver> pd1 = AllocateProtocolDriver(opts);\n std::unique_ptr<ProtocolDriver> pd2 = AllocateProtocolDriver(opts);\n std::atomic<int> server_rpc_count = 0;\n ASSERT_OK(pd2->Initialize(\"\", AllocatePort()));\n pd2->SetNumPeers(1);\n pd2->SetHandler([&](ServerRpcState *s) {\n ++server_rpc_count;\n s->response.set_payload(s->request->payload());\n s->send_response();\n });\n ASSERT_OK(pd1->Initialize(\"\", AllocatePort()));\n pd1->SetNumPeers(1);\n pd1->SetHandler([&](ServerRpcState *s) {\n ADD_FAILURE() << \"should not get here\";\n });\n std::string addr1 = pd1->HandlePreConnect(\"\", 0).value();\n std::string addr2 = pd2->HandlePreConnect(\"\", 0).value();\n ASSERT_OK(pd1->HandleConnect(addr2, 0));\n ASSERT_OK(pd2->HandleConnect(addr1, 0));\n\n std::atomic<int> client_rpc_count = 0;\n ClientRpcState rpc_state;\n rpc_state.request.set_payload(\"ping!\");\n for (auto s : state) {\n pd1->InitiateRpc(0, &rpc_state, [&]() {\n ++client_rpc_count;\n EXPECT_EQ(rpc_state.request.payload(), rpc_state.response.payload());\n EXPECT_EQ(rpc_state.response.payload(), \"ping!\");\n });\n pd1->ShutdownClient();\n }\n}\n\nProtocolDriverOptions GrpcOptions() {\n ProtocolDriverOptions ret;\n ret.set_protocol_name(\"grpc\");\n return ret;\n}\n\nProtocolDriverOptions GrpcCallbackOptions() {\n ProtocolDriverOptions ret;\n ret.set_protocol_name(\"grpc_async_callback\");\n return ret;\n}\n\nvoid BM_GrpcEcho(benchmark::State &state) {\n Echo(state, GrpcOptions());\n}\n\nvoid BM_GrpcCallbackEcho(benchmark::State &state) {\n Echo(state, GrpcCallbackOptions());\n}\n\nBENCHMARK(BM_GrpcEcho);\nBENCHMARK(BM_GrpcCallbackEcho);\n\nINSTANTIATE_TEST_SUITE_P(\n ProtocolDriverTests, ProtocolDriverTest,\n testing::Values(GrpcOptions()\/*, GrpcCallbackOptions()*\/));\n\n} \/\/ namespace distbench\n<|endoftext|>"} {"text":"<commit_before>#include \"device.h\"\n#include <libudev.h>\n#include<monitor.h>\n#include <poll.h>\n#include <QtCore\/QDebug>\n#include \"udevnotifier.h\"\n#include \"udevnotifier_p.h\"\nnamespace UdevNotifier {\n\nUdevNotifier::UdevNotifier(const QStringList &groups, QObject *parent)\n : QThread(parent)\n , d(new UdevNotifierPrivate)\n{\n \/\/ register types needed for signals and slots\n qRegisterMetaType<UdevNotifier::Action>(\"UdevNotifier::Action\");\n qRegisterMetaType<Device>(\"Device\");\n\n d->groups = groups;\n d->udev = udev_new();\n\n if (!d->udev) {\n printf(\"Can't create udev\\n\");\n exit(1);\n }\n\n \/\/ TODO group monitoring goes here\n d->udevMonitor = udev_monitor_new_from_netlink(d->udev, \"udev\");\n\n if (d->udevMonitor) {\n \/\/ start receiving events\n udev_monitor_enable_receiving(d->udevMonitor);\n } else {\n qDebug(\"FAILED UDEv MONITOR\");\n }\n}\n\nUdevNotifier::~UdevNotifier()\n{\n delete d;\n}\n\nUdevNotifier::Action UdevNotifier::actionFromString(const QString &actionStr)\n{\n qDebug(\"[UdevNotifier::actionFromString]\");\n qDebug() << actionStr;\n\n\n if (actionStr == \"add\") {\n return ADD;\n } else if (actionStr == \"remove\") {\n return REMOVE;\n } else {\n return NONE;\n }\n}\n\nvoid UdevNotifier::run()\n{\n qDebug(\"[UdevNotifier::run]\");\n d->exit = false;\n\n while (!d->exit) {\n \/\/ create the poll item\n pollfd items[1];\n items[0].fd = udev_monitor_get_fd(d->udevMonitor);\n items[0].events = POLLIN;\n items[0].revents = 0;\n\n \/\/ while there are hotplug events to process\n while (poll(items, 1, 50) > 0) {\n \/\/ XXX\n qDebug() << \"hotplug[ \" << items[0].revents << \" ]\";\n\n \/\/ receive the relevant device\n udev_device* dev = udev_monitor_receive_device(d->udevMonitor);\n if (!dev) {\n \/\/ error receiving device, skip it\n qDebug(\"error rcv device. Skip\");\n continue;\n }\n\n \/\/ XXX\n\/\/ qDebug() << \"hotplug[\" << udev_device_get_action(dev) << \"] \" << udev_device_get_devnode(dev) << \",\" << udev_device_get_subsystem(dev) << \",\" << udev_device_get_devtype(dev);\n \/\/ emit the found device\n if(udev_device_get_devtype(dev)==QStringLiteral(\"drm_minor\")){\n Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Monitor(dev));}\n if(udev_device_get_devtype(dev)==QStringLiteral(\"usb_device\")){\n Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Device(dev));}\n\n \/\/ destroy the relevant device\n udev_device_unref(dev);\n\n \/\/ XXX\n \/\/ qDebug(\"-> done\");\n\n \/\/ clear the revents\n items[0].revents = 0;\n }\n }\n\n \/\/ qDebug(\"-> OUT\");\n}\n\nvoid UdevNotifier::stop()\n{\n d->exit = true;\n}\n\n}\n<commit_msg>revisionato3<commit_after>#include \"device.h\"\n#include <libudev.h>\n#include<monitor.h>\n#include <poll.h>\n#include <QtCore\/QDebug>\n#include \"udevnotifier.h\"\n#include \"udevnotifier_p.h\"\nnamespace UdevNotifier {\n\nUdevNotifier::UdevNotifier(const QStringList &groups, QObject *parent)\n : QThread(parent)\n , d(new UdevNotifierPrivate)\n{\n \/\/ register types needed for signals and slots\n qRegisterMetaType<UdevNotifier::Action>(\"UdevNotifier::Action\");\n qRegisterMetaType<Device>(\"Device\");\n\n d->groups = groups;\n d->udev = udev_new();\n\n if (!d->udev) {\n printf(\"Can't create udev\\n\");\n exit(1);\n }\n\n \/\/ TODO group monitoring goes here\n d->udevMonitor = udev_monitor_new_from_netlink(d->udev, \"udev\");\n\n if (d->udevMonitor) {\n \/\/ start receiving events\n udev_monitor_enable_receiving(d->udevMonitor);\n } else {\n qDebug(\"FAILED UDEv MONITOR\");\n }\n}\n\nUdevNotifier::~UdevNotifier()\n{\n delete d;\n}\n\nUdevNotifier::Action UdevNotifier::actionFromString(const QString &actionStr)\n{\n qDebug(\"[UdevNotifier::actionFromString]\");\n qDebug() << actionStr;\n\n\n if (actionStr == \"add\") {\n return ADD;\n } else if (actionStr == \"remove\") {\n return REMOVE;\n } else {\n return NONE;\n }\n}\n\nvoid UdevNotifier::run()\n{\n qDebug(\"[UdevNotifier::run]\");\n d->exit = false;\n\n while (!d->exit) {\n \/\/ create the poll item\n pollfd items[1];\n items[0].fd = udev_monitor_get_fd(d->udevMonitor);\n items[0].events = POLLIN;\n items[0].revents = 0;\n\n \/\/ while there are hotplug events to process\n while (poll(items, 1, 50) > 0) {\n \/\/ XXX\n qDebug() << \"hotplug[ \" << items[0].revents << \" ]\";\n\n \/\/ receive the relevant device\n udev_device* dev = udev_monitor_receive_device(d->udevMonitor);\n if (!dev) {\n \/\/ error receiving device, skip it\n qDebug(\"error rcv device. Skip\");\n continue;\n }\n\n \/\/ XXX\n\/\/ qDebug() << \"hotplug[\" << udev_device_get_action(dev) << \"] \" << udev_device_get_devnode(dev) << \",\" << udev_device_get_subsystem(dev) << \",\" << udev_device_get_devtype(dev);\n \/\/ emit the found device\n if(udev_device_get_devtype(dev)==QStringLiteral(\"drm_minor\")){\n Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Monitor(dev));\n }\n\n if(udev_device_get_devtype(dev)==QStringLiteral(\"usb_device\")){\n Q_EMIT udevEvent(actionFromString(udev_device_get_action(dev)), new Device(dev));\n }\n\n \/\/ destroy the relevant device\n udev_device_unref(dev);\n\n \/\/ XXX\n \/\/ qDebug(\"-> done\");\n\n \/\/ clear the revents\n items[0].revents = 0;\n }\n }\n\n \/\/ qDebug(\"-> OUT\");\n}\n\nvoid UdevNotifier::stop()\n{\n d->exit = true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Mutex.cpp - Mutual Exclusion Lock ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the llvm::sys::Mutex class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/System\/Mutex.h\"\n#include \"llvm\/System\/IncludeFile.h\"\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if !defined(ENABLE_THREADS) || ENABLE_THREADS == 0\n\/\/ Define all methods as no-ops if threading is explicitly disabled\nnamespace llvm {\nusing namespace sys;\nMutex::Mutex( bool recursive) { }\nMutex::~Mutex() { }\nbool Mutex::acquire() { return true; }\nbool Mutex::release() { return true; }\nbool Mutex::tryacquire() { return true; }\n}\n#else\n\n#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_MUTEX_LOCK)\n\n#include <cassert>\n#include <pthread.h>\n#include <stdlib.h>\n\nnamespace llvm {\nusing namespace sys;\n\n\n\/\/ This variable is useful for situations where the pthread library has been\n\/\/ compiled with weak linkage for its interface symbols. This allows the\n\/\/ threading support to be turned off by simply not linking against -lpthread.\n\/\/ In that situation, the value of pthread_mutex_init will be 0 and\n\/\/ consequently pthread_enabled will be false. In such situations, all the\n\/\/ pthread operations become no-ops and the functions all return false. If\n\/\/ pthread_mutex_init does have an address, then mutex support is enabled.\n\/\/ Note: all LLVM tools will link against -lpthread if its available since it\n\/\/ is configured into the LIBS variable.\n\/\/ Note: this line of code generates a warning if pthread_mutex_init is not\n\/\/ declared with weak linkage. It's safe to ignore the warning.\nstatic const bool pthread_enabled = true;\n\n\/\/ Construct a Mutex using pthread calls\nMutex::Mutex( bool recursive)\n : data_(0)\n{\n if (pthread_enabled)\n {\n \/\/ Declare the pthread_mutex data structures\n pthread_mutex_t* mutex =\n static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));\n pthread_mutexattr_t attr;\n\n \/\/ Initialize the mutex attributes\n int errorcode = pthread_mutexattr_init(&attr);\n assert(errorcode == 0);\n\n \/\/ Initialize the mutex as a recursive mutex, if requested, or normal\n \/\/ otherwise.\n int kind = ( recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORMAL );\n errorcode = pthread_mutexattr_settype(&attr, kind);\n assert(errorcode == 0);\n\n#if !defined(__FreeBSD__) && !defined(__OpenBSD__)\n \/\/ Make it a process local mutex\n errorcode = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);\n#endif\n\n \/\/ Initialize the mutex\n errorcode = pthread_mutex_init(mutex, &attr);\n assert(errorcode == 0);\n\n \/\/ Destroy the attributes\n errorcode = pthread_mutexattr_destroy(&attr);\n assert(errorcode == 0);\n\n \/\/ Assign the data member\n data_ = mutex;\n }\n}\n\n\/\/ Destruct a Mutex\nMutex::~Mutex()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n pthread_mutex_destroy(mutex);\n assert(mutex != 0);\n }\n}\n\nbool\nMutex::acquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_lock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::release()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_unlock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::tryacquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_trylock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\n}\n\n#elif defined(LLVM_ON_UNIX)\n#include \"Unix\/Mutex.inc\"\n#elif defined( LLVM_ON_WIN32)\n#include \"Win32\/Mutex.inc\"\n#else\n#warning Neither LLVM_ON_UNIX nor LLVM_ON_WIN32 was set in System\/Mutex.cpp\n#endif\n#endif\n\nDEFINING_FILE_FOR(SystemMutex)\n<commit_msg>For PR808: NetBSD also doesn't have pthread_mutexattr_setpshared<commit_after>\/\/===- Mutex.cpp - Mutual Exclusion Lock ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the llvm::sys::Mutex class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/System\/Mutex.h\"\n#include \"llvm\/System\/IncludeFile.h\"\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#if !defined(ENABLE_THREADS) || ENABLE_THREADS == 0\n\/\/ Define all methods as no-ops if threading is explicitly disabled\nnamespace llvm {\nusing namespace sys;\nMutex::Mutex( bool recursive) { }\nMutex::~Mutex() { }\nbool Mutex::acquire() { return true; }\nbool Mutex::release() { return true; }\nbool Mutex::tryacquire() { return true; }\n}\n#else\n\n#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_MUTEX_LOCK)\n\n#include <cassert>\n#include <pthread.h>\n#include <stdlib.h>\n\nnamespace llvm {\nusing namespace sys;\n\n\n\/\/ This variable is useful for situations where the pthread library has been\n\/\/ compiled with weak linkage for its interface symbols. This allows the\n\/\/ threading support to be turned off by simply not linking against -lpthread.\n\/\/ In that situation, the value of pthread_mutex_init will be 0 and\n\/\/ consequently pthread_enabled will be false. In such situations, all the\n\/\/ pthread operations become no-ops and the functions all return false. If\n\/\/ pthread_mutex_init does have an address, then mutex support is enabled.\n\/\/ Note: all LLVM tools will link against -lpthread if its available since it\n\/\/ is configured into the LIBS variable.\n\/\/ Note: this line of code generates a warning if pthread_mutex_init is not\n\/\/ declared with weak linkage. It's safe to ignore the warning.\nstatic const bool pthread_enabled = true;\n\n\/\/ Construct a Mutex using pthread calls\nMutex::Mutex( bool recursive)\n : data_(0)\n{\n if (pthread_enabled)\n {\n \/\/ Declare the pthread_mutex data structures\n pthread_mutex_t* mutex =\n static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));\n pthread_mutexattr_t attr;\n\n \/\/ Initialize the mutex attributes\n int errorcode = pthread_mutexattr_init(&attr);\n assert(errorcode == 0);\n\n \/\/ Initialize the mutex as a recursive mutex, if requested, or normal\n \/\/ otherwise.\n int kind = ( recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORMAL );\n errorcode = pthread_mutexattr_settype(&attr, kind);\n assert(errorcode == 0);\n\n#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)\n \/\/ Make it a process local mutex\n errorcode = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);\n#endif\n\n \/\/ Initialize the mutex\n errorcode = pthread_mutex_init(mutex, &attr);\n assert(errorcode == 0);\n\n \/\/ Destroy the attributes\n errorcode = pthread_mutexattr_destroy(&attr);\n assert(errorcode == 0);\n\n \/\/ Assign the data member\n data_ = mutex;\n }\n}\n\n\/\/ Destruct a Mutex\nMutex::~Mutex()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n pthread_mutex_destroy(mutex);\n assert(mutex != 0);\n }\n}\n\nbool\nMutex::acquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_lock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::release()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_unlock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\nbool\nMutex::tryacquire()\n{\n if (pthread_enabled)\n {\n pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(data_);\n assert(mutex != 0);\n\n int errorcode = pthread_mutex_trylock(mutex);\n return errorcode == 0;\n }\n return false;\n}\n\n}\n\n#elif defined(LLVM_ON_UNIX)\n#include \"Unix\/Mutex.inc\"\n#elif defined( LLVM_ON_WIN32)\n#include \"Win32\/Mutex.inc\"\n#else\n#warning Neither LLVM_ON_UNIX nor LLVM_ON_WIN32 was set in System\/Mutex.cpp\n#endif\n#endif\n\nDEFINING_FILE_FOR(SystemMutex)\n<|endoftext|>"} {"text":"<commit_before>#include <map> \n#include <string>\n#include <iostream>\n#include <Eigen\/Dense>\n\n#include <boost\/python\/extract.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/dict.hpp>\n#include <boost\/python\/def.hpp>\n\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <numpy\/arrayobject.h>\n\n\nnamespace python = boost::python;\n\nnamespace {\n\n Eigen::MatrixXd numpy2matrix(const PyObject* po)\n {\n if (!PyArray_Check(po))\n throw std::invalid_argument(\"PyObject is not an array!\");\n \n PyArrayObject* pao = (PyArrayObject*) po;\n if (!PyArray_ISFLOAT(pao))\n throw std::invalid_argument(\"PyObject is not an array of floats\/doubles!\");\n \n npy_intp *shape = PyArray_SHAPE(pao);\n Eigen::MatrixXd m(shape[0], shape[1]);\n memcpy(m.data(), PyArray_DATA(pao), m.size() * sizeof(double));\n return m;\n }\n\n python::object matrix2numpy(const Eigen::MatrixXd& m)\n {\n npy_intp shape[] = {m.rows(), m.cols()};\n PyArrayObject *array = (PyArrayObject*) PyArray_SimpleNew(2, shape, NPY_DOUBLE);\n memcpy(PyArray_DATA(array), m.data(), m.size() * sizeof(double));\n return python::object(python::handle<>((PyObject*) array));\n }\n \n template <class Key, class Value>\n std::map<Key, Value> dict2map(const python::dict &dict)\n {\n std::map<Key, Value> map;\n python::list keys = dict.keys();\n for (int i = 0; i < python::len(keys); i++)\n {\n python::extract<Key> key(keys[i]);\n python::extract<Value> value(dict[(std::string)key]);\n map[key] = value;\n }\n return map;\n }\n\n template <class Key, class Value>\n python::dict map2dict(const std::map<Key, Value> &map)\n {\n python::dict dict;\n for (const auto &it : map)\n dict[it.first] = it.second;\n return dict;\n }\n \n void init_numpy() { import_array(); }\n\n python::object double_matrix_python(PyObject* m) {\n init_numpy();\n Eigen::MatrixXd _m = numpy2matrix(m);\n return matrix2numpy(_m*2);\n }\n}\n\n\nBOOST_PYTHON_MODULE(fgm)\n{\n python::def(\"double_matrix\", double_matrix_python);\n}\n<commit_msg>Register converters<commit_after>#include <map> \n#include <string>\n#include <iostream>\n#include <Eigen\/Dense>\n\n#include <boost\/python\/to_python_converter.hpp>\n#include <boost\/python\/extract.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/dict.hpp>\n#include <boost\/python\/def.hpp>\n\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <numpy\/arrayobject.h>\n\n\nnamespace python = boost::python;\n\nnamespace {\n\n template <class Key, class Value>\n std::map<Key, Value> dict2map(const python::dict &dict)\n {\n std::map<Key, Value> map;\n python::list keys = dict.keys();\n for (int i = 0; i < python::len(keys); i++)\n {\n python::extract<Key> key(keys[i]);\n python::extract<Value> value(dict[(std::string)key]);\n map[key] = value;\n }\n return map;\n }\n\n template <class Key, class Value>\n python::dict map2dict(const std::map<Key, Value> &map)\n {\n python::dict dict;\n for (const auto &it : map)\n dict[it.first] = it.second;\n return dict;\n }\n\n struct eigen2numpy {\n eigen2numpy()\n {\n python::to_python_converter<Eigen::MatrixXd, eigen2numpy>();\n }\n\n static PyObject* convert(const Eigen::MatrixXd& m)\n {\n npy_intp shape[] = {m.rows(), m.cols()};\n PyArrayObject* array = (PyArrayObject*) PyArray_SimpleNew(2, shape, NPY_DOUBLE);\n memcpy(PyArray_DATA(array), m.data(), m.size() * sizeof(double));\n return (PyObject*)array;\n }\n };\n\n struct numpy2eigen {\n numpy2eigen()\n {\n python::converter::registry::push_back(&convertible, &construct, python::type_id<Eigen::MatrixXd>());\n }\n\n static void* convertible(PyObject* po)\n {\n return PyArray_Check(po) ? po : 0;\n }\n\n static void construct(PyObject* po, python::converter::rvalue_from_python_stage1_data* data)\n {\n PyArrayObject* pao = (PyArrayObject*) po;\n if (!PyArray_ISFLOAT(pao))\n throw std::invalid_argument(\"PyObject is not an array of floats\/doubles!\");\n \n void* storage = ((python::converter::rvalue_from_python_storage<Eigen::MatrixXd>*)(data))->storage.bytes;\n\n npy_intp* shape = PyArray_SHAPE(pao);\n Eigen::MatrixXd* m = new (storage) Eigen::MatrixXd(shape[0], shape[1]);\n memcpy(m->data(), PyArray_DATA(pao), m->size() * sizeof(double));\n data->convertible = storage;\n }\n };\n\n void initializeConverters()\n {\n import_array();\n eigen2numpy();\n numpy2eigen();\n }\n\n python::object double_matrix_python(PyObject* m)\n {\n Eigen::MatrixXd _m = python::extract<Eigen::MatrixXd>(m);\n _m *= 2;\n return python::object(_m);\n }\n\n python::object fgm_python(PyObject* KP, PyObject* KQ, PyObject* Ct, PyObject* asgTX,\n const python::dict& gph1, const python::dict& gph2,\n const python::dict& params)\n {\n Eigen::MatrixXd _KP = python::extract<Eigen::MatrixXd>(KP);\n Eigen::MatrixXd _KQ = python::extract<Eigen::MatrixXd>(KQ);\n Eigen::MatrixXd _Ct = python::extract<Eigen::MatrixXd>(Ct);\n Eigen::MatrixXd _asgTX = python::extract<Eigen::MatrixXd>(asgTX);\n auto _gph1 = dict2map<std::string, Eigen::MatrixXd>(gph1);\n auto _gph2 = dict2map<std::string, Eigen::MatrixXd>(gph2);\n auto _params = dict2map<std::string, std::string>(params);\n return python::object(_Ct);\n }\n}\n\n\nBOOST_PYTHON_MODULE(fgm)\n{\n python::def(\"double_matrix\", double_matrix_python);\n python::def(\"fgm\", fgm_python);\n initializeConverters();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef FGM_H_INCLUDED\n#define FGM_H_INCLUDED\n\n#include <utility>\n#include <string>\n#include <map>\n#include <Eigen\/Dense>\n\n#define FGM_VERSION \"0.0.1\"\n\n\nEigen::MatrixXd gmPosDHun(Eigen::MatrixXd& X);\n\ndouble multGXHSQTr(const Eigen::MatrixXd& indG, const Eigen::MatrixXd& X,\n const Eigen::MatrixXd& indH, const Eigen::MatrixXd& IndS0, const Eigen::MatrixXd& Q);\n\nstd::pair<Eigen::MatrixXd, double> fgm(Eigen::MatrixXd& KP, Eigen::MatrixXd& KQ, \n Eigen::MatrixXd& Ct, Eigen::MatrixXd& asgTX, \n std::map<std::string, Eigen::MatrixXd>& gph1,\n std::map<std::string, Eigen::MatrixXd>& gph2,\n int nAlp = 101, int nItMa = 100, int nHst = 10);\n\n#endif\n<commit_msg>Bump version to v0.0.2<commit_after>#ifndef FGM_H_INCLUDED\n#define FGM_H_INCLUDED\n\n#include <utility>\n#include <string>\n#include <map>\n#include <Eigen\/Dense>\n\n#define FGM_VERSION \"0.0.2\"\n\n\nEigen::MatrixXd gmPosDHun(Eigen::MatrixXd& X);\n\ndouble multGXHSQTr(const Eigen::MatrixXd& indG, const Eigen::MatrixXd& X,\n const Eigen::MatrixXd& indH, const Eigen::MatrixXd& IndS0, const Eigen::MatrixXd& Q);\n\nstd::pair<Eigen::MatrixXd, double> fgm(Eigen::MatrixXd& KP, Eigen::MatrixXd& KQ, \n Eigen::MatrixXd& Ct, Eigen::MatrixXd& asgTX, \n std::map<std::string, Eigen::MatrixXd>& gph1,\n std::map<std::string, Eigen::MatrixXd>& gph2,\n int nAlp = 101, int nItMa = 100, int nHst = 10);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: aststack.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: jsc $ $Date: 2001-03-15 12:30:43 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _RTL_ALLOC_H_\n#include <rtl\/alloc.h>\n#endif\n#ifndef _IDLC_ASTSTACK_HXX_\n#include <idlc\/aststack.hxx>\n#endif\n#ifndef _IDLC_ASTSCOPE_HXX_\n#include <idlc\/astscope.hxx>\n#endif\n\n#define STACKSIZE_INCREMENT 64\n\nAstStack::AstStack()\n : m_size(STACKSIZE_INCREMENT)\n , m_top(0)\n , m_stack((AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * STACKSIZE_INCREMENT))\n{\n}\n\nAstStack::~AstStack()\n{\n for(sal_uInt32 i=0; i < m_top; i++)\n {\n if (m_stack[i])\n delete(m_stack[i]);\n }\n\n rtl_freeMemory(m_stack);\n}\n\nsal_uInt32 AstStack::depth()\n{\n return m_top;\n}\n\nAstScope* AstStack::top()\n{\n if (m_top < 1)\n return NULL;\n return m_stack[m_top - 1];\n}\n\nAstScope* AstStack::bottom()\n{\n if (m_top == 0)\n return NULL;\n return m_stack[0];\n}\n\nAstScope* AstStack::nextToTop()\n{\n AstScope *tmp, *retval;\n\n if (depth() < 2)\n return NULL;\n\n tmp = top(); \/\/ Save top\n (void) pop(); \/\/ Pop it\n retval = top(); \/\/ Get next one down\n (void) push(tmp); \/\/ Push top back\n return retval; \/\/ Return next one down\n}\n\nAstScope* AstStack::topNonNull()\n{\n for (sal_uInt32 i = m_top - 1; i >= 0; i--)\n {\n if ( m_stack[i] )\n return m_stack[i];\n }\n return NULL;\n}\n\nAstStack* AstStack::push(AstScope* pScope)\n{\n AstScope **tmp;\n\/\/ AstDeclaration *pDecl = ScopeAsDecl(pScope);\n sal_uInt32 newSize;\n sal_uInt32 i;\n\n \/\/ Make sure there's space for one more\n if (m_size == m_top)\n {\n newSize = m_size;\n newSize += STACKSIZE_INCREMENT;\n tmp = (AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * newSize);\n\n for(i=0; i < m_size; i++)\n tmp[i] = m_stack[i];\n\n rtl_freeMemory(m_stack);\n m_stack = tmp;\n }\n\n \/\/ Insert new scope\n m_stack[m_top++] = pScope;\n\n return this;\n}\n\nvoid AstStack::pop()\n{\n AstScope *pScope;\n\n if (m_top < 1)\n return;\n pScope = m_stack[--m_top];\n}\n\nvoid AstStack::clear()\n{\n m_top = 0;\n}\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.1.150); FILE MERGED 2005\/09\/05 17:39:39 rt 1.1.150.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: aststack.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:08:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _RTL_ALLOC_H_\n#include <rtl\/alloc.h>\n#endif\n#ifndef _IDLC_ASTSTACK_HXX_\n#include <idlc\/aststack.hxx>\n#endif\n#ifndef _IDLC_ASTSCOPE_HXX_\n#include <idlc\/astscope.hxx>\n#endif\n\n#define STACKSIZE_INCREMENT 64\n\nAstStack::AstStack()\n : m_size(STACKSIZE_INCREMENT)\n , m_top(0)\n , m_stack((AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * STACKSIZE_INCREMENT))\n{\n}\n\nAstStack::~AstStack()\n{\n for(sal_uInt32 i=0; i < m_top; i++)\n {\n if (m_stack[i])\n delete(m_stack[i]);\n }\n\n rtl_freeMemory(m_stack);\n}\n\nsal_uInt32 AstStack::depth()\n{\n return m_top;\n}\n\nAstScope* AstStack::top()\n{\n if (m_top < 1)\n return NULL;\n return m_stack[m_top - 1];\n}\n\nAstScope* AstStack::bottom()\n{\n if (m_top == 0)\n return NULL;\n return m_stack[0];\n}\n\nAstScope* AstStack::nextToTop()\n{\n AstScope *tmp, *retval;\n\n if (depth() < 2)\n return NULL;\n\n tmp = top(); \/\/ Save top\n (void) pop(); \/\/ Pop it\n retval = top(); \/\/ Get next one down\n (void) push(tmp); \/\/ Push top back\n return retval; \/\/ Return next one down\n}\n\nAstScope* AstStack::topNonNull()\n{\n for (sal_uInt32 i = m_top - 1; i >= 0; i--)\n {\n if ( m_stack[i] )\n return m_stack[i];\n }\n return NULL;\n}\n\nAstStack* AstStack::push(AstScope* pScope)\n{\n AstScope **tmp;\n\/\/ AstDeclaration *pDecl = ScopeAsDecl(pScope);\n sal_uInt32 newSize;\n sal_uInt32 i;\n\n \/\/ Make sure there's space for one more\n if (m_size == m_top)\n {\n newSize = m_size;\n newSize += STACKSIZE_INCREMENT;\n tmp = (AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * newSize);\n\n for(i=0; i < m_size; i++)\n tmp[i] = m_stack[i];\n\n rtl_freeMemory(m_stack);\n m_stack = tmp;\n }\n\n \/\/ Insert new scope\n m_stack[m_top++] = pScope;\n\n return this;\n}\n\nvoid AstStack::pop()\n{\n AstScope *pScope;\n\n if (m_top < 1)\n return;\n pScope = m_stack[--m_top];\n}\n\nvoid AstStack::clear()\n{\n m_top = 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef FUJI_CAM_WIFI_TOOL_COMM_HPP\n#define FUJI_CAM_WIFI_TOOL_COMM_HPP\n\n#include <stdint.h>\n#include <stddef.h>\n#include <string.h>\n#include <memory>\n\nnamespace fcwt {\n\nconst int control_server_port = 55740;\nconst int jpg_stream_server_port = 55742;\n\n#ifdef _WIN32\n#define FCWT_USE_WINSOCK 1\n#elif defined(__unix__) || defined(__MACH__) || defined(__linux__)\n#define FCWT_USE_BSD_SOCKET 1\n#endif\n\n#if FCWT_USE_BSD_SOCKETS\n\ttypedef int native_socket;\n#elif FCWT_USE_WINSOCK\n\ttypedef uintptr_t native_socket;\n#else\n#\terror unsupported platform\n#endif\n\nclass sock {\n native_socket sockfd;\n\n public:\n sock(native_socket fd = 0);\n ~sock();\n sock(sock const&) = delete;\n sock& operator=(sock const&) = delete;\n sock(sock&& other);\n sock& operator=(sock&& other);\n void swap(sock& other);\n operator native_socket() const;\n};\n\nsock connect_to_camera(int port);\n\nvoid send_data(native_socket sockfd, void const* data, size_t sizeBytes);\nvoid receive_data(native_socket sockfd, void* data, size_t sizeBytes);\nvoid fuji_send(native_socket sockfd, void const* data, size_t sizeBytes);\n\n\/\/ returns the total payload bytes, if this is more than sizeBytes the caller\n\/\/ needs to use receive_data to get the additional data\nsize_t fuji_receive(native_socket sockfd, void* data, size_t sizeBytes);\n\ntemplate <size_t N>\nvoid fuji_send(native_socket sockfd, uint8_t const(&data)[N]) {\n fuji_send(sockfd, data, N);\n}\n\ntemplate <size_t N>\nsize_t fuji_receive(native_socket sockfd, uint8_t(&data)[N]) {\n return fuji_receive(sockfd, data, N);\n}\n\n} \/\/ namespace fcwt\n\n#endif\n<commit_msg>Another fix of platform macros<commit_after>#ifndef FUJI_CAM_WIFI_TOOL_COMM_HPP\n#define FUJI_CAM_WIFI_TOOL_COMM_HPP\n\n#include <stdint.h>\n#include <stddef.h>\n#include <string.h>\n#include <memory>\n\nnamespace fcwt {\n\nconst int control_server_port = 55740;\nconst int jpg_stream_server_port = 55742;\n\n#ifdef _WIN32\n#define FCWT_USE_WINSOCK 1\n#elif defined(__unix__) || defined(__MACH__) || defined(__linux__)\n#define FCWT_USE_BSD_SOCKETS 1\n#endif\n\n#if FCWT_USE_BSD_SOCKETS\n\ttypedef int native_socket;\n#elif FCWT_USE_WINSOCK\n\ttypedef uintptr_t native_socket;\n#else\n#\terror unsupported platform\n#endif\n\nclass sock {\n native_socket sockfd;\n\n public:\n sock(native_socket fd = 0);\n ~sock();\n sock(sock const&) = delete;\n sock& operator=(sock const&) = delete;\n sock(sock&& other);\n sock& operator=(sock&& other);\n void swap(sock& other);\n operator native_socket() const;\n};\n\nsock connect_to_camera(int port);\n\nvoid send_data(native_socket sockfd, void const* data, size_t sizeBytes);\nvoid receive_data(native_socket sockfd, void* data, size_t sizeBytes);\nvoid fuji_send(native_socket sockfd, void const* data, size_t sizeBytes);\n\n\/\/ returns the total payload bytes, if this is more than sizeBytes the caller\n\/\/ needs to use receive_data to get the additional data\nsize_t fuji_receive(native_socket sockfd, void* data, size_t sizeBytes);\n\ntemplate <size_t N>\nvoid fuji_send(native_socket sockfd, uint8_t const(&data)[N]) {\n fuji_send(sockfd, data, N);\n}\n\ntemplate <size_t N>\nsize_t fuji_receive(native_socket sockfd, uint8_t(&data)[N]) {\n return fuji_receive(sockfd, data, N);\n}\n\n} \/\/ namespace fcwt\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Core ros functionality like ros::init and spin\n#include <ros\/ros.h>\n\/\/ ROS Trajectory Action server definition\n#include <control_msgs\/FollowJointTrajectoryAction.h>\n\/\/ Means by which we communicate with above action-server\n#include <actionlib\/client\/simple_action_client.h>\n\n\/\/ Includes the descartes robot model we will be using\n#include <descartes_moveit\/moveit_state_adapter.h>\n\/\/ Includes the descartes trajectory type we will be using\n#include <descartes_trajectory\/cart_trajectory_pt.h>\n\/\/ Includes the planner we will be using\n#include <descartes_planner\/dense_planner.h>\n\n#include <eigen3\/Eigen\/Dense>\n\ntypedef std::vector<descartes_core::TrajectoryPtPtr> TrajectoryVec;\ntypedef TrajectoryVec::const_iterator TrajectoryIter;\n\ndescartes_core::TrajectoryPtPtr makeCartesianPoint(const Eigen::Affine3d& pose)\n{\n using namespace descartes_core;\n using namespace descartes_trajectory;\n\n return TrajectoryPtPtr( new CartTrajectoryPt(\n TolerancedFrame(pose)) );\n}\n\ndescartes_core::TrajectoryPtPtr makeTolerancedCartesianPoint(const Eigen::Affine3d& pose)\n{\n using namespace descartes_core;\n using namespace descartes_trajectory;\n\n \/\/ Extract rotation information\n Eigen::Vector3d rpy = pose.rotation().eulerAngles(0, 1, 2);\n double rx = rpy(0);\n double ry = rpy(1);\n double rz = rpy(2);\n \/\/ Extract translation information\n Eigen::Vector3d trans = pose.translation();\n double x = trans(0);\n double y = trans(1);\n double z = trans(2);\n\n return TrajectoryPtPtr( new CartTrajectoryPt(\n TolerancedFrame(pose,\n ToleranceBase::zeroTolerance<PositionTolerance>(x, y, z),\n ToleranceBase::createSymmetric<OrientationTolerance>(rx, ry, 0.0, 0.0, 0.0, 2*M_PI)),\n 0.0, \/\/ pos search increment\n 0.4)); \/\/ orientation search increment\n}\n\ntrajectory_msgs::JointTrajectory\ntoROSJointTrajectory(const TrajectoryVec& trajectory,\n const descartes_core::RobotModel& model,\n const std::vector<std::string>& joint_names,\n double time_delay)\n{\n \/\/ Fill out information about our trajectory\n trajectory_msgs::JointTrajectory result;\n result.header.stamp = ros::Time::now();\n result.header.frame_id = \"world_frame\";\n result.joint_names = joint_names;\n\n \/\/ For keeping track of time-so-far in the trajectory\n double time_offset = 0.0;\n \/\/ Loop through the trajectory\n for (TrajectoryIter it = trajectory.begin(); it != trajectory.end(); ++it)\n {\n \/\/ Find nominal joint solution at this point\n std::vector<double> joints;\n it->get()->getNominalJointPose(std::vector<double>(), model, joints);\n\n \/\/ Fill out a ROS trajectory point\n trajectory_msgs::JointTrajectoryPoint pt;\n pt.positions = joints;\n \/\/ velocity, acceleration, and effort are given dummy values\n \/\/ we'll let the controller figure them out\n pt.velocities.resize(joints.size(), 0.0);\n pt.accelerations.resize(joints.size(), 0.0);\n pt.effort.resize(joints.size(), 0.0);\n \/\/ set the time into the trajectory\n pt.time_from_start = ros::Duration(time_offset);\n \/\/ increment time\n time_offset += time_delay;\n\n result.points.push_back(pt);\n }\n\n return result;\n}\n\nbool executeTrajectory(const trajectory_msgs::JointTrajectory& trajectory)\n{\n \/\/ Create a Follow Joint Trajectory Action Client\n actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction> ac(\"joint_trajectory_action\", true);\n if (!ac.waitForServer(ros::Duration(2.0)))\n {\n ROS_ERROR(\"Could not connect to action server\");\n return false;\n }\n\n control_msgs::FollowJointTrajectoryGoal goal;\n goal.trajectory = trajectory;\n goal.goal_time_tolerance = ros::Duration(1.0);\n \n ac.sendGoal(goal);\n\n if (ac.waitForResult(goal.trajectory.points[goal.trajectory.points.size()-1].time_from_start + ros::Duration(5)))\n {\n ROS_INFO(\"Action server reported successful execution\");\n return true;\n } else {\n ROS_WARN(\"Action server could not execute trajectory\");\n return false;\n }\n}\n\nint main(int argc, char** argv)\n{\n \/\/ Initialize ROS\n ros::init(argc, argv, \"descartes_tutorial\");\n ros::NodeHandle nh;\n\n \/\/ Required for communication with moveit components\n ros::AsyncSpinner spinner (1);\n spinner.start();\n\n \/\/ 1. Define sequence of points\n TrajectoryVec points;\n for (unsigned int i = 0; i < 10; ++i)\n {\n Eigen::Affine3d pose;\n pose = Eigen::Translation3d(0.0, 0.0, 1.0 + 0.05 * i);\n descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);\n points.push_back(pt);\n }\n\n \/\/ 2. Create a robot model and initialize it\n descartes_core::RobotModelPtr model (new descartes_moveit::MoveitStateAdapter);\n\n \/\/ Name of description on parameter server. Typically just \"robot_description\".\n const std::string robot_description = \"robot_description\";\n\n \/\/ name of the kinematic group you defined when running MoveitSetupAssistant\n const std::string group_name = \"manipulator\";\n\n \/\/ Name of frame in which you are expressing poses. Typically \"world_frame\" or \"base_link\".\n const std::string world_frame = \"base_link\";\n\n \/\/ tool center point frame (name of link associated with tool)\n const std::string tcp_frame = \"tool0\";\n\n ROS_INFO(\"INIT\");\n if (!model->initialize(robot_description, group_name, world_frame, tcp_frame))\n {\n ROS_INFO(\"Could not initialize robot model\");\n return -4;\n }\n\n \/\/ 3. Create a planner and initialize it with our robot model\n descartes_planner::DensePlanner planner;\n planner.initialize(model);\n\n \/\/ 4. Feed the trajectory to the planner\n if (!planner.planPath(points))\n {\n ROS_ERROR(\"Could not solve for a valid path\");\n return -1;\n }\n\n TrajectoryVec result;\n if (!planner.getPath(result))\n {\n ROS_ERROR(\"Could not retrieve path\");\n return -2;\n }\n\n \/\/ 5. Translate the result into a type that ROS understands\n \/\/ Get Joint Names\n std::vector<std::string> names;\n nh.getParam(\"controller_joint_names\", names);\n\n trajectory_msgs::JointTrajectory joint_solution =\n toROSJointTrajectory(result, *model, names, 1.0);\n\n \/\/ 6. Send the ROS trajectory to the robot for execution\n if (!executeTrajectory(joint_solution))\n {\n ROS_ERROR(\"Could not execute trajectory!\");\n return -3;\n }\n\n \/\/ Wait till user kills the process (Control-C)\n ROS_INFO(\"Done!\");\n return 0;\n}\n<commit_msg>Cleaning up code. Adding axially symmetric points<commit_after>\/\/ Core ros functionality like ros::init and spin\n#include <ros\/ros.h>\n\/\/ ROS Trajectory Action server definition\n#include <control_msgs\/FollowJointTrajectoryAction.h>\n\/\/ Means by which we communicate with above action-server\n#include <actionlib\/client\/simple_action_client.h>\n\n\/\/ Includes the descartes robot model we will be using\n#include <descartes_moveit\/moveit_state_adapter.h>\n\/\/ Includes the descartes trajectory type we will be using\n#include <descartes_trajectory\/axial_symmetric_pt.h>\n#include <descartes_trajectory\/cart_trajectory_pt.h>\n\/\/ Includes the planner we will be using\n#include <descartes_planner\/dense_planner.h>\n\ntypedef std::vector<descartes_core::TrajectoryPtPtr> TrajectoryVec;\ntypedef TrajectoryVec::const_iterator TrajectoryIter;\n\n\/**\n * Generates an completely defined (zero-tolerance) cartesian point from a pose\n *\/\ndescartes_core::TrajectoryPtPtr makeCartesianPoint(const Eigen::Affine3d& pose);\n\/**\n * Generates a cartesian point with free rotation about the Z axis of the EFF frame\n *\/\ndescartes_core::TrajectoryPtPtr makeTolerancedCartesianPoint(const Eigen::Affine3d& pose);\n\n\/**\n * Translates a descartes trajectory to a ROS joint trajectory\n *\/\ntrajectory_msgs::JointTrajectory\ntoROSJointTrajectory(const TrajectoryVec& trajectory, const descartes_core::RobotModel& model,\n const std::vector<std::string>& joint_names, double time_delay);\n\n\/**\n * Sends a ROS trajectory to the robot controller\n *\/\nbool executeTrajectory(const trajectory_msgs::JointTrajectory& trajectory);\n\nint main(int argc, char** argv)\n{\n \/\/ Initialize ROS\n ros::init(argc, argv, \"descartes_tutorial\");\n ros::NodeHandle nh;\n\n \/\/ Required for communication with moveit components\n ros::AsyncSpinner spinner (1);\n spinner.start();\n\n \/\/ 1. Define sequence of points\n TrajectoryVec points;\n for (unsigned int i = 0; i < 10; ++i)\n {\n Eigen::Affine3d pose;\n pose = Eigen::Translation3d(0.0, 0.0, 1.0 + 0.05 * i);\n descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);\n points.push_back(pt);\n }\n\n for (unsigned int i = 0; i < 5; ++i)\n {\n Eigen::Affine3d pose;\n pose = Eigen::Translation3d(0.0, 0.04 * i, 1.3);\n descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);\n points.push_back(pt);\n }\n\n \/\/ 2. Create a robot model and initialize it\n descartes_core::RobotModelPtr model (new descartes_moveit::MoveitStateAdapter);\n\n \/\/ Name of description on parameter server. Typically just \"robot_description\".\n const std::string robot_description = \"robot_description\";\n\n \/\/ name of the kinematic group you defined when running MoveitSetupAssistant\n const std::string group_name = \"manipulator\";\n\n \/\/ Name of frame in which you are expressing poses. Typically \"world_frame\" or \"base_link\".\n const std::string world_frame = \"base_link\";\n\n \/\/ tool center point frame (name of link associated with tool)\n const std::string tcp_frame = \"tool0\";\n\n if (!model->initialize(robot_description, group_name, world_frame, tcp_frame))\n {\n ROS_INFO(\"Could not initialize robot model\");\n return -1;\n }\n\n \/\/ 3. Create a planner and initialize it with our robot model\n descartes_planner::DensePlanner planner;\n planner.initialize(model);\n\n \/\/ 4. Feed the trajectory to the planner\n if (!planner.planPath(points))\n {\n ROS_ERROR(\"Could not solve for a valid path\");\n return -2;\n }\n\n TrajectoryVec result;\n if (!planner.getPath(result))\n {\n ROS_ERROR(\"Could not retrieve path\");\n return -3;\n }\n\n \/\/ 5. Translate the result into a type that ROS understands\n \/\/ Get Joint Names\n std::vector<std::string> names;\n nh.getParam(\"controller_joint_names\", names);\n \/\/ Generate a ROS joint trajectory with the result path, robot model, given joint names,\n \/\/ a certain time delta between each trajectory point\n trajectory_msgs::JointTrajectory joint_solution = toROSJointTrajectory(result, *model, names, 1.0);\n\n \/\/ 6. Send the ROS trajectory to the robot for execution\n if (!executeTrajectory(joint_solution))\n {\n ROS_ERROR(\"Could not execute trajectory!\");\n return -4;\n }\n\n \/\/ Wait till user kills the process (Control-C)\n ROS_INFO(\"Done!\");\n return 0;\n}\n\ndescartes_core::TrajectoryPtPtr makeCartesianPoint(const Eigen::Affine3d& pose)\n{\n using namespace descartes_core;\n using namespace descartes_trajectory;\n\n return TrajectoryPtPtr( new CartTrajectoryPt( TolerancedFrame(pose)) );\n}\n\ndescartes_core::TrajectoryPtPtr makeTolerancedCartesianPoint(const Eigen::Affine3d& pose)\n{\n using namespace descartes_core;\n using namespace descartes_trajectory;\n return TrajectoryPtPtr( new AxialSymmetricPt(pose, M_PI\/2.0-0.0001, AxialSymmetricPt::Z_AXIS) );\n}\n\ntrajectory_msgs::JointTrajectory\ntoROSJointTrajectory(const TrajectoryVec& trajectory,\n const descartes_core::RobotModel& model,\n const std::vector<std::string>& joint_names,\n double time_delay)\n{\n \/\/ Fill out information about our trajectory\n trajectory_msgs::JointTrajectory result;\n result.header.stamp = ros::Time::now();\n result.header.frame_id = \"world_frame\";\n result.joint_names = joint_names;\n\n \/\/ For keeping track of time-so-far in the trajectory\n double time_offset = 0.0;\n \/\/ Loop through the trajectory\n for (TrajectoryIter it = trajectory.begin(); it != trajectory.end(); ++it)\n {\n \/\/ Find nominal joint solution at this point\n std::vector<double> joints;\n it->get()->getNominalJointPose(std::vector<double>(), model, joints);\n\n \/\/ Fill out a ROS trajectory point\n trajectory_msgs::JointTrajectoryPoint pt;\n pt.positions = joints;\n \/\/ velocity, acceleration, and effort are given dummy values\n \/\/ we'll let the controller figure them out\n pt.velocities.resize(joints.size(), 0.0);\n pt.accelerations.resize(joints.size(), 0.0);\n pt.effort.resize(joints.size(), 0.0);\n \/\/ set the time into the trajectory\n pt.time_from_start = ros::Duration(time_offset);\n \/\/ increment time\n time_offset += time_delay;\n\n result.points.push_back(pt);\n }\n\n return result;\n}\n\nbool executeTrajectory(const trajectory_msgs::JointTrajectory& trajectory)\n{\n \/\/ Create a Follow Joint Trajectory Action Client\n actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction> ac(\"joint_trajectory_action\", true);\n if (!ac.waitForServer(ros::Duration(2.0)))\n {\n ROS_ERROR(\"Could not connect to action server\");\n return false;\n }\n\n control_msgs::FollowJointTrajectoryGoal goal;\n goal.trajectory = trajectory;\n goal.goal_time_tolerance = ros::Duration(1.0);\n \n ac.sendGoal(goal);\n\n if (ac.waitForResult(goal.trajectory.points[goal.trajectory.points.size()-1].time_from_start + ros::Duration(5)))\n {\n ROS_INFO(\"Action server reported successful execution\");\n return true;\n } else {\n ROS_WARN(\"Action server could not execute trajectory\");\n return false;\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\/*\n * Description:\n * What is this file about?\n *\n * Revision history:\n * xxxx-xx-xx, author, first version\n * xxxx-xx-xx, author, fix bug about xxx\n *\/\n\n#include \"prepare_list.h\"\n#include \"mutation.h\"\n\n# ifdef __TITLE__\n# undef __TITLE__\n# endif\n# define __TITLE__ \"prepare_list\"\n\nnamespace dsn { namespace replication {\n\nprepare_list::prepare_list(\n decree init_decree, int max_count,\n mutation_committer committer\n )\n : mutation_cache(init_decree, max_count)\n{\n _committer = committer;\n _last_committed_decree = init_decree;\n}\n\nvoid prepare_list::sanity_check()\n{\n\n}\n\nvoid prepare_list::reset(decree init_decree)\n{\n _last_committed_decree = init_decree;\n mutation_cache::reset(init_decree, true);\n}\n\nvoid prepare_list::truncate(decree init_decree)\n{\n while (min_decree() <= init_decree && count() > 0)\n {\n pop_min();\n }\n\n if (count() == 0)\n {\n mutation_cache::reset(init_decree, true);\n }\n\n _last_committed_decree = init_decree;\n}\n\nerror_code prepare_list::prepare(mutation_ptr& mu, partition_status status)\n{\n decree d = mu->data.header.decree;\n dassert (d > last_committed_decree(), \"\");\n\n \/\/ pop committed mutations if buffer is full\n while (d - min_decree() >= capacity() && last_committed_decree() > min_decree())\n {\n pop_min();\n } \n\n error_code err;\n switch (status)\n {\n case PS_PRIMARY:\n return mutation_cache::put(mu);\n\n case PS_SECONDARY: \n case PS_POTENTIAL_SECONDARY:\n \/\/ all mutations with lower decree must be ready\n commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD);\n err = mutation_cache::put(mu);\n dassert (err == ERR_OK, \"\");\n return err;\n\n \/\/\/\/ delayed commit - only when capacity is an issue\n \/\/case PS_POTENTIAL_SECONDARY:\n \/\/ while (true)\n \/\/ {\n \/\/ err = mutation_cache::put(mu);\n \/\/ if (err == ERR_CAPACITY_EXCEEDED)\n \/\/ {\n \/\/ dassert(mu->data.header.last_committed_decree >= min_decree(), \"\");\n \/\/ commit (min_decree(), true);\n \/\/ pop_min();\n \/\/ }\n \/\/ else\n \/\/ break;\n \/\/ }\n \/\/ dassert (err == ERR_OK, \"\");\n \/\/ return err;\n \n case PS_INACTIVE: \/\/ only possible during init \n if (mu->data.header.last_committed_decree > max_decree())\n {\n reset(mu->data.header.last_committed_decree);\n }\n else if (mu->data.header.last_committed_decree > _last_committed_decree)\n {\n commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD);\n }\n err = mutation_cache::put(mu);\n dassert (err == ERR_OK, \"\");\n return err;\n\n default:\n dassert (false, \"\");\n return 0;\n }\n}\n\n\/\/\n\/\/ ordered commit\n\/\/\nbool prepare_list::commit(decree d, commit_type ct)\n{\n if (d <= last_committed_decree())\n return false;\n\n dinfo(\"commit to decree %\" PRId64, d);\n \n ballot last_bt = 0;\n switch (ct)\n {\n case COMMIT_TO_DECREE_HARD:\n {\n for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++)\n {\n mutation_ptr mu = get_mutation_by_decree(d0);\n dassert(mu != nullptr &&\n (mu->is_logged()) &&\n mu->data.header.ballot >= last_bt,\n \"mutation %\" PRId64 \" is missing in prepare list\",\n d0\n );\n\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n }\n\n sanity_check();\n return true;\n }\n case COMMIT_TO_DECREE_SOFT:\n {\n for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++)\n {\n mutation_ptr mu = get_mutation_by_decree(d0);\n if (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt)\n {\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n }\n else\n break;\n }\n\n sanity_check();\n return true;\n }\n case COMMIT_ALL_READY:\n {\n if (d != last_committed_decree() + 1)\n return false;\n\n int count = 0;\n mutation_ptr mu = get_mutation_by_decree(last_committed_decree() + 1);\n\n while (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt)\n {\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n count++;\n mu = mutation_cache::get_mutation_by_decree(_last_committed_decree + 1);\n }\n\n sanity_check();\n return count > 0;\n }\n default:\n dassert(false, \"invalid commit type %d\", (int)ct);\n }\n\n return false;\n}\n\n}} \/\/ namespace end\n<commit_msg>smallfix<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\/*\n * Description:\n * What is this file about?\n *\n * Revision history:\n * xxxx-xx-xx, author, first version\n * xxxx-xx-xx, author, fix bug about xxx\n *\/\n\n#include \"prepare_list.h\"\n#include \"mutation.h\"\n\n# ifdef __TITLE__\n# undef __TITLE__\n# endif\n# define __TITLE__ \"prepare_list\"\n\nnamespace dsn { namespace replication {\n\nprepare_list::prepare_list(\n decree init_decree, int max_count,\n mutation_committer committer\n )\n : mutation_cache(init_decree, max_count)\n{\n _committer = committer;\n _last_committed_decree = init_decree;\n}\n\nvoid prepare_list::sanity_check()\n{\n\n}\n\nvoid prepare_list::reset(decree init_decree)\n{\n _last_committed_decree = init_decree;\n mutation_cache::reset(init_decree, true);\n}\n\nvoid prepare_list::truncate(decree init_decree)\n{\n while (min_decree() <= init_decree && count() > 0)\n {\n pop_min();\n }\n\n if (count() == 0)\n {\n mutation_cache::reset(init_decree, true);\n }\n\n _last_committed_decree = init_decree;\n}\n\nerror_code prepare_list::prepare(mutation_ptr& mu, partition_status status)\n{\n decree d = mu->data.header.decree;\n dassert (d > last_committed_decree(), \"\");\n\n \/\/ pop committed mutations if buffer is full\n while (d - min_decree() >= capacity() && last_committed_decree() > min_decree())\n {\n pop_min();\n } \n\n error_code err;\n switch (status)\n {\n case PS_PRIMARY:\n return mutation_cache::put(mu);\n\n case PS_SECONDARY: \n case PS_POTENTIAL_SECONDARY:\n \/\/ all mutations with lower decree must be ready\n commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD);\n err = mutation_cache::put(mu);\n dassert (err == ERR_OK, \"\");\n return err;\n\n \/\/\/\/ delayed commit - only when capacity is an issue\n \/\/case PS_POTENTIAL_SECONDARY:\n \/\/ while (true)\n \/\/ {\n \/\/ err = mutation_cache::put(mu);\n \/\/ if (err == ERR_CAPACITY_EXCEEDED)\n \/\/ {\n \/\/ dassert(mu->data.header.last_committed_decree >= min_decree(), \"\");\n \/\/ commit (min_decree(), true);\n \/\/ pop_min();\n \/\/ }\n \/\/ else\n \/\/ break;\n \/\/ }\n \/\/ dassert (err == ERR_OK, \"\");\n \/\/ return err;\n \n case PS_INACTIVE: \/\/ only possible during init \n if (mu->data.header.last_committed_decree > max_decree())\n {\n reset(mu->data.header.last_committed_decree);\n }\n else if (mu->data.header.last_committed_decree > _last_committed_decree)\n {\n commit(mu->data.header.last_committed_decree, COMMIT_TO_DECREE_HARD);\n }\n err = mutation_cache::put(mu);\n dassert (err == ERR_OK, \"\");\n return err;\n\n default:\n dassert (false, \"\");\n return 0;\n }\n}\n\n\/\/\n\/\/ ordered commit\n\/\/\nbool prepare_list::commit(decree d, commit_type ct)\n{\n if (d <= last_committed_decree())\n return false;\n \n ballot last_bt = 0;\n switch (ct)\n {\n case COMMIT_TO_DECREE_HARD:\n {\n for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++)\n {\n mutation_ptr mu = get_mutation_by_decree(d0);\n dassert(mu != nullptr &&\n (mu->is_logged()) &&\n mu->data.header.ballot >= last_bt,\n \"mutation %\" PRId64 \" is missing in prepare list\",\n d0\n );\n\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n }\n\n sanity_check();\n return true;\n }\n case COMMIT_TO_DECREE_SOFT:\n {\n for (decree d0 = last_committed_decree() + 1; d0 <= d; d0++)\n {\n mutation_ptr mu = get_mutation_by_decree(d0);\n if (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt)\n {\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n }\n else\n break;\n }\n\n sanity_check();\n return true;\n }\n case COMMIT_ALL_READY:\n {\n if (d != last_committed_decree() + 1)\n return false;\n\n int count = 0;\n mutation_ptr mu = get_mutation_by_decree(last_committed_decree() + 1);\n\n while (mu != nullptr && mu->is_ready_for_commit() && mu->data.header.ballot >= last_bt)\n {\n _last_committed_decree++;\n last_bt = mu->data.header.ballot;\n _committer(mu);\n count++;\n mu = mutation_cache::get_mutation_by_decree(_last_committed_decree + 1);\n }\n\n sanity_check();\n return count > 0;\n }\n default:\n dassert(false, \"invalid commit type %d\", (int)ct);\n }\n\n return false;\n}\n\n}} \/\/ namespace end\n<|endoftext|>"} {"text":"<commit_before>#include \"settings.h\"\n#include \"SimpleIni.h\"\n#include \"GLFW\/glfw3.h\"\n#include <sys\/stat.h>\n\nnamespace konstructs {\n\n void config_path(char* r, size_t size) {\n if(const char* path = std::getenv(\"LOCALAPPDATA\")) {\n \/\/ Looks like Windows, C:\\Users\\(user-name)\\AppData\\Local\n snprintf(r, size, \"%s\\\\%s\", path, \"konstructs.ini\");\n } else if (const char* path = std::getenv(\"SNAP_USER_DATA\")) {\n \/\/ Looks like Linux and inside a snap, $HOME\/snap\/konstructs-client\/(version)\n snprintf(r, size, \"%s\/%s\", path, \"konstructs.conf\");\n } else if (const char* path = std::getenv(\"HOME\")) {\n char _path[4096];\n snprintf(_path, 4096, \"%s\/%s\", path, \".config\");\n struct stat info;\n if (stat(_path, &info) == 0) {\n \/\/ Looks like we have a $HOME\/.config folder, use it\n snprintf(r, size, \"%s\/%s\", _path, \"konstructs.conf\");\n } else {\n \/\/ Just use a classic dotfile in HOME\n snprintf(r, size, \"%s\/%s\", path, \".konstructs.conf\");\n }\n }\n }\n\n void load_settings(Settings &settings) {\n char settings_path[4096];\n config_path(settings_path, 4096);\n\n CSimpleIniA ini;\n ini.SetUnicode(true);\n ini.LoadFile(settings_path);\n\n \/\/ Load default values (and set defaults)\n settings.server.address = ini.GetValue(\"server\", \"address\", \"play.konstructs.org\");\n settings.server.port = (unsigned int)ini.GetLongValue(\"server\", \"port\", 4080);\n settings.server.username = ini.GetValue(\"server\", \"username\", \"\");\n settings.server.password = ini.GetValue(\"server\", \"password\", \"\");\n settings.server.password_save = !settings.server.password.empty();\n settings.client.debug = ini.GetBoolValue(\"client\", \"debug\", false);\n settings.client.field_of_view = (int)ini.GetLongValue(\"client\", \"field_of_view\", 70);\n settings.client.window_width = (unsigned int)ini.GetLongValue(\"client\", \"window_width\", 854);\n settings.client.window_height = (unsigned int)ini.GetLongValue(\"client\", \"window_height\", 480);\n settings.client.radius_start = (unsigned int)ini.GetLongValue(\"client\", \"radius_start\", 5);\n settings.client.radius_max = (unsigned int)ini.GetLongValue(\"client\", \"radius_max\", 20);\n settings.client.frames_per_second = (float)ini.GetLongValue(\"client\", \"frames_per_second\", 60);\n settings.keys.up = (int)ini.GetLongValue(\"keys\", \"up\", GLFW_KEY_W);\n settings.keys.down = (int)ini.GetLongValue(\"keys\", \"down\", GLFW_KEY_S);\n settings.keys.left = (int)ini.GetLongValue(\"keys\", \"left\", GLFW_KEY_A);\n settings.keys.right = (int)ini.GetLongValue(\"keys\", \"right\", GLFW_KEY_D);\n settings.keys.jump = (int)ini.GetLongValue(\"keys\", \"jump\", GLFW_KEY_SPACE);\n settings.keys.fly = (int)ini.GetLongValue(\"keys\", \"fly\", GLFW_KEY_TAB);\n settings.keys.sneak = (int)ini.GetLongValue(\"keys\", \"sneak\", GLFW_KEY_LEFT_SHIFT);\n settings.keys.tertiary = (int)ini.GetLongValue(\"keys\", \"tertiary\", GLFW_KEY_E);\n settings.keys.debug = (int)ini.GetLongValue(\"keys\", \"debug\", GLFW_KEY_F3);\n }\n\n void save_settings(Settings &settings) {\n char settings_path[4096];\n config_path(settings_path, 4096);\n\n CSimpleIniA ini;\n ini.SetUnicode(true);\n\n ini.SetValue(\"server\", \"address\", settings.server.address.c_str());\n ini.SetLongValue(\"server\", \"port\", settings.server.port);\n ini.SetValue(\"server\", \"username\", settings.server.username.c_str());\n\n \/\/ Only save the password back to the file if it's already there.\n \/\/ This allows users to save the password, but it's an opt-in.\n if (settings.server.password_save) {\n ini.SetValue(\"server\", \"password\", settings.server.password.c_str());\n } else {\n ini.SetValue(\"server\", \"password\", \"\");\n }\n\n ini.SetBoolValue(\"client\", \"debug\", settings.client.debug);\n ini.SetLongValue(\"client\", \"field_of_view\", settings.client.field_of_view);\n ini.SetLongValue(\"client\", \"window_width\", settings.client.window_width);\n ini.SetLongValue(\"client\", \"window_height\", settings.client.window_height);\n ini.SetLongValue(\"client\", \"radius_start\", settings.client.radius_start);\n ini.SetLongValue(\"client\", \"radius_max\", settings.client.radius_max);\n ini.SetLongValue(\"client\", \"frames_per_second\", (long)settings.client.frames_per_second);\n ini.SetLongValue(\"keys\", \"up\", settings.keys.up);\n ini.SetLongValue(\"keys\", \"down\", settings.keys.down);\n ini.SetLongValue(\"keys\", \"left\", settings.keys.left);\n ini.SetLongValue(\"keys\", \"right\", settings.keys.right);\n ini.SetLongValue(\"keys\", \"jump\", settings.keys.jump);\n ini.SetLongValue(\"keys\", \"fly\", settings.keys.fly);\n ini.SetLongValue(\"keys\", \"sneak\", settings.keys.sneak);\n ini.SetLongValue(\"keys\", \"tertiary\", settings.keys.tertiary);\n ini.SetLongValue(\"keys\", \"debug\", settings.keys.debug);\n ini.SaveFile(settings_path);\n }\n}<commit_msg>Add failure messages on config load\/save.<commit_after>#include \"settings.h\"\n#include \"SimpleIni.h\"\n#include \"GLFW\/glfw3.h\"\n#include <sys\/stat.h>\n\nnamespace konstructs {\n\n void config_path(char* r, size_t size) {\n if(const char* path = std::getenv(\"LOCALAPPDATA\")) {\n \/\/ Looks like Windows, C:\\Users\\(user-name)\\AppData\\Local\n snprintf(r, size, \"%s\\\\%s\", path, \"konstructs.ini\");\n } else if (const char* path = std::getenv(\"SNAP_USER_DATA\")) {\n \/\/ Looks like Linux and inside a snap, $HOME\/snap\/konstructs-client\/(version)\n snprintf(r, size, \"%s\/%s\", path, \"konstructs.conf\");\n } else if (const char* path = std::getenv(\"HOME\")) {\n char _path[4096];\n snprintf(_path, 4096, \"%s\/%s\", path, \".config\");\n struct stat info;\n if (stat(_path, &info) == 0) {\n \/\/ Looks like we have a $HOME\/.config folder, use it\n snprintf(r, size, \"%s\/%s\", _path, \"konstructs.conf\");\n } else {\n \/\/ Just use a classic dotfile in HOME\n snprintf(r, size, \"%s\/%s\", path, \".konstructs.conf\");\n }\n }\n }\n\n void load_settings(Settings &settings) {\n char settings_path[4096];\n config_path(settings_path, 4096);\n\n CSimpleIniA ini;\n ini.SetUnicode(true);\n if (ini.LoadFile(settings_path) < 0) {\n std::cout << \"Failed to load config file \" << settings_path << std::endl;\n std::cout << \"This is normal if this is your first run.\" << std::endl;\n }\n\n \/\/ Load default values (and set defaults)\n settings.server.address = ini.GetValue(\"server\", \"address\", \"play.konstructs.org\");\n settings.server.port = (unsigned int)ini.GetLongValue(\"server\", \"port\", 4080);\n settings.server.username = ini.GetValue(\"server\", \"username\", \"\");\n settings.server.password = ini.GetValue(\"server\", \"password\", \"\");\n settings.server.password_save = !settings.server.password.empty();\n settings.client.debug = ini.GetBoolValue(\"client\", \"debug\", false);\n settings.client.field_of_view = (int)ini.GetLongValue(\"client\", \"field_of_view\", 70);\n settings.client.window_width = (unsigned int)ini.GetLongValue(\"client\", \"window_width\", 854);\n settings.client.window_height = (unsigned int)ini.GetLongValue(\"client\", \"window_height\", 480);\n settings.client.radius_start = (unsigned int)ini.GetLongValue(\"client\", \"radius_start\", 5);\n settings.client.radius_max = (unsigned int)ini.GetLongValue(\"client\", \"radius_max\", 20);\n settings.client.frames_per_second = (float)ini.GetLongValue(\"client\", \"frames_per_second\", 60);\n settings.keys.up = (int)ini.GetLongValue(\"keys\", \"up\", GLFW_KEY_W);\n settings.keys.down = (int)ini.GetLongValue(\"keys\", \"down\", GLFW_KEY_S);\n settings.keys.left = (int)ini.GetLongValue(\"keys\", \"left\", GLFW_KEY_A);\n settings.keys.right = (int)ini.GetLongValue(\"keys\", \"right\", GLFW_KEY_D);\n settings.keys.jump = (int)ini.GetLongValue(\"keys\", \"jump\", GLFW_KEY_SPACE);\n settings.keys.fly = (int)ini.GetLongValue(\"keys\", \"fly\", GLFW_KEY_TAB);\n settings.keys.sneak = (int)ini.GetLongValue(\"keys\", \"sneak\", GLFW_KEY_LEFT_SHIFT);\n settings.keys.tertiary = (int)ini.GetLongValue(\"keys\", \"tertiary\", GLFW_KEY_E);\n settings.keys.debug = (int)ini.GetLongValue(\"keys\", \"debug\", GLFW_KEY_F3);\n }\n\n void save_settings(Settings &settings) {\n char settings_path[4096];\n config_path(settings_path, 4096);\n\n CSimpleIniA ini;\n ini.SetUnicode(true);\n\n ini.SetValue(\"server\", \"address\", settings.server.address.c_str());\n ini.SetLongValue(\"server\", \"port\", settings.server.port);\n ini.SetValue(\"server\", \"username\", settings.server.username.c_str());\n\n \/\/ Only save the password back to the file if it's already there.\n \/\/ This allows users to save the password, but it's an opt-in.\n if (settings.server.password_save) {\n ini.SetValue(\"server\", \"password\", settings.server.password.c_str());\n } else {\n ini.SetValue(\"server\", \"password\", \"\");\n }\n\n ini.SetBoolValue(\"client\", \"debug\", settings.client.debug);\n ini.SetLongValue(\"client\", \"field_of_view\", settings.client.field_of_view);\n ini.SetLongValue(\"client\", \"window_width\", settings.client.window_width);\n ini.SetLongValue(\"client\", \"window_height\", settings.client.window_height);\n ini.SetLongValue(\"client\", \"radius_start\", settings.client.radius_start);\n ini.SetLongValue(\"client\", \"radius_max\", settings.client.radius_max);\n ini.SetLongValue(\"client\", \"frames_per_second\", (long)settings.client.frames_per_second);\n ini.SetLongValue(\"keys\", \"up\", settings.keys.up);\n ini.SetLongValue(\"keys\", \"down\", settings.keys.down);\n ini.SetLongValue(\"keys\", \"left\", settings.keys.left);\n ini.SetLongValue(\"keys\", \"right\", settings.keys.right);\n ini.SetLongValue(\"keys\", \"jump\", settings.keys.jump);\n ini.SetLongValue(\"keys\", \"fly\", settings.keys.fly);\n ini.SetLongValue(\"keys\", \"sneak\", settings.keys.sneak);\n ini.SetLongValue(\"keys\", \"tertiary\", settings.keys.tertiary);\n ini.SetLongValue(\"keys\", \"debug\", settings.keys.debug);\n if (ini.SaveFile(settings_path) < 0) {\n std::cout << \"Failed to save config file \" << settings_path << std::endl;\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2020, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include <numeric>\n#include <thread>\n\n#include \"algorithms\/heuristics\/solomon.h\"\n#include \"algorithms\/local_search\/local_search.h\"\n#include \"problems\/cvrp\/cvrp.h\"\n#include \"problems\/cvrp\/operators\/cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_or_opt.h\"\n#include \"problems\/cvrp\/operators\/intra_relocate.h\"\n#include \"problems\/cvrp\/operators\/mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/or_opt.h\"\n#include \"problems\/cvrp\/operators\/pd_shift.h\"\n#include \"problems\/cvrp\/operators\/relocate.h\"\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n#include \"problems\/cvrp\/operators\/route_exchange.h\"\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n#include \"problems\/tsp\/tsp.h\"\n#include \"structures\/vroom\/input\/input.h\"\n#include \"structures\/vroom\/raw_route.h\"\n#include \"utils\/helpers.h\"\n\nnamespace vroom {\n\nusing RawSolution = std::vector<RawRoute>;\n\nusing LocalSearch = ls::LocalSearch<RawRoute,\n cvrp::Exchange,\n cvrp::CrossExchange,\n cvrp::MixedExchange,\n cvrp::TwoOpt,\n cvrp::ReverseTwoOpt,\n cvrp::Relocate,\n cvrp::OrOpt,\n cvrp::IntraExchange,\n cvrp::IntraCrossExchange,\n cvrp::IntraMixedExchange,\n cvrp::IntraRelocate,\n cvrp::IntraOrOpt,\n cvrp::PDShift,\n cvrp::RouteExchange>;\n\nconst std::vector<HeuristicParameters> CVRP::homogeneous_parameters =\n {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)};\n\nconst std::vector<HeuristicParameters> CVRP::heterogeneous_parameters =\n {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)};\n\nCVRP::CVRP(const Input& input) : VRP(input) {\n}\n\nSolution CVRP::solve(unsigned exploration_level,\n unsigned nb_threads,\n const std::vector<HeuristicParameters>& h_param) const {\n if (_input.vehicles.size() == 1 and !_input.has_skills() and\n _input.zero_amount().size() == 0) {\n \/\/ This is a plain TSP, no need to go through the trouble below.\n std::vector<Index> job_ranks(_input.jobs.size());\n std::iota(job_ranks.begin(), job_ranks.end(), 0);\n\n TSP p(_input, job_ranks, 0);\n\n RawRoute r(_input, 0);\n r.set_route(_input, p.raw_solve(nb_threads));\n\n return utils::format_solution(_input, {r});\n }\n\n \/\/ Use vector of parameters when passed for debugging, else use\n \/\/ predefined parameter set.\n const auto& parameters = (!h_param.empty())\n ? h_param\n : (_input.has_homogeneous_locations())\n ? homogeneous_parameters\n : heterogeneous_parameters;\n unsigned max_nb_jobs_removal = exploration_level;\n unsigned nb_init_solutions = h_param.size();\n\n if (nb_init_solutions == 0) {\n \/\/ Local search parameter.\n nb_init_solutions = 4 * (exploration_level + 1);\n if (exploration_level >= 4) {\n nb_init_solutions += 4;\n }\n if (exploration_level >= 5) {\n nb_init_solutions += 4;\n }\n }\n assert(nb_init_solutions <= parameters.size());\n\n std::vector<RawSolution> solutions(nb_init_solutions);\n std::vector<utils::SolutionIndicators> sol_indicators(nb_init_solutions);\n\n \/\/ Split the work among threads.\n std::vector<std::vector<std::size_t>>\n thread_ranks(nb_threads, std::vector<std::size_t>());\n for (std::size_t i = 0; i < nb_init_solutions; ++i) {\n thread_ranks[i % nb_threads].push_back(i);\n }\n\n auto run_solve = [&](const std::vector<std::size_t>& param_ranks) {\n for (auto rank : param_ranks) {\n auto& p = parameters[rank];\n\n switch (p.heuristic) {\n case HEURISTIC::BASIC:\n solutions[rank] =\n heuristics::basic<RawSolution>(_input, p.init, p.regret_coeff);\n break;\n case HEURISTIC::DYNAMIC:\n solutions[rank] =\n heuristics::dynamic_vehicle_choice<RawSolution>(_input,\n p.init,\n p.regret_coeff);\n break;\n }\n\n \/\/ Local search phase.\n LocalSearch ls(_input, solutions[rank], max_nb_jobs_removal);\n ls.run();\n\n \/\/ Store solution indicators.\n sol_indicators[rank] = ls.indicators();\n }\n };\n\n std::vector<std::thread> solving_threads;\n\n for (std::size_t i = 0; i < nb_threads; ++i) {\n solving_threads.emplace_back(run_solve, thread_ranks[i]);\n }\n\n for (auto& t : solving_threads) {\n t.join();\n }\n\n auto best_indic =\n std::min_element(sol_indicators.cbegin(), sol_indicators.cend());\n\n return utils::format_solution(_input,\n solutions[std::distance(sol_indicators.cbegin(),\n best_indic)]);\n}\n\n} \/\/ namespace vroom\n<commit_msg>Don't solve as a TSP when there are shipments. #333<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2020, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include <numeric>\n#include <thread>\n\n#include \"algorithms\/heuristics\/solomon.h\"\n#include \"algorithms\/local_search\/local_search.h\"\n#include \"problems\/cvrp\/cvrp.h\"\n#include \"problems\/cvrp\/operators\/cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_or_opt.h\"\n#include \"problems\/cvrp\/operators\/intra_relocate.h\"\n#include \"problems\/cvrp\/operators\/mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/or_opt.h\"\n#include \"problems\/cvrp\/operators\/pd_shift.h\"\n#include \"problems\/cvrp\/operators\/relocate.h\"\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n#include \"problems\/cvrp\/operators\/route_exchange.h\"\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n#include \"problems\/tsp\/tsp.h\"\n#include \"structures\/vroom\/input\/input.h\"\n#include \"structures\/vroom\/raw_route.h\"\n#include \"utils\/helpers.h\"\n\nnamespace vroom {\n\nusing RawSolution = std::vector<RawRoute>;\n\nusing LocalSearch = ls::LocalSearch<RawRoute,\n cvrp::Exchange,\n cvrp::CrossExchange,\n cvrp::MixedExchange,\n cvrp::TwoOpt,\n cvrp::ReverseTwoOpt,\n cvrp::Relocate,\n cvrp::OrOpt,\n cvrp::IntraExchange,\n cvrp::IntraCrossExchange,\n cvrp::IntraMixedExchange,\n cvrp::IntraRelocate,\n cvrp::IntraOrOpt,\n cvrp::PDShift,\n cvrp::RouteExchange>;\n\nconst std::vector<HeuristicParameters> CVRP::homogeneous_parameters =\n {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)};\n\nconst std::vector<HeuristicParameters> CVRP::heterogeneous_parameters =\n {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)};\n\nCVRP::CVRP(const Input& input) : VRP(input) {\n}\n\nSolution CVRP::solve(unsigned exploration_level,\n unsigned nb_threads,\n const std::vector<HeuristicParameters>& h_param) const {\n if (_input.vehicles.size() == 1 and !_input.has_skills() and\n _input.zero_amount().size() == 0 and !_input.has_shipments()) {\n \/\/ This is a plain TSP, no need to go through the trouble below.\n std::vector<Index> job_ranks(_input.jobs.size());\n std::iota(job_ranks.begin(), job_ranks.end(), 0);\n\n TSP p(_input, job_ranks, 0);\n\n RawRoute r(_input, 0);\n r.set_route(_input, p.raw_solve(nb_threads));\n\n return utils::format_solution(_input, {r});\n }\n\n \/\/ Use vector of parameters when passed for debugging, else use\n \/\/ predefined parameter set.\n const auto& parameters = (!h_param.empty())\n ? h_param\n : (_input.has_homogeneous_locations())\n ? homogeneous_parameters\n : heterogeneous_parameters;\n unsigned max_nb_jobs_removal = exploration_level;\n unsigned nb_init_solutions = h_param.size();\n\n if (nb_init_solutions == 0) {\n \/\/ Local search parameter.\n nb_init_solutions = 4 * (exploration_level + 1);\n if (exploration_level >= 4) {\n nb_init_solutions += 4;\n }\n if (exploration_level >= 5) {\n nb_init_solutions += 4;\n }\n }\n assert(nb_init_solutions <= parameters.size());\n\n std::vector<RawSolution> solutions(nb_init_solutions);\n std::vector<utils::SolutionIndicators> sol_indicators(nb_init_solutions);\n\n \/\/ Split the work among threads.\n std::vector<std::vector<std::size_t>>\n thread_ranks(nb_threads, std::vector<std::size_t>());\n for (std::size_t i = 0; i < nb_init_solutions; ++i) {\n thread_ranks[i % nb_threads].push_back(i);\n }\n\n auto run_solve = [&](const std::vector<std::size_t>& param_ranks) {\n for (auto rank : param_ranks) {\n auto& p = parameters[rank];\n\n switch (p.heuristic) {\n case HEURISTIC::BASIC:\n solutions[rank] =\n heuristics::basic<RawSolution>(_input, p.init, p.regret_coeff);\n break;\n case HEURISTIC::DYNAMIC:\n solutions[rank] =\n heuristics::dynamic_vehicle_choice<RawSolution>(_input,\n p.init,\n p.regret_coeff);\n break;\n }\n\n \/\/ Local search phase.\n LocalSearch ls(_input, solutions[rank], max_nb_jobs_removal);\n ls.run();\n\n \/\/ Store solution indicators.\n sol_indicators[rank] = ls.indicators();\n }\n };\n\n std::vector<std::thread> solving_threads;\n\n for (std::size_t i = 0; i < nb_threads; ++i) {\n solving_threads.emplace_back(run_solve, thread_ranks[i]);\n }\n\n for (auto& t : solving_threads) {\n t.join();\n }\n\n auto best_indic =\n std::min_element(sol_indicators.cbegin(), sol_indicators.cend());\n\n return utils::format_solution(_input,\n solutions[std::distance(sol_indicators.cbegin(),\n best_indic)]);\n}\n\n} \/\/ namespace vroom\n<|endoftext|>"} {"text":"<commit_before>\/\/ibnu.yahya@toroo.org\n\n#include \"ign.h\"\n#include \"fs.h\"\n#include \"cmath\"\n#include <QtCore\/QVariant>\n#include <qjson\/parser.h>\n#include <qjson\/parserrunnable.h>\n#include <qjson\/serializer.h>\n#include <qjson\/serializerrunnable.h>\n#include <qjson\/qjson_export.h>\n#include <qjson\/qobjecthelper.h>\n#include <iostream>\nusing namespace std;\nign::ign(QObject *parent)\n : QObject(parent)\n{\n frame = web.page()->mainFrame();\n connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));\n this->filesystem = new fs;\n this->dl = new QtDownload;\n this->sqldrv = new ignsql;\n\n QFile jqueryfile;\n\n QString jquery;\n jqueryfile.setFileName(\":\/js\/jquery.js\");\n if(jqueryfile.open(QIODevice::ReadOnly)){\n jquery = jqueryfile.readAll();\n frame->evaluateJavaScript(jquery);\n }\n jqueryfile.close();\n\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);\n web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);\n web.settings()->setAttribute(QWebSettings::JavaEnabled,true);\n web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);\n web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);\n \/\/webstorage\n QString home = QDir::homePath();\n home += \"\/.ignsdk\";\n web.settings()->setLocalStoragePath(home);\n web.settings()->enablePersistentStorage(home);\n web.settings()->setOfflineWebApplicationCachePath(home);\n \/\/stylesheet default\n web.settings()->setUserStyleSheetUrl(QUrl(\"qrc:\/css\/ign.css\"));\n \/\/config mode disable\n web.page()->action(QWebPage::Back)->setVisible(false);\n web.page()->action(QWebPage::Forward)->setVisible(false);\n web.page()->action(QWebPage::Reload)->setVisible(false);\n web.page()->action(QWebPage::Stop)->setVisible(false);\n \/\/set fullscrean mode default to false\n fullscreen = false;\n\n \/\/web.setWindowOpacity(0.1);\n}\n\nvoid ign::ignJS(){\n this->frame->addToJavaScriptWindowObject(\"ign\",this);\n \/\/fs filesystem;\n \/\/this->frame->addToJavaScriptWindowObject(\"fs\",filesystem);\n}\nvoid ign::getToggleFullScreen(){\n if(this->fullscreen){\n this->web.showNormal();\n this->fullscreen = false;\n }\n else{\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n}\n\nvoid ign::getFullScreen(bool screen){\n if(screen){\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n else {\n this->web.showNormal();\n this->fullscreen = false;\n }\n}\n\nvoid ign::render(QString w){\n this->web.load(QUrl(w));\n}\n\nvoid ign::show(){\n this->web.show();\n}\n\nvoid ign::showMaximized(){\n this->web.showMaximized();\n}\n\nvoid ign::showMinimized(){\n this->web.showMinimized();\n}\n\nvoid ign::showMessage(const QString &msg)\n{\n QMessageBox::information(0, \"Information\", msg);\n}\n\nvoid ign::quit(){\n this->web.close();\n}\n\nvoid ign::back(){\n this->web.page()->action(QWebPage::Back)->setVisible(true);\n}\n\nvoid ign::forward(){\n this->web.page()->action(QWebPage::Forward)->setVisible(true);\n}\n\nvoid ign::stop(){\n this->web.page()->action(QWebPage::Stop)->setVisible(true);\n}\n\nvoid ign::reload(){\n this->web.page()->action(QWebPage::Reload)->setVisible(true);\n}\n\nvoid ign::setDev(bool v){\n this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);\n}\n\nvoid ign::websecurity(bool c){\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);\n}\n\nvoid ign::widgetSizeMax(int w, int h){\n this->web.setMaximumSize(w,h);\n}\n\nvoid ign::widgetSizeMin(int w, int h){\n this->web.setMinimumSize(w,h);\n}\n\nvoid ign::widgetSize(int w, int h){\n this->web.resize(w,h);\n}\n\nvoid ign::widgetNoFrame(){\n this->web.setWindowFlags(Qt::FramelessWindowHint);\n}\n\nvoid ign::widgetTransparent(){\n QPalette pal = this->web.palette();\n pal.setBrush(QPalette::Base, Qt::transparent);\n this->web.setPalette(pal);\n this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);\n this->web.setAttribute(Qt::WA_TranslucentBackground, true);\n}\n\nQString ign::cliOut(const QString& cli){\n QProcess os;\n os.start(cli);\n os.waitForFinished(-1);\n return os.readAllStandardOutput();\n}\n\nvoid ign::mousePressEvent(QMouseEvent *event)\n{\n qDebug()<<event->type();\n}\n\nvoid ign::config(QString path){\n QFile config_file;\n QDir::setCurrent(path);\n config_file.setFileName(\"ignsdk.json\");\n QByteArray config;\n if(config_file.open(QIODevice::ReadOnly)){\n config = config_file.readAll();\n QJson::Parser parse;\n bool ok;\n\n QVariantMap result = parse.parse(config, &ok).toMap();\n if (!ok) {\n qFatal(\"An error occurred during parsing\");\n exit (1);\n }\n\n QVariantMap configure = result[\"config\"].toMap();\n\n if(configure[\"debug\"].toBool()){\n this->setDev(true);\n }\n if(configure[\"websecurity\"].toBool()){\n this->websecurity(true);\n }\n if(configure[\"name\"].toString() != \"\"){\n this->web.setWindowTitle(configure[\"name\"].toString());\n }\n QVariantMap window = result[\"window\"].toMap();\n if(window[\"transparent\"].toBool()){\n this->widgetTransparent();\n }\n if(window[\"noframe\"].toBool()){\n this->widgetNoFrame();\n }\n if(window[\"fullscreen\"].toBool()){\n this->getToggleFullScreen();\n }\n if(window[\"width\"].toInt() != 0){\n if(window[\"height\"].toInt() != 0){\n this->widgetSize(window[\"width\"].toInt(),window[\"height\"].toInt());\n }\n }\n\n foreach (QVariant button, result[\"button\"].toList()) {\n\n if (button.toString() == \"back\"){\n this->back();\n }\n if (button.toString() == \"forward\"){\n this->forward();\n }\n if (button.toString() == \"stop\"){\n this->stop();\n }\n if (button.toString() == \"reload\"){\n this->reload();\n }\n\n }\n\n }\n\n config_file.close();\n}\n\nQString ign::hash(const QString &data,QString hash_func){\n QByteArray hash;\n QByteArray byteArray = data.toLatin1();\n if(hash_func == \"md4\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);\n }\n else if(hash_func == \"md5\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);\n }\n else if(hash_func == \"sha1\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);\n }\n\n return hash.toHex();\n}\n\nQString ign::homePath(){\n return this->filesystem->home_path();\n}\n\nbool ign::createFile(const QString &path, const QString &data){\n return this->filesystem->create_file(path,data);\n}\n\nQString ign::readFile(const QString &path){\n return this->filesystem->read_file(path);\n}\n\nvoid ign::saveFile(const QByteArray &data, QString filename, QString path){\n QByteArray byteArray = QByteArray::fromBase64(data);\n QString home;\n home = path+\"\/\"+filename;\n QFile localFile(home);\n if (!localFile.open(QIODevice::WriteOnly))\n return;\n localFile.write(byteArray);\n localFile.close();\n}\n\nvoid ign::download(QString data,QString path,QString id){\n this->dl = new QtDownload;\n this->id = id;\n this->dl->setTarget(data);\n this->dl->save(path);\n this->dl->download();\n connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));\n}\n\nvoid ign::download_signal(qint64 recieved, qint64 total){\n QString r = QString::number(recieved);\n QString t = QString::number(total);\n float pr = (r.toFloat()\/t.toFloat())*100;\n QString prs = QString::number(pr,'g',5);\n qDebug() << prs;\n QString idx = this->id;\n frame->evaluateJavaScript(\"document.getElementById('\"+idx+\"').setAttribute('style','width : \"+prs+\"%')\");\n\n}\n\n\/*IGN SQL*\/\nvoid ign::sql(const QString &drv, QString connect){\n this->sqldrv->driver(drv,connect);\n}\n\n\/*void ign::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n QMessageBox::information(0, \"Information\", \"press\");\n mMoving = true;\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseMoveEvent(QMouseEvent *event)\n{\n if( event->buttons().testFlag(Qt::LeftButton) && mMoving)\n {\n this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n mMoving = false;\n }\n}*\/\n<commit_msg>ADD: maximize to ignsdk manifest<commit_after>\/\/ibnu.yahya@toroo.org\n\n#include \"ign.h\"\n#include \"fs.h\"\n#include \"cmath\"\n#include <QtCore\/QVariant>\n#include <qjson\/parser.h>\n#include <qjson\/parserrunnable.h>\n#include <qjson\/serializer.h>\n#include <qjson\/serializerrunnable.h>\n#include <qjson\/qjson_export.h>\n#include <qjson\/qobjecthelper.h>\n#include <iostream>\nusing namespace std;\nign::ign(QObject *parent)\n : QObject(parent)\n{\n frame = web.page()->mainFrame();\n connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));\n this->filesystem = new fs;\n this->dl = new QtDownload;\n this->sqldrv = new ignsql;\n\n QFile jqueryfile;\n\n QString jquery;\n jqueryfile.setFileName(\":\/js\/jquery.js\");\n if(jqueryfile.open(QIODevice::ReadOnly)){\n jquery = jqueryfile.readAll();\n frame->evaluateJavaScript(jquery);\n }\n jqueryfile.close();\n\n QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);\n web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);\n web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);\n web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);\n web.settings()->setAttribute(QWebSettings::JavaEnabled,true);\n web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);\n web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);\n \/\/webstorage\n QString home = QDir::homePath();\n home += \"\/.ignsdk\";\n web.settings()->setLocalStoragePath(home);\n web.settings()->enablePersistentStorage(home);\n web.settings()->setOfflineWebApplicationCachePath(home);\n \/\/stylesheet default\n web.settings()->setUserStyleSheetUrl(QUrl(\"qrc:\/css\/ign.css\"));\n \/\/config mode disable\n web.page()->action(QWebPage::Back)->setVisible(false);\n web.page()->action(QWebPage::Forward)->setVisible(false);\n web.page()->action(QWebPage::Reload)->setVisible(false);\n web.page()->action(QWebPage::Stop)->setVisible(false);\n \/\/set fullscrean mode default to false\n fullscreen = false;\n\n \/\/web.setWindowOpacity(0.1);\n}\n\nvoid ign::ignJS(){\n this->frame->addToJavaScriptWindowObject(\"ign\",this);\n \/\/fs filesystem;\n \/\/this->frame->addToJavaScriptWindowObject(\"fs\",filesystem);\n}\nvoid ign::getToggleFullScreen(){\n if(this->fullscreen){\n this->web.showNormal();\n this->fullscreen = false;\n }\n else{\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n}\n\nvoid ign::getFullScreen(bool screen){\n if(screen){\n this->web.showFullScreen();\n this->fullscreen = true;\n }\n else {\n this->web.showNormal();\n this->fullscreen = false;\n }\n}\n\nvoid ign::render(QString w){\n this->web.load(QUrl(w));\n}\n\nvoid ign::show(){\n this->web.show();\n}\n\nvoid ign::showMaximized(){\n this->web.showMaximized();\n}\n\nvoid ign::showMinimized(){\n this->web.showMinimized();\n}\n\nvoid ign::showMessage(const QString &msg)\n{\n QMessageBox::information(0, \"Information\", msg);\n}\n\nvoid ign::quit(){\n this->web.close();\n}\n\nvoid ign::back(){\n this->web.page()->action(QWebPage::Back)->setVisible(true);\n}\n\nvoid ign::forward(){\n this->web.page()->action(QWebPage::Forward)->setVisible(true);\n}\n\nvoid ign::stop(){\n this->web.page()->action(QWebPage::Stop)->setVisible(true);\n}\n\nvoid ign::reload(){\n this->web.page()->action(QWebPage::Reload)->setVisible(true);\n}\n\nvoid ign::setDev(bool v){\n this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);\n}\n\nvoid ign::websecurity(bool c){\n web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);\n}\n\nvoid ign::widgetSizeMax(int w, int h){\n this->web.setMaximumSize(w,h);\n}\n\nvoid ign::widgetSizeMin(int w, int h){\n this->web.setMinimumSize(w,h);\n}\n\nvoid ign::widgetSize(int w, int h){\n this->web.resize(w,h);\n}\n\nvoid ign::widgetNoFrame(){\n this->web.setWindowFlags(Qt::FramelessWindowHint);\n}\n\nvoid ign::widgetTransparent(){\n QPalette pal = this->web.palette();\n pal.setBrush(QPalette::Base, Qt::transparent);\n this->web.setPalette(pal);\n this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);\n this->web.setAttribute(Qt::WA_TranslucentBackground, true);\n}\n\nQString ign::cliOut(const QString& cli){\n QProcess os;\n os.start(cli);\n os.waitForFinished(-1);\n return os.readAllStandardOutput();\n}\n\nvoid ign::mousePressEvent(QMouseEvent *event)\n{\n qDebug()<<event->type();\n}\n\nvoid ign::config(QString path){\n QFile config_file;\n QDir::setCurrent(path);\n config_file.setFileName(\"ignsdk.json\");\n QByteArray config;\n if(config_file.open(QIODevice::ReadOnly)){\n config = config_file.readAll();\n QJson::Parser parse;\n bool ok;\n\n QVariantMap result = parse.parse(config, &ok).toMap();\n if (!ok) {\n qFatal(\"An error occurred during parsing\");\n exit (1);\n }\n\n QVariantMap configure = result[\"config\"].toMap();\n\n if(configure[\"debug\"].toBool()){\n this->setDev(true);\n }\n if(configure[\"websecurity\"].toBool()){\n this->websecurity(true);\n }\n if(configure[\"name\"].toString() != \"\"){\n this->web.setWindowTitle(configure[\"name\"].toString());\n }\n QVariantMap window = result[\"window\"].toMap();\n if(window[\"transparent\"].toBool()){\n this->widgetTransparent();\n }\n if(window[\"noframe\"].toBool()){\n this->widgetNoFrame();\n }\n if(window[\"fullscreen\"].toBool()){\n this->getToggleFullScreen();\n }\n if(window[\"maximize\"].toBool()){\n this->showMaximized();\n }\n if(window[\"width\"].toInt() != 0){\n if(window[\"height\"].toInt() != 0){\n this->widgetSize(window[\"width\"].toInt(),window[\"height\"].toInt());\n }\n }\n\n foreach (QVariant button, result[\"button\"].toList()) {\n\n if (button.toString() == \"back\"){\n this->back();\n }\n if (button.toString() == \"forward\"){\n this->forward();\n }\n if (button.toString() == \"stop\"){\n this->stop();\n }\n if (button.toString() == \"reload\"){\n this->reload();\n }\n\n }\n\n }\n\n config_file.close();\n}\n\nQString ign::hash(const QString &data,QString hash_func){\n QByteArray hash;\n QByteArray byteArray = data.toLatin1();\n if(hash_func == \"md4\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);\n }\n else if(hash_func == \"md5\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);\n }\n else if(hash_func == \"sha1\"){\n hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);\n }\n\n return hash.toHex();\n}\n\nQString ign::homePath(){\n return this->filesystem->home_path();\n}\n\nbool ign::createFile(const QString &path, const QString &data){\n return this->filesystem->create_file(path,data);\n}\n\nQString ign::readFile(const QString &path){\n return this->filesystem->read_file(path);\n}\n\nvoid ign::saveFile(const QByteArray &data, QString filename, QString path){\n QByteArray byteArray = QByteArray::fromBase64(data);\n QString home;\n home = path+\"\/\"+filename;\n QFile localFile(home);\n if (!localFile.open(QIODevice::WriteOnly))\n return;\n localFile.write(byteArray);\n localFile.close();\n}\n\nvoid ign::download(QString data,QString path,QString id){\n this->dl = new QtDownload;\n this->id = id;\n this->dl->setTarget(data);\n this->dl->save(path);\n this->dl->download();\n connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));\n}\n\nvoid ign::download_signal(qint64 recieved, qint64 total){\n QString r = QString::number(recieved);\n QString t = QString::number(total);\n float pr = (r.toFloat()\/t.toFloat())*100;\n QString prs = QString::number(pr,'g',5);\n qDebug() << prs;\n QString idx = this->id;\n frame->evaluateJavaScript(\"document.getElementById('\"+idx+\"').setAttribute('style','width : \"+prs+\"%')\");\n\n}\n\n\/*IGN SQL*\/\nvoid ign::sql(const QString &drv, QString connect){\n this->sqldrv->driver(drv,connect);\n}\n\n\/*void ign::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n QMessageBox::information(0, \"Information\", \"press\");\n mMoving = true;\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseMoveEvent(QMouseEvent *event)\n{\n if( event->buttons().testFlag(Qt::LeftButton) && mMoving)\n {\n this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));\n mLastMousePosition = event->pos();\n }\n}\n\nvoid ign::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n mMoving = false;\n }\n}*\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ -D_GNU_SOURCE makes SOCK_NONBLOCK etc. available on linux\n#undef _GNU_SOURCE\n#define _GNU_SOURCE\n\n#include <nan.h>\n\n#include <errno.h>\n#include <stddef.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <sys\/socket.h>\n#include <sys\/un.h>\n\n#include <map>\n\n#define offset_of(type, member) \\\n ((intptr_t) ((char *) &(((type *) 8)->member) - 8))\n\n#define container_of(ptr, type, member) \\\n ((type *) ((char *) (ptr) - offset_of(type, member)))\n\nnamespace {\n\nvoid OnEvent(uv_poll_t* handle, int status, int events);\n\nusing node::FatalException;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::TryCatch;\nusing v8::Value;\n\nstruct SocketContext {\n Persistent<Function> recv_cb_;\n Persistent<Function> writable_cb_;\n uv_poll_t handle_;\n int fd_;\n};\n\ntypedef std::map<int, SocketContext*> watchers_t;\n\nwatchers_t watchers;\n\n\nvoid SetNonBlock(int fd) {\n int flags;\n int r;\n\n flags = fcntl(fd, F_GETFL);\n assert(flags != -1);\n\n r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n assert(r != -1);\n}\n\n\nvoid SetCloExec(int fd) {\n int flags;\n int r;\n\n flags = fcntl(fd, F_GETFD);\n assert(flags != -1);\n\n r = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);\n assert(r != -1);\n}\n\nvoid OnRecv(SocketContext* sc) {\n NanScope();\n Handle<Value> argv[3];\n msghdr msg;\n iovec iov;\n ssize_t err;\n char scratch[65536];\n\n \/* Union to avoid breaking strict-aliasing rules *\/\n union {\n struct sockaddr_un sun;\n struct sockaddr_storage ss;\n } u_addr;\n\n argv[0] = argv[1] = argv[2] = NanNull();\n\n iov.iov_base = scratch;\n iov.iov_len = sizeof scratch;\n\n u_addr.sun.sun_path[0] = '\\0';\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n msg.msg_name = &u_addr.ss;\n msg.msg_namelen = sizeof u_addr.ss;\n\n do\n err = recvmsg(sc->fd_, &msg, 0);\n while (err == -1 && errno == EINTR);\n\n if (err == -1) {\n err = -errno;\n } else {\n argv[1] = NanNewBufferHandle(scratch, err);\n if (u_addr.sun.sun_path[0] != '\\0') {\n argv[2] = NanNew<String>(u_addr.sun.sun_path);\n }\n }\n\n argv[0] = NanNew(err);\n\n TryCatch tc;\n NanNew(sc->recv_cb_)->Call(NanGetCurrentContext()->Global(),\n sizeof(argv) \/ sizeof(argv[0]),\n argv);\n\n if (tc.HasCaught())\n FatalException(tc);\n}\n\nvoid OnWritable(SocketContext* sc) {\n NanScope();\n TryCatch tc;\n uv_poll_start(&sc->handle_, UV_READABLE, OnEvent);\n NanNew(sc->writable_cb_)->Call(NanGetCurrentContext()->Global(), 0, 0);\n if (tc.HasCaught())\n FatalException(tc);\n}\n\nvoid OnEvent(uv_poll_t* handle, int status, int events) {\n assert(0 == status);\n assert(0 == (events & ~(UV_READABLE | UV_WRITABLE)));\n SocketContext* sc = container_of(handle, SocketContext, handle_);\n if (events & UV_READABLE)\n OnRecv(sc);\n\n if (events & UV_WRITABLE)\n OnWritable(sc);\n}\n\nvoid StartWatcher(int fd, Handle<Value> recv_cb, Handle<Value> writable_cb) {\n \/\/ start listening for incoming dgrams\n SocketContext* sc = new SocketContext;\n NanAssignPersistent(sc->recv_cb_, recv_cb.As<Function>());\n NanAssignPersistent(sc->writable_cb_, writable_cb.As<Function>());\n sc->fd_ = fd;\n\n uv_poll_init(uv_default_loop(), &sc->handle_, fd);\n uv_poll_start(&sc->handle_, UV_READABLE, OnEvent);\n\n \/\/ so we can disarm the watcher when close(fd) is called\n watchers.insert(watchers_t::value_type(fd, sc));\n}\n\n\nvoid FreeSocketContext(uv_handle_t* handle) {\n SocketContext* sc = container_of(handle, SocketContext, handle_);\n delete sc;\n}\n\n\nvoid StopWatcher(int fd) {\n watchers_t::iterator iter = watchers.find(fd);\n assert(iter != watchers.end());\n\n SocketContext* sc = iter->second;\n NanDisposePersistent(sc->recv_cb_);\n NanDisposePersistent(sc->writable_cb_);\n watchers.erase(iter);\n\n uv_poll_stop(&sc->handle_);\n uv_close(reinterpret_cast<uv_handle_t*>(&sc->handle_), FreeSocketContext);\n}\n\n\nNAN_METHOD(Socket) {\n NanScope();\n Local<Value> recv_cb;\n Local<Value> writable_cb;\n int protocol;\n int domain;\n int type;\n int fd;\n\n assert(args.Length() == 5);\n\n domain = args[0]->Int32Value();\n type = args[1]->Int32Value();\n protocol = args[2]->Int32Value();\n recv_cb = args[3];\n writable_cb = args[4];\n\n#if defined(SOCK_NONBLOCK)\n type |= SOCK_NONBLOCK;\n#endif\n#if defined(SOCK_CLOEXEC)\n type |= SOCK_CLOEXEC;\n#endif\n\n fd = socket(domain, type, protocol);\n if (fd == -1) {\n fd = -errno;\n goto out;\n }\n\n #if !defined(SOCK_NONBLOCK)\n SetNonBlock(fd);\n#endif\n#if !defined(SOCK_CLOEXEC)\n SetCloExec(fd);\n#endif\n\n StartWatcher(fd, recv_cb, writable_cb);\n\nout:\n NanReturnValue(NanNew(fd));\n}\n\n\nNAN_METHOD(Bind) {\n NanScope();\n sockaddr_un s;\n int err;\n int fd;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n String::Utf8Value path(args[1]);\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n err = 0;\n if (bind(fd, reinterpret_cast<sockaddr*>(&s), sizeof(s)))\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(SendTo) {\n NanScope();\n Local<Object> buf;\n sockaddr_un s;\n size_t offset;\n size_t length;\n msghdr msg;\n iovec iov;\n int err;\n int fd;\n int r;\n\n assert(args.Length() == 5);\n\n fd = args[0]->Int32Value();\n buf = args[1]->ToObject();\n offset = args[2]->Uint32Value();\n length = args[3]->Uint32Value();\n String::Utf8Value path(args[4]);\n\n assert(node::Buffer::HasInstance(buf));\n assert(offset + length <= node::Buffer::Length(buf));\n\n iov.iov_base = node::Buffer::Data(buf) + offset;\n iov.iov_len = length;\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n msg.msg_name = reinterpret_cast<void*>(&s);\n msg.msg_namelen = sizeof(s);\n\n do\n r = sendmsg(fd, &msg, 0);\n while (r == -1 && errno == EINTR);\n\n err = 0;\n if (r == -1)\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(Send) {\n NanScope();\n Local<Object> buf;\n msghdr msg;\n iovec iov;\n int err;\n int fd;\n int r;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n buf = args[1]->ToObject();\n assert(node::Buffer::HasInstance(buf));\n\n iov.iov_base = node::Buffer::Data(buf);\n iov.iov_len = node::Buffer::Length(buf);\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n\n do\n r = sendmsg(fd, &msg, 0);\n while (r == -1 && errno == EINTR);\n\n err = 0;\n if (r == -1) {\n err = -errno;\n if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {\n watchers_t::iterator iter = watchers.find(fd);\n assert(iter != watchers.end());\n SocketContext* sc = iter->second;\n uv_poll_start(&sc->handle_, UV_READABLE | UV_WRITABLE, OnEvent);\n err = 1;\n }\n }\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(Connect) {\n NanScope();\n sockaddr_un s;\n int err;\n int fd;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n String::Utf8Value path(args[1]);\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n err = 0;\n if (connect(fd, reinterpret_cast<sockaddr*>(&s), sizeof(s)))\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\n\nNAN_METHOD(Close) {\n NanScope();\n int err;\n int fd;\n\n assert(args.Length() == 1);\n fd = args[0]->Int32Value();\n\n \/\/ Suppress EINTR and EINPROGRESS. EINTR means that the close() system call\n \/\/ was interrupted by a signal. According to POSIX, the file descriptor is\n \/\/ in an undefined state afterwards. It's not safe to try closing it again\n \/\/ because it may have been closed, despite the signal. If we call close()\n \/\/ again, then it would either:\n \/\/\n \/\/ a) fail with EBADF, or\n \/\/\n \/\/ b) close the wrong file descriptor if another thread or a signal handler\n \/\/ has reused it in the mean time.\n \/\/\n \/\/ Neither is what we want but scenario B is particularly bad. Not retrying\n \/\/ the close() could, in theory, lead to file descriptor leaks but, in\n \/\/ practice, operating systems do the right thing and close the file\n \/\/ descriptor, regardless of whether the operation was interrupted by\n \/\/ a signal.\n \/\/\n \/\/ EINPROGRESS is benign. It means the close operation was interrupted but\n \/\/ that the file descriptor has been closed or is being closed in the\n \/\/ background. It's informative, not an error.\n err = 0;\n if (close(fd))\n if (errno != EINTR && errno != EINPROGRESS)\n err = -errno;\n\n StopWatcher(fd);\n NanReturnValue(NanNew(err));\n}\n\n\nvoid Initialize(Handle<Object> target) {\n \/\/ don't need to be read-only, only used by the JS shim\n target->Set(NanNew(\"AF_UNIX\"), NanNew(AF_UNIX));\n target->Set(NanNew(\"SOCK_DGRAM\"), NanNew(SOCK_DGRAM));\n\n target->Set(NanNew(\"socket\"),\n NanNew<FunctionTemplate>(Socket)->GetFunction());\n\n target->Set(NanNew(\"bind\"),\n NanNew<FunctionTemplate>(Bind)->GetFunction());\n\n target->Set(NanNew(\"sendto\"),\n NanNew<FunctionTemplate>(SendTo)->GetFunction());\n\n target->Set(NanNew(\"send\"),\n NanNew<FunctionTemplate>(Send)->GetFunction());\n\n target->Set(NanNew(\"connect\"),\n NanNew<FunctionTemplate>(Connect)->GetFunction());\n\n target->Set(NanNew(\"close\"),\n NanNew<FunctionTemplate>(Close)->GetFunction());\n}\n\n\n} \/\/ anonymous namespace\n\nNODE_MODULE(unix_dgram, Initialize)\n<commit_msg>src: Fixing compilation error on node 11<commit_after>\/\/ -D_GNU_SOURCE makes SOCK_NONBLOCK etc. available on linux\n#undef _GNU_SOURCE\n#define _GNU_SOURCE\n\n#include <nan.h>\n\n#include <errno.h>\n#include <stddef.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include <sys\/socket.h>\n#include <sys\/un.h>\n\n#include <map>\n\n#define offset_of(type, member) \\\n ((intptr_t) ((char *) &(((type *) 8)->member) - 8))\n\n#define container_of(ptr, type, member) \\\n ((type *) ((char *) (ptr) - offset_of(type, member)))\n\nnamespace {\n\nvoid OnEvent(uv_poll_t* handle, int status, int events);\n\nusing node::FatalException;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::TryCatch;\nusing v8::Value;\n\nstruct SocketContext {\n Persistent<Function> recv_cb_;\n Persistent<Function> writable_cb_;\n uv_poll_t handle_;\n int fd_;\n};\n\ntypedef std::map<int, SocketContext*> watchers_t;\n\nwatchers_t watchers;\n\n\nvoid SetNonBlock(int fd) {\n int flags;\n int r;\n\n flags = fcntl(fd, F_GETFL);\n assert(flags != -1);\n\n r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n assert(r != -1);\n}\n\n\nvoid SetCloExec(int fd) {\n int flags;\n int r;\n\n flags = fcntl(fd, F_GETFD);\n assert(flags != -1);\n\n r = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);\n assert(r != -1);\n}\n\nvoid OnRecv(SocketContext* sc) {\n NanScope();\n Handle<Value> argv[3];\n msghdr msg;\n iovec iov;\n ssize_t err;\n char scratch[65536];\n\n \/* Union to avoid breaking strict-aliasing rules *\/\n union {\n struct sockaddr_un sun;\n struct sockaddr_storage ss;\n } u_addr;\n\n argv[0] = argv[1] = argv[2] = NanNull();\n\n iov.iov_base = scratch;\n iov.iov_len = sizeof scratch;\n\n u_addr.sun.sun_path[0] = '\\0';\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n msg.msg_name = &u_addr.ss;\n msg.msg_namelen = sizeof u_addr.ss;\n\n do\n err = recvmsg(sc->fd_, &msg, 0);\n while (err == -1 && errno == EINTR);\n\n if (err == -1) {\n err = -errno;\n } else {\n argv[1] = NanNewBufferHandle(scratch, err);\n if (u_addr.sun.sun_path[0] != '\\0') {\n argv[2] = NanNew<String>(u_addr.sun.sun_path);\n }\n }\n\n argv[0] = NanNew<Integer>(err);\n\n TryCatch tc;\n NanNew(sc->recv_cb_)->Call(NanGetCurrentContext()->Global(),\n sizeof(argv) \/ sizeof(argv[0]),\n argv);\n\n if (tc.HasCaught())\n FatalException(tc);\n}\n\nvoid OnWritable(SocketContext* sc) {\n NanScope();\n TryCatch tc;\n uv_poll_start(&sc->handle_, UV_READABLE, OnEvent);\n NanNew(sc->writable_cb_)->Call(NanGetCurrentContext()->Global(), 0, 0);\n if (tc.HasCaught())\n FatalException(tc);\n}\n\nvoid OnEvent(uv_poll_t* handle, int status, int events) {\n assert(0 == status);\n assert(0 == (events & ~(UV_READABLE | UV_WRITABLE)));\n SocketContext* sc = container_of(handle, SocketContext, handle_);\n if (events & UV_READABLE)\n OnRecv(sc);\n\n if (events & UV_WRITABLE)\n OnWritable(sc);\n}\n\nvoid StartWatcher(int fd, Handle<Value> recv_cb, Handle<Value> writable_cb) {\n \/\/ start listening for incoming dgrams\n SocketContext* sc = new SocketContext;\n NanAssignPersistent(sc->recv_cb_, recv_cb.As<Function>());\n NanAssignPersistent(sc->writable_cb_, writable_cb.As<Function>());\n sc->fd_ = fd;\n\n uv_poll_init(uv_default_loop(), &sc->handle_, fd);\n uv_poll_start(&sc->handle_, UV_READABLE, OnEvent);\n\n \/\/ so we can disarm the watcher when close(fd) is called\n watchers.insert(watchers_t::value_type(fd, sc));\n}\n\n\nvoid FreeSocketContext(uv_handle_t* handle) {\n SocketContext* sc = container_of(handle, SocketContext, handle_);\n delete sc;\n}\n\n\nvoid StopWatcher(int fd) {\n watchers_t::iterator iter = watchers.find(fd);\n assert(iter != watchers.end());\n\n SocketContext* sc = iter->second;\n NanDisposePersistent(sc->recv_cb_);\n NanDisposePersistent(sc->writable_cb_);\n watchers.erase(iter);\n\n uv_poll_stop(&sc->handle_);\n uv_close(reinterpret_cast<uv_handle_t*>(&sc->handle_), FreeSocketContext);\n}\n\n\nNAN_METHOD(Socket) {\n NanScope();\n Local<Value> recv_cb;\n Local<Value> writable_cb;\n int protocol;\n int domain;\n int type;\n int fd;\n\n assert(args.Length() == 5);\n\n domain = args[0]->Int32Value();\n type = args[1]->Int32Value();\n protocol = args[2]->Int32Value();\n recv_cb = args[3];\n writable_cb = args[4];\n\n#if defined(SOCK_NONBLOCK)\n type |= SOCK_NONBLOCK;\n#endif\n#if defined(SOCK_CLOEXEC)\n type |= SOCK_CLOEXEC;\n#endif\n\n fd = socket(domain, type, protocol);\n if (fd == -1) {\n fd = -errno;\n goto out;\n }\n\n #if !defined(SOCK_NONBLOCK)\n SetNonBlock(fd);\n#endif\n#if !defined(SOCK_CLOEXEC)\n SetCloExec(fd);\n#endif\n\n StartWatcher(fd, recv_cb, writable_cb);\n\nout:\n NanReturnValue(NanNew(fd));\n}\n\n\nNAN_METHOD(Bind) {\n NanScope();\n sockaddr_un s;\n int err;\n int fd;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n String::Utf8Value path(args[1]);\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n err = 0;\n if (bind(fd, reinterpret_cast<sockaddr*>(&s), sizeof(s)))\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(SendTo) {\n NanScope();\n Local<Object> buf;\n sockaddr_un s;\n size_t offset;\n size_t length;\n msghdr msg;\n iovec iov;\n int err;\n int fd;\n int r;\n\n assert(args.Length() == 5);\n\n fd = args[0]->Int32Value();\n buf = args[1]->ToObject();\n offset = args[2]->Uint32Value();\n length = args[3]->Uint32Value();\n String::Utf8Value path(args[4]);\n\n assert(node::Buffer::HasInstance(buf));\n assert(offset + length <= node::Buffer::Length(buf));\n\n iov.iov_base = node::Buffer::Data(buf) + offset;\n iov.iov_len = length;\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n msg.msg_name = reinterpret_cast<void*>(&s);\n msg.msg_namelen = sizeof(s);\n\n do\n r = sendmsg(fd, &msg, 0);\n while (r == -1 && errno == EINTR);\n\n err = 0;\n if (r == -1)\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(Send) {\n NanScope();\n Local<Object> buf;\n msghdr msg;\n iovec iov;\n int err;\n int fd;\n int r;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n buf = args[1]->ToObject();\n assert(node::Buffer::HasInstance(buf));\n\n iov.iov_base = node::Buffer::Data(buf);\n iov.iov_len = node::Buffer::Length(buf);\n\n memset(&msg, 0, sizeof msg);\n msg.msg_iovlen = 1;\n msg.msg_iov = &iov;\n\n do\n r = sendmsg(fd, &msg, 0);\n while (r == -1 && errno == EINTR);\n\n err = 0;\n if (r == -1) {\n err = -errno;\n if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {\n watchers_t::iterator iter = watchers.find(fd);\n assert(iter != watchers.end());\n SocketContext* sc = iter->second;\n uv_poll_start(&sc->handle_, UV_READABLE | UV_WRITABLE, OnEvent);\n err = 1;\n }\n }\n\n NanReturnValue(NanNew(err));\n}\n\nNAN_METHOD(Connect) {\n NanScope();\n sockaddr_un s;\n int err;\n int fd;\n\n assert(args.Length() == 2);\n\n fd = args[0]->Int32Value();\n String::Utf8Value path(args[1]);\n\n memset(&s, 0, sizeof(s));\n strncpy(s.sun_path, *path, sizeof(s.sun_path) - 1);\n s.sun_family = AF_UNIX;\n\n err = 0;\n if (connect(fd, reinterpret_cast<sockaddr*>(&s), sizeof(s)))\n err = -errno;\n\n NanReturnValue(NanNew(err));\n}\n\n\nNAN_METHOD(Close) {\n NanScope();\n int err;\n int fd;\n\n assert(args.Length() == 1);\n fd = args[0]->Int32Value();\n\n \/\/ Suppress EINTR and EINPROGRESS. EINTR means that the close() system call\n \/\/ was interrupted by a signal. According to POSIX, the file descriptor is\n \/\/ in an undefined state afterwards. It's not safe to try closing it again\n \/\/ because it may have been closed, despite the signal. If we call close()\n \/\/ again, then it would either:\n \/\/\n \/\/ a) fail with EBADF, or\n \/\/\n \/\/ b) close the wrong file descriptor if another thread or a signal handler\n \/\/ has reused it in the mean time.\n \/\/\n \/\/ Neither is what we want but scenario B is particularly bad. Not retrying\n \/\/ the close() could, in theory, lead to file descriptor leaks but, in\n \/\/ practice, operating systems do the right thing and close the file\n \/\/ descriptor, regardless of whether the operation was interrupted by\n \/\/ a signal.\n \/\/\n \/\/ EINPROGRESS is benign. It means the close operation was interrupted but\n \/\/ that the file descriptor has been closed or is being closed in the\n \/\/ background. It's informative, not an error.\n err = 0;\n if (close(fd))\n if (errno != EINTR && errno != EINPROGRESS)\n err = -errno;\n\n StopWatcher(fd);\n NanReturnValue(NanNew(err));\n}\n\n\nvoid Initialize(Handle<Object> target) {\n \/\/ don't need to be read-only, only used by the JS shim\n target->Set(NanNew(\"AF_UNIX\"), NanNew(AF_UNIX));\n target->Set(NanNew(\"SOCK_DGRAM\"), NanNew(SOCK_DGRAM));\n\n target->Set(NanNew(\"socket\"),\n NanNew<FunctionTemplate>(Socket)->GetFunction());\n\n target->Set(NanNew(\"bind\"),\n NanNew<FunctionTemplate>(Bind)->GetFunction());\n\n target->Set(NanNew(\"sendto\"),\n NanNew<FunctionTemplate>(SendTo)->GetFunction());\n\n target->Set(NanNew(\"send\"),\n NanNew<FunctionTemplate>(Send)->GetFunction());\n\n target->Set(NanNew(\"connect\"),\n NanNew<FunctionTemplate>(Connect)->GetFunction());\n\n target->Set(NanNew(\"close\"),\n NanNew<FunctionTemplate>(Close)->GetFunction());\n}\n\n\n} \/\/ anonymous namespace\n\nNODE_MODULE(unix_dgram, Initialize)\n<|endoftext|>"} {"text":"<commit_before>\/\/======================================================================\n\n#include <upl\/lexer.hpp>\n#include <cstring>\n\n\/\/======================================================================\n\nnamespace UPL {\n\n\/\/======================================================================\n\nLexer::Lexer (InputStream & input, Error::Reporter & reporter)\n\t: m_input (input)\n\t, m_reporter (reporter)\n\t, m_cur_tok ()\n\t, m_has_error (false)\n{\n\tpop ();\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop ()\n{\n\tbool token_popped = false;\n\n\tif (m_cur_tok.is(TT::EOI))\n\t\treturn false;\n\n\twhile (consume_whitespace() || consume_comment());\n\n\tif (pop_name() || pop_numeric_literal() | pop_string_literal() ||\n\t\tpop_separator_or_operator())\n\t{\n\t\ttoken_popped = true;\n\t}\n\n\tif (!token_popped && !m_input.eoi()) {\n\t\tLocation location = m_input.location();\n\t\tChar c = m_input.curr();\n\t\tm_input.pop();\n\n\t\tString value;\n\t\tvalue += c;\n\n\t\tm_cur_tok = Token(TT::Error, location, value);\n\t\ttoken_popped = true;\n\t}\n\n\tif (!token_popped) {\n\t\tm_cur_tok = Token(TT::EOI, m_input.location(), L\"\");\n\t\ttoken_popped = true;\n\t}\n\n\tif (m_cur_tok.is(TT::Error))\n\t\tm_has_error = true;\n\n\treturn token_popped;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::consume_whitespace()\n{\n\tbool consumed_input = false;\n\n\twhile (!m_input.eoi()) {\n\t\tChar c = m_input.curr();\n\t\tif (!IsWhitespace(c))\n\t\t\tbreak;\n\n\t\tm_input.pop();\n\t\tconsumed_input = true;\n\t}\n\n\treturn consumed_input;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::consume_comment()\n{\n\tif (!IsCommentStarter(m_input.curr()))\n\t\treturn false;\n\n\twhile (!m_input.eoi()) {\n\t\tChar c = m_input.curr();\n\t\tif (IsNewline(c))\n\t\t\tbreak;\n\n\t\tm_input.pop();\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_name()\n{\n\tString name;\n\tLocation location;\n\n\tif (!IsIdentStarter(m_input.curr()))\n\t\treturn false;\n\n\t\/* save location and read the name *\/\n\tlocation = m_input.location();\n\twhile (!m_input.eoi() && IsIdentContinuer(m_input.curr())) {\n\t\tname += m_input.curr();\n\t\tm_input.pop();\n\t}\n\n\t\/* check for bool literals *\/\n\tif (IsFalseLiteral(name)) {\n\t\tm_cur_tok = Token(TT::BoolLiteral, location, name, false);\n\t\treturn true;\n\t}\n\telse if (IsTrueLiteral(name)) {\n\t\tm_cur_tok = Token(TT::BoolLiteral, location, name, true);\n\t\treturn true;\n\t}\n\n\t\/* check for keywords *\/\n\tTT keyword_token = StringToKeyword(name);\n\tif (TT::Error != keyword_token)\n\t{\n\t\tm_cur_tok = Token(keyword_token, location, name);\n\t\treturn true;\n\t}\n\n\t\/* otherwise it is a simple identifier *\/\n\tm_cur_tok = Token(TT::Identifier, location, name);\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_numeric_literal()\n{\n\tString number;\n\tLocation location;\n\tenum {\n\t\tINTEGER_PART,\n\t\tFRACTIONAL_PART_FIRST,\n\t\tFRACTIONAL_PART_REST,\n\t\tEXPONENT_SIGN,\n\t\tEXPONENT_VALUE_FIRST,\n\t\tEXPONENT_VALUE_REST,\n\t\tDONE_INTEGER,\n\t\tDONE_REAL,\n\t\tERROR\n\t} state = INTEGER_PART;\n\n\tif (!IsDigit(m_input.curr()))\n\t\treturn false;\n\n\tlocation = m_input.location();\n\n\twhile (state != DONE_INTEGER && state != DONE_REAL && state != ERROR) {\n\t\tchar c = m_input.curr();\n\t\tswitch (state) {\n\t\tcase INTEGER_PART:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse if (c == UPL_PRIVATE__FRACTIONAL_SEP) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = FRACTIONAL_PART_FIRST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_INTEGER;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase FRACTIONAL_PART_FIRST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = FRACTIONAL_PART_REST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = ERROR;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase FRACTIONAL_PART_REST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse if (c == UPL_PRIVATE__EXPONENT_SEP) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = EXPONENT_SIGN;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_REAL;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase EXPONENT_SIGN:\n\t\t\tif (c == UPL_PRIVATE__POSITIVE_SIGN ||\n\t\t\t\tc == UPL_PRIVATE__NEGATIVE_SIGN) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\tstate = EXPONENT_VALUE_FIRST;\n\t\t\tbreak;\n\t\tcase EXPONENT_VALUE_FIRST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = EXPONENT_VALUE_REST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = ERROR;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase EXPONENT_VALUE_REST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_REAL;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (state == DONE_INTEGER) {\n\t\tInt value = stoll(number);\n\t\tm_cur_tok = Token(TT::IntLiteral, location, number, value);\n\t}\n\telse if (state == DONE_REAL) {\n\t\tReal value = stod(number);\n\t\tm_cur_tok = Token(TT::RealLiteral, location, number, value);\n\t}\n\telse if (state == ERROR) {\n\t\tm_cur_tok = Token(TT::Error, location, number);\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_string_literal()\n{\n\tString uncooked;\n\tString value;\n\tLocation location;\n\tbool escape = false;\n\tbool error = false;\n\tbool done = false;\n\n\tif (!IsStringDelimiter(m_input.curr()))\n\t\treturn false;\n\n\tlocation = m_input.location();\n\tuncooked += m_input.curr();\n\tm_input.pop();\n\n\twhile (!done && !error) {\n\t\tchar c = m_input.curr();\n\t\tif (escape) {\n\t\t\tvalue += EscapeCharacter(c);\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tescape = false;\n\t\t}\n\t\telse if (IsNewline(c) || c == 0) {\n\t\t\terror = true;\n\t\t}\n\t\telse if (IsStringDelimiter(c)) {\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tdone = true;\n\t\t}\n\t\telse if (IsStringEscapeCharacter(c)) {\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tescape = true;\n\t\t}\n\t\telse {\n\t\t\tvalue += c;\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t}\n\t}\n\n\tif (error) {\n\t\tm_cur_tok = Token(TT::Error, location, uncooked);\n\t}\n\telse {\n\t\tm_cur_tok = Token(TT::StrLiteral, location, uncooked, value);\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_separator_or_operator()\n{\n\tTT token_type = TT::Empty;\n\tLocation location = m_input.location();\n\tString uncooked;\n\n\t\/* detect single character separators *\/\n\tswitch (m_input.curr()) {\n\tcase UPL_PRIVATE__OPEN_BRACKET:\n\t\ttoken_type = TT::OpenBracket;\n\t\tbreak;\n\tcase UPL_PRIVATE__CLOSE_BRACKET:\n\t\ttoken_type = TT::CloseBracket;\n\t\tbreak;\n\tcase UPL_PRIVATE__OPEN_PAREN:\n\t\ttoken_type = TT::OpenParen;\n\t\tbreak;\n\tcase UPL_PRIVATE__CLOSE_PAREN:\n\t\ttoken_type = TT::CloseParen;\n\t\tbreak;\n\tcase UPL_PRIVATE__ARGUMENT_SEP:\n\t\ttoken_type = TT::ArgumentSep;\n\t\tbreak;\n\tcase UPL_PRIVATE__STATEMENT_SEP:\n\t\ttoken_type = TT::StatementSep;\n\t\tbreak;\n\t}\n\n\tif (token_type != TT::Empty) {\n\t\tuncooked += m_input.curr();\n\t\tm_input.pop();\n\n\t\tm_cur_tok = Token(token_type, location, uncooked);\n\t\treturn true;\n\t}\n\n\t\/* detect multi character separators and operators *\/\n\twhile (!m_input.eoi() &&\n\t\t strchr(UPL_PRIVATE__OPERATOR_CHAR_SET, m_input.curr()) != NULL) {\n\t\tuncooked += m_input.curr();\n\t\tm_input.pop();\n\t}\n\n\tif (uncooked == UPL_PRIVATE__ASSIGNMENT)\n\t\ttoken_type = TT::Assignment;\n\telse if (uncooked == UPL_PRIVATE__RETURNS_SEP)\n\t\ttoken_type = TT::ReturnsSep;\n\telse if (uncooked.length() != 0)\n\t\ttoken_type = TT::Operator;\n\n\tif (token_type != TT::Empty) {\n\t\tm_cur_tok = Token(token_type, location, uncooked);\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\n\/\/----------------------------------------------------------------------\n\/\/======================================================================\n\n}\t\/\/ namespace UPL\n\n\/\/======================================================================\n<commit_msg>Check for m_input.error() in Lexer.<commit_after>\/\/======================================================================\n\n#include <upl\/lexer.hpp>\n#include <cstring>\n\n\/\/======================================================================\n\nnamespace UPL {\n\n\/\/======================================================================\n\nLexer::Lexer (InputStream & input, Error::Reporter & reporter)\n\t: m_input (input)\n\t, m_reporter (reporter)\n\t, m_cur_tok ()\n\t, m_has_error (false)\n{\n\tpop ();\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop ()\n{\n\tbool token_popped = false;\n\n\tif (m_cur_tok.is(TT::EOI))\n\t\treturn false;\n\n\twhile (consume_whitespace() || consume_comment());\n\n\tif (pop_name() || pop_numeric_literal() | pop_string_literal() ||\n\t\tpop_separator_or_operator())\n\t{\n\t\ttoken_popped = true;\n\t}\n\n\tif (!token_popped && (!m_input.eoi() || m_input.error())) {\n\t\tLocation location = m_input.location();\n\t\tChar c = m_input.curr();\n\t\tm_input.pop();\n\n\t\tString value;\n\t\tvalue += c;\n\n\t\tm_cur_tok = Token(TT::Error, location, value);\n\t\ttoken_popped = true;\n\t}\n\n\tif (!token_popped) {\n\t\tm_cur_tok = Token(TT::EOI, m_input.location(), L\"\");\n\t\ttoken_popped = true;\n\t}\n\n\tif (m_cur_tok.is(TT::Error))\n\t\tm_has_error = true;\n\n\treturn token_popped;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::consume_whitespace()\n{\n\tbool consumed_input = false;\n\n\twhile (!m_input.eoi() && !m_input.error()) {\n\t\tChar c = m_input.curr();\n\t\tif (!IsWhitespace(c))\n\t\t\tbreak;\n\n\t\tm_input.pop();\n\t\tconsumed_input = true;\n\t}\n\n\treturn consumed_input;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::consume_comment()\n{\n\tif (!IsCommentStarter(m_input.curr()))\n\t\treturn false;\n\n\twhile (!m_input.eoi() && !m_input.error()) {\n\t\tChar c = m_input.curr();\n\t\tif (IsNewline(c))\n\t\t\tbreak;\n\n\t\tm_input.pop();\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_name()\n{\n\tString name;\n\tLocation location;\n\n\tif (!IsIdentStarter(m_input.curr()))\n\t\treturn false;\n\n\t\/* save location and read the name *\/\n\tlocation = m_input.location();\n\twhile (!m_input.eoi() && !m_input.error() &&\n\t\t IsIdentContinuer(m_input.curr())) {\n\t\tname += m_input.curr();\n\t\tm_input.pop();\n\t}\n\n\t\/* check for bool literals *\/\n\tif (IsFalseLiteral(name)) {\n\t\tm_cur_tok = Token(TT::BoolLiteral, location, name, false);\n\t\treturn true;\n\t}\n\telse if (IsTrueLiteral(name)) {\n\t\tm_cur_tok = Token(TT::BoolLiteral, location, name, true);\n\t\treturn true;\n\t}\n\n\t\/* check for keywords *\/\n\tTT keyword_token = StringToKeyword(name);\n\tif (TT::Error != keyword_token)\n\t{\n\t\tm_cur_tok = Token(keyword_token, location, name);\n\t\treturn true;\n\t}\n\n\t\/* otherwise it is a simple identifier *\/\n\tm_cur_tok = Token(TT::Identifier, location, name);\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_numeric_literal()\n{\n\tString number;\n\tLocation location;\n\tenum {\n\t\tINTEGER_PART,\n\t\tFRACTIONAL_PART_FIRST,\n\t\tFRACTIONAL_PART_REST,\n\t\tEXPONENT_SIGN,\n\t\tEXPONENT_VALUE_FIRST,\n\t\tEXPONENT_VALUE_REST,\n\t\tDONE_INTEGER,\n\t\tDONE_REAL,\n\t\tERROR\n\t} state = INTEGER_PART;\n\n\tif (!IsDigit(m_input.curr()))\n\t\treturn false;\n\n\tlocation = m_input.location();\n\n\twhile (state != DONE_INTEGER && state != DONE_REAL && state != ERROR) {\n\t\tChar c = m_input.curr();\n\n\t\tswitch (state) {\n\t\tcase INTEGER_PART:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse if (c == UPL_PRIVATE__FRACTIONAL_SEP) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = FRACTIONAL_PART_FIRST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_INTEGER;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FRACTIONAL_PART_FIRST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = FRACTIONAL_PART_REST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = ERROR;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FRACTIONAL_PART_REST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse if (c == UPL_PRIVATE__EXPONENT_SEP) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = EXPONENT_SIGN;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_REAL;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase EXPONENT_SIGN:\n\t\t\tif (c == UPL_PRIVATE__POSITIVE_SIGN ||\n\t\t\t\tc == UPL_PRIVATE__NEGATIVE_SIGN) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\tstate = EXPONENT_VALUE_FIRST;\n\t\t\tbreak;\n\n\t\tcase EXPONENT_VALUE_FIRST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t\tstate = EXPONENT_VALUE_REST;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = ERROR;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase EXPONENT_VALUE_REST:\n\t\t\tif (IsDigit(c)) {\n\t\t\t\tnumber += c;\n\t\t\t\tm_input.pop();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = DONE_REAL;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (state == DONE_INTEGER) {\n\t\tInt value = stoll(number);\n\t\tm_cur_tok = Token(TT::IntLiteral, location, number, value);\n\t}\n\telse if (state == DONE_REAL) {\n\t\tReal value = stod(number);\n\t\tm_cur_tok = Token(TT::RealLiteral, location, number, value);\n\t}\n\telse if (state == ERROR) {\n\t\tm_cur_tok = Token(TT::Error, location, number);\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_string_literal()\n{\n\tString uncooked;\n\tString value;\n\tLocation location;\n\tbool escape = false;\n\tbool error = false;\n\tbool done = false;\n\n\tif (!IsStringDelimiter(m_input.curr()))\n\t\treturn false;\n\n\tlocation = m_input.location();\n\tuncooked += m_input.curr();\n\tm_input.pop();\n\n\twhile (!done && !error) {\n\t\tif (m_input.eoi() || m_input.error() || IsNewline(m_input.curr())) {\n\t\t\terror = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tChar c = m_input.curr();\n\t\tif (escape) {\n\t\t\tvalue += EscapeCharacter(c);\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tescape = false;\n\t\t}\n\t\telse if (IsStringDelimiter(c)) {\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tdone = true;\n\t\t}\n\t\telse if (IsStringEscapeCharacter(c)) {\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t\tescape = true;\n\t\t}\n\t\telse {\n\t\t\tvalue += c;\n\t\t\tuncooked += c;\n\t\t\tm_input.pop();\n\t\t}\n\t}\n\n\tif (error) {\n\t\tm_cur_tok = Token(TT::Error, location, uncooked);\n\t}\n\telse {\n\t\tm_cur_tok = Token(TT::StrLiteral, location, uncooked, value);\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------\n\nbool Lexer::pop_separator_or_operator()\n{\n\tTT token_type = TT::Empty;\n\tLocation location = m_input.location();\n\tString uncooked;\n\n\t\/* detect single character separators *\/\n\tswitch (m_input.curr()) {\n\tcase UPL_PRIVATE__OPEN_BRACKET:\n\t\ttoken_type = TT::OpenBracket;\n\t\tbreak;\n\n\tcase UPL_PRIVATE__CLOSE_BRACKET:\n\t\ttoken_type = TT::CloseBracket;\n\t\tbreak;\n\n\tcase UPL_PRIVATE__OPEN_PAREN:\n\t\ttoken_type = TT::OpenParen;\n\t\tbreak;\n\n\tcase UPL_PRIVATE__CLOSE_PAREN:\n\t\ttoken_type = TT::CloseParen;\n\t\tbreak;\n\n\tcase UPL_PRIVATE__ARGUMENT_SEP:\n\t\ttoken_type = TT::ArgumentSep;\n\t\tbreak;\n\n\tcase UPL_PRIVATE__STATEMENT_SEP:\n\t\ttoken_type = TT::StatementSep;\n\t\tbreak;\n\t}\n\n\tif (token_type != TT::Empty) {\n\t\tuncooked += m_input.curr();\n\t\tm_input.pop();\n\n\t\tm_cur_tok = Token(token_type, location, uncooked);\n\t\treturn true;\n\t}\n\n\t\/* detect multi character separators and operators *\/\n\twhile (!m_input.eoi() && !m_input.error() &&\n\t\t strchr(UPL_PRIVATE__OPERATOR_CHAR_SET, m_input.curr()) != NULL) {\n\t\tuncooked += m_input.curr();\n\t\tm_input.pop();\n\t}\n\n\tif (uncooked == UPL_PRIVATE__ASSIGNMENT)\n\t\ttoken_type = TT::Assignment;\n\telse if (uncooked == UPL_PRIVATE__RETURNS_SEP)\n\t\ttoken_type = TT::ReturnsSep;\n\telse if (uncooked.length() != 0)\n\t\ttoken_type = TT::Operator;\n\n\tif (token_type != TT::Empty) {\n\t\tm_cur_tok = Token(token_type, location, uncooked);\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\n\/\/----------------------------------------------------------------------\n\/\/======================================================================\n\n}\t\/\/ namespace UPL\n\n\/\/======================================================================\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"bloom.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"hash.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"random.h\"\n#include \"streams.h\"\n\n#include <math.h>\n#include <stdlib.h>\n\n#include <boost\/foreach.hpp>\n\n#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455\n#define LN2 0.6931471805599453094172321214581765680755001343602552\n\nCBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :\n \/**\n * The ideal size for a bloom filter with a given number of elements and false positive rate is:\n * - nElements * log(fp rate) \/ ln(2)^2\n * We ignore filter parameters which will create a bloom filter larger than the protocol limits\n *\/\n vData(std::min((unsigned int)(-1 \/ LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) \/ 8),\n \/**\n * The ideal number of hash functions is filter size * ln(2) \/ number of elements\n * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits\n * See https:\/\/en.wikipedia.org\/wiki\/Bloom_filter for an explanation of these formulas\n *\/\n isFull(false),\n isEmpty(true),\n nHashFuncs(std::min((unsigned int)(vData.size() * 8 \/ nElements * LN2), MAX_HASH_FUNCS)),\n nTweak(nTweakIn),\n nFlags(nFlagsIn)\n{\n}\n\n\/\/ Private constructor used by CRollingBloomFilter\nCBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn) :\n vData((unsigned int)(-1 \/ LN2SQUARED * nElements * log(nFPRate)) \/ 8),\n isFull(false),\n isEmpty(true),\n nHashFuncs((unsigned int)(vData.size() * 8 \/ nElements * LN2)),\n nTweak(nTweakIn),\n nFlags(BLOOM_UPDATE_NONE)\n{\n}\n\ninline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const\n{\n \/\/ 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.\n return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);\n}\n\nvoid CBloomFilter::insert(const std::vector<unsigned char>& vKey)\n{\n if (isFull)\n return;\n for (unsigned int i = 0; i < nHashFuncs; i++)\n {\n unsigned int nIndex = Hash(i, vKey);\n \/\/ Sets bit nIndex of vData\n vData[nIndex >> 3] |= (1 << (7 & nIndex));\n }\n isEmpty = false;\n}\n\nvoid CBloomFilter::insert(const COutPoint& outpoint)\n{\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << outpoint;\n std::vector<unsigned char> data(stream.begin(), stream.end());\n insert(data);\n}\n\nvoid CBloomFilter::insert(const uint256& hash)\n{\n std::vector<unsigned char> data(hash.begin(), hash.end());\n insert(data);\n}\n\nbool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const\n{\n if (isFull)\n return true;\n if (isEmpty)\n return false;\n for (unsigned int i = 0; i < nHashFuncs; i++)\n {\n unsigned int nIndex = Hash(i, vKey);\n \/\/ Checks bit nIndex of vData\n if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))\n return false;\n }\n return true;\n}\n\nbool CBloomFilter::contains(const COutPoint& outpoint) const\n{\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << outpoint;\n std::vector<unsigned char> data(stream.begin(), stream.end());\n return contains(data);\n}\n\nbool CBloomFilter::contains(const uint256& hash) const\n{\n std::vector<unsigned char> data(hash.begin(), hash.end());\n return contains(data);\n}\n\nvoid CBloomFilter::clear()\n{\n vData.assign(vData.size(),0);\n isFull = false;\n isEmpty = true;\n}\n\nvoid CBloomFilter::reset(unsigned int nNewTweak)\n{\n clear();\n nTweak = nNewTweak;\n}\n\nbool CBloomFilter::IsWithinSizeConstraints() const\n{\n return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;\n}\n\nbool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)\n{\n bool fFound = false;\n \/\/ Match if the filter contains the hash of tx\n \/\/ for finding tx when they appear in a block\n if (isFull)\n return true;\n if (isEmpty)\n return false;\n const uint256& hash = tx.GetHash();\n if (contains(hash))\n fFound = true;\n\n for (unsigned int i = 0; i < tx.vout.size(); i++)\n {\n const CTxOut& txout = tx.vout[i];\n \/\/ Match if the filter contains any arbitrary script data element in any scriptPubKey in tx\n \/\/ If this matches, also add the specific output that was matched.\n \/\/ This means clients don't have to update the filter themselves when a new relevant tx \n \/\/ is discovered in order to find spending transactions, which avoids round-tripping and race conditions.\n CScript::const_iterator pc = txout.scriptPubKey.begin();\n std::vector<unsigned char> data;\n while (pc < txout.scriptPubKey.end())\n {\n opcodetype opcode;\n if (!txout.scriptPubKey.GetOp(pc, opcode, data))\n break;\n if (data.size() != 0 && contains(data))\n {\n fFound = true;\n if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)\n insert(COutPoint(hash, i));\n else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)\n {\n txnouttype type;\n std::vector<std::vector<unsigned char> > vSolutions;\n if (Solver(txout.scriptPubKey, type, vSolutions) &&\n (type == TX_PUBKEY || type == TX_MULTISIG))\n insert(COutPoint(hash, i));\n }\n break;\n }\n }\n }\n\n if (fFound)\n return true;\n\n BOOST_FOREACH(const CTxIn& txin, tx.vin)\n {\n \/\/ Match if the filter contains an outpoint tx spends\n if (contains(txin.prevout))\n return true;\n\n \/\/ Match if the filter contains any arbitrary script data element in any scriptSig in tx\n CScript::const_iterator pc = txin.scriptSig.begin();\n std::vector<unsigned char> data;\n while (pc < txin.scriptSig.end())\n {\n opcodetype opcode;\n if (!txin.scriptSig.GetOp(pc, opcode, data))\n break;\n if (data.size() != 0 && contains(data))\n return true;\n }\n }\n\n return false;\n}\n\nvoid CBloomFilter::UpdateEmptyFull()\n{\n bool full = true;\n bool empty = true;\n for (unsigned int i = 0; i < vData.size(); i++)\n {\n full &= vData[i] == 0xff;\n empty &= vData[i] == 0;\n }\n isFull = full;\n isEmpty = empty;\n}\n\nCRollingBloomFilter::CRollingBloomFilter(unsigned int nElements, double fpRate)\n{\n double logFpRate = log(fpRate);\n \/* The optimal number of hash functions is log(fpRate) \/ log(0.5), but\n * restrict it to the range 1-50. *\/\n nHashFuncs = std::max(1, std::min((int)round(logFpRate \/ log(0.5)), 50));\n \/* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements \/ 2 entries. *\/\n nEntriesPerGeneration = (nElements + 1) \/ 2;\n uint32_t nMaxElements = nEntriesPerGeneration * 3;\n \/* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements \/ nFilterBits), nHashFuncs)\n * => pow(fpRate, 1.0 \/ nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements \/ nFilterBits)\n * => 1.0 - pow(fpRate, 1.0 \/ nHashFuncs) = exp(-nHashFuncs * nMaxElements \/ nFilterBits)\n * => log(1.0 - pow(fpRate, 1.0 \/ nHashFuncs)) = -nHashFuncs * nMaxElements \/ nFilterBits\n * => nFilterBits = -nHashFuncs * nMaxElements \/ log(1.0 - pow(fpRate, 1.0 \/ nHashFuncs))\n * => nFilterBits = -nHashFuncs * nMaxElements \/ log(1.0 - exp(logFpRate \/ nHashFuncs))\n *\/\n uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements \/ log(1.0 - exp(logFpRate \/ nHashFuncs)));\n data.clear();\n \/* For each data element we need to store 2 bits. If both bits are 0, the\n * bit is treated as unset. If the bits are (01), (10), or (11), the bit is\n * treated as set in generation 1, 2, or 3 respectively.\n * These bits are stored in separate integers: position P corresponds to bit\n * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. *\/\n data.resize(((nFilterBits + 63) \/ 64) << 1);\n reset();\n}\n\n\/* Similar to CBloomFilter::Hash *\/\nstatic inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {\n return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);\n}\n\nvoid CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)\n{\n if (nEntriesThisGeneration == nEntriesPerGeneration) {\n nEntriesThisGeneration = 0;\n nGeneration++;\n if (nGeneration == 4) {\n nGeneration = 1;\n }\n uint64_t nGenerationMask1 = -(uint64_t)(nGeneration & 1);\n uint64_t nGenerationMask2 = -(uint64_t)(nGeneration >> 1);\n \/* Wipe old entries that used this generation number. *\/\n for (uint32_t p = 0; p < data.size(); p += 2) {\n uint64_t p1 = data[p], p2 = data[p + 1];\n uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);\n data[p] = p1 & mask;\n data[p + 1] = p2 & mask;\n }\n }\n nEntriesThisGeneration++;\n\n for (int n = 0; n < nHashFuncs; n++) {\n uint32_t h = RollingBloomHash(n, nTweak, vKey);\n int bit = h & 0x3F;\n uint32_t pos = (h >> 6) % data.size();\n \/* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. *\/\n data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;\n data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;\n }\n}\n\nvoid CRollingBloomFilter::insert(const uint256& hash)\n{\n std::vector<unsigned char> vData(hash.begin(), hash.end());\n insert(vData);\n}\n\nbool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const\n{\n for (int n = 0; n < nHashFuncs; n++) {\n uint32_t h = RollingBloomHash(n, nTweak, vKey);\n int bit = h & 0x3F;\n uint32_t pos = (h >> 6) % data.size();\n \/* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey *\/\n if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {\n return false;\n }\n }\n return true;\n}\n\nbool CRollingBloomFilter::contains(const uint256& hash) const\n{\n std::vector<unsigned char> vData(hash.begin(), hash.end());\n return contains(vData);\n}\n\nvoid CRollingBloomFilter::reset()\n{\n nTweak = GetRand(std::numeric_limits<unsigned int>::max());\n nEntriesThisGeneration = 0;\n nGeneration = 1;\n for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {\n *it = 0;\n }\n}\n<commit_msg>Fix msvc compiler error C4146 (minus operator applied to unsigned type)<commit_after>\/\/ Copyright (c) 2012-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"bloom.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"hash.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"random.h\"\n#include \"streams.h\"\n\n#include <math.h>\n#include <stdlib.h>\n\n#include <boost\/foreach.hpp>\n\n#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455\n#define LN2 0.6931471805599453094172321214581765680755001343602552\n\nCBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :\n \/**\n * The ideal size for a bloom filter with a given number of elements and false positive rate is:\n * - nElements * log(fp rate) \/ ln(2)^2\n * We ignore filter parameters which will create a bloom filter larger than the protocol limits\n *\/\n vData(std::min((unsigned int)(-1 \/ LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) \/ 8),\n \/**\n * The ideal number of hash functions is filter size * ln(2) \/ number of elements\n * Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits\n * See https:\/\/en.wikipedia.org\/wiki\/Bloom_filter for an explanation of these formulas\n *\/\n isFull(false),\n isEmpty(true),\n nHashFuncs(std::min((unsigned int)(vData.size() * 8 \/ nElements * LN2), MAX_HASH_FUNCS)),\n nTweak(nTweakIn),\n nFlags(nFlagsIn)\n{\n}\n\n\/\/ Private constructor used by CRollingBloomFilter\nCBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn) :\n vData((unsigned int)(-1 \/ LN2SQUARED * nElements * log(nFPRate)) \/ 8),\n isFull(false),\n isEmpty(true),\n nHashFuncs((unsigned int)(vData.size() * 8 \/ nElements * LN2)),\n nTweak(nTweakIn),\n nFlags(BLOOM_UPDATE_NONE)\n{\n}\n\ninline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const\n{\n \/\/ 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.\n return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);\n}\n\nvoid CBloomFilter::insert(const std::vector<unsigned char>& vKey)\n{\n if (isFull)\n return;\n for (unsigned int i = 0; i < nHashFuncs; i++)\n {\n unsigned int nIndex = Hash(i, vKey);\n \/\/ Sets bit nIndex of vData\n vData[nIndex >> 3] |= (1 << (7 & nIndex));\n }\n isEmpty = false;\n}\n\nvoid CBloomFilter::insert(const COutPoint& outpoint)\n{\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << outpoint;\n std::vector<unsigned char> data(stream.begin(), stream.end());\n insert(data);\n}\n\nvoid CBloomFilter::insert(const uint256& hash)\n{\n std::vector<unsigned char> data(hash.begin(), hash.end());\n insert(data);\n}\n\nbool CBloomFilter::contains(const std::vector<unsigned char>& vKey) const\n{\n if (isFull)\n return true;\n if (isEmpty)\n return false;\n for (unsigned int i = 0; i < nHashFuncs; i++)\n {\n unsigned int nIndex = Hash(i, vKey);\n \/\/ Checks bit nIndex of vData\n if (!(vData[nIndex >> 3] & (1 << (7 & nIndex))))\n return false;\n }\n return true;\n}\n\nbool CBloomFilter::contains(const COutPoint& outpoint) const\n{\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << outpoint;\n std::vector<unsigned char> data(stream.begin(), stream.end());\n return contains(data);\n}\n\nbool CBloomFilter::contains(const uint256& hash) const\n{\n std::vector<unsigned char> data(hash.begin(), hash.end());\n return contains(data);\n}\n\nvoid CBloomFilter::clear()\n{\n vData.assign(vData.size(),0);\n isFull = false;\n isEmpty = true;\n}\n\nvoid CBloomFilter::reset(unsigned int nNewTweak)\n{\n clear();\n nTweak = nNewTweak;\n}\n\nbool CBloomFilter::IsWithinSizeConstraints() const\n{\n return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;\n}\n\nbool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx)\n{\n bool fFound = false;\n \/\/ Match if the filter contains the hash of tx\n \/\/ for finding tx when they appear in a block\n if (isFull)\n return true;\n if (isEmpty)\n return false;\n const uint256& hash = tx.GetHash();\n if (contains(hash))\n fFound = true;\n\n for (unsigned int i = 0; i < tx.vout.size(); i++)\n {\n const CTxOut& txout = tx.vout[i];\n \/\/ Match if the filter contains any arbitrary script data element in any scriptPubKey in tx\n \/\/ If this matches, also add the specific output that was matched.\n \/\/ This means clients don't have to update the filter themselves when a new relevant tx \n \/\/ is discovered in order to find spending transactions, which avoids round-tripping and race conditions.\n CScript::const_iterator pc = txout.scriptPubKey.begin();\n std::vector<unsigned char> data;\n while (pc < txout.scriptPubKey.end())\n {\n opcodetype opcode;\n if (!txout.scriptPubKey.GetOp(pc, opcode, data))\n break;\n if (data.size() != 0 && contains(data))\n {\n fFound = true;\n if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)\n insert(COutPoint(hash, i));\n else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)\n {\n txnouttype type;\n std::vector<std::vector<unsigned char> > vSolutions;\n if (Solver(txout.scriptPubKey, type, vSolutions) &&\n (type == TX_PUBKEY || type == TX_MULTISIG))\n insert(COutPoint(hash, i));\n }\n break;\n }\n }\n }\n\n if (fFound)\n return true;\n\n BOOST_FOREACH(const CTxIn& txin, tx.vin)\n {\n \/\/ Match if the filter contains an outpoint tx spends\n if (contains(txin.prevout))\n return true;\n\n \/\/ Match if the filter contains any arbitrary script data element in any scriptSig in tx\n CScript::const_iterator pc = txin.scriptSig.begin();\n std::vector<unsigned char> data;\n while (pc < txin.scriptSig.end())\n {\n opcodetype opcode;\n if (!txin.scriptSig.GetOp(pc, opcode, data))\n break;\n if (data.size() != 0 && contains(data))\n return true;\n }\n }\n\n return false;\n}\n\nvoid CBloomFilter::UpdateEmptyFull()\n{\n bool full = true;\n bool empty = true;\n for (unsigned int i = 0; i < vData.size(); i++)\n {\n full &= vData[i] == 0xff;\n empty &= vData[i] == 0;\n }\n isFull = full;\n isEmpty = empty;\n}\n\nCRollingBloomFilter::CRollingBloomFilter(unsigned int nElements, double fpRate)\n{\n double logFpRate = log(fpRate);\n \/* The optimal number of hash functions is log(fpRate) \/ log(0.5), but\n * restrict it to the range 1-50. *\/\n nHashFuncs = std::max(1, std::min((int)round(logFpRate \/ log(0.5)), 50));\n \/* In this rolling bloom filter, we'll store between 2 and 3 generations of nElements \/ 2 entries. *\/\n nEntriesPerGeneration = (nElements + 1) \/ 2;\n uint32_t nMaxElements = nEntriesPerGeneration * 3;\n \/* The maximum fpRate = pow(1.0 - exp(-nHashFuncs * nMaxElements \/ nFilterBits), nHashFuncs)\n * => pow(fpRate, 1.0 \/ nHashFuncs) = 1.0 - exp(-nHashFuncs * nMaxElements \/ nFilterBits)\n * => 1.0 - pow(fpRate, 1.0 \/ nHashFuncs) = exp(-nHashFuncs * nMaxElements \/ nFilterBits)\n * => log(1.0 - pow(fpRate, 1.0 \/ nHashFuncs)) = -nHashFuncs * nMaxElements \/ nFilterBits\n * => nFilterBits = -nHashFuncs * nMaxElements \/ log(1.0 - pow(fpRate, 1.0 \/ nHashFuncs))\n * => nFilterBits = -nHashFuncs * nMaxElements \/ log(1.0 - exp(logFpRate \/ nHashFuncs))\n *\/\n uint32_t nFilterBits = (uint32_t)ceil(-1.0 * nHashFuncs * nMaxElements \/ log(1.0 - exp(logFpRate \/ nHashFuncs)));\n data.clear();\n \/* For each data element we need to store 2 bits. If both bits are 0, the\n * bit is treated as unset. If the bits are (01), (10), or (11), the bit is\n * treated as set in generation 1, 2, or 3 respectively.\n * These bits are stored in separate integers: position P corresponds to bit\n * (P & 63) of the integers data[(P >> 6) * 2] and data[(P >> 6) * 2 + 1]. *\/\n data.resize(((nFilterBits + 63) \/ 64) << 1);\n reset();\n}\n\n\/* Similar to CBloomFilter::Hash *\/\nstatic inline uint32_t RollingBloomHash(unsigned int nHashNum, uint32_t nTweak, const std::vector<unsigned char>& vDataToHash) {\n return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash);\n}\n\nvoid CRollingBloomFilter::insert(const std::vector<unsigned char>& vKey)\n{\n if (nEntriesThisGeneration == nEntriesPerGeneration) {\n nEntriesThisGeneration = 0;\n nGeneration++;\n if (nGeneration == 4) {\n nGeneration = 1;\n }\n uint64_t nGenerationMask1 = 0 - (uint64_t)(nGeneration & 1);\n uint64_t nGenerationMask2 = 0 - (uint64_t)(nGeneration >> 1);\n \/* Wipe old entries that used this generation number. *\/\n for (uint32_t p = 0; p < data.size(); p += 2) {\n uint64_t p1 = data[p], p2 = data[p + 1];\n uint64_t mask = (p1 ^ nGenerationMask1) | (p2 ^ nGenerationMask2);\n data[p] = p1 & mask;\n data[p + 1] = p2 & mask;\n }\n }\n nEntriesThisGeneration++;\n\n for (int n = 0; n < nHashFuncs; n++) {\n uint32_t h = RollingBloomHash(n, nTweak, vKey);\n int bit = h & 0x3F;\n uint32_t pos = (h >> 6) % data.size();\n \/* The lowest bit of pos is ignored, and set to zero for the first bit, and to one for the second. *\/\n data[pos & ~1] = (data[pos & ~1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration & 1)) << bit;\n data[pos | 1] = (data[pos | 1] & ~(((uint64_t)1) << bit)) | ((uint64_t)(nGeneration >> 1)) << bit;\n }\n}\n\nvoid CRollingBloomFilter::insert(const uint256& hash)\n{\n std::vector<unsigned char> vData(hash.begin(), hash.end());\n insert(vData);\n}\n\nbool CRollingBloomFilter::contains(const std::vector<unsigned char>& vKey) const\n{\n for (int n = 0; n < nHashFuncs; n++) {\n uint32_t h = RollingBloomHash(n, nTweak, vKey);\n int bit = h & 0x3F;\n uint32_t pos = (h >> 6) % data.size();\n \/* If the relevant bit is not set in either data[pos & ~1] or data[pos | 1], the filter does not contain vKey *\/\n if (!(((data[pos & ~1] | data[pos | 1]) >> bit) & 1)) {\n return false;\n }\n }\n return true;\n}\n\nbool CRollingBloomFilter::contains(const uint256& hash) const\n{\n std::vector<unsigned char> vData(hash.begin(), hash.end());\n return contains(vData);\n}\n\nvoid CRollingBloomFilter::reset()\n{\n nTweak = GetRand(std::numeric_limits<unsigned int>::max());\n nEntriesThisGeneration = 0;\n nGeneration = 1;\n for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {\n *it = 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>\n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"libs\/sha1\/sha1.h\"\n#include \"backends\/ilang\/ilang_backend.h\"\n\n#if !defined(_WIN32) || defined(__MINGW32__)\n# include <sys\/time.h>\n#endif\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include <vector>\n#include <list>\n\nYOSYS_NAMESPACE_BEGIN\n\nstd::vector<FILE*> log_files;\nstd::vector<std::ostream*> log_streams;\nFILE *log_errfile = NULL;\nSHA1 *log_hasher = NULL;\n\nbool log_time = false;\nbool log_cmd_error_throw = false;\nint log_verbose_level;\n\nstd::vector<int> header_count;\nstd::list<std::string> string_buf;\nint string_buf_size = 0;\n\nstatic struct timeval initial_tv = { 0, 0 };\nstatic bool next_print_log = false;\nstatic int log_newline_count = 0;\n\n#if defined(_WIN32) && !defined(__MINGW32__)\n\/\/ this will get time information and return it in timeval, simulating gettimeofday()\nint gettimeofday(struct timeval *tv, struct timezone *tz)\n{\n\tLARGE_INTEGER counter;\n\tLARGE_INTEGER freq;\n\n\tQueryPerformanceFrequency(&freq);\n\tQueryPerformanceCounter(&counter);\n\n\tcounter.QuadPart *= 1000000;\n\tcounter.QuadPart \/= freq.QuadPart;\n\n\ttv->tv_sec = long(counter.QuadPart \/ 1000000);\n\ttv->tv_usec = counter.QuadPart % 1000000;\n\n\treturn 0;\n}\n#endif\n\nvoid logv(const char *format, va_list ap)\n{\n\twhile (format[0] == '\\n' && format[1] != 0) {\n\t\tlog(\"\\n\");\n\t\tformat++;\n\t}\n\n\tstd::string str = vstringf(format, ap);\n\n\tif (str.empty())\n\t\treturn;\n\n\tsize_t nnl_pos = str.find_last_not_of('\\n');\n\tif (nnl_pos == std::string::npos)\n\t\tlog_newline_count += GetSize(str);\n\telse\n\t\tlog_newline_count = GetSize(str) - nnl_pos - 1;\n\n\tif (log_hasher)\n\t\tlog_hasher->update(str);\n\n\tif (log_time)\n\t{\n\t\tstd::string time_str;\n\n\t\tif (next_print_log || initial_tv.tv_sec == 0) {\n\t\t\tnext_print_log = false;\n\t\t\tstruct timeval tv;\n\t\t\tgettimeofday(&tv, NULL);\n\t\t\tif (initial_tv.tv_sec == 0)\n\t\t\t\tinitial_tv = tv;\n\t\t\tif (tv.tv_usec < initial_tv.tv_usec) {\n\t\t\t\ttv.tv_sec--;\n\t\t\t\ttv.tv_usec += 1000000;\n\t\t\t}\n\t\t\ttv.tv_sec -= initial_tv.tv_sec;\n\t\t\ttv.tv_usec -= initial_tv.tv_usec;\n\t\t\ttime_str += stringf(\"[%05d.%06d] \", int(tv.tv_sec), int(tv.tv_usec));\n\t\t}\n\n\t\tif (format[0] && format[strlen(format)-1] == '\\n')\n\t\t\tnext_print_log = true;\n\n\t\tfor (auto f : log_files)\n\t\t\tfputs(time_str.c_str(), f);\n\n\t\tfor (auto f : log_streams)\n\t\t\t*f << time_str;\n\t}\n\n\tfor (auto f : log_files)\n\t\tfputs(str.c_str(), f);\n\n\tfor (auto f : log_streams)\n\t\t*f << str;\n}\n\nvoid logv_header(const char *format, va_list ap)\n{\n\tbool pop_errfile = false;\n\n\tlog_spacer();\n\tif (header_count.size() > 0)\n\t\theader_count.back()++;\n\n\tif (int(header_count.size()) <= log_verbose_level && log_errfile != NULL) {\n\t\tlog_files.push_back(log_errfile);\n\t\tpop_errfile = true;\n\t}\n\n\tfor (int c : header_count)\n\t\tlog(\"%d.\", c);\n\tlog(\" \");\n\tlogv(format, ap);\n\tlog_flush();\n\n\tif (pop_errfile)\n\t\tlog_files.pop_back();\n}\n\nvoid logv_error(const char *format, va_list ap)\n{\n\tif (log_errfile != NULL)\n\t\tlog_files.push_back(log_errfile);\n\n\tlog(\"ERROR: \");\n\tlogv(format, ap);\n\tlog_flush();\n\texit(1);\n}\n\nvoid log(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv(format, ap);\n\tva_end(ap);\n}\n\nvoid log_header(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv_header(format, ap);\n\tva_end(ap);\n}\n\nvoid log_error(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv_error(format, ap);\n}\n\nvoid log_cmd_error(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\n\tif (log_cmd_error_throw) {\n\t\tlog(\"ERROR: \");\n\t\tlogv(format, ap);\n\t\tlog_flush();\n\t\tthrow log_cmd_error_exception();\n\t}\n\n\tlogv_error(format, ap);\n}\n\nvoid log_spacer()\n{\n\twhile (log_newline_count < 2)\n\t\tlog(\"\\n\");\n}\n\nvoid log_push()\n{\n\theader_count.push_back(0);\n}\n\nvoid log_pop()\n{\n\theader_count.pop_back();\n\tstring_buf.clear();\n\tstring_buf_size = 0;\n\tlog_flush();\n}\n\nvoid log_reset_stack()\n{\n\twhile (header_count.size() > 1)\n\t\theader_count.pop_back();\n\tstring_buf.clear();\n\tstring_buf_size = 0;\n\tlog_flush();\n}\n\nvoid log_flush()\n{\n\tfor (auto f : log_files)\n\t\tfflush(f);\n\n\tfor (auto f : log_streams)\n\t\tf->flush();\n}\n\nvoid log_dump_val_worker(RTLIL::SigSpec v) {\n\tlog(\"%s\", log_signal(v));\n}\n\nconst char *log_signal(const RTLIL::SigSpec &sig, bool autoint)\n{\n\tstd::stringstream buf;\n\tILANG_BACKEND::dump_sigspec(buf, sig, autoint);\n\n\tif (string_buf_size < 100)\n\t\tstring_buf_size++;\n\telse\n\t\tstring_buf.pop_front();\n\tstring_buf.push_back(buf.str());\n\n\treturn string_buf.back().c_str();\n}\n\nconst char *log_id(RTLIL::IdString str)\n{\n\tconst char *p = str.c_str();\n\tlog_assert(RTLIL::IdString::global_refcount_storage_[str.index_] > 1);\n\tif (p[0] == '\\\\' && p[1] != '$' && p[1] != 0)\n\t\treturn p+1;\n\treturn p;\n}\n\nvoid log_cell(RTLIL::Cell *cell, std::string indent)\n{\n\tstd::stringstream buf;\n\tILANG_BACKEND::dump_cell(buf, indent, cell);\n\tlog(\"%s\", buf.str().c_str());\n}\n\n\/\/ ---------------------------------------------------\n\/\/ This is the magic behind the code coverage counters\n\/\/ ---------------------------------------------------\n#ifdef YOSYS_ENABLE_COVER\n\nstd::map<std::string, std::pair<std::string, int>> extra_coverage_data;\n\nvoid cover_extra(std::string parent, std::string id, bool increment) {\n\tif (extra_coverage_data.count(id) == 0) {\n\t\tfor (CoverData *p = __start_yosys_cover_list; p != __stop_yosys_cover_list; p++)\n\t\t\tif (p->id == parent)\n\t\t\t\textra_coverage_data[id].first = stringf(\"%s:%d:%s\", p->file, p->line, p->func);\n\t\tlog_assert(extra_coverage_data.count(id));\n\t}\n\tif (increment)\n\t\textra_coverage_data[id].second++;\n}\n\nstd::map<std::string, std::pair<std::string, int>> get_coverage_data()\n{\n\tstd::map<std::string, std::pair<std::string, int>> coverage_data;\n\n\tfor (auto &it : pass_register) {\n\t\tstd::string key = stringf(\"passes.%s\", it.first.c_str());\n\t\tcoverage_data[key].first = stringf(\"%s:%d:%s\", __FILE__, __LINE__, __FUNCTION__);\n\t\tcoverage_data[key].second += it.second->call_counter;\n\t}\n\n\tfor (auto &it : extra_coverage_data) {\n\t\tif (coverage_data.count(it.first))\n\t\t\tlog(\"WARNING: found duplicate coverage id \\\"%s\\\".\\n\", it.first.c_str());\n\t\tcoverage_data[it.first].first = it.second.first;\n\t\tcoverage_data[it.first].second += it.second.second;\n\t}\n\n\tfor (CoverData *p = __start_yosys_cover_list; p != __stop_yosys_cover_list; p++) {\n\t\tif (coverage_data.count(p->id))\n\t\t\tlog(\"WARNING: found duplicate coverage id \\\"%s\\\".\\n\", p->id);\n\t\tcoverage_data[p->id].first = stringf(\"%s:%d:%s\", p->file, p->line, p->func);\n\t\tcoverage_data[p->id].second += p->counter;\n\t}\n\n\tfor (auto &it : coverage_data)\n\t\tif (!it.second.first.compare(0, strlen(YOSYS_SRC \"\/\"), YOSYS_SRC \"\/\"))\n\t\t\tit.second.first = it.second.first.substr(strlen(YOSYS_SRC \"\/\"));\n\n\treturn coverage_data;\n}\n\n#endif\n\nYOSYS_NAMESPACE_END\n\n<commit_msg>Use a cache for log_id() memory management<commit_after>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>\n * \n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"libs\/sha1\/sha1.h\"\n#include \"backends\/ilang\/ilang_backend.h\"\n\n#if !defined(_WIN32) || defined(__MINGW32__)\n# include <sys\/time.h>\n#endif\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include <vector>\n#include <list>\n\nYOSYS_NAMESPACE_BEGIN\n\nstd::vector<FILE*> log_files;\nstd::vector<std::ostream*> log_streams;\nFILE *log_errfile = NULL;\nSHA1 *log_hasher = NULL;\n\nbool log_time = false;\nbool log_cmd_error_throw = false;\nint log_verbose_level;\n\nstd::vector<int> header_count;\nstd::set<RTLIL::IdString> log_id_cache;\nstd::list<std::string> string_buf;\nint string_buf_size = 0;\n\nstatic struct timeval initial_tv = { 0, 0 };\nstatic bool next_print_log = false;\nstatic int log_newline_count = 0;\n\n#if defined(_WIN32) && !defined(__MINGW32__)\n\/\/ this will get time information and return it in timeval, simulating gettimeofday()\nint gettimeofday(struct timeval *tv, struct timezone *tz)\n{\n\tLARGE_INTEGER counter;\n\tLARGE_INTEGER freq;\n\n\tQueryPerformanceFrequency(&freq);\n\tQueryPerformanceCounter(&counter);\n\n\tcounter.QuadPart *= 1000000;\n\tcounter.QuadPart \/= freq.QuadPart;\n\n\ttv->tv_sec = long(counter.QuadPart \/ 1000000);\n\ttv->tv_usec = counter.QuadPart % 1000000;\n\n\treturn 0;\n}\n#endif\n\nvoid logv(const char *format, va_list ap)\n{\n\twhile (format[0] == '\\n' && format[1] != 0) {\n\t\tlog(\"\\n\");\n\t\tformat++;\n\t}\n\n\tstd::string str = vstringf(format, ap);\n\n\tif (str.empty())\n\t\treturn;\n\n\tsize_t nnl_pos = str.find_last_not_of('\\n');\n\tif (nnl_pos == std::string::npos)\n\t\tlog_newline_count += GetSize(str);\n\telse\n\t\tlog_newline_count = GetSize(str) - nnl_pos - 1;\n\n\tif (log_hasher)\n\t\tlog_hasher->update(str);\n\n\tif (log_time)\n\t{\n\t\tstd::string time_str;\n\n\t\tif (next_print_log || initial_tv.tv_sec == 0) {\n\t\t\tnext_print_log = false;\n\t\t\tstruct timeval tv;\n\t\t\tgettimeofday(&tv, NULL);\n\t\t\tif (initial_tv.tv_sec == 0)\n\t\t\t\tinitial_tv = tv;\n\t\t\tif (tv.tv_usec < initial_tv.tv_usec) {\n\t\t\t\ttv.tv_sec--;\n\t\t\t\ttv.tv_usec += 1000000;\n\t\t\t}\n\t\t\ttv.tv_sec -= initial_tv.tv_sec;\n\t\t\ttv.tv_usec -= initial_tv.tv_usec;\n\t\t\ttime_str += stringf(\"[%05d.%06d] \", int(tv.tv_sec), int(tv.tv_usec));\n\t\t}\n\n\t\tif (format[0] && format[strlen(format)-1] == '\\n')\n\t\t\tnext_print_log = true;\n\n\t\tfor (auto f : log_files)\n\t\t\tfputs(time_str.c_str(), f);\n\n\t\tfor (auto f : log_streams)\n\t\t\t*f << time_str;\n\t}\n\n\tfor (auto f : log_files)\n\t\tfputs(str.c_str(), f);\n\n\tfor (auto f : log_streams)\n\t\t*f << str;\n}\n\nvoid logv_header(const char *format, va_list ap)\n{\n\tbool pop_errfile = false;\n\n\tlog_spacer();\n\tif (header_count.size() > 0)\n\t\theader_count.back()++;\n\n\tif (int(header_count.size()) <= log_verbose_level && log_errfile != NULL) {\n\t\tlog_files.push_back(log_errfile);\n\t\tpop_errfile = true;\n\t}\n\n\tfor (int c : header_count)\n\t\tlog(\"%d.\", c);\n\tlog(\" \");\n\tlogv(format, ap);\n\tlog_flush();\n\n\tif (pop_errfile)\n\t\tlog_files.pop_back();\n}\n\nvoid logv_error(const char *format, va_list ap)\n{\n\tif (log_errfile != NULL)\n\t\tlog_files.push_back(log_errfile);\n\n\tlog(\"ERROR: \");\n\tlogv(format, ap);\n\tlog_flush();\n\texit(1);\n}\n\nvoid log(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv(format, ap);\n\tva_end(ap);\n}\n\nvoid log_header(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv_header(format, ap);\n\tva_end(ap);\n}\n\nvoid log_error(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\tlogv_error(format, ap);\n}\n\nvoid log_cmd_error(const char *format, ...)\n{\n\tva_list ap;\n\tva_start(ap, format);\n\n\tif (log_cmd_error_throw) {\n\t\tlog(\"ERROR: \");\n\t\tlogv(format, ap);\n\t\tlog_flush();\n\t\tthrow log_cmd_error_exception();\n\t}\n\n\tlogv_error(format, ap);\n}\n\nvoid log_spacer()\n{\n\twhile (log_newline_count < 2)\n\t\tlog(\"\\n\");\n}\n\nvoid log_push()\n{\n\theader_count.push_back(0);\n}\n\nvoid log_pop()\n{\n\theader_count.pop_back();\n\tlog_id_cache.clear();\n\tstring_buf.clear();\n\tstring_buf_size = 0;\n\tlog_flush();\n}\n\nvoid log_reset_stack()\n{\n\twhile (header_count.size() > 1)\n\t\theader_count.pop_back();\n\tlog_id_cache.clear();\n\tstring_buf.clear();\n\tstring_buf_size = 0;\n\tlog_flush();\n}\n\nvoid log_flush()\n{\n\tfor (auto f : log_files)\n\t\tfflush(f);\n\n\tfor (auto f : log_streams)\n\t\tf->flush();\n}\n\nvoid log_dump_val_worker(RTLIL::SigSpec v) {\n\tlog(\"%s\", log_signal(v));\n}\n\nconst char *log_signal(const RTLIL::SigSpec &sig, bool autoint)\n{\n\tstd::stringstream buf;\n\tILANG_BACKEND::dump_sigspec(buf, sig, autoint);\n\n\tif (string_buf_size < 100)\n\t\tstring_buf_size++;\n\telse\n\t\tstring_buf.pop_front();\n\tstring_buf.push_back(buf.str());\n\n\treturn string_buf.back().c_str();\n}\n\nconst char *log_id(RTLIL::IdString str)\n{\n\tlog_id_cache.insert(str);\n\tconst char *p = str.c_str();\n\tif (p[0] == '\\\\' && p[1] != '$' && p[1] != 0)\n\t\treturn p+1;\n\treturn p;\n}\n\nvoid log_cell(RTLIL::Cell *cell, std::string indent)\n{\n\tstd::stringstream buf;\n\tILANG_BACKEND::dump_cell(buf, indent, cell);\n\tlog(\"%s\", buf.str().c_str());\n}\n\n\/\/ ---------------------------------------------------\n\/\/ This is the magic behind the code coverage counters\n\/\/ ---------------------------------------------------\n#ifdef YOSYS_ENABLE_COVER\n\nstd::map<std::string, std::pair<std::string, int>> extra_coverage_data;\n\nvoid cover_extra(std::string parent, std::string id, bool increment) {\n\tif (extra_coverage_data.count(id) == 0) {\n\t\tfor (CoverData *p = __start_yosys_cover_list; p != __stop_yosys_cover_list; p++)\n\t\t\tif (p->id == parent)\n\t\t\t\textra_coverage_data[id].first = stringf(\"%s:%d:%s\", p->file, p->line, p->func);\n\t\tlog_assert(extra_coverage_data.count(id));\n\t}\n\tif (increment)\n\t\textra_coverage_data[id].second++;\n}\n\nstd::map<std::string, std::pair<std::string, int>> get_coverage_data()\n{\n\tstd::map<std::string, std::pair<std::string, int>> coverage_data;\n\n\tfor (auto &it : pass_register) {\n\t\tstd::string key = stringf(\"passes.%s\", it.first.c_str());\n\t\tcoverage_data[key].first = stringf(\"%s:%d:%s\", __FILE__, __LINE__, __FUNCTION__);\n\t\tcoverage_data[key].second += it.second->call_counter;\n\t}\n\n\tfor (auto &it : extra_coverage_data) {\n\t\tif (coverage_data.count(it.first))\n\t\t\tlog(\"WARNING: found duplicate coverage id \\\"%s\\\".\\n\", it.first.c_str());\n\t\tcoverage_data[it.first].first = it.second.first;\n\t\tcoverage_data[it.first].second += it.second.second;\n\t}\n\n\tfor (CoverData *p = __start_yosys_cover_list; p != __stop_yosys_cover_list; p++) {\n\t\tif (coverage_data.count(p->id))\n\t\t\tlog(\"WARNING: found duplicate coverage id \\\"%s\\\".\\n\", p->id);\n\t\tcoverage_data[p->id].first = stringf(\"%s:%d:%s\", p->file, p->line, p->func);\n\t\tcoverage_data[p->id].second += p->counter;\n\t}\n\n\tfor (auto &it : coverage_data)\n\t\tif (!it.second.first.compare(0, strlen(YOSYS_SRC \"\/\"), YOSYS_SRC \"\/\"))\n\t\t\tit.second.first = it.second.first.substr(strlen(YOSYS_SRC \"\/\"));\n\n\treturn coverage_data;\n}\n\n#endif\n\nYOSYS_NAMESPACE_END\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Robert McGibbon\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Calculation of the fused-sphere van der waals surface of a molecule.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <math.h>\n#include <algorithm>\n#include <utility>\n#include <vector>\n#include <iostream>\n#include <stdio.h>\n#include <map>\n#include <set>\n\n#include \"include\/dotsphere.h\"\n\/\/ this is also included in the psi4 code as libmints\/vector3.h\n#include \"include\/vector3.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nusing namespace std;\nusing namespace psi;\n\n\n\/\/ A. Bondi (1964). \"van der Waals Volumes and Radii\". J. Phys. Chem. 68: 441. doi:10.1021\/j100785a001\nstatic map<string, double> create_bondi_radii() {\n map<string, double> m;\n m[\"H\"] = 1.2;\n m[\"C\"] = 1.7;\n m[\"N\"] = 1.55;\n m[\"O\"] = 1.52;\n m[\"F\"] = 1.47;\n m[\"P\"] = 1.8;\n m[\"S\"] = 1.8;\n m[\"Cl\"] = 1.75;\n\n m[\"Ar\"] = 1.88;\n m[\"As\"] = 1.85;\n m[\"Br\"] = 1.85;\n m[\"Cd\"] = 1.62;\n m[\"Cu\"] = 1.4;\n m[\"Ga\"] = 1.87;\n m[\"Au\"] = 1.66;\n m[\"He\"] = 1.4;\n m[\"In\"] = 1.93;\n m[\"I\"] = 1.98;\n m[\"Kr\"] = 2.02;\n m[\"Pb\"] = 2.02;\n m[\"Li\"] = 1.82;\n m[\"Mg\"] = 1.73;\n m[\"Hg\"] = 1.70;\n m[\"Ne\"] = 1.54;\n m[\"Ni\"] = 1.64;\n m[\"Pd\"] = 1.63;\n m[\"Pt\"] = 1.8;\n m[\"K\"] = 2.75;\n m[\"Se\"] = 1.90;\n m[\"Si\"] = 2.1;\n m[\"Ag\"] = 1.9;\n m[\"Na\"] = 2.27;\n m[\"Te\"] = 2.06;\n m[\"Tl\"] = 1.96;\n m[\"Sn\"] = 2.17;\n m[\"U\"] = 1.86;\n m[\"Xe\"] = 2.16;\n m[\"Zn\"] = 1.37;\n return m;\n}\nstatic map<string, double> BONDI_RADII = create_bondi_radii();\n\n\n\/\/ #############################################################################\n\/\/ # Functions\n\/\/ #############################################################################\n\/\/\nvector<Vector3> vdw_surface(vector<Vector3> coordinates, vector<string> elements,\n double scale_factor, double density) {\n \/\/ Compute points on the VDW surface of a molecule\n \/\/\n \/\/ Parameters\n \/\/ ----------\n \/\/ coordinates : np.ndarray, shape=(n_atoms, 3)\n \/\/ The cartesian coordinates of the nuclei, in units of ANGSTROMS\n \/\/ elements : list, shape=(n_atoms)\n \/\/ The element symbols (C, H, etc) for each of the nuceli\n \/\/ scale_factor : float\n \/\/ The points on the molecular surface are set at a distance of\n \/\/ scale_factor * vdw_radius away from each of the atoms.\n \/\/ density : float\n \/\/ The (approximate) number of points to generate per square angstrom\n \/\/ of surface area. 1.0 is the default recommended by Kollman & Singh.\n if (coordinates.size() != elements.size()) {\n fprintf(stderr, \"coordinate.size doesnot match elements.size\");\n exit(1);\n }\n\n vector<Vector3> surfacepoints;\n vector<double> radii;\n\n for (size_t i = 0; i < elements.size(); i++) {\n \/\/ todo: check for error if element not in BONDI_RADII table\n if (BONDI_RADII.find(elements[i]) != BONDI_RADII.end()) {\n radii.push_back(BONDI_RADII[elements[i]] * scale_factor);\n } else {\n fprintf(stderr, \"%s is not a supported element\", elements[i].c_str());\n exit(1);\n }\n }\n\n for (size_t i = 0; i < coordinates.size(); i++) {\n \/\/ this could be optimized -- we don't need to compute the dotsphere.\n \/\/ at maximum we only need to compute it once per unique element \/ radius\n vector<Vector3> dots = dotsphere(density * ((4.0\/3.0) * M_PI * radii[i]*radii[i]*radii[i]));\n\n for (size_t j = 0; j < dots.size(); j++)\n dots[j] = coordinates[i] + radii[i]*dots[j];\n\n \/\/ all of the atoms that i is close to\n typedef std::pair<double, size_t> Neighbor;\n vector<Neighbor> neighbors;\n for (size_t j = 0; j < coordinates.size(); j++) {\n if (i == j)\n continue;\n double d = (coordinates[i] - coordinates[j]).norm();\n if (d < (radii[i] + radii[j])) {\n neighbors.push_back(make_pair(d, j));\n }\n }\n sort(neighbors.begin(), neighbors.end());\n\n for (size_t k = 0; k < dots.size(); k++) {\n int accessible = 1;\n for (vector<Neighbor>::iterator it = neighbors.begin() ; it != neighbors.end(); ++it) {\n if ((coordinates[(*it).second] - dots[k]).norm() < radii[(*it).second]) {\n accessible = 0;\n break;\n }\n }\n if (accessible)\n surfacepoints.push_back(dots[k]);\n }\n }\n\n return surfacepoints;\n}\n\n\/\/ extern \"C\" void vdw_surface(double* coordinates, char* elements, int n_elements,\n\/\/ double scale_factor, double density, double* out, int* n_out) {\n\/\/ vector<string> elements_;\n\/\/ vector<Vector3> coordinates_;\n\/\/ \n\/\/ istringstream iss(elements);\n\/\/ string s;\n\/\/ for (int i = 0; i < n_elements; i++) {\n\/\/ getline(iss, s, ' ');\n\/\/ elements_.push_back(string(s));\n\/\/ coordinates_.push_back(Vector3(coordinates[3*i+0], coordinates[3*i+1], coordinates[3*i+2]));\n\/\/ }\n\/\/ \n\/\/ vector<Vector3> points = vdw_surface(coordinates_, elements_, scale_factor, density);\n\/\/ for (size_t i = 0; i < points.size(); i++) {\n\/\/ out[3*i+0] = points[i][0];\n\/\/ out[3*i+1] = points[i][1];\n\/\/ out[3*i+2] = points[i][2];\n\/\/ }\n\/\/ *n_out = points.size();\n\/\/ }\n<commit_msg>Update vdwsurface.cc<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Calculation of the fused-sphere van der waals surface of a molecule.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <math.h>\n#include <algorithm>\n#include <utility>\n#include <vector>\n#include <iostream>\n#include <stdio.h>\n#include <map>\n#include <set>\n\n#include \"include\/dotsphere.h\"\n\/\/ this is also included in the psi4 code as libmints\/vector3.h\n#include \"include\/vector3.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nusing namespace std;\nusing namespace psi;\n\n\n\/\/ A. Bondi (1964). \"van der Waals Volumes and Radii\". J. Phys. Chem. 68: 441. doi:10.1021\/j100785a001\nstatic map<string, double> create_bondi_radii() {\n map<string, double> m;\n m[\"H\"] = 1.2;\n m[\"C\"] = 1.7;\n m[\"N\"] = 1.55;\n m[\"O\"] = 1.52;\n m[\"F\"] = 1.47;\n m[\"P\"] = 1.8;\n m[\"S\"] = 1.8;\n m[\"Cl\"] = 1.75;\n\n m[\"Ar\"] = 1.88;\n m[\"As\"] = 1.85;\n m[\"Br\"] = 1.85;\n m[\"Cd\"] = 1.62;\n m[\"Cu\"] = 1.4;\n m[\"Ga\"] = 1.87;\n m[\"Au\"] = 1.66;\n m[\"He\"] = 1.4;\n m[\"In\"] = 1.93;\n m[\"I\"] = 1.98;\n m[\"Kr\"] = 2.02;\n m[\"Pb\"] = 2.02;\n m[\"Li\"] = 1.82;\n m[\"Mg\"] = 1.73;\n m[\"Hg\"] = 1.70;\n m[\"Ne\"] = 1.54;\n m[\"Ni\"] = 1.64;\n m[\"Pd\"] = 1.63;\n m[\"Pt\"] = 1.8;\n m[\"K\"] = 2.75;\n m[\"Se\"] = 1.90;\n m[\"Si\"] = 2.1;\n m[\"Ag\"] = 1.9;\n m[\"Na\"] = 2.27;\n m[\"Te\"] = 2.06;\n m[\"Tl\"] = 1.96;\n m[\"Sn\"] = 2.17;\n m[\"U\"] = 1.86;\n m[\"Xe\"] = 2.16;\n m[\"Zn\"] = 1.37;\n return m;\n}\nstatic map<string, double> BONDI_RADII = create_bondi_radii();\n\n\n\/\/ #############################################################################\n\/\/ # Functions\n\/\/ #############################################################################\n\/\/\nvector<Vector3> vdw_surface(vector<Vector3> coordinates, vector<string> elements,\n double scale_factor, double density) {\n \/\/ Compute points on the VDW surface of a molecule\n \/\/\n \/\/ Parameters\n \/\/ ----------\n \/\/ coordinates : np.ndarray, shape=(n_atoms, 3)\n \/\/ The cartesian coordinates of the nuclei, in units of ANGSTROMS\n \/\/ elements : list, shape=(n_atoms)\n \/\/ The element symbols (C, H, etc) for each of the nuceli\n \/\/ scale_factor : float\n \/\/ The points on the molecular surface are set at a distance of\n \/\/ scale_factor * vdw_radius away from each of the atoms.\n \/\/ density : float\n \/\/ The (approximate) number of points to generate per square angstrom\n \/\/ of surface area. 1.0 is the default recommended by Kollman & Singh.\n if (coordinates.size() != elements.size()) {\n fprintf(stderr, \"coordinate.size doesnot match elements.size\");\n exit(1);\n }\n\n vector<Vector3> surfacepoints;\n vector<double> radii;\n\n for (size_t i = 0; i < elements.size(); i++) {\n \/\/ todo: check for error if element not in BONDI_RADII table\n if (BONDI_RADII.find(elements[i]) != BONDI_RADII.end()) {\n radii.push_back(BONDI_RADII[elements[i]] * scale_factor);\n } else {\n fprintf(stderr, \"%s is not a supported element\", elements[i].c_str());\n exit(1);\n }\n }\n\n for (size_t i = 0; i < coordinates.size(); i++) {\n \/\/ this could be optimized -- we don't need to compute the dotsphere.\n \/\/ at maximum we only need to compute it once per unique element \/ radius\n vector<Vector3> dots = dotsphere(density * ((4.0\/3.0) * M_PI * radii[i]*radii[i]*radii[i]));\n\n for (size_t j = 0; j < dots.size(); j++)\n dots[j] = coordinates[i] + radii[i]*dots[j];\n\n \/\/ all of the atoms that i is close to\n typedef std::pair<double, size_t> Neighbor;\n vector<Neighbor> neighbors;\n for (size_t j = 0; j < coordinates.size(); j++) {\n if (i == j)\n continue;\n double d = (coordinates[i] - coordinates[j]).norm();\n if (d < (radii[i] + radii[j])) {\n neighbors.push_back(make_pair(d, j));\n }\n }\n sort(neighbors.begin(), neighbors.end());\n\n for (size_t k = 0; k < dots.size(); k++) {\n int accessible = 1;\n for (vector<Neighbor>::iterator it = neighbors.begin() ; it != neighbors.end(); ++it) {\n if ((coordinates[(*it).second] - dots[k]).norm() < radii[(*it).second]) {\n accessible = 0;\n break;\n }\n }\n if (accessible)\n surfacepoints.push_back(dots[k]);\n }\n }\n\n return surfacepoints;\n}\n\n\/\/ extern \"C\" void vdw_surface(double* coordinates, char* elements, int n_elements,\n\/\/ double scale_factor, double density, double* out, int* n_out) {\n\/\/ vector<string> elements_;\n\/\/ vector<Vector3> coordinates_;\n\/\/ \n\/\/ istringstream iss(elements);\n\/\/ string s;\n\/\/ for (int i = 0; i < n_elements; i++) {\n\/\/ getline(iss, s, ' ');\n\/\/ elements_.push_back(string(s));\n\/\/ coordinates_.push_back(Vector3(coordinates[3*i+0], coordinates[3*i+1], coordinates[3*i+2]));\n\/\/ }\n\/\/ \n\/\/ vector<Vector3> points = vdw_surface(coordinates_, elements_, scale_factor, density);\n\/\/ for (size_t i = 0; i < points.size(); i++) {\n\/\/ out[3*i+0] = points[i][0];\n\/\/ out[3*i+1] = points[i][1];\n\/\/ out[3*i+2] = points[i][2];\n\/\/ }\n\/\/ *n_out = points.size();\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <boost\/assign.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/trainer.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/dict.hpp>\n#include <pkmn\/types\/prng.hpp>\n\n#include \"bag_impl.hpp\"\n#include \"team_pokemon_gen1impl.hpp\"\n#include \"team_pokemon_gen2impl.hpp\"\n#include \"team_pokemon_modernimpl.hpp\"\n\n#include \"trainer_impl.hpp\"\n\nusing namespace std;\n\nnamespace pkmn\n{\n trainer::sptr trainer::make(unsigned int game, pokemon_text name, unsigned int gender)\n {\n return sptr(new trainer_impl(game, name, gender));\n }\n\n trainer::sptr trainer::make(std::string game, pokemon_text name, std::string gender)\n {\n return make(database::get_game_id(game),\n name,\n ((gender == \"Female\") ? Genders::FEMALE : Genders::MALE));\n }\n\n trainer_impl::trainer_impl(unsigned int game, pokemon_text name, unsigned int gender): trainer()\n {\n prng::sptr _rand_gen = prng::get(_generation);\n\n _game_id = game;\n _generation = database::get_generation(_game_id);\n _trainer_name = name;\n _gender_id = gender;\n _money = 0;\n \n \/*\n * Public vs. secret ID's weren't a factor in Generations I-II\n *\/\n _trainer_id = (_generation < 3) ? (_rand_gen->lcrng() % 65535)\n : _rand_gen->lcrng();\n\n _party = pokemon_team_t(6);\n for(int i = 0; i < 6; i++)\n {\n _party[i] = team_pokemon::make(Species::NONE, _game_id, 1, Moves::NONE, Moves::NONE,\n Moves::NONE, Moves::NONE);\n }\n \n _bag = bag::make(_game_id);\n }\n\n pokemon_text trainer_impl::get_game() const {return database::get_game_name(_game_id);}\n\n unsigned int trainer_impl::get_generation() const {return _generation;}\n\n pokemon_text trainer_impl::get_name() const {return _trainer_name;}\n\n unsigned int trainer_impl::get_money() const {return _money;}\n\n pokemon_text trainer_impl::get_gender() const\n {\n return (_gender_id == Genders::MALE) ? \"Male\" : \"Female\";\n }\n\n unsigned int trainer_impl::get_id() const\n {\n return (_generation < 3) ? _tid.public_id\n : _trainer_id;\n }\n\n unsigned short trainer_impl::get_public_id() const {return _tid.public_id;}\n\n unsigned short trainer_impl::get_secret_id() const\n {\n return (_generation < 3) ? 0\n : _tid.secret_id;\n }\n\n void trainer_impl::set_name(pokemon_text name)\n {\n _trainer_name = (name.std_string().length() >= 1\n and name.std_string().length() <= 7) ? name\n : _trainer_name;\n }\n\n void trainer_impl::set_money(unsigned int money)\n {\n _money = (money > 999999) ? _money : money;\n }\n\n void trainer_impl::set_gender(pokemon_text gender)\n {\n if(gender == \"Male\") _gender_id = Genders::MALE;\n else if(gender == \"Female\") _gender_id = Genders::FEMALE;\n }\n\n void trainer_impl::set_id(unsigned int id) {_trainer_id = id;}\n\n void trainer_impl::set_public_id(unsigned short id) {_tid.public_id = id;}\n \n void trainer_impl::set_secret_id(unsigned short id) {_tid.secret_id = id;}\n\n team_pokemon::sptr trainer_impl::get_pokemon(unsigned int pos)\n {\n \/\/If invalid position given, return invalid Pokemon\n if(pos == 0 or pos > 6) return team_pokemon::make(Species::INVALID, _game_id, 0, Moves::NONE,\n Moves::NONE, Moves::NONE, Moves::NONE);\n else return _party[pos-1];\n }\n\n void trainer_impl::set_pokemon(unsigned int pos, team_pokemon::sptr t_pkmn)\n {\n \/\/Check for valid position, don't do anything otherwise\n if(pos >= 1 and pos <= 6)\n {\n \/\/TODO: more through check (items, forms, etc)\n if(database::get_version_group(_game_id) ==\n database::get_version_group(t_pkmn->get_game_id())) _party[pos-1] = t_pkmn;\n }\n }\n\n void trainer_impl::remove_pokemon(unsigned int pos)\n {\n unsigned int actual_pos = (pos > 6) ? 5 : (pos == 0) ? 0 : (pos-1);\n \n team_pokemon::sptr blank_pokemon = team_pokemon::make(Species::NONE, _game_id, 0, Moves::NONE,\n Moves::NONE, Moves::NONE, Moves::NONE);\n\n set_pokemon(actual_pos, blank_pokemon);\n \n \/\/Move over any non-blank Pokemon in later positions\n for(int i = (actual_pos+1); i < 6; i++)\n {\n if(_party[i]->get_species_id() == Species::NONE) break;\n else\n {\n _party[i-1] = _party[i];\n _party[i] = blank_pokemon;\n }\n }\n }\n\n void trainer_impl::get_party(pokemon_team_t& party)\n {\n party = _party;\n }\n\n \/\/TODO: allow for other trainers' Pokemon\n void trainer_impl::set_party(pokemon_team_t& party)\n {\n \/\/Only set party if party and all Pokemon are valid\n if(party.size() != 6) return;\n if(party[0]->get_game_id() != _game_id or\n party[1]->get_game_id() != _game_id or\n party[2]->get_game_id() != _game_id or\n party[3]->get_game_id() != _game_id or\n party[4]->get_game_id() != _game_id or\n party[5]->get_game_id() != _game_id) return;\n\n _party = party;\n }\n\n bag::sptr trainer_impl::get_bag() const {return _bag;}\n\n unsigned int trainer_impl::get_game_id() const {return _game_id;}\n} \/* namespace pkmn *\/\n<commit_msg>trainer: made sure _generation is set before using it to create PRNG<commit_after>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <boost\/assign.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/trainer.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/dict.hpp>\n#include <pkmn\/types\/prng.hpp>\n\n#include \"bag_impl.hpp\"\n#include \"team_pokemon_gen1impl.hpp\"\n#include \"team_pokemon_gen2impl.hpp\"\n#include \"team_pokemon_modernimpl.hpp\"\n\n#include \"trainer_impl.hpp\"\n\nusing namespace std;\n\nnamespace pkmn\n{\n trainer::sptr trainer::make(unsigned int game, pokemon_text name, unsigned int gender)\n {\n return sptr(new trainer_impl(game, name, gender));\n }\n\n trainer::sptr trainer::make(std::string game, pokemon_text name, std::string gender)\n {\n return make(database::get_game_id(game),\n name,\n ((gender == \"Female\") ? Genders::FEMALE : Genders::MALE));\n }\n\n trainer_impl::trainer_impl(unsigned int game, pokemon_text name, unsigned int gender): trainer()\n {\n _game_id = game;\n _generation = database::get_generation(_game_id);\n _trainer_name = name;\n _gender_id = gender;\n _money = 0;\n\n prng::sptr _rand_gen = prng::get(_generation);\n \n \/*\n * Public vs. secret ID's weren't a factor in Generations I-II\n *\/\n _trainer_id = (_generation < 3) ? (_rand_gen->lcrng() % 65535)\n : _rand_gen->lcrng();\n\n _party = pokemon_team_t(6);\n for(int i = 0; i < 6; i++)\n {\n _party[i] = team_pokemon::make(Species::NONE, _game_id, 1, Moves::NONE, Moves::NONE,\n Moves::NONE, Moves::NONE);\n }\n \n _bag = bag::make(_game_id);\n }\n\n pokemon_text trainer_impl::get_game() const {return database::get_game_name(_game_id);}\n\n unsigned int trainer_impl::get_generation() const {return _generation;}\n\n pokemon_text trainer_impl::get_name() const {return _trainer_name;}\n\n unsigned int trainer_impl::get_money() const {return _money;}\n\n pokemon_text trainer_impl::get_gender() const\n {\n return (_gender_id == Genders::MALE) ? \"Male\" : \"Female\";\n }\n\n unsigned int trainer_impl::get_id() const\n {\n return (_generation < 3) ? _tid.public_id\n : _trainer_id;\n }\n\n unsigned short trainer_impl::get_public_id() const {return _tid.public_id;}\n\n unsigned short trainer_impl::get_secret_id() const\n {\n return (_generation < 3) ? 0\n : _tid.secret_id;\n }\n\n void trainer_impl::set_name(pokemon_text name)\n {\n _trainer_name = (name.std_string().length() >= 1\n and name.std_string().length() <= 7) ? name\n : _trainer_name;\n }\n\n void trainer_impl::set_money(unsigned int money)\n {\n _money = (money > 999999) ? _money : money;\n }\n\n void trainer_impl::set_gender(pokemon_text gender)\n {\n if(gender == \"Male\") _gender_id = Genders::MALE;\n else if(gender == \"Female\") _gender_id = Genders::FEMALE;\n }\n\n void trainer_impl::set_id(unsigned int id) {_trainer_id = id;}\n\n void trainer_impl::set_public_id(unsigned short id) {_tid.public_id = id;}\n \n void trainer_impl::set_secret_id(unsigned short id) {_tid.secret_id = id;}\n\n team_pokemon::sptr trainer_impl::get_pokemon(unsigned int pos)\n {\n \/\/If invalid position given, return invalid Pokemon\n if(pos == 0 or pos > 6) return team_pokemon::make(Species::INVALID, _game_id, 0, Moves::NONE,\n Moves::NONE, Moves::NONE, Moves::NONE);\n else return _party[pos-1];\n }\n\n void trainer_impl::set_pokemon(unsigned int pos, team_pokemon::sptr t_pkmn)\n {\n \/\/Check for valid position, don't do anything otherwise\n if(pos >= 1 and pos <= 6)\n {\n \/\/TODO: more through check (items, forms, etc)\n if(database::get_version_group(_game_id) ==\n database::get_version_group(t_pkmn->get_game_id())) _party[pos-1] = t_pkmn;\n }\n }\n\n void trainer_impl::remove_pokemon(unsigned int pos)\n {\n unsigned int actual_pos = (pos > 6) ? 5 : (pos == 0) ? 0 : (pos-1);\n \n team_pokemon::sptr blank_pokemon = team_pokemon::make(Species::NONE, _game_id, 0, Moves::NONE,\n Moves::NONE, Moves::NONE, Moves::NONE);\n\n set_pokemon(actual_pos, blank_pokemon);\n \n \/\/Move over any non-blank Pokemon in later positions\n for(int i = (actual_pos+1); i < 6; i++)\n {\n if(_party[i]->get_species_id() == Species::NONE) break;\n else\n {\n _party[i-1] = _party[i];\n _party[i] = blank_pokemon;\n }\n }\n }\n\n void trainer_impl::get_party(pokemon_team_t& party)\n {\n party = _party;\n }\n\n \/\/TODO: allow for other trainers' Pokemon\n void trainer_impl::set_party(pokemon_team_t& party)\n {\n \/\/Only set party if party and all Pokemon are valid\n if(party.size() != 6) return;\n if(party[0]->get_game_id() != _game_id or\n party[1]->get_game_id() != _game_id or\n party[2]->get_game_id() != _game_id or\n party[3]->get_game_id() != _game_id or\n party[4]->get_game_id() != _game_id or\n party[5]->get_game_id() != _game_id) return;\n\n _party = party;\n }\n\n bag::sptr trainer_impl::get_bag() const {return _bag;}\n\n unsigned int trainer_impl::get_game_id() const {return _game_id;}\n} \/* namespace pkmn *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Input.hxx\"\n#include \"was\/async\/Error.hxx\"\n#include \"event\/PipeEvent.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/Result.hxx\"\n#include \"istream\/Bucket.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"io\/Buffered.hxx\"\n#include \"io\/SpliceSupport.hxx\"\n#include \"system\/Error.hxx\"\n#include \"util\/ScopeExit.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <errno.h>\n#include <string.h>\n#include <unistd.h>\n\nclass WasInput final : Istream {\n\tPipeEvent event;\n\n\tWasInputHandler &handler;\n\n\tSliceFifoBuffer buffer;\n\n\tuint64_t received = 0, length;\n\n\tbool direct = false;\n\n\tbool enabled = false;\n\n\tbool closed = false, known_length = false;\n\npublic:\n\tWasInput(struct pool &p, EventLoop &event_loop, FileDescriptor fd,\n\t\t WasInputHandler &_handler) noexcept\n\t\t:Istream(p),\n\t\t event(event_loop, BIND_THIS_METHOD(EventCallback), fd),\n\t\t handler(_handler) {\n\t}\n\n\tvoid Free(std::exception_ptr ep) noexcept;\n\n\tusing Istream::Destroy;\n\n\tvoid DestroyUnused() noexcept {\n\t\tassert(!HasHandler());\n\t\tassert(!closed);\n\t\tassert(!buffer.IsDefined());\n\n\t\tDestroy();\n\t}\n\n\tUnusedIstreamPtr Enable() noexcept {\n\t\tassert(!enabled);\n\t\tenabled = true;\n\t\tScheduleRead();\n\t\treturn UnusedIstreamPtr(this);\n\t}\n\n\tvoid Disable() noexcept {\n\t\tevent.Cancel();\n\t}\n\n\tbool SetLength(uint64_t _length) noexcept;\n\tvoid PrematureThrow(uint64_t _length);\n\tvoid Premature(uint64_t _length) noexcept;\n\nprivate:\n\tbool HasPipe() const noexcept {\n\t\treturn event.IsDefined();\n\t}\n\n\tFileDescriptor GetPipe() noexcept {\n\t\treturn event.GetFileDescriptor();\n\t}\n\n\tbool CanRelease() const {\n\t\treturn known_length && received == length;\n\t}\n\n\t\/**\n\t * @return false if the #WasInput has been destroyed\n\t *\/\n\tbool ReleasePipe() noexcept {\n\t\tassert(HasPipe());\n\n\t\tevent.Cancel();\n\t\tevent.ReleaseFileDescriptor();\n\n\t\treturn handler.WasInputRelease();\n\t}\n\n\t\/**\n\t * @return false if the #WasInput has been destroyed\n\t *\/\n\tbool CheckReleasePipe() noexcept {\n\t\treturn !CanRelease() || ReleasePipe();\n\t}\n\n\tvoid ScheduleRead() noexcept {\n\t\tassert(HasPipe());\n\t\tassert(!buffer.IsDefined() || !buffer.IsFull());\n\n\t\tevent.ScheduleRead();\n\t}\n\n\tvoid AbortError(std::exception_ptr ep) noexcept {\n\t\tbuffer.FreeIfDefined();\n\t\tevent.Cancel();\n\n\t\t\/* protect against recursive Free() call within the istream\n\t\t handler *\/\n\t\tclosed = true;\n\n\t\thandler.WasInputError();\n\t\tDestroyError(ep);\n\t}\n\n\tvoid AbortError(const char *msg) noexcept {\n\t\tAbortError(std::make_exception_ptr(WasProtocolError(msg)));\n\t}\n\n\tvoid Eof() noexcept {\n\t\tassert(known_length);\n\t\tassert(received == length);\n\t\tassert(!buffer.IsDefined());\n\n\t\tevent.Cancel();\n\n\t\thandler.WasInputEof();\n\t\tDestroyEof();\n\t}\n\n\tbool CheckEof() noexcept {\n\t\tif (CanRelease() && buffer.empty()) {\n\t\t\tEof();\n\t\t\treturn true;\n\t\t} else\n\t\t\treturn false;\n\t}\n\n\t\/**\n\t * Consume data from the input buffer.\n\t *\n\t * @return false if the handler blocks or if this object has been\n\t * destroyed\n\t *\/\n\tbool SubmitBuffer() noexcept {\n\t\tauto r = buffer.Read();\n\t\tif (!r.empty()) {\n\t\t\tsize_t nbytes = InvokeData(r.data, r.size);\n\t\t\tif (nbytes == 0)\n\t\t\t\treturn false;\n\n\t\t\tbuffer.Consume(nbytes);\n\t\t\tbuffer.FreeIfEmpty();\n\t\t}\n\n\t\tif (CheckEof())\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\t\/*\n\t * socket i\/o\n\t *\n\t *\/\n\n\t\/**\n\t * Throws on error.\n\t *\/\n\tvoid ReadToBuffer();\n\n\tbool TryBuffered() noexcept;\n\tbool TryDirect() noexcept;\n\n\tvoid TryRead() noexcept {\n\t\tif (direct) {\n\t\t\tif (SubmitBuffer() && buffer.empty())\n\t\t\t\tTryDirect();\n\t\t} else {\n\t\t\tTryBuffered();\n\t\t}\n\t}\n\n\tvoid EventCallback(unsigned events) noexcept;\n\n\t\/* virtual methods from class Istream *\/\n\n\tvoid _SetDirect(FdTypeMask mask) noexcept override {\n\t\tdirect = (mask & ISTREAM_TO_PIPE) != 0;\n\t}\n\n\toff_t _GetAvailable(bool partial) noexcept override {\n\t\tif (known_length)\n\t\t\treturn length - received + buffer.GetAvailable();\n\t\telse if (partial)\n\t\t\treturn buffer.GetAvailable();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tvoid _Read() noexcept override {\n\t\tif (SubmitBuffer())\n\t\t\tTryRead();\n\t}\n\n\tvoid _FillBucketList(IstreamBucketList &list) override;\n\tsize_t _ConsumeBucketList(size_t nbytes) noexcept override;\n\n\tvoid _Close() noexcept override {\n\t\tbuffer.FreeIfDefined();\n\t\tevent.Cancel();\n\n\t\t\/* protect against recursive Free() call within the istream\n\t\t handler *\/\n\t\tclosed = true;\n\n\t\thandler.WasInputClose(received);\n\n\t\tDestroy();\n\t}\n};\n\nvoid\nWasInput::ReadToBuffer()\n{\n\tbuffer.AllocateIfNull(fb_pool_get());\n\n\tsize_t max_length = FB_SIZE;\n\tif (known_length) {\n\t\tuint64_t rest = length - received;\n\t\tif (rest < (uint64_t)max_length)\n\t\t\tmax_length = rest;\n\n\t\tif (max_length == 0)\n\t\t\t\/* all the data we need is already in the buffer *\/\n\t\t\treturn;\n\t}\n\n\tssize_t nbytes = read_to_buffer(GetPipe().Get(), buffer, max_length);\n\tassert(nbytes != -2);\n\n\tif (nbytes == 0)\n\t\tthrow WasProtocolError(\"server closed the data connection\");\n\n\tif (nbytes < 0) {\n\t\tconst int e = errno;\n\n\t\tif (e == EAGAIN) {\n\t\t\tbuffer.FreeIfEmpty();\n\t\t\tScheduleRead();\n\t\t\treturn;\n\t\t}\n\n\t\tthrow MakeErrno(e, \"read error on WAS data connection\");\n\t}\n\n\treceived += nbytes;\n\n\tif (buffer.IsFull())\n\t\tevent.CancelRead();\n}\n\ninline bool\nWasInput::TryBuffered() noexcept\n{\n\tif (HasPipe()) {\n\t\ttry {\n\t\t\tReadToBuffer();\n\t\t} catch (...) {\n\t\t\tAbortError(std::current_exception());\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!CheckReleasePipe())\n\t\t\treturn false;\n\t}\n\n\tif (SubmitBuffer()) {\n\t\tassert(!buffer.IsDefinedAndFull());\n\n\t\tif (HasPipe())\n\t\t\tScheduleRead();\n\t}\n\n\treturn true;\n}\n\ninline bool\nWasInput::TryDirect() noexcept\n{\n\tassert(buffer.empty());\n\tassert(!buffer.IsDefined());\n\n\tsize_t max_length = 0x1000000;\n\tif (known_length) {\n\t\tuint64_t rest = length - received;\n\t\tif (rest < (uint64_t)max_length)\n\t\t\tmax_length = rest;\n\t}\n\n\tssize_t nbytes = InvokeDirect(FdType::FD_PIPE, GetPipe().Get(), max_length);\n\tif (nbytes == ISTREAM_RESULT_BLOCKING) {\n\t\tevent.CancelRead();\n\t\treturn false;\n\t}\n\n\tif (nbytes == ISTREAM_RESULT_EOF || nbytes == ISTREAM_RESULT_CLOSED)\n\t\treturn false;\n\n\tif (nbytes < 0) {\n\t\tconst int e = errno;\n\n\t\tif (e == EAGAIN) {\n\t\t\tScheduleRead();\n\t\t\treturn false;\n\t\t}\n\n\t\tAbortError(std::make_exception_ptr(MakeErrno(e,\n\t\t\t\t\t\t\t \"read error on WAS data connection\")));\n\t\treturn false;\n\t}\n\n\treceived += nbytes;\n\n\tif (!CheckReleasePipe())\n\t\treturn false;\n\n\tif (CheckEof())\n\t\treturn false;\n\n\tScheduleRead();\n\treturn true;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nWasInput::EventCallback(unsigned) noexcept\n{\n\tassert(HasPipe());\n\n\tTryRead();\n}\n\n\/*\n * constructor\n *\n *\/\n\nWasInput *\nwas_input_new(struct pool &pool, EventLoop &event_loop, FileDescriptor fd,\n\t WasInputHandler &handler) noexcept\n{\n\tassert(fd.IsDefined());\n\n\treturn NewFromPool<WasInput>(pool, pool, event_loop, fd,\n\t\t\t\t handler);\n}\n\ninline void\nWasInput::Free(std::exception_ptr ep) noexcept\n{\n\tassert(ep || closed || !enabled);\n\n\tbuffer.FreeIfDefined();\n\n\tevent.Cancel();\n\n\tif (!closed && enabled)\n\t\tDestroyError(ep);\n}\n\nvoid\nwas_input_free(WasInput *input, std::exception_ptr ep) noexcept\n{\n\tinput->Free(ep);\n}\n\nvoid\nwas_input_free_unused(WasInput *input) noexcept\n{\n\tinput->DestroyUnused();\n}\n\nUnusedIstreamPtr\nwas_input_enable(WasInput &input) noexcept\n{\n\treturn input.Enable();\n}\n\nvoid\nwas_input_disable(WasInput &input) noexcept\n{\n\tinput.Disable();\n}\n\ninline bool\nWasInput::SetLength(uint64_t _length) noexcept\n{\n\tif (known_length) {\n\t\tif (_length == length)\n\t\t\treturn true;\n\n\t\t\/\/ TODO: don't invoke Istream::DestroyError() if not yet enabled\n\t\tAbortError(\"wrong input length announced\");\n\t\treturn false;\n\t}\n\n\tif (_length < received) {\n\t\t\/* this length must be bogus, because we already received more than that from the socket *\/\n\t\tAbortError(\"announced length is too small\");\n\t\treturn false;\n\t}\n\n\tlength = _length;\n\tknown_length = true;\n\n\tif (!CheckReleasePipe())\n\t\treturn false;\n\n\tif (enabled && CheckEof())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool\nwas_input_set_length(WasInput *input, uint64_t length) noexcept\n{\n\treturn input->SetLength(length);\n}\n\nvoid\nWasInput::PrematureThrow(uint64_t _length)\n{\n\tbuffer.FreeIfDefined();\n\tevent.Cancel();\n\n\tif (known_length && _length > length)\n\t\tthrow WasProtocolError(\"announced premature length is too large\");\n\n\tif (_length < received)\n\t\tthrow WasProtocolError(\"announced premature length is too small\");\n\n\tuint64_t remaining = _length - received;\n\n\twhile (remaining > 0) {\n\t\tuint8_t discard_buffer[4096];\n\t\tsize_t size = std::min(remaining, uint64_t(sizeof(discard_buffer)));\n\t\tssize_t nbytes = GetPipe().Read(discard_buffer, size);\n\t\tif (nbytes < 0)\n\t\t\tthrow NestException(std::make_exception_ptr(MakeErrno(\"Read error\")),\n\t\t\t\t\t WasError(\"read error on WAS data connection\"));\n\n\t\tif (nbytes == 0)\n\t\t\tthrow WasProtocolError(\"server closed the WAS data connection\");\n\n\t\tremaining -= nbytes;\n\t}\n}\n\ninline void\nWasInput::Premature(uint64_t _length) noexcept\n{\n\ttry {\n\t\tPrematureThrow(_length);\n\t} catch (...) {\n\t\t\/* protocol error - notify our WasInputHandler *\/\n\t\thandler.WasInputError();\n\t\tDestroyError(std::current_exception());\n\t\treturn;\n\t}\n\n\t\/* recovery was successful *\/\n\n\t\/* first, release the pipe (which cannot be released\n\t already) *\/\n\tif (!ReleasePipe())\n\t\t\/* WasInputHandler::WasInputRelease() has failed and\n\t\t everything has been cleaned up already *\/\n\t\treturn;\n\n\t\/* pretend this is end-of-file, which will cause the\n\t WasInputHandler to allow reusing the connection *\/\n\thandler.WasInputEof();\n\n\t\/* finall let our IstreamHandler know that the stream was\n\t closed prematurely *\/\n\tDestroyError(std::make_exception_ptr(WasProtocolError(\"premature end of WAS response\")));\n}\n\nvoid\nwas_input_premature(WasInput *input, uint64_t length) noexcept\n{\n\tinput->Premature(length);\n}\n\nvoid\nwas_input_premature_throw(WasInput *input, uint64_t length)\n{\n\tAtScopeExit(input) { input->Destroy(); };\n\tinput->PrematureThrow(length);\n\tthrow WasProtocolError(\"premature end of WAS response\");\n}\n\nvoid\nWasInput::_FillBucketList(IstreamBucketList &list)\n{\n\tauto r = buffer.Read();\n\tif (r.empty()) {\n\t\tif (!HasPipe())\n\t\t\treturn;\n\n\t\ttry {\n\t\t\tReadToBuffer();\n\t\t} catch (...) {\n\t\t\thandler.WasInputError();\n\t\t\tDestroy();\n\t\t\tthrow;\n\t\t}\n\n\t\tif (!CheckReleasePipe()) {\n\t\t\t\/\/ TODO: deal with this condition properly or improve error message\n\t\t\thandler.WasInputError();\n\t\t\tDestroy();\n\t\t\tthrow std::runtime_error(\"WAS peer failed\");\n\t\t}\n\n\t\tr = buffer.Read();\n\t\tif (r.empty()) {\n\t\t\tlist.SetMore();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlist.Push(r.ToVoid());\n\n\tif (!known_length || received < length)\n\t\tlist.SetMore();\n}\n\nsize_t\nWasInput::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t consumed = std::min(buffer.GetAvailable(), nbytes);\n\n\tbuffer.Consume(consumed);\n\tbuffer.FreeIfEmpty();\n\n\treturn Consumed(consumed);\n}\n<commit_msg>was\/Input: allocate buffer after checking EOF<commit_after>\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Input.hxx\"\n#include \"was\/async\/Error.hxx\"\n#include \"event\/PipeEvent.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/Result.hxx\"\n#include \"istream\/Bucket.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"io\/Buffered.hxx\"\n#include \"io\/SpliceSupport.hxx\"\n#include \"system\/Error.hxx\"\n#include \"util\/ScopeExit.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <errno.h>\n#include <string.h>\n#include <unistd.h>\n\nclass WasInput final : Istream {\n\tPipeEvent event;\n\n\tWasInputHandler &handler;\n\n\tSliceFifoBuffer buffer;\n\n\tuint64_t received = 0, length;\n\n\tbool direct = false;\n\n\tbool enabled = false;\n\n\tbool closed = false, known_length = false;\n\npublic:\n\tWasInput(struct pool &p, EventLoop &event_loop, FileDescriptor fd,\n\t\t WasInputHandler &_handler) noexcept\n\t\t:Istream(p),\n\t\t event(event_loop, BIND_THIS_METHOD(EventCallback), fd),\n\t\t handler(_handler) {\n\t}\n\n\tvoid Free(std::exception_ptr ep) noexcept;\n\n\tusing Istream::Destroy;\n\n\tvoid DestroyUnused() noexcept {\n\t\tassert(!HasHandler());\n\t\tassert(!closed);\n\t\tassert(!buffer.IsDefined());\n\n\t\tDestroy();\n\t}\n\n\tUnusedIstreamPtr Enable() noexcept {\n\t\tassert(!enabled);\n\t\tenabled = true;\n\t\tScheduleRead();\n\t\treturn UnusedIstreamPtr(this);\n\t}\n\n\tvoid Disable() noexcept {\n\t\tevent.Cancel();\n\t}\n\n\tbool SetLength(uint64_t _length) noexcept;\n\tvoid PrematureThrow(uint64_t _length);\n\tvoid Premature(uint64_t _length) noexcept;\n\nprivate:\n\tbool HasPipe() const noexcept {\n\t\treturn event.IsDefined();\n\t}\n\n\tFileDescriptor GetPipe() noexcept {\n\t\treturn event.GetFileDescriptor();\n\t}\n\n\tbool CanRelease() const {\n\t\treturn known_length && received == length;\n\t}\n\n\t\/**\n\t * @return false if the #WasInput has been destroyed\n\t *\/\n\tbool ReleasePipe() noexcept {\n\t\tassert(HasPipe());\n\n\t\tevent.Cancel();\n\t\tevent.ReleaseFileDescriptor();\n\n\t\treturn handler.WasInputRelease();\n\t}\n\n\t\/**\n\t * @return false if the #WasInput has been destroyed\n\t *\/\n\tbool CheckReleasePipe() noexcept {\n\t\treturn !CanRelease() || ReleasePipe();\n\t}\n\n\tvoid ScheduleRead() noexcept {\n\t\tassert(HasPipe());\n\t\tassert(!buffer.IsDefined() || !buffer.IsFull());\n\n\t\tevent.ScheduleRead();\n\t}\n\n\tvoid AbortError(std::exception_ptr ep) noexcept {\n\t\tbuffer.FreeIfDefined();\n\t\tevent.Cancel();\n\n\t\t\/* protect against recursive Free() call within the istream\n\t\t handler *\/\n\t\tclosed = true;\n\n\t\thandler.WasInputError();\n\t\tDestroyError(ep);\n\t}\n\n\tvoid AbortError(const char *msg) noexcept {\n\t\tAbortError(std::make_exception_ptr(WasProtocolError(msg)));\n\t}\n\n\tvoid Eof() noexcept {\n\t\tassert(known_length);\n\t\tassert(received == length);\n\t\tassert(!buffer.IsDefined());\n\n\t\tevent.Cancel();\n\n\t\thandler.WasInputEof();\n\t\tDestroyEof();\n\t}\n\n\tbool CheckEof() noexcept {\n\t\tif (CanRelease() && buffer.empty()) {\n\t\t\tEof();\n\t\t\treturn true;\n\t\t} else\n\t\t\treturn false;\n\t}\n\n\t\/**\n\t * Consume data from the input buffer.\n\t *\n\t * @return false if the handler blocks or if this object has been\n\t * destroyed\n\t *\/\n\tbool SubmitBuffer() noexcept {\n\t\tauto r = buffer.Read();\n\t\tif (!r.empty()) {\n\t\t\tsize_t nbytes = InvokeData(r.data, r.size);\n\t\t\tif (nbytes == 0)\n\t\t\t\treturn false;\n\n\t\t\tbuffer.Consume(nbytes);\n\t\t\tbuffer.FreeIfEmpty();\n\t\t}\n\n\t\tif (CheckEof())\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\t\/*\n\t * socket i\/o\n\t *\n\t *\/\n\n\t\/**\n\t * Throws on error.\n\t *\/\n\tvoid ReadToBuffer();\n\n\tbool TryBuffered() noexcept;\n\tbool TryDirect() noexcept;\n\n\tvoid TryRead() noexcept {\n\t\tif (direct) {\n\t\t\tif (SubmitBuffer() && buffer.empty())\n\t\t\t\tTryDirect();\n\t\t} else {\n\t\t\tTryBuffered();\n\t\t}\n\t}\n\n\tvoid EventCallback(unsigned events) noexcept;\n\n\t\/* virtual methods from class Istream *\/\n\n\tvoid _SetDirect(FdTypeMask mask) noexcept override {\n\t\tdirect = (mask & ISTREAM_TO_PIPE) != 0;\n\t}\n\n\toff_t _GetAvailable(bool partial) noexcept override {\n\t\tif (known_length)\n\t\t\treturn length - received + buffer.GetAvailable();\n\t\telse if (partial)\n\t\t\treturn buffer.GetAvailable();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tvoid _Read() noexcept override {\n\t\tif (SubmitBuffer())\n\t\t\tTryRead();\n\t}\n\n\tvoid _FillBucketList(IstreamBucketList &list) override;\n\tsize_t _ConsumeBucketList(size_t nbytes) noexcept override;\n\n\tvoid _Close() noexcept override {\n\t\tbuffer.FreeIfDefined();\n\t\tevent.Cancel();\n\n\t\t\/* protect against recursive Free() call within the istream\n\t\t handler *\/\n\t\tclosed = true;\n\n\t\thandler.WasInputClose(received);\n\n\t\tDestroy();\n\t}\n};\n\nvoid\nWasInput::ReadToBuffer()\n{\n\tsize_t max_length = FB_SIZE;\n\tif (known_length) {\n\t\tuint64_t rest = length - received;\n\t\tif (rest < (uint64_t)max_length)\n\t\t\tmax_length = rest;\n\n\t\tif (max_length == 0)\n\t\t\t\/* all the data we need is already in the buffer *\/\n\t\t\treturn;\n\t}\n\n\tbuffer.AllocateIfNull(fb_pool_get());\n\n\tssize_t nbytes = read_to_buffer(GetPipe().Get(), buffer, max_length);\n\tassert(nbytes != -2);\n\n\tif (nbytes == 0)\n\t\tthrow WasProtocolError(\"server closed the data connection\");\n\n\tif (nbytes < 0) {\n\t\tconst int e = errno;\n\n\t\tif (e == EAGAIN) {\n\t\t\tbuffer.FreeIfEmpty();\n\t\t\tScheduleRead();\n\t\t\treturn;\n\t\t}\n\n\t\tthrow MakeErrno(e, \"read error on WAS data connection\");\n\t}\n\n\treceived += nbytes;\n\n\tif (buffer.IsFull())\n\t\tevent.CancelRead();\n}\n\ninline bool\nWasInput::TryBuffered() noexcept\n{\n\tif (HasPipe()) {\n\t\ttry {\n\t\t\tReadToBuffer();\n\t\t} catch (...) {\n\t\t\tAbortError(std::current_exception());\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!CheckReleasePipe())\n\t\t\treturn false;\n\t}\n\n\tif (SubmitBuffer()) {\n\t\tassert(!buffer.IsDefinedAndFull());\n\n\t\tif (HasPipe())\n\t\t\tScheduleRead();\n\t}\n\n\treturn true;\n}\n\ninline bool\nWasInput::TryDirect() noexcept\n{\n\tassert(buffer.empty());\n\tassert(!buffer.IsDefined());\n\n\tsize_t max_length = 0x1000000;\n\tif (known_length) {\n\t\tuint64_t rest = length - received;\n\t\tif (rest < (uint64_t)max_length)\n\t\t\tmax_length = rest;\n\t}\n\n\tssize_t nbytes = InvokeDirect(FdType::FD_PIPE, GetPipe().Get(), max_length);\n\tif (nbytes == ISTREAM_RESULT_BLOCKING) {\n\t\tevent.CancelRead();\n\t\treturn false;\n\t}\n\n\tif (nbytes == ISTREAM_RESULT_EOF || nbytes == ISTREAM_RESULT_CLOSED)\n\t\treturn false;\n\n\tif (nbytes < 0) {\n\t\tconst int e = errno;\n\n\t\tif (e == EAGAIN) {\n\t\t\tScheduleRead();\n\t\t\treturn false;\n\t\t}\n\n\t\tAbortError(std::make_exception_ptr(MakeErrno(e,\n\t\t\t\t\t\t\t \"read error on WAS data connection\")));\n\t\treturn false;\n\t}\n\n\treceived += nbytes;\n\n\tif (!CheckReleasePipe())\n\t\treturn false;\n\n\tif (CheckEof())\n\t\treturn false;\n\n\tScheduleRead();\n\treturn true;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nWasInput::EventCallback(unsigned) noexcept\n{\n\tassert(HasPipe());\n\n\tTryRead();\n}\n\n\/*\n * constructor\n *\n *\/\n\nWasInput *\nwas_input_new(struct pool &pool, EventLoop &event_loop, FileDescriptor fd,\n\t WasInputHandler &handler) noexcept\n{\n\tassert(fd.IsDefined());\n\n\treturn NewFromPool<WasInput>(pool, pool, event_loop, fd,\n\t\t\t\t handler);\n}\n\ninline void\nWasInput::Free(std::exception_ptr ep) noexcept\n{\n\tassert(ep || closed || !enabled);\n\n\tbuffer.FreeIfDefined();\n\n\tevent.Cancel();\n\n\tif (!closed && enabled)\n\t\tDestroyError(ep);\n}\n\nvoid\nwas_input_free(WasInput *input, std::exception_ptr ep) noexcept\n{\n\tinput->Free(ep);\n}\n\nvoid\nwas_input_free_unused(WasInput *input) noexcept\n{\n\tinput->DestroyUnused();\n}\n\nUnusedIstreamPtr\nwas_input_enable(WasInput &input) noexcept\n{\n\treturn input.Enable();\n}\n\nvoid\nwas_input_disable(WasInput &input) noexcept\n{\n\tinput.Disable();\n}\n\ninline bool\nWasInput::SetLength(uint64_t _length) noexcept\n{\n\tif (known_length) {\n\t\tif (_length == length)\n\t\t\treturn true;\n\n\t\t\/\/ TODO: don't invoke Istream::DestroyError() if not yet enabled\n\t\tAbortError(\"wrong input length announced\");\n\t\treturn false;\n\t}\n\n\tif (_length < received) {\n\t\t\/* this length must be bogus, because we already received more than that from the socket *\/\n\t\tAbortError(\"announced length is too small\");\n\t\treturn false;\n\t}\n\n\tlength = _length;\n\tknown_length = true;\n\n\tif (!CheckReleasePipe())\n\t\treturn false;\n\n\tif (enabled && CheckEof())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool\nwas_input_set_length(WasInput *input, uint64_t length) noexcept\n{\n\treturn input->SetLength(length);\n}\n\nvoid\nWasInput::PrematureThrow(uint64_t _length)\n{\n\tbuffer.FreeIfDefined();\n\tevent.Cancel();\n\n\tif (known_length && _length > length)\n\t\tthrow WasProtocolError(\"announced premature length is too large\");\n\n\tif (_length < received)\n\t\tthrow WasProtocolError(\"announced premature length is too small\");\n\n\tuint64_t remaining = _length - received;\n\n\twhile (remaining > 0) {\n\t\tuint8_t discard_buffer[4096];\n\t\tsize_t size = std::min(remaining, uint64_t(sizeof(discard_buffer)));\n\t\tssize_t nbytes = GetPipe().Read(discard_buffer, size);\n\t\tif (nbytes < 0)\n\t\t\tthrow NestException(std::make_exception_ptr(MakeErrno(\"Read error\")),\n\t\t\t\t\t WasError(\"read error on WAS data connection\"));\n\n\t\tif (nbytes == 0)\n\t\t\tthrow WasProtocolError(\"server closed the WAS data connection\");\n\n\t\tremaining -= nbytes;\n\t}\n}\n\ninline void\nWasInput::Premature(uint64_t _length) noexcept\n{\n\ttry {\n\t\tPrematureThrow(_length);\n\t} catch (...) {\n\t\t\/* protocol error - notify our WasInputHandler *\/\n\t\thandler.WasInputError();\n\t\tDestroyError(std::current_exception());\n\t\treturn;\n\t}\n\n\t\/* recovery was successful *\/\n\n\t\/* first, release the pipe (which cannot be released\n\t already) *\/\n\tif (!ReleasePipe())\n\t\t\/* WasInputHandler::WasInputRelease() has failed and\n\t\t everything has been cleaned up already *\/\n\t\treturn;\n\n\t\/* pretend this is end-of-file, which will cause the\n\t WasInputHandler to allow reusing the connection *\/\n\thandler.WasInputEof();\n\n\t\/* finall let our IstreamHandler know that the stream was\n\t closed prematurely *\/\n\tDestroyError(std::make_exception_ptr(WasProtocolError(\"premature end of WAS response\")));\n}\n\nvoid\nwas_input_premature(WasInput *input, uint64_t length) noexcept\n{\n\tinput->Premature(length);\n}\n\nvoid\nwas_input_premature_throw(WasInput *input, uint64_t length)\n{\n\tAtScopeExit(input) { input->Destroy(); };\n\tinput->PrematureThrow(length);\n\tthrow WasProtocolError(\"premature end of WAS response\");\n}\n\nvoid\nWasInput::_FillBucketList(IstreamBucketList &list)\n{\n\tauto r = buffer.Read();\n\tif (r.empty()) {\n\t\tif (!HasPipe())\n\t\t\treturn;\n\n\t\ttry {\n\t\t\tReadToBuffer();\n\t\t} catch (...) {\n\t\t\thandler.WasInputError();\n\t\t\tDestroy();\n\t\t\tthrow;\n\t\t}\n\n\t\tif (!CheckReleasePipe()) {\n\t\t\t\/\/ TODO: deal with this condition properly or improve error message\n\t\t\thandler.WasInputError();\n\t\t\tDestroy();\n\t\t\tthrow std::runtime_error(\"WAS peer failed\");\n\t\t}\n\n\t\tr = buffer.Read();\n\t\tif (r.empty()) {\n\t\t\tlist.SetMore();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tlist.Push(r.ToVoid());\n\n\tif (!known_length || received < length)\n\t\tlist.SetMore();\n}\n\nsize_t\nWasInput::_ConsumeBucketList(size_t nbytes) noexcept\n{\n\tsize_t consumed = std::min(buffer.GetAvailable(), nbytes);\n\n\tbuffer.Consume(consumed);\n\tbuffer.FreeIfEmpty();\n\n\treturn Consumed(consumed);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 Jolla Mobile. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webwindow.h\"\n\n#include <QDebug>\n#include <QOpenGLContext>\n#include <QOpenGLFunctions>\n#include <QResizeEvent>\n#include <QThread>\n\n#include \"webview.h\"\n\nWebWindow::WebWindow(QWindow* parent)\n : QWindow(parent)\n , web_view_(nullptr)\n , clear_surface_task_(nullptr) {\n setSurfaceType(QWindow::OpenGLSurface);\n QSurfaceFormat format(requestedFormat());\n format.setAlphaBufferSize(0);\n setFormat(format);\n create();\n}\n\nWebWindow::~WebWindow() {\n QMutexLocker lock(&clear_surface_task_mutex_);\n if (clear_surface_task_) {\n QMozContext::GetInstance()->CancelTask(clear_surface_task_);\n }\n}\n\nvoid\nWebWindow::SetActiveWebView(WebView* wv) {\n if (web_view_ && wv == web_view_) {\n qWarning() << \"Tryig to activate already active webview\";\n return;\n }\n\n if (web_view_ && web_view_ != wv) {\n disconnect(web_view_, &WebView::titleChanged,\n this, &WebWindow::OnTitleChanged);\n web_view_->setActive(false);\n }\n\n web_view_ = wv;\n\n if (web_view_) {\n web_view_->setActive(true);\n web_view_->update();\n\n connect(web_view_, &WebView::titleChanged,\n this, &WebWindow::OnTitleChanged);\n\n web_view_->setSize(QSizeF(width(), height()));\n web_view_->updateContentOrientation(Qt::PortraitOrientation);\n } else {\n ClearWindowSurface();\n }\n}\n\nQOpenGLContext*\nWebWindow::GLContext() const {\n static QOpenGLContext* context = nullptr;\n if (!context) {\n context = new QOpenGLContext();\n context->setFormat(requestedFormat());\n if (!context->create())\n qFatal(\"Failed to create QOpenGLContext!\");\n }\n return context;\n}\n\nbool\nWebWindow::ClearWindowSurface() {\n QMutexLocker lock(&clear_surface_task_mutex_);\n if (clear_surface_task_) {\n return true;\n }\n clear_surface_task_ = QMozContext::GetInstance()->PostCompositorTask(\n &WebWindow::ClearWindowSurfaceImpl, this);\n return clear_surface_task_ != 0;\n}\n\nvoid\nWebWindow::resizeEvent(QResizeEvent* evt) {\n if (web_view_) {\n web_view_->setSize(evt->size());\n web_view_->updateContentOrientation(Qt::PortraitOrientation);\n }\n}\n\nvoid\nWebWindow::focusInEvent(QFocusEvent* evt) {\n if (web_view_)\n web_view_->focusInEvent(evt);\n}\n\nvoid\nWebWindow::focusOutEvent(QFocusEvent* evt) {\n if (web_view_)\n web_view_->focusOutEvent(evt);\n}\n\nvoid\nWebWindow::touchEvent(QTouchEvent* evt) {\n if (web_view_)\n web_view_->touchEvent(evt);\n}\n\nvoid\nWebWindow::mouseMoveEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::mousePressEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::mouseReleaseEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::keyPressEvent(QKeyEvent* evt) {\n if (web_view_)\n web_view_->keyPressEvent(evt);\n}\n\nvoid\nWebWindow::keyReleaseEvent(QKeyEvent* evt) {\n if (web_view_)\n web_view_->keyReleaseEvent(evt);\n}\n\nvoid\nWebWindow::exposeEvent(QExposeEvent*) {\n if (QWindow::isExposed()) {\n if (web_view_) {\n web_view_->update();\n } else {\n ClearWindowSurface();\n }\n }\n}\n\nvoid\nWebWindow::OnTitleChanged() {\n Q_ASSERT(web_view_);\n setTitle(web_view_->title());\n}\n\nvoid\nWebWindow::ClearWindowSurfaceImpl(void* data) {\n WebWindow* ww = static_cast<WebWindow*>(data);\n QMutexLocker lock(&ww->clear_surface_task_mutex_);\n\n QOpenGLContext* context = ww->GLContext();\n \/\/ The GL context should always be used from the same thread in which it was created.\n Q_ASSERT(context->thread() == QThread::currentThread());\n context->makeCurrent(ww);\n QOpenGLFunctions* funcs = context->functions();\n Q_ASSERT(funcs);\n funcs->glClearColor(1.0, 1.0, 1.0, 0.0);\n funcs->glClear(GL_COLOR_BUFFER_BIT);\n context->swapBuffers(ww);\n\n ww->clear_surface_task_ = 0;\n}\n<commit_msg>Reset GL scissor box before clearing the compositing surface.<commit_after>\/\/ Copyright (c) 2015 Jolla Mobile. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webwindow.h\"\n\n#include <QDebug>\n#include <QOpenGLContext>\n#include <QOpenGLFunctions>\n#include <QResizeEvent>\n#include <QThread>\n\n#include \"webview.h\"\n\nWebWindow::WebWindow(QWindow* parent)\n : QWindow(parent)\n , web_view_(nullptr)\n , clear_surface_task_(nullptr) {\n setSurfaceType(QWindow::OpenGLSurface);\n QSurfaceFormat format(requestedFormat());\n format.setAlphaBufferSize(0);\n setFormat(format);\n create();\n}\n\nWebWindow::~WebWindow() {\n QMutexLocker lock(&clear_surface_task_mutex_);\n if (clear_surface_task_) {\n QMozContext::GetInstance()->CancelTask(clear_surface_task_);\n }\n}\n\nvoid\nWebWindow::SetActiveWebView(WebView* wv) {\n if (web_view_ && wv == web_view_) {\n qWarning() << \"Tryig to activate already active webview\";\n return;\n }\n\n if (web_view_ && web_view_ != wv) {\n disconnect(web_view_, &WebView::titleChanged,\n this, &WebWindow::OnTitleChanged);\n web_view_->setActive(false);\n }\n\n web_view_ = wv;\n\n if (web_view_) {\n web_view_->setActive(true);\n web_view_->update();\n\n connect(web_view_, &WebView::titleChanged,\n this, &WebWindow::OnTitleChanged);\n\n web_view_->setSize(QSizeF(width(), height()));\n web_view_->updateContentOrientation(Qt::PortraitOrientation);\n } else {\n ClearWindowSurface();\n }\n}\n\nQOpenGLContext*\nWebWindow::GLContext() const {\n static QOpenGLContext* context = nullptr;\n if (!context) {\n context = new QOpenGLContext();\n context->setFormat(requestedFormat());\n if (!context->create())\n qFatal(\"Failed to create QOpenGLContext!\");\n }\n return context;\n}\n\nbool\nWebWindow::ClearWindowSurface() {\n QMutexLocker lock(&clear_surface_task_mutex_);\n if (clear_surface_task_) {\n return true;\n }\n clear_surface_task_ = QMozContext::GetInstance()->PostCompositorTask(\n &WebWindow::ClearWindowSurfaceImpl, this);\n return clear_surface_task_ != 0;\n}\n\nvoid\nWebWindow::resizeEvent(QResizeEvent* evt) {\n if (web_view_) {\n web_view_->setSize(evt->size());\n web_view_->updateContentOrientation(Qt::PortraitOrientation);\n }\n}\n\nvoid\nWebWindow::focusInEvent(QFocusEvent* evt) {\n if (web_view_)\n web_view_->focusInEvent(evt);\n}\n\nvoid\nWebWindow::focusOutEvent(QFocusEvent* evt) {\n if (web_view_)\n web_view_->focusOutEvent(evt);\n}\n\nvoid\nWebWindow::touchEvent(QTouchEvent* evt) {\n if (web_view_)\n web_view_->touchEvent(evt);\n}\n\nvoid\nWebWindow::mouseMoveEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::mousePressEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::mouseReleaseEvent(QMouseEvent* evt) {\n \/\/ Let Qt synthesize touch event\n evt->ignore();\n}\n\nvoid\nWebWindow::keyPressEvent(QKeyEvent* evt) {\n if (web_view_)\n web_view_->keyPressEvent(evt);\n}\n\nvoid\nWebWindow::keyReleaseEvent(QKeyEvent* evt) {\n if (web_view_)\n web_view_->keyReleaseEvent(evt);\n}\n\nvoid\nWebWindow::exposeEvent(QExposeEvent*) {\n if (QWindow::isExposed()) {\n if (web_view_) {\n web_view_->update();\n } else {\n ClearWindowSurface();\n }\n }\n}\n\nvoid\nWebWindow::OnTitleChanged() {\n Q_ASSERT(web_view_);\n setTitle(web_view_->title());\n}\n\nvoid\nWebWindow::ClearWindowSurfaceImpl(void* data) {\n WebWindow* ww = static_cast<WebWindow*>(data);\n QMutexLocker lock(&ww->clear_surface_task_mutex_);\n\n QOpenGLContext* context = ww->GLContext();\n \/\/ The GL context should always be used from the same thread in which it was created.\n Q_ASSERT(context->thread() == QThread::currentThread());\n context->makeCurrent(ww);\n QOpenGLFunctions* funcs = context->functions();\n Q_ASSERT(funcs);\n funcs->glScissor(0, 0, ww->width(), ww->height());\n funcs->glClearColor(1.0, 1.0, 1.0, 0.0);\n funcs->glClear(GL_COLOR_BUFFER_BIT);\n context->swapBuffers(ww);\n\n ww->clear_surface_task_ = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"minilzo209\/minilzo.h\"\n\n#include <node.h>\n#include <v8.h>\n#include <sstream>\n\n#include <node_buffer.h>\n\nusing namespace v8;\n\nint compress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {\n char* wrkmem = (char*) malloc(LZO1X_1_MEM_COMPRESS);\n\n int result = lzo1x_1_compress(input, in_len, output, &out_len, wrkmem);\n\n free(wrkmem);\n\n return result;\n}\n\nlzo_uint decompress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {\n int r = lzo1x_decompress_safe(input, in_len, output, &out_len, NULL);\n\n if (r == LZO_E_OK)\n return out_len;\n else\n return r;\n}\n\nvoid js_compress(const v8::FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n HandleScope scope(isolate);\n\n Handle<Object> inputBuffer = args[0]->ToObject();\n Handle<Object> outputBuffer = args[1]->ToObject();\n\n lzo_uint input_len = node::Buffer::Length(inputBuffer);\n lzo_uint output_len = node::Buffer::Length(outputBuffer);\n\n int result = compress( (unsigned char *) node::Buffer::Data(inputBuffer),\n (unsigned char *) node::Buffer::Data(outputBuffer),\n input_len,\n output_len );\n\n Local<Object> ret = Object::New(isolate);\n\n ret->Set(String::NewFromUtf8(isolate, \"err\"),\n Number::New(isolate, result));\n\n ret->Set(String::NewFromUtf8(isolate, \"len\"),\n Number::New(isolate, (int) output_len) );\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid js_decompress(const v8::FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n HandleScope scope(isolate);\n\n Handle<Object> inputBuffer = args[0]->ToObject();\n Handle<Object> outputBuffer = args[1]->ToObject();\n\n lzo_uint input_len = node::Buffer::Length(inputBuffer);\n lzo_uint output_len = node::Buffer::Length(outputBuffer);\n\n lzo_uint len = decompress( (unsigned char *) node::Buffer::Data(inputBuffer),\n (unsigned char *) node::Buffer::Data(outputBuffer),\n input_len,\n output_len);\n\n int err = (int) len < 0 ? (int) len : 0;\n\n Local<Object> ret = Object::New(isolate);\n\n ret->Set(String::NewFromUtf8(isolate, \"err\"),\n Number::New(isolate, err));\n\n ret->Set(String::NewFromUtf8(isolate, \"len\"),\n Number::New(isolate, (int) len) );\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid Init(Local<Object> exports, Local<Context> context) {\n Isolate* isolate = context->GetIsolate();\n\n int init_result = lzo_init();\n\n if(init_result != LZO_E_OK) {\n std::stringstream ss;\n\n ss << \"lzo_init() failed and returned `\" << init_result << \"`. \";\n ss << \"Please report this on GitHub: https:\/\/github.com\/schroffl\/node-lzo\/issues\";\n\n Local<String> err = String::NewFromUtf8(isolate, ss.str().c_str());\n\n isolate->ThrowException(Exception::Error(err));\n\n return;\n }\n\n \/\/ Compression\n exports->Set(String::NewFromUtf8(isolate, \"compress\"),\n FunctionTemplate::New(isolate, js_compress)->GetFunction());\n\n \/\/ Decompression\n exports->Set(String::NewFromUtf8(isolate, \"decompress\"),\n FunctionTemplate::New(isolate, js_decompress)->GetFunction());\n\n \/\/ Current lzo version\n exports->Set(String::NewFromUtf8(isolate, \"version\"),\n String::NewFromUtf8(isolate, lzo_version_string()));\n\n \/\/ Date for current lzo version\n exports->Set(String::NewFromUtf8(isolate, \"versionDate\"),\n String::NewFromUtf8(isolate, lzo_version_date()));\n}\n\n#if NODE_MAJOR_VERSION >= 10 && NODE_MINOR_VERSION >= 7\n \/\/ Initialize this addon to be context-aware. See Issue #11\n NODE_MODULE_INIT(\/* exports, module, context *\/) {\n Init(exports, context);\n }\n#else\n \/\/ For backwards compatibility. See Issue #13\n NODE_MODULE(node_lzo, Init)\n#endif\n<commit_msg>Fix #14 - Allows the library to be built with Node v12.x<commit_after>#include \"minilzo209\/minilzo.h\"\n\n#include <node.h>\n#include <v8.h>\n#include <sstream>\n\n#include <node_buffer.h>\n\n#define GET_FUNCTION(A, B, C) FunctionTemplate::New(A, B)->GetFunction()\n#define MAKE_STRING(A, B) String::NewFromUtf8(A, B)\n\n#if NODE_MAJOR_VERSION >= 12\n#define NODE_12\n\n#undef GET_FUNCTION\n#define GET_FUNCTION(A, B, C) FunctionTemplate::New(A, B)->GetFunction(C).ToLocalChecked()\n\n#undef MAKE_STRING\n#define MAKE_STRING(A, B) String::NewFromUtf8(A, B, NewStringType::kNormal).ToLocalChecked()\n#endif\n\n#define NEW_API (NODE_MAJOR_VERSION >= 10)\n\nusing namespace v8;\n\nint compress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {\n char* wrkmem = (char*) malloc(LZO1X_1_MEM_COMPRESS);\n\n int result = lzo1x_1_compress(input, in_len, output, &out_len, wrkmem);\n\n free(wrkmem);\n\n return result;\n}\n\nlzo_uint decompress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {\n int r = lzo1x_decompress_safe(input, in_len, output, &out_len, NULL);\n\n if (r == LZO_E_OK)\n return out_len;\n else\n return r;\n}\n\nvoid js_compress(const v8::FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n HandleScope scope(isolate);\n\n#if NEW_API\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> inputBuffer = args[0]->ToObject(context).ToLocalChecked();\n Local<Object> outputBuffer = args[1]->ToObject(context).ToLocalChecked();\n#else\n Handle<Object> inputBuffer = args[0]->ToObject();\n Handle<Object> outputBuffer = args[1]->ToObject();\n#endif\n\n lzo_uint input_len = node::Buffer::Length(inputBuffer);\n lzo_uint output_len = node::Buffer::Length(outputBuffer);\n\n int result = compress( (unsigned char *) node::Buffer::Data(inputBuffer),\n (unsigned char *) node::Buffer::Data(outputBuffer),\n input_len,\n output_len );\n\n Local<Object> ret = Object::New(isolate);\n\n#ifdef NODE_12\n (void) ret->Set(context, MAKE_STRING(isolate, \"err\"), Number::New(isolate, result));\n (void) ret->Set(context, MAKE_STRING(isolate, \"len\"), Number::New(isolate, (int) output_len));\n#else\n ret->Set(MAKE_STRING(isolate, \"err\"), Number::New(isolate, result));\n ret->Set(MAKE_STRING(isolate, \"len\"), Number::New(isolate, (int) output_len));\n#endif\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid js_decompress(const v8::FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n HandleScope scope(isolate);\n\n#if NEW_API\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> inputBuffer = args[0]->ToObject(context).ToLocalChecked();\n Local<Object> outputBuffer = args[1]->ToObject(context).ToLocalChecked();\n#else\n Handle<Object> inputBuffer = args[0]->ToObject();\n Handle<Object> outputBuffer = args[1]->ToObject();\n#endif\n\n lzo_uint input_len = node::Buffer::Length(inputBuffer);\n lzo_uint output_len = node::Buffer::Length(outputBuffer);\n\n lzo_uint len = decompress( (unsigned char *) node::Buffer::Data(inputBuffer),\n (unsigned char *) node::Buffer::Data(outputBuffer),\n input_len,\n output_len);\n\n int err = (int) len < 0 ? (int) len : 0;\n\n Local<Object> ret = Object::New(isolate);\n\n#ifdef NODE_12\n (void) ret->Set(context, MAKE_STRING(isolate, \"err\"), Number::New(isolate, err));\n (void) ret->Set(context, MAKE_STRING(isolate, \"len\"), Number::New(isolate, (int) len) );\n#else\n ret->Set(MAKE_STRING(isolate, \"err\"), Number::New(isolate, err));\n ret->Set(MAKE_STRING(isolate, \"len\"), Number::New(isolate, (int) len) );\n#endif\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid Init(Local<Object> exports, Local<Context> context) {\n Isolate* isolate = context->GetIsolate();\n\n int init_result = lzo_init();\n\n if(init_result != LZO_E_OK) {\n std::stringstream ss;\n\n ss << \"lzo_init() failed and returned `\" << init_result << \"`. \";\n ss << \"Please report this on GitHub: https:\/\/github.com\/schroffl\/node-lzo\/issues\";\n\n Local<String> err = MAKE_STRING(isolate, ss.str().c_str());\n\n isolate->ThrowException(Exception::Error(err));\n\n return;\n }\n\n \/\/ Compression\n (void) exports->Set(\n context,\n MAKE_STRING(isolate, \"compress\"),\n GET_FUNCTION(isolate, js_compress, context)\n );\n\n \/\/ Decompression\n (void) exports->Set(\n context,\n MAKE_STRING(isolate, \"decompress\"),\n GET_FUNCTION(isolate, js_decompress, context)\n );\n\n \/\/ Current lzo version\n const char *version = lzo_version_string();\n (void) exports->Set(\n context,\n MAKE_STRING(isolate, \"version\"),\n MAKE_STRING(isolate, version)\n );\n\n \/\/ Date for current lzo version\n const char *date = lzo_version_date();\n (void) exports->Set(\n context,\n MAKE_STRING(isolate, \"versionDate\"),\n MAKE_STRING(isolate, date)\n );\n}\n\n#if (NODE_MAJOR_VERSION >= 10 && NODE_MINOR_VERSION >= 7) || NODE_MAJOR_VERSION >= 11\n \/\/ Initialize this addon to be context-aware. See Issue #11\n NODE_MODULE_INIT(\/* exports, module, context *\/) {\n Init(exports, context);\n }\n#else\n \/\/ For backwards compatibility. See Issue #13\n NODE_MODULE(node_lzo, Init)\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n#include <stdlib.h>\n#include <string>\n\n#include \"number.h\"\n\nnamespace rtl {\n\nstd::string os$getenv(const std::string &name)\n{\n return getenv(name.c_str());\n}\n\nNumber os$system(const std::string &command)\n{\n return number_from_sint32(system(command.c_str()));\n}\n\n}\n<commit_msg>Change slashes to backslashes in os.system() on Windows<commit_after>#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n#include <ctype.h>\n#include <iso646.h>\n#include <stdlib.h>\n#include <string>\n\n#include \"number.h\"\n\nnamespace rtl {\n\nstd::string os$getenv(const std::string &name)\n{\n return getenv(name.c_str());\n}\n\nNumber os$system(const std::string &command)\n{\n std::string cmd = command;\n#ifdef _WIN32\n \/\/ Terrible hack to change slashes to backslashes so cmd.exe isn't confused.\n \/\/ Probably better handled by calling a lower level function than system().\n for (std::string::iterator i = cmd.begin(); not isspace(*i); ++i) {\n if (*i == '\/') {\n *i = '\\\\';\n }\n }\n#endif\n return number_from_sint32(system(cmd.c_str()));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013 midnightBITS\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"pch.h\"\n#include <sstream>\n#include <wiki.hpp>\n#include <filesystem.hpp>\n#include \"wiki_parser.hpp\"\n#include \"wiki_nodes.hpp\"\n#include <iomanip>\n#include <fcntl.h>\n\n#ifdef _WIN32\n#include <process.h>\n#include <io.h>\n#else\n#include <unistd.h>\n#define _getpid getpid\n#endif\n\nnamespace wiki\n{\n\tstruct compiler\n\t{\n\t\tusing Token = parser::Token;\n\t\tusing Tokens = parser::line::Tokens;\n\t\tusing Block = parser::Parser::Block;\n\t\tusing Blocks = parser::Parser::Text;\n\n\t\tstruct by_token\n\t\t{\n\t\t\tTOKEN end_tok;\n\t\t\tby_token(TOKEN end_tok)\n\t\t\t\t: end_tok(end_tok)\n\t\t\t{}\n\n\t\t\tbool reached(Tokens::const_iterator cur)\n\t\t\t{\n\t\t\t\treturn cur->type == end_tok;\n\t\t\t}\n\t\t};\n\n\t\tstruct by_argument\n\t\t{\n\t\t\tTOKEN end_tok;\n\t\t\tstd::string arg;\n\t\t\tby_argument(TOKEN end_tok, std::string&& arg)\n\t\t\t\t: end_tok(end_tok)\n\t\t\t\t, arg(std::move(arg))\n\t\t\t{}\n\n\t\t\tbool reached(Tokens::const_iterator cur)\n\t\t\t{\n\t\t\t\treturn cur->type == end_tok && arg == cur->arg.str();\n\t\t\t}\n\t\t};\n\n\t\ttemplate <typename Final, typename Right = by_token>\n\t\tstruct scanner: Right\n\t\t{\n\t\t\tTokens::const_iterator from, to;\n\n\t\t\ttemplate <typename... Args>\n\t\t\tscanner(Tokens::const_iterator from, Tokens::const_iterator to, Args&&... args)\n\t\t\t\t: Right(std::forward<Args>(args)...)\n\t\t\t\t, from(from)\n\t\t\t\t, to(to)\n\t\t\t{}\n\n\t\t\tTokens::const_iterator scan()\n\t\t\t{\n\t\t\t\tNodes children;\n\n\t\t\t\t++from;\n\t\t\t\tfrom = compile(children, from, to, Right::end_tok, false);\n\t\t\t\tif (from != to && Right::reached(from))\n\t\t\t\t\tstatic_cast<Final*>(this)->visit(children);\n\n\t\t\t\treturn from;\n\t\t\t}\n\t\t};\n\n\t\ttemplate <typename Final>\n\t\tusing arg_scanner = scanner<Final, by_argument>;\n\n\t\tstruct items\n\t\t{\n\t\t\tNodes& m_items;\n\n\t\t\titems(Nodes& _items) : m_items(_items) {}\n\t\t};\n\n\t\tstruct variable : scanner<variable>, items\n\t\t{\n\t\t\tvariable(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to) : scanner<variable>(from, to, TOKEN::VAR_E), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Variable>(m_items, text(children));\n\t\t\t}\n\t\t};\n\n\t\tstruct link : scanner<link>, items\n\t\t{\n\t\t\tlink(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to) : scanner<link>(from, to, TOKEN::HREF_E), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Link>(m_items, children)->normalize();\n\t\t\t}\n\t\t};\n\n\t\tstruct element : arg_scanner<element>, items\n\t\t{\n\t\t\telement(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to, std::string&& arg) : arg_scanner<element>(from, to, TOKEN::TAG_E, std::move(arg)), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Element>(m_items, arg, children);\n\t\t\t}\n\t\t};\n\n\t\tstatic inline Nodes compile(const Tokens& tokens, bool pre);\n\t\tstatic inline Tokens::const_iterator compile(Nodes& children, Tokens::const_iterator begin, Tokens::const_iterator end, TOKEN endtok, bool pre);\n\t\tstatic inline NodePtr compile(const Block& block, bool pre);\n\t\tstatic inline void compile(Nodes& children, const Blocks& blocks, bool pre);\n\t\tstatic inline std::string text(const Nodes& nodes);\n\t\ttemplate <typename Class, typename... Args>\n\t\tstatic inline std::shared_ptr<Class> make_node(Nodes& items, Args&&... args)\n\t\t{\n\t\t\tauto elem = std::make_shared<Class>(std::forward<Args>(args)...);\n\t\t\titems.push_back(elem);\n\t\t\treturn elem;\n\t\t}\n\t\ttemplate <typename Class, typename... Args>\n\t\tstatic inline std::shared_ptr<Class> make_block(Args&&... args)\n\t\t{\n\t\t\treturn std::make_shared<Class>(std::forward<Args>(args)...);\n\t\t}\n\t};\n\n\tclass Document : public document\n\t{\n\t\tNodes m_children;\n\tpublic:\n\t\tDocument(const Nodes& children) : m_children(children) {}\n\t\tvoid text(stream& o, const variables_t& vars, list_ctx& ctx) const override\n\t\t{\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->text(o, vars, ctx);\n\t\t}\n\n\t\tvoid markup(stream& o, const variables_t& vars, const styler_ptr& styler, list_ctx& ctx) const override\n\t\t{\n\t\t\tstyler->begin_document(o);\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->markup(o, vars, styler, ctx);\n\t\t\tstyler->end_document(o);\n\t\t}\n\n\t\tvoid debug(stream& o) const override\n\t\t{\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->debug(o);\n\t\t}\n\n\t\tvoid store(const filesystem::path& obj)\n\t\t{\n\t\t\tbinary::Writer wr;\n\t\t\tif (!wr.open(obj))\n\t\t\t\treturn;\n\n\t\t\tif (!wr.store(m_children) || !wr.close())\n\t\t\t\tfilesystem::remove(obj);\n\t\t}\n\t};\n\n\t\/* public: *\/\n\n\tvoid cstream::write(const char* buffer, size_t size)\n\t{\n\t\tref.write(buffer, size);\n\t}\n\n\tdocument_ptr compile(const filesystem::path& file, const filesystem::path& obj)\n\t{\n\t\tfilesystem::status st{ file };\n\t\tif (!st.exists())\n\t\t\treturn nullptr;\n\n\t\tif (st.mtime() <= filesystem::status{ obj }.mtime())\n\t\t{\n\t\t\tbinary::Reader r;\n\t\t\tif (r.open(obj))\n\t\t\t{\n\t\t\t\tNodes children;\n\t\t\t\tif (r.load(children))\n\t\t\t\t\treturn std::make_shared<Document>(children);\n\t\t\t}\n\t\t}\n\n\t\tsize_t size = (size_t)st.file_size();\n\n\t\tstd::string text;\n\t\ttext.resize(size + 1);\n\t\tif (text.size() <= size)\n\t\t\treturn nullptr;\n\n\t\tauto f = fopen(file.native().c_str(), \"r\");\n\t\tif (!f)\n\t\t\treturn nullptr;\n\t\tfread(&text[0], 1, size, f);\n\t\tfclose(f);\n\n\t\ttext[size] = 0;\n\n\t\tdocument_ptr out = compile(text);\n\t\tstd::static_pointer_cast<Document>(out)->store(obj);\n\t\treturn out;\n\t}\n\n\tdocument_ptr compile(const filesystem::path& file)\n\t{\n\t\tfilesystem::status st{ file };\n\t\tif (!st.exists())\n\t\t\treturn nullptr;\n\n\t\tsize_t size = (size_t)st.file_size();\n\n\t\tstd::string text;\n\t\ttext.resize(size + 1);\n\t\tif (text.size() <= size)\n\t\t\treturn nullptr;\n\n\t\tauto f = fopen(file.native().c_str(), \"r\");\n\t\tif (!f)\n\t\t\treturn nullptr;\n\t\tfread(&text[0], 1, size, f);\n\t\tfclose(f);\n\n\t\ttext[size] = 0;\n\t\treturn compile(text);\n\t}\n\n\tdocument_ptr compile(const std::string& text)\n\t{\n\t\tauto blocks = parser::Parser{}.parse(text);\n\n\t\tNodes children;\n\t\tcompiler::compile(children, blocks, false);\n\t\treturn std::make_shared<Document>(children);\n\t}\n\n\t\/* private: *\/\n\tNodes compiler::compile(const parser::line::Tokens& tokens, bool pre)\n\t{\n\t\tNodes list;\n\t\tcompile(list, tokens.begin(), tokens.end(), TOKEN::BAD, pre);\n\t\treturn list;\n\t}\n\n\tcompiler::Tokens::const_iterator compiler::compile(Nodes& items, Tokens::const_iterator begin, Tokens::const_iterator end, TOKEN endtok, bool pre)\n\t{\n\t\tstd::shared_ptr<inline_elem::Text> text;\n\t\tstd::shared_ptr<Node> elem;\n\n\t\tauto cur = begin;\n\t\tfor (; cur != end; ++cur)\n\t\t{\n\t\t\tif (cur->type == endtok)\n\t\t\t\treturn cur;\n\n\t\t\tif (cur->type != TOKEN::TEXT)\n\t\t\t\ttext = nullptr;\n\n\t\t\tNodes children;\n\n\t\t\tauto&& token = *cur;\n\t\t\tswitch (token.type)\n\t\t\t{\n\t\t\tcase TOKEN::TEXT:\n\t\t\t\tif (text)\n\t\t\t\t\ttext->append(token.arg.begin(), token.arg.end());\n\t\t\t\telse\n\t\t\t\t\ttext = make_node<inline_elem::Text>(items, token.arg.str());\n\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::BREAK:\n\t\t\t\tmake_node<inline_elem::Break>(items);\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::LINE:\n\t\t\t\tmake_node<inline_elem::Line>(items);\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::TAG_S:\n\t\t\t\tcur = element{ items, cur, end, token.arg.str() }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::VAR_S:\n\t\t\t\tcur = variable{ items, cur, end }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::HREF_S:\n\t\t\t\tcur = link{ items, cur, end }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::HREF_NS:\n\t\t\tcase TOKEN::HREF_SEG:\n\t\t\t\tmake_node<inline_elem::Token>(items, token.type);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (cur == end)\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn cur;\n\t}\n\n\tvoid compiler::compile(Nodes& children, const parser::Parser::Text& blocks, bool pre)\n\t{\n\t\tfor (auto&& block : blocks)\n\t\t{\n\t\t\tauto child = compile(block, pre);\n\t\t\tif (child)\n\t\t\t\tchildren.push_back(child);\n\t\t}\n\t}\n\n\tNodePtr compiler::compile(const parser::Parser::Block& block, bool pre)\n\t{\n\t\tusing BLOCK = parser::Parser::BLOCK;\n\n\t\tif (!pre)\n\t\t\tpre = block.type == BLOCK::PRE;\n\t\tauto children = compile(block.tokens, pre);\n\t\tcompile(children, block.items, pre);\n\n\t\tswitch (block.type)\n\t\t{\n\t\tcase BLOCK::HEADER: return make_block<block_elem::Header>(block.iArg, children);\n\t\tcase BLOCK::PARA: return make_block<block_elem::Para>(children);\n\t\tcase BLOCK::QUOTE: return make_block<block_elem::Quote>(children);\n\t\tcase BLOCK::PRE: return make_block<block_elem::Pre>(children);\n\t\tcase BLOCK::UL: return make_block<block_elem::UList>(children);\n\t\tcase BLOCK::OL: return make_block<block_elem::OList>(children);\n\t\tcase BLOCK::ITEM: return make_block<block_elem::Item>(children);\n\t\tcase BLOCK::HR: return make_block<block_elem::HR>();\n\t\tcase BLOCK::SIGNATURE: return make_block<block_elem::Signature>(children);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tstd::string compiler::text(const Nodes& nodes)\n\t{\n\t\tstd::ostringstream o;\n\t\tcstream co{ o };\n\t\tvariables_t vars;\n\t\tlist_ctx ctx;\n\t\tfor (auto&& node : nodes)\n\t\t\tnode->text(co, vars, ctx);\n\t\treturn o.str();\n\t}\n}\n<commit_msg>COmpilation issue with GCC high optimalisation<commit_after>\/*\n * Copyright (C) 2013 midnightBITS\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"pch.h\"\n#include <sstream>\n#include <wiki.hpp>\n#include <filesystem.hpp>\n#include \"wiki_parser.hpp\"\n#include \"wiki_nodes.hpp\"\n#include <iomanip>\n#include <fcntl.h>\n\n#ifdef _WIN32\n#include <process.h>\n#include <io.h>\n#else\n#include <unistd.h>\n#define _getpid getpid\n#endif\n\nnamespace wiki\n{\n\tstruct compiler\n\t{\n\t\tusing Token = parser::Token;\n\t\tusing Tokens = parser::line::Tokens;\n\t\tusing Block = parser::Parser::Block;\n\t\tusing Blocks = parser::Parser::Text;\n\n\t\tstruct by_token\n\t\t{\n\t\t\tTOKEN end_tok;\n\t\t\tby_token(TOKEN end_tok)\n\t\t\t\t: end_tok(end_tok)\n\t\t\t{}\n\n\t\t\tbool reached(Tokens::const_iterator cur)\n\t\t\t{\n\t\t\t\treturn cur->type == end_tok;\n\t\t\t}\n\t\t};\n\n\t\tstruct by_argument\n\t\t{\n\t\t\tTOKEN end_tok;\n\t\t\tstd::string arg;\n\t\t\tby_argument(TOKEN end_tok, std::string&& arg)\n\t\t\t\t: end_tok(end_tok)\n\t\t\t\t, arg(std::move(arg))\n\t\t\t{}\n\n\t\t\tbool reached(Tokens::const_iterator cur)\n\t\t\t{\n\t\t\t\treturn cur->type == end_tok && arg == cur->arg.str();\n\t\t\t}\n\t\t};\n\n\t\ttemplate <typename Final, typename Right = by_token>\n\t\tstruct scanner: Right\n\t\t{\n\t\t\tTokens::const_iterator from, to;\n\n\t\t\ttemplate <typename... Args>\n\t\t\tscanner(Tokens::const_iterator from, Tokens::const_iterator to, Args&&... args)\n\t\t\t\t: Right(std::forward<Args>(args)...)\n\t\t\t\t, from(from)\n\t\t\t\t, to(to)\n\t\t\t{}\n\n\t\t\tTokens::const_iterator scan()\n\t\t\t{\n\t\t\t\tNodes children;\n\n\t\t\t\t++from;\n\t\t\t\tfrom = compile(children, from, to, Right::end_tok, false);\n\t\t\t\tif (from != to && Right::reached(from))\n\t\t\t\t\tstatic_cast<Final*>(this)->visit(children);\n\n\t\t\t\treturn from;\n\t\t\t}\n\t\t};\n\n\t\ttemplate <typename Final>\n\t\tusing arg_scanner = scanner<Final, by_argument>;\n\n\t\tstruct items\n\t\t{\n\t\t\tNodes& m_items;\n\n\t\t\titems(Nodes& _items) : m_items(_items) {}\n\t\t};\n\n\t\tstruct variable : scanner<variable>, items\n\t\t{\n\t\t\tvariable(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to) : scanner<variable>(from, to, TOKEN::VAR_E), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Variable>(m_items, text(children));\n\t\t\t}\n\t\t};\n\n\t\tstruct link : scanner<link>, items\n\t\t{\n\t\t\tlink(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to) : scanner<link>(from, to, TOKEN::HREF_E), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Link>(m_items, children)->normalize();\n\t\t\t}\n\t\t};\n\n\t\tstruct element : arg_scanner<element>, items\n\t\t{\n\t\t\telement(Nodes& _items, Tokens::const_iterator from, Tokens::const_iterator to, std::string&& arg) : arg_scanner<element>(from, to, TOKEN::TAG_E, std::move(arg)), items(_items) {}\n\t\t\tvoid visit(Nodes& children)\n\t\t\t{\n\t\t\t\tmake_node<inline_elem::Element>(m_items, arg, children);\n\t\t\t}\n\t\t};\n\n\t\tstatic inline Nodes compile(const Tokens& tokens, bool pre);\n\t\tstatic inline Tokens::const_iterator compile(Nodes& children, Tokens::const_iterator begin, Tokens::const_iterator end, TOKEN endtok, bool pre);\n\t\tstatic inline NodePtr compile(const Block& block, bool pre);\n\t\tstatic inline void compile(Nodes& children, const Blocks& blocks, bool pre);\n\t\tstatic inline std::string text(const Nodes& nodes);\n\t\ttemplate <typename Class, typename... Args>\n\t\tstatic inline std::shared_ptr<Class> make_node(Nodes& items, Args&&... args)\n\t\t{\n\t\t\tauto elem = std::make_shared<Class>(std::forward<Args>(args)...);\n\t\t\titems.push_back(elem);\n\t\t\treturn elem;\n\t\t}\n\t\ttemplate <typename Class, typename... Args>\n\t\tstatic inline std::shared_ptr<Class> make_block(Args&&... args)\n\t\t{\n\t\t\treturn std::make_shared<Class>(std::forward<Args>(args)...);\n\t\t}\n\t};\n\n\tclass Document : public document\n\t{\n\t\tNodes m_children;\n\tpublic:\n\t\tDocument(const Nodes& children) : m_children(children) {}\n\t\tvoid text(stream& o, const variables_t& vars, list_ctx& ctx) const override\n\t\t{\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->text(o, vars, ctx);\n\t\t}\n\n\t\tvoid markup(stream& o, const variables_t& vars, const styler_ptr& styler, list_ctx& ctx) const override\n\t\t{\n\t\t\tstyler->begin_document(o);\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->markup(o, vars, styler, ctx);\n\t\t\tstyler->end_document(o);\n\t\t}\n\n\t\tvoid debug(stream& o) const override\n\t\t{\n\t\t\tfor (auto& child : m_children)\n\t\t\t\tchild->debug(o);\n\t\t}\n\n\t\tvoid store(const filesystem::path& obj)\n\t\t{\n\t\t\tbinary::Writer wr;\n\t\t\tif (!wr.open(obj))\n\t\t\t\treturn;\n\n\t\t\tif (!wr.store(m_children) || !wr.close())\n\t\t\t\tfilesystem::remove(obj);\n\t\t}\n\t};\n\n\t\/* public: *\/\n\n\tvoid cstream::write(const char* buffer, size_t size)\n\t{\n\t\tref.write(buffer, size);\n\t}\n\n\tdocument_ptr compile(const filesystem::path& file, const filesystem::path& obj)\n\t{\n\t\tfilesystem::status st{ file };\n\t\tif (!st.exists())\n\t\t\treturn nullptr;\n\n\t\tif (st.mtime() <= filesystem::status{ obj }.mtime())\n\t\t{\n\t\t\tbinary::Reader r;\n\t\t\tif (r.open(obj))\n\t\t\t{\n\t\t\t\tNodes children;\n\t\t\t\tif (r.load(children))\n\t\t\t\t\treturn std::make_shared<Document>(children);\n\t\t\t}\n\t\t}\n\n\t\tsize_t size = (size_t)st.file_size();\n\n\t\tstd::string text;\n\t\ttext.resize(size + 1);\n\t\tif (text.size() <= size)\n\t\t\treturn nullptr;\n\n\t\tauto f = fopen(file.native().c_str(), \"r\");\n\t\tif (!f)\n\t\t\treturn nullptr;\n\t\tif (fread(&text[0], 1, size, f) != size)\n\t\t{\n\t\t\tfclose(f);\n\t\t\treturn nullptr;\n\t\t};\n\t\tfclose(f);\n\n\t\ttext[size] = 0;\n\n\t\tdocument_ptr out = compile(text);\n\t\tstd::static_pointer_cast<Document>(out)->store(obj);\n\t\treturn out;\n\t}\n\n\tdocument_ptr compile(const filesystem::path& file)\n\t{\n\t\tfilesystem::status st{ file };\n\t\tif (!st.exists())\n\t\t\treturn nullptr;\n\n\t\tsize_t size = (size_t)st.file_size();\n\n\t\tstd::string text;\n\t\ttext.resize(size + 1);\n\t\tif (text.size() <= size)\n\t\t\treturn nullptr;\n\n\t\tauto f = fopen(file.native().c_str(), \"r\");\n\t\tif (!f)\n\t\t\treturn nullptr;\n\n\t\tif (fread(&text[0], 1, size, f) != size)\n\t\t{\n\t\t\tfclose(f);\n\t\t\treturn nullptr;\n\t\t};\n\t\tfclose(f);\n\n\t\ttext[size] = 0;\n\t\treturn compile(text);\n\t}\n\n\tdocument_ptr compile(const std::string& text)\n\t{\n\t\tauto blocks = parser::Parser{}.parse(text);\n\n\t\tNodes children;\n\t\tcompiler::compile(children, blocks, false);\n\t\treturn std::make_shared<Document>(children);\n\t}\n\n\t\/* private: *\/\n\tNodes compiler::compile(const parser::line::Tokens& tokens, bool pre)\n\t{\n\t\tNodes list;\n\t\tcompile(list, tokens.begin(), tokens.end(), TOKEN::BAD, pre);\n\t\treturn list;\n\t}\n\n\tcompiler::Tokens::const_iterator compiler::compile(Nodes& items, Tokens::const_iterator begin, Tokens::const_iterator end, TOKEN endtok, bool pre)\n\t{\n\t\tstd::shared_ptr<inline_elem::Text> text;\n\t\tstd::shared_ptr<Node> elem;\n\n\t\tauto cur = begin;\n\t\tfor (; cur != end; ++cur)\n\t\t{\n\t\t\tif (cur->type == endtok)\n\t\t\t\treturn cur;\n\n\t\t\tif (cur->type != TOKEN::TEXT)\n\t\t\t\ttext = nullptr;\n\n\t\t\tNodes children;\n\n\t\t\tauto&& token = *cur;\n\t\t\tswitch (token.type)\n\t\t\t{\n\t\t\tcase TOKEN::TEXT:\n\t\t\t\tif (text)\n\t\t\t\t\ttext->append(token.arg.begin(), token.arg.end());\n\t\t\t\telse\n\t\t\t\t\ttext = make_node<inline_elem::Text>(items, token.arg.str());\n\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::BREAK:\n\t\t\t\tmake_node<inline_elem::Break>(items);\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::LINE:\n\t\t\t\tmake_node<inline_elem::Line>(items);\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::TAG_S:\n\t\t\t\tcur = element{ items, cur, end, token.arg.str() }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::VAR_S:\n\t\t\t\tcur = variable{ items, cur, end }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::HREF_S:\n\t\t\t\tcur = link{ items, cur, end }.scan();\n\t\t\t\tbreak;\n\n\t\t\tcase TOKEN::HREF_NS:\n\t\t\tcase TOKEN::HREF_SEG:\n\t\t\t\tmake_node<inline_elem::Token>(items, token.type);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (cur == end)\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn cur;\n\t}\n\n\tvoid compiler::compile(Nodes& children, const parser::Parser::Text& blocks, bool pre)\n\t{\n\t\tfor (auto&& block : blocks)\n\t\t{\n\t\t\tauto child = compile(block, pre);\n\t\t\tif (child)\n\t\t\t\tchildren.push_back(child);\n\t\t}\n\t}\n\n\tNodePtr compiler::compile(const parser::Parser::Block& block, bool pre)\n\t{\n\t\tusing BLOCK = parser::Parser::BLOCK;\n\n\t\tif (!pre)\n\t\t\tpre = block.type == BLOCK::PRE;\n\t\tauto children = compile(block.tokens, pre);\n\t\tcompile(children, block.items, pre);\n\n\t\tswitch (block.type)\n\t\t{\n\t\tcase BLOCK::HEADER: return make_block<block_elem::Header>(block.iArg, children);\n\t\tcase BLOCK::PARA: return make_block<block_elem::Para>(children);\n\t\tcase BLOCK::QUOTE: return make_block<block_elem::Quote>(children);\n\t\tcase BLOCK::PRE: return make_block<block_elem::Pre>(children);\n\t\tcase BLOCK::UL: return make_block<block_elem::UList>(children);\n\t\tcase BLOCK::OL: return make_block<block_elem::OList>(children);\n\t\tcase BLOCK::ITEM: return make_block<block_elem::Item>(children);\n\t\tcase BLOCK::HR: return make_block<block_elem::HR>();\n\t\tcase BLOCK::SIGNATURE: return make_block<block_elem::Signature>(children);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tstd::string compiler::text(const Nodes& nodes)\n\t{\n\t\tstd::ostringstream o;\n\t\tcstream co{ o };\n\t\tvariables_t vars;\n\t\tlist_ctx ctx;\n\t\tfor (auto&& node : nodes)\n\t\t\tnode->text(co, vars, ctx);\n\t\treturn o.str();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2012, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n\n#include <QApplication>\n#include <QX11Info>\n#include <QProcess>\n#include <QProcessEnvironment>\n#include <QFile>\n#include <QFileInfo>\n#include <QString>\n#include <QUrl>\n#include <QDebug>\n#include <QTranslator>\n\/\/#include <QLocale>\n#include <QMessageBox>\n#include <QSplashScreen>\n#include <QDateTime>\n#include <QPixmap>\n#include <QColor>\n#include <QFont>\n\/\/#include <QTextCodec>\n\n#include \"LFileDialog.h\"\n\n#include <LuminaXDG.h>\n#include <LuminaUtils.h>\n#include <LuminaOS.h>\n#include <LuminaThemes.h>\n\nvoid printUsageInfo(){\n qDebug() << \"lumina-open: Application launcher for the Lumina Desktop Environment\";\n qDebug() << \"Description: Given a file (with absolute path) or URL, this utility will try to find the appropriate application with which to open the file. If the file is a *.desktop application shortcut, it will just start the application appropriately. It can also perform a few specific system operations if given special flags.\";\n qDebug() << \"Usage: lumina-open [-select] <absolute file path or URL>\";\n qDebug() << \" lumina-open [-volumeup, -volumedown, -brightnessup, -brightnessdown]\";\n qDebug() << \" [-select] (optional) flag to bypass any default application settings and show the application selector window\";\n qDebug() << \"Special Flags:\";\n qDebug() << \" \\\"-volume[up\/down]\\\" Flag to increase\/decrease audio volume by 5%\";\n qDebug() << \" \\\"-brightness[up\/down]\\\" Flag to increase\/decrease screen brightness by 5%\";\n exit(1);\n}\n\nvoid ShowErrorDialog(int argc, char **argv, QString message){\n \/\/Setup the application\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n\tLUtils::LoadTranslation(&App,\"lumina-open\");\n QMessageBox dlg(QMessageBox::Critical, QObject::tr(\"File Error\"), message );\n dlg.exec();\n exit(1);\n}\n\nvoid showOSD(int argc, char **argv, QString message){\n \/\/Setup the application\n QApplication App(argc, argv);\n LUtils::LoadTranslation(&App,\"lumina-open\");\n\n \/\/Display the OSD\n QPixmap pix(\":\/icons\/OSD.png\");\n QSplashScreen splash(pix, Qt::SplashScreen | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);\n splash.setWindowTitle(\"\");\n QFont myfont;\n\tmyfont.setBold(true);\n\tmyfont.setPixelSize(13);\n\tsplash.setFont(myfont);\n qDebug() << \"Display OSD\";\n splash.show();\n \/\/qDebug() << \" - show message\";\n splash.showMessage(message, Qt::AlignCenter, Qt::white);\n \/\/qDebug() << \" - loop\";\n QDateTime end = QDateTime::currentDateTime().addMSecs(800);\n while(QDateTime::currentDateTime() < end){ App.processEvents(); }\n splash.hide();\n}\n\nQString cmdFromUser(int argc, char **argv, QString inFile, QString extension, QString& path, bool showDLG=false){\n \/\/First check to see if there is a default for this extension\n QString defApp;\n if(extension==\"mimetype\"){\n\t\/\/qDebug() << \"inFile:\" << inFile;\n\tQStringList matches = LXDG::findAppMimeForFile(inFile, true).split(\"::::\"); \/\/allow multiple matches\n\t\/\/qDebug() << \"Matches:\" << matches;\n\tfor(int i=0; i<matches.length(); i++){\n\t defApp = LXDG::findDefaultAppForMime(matches[i]);\n\t if(!defApp.isEmpty()){ extension = matches[i]; break; }\n\t else if(i+1==matches.length()){ extension = matches[0]; }\n\t}\n }else{ defApp = LFileDialog::getDefaultApp(extension); }\n \n if( !defApp.isEmpty() && !showDLG ){\n bool ok = false;\n if(defApp.endsWith(\".desktop\")){\n XDGDesktop DF = LXDG::loadDesktopFile(defApp, ok);\n if(ok){\n \t QString exec = LXDG::getDesktopExec(DF);\n \t if(!exec.isEmpty()){\n \t qDebug() << \"[lumina-open] Using default application:\" << DF.name << \"File:\" << inFile;\n if(!DF.path.isEmpty()){ path = DF.path; }\n return exec;\n }\n }\n }else{\n\t\/\/Only binary given\n\tif(LUtils::isValidBinary(defApp)){\n\t qDebug() << \"[lumina-open] Using default application:\" << defApp << \"File:\" << inFile;\n\t return defApp; \/\/just use the binary\n\t}\n }\n \/\/invalid default - reset it and continue on\n LFileDialog::setDefaultApp(extension, \"\");\n }\n \/\/Final catch: directory given - no valid default found - use lumina-fm\n if(extension==\"directory\" && !showDLG){ return \"lumina-fm\"; }\n \/\/No default set -- Start up the application selection dialog\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n LUtils::LoadTranslation(&App,\"lumina-open\");\n\n LFileDialog w;\n if(extension==\"email\" || extension==\"webbrowser\"){\n \/\/URL\n w.setFileInfo(inFile, extension, false);\n }else{\n \/\/File\n if(inFile.endsWith(\"\/\")){ inFile.chop(1); }\n w.setFileInfo(inFile.section(\"\/\",-1), extension, true);\n }\n\n w.show();\n App.exec();\n if(!w.appSelected){ return \"\"; }\n \/\/Return the run path if appropriate\n if(!w.appPath.isEmpty()){ path = w.appPath; }\n \/\/Just do the default application registration here for now\n \/\/ might move it to the runtime phase later after seeing that the app has successfully started\n if(w.setDefault){ \n if(!w.appFile.isEmpty()){ LFileDialog::setDefaultApp(extension, w.appFile); }\n else{ LFileDialog::setDefaultApp(extension, w.appExec); }\n }else{ LFileDialog::setDefaultApp(extension, \"\"); }\n \/\/Now return the resulting application command\n return w.appExec;\n}\n\nvoid getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){\n \/\/Get the input file\n \/\/Make sure to load the proper system encoding first\n LUtils::LoadTranslation(0,\"\"); \/\/bypass application modification\n QString inFile;\n bool showDLG = false; \/\/flag to bypass any default application setting\n if(argc > 1){\n for(int i=1; i<argc; i++){\n if(QString(argv[i]).simplified() == \"-select\"){\n \tshowDLG = true;\n }else if(QString(argv[i]).simplified() == \"-volumeup\"){\n\tint vol = LOS::audioVolume()+5; \/\/increase 5%\n\tif(vol>100){ vol=100; }\n\tLOS::setAudioVolume(vol);\n\tshowOSD(argc,argv, QString(QObject::tr(\"Audio Volume %1%\")).arg(QString::number(vol)) );\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-volumedown\"){\n\tint vol = LOS::audioVolume()-5; \/\/decrease 5%\n\tif(vol<0){ vol=0; }\n\tLOS::setAudioVolume(vol);\n\tshowOSD(argc,argv, QString(QObject::tr(\"Audio Volume %1%\")).arg(QString::number(vol)) );\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-brightnessup\"){\n\tint bright = LOS::ScreenBrightness();\n\tif(bright > 0){ \/\/brightness control available\n\t bright = bright+5; \/\/increase 5%\n\t if(bright>100){ bright = 100; }\n\t LOS::setScreenBrightness(bright);\n\t showOSD(argc,argv, QString(QObject::tr(\"Screen Brightness %1%\")).arg(QString::number(bright)) );\n\t}\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-brightnessdown\"){\n\tint bright = LOS::ScreenBrightness();\n\tif(bright > 0){ \/\/brightness control available\n\t bright = bright-5; \/\/decrease 5%\n\t if(bright<0){ bright = 0; }\n\t LOS::setScreenBrightness(bright);\n\t showOSD(argc,argv, QString(QObject::tr(\"Screen Brightness %1%\")).arg(QString::number(bright)) );\n\t}\n\treturn;\n }else{\n inFile = QString::fromLocal8Bit(argv[i]);\n break;\n }\n }\n }else{\n printUsageInfo();\n }\n \/\/Make sure that it is a valid file\/URL\n bool isFile=false; bool isUrl=false;\n if(QFile::exists(inFile)){ isFile=true; }\n else if(QFile::exists(QDir::currentPath()+\"\/\"+inFile)){isFile=true; inFile = QDir::currentPath()+\"\/\"+inFile;} \/\/account for relative paths\n else if(QUrl(inFile).isValid() && !inFile.startsWith(\"\/\") ){ isUrl=true; }\n if( !isFile && !isUrl ){ ShowErrorDialog( argc, argv, QString(QObject::tr(\"Invalid file or URL: %1\")).arg(inFile) ); }\n \/\/Determing the type of file (extension)\n QString extension;\n \/\/qDebug() << \"File Type:\" << isFile << isUrl;\n if(isFile){\n QFileInfo info(inFile);\n extension=info.suffix();\n \/\/qDebug() << \" - Extension:\" << extension;\n if(info.isDir()){ extension=\"directory\"; }\n else if(info.isExecutable() && extension.isEmpty()){ extension=\"binary\"; }\n else if(extension!=\"desktop\"){ extension=\"mimetype\"; } \/\/flag to check for mimetype default based on file\n }\n else if(isUrl && inFile.startsWith(\"mailto:\")){ extension = \"email\"; }\n else if(isUrl){ extension = \"webbrowser\"; }\n \/\/qDebug() << \"Input:\" << inFile << isFile << isUrl << extension;\n \/\/if not an application - find the right application to open the file\n QString cmd;\n bool useInputFile = false;\n if(extension==\"desktop\" && !showDLG){\n bool ok = false;\n XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);\n if(!ok){\n ShowErrorDialog( argc, argv, QString(QObject::tr(\"File could not be opened: %1\")).arg(inFile) );\n }\n switch(DF.type){\n case XDGDesktop::APP:\n if(!DF.exec.isEmpty()){\n cmd = LXDG::getDesktopExec(DF);\n if(!DF.path.isEmpty()){ path = DF.path; }\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"Application shortcut is missing the launching information (malformed shortcut): %1\")).arg(inFile) );\n }\n break;\n case XDGDesktop::LINK:\n if(!DF.url.isEmpty()){\n \/\/This is a URL - so adjust the input variables appropriately\n inFile = DF.url;\n cmd.clear();\n extension = inFile.section(\":\",0,0);\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"URL shortcut is missing the URL: %1\")).arg(inFile) );\n }\n break;\n case XDGDesktop::DIR:\n if(!DF.path.isEmpty()){\n \/\/This is a directory link - adjust inputs\n inFile = DF.path;\n cmd.clear();\n extension = \"directory\";\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"Directory shortcut is missing the path to the directory: %1\")).arg(inFile) );\n }\n break;\n default:\n\tShowErrorDialog( argc, argv, QString(QObject::tr(\"Unknown type of shortcut : %1\")).arg(inFile) );\n }\n }\n if(cmd.isEmpty()){\n if(extension==\"binary\"){ cmd = inFile; }\n else{\n \/\/Find out the proper application to use this file\/directory\n useInputFile=true;\n cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);\n if(cmd.isEmpty()){ return; }\n }\n }\n \/\/Now assemble the exec string (replace file\/url field codes as necessary)\n if(useInputFile){ \n args = inFile; \/\/just to keep them distinct internally\n \/\/ NOTE: lumina-open is only designed for a single input file,\n \/\/ so no need to distinguish between the list codes (uppercase) \n \/\/ and the single-file codes (lowercase)\n if(isFile && (cmd.contains(\"%f\") || cmd.contains(\"%F\") ) ){\n cmd.replace(\"%f\",\"\\\"\"+inFile+\"\\\"\");\n cmd.replace(\"%F\",\"\\\"\"+inFile+\"\\\"\");\n }else if(isUrl && (cmd.contains(\"%U\") || cmd.contains(\"%u\")) ){\n cmd.replace(\"%u\",\"\\\"\"+inFile+\"\\\"\");\n cmd.replace(\"%U\",\"\\\"\"+inFile+\"\\\"\");\n }else{\n \/\/No field codes (or improper field codes given - which is quite common)\n \/\/ - Just tack the input file on the end and let the app handle it as necessary\n cmd.append(\" \\\"\"+inFile+\"\\\"\");\n }\n }\n \/\/qDebug() << \"Found Command:\" << cmd << \"Extension:\" << extension;\n \/\/Clean up any leftover \"Exec\" field codes (should have already been replaced earlier)\n if(cmd.contains(\"%\")){cmd = cmd.remove(\"%U\").remove(\"%u\").remove(\"%F\").remove(\"%f\").remove(\"%i\").remove(\"%c\").remove(\"%k\").simplified(); }\n binary = cmd; \/\/pass this string to the calling function\n\n}\n\nint main(int argc, char **argv){\n \/\/Run all the actual code in a separate function to have as little memory usage\n \/\/ as possible aside from the main application when running\n\n \/\/Make sure the XDG environment variables exist first\n LXDG::setEnvironmentVars();\n \/\/now get the command\n QString cmd, args, path;\n getCMD(argc, argv, cmd, args, path);\n \/\/qDebug() << \"Run CMD:\" << cmd << args;\n \/\/Now run the command (move to execvp() later?)\n if(cmd.isEmpty()){ return 0; } \/\/no command to run (handled internally)\n \/\/if(!args.isEmpty()){ cmd.append(\" \"+args+\"\"); }\n \/\/int retcode = system( cmd.toUtf8() );\n qDebug() << \"[lumina-open] Running Cmd:\" << cmd;\n QProcess *p = new QProcess();\n p->setProcessEnvironment(QProcessEnvironment::systemEnvironment());\n if(!path.isEmpty() && QFile::exists(path)){ p->setWorkingDirectory(path); }\n p->start(cmd);\n \/\/Check the startup procedure\n \/*while(!p->waitForStarted(5000)){\n if(p->state() == QProcess::NotRunning){\n \/\/bad\/invalid start\n qDebug() << \"[lumina-open] Application did not start properly:\"<<cmd;\n return p->exitCode();\n }else if(p->state() == QProcess::Running){\n \/\/This just missed the \"started\" signal - continue\n break;\n }\n }*\/\n \/\/Now check up on it once every minute until it is finished\n while(!p->waitForFinished(60000)){\n \/\/qDebug() << \"[lumina-open] process check:\" << p->state();\n if(p->state() != QProcess::Running){ break; } \/\/somehow missed the finished signal\n }\n int retcode = p->exitCode();\n \/\/qDebug() << \"[lumina-open] Finished Cmd:\" << cmd << retcode << p->exitStatus();\n \n \/\/if(retcode!=0 ){\n if(p->exitStatus() == QProcess::CrashExit){\n qDebug() << \"[lumina-open] Application Error:\" << retcode;\n QString err = QString(p->readAllStandardError());\n if(err.isEmpty()){ err = QString(p->readAllStandardOutput()); }\n \/\/Setup the application\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n\tLUtils::LoadTranslation(&App,\"lumina-open\");\n QMessageBox dlg(QMessageBox::Critical, QObject::tr(\"Application Error\"), QObject::tr(\"The following application experienced an error and needed to close:\")+\"\\n\\n\"+cmd );\n if(!err.isEmpty()){ dlg.setDetailedText(err); }\n dlg.exec();\n }\n return retcode;\n}\n<commit_msg>fix issue #55: inform user whan return code is not null<commit_after>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2012, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n\n#include <QApplication>\n#include <QX11Info>\n#include <QProcess>\n#include <QProcessEnvironment>\n#include <QFile>\n#include <QFileInfo>\n#include <QString>\n#include <QUrl>\n#include <QDebug>\n#include <QTranslator>\n\/\/#include <QLocale>\n#include <QMessageBox>\n#include <QSplashScreen>\n#include <QDateTime>\n#include <QPixmap>\n#include <QColor>\n#include <QFont>\n\/\/#include <QTextCodec>\n\n#include \"LFileDialog.h\"\n\n#include <LuminaXDG.h>\n#include <LuminaUtils.h>\n#include <LuminaOS.h>\n#include <LuminaThemes.h>\n\nvoid printUsageInfo(){\n qDebug() << \"lumina-open: Application launcher for the Lumina Desktop Environment\";\n qDebug() << \"Description: Given a file (with absolute path) or URL, this utility will try to find the appropriate application with which to open the file. If the file is a *.desktop application shortcut, it will just start the application appropriately. It can also perform a few specific system operations if given special flags.\";\n qDebug() << \"Usage: lumina-open [-select] <absolute file path or URL>\";\n qDebug() << \" lumina-open [-volumeup, -volumedown, -brightnessup, -brightnessdown]\";\n qDebug() << \" [-select] (optional) flag to bypass any default application settings and show the application selector window\";\n qDebug() << \"Special Flags:\";\n qDebug() << \" \\\"-volume[up\/down]\\\" Flag to increase\/decrease audio volume by 5%\";\n qDebug() << \" \\\"-brightness[up\/down]\\\" Flag to increase\/decrease screen brightness by 5%\";\n exit(1);\n}\n\nvoid ShowErrorDialog(int argc, char **argv, QString message){\n \/\/Setup the application\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n\tLUtils::LoadTranslation(&App,\"lumina-open\");\n QMessageBox dlg(QMessageBox::Critical, QObject::tr(\"File Error\"), message );\n dlg.exec();\n exit(1);\n}\n\nvoid showOSD(int argc, char **argv, QString message){\n \/\/Setup the application\n QApplication App(argc, argv);\n LUtils::LoadTranslation(&App,\"lumina-open\");\n\n \/\/Display the OSD\n QPixmap pix(\":\/icons\/OSD.png\");\n QSplashScreen splash(pix, Qt::SplashScreen | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);\n splash.setWindowTitle(\"\");\n QFont myfont;\n\tmyfont.setBold(true);\n\tmyfont.setPixelSize(13);\n\tsplash.setFont(myfont);\n qDebug() << \"Display OSD\";\n splash.show();\n \/\/qDebug() << \" - show message\";\n splash.showMessage(message, Qt::AlignCenter, Qt::white);\n \/\/qDebug() << \" - loop\";\n QDateTime end = QDateTime::currentDateTime().addMSecs(800);\n while(QDateTime::currentDateTime() < end){ App.processEvents(); }\n splash.hide();\n}\n\nQString cmdFromUser(int argc, char **argv, QString inFile, QString extension, QString& path, bool showDLG=false){\n \/\/First check to see if there is a default for this extension\n QString defApp;\n if(extension==\"mimetype\"){\n\t\/\/qDebug() << \"inFile:\" << inFile;\n\tQStringList matches = LXDG::findAppMimeForFile(inFile, true).split(\"::::\"); \/\/allow multiple matches\n\t\/\/qDebug() << \"Matches:\" << matches;\n\tfor(int i=0; i<matches.length(); i++){\n\t defApp = LXDG::findDefaultAppForMime(matches[i]);\n\t if(!defApp.isEmpty()){ extension = matches[i]; break; }\n\t else if(i+1==matches.length()){ extension = matches[0]; }\n\t}\n }else{ defApp = LFileDialog::getDefaultApp(extension); }\n \n if( !defApp.isEmpty() && !showDLG ){\n bool ok = false;\n if(defApp.endsWith(\".desktop\")){\n XDGDesktop DF = LXDG::loadDesktopFile(defApp, ok);\n if(ok){\n \t QString exec = LXDG::getDesktopExec(DF);\n \t if(!exec.isEmpty()){\n \t qDebug() << \"[lumina-open] Using default application:\" << DF.name << \"File:\" << inFile;\n if(!DF.path.isEmpty()){ path = DF.path; }\n return exec;\n }\n }\n }else{\n\t\/\/Only binary given\n\tif(LUtils::isValidBinary(defApp)){\n\t qDebug() << \"[lumina-open] Using default application:\" << defApp << \"File:\" << inFile;\n\t return defApp; \/\/just use the binary\n\t}\n }\n \/\/invalid default - reset it and continue on\n LFileDialog::setDefaultApp(extension, \"\");\n }\n \/\/Final catch: directory given - no valid default found - use lumina-fm\n if(extension==\"directory\" && !showDLG){ return \"lumina-fm\"; }\n \/\/No default set -- Start up the application selection dialog\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n LUtils::LoadTranslation(&App,\"lumina-open\");\n\n LFileDialog w;\n if(extension==\"email\" || extension==\"webbrowser\"){\n \/\/URL\n w.setFileInfo(inFile, extension, false);\n }else{\n \/\/File\n if(inFile.endsWith(\"\/\")){ inFile.chop(1); }\n w.setFileInfo(inFile.section(\"\/\",-1), extension, true);\n }\n\n w.show();\n App.exec();\n if(!w.appSelected){ return \"\"; }\n \/\/Return the run path if appropriate\n if(!w.appPath.isEmpty()){ path = w.appPath; }\n \/\/Just do the default application registration here for now\n \/\/ might move it to the runtime phase later after seeing that the app has successfully started\n if(w.setDefault){ \n if(!w.appFile.isEmpty()){ LFileDialog::setDefaultApp(extension, w.appFile); }\n else{ LFileDialog::setDefaultApp(extension, w.appExec); }\n }else{ LFileDialog::setDefaultApp(extension, \"\"); }\n \/\/Now return the resulting application command\n return w.appExec;\n}\n\nvoid getCMD(int argc, char ** argv, QString& binary, QString& args, QString& path){\n \/\/Get the input file\n \/\/Make sure to load the proper system encoding first\n LUtils::LoadTranslation(0,\"\"); \/\/bypass application modification\n QString inFile;\n bool showDLG = false; \/\/flag to bypass any default application setting\n if(argc > 1){\n for(int i=1; i<argc; i++){\n if(QString(argv[i]).simplified() == \"-select\"){\n \tshowDLG = true;\n }else if(QString(argv[i]).simplified() == \"-volumeup\"){\n\tint vol = LOS::audioVolume()+5; \/\/increase 5%\n\tif(vol>100){ vol=100; }\n\tLOS::setAudioVolume(vol);\n\tshowOSD(argc,argv, QString(QObject::tr(\"Audio Volume %1%\")).arg(QString::number(vol)) );\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-volumedown\"){\n\tint vol = LOS::audioVolume()-5; \/\/decrease 5%\n\tif(vol<0){ vol=0; }\n\tLOS::setAudioVolume(vol);\n\tshowOSD(argc,argv, QString(QObject::tr(\"Audio Volume %1%\")).arg(QString::number(vol)) );\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-brightnessup\"){\n\tint bright = LOS::ScreenBrightness();\n\tif(bright > 0){ \/\/brightness control available\n\t bright = bright+5; \/\/increase 5%\n\t if(bright>100){ bright = 100; }\n\t LOS::setScreenBrightness(bright);\n\t showOSD(argc,argv, QString(QObject::tr(\"Screen Brightness %1%\")).arg(QString::number(bright)) );\n\t}\n\treturn;\n }else if(QString(argv[i]).simplified() == \"-brightnessdown\"){\n\tint bright = LOS::ScreenBrightness();\n\tif(bright > 0){ \/\/brightness control available\n\t bright = bright-5; \/\/decrease 5%\n\t if(bright<0){ bright = 0; }\n\t LOS::setScreenBrightness(bright);\n\t showOSD(argc,argv, QString(QObject::tr(\"Screen Brightness %1%\")).arg(QString::number(bright)) );\n\t}\n\treturn;\n }else{\n inFile = QString::fromLocal8Bit(argv[i]);\n break;\n }\n }\n }else{\n printUsageInfo();\n }\n \/\/Make sure that it is a valid file\/URL\n bool isFile=false; bool isUrl=false;\n if(QFile::exists(inFile)){ isFile=true; }\n else if(QFile::exists(QDir::currentPath()+\"\/\"+inFile)){isFile=true; inFile = QDir::currentPath()+\"\/\"+inFile;} \/\/account for relative paths\n else if(QUrl(inFile).isValid() && !inFile.startsWith(\"\/\") ){ isUrl=true; }\n if( !isFile && !isUrl ){ ShowErrorDialog( argc, argv, QString(QObject::tr(\"Invalid file or URL: %1\")).arg(inFile) ); }\n \/\/Determing the type of file (extension)\n QString extension;\n \/\/qDebug() << \"File Type:\" << isFile << isUrl;\n if(isFile){\n QFileInfo info(inFile);\n extension=info.suffix();\n \/\/qDebug() << \" - Extension:\" << extension;\n if(info.isDir()){ extension=\"directory\"; }\n else if(info.isExecutable() && extension.isEmpty()){ extension=\"binary\"; }\n else if(extension!=\"desktop\"){ extension=\"mimetype\"; } \/\/flag to check for mimetype default based on file\n }\n else if(isUrl && inFile.startsWith(\"mailto:\")){ extension = \"email\"; }\n else if(isUrl){ extension = \"webbrowser\"; }\n \/\/qDebug() << \"Input:\" << inFile << isFile << isUrl << extension;\n \/\/if not an application - find the right application to open the file\n QString cmd;\n bool useInputFile = false;\n if(extension==\"desktop\" && !showDLG){\n bool ok = false;\n XDGDesktop DF = LXDG::loadDesktopFile(inFile, ok);\n if(!ok){\n ShowErrorDialog( argc, argv, QString(QObject::tr(\"File could not be opened: %1\")).arg(inFile) );\n }\n switch(DF.type){\n case XDGDesktop::APP:\n if(!DF.exec.isEmpty()){\n cmd = LXDG::getDesktopExec(DF);\n if(!DF.path.isEmpty()){ path = DF.path; }\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"Application shortcut is missing the launching information (malformed shortcut): %1\")).arg(inFile) );\n }\n break;\n case XDGDesktop::LINK:\n if(!DF.url.isEmpty()){\n \/\/This is a URL - so adjust the input variables appropriately\n inFile = DF.url;\n cmd.clear();\n extension = inFile.section(\":\",0,0);\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"URL shortcut is missing the URL: %1\")).arg(inFile) );\n }\n break;\n case XDGDesktop::DIR:\n if(!DF.path.isEmpty()){\n \/\/This is a directory link - adjust inputs\n inFile = DF.path;\n cmd.clear();\n extension = \"directory\";\n }else{\n\t ShowErrorDialog( argc, argv, QString(QObject::tr(\"Directory shortcut is missing the path to the directory: %1\")).arg(inFile) );\n }\n break;\n default:\n\tShowErrorDialog( argc, argv, QString(QObject::tr(\"Unknown type of shortcut : %1\")).arg(inFile) );\n }\n }\n if(cmd.isEmpty()){\n if(extension==\"binary\"){ cmd = inFile; }\n else{\n \/\/Find out the proper application to use this file\/directory\n useInputFile=true;\n cmd = cmdFromUser(argc, argv, inFile, extension, path, showDLG);\n if(cmd.isEmpty()){ return; }\n }\n }\n \/\/Now assemble the exec string (replace file\/url field codes as necessary)\n if(useInputFile){ \n args = inFile; \/\/just to keep them distinct internally\n \/\/ NOTE: lumina-open is only designed for a single input file,\n \/\/ so no need to distinguish between the list codes (uppercase) \n \/\/ and the single-file codes (lowercase)\n if(isFile && (cmd.contains(\"%f\") || cmd.contains(\"%F\") ) ){\n cmd.replace(\"%f\",\"\\\"\"+inFile+\"\\\"\");\n cmd.replace(\"%F\",\"\\\"\"+inFile+\"\\\"\");\n }else if(isUrl && (cmd.contains(\"%U\") || cmd.contains(\"%u\")) ){\n cmd.replace(\"%u\",\"\\\"\"+inFile+\"\\\"\");\n cmd.replace(\"%U\",\"\\\"\"+inFile+\"\\\"\");\n }else{\n \/\/No field codes (or improper field codes given - which is quite common)\n \/\/ - Just tack the input file on the end and let the app handle it as necessary\n cmd.append(\" \\\"\"+inFile+\"\\\"\");\n }\n }\n \/\/qDebug() << \"Found Command:\" << cmd << \"Extension:\" << extension;\n \/\/Clean up any leftover \"Exec\" field codes (should have already been replaced earlier)\n if(cmd.contains(\"%\")){cmd = cmd.remove(\"%U\").remove(\"%u\").remove(\"%F\").remove(\"%f\").remove(\"%i\").remove(\"%c\").remove(\"%k\").simplified(); }\n binary = cmd; \/\/pass this string to the calling function\n\n}\n\nint main(int argc, char **argv){\n \/\/Run all the actual code in a separate function to have as little memory usage\n \/\/ as possible aside from the main application when running\n\n \/\/Make sure the XDG environment variables exist first\n LXDG::setEnvironmentVars();\n \/\/now get the command\n QString cmd, args, path;\n getCMD(argc, argv, cmd, args, path);\n \/\/qDebug() << \"Run CMD:\" << cmd << args;\n \/\/Now run the command (move to execvp() later?)\n if(cmd.isEmpty()){ return 0; } \/\/no command to run (handled internally)\n \/\/if(!args.isEmpty()){ cmd.append(\" \"+args+\"\"); }\n \/\/int retcode = system( cmd.toUtf8() );\n qDebug() << \"[lumina-open] Running Cmd:\" << cmd;\n QProcess *p = new QProcess();\n p->setProcessEnvironment(QProcessEnvironment::systemEnvironment());\n if(!path.isEmpty() && QFile::exists(path)){ p->setWorkingDirectory(path); }\n p->start(cmd);\n \/\/Check the startup procedure\n \/*while(!p->waitForStarted(5000)){\n if(p->state() == QProcess::NotRunning){\n \/\/bad\/invalid start\n qDebug() << \"[lumina-open] Application did not start properly:\"<<cmd;\n return p->exitCode();\n }else if(p->state() == QProcess::Running){\n \/\/This just missed the \"started\" signal - continue\n break;\n }\n }*\/\n \/\/Now check up on it once every minute until it is finished\n while(!p->waitForFinished(60000)){\n \/\/qDebug() << \"[lumina-open] process check:\" << p->state();\n if(p->state() != QProcess::Running){ break; } \/\/somehow missed the finished signal\n }\n int retcode = p->exitCode();\n \/\/qDebug() << \"[lumina-open] Finished Cmd:\" << cmd << retcode << p->exitStatus();\n \n \/\/if(retcode!=0 ){\n if(p->exitStatus() == QProcess::CrashExit or retcode > 0){\n qDebug() << \"[lumina-open] Application Error:\" << retcode;\n QString err = QString(p->readAllStandardError());\n if(err.isEmpty()){ err = QString(p->readAllStandardOutput()); }\n \/\/Setup the application\n QApplication App(argc, argv);\n LuminaThemeEngine theme(&App);\n\tLUtils::LoadTranslation(&App,\"lumina-open\");\n QMessageBox dlg(QMessageBox::Critical, QObject::tr(\"Application Error\"), QObject::tr(\"The following application experienced an error and needed to close:\")+\"\\n\\n\"+cmd );\n if(!err.isEmpty()){ dlg.setDetailedText(err); }\n dlg.exec();\n }\n return retcode;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/data.hpp\"\n#include \"vast\/json.hpp\"\n\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/detail\/overload.hpp\"\n\nnamespace vast {\nnamespace {\n\nstruct adder {\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, caf::none_t>{}\n || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n >\n operator()(caf::none_t, const T& x) const {\n self = x;\n }\n\n void operator()(caf::none_t, caf::none_t) const {\n \/\/ nop\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n && (std::is_same<T, boolean>{}\n || std::is_same<T, integer>{}\n || std::is_same<T, count>{}\n || std::is_same<T, real>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, std::string>{})\n >\n operator()(T& x, const T& y) const {\n x += y;\n }\n\n template <class T, class U>\n std::enable_if_t<\n !(std::is_same<T, U>{} || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n && (std::is_same<T, boolean>{}\n || std::is_same<T, integer>{}\n || std::is_same<T, count>{}\n || std::is_same<T, real>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, std::string>{})\n >\n operator()(T&, const U&) const {\n \/\/ impossible\n }\n\n void operator()(timestamp&, timestamp) const {\n \/\/ impossible\n }\n\n void operator()(timestamp& ts, timespan x) const {\n ts += x;\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, timestamp>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n >\n operator()(timestamp&, const T&) const {\n \/\/ impossible\n }\n\n template <class T, class U>\n std::enable_if_t<\n !(std::is_same<U, vector>{} || std::is_same<U, set>{})\n && (std::is_same<T, pattern>{}\n || std::is_same<T, address>{}\n || std::is_same<T, subnet>{}\n || std::is_same<T, port>{}\n || std::is_same<T, enumeration>{}\n || std::is_same<T, map>{})\n >\n operator()(T&, const U&) const {\n \/\/ impossible\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n >\n operator()(vector& lhs, const T& rhs) const {\n lhs.emplace_back(rhs);\n }\n\n void operator()(vector& lhs, const vector& rhs) const {\n std::copy(rhs.begin(), rhs.end(), std::back_inserter(lhs));\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n >\n operator()(set& lhs, const T& rhs) const {\n lhs.emplace(rhs);\n }\n\n void operator()(set& lhs, const set& rhs) const {\n std::copy(rhs.begin(), rhs.end(), std::inserter(lhs, lhs.end()));\n }\n\n template <class T>\n std::enable_if_t<!std::is_same<T, vector>{}>\n operator()(T&, const vector& rhs) const {\n vector v;\n v.reserve(rhs.size() + 1);\n v.push_back(std::move(self));\n std::copy(rhs.begin(), rhs.end(), std::back_inserter(v));\n self = std::move(v);\n }\n\n template <class T>\n std::enable_if_t<!std::is_same<T, set>{}>\n operator()(T&, const set& rhs) const {\n set s;\n s.insert(std::move(self));\n std::copy(rhs.begin(), rhs.end(), std::inserter(s, s.end()));\n self = std::move(s);\n }\n\n data& self;\n};\n\nstruct match_visitor {\n bool operator()(const std::string& lhs, const pattern& rhs) const {\n return rhs.match(lhs);\n }\n\n template <class T, class U>\n bool operator()(const T&, const U&) const {\n return false;\n }\n};\n\nstruct in_visitor {\n bool operator()(const std::string& lhs, const std::string& rhs) const {\n return rhs.find(lhs) != std::string::npos;\n }\n\n bool operator()(const std::string& lhs, const pattern& rhs) const {\n return rhs.search(lhs);\n }\n\n bool operator()(const address& lhs, const subnet& rhs) const {\n return rhs.contains(lhs);\n }\n\n bool operator()(const subnet& lhs, const subnet& rhs) const {\n return rhs.contains(lhs);\n }\n\n template <class T>\n bool operator()(const T& lhs, const set& rhs) const {\n return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end();\n }\n\n template <class T>\n bool operator()(const T& lhs, const vector& rhs) const {\n return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end();\n }\n\n template <class T, class U>\n bool operator()(const T&, const U&) const {\n return false;\n }\n};\n\n} \/\/ namespace <anonymous>\n\ndata& data::operator+=(const data& rhs) {\n caf::visit(adder{*this}, *this, rhs);\n return *this;\n}\n\nbool operator==(const data& lhs, const data& rhs) {\n return lhs.data_ == rhs.data_;\n}\n\nbool operator<(const data& lhs, const data& rhs) {\n return lhs.data_ < rhs.data_;\n}\n\nbool evaluate(const data& lhs, relational_operator op, const data& rhs) {\n switch (op) {\n default:\n VAST_ASSERT(!\"missing case\");\n return false;\n case match:\n return caf::visit(match_visitor{}, lhs, rhs);\n case not_match:\n return !caf::visit(match_visitor{}, lhs, rhs);\n case in:\n return caf::visit(in_visitor{}, lhs, rhs);\n case not_in:\n return !caf::visit(in_visitor{}, lhs, rhs);\n case ni:\n return caf::visit(in_visitor{}, rhs, lhs);\n case not_ni:\n return !caf::visit(in_visitor{}, rhs, lhs);\n case equal:\n return lhs == rhs;\n case not_equal:\n return lhs != rhs;\n case less:\n return lhs < rhs;\n case less_equal:\n return lhs <= rhs;\n case greater:\n return lhs > rhs;\n case greater_equal:\n return lhs >= rhs;\n }\n}\n\nbool is_basic(const data& x) {\n return caf::visit(detail::overload(\n [](const auto&) { return true; },\n [](const enumeration&) { return false; },\n [](const vector&) { return false; },\n [](const set&) { return false; },\n [](const map&) { return false; }\n ), x);\n}\n\nbool is_complex(const data& x) {\n return !is_basic(x);\n}\n\nbool is_recursive(const data& x) {\n return caf::visit(detail::overload(\n [](const auto&) { return false; },\n [](const vector&) { return true; },\n [](const set&) { return true; },\n [](const map&) { return true; }\n ), x);\n}\n\nbool is_container(const data& x) {\n return is_recursive(x);\n}\n\nconst data* get(const vector& v, const offset& o) {\n const vector* x = &v;\n for (size_t i = 0; i < o.size(); ++i) {\n auto& idx = o[i];\n if (idx >= x->size())\n return nullptr;\n auto d = &(*x)[idx];\n if (i + 1 == o.size())\n return d;\n x = caf::get_if<vector>(d);\n if (!x)\n return nullptr;\n }\n return nullptr;\n}\n\nconst data* get(const data& d, const offset& o) {\n if (auto v = caf::get_if<vector>(&d))\n return get(*v, o);\n return nullptr;\n}\n\nnamespace {\n\ntemplate <class Iterator>\nvector flatten(Iterator& f, Iterator l) {\n vector xs;\n xs.reserve(l - f);\n for (; f != l; ++f) {\n auto&& x = *f;\n if (auto v = caf::get_if<vector>(&x)) {\n auto begin = Iterator{v->begin()};\n auto end = Iterator{v->end()};\n auto ys = flatten(begin, end);\n xs.insert(xs.end(),\n std::make_move_iterator(ys.begin()),\n std::make_move_iterator(ys.end()));\n } else {\n xs.push_back(*f);\n }\n }\n return xs;\n}\n\ntemplate <class Iterator>\ncaf::optional<vector> unflatten(Iterator& f, Iterator l, const record_type& rec) {\n vector xs;\n xs.reserve(rec.fields.size());\n for (auto& field : rec.fields)\n if (f == l) {\n return {};\n } else if (auto rt = caf::get_if<record_type>(&field.type)) {\n auto ys = unflatten(f, l, *rt);\n if (!ys)\n return ys;\n xs.push_back(std::move(*ys));\n } else {\n xs.push_back(*f++);\n }\n return xs;\n}\n\n} \/\/ namespace <anonymous>\n\nvector flatten(const vector& xs) {\n auto f = xs.begin();\n auto l = xs.end();\n return flatten(f, l);\n}\n\nvector flatten(vector&& xs) {\n auto f = std::make_move_iterator(xs.begin());\n auto l = std::make_move_iterator(xs.end());\n return flatten(f, l);\n}\n\ndata flatten(const data& x) {\n auto xs = caf::get_if<vector>(&x);\n return xs ? flatten(*xs) : x;\n}\n\ndata flatten(data&& x) {\n auto xs = caf::get_if<vector>(&x);\n return xs ? flatten(std::move(*xs)) : x;\n}\n\ncaf::optional<vector> unflatten(const vector& xs, const record_type& rt) {\n auto first = xs.begin();\n auto last = xs.end();\n return unflatten(first, last, rt);\n}\n\ncaf::optional<vector> unflatten(vector&& xs, const record_type& rt) {\n auto first = std::make_move_iterator(xs.begin());\n auto last = std::make_move_iterator(xs.end());\n return unflatten(first, last, rt);\n}\n\ncaf::optional<vector> unflatten(const data& x, const type& t) {\n auto xs = caf::get_if<vector>(&x);\n auto rt = caf::get_if<record_type>(&t);\n return xs && rt ? unflatten(*xs, *rt) : caf::optional<vector>{};\n}\n\ncaf::optional<vector> unflatten(data&& x, const type& t) {\n auto xs = caf::get_if<vector>(&x);\n auto rt = caf::get_if<record_type>(&t);\n return xs && rt ? unflatten(std::move(*xs), *rt) : caf::optional<vector>{};\n}\n\nnamespace {\n\njson jsonize(const data& x) {\n return caf::visit(detail::overload(\n [&](const auto& y) { return to_json(y); },\n [&](caf::none_t) { return json{}; },\n [&](const std::string& str) { return json{str}; }\n ), x);\n}\n\n} \/\/ namespace <anonymous>\n\nbool convert(const vector& v, json& j) {\n json::array a(v.size());\n for (auto i = 0u; i < v.size(); ++i)\n a[i] = jsonize(v[i]);\n j = std::move(a);\n return true;\n}\n\nbool convert(const set& s, json& j) {\n json::array a(s.size());\n auto i = 0u;\n for (auto& x : s)\n a[i++] = jsonize(x);\n j = std::move(a);\n return true;\n}\n\nbool convert(const map& t, json& j) {\n json::array values;\n for (auto& p : t) {\n json::array a;\n a.emplace_back(jsonize(p.first));\n a.emplace_back(jsonize(p.second));\n values.emplace_back(std::move(a));\n };\n j = std::move(values);\n return true;\n}\n\nbool convert(const data& d, json& j) {\n j = jsonize(d);\n return true;\n}\n\nbool convert(const data& d, json& j, const type& t) {\n auto v = caf::get_if<vector>(&d);\n auto rt = caf::get_if<record_type>(&t);\n if (v && rt) {\n if (v->size() != rt->fields.size())\n return false;\n json::object o;\n for (auto i = 0u; i < v->size(); ++i) {\n auto& f = rt->fields[i];\n if (!convert((*v)[i], o[f.name], f.type))\n return false;\n }\n j = std::move(o);\n return true;\n }\n return convert(d, j);\n}\n\n} \/\/ namespace vast\n<commit_msg>Refactor data evaluation<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/data.hpp\"\n#include \"vast\/json.hpp\"\n\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/detail\/overload.hpp\"\n\nnamespace vast {\nnamespace {\n\nstruct adder {\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, caf::none_t>{}\n || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n >\n operator()(caf::none_t, const T& x) const {\n self = x;\n }\n\n void operator()(caf::none_t, caf::none_t) const {\n \/\/ nop\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n && (std::is_same<T, boolean>{}\n || std::is_same<T, integer>{}\n || std::is_same<T, count>{}\n || std::is_same<T, real>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, std::string>{})\n >\n operator()(T& x, const T& y) const {\n x += y;\n }\n\n template <class T, class U>\n std::enable_if_t<\n !(std::is_same<T, U>{} || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n && (std::is_same<T, boolean>{}\n || std::is_same<T, integer>{}\n || std::is_same<T, count>{}\n || std::is_same<T, real>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, std::string>{})\n >\n operator()(T&, const U&) const {\n \/\/ impossible\n }\n\n void operator()(timestamp&, timestamp) const {\n \/\/ impossible\n }\n\n void operator()(timestamp& ts, timespan x) const {\n ts += x;\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, timestamp>{}\n || std::is_same<T, timespan>{}\n || std::is_same<T, vector>{}\n || std::is_same<T, set>{})\n >\n operator()(timestamp&, const T&) const {\n \/\/ impossible\n }\n\n template <class T, class U>\n std::enable_if_t<\n !(std::is_same<U, vector>{} || std::is_same<U, set>{})\n && (std::is_same<T, pattern>{}\n || std::is_same<T, address>{}\n || std::is_same<T, subnet>{}\n || std::is_same<T, port>{}\n || std::is_same<T, enumeration>{}\n || std::is_same<T, map>{})\n >\n operator()(T&, const U&) const {\n \/\/ impossible\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n >\n operator()(vector& lhs, const T& rhs) const {\n lhs.emplace_back(rhs);\n }\n\n void operator()(vector& lhs, const vector& rhs) const {\n std::copy(rhs.begin(), rhs.end(), std::back_inserter(lhs));\n }\n\n template <class T>\n std::enable_if_t<\n !(std::is_same<T, vector>{} || std::is_same<T, set>{})\n >\n operator()(set& lhs, const T& rhs) const {\n lhs.emplace(rhs);\n }\n\n void operator()(set& lhs, const set& rhs) const {\n std::copy(rhs.begin(), rhs.end(), std::inserter(lhs, lhs.end()));\n }\n\n template <class T>\n std::enable_if_t<!std::is_same<T, vector>{}>\n operator()(T&, const vector& rhs) const {\n vector v;\n v.reserve(rhs.size() + 1);\n v.push_back(std::move(self));\n std::copy(rhs.begin(), rhs.end(), std::back_inserter(v));\n self = std::move(v);\n }\n\n template <class T>\n std::enable_if_t<!std::is_same<T, set>{}>\n operator()(T&, const set& rhs) const {\n set s;\n s.insert(std::move(self));\n std::copy(rhs.begin(), rhs.end(), std::inserter(s, s.end()));\n self = std::move(s);\n }\n\n data& self;\n};\n\n} \/\/ namespace <anonymous>\n\ndata& data::operator+=(const data& rhs) {\n caf::visit(adder{*this}, *this, rhs);\n return *this;\n}\n\nbool operator==(const data& lhs, const data& rhs) {\n return lhs.data_ == rhs.data_;\n}\n\nbool operator<(const data& lhs, const data& rhs) {\n return lhs.data_ < rhs.data_;\n}\n\nbool evaluate(const data& lhs, relational_operator op, const data& rhs) {\n auto check_match = [](const auto& x, const auto& y) {\n return caf::visit(detail::overload(\n [](const auto&, const auto&) {\n return false;\n },\n [](const std::string& lhs, const pattern& rhs) {\n return rhs.match(lhs);\n }\n ), x, y);\n };\n auto check_in = [](const auto& x, const auto& y) {\n return caf::visit(detail::overload(\n [](const auto&, const auto&) {\n return false;\n },\n [](const std::string& lhs, const std::string& rhs) {\n return rhs.find(lhs) != std::string::npos;\n },\n [](const std::string& lhs, const pattern& rhs) {\n return rhs.search(lhs);\n },\n [](const address& lhs, const subnet& rhs) {\n return rhs.contains(lhs);\n },\n [](const subnet& lhs, const subnet& rhs) {\n return rhs.contains(lhs);\n },\n [](const auto& lhs, const vector& rhs) {\n return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end();\n },\n [](const auto& lhs, const set& rhs) {\n return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end();\n }\n ), x, y);\n };\n switch (op) {\n default:\n VAST_ASSERT(!\"missing case\");\n return false;\n case match:\n return check_match(lhs, rhs);\n case not_match:\n return !check_match(lhs, rhs);\n case in:\n return check_in(lhs, rhs);\n case not_in:\n return !check_in(lhs, rhs);\n case ni:\n return check_in(rhs, lhs);\n case not_ni:\n return !check_in(rhs, lhs);\n case equal:\n return lhs == rhs;\n case not_equal:\n return lhs != rhs;\n case less:\n return lhs < rhs;\n case less_equal:\n return lhs <= rhs;\n case greater:\n return lhs > rhs;\n case greater_equal:\n return lhs >= rhs;\n }\n}\n\nbool is_basic(const data& x) {\n return caf::visit(detail::overload(\n [](const auto&) { return true; },\n [](const enumeration&) { return false; },\n [](const vector&) { return false; },\n [](const set&) { return false; },\n [](const map&) { return false; }\n ), x);\n}\n\nbool is_complex(const data& x) {\n return !is_basic(x);\n}\n\nbool is_recursive(const data& x) {\n return caf::visit(detail::overload(\n [](const auto&) { return false; },\n [](const vector&) { return true; },\n [](const set&) { return true; },\n [](const map&) { return true; }\n ), x);\n}\n\nbool is_container(const data& x) {\n return is_recursive(x);\n}\n\nconst data* get(const vector& v, const offset& o) {\n const vector* x = &v;\n for (size_t i = 0; i < o.size(); ++i) {\n auto& idx = o[i];\n if (idx >= x->size())\n return nullptr;\n auto d = &(*x)[idx];\n if (i + 1 == o.size())\n return d;\n x = caf::get_if<vector>(d);\n if (!x)\n return nullptr;\n }\n return nullptr;\n}\n\nconst data* get(const data& d, const offset& o) {\n if (auto v = caf::get_if<vector>(&d))\n return get(*v, o);\n return nullptr;\n}\n\nnamespace {\n\ntemplate <class Iterator>\nvector flatten(Iterator& f, Iterator l) {\n vector xs;\n xs.reserve(l - f);\n for (; f != l; ++f) {\n auto&& x = *f;\n if (auto v = caf::get_if<vector>(&x)) {\n auto begin = Iterator{v->begin()};\n auto end = Iterator{v->end()};\n auto ys = flatten(begin, end);\n xs.insert(xs.end(),\n std::make_move_iterator(ys.begin()),\n std::make_move_iterator(ys.end()));\n } else {\n xs.push_back(*f);\n }\n }\n return xs;\n}\n\ntemplate <class Iterator>\ncaf::optional<vector> unflatten(Iterator& f, Iterator l, const record_type& rec) {\n vector xs;\n xs.reserve(rec.fields.size());\n for (auto& field : rec.fields)\n if (f == l) {\n return {};\n } else if (auto rt = caf::get_if<record_type>(&field.type)) {\n auto ys = unflatten(f, l, *rt);\n if (!ys)\n return ys;\n xs.push_back(std::move(*ys));\n } else {\n xs.push_back(*f++);\n }\n return xs;\n}\n\n} \/\/ namespace <anonymous>\n\nvector flatten(const vector& xs) {\n auto f = xs.begin();\n auto l = xs.end();\n return flatten(f, l);\n}\n\nvector flatten(vector&& xs) {\n auto f = std::make_move_iterator(xs.begin());\n auto l = std::make_move_iterator(xs.end());\n return flatten(f, l);\n}\n\ndata flatten(const data& x) {\n auto xs = caf::get_if<vector>(&x);\n return xs ? flatten(*xs) : x;\n}\n\ndata flatten(data&& x) {\n auto xs = caf::get_if<vector>(&x);\n return xs ? flatten(std::move(*xs)) : x;\n}\n\ncaf::optional<vector> unflatten(const vector& xs, const record_type& rt) {\n auto first = xs.begin();\n auto last = xs.end();\n return unflatten(first, last, rt);\n}\n\ncaf::optional<vector> unflatten(vector&& xs, const record_type& rt) {\n auto first = std::make_move_iterator(xs.begin());\n auto last = std::make_move_iterator(xs.end());\n return unflatten(first, last, rt);\n}\n\ncaf::optional<vector> unflatten(const data& x, const type& t) {\n auto xs = caf::get_if<vector>(&x);\n auto rt = caf::get_if<record_type>(&t);\n return xs && rt ? unflatten(*xs, *rt) : caf::optional<vector>{};\n}\n\ncaf::optional<vector> unflatten(data&& x, const type& t) {\n auto xs = caf::get_if<vector>(&x);\n auto rt = caf::get_if<record_type>(&t);\n return xs && rt ? unflatten(std::move(*xs), *rt) : caf::optional<vector>{};\n}\n\nnamespace {\n\njson jsonize(const data& x) {\n return caf::visit(detail::overload(\n [&](const auto& y) { return to_json(y); },\n [&](caf::none_t) { return json{}; },\n [&](const std::string& str) { return json{str}; }\n ), x);\n}\n\n} \/\/ namespace <anonymous>\n\nbool convert(const vector& v, json& j) {\n json::array a(v.size());\n for (auto i = 0u; i < v.size(); ++i)\n a[i] = jsonize(v[i]);\n j = std::move(a);\n return true;\n}\n\nbool convert(const set& s, json& j) {\n json::array a(s.size());\n auto i = 0u;\n for (auto& x : s)\n a[i++] = jsonize(x);\n j = std::move(a);\n return true;\n}\n\nbool convert(const map& t, json& j) {\n json::array values;\n for (auto& p : t) {\n json::array a;\n a.emplace_back(jsonize(p.first));\n a.emplace_back(jsonize(p.second));\n values.emplace_back(std::move(a));\n };\n j = std::move(values);\n return true;\n}\n\nbool convert(const data& d, json& j) {\n j = jsonize(d);\n return true;\n}\n\nbool convert(const data& d, json& j, const type& t) {\n auto v = caf::get_if<vector>(&d);\n auto rt = caf::get_if<record_type>(&t);\n if (v && rt) {\n if (v->size() != rt->fields.size())\n return false;\n json::object o;\n for (auto i = 0u; i < v->size(); ++i) {\n auto& f = rt->fields[i];\n if (!convert((*v)[i], o[f.name], f.type))\n return false;\n }\n j = std::move(o);\n return true;\n }\n return convert(d, j);\n}\n\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include <string.h>\n#include \"tests\/fff.h\"\nDEFINE_FFF_GLOBALS;\n\n\nextern \"C\" {\n#undef LOG_TAG\n#include \"..\/..\/utl\/utl_thread.c\"\n#undef LOG_TAG\n#include \"..\/..\/utl\/utl_log.c\"\n#include \"..\/..\/utl\/utl_dbg.c\"\n#include \"..\/..\/utl\/utl_buf.c\"\n#include \"..\/..\/utl\/utl_push.c\"\n#include \"..\/..\/utl\/utl_time.c\"\n#include \"..\/..\/utl\/utl_int.c\"\n#include \"..\/..\/utl\/utl_str.c\"\n#include \"..\/..\/utl\/utl_mem.c\"\n#undef LOG_TAG\n#include \"..\/..\/btc\/btc.c\"\n#include \"..\/..\/btc\/btc_buf.c\"\n#include \"..\/..\/btc\/btc_extkey.c\"\n#include \"..\/..\/btc\/btc_keys.c\"\n#include \"..\/..\/btc\/btc_sw.c\"\n#include \"..\/..\/btc\/btc_sig.c\"\n#include \"..\/..\/btc\/btc_script.c\"\n#include \"..\/..\/btc\/btc_tx.c\"\n#include \"..\/..\/btc\/btc_tx_buf.c\"\n#include \"..\/..\/btc\/btc_crypto.c\"\n#include \"..\/..\/btc\/segwit_addr.c\"\n#include \"..\/..\/btc\/btc_segwit_addr.c\"\n#include \"..\/..\/btc\/btc_test_util.c\"\n\n#undef LOG_TAG\n#include \"ln_derkey.c\"\n#include \"ln_derkey_ex.c\"\n#include \"ln_msg_anno.c\"\n#include \"ln_msg_close.c\"\n\/\/#include \"ln_msg_establish.c\"\n#include \"ln_msg_normalope.c\"\n#include \"ln_msg_setupctl.c\"\n#include \"ln_node.c\"\n#include \"ln_onion.c\"\n#include \"ln_script.c\"\n#include \"ln_noise.c\"\n#include \"ln_signer.c\"\n#include \"ln_invoice.c\"\n#include \"ln_print.c\"\n#include \"ln_update.c\"\n#include \"ln_update_info.c\"\n\n#include \"ln.c\"\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/FAKE関数\n\n\/\/ FAKE_VOID_FUNC(ln_db_preimage_cur_close, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_cnlupd_load, utl_buf_t *, uint32_t *, uint64_t, uint8_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_del, const uint8_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_cur_open, void **);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_cur_get, void *, bool *, ln_db_preimage_t *, const char**);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_channel_search, ln_db_func_cmp_t, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_channel_search_readonly, ln_db_func_cmp_t, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_payment_hash_save, const uint8_t*, const uint8_t*, ln_commit_tx_output_type_t, uint32_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_search, ln_db_func_preimage_t, void*);\n\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_open_channel_write, utl_buf_t *, const ln_open_channel_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_open_channel_read, ln_open_channel_t*, const uint8_t*, uint16_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_accept_channel_write, utl_buf_t *, const ln_msg_accept_channel_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_accept_channel_read, ln_msg_accept_channel_t *, const uint8_t *, uint16_t );\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_created_write, utl_buf_t *, const ln_funding_writed_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_created_read, ln_msg_funding_created_t *, const uint8_t *, uint16_t );\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_signed_write, utl_buf_t *, const ln_msg_funding_signed_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_signed_read, ln_msg_funding_signed_t *, const uint8_t *, uint16_t );\ntypedef uint8_t (fake_sig_t)[LN_SZ_SIGNATURE];\nFAKE_VALUE_FUNC(bool, ln_commit_tx_create_remote, ln_commit_info_t *, const ln_update_info_t *, const ln_derkey_local_keys_t *, const ln_derkey_remote_keys_t *, fake_sig_t **);\nFAKE_VALUE_FUNC(bool, ln_commit_tx_create_remote_close, const ln_commit_info_t *, const ln_update_info_t *, const ln_derkey_local_keys_t *, const ln_derkey_remote_keys_t *, const utl_buf_t *, ln_close_force_t *);\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ln: public testing::Test {\nprotected:\n virtual void SetUp() {\n \/\/utl_log_init_stderr();\n \/\/ RESET_FAKE(ln_db_preimage_cur_close)\n \/\/ RESET_FAKE(ln_db_cnlupd_load)\n \/\/ RESET_FAKE(ln_db_preimage_del)\n \/\/ RESET_FAKE(ln_db_preimage_cur_open)\n \/\/ RESET_FAKE(ln_db_preimage_cur_get)\n \/\/ RESET_FAKE(ln_db_channel_search)\n \/\/ RESET_FAKE(ln_db_channel_search_readonly)\n \/\/ RESET_FAKE(ln_db_payment_hash_save)\n \/\/ RESET_FAKE(ln_db_preimage_search)\n \/\/ RESET_FAKE(ln_msg_open_channel_read)\n \/\/ RESET_FAKE(ln_msg_accept_channel_write)\n \/\/ RESET_FAKE(ln_msg_accept_channel_read)\n \/\/ RESET_FAKE(ln_msg_funding_created_write)\n \/\/ RESET_FAKE(ln_msg_funding_created_read)\n \/\/ RESET_FAKE(ln_msg_funding_signed_write)\n \/\/ RESET_FAKE(ln_msg_funding_signed_read)\n RESET_FAKE(ln_commit_tx_create_remote)\n\n ln_commit_tx_create_remote_fake.return_val = true;\n ln_commit_tx_create_remote_close_fake.return_val = true;\n utl_dbg_malloc_cnt_reset();\n btc_init(BTC_BLOCK_CHAIN_BTCTEST, true);\n }\n\n virtual void TearDown() {\n ln_node_term();\n btc_term();\n ASSERT_EQ(0, utl_dbg_malloc_cnt());\n }\n\npublic:\n static void DumpBin(const uint8_t *pData, uint16_t Len)\n {\n for (uint16_t lp = 0; lp < Len; lp++) {\n printf(\"%02x\", pData[lp]);\n }\n printf(\"\\n\");\n }\n static bool DumpCheck(const void *pData, uint32_t Len, uint8_t Fill)\n {\n bool ret = true;\n const uint8_t *p = (const uint8_t *)pData;\n for (uint32_t lp = 0; lp < Len; lp++) {\n if (p[lp] != Fill) {\n ret = false;\n break;\n }\n }\n return ret;\n }\n static void LnCallbackType(ln_cb_type_t Type, void *pCommonParam, void *pTypeSpecificParam) {\n (void)pCommonParam; (void)pTypeSpecificParam;\n const char *p_str;\n switch (Type) {\n case LN_CB_TYPE_NOTIFY_ERROR: p_str = \"LN_CB_TYPE_NOTIFY_ERROR\"; break;\n case LN_CB_TYPE_NOTIFY_INIT_RECV: p_str = \"LN_CB_TYPE_NOTIFY_INIT_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_REESTABLISH_RECV: p_str = \"LN_CB_TYPE_NOTIFY_REESTABLISH_RECV\"; break;\n case LN_CB_TYPE_SIGN_FUNDING_TX: p_str = \"LN_CB_TYPE_SIGN_FUNDING_TX\"; break;\n case LN_CB_TYPE_WAIT_FUNDING_TX: p_str = \"LN_CB_TYPE_WAIT_FUNDING_TX\"; break;\n case LN_CB_TYPE_NOTIFY_FUNDING_LOCKED_RECV: p_str = \"LN_CB_TYPE_NOTIFY_FUNDING_LOCKED_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_ANNODB_UPDATE: p_str = \"LN_CB_TYPE_NOTIFY_ANNODB_UPDATE\"; break;\n case LN_CB_TYPE_NOTIFY_ADDFINAL_HTLC_RECV: p_str = \"LN_CB_TYPE_NOTIFY_ADDFINAL_HTLC_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_FULFILL_HTLC_RECV: p_str = \"LN_CB_TYPE_NOTIFY_FULFILL_HTLC_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_REV_AND_ACK_EXCHANGE: p_str = \"LN_CB_TYPE_NOTIFY_REV_AND_ACK_EXCHANGE\"; break;\n case LN_CB_TYPE_NOTIFY_UPDATE_FEE_RECV: p_str = \"LN_CB_TYPE_NOTIFY_UPDATE_FEE_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_SHUTDOWN_RECV: p_str = \"LN_CB_TYPE_NOTIFY_SHUTDOWN_RECV\"; break;\n case LN_CB_TYPE_UPDATE_CLOSING_FEE: p_str = \"LN_CB_TYPE_UPDATE_CLOSING_FEE\"; break;\n case LN_CB_TYPE_NOTIFY_CLOSING_END: p_str = \"LN_CB_TYPE_NOTIFY_CLOSING_END\"; break;\n case LN_CB_TYPE_SEND_MESSAGE: p_str = \"LN_CB_TYPE_SEND_MESSAGE\"; break;\n case LN_CB_TYPE_GET_LATEST_FEERATE: p_str = \"LN_CB_TYPE_GET_LATEST_FEERATE\"; break;\n case LN_CB_TYPE_GET_BLOCK_COUNT: p_str = \"LN_CB_TYPE_GET_BLOCK_COUNT\"; break;\n default:\n p_str = \"unknown\";\n }\n printf(\"*** callback: %s(%d)\\n\", p_str, Type);\n }\n static void LnInit(ln_channel_t *pChannel)\n {\n ln_anno_param_t anno_param;\n\n memset(pChannel, 0xcc, sizeof(ln_channel_t));\n anno_param.cltv_expiry_delta = 10;\n anno_param.htlc_minimum_msat = 1000;\n anno_param.fee_base_msat = 20;\n anno_param.fee_prop_millionths = 200;\n ln_init(pChannel, &anno_param, NULL, (ln_callback_t)0x123456, NULL);\n pChannel->commit_info_local.dust_limit_sat = BTC_DUST_LIMIT;\n pChannel->commit_info_local.htlc_minimum_msat = 0;\n pChannel->commit_info_local.max_accepted_htlcs = 10;\n pChannel->commit_info_local.local_msat = 1000000;\n pChannel->commit_info_local.remote_msat = 1000000;\n pChannel->commit_info_remote.dust_limit_sat = BTC_DUST_LIMIT;\n pChannel->commit_info_remote.htlc_minimum_msat = 0;\n pChannel->commit_info_remote.max_accepted_htlcs = 10;\n pChannel->commit_info_remote.local_msat = 1000000;\n pChannel->commit_info_remote.remote_msat = 1000000;\n btc_tx_init(&pChannel->funding_info.tx_data);\n utl_buf_init(&pChannel->funding_info.wit_script);\n pChannel->p_callback = LnCallbackType;\n }\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_F(ln, init)\n{\n ln_channel_t channel;\n ln_anno_param_t anno_param;\n\n memset(&channel, 0xcc, sizeof(channel));\n anno_param.cltv_expiry_delta = 10;\n anno_param.htlc_minimum_msat = 1000;\n anno_param.fee_base_msat = 20;\n anno_param.fee_prop_millionths = 200;\n ln_init(&channel, &anno_param, NULL, (ln_callback_t)0x123456, (void *)0x654321);\n\n ASSERT_EQ(LN_STATUS_NONE, channel.status);\n for (uint16_t idx = 0; idx < LN_UPDATE_MAX; idx++) {\n ASSERT_TRUE(utl_mem_is_all_zero(\n &channel.update_info.updates[idx].state, sizeof(channel.update_info.updates[idx].state)));\n }\n ASSERT_EQ(0x654321, channel.p_param);\n ASSERT_EQ(0x123456, channel.p_callback);\n\n ln_term(&channel);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_F(ln, calc_short1)\n{\n uint64_t sid = ln_short_channel_id_calc(0x12345678, 0x9abcdef0, 0x6543210f);\n ASSERT_EQ(0x345678bcdef0210f, sid);\n}\n\n\nTEST_F(ln, calc_short2)\n{\n uint64_t sid = ln_short_channel_id_calc(1116104, 33, 0);\n ASSERT_EQ(0x1107c80000210000, sid);\n}\n<commit_msg>tests<commit_after>#include \"gtest\/gtest.h\"\n#include <string.h>\n#include \"tests\/fff.h\"\nDEFINE_FFF_GLOBALS;\n\n\nextern \"C\" {\n#undef LOG_TAG\n#include \"..\/..\/utl\/utl_thread.c\"\n#undef LOG_TAG\n#include \"..\/..\/utl\/utl_log.c\"\n#include \"..\/..\/utl\/utl_dbg.c\"\n#include \"..\/..\/utl\/utl_buf.c\"\n#include \"..\/..\/utl\/utl_push.c\"\n#include \"..\/..\/utl\/utl_time.c\"\n#include \"..\/..\/utl\/utl_int.c\"\n#include \"..\/..\/utl\/utl_str.c\"\n#include \"..\/..\/utl\/utl_mem.c\"\n#undef LOG_TAG\n#include \"..\/..\/btc\/btc.c\"\n#include \"..\/..\/btc\/btc_buf.c\"\n#include \"..\/..\/btc\/btc_extkey.c\"\n#include \"..\/..\/btc\/btc_keys.c\"\n#include \"..\/..\/btc\/btc_sw.c\"\n#include \"..\/..\/btc\/btc_sig.c\"\n#include \"..\/..\/btc\/btc_script.c\"\n#include \"..\/..\/btc\/btc_tx.c\"\n#include \"..\/..\/btc\/btc_tx_buf.c\"\n#include \"..\/..\/btc\/btc_crypto.c\"\n#include \"..\/..\/btc\/segwit_addr.c\"\n#include \"..\/..\/btc\/btc_segwit_addr.c\"\n#include \"..\/..\/btc\/btc_test_util.c\"\n\n#undef LOG_TAG\n#include \"ln_derkey.c\"\n#include \"ln_derkey_ex.c\"\n#include \"ln_msg_anno.c\"\n#include \"ln_msg_close.c\"\n\/\/#include \"ln_msg_establish.c\"\n#include \"ln_msg_normalope.c\"\n#include \"ln_msg_setupctl.c\"\n#include \"ln_node.c\"\n#include \"ln_onion.c\"\n#include \"ln_script.c\"\n#include \"ln_noise.c\"\n#include \"ln_signer.c\"\n#include \"ln_invoice.c\"\n#include \"ln_print.c\"\n#include \"ln_update.c\"\n#include \"ln_update_info.c\"\n\n#include \"ln.c\"\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/FAKE関数\n\n\/\/ FAKE_VOID_FUNC(ln_db_preimage_cur_close, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_cnlupd_load, utl_buf_t *, uint32_t *, uint64_t, uint8_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_del, const uint8_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_cur_open, void **);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_cur_get, void *, bool *, ln_db_preimage_t *, const char**);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_channel_search, ln_db_func_cmp_t, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_channel_search_readonly, ln_db_func_cmp_t, void *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_payment_hash_save, const uint8_t*, const uint8_t*, ln_commit_tx_output_type_t, uint32_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_db_preimage_search, ln_db_func_preimage_t, void*);\n\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_open_channel_write, utl_buf_t *, const ln_open_channel_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_open_channel_read, ln_open_channel_t*, const uint8_t*, uint16_t);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_accept_channel_write, utl_buf_t *, const ln_msg_accept_channel_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_accept_channel_read, ln_msg_accept_channel_t *, const uint8_t *, uint16_t );\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_created_write, utl_buf_t *, const ln_funding_writed_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_created_read, ln_msg_funding_created_t *, const uint8_t *, uint16_t );\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_signed_write, utl_buf_t *, const ln_msg_funding_signed_t *);\n\/\/ FAKE_VALUE_FUNC(bool, ln_msg_funding_signed_read, ln_msg_funding_signed_t *, const uint8_t *, uint16_t );\ntypedef uint8_t (fake_sig_t)[LN_SZ_SIGNATURE];\nFAKE_VALUE_FUNC(bool, ln_commit_tx_create_remote, ln_commit_info_t *, const ln_update_info_t *, const ln_derkey_local_keys_t *, const ln_derkey_remote_keys_t *, fake_sig_t **);\nFAKE_VALUE_FUNC(bool, ln_commit_tx_create_remote_close, const ln_commit_info_t *, const ln_update_info_t *, const ln_derkey_local_keys_t *, const ln_derkey_remote_keys_t *, const utl_buf_t *, ln_close_force_t *);\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ln: public testing::Test {\nprotected:\n virtual void SetUp() {\n \/\/utl_log_init_stderr();\n \/\/ RESET_FAKE(ln_db_preimage_cur_close)\n \/\/ RESET_FAKE(ln_db_cnlupd_load)\n \/\/ RESET_FAKE(ln_db_preimage_del)\n \/\/ RESET_FAKE(ln_db_preimage_cur_open)\n \/\/ RESET_FAKE(ln_db_preimage_cur_get)\n \/\/ RESET_FAKE(ln_db_channel_search)\n \/\/ RESET_FAKE(ln_db_channel_search_readonly)\n \/\/ RESET_FAKE(ln_db_payment_hash_save)\n \/\/ RESET_FAKE(ln_db_preimage_search)\n \/\/ RESET_FAKE(ln_msg_open_channel_read)\n \/\/ RESET_FAKE(ln_msg_accept_channel_write)\n \/\/ RESET_FAKE(ln_msg_accept_channel_read)\n \/\/ RESET_FAKE(ln_msg_funding_created_write)\n \/\/ RESET_FAKE(ln_msg_funding_created_read)\n \/\/ RESET_FAKE(ln_msg_funding_signed_write)\n \/\/ RESET_FAKE(ln_msg_funding_signed_read)\n RESET_FAKE(ln_commit_tx_create_remote)\n\n ln_commit_tx_create_remote_fake.return_val = true;\n ln_commit_tx_create_remote_close_fake.return_val = true;\n utl_dbg_malloc_cnt_reset();\n btc_init(BTC_BLOCK_CHAIN_BTCTEST, true);\n }\n\n virtual void TearDown() {\n ln_node_term();\n btc_term();\n ASSERT_EQ(0, utl_dbg_malloc_cnt());\n }\n\npublic:\n static void DumpBin(const uint8_t *pData, uint16_t Len)\n {\n for (uint16_t lp = 0; lp < Len; lp++) {\n printf(\"%02x\", pData[lp]);\n }\n printf(\"\\n\");\n }\n static bool DumpCheck(const void *pData, uint32_t Len, uint8_t Fill)\n {\n bool ret = true;\n const uint8_t *p = (const uint8_t *)pData;\n for (uint32_t lp = 0; lp < Len; lp++) {\n if (p[lp] != Fill) {\n ret = false;\n break;\n }\n }\n return ret;\n }\n static void LnCallbackType(ln_cb_type_t Type, void *pCommonParam, void *pTypeSpecificParam) {\n (void)pCommonParam; (void)pTypeSpecificParam;\n const char *p_str;\n switch (Type) {\n case LN_CB_TYPE_NOTIFY_ERROR: p_str = \"LN_CB_TYPE_NOTIFY_ERROR\"; break;\n case LN_CB_TYPE_NOTIFY_INIT_RECV: p_str = \"LN_CB_TYPE_NOTIFY_INIT_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_REESTABLISH_RECV: p_str = \"LN_CB_TYPE_NOTIFY_REESTABLISH_RECV\"; break;\n case LN_CB_TYPE_SIGN_FUNDING_TX: p_str = \"LN_CB_TYPE_SIGN_FUNDING_TX\"; break;\n case LN_CB_TYPE_WAIT_FUNDING_TX: p_str = \"LN_CB_TYPE_WAIT_FUNDING_TX\"; break;\n case LN_CB_TYPE_NOTIFY_FUNDING_LOCKED_RECV: p_str = \"LN_CB_TYPE_NOTIFY_FUNDING_LOCKED_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_ANNODB_UPDATE: p_str = \"LN_CB_TYPE_NOTIFY_ANNODB_UPDATE\"; break;\n case LN_CB_TYPE_NOTIFY_ADDFINAL_HTLC_RECV: p_str = \"LN_CB_TYPE_NOTIFY_ADDFINAL_HTLC_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_FULFILL_HTLC_RECV: p_str = \"LN_CB_TYPE_NOTIFY_FULFILL_HTLC_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_REV_AND_ACK_EXCHANGE: p_str = \"LN_CB_TYPE_NOTIFY_REV_AND_ACK_EXCHANGE\"; break;\n case LN_CB_TYPE_NOTIFY_UPDATE_FEE_RECV: p_str = \"LN_CB_TYPE_NOTIFY_UPDATE_FEE_RECV\"; break;\n case LN_CB_TYPE_NOTIFY_SHUTDOWN_RECV: p_str = \"LN_CB_TYPE_NOTIFY_SHUTDOWN_RECV\"; break;\n case LN_CB_TYPE_UPDATE_CLOSING_FEE: p_str = \"LN_CB_TYPE_UPDATE_CLOSING_FEE\"; break;\n case LN_CB_TYPE_NOTIFY_CLOSING_END: p_str = \"LN_CB_TYPE_NOTIFY_CLOSING_END\"; break;\n case LN_CB_TYPE_SEND_MESSAGE: p_str = \"LN_CB_TYPE_SEND_MESSAGE\"; break;\n case LN_CB_TYPE_GET_LATEST_FEERATE: p_str = \"LN_CB_TYPE_GET_LATEST_FEERATE\"; break;\n case LN_CB_TYPE_GET_BLOCK_COUNT: p_str = \"LN_CB_TYPE_GET_BLOCK_COUNT\"; break;\n default:\n p_str = \"unknown\";\n }\n printf(\"*** callback: %s(%d)\\n\", p_str, Type);\n }\n static void LnInit(ln_channel_t *pChannel)\n {\n ln_anno_param_t anno_param;\n\n memset(pChannel, 0xcc, sizeof(ln_channel_t));\n anno_param.cltv_expiry_delta = 10;\n anno_param.htlc_minimum_msat = 1000;\n anno_param.fee_base_msat = 20;\n anno_param.fee_prop_millionths = 200;\n ln_init(pChannel, &anno_param, NULL, (ln_callback_t)0x123456, NULL);\n pChannel->commit_info_local.dust_limit_sat = BTC_DUST_LIMIT;\n pChannel->commit_info_local.htlc_minimum_msat = 0;\n pChannel->commit_info_local.max_accepted_htlcs = 10;\n pChannel->commit_info_local.local_msat = 1000000;\n pChannel->commit_info_local.remote_msat = 1000000;\n pChannel->commit_info_remote.dust_limit_sat = BTC_DUST_LIMIT;\n pChannel->commit_info_remote.htlc_minimum_msat = 0;\n pChannel->commit_info_remote.max_accepted_htlcs = 10;\n pChannel->commit_info_remote.local_msat = 1000000;\n pChannel->commit_info_remote.remote_msat = 1000000;\n btc_tx_init(&pChannel->funding_info.tx_data);\n utl_buf_init(&pChannel->funding_info.wit_script);\n pChannel->p_callback = LnCallbackType;\n }\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_F(ln, init)\n{\n ln_channel_t channel;\n ln_anno_param_t anno_param;\n\n memset(&channel, 0xcc, sizeof(channel));\n anno_param.cltv_expiry_delta = 10;\n anno_param.htlc_minimum_msat = 1000;\n anno_param.fee_base_msat = 20;\n anno_param.fee_prop_millionths = 200;\n ln_init(&channel, &anno_param, NULL, (ln_callback_t)0x123456, (void *)0x654321);\n\n ASSERT_EQ(LN_STATUS_NONE, channel.status);\n for (uint16_t idx = 0; idx < LN_UPDATE_MAX; idx++) {\n ASSERT_TRUE(utl_mem_is_all_zero(\n &channel.update_info.updates[idx].state, sizeof(channel.update_info.updates[idx].state)));\n }\n ASSERT_EQ(0x654321, channel.p_param);\n ASSERT_EQ(0x123456, channel.p_callback);\n\n ln_term(&channel);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_F(ln, calc_short1)\n{\n uint64_t sid = ln_short_channel_id_calc(0x12345678, 0x9abcdef0, 0x6543210f);\n ASSERT_EQ(0x345678bcdef0210f, sid);\n}\n\n\nTEST_F(ln, calc_short2)\n{\n uint64_t sid = ln_short_channel_id_calc(1116104, 33, 0);\n ASSERT_EQ(0x1107c80000210000, sid);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTEST_F(ln, ln_feerate_limit_set)\n{\n ln_feerate_limit_set(65535, 0);\n ASSERT_EQ(65535, mFeerateMin);\n ASSERT_EQ(0, mFeerateMax);\n\n ln_feerate_limit_set(0, 65535);\n ASSERT_EQ(0, mFeerateMin);\n ASSERT_EQ(65535, mFeerateMax);\n}\n\n\nTEST_F(ln, ln_feerate_limit_get)\n{\n uint32_t min, max;\n\n mFeerateMin = 0;\n mFeerateMax = 0;\n ln_feerate_limit_get(&min, &max, 253);\n ASSERT_EQ(0, min);\n ASSERT_EQ(0, max);\n\n mFeerateMin = 100;\n mFeerateMax = 200;\n ln_feerate_limit_get(&min, &max, 253);\n ASSERT_EQ(253, min);\n ASSERT_EQ(506, max);\n\n mFeerateMin = 5;\n mFeerateMax = 2000;\n ln_feerate_limit_get(&min, &max, 253);\n ASSERT_EQ(12, min);\n ASSERT_EQ(5060, max);\n\n mFeerateMin = 5;\n mFeerateMax = 2000;\n ln_feerate_limit_get(&min, &max, 50000);\n ASSERT_EQ(2500, min);\n ASSERT_EQ(1000000, max);\n\n mFeerateMin = 0;\n mFeerateMax = 0;\n ln_feerate_limit_get(&min, &max, 50000);\n ASSERT_EQ(0, min);\n ASSERT_EQ(0, max);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2016 Nervana Systems Inc.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#pragma once\n\n#include <vector>\n#include <cstdio>\n#include <stdexcept>\n#include <cstring>\n#include <sstream>\n\nusing std::vector;\n\nclass RawMedia {\npublic:\n RawMedia() : _bufSize(0), _dataSize(0), _bytesPerSample(0) {\n }\n\n RawMedia(const RawMedia& media)\n : _bufSize(media._bufSize),\n _dataSize(media._dataSize),\n _bytesPerSample(media._bytesPerSample) {\n for (uint i = 0; i < media._bufs.size(); i++) {\n _bufs.push_back(new char[_bufSize]);\n memcpy(_bufs[i], media._bufs[i], _bufSize);\n }\n }\n\n virtual ~RawMedia() {\n for (uint i = 0; i < _bufs.size(); i++) {\n delete[] _bufs[i];\n }\n }\n\n void reset() {\n _dataSize = 0;\n }\n\n void addBufs(int count, int size) {\n for (int i = 0; i < count; i++) {\n _bufs.push_back(new char[size]);\n }\n _bufSize = size;\n }\n\n void fillBufs(char** frames, int frameSize) {\n \/\/ `frames` should contain one frame per channel of audio\n for (uint i = 0; i < _bufs.size(); i++) {\n memcpy(_bufs[i] + _dataSize, frames[i], frameSize);\n }\n _dataSize += frameSize;\n }\n\n void growBufs(int grow) {\n for (uint i = 0; i < _bufs.size(); i++) {\n char* buf = new char[_bufSize + grow];\n memcpy(buf, _bufs[i], _dataSize);\n delete[] _bufs[i];\n _bufs[i] = buf;\n }\n _bufSize += grow;\n }\n\n void setBytesPerSample(int bytesPerSample) {\n _bytesPerSample = bytesPerSample;\n }\n\n int size() {\n return _bufs.size();\n }\n\n char* getBuf(int idx) {\n return _bufs[idx];\n }\n\n int bufSize() {\n return _bufSize;\n }\n\n int dataSize() {\n return _dataSize;\n }\n\n int bytesPerSample() {\n return _bytesPerSample;\n }\n\n int numSamples() {\n return dataSize() \/ bytesPerSample();\n }\n\nprivate:\n vector<char*> _bufs;\n int _bufSize;\n int _dataSize;\n int _bytesPerSample;\n};\n<commit_msg>remove unused RawMedia copy constructor<commit_after>\/*\n Copyright 2016 Nervana Systems Inc.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#pragma once\n\n#include <vector>\n#include <cstdio>\n#include <stdexcept>\n#include <cstring>\n#include <sstream>\n\nusing std::vector;\n\nclass RawMedia {\npublic:\n RawMedia() : _bufSize(0), _dataSize(0), _bytesPerSample(0) {\n }\n\n virtual ~RawMedia() {\n for (uint i = 0; i < _bufs.size(); i++) {\n delete[] _bufs[i];\n }\n }\n\n void reset() {\n _dataSize = 0;\n }\n\n void addBufs(int count, int size) {\n for (int i = 0; i < count; i++) {\n _bufs.push_back(new char[size]);\n }\n _bufSize = size;\n }\n\n void fillBufs(char** frames, int frameSize) {\n \/\/ `frames` should contain one frame per channel of audio\n for (uint i = 0; i < _bufs.size(); i++) {\n memcpy(_bufs[i] + _dataSize, frames[i], frameSize);\n }\n _dataSize += frameSize;\n }\n\n void growBufs(int grow) {\n for (uint i = 0; i < _bufs.size(); i++) {\n char* buf = new char[_bufSize + grow];\n memcpy(buf, _bufs[i], _dataSize);\n delete[] _bufs[i];\n _bufs[i] = buf;\n }\n _bufSize += grow;\n }\n\n void setBytesPerSample(int bytesPerSample) {\n _bytesPerSample = bytesPerSample;\n }\n\n int size() {\n return _bufs.size();\n }\n\n char* getBuf(int idx) {\n return _bufs[idx];\n }\n\n int bufSize() {\n return _bufSize;\n }\n\n int dataSize() {\n return _dataSize;\n }\n\n int bytesPerSample() {\n return _bytesPerSample;\n }\n\n int numSamples() {\n return dataSize() \/ bytesPerSample();\n }\n\nprivate:\n vector<char*> _bufs;\n int _bufSize;\n int _dataSize;\n int _bytesPerSample;\n};\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++ -*-\n $Id: KDGanttSemiSizingControl.cpp,v 1.6 2005\/10\/11 13:59:02 lutz Exp $\n*\/\n\n\/****************************************************************************\n ** Copyright (C) 2002-2004 Klarälvdalens Datakonsult AB. All rights reserved.\n **\n ** This file is part of the KDGantt library.\n **\n ** This file may be used under the terms of the GNU General Public\n ** License versions 2.0 or 3.0 as published by the Free Software\n ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3\n ** included in the packaging of this file. Alternatively you may (at\n ** your option) use any later version of the GNU General Public\n ** License if such license has been publicly approved by\n ** Klarälvdalens Datakonsult AB (or its successors, if any).\n ** \n ** This file is provided \"AS IS\" with NO WARRANTY OF ANY KIND,\n ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR\n ** A PARTICULAR PURPOSE. Klarälvdalens Datakonsult AB reserves all rights\n ** not expressly granted herein.\n ** \n ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** As a special exception, permission is given to link this program\n ** with any edition of Qt, and distribute the resulting executable,\n ** without including the source code for Qt in the source distribution.\n **\n **********************************************************************\/\n\n\n#include \"KDGanttSemiSizingControl.h\"\n#include <QPushButton>\n#include <QPainter>\n#include <QBitmap>\n\n#include <QWhatsThis>\n\/*!\n \\class KDGanttSemiSizingControl KDGanttSemiSizingControl.h\n This class provides exactly one child widget with a button for\n minimizing and restoring. You can also specify a so-called minimize\n widget that will be shown in place of the child widget while the\n latter one is minimized. While the child widget is not minimized,\n the minimize widget will not be visible.\n\n If you add more than one child widget (besides the minimize widget),\n only the last one added will be visible.\n*\/\n\n\n\/*!\n Constructs an empty semi sizing control with horizontal\n orientation and the control arrow button on top of the controlled\n widget.\n\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( QWidget* parent ) :\n KDGanttSizingControl( parent ), _orient( Qt::Horizontal ),\n _arrowPos( Before ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Constructs an empty semi sizing control with the specified\n orientation and the control arrow button either on top or left of\n the controlled widget (depending on the orientation).\n\n \\param orientation the orientation of the splitter\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( Qt::Orientation orientation,\n QWidget* parent ):\n KDGanttSizingControl( parent ), _orient( orientation ),\n _arrowPos( Before ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Constructs an empty semi sizing control with the specified\n orientation and position of the control arrow button.\n\n \\param arrowPosition specifies whether the control arrow button\n should appear before or after the controlled widget\n \\param orientation the orientation of the splitter\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( ArrowPosition arrowPosition,\n Qt::Orientation orientation,\n QWidget* parent ):\n KDGanttSizingControl( parent ), _orient( orientation ),\n _arrowPos( arrowPosition ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Specifies the widget that should be shown while the child widget is\n minimized. This so-called minimize widget should be a child widget\n of the KDGanttSemiSizingControl.\n\n \\param widget the minimize widget\n \\sa minimizedWidget()\n*\/\n\nvoid KDGanttSemiSizingControl::setMinimizedWidget( QWidget* widget )\n{\n _minimizedWidget = widget;\n if( _minimizedWidget ) _minimizedWidget->hide();\n setup();\n}\n\n\n\/*!\n Returns the widget that is shown while the child widget is\n minimized.\n\n \\return the minimize widget\n \\sa setMinimizedWidget()\n*\/\n\nQWidget* KDGanttSemiSizingControl::minimizedWidget() const\n{\n return _minimizedWidget;\n}\n\n\/*!\n Specifies the widget that should be shown while the child widget is\n maximized. This so-called maximize widget should be a child widget\n of the KDGanttSemiSizingControl.\n\n \\param widget the minimize widget\n \\sa maximizedWidget()\n*\/\n\nvoid KDGanttSemiSizingControl::setMaximizedWidget( QWidget* widget )\n{\n _maximizedWidget = widget;\n \/\/if( _maximizedWidget ) _maximizedWidget->show();\n setup();\n}\n\n\/*!\n Returns the widget that is shown while the child widget is\n maximized.\n\n \\return the maximize widget\n \\sa setMaximizedWidget()\n*\/\n\nQWidget* KDGanttSemiSizingControl::maximizedWidget() const\n{\n return _maximizedWidget;\n}\n\n\n\n\/*!\n Sets the orientation of the simple sizing control.\n\n \\param orientation the new orientation\n \\sa orientation()\n*\/\n\nvoid KDGanttSemiSizingControl::setOrientation( Qt::Orientation orientation )\n{\n if ( _orient != orientation ) {\n _orient = orientation;\n setup();\n }\n}\n\n\n\/*!\n Returns the orientation of the simple sizing control.\n \\return the orientation\n \\sa setOrientation()\n*\/\n\nQt::Orientation KDGanttSemiSizingControl::orientation() const\n{\n return _orient;\n}\n\n\n\/*!\n Returns the position of the control arrow button.\n\n \\param arrowPosition the position of the control arrow button\n \\sa arrowPosition()\n*\/\n\nvoid KDGanttSemiSizingControl::setArrowPosition( ArrowPosition arrowPosition )\n{\n if ( _arrowPos != arrowPosition ) {\n _arrowPos = arrowPosition;\n setup();\n }\n}\n\n\n\/*!\n Returns the position of the control arrow button.\n\n \\return the position of the control arrow button\n \\sa setArrowPosition()\n*\/\n\nKDGanttSemiSizingControl::ArrowPosition KDGanttSemiSizingControl::arrowPosition() const\n{\n return _arrowPos;\n}\n\n\n\/*!\n \\enum KDGanttSemiSizingControl::ArrowPosition\n\n This enum is used for specifying whether the control arrow button\n should appear before (on top of, left of) or after (below, right of)\n the controlled widget.\n*\/\n\nvoid KDGanttSemiSizingControl::init()\n{\n _but = new QPushButton( this );\n _but->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n connect( _but, SIGNAL( clicked() ), this, SLOT(changeState()) );\n _layout = 0;\n _but->setWhatsThis( \"Click on this button to show the \\nlegend at the bottom of the widget\");\n _but->setToolTip( \"Show \/ hide legend\");\n\n\n}\n\nvoid KDGanttSemiSizingControl::setup()\n{\n \/\/-------------------------------------------------- Setup layout\n delete _layout;\n QBoxLayout* butLayout; \/\/ _layout will delete me\n\n if ( _orient == Qt::Horizontal || isMinimized() )\n _layout = new QHBoxLayout( this );\n else\n _layout = new QVBoxLayout( this );\n\n if ( _orient == Qt::Vertical && !isMinimized() ) {\n butLayout = new QHBoxLayout();\n _layout->addItem( butLayout );\n } else {\n butLayout = new QVBoxLayout();\n _layout->addItem( butLayout );\n }\n\n\n \/\/---------------------------------------- Set the arrow on the button\n if ( !isMinimized() ) {\n _but->setIcon( QIcon(pixmap( Down )) );\n }\n else {\n if ( _arrowPos == Before ) {\n _but->setIcon( QIcon(pixmap( Right )) );\n }\n else {\n _but->setIcon( QIcon(pixmap( Left )) );\n }\n }\n\n \/\/------------------------------ Setup the button at the correct possition\n if ( _arrowPos == After && _orient == Qt::Vertical && !isMinimized() ) {\n butLayout->addStretch( 1 );\n butLayout->addWidget( _but, 0, Qt::AlignLeft );\n }\n else {\n butLayout->addWidget( _but, 0, Qt::AlignRight );\n butLayout->addStretch( 1 );\n }\n\n \/\/ Set widget in the correct possition\n QWidget* widget;\n \/* ************************** old code ***************\n if ( isMinimized() )\n widget = _minimizedWidget;\n else\n widget = _maximizedWidget;\n if( widget ) {\n if ( _arrowPos == Before || _orient == Vertical && !isMinimized() )\n _layout->addWidget( widget, 1 );\n else\n _layout->insertWidget( 0, widget, 1 );\n\t}\n ************************************************** *\/\n \/\/ hack for the usage in KDGantt as pop-up legend widget\n \/\/ for this purpose,\n \/\/ the _maximizedWidget must be a child of the parent of this widget\n\n if ( isMinimized() ) {\n widget = _minimizedWidget;\n if( widget ) {\n\t if ( _arrowPos == Before || _orient == Qt::Vertical && !isMinimized() )\n\t _layout->addWidget( widget, 1 );\n\t else\n\t _layout->insertWidget( 0, widget, 1 );\n }\n }\n else {\n if ( _arrowPos == Before || _orient == Qt::Vertical && !isMinimized() )\n\t_layout->addStretch( 1 );\n else\n\t_layout->insertStretch( 0, 1 );\n widget = _maximizedWidget;\n \/\/ the following is only the special case\n \/\/ arrowPos == Before and _orient == Vertical\n \/\/widget->move( 0+x(), _but->height()+y());\n }\n}\n\n\n\/*!\n Restores or minimizes the child widget. \\a minimize() does exactly the\n opposite to this method.\n\n \\param restore true to restore, false to minimize\n \\sa minimize()\n*\/\n\nvoid KDGanttSemiSizingControl::restore( bool restore )\n{\n if ( ! restore ) {\n minimize( true );\n }\n else {\n if( _maximizedWidget ) _maximizedWidget->show();\n if( _minimizedWidget ) _minimizedWidget->hide();\n KDGanttSizingControl::restore( restore );\n setup();\n }\n}\n\n\/*!\n Restores or minimizes the child widget. \\a restore() does exactly the\n opposite to this method.\n\n \\param minimize true to minimize, false to restore\n \\sa restore()\n\n*\/\n\nvoid KDGanttSemiSizingControl::minimize( bool minimize )\n{\n if ( ! minimize ) {\n restore( true );\n }\n else {\n if( _minimizedWidget ) _minimizedWidget->show();\n\tif( _maximizedWidget ) _maximizedWidget->hide();\n KDGanttSizingControl::minimize( minimize );\n setup();\n }\n}\n\nQPixmap KDGanttSemiSizingControl::pixmap( Direction direction ) {\n int s = 10;\n QPixmap pix( s, s );\n pix.fill( Qt::blue );\n\n QPointArray arr;\n switch ( direction ) {\n case Up: arr.setPoints( 3, 0, s-1, s-1, s-1, 0, s\/2 ); ;break;\n case Down: arr.setPoints( 3, 0, 0, s-1, 0, s\/2, s-1 ); break;\n case Left: arr.setPoints( 3, s-1, 0, s-1, s-1, 0, s\/2 ); break;\n case Right: arr.setPoints( 3, 0,0, s-1, s\/2, 0, s-1 ); break;\n }\n#if QT_VERSION < 0x040000\n QPainter p( &pix );\n p.setPen( Qt::black );\n p.setBrush( colorGroup().button() );\n p.drawPolygon( arr );\n QBitmap bit( s, s );\n bit.fill( color0 );\n\n QPainter p2( &bit );\n p2.setPen( color1 );\n p2.setBrush( color1 );\n p2.drawPolygon( arr );\n pix.setMask( bit );\n#else\n QPainter p( &pix );\n p.setPen( Qt::black );\n p.setBrush( palette().color( QPalette::Button) );\n p.drawPolygon( arr );\n QBitmap bit( s, s );\n bit.fill( Qt::blue );\n\n QPainter p2( &bit );\n p2.setPen( Qt::red );\n p2.setBrush( Qt::red );\n p2.drawPolygon( arr );\n pix.setMask( bit );\n#endif\n return pix;\n}\n\n#include \"KDGanttSemiSizingControl.moc\"\n<commit_msg>complete with some more parentheses<commit_after>\/* -*- Mode: C++ -*-\n $Id: KDGanttSemiSizingControl.cpp,v 1.6 2005\/10\/11 13:59:02 lutz Exp $\n*\/\n\n\/****************************************************************************\n ** Copyright (C) 2002-2004 Klarälvdalens Datakonsult AB. All rights reserved.\n **\n ** This file is part of the KDGantt library.\n **\n ** This file may be used under the terms of the GNU General Public\n ** License versions 2.0 or 3.0 as published by the Free Software\n ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3\n ** included in the packaging of this file. Alternatively you may (at\n ** your option) use any later version of the GNU General Public\n ** License if such license has been publicly approved by\n ** Klarälvdalens Datakonsult AB (or its successors, if any).\n ** \n ** This file is provided \"AS IS\" with NO WARRANTY OF ANY KIND,\n ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR\n ** A PARTICULAR PURPOSE. Klarälvdalens Datakonsult AB reserves all rights\n ** not expressly granted herein.\n ** \n ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** As a special exception, permission is given to link this program\n ** with any edition of Qt, and distribute the resulting executable,\n ** without including the source code for Qt in the source distribution.\n **\n **********************************************************************\/\n\n\n#include \"KDGanttSemiSizingControl.h\"\n#include <QPushButton>\n#include <QPainter>\n#include <QBitmap>\n\n#include <QWhatsThis>\n\/*!\n \\class KDGanttSemiSizingControl KDGanttSemiSizingControl.h\n This class provides exactly one child widget with a button for\n minimizing and restoring. You can also specify a so-called minimize\n widget that will be shown in place of the child widget while the\n latter one is minimized. While the child widget is not minimized,\n the minimize widget will not be visible.\n\n If you add more than one child widget (besides the minimize widget),\n only the last one added will be visible.\n*\/\n\n\n\/*!\n Constructs an empty semi sizing control with horizontal\n orientation and the control arrow button on top of the controlled\n widget.\n\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( QWidget* parent ) :\n KDGanttSizingControl( parent ), _orient( Qt::Horizontal ),\n _arrowPos( Before ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Constructs an empty semi sizing control with the specified\n orientation and the control arrow button either on top or left of\n the controlled widget (depending on the orientation).\n\n \\param orientation the orientation of the splitter\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( Qt::Orientation orientation,\n QWidget* parent ):\n KDGanttSizingControl( parent ), _orient( orientation ),\n _arrowPos( Before ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Constructs an empty semi sizing control with the specified\n orientation and position of the control arrow button.\n\n \\param arrowPosition specifies whether the control arrow button\n should appear before or after the controlled widget\n \\param orientation the orientation of the splitter\n \\param parent the parent widget. This parameter is passed to the\n base class.\n \\param name the internal widget name. This parameter is passed to\n the base class.\n*\/\n\nKDGanttSemiSizingControl::KDGanttSemiSizingControl( ArrowPosition arrowPosition,\n Qt::Orientation orientation,\n QWidget* parent ):\n KDGanttSizingControl( parent ), _orient( orientation ),\n _arrowPos( arrowPosition ), _minimizedWidget(0), _maximizedWidget(0)\n{\n init();\n}\n\n\n\/*!\n Specifies the widget that should be shown while the child widget is\n minimized. This so-called minimize widget should be a child widget\n of the KDGanttSemiSizingControl.\n\n \\param widget the minimize widget\n \\sa minimizedWidget()\n*\/\n\nvoid KDGanttSemiSizingControl::setMinimizedWidget( QWidget* widget )\n{\n _minimizedWidget = widget;\n if( _minimizedWidget ) _minimizedWidget->hide();\n setup();\n}\n\n\n\/*!\n Returns the widget that is shown while the child widget is\n minimized.\n\n \\return the minimize widget\n \\sa setMinimizedWidget()\n*\/\n\nQWidget* KDGanttSemiSizingControl::minimizedWidget() const\n{\n return _minimizedWidget;\n}\n\n\/*!\n Specifies the widget that should be shown while the child widget is\n maximized. This so-called maximize widget should be a child widget\n of the KDGanttSemiSizingControl.\n\n \\param widget the minimize widget\n \\sa maximizedWidget()\n*\/\n\nvoid KDGanttSemiSizingControl::setMaximizedWidget( QWidget* widget )\n{\n _maximizedWidget = widget;\n \/\/if( _maximizedWidget ) _maximizedWidget->show();\n setup();\n}\n\n\/*!\n Returns the widget that is shown while the child widget is\n maximized.\n\n \\return the maximize widget\n \\sa setMaximizedWidget()\n*\/\n\nQWidget* KDGanttSemiSizingControl::maximizedWidget() const\n{\n return _maximizedWidget;\n}\n\n\n\n\/*!\n Sets the orientation of the simple sizing control.\n\n \\param orientation the new orientation\n \\sa orientation()\n*\/\n\nvoid KDGanttSemiSizingControl::setOrientation( Qt::Orientation orientation )\n{\n if ( _orient != orientation ) {\n _orient = orientation;\n setup();\n }\n}\n\n\n\/*!\n Returns the orientation of the simple sizing control.\n \\return the orientation\n \\sa setOrientation()\n*\/\n\nQt::Orientation KDGanttSemiSizingControl::orientation() const\n{\n return _orient;\n}\n\n\n\/*!\n Returns the position of the control arrow button.\n\n \\param arrowPosition the position of the control arrow button\n \\sa arrowPosition()\n*\/\n\nvoid KDGanttSemiSizingControl::setArrowPosition( ArrowPosition arrowPosition )\n{\n if ( _arrowPos != arrowPosition ) {\n _arrowPos = arrowPosition;\n setup();\n }\n}\n\n\n\/*!\n Returns the position of the control arrow button.\n\n \\return the position of the control arrow button\n \\sa setArrowPosition()\n*\/\n\nKDGanttSemiSizingControl::ArrowPosition KDGanttSemiSizingControl::arrowPosition() const\n{\n return _arrowPos;\n}\n\n\n\/*!\n \\enum KDGanttSemiSizingControl::ArrowPosition\n\n This enum is used for specifying whether the control arrow button\n should appear before (on top of, left of) or after (below, right of)\n the controlled widget.\n*\/\n\nvoid KDGanttSemiSizingControl::init()\n{\n _but = new QPushButton( this );\n _but->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n connect( _but, SIGNAL( clicked() ), this, SLOT(changeState()) );\n _layout = 0;\n _but->setWhatsThis( \"Click on this button to show the \\nlegend at the bottom of the widget\");\n _but->setToolTip( \"Show \/ hide legend\");\n\n\n}\n\nvoid KDGanttSemiSizingControl::setup()\n{\n \/\/-------------------------------------------------- Setup layout\n delete _layout;\n QBoxLayout* butLayout; \/\/ _layout will delete me\n\n if ( _orient == Qt::Horizontal || isMinimized() )\n _layout = new QHBoxLayout( this );\n else\n _layout = new QVBoxLayout( this );\n\n if ( _orient == Qt::Vertical && !isMinimized() ) {\n butLayout = new QHBoxLayout();\n _layout->addItem( butLayout );\n } else {\n butLayout = new QVBoxLayout();\n _layout->addItem( butLayout );\n }\n\n\n \/\/---------------------------------------- Set the arrow on the button\n if ( !isMinimized() ) {\n _but->setIcon( QIcon(pixmap( Down )) );\n }\n else {\n if ( _arrowPos == Before ) {\n _but->setIcon( QIcon(pixmap( Right )) );\n }\n else {\n _but->setIcon( QIcon(pixmap( Left )) );\n }\n }\n\n \/\/------------------------------ Setup the button at the correct possition\n if ( _arrowPos == After && _orient == Qt::Vertical && !isMinimized() ) {\n butLayout->addStretch( 1 );\n butLayout->addWidget( _but, 0, Qt::AlignLeft );\n }\n else {\n butLayout->addWidget( _but, 0, Qt::AlignRight );\n butLayout->addStretch( 1 );\n }\n\n \/\/ Set widget in the correct possition\n QWidget* widget;\n \/* ************************** old code ***************\n if ( isMinimized() )\n widget = _minimizedWidget;\n else\n widget = _maximizedWidget;\n if( widget ) {\n if ( _arrowPos == Before || _orient == Vertical && !isMinimized() )\n _layout->addWidget( widget, 1 );\n else\n _layout->insertWidget( 0, widget, 1 );\n\t}\n ************************************************** *\/\n \/\/ hack for the usage in KDGantt as pop-up legend widget\n \/\/ for this purpose,\n \/\/ the _maximizedWidget must be a child of the parent of this widget\n\n if ( isMinimized() ) {\n widget = _minimizedWidget;\n if( widget ) {\n\t if ( _arrowPos == Before || ( _orient == Qt::Vertical && !isMinimized() ) )\n\t _layout->addWidget( widget, 1 );\n\t else\n\t _layout->insertWidget( 0, widget, 1 );\n }\n }\n else {\n if ( _arrowPos == Before || ( _orient == Qt::Vertical && !isMinimized() ) )\n\t_layout->addStretch( 1 );\n else\n\t_layout->insertStretch( 0, 1 );\n widget = _maximizedWidget;\n \/\/ the following is only the special case\n \/\/ arrowPos == Before and _orient == Vertical\n \/\/widget->move( 0+x(), _but->height()+y());\n }\n}\n\n\n\/*!\n Restores or minimizes the child widget. \\a minimize() does exactly the\n opposite to this method.\n\n \\param restore true to restore, false to minimize\n \\sa minimize()\n*\/\n\nvoid KDGanttSemiSizingControl::restore( bool restore )\n{\n if ( ! restore ) {\n minimize( true );\n }\n else {\n if( _maximizedWidget ) _maximizedWidget->show();\n if( _minimizedWidget ) _minimizedWidget->hide();\n KDGanttSizingControl::restore( restore );\n setup();\n }\n}\n\n\/*!\n Restores or minimizes the child widget. \\a restore() does exactly the\n opposite to this method.\n\n \\param minimize true to minimize, false to restore\n \\sa restore()\n\n*\/\n\nvoid KDGanttSemiSizingControl::minimize( bool minimize )\n{\n if ( ! minimize ) {\n restore( true );\n }\n else {\n if( _minimizedWidget ) _minimizedWidget->show();\n\tif( _maximizedWidget ) _maximizedWidget->hide();\n KDGanttSizingControl::minimize( minimize );\n setup();\n }\n}\n\nQPixmap KDGanttSemiSizingControl::pixmap( Direction direction ) {\n int s = 10;\n QPixmap pix( s, s );\n pix.fill( Qt::blue );\n\n QPointArray arr;\n switch ( direction ) {\n case Up: arr.setPoints( 3, 0, s-1, s-1, s-1, 0, s\/2 ); ;break;\n case Down: arr.setPoints( 3, 0, 0, s-1, 0, s\/2, s-1 ); break;\n case Left: arr.setPoints( 3, s-1, 0, s-1, s-1, 0, s\/2 ); break;\n case Right: arr.setPoints( 3, 0,0, s-1, s\/2, 0, s-1 ); break;\n }\n#if QT_VERSION < 0x040000\n QPainter p( &pix );\n p.setPen( Qt::black );\n p.setBrush( colorGroup().button() );\n p.drawPolygon( arr );\n QBitmap bit( s, s );\n bit.fill( color0 );\n\n QPainter p2( &bit );\n p2.setPen( color1 );\n p2.setBrush( color1 );\n p2.drawPolygon( arr );\n pix.setMask( bit );\n#else\n QPainter p( &pix );\n p.setPen( Qt::black );\n p.setBrush( palette().color( QPalette::Button) );\n p.drawPolygon( arr );\n QBitmap bit( s, s );\n bit.fill( Qt::blue );\n\n QPainter p2( &bit );\n p2.setPen( Qt::red );\n p2.setBrush( Qt::red );\n p2.drawPolygon( arr );\n pix.setMask( bit );\n#endif\n return pix;\n}\n\n#include \"KDGanttSemiSizingControl.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Bareflank Hypervisor\n\/\/\n\/\/ Copyright (C) 2015 Assured Information Security, Inc.\n\/\/ Author: Rian Quinn <quinnr@ainfosec.com>\n\/\/ Author: Brendan Kerrigan <kerriganb@ainfosec.com>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <gsl\/gsl>\n\n#include <json.h>\n#include <debug.h>\n#include <exception.h>\n#include <ioctl_driver.h>\n#include <vmcall_interface.h>\n#include <driver_entry_interface.h>\n\nioctl_driver::ioctl_driver(gsl::not_null<file *> f,\n gsl::not_null<ioctl *> ctl,\n gsl::not_null<command_line_parser *> clp) :\n m_file(f),\n m_ioctl(ctl),\n m_clp(clp)\n{ }\n\nvoid\nioctl_driver::process()\n{\n switch (m_clp->cmd())\n {\n case command_line_parser::command_type::help:\n return;\n\n case command_line_parser::command_type::load:\n return this->load_vmm();\n\n case command_line_parser::command_type::unload:\n return this->unload_vmm();\n\n case command_line_parser::command_type::start:\n return this->start_vmm();\n\n case command_line_parser::command_type::stop:\n return this->stop_vmm();\n\n case command_line_parser::command_type::dump:\n return this->dump_vmm();\n\n case command_line_parser::command_type::status:\n return this->vmm_status();\n\n case command_line_parser::command_type::vmcall:\n return this->vmcall();\n }\n}\n\nvoid\nioctl_driver::load_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: unload_vmm();\n case VMM_UNLOADED: break;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n auto &&modules = json::parse(m_file->read_text(m_clp->modules()));\n\n auto ___ = gsl::on_failure([&]\n { unload_vmm(); });\n\n for (const auto &module : modules[\"modules\"])\n m_ioctl->call_ioctl_add_module(m_file->read_binary(module));\n\n m_ioctl->call_ioctl_load_vmm();\n}\n\nvoid\nioctl_driver::unload_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: break;\n case VMM_UNLOADED: break;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_unload_vmm();\n}\n\nvoid\nioctl_driver::start_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: break;\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be loaded first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_start_vmm();\n}\n\nvoid\nioctl_driver::stop_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: return;\n case VMM_UNLOADED: return;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_stop_vmm();\n}\n\nvoid\nioctl_driver::dump_vmm()\n{\n auto drr = ioctl::drr_type{};\n auto buffer = std::make_unique<char[]>(DEBUG_RING_SIZE);\n\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: break;\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be loaded first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_dump_vmm(&drr, m_clp->vcpuid());\n\n if (debug_ring_read(&drr, buffer.get(), DEBUG_RING_SIZE) > 0)\n std::cout << buffer.get();\n}\n\nvoid\nioctl_driver::vmm_status()\n{\n switch (get_status())\n {\n case VMM_UNLOADED: std::cout << \"VMM_UNLOADED\\n\"; return;\n case VMM_LOADED: std::cout << \"VMM_LOADED\\n\"; return;\n case VMM_RUNNING: std::cout << \"VMM_RUNNING\\n\"; return;\n case VMM_CORRUPT: std::cout << \"VMM_CORRUPT\\n\"; return;\n default: throw unknown_status();\n }\n}\n\nvoid\nioctl_driver::vmcall()\n{\n auto regs = m_clp->registers();\n\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: throw invalid_vmm_state(\"vmm must be running first\");\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be running first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n switch (regs.r00)\n {\n case VMCALL_VERSIONS:\n this->vmcall_versions(regs);\n break;\n\n case VMCALL_REGISTERS:\n this->vmcall_registers(regs);\n break;\n\n case VMCALL_DATA:\n this->vmcall_data(regs);\n break;\n\n case VMCALL_EVENT:\n this->vmcall_event(regs);\n break;\n\n case VMCALL_UNITTEST:\n this->vmcall_unittest(regs);\n break;\n\n default:\n throw std::logic_error(\"unknown vmcall opcode\");\n }\n}\n\nvoid\nioctl_driver::vmcall_send_regs(registers_type ®s)\n{\n m_ioctl->call_ioctl_vmcall(®s, m_clp->cpuid());\n\n if (regs.r01 != 0)\n throw ioctl_failed(IOCTL_VMCALL);\n}\n\nvoid\nioctl_driver::vmcall_versions(registers_type ®s)\n{\n this->vmcall_send_regs(regs);\n\n switch (regs.r02)\n {\n case VMCALL_VERSION_PROTOCOL:\n std::cout << \"VMCALL_VERSIONS: \" << view_as_pointer(regs.r03) << std::endl;\n break;\n\n case VMCALL_VERSION_BAREFLANK:\n std::cout << \"BAREFLANK_VERSION_MAJOR: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"BAREFLANK_VERSION_MINOR: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"BAREFLANK_VERSION_PATCH: \" << view_as_pointer(regs.r05) << std::endl;\n break;\n\n case VMCALL_VERSION_USER:\n std::cout << \"USER_VERSION_MAJOR: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"USER_VERSION_MINOR: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"USER_VERSION_PATCH: \" << view_as_pointer(regs.r05) << std::endl;\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_registers(registers_type ®s)\n{\n this->vmcall_send_regs(regs);\n\n std::cout << \"r02: \" << view_as_pointer(regs.r02) << std::endl;\n std::cout << \"r03: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"r04: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"r05: \" << view_as_pointer(regs.r05) << std::endl;\n std::cout << \"r06: \" << view_as_pointer(regs.r06) << std::endl;\n std::cout << \"r07: \" << view_as_pointer(regs.r07) << std::endl;\n std::cout << \"r08: \" << view_as_pointer(regs.r08) << std::endl;\n std::cout << \"r09: \" << view_as_pointer(regs.r09) << std::endl;\n std::cout << \"r10: \" << view_as_pointer(regs.r10) << std::endl;\n std::cout << \"r11: \" << view_as_pointer(regs.r11) << std::endl;\n std::cout << \"r12: \" << view_as_pointer(regs.r12) << std::endl;\n \/\/ std::cout << \"r13: \" << view_as_pointer(regs.r13) << std::endl;\n \/\/ std::cout << \"r14: \" << view_as_pointer(regs.r14) << std::endl;\n \/\/ std::cout << \"r15: \" << view_as_pointer(regs.r15) << std::endl;\n}\n\nvoid\nioctl_driver::vmcall_data(registers_type ®s)\n{\n switch (regs.r04)\n {\n case VMCALL_DATA_STRING_UNFORMATTED:\n case VMCALL_DATA_STRING_JSON:\n this->vmcall_data_string(regs);\n break;\n\n case VMCALL_DATA_BINARY_UNFORMATTED:\n this->vmcall_data_binary(regs);\n break;\n\n default:\n throw std::logic_error(\"unknown vmcall data type\");\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_data_string(registers_type ®s)\n{\n auto &&obuffer = std::make_unique<char[]>(VMCALL_OUT_BUFFER_SIZE);\n regs.r08 = reinterpret_cast<decltype(regs.r08)>(obuffer.get());\n regs.r09 = VMCALL_OUT_BUFFER_SIZE;\n\n vmcall_send_regs(regs);\n\n switch (regs.r07)\n {\n case VMCALL_DATA_STRING_JSON:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n std::cout << \"received from vmm: \" << json::parse(std::string(obuffer.get(), regs.r09)) << '\\n';\n break;\n\n case VMCALL_DATA_STRING_UNFORMATTED:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n std::cout << \"received from vmm: \" << std::string(obuffer.get(), regs.r09) << '\\n';\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_data_binary(registers_type ®s)\n{\n auto &&ifile_buffer = m_file->read_binary(m_clp->ifile());\n auto &&ofile_buffer = file::binary_data(VMCALL_OUT_BUFFER_SIZE);\n regs.r05 = reinterpret_cast<decltype(regs.r05)>(ifile_buffer.data());\n regs.r06 = ifile_buffer.size();\n regs.r08 = reinterpret_cast<decltype(regs.r08)>(ofile_buffer.data());\n regs.r09 = VMCALL_OUT_BUFFER_SIZE;\n\n vmcall_send_regs(regs);\n\n switch (regs.r07)\n {\n case VMCALL_DATA_BINARY_UNFORMATTED:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n ofile_buffer.resize(regs.r09);\n m_file->write_binary(m_clp->ofile(), ofile_buffer);\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_event(registers_type ®s)\n{\n vmcall_send_regs(regs);\n std::cout << \"success\" << std::endl;\n}\n\nvoid\nioctl_driver::vmcall_unittest(registers_type ®s)\n{\n vmcall_send_regs(regs);\n std::cout << \"\\033[1;36m\" << std::hex << \"0x\" << regs.r02 << std::dec << \":\\033[1;32m passed\\033[0m\\n\";\n}\n\nioctl_driver::status_type\nioctl_driver::get_status() const\n{\n status_type status = -1;\n m_ioctl->call_ioctl_vmm_status(&status);\n\n return status;\n}\n<commit_msg>Turn on Pretty Print<commit_after>\/\/\n\/\/ Bareflank Hypervisor\n\/\/\n\/\/ Copyright (C) 2015 Assured Information Security, Inc.\n\/\/ Author: Rian Quinn <quinnr@ainfosec.com>\n\/\/ Author: Brendan Kerrigan <kerriganb@ainfosec.com>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <gsl\/gsl>\n\n#include <json.h>\n#include <debug.h>\n#include <exception.h>\n#include <ioctl_driver.h>\n#include <vmcall_interface.h>\n#include <driver_entry_interface.h>\n\nioctl_driver::ioctl_driver(gsl::not_null<file *> f,\n gsl::not_null<ioctl *> ctl,\n gsl::not_null<command_line_parser *> clp) :\n m_file(f),\n m_ioctl(ctl),\n m_clp(clp)\n{ }\n\nvoid\nioctl_driver::process()\n{\n switch (m_clp->cmd())\n {\n case command_line_parser::command_type::help:\n return;\n\n case command_line_parser::command_type::load:\n return this->load_vmm();\n\n case command_line_parser::command_type::unload:\n return this->unload_vmm();\n\n case command_line_parser::command_type::start:\n return this->start_vmm();\n\n case command_line_parser::command_type::stop:\n return this->stop_vmm();\n\n case command_line_parser::command_type::dump:\n return this->dump_vmm();\n\n case command_line_parser::command_type::status:\n return this->vmm_status();\n\n case command_line_parser::command_type::vmcall:\n return this->vmcall();\n }\n}\n\nvoid\nioctl_driver::load_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: unload_vmm();\n case VMM_UNLOADED: break;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n auto &&modules = json::parse(m_file->read_text(m_clp->modules()));\n\n auto ___ = gsl::on_failure([&]\n { unload_vmm(); });\n\n for (const auto &module : modules[\"modules\"])\n m_ioctl->call_ioctl_add_module(m_file->read_binary(module));\n\n m_ioctl->call_ioctl_load_vmm();\n}\n\nvoid\nioctl_driver::unload_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: break;\n case VMM_UNLOADED: break;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_unload_vmm();\n}\n\nvoid\nioctl_driver::start_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: stop_vmm();\n case VMM_LOADED: break;\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be loaded first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_start_vmm();\n}\n\nvoid\nioctl_driver::stop_vmm()\n{\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: return;\n case VMM_UNLOADED: return;\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_stop_vmm();\n}\n\nvoid\nioctl_driver::dump_vmm()\n{\n auto drr = ioctl::drr_type{};\n auto buffer = std::make_unique<char[]>(DEBUG_RING_SIZE);\n\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: break;\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be loaded first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n m_ioctl->call_ioctl_dump_vmm(&drr, m_clp->vcpuid());\n\n if (debug_ring_read(&drr, buffer.get(), DEBUG_RING_SIZE) > 0)\n std::cout << buffer.get();\n}\n\nvoid\nioctl_driver::vmm_status()\n{\n switch (get_status())\n {\n case VMM_UNLOADED: std::cout << \"VMM_UNLOADED\\n\"; return;\n case VMM_LOADED: std::cout << \"VMM_LOADED\\n\"; return;\n case VMM_RUNNING: std::cout << \"VMM_RUNNING\\n\"; return;\n case VMM_CORRUPT: std::cout << \"VMM_CORRUPT\\n\"; return;\n default: throw unknown_status();\n }\n}\n\nvoid\nioctl_driver::vmcall()\n{\n auto regs = m_clp->registers();\n\n switch (get_status())\n {\n case VMM_RUNNING: break;\n case VMM_LOADED: throw invalid_vmm_state(\"vmm must be running first\");\n case VMM_UNLOADED: throw invalid_vmm_state(\"vmm must be running first\");\n case VMM_CORRUPT: throw corrupt_vmm();\n default: throw unknown_status();\n }\n\n switch (regs.r00)\n {\n case VMCALL_VERSIONS:\n this->vmcall_versions(regs);\n break;\n\n case VMCALL_REGISTERS:\n this->vmcall_registers(regs);\n break;\n\n case VMCALL_DATA:\n this->vmcall_data(regs);\n break;\n\n case VMCALL_EVENT:\n this->vmcall_event(regs);\n break;\n\n case VMCALL_UNITTEST:\n this->vmcall_unittest(regs);\n break;\n\n default:\n throw std::logic_error(\"unknown vmcall opcode\");\n }\n}\n\nvoid\nioctl_driver::vmcall_send_regs(registers_type ®s)\n{\n m_ioctl->call_ioctl_vmcall(®s, m_clp->cpuid());\n\n if (regs.r01 != 0)\n throw ioctl_failed(IOCTL_VMCALL);\n}\n\nvoid\nioctl_driver::vmcall_versions(registers_type ®s)\n{\n this->vmcall_send_regs(regs);\n\n switch (regs.r02)\n {\n case VMCALL_VERSION_PROTOCOL:\n std::cout << \"VMCALL_VERSIONS: \" << view_as_pointer(regs.r03) << std::endl;\n break;\n\n case VMCALL_VERSION_BAREFLANK:\n std::cout << \"BAREFLANK_VERSION_MAJOR: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"BAREFLANK_VERSION_MINOR: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"BAREFLANK_VERSION_PATCH: \" << view_as_pointer(regs.r05) << std::endl;\n break;\n\n case VMCALL_VERSION_USER:\n std::cout << \"USER_VERSION_MAJOR: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"USER_VERSION_MINOR: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"USER_VERSION_PATCH: \" << view_as_pointer(regs.r05) << std::endl;\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_registers(registers_type ®s)\n{\n this->vmcall_send_regs(regs);\n\n std::cout << \"r02: \" << view_as_pointer(regs.r02) << std::endl;\n std::cout << \"r03: \" << view_as_pointer(regs.r03) << std::endl;\n std::cout << \"r04: \" << view_as_pointer(regs.r04) << std::endl;\n std::cout << \"r05: \" << view_as_pointer(regs.r05) << std::endl;\n std::cout << \"r06: \" << view_as_pointer(regs.r06) << std::endl;\n std::cout << \"r07: \" << view_as_pointer(regs.r07) << std::endl;\n std::cout << \"r08: \" << view_as_pointer(regs.r08) << std::endl;\n std::cout << \"r09: \" << view_as_pointer(regs.r09) << std::endl;\n std::cout << \"r10: \" << view_as_pointer(regs.r10) << std::endl;\n std::cout << \"r11: \" << view_as_pointer(regs.r11) << std::endl;\n std::cout << \"r12: \" << view_as_pointer(regs.r12) << std::endl;\n \/\/ std::cout << \"r13: \" << view_as_pointer(regs.r13) << std::endl;\n \/\/ std::cout << \"r14: \" << view_as_pointer(regs.r14) << std::endl;\n \/\/ std::cout << \"r15: \" << view_as_pointer(regs.r15) << std::endl;\n}\n\nvoid\nioctl_driver::vmcall_data(registers_type ®s)\n{\n switch (regs.r04)\n {\n case VMCALL_DATA_STRING_UNFORMATTED:\n case VMCALL_DATA_STRING_JSON:\n this->vmcall_data_string(regs);\n break;\n\n case VMCALL_DATA_BINARY_UNFORMATTED:\n this->vmcall_data_binary(regs);\n break;\n\n default:\n throw std::logic_error(\"unknown vmcall data type\");\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_data_string(registers_type ®s)\n{\n auto &&obuffer = std::make_unique<char[]>(VMCALL_OUT_BUFFER_SIZE);\n regs.r08 = reinterpret_cast<decltype(regs.r08)>(obuffer.get());\n regs.r09 = VMCALL_OUT_BUFFER_SIZE;\n\n vmcall_send_regs(regs);\n\n switch (regs.r07)\n {\n case VMCALL_DATA_STRING_JSON:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n std::cout << \"received from vmm: \\n\" << json::parse(std::string(obuffer.get(), regs.r09)).dump(4) << '\\n';\n break;\n\n case VMCALL_DATA_STRING_UNFORMATTED:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n std::cout << \"received from vmm: \" << std::string(obuffer.get(), regs.r09) << '\\n';\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_data_binary(registers_type ®s)\n{\n auto &&ifile_buffer = m_file->read_binary(m_clp->ifile());\n auto &&ofile_buffer = file::binary_data(VMCALL_OUT_BUFFER_SIZE);\n regs.r05 = reinterpret_cast<decltype(regs.r05)>(ifile_buffer.data());\n regs.r06 = ifile_buffer.size();\n regs.r08 = reinterpret_cast<decltype(regs.r08)>(ofile_buffer.data());\n regs.r09 = VMCALL_OUT_BUFFER_SIZE;\n\n vmcall_send_regs(regs);\n\n switch (regs.r07)\n {\n case VMCALL_DATA_BINARY_UNFORMATTED:\n\n if (regs.r09 >= VMCALL_OUT_BUFFER_SIZE)\n throw std::out_of_range(\"return output buffer size out of range\");\n\n ofile_buffer.resize(regs.r09);\n m_file->write_binary(m_clp->ofile(), ofile_buffer);\n break;\n\n default:\n break;\n }\n}\n\nvoid\nioctl_driver::vmcall_event(registers_type ®s)\n{\n vmcall_send_regs(regs);\n std::cout << \"success\" << std::endl;\n}\n\nvoid\nioctl_driver::vmcall_unittest(registers_type ®s)\n{\n vmcall_send_regs(regs);\n std::cout << \"\\033[1;36m\" << std::hex << \"0x\" << regs.r02 << std::dec << \":\\033[1;32m passed\\033[0m\\n\";\n}\n\nioctl_driver::status_type\nioctl_driver::get_status() const\n{\n status_type status = -1;\n m_ioctl->call_ioctl_vmm_status(&status);\n\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>int main() {\n return 0;\n}\n<commit_msg>Add license header to no_op.cc.<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ No-op main() to provide a dummy executable target.\nint main() {\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <stdexcept>\n#include <ctime>\n\n#include \"kapi.hpp\"\n#include \"libjson\/libjson.h\"\n\nusing namespace std;\nusing namespace Kraken;\n\n\/\/------------------------------------------------------------------------------\n\/\/ deals with Kraken trades:\nstruct Trade {\n double price, volume; \n time_t time; \n char order;\n\n Trade(JSONNode node) {\n price = node[0].as_float();\n volume = node[1].as_float();\n time = node[2].as_int();\n order = node[3].as_string()[0];\n }\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ prints out a kraken trade:\nostream& operator<<(ostream& os, const Trade& t) \n{\n return os << '\"'\n\t << t.time << \"\\\",\\\"\"\n\t << t.order << \"\\\",\\\"\"\n\t << fixed\n\t << setprecision(5) << t.price << \"\\\",\\\"\"\n\t << setprecision(9) << t.volume << '\"';\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ helper types to map time to a group of trades:\ntypedef vector<Trade> Period; \ntypedef map<time_t,Period> Period_map;\n\n\/\/------------------------------------------------------------------------------\n\/\/ deal with candlesticks:\nstruct Candlestick {\n double open, close, low, high;\n double volume;\n time_t time;\n};\n\n\/\/------------------------------------------------------------------------------\nstruct HA_Candlestick : public Candlestick {\n\n \/\/ create a candlestick from current period\n HA_Candlestick(const Candlestick& curr)\n {\n time = curr.time;\n volume = curr.volume;\n close = (curr.open + curr.close + curr.low + curr.high) \/ 4;\n open = (curr.open + curr.close) \/ 2;\n low = min(curr.low, min(open, close)); \n high = max(curr.high, max(open, close));\n }\n\n \/\/ create a HA candlestick from current period\n \/\/ and WITH a prior HA candlestick\n HA_Candlestick(const Candlestick& curr, const HA_Candlestick& prior) \n {\n time = curr.time;\n volume = curr.volume;\n close = (curr.open + curr.close + curr.low + curr.high) \/ 4;\n open = (prior.open + prior.close) \/ 2;\n low = min(curr.low, min(open, close)); \n high = max(curr.high, max(open, close));\n }\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ prints out a Candlestick\nostream& operator<<(ostream& os, const Candlestick& c) \n{\n struct tm timeinfo;\n localtime_r(&c.time, &timeinfo);\n \n return os << c.time << ','\n\t << fixed << setprecision(5) \n\t << c.open << ','\n\t << c.high << ','\n\t << c.low << ','\n\t << c.close << ','\n\t << setprecision(9) \n\t << c.volume;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ downloads recent trades:\nstring recent_trades(const KAPI& k, const KAPI::Input& i, vector<Trade>& v)\n{\n string json_data = k.public_method(\"Trades\", i);\n JSONNode root = libjson::parse(json_data);\n \/\/cout << json_data << endl;\n\n \/\/ throw an exception if there are errors in the JSON response\n if (!root.at(\"error\").empty()) {\n std::ostringstream oss;\n oss << \"Kraken response contains errors: \";\n \n \/\/ append errors to output string stream\n for (auto it = root[\"error\"].begin(); it != root[\"error\"].end(); ++it) \n\t oss << endl << \" * \" << libjson::to_std_string(it->as_string());\n \n throw runtime_error(oss.str());\n }\n\n \/\/ throw an exception if result is empty \n if (root.at(\"result\").empty()) {\n throw runtime_error(\"Kraken response doesn't contain result data\");\n }\n\n const string& pair = i.at(\"pair\");\n\n JSONNode& result = root[\"result\"];\n JSONNode& result_pair = result.at(pair);\n\n vector<Trade> output;\n for (JSONNode::iterator it = result_pair.begin(); \n\tit != result_pair.end(); ++it)\n output.push_back(Trade(*it));\n \n output.swap(v);\n return libjson::to_std_string( result.at(\"last\").as_string() );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ fills a candlestick vector grouping trades by time:\nvoid group_by_time(const vector<Trade>& trades, \n\t\t const time_t step, \n\t\t vector<Candlestick>& candlesticks)\n{\n vector<Trade>::const_iterator it = trades.begin();\n\n while (it != trades.end()) {\n Candlestick period;\t \n period.volume = 0;\n period.open = it->price;\n period.low = it->price;\n period.high = it->price;\n \n \/\/ the period time\n period.time = it->time - (it->time % step); \n \n while (it != trades.end() && it->time < (period.time+step)) {\n\t \/\/ the lowest price\n\t if (it->price < period.low) \n\t period.low = it->price;\n\n\t \/\/ the highest price\n\t if (it->price > period.high) \n\t period.high = it->price;\n\n\t \/\/ sum volumes\n\t period.volume += it->volume;\n\n\t \/\/ last price is close time\n\t period.close = it->price;\n\t \n\t \/\/ next element\n\t it++;\n }\n\n \/\/ store period\n candlesticks.push_back(period);\n \n \/\/ next group\n } \n}\n\n\/\/------------------------------------------------------------------------------\n\nint main(int argc, char* argv[]) \n{ \n try {\n time_t step = 600; \/\/ by default 10 minutes\n\n \/\/ \n \/\/ usage: prog <pair> [seconds]\n \/\/\n\n KAPI::Input input;\n input[\"since\"] = \"0\";\n\n switch (argc) {\n case 3:\n\t istringstream(argv[2]) >> step;\n case 2:\n\t input[\"pair\"] = std::string(argv[1]);\n\t break;\n default:\n\t throw std::runtime_error(\"wrong number of arguments\");\n };\n\n \/\/ initialize kraken lib's resources:\n Kraken::initialize();\n KAPI kapi;\n\n std::vector<Trade> trades;\n std::vector<Candlestick> candlesticks;\n\n string last = recent_trades(kapi, input, trades);\n\n \/\/ group trades by time\n group_by_time(trades, step, candlesticks);\n \n if (!candlesticks.empty()) {\n\t auto it = candlesticks.cbegin();\n\t HA_Candlestick ha(*it);\n\t cout << ha << endl;\n\t \n\t for (++it; it != candlesticks.cend(); ++it) {\n\t ha = HA_Candlestick(*it, ha);\n\t cout << ha << endl;\n\t }\n }\n }\n catch(exception& e) {\n cerr << \"Error: \" << e.what() << endl;\n }\n catch(...) {\n cerr << \"Unknow exception.\" << endl;\n }\n\n curl_global_cleanup();\n return 0;\n}\n<commit_msg>added new parameter to kph<commit_after>#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <stdexcept>\n#include <ctime>\n\n#include \"kapi.hpp\"\n#include \"libjson\/libjson.h\"\n\nusing namespace std;\nusing namespace Kraken;\n\n\/\/------------------------------------------------------------------------------\n\/\/ deals with Kraken trades:\nstruct Trade {\n double price, volume; \n time_t time; \n char order;\n\n Trade(JSONNode node) {\n price = node[0].as_float();\n volume = node[1].as_float();\n time = node[2].as_int();\n order = node[3].as_string()[0];\n }\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ prints out a kraken trade:\nostream& operator<<(ostream& os, const Trade& t) \n{\n return os << '\"'\n\t << t.time << \"\\\",\\\"\"\n\t << t.order << \"\\\",\\\"\"\n\t << fixed\n\t << setprecision(5) << t.price << \"\\\",\\\"\"\n\t << setprecision(9) << t.volume << '\"';\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ helper types to map time to a group of trades:\ntypedef vector<Trade> Period; \ntypedef map<time_t,Period> Period_map;\n\n\/\/------------------------------------------------------------------------------\n\/\/ deal with candlesticks:\nstruct Candlestick {\n double open, close, low, high;\n double volume;\n time_t time;\n};\n\n\/\/------------------------------------------------------------------------------\nstruct HA_Candlestick : public Candlestick {\n\n \/\/ create a candlestick from current period\n HA_Candlestick(const Candlestick& curr)\n {\n time = curr.time;\n volume = curr.volume;\n close = (curr.open + curr.close + curr.low + curr.high) \/ 4;\n open = (curr.open + curr.close) \/ 2;\n low = min(curr.low, min(open, close)); \n high = max(curr.high, max(open, close));\n }\n\n \/\/ create a HA candlestick from current period\n \/\/ and WITH a prior HA candlestick\n HA_Candlestick(const Candlestick& curr, const HA_Candlestick& prior) \n {\n time = curr.time;\n volume = curr.volume;\n close = (curr.open + curr.close + curr.low + curr.high) \/ 4;\n open = (prior.open + prior.close) \/ 2;\n low = min(curr.low, min(open, close)); \n high = max(curr.high, max(open, close));\n }\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ prints out a Candlestick\nostream& operator<<(ostream& os, const Candlestick& c) \n{\n struct tm timeinfo;\n localtime_r(&c.time, &timeinfo);\n \n return os << c.time << ','\n\t << fixed << setprecision(5) \n\t << c.open << ','\n\t << c.high << ','\n\t << c.low << ','\n\t << c.close << ','\n\t << setprecision(9) \n\t << c.volume;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ downloads recent trades:\nstring recent_trades(const KAPI& k, const KAPI::Input& i, vector<Trade>& v)\n{\n string json_data = k.public_method(\"Trades\", i);\n JSONNode root = libjson::parse(json_data);\n \/\/cout << json_data << endl;\n\n \/\/ throw an exception if there are errors in the JSON response\n if (!root.at(\"error\").empty()) {\n std::ostringstream oss;\n oss << \"Kraken response contains errors: \";\n \n \/\/ append errors to output string stream\n for (auto it = root[\"error\"].begin(); it != root[\"error\"].end(); ++it) \n\t oss << endl << \" * \" << libjson::to_std_string(it->as_string());\n \n throw runtime_error(oss.str());\n }\n\n \/\/ throw an exception if result is empty \n if (root.at(\"result\").empty()) {\n throw runtime_error(\"Kraken response doesn't contain result data\");\n }\n\n const string& pair = i.at(\"pair\");\n\n JSONNode& result = root[\"result\"];\n JSONNode& result_pair = result.at(pair);\n\n vector<Trade> output;\n for (JSONNode::iterator it = result_pair.begin(); \n\tit != result_pair.end(); ++it)\n output.push_back(Trade(*it));\n \n output.swap(v);\n return libjson::to_std_string( result.at(\"last\").as_string() );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ fills a candlestick vector grouping trades by time:\nvoid group_by_time(const vector<Trade>& trades, \n\t\t const time_t step, \n\t\t vector<Candlestick>& candlesticks)\n{\n vector<Trade>::const_iterator it = trades.begin();\n\n while (it != trades.end()) {\n Candlestick period;\t \n period.volume = 0;\n period.open = it->price;\n period.low = it->price;\n period.high = it->price;\n \n \/\/ the period time\n period.time = it->time - (it->time % step); \n \n while (it != trades.end() && it->time < (period.time+step)) {\n\t \/\/ the lowest price\n\t if (it->price < period.low) \n\t period.low = it->price;\n\n\t \/\/ the highest price\n\t if (it->price > period.high) \n\t period.high = it->price;\n\n\t \/\/ sum volumes\n\t period.volume += it->volume;\n\n\t \/\/ last price is close time\n\t period.close = it->price;\n\t \n\t \/\/ next element\n\t it++;\n }\n\n \/\/ store period\n candlesticks.push_back(period);\n \n \/\/ next group\n } \n}\n\n\/\/------------------------------------------------------------------------------\n\nint main(int argc, char* argv[]) \n{ \n try {\n time_t step = 15*60; \/\/ by default 15 minutes\n time_t last = 24*60*60; \/\/ by default last 24 hours\n\n \/\/ \n \/\/ usage: prog <pair> [seconds] [last]\n \/\/\n \/\/ kph prints out the price history of the <pair> in \n \/\/ the [last] number of seconds. The trade data is \n \/\/ showed as candlesticks grouped in periods of \n \/\/ [seconds] seconds.\n \/\/\n\n KAPI::Input input;\n input[\"since\"] = \"0\";\n\n switch (argc) {\n case 4: \n\t istringstream(argv[3]) >> last;\n case 3:\n\t istringstream(argv[2]) >> step;\n case 2:\n\t input[\"pair\"] = std::string(argv[1]);\n\t break;\n default:\n\t throw std::runtime_error(\"wrong number of arguments\");\n };\n\n \/\/ initialize kraken lib's resources:\n Kraken::initialize();\n KAPI kapi;\n\n std::vector<Trade> trades;\n std::vector<Candlestick> candlesticks;\n\n recent_trades(kapi, input, trades);\n\n \/\/ group trades by time\n group_by_time(trades, step, candlesticks);\n \n if (!candlesticks.empty()) {\n\t \/\/ print candlestick after this threshold\n\t time_t thresh = candlesticks.back().time - last;\n\n\t auto it = candlesticks.cbegin();\n\t HA_Candlestick ha(*it);\n\t if (ha.time > thresh) \n\t cout << ha << endl;\n\t \n\t for (++it; it != candlesticks.cend(); ++it) {\t \n\t ha = HA_Candlestick(*it, ha);\n\t if (ha.time >= thresh) \n\t cout << ha << endl;\n\t }\n }\n }\n catch(exception& e) {\n cerr << \"Error: \" << e.what() << endl;\n }\n catch(...) {\n cerr << \"Unknow exception.\" << endl;\n }\n\n curl_global_cleanup();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Consider the following continuous optimal control problem:\n *\n * find q, u, a, lm (fiber length), e (excitation), mult_t\n * minimize reaction force in knee joint\n * subject to \n * adot = f_act(a,e) activation dynamics\n * f_equil(q,lm,lmdot,a) = 0 fiber dynamics\n * qdot = N u kinematics\n * M udot + ~G mult = T + ~J*(F-C) multi-body dynamics\n * p(t,q) = 0 holonomic constraints\n * v(t,q,u) = 0 non-holonomic constraints\n * a(t,q,u,udot) = 0 acceleration-only constraints\n *\n *\n * The discretized problem (no derivatives):\n *\n * find q_t, u_t, a_t, lm_t (fiber length), e_t (excitation), mult_t\n * for t in [1, T]\n * minimize sum (reaction_t)\n * subject to \n * (a_t+1-a_t)\/h = f_act(a_t,e_t) \n * f_equil(q_t,lm_t,(lm_t+1-lm_t)\/h,a_t) = 0 \n * (q_t+1-q_t)\/h = N u_t \n * M (u_t+1-u_t)\/h + ~G mult_t = T + ~J*(F-C) \n * p(t,q_t) = 0 \n * v(t,q_t,u_t) = 0 \n * a(t,q_t,u_t,(u_t+1-u_t)\/h) = 0 \n * (for t in [1, T-1])\n *\/\n\n\/* Here is a sketch of how to solve the above problem using a\n * SimTK::OptimizerSystem, if YDotGuess and LambdaGuess (MultiplierGuess)\n * live in the State.\n *\/\nstruct Trajectory {\n struct Step {\n State state;\n Vector excitations;\n int i; \/\/ Starting index in global vector of unknowns.\n int N; \/\/ Number of unknowns in this step.\n };\n std::vector<Step> steps;\n};\n\nclass DirectCollocationProblem : public SimTK::OptimizerSystem {\npublic:\n Trajectory createTrajectory(const Vector& x) const {\n Trajectory traj;\n for (int istep = 0; istep < nsteps; ++istep) {\n Step step; step.state = State();\n step.state.updY() = x[indices];\n step.excitations = x[indices];\n step.state.updYDotGuess() = (x[indices+1] - x[indicies])\/h;\n step.state.updMultipliersGuess() = x[indices];\n traj.append(step);\n }\n return traj;\n }\n int objectiveFunc(const Vector& x, Real& f) const {\n \/\/ Add up reaction on knee over all time.\n Trajectory traj = createTrajectory(x);\n for (const auto& step : traj) {\n model.realizeAcceleration(step.state);\n f += model.getJoint(\"knee\").calcReactionOnParentExpressedInGround(step.state).norm();\n }\n }\n int constraintFunc(const Vector& x, Vector& constraints) const {\n Trajectory traj = createTrajectory(x);\n \/\/ Compute implicit diff eqn error and constraint error for all time.\n for (const auto& step : traj) {\n Vector residual, pvaerrs;\n model.realizeAcceleration(step.state);\n constraints(step.i,step.i+step.N) = [step.state.getResidual();\n step.state.getUDotErr()];\n }\n }\n};\n\/* One issue in the above scheme is that \"realize\" somewhat indicates\n * that the system is consistent; that the constraints are satisfied. You could\n * imagine that \"realize\" with an implicit form means that one performs a\n * root-solve on the implicit form to solve for a consistent YDot and Lambda.\n * But if the meaning of \"realize\" is \"compute cache entries based on state\n * variables,\" then that's fine.\n *\/\n\n\n\/* The alternative OptimizerSystem, if YDotGuess and LambdaGuess do not live\n * in the State.\n *\/\nstruct Trajectory {\n struct Step {\n State state;\n Vector excitations;\n Vector yDotGuess; \/\/ Need to hold onto guesses separately.\n Vector lambdaGuess;\n int i; \/\/ Starting index in global vector of unknowns.\n int N; \/\/ Number of unknowns in this step.\n };\n std::vector<Step> steps;\n};\nclass DirectCollocationProblem : public SimTK::OptimizerSystem {\npublic:\n Trajectory createTrajectory(const Vector& x) const {\n Trajectory traj;\n for (int istep = 0; istep < nsteps; ++istep) {\n Step step; step.state = State();\n step.state.updY() = x[indices];\n step.excitations = x[indices];\n step.yDotGuess = (x[indices+1] - x[indices])\/h;\n step.lambdaGuess = x[indices];\n traj.append(step);\n }\n return traj;\n }\n int objectiveFunc(const Vector& x, Real& f) const {\n \/\/ Add up reaction on knee over all time.\n Trajectory traj = createTrajectory(x);\n for (const auto& step : traj) {\n Vector_<SpatialVec> allReactionForces;\n \/\/ WRONG: model.realizeAcceleration(step.state);\n \/\/ WRONG: f += model.getJoint(\"knee\").calcReactionOnParentExpressedInGround(step.state).norm();\n \/\/ Must use operator form.\n \/\/ TODO this method does not exist yet.\n model.getMatterSubsystem().calcMobilizerReactionForces(step.state,\n step.yDotGuess, step.lambda?,\n allReactionForces);\n f += allReactionForces[kneeIndex].norm();\n }\n }\n int constraintFunc(const Vector& x, Vector& constraints) const {\n Trajectory traj = createTrajectory(x);\n \/\/ Compute implicit diff eqn error and constraint error for all time.\n for (const auto& step : traj) {\n Vector residual, pvaerrs;\n \/\/ Operator.\n model.calcImplicitResidualsAndConstraintErrors(step.state,\n step.yDotGuess, step.lambdaGuess,\n residuals, pvaerrs);\n constraints(step.i,step.i+step.N) = [residuals; pvaerrs];\n }\n }\n};\n<commit_msg>Update pseudoImplicitDifferentialEquations<commit_after>\/* Consider the following continuous optimal control problem:\n *\n * find q, u, a, lm (fiber length), e (excitation), mult_t\n * minimize reaction force in knee joint\n * subject to \n * adot = f_act(a,e) activation dynamics\n * f_equil(q,lm,lmdot,a) = 0 fiber dynamics\n * qdot = N u kinematics\n * M udot + ~G mult = T + ~J*(F-C) multi-body dynamics\n * p(t,q) = 0 holonomic constraints\n * v(t,q,u) = 0 non-holonomic constraints\n * a(t,q,u,udot) = 0 acceleration-only constraints\n *\n *\n * The discretized problem (no derivatives):\n *\n * find q_t, u_t, a_t, lm_t (fiber length), e_t (excitation), mult_t\n * for t in [1, T]\n * minimize sum (reaction_t)\n * subject to \n * (a_t+1-a_t)\/h = f_act(a_t,e_t) \n * f_equil(q_t,lm_t,(lm_t+1-lm_t)\/h,a_t) = 0 \n * (q_t+1-q_t)\/h = N u_t \n * M (u_t+1-u_t)\/h + ~G mult_t = T + ~J*(F-C) \n * p(t,q_t) = 0 \n * v(t,q_t,u_t) = 0 \n * a(t,q_t,u_t,(u_t+1-u_t)\/h) = 0 \n * (for t in [1, T-1])\n *\/\n\n\/* Here is a sketch of how to solve the above problem using a\n * SimTK::OptimizerSystem, if YDotGuess and LambdaGuess (MultiplierGuess)\n * live in the State.\n *\/\nstruct Trajectory {\n struct Step {\n State state;\n Vector excitations;\n int i; \/\/ Starting index in global vector of unknowns.\n int N; \/\/ Number of unknowns in this step.\n };\n std::vector<Step> steps;\n};\n\nclass DirectCollocationProblem : public SimTK::OptimizerSystem {\npublic:\n Trajectory createTrajectory(const Vector& x) const {\n Trajectory traj;\n for (int istep = 0; istep < nsteps; ++istep) {\n Step step; step.state = State();\n step.state.updY() = x[indices];\n step.excitations = x[indices];\n step.state.updYDotGuess() = (x[indices+1] - x[indicies])\/h;\n step.state.updMultipliersGuess() = x[indices];\n traj.append(step);\n }\n return traj;\n }\n int objectiveFunc(const Vector& x, Real& f) const {\n \/\/ Add up reaction on knee over all time.\n Trajectory traj = createTrajectory(x);\n for (const auto& step : traj) {\n model.realizeAcceleration(step.state);\n f += model.getJoint(\"knee\").calcReactionOnParentExpressedInGround(step.state).norm();\n }\n }\n int constraintFunc(const Vector& x, Vector& constraints) const {\n Trajectory traj = createTrajectory(x);\n \/\/ Compute implicit diff eqn error and constraint error for all time.\n for (const auto& step : traj) {\n Vector residual, pvaerrs;\n model.realizeAcceleration(step.state);\n constraints(step.i,step.i+step.N) = [step.state.getResidual();\n step.state.getUDotErr()];\n }\n }\n};\n\/* One issue in the above scheme is that \"realize\" somewhat indicates\n * that the system is consistent; that the constraints are satisfied. You could\n * imagine that \"realize\" with an implicit form means that one performs a\n * root-solve on the implicit form to solve for a consistent YDot and Lambda.\n * But if the meaning of \"realize\" is \"compute cache entries based on state\n * variables,\" then that's fine.\n *\/\n\n\n\/* The alternative OptimizerSystem, if YDotGuess and LambdaGuess do not live\n * in the State.\n *\/\nstruct Trajectory {\n struct Step {\n State state;\n Vector excitations;\n Vector yDotGuess; \/\/ Need to hold onto guesses separately.\n Vector lambdaGuess;\n int i; \/\/ Starting index in global vector of unknowns.\n int N; \/\/ Number of unknowns in this step.\n };\n std::vector<Step> steps;\n};\nclass DirectCollocationProblem : public SimTK::OptimizerSystem {\npublic:\n Trajectory createTrajectory(const Vector& x) const {\n Trajectory traj;\n for (int istep = 0; istep < nsteps; ++istep) {\n Step step; \n step.state = State();\n step.state.updY() = x[indices];\n step.excitations = x[indices];\n step.yDotGuess = (x[indices+1] - x[indices])\/h;\n step.lambdaGuess = x[indices];\n traj.append(step);\n }\n return traj;\n }\n int objectiveFunc(const Vector& x, Real& f) const {\n \/\/ Add up reaction on knee over all time.\n Trajectory traj = createTrajectory(x);\n for (const auto& step : traj) {\n Vector_<SpatialVec> allReactionForces;\n \/\/ WRONG: model.realizeAcceleration(step.state);\n \/\/ WRONG: f += model.getJoint(\"knee\").calcReactionOnParentExpressedInGround(step.state).norm();\n \/\/ Must use operator form.\n \/\/ TODO this method does not exist yet.\n model.getMatterSubsystem().calcMobilizerReactionForces(step.state,\n step.yDotGuess, step.lambda,\n allReactionForces);\n f += allReactionForces[kneeIndex].norm();\n }\n }\n int constraintFunc(const Vector& x, Vector& constraints) const {\n Trajectory traj = createTrajectory(x);\n \/\/ Compute implicit diff eqn error and constraint error for all time.\n for (const auto& step : traj) {\n Vector residual, pvaerrs;\n \/\/ Operator.\n model.calcImplicitResidualsAndConstraintErrors(step.state,\n step.yDotGuess, step.lambdaGuess,\n residuals, pvaerrs);\n constraints(step.i,step.i+step.N) = [residuals; pvaerrs];\n }\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2013-present Barefoot Networks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Antonin Bas (antonin@barefootnetworks.com)\n *\n *\/\n\n#include \"packet_io_mgr.h\"\n\n#include <algorithm> \/\/ for std::fill, std::copy\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"google\/rpc\/code.pb.h\"\n\nnamespace p4v1 = ::p4::v1;\nnamespace p4configv1 = ::p4::config::v1;\n\nnamespace pi {\n\nnamespace fe {\n\nnamespace proto {\n\nusing Code = ::google::rpc::Code;\n\nnamespace {\n\nusing p4configv1::ControllerPacketMetadata;\n\nsize_t compute_nbytes(const ControllerPacketMetadata &metadata_hdr) {\n size_t nbits = 0;\n for (const auto &metadata : metadata_hdr.metadata())\n nbits += metadata.bitwidth();\n return (nbits + 7) \/ 8;\n}\n\n\/\/ generic_extract and generic_deparse taken from the behavioral-model code\n\nvoid generic_extract(const char *data, int bit_offset, int bitwidth,\n char *dst) {\n int nbytes = (bitwidth + 7) \/ 8;\n\n if (bit_offset == 0 && bitwidth % 8 == 0) {\n memcpy(dst, data, nbytes);\n return;\n }\n\n int dst_offset = (nbytes << 3) - bitwidth;\n int i;\n\n \/\/ necessary to ensure correct behavior when shifting right (no sign\n \/\/ extension)\n auto udata = reinterpret_cast<const unsigned char *>(data);\n\n int offset = bit_offset - dst_offset;\n if (offset == 0) {\n memcpy(dst, udata, nbytes);\n dst[0] &= (0xFF >> dst_offset);\n } else if (offset > 0) { \/\/ shift left\n for (i = 0; i < nbytes - 1; i++) {\n dst[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset));\n }\n dst[0] &= (0xFF >> dst_offset);\n dst[i] = udata[i] << offset;\n if ((bit_offset + bitwidth) > (nbytes << 3)) {\n dst[i] |= (udata[i + 1] >> (8 - offset));\n }\n } else { \/\/ shift right\n offset = -offset;\n dst[0] = udata[0] >> offset;\n dst[0] &= (0xFF >> dst_offset);\n for (i = 1; i < nbytes; i++) {\n dst[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);\n }\n }\n}\n\nvoid generic_deparse(const char *data, int bitwidth, char *dst,\n int hdr_offset) {\n if (bitwidth == 0) return;\n\n int nbytes = (bitwidth + 7) \/ 8;\n\n if (hdr_offset == 0 && bitwidth % 8 == 0) {\n memcpy(dst, data, nbytes);\n return;\n }\n\n int field_offset = (nbytes << 3) - bitwidth;\n int hdr_bytes = (hdr_offset + bitwidth + 7) \/ 8;\n\n int i;\n\n \/\/ necessary to ensure correct behavior when shifting right (no sign\n \/\/ extension)\n auto udata = reinterpret_cast<const unsigned char *>(data);\n\n \/\/ zero out bits we are going to write in dst[0]\n dst[0] &= (~(0xFF >> hdr_offset));\n\n int offset = field_offset - hdr_offset;\n if (offset == 0) {\n std::copy(data + 1, data + hdr_bytes, dst + 1);\n dst[0] |= udata[0];\n } else if (offset > 0) { \/\/ shift left\n \/\/ don't know if this is very efficient, we memset the remaining bytes to 0\n \/\/ so we can use |= and preserve what was originally in dst[0]\n std::fill(&dst[1], &dst[hdr_bytes], 0);\n for (i = 0; i < hdr_bytes - 1; i++) {\n dst[i] |= (udata[i] << offset) | (udata[i + 1] >> (8 - offset));\n }\n dst[i] |= udata[i] << offset;\n } else { \/\/ shift right\n offset = -offset;\n dst[0] |= (udata[0] >> offset);\n if (nbytes == 1) {\n \/\/ dst[1] is always valid, otherwise we would not need to shift the field\n \/\/ to the right\n dst[1] = udata[0] << (8 - offset);\n return;\n }\n for (i = 1; i < hdr_bytes - 1; i++) {\n dst[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);\n }\n int tail_offset = (hdr_bytes << 3) - (hdr_offset + bitwidth);\n dst[i] &= ((1 << tail_offset) - 1);\n dst[i] |= (udata[i - 1] << (8 - offset));\n }\n}\n\n} \/\/ namespace\n\nclass PacketInMutate {\n public:\n static constexpr const char name[] = \"packet_in\";\n\n explicit PacketInMutate(const ControllerPacketMetadata &metadata_hdr)\n : metadata_hdr(metadata_hdr) {\n nbytes = compute_nbytes(metadata_hdr);\n }\n\n bool operator ()(const char *pkt, size_t size,\n p4v1::PacketIn *packet_in) const {\n if (size < nbytes) return false;\n packet_in->set_payload(pkt + nbytes, size - nbytes);\n int bit_offset = 0;\n std::vector<char> buffer(32);\n for (const auto &metadata_info : metadata_hdr.metadata()) {\n auto metadata = packet_in->add_metadata();\n metadata->set_metadata_id(metadata_info.id());\n auto bitwidth = metadata_info.bitwidth();\n buffer.resize((bitwidth + 7) \/ 8);\n buffer[0] = 0;\n generic_extract(pkt, bit_offset, bitwidth, buffer.data());\n bit_offset += (bitwidth % 8);\n pkt += (bitwidth \/ 8);\n metadata->set_value(buffer.data(), buffer.size());\n }\n return true;\n }\n\n private:\n ControllerPacketMetadata metadata_hdr;\n size_t nbytes{0};\n};\n\nconstexpr const char PacketInMutate::name[];\n\nnamespace {\n\nclass Id2Offset {\n public:\n struct Offset {\n int byte_offset;\n int bit_offset;\n int bitwidth;\n };\n\n explicit Id2Offset(const ControllerPacketMetadata &metadata_hdr) {\n int nbits = 0;\n for (const auto &metadata : metadata_hdr.metadata()) {\n auto id = metadata.id();\n auto bitwidth = metadata.bitwidth();\n offsets.emplace(id, Offset{nbits \/ 8, nbits % 8, bitwidth});\n nbits += bitwidth;\n }\n }\n\n const Offset &at(uint32_t id) const { return offsets.at(id); }\n\n private:\n std::unordered_map<uint32_t, Offset> offsets{};\n};\n\n} \/\/ namespace\n\nclass PacketOutMutate {\n public:\n static constexpr const char name[] = \"packet_out\";\n\n explicit PacketOutMutate(const ControllerPacketMetadata &metadata_hdr)\n : metadata_hdr(metadata_hdr), id2offset(metadata_hdr) {\n nbytes = compute_nbytes(metadata_hdr);\n }\n\n bool operator ()(const p4v1::PacketOut &packet_out, std::string *pkt) const {\n pkt->clear();\n const auto &payload = packet_out.payload();\n pkt->reserve(nbytes + payload.size());\n pkt->append(nbytes, 0);\n for (const auto &metadata : packet_out.metadata()) {\n const auto &offset = id2offset.at(metadata.metadata_id());\n generic_deparse(metadata.value().data(), offset.bitwidth,\n &(*pkt)[offset.byte_offset], offset.bit_offset);\n }\n pkt->append(payload);\n return true;\n }\n\n private:\n ControllerPacketMetadata metadata_hdr;\n size_t nbytes{0};\n Id2Offset id2offset;\n};\n\nconstexpr const char PacketOutMutate::name[];\n\nusing Status = PacketIOMgr::Status;\n\nPacketIOMgr::PacketIOMgr(device_id_t device_id)\n : device_id(device_id), packet_in_mutate(nullptr),\n packet_out_mutate(nullptr) { }\n\nPacketIOMgr::~PacketIOMgr() = default;\n\nvoid\nPacketIOMgr::p4_change(const p4configv1::P4Info &p4info) {\n PacketInMutate *packet_in_mutate_new = nullptr;\n PacketOutMutate *packet_out_mutate_new = nullptr;\n for (const auto &metadata_hdr : p4info.controller_packet_metadata()) {\n const auto &name = metadata_hdr.preamble().name();\n if (name == PacketInMutate::name)\n packet_in_mutate_new = new PacketInMutate(metadata_hdr);\n else if (name == PacketOutMutate::name)\n packet_out_mutate_new = new PacketOutMutate(metadata_hdr);\n }\n Lock lock(mutex);\n packet_in_mutate.reset(packet_in_mutate_new);\n packet_out_mutate.reset(packet_out_mutate_new);\n}\n\nStatus\nPacketIOMgr::packet_out_send(const p4v1::PacketOut &packet) const {\n Status status;\n pi_status_t pi_status = PI_STATUS_SUCCESS;\n if (packet_out_mutate) {\n std::string raw_packet;\n auto success = (*packet_out_mutate)(packet, &raw_packet);\n if (!success) {\n status.set_code(Code::UNKNOWN);\n return status;\n }\n pi_status = pi_packetout_send(device_id, raw_packet.data(),\n raw_packet.size());\n } else {\n const auto &payload = packet.payload();\n pi_status = pi_packetout_send(device_id, payload.data(),\n payload.size());\n }\n if (pi_status != PI_STATUS_SUCCESS)\n status.set_code(Code::UNKNOWN);\n else\n status.set_code(Code::OK);\n return status;\n}\n\nvoid\nPacketIOMgr::packet_in_register_cb(PacketInCb cb, void *cookie) {\n cb_ = std::move(cb);\n cookie_ = cookie;\n pi_packetin_register_cb(device_id, &PacketIOMgr::packet_in_cb,\n static_cast<void *>(this));\n}\n\nvoid\nPacketIOMgr::packet_in_cb(pi_dev_id_t dev_id, const char *pkt, size_t size,\n void *cookie) {\n auto mgr = static_cast<PacketIOMgr *>(cookie);\n assert(dev_id == mgr->device_id);\n p4v1::PacketIn packet_in;\n if (mgr->packet_in_mutate) {\n Lock lock(mgr->mutex);\n auto success = (*mgr->packet_in_mutate)(pkt, size, &packet_in);\n if (!success) return;\n } else {\n packet_in.set_payload(pkt, size);\n }\n mgr->cb_(mgr->device_id, &packet_in, mgr->cookie_);\n}\n\n} \/\/ namespace proto\n\n} \/\/ namespace fe\n\n} \/\/ namespace pi\n<commit_msg>Fix extract for sub-byte fields that need to be shifted left<commit_after>\/* Copyright 2013-present Barefoot Networks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Antonin Bas (antonin@barefootnetworks.com)\n *\n *\/\n\n#include \"packet_io_mgr.h\"\n\n#include <algorithm> \/\/ for std::fill, std::copy\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"google\/rpc\/code.pb.h\"\n\nnamespace p4v1 = ::p4::v1;\nnamespace p4configv1 = ::p4::config::v1;\n\nnamespace pi {\n\nnamespace fe {\n\nnamespace proto {\n\nusing Code = ::google::rpc::Code;\n\nnamespace {\n\nusing p4configv1::ControllerPacketMetadata;\n\nsize_t compute_nbytes(const ControllerPacketMetadata &metadata_hdr) {\n size_t nbits = 0;\n for (const auto &metadata : metadata_hdr.metadata())\n nbits += metadata.bitwidth();\n return (nbits + 7) \/ 8;\n}\n\n\/\/ generic_extract and generic_deparse taken from the behavioral-model code\n\nvoid generic_extract(const char *data, int bit_offset, int bitwidth,\n char *dst) {\n int nbytes = (bitwidth + 7) \/ 8;\n\n if (bit_offset == 0 && bitwidth % 8 == 0) {\n memcpy(dst, data, nbytes);\n return;\n }\n\n int dst_offset = (nbytes << 3) - bitwidth;\n int i;\n\n \/\/ necessary to ensure correct behavior when shifting right (no sign\n \/\/ extension)\n auto udata = reinterpret_cast<const unsigned char *>(data);\n\n int offset = bit_offset - dst_offset;\n if (offset == 0) {\n memcpy(dst, udata, nbytes);\n dst[0] &= (0xFF >> dst_offset);\n } else if (offset > 0) { \/\/ shift left\n for (i = 0; i < nbytes - 1; i++) {\n dst[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset));\n }\n dst[i] = udata[i] << offset;\n dst[0] &= (0xFF >> dst_offset);\n if ((bit_offset + bitwidth) > (nbytes << 3)) {\n dst[i] |= (udata[i + 1] >> (8 - offset));\n }\n } else { \/\/ shift right\n offset = -offset;\n dst[0] = udata[0] >> offset;\n dst[0] &= (0xFF >> dst_offset);\n for (i = 1; i < nbytes; i++) {\n dst[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);\n }\n }\n}\n\nvoid generic_deparse(const char *data, int bitwidth, char *dst,\n int hdr_offset) {\n if (bitwidth == 0) return;\n\n int nbytes = (bitwidth + 7) \/ 8;\n\n if (hdr_offset == 0 && bitwidth % 8 == 0) {\n memcpy(dst, data, nbytes);\n return;\n }\n\n int field_offset = (nbytes << 3) - bitwidth;\n int hdr_bytes = (hdr_offset + bitwidth + 7) \/ 8;\n\n int i;\n\n \/\/ necessary to ensure correct behavior when shifting right (no sign\n \/\/ extension)\n auto udata = reinterpret_cast<const unsigned char *>(data);\n\n \/\/ zero out bits we are going to write in dst[0]\n dst[0] &= (~(0xFF >> hdr_offset));\n\n int offset = field_offset - hdr_offset;\n if (offset == 0) {\n std::copy(data + 1, data + hdr_bytes, dst + 1);\n dst[0] |= udata[0];\n } else if (offset > 0) { \/\/ shift left\n \/\/ don't know if this is very efficient, we memset the remaining bytes to 0\n \/\/ so we can use |= and preserve what was originally in dst[0]\n std::fill(&dst[1], &dst[hdr_bytes], 0);\n for (i = 0; i < hdr_bytes - 1; i++) {\n dst[i] |= (udata[i] << offset) | (udata[i + 1] >> (8 - offset));\n }\n dst[i] |= udata[i] << offset;\n } else { \/\/ shift right\n offset = -offset;\n dst[0] |= (udata[0] >> offset);\n if (nbytes == 1) {\n \/\/ dst[1] is always valid, otherwise we would not need to shift the field\n \/\/ to the right\n dst[1] = udata[0] << (8 - offset);\n return;\n }\n for (i = 1; i < hdr_bytes - 1; i++) {\n dst[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);\n }\n int tail_offset = (hdr_bytes << 3) - (hdr_offset + bitwidth);\n dst[i] &= ((1 << tail_offset) - 1);\n dst[i] |= (udata[i - 1] << (8 - offset));\n }\n}\n\n} \/\/ namespace\n\nclass PacketInMutate {\n public:\n static constexpr const char name[] = \"packet_in\";\n\n explicit PacketInMutate(const ControllerPacketMetadata &metadata_hdr)\n : metadata_hdr(metadata_hdr) {\n nbytes = compute_nbytes(metadata_hdr);\n }\n\n bool operator ()(const char *pkt, size_t size,\n p4v1::PacketIn *packet_in) const {\n if (size < nbytes) return false;\n packet_in->set_payload(pkt + nbytes, size - nbytes);\n int bit_offset = 0;\n std::vector<char> buffer(32);\n for (const auto &metadata_info : metadata_hdr.metadata()) {\n auto metadata = packet_in->add_metadata();\n metadata->set_metadata_id(metadata_info.id());\n auto bitwidth = metadata_info.bitwidth();\n buffer.resize((bitwidth + 7) \/ 8);\n buffer[0] = 0;\n generic_extract(pkt, bit_offset, bitwidth, buffer.data());\n bit_offset += (bitwidth % 8);\n pkt += (bitwidth \/ 8);\n metadata->set_value(buffer.data(), buffer.size());\n }\n return true;\n }\n\n private:\n ControllerPacketMetadata metadata_hdr;\n size_t nbytes{0};\n};\n\nconstexpr const char PacketInMutate::name[];\n\nnamespace {\n\nclass Id2Offset {\n public:\n struct Offset {\n int byte_offset;\n int bit_offset;\n int bitwidth;\n };\n\n explicit Id2Offset(const ControllerPacketMetadata &metadata_hdr) {\n int nbits = 0;\n for (const auto &metadata : metadata_hdr.metadata()) {\n auto id = metadata.id();\n auto bitwidth = metadata.bitwidth();\n offsets.emplace(id, Offset{nbits \/ 8, nbits % 8, bitwidth});\n nbits += bitwidth;\n }\n }\n\n const Offset &at(uint32_t id) const { return offsets.at(id); }\n\n private:\n std::unordered_map<uint32_t, Offset> offsets{};\n};\n\n} \/\/ namespace\n\nclass PacketOutMutate {\n public:\n static constexpr const char name[] = \"packet_out\";\n\n explicit PacketOutMutate(const ControllerPacketMetadata &metadata_hdr)\n : metadata_hdr(metadata_hdr), id2offset(metadata_hdr) {\n nbytes = compute_nbytes(metadata_hdr);\n }\n\n bool operator ()(const p4v1::PacketOut &packet_out, std::string *pkt) const {\n pkt->clear();\n const auto &payload = packet_out.payload();\n pkt->reserve(nbytes + payload.size());\n pkt->append(nbytes, 0);\n for (const auto &metadata : packet_out.metadata()) {\n const auto &offset = id2offset.at(metadata.metadata_id());\n generic_deparse(metadata.value().data(), offset.bitwidth,\n &(*pkt)[offset.byte_offset], offset.bit_offset);\n }\n pkt->append(payload);\n return true;\n }\n\n private:\n ControllerPacketMetadata metadata_hdr;\n size_t nbytes{0};\n Id2Offset id2offset;\n};\n\nconstexpr const char PacketOutMutate::name[];\n\nusing Status = PacketIOMgr::Status;\n\nPacketIOMgr::PacketIOMgr(device_id_t device_id)\n : device_id(device_id), packet_in_mutate(nullptr),\n packet_out_mutate(nullptr) { }\n\nPacketIOMgr::~PacketIOMgr() = default;\n\nvoid\nPacketIOMgr::p4_change(const p4configv1::P4Info &p4info) {\n PacketInMutate *packet_in_mutate_new = nullptr;\n PacketOutMutate *packet_out_mutate_new = nullptr;\n for (const auto &metadata_hdr : p4info.controller_packet_metadata()) {\n const auto &name = metadata_hdr.preamble().name();\n if (name == PacketInMutate::name)\n packet_in_mutate_new = new PacketInMutate(metadata_hdr);\n else if (name == PacketOutMutate::name)\n packet_out_mutate_new = new PacketOutMutate(metadata_hdr);\n }\n Lock lock(mutex);\n packet_in_mutate.reset(packet_in_mutate_new);\n packet_out_mutate.reset(packet_out_mutate_new);\n}\n\nStatus\nPacketIOMgr::packet_out_send(const p4v1::PacketOut &packet) const {\n Status status;\n pi_status_t pi_status = PI_STATUS_SUCCESS;\n if (packet_out_mutate) {\n std::string raw_packet;\n auto success = (*packet_out_mutate)(packet, &raw_packet);\n if (!success) {\n status.set_code(Code::UNKNOWN);\n return status;\n }\n pi_status = pi_packetout_send(device_id, raw_packet.data(),\n raw_packet.size());\n } else {\n const auto &payload = packet.payload();\n pi_status = pi_packetout_send(device_id, payload.data(),\n payload.size());\n }\n if (pi_status != PI_STATUS_SUCCESS)\n status.set_code(Code::UNKNOWN);\n else\n status.set_code(Code::OK);\n return status;\n}\n\nvoid\nPacketIOMgr::packet_in_register_cb(PacketInCb cb, void *cookie) {\n cb_ = std::move(cb);\n cookie_ = cookie;\n pi_packetin_register_cb(device_id, &PacketIOMgr::packet_in_cb,\n static_cast<void *>(this));\n}\n\nvoid\nPacketIOMgr::packet_in_cb(pi_dev_id_t dev_id, const char *pkt, size_t size,\n void *cookie) {\n auto mgr = static_cast<PacketIOMgr *>(cookie);\n assert(dev_id == mgr->device_id);\n p4v1::PacketIn packet_in;\n if (mgr->packet_in_mutate) {\n Lock lock(mgr->mutex);\n auto success = (*mgr->packet_in_mutate)(pkt, size, &packet_in);\n if (!success) return;\n } else {\n packet_in.set_payload(pkt, size);\n }\n mgr->cb_(mgr->device_id, &packet_in, mgr->cookie_);\n}\n\n} \/\/ namespace proto\n\n} \/\/ namespace fe\n\n} \/\/ namespace pi\n<|endoftext|>"} {"text":"<commit_before>#include \"PrecompiledHeader.h\"\n#include \"DirectStorageFileReadWorkQueue.h\"\n#include \"DirectXContext.h\"\n#include \"SearchInstructions.h\"\n#include \"SearchResultReporter.h\"\n#include \"StringSearch\/StringSearcher.h\"\n#include \"Utilities\/ScopedStackAllocator.h\"\n\nDirectStorageFileReadWorkQueue::DirectStorageFileReadWorkQueue(const StringSearcher& stringSearcher, const SearchInstructions& searchInstructions, SearchResultReporter& searchResultReporter) :\n m_SearchResultReporter(searchResultReporter),\n m_StringSearcher(stringSearcher),\n m_ReadBufferSize(0),\n m_FenceEvent(false),\n m_FenceValue(0),\n m_IsTerminating(false),\n m_FreeReadSlotCount(ARRAYSIZE(m_FileReadSlots))\n{\n if (searchInstructions.SearchInFileContents())\n m_ReadBufferSize = kFileReadBufferBaseSize + std::max(searchInstructions.utf8SearchString.length(), searchInstructions.searchString.length() * sizeof(wchar_t));\n}\n\nDirectStorageFileReadWorkQueue::~DirectStorageFileReadWorkQueue()\n{\n if (m_DStorageQueue != nullptr)\n {\n m_DStorageQueue->Close();\n m_DStorageQueue = nullptr;\n }\n}\n\nvoid DirectStorageFileReadWorkQueue::Initialize()\n{\n m_FileReadBuffers.reset(new uint8_t[m_ReadBufferSize * kFileReadSlotCount]);\n m_WaitableTimer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);\n\n memset(m_FreeReadSlots, 0xFF, sizeof(m_FreeReadSlots));\n\n DSTORAGE_QUEUE_DESC queueDesc = {};\n queueDesc.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;\n queueDesc.Capacity = DSTORAGE_MAX_QUEUE_CAPACITY;\n queueDesc.Priority = DSTORAGE_PRIORITY_NORMAL;\n\n auto hr = DirectXContext::GetDStorageFactory()->CreateQueue(&queueDesc, __uuidof(m_DStorageQueue), &m_DStorageQueue);\n Assert(SUCCEEDED(hr));\n\n hr = DirectXContext::GetD3D12Device()->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(m_Fence), &m_Fence);\n Assert(SUCCEEDED(hr));\n\n m_FenceEvent.Initialize();\n\n SYSTEM_INFO systemInfo;\n GetNativeSystemInfo(&systemInfo);\n\n MyFileReadBase::Initialize();\n m_FileOpenWorkQueue.Initialize<&DirectStorageFileReadWorkQueue::FileOpenThread>(this, systemInfo.dwNumberOfProcessors - 2);\n m_SearchWorkQueue.Initialize<&DirectStorageFileReadWorkQueue::ContentsSearchThread>(this, systemInfo.dwNumberOfProcessors - 1);\n MySearchResultBase::Initialize<&DirectStorageFileReadWorkQueue::FileReadThread>(this, 1);\n}\n\nvoid DirectStorageFileReadWorkQueue::DrainWorkQueue()\n{\n m_IsTerminating = true;\n m_FileOpenWorkQueue.DrainWorkQueue();\n MyFileReadBase::DrainWorkQueue();\n m_SearchWorkQueue.DrainWorkQueue();\n MySearchResultBase::DrainWorkQueue();\n}\n\nvoid DirectStorageFileReadWorkQueue::CompleteAllWork()\n{\n m_FileOpenWorkQueue.CompleteAllWork();\n\n ReleaseSemaphore(MyFileReadBase::GetWorkSemaphore(), 1, nullptr);\n WaitForSingleObject(m_FileReadsCompletedEvent, INFINITE);\n\n m_SearchWorkQueue.CompleteAllWork();\n MySearchResultBase::CompleteAllWork();\n}\n\nvoid DirectStorageFileReadWorkQueue::FileOpenThread()\n{\n SetThreadDescription(GetCurrentThread(), L\"FSS File Open Thread\");\n\n m_FileOpenWorkQueue.DoWork([this](FileOpenData& searchData)\n {\n if (m_IsTerminating)\n return;\n\n FileReadData readData(std::move(searchData));\n auto hr = DirectXContext::GetDStorageFactory()->OpenFile(readData.filePath.c_str(), __uuidof(readData.file), &readData.file);\n if (FAILED(hr))\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(readData.fileSize);\n return;\n }\n\n MyFileReadBase::PushWorkItem(std::move(readData));\n });\n}\n\nvoid DirectStorageFileReadWorkQueue::FileReadThread()\n{\n bool readSubmissionCompleted = false;\n bool fileContentSearchCompleted = false;\n SetThreadDescription(GetCurrentThread(), L\"FSS Read Submission Thread\");\n\n for (;;)\n {\n uint32_t handleCount = 0;\n HANDLE waitHandles[4];\n\n if (!readSubmissionCompleted)\n waitHandles[handleCount++] = MyFileReadBase::GetWorkSemaphore();\n\n if (!fileContentSearchCompleted)\n waitHandles[handleCount++] = MySearchResultBase::GetWorkSemaphore();\n\n if (!m_CurrentBatch.slots.empty())\n {\n LARGE_INTEGER timer;\n timer.QuadPart = -10000; \/\/ 1 ms\n auto result = SetWaitableTimer(m_WaitableTimer, &timer, 0, nullptr, nullptr, FALSE);\n Assert(result);\n\n waitHandles[handleCount++] = m_WaitableTimer;\n }\n\n if (!m_SubmittedBatches.empty())\n waitHandles[handleCount++] = m_FenceEvent;\n\n if (handleCount == 0)\n break;\n\n auto waitResult = WaitForMultipleObjects(handleCount, waitHandles, FALSE, INFINITE);\n Assert(waitResult >= WAIT_OBJECT_0 && waitResult < WAIT_OBJECT_0 + handleCount);\n\n if (waitResult < WAIT_OBJECT_0 || waitResult >= WAIT_OBJECT_0 + handleCount)\n break;\n\n if (m_IsTerminating)\n {\n DrainWorkQueue();\n break;\n }\n\n auto signaledHandle = waitHandles[waitResult - WAIT_OBJECT_0];\n if (signaledHandle == MyFileReadBase::GetWorkSemaphore())\n {\n auto workEntry = MyFileReadBase::PopWorkEntry();\n if (workEntry != nullptr)\n {\n m_FilesToRead.push_back(std::move(workEntry->workItem));\n QueueFileReads();\n\n MyFileReadBase::DeleteWorkEntry(workEntry);\n }\n else\n {\n readSubmissionCompleted = true;\n }\n }\n else if (signaledHandle == MySearchResultBase::GetWorkSemaphore())\n {\n auto workEntry = MySearchResultBase::PopWorkEntry();\n if (workEntry != nullptr)\n {\n ProcessSearchCompletion(workEntry->workItem);\n MySearchResultBase::DeleteWorkEntry(workEntry);\n }\n else\n {\n fileContentSearchCompleted = true;\n }\n\n if (readSubmissionCompleted && m_CurrentBatch.slots.empty() && m_FreeReadSlotCount == ARRAYSIZE(m_FileReadSlots))\n m_FileReadsCompletedEvent.Set();\n }\n else if (signaledHandle == m_WaitableTimer)\n {\n \/\/ No requests for 1 ms, submit outstanding work\n SubmitReadRequests();\n }\n else\n {\n ProcessReadCompletion();\n }\n }\n}\n\nstatic uint32_t GetChunkCount(const FileReadStateData& file)\n{\n const auto fileSize = file.fileSize;\n auto chunkCount = file.fileSize \/ DirectStorageFileReadWorkQueue::kFileReadBufferBaseSize;\n if (file.fileSize % DirectStorageFileReadWorkQueue::kFileReadBufferBaseSize)\n chunkCount++;\n\n Assert(chunkCount < std::numeric_limits<uint32_t>::max());\n return static_cast<uint32_t>(chunkCount);\n}\n\nvoid DirectStorageFileReadWorkQueue::QueueFileReads()\n{\n while (true)\n {\n uint16_t slot = std::numeric_limits<uint16_t>::max();\n\n \/\/ TO DO: use a trie if this is too slow\n for (uint16_t i = 0; i < ARRAYSIZE(m_FreeReadSlots); i++)\n {\n DWORD index;\n if (_BitScanForward64(&index, m_FreeReadSlots[i]))\n {\n slot = 64 * i + static_cast<uint16_t>(index);\n break;\n }\n }\n\n if (slot == std::numeric_limits<uint16_t>::max())\n return;\n\n if (m_FilesWithReadProgress.empty() || m_FilesWithReadProgress.back().chunksRead == GetChunkCount(m_FilesWithReadProgress.back()))\n {\n if (m_FilesToRead.empty())\n return;\n\n m_FilesWithReadProgress.push_back(std::move(m_FilesToRead.back()));\n m_FilesToRead.pop_back();\n }\n\n uint32_t fileIndex = static_cast<uint32_t>(m_FilesWithReadProgress.size() - 1);\n auto& file = m_FilesWithReadProgress[fileIndex];\n file.readsInProgress++;\n\n Assert(slot < kFileReadSlotCount);\n m_FileReadSlots[slot] = fileIndex;\n m_FreeReadSlots[slot \/ 64] &= ~(1ULL << (slot % 64));\n m_FreeReadSlotCount--;\n\n const auto fileOffset = (file.chunksRead++) * kFileReadBufferBaseSize;\n uint32_t bytesToRead = static_cast<uint32_t>(std::min(file.fileSize - fileOffset, m_ReadBufferSize));\n\n DSTORAGE_REQUEST request = {};\n request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;\n request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;\n request.Source.File.Source = file.file.Get();\n request.Source.File.Offset = fileOffset;\n request.Source.File.Size = bytesToRead;\n request.Destination.Memory.Buffer = m_FileReadBuffers.get() + slot * m_ReadBufferSize;\n request.Destination.Memory.Size = bytesToRead;\n request.UncompressedSize = bytesToRead;\n\n m_DStorageQueue->EnqueueRequest(&request);\n m_CurrentBatch.slots.emplace_back(slot, bytesToRead);\n\n if (m_CurrentBatch.slots.size() >= ARRAYSIZE(m_FileReadSlots) \/ 2)\n SubmitReadRequests();\n }\n}\n\nvoid DirectStorageFileReadWorkQueue::SubmitReadRequests()\n{\n Assert(m_CurrentBatch.slots.size() > 0);\n m_CurrentBatch.fenceValue = m_FenceValue++;\n\n m_DStorageQueue->EnqueueSignal(m_Fence.Get(), m_CurrentBatch.fenceValue);\n m_DStorageQueue->Submit();\n\n if (m_SubmittedBatches.empty())\n m_Fence->SetEventOnCompletion(m_CurrentBatch.fenceValue, m_FenceEvent);\n\n m_SubmittedBatches.push_back(std::move(m_CurrentBatch));\n m_CurrentBatch = m_BatchPool.GetNewObject();\n}\n\nvoid DirectStorageFileReadWorkQueue::ProcessReadCompletion()\n{\n uint32_t batchIndex = 0;\n for (; batchIndex < m_SubmittedBatches.size() && m_SubmittedBatches[batchIndex].fenceValue <= m_Fence->GetCompletedValue(); batchIndex++)\n {\n auto& batch = m_SubmittedBatches[batchIndex];\n\n for (auto slot : batch.slots)\n m_SearchWorkQueue.PushWorkItem(slot);\n\n batch.slots.clear();\n m_BatchPool.PoolObject(std::move(batch));\n }\n\n m_SubmittedBatches.erase(m_SubmittedBatches.begin(), m_SubmittedBatches.begin() + batchIndex);\n if (!m_SubmittedBatches.empty())\n m_Fence->SetEventOnCompletion(m_SubmittedBatches.front().fenceValue, m_FenceEvent);\n}\n\nvoid DirectStorageFileReadWorkQueue::ContentsSearchThread()\n{\n ScopedStackAllocator allocator;\n SetThreadDescription(GetCurrentThread(), L\"FSS Content Search Thread\");\n\n m_SearchWorkQueue.DoWork([this, &allocator](SlotSearchData& searchData)\n {\n searchData.found = m_StringSearcher.PerformFileContentSearch(m_FileReadBuffers.get() + searchData.slot * m_ReadBufferSize, searchData.size, allocator);\n MySearchResultBase::PushWorkItem(searchData);\n });\n}\n\nvoid DirectStorageFileReadWorkQueue::ProcessSearchCompletion(SlotSearchData searchData)\n{\n auto& fileIndex = m_FileReadSlots[searchData.slot];\n auto& file = m_FilesWithReadProgress[fileIndex];\n\n Assert(file.readsInProgress > 0);\n file.readsInProgress--;\n m_FreeReadSlots[searchData.slot \/ 64] |= 1ULL << (searchData.slot % 64);\n m_FreeReadSlotCount++;\n\n if (!file.dispatchedToResults)\n {\n if (searchData.found)\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(file.fileSize - file.totalScannedSize);\n m_SearchResultReporter.DispatchSearchResult(file.fileFindData, std::move(file.filePath));\n\n file.totalScannedSize = file.fileSize;\n file.chunksRead = GetChunkCount(file);\n file.dispatchedToResults = true;\n }\n else if (file.readsInProgress == 0 && file.chunksRead == GetChunkCount(file))\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(file.fileSize - file.totalScannedSize);\n file.totalScannedSize = file.fileSize;\n }\n else\n {\n m_SearchResultReporter.AddToScannedFileSize(kFileReadBufferBaseSize);\n file.totalScannedSize += kFileReadBufferBaseSize;\n }\n }\n\n while (!m_FilesWithReadProgress.empty())\n {\n auto& lastFile = m_FilesWithReadProgress.back();\n\n if (lastFile.chunksRead == GetChunkCount(lastFile) && lastFile.readsInProgress == 0)\n {\n m_FilesWithReadProgress.pop_back();\n }\n else\n {\n break;\n }\n }\n\n QueueFileReads();\n}\n<commit_msg>Fix off by one error in fence value, causing search to proceed before reads are complete.<commit_after>#include \"PrecompiledHeader.h\"\n#include \"DirectStorageFileReadWorkQueue.h\"\n#include \"DirectXContext.h\"\n#include \"SearchInstructions.h\"\n#include \"SearchResultReporter.h\"\n#include \"StringSearch\/StringSearcher.h\"\n#include \"Utilities\/ScopedStackAllocator.h\"\n\nDirectStorageFileReadWorkQueue::DirectStorageFileReadWorkQueue(const StringSearcher& stringSearcher, const SearchInstructions& searchInstructions, SearchResultReporter& searchResultReporter) :\n m_SearchResultReporter(searchResultReporter),\n m_StringSearcher(stringSearcher),\n m_ReadBufferSize(0),\n m_FenceEvent(false),\n m_FenceValue(0),\n m_IsTerminating(false),\n m_FreeReadSlotCount(ARRAYSIZE(m_FileReadSlots))\n{\n if (searchInstructions.SearchInFileContents())\n m_ReadBufferSize = kFileReadBufferBaseSize + std::max(searchInstructions.utf8SearchString.length(), searchInstructions.searchString.length() * sizeof(wchar_t));\n}\n\nDirectStorageFileReadWorkQueue::~DirectStorageFileReadWorkQueue()\n{\n if (m_DStorageQueue != nullptr)\n {\n m_DStorageQueue->Close();\n m_DStorageQueue = nullptr;\n }\n}\n\nvoid DirectStorageFileReadWorkQueue::Initialize()\n{\n m_FileReadBuffers.reset(new uint8_t[m_ReadBufferSize * kFileReadSlotCount]);\n m_WaitableTimer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);\n\n memset(m_FreeReadSlots, 0xFF, sizeof(m_FreeReadSlots));\n\n DSTORAGE_QUEUE_DESC queueDesc = {};\n queueDesc.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;\n queueDesc.Capacity = DSTORAGE_MAX_QUEUE_CAPACITY;\n queueDesc.Priority = DSTORAGE_PRIORITY_NORMAL;\n\n auto hr = DirectXContext::GetDStorageFactory()->CreateQueue(&queueDesc, __uuidof(m_DStorageQueue), &m_DStorageQueue);\n Assert(SUCCEEDED(hr));\n\n hr = DirectXContext::GetD3D12Device()->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(m_Fence), &m_Fence);\n Assert(SUCCEEDED(hr));\n\n m_FenceEvent.Initialize();\n\n SYSTEM_INFO systemInfo;\n GetNativeSystemInfo(&systemInfo);\n\n MyFileReadBase::Initialize();\n m_FileOpenWorkQueue.Initialize<&DirectStorageFileReadWorkQueue::FileOpenThread>(this, systemInfo.dwNumberOfProcessors - 2);\n m_SearchWorkQueue.Initialize<&DirectStorageFileReadWorkQueue::ContentsSearchThread>(this, systemInfo.dwNumberOfProcessors - 1);\n MySearchResultBase::Initialize<&DirectStorageFileReadWorkQueue::FileReadThread>(this, 1);\n}\n\nvoid DirectStorageFileReadWorkQueue::DrainWorkQueue()\n{\n m_IsTerminating = true;\n m_FileOpenWorkQueue.DrainWorkQueue();\n MyFileReadBase::DrainWorkQueue();\n m_SearchWorkQueue.DrainWorkQueue();\n MySearchResultBase::DrainWorkQueue();\n}\n\nvoid DirectStorageFileReadWorkQueue::CompleteAllWork()\n{\n m_FileOpenWorkQueue.CompleteAllWork();\n\n ReleaseSemaphore(MyFileReadBase::GetWorkSemaphore(), 1, nullptr);\n WaitForSingleObject(m_FileReadsCompletedEvent, INFINITE);\n\n m_SearchWorkQueue.CompleteAllWork();\n MySearchResultBase::CompleteAllWork();\n}\n\nvoid DirectStorageFileReadWorkQueue::FileOpenThread()\n{\n SetThreadDescription(GetCurrentThread(), L\"FSS File Open Thread\");\n\n m_FileOpenWorkQueue.DoWork([this](FileOpenData& searchData)\n {\n if (m_IsTerminating)\n return;\n\n FileReadData readData(std::move(searchData));\n auto hr = DirectXContext::GetDStorageFactory()->OpenFile(readData.filePath.c_str(), __uuidof(readData.file), &readData.file);\n if (FAILED(hr))\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(readData.fileSize);\n return;\n }\n\n MyFileReadBase::PushWorkItem(std::move(readData));\n });\n}\n\nvoid DirectStorageFileReadWorkQueue::FileReadThread()\n{\n bool readSubmissionCompleted = false;\n bool fileContentSearchCompleted = false;\n SetThreadDescription(GetCurrentThread(), L\"FSS Read Submission Thread\");\n\n for (;;)\n {\n uint32_t handleCount = 0;\n HANDLE waitHandles[4];\n\n if (!readSubmissionCompleted)\n waitHandles[handleCount++] = MyFileReadBase::GetWorkSemaphore();\n\n if (!fileContentSearchCompleted)\n waitHandles[handleCount++] = MySearchResultBase::GetWorkSemaphore();\n\n if (!m_CurrentBatch.slots.empty())\n {\n LARGE_INTEGER timer;\n timer.QuadPart = -10000; \/\/ 1 ms\n auto result = SetWaitableTimer(m_WaitableTimer, &timer, 0, nullptr, nullptr, FALSE);\n Assert(result);\n\n waitHandles[handleCount++] = m_WaitableTimer;\n }\n\n if (!m_SubmittedBatches.empty())\n waitHandles[handleCount++] = m_FenceEvent;\n\n if (handleCount == 0)\n break;\n\n auto waitResult = WaitForMultipleObjects(handleCount, waitHandles, FALSE, INFINITE);\n Assert(waitResult >= WAIT_OBJECT_0 && waitResult < WAIT_OBJECT_0 + handleCount);\n\n if (waitResult < WAIT_OBJECT_0 || waitResult >= WAIT_OBJECT_0 + handleCount)\n break;\n\n if (m_IsTerminating)\n {\n DrainWorkQueue();\n break;\n }\n\n auto signaledHandle = waitHandles[waitResult - WAIT_OBJECT_0];\n if (signaledHandle == MyFileReadBase::GetWorkSemaphore())\n {\n auto workEntry = MyFileReadBase::PopWorkEntry();\n if (workEntry != nullptr)\n {\n m_FilesToRead.push_back(std::move(workEntry->workItem));\n QueueFileReads();\n\n MyFileReadBase::DeleteWorkEntry(workEntry);\n }\n else\n {\n readSubmissionCompleted = true;\n }\n }\n else if (signaledHandle == MySearchResultBase::GetWorkSemaphore())\n {\n auto workEntry = MySearchResultBase::PopWorkEntry();\n if (workEntry != nullptr)\n {\n ProcessSearchCompletion(workEntry->workItem);\n MySearchResultBase::DeleteWorkEntry(workEntry);\n }\n else\n {\n fileContentSearchCompleted = true;\n }\n\n if (readSubmissionCompleted && m_CurrentBatch.slots.empty() && m_FreeReadSlotCount == ARRAYSIZE(m_FileReadSlots))\n m_FileReadsCompletedEvent.Set();\n }\n else if (signaledHandle == m_WaitableTimer)\n {\n \/\/ No requests for 1 ms, submit outstanding work\n SubmitReadRequests();\n }\n else\n {\n ProcessReadCompletion();\n }\n }\n}\n\nstatic uint32_t GetChunkCount(const FileReadStateData& file)\n{\n const auto fileSize = file.fileSize;\n auto chunkCount = file.fileSize \/ DirectStorageFileReadWorkQueue::kFileReadBufferBaseSize;\n if (file.fileSize % DirectStorageFileReadWorkQueue::kFileReadBufferBaseSize)\n chunkCount++;\n\n Assert(chunkCount < std::numeric_limits<uint32_t>::max());\n return static_cast<uint32_t>(chunkCount);\n}\n\nvoid DirectStorageFileReadWorkQueue::QueueFileReads()\n{\n while (true)\n {\n uint16_t slot = std::numeric_limits<uint16_t>::max();\n\n \/\/ TO DO: use a trie if this is too slow\n for (uint16_t i = 0; i < ARRAYSIZE(m_FreeReadSlots); i++)\n {\n DWORD index;\n if (_BitScanForward64(&index, m_FreeReadSlots[i]))\n {\n slot = 64 * i + static_cast<uint16_t>(index);\n break;\n }\n }\n\n if (slot == std::numeric_limits<uint16_t>::max())\n return;\n\n if (m_FilesWithReadProgress.empty() || m_FilesWithReadProgress.back().chunksRead == GetChunkCount(m_FilesWithReadProgress.back()))\n {\n if (m_FilesToRead.empty())\n return;\n\n m_FilesWithReadProgress.push_back(std::move(m_FilesToRead.back()));\n m_FilesToRead.pop_back();\n }\n\n uint32_t fileIndex = static_cast<uint32_t>(m_FilesWithReadProgress.size() - 1);\n auto& file = m_FilesWithReadProgress[fileIndex];\n file.readsInProgress++;\n\n Assert(slot < kFileReadSlotCount);\n m_FileReadSlots[slot] = fileIndex;\n m_FreeReadSlots[slot \/ 64] &= ~(1ULL << (slot % 64));\n m_FreeReadSlotCount--;\n\n const auto fileOffset = (file.chunksRead++) * kFileReadBufferBaseSize;\n uint32_t bytesToRead = static_cast<uint32_t>(std::min(file.fileSize - fileOffset, m_ReadBufferSize));\n\n DSTORAGE_REQUEST request = {};\n request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;\n request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;\n request.Source.File.Source = file.file.Get();\n request.Source.File.Offset = fileOffset;\n request.Source.File.Size = bytesToRead;\n request.Destination.Memory.Buffer = m_FileReadBuffers.get() + slot * m_ReadBufferSize;\n request.Destination.Memory.Size = bytesToRead;\n request.UncompressedSize = bytesToRead;\n\n m_DStorageQueue->EnqueueRequest(&request);\n m_CurrentBatch.slots.emplace_back(slot, bytesToRead);\n\n if (m_CurrentBatch.slots.size() >= ARRAYSIZE(m_FileReadSlots) \/ 2)\n SubmitReadRequests();\n }\n}\n\nvoid DirectStorageFileReadWorkQueue::SubmitReadRequests()\n{\n Assert(m_CurrentBatch.slots.size() > 0);\n m_CurrentBatch.fenceValue = ++m_FenceValue;\n\n m_DStorageQueue->EnqueueSignal(m_Fence.Get(), m_CurrentBatch.fenceValue);\n m_DStorageQueue->Submit();\n\n if (m_SubmittedBatches.empty())\n m_Fence->SetEventOnCompletion(m_CurrentBatch.fenceValue, m_FenceEvent);\n\n m_SubmittedBatches.push_back(std::move(m_CurrentBatch));\n m_CurrentBatch = m_BatchPool.GetNewObject();\n}\n\nvoid DirectStorageFileReadWorkQueue::ProcessReadCompletion()\n{\n uint32_t batchIndex = 0;\n for (; batchIndex < m_SubmittedBatches.size() && m_SubmittedBatches[batchIndex].fenceValue <= m_Fence->GetCompletedValue(); batchIndex++)\n {\n auto& batch = m_SubmittedBatches[batchIndex];\n\n for (auto slot : batch.slots)\n m_SearchWorkQueue.PushWorkItem(slot);\n\n batch.slots.clear();\n m_BatchPool.PoolObject(std::move(batch));\n }\n\n m_SubmittedBatches.erase(m_SubmittedBatches.begin(), m_SubmittedBatches.begin() + batchIndex);\n if (!m_SubmittedBatches.empty())\n m_Fence->SetEventOnCompletion(m_SubmittedBatches.front().fenceValue, m_FenceEvent);\n}\n\nvoid DirectStorageFileReadWorkQueue::ContentsSearchThread()\n{\n ScopedStackAllocator allocator;\n SetThreadDescription(GetCurrentThread(), L\"FSS Content Search Thread\");\n\n m_SearchWorkQueue.DoWork([this, &allocator](SlotSearchData& searchData)\n {\n searchData.found = m_StringSearcher.PerformFileContentSearch(m_FileReadBuffers.get() + searchData.slot * m_ReadBufferSize, searchData.size, allocator);\n MySearchResultBase::PushWorkItem(searchData);\n });\n}\n\nvoid DirectStorageFileReadWorkQueue::ProcessSearchCompletion(SlotSearchData searchData)\n{\n auto& fileIndex = m_FileReadSlots[searchData.slot];\n auto& file = m_FilesWithReadProgress[fileIndex];\n\n Assert(file.readsInProgress > 0);\n file.readsInProgress--;\n m_FreeReadSlots[searchData.slot \/ 64] |= 1ULL << (searchData.slot % 64);\n m_FreeReadSlotCount++;\n\n if (!file.dispatchedToResults)\n {\n if (searchData.found)\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(file.fileSize - file.totalScannedSize);\n m_SearchResultReporter.DispatchSearchResult(file.fileFindData, std::move(file.filePath));\n\n file.totalScannedSize = file.fileSize;\n file.chunksRead = GetChunkCount(file);\n file.dispatchedToResults = true;\n }\n else if (file.readsInProgress == 0 && file.chunksRead == GetChunkCount(file))\n {\n m_SearchResultReporter.AddToScannedFileCount();\n m_SearchResultReporter.AddToScannedFileSize(file.fileSize - file.totalScannedSize);\n file.totalScannedSize = file.fileSize;\n }\n else\n {\n m_SearchResultReporter.AddToScannedFileSize(kFileReadBufferBaseSize);\n file.totalScannedSize += kFileReadBufferBaseSize;\n }\n }\n\n while (!m_FilesWithReadProgress.empty())\n {\n auto& lastFile = m_FilesWithReadProgress.back();\n\n if (lastFile.chunksRead == GetChunkCount(lastFile) && lastFile.readsInProgress == 0)\n {\n m_FilesWithReadProgress.pop_back();\n }\n else\n {\n break;\n }\n }\n\n QueueFileReads();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"transactionview.h\"\n\n#include \"transactionfilterproxy.h\"\n#include \"transactionrecord.h\"\n#include \"walletmodel.h\"\n#include \"addresstablemodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"bitcoinunits.h\"\n#include \"csvmodelwriter.h\"\n#include \"transactiondescdialog.h\"\n#include \"editaddressdialog.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n\n#include <QScrollBar>\n#include <QComboBox>\n#include <QDoubleValidator>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QTableView>\n#include <QHeaderView>\n#include <QPushButton>\n#include <QMessageBox>\n#include <QPoint>\n#include <QMenu>\n#include <QApplication>\n#include <QClipboard>\n#include <QLabel>\n#include <QDateTimeEdit>\n\nTransactionView::TransactionView(QWidget *parent) :\n QWidget(parent), model(0), transactionProxyModel(0),\n transactionView(0)\n{\n \/\/ Build filter row\n setContentsMargins(0,0,0,0);\n\n QHBoxLayout *hlayout = new QHBoxLayout();\n hlayout->setContentsMargins(0,0,0,0);\n#ifdef Q_OS_MAC\n hlayout->setSpacing(5);\n hlayout->addSpacing(26);\n#else\n hlayout->setSpacing(0);\n hlayout->addSpacing(23);\n#endif\n\n dateWidget = new QComboBox(this);\n#ifdef Q_OS_MAC\n dateWidget->setFixedWidth(121);\n#else\n dateWidget->setFixedWidth(120);\n#endif\n dateWidget->addItem(tr(\"All\"), All);\n dateWidget->addItem(tr(\"Today\"), Today);\n dateWidget->addItem(tr(\"This week\"), ThisWeek);\n dateWidget->addItem(tr(\"This month\"), ThisMonth);\n dateWidget->addItem(tr(\"Last month\"), LastMonth);\n dateWidget->addItem(tr(\"This year\"), ThisYear);\n dateWidget->addItem(tr(\"Range...\"), Range);\n hlayout->addWidget(dateWidget);\n\n typeWidget = new QComboBox(this);\n#ifdef Q_OS_MAC\n typeWidget->setFixedWidth(121);\n#else\n typeWidget->setFixedWidth(120);\n#endif\n\n typeWidget->addItem(tr(\"All\"), TransactionFilterProxy::ALL_TYPES);\n typeWidget->addItem(tr(\"Received with\"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));\n typeWidget->addItem(tr(\"Sent to\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));\n typeWidget->addItem(tr(\"To yourself\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));\n typeWidget->addItem(tr(\"Mined\"), TransactionFilterProxy::TYPE(TransactionRecord::StakeMint));\n typeWidget->addItem(tr(\"Mined\"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));\n typeWidget->addItem(tr(\"Other\"), TransactionFilterProxy::TYPE(TransactionRecord::Other));\n\n hlayout->addWidget(typeWidget);\n\n addressWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n addressWidget->setPlaceholderText(tr(\"Enter address or label to search\"));\n#endif\n hlayout->addWidget(addressWidget);\n\n amountWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n amountWidget->setPlaceholderText(tr(\"Min amount\"));\n#endif\n#ifdef Q_OS_MAC\n amountWidget->setFixedWidth(97);\n#else\n amountWidget->setFixedWidth(100);\n#endif\n amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));\n hlayout->addWidget(amountWidget);\n\n QVBoxLayout *vlayout = new QVBoxLayout(this);\n vlayout->setContentsMargins(0,0,0,0);\n vlayout->setSpacing(0);\n\n QTableView *view = new QTableView(this);\n vlayout->addLayout(hlayout);\n vlayout->addWidget(createDateRangeWidget());\n vlayout->addWidget(view);\n vlayout->setSpacing(0);\n int width = view->verticalScrollBar()->sizeHint().width();\n \/\/ Cover scroll bar width with spacing\n#ifdef Q_OS_MAC\n hlayout->addSpacing(width+2);\n#else\n hlayout->addSpacing(width);\n#endif\n \/\/ Always show scroll bar\n view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n view->setTabKeyNavigation(false);\n view->setContextMenuPolicy(Qt::CustomContextMenu);\n\n transactionView = view;\n\n \/\/ Actions\n QAction *copyAddressAction = new QAction(tr(\"Copy address\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy label\"), this);\n QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\n QAction *editLabelAction = new QAction(tr(\"Edit label\"), this);\n QAction *showDetailsAction = new QAction(tr(\"Show transaction details\"), this);\n\n contextMenu = new QMenu();\n contextMenu->addAction(copyAddressAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(copyAmountAction);\n contextMenu->addAction(editLabelAction);\n contextMenu->addAction(showDetailsAction);\n\n \/\/ Connect actions\n connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\n connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\n connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));\n connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));\n\n connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));\n connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\n\n connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));\n connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\n connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));\n connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));\n}\n\nvoid TransactionView::setModel(WalletModel *model)\n{\n this->model = model;\n if(model)\n {\n transactionProxyModel = new TransactionFilterProxy(this);\n transactionProxyModel->setSourceModel(model->getTransactionTableModel());\n transactionProxyModel->setDynamicSortFilter(true);\n transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n\n transactionProxyModel->setSortRole(Qt::EditRole);\n\n transactionView->setModel(transactionProxyModel);\n transactionView->setAlternatingRowColors(true);\n transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);\n transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);\n transactionView->setSortingEnabled(true);\n transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);\n transactionView->verticalHeader()->hide();\n\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Status, 23);\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Date, 120);\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Type, 120);\n#if QT_VERSION < 0x050000\n transactionView->horizontalHeader()->setResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);\n#else\n transactionView->horizontalHeader()->setSectionResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);\n#endif\n transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Amount, 100);\n }\n}\n\nvoid TransactionView::chooseDate(int idx)\n{\n if(!transactionProxyModel)\n return;\n QDate current = QDate::currentDate();\n dateRangeWidget->setVisible(false);\n switch(dateWidget->itemData(idx).toInt())\n {\n case All:\n transactionProxyModel->setDateRange(\n TransactionFilterProxy::MIN_DATE,\n TransactionFilterProxy::MAX_DATE);\n break;\n case Today:\n transactionProxyModel->setDateRange(\n QDateTime(current),\n TransactionFilterProxy::MAX_DATE);\n break;\n case ThisWeek: {\n \/\/ Find last Monday\n QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\n transactionProxyModel->setDateRange(\n QDateTime(startOfWeek),\n TransactionFilterProxy::MAX_DATE);\n\n } break;\n case ThisMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month(), 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case LastMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month()-1, 1)),\n QDateTime(QDate(current.year(), current.month(), 1)));\n break;\n case ThisYear:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), 1, 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case Range:\n dateRangeWidget->setVisible(true);\n dateRangeChanged();\n break;\n }\n}\n\nvoid TransactionView::chooseType(int idx)\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setTypeFilter(\n typeWidget->itemData(idx).toInt());\n}\n\nvoid TransactionView::changedPrefix(const QString &prefix)\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setAddressPrefix(prefix);\n}\n\nvoid TransactionView::changedAmount(const QString &amount)\n{\n if(!transactionProxyModel)\n return;\n qint64 amount_parsed = 0;\n if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))\n {\n transactionProxyModel->setMinAmount(amount_parsed);\n }\n else\n {\n transactionProxyModel->setMinAmount(0);\n }\n}\n\nvoid TransactionView::exportClicked()\n{\n \/\/ CSV is currently the only supported format\n QString filename = GUIUtil::getSaveFileName(\n this,\n tr(\"Export Transaction Data\"), QString(),\n tr(\"Comma separated file (*.csv)\"));\n\n if (filename.isNull()) return;\n\n CSVModelWriter writer(filename);\n\n \/\/ name, column, role\n writer.setModel(transactionProxyModel);\n writer.addColumn(tr(\"Confirmed\"), 0, TransactionTableModel::ConfirmedRole);\n writer.addColumn(tr(\"Date\"), 0, TransactionTableModel::DateRole);\n writer.addColumn(tr(\"Type\"), TransactionTableModel::Type, Qt::EditRole);\n writer.addColumn(tr(\"Label\"), 0, TransactionTableModel::LabelRole);\n writer.addColumn(tr(\"Address\"), 0, TransactionTableModel::AddressRole);\n writer.addColumn(tr(\"Amount\"), 0, TransactionTableModel::FormattedAmountRole);\n writer.addColumn(tr(\"ID\"), 0, TransactionTableModel::TxIDRole);\n\n if(!writer.write())\n {\n QMessageBox::critical(this, tr(\"Error exporting\"), tr(\"Could not write to file %1.\").arg(filename),\n QMessageBox::Abort, QMessageBox::Abort);\n }\n}\n\nvoid TransactionView::contextualMenu(const QPoint &point)\n{\n QModelIndex index = transactionView->indexAt(point);\n if(index.isValid())\n {\n contextMenu->exec(QCursor::pos());\n }\n}\n\nvoid TransactionView::copyAddress()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);\n}\n\nvoid TransactionView::copyLabel()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);\n}\n\nvoid TransactionView::copyAmount()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);\n}\n\nvoid TransactionView::editLabel()\n{\n if(!transactionView->selectionModel() ||!model)\n return;\n QModelIndexList selection = transactionView->selectionModel()->selectedRows();\n if(!selection.isEmpty())\n {\n AddressTableModel *addressBook = model->getAddressTableModel();\n if(!addressBook)\n return;\n QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();\n if(address.isEmpty())\n {\n \/\/ If this transaction has no associated address, exit\n return;\n }\n \/\/ Is address in address book? Address book can miss address when a transaction is\n \/\/ sent from outside the UI.\n int idx = addressBook->lookupAddress(address);\n if(idx != -1)\n {\n \/\/ Edit sending \/ receiving address\n QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());\n \/\/ Determine type of address, launch appropriate editor dialog type\n QString type = modelIdx.data(AddressTableModel::TypeRole).toString();\n\n EditAddressDialog dlg(type==AddressTableModel::Receive\n ? EditAddressDialog::EditReceivingAddress\n : EditAddressDialog::EditSendingAddress,\n this);\n dlg.setModel(addressBook);\n dlg.loadRow(idx);\n dlg.exec();\n }\n else\n {\n \/\/ Add sending address\n EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,\n this);\n dlg.setModel(addressBook);\n dlg.setAddress(address);\n dlg.exec();\n }\n }\n}\n\nvoid TransactionView::showDetails()\n{\n if(!transactionView->selectionModel())\n return;\n QModelIndexList selection = transactionView->selectionModel()->selectedRows();\n if(!selection.isEmpty())\n {\n TransactionDescDialog dlg(selection.at(0));\n dlg.exec();\n }\n}\n\nQWidget *TransactionView::createDateRangeWidget()\n{\n dateRangeWidget = new QFrame();\n dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);\n dateRangeWidget->setContentsMargins(1,1,1,1);\n QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);\n layout->setContentsMargins(0,0,0,0);\n layout->addSpacing(23);\n layout->addWidget(new QLabel(tr(\"Range:\")));\n\n dateFrom = new QDateTimeEdit(this);\n dateFrom->setDisplayFormat(\"dd\/MM\/yy\");\n dateFrom->setCalendarPopup(true);\n dateFrom->setMinimumWidth(100);\n dateFrom->setDate(QDate::currentDate().addDays(-7));\n layout->addWidget(dateFrom);\n layout->addWidget(new QLabel(tr(\"to\")));\n\n dateTo = new QDateTimeEdit(this);\n dateTo->setDisplayFormat(\"dd\/MM\/yy\");\n dateTo->setCalendarPopup(true);\n dateTo->setMinimumWidth(100);\n dateTo->setDate(QDate::currentDate());\n layout->addWidget(dateTo);\n layout->addStretch();\n\n \/\/ Hide by default\n dateRangeWidget->setVisible(false);\n\n \/\/ Notify on change\n connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\n connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\n\n return dateRangeWidget;\n}\n\nvoid TransactionView::dateRangeChanged()\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setDateRange(\n QDateTime(dateFrom->date()),\n QDateTime(dateTo->date()).addDays(1));\n}\n\nvoid TransactionView::focusTransaction(const QModelIndex &idx)\n{\n if(!transactionProxyModel)\n return;\n QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);\n transactionView->scrollTo(targetIdx);\n transactionView->setCurrentIndex(targetIdx);\n transactionView->setFocus();\n}\n<commit_msg>Fix for #349<commit_after>#include \"transactionview.h\"\n\n#include \"transactionfilterproxy.h\"\n#include \"transactionrecord.h\"\n#include \"walletmodel.h\"\n#include \"addresstablemodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"bitcoinunits.h\"\n#include \"csvmodelwriter.h\"\n#include \"transactiondescdialog.h\"\n#include \"editaddressdialog.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n\n#include <QScrollBar>\n#include <QComboBox>\n#include <QDoubleValidator>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QTableView>\n#include <QHeaderView>\n#include <QPushButton>\n#include <QMessageBox>\n#include <QPoint>\n#include <QMenu>\n#include <QApplication>\n#include <QClipboard>\n#include <QLabel>\n#include <QDateTimeEdit>\n\nTransactionView::TransactionView(QWidget *parent) :\n QWidget(parent), model(0), transactionProxyModel(0),\n transactionView(0)\n{\n \/\/ Build filter row\n setContentsMargins(0,0,0,0);\n\n QHBoxLayout *hlayout = new QHBoxLayout();\n hlayout->setContentsMargins(0,0,0,0);\n#ifdef Q_OS_MAC\n hlayout->setSpacing(5);\n hlayout->addSpacing(26);\n#else\n hlayout->setSpacing(0);\n hlayout->addSpacing(23);\n#endif\n\n dateWidget = new QComboBox(this);\n#ifdef Q_OS_MAC\n dateWidget->setFixedWidth(121);\n#else\n dateWidget->setFixedWidth(120);\n#endif\n dateWidget->addItem(tr(\"All\"), All);\n dateWidget->addItem(tr(\"Today\"), Today);\n dateWidget->addItem(tr(\"This week\"), ThisWeek);\n dateWidget->addItem(tr(\"This month\"), ThisMonth);\n dateWidget->addItem(tr(\"Last month\"), LastMonth);\n dateWidget->addItem(tr(\"This year\"), ThisYear);\n dateWidget->addItem(tr(\"Range...\"), Range);\n hlayout->addWidget(dateWidget);\n\n typeWidget = new QComboBox(this);\n#ifdef Q_OS_MAC\n typeWidget->setFixedWidth(121);\n#else\n typeWidget->setFixedWidth(120);\n#endif\n\n typeWidget->addItem(tr(\"All\"), TransactionFilterProxy::ALL_TYPES);\n typeWidget->addItem(tr(\"Received with\"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));\n typeWidget->addItem(tr(\"Sent to\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));\n typeWidget->addItem(tr(\"To yourself\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));\n typeWidget->addItem(tr(\"Mined\"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));\n typeWidget->addItem(tr(\"Other\"), TransactionFilterProxy::TYPE(TransactionRecord::Other));\n\n hlayout->addWidget(typeWidget);\n\n addressWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n addressWidget->setPlaceholderText(tr(\"Enter address or label to search\"));\n#endif\n hlayout->addWidget(addressWidget);\n\n amountWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n amountWidget->setPlaceholderText(tr(\"Min amount\"));\n#endif\n#ifdef Q_OS_MAC\n amountWidget->setFixedWidth(97);\n#else\n amountWidget->setFixedWidth(100);\n#endif\n amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));\n hlayout->addWidget(amountWidget);\n\n QVBoxLayout *vlayout = new QVBoxLayout(this);\n vlayout->setContentsMargins(0,0,0,0);\n vlayout->setSpacing(0);\n\n QTableView *view = new QTableView(this);\n vlayout->addLayout(hlayout);\n vlayout->addWidget(createDateRangeWidget());\n vlayout->addWidget(view);\n vlayout->setSpacing(0);\n int width = view->verticalScrollBar()->sizeHint().width();\n \/\/ Cover scroll bar width with spacing\n#ifdef Q_OS_MAC\n hlayout->addSpacing(width+2);\n#else\n hlayout->addSpacing(width);\n#endif\n \/\/ Always show scroll bar\n view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n view->setTabKeyNavigation(false);\n view->setContextMenuPolicy(Qt::CustomContextMenu);\n\n transactionView = view;\n\n \/\/ Actions\n QAction *copyAddressAction = new QAction(tr(\"Copy address\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy label\"), this);\n QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\n QAction *editLabelAction = new QAction(tr(\"Edit label\"), this);\n QAction *showDetailsAction = new QAction(tr(\"Show transaction details\"), this);\n\n contextMenu = new QMenu();\n contextMenu->addAction(copyAddressAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(copyAmountAction);\n contextMenu->addAction(editLabelAction);\n contextMenu->addAction(showDetailsAction);\n\n \/\/ Connect actions\n connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\n connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\n connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));\n connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));\n\n connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));\n connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\n\n connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));\n connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\n connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));\n connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));\n}\n\nvoid TransactionView::setModel(WalletModel *model)\n{\n this->model = model;\n if(model)\n {\n transactionProxyModel = new TransactionFilterProxy(this);\n transactionProxyModel->setSourceModel(model->getTransactionTableModel());\n transactionProxyModel->setDynamicSortFilter(true);\n transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n\n transactionProxyModel->setSortRole(Qt::EditRole);\n\n transactionView->setModel(transactionProxyModel);\n transactionView->setAlternatingRowColors(true);\n transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);\n transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);\n transactionView->setSortingEnabled(true);\n transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);\n transactionView->verticalHeader()->hide();\n\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Status, 23);\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Date, 120);\n transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Type, 120);\n#if QT_VERSION < 0x050000\n transactionView->horizontalHeader()->setResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);\n#else\n transactionView->horizontalHeader()->setSectionResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);\n#endif\n transactionView->horizontalHeader()->resizeSection( TransactionTableModel::Amount, 100);\n }\n}\n\nvoid TransactionView::chooseDate(int idx)\n{\n if(!transactionProxyModel)\n return;\n QDate current = QDate::currentDate();\n dateRangeWidget->setVisible(false);\n switch(dateWidget->itemData(idx).toInt())\n {\n case All:\n transactionProxyModel->setDateRange(\n TransactionFilterProxy::MIN_DATE,\n TransactionFilterProxy::MAX_DATE);\n break;\n case Today:\n transactionProxyModel->setDateRange(\n QDateTime(current),\n TransactionFilterProxy::MAX_DATE);\n break;\n case ThisWeek: {\n \/\/ Find last Monday\n QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\n transactionProxyModel->setDateRange(\n QDateTime(startOfWeek),\n TransactionFilterProxy::MAX_DATE);\n\n } break;\n case ThisMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month(), 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case LastMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month()-1, 1)),\n QDateTime(QDate(current.year(), current.month(), 1)));\n break;\n case ThisYear:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), 1, 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case Range:\n dateRangeWidget->setVisible(true);\n dateRangeChanged();\n break;\n }\n}\n\nvoid TransactionView::chooseType(int idx)\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setTypeFilter(\n typeWidget->itemData(idx).toInt());\n}\n\nvoid TransactionView::changedPrefix(const QString &prefix)\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setAddressPrefix(prefix);\n}\n\nvoid TransactionView::changedAmount(const QString &amount)\n{\n if(!transactionProxyModel)\n return;\n qint64 amount_parsed = 0;\n if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))\n {\n transactionProxyModel->setMinAmount(amount_parsed);\n }\n else\n {\n transactionProxyModel->setMinAmount(0);\n }\n}\n\nvoid TransactionView::exportClicked()\n{\n \/\/ CSV is currently the only supported format\n QString filename = GUIUtil::getSaveFileName(\n this,\n tr(\"Export Transaction Data\"), QString(),\n tr(\"Comma separated file (*.csv)\"));\n\n if (filename.isNull()) return;\n\n CSVModelWriter writer(filename);\n\n \/\/ name, column, role\n writer.setModel(transactionProxyModel);\n writer.addColumn(tr(\"Confirmed\"), 0, TransactionTableModel::ConfirmedRole);\n writer.addColumn(tr(\"Date\"), 0, TransactionTableModel::DateRole);\n writer.addColumn(tr(\"Type\"), TransactionTableModel::Type, Qt::EditRole);\n writer.addColumn(tr(\"Label\"), 0, TransactionTableModel::LabelRole);\n writer.addColumn(tr(\"Address\"), 0, TransactionTableModel::AddressRole);\n writer.addColumn(tr(\"Amount\"), 0, TransactionTableModel::FormattedAmountRole);\n writer.addColumn(tr(\"ID\"), 0, TransactionTableModel::TxIDRole);\n\n if(!writer.write())\n {\n QMessageBox::critical(this, tr(\"Error exporting\"), tr(\"Could not write to file %1.\").arg(filename),\n QMessageBox::Abort, QMessageBox::Abort);\n }\n}\n\nvoid TransactionView::contextualMenu(const QPoint &point)\n{\n QModelIndex index = transactionView->indexAt(point);\n if(index.isValid())\n {\n contextMenu->exec(QCursor::pos());\n }\n}\n\nvoid TransactionView::copyAddress()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);\n}\n\nvoid TransactionView::copyLabel()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);\n}\n\nvoid TransactionView::copyAmount()\n{\n GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);\n}\n\nvoid TransactionView::editLabel()\n{\n if(!transactionView->selectionModel() ||!model)\n return;\n QModelIndexList selection = transactionView->selectionModel()->selectedRows();\n if(!selection.isEmpty())\n {\n AddressTableModel *addressBook = model->getAddressTableModel();\n if(!addressBook)\n return;\n QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();\n if(address.isEmpty())\n {\n \/\/ If this transaction has no associated address, exit\n return;\n }\n \/\/ Is address in address book? Address book can miss address when a transaction is\n \/\/ sent from outside the UI.\n int idx = addressBook->lookupAddress(address);\n if(idx != -1)\n {\n \/\/ Edit sending \/ receiving address\n QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());\n \/\/ Determine type of address, launch appropriate editor dialog type\n QString type = modelIdx.data(AddressTableModel::TypeRole).toString();\n\n EditAddressDialog dlg(type==AddressTableModel::Receive\n ? EditAddressDialog::EditReceivingAddress\n : EditAddressDialog::EditSendingAddress,\n this);\n dlg.setModel(addressBook);\n dlg.loadRow(idx);\n dlg.exec();\n }\n else\n {\n \/\/ Add sending address\n EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,\n this);\n dlg.setModel(addressBook);\n dlg.setAddress(address);\n dlg.exec();\n }\n }\n}\n\nvoid TransactionView::showDetails()\n{\n if(!transactionView->selectionModel())\n return;\n QModelIndexList selection = transactionView->selectionModel()->selectedRows();\n if(!selection.isEmpty())\n {\n TransactionDescDialog dlg(selection.at(0));\n dlg.exec();\n }\n}\n\nQWidget *TransactionView::createDateRangeWidget()\n{\n dateRangeWidget = new QFrame();\n dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);\n dateRangeWidget->setContentsMargins(1,1,1,1);\n QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);\n layout->setContentsMargins(0,0,0,0);\n layout->addSpacing(23);\n layout->addWidget(new QLabel(tr(\"Range:\")));\n\n dateFrom = new QDateTimeEdit(this);\n dateFrom->setDisplayFormat(\"dd\/MM\/yy\");\n dateFrom->setCalendarPopup(true);\n dateFrom->setMinimumWidth(100);\n dateFrom->setDate(QDate::currentDate().addDays(-7));\n layout->addWidget(dateFrom);\n layout->addWidget(new QLabel(tr(\"to\")));\n\n dateTo = new QDateTimeEdit(this);\n dateTo->setDisplayFormat(\"dd\/MM\/yy\");\n dateTo->setCalendarPopup(true);\n dateTo->setMinimumWidth(100);\n dateTo->setDate(QDate::currentDate());\n layout->addWidget(dateTo);\n layout->addStretch();\n\n \/\/ Hide by default\n dateRangeWidget->setVisible(false);\n\n \/\/ Notify on change\n connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\n connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\n\n return dateRangeWidget;\n}\n\nvoid TransactionView::dateRangeChanged()\n{\n if(!transactionProxyModel)\n return;\n transactionProxyModel->setDateRange(\n QDateTime(dateFrom->date()),\n QDateTime(dateTo->date()).addDays(1));\n}\n\nvoid TransactionView::focusTransaction(const QModelIndex &idx)\n{\n if(!transactionProxyModel)\n return;\n QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);\n transactionView->scrollTo(targetIdx);\n transactionView->setCurrentIndex(targetIdx);\n transactionView->setFocus();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- swift-demangle.cpp - Swift Demangler app -------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/DemangleWrappers.h\"\n#include \"swift\/Basic\/ManglingMacros.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Regex.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <cstdlib>\n#include <string>\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nstatic llvm::cl::opt<bool>\nExpandMode(\"expand\",\n llvm::cl::desc(\"Expand mode (show node structure of the demangling)\"));\n\nstatic llvm::cl::opt<bool>\nCompactMode(\"compact\",\n llvm::cl::desc(\"Compact mode (only emit the demangled names)\"));\n\nstatic llvm::cl::opt<bool>\nTreeOnly(\"tree-only\",\n llvm::cl::desc(\"Tree-only mode (do not show the demangled string)\"));\n\nstatic llvm::cl::opt<bool>\nRemangleMode(\"test-remangle\",\n llvm::cl::desc(\"Remangle test mode (show the remangled string)\"));\n\nstatic llvm::cl::opt<bool>\nDisableSugar(\"no-sugar\",\n llvm::cl::desc(\"No sugar mode (disable common language idioms such as ? and [] from the output)\"));\n\nstatic llvm::cl::opt<bool>\nSimplified(\"simplified\",\n llvm::cl::desc(\"Don't display module names or implicit self types\"));\n\nstatic llvm::cl::list<std::string>\nInputNames(llvm::cl::Positional, llvm::cl::desc(\"[mangled name...]\"),\n llvm::cl::ZeroOrMore);\n\nstatic llvm::StringRef substrBefore(llvm::StringRef whole,\n llvm::StringRef part) {\n return whole.slice(0, part.data() - whole.data());\n}\n\nstatic llvm::StringRef substrAfter(llvm::StringRef whole,\n llvm::StringRef part) {\n return whole.substr((part.data() - whole.data()) + part.size());\n}\n\nstatic void demangle(llvm::raw_ostream &os, llvm::StringRef name,\n const swift::Demangle::DemangleOptions &options) {\n bool hadLeadingUnderscore = false;\n if (name.startswith(\"__\")) {\n hadLeadingUnderscore = true;\n name = name.substr(1);\n }\n swift::Demangle::NodePointer pointer =\n swift::demangle_wrappers::demangleSymbolAsNode(name);\n if (ExpandMode || TreeOnly) {\n llvm::outs() << \"Demangling for \" << name << '\\n';\n swift::demangle_wrappers::NodeDumper(pointer).print(llvm::outs());\n }\n if (RemangleMode) {\n if (hadLeadingUnderscore) llvm::outs() << '_';\n \/\/ Just reprint the original mangled name if it didn't demangle.\n \/\/ This makes it easier to share the same database between the\n \/\/ mangling and demangling tests.\n if (!pointer) {\n llvm::outs() << name;\n } else {\n llvm::outs() << swift::Demangle::mangleNode(pointer);\n }\n return;\n }\n if (!TreeOnly) {\n std::string string = swift::Demangle::nodeToString(pointer, options);\n if (!CompactMode)\n llvm::outs() << name << \" ---> \";\n llvm::outs() << (string.empty() ? name : llvm::StringRef(string));\n }\n}\n\nstatic int demangleSTDIN(const swift::Demangle::DemangleOptions &options) {\n \/\/ This doesn't handle Unicode symbols, but maybe that's okay.\n llvm::Regex maybeSymbol(\"(_T|\" MANGLING_PREFIX_STR \")[_a-zA-Z0-9$]+\");\n\n while (true) {\n char *inputLine = NULL;\n size_t size;\n if (getline(&inputLine, &size, stdin) == -1 || size <= 0) {\n if (errno == 0) {\n break;\n }\n\n return EXIT_FAILURE;\n }\n\n llvm::StringRef inputContents(inputLine);\n llvm::SmallVector<llvm::StringRef, 1> matches;\n while (maybeSymbol.match(inputContents, &matches)) {\n llvm::outs() << substrBefore(inputContents, matches.front());\n demangle(llvm::outs(), matches.front(), options);\n inputContents = substrAfter(inputContents, matches.front());\n }\n\n llvm::outs() << inputContents;\n free(inputLine);\n }\n\n return EXIT_SUCCESS;\n}\n\nint main(int argc, char **argv) {\n#if defined(__CYGWIN__)\n \/\/ Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,\n \/\/ if main()'s first function call is passing argv[0].\n std::rand();\n#endif\n llvm::cl::ParseCommandLineOptions(argc, argv);\n\n swift::Demangle::DemangleOptions options;\n options.SynthesizeSugarOnTypes = !DisableSugar;\n if (Simplified)\n options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();\n\n if (InputNames.empty()) {\n CompactMode = true;\n return demangleSTDIN(options);\n } else {\n for (llvm::StringRef name : InputNames) {\n demangle(llvm::outs(), name, options);\n llvm::outs() << '\\n';\n }\n\n return EXIT_SUCCESS;\n }\n}\n<commit_msg>swift-demangle: Abort with an error if the demangling-test fails for a symbol.<commit_after>\/\/===--- swift-demangle.cpp - Swift Demangler app -------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/DemangleWrappers.h\"\n#include \"swift\/Basic\/ManglingMacros.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Regex.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <cstdlib>\n#include <string>\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nstatic llvm::cl::opt<bool>\nExpandMode(\"expand\",\n llvm::cl::desc(\"Expand mode (show node structure of the demangling)\"));\n\nstatic llvm::cl::opt<bool>\nCompactMode(\"compact\",\n llvm::cl::desc(\"Compact mode (only emit the demangled names)\"));\n\nstatic llvm::cl::opt<bool>\nTreeOnly(\"tree-only\",\n llvm::cl::desc(\"Tree-only mode (do not show the demangled string)\"));\n\nstatic llvm::cl::opt<bool>\nRemangleMode(\"test-remangle\",\n llvm::cl::desc(\"Remangle test mode (show the remangled string)\"));\n\nstatic llvm::cl::opt<bool>\nDisableSugar(\"no-sugar\",\n llvm::cl::desc(\"No sugar mode (disable common language idioms such as ? and [] from the output)\"));\n\nstatic llvm::cl::opt<bool>\nSimplified(\"simplified\",\n llvm::cl::desc(\"Don't display module names or implicit self types\"));\n\nstatic llvm::cl::list<std::string>\nInputNames(llvm::cl::Positional, llvm::cl::desc(\"[mangled name...]\"),\n llvm::cl::ZeroOrMore);\n\nstatic llvm::StringRef substrBefore(llvm::StringRef whole,\n llvm::StringRef part) {\n return whole.slice(0, part.data() - whole.data());\n}\n\nstatic llvm::StringRef substrAfter(llvm::StringRef whole,\n llvm::StringRef part) {\n return whole.substr((part.data() - whole.data()) + part.size());\n}\n\nstatic void demangle(llvm::raw_ostream &os, llvm::StringRef name,\n const swift::Demangle::DemangleOptions &options) {\n bool hadLeadingUnderscore = false;\n if (name.startswith(\"__\")) {\n hadLeadingUnderscore = true;\n name = name.substr(1);\n }\n swift::Demangle::NodePointer pointer =\n swift::demangle_wrappers::demangleSymbolAsNode(name);\n if (ExpandMode || TreeOnly) {\n llvm::outs() << \"Demangling for \" << name << '\\n';\n swift::demangle_wrappers::NodeDumper(pointer).print(llvm::outs());\n }\n if (RemangleMode) {\n std::string remangled;\n if (!pointer) {\n \/\/ Just reprint the original mangled name if it didn't demangle.\n \/\/ This makes it easier to share the same database between the\n \/\/ mangling and demangling tests.\n remangled = name;\n } else {\n remangled = swift::Demangle::mangleNode(pointer,\n \/*NewMangling*\/ name.startswith(\"_S\"));\n if (name != remangled) {\n llvm::errs() << \"\\nError: re-mangled name \\n \" << remangled\n << \"\\ndoes not match original name\\n \" << name << '\\n';\n exit(1);\n }\n }\n if (hadLeadingUnderscore) llvm::outs() << '_';\n llvm::outs() << remangled;\n return;\n }\n if (!TreeOnly) {\n std::string string = swift::Demangle::nodeToString(pointer, options);\n if (!CompactMode)\n llvm::outs() << name << \" ---> \";\n llvm::outs() << (string.empty() ? name : llvm::StringRef(string));\n }\n}\n\nstatic int demangleSTDIN(const swift::Demangle::DemangleOptions &options) {\n \/\/ This doesn't handle Unicode symbols, but maybe that's okay.\n llvm::Regex maybeSymbol(\"(_T|\" MANGLING_PREFIX_STR \")[_a-zA-Z0-9$]+\");\n\n while (true) {\n char *inputLine = NULL;\n size_t size;\n if (getline(&inputLine, &size, stdin) == -1 || size <= 0) {\n if (errno == 0) {\n break;\n }\n\n return EXIT_FAILURE;\n }\n\n llvm::StringRef inputContents(inputLine);\n llvm::SmallVector<llvm::StringRef, 1> matches;\n while (maybeSymbol.match(inputContents, &matches)) {\n llvm::outs() << substrBefore(inputContents, matches.front());\n demangle(llvm::outs(), matches.front(), options);\n inputContents = substrAfter(inputContents, matches.front());\n }\n\n llvm::outs() << inputContents;\n free(inputLine);\n }\n\n return EXIT_SUCCESS;\n}\n\nint main(int argc, char **argv) {\n#if defined(__CYGWIN__)\n \/\/ Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,\n \/\/ if main()'s first function call is passing argv[0].\n std::rand();\n#endif\n llvm::cl::ParseCommandLineOptions(argc, argv);\n\n swift::Demangle::DemangleOptions options;\n options.SynthesizeSugarOnTypes = !DisableSugar;\n if (Simplified)\n options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();\n\n if (InputNames.empty()) {\n CompactMode = true;\n return demangleSTDIN(options);\n } else {\n for (llvm::StringRef name : InputNames) {\n demangle(llvm::outs(), name, options);\n llvm::outs() << '\\n';\n }\n\n return EXIT_SUCCESS;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the CallGraphSCCPass class, which is used for passes\n\/\/ which are implemented as bottom-up traversals on the call graph. Because\n\/\/ there may be cycles in the call graph, passes of this type operate on the\n\/\/ call-graph in SCC order: that is, they process function bottom-up, except for\n\/\/ recursive functions, which they process all at once.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"cgscc-passmgr\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/ADT\/SCCIterator.h\"\n#include \"llvm\/PassManagers.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ CGPassManager\n\/\/\n\/\/\/ CGPassManager manages FPPassManagers and CalLGraphSCCPasses.\n\nnamespace {\n\nclass CGPassManager : public ModulePass, public PMDataManager {\npublic:\n static char ID;\n explicit CGPassManager(int Depth) \n : ModulePass(&ID), PMDataManager(Depth) { }\n\n \/\/\/ run - Execute all of the passes scheduled for execution. Keep track of\n \/\/\/ whether any of the passes modifies the module, and if so, return true.\n bool runOnModule(Module &M);\n\n bool doInitialization(CallGraph &CG);\n bool doFinalization(CallGraph &CG);\n\n \/\/\/ Pass Manager itself does not invalidate any analysis info.\n void getAnalysisUsage(AnalysisUsage &Info) const {\n \/\/ CGPassManager walks SCC and it needs CallGraph.\n Info.addRequired<CallGraph>();\n Info.setPreservesAll();\n }\n\n virtual const char *getPassName() const {\n return \"CallGraph Pass Manager\";\n }\n\n \/\/ Print passes managed by this manager\n void dumpPassStructure(unsigned Offset) {\n errs().indent(Offset*2) << \"Call Graph SCC Pass Manager\\n\";\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {\n Pass *P = getContainedPass(Index);\n P->dumpPassStructure(Offset + 1);\n dumpLastUses(P, Offset+1);\n }\n }\n\n Pass *getContainedPass(unsigned N) {\n assert(N < PassVector.size() && \"Pass number out of range!\");\n return static_cast<Pass *>(PassVector[N]);\n }\n\n virtual PassManagerType getPassManagerType() const { \n return PMT_CallGraphPassManager; \n }\n \nprivate:\n bool RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool &CallGraphUpToDate);\n void RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC, CallGraph &CG,\n bool IsCheckingMode);\n};\n\n} \/\/ end anonymous namespace.\n\nchar CGPassManager::ID = 0;\n\nbool CGPassManager::RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool &CallGraphUpToDate) {\n bool Changed = false;\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass*>(P)) {\n if (!CallGraphUpToDate) {\n RefreshCallGraph(CurSCC, CG, false);\n CallGraphUpToDate = true;\n }\n\n StartPassTimer(CGSP);\n Changed = CGSP->runOnSCC(CurSCC);\n StopPassTimer(CGSP);\n \n \/\/ After the CGSCCPass is done, when assertions are enabled, use\n \/\/ RefreshCallGraph to verify that the callgraph was correctly updated.\n#ifndef NDEBUG\n if (Changed)\n RefreshCallGraph(CurSCC, CG, true);\n#endif\n \n return Changed;\n }\n \n StartPassTimer(P);\n FPPassManager *FPP = dynamic_cast<FPPassManager *>(P);\n assert(FPP && \"Invalid CGPassManager member\");\n \n \/\/ Run pass P on all functions in the current SCC.\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i) {\n if (Function *F = CurSCC[i]->getFunction()) {\n dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());\n Changed |= FPP->runOnFunction(*F);\n }\n }\n StopPassTimer(P);\n \n \/\/ The function pass(es) modified the IR, they may have clobbered the\n \/\/ callgraph.\n if (Changed && CallGraphUpToDate) {\n DEBUG(errs() << \"CGSCCPASSMGR: Pass Dirtied SCC: \"\n << P->getPassName() << '\\n');\n CallGraphUpToDate = false;\n }\n return Changed;\n}\n\n\n\/\/\/ RefreshCallGraph - Scan the functions in the specified CFG and resync the\n\/\/\/ callgraph with the call sites found in it. This is used after\n\/\/\/ FunctionPasses have potentially munged the callgraph, and can be used after\n\/\/\/ CallGraphSCC passes to verify that they correctly updated the callgraph.\n\/\/\/\nvoid CGPassManager::RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool CheckingMode) {\n DenseMap<Value*, CallGraphNode*> CallSites;\n \n DEBUG(errs() << \"CGSCCPASSMGR: Refreshing SCC with \" << CurSCC.size()\n << \" nodes:\\n\";\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)\n CurSCC[i]->dump();\n );\n\n bool MadeChange = false;\n \n \/\/ Scan all functions in the SCC.\n for (unsigned sccidx = 0, e = CurSCC.size(); sccidx != e; ++sccidx) {\n CallGraphNode *CGN = CurSCC[sccidx];\n Function *F = CGN->getFunction();\n if (F == 0 || F->isDeclaration()) continue;\n \n \/\/ Walk the function body looking for call sites. Sync up the call sites in\n \/\/ CGN with those actually in the function.\n \n \/\/ Get the set of call sites currently in the function.\n for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ){\n \/\/ If this call site is null, then the function pass deleted the call\n \/\/ entirely and the WeakVH nulled it out. \n if (I->first == 0 ||\n \/\/ If we've already seen this call site, then the FunctionPass RAUW'd\n \/\/ one call with another, which resulted in two \"uses\" in the edge\n \/\/ list of the same call.\n CallSites.count(I->first) ||\n\n \/\/ If the call edge is not from a call or invoke, then the function\n \/\/ pass RAUW'd a call with another value. This can happen when\n \/\/ constant folding happens of well known functions etc.\n CallSite::get(I->first).getInstruction() == 0) {\n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n \n \/\/ Just remove the edge from the set of callees.\n CGN->removeCallEdge(I);\n E = CGN->end();\n continue;\n }\n \n assert(!CallSites.count(I->first) &&\n \"Call site occurs in node multiple times\");\n CallSites.insert(std::make_pair(I->first, I->second));\n ++I;\n }\n \n \/\/ Loop over all of the instructions in the function, getting the callsites.\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {\n CallSite CS = CallSite::get(I);\n if (!CS.getInstruction() || isa<DbgInfoIntrinsic>(I)) continue;\n \n \/\/ If this call site already existed in the callgraph, just verify it\n \/\/ matches up to expectations and remove it from CallSites.\n DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =\n CallSites.find(CS.getInstruction());\n if (ExistingIt != CallSites.end()) {\n CallGraphNode *ExistingNode = ExistingIt->second;\n\n \/\/ Remove from CallSites since we have now seen it.\n CallSites.erase(ExistingIt);\n \n \/\/ Verify that the callee is right.\n if (ExistingNode->getFunction() == CS.getCalledFunction())\n continue;\n \n \/\/ If we are in checking mode, we are not allowed to actually mutate\n \/\/ the callgraph. If this is a case where we can infer that the\n \/\/ callgraph is less precise than it could be (e.g. an indirect call\n \/\/ site could be turned direct), don't reject it in checking mode, and\n \/\/ don't tweak it to be more precise.\n if (CheckingMode && CS.getCalledFunction() &&\n ExistingNode->getFunction() == 0)\n continue;\n \n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n \n \/\/ If not, we either went from a direct call to indirect, indirect to\n \/\/ direct, or direct to different direct.\n CallGraphNode *CalleeNode;\n if (Function *Callee = CS.getCalledFunction())\n CalleeNode = CG.getOrInsertFunction(Callee);\n else\n CalleeNode = CG.getCallsExternalNode();\n\n \/\/ Update the edge target in CGN.\n for (CallGraphNode::iterator I = CGN->begin(); ; ++I) {\n assert(I != CGN->end() && \"Didn't find call entry\");\n if (I->first == CS.getInstruction()) {\n I->second = CalleeNode;\n break;\n }\n }\n MadeChange = true;\n continue;\n }\n \n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n\n \/\/ If the call site didn't exist in the CGN yet, add it. We assume that\n \/\/ newly introduced call sites won't be indirect. This could be fixed\n \/\/ in the future.\n CallGraphNode *CalleeNode;\n if (Function *Callee = CS.getCalledFunction())\n CalleeNode = CG.getOrInsertFunction(Callee);\n else\n CalleeNode = CG.getCallsExternalNode();\n \n CGN->addCalledFunction(CS, CalleeNode);\n MadeChange = true;\n }\n \n \/\/ After scanning this function, if we still have entries in callsites, then\n \/\/ they are dangling pointers. WeakVH should save us for this, so abort if\n \/\/ this happens.\n assert(CallSites.empty() && \"Dangling pointers found in call sites map\");\n \n \/\/ Periodically do an explicit clear to remove tombstones when processing\n \/\/ large scc's.\n if ((sccidx & 15) == 0)\n CallSites.clear();\n }\n\n DEBUG(if (MadeChange) {\n errs() << \"CGSCCPASSMGR: Refreshed SCC is now:\\n\";\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)\n CurSCC[i]->dump();\n } else {\n errs() << \"CGSCCPASSMGR: SCC Refresh didn't change call graph.\\n\";\n }\n );\n}\n\n\/\/\/ run - Execute all of the passes scheduled for execution. Keep track of\n\/\/\/ whether any of the passes modifies the module, and if so, return true.\nbool CGPassManager::runOnModule(Module &M) {\n CallGraph &CG = getAnalysis<CallGraph>();\n bool Changed = doInitialization(CG);\n\n std::vector<CallGraphNode*> CurSCC;\n \n \/\/ Walk the callgraph in bottom-up SCC order.\n for (scc_iterator<CallGraph*> CGI = scc_begin(&CG), E = scc_end(&CG);\n CGI != E;) {\n \/\/ Copy the current SCC and increment past it so that the pass can hack\n \/\/ on the SCC if it wants to without invalidating our iterator.\n CurSCC = *CGI;\n ++CGI;\n \n \n \/\/ CallGraphUpToDate - Keep track of whether the callgraph is known to be\n \/\/ up-to-date or not. The CGSSC pass manager runs two types of passes:\n \/\/ CallGraphSCC Passes and other random function passes. Because other\n \/\/ random function passes are not CallGraph aware, they may clobber the\n \/\/ call graph by introducing new calls or deleting other ones. This flag\n \/\/ is set to false when we run a function pass so that we know to clean up\n \/\/ the callgraph when we need to run a CGSCCPass again.\n bool CallGraphUpToDate = true;\n \n \/\/ Run all passes on current SCC.\n for (unsigned PassNo = 0, e = getNumContainedPasses();\n PassNo != e; ++PassNo) {\n Pass *P = getContainedPass(PassNo);\n\n dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, \"\");\n dumpRequiredSet(P);\n\n initializeAnalysisImpl(P);\n\n \/\/ Actually run this pass on the current SCC.\n Changed |= RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate);\n\n if (Changed)\n dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, \"\");\n dumpPreservedSet(P);\n\n verifyPreservedAnalysis(P); \n removeNotPreservedAnalysis(P);\n recordAvailableAnalysis(P);\n removeDeadPasses(P, \"\", ON_CG_MSG);\n }\n \n \/\/ If the callgraph was left out of date (because the last pass run was a\n \/\/ functionpass), refresh it before we move on to the next SCC.\n if (!CallGraphUpToDate)\n RefreshCallGraph(CurSCC, CG, false);\n }\n Changed |= doFinalization(CG);\n return Changed;\n}\n\n\/\/\/ Initialize CG\nbool CGPassManager::doInitialization(CallGraph &CG) {\n bool Changed = false;\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { \n Pass *P = getContainedPass(Index);\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {\n Changed |= CGSP->doInitialization(CG);\n } else {\n FPPassManager *FP = dynamic_cast<FPPassManager *>(P);\n assert (FP && \"Invalid CGPassManager member\");\n Changed |= FP->doInitialization(CG.getModule());\n }\n }\n return Changed;\n}\n\n\/\/\/ Finalize CG\nbool CGPassManager::doFinalization(CallGraph &CG) {\n bool Changed = false;\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { \n Pass *P = getContainedPass(Index);\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {\n Changed |= CGSP->doFinalization(CG);\n } else {\n FPPassManager *FP = dynamic_cast<FPPassManager *>(P);\n assert (FP && \"Invalid CGPassManager member\");\n Changed |= FP->doFinalization(CG.getModule());\n }\n }\n return Changed;\n}\n\n\/\/\/ Assign pass manager to manage this pass.\nvoid CallGraphSCCPass::assignPassManager(PMStack &PMS,\n PassManagerType PreferredType) {\n \/\/ Find CGPassManager \n while (!PMS.empty() &&\n PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)\n PMS.pop();\n\n assert (!PMS.empty() && \"Unable to handle Call Graph Pass\");\n CGPassManager *CGP = dynamic_cast<CGPassManager *>(PMS.top());\n\n \/\/ Create new Call Graph SCC Pass Manager if it does not exist. \n if (!CGP) {\n\n assert (!PMS.empty() && \"Unable to create Call Graph Pass Manager\");\n PMDataManager *PMD = PMS.top();\n\n \/\/ [1] Create new Call Graph Pass Manager\n CGP = new CGPassManager(PMD->getDepth() + 1);\n\n \/\/ [2] Set up new manager's top level manager\n PMTopLevelManager *TPM = PMD->getTopLevelManager();\n TPM->addIndirectPassManager(CGP);\n\n \/\/ [3] Assign manager to manage this new manager. This may create\n \/\/ and push new managers into PMS\n Pass *P = dynamic_cast<Pass *>(CGP);\n TPM->schedulePass(P);\n\n \/\/ [4] Push new manager into PMS\n PMS.push(CGP);\n }\n\n CGP->add(this);\n}\n\n\/\/\/ getAnalysisUsage - For this class, we declare that we require and preserve\n\/\/\/ the call graph. If the derived class implements this method, it should\n\/\/\/ always explicitly call the implementation here.\nvoid CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<CallGraph>();\n AU.addPreserved<CallGraph>();\n}\n<commit_msg>Complicate Chris's simplification, avoiding complaints about singular iterators when building with expensive checks turned on.<commit_after>\/\/===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the CallGraphSCCPass class, which is used for passes\n\/\/ which are implemented as bottom-up traversals on the call graph. Because\n\/\/ there may be cycles in the call graph, passes of this type operate on the\n\/\/ call-graph in SCC order: that is, they process function bottom-up, except for\n\/\/ recursive functions, which they process all at once.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"cgscc-passmgr\"\n#include \"llvm\/CallGraphSCCPass.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/ADT\/SCCIterator.h\"\n#include \"llvm\/PassManagers.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ CGPassManager\n\/\/\n\/\/\/ CGPassManager manages FPPassManagers and CalLGraphSCCPasses.\n\nnamespace {\n\nclass CGPassManager : public ModulePass, public PMDataManager {\npublic:\n static char ID;\n explicit CGPassManager(int Depth) \n : ModulePass(&ID), PMDataManager(Depth) { }\n\n \/\/\/ run - Execute all of the passes scheduled for execution. Keep track of\n \/\/\/ whether any of the passes modifies the module, and if so, return true.\n bool runOnModule(Module &M);\n\n bool doInitialization(CallGraph &CG);\n bool doFinalization(CallGraph &CG);\n\n \/\/\/ Pass Manager itself does not invalidate any analysis info.\n void getAnalysisUsage(AnalysisUsage &Info) const {\n \/\/ CGPassManager walks SCC and it needs CallGraph.\n Info.addRequired<CallGraph>();\n Info.setPreservesAll();\n }\n\n virtual const char *getPassName() const {\n return \"CallGraph Pass Manager\";\n }\n\n \/\/ Print passes managed by this manager\n void dumpPassStructure(unsigned Offset) {\n errs().indent(Offset*2) << \"Call Graph SCC Pass Manager\\n\";\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {\n Pass *P = getContainedPass(Index);\n P->dumpPassStructure(Offset + 1);\n dumpLastUses(P, Offset+1);\n }\n }\n\n Pass *getContainedPass(unsigned N) {\n assert(N < PassVector.size() && \"Pass number out of range!\");\n return static_cast<Pass *>(PassVector[N]);\n }\n\n virtual PassManagerType getPassManagerType() const { \n return PMT_CallGraphPassManager; \n }\n \nprivate:\n bool RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool &CallGraphUpToDate);\n void RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC, CallGraph &CG,\n bool IsCheckingMode);\n};\n\n} \/\/ end anonymous namespace.\n\nchar CGPassManager::ID = 0;\n\nbool CGPassManager::RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool &CallGraphUpToDate) {\n bool Changed = false;\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass*>(P)) {\n if (!CallGraphUpToDate) {\n RefreshCallGraph(CurSCC, CG, false);\n CallGraphUpToDate = true;\n }\n\n StartPassTimer(CGSP);\n Changed = CGSP->runOnSCC(CurSCC);\n StopPassTimer(CGSP);\n \n \/\/ After the CGSCCPass is done, when assertions are enabled, use\n \/\/ RefreshCallGraph to verify that the callgraph was correctly updated.\n#ifndef NDEBUG\n if (Changed)\n RefreshCallGraph(CurSCC, CG, true);\n#endif\n \n return Changed;\n }\n \n StartPassTimer(P);\n FPPassManager *FPP = dynamic_cast<FPPassManager *>(P);\n assert(FPP && \"Invalid CGPassManager member\");\n \n \/\/ Run pass P on all functions in the current SCC.\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i) {\n if (Function *F = CurSCC[i]->getFunction()) {\n dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());\n Changed |= FPP->runOnFunction(*F);\n }\n }\n StopPassTimer(P);\n \n \/\/ The function pass(es) modified the IR, they may have clobbered the\n \/\/ callgraph.\n if (Changed && CallGraphUpToDate) {\n DEBUG(errs() << \"CGSCCPASSMGR: Pass Dirtied SCC: \"\n << P->getPassName() << '\\n');\n CallGraphUpToDate = false;\n }\n return Changed;\n}\n\n\n\/\/\/ RefreshCallGraph - Scan the functions in the specified CFG and resync the\n\/\/\/ callgraph with the call sites found in it. This is used after\n\/\/\/ FunctionPasses have potentially munged the callgraph, and can be used after\n\/\/\/ CallGraphSCC passes to verify that they correctly updated the callgraph.\n\/\/\/\nvoid CGPassManager::RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC,\n CallGraph &CG, bool CheckingMode) {\n DenseMap<Value*, CallGraphNode*> CallSites;\n \n DEBUG(errs() << \"CGSCCPASSMGR: Refreshing SCC with \" << CurSCC.size()\n << \" nodes:\\n\";\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)\n CurSCC[i]->dump();\n );\n\n bool MadeChange = false;\n \n \/\/ Scan all functions in the SCC.\n for (unsigned sccidx = 0, e = CurSCC.size(); sccidx != e; ++sccidx) {\n CallGraphNode *CGN = CurSCC[sccidx];\n Function *F = CGN->getFunction();\n if (F == 0 || F->isDeclaration()) continue;\n \n \/\/ Walk the function body looking for call sites. Sync up the call sites in\n \/\/ CGN with those actually in the function.\n \n \/\/ Get the set of call sites currently in the function.\n for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {\n \/\/ If this call site is null, then the function pass deleted the call\n \/\/ entirely and the WeakVH nulled it out. \n if (I->first == 0 ||\n \/\/ If we've already seen this call site, then the FunctionPass RAUW'd\n \/\/ one call with another, which resulted in two \"uses\" in the edge\n \/\/ list of the same call.\n CallSites.count(I->first) ||\n\n \/\/ If the call edge is not from a call or invoke, then the function\n \/\/ pass RAUW'd a call with another value. This can happen when\n \/\/ constant folding happens of well known functions etc.\n CallSite::get(I->first).getInstruction() == 0) {\n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n \n \/\/ Just remove the edge from the set of callees.\n bool wasLast = I + 1 == E;\n CGN->removeCallEdge(I);\n if (wasLast)\n \/\/ I is now a singular iterator, do not compare with E.\n break;\n E = CGN->end();\n continue;\n }\n \n assert(!CallSites.count(I->first) &&\n \"Call site occurs in node multiple times\");\n CallSites.insert(std::make_pair(I->first, I->second));\n ++I;\n }\n \n \/\/ Loop over all of the instructions in the function, getting the callsites.\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {\n CallSite CS = CallSite::get(I);\n if (!CS.getInstruction() || isa<DbgInfoIntrinsic>(I)) continue;\n \n \/\/ If this call site already existed in the callgraph, just verify it\n \/\/ matches up to expectations and remove it from CallSites.\n DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =\n CallSites.find(CS.getInstruction());\n if (ExistingIt != CallSites.end()) {\n CallGraphNode *ExistingNode = ExistingIt->second;\n\n \/\/ Remove from CallSites since we have now seen it.\n CallSites.erase(ExistingIt);\n \n \/\/ Verify that the callee is right.\n if (ExistingNode->getFunction() == CS.getCalledFunction())\n continue;\n \n \/\/ If we are in checking mode, we are not allowed to actually mutate\n \/\/ the callgraph. If this is a case where we can infer that the\n \/\/ callgraph is less precise than it could be (e.g. an indirect call\n \/\/ site could be turned direct), don't reject it in checking mode, and\n \/\/ don't tweak it to be more precise.\n if (CheckingMode && CS.getCalledFunction() &&\n ExistingNode->getFunction() == 0)\n continue;\n \n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n \n \/\/ If not, we either went from a direct call to indirect, indirect to\n \/\/ direct, or direct to different direct.\n CallGraphNode *CalleeNode;\n if (Function *Callee = CS.getCalledFunction())\n CalleeNode = CG.getOrInsertFunction(Callee);\n else\n CalleeNode = CG.getCallsExternalNode();\n\n \/\/ Update the edge target in CGN.\n for (CallGraphNode::iterator I = CGN->begin(); ; ++I) {\n assert(I != CGN->end() && \"Didn't find call entry\");\n if (I->first == CS.getInstruction()) {\n I->second = CalleeNode;\n break;\n }\n }\n MadeChange = true;\n continue;\n }\n \n assert(!CheckingMode &&\n \"CallGraphSCCPass did not update the CallGraph correctly!\");\n\n \/\/ If the call site didn't exist in the CGN yet, add it. We assume that\n \/\/ newly introduced call sites won't be indirect. This could be fixed\n \/\/ in the future.\n CallGraphNode *CalleeNode;\n if (Function *Callee = CS.getCalledFunction())\n CalleeNode = CG.getOrInsertFunction(Callee);\n else\n CalleeNode = CG.getCallsExternalNode();\n \n CGN->addCalledFunction(CS, CalleeNode);\n MadeChange = true;\n }\n \n \/\/ After scanning this function, if we still have entries in callsites, then\n \/\/ they are dangling pointers. WeakVH should save us for this, so abort if\n \/\/ this happens.\n assert(CallSites.empty() && \"Dangling pointers found in call sites map\");\n \n \/\/ Periodically do an explicit clear to remove tombstones when processing\n \/\/ large scc's.\n if ((sccidx & 15) == 0)\n CallSites.clear();\n }\n\n DEBUG(if (MadeChange) {\n errs() << \"CGSCCPASSMGR: Refreshed SCC is now:\\n\";\n for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)\n CurSCC[i]->dump();\n } else {\n errs() << \"CGSCCPASSMGR: SCC Refresh didn't change call graph.\\n\";\n }\n );\n}\n\n\/\/\/ run - Execute all of the passes scheduled for execution. Keep track of\n\/\/\/ whether any of the passes modifies the module, and if so, return true.\nbool CGPassManager::runOnModule(Module &M) {\n CallGraph &CG = getAnalysis<CallGraph>();\n bool Changed = doInitialization(CG);\n\n std::vector<CallGraphNode*> CurSCC;\n \n \/\/ Walk the callgraph in bottom-up SCC order.\n for (scc_iterator<CallGraph*> CGI = scc_begin(&CG), E = scc_end(&CG);\n CGI != E;) {\n \/\/ Copy the current SCC and increment past it so that the pass can hack\n \/\/ on the SCC if it wants to without invalidating our iterator.\n CurSCC = *CGI;\n ++CGI;\n \n \n \/\/ CallGraphUpToDate - Keep track of whether the callgraph is known to be\n \/\/ up-to-date or not. The CGSSC pass manager runs two types of passes:\n \/\/ CallGraphSCC Passes and other random function passes. Because other\n \/\/ random function passes are not CallGraph aware, they may clobber the\n \/\/ call graph by introducing new calls or deleting other ones. This flag\n \/\/ is set to false when we run a function pass so that we know to clean up\n \/\/ the callgraph when we need to run a CGSCCPass again.\n bool CallGraphUpToDate = true;\n \n \/\/ Run all passes on current SCC.\n for (unsigned PassNo = 0, e = getNumContainedPasses();\n PassNo != e; ++PassNo) {\n Pass *P = getContainedPass(PassNo);\n\n dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, \"\");\n dumpRequiredSet(P);\n\n initializeAnalysisImpl(P);\n\n \/\/ Actually run this pass on the current SCC.\n Changed |= RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate);\n\n if (Changed)\n dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, \"\");\n dumpPreservedSet(P);\n\n verifyPreservedAnalysis(P); \n removeNotPreservedAnalysis(P);\n recordAvailableAnalysis(P);\n removeDeadPasses(P, \"\", ON_CG_MSG);\n }\n \n \/\/ If the callgraph was left out of date (because the last pass run was a\n \/\/ functionpass), refresh it before we move on to the next SCC.\n if (!CallGraphUpToDate)\n RefreshCallGraph(CurSCC, CG, false);\n }\n Changed |= doFinalization(CG);\n return Changed;\n}\n\n\/\/\/ Initialize CG\nbool CGPassManager::doInitialization(CallGraph &CG) {\n bool Changed = false;\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { \n Pass *P = getContainedPass(Index);\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {\n Changed |= CGSP->doInitialization(CG);\n } else {\n FPPassManager *FP = dynamic_cast<FPPassManager *>(P);\n assert (FP && \"Invalid CGPassManager member\");\n Changed |= FP->doInitialization(CG.getModule());\n }\n }\n return Changed;\n}\n\n\/\/\/ Finalize CG\nbool CGPassManager::doFinalization(CallGraph &CG) {\n bool Changed = false;\n for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { \n Pass *P = getContainedPass(Index);\n if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {\n Changed |= CGSP->doFinalization(CG);\n } else {\n FPPassManager *FP = dynamic_cast<FPPassManager *>(P);\n assert (FP && \"Invalid CGPassManager member\");\n Changed |= FP->doFinalization(CG.getModule());\n }\n }\n return Changed;\n}\n\n\/\/\/ Assign pass manager to manage this pass.\nvoid CallGraphSCCPass::assignPassManager(PMStack &PMS,\n PassManagerType PreferredType) {\n \/\/ Find CGPassManager \n while (!PMS.empty() &&\n PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)\n PMS.pop();\n\n assert (!PMS.empty() && \"Unable to handle Call Graph Pass\");\n CGPassManager *CGP = dynamic_cast<CGPassManager *>(PMS.top());\n\n \/\/ Create new Call Graph SCC Pass Manager if it does not exist. \n if (!CGP) {\n\n assert (!PMS.empty() && \"Unable to create Call Graph Pass Manager\");\n PMDataManager *PMD = PMS.top();\n\n \/\/ [1] Create new Call Graph Pass Manager\n CGP = new CGPassManager(PMD->getDepth() + 1);\n\n \/\/ [2] Set up new manager's top level manager\n PMTopLevelManager *TPM = PMD->getTopLevelManager();\n TPM->addIndirectPassManager(CGP);\n\n \/\/ [3] Assign manager to manage this new manager. This may create\n \/\/ and push new managers into PMS\n Pass *P = dynamic_cast<Pass *>(CGP);\n TPM->schedulePass(P);\n\n \/\/ [4] Push new manager into PMS\n PMS.push(CGP);\n }\n\n CGP->add(this);\n}\n\n\/\/\/ getAnalysisUsage - For this class, we declare that we require and preserve\n\/\/\/ the call graph. If the derived class implements this method, it should\n\/\/\/ always explicitly call the implementation here.\nvoid CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<CallGraph>();\n AU.addPreserved<CallGraph>();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- LogDiagnosticPrinter.cpp - Log Diagnostic Printer ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Frontend\/LogDiagnosticPrinter.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\n\nLogDiagnosticPrinter::LogDiagnosticPrinter(llvm::raw_ostream &os,\n const DiagnosticOptions &diags,\n bool _OwnsOutputStream)\n : OS(os), LangOpts(0), DiagOpts(&diags),\n OwnsOutputStream(_OwnsOutputStream) {\n}\n\nLogDiagnosticPrinter::~LogDiagnosticPrinter() {\n if (OwnsOutputStream)\n delete &OS;\n}\n\nstatic llvm::StringRef getLevelName(Diagnostic::Level Level) {\n switch (Level) {\n default:\n return \"<unknown>\";\n case Diagnostic::Ignored: return \"ignored\";\n case Diagnostic::Note: return \"note\";\n case Diagnostic::Warning: return \"warning\";\n case Diagnostic::Error: return \"error\";\n case Diagnostic::Fatal: return \"fatal error\";\n }\n}\n\nvoid LogDiagnosticPrinter::EndSourceFile() {\n \/\/ We emit all the diagnostics in EndSourceFile. However, we don't emit any\n \/\/ entry if no diagnostics were present.\n \/\/\n \/\/ Note that DiagnosticClient has no \"end-of-compilation\" callback, so we will\n \/\/ miss any diagnostics which are emitted after and outside the translation\n \/\/ unit processing.\n if (Entries.empty())\n return;\n\n \/\/ Write to a temporary string to ensure atomic write of diagnostic object.\n llvm::SmallString<512> Msg;\n llvm::raw_svector_ostream OS(Msg);\n\n OS << \"{\\n\";\n \/\/ FIXME: Output main translation unit file name.\n \/\/ FIXME: Include the invocation, if dwarf-debug-flags is available.\n OS << \" \\\"diagnostics\\\" : [\\n\";\n for (unsigned i = 0, e = Entries.size(); i != e; ++i) {\n DiagEntry &DE = Entries[i];\n\n OS << \" {\\n\";\n OS << \" \\\"filename\\\" : \\\"\" << DE.Filename << \"\\\",\\n\";\n OS << \" \\\"line\\\" : \" << DE.Line << \",\\n\";\n OS << \" \\\"column\\\" : \" << DE.Column << \",\\n\";\n OS << \" \\\"message\\\" : \\\"\" << DE.Message << \"\\\",\\n\";\n OS << \" \\\"level\\\" : \\\"\" << getLevelName(DE.DiagnosticLevel) << \"\\\"\\n\";\n OS << \" }\" << ((i + 1 != e) ? \",\" : \"\") << '\\n';\n }\n OS << \" ]\\n\";\n OS << \"},\\n\";\n\n this->OS << OS.str();\n}\n\nvoid LogDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,\n const DiagnosticInfo &Info) {\n \/\/ Default implementation (Warnings\/errors count).\n DiagnosticClient::HandleDiagnostic(Level, Info);\n\n \/\/ Create the diag entry.\n DiagEntry DE;\n DE.DiagnosticID = Info.getID();\n DE.DiagnosticLevel = Level;\n\n \/\/ Format the message.\n llvm::SmallString<100> MessageStr;\n Info.FormatDiagnostic(MessageStr);\n DE.Message = MessageStr.str();\n\n \/\/ Set the location information.\n DE.Filename = \"\";\n DE.Line = DE.Column = 0;\n if (Info.getLocation().isValid()) {\n const SourceManager &SM = Info.getSourceManager();\n PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());\n\n if (PLoc.isInvalid()) {\n \/\/ At least print the file name if available:\n FileID FID = SM.getFileID(Info.getLocation());\n if (!FID.isInvalid()) {\n const FileEntry *FE = SM.getFileEntryForID(FID);\n if (FE && FE->getName())\n DE.Filename = FE->getName();\n }\n } else {\n DE.Filename = PLoc.getFilename();\n DE.Line = PLoc.getLine();\n DE.Column = PLoc.getColumn();\n }\n }\n\n \/\/ Record the diagnostic entry.\n Entries.push_back(DE);\n}\n<commit_msg>Fronted\/CC_LOG_DIAGNOSTICS: Tweak output form to be plist chunks, and don't output missing data.<commit_after>\/\/===--- LogDiagnosticPrinter.cpp - Log Diagnostic Printer ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Frontend\/LogDiagnosticPrinter.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\n\nLogDiagnosticPrinter::LogDiagnosticPrinter(llvm::raw_ostream &os,\n const DiagnosticOptions &diags,\n bool _OwnsOutputStream)\n : OS(os), LangOpts(0), DiagOpts(&diags),\n OwnsOutputStream(_OwnsOutputStream) {\n}\n\nLogDiagnosticPrinter::~LogDiagnosticPrinter() {\n if (OwnsOutputStream)\n delete &OS;\n}\n\nstatic llvm::StringRef getLevelName(Diagnostic::Level Level) {\n switch (Level) {\n default:\n return \"<unknown>\";\n case Diagnostic::Ignored: return \"ignored\";\n case Diagnostic::Note: return \"note\";\n case Diagnostic::Warning: return \"warning\";\n case Diagnostic::Error: return \"error\";\n case Diagnostic::Fatal: return \"fatal error\";\n }\n}\n\nvoid LogDiagnosticPrinter::EndSourceFile() {\n \/\/ We emit all the diagnostics in EndSourceFile. However, we don't emit any\n \/\/ entry if no diagnostics were present.\n \/\/\n \/\/ Note that DiagnosticClient has no \"end-of-compilation\" callback, so we will\n \/\/ miss any diagnostics which are emitted after and outside the translation\n \/\/ unit processing.\n if (Entries.empty())\n return;\n\n \/\/ Write to a temporary string to ensure atomic write of diagnostic object.\n llvm::SmallString<512> Msg;\n llvm::raw_svector_ostream OS(Msg);\n\n OS << \"<dict>\\n\";\n \/\/ FIXME: Output main translation unit file name.\n \/\/ FIXME: Include the invocation, if dwarf-debug-flags is available.\n OS << \" <key>diagnostics<\/key>\\n\";\n OS << \" <array>\\n\";\n for (unsigned i = 0, e = Entries.size(); i != e; ++i) {\n DiagEntry &DE = Entries[i];\n\n OS << \" <dict>\\n\";\n OS << \" <key>level<\/key>\\n\"\n << \" <string>\" << getLevelName(DE.DiagnosticLevel) << \"<\/string>\\n\";\n if (!DE.Filename.empty()) {\n OS << \" <key>filename<\/key>\\n\"\n << \" <string>\" << DE.Filename << \"<\/string>\\n\";\n }\n if (DE.Line != 0) {\n OS << \" <key>line<\/key>\\n\"\n << \" <integer>\" << DE.Line << \"<\/integer>\\n\";\n }\n if (DE.Column != 0) {\n OS << \" <key>column<\/key>\\n\"\n << \" <integer>\" << DE.Column << \"<\/integer>\\n\";\n }\n if (!DE.Message.empty()) {\n OS << \" <key>message<\/key>\\n\"\n << \" <string>\" << DE.Message << \"<\/string>\\n\";\n }\n OS << \" <\/dict>\\n\";\n }\n OS << \" <\/array>\\n\";\n OS << \"<\/dict>\\n\";\n\n this->OS << OS.str();\n}\n\nvoid LogDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,\n const DiagnosticInfo &Info) {\n \/\/ Default implementation (Warnings\/errors count).\n DiagnosticClient::HandleDiagnostic(Level, Info);\n\n \/\/ Create the diag entry.\n DiagEntry DE;\n DE.DiagnosticID = Info.getID();\n DE.DiagnosticLevel = Level;\n\n \/\/ Format the message.\n llvm::SmallString<100> MessageStr;\n Info.FormatDiagnostic(MessageStr);\n DE.Message = MessageStr.str();\n\n \/\/ Set the location information.\n DE.Filename = \"\";\n DE.Line = DE.Column = 0;\n if (Info.getLocation().isValid()) {\n const SourceManager &SM = Info.getSourceManager();\n PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());\n\n if (PLoc.isInvalid()) {\n \/\/ At least print the file name if available:\n FileID FID = SM.getFileID(Info.getLocation());\n if (!FID.isInvalid()) {\n const FileEntry *FE = SM.getFileEntryForID(FID);\n if (FE && FE->getName())\n DE.Filename = FE->getName();\n }\n } else {\n DE.Filename = PLoc.getFilename();\n DE.Line = PLoc.getLine();\n DE.Column = PLoc.getColumn();\n }\n }\n\n \/\/ Record the diagnostic entry.\n Entries.push_back(DE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=== Taint.cpp - Taint tracking and basic propagation rules. ------*- C++ -*-\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Defines basic, non-domain-specific mechanisms for tracking tainted values.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Taint.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugReporter.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ProgramStateTrait.h\"\n\nusing namespace clang;\nusing namespace ento;\nusing namespace taint;\n\n\/\/ Fully tainted symbols.\nREGISTER_MAP_WITH_PROGRAMSTATE(TaintMap, SymbolRef, TaintTagType)\n\n\/\/ Partially tainted symbols.\nREGISTER_MAP_FACTORY_WITH_PROGRAMSTATE(TaintedSubRegions, const SubRegion *,\n TaintTagType);\nREGISTER_MAP_WITH_PROGRAMSTATE(DerivedSymTaint, SymbolRef, TaintedSubRegions)\n\nvoid taint::printTaint(ProgramStateRef State, raw_ostream &Out, const char *NL,\n const char *Sep) {\n TaintMapTy TM = State->get<TaintMap>();\n\n if (!TM.isEmpty())\n Out << \"Tainted symbols:\" << NL;\n\n for (const auto &I : TM)\n Out << I.first << \" : \" << I.second << NL;\n}\n\nvoid dumpTaint(ProgramStateRef State) {\n printTaint(State, llvm::errs());\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, const Stmt *S,\n const LocationContext *LCtx,\n TaintTagType Kind) {\n return addTaint(State, State->getSVal(S, LCtx), Kind);\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, SVal V,\n TaintTagType Kind) {\n SymbolRef Sym = V.getAsSymbol();\n if (Sym)\n return addTaint(State, Sym, Kind);\n\n \/\/ If the SVal represents a structure, try to mass-taint all values within the\n \/\/ structure. For now it only works efficiently on lazy compound values that\n \/\/ were conjured during a conservative evaluation of a function - either as\n \/\/ return values of functions that return structures or arrays by value, or as\n \/\/ values of structures or arrays passed into the function by reference,\n \/\/ directly or through pointer aliasing. Such lazy compound values are\n \/\/ characterized by having exactly one binding in their captured store within\n \/\/ their parent region, which is a conjured symbol default-bound to the base\n \/\/ region of the parent region.\n if (auto LCV = V.getAs<nonloc::LazyCompoundVal>()) {\n if (Optional<SVal> binding =\n State->getStateManager().getStoreManager()\n .getDefaultBinding(*LCV)) {\n if (SymbolRef Sym = binding->getAsSymbol())\n return addPartialTaint(State, Sym, LCV->getRegion(), Kind);\n }\n }\n\n const MemRegion *R = V.getAsRegion();\n return addTaint(State, R, Kind);\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, const MemRegion *R,\n TaintTagType Kind) {\n if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))\n return addTaint(State, SR->getSymbol(), Kind);\n return State;\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, SymbolRef Sym,\n TaintTagType Kind) {\n \/\/ If this is a symbol cast, remove the cast before adding the taint. Taint\n \/\/ is cast agnostic.\n while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))\n Sym = SC->getOperand();\n\n ProgramStateRef NewState = State->set<TaintMap>(Sym, Kind);\n assert(NewState);\n return NewState;\n}\n\nProgramStateRef taint::addPartialTaint(ProgramStateRef State,\n SymbolRef ParentSym,\n const SubRegion *SubRegion,\n TaintTagType Kind) {\n \/\/ Ignore partial taint if the entire parent symbol is already tainted.\n if (const TaintTagType *T = State->get<TaintMap>(ParentSym))\n if (*T == Kind)\n return State;\n\n \/\/ Partial taint applies if only a portion of the symbol is tainted.\n if (SubRegion == SubRegion->getBaseRegion())\n return addTaint(State, ParentSym, Kind);\n\n const TaintedSubRegions *SavedRegs = State->get<DerivedSymTaint>(ParentSym);\n TaintedSubRegions::Factory &F = State->get_context<TaintedSubRegions>();\n TaintedSubRegions Regs = SavedRegs ? *SavedRegs : F.getEmptyMap();\n\n Regs = F.add(Regs, SubRegion, Kind);\n ProgramStateRef NewState = State->set<DerivedSymTaint>(ParentSym, Regs);\n assert(NewState);\n return NewState;\n}\n\nbool taint::isTainted(ProgramStateRef State, const Stmt *S,\n const LocationContext *LCtx, TaintTagType Kind) {\n SVal val = State->getSVal(S, LCtx);\n return isTainted(State, val, Kind);\n}\n\nbool taint::isTainted(ProgramStateRef State, SVal V, TaintTagType Kind) {\n if (const SymExpr *Sym = V.getAsSymExpr())\n return isTainted(State, Sym, Kind);\n if (const MemRegion *Reg = V.getAsRegion())\n return isTainted(State, Reg, Kind);\n return false;\n}\n\nbool taint::isTainted(ProgramStateRef State, const MemRegion *Reg,\n TaintTagType K) {\n if (!Reg)\n return false;\n\n \/\/ Element region (array element) is tainted if either the base or the offset\n \/\/ are tainted.\n if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))\n return isTainted(State, ER->getSuperRegion(), K) ||\n isTainted(State, ER->getIndex(), K);\n\n if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))\n return isTainted(State, SR->getSymbol(), K);\n\n if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))\n return isTainted(State, ER->getSuperRegion(), K);\n\n return false;\n}\n\nbool taint::isTainted(ProgramStateRef State, SymbolRef Sym, TaintTagType Kind) {\n if (!Sym)\n return false;\n\n \/\/ Traverse all the symbols this symbol depends on to see if any are tainted.\n for (SymExpr::symbol_iterator SI = Sym->symbol_begin(),\n SE = Sym->symbol_end(); SI != SE; ++SI) {\n if (!isa<SymbolData>(*SI))\n continue;\n\n if (const TaintTagType *Tag = State->get<TaintMap>(*SI)) {\n if (*Tag == Kind)\n return true;\n }\n\n if (const auto *SD = dyn_cast<SymbolDerived>(*SI)) {\n \/\/ If this is a SymbolDerived with a tainted parent, it's also tainted.\n if (isTainted(State, SD->getParentSymbol(), Kind))\n return true;\n\n \/\/ If this is a SymbolDerived with the same parent symbol as another\n \/\/ tainted SymbolDerived and a region that's a sub-region of that tainted\n \/\/ symbol, it's also tainted.\n if (const TaintedSubRegions *Regs =\n State->get<DerivedSymTaint>(SD->getParentSymbol())) {\n const TypedValueRegion *R = SD->getRegion();\n for (auto I : *Regs) {\n \/\/ FIXME: The logic to identify tainted regions could be more\n \/\/ complete. For example, this would not currently identify\n \/\/ overlapping fields in a union as tainted. To identify this we can\n \/\/ check for overlapping\/nested byte offsets.\n if (Kind == I.second && R->isSubRegionOf(I.first))\n return true;\n }\n }\n }\n\n \/\/ If memory region is tainted, data is also tainted.\n if (const auto *SRV = dyn_cast<SymbolRegionValue>(*SI)) {\n if (isTainted(State, SRV->getRegion(), Kind))\n return true;\n }\n\n \/\/ If this is a SymbolCast from a tainted value, it's also tainted.\n if (const auto *SC = dyn_cast<SymbolCast>(*SI)) {\n if (isTainted(State, SC->getOperand(), Kind))\n return true;\n }\n }\n\n return false;\n}\n\nstd::shared_ptr<PathDiagnosticPiece>\nTaintBugVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,\n BugReport &BR) {\n\n \/\/ Find the ExplodedNode where the taint was first introduced\n if (!isTainted(N->getState(), V) ||\n isTainted(N->getFirstPred()->getState(), V))\n return nullptr;\n\n const Stmt *S = PathDiagnosticLocation::getStmt(N);\n if (!S)\n return nullptr;\n\n const LocationContext *NCtx = N->getLocationContext();\n PathDiagnosticLocation L =\n PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);\n if (!L.isValid() || !L.asLocation().isValid())\n return nullptr;\n\n return std::make_shared<PathDiagnosticEventPiece>(L, \"Taint originated here\");\n}\n<commit_msg>Fix compiler warning, remove extra \";\" [NFC]<commit_after>\/\/=== Taint.cpp - Taint tracking and basic propagation rules. ------*- C++ -*-\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Defines basic, non-domain-specific mechanisms for tracking tainted values.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Taint.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugReporter.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ProgramStateTrait.h\"\n\nusing namespace clang;\nusing namespace ento;\nusing namespace taint;\n\n\/\/ Fully tainted symbols.\nREGISTER_MAP_WITH_PROGRAMSTATE(TaintMap, SymbolRef, TaintTagType)\n\n\/\/ Partially tainted symbols.\nREGISTER_MAP_FACTORY_WITH_PROGRAMSTATE(TaintedSubRegions, const SubRegion *,\n TaintTagType)\nREGISTER_MAP_WITH_PROGRAMSTATE(DerivedSymTaint, SymbolRef, TaintedSubRegions)\n\nvoid taint::printTaint(ProgramStateRef State, raw_ostream &Out, const char *NL,\n const char *Sep) {\n TaintMapTy TM = State->get<TaintMap>();\n\n if (!TM.isEmpty())\n Out << \"Tainted symbols:\" << NL;\n\n for (const auto &I : TM)\n Out << I.first << \" : \" << I.second << NL;\n}\n\nvoid dumpTaint(ProgramStateRef State) {\n printTaint(State, llvm::errs());\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, const Stmt *S,\n const LocationContext *LCtx,\n TaintTagType Kind) {\n return addTaint(State, State->getSVal(S, LCtx), Kind);\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, SVal V,\n TaintTagType Kind) {\n SymbolRef Sym = V.getAsSymbol();\n if (Sym)\n return addTaint(State, Sym, Kind);\n\n \/\/ If the SVal represents a structure, try to mass-taint all values within the\n \/\/ structure. For now it only works efficiently on lazy compound values that\n \/\/ were conjured during a conservative evaluation of a function - either as\n \/\/ return values of functions that return structures or arrays by value, or as\n \/\/ values of structures or arrays passed into the function by reference,\n \/\/ directly or through pointer aliasing. Such lazy compound values are\n \/\/ characterized by having exactly one binding in their captured store within\n \/\/ their parent region, which is a conjured symbol default-bound to the base\n \/\/ region of the parent region.\n if (auto LCV = V.getAs<nonloc::LazyCompoundVal>()) {\n if (Optional<SVal> binding =\n State->getStateManager().getStoreManager()\n .getDefaultBinding(*LCV)) {\n if (SymbolRef Sym = binding->getAsSymbol())\n return addPartialTaint(State, Sym, LCV->getRegion(), Kind);\n }\n }\n\n const MemRegion *R = V.getAsRegion();\n return addTaint(State, R, Kind);\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, const MemRegion *R,\n TaintTagType Kind) {\n if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))\n return addTaint(State, SR->getSymbol(), Kind);\n return State;\n}\n\nProgramStateRef taint::addTaint(ProgramStateRef State, SymbolRef Sym,\n TaintTagType Kind) {\n \/\/ If this is a symbol cast, remove the cast before adding the taint. Taint\n \/\/ is cast agnostic.\n while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))\n Sym = SC->getOperand();\n\n ProgramStateRef NewState = State->set<TaintMap>(Sym, Kind);\n assert(NewState);\n return NewState;\n}\n\nProgramStateRef taint::addPartialTaint(ProgramStateRef State,\n SymbolRef ParentSym,\n const SubRegion *SubRegion,\n TaintTagType Kind) {\n \/\/ Ignore partial taint if the entire parent symbol is already tainted.\n if (const TaintTagType *T = State->get<TaintMap>(ParentSym))\n if (*T == Kind)\n return State;\n\n \/\/ Partial taint applies if only a portion of the symbol is tainted.\n if (SubRegion == SubRegion->getBaseRegion())\n return addTaint(State, ParentSym, Kind);\n\n const TaintedSubRegions *SavedRegs = State->get<DerivedSymTaint>(ParentSym);\n TaintedSubRegions::Factory &F = State->get_context<TaintedSubRegions>();\n TaintedSubRegions Regs = SavedRegs ? *SavedRegs : F.getEmptyMap();\n\n Regs = F.add(Regs, SubRegion, Kind);\n ProgramStateRef NewState = State->set<DerivedSymTaint>(ParentSym, Regs);\n assert(NewState);\n return NewState;\n}\n\nbool taint::isTainted(ProgramStateRef State, const Stmt *S,\n const LocationContext *LCtx, TaintTagType Kind) {\n SVal val = State->getSVal(S, LCtx);\n return isTainted(State, val, Kind);\n}\n\nbool taint::isTainted(ProgramStateRef State, SVal V, TaintTagType Kind) {\n if (const SymExpr *Sym = V.getAsSymExpr())\n return isTainted(State, Sym, Kind);\n if (const MemRegion *Reg = V.getAsRegion())\n return isTainted(State, Reg, Kind);\n return false;\n}\n\nbool taint::isTainted(ProgramStateRef State, const MemRegion *Reg,\n TaintTagType K) {\n if (!Reg)\n return false;\n\n \/\/ Element region (array element) is tainted if either the base or the offset\n \/\/ are tainted.\n if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))\n return isTainted(State, ER->getSuperRegion(), K) ||\n isTainted(State, ER->getIndex(), K);\n\n if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))\n return isTainted(State, SR->getSymbol(), K);\n\n if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))\n return isTainted(State, ER->getSuperRegion(), K);\n\n return false;\n}\n\nbool taint::isTainted(ProgramStateRef State, SymbolRef Sym, TaintTagType Kind) {\n if (!Sym)\n return false;\n\n \/\/ Traverse all the symbols this symbol depends on to see if any are tainted.\n for (SymExpr::symbol_iterator SI = Sym->symbol_begin(),\n SE = Sym->symbol_end(); SI != SE; ++SI) {\n if (!isa<SymbolData>(*SI))\n continue;\n\n if (const TaintTagType *Tag = State->get<TaintMap>(*SI)) {\n if (*Tag == Kind)\n return true;\n }\n\n if (const auto *SD = dyn_cast<SymbolDerived>(*SI)) {\n \/\/ If this is a SymbolDerived with a tainted parent, it's also tainted.\n if (isTainted(State, SD->getParentSymbol(), Kind))\n return true;\n\n \/\/ If this is a SymbolDerived with the same parent symbol as another\n \/\/ tainted SymbolDerived and a region that's a sub-region of that tainted\n \/\/ symbol, it's also tainted.\n if (const TaintedSubRegions *Regs =\n State->get<DerivedSymTaint>(SD->getParentSymbol())) {\n const TypedValueRegion *R = SD->getRegion();\n for (auto I : *Regs) {\n \/\/ FIXME: The logic to identify tainted regions could be more\n \/\/ complete. For example, this would not currently identify\n \/\/ overlapping fields in a union as tainted. To identify this we can\n \/\/ check for overlapping\/nested byte offsets.\n if (Kind == I.second && R->isSubRegionOf(I.first))\n return true;\n }\n }\n }\n\n \/\/ If memory region is tainted, data is also tainted.\n if (const auto *SRV = dyn_cast<SymbolRegionValue>(*SI)) {\n if (isTainted(State, SRV->getRegion(), Kind))\n return true;\n }\n\n \/\/ If this is a SymbolCast from a tainted value, it's also tainted.\n if (const auto *SC = dyn_cast<SymbolCast>(*SI)) {\n if (isTainted(State, SC->getOperand(), Kind))\n return true;\n }\n }\n\n return false;\n}\n\nstd::shared_ptr<PathDiagnosticPiece>\nTaintBugVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,\n BugReport &BR) {\n\n \/\/ Find the ExplodedNode where the taint was first introduced\n if (!isTainted(N->getState(), V) ||\n isTainted(N->getFirstPred()->getState(), V))\n return nullptr;\n\n const Stmt *S = PathDiagnosticLocation::getStmt(N);\n if (!S)\n return nullptr;\n\n const LocationContext *NCtx = N->getLocationContext();\n PathDiagnosticLocation L =\n PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);\n if (!L.isValid() || !L.asLocation().isValid())\n return nullptr;\n\n return std::make_shared<PathDiagnosticEventPiece>(L, \"Taint originated here\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <arpa\/inet.h>\n\n#include <pistache\/listener.h>\n#include <pistache\/http.h>\nclass SocketWrapper {\n\npublic:\n explicit SocketWrapper(int fd): fd_(fd) {}\n ~SocketWrapper() { close(fd_);}\n\n uint16_t port() {\n sockaddr_in sin;\n socklen_t len = sizeof(sin);\n\n uint16_t port = 0;\n if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) {\n perror(\"getsockname\");\n } else {\n port = ntohs(sin.sin_port);\n }\n return port;\n }\nprivate:\n int fd_;\n};\n\n\/\/ Just there for show.\nclass DummyHandler : public Pistache::Http::Handler {\npublic:\n\nHTTP_PROTOTYPE(DummyHandler)\n\n void onRequest(const Pistache::Http::Request& request, Pistache::Http::ResponseWriter response) override {\n UNUSED(request);\n response.send(Pistache::Http::Code::Ok, \"I am a dummy handler\\n\");\n }\n};\n\n\/*\n * Will try to get a free port by binding port 0.\n *\/\nSocketWrapper bind_free_port() {\n int sockfd; \/\/ listen on sock_fd, new connection on new_fd\n addrinfo hints, *servinfo, *p;\n\n int yes=1;\n int rv;\n\n memset(&hints, 0, sizeof hints);\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE; \/\/ use my IP\n\n if ((rv = getaddrinfo(nullptr, \"0\", &hints, &servinfo)) != 0) {\n std::cerr << \"getaddrinfo: \" << gai_strerror(rv) << \"\\n\";\n exit(1);\n }\n\n \/\/ loop through all the results and bind to the first we can\n for(p = servinfo; p != nullptr; p = p->ai_next) {\n if ((sockfd = socket(p->ai_family, p->ai_socktype,\n p->ai_protocol)) == -1) {\n perror(\"server: socket\");\n continue;\n }\n\n if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,\n sizeof(int)) == -1) {\n perror(\"setsockopt\");\n exit(1);\n }\n\n if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {\n close(sockfd);\n perror(\"server: bind\");\n continue;\n }\n\n break;\n }\n\n freeaddrinfo(servinfo); \/\/ all done with this structure\n\n if (p == nullptr) {\n fprintf(stderr, \"server: failed to bind\\n\");\n exit(1);\n }\n return SocketWrapper(sockfd);\n}\n\nTEST(listener_test, listener_bind_port_free) {\n uint16_t port_nb;\n\n \/\/ This is just done to get the value of a free port. The socket will be closed\n \/\/ after the closing curly bracket and the port will be free again (SO_REUSEADDR option).\n \/\/ In theory, it is possible that some application grab this port before we bind it again...\n {\n SocketWrapper s = bind_free_port();\n port_nb = s.port();\n }\n\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.init(1, options);\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n ASSERT_TRUE(true);\n}\n\nTEST(listener_test, listener_bind_ephemeral_v6_port) {\n Pistache::Port port(0);\n Pistache::Address address(Pistache::Ipv6::any(), port);\n\n Pistache::Tcp::Listener listener;\n if (not listener.systemSupportsIpv6()) {\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.init(1, options);\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n }\n ASSERT_TRUE(true);\n}\n\n\/\/ Listener should not crash if an additional member is added to the listener class. This test\n\/\/ is there to prevent regression for PR 303\nTEST(listener_test, listener_uses_default) {\n uint16_t port_nb;\n\n \/\/ This is just done to get the value of a free port. The socket will be closed\n \/\/ after the closing curly bracket and the port will be free again (SO_REUSEADDR option).\n \/\/ In theory, it is possible that some application grab this port before we bind it again...\n {\n SocketWrapper s = bind_free_port();\n port_nb = s.port();\n }\n\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n ASSERT_TRUE(true);\n}\n\n\n\nTEST(listener_test, listener_bind_port_not_free_throw_runtime) {\n\n SocketWrapper s = bind_free_port();\n uint16_t port_nb = s.port();\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.init(1, options);\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n\n try {\n listener.bind(address);\n FAIL() << \"Expected std::runtime_error while binding, got nothing\";\n } catch (std::runtime_error const & err) {\n std::cout << err.what() << std::endl;\n ASSERT_STREQ(\"Address already in use\", err.what());\n } catch ( ... ) {\n FAIL() << \"Expected std::runtime_error\";\n }\n}\n\n\/\/ Listener should be able to bind port 0 directly to get an ephemeral port.\nTEST(listener_test, listener_bind_ephemeral_port) {\n Pistache::Port port(0);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n\n Pistache::Port bound_port = listener.getPort();\n ASSERT_TRUE(bound_port > (uint16_t)0);\n}\n<commit_msg>Rebased onto upstream\/master and modified test<commit_after>#include \"gtest\/gtest.h\"\n\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <arpa\/inet.h>\n\n#include <pistache\/listener.h>\n#include <pistache\/http.h>\nclass SocketWrapper {\n\npublic:\n explicit SocketWrapper(int fd): fd_(fd) {}\n ~SocketWrapper() { close(fd_);}\n\n uint16_t port() {\n sockaddr_in sin;\n socklen_t len = sizeof(sin);\n\n uint16_t port = 0;\n if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) {\n perror(\"getsockname\");\n } else {\n port = ntohs(sin.sin_port);\n }\n return port;\n }\nprivate:\n int fd_;\n};\n\n\/\/ Just there for show.\nclass DummyHandler : public Pistache::Http::Handler {\npublic:\n\nHTTP_PROTOTYPE(DummyHandler)\n\n void onRequest(const Pistache::Http::Request& request, Pistache::Http::ResponseWriter response) override {\n UNUSED(request);\n response.send(Pistache::Http::Code::Ok, \"I am a dummy handler\\n\");\n }\n};\n\n\/*\n * Will try to get a free port by binding port 0.\n *\/\nSocketWrapper bind_free_port() {\n int sockfd; \/\/ listen on sock_fd, new connection on new_fd\n addrinfo hints, *servinfo, *p;\n\n int yes=1;\n int rv;\n\n memset(&hints, 0, sizeof hints);\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_PASSIVE; \/\/ use my IP\n\n if ((rv = getaddrinfo(nullptr, \"0\", &hints, &servinfo)) != 0) {\n std::cerr << \"getaddrinfo: \" << gai_strerror(rv) << \"\\n\";\n exit(1);\n }\n\n \/\/ loop through all the results and bind to the first we can\n for(p = servinfo; p != nullptr; p = p->ai_next) {\n if ((sockfd = socket(p->ai_family, p->ai_socktype,\n p->ai_protocol)) == -1) {\n perror(\"server: socket\");\n continue;\n }\n\n if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,\n sizeof(int)) == -1) {\n perror(\"setsockopt\");\n exit(1);\n }\n\n if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {\n close(sockfd);\n perror(\"server: bind\");\n continue;\n }\n\n break;\n }\n\n freeaddrinfo(servinfo); \/\/ all done with this structure\n\n if (p == nullptr) {\n fprintf(stderr, \"server: failed to bind\\n\");\n exit(1);\n }\n return SocketWrapper(sockfd);\n}\n\nTEST(listener_test, listener_bind_port_free) {\n uint16_t port_nb;\n\n \/\/ This is just done to get the value of a free port. The socket will be closed\n \/\/ after the closing curly bracket and the port will be free again (SO_REUSEADDR option).\n \/\/ In theory, it is possible that some application grab this port before we bind it again...\n {\n SocketWrapper s = bind_free_port();\n port_nb = s.port();\n }\n\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.init(1, options);\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n ASSERT_TRUE(true);\n}\n\n\n\/\/ Listener should not crash if an additional member is added to the listener class. This test\n\/\/ is there to prevent regression for PR 303\nTEST(listener_test, listener_uses_default) {\n uint16_t port_nb;\n\n \/\/ This is just done to get the value of a free port. The socket will be closed\n \/\/ after the closing curly bracket and the port will be free again (SO_REUSEADDR option).\n \/\/ In theory, it is possible that some application grab this port before we bind it again...\n {\n SocketWrapper s = bind_free_port();\n port_nb = s.port();\n }\n\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n ASSERT_TRUE(true);\n}\n\n\n\nTEST(listener_test, listener_bind_port_not_free_throw_runtime) {\n\n SocketWrapper s = bind_free_port();\n uint16_t port_nb = s.port();\n\n if (port_nb == 0) {\n FAIL() << \"Could not find a free port. Abort test.\\n\";\n }\n\n Pistache::Port port(port_nb);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.init(1, options);\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n\n try {\n listener.bind(address);\n FAIL() << \"Expected std::runtime_error while binding, got nothing\";\n } catch (std::runtime_error const & err) {\n std::cout << err.what() << std::endl;\n ASSERT_STREQ(\"Address already in use\", err.what());\n } catch ( ... ) {\n FAIL() << \"Expected std::runtime_error\";\n }\n}\n\n\n\/\/ Listener should be able to bind port 0 directly to get an ephemeral port.\nTEST(listener_test, listener_bind_ephemeral_port) {\n Pistache::Port port(0);\n Pistache::Address address(Pistache::Ipv4::any(), port);\n\n Pistache::Tcp::Listener listener;\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n\n Pistache::Port bound_port = listener.getPort();\n ASSERT_TRUE(bound_port > (uint16_t)0);\n}\n\n\nTEST(listener_test, listener_bind_ephemeral_v6_port) {\n Pistache::Port port(0);\n Pistache::Address address(Pistache::Ipv6::any(), port);\n\n Pistache::Tcp::Listener listener;\n if (not listener.systemSupportsIpv6()) {\n Pistache::Flags<Pistache::Tcp::Options> options;\n listener.setHandler(Pistache::Http::make_handler<DummyHandler>());\n listener.bind(address);\n \n Pistache::Port bound_port = listener.getPort();\n ASSERT_TRUE(bound_port > (uint16_t)0);\n }\n ASSERT_TRUE(true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ TODO: make cursor the fixed point of the zoom\n\/\/ TODO: compute area for selfintersecting polygons\n\/\/ TODO: polygon editing: move caption, change color, move segments (?), add points (?), delete points (?)\n\/\/ TODO: set scale by two points GPS coordinates\n\/\/ TODO: result printing\n\/\/ TODO: make it possible to reset selection; perhaps, it's time to use 3 modes instead of 2: normal draw, draw etalon, edit?\n\/\/ TODO: won't it be easier to use weak pointers (e.g., QPointers) to figures?\n\n#include <cassert>\n#include <cmath>\n\n#include <QInputDialog>\n#include <QLabel>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QScrollArea>\n#include <QScrollBar>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"paint_utils.h\"\n#include \"shape.h\"\n\n\nconst int rulerMargin = 16;\nconst int rulerThickness = 2;\nconst int rulerFrameThickness = 1;\nconst int rulerTextMargin = 3;\nconst int rulerSerifsSize = 8;\nconst int rulerMaxLength = 180;\nconst int rulerMinLength = 40;\nconst QColor rulerBodyColor = Qt::black;\nconst QColor rulerFrameColor = Qt::white;\n\nconst int maxImageSize = 4096;\n\n\nCanvasWidget::CanvasWidget(const QPixmap* image, MainWindow* mainWindow, QScrollArea* scrollArea,\n QLabel* scaleLabel, QLabel* statusLabel, QWidget* parent) :\n QWidget(parent),\n mainWindow_(mainWindow),\n scrollArea_(scrollArea),\n scaleLabel_(scaleLabel),\n statusLabel_(statusLabel),\n originalImage_(image)\n{\n acceptableScales_ << 0.01 << 0.015 << 0.02 << 0.025 << 0.03 << 0.04 << 0.05 << 0.06 << 0.07 << 0.08 << 0.09;\n acceptableScales_ << 0.10 << 0.12 << 0.14 << 0.17 << 0.20 << 0.23 << 0.26 << 0.30 << 0.35 << 0.40 << 0.45;\n acceptableScales_ << 0.50 << 0.60 << 0.70 << 0.80 << 0.90;\n acceptableScales_ << 1.00 << 1.25 << 1.50 << 1.75 << 2.00 << 2.50 << 3.00 << 4.00;\n iScale_ = acceptableScales_.indexOf(1.00);\n\n scrollArea_->viewport()->installEventFilter(this);\n setFocusPolicy(Qt::StrongFocus);\n setMouseTracking(true);\n shapeType_ = DEFAULT_TYPE;\n isDefiningEtalon_ = true;\n showRuler_ = false;\n etalonFigure_ = 0;\n activeFigure_ = 0;\n clearEtalon();\n scaleChanged();\n}\n\nCanvasWidget::~CanvasWidget()\n{\n delete originalImage_;\n}\n\n\nvoid CanvasWidget::paintEvent(QPaintEvent* event)\n{\n QPainter painter(this);\n painter.setFont(mainWindow_->getInscriptionFont());\n painter.setRenderHint(QPainter::Antialiasing, true);\n painter.drawPixmap(event->rect().topLeft(), image_, event->rect());\n foreach (const Figure& figure, figures_)\n figure.draw(painter);\n if (showRuler_)\n drawRuler(painter, event->rect());\n event->accept();\n}\n\nvoid CanvasWidget::keyPressEvent(QKeyEvent* event)\n{\n if (event->key() == Qt::Key_Delete) {\n if (!selection_.isEmpty() && !selection_.figure->isEtalon()) {\n removeFigure(selection_.figure);\n updateAll();\n }\n }\n else {\n QWidget::keyPressEvent(event);\n }\n}\n\nvoid CanvasWidget::mousePressEvent(QMouseEvent* event)\n{\n updateMousePos(event->pos());\n if (event->buttons() == Qt::LeftButton) {\n selection_ = hover_;\n if (hover_.isEmpty()) {\n if (!activeFigure_) {\n if (isDefiningEtalon_) {\n clearEtalon();\n removeFigure(etalonFigure_);\n }\n addActiveFigure();\n }\n bool polygonFinished = activeFigure_->addPoint(originalPointUnderMouse_);\n if (polygonFinished)\n finishPlotting();\n else\n updateAll();\n }\n else {\n update();\n }\n }\n else if (event->buttons() == Qt::RightButton) {\n scrollStartPoint_ = event->globalPos();\n scrollStartHValue_ = scrollArea_->horizontalScrollBar()->value();\n scrollStartVValue_ = scrollArea_->verticalScrollBar() ->value();\n }\n event->accept();\n}\n\nvoid CanvasWidget::mouseReleaseEvent(QMouseEvent* \/*event*\/)\n{\n updateHover();\n}\n\nvoid CanvasWidget::mouseMoveEvent(QMouseEvent* event)\n{\n if (event->buttons() == Qt::NoButton) {\n updateMousePos(event->pos());\n updateAll();\n }\n else if (event->buttons() == Qt::LeftButton) {\n updateMousePos(event->pos());\n selection_.dragTo(originalPointUnderMouse_);\n if (!selection_.isEmpty() && selection_.figure->isEtalon())\n defineEtalon(selection_.figure);\n updateAll();\n }\n else if (event->buttons() == Qt::RightButton) {\n QPoint scrollBy = scrollStartPoint_ - event->globalPos();\n scrollArea_->horizontalScrollBar()->setValue(scrollStartHValue_ + scrollBy.x());\n scrollArea_->verticalScrollBar() ->setValue(scrollStartVValue_ + scrollBy.y());\n }\n event->accept();\n}\n\nvoid CanvasWidget::mouseDoubleClickEvent(QMouseEvent* event)\n{\n finishPlotting();\n event->accept();\n}\n\nbool CanvasWidget::eventFilter(QObject* object, QEvent* event__)\n{\n if (object == scrollArea_->viewport() && event__->type() == QEvent::Wheel) {\n QWheelEvent* event = static_cast<QWheelEvent*>(event__);\n int numSteps = event->delta() \/ 120;\n iScale_ = qBound(0, iScale_ + numSteps, acceptableScales_.size() - 1);\n int size = qMax(originalImage_->width(), originalImage_->height());\n while (size * acceptableScales_[iScale_] > maxImageSize && acceptableScales_[iScale_] > 1.)\n iScale_--;\n scaleChanged();\n return true;\n }\n return false;\n}\n\n\n\nvoid CanvasWidget::setMode(ShapeType newMode)\n{\n shapeType_ = newMode;\n resetAll();\n}\n\nbool CanvasWidget::hasEtalon() const\n{\n return originalMetersPerPixel_ > 0.;\n}\n\nQPixmap CanvasWidget::getModifiedImage()\n{\n int oldIScale = iScale_;\n iScale_ = acceptableScales_.indexOf(1.00);\n scaleChanged();\n QPixmap resultingImage(size());\n render(&resultingImage);\n iScale_ = oldIScale;\n scaleChanged();\n return resultingImage;\n}\n\n\nvoid CanvasWidget::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n if (isDefiningEtalon_ == isDefiningEtalon)\n return;\n isDefiningEtalon_ = isDefiningEtalon;\n resetAll();\n}\n\nvoid CanvasWidget::toggleRuler(bool showRuler)\n{\n if (showRuler_ == showRuler)\n return;\n showRuler_ = showRuler;\n update();\n}\n\n\nvoid CanvasWidget::addActiveFigure()\n{\n assert(!activeFigure_);\n figures_.append(Figure(shapeType_, isDefiningEtalon_, this));\n activeFigure_ = &figures_.last();\n}\n\nvoid CanvasWidget::removeFigure(const Figure* figure)\n{\n if (!figure)\n return;\n\n if (etalonFigure_ == figure)\n etalonFigure_ = 0;\n if (activeFigure_ == figure)\n activeFigure_ = 0;\n if (selection_.figure == figure)\n selection_.reset();\n if (hover_.figure == figure)\n hover_.reset();\n\n bool erased = false;\n for (auto it = figures_.begin(); it != figures_.end(); ++it) {\n if (&(*it) == figure) {\n figures_.erase(it);\n erased = true;\n break;\n }\n }\n assert(erased);\n}\n\n\nvoid CanvasWidget::drawRuler(QPainter& painter, const QRect& rect)\n{\n int maxLength = qMin(rulerMaxLength, rect.width() - 2 * rulerMargin);\n if (!hasEtalon() || maxLength < rulerMinLength)\n return;\n\n double pixelLengthF;\n double metersLength;\n double base = 1e10;\n while (base > 1e-10) {\n if ((pixelLengthF = (metersLength = base * 5.) \/ metersPerPixel_) < maxLength)\n break;\n if ((pixelLengthF = (metersLength = base * 2.) \/ metersPerPixel_) < maxLength)\n break;\n if ((pixelLengthF = (metersLength = base * 1.) \/ metersPerPixel_) < maxLength)\n break;\n base \/= 10.;\n }\n int pixelLength = pixelLengthF;\n\n QList<QRect> ruler;\n int rulerLeft = rect.left() + rulerMargin;\n int rulerY = rect.bottom() - rulerMargin;\n ruler.append(QRect(rulerLeft, rulerY - rulerThickness \/ 2, pixelLength, rulerThickness));\n ruler.append(QRect(rulerLeft - rulerThickness, rulerY - rulerSerifsSize \/ 2, rulerThickness, rulerSerifsSize));\n ruler.append(QRect(rulerLeft + pixelLength , rulerY - rulerSerifsSize \/ 2, rulerThickness, rulerSerifsSize));\n drawFramed(painter, ruler, rulerFrameThickness, rulerBodyColor, rulerFrameColor);\n\n QString rulerLabel = QString::number(metersLength) + \" \" + linearUnitSuffix;\n QPoint labelPos(rulerLeft + rulerFrameThickness + rulerTextMargin,\n rulerY - rulerThickness \/ 2 - rulerFrameThickness - rulerTextMargin - painter.fontMetrics().descent());\n drawTextWithBackground(painter, rulerLabel, labelPos);\n}\n\n\nvoid CanvasWidget::updateMousePos(QPoint mousePos)\n{\n pointUnderMouse_ = mousePos;\n originalPointUnderMouse_ = pointUnderMouse_ \/ scale_;\n}\n\nvoid CanvasWidget::updateHover()\n{\n Selection newHover;\n if (activeFigure_) {\n newHover.reset();\n }\n else {\n SelectionFinder selectionFinder(pointUnderMouse_);\n for (auto it = figures_.begin(); it != figures_.end(); ++it)\n if (it->isFinished())\n it->testSelection(selectionFinder);\n newHover = selectionFinder.bestSelection();\n }\n if (hover_ != newHover) {\n hover_ = newHover;\n update();\n }\n}\n\nvoid CanvasWidget::defineEtalon(Figure* newEtalonFigure)\n{\n assert(newEtalonFigure && newEtalonFigure->isFinished());\n bool isResizing = (etalonFigure_ == newEtalonFigure);\n etalonFigure_ = newEtalonFigure;\n const Shape originalShapeDrawn = newEtalonFigure->originalShape();\n double originalEtalonPixelLength = 0.;\n QString prompt;\n switch (originalShapeDrawn.dimensionality()) {\n case SHAPE_1D:\n originalEtalonPixelLength = originalShapeDrawn.length();\n prompt = QString::fromUtf8(\"Укажите длину эталона (%1): \").arg(linearUnitSuffix);\n break;\n case SHAPE_2D:\n originalEtalonPixelLength = std::sqrt(originalShapeDrawn.area());\n prompt = QString::fromUtf8(\"Укажите площадь эталона (%1): \").arg(squareUnitSuffix);\n break;\n }\n bool userInputIsOk = true;\n if (!isResizing)\n etalonMetersSize_ = QInputDialog::getDouble(this, mainWindow_->appName(), prompt, 1., 0.001, 1e9, 3, &userInputIsOk);\n if (originalShapeDrawn.isValid() && originalEtalonPixelLength > 0. && userInputIsOk) {\n double etalonMetersLength;\n switch (originalShapeDrawn.dimensionality()) {\n case SHAPE_1D: etalonMetersLength = etalonMetersSize_; break;\n case SHAPE_2D: etalonMetersLength = std::sqrt(etalonMetersSize_); break;\n }\n originalMetersPerPixel_ = etalonMetersLength \/ originalEtalonPixelLength;\n metersPerPixel_ = originalMetersPerPixel_ \/ scale_;\n }\n else {\n clearEtalon(true);\n }\n if (!isResizing)\n mainWindow_->toggleEtalonDefinition(false);\n}\n\nvoid CanvasWidget::clearEtalon(bool invalidateOnly)\n{\n if (!invalidateOnly)\n etalonMetersSize_ = 0;\n originalMetersPerPixel_ = 0.;\n metersPerPixel_ = 0.;\n}\n\nvoid CanvasWidget::finishPlotting()\n{\n assert(activeFigure_);\n activeFigure_->finish();\n Figure *oldActiveFigure = activeFigure_;\n activeFigure_ = 0;\n if (isDefiningEtalon_)\n defineEtalon(oldActiveFigure);\n updateAll();\n}\n\nvoid CanvasWidget::resetAll()\n{\n removeFigure(activeFigure_);\n updateAll();\n}\n\nvoid CanvasWidget::scaleChanged()\n{\n scale_ = acceptableScales_[iScale_];\n image_ = originalImage_->scaled(originalImage_->size() * scale_, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n metersPerPixel_ = originalMetersPerPixel_ \/ scale_;\n setFixedSize(image_.size());\n scaleLabel_->setText(QString::number(scale_ * 100.) + \"%\");\n updateAll();\n}\n\nvoid CanvasWidget::updateAll()\n{\n updateHover();\n statusLabel_->setText(activeFigure_ ? activeFigure_->statusString() : QString());\n update();\n}\n<commit_msg>Fix finishing drawing on double-clicking non-left button<commit_after>\/\/ TODO: make cursor the fixed point of the zoom\n\/\/ TODO: compute area for selfintersecting polygons\n\/\/ TODO: polygon editing: move caption, change color, move segments (?), add points (?), delete points (?)\n\/\/ TODO: set scale by two points GPS coordinates\n\/\/ TODO: result printing\n\/\/ TODO: make it possible to reset selection; perhaps, it's time to use 3 modes instead of 2: normal draw, draw etalon, edit?\n\/\/ TODO: won't it be easier to use weak pointers (e.g., QPointers) to figures?\n\n#include <cassert>\n#include <cmath>\n\n#include <QInputDialog>\n#include <QLabel>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QScrollArea>\n#include <QScrollBar>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"paint_utils.h\"\n#include \"shape.h\"\n\n\nconst int rulerMargin = 16;\nconst int rulerThickness = 2;\nconst int rulerFrameThickness = 1;\nconst int rulerTextMargin = 3;\nconst int rulerSerifsSize = 8;\nconst int rulerMaxLength = 180;\nconst int rulerMinLength = 40;\nconst QColor rulerBodyColor = Qt::black;\nconst QColor rulerFrameColor = Qt::white;\n\nconst int maxImageSize = 4096;\n\n\nCanvasWidget::CanvasWidget(const QPixmap* image, MainWindow* mainWindow, QScrollArea* scrollArea,\n QLabel* scaleLabel, QLabel* statusLabel, QWidget* parent) :\n QWidget(parent),\n mainWindow_(mainWindow),\n scrollArea_(scrollArea),\n scaleLabel_(scaleLabel),\n statusLabel_(statusLabel),\n originalImage_(image)\n{\n acceptableScales_ << 0.01 << 0.015 << 0.02 << 0.025 << 0.03 << 0.04 << 0.05 << 0.06 << 0.07 << 0.08 << 0.09;\n acceptableScales_ << 0.10 << 0.12 << 0.14 << 0.17 << 0.20 << 0.23 << 0.26 << 0.30 << 0.35 << 0.40 << 0.45;\n acceptableScales_ << 0.50 << 0.60 << 0.70 << 0.80 << 0.90;\n acceptableScales_ << 1.00 << 1.25 << 1.50 << 1.75 << 2.00 << 2.50 << 3.00 << 4.00;\n iScale_ = acceptableScales_.indexOf(1.00);\n\n scrollArea_->viewport()->installEventFilter(this);\n setFocusPolicy(Qt::StrongFocus);\n setMouseTracking(true);\n shapeType_ = DEFAULT_TYPE;\n isDefiningEtalon_ = true;\n showRuler_ = false;\n etalonFigure_ = 0;\n activeFigure_ = 0;\n clearEtalon();\n scaleChanged();\n}\n\nCanvasWidget::~CanvasWidget()\n{\n delete originalImage_;\n}\n\n\nvoid CanvasWidget::paintEvent(QPaintEvent* event)\n{\n QPainter painter(this);\n painter.setFont(mainWindow_->getInscriptionFont());\n painter.setRenderHint(QPainter::Antialiasing, true);\n painter.drawPixmap(event->rect().topLeft(), image_, event->rect());\n foreach (const Figure& figure, figures_)\n figure.draw(painter);\n if (showRuler_)\n drawRuler(painter, event->rect());\n event->accept();\n}\n\nvoid CanvasWidget::keyPressEvent(QKeyEvent* event)\n{\n if (event->key() == Qt::Key_Delete) {\n if (!selection_.isEmpty() && !selection_.figure->isEtalon()) {\n removeFigure(selection_.figure);\n updateAll();\n }\n }\n else {\n QWidget::keyPressEvent(event);\n }\n}\n\nvoid CanvasWidget::mousePressEvent(QMouseEvent* event)\n{\n updateMousePos(event->pos());\n if (event->buttons() == Qt::LeftButton) {\n selection_ = hover_;\n if (hover_.isEmpty()) {\n if (!activeFigure_) {\n if (isDefiningEtalon_) {\n clearEtalon();\n removeFigure(etalonFigure_);\n }\n addActiveFigure();\n }\n bool polygonFinished = activeFigure_->addPoint(originalPointUnderMouse_);\n if (polygonFinished)\n finishPlotting();\n else\n updateAll();\n }\n else {\n update();\n }\n }\n else if (event->buttons() == Qt::RightButton) {\n scrollStartPoint_ = event->globalPos();\n scrollStartHValue_ = scrollArea_->horizontalScrollBar()->value();\n scrollStartVValue_ = scrollArea_->verticalScrollBar() ->value();\n }\n event->accept();\n}\n\nvoid CanvasWidget::mouseReleaseEvent(QMouseEvent* \/*event*\/)\n{\n updateHover();\n}\n\nvoid CanvasWidget::mouseMoveEvent(QMouseEvent* event)\n{\n if (event->buttons() == Qt::NoButton) {\n updateMousePos(event->pos());\n updateAll();\n }\n else if (event->buttons() == Qt::LeftButton) {\n updateMousePos(event->pos());\n selection_.dragTo(originalPointUnderMouse_);\n if (!selection_.isEmpty() && selection_.figure->isEtalon())\n defineEtalon(selection_.figure);\n updateAll();\n }\n else if (event->buttons() == Qt::RightButton) {\n QPoint scrollBy = scrollStartPoint_ - event->globalPos();\n scrollArea_->horizontalScrollBar()->setValue(scrollStartHValue_ + scrollBy.x());\n scrollArea_->verticalScrollBar() ->setValue(scrollStartVValue_ + scrollBy.y());\n }\n event->accept();\n}\n\n\/\/ TODO: deal with case when double-click is the first click\nvoid CanvasWidget::mouseDoubleClickEvent(QMouseEvent* event)\n{\n if (event->buttons() == Qt::LeftButton)\n finishPlotting();\n event->accept();\n}\n\nbool CanvasWidget::eventFilter(QObject* object, QEvent* event__)\n{\n if (object == scrollArea_->viewport() && event__->type() == QEvent::Wheel) {\n QWheelEvent* event = static_cast<QWheelEvent*>(event__);\n int numSteps = event->delta() \/ 120;\n iScale_ = qBound(0, iScale_ + numSteps, acceptableScales_.size() - 1);\n int size = qMax(originalImage_->width(), originalImage_->height());\n while (size * acceptableScales_[iScale_] > maxImageSize && acceptableScales_[iScale_] > 1.)\n iScale_--;\n scaleChanged();\n return true;\n }\n return false;\n}\n\n\n\nvoid CanvasWidget::setMode(ShapeType newMode)\n{\n shapeType_ = newMode;\n resetAll();\n}\n\nbool CanvasWidget::hasEtalon() const\n{\n return originalMetersPerPixel_ > 0.;\n}\n\nQPixmap CanvasWidget::getModifiedImage()\n{\n int oldIScale = iScale_;\n iScale_ = acceptableScales_.indexOf(1.00);\n scaleChanged();\n QPixmap resultingImage(size());\n render(&resultingImage);\n iScale_ = oldIScale;\n scaleChanged();\n return resultingImage;\n}\n\n\nvoid CanvasWidget::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n if (isDefiningEtalon_ == isDefiningEtalon)\n return;\n isDefiningEtalon_ = isDefiningEtalon;\n resetAll();\n}\n\nvoid CanvasWidget::toggleRuler(bool showRuler)\n{\n if (showRuler_ == showRuler)\n return;\n showRuler_ = showRuler;\n update();\n}\n\n\nvoid CanvasWidget::addActiveFigure()\n{\n assert(!activeFigure_);\n figures_.append(Figure(shapeType_, isDefiningEtalon_, this));\n activeFigure_ = &figures_.last();\n}\n\nvoid CanvasWidget::removeFigure(const Figure* figure)\n{\n if (!figure)\n return;\n\n if (etalonFigure_ == figure)\n etalonFigure_ = 0;\n if (activeFigure_ == figure)\n activeFigure_ = 0;\n if (selection_.figure == figure)\n selection_.reset();\n if (hover_.figure == figure)\n hover_.reset();\n\n bool erased = false;\n for (auto it = figures_.begin(); it != figures_.end(); ++it) {\n if (&(*it) == figure) {\n figures_.erase(it);\n erased = true;\n break;\n }\n }\n assert(erased);\n}\n\n\nvoid CanvasWidget::drawRuler(QPainter& painter, const QRect& rect)\n{\n int maxLength = qMin(rulerMaxLength, rect.width() - 2 * rulerMargin);\n if (!hasEtalon() || maxLength < rulerMinLength)\n return;\n\n double pixelLengthF;\n double metersLength;\n double base = 1e10;\n while (base > 1e-10) {\n if ((pixelLengthF = (metersLength = base * 5.) \/ metersPerPixel_) < maxLength)\n break;\n if ((pixelLengthF = (metersLength = base * 2.) \/ metersPerPixel_) < maxLength)\n break;\n if ((pixelLengthF = (metersLength = base * 1.) \/ metersPerPixel_) < maxLength)\n break;\n base \/= 10.;\n }\n int pixelLength = pixelLengthF;\n\n QList<QRect> ruler;\n int rulerLeft = rect.left() + rulerMargin;\n int rulerY = rect.bottom() - rulerMargin;\n ruler.append(QRect(rulerLeft, rulerY - rulerThickness \/ 2, pixelLength, rulerThickness));\n ruler.append(QRect(rulerLeft - rulerThickness, rulerY - rulerSerifsSize \/ 2, rulerThickness, rulerSerifsSize));\n ruler.append(QRect(rulerLeft + pixelLength , rulerY - rulerSerifsSize \/ 2, rulerThickness, rulerSerifsSize));\n drawFramed(painter, ruler, rulerFrameThickness, rulerBodyColor, rulerFrameColor);\n\n QString rulerLabel = QString::number(metersLength) + \" \" + linearUnitSuffix;\n QPoint labelPos(rulerLeft + rulerFrameThickness + rulerTextMargin,\n rulerY - rulerThickness \/ 2 - rulerFrameThickness - rulerTextMargin - painter.fontMetrics().descent());\n drawTextWithBackground(painter, rulerLabel, labelPos);\n}\n\n\nvoid CanvasWidget::updateMousePos(QPoint mousePos)\n{\n pointUnderMouse_ = mousePos;\n originalPointUnderMouse_ = pointUnderMouse_ \/ scale_;\n}\n\nvoid CanvasWidget::updateHover()\n{\n Selection newHover;\n if (activeFigure_) {\n newHover.reset();\n }\n else {\n SelectionFinder selectionFinder(pointUnderMouse_);\n for (auto it = figures_.begin(); it != figures_.end(); ++it)\n if (it->isFinished())\n it->testSelection(selectionFinder);\n newHover = selectionFinder.bestSelection();\n }\n if (hover_ != newHover) {\n hover_ = newHover;\n update();\n }\n}\n\nvoid CanvasWidget::defineEtalon(Figure* newEtalonFigure)\n{\n assert(newEtalonFigure && newEtalonFigure->isFinished());\n bool isResizing = (etalonFigure_ == newEtalonFigure);\n etalonFigure_ = newEtalonFigure;\n const Shape originalShapeDrawn = newEtalonFigure->originalShape();\n double originalEtalonPixelLength = 0.;\n QString prompt;\n switch (originalShapeDrawn.dimensionality()) {\n case SHAPE_1D:\n originalEtalonPixelLength = originalShapeDrawn.length();\n prompt = QString::fromUtf8(\"Укажите длину эталона (%1): \").arg(linearUnitSuffix);\n break;\n case SHAPE_2D:\n originalEtalonPixelLength = std::sqrt(originalShapeDrawn.area());\n prompt = QString::fromUtf8(\"Укажите площадь эталона (%1): \").arg(squareUnitSuffix);\n break;\n }\n bool userInputIsOk = true;\n if (!isResizing)\n etalonMetersSize_ = QInputDialog::getDouble(this, mainWindow_->appName(), prompt, 1., 0.001, 1e9, 3, &userInputIsOk);\n if (originalShapeDrawn.isValid() && originalEtalonPixelLength > 0. && userInputIsOk) {\n double etalonMetersLength;\n switch (originalShapeDrawn.dimensionality()) {\n case SHAPE_1D: etalonMetersLength = etalonMetersSize_; break;\n case SHAPE_2D: etalonMetersLength = std::sqrt(etalonMetersSize_); break;\n }\n originalMetersPerPixel_ = etalonMetersLength \/ originalEtalonPixelLength;\n metersPerPixel_ = originalMetersPerPixel_ \/ scale_;\n }\n else {\n clearEtalon(true);\n }\n if (!isResizing)\n mainWindow_->toggleEtalonDefinition(false);\n}\n\nvoid CanvasWidget::clearEtalon(bool invalidateOnly)\n{\n if (!invalidateOnly)\n etalonMetersSize_ = 0;\n originalMetersPerPixel_ = 0.;\n metersPerPixel_ = 0.;\n}\n\nvoid CanvasWidget::finishPlotting()\n{\n assert(activeFigure_);\n activeFigure_->finish();\n Figure *oldActiveFigure = activeFigure_;\n activeFigure_ = 0;\n if (isDefiningEtalon_)\n defineEtalon(oldActiveFigure);\n updateAll();\n}\n\nvoid CanvasWidget::resetAll()\n{\n removeFigure(activeFigure_);\n updateAll();\n}\n\nvoid CanvasWidget::scaleChanged()\n{\n scale_ = acceptableScales_[iScale_];\n image_ = originalImage_->scaled(originalImage_->size() * scale_, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n metersPerPixel_ = originalMetersPerPixel_ \/ scale_;\n setFixedSize(image_.size());\n scaleLabel_->setText(QString::number(scale_ * 100.) + \"%\");\n updateAll();\n}\n\nvoid CanvasWidget::updateAll()\n{\n updateHover();\n statusLabel_->setText(activeFigure_ ? activeFigure_->statusString() : QString());\n update();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n#include <google\/protobuf\/compiler\/java\/java_doc_comment.h>\n\n#include <vector>\n\n#include <google\/protobuf\/io\/printer.h>\n#include <google\/protobuf\/stubs\/strutil.h>\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace java {\n\nstd::string EscapeJavadoc(const std::string& input) {\n std::string result;\n result.reserve(input.size() * 2);\n\n char prev = '*';\n\n for (std::string::size_type i = 0; i < input.size(); i++) {\n char c = input[i];\n switch (c) {\n case '*':\n \/\/ Avoid \"\/*\".\n if (prev == '\/') {\n result.append(\"*\");\n } else {\n result.push_back(c);\n }\n break;\n case '\/':\n \/\/ Avoid \"*\/\".\n if (prev == '*') {\n result.append(\"/\");\n } else {\n result.push_back(c);\n }\n break;\n case '@':\n \/\/ '@' starts javadoc tags including the @deprecated tag, which will\n \/\/ cause a compile-time error if inserted before a declaration that\n \/\/ does not have a corresponding @Deprecated annotation.\n result.append(\"@\");\n break;\n case '<':\n \/\/ Avoid interpretation as HTML.\n result.append(\"<\");\n break;\n case '>':\n \/\/ Avoid interpretation as HTML.\n result.append(\">\");\n break;\n case '&':\n \/\/ Avoid interpretation as HTML.\n result.append(\"&\");\n break;\n case '\\\\':\n \/\/ Java interprets Unicode escape sequences anywhere!\n result.append(\"\\");\n break;\n default:\n result.push_back(c);\n break;\n }\n\n prev = c;\n }\n\n return result;\n}\n\nstatic void WriteDocCommentBodyForLocation(io::Printer* printer,\n const SourceLocation& location) {\n std::string comments = location.leading_comments.empty()\n ? location.trailing_comments\n : location.leading_comments;\n if (!comments.empty()) {\n \/\/ TODO(kenton): Ideally we should parse the comment text as Markdown and\n \/\/ write it back as HTML, but this requires a Markdown parser. For now\n \/\/ we just use <pre> to get fixed-width text formatting.\n\n \/\/ If the comment itself contains block comment start or end markers,\n \/\/ HTML-escape them so that they don't accidentally close the doc comment.\n comments = EscapeJavadoc(comments);\n\n std::vector<std::string> lines = Split(comments, \"\\n\");\n while (!lines.empty() && lines.back().empty()) {\n lines.pop_back();\n }\n\n printer->Print(\" * <pre>\\n\");\n for (int i = 0; i < lines.size(); i++) {\n \/\/ Most lines should start with a space. Watch out for lines that start\n \/\/ with a \/, since putting that right after the leading asterisk will\n \/\/ close the comment.\n if (!lines[i].empty() && lines[i][0] == '\/') {\n printer->Print(\" * $line$\\n\", \"line\", lines[i]);\n } else {\n printer->Print(\" *$line$\\n\", \"line\", lines[i]);\n }\n }\n printer->Print(\n \" * <\/pre>\\n\"\n \" *\\n\");\n }\n}\n\ntemplate <typename DescriptorType>\nstatic void WriteDocCommentBody(io::Printer* printer,\n const DescriptorType* descriptor) {\n SourceLocation location;\n if (descriptor->GetSourceLocation(&location)) {\n WriteDocCommentBodyForLocation(printer, location);\n }\n}\n\nstatic std::string FirstLineOf(const std::string& value) {\n std::string result = value;\n\n std::string::size_type pos = result.find_first_of('\\n');\n if (pos != std::string::npos) {\n result.erase(pos);\n }\n\n \/\/ If line ends in an opening brace, make it \"{ ... }\" so it looks nice.\n if (!result.empty() && result[result.size() - 1] == '{') {\n result.append(\" ... }\");\n }\n\n return result;\n}\n\nvoid WriteMessageDocComment(io::Printer* printer, const Descriptor* message) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, message);\n printer->Print(\n \" * Protobuf type {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(message->full_name()));\n}\n\nvoid WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) {\n \/\/ We start the comment with the main body based on the comments from the\n \/\/ .proto file (if present). We then continue with the field declaration, e.g.:\n \/\/ optional string foo = 5;\n \/\/ And then we end with the javadoc tags if applicable.\n \/\/ If the field is a group, the debug string might end with {.\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\",\n EscapeJavadoc(FirstLineOf(field->DebugString())));\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n printer->Print(\" * @return Whether the $name$ field is set.\\n\", \"name\", \n field->camelcase_name());\n break;\n case GETTER:\n printer->Print(\" * @return The $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The $name$ to set.\\n\", \"name\",\n field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n printer->Print(\" * @return The number of $name$(s).\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the $name$(s).\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the element to return.\\n\");\n printer->Print(\" * @return The $name$(s) at the given index.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The $name$ to set.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The $name$ to add.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The $name$(s) to add.\\n\", \"name\",\n field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldEnumValueAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n \/\/ Should never happen\n break;\n case GETTER:\n printer->Print(\" * @return The enum value for $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The enum value for $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n \/\/ Should never happen\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the enum values for $name$(s).\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the value to return.\\n\");\n printer->Print(\" * @return The enum value of the $name$ at the given index.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The enum value of the $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The enum value of the $name$ to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The enum values of the $name$(s) to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldStringBytesAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n \/\/ Should never happen\n break;\n case GETTER:\n printer->Print(\" * @return The bytes for $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The bytes for $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n \/\/ Should never happen\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the bytes for $name$(s).\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the value to return.\\n\");\n printer->Print(\" * @return The bytes of the $name$ at the given index.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The bytes of the $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The bytes of the $name$ to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The bytes of the $name$(s) to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\n\/\/ Enum\n\nvoid WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, enum_);\n printer->Print(\n \" * Protobuf enum {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(enum_->full_name()));\n}\n\nvoid WriteEnumValueDocComment(io::Printer* printer,\n const EnumValueDescriptor* value) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, value);\n printer->Print(\n \" * <code>$def$<\/code>\\n\"\n \" *\/\\n\",\n \"def\", EscapeJavadoc(FirstLineOf(value->DebugString())));\n}\n\nvoid WriteServiceDocComment(io::Printer* printer,\n const ServiceDescriptor* service) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, service);\n printer->Print(\n \" * Protobuf service {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(service->full_name()));\n}\n\nvoid WriteMethodDocComment(io::Printer* printer,\n const MethodDescriptor* method) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, method);\n printer->Print(\n \" * <code>$def$<\/code>\\n\"\n \" *\/\\n\",\n \"def\", EscapeJavadoc(FirstLineOf(method->DebugString())));\n}\n\n} \/\/ namespace java\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<commit_msg>Follow line length guidelines<commit_after>\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Author: kenton@google.com (Kenton Varda)\n\/\/ Based on original Protocol Buffers design by\n\/\/ Sanjay Ghemawat, Jeff Dean, and others.\n\n#include <google\/protobuf\/compiler\/java\/java_doc_comment.h>\n\n#include <vector>\n\n#include <google\/protobuf\/io\/printer.h>\n#include <google\/protobuf\/stubs\/strutil.h>\n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace java {\n\nstd::string EscapeJavadoc(const std::string& input) {\n std::string result;\n result.reserve(input.size() * 2);\n\n char prev = '*';\n\n for (std::string::size_type i = 0; i < input.size(); i++) {\n char c = input[i];\n switch (c) {\n case '*':\n \/\/ Avoid \"\/*\".\n if (prev == '\/') {\n result.append(\"*\");\n } else {\n result.push_back(c);\n }\n break;\n case '\/':\n \/\/ Avoid \"*\/\".\n if (prev == '*') {\n result.append(\"/\");\n } else {\n result.push_back(c);\n }\n break;\n case '@':\n \/\/ '@' starts javadoc tags including the @deprecated tag, which will\n \/\/ cause a compile-time error if inserted before a declaration that\n \/\/ does not have a corresponding @Deprecated annotation.\n result.append(\"@\");\n break;\n case '<':\n \/\/ Avoid interpretation as HTML.\n result.append(\"<\");\n break;\n case '>':\n \/\/ Avoid interpretation as HTML.\n result.append(\">\");\n break;\n case '&':\n \/\/ Avoid interpretation as HTML.\n result.append(\"&\");\n break;\n case '\\\\':\n \/\/ Java interprets Unicode escape sequences anywhere!\n result.append(\"\\");\n break;\n default:\n result.push_back(c);\n break;\n }\n\n prev = c;\n }\n\n return result;\n}\n\nstatic void WriteDocCommentBodyForLocation(io::Printer* printer,\n const SourceLocation& location) {\n std::string comments = location.leading_comments.empty()\n ? location.trailing_comments\n : location.leading_comments;\n if (!comments.empty()) {\n \/\/ TODO(kenton): Ideally we should parse the comment text as Markdown and\n \/\/ write it back as HTML, but this requires a Markdown parser. For now\n \/\/ we just use <pre> to get fixed-width text formatting.\n\n \/\/ If the comment itself contains block comment start or end markers,\n \/\/ HTML-escape them so that they don't accidentally close the doc comment.\n comments = EscapeJavadoc(comments);\n\n std::vector<std::string> lines = Split(comments, \"\\n\");\n while (!lines.empty() && lines.back().empty()) {\n lines.pop_back();\n }\n\n printer->Print(\" * <pre>\\n\");\n for (int i = 0; i < lines.size(); i++) {\n \/\/ Most lines should start with a space. Watch out for lines that start\n \/\/ with a \/, since putting that right after the leading asterisk will\n \/\/ close the comment.\n if (!lines[i].empty() && lines[i][0] == '\/') {\n printer->Print(\" * $line$\\n\", \"line\", lines[i]);\n } else {\n printer->Print(\" *$line$\\n\", \"line\", lines[i]);\n }\n }\n printer->Print(\n \" * <\/pre>\\n\"\n \" *\\n\");\n }\n}\n\ntemplate <typename DescriptorType>\nstatic void WriteDocCommentBody(io::Printer* printer,\n const DescriptorType* descriptor) {\n SourceLocation location;\n if (descriptor->GetSourceLocation(&location)) {\n WriteDocCommentBodyForLocation(printer, location);\n }\n}\n\nstatic std::string FirstLineOf(const std::string& value) {\n std::string result = value;\n\n std::string::size_type pos = result.find_first_of('\\n');\n if (pos != std::string::npos) {\n result.erase(pos);\n }\n\n \/\/ If line ends in an opening brace, make it \"{ ... }\" so it looks nice.\n if (!result.empty() && result[result.size() - 1] == '{') {\n result.append(\" ... }\");\n }\n\n return result;\n}\n\nvoid WriteMessageDocComment(io::Printer* printer, const Descriptor* message) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, message);\n printer->Print(\n \" * Protobuf type {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(message->full_name()));\n}\n\nvoid WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) {\n \/\/ We start the comment with the main body based on the comments from the\n \/\/ .proto file (if present). We then continue with the field declaration, e.g.:\n \/\/ optional string foo = 5;\n \/\/ And then we end with the javadoc tags if applicable.\n \/\/ If the field is a group, the debug string might end with {.\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\",\n EscapeJavadoc(FirstLineOf(field->DebugString())));\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n printer->Print(\" * @return Whether the $name$ field is set.\\n\", \"name\", \n field->camelcase_name());\n break;\n case GETTER:\n printer->Print(\" * @return The $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The $name$ to set.\\n\", \"name\",\n field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n printer->Print(\" * @return The number of $name$(s).\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the $name$(s).\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the element to return.\\n\");\n printer->Print(\" * @return The $name$(s) at the given index.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The $name$ to set.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The $name$ to add.\\n\", \"name\",\n field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The $name$(s) to add.\\n\", \"name\",\n field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldEnumValueAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n \/\/ Should never happen\n break;\n case GETTER:\n printer->Print(\" * @return The enum value for $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The enum value for $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n \/\/ Should never happen\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the enum values for \"\n \"$name$(s).\\n\", \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the value to return.\\n\");\n printer->Print(\" * @return The enum value of the $name$ at the given \"\n \"index.\\n\", \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The enum value of the $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The enum value of the $name$ to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The enum values of the $name$(s) to \"\n \"add.\\n\", \"name\", field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\nvoid WriteFieldStringBytesAccessorDocComment(io::Printer* printer, \n const FieldDescriptor* field,\n const FieldAccessorType type,\n const bool builder) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, field);\n printer->Print(\" * <code>$def$<\/code>\\n\", \"def\", \n EscapeJavadoc(FirstLineOf(field->DebugString())));\n switch (type) {\n case HAZZER:\n \/\/ Should never happen\n break;\n case GETTER:\n printer->Print(\" * @return The bytes for $name$.\\n\", \"name\",\n field->camelcase_name());\n break;\n case SETTER:\n printer->Print(\" * @param value The bytes for $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case CLEARER:\n \/\/ Print nothing\n break;\n \/\/ Repeated\n case LIST_COUNT:\n \/\/ Should never happen\n break;\n case LIST_GETTER:\n printer->Print(\" * @return A list containing the bytes for $name$(s).\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_GETTER:\n printer->Print(\" * @param index The index of the value to return.\\n\");\n printer->Print(\" * @return The bytes of the $name$ at the given index.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_INDEXED_SETTER:\n printer->Print(\" * @param index The index to set the value at.\\n\");\n printer->Print(\" * @param value The bytes of the $name$ to set.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_ADDER:\n printer->Print(\" * @param value The bytes of the $name$ to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n case LIST_MULTI_ADDER:\n printer->Print(\" * @param values The bytes of the $name$(s) to add.\\n\",\n \"name\", field->camelcase_name());\n break;\n }\n if (builder) {\n printer->Print(\" * @return This builder for chaining.\\n\");\n }\n printer->Print(\" *\/\\n\");\n}\n\n\/\/ Enum\n\nvoid WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, enum_);\n printer->Print(\n \" * Protobuf enum {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(enum_->full_name()));\n}\n\nvoid WriteEnumValueDocComment(io::Printer* printer,\n const EnumValueDescriptor* value) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, value);\n printer->Print(\n \" * <code>$def$<\/code>\\n\"\n \" *\/\\n\",\n \"def\", EscapeJavadoc(FirstLineOf(value->DebugString())));\n}\n\nvoid WriteServiceDocComment(io::Printer* printer,\n const ServiceDescriptor* service) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, service);\n printer->Print(\n \" * Protobuf service {@code $fullname$}\\n\"\n \" *\/\\n\",\n \"fullname\", EscapeJavadoc(service->full_name()));\n}\n\nvoid WriteMethodDocComment(io::Printer* printer,\n const MethodDescriptor* method) {\n printer->Print(\"\/**\\n\");\n WriteDocCommentBody(printer, method);\n printer->Print(\n \" * <code>$def$<\/code>\\n\"\n \" *\/\\n\",\n \"def\", EscapeJavadoc(FirstLineOf(method->DebugString())));\n}\n\n} \/\/ namespace java\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>\/* \n* Copyright 2016 Matthias Fuchs\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n\n#include <zbar.h>\n\n#include <stromx\/runtime\/ConstDataRef.h>\n#include <stromx\/runtime\/DataContainer.h>\n#include <stromx\/runtime\/List.h>\n#include <stromx\/runtime\/OperatorTester.h>\n#include <stromx\/runtime\/ReadAccess.h>\n#include <stromx\/runtime\/String.h>\n#include <stromx\/cvsupport\/Image.h>\n\n#include \"stromx\/zbar\/Scan.h\"\n\nnamespace stromx\n{\nnamespace zbar\n{\n\nclass ScanTest : public CPPUNIT_NS :: TestFixture\n{\n CPPUNIT_TEST_SUITE (ScanTest);\n CPPUNIT_TEST (testExecute);\n CPPUNIT_TEST (testExecuteWrongSymbolType);\n CPPUNIT_TEST (testSetSymbolType);\n CPPUNIT_TEST_SUITE_END ();\n\n public:\n ScanTest() : m_operator(0) {}\n \n void setUp();\n void tearDown();\n\n protected:\n void testExecute();\n void testExecuteWrongSymbolType();\n void testSetSymbolType();\n \n private:\n runtime::OperatorTester* m_operator;\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION (ScanTest);\n\nvoid ScanTest::setUp ( void )\n{\n m_operator = new runtime::OperatorTester(new Scan());\n m_operator->initialize();\n m_operator->activate();\n}\n\nvoid ScanTest::testExecute()\n{\n runtime::DataContainer input(new cvsupport::Image(\"barcode.png\")); \n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));\n m_operator->setInputData(Scan::INPUT, input);\n \n runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);\n \n runtime::ReadAccess access(result);\n const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();\n CPPUNIT_ASSERT_EQUAL(std::size_t(1), content.size());\n const runtime::String* symbol = runtime::data_cast<runtime::String>(content[0]);\n CPPUNIT_ASSERT_EQUAL(symbol->get(), std::string(\"9876543210128\"));\n}\n\nvoid ScanTest::testExecuteWrongSymbolType()\n{\n runtime::DataContainer input(new cvsupport::Image(\"barcode.png\")); \n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN8));\n m_operator->setInputData(Scan::INPUT, input);\n \n runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);\n \n runtime::ReadAccess access(result);\n const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();\n CPPUNIT_ASSERT_EQUAL(std::size_t(0), content.size());\n}\n\nvoid ScanTest::testSetSymbolType()\n{\n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));\n runtime::DataRef value = m_operator->getParameter(Scan::SYMBOL_TYPE);\n \n CPPUNIT_ASSERT_EQUAL(runtime::Enum(::zbar::ZBAR_EAN13),\n runtime::data_cast<runtime::Enum>(value));\n}\n\nvoid ScanTest::tearDown ( void )\n{\n delete m_operator;\n}\n\n}\n}\n\n<commit_msg>Fix scan test<commit_after>\/* \n* Copyright 2016 Matthias Fuchs\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n\n#include <zbar.h>\n\n#include <stromx\/runtime\/ConstDataRef.h>\n#include <stromx\/runtime\/DataContainer.h>\n#include <stromx\/runtime\/List.h>\n#include <stromx\/runtime\/OperatorTester.h>\n#include <stromx\/runtime\/ReadAccess.h>\n#include <stromx\/runtime\/String.h>\n#include <stromx\/cvsupport\/Image.h>\n\n#include \"stromx\/zbar\/Scan.h\"\n\nnamespace stromx\n{\nnamespace zbar\n{\n\nclass ScanTest : public CPPUNIT_NS :: TestFixture\n{\n CPPUNIT_TEST_SUITE (ScanTest);\n CPPUNIT_TEST (testExecute);\n CPPUNIT_TEST (testExecuteWrongSymbolType);\n CPPUNIT_TEST (testSetSymbolType);\n CPPUNIT_TEST_SUITE_END ();\n\n public:\n ScanTest() : m_operator(0) {}\n \n void setUp();\n void tearDown();\n\n protected:\n void testExecute();\n void testExecuteWrongSymbolType();\n void testSetSymbolType();\n \n private:\n runtime::OperatorTester* m_operator;\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION (ScanTest);\n\nvoid ScanTest::setUp ( void )\n{\n m_operator = new runtime::OperatorTester(new Scan());\n m_operator->initialize();\n m_operator->activate();\n}\n\nvoid ScanTest::testExecute()\n{\n runtime::DataContainer input(new cvsupport::Image(\"barcode.png\", cvsupport::Image::GRAYSCALE)); \n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));\n m_operator->setInputData(Scan::INPUT, input);\n \n runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);\n \n runtime::ReadAccess access(result);\n const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();\n CPPUNIT_ASSERT_EQUAL(std::size_t(1), content.size());\n const runtime::String* symbol = runtime::data_cast<runtime::String>(content[0]);\n CPPUNIT_ASSERT_EQUAL(symbol->get(), std::string(\"9876543210128\"));\n}\n\nvoid ScanTest::testExecuteWrongSymbolType()\n{\n runtime::DataContainer input(new cvsupport::Image(\"barcode.png\", cvsupport::Image::GRAYSCALE)); \n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN8));\n m_operator->setInputData(Scan::INPUT, input);\n \n runtime::DataContainer result = m_operator->getOutputData(Scan::SYMBOLS);\n \n runtime::ReadAccess access(result);\n const std::vector<const runtime::Data*> & content = access.get<runtime::List>().content();\n CPPUNIT_ASSERT_EQUAL(std::size_t(0), content.size());\n}\n\nvoid ScanTest::testSetSymbolType()\n{\n m_operator->setParameter(Scan::SYMBOL_TYPE, runtime::Enum(::zbar::ZBAR_EAN13));\n runtime::DataRef value = m_operator->getParameter(Scan::SYMBOL_TYPE);\n \n CPPUNIT_ASSERT_EQUAL(runtime::Enum(::zbar::ZBAR_EAN13),\n runtime::data_cast<runtime::Enum>(value));\n}\n\nvoid ScanTest::tearDown ( void )\n{\n delete m_operator;\n}\n\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n\n\/*\n \n It is possible to change the target sound file for this test using the macros below.\n Both sound files are included in the Jamoma respository at the following path:\n {JAMOMA_ROOT}\/Core\/DSP\/extensions\/SoundfileLib\/\n \n The test should look for the named TESTFILE at this path.\n \n *\/\n\n\/* *\/\n #define TESTFILE \"geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n\/* *\/\n\n\/* \n#define TESTFILE \"ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n int errorCount = 0;\n int testAssertionCount = 0;\n \n \/\/ assemble the full path of the target sound file\n \n TTString testSoundPath = TTFoundationBinaryPath;\n int pos = testSoundPath.find_last_of('\/');\n testSoundPath = testSoundPath.substr(0,pos+1);\n testSoundPath += TESTFILE;\n \n std::cout << \"We will be using the following path for testing: \" << testSoundPath << \"\\n\";\n \n try {\n \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n \/\/ TEST 0: establish our objects & pointers\n TTObject* testTargetMatrix = new TTObject(\"samplematrix\");\n TTObject* testNonSampleMatrix = new TTObject(\"delay\");\n TTObjectBase* objectBasePtrToSampleMatrix;\n TTObjectBase* ptrToNonSampleMatrix;\n \n \/\/ TEST 1: set the filepath\n TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };\n \n TTTestAssertion(\"setFilePath operates successfully\",\n result1,\n testAssertionCount,\n errorCount);\n \n \/\/ TEST 2: set up the samplematrix first\n int channelsSend = 1; \/\/ compiler complained about TTInt32 being ambiguous here\n int lengthSend = 22050; \/\/ compiler complained about TTInt32 being ambiguous here\n testTargetMatrix->set(\"numChannels\", channelsSend);\n testTargetMatrix->set(\"lengthInSamples\", lengthSend);\n \n TTInt32 channelsReturn, lengthReturn;\n \n testTargetMatrix->get(\"numChannels\", channelsReturn);\n testTargetMatrix->get(\"lengthInSamples\", lengthReturn);\n \n \/\/ now for the actual test\n TTBoolean result2a = { channelsSend == channelsReturn };\n \n TTTestAssertion(\"numChannels attribute set successfully\",\n\t\t\t\t\t\tresult2a,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n TTBoolean result2b = { lengthSend == lengthReturn };\n \n TTTestAssertion(\"lengthInSamples attribute set successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \/\/\n \n \/\/ TEST 3: set the target via an objectBasePtr\n objectBasePtrToSampleMatrix = testTargetMatrix->instance(); \/\/ is there a better syntax for this?\n \n TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n \n TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 4: set the target to a non-SampleMatrix, should FAIL\n ptrToNonSampleMatrix = testNonSampleMatrix->instance();\n \n TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n \n TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult4,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 5: copy samplevalues until samplematrix is filled\n \n TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };\n \n TTTestAssertion(\"copyUntilFilled operates successfully\",\n\t\t\t\t\t\tresult5,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence\n \n \/\/ create a new TTSampleMatrix\n TTObject newTargetMatrix(\"samplematrix\");\n \n \/\/ set the length and channel count\n newTargetMatrix.set(\"numChannels\", TESTNUMCHANNELS);\n newTargetMatrix.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n \n \/\/ prepare necessary TTValues\n TTValue loadInput6 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n TTValue aReturnWeDontCareAbout6;\n \n \/\/ send message\n TTBoolean result6a = { newTargetMatrix.send(\"load\", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };\n \n TTTestAssertion(\"TTSampleMatrix load operates successfully\",\n result6a,\n testAssertionCount,\n errorCount);\n \n \/\/ now let's test some values!\n int randomIndex6;\n TTSampleValue randomValueSoundFile6;\n TTBoolean result6 = true;\n \n for (int i = 0; i<5; i++)\n {\n randomIndex6 = lengthReturn * TTRandom64();\n std::cout << \"let's look at index \" << randomIndex6 << \"\\n\";\n \n TTValue peekInput6(randomIndex6);\n peekInput6.append(0);\n TTValue peekOutput6;\n \n this->peek(randomIndex6,0,randomValueSoundFile6);\n newTargetMatrix.send(\"peek\",peekInput6,peekOutput6);\n std::cout << \"Does \" << randomValueSoundFile6 << \" = \" << double(peekOutput6) << \" ?\\n\";\n \n if (result6) \/\/ allows test to keep variable false once it is false\n result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);\n }\n \n TTTestAssertion(\"comparing 5 random values for equivalence\",\n result6,\n testAssertionCount,\n errorCount);\n \n \/\/\n \n \/\/ TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence\n \n \/\/ create a new TTBuffer\n TTObject newTargetBuffer(\"buffer\");\n \n \/\/ set the length and channel count\n newTargetBuffer.set(\"numChannels\", TESTNUMCHANNELS);\n newTargetBuffer.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n \n \/\/ prepare necessary TTValues\n TTValue loadInput7 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n TTValue aReturnWeDontCareAbout7;\n \n \/\/ send message\n TTBoolean result7a = { newTargetBuffer.send(\"load\", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };\n \n TTTestAssertion(\"TTBuffer load operates successfully\",\n result7a,\n testAssertionCount,\n errorCount);\n \n \/\/ now let's test some values!\n int randomIndex7;\n TTSampleValue randomValueSoundFile7;\n TTBoolean result7 = true;\n \n for (int i = 0; i<5; i++)\n {\n randomIndex7 = lengthReturn * TTRandom64();\n std::cout << \"let's look at index \" << randomIndex7 << \"\\n\";\n \n TTValue peekInput7(randomIndex7);\n peekInput7.append(0);\n TTValue peekOutput7;\n \n this->peek(randomIndex7,0,randomValueSoundFile7);\n newTargetBuffer.send(\"peek\",peekInput7,peekOutput7);\n std::cout << \"Does \" << randomValueSoundFile7 << \" = \" << double(peekOutput7) << \" ?\\n\";\n \n if (result7) \/\/ allows test to keep variable false once it is false\n result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);\n }\n \n TTTestAssertion(\"comparing 5 random values for equivalence\",\n result7,\n testAssertionCount,\n errorCount);\n \n \/\/\n \n \n \/\/ releasing objects\n objectBasePtrToSampleMatrix = NULL;\n ptrToNonSampleMatrix = NULL;\n delete testTargetMatrix;\n delete testNonSampleMatrix;\n \n } catch (...) {\n TTTestAssertion(\"FAILED to run tests -- likely that necessary objects did not instantiate\",\n 0,\n testAssertionCount,\n errorCount);\n \n }\n \n return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<commit_msg>TTSoundfileLoader::test() - test 7 works. resolves #176, but I don't like this goofy syntax.<commit_after>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n#include \"TTBuffer.h\"\n\n\/*\n \n It is possible to change the target sound file for this test using the macros below.\n Both sound files are included in the Jamoma respository at the following path:\n {JAMOMA_ROOT}\/Core\/DSP\/extensions\/SoundfileLib\/\n \n The test should look for the named TESTFILE at this path.\n \n *\/\n\n\/* *\/\n #define TESTFILE \"geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n\/* *\/\n\n\/* \n#define TESTFILE \"ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n int errorCount = 0;\n int testAssertionCount = 0;\n \n \/\/ assemble the full path of the target sound file\n \n TTString testSoundPath = TTFoundationBinaryPath;\n int pos = testSoundPath.find_last_of('\/');\n testSoundPath = testSoundPath.substr(0,pos+1);\n testSoundPath += TESTFILE;\n \n std::cout << \"We will be using the following path for testing: \" << testSoundPath << \"\\n\";\n \n try {\n \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n \/\/ TEST 0: establish our objects & pointers\n TTObject* testTargetMatrix = new TTObject(\"samplematrix\");\n TTObject* testNonSampleMatrix = new TTObject(\"delay\");\n TTObjectBase* objectBasePtrToSampleMatrix;\n TTObjectBase* ptrToNonSampleMatrix;\n \n \/\/ TEST 1: set the filepath\n TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };\n \n TTTestAssertion(\"setFilePath operates successfully\",\n result1,\n testAssertionCount,\n errorCount);\n \n \/\/ TEST 2: set up the samplematrix first\n int channelsSend = 1; \/\/ compiler complained about TTInt32 being ambiguous here\n int lengthSend = 22050; \/\/ compiler complained about TTInt32 being ambiguous here\n testTargetMatrix->set(\"numChannels\", channelsSend);\n testTargetMatrix->set(\"lengthInSamples\", lengthSend);\n \n TTInt32 channelsReturn, lengthReturn;\n \n testTargetMatrix->get(\"numChannels\", channelsReturn);\n testTargetMatrix->get(\"lengthInSamples\", lengthReturn);\n \n \/\/ now for the actual test\n TTBoolean result2a = { channelsSend == channelsReturn };\n \n TTTestAssertion(\"numChannels attribute set successfully\",\n\t\t\t\t\t\tresult2a,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n TTBoolean result2b = { lengthSend == lengthReturn };\n \n TTTestAssertion(\"lengthInSamples attribute set successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \/\/\n \n \/\/ TEST 3: set the target via an objectBasePtr\n objectBasePtrToSampleMatrix = testTargetMatrix->instance(); \/\/ is there a better syntax for this?\n \n TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n \n TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 4: set the target to a non-SampleMatrix, should FAIL\n ptrToNonSampleMatrix = testNonSampleMatrix->instance();\n \n TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n \n TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult4,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 5: copy samplevalues until samplematrix is filled\n \n TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };\n \n TTTestAssertion(\"copyUntilFilled operates successfully\",\n\t\t\t\t\t\tresult5,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n \n \/\/ TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence\n \n \/\/ create a new TTSampleMatrix\n TTObject newTargetMatrix(\"samplematrix\");\n \n \/\/ set the length and channel count\n newTargetMatrix.set(\"numChannels\", TESTNUMCHANNELS);\n newTargetMatrix.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n \n \/\/ prepare necessary TTValues\n TTValue loadInput6 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n TTValue aReturnWeDontCareAbout6;\n \n \/\/ send message\n TTBoolean result6a = { newTargetMatrix.send(\"load\", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };\n \n TTTestAssertion(\"TTSampleMatrix load operates successfully\",\n result6a,\n testAssertionCount,\n errorCount);\n \n \/\/ now let's test some values!\n int randomIndex6;\n TTSampleValue randomValueSoundFile6;\n TTBoolean result6 = true;\n \n for (int i = 0; i<5; i++)\n {\n randomIndex6 = lengthReturn * TTRandom64();\n std::cout << \"let's look at index \" << randomIndex6 << \"\\n\";\n \n TTValue peekInput6(randomIndex6);\n peekInput6.append(0);\n TTValue peekOutput6;\n \n this->peek(randomIndex6,0,randomValueSoundFile6);\n newTargetMatrix.send(\"peek\",peekInput6,peekOutput6);\n std::cout << \"Does \" << randomValueSoundFile6 << \" = \" << double(peekOutput6) << \" ?\\n\";\n \n if (result6) \/\/ allows test to keep variable false once it is false\n result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);\n }\n \n TTTestAssertion(\"comparing 5 random values for equivalence\",\n result6,\n testAssertionCount,\n errorCount);\n \n \/\/\n \n \/\/ TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence\n \n \/\/ create a new TTBuffer\n TTObject newTargetBuffer(\"buffer\");\n \n \/\/ set the length and channel count\n newTargetBuffer.set(\"numChannels\", TESTNUMCHANNELS);\n newTargetBuffer.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n \n \/\/ prepare necessary TTValues\n TTValue loadInput7 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;\n TTValue checkOutValue;\n \n \/\/ send message\n TTBoolean result7a = { newTargetBuffer.send(\"load\", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };\n \n TTTestAssertion(\"TTBuffer load operates successfully\",\n result7a,\n testAssertionCount,\n errorCount);\n \n \/\/ check out samplematrix\n newTargetBuffer.send(\"checkOutMatrix\",aSendWeDontCareAbout7,checkOutValue);\n TTObjectBase* checkedOutMatrix = checkOutValue[0];\n \n \/\/ now let's test some values!\n int randomIndex7;\n TTSampleValue randomValueSoundFile7;\n TTBoolean result7 = true;\n \n for (int i = 0; i<5; i++)\n {\n randomIndex7 = lengthReturn * TTRandom64();\n std::cout << \"let's look at index \" << randomIndex7 << \"\\n\";\n \n TTValue peekInput7(randomIndex7);\n peekInput7.append(0);\n TTValue peekOutput7;\n \n this->peek(randomIndex7,0,randomValueSoundFile7);\n checkedOutMatrix->sendMessage(\"peek\",peekInput7,peekOutput7);\n std::cout << \"Does \" << randomValueSoundFile7 << \" = \" << double(peekOutput7) << \" ?\\n\";\n \n if (result7) \/\/ allows test to keep variable false once it is false\n result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);\n }\n \n TTTestAssertion(\"comparing 5 random values for equivalence\",\n result7,\n testAssertionCount,\n errorCount);\n \n \/\/ check in samplematrix\n TTBoolean result7c = { newTargetBuffer.send(\"checkInMatrix\",checkOutValue,aReturnWeDontCareAbout7) == kTTErrNone };\n \n TTTestAssertion(\"TTBuffer checks in SampleMatrix successfully\",\n result7c,\n testAssertionCount,\n errorCount);\n \n \n \/\/ releasing objects\n objectBasePtrToSampleMatrix = NULL;\n ptrToNonSampleMatrix = NULL;\n delete testTargetMatrix;\n delete testNonSampleMatrix;\n \n } catch (...) {\n TTTestAssertion(\"FAILED to run tests -- likely that necessary objects did not instantiate\",\n 0,\n testAssertionCount,\n errorCount);\n \n }\n \n return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* File: SamplerGenMonkeyPatch.cpp\n * Author: Chris Dellin <cdellin@gmail.com>\n * Copyright: 2015 Carnegie Mellon University\n * License: BSD\n *\/\n\n#include <sstream>\n#include <ompl\/base\/StateSampler.h>\n#include <ompl_multiset\/SamplerGenMonkeyPatch.h>\n\n\/\/ from Johannes Schaub - litb\n\/\/ http:\/\/bloglitb.blogspot.de\/2011\/12\/access-to-private-members-safer.html\n\nnamespace {\n \n \/\/ this defines a friend function\n \/\/ that can be called by ADL using the tag type\n template<typename Tag, typename Tag::type M>\n struct Rob { \n friend typename Tag::type get(Tag) {\n return M;\n }\n };\n\n \/\/ tag used to access StateSampler::rng_\n struct StateSampler_rng { \n typedef ompl::RNG ompl::base::StateSampler::*type;\n friend type get(StateSampler_rng);\n };\n template struct Rob<StateSampler_rng, &ompl::base::StateSampler::rng_>;\n\n \/\/ tag used to access RNG::generator_\n struct RNG_generator { \n typedef boost::mt19937 ompl::RNG::*type;\n friend type get(RNG_generator);\n };\n template struct Rob<RNG_generator, &ompl::RNG::generator_>;\n \n} \/\/ anonymous namespace\n\nboost::mt19937 & ompl_multiset::SamplerGenMonkeyPatch(\n ompl::base::StateSamplerPtr sampler)\n{\n return (*sampler).*get(StateSampler_rng()).*get(RNG_generator());\n}\n<commit_msg>fixed up indentation<commit_after>\/* File: SamplerGenMonkeyPatch.cpp\n * Author: Chris Dellin <cdellin@gmail.com>\n * Copyright: 2015 Carnegie Mellon University\n * License: BSD\n *\/\n\n#include <sstream>\n#include <ompl\/base\/StateSampler.h>\n#include <ompl_multiset\/SamplerGenMonkeyPatch.h>\n\n\/\/ from Johannes Schaub - litb\n\/\/ http:\/\/bloglitb.blogspot.de\/2011\/12\/access-to-private-members-safer.html\n\nnamespace {\n \n \/\/ this defines a friend function\n \/\/ that can be called by ADL using the tag type\n template<typename Tag, typename Tag::type M>\n struct Rob\n { \n friend typename Tag::type get(Tag)\n {\n return M;\n }\n };\n\n \/\/ tag used to access StateSampler::rng_\n struct StateSampler_rng\n { \n typedef ompl::RNG ompl::base::StateSampler::*type;\n friend type get(StateSampler_rng);\n };\n template struct Rob<StateSampler_rng, &ompl::base::StateSampler::rng_>;\n\n \/\/ tag used to access RNG::generator_\n struct RNG_generator\n { \n typedef boost::mt19937 ompl::RNG::*type;\n friend type get(RNG_generator);\n };\n template struct Rob<RNG_generator, &ompl::RNG::generator_>;\n \n} \/\/ anonymous namespace\n\nboost::mt19937 & ompl_multiset::SamplerGenMonkeyPatch(\n ompl::base::StateSamplerPtr sampler)\n{\n return (*sampler).*get(StateSampler_rng()).*get(RNG_generator());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: testserver.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2003-03-18 19:07:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <string.h>\n#include <assert.h>\n\n#ifndef _OSL_TIME_H_\n#include <osl\/time.h>\n#endif\n\n#include <osl\/mutex.hxx>\n#include <osl\/conditn.h>\n\n#include <osl\/thread.hxx>\n\n#include <cppuhelper\/servicefactory.hxx>\n#include <cppuhelper\/implbase1.hxx>\n\n#include <com\/sun\/star\/connection\/XAcceptor.hpp>\n#include <com\/sun\/star\/connection\/XConnection.hpp>\n\n#include <com\/sun\/star\/bridge\/XInstanceProvider.hpp>\n#include <com\/sun\/star\/bridge\/XBridgeFactory.hpp>\n\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n\n\n#include <test\/XTestFactory.hpp>\n\n#include <cppuhelper\/weak.hxx>\n\nusing namespace ::test;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::bridge;\nusing namespace ::com::sun::star::connection;\n#include \"testcomp.h\"\n#ifdef SAL_W32\n#include <conio.h>\n#endif\n\n\/*********\n *\n ********\/\n\n\n\nclass MyThread :\n public Thread\n{\npublic:\n MyThread( const Reference< XAcceptor > &r ,\n const Reference< XBridgeFactory > &rFactory,\n const Reference< XMultiServiceFactory > &rSMgr,\n const OUString &sConnectionDescription,\n const OUString &sProtocol,\n sal_Bool bReverse,\n sal_Bool bLatency ) :\n m_rAcceptor( r ),\n m_rBridgeFactory ( rFactory ),\n m_sConnectionDescription( sConnectionDescription ),\n m_sProtocol( sProtocol ),\n m_bReverse( bReverse ),\n m_bLatency( bLatency ),\n m_rSMgr( rSMgr )\n {}\n virtual void SAL_CALL run();\n\n void latencyTest( const Reference< XConnection > &r );\n\nprivate:\n Reference < XAcceptor > m_rAcceptor;\n Reference < XBridgeFactory > m_rBridgeFactory;\n Reference < XMultiServiceFactory > m_rSMgr;\n OUString m_sConnectionDescription;\n OUString m_sProtocol;\n sal_Bool m_bReverse;\n sal_Bool m_bLatency;\n};\n\n\nvoid MyThread::latencyTest( const Reference< XConnection > &r )\n{\n Sequence < sal_Int8 > s;\n while( 12 == r->read( s , 12 ) )\n {\n r->read( s , 188 );\n s = Sequence < sal_Int8 >(60);\n r->write( s );\n }\n}\n\nvoid MyThread::run()\n{\n\n while ( sal_True )\n {\n try\n {\n Reference < XConnection > rConnection =\n m_rAcceptor->accept( m_sConnectionDescription );\n\n if( ! rConnection.is() )\n {\n break;\n }\n if( m_bLatency )\n {\n latencyTest( rConnection );\n }\n else\n {\n\n Reference < XBridge > rBridge =\n m_rBridgeFactory->createBridge(\n OUString() ,\n m_sProtocol,\n rConnection ,\n (XInstanceProvider * ) new OInstanceProvider(m_rSMgr) );\n\n\n if( m_bReverse )\n {\n printf( \"doing reverse callme test (test is ok, when on each line a +- appears\\n\" );\n Reference < XInterface > r = rBridge->getInstance(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"blubber\" )));\n Reference < XTestFactory > rFactory( r , UNO_QUERY );\n Reference < XCallMe > rCallMe = rFactory->createCallMe();\n\n for( sal_Int32 i = 0 ; i < 1 ; i ++ )\n {\n rCallMe->callOneway(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"my test string\")) , 2 );\n }\n printf( \"all oneway are send\\n\" );\n rCallMe->call( OUString::createFromAscii( \"reverse call me test finished\" ) , 0 );\n printf( \"revers callme test finished\\n\" );\n }\n }\n }\n catch ( Exception & e )\n {\n printf( \"Exception was thrown by acceptor \\n\" );\n OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n printf( \"%s\\n\" , o.getStr() );\n break;\n }\n catch ( ... )\n {\n printf( \"Exception was thrown by acceptor thread\\n\" );\n break;\n }\n }\n}\n\n\nint main( int argc, char *argv[] )\n{\n\/\/ testserver();\n\n if( argc < 2 )\n {\n printf( \"usage : testserver [-r] connectionstring\\n\"\n \" -r does a reverse test (server calls client)\\n\" );\n return 0;\n }\n\n OUString sConnectionString;\n OUString sProtocol;\n sal_Bool bReverse = sal_False;\n sal_Bool bLatency = sal_False;\n\n parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse );\n\n {\n Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory(\n OUString( RTL_CONSTASCII_USTRINGPARAM( \"server.rdb\" ) ) );\n\n Reference < XBridgeFactory > rBridgeFactory ( createComponent(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.bridge.BridgeFactory\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"brdgfctr\" )),\n rSMgr ),\n UNO_QUERY );\n\n\n createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.bridge.Bridge.iiop\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"remotebridge\")),\n rSMgr );\n\n\n Reference < XAcceptor > rAcceptor(\n createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.connection.Acceptor\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"acceptor\")),\n rSMgr ) ,\n UNO_QUERY );\n\n MyThread thread( rAcceptor ,\n rBridgeFactory,\n rSMgr,\n sConnectionString,\n sProtocol,\n bReverse,\n bLatency);\n thread.create();\n\n#ifdef SAL_W32\n _getch();\n#elif SOLARIS\n getchar();\n#elif LINUX\n TimeValue value={360,0};\n osl_waitThread( &value );\n#endif\n printf( \"Closing...\\n\" );\n\n rAcceptor->stopAccepting();\n thread.join();\n\n printf( \"Closed\\n\" );\n\n Reference < XComponent > rComp2( rBridgeFactory , UNO_QUERY );\n rComp2->dispose();\n Reference < XComponent > rComp( rSMgr, UNO_QUERY );\n rComp->dispose();\n }\n return 0;\n}\n<commit_msg>INTEGRATION: CWS dbgmacros1 (1.8.6); FILE MERGED 2003\/04\/09 10:15:49 kso 1.8.6.1: #108413# - debug macro unification.<commit_after>\/*************************************************************************\n *\n * $RCSfile: testserver.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2003-04-15 16:30:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <string.h>\n\n#ifndef _OSL_TIME_H_\n#include <osl\/time.h>\n#endif\n\n#include <osl\/mutex.hxx>\n#include <osl\/conditn.h>\n\n#include <osl\/thread.hxx>\n\n#include <cppuhelper\/servicefactory.hxx>\n#include <cppuhelper\/implbase1.hxx>\n\n#include <com\/sun\/star\/connection\/XAcceptor.hpp>\n#include <com\/sun\/star\/connection\/XConnection.hpp>\n\n#include <com\/sun\/star\/bridge\/XInstanceProvider.hpp>\n#include <com\/sun\/star\/bridge\/XBridgeFactory.hpp>\n\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n\n\n#include <test\/XTestFactory.hpp>\n\n#include <cppuhelper\/weak.hxx>\n\nusing namespace ::test;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::bridge;\nusing namespace ::com::sun::star::connection;\n#include \"testcomp.h\"\n#ifdef SAL_W32\n#include <conio.h>\n#endif\n\n\/*********\n *\n ********\/\n\n\n\nclass MyThread :\n public Thread\n{\npublic:\n MyThread( const Reference< XAcceptor > &r ,\n const Reference< XBridgeFactory > &rFactory,\n const Reference< XMultiServiceFactory > &rSMgr,\n const OUString &sConnectionDescription,\n const OUString &sProtocol,\n sal_Bool bReverse,\n sal_Bool bLatency ) :\n m_rAcceptor( r ),\n m_rBridgeFactory ( rFactory ),\n m_sConnectionDescription( sConnectionDescription ),\n m_sProtocol( sProtocol ),\n m_bReverse( bReverse ),\n m_bLatency( bLatency ),\n m_rSMgr( rSMgr )\n {}\n virtual void SAL_CALL run();\n\n void latencyTest( const Reference< XConnection > &r );\n\nprivate:\n Reference < XAcceptor > m_rAcceptor;\n Reference < XBridgeFactory > m_rBridgeFactory;\n Reference < XMultiServiceFactory > m_rSMgr;\n OUString m_sConnectionDescription;\n OUString m_sProtocol;\n sal_Bool m_bReverse;\n sal_Bool m_bLatency;\n};\n\n\nvoid MyThread::latencyTest( const Reference< XConnection > &r )\n{\n Sequence < sal_Int8 > s;\n while( 12 == r->read( s , 12 ) )\n {\n r->read( s , 188 );\n s = Sequence < sal_Int8 >(60);\n r->write( s );\n }\n}\n\nvoid MyThread::run()\n{\n\n while ( sal_True )\n {\n try\n {\n Reference < XConnection > rConnection =\n m_rAcceptor->accept( m_sConnectionDescription );\n\n if( ! rConnection.is() )\n {\n break;\n }\n if( m_bLatency )\n {\n latencyTest( rConnection );\n }\n else\n {\n\n Reference < XBridge > rBridge =\n m_rBridgeFactory->createBridge(\n OUString() ,\n m_sProtocol,\n rConnection ,\n (XInstanceProvider * ) new OInstanceProvider(m_rSMgr) );\n\n\n if( m_bReverse )\n {\n printf( \"doing reverse callme test (test is ok, when on each line a +- appears\\n\" );\n Reference < XInterface > r = rBridge->getInstance(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"blubber\" )));\n Reference < XTestFactory > rFactory( r , UNO_QUERY );\n Reference < XCallMe > rCallMe = rFactory->createCallMe();\n\n for( sal_Int32 i = 0 ; i < 1 ; i ++ )\n {\n rCallMe->callOneway(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"my test string\")) , 2 );\n }\n printf( \"all oneway are send\\n\" );\n rCallMe->call( OUString::createFromAscii( \"reverse call me test finished\" ) , 0 );\n printf( \"revers callme test finished\\n\" );\n }\n }\n }\n catch ( Exception & e )\n {\n printf( \"Exception was thrown by acceptor \\n\" );\n OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n printf( \"%s\\n\" , o.getStr() );\n break;\n }\n catch ( ... )\n {\n printf( \"Exception was thrown by acceptor thread\\n\" );\n break;\n }\n }\n}\n\n\nint main( int argc, char *argv[] )\n{\n\/\/ testserver();\n\n if( argc < 2 )\n {\n printf( \"usage : testserver [-r] connectionstring\\n\"\n \" -r does a reverse test (server calls client)\\n\" );\n return 0;\n }\n\n OUString sConnectionString;\n OUString sProtocol;\n sal_Bool bReverse = sal_False;\n sal_Bool bLatency = sal_False;\n\n parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse );\n\n {\n Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory(\n OUString( RTL_CONSTASCII_USTRINGPARAM( \"server.rdb\" ) ) );\n\n Reference < XBridgeFactory > rBridgeFactory ( createComponent(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.bridge.BridgeFactory\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"brdgfctr\" )),\n rSMgr ),\n UNO_QUERY );\n\n\n createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.bridge.Bridge.iiop\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"remotebridge\")),\n rSMgr );\n\n\n Reference < XAcceptor > rAcceptor(\n createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.connection.Acceptor\")),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"acceptor\")),\n rSMgr ) ,\n UNO_QUERY );\n\n MyThread thread( rAcceptor ,\n rBridgeFactory,\n rSMgr,\n sConnectionString,\n sProtocol,\n bReverse,\n bLatency);\n thread.create();\n\n#ifdef SAL_W32\n _getch();\n#elif SOLARIS\n getchar();\n#elif LINUX\n TimeValue value={360,0};\n osl_waitThread( &value );\n#endif\n printf( \"Closing...\\n\" );\n\n rAcceptor->stopAccepting();\n thread.join();\n\n printf( \"Closed\\n\" );\n\n Reference < XComponent > rComp2( rBridgeFactory , UNO_QUERY );\n rComp2->dispose();\n Reference < XComponent > rComp( rSMgr, UNO_QUERY );\n rComp->dispose();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QDebug>\n\nusing namespace View;\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n undoButton = new QPushButton(this);\n undoButton->setText(\"Undo\");\n undoButton->move(50, 600);\n connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo()));\n\n redoButton = new QPushButton(this);\n redoButton->setText(\"Redo\");\n redoButton->move(150, 600);\n connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo()));\n\n loadPuzzleButton = new QPushButton(this);\n loadPuzzleButton->setText(\"Load Puzzle\");\n loadPuzzleButton->move(250, 600);\n connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed()));\n\n savePuzzleButton = new QPushButton(this);\n savePuzzleButton->setText(\"Save Puzzle\");\n savePuzzleButton->move(350, 600);\n connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed()));\n\n loadProgressButton = new QPushButton(this);\n loadProgressButton->setText(\"Load Progress\");\n loadProgressButton->move(450, 600);\n connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed()));\n\n saveProgressButton = new QPushButton(this);\n saveProgressButton->setText(\"Save Progress\");\n saveProgressButton->move(550, 600);\n connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed()));\n\n for (int i = 1; i < 10; i++) {\n for (int j = 1; j < 10; j++) {\n\n \/\/Creating and formatting each QLineEdit field.\n fields[i][j] = new QLineEdit(\" \",this);\n fields[i][j]->setInputMask(\"D\");\n fields[i][j]->setObjectName(QString::number(i) + \"_\" + QString::number(j));\n fields[i][j]->setFixedHeight(31);\n fields[i][j]->setFixedWidth(41);\n fields[i][j]->setAlignment(Qt::AlignCenter);\n fields[i][j]->setStyleSheet(\"font: 18pt;\");\n\n connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString)));\n }\n }\n createLayout();\n}\n\nMainWindow::~MainWindow()\n{\n \/\/buttons are deleted when ui is deleted since it is parent, see Qt documentation\n delete ui;\n}\n\nvoid MainWindow::fieldChanged(QString text)\n{\n \/\/Will eventually parse the object name '1_1' (row 1, col 1) into a position array,\n \/\/and pass the position and values to the Controller, for now just update label to display Value\/Field.\n QLineEdit *field = (QLineEdit *)sender();\n emit onMakeMove(QString(\"Value: \" + text + \" Field: \" + field->objectName()));\n}\n\n\nvoid MainWindow::createLayout()\n{\n ui->gridLayout->setMargin(6);\n ui->gridLayout->setSpacing(6);\n\n for(int i = 1; i < 10; i++) {\n for(int j = 1; j < 10; j++) {\n ui->gridLayout->addWidget(fields[i][j], i, j);\n\n }\n }\n}\n<commit_msg>Changed input mask to QValidator<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QDebug>\n\nusing namespace View;\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n undoButton = new QPushButton(this);\n undoButton->setText(\"Undo\");\n undoButton->move(50, 600);\n connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo()));\n\n redoButton = new QPushButton(this);\n redoButton->setText(\"Redo\");\n redoButton->move(150, 600);\n connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo()));\n\n loadPuzzleButton = new QPushButton(this);\n loadPuzzleButton->setText(\"Load Puzzle\");\n loadPuzzleButton->move(250, 600);\n connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed()));\n\n savePuzzleButton = new QPushButton(this);\n savePuzzleButton->setText(\"Save Puzzle\");\n savePuzzleButton->move(350, 600);\n connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed()));\n\n loadProgressButton = new QPushButton(this);\n loadProgressButton->setText(\"Load Progress\");\n loadProgressButton->move(450, 600);\n connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed()));\n\n saveProgressButton = new QPushButton(this);\n saveProgressButton->setText(\"Save Progress\");\n saveProgressButton->move(550, 600);\n connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed()));\n\n for (int i = 1; i < 10; i++) {\n for (int j = 1; j < 10; j++) {\n\n \/\/Creating and formatting each QLineEdit field.\n fields[i][j] = new QLineEdit();\n\n QValidator *val = new QIntValidator(1,9,fields[i][j]);\n fields[i][j]->setValidator(val);\n\n\/\/ fields[i][j]->setInputMask(\"D\");\n fields[i][j]->setObjectName(QString::number(i) + \"_\" + QString::number(j));\n fields[i][j]->setFixedHeight(31);\n fields[i][j]->setFixedWidth(41);\n fields[i][j]->setAlignment(Qt::AlignCenter);\n fields[i][j]->setStyleSheet(\"font: 18pt;\");\n\n connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString)));\n }\n }\n createLayout();\n}\n\nMainWindow::~MainWindow()\n{\n \/\/buttons are deleted when ui is deleted since it is parent, see Qt documentation\n delete ui;\n}\n\nvoid MainWindow::fieldChanged(QString text)\n{\n \/\/Will eventually parse the object name '1_1' (row 1, col 1) into a position array,\n \/\/and pass the position and values to the Controller, for now just update label to display Value\/Field.\n QLineEdit *field = (QLineEdit *)sender();\n emit onMakeMove(QString(\"Value: \" + text + \" Field: \" + field->objectName()));\n}\n\n\nvoid MainWindow::createLayout()\n{\n ui->gridLayout->setMargin(6);\n ui->gridLayout->setSpacing(6);\n\n for(int i = 1; i < 10; i++) {\n for(int j = 1; j < 10; j++) {\n ui->gridLayout->addWidget(fields[i][j], i, j);\n\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bigentry.hpp\"\n#include \"log.hpp\"\n#include <algorithm>\n#include <cstdio>\n#include <cctype>\n\n#include FILESYSTEM_HEADER\nnamespace fs = FILESYSTEM_NAMESPACE;\n\nnamespace OpenBFME {\n\nuint32_t readUInt32(FILE* file){\n uint8_t val[4];\n fread(val, 1, 4, file);\n return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3];\n}\n\nvoid writeUInt32(FILE* file, uint32_t value){\n uint8_t val[] { uint8_t(value >> 24), uint8_t(value >> 16), uint8_t(value >> 8), uint8_t(value) };\n fwrite(val, 1, 4, file);\n}\n\nstring readString(FILE* file, uint32_t limit, char terminator = '\\0'){\n string data;\n while(uint32_t(ftell(file)) < limit){\n character c = fgetc(file);\n if(c == '\\0' || c == terminator || ferror(file) || feof(file)){\n break;\n }\n data += c;\n }\n return data;\n}\n\nBigArchive::BigArchive(const string &filename) : archiveFilename(fs::path(filename).generic_string()), file(nullptr) { }\n\nBigArchive::~BigArchive() {\n close();\n}\n\nbool BigArchive::readHeader() {\n if (fs::is_directory(fs::path(archiveFilename))) {\n backend = Folder;\n \n \/* Make sure the archiveFilename ends with a '\/' *\/\n if (archiveFilename.back() != '\/')\n archiveFilename += '\/';\n\n for (fs::recursive_directory_iterator dir(archiveFilename), end; dir != end; ++dir) {\n const fs::path& currentPath = dir->path();\n if (fs::is_regular_file(currentPath)) {\n string filename = currentPath.generic_string();\n\n \/* Check to see if the filename contains the parent path, and if so remove it. *\/\n if (filename.compare(0, archiveFilename.size(), archiveFilename, 0, archiveFilename.size()) == 0)\n filename.erase(0, archiveFilename.size());\n else\n \/* Otherwise fall back to removing the first element in the path. *\/\n filename.erase(0, filename.find_first_of('\/') + 1);\n\n uint32_t filesize = uint32_t(fs::file_size(currentPath));\n\n entries.emplace(*this, 0, filesize, filename);\n Log::debug(\"File path: \\\"%s\\\" length: %#08x\", filename, filesize);\n }\n }\n\n return true;\n }\n\n backend = BigFile;\n\n if (!open())\n return false;\n\n \/* The first 4 bytes shoule be either \"BIG4\" or \"BIGF\", quit if they aren't. *\/\n character id[4] = {0};\n fread(id, 1, 4, file);\n\n if (id[0] != 'B' || id[1] != 'I' || id[2] != 'G' || (id[3] != '4' && id[3] != 'F')) {\n Log::error(\"File \\\"%s\\\" is not a valid big file!\");\n close();\n return false;\n }\n\n fseek(file, 8, SEEK_SET);\n\n uint32_t fileCount = readUInt32(file);\n uint32_t headerEnd = readUInt32(file);\n\n Log::info(\"File Count: %u Header End: %#08x\", fileCount, headerEnd);\n\n \/* Read the individual file information into entries. *\/\n for (uint32_t f = 0; f < fileCount; ++f) {\n uint32_t start = readUInt32(file);\n uint32_t end = start + readUInt32(file);\n string path = readString(file, headerEnd);\n std::replace(path.begin(), path.end(), '\\\\', '\/');\n\n entries.emplace(*this, start, end, path);\n\n Log::debug(\"File #%04d start: %#08x end: %#08x path: \\\"%s\\\"\", f + 1, start, end, path);\n }\n\n if (uint32_t(ftell(file)) > headerEnd)\n Log::warning(\"Reading of file info passed through end of header.\");\n\n return true;\n}\n\nbool BigArchive::open() {\n \/* File is already open. *\/\n if (file != nullptr)\n return true;\n\n \/* If it's a .big archive we can try to open the file here. *\/\n if (backend == BigFile)\n file = fopen(archiveFilename.c_str(), \"rb\");\n\n return file != nullptr;\n}\n\nvoid BigArchive::close() {\n if (file != nullptr) {\n fclose(file);\n file = nullptr;\n }\n currentEntry = nullptr;\n}\n\nbool BigArchive::openEntry(const BigEntry& entry) {\n entry.resetLineNumber();\n\n switch (backend) {\n case BigFile:\n if (open()) {\n fseek(file, entry.start, SEEK_SET);\n currentEntry = &entry;\n return true;\n }\n break;\n case Folder:\n close();\n file = fopen((archiveFilename + '\/' + entry.filename).c_str(), \"rb\");\n if (file != nullptr) {\n currentEntry = &entry;\n return true;\n }\n break;\n }\n return false;\n}\n\nconst BigEntry* BigArchive::openFile(const string &filename) {\n \/* Find an entry with the filename. *\/\n auto entry = std::find_if(begin(), end(), [&](const BigEntry& it){ return it.filename == filename; });\n\n \/* If one was found, open it and return it's address. *\/\n if (entry != end() && openEntry(*entry))\n return &(*entry);\n\n \/* Nothing was found, or it failed to open. *\/\n return nullptr;\n}\n\ncharacter BigArchive::getChar(const BigEntry &entry) {\n \/* The archive needs to be open, and we need to be inside the correct file. *\/\n if (!open() || eof(entry))\n return 0;\n\n character ch = fgetc(file);\n\n \/* Tell the entry we have a newline. *\/\n if (ch == '\\n')\n entry.incrementLineNumber();\n\n return ch;\n}\n\nvoid BigArchive::ungetChar(const BigEntry &entry, character c) {\n if (tell(entry) > 0) {\n ungetc(c, file);\n\n \/* If it was a newline we need the line number to go back to how it was before getting the character. *\/\n if (c == '\\n')\n entry.decrementLineNumber();\n }\n}\n\nbool BigArchive::seek(const BigEntry &entry, uint32_t pos) {\n \/* If the entry isn't the current one try opening it. *\/\n if (&entry != currentEntry && !openEntry(entry))\n return false;\n\n \/* Invalidate the stored current line number. *\/\n entry.invalidateLineNumber();\n\n pos += entry.start;\n\n \/* Make sure it's inside the file before seeking. *\/\n if (pos < entry.end) {\n fseek(file, pos, SEEK_SET);\n return true;\n }\n return false;\n}\n\nuint32_t BigArchive::tell(const BigEntry &entry) {\n \/* This only works if the file is already current. *\/\n if (&entry != currentEntry)\n return 0;\n\n uint32_t pos = ftell(file);\n if (pos <= entry.start)\n return 0;\n\n if (pos > entry.end)\n return entry.end - entry.start;\n\n return pos - entry.start;\n}\n\nbool BigArchive::eof(const BigEntry &entry) {\n if (&entry != currentEntry)\n return true;\n\n uint32_t cpos = ftell(file);\n return cpos < entry.start || cpos >= entry.end;\n}\n\nbool BigArchive::extract(const BigEntry& entry, const string &directory, bool fullPath, bool ignore, bool overwrite) {\n if (!openEntry(entry)) {\n Log::error(\"Error opening entry \\\"%s\\\"!\", entry.filename);\n return false;\n }\n\n fs::path path = entry.filename;\n\n path = fs::canonical(fs::path(directory)) \/ (fullPath ? path : path.filename());\n\n fs::create_directories(path.parent_path());\n\n if (fs::exists(path)) {\n \/* The option to ignore existing files takes precedence over overwriting them. *\/\n if (ignore) {\n Log::info(\"Skipping existing file: \\\"%s\\\".\", entry.filename);\n\n return true;\n } else if (!overwrite) {\n character c = 0;\n\n while (c != 'n' && c != 'y') {\n Log::info(\"Overwrite existing file \\\"%s\\\"? [Y\/N]:\", path.generic_string());\n\n c = std::tolower(std::getchar());\n\n if (c == '\\n') continue;\n\n \/* Only take one letter input. *\/\n if (std::getchar() != '\\n') {\n c = 0;\n while(std::getchar() != '\\n') continue;\n }\n }\n\n if (c == 'n') {\n Log::info(\"Skipping \\\"%s\\\".\", entry.filename);\n\n return true;\n }\n }\n Log::info(\"Overwriting \\\"%s\\\"...\", entry.filename);\n } else {\n Log::info(\"Extracting to \\\"%s\\\"...\", path.generic_string());\n }\n\n FILE* out = fopen(path.generic_string().c_str(), \"wb\");\n\n if (out == nullptr) {\n Log::error(\"Unable to create file \\\"%s\\\"!\", path.generic_string());\n return false;\n }\n uint32_t length = entry.end - entry.start;\n uint8_t *buffer = new uint8_t[length];\n\n fread(buffer, 1, length, file);\n fwrite(buffer, 1, length, out);\n\n fclose(out);\n delete[] buffer;\n\n Log::info(\"File successfully extracted.\");\n\n return true;\n}\n\nbool BigArchive::extractAll(const string &directory, bool ignore, bool overwrite) {\n fs::create_directories(fs::path(directory));\n\n for (auto &entry : entries)\n if (!extract(entry, directory, true, ignore, overwrite))\n return false;\n\n return true;\n}\n\nbool BigArchive::writeBig(const EntryList& entries, const string& filename) {\n Log::info(\"Preparing to write %d files to \\\"%s\\\"\", entries.size(), filename);\n\n \/* 8 bytes for every entry + 20 at the start and end. *\/\n uint32_t headerLength = uint32_t(entries.size() * 8) + 20;\n\n \/* Add the length of the filenames to headerLength. *\/\n for (auto &entry : entries)\n headerLength += uint32_t(entry.filename.size()) + 1;\n\n Log::info(\"Calculated header length: %#08x\", headerLength);\n\n FILE* file = fopen(filename.c_str(), \"wb\");\n\n if (file == nullptr) {\n Log::error(\"Unable to open \\\"%s\\\" for writing!\", filename);\n return false;\n }\n\n \/* Either that or \"BIG4\". I'm not sure which... *\/\n fwrite(\"BIGF\", 1, 4, file);\n\n writeUInt32(file, 0);\n\n \/* General info about the file. *\/\n writeUInt32(file, uint32_t(entries.size()));\n writeUInt32(file, headerLength);\n\n \/* Put the first file one byte after the end of the header. *\/\n uint32_t lastEnd = headerLength + 1;\n\n \/* Write all the file information. *\/\n for (auto &entry : entries) {\n uint32_t fileLength = entry.end - entry.start;\n writeUInt32(file, lastEnd);\n writeUInt32(file, fileLength);\n\n Log::info(\"Writing header for \\\"%s\\\". Start: %#08x Length: %#08x\", entry.filename, lastEnd, fileLength);\n\n \/* Write the filename and terminating null character. *\/\n fputs(entry.filename.c_str(), file);\n fputc('\\0', file);\n\n \/* So we know where the next file will be written. *\/\n lastEnd += fileLength;\n }\n\n \/* What exactly is this? *\/\n fputs(\"L253\", file);\n\n if (uint32_t(ftell(file)) != headerLength) {\n Log::error(\"Calculated header length was incorrect! Calculated: %#08x Got: %#08x\", headerLength, ftell(file));\n return false;\n }\n\n \/* One more byte until where we start the first file... *\/\n fputc('\\0', file);\n\n \/* Write all the files. *\/\n for (auto &entry : entries) {\n Log::info(\"Writing file \\\"%s\\\".\", entry.filename);\n entry.seek(0);\n\n for (character c; !entry.eof();) {\n c = entry.getChar();\n fwrite(&c, sizeof(character), 1, file);\n }\n }\n\n fclose(file);\n\n Log::info(\"Finished writing to \\\"%s\\\".\", filename);\n\n return true;\n}\n\nbool BigArchive::writeBig(const string& filename) {\n \/* We only do this on a folder backend, because why would you do it on a .big? *\/\n if (backend == Folder) {\n return writeBig(entries, filename);\n }\n return false;\n}\n\nBigArchive::EntryList::const_iterator BigArchive::begin() {\n return entries.cbegin();\n}\n\nBigArchive::EntryList::const_iterator BigArchive::end() {\n return entries.cend();\n}\n\n}\n<commit_msg>Fixed getWord() hanging when eof of archive is reached.<commit_after>#include \"bigentry.hpp\"\n#include \"log.hpp\"\n#include <algorithm>\n#include <cstdio>\n#include <cctype>\n\n#include FILESYSTEM_HEADER\nnamespace fs = FILESYSTEM_NAMESPACE;\n\nnamespace OpenBFME {\n\nuint32_t readUInt32(FILE* file){\n uint8_t val[4];\n fread(val, 1, 4, file);\n return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3];\n}\n\nvoid writeUInt32(FILE* file, uint32_t value){\n uint8_t val[] { uint8_t(value >> 24), uint8_t(value >> 16), uint8_t(value >> 8), uint8_t(value) };\n fwrite(val, 1, 4, file);\n}\n\nstring readString(FILE* file, uint32_t limit, char terminator = '\\0'){\n string data;\n while(uint32_t(ftell(file)) < limit){\n character c = fgetc(file);\n if(c == '\\0' || c == terminator || ferror(file) || feof(file)){\n break;\n }\n data += c;\n }\n return data;\n}\n\nBigArchive::BigArchive(const string &filename) : archiveFilename(fs::path(filename).generic_string()), file(nullptr) { }\n\nBigArchive::~BigArchive() {\n close();\n}\n\nbool BigArchive::readHeader() {\n if (fs::is_directory(fs::path(archiveFilename))) {\n backend = Folder;\n \n \/* Make sure the archiveFilename ends with a '\/' *\/\n if (archiveFilename.back() != '\/')\n archiveFilename += '\/';\n\n for (fs::recursive_directory_iterator dir(archiveFilename), end; dir != end; ++dir) {\n const fs::path& currentPath = dir->path();\n if (fs::is_regular_file(currentPath)) {\n string filename = currentPath.generic_string();\n\n \/* Check to see if the filename contains the parent path, and if so remove it. *\/\n if (filename.compare(0, archiveFilename.size(), archiveFilename, 0, archiveFilename.size()) == 0)\n filename.erase(0, archiveFilename.size());\n else\n \/* Otherwise fall back to removing the first element in the path. *\/\n filename.erase(0, filename.find_first_of('\/') + 1);\n\n uint32_t filesize = uint32_t(fs::file_size(currentPath));\n\n entries.emplace(*this, 0, filesize, filename);\n Log::debug(\"File path: \\\"%s\\\" length: %#08x\", filename, filesize);\n }\n }\n\n return true;\n }\n\n backend = BigFile;\n\n if (!open())\n return false;\n\n \/* The first 4 bytes shoule be either \"BIG4\" or \"BIGF\", quit if they aren't. *\/\n character id[4] = {0};\n fread(id, 1, 4, file);\n\n if (id[0] != 'B' || id[1] != 'I' || id[2] != 'G' || (id[3] != '4' && id[3] != 'F')) {\n Log::error(\"File \\\"%s\\\" is not a valid big file!\");\n close();\n return false;\n }\n\n fseek(file, 8, SEEK_SET);\n\n uint32_t fileCount = readUInt32(file);\n uint32_t headerEnd = readUInt32(file);\n\n Log::info(\"File Count: %u Header End: %#08x\", fileCount, headerEnd);\n\n \/* Read the individual file information into entries. *\/\n for (uint32_t f = 0; f < fileCount; ++f) {\n uint32_t start = readUInt32(file);\n uint32_t end = start + readUInt32(file);\n string path = readString(file, headerEnd);\n std::replace(path.begin(), path.end(), '\\\\', '\/');\n\n entries.emplace(*this, start, end, path);\n\n Log::debug(\"File #%04d start: %#08x end: %#08x path: \\\"%s\\\"\", f + 1, start, end, path);\n }\n\n if (uint32_t(ftell(file)) > headerEnd)\n Log::warning(\"Reading of file info passed through end of header.\");\n\n return true;\n}\n\nbool BigArchive::open() {\n \/* File is already open. *\/\n if (file != nullptr)\n return true;\n\n \/* If it's a .big archive we can try to open the file here. *\/\n if (backend == BigFile)\n file = fopen(archiveFilename.c_str(), \"rb\");\n\n return file != nullptr;\n}\n\nvoid BigArchive::close() {\n if (file != nullptr) {\n fclose(file);\n file = nullptr;\n }\n currentEntry = nullptr;\n}\n\nbool BigArchive::openEntry(const BigEntry& entry) {\n entry.resetLineNumber();\n\n switch (backend) {\n case BigFile:\n if (open()) {\n fseek(file, entry.start, SEEK_SET);\n currentEntry = &entry;\n return true;\n }\n break;\n case Folder:\n close();\n file = fopen((archiveFilename + '\/' + entry.filename).c_str(), \"rb\");\n if (file != nullptr) {\n currentEntry = &entry;\n return true;\n }\n break;\n }\n return false;\n}\n\nconst BigEntry* BigArchive::openFile(const string &filename) {\n \/* Find an entry with the filename. *\/\n auto entry = std::find_if(begin(), end(), [&](const BigEntry& it){ return it.filename == filename; });\n\n \/* If one was found, open it and return it's address. *\/\n if (entry != end() && openEntry(*entry))\n return &(*entry);\n\n \/* Nothing was found, or it failed to open. *\/\n return nullptr;\n}\n\ncharacter BigArchive::getChar(const BigEntry &entry) {\n \/* The archive needs to be open, and we need to be inside the correct file. *\/\n if (!open() || eof(entry))\n return 0;\n\n character ch = fgetc(file);\n\n \/* Tell the entry we have a newline. *\/\n if (ch == '\\n')\n entry.incrementLineNumber();\n\n return ch;\n}\n\nvoid BigArchive::ungetChar(const BigEntry &entry, character c) {\n if (tell(entry) > 0) {\n ungetc(c, file);\n\n \/* If it was a newline we need the line number to go back to how it was before getting the character. *\/\n if (c == '\\n')\n entry.decrementLineNumber();\n }\n}\n\nbool BigArchive::seek(const BigEntry &entry, uint32_t pos) {\n \/* If the entry isn't the current one try opening it. *\/\n if (&entry != currentEntry && !openEntry(entry))\n return false;\n\n \/* Invalidate the stored current line number. *\/\n entry.invalidateLineNumber();\n\n pos += entry.start;\n\n \/* Make sure it's inside the file before seeking. *\/\n if (pos < entry.end) {\n fseek(file, pos, SEEK_SET);\n return true;\n }\n return false;\n}\n\nuint32_t BigArchive::tell(const BigEntry &entry) {\n \/* This only works if the file is already current. *\/\n if (&entry != currentEntry)\n return 0;\n\n uint32_t pos = ftell(file);\n if (pos <= entry.start)\n return 0;\n\n if (pos > entry.end)\n return entry.end - entry.start;\n\n return pos - entry.start;\n}\n\nbool BigArchive::eof(const BigEntry &entry) {\n if (&entry != currentEntry || feof(file))\n return true;\n\n uint32_t cpos = ftell(file);\n return cpos < entry.start || cpos >= entry.end;\n}\n\nbool BigArchive::extract(const BigEntry& entry, const string &directory, bool fullPath, bool ignore, bool overwrite) {\n if (!openEntry(entry)) {\n Log::error(\"Error opening entry \\\"%s\\\"!\", entry.filename);\n return false;\n }\n\n fs::path path = entry.filename;\n\n path = fs::canonical(fs::path(directory)) \/ (fullPath ? path : path.filename());\n\n fs::create_directories(path.parent_path());\n\n if (fs::exists(path)) {\n \/* The option to ignore existing files takes precedence over overwriting them. *\/\n if (ignore) {\n Log::info(\"Skipping existing file: \\\"%s\\\".\", entry.filename);\n\n return true;\n } else if (!overwrite) {\n character c = 0;\n\n while (c != 'n' && c != 'y') {\n Log::info(\"Overwrite existing file \\\"%s\\\"? [Y\/N]:\", path.generic_string());\n\n c = std::tolower(std::getchar());\n\n if (c == '\\n') continue;\n\n \/* Only take one letter input. *\/\n if (std::getchar() != '\\n') {\n c = 0;\n while(std::getchar() != '\\n') continue;\n }\n }\n\n if (c == 'n') {\n Log::info(\"Skipping \\\"%s\\\".\", entry.filename);\n\n return true;\n }\n }\n Log::info(\"Overwriting \\\"%s\\\"...\", entry.filename);\n } else {\n Log::info(\"Extracting to \\\"%s\\\"...\", path.generic_string());\n }\n\n FILE* out = fopen(path.generic_string().c_str(), \"wb\");\n\n if (out == nullptr) {\n Log::error(\"Unable to create file \\\"%s\\\"!\", path.generic_string());\n return false;\n }\n uint32_t length = entry.end - entry.start;\n uint8_t *buffer = new uint8_t[length];\n\n fread(buffer, 1, length, file);\n fwrite(buffer, 1, length, out);\n\n fclose(out);\n delete[] buffer;\n\n Log::info(\"File successfully extracted.\");\n\n return true;\n}\n\nbool BigArchive::extractAll(const string &directory, bool ignore, bool overwrite) {\n fs::create_directories(fs::path(directory));\n\n for (auto &entry : entries)\n if (!extract(entry, directory, true, ignore, overwrite))\n return false;\n\n return true;\n}\n\nbool BigArchive::writeBig(const EntryList& entries, const string& filename) {\n Log::info(\"Preparing to write %d files to \\\"%s\\\"\", entries.size(), filename);\n\n \/* 8 bytes for every entry + 20 at the start and end. *\/\n uint32_t headerLength = uint32_t(entries.size() * 8) + 20;\n\n \/* Add the length of the filenames to headerLength. *\/\n for (auto &entry : entries)\n headerLength += uint32_t(entry.filename.size()) + 1;\n\n Log::info(\"Calculated header length: %#08x\", headerLength);\n\n FILE* file = fopen(filename.c_str(), \"wb\");\n\n if (file == nullptr) {\n Log::error(\"Unable to open \\\"%s\\\" for writing!\", filename);\n return false;\n }\n\n \/* Either that or \"BIG4\". I'm not sure which... *\/\n fwrite(\"BIGF\", 1, 4, file);\n\n writeUInt32(file, 0);\n\n \/* General info about the file. *\/\n writeUInt32(file, uint32_t(entries.size()));\n writeUInt32(file, headerLength);\n\n \/* Put the first file one byte after the end of the header. *\/\n uint32_t lastEnd = headerLength + 1;\n\n \/* Write all the file information. *\/\n for (auto &entry : entries) {\n uint32_t fileLength = entry.end - entry.start;\n writeUInt32(file, lastEnd);\n writeUInt32(file, fileLength);\n\n Log::info(\"Writing header for \\\"%s\\\". Start: %#08x Length: %#08x\", entry.filename, lastEnd, fileLength);\n\n \/* Write the filename and terminating null character. *\/\n fputs(entry.filename.c_str(), file);\n fputc('\\0', file);\n\n \/* So we know where the next file will be written. *\/\n lastEnd += fileLength;\n }\n\n \/* What exactly is this? *\/\n fputs(\"L253\", file);\n\n if (uint32_t(ftell(file)) != headerLength) {\n Log::error(\"Calculated header length was incorrect! Calculated: %#08x Got: %#08x\", headerLength, ftell(file));\n return false;\n }\n\n \/* One more byte until where we start the first file... *\/\n fputc('\\0', file);\n\n \/* Write all the files. *\/\n for (auto &entry : entries) {\n Log::info(\"Writing file \\\"%s\\\".\", entry.filename);\n entry.seek(0);\n\n for (character c; !entry.eof();) {\n c = entry.getChar();\n fwrite(&c, sizeof(character), 1, file);\n }\n }\n\n fclose(file);\n\n Log::info(\"Finished writing to \\\"%s\\\".\", filename);\n\n return true;\n}\n\nbool BigArchive::writeBig(const string& filename) {\n \/* We only do this on a folder backend, because why would you do it on a .big? *\/\n if (backend == Folder) {\n return writeBig(entries, filename);\n }\n return false;\n}\n\nBigArchive::EntryList::const_iterator BigArchive::begin() {\n return entries.cbegin();\n}\n\nBigArchive::EntryList::const_iterator BigArchive::end() {\n return entries.cend();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Certificate Store\n* (C) 1999-2019 Jack Lloyd\n* (C) 2019 René Meusel\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/build.h>\n\n#include <algorithm>\n#include <array>\n\n#define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0\n#include <CoreFoundation\/CoreFoundation.h>\n#include <CoreServices\/CoreServices.h>\n\n#include <botan\/assert.h>\n#include <botan\/ber_dec.h>\n#include <botan\/certstor_macos.h>\n#include <botan\/data_src.h>\n#include <botan\/der_enc.h>\n#include <botan\/exceptn.h>\n#include <botan\/x509_dn.h>\n\nnamespace Botan {\n\nnamespace {\n\n\/**\n * Abstract RAII wrapper for CFTypeRef-style object handles\n * All of those xxxRef types are eventually typedefs to void*\n *\/\ntemplate<typename T>\nclass scoped_CFType\n {\n public:\n explicit scoped_CFType(T value)\n : m_value(value)\n {\n }\n\n scoped_CFType(const scoped_CFType<T>& rhs) = delete;\n scoped_CFType(scoped_CFType<T>&& rhs) :\n m_value(std::move(rhs.m_value))\n {\n rhs.m_value = nullptr;\n }\n\n ~scoped_CFType()\n {\n if(m_value)\n {\n CFRelease(m_value);\n }\n }\n\n operator bool() const { return m_value != nullptr; }\n\n void assign(T value)\n {\n BOTAN_ASSERT(m_value == nullptr, \"scoped_CFType was not set yet\");\n m_value = value;\n }\n\n T& get() { return m_value; }\n const T& get() const { return m_value; }\n\n private:\n T m_value;\n };\n\n\/**\n * Apple's DN parser \"normalizes\" ASN1 'PrintableString' into upper-case values\n * and strips leading, trailing as well as multiple white spaces.\n * See: opensource.apple.com\/source\/Security\/Security-55471\/sec\/Security\/SecCertificate.c.auto.html\n *\/\nX509_DN normalize(const X509_DN& dn)\n {\n X509_DN result;\n\n for(const auto& rdn : dn.dn_info())\n {\n \/\/ TODO: C++14 - use std::get<ASN1_String>(), resp. std::get<OID>()\n const auto oid = rdn.first;\n auto str = rdn.second;\n\n if(str.tagging() == ASN1_Tag::PRINTABLE_STRING)\n {\n std::string normalized;\n normalized.reserve(str.value().size());\n for(const char c : str.value())\n {\n if(c != ' ')\n {\n \/\/ store all 'normal' characters as upper case\n normalized.push_back(::toupper(c));\n }\n else if(!normalized.empty() && normalized.back() != ' ')\n {\n \/\/ remove leading and squash multiple white spaces\n normalized.push_back(c);\n }\n }\n\n if(normalized.back() == ' ')\n {\n \/\/ remove potential remaining single trailing white space char\n normalized.erase(normalized.end() - 1);\n }\n\n str = ASN1_String(normalized, str.tagging());\n }\n\n result.add_attribute(oid, str);\n }\n\n return result;\n }\n\nstd::string to_string(const CFStringRef cfstring)\n {\n const char* ccstr = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);\n\n if(ccstr != nullptr)\n {\n return std::string(ccstr);\n }\n\n auto utf16_pairs = CFStringGetLength(cfstring);\n auto max_utf8_bytes = CFStringGetMaximumSizeForEncoding(utf16_pairs, kCFStringEncodingUTF8);\n\n std::vector<char> cstr(max_utf8_bytes, '\\0');\n auto result = CFStringGetCString(cfstring,\n cstr.data(), cstr.size(),\n kCFStringEncodingUTF8);\n\n return (result) ? std::string(cstr.data()) : std::string();\n }\n\nstd::string to_string(const OSStatus status)\n {\n scoped_CFType<CFStringRef> eCFString(\n SecCopyErrorMessageString(status, nullptr));\n return to_string(eCFString.get());\n }\n\nvoid check_success(const OSStatus status, const std::string context)\n {\n if(errSecSuccess == status)\n {\n return;\n }\n\n throw Internal_Error(\n std::string(\"failed to \" + context + \": \" + to_string(status)));\n }\n\ntemplate <typename T>\nvoid check_notnull(const scoped_CFType<T>& value, const std::string context)\n {\n if(value)\n {\n return;\n }\n\n throw Internal_Error(std::string(\"failed to \") + context);\n }\n\nSecCertificateRef to_SecCertificateRef(CFTypeRef object)\n {\n if(!object || CFGetTypeID(object) != SecCertificateGetTypeID())\n {\n throw Internal_Error(\"cannot convert CFTypeRef to SecCertificateRef\");\n }\n\n return static_cast<SecCertificateRef>(const_cast<void*>(object));\n }\n\n\/**\n * Create a CFDataRef view over some provided std::vector<uint8_t. The data is\n * not copied but the resulting CFDataRef uses the std::vector's buffer as data\n * store. Note that the CFDataRef still needs to be manually freed, hence the\n * scoped_CFType wrapper.\n *\/\nscoped_CFType<CFDataRef> createCFDataView(const std::vector<uint8_t>& data)\n {\n return scoped_CFType<CFDataRef>(\n CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,\n data.data(),\n data.size(),\n kCFAllocatorNull));\n }\n\n\/**\n * Convert a SecCertificateRef object into a Botan::X509_Certificate\n *\/\nstd::shared_ptr<const X509_Certificate> readCertificate(SecCertificateRef cert)\n {\n scoped_CFType<CFDataRef> derData(SecCertificateCopyData(cert));\n check_notnull(derData, \"read extracted certificate\");\n\n \/\/ TODO: factor this out into a createDataSourceView() as soon as this class\n \/\/ gets a move-constructor\n const auto data = CFDataGetBytePtr(derData.get());\n const auto length = CFDataGetLength(derData.get());\n\n DataSource_Memory ds(data, length);\n return std::make_shared<Botan::X509_Certificate>(ds);\n }\n\n}\n\n\/**\n * Internal class implementation (i.e. Pimpl) to keep the required platform-\n * dependent members of Certificate_Store_MacOS contained in this compilation\n * unit.\n *\/\nclass Certificate_Store_MacOS_Impl\n {\n private:\n static constexpr const char* system_roots =\n \"\/System\/Library\/Keychains\/SystemRootCertificates.keychain\";\n static constexpr const char* system_keychain =\n \"\/Library\/Keychains\/System.keychain\";\n\n public:\n using Query = std::vector<std::pair<CFStringRef, CFTypeRef>>;\n\n public:\n Certificate_Store_MacOS_Impl() :\n m_policy(SecPolicyCreateBasicX509()),\n m_system_roots(nullptr),\n m_system_chain(nullptr),\n m_keychains(nullptr)\n {\n check_success(SecKeychainOpen(system_roots, &m_system_roots.get()),\n \"open system root certificates\");\n check_success(SecKeychainOpen(system_keychain, &m_system_chain.get()),\n \"open system keychain\");\n check_notnull(m_system_roots, \"open system root certificate chain\");\n check_notnull(m_system_chain, \"open system certificate chain\");\n\n \/\/ m_keychains is merely a convenience list view into all open keychain\n \/\/ objects. This list is required in prepareQuery().\n std::array<const void*, 2> keychains{{\n m_system_roots.get(),\n m_system_chain.get()\n }};\n\n m_keychains.assign(\n CFArrayCreate(kCFAllocatorDefault,\n keychains.data(),\n keychains.size(),\n &kCFTypeArrayCallBacks));\n check_notnull(m_keychains, \"initialize keychain array\");\n }\n\n CFArrayRef keychains() const { return m_keychains.get(); }\n SecPolicyRef policy() const { return m_policy.get(); }\n\n \/**\n * Searches certificates in all opened system keychains. Takes an optional\n * \\p query that defines filter attributes to be searched for. That query\n * is amended by generic attributes for \"certificate filtering\".\n *\n * \\param query a list of key-value pairs used for filtering\n * \\returns an array with the resulting certificates or nullptr if\n * no matching certificate was found\n *\/\n scoped_CFType<CFArrayRef> search(Query query = Query()) const\n {\n scoped_CFType<CFDictionaryRef> fullQuery(\n prepareQuery(std::move(query)));\n check_notnull(fullQuery, \"create search query\");\n\n scoped_CFType<CFArrayRef> result(nullptr);\n auto status = SecItemCopyMatching(fullQuery.get(),\n (CFTypeRef*)&result.get());\n if(errSecItemNotFound == status)\n {\n return scoped_CFType<CFArrayRef>(nullptr); \/\/ no matches\n }\n\n check_success(status, \"look up certificate\");\n check_notnull(result, \"look up certificate (invalid result value)\");\n\n return result;\n }\n\n protected:\n \/**\n * Amends the user-provided search query with generic filter rules for\n * the associated system keychains.\n *\/\n scoped_CFType<CFDictionaryRef> prepareQuery(Query pairs) const\n {\n std::vector<CFStringRef> keys({kSecClass,\n kSecReturnRef,\n kSecMatchLimit,\n kSecMatchTrustedOnly,\n kSecMatchSearchList,\n kSecMatchPolicy});\n std::vector<CFTypeRef> values({kSecClassCertificate,\n kCFBooleanTrue,\n kSecMatchLimitAll,\n kCFBooleanTrue,\n keychains(),\n policy()});\n keys.reserve(pairs.size() + keys.size());\n values.reserve(pairs.size() + values.size());\n\n for(const auto& pair : pairs)\n {\n keys.push_back(pair.first);\n values.push_back(pair.second);\n }\n\n BOTAN_ASSERT_EQUAL(keys.size(), values.size(), \"valid key-value pairs\");\n\n return scoped_CFType<CFDictionaryRef>(CFDictionaryCreate(\n kCFAllocatorDefault, (const void**)keys.data(),\n (const void**)values.data(), keys.size(),\n &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));\n }\n\n private:\n scoped_CFType<SecPolicyRef> m_policy;\n scoped_CFType<SecKeychainRef> m_system_roots;\n scoped_CFType<SecKeychainRef> m_system_chain;\n scoped_CFType<CFArrayRef> m_keychains;\n };\n\n\nCertificate_Store_MacOS::Certificate_Store_MacOS() :\n m_impl(std::make_shared<Certificate_Store_MacOS_Impl>())\n {\n }\n\nstd::vector<X509_DN> Certificate_Store_MacOS::all_subjects() const\n {\n scoped_CFType<CFArrayRef> result(m_impl->search());\n\n if(!result)\n {\n return {}; \/\/ not a single certificate found in the keychain\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"subject result list contains data\");\n\n std::vector<X509_DN> output;\n output.reserve(count);\n for(unsigned int i = 0; i < count; ++i)\n {\n \/\/ Note: Apple's API provides SecCertificateCopyNormalizedSubjectSequence\n \/\/ which would have saved us from reading a Botan::X509_Certificate,\n \/\/ however, this function applies the same DN \"normalization\" as\n \/\/ stated above.\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), i));\n auto cert = readCertificate(cfCert);\n output.emplace_back(cert->subject_dn());\n }\n\n return output;\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert(const X509_DN& subject_dn,\n const std::vector<uint8_t>& key_id) const\n {\n const auto certs = find_all_certs(subject_dn, key_id);\n\n if(certs.empty())\n {\n return nullptr; \/\/ certificate not found\n }\n\n if(certs.size() != 1)\n {\n throw Lookup_Error(\"ambiguous certificate result\");\n }\n\n return certs.front();\n }\n\nstd::vector<std::shared_ptr<const X509_Certificate>> Certificate_Store_MacOS::find_all_certs(\n const X509_DN& subject_dn,\n const std::vector<uint8_t>& key_id) const\n {\n std::vector<uint8_t> dn_data;\n DER_Encoder encoder(dn_data);\n normalize(subject_dn).encode_into(encoder);\n\n scoped_CFType<CFDataRef> dn_cfdata(createCFDataView(dn_data));\n check_notnull(dn_cfdata, \"create DN search object\");\n\n Certificate_Store_MacOS_Impl::Query query_params(\n {\n {kSecAttrSubject, dn_cfdata.get()}\n });\n\n scoped_CFType<CFDataRef> keyid_cfdata(createCFDataView(key_id));\n check_notnull(keyid_cfdata, \"create key ID search object\");\n if(!key_id.empty())\n {\n query_params.push_back({kSecAttrSubjectKeyID, keyid_cfdata.get()});\n }\n\n scoped_CFType<CFArrayRef> result(m_impl->search(std::move(query_params)));\n\n if(!result)\n {\n return {}; \/\/ no certificates found\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"certificate result list contains data\");\n\n std::vector<std::shared_ptr<const X509_Certificate>> output;\n output.reserve(count);\n for(unsigned int i = 0; i < count; ++i)\n {\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), i));\n output.emplace_back(readCertificate(cfCert));\n }\n\n return output;\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert_by_pubkey_sha1(const std::vector<uint8_t>& key_hash) const\n {\n if(key_hash.size() != 20)\n {\n throw Invalid_Argument(\"Certificate_Store_MacOS::find_cert_by_pubkey_sha1 invalid hash\");\n }\n\n scoped_CFType<CFDataRef> key_hash_cfdata(createCFDataView(key_hash));\n check_notnull(key_hash_cfdata, \"create key hash search object\");\n\n scoped_CFType<CFArrayRef> result(m_impl->search(\n {\n {kSecAttrPublicKeyHash, key_hash_cfdata.get()},\n }));\n\n if(!result)\n {\n return nullptr; \/\/ no certificate found\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"certificate result list contains an object\");\n\n \/\/ `count` might be greater than 1, but we'll just select the first match\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), 0));\n return readCertificate(cfCert);\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256(const std::vector<uint8_t>& subject_hash) const\n {\n BOTAN_UNUSED(subject_hash);\n throw Not_Implemented(\"Certificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256\");\n }\n\nstd::shared_ptr<const X509_CRL> Certificate_Store_MacOS::find_crl_for(const X509_Certificate& subject) const\n {\n BOTAN_UNUSED(subject);\n return {};\n }\n\n}\n<commit_msg>FIX: handle duplicated root certs more graceful<commit_after>\/*\n* Certificate Store\n* (C) 1999-2019 Jack Lloyd\n* (C) 2019 René Meusel\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/build.h>\n\n#include <algorithm>\n#include <array>\n\n#define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0\n#include <CoreFoundation\/CoreFoundation.h>\n#include <CoreServices\/CoreServices.h>\n\n#include <botan\/assert.h>\n#include <botan\/ber_dec.h>\n#include <botan\/certstor_macos.h>\n#include <botan\/data_src.h>\n#include <botan\/der_enc.h>\n#include <botan\/exceptn.h>\n#include <botan\/x509_dn.h>\n\nnamespace Botan {\n\nnamespace {\n\n\/**\n * Abstract RAII wrapper for CFTypeRef-style object handles\n * All of those xxxRef types are eventually typedefs to void*\n *\/\ntemplate<typename T>\nclass scoped_CFType\n {\n public:\n explicit scoped_CFType(T value)\n : m_value(value)\n {\n }\n\n scoped_CFType(const scoped_CFType<T>& rhs) = delete;\n scoped_CFType(scoped_CFType<T>&& rhs) :\n m_value(std::move(rhs.m_value))\n {\n rhs.m_value = nullptr;\n }\n\n ~scoped_CFType()\n {\n if(m_value)\n {\n CFRelease(m_value);\n }\n }\n\n operator bool() const { return m_value != nullptr; }\n\n void assign(T value)\n {\n BOTAN_ASSERT(m_value == nullptr, \"scoped_CFType was not set yet\");\n m_value = value;\n }\n\n T& get() { return m_value; }\n const T& get() const { return m_value; }\n\n private:\n T m_value;\n };\n\n\/**\n * Apple's DN parser \"normalizes\" ASN1 'PrintableString' into upper-case values\n * and strips leading, trailing as well as multiple white spaces.\n * See: opensource.apple.com\/source\/Security\/Security-55471\/sec\/Security\/SecCertificate.c.auto.html\n *\/\nX509_DN normalize(const X509_DN& dn)\n {\n X509_DN result;\n\n for(const auto& rdn : dn.dn_info())\n {\n \/\/ TODO: C++14 - use std::get<ASN1_String>(), resp. std::get<OID>()\n const auto oid = rdn.first;\n auto str = rdn.second;\n\n if(str.tagging() == ASN1_Tag::PRINTABLE_STRING)\n {\n std::string normalized;\n normalized.reserve(str.value().size());\n for(const char c : str.value())\n {\n if(c != ' ')\n {\n \/\/ store all 'normal' characters as upper case\n normalized.push_back(::toupper(c));\n }\n else if(!normalized.empty() && normalized.back() != ' ')\n {\n \/\/ remove leading and squash multiple white spaces\n normalized.push_back(c);\n }\n }\n\n if(normalized.back() == ' ')\n {\n \/\/ remove potential remaining single trailing white space char\n normalized.erase(normalized.end() - 1);\n }\n\n str = ASN1_String(normalized, str.tagging());\n }\n\n result.add_attribute(oid, str);\n }\n\n return result;\n }\n\nstd::string to_string(const CFStringRef cfstring)\n {\n const char* ccstr = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);\n\n if(ccstr != nullptr)\n {\n return std::string(ccstr);\n }\n\n auto utf16_pairs = CFStringGetLength(cfstring);\n auto max_utf8_bytes = CFStringGetMaximumSizeForEncoding(utf16_pairs, kCFStringEncodingUTF8);\n\n std::vector<char> cstr(max_utf8_bytes, '\\0');\n auto result = CFStringGetCString(cfstring,\n cstr.data(), cstr.size(),\n kCFStringEncodingUTF8);\n\n return (result) ? std::string(cstr.data()) : std::string();\n }\n\nstd::string to_string(const OSStatus status)\n {\n scoped_CFType<CFStringRef> eCFString(\n SecCopyErrorMessageString(status, nullptr));\n return to_string(eCFString.get());\n }\n\nvoid check_success(const OSStatus status, const std::string context)\n {\n if(errSecSuccess == status)\n {\n return;\n }\n\n throw Internal_Error(\n std::string(\"failed to \" + context + \": \" + to_string(status)));\n }\n\ntemplate <typename T>\nvoid check_notnull(const scoped_CFType<T>& value, const std::string context)\n {\n if(value)\n {\n return;\n }\n\n throw Internal_Error(std::string(\"failed to \") + context);\n }\n\nSecCertificateRef to_SecCertificateRef(CFTypeRef object)\n {\n if(!object || CFGetTypeID(object) != SecCertificateGetTypeID())\n {\n throw Internal_Error(\"cannot convert CFTypeRef to SecCertificateRef\");\n }\n\n return static_cast<SecCertificateRef>(const_cast<void*>(object));\n }\n\n\/**\n * Create a CFDataRef view over some provided std::vector<uint8_t. The data is\n * not copied but the resulting CFDataRef uses the std::vector's buffer as data\n * store. Note that the CFDataRef still needs to be manually freed, hence the\n * scoped_CFType wrapper.\n *\/\nscoped_CFType<CFDataRef> createCFDataView(const std::vector<uint8_t>& data)\n {\n return scoped_CFType<CFDataRef>(\n CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,\n data.data(),\n data.size(),\n kCFAllocatorNull));\n }\n\n\/**\n * Convert a SecCertificateRef object into a Botan::X509_Certificate\n *\/\nstd::shared_ptr<const X509_Certificate> readCertificate(SecCertificateRef cert)\n {\n scoped_CFType<CFDataRef> derData(SecCertificateCopyData(cert));\n check_notnull(derData, \"read extracted certificate\");\n\n \/\/ TODO: factor this out into a createDataSourceView() as soon as this class\n \/\/ gets a move-constructor\n const auto data = CFDataGetBytePtr(derData.get());\n const auto length = CFDataGetLength(derData.get());\n\n DataSource_Memory ds(data, length);\n return std::make_shared<Botan::X509_Certificate>(ds);\n }\n\n}\n\n\/**\n * Internal class implementation (i.e. Pimpl) to keep the required platform-\n * dependent members of Certificate_Store_MacOS contained in this compilation\n * unit.\n *\/\nclass Certificate_Store_MacOS_Impl\n {\n private:\n static constexpr const char* system_roots =\n \"\/System\/Library\/Keychains\/SystemRootCertificates.keychain\";\n static constexpr const char* system_keychain =\n \"\/Library\/Keychains\/System.keychain\";\n\n public:\n using Query = std::vector<std::pair<CFStringRef, CFTypeRef>>;\n\n public:\n Certificate_Store_MacOS_Impl() :\n m_policy(SecPolicyCreateBasicX509()),\n m_system_roots(nullptr),\n m_system_chain(nullptr),\n m_keychains(nullptr)\n {\n check_success(SecKeychainOpen(system_roots, &m_system_roots.get()),\n \"open system root certificates\");\n check_success(SecKeychainOpen(system_keychain, &m_system_chain.get()),\n \"open system keychain\");\n check_notnull(m_system_roots, \"open system root certificate chain\");\n check_notnull(m_system_chain, \"open system certificate chain\");\n\n \/\/ m_keychains is merely a convenience list view into all open keychain\n \/\/ objects. This list is required in prepareQuery().\n std::array<const void*, 2> keychains{{\n m_system_roots.get(),\n m_system_chain.get()\n }};\n\n m_keychains.assign(\n CFArrayCreate(kCFAllocatorDefault,\n keychains.data(),\n keychains.size(),\n &kCFTypeArrayCallBacks));\n check_notnull(m_keychains, \"initialize keychain array\");\n }\n\n CFArrayRef keychains() const { return m_keychains.get(); }\n SecPolicyRef policy() const { return m_policy.get(); }\n\n \/**\n * Searches certificates in all opened system keychains. Takes an optional\n * \\p query that defines filter attributes to be searched for. That query\n * is amended by generic attributes for \"certificate filtering\".\n *\n * \\param query a list of key-value pairs used for filtering\n * \\returns an array with the resulting certificates or nullptr if\n * no matching certificate was found\n *\/\n scoped_CFType<CFArrayRef> search(Query query = Query()) const\n {\n scoped_CFType<CFDictionaryRef> fullQuery(\n prepareQuery(std::move(query)));\n check_notnull(fullQuery, \"create search query\");\n\n scoped_CFType<CFArrayRef> result(nullptr);\n auto status = SecItemCopyMatching(fullQuery.get(),\n (CFTypeRef*)&result.get());\n if(errSecItemNotFound == status)\n {\n return scoped_CFType<CFArrayRef>(nullptr); \/\/ no matches\n }\n\n check_success(status, \"look up certificate\");\n check_notnull(result, \"look up certificate (invalid result value)\");\n\n return result;\n }\n\n protected:\n \/**\n * Amends the user-provided search query with generic filter rules for\n * the associated system keychains.\n *\/\n scoped_CFType<CFDictionaryRef> prepareQuery(Query pairs) const\n {\n std::vector<CFStringRef> keys({kSecClass,\n kSecReturnRef,\n kSecMatchLimit,\n kSecMatchTrustedOnly,\n kSecMatchSearchList,\n kSecMatchPolicy});\n std::vector<CFTypeRef> values({kSecClassCertificate,\n kCFBooleanTrue,\n kSecMatchLimitAll,\n kCFBooleanTrue,\n keychains(),\n policy()});\n keys.reserve(pairs.size() + keys.size());\n values.reserve(pairs.size() + values.size());\n\n for(const auto& pair : pairs)\n {\n keys.push_back(pair.first);\n values.push_back(pair.second);\n }\n\n BOTAN_ASSERT_EQUAL(keys.size(), values.size(), \"valid key-value pairs\");\n\n return scoped_CFType<CFDictionaryRef>(CFDictionaryCreate(\n kCFAllocatorDefault, (const void**)keys.data(),\n (const void**)values.data(), keys.size(),\n &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));\n }\n\n private:\n scoped_CFType<SecPolicyRef> m_policy;\n scoped_CFType<SecKeychainRef> m_system_roots;\n scoped_CFType<SecKeychainRef> m_system_chain;\n scoped_CFType<CFArrayRef> m_keychains;\n };\n\n\nCertificate_Store_MacOS::Certificate_Store_MacOS() :\n m_impl(std::make_shared<Certificate_Store_MacOS_Impl>())\n {\n }\n\nstd::vector<X509_DN> Certificate_Store_MacOS::all_subjects() const\n {\n scoped_CFType<CFArrayRef> result(m_impl->search());\n\n if(!result)\n {\n return {}; \/\/ not a single certificate found in the keychain\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"subject result list contains data\");\n\n std::vector<X509_DN> output;\n output.reserve(count);\n for(unsigned int i = 0; i < count; ++i)\n {\n \/\/ Note: Apple's API provides SecCertificateCopyNormalizedSubjectSequence\n \/\/ which would have saved us from reading a Botan::X509_Certificate,\n \/\/ however, this function applies the same DN \"normalization\" as\n \/\/ stated above.\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), i));\n auto cert = readCertificate(cfCert);\n output.emplace_back(cert->subject_dn());\n }\n\n return output;\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert(const X509_DN& subject_dn,\n const std::vector<uint8_t>& key_id) const\n {\n const auto certs = find_all_certs(subject_dn, key_id);\n\n if(certs.empty())\n {\n return nullptr; \/\/ certificate not found\n }\n\n \/\/ `count` might be greater than 1, but we'll just select the first match\n return certs.front();\n }\n\nstd::vector<std::shared_ptr<const X509_Certificate>> Certificate_Store_MacOS::find_all_certs(\n const X509_DN& subject_dn,\n const std::vector<uint8_t>& key_id) const\n {\n std::vector<uint8_t> dn_data;\n DER_Encoder encoder(dn_data);\n normalize(subject_dn).encode_into(encoder);\n\n scoped_CFType<CFDataRef> dn_cfdata(createCFDataView(dn_data));\n check_notnull(dn_cfdata, \"create DN search object\");\n\n Certificate_Store_MacOS_Impl::Query query_params(\n {\n {kSecAttrSubject, dn_cfdata.get()}\n });\n\n scoped_CFType<CFDataRef> keyid_cfdata(createCFDataView(key_id));\n check_notnull(keyid_cfdata, \"create key ID search object\");\n if(!key_id.empty())\n {\n query_params.push_back({kSecAttrSubjectKeyID, keyid_cfdata.get()});\n }\n\n scoped_CFType<CFArrayRef> result(m_impl->search(std::move(query_params)));\n\n if(!result)\n {\n return {}; \/\/ no certificates found\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"certificate result list contains data\");\n\n std::vector<std::shared_ptr<const X509_Certificate>> output;\n output.reserve(count);\n for(unsigned int i = 0; i < count; ++i)\n {\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), i));\n output.emplace_back(readCertificate(cfCert));\n }\n\n return output;\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert_by_pubkey_sha1(const std::vector<uint8_t>& key_hash) const\n {\n if(key_hash.size() != 20)\n {\n throw Invalid_Argument(\"Certificate_Store_MacOS::find_cert_by_pubkey_sha1 invalid hash\");\n }\n\n scoped_CFType<CFDataRef> key_hash_cfdata(createCFDataView(key_hash));\n check_notnull(key_hash_cfdata, \"create key hash search object\");\n\n scoped_CFType<CFArrayRef> result(m_impl->search(\n {\n {kSecAttrPublicKeyHash, key_hash_cfdata.get()},\n }));\n\n if(!result)\n {\n return nullptr; \/\/ no certificate found\n }\n\n const auto count = CFArrayGetCount(result.get());\n BOTAN_ASSERT(count > 0, \"certificate result list contains an object\");\n\n \/\/ `count` might be greater than 1, but we'll just select the first match\n auto cfCert = to_SecCertificateRef(CFArrayGetValueAtIndex(result.get(), 0));\n return readCertificate(cfCert);\n }\n\nstd::shared_ptr<const X509_Certificate>\nCertificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256(const std::vector<uint8_t>& subject_hash) const\n {\n BOTAN_UNUSED(subject_hash);\n throw Not_Implemented(\"Certificate_Store_MacOS::find_cert_by_raw_subject_dn_sha256\");\n }\n\nstd::shared_ptr<const X509_CRL> Certificate_Store_MacOS::find_crl_for(const X509_Certificate& subject) const\n {\n BOTAN_UNUSED(subject);\n return {};\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <cstdlib>\n#include <sstream>\n\n#include <transport\/THttpClient.h>\n#include <transport\/TSocket.h>\n\nnamespace apache { namespace thrift { namespace transport {\n\nusing namespace std;\n\nTHttpClient::THttpClient(boost::shared_ptr<TTransport> transport, std::string host, std::string path) :\n THttpTransport(transport), host_(host), path_(path) {\n}\n\nTHttpClient::THttpClient(string host, int port, string path) :\n THttpTransport(boost::shared_ptr<TTransport>(new TSocket(host, port))), host_(host), path_(path) {\n}\n\nTHttpClient::~THttpClient() {}\n\nvoid THttpClient::parseHeader(char* header) {\n char* colon = strchr(header, ':');\n if (colon == NULL) {\n return;\n }\n uint32_t sz = colon - header;\n char* value = colon+1;\n\n if (strncmp(header, \"Transfer-Encoding\", sz) == 0) {\n if (strstr(value, \"chunked\") != NULL) {\n chunked_ = true;\n }\n } else if (strncmp(header, \"Content-Length\", sz) == 0) {\n chunked_ = false;\n contentLength_ = atoi(value);\n }\n}\n\nbool THttpClient::parseStatusLine(char* status) {\n char* http = status;\n\n char* code = strchr(http, ' ');\n if (code == NULL) {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n\n *code = '\\0';\n while (*(code++) == ' ') {};\n\n char* msg = strchr(code, ' ');\n if (msg == NULL) {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n *msg = '\\0';\n\n if (strcmp(code, \"200\") == 0) {\n \/\/ HTTP 200 = OK, we got the response\n return true;\n } else if (strcmp(code, \"100\") == 0) {\n \/\/ HTTP 100 = continue, just keep reading\n return false;\n } else {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n}\n\nvoid THttpClient::flush() {\n \/\/ Fetch the contents of the write buffer\n uint8_t* buf;\n uint32_t len;\n writeBuffer_.getBuffer(&buf, &len);\n\n \/\/ Construct the HTTP header\n std::ostringstream h;\n h <<\n \"POST \" << path_ << \" HTTP\/1.1\" << CRLF <<\n \"Host: \" << host_ << CRLF <<\n \"Content-Type: application\/x-thrift\" << CRLF <<\n \"Content-Length: \" << len << CRLF <<\n \"Accept: application\/x-thrift\" << CRLF <<\n \"User-Agent: Thrift\/\" << VERSION << \" (C++\/THttpClient)\" << CRLF <<\n CRLF;\n string header = h.str();\n\n \/\/ Write the header, then the data, then flush\n transport_->write((const uint8_t*)header.c_str(), header.size());\n transport_->write(buf, len);\n transport_->flush();\n\n \/\/ Reset the buffer and header variables\n writeBuffer_.resetBuffer();\n readHeaders_ = true;\n}\n\n}}} \/\/ apache::thrift::transport\n<commit_msg>THRIFT-1030 C++ THttpTransport doesn't support chucked transfer encoding Patch: Rowan Kerr<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <cstdlib>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include <transport\/THttpClient.h>\n#include <transport\/TSocket.h>\n\nnamespace apache { namespace thrift { namespace transport {\n\nusing namespace std;\n\nTHttpClient::THttpClient(boost::shared_ptr<TTransport> transport, std::string host, std::string path) :\n THttpTransport(transport), host_(host), path_(path) {\n}\n\nTHttpClient::THttpClient(string host, int port, string path) :\n THttpTransport(boost::shared_ptr<TTransport>(new TSocket(host, port))), host_(host), path_(path) {\n}\n\nTHttpClient::~THttpClient() {}\n\nvoid THttpClient::parseHeader(char* header) {\n char* colon = strchr(header, ':');\n if (colon == NULL) {\n return;\n }\n uint32_t sz = colon - header;\n char* value = colon+1;\n\n if (boost::istarts_with(header, \"Transfer-Encoding\")) {\n if (boost::iends_with(value, \"chunked\")) {\n chunked_ = true;\n }\n } else if (boost::istarts_with(header, \"Content-Length\")) { \n chunked_ = false;\n contentLength_ = atoi(value);\n }\n}\n\nbool THttpClient::parseStatusLine(char* status) {\n char* http = status;\n\n char* code = strchr(http, ' ');\n if (code == NULL) {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n\n *code = '\\0';\n while (*(code++) == ' ') {};\n\n char* msg = strchr(code, ' ');\n if (msg == NULL) {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n *msg = '\\0';\n\n if (strcmp(code, \"200\") == 0) {\n \/\/ HTTP 200 = OK, we got the response\n return true;\n } else if (strcmp(code, \"100\") == 0) {\n \/\/ HTTP 100 = continue, just keep reading\n return false;\n } else {\n throw TTransportException(string(\"Bad Status: \") + status);\n }\n}\n\nvoid THttpClient::flush() {\n \/\/ Fetch the contents of the write buffer\n uint8_t* buf;\n uint32_t len;\n writeBuffer_.getBuffer(&buf, &len);\n\n \/\/ Construct the HTTP header\n std::ostringstream h;\n h <<\n \"POST \" << path_ << \" HTTP\/1.1\" << CRLF <<\n \"Host: \" << host_ << CRLF <<\n \"Content-Type: application\/x-thrift\" << CRLF <<\n \"Content-Length: \" << len << CRLF <<\n \"Accept: application\/x-thrift\" << CRLF <<\n \"User-Agent: Thrift\/\" << VERSION << \" (C++\/THttpClient)\" << CRLF <<\n CRLF;\n string header = h.str();\n\n \/\/ Write the header, then the data, then flush\n transport_->write((const uint8_t*)header.c_str(), header.size());\n transport_->write(buf, len);\n transport_->flush();\n\n \/\/ Reset the buffer and header variables\n writeBuffer_.resetBuffer();\n readHeaders_ = true;\n}\n\n}}} \/\/ apache::thrift::transport\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <iostream>\n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\nint main(){\n auto dataset = icdar::read_2013_dataset(\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 1, 1);\n\n if(dataset.training_labels.empty() || dataset.training_images.empty()){\n std::cout << \"Problem while reading the dataset\" << std::endl;\n\n return -1;\n }\n\n std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n for(auto& image : dataset.training_images){\n std::vector<std::vector<uint8_t>> windows;\n\n std::cout << image.width << \"x\" << image.height << std::endl;\n\n for(std::size_t i = context; i < image.width - context; ++i){\n for(std::size_t j = context; j < image.height - context; ++j){\n\n windows.emplace_back(window * window);\n\n \/\/std::cout << i << \":\" << j << std::endl;\n\n for(std::size_t a = i - context; a < i - context + window; ++a){\n for(std::size_t b = j - context; b <= j - context + window; ++b){\n \/\/std::cout << a << \"<->\" << b << std::endl;\n \/\/std::cout << ((a * image.height) + b) << std::endl;\n \/\/std::cout << ((i -context + a) * window + (j - context + b)) << std::endl;\n windows.back().at((i - context + a) * window + (j - context + b)) = 1;\/\/image.pixels.at(a * image.height + b).r;\n }\n }\n\n }\n }\n\n }\n\n return 0;\n}\n<commit_msg>Finish window extraction<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <iostream>\n\n#include \"icdar\/icdar_reader.hpp\"\n\nconstexpr const std::size_t context = 5;\nconstexpr const std::size_t window = context * 2 + 1;\n\nint main(){\n auto dataset = icdar::read_2013_dataset(\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/train\",\n \"\/home\/wichtounet\/datasets\/icdar_2013_natural\/test\", 5, 1);\n\n if(dataset.training_labels.empty() || dataset.training_images.empty()){\n std::cout << \"Problem while reading the dataset\" << std::endl;\n\n return -1;\n }\n\n std::cout << dataset.training_images.size() << \" training images\" << std::endl;\n std::cout << dataset.test_images.size() << \" test images\" << std::endl;\n\n for(auto& image : dataset.training_images){\n std::vector<std::vector<uint8_t>> windows;\n windows.reserve(image.width * image.height);\n\n for(std::size_t i = context; i < image.width - context; ++i){\n for(std::size_t j = context; j < image.height - context; ++j){\n\n windows.emplace_back(window * window);\n\n for(std::size_t a = i - context; a < i - context + window; ++a){\n for(std::size_t b = j - context; b < j - context + window; ++b){\n auto w_i = (a - (i - context));\n auto w_j = (b - (j - context));\n windows.back().at(w_i * window + w_j) = image.pixels.at(a * image.height + b).r;\n }\n }\n }\n }\n\n std::cout << windows.size() << \" windows extracted\" << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: hldoctp.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: hr $ $Date: 2003-04-04 18:01:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"hyperdlg.hxx\"\n\n#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX\n#include <unotools\/localfilehelper.hxx>\n#endif\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n\n#include \"hldoctp.hxx\"\n#include \"hyperdlg.hrc\"\n\nsal_Char __READONLY_DATA sHash[] = \"#\";\nsal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME;\nsal_Char __READONLY_DATA sPortalFileScheme[] = \"vnd.sun.star.wfs:\/\/\";\nsal_Char __READONLY_DATA sNewsSRVScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\nsal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet)\n: maGrpDocument ( this, ResId (GRP_DOCUMENT) ),\n maFtPath ( this, ResId (FT_PATH_DOC) ),\n maCbbPath ( this, INET_PROT_FILE ),\n maBtFileopen ( this, ResId (BTN_FILEOPEN) ),\n maGrpTarget ( this, ResId (GRP_TARGET) ),\n maFtTarget ( this, ResId (FT_TARGET_DOC) ),\n maEdTarget ( this, ResId (ED_TARGET_DOC) ),\n maFtURL ( this, ResId (FT_URL) ),\n maFtFullURL ( this, ResId (FT_FULL_URL) ),\n maBtBrowse ( this, ResId (BTN_BROWSE) ),\n mbMarkWndOpen ( FALSE ),\n SvxHyperlinkTabPageBase ( pParent, SVX_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet )\n{\n \/\/ Set HC bitmaps and disable display of bitmap names.\n maBtBrowse.SetModeImage( Image( ResId( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtBrowse.EnableTextDisplay (FALSE);\n maBtFileopen.SetModeImage( Image( ResId( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtFileopen.EnableTextDisplay (FALSE);\n\n InitStdControls();\n FreeResource();\n\n \/\/ Init URL-Box (pos&size, Open-Handler)\n maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ),\n LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) );\n maCbbPath.Show();\n String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US );\n maCbbPath.SetBaseURL(aFileScheme);\n maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH );\n\n SetExchangeSupport ();\n\n \/\/ overload handlers\n maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) );\n maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) );\n maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) );\n maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) );\n\n maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) );\n\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkDocTp::~SvxHyperlinkDocTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL )\n{\n INetURLObject aURL ( aStrURL );\n String aStrScheme;\n\n \/\/ set protocoll-radiobuttons\n INetProtocol aProtocol = aURL.GetProtocol();\n switch ( aProtocol )\n {\n case INET_PROT_FILE :\n case INET_PROT_VND_SUN_STAR_WFS :\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( sFileScheme ) );\n break;\n case INET_PROT_POP3 :\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( INET_POP3_SCHEME ) );\n break;\n case INET_PROT_IMAP :\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( INET_IMAP_SCHEME ) );\n break;\n case INET_PROT_OUT :\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( INET_OUT_SCHEME ) );\n break;\n default :\n if ( aStrURL.SearchAscii( sNewsSRVScheme ) == 0 )\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( sNewsSRVScheme ) );\n else if( aStrURL.SearchAscii( sHash ) == 0 )\n aStrScheme.AssignAscii( RTL_CONSTASCII_STRINGPARAM ( sFileScheme ) );\n }\n\n if ( aStrScheme != aEmptyStr )\n {\n String aStrMark;\n\n xub_StrLen nPos = aStrURL.SearchAscii( sHash );\n \/\/ path\n maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) );\n\n \/\/ set target in document at editfield\n if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 )\n aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() );\n maEdTarget.SetText ( aStrMark );\n }\n else\n {\n maCbbPath.SetText ( aEmptyStr );\n maEdTarget.SetText ( aEmptyStr );\n }\n\n ModifiedPathHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve current url-string\n|*\n|************************************************************************\/\n\nString SvxHyperlinkDocTp::GetCurrentURL ()\n{\n \/\/ get data from dialog-controls\n String aStrURL;\n String aStrPath ( maCbbPath.GetText() );\n const String aBaseURL ( maCbbPath.GetBaseURL() );\n String aStrMark( maEdTarget.GetText() );\n\n if ( aStrPath != aEmptyStr )\n {\n INetURLObject aURL( aStrPath );\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) \/\/ maybe the path is already a valid\n aStrURL = aStrPath; \/\/ hyperlink, then we can use this path directly\n else\n utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL );\n\n if ( aStrMark != aEmptyStr )\n {\n aStrURL.AppendAscii( \"#\" );\n aStrURL += aStrMark;\n }\n\n \/\/ if there is a empty string, the url will be the html-scheme\n \/\/ but its better to show only the file-scheme\n\n if ( aStrURL.SearchAscii( sHTTPScheme ) == 0 )\n {\n aStrURL.Erase( 0, UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM ( sHTTPScheme ) ).Len() );\n String aStrTmp( aStrURL );\n aStrURL.AssignAscii( sHTTPScheme );\n aStrURL += aStrTmp;\n }\n }\n else\n if( aStrMark != aEmptyStr )\n {\n aStrURL.AssignAscii( sHash );\n aStrURL += aStrMark;\n }\n\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName,\n String& aStrIntName, String& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n \/\/ get data from standard-fields\n aStrURL = GetCurrentURL();\n\n if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n aStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n aStrURL=aEmptyStr;\n\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkDocTp( pWindow, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetInitFocus()\n{\n maCbbPath.GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : fileopen\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG )\n{\n \/\/ Open Fileopen-Dialog\n ::sfx2::FileDialogHelper aDlg( ::sfx2::FILEOPEN_SIMPLE, 0, GetParent() );\n String aOldURL( GetCurrentURL() );\n if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) ||\n aOldURL.EqualsIgnoreCaseAscii( sPortalFileScheme, 0, sizeof( sFileScheme ) - 1 ) )\n {\n aDlg.SetDisplayDirectory( aOldURL );\n }\n\n if ( aDlg.Execute() == ERRCODE_NONE )\n {\n String aURL( aDlg.GetPath() );\n String aPath;\n\n utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath );\n\n maCbbPath.SetBaseURL( aURL );\n maCbbPath.SetText( aPath );\n\n if ( aOldURL != GetCurrentURL() )\n ModifiedPathHdl_Impl (NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : target\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG )\n{\n if ( GetPathType ( maStrURL ) == Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ||\n maStrURL.SearchAscii( sHash ) == 0 )\n {\n mpMarkWnd->SetError( LERR_NOERROR );\n\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n\n ShowMarkWnd ();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of combobox \"Path\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If path-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG )\n{\n if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) )\n {\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n if ( IsMarkWndVisible() )\n mpMarkWnd->SelectEntry ( maEdTarget.GetText() );\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* editfield \"Target\" lost focus\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maFtFullURL.SetText( maStrURL );\n\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark )\n{\n maEdTarget.SetText ( aStrMark );\n\n ModifiedTargetHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve kind of pathstr\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath )\n{\n BOOL bExists = FALSE;\n INetURLObject aURL( aStrPath, INET_PROT_FILE );\n\n if( aURL.HasError() )\n return Type_Invalid;\n else\n return Type_ExistsFile;\n\n return Type_Unknown;\n}\n<commit_msg>INTEGRATION: CWS draw9 (1.15.2.1.66); FILE MERGED 2003\/04\/14 15:48:56 af 1.15.2.1.66.2: RESYNC: (1.16-1.17); FILE MERGED 2003\/03\/25 20:30:57 iha 1.15.2.1.66.1: #105788# create links also from invalid urls<commit_after>\/*************************************************************************\n *\n * $RCSfile: hldoctp.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: rt $ $Date: 2003-04-24 14:46:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"hyperdlg.hxx\"\n\n#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX\n#include <unotools\/localfilehelper.hxx>\n#endif\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n\n#include \"hldoctp.hxx\"\n#include \"hyperdlg.hrc\"\n\nsal_Char __READONLY_DATA sHash[] = \"#\";\nsal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME;\nsal_Char __READONLY_DATA sPortalFileScheme[] = \"vnd.sun.star.wfs:\/\/\";\nsal_Char __READONLY_DATA sNewsSRVScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\nsal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet)\n: maGrpDocument ( this, ResId (GRP_DOCUMENT) ),\n maFtPath ( this, ResId (FT_PATH_DOC) ),\n maCbbPath ( this, INET_PROT_FILE ),\n maBtFileopen ( this, ResId (BTN_FILEOPEN) ),\n maGrpTarget ( this, ResId (GRP_TARGET) ),\n maFtTarget ( this, ResId (FT_TARGET_DOC) ),\n maEdTarget ( this, ResId (ED_TARGET_DOC) ),\n maFtURL ( this, ResId (FT_URL) ),\n maFtFullURL ( this, ResId (FT_FULL_URL) ),\n maBtBrowse ( this, ResId (BTN_BROWSE) ),\n mbMarkWndOpen ( FALSE ),\n SvxHyperlinkTabPageBase ( pParent, SVX_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet )\n{\n \/\/ Set HC bitmaps and disable display of bitmap names.\n maBtBrowse.SetModeImage( Image( ResId( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtBrowse.EnableTextDisplay (FALSE);\n maBtFileopen.SetModeImage( Image( ResId( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtFileopen.EnableTextDisplay (FALSE);\n\n InitStdControls();\n FreeResource();\n\n \/\/ Init URL-Box (pos&size, Open-Handler)\n maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ),\n LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) );\n maCbbPath.Show();\n String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US );\n maCbbPath.SetBaseURL(aFileScheme);\n maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH );\n\n SetExchangeSupport ();\n\n \/\/ overload handlers\n maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) );\n maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) );\n maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) );\n maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) );\n\n maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) );\n\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkDocTp::~SvxHyperlinkDocTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL )\n{\n INetURLObject aURL ( aStrURL );\n\n String aStrMark;\n xub_StrLen nPos = aStrURL.SearchAscii( sHash );\n \/\/ path\n maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) );\n\n \/\/ set target in document at editfield\n if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 )\n aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() );\n maEdTarget.SetText ( aStrMark );\n\n ModifiedPathHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve current url-string\n|*\n|************************************************************************\/\n\nString SvxHyperlinkDocTp::GetCurrentURL ()\n{\n \/\/ get data from dialog-controls\n String aStrURL;\n String aStrPath ( maCbbPath.GetText() );\n const String aBaseURL ( maCbbPath.GetBaseURL() );\n String aStrMark( maEdTarget.GetText() );\n\n if ( aStrPath != aEmptyStr )\n {\n INetURLObject aURL( aStrPath );\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) \/\/ maybe the path is already a valid\n aStrURL = aStrPath; \/\/ hyperlink, then we can use this path directly\n else\n utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL );\n\n \/\/#105788# always create a URL even if it is not valid\n if( aStrURL == aEmptyStr )\n aStrURL = aStrPath;\n }\n\n if( aStrMark != aEmptyStr )\n {\n aStrURL.AssignAscii( sHash );\n aStrURL += aStrMark;\n }\n\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName,\n String& aStrIntName, String& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n \/\/ get data from standard-fields\n aStrURL = GetCurrentURL();\n\n if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n aStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n aStrURL=aEmptyStr;\n\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkDocTp( pWindow, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetInitFocus()\n{\n maCbbPath.GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : fileopen\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG )\n{\n \/\/ Open Fileopen-Dialog\n ::sfx2::FileDialogHelper aDlg( ::sfx2::FILEOPEN_SIMPLE, 0, GetParent() );\n String aOldURL( GetCurrentURL() );\n if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) ||\n aOldURL.EqualsIgnoreCaseAscii( sPortalFileScheme, 0, sizeof( sFileScheme ) - 1 ) )\n {\n aDlg.SetDisplayDirectory( aOldURL );\n }\n\n if ( aDlg.Execute() == ERRCODE_NONE )\n {\n String aURL( aDlg.GetPath() );\n String aPath;\n\n utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath );\n\n maCbbPath.SetBaseURL( aURL );\n maCbbPath.SetText( aPath );\n\n if ( aOldURL != GetCurrentURL() )\n ModifiedPathHdl_Impl (NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : target\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG )\n{\n if ( GetPathType ( maStrURL ) == Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ||\n maStrURL.SearchAscii( sHash ) == 0 )\n {\n mpMarkWnd->SetError( LERR_NOERROR );\n\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n\n ShowMarkWnd ();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of combobox \"Path\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If path-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG )\n{\n if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) )\n {\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n if ( IsMarkWndVisible() )\n mpMarkWnd->SelectEntry ( maEdTarget.GetText() );\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* editfield \"Target\" lost focus\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maFtFullURL.SetText( maStrURL );\n\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark )\n{\n maEdTarget.SetText ( aStrMark );\n\n ModifiedTargetHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve kind of pathstr\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath )\n{\n BOOL bExists = FALSE;\n INetURLObject aURL( aStrPath, INET_PROT_FILE );\n\n if( aURL.HasError() )\n return Type_Invalid;\n else\n return Type_ExistsFile;\n\n return Type_Unknown;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: langbox.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-23 16:38:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HDL_\n#include <com\/sun\/star\/linguistic2\/XLinguServiceManager.hdl>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XAVAILABLELOCALES_HPP_\n#include <com\/sun\/star\/linguistic2\/XAvailableLocales.hpp>\n#endif\n#ifndef _LINGUISTIC_MISC_HXX_\n#include <linguistic\/misc.hxx>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include<rtl\/ustring.hxx>\n#endif\n\n#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX\n#include <unotools\/localedatawrapper.hxx>\n#endif\n\n#include <svtools\/langtab.hxx>\n\n#ifndef _SHL_HXX\n#include <tools\/shl.hxx>\n#endif\n#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX\n#include <i18npool\/mslangid.hxx>\n#endif\n#ifndef INCLUDED_I18NPOOL_LANG_H\n#include <i18npool\/lang.h>\n#endif\n#ifndef _SVX_SCRIPTTYPEITEM_HXX\n#include <svx\/scripttypeitem.hxx>\n#endif\n#ifndef _UNO_LINGU_HXX\n#include <unolingu.hxx>\n#endif\n#include <svx\/langbox.hxx>\n#include <svx\/dialmgr.hxx>\n#include <svx\/dialogs.hrc>\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::linguistic2;\nusing namespace ::com::sun::star::uno;\n\n\n\/\/========================================================================\n\/\/ misc local helper functions\n\/\/========================================================================\n\n\n\nstatic Sequence< INT16 > lcl_LocaleSeqToLangSeq( Sequence< Locale > &rSeq )\n{\n const Locale *pLocale = rSeq.getConstArray();\n INT32 nCount = rSeq.getLength();\n\n Sequence< INT16 > aLangs( nCount );\n INT16 *pLang = aLangs.getArray();\n for (INT32 i = 0; i < nCount; ++i)\n {\n pLang[i] = SvxLocaleToLanguage( pLocale[i] );\n\n }\n\n return aLangs;\n}\n\n\nstatic BOOL lcl_SeqHasLang( const Sequence< INT16 > & rLangSeq, INT16 nLang )\n{\n INT32 i = -1;\n INT32 nLen = rLangSeq.getLength();\n if (nLen)\n {\n const INT16 *pLang = rLangSeq.getConstArray();\n for (i = 0; i < nLen; ++i)\n {\n if (nLang == pLang[i])\n break;\n }\n }\n return i >= 0 && i < nLen;\n}\n\n\/\/========================================================================\n\/\/ class SvxLanguageBox\n\/\/========================================================================\n\nUSHORT TypeToPos_Impl( LanguageType eType, const ListBox& rLb )\n{\n USHORT nPos = LISTBOX_ENTRY_NOTFOUND;\n USHORT nCount = rLb.GetEntryCount();\n\n for ( USHORT i=0; nPos == LISTBOX_ENTRY_NOTFOUND && i<nCount; i++ )\n if ( eType == LanguageType((ULONG)rLb.GetEntryData(i)) )\n nPos = i;\n\n return nPos;\n}\n\n\/\/-----------------------------------------------------------------------\nSvxLanguageBox::SvxLanguageBox( Window* pParent, WinBits nWinStyle, BOOL bCheck ) :\n ListBox( pParent, nWinStyle ),\n m_pSpellUsedLang( NULL ),\n m_bWithCheckmark( bCheck )\n{\n Init();\n}\n\/\/------------------------------------------------------------------------\nSvxLanguageBox::SvxLanguageBox( Window* pParent, const ResId& rResId, BOOL bCheck ) :\n ListBox( pParent, rResId ),\n m_pSpellUsedLang( NULL ),\n m_bWithCheckmark( bCheck )\n{\n Init();\n}\n\/\/------------------------------------------------------------------------\nvoid SvxLanguageBox::Init()\n{\n m_pLangTable = new SvtLanguageTable;\n m_aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );\n m_aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );\n m_aCheckedImageHC = Image( SVX_RES( RID_SVXIMG_CHECKED_H ) );\n m_aAllString = String( SVX_RESSTR( RID_SVXSTR_LANGUAGE_ALL ) );\n m_nLangList = LANG_LIST_EMPTY;\n m_bHasLangNone = FALSE;\n m_bLangNoneIsLangAll = FALSE;\n\n \/\/ display entries sorted\n SetStyle( GetStyle() | WB_SORT );\n\n if ( m_bWithCheckmark )\n {\n SvtLanguageTable aLangTable;\n sal_uInt32 nCount = aLangTable.GetEntryCount();\n for ( sal_uInt32 i = 0; i < nCount; i++ )\n {\n LanguageType nLangType = aLangTable.GetTypeAtIndex( i );\n\n BOOL bInsert = TRUE;\n if ((LANGUAGE_DONTKNOW == nLangType) ||\n (LANGUAGE_SYSTEM == nLangType) ||\n (LANGUAGE_USER1 <= nLangType && nLangType <= LANGUAGE_USER9))\n {\n bInsert = FALSE;\n }\n\n if ( bInsert )\n InsertLanguage( nLangType );\n }\n m_nLangList = LANG_LIST_ALL;\n }\n}\n\/\/------------------------------------------------------------------------\n\nSvxLanguageBox::~SvxLanguageBox()\n{\n delete m_pSpellUsedLang;\n delete m_pLangTable;\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::ImplInsertImgEntry( const String& rEntry, USHORT nPos, bool bChecked )\n{\n USHORT nRet = 0;\n if( !bChecked )\n nRet = InsertEntry( rEntry, m_aNotCheckedImage, nPos );\n else if( GetSettings().GetStyleSettings().GetFaceColor().IsDark() )\n nRet = InsertEntry( rEntry, m_aCheckedImageHC, nPos );\n else\n nRet = InsertEntry( rEntry, m_aCheckedImage, nPos );\n return nRet;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::SetLanguageList( INT16 nLangList,\n BOOL bHasLangNone, BOOL bLangNoneIsLangAll, BOOL bCheckSpellAvail )\n{\n Clear();\n\n m_nLangList = nLangList;\n m_bHasLangNone = bHasLangNone;\n m_bLangNoneIsLangAll = bLangNoneIsLangAll;\n m_bWithCheckmark = bCheckSpellAvail;\n\n if ( LANG_LIST_EMPTY != nLangList )\n {\n Sequence< INT16 > aSpellAvailLang;\n Sequence< INT16 > aHyphAvailLang;\n Sequence< INT16 > aThesAvailLang;\n Sequence< INT16 > aSpellUsedLang;\n Sequence< INT16 > aHyphUsedLang;\n Sequence< INT16 > aThesUsedLang;\n Reference< XAvailableLocales > xAvail( LinguMgr::GetLngSvcMgr(), UNO_QUERY );\n if (xAvail.is())\n {\n Sequence< Locale > aTmp;\n\n if (LANG_LIST_SPELL_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_SPELLCHECKER ) );\n aSpellAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n if (LANG_LIST_HYPH_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_HYPHENATOR ) );\n aHyphAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n if (LANG_LIST_THES_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_THESAURUS ) );\n aThesAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n }\n if (LANG_LIST_SPELL_USED & nLangList)\n {\n Reference< XSpellChecker1 > xTmp1( SvxGetSpellChecker(), UNO_QUERY );\n if (xTmp1.is())\n aSpellUsedLang = xTmp1->getLanguages();\n }\n if (LANG_LIST_HYPH_USED & nLangList)\n {\n Reference< XHyphenator > xTmp( SvxGetHyphenator() );\n if (xTmp.is()) {\n Sequence < Locale > aLocaleSequence( xTmp->getLocales() );\n aHyphUsedLang = lcl_LocaleSeqToLangSeq( aLocaleSequence );\n }\n }\n if (LANG_LIST_THES_USED & nLangList)\n {\n Reference< XThesaurus > xTmp( SvxGetThesaurus() );\n if (xTmp.is()) {\n Sequence < Locale > aLocaleSequence( xTmp->getLocales() );\n aThesUsedLang = lcl_LocaleSeqToLangSeq( aLocaleSequence );\n }\n }\n\n SvtLanguageTable aLangTable;\n ::com::sun::star::uno::Sequence< sal_uInt16 > xKnown;\n const sal_uInt16* pKnown;\n sal_uInt32 nCount;\n if ( nLangList & LANG_LIST_ONLY_KNOWN )\n {\n xKnown = LocaleDataWrapper::getInstalledLanguageTypes();\n pKnown = xKnown.getConstArray();\n nCount = xKnown.getLength();\n }\n else\n {\n nCount = aLangTable.GetEntryCount();\n pKnown = NULL;\n }\n for ( sal_uInt32 i = 0; i < nCount; i++ )\n {\n LanguageType nLangType;\n if ( nLangList & LANG_LIST_ONLY_KNOWN )\n nLangType = pKnown[i];\n else\n nLangType = aLangTable.GetTypeAtIndex( i );\n if ( nLangType != LANGUAGE_DONTKNOW &&\n nLangType != LANGUAGE_SYSTEM &&\n nLangType != LANGUAGE_NONE &&\n (nLangType < LANGUAGE_USER1 || nLangType > LANGUAGE_USER9) &&\n ((nLangList & LANG_LIST_ALL) != 0 ||\n ((nLangList & LANG_LIST_WESTERN) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_LATIN)) ||\n ((nLangList & LANG_LIST_CTL) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_COMPLEX)) ||\n ((nLangList & LANG_LIST_CJK) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_ASIAN)) ||\n ((nLangList & LANG_LIST_FBD_CHARS) != 0 &&\n MsLangId::hasForbiddenCharacters(nLangType)) ||\n ((nLangList & LANG_LIST_SPELL_AVAIL) != 0 &&\n lcl_SeqHasLang(aSpellAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_HYPH_AVAIL) != 0 &&\n lcl_SeqHasLang(aHyphAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_THES_AVAIL) != 0 &&\n lcl_SeqHasLang(aThesAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_SPELL_USED) != 0 &&\n lcl_SeqHasLang(aSpellUsedLang, nLangType)) ||\n ((nLangList & LANG_LIST_HYPH_USED) != 0 &&\n lcl_SeqHasLang(aHyphUsedLang, nLangType)) ||\n ((nLangList & LANG_LIST_THES_USED) != 0 &&\n lcl_SeqHasLang(aThesUsedLang, nLangType))) )\n InsertLanguage( nLangType );\n }\n\n if (bHasLangNone)\n InsertLanguage( LANGUAGE_NONE );\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::InsertLanguage( const LanguageType nLangType, USHORT nPos )\n{\n String aStrEntry = m_pLangTable->GetString( nLangType );\n if (LANGUAGE_NONE == nLangType && m_bHasLangNone && m_bLangNoneIsLangAll)\n aStrEntry = m_aAllString;\n\n USHORT nAt = 0;\n if ( m_bWithCheckmark )\n {\n sal_Bool bFound = sal_False;\n\n if (!m_pSpellUsedLang)\n {\n Reference< XSpellChecker1 > xSpell( SvxGetSpellChecker(), UNO_QUERY );\n if ( xSpell.is() )\n m_pSpellUsedLang = new Sequence< INT16 >( xSpell->getLanguages() );\n }\n bFound = m_pSpellUsedLang ?\n lcl_SeqHasLang( *m_pSpellUsedLang, nLangType ) : FALSE;\n\n nAt = ImplInsertImgEntry( aStrEntry, nPos, bFound );\n }\n else\n nAt = InsertEntry( aStrEntry, nPos );\n\n SetEntryData( nAt, (void*)(ULONG)nLangType );\n return nAt;\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::InsertLanguage( const LanguageType nLangType,\n BOOL bCheckEntry, USHORT nPos )\n{\n String aStrEntry = m_pLangTable->GetString( nLangType );\n if (LANGUAGE_NONE == nLangType && m_bHasLangNone && m_bLangNoneIsLangAll)\n aStrEntry = m_aAllString;\n\n USHORT nAt = ImplInsertImgEntry( aStrEntry, nPos, bCheckEntry );\n SetEntryData( nAt, (void*)(ULONG)nLangType );\n\n return nAt;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::RemoveLanguage( const LanguageType eLangType )\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n RemoveEntry( nAt );\n}\n\n\/\/------------------------------------------------------------------------\n\nLanguageType SvxLanguageBox::GetSelectLanguage() const\n{\n USHORT nPos = GetSelectEntryPos();\n\n if ( nPos != LISTBOX_ENTRY_NOTFOUND )\n return LanguageType( (ULONG)GetEntryData(nPos) );\n else\n return LanguageType( LANGUAGE_DONTKNOW );\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::SelectLanguage( const LanguageType eLangType, BOOL bSelect )\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n SelectEntryPos( nAt, bSelect );\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL SvxLanguageBox::IsLanguageSelected( const LanguageType eLangType ) const\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n return IsEntryPosSelected( nAt );\n else\n return FALSE;\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.23.196); FILE MERGED 2008\/04\/01 15:50:23 thb 1.23.196.3: #i85898# Stripping all external header guards 2008\/04\/01 12:48:15 thb 1.23.196.2: #i85898# Stripping all external header guards 2008\/03\/31 14:19:30 rt 1.23.196.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: langbox.cxx,v $\n * $Revision: 1.24 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HDL_\n#include <com\/sun\/star\/linguistic2\/XLinguServiceManager.hdl>\n#endif\n#include <com\/sun\/star\/linguistic2\/XAvailableLocales.hpp>\n#include <linguistic\/misc.hxx>\n#include<rtl\/ustring.hxx>\n#include <unotools\/localedatawrapper.hxx>\n\n#include <svtools\/langtab.hxx>\n#include <tools\/shl.hxx>\n#include <i18npool\/mslangid.hxx>\n#include <i18npool\/lang.h>\n#include <svx\/scripttypeitem.hxx>\n#include <unolingu.hxx>\n#include <svx\/langbox.hxx>\n#include <svx\/dialmgr.hxx>\n#include <svx\/dialogs.hrc>\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::linguistic2;\nusing namespace ::com::sun::star::uno;\n\n\n\/\/========================================================================\n\/\/ misc local helper functions\n\/\/========================================================================\n\n\n\nstatic Sequence< INT16 > lcl_LocaleSeqToLangSeq( Sequence< Locale > &rSeq )\n{\n const Locale *pLocale = rSeq.getConstArray();\n INT32 nCount = rSeq.getLength();\n\n Sequence< INT16 > aLangs( nCount );\n INT16 *pLang = aLangs.getArray();\n for (INT32 i = 0; i < nCount; ++i)\n {\n pLang[i] = SvxLocaleToLanguage( pLocale[i] );\n\n }\n\n return aLangs;\n}\n\n\nstatic BOOL lcl_SeqHasLang( const Sequence< INT16 > & rLangSeq, INT16 nLang )\n{\n INT32 i = -1;\n INT32 nLen = rLangSeq.getLength();\n if (nLen)\n {\n const INT16 *pLang = rLangSeq.getConstArray();\n for (i = 0; i < nLen; ++i)\n {\n if (nLang == pLang[i])\n break;\n }\n }\n return i >= 0 && i < nLen;\n}\n\n\/\/========================================================================\n\/\/ class SvxLanguageBox\n\/\/========================================================================\n\nUSHORT TypeToPos_Impl( LanguageType eType, const ListBox& rLb )\n{\n USHORT nPos = LISTBOX_ENTRY_NOTFOUND;\n USHORT nCount = rLb.GetEntryCount();\n\n for ( USHORT i=0; nPos == LISTBOX_ENTRY_NOTFOUND && i<nCount; i++ )\n if ( eType == LanguageType((ULONG)rLb.GetEntryData(i)) )\n nPos = i;\n\n return nPos;\n}\n\n\/\/-----------------------------------------------------------------------\nSvxLanguageBox::SvxLanguageBox( Window* pParent, WinBits nWinStyle, BOOL bCheck ) :\n ListBox( pParent, nWinStyle ),\n m_pSpellUsedLang( NULL ),\n m_bWithCheckmark( bCheck )\n{\n Init();\n}\n\/\/------------------------------------------------------------------------\nSvxLanguageBox::SvxLanguageBox( Window* pParent, const ResId& rResId, BOOL bCheck ) :\n ListBox( pParent, rResId ),\n m_pSpellUsedLang( NULL ),\n m_bWithCheckmark( bCheck )\n{\n Init();\n}\n\/\/------------------------------------------------------------------------\nvoid SvxLanguageBox::Init()\n{\n m_pLangTable = new SvtLanguageTable;\n m_aNotCheckedImage = Image( SVX_RES( RID_SVXIMG_NOTCHECKED ) );\n m_aCheckedImage = Image( SVX_RES( RID_SVXIMG_CHECKED ) );\n m_aCheckedImageHC = Image( SVX_RES( RID_SVXIMG_CHECKED_H ) );\n m_aAllString = String( SVX_RESSTR( RID_SVXSTR_LANGUAGE_ALL ) );\n m_nLangList = LANG_LIST_EMPTY;\n m_bHasLangNone = FALSE;\n m_bLangNoneIsLangAll = FALSE;\n\n \/\/ display entries sorted\n SetStyle( GetStyle() | WB_SORT );\n\n if ( m_bWithCheckmark )\n {\n SvtLanguageTable aLangTable;\n sal_uInt32 nCount = aLangTable.GetEntryCount();\n for ( sal_uInt32 i = 0; i < nCount; i++ )\n {\n LanguageType nLangType = aLangTable.GetTypeAtIndex( i );\n\n BOOL bInsert = TRUE;\n if ((LANGUAGE_DONTKNOW == nLangType) ||\n (LANGUAGE_SYSTEM == nLangType) ||\n (LANGUAGE_USER1 <= nLangType && nLangType <= LANGUAGE_USER9))\n {\n bInsert = FALSE;\n }\n\n if ( bInsert )\n InsertLanguage( nLangType );\n }\n m_nLangList = LANG_LIST_ALL;\n }\n}\n\/\/------------------------------------------------------------------------\n\nSvxLanguageBox::~SvxLanguageBox()\n{\n delete m_pSpellUsedLang;\n delete m_pLangTable;\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::ImplInsertImgEntry( const String& rEntry, USHORT nPos, bool bChecked )\n{\n USHORT nRet = 0;\n if( !bChecked )\n nRet = InsertEntry( rEntry, m_aNotCheckedImage, nPos );\n else if( GetSettings().GetStyleSettings().GetFaceColor().IsDark() )\n nRet = InsertEntry( rEntry, m_aCheckedImageHC, nPos );\n else\n nRet = InsertEntry( rEntry, m_aCheckedImage, nPos );\n return nRet;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::SetLanguageList( INT16 nLangList,\n BOOL bHasLangNone, BOOL bLangNoneIsLangAll, BOOL bCheckSpellAvail )\n{\n Clear();\n\n m_nLangList = nLangList;\n m_bHasLangNone = bHasLangNone;\n m_bLangNoneIsLangAll = bLangNoneIsLangAll;\n m_bWithCheckmark = bCheckSpellAvail;\n\n if ( LANG_LIST_EMPTY != nLangList )\n {\n Sequence< INT16 > aSpellAvailLang;\n Sequence< INT16 > aHyphAvailLang;\n Sequence< INT16 > aThesAvailLang;\n Sequence< INT16 > aSpellUsedLang;\n Sequence< INT16 > aHyphUsedLang;\n Sequence< INT16 > aThesUsedLang;\n Reference< XAvailableLocales > xAvail( LinguMgr::GetLngSvcMgr(), UNO_QUERY );\n if (xAvail.is())\n {\n Sequence< Locale > aTmp;\n\n if (LANG_LIST_SPELL_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_SPELLCHECKER ) );\n aSpellAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n if (LANG_LIST_HYPH_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_HYPHENATOR ) );\n aHyphAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n if (LANG_LIST_THES_AVAIL & nLangList)\n {\n aTmp = xAvail->getAvailableLocales( A2OU( SN_THESAURUS ) );\n aThesAvailLang = lcl_LocaleSeqToLangSeq( aTmp );\n }\n }\n if (LANG_LIST_SPELL_USED & nLangList)\n {\n Reference< XSpellChecker1 > xTmp1( SvxGetSpellChecker(), UNO_QUERY );\n if (xTmp1.is())\n aSpellUsedLang = xTmp1->getLanguages();\n }\n if (LANG_LIST_HYPH_USED & nLangList)\n {\n Reference< XHyphenator > xTmp( SvxGetHyphenator() );\n if (xTmp.is()) {\n Sequence < Locale > aLocaleSequence( xTmp->getLocales() );\n aHyphUsedLang = lcl_LocaleSeqToLangSeq( aLocaleSequence );\n }\n }\n if (LANG_LIST_THES_USED & nLangList)\n {\n Reference< XThesaurus > xTmp( SvxGetThesaurus() );\n if (xTmp.is()) {\n Sequence < Locale > aLocaleSequence( xTmp->getLocales() );\n aThesUsedLang = lcl_LocaleSeqToLangSeq( aLocaleSequence );\n }\n }\n\n SvtLanguageTable aLangTable;\n ::com::sun::star::uno::Sequence< sal_uInt16 > xKnown;\n const sal_uInt16* pKnown;\n sal_uInt32 nCount;\n if ( nLangList & LANG_LIST_ONLY_KNOWN )\n {\n xKnown = LocaleDataWrapper::getInstalledLanguageTypes();\n pKnown = xKnown.getConstArray();\n nCount = xKnown.getLength();\n }\n else\n {\n nCount = aLangTable.GetEntryCount();\n pKnown = NULL;\n }\n for ( sal_uInt32 i = 0; i < nCount; i++ )\n {\n LanguageType nLangType;\n if ( nLangList & LANG_LIST_ONLY_KNOWN )\n nLangType = pKnown[i];\n else\n nLangType = aLangTable.GetTypeAtIndex( i );\n if ( nLangType != LANGUAGE_DONTKNOW &&\n nLangType != LANGUAGE_SYSTEM &&\n nLangType != LANGUAGE_NONE &&\n (nLangType < LANGUAGE_USER1 || nLangType > LANGUAGE_USER9) &&\n ((nLangList & LANG_LIST_ALL) != 0 ||\n ((nLangList & LANG_LIST_WESTERN) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_LATIN)) ||\n ((nLangList & LANG_LIST_CTL) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_COMPLEX)) ||\n ((nLangList & LANG_LIST_CJK) != 0 &&\n (SvtLanguageOptions::GetScriptTypeOfLanguage(nLangType) ==\n SCRIPTTYPE_ASIAN)) ||\n ((nLangList & LANG_LIST_FBD_CHARS) != 0 &&\n MsLangId::hasForbiddenCharacters(nLangType)) ||\n ((nLangList & LANG_LIST_SPELL_AVAIL) != 0 &&\n lcl_SeqHasLang(aSpellAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_HYPH_AVAIL) != 0 &&\n lcl_SeqHasLang(aHyphAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_THES_AVAIL) != 0 &&\n lcl_SeqHasLang(aThesAvailLang, nLangType)) ||\n ((nLangList & LANG_LIST_SPELL_USED) != 0 &&\n lcl_SeqHasLang(aSpellUsedLang, nLangType)) ||\n ((nLangList & LANG_LIST_HYPH_USED) != 0 &&\n lcl_SeqHasLang(aHyphUsedLang, nLangType)) ||\n ((nLangList & LANG_LIST_THES_USED) != 0 &&\n lcl_SeqHasLang(aThesUsedLang, nLangType))) )\n InsertLanguage( nLangType );\n }\n\n if (bHasLangNone)\n InsertLanguage( LANGUAGE_NONE );\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::InsertLanguage( const LanguageType nLangType, USHORT nPos )\n{\n String aStrEntry = m_pLangTable->GetString( nLangType );\n if (LANGUAGE_NONE == nLangType && m_bHasLangNone && m_bLangNoneIsLangAll)\n aStrEntry = m_aAllString;\n\n USHORT nAt = 0;\n if ( m_bWithCheckmark )\n {\n sal_Bool bFound = sal_False;\n\n if (!m_pSpellUsedLang)\n {\n Reference< XSpellChecker1 > xSpell( SvxGetSpellChecker(), UNO_QUERY );\n if ( xSpell.is() )\n m_pSpellUsedLang = new Sequence< INT16 >( xSpell->getLanguages() );\n }\n bFound = m_pSpellUsedLang ?\n lcl_SeqHasLang( *m_pSpellUsedLang, nLangType ) : FALSE;\n\n nAt = ImplInsertImgEntry( aStrEntry, nPos, bFound );\n }\n else\n nAt = InsertEntry( aStrEntry, nPos );\n\n SetEntryData( nAt, (void*)(ULONG)nLangType );\n return nAt;\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT SvxLanguageBox::InsertLanguage( const LanguageType nLangType,\n BOOL bCheckEntry, USHORT nPos )\n{\n String aStrEntry = m_pLangTable->GetString( nLangType );\n if (LANGUAGE_NONE == nLangType && m_bHasLangNone && m_bLangNoneIsLangAll)\n aStrEntry = m_aAllString;\n\n USHORT nAt = ImplInsertImgEntry( aStrEntry, nPos, bCheckEntry );\n SetEntryData( nAt, (void*)(ULONG)nLangType );\n\n return nAt;\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::RemoveLanguage( const LanguageType eLangType )\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n RemoveEntry( nAt );\n}\n\n\/\/------------------------------------------------------------------------\n\nLanguageType SvxLanguageBox::GetSelectLanguage() const\n{\n USHORT nPos = GetSelectEntryPos();\n\n if ( nPos != LISTBOX_ENTRY_NOTFOUND )\n return LanguageType( (ULONG)GetEntryData(nPos) );\n else\n return LanguageType( LANGUAGE_DONTKNOW );\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid SvxLanguageBox::SelectLanguage( const LanguageType eLangType, BOOL bSelect )\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n SelectEntryPos( nAt, bSelect );\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL SvxLanguageBox::IsLanguageSelected( const LanguageType eLangType ) const\n{\n USHORT nAt = TypeToPos_Impl( eLangType, *this );\n\n if ( nAt != LISTBOX_ENTRY_NOTFOUND )\n return IsEntryPosSelected( nAt );\n else\n return FALSE;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: zoomitem.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 08:34:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef __SBX_SBXVARIABLE_HXX\n#include <basic\/sbxvar.hxx>\n#endif\n#pragma hdrstop\n\n#include \"zoomitem.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\nTYPEINIT1_AUTOFACTORY(SvxZoomItem,SfxUInt16Item);\n\n#define ZOOM_PARAM_VALUE \"Value\"\n#define ZOOM_PARAM_VALUESET \"ValueSet\"\n#define ZOOM_PARAM_TYPE \"Type\"\n#define ZOOM_PARAMS 3\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::SvxZoomItem\n(\n SvxZoomType eZoomType,\n sal_uInt16 nVal,\n sal_uInt16 nWhich\n)\n: SfxUInt16Item( nWhich, nVal ),\n nValueSet( SVX_ZOOM_ENABLE_ALL ),\n eType( eZoomType )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )\n: SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),\n nValueSet( rOrig.GetValueSet() ),\n eType( rOrig.GetType() )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::~SvxZoomItem()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxZoomItem::Clone( SfxItemPool *pPool ) const\n{\n return new SvxZoomItem( *this );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 nVersion ) const\n{\n sal_uInt16 nValue;\n sal_uInt16 nValSet;\n sal_Int8 nType;\n rStrm >> nValue >> nValSet >> nType;\n SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );\n pNew->SetValueSet( nValSet );\n return pNew;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 nItemVersion ) const\n{\n rStrm << (sal_uInt16)GetValue()\n << nValueSet\n << (sal_Int8)eType;\n return rStrm;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n SvxZoomItem& rItem = (SvxZoomItem&)rAttr;\n\n return ( GetValue() == rItem.GetValue() &&\n nValueSet == rItem.GetValueSet() &&\n eType == rItem.GetType() );\n}\n\nsal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const\n{\n sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);\n nMemberId &= ~CONVERT_TWIPS;\n switch ( nMemberId )\n {\n case 0 :\n {\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );\n aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));\n aSeq[0].Value <<= sal_Int32( GetValue() );\n aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));\n aSeq[1].Value <<= sal_Int16( nValueSet );\n aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));\n aSeq[2].Value <<= sal_Int16( eType );\n rVal <<= aSeq;\n }\n break;\n\n case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;\n case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;\n case MID_TYPE: rVal <<= (sal_Int16) eType; break;\n default: DBG_ERROR(\"Wrong MemberId!\"); return sal_False;\n }\n\n return sal_True;\n}\n\nsal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )\n{\n sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);\n nMemberId &= ~CONVERT_TWIPS;\n switch ( nMemberId )\n {\n case 0 :\n {\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;\n if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))\n {\n sal_Int32 nValueTmp( 0 );\n sal_Int16 nValueSetTmp( 0 );\n sal_Int16 nTypeTmp( 0 );\n sal_Bool bAllConverted( sal_True );\n sal_Int16 nConvertedCount( 0 );\n for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )\n {\n if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nValueTmp );\n ++nConvertedCount;\n }\n else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );\n ++nConvertedCount;\n }\n else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );\n ++nConvertedCount;\n }\n }\n\n if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )\n {\n SetValue( nValueTmp );\n nValueSet = nValueSetTmp;\n eType = SvxZoomType( nTypeTmp );\n return sal_True;\n }\n }\n\n return sal_False;\n }\n break;\n\n case MID_VALUE:\n {\n sal_Int32 nVal;\n if ( rVal >>= nVal )\n {\n SetValue( nVal );\n return sal_True;\n }\n else\n return sal_False;\n }\n break;\n\n case MID_VALUESET:\n case MID_TYPE:\n {\n sal_Int16 nVal;\n if ( rVal >>= nVal )\n {\n if ( nMemberId == MID_VALUESET )\n nValueSet = (sal_Int16) nVal;\n else if ( nMemberId == MID_TYPE )\n eType = SvxZoomType( (sal_Int16) nVal );\n return sal_True;\n }\n else\n return sal_False;\n }\n break;\n\n default: DBG_ERROR(\"Wrong MemberId!\"); return sal_False;\n }\n\n return sal_True;\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.218); FILE MERGED 2005\/09\/05 14:25:51 rt 1.5.218.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zoomitem.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:42:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef __SBX_SBXVARIABLE_HXX\n#include <basic\/sbxvar.hxx>\n#endif\n#pragma hdrstop\n\n#include \"zoomitem.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\nTYPEINIT1_AUTOFACTORY(SvxZoomItem,SfxUInt16Item);\n\n#define ZOOM_PARAM_VALUE \"Value\"\n#define ZOOM_PARAM_VALUESET \"ValueSet\"\n#define ZOOM_PARAM_TYPE \"Type\"\n#define ZOOM_PARAMS 3\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::SvxZoomItem\n(\n SvxZoomType eZoomType,\n sal_uInt16 nVal,\n sal_uInt16 nWhich\n)\n: SfxUInt16Item( nWhich, nVal ),\n nValueSet( SVX_ZOOM_ENABLE_ALL ),\n eType( eZoomType )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )\n: SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),\n nValueSet( rOrig.GetValueSet() ),\n eType( rOrig.GetType() )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvxZoomItem::~SvxZoomItem()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxZoomItem::Clone( SfxItemPool *pPool ) const\n{\n return new SvxZoomItem( *this );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 nVersion ) const\n{\n sal_uInt16 nValue;\n sal_uInt16 nValSet;\n sal_Int8 nType;\n rStrm >> nValue >> nValSet >> nType;\n SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );\n pNew->SetValueSet( nValSet );\n return pNew;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 nItemVersion ) const\n{\n rStrm << (sal_uInt16)GetValue()\n << nValueSet\n << (sal_Int8)eType;\n return rStrm;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n SvxZoomItem& rItem = (SvxZoomItem&)rAttr;\n\n return ( GetValue() == rItem.GetValue() &&\n nValueSet == rItem.GetValueSet() &&\n eType == rItem.GetType() );\n}\n\nsal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const\n{\n sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);\n nMemberId &= ~CONVERT_TWIPS;\n switch ( nMemberId )\n {\n case 0 :\n {\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );\n aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));\n aSeq[0].Value <<= sal_Int32( GetValue() );\n aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));\n aSeq[1].Value <<= sal_Int16( nValueSet );\n aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));\n aSeq[2].Value <<= sal_Int16( eType );\n rVal <<= aSeq;\n }\n break;\n\n case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;\n case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;\n case MID_TYPE: rVal <<= (sal_Int16) eType; break;\n default: DBG_ERROR(\"Wrong MemberId!\"); return sal_False;\n }\n\n return sal_True;\n}\n\nsal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )\n{\n sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);\n nMemberId &= ~CONVERT_TWIPS;\n switch ( nMemberId )\n {\n case 0 :\n {\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;\n if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))\n {\n sal_Int32 nValueTmp( 0 );\n sal_Int16 nValueSetTmp( 0 );\n sal_Int16 nTypeTmp( 0 );\n sal_Bool bAllConverted( sal_True );\n sal_Int16 nConvertedCount( 0 );\n for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )\n {\n if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nValueTmp );\n ++nConvertedCount;\n }\n else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );\n ++nConvertedCount;\n }\n else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))\n {\n bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );\n ++nConvertedCount;\n }\n }\n\n if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )\n {\n SetValue( nValueTmp );\n nValueSet = nValueSetTmp;\n eType = SvxZoomType( nTypeTmp );\n return sal_True;\n }\n }\n\n return sal_False;\n }\n break;\n\n case MID_VALUE:\n {\n sal_Int32 nVal;\n if ( rVal >>= nVal )\n {\n SetValue( nVal );\n return sal_True;\n }\n else\n return sal_False;\n }\n break;\n\n case MID_VALUESET:\n case MID_TYPE:\n {\n sal_Int16 nVal;\n if ( rVal >>= nVal )\n {\n if ( nMemberId == MID_VALUESET )\n nValueSet = (sal_Int16) nVal;\n else if ( nMemberId == MID_TYPE )\n eType = SvxZoomType( (sal_Int16) nVal );\n return sal_True;\n }\n else\n return sal_False;\n }\n break;\n\n default: DBG_ERROR(\"Wrong MemberId!\"); return sal_False;\n }\n\n return sal_True;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mediain.hpp\"\n\nMediaIn::MediaIn()\n{\n}\n\nint MediaIn::frameCount(void) const\n{\n return -1;\n}\n\nint MediaIn::frameCounter(void) const\n{\n return -1;\n}\n\nvoid MediaIn::frameCounter(int frameCount)\n{\n\t(void)frameCount;\n}\n\nbool MediaIn::getDepthMat(cv::Mat &depthMat)\n{\n\t(void)depthMat;\n\treturn false;\n}\n\ndouble MediaIn::getDepth(int x, int y)\n{\n\t(void)x;\n\t(void)y;\n return -1000.;\n}\n<commit_msg>Set returned mat to empty in base getDepthMat<commit_after>#include \"mediain.hpp\"\n\nMediaIn::MediaIn()\n{\n}\n\nint MediaIn::frameCount(void) const\n{\n\treturn -1;\n}\n\nint MediaIn::frameCounter(void) const\n{\n\treturn -1;\n}\n\nvoid MediaIn::frameCounter(int frameCount)\n{\n\t(void)frameCount;\n}\n\nbool MediaIn::getDepthMat(cv::Mat &depthMat)\n{\n\tdepthMat = Mat(); \/\/ return empty mat to indicate no depth info\n\treturn false; \/\/ in addition to returning false\n}\n\ndouble MediaIn::getDepth(int x, int y)\n{\n\t(void)x;\n\t(void)y;\n\treturn -1000.;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>SdrMarkView tiled rendering: suppress handles during text edit<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: svdoutl.cxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include <svx\/svdoutl.hxx>\n#include <svx\/outliner.hxx>\n#include <svx\/svdotext.hxx>\n#include <editstat.hxx>\n#include <svx\/svdmodel.hxx>\n#include <svx\/eeitem.hxx>\n#include <svtools\/itempool.hxx>\n\nDBG_NAME(SdrOutliner)\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\nSdrOutliner::SdrOutliner( SfxItemPool* pItemPool, USHORT nMode )\n: Outliner( pItemPool, nMode ),\n mpPaintInfoRec( NULL )\n{\n DBG_CTOR(SdrOutliner,NULL);\n}\n\n\n\/*************************************************************************\n|*\n|* Dtor\n|*\n\\************************************************************************\/\nSdrOutliner::~SdrOutliner()\n{\n DBG_DTOR(SdrOutliner,NULL);\n}\n\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nvoid SdrOutliner::SetTextObj( const SdrTextObj* pObj )\n{\n if( pObj && pObj != mpTextObj.get() )\n {\n SetUpdateMode(FALSE);\n USHORT nOutlinerMode2 = OUTLINERMODE_OUTLINEOBJECT;\n if ( !pObj->IsOutlText() )\n nOutlinerMode2 = OUTLINERMODE_TEXTOBJECT;\n Init( nOutlinerMode2 );\n\n SetGlobalCharStretching(100,100);\n\n ULONG nStat = GetControlWord();\n nStat &= ~( EE_CNTRL_STRETCHING | EE_CNTRL_AUTOPAGESIZE );\n SetControlWord(nStat);\n\n Size aNullSize;\n Size aMaxSize( 100000,100000 );\n SetMinAutoPaperSize( aNullSize );\n SetMaxAutoPaperSize( aMaxSize );\n SetPaperSize( aMaxSize );\n ClearPolygon();\n }\n\n mpTextObj.reset( const_cast< SdrTextObj* >(pObj) );\n}\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nvoid SdrOutliner::SetTextObjNoInit( const SdrTextObj* pObj )\n{\n mpTextObj.reset( const_cast< SdrTextObj* >(pObj) );\n}\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nXubString SdrOutliner::CalcFieldValue(const SvxFieldItem& rField, USHORT nPara, USHORT nPos,\n Color*& rpTxtColor, Color*& rpFldColor)\n{\n FASTBOOL bOk = FALSE;\n XubString aRet;\n\n if(mpTextObj.is())\n bOk = static_cast< SdrTextObj* >( mpTextObj.get())->CalcFieldValue(rField, nPara, nPos, FALSE, rpTxtColor, rpFldColor, aRet);\n\n if (!bOk)\n aRet = Outliner::CalcFieldValue(rField, nPara, nPos, rpTxtColor, rpFldColor);\n\n return aRet;\n}\n\nconst SdrTextObj* SdrOutliner::GetTextObj() const\n{\n return static_cast< SdrTextObj* >( mpTextObj.get() );\n}\n\n\n\n\n\n<commit_msg>INTEGRATION: CWS impressodf12 (1.11.26); FILE MERGED 2008\/05\/26 11:43:09 cl 1.11.26.1: #i35937# code cleanup after bullet rework<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: svdoutl.cxx,v $\n * $Revision: 1.12 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include <svx\/svdoutl.hxx>\n#include <svx\/outliner.hxx>\n#include <svx\/svdotext.hxx>\n#include <editstat.hxx>\n#include <svx\/svdmodel.hxx>\n#include <svx\/eeitem.hxx>\n#include <svtools\/itempool.hxx>\n\nDBG_NAME(SdrOutliner)\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\nSdrOutliner::SdrOutliner( SfxItemPool* pItemPool, USHORT nMode )\n: Outliner( pItemPool, nMode ),\n mpPaintInfoRec( NULL )\n{\n DBG_CTOR(SdrOutliner,NULL);\n}\n\n\n\/*************************************************************************\n|*\n|* Dtor\n|*\n\\************************************************************************\/\nSdrOutliner::~SdrOutliner()\n{\n DBG_DTOR(SdrOutliner,NULL);\n}\n\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nvoid SdrOutliner::SetTextObj( const SdrTextObj* pObj )\n{\n if( pObj && pObj != mpTextObj.get() )\n {\n SetUpdateMode(FALSE);\n USHORT nOutlinerMode2 = OUTLINERMODE_OUTLINEOBJECT;\n if ( !pObj->IsOutlText() )\n nOutlinerMode2 = OUTLINERMODE_TEXTOBJECT;\n Init( nOutlinerMode2 );\n\n SetGlobalCharStretching(100,100);\n\n ULONG nStat = GetControlWord();\n nStat &= ~( EE_CNTRL_STRETCHING | EE_CNTRL_AUTOPAGESIZE );\n SetControlWord(nStat);\n\n Size aNullSize;\n Size aMaxSize( 100000,100000 );\n SetMinAutoPaperSize( aNullSize );\n SetMaxAutoPaperSize( aMaxSize );\n SetPaperSize( aMaxSize );\n ClearPolygon();\n }\n\n mpTextObj.reset( const_cast< SdrTextObj* >(pObj) );\n}\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nvoid SdrOutliner::SetTextObjNoInit( const SdrTextObj* pObj )\n{\n mpTextObj.reset( const_cast< SdrTextObj* >(pObj) );\n}\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\nXubString SdrOutliner::CalcFieldValue(const SvxFieldItem& rField, USHORT nPara, USHORT nPos,\n Color*& rpTxtColor, Color*& rpFldColor)\n{\n FASTBOOL bOk = FALSE;\n XubString aRet;\n\n if(mpTextObj.is())\n bOk = static_cast< SdrTextObj* >( mpTextObj.get())->CalcFieldValue(rField, nPara, nPos, FALSE, rpTxtColor, rpFldColor, aRet);\n\n if (!bOk)\n aRet = Outliner::CalcFieldValue(rField, nPara, nPos, rpTxtColor, rpFldColor);\n\n return aRet;\n}\n\nconst SdrTextObj* SdrOutliner::GetTextObj() const\n{\n return static_cast< SdrTextObj* >( mpTextObj.get() );\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>do not use manual iteration<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: guess.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: fme $ $Date: 2001-04-09 10:41:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _GUESS_HXX\n#define _GUESS_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n#endif\n\n#include \"txttypes.hxx\"\n#include \"breakit.hxx\"\n#include \"porrst.hxx\" \/\/ SwHangingPortion\n\nclass SwTxtSizeInfo;\nclass SwTxtFormatInfo;\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::linguistic2;\n\n\/*************************************************************************\n * class SwTxtGuess\n *************************************************************************\/\n\nclass SwTxtGuess\n{\n uno::Reference< XHyphenatedWord > xHyphWord;\n SwHangingPortion *pHanging; \/\/ for hanging punctuation\n xub_StrLen nCutPos; \/\/ this character doesn't fit\n xub_StrLen nBreakStart; \/\/ start index of word containing line break\n xub_StrLen nBreakPos; \/\/ start index of break position\n KSHORT nBreakWidth; \/\/ width of the broken portion\n KSHORT nHeight; \/\/ GetTxtSize()-Height\npublic:\n inline SwTxtGuess(): pHanging( NULL ), nCutPos(0), nBreakStart(0),\n nBreakPos(0), nBreakWidth(0), nHeight(0)\n { }\n ~SwTxtGuess() { delete pHanging; }\n\n \/\/ true, if current portion still fits to current line\n sal_Bool Guess( const SwTxtPortion& rPor, SwTxtFormatInfo &rInf,\n const KSHORT nHeight );\n sal_Bool AlternativeSpelling( const SwTxtFormatInfo &rInf, const xub_StrLen nPos );\n\n inline SwHangingPortion* GetHangingPortion() const { return pHanging; }\n inline void ClearHangingPortion() { pHanging = NULL; }\n inline KSHORT BreakWidth() const { return nBreakWidth; }\n inline xub_StrLen CutPos() const { return nCutPos; }\n inline xub_StrLen BreakStart() const { return nBreakStart; }\n inline xub_StrLen BreakPos() const {return nBreakPos; }\n inline KSHORT Height() const { return nHeight; }\n inline uno::Reference< XHyphenatedWord > HyphWord() const\n { return xHyphWord; }\n static xub_StrLen GetWordStart( const SwTxtFormatInfo &rInf,\n const xub_StrLen nPos );\n};\n\n#endif\n<commit_msg>Opt: Remove of obsolete field nHeight<commit_after>\/*************************************************************************\n *\n * $RCSfile: guess.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: fme $ $Date: 2001-05-07 11:38:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _GUESS_HXX\n#define _GUESS_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_\n#include <com\/sun\/star\/linguistic2\/XHyphenatedWord.hpp>\n#endif\n\n#include \"txttypes.hxx\"\n#include \"breakit.hxx\"\n#include \"porrst.hxx\" \/\/ SwHangingPortion\n\nclass SwTxtSizeInfo;\nclass SwTxtFormatInfo;\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::linguistic2;\n\n\/*************************************************************************\n * class SwTxtGuess\n *************************************************************************\/\n\nclass SwTxtGuess\n{\n uno::Reference< XHyphenatedWord > xHyphWord;\n SwHangingPortion *pHanging; \/\/ for hanging punctuation\n xub_StrLen nCutPos; \/\/ this character doesn't fit\n xub_StrLen nBreakStart; \/\/ start index of word containing line break\n xub_StrLen nBreakPos; \/\/ start index of break position\n KSHORT nBreakWidth; \/\/ width of the broken portion\npublic:\n inline SwTxtGuess(): pHanging( NULL ), nCutPos(0), nBreakStart(0),\n nBreakPos(0), nBreakWidth(0)\n { }\n ~SwTxtGuess() { delete pHanging; }\n\n \/\/ true, if current portion still fits to current line\n sal_Bool Guess( const SwTxtPortion& rPor, SwTxtFormatInfo &rInf,\n const KSHORT nHeight );\n sal_Bool AlternativeSpelling( const SwTxtFormatInfo &rInf, const xub_StrLen nPos );\n\n inline SwHangingPortion* GetHangingPortion() const { return pHanging; }\n inline void ClearHangingPortion() { pHanging = NULL; }\n inline KSHORT BreakWidth() const { return nBreakWidth; }\n inline xub_StrLen CutPos() const { return nCutPos; }\n inline xub_StrLen BreakStart() const { return nBreakStart; }\n inline xub_StrLen BreakPos() const {return nBreakPos; }\n inline uno::Reference< XHyphenatedWord > HyphWord() const\n { return xHyphWord; }\n static xub_StrLen GetWordStart( const SwTxtFormatInfo &rInf,\n const xub_StrLen nPos );\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#include <config.h>\n#include <signal.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef HAVE_PATHS_H\n#include <paths.h>\n#endif\n\n#include <kuniqueapp.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n#include <kdebug.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\nstatic void signalHandler(int sigId);\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/-----------------------------------------------------------------------------\n\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = args->getOption(\"subject\");\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = args->getOption(\"cc\");\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = args->getOption(\"bcc\");\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = args->getOption(\"body\");\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData *about = new KAboutData(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"A KDE E-Mail client.\"),\n\t\t KAboutData::License_GPL,\n \"(c) 1997-2000, The KMail developers\",\n\t\t \"http:\/\/kmail.kde.org\");\n about->addAuthor( \"Don Sanders\", I18N_NOOP(\"Current maintainer\"), \"don@sanders.org\" );\n about->addAuthor( \"Waldo Bastian\", QString::null, \"bastian@kde.org\" );\n about->addAuthor( \"Andreas Gungl\", QString::null, \"a.gungl@gmx.de\" );\n about->addAuthor( \"Michael Haeckel\", QString::null, \"michael@haeckel.net\" );\n about->addAuthor( \"Lars Knoll\", QString::null, \"knoll@kde.org\" );\n about->addAuthor( \"J. Nick Koston\", QString::null, \"bdraco@darkorb.net\" );\n about->addAuthor( \"Daniel Naber\", QString::null, \"daniel.naber@t-online.de\" );\n about->addAuthor( \"Sven Radej\", QString::null, \"radej@kde.org\" );\n about->addAuthor( \"Espen Sand\", QString::null, \"espen@kde.org\" );\n about->addAuthor( \"George Staikos\", QString::null, \"staikos@kde.org\" );\n about->addAuthor( \"Stefan Taferner \", QString::null, \"taferner@kde.org\" );\n about->addAuthor( \"Mario Weilguni\", QString::null, \"mweilguni@sime.com\" );\n about->addAuthor( \"Robert D. Williams\", QString::null, \"rwilliams@kde.org\" );\n about->addAuthor( \"Markus Wuebben\", QString::null, \"markus.wuebben@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n exit(0);\n\n KMailApplication app;\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n return ret;\n}\n\n<commit_msg>the homepage url is now at the correct place in this long list of parameters<commit_after>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#include <config.h>\n#include <signal.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef HAVE_PATHS_H\n#include <paths.h>\n#endif\n\n#include <kuniqueapp.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n#include <kdebug.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\nstatic void signalHandler(int sigId);\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/-----------------------------------------------------------------------------\n\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = args->getOption(\"subject\");\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = args->getOption(\"cc\");\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = args->getOption(\"bcc\");\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = args->getOption(\"body\");\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData *about = new KAboutData(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"A KDE E-Mail client.\"),\n\t\t KAboutData::License_GPL,\n \"(c) 1997-2000, The KMail developers\",\n\t\t 0,\n\t\t \"http:\/\/kmail.kde.org\");\n about->addAuthor( \"Don Sanders\", I18N_NOOP(\"Current maintainer\"), \"don@sanders.org\" );\n about->addAuthor( \"Waldo Bastian\", QString::null, \"bastian@kde.org\" );\n about->addAuthor( \"Andreas Gungl\", QString::null, \"a.gungl@gmx.de\" );\n about->addAuthor( \"Michael Haeckel\", QString::null, \"michael@haeckel.net\" );\n about->addAuthor( \"Lars Knoll\", QString::null, \"knoll@kde.org\" );\n about->addAuthor( \"J. Nick Koston\", QString::null, \"bdraco@darkorb.net\" );\n about->addAuthor( \"Daniel Naber\", QString::null, \"daniel.naber@t-online.de\" );\n about->addAuthor( \"Sven Radej\", QString::null, \"radej@kde.org\" );\n about->addAuthor( \"Espen Sand\", QString::null, \"espen@kde.org\" );\n about->addAuthor( \"George Staikos\", QString::null, \"staikos@kde.org\" );\n about->addAuthor( \"Stefan Taferner \", QString::null, \"taferner@kde.org\" );\n about->addAuthor( \"Mario Weilguni\", QString::null, \"mweilguni@sime.com\" );\n about->addAuthor( \"Robert D. Williams\", QString::null, \"rwilliams@kde.org\" );\n about->addAuthor( \"Markus Wuebben\", QString::null, \"markus.wuebben@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n exit(0);\n\n KMailApplication app;\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inpdlg.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2006-11-06 14:52:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n\n#define _INPDLG_CXX\n\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _UNO_LINGU_HXX\n#include <svx\/unolingu.hxx>\n#endif\n\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _FLDBAS_HXX\n#include <fldbas.hxx>\n#endif\n#ifndef _EXPFLD_HXX\n#include <expfld.hxx>\n#endif\n#ifndef _USRFLD_HXX\n#include <usrfld.hxx>\n#endif\n#ifndef _INPDLG_HXX\n#include <inpdlg.hxx>\n#endif\n#ifndef _FLDMGR_HXX\n#include <fldmgr.hxx>\n#endif\n\n#ifndef _FLDUI_HRC\n#include <fldui.hrc>\n#endif\n#ifndef _INPDLG_HRC\n#include <inpdlg.hrc>\n#endif\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Feldeinfuegen bearbeiten\n --------------------------------------------------------------------*\/\n\nSwFldInputDlg::SwFldInputDlg( Window *pParent, SwWrtShell &rS,\n SwField* pField, BOOL bNextButton ) :\n\n SvxStandardDialog(pParent, SW_RES(DLG_FLD_INPUT)),\n\n rSh( rS ),\n aLabelED (this, SW_RES(ED_LABEL )),\n aEditED (this, SW_RES(ED_EDIT )),\n aEditFL (this, SW_RES(FL_EDIT )),\n aOKBT (this, SW_RES(BT_OK )),\n aCancelBT (this, SW_RES(BT_CANCEL )),\n aNextBT (this, SW_RES(PB_NEXT )),\n aHelpBT (this, SW_RES(PB_HELP )),\n pInpFld(0),\n pSetFld(0),\n pUsrType(0)\n{\n \/\/ Font fuers Edit umschalten\n Font aFont(aEditED.GetFont());\n aFont.SetWeight(WEIGHT_LIGHT);\n aEditED.SetFont(aFont);\n\n if( bNextButton )\n {\n aNextBT.Show();\n aNextBT.SetClickHdl(LINK(this, SwFldInputDlg, NextHdl));\n }\n else\n {\n long nDiff = aCancelBT.GetPosPixel().Y() - aOKBT.GetPosPixel().Y();\n Point aPos = aHelpBT.GetPosPixel();\n aPos.Y() -= nDiff;\n aHelpBT.SetPosPixel(aPos);\n }\n\n \/\/ Auswertung hier\n String aStr;\n if( RES_INPUTFLD == pField->GetTyp()->Which() )\n { \/\/ Es ist eine Eingabefeld\n \/\/\n pInpFld = (SwInputField*)pField;\n aLabelED.SetText( pInpFld->GetPar2() );\n USHORT nSubType = pInpFld->GetSubType();\n\n switch(nSubType & 0xff)\n {\n case INP_TXT:\n aStr = pInpFld->GetPar1();\n break;\n\n case INP_USR:\n \/\/ Benutzerfeld\n if( 0 != ( pUsrType = (SwUserFieldType*)rSh.GetFldType(\n RES_USERFLD, pInpFld->GetPar1() ) ) )\n aStr = pUsrType->GetContent();\n break;\n }\n }\n else\n {\n \/\/ es ist eine SetExpression\n pSetFld = (SwSetExpField*)pField;\n String sFormula(pSetFld->GetFormula());\n \/\/values are formatted - formulas are not\n CharClass aCC( SvxCreateLocale( pSetFld->GetLanguage() ));\n if( aCC.isNumeric( sFormula ))\n aStr = pSetFld->Expand();\n else\n aStr = sFormula;\n aLabelED.SetText( pSetFld->GetPromptText() );\n }\n\n \/\/ JP 31.3.00: Inputfields in readonly regions must be allowed to\n \/\/ input any content. - 74639\n BOOL bEnable = !rSh.IsCrsrReadonly();\n \/*!rSh.IsReadOnlyAvailable() || !rSh.HasReadonlySel()*\/;\n aOKBT.Enable( bEnable );\n aEditED.SetReadOnly( !bEnable );\n\n if( aStr.Len() )\n aEditED.SetText( aStr.ConvertLineEnd() );\n FreeResource();\n}\n\nSwFldInputDlg::~SwFldInputDlg()\n{\n}\n\nvoid SwFldInputDlg::StateChanged( StateChangedType nType )\n{\n if ( nType == STATE_CHANGE_INITSHOW )\n aEditED.GrabFocus();\n SvxStandardDialog::StateChanged( nType );\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Schliessen\n --------------------------------------------------------------------*\/\n\nvoid SwFldInputDlg::Apply()\n{\n String aTmp( aEditED.GetText() );\n aTmp.EraseAllChars( '\\r' );\n\n rSh.StartAllAction();\n BOOL bModified = FALSE;\n if(pInpFld)\n {\n if(pUsrType)\n {\n if( aTmp != pUsrType->GetContent() )\n {\n pUsrType->SetContent(aTmp);\n pUsrType->UpdateFlds();\n bModified = TRUE;\n }\n }\n else if( aTmp != pInpFld->GetPar1() )\n {\n pInpFld->SetPar1(aTmp);\n rSh.SwEditShell::UpdateFlds(*pInpFld);\n bModified = TRUE;\n }\n }\n else if( aTmp != pSetFld->GetPar2() )\n {\n pSetFld->SetPar2(aTmp);\n rSh.SwEditShell::UpdateFlds(*pSetFld);\n bModified = TRUE;\n }\n\n if( bModified )\n rSh.SetUndoNoResetModified();\n\n rSh.EndAllAction();\n}\n\n\nIMPL_LINK(SwFldInputDlg, NextHdl, PushButton*, EMPTYARG)\n{\n EndDialog(RET_OK);\n return 0;\n}\n\n\n<commit_msg>INTEGRATION: CWS swwarnings (1.9.160); FILE MERGED 2007\/03\/26 12:09:03 tl 1.9.160.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: inpdlg.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 11:49:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n\n#define _INPDLG_CXX\n\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _UNO_LINGU_HXX\n#include <svx\/unolingu.hxx>\n#endif\n\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _FLDBAS_HXX\n#include <fldbas.hxx>\n#endif\n#ifndef _EXPFLD_HXX\n#include <expfld.hxx>\n#endif\n#ifndef _USRFLD_HXX\n#include <usrfld.hxx>\n#endif\n#ifndef _INPDLG_HXX\n#include <inpdlg.hxx>\n#endif\n#ifndef _FLDMGR_HXX\n#include <fldmgr.hxx>\n#endif\n\n#ifndef _FLDUI_HRC\n#include <fldui.hrc>\n#endif\n#ifndef _INPDLG_HRC\n#include <inpdlg.hrc>\n#endif\n\n\n\/*--------------------------------------------------------------------\n Beschreibung: Feldeinfuegen bearbeiten\n --------------------------------------------------------------------*\/\n\nSwFldInputDlg::SwFldInputDlg( Window *pParent, SwWrtShell &rS,\n SwField* pField, BOOL bNextButton ) :\n\n SvxStandardDialog(pParent, SW_RES(DLG_FLD_INPUT)),\n\n rSh( rS ),\n pInpFld(0),\n pSetFld(0),\n pUsrType(0),\n\n aLabelED (this, SW_RES(ED_LABEL )),\n aEditED (this, SW_RES(ED_EDIT )),\n aEditFL (this, SW_RES(FL_EDIT )),\n\n aOKBT (this, SW_RES(BT_OK )),\n aCancelBT (this, SW_RES(BT_CANCEL )),\n aNextBT (this, SW_RES(PB_NEXT )),\n aHelpBT (this, SW_RES(PB_HELP ))\n{\n \/\/ Font fuers Edit umschalten\n Font aFont(aEditED.GetFont());\n aFont.SetWeight(WEIGHT_LIGHT);\n aEditED.SetFont(aFont);\n\n if( bNextButton )\n {\n aNextBT.Show();\n aNextBT.SetClickHdl(LINK(this, SwFldInputDlg, NextHdl));\n }\n else\n {\n long nDiff = aCancelBT.GetPosPixel().Y() - aOKBT.GetPosPixel().Y();\n Point aPos = aHelpBT.GetPosPixel();\n aPos.Y() -= nDiff;\n aHelpBT.SetPosPixel(aPos);\n }\n\n \/\/ Auswertung hier\n String aStr;\n if( RES_INPUTFLD == pField->GetTyp()->Which() )\n { \/\/ Es ist eine Eingabefeld\n \/\/\n pInpFld = (SwInputField*)pField;\n aLabelED.SetText( pInpFld->GetPar2() );\n USHORT nSubType = pInpFld->GetSubType();\n\n switch(nSubType & 0xff)\n {\n case INP_TXT:\n aStr = pInpFld->GetPar1();\n break;\n\n case INP_USR:\n \/\/ Benutzerfeld\n if( 0 != ( pUsrType = (SwUserFieldType*)rSh.GetFldType(\n RES_USERFLD, pInpFld->GetPar1() ) ) )\n aStr = pUsrType->GetContent();\n break;\n }\n }\n else\n {\n \/\/ es ist eine SetExpression\n pSetFld = (SwSetExpField*)pField;\n String sFormula(pSetFld->GetFormula());\n \/\/values are formatted - formulas are not\n CharClass aCC( SvxCreateLocale( pSetFld->GetLanguage() ));\n if( aCC.isNumeric( sFormula ))\n aStr = pSetFld->Expand();\n else\n aStr = sFormula;\n aLabelED.SetText( pSetFld->GetPromptText() );\n }\n\n \/\/ JP 31.3.00: Inputfields in readonly regions must be allowed to\n \/\/ input any content. - 74639\n BOOL bEnable = !rSh.IsCrsrReadonly();\n \/*!rSh.IsReadOnlyAvailable() || !rSh.HasReadonlySel()*\/;\n aOKBT.Enable( bEnable );\n aEditED.SetReadOnly( !bEnable );\n\n if( aStr.Len() )\n aEditED.SetText( aStr.ConvertLineEnd() );\n FreeResource();\n}\n\nSwFldInputDlg::~SwFldInputDlg()\n{\n}\n\nvoid SwFldInputDlg::StateChanged( StateChangedType nType )\n{\n if ( nType == STATE_CHANGE_INITSHOW )\n aEditED.GrabFocus();\n SvxStandardDialog::StateChanged( nType );\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Schliessen\n --------------------------------------------------------------------*\/\n\nvoid SwFldInputDlg::Apply()\n{\n String aTmp( aEditED.GetText() );\n aTmp.EraseAllChars( '\\r' );\n\n rSh.StartAllAction();\n BOOL bModified = FALSE;\n if(pInpFld)\n {\n if(pUsrType)\n {\n if( aTmp != pUsrType->GetContent() )\n {\n pUsrType->SetContent(aTmp);\n pUsrType->UpdateFlds();\n bModified = TRUE;\n }\n }\n else if( aTmp != pInpFld->GetPar1() )\n {\n pInpFld->SetPar1(aTmp);\n rSh.SwEditShell::UpdateFlds(*pInpFld);\n bModified = TRUE;\n }\n }\n else if( aTmp != pSetFld->GetPar2() )\n {\n pSetFld->SetPar2(aTmp);\n rSh.SwEditShell::UpdateFlds(*pSetFld);\n bModified = TRUE;\n }\n\n if( bModified )\n rSh.SetUndoNoResetModified();\n\n rSh.EndAllAction();\n}\n\n\nIMPL_LINK(SwFldInputDlg, NextHdl, PushButton*, EMPTYARG)\n{\n EndDialog(RET_OK);\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: docfnote.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 17:14:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _DOCFNOTE_HXX\n#define _DOCFNOTE_HXX\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\nclass SwWrtShell;\n\nclass SwFootNoteOptionDlg :public SfxTabDialog\n{\n SwWrtShell &rSh;\n Link aOldOkHdl;\n\n virtual void PageCreated( USHORT nId, SfxTabPage &rPage );\n\n#ifdef __PRIVATE\n DECL_LINK( OkHdl, Button * );\n#endif\n\npublic:\n SwFootNoteOptionDlg(Window *pParent, SwWrtShell &rSh );\n ~SwFootNoteOptionDlg();\n};\n\n#endif\n<commit_msg>#58628#,#65293# __PRIVATE -> _SOLAR__PRIVATE<commit_after>\/*************************************************************************\n *\n * $RCSfile: docfnote.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2000-12-07 15:57:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _DOCFNOTE_HXX\n#define _DOCFNOTE_HXX\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\nclass SwWrtShell;\n\nclass SwFootNoteOptionDlg :public SfxTabDialog\n{\n SwWrtShell &rSh;\n Link aOldOkHdl;\n\n virtual void PageCreated( USHORT nId, SfxTabPage &rPage );\n\n#ifdef _SOLAR__PRIVATE\n DECL_LINK( OkHdl, Button * );\n#endif\n\npublic:\n SwFootNoteOptionDlg(Window *pParent, SwWrtShell &rSh );\n ~SwFootNoteOptionDlg();\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: navicont.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jp $ $Date: 2001-05-07 08:53:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _NAVICONT_HXX\n#define _NAVICONT_HXX\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\nclass SwDocShell;\nclass TransferDataContainer;\nclass TransferableDataHelper;\n\n\/* [Beschreibung]\n Navigator-Bookmark zur eindeutigen Identifizierung im Sw\n*\/\n\nclass NaviContentBookmark\n{\n String aUrl; \/\/ URL inkl. Sprungmarke\n String aDescr; \/\/ Description\n long nDocSh; \/\/ Adresse der DocShell\n USHORT nDefDrag; \/\/ Description enthaelt defaultDragType\n\npublic:\n NaviContentBookmark();\n NaviContentBookmark( const String &rUrl, const String& rDesc,\n USHORT nDragType, const SwDocShell* );\n\n const String& GetURL() const { return aUrl; }\n const String& GetDescription() const { return aDescr; }\n USHORT GetDefaultDragType() const { return nDefDrag; }\n long GetDocShell() const { return nDocSh; }\n\n static BOOL HasFormat( TransferableDataHelper& rData,\n const SwDocShell* pDocSh = 0 );\n\n void Copy( TransferDataContainer& rData ) const;\n BOOL Paste( TransferableDataHelper& rData );\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS tune05 (1.2.764); FILE MERGED 2004\/07\/22 08:13:50 cmc 1.2.764.1: #i30554# NaviContentBookmark::HasFormat unused<commit_after>\/*************************************************************************\n *\n * $RCSfile: navicont.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-08-12 13:05:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _NAVICONT_HXX\n#define _NAVICONT_HXX\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\nclass SwDocShell;\nclass TransferDataContainer;\nclass TransferableDataHelper;\n\n\/* [Beschreibung]\n Navigator-Bookmark zur eindeutigen Identifizierung im Sw\n*\/\n\nclass NaviContentBookmark\n{\n String aUrl; \/\/ URL inkl. Sprungmarke\n String aDescr; \/\/ Description\n long nDocSh; \/\/ Adresse der DocShell\n USHORT nDefDrag; \/\/ Description enthaelt defaultDragType\n\npublic:\n NaviContentBookmark();\n NaviContentBookmark( const String &rUrl, const String& rDesc,\n USHORT nDragType, const SwDocShell* );\n\n const String& GetURL() const { return aUrl; }\n const String& GetDescription() const { return aDescr; }\n USHORT GetDefaultDragType() const { return nDefDrag; }\n long GetDocShell() const { return nDocSh; }\n void Copy( TransferDataContainer& rData ) const;\n BOOL Paste( TransferableDataHelper& rData );\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: view0.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 17:14:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"hintids.hxx\"\n\n#ifndef _SVX_SRCHITEM_HXX\n#include <svx\/srchitem.hxx>\n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SVX_SRCHDLG_HXX \/\/autogen\n#include <svx\/srchdlg.hxx>\n#endif\n#ifndef _IDETEMP_HXX\n#include <basctl\/idetemp.hxx>\n#endif\n#ifndef _SFX_TEMPLDLG_HXX \/\/autogen\n#include <sfx2\/templdlg.hxx>\n#endif\n#ifndef _UIVWIMP_HXX\n#include <uivwimp.hxx>\n#endif\n\n#ifndef _NAVIPI_HXX \/\/autogen\n#include <navipi.hxx>\n#endif\n#include \"view.hxx\"\n#include \"basesh.hxx\"\n#include \"docsh.hxx\"\n#include \"globals.hrc\"\n#include \"cmdid.h\" \/\/ FN_ ...\n#include \"globdoc.hxx\"\n#include \"wview.hxx\"\n#include \"shells.hrc\"\n\n#define OLEObjects\n#define SwView\n#define SearchAttributes\n#define ReplaceAttributes\n#define SearchSettings\n#define _ExecSearch ExecSearch\n#define _StateSearch StateSearch\n#define Frames\n#define Graphics\n#define Tables\n#define Controls\n#define GlobalContents\n#define Text\n#define Frame\n#define Graphic\n#define Object\n#define Draw\n#define TextDrawText\n#define TextInTable\n#define ListInText\n#define ListInTable\n#define WebTextInTable\n#define WebListInText\n#define WebListInTable\n#define TextPage\n#include \"itemdef.hxx\"\n#include <svx\/svxslots.hxx>\n#include \"swslots.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\n#define C2S(cChar) UniString::CreateFromAscii(cChar)\n\nSFX_IMPL_VIEWFACTORY(SwView, SW_RES(STR_NONAME))\n{\n SFX_VIEW_REGISTRATION(SwDocShell);\n SFX_VIEW_REGISTRATION(SwGlobalDocShell);\n}\n\nSFX_IMPL_INTERFACE( SwView, SfxViewShell, SW_RES(RID_TOOLS_TOOLBOX) )\n{\n SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);\n SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SvxSearchDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(FN_REDLINE_ACCEPT);\n SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);\n SFX_FEATURED_CHILDWINDOW_REGISTRATION(FN_SYNC_LABELS, 1);\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS|\n SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,\n SW_RES(RID_TOOLS_TOOLBOX) );\n}\n\nTYPEINIT1(SwView,SfxViewShell)\n\n\/*-----------------13.12.97 11:06-------------------\n\n--------------------------------------------------*\/\nShellModes SwView::GetShellMode()\n{\n return pViewImpl->GetShellMode();\n}\n\n\/*-----------------13.12.97 11:28-------------------\n\n--------------------------------------------------*\/\nview::XSelectionSupplier* SwView::GetUNOObject()\n{\n return pViewImpl->GetUNOObject();\n}\n\n\n\/*------------------------------------------------------------------------\n $Log: not supported by cvs2svn $\n Revision 1.72 2000\/09\/18 16:06:12 willem.vandorp\n OpenOffice header added.\n\n Revision 1.71 2000\/09\/04 11:44:56 tbe\n basicide, isetbrw, si, vcdlged moved from svx to basctl\n\n Revision 1.70 2000\/05\/10 11:53:20 os\n Basic API removed\n\n Revision 1.69 2000\/05\/09 14:43:13 os\n BASIC interface partially removed\n\n Revision 1.68 2000\/04\/18 15:02:50 os\n UNICODE\n\n Revision 1.67 2000\/03\/23 07:50:25 os\n UNO III\n\n Revision 1.66 2000\/02\/09 08:07:01 os\n #72165# hyperlink dialog moved again\n\n Revision 1.65 1999\/09\/07 13:56:53 os\n Insert\/EditIndexEntry as FloatingWindow\n\n Revision 1.64 1999\/01\/27 08:58:32 OS\n #56371# TF_ONE51\n\n\n Rev 1.63 27 Jan 1999 09:58:32 OS\n #56371# TF_ONE51\n\n Rev 1.62 15 Jul 1998 12:52:42 OS\n Navigator an der SwView registrieren #34794#\n\n Rev 1.61 09 Jun 1998 15:32:20 OM\n VC-Controls entfernt\n\n Rev 1.60 02 Jun 1998 15:49:54 OS\n TF_STARONE raus; GetUNOSelectionObject gestrichen\n\n Rev 1.59 03 Apr 1998 14:38:18 OS\n UnoObject fuer die View reaktiviert\n\n Rev 1.58 16 Mar 1998 16:18:04 OM\n Aktualisieren-Button kontextsensitiv\n\n Rev 1.57 15 Mar 1998 15:14:08 OM\n Synchron-Button\n\n Rev 1.56 27 Feb 1998 18:25:14 OM\n Redline-Browser\n\n Rev 1.55 29 Jan 1998 09:21:06 OS\n TF_STARONE\n\n Rev 1.54 16 Dec 1997 12:00:24 OS\n Impl-Pointer fuer UNO\n\n Rev 1.53 29 Nov 1997 16:49:14 MA\n includes\n\n Rev 1.52 21 Nov 1997 15:00:12 MA\n includes\n\n Rev 1.51 03 Nov 1997 13:58:28 MA\n precomp entfernt\n\n Rev 1.50 09 Sep 1997 11:33:08 OS\n TextPage heisst nur Page #43650#\n\n Rev 1.49 08 Sep 1997 10:52:36 OS\n DBG_ERROR -> DBG_ASSERT\n\n Rev 1.48 08 Sep 1997 07:43:38 OS\n TextTables nur ClassName\n\n Rev 1.47 04 Sep 1997 18:10:56 MBA\n GetSelectionObject erzeugt richtiges Objekt auch bei WebView\n\n Rev 1.46 04 Sep 1997 08:25:24 OS\n Tables heisst jetzt TextTables, kein GPF wg. fehlender TLB-Angaben\n\n Rev 1.45 03 Sep 1997 10:52:26 MBA\n OLEObjects in SVX\n\n Rev 1.44 29 Aug 1997 12:21:34 MH\n chg: SfxTypeLib_Impl\n\n Rev 1.43 05 Aug 1997 16:36:38 TJ\n include svx\/srchitem.hxx\n\n Rev 1.42 07 Jul 1997 09:35:10 OS\n Collection fuer GlobalDoc\n\n------------------------------------------------------------------------*\/\n\n<commit_msg>gallery child window registered<commit_after>\/*************************************************************************\n *\n * $RCSfile: view0.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: os $ $Date: 2000-09-28 15:34:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"hintids.hxx\"\n\n#ifndef _SVX_GALBRWS_HXX_\n#include <svx\/galbrws.hxx>\n#endif\n#ifndef _SVX_SRCHITEM_HXX\n#include <svx\/srchitem.hxx>\n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SVX_SRCHDLG_HXX \/\/autogen\n#include <svx\/srchdlg.hxx>\n#endif\n#ifndef _IDETEMP_HXX\n#include <basctl\/idetemp.hxx>\n#endif\n#ifndef _SFX_TEMPLDLG_HXX \/\/autogen\n#include <sfx2\/templdlg.hxx>\n#endif\n#ifndef _UIVWIMP_HXX\n#include <uivwimp.hxx>\n#endif\n\n#ifndef _NAVIPI_HXX \/\/autogen\n#include <navipi.hxx>\n#endif\n#include \"view.hxx\"\n#include \"basesh.hxx\"\n#include \"docsh.hxx\"\n#include \"globals.hrc\"\n#include \"cmdid.h\" \/\/ FN_ ...\n#include \"globdoc.hxx\"\n#include \"wview.hxx\"\n#include \"shells.hrc\"\n\n#define OLEObjects\n#define SwView\n#define SearchAttributes\n#define ReplaceAttributes\n#define SearchSettings\n#define _ExecSearch ExecSearch\n#define _StateSearch StateSearch\n#define Frames\n#define Graphics\n#define Tables\n#define Controls\n#define GlobalContents\n#define Text\n#define Frame\n#define Graphic\n#define Object\n#define Draw\n#define TextDrawText\n#define TextInTable\n#define ListInText\n#define ListInTable\n#define WebTextInTable\n#define WebListInText\n#define WebListInTable\n#define TextPage\n#include \"itemdef.hxx\"\n#include <svx\/svxslots.hxx>\n#include \"swslots.hxx\"\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\n#define C2S(cChar) UniString::CreateFromAscii(cChar)\n\nSFX_IMPL_VIEWFACTORY(SwView, SW_RES(STR_NONAME))\n{\n SFX_VIEW_REGISTRATION(SwDocShell);\n SFX_VIEW_REGISTRATION(SwGlobalDocShell);\n}\n\nSFX_IMPL_INTERFACE( SwView, SfxViewShell, SW_RES(RID_TOOLS_TOOLBOX) )\n{\n SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);\n SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SvxSearchDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(FN_REDLINE_ACCEPT);\n SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);\n SFX_CHILDWINDOW_REGISTRATION(GalleryChildWindow::GetChildWindowId());\n\n\n SFX_FEATURED_CHILDWINDOW_REGISTRATION(FN_SYNC_LABELS, 1);\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS|\n SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,\n SW_RES(RID_TOOLS_TOOLBOX) );\n}\n\nTYPEINIT1(SwView,SfxViewShell)\n\n\/*-----------------13.12.97 11:06-------------------\n\n--------------------------------------------------*\/\nShellModes SwView::GetShellMode()\n{\n return pViewImpl->GetShellMode();\n}\n\n\/*-----------------13.12.97 11:28-------------------\n\n--------------------------------------------------*\/\nview::XSelectionSupplier* SwView::GetUNOObject()\n{\n return pViewImpl->GetUNOObject();\n}\n\n\n\/*------------------------------------------------------------------------\n $Log: not supported by cvs2svn $\n Revision 1.1.1.1 2000\/09\/18 17:14:49 hr\n initial import\n\n Revision 1.72 2000\/09\/18 16:06:12 willem.vandorp\n OpenOffice header added.\n\n Revision 1.71 2000\/09\/04 11:44:56 tbe\n basicide, isetbrw, si, vcdlged moved from svx to basctl\n\n Revision 1.70 2000\/05\/10 11:53:20 os\n Basic API removed\n\n Revision 1.69 2000\/05\/09 14:43:13 os\n BASIC interface partially removed\n\n Revision 1.68 2000\/04\/18 15:02:50 os\n UNICODE\n\n Revision 1.67 2000\/03\/23 07:50:25 os\n UNO III\n\n Revision 1.66 2000\/02\/09 08:07:01 os\n #72165# hyperlink dialog moved again\n\n Revision 1.65 1999\/09\/07 13:56:53 os\n Insert\/EditIndexEntry as FloatingWindow\n\n Revision 1.64 1999\/01\/27 08:58:32 OS\n #56371# TF_ONE51\n\n\n Rev 1.63 27 Jan 1999 09:58:32 OS\n #56371# TF_ONE51\n\n Rev 1.62 15 Jul 1998 12:52:42 OS\n Navigator an der SwView registrieren #34794#\n\n Rev 1.61 09 Jun 1998 15:32:20 OM\n VC-Controls entfernt\n\n Rev 1.60 02 Jun 1998 15:49:54 OS\n TF_STARONE raus; GetUNOSelectionObject gestrichen\n\n Rev 1.59 03 Apr 1998 14:38:18 OS\n UnoObject fuer die View reaktiviert\n\n Rev 1.58 16 Mar 1998 16:18:04 OM\n Aktualisieren-Button kontextsensitiv\n\n Rev 1.57 15 Mar 1998 15:14:08 OM\n Synchron-Button\n\n Rev 1.56 27 Feb 1998 18:25:14 OM\n Redline-Browser\n\n Rev 1.55 29 Jan 1998 09:21:06 OS\n TF_STARONE\n\n Rev 1.54 16 Dec 1997 12:00:24 OS\n Impl-Pointer fuer UNO\n\n Rev 1.53 29 Nov 1997 16:49:14 MA\n includes\n\n Rev 1.52 21 Nov 1997 15:00:12 MA\n includes\n\n Rev 1.51 03 Nov 1997 13:58:28 MA\n precomp entfernt\n\n Rev 1.50 09 Sep 1997 11:33:08 OS\n TextPage heisst nur Page #43650#\n\n Rev 1.49 08 Sep 1997 10:52:36 OS\n DBG_ERROR -> DBG_ASSERT\n\n Rev 1.48 08 Sep 1997 07:43:38 OS\n TextTables nur ClassName\n\n Rev 1.47 04 Sep 1997 18:10:56 MBA\n GetSelectionObject erzeugt richtiges Objekt auch bei WebView\n\n Rev 1.46 04 Sep 1997 08:25:24 OS\n Tables heisst jetzt TextTables, kein GPF wg. fehlender TLB-Angaben\n\n Rev 1.45 03 Sep 1997 10:52:26 MBA\n OLEObjects in SVX\n\n Rev 1.44 29 Aug 1997 12:21:34 MH\n chg: SfxTypeLib_Impl\n\n Rev 1.43 05 Aug 1997 16:36:38 TJ\n include svx\/srchitem.hxx\n\n Rev 1.42 07 Jul 1997 09:35:10 OS\n Collection fuer GlobalDoc\n\n------------------------------------------------------------------------*\/\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n#ifndef __INCOHERENT_RELEASER_HPP__\n#define __INCOHERENT_RELEASER_HPP__\n\n#include \"Grappa.hpp\"\n#include \"Message.hpp\"\n\n#ifdef VTRACE\n#include <vt_user.h>\n#endif\n\n\/\/ forward declare for active message templates\ntemplate< typename T >\nclass IncoherentReleaser;\n\n\ntemplate< typename T >\nstatic void incoherent_release_reply_am( typename IncoherentReleaser< T >::ReplyArgs * args, \n size_t size, \n void * payload, size_t payload_size );\n\ntemplate< typename T >\nstatic void incoherent_release_request_am( typename IncoherentReleaser< T >::RequestArgs * args, \n size_t size, \n void * payload, size_t payload_size );\n\n\/\/\/ Stats for IncoherentReleaser\nclass IRStatistics {\n private:\n uint64_t release_ams;\n uint64_t release_ams_bytes;\n#ifdef VTRACE_SAMPLED\n unsigned ir_grp_vt;\n unsigned release_ams_ev_vt;\n unsigned release_ams_bytes_ev_vt;\n#endif\n\n public:\n IRStatistics();\n void reset();\n\n inline void count_release_ams( uint64_t bytes ) {\n release_ams++;\n release_ams_bytes+=bytes;\n }\n\n void dump( std::ostream& o, const char * terminator );\n void sample();\n void profiling_sample();\n void merge(const IRStatistics * other);\n};\n\nextern IRStatistics incoherent_releaser_stats;\n\n\n\/\/\/ IncoherentReleaser behavior for cache.\ntemplate< typename T >\nclass IncoherentReleaser {\nprivate:\n bool release_started_;\n bool released_;\n GlobalAddress< T > * request_address_;\n size_t * count_;\n T ** pointer_;\n Thread * thread_;\n int num_messages_;\n int response_count_;\n\n\npublic:\n\n IncoherentReleaser( GlobalAddress< T > * request_address, size_t * count, T ** pointer )\n : request_address_( request_address )\n , count_( count )\n , pointer_( pointer )\n , release_started_( false )\n , released_( false )\n , thread_(NULL)\n , num_messages_(0)\n , response_count_(0)\n { \n reset();\n }\n \n void reset( ) {\n CHECK( !release_started_ || released_ ) << \"inconsistent state for reset\";\n release_started_ = false;\n released_ = false;\n thread_ = NULL;\n num_messages_ = 0;\n response_count_ = 0;\n if( *count_ == 0 ) {\n DVLOG(5) << \"Zero-length release\";\n release_started_ = true;\n released_ = true;\n } else if( request_address_->is_2D() ) {\n num_messages_ = 1;\n if( request_address_->node() == Grappa_mynode() ) {\n release_started_ = true;\n released_ = true;\n }\n } else {\n DVLOG(5) << \"Straddle: block_max is \" << (*request_address_ + *count_).block_max() ;\n DVLOG(5) << \", request_address is \" << *request_address_;\n DVLOG(5) << \", sizeof(T) is \" << sizeof(T);\n DVLOG(5) << \", count is \" << *count_;\n DVLOG(5) << \", block_min is \" << request_address_->block_min();\n\n\n DVLOG(5) << \"Straddle: address is \" << *request_address_ ;\n DVLOG(5) << \", address + count is \" << *request_address_ + *count_;\n\n ptrdiff_t byte_diff = ( (*request_address_ + *count_ - 1).last_byte().block_max() - \n request_address_->first_byte().block_min() );\n\n DVLOG(5) << \"Straddle: address block max is \" << request_address_->block_max();\n DVLOG(5) << \" address + count block max is \" << (*request_address_ + *count_).block_max();\n DVLOG(5) << \" address + count -1 block max is \" << (*request_address_ + *count_ - 1).block_max();\n DVLOG(5) << \" difference is \" << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() );\n DVLOG(5) << \" multiplied difference is \" << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ) * sizeof(T);\n DVLOG(5) << \" address block min \" << request_address_->block_min();\n DVLOG(5) << \"Straddle: diff is \" << byte_diff << \" bs \" << block_size;\n num_messages_ = byte_diff \/ block_size;\n }\n\n if( num_messages_ > 1 ) DVLOG(5) << \"****************************** MULTI BLOCK CACHE REQUEST ******************************\";\n\n DVLOG(5) << \"Detecting straddle for sizeof(T):\" << sizeof(T)\n << \" count:\" << *count_\n << \" num_messages_:\" << num_messages_\n << \" request_address:\" << *request_address_;\n }\n\n void start_release() { \n if( !release_started_ ) {\n#ifdef VTRACE_FULL\n VT_TRACER(\"incoherent start_release\");\n#endif\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" issuing release for \" << *request_address_ \n << \" * \" << *count_ ;\n release_started_ = true;\n RequestArgs args;\n args.request_address = *request_address_;\n DVLOG(5) << \"Computing request_bytes from block_max \" << request_address_->first_byte().block_max() << \" and \" << *request_address_;\n args.reply_address = make_global( this );\n size_t offset = 0; \n size_t request_bytes = 0;\n size_t total_bytes = *count_ * sizeof(T);\n\n \/\/ allocate enough requests\/messages that we don't run out\n size_t nmsg = total_bytes \/ block_size + 2;\n RequestArgs arg_array[nmsg];\n Grappa::ExternalPayloadMessage<RequestArgs> msg_array[nmsg];\n \n for( size_t i = 0;\n offset < total_bytes; \n offset += request_bytes, i++) {\n\n request_bytes = args.request_address.first_byte().block_max() - args.request_address.first_byte();\n\n if( request_bytes > total_bytes - offset ) {\n request_bytes = total_bytes - offset;\n }\n\n DVLOG(5) << \"sending release request with \" << request_bytes\n << \" of total bytes = \" << *count_ * sizeof(T)\n << \" to \" << args.request_address;\n\n arg_array[i] = args;\n new (msg_array+i) Grappa::ExternalPayloadMessage<RequestArgs>(arg_array[i].request_address.node(), &arg_array[i], ((char*)(*pointer_)) + offset, request_bytes);\n msg_array[i].enqueue();\n\/\/ Grappa_call_on( args.request_address.node(), &incoherent_release_request_am<T>,\n\/\/ &args, sizeof( args ),\n\/\/ ((char*)(*pointer_)) + offset, request_bytes);\n\n\t\/\/ TODO: change type so we don't screw with pointer like this\n args.request_address = GlobalAddress<T>::Raw( args.request_address.raw_bits() + request_bytes );\n }\n DVLOG(5) << \"release started for \" << args.request_address;\n \n \/\/ blocks here waiting for messages to be sent\n }\n }\n\n void block_until_released() {\n if( !released_ ) {\n start_release();\n#ifdef VTRACE_FULL\n VT_TRACER(\"incoherent block_until_released\");\n#endif\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" ready to block on \" << *request_address_ \n << \" * \" << *count_ ;\n while( !released_ ) {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" blocking on \" << *request_address_ \n << \" * \" << *count_ ;\n if( !released_ ) {\n thread_ = CURRENT_THREAD;\n Grappa_suspend();\n thread_ = NULL;\n }\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" woke up for \" << *request_address_ \n << \" * \" << *count_ ;\n }\n }\n }\n\n void release_reply( ) { \n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" received release reply \";\n ++response_count_;\n if ( response_count_ == num_messages_ ) {\n released_ = true;\n if( thread_ != NULL ) {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" waking Thread \" << thread_;\n Grappa_wake( thread_ );\n }\n }\n }\n\n bool released() const { return released_; }\n\n\n struct ReplyArgs {\n GlobalAddress< IncoherentReleaser > reply_address;\n void operator()() {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD << \" received release reply to \" << reply_address;\n reply_address.pointer()->release_reply( );\n }\n };\n \n struct RequestArgs {\n GlobalAddress< T > request_address;\n GlobalAddress< IncoherentReleaser > reply_address;\n \n void operator()(void * payload, size_t payload_size) {\n incoherent_releaser_stats.count_release_ams( payload_size );\n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" received release request to \" << request_address\n << \" reply to \" << reply_address;\n memcpy( request_address.pointer(), payload, payload_size );\n ReplyArgs reply_args;\n reply_args.reply_address = reply_address;\n \n Grappa::send_heap_message(reply_address.node(), reply_args);\n \n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" sent release reply to \" << reply_address;\n }\n };\n};\n\n#endif\n<commit_msg>Fix stack overflow in IncoherentReleaser, use new blocking MessagePool.<commit_after>\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n#ifndef __INCOHERENT_RELEASER_HPP__\n#define __INCOHERENT_RELEASER_HPP__\n\n#include \"Grappa.hpp\"\n#include \"Message.hpp\"\n#include \"MessagePool.hpp\"\n\n#ifdef VTRACE\n#include <vt_user.h>\n#endif\n\n\/\/ forward declare for active message templates\ntemplate< typename T >\nclass IncoherentReleaser;\n\n\ntemplate< typename T >\nstatic void incoherent_release_reply_am( typename IncoherentReleaser< T >::ReplyArgs * args, \n size_t size, \n void * payload, size_t payload_size );\n\ntemplate< typename T >\nstatic void incoherent_release_request_am( typename IncoherentReleaser< T >::RequestArgs * args, \n size_t size, \n void * payload, size_t payload_size );\n\n\/\/\/ Stats for IncoherentReleaser\nclass IRStatistics {\n private:\n uint64_t release_ams;\n uint64_t release_ams_bytes;\n#ifdef VTRACE_SAMPLED\n unsigned ir_grp_vt;\n unsigned release_ams_ev_vt;\n unsigned release_ams_bytes_ev_vt;\n#endif\n\n public:\n IRStatistics();\n void reset();\n\n inline void count_release_ams( uint64_t bytes ) {\n release_ams++;\n release_ams_bytes+=bytes;\n }\n\n void dump( std::ostream& o, const char * terminator );\n void sample();\n void profiling_sample();\n void merge(const IRStatistics * other);\n};\n\nextern IRStatistics incoherent_releaser_stats;\n\n\n\/\/\/ IncoherentReleaser behavior for cache.\ntemplate< typename T >\nclass IncoherentReleaser {\nprivate:\n bool release_started_;\n bool released_;\n GlobalAddress< T > * request_address_;\n size_t * count_;\n T ** pointer_;\n Thread * thread_;\n int num_messages_;\n int response_count_;\n\n\npublic:\n\n IncoherentReleaser( GlobalAddress< T > * request_address, size_t * count, T ** pointer )\n : request_address_( request_address )\n , count_( count )\n , pointer_( pointer )\n , release_started_( false )\n , released_( false )\n , thread_(NULL)\n , num_messages_(0)\n , response_count_(0)\n { \n reset();\n }\n \n void reset( ) {\n CHECK( !release_started_ || released_ ) << \"inconsistent state for reset\";\n release_started_ = false;\n released_ = false;\n thread_ = NULL;\n num_messages_ = 0;\n response_count_ = 0;\n if( *count_ == 0 ) {\n DVLOG(5) << \"Zero-length release\";\n release_started_ = true;\n released_ = true;\n } else if( request_address_->is_2D() ) {\n num_messages_ = 1;\n if( request_address_->node() == Grappa_mynode() ) {\n release_started_ = true;\n released_ = true;\n }\n } else {\n DVLOG(5) << \"Straddle: block_max is \" << (*request_address_ + *count_).block_max() ;\n DVLOG(5) << \", request_address is \" << *request_address_;\n DVLOG(5) << \", sizeof(T) is \" << sizeof(T);\n DVLOG(5) << \", count is \" << *count_;\n DVLOG(5) << \", block_min is \" << request_address_->block_min();\n\n\n DVLOG(5) << \"Straddle: address is \" << *request_address_ ;\n DVLOG(5) << \", address + count is \" << *request_address_ + *count_;\n\n ptrdiff_t byte_diff = ( (*request_address_ + *count_ - 1).last_byte().block_max() - \n request_address_->first_byte().block_min() );\n\n DVLOG(5) << \"Straddle: address block max is \" << request_address_->block_max();\n DVLOG(5) << \" address + count block max is \" << (*request_address_ + *count_).block_max();\n DVLOG(5) << \" address + count -1 block max is \" << (*request_address_ + *count_ - 1).block_max();\n DVLOG(5) << \" difference is \" << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() );\n DVLOG(5) << \" multiplied difference is \" << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ) * sizeof(T);\n DVLOG(5) << \" address block min \" << request_address_->block_min();\n DVLOG(5) << \"Straddle: diff is \" << byte_diff << \" bs \" << block_size;\n num_messages_ = byte_diff \/ block_size;\n }\n\n if( num_messages_ > 1 ) DVLOG(5) << \"****************************** MULTI BLOCK CACHE REQUEST ******************************\";\n\n DVLOG(5) << \"Detecting straddle for sizeof(T):\" << sizeof(T)\n << \" count:\" << *count_\n << \" num_messages_:\" << num_messages_\n << \" request_address:\" << *request_address_;\n }\n\n void start_release() { \n if( !release_started_ ) {\n#ifdef VTRACE_FULL\n VT_TRACER(\"incoherent start_release\");\n#endif\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" issuing release for \" << *request_address_ \n << \" * \" << *count_ ;\n release_started_ = true;\n RequestArgs args;\n args.request_address = *request_address_;\n DVLOG(5) << \"Computing request_bytes from block_max \" << request_address_->first_byte().block_max() << \" and \" << *request_address_;\n args.reply_address = make_global( this );\n size_t offset = 0; \n size_t request_bytes = 0;\n size_t total_bytes = *count_ * sizeof(T);\n\n \/\/ allocate enough requests\/messages that we don't run out\n size_t nmsg = total_bytes \/ block_size + 2;\n\n Grappa::MessagePoolStatic<STACK_SIZE\/2> pool;\n \n for( size_t i = 0;\n offset < total_bytes; \n offset += request_bytes, i++) {\n\n request_bytes = args.request_address.first_byte().block_max() - args.request_address.first_byte();\n\n if( request_bytes > total_bytes - offset ) {\n request_bytes = total_bytes - offset;\n }\n\n DVLOG(5) << \"sending release request with \" << request_bytes\n << \" of total bytes = \" << *count_ * sizeof(T)\n << \" to \" << args.request_address;\n\n pool.send_message(args.request_address.core(),\n [args](void * payload, size_t payload_size) {\n incoherent_releaser_stats.count_release_ams( payload_size );\n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" received release request to \" << args.request_address\n << \" reply to \" << args.reply_address;\n memcpy( args.request_address.pointer(), payload, payload_size );\n \n auto reply_address = args.reply_address;\n Grappa::send_heap_message(args.reply_address.core(), [reply_address]{\n DVLOG(5) << \"Thread \" << CURRENT_THREAD << \" received release reply to \" << reply_address;\n reply_address.pointer()->release_reply();\n });\n \n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" sent release reply to \" << reply_address;\n },\n (char*)(*pointer_) + offset, request_bytes\n );\n\n \t\/\/ TODO: change type so we don't screw with pointer like this\n args.request_address = GlobalAddress<T>::Raw( args.request_address.raw_bits() + request_bytes );\n }\n DVLOG(5) << \"release started for \" << args.request_address;\n \n \/\/ blocks here waiting for messages to be sent\n }\n }\n\n void block_until_released() {\n if( !released_ ) {\n start_release();\n#ifdef VTRACE_FULL\n VT_TRACER(\"incoherent block_until_released\");\n#endif\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" ready to block on \" << *request_address_ \n << \" * \" << *count_ ;\n while( !released_ ) {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" blocking on \" << *request_address_ \n << \" * \" << *count_ ;\n if( !released_ ) {\n thread_ = CURRENT_THREAD;\n Grappa_suspend();\n thread_ = NULL;\n }\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" woke up for \" << *request_address_ \n << \" * \" << *count_ ;\n }\n }\n }\n\n void release_reply( ) { \n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" received release reply \";\n ++response_count_;\n if ( response_count_ == num_messages_ ) {\n released_ = true;\n if( thread_ != NULL ) {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD \n << \" waking Thread \" << thread_;\n Grappa_wake( thread_ );\n }\n }\n }\n\n bool released() const { return released_; }\n\n\n struct ReplyArgs {\n GlobalAddress< IncoherentReleaser > reply_address;\n void operator()() {\n DVLOG(5) << \"Thread \" << CURRENT_THREAD << \" received release reply to \" << reply_address;\n reply_address.pointer()->release_reply( );\n }\n };\n \n struct RequestArgs {\n GlobalAddress< T > request_address;\n GlobalAddress< IncoherentReleaser > reply_address;\n \n void operator()(void * payload, size_t payload_size) {\n incoherent_releaser_stats.count_release_ams( payload_size );\n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" received release request to \" << request_address\n << \" reply to \" << reply_address;\n memcpy( request_address.pointer(), payload, payload_size );\n ReplyArgs reply_args;\n reply_args.reply_address = reply_address;\n \n Grappa::send_heap_message(reply_address.node(), reply_args);\n \n DVLOG(5) << \"Thread \" << CURRENT_THREAD\n << \" sent release reply to \" << reply_address;\n }\n };\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include <stdio.h>\n\n#include \"extern.h\"\n#include \"configuration.h\"\n#include \"statistics.h\"\n#include \"database.h\"\n\nextern FILE *obj_f;\nextern FILE *mob_f;\n\nstd::vector<mobIndexData>mob_index(0);\nstd::vector<objIndexData>obj_index(0);\n\nindexData::indexData() :\n virt(0),\n pos(0),\n number(0),\n name(NULL),\n short_desc(NULL),\n long_desc(NULL),\n description(NULL),\n max_exist(-99),\n spec(0),\n weight(0)\n{\n}\n\nindexData & indexData::operator= (const indexData &a)\n{\n if (this == &a)\n return *this;\n\n virt = a.virt;\n pos = a.pos;\n number = a.number;\n delete [] name;\n delete [] short_desc;\n delete [] long_desc;\n delete [] description;\n name = mud_str_dup(a.name);\n short_desc = mud_str_dup(a.short_desc);\n long_desc = mud_str_dup(a.long_desc);\n description = mud_str_dup(a.description);\n\n max_exist = a.max_exist;\n spec = a.spec;\n weight = a.weight;\n\n return *this;\n}\n\nindexData::indexData(const indexData &a) :\n virt(a.virt),\n pos(a.pos),\n number(a.number),\n max_exist(a.max_exist),\n spec(a.spec),\n weight(a.weight)\n{\n name = mud_str_dup(a.name);\n short_desc = mud_str_dup(a.short_desc);\n long_desc = mud_str_dup(a.long_desc);\n description = mud_str_dup(a.description);\n}\n\nindexData::~indexData()\n{\n delete [] name;\n delete [] short_desc;\n delete [] long_desc;\n delete [] description;\n}\n\nmobIndexData::mobIndexData() :\n faction(-99),\n Class(-99),\n level(-99),\n race(-99),\n doesLoad(false),\n numberLoad(0)\n{\n}\n\nmobIndexData & mobIndexData::operator= (const mobIndexData &a)\n{\n if (this == &a)\n return *this;\n\n indexData::operator=(a);\n\n faction = a.faction;\n Class = a.Class;\n level = a.level;\n race = a.race;\n doesLoad = a.doesLoad;\n numberLoad = a.numberLoad;\n\n return *this;\n}\n\nmobIndexData::mobIndexData(const mobIndexData &a) :\n indexData(a),\n faction(a.faction),\n Class(a.Class),\n level(a.level),\n race(a.race),\n doesLoad(a.doesLoad),\n numberLoad(a.numberLoad)\n{\n}\n\nmobIndexData::~mobIndexData()\n{\n}\n\nobjIndexData::objIndexData() :\n ex_description(NULL),\n max_struct(-99),\n armor(-99),\n where_worn(0),\n itemtype(MAX_OBJ_TYPES),\n value(-99)\n{\n}\n\nobjIndexData & objIndexData::operator= (const objIndexData &a)\n{\n if (this == &a)\n return *this;\n\n indexData::operator=(a);\n\n \/\/ use copy operator;\n if (a.ex_description)\n ex_description = new extraDescription(*a.ex_description);\n else\n ex_description = NULL;\n\n max_struct = a.max_struct;\n armor = a.armor;\n where_worn = a.where_worn;\n itemtype = a.itemtype;\n value = a.value;\n\n int i;\n for(i=0;i<MAX_OBJ_AFFECT;++i){\n affected[i]=a.affected[i];\n }\n\n return *this;\n}\n\nobjIndexData::objIndexData(const objIndexData &a) :\n indexData(a),\n max_struct(a.max_struct),\n armor(a.armor),\n where_worn(a.where_worn),\n itemtype(a.itemtype),\n value(a.value)\n{\n \/\/ use copy operator;\n if (a.ex_description)\n ex_description = new extraDescription(*a.ex_description);\n else\n ex_description = NULL;\n\n int i;\n for(i=0;i<MAX_OBJ_AFFECT;++i){\n affected[i]=a.affected[i];\n }\n}\n\nobjIndexData::~objIndexData()\n{\n extraDescription *tmp;\n while ((tmp = ex_description)) {\n ex_description = tmp->next;\n delete tmp;\n }\n}\n\n\/\/ generate index table for object\nvoid generate_obj_index()\n{\n objIndexData *tmpi = NULL;\n extraDescription *new_descr;\n int i=0;\n\n \/\/ to prevent constant resizing (slows boot), declare an appropriate initial\n \/\/ size. Should be smallest power of 2 that will hold everything\n obj_index.reserve(8192);\n\n \/****** extra ******\/\n TDatabase extra_db(DB_SNEEZY);\n extra_db.query(\"select vnum, name, description from objextra order by vnum\");\n extra_db.fetchRow();\n\n \/****** affect ******\/\n TDatabase affect_db(DB_SNEEZY);\n affect_db.query(\"select vnum, type, mod1, mod2 from objaffect order by vnum\");\n affect_db.fetchRow();\n\n \/********************\/\n\n TDatabase db(DB_SNEEZY);\n db.query(\"select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum\");\n\n while(db.fetchRow()){\n tmpi = new objIndexData();\n if (!tmpi) {\n perror(\"indexData\");\n exit(0);\n }\n \n tmpi->virt=convertTo<int>(db[\"vnum\"]);\n tmpi->name=mud_str_dup(db[\"name\"]);\n tmpi->short_desc=mud_str_dup(db[\"short_desc\"]);\n tmpi->long_desc=mud_str_dup(db[\"long_desc\"]);\n tmpi->max_exist=convertTo<int>(db[\"max_exist\"]);\n\n \/\/ use 327 so we don't go over 32765 in calculation\n if (tmpi->max_exist < 327) {\n tmpi->max_exist *= (short) (stats.max_exist * 100);\n tmpi->max_exist \/= 100;\n }\n if (tmpi->max_exist)\n tmpi->max_exist = max(tmpi->max_exist, (short int) 1);\n \n\n tmpi->spec=convertTo<int>(db[\"spec_proc\"]);\n tmpi->weight=convertTo<float>(db[\"weight\"]);\n tmpi->max_struct=convertTo<int>(db[\"max_struct\"]);\n tmpi->where_worn=convertTo<int>(db[\"wear_flag\"]);\n tmpi->itemtype=convertTo<int>(db[\"type\"]);\n tmpi->value=convertTo<int>(db[\"price\"]);\n if(!db[\"action_desc\"].empty())\n tmpi->description=mud_str_dup(db[\"action_desc\"]);\n else tmpi->description=NULL;\n\n while(!extra_db[\"vnum\"].empty() && convertTo<int>(extra_db[\"vnum\"]) < tmpi->virt){\n extra_db.fetchRow();\n }\n\n while(!extra_db[\"vnum\"].empty() &&\n\t convertTo<int>(extra_db[\"vnum\"])==tmpi->virt){\n new_descr = new extraDescription();\n new_descr->keyword = mud_str_dup(extra_db[\"name\"]);\n new_descr->description = mud_str_dup(extra_db[\"description\"]);\n new_descr->next = tmpi->ex_description;\n tmpi->ex_description = new_descr;\n\n extra_db.fetchRow();\n }\n\n while(!affect_db[\"vnum\"].empty() &&\n\t convertTo<int>(affect_db[\"vnum\"]) < tmpi->virt){\n affect_db.fetchRow();\n }\n\n i=0;\n while(!affect_db[\"vnum\"].empty() &&\n\t convertTo<int>(affect_db[\"vnum\"])==tmpi->virt){\n tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db[\"type\"]));\n\n if (tmpi->affected[i].location == APPLY_SPELL)\n\ttmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db[\"mod1\"]));\n else\n\ttmpi->affected[i].modifier = convertTo<int>(affect_db[\"mod1\"]);\n \n tmpi->affected[i].modifier2 = convertTo<int>(affect_db[\"mod2\"]);\n tmpi->affected[i].type = TYPE_UNDEFINED;\n tmpi->affected[i].level = 0;\n tmpi->affected[i].bitvector = 0; \n\n affect_db.fetchRow();\n i++;\n }\n\n obj_index.push_back(*tmpi);\n delete tmpi;\n }\n}\n\n\n\n\/\/ generate index table for monster file \nvoid generate_mob_index()\n{\n mobIndexData *tmpi = NULL;\n TDatabase db(DB_SNEEZY);\n \n \/\/ to prevent constant resizing (slows boot), declare an appropriate initial\n \/\/ size. Should be smallest power of 2 that will hold everything\n mob_index.reserve(8192);\n\n \/\/ start by reading\n db.query(\"select * from mob\");\n\n while(db.fetchRow()){\n if (tmpi) {\n \/\/ push the previous one into the stack\n mob_index.push_back(*tmpi);\n delete tmpi;\n }\n\n \/\/ start a new data member\n tmpi = new mobIndexData();\n if (!tmpi) {\n perror(\"mobIndexData\");\n exit(0);\n }\n \n tmpi->virt = convertTo<int>(db[\"vnum\"]);\n \n \/\/ read the sstrings\n tmpi->name = mud_str_dup(db[\"name\"]);\n tmpi->short_desc = mud_str_dup(db[\"short_desc\"]);\n tmpi->long_desc = mud_str_dup(db[\"long_desc\"]);\n tmpi->description = mud_str_dup(db[\"description\"]);\n \n long fac=convertTo<int>(db[\"faction\"]);\n \n tmpi->faction = fac;\n \n long Class=convertTo<int>(db[\"class\"]);\n float arm=convertTo<int>(db[\"ac\"]);\n float hp=convertTo<int>(db[\"hpbonus\"]);\n float daml=convertTo<int>(db[\"damage_level\"]);\n \n long lev = (long)((arm + hp + daml) \/ 3);\n \n tmpi->Class = Class;\n tmpi->level = lev;\n \n long race=convertTo<int>(db[\"race\"]);\n long wgt=convertTo<int>(db[\"weight\"]);\n \n tmpi->race = race;\n tmpi->weight = wgt;\n \n long spec=convertTo<int>(db[\"spec_proc\"]);\n \n tmpi->spec = spec;\n \n long maxe=convertTo<int>(db[\"max_exist\"]);\n \n tmpi->max_exist = maxe;\n \n \/\/ handle some stat counters\n if (lev <= 5) {\n stats.mobs_1_5++;\n } else if (lev <= 10) {\n stats.mobs_6_10++;\n } else if (lev <= 15) {\n stats.mobs_11_15++;\n } else if (lev <= 20) {\n stats.mobs_16_20++;\n } else if (lev <= 25) {\n stats.mobs_21_25++;\n } else if (lev <= 30) {\n stats.mobs_26_30++;\n } else if (lev <= 40) {\n stats.mobs_31_40++;\n } else if (lev <= 50) {\n stats.mobs_41_50++;\n } else if (lev <= 60) {\n stats.mobs_51_60++;\n } else if (lev <= 70) {\n stats.mobs_61_70++;\n } else if (lev <= 100) {\n stats.mobs_71_100++;\n } else {\n stats.mobs_101_127++;\n }\n \/\/ end stat counters\n }\n \/\/ and push the last one into the stack\n \/\/ ... if it exists, ie. we have at least one mob.\n if (tmpi) {\n mob_index.push_back(*tmpi);\n delete tmpi;\n }\n}\n<commit_msg>Fixed ctags not finding mob_index<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include <stdio.h>\n\n#include \"extern.h\"\n#include \"configuration.h\"\n#include \"statistics.h\"\n#include \"database.h\"\n\nextern FILE *obj_f;\nextern FILE *mob_f;\n\nstd::vector<mobIndexData> mob_index;\nstd::vector<objIndexData> obj_index;\n\nindexData::indexData() :\n virt(0),\n pos(0),\n number(0),\n name(NULL),\n short_desc(NULL),\n long_desc(NULL),\n description(NULL),\n max_exist(-99),\n spec(0),\n weight(0)\n{\n}\n\nindexData & indexData::operator= (const indexData &a)\n{\n if (this == &a)\n return *this;\n\n virt = a.virt;\n pos = a.pos;\n number = a.number;\n delete [] name;\n delete [] short_desc;\n delete [] long_desc;\n delete [] description;\n name = mud_str_dup(a.name);\n short_desc = mud_str_dup(a.short_desc);\n long_desc = mud_str_dup(a.long_desc);\n description = mud_str_dup(a.description);\n\n max_exist = a.max_exist;\n spec = a.spec;\n weight = a.weight;\n\n return *this;\n}\n\nindexData::indexData(const indexData &a) :\n virt(a.virt),\n pos(a.pos),\n number(a.number),\n max_exist(a.max_exist),\n spec(a.spec),\n weight(a.weight)\n{\n name = mud_str_dup(a.name);\n short_desc = mud_str_dup(a.short_desc);\n long_desc = mud_str_dup(a.long_desc);\n description = mud_str_dup(a.description);\n}\n\nindexData::~indexData()\n{\n delete [] name;\n delete [] short_desc;\n delete [] long_desc;\n delete [] description;\n}\n\nmobIndexData::mobIndexData() :\n faction(-99),\n Class(-99),\n level(-99),\n race(-99),\n doesLoad(false),\n numberLoad(0)\n{\n}\n\nmobIndexData & mobIndexData::operator= (const mobIndexData &a)\n{\n if (this == &a)\n return *this;\n\n indexData::operator=(a);\n\n faction = a.faction;\n Class = a.Class;\n level = a.level;\n race = a.race;\n doesLoad = a.doesLoad;\n numberLoad = a.numberLoad;\n\n return *this;\n}\n\nmobIndexData::mobIndexData(const mobIndexData &a) :\n indexData(a),\n faction(a.faction),\n Class(a.Class),\n level(a.level),\n race(a.race),\n doesLoad(a.doesLoad),\n numberLoad(a.numberLoad)\n{\n}\n\nmobIndexData::~mobIndexData()\n{\n}\n\nobjIndexData::objIndexData() :\n ex_description(NULL),\n max_struct(-99),\n armor(-99),\n where_worn(0),\n itemtype(MAX_OBJ_TYPES),\n value(-99)\n{\n}\n\nobjIndexData & objIndexData::operator= (const objIndexData &a)\n{\n if (this == &a)\n return *this;\n\n indexData::operator=(a);\n\n \/\/ use copy operator;\n if (a.ex_description)\n ex_description = new extraDescription(*a.ex_description);\n else\n ex_description = NULL;\n\n max_struct = a.max_struct;\n armor = a.armor;\n where_worn = a.where_worn;\n itemtype = a.itemtype;\n value = a.value;\n\n int i;\n for(i=0;i<MAX_OBJ_AFFECT;++i){\n affected[i]=a.affected[i];\n }\n\n return *this;\n}\n\nobjIndexData::objIndexData(const objIndexData &a) :\n indexData(a),\n max_struct(a.max_struct),\n armor(a.armor),\n where_worn(a.where_worn),\n itemtype(a.itemtype),\n value(a.value)\n{\n \/\/ use copy operator;\n if (a.ex_description)\n ex_description = new extraDescription(*a.ex_description);\n else\n ex_description = NULL;\n\n int i;\n for(i=0;i<MAX_OBJ_AFFECT;++i){\n affected[i]=a.affected[i];\n }\n}\n\nobjIndexData::~objIndexData()\n{\n extraDescription *tmp;\n while ((tmp = ex_description)) {\n ex_description = tmp->next;\n delete tmp;\n }\n}\n\n\/\/ generate index table for object\nvoid generate_obj_index()\n{\n objIndexData *tmpi = NULL;\n extraDescription *new_descr;\n int i=0;\n\n \/\/ to prevent constant resizing (slows boot), declare an appropriate initial\n \/\/ size. Should be smallest power of 2 that will hold everything\n obj_index.reserve(8192);\n\n \/****** extra ******\/\n TDatabase extra_db(DB_SNEEZY);\n extra_db.query(\"select vnum, name, description from objextra order by vnum\");\n extra_db.fetchRow();\n\n \/****** affect ******\/\n TDatabase affect_db(DB_SNEEZY);\n affect_db.query(\"select vnum, type, mod1, mod2 from objaffect order by vnum\");\n affect_db.fetchRow();\n\n \/********************\/\n\n TDatabase db(DB_SNEEZY);\n db.query(\"select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum\");\n\n while(db.fetchRow()){\n tmpi = new objIndexData();\n if (!tmpi) {\n perror(\"indexData\");\n exit(0);\n }\n \n tmpi->virt=convertTo<int>(db[\"vnum\"]);\n tmpi->name=mud_str_dup(db[\"name\"]);\n tmpi->short_desc=mud_str_dup(db[\"short_desc\"]);\n tmpi->long_desc=mud_str_dup(db[\"long_desc\"]);\n tmpi->max_exist=convertTo<int>(db[\"max_exist\"]);\n\n \/\/ use 327 so we don't go over 32765 in calculation\n if (tmpi->max_exist < 327) {\n tmpi->max_exist *= (short) (stats.max_exist * 100);\n tmpi->max_exist \/= 100;\n }\n if (tmpi->max_exist)\n tmpi->max_exist = max(tmpi->max_exist, (short int) 1);\n \n\n tmpi->spec=convertTo<int>(db[\"spec_proc\"]);\n tmpi->weight=convertTo<float>(db[\"weight\"]);\n tmpi->max_struct=convertTo<int>(db[\"max_struct\"]);\n tmpi->where_worn=convertTo<int>(db[\"wear_flag\"]);\n tmpi->itemtype=convertTo<int>(db[\"type\"]);\n tmpi->value=convertTo<int>(db[\"price\"]);\n if(!db[\"action_desc\"].empty())\n tmpi->description=mud_str_dup(db[\"action_desc\"]);\n else tmpi->description=NULL;\n\n while(!extra_db[\"vnum\"].empty() && convertTo<int>(extra_db[\"vnum\"]) < tmpi->virt){\n extra_db.fetchRow();\n }\n\n while(!extra_db[\"vnum\"].empty() &&\n\t convertTo<int>(extra_db[\"vnum\"])==tmpi->virt){\n new_descr = new extraDescription();\n new_descr->keyword = mud_str_dup(extra_db[\"name\"]);\n new_descr->description = mud_str_dup(extra_db[\"description\"]);\n new_descr->next = tmpi->ex_description;\n tmpi->ex_description = new_descr;\n\n extra_db.fetchRow();\n }\n\n while(!affect_db[\"vnum\"].empty() &&\n\t convertTo<int>(affect_db[\"vnum\"]) < tmpi->virt){\n affect_db.fetchRow();\n }\n\n i=0;\n while(!affect_db[\"vnum\"].empty() &&\n\t convertTo<int>(affect_db[\"vnum\"])==tmpi->virt){\n tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db[\"type\"]));\n\n if (tmpi->affected[i].location == APPLY_SPELL)\n\ttmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db[\"mod1\"]));\n else\n\ttmpi->affected[i].modifier = convertTo<int>(affect_db[\"mod1\"]);\n \n tmpi->affected[i].modifier2 = convertTo<int>(affect_db[\"mod2\"]);\n tmpi->affected[i].type = TYPE_UNDEFINED;\n tmpi->affected[i].level = 0;\n tmpi->affected[i].bitvector = 0; \n\n affect_db.fetchRow();\n i++;\n }\n\n obj_index.push_back(*tmpi);\n delete tmpi;\n }\n}\n\n\n\n\/\/ generate index table for monster file \nvoid generate_mob_index()\n{\n mobIndexData *tmpi = NULL;\n TDatabase db(DB_SNEEZY);\n \n \/\/ to prevent constant resizing (slows boot), declare an appropriate initial\n \/\/ size. Should be smallest power of 2 that will hold everything\n mob_index.reserve(8192);\n\n \/\/ start by reading\n db.query(\"select * from mob\");\n\n while(db.fetchRow()){\n if (tmpi) {\n \/\/ push the previous one into the stack\n mob_index.push_back(*tmpi);\n delete tmpi;\n }\n\n \/\/ start a new data member\n tmpi = new mobIndexData();\n if (!tmpi) {\n perror(\"mobIndexData\");\n exit(0);\n }\n \n tmpi->virt = convertTo<int>(db[\"vnum\"]);\n \n \/\/ read the sstrings\n tmpi->name = mud_str_dup(db[\"name\"]);\n tmpi->short_desc = mud_str_dup(db[\"short_desc\"]);\n tmpi->long_desc = mud_str_dup(db[\"long_desc\"]);\n tmpi->description = mud_str_dup(db[\"description\"]);\n \n long fac=convertTo<int>(db[\"faction\"]);\n \n tmpi->faction = fac;\n \n long Class=convertTo<int>(db[\"class\"]);\n float arm=convertTo<int>(db[\"ac\"]);\n float hp=convertTo<int>(db[\"hpbonus\"]);\n float daml=convertTo<int>(db[\"damage_level\"]);\n \n long lev = (long)((arm + hp + daml) \/ 3);\n \n tmpi->Class = Class;\n tmpi->level = lev;\n \n long race=convertTo<int>(db[\"race\"]);\n long wgt=convertTo<int>(db[\"weight\"]);\n \n tmpi->race = race;\n tmpi->weight = wgt;\n \n long spec=convertTo<int>(db[\"spec_proc\"]);\n \n tmpi->spec = spec;\n \n long maxe=convertTo<int>(db[\"max_exist\"]);\n \n tmpi->max_exist = maxe;\n \n \/\/ handle some stat counters\n if (lev <= 5) {\n stats.mobs_1_5++;\n } else if (lev <= 10) {\n stats.mobs_6_10++;\n } else if (lev <= 15) {\n stats.mobs_11_15++;\n } else if (lev <= 20) {\n stats.mobs_16_20++;\n } else if (lev <= 25) {\n stats.mobs_21_25++;\n } else if (lev <= 30) {\n stats.mobs_26_30++;\n } else if (lev <= 40) {\n stats.mobs_31_40++;\n } else if (lev <= 50) {\n stats.mobs_41_50++;\n } else if (lev <= 60) {\n stats.mobs_51_60++;\n } else if (lev <= 70) {\n stats.mobs_61_70++;\n } else if (lev <= 100) {\n stats.mobs_71_100++;\n } else {\n stats.mobs_101_127++;\n }\n \/\/ end stat counters\n }\n \/\/ and push the last one into the stack\n \/\/ ... if it exists, ie. we have at least one mob.\n if (tmpi) {\n mob_index.push_back(*tmpi);\n delete tmpi;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"provider.h\"\n#include \"iproviderplugin.h\"\n#include \"handlesignalrouter.h\"\n#include \"sconnect.h\"\n#include \"contextkitplugin.h\"\n#include \"logging.h\"\n#include \"loggingfeatures.h\"\n#include <QTimer>\n#include <QMutexLocker>\n#include <QCoreApplication>\n#include <QThread>\n#include <QLibrary>\n\nnamespace ContextSubscriber {\n\n\/*!\n \\class IProviderPlugin\n \\brief Interface for provider plugins.\n\n Note: this interface is private, currently it is not advised to use\n it and create ContextKit subscriber plugins on your own, we can and\n will change this interface anytime in the future even between small\n bugfix releases.\n\n Every Provider instance contains exactly one plugin (pointer) with\n this interface which is constructed on initialization time and never\n change after that. This way the concrete protocol (dbus, shared\n memory, etc.) between the library and the provider is abstracted.\n\n The Provider instance communicates need for subscribe and\n unsubscribe calls (on the wire) using the \\c subscribe and \\c\n unsubscribe methods.\n\n The plugin can fail or became ready anytime because of things\n happening on the wire inside the plugin (socket closed, dbus service\n appears\/disappears). Whenever the plugin has new information about\n this it should emit the signal \\c ready or \\c failed accordingly.\n\n When the plugin is ready, it has to be able to handle \\c subscribe\n and \\c unsubscribe function calls. Also, after emitting \\c ready it\n should be in a state where it is not subscribed to anything on the\n wire, since immediately after \\c ready is emitted, the provider will\n place a subscribe call with all of the properties that should be\n subscribed.\n\n Subscription failures or successes can be signaled with emitting \\c\n subscribeFailed and \\c subscribeFinished.\n\n At last, but not least, the plugin can emit \\c valueChanged, when it\n has a new value for any property. It is not required to only signal\n new values, the library takes care of keeping the old value and only\n emit change signals to the upper layers if the new value is really\n new.\n\n An implementation of this interface doesn't have to care about\n threads at all, all of the methods, starting from the constructor\n will be only called from inside the Qt event loop of the main\n thread. This means that neither the constructor nor the \\c\n subscribe, \\c unsubscribe calls should block. They have to finish\n as soon as possible and signal the results later via signals.\n\n \\class Provider\n \\brief Connects to a group of properties via the help of a plugin.\n\n Each instance of this class keeps a plugin dependent communication\n channel (DBus, shared memory, etc.) open and handles subscriptions,\n value changes of the properties belonging to the provider on the\n other end of the channel.\n\n This class is thread safe, the \\c instance, \\c subscribe and \\c\n unsubscribe methods can be called from any threads. However this\n class also guarantees that the signal \\c subscribeFinished and \\c\n valueChanged will be always emitted from inside the main thread's\n main loop.\n\n \\fn void Provider::subscribeFinished(QSet<QString> keys)\n \\brief Emitted when the subscription procedure for \\c keys finished\n (either succeeded, either failed) *\/\n\n\/\/\/ Stores the passed plugin name and construction paramater, then\n\/\/\/ moves into the main thread and queues a constructPlugin call.\nProvider::Provider(const QString &plugin, const QString &constructionString)\n : plugin(0), pluginState(INITIALIZING), pluginName(plugin), constructionString(constructionString)\n{\n \/\/ Move the PropertyHandle (and all children) to main thread.\n moveToThread(QCoreApplication::instance()->thread());\n\n queueOnce(\"constructPlugin\");\n}\n\n\/\/\/ Decides which plugin to instantiate based on the \\c plugin passed\n\/\/\/ to the constructor. Always called in the main loop after the\n\/\/\/ constructor is finished. Each plugin library implements a\n\/\/\/ function which can create new instances of that plugin (TODO: come\n\/\/\/ up with the name of the function).\nvoid Provider::constructPlugin()\n{\n contextDebug() << F_PLUGINS;\n if (pluginName == \"contextkit-dbus\") {\n plugin = contextKitPluginFactory(constructionString);\n }\n else if (pluginName.startsWith(\"\/\")) { \/\/ Require the plugin name to start with \/\n \/\/ Enable overriding the plugin location with an environment variable\n const char *pluginPath = getenv(\"CONTEXT_SUBSCRIBER_PLUGINS\");\n if (! pluginPath)\n pluginPath = DEFAULT_CONTEXT_SUBSCRIBER_PLUGINS;\n\n QString pluginFilename(pluginPath);\n \/\/ Allow pluginPath to have a trailing \/ or not\n if (pluginFilename.endsWith(\"\/\")) {\n pluginFilename.chop(1);\n }\n\n pluginFilename.append(pluginName);\n\n QLibrary library(pluginFilename);\n library.load();\n\n if (library.isLoaded()) {\n PluginFactoryFunc factory = (PluginFactoryFunc) library.resolve(\"pluginFactory\");\n if (factory) {\n contextDebug() << \"Resolved factory function\";\n plugin = factory(constructionString);\n } else {\n contextCritical() << \"Error resolving function pluginFactory from plugin\" << pluginFilename;\n }\n }\n else {\n contextCritical() << \"Error loading plugin\" << pluginFilename << \":\" << library.errorString();\n }\n }\n else {\n contextCritical() << \"Illegal plugin name\" << pluginName << \", doesn't start with \/\";\n }\n\n if (plugin == 0) {\n pluginState = FAILED;\n handleSubscribes();\n return;\n }\n\n \/\/ Connect the signal of changing values to the class who handles it\n HandleSignalRouter* handleSignalRouter = HandleSignalRouter::instance();\n sconnect(plugin, SIGNAL(valueChanged(QString, QVariant)),\n this, SLOT(onPluginValueChanged(QString, QVariant)));\n sconnect(this, SIGNAL(valueChanged(QString, QVariant)),\n handleSignalRouter, SLOT(onValueChanged(QString, QVariant)));\n\n sconnect(plugin, SIGNAL(ready()),\n this, SLOT(onPluginReady()));\n sconnect(plugin, SIGNAL(failed(QString)),\n this, SLOT(onPluginFailed(QString)));\n\n sconnect(plugin, SIGNAL(subscribeFinished(QString)),\n this, SLOT(onPluginSubscribeFinished(QString)), Qt::QueuedConnection);\n sconnect(plugin, SIGNAL(subscribeFailed(QString, QString)),\n this, SLOT(onPluginSubscribeFailed(QString, QString)), Qt::QueuedConnection);\n sconnect(this, SIGNAL(subscribeFinished(QString)),\n handleSignalRouter, SLOT(onSubscribeFinished(QString)));\n}\n\n\/\/\/ Updates \\c pluginState to \\c READY and requests subscription for\n\/\/\/ the keys that should be subscribed.\nvoid Provider::onPluginReady()\n{\n contextDebug();\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Renew the subscriptions (if any).\n \/\/ Renewing happens when a provider has disappeared and now it appeared again.\n toUnsubscribe.clear();\n toSubscribe.clear();\n toSubscribe += subscribedKeys;\n pluginState = READY;\n lock.unlock();\n handleSubscribes();\n}\n\n\/\/\/ Updates \\c pluginState to \\c FAILED and signals subscribeFinished\n\/\/\/ for keys we are trying to subscribe to.\nvoid Provider::onPluginFailed(QString error)\n{\n contextWarning() << error;\n\n QMutexLocker lock(&subscribeLock);\n pluginState = FAILED;\n lock.unlock();\n handleSubscribes();\n}\n\n\/\/\/ The plugin has finished subscribing to a key, signals this fact to\n\/\/\/ the upper layer. The final API for this is the\n\/\/\/ <tt>waitForSubscription()<\/tt> method in \\c ContextProperty.\nvoid Provider::signalSubscribeFinished(QString key)\n{\n QMutexLocker lock(&subscribeLock);\n if (subscribedKeys.contains(key))\n emit subscribeFinished(key);\n}\n\n\/\/\/ Forwards the call to \\c signalSubscribeFinished.\nvoid Provider::onPluginSubscribeFinished(QString key)\n{\n contextDebug() << key;\n\n signalSubscribeFinished(key);\n}\n\n\/\/\/ Forwards the call to \\c signalSubscribeFinished, after logging a\n\/\/\/ warning.\nvoid Provider::onPluginSubscribeFailed(QString key, QString error)\n{\n contextWarning() << key << error;\n\n signalSubscribeFinished(key);\n}\n\n\/\/\/ Schedules a property to be subscribed to. Returns true if and\n\/\/\/ only if the main loop has to run for the subscription to be\n\/\/\/ finalized.\nbool Provider::subscribe(const QString &key)\n{\n contextDebug() << \"plugin\" << pluginName << constructionString;\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Note: the intention is saved in all cases; whether we can really subscribe or not.\n subscribedKeys.insert(key);\n\n \/\/ If the key was scheduled to be unsubscribed then remove that\n \/\/ scheduling, and return false.\n if (toUnsubscribe.contains(key)) {\n toUnsubscribe.remove(key);\n return false;\n }\n\n \/\/ Schedule the key to be subscribed to and return true\n contextDebug() << \"Inserting the key to toSubscribe\" << QThread::currentThread();\n\n \/\/ Really schedule the key to be subscribed to\n toSubscribe.insert(key);\n\n queueOnce(\"handleSubscribes\");\n\n return true;\n}\n\n\/\/\/ Schedules a property to be unsubscribed from when the main loop is\n\/\/\/ entered the next time.\nvoid Provider::unsubscribe(const QString &key)\n{\n contextDebug() << \"Provider::unsubscribe, plugin\" << pluginName << constructionString;\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Save the intention of the higher level\n subscribedKeys.remove(key);\n\n \/\/ Schedule the key to be unsubscribed from\n if (toSubscribe.contains(key)) {\n \/\/ The key was scheduled to be subscribed\n \/\/ Remove that scheduling, and nothing else needs to be done.\n toSubscribe.remove(key);\n }\n else {\n \/\/ Really schedule the key to be unsubscribed from\n toUnsubscribe.insert(key);\n\n queueOnce(\"handleSubscribes\");\n }\n}\n\n\/\/\/ Executed when the main loop is entered and we have previously\n\/\/\/ scheduled subscriptions \/ unsubscriptions.\nvoid Provider::handleSubscribes()\n{\n contextDebug() << \"Provider::handleSubscribes in thread\" << QThread::currentThread();\n\n QMutexLocker lock(&subscribeLock);\n\n switch (pluginState) {\n case READY:\n if (toSubscribe.size() > 0) plugin->subscribe(toSubscribe);\n if (toUnsubscribe.size() > 0) plugin->unsubscribe(toUnsubscribe);\n toSubscribe.clear();\n toUnsubscribe.clear();\n break;\n case FAILED:\n \/\/ it failed for good.\n contextDebug() << \"Plugin init has failed\";\n if (toSubscribe.size() > 0)\n foreach (QString key, toSubscribe)\n emit subscribeFinished(key);\n toSubscribe.clear();\n toUnsubscribe.clear();\n break;\n case INITIALIZING:\n \/\/ we just have to wait,\n break;\n }\n\n contextDebug() << \"Provider::handleSubscribes processed\";\n}\n\n\/\/\/ Forwards the \\c newValue for \\c key received from the plugin to\n\/\/\/ the upper layers via \\c HandleSignalRouter.\nvoid Provider::onPluginValueChanged(QString key, QVariant newValue)\n{\n QMutexLocker lock(&subscribeLock);\n if (subscribedKeys.contains(key))\n emit valueChanged(key, newValue);\n else\n contextWarning() << \"Received a property not subscribed to:\" << key;\n}\n\n\/\/\/ Returns a singleton for the named \\c plugin with the \\c constructionString.\nProvider* Provider::instance(const QString& plugin, const QString& constructionString)\n{\n \/\/ Singleton instance container\n \/\/ plugin path, constructionstring -> Provider\n static QMap<QPair<QString, QString>, Provider*> providerInstances;\n QPair<QString, QString> lookupValue(plugin, constructionString);\n\n static QMutex providerInstancesLock;\n QMutexLocker locker(&providerInstancesLock);\n if (!providerInstances.contains(lookupValue))\n providerInstances.insert(lookupValue, new Provider(plugin, constructionString));\n\n contextDebug() << \"Returning provider instance for\" << plugin << \":\" << constructionString;\n\n return providerInstances[lookupValue];\n}\n\n} \/\/ end namespace\n<commit_msg>libcontextsubscriber documentation: Small clarification to the plugin documentation.<commit_after>\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"provider.h\"\n#include \"iproviderplugin.h\"\n#include \"handlesignalrouter.h\"\n#include \"sconnect.h\"\n#include \"contextkitplugin.h\"\n#include \"logging.h\"\n#include \"loggingfeatures.h\"\n#include <QTimer>\n#include <QMutexLocker>\n#include <QCoreApplication>\n#include <QThread>\n#include <QLibrary>\n\nnamespace ContextSubscriber {\n\n\/*!\n \\class IProviderPlugin\n \\brief Interface for provider plugins.\n\n Note: this interface is private, currently it is not advised to use\n it and create ContextKit subscriber plugins on your own, we can and\n will change this interface anytime in the future even between small\n bugfix releases.\n\n Every Provider instance contains exactly one plugin (pointer) with\n this interface which is constructed on initialization time and never\n change after that. This way the concrete protocol (dbus, shared\n memory, etc.) between the library and the provider is abstracted.\n\n The Provider instance communicates need for subscribe and\n unsubscribe calls (on the wire) using the \\c subscribe and \\c\n unsubscribe methods.\n\n When the plugin is constructed, it should emit the signal ready()\n when it is ready to take in subscriptions. However, the signal\n ready() should not be emitted in the plugin constructor. If the\n plugin is able to take in subscriptions immediately, you can use\n QMetaObject::invokeMethod with QueuedConnection to emit the signal\n when the main loop is entered the next time.\n\n The plugin can fail or became ready again anytime because of things\n happening on the wire inside the plugin (socket closed, dbus service\n appears\/disappears). Whenever the plugin has new information about\n this it should emit the signal \\c ready or \\c failed accordingly.\n\n When the plugin is ready, it has to be able to handle \\c subscribe\n and \\c unsubscribe function calls. Also, after emitting \\c ready it\n should be in a state where it is not subscribed to anything on the\n wire, since immediately after \\c ready is emitted, the provider will\n place a subscribe call with all of the properties that should be\n subscribed.\n\n Subscription failures or successes can be signaled with emitting \\c\n subscribeFailed and \\c subscribeFinished.\n\n At last, but not least, the plugin can emit \\c valueChanged, when it\n has a new value for any property. It is not required to only signal\n new values, the library takes care of keeping the old value and only\n emit change signals to the upper layers if the new value is really\n new.\n\n An implementation of this interface doesn't have to care about\n threads at all, all of the methods, starting from the constructor\n will be only called from inside the Qt event loop of the main\n thread. This means that neither the constructor nor the \\c\n subscribe, \\c unsubscribe calls should block. They have to finish\n as soon as possible and signal the results later via signals.\n\n \\class Provider\n \\brief Connects to a group of properties via the help of a plugin.\n\n Each instance of this class keeps a plugin dependent communication\n channel (DBus, shared memory, etc.) open and handles subscriptions,\n value changes of the properties belonging to the provider on the\n other end of the channel.\n\n This class is thread safe, the \\c instance, \\c subscribe and \\c\n unsubscribe methods can be called from any threads. However this\n class also guarantees that the signal \\c subscribeFinished and \\c\n valueChanged will be always emitted from inside the main thread's\n main loop.\n\n \\fn void Provider::subscribeFinished(QSet<QString> keys)\n \\brief Emitted when the subscription procedure for \\c keys finished\n (either succeeded, either failed) *\/\n\n\/\/\/ Stores the passed plugin name and construction paramater, then\n\/\/\/ moves into the main thread and queues a constructPlugin call.\nProvider::Provider(const QString &plugin, const QString &constructionString)\n : plugin(0), pluginState(INITIALIZING), pluginName(plugin), constructionString(constructionString)\n{\n \/\/ Move the PropertyHandle (and all children) to main thread.\n moveToThread(QCoreApplication::instance()->thread());\n\n queueOnce(\"constructPlugin\");\n}\n\n\/\/\/ Decides which plugin to instantiate based on the \\c plugin passed\n\/\/\/ to the constructor. Always called in the main loop after the\n\/\/\/ constructor is finished. Each plugin library implements a\n\/\/\/ function which can create new instances of that plugin (TODO: come\n\/\/\/ up with the name of the function).\nvoid Provider::constructPlugin()\n{\n contextDebug() << F_PLUGINS;\n if (pluginName == \"contextkit-dbus\") {\n plugin = contextKitPluginFactory(constructionString);\n }\n else if (pluginName.startsWith(\"\/\")) { \/\/ Require the plugin name to start with \/\n \/\/ Enable overriding the plugin location with an environment variable\n const char *pluginPath = getenv(\"CONTEXT_SUBSCRIBER_PLUGINS\");\n if (! pluginPath)\n pluginPath = DEFAULT_CONTEXT_SUBSCRIBER_PLUGINS;\n\n QString pluginFilename(pluginPath);\n \/\/ Allow pluginPath to have a trailing \/ or not\n if (pluginFilename.endsWith(\"\/\")) {\n pluginFilename.chop(1);\n }\n\n pluginFilename.append(pluginName);\n\n QLibrary library(pluginFilename);\n library.load();\n\n if (library.isLoaded()) {\n PluginFactoryFunc factory = (PluginFactoryFunc) library.resolve(\"pluginFactory\");\n if (factory) {\n contextDebug() << \"Resolved factory function\";\n plugin = factory(constructionString);\n } else {\n contextCritical() << \"Error resolving function pluginFactory from plugin\" << pluginFilename;\n }\n }\n else {\n contextCritical() << \"Error loading plugin\" << pluginFilename << \":\" << library.errorString();\n }\n }\n else {\n contextCritical() << \"Illegal plugin name\" << pluginName << \", doesn't start with \/\";\n }\n\n if (plugin == 0) {\n pluginState = FAILED;\n handleSubscribes();\n return;\n }\n\n \/\/ Connect the signal of changing values to the class who handles it\n HandleSignalRouter* handleSignalRouter = HandleSignalRouter::instance();\n sconnect(plugin, SIGNAL(valueChanged(QString, QVariant)),\n this, SLOT(onPluginValueChanged(QString, QVariant)));\n sconnect(this, SIGNAL(valueChanged(QString, QVariant)),\n handleSignalRouter, SLOT(onValueChanged(QString, QVariant)));\n\n sconnect(plugin, SIGNAL(ready()),\n this, SLOT(onPluginReady()));\n sconnect(plugin, SIGNAL(failed(QString)),\n this, SLOT(onPluginFailed(QString)));\n\n sconnect(plugin, SIGNAL(subscribeFinished(QString)),\n this, SLOT(onPluginSubscribeFinished(QString)), Qt::QueuedConnection);\n sconnect(plugin, SIGNAL(subscribeFailed(QString, QString)),\n this, SLOT(onPluginSubscribeFailed(QString, QString)), Qt::QueuedConnection);\n sconnect(this, SIGNAL(subscribeFinished(QString)),\n handleSignalRouter, SLOT(onSubscribeFinished(QString)));\n}\n\n\/\/\/ Updates \\c pluginState to \\c READY and requests subscription for\n\/\/\/ the keys that should be subscribed.\nvoid Provider::onPluginReady()\n{\n contextDebug();\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Renew the subscriptions (if any).\n \/\/ Renewing happens when a provider has disappeared and now it appeared again.\n toUnsubscribe.clear();\n toSubscribe.clear();\n toSubscribe += subscribedKeys;\n pluginState = READY;\n lock.unlock();\n handleSubscribes();\n}\n\n\/\/\/ Updates \\c pluginState to \\c FAILED and signals subscribeFinished\n\/\/\/ for keys we are trying to subscribe to.\nvoid Provider::onPluginFailed(QString error)\n{\n contextWarning() << error;\n\n QMutexLocker lock(&subscribeLock);\n pluginState = FAILED;\n lock.unlock();\n handleSubscribes();\n}\n\n\/\/\/ The plugin has finished subscribing to a key, signals this fact to\n\/\/\/ the upper layer. The final API for this is the\n\/\/\/ <tt>waitForSubscription()<\/tt> method in \\c ContextProperty.\nvoid Provider::signalSubscribeFinished(QString key)\n{\n QMutexLocker lock(&subscribeLock);\n if (subscribedKeys.contains(key))\n emit subscribeFinished(key);\n}\n\n\/\/\/ Forwards the call to \\c signalSubscribeFinished.\nvoid Provider::onPluginSubscribeFinished(QString key)\n{\n contextDebug() << key;\n\n signalSubscribeFinished(key);\n}\n\n\/\/\/ Forwards the call to \\c signalSubscribeFinished, after logging a\n\/\/\/ warning.\nvoid Provider::onPluginSubscribeFailed(QString key, QString error)\n{\n contextWarning() << key << error;\n\n signalSubscribeFinished(key);\n}\n\n\/\/\/ Schedules a property to be subscribed to. Returns true if and\n\/\/\/ only if the main loop has to run for the subscription to be\n\/\/\/ finalized.\nbool Provider::subscribe(const QString &key)\n{\n contextDebug() << \"plugin\" << pluginName << constructionString;\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Note: the intention is saved in all cases; whether we can really subscribe or not.\n subscribedKeys.insert(key);\n\n \/\/ If the key was scheduled to be unsubscribed then remove that\n \/\/ scheduling, and return false.\n if (toUnsubscribe.contains(key)) {\n toUnsubscribe.remove(key);\n return false;\n }\n\n \/\/ Schedule the key to be subscribed to and return true\n contextDebug() << \"Inserting the key to toSubscribe\" << QThread::currentThread();\n\n \/\/ Really schedule the key to be subscribed to\n toSubscribe.insert(key);\n\n queueOnce(\"handleSubscribes\");\n\n return true;\n}\n\n\/\/\/ Schedules a property to be unsubscribed from when the main loop is\n\/\/\/ entered the next time.\nvoid Provider::unsubscribe(const QString &key)\n{\n contextDebug() << \"Provider::unsubscribe, plugin\" << pluginName << constructionString;\n\n QMutexLocker lock(&subscribeLock);\n \/\/ Save the intention of the higher level\n subscribedKeys.remove(key);\n\n \/\/ Schedule the key to be unsubscribed from\n if (toSubscribe.contains(key)) {\n \/\/ The key was scheduled to be subscribed\n \/\/ Remove that scheduling, and nothing else needs to be done.\n toSubscribe.remove(key);\n }\n else {\n \/\/ Really schedule the key to be unsubscribed from\n toUnsubscribe.insert(key);\n\n queueOnce(\"handleSubscribes\");\n }\n}\n\n\/\/\/ Executed when the main loop is entered and we have previously\n\/\/\/ scheduled subscriptions \/ unsubscriptions.\nvoid Provider::handleSubscribes()\n{\n contextDebug() << \"Provider::handleSubscribes in thread\" << QThread::currentThread();\n\n QMutexLocker lock(&subscribeLock);\n\n switch (pluginState) {\n case READY:\n if (toSubscribe.size() > 0) plugin->subscribe(toSubscribe);\n if (toUnsubscribe.size() > 0) plugin->unsubscribe(toUnsubscribe);\n toSubscribe.clear();\n toUnsubscribe.clear();\n break;\n case FAILED:\n \/\/ it failed for good.\n contextDebug() << \"Plugin init has failed\";\n if (toSubscribe.size() > 0)\n foreach (QString key, toSubscribe)\n emit subscribeFinished(key);\n toSubscribe.clear();\n toUnsubscribe.clear();\n break;\n case INITIALIZING:\n \/\/ we just have to wait,\n break;\n }\n\n contextDebug() << \"Provider::handleSubscribes processed\";\n}\n\n\/\/\/ Forwards the \\c newValue for \\c key received from the plugin to\n\/\/\/ the upper layers via \\c HandleSignalRouter.\nvoid Provider::onPluginValueChanged(QString key, QVariant newValue)\n{\n QMutexLocker lock(&subscribeLock);\n if (subscribedKeys.contains(key))\n emit valueChanged(key, newValue);\n else\n contextWarning() << \"Received a property not subscribed to:\" << key;\n}\n\n\/\/\/ Returns a singleton for the named \\c plugin with the \\c constructionString.\nProvider* Provider::instance(const QString& plugin, const QString& constructionString)\n{\n \/\/ Singleton instance container\n \/\/ plugin path, constructionstring -> Provider\n static QMap<QPair<QString, QString>, Provider*> providerInstances;\n QPair<QString, QString> lookupValue(plugin, constructionString);\n\n static QMutex providerInstancesLock;\n QMutexLocker locker(&providerInstancesLock);\n if (!providerInstances.contains(lookupValue))\n providerInstances.insert(lookupValue, new Provider(plugin, constructionString));\n\n contextDebug() << \"Returning provider instance for\" << plugin << \":\" << constructionString;\n\n return providerInstances[lookupValue];\n}\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n kopeteemoticons.cpp - Kopete Preferences Container-Class\n\n Copyright (c) 2002 by Stefan Gehn <sgehn@gmx.net>\n Copyright (c) 2002 by Olivier Goffart <ogoffart@tiscalinet.be>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"kopeteemoticons.h\"\n\n#include \"kopeteprefs.h\"\n\n#include <qdom.h>\n#include <qfile.h>\n#include <qregexp.h>\n#include <qstylesheet.h>\n#include <qimage.h>\n\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kstandarddirs.h>\n\nKopeteEmoticons *KopeteEmoticons::s_instance = 0L;\n\nKopeteEmoticons *KopeteEmoticons::emoticons()\n{\n\tif( !s_instance )\n\t\ts_instance = new KopeteEmoticons;\n\treturn s_instance;\n}\n\nKopeteEmoticons::KopeteEmoticons( const QString &theme ) : QObject( kapp, \"KopeteEmoticons\" )\n{\n\/\/\tkdDebug(14010) << \"KopeteEmoticons::KopeteEmoticons\" << endl;\n\tif(theme.isNull())\n\t{\n\t\tinitEmoticons();\n\t\tconnect( KopetePrefs::prefs(), SIGNAL(saved()), this, SLOT(initEmoticons()) );\n\t}\n\telse\n\t{\n\t\tinitEmoticons( theme );\n\t}\n}\n\nvoid KopeteEmoticons::addIfPossible( const QString& filenameNoExt, QStringList emoticons )\n{\n\tKStandardDirs *dir = KGlobal::dirs();\n\tQString pic;\n\n\t\/\/maybe an extention was given, so try to find the exact file\n\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) + m_theme +\n\t\tQString::fromLatin1( \"\/\" ) + filenameNoExt );\n\n\tif( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) + m_theme +\n\t\t\tQString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".mng\" ) );\n\tif ( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\t\tm_theme + QString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".png\" ) );\n\tif ( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\t\tm_theme + QString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".gif\" ) );\n\n\tif( !pic.isNull() ) \/\/ only add if we found one file\n\t{\n\/\/\t\tkdDebug(14010) << \"KopeteEmoticons::addIfPossible : found pixmap for emoticons\" <<endl;\n\t\tmap[pic] = emoticons;\n\t}\n}\n\nvoid KopeteEmoticons::initEmoticons( const QString &theme )\n{\n\tif(theme.isNull())\n\t{\n\t\tif ( m_theme == KopetePrefs::prefs()->iconTheme() )\n\t\t\treturn;\n\n\t\tm_theme = KopetePrefs::prefs()->iconTheme();\n\t}\n\telse\n\t\tm_theme = theme;\n\n\/\/\tkdDebug(14010) << k_funcinfo << \"Called\" << endl;\n\tmap.clear(); \/\/ empty the mapping\n\n\tQDomDocument emoticonMap( QString::fromLatin1( \"messaging-emoticon-map\" ) );\n\tQString filename = KGlobal::dirs()->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\tm_theme + QString::fromLatin1( \"\/emoticons.xml\" ) );\n\n\tif( filename.isEmpty() )\n\t{\n\t\tkdDebug(14010) << \"KopeteEmoticons::initEmoticons : WARNING: emoticon-map not found\" <<endl;\n\t\treturn ;\n\t}\n\n\tQFile mapFile( filename );\n\tmapFile.open( IO_ReadOnly );\n\temoticonMap.setContent( &mapFile );\n\n\tQDomElement list = emoticonMap.documentElement();\n\tQDomNode node = list.firstChild();\n\twhile( !node.isNull() )\n\t{\n\t\tQDomElement element = node.toElement();\n\t\tif( !element.isNull() )\n\t\t{\n\t\t\tif( element.tagName() == QString::fromLatin1( \"emoticon\" ) )\n\t\t\t{\n\t\t\t\tQString emoticon_file = element.attribute(\n\t\t\t\t\tQString::fromLatin1( \"file\" ), QString::null );\n\t\t\t\tQStringList items;\n\n\t\t\t\tQDomNode emoticonNode = node.firstChild();\n\t\t\t\twhile( !emoticonNode.isNull() )\n\t\t\t\t{\n\t\t\t\t\tQDomElement emoticonElement = emoticonNode.toElement();\n\t\t\t\t\tif( !emoticonElement.isNull() )\n\t\t\t\t\t{\n\t\t\t\t\t\tif( emoticonElement.tagName() == QString::fromLatin1( \"string\" ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\titems << emoticonElement.text();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkdDebug(14010) << k_funcinfo <<\n\t\t\t\t\t\t\t\t\"Warning: Unknown element '\" << element.tagName() <<\n\t\t\t\t\t\t\t\t\"' in emoticon data\" << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\temoticonNode = emoticonNode.nextSibling();\n\t\t\t\t}\n\n\t\t\t\taddIfPossible ( emoticon_file, items );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tkdDebug(14010) << k_funcinfo << \"Warning: Unknown element '\" <<\n\t\t\t\t\telement.tagName() << \"' in map file\" << endl;\n\t\t\t}\n\t\t}\n\t\tnode = node.nextSibling();\n\t}\n\tmapFile.close();\n}\n\nQString KopeteEmoticons::emoticonToPicPath ( const QString& em )\n{\n\tEmoticonMap::Iterator it;\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t{\n\t\t\/\/ search in QStringList data for emoticon\n\t\tif ( it.data().findIndex(em) != -1 )\n\t\t\treturn it.key();\n\t\t\/\/ if found return path for corresponding animation or pixmap\n\t}\n\n\treturn QString();\n}\n\nQStringList KopeteEmoticons::picPathToEmoticon ( const QString& path )\n{\n\tEmoticonMap::Iterator it = map.find( path );\n\tif ( it != map.end() )\n\t\treturn it.data();\n\n\treturn QStringList();\n}\n\nQStringList KopeteEmoticons::emoticonList()\n{\n\tQStringList retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal += it.data();\n\n\treturn retVal;\n}\n\nQStringList KopeteEmoticons::picList()\n{\n\tQStringList retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal += it.key();\n\n\treturn retVal;\n}\n\n\nQMap<QString, QString> KopeteEmoticons::emoticonAndPicList()\n{\n\tQMap<QString, QString> retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal[it.data().first()] = it.key();\n\n\treturn retVal;\n}\n\nQString KopeteEmoticons::parseEmoticons( QString message )\n{\n\t\/\/ if emoticons are disabled, we do nothing\n\tif ( !KopetePrefs::prefs()->useEmoticons() )\n\t\treturn message;\n\n\tQStringList emoticons = KopeteEmoticons::emoticons()->emoticonList();\n\n\n\tfor ( QStringList::Iterator it = emoticons.begin(); it != emoticons.end(); ++it )\n\t{\n\t\tif(message.contains( QStyleSheet::escape(*it) ))\n\t\t{\n\t\t\tQString em = QRegExp::escape( QStyleSheet::escape(*it) );\n\n\t\t\tQString imgPath = KopeteEmoticons::emoticons()->emoticonToPicPath( *it );\n\n\t\t\tQImage iconImage(imgPath);\n\n\t\t\tmessage.replace( QRegExp(QString::fromLatin1( \"(^|[\\\\W\\\\s]|%1)(%1)(?!\\\\w)\" ).arg(em).arg(em)),\n\t\t\t\tQString::fromLatin1(\"\\\\1<img align=\\\"center\\\" width=\\\"\") +\n\t\t\t\tQString::number(iconImage.width()) +\n\t\t\t\tQString::fromLatin1(\"\\\" height=\\\"\") +\n\t\t\t\tQString::number(iconImage.height()) +\n\t\t\t\tQString::fromLatin1(\"\\\" src=\\\"\") +\n\t\t\t\timgPath + QString::fromLatin1( \"\\\">\" )\n\t\t\t\t);\n\t\t}\n\t}\n\n\treturn message;\n}\n\n#include \"kopeteemoticons.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<commit_msg>Add a title to the emoticon to show a tool-tip showing the original text<commit_after>\/*\n kopeteemoticons.cpp - Kopete Preferences Container-Class\n\n Copyright (c) 2002 by Stefan Gehn <sgehn@gmx.net>\n Copyright (c) 2002 by Olivier Goffart <ogoffart@tiscalinet.be>\n\n Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"kopeteemoticons.h\"\n\n#include \"kopeteprefs.h\"\n\n#include <qdom.h>\n#include <qfile.h>\n#include <qregexp.h>\n#include <qstylesheet.h>\n#include <qimage.h>\n\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kstandarddirs.h>\n\nKopeteEmoticons *KopeteEmoticons::s_instance = 0L;\n\nKopeteEmoticons *KopeteEmoticons::emoticons()\n{\n\tif( !s_instance )\n\t\ts_instance = new KopeteEmoticons;\n\treturn s_instance;\n}\n\nKopeteEmoticons::KopeteEmoticons( const QString &theme ) : QObject( kapp, \"KopeteEmoticons\" )\n{\n\/\/\tkdDebug(14010) << \"KopeteEmoticons::KopeteEmoticons\" << endl;\n\tif(theme.isNull())\n\t{\n\t\tinitEmoticons();\n\t\tconnect( KopetePrefs::prefs(), SIGNAL(saved()), this, SLOT(initEmoticons()) );\n\t}\n\telse\n\t{\n\t\tinitEmoticons( theme );\n\t}\n}\n\nvoid KopeteEmoticons::addIfPossible( const QString& filenameNoExt, QStringList emoticons )\n{\n\tKStandardDirs *dir = KGlobal::dirs();\n\tQString pic;\n\n\t\/\/maybe an extention was given, so try to find the exact file\n\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) + m_theme +\n\t\tQString::fromLatin1( \"\/\" ) + filenameNoExt );\n\n\tif( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) + m_theme +\n\t\t\tQString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".mng\" ) );\n\tif ( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\t\tm_theme + QString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".png\" ) );\n\tif ( pic.isNull() )\n\t\tpic = dir->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\t\tm_theme + QString::fromLatin1( \"\/\" ) + filenameNoExt + QString::fromLatin1( \".gif\" ) );\n\n\tif( !pic.isNull() ) \/\/ only add if we found one file\n\t{\n\/\/\t\tkdDebug(14010) << \"KopeteEmoticons::addIfPossible : found pixmap for emoticons\" <<endl;\n\t\tmap[pic] = emoticons;\n\t}\n}\n\nvoid KopeteEmoticons::initEmoticons( const QString &theme )\n{\n\tif(theme.isNull())\n\t{\n\t\tif ( m_theme == KopetePrefs::prefs()->iconTheme() )\n\t\t\treturn;\n\n\t\tm_theme = KopetePrefs::prefs()->iconTheme();\n\t}\n\telse\n\t\tm_theme = theme;\n\n\/\/\tkdDebug(14010) << k_funcinfo << \"Called\" << endl;\n\tmap.clear(); \/\/ empty the mapping\n\n\tQDomDocument emoticonMap( QString::fromLatin1( \"messaging-emoticon-map\" ) );\n\tQString filename = KGlobal::dirs()->findResource( \"data\", QString::fromLatin1( \"kopete\/pics\/emoticons\/\" ) +\n\t\tm_theme + QString::fromLatin1( \"\/emoticons.xml\" ) );\n\n\tif( filename.isEmpty() )\n\t{\n\t\tkdDebug(14010) << \"KopeteEmoticons::initEmoticons : WARNING: emoticon-map not found\" <<endl;\n\t\treturn ;\n\t}\n\n\tQFile mapFile( filename );\n\tmapFile.open( IO_ReadOnly );\n\temoticonMap.setContent( &mapFile );\n\n\tQDomElement list = emoticonMap.documentElement();\n\tQDomNode node = list.firstChild();\n\twhile( !node.isNull() )\n\t{\n\t\tQDomElement element = node.toElement();\n\t\tif( !element.isNull() )\n\t\t{\n\t\t\tif( element.tagName() == QString::fromLatin1( \"emoticon\" ) )\n\t\t\t{\n\t\t\t\tQString emoticon_file = element.attribute(\n\t\t\t\t\tQString::fromLatin1( \"file\" ), QString::null );\n\t\t\t\tQStringList items;\n\n\t\t\t\tQDomNode emoticonNode = node.firstChild();\n\t\t\t\twhile( !emoticonNode.isNull() )\n\t\t\t\t{\n\t\t\t\t\tQDomElement emoticonElement = emoticonNode.toElement();\n\t\t\t\t\tif( !emoticonElement.isNull() )\n\t\t\t\t\t{\n\t\t\t\t\t\tif( emoticonElement.tagName() == QString::fromLatin1( \"string\" ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\titems << emoticonElement.text();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkdDebug(14010) << k_funcinfo <<\n\t\t\t\t\t\t\t\t\"Warning: Unknown element '\" << element.tagName() <<\n\t\t\t\t\t\t\t\t\"' in emoticon data\" << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\temoticonNode = emoticonNode.nextSibling();\n\t\t\t\t}\n\n\t\t\t\taddIfPossible ( emoticon_file, items );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tkdDebug(14010) << k_funcinfo << \"Warning: Unknown element '\" <<\n\t\t\t\t\telement.tagName() << \"' in map file\" << endl;\n\t\t\t}\n\t\t}\n\t\tnode = node.nextSibling();\n\t}\n\tmapFile.close();\n}\n\nQString KopeteEmoticons::emoticonToPicPath ( const QString& em )\n{\n\tEmoticonMap::Iterator it;\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t{\n\t\t\/\/ search in QStringList data for emoticon\n\t\tif ( it.data().findIndex(em) != -1 )\n\t\t\treturn it.key();\n\t\t\/\/ if found return path for corresponding animation or pixmap\n\t}\n\n\treturn QString();\n}\n\nQStringList KopeteEmoticons::picPathToEmoticon ( const QString& path )\n{\n\tEmoticonMap::Iterator it = map.find( path );\n\tif ( it != map.end() )\n\t\treturn it.data();\n\n\treturn QStringList();\n}\n\nQStringList KopeteEmoticons::emoticonList()\n{\n\tQStringList retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal += it.data();\n\n\treturn retVal;\n}\n\nQStringList KopeteEmoticons::picList()\n{\n\tQStringList retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal += it.key();\n\n\treturn retVal;\n}\n\n\nQMap<QString, QString> KopeteEmoticons::emoticonAndPicList()\n{\n\tQMap<QString, QString> retVal;\n\tEmoticonMap::Iterator it;\n\n\tfor ( it = map.begin(); it != map.end(); ++it )\n\t\tretVal[it.data().first()] = it.key();\n\n\treturn retVal;\n}\n\nQString KopeteEmoticons::parseEmoticons( QString message )\n{\n\t\/\/ if emoticons are disabled, we do nothing\n\tif ( !KopetePrefs::prefs()->useEmoticons() )\n\t\treturn message;\n\n\tQStringList emoticons = KopeteEmoticons::emoticons()->emoticonList();\n\n\n\tfor ( QStringList::Iterator it = emoticons.begin(); it != emoticons.end(); ++it )\n\t{\n\t\tif(message.contains( QStyleSheet::escape(*it) ))\n\t\t{\n\t\t\tQString em = QRegExp::escape( QStyleSheet::escape(*it) );\n\n\t\t\tQString imgPath = KopeteEmoticons::emoticons()->emoticonToPicPath( *it );\n\n\t\t\tQImage iconImage(imgPath);\n\n\t\t\tmessage.replace( QRegExp(QString::fromLatin1( \"(^|[\\\\W\\\\s]|%1)(%1)(?!\\\\w)\" ).arg(em).arg(em)),\n\t\t\t\tQString::fromLatin1(\"\\\\1<img align=\\\"center\\\" width=\\\"\") +\n\t\t\t\tQString::number(iconImage.width()) +\n\t\t\t\tQString::fromLatin1(\"\\\" height=\\\"\") +\n\t\t\t\tQString::number(iconImage.height()) +\n\t\t\t\tQString::fromLatin1(\"\\\" src=\\\"\") + imgPath +\n\t\t\t\tQString::fromLatin1(\"\\\" title=\\\"\") + QStyleSheet::escape(*it) +\n\t\t\t\tQString::fromLatin1( \"\\\">\" ) );\n\t\t}\n\t}\n\n\treturn message;\n}\n\n#include \"kopeteemoticons.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#pragma once\n#ifndef _INCLUDE__YAJR__YAJR_HPP\n#define _INCLUDE__YAJR__YAJR_HPP\n\n#include <string>\n#include <uv.h>\n\nnamespace yajr {\n\nint initLoop(uv_loop_t * loop);\nvoid finiLoop(uv_loop_t * loop);\n\nnamespace StateChange {\n enum To {\n CONNECT,\n DISCONNECT,\n FAILURE,\n DELETE,\n };\n};\n\n\/**\n * @brief A yajr communication peer.\n *\/\nstruct Peer {\n\n public:\n\n \/**\n * @brief Typedef for a Peer state change callback\n *\n * Callback type for a Peer State Change. The callback is invoked when a\n * Peer becomes CONNECT'ed, or DISCONNECT'ed or when a FAILURE occurs for the\n * Peer. These three states are represented by the \\p stateChange parameter.\n *\n * When \\p stateChange is FAILURE, \\p error carries a non-zero value, which\n * is to be interpreted as a libuv error code.\n *\n * When \\p stateChange is DELETE, the Peer is about to be deleted. It's a\n * good time to release any resources such as the memory reachable via the\n * \\p data pointer.\n *\/\n typedef void (*StateChangeCb)(\n yajr::Peer *,\n \/**< [in] the Peer the callback refers to *\/\n void * data,\n \/**< [in] Callback data for the Peer *\/\n yajr::StateChange::To stateChange,\n \/**< [in] New state for Peer *\/\n int error\n \/**< [in] libuv error for Peer *\/\n );\n\n \/**\n * @brief Typedef for a uv_loop selector\n *\n * Function pointer type for the uv_loop selector method to be used to\n * select which particular uv_loop to assign a peer to.\n *\n * @return a pointer to the desired uv_loop.\n *\/\n typedef uv_loop_t * (*UvLoopSelector)(\n void * data\n \/**< [in] Callback data for the Peer *\/\n );\n\n \/**\n * @brief Factory for an active yajr communication Peer.\n *\n * This static class method creates a communication Peer and connects it\n * to the desired \\p host and \\p service at the very next opportunity.\n *\n * Upon successful connect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::CONNECT, and an error value of 0 (success).\n *\n * Upon an error, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::FAILURE, and a non-zero error value. If the Peer had\n * managed to connect before the failure, the callback will get invoked once\n * again shortly after, with a state of DISCONNECT.\n *\n * Upon disconnect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::DISCONNECT, and possibly a non-zero error value. If the\n * disconnect is due to a failure, the callback will have just been invoked\n * with a FAILURE state immediately before this time.\n *\n * If \\p data was allocated by the caller, \\p connectionHandler should be\n * releasing \\p data upon DISCONNECT.\n *\n * @return a pointer to the Peer created\n **\/\n static Peer * create(\n std::string const & host,\n \/**< [in] the hostname to connect to *\/\n std::string const & service,\n \/**< [in] service name or port *\/\n StateChangeCb connectionHandler,\n \/**< [in] state change callback *\/\n void * data = NULL,\n \/**< [in] callback data *\/\n UvLoopSelector uvLoopSelector = NULL\n \/**< [in] uv_loop selector for this Peer *\/\n );\n\n \/**\n * @brief perform an asynchronous delete\n *\n * Perform an asynchronous delete of this communication peer, disconnecting\n * it if still connected and destroying it as soon as no more callbacks are\n * pending for this Peer.\n *\/\n virtual void destroy() = 0;\n\n \/**\n * @brief retrieves the pointer to the opaque data associated with this peer\n *\n * @return a pointer to the opaque data for this peer, the same pointer that\n * is provided to the State Change callback\n *\/\n virtual void * getData() const = 0;\n\n \/**\n * @brief start performing periodic keep-alive\n *\n * start performing periodic keep-alive exchanges via the json-rpc\n * \"echo\" method. Abort the connection after 2 times interval worth of\n * silence from the other end.\n *\/\n virtual void startKeepAlive(\n uint64_t begin = 100,\n uint64_t repeat = 1250,\n uint64_t interval = 2500\n ) = 0;\n\n \/**\n * @brief stop performing periodic keep-alive\n *\/\n virtual void stopKeepAlive() = 0;\n\n protected:\n Peer() {}\n ~Peer() {}\n};\n\nstruct Listener {\n\n public:\n\n \/**\n * @brief Typedef for an Accept callback\n *\n * Callback type for an Accept callback. The callback is invoked when a\n * Peer is ACCEPT'ed.\n *\n * @return void pointer to callback data for the StateChange callback for\n * the accepted passive peer, or NULL if error != 0.\n *\/\n typedef void * (*AcceptCb)(\n Listener *,\n \/**< [in] the Listener the callback refers to *\/\n void * data,\n \/**< [in] Callback data for the Listener *\/\n int error\n \/**< [in] libuv error for Peer *\/\n );\n\n \/**\n * @brief Factory for a passive yajr Listener.\n *\n * This static class method creates a yajr Listener and binds it to\n * the desired \\p ip and \\p port at the very next opportunity. Upon\n * accept'ing a client, a passive peer gets created with \\p connectionHandler\n * as a state change callback, and the callback data returned by the\n * \\p acceptHandler callback.\n *\n * The \\p acceptHandler callback gets invoked upon accept'ing a client. It\n * get invoked with the following parameters: the Listener pointer, the\n * \\p data pointer supplied to Listener::create(), and an \\p error value.\n * The \\p error value will be 0 in case of a successful accept, or a libuv\n * error value otherwise. If \\p error is 0, \\p acceptHandler is expected to\n * return a void pointer to the callback \\p data to be associated with the\n * passive peer that is being accepted, and to be passed by that peer to its\n * \\p connectionHandler. If \\p error is non-zero, \\p acceptHandler is\n * expected to return NULL, since no passive peer is being created. If the\n * \\p acceptHandler callback is allocating memory, the \\p connectionHandler\n * callback should be releasing that memory when invoked with a state of\n * DISCONNECTED.\n *\n * Upon an error, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::FAILURE, and a non-zero error value. If the Peer had\n * managed to connect before the failure, the callback will get invoked once\n * again shortly after, with a state of DISCONNECT.\n *\n * Upon disconnect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::DICONNECT, and possibly a non-zero error value. If the\n * disconnect is due to a failure, the callback will have just been invoked\n * with a FAILURE state immediately before this time.\n *\n * @return a pointer to the Peer created\n **\/\n static Listener * create(\n char const * ip_address,\n \/**< [in] the ip address to bind to, or \"0.0.0.0\" to bind all *\/\n uint16_t port,\n \/**< [in] the port to bind to *\/\n Peer::StateChangeCb connectionHandler,\n \/**< [in] state change callback for the accepted passive peers *\/\n AcceptCb acceptHandler = NULL,\n \/**< [in] accept callback for this listener *\/\n void * data = NULL,\n \/**< [in] callback data for the accept callback *\/\n uv_loop_t * listenerUvLoop = NULL,\n \/**< [in] libuv loop for this Listener *\/\n Peer::UvLoopSelector uvLoopSelector = NULL\n \/**< [in] libuv loop selector for the accepted passive peers *\/\n );\n\n \/**\n * @brief perform an asynchronous delete\n *\n * Perform an asynchronous delete of this Listener, destroying it as soon as\n * no more callbacks are pending for it.\n *\/\n virtual void destroy() = 0;\n\n protected:\n Listener() {}\n ~Listener() {}\n};\n\n}\n\n#endif \/* _INCLUDE__YAJR__YAJR_HPP *\/\n<commit_msg>fix small inaccuracy in documentation<commit_after>\/*\n * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#pragma once\n#ifndef _INCLUDE__YAJR__YAJR_HPP\n#define _INCLUDE__YAJR__YAJR_HPP\n\n#include <string>\n#include <uv.h>\n\nnamespace yajr {\n\nint initLoop(uv_loop_t * loop);\nvoid finiLoop(uv_loop_t * loop);\n\nnamespace StateChange {\n enum To {\n CONNECT,\n DISCONNECT,\n FAILURE,\n DELETE,\n };\n};\n\n\/**\n * @brief A yajr communication peer.\n *\/\nstruct Peer {\n\n public:\n\n \/**\n * @brief Typedef for a Peer state change callback\n *\n * Callback type for a Peer State Change. The callback is invoked when a\n * Peer becomes CONNECT'ed, or DISCONNECT'ed or when a FAILURE occurs for the\n * Peer. These three states are represented by the \\p stateChange parameter.\n *\n * When \\p stateChange is FAILURE, \\p error carries a non-zero value, which\n * is to be interpreted as a libuv error code.\n *\n * When \\p stateChange is DELETE, the Peer is about to be deleted. It's a\n * good time to release any resources such as the memory reachable via the\n * \\p data pointer.\n *\/\n typedef void (*StateChangeCb)(\n yajr::Peer *,\n \/**< [in] the Peer the callback refers to *\/\n void * data,\n \/**< [in] Callback data for the Peer *\/\n yajr::StateChange::To stateChange,\n \/**< [in] New state for Peer *\/\n int error\n \/**< [in] libuv error for Peer *\/\n );\n\n \/**\n * @brief Typedef for a uv_loop selector\n *\n * Function pointer type for the uv_loop selector method to be used to\n * select which particular uv_loop to assign a peer to.\n *\n * @return a pointer to the desired uv_loop.\n *\/\n typedef uv_loop_t * (*UvLoopSelector)(\n void * data\n \/**< [in] Callback data for the Peer *\/\n );\n\n \/**\n * @brief Factory for an active yajr communication Peer.\n *\n * This static class method creates a communication Peer and connects it\n * to the desired \\p host and \\p service at the very next opportunity.\n *\n * Upon successful connect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::CONNECT, and an error value of 0 (success).\n *\n * Upon an error, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::FAILURE, and a non-zero error value. If the Peer had\n * managed to connect before the failure, the callback will get invoked once\n * again shortly after, with a state of DISCONNECT.\n *\n * Upon disconnect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::DISCONNECT, and possibly a non-zero error value. If the\n * disconnect is due to a failure, the callback will have just been invoked\n * with a FAILURE state immediately before this time.\n *\n * If \\p data was allocated by the caller, \\p connectionHandler should be\n * releasing \\p data upon StateChange::To::DELETE.\n *\n * @return a pointer to the Peer created\n **\/\n static Peer * create(\n std::string const & host,\n \/**< [in] the hostname to connect to *\/\n std::string const & service,\n \/**< [in] service name or port *\/\n StateChangeCb connectionHandler,\n \/**< [in] state change callback *\/\n void * data = NULL,\n \/**< [in] callback data *\/\n UvLoopSelector uvLoopSelector = NULL\n \/**< [in] uv_loop selector for this Peer *\/\n );\n\n \/**\n * @brief perform an asynchronous delete\n *\n * Perform an asynchronous delete of this communication peer, disconnecting\n * it if still connected and destroying it as soon as no more callbacks are\n * pending for this Peer.\n *\/\n virtual void destroy() = 0;\n\n \/**\n * @brief retrieves the pointer to the opaque data associated with this peer\n *\n * @return a pointer to the opaque data for this peer, the same pointer that\n * is provided to the State Change callback\n *\/\n virtual void * getData() const = 0;\n\n \/**\n * @brief start performing periodic keep-alive\n *\n * start performing periodic keep-alive exchanges via the json-rpc\n * \"echo\" method. Abort the connection after 2 times interval worth of\n * silence from the other end.\n *\/\n virtual void startKeepAlive(\n uint64_t begin = 100,\n uint64_t repeat = 1250,\n uint64_t interval = 2500\n ) = 0;\n\n \/**\n * @brief stop performing periodic keep-alive\n *\/\n virtual void stopKeepAlive() = 0;\n\n protected:\n Peer() {}\n ~Peer() {}\n};\n\nstruct Listener {\n\n public:\n\n \/**\n * @brief Typedef for an Accept callback\n *\n * Callback type for an Accept callback. The callback is invoked when a\n * Peer is ACCEPT'ed.\n *\n * @return void pointer to callback data for the StateChange callback for\n * the accepted passive peer, or NULL if error != 0.\n *\/\n typedef void * (*AcceptCb)(\n Listener *,\n \/**< [in] the Listener the callback refers to *\/\n void * data,\n \/**< [in] Callback data for the Listener *\/\n int error\n \/**< [in] libuv error for Peer *\/\n );\n\n \/**\n * @brief Factory for a passive yajr Listener.\n *\n * This static class method creates a yajr Listener and binds it to\n * the desired \\p ip and \\p port at the very next opportunity. Upon\n * accept'ing a client, a passive peer gets created with \\p connectionHandler\n * as a state change callback, and the callback data returned by the\n * \\p acceptHandler callback.\n *\n * The \\p acceptHandler callback gets invoked upon accept'ing a client. It\n * get invoked with the following parameters: the Listener pointer, the\n * \\p data pointer supplied to Listener::create(), and an \\p error value.\n * The \\p error value will be 0 in case of a successful accept, or a libuv\n * error value otherwise. If \\p error is 0, \\p acceptHandler is expected to\n * return a void pointer to the callback \\p data to be associated with the\n * passive peer that is being accepted, and to be passed by that peer to its\n * \\p connectionHandler. If \\p error is non-zero, \\p acceptHandler is\n * expected to return NULL, since no passive peer is being created. If the\n * \\p acceptHandler callback is allocating memory, the \\p connectionHandler\n * callback should be releasing that memory when invoked with a state of\n * DISCONNECTED.\n *\n * Upon an error, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::FAILURE, and a non-zero error value. If the Peer had\n * managed to connect before the failure, the callback will get invoked once\n * again shortly after, with a state of DISCONNECT.\n *\n * Upon disconnect, the \\p connectionHandler callback gets invoked\n * with the Peer pointer, the \\p data pointer supplied to Peer::create(),\n * StateChange::To::DICONNECT, and possibly a non-zero error value. If the\n * disconnect is due to a failure, the callback will have just been invoked\n * with a FAILURE state immediately before this time.\n *\n * @return a pointer to the Peer created\n **\/\n static Listener * create(\n char const * ip_address,\n \/**< [in] the ip address to bind to, or \"0.0.0.0\" to bind all *\/\n uint16_t port,\n \/**< [in] the port to bind to *\/\n Peer::StateChangeCb connectionHandler,\n \/**< [in] state change callback for the accepted passive peers *\/\n AcceptCb acceptHandler = NULL,\n \/**< [in] accept callback for this listener *\/\n void * data = NULL,\n \/**< [in] callback data for the accept callback *\/\n uv_loop_t * listenerUvLoop = NULL,\n \/**< [in] libuv loop for this Listener *\/\n Peer::UvLoopSelector uvLoopSelector = NULL\n \/**< [in] libuv loop selector for the accepted passive peers *\/\n );\n\n \/**\n * @brief perform an asynchronous delete\n *\n * Perform an asynchronous delete of this Listener, destroying it as soon as\n * no more callbacks are pending for it.\n *\/\n virtual void destroy() = 0;\n\n protected:\n Listener() {}\n ~Listener() {}\n};\n\n}\n\n#endif \/* _INCLUDE__YAJR__YAJR_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"shared_library.h\"\n\n\/\/ clang-format off\n#if defined(_WIN64) || defined(_WIN32)\n# include <Windows.h>\n#elif defined(__unix__)\n# include <dlfcn.h>\n#endif\n\/\/ clang-format on\n#include \"spaghetti\/logger.h\"\n\nnamespace spaghetti {\n\nSharedLibrary::SharedLibrary(fs::path a_file, std::error_code &a_errorCode)\n : m_filename{ a_file.string() }\n{\n log::info(\"[shared_library]: Opening {}\", m_filename);\n\n if (!fs::exists(a_file)) {\n log::error(\"{} don't exist!\", m_filename);\n a_errorCode = std::error_code(ENOENT, std::system_category());\n return;\n }\n\n#if defined(_WIN64) || defined(_WIN32)\n if (a_file.extension() != \".dll\") {\n#else\n if (a_file.extension() != \".so\") {\n#endif\n log::debug(\"{} is not shared library!\", m_filename);\n a_errorCode = std::error_code(EINVAL, std::system_category());\n return;\n }\n\n#if defined(_WIN64) || defined(_WIN32)\n m_handle = LoadLibrary(a_file.c_str());\n if (m_handle == nullptr) {\n auto const ERROR_CODE = GetLastError();\n LPSTR buffer{};\n size_t const SIZE{ FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, ERROR_CODE, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr) };\n std::string const MESSAGE(buffer, SIZE);\n LocalFree(buffer);\n log::error(\"LoadLibrary error: {}\", MESSAGE);\n a_errorCode = std::error_code(ERROR_CODE, std::system_category());\n }\n#elif defined(__unix__)\n m_handle = dlopen(a_file.c_str(), RTLD_NOW);\n if (m_handle == nullptr) {\n log::error(\"{}\", dlerror());\n a_errorCode = std::error_code(EINVAL, std::system_category());\n return;\n }\n#endif\n\n a_errorCode = std::error_code(0, std::system_category());\n}\n\nSharedLibrary::~SharedLibrary()\n{\n log::info(\"[shared_library]: Closing {}\", m_filename);\n#if defined(_WIN64) || defined(_WIN32)\n if (m_handle) FreeLibrary(static_cast<HMODULE>(m_handle));\n#elif defined(__unix__)\n if (m_handle) dlclose(m_handle);\n#endif\n}\n\nbool SharedLibrary::has(std::string_view a_signature) const\n{\n log::info(\"[shared_library]: Checking if symbol {} exists in {}\", a_signature.data(), m_filename);\n\n if (m_handle == nullptr) return false;\n\n#if defined(_WIN64) || defined(_WIN32)\n return GetProcAddress(static_cast<HMODULE>(m_handle), a_signature.data()) != nullptr;\n#elif defined(__unix__)\n return dlsym(m_handle, a_signature.data()) != nullptr;\n#endif\n}\n\nvoid *SharedLibrary::getSymbol(std::string_view a_signature)\n{\n log::info(\"[shared_library]: Getting symbol {} from {}\", a_signature.data(), m_filename);\n\n#if defined(_WIN64) || defined(_WIN32)\n return GetProcAddress(static_cast<HMODULE>(m_handle), a_signature.data());\n#elif defined(__unix__)\n return dlsym(m_handle, a_signature.data());\n#endif\n}\n\n} \/\/ namespace spaghetti\n<commit_msg>Reformat shared_library.cc<commit_after>\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"shared_library.h\"\n\n\/\/ clang-format off\n#if defined(_WIN64) || defined(_WIN32)\n# include <Windows.h>\n#elif defined(__unix__)\n# include <dlfcn.h>\n#endif\n\/\/ clang-format on\n#include \"spaghetti\/logger.h\"\n\nnamespace spaghetti {\n\nSharedLibrary::SharedLibrary(fs::path a_file, std::error_code &a_errorCode)\n : m_filename{ a_file.string() }\n{\n log::info(\"[shared_library]: Opening {}\", m_filename);\n\n if (!fs::exists(a_file)) {\n log::error(\"{} don't exist!\", m_filename);\n a_errorCode = std::error_code(ENOENT, std::system_category());\n return;\n }\n\n#if defined(_WIN64) || defined(_WIN32)\n if (a_file.extension() != \".dll\") {\n#else\n if (a_file.extension() != \".so\") {\n#endif\n log::debug(\"{} is not shared library!\", m_filename);\n a_errorCode = std::error_code(EINVAL, std::system_category());\n return;\n }\n\n#if defined(_WIN64) || defined(_WIN32)\n m_handle = LoadLibrary(a_file.c_str());\n if (m_handle == nullptr) {\n auto const ERROR_CODE = GetLastError();\n LPSTR buffer{};\n size_t const SIZE{ FormatMessageA(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ERROR_CODE,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, nullptr) };\n std::string const MESSAGE(buffer, SIZE);\n LocalFree(buffer);\n log::error(\"LoadLibrary error: {}\", MESSAGE);\n a_errorCode = std::error_code(ERROR_CODE, std::system_category());\n }\n#elif defined(__unix__)\n m_handle = dlopen(a_file.c_str(), RTLD_NOW);\n if (m_handle == nullptr) {\n log::error(\"{}\", dlerror());\n a_errorCode = std::error_code(EINVAL, std::system_category());\n return;\n }\n#endif\n\n a_errorCode = std::error_code(0, std::system_category());\n}\n\nSharedLibrary::~SharedLibrary()\n{\n log::info(\"[shared_library]: Closing {}\", m_filename);\n#if defined(_WIN64) || defined(_WIN32)\n if (m_handle) FreeLibrary(static_cast<HMODULE>(m_handle));\n#elif defined(__unix__)\n if (m_handle) dlclose(m_handle);\n#endif\n}\n\nbool SharedLibrary::has(std::string_view a_signature) const\n{\n log::info(\"[shared_library]: Checking if symbol {} exists in {}\", a_signature.data(), m_filename);\n\n if (m_handle == nullptr) return false;\n\n#if defined(_WIN64) || defined(_WIN32)\n return GetProcAddress(static_cast<HMODULE>(m_handle), a_signature.data()) != nullptr;\n#elif defined(__unix__)\n return dlsym(m_handle, a_signature.data()) != nullptr;\n#endif\n}\n\nvoid *SharedLibrary::getSymbol(std::string_view a_signature)\n{\n log::info(\"[shared_library]: Getting symbol {} from {}\", a_signature.data(), m_filename);\n\n#if defined(_WIN64) || defined(_WIN32)\n return GetProcAddress(static_cast<HMODULE>(m_handle), a_signature.data());\n#elif defined(__unix__)\n return dlsym(m_handle, a_signature.data());\n#endif\n}\n\n} \/\/ namespace spaghetti\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Dawid Kurek. All Rights Reserved.\n\n#include \"chip\/chip8.hpp\"\n\n#include <atomic>\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <thread>\n\n#include \"chip\/executor.hpp\"\n#include \"chip\/memory.hpp\"\n#include \"chip\/opcode.hpp\"\n\nnamespace chip {\n\nChip8::Chip8(Byte const &clock)\n : _cycleDuration{1000 \/ clock}\n , _memory{}\n , _execute{}\n , _getKey{[]() { return 0; }}\n , _redraw{[]() {}}\n , _running{false}\n , _worker{} {}\n\nChip8::~Chip8() {\n stop();\n}\n\nvoid Chip8::getKey(GetKey const &callback) {\n _getKey = callback;\n}\n\nvoid Chip8::redraw(Redraw const &callback) {\n _redraw = callback;\n}\n\nFileChoosen Chip8::fileChoosenCallback() {\n return [this](std::string const &file) { load(file); };\n}\n\nKeyEvent Chip8::keyEventCallback() {\n return [this](char const key, bool const isPressed) {};\n}\n\nByte const *const Chip8::getDisplay() {\n return _memory.Display;\n}\n\nvoid Chip8::load(std::string const &file) {\n stop();\n\n size_t position = 0x200;\n for (std::ifstream input{file, std::ios::binary}; input.good();) {\n if (position > 0x1000) {\n throw std::runtime_error{\"Input file is too big, max size is \" +\n std::to_string(0x1000 - 0x200)};\n }\n\n _memory.Raw[position++] = input.get();\n }\n\n start();\n}\n\nvoid Chip8::start() {\n _running = true;\n _memory.PC = 0x200;\n _worker = std::thread{&Chip8::main, this};\n}\n\nvoid Chip8::stop() {\n _running = false;\n if (_worker.joinable()) {\n _worker.join();\n }\n}\n\nvoid Chip8::main() {\n while (_running) {\n auto const opcode = fetch();\n tick();\n _execute(Opcode{opcode}, _memory, _getKey);\n wait();\n }\n}\n\nWord Chip8::fetch() {\n return _memory.Raw[_memory.PC] << 8 | _memory.Raw[_memory.PC + 1];\n}\n\nvoid Chip8::tick() {\n _memory.PC += 2;\n if (_memory.ST > 0) {\n --_memory.ST;\n }\n if (_memory.DT > 0) {\n --_memory.DT;\n }\n _redraw();\n}\n\nvoid Chip8::wait() {\n std::this_thread::sleep_for(std::chrono::milliseconds(16));\n}\n\n} \/\/ namespace chip\n<commit_msg>Fix cycle sleep<commit_after>\/\/ Copyright 2016 Dawid Kurek. All Rights Reserved.\n\n#include \"chip\/chip8.hpp\"\n\n#include <atomic>\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <thread>\n\n#include \"chip\/executor.hpp\"\n#include \"chip\/memory.hpp\"\n#include \"chip\/opcode.hpp\"\n\nnamespace chip {\n\nChip8::Chip8(Byte const &clock)\n : _cycleDuration{1000 \/ clock}\n , _memory{}\n , _execute{}\n , _getKey{[]() { return 0; }}\n , _redraw{[]() {}}\n , _running{false}\n , _worker{} {}\n\nChip8::~Chip8() {\n stop();\n}\n\nvoid Chip8::getKey(GetKey const &callback) {\n _getKey = callback;\n}\n\nvoid Chip8::redraw(Redraw const &callback) {\n _redraw = callback;\n}\n\nFileChoosen Chip8::fileChoosenCallback() {\n return [this](std::string const &file) { load(file); };\n}\n\nKeyEvent Chip8::keyEventCallback() {\n return [this](char const key, bool const isPressed) {};\n}\n\nByte const *const Chip8::getDisplay() {\n return _memory.Display;\n}\n\nvoid Chip8::load(std::string const &file) {\n stop();\n\n size_t position = 0x200;\n for (std::ifstream input{file, std::ios::binary}; input.good();) {\n if (position > 0x1000) {\n throw std::runtime_error{\"Input file is too big, max size is \" +\n std::to_string(0x1000 - 0x200)};\n }\n\n _memory.Raw[position++] = input.get();\n }\n\n start();\n}\n\nvoid Chip8::start() {\n _running = true;\n _memory.PC = 0x200;\n _worker = std::thread{&Chip8::main, this};\n}\n\nvoid Chip8::stop() {\n _running = false;\n if (_worker.joinable()) {\n _worker.join();\n }\n}\n\nvoid Chip8::main() {\n while (_running) {\n auto const opcode = fetch();\n tick();\n _execute(Opcode{opcode}, _memory, _getKey);\n wait();\n }\n}\n\nWord Chip8::fetch() {\n return _memory.Raw[_memory.PC] << 8 | _memory.Raw[_memory.PC + 1];\n}\n\nvoid Chip8::tick() {\n _memory.PC += 2;\n if (_memory.ST > 0) {\n --_memory.ST;\n }\n if (_memory.DT > 0) {\n --_memory.DT;\n }\n _redraw();\n}\n\nvoid Chip8::wait() {\n static auto lastEntry = std::chrono::system_clock::now();\n\n auto const newEntry = std::chrono::system_clock::now();\n auto const lastCycleDuration = newEntry - lastEntry;\n\n if (lastCycleDuration < _cycleDuration) {\n std::this_thread::sleep_for(_cycleDuration - lastCycleDuration);\n }\n\n lastEntry = newEntry;\n}\n\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <string>\n#include <coodinate_system.hpp>\n#include <tle.hpp>\n#include <orbit.hpp>\n#include <ctime>\n#include <Eigen\/Core>\n#include <Eigen\/Geometry>\n#include \"mathematic_utils.hpp\"\n\nusing namespace Eigen;\n\n\/\/ 地心直交座標系で、\n\/\/ 射点位置(P0)\n\/\/ 衛星位置(P1)\n\/\/ 軌道接平面法線(N)\n\/\/ から、\n\/\/ 楕円体(E(O,R)) 面上の着弾点を得る\nVector3dSet find_impact_point(\n const Vector3d& P0, const Vector3d& P1, const Vector3d& N,\n const Vector3d& O, const Vector3d& R)\n{\n Vector3d v1 = P1 - P0; \/\/ 発射ビームの向き\n Vector3d v2 = reflect(v1,N); \/\/ 反射ビームの向き\n Vector3dSet Q = intersection(P1,v2,O,R); \/\/ 着弾点候補\n Vector3dSet X = neighoring(P1,Q); \/\/ 着弾点候補のうちP1に近い点\n\n return X;\n}\n\n\/\/ 測地座標系で、\n\/\/ 射点位置(P)\n\/\/ 使う人工衛星のTLE\n\/\/ 現在時刻 t\n\/\/ から、地上の着弾点を得る\nbool find_impact(const polar& P, polar* X,\n const std::string& tle_str, const time_t* t)\n{\n \/\/ TLE読み込み\n TLE tle;\n std::string tle_str1 = tle_str.substr(0,69);\n std::string tle_str2 = tle_str.substr(69,69);\n tle.set(tle_str1,tle_str2);\n\n \/\/ 地心赤道直交座標系での射点座標\n ::polar Po = P;\n Po.latitude *= M_PI \/ 180.; \/\/ degree -> radian\n Po.longitude *= M_PI \/ 180.; \/\/ degree -> radian\n rectangular Pr = Po.toEquatorial(t).toRectangular();\n Eigen::Vector3d P0(Pr.X, Pr.Y, Pr.Z);\n\n \/\/ 軌道\n orbit orb;\n orb.setTLE(&tle);\n double since_day = orb.elapsed_day(t);\n double since_min = since_day * 1440.;\n double since_sec = since_day * 86400.;\n\n double motion = tle.motion; \/\/ revolutions per day\n double dayp6 = 1. \/ (6. * motion); \/\/ day for 1\/6 revolution.\n double minp6 = dayp6 * 1440.;\n double secp6 = dayp6 * 86400.;\n\n \/\/ 人工衛星の所在地\n double position0[3],position1[3],position2[3];\n double velocity0[3],velocity1[3],velocity2[3];\n orb.sgp(position0,velocity0,since_min - minp6);\n orb.sgp(position1,velocity1,since_min);\n orb.sgp(position2,velocity2,since_min + minp6);\n\n Eigen::Vector3d p0(position0);\n Eigen::Vector3d p1(position1); \/\/ 人工衛星の現在地の位置ベクトル\n Eigen::Vector3d p2(position2);\n Eigen::Vector3d v1(velocity1);\n\n Eigen::Vector3d n0 = normalize((p1-p0).cross(p2-p1)); \/\/ 軌道面の法線ベクトル\n Eigen::Vector3d n1 = n0.cross(normalize(v1)); \/\/ 反射面の法線ベクトル\n\n Eigen::Vector3d O(0.,0.,0.);\n Eigen::Vector3d R(6378.137,6378.137,6356.752); \/\/ 地球楕円体\n Vector3dSet Q = find_impact_point(P0,p1,n1,O,R);\n\n rectangular Xr;\n bool f = (Q.size() != 0);\n if (f) {\n Eigen::Vector3d q = Q[0];\n Xr.X = q[0];\n Xr.Y = q[1];\n Xr.Z = q[2];\n } else {\n Xr.X = 0.0;\n Xr.Y = 0.0;\n Xr.Z = 0.0;\n }\n\n ::polar x = Xr.toPolar();\n *X = Xr.toPolar().toGeodetic(t); \/\/ 測地座標系に変換\n X->latitude *= 180. \/ M_PI; \/\/ radian -> degree\n X->longitude *= 180. \/ M_PI; \/\/ radian -> degree\n if ( X->latitude > 180.) X->latitude -= 180.;\n if ( X->latitude < -180.) X->latitude += 180.;\n if ( X->longitude > 180.) X->longitude -= 180.;\n if ( X->longitude < -180.) X->longitude += 180.;\n\n return f;\n}\n\n<commit_msg>着弾点の緯度経度が180度を越えたときの補正方法を修正<commit_after>#include <cmath>\n#include <string>\n#include <coodinate_system.hpp>\n#include <tle.hpp>\n#include <orbit.hpp>\n#include <ctime>\n#include <Eigen\/Core>\n#include <Eigen\/Geometry>\n#include \"mathematic_utils.hpp\"\n\nusing namespace Eigen;\n\n\/\/ 地心直交座標系で、\n\/\/ 射点位置(P0)\n\/\/ 衛星位置(P1)\n\/\/ 軌道接平面法線(N)\n\/\/ から、\n\/\/ 楕円体(E(O,R)) 面上の着弾点を得る\nVector3dSet find_impact_point(\n const Vector3d& P0, const Vector3d& P1, const Vector3d& N,\n const Vector3d& O, const Vector3d& R)\n{\n Vector3d v1 = P1 - P0; \/\/ 発射ビームの向き\n Vector3d v2 = reflect(v1,N); \/\/ 反射ビームの向き\n Vector3dSet Q = intersection(P1,v2,O,R); \/\/ 着弾点候補\n Vector3dSet X = neighoring(P1,Q); \/\/ 着弾点候補のうちP1に近い点\n\n return X;\n}\n\n\/\/ 測地座標系で、\n\/\/ 射点位置(P)\n\/\/ 使う人工衛星のTLE\n\/\/ 現在時刻 t\n\/\/ から、地上の着弾点を得る\nbool find_impact(const polar& P, polar* X,\n const std::string& tle_str, const time_t* t)\n{\n \/\/ TLE読み込み\n TLE tle;\n std::string tle_str1 = tle_str.substr(0,69);\n std::string tle_str2 = tle_str.substr(69,69);\n tle.set(tle_str1,tle_str2);\n\n \/\/ 地心赤道直交座標系での射点座標\n ::polar Po = P;\n Po.latitude *= M_PI \/ 180.; \/\/ degree -> radian\n Po.longitude *= M_PI \/ 180.; \/\/ degree -> radian\n rectangular Pr = Po.toEquatorial(t).toRectangular();\n Eigen::Vector3d P0(Pr.X, Pr.Y, Pr.Z);\n\n \/\/ 軌道\n orbit orb;\n orb.setTLE(&tle);\n double since_day = orb.elapsed_day(t);\n double since_min = since_day * 1440.;\n double since_sec = since_day * 86400.;\n\n double motion = tle.motion; \/\/ revolutions per day\n double dayp6 = 1. \/ (6. * motion); \/\/ day for 1\/6 revolution.\n double minp6 = dayp6 * 1440.;\n double secp6 = dayp6 * 86400.;\n\n \/\/ 人工衛星の所在地\n double position0[3],position1[3],position2[3];\n double velocity0[3],velocity1[3],velocity2[3];\n orb.sgp(position0,velocity0,since_min - minp6);\n orb.sgp(position1,velocity1,since_min);\n orb.sgp(position2,velocity2,since_min + minp6);\n\n Eigen::Vector3d p0(position0);\n Eigen::Vector3d p1(position1); \/\/ 人工衛星の現在地の位置ベクトル\n Eigen::Vector3d p2(position2);\n Eigen::Vector3d v1(velocity1);\n\n Eigen::Vector3d n0 = normalize((p1-p0).cross(p2-p1)); \/\/ 軌道面の法線ベクトル\n Eigen::Vector3d n1 = n0.cross(normalize(v1)); \/\/ 反射面の法線ベクトル\n\n Eigen::Vector3d O(0.,0.,0.);\n Eigen::Vector3d R(6378.137,6378.137,6356.752); \/\/ 地球楕円体\n Vector3dSet Q = find_impact_point(P0,p1,n1,O,R);\n\n rectangular Xr;\n bool f = (Q.size() != 0);\n if (f) {\n Eigen::Vector3d q = Q[0];\n Xr.X = q[0];\n Xr.Y = q[1];\n Xr.Z = q[2];\n } else {\n Xr.X = 0.0;\n Xr.Y = 0.0;\n Xr.Z = 0.0;\n }\n\n ::polar x = Xr.toPolar();\n *X = Xr.toPolar().toGeodetic(t); \/\/ 測地座標系に変換\n X->latitude *= 180. \/ M_PI; \/\/ radian -> degree\n X->longitude *= 180. \/ M_PI; \/\/ radian -> degree\n if ( X->latitude > 180.) X->latitude -= 360.;\n else if ( X->latitude < -180.) X->latitude += 360.;\n if ( X->longitude > 180.) X->longitude -= 360.;\n else if ( X->longitude < -180.) X->longitude += 360.;\n\n return f;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"maze.h\"\n\n\nTEST (Location, DefaultValueOfHome)\n{\n location_t loc = Home();\n EXPECT_EQ (0, loc.row);\n EXPECT_EQ (0, loc.col);\n}\n\n\nTEST (Location, InitialisingGoal_SetToRow7Col8)\n{\n location_t loc = Goal();\n EXPECT_EQ (7, loc.row);\n EXPECT_EQ (7, loc.col);\n}\n\nTEST (Location, Width_DefaultReturnsMAZE_COLS)\n{\n EXPECT_EQ (MAZE_COLS, MazeWidth());\n}\n\nTEST (Location, Height_DefaultReturnsMAZE_ROWS)\n{\n EXPECT_EQ (MAZE_ROWS, MazeHeight());\n}\n\nTEST (Location, SetAndFetchFGoal_SetGoal_ReturnGoal)\n{\n location_t newGoal;\n newGoal.row = 3;\n newGoal.col = 4;\n location_t goal;\n SetGoal (newGoal);\n goal = Goal();\n EXPECT_EQ (newGoal.row, goal.row);\n EXPECT_EQ (newGoal.col, goal.col);\n}\n\nTEST (Location, FindNeighbour_SeekNORTHNeighbour_GetRowPlus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, NORTH);\n EXPECT_EQ (loc.row + 1, neighbour.row);\n EXPECT_EQ (loc.col, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekEASTNeighbour_GetColPlus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, EAST);\n EXPECT_EQ (loc.row, neighbour.row);\n EXPECT_EQ (loc.col + 1, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekSOUTHNeighbour_GetRowMinus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, SOUTH);\n EXPECT_EQ (loc.row - 1, neighbour.row);\n EXPECT_EQ (loc.col, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekWESTNeighbour_GetColMinus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, WEST);\n EXPECT_EQ (loc.row, neighbour.row);\n EXPECT_EQ (loc.col - 1, neighbour.col);\n}\n\n\nTEST (Location, LocationInGoal)\n{\n location_t goal = {12, 13};\n SetGoal (goal);\n location_t inGoal = goal;\n location_t notInGoal = {0, 0};\n EXPECT_TRUE (IsGoal (inGoal));\n EXPECT_FALSE (IsGoal (notInGoal));\n}\n\nTEST (Location, LocationInHome)\n{\n location_t inHome = {0, 0};\n location_t notInHome = {0, 1};\n EXPECT_TRUE (IsHome (inHome));\n EXPECT_FALSE (IsHome (notInHome));\n}\n\nTEST (Location, Neighbour_WrapAroundEdges)\n{\n location_t loc;\n location_t neighbour;\n loc.col = MazeWidth() - 1;\n loc.row = MazeHeight() - 1;\n EXPECT_EQ (0, Neighbour (loc, NORTH).row);\n EXPECT_EQ (0, Neighbour (loc, EAST).col);\n loc.col = 0;\n loc.row = 0;\n EXPECT_EQ (MazeHeight() - 1, Neighbour (loc, SOUTH).row);\n EXPECT_EQ (MazeWidth() - 1, Neighbour (loc, WEST).col);\n}\n\n<commit_msg>Added a test for boundary cases in calculating neighbour locations<commit_after>#include \"gtest\/gtest.h\"\n#include \"maze.h\"\n\n\nTEST (Location, DefaultValueOfHome)\n{\n location_t loc = Home();\n EXPECT_EQ (0, loc.row);\n EXPECT_EQ (0, loc.col);\n}\n\n\nTEST (Location, InitialisingGoal_SetToRow7Col8)\n{\n location_t loc = Goal();\n EXPECT_EQ (7, loc.row);\n EXPECT_EQ (7, loc.col);\n}\n\nTEST (Location, Width_DefaultReturnsMAZE_COLS)\n{\n EXPECT_EQ (MAZE_COLS, MazeWidth());\n}\n\nTEST (Location, Height_DefaultReturnsMAZE_ROWS)\n{\n EXPECT_EQ (MAZE_ROWS, MazeHeight());\n}\n\nTEST (Location, SetAndFetchFGoal_SetGoal_ReturnGoal)\n{\n location_t newGoal;\n newGoal.row = 3;\n newGoal.col = 4;\n location_t goal;\n SetGoal (newGoal);\n goal = Goal();\n EXPECT_EQ (newGoal.row, goal.row);\n EXPECT_EQ (newGoal.col, goal.col);\n}\n\nTEST (Location, FindNeighbour_SeekNORTHNeighbour_GetRowPlus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, NORTH);\n EXPECT_EQ (loc.row + 1, neighbour.row);\n EXPECT_EQ (loc.col, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekEASTNeighbour_GetColPlus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, EAST);\n EXPECT_EQ (loc.row, neighbour.row);\n EXPECT_EQ (loc.col + 1, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekSOUTHNeighbour_GetRowMinus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, SOUTH);\n EXPECT_EQ (loc.row - 1, neighbour.row);\n EXPECT_EQ (loc.col, neighbour.col);\n}\n\nTEST (Location, FindNeighbour_SeekWESTNeighbour_GetColMinus1)\n{\n location_t loc;\n loc.row = 5;\n loc.col = 8;\n location_t neighbour;\n neighbour = Neighbour (loc, WEST);\n EXPECT_EQ (loc.row, neighbour.row);\n EXPECT_EQ (loc.col - 1, neighbour.col);\n}\n\n\nTEST (Location, LocationInGoal)\n{\n location_t goal = {12, 13};\n SetGoal (goal);\n location_t inGoal = goal;\n location_t notInGoal = {0, 0};\n EXPECT_TRUE (IsGoal (inGoal));\n EXPECT_FALSE (IsGoal (notInGoal));\n}\n\nTEST (Location, LocationInHome)\n{\n location_t inHome = {0, 0};\n location_t notInHome = {0, 1};\n EXPECT_TRUE (IsHome (inHome));\n EXPECT_FALSE (IsHome (notInHome));\n}\n\nTEST (Location, Neighbour_WrapAroundEdges)\n{\n location_t loc;\n location_t neighbour;\n loc.col = MazeWidth() - 1;\n loc.row = MazeHeight() - 1;\n EXPECT_EQ (0, Neighbour (loc, NORTH).row);\n EXPECT_EQ (0, Neighbour (loc, EAST).col);\n loc.col = 0;\n loc.row = 0;\n EXPECT_EQ (MazeHeight() - 1, Neighbour (loc, SOUTH).row);\n EXPECT_EQ (MazeWidth() - 1, Neighbour (loc, WEST).col);\n}\n\nTEST (Location, Neighbour_BoundaryCases)\n{\n location_t loc;\n location_t neighbour;\n int lastColumn = MazeWidth() -1;\n int lastRow = MazeWidth() -1;\n loc.col = lastColumn - 1;\n loc.row = lastRow - 1;\n EXPECT_EQ (lastRow, Neighbour (loc, NORTH).row);\n EXPECT_EQ (lastColumn, Neighbour (loc, EAST).col);\n loc.col = 1;\n loc.row = 1;\n EXPECT_EQ (0, Neighbour (loc, SOUTH).row);\n EXPECT_EQ (0, Neighbour (loc, WEST).col);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_TEST_OPENCL_UTIL_HPP\n#define STAN_TEST_OPENCL_UTIL_HPP\n\n#include <stan\/math.hpp>\n#include <stan\/math\/opencl\/rev\/opencl.hpp>\n#include <test\/unit\/math\/expect_near_rel.hpp>\n#include <test\/unit\/pretty_print_types.hpp>\n#include <gtest\/gtest.h>\n#include <utility>\n#include <string>\n#include <tuple>\n\nnamespace stan {\nnamespace math {\nnamespace test {\n\nnamespace internal {\n\ntemplate <typename T, require_stan_scalar_t<T>* = nullptr>\nT opencl_argument(T&& x) {\n return x;\n}\ntemplate <typename T, require_not_stan_scalar_t<T>* = nullptr>\nauto opencl_argument(const T& x) {\n return to_matrix_cl(x);\n}\n\ntemplate <typename T, require_st_same<T, int>* = nullptr>\nT var_argument(T&& x) {\n return x;\n}\ntemplate <typename T, require_not_st_same<T, int>* = nullptr>\nauto var_argument(T&& x) {\n return to_var(x);\n}\n\ntemplate <typename T, require_arithmetic_t<T>* = nullptr>\nvoid expect_eq(T a, T b, const char* msg) {\n stan::test::expect_near_rel(msg, a, b);\n}\nvoid expect_eq(math::var a, math::var b, const char* msg) {\n stan::test::expect_near_rel(msg, a.val(), b.val());\n}\ntemplate <typename T1, typename T2, require_all_eigen_t<T1, T2>* = nullptr,\n require_all_not_st_var<T1, T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n EXPECT_EQ(a.rows(), b.rows()) << msg;\n EXPECT_EQ(a.cols(), b.cols()) << msg;\n const auto& a_ref = math::to_ref(a);\n const auto& b_ref = math::to_ref(b);\n for (int i = 0; i < a.rows(); i++) {\n for (int j = 0; j < a.cols(); j++) {\n expect_eq(a_ref(i, j), b_ref(i, j), msg);\n }\n }\n}\ntemplate <typename T1, typename T2, require_all_rev_matrix_t<T1, T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(a.val(), b.val(), msg);\n}\ntemplate <typename T>\nvoid expect_eq(const std::vector<T>& a, const std::vector<T>& b,\n const char* msg) {\n EXPECT_EQ(a.size(), b.size());\n for (int i = 0; i < a.size(); i++) {\n expect_eq(a[i], b[i], msg);\n }\n}\ntemplate <typename T1, typename T2,\n require_nonscalar_prim_or_rev_kernel_expression_t<T1>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(from_matrix_cl(a), b, msg);\n}\ntemplate <typename T1, typename T2,\n require_nonscalar_prim_or_rev_kernel_expression_t<T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(a, from_matrix_cl(b), msg);\n}\n\ntemplate <typename T>\nauto recursive_sum(const T& a) {\n return math::sum(a);\n}\ntemplate <typename T>\nauto recursive_sum(const std::vector<T>& a) {\n scalar_type_t<T> res = recursive_sum(a[0]);\n for (int i = 0; i < a.size(); i++) {\n res += recursive_sum(a[i]);\n }\n return res;\n}\n\ntemplate <typename T, require_not_st_var<T>* = nullptr>\nvoid expect_adj_near(const T& a, const T& b, const char* msg) {}\nvoid expect_adj_near(var a, var b, const char* msg) {\n stan::test::expect_near_rel(msg, a.adj(), b.adj());\n}\ntemplate <typename T1, typename T2, require_all_eigen_t<T1, T2>* = nullptr,\n require_vt_same<T1, T2>* = nullptr>\nvoid expect_adj_near(const T1& a, const T2& b, const char* msg) {\n EXPECT_EQ(a.rows(), b.rows()) << msg;\n EXPECT_EQ(a.cols(), b.cols()) << msg;\n const auto& a_ref = math::to_ref(a);\n const auto& b_ref = math::to_ref(b);\n stan::test::expect_near_rel(msg, a_ref.adj(), b_ref.adj());\n}\ntemplate <typename T>\nvoid expect_adj_near(const std::vector<T>& a, const std::vector<T>& b,\n const char* msg) {\n EXPECT_EQ(a.size(), b.size()) << msg;\n for (int i = 0; i < a.size(); i++) {\n expect_adj_near(a[i], b[i], msg);\n }\n}\n\ntemplate <typename Functor>\nvoid prim_rev_argument_combinations(Functor f) {\n f(std::make_tuple(), std::make_tuple());\n}\ntemplate <typename Functor, typename Arg0, typename... Args>\nvoid prim_rev_argument_combinations(const Functor& f, const Arg0& arg0,\n const Args&... args) {\n prim_rev_argument_combinations(\n [&f, &arg0](auto args_for_cpu, auto args_for_opencl) {\n constexpr size_t Size\n = std::tuple_size<std::decay_t<decltype(args_for_cpu)>>::value;\n return index_apply<Size>([&](auto... Is) {\n return f(\n std::forward_as_tuple(arg0, std::get<Is>(args_for_cpu)...),\n std::forward_as_tuple(arg0, std::get<Is>(args_for_opencl)...));\n });\n },\n args...);\n prim_rev_argument_combinations(\n [&](const auto& args_for_cpu, const auto& args_for_opencl) {\n constexpr size_t Size\n = std::tuple_size<std::decay_t<decltype(args_for_cpu)>>::value;\n return index_apply<Size>([&](auto... Is) {\n return f(std::make_tuple(var_argument(arg0),\n std::get<Is>(args_for_cpu)...),\n std::make_tuple(var_argument(arg0),\n std::get<Is>(args_for_opencl)...));\n });\n },\n args...);\n}\n\ntemplate <typename Functor, std::size_t... Is, typename... Args>\nvoid compare_cpu_opencl_prim_rev_impl(const Functor& functor,\n std::index_sequence<Is...>,\n const Args&... args) {\n prim_rev_argument_combinations(\n [&functor](auto args_for_cpu, auto args_for_opencl) {\n auto res_cpu = functor(std::get<Is>(args_for_cpu)...);\n auto res_opencl\n = functor(opencl_argument(std::get<Is>(args_for_opencl))...);\n std::string signature = type_name<decltype(args_for_cpu)>().data();\n expect_eq(res_opencl, res_cpu,\n (\"CPU and OpenCL return values do not match for signature \"\n + signature + \"!\")\n .c_str());\n var(recursive_sum(res_cpu) + recursive_sum(res_opencl)).grad();\n\n static_cast<void>(std::initializer_list<int>{\n (expect_adj_near(\n std::get<Is>(args_for_opencl), std::get<Is>(args_for_cpu),\n (\"CPU and OpenCL adjoints do not match for argument \"\n + std::to_string(Is) + \" for signature \" + signature + \"!\")\n .c_str()),\n 0)...});\n\n set_zero_all_adjoints();\n },\n args...);\n}\n\n} \/\/ namespace internal\n\n\/**\n * Tests that given functor calculates same values and adjoints when given\n * arguments on CPU and OpenCL device.\n *\n * @tparam Functor type of the functor\n * @tparam Args types of the arguments\n * @param fucntor functor to test\n * @param args arguments to test the functor with. These should be just values\n * in CPU memory (no vars, no arguments on the OpenCL device).\n *\/\ntemplate <typename Functor, typename... Args>\nvoid compare_cpu_opencl_prim_rev(const Functor& functor, const Args&... args) {\n internal::compare_cpu_opencl_prim_rev_impl(\n functor, std::make_index_sequence<sizeof...(args)>{}, args...);\n}\n\n} \/\/ namespace test\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<commit_msg>wake up jenkins<commit_after>#ifndef STAN_TEST_OPENCL_UTIL_HPP\n#define STAN_TEST_OPENCL_UTIL_HPP\n\n#include <stan\/math.hpp>\n#include <stan\/math\/opencl\/rev\/opencl.hpp>\n#include <test\/unit\/math\/expect_near_rel.hpp>\n#include <test\/unit\/pretty_print_types.hpp>\n#include <gtest\/gtest.h>\n#include <utility>\n#include <string>\n#include <tuple>\n\nnamespace stan {\nnamespace math {\nnamespace test {\n\nnamespace internal {\n\ntemplate <typename T, require_stan_scalar_t<T>* = nullptr>\nT opencl_argument(T&& x) {\n return x;\n}\ntemplate <typename T, require_not_stan_scalar_t<T>* = nullptr>\nauto opencl_argument(const T& x) {\n return to_matrix_cl(x);\n}\n\ntemplate <typename T, require_st_same<T, int>* = nullptr>\nT var_argument(T&& x) {\n return x;\n}\ntemplate <typename T, require_not_st_same<T, int>* = nullptr>\nauto var_argument(T&& x) {\n return to_var(x);\n}\n\ntemplate <typename T, require_arithmetic_t<T>* = nullptr>\nvoid expect_eq(T a, T b, const char* msg) {\n stan::test::expect_near_rel(msg, a, b);\n}\nvoid expect_eq(math::var a, math::var b, const char* msg) {\n stan::test::expect_near_rel(msg, a.val(), b.val());\n}\ntemplate <typename T1, typename T2, require_all_eigen_t<T1, T2>* = nullptr,\n require_all_not_st_var<T1, T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n EXPECT_EQ(a.rows(), b.rows()) << msg;\n EXPECT_EQ(a.cols(), b.cols()) << msg;\n const auto& a_ref = math::to_ref(a);\n const auto& b_ref = math::to_ref(b);\n for (int i = 0; i < a.rows(); i++) {\n for (int j = 0; j < a.cols(); j++) {\n expect_eq(a_ref(i, j), b_ref(i, j), msg);\n }\n }\n}\ntemplate <typename T1, typename T2, require_all_rev_matrix_t<T1, T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(a.val(), b.val(), msg);\n}\ntemplate <typename T>\nvoid expect_eq(const std::vector<T>& a, const std::vector<T>& b,\n const char* msg) {\n EXPECT_EQ(a.size(), b.size());\n for (int i = 0; i < a.size(); i++) {\n expect_eq(a[i], b[i], msg);\n }\n}\ntemplate <typename T1, typename T2,\n require_nonscalar_prim_or_rev_kernel_expression_t<T1>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(from_matrix_cl(a), b, msg);\n}\ntemplate <typename T1, typename T2,\n require_nonscalar_prim_or_rev_kernel_expression_t<T2>* = nullptr>\nvoid expect_eq(const T1& a, const T2& b, const char* msg) {\n expect_eq(a, from_matrix_cl(b), msg);\n}\n\ntemplate <typename T>\nauto recursive_sum(const T& a) {\n return math::sum(a);\n}\ntemplate <typename T>\nauto recursive_sum(const std::vector<T>& a) {\n scalar_type_t<T> res = recursive_sum(a[0]);\n for (int i = 0; i < a.size(); i++) {\n res += recursive_sum(a[i]);\n }\n return res;\n}\n\ntemplate <typename T, require_not_st_var<T>* = nullptr>\nvoid expect_adj_near(const T& a, const T& b, const char* msg) {}\nvoid expect_adj_near(var a, var b, const char* msg) {\n stan::test::expect_near_rel(msg, a.adj(), b.adj());\n}\ntemplate <typename T1, typename T2, require_all_eigen_t<T1, T2>* = nullptr,\n require_vt_same<T1, T2>* = nullptr>\nvoid expect_adj_near(const T1& a, const T2& b, const char* msg) {\n EXPECT_EQ(a.rows(), b.rows()) << msg;\n EXPECT_EQ(a.cols(), b.cols()) << msg;\n const auto& a_ref = math::to_ref(a);\n const auto& b_ref = math::to_ref(b);\n stan::test::expect_near_rel(msg, a_ref.adj(), b_ref.adj());\n}\ntemplate <typename T>\nvoid expect_adj_near(const std::vector<T>& a, const std::vector<T>& b,\n const char* msg) {\n EXPECT_EQ(a.size(), b.size()) << msg;\n for (int i = 0; i < a.size(); i++) {\n expect_adj_near(a[i], b[i], msg);\n }\n}\n\ntemplate <typename Functor>\nvoid prim_rev_argument_combinations(Functor f) {\n f(std::make_tuple(), std::make_tuple());\n}\ntemplate <typename Functor, typename Arg0, typename... Args>\nvoid prim_rev_argument_combinations(const Functor& f, const Arg0& arg0,\n const Args&... args) {\n prim_rev_argument_combinations(\n [&f, &arg0](auto args_for_cpu, auto args_for_opencl) {\n constexpr size_t Size\n = std::tuple_size<std::decay_t<decltype(args_for_cpu)>>::value;\n return index_apply<Size>([&](auto... Is) {\n return f(\n std::forward_as_tuple(arg0, std::get<Is>(args_for_cpu)...),\n std::forward_as_tuple(arg0, std::get<Is>(args_for_opencl)...));\n });\n },\n args...);\n prim_rev_argument_combinations(\n [&](const auto& args_for_cpu, const auto& args_for_opencl) {\n constexpr size_t Size\n = std::tuple_size<std::decay_t<decltype(args_for_cpu)>>::value;\n return index_apply<Size>([&](auto... Is) {\n return f(std::make_tuple(var_argument(arg0),\n std::get<Is>(args_for_cpu)...),\n std::make_tuple(var_argument(arg0),\n std::get<Is>(args_for_opencl)...));\n });\n },\n args...);\n}\n\ntemplate <typename Functor, std::size_t... Is, typename... Args>\nvoid compare_cpu_opencl_prim_rev_impl(const Functor& functor,\n std::index_sequence<Is...>,\n const Args&... args) {\n prim_rev_argument_combinations(\n [&functor](auto args_for_cpu, auto args_for_opencl) {\n auto res_cpu = functor(std::get<Is>(args_for_cpu)...);\n auto res_opencl\n = functor(opencl_argument(std::get<Is>(args_for_opencl))...);\n std::string signature = type_name<decltype(args_for_cpu)>().data();\n expect_eq(res_opencl, res_cpu,\n (\"CPU and OpenCL return values do not match for signature \"\n + signature + \"!\")\n .c_str());\n var(recursive_sum(res_cpu) + recursive_sum(res_opencl)).grad();\n\n static_cast<void>(std::initializer_list<int>{\n (expect_adj_near(\n std::get<Is>(args_for_opencl), std::get<Is>(args_for_cpu),\n (\"CPU and OpenCL adjoints do not match for argument \"\n + std::to_string(Is) + \" for signature \" + signature + \"!\")\n .c_str()),\n 0)...});\n\n set_zero_all_adjoints();\n },\n args...);\n}\n} \/\/ namespace internal\n\n\/**\n * Tests that given functor calculates same values and adjoints when given\n * arguments on CPU and OpenCL device.\n *\n * @tparam Functor type of the functor\n * @tparam Args types of the arguments\n * @param fucntor functor to test\n * @param args arguments to test the functor with. These should be just values\n * in CPU memory (no vars, no arguments on the OpenCL device).\n *\/\ntemplate <typename Functor, typename... Args>\nvoid compare_cpu_opencl_prim_rev(const Functor& functor, const Args&... args) {\n internal::compare_cpu_opencl_prim_rev_impl(\n functor, std::make_index_sequence<sizeof...(args)>{}, args...);\n}\n\n} \/\/ namespace test\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Create command\n\n#include \"SAMdisk.h\"\n\nbool CreateImage (const std::string &path, Range range)\n{\n\tauto disk = std::make_shared<Disk>();\n\n\tValidateRange(range, NORMAL_TRACKS, NORMAL_SIDES);\n\n\tFormat fmt;\n\tfmt.cyls = range.cyls();\n\tfmt.heads = range.heads();\n\n\t\/\/ Are we allowed to format?\n\tif (!opt.noformat)\n\t{\n\t\t\/\/ Set up the format for ProDos or MGT, with automatic gap3 size\n\t\tfmt = opt.cpm ? RegularFormat::ProDos : RegularFormat::MGT;\n\t\tfmt.gap3 = 0;\n\n\t\t\/\/ Prevent CP\/M wrapping during image write\n\t\topt.cpm = 0;\n\n\t\t\/\/ Set the disk label, if supplied\n\/\/\t\tif (opt.label)\n\/\/\t\t\tdisk->strDiskLabel = opt.label;\n\n\t\t\/\/ To ensure it fits by default, halve the sector count in FM mode\n\t\tif (opt.fm == 1) fmt.sectors >>= 1;\n\n\t\t\/\/ Allow everything about the format to be overridden\n\t\tOverrideFormat(fmt, true);\n\n\t\t\/\/ Check sector count and size\n\t\tValidateGeometry(1, 1, fmt.sectors, fmt.size, 7);\n\n\t\tdisk->format(fmt);\n\t}\n\n\t\/\/ Write to the output disk image\n\tWriteImage(path, disk);\n\n\tauto cyls = disk->cyls();\n\tauto heads = disk->heads();\n\n\t\/\/ Report the new disk parameters\n\tif (opt.noformat)\n\t\tutil::cout << util::fmt(\"Created %2u cyl%s, %u head%s, unformatted.\\n\", cyls, (cyls == 1) ? \"\" : \"s\", heads, (heads == 1) ? \"\" : \"s\");\n\telse\n\t{\n\t\tutil::cout << util::fmt(\"Created %2u cyl%s, %u head%s, %2u sector%s\/track, %4u bytes\/sector\\n\",\n\t\t\t\t\t\t\t\tcyls, (cyls == 1) ? \"\" : \"s\", heads, (heads == 1) ? \"\" : \"s\",\n\t\t\t\t\t\t\t\tfmt.sectors, (fmt.sectors == 1) ? \"\" : \"s\", fmt.sector_size());\n\t}\n\n\treturn true;\n}\n\nbool CreateHddImage (const std::string &path, int nSizeMB_)\n{\n\tbool f = false;\n\n\t\/\/ If no sector count is specified, use the size parameter\n\tint64_t llSize = (opt.sectors == -1) ? nSizeMB_ << 20 : opt.sectors << 9;\n\tif (llSize < 4 * 1024 * 1024)\n\t\tthrow util::exception(\"needs image size in MB (>=4) or sector count with -s\");\n\n\t\/\/ Create the specified HDD image, ensuring we don't overwrite any existing file\n\tauto hdd = HDD::CreateDisk(path, llSize, nullptr, false);\n\tif (!hdd)\n\t\tError(\"create\");\n\telse\n\t{\n\t\t\/\/ Zero-fill up to the required sector count\n\t\tf = hdd->Copy(nullptr, hdd->total_sectors, 0, 0, 0, \"Creating\");\n\n\t\t\/\/ If anything went wrong, remove the new file\n\t\tif (!f)\n\t\t\tunlink(path.c_str());\n\t}\n\n\treturn f;\n}\n<commit_msg>Fixed HDF creation clipping size to 32-bit<commit_after>\/\/ Create command\n\n#include \"SAMdisk.h\"\n\nbool CreateImage (const std::string &path, Range range)\n{\n\tauto disk = std::make_shared<Disk>();\n\n\tValidateRange(range, NORMAL_TRACKS, NORMAL_SIDES);\n\n\tFormat fmt;\n\tfmt.cyls = range.cyls();\n\tfmt.heads = range.heads();\n\n\t\/\/ Are we allowed to format?\n\tif (!opt.noformat)\n\t{\n\t\t\/\/ Set up the format for ProDos or MGT, with automatic gap3 size\n\t\tfmt = opt.cpm ? RegularFormat::ProDos : RegularFormat::MGT;\n\t\tfmt.gap3 = 0;\n\n\t\t\/\/ Prevent CP\/M wrapping during image write\n\t\topt.cpm = 0;\n\n\t\t\/\/ Set the disk label, if supplied\n\/\/\t\tif (opt.label)\n\/\/\t\t\tdisk->strDiskLabel = opt.label;\n\n\t\t\/\/ To ensure it fits by default, halve the sector count in FM mode\n\t\tif (opt.fm == 1) fmt.sectors >>= 1;\n\n\t\t\/\/ Allow everything about the format to be overridden\n\t\tOverrideFormat(fmt, true);\n\n\t\t\/\/ Check sector count and size\n\t\tValidateGeometry(1, 1, fmt.sectors, fmt.size, 7);\n\n\t\tdisk->format(fmt);\n\t}\n\n\t\/\/ Write to the output disk image\n\tWriteImage(path, disk);\n\n\tauto cyls = disk->cyls();\n\tauto heads = disk->heads();\n\n\t\/\/ Report the new disk parameters\n\tif (opt.noformat)\n\t\tutil::cout << util::fmt(\"Created %2u cyl%s, %u head%s, unformatted.\\n\", cyls, (cyls == 1) ? \"\" : \"s\", heads, (heads == 1) ? \"\" : \"s\");\n\telse\n\t{\n\t\tutil::cout << util::fmt(\"Created %2u cyl%s, %u head%s, %2u sector%s\/track, %4u bytes\/sector\\n\",\n\t\t\t\t\t\t\t\tcyls, (cyls == 1) ? \"\" : \"s\", heads, (heads == 1) ? \"\" : \"s\",\n\t\t\t\t\t\t\t\tfmt.sectors, (fmt.sectors == 1) ? \"\" : \"s\", fmt.sector_size());\n\t}\n\n\treturn true;\n}\n\nbool CreateHddImage (const std::string &path, int nSizeMB_)\n{\n\tbool f = false;\n\n\t\/\/ If no sector count is specified, use the size parameter\n\tauto total_size = (opt.sectors == -1) ?\n\t\tstatic_cast<int64_t>(nSizeMB_) << 20 :\n\t\tstatic_cast<int64_t>(opt.sectors) << 9;\n\n\tif (total_size < 4 * 1024 * 1024)\n\t\tthrow util::exception(\"needs image size in MB (>=4) or sector count with -s\");\n\n\t\/\/ Create the specified HDD image, ensuring we don't overwrite any existing file\n\tauto hdd = HDD::CreateDisk(path, total_size, nullptr, false);\n\tif (!hdd)\n\t\tError(\"create\");\n\telse\n\t{\n\t\t\/\/ Zero-fill up to the required sector count\n\t\tf = hdd->Copy(nullptr, hdd->total_sectors, 0, 0, 0, \"Creating\");\n\n\t\t\/\/ If anything went wrong, remove the new file\n\t\tif (!f)\n\t\t\tunlink(path.c_str());\n\t}\n\n\treturn f;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.\n\/\/ Copyright (c) 2015-2017, University of Bremen\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n#define BOOST_TEST_MODULE VizTest\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/archive\/polymorphic_binary_oarchive.hpp>\n\n#include <Eigen\/Geometry>\n\n#include \"StandaloneVisualizer.hpp\"\n#include <maps\/grid\/MLSMap.hpp>\n\n#include <maps\/operations\/CoverageMapGeneration.hpp>\n\nusing namespace ::maps::grid;\n\ntemplate<class MLSMap>\nstatic void show_MLS(const MLSMap& mls)\n{\n std::cout << \"update finish\" << std::endl;\n StandaloneVisualizer app;\n app.updateData(mls);\n\n while (app.wait(1000))\n {\n }\n}\n\n\n\nBOOST_AUTO_TEST_CASE(mls_loop)\n{\n \/\/ GridConfig conf(150, 150, 0.1, 0.1, -7.5, -7.5);\n Eigen::Vector2d res(0.1, 0.1);\n Vector2ui numCells(150, 150);\n\n MLSConfig mls_config;\n mls_config.updateModel = MLSConfig::KALMAN;\n mls_config.gapSize = 0.05f;\n mls_config.useNegativeInformation = false;\n float R = 5.0f, r=2.05f;\n MLSMapKalman mls(numCells, res, mls_config);\n\n maps::operations::CoverageTracker coverage;\n\n\n mls.getLocalFrame().translation() << 0.5*mls.getSize(), 0;\n\n coverage.setFrame(mls);\n\n StandaloneVisualizer app;\n\n Eigen::ArrayXXd ranges;\n PointCloud pointcloud;\n base::Pose trafo;\n int loop = 0;\n while (app.wait(1000))\n {\n if(++loop & 1023) continue;\n trafo.position +=Eigen::Vector3d::Random() * 0.5;\n Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize();\n trafo.orientation = q;\n\n coverage.addCoverage(2.0, base::AngleSegment(), trafo);\n\n app.updateData(coverage.getCoverage());\n }\n}\n\n<commit_msg>fix warnings and renamed test case<commit_after>\/\/\n\/\/ Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.\n\/\/ Copyright (c) 2015-2017, University of Bremen\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n#define BOOST_TEST_MODULE VizTest\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/archive\/polymorphic_binary_oarchive.hpp>\n\n#include <Eigen\/Geometry>\n\n#include \"StandaloneVisualizer.hpp\"\n#include <maps\/grid\/MLSMap.hpp>\n\n#include <maps\/operations\/CoverageMapGeneration.hpp>\n\nusing namespace ::maps::grid;\n\ntemplate<class MLSMap>\nstatic void show_MLS(const MLSMap& mls)\n{\n std::cout << \"update finish\" << std::endl;\n StandaloneVisualizer app;\n app.updateData(mls);\n\n while (app.wait(1000))\n {\n }\n}\n\n\n\nBOOST_AUTO_TEST_CASE(mls_coverage)\n{\n \/\/ GridConfig conf(150, 150, 0.1, 0.1, -7.5, -7.5);\n Eigen::Vector2d res(0.1, 0.1);\n Vector2ui numCells(150, 150);\n\n MLSConfig mls_config;\n mls_config.updateModel = MLSConfig::KALMAN;\n mls_config.gapSize = 0.05f;\n mls_config.useNegativeInformation = false;\n MLSMapKalman mls(numCells, res, mls_config);\n\n maps::operations::CoverageTracker coverage;\n\n\n mls.getLocalFrame().translation() << 0.5*mls.getSize(), 0;\n\n coverage.setFrame(mls);\n\n StandaloneVisualizer app;\n\n Eigen::ArrayXXd ranges;\n PointCloud pointcloud;\n base::Pose trafo;\n int loop = 0;\n while (app.wait(1000))\n {\n if(++loop & 1023) continue;\n trafo.position +=Eigen::Vector3d::Random() * 0.5;\n Eigen::Quaterniond q; q.coeffs().setRandom(); q.normalize();\n trafo.orientation = q;\n\n coverage.addCoverage(2.0, base::AngleSegment(), trafo);\n\n app.updateData(coverage.getCoverage());\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015\n\/\/ Ravi Peters -- r.y.peters@tudelft.nl\n\/\/ All rights reserved\n\/\/ This file is part of masbcpp.\n\/\/\n\/\/ masbcpp is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ masbcpp is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with masbcpp. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ #define VERBOSEPRINT 1;\n\/\/ #define WITH_OPENMP 1;\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n\/\/ OpenMP\n#ifdef WITH_OPENMP\n #ifdef CLANG_OMP\n #include <libiomp\/omp.h>\n #else\n #include <omp.h>\n #endif\n#endif\n\n\/\/ Vrui\n#include <vrui\/Geometry\/ComponentArray.h>\n#include <vrui\/Math\/Math.h>\n#include <vrui\/Misc\/Timer.h>\n\/\/ kdtree2\n#include <kdtree2\/kdtree2.hpp>\n\/\/ cnpy\n#include <cnpy\/cnpy.h>\n\/\/ tclap\n#include <tclap\/CmdLine.h>\n\n\/\/ typedefs\n#include \"types.h\"\n\n\/\/ globals\nScalar initial_radius;\ndouble denoise_preserve;\ndouble denoise_planar;\nconst Scalar delta_convergance = 1E-5;\nconst uint iteration_limit = 30;\n\ninline Scalar compute_radius(Point &p, Vector &n, Point &q)\n{\n \/\/ this is basic goniometry\n double d = Geometry::mag(p-q);\n Scalar cos_theta = ( n * (p-q) ) \/ d;\n return d\/(2*cos_theta);\n}\n\ninline Scalar cos_angle(Vector p, Vector q)\n{\n \/\/ Calculate the cosine of angle between vector p and q, see http:\/\/en.wikipedia.org\/wiki\/Law_of_cosines#Vector_formulation\n Scalar result = p*q \/ ( Geometry::mag(p) * Geometry::mag(q) );\n if( result > 1 ) return 1;\n else if( result < -1 ) return -1;\n return result;\n}\n\nPoint sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)\n{\n uint j=0;\n Scalar r, r_previous = 0;\n Point q, c_next;\n Point c = p - n * initial_radius;\n\n while (1) \n {\n #ifdef VERBOSEPRINT\n std::cout << \"\\nloop iteration: \" << j << \", p = (\" << p[0] << \",\" << p[1] << \",\" << p[2] << \", n = (\" << n[0] << \",\" << n[1] << \",\" << n[2] << \") \\n\";\n\n std::cout << \"c = (\" << c[0] << \",\" << c[1] << \",\" << c[2] << \")\\n\";\n #endif\n\n \/\/ find closest point to c\n kdtree2::KDTreeResultVector result;\n kd_tree->n_nearest(c,2,result);\n q = kd_tree->the_data[ result[0].idx ];\n\n #ifdef VERBOSEPRINT\n std::cout << \"q = (\" << q[0] << \",\" << q[1] << \",\" << q[2] << \")\\n\";\n #endif\n\n \/\/ handle case when q==p\n if( q == p )\n {\n \/\/ 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball\n if( r_previous == initial_radius )\n {\n r = initial_radius;\n break;\n \/\/ 2) otherwise just pick the second closest point\n } else {\n q = kd_tree->the_data[ result[1].idx ];\n }\n }\n\n \/\/ compute radius\n r = compute_radius(p,n,q);\n\n #ifdef VERBOSEPRINT\n std::cout << \"r = \" << r << \"\\n\";\n #endif\n\n \/\/ if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane\n if( r < 0 )\n r = initial_radius;\n \/\/ if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop\n else if( r > initial_radius )\n {\n r = initial_radius;\n break;\n }\n\n \/\/ compute next ball center\n c_next = p - n * r;\n\n \/\/ denoising\n if( denoise_preserve or denoise_planar )\n {\n Scalar a = cos_angle(p-c_next, q-c_next);\n Scalar separation_angle = Math::acos(a);\n\n if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )\n {\n \/\/ keep previous radius:\n r = r_previous;\n break;\n }\n if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )\n {\n r = initial_radius;\n break;\n }\n }\n\n \/\/ stop iteration if r has converged\n if( Math::abs(r_previous-r) < delta_convergance )\n break;\n\n \/\/ stop iteration if this looks like an infinite loop:\n if( j > iteration_limit )\n break;\n\n r_previous = r;\n c = c_next;\n j++;\n \n }\n\n return c;\n}\n\nPointList sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, bool inner=1)\n{\n PointList ma_coords(points.size());\n Point p;\n Vector n;\n\n #pragma omp parallel for private(p, n)\n for( uint i=0; i<points.size(); i++ )\n {\n p = points[i];\n if( inner )\n n = normals[i];\n else\n n = -normals[i];\n ma_coords[i] = sb_point(p, n, kd_tree);\n }\n return ma_coords;\n}\n\n\nint main(int argc, char **argv)\n{\n \/\/ parse command line arguments\n try {\n TCLAP::CmdLine cmd(\"Computes a MAT point approximation\", ' ', \"0.1\");\n\n TCLAP::UnlabeledValueArg<std::string> inputArg( \"input\", \"path to directory with inside it a 'coords.npy' and a 'normals.npy' file\", true, \"\", \"input dir\", cmd);\n TCLAP::UnlabeledValueArg<std::string> outputArg( \"ouput\", \"path to output directory\", true, \"\", \"output dir\", cmd);\n\n TCLAP::ValueArg<double> denoise_preserveArg(\"d\",\"preserve\",\"denoise preserve threshold\",false,20,\"double\", cmd);\n TCLAP::ValueArg<double> denoise_planarArg(\"p\",\"planar\",\"denoise planar threshold\",false,32,\"double\", cmd);\n TCLAP::ValueArg<double> initial_radiusArg(\"r\",\"radius\",\"initial ball radius\",false,200,\"double\", cmd);\n\n cmd.parse(argc,argv);\n \n initial_radius = initial_radiusArg.getValue();\n denoise_preserve = (3.1415\/180) * denoise_preserveArg.getValue();\n denoise_planar = (3.1415\/180) * denoise_planarArg.getValue();\n\n std::string input_coords_path = inputArg.getValue()+\"\/coords.npy\";\n std::string input_normals_path = inputArg.getValue()+\"\/normals.npy\";\n\n \/\/ check for proper in-output arguments\n {\n std::ifstream infile(input_coords_path.c_str());\n if(!infile)\n throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n }\n {\n std::ifstream infile(input_normals_path.c_str());\n if(!infile)\n throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n }\n {\n std::string output_path = outputArg.getValue()+\"\/ma_coords_in.npy\";\n std::ofstream outfile(output_path.c_str()); \n if(!outfile)\n throw TCLAP::ArgParseException(\"invalid filepath\", outputArg.getValue());\n }\n \n std::cout << \"Parameters: denoise_preserve=\"<<denoise_preserve<<\", denoise_planar=\"<<denoise_planar<<\", initial_radius=\"<<initial_radius<<\"\\n\";\n\n cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );\n float* coords_carray = reinterpret_cast<float*>(coords_npy.data);\n\n uint num_points = coords_npy.shape[0];\n uint dim = coords_npy.shape[1];\n PointList coords(num_points);\n for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);\n coords_npy.destruct();\n\n cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );\n float* normals_carray = reinterpret_cast<float*>(normals_npy.data);\n VectorList normals(normals_npy.shape[0]);\n for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);\n normals_npy.destruct();\n \n Misc::Timer t0;\n kdtree2::KDTree* kd_tree;\n kd_tree = new kdtree2::KDTree(coords,true);\n kd_tree->sort_results = true;\n t0.elapse();\n std::cout<<\"Constructed kd-tree in \"<<t0.getTime()*1000.0<<\" ms\"<<std::endl;\n\n \/\/ omp_set_num_threads(4);\n\n {\n Scalar* ma_coords_in_carray = new Scalar[num_points*3];\n Misc::Timer t1;\n PointList ma_coords_in = sb_points(coords, normals, kd_tree, 1);\n t1.elapse();\n std::cout<<\"Done shrinking interior balls, took \"<<t1.getTime()*1000.0<<\" ms\"<<std::endl;\n \n \n for (int i=0; i<ma_coords_in.size(); i++)\n for (int j=0; j<3; j++)\n ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];\n \n const unsigned int c_size = ma_coords_in.size();\n const unsigned int shape[] = {c_size,3};\n cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_in.npy\").c_str(), ma_coords_in_carray, shape, 2, \"w\");\n }\n\n {\n Scalar* ma_coords_out_carray = new Scalar[num_points*3];\n Misc::Timer t2;\n PointList ma_coords_out = sb_points(coords, normals, kd_tree, 0);\n t2.elapse();\n std::cout<<\"Done shrinking exterior balls, took \"<<t2.getTime()*1000.0<<\" ms\"<<std::endl;\n \n for (int i=0; i<ma_coords_out.size(); i++)\n for (int j=0; j<3; j++)\n ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];\n\n const unsigned int c_size = ma_coords_out.size();\n const unsigned int shape[] = {c_size,3};\n cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_out.npy\").c_str(), ma_coords_out_carray, shape, 2, \"w\");\n }\n\n } catch (TCLAP::ArgException &e) { std::cerr << \"Error: \" << e.error() << \" for \" << e.argId() << std::endl; }\n\n return 0;\n}\n<commit_msg>handle invalid MA points properly with float nan's<commit_after>\/\/ Copyright (c) 2015\n\/\/ Ravi Peters -- r.y.peters@tudelft.nl\n\/\/ All rights reserved\n\/\/ This file is part of masbcpp.\n\/\/\n\/\/ masbcpp is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ masbcpp is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with masbcpp. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ #define VERBOSEPRINT 1;\n\/\/ #define WITH_OPENMP 1;\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <limits>\n\n\/\/ OpenMP\n#ifdef WITH_OPENMP\n #ifdef CLANG_OMP\n #include <libiomp\/omp.h>\n #else\n #include <omp.h>\n #endif\n#endif\n\n\/\/ Vrui\n#include <vrui\/Geometry\/ComponentArray.h>\n#include <vrui\/Math\/Math.h>\n#include <vrui\/Misc\/Timer.h>\n\/\/ kdtree2\n#include <kdtree2\/kdtree2.hpp>\n\/\/ cnpy\n#include <cnpy\/cnpy.h>\n\/\/ tclap\n#include <tclap\/CmdLine.h>\n\n\/\/ typedefs\n#include \"types.h\"\n\n\/\/ globals\nScalar initial_radius;\ndouble denoise_preserve;\ndouble denoise_planar;\nconst Scalar delta_convergance = 1E-5;\nconst uint iteration_limit = 30;\nconst Point nanPoint( std::numeric_limits<Scalar>::quiet_NaN() );\n\ninline Scalar compute_radius(Point &p, Vector &n, Point &q)\n{\n \/\/ this is basic goniometry\n double d = Geometry::mag(p-q);\n Scalar cos_theta = ( n * (p-q) ) \/ d;\n return d\/(2*cos_theta);\n}\n\ninline Scalar cos_angle(Vector p, Vector q)\n{\n \/\/ Calculate the cosine of angle between vector p and q, see http:\/\/en.wikipedia.org\/wiki\/Law_of_cosines#Vector_formulation\n Scalar result = p*q \/ ( Geometry::mag(p) * Geometry::mag(q) );\n if( result > 1 ) return 1;\n else if( result < -1 ) return -1;\n return result;\n}\n\nPoint sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)\n{\n uint j=0;\n Scalar r, r_previous = 0;\n Point q, c_next;\n Point c = p - n * initial_radius;\n\n while (1) \n {\n #ifdef VERBOSEPRINT\n std::cout << \"\\nloop iteration: \" << j << \", p = (\" << p[0] << \",\" << p[1] << \",\" << p[2] << \", n = (\" << n[0] << \",\" << n[1] << \",\" << n[2] << \") \\n\";\n\n std::cout << \"c = (\" << c[0] << \",\" << c[1] << \",\" << c[2] << \")\\n\";\n #endif\n\n \/\/ find closest point to c\n kdtree2::KDTreeResultVector result;\n kd_tree->n_nearest(c,2,result);\n q = kd_tree->the_data[ result[0].idx ];\n\n #ifdef VERBOSEPRINT\n std::cout << \"q = (\" << q[0] << \",\" << q[1] << \",\" << q[2] << \")\\n\";\n #endif\n\n \/\/ handle case when q==p\n if( q == p )\n {\n \/\/ 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball\n if( r_previous == initial_radius )\n {\n r = initial_radius;\n c = nanPoint;\n break;\n \/\/ 2) otherwise just pick the second closest point\n } else {\n q = kd_tree->the_data[ result[1].idx ];\n }\n }\n\n \/\/ compute radius\n r = compute_radius(p,n,q);\n\n #ifdef VERBOSEPRINT\n std::cout << \"r = \" << r << \"\\n\";\n #endif\n\n \/\/ if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane\n if( r < 0 )\n r = initial_radius;\n \/\/ if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop\n else if( r > initial_radius )\n {\n r = initial_radius;\n c = nanPoint;\n break;\n }\n\n \/\/ compute next ball center\n c_next = p - n * r;\n\n \/\/ denoising\n if( denoise_preserve or denoise_planar )\n {\n Scalar a = cos_angle(p-c_next, q-c_next);\n Scalar separation_angle = Math::acos(a);\n\n if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )\n {\n \/\/ keep previous radius:\n r = r_previous;\n break;\n }\n if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )\n {\n r = initial_radius;\n c = nanPoint;\n break;\n }\n }\n\n \/\/ stop iteration if r has converged\n if( Math::abs(r_previous-r) < delta_convergance )\n break;\n\n \/\/ stop iteration if this looks like an infinite loop:\n if( j > iteration_limit )\n break;\n\n r_previous = r;\n c = c_next;\n j++;\n }\n \n return c;\n}\n\nPointList sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, bool inner=1)\n{\n PointList ma_coords(points.size());\n Point p;\n Vector n;\n\n #pragma omp parallel for private(p, n)\n for( uint i=0; i<points.size(); i++ )\n {\n p = points[i];\n if( inner )\n n = normals[i];\n else\n n = -normals[i];\n ma_coords[i] = sb_point(p, n, kd_tree);\n }\n return ma_coords;\n}\n\n\nint main(int argc, char **argv)\n{\n \/\/ parse command line arguments\n try {\n TCLAP::CmdLine cmd(\"Computes a MAT point approximation\", ' ', \"0.1\");\n\n TCLAP::UnlabeledValueArg<std::string> inputArg( \"input\", \"path to directory with inside it a 'coords.npy' and a 'normals.npy' file\", true, \"\", \"input dir\", cmd);\n TCLAP::UnlabeledValueArg<std::string> outputArg( \"ouput\", \"path to output directory\", true, \"\", \"output dir\", cmd);\n\n TCLAP::ValueArg<double> denoise_preserveArg(\"d\",\"preserve\",\"denoise preserve threshold\",false,20,\"double\", cmd);\n TCLAP::ValueArg<double> denoise_planarArg(\"p\",\"planar\",\"denoise planar threshold\",false,32,\"double\", cmd);\n TCLAP::ValueArg<double> initial_radiusArg(\"r\",\"radius\",\"initial ball radius\",false,200,\"double\", cmd);\n\n cmd.parse(argc,argv);\n \n initial_radius = initial_radiusArg.getValue();\n denoise_preserve = (3.1415\/180) * denoise_preserveArg.getValue();\n denoise_planar = (3.1415\/180) * denoise_planarArg.getValue();\n\n std::string input_coords_path = inputArg.getValue()+\"\/coords.npy\";\n std::string input_normals_path = inputArg.getValue()+\"\/normals.npy\";\n\n \/\/ check for proper in-output arguments\n {\n std::ifstream infile(input_coords_path.c_str());\n if(!infile)\n throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n }\n {\n std::ifstream infile(input_normals_path.c_str());\n if(!infile)\n throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n }\n {\n std::string output_path = outputArg.getValue()+\"\/ma_coords_in.npy\";\n std::ofstream outfile(output_path.c_str()); \n if(!outfile)\n throw TCLAP::ArgParseException(\"invalid filepath\", outputArg.getValue());\n }\n \n std::cout << \"Parameters: denoise_preserve=\"<<denoise_preserve<<\", denoise_planar=\"<<denoise_planar<<\", initial_radius=\"<<initial_radius<<\"\\n\";\n\n cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );\n float* coords_carray = reinterpret_cast<float*>(coords_npy.data);\n\n uint num_points = coords_npy.shape[0];\n uint dim = coords_npy.shape[1];\n PointList coords(num_points);\n for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);\n coords_npy.destruct();\n\n cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );\n float* normals_carray = reinterpret_cast<float*>(normals_npy.data);\n VectorList normals(normals_npy.shape[0]);\n for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);\n normals_npy.destruct();\n \n Misc::Timer t0;\n kdtree2::KDTree* kd_tree;\n kd_tree = new kdtree2::KDTree(coords,true);\n kd_tree->sort_results = true;\n t0.elapse();\n std::cout<<\"Constructed kd-tree in \"<<t0.getTime()*1000.0<<\" ms\"<<std::endl;\n\n \/\/ omp_set_num_threads(4);\n\n {\n Scalar* ma_coords_in_carray = new Scalar[num_points*3];\n Misc::Timer t1;\n PointList ma_coords_in = sb_points(coords, normals, kd_tree, 1);\n t1.elapse();\n std::cout<<\"Done shrinking interior balls, took \"<<t1.getTime()*1000.0<<\" ms\"<<std::endl;\n \n \n for (int i=0; i<ma_coords_in.size(); i++)\n for (int j=0; j<3; j++)\n ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];\n \n const unsigned int c_size = ma_coords_in.size();\n const unsigned int shape[] = {c_size,3};\n cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_in.npy\").c_str(), ma_coords_in_carray, shape, 2, \"w\");\n }\n\n {\n Scalar* ma_coords_out_carray = new Scalar[num_points*3];\n Misc::Timer t2;\n PointList ma_coords_out = sb_points(coords, normals, kd_tree, 0);\n t2.elapse();\n std::cout<<\"Done shrinking exterior balls, took \"<<t2.getTime()*1000.0<<\" ms\"<<std::endl;\n \n for (int i=0; i<ma_coords_out.size(); i++)\n for (int j=0; j<3; j++)\n ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];\n\n const unsigned int c_size = ma_coords_out.size();\n const unsigned int shape[] = {c_size,3};\n cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_out.npy\").c_str(), ma_coords_out_carray, shape, 2, \"w\");\n }\n\n } catch (TCLAP::ArgException &e) { std::cerr << \"Error: \" << e.error() << \" for \" << e.argId() << std::endl; }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- shm.cpp -----------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Save\/restore via shared memory to survive exec*()\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"shm.h\"\n\n#include \"ipcreg_internal.h\"\n#include \"magic_socket_nums.h\"\n#include \"real.h\"\n#include \"rename_fd.h\"\n\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#define UC(ret, msg) \\\n unixCheck(ret, msg, __FILE__, __LINE__, __PRETTY_FUNCTION__);\n\nvoid unixCheck(int ret, const char *msg, const char *file, unsigned line,\n const char *func, int err = errno) {\n if (ret == -1) {\n ipclog(\"Unix call failed in %s at %s:%u: %s - %s\\n\", func, file, line, msg,\n strerror(err));\n abort();\n }\n}\n\nstatic char buf[100];\nconst char *getShmName() {\n sprintf(buf, \"\/ipcd.%d\\n\", getpid());\n return buf;\n}\n\nint get_shm(int flags, mode_t mode) {\n int fd = shm_open(getShmName(), flags, mode);\n if (fd == -1 && errno == EEXIST) {\n ipclog(\"Shared memory segment exists, attempting to remove it...\\n\");\n int ret = shm_unlink(getShmName());\n UC(ret, \"Closing existing shm\");\n\n \/\/ Okay, let's try this again\n fd = shm_open(getShmName(), flags, mode);\n }\n UC(fd, \"shm_open\");\n UC(fchmod(fd, mode), \"fchmod on shared memory segment\");\n return fd;\n}\n\nvoid shm_state_save() {\n \/\/ Create shared memory segment\n int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0777);\n UC(fd, \"get_shm\");\n\n bool success = rename_fd(fd, MAGIC_SHM_FD, \/* cloexec *\/ false);\n assert(success && \"Failed to rename SHM fd!\");\n\n \/\/ Do *not* close on exec! :)\n int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, \/* kludge *\/ 0);\n assert(flags >= 0);\n flags &= ~FD_CLOEXEC;\n int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags);\n UC(ret, \"fcntl CLOEXEC on shared memory segment\");\n\n \/\/ Size the memory segment:\n ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state));\n UC(ret, \"ftruncate on shm\");\n\n void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE,\n MAP_SHARED, MAGIC_SHM_FD, 0);\n assert(stateptr != MAP_FAILED);\n\n \/\/ Copy state to shared memory segment\n *(libipc_state*)stateptr = state;\n\n \/\/ Unmap, but don't unlink the shared memory\n ret = munmap(stateptr, sizeof(libipc_state));\n UC(ret, \"unmap shm\");\n\n ipclog(\"State saved!\\n\");\n}\n\nbool is_valid_fd(int fd) {\n return __real_fcntl(fd, F_GETFD, \/* kludge *\/ 0) >= 0;\n}\n\nvoid shm_state_restore() {\n \/\/ If we have memory to restore, it'll be in our magic FD!\n if (!is_valid_fd(MAGIC_SHM_FD))\n return;\n\n ipclog(\"Inherited ipc state FD, starting state restoration...\\n\");\n\n void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE,\n MAP_SHARED, MAGIC_SHM_FD, 0);\n \/\/ If our FD is still open, the memory better still be there!\n assert(stateptr != MAP_FAILED);\n\n \/\/ Copy state to shared memory segment\n \/\/ Copy state from shared memory segment\n state = *(libipc_state*)stateptr;\n\n int ret = munmap(stateptr, sizeof(libipc_state));\n UC(ret, \"unmap shm\");\n\n \/\/ Done with the shared segment, thank you!\n ret = __real_close(MAGIC_SHM_FD);\n UC(ret, \"close shm\");\n ret = shm_unlink(getShmName());\n UC(ret, \"shm_unlink after close\");\n\n ipclog(\"State restored!\\n\");\n}\n\nvoid shm_state_destroy() {\n \/\/ If we have memory to restore, it'll be in our magic FD!\n assert(is_valid_fd(MAGIC_SHM_FD));\n\n int ret = __real_close(MAGIC_SHM_FD);\n assert(ret == 0);\n\n ret = shm_unlink(getShmName());\n UC(ret, \"shm_unlink\");\n\n ipclog(\"Destroyed saved state!\\n\");\n}\n<commit_msg>libipc: Issue shm_unlink while still open, hopefully fix perm issues.<commit_after>\/\/===-- shm.cpp -----------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Save\/restore via shared memory to survive exec*()\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"shm.h\"\n\n#include \"ipcreg_internal.h\"\n#include \"magic_socket_nums.h\"\n#include \"real.h\"\n#include \"rename_fd.h\"\n\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string.h>\n\n#define UC(ret, msg) \\\n unixCheck(ret, msg, __FILE__, __LINE__, __PRETTY_FUNCTION__);\n\nvoid unixCheck(int ret, const char *msg, const char *file, unsigned line,\n const char *func, int err = errno) {\n if (ret == -1) {\n ipclog(\"Unix call failed in %s at %s:%u: %s - %s\\n\", func, file, line, msg,\n strerror(err));\n abort();\n }\n}\n\nstatic char buf[100];\nconst char *getShmName() {\n sprintf(buf, \"\/ipcd.%d\\n\", getpid());\n return buf;\n}\n\nint get_shm(int flags, mode_t mode) {\n int fd = shm_open(getShmName(), flags, mode);\n if (fd == -1 && errno == EEXIST) {\n ipclog(\"Shared memory segment exists, attempting to remove it...\\n\");\n int ret = shm_unlink(getShmName());\n UC(ret, \"Closing existing shm\");\n\n \/\/ Okay, let's try this again\n fd = shm_open(getShmName(), flags, mode);\n }\n UC(fd, \"shm_open\");\n UC(fchmod(fd, mode), \"fchmod on shared memory segment\");\n return fd;\n}\n\nvoid shm_state_save() {\n \/\/ Create shared memory segment\n int fd = get_shm(O_RDWR | O_CREAT | O_EXCL, 0400);\n UC(fd, \"get_shm\");\n\n bool success = rename_fd(fd, MAGIC_SHM_FD, \/* cloexec *\/ false);\n assert(success && \"Failed to rename SHM fd!\");\n\n \/\/ Do *not* close on exec! :)\n int flags = __real_fcntl(MAGIC_SHM_FD, F_GETFD, \/* kludge *\/ 0);\n assert(flags >= 0);\n flags &= ~FD_CLOEXEC;\n int ret = __real_fcntl_int(MAGIC_SHM_FD, F_SETFD, flags);\n UC(ret, \"fcntl CLOEXEC on shared memory segment\");\n\n \/\/ Size the memory segment:\n ret = ftruncate(MAGIC_SHM_FD, sizeof(libipc_state));\n UC(ret, \"ftruncate on shm\");\n\n void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE,\n MAP_SHARED, MAGIC_SHM_FD, 0);\n assert(stateptr != MAP_FAILED);\n\n \/\/ Copy state to shared memory segment\n *(libipc_state*)stateptr = state;\n\n \/\/ Unmap memory, we're done with it\n ret = munmap(stateptr, sizeof(libipc_state));\n UC(ret, \"unmap shm\");\n\n \/\/ Issue request to unlink the memory,\n \/\/ but this won't occur until our fd is closed.\n \/\/ (which we leave open intentionally)\n ret = shm_unlink(getShmName());\n UC(ret, \"eager shm_unlink\");\n\n ipclog(\"State saved!\\n\");\n}\n\nbool is_valid_fd(int fd) {\n return __real_fcntl(fd, F_GETFD, \/* kludge *\/ 0) >= 0;\n}\n\nvoid shm_state_restore() {\n \/\/ If we have memory to restore, it'll be in our magic FD!\n if (!is_valid_fd(MAGIC_SHM_FD))\n return;\n\n ipclog(\"Inherited ipc state FD, starting state restoration...\\n\");\n\n void *stateptr = mmap(NULL, sizeof(libipc_state), PROT_READ | PROT_WRITE,\n MAP_SHARED, MAGIC_SHM_FD, 0);\n \/\/ If our FD is still open, the memory better still be there!\n assert(stateptr != MAP_FAILED);\n\n \/\/ Copy state to shared memory segment\n \/\/ Copy state from shared memory segment\n state = *(libipc_state*)stateptr;\n\n int ret = munmap(stateptr, sizeof(libipc_state));\n UC(ret, \"unmap shm\");\n\n \/\/ Done with the shared segment, thank you!\n ret = __real_close(MAGIC_SHM_FD);\n UC(ret, \"close shm\");\n\n ipclog(\"State restored!\\n\");\n}\n\nvoid shm_state_destroy() {\n \/\/ If we have memory to restore, it'll be in our magic FD!\n assert(is_valid_fd(MAGIC_SHM_FD));\n\n int ret = __real_close(MAGIC_SHM_FD);\n assert(ret == 0);\n\n ipclog(\"Destroyed saved state!\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>A friend declaration is not an actual declaration of the function. icc seem 'mean' about it.<commit_after><|endoftext|>"} {"text":"<commit_before>#define TP_QT4_ENABLE_LOWLEVEL_API\n\n#include <TelepathyQt4\/AvatarData>\n#include <TelepathyQt4\/ChannelFactory>\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ConnectionLowlevel>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactFactory>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingReady>\n\n#include <telepathy-glib\/telepathy-glib.h>\n\n#include <tests\/lib\/glib\/contacts-conn.h>\n#include <tests\/lib\/test.h>\n\nusing namespace Tp;\n\nclass SmartDir : public QDir\n{\npublic:\n SmartDir(const QString &path) : QDir(path) { }\n bool rmdir() { return QDir().rmdir(path()); }\n bool removeDirectory();\n};\n\nbool SmartDir::removeDirectory()\n{\n bool ret = true;\n\n QFileInfoList list = entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);\n Q_FOREACH (QFileInfo info, list) {\n if (info.isDir()) {\n SmartDir subDir(info.filePath());\n if (!subDir.removeDirectory()) {\n ret = false;\n }\n } else {\n qDebug() << \"deleting\" << info.filePath();\n if (!QFile(info.filePath()).remove()) {\n ret = false;\n }\n }\n }\n\n if (ret) {\n qDebug() << \"deleting\" << path();\n ret = rmdir();\n }\n\n return ret;\n}\n\nclass TestContactsAvatar : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsAvatar(QObject *parent = 0)\n : Test(parent), mConnService(0)\n { }\n\nprotected Q_SLOTS:\n void expectConnInvalidated();\n void expectPendingContactsFinished(Tp::PendingOperation *);\n void onAvatarRetrieved(uint, const QString &, const QByteArray &, const QString &);\n void onAvatarDataChanged(const Tp::AvatarData &);\n void createContactWithFakeAvatar(const char *);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testAvatar();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n QString mConnName, mConnPath;\n TpTestsContactsConnection *mConnService;\n ConnectionPtr mConn;\n QList<ContactPtr> mContacts;\n bool mAvatarRetrievedCalled;\n};\n\nvoid TestContactsAvatar::onAvatarRetrieved(uint handle, const QString &token,\n const QByteArray &data, const QString &mimeType)\n{\n Q_UNUSED(handle);\n Q_UNUSED(token);\n Q_UNUSED(data);\n Q_UNUSED(mimeType);\n\n mAvatarRetrievedCalled = true;\n}\n\nvoid TestContactsAvatar::onAvatarDataChanged(const AvatarData &avatar)\n{\n Q_UNUSED(avatar);\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::createContactWithFakeAvatar(const char *id)\n{\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n (TpBaseConnection *) mConnService, TP_HANDLE_TYPE_CONTACT);\n const gchar avatarData[] = \"fake-avatar-data\";\n const gchar avatarToken[] = \"fake-avatar-token\";\n const gchar avatarMimeType[] = \"fake-avatar-mime-type\";\n TpHandle handle;\n GArray *array;\n\n handle = tp_handle_ensure(serviceRepo, id, NULL, NULL);\n array = g_array_new(FALSE, FALSE, sizeof(gchar));\n g_array_append_vals (array, avatarData, strlen(avatarData));\n\n tp_tests_contacts_connection_change_avatar_data(mConnService, handle,\n array, avatarMimeType, avatarToken);\n\n Tp::UIntList handles = Tp::UIntList() << handle;\n Features features = Features()\n << Contact::FeatureAvatarToken\n << Contact::FeatureAvatarData;\n\n PendingContacts *pending = mConn->contactManager()->contactsForHandles(\n handles, features);\n QVERIFY(connect(pending,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mContacts.size(), 1);\n\n if (mContacts[0]->avatarData().fileName.isEmpty()) {\n QVERIFY(connect(mContacts[0].data(),\n SIGNAL(avatarDataChanged(const Tp::AvatarData &)),\n SLOT(onAvatarDataChanged(const Tp::AvatarData &))));\n QCOMPARE(mLoop->exec(), 0);\n }\n\n AvatarData avatar = mContacts[0]->avatarData();\n\n qDebug() << \"Contact created:\";\n qDebug() << \"Avatar token:\" << mContacts[0]->avatarToken();\n qDebug() << \"Avatar file:\" << avatar.fileName;\n qDebug() << \"Avatar MimeType:\" << avatar.mimeType;\n\n QFile file(avatar.fileName);\n file.open(QIODevice::ReadOnly);\n QByteArray data(file.readAll());\n file.close();\n\n QCOMPARE(mContacts[0]->avatarToken(), QString(QLatin1String(avatarToken)));\n QCOMPARE(data, QByteArray(avatarData));\n QCOMPARE(avatar.mimeType, QString(QLatin1String(avatarMimeType)));\n}\n\n#define RAND_STR_LEN 6\n\nvoid TestContactsAvatar::testAvatar()\n{\n \/* Make sure our tests does not mess up user's avatar cache *\/\n qsrand(time(0));\n static const char letters[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n static const int DirNameLength = 6;\n QString dirName;\n for (int i = 0; i < DirNameLength; ++i) {\n dirName += QLatin1Char(letters[qrand() % qstrlen(letters)]);\n }\n QString tmpDir = QString(QLatin1String(\"%1\/%2\")).arg(QDir::tempPath()).arg(dirName);\n QByteArray a = tmpDir.toLatin1();\n setenv (\"XDG_CACHE_HOME\", a.constData(), true);\n\n Client::ConnectionInterfaceAvatarsInterface *connAvatarsInterface =\n mConn->optionalInterface<Client::ConnectionInterfaceAvatarsInterface>();\n\n \/* Check if AvatarRetrieved gets called *\/\n connect(connAvatarsInterface,\n SIGNAL(AvatarRetrieved(uint, const QString &, const QByteArray &, const QString &)),\n SLOT(onAvatarRetrieved(uint, const QString &, const QByteArray &, const QString &)));\n\n \/* First time we create a contact, avatar should not be in cache, so\n * AvatarRetrieved should be called *\/\n mAvatarRetrievedCalled = false;\n createContactWithFakeAvatar(\"foo\");\n QVERIFY(mAvatarRetrievedCalled);\n\n \/* Second time we create a contact, avatar should be in cache now, so\n * AvatarRetrieved should NOT be called *\/\n mAvatarRetrievedCalled = false;\n createContactWithFakeAvatar(\"bar\");\n QVERIFY(!mAvatarRetrievedCalled);\n\n QVERIFY(SmartDir(tmpDir).removeDirectory());\n}\n\nvoid TestContactsAvatar::expectConnInvalidated()\n{\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::expectPendingContactsFinished(PendingOperation *op)\n{\n if (!op->isFinished()) {\n qWarning() << \"unfinished\";\n mLoop->exit(1);\n return;\n }\n\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mLoop->exit(2);\n return;\n }\n\n if (!op->isValid()) {\n qWarning() << \"inconsistent results\";\n mLoop->exit(3);\n return;\n }\n\n qDebug() << \"finished\";\n PendingContacts *pending = qobject_cast<PendingContacts *>(op);\n mContacts = pending->contacts();\n\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-avatar\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n gchar *name;\n gchar *connPath;\n GError *error = 0;\n\n mConnService = TP_TESTS_CONTACTS_CONNECTION(g_object_new(\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL));\n QVERIFY(mConnService != 0);\n QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),\n \"foo\", &name, &connPath, &error));\n QVERIFY(error == 0);\n\n QVERIFY(name != 0);\n QVERIFY(connPath != 0);\n\n mConnName = QLatin1String(name);\n mConnPath = QLatin1String(connPath);\n\n g_free(name);\n g_free(connPath);\n\n mConn = Connection::create(mConnName, mConnPath,\n ChannelFactory::create(QDBusConnection::sessionBus()),\n ContactFactory::create());\n QCOMPARE(mConn->isReady(), false);\n\n QVERIFY(connect(mConn->lowlevel()->requestConnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mConn->isReady(), true);\n\n QCOMPARE(mConn->status(), ConnectionStatusConnected);\n\n QVERIFY(mConn->contactManager()->supportedFeatures().contains(Contact::FeatureAvatarData));\n}\n\nvoid TestContactsAvatar::init()\n{\n initImpl();\n}\n\nvoid TestContactsAvatar::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsAvatar::cleanupTestCase()\n{\n if (mConn) {\n \/\/ Disconnect and wait for invalidated\n QVERIFY(connect(mConn->lowlevel()->requestDisconnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n\n if (mConn->isValid()) {\n QVERIFY(connect(mConn.data(),\n SIGNAL(invalidated(Tp::DBusProxy *,\n const QString &, const QString &)),\n SLOT(expectConnInvalidated())));\n QCOMPARE(mLoop->exec(), 0);\n }\n }\n\n if (mConnService != 0) {\n g_object_unref(mConnService);\n mConnService = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsAvatar)\n#include \"_gen\/contacts-avatar.cpp.moc.hpp\"\n<commit_msg>Don't leak avatar data array in TestContactsAvatar<commit_after>#define TP_QT4_ENABLE_LOWLEVEL_API\n\n#include <TelepathyQt4\/AvatarData>\n#include <TelepathyQt4\/ChannelFactory>\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ConnectionLowlevel>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactFactory>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingReady>\n\n#include <telepathy-glib\/telepathy-glib.h>\n\n#include <tests\/lib\/glib\/contacts-conn.h>\n#include <tests\/lib\/test.h>\n\nusing namespace Tp;\n\nclass SmartDir : public QDir\n{\npublic:\n SmartDir(const QString &path) : QDir(path) { }\n bool rmdir() { return QDir().rmdir(path()); }\n bool removeDirectory();\n};\n\nbool SmartDir::removeDirectory()\n{\n bool ret = true;\n\n QFileInfoList list = entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);\n Q_FOREACH (QFileInfo info, list) {\n if (info.isDir()) {\n SmartDir subDir(info.filePath());\n if (!subDir.removeDirectory()) {\n ret = false;\n }\n } else {\n qDebug() << \"deleting\" << info.filePath();\n if (!QFile(info.filePath()).remove()) {\n ret = false;\n }\n }\n }\n\n if (ret) {\n qDebug() << \"deleting\" << path();\n ret = rmdir();\n }\n\n return ret;\n}\n\nclass TestContactsAvatar : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsAvatar(QObject *parent = 0)\n : Test(parent), mConnService(0)\n { }\n\nprotected Q_SLOTS:\n void expectConnInvalidated();\n void expectPendingContactsFinished(Tp::PendingOperation *);\n void onAvatarRetrieved(uint, const QString &, const QByteArray &, const QString &);\n void onAvatarDataChanged(const Tp::AvatarData &);\n void createContactWithFakeAvatar(const char *);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testAvatar();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n QString mConnName, mConnPath;\n TpTestsContactsConnection *mConnService;\n ConnectionPtr mConn;\n QList<ContactPtr> mContacts;\n bool mAvatarRetrievedCalled;\n};\n\nvoid TestContactsAvatar::onAvatarRetrieved(uint handle, const QString &token,\n const QByteArray &data, const QString &mimeType)\n{\n Q_UNUSED(handle);\n Q_UNUSED(token);\n Q_UNUSED(data);\n Q_UNUSED(mimeType);\n\n mAvatarRetrievedCalled = true;\n}\n\nvoid TestContactsAvatar::onAvatarDataChanged(const AvatarData &avatar)\n{\n Q_UNUSED(avatar);\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::createContactWithFakeAvatar(const char *id)\n{\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n (TpBaseConnection *) mConnService, TP_HANDLE_TYPE_CONTACT);\n const gchar avatarData[] = \"fake-avatar-data\";\n const gchar avatarToken[] = \"fake-avatar-token\";\n const gchar avatarMimeType[] = \"fake-avatar-mime-type\";\n TpHandle handle;\n GArray *array;\n\n handle = tp_handle_ensure(serviceRepo, id, NULL, NULL);\n array = g_array_new(FALSE, FALSE, sizeof(gchar));\n g_array_append_vals (array, avatarData, strlen(avatarData));\n\n tp_tests_contacts_connection_change_avatar_data(mConnService, handle,\n array, avatarMimeType, avatarToken);\n\n Tp::UIntList handles = Tp::UIntList() << handle;\n Features features = Features()\n << Contact::FeatureAvatarToken\n << Contact::FeatureAvatarData;\n\n PendingContacts *pending = mConn->contactManager()->contactsForHandles(\n handles, features);\n QVERIFY(connect(pending,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mContacts.size(), 1);\n\n if (mContacts[0]->avatarData().fileName.isEmpty()) {\n QVERIFY(connect(mContacts[0].data(),\n SIGNAL(avatarDataChanged(const Tp::AvatarData &)),\n SLOT(onAvatarDataChanged(const Tp::AvatarData &))));\n QCOMPARE(mLoop->exec(), 0);\n }\n\n AvatarData avatar = mContacts[0]->avatarData();\n\n qDebug() << \"Contact created:\";\n qDebug() << \"Avatar token:\" << mContacts[0]->avatarToken();\n qDebug() << \"Avatar file:\" << avatar.fileName;\n qDebug() << \"Avatar MimeType:\" << avatar.mimeType;\n\n QFile file(avatar.fileName);\n file.open(QIODevice::ReadOnly);\n QByteArray data(file.readAll());\n file.close();\n\n QCOMPARE(mContacts[0]->avatarToken(), QString(QLatin1String(avatarToken)));\n QCOMPARE(data, QByteArray(avatarData));\n QCOMPARE(avatar.mimeType, QString(QLatin1String(avatarMimeType)));\n\n g_array_free(array, TRUE);\n}\n\n#define RAND_STR_LEN 6\n\nvoid TestContactsAvatar::testAvatar()\n{\n \/* Make sure our tests does not mess up user's avatar cache *\/\n qsrand(time(0));\n static const char letters[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n static const int DirNameLength = 6;\n QString dirName;\n for (int i = 0; i < DirNameLength; ++i) {\n dirName += QLatin1Char(letters[qrand() % qstrlen(letters)]);\n }\n QString tmpDir = QString(QLatin1String(\"%1\/%2\")).arg(QDir::tempPath()).arg(dirName);\n QByteArray a = tmpDir.toLatin1();\n setenv (\"XDG_CACHE_HOME\", a.constData(), true);\n\n Client::ConnectionInterfaceAvatarsInterface *connAvatarsInterface =\n mConn->optionalInterface<Client::ConnectionInterfaceAvatarsInterface>();\n\n \/* Check if AvatarRetrieved gets called *\/\n connect(connAvatarsInterface,\n SIGNAL(AvatarRetrieved(uint, const QString &, const QByteArray &, const QString &)),\n SLOT(onAvatarRetrieved(uint, const QString &, const QByteArray &, const QString &)));\n\n \/* First time we create a contact, avatar should not be in cache, so\n * AvatarRetrieved should be called *\/\n mAvatarRetrievedCalled = false;\n createContactWithFakeAvatar(\"foo\");\n QVERIFY(mAvatarRetrievedCalled);\n\n \/* Second time we create a contact, avatar should be in cache now, so\n * AvatarRetrieved should NOT be called *\/\n mAvatarRetrievedCalled = false;\n createContactWithFakeAvatar(\"bar\");\n QVERIFY(!mAvatarRetrievedCalled);\n\n QVERIFY(SmartDir(tmpDir).removeDirectory());\n}\n\nvoid TestContactsAvatar::expectConnInvalidated()\n{\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::expectPendingContactsFinished(PendingOperation *op)\n{\n if (!op->isFinished()) {\n qWarning() << \"unfinished\";\n mLoop->exit(1);\n return;\n }\n\n if (op->isError()) {\n qWarning().nospace() << op->errorName()\n << \": \" << op->errorMessage();\n mLoop->exit(2);\n return;\n }\n\n if (!op->isValid()) {\n qWarning() << \"inconsistent results\";\n mLoop->exit(3);\n return;\n }\n\n qDebug() << \"finished\";\n PendingContacts *pending = qobject_cast<PendingContacts *>(op);\n mContacts = pending->contacts();\n\n mLoop->exit(0);\n}\n\nvoid TestContactsAvatar::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-avatar\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n gchar *name;\n gchar *connPath;\n GError *error = 0;\n\n mConnService = TP_TESTS_CONTACTS_CONNECTION(g_object_new(\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL));\n QVERIFY(mConnService != 0);\n QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),\n \"foo\", &name, &connPath, &error));\n QVERIFY(error == 0);\n\n QVERIFY(name != 0);\n QVERIFY(connPath != 0);\n\n mConnName = QLatin1String(name);\n mConnPath = QLatin1String(connPath);\n\n g_free(name);\n g_free(connPath);\n\n mConn = Connection::create(mConnName, mConnPath,\n ChannelFactory::create(QDBusConnection::sessionBus()),\n ContactFactory::create());\n QCOMPARE(mConn->isReady(), false);\n\n QVERIFY(connect(mConn->lowlevel()->requestConnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mConn->isReady(), true);\n\n QCOMPARE(mConn->status(), ConnectionStatusConnected);\n\n QVERIFY(mConn->contactManager()->supportedFeatures().contains(Contact::FeatureAvatarData));\n}\n\nvoid TestContactsAvatar::init()\n{\n initImpl();\n}\n\nvoid TestContactsAvatar::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsAvatar::cleanupTestCase()\n{\n if (mConn) {\n \/\/ Disconnect and wait for invalidated\n QVERIFY(connect(mConn->lowlevel()->requestDisconnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n\n if (mConn->isValid()) {\n QVERIFY(connect(mConn.data(),\n SIGNAL(invalidated(Tp::DBusProxy *,\n const QString &, const QString &)),\n SLOT(expectConnInvalidated())));\n QCOMPARE(mLoop->exec(), 0);\n }\n }\n\n if (mConnService != 0) {\n g_object_unref(mConnService);\n mConnService = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsAvatar)\n#include \"_gen\/contacts-avatar.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 Andrew Sutton\n\/\/ All rights reserved\n\n#ifndef LINGO_NODE_HPP\n#define LINGO_NODE_HPP\n\n#include \"lingo\/utility.hpp\"\n\n#include <cassert>\n#include <vector>\n#include <type_traits>\n\n\/\/ This module provides defines a node abstraction for various\n\/\/ kinds of trees used in different languages and facilities\n\/\/ for working with those abstractions.\n\nnamespace lingo\n{\n\n\ntemplate<typename T>\ninline String \nget_node_name(T const* t)\n{\n return type_str(*t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Special values\n\/\/\n\/\/ The following functions define special values of node pointers.\n\n\n\/\/ Returns true if the node is empty.\ntemplate<typename T>\ninline bool\nis_empty_node(T const* t)\n{\n return t == nullptr;\n}\n\n\n\/\/ Construct a node pointer that acts as an error value.\n\/\/ The type of the node is explicitly given as a template\n\/\/ argument.\ntemplate<typename T>\ninline T* \nmake_error_node()\n{\n return (T*)0x01;\n}\n\n\n\/\/ Returns true if `t` is an error node.\ntemplate<typename T>\ninline bool\nis_error_node(T const* t)\n{\n return t == make_error_node<T>();\n}\n\n\n\/\/ Returns true if `t` is neither null nor an error.\ntemplate<typename T>\ninline bool\nis_valid_node(T const* t)\n{\n return t && !is_error_node(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Dynamic type information\n\n\n\/\/ Returns true if the object pointed to by `u` has \n\/\/ the dynamic type `T`.\ntemplate<typename T, typename U>\ninline bool\nis(U const* u)\n{\n return dynamic_cast<T const*>(u);\n}\n\n\n\/\/ Statically cast a pointer to a Node of type T to a \n\/\/ pointer to a Node of type U. This is not a checked\n\/\/ operation (except in debug mode).\n\/\/\n\/\/ Note that this allows null and error nodes to be\n\/\/ interpreted as nodes of the given type (as their\n\/\/ values are considered common to all).\ntemplate<typename T, typename U>\ninline T* \ncast(U* u)\n{\n lingo_assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\ncast(U const* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T const*>(u);\n}\n\n\n\/\/ Returns `u` with type `T*` iff the object pointed\n\/\/ to by `u` has dynamic type `T`.\ntemplate<typename T, typename U>\ninline T*\nas(U* u)\n{\n return dynamic_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\nas(U const* u)\n{\n return dynamic_cast<T const*>(u);\n}\n\n\n\/\/ Return a non-const pointer to the term. This is used\n\/\/ to modify a term post-initializatoin (which should\n\/\/ be rare).\ntemplate<typename T>\ninline T*\nmodify(T const* t)\n{\n return const_cast<T*>(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Concepts\n\/\/\n\/\/ There are several concepts describing the kinds of nodes over \n\/\/ which an algorithm can operate generically. The primary \n\/\/ characterization \/\/ of node types is based on their arity. \n\/\/\n\/\/ ## The Node concept\n\/\/\n\/\/ Every node in an abstract syntax tree must provide a static\n\/\/ constexpr member, node_kind that statically defines the kind\n\/\/ of node.\n\/\/\n\/\/ ## Node arity\n\/\/\n\/\/ Nodes with fixed arity have tuple-like member names (e.g., \n\/\/ first, second, third). These accessor members correspond to \n\/\/ the sub-terms of each node. Accessor members may have different\n\/\/ tpyes, and are not required to be nodes.\n\/\/\n\/\/ A nullary node is a Node is an empty tuple, and has no\n\/\/ accessor members. A unary node has only accessor member\n\/\/ `first`. A binary node has only `first` and `second`.\n\/\/ A ternary node has `first`, second`, and `third`.\n\/\/\n\/\/ Note that more arity nodes can be defined if needed.\n\/\/\n\/\/ A k-ary has k sub-terms, and that range of terms is accessed \n\/\/ by its `begin()` and `end()` members. The types of these \n\/\/ sub-terms are the same.\n\n\nnamespace traits\n{\n\n\n\/\/ A helper trait used to detect substitution failures.\ntemplate<typename T>\nstruct is_non_void\n{\n static constexpr bool value = true;\n};\n\n\ntemplate<>\nstruct is_non_void<void>\n{\n static constexpr bool value = false;\n};\n\n\n\/\/ Detect the existince of the member t->first.\ntemplate<typename T>\nstruct first_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->first);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->second;\ntemplate<typename T>\nstruct second_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->second);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->third;\ntemplate<typename T>\nstruct third_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->third);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->begin().\ntemplate<typename T>\nstruct begin_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->begin());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\n\/\/ Detect the existence of the member t->end().\ntemplate<typename T>\nstruct end_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->end());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Returns true when `T` has the member `first`.\ntemplate<typename T>\nconstexpr bool\nhas_first()\n{\n return is_non_void<typename first_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `second`.\ntemplate<typename T>\nconstexpr bool\nhas_second()\n{\n return is_non_void<typename second_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `third`.\ntemplate<typename T>\nconstexpr bool\nhas_third()\n{\n return is_non_void<typename third_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `begin`.\ntemplate<typename T>\nconstexpr bool\nhas_begin()\n{\n return is_non_void<typename begin_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `end`.\ntemplate<typename T>\nconstexpr bool\nhas_end()\n{\n return is_non_void<typename end_type<T>::type>::value;\n}\n\n\n} \/\/ namesapce traits\n\n\n\/\/ Returns true if T is a Nullary_node.\ntemplate<typename T>\nconstexpr bool\nis_nullary_node()\n{\n return !traits::has_first<T>();\n}\n\n\n\/\/ Returns true if T is a unary node.\ntemplate<typename T>\nconstexpr bool\nis_unary_node()\n{\n return traits::has_first<T>() \n && !traits::has_second<T>();\n}\n\n\n\/\/ Returns true if T is a binary node.\ntemplate<typename T>\nconstexpr bool\nis_binary_node()\n{\n return traits::has_second<T>() \n && !traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a ternary node.\ntemplate<typename T>\nconstexpr bool\nis_ternary_node()\n{\n return traits::has_first<T>()\n && traits::has_second<T>() \n && traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a k-ary node.\ntemplate<typename T>\nconstexpr bool\nis_kary_node()\n{\n return traits::has_begin<T>() && traits::has_end<T>();\n}\n\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Reqiured term\n\n\/\/ The Maybe template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Required<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is initialized to a non-null, non-error value. \ntemplate<typename T>\nstruct Required\n{\n Required()\n : ptr(nullptr)\n { }\n\n Required(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid.\n explicit operator bool() const { return is_valid_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error or\n \/\/ empty term.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Optional results\n\n\/\/ The Optional template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Optional<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is a non-error value. Note that the term may be empty.\ntemplate<typename T>\nstruct Optional\n{\n Optional()\n : ptr(nullptr)\n { }\n\n Optional(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid or empty.\n explicit operator bool() const { return !is_error_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Nonempty results\n\n\/\/ The Nonempty template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Nonempty<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ is non-empty. Note that error conditions are treated as\n\/\/ valid results. \ntemplate<typename T>\nstruct Nonempty\n{\n Nonempty()\n : ptr(nullptr)\n { }\n\n Nonempty(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is non-empty.\n explicit operator bool() const { return !is_empty_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is a empty.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\n} \/\/ namespace lingo\n\n\n#endif\n<commit_msg>Comments.<commit_after>\/\/ Copyright (c) 2015 Andrew Sutton\n\/\/ All rights reserved\n\n#ifndef LINGO_NODE_HPP\n#define LINGO_NODE_HPP\n\n#include \"lingo\/utility.hpp\"\n\n#include <cassert>\n#include <vector>\n#include <type_traits>\n\n\/\/ This module provides defines a node abstraction for various\n\/\/ kinds of trees used in different languages and facilities\n\/\/ for working with those abstractions.\n\nnamespace lingo\n{\n\n\/\/ Returns the name of the object pointed to\n\/\/ by t.\ntemplate<typename T>\ninline String\nget_node_name(T const* t)\n{\n return type_str(*t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Special values\n\/\/\n\/\/ The following functions define special values of node pointers.\n\n\n\/\/ Returns true if the node is empty.\ntemplate<typename T>\ninline bool\nis_empty_node(T const* t)\n{\n return t == nullptr;\n}\n\n\n\/\/ Construct a node pointer that acts as an error value.\n\/\/ The type of the node is explicitly given as a template\n\/\/ argument.\ntemplate<typename T>\ninline T*\nmake_error_node()\n{\n return (T*)0x01;\n}\n\n\n\/\/ Returns true if `t` is an error node.\ntemplate<typename T>\ninline bool\nis_error_node(T const* t)\n{\n return t == make_error_node<T>();\n}\n\n\n\/\/ Returns true if `t` is neither null nor an error.\ntemplate<typename T>\ninline bool\nis_valid_node(T const* t)\n{\n return t && !is_error_node(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Dynamic type information\n\n\n\/\/ Returns true if the object pointed to by `u` has\n\/\/ the dynamic type `T`.\ntemplate<typename T, typename U>\ninline bool\nis(U const* u)\n{\n return dynamic_cast<T const*>(u);\n}\n\n\n\/\/ Statically cast a pointer to a Node of type T to a\n\/\/ pointer to a Node of type U. This is not a checked\n\/\/ operation (except in debug mode).\n\/\/\n\/\/ Note that this allows null and error nodes to be\n\/\/ interpreted as nodes of the given type (as their\n\/\/ values are considered common to all).\ntemplate<typename T, typename U>\ninline T*\ncast(U* u)\n{\n lingo_assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\ncast(U const* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T const*>(u);\n}\n\n\n\/\/ Returns `u` with type `T*` iff the object pointed\n\/\/ to by `u` has dynamic type `T`.\ntemplate<typename T, typename U>\ninline T*\nas(U* u)\n{\n return dynamic_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\nas(U const* u)\n{\n return dynamic_cast<T const*>(u);\n}\n\n\n\/\/ Return a non-const pointer to the term. This is used\n\/\/ to modify a term post-initializatoin (which should\n\/\/ be rare).\ntemplate<typename T>\ninline T*\nmodify(T const* t)\n{\n return const_cast<T*>(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Concepts\n\/\/\n\/\/ There are several concepts describing the kinds of nodes over\n\/\/ which an algorithm can operate generically. The primary\n\/\/ characterization of node types is based on their arity.\n\/\/\n\/\/ ## The Node concept\n\/\/\n\/\/ Every node in an abstract syntax tree must provide a static\n\/\/ constexpr member, node_kind that statically defines the kind\n\/\/ of node.\n\/\/\n\/\/ ## Node arity\n\/\/\n\/\/ Nodes with fixed arity have tuple-like member names (e.g.,\n\/\/ first, second, third). These accessor members correspond to\n\/\/ the sub-terms of each node. Accessor members may have different\n\/\/ tpyes, and are not required to be nodes.\n\/\/\n\/\/ A nullary node is a Node is an empty tuple, and has no\n\/\/ accessor members. A unary node has only accessor member\n\/\/ `first`. A binary node has only `first` and `second`.\n\/\/ A ternary node has `first`, second`, and `third`.\n\/\/\n\/\/ Note that more arity nodes can be defined if needed.\n\/\/\n\/\/ A k-ary has k sub-terms, and that range of terms is accessed\n\/\/ by its `begin()` and `end()` members. The types of these\n\/\/ sub-terms are the same.\n\n\nnamespace traits\n{\n\n\n\/\/ A helper trait used to detect substitution failures.\ntemplate<typename T>\nstruct is_non_void\n{\n static constexpr bool value = true;\n};\n\n\ntemplate<>\nstruct is_non_void<void>\n{\n static constexpr bool value = false;\n};\n\n\n\/\/ Detect the existince of the member t->first.\ntemplate<typename T>\nstruct first_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->first);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->second;\ntemplate<typename T>\nstruct second_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->second);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->third;\ntemplate<typename T>\nstruct third_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->third);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->begin().\ntemplate<typename T>\nstruct begin_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->begin());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\n\/\/ Detect the existence of the member t->end().\ntemplate<typename T>\nstruct end_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->end());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Returns true when `T` has the member `first`.\ntemplate<typename T>\nconstexpr bool\nhas_first()\n{\n return is_non_void<typename first_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `second`.\ntemplate<typename T>\nconstexpr bool\nhas_second()\n{\n return is_non_void<typename second_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `third`.\ntemplate<typename T>\nconstexpr bool\nhas_third()\n{\n return is_non_void<typename third_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `begin`.\ntemplate<typename T>\nconstexpr bool\nhas_begin()\n{\n return is_non_void<typename begin_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `end`.\ntemplate<typename T>\nconstexpr bool\nhas_end()\n{\n return is_non_void<typename end_type<T>::type>::value;\n}\n\n\n} \/\/ namesapce traits\n\n\n\/\/ Returns true if T is a Nullary_node.\ntemplate<typename T>\nconstexpr bool\nis_nullary_node()\n{\n return !traits::has_first<T>();\n}\n\n\n\/\/ Returns true if T is a unary node.\ntemplate<typename T>\nconstexpr bool\nis_unary_node()\n{\n return traits::has_first<T>()\n && !traits::has_second<T>();\n}\n\n\n\/\/ Returns true if T is a binary node.\ntemplate<typename T>\nconstexpr bool\nis_binary_node()\n{\n return traits::has_second<T>()\n && !traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a ternary node.\ntemplate<typename T>\nconstexpr bool\nis_ternary_node()\n{\n return traits::has_first<T>()\n && traits::has_second<T>()\n && traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a k-ary node.\ntemplate<typename T>\nconstexpr bool\nis_kary_node()\n{\n return traits::has_begin<T>() && traits::has_end<T>();\n}\n\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Reqiured term\n\n\/\/ The Maybe template is typically used to declare node\n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Required<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is initialized to a non-null, non-error value.\ntemplate<typename T>\nstruct Required\n{\n Required()\n : ptr(nullptr)\n { }\n\n Required(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid.\n explicit operator bool() const { return is_valid_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error or\n \/\/ empty term.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Optional results\n\n\/\/ The Optional template is typically used to declare node\n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Optional<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is a non-error value. Note that the term may be empty.\ntemplate<typename T>\nstruct Optional\n{\n Optional()\n : ptr(nullptr)\n { }\n\n Optional(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid or empty.\n explicit operator bool() const { return !is_error_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Nonempty results\n\n\/\/ The Nonempty template is typically used to declare node\n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Nonempty<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ is non-empty. Note that error conditions are treated as\n\/\/ valid results.\ntemplate<typename T>\nstruct Nonempty\n{\n Nonempty()\n : ptr(nullptr)\n { }\n\n Nonempty(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is non-empty.\n explicit operator bool() const { return !is_empty_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is a empty.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\n} \/\/ namespace lingo\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"scene.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/environmentedf\/environmentedf.h\"\n#include \"renderer\/modeling\/environmentshader\/environmentshader.h\"\n#include \"renderer\/modeling\/object\/object.h\"\n#include \"renderer\/modeling\/scene\/assembly.h\"\n#include \"renderer\/modeling\/scene\/assemblyinstance.h\"\n#include \"renderer\/modeling\/scene\/objectinstance.h\"\n#include \"renderer\/modeling\/scene\/textureinstance.h\"\n#include \"renderer\/modeling\/scene\/visibilityflags.h\"\n#include \"renderer\/modeling\/surfaceshader\/physicalsurfaceshader.h\"\n#include \"renderer\/modeling\/surfaceshader\/surfaceshader.h\"\n#include \"renderer\/utility\/bbox.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/job\/abortswitch.h\"\n#include \"foundation\/utility\/foreach.h\"\n\n\/\/ Standard headers.\n#include <set>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ Scene class implementation.\n\/\/\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nUniqueID Scene::get_class_uid()\n{\n return g_class_uid;\n}\n\nstruct Scene::Impl\n{\n UniqueID m_uid;\n auto_release_ptr<Camera> m_camera;\n auto_release_ptr<Environment> m_environment;\n EnvironmentEDFContainer m_environment_edfs;\n EnvironmentShaderContainer m_environment_shaders;\n auto_release_ptr<SurfaceShader> m_default_surface_shader;\n\n explicit Impl(Entity* parent)\n : m_environment_edfs(parent)\n , m_environment_shaders(parent)\n , m_default_surface_shader(\n PhysicalSurfaceShaderFactory().create(\n \"default_surface_shader\",\n ParamArray()))\n {\n }\n};\n\nScene::Scene()\n : Entity(g_class_uid)\n , BaseGroup(this)\n , impl(new Impl(this))\n , m_has_render_data(false)\n{\n set_name(\"scene\");\n}\n\nScene::~Scene()\n{\n delete impl;\n}\n\nvoid Scene::release()\n{\n delete this;\n}\n\nvoid Scene::set_camera(auto_release_ptr<Camera> camera)\n{\n impl->m_camera = camera;\n\n if (impl->m_camera.get())\n impl->m_camera->set_parent(this);\n}\n\nCamera* Scene::get_camera() const\n{\n return impl->m_camera.get();\n}\n\nvoid Scene::set_environment(auto_release_ptr<Environment> environment)\n{\n impl->m_environment = environment;\n\n if (impl->m_environment.get())\n impl->m_environment->set_parent(this);\n}\n\nEnvironment* Scene::get_environment() const\n{\n return impl->m_environment.get();\n}\n\nEnvironmentEDFContainer& Scene::environment_edfs() const\n{\n return impl->m_environment_edfs;\n}\n\nEnvironmentShaderContainer& Scene::environment_shaders() const\n{\n return impl->m_environment_shaders;\n}\n\nSurfaceShader* Scene::get_default_surface_shader() const\n{\n return impl->m_default_surface_shader.get();\n}\n\nGAABB3 Scene::compute_bbox() const\n{\n const AssemblyInstanceContainer& instances = assembly_instances();\n return compute_parent_bbox<GAABB3>(instances.begin(), instances.end());\n}\n\nnamespace\n{\n bool assembly_instances_use_alpha_mapping(\n const AssemblyInstanceContainer& assembly_instances,\n set<UniqueID>& visited_assemblies)\n {\n \/\/ Regarding transparency in the Tracer,\n \/\/ we only care about camera and shadow rays.\n const uint32 visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay;\n\n for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i)\n {\n \/\/ Retrieve the assembly instance.\n const AssemblyInstance& assembly_instance = *i;\n\n \/\/ Skip invisible assembly instances.\n if ((assembly_instance.get_vis_flags() & visibility_mask) == 0)\n continue;\n\n \/\/ Retrieve the assembly.\n const Assembly& assembly = assembly_instance.get_assembly();\n\n if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end())\n {\n visited_assemblies.insert(assembly.get_uid());\n\n \/\/ Check the assembly contents.\n for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i)\n {\n \/\/ Skip invisible object instances.\n if ((i->get_vis_flags() & visibility_mask) == 0)\n continue;\n\n if (i->uses_alpha_mapping())\n return true;\n }\n\n \/\/ Recurse into child assembly instances.\n if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies))\n return true;\n }\n }\n\n return false;\n }\n}\n\nbool Scene::uses_alpha_mapping() const\n{\n set<UniqueID> visited_assemblies;\n return assembly_instances_use_alpha_mapping(assembly_instances(), visited_assemblies);\n}\n\nnamespace\n{\n template <typename EntityCollection>\n bool invoke_on_frame_begin(\n const Project& project,\n EntityCollection& entities,\n IAbortSwitch* abort_switch)\n {\n bool success = true;\n\n for (each<EntityCollection> i = entities; i; ++i)\n {\n if (is_aborted(abort_switch))\n break;\n\n success = success && i->on_frame_begin(project, abort_switch);\n }\n\n return success;\n }\n\n template <typename EntityCollection>\n void invoke_on_frame_end(\n const Project& project,\n EntityCollection& entities)\n {\n for (each<EntityCollection> i = entities; i; ++i)\n i->on_frame_end(project);\n }\n}\n\nbool Scene::on_frame_begin(\n const Project& project,\n IAbortSwitch* abort_switch)\n{\n create_render_data();\n\n bool success = true;\n\n if (impl->m_camera.get())\n success = success && impl->m_camera->on_frame_begin(project, abort_switch);\n\n success = success && invoke_on_frame_begin(project, texture_instances(), abort_switch);\n success = success && invoke_on_frame_begin(project, environment_edfs(), abort_switch);\n success = success && invoke_on_frame_begin(project, environment_shaders(), abort_switch);\n\n if (is_aborted(abort_switch))\n return success;\n\n if (impl->m_environment.get())\n success = success && impl->m_environment->on_frame_begin(project, abort_switch);\n\n success = success && invoke_on_frame_begin(project, assemblies(), abort_switch);\n success = success && invoke_on_frame_begin(project, assembly_instances(), abort_switch);\n\n return success;\n}\n\nvoid Scene::on_frame_end(const Project& project)\n{\n invoke_on_frame_end(project, assembly_instances());\n invoke_on_frame_end(project, assemblies());\n\n if (impl->m_environment.get())\n impl->m_environment->on_frame_end(project);\n\n invoke_on_frame_end(project, environment_shaders());\n invoke_on_frame_end(project, environment_edfs());\n invoke_on_frame_end(project, texture_instances());\n\n if (impl->m_camera.get())\n impl->m_camera->on_frame_end(project);\n\n m_has_render_data = false;\n}\n\nvoid Scene::create_render_data()\n{\n assert(!m_has_render_data);\n\n m_render_data.m_bbox = compute_bbox();\n\n if (m_render_data.m_bbox.is_valid())\n {\n m_render_data.m_center = m_render_data.m_bbox.center();\n m_render_data.m_radius = m_render_data.m_bbox.radius();\n m_render_data.m_diameter = m_render_data.m_bbox.diameter();\n m_render_data.m_safe_diameter = m_render_data.m_diameter * GScalar(1.01);\n }\n else\n {\n m_render_data.m_center = GVector3(0.0);\n m_render_data.m_radius = GScalar(0.0);\n m_render_data.m_diameter = GScalar(0.0);\n m_render_data.m_safe_diameter = GScalar(0.0);\n }\n\n m_has_render_data = true;\n}\n\n\n\/\/\n\/\/ SceneFactory class implementation.\n\/\/\n\nauto_release_ptr<Scene> SceneFactory::create()\n{\n return auto_release_ptr<Scene>(new Scene());\n}\n\n} \/\/ namespace renderer\n<commit_msg>Tweak code<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"scene.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/environmentedf\/environmentedf.h\"\n#include \"renderer\/modeling\/environmentshader\/environmentshader.h\"\n#include \"renderer\/modeling\/object\/object.h\"\n#include \"renderer\/modeling\/scene\/assembly.h\"\n#include \"renderer\/modeling\/scene\/assemblyinstance.h\"\n#include \"renderer\/modeling\/scene\/objectinstance.h\"\n#include \"renderer\/modeling\/scene\/textureinstance.h\"\n#include \"renderer\/modeling\/scene\/visibilityflags.h\"\n#include \"renderer\/modeling\/surfaceshader\/physicalsurfaceshader.h\"\n#include \"renderer\/modeling\/surfaceshader\/surfaceshader.h\"\n#include \"renderer\/utility\/bbox.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/job\/abortswitch.h\"\n#include \"foundation\/utility\/foreach.h\"\n\n\/\/ Standard headers.\n#include <set>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ Scene class implementation.\n\/\/\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nUniqueID Scene::get_class_uid()\n{\n return g_class_uid;\n}\n\nstruct Scene::Impl\n{\n UniqueID m_uid;\n auto_release_ptr<Camera> m_camera;\n auto_release_ptr<Environment> m_environment;\n EnvironmentEDFContainer m_environment_edfs;\n EnvironmentShaderContainer m_environment_shaders;\n auto_release_ptr<SurfaceShader> m_default_surface_shader;\n\n explicit Impl(Entity* parent)\n : m_environment_edfs(parent)\n , m_environment_shaders(parent)\n , m_default_surface_shader(\n PhysicalSurfaceShaderFactory().create(\n \"default_surface_shader\",\n ParamArray()))\n {\n }\n};\n\nScene::Scene()\n : Entity(g_class_uid)\n , BaseGroup(this)\n , impl(new Impl(this))\n , m_has_render_data(false)\n{\n set_name(\"scene\");\n}\n\nScene::~Scene()\n{\n delete impl;\n}\n\nvoid Scene::release()\n{\n delete this;\n}\n\nvoid Scene::set_camera(auto_release_ptr<Camera> camera)\n{\n impl->m_camera = camera;\n\n if (impl->m_camera.get())\n impl->m_camera->set_parent(this);\n}\n\nCamera* Scene::get_camera() const\n{\n return impl->m_camera.get();\n}\n\nvoid Scene::set_environment(auto_release_ptr<Environment> environment)\n{\n impl->m_environment = environment;\n\n if (impl->m_environment.get())\n impl->m_environment->set_parent(this);\n}\n\nEnvironment* Scene::get_environment() const\n{\n return impl->m_environment.get();\n}\n\nEnvironmentEDFContainer& Scene::environment_edfs() const\n{\n return impl->m_environment_edfs;\n}\n\nEnvironmentShaderContainer& Scene::environment_shaders() const\n{\n return impl->m_environment_shaders;\n}\n\nSurfaceShader* Scene::get_default_surface_shader() const\n{\n return impl->m_default_surface_shader.get();\n}\n\nGAABB3 Scene::compute_bbox() const\n{\n const AssemblyInstanceContainer& instances = assembly_instances();\n return compute_parent_bbox<GAABB3>(instances.begin(), instances.end());\n}\n\nnamespace\n{\n bool assembly_instances_use_alpha_mapping(\n const AssemblyInstanceContainer& assembly_instances,\n set<UniqueID>& visited_assemblies)\n {\n \/\/ Regarding transparency in the Tracer,\n \/\/ we only care about camera and shadow rays.\n const uint32 visibility_mask = VisibilityFlags::CameraRay | VisibilityFlags::ShadowRay;\n\n for (const_each<AssemblyInstanceContainer> i = assembly_instances; i; ++i)\n {\n \/\/ Retrieve the assembly instance.\n const AssemblyInstance& assembly_instance = *i;\n\n \/\/ Skip invisible assembly instances.\n if ((assembly_instance.get_vis_flags() & visibility_mask) == 0)\n continue;\n\n \/\/ Retrieve the assembly.\n const Assembly& assembly = assembly_instance.get_assembly();\n\n if (visited_assemblies.find(assembly.get_uid()) == visited_assemblies.end())\n {\n visited_assemblies.insert(assembly.get_uid());\n\n \/\/ Check the assembly contents.\n for (const_each<ObjectInstanceContainer> i = assembly.object_instances(); i; ++i)\n {\n \/\/ Skip invisible object instances.\n if ((i->get_vis_flags() & visibility_mask) == 0)\n continue;\n\n if (i->uses_alpha_mapping())\n return true;\n }\n\n \/\/ Recurse into child assembly instances.\n if (assembly_instances_use_alpha_mapping(assembly.assembly_instances(), visited_assemblies))\n return true;\n }\n }\n\n return false;\n }\n}\n\nbool Scene::uses_alpha_mapping() const\n{\n set<UniqueID> visited_assemblies;\n return assembly_instances_use_alpha_mapping(assembly_instances(), visited_assemblies);\n}\n\nnamespace\n{\n template <typename EntityCollection>\n bool invoke_on_frame_begin(\n const Project& project,\n EntityCollection& entities,\n IAbortSwitch* abort_switch)\n {\n bool success = true;\n\n for (each<EntityCollection> i = entities; i; ++i)\n {\n if (is_aborted(abort_switch))\n break;\n\n success = success && i->on_frame_begin(project, abort_switch);\n }\n\n return success;\n }\n\n template <typename EntityCollection>\n void invoke_on_frame_end(\n const Project& project,\n EntityCollection& entities)\n {\n for (each<EntityCollection> i = entities; i; ++i)\n i->on_frame_end(project);\n }\n}\n\nbool Scene::on_frame_begin(\n const Project& project,\n IAbortSwitch* abort_switch)\n{\n create_render_data();\n\n bool success = true;\n\n if (impl->m_camera.get())\n success = success && impl->m_camera->on_frame_begin(project, abort_switch);\n\n success = success && invoke_on_frame_begin(project, texture_instances(), abort_switch);\n success = success && invoke_on_frame_begin(project, environment_edfs(), abort_switch);\n success = success && invoke_on_frame_begin(project, environment_shaders(), abort_switch);\n\n if (!is_aborted(abort_switch) && impl->m_environment.get())\n success = success && impl->m_environment->on_frame_begin(project, abort_switch);\n\n success = success && invoke_on_frame_begin(project, assemblies(), abort_switch);\n success = success && invoke_on_frame_begin(project, assembly_instances(), abort_switch);\n\n return success;\n}\n\nvoid Scene::on_frame_end(const Project& project)\n{\n invoke_on_frame_end(project, assembly_instances());\n invoke_on_frame_end(project, assemblies());\n\n if (impl->m_environment.get())\n impl->m_environment->on_frame_end(project);\n\n invoke_on_frame_end(project, environment_shaders());\n invoke_on_frame_end(project, environment_edfs());\n invoke_on_frame_end(project, texture_instances());\n\n if (impl->m_camera.get())\n impl->m_camera->on_frame_end(project);\n\n m_has_render_data = false;\n}\n\nvoid Scene::create_render_data()\n{\n assert(!m_has_render_data);\n\n m_render_data.m_bbox = compute_bbox();\n\n if (m_render_data.m_bbox.is_valid())\n {\n m_render_data.m_center = m_render_data.m_bbox.center();\n m_render_data.m_radius = m_render_data.m_bbox.radius();\n m_render_data.m_diameter = m_render_data.m_bbox.diameter();\n m_render_data.m_safe_diameter = m_render_data.m_diameter * GScalar(1.01);\n }\n else\n {\n m_render_data.m_center = GVector3(0.0);\n m_render_data.m_radius = GScalar(0.0);\n m_render_data.m_diameter = GScalar(0.0);\n m_render_data.m_safe_diameter = GScalar(0.0);\n }\n\n m_has_render_data = true;\n}\n\n\n\/\/\n\/\/ SceneFactory class implementation.\n\/\/\n\nauto_release_ptr<Scene> SceneFactory::create()\n{\n return auto_release_ptr<Scene>(new Scene());\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <stdio.h>\r\n#include <limits.h>\r\n#include <cstring>\r\n\r\n#define MAX_ARR_SIZE 100000\r\n\r\nint arrLength;\r\n\/\/ Array containing the input data\r\nint arr[MAX_ARR_SIZE];\r\n\/\/ Array containing max\r\nint resultArr[MAX_ARR_SIZE];\r\nint resultLink[MAX_ARR_SIZE];\r\n\r\nint findLongestSequence()\r\n{\r\n int globalMaxIndex = 0;\r\n for(int i=0; i<arrLength; ++i)\r\n {\r\n for(int j=0; j<i; ++j)\r\n {\r\n \/\/std::cout << \"arr[\"<<j<<\"]=\"<<arr[j]<<\" < arr[\"<<i<<\"]=\"<<arr[i]<<\" && currentMax=\"<<currentMax<<\" < resultArr[\"<<j<<\"]=\"<<resultArr[j]<<\" \";\r\n if(arr[j] < arr[i] && resultArr[i] <= resultArr[j])\r\n {\r\n \/\/std::cout << \"best\";\r\n resultArr[i] = resultArr[j] + 1;\r\n resultLink[i] = j;\r\n }\r\n \/\/std::cout << std::endl;\r\n }\r\n if(resultArr[globalMaxIndex] < resultArr[i])\r\n globalMaxIndex = i;\r\n }\r\n\r\n \/*std::cout << \"resultArr: \";\r\n for(int i=0; i< arrLength; ++i)\r\n std::cout << resultArr[i] << \" \";\r\n std::cout << std::endl << \"resultLink: \";\r\n for(int i=0; i< arrLength; ++i)\r\n std::cout << resultLink[i] << \" \";\r\n std::cout << std::endl << \"index: \" << globalMaxIndex << std::endl;*\/\r\n return globalMaxIndex;\r\n}\r\n\r\n\r\nint main()\r\n{ \r\n arr[0] = INT_MIN;\r\n while( std::cin >> arrLength )\r\n {\r\n for(int i=0; i<arrLength; ++i)\r\n {\r\n scanf(\"%d\", &arr[i]);\r\n resultArr[i] = 1;\r\n resultLink[i] = -1;\r\n }\r\n \r\n \r\n int linkIndex = findLongestSequence();\r\n \r\n std::cout << resultArr[linkIndex] << std::endl;\r\n while(linkIndex >= 0)\r\n {\r\n std::cout << linkIndex << \" \";\r\n linkIndex = resultLink[linkIndex];\r\n }\r\n std::cout << std::endl;\r\n } \r\n}<commit_msg>Imprived LIS but still to slow<commit_after>#include <iostream>\r\n#include <stdio.h>\r\n#include <limits.h>\r\n#include <cstring>\r\n\r\n#define MAX_ARR_SIZE 100000\r\n\r\nint arrLength;\r\n\/\/ Array containing the input data\r\nint arr[MAX_ARR_SIZE];\r\n\/\/ Array containing max\r\nint resultArr[MAX_ARR_SIZE];\r\nint resultLink[MAX_ARR_SIZE];\r\n\r\nint findLongestSequence()\r\n{\r\n int globalMaxIndex = 0;\r\n for(int i=arrLength-1; i>=0; --i)\r\n {\r\n for(int j=i+1; j<arrLength; ++j)\r\n {\r\n if(arr[j] > arr[i] && resultArr[i] <= resultArr[j])\r\n {\r\n resultArr[i] = resultArr[j] + 1;\r\n resultLink[i] = j;\r\n }\r\n }\r\n if(resultArr[globalMaxIndex] < resultArr[i])\r\n globalMaxIndex = i;\r\n }\r\n\r\n return globalMaxIndex;\r\n}\r\n\r\n\r\nint main()\r\n{ \r\n arr[0] = INT_MIN;\r\n while( std::cin >> arrLength )\r\n {\r\n for(int i=0; i<arrLength; ++i)\r\n {\r\n scanf(\"%d\", &arr[i]);\r\n resultArr[i] = 1;\r\n resultLink[i] = -1;\r\n }\r\n \r\n \r\n int linkIndex = findLongestSequence();\r\n \r\n std::cout << resultArr[linkIndex] << std::endl;\r\n while(linkIndex >= 0)\r\n {\r\n std::cout << linkIndex << \" \";\r\n linkIndex = resultLink[linkIndex];\r\n }\r\n std::cout << std::endl;\r\n } \r\n}<|endoftext|>"} {"text":"<commit_before>#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"geometry_msgs\/Wrench.h\"\n#include \"uranus_dp\/State.h\"\n\nclass Controller\n{\npublic:\n Controller()\n {\n outputPub = n.advertise<geometry_msgs::Wrench>(\"outputTopic\", 1);\n\n \/\/ I don't know why, but 'this' is necessary here\n stateSub = n.subscribe(\"stateTopic\", 1, &Controller::stateCallback, this);\n setpointSub = n.subscribe(\"setpointTopic\", 1, &Controller::setpointCallback, this);\n }\n\n \/\/ stateCallback updates the private state variables when a new state message arrives.\n void stateCallback(const uranus_dp::State &state_msg)\n {\n \/\/ Copy pose values (position and orientation)\n eta[0] = state_msg.pose.position.x;\n eta[1] = state_msg.pose.position.y;\n eta[2] = state_msg.pose.position.z;\n eta[3] = state_msg.pose.orientation.x;\n eta[4] = state_msg.pose.orientation.y;\n eta[5] = state_msg.pose.orientation.z;\n eta[6] = state_msg.pose.orientation.w;\n\n \/\/ Copy twist values (linear and angular velocity)\n nu[0] = state_msg.twist.linear.x;\n nu[1] = state_msg.twist.linear.y;\n nu[2] = state_msg.twist.linear.z;\n nu[3] = state_msg.twist.angular.x;\n nu[4] = state_msg.twist.angular.y;\n nu[5] = state_msg.twist.angular.z;\n }\n\n \/\/ setpointCallback updates the private setpoint variable when a new setpoint message arrives.\n void setpointCallback(const geometry_msgs::Twist &setpoint_msg)\n {\n \/\/ Copy velocity setpoint values\n nu_sp[0] = setpoint_msg.linear.x;\n nu_sp[1] = setpoint_msg.linear.y;\n nu_sp[2] = setpoint_msg.linear.z;\n nu_sp[3] = setpoint_msg.angular.x;\n nu_sp[4] = setpoint_msg.angular.y;\n nu_sp[5] = setpoint_msg.angular.z;\n }\n\n \/\/ calculate contains the control algorithm, and calculates the control output based on the\n \/\/ current state and setpoint.\n void calculate(void)\n {\n \/\/ Only velocity control for now.\n\n \/\/ geometry_msgs::Twist velocityError = setpoint - state.velocity;\n\n geometry_msgs::Wrench output;\n output.force.x = 0;\n output.force.y = 0;\n output.force.z = 0;\n output.torque.x = 0;\n output.torque.y = 0;\n output.torque.z = 0;\n\n outputPub.publish(output);\n }\nprivate:\n ros::NodeHandle n;\n\n ros::Publisher outputPub;\n ros::Subscriber stateSub;\n ros::Subscriber setpointSub;\n\n \/\/ State as pose eta = [p q], and twist nu = [v omega]\n double eta [7];\n double nu [6];\n\n \/\/ Velocity setpoints nu_sp = [v_sp omega_sp]\n double nu_sp [6];\n}; \/\/ End of class Controller\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"controller\");\n\n Controller controllerObject;\n\n \/\/ Run the controller at 10 Hz\n ros::Rate loop_rate(10);\n while (ros::ok())\n {\n ros::spinOnce();\n\n controllerObject.calculate();\n\n loop_rate.sleep();\n }\n\n return 0;\n}\n<commit_msg>Added more necessary variables and some math<commit_after>#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"geometry_msgs\/Wrench.h\"\n#include \"uranus_dp\/State.h\"\n#include <Eigen\/Dense>\n#include <cmath>\n\nclass Controller\n{\npublic:\n Controller()\n {\n outputPub = n.advertise<geometry_msgs::Wrench>(\"outputTopic\", 1);\n\n \/\/ I don't know why, but 'this' is necessary here\n stateSub = n.subscribe(\"stateTopic\", 1, &Controller::stateCallback, this);\n setpointSub = n.subscribe(\"setpointTopic\", 1, &Controller::setpointCallback, this);\n\n \/\/ Allocate dynamic member variables\n T = Eigen::MatrixXd(4,3);\n tau = Eigen::VectorXd(3);\n\n \/\/ Initialize controller gains\n K_p = Eigen::Matrix3d::Identity();\n K_d = Eigen::Matrix3d::Identity();\n }\n\n \/\/ stateCallback updates the private state variables when a new state message arrives.\n void stateCallback(const uranus_dp::State &state_msg)\n {\n \/\/ Copy position values\n p[0] = state_msg.pose.position.x;\n p[1] = state_msg.pose.position.y;\n p[2] = state_msg.pose.position.z;\n\n \/\/ Copy orientation values (quaternion)\n q.w() = state_msg.pose.orientation.x;\n q.x() = state_msg.pose.orientation.y;\n q.y() = state_msg.pose.orientation.z;\n q.z() = state_msg.pose.orientation.w;\n\n \/\/ Copy linear velocity values\n v[0] = state_msg.twist.linear.x;\n v[1] = state_msg.twist.linear.y;\n v[2] = state_msg.twist.linear.z;\n\n \/\/ Copy angular velocity values\n omega[0] = state_msg.twist.angular.x;\n omega[1] = state_msg.twist.angular.y;\n omega[2] = state_msg.twist.angular.z;\n }\n\n \/\/ setpointCallback updates the private setpoint variable when a new setpoint message arrives.\n void setpointCallback(const geometry_msgs::Twist &setpoint_msg)\n {\n \/\/ Copy linear velocity setpoint values\n v_sp[0] = setpoint_msg.linear.x;\n v_sp[1] = setpoint_msg.linear.y;\n v_sp[2] = setpoint_msg.linear.z;\n\n \/\/ Copy angular velocity setpoint values\n omega_sp[0] = setpoint_msg.angular.x;\n omega_sp[1] = setpoint_msg.angular.y;\n omega_sp[2] = setpoint_msg.angular.z;\n }\n\n \/\/ calculate contains the control algorithm, and calculates the control output based on the\n \/\/ current state and setpoint.\n void calculate(void)\n {\n \/\/ Only orientation control for now.\n\n \/\/ Orientation error\n \/\/ q_err.x() = q_sp.x() - q.x();\n\n updateTransformationMatrices();\n\n \/\/ Control output\n \/\/ tau = - K_d * omega - K_p * T.transpose() * q_err;\n \/\/ tau = K_p * T.transpose() * q_err;\n \/\/ Eigen::Vector3d temp = T.transpose() * q_err;\n\n \/\/ Build output message\n geometry_msgs::Wrench output;\n output.force.x = 0;\n output.force.y = 0;\n output.force.z = 0;\n output.torque.x = tau(0);\n output.torque.y = tau(1);\n output.torque.z = tau(2);\n outputPub.publish(output);\n }\n\n void updateTransformationMatrices(void)\n {\n \/\/ Linear velocity transformation matrix\n R(0,0) = 1 - 2*(pow(q.y(),2) + pow(q.z(),2));\n R(0,1) = 2*(q.x()*q.y() - q.z()*q.w());\n R(0,2) = 2*(q.x()*q.z() - q.y()*q.w());\n \n R(1,0) = 2*(q.x()*q.y() + q.z()*q.w());\n R(1,1) = 1 - 2*(pow(q.x(),2) + pow(q.w(),2));\n R(1,2) = 2*(q.y()*q.z() + q.x()*q.w());\n \n R(2,0) = 2*(q.x()*q.z() + q.y()*q.w());\n R(2,1) = 2*(q.y()*q.z() + q.x()*q.w());\n R(2,2) = 1 - 2*(pow(q.x(),2) + pow(q.y(),2));\n\n \/\/ Angular velocity transformation matrix\n T(0,0) = -q.x();\n T(0,1) = -q.y();\n T(0,2) = -q.z();\n\n T(1,0) = q.w();\n T(1,1) = -q.z();\n T(1,2) = q.y();\n\n T(2,0) = q.z();\n T(2,1) = q.z();\n T(2,2) = -q.x();\n\n T(3,0) = -q.y();\n T(3,1) = q.x();\n T(3,2) = q.w();\n\n T *= 0.5;\n } \nprivate:\n ros::NodeHandle n;\n\n ros::Publisher outputPub;\n ros::Subscriber stateSub;\n ros::Subscriber setpointSub;\n\n \/\/ State\n Eigen::Vector3d p; \/\/ Position\n Eigen::Quaterniond q; \/\/ Orientation\n Eigen::Vector3d v; \/\/ Linear velocity\n Eigen::Vector3d omega; \/\/ Angular velocity\n\n \/\/ Setpoints\n Eigen::Vector3d p_sp; \/\/ Position\n Eigen::Quaterniond q_sp; \/\/ Orientation\n Eigen::Vector3d v_sp; \/\/ Linear velocity\n Eigen::Vector3d omega_sp; \/\/ Angular velocity\n\n \/\/ Errors\n Eigen::Vector3d p_err; \/\/ Position\n Eigen::Quaterniond q_err; \/\/ Orientation\n Eigen::Vector3d v_err; \/\/ Linear velocity\n Eigen::Vector3d omega_err; \/\/ Angular velocity\n\n \/\/ Transformation matrices\n Eigen::Matrix3d R;\n Eigen::MatrixXd T;\n\n \/\/ Control output\n Eigen::VectorXd tau;\n\n \/\/ Controller gains\n Eigen::Matrix3d K_d;\n Eigen::Matrix3d K_p;\n}; \/\/ End of class Controller\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"controller\");\n\n Controller controllerObject;\n\n \/\/ Run the controller at 10 Hz\n ros::Rate loop_rate(10);\n while (ros::ok())\n {\n ros::spinOnce();\n\n controllerObject.calculate();\n\n loop_rate.sleep();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Python.h>\n#include <string>\n#include <iostream>\n#include <TTree.h>\n#include <TFile.h>\n#include <TChain.h>\n#include <TLeaf.h>\n#include <map>\n#include <numpy\/arrayobject.h>\n#include <cassert>\n#include <set>\nstruct TypeInfo{\n PyObject* nptype;\n int size;\/\/in bytes\n TypeInfo(const TypeInfo& t):nptype(t.nptype),size(t.size){Py_INCREF(nptype);}\n TypeInfo(const char* nptype, int size):nptype(PyString_FromString(nptype)),size(size){};\n ~TypeInfo(){Py_DECREF(nptype);}\n};\n\nstatic std::map<std::string, TypeInfo> root_typemap;\n\/\/map roottype string to TypeInfo Object\nvoid init_roottypemap(){\n using std::make_pair;\n \/\/TODO: correct this one so it doesn't depend on system\n \/\/ from TTree doc\n \/\/ - C : a character string terminated by the 0 character\n \/\/ - B : an 8 bit signed integer (Char_t)\n \/\/ - b : an 8 bit unsigned integer (UChar_t)\n \/\/ - S : a 16 bit signed integer (Short_t)\n \/\/ - s : a 16 bit unsigned integer (UShort_t)\n \/\/ - I : a 32 bit signed integer (Int_t)\n \/\/ - i : a 32 bit unsigned integer (UInt_t)\n \/\/ - F : a 32 bit floating point (Float_t)\n \/\/ - D : a 64 bit floating point (Double_t)\n \/\/ - L : a 64 bit signed integer (Long64_t)\n \/\/ - l : a 64 bit unsigned integer (ULong64_t)\n \/\/ - O : [the letter 'o', not a zero] a boolean (Bool_t)\n \/\/ from numericdtype.py\n \/\/ # b -> boolean\n \/\/ # u -> unsigned integer\n \/\/ # i -> signed integer\n \/\/ # f -> floating point\n \/\/ # c -> complex\n \/\/ # M -> datetime\n \/\/ # m -> timedelta\n \/\/ # S -> string\n \/\/ # U -> Unicode string\n \/\/ # V -> record\n \/\/ # O -> Python object\n \n root_typemap.insert(make_pair(\"Char_t\",TypeInfo(\"i1\",1)));\n root_typemap.insert(make_pair(\"UChar_t\",TypeInfo(\"u1\",1))); \n\n root_typemap.insert(make_pair(\"Short_t\",TypeInfo(\"i2\",1)));\n root_typemap.insert(make_pair(\"UShort_t\",TypeInfo(\"u2\",1)));\n \n root_typemap.insert(make_pair(\"Int_t\",TypeInfo(\"i4\",4)));\n root_typemap.insert(make_pair(\"UInt_t\",TypeInfo(\"u4\",4)));\n\n root_typemap.insert(make_pair(\"Float_t\",TypeInfo(\"f4\",4)));\n root_typemap.insert(std::make_pair(\"Double_t\",TypeInfo(\"f8\",8)));\n \n root_typemap.insert(make_pair(\"Long64_t\",TypeInfo(\"i4\",8)));\n root_typemap.insert(make_pair(\"ULong64_t\",TypeInfo(\"u4\",8)));\n \n \/\/this one is kinda special currently need to read c-api on exacly how numpy and root store bool\n \/\/but int seems to work\n root_typemap.insert(make_pair(\"Bool_t\",TypeInfo(\"i4\",4))); \n}\n\nTypeInfo* convert_roottype(const std::string& t){\n std::map<std::string, TypeInfo>::iterator it = root_typemap.find(t);\n if(it==root_typemap.end()){\n std::string msg = \"Unknown root type: \"+t;\n PyErr_SetString(PyExc_RuntimeError,msg.c_str());\n return NULL;\n }\n return &(it->second);\n}\n\nstruct LeafInfo{\n std::string name;\n TypeInfo* type;\n std::string root_type;\n char payload[64];\/\/reserve for payload\n LeafInfo():name(),type(){}\n LeafInfo(const std::string& name,const std::string& root_type):name(name),root_type(root_type),type(0){};\n std::string repr(){\n return name + \"(\"+root_type+\")\";\n }\n};\n\/\/return all branch name from tree\nstd::vector<std::string> get_branchnames(TTree& tree){\n TObjArray* branches = (TObjArray*)tree.GetListOfBranches();\n std::vector<std::string> ret;\n for(int i=0;i<branches->GetEntries();++i){\n TBranch* thisBranch = dynamic_cast<TBranch*>(branches->At(i));\n const char* tmp = thisBranch->GetName();\n std::string str(tmp);\n ret.push_back(tmp);\n }\n return ret;\n}\n\n\/\/vector unique with order preservation(just get the first one) O(nlogn)\nstd::vector<std::string> vector_unique(const std::vector<std::string>& org){\n using namespace std;\n set<string> myset;\n myset.insert(org.begin(),org.end());\n vector<string> ret;\n for(int i=0;i<org.size();i++){\n set<string>::iterator it = myset.find(org[i]);\n if(it!=myset.end()){\n myset.erase(it);\n ret.push_back(org[i]);\n }\n }\n return ret; \n}\n\n\/\/get list of leafinfo from tree\n\/\/if branches is not empty, only the branches specified in branches will be used\n\/\/otherwise it will automatically list all the branches of the first tree in chain \nstd::vector<LeafInfo*> get_leafinfo(TTree& tree,const std::vector<std::string>& branches){\n \n using namespace std;\n vector<string> branchNames;\n std::vector<LeafInfo*> ret;\n if(branches.size()==0) branchNames = get_branchnames(tree);\n else branchNames = vector_unique(branches);\n\n for(int i=0;i<branchNames.size();i++){\n TBranch* thisBranch = dynamic_cast<TBranch*>(tree.GetBranch(branchNames[i].c_str()));\n std::string roottype(\"Float_t\");\n if(thisBranch!=0){\n TObjArray* leaves = thisBranch->GetListOfLeaves();\n assert(leaves!=0);\n TLeaf* thisLeaf = dynamic_cast<TLeaf*>(leaves->At(0));\n assert(thisLeaf!=0);\n roottype = thisLeaf->GetTypeName();\n }else{ \n std::cout << \"Warning: branch not found in the first tree(assume type of Float_t)\" << branchNames[i] << std::endl;\n }\n \/\/need to set branch address at tree level because TChain will fail if branch is set at the first tree\n LeafInfo* li = new LeafInfo(thisBranch->GetName(),roottype);\n tree.SetBranchAddress(thisBranch->GetName(),&(li->payload));\n ret.push_back(li);\n }\n return ret;\n}\n\/\/helper function for building numpy descr\nPyObject* build_numpy_descr(const std::vector<LeafInfo*>& lis){\n \n PyObject* mylist = PyList_New(0);\n for(int i=0;i<lis.size();++i){\n PyObject* pyname = PyString_FromString(lis[i]->name.c_str());\n TypeInfo* ti = convert_roottype(lis[i]->root_type);\n lis[i]->type = ti;\n if(ti==0) return NULL;\n PyObject* pytype = ti->nptype;\n\n Py_INCREF(pytype);\n PyObject* nt_tuple = PyTuple_New(2);\n PyTuple_SetItem(nt_tuple,0,pyname);\n PyTuple_SetItem(nt_tuple,1,pytype);\n \n PyList_Append(mylist,nt_tuple);\n }\n return mylist;\n}\n\n\/\/convert all leaf specified in lis to numpy structured array\nPyObject* read_helper(TTree& chain, std::vector<LeafInfo*>& lis){\n int numEntries = chain.GetEntries();\n PyObject* numpy_descr = build_numpy_descr(lis);\n if(numpy_descr==0){return NULL;}\n \n \/\/build the array\n PyArray_Descr* descr;\n PyArray_DescrConverter(numpy_descr,&descr);\n Py_DECREF(numpy_descr);\n \n npy_intp dims[1];\n dims[0]=numEntries;\n \n PyArrayObject* array = (PyArrayObject*)PyArray_SimpleNewFromDescr(1,dims,descr);\n \n \/\/assume numpy array is contiguous\n char* current = (char*)PyArray_DATA(array);\n \/\/now put stuff in array\n for(int iEntry=0;iEntry<numEntries;++iEntry){\n chain.GetEntry(iEntry);\n for(int ileaf=0;ileaf<lis.size();++ileaf){\n \/\/cout << *(int*)(lis[ileaf]->payload) << \" \" << *(float*)(lis[ileaf]->payload) << endl;\n int size = lis[ileaf]->type->size;\n memcpy((void*)current,(void*)lis[ileaf]->payload,size);\n current+=size;\n }\n }\n \/\/return Py_BuildValue(\"i\",numEntries);\n return (PyObject*)array;\n}\n\n\/\/convert list of string to vector of string\n\/\/if los is just a string vos will be filled with that string\n\/\/if los is null or PyNone it do nothing to vos and return OK;\nint los2vos(PyObject* los, std::vector<std::string>& vos){\n int ret=1;\n if(los==NULL){\n \/\/do nothing\n }\n else if(los==Py_None){\n \/\/do nothing\n }\n else if(PyString_Check(los)){\n char* tmp = PyString_AsString(los);\n vos.push_back(tmp);\n }else if(PyList_Check(los)){\n int len = PyList_Size(los);\n for(int i=0;i<len;i++){\n PyObject* s = PyList_GetItem(los,i);\n if(!s){return NULL;}\n char* tmp = PyString_AsString(s);\n if(!tmp){return NULL;}\n std::string str(tmp);\n vos.push_back(tmp);\n }\n }else{\n ret=NULL;\n }\n return ret;\n}\n\n\/**\n* loadTTree from PyObject if fnames is list of string then it load every pattern in fnames\n* if fnames is just a string then it load just one\n* caller is responsible to delete the return value\n* null is return if fnames is not a valid python object(either list of string or string)\n*\/\nTTree* loadTree(PyObject* fnames, const char* treename){\n using namespace std;\n vector<string> vs;\n if(!los2vos(fnames,vs)){return NULL;}\n TChain* chain = new TChain(treename);\n for(int i=0;i<vs.size();++i){chain->Add(vs[i].c_str());}\n return dynamic_cast<TTree*>(chain);\n}\n\nPyObject* root2array(PyObject *self, PyObject *args, PyObject* keywords){\n using namespace std;\n PyObject* fnames;\n char* treename_;\n PyObject* branches_=NULL;\n PyObject* array=NULL;\n static const char* keywordslist[] = {\"fname\",\"treename\",\"branches\",NULL};\n \n if(!PyArg_ParseTupleAndKeywords(args,keywords,\"Os|O\",const_cast<char **>(keywordslist),&fnames,&treename_,&branches_)){\n return NULL;\n }\n \n vector<string> branches;\n if(!los2vos(branches_,branches)){return NULL;}\n \n TTree* chain = loadTree(fnames,treename_);\n if(!chain){return NULL;}\n \n int numEntries = chain->GetEntries();\n if(numEntries==0){\n PyErr_SetString(PyExc_TypeError,\"Empty Tree\");\n return NULL;\n }\n \n vector<LeafInfo*> lis = get_leafinfo(*chain,branches);\n \n array = read_helper(*chain, lis);\n \n \/\/don't switch these two lines because lis[i] contains payload\n delete chain;\n for(int i=0;i<lis.size();i++){delete lis[i];}\n\n return (PyObject*)array;\n}\n\nstatic PyMethodDef methods[] = {\n {\"root2array\", (PyCFunction)root2array, METH_VARARGS|METH_KEYWORDS,\n \"root2array(fnames,treename,branches=None)\\n\"\n \"convert tree treename in root files specified in fnames to numpy structured array\\n\"\n \"------------------\\n\"\n \"return numpy array\\n\"\n \"fnames: list of string or string. Root file name patterns. Anything that works with TChain.Add is accepted\\n\"\n \"treename: name of tree to convert to numpy array\\n\"\n \"branches(optional): list of string for branch name to be extracted from tree.\\n\"\n \"\\tIf branches is not specified or is none or is empty, all from the first treebranches are extracted\\n\"\n \"\\tIf branches contains duplicate branches, only the first one is used.\\n\"\n \"\\n\"\n \"Caveat: This should not matter for most use cases. But, due to the way TChain works, if the trees specified in the input files have different\\n\"\n \"structures, only the branch in the first tree will be automatically extracted. You can work around this by either reordering the input file or\\n\"\n \"specify the branches manually.\\n\"\n \"------------------\\n\"\n \"Ex:\\n\"\n \"root2array('a.root','mytree')#read all branches from tree named mytree from a.root\\n\\n\"\n \"root2array('a*.root','mytree')#read all branches from tree named mytree from a*.root\\n\\n\"\n \"root2array(['a*.root','b*.root'],'mytree')#read all branches from tree named mytree from a*.root and b*.root\\n\\n\"\n \"root2array('a.root','mytree','x')#read branch x from tree named mytree from a.root(useful if memory usage matters)\\n\\n\"\n \"root2array('a.root','mytree',['x','y'])#read branch x and y from tree named mytree from a.root\\n\"\n },\n {NULL, NULL, 0, NULL} \/* Sentinel *\/\n};\n\nvoid cleanup(){\n \/\/do nothing\n}\n\nPyMODINIT_FUNC\ninitcroot_numpy(void)\n{\n import_array();\n init_roottypemap();\n (void) Py_InitModule(\"croot_numpy\", methods);\n \/\/import_array();\n}\n<commit_msg>fix the wrong type convertion for Long_t and ULong_t<commit_after>#include <Python.h>\n#include <string>\n#include <iostream>\n#include <TTree.h>\n#include <TFile.h>\n#include <TChain.h>\n#include <TLeaf.h>\n#include <map>\n#include <numpy\/arrayobject.h>\n#include <cassert>\n#include <set>\nstruct TypeInfo{\n PyObject* nptype;\n int size;\/\/in bytes\n TypeInfo(const TypeInfo& t):nptype(t.nptype),size(t.size){Py_INCREF(nptype);}\n TypeInfo(const char* nptype, int size):nptype(PyString_FromString(nptype)),size(size){};\n ~TypeInfo(){Py_DECREF(nptype);}\n};\n\nstatic std::map<std::string, TypeInfo> root_typemap;\n\/\/map roottype string to TypeInfo Object\nvoid init_roottypemap(){\n using std::make_pair;\n \/\/TODO: correct this one so it doesn't depend on system\n \/\/ from TTree doc\n \/\/ - C : a character string terminated by the 0 character\n \/\/ - B : an 8 bit signed integer (Char_t)\n \/\/ - b : an 8 bit unsigned integer (UChar_t)\n \/\/ - S : a 16 bit signed integer (Short_t)\n \/\/ - s : a 16 bit unsigned integer (UShort_t)\n \/\/ - I : a 32 bit signed integer (Int_t)\n \/\/ - i : a 32 bit unsigned integer (UInt_t)\n \/\/ - F : a 32 bit floating point (Float_t)\n \/\/ - D : a 64 bit floating point (Double_t)\n \/\/ - L : a 64 bit signed integer (Long64_t)\n \/\/ - l : a 64 bit unsigned integer (ULong64_t)\n \/\/ - O : [the letter 'o', not a zero] a boolean (Bool_t)\n \/\/ from numericdtype.py\n \/\/ # b -> boolean\n \/\/ # u -> unsigned integer\n \/\/ # i -> signed integer\n \/\/ # f -> floating point\n \/\/ # c -> complex\n \/\/ # M -> datetime\n \/\/ # m -> timedelta\n \/\/ # S -> string\n \/\/ # U -> Unicode string\n \/\/ # V -> record\n \/\/ # O -> Python object\n \n root_typemap.insert(make_pair(\"Char_t\",TypeInfo(\"i1\",1)));\n root_typemap.insert(make_pair(\"UChar_t\",TypeInfo(\"u1\",1))); \n\n root_typemap.insert(make_pair(\"Short_t\",TypeInfo(\"i2\",1)));\n root_typemap.insert(make_pair(\"UShort_t\",TypeInfo(\"u2\",1)));\n \n root_typemap.insert(make_pair(\"Int_t\",TypeInfo(\"i4\",4)));\n root_typemap.insert(make_pair(\"UInt_t\",TypeInfo(\"u4\",4)));\n\n root_typemap.insert(make_pair(\"Float_t\",TypeInfo(\"f4\",4)));\n root_typemap.insert(std::make_pair(\"Double_t\",TypeInfo(\"f8\",8)));\n \n root_typemap.insert(make_pair(\"Long64_t\",TypeInfo(\"i8\",8)));\n root_typemap.insert(make_pair(\"ULong64_t\",TypeInfo(\"u8\",8)));\n \n \/\/this one is kinda special currently need to read c-api on exacly how numpy and root store bool\n \/\/but int seems to work\n root_typemap.insert(make_pair(\"Bool_t\",TypeInfo(\"i4\",4))); \n}\n\nTypeInfo* convert_roottype(const std::string& t){\n std::map<std::string, TypeInfo>::iterator it = root_typemap.find(t);\n if(it==root_typemap.end()){\n std::string msg = \"Unknown root type: \"+t;\n PyErr_SetString(PyExc_RuntimeError,msg.c_str());\n return NULL;\n }\n return &(it->second);\n}\n\nstruct LeafInfo{\n std::string name;\n TypeInfo* type;\n std::string root_type;\n char payload[64];\/\/reserve for payload\n LeafInfo():name(),type(){}\n LeafInfo(const std::string& name,const std::string& root_type):name(name),root_type(root_type),type(0){};\n std::string repr(){\n return name + \"(\"+root_type+\")\";\n }\n};\n\/\/return all branch name from tree\nstd::vector<std::string> get_branchnames(TTree& tree){\n TObjArray* branches = (TObjArray*)tree.GetListOfBranches();\n std::vector<std::string> ret;\n for(int i=0;i<branches->GetEntries();++i){\n TBranch* thisBranch = dynamic_cast<TBranch*>(branches->At(i));\n const char* tmp = thisBranch->GetName();\n std::string str(tmp);\n ret.push_back(tmp);\n }\n return ret;\n}\n\n\/\/vector unique with order preservation(just get the first one) O(nlogn)\nstd::vector<std::string> vector_unique(const std::vector<std::string>& org){\n using namespace std;\n set<string> myset;\n myset.insert(org.begin(),org.end());\n vector<string> ret;\n for(int i=0;i<org.size();i++){\n set<string>::iterator it = myset.find(org[i]);\n if(it!=myset.end()){\n myset.erase(it);\n ret.push_back(org[i]);\n }\n }\n return ret; \n}\n\n\/\/get list of leafinfo from tree\n\/\/if branches is not empty, only the branches specified in branches will be used\n\/\/otherwise it will automatically list all the branches of the first tree in chain \nstd::vector<LeafInfo*> get_leafinfo(TTree& tree,const std::vector<std::string>& branches){\n \n using namespace std;\n vector<string> branchNames;\n std::vector<LeafInfo*> ret;\n if(branches.size()==0) branchNames = get_branchnames(tree);\n else branchNames = vector_unique(branches);\n\n for(int i=0;i<branchNames.size();i++){\n TBranch* thisBranch = dynamic_cast<TBranch*>(tree.GetBranch(branchNames[i].c_str()));\n std::string roottype(\"Float_t\");\n if(thisBranch!=0){\n TObjArray* leaves = thisBranch->GetListOfLeaves();\n assert(leaves!=0);\n TLeaf* thisLeaf = dynamic_cast<TLeaf*>(leaves->At(0));\n assert(thisLeaf!=0);\n roottype = thisLeaf->GetTypeName();\n }else{ \n std::cout << \"Warning: branch not found in the first tree(assume type of Float_t)\" << branchNames[i] << std::endl;\n }\n \/\/need to set branch address at tree level because TChain will fail if branch is set at the first tree\n LeafInfo* li = new LeafInfo(thisBranch->GetName(),roottype);\n tree.SetBranchAddress(thisBranch->GetName(),&(li->payload));\n ret.push_back(li);\n }\n return ret;\n}\n\/\/helper function for building numpy descr\nPyObject* build_numpy_descr(const std::vector<LeafInfo*>& lis){\n \n PyObject* mylist = PyList_New(0);\n for(int i=0;i<lis.size();++i){\n PyObject* pyname = PyString_FromString(lis[i]->name.c_str());\n TypeInfo* ti = convert_roottype(lis[i]->root_type);\n lis[i]->type = ti;\n if(ti==0) return NULL;\n PyObject* pytype = ti->nptype;\n\n Py_INCREF(pytype);\n PyObject* nt_tuple = PyTuple_New(2);\n PyTuple_SetItem(nt_tuple,0,pyname);\n PyTuple_SetItem(nt_tuple,1,pytype);\n \n PyList_Append(mylist,nt_tuple);\n }\n return mylist;\n}\n\n\/\/convert all leaf specified in lis to numpy structured array\nPyObject* read_helper(TTree& chain, std::vector<LeafInfo*>& lis){\n int numEntries = chain.GetEntries();\n PyObject* numpy_descr = build_numpy_descr(lis);\n if(numpy_descr==0){return NULL;}\n \n \/\/build the array\n PyArray_Descr* descr;\n PyArray_DescrConverter(numpy_descr,&descr);\n Py_DECREF(numpy_descr);\n \n npy_intp dims[1];\n dims[0]=numEntries;\n \n PyArrayObject* array = (PyArrayObject*)PyArray_SimpleNewFromDescr(1,dims,descr);\n \n \/\/assume numpy array is contiguous\n char* current = (char*)PyArray_DATA(array);\n \/\/now put stuff in array\n for(int iEntry=0;iEntry<numEntries;++iEntry){\n chain.GetEntry(iEntry);\n for(int ileaf=0;ileaf<lis.size();++ileaf){\n \/\/cout << *(int*)(lis[ileaf]->payload) << \" \" << *(float*)(lis[ileaf]->payload) << endl;\n int size = lis[ileaf]->type->size;\n memcpy((void*)current,(void*)lis[ileaf]->payload,size);\n current+=size;\n }\n }\n \/\/return Py_BuildValue(\"i\",numEntries);\n return (PyObject*)array;\n}\n\n\/\/convert list of string to vector of string\n\/\/if los is just a string vos will be filled with that string\n\/\/if los is null or PyNone it do nothing to vos and return OK;\nint los2vos(PyObject* los, std::vector<std::string>& vos){\n int ret=1;\n if(los==NULL){\n \/\/do nothing\n }\n else if(los==Py_None){\n \/\/do nothing\n }\n else if(PyString_Check(los)){\n char* tmp = PyString_AsString(los);\n vos.push_back(tmp);\n }else if(PyList_Check(los)){\n int len = PyList_Size(los);\n for(int i=0;i<len;i++){\n PyObject* s = PyList_GetItem(los,i);\n if(!s){return NULL;}\n char* tmp = PyString_AsString(s);\n if(!tmp){return NULL;}\n std::string str(tmp);\n vos.push_back(tmp);\n }\n }else{\n ret=NULL;\n }\n return ret;\n}\n\n\/**\n* loadTTree from PyObject if fnames is list of string then it load every pattern in fnames\n* if fnames is just a string then it load just one\n* caller is responsible to delete the return value\n* null is return if fnames is not a valid python object(either list of string or string)\n*\/\nTTree* loadTree(PyObject* fnames, const char* treename){\n using namespace std;\n vector<string> vs;\n if(!los2vos(fnames,vs)){return NULL;}\n TChain* chain = new TChain(treename);\n for(int i=0;i<vs.size();++i){chain->Add(vs[i].c_str());}\n return dynamic_cast<TTree*>(chain);\n}\n\nPyObject* root2array(PyObject *self, PyObject *args, PyObject* keywords){\n using namespace std;\n PyObject* fnames;\n char* treename_;\n PyObject* branches_=NULL;\n PyObject* array=NULL;\n static const char* keywordslist[] = {\"fname\",\"treename\",\"branches\",NULL};\n \n if(!PyArg_ParseTupleAndKeywords(args,keywords,\"Os|O\",const_cast<char **>(keywordslist),&fnames,&treename_,&branches_)){\n return NULL;\n }\n \n vector<string> branches;\n if(!los2vos(branches_,branches)){return NULL;}\n \n TTree* chain = loadTree(fnames,treename_);\n if(!chain){return NULL;}\n \n int numEntries = chain->GetEntries();\n if(numEntries==0){\n PyErr_SetString(PyExc_TypeError,\"Empty Tree\");\n return NULL;\n }\n \n vector<LeafInfo*> lis = get_leafinfo(*chain,branches);\n \n array = read_helper(*chain, lis);\n \n \/\/don't switch these two lines because lis[i] contains payload\n delete chain;\n for(int i=0;i<lis.size();i++){delete lis[i];}\n\n return (PyObject*)array;\n}\n\nstatic PyMethodDef methods[] = {\n {\"root2array\", (PyCFunction)root2array, METH_VARARGS|METH_KEYWORDS,\n \"root2array(fnames,treename,branches=None)\\n\"\n \"convert tree treename in root files specified in fnames to numpy structured array\\n\"\n \"------------------\\n\"\n \"return numpy array\\n\"\n \"fnames: list of string or string. Root file name patterns. Anything that works with TChain.Add is accepted\\n\"\n \"treename: name of tree to convert to numpy array\\n\"\n \"branches(optional): list of string for branch name to be extracted from tree.\\n\"\n \"\\tIf branches is not specified or is none or is empty, all from the first treebranches are extracted\\n\"\n \"\\tIf branches contains duplicate branches, only the first one is used.\\n\"\n \"\\n\"\n \"Caveat: This should not matter for most use cases. But, due to the way TChain works, if the trees specified in the input files have different\\n\"\n \"structures, only the branch in the first tree will be automatically extracted. You can work around this by either reordering the input file or\\n\"\n \"specify the branches manually.\\n\"\n \"------------------\\n\"\n \"Ex:\\n\"\n \"root2array('a.root','mytree')#read all branches from tree named mytree from a.root\\n\\n\"\n \"root2array('a*.root','mytree')#read all branches from tree named mytree from a*.root\\n\\n\"\n \"root2array(['a*.root','b*.root'],'mytree')#read all branches from tree named mytree from a*.root and b*.root\\n\\n\"\n \"root2array('a.root','mytree','x')#read branch x from tree named mytree from a.root(useful if memory usage matters)\\n\\n\"\n \"root2array('a.root','mytree',['x','y'])#read branch x and y from tree named mytree from a.root\\n\"\n },\n {NULL, NULL, 0, NULL} \/* Sentinel *\/\n};\n\nvoid cleanup(){\n \/\/do nothing\n}\n\nPyMODINIT_FUNC\ninitcroot_numpy(void)\n{\n import_array();\n init_roottypemap();\n (void) Py_InitModule(\"croot_numpy\", methods);\n \/\/import_array();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Generator\/Generator.h\"\n\n#include \"Config.h\"\n#include \"Utils\/Utils.h\"\n#include <cstring>\n#include <cstdlib>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <getopt.h>\n#include <cstdio>\n#include <iostream>\n\n\/*! dalec\n\n The main compiler executable, responsible for organising the\n arguments for Generator, running Generator, and assembling\/linking\n the results together using the system's compiler.\n*\/\n\nusing namespace dale;\n\nstatic const char *options = \"M:m:O:a:I:L:l:o:s:b:cdrR\";\n\nstatic bool\nappearsToBeLib(const char *str)\n{\n int len = strlen(str);\n if (len >= 2) {\n const char *end = str + (len - 2);\n if ((!strcmp(end, \".o\")) || (!strcmp(end, \".a\"))) {\n return true;\n }\n }\n return false;\n}\n\nstd::string\njoinWithPrefix (std::vector<const char*> strings,\n const std::string prefix, std::string buffer)\n{\n for (std::vector<const char*>::iterator b = strings.begin (),\n e = strings.end ();\n b != e; buffer += \" \" + prefix + \" \" + (* b ++));\n\n return buffer;\n}\n\nint\nmain(int argc, char **argv)\n{\n srand(time(NULL) + getpid());\n\n progname = argv[0];\n\n int opt;\n char optc;\n\n std::vector<const char*>\n input_files,\n input_link_files,\n compile_libs,\n run_libs,\n include_paths,\n run_paths,\n bitcode_paths,\n static_modules,\n module_paths;\n\n const char *output_path_arg = NULL;\n const char *module_name = NULL;\n\n int produce = ASM;\n int optlevel = 0;\n\n int produce_set = 0;\n int no_linking = 0;\n int debug = 0;\n int no_dale_stdlib = 0;\n int no_stdlib = 0;\n int remove_macros = 0;\n int no_common = 0;\n int static_mods_all = 0;\n int found_sm = 0;\n int enable_cto = 0;\n int version = 0;\n int print_expansions = 0;\n\n int option_index = 0;\n int forced_remove_macros = 0;\n\n static struct option long_options[] = {\n { \"no-dale-stdlib\", no_argument, &no_dale_stdlib, 1 },\n { \"no-common\", no_argument, &no_common, 1 },\n { \"no-stdlib\", no_argument, &no_stdlib, 1 },\n { \"static-modules\", no_argument, &static_mods_all, 1 },\n { \"static-module\", required_argument, &found_sm, 1 },\n { \"enable-cto\", no_argument, &enable_cto, 1 },\n { \"version\", no_argument, &version, 1 },\n { \"print-expansions\", no_argument, &print_expansions, 1 },\n { 0, 0, 0, 0 }\n };\n\n if (argc < 2) {\n error(\"no input files\");\n }\n\n while ((opt = getopt_long(argc, argv, options,\n long_options, &option_index)) != -1) {\n optc = (char) opt;\n\n switch (optc) {\n case 'o': {\n if (output_path_arg) {\n error(\"an output path has already been specified\");\n }\n output_path_arg = optarg;\n break;\n }\n case 'O': {\n optlevel = (optarg[0] - '0');\n if ((optlevel < 0) || (optlevel > 4)) {\n error(\"invalid optimisation level\");\n }\n break;\n }\n case 's': {\n produce_set = true;\n\n const char *type = optarg;\n if (!strcmp (type, \"as\")) produce = ASM; else\n if (!strcmp (type, \"ir\")) produce = IR; else\n if (!strcmp (type, \"bc\")) produce = BitCode; else\n error (\"unrecognised output file format\");\n\n break;\n }\n case 'd': debug = 1; break;\n case 'c': no_linking = 1; break;\n case 'r': remove_macros = 1; forced_remove_macros = 1; break;\n case 'R': remove_macros = 0; forced_remove_macros = 1; break;\n case 'I': include_paths.push_back(optarg); break;\n case 'a': compile_libs.push_back(optarg); break;\n case 'L': run_paths.push_back(optarg); break;\n case 'l': run_libs.push_back(optarg); break;\n case 'b': bitcode_paths.push_back(optarg); break;\n case 'M': module_paths.push_back(optarg); break;\n case 'm': module_name = optarg; break;\n };\n\n if (found_sm) {\n found_sm = 0;\n static_modules.push_back(optarg);\n }\n }\n\n if (version)\n std::cout << DALE_VERSION_MAJOR << \".\"\n << DALE_VERSION_MINOR << std::endl, exit (0);\n\n \/* If the user wants an executable and has not specified either\n * way with respect to removing macros, then remove macros. *\/\n if (!no_linking && !produce_set && !forced_remove_macros) {\n remove_macros = 1;\n }\n\n \/* Every argument after the options is treated as an input file.\n * Input files that end with .o or .a should go straight to the\n * linker. *\/\n while (optind != argc)\n {\n const char *input_file = argv [optind ++];\n\n (appearsToBeLib (input_file) ?\n input_link_files : input_files) .push_back (input_file);\n }\n if (input_files.size () == 0) error (\"no input files\");\n\n \/* Set output_path. *\/\n std::string output_path;\n if (output_path_arg) output_path = output_path_arg; \/\/ is given\n else \/\/ otherwise construct it\n {\n output_path = input_files [0]; \/\/ leave the extension as is\n\n if (no_linking) output_path += \".o\";\n else if (produce_set) output_path +=\n ((produce == IR) ? \".ll\" :\n (produce == ASM) ? \".s\" :\n (produce == BitCode) ? \".bc\" :\n \".unknown\" ); \/\/ impossible, an error\n else output_path = \"a.out\"; \/\/ overwrite what was there\n }\n\n std::vector<std::string> so_paths;\n Generator generator;\n\n std::string intermediate_output_path =\n output_path + (produce_set ? \"\" : \".s\");\n {\n FILE *output_file =\n fopen (intermediate_output_path.c_str (), \"w\");\n if (output_file == NULL) error (\"unable to open %s for writing\",\n intermediate_output_path.c_str (),\n true);\n if (! generator.run (&input_files,\n &bitcode_paths,\n &compile_libs,\n &include_paths,\n &module_paths,\n &static_modules,\n module_name,\n debug,\n produce,\n optlevel,\n remove_macros,\n no_common,\n no_dale_stdlib,\n static_mods_all,\n enable_cto,\n print_expansions,\n &so_paths,\n output_file)) exit (1);\n if (fflush (output_file) != 0)\n error (\"unable to flush the intermediate output file\", true);\n }\n if (produce_set) exit (0); \/\/ we're done\n\n \/\/ prepare the strings to sew the compile command with\n std::string input_file_str =\n joinWithPrefix (input_files, \" \", \"\");\n std::string compile_lib_str =\n joinWithPrefix (compile_libs, \"-l\", \"\");\n std::string include_path_str =\n joinWithPrefix (include_paths, \"-I\", \"\");\n std::string run_path_str =\n joinWithPrefix (run_paths, \"-L\", \"\");\n std::string run_lib_str =\n joinWithPrefix (run_libs, \"-l\", \"\");\n std::string rpath_str = strcmp (SYSTEM_NAME, \"Darwin\") ?\n \"\" : joinWithPrefix (module_paths, \"-rpath\", \"\");\n\n std::string input_link_file_str =\n joinWithPrefix (input_link_files, \" \", \"\");\n for (std::vector<std::string>::iterator b = so_paths.begin (),\n e = so_paths.end ();\n b != e; input_link_file_str += \" \" + (* b ++));\n\n \/\/ compose the compiler\/linker command and execute it\n const char *aux = getenv (\"DALE_CC_FLAGS\"); \/\/ auxiliary options\n std::string compile_cmd = DALE_CC;\n if (no_stdlib) compile_cmd += \" --nostdlib\";\n if (no_linking) compile_cmd += \" -c\";\n else compile_cmd += strcmp (SYSTEM_NAME, \"Darwin\")\n ? \" -Wl,--gc-sections\" : \"\";\n compile_cmd += run_path_str + rpath_str;\n if (no_linking) compile_cmd += run_lib_str;\n compile_cmd += \" \" + intermediate_output_path;\n if (! no_linking)\n compile_cmd += input_link_file_str + run_lib_str + \" -lm\";\n compile_cmd += \" -o \" + output_path;\n if (aux) compile_cmd += \" \", compile_cmd += aux;\n\n if (aux) std::cerr << \"Going to run: \" << compile_cmd << std::endl,\n fflush (stderr); \/\/ show it immediately\n\n int status = system (compile_cmd.c_str ());\n if (status != 0) {\n if (debug) {\n std::cerr << compile_cmd << std::endl;\n }\n error(DALE_CC \" failed\");\n }\n\n status = remove(intermediate_output_path.c_str());\n if (status != 0) {\n if (debug) {\n std::cerr << intermediate_output_path << std::endl;\n }\n error(\"unable to remove temporary file\");\n }\n\n return 0;\n}\n<commit_msg>dalec: `appearsToBeLib` is rewritten functionally<commit_after>#include \"Generator\/Generator.h\"\n\n#include \"Config.h\"\n#include \"Utils\/Utils.h\"\n#include <cstring>\n#include <cstdlib>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <getopt.h>\n#include <cstdio>\n#include <iostream>\n\n\/*! dalec\n\n The main compiler executable, responsible for organising the\n arguments for Generator, running Generator, and assembling\/linking\n the results together using the system's compiler.\n*\/\n\nusing namespace dale;\n\nstatic const char *options = \"M:m:O:a:I:L:l:o:s:b:cdrR\";\n\nstatic bool\nis_ending_on (const char *string, const char *ending)\n{\n size_t sl = strlen (string), el = strlen (ending);\n\n return (sl >= el) && (strcmp (string + (sl - el), ending) == 0);\n}\n\nstatic bool\nappearsToBeLib (const char *str)\n{\n return is_ending_on (str, \".o\") || is_ending_on (str, \".a\");\n}\n\nstd::string\njoinWithPrefix (std::vector<const char*> strings,\n const std::string prefix, std::string buffer)\n{\n for (std::vector<const char*>::iterator b = strings.begin (),\n e = strings.end ();\n b != e; buffer += \" \" + prefix + \" \" + (* b ++));\n\n return buffer;\n}\n\nint\nmain(int argc, char **argv)\n{\n srand(time(NULL) + getpid());\n\n progname = argv[0];\n\n int opt;\n char optc;\n\n std::vector<const char*>\n input_files,\n input_link_files,\n compile_libs,\n run_libs,\n include_paths,\n run_paths,\n bitcode_paths,\n static_modules,\n module_paths;\n\n const char *output_path_arg = NULL;\n const char *module_name = NULL;\n\n int produce = ASM;\n int optlevel = 0;\n\n int produce_set = 0;\n int no_linking = 0;\n int debug = 0;\n int no_dale_stdlib = 0;\n int no_stdlib = 0;\n int remove_macros = 0;\n int no_common = 0;\n int static_mods_all = 0;\n int found_sm = 0;\n int enable_cto = 0;\n int version = 0;\n int print_expansions = 0;\n\n int option_index = 0;\n int forced_remove_macros = 0;\n\n static struct option long_options[] = {\n { \"no-dale-stdlib\", no_argument, &no_dale_stdlib, 1 },\n { \"no-common\", no_argument, &no_common, 1 },\n { \"no-stdlib\", no_argument, &no_stdlib, 1 },\n { \"static-modules\", no_argument, &static_mods_all, 1 },\n { \"static-module\", required_argument, &found_sm, 1 },\n { \"enable-cto\", no_argument, &enable_cto, 1 },\n { \"version\", no_argument, &version, 1 },\n { \"print-expansions\", no_argument, &print_expansions, 1 },\n { 0, 0, 0, 0 }\n };\n\n if (argc < 2) {\n error(\"no input files\");\n }\n\n while ((opt = getopt_long(argc, argv, options,\n long_options, &option_index)) != -1) {\n optc = (char) opt;\n\n switch (optc) {\n case 'o': {\n if (output_path_arg) {\n error(\"an output path has already been specified\");\n }\n output_path_arg = optarg;\n break;\n }\n case 'O': {\n optlevel = (optarg[0] - '0');\n if ((optlevel < 0) || (optlevel > 4)) {\n error(\"invalid optimisation level\");\n }\n break;\n }\n case 's': {\n produce_set = true;\n\n const char *type = optarg;\n if (!strcmp (type, \"as\")) produce = ASM; else\n if (!strcmp (type, \"ir\")) produce = IR; else\n if (!strcmp (type, \"bc\")) produce = BitCode; else\n error (\"unrecognised output file format\");\n\n break;\n }\n case 'd': debug = 1; break;\n case 'c': no_linking = 1; break;\n case 'r': remove_macros = 1; forced_remove_macros = 1; break;\n case 'R': remove_macros = 0; forced_remove_macros = 1; break;\n case 'I': include_paths.push_back(optarg); break;\n case 'a': compile_libs.push_back(optarg); break;\n case 'L': run_paths.push_back(optarg); break;\n case 'l': run_libs.push_back(optarg); break;\n case 'b': bitcode_paths.push_back(optarg); break;\n case 'M': module_paths.push_back(optarg); break;\n case 'm': module_name = optarg; break;\n };\n\n if (found_sm) {\n found_sm = 0;\n static_modules.push_back(optarg);\n }\n }\n\n if (version)\n std::cout << DALE_VERSION_MAJOR << \".\"\n << DALE_VERSION_MINOR << std::endl, exit (0);\n\n \/* If the user wants an executable and has not specified either\n * way with respect to removing macros, then remove macros. *\/\n if (!no_linking && !produce_set && !forced_remove_macros) {\n remove_macros = 1;\n }\n\n \/* Every argument after the options is treated as an input file.\n * Input files that end with .o or .a should go straight to the\n * linker. *\/\n while (optind != argc)\n {\n const char *input_file = argv [optind ++];\n\n (appearsToBeLib (input_file) ?\n input_link_files : input_files) .push_back (input_file);\n }\n if (input_files.size () == 0) error (\"no input files\");\n\n \/* Set output_path. *\/\n std::string output_path;\n if (output_path_arg) output_path = output_path_arg; \/\/ is given\n else \/\/ otherwise construct it\n {\n output_path = input_files [0]; \/\/ leave the extension as is\n\n if (no_linking) output_path += \".o\";\n else if (produce_set) output_path +=\n ((produce == IR) ? \".ll\" :\n (produce == ASM) ? \".s\" :\n (produce == BitCode) ? \".bc\" :\n \".unknown\" ); \/\/ impossible, an error\n else output_path = \"a.out\"; \/\/ overwrite what was there\n }\n\n std::vector<std::string> so_paths;\n Generator generator;\n\n std::string intermediate_output_path =\n output_path + (produce_set ? \"\" : \".s\");\n {\n FILE *output_file =\n fopen (intermediate_output_path.c_str (), \"w\");\n if (output_file == NULL) error (\"unable to open %s for writing\",\n intermediate_output_path.c_str (),\n true);\n if (! generator.run (&input_files,\n &bitcode_paths,\n &compile_libs,\n &include_paths,\n &module_paths,\n &static_modules,\n module_name,\n debug,\n produce,\n optlevel,\n remove_macros,\n no_common,\n no_dale_stdlib,\n static_mods_all,\n enable_cto,\n print_expansions,\n &so_paths,\n output_file)) exit (1);\n if (fflush (output_file) != 0)\n error (\"unable to flush the intermediate output file\", true);\n }\n if (produce_set) exit (0); \/\/ we're done\n\n \/\/ prepare the strings to sew the compile command with\n std::string input_file_str =\n joinWithPrefix (input_files, \" \", \"\");\n std::string compile_lib_str =\n joinWithPrefix (compile_libs, \"-l\", \"\");\n std::string include_path_str =\n joinWithPrefix (include_paths, \"-I\", \"\");\n std::string run_path_str =\n joinWithPrefix (run_paths, \"-L\", \"\");\n std::string run_lib_str =\n joinWithPrefix (run_libs, \"-l\", \"\");\n std::string rpath_str = strcmp (SYSTEM_NAME, \"Darwin\") ?\n \"\" : joinWithPrefix (module_paths, \"-rpath\", \"\");\n\n std::string input_link_file_str =\n joinWithPrefix (input_link_files, \" \", \"\");\n for (std::vector<std::string>::iterator b = so_paths.begin (),\n e = so_paths.end ();\n b != e; input_link_file_str += \" \" + (* b ++));\n\n \/\/ compose the compiler\/linker command and execute it\n const char *aux = getenv (\"DALE_CC_FLAGS\"); \/\/ auxiliary options\n std::string compile_cmd = DALE_CC;\n if (no_stdlib) compile_cmd += \" --nostdlib\";\n if (no_linking) compile_cmd += \" -c\";\n else compile_cmd += strcmp (SYSTEM_NAME, \"Darwin\")\n ? \" -Wl,--gc-sections\" : \"\";\n compile_cmd += run_path_str + rpath_str;\n if (no_linking) compile_cmd += run_lib_str;\n compile_cmd += \" \" + intermediate_output_path;\n if (! no_linking)\n compile_cmd += input_link_file_str + run_lib_str + \" -lm\";\n compile_cmd += \" -o \" + output_path;\n if (aux) compile_cmd += \" \", compile_cmd += aux;\n\n if (aux) std::cerr << \"Going to run: \" << compile_cmd << std::endl,\n fflush (stderr); \/\/ show it immediately\n\n int status = system (compile_cmd.c_str ());\n if (status != 0) {\n if (debug) {\n std::cerr << compile_cmd << std::endl;\n }\n error(DALE_CC \" failed\");\n }\n\n status = remove(intermediate_output_path.c_str());\n if (status != 0) {\n if (debug) {\n std::cerr << intermediate_output_path << std::endl;\n }\n error(\"unable to remove temporary file\");\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2014 Software Reliability Lab, ETH Zurich\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"nice2server.h\"\n\n#include \"glog\/logging.h\"\n#include \"jsoncpp\/json\/json.h\"\n#include \"jsonrpccpp\/server.h\"\n#include \"jsonrpccpp\/server\/connectors\/httpserver.h\"\n#include \"jsonrpccpp\/common\/exception.h\"\n\n#include \"stringprintf.h\"\n\n#include \"graph_inference.h\"\n#include \"server_log.h\"\n#include \"inference.h\"\n\nDEFINE_string(model, \"model\", \"Input model files\");\nDEFINE_string(model_version, \"\", \"Version of the current model\");\n\nDEFINE_string(logfile_prefix, \"\", \"File where to log all requests and responses\");\n\nnamespace {\nvoid DropTrainingNewLine(std::string* s) {\n if (s->empty()) return;\n if ((*s)[s->size() - 1] == '\\n') s->erase(s->begin() + s->size() - 1, s->end());\n}\n}\n\nclass Nice2ServerInternal : public jsonrpc::AbstractServer<Nice2ServerInternal> {\npublic:\n Nice2ServerInternal(jsonrpc::HttpServer* server) : jsonrpc::AbstractServer<Nice2ServerInternal>(*server) {\n bindAndAddMethod(\n jsonrpc::Procedure(\"infer\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::infer);\n bindAndAddMethod(\n jsonrpc::Procedure(\"nbest\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"n\", jsonrpc::JSON_INTEGER,\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::nbest);\n\n bindAndAddMethod(\n jsonrpc::Procedure(\"showgraph\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::showgraph);\n\n inference_.LoadModel(FLAGS_model);\n\n if (!FLAGS_logfile_prefix.empty()) {\n logging_.reset(new Nice2ServerLog(FLAGS_logfile_prefix));\n }\n }\n\n void verifyVersion(const Json::Value& request){\n VLOG(3) << \"Current version: \" << FLAGS_model_version << \". Request version: \" << request[\"version\"];\n if (FLAGS_model_version.empty()){\n return;\n }\n\n if (!request.isMember(\"version\") ||\n strcmp(request[\"version\"].asCString(), FLAGS_model_version.c_str()) != 0){\n std::ostringstream stringStream;\n stringStream << \"The version of client '\" << request[\"version\"].asString() <<\n \"' does not match the server version '\" << FLAGS_model_version << \"'. \" <<\n \"Please update the client to the latest version by running 'npm update -g unuglify-js'.\";\n throw jsonrpc::JsonRpcException(-31001, stringStream.str());\n }\n }\n\n\n void MaybeLogQuery(const char* method, const Json::Value& request, const Json::Value& response) {\n if (logging_.get() == NULL) {\n return;\n }\n\n Json::FastWriter writer;\n std::string rs1 = writer.write(request);\n std::string rs2 = writer.write(response);\n DropTrainingNewLine(&rs1);\n DropTrainingNewLine(&rs2);\n logging_->LogRecord(StringPrintf(\n \"\\\"method\\\":\\\"%s\\\", \"\n \"\\\"request\\\":%s, \"\n \"\\\"reply\\\":%s\",\n method, rs1.c_str(), rs2.c_str()));\n }\n\n\n void infer(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->ToJSON(&response);\n\n MaybeLogQuery(\"infer\", request, response);\n }\n\n void nbest(const Json::Value& request, Json::Value& response)\n {\n int n = request[\"n\"].asInt();\n int v = request[\"v\"].asInt();\n\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->GetCandidates(inference_, n, v, &response);\n\n MaybeLogQuery(\"nbest\", request, response);\n }\n\n void showgraph(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n if (request.isMember(\"infer\") && request[\"infer\"].asBool() == true) {\n inference_.MapInference(query.get(), assignment.get());\n }\n inference_.DisplayGraph(query.get(), assignment.get(), &response);\n\n MaybeLogQuery(\"showgraph\", request, response);\n }\n\nprivate:\n GraphInference inference_;\n std::unique_ptr<Nice2ServerLog> logging_;\n};\n\nNice2Server::Nice2Server(jsonrpc::HttpServer* server)\n : internal_(new Nice2ServerInternal(server)) {\n}\n\nNice2Server::~Nice2Server() {\n delete internal_;\n}\n\nvoid Nice2Server::Listen() {\n internal_->StartListening();\n LOG(INFO) << \"Nice2Server started.\";\n for (;;) {\n sleep(1);\n }\n internal_->StopListening();\n}\n<commit_msg>fixed parameters <commit_after>\/*\n Copyright 2014 Software Reliability Lab, ETH Zurich\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"nice2server.h\"\n\n#include \"glog\/logging.h\"\n#include \"jsoncpp\/json\/json.h\"\n#include \"jsonrpccpp\/server.h\"\n#include \"jsonrpccpp\/server\/connectors\/httpserver.h\"\n#include \"jsonrpccpp\/common\/exception.h\"\n\n#include \"stringprintf.h\"\n\n#include \"graph_inference.h\"\n#include \"server_log.h\"\n#include \"inference.h\"\n\nDEFINE_string(model, \"model\", \"Input model files\");\nDEFINE_string(model_version, \"\", \"Version of the current model\");\n\nDEFINE_string(logfile_prefix, \"\", \"File where to log all requests and responses\");\n\nnamespace {\nvoid DropTrainingNewLine(std::string* s) {\n if (s->empty()) return;\n if ((*s)[s->size() - 1] == '\\n') s->erase(s->begin() + s->size() - 1, s->end());\n}\n}\n\nclass Nice2ServerInternal : public jsonrpc::AbstractServer<Nice2ServerInternal> {\npublic:\n Nice2ServerInternal(jsonrpc::HttpServer* server) : jsonrpc::AbstractServer<Nice2ServerInternal>(*server) {\n bindAndAddMethod(\n jsonrpc::Procedure(\"infer\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::infer);\n bindAndAddMethod(\n jsonrpc::Procedure(\"nbest\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"n\", jsonrpc::JSON_INTEGER,\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::nbest);\n\n bindAndAddMethod(\n jsonrpc::Procedure(\"showgraph\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::showgraph);\n\n inference_.LoadModel(FLAGS_model);\n\n if (!FLAGS_logfile_prefix.empty()) {\n logging_.reset(new Nice2ServerLog(FLAGS_logfile_prefix));\n }\n }\n\n void verifyVersion(const Json::Value& request){\n VLOG(3) << \"Current version: \" << FLAGS_model_version << \". Request version: \" << request[\"version\"];\n if (FLAGS_model_version.empty()){\n return;\n }\n\n if (!request.isMember(\"version\") ||\n strcmp(request[\"version\"].asCString(), FLAGS_model_version.c_str()) != 0){\n std::ostringstream stringStream;\n stringStream << \"The version of client '\" << request[\"version\"].asString() <<\n \"' does not match the server version '\" << FLAGS_model_version << \"'. \" <<\n \"Please update the client to the latest version by running 'npm update -g unuglify-js'.\";\n throw jsonrpc::JsonRpcException(-31001, stringStream.str());\n }\n }\n\n\n void MaybeLogQuery(const char* method, const Json::Value& request, const Json::Value& response) {\n if (logging_.get() == NULL) {\n return;\n }\n\n Json::FastWriter writer;\n std::string rs1 = writer.write(request);\n std::string rs2 = writer.write(response);\n DropTrainingNewLine(&rs1);\n DropTrainingNewLine(&rs2);\n logging_->LogRecord(StringPrintf(\n \"\\\"method\\\":\\\"%s\\\", \"\n \"\\\"request\\\":%s, \"\n \"\\\"reply\\\":%s\",\n method, rs1.c_str(), rs2.c_str()));\n }\n\n\n void infer(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->ToJSON(&response);\n\n MaybeLogQuery(\"infer\", request, response);\n }\n\n void nbest(const Json::Value& request, Json::Value& response)\n {\n int n = request[\"n\"].asInt();\n int v = request[\"v\"].asInt();\n\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->GetCandidates(inference_, v, n, &response);\n\n MaybeLogQuery(\"nbest\", request, response);\n }\n\n void showgraph(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n if (request.isMember(\"infer\") && request[\"infer\"].asBool() == true) {\n inference_.MapInference(query.get(), assignment.get());\n }\n inference_.DisplayGraph(query.get(), assignment.get(), &response);\n\n MaybeLogQuery(\"showgraph\", request, response);\n }\n\nprivate:\n GraphInference inference_;\n std::unique_ptr<Nice2ServerLog> logging_;\n};\n\nNice2Server::Nice2Server(jsonrpc::HttpServer* server)\n : internal_(new Nice2ServerInternal(server)) {\n}\n\nNice2Server::~Nice2Server() {\n delete internal_;\n}\n\nvoid Nice2Server::Listen() {\n internal_->StartListening();\n LOG(INFO) << \"Nice2Server started.\";\n for (;;) {\n sleep(1);\n }\n internal_->StopListening();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"3rd_party\/exception.h\"\n#include \"3rd_party\/yaml-cpp\/yaml.h\"\n#include \"common\/logging.h\"\n#include \"common\/utils.h\"\n#include \"data\/vocab.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n#include <unordered_set>\n#include <regex>\n\nnamespace marian {\n\nVocab::Vocab() {}\n\nsize_t Vocab::operator[](const std::string& word) const {\n auto it = str2id_.find(word);\n if(it != str2id_.end())\n return it->second;\n else\n return UNK_ID;\n}\n\nWords Vocab::operator()(const std::vector<std::string>& lineTokens,\n bool addEOS) const {\n Words words(lineTokens.size());\n std::transform(lineTokens.begin(),\n lineTokens.end(),\n words.begin(),\n [&](const std::string& w) { return (*this)[w]; });\n if(addEOS)\n words.push_back(EOS_ID);\n return words;\n}\n\nWords Vocab::operator()(const std::string& line, bool addEOS) const {\n std::vector<std::string> lineTokens;\n Split(line, lineTokens, \" \");\n return (*this)(lineTokens, addEOS);\n}\n\nstd::vector<std::string> Vocab::operator()(const Words& sentence,\n bool ignoreEOS) const {\n std::vector<std::string> decoded;\n for(size_t i = 0; i < sentence.size(); ++i) {\n if((sentence[i] != EOS_ID || !ignoreEOS)) {\n decoded.push_back((*this)[sentence[i]]);\n }\n }\n return decoded;\n}\n\nconst std::string& Vocab::operator[](size_t id) const {\n ABORT_IF(id >= id2str_.size(), \"Unknown word id: \", id);\n return id2str_[id];\n}\n\nsize_t Vocab::size() const {\n return id2str_.size();\n}\n\nint Vocab::loadOrCreate(const std::string& vocabPath,\n const std::string& trainPath,\n int max) {\n if(vocabPath.empty()) {\n if(boost::filesystem::exists(trainPath + \".json\")) {\n return load(trainPath + \".json\", max);\n }\n if(boost::filesystem::exists(trainPath + \".yml\")) {\n return load(trainPath + \".yml\", max);\n }\n create(trainPath + \".yml\", trainPath);\n return load(trainPath + \".yml\", max);\n } else {\n if(!boost::filesystem::exists(vocabPath))\n create(vocabPath, trainPath);\n return load(vocabPath, max);\n }\n}\n\nint Vocab::load(const std::string& vocabPath, int max) {\n bool isYaml = std::regex_search(vocabPath, std::regex(\".yml$\"));\n LOG(info, \"[data] Loading vocabulary from {} file {}\", isYaml ? \"Yaml\" : \"text\", vocabPath);\n ABORT_IF(!boost::filesystem::exists(vocabPath),\n \"Vocabulary {} does not exits\",\n vocabPath);\n\n std::map<std::string,Word> vocab;\n if (isYaml) \/\/ read from Yaml file\n {\n YAML::Node vocabNode = YAML::Load(InputFileStream(vocabPath));\n for(auto&& pair : vocabNode)\n vocab.insert({ pair.first.as<std::string>(), pair.second.as<Word>() });\n }\n else \/\/ read from flat text file\n {\n std::ifstream in(vocabPath);\n std::string line;\n while (std::getline(in, line))\n vocab.insert({ line, vocab.size() });\n ABORT_IF(in.bad(), \"Vocabulary file {} could not be read\", vocabPath);\n }\n\n std::unordered_set<Word> seenSpecial;\n\n for(auto&& pair : vocab) {\n auto str = pair.first;\n auto id = pair.second;\n\n if(SPEC2SYM.count(str)) {\n seenSpecial.insert(id);\n }\n\n if(!max || id < (Word)max) { \/\/ note: this requires ids to be sorted by frequency\n str2id_[str] = id;\n if(id >= id2str_.size())\n id2str_.resize(id + 1);\n id2str_[id] = str;\n }\n }\n ABORT_IF(id2str_.empty(), \"Empty vocabulary: \", vocabPath);\n\n \/\/ <\/s> and <unk> are expected at specific positions\n auto requireWord = [&](Word id, const std::string& str)\n {\n auto iter = str2id_.find(str);\n if (iter != str2id_.end()) \/\/ word already in vocab: must be at right index, else fail\n {\n ABORT_IF(iter->second != id, \"vocabulary entry '{}' is expected to have id {}\", str, id);\n#if 0\n return;\n#else\n \/\/ some old config needs this patching for now\n \/\/ BUGBUG: If another word already uses this id, then str2id_ for that will still exist.\n#endif\n }\n str2id_[str] = id;\n id2str_[id] = str;\n };\n requireWord(EOS_ID, EOS_STR);\n requireWord(UNK_ID, UNK_STR);\n for(auto id : seenSpecial)\n requireWord(id, SYM2SPEC.at(id));\n\n return std::max((int)id2str_.size(), max);\n}\n\nclass Vocab::VocabFreqOrderer {\nprivate:\n std::unordered_map<std::string, size_t>& counter_;\n\npublic:\n VocabFreqOrderer(std::unordered_map<std::string, size_t>& counter)\n : counter_(counter) {}\n\n bool operator()(const std::string& a, const std::string& b) const {\n return counter_[a] > counter_[b] || (counter_[a] == counter_[b] && a < b);\n }\n};\n\nvoid Vocab::create(const std::string& vocabPath, const std::string& trainPath) {\n LOG(info, \"[data] Creating vocabulary {} from {}\", vocabPath, trainPath);\n\n boost::filesystem::path path(vocabPath);\n auto dir = path.parent_path();\n if(dir.empty())\n dir = boost::filesystem::current_path();\n\n ABORT_IF(!dir.empty() && !boost::filesystem::is_directory(dir),\n \"Specified vocab directory {} does not exist\",\n dir);\n\n ABORT_IF(!dir.empty()\n && !(boost::filesystem::status(dir).permissions()\n & boost::filesystem::owner_write),\n \"No write permission in vocab directory {}\",\n dir);\n\n ABORT_IF(boost::filesystem::exists(vocabPath),\n \"Vocab file '{}' exists. Not overwriting\",\n vocabPath);\n\n InputFileStream trainStrm(trainPath);\n OutputFileStream vocabStrm(vocabPath);\n create(trainStrm, vocabStrm);\n}\n\nvoid Vocab::create(InputFileStream& trainStrm,\n OutputFileStream& vocabStrm,\n size_t maxSize) {\n std::string line;\n std::unordered_map<std::string, size_t> counter;\n\n std::unordered_set<Word> seenSpecial;\n\n while(getline((std::istream&)trainStrm, line)) {\n std::vector<std::string> toks;\n Split(line, toks);\n\n for(const std::string& tok : toks) {\n if(SPEC2SYM.count(tok)) {\n seenSpecial.insert(SPEC2SYM.at(tok));\n continue;\n }\n\n auto iter = counter.find(tok);\n if(iter == counter.end())\n counter[tok] = 1;\n else\n iter->second++;\n }\n }\n\n std::vector<std::string> vocabVec;\n for(auto& p : counter)\n vocabVec.push_back(p.first);\n\n std::sort(vocabVec.begin(), vocabVec.end(), VocabFreqOrderer(counter));\n\n YAML::Node vocabYaml;\n vocabYaml.force_insert(EOS_STR, EOS_ID);\n vocabYaml.force_insert(UNK_STR, UNK_ID);\n\n for(auto word : seenSpecial)\n vocabYaml.force_insert(SYM2SPEC.at(word), word);\n\n Word maxSpec = 1;\n for(auto i : seenSpecial)\n if(i > maxSpec)\n maxSpec = i;\n\n auto vocabSize = vocabVec.size();\n if(maxSize > maxSpec)\n vocabSize = std::min(maxSize - maxSpec - 1, vocabVec.size());\n\n for(size_t i = 0; i < vocabSize; ++i)\n vocabYaml.force_insert(vocabVec[i], i + maxSpec + 1);\n\n (std::ostream&)vocabStrm << vocabYaml;\n}\n}\n<commit_msg>added a BUGBUG comment<commit_after>#include \"3rd_party\/exception.h\"\n#include \"3rd_party\/yaml-cpp\/yaml.h\"\n#include \"common\/logging.h\"\n#include \"common\/utils.h\"\n#include \"data\/vocab.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n#include <unordered_set>\n#include <regex>\n\nnamespace marian {\n\nVocab::Vocab() {}\n\nsize_t Vocab::operator[](const std::string& word) const {\n auto it = str2id_.find(word);\n if(it != str2id_.end())\n return it->second;\n else\n return UNK_ID;\n}\n\nWords Vocab::operator()(const std::vector<std::string>& lineTokens,\n bool addEOS) const {\n Words words(lineTokens.size());\n std::transform(lineTokens.begin(),\n lineTokens.end(),\n words.begin(),\n [&](const std::string& w) { return (*this)[w]; });\n if(addEOS)\n words.push_back(EOS_ID);\n return words;\n}\n\nWords Vocab::operator()(const std::string& line, bool addEOS) const {\n std::vector<std::string> lineTokens;\n Split(line, lineTokens, \" \");\n return (*this)(lineTokens, addEOS);\n}\n\nstd::vector<std::string> Vocab::operator()(const Words& sentence,\n bool ignoreEOS) const {\n std::vector<std::string> decoded;\n for(size_t i = 0; i < sentence.size(); ++i) {\n if((sentence[i] != EOS_ID || !ignoreEOS)) {\n decoded.push_back((*this)[sentence[i]]);\n }\n }\n return decoded;\n}\n\nconst std::string& Vocab::operator[](size_t id) const {\n ABORT_IF(id >= id2str_.size(), \"Unknown word id: \", id);\n return id2str_[id];\n}\n\nsize_t Vocab::size() const {\n return id2str_.size();\n}\n\nint Vocab::loadOrCreate(const std::string& vocabPath,\n const std::string& trainPath,\n int max) {\n if(vocabPath.empty()) {\n if(boost::filesystem::exists(trainPath + \".json\")) {\n return load(trainPath + \".json\", max);\n }\n if(boost::filesystem::exists(trainPath + \".yml\")) {\n return load(trainPath + \".yml\", max);\n }\n create(trainPath + \".yml\", trainPath);\n return load(trainPath + \".yml\", max);\n } else {\n if(!boost::filesystem::exists(vocabPath))\n create(vocabPath, trainPath);\n return load(vocabPath, max);\n }\n}\n\nint Vocab::load(const std::string& vocabPath, int max) {\n bool isYaml = std::regex_search(vocabPath, std::regex(\".yml$\")); \/\/ BUGBUG: Is .json also indicative of a Yaml file? Whats \"\\.{yml,json}$\" in C++ regex?\n LOG(info, \"[data] Loading vocabulary from {} file {}\", isYaml ? \"Yaml\" : \"text\", vocabPath);\n ABORT_IF(!boost::filesystem::exists(vocabPath),\n \"Vocabulary {} does not exits\",\n vocabPath);\n\n std::map<std::string,Word> vocab;\n if (isYaml) \/\/ read from Yaml file\n {\n YAML::Node vocabNode = YAML::Load(InputFileStream(vocabPath));\n for(auto&& pair : vocabNode)\n vocab.insert({ pair.first.as<std::string>(), pair.second.as<Word>() });\n }\n else \/\/ read from flat text file\n {\n std::ifstream in(vocabPath);\n std::string line;\n while (std::getline(in, line))\n vocab.insert({ line, vocab.size() });\n ABORT_IF(in.bad(), \"Vocabulary file {} could not be read\", vocabPath);\n }\n\n std::unordered_set<Word> seenSpecial;\n\n for(auto&& pair : vocab) {\n auto str = pair.first;\n auto id = pair.second;\n\n if(SPEC2SYM.count(str)) {\n seenSpecial.insert(id);\n }\n\n if(!max || id < (Word)max) { \/\/ note: this requires ids to be sorted by frequency\n str2id_[str] = id;\n if(id >= id2str_.size())\n id2str_.resize(id + 1);\n id2str_[id] = str;\n }\n }\n ABORT_IF(id2str_.empty(), \"Empty vocabulary: \", vocabPath);\n\n \/\/ <\/s> and <unk> are expected at specific positions\n auto requireWord = [&](Word id, const std::string& str)\n {\n auto iter = str2id_.find(str);\n if (iter != str2id_.end()) \/\/ word already in vocab: must be at right index, else fail\n {\n ABORT_IF(iter->second != id, \"vocabulary entry '{}' is expected to have id {}\", str, id);\n#if 0\n return;\n#else\n \/\/ some old config needs this patching for now\n \/\/ BUGBUG: If another word already uses this id, then str2id_ for that will still exist.\n#endif\n }\n str2id_[str] = id;\n id2str_[id] = str;\n };\n requireWord(EOS_ID, EOS_STR);\n requireWord(UNK_ID, UNK_STR);\n for(auto id : seenSpecial)\n requireWord(id, SYM2SPEC.at(id));\n\n return std::max((int)id2str_.size(), max);\n}\n\nclass Vocab::VocabFreqOrderer {\nprivate:\n std::unordered_map<std::string, size_t>& counter_;\n\npublic:\n VocabFreqOrderer(std::unordered_map<std::string, size_t>& counter)\n : counter_(counter) {}\n\n bool operator()(const std::string& a, const std::string& b) const {\n return counter_[a] > counter_[b] || (counter_[a] == counter_[b] && a < b);\n }\n};\n\nvoid Vocab::create(const std::string& vocabPath, const std::string& trainPath) {\n LOG(info, \"[data] Creating vocabulary {} from {}\", vocabPath, trainPath);\n\n boost::filesystem::path path(vocabPath);\n auto dir = path.parent_path();\n if(dir.empty())\n dir = boost::filesystem::current_path();\n\n ABORT_IF(!dir.empty() && !boost::filesystem::is_directory(dir),\n \"Specified vocab directory {} does not exist\",\n dir);\n\n ABORT_IF(!dir.empty()\n && !(boost::filesystem::status(dir).permissions()\n & boost::filesystem::owner_write),\n \"No write permission in vocab directory {}\",\n dir);\n\n ABORT_IF(boost::filesystem::exists(vocabPath),\n \"Vocab file '{}' exists. Not overwriting\",\n vocabPath);\n\n InputFileStream trainStrm(trainPath);\n OutputFileStream vocabStrm(vocabPath);\n create(trainStrm, vocabStrm);\n}\n\nvoid Vocab::create(InputFileStream& trainStrm,\n OutputFileStream& vocabStrm,\n size_t maxSize) {\n std::string line;\n std::unordered_map<std::string, size_t> counter;\n\n std::unordered_set<Word> seenSpecial;\n\n while(getline((std::istream&)trainStrm, line)) {\n std::vector<std::string> toks;\n Split(line, toks);\n\n for(const std::string& tok : toks) {\n if(SPEC2SYM.count(tok)) {\n seenSpecial.insert(SPEC2SYM.at(tok));\n continue;\n }\n\n auto iter = counter.find(tok);\n if(iter == counter.end())\n counter[tok] = 1;\n else\n iter->second++;\n }\n }\n\n std::vector<std::string> vocabVec;\n for(auto& p : counter)\n vocabVec.push_back(p.first);\n\n std::sort(vocabVec.begin(), vocabVec.end(), VocabFreqOrderer(counter));\n\n YAML::Node vocabYaml;\n vocabYaml.force_insert(EOS_STR, EOS_ID);\n vocabYaml.force_insert(UNK_STR, UNK_ID);\n\n for(auto word : seenSpecial)\n vocabYaml.force_insert(SYM2SPEC.at(word), word);\n\n Word maxSpec = 1;\n for(auto i : seenSpecial)\n if(i > maxSpec)\n maxSpec = i;\n\n auto vocabSize = vocabVec.size();\n if(maxSize > maxSpec)\n vocabSize = std::min(maxSize - maxSpec - 1, vocabVec.size());\n\n for(size_t i = 0; i < vocabSize; ++i)\n vocabYaml.force_insert(vocabVec[i], i + maxSpec + 1);\n\n (std::ostream&)vocabStrm << vocabYaml;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdint>\n\n#include <algorithm>\n#include <chrono>\n#include <stdexcept>\n\n#include <buffer.hpp>\n#include <client.hpp>\n#include <deepstream.hpp>\n#include <error_handler.hpp>\n#include <message.hpp>\n#include <message_builder.hpp>\n#include <scope_guard.hpp>\n#include <websockets.hpp>\n#include <websockets\/poco.hpp>\n#include <use.hpp>\n\n#include <cassert>\n\n\nnamespace deepstream\n{\n\nClient Client::make(\n\tstd::unique_ptr<websockets::Client> p_websocket,\n\tstd::unique_ptr<ErrorHandler> p_error_handler)\n{\n\tassert( p_websocket );\n\tassert( p_error_handler );\n\n\tconst unsigned MAX_NUM_REDIRECTIONS = 3;\n\n\tfor(unsigned num_redirections = 0;\n\t\tnum_redirections < MAX_NUM_REDIRECTIONS;\n\t\t++num_redirections)\n\t{\n\t\tp_websocket->set_receive_timeout( std::chrono::seconds(1) );\n\n\t\tconst std::string uri = p_websocket->uri();\n\n\t\tClient c(\n\t\t\tstd::move(p_websocket),\n\t\t\tstd::move(p_error_handler)\n\t\t);\n\n\t\tBuffer buffer;\n\t\tparser::MessageList messages;\n\t\tclient::State& state = c.state_;\n\n\t\tif( c.receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\t\treturn c;\n\n\t\tif( messages.size() != 1 || state != client::State::CHALLENGING )\n\t\t{\n\t\t\tc.close();\n\t\t\treturn c;\n\t\t}\n\n\t\t{\n\t\t\tMessageBuilder chr(Topic::CONNECTION, Action::CHALLENGE_RESPONSE);\n\t\t\tchr.add_argument(uri);\n\n\t\t\tif( c.send_(chr) != websockets::State::OPEN )\n\t\t\t\treturn c;\n\t\t}\n\n\t\tif( c.receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\t\treturn c;\n\n\t\tif( messages.size() != 1 )\n\t\t{\n\t\t\tc.close();\n\t\t\treturn c;\n\t\t}\n\n\t\tif( state == client::State::AWAIT_AUTHENTICATION )\n\t\t\treturn c;\n\n\t\tif( state == client::State::AWAIT_CONNECTION )\n\t\t{\n\t\t\tconst Message& redirect_msg = messages.front();\n\t\t\tassert( redirect_msg.num_arguments() == 1 );\n\n\t\t\tconst Buffer& uri_buffer = redirect_msg[0];\n\t\t\tstd::string new_uri( uri_buffer.cbegin(), uri_buffer.cend() );\n\n\t\t\tp_websocket = c.p_websocket_->construct(new_uri);\n\t\t\tp_error_handler = std::move(c.p_error_handler_);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tc.close();\n\t\treturn c;\n\t}\n\n\tassert( p_error_handler );\n\tp_error_handler->too_many_redirections(MAX_NUM_REDIRECTIONS);\n\n\treturn Client( nullptr, std::move(p_error_handler) );\n}\n\n\nClient Client::make(const std::string& uri)\n{\n\treturn Client::make(\n\t\tstd::unique_ptr<websockets::Client>(new websockets::poco::Client(uri)),\n\t\tstd::unique_ptr<ErrorHandler>(new ErrorHandler())\n\t);\n}\n\n\n\nClient::Client(\n\tstd::unique_ptr<websockets::Client> p_websocket,\n\tstd::unique_ptr<ErrorHandler> p_error_handler\n) :\n\tevent(\n\t\t[this] (const Message& message) -> bool {\n\t\t\treturn send_(message) == websockets::State::OPEN;\n\t\t}\n\t),\n\tpresence(\n\t\t[this] (const Message& message) -> bool {\n\t\t\treturn send_(message) == websockets::State::OPEN;\n\t\t}\n\t),\n\tstate_(\n\t\tp_websocket\n\t\t? client::State::AWAIT_CONNECTION\n\t\t: client::State::ERROR\n\t),\n\tp_websocket_( std::move(p_websocket) ),\n\tp_error_handler_( std::move(p_error_handler) )\n{\n\tassert( p_error_handler_ );\n}\n\n\nclient::State Client::login(\n\tconst std::string& auth, Buffer* p_user_data)\n{\n\tif( !p_websocket_ )\n\t\treturn client::State::ERROR;\n\n\tif( state_ != client::State::AWAIT_AUTHENTICATION )\n\t\tthrow std::logic_error(\"Cannot login() in current state\");\n\n\tMessageBuilder areq(Topic::AUTH, Action::REQUEST);\n\tareq.add_argument(auth);\n\n\tif( send_(areq) != websockets::State::OPEN )\n\t\treturn state_;\n\n\tBuffer buffer;\n\tparser::MessageList messages;\n\n\tif( receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\treturn state_;\n\n\tif( messages.size() != 1 )\n\t{\n\t\tclose();\n\t\treturn client::State::ERROR;\n\t}\n\n\tconst Message& msg = messages.front();\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::REQUEST &&\n\t\tmsg.is_ack() )\n\t{\n\t\tassert( state_ == client::State::CONNECTED );\n\n\t\tif( msg.num_arguments() == 0 && p_user_data )\n\t\t\tp_user_data->clear();\n\t\telse if( msg.num_arguments() == 1 && p_user_data )\n\t\t\t*p_user_data = msg[0];\n\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_INVALID_AUTH_DATA )\n\t{\n\t\tassert( state_ == client::State::AWAIT_AUTHENTICATION );\n\n\t\tp_error_handler_->authentication_error(msg);\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_INVALID_AUTH_MSG )\n\t{\n\t\tp_error_handler_->authentication_error(msg);\n\t\tclose();\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS )\n\t{\n\t\tp_error_handler_->authentication_error(msg);\n\t\tclose();\n\t\treturn state_;\n\t}\n\n\n\tclose();\n\treturn client::State::ERROR;\n}\n\n\nvoid Client::close()\n{\n\tassert( p_websocket_ || state_ == client::State::ERROR );\n\n\tif( !p_websocket_ )\n\t\treturn;\n\n\tstate_ = client::State::DISCONNECTED;\n\n\t\tp_websocket_->close();\n}\n\n\n\nvoid Client::process_messages()\n{\n\tif( !p_websocket_ )\n\t\treturn;\n\n\n\tBuffer buffer;\n\tparser::MessageList messages;\n\n\tp_websocket_->set_receive_timeout( std::chrono::milliseconds(1) );\n\n\twhile( receive_(&buffer, &messages) == websockets::State::OPEN )\n\t{\n\t\tif( messages.empty() )\n\t\t\tbreak;\n\n\t\tfor(const Message& message : messages)\n\t\t{\n\t\t\tif( message.topic() == Topic::CONNECTION &&\n\t\t\t\tmessage.action() == Action::PING )\n\t\t\t{\n\t\t\t\tMessageBuilder pong( Topic::CONNECTION, Action::PONG );\n\t\t\t\tsend_(pong);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch( message.topic() )\n\t\t\t{\n\t\t\t\tcase Topic::EVENT:\n\t\t\t\t\tevent.notify_(message);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Topic::PRESENCE:\n\t\t\t\t\tpresence.notify_(message);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tassert(0);\n\t\t\t\t\tclose();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nwebsockets::State Client::receive_(\n\tBuffer* p_buffer, parser::MessageList* p_messages)\n{\n\tassert( p_buffer );\n\tassert( p_messages );\n\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\tauto receive_ret = p_websocket_->receive_frame();\n\twebsockets::State ws_state = receive_ret.first;\n\tstd::unique_ptr<websockets::Frame> p_frame = std::move(receive_ret.second);\n\n\tif( ws_state == websockets::State::OPEN && !p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::CLOSED && p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::CLOSED && !p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\t\tp_error_handler_->sudden_disconnect( p_websocket_->uri() );\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::ERROR )\n\t{\n\t\tassert( p_frame );\n\n\t\tclose();\n\t\tp_error_handler_->invalid_close_frame_size(*p_frame);\n\n\t\treturn ws_state;\n\t}\n\n\tassert( ws_state == websockets::State::OPEN );\n\tassert( p_frame );\n\n\tif( p_frame->flags() !=\n\t\t(websockets::Frame::Bit::FIN | websockets::Frame::Opcode::TEXT_FRAME) )\n\t{\n\t\tp_error_handler_->unexpected_websocket_frame_flags( p_frame->flags() );\n\t\tclose();\n\n\t\treturn websockets::State::ERROR;\n\t}\n\n\n\tconst Buffer& payload = p_frame->payload();\n\tp_buffer->assign( payload.cbegin(), payload.cend() );\n\tp_buffer->push_back(0);\n\tp_buffer->push_back(0);\n\n\tauto parser_ret = parser::execute( p_buffer->data(), p_buffer->size() );\n\tconst parser::ErrorList& errors = parser_ret.second;\n\n\tstd::for_each(\n\t\terrors.cbegin(), errors.cend(),\n\t\t[this] (const parser::Error& e) {\n\t\t\tthis->p_error_handler_->parser_error(e);\n\t\t}\n\t);\n\n\tif( !errors.empty() )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\t\treturn websockets::State::ERROR;\n\t}\n\n\n\t*p_messages = std::move(parser_ret.first);\n\n\tfor(auto it = p_messages->cbegin(); it != p_messages->cend(); ++it)\n\t{\n\t\tconst Message& msg = *it;\n\n\t\tclient::State old_state = state_;\n\t\tclient::State new_state =\n\t\t\tclient::transition(old_state, msg, Sender::SERVER);\n\n\t\tif( new_state == client::State::ERROR )\n\t\t{\n\t\t\tclose();\n\t\t\tp_error_handler_->invalid_state_transition(old_state, msg);\n\n\t\t\treturn websockets::State::ERROR;\n\t\t}\n\n\t\tif( new_state == client::State::DISCONNECTED )\n\t\t\treturn websockets::State::OPEN;\n\n\t\tstate_ = new_state;\n\t}\n\n\treturn ws_state;\n}\n\n\nwebsockets::State Client::send_(const Message& message)\n{\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\tclient::State new_state =\n\t\tclient::transition(state_, message, Sender::CLIENT);\n\tassert( new_state != client::State::ERROR );\n\n\tif( new_state == client::State::ERROR )\n\t\tthrow std::logic_error( \"Invalid client state transition\" );\n\n\tstate_ = new_state;\n\n\treturn send_frame_( message.to_binary() );\n}\n\n\n\nwebsockets::State Client::send_frame_(const Buffer& buffer)\n{\n\treturn send_frame_(\n\t\tbuffer,\n\t\twebsockets::Frame::Bit::FIN | websockets::Frame::Opcode::TEXT_FRAME\n\t);\n}\n\n\nwebsockets::State Client::send_frame_(\n\tconst Buffer& buffer,\n\twebsockets::Frame::Flags flags)\n{\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\ttry\n\t{\n\t\twebsockets::State state = p_websocket_->send_frame(buffer, flags);\n\n\t\tif( state != websockets::State::OPEN )\n\t\t{\n\t\t\tclose();\n\t\t\tp_error_handler_->sudden_disconnect( p_websocket_->uri() );\n\n\t\t\treturn websockets::State::CLOSED;\n\t\t}\n\n\t\treturn state;\n\t}\n\tcatch(std::system_error& e)\n\t{\n\t\tp_error_handler_->system_error(e);\n\t}\n\tcatch(std::exception& e)\n\t{\n\t\tp_error_handler_->websocket_exception(e);\n\t}\n\n\tclose();\n\treturn websockets::State::ERROR;\n}\n\n}\n<commit_msg>Client: fix return value<commit_after>\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdint>\n\n#include <algorithm>\n#include <chrono>\n#include <stdexcept>\n\n#include <buffer.hpp>\n#include <client.hpp>\n#include <deepstream.hpp>\n#include <error_handler.hpp>\n#include <message.hpp>\n#include <message_builder.hpp>\n#include <scope_guard.hpp>\n#include <websockets.hpp>\n#include <websockets\/poco.hpp>\n#include <use.hpp>\n\n#include <cassert>\n\n\nnamespace deepstream\n{\n\nClient Client::make(\n\tstd::unique_ptr<websockets::Client> p_websocket,\n\tstd::unique_ptr<ErrorHandler> p_error_handler)\n{\n\tassert( p_websocket );\n\tassert( p_error_handler );\n\n\tconst unsigned MAX_NUM_REDIRECTIONS = 3;\n\n\tfor(unsigned num_redirections = 0;\n\t\tnum_redirections < MAX_NUM_REDIRECTIONS;\n\t\t++num_redirections)\n\t{\n\t\tp_websocket->set_receive_timeout( std::chrono::seconds(1) );\n\n\t\tconst std::string uri = p_websocket->uri();\n\n\t\tClient c(\n\t\t\tstd::move(p_websocket),\n\t\t\tstd::move(p_error_handler)\n\t\t);\n\n\t\tBuffer buffer;\n\t\tparser::MessageList messages;\n\t\tclient::State& state = c.state_;\n\n\t\tif( c.receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\t\treturn c;\n\n\t\tif( messages.size() != 1 || state != client::State::CHALLENGING )\n\t\t{\n\t\t\tc.close();\n\t\t\treturn c;\n\t\t}\n\n\t\t{\n\t\t\tMessageBuilder chr(Topic::CONNECTION, Action::CHALLENGE_RESPONSE);\n\t\t\tchr.add_argument(uri);\n\n\t\t\tif( c.send_(chr) != websockets::State::OPEN )\n\t\t\t\treturn c;\n\t\t}\n\n\t\tif( c.receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\t\treturn c;\n\n\t\tif( messages.size() != 1 )\n\t\t{\n\t\t\tc.close();\n\t\t\treturn c;\n\t\t}\n\n\t\tif( state == client::State::AWAIT_AUTHENTICATION )\n\t\t\treturn c;\n\n\t\tif( state == client::State::AWAIT_CONNECTION )\n\t\t{\n\t\t\tconst Message& redirect_msg = messages.front();\n\t\t\tassert( redirect_msg.num_arguments() == 1 );\n\n\t\t\tconst Buffer& uri_buffer = redirect_msg[0];\n\t\t\tstd::string new_uri( uri_buffer.cbegin(), uri_buffer.cend() );\n\n\t\t\tp_websocket = c.p_websocket_->construct(new_uri);\n\t\t\tp_error_handler = std::move(c.p_error_handler_);\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tc.close();\n\t\treturn c;\n\t}\n\n\tassert( p_error_handler );\n\tp_error_handler->too_many_redirections(MAX_NUM_REDIRECTIONS);\n\n\treturn Client( nullptr, std::move(p_error_handler) );\n}\n\n\nClient Client::make(const std::string& uri)\n{\n\treturn Client::make(\n\t\tstd::unique_ptr<websockets::Client>(new websockets::poco::Client(uri)),\n\t\tstd::unique_ptr<ErrorHandler>(new ErrorHandler())\n\t);\n}\n\n\n\nClient::Client(\n\tstd::unique_ptr<websockets::Client> p_websocket,\n\tstd::unique_ptr<ErrorHandler> p_error_handler\n) :\n\tevent(\n\t\t[this] (const Message& message) -> bool {\n\t\t\treturn send_(message) == websockets::State::OPEN;\n\t\t}\n\t),\n\tpresence(\n\t\t[this] (const Message& message) -> bool {\n\t\t\treturn send_(message) == websockets::State::OPEN;\n\t\t}\n\t),\n\tstate_(\n\t\tp_websocket\n\t\t? client::State::AWAIT_CONNECTION\n\t\t: client::State::ERROR\n\t),\n\tp_websocket_( std::move(p_websocket) ),\n\tp_error_handler_( std::move(p_error_handler) )\n{\n\tassert( p_error_handler_ );\n}\n\n\nclient::State Client::login(\n\tconst std::string& auth, Buffer* p_user_data)\n{\n\tif( !p_websocket_ )\n\t\treturn client::State::ERROR;\n\n\tif( state_ != client::State::AWAIT_AUTHENTICATION )\n\t\tthrow std::logic_error(\"Cannot login() in current state\");\n\n\tMessageBuilder areq(Topic::AUTH, Action::REQUEST);\n\tareq.add_argument(auth);\n\n\tif( send_(areq) != websockets::State::OPEN )\n\t\treturn state_;\n\n\tBuffer buffer;\n\tparser::MessageList messages;\n\n\tif( receive_(&buffer, &messages) != websockets::State::OPEN )\n\t\treturn state_;\n\n\tif( messages.size() != 1 )\n\t{\n\t\tclose();\n\t\treturn state_;\n\t}\n\n\tconst Message& msg = messages.front();\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::REQUEST &&\n\t\tmsg.is_ack() )\n\t{\n\t\tassert( state_ == client::State::CONNECTED );\n\n\t\tif( msg.num_arguments() == 0 && p_user_data )\n\t\t\tp_user_data->clear();\n\t\telse if( msg.num_arguments() == 1 && p_user_data )\n\t\t\t*p_user_data = msg[0];\n\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_INVALID_AUTH_DATA )\n\t{\n\t\tassert( state_ == client::State::AWAIT_AUTHENTICATION );\n\n\t\tp_error_handler_->authentication_error(msg);\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_INVALID_AUTH_MSG )\n\t{\n\t\tp_error_handler_->authentication_error(msg);\n\t\tclose();\n\t\treturn state_;\n\t}\n\n\tif( msg.topic() == Topic::AUTH &&\n\t\tmsg.action() == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS )\n\t{\n\t\tp_error_handler_->authentication_error(msg);\n\t\tclose();\n\t\treturn state_;\n\t}\n\n\n\tclose();\n\treturn client::State::ERROR;\n}\n\n\nvoid Client::close()\n{\n\tassert( p_websocket_ || state_ == client::State::ERROR );\n\n\tif( !p_websocket_ )\n\t\treturn;\n\n\tstate_ = client::State::DISCONNECTED;\n\n\t\tp_websocket_->close();\n}\n\n\n\nvoid Client::process_messages()\n{\n\tif( !p_websocket_ )\n\t\treturn;\n\n\n\tBuffer buffer;\n\tparser::MessageList messages;\n\n\tp_websocket_->set_receive_timeout( std::chrono::milliseconds(1) );\n\n\twhile( receive_(&buffer, &messages) == websockets::State::OPEN )\n\t{\n\t\tif( messages.empty() )\n\t\t\tbreak;\n\n\t\tfor(const Message& message : messages)\n\t\t{\n\t\t\tif( message.topic() == Topic::CONNECTION &&\n\t\t\t\tmessage.action() == Action::PING )\n\t\t\t{\n\t\t\t\tMessageBuilder pong( Topic::CONNECTION, Action::PONG );\n\t\t\t\tsend_(pong);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch( message.topic() )\n\t\t\t{\n\t\t\t\tcase Topic::EVENT:\n\t\t\t\t\tevent.notify_(message);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Topic::PRESENCE:\n\t\t\t\t\tpresence.notify_(message);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tassert(0);\n\t\t\t\t\tclose();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nwebsockets::State Client::receive_(\n\tBuffer* p_buffer, parser::MessageList* p_messages)\n{\n\tassert( p_buffer );\n\tassert( p_messages );\n\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\tauto receive_ret = p_websocket_->receive_frame();\n\twebsockets::State ws_state = receive_ret.first;\n\tstd::unique_ptr<websockets::Frame> p_frame = std::move(receive_ret.second);\n\n\tif( ws_state == websockets::State::OPEN && !p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::CLOSED && p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::CLOSED && !p_frame )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\t\tp_error_handler_->sudden_disconnect( p_websocket_->uri() );\n\n\t\treturn ws_state;\n\t}\n\n\tif( ws_state == websockets::State::ERROR )\n\t{\n\t\tassert( p_frame );\n\n\t\tclose();\n\t\tp_error_handler_->invalid_close_frame_size(*p_frame);\n\n\t\treturn ws_state;\n\t}\n\n\tassert( ws_state == websockets::State::OPEN );\n\tassert( p_frame );\n\n\tif( p_frame->flags() !=\n\t\t(websockets::Frame::Bit::FIN | websockets::Frame::Opcode::TEXT_FRAME) )\n\t{\n\t\tp_error_handler_->unexpected_websocket_frame_flags( p_frame->flags() );\n\t\tclose();\n\n\t\treturn websockets::State::ERROR;\n\t}\n\n\n\tconst Buffer& payload = p_frame->payload();\n\tp_buffer->assign( payload.cbegin(), payload.cend() );\n\tp_buffer->push_back(0);\n\tp_buffer->push_back(0);\n\n\tauto parser_ret = parser::execute( p_buffer->data(), p_buffer->size() );\n\tconst parser::ErrorList& errors = parser_ret.second;\n\n\tstd::for_each(\n\t\terrors.cbegin(), errors.cend(),\n\t\t[this] (const parser::Error& e) {\n\t\t\tthis->p_error_handler_->parser_error(e);\n\t\t}\n\t);\n\n\tif( !errors.empty() )\n\t{\n\t\tp_buffer->clear();\n\t\tp_messages->clear();\n\n\t\tclose();\n\t\treturn websockets::State::ERROR;\n\t}\n\n\n\t*p_messages = std::move(parser_ret.first);\n\n\tfor(auto it = p_messages->cbegin(); it != p_messages->cend(); ++it)\n\t{\n\t\tconst Message& msg = *it;\n\n\t\tclient::State old_state = state_;\n\t\tclient::State new_state =\n\t\t\tclient::transition(old_state, msg, Sender::SERVER);\n\n\t\tif( new_state == client::State::ERROR )\n\t\t{\n\t\t\tclose();\n\t\t\tp_error_handler_->invalid_state_transition(old_state, msg);\n\n\t\t\treturn websockets::State::ERROR;\n\t\t}\n\n\t\tif( new_state == client::State::DISCONNECTED )\n\t\t\treturn websockets::State::OPEN;\n\n\t\tstate_ = new_state;\n\t}\n\n\treturn ws_state;\n}\n\n\nwebsockets::State Client::send_(const Message& message)\n{\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\tclient::State new_state =\n\t\tclient::transition(state_, message, Sender::CLIENT);\n\tassert( new_state != client::State::ERROR );\n\n\tif( new_state == client::State::ERROR )\n\t\tthrow std::logic_error( \"Invalid client state transition\" );\n\n\tstate_ = new_state;\n\n\treturn send_frame_( message.to_binary() );\n}\n\n\n\nwebsockets::State Client::send_frame_(const Buffer& buffer)\n{\n\treturn send_frame_(\n\t\tbuffer,\n\t\twebsockets::Frame::Bit::FIN | websockets::Frame::Opcode::TEXT_FRAME\n\t);\n}\n\n\nwebsockets::State Client::send_frame_(\n\tconst Buffer& buffer,\n\twebsockets::Frame::Flags flags)\n{\n\tif( !p_websocket_ )\n\t\treturn websockets::State::ERROR;\n\n\ttry\n\t{\n\t\twebsockets::State state = p_websocket_->send_frame(buffer, flags);\n\n\t\tif( state != websockets::State::OPEN )\n\t\t{\n\t\t\tclose();\n\t\t\tp_error_handler_->sudden_disconnect( p_websocket_->uri() );\n\n\t\t\treturn websockets::State::CLOSED;\n\t\t}\n\n\t\treturn state;\n\t}\n\tcatch(std::system_error& e)\n\t{\n\t\tp_error_handler_->system_error(e);\n\t}\n\tcatch(std::exception& e)\n\t{\n\t\tp_error_handler_->websocket_exception(e);\n\t}\n\n\tclose();\n\treturn websockets::State::ERROR;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::cin;\n\nint main()\n{\n vector<int> ivec;\n for (int i; cin >> i; ivec.push_back(i));\n\n if (ivec.empty())\n {\n cout << \"input at least one integer.\" << endl;\n return -1;\n }\n\n auto size = ivec.size();\n if (size % 2 != 0) size = size \/ 2 + 1;\n else size \/= 2;\n\n for (int i = 0; i != size; ++i)\n cout << ivec[i] + ivec[ivec.size() - i - 1] << \" \";\n cout << endl;\n\n return 0;\n}\n<commit_msg>Revise redundant version size<commit_after>#include <iostream>\n#include <vector>\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::cin;\n\nint main()\n{\n vector<int> ivec;\n for (int i; cin >> i; ivec.push_back(i));\n\n if (ivec.empty())\n {\n cout << \"input at least one integer.\" << endl;\n return -1;\n }\n\n \/\/ If the vector has odd size, element in the middle will add to itself.\n auto size = (ivec.size() + 1) \/ 2;\n\n for (int i = 0; i != size; ++i)\n cout << ivec[i] + ivec[ivec.size() - i - 1] << \" \";\n cout << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"widgets\/ui_scroll_pane.h\"\n#include \"ui_style.h\"\n#include \"halley\/support\/logger.h\"\n\nusing namespace Halley;\n\nUIScrollPane::UIScrollPane(String id, Vector2f clipSize, UISizer&& sizer, bool scrollHorizontal, bool scrollVertical)\n\t: UIWidget(std::move(id), Vector2f(), std::move(sizer))\n\t, clipSize(clipSize)\n\t, scrollSpeed(50.0f)\n\t, scrollHorizontal(scrollHorizontal)\n\t, scrollVertical(scrollVertical)\n{\n\tsetHandle(UIEventType::MouseWheel, [this] (const UIEvent& event)\n\t{\n\t\tonMouseWheel(event);\n\t});\n\n\tsetHandle(UIEventType::MakeAreaVisible, [this] (const UIEvent& event)\n\t{\n\t\tscrollToShow(event.getRectData() + getBasePosition(event.getSourceId()), false);\n\t});\n\n\tsetHandle(UIEventType::MakeAreaVisibleCentered, [this] (const UIEvent& event)\n\t{\n\t\tscrollToShow(event.getRectData() + getBasePosition(event.getSourceId()), true);\n\t});\n}\n\nUIScrollPane::UIScrollPane(Vector2f clipSize, UISizer&& sizer, bool scrollHorizontal, bool scrollVertical)\n: UIScrollPane(\"\", clipSize, std::move(sizer), scrollHorizontal, scrollVertical) {\n\n}\n\nVector2f UIScrollPane::getScrollPosition() const\n{\n\treturn scrollPos;\n}\n\nVector2f UIScrollPane::getRelativeScrollPosition() const\n{\n\treturn scrollPos \/ std::max(contentsSize, Vector2f(1.0f, 1.0f));\n}\n\nVector2f UIScrollPane::getRelativeScrollEndPosition() const\n{\n\treturn (scrollPos + clipSize) \/ std::max(contentsSize, Vector2f(1.0f, 1.0f));\n}\n\nvoid UIScrollPane::scrollTo(Vector2f position)\n{\t\n\tif (scrollHorizontal) {\n\t\tscrollPos.x = clamp2(position.x, 0.0f, contentsSize.x - getSize().x);\n\t}\n\t\n\tif (scrollVertical) {\n\t\tscrollPos.y = clamp2(position.y, 0.0f, contentsSize.y - getSize().y);\n\t}\n}\n\nvoid UIScrollPane::scrollBy(Vector2f delta)\n{\n\tscrollTo(scrollPos + delta);\n}\n\nvoid UIScrollPane::setScrollSpeed(float speed)\n{\n\tscrollSpeed = speed;\n}\n\nvoid UIScrollPane::update(Time t, bool moved)\n{\n\trefresh();\n}\n\nbool UIScrollPane::canScroll(UIScrollDirection direction) const\n{\n\tauto contentsSize = UIWidget::getLayoutMinimumSize(false);\n\tif (direction == UIScrollDirection::Horizontal) {\n\t\treturn scrollHorizontal && getSize().x < contentsSize.x;\n\t} else {\n\t\treturn scrollVertical && getSize().y < contentsSize.y;\n\t}\n}\n\nfloat UIScrollPane::getCoverageSize(UIScrollDirection direction) const\n{\n\tauto contentsSize = UIWidget::getLayoutMinimumSize(false);\n\tif (direction == UIScrollDirection::Horizontal) {\n\t\treturn getSize().x \/ contentsSize.x;\n\t} else {\n\t\treturn getSize().y \/ contentsSize.y;\n\t}\n}\n\nvoid UIScrollPane::setScrollWheelEnabled(bool enabled)\n{\n\tscrollWheelEnabled = enabled;\n}\n\nbool UIScrollPane::isScrollWheelEnabled() const\n{\n\treturn scrollWheelEnabled;\n}\n\nvoid UIScrollPane::refresh(bool force)\n{\n\tif (!scrollHorizontal) {\n\t\tclipSize.x = getSize().x;\n\t\tscrollPos.x = 0;\n\t}\n\tif (!scrollVertical) {\n\t\tclipSize.y = getSize().y;\n\t\tscrollPos.y = 0;\n\t}\n\tcontentsSize = UIWidget::getLayoutMinimumSize(false);\n\n\tsetMouseClip(getRect(), force);\n\tscrollTo(getScrollPosition());\n}\n\nvoid UIScrollPane::drawChildren(UIPainter& painter) const\n{\n\tauto p = painter.withClip(getRect());\n\tUIWidget::drawChildren(p);\n}\n\nVector2f UIScrollPane::getLayoutMinimumSize(bool force) const\n{\n\tauto size = UIWidget::getLayoutMinimumSize(false);\n\tif (scrollHorizontal) {\n\t\tsize.x = std::min(size.x, clipSize.x);\n\t}\n\tif (scrollVertical) {\n\t\tsize.y = std::min(size.y, clipSize.y);\n\t}\n\treturn size;\n}\n\nbool UIScrollPane::canInteractWithMouse() const\n{\n\treturn true;\n}\n\nvoid UIScrollPane::onLayout()\n{\n\trefresh();\n}\n\nvoid UIScrollPane::onMouseWheel(const UIEvent& event)\n{\n\tif (scrollWheelEnabled) {\n\t\tconst float delta = scrollSpeed * float(event.getIntData());\n\t\tif (scrollVertical) {\n\t\t\tscrollBy(Vector2f(0.0f, -delta));\n\t\t} else {\n\t\t\tscrollBy(Vector2f(-delta, 0.0f));\n\t\t}\n\t}\n}\n\nVector2f UIScrollPane::getBasePosition(const String& widgetId)\n{\n\tauto widget = tryGetWidget(widgetId);\n\tif (widget) {\n\t\treturn widget->getPosition() + scrollPos - getPosition();\n\t} else {\n\t\treturn Vector2f();\n\t}\n}\n\nVector2f UIScrollPane::getLayoutOriginPosition() const\n{\n\treturn getPosition() - scrollPos.floor();\n}\n\nvoid UIScrollPane::scrollToShow(Rect4f rect, bool center)\n{\n\tauto size = getSize();\n\n\tfloat maxX = rect.getLeft();\n\tfloat minX = rect.getRight() - size.x;\n\tfloat maxY = rect.getTop();\n\tfloat minY = rect.getBottom() - size.y;\n\tauto target = center ? (rect.getCenter() - 0.5f * size) : scrollPos;\n\tscrollTo(Vector2f(clamp(target.x, minX, maxX), clamp(target.y, minY, maxY)));\n}\n\nfloat UIScrollPane::getScrollSpeed() const\n{\n\treturn scrollSpeed;\n}\n\nvoid UIScrollPane::setRelativeScroll(float position, UIScrollDirection direction)\n{\n\tint axis = direction == UIScrollDirection::Horizontal ? 0 : 1;\n\tauto target = scrollPos;\n\ttarget[axis] = position * contentsSize[axis];\n\tscrollTo(target);\n}\n\nstd::optional<float> UIScrollPane::getMaxChildWidth() const\n{\n\tif (scrollHorizontal) {\n\t\treturn std::optional<float>();\n\t} else {\n\t\treturn getSize().x;\n\t}\n}\n\nbool UIScrollPane::ignoreClip() const\n{\n\treturn true;\n}\n\nvoid UIScrollPane::onChildrenAdded()\n{\n\trefresh(true);\n}\n\nvoid UIScrollPane::onChildrenRemoved()\n{\n\trefresh(true);\n}\n<commit_msg>Fix scrolling to new list entities<commit_after>#include \"widgets\/ui_scroll_pane.h\"\n#include \"ui_style.h\"\n#include \"halley\/support\/logger.h\"\n\nusing namespace Halley;\n\nUIScrollPane::UIScrollPane(String id, Vector2f clipSize, UISizer&& sizer, bool scrollHorizontal, bool scrollVertical)\n\t: UIWidget(std::move(id), Vector2f(), std::move(sizer))\n\t, clipSize(clipSize)\n\t, scrollSpeed(50.0f)\n\t, scrollHorizontal(scrollHorizontal)\n\t, scrollVertical(scrollVertical)\n{\n\tsetHandle(UIEventType::MouseWheel, [this] (const UIEvent& event)\n\t{\n\t\tonMouseWheel(event);\n\t});\n\n\tsetHandle(UIEventType::MakeAreaVisible, [this] (const UIEvent& event)\n\t{\n\t\trefresh();\n\t\tscrollToShow(event.getRectData() + getBasePosition(event.getSourceId()), false);\n\t});\n\n\tsetHandle(UIEventType::MakeAreaVisibleCentered, [this] (const UIEvent& event)\n\t{\n\t\trefresh();\n\t\tscrollToShow(event.getRectData() + getBasePosition(event.getSourceId()), true);\n\t});\n}\n\nUIScrollPane::UIScrollPane(Vector2f clipSize, UISizer&& sizer, bool scrollHorizontal, bool scrollVertical)\n: UIScrollPane(\"\", clipSize, std::move(sizer), scrollHorizontal, scrollVertical) {\n\n}\n\nVector2f UIScrollPane::getScrollPosition() const\n{\n\treturn scrollPos;\n}\n\nVector2f UIScrollPane::getRelativeScrollPosition() const\n{\n\treturn scrollPos \/ std::max(contentsSize, Vector2f(1.0f, 1.0f));\n}\n\nVector2f UIScrollPane::getRelativeScrollEndPosition() const\n{\n\treturn (scrollPos + clipSize) \/ std::max(contentsSize, Vector2f(1.0f, 1.0f));\n}\n\nvoid UIScrollPane::scrollTo(Vector2f position)\n{\t\n\tif (scrollHorizontal) {\n\t\tscrollPos.x = clamp2(position.x, 0.0f, contentsSize.x - getSize().x);\n\t}\n\t\n\tif (scrollVertical) {\n\t\tscrollPos.y = clamp2(position.y, 0.0f, contentsSize.y - getSize().y);\n\t}\n}\n\nvoid UIScrollPane::scrollBy(Vector2f delta)\n{\n\tscrollTo(scrollPos + delta);\n}\n\nvoid UIScrollPane::setScrollSpeed(float speed)\n{\n\tscrollSpeed = speed;\n}\n\nvoid UIScrollPane::update(Time t, bool moved)\n{\n\trefresh();\n}\n\nbool UIScrollPane::canScroll(UIScrollDirection direction) const\n{\n\tauto contentsSize = UIWidget::getLayoutMinimumSize(false);\n\tif (direction == UIScrollDirection::Horizontal) {\n\t\treturn scrollHorizontal && getSize().x < contentsSize.x;\n\t} else {\n\t\treturn scrollVertical && getSize().y < contentsSize.y;\n\t}\n}\n\nfloat UIScrollPane::getCoverageSize(UIScrollDirection direction) const\n{\n\tauto contentsSize = UIWidget::getLayoutMinimumSize(false);\n\tif (direction == UIScrollDirection::Horizontal) {\n\t\treturn getSize().x \/ contentsSize.x;\n\t} else {\n\t\treturn getSize().y \/ contentsSize.y;\n\t}\n}\n\nvoid UIScrollPane::setScrollWheelEnabled(bool enabled)\n{\n\tscrollWheelEnabled = enabled;\n}\n\nbool UIScrollPane::isScrollWheelEnabled() const\n{\n\treturn scrollWheelEnabled;\n}\n\nvoid UIScrollPane::refresh(bool force)\n{\n\tif (!scrollHorizontal) {\n\t\tclipSize.x = getSize().x;\n\t\tscrollPos.x = 0;\n\t}\n\tif (!scrollVertical) {\n\t\tclipSize.y = getSize().y;\n\t\tscrollPos.y = 0;\n\t}\n\tcontentsSize = UIWidget::getLayoutMinimumSize(false);\n\n\tsetMouseClip(getRect(), force);\n\tscrollTo(getScrollPosition());\n}\n\nvoid UIScrollPane::drawChildren(UIPainter& painter) const\n{\n\tauto p = painter.withClip(getRect());\n\tUIWidget::drawChildren(p);\n}\n\nVector2f UIScrollPane::getLayoutMinimumSize(bool force) const\n{\n\tauto size = UIWidget::getLayoutMinimumSize(false);\n\tif (scrollHorizontal) {\n\t\tsize.x = std::min(size.x, clipSize.x);\n\t}\n\tif (scrollVertical) {\n\t\tsize.y = std::min(size.y, clipSize.y);\n\t}\n\treturn size;\n}\n\nbool UIScrollPane::canInteractWithMouse() const\n{\n\treturn true;\n}\n\nvoid UIScrollPane::onLayout()\n{\n\trefresh();\n}\n\nvoid UIScrollPane::onMouseWheel(const UIEvent& event)\n{\n\tif (scrollWheelEnabled) {\n\t\tconst float delta = scrollSpeed * float(event.getIntData());\n\t\tif (scrollVertical) {\n\t\t\tscrollBy(Vector2f(0.0f, -delta));\n\t\t} else {\n\t\t\tscrollBy(Vector2f(-delta, 0.0f));\n\t\t}\n\t}\n}\n\nVector2f UIScrollPane::getBasePosition(const String& widgetId)\n{\n\tauto widget = tryGetWidget(widgetId);\n\tif (widget) {\n\t\treturn widget->getPosition() + scrollPos - getPosition();\n\t} else {\n\t\treturn Vector2f();\n\t}\n}\n\nVector2f UIScrollPane::getLayoutOriginPosition() const\n{\n\treturn getPosition() - scrollPos.floor();\n}\n\nvoid UIScrollPane::scrollToShow(Rect4f rect, bool center)\n{\n\tauto size = getSize();\n\n\tfloat maxX = rect.getLeft();\n\tfloat minX = rect.getRight() - size.x;\n\tfloat maxY = rect.getTop();\n\tfloat minY = rect.getBottom() - size.y;\n\tauto target = center ? (rect.getCenter() - 0.5f * size) : scrollPos;\n\tscrollTo(Vector2f(clamp(target.x, minX, maxX), clamp(target.y, minY, maxY)));\n}\n\nfloat UIScrollPane::getScrollSpeed() const\n{\n\treturn scrollSpeed;\n}\n\nvoid UIScrollPane::setRelativeScroll(float position, UIScrollDirection direction)\n{\n\tint axis = direction == UIScrollDirection::Horizontal ? 0 : 1;\n\tauto target = scrollPos;\n\ttarget[axis] = position * contentsSize[axis];\n\tscrollTo(target);\n}\n\nstd::optional<float> UIScrollPane::getMaxChildWidth() const\n{\n\tif (scrollHorizontal) {\n\t\treturn std::optional<float>();\n\t} else {\n\t\treturn getSize().x;\n\t}\n}\n\nbool UIScrollPane::ignoreClip() const\n{\n\treturn true;\n}\n\nvoid UIScrollPane::onChildrenAdded()\n{\n\trefresh(true);\n}\n\nvoid UIScrollPane::onChildrenRemoved()\n{\n\trefresh(true);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ex14_23.h\"\n#include <algorithm> \/\/ for_each, equal\n\nvoid StrVec::push_back(const std::string &s)\n{\n chk_n_alloc();\n alloc.construct(first_free++, s);\n}\n\nstd::pair<std::string*, std::string*>\nStrVec::alloc_n_copy(const std::string *b, const std::string *e)\n{\n auto data = alloc.allocate(e - b);\n return{ data, std::uninitialized_copy(b, e, data) };\n}\n\nvoid StrVec::free()\n{\n if (elements) {\n for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); });\n alloc.deallocate(elements, cap - elements);\n }\n}\n\nvoid StrVec::range_initialize(const std::string *first, const std::string *last)\n{\n auto newdata = alloc_n_copy(first, last);\n elements = newdata.first;\n first_free = cap = newdata.second;\n}\n\nStrVec::StrVec(const StrVec &rhs)\n{\n range_initialize(rhs.begin(), rhs.end());\n}\n\nStrVec::StrVec(std::initializer_list<std::string> il)\n{\n range_initialize(il.begin(), il.end());\n}\n\nStrVec::~StrVec()\n{\n free();\n}\n\nStrVec& StrVec::operator = (const StrVec &rhs)\n{\n auto data = alloc_n_copy(rhs.begin(), rhs.end());\n free();\n elements = data.first;\n first_free = cap = data.second;\n return *this;\n}\n\nvoid StrVec::alloc_n_move(size_t new_cap)\n{\n auto newdata = alloc.allocate(new_cap);\n auto dest = newdata;\n auto elem = elements;\n for (size_t i = 0; i != size(); ++i)\n alloc.construct(dest++, std::move(*elem++));\n free();\n elements = newdata;\n first_free = dest;\n cap = elements + new_cap;\n}\n\nvoid StrVec::reallocate()\n{\n auto newcapacity = size() ? 2 * size() : 1;\n alloc_n_move(newcapacity);\n}\n\nvoid StrVec::reserve(size_t new_cap)\n{\n if (new_cap <= capacity()) return;\n alloc_n_move(new_cap);\n}\n\nvoid StrVec::resize(size_t count)\n{\n resize(count, std::string());\n}\n\nvoid StrVec::resize(size_t count, const std::string &s)\n{\n if (count > size()) {\n if (count > capacity()) reserve(count * 2);\n for (size_t i = size(); i != count; ++i)\n alloc.construct(first_free++, s);\n }\n else if (count < size()) {\n while (first_free != elements + count)\n alloc.destroy(--first_free);\n }\n}\n\nStrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap)\n{\n \/\/ leave s in a state in which it is safe to run the destructor.\n s.elements = s.first_free = s.cap = nullptr;\n}\n\nStrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT\n{\n if (this != &rhs) {\n free();\n elements = rhs.elements;\n first_free = rhs.first_free;\n cap = rhs.cap;\n rhs.elements = rhs.first_free = rhs.cap = nullptr;\n }\n return *this;\n}\n\nbool operator==(const StrVec &lhs, const StrVec &rhs)\n{\n return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()));\n}\n\nbool operator!=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(lhs == rhs);\n}\n\nbool operator<(const StrVec &lhs, const StrVec &rhs)\n{\n return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n\nbool operator>(const StrVec &lhs, const StrVec &rhs)\n{\n return rhs < lhs;\n}\n\nbool operator<=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(rhs < lhs);\n}\n\nbool operator>=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(lhs < rhs);\n}\n\nStrVec& StrVec::operator=(std::initializer_list<std::string> il)\n{\n *this = StrVec(il);\n return *this;\n}\n<commit_msg>Update ex14_23.cpp<commit_after>#include \"ex14_23.h\"\n#include <algorithm> \/\/ for_each, equal\n\nvoid StrVec::push_back(const std::string &s)\n{\n chk_n_alloc();\n alloc.construct(first_free++, s);\n}\n\nstd::pair<std::string*, std::string*>\nStrVec::alloc_n_copy(const std::string *b, const std::string *e)\n{\n auto data = alloc.allocate(e - b);\n return{ data, std::uninitialized_copy(b, e, data) };\n}\n\nvoid StrVec::free()\n{\n if (elements) {\n for_each(elements, first_free, [this](std::string &rhs){ alloc.destroy(&rhs); });\n alloc.deallocate(elements, cap - elements);\n }\n}\n\nvoid StrVec::range_initialize(const std::string *first, const std::string *last)\n{\n auto newdata = alloc_n_copy(first, last);\n elements = newdata.first;\n first_free = cap = newdata.second;\n}\n\nStrVec::StrVec(const StrVec &rhs)\n{\n range_initialize(rhs.begin(), rhs.end());\n}\n\nStrVec::StrVec(std::initializer_list<std::string> il)\n{\n range_initialize(il.begin(), il.end());\n}\n\nStrVec::~StrVec()\n{\n free();\n}\n\nStrVec& StrVec::operator = (const StrVec &rhs)\n{\n auto data = alloc_n_copy(rhs.begin(), rhs.end());\n free();\n elements = data.first;\n first_free = cap = data.second;\n return *this;\n}\n\nvoid StrVec::alloc_n_move(size_t new_cap)\n{\n auto newdata = alloc.allocate(new_cap);\n auto dest = newdata;\n auto elem = elements;\n for (size_t i = 0; i != size(); ++i)\n alloc.construct(dest++, std::move(*elem++));\n free();\n elements = newdata;\n first_free = dest;\n cap = elements + new_cap;\n}\n\nvoid StrVec::reallocate()\n{\n auto newcapacity = size() ? 2 * size() : 1;\n alloc_n_move(newcapacity);\n}\n\nvoid StrVec::reserve(size_t new_cap)\n{\n if (new_cap <= capacity()) return;\n alloc_n_move(new_cap);\n}\n\nvoid StrVec::resize(size_t count)\n{\n resize(count, std::string());\n}\n\nvoid StrVec::resize(size_t count, const std::string &s)\n{\n if (count > size()) {\n if (count > capacity()) reserve(count * 2);\n for (size_t i = size(); i != count; ++i)\n alloc.construct(first_free++, s);\n }\n else if (count < size()) {\n while (first_free != elements + count)\n alloc.destroy(--first_free);\n }\n}\n\nStrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap)\n{\n \/\/ leave s in a state in which it is safe to run the destructor.\n s.elements = s.first_free = s.cap = nullptr;\n}\n\nStrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT\n{\n if (this != &rhs) {\n free();\n elements = rhs.elements;\n first_free = rhs.first_free;\n cap = rhs.cap;\n rhs.elements = rhs.first_free = rhs.cap = nullptr;\n }\n return *this;\n}\n\nbool operator==(const StrVec &lhs, const StrVec &rhs)\n{\n return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()));\n}\n\nbool operator!=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(lhs == rhs);\n}\n\nbool operator<(const StrVec &lhs, const StrVec &rhs)\n{\n return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n\nbool operator>(const StrVec &lhs, const StrVec &rhs)\n{\n return rhs < lhs;\n}\n\nbool operator<=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(rhs < lhs);\n}\n\nbool operator>=(const StrVec &lhs, const StrVec &rhs)\n{\n return !(lhs < rhs);\n}\n\nStrVec& StrVec::operator=(std::initializer_list<std::string> il)\n{\n auto data = alloc_n_copy(il.begin(), il.end());\n\tfree();\n\telements = data.first;\n\tfirst_free = cap = data.second;\n return *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file util_private_ostream.hpp\n * \\brief file util_private_ostream.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <vector>\n#include <iostream>\n#include <sstream>\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/glsl\/shader_source.hpp>\n\n#include \"bounding_box.hpp\"\n\ntemplate<typename T>\nstd::ostream&\noperator<<(std::ostream &ostr, const fastuidraw::range_type<T> &obj)\n{\n ostr << \"[\" << obj.m_begin << \", \" << obj.m_end << \")\";\n return ostr;\n}\n\ntemplate<typename T, size_t N>\nstd::ostream&\noperator<<(std::ostream &ostr, const fastuidraw::vecN<T, N> &obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < N; ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator<<(std::ostream &ostr, fastuidraw::c_array<T> obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < obj.size(); ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator<<(std::ostream &ostr, const std::vector<T> &obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < obj.size(); ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nstd::ostream&\noperator<<(std::ostream &str, const fastuidraw::BoundingBox<T> &obj)\n{\n if (obj.empty())\n {\n str << \"{}\";\n }\n else\n {\n str << \"[\" << obj.min_point() << \" -- \" << obj.max_point() << \"]\";\n }\n return str;\n}\n\ntemplate<typename T>\nfastuidraw::glsl::ShaderSource&\noperator<<(fastuidraw::glsl::ShaderSource &src, const T &obj)\n{\n std::ostringstream str;\n str << obj;\n src.add_source(str.str().c_str(), fastuidraw::glsl::ShaderSource::from_string);\n return src;\n}\n<commit_msg>fastuidraw\/private\/util_private_ostream: add PrintBytes class and place std::ostream& operator<< methods into namespace std<commit_after>\/*!\n * \\file util_private_ostream.hpp\n * \\brief file util_private_ostream.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <vector>\n#include <iostream>\n#include <sstream>\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/glsl\/shader_source.hpp>\n\n#include \"bounding_box.hpp\"\n\nnamespace fastuidraw { namespace detail {\n\nclass PrintBytes\n{\npublic:\n enum rounding_mode_t\n {\n round_to_highest_unit = 0,\n round_to_mb_or_highest_unit = 1,\n round_to_kb_or_highest_unit = 2,\n do_not_round= 3,\n };\n\n explicit\n PrintBytes(uint64_t v, enum rounding_mode_t r = round_to_kb_or_highest_unit):\n m_gb(fastuidraw::uint64_unpack_bits(30u, 34u, v)),\n m_mb(fastuidraw::uint64_unpack_bits(20u, 10u, v)),\n m_kb(fastuidraw::uint64_unpack_bits(10u, 10u, v)),\n m_b(fastuidraw::uint64_unpack_bits(0u, 10u, v)),\n m_rounding_mode(r)\n {}\n\n uint64_t m_gb, m_mb, m_kb, m_b;\n enum rounding_mode_t m_rounding_mode;\n};\n\n}}\n\nnamespace std {\ninline\nostream&\noperator<<(ostream &str, const fastuidraw::detail::PrintBytes &obj)\n{\n bool print_spe(false), print(true);\n char spe(' ');\n\n if (obj.m_gb && print)\n {\n str << obj.m_gb << \"GB\";\n print_spe = true;\n print = (obj.m_rounding_mode > fastuidraw::detail::PrintBytes::round_to_highest_unit);\n }\n\n if (obj.m_mb && print)\n {\n if (print_spe)\n {\n str << spe;\n }\n str << obj.m_mb << \"MB\";\n print_spe = true;\n print = (obj.m_rounding_mode > fastuidraw::detail::PrintBytes::round_to_mb_or_highest_unit);\n }\n\n if (obj.m_kb && print)\n {\n if (print_spe)\n {\n str << spe;\n }\n str << obj.m_kb << \"KB\";\n print_spe = true;\n print = (obj.m_rounding_mode > fastuidraw::detail::PrintBytes::round_to_kb_or_highest_unit);\n }\n\n if (obj.m_b && print)\n {\n if (print_spe)\n {\n str << spe;\n }\n str << obj.m_b << \"B\";\n }\n return str;\n}\n\ntemplate<typename T>\nostream&\noperator<<(ostream &ostr, const fastuidraw::range_type<T> &obj)\n{\n ostr << \"[\" << obj.m_begin << \", \" << obj.m_end << \")\";\n return ostr;\n}\n\ntemplate<typename T, size_t N>\nostream&\noperator<<(ostream &ostr, const fastuidraw::vecN<T, N> &obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < N; ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nostream&\noperator<<(ostream &ostr, fastuidraw::c_array<T> obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < obj.size(); ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nostream&\noperator<<(ostream &ostr, const vector<T> &obj)\n{\n ostr << \"(\";\n for(size_t i = 0; i < obj.size(); ++i)\n {\n if (i != 0)\n {\n ostr << \", \";\n }\n ostr << obj[i];\n }\n ostr << \")\";\n return ostr;\n}\n\ntemplate<typename T>\nostream&\noperator<<(ostream &str, const fastuidraw::BoundingBox<T> &obj)\n{\n if (obj.empty())\n {\n str << \"{}\";\n }\n else\n {\n str << \"[\" << obj.min_point() << \" -- \" << obj.max_point() << \"]\";\n }\n return str;\n}\n}\n\ntemplate<typename T>\nfastuidraw::glsl::ShaderSource&\noperator<<(fastuidraw::glsl::ShaderSource &src, const T &obj)\n{\n std::ostringstream str;\n str << obj;\n src.add_source(str.str().c_str(), fastuidraw::glsl::ShaderSource::from_string);\n return src;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Licensed to Qualys, Inc. (QUALYS) under one or more\n\/\/ contributor license agreements. See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ QUALYS licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file\n\/\/\/ @brief IronBee &dso; Dynamic Shared Object Tests\n\/\/\/\n\/\/\/ @author Nick LeRoy <nleroy@qualys.com>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <ironbee\/hash.h>\n\n#include \"ironbee_config_auto.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"gtest\/gtest-spi.h\"\n\n#include <ironbee\/types.h>\n#include <ironbee\/dso.h>\n\n#include \"test_util_dso.h\"\n\n#include <stdexcept>\n\n\nclass TestIBUtilDso : public ::testing::Test\n{\npublic:\n TestIBUtilDso( ) : m_dso(NULL) { };\n\n ~TestIBUtilDso( )\n {\n DsoClose( );\n }\n\n virtual void SetUp()\n {\n ib_status_t rc = ib_mpool_create(&m_pool, NULL, NULL);\n if (rc != IB_OK) {\n throw std::runtime_error(\"Could not initialize mpool.\");\n }\n }\n\n virtual void TearDown()\n {\n ib_mpool_destroy(m_pool);\n }\n\n ib_status_t DsoOpen(const char *file)\n {\n return ib_dso_open(&m_dso, file, m_pool);\n }\n ib_status_t DsoClose( void )\n {\n ib_status_t rc = IB_OK;\n if (m_dso != NULL) {\n rc = ib_dso_close(m_dso);\n m_dso = NULL;\n }\n return rc;\n }\n ib_status_t DsoSymFind(const char *name, ib_dso_sym_t **sym)\n {\n return ib_dso_sym_find(sym, m_dso, name);\n }\n\nprotected:\n ib_mpool_t *m_pool;\n ib_dso_t *m_dso;\n};\n\nTEST_F(TestIBUtilDso, test_open)\n{\n {\n SCOPED_TRACE(\"test_open: normal\");\n ib_status_t rc;\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n }\n\n {\n SCOPED_TRACE(\"test_open: does not exist\");\n ib_status_t rc;\n rc = DsoOpen(\".libs\/libtest_doesnotexist.so\");\n ASSERT_EQ(IB_EINVAL, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n }\n \n}\n\nTEST_F(TestIBUtilDso, test_sym_find)\n{\n ib_status_t rc;\n ib_dso_sym_t *sym;\n\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n {\n SCOPED_TRACE(\"test_sym_find: does not exist\");\n rc = DsoSymFind(\"does_not_exit\", &sym);\n ASSERT_EQ(IB_ENOENT, rc);\n }\n\n {\n SCOPED_TRACE(\"test_sym_find: normal\");\n rc = DsoSymFind(\"ib_test_util_dso_getfns\", &sym);\n ASSERT_EQ(IB_OK, rc);\n }\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n}\n\nTEST_F(TestIBUtilDso, test_lib)\n{\n ib_status_t rc;\n ib_dso_sym_t *sym;\n ib_test_dso_getfns_fn_t getfns;\n ib_test_util_dso_fns_t *fns;\n ib_test_util_dso_data_t *data;\n int num;\n const char *str;\n\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoSymFind(\"ib_test_util_dso_getfns\", &sym);\n ASSERT_EQ(IB_OK, rc);\n\n getfns = (ib_test_dso_getfns_fn_t)sym;\n rc = getfns(&fns);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_create(&data, m_pool, 3);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(3, num);\n\n rc = fns->fn_setnum(data, 666);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(666, num);\n\n rc = fns->fn_getstr(data, &str);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_STREQ(NULL, str);\n\n rc = fns->fn_setstr(data, \"abc123\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getstr(data, &str);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_STREQ(\"abc123\", str);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(666, num);\n\n rc = fns->fn_destroy(data);\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n}\n<commit_msg>test_util_dso.cc: Strip trailing whitespace.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Licensed to Qualys, Inc. (QUALYS) under one or more\n\/\/ contributor license agreements. See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ QUALYS licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file\n\/\/\/ @brief IronBee &dso; Dynamic Shared Object Tests\n\/\/\/\n\/\/\/ @author Nick LeRoy <nleroy@qualys.com>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <ironbee\/hash.h>\n\n#include \"ironbee_config_auto.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"gtest\/gtest-spi.h\"\n\n#include <ironbee\/types.h>\n#include <ironbee\/dso.h>\n\n#include \"test_util_dso.h\"\n\n#include <stdexcept>\n\n\nclass TestIBUtilDso : public ::testing::Test\n{\npublic:\n TestIBUtilDso( ) : m_dso(NULL) { };\n\n ~TestIBUtilDso( )\n {\n DsoClose( );\n }\n\n virtual void SetUp()\n {\n ib_status_t rc = ib_mpool_create(&m_pool, NULL, NULL);\n if (rc != IB_OK) {\n throw std::runtime_error(\"Could not initialize mpool.\");\n }\n }\n\n virtual void TearDown()\n {\n ib_mpool_destroy(m_pool);\n }\n\n ib_status_t DsoOpen(const char *file)\n {\n return ib_dso_open(&m_dso, file, m_pool);\n }\n ib_status_t DsoClose( void )\n {\n ib_status_t rc = IB_OK;\n if (m_dso != NULL) {\n rc = ib_dso_close(m_dso);\n m_dso = NULL;\n }\n return rc;\n }\n ib_status_t DsoSymFind(const char *name, ib_dso_sym_t **sym)\n {\n return ib_dso_sym_find(sym, m_dso, name);\n }\n\nprotected:\n ib_mpool_t *m_pool;\n ib_dso_t *m_dso;\n};\n\nTEST_F(TestIBUtilDso, test_open)\n{\n {\n SCOPED_TRACE(\"test_open: normal\");\n ib_status_t rc;\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n }\n\n {\n SCOPED_TRACE(\"test_open: does not exist\");\n ib_status_t rc;\n rc = DsoOpen(\".libs\/libtest_doesnotexist.so\");\n ASSERT_EQ(IB_EINVAL, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n }\n\n}\n\nTEST_F(TestIBUtilDso, test_sym_find)\n{\n ib_status_t rc;\n ib_dso_sym_t *sym;\n\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n {\n SCOPED_TRACE(\"test_sym_find: does not exist\");\n rc = DsoSymFind(\"does_not_exit\", &sym);\n ASSERT_EQ(IB_ENOENT, rc);\n }\n\n {\n SCOPED_TRACE(\"test_sym_find: normal\");\n rc = DsoSymFind(\"ib_test_util_dso_getfns\", &sym);\n ASSERT_EQ(IB_OK, rc);\n }\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n}\n\nTEST_F(TestIBUtilDso, test_lib)\n{\n ib_status_t rc;\n ib_dso_sym_t *sym;\n ib_test_dso_getfns_fn_t getfns;\n ib_test_util_dso_fns_t *fns;\n ib_test_util_dso_data_t *data;\n int num;\n const char *str;\n\n rc = DsoOpen(\".libs\/libtest_util_dso_lib.so\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoSymFind(\"ib_test_util_dso_getfns\", &sym);\n ASSERT_EQ(IB_OK, rc);\n\n getfns = (ib_test_dso_getfns_fn_t)sym;\n rc = getfns(&fns);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_create(&data, m_pool, 3);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(3, num);\n\n rc = fns->fn_setnum(data, 666);\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(666, num);\n\n rc = fns->fn_getstr(data, &str);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_STREQ(NULL, str);\n\n rc = fns->fn_setstr(data, \"abc123\");\n ASSERT_EQ(IB_OK, rc);\n\n rc = fns->fn_getstr(data, &str);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_STREQ(\"abc123\", str);\n\n rc = fns->fn_getnum(data, &num);\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(666, num);\n\n rc = fns->fn_destroy(data);\n ASSERT_EQ(IB_OK, rc);\n\n rc = DsoClose( );\n ASSERT_EQ(IB_OK, rc);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019-2020 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/mnauth.h>\n\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_utils.h>\n#include <masternode\/activemasternode.h>\n#include <masternode\/masternode-meta.h>\n#include <masternode\/masternode-sync.h>\n#include <net.h>\n#include <net_processing.h>\n#include <netmessagemaker.h>\n#include <validation.h>\n\n#include <unordered_set>\n\nvoid CMNAuth::PushMNAUTH(CNode* pnode, CConnman& connman)\n{\n if (!fMasternodeMode || activeMasternodeInfo.proTxHash.IsNull()) {\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n if (pnode->receivedMNAuthChallenge.IsNull()) {\n return;\n }\n \/\/ We include fInbound in signHash to forbid interchanging of challenges by a man in the middle (MITM). This way\n \/\/ we protect ourselves against MITM in this form:\n \/\/ node1 <- Eve -> node2\n \/\/ It does not protect against:\n \/\/ node1 -> Eve -> node2\n \/\/ This is ok as we only use MNAUTH as a DoS protection and not for sensitive stuff\n signHash = ::SerializeHash(std::make_tuple(*activeMasternodeInfo.blsPubKeyOperator, pnode->receivedMNAuthChallenge, pnode->fInbound));\n }\n\n CMNAuth mnauth;\n mnauth.proRegTxHash = activeMasternodeInfo.proTxHash;\n mnauth.sig = activeMasternodeInfo.blsKeyOperator->Sign(signHash);\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Sending MNAUTH, peer=%d\\n\", __func__, pnode->GetId());\n\n connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::MNAUTH, mnauth));\n}\n\nvoid CMNAuth::ProcessMessage(CNode* pnode, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)\n{\n if (!masternodeSync.IsBlockchainSynced()) {\n \/\/ we can't verify MNAUTH messages when we don't have the latest MN list\n return;\n }\n\n if (strCommand == NetMsgType::MNAUTH) {\n CMNAuth mnauth;\n vRecv >> mnauth;\n\n \/\/ only one MNAUTH allowed\n bool fAlreadyHaveMNAUTH = false;\n {\n LOCK(pnode->cs_mnauth);\n fAlreadyHaveMNAUTH = !pnode->verifiedProRegTxHash.IsNull();\n }\n if (fAlreadyHaveMNAUTH) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"duplicate mnauth\");\n return;\n }\n\n if ((~pnode->nServices) & NODE_NETWORK)) {\n \/\/ NODE_NETWORK bit is missing in node's services\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"mnauth from a node with invalid services\");\n return;\n }\n\n if (mnauth.proRegTxHash.IsNull()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"empty mnauth proRegTxHash\");\n return;\n }\n\n if (!mnauth.sig.IsValid()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"invalid mnauth signature\");\n return;\n }\n\n auto mnList = deterministicMNManager->GetListAtChainTip();\n auto dmn = mnList.GetMN(mnauth.proRegTxHash);\n if (!dmn) {\n LOCK(cs_main);\n \/\/ in case node was unlucky and not up to date, just let it be connected as a regular node, which gives it\n \/\/ a chance to get up-to-date and thus realize that it's not a MN anymore. We still give it a\n \/\/ low DoS score.\n Misbehaving(pnode->GetId(), 10, \"missing mnauth masternode\");\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n \/\/ See comment in PushMNAUTH (fInbound is negated here as we're on the other side of the connection)\n signHash = ::SerializeHash(std::make_tuple(dmn->pdmnState->pubKeyOperator, pnode->sentMNAuthChallenge, !pnode->fInbound));\n }\n\n if (!mnauth.sig.VerifyInsecure(dmn->pdmnState->pubKeyOperator.Get(), signHash)) {\n LOCK(cs_main);\n \/\/ Same as above, MN seems to not know its fate yet, so give it a chance to update. If this is a\n \/\/ malicious node (DoSing us), it'll get banned soon.\n Misbehaving(pnode->GetId(), 10, \"mnauth signature verification failed\");\n return;\n }\n\n if (!pnode->fInbound) {\n mmetaman.GetMetaInfo(mnauth.proRegTxHash)->SetLastOutboundSuccess(GetAdjustedTime());\n if (pnode->fMasternodeProbe) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode probe successful for %s, disconnecting. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n return;\n }\n }\n\n connman.ForEachNode([&](CNode* pnode2) {\n if (pnode->fDisconnect) {\n \/\/ we've already disconnected the new peer\n return;\n }\n\n if (pnode2->verifiedProRegTxHash == mnauth.proRegTxHash) {\n if (fMasternodeMode) {\n auto deterministicOutbound = llmq::CLLMQUtils::DeterministicOutboundConnection(activeMasternodeInfo.proTxHash, mnauth.proRegTxHash);\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, deterministicOutbound=%s. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), deterministicOutbound.ToString(), pnode->GetId());\n if (deterministicOutbound == activeMasternodeInfo.proTxHash) {\n if (pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old inbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new inbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n } else {\n if (!pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old outbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (!pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new outbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n } else {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, dropping new connection. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n });\n\n if (pnode->fDisconnect) {\n return;\n }\n\n {\n LOCK(pnode->cs_mnauth);\n pnode->verifiedProRegTxHash = mnauth.proRegTxHash;\n pnode->verifiedPubKeyHash = dmn->pdmnState->pubKeyOperator.GetHash();\n }\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Valid MNAUTH for %s, peer=%d\\n\", __func__, mnauth.proRegTxHash.ToString(), pnode->GetId());\n }\n}\n\nvoid CMNAuth::NotifyMasternodeListChanged(bool undo, const CDeterministicMNList& oldMNList, const CDeterministicMNListDiff& diff, CConnman& connman)\n{\n \/\/ we're only interested in updated\/removed MNs. Added MNs are of no interest for us\n if (diff.updatedMNs.empty() && diff.removedMns.empty()) {\n return;\n }\n\n connman.ForEachNode([&](CNode* pnode) {\n LOCK(pnode->cs_mnauth);\n if (pnode->verifiedProRegTxHash.IsNull()) {\n return;\n }\n auto verifiedDmn = oldMNList.GetMN(pnode->verifiedProRegTxHash);\n if (!verifiedDmn) {\n return;\n }\n bool doRemove = false;\n if (diff.removedMns.count(verifiedDmn->GetInternalId())) {\n doRemove = true;\n } else {\n auto it = diff.updatedMNs.find(verifiedDmn->GetInternalId());\n if (it != diff.updatedMNs.end()) {\n if ((it->second.fields & CDeterministicMNStateDiff::Field_pubKeyOperator) && it->second.state.pubKeyOperator.GetHash() != pnode->verifiedPubKeyHash) {\n doRemove = true;\n }\n }\n }\n\n if (doRemove) {\n LogPrint(BCLog::NET, \"CMNAuth::NotifyMasternodeListChanged -- Disconnecting MN %s due to key changed\/removed, peer=%d\\n\",\n pnode->verifiedProRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n });\n}\n<commit_msg>compile<commit_after>\/\/ Copyright (c) 2019-2020 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/mnauth.h>\n\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_utils.h>\n#include <masternode\/activemasternode.h>\n#include <masternode\/masternode-meta.h>\n#include <masternode\/masternode-sync.h>\n#include <net.h>\n#include <net_processing.h>\n#include <netmessagemaker.h>\n#include <validation.h>\n\n#include <unordered_set>\n\nvoid CMNAuth::PushMNAUTH(CNode* pnode, CConnman& connman)\n{\n if (!fMasternodeMode || activeMasternodeInfo.proTxHash.IsNull()) {\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n if (pnode->receivedMNAuthChallenge.IsNull()) {\n return;\n }\n \/\/ We include fInbound in signHash to forbid interchanging of challenges by a man in the middle (MITM). This way\n \/\/ we protect ourselves against MITM in this form:\n \/\/ node1 <- Eve -> node2\n \/\/ It does not protect against:\n \/\/ node1 -> Eve -> node2\n \/\/ This is ok as we only use MNAUTH as a DoS protection and not for sensitive stuff\n signHash = ::SerializeHash(std::make_tuple(*activeMasternodeInfo.blsPubKeyOperator, pnode->receivedMNAuthChallenge, pnode->fInbound));\n }\n\n CMNAuth mnauth;\n mnauth.proRegTxHash = activeMasternodeInfo.proTxHash;\n mnauth.sig = activeMasternodeInfo.blsKeyOperator->Sign(signHash);\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Sending MNAUTH, peer=%d\\n\", __func__, pnode->GetId());\n\n connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::MNAUTH, mnauth));\n}\n\nvoid CMNAuth::ProcessMessage(CNode* pnode, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)\n{\n if (!masternodeSync.IsBlockchainSynced()) {\n \/\/ we can't verify MNAUTH messages when we don't have the latest MN list\n return;\n }\n\n if (strCommand == NetMsgType::MNAUTH) {\n CMNAuth mnauth;\n vRecv >> mnauth;\n\n \/\/ only one MNAUTH allowed\n bool fAlreadyHaveMNAUTH = false;\n {\n LOCK(pnode->cs_mnauth);\n fAlreadyHaveMNAUTH = !pnode->verifiedProRegTxHash.IsNull();\n }\n if (fAlreadyHaveMNAUTH) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"duplicate mnauth\");\n return;\n }\n\n if ((~pnode->nServices) & NODE_NETWORK) {\n \/\/ NODE_NETWORK bit is missing in node's services\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"mnauth from a node with invalid services\");\n return;\n }\n\n if (mnauth.proRegTxHash.IsNull()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"empty mnauth proRegTxHash\");\n return;\n }\n\n if (!mnauth.sig.IsValid()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"invalid mnauth signature\");\n return;\n }\n\n auto mnList = deterministicMNManager->GetListAtChainTip();\n auto dmn = mnList.GetMN(mnauth.proRegTxHash);\n if (!dmn) {\n LOCK(cs_main);\n \/\/ in case node was unlucky and not up to date, just let it be connected as a regular node, which gives it\n \/\/ a chance to get up-to-date and thus realize that it's not a MN anymore. We still give it a\n \/\/ low DoS score.\n Misbehaving(pnode->GetId(), 10, \"missing mnauth masternode\");\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n \/\/ See comment in PushMNAUTH (fInbound is negated here as we're on the other side of the connection)\n signHash = ::SerializeHash(std::make_tuple(dmn->pdmnState->pubKeyOperator, pnode->sentMNAuthChallenge, !pnode->fInbound));\n }\n\n if (!mnauth.sig.VerifyInsecure(dmn->pdmnState->pubKeyOperator.Get(), signHash)) {\n LOCK(cs_main);\n \/\/ Same as above, MN seems to not know its fate yet, so give it a chance to update. If this is a\n \/\/ malicious node (DoSing us), it'll get banned soon.\n Misbehaving(pnode->GetId(), 10, \"mnauth signature verification failed\");\n return;\n }\n\n if (!pnode->fInbound) {\n mmetaman.GetMetaInfo(mnauth.proRegTxHash)->SetLastOutboundSuccess(GetAdjustedTime());\n if (pnode->fMasternodeProbe) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode probe successful for %s, disconnecting. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n return;\n }\n }\n\n connman.ForEachNode([&](CNode* pnode2) {\n if (pnode->fDisconnect) {\n \/\/ we've already disconnected the new peer\n return;\n }\n\n if (pnode2->verifiedProRegTxHash == mnauth.proRegTxHash) {\n if (fMasternodeMode) {\n auto deterministicOutbound = llmq::CLLMQUtils::DeterministicOutboundConnection(activeMasternodeInfo.proTxHash, mnauth.proRegTxHash);\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, deterministicOutbound=%s. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), deterministicOutbound.ToString(), pnode->GetId());\n if (deterministicOutbound == activeMasternodeInfo.proTxHash) {\n if (pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old inbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new inbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n } else {\n if (!pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old outbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (!pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new outbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n } else {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, dropping new connection. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n });\n\n if (pnode->fDisconnect) {\n return;\n }\n\n {\n LOCK(pnode->cs_mnauth);\n pnode->verifiedProRegTxHash = mnauth.proRegTxHash;\n pnode->verifiedPubKeyHash = dmn->pdmnState->pubKeyOperator.GetHash();\n }\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Valid MNAUTH for %s, peer=%d\\n\", __func__, mnauth.proRegTxHash.ToString(), pnode->GetId());\n }\n}\n\nvoid CMNAuth::NotifyMasternodeListChanged(bool undo, const CDeterministicMNList& oldMNList, const CDeterministicMNListDiff& diff, CConnman& connman)\n{\n \/\/ we're only interested in updated\/removed MNs. Added MNs are of no interest for us\n if (diff.updatedMNs.empty() && diff.removedMns.empty()) {\n return;\n }\n\n connman.ForEachNode([&](CNode* pnode) {\n LOCK(pnode->cs_mnauth);\n if (pnode->verifiedProRegTxHash.IsNull()) {\n return;\n }\n auto verifiedDmn = oldMNList.GetMN(pnode->verifiedProRegTxHash);\n if (!verifiedDmn) {\n return;\n }\n bool doRemove = false;\n if (diff.removedMns.count(verifiedDmn->GetInternalId())) {\n doRemove = true;\n } else {\n auto it = diff.updatedMNs.find(verifiedDmn->GetInternalId());\n if (it != diff.updatedMNs.end()) {\n if ((it->second.fields & CDeterministicMNStateDiff::Field_pubKeyOperator) && it->second.state.pubKeyOperator.GetHash() != pnode->verifiedPubKeyHash) {\n doRemove = true;\n }\n }\n }\n\n if (doRemove) {\n LogPrint(BCLog::NET, \"CMNAuth::NotifyMasternodeListChanged -- Disconnecting MN %s due to key changed\/removed, peer=%d\\n\",\n pnode->verifiedProRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019-2020 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/mnauth.h>\n\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_utils.h>\n#include <masternode\/activemasternode.h>\n#include <masternode\/masternode-meta.h>\n#include <masternode\/masternode-sync.h>\n#include <net.h>\n#include <net_processing.h>\n#include <netmessagemaker.h>\n#include <validation.h>\n\n#include <unordered_set>\n\nvoid CMNAuth::PushMNAUTH(CNode* pnode, CConnman& connman)\n{\n if (!fMasternodeMode || activeMasternodeInfo.proTxHash.IsNull()) {\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n if (pnode->receivedMNAuthChallenge.IsNull()) {\n return;\n }\n \/\/ We include fInbound in signHash to forbid interchanging of challenges by a man in the middle (MITM). This way\n \/\/ we protect ourselves against MITM in this form:\n \/\/ node1 <- Eve -> node2\n \/\/ It does not protect against:\n \/\/ node1 -> Eve -> node2\n \/\/ This is ok as we only use MNAUTH as a DoS protection and not for sensitive stuff\n signHash = ::SerializeHash(std::make_tuple(*activeMasternodeInfo.blsPubKeyOperator, pnode->receivedMNAuthChallenge, pnode->fInbound));\n }\n\n CMNAuth mnauth;\n mnauth.proRegTxHash = activeMasternodeInfo.proTxHash;\n mnauth.sig = activeMasternodeInfo.blsKeyOperator->Sign(signHash);\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Sending MNAUTH, peer=%d\\n\", __func__, pnode->GetId());\n\n connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::MNAUTH, mnauth));\n}\n\nvoid CMNAuth::ProcessMessage(CNode* pnode, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)\n{\n if (!masternodeSync.IsBlockchainSynced()) {\n \/\/ we can't verify MNAUTH messages when we don't have the latest MN list\n return;\n }\n\n if (strCommand == NetMsgType::MNAUTH) {\n CMNAuth mnauth;\n vRecv >> mnauth;\n\n \/\/ only one MNAUTH allowed\n bool fAlreadyHaveMNAUTH = false;\n {\n LOCK(pnode->cs_mnauth);\n fAlreadyHaveMNAUTH = !pnode->verifiedProRegTxHash.IsNull();\n }\n if (fAlreadyHaveMNAUTH) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"duplicate mnauth\");\n return;\n }\n\n if ((~pnode->nServices) & (NODE_NETWORK | NODE_BLOOM)) {\n \/\/ either NODE_NETWORK or NODE_BLOOM bit is missing in node's services\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"mnauth from a node with invalid services\");\n return;\n }\n\n if (mnauth.proRegTxHash.IsNull()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"empty mnauth proRegTxHash\");\n return;\n }\n\n if (!mnauth.sig.IsValid()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"invalid mnauth signature\");\n return;\n }\n\n auto mnList = deterministicMNManager->GetListAtChainTip();\n auto dmn = mnList.GetMN(mnauth.proRegTxHash);\n if (!dmn) {\n LOCK(cs_main);\n \/\/ in case node was unlucky and not up to date, just let it be connected as a regular node, which gives it\n \/\/ a chance to get up-to-date and thus realize that it's not a MN anymore. We still give it a\n \/\/ low DoS score.\n Misbehaving(pnode->GetId(), 10, \"missing mnauth masternode\");\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n \/\/ See comment in PushMNAUTH (fInbound is negated here as we're on the other side of the connection)\n signHash = ::SerializeHash(std::make_tuple(dmn->pdmnState->pubKeyOperator, pnode->sentMNAuthChallenge, !pnode->fInbound));\n }\n\n if (!mnauth.sig.VerifyInsecure(dmn->pdmnState->pubKeyOperator.Get(), signHash)) {\n LOCK(cs_main);\n \/\/ Same as above, MN seems to not know its fate yet, so give it a chance to update. If this is a\n \/\/ malicious node (DoSing us), it'll get banned soon.\n Misbehaving(pnode->GetId(), 10, \"mnauth signature verification failed\");\n return;\n }\n\n if (!pnode->fInbound) {\n mmetaman.GetMetaInfo(mnauth.proRegTxHash)->SetLastOutboundSuccess(GetAdjustedTime());\n if (pnode->fMasternodeProbe) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode probe successful for %s, disconnecting. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n return;\n }\n }\n\n connman.ForEachNode([&](CNode* pnode2) {\n if (pnode->fDisconnect) {\n \/\/ we've already disconnected the new peer\n return;\n }\n\n if (pnode2->verifiedProRegTxHash == mnauth.proRegTxHash) {\n if (fMasternodeMode) {\n auto deterministicOutbound = llmq::CLLMQUtils::DeterministicOutboundConnection(activeMasternodeInfo.proTxHash, mnauth.proRegTxHash);\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, deterministicOutbound=%s. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), deterministicOutbound.ToString(), pnode->GetId());\n if (deterministicOutbound == activeMasternodeInfo.proTxHash) {\n if (pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old inbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new inbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n } else {\n if (!pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old outbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (!pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new outbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n } else {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, dropping new connection. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n });\n\n if (pnode->fDisconnect) {\n return;\n }\n\n {\n LOCK(pnode->cs_mnauth);\n pnode->verifiedProRegTxHash = mnauth.proRegTxHash;\n pnode->verifiedPubKeyHash = dmn->pdmnState->pubKeyOperator.GetHash();\n }\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Valid MNAUTH for %s, peer=%d\\n\", __func__, mnauth.proRegTxHash.ToString(), pnode->GetId());\n }\n}\n\nvoid CMNAuth::NotifyMasternodeListChanged(bool undo, const CDeterministicMNList& oldMNList, const CDeterministicMNListDiff& diff, CConnman& connman)\n{\n \/\/ we're only interested in updated\/removed MNs. Added MNs are of no interest for us\n if (diff.updatedMNs.empty() && diff.removedMns.empty()) {\n return;\n }\n\n connman.ForEachNode([&](CNode* pnode) {\n LOCK(pnode->cs_mnauth);\n if (pnode->verifiedProRegTxHash.IsNull()) {\n return;\n }\n auto verifiedDmn = oldMNList.GetMN(pnode->verifiedProRegTxHash);\n if (!verifiedDmn) {\n return;\n }\n bool doRemove = false;\n if (diff.removedMns.count(verifiedDmn->GetInternalId())) {\n doRemove = true;\n } else {\n auto it = diff.updatedMNs.find(verifiedDmn->GetInternalId());\n if (it != diff.updatedMNs.end()) {\n if ((it->second.fields & CDeterministicMNStateDiff::Field_pubKeyOperator) && it->second.state.pubKeyOperator.GetHash() != pnode->verifiedPubKeyHash) {\n doRemove = true;\n }\n }\n }\n\n if (doRemove) {\n LogPrint(BCLog::NET, \"CMNAuth::NotifyMasternodeListChanged -- Disconnecting MN %s due to key changed\/removed, peer=%d\\n\",\n pnode->verifiedProRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n });\n}\n<commit_msg>remove bloom requirement for mn<commit_after>\/\/ Copyright (c) 2019-2020 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/mnauth.h>\n\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_utils.h>\n#include <masternode\/activemasternode.h>\n#include <masternode\/masternode-meta.h>\n#include <masternode\/masternode-sync.h>\n#include <net.h>\n#include <net_processing.h>\n#include <netmessagemaker.h>\n#include <validation.h>\n\n#include <unordered_set>\n\nvoid CMNAuth::PushMNAUTH(CNode* pnode, CConnman& connman)\n{\n if (!fMasternodeMode || activeMasternodeInfo.proTxHash.IsNull()) {\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n if (pnode->receivedMNAuthChallenge.IsNull()) {\n return;\n }\n \/\/ We include fInbound in signHash to forbid interchanging of challenges by a man in the middle (MITM). This way\n \/\/ we protect ourselves against MITM in this form:\n \/\/ node1 <- Eve -> node2\n \/\/ It does not protect against:\n \/\/ node1 -> Eve -> node2\n \/\/ This is ok as we only use MNAUTH as a DoS protection and not for sensitive stuff\n signHash = ::SerializeHash(std::make_tuple(*activeMasternodeInfo.blsPubKeyOperator, pnode->receivedMNAuthChallenge, pnode->fInbound));\n }\n\n CMNAuth mnauth;\n mnauth.proRegTxHash = activeMasternodeInfo.proTxHash;\n mnauth.sig = activeMasternodeInfo.blsKeyOperator->Sign(signHash);\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Sending MNAUTH, peer=%d\\n\", __func__, pnode->GetId());\n\n connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::MNAUTH, mnauth));\n}\n\nvoid CMNAuth::ProcessMessage(CNode* pnode, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)\n{\n if (!masternodeSync.IsBlockchainSynced()) {\n \/\/ we can't verify MNAUTH messages when we don't have the latest MN list\n return;\n }\n\n if (strCommand == NetMsgType::MNAUTH) {\n CMNAuth mnauth;\n vRecv >> mnauth;\n\n \/\/ only one MNAUTH allowed\n bool fAlreadyHaveMNAUTH = false;\n {\n LOCK(pnode->cs_mnauth);\n fAlreadyHaveMNAUTH = !pnode->verifiedProRegTxHash.IsNull();\n }\n if (fAlreadyHaveMNAUTH) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"duplicate mnauth\");\n return;\n }\n\n if ((~pnode->nServices) & NODE_NETWORK)) {\n \/\/ NODE_NETWORK bit is missing in node's services\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"mnauth from a node with invalid services\");\n return;\n }\n\n if (mnauth.proRegTxHash.IsNull()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"empty mnauth proRegTxHash\");\n return;\n }\n\n if (!mnauth.sig.IsValid()) {\n LOCK(cs_main);\n Misbehaving(pnode->GetId(), 100, \"invalid mnauth signature\");\n return;\n }\n\n auto mnList = deterministicMNManager->GetListAtChainTip();\n auto dmn = mnList.GetMN(mnauth.proRegTxHash);\n if (!dmn) {\n LOCK(cs_main);\n \/\/ in case node was unlucky and not up to date, just let it be connected as a regular node, which gives it\n \/\/ a chance to get up-to-date and thus realize that it's not a MN anymore. We still give it a\n \/\/ low DoS score.\n Misbehaving(pnode->GetId(), 10, \"missing mnauth masternode\");\n return;\n }\n\n uint256 signHash;\n {\n LOCK(pnode->cs_mnauth);\n \/\/ See comment in PushMNAUTH (fInbound is negated here as we're on the other side of the connection)\n signHash = ::SerializeHash(std::make_tuple(dmn->pdmnState->pubKeyOperator, pnode->sentMNAuthChallenge, !pnode->fInbound));\n }\n\n if (!mnauth.sig.VerifyInsecure(dmn->pdmnState->pubKeyOperator.Get(), signHash)) {\n LOCK(cs_main);\n \/\/ Same as above, MN seems to not know its fate yet, so give it a chance to update. If this is a\n \/\/ malicious node (DoSing us), it'll get banned soon.\n Misbehaving(pnode->GetId(), 10, \"mnauth signature verification failed\");\n return;\n }\n\n if (!pnode->fInbound) {\n mmetaman.GetMetaInfo(mnauth.proRegTxHash)->SetLastOutboundSuccess(GetAdjustedTime());\n if (pnode->fMasternodeProbe) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode probe successful for %s, disconnecting. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n return;\n }\n }\n\n connman.ForEachNode([&](CNode* pnode2) {\n if (pnode->fDisconnect) {\n \/\/ we've already disconnected the new peer\n return;\n }\n\n if (pnode2->verifiedProRegTxHash == mnauth.proRegTxHash) {\n if (fMasternodeMode) {\n auto deterministicOutbound = llmq::CLLMQUtils::DeterministicOutboundConnection(activeMasternodeInfo.proTxHash, mnauth.proRegTxHash);\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, deterministicOutbound=%s. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), deterministicOutbound.ToString(), pnode->GetId());\n if (deterministicOutbound == activeMasternodeInfo.proTxHash) {\n if (pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old inbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new inbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n } else {\n if (!pnode2->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping old outbound, peer=%d\\n\", pnode2->GetId());\n pnode2->fDisconnect = true;\n } else if (!pnode->fInbound) {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- dropping new outbound, peer=%d\\n\", pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n } else {\n LogPrint(BCLog::NET, \"CMNAuth::ProcessMessage -- Masternode %s has already verified as peer %d, dropping new connection. peer=%d\\n\",\n mnauth.proRegTxHash.ToString(), pnode2->GetId(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n }\n });\n\n if (pnode->fDisconnect) {\n return;\n }\n\n {\n LOCK(pnode->cs_mnauth);\n pnode->verifiedProRegTxHash = mnauth.proRegTxHash;\n pnode->verifiedPubKeyHash = dmn->pdmnState->pubKeyOperator.GetHash();\n }\n\n LogPrint(BCLog::NET, \"CMNAuth::%s -- Valid MNAUTH for %s, peer=%d\\n\", __func__, mnauth.proRegTxHash.ToString(), pnode->GetId());\n }\n}\n\nvoid CMNAuth::NotifyMasternodeListChanged(bool undo, const CDeterministicMNList& oldMNList, const CDeterministicMNListDiff& diff, CConnman& connman)\n{\n \/\/ we're only interested in updated\/removed MNs. Added MNs are of no interest for us\n if (diff.updatedMNs.empty() && diff.removedMns.empty()) {\n return;\n }\n\n connman.ForEachNode([&](CNode* pnode) {\n LOCK(pnode->cs_mnauth);\n if (pnode->verifiedProRegTxHash.IsNull()) {\n return;\n }\n auto verifiedDmn = oldMNList.GetMN(pnode->verifiedProRegTxHash);\n if (!verifiedDmn) {\n return;\n }\n bool doRemove = false;\n if (diff.removedMns.count(verifiedDmn->GetInternalId())) {\n doRemove = true;\n } else {\n auto it = diff.updatedMNs.find(verifiedDmn->GetInternalId());\n if (it != diff.updatedMNs.end()) {\n if ((it->second.fields & CDeterministicMNStateDiff::Field_pubKeyOperator) && it->second.state.pubKeyOperator.GetHash() != pnode->verifiedPubKeyHash) {\n doRemove = true;\n }\n }\n }\n\n if (doRemove) {\n LogPrint(BCLog::NET, \"CMNAuth::NotifyMasternodeListChanged -- Disconnecting MN %s due to key changed\/removed, peer=%d\\n\",\n pnode->verifiedProRegTxHash.ToString(), pnode->GetId());\n pnode->fDisconnect = true;\n }\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * libjson-rpc-cpp\n *************************************************************************\n * @file httpserver.cpp\n * @date 31.12.2012\n * @author Peter Spiess-Knafl <dev@spiessknafl.at>\n * @license See attached LICENSE.txt\n ************************************************************************\/\n\n#include \"httpserver.h\"\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <jsonrpccpp\/common\/specificationparser.h>\n#include <sstream>\n\nusing namespace jsonrpc;\nusing namespace std;\n\n#define BUFFERSIZE 65536\n\nstruct mhd_coninfo {\n struct MHD_PostProcessor *postprocessor;\n MHD_Connection *connection;\n stringstream request;\n HttpServer *server;\n int code;\n};\n\nHttpServer::HttpServer(int port, const std::string &sslcert,\n const std::string &sslkey, int threads)\n : AbstractServerConnector(), port(port), threads(threads), running(false),\n path_sslcert(sslcert), path_sslkey(sslkey), daemon(NULL) {}\n\nHttpServer::~HttpServer() {}\n\nbool HttpServer::SetBindAddress(const std::string &addr) {\n\n bind_address.sin_family = AF_INET;\n bind_address.sin_port = htons(this->port);\n\n if (addr == \"\")\n bind_address.sin_addr.s_addr = htonl(INADDR_ANY);\n else\n inet_aton(\"127.0.0.1\", (struct in_addr *)&bind_address.sin_addr.s_addr);\n return true;\n}\n\nIClientConnectionHandler *HttpServer::GetHandler(const std::string &url) {\n if (AbstractServerConnector::GetHandler() != NULL)\n return AbstractServerConnector::GetHandler();\n map<string, IClientConnectionHandler *>::iterator it =\n this->urlhandler.find(url);\n if (it != this->urlhandler.end())\n return it->second;\n return NULL;\n}\n\nbool HttpServer::StartListening() {\n if (!this->running) {\n const bool has_epoll =\n (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES);\n const bool has_poll =\n (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES);\n unsigned int mhd_flags;\n\n SetBindAddress(\"\");\n\n if (has_epoll)\n\/\/ In MHD version 0.9.44 the flag is renamed to\n\/\/ MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY. In later versions both\n\/\/ are deprecated.\n#if defined(MHD_USE_EPOLL_INTERNALLY)\n mhd_flags = MHD_USE_EPOLL_INTERNALLY;\n#else\n mhd_flags = MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY;\n#endif\n else if (has_poll)\n mhd_flags = MHD_USE_POLL_INTERNALLY;\n if (this->path_sslcert != \"\" && this->path_sslkey != \"\") {\n try {\n SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert);\n SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey);\n\n this->daemon = MHD_start_daemon(\n MHD_USE_SSL | mhd_flags, this->port, NULL, NULL,\n HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY,\n this->sslkey.c_str(), MHD_OPTION_HTTPS_MEM_CERT,\n this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads,\n MHD_OPTION_SOCK_ADDR, &bind_address, MHD_OPTION_END);\n } catch (JsonRpcException &ex) {\n return false;\n }\n } else {\n this->daemon = MHD_start_daemon(\n mhd_flags, this->port, NULL, NULL, HttpServer::callback, this,\n MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_SOCK_ADDR,\n &bind_address, MHD_OPTION_END);\n }\n if (this->daemon != NULL)\n this->running = true;\n }\n return this->running;\n}\n\nbool HttpServer::StopListening() {\n if (this->running) {\n MHD_stop_daemon(this->daemon);\n this->running = false;\n }\n return true;\n}\n\nbool HttpServer::SendResponse(const string &response, void *addInfo) {\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(addInfo);\n struct MHD_Response *result = MHD_create_response_from_buffer(\n response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY);\n\n MHD_add_response_header(result, \"Content-Type\", \"application\/json\");\n MHD_add_response_header(result, \"Access-Control-Allow-Origin\", \"*\");\n\n int ret = MHD_queue_response(client_connection->connection,\n client_connection->code, result);\n MHD_destroy_response(result);\n return ret == MHD_YES;\n}\n\nbool HttpServer::SendOptionsResponse(void *addInfo) {\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(addInfo);\n struct MHD_Response *result =\n MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY);\n\n MHD_add_response_header(result, \"Allow\", \"POST, OPTIONS\");\n MHD_add_response_header(result, \"Access-Control-Allow-Origin\", \"*\");\n MHD_add_response_header(result, \"Access-Control-Allow-Headers\",\n \"origin, content-type, accept\");\n MHD_add_response_header(result, \"DAV\", \"1\");\n\n int ret = MHD_queue_response(client_connection->connection,\n client_connection->code, result);\n MHD_destroy_response(result);\n return ret == MHD_YES;\n}\n\nvoid HttpServer::SetUrlHandler(const string &url,\n IClientConnectionHandler *handler) {\n this->urlhandler[url] = handler;\n this->SetHandler(NULL);\n}\n\nint HttpServer::callback(void *cls, MHD_Connection *connection, const char *url,\n const char *method, const char *version,\n const char *upload_data, size_t *upload_data_size,\n void **con_cls) {\n (void)version;\n if (*con_cls == NULL) {\n struct mhd_coninfo *client_connection = new mhd_coninfo;\n client_connection->connection = connection;\n client_connection->server = static_cast<HttpServer *>(cls);\n *con_cls = client_connection;\n return MHD_YES;\n }\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(*con_cls);\n\n if (string(\"POST\") == method) {\n if (*upload_data_size != 0) {\n client_connection->request.write(upload_data, *upload_data_size);\n *upload_data_size = 0;\n return MHD_YES;\n } else {\n string response;\n IClientConnectionHandler *handler =\n client_connection->server->GetHandler(string(url));\n if (handler == NULL) {\n client_connection->code = MHD_HTTP_INTERNAL_SERVER_ERROR;\n client_connection->server->SendResponse(\n \"No client connection handler found\", client_connection);\n } else {\n client_connection->code = MHD_HTTP_OK;\n handler->HandleRequest(client_connection->request.str(), response);\n client_connection->server->SendResponse(response, client_connection);\n }\n }\n } else if (string(\"OPTIONS\") == method) {\n client_connection->code = MHD_HTTP_OK;\n client_connection->server->SendOptionsResponse(client_connection);\n } else {\n client_connection->code = MHD_HTTP_METHOD_NOT_ALLOWED;\n client_connection->server->SendResponse(\"Not allowed HTTP Method\",\n client_connection);\n }\n delete client_connection;\n *con_cls = NULL;\n\n return MHD_YES;\n}\n<commit_msg>Fix bind addr string<commit_after>\/*************************************************************************\n * libjson-rpc-cpp\n *************************************************************************\n * @file httpserver.cpp\n * @date 31.12.2012\n * @author Peter Spiess-Knafl <dev@spiessknafl.at>\n * @license See attached LICENSE.txt\n ************************************************************************\/\n\n#include \"httpserver.h\"\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <jsonrpccpp\/common\/specificationparser.h>\n#include <sstream>\n\nusing namespace jsonrpc;\nusing namespace std;\n\n#define BUFFERSIZE 65536\n\nstruct mhd_coninfo {\n struct MHD_PostProcessor *postprocessor;\n MHD_Connection *connection;\n stringstream request;\n HttpServer *server;\n int code;\n};\n\nHttpServer::HttpServer(int port, const std::string &sslcert,\n const std::string &sslkey, int threads)\n : AbstractServerConnector(), port(port), threads(threads), running(false),\n path_sslcert(sslcert), path_sslkey(sslkey), daemon(NULL) {}\n\nHttpServer::~HttpServer() {}\n\nbool HttpServer::SetBindAddress(const std::string &addr) {\n\n bind_address.sin_family = AF_INET;\n bind_address.sin_port = htons(this->port);\n\n if (addr == \"\")\n bind_address.sin_addr.s_addr = htonl(INADDR_ANY);\n else\n inet_aton(addr.c_str(), (struct in_addr *)&bind_address.sin_addr.s_addr);\n return true;\n}\n\nIClientConnectionHandler *HttpServer::GetHandler(const std::string &url) {\n if (AbstractServerConnector::GetHandler() != NULL)\n return AbstractServerConnector::GetHandler();\n map<string, IClientConnectionHandler *>::iterator it =\n this->urlhandler.find(url);\n if (it != this->urlhandler.end())\n return it->second;\n return NULL;\n}\n\nbool HttpServer::StartListening() {\n if (!this->running) {\n const bool has_epoll =\n (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES);\n const bool has_poll =\n (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES);\n unsigned int mhd_flags;\n\n SetBindAddress(\"\");\n\n if (has_epoll)\n\/\/ In MHD version 0.9.44 the flag is renamed to\n\/\/ MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY. In later versions both\n\/\/ are deprecated.\n#if defined(MHD_USE_EPOLL_INTERNALLY)\n mhd_flags = MHD_USE_EPOLL_INTERNALLY;\n#else\n mhd_flags = MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY;\n#endif\n else if (has_poll)\n mhd_flags = MHD_USE_POLL_INTERNALLY;\n if (this->path_sslcert != \"\" && this->path_sslkey != \"\") {\n try {\n SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert);\n SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey);\n\n this->daemon = MHD_start_daemon(\n MHD_USE_SSL | mhd_flags, this->port, NULL, NULL,\n HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY,\n this->sslkey.c_str(), MHD_OPTION_HTTPS_MEM_CERT,\n this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads,\n MHD_OPTION_SOCK_ADDR, &bind_address, MHD_OPTION_END);\n } catch (JsonRpcException &ex) {\n return false;\n }\n } else {\n this->daemon = MHD_start_daemon(\n mhd_flags, this->port, NULL, NULL, HttpServer::callback, this,\n MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_SOCK_ADDR,\n &bind_address, MHD_OPTION_END);\n }\n if (this->daemon != NULL)\n this->running = true;\n }\n return this->running;\n}\n\nbool HttpServer::StopListening() {\n if (this->running) {\n MHD_stop_daemon(this->daemon);\n this->running = false;\n }\n return true;\n}\n\nbool HttpServer::SendResponse(const string &response, void *addInfo) {\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(addInfo);\n struct MHD_Response *result = MHD_create_response_from_buffer(\n response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY);\n\n MHD_add_response_header(result, \"Content-Type\", \"application\/json\");\n MHD_add_response_header(result, \"Access-Control-Allow-Origin\", \"*\");\n\n int ret = MHD_queue_response(client_connection->connection,\n client_connection->code, result);\n MHD_destroy_response(result);\n return ret == MHD_YES;\n}\n\nbool HttpServer::SendOptionsResponse(void *addInfo) {\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(addInfo);\n struct MHD_Response *result =\n MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY);\n\n MHD_add_response_header(result, \"Allow\", \"POST, OPTIONS\");\n MHD_add_response_header(result, \"Access-Control-Allow-Origin\", \"*\");\n MHD_add_response_header(result, \"Access-Control-Allow-Headers\",\n \"origin, content-type, accept\");\n MHD_add_response_header(result, \"DAV\", \"1\");\n\n int ret = MHD_queue_response(client_connection->connection,\n client_connection->code, result);\n MHD_destroy_response(result);\n return ret == MHD_YES;\n}\n\nvoid HttpServer::SetUrlHandler(const string &url,\n IClientConnectionHandler *handler) {\n this->urlhandler[url] = handler;\n this->SetHandler(NULL);\n}\n\nint HttpServer::callback(void *cls, MHD_Connection *connection, const char *url,\n const char *method, const char *version,\n const char *upload_data, size_t *upload_data_size,\n void **con_cls) {\n (void)version;\n if (*con_cls == NULL) {\n struct mhd_coninfo *client_connection = new mhd_coninfo;\n client_connection->connection = connection;\n client_connection->server = static_cast<HttpServer *>(cls);\n *con_cls = client_connection;\n return MHD_YES;\n }\n struct mhd_coninfo *client_connection =\n static_cast<struct mhd_coninfo *>(*con_cls);\n\n if (string(\"POST\") == method) {\n if (*upload_data_size != 0) {\n client_connection->request.write(upload_data, *upload_data_size);\n *upload_data_size = 0;\n return MHD_YES;\n } else {\n string response;\n IClientConnectionHandler *handler =\n client_connection->server->GetHandler(string(url));\n if (handler == NULL) {\n client_connection->code = MHD_HTTP_INTERNAL_SERVER_ERROR;\n client_connection->server->SendResponse(\n \"No client connection handler found\", client_connection);\n } else {\n client_connection->code = MHD_HTTP_OK;\n handler->HandleRequest(client_connection->request.str(), response);\n client_connection->server->SendResponse(response, client_connection);\n }\n }\n } else if (string(\"OPTIONS\") == method) {\n client_connection->code = MHD_HTTP_OK;\n client_connection->server->SendOptionsResponse(client_connection);\n } else {\n client_connection->code = MHD_HTTP_METHOD_NOT_ALLOWED;\n client_connection->server->SendResponse(\"Not allowed HTTP Method\",\n client_connection);\n }\n delete client_connection;\n *con_cls = NULL;\n\n return MHD_YES;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Test Driver for Botan\n *\/\n\n#include <vector>\n#include <string>\n\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <limits>\n\n#include <botan\/botan.h>\n#include <botan\/mp_types.h>\n\nusing namespace Botan_types;\n\n#include \"getopt.h\"\n\nconst std::string VALIDATION_FILE = \"checks\/validate.dat\";\nconst std::string BIGINT_VALIDATION_FILE = \"checks\/mp_valid.dat\";\nconst std::string PK_VALIDATION_FILE = \"checks\/pk_valid.dat\";\nconst std::string EXPECTED_FAIL_FILE = \"checks\/fail.dat\";\n\nvoid benchmark(const std::string&, bool html, double seconds);\nvoid bench_pk(const std::string&, bool html, double seconds);\nu32bit bench_algo(const std::string&, double);\nint validate();\nvoid print_help();\n\nint main(int argc, char* argv[])\n {\n try\n {\n OptionParser opts(\"help|html|init=|validate|\"\n \"benchmark|bench-type=|bench-algo=|seconds=\");\n opts.parse(argv);\n\n std::string init_flags = (opts.is_set(\"init\") ? opts.value(\"init\") : \"\");\n\n Botan::InitializerOptions init_options(init_flags);\n Botan::LibraryInitializer init(init_options);\n\n if(opts.is_set(\"help\") || argc <= 1)\n { print_help(); return 1; }\n if(opts.is_set(\"validate\"))\n return validate();\n\n double seconds = 1.5;\n\n if(opts.is_set(\"seconds\"))\n {\n seconds = std::atof(opts.value(\"seconds\").c_str());\n if((seconds < 0.1 || seconds > 30) && seconds != 0)\n {\n std::cout << \"Invalid argument to --seconds\\n\";\n return 2;\n }\n }\n\n if(opts.is_set(\"bench-algo\"))\n {\n const std::string alg = opts.value(\"bench-algo\");\n u32bit found = bench_algo(alg, seconds);\n if(!found) \/\/ maybe it's a PK algorithm\n bench_pk(alg, false, seconds);\n }\n\n const bool html = opts.is_set(\"html\");\n\n if(opts.is_set(\"benchmark\"))\n benchmark(\"All\", html, seconds);\n else if(opts.is_set(\"bench-type\"))\n {\n const std::string type = opts.value(\"bench-type\");\n\n if(type == \"all\")\n benchmark(\"All\", html, seconds);\n else if(type == \"block\")\n benchmark(\"Block Cipher\", html, seconds);\n else if(type == \"stream\")\n benchmark(\"Stream Cipher\", html, seconds);\n else if(type == \"hash\")\n benchmark(\"Hash\", html, seconds);\n else if(type == \"mac\")\n benchmark(\"MAC\", html, seconds);\n else if(type == \"rng\")\n benchmark(\"RNG\", html, seconds);\n else if(type == \"pk\")\n bench_pk(\"All\", html, seconds);\n }\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Exception caught:\\n \" << e.what() << std::endl;\n return 1;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught:\\n \"\n << e.what() << std::endl;\n return 1;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 1;\n }\n\n return 0;\n }\n\nvoid print_help()\n {\n std::cout << Botan::version_string() << \" test driver\" << std::endl\n << \"Usage:\\n\"\n << \" --validate: Check test vectors\\n\"\n << \" --benchmark: Benchmark everything\\n\"\n << \" --bench-type={block,mode,stream,hash,mac,rng,pk}:\\n\"\n << \" Benchmark only algorithms of a particular type\\n\"\n << \" --html: Produce HTML output for benchmarks\\n\"\n << \" --seconds=n: Benchmark for n seconds\\n\"\n << \" --help: Print this message\\n\";\n }\n\nint validate()\n {\n void test_types();\n u32bit do_validation_tests(const std::string&, bool = true);\n u32bit do_bigint_tests(const std::string&);\n u32bit do_pk_validation_tests(const std::string&);\n\n std::cout << \"Beginning validation tests...\" << std::endl;\n\n test_types();\n u32bit errors = 0;\n try {\n errors += do_validation_tests(VALIDATION_FILE);\n errors += do_validation_tests(EXPECTED_FAIL_FILE, false);\n errors += do_bigint_tests(BIGINT_VALIDATION_FILE);\n errors += do_pk_validation_tests(PK_VALIDATION_FILE);\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Exception caught: \" << e.what() << std::endl;\n return 1;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \"\n << e.what() << std::endl;\n return 1;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 1;\n }\n\n if(errors)\n {\n std::cout << errors << \" test\" << ((errors == 1) ? \"\" : \"s\")\n << \" failed.\" << std::endl;\n return 1;\n }\n\n std::cout << \"All tests passed!\" << std::endl;\n return 0;\n }\n\ntemplate<typename T>\nbool test(const char* type, int digits, bool is_signed)\n {\n bool passed = true;\n if(std::numeric_limits<T>::is_specialized == false)\n {\n std::cout << \"WARNING: Could not check parameters of \" << type\n << \" in std::numeric_limits\" << std::endl;\n return true;\n }\n\n if(std::numeric_limits<T>::digits != digits && digits != 0)\n {\n std::cout << \"ERROR: numeric_limits<\" << type << \">::digits != \"\n << digits << std::endl;\n passed = false;\n }\n if(std::numeric_limits<T>::is_signed != is_signed)\n {\n std::cout << \"ERROR: numeric_limits<\" << type << \">::is_signed != \"\n << std::boolalpha << is_signed << std::endl;\n passed = false;\n }\n if(std::numeric_limits<T>::is_integer == false)\n {\n std::cout << \"ERROR: numeric_limits<\" << type\n << \">::is_integer == false \" << std::endl;\n passed = false;\n }\n return passed;\n }\n\nvoid test_types()\n {\n bool passed = true;\n\n passed = passed && test<Botan::byte >(\"byte\", 8, false);\n passed = passed && test<Botan::u16bit>(\"u16bit\", 16, false);\n passed = passed && test<Botan::u32bit>(\"u32bit\", 32, false);\n passed = passed && test<Botan::u64bit>(\"u64bit\", 64, false);\n passed = passed && test<Botan::s32bit>(\"s32bit\", 31, true);\n passed = passed && test<Botan::word>(\"word\", 0, false);\n\n if(!passed)\n {\n std::cout << \"Important settings in types.h are wrong. Please fix \"\n \"and recompile.\" << std::endl;\n std::exit(1);\n }\n }\n<commit_msg>Allow --bench-algo to take multiple arguments<commit_after>\/*\n * Test Driver for Botan\n *\/\n\n#include <vector>\n#include <string>\n\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <limits>\n\n#include <botan\/botan.h>\n#include <botan\/mp_types.h>\n\nusing namespace Botan_types;\n\n#include \"getopt.h\"\n\nconst std::string VALIDATION_FILE = \"checks\/validate.dat\";\nconst std::string BIGINT_VALIDATION_FILE = \"checks\/mp_valid.dat\";\nconst std::string PK_VALIDATION_FILE = \"checks\/pk_valid.dat\";\nconst std::string EXPECTED_FAIL_FILE = \"checks\/fail.dat\";\n\nvoid benchmark(const std::string&, bool html, double seconds);\nvoid bench_pk(const std::string&, bool html, double seconds);\nu32bit bench_algo(const std::string&, double);\nint validate();\nvoid print_help();\n\nint main(int argc, char* argv[])\n {\n try\n {\n OptionParser opts(\"help|html|init=|validate|\"\n \"benchmark|bench-type=|bench-algo=|seconds=\");\n opts.parse(argv);\n\n std::string init_flags = (opts.is_set(\"init\") ? opts.value(\"init\") : \"\");\n\n Botan::InitializerOptions init_options(init_flags);\n Botan::LibraryInitializer init(init_options);\n\n if(opts.is_set(\"help\") || argc <= 1)\n { print_help(); return 1; }\n if(opts.is_set(\"validate\"))\n return validate();\n\n double seconds = 1.5;\n\n if(opts.is_set(\"seconds\"))\n {\n seconds = std::atof(opts.value(\"seconds\").c_str());\n if((seconds < 0.1 || seconds > 30) && seconds != 0)\n {\n std::cout << \"Invalid argument to --seconds\\n\";\n return 2;\n }\n }\n\n if(opts.is_set(\"bench-algo\"))\n {\n std::vector<std::string> algs =\n Botan::split_on(opts.value(\"bench-algo\"), ',');\n\n for(u32bit j = 0; j != algs.size(); j++)\n {\n const std::string alg = algs[j];\n u32bit found = bench_algo(alg, seconds);\n if(!found) \/\/ maybe it's a PK algorithm\n bench_pk(alg, false, seconds);\n }\n }\n\n const bool html = opts.is_set(\"html\");\n\n if(opts.is_set(\"benchmark\"))\n benchmark(\"All\", html, seconds);\n else if(opts.is_set(\"bench-type\"))\n {\n const std::string type = opts.value(\"bench-type\");\n\n if(type == \"all\")\n benchmark(\"All\", html, seconds);\n else if(type == \"block\")\n benchmark(\"Block Cipher\", html, seconds);\n else if(type == \"stream\")\n benchmark(\"Stream Cipher\", html, seconds);\n else if(type == \"hash\")\n benchmark(\"Hash\", html, seconds);\n else if(type == \"mac\")\n benchmark(\"MAC\", html, seconds);\n else if(type == \"rng\")\n benchmark(\"RNG\", html, seconds);\n else if(type == \"pk\")\n bench_pk(\"All\", html, seconds);\n }\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Exception caught:\\n \" << e.what() << std::endl;\n return 1;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught:\\n \"\n << e.what() << std::endl;\n return 1;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 1;\n }\n\n return 0;\n }\n\nvoid print_help()\n {\n std::cout << Botan::version_string() << \" test driver\" << std::endl\n << \"Usage:\\n\"\n << \" --validate: Check test vectors\\n\"\n << \" --benchmark: Benchmark everything\\n\"\n << \" --bench-type={block,mode,stream,hash,mac,rng,pk}:\\n\"\n << \" Benchmark only algorithms of a particular type\\n\"\n << \" --html: Produce HTML output for benchmarks\\n\"\n << \" --seconds=n: Benchmark for n seconds\\n\"\n << \" --help: Print this message\\n\";\n }\n\nint validate()\n {\n void test_types();\n u32bit do_validation_tests(const std::string&, bool = true);\n u32bit do_bigint_tests(const std::string&);\n u32bit do_pk_validation_tests(const std::string&);\n\n std::cout << \"Beginning validation tests...\" << std::endl;\n\n test_types();\n u32bit errors = 0;\n try {\n errors += do_validation_tests(VALIDATION_FILE);\n errors += do_validation_tests(EXPECTED_FAIL_FILE, false);\n errors += do_bigint_tests(BIGINT_VALIDATION_FILE);\n errors += do_pk_validation_tests(PK_VALIDATION_FILE);\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Exception caught: \" << e.what() << std::endl;\n return 1;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \"\n << e.what() << std::endl;\n return 1;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 1;\n }\n\n if(errors)\n {\n std::cout << errors << \" test\" << ((errors == 1) ? \"\" : \"s\")\n << \" failed.\" << std::endl;\n return 1;\n }\n\n std::cout << \"All tests passed!\" << std::endl;\n return 0;\n }\n\ntemplate<typename T>\nbool test(const char* type, int digits, bool is_signed)\n {\n bool passed = true;\n if(std::numeric_limits<T>::is_specialized == false)\n {\n std::cout << \"WARNING: Could not check parameters of \" << type\n << \" in std::numeric_limits\" << std::endl;\n return true;\n }\n\n if(std::numeric_limits<T>::digits != digits && digits != 0)\n {\n std::cout << \"ERROR: numeric_limits<\" << type << \">::digits != \"\n << digits << std::endl;\n passed = false;\n }\n if(std::numeric_limits<T>::is_signed != is_signed)\n {\n std::cout << \"ERROR: numeric_limits<\" << type << \">::is_signed != \"\n << std::boolalpha << is_signed << std::endl;\n passed = false;\n }\n if(std::numeric_limits<T>::is_integer == false)\n {\n std::cout << \"ERROR: numeric_limits<\" << type\n << \">::is_integer == false \" << std::endl;\n passed = false;\n }\n return passed;\n }\n\nvoid test_types()\n {\n bool passed = true;\n\n passed = passed && test<Botan::byte >(\"byte\", 8, false);\n passed = passed && test<Botan::u16bit>(\"u16bit\", 16, false);\n passed = passed && test<Botan::u32bit>(\"u32bit\", 32, false);\n passed = passed && test<Botan::u64bit>(\"u64bit\", 64, false);\n passed = passed && test<Botan::s32bit>(\"s32bit\", 31, true);\n passed = passed && test<Botan::word>(\"word\", 0, false);\n\n if(!passed)\n {\n std::cout << \"Important settings in types.h are wrong. Please fix \"\n \"and recompile.\" << std::endl;\n std::exit(1);\n }\n }\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2003 Scott Wheeler <wheeler@kde.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n\n#include <tbytevector.h>\n#include <tbytevectorlist.h>\n#include <tstring.h>\n#include <tlist.h>\n#include <tdebug.h>\n\n#include <id3v2synchdata.h>\n\nusing namespace TagLib;\nusing namespace std;\n\nvoid testString();\nvoid testByteVector();\nvoid testSynchData();\nvoid testList();\n\nstatic int resultCount = 1;\n\nint main()\n{\n testString();\n resultCount = 1;\n testByteVector();\n resultCount = 1;\n testSynchData();\n resultCount = 1;\n testList();\n\n return 0;\n}\n\nvoid printResult(bool result)\n{\n if(result)\n cout << \"(\" << resultCount << \")\\tpass\" << endl;\n else\n cout << \"(\" << resultCount << \")\\tFAIL\" << endl;\n\n resultCount++;\n}\n\nvoid testString()\n{\n cout << \"*** Testing TagLib::String ***\" << endl;\n\n String s = \"taglib string\";\n ByteVector v = \"taglib string\";\n printResult(v == s.data(String::Latin1));\n\n char str[] = \"taglib string\";\n printResult(strcmp(s.toCString(), str) == 0);\n\n String unicode(\"José Carlos\", String::UTF8);\n printResult(strcmp(unicode.toCString(), \"Jos Carlos\") == 0);\n\n String latin = \"Jos Carlos\";\n printResult(strcmp(latin.toCString(true), \"José Carlos\") == 0);\n\n String unicode2(unicode.to8Bit(true), String::UTF8);\n printResult(unicode == unicode2);\n\n printResult(strcmp(String::number(0).toCString(), \"0\") == 0);\n printResult(strcmp(String::number(12345678).toCString(), \"12345678\") == 0);\n printResult(strcmp(String::number(-12345678).toCString(), \"-12345678\") == 0);\n\n String n = \"123\";\n printResult(n.toInt() == 123);\n\n n = \"-123\";\n printResult(n.toInt() == -123);\n\n printResult(String(\"0\").toInt() == 0);\n printResult(String(\"1\").toInt() == 1);\n\n printResult(String(\" foo \").stripWhiteSpace() == String(\"foo\"));\n printResult(String(\"foo \").stripWhiteSpace() == String(\"foo\"));\n printResult(String(\" foo\").stripWhiteSpace() == String(\"foo\"));\n\n printResult(memcmp(String(\"foo\").data(String::Latin1).data(), \"foo\", 3) == 0);\n printResult(memcmp(String(\"f\").data(String::Latin1).data(), \"f\", 1) == 0);\n}\n\nvoid testConversion(unsigned int i, unsigned char a, unsigned char b, unsigned char c, unsigned char d)\n{\n ByteVector v(4, 0);\n\n v[3] = a;\n v[2] = b;\n v[1] = c;\n v[0] = d;\n printResult(v.toUInt(false) == i);\n\n v[0] = a;\n v[1] = b;\n v[2] = c;\n v[3] = d;\n printResult(v.toUInt() == i);\n}\n\n\nvoid testByteVector()\n{\n cout << \"*** Testing TagLib::ByteVector ***\" << endl;\n ByteVector v(\"foobar\");\n\n printResult(v.find(\"ob\") == 2);\n printResult(v.find('b') == 3);\n\n ByteVector n(4, 0);\n n[0] = 1;\n printResult(n.toUInt(true) == 16777216);\n printResult(n.toUInt(false) == 1);\n printResult(ByteVector::fromUInt(16777216, true) == n);\n printResult(ByteVector::fromUInt(1, false) == n);\n\n printResult(ByteVector::fromUInt(0xa0).toUInt() == 0xa0);\n\n testConversion(0x000000a0, 0x00, 0x00, 0x00, 0xa0);\n testConversion(0xd50bf072, 0xd5, 0x0b, 0xf0, 0x72);\n\n ByteVector r0(\"**************\");\n ByteVector r1(\"OggS**********\");\n ByteVector r2(\"**********OggS\");\n ByteVector r3(\"OggS******OggS\");\n ByteVector r4(\"OggS*OggS*OggS\");\n\n printResult(r0.find(\"OggS\") == -1);\n printResult(r0.rfind(\"OggS\") == -1);\n printResult(r1.find(\"OggS\") == r1.rfind(\"OggS\"));\n printResult(r2.find(\"OggS\") == r2.rfind(\"OggS\"));\n printResult(r3.find(\"OggS\") == 0);\n printResult(r3.rfind(\"OggS\") == 10);\n printResult(r4.rfind(\"OggS\") == 10);\n printResult(r4.rfind(\"OggS\", 12) == 5);\n\n printResult(ByteVector::fromLongLong(1).toLongLong() == 1);\n printResult(ByteVector::fromLongLong(0).toLongLong() == 0);\n printResult(ByteVector::fromLongLong(0xffffffffffffffffLL).toLongLong() == -1);\n printResult(ByteVector::fromLongLong(0xfffffffffffffffeLL).toLongLong() == -2);\n printResult(ByteVector::fromLongLong(1024).toLongLong() == 1024);\n\n ByteVector a1(\"foo\");\n a1.append(\"bar\");\n printResult(a1 == \"foobar\");\n\n ByteVector a2(\"foo\");\n a2.append(\"b\");\n printResult(a2 == \"foob\");\n\n ByteVector a3;\n a3.append(\"b\");\n printResult(a3 == \"b\");\n\n ByteVector s1(\"foo\");\n printResult(ByteVectorList::split(s1, \" \").size() == 1);\n\n ByteVector s2(\"f\");\n printResult(ByteVectorList::split(s2, \" \").size() == 1);\n}\n\nvoid testSynchData()\n{\n cout << \"*** Testing TagLib::ID3v2::SynchData ***\" << endl;\n\n { \/\/ test 1\n char data[] = { 0, 0, 0, 127 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 127);\n printResult(ID3v2::SynchData::fromUInt(127) == v);\n }\n { \/\/ test 2\n char data[] = { 0, 0, 1, 0 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 128);\n printResult(ID3v2::SynchData::fromUInt(128) == v);\n }\n { \/\/ test 3\n char data[] = { 0, 0, 1, 1 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 129);\n printResult(ID3v2::SynchData::fromUInt(129) == v);\n }\n}\n\nvoid testList()\n{\n cout << \"*** Testing TagLib::List<T> ***\" << endl;\n List<int> l1;\n List<int> l2;\n List<int> l3;\n l1.append(1);\n l1.append(2);\n l2.append(3);\n l2.append(4);\n l1.append(l2);\n l3.append(1);\n l3.append(2);\n l3.append(3);\n l3.append(4);\n printResult(l1 == l3);\n}\n<commit_msg>Add a couple of testcases that point out UTF16 bugs.<commit_after>\/* Copyright (C) 2003 Scott Wheeler <wheeler@kde.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n\n#include <tbytevector.h>\n#include <tbytevectorlist.h>\n#include <tstring.h>\n#include <tlist.h>\n#include <tdebug.h>\n\n#include <id3v2synchdata.h>\n\nusing namespace TagLib;\nusing namespace std;\n\nvoid testString();\nvoid testByteVector();\nvoid testSynchData();\nvoid testList();\n\nstatic int resultCount = 1;\n\nint main()\n{\n testString();\n resultCount = 1;\n testByteVector();\n resultCount = 1;\n testSynchData();\n resultCount = 1;\n testList();\n\n return 0;\n}\n\nvoid printResult(bool result)\n{\n if(result)\n cout << \"(\" << resultCount << \")\\tpass\" << endl;\n else\n cout << \"(\" << resultCount << \")\\tFAIL\" << endl;\n\n resultCount++;\n}\n\nvoid testString()\n{\n cout << \"*** Testing TagLib::String ***\" << endl;\n\n String s = \"taglib string\";\n ByteVector v = \"taglib string\";\n printResult(v == s.data(String::Latin1));\n\n char str[] = \"taglib string\";\n printResult(strcmp(s.toCString(), str) == 0);\n\n String unicode(\"José Carlos\", String::UTF8);\n printResult(strcmp(unicode.toCString(), \"Jos Carlos\") == 0);\n\n String latin = \"Jos Carlos\";\n printResult(strcmp(latin.toCString(true), \"José Carlos\") == 0);\n\n String unicode2(unicode.to8Bit(true), String::UTF8);\n printResult(unicode == unicode2);\n \n printResult(strcmp(String::number(0).toCString(), \"0\") == 0);\n printResult(strcmp(String::number(12345678).toCString(), \"12345678\") == 0);\n printResult(strcmp(String::number(-12345678).toCString(), \"-12345678\") == 0);\n\n String n = \"123\";\n printResult(n.toInt() == 123);\n\n n = \"-123\";\n printResult(n.toInt() == -123);\n\n printResult(String(\"0\").toInt() == 0);\n printResult(String(\"1\").toInt() == 1);\n\n printResult(String(\" foo \").stripWhiteSpace() == String(\"foo\"));\n printResult(String(\"foo \").stripWhiteSpace() == String(\"foo\"));\n printResult(String(\" foo\").stripWhiteSpace() == String(\"foo\"));\n\n printResult(memcmp(String(\"foo\").data(String::Latin1).data(), \"foo\", 3) == 0);\n printResult(memcmp(String(\"f\").data(String::Latin1).data(), \"f\", 1) == 0);\n\n ByteVector utf16 = unicode.data(String::UTF16);\n\n \/\/ Check to make sure that the BOM is there and that the data size is correct\n\n printResult(utf16.size() == 2 + (unicode.size() * 2));\n\n printResult(unicode == String(utf16, String::UTF16));\n}\n\nvoid testConversion(unsigned int i, unsigned char a, unsigned char b, unsigned char c, unsigned char d)\n{\n ByteVector v(4, 0);\n\n v[3] = a;\n v[2] = b;\n v[1] = c;\n v[0] = d;\n printResult(v.toUInt(false) == i);\n\n v[0] = a;\n v[1] = b;\n v[2] = c;\n v[3] = d;\n printResult(v.toUInt() == i);\n}\n\n\nvoid testByteVector()\n{\n cout << \"*** Testing TagLib::ByteVector ***\" << endl;\n ByteVector v(\"foobar\");\n\n printResult(v.find(\"ob\") == 2);\n printResult(v.find('b') == 3);\n\n ByteVector n(4, 0);\n n[0] = 1;\n printResult(n.toUInt(true) == 16777216);\n printResult(n.toUInt(false) == 1);\n printResult(ByteVector::fromUInt(16777216, true) == n);\n printResult(ByteVector::fromUInt(1, false) == n);\n\n printResult(ByteVector::fromUInt(0xa0).toUInt() == 0xa0);\n\n testConversion(0x000000a0, 0x00, 0x00, 0x00, 0xa0);\n testConversion(0xd50bf072, 0xd5, 0x0b, 0xf0, 0x72);\n\n ByteVector r0(\"**************\");\n ByteVector r1(\"OggS**********\");\n ByteVector r2(\"**********OggS\");\n ByteVector r3(\"OggS******OggS\");\n ByteVector r4(\"OggS*OggS*OggS\");\n\n printResult(r0.find(\"OggS\") == -1);\n printResult(r0.rfind(\"OggS\") == -1);\n printResult(r1.find(\"OggS\") == r1.rfind(\"OggS\"));\n printResult(r2.find(\"OggS\") == r2.rfind(\"OggS\"));\n printResult(r3.find(\"OggS\") == 0);\n printResult(r3.rfind(\"OggS\") == 10);\n printResult(r4.rfind(\"OggS\") == 10);\n printResult(r4.rfind(\"OggS\", 12) == 5);\n\n printResult(ByteVector::fromLongLong(1).toLongLong() == 1);\n printResult(ByteVector::fromLongLong(0).toLongLong() == 0);\n printResult(ByteVector::fromLongLong(0xffffffffffffffffLL).toLongLong() == -1);\n printResult(ByteVector::fromLongLong(0xfffffffffffffffeLL).toLongLong() == -2);\n printResult(ByteVector::fromLongLong(1024).toLongLong() == 1024);\n\n ByteVector a1(\"foo\");\n a1.append(\"bar\");\n printResult(a1 == \"foobar\");\n\n ByteVector a2(\"foo\");\n a2.append(\"b\");\n printResult(a2 == \"foob\");\n\n ByteVector a3;\n a3.append(\"b\");\n printResult(a3 == \"b\");\n\n ByteVector s1(\"foo\");\n printResult(ByteVectorList::split(s1, \" \").size() == 1);\n\n ByteVector s2(\"f\");\n printResult(ByteVectorList::split(s2, \" \").size() == 1);\n}\n\nvoid testSynchData()\n{\n cout << \"*** Testing TagLib::ID3v2::SynchData ***\" << endl;\n\n { \/\/ test 1\n char data[] = { 0, 0, 0, 127 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 127);\n printResult(ID3v2::SynchData::fromUInt(127) == v);\n }\n { \/\/ test 2\n char data[] = { 0, 0, 1, 0 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 128);\n printResult(ID3v2::SynchData::fromUInt(128) == v);\n }\n { \/\/ test 3\n char data[] = { 0, 0, 1, 1 };\n ByteVector v(data, 4);\n\n printResult(ID3v2::SynchData::toUInt(v) == 129);\n printResult(ID3v2::SynchData::fromUInt(129) == v);\n }\n}\n\nvoid testList()\n{\n cout << \"*** Testing TagLib::List<T> ***\" << endl;\n List<int> l1;\n List<int> l2;\n List<int> l3;\n l1.append(1);\n l1.append(2);\n l2.append(3);\n l2.append(4);\n l1.append(l2);\n l3.append(1);\n l3.append(2);\n l3.append(3);\n l3.append(4);\n printResult(l1 == l3);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/container\/pmr\/memory_resource.hpp>\n#include <boost\/core\/no_exceptions_support.hpp>\n\n#include <cstddef>\n\nnamespace boost {\nnamespace container {\nnamespace pmr {\n\nclass default_resource_impl : public memory_resource {\n public:\n virtual ~default_resource_impl() {}\n\n virtual void* do_allocate(std::size_t bytes, std::size_t alignment) { return std::malloc(bytes); }\n\n virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) { std::free(p); }\n\n virtual bool do_is_equal(const memory_resource& other) const BOOST_NOEXCEPT { return &other == this; }\n} default_resource_instance;\n\nmemory_resource* new_delete_resource() BOOST_NOEXCEPT { return &default_resource_instance; }\n\nmemory_resource* set_default_resource(memory_resource* r) BOOST_NOEXCEPT {\n \/\/ Do nothing\n return &default_resource_instance;\n}\n\nmemory_resource* get_default_resource() BOOST_NOEXCEPT { return &default_resource_instance; }\n\n} \/\/ namespace pmr\n} \/\/ namespace container\n} \/\/ namespace boost\n<commit_msg>Fix missing cstdlib include (#237)<commit_after>#include <boost\/container\/pmr\/memory_resource.hpp>\n#include <boost\/core\/no_exceptions_support.hpp>\n\n#include <cstddef>\n#include <cstdlib>\n\nnamespace boost {\nnamespace container {\nnamespace pmr {\n\nclass default_resource_impl : public memory_resource {\n public:\n virtual ~default_resource_impl() {}\n\n virtual void* do_allocate(std::size_t bytes, std::size_t alignment) { return std::malloc(bytes); }\n\n virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) { std::free(p); }\n\n virtual bool do_is_equal(const memory_resource& other) const BOOST_NOEXCEPT { return &other == this; }\n} default_resource_instance;\n\nmemory_resource* new_delete_resource() BOOST_NOEXCEPT { return &default_resource_instance; }\n\nmemory_resource* set_default_resource(memory_resource* r) BOOST_NOEXCEPT {\n \/\/ Do nothing\n return &default_resource_instance;\n}\n\nmemory_resource* get_default_resource() BOOST_NOEXCEPT { return &default_resource_instance; }\n\n} \/\/ namespace pmr\n} \/\/ namespace container\n} \/\/ namespace boost\n<|endoftext|>"} {"text":"<commit_before>\/\/ Authors: see AUTHORS.md at project root.\n\/\/ CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.\n\/\/ URL: https:\/\/github.com\/asrob-uc3m\/robotDevastation\n\n#include \"YarpNetworkManager.hpp\"\n\n#include <sstream>\n#include <cstring> \/\/ strcmp()\n\n#include <yarp\/os\/Network.h>\n\n#include <ColorDebug.hpp>\n\n#include \"Vocabs.hpp\"\n\n\/\/-- Initialize static members\nrd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL;\nconst std::string rd::YarpNetworkManager::id = \"YARP\";\nconst int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000;\n\nbool rd::YarpNetworkManager::RegisterManager()\n{\n if (uniqueInstance == NULL)\n {\n uniqueInstance = new YarpNetworkManager();\n }\n\n return Register( uniqueInstance, id);\n}\n\nrd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS)\n{\n started = false;\n}\n\nvoid rd::YarpNetworkManager::run()\n{\n keepAlive();\n}\n\nrd::YarpNetworkManager::~YarpNetworkManager()\n{\n uniqueInstance = NULL;\n}\n\nbool rd::YarpNetworkManager::start()\n{\n if (player.getId() == -1)\n {\n CD_ERROR(\"NetworkManager not initialized, player id not set\\n\");\n return false;\n }\n\n if (started)\n {\n CD_ERROR(\"NetworkManager already started\\n\");\n return false;\n }\n\n yarp::os::Network::initMinimum();\n\n if ( ! yarp::os::Network::checkNetwork() )\n {\n CD_INFO_NO_HEADER(\"Checking for yarp network... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Found no yarp network to connect to rdServer (try running \\\"yarpserver &\\\"), bye!\\n\");\n return false;\n }\n\n \/\/-- Open the rpcClient port with this player's id\n std::ostringstream rpc_str;\n rpc_str << \"\/robotDevastation\/\";\n rpc_str << player.getId();\n rpc_str << \"\/rdServer\/rpc:c\";\n if( ! rpcClient.open( rpc_str.str() ) )\n {\n CD_ERROR(\"Could not open '%s'. Bye!\\n\",rpc_str.str().c_str());\n return false;\n }\n\n \/\/-- Open the callback port with this player's id\n std::ostringstream callback_str;\n callback_str << \"\/robotDevastation\/\";\n callback_str << player.getId();\n callback_str << \"\/rdServer\/info:i\";\n if( ! callbackPort.open( callback_str.str() ) )\n {\n CD_ERROR(\"Could not open '%s'. Bye!\\n\",callback_str.str().c_str());\n return false;\n }\n\n \/\/-- Connect robotDevastation RpcClient to rdServer RpcServer\n std::string rdServerRpcS(\"\/rdServer\/rpc:s\");\n if( ! yarp::os::Network::connect( rpc_str.str() , rdServerRpcS ) )\n {\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Could not connect to rdServer '%s' port (try running \\\"rdServer &\\\"), bye!\\n\",rdServerRpcS.c_str());\n return false;\n }\n\n \/\/-- Connect from rdServer info to robotDevastation callbackPort\n std::string rdServerInfoO(\"\/rdServer\/info:o\");\n if ( ! yarp::os::Network::connect( rdServerInfoO, callback_str.str() ))\n {\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Could not connect from rdServer '%s' port (try running \\\"rdServer &\\\"), bye!\\n\",rdServerInfoO.c_str());\n return false;\n }\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_SUCCESS_NO_HEADER(\"[ok]\\n\");\n\n callbackPort.useCallback(*this);\n\n RateThread::start();\n\n started = true;\n return true;\n}\n\n\nvoid rd::YarpNetworkManager::onRead(yarp::os::Bottle &b)\n{\n \/\/CD_INFO(\"Got %s\\n\", b.toString().c_str());\n if ((b.get(0).asString() == \"players\")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { \/\/ players \/\/\n \/\/CD_INFO(\"Number of players: %d\\n\",b.size()-1); \/\/ -1 because of vocab.\n std::vector< Player > players;\n for (int i = 1; i < b.size(); i++)\n {\n Player rdPlayer(b.get(i).asList()->get(0).asInt(),\n b.get(i).asList()->get(1).asString().c_str(),\n b.get(i).asList()->get(2).asInt(),\n b.get(i).asList()->get(3).asInt(),\n b.get(i).asList()->get(4).asInt(),\n b.get(i).asList()->get(5).asInt()\n );\n players.push_back(rdPlayer);\n }\n\n \/\/-- Notify listeners\n for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)\n {\n (*it)->onDataArrived(players);\n }\n }\n else\n {\n CD_ERROR(\"What?\\n\");\n }\n\n}\n\nbool rd::YarpNetworkManager::stop()\n{\n if (!started)\n {\n CD_ERROR(\"Already stopped\\n\");\n return false;\n }\n\n RateThread::askToStop();\n\n rpcClient.close();\n\n callbackPort.disableCallback();\n callbackPort.interrupt();\n callbackPort.close();\n\n yarp::os::NetworkBase::finiMinimum();\n\n started = false;\n return true;\n}\n\nbool rd::YarpNetworkManager::isStopped() const\n{\n return !started;\n}\n\nbool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value)\n{\n if (parameter.compare(\"player\") == 0)\n {\n player = value;\n return true;\n }\n\n return NetworkManager::configure(parameter, value);\n}\n\nbool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage)\n{\n if (!started)\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n \/\/-- Send a message to the server with the player Id and the damage done:\n yarp::os::Bottle msg_player_hit, response;\n msg_player_hit.addVocab(VOCAB_RD_HIT);\n msg_player_hit.addInt(player.getId());\n msg_player_hit.addInt(damage);\n rpcClient.write(msg_player_hit,response);\n CD_INFO(\"rdServer response from hit: %s\\n\",response.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(response.toString().c_str(), \"[ok]\") == 0)\n return true;\n else\n return false;\n}\n\nbool rd::YarpNetworkManager::login()\n{\n if ( ! started )\n {\n CD_WARNING(\"NetworkManager has not been started\\n\");\n if( ! start() )\n {\n CD_ERROR(\"NetworkManager could not be started for player %d\\n\", player.getId() );\n return false;\n }\n }\n\n \/\/-- Start network system\n std::stringstream ss;\n ss << player.getId();\n\n \/\/-- Send login message\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_LOGIN);\n msgRdPlayer.addInt(player.getId());\n msgRdPlayer.addString(player.getName().c_str());\n msgRdPlayer.addInt(player.getTeamId());\n rpcClient.write(msgRdPlayer,res);\n CD_INFO(\"rdServer response from login: %s\\n\",res.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n return true;\n else\n return false;\n}\n\nbool rd::YarpNetworkManager::logout()\n{\n if (!started)\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n CD_INFO(\"Logout...\\n\");\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_LOGOUT);\n msgRdPlayer.addInt(player.getId());\n rpcClient.write(msgRdPlayer,res);\n CD_INFO(\"rdServer response from logout: %s\\n\",res.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n {\n CD_SUCCESS(\"Logout ok\\n\");\n return true;\n }\n else\n {\n CD_ERROR(\"Logout failed\\n\");\n return false;\n }\n}\n\nbool rd::YarpNetworkManager::keepAlive()\n{\n if (!started)\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n CD_INFO(\"Keep alive...\\n\");\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE);\n msgRdPlayer.addInt(player.getId());\n rpcClient.write(msgRdPlayer,res);\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n {\n return true;\n }\n else\n {\n CD_ERROR(\"Keep alive failed\\n\");\n return false;\n }\n}\n<commit_msg>astyle<commit_after>\/\/ Authors: see AUTHORS.md at project root.\n\/\/ CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.\n\/\/ URL: https:\/\/github.com\/asrob-uc3m\/robotDevastation\n\n#include \"YarpNetworkManager.hpp\"\n\n#include <sstream>\n#include <cstring> \/\/ strcmp()\n\n#include <yarp\/os\/Network.h>\n\n#include <ColorDebug.hpp>\n\n#include \"Vocabs.hpp\"\n\n\/\/-- Initialize static members\nrd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL;\nconst std::string rd::YarpNetworkManager::id = \"YARP\";\nconst int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000;\n\nbool rd::YarpNetworkManager::RegisterManager()\n{\n if (uniqueInstance == NULL)\n {\n uniqueInstance = new YarpNetworkManager();\n }\n\n return Register( uniqueInstance, id);\n}\n\nrd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS)\n{\n started = false;\n}\n\nvoid rd::YarpNetworkManager::run()\n{\n keepAlive();\n}\n\nrd::YarpNetworkManager::~YarpNetworkManager()\n{\n uniqueInstance = NULL;\n}\n\nbool rd::YarpNetworkManager::start()\n{\n if (player.getId() == -1)\n {\n CD_ERROR(\"NetworkManager not initialized, player id not set\\n\");\n return false;\n }\n\n if (started)\n {\n CD_ERROR(\"NetworkManager already started\\n\");\n return false;\n }\n\n yarp::os::Network::initMinimum();\n\n if ( ! yarp::os::Network::checkNetwork() )\n {\n CD_INFO_NO_HEADER(\"Checking for yarp network... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Found no yarp network to connect to rdServer (try running \\\"yarpserver &\\\"), bye!\\n\");\n return false;\n }\n\n \/\/-- Open the rpcClient port with this player's id\n std::ostringstream rpc_str;\n rpc_str << \"\/robotDevastation\/\";\n rpc_str << player.getId();\n rpc_str << \"\/rdServer\/rpc:c\";\n if( ! rpcClient.open( rpc_str.str() ) )\n {\n CD_ERROR(\"Could not open '%s'. Bye!\\n\",rpc_str.str().c_str());\n return false;\n }\n\n \/\/-- Open the callback port with this player's id\n std::ostringstream callback_str;\n callback_str << \"\/robotDevastation\/\";\n callback_str << player.getId();\n callback_str << \"\/rdServer\/info:i\";\n if( ! callbackPort.open( callback_str.str() ) )\n {\n CD_ERROR(\"Could not open '%s'. Bye!\\n\",callback_str.str().c_str());\n return false;\n }\n\n \/\/-- Connect robotDevastation RpcClient to rdServer RpcServer\n std::string rdServerRpcS(\"\/rdServer\/rpc:s\");\n if( ! yarp::os::Network::connect( rpc_str.str() , rdServerRpcS ) )\n {\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Could not connect to rdServer '%s' port (try running \\\"rdServer &\\\"), bye!\\n\",rdServerRpcS.c_str());\n return false;\n }\n\n \/\/-- Connect from rdServer info to robotDevastation callbackPort\n std::string rdServerInfoO(\"\/rdServer\/info:o\");\n if ( ! yarp::os::Network::connect( rdServerInfoO, callback_str.str() ))\n {\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_ERROR_NO_HEADER(\"[fail]\\n\");\n CD_INFO_NO_HEADER(\"Could not connect from rdServer '%s' port (try running \\\"rdServer &\\\"), bye!\\n\",rdServerInfoO.c_str());\n return false;\n }\n CD_INFO_NO_HEADER(\"Checking for rdServer ports... \");\n CD_SUCCESS_NO_HEADER(\"[ok]\\n\");\n\n callbackPort.useCallback(*this);\n\n RateThread::start();\n\n started = true;\n return true;\n}\n\n\nvoid rd::YarpNetworkManager::onRead(yarp::os::Bottle &b)\n{\n \/\/CD_INFO(\"Got %s\\n\", b.toString().c_str());\n if ((b.get(0).asString() == \"players\")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { \/\/ players \/\/\n \/\/CD_INFO(\"Number of players: %d\\n\",b.size()-1); \/\/ -1 because of vocab.\n std::vector< Player > players;\n for (int i = 1; i < b.size(); i++)\n {\n Player rdPlayer(b.get(i).asList()->get(0).asInt(),\n b.get(i).asList()->get(1).asString().c_str(),\n b.get(i).asList()->get(2).asInt(),\n b.get(i).asList()->get(3).asInt(),\n b.get(i).asList()->get(4).asInt(),\n b.get(i).asList()->get(5).asInt()\n );\n players.push_back(rdPlayer);\n }\n\n \/\/-- Notify listeners\n for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)\n {\n (*it)->onDataArrived(players);\n }\n }\n else\n {\n CD_ERROR(\"What?\\n\");\n }\n\n}\n\nbool rd::YarpNetworkManager::stop()\n{\n if (!started)\n {\n CD_ERROR(\"Already stopped\\n\");\n return false;\n }\n\n RateThread::askToStop();\n\n rpcClient.close();\n\n callbackPort.disableCallback();\n callbackPort.interrupt();\n callbackPort.close();\n\n yarp::os::NetworkBase::finiMinimum();\n\n started = false;\n return true;\n}\n\nbool rd::YarpNetworkManager::isStopped() const\n{\n return ! started;\n}\n\nbool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value)\n{\n if (parameter.compare(\"player\") == 0)\n {\n player = value;\n return true;\n }\n\n return NetworkManager::configure(parameter, value);\n}\n\nbool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage)\n{\n if ( ! started )\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n \/\/-- Send a message to the server with the player Id and the damage done:\n yarp::os::Bottle msg_player_hit, response;\n msg_player_hit.addVocab(VOCAB_RD_HIT);\n msg_player_hit.addInt(player.getId());\n msg_player_hit.addInt(damage);\n rpcClient.write(msg_player_hit,response);\n CD_INFO(\"rdServer response from hit: %s\\n\",response.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(response.toString().c_str(), \"[ok]\") == 0)\n return true;\n else\n return false;\n}\n\nbool rd::YarpNetworkManager::login()\n{\n if ( ! started )\n {\n CD_WARNING(\"NetworkManager has not been started\\n\");\n if( ! start() )\n {\n CD_ERROR(\"NetworkManager could not be started for player %d\\n\", player.getId() );\n return false;\n }\n }\n\n \/\/-- Start network system\n std::stringstream ss;\n ss << player.getId();\n\n \/\/-- Send login message\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_LOGIN);\n msgRdPlayer.addInt(player.getId());\n msgRdPlayer.addString(player.getName().c_str());\n msgRdPlayer.addInt(player.getTeamId());\n rpcClient.write(msgRdPlayer,res);\n CD_INFO(\"rdServer response from login: %s\\n\",res.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n return true;\n else\n return false;\n}\n\nbool rd::YarpNetworkManager::logout()\n{\n if (!started)\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n CD_INFO(\"Logout...\\n\");\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_LOGOUT);\n msgRdPlayer.addInt(player.getId());\n rpcClient.write(msgRdPlayer,res);\n CD_INFO(\"rdServer response from logout: %s\\n\",res.toString().c_str());\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n {\n CD_SUCCESS(\"Logout ok\\n\");\n return true;\n }\n else\n {\n CD_ERROR(\"Logout failed\\n\");\n return false;\n }\n}\n\nbool rd::YarpNetworkManager::keepAlive()\n{\n if (!started)\n {\n CD_ERROR(\"NetworkManager has not been started\\n\");\n return false;\n }\n\n CD_INFO(\"Keep alive...\\n\");\n yarp::os::Bottle msgRdPlayer,res;\n msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE);\n msgRdPlayer.addInt(player.getId());\n rpcClient.write(msgRdPlayer,res);\n\n \/\/-- Check response\n if (std::strcmp(res.toString().c_str(), \"[ok]\") == 0)\n {\n return true;\n }\n else\n {\n CD_ERROR(\"Keep alive failed\\n\");\n return false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2017. The YARA Authors. All Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <stdint.h>\n#include <stddef.h>\n\n#include <yara.h>\n\n\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n yr_initialize();\n return 0;\n}\n\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)\n{\n YR_COMPILER* compiler;\n\n char* buffer = (char*) malloc(size + 1);\n\n if (!buffer)\n return 1;\n\n strlcpy(buffer, data, size + 1);\n\n if (yr_compiler_create(&compiler) != ERROR_SUCCESS)\n return 1;\n\n if (yr_compiler_add_string(compiler, buffer, NULL) == 0)\n {\n if (yr_compiler_get_rules(compiler, &rules) != ERROR_SUCCESS)\n return 1;\n }\n\n yr_compiler_destroy(compiler);\n\n return 0;\n}<commit_msg>Fix issues with rules fuzzer.<commit_after>\/*\nCopyright (c) 2017. The YARA Authors. All Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\nmay be used to endorse or promote products derived from this software without\nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <stdint.h>\n#include <stddef.h>\n\n#include <yara.h>\n\n\nextern \"C\" int LLVMFuzzerInitialize(int* argc, char*** argv)\n{\n yr_initialize();\n return 0;\n}\n\n\nextern \"C\" int LLVMFuzzerTestOneInput(const char *data, size_t size)\n{\n YR_RULES* rules;\n YR_COMPILER* compiler;\n\n char* buffer = (char*) malloc(size + 1);\n\n if (!buffer)\n return 1;\n\n strlcpy(buffer, data, size + 1);\n\n if (yr_compiler_create(&compiler) != ERROR_SUCCESS)\n return 1;\n\n if (yr_compiler_add_string(compiler, (const char*) buffer, NULL) == 0)\n {\n if (yr_compiler_get_rules(compiler, &rules) != ERROR_SUCCESS)\n return 1;\n }\n\n yr_compiler_destroy(compiler);\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: pyuno_loader.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2005-02-24 14:24:54 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Ralph Thomas\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ralph Thomas, Joerg Budischewski\n *\n *\n ************************************************************************\/\n#include <osl\/module.hxx>\n#include <osl\/process.h>\n#include <osl\/file.h>\n#include <osl\/thread.h>\n\n#include <rtl\/ustrbuf.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n\n#include <cppuhelper\/implementationentry.hxx>\n#include <cppuhelper\/factory.hxx>\n\n#include <pyuno\/pyuno.hxx>\n\nusing rtl::OUString;\nusing rtl::OUStringBuffer;\nusing rtl::OString;\n\nusing pyuno::PyRef;\nusing pyuno::Runtime;\nusing pyuno::PyThreadAttach;\n\nusing com::sun::star::registry::XRegistryKey;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::XInterface;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::XComponentContext;\nusing com::sun::star::uno::RuntimeException;\n\nnamespace pyuno_loader\n{\n\nstatic void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )\n{\n if( PyErr_Occurred() )\n {\n PyRef excType, excValue, excTraceback;\n PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);\n Runtime runtime;\n com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );\n OUStringBuffer buf;\n buf.appendAscii( \"python-loader:\" );\n if( a.hasValue() )\n buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );\n throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );\n }\n}\n\nstatic PyRef getLoaderModule() throw( RuntimeException )\n{\n PyRef module( PyImport_ImportModule( \"pythonloader\" ), SAL_NO_ACQUIRE );\n raiseRuntimeExceptionWhenNeeded();\n if( !module.is() )\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM( \"pythonloader: Couldn't load pythonloader module\" ) ),\n Reference< XInterface > () );\n }\n return PyRef( PyModule_GetDict( module.get() ));\n}\n\nstatic PyRef getObjectFromLoaderModule( const char * func )\n throw ( RuntimeException )\n{\n PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );\n if( !object.is() )\n {\n OUStringBuffer buf;\n buf.appendAscii( \"pythonloader: couldn't find core element pythonloader.\" );\n buf.appendAscii( func );\n throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());\n }\n return object;\n}\n\nOUString getImplementationName()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.comp.pyuno.Loader\" ) );\n}\n\nSequence< OUString > getSupportedServiceNames()\n{\n OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.loader.Python\" ) );\n return Sequence< OUString > ( &serviceName, 1 );\n}\n\nstatic OUString getLibDir()\n{\n static OUString *pLibDir;\n if( !pLibDir )\n {\n osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );\n if( ! pLibDir )\n {\n static OUString libDir;\n\n \/\/ changed from reinterpret_cast<void*> this is not allowed\n \/\/ in gcc 3.3 without permissive. Us simple C cast.\n if( osl::Module::getUrlFromAddress( (void*)(getLibDir) , libDir ) )\n {\n libDir = OUString( libDir.getStr(), libDir.lastIndexOf('\/' ) );\n }\n pLibDir = &libDir;\n }\n }\n return *pLibDir;\n}\n\nReference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )\n{\n Reference< XInterface > ret;\n\n if( ! Py_IsInitialized() )\n {\n \/\/ in case python path is already set, nothing is done ...\n const OUString pythonPath ( RTL_CONSTASCII_USTRINGPARAM( \"PYTHONPATH\" ) );\n\n \/\/ otherwise, try to get the PYTHONPATH bootstrap variable\n OUStringBuffer bufPYTHONPATH( 256 );\n OUString path = getLibDir();\n if( path.getLength() )\n {\n path += OUString( RTL_CONSTASCII_USTRINGPARAM( \"\/\" SAL_CONFIGFILE(\"pythonloader.uno\" )));\n rtl::Bootstrap bootstrap(path);\n\n \/\/ look for pythonhome\n OUString pythonHome;\n if( bootstrap.getFrom( OUString ( RTL_CONSTASCII_USTRINGPARAM( \"PYTHONHOME\") ),\n pythonHome ) )\n {\n osl_getFileURLFromSystemPath( pythonHome.pData, &(pythonHome.pData) );\n rtl::OStringBuffer stringBuffer( pythonHome.getLength() +20);\n stringBuffer.append( \"PYTHONHOME=\" );\n stringBuffer.append(\n rtl::OUStringToOString( pythonHome, osl_getThreadTextEncoding() ) );\n\n OString env2= stringBuffer.makeStringAndClear();\n rtl_string_acquire(env2.pData );\n putenv( env2.pData->buffer );\n\n }\n\n \/\/ check for pythonpath\n OUString pythonPathBootstrap;\n bootstrap.getFrom( pythonPath , pythonPathBootstrap );\n\n sal_Int32 nIndex = 0;\n while( 1 )\n {\n sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );\n OUString fileUrl;\n if( nNew == -1 )\n {\n fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );\n }\n else\n {\n fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );\n }\n OUString systemPath;\n osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );\n bufPYTHONPATH.append( systemPath );\n if( nNew == -1 )\n break;\n bufPYTHONPATH.append( (sal_Unicode) SAL_PATHSEPARATOR );\n nIndex = nNew + 1;\n }\n }\n\n OUString value;\n osl_getEnvironment( pythonPath.pData, &value.pData );\n bufPYTHONPATH.append( value );\n\n rtl::OStringBuffer stringBuffer;\n stringBuffer.append( \"PYTHONPATH=\" );\n stringBuffer.append(\n rtl::OUStringToOString( bufPYTHONPATH.makeStringAndClear(), osl_getThreadTextEncoding()));\n\n OString env = stringBuffer.makeStringAndClear();\n\n \/\/ leak this string (putenv does not make a copy)\n rtl_string_acquire( env.pData );\n putenv( env.pData->buffer );\n\n\n \/\/ initialize python\n Py_Initialize();\n PyEval_InitThreads();\n\n PyThreadState *tstate = PyThreadState_Get();\n PyEval_ReleaseThread( tstate );\n }\n\n PyThreadAttach attach( PyInterpreterState_Head() );\n {\n if( ! Runtime::isInitialized() )\n {\n Runtime::initialize( ctx );\n }\n Runtime runtime;\n\n PyRef pyCtx = runtime.any2PyObject(\n com::sun::star::uno::makeAny( ctx ) );\n\n PyRef clazz = getObjectFromLoaderModule( \"Loader\" );\n PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );\n PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );\n PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );\n runtime.pyObject2Any( pyInstance ) >>= ret;\n }\n return ret;\n}\n\n}\n\n\nstatic struct cppu::ImplementationEntry g_entries[] =\n{\n {\n pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,\n pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,\n 0 , 0\n },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nextern \"C\"\n{\n\n\/\/==================================================================================================\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\/\/==================================================================================================\nsal_Bool SAL_CALL component_writeInfo(\n void * pServiceManager, void * pRegistryKey )\n{\n return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );\n}\n\/\/==================================================================================================\nvoid * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );\n}\n\n}\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.12); FILE MERGED 2005\/09\/05 18:39:19 rt 1.6.12.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pyuno_loader.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:50:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include <osl\/module.hxx>\n#include <osl\/process.h>\n#include <osl\/file.h>\n#include <osl\/thread.h>\n\n#include <rtl\/ustrbuf.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n\n#include <cppuhelper\/implementationentry.hxx>\n#include <cppuhelper\/factory.hxx>\n\n#include <pyuno\/pyuno.hxx>\n\nusing rtl::OUString;\nusing rtl::OUStringBuffer;\nusing rtl::OString;\n\nusing pyuno::PyRef;\nusing pyuno::Runtime;\nusing pyuno::PyThreadAttach;\n\nusing com::sun::star::registry::XRegistryKey;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::XInterface;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::XComponentContext;\nusing com::sun::star::uno::RuntimeException;\n\nnamespace pyuno_loader\n{\n\nstatic void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )\n{\n if( PyErr_Occurred() )\n {\n PyRef excType, excValue, excTraceback;\n PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);\n Runtime runtime;\n com::sun::star::uno::Any a = runtime.extractUnoException( excType, excValue, excTraceback );\n OUStringBuffer buf;\n buf.appendAscii( \"python-loader:\" );\n if( a.hasValue() )\n buf.append( ((com::sun::star::uno::Exception *)a.getValue())->Message );\n throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface> () );\n }\n}\n\nstatic PyRef getLoaderModule() throw( RuntimeException )\n{\n PyRef module( PyImport_ImportModule( \"pythonloader\" ), SAL_NO_ACQUIRE );\n raiseRuntimeExceptionWhenNeeded();\n if( !module.is() )\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM( \"pythonloader: Couldn't load pythonloader module\" ) ),\n Reference< XInterface > () );\n }\n return PyRef( PyModule_GetDict( module.get() ));\n}\n\nstatic PyRef getObjectFromLoaderModule( const char * func )\n throw ( RuntimeException )\n{\n PyRef object( PyDict_GetItemString(getLoaderModule().get(), (char*)func ) );\n if( !object.is() )\n {\n OUStringBuffer buf;\n buf.appendAscii( \"pythonloader: couldn't find core element pythonloader.\" );\n buf.appendAscii( func );\n throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());\n }\n return object;\n}\n\nOUString getImplementationName()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.comp.pyuno.Loader\" ) );\n}\n\nSequence< OUString > getSupportedServiceNames()\n{\n OUString serviceName( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.loader.Python\" ) );\n return Sequence< OUString > ( &serviceName, 1 );\n}\n\nstatic OUString getLibDir()\n{\n static OUString *pLibDir;\n if( !pLibDir )\n {\n osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );\n if( ! pLibDir )\n {\n static OUString libDir;\n\n \/\/ changed from reinterpret_cast<void*> this is not allowed\n \/\/ in gcc 3.3 without permissive. Us simple C cast.\n if( osl::Module::getUrlFromAddress( (void*)(getLibDir) , libDir ) )\n {\n libDir = OUString( libDir.getStr(), libDir.lastIndexOf('\/' ) );\n }\n pLibDir = &libDir;\n }\n }\n return *pLibDir;\n}\n\nReference< XInterface > CreateInstance( const Reference< XComponentContext > & ctx )\n{\n Reference< XInterface > ret;\n\n if( ! Py_IsInitialized() )\n {\n \/\/ in case python path is already set, nothing is done ...\n const OUString pythonPath ( RTL_CONSTASCII_USTRINGPARAM( \"PYTHONPATH\" ) );\n\n \/\/ otherwise, try to get the PYTHONPATH bootstrap variable\n OUStringBuffer bufPYTHONPATH( 256 );\n OUString path = getLibDir();\n if( path.getLength() )\n {\n path += OUString( RTL_CONSTASCII_USTRINGPARAM( \"\/\" SAL_CONFIGFILE(\"pythonloader.uno\" )));\n rtl::Bootstrap bootstrap(path);\n\n \/\/ look for pythonhome\n OUString pythonHome;\n if( bootstrap.getFrom( OUString ( RTL_CONSTASCII_USTRINGPARAM( \"PYTHONHOME\") ),\n pythonHome ) )\n {\n osl_getFileURLFromSystemPath( pythonHome.pData, &(pythonHome.pData) );\n rtl::OStringBuffer stringBuffer( pythonHome.getLength() +20);\n stringBuffer.append( \"PYTHONHOME=\" );\n stringBuffer.append(\n rtl::OUStringToOString( pythonHome, osl_getThreadTextEncoding() ) );\n\n OString env2= stringBuffer.makeStringAndClear();\n rtl_string_acquire(env2.pData );\n putenv( env2.pData->buffer );\n\n }\n\n \/\/ check for pythonpath\n OUString pythonPathBootstrap;\n bootstrap.getFrom( pythonPath , pythonPathBootstrap );\n\n sal_Int32 nIndex = 0;\n while( 1 )\n {\n sal_Int32 nNew = pythonPathBootstrap.indexOf( ' ', nIndex );\n OUString fileUrl;\n if( nNew == -1 )\n {\n fileUrl = OUString( &( pythonPathBootstrap[nIndex] ) );\n }\n else\n {\n fileUrl = OUString( &(pythonPathBootstrap[nIndex]) , nNew - nIndex );\n }\n OUString systemPath;\n osl_getSystemPathFromFileURL( fileUrl.pData, &(systemPath.pData) );\n bufPYTHONPATH.append( systemPath );\n if( nNew == -1 )\n break;\n bufPYTHONPATH.append( (sal_Unicode) SAL_PATHSEPARATOR );\n nIndex = nNew + 1;\n }\n }\n\n OUString value;\n osl_getEnvironment( pythonPath.pData, &value.pData );\n bufPYTHONPATH.append( value );\n\n rtl::OStringBuffer stringBuffer;\n stringBuffer.append( \"PYTHONPATH=\" );\n stringBuffer.append(\n rtl::OUStringToOString( bufPYTHONPATH.makeStringAndClear(), osl_getThreadTextEncoding()));\n\n OString env = stringBuffer.makeStringAndClear();\n\n \/\/ leak this string (putenv does not make a copy)\n rtl_string_acquire( env.pData );\n putenv( env.pData->buffer );\n\n\n \/\/ initialize python\n Py_Initialize();\n PyEval_InitThreads();\n\n PyThreadState *tstate = PyThreadState_Get();\n PyEval_ReleaseThread( tstate );\n }\n\n PyThreadAttach attach( PyInterpreterState_Head() );\n {\n if( ! Runtime::isInitialized() )\n {\n Runtime::initialize( ctx );\n }\n Runtime runtime;\n\n PyRef pyCtx = runtime.any2PyObject(\n com::sun::star::uno::makeAny( ctx ) );\n\n PyRef clazz = getObjectFromLoaderModule( \"Loader\" );\n PyRef args ( PyTuple_New( 1 ), SAL_NO_ACQUIRE );\n PyTuple_SetItem( args.get(), 0 , pyCtx.getAcquired() );\n PyRef pyInstance( PyObject_CallObject( clazz.get() , args.get() ), SAL_NO_ACQUIRE );\n runtime.pyObject2Any( pyInstance ) >>= ret;\n }\n return ret;\n}\n\n}\n\n\nstatic struct cppu::ImplementationEntry g_entries[] =\n{\n {\n pyuno_loader::CreateInstance, pyuno_loader::getImplementationName,\n pyuno_loader::getSupportedServiceNames, cppu::createSingleComponentFactory,\n 0 , 0\n },\n { 0, 0, 0, 0, 0, 0 }\n};\n\nextern \"C\"\n{\n\n\/\/==================================================================================================\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\/\/==================================================================================================\nsal_Bool SAL_CALL component_writeInfo(\n void * pServiceManager, void * pRegistryKey )\n{\n return cppu::component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );\n}\n\/\/==================================================================================================\nvoid * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n return cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"braincloud\/BrainCloudClient.h\"\n#include \"TestResult.h\"\n#include \"TestBCTournament.h\"\n#include \"braincloud\/reason_codes.h\"\n#include \"braincloud\/BrainCloudSocialLeaderboard.h\"\n\nusing namespace BrainCloud;\n\n\nTEST_F(TestBCTournament, ClaimTournamentReward)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\n\tm_bc->getTournamentService()->claimTournamentReward(_leaderboardId, version, &tr);\n\ttr.runExpectFail(m_bc, 400, VIEWING_REWARD_FOR_NON_PROCESSED_TOURNAMENTS);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, GetTournamentStatus)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\n\tm_bc->getTournamentService()->getTournamentStatus(_leaderboardId, version, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, JoinTournament)\n{\n\tJoinTournament();\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, LeaveTournament)\n{\n\tJoinTournament();\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, PostTournamentScore)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\ttime_t t = time(0);\n\tstruct tm * time = gmtime(&t);\n\n\tm_bc->getTournamentService()->postTournamentScore(_leaderboardId, 200, \"\", time, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, PostTournamentScoreWithResults)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\ttime_t t = time(0);\n\tstruct tm * time = gmtime(&t);\n\n\tm_bc->getTournamentService()->postTournamentScoreWithResults(_leaderboardId, 200, \"\", time, HIGH_TO_LOW, 10, 10, 0, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, ViewCurrentReward)\n{\n\tJoinTournament();\n\n\tTestResult tr;\n\tm_bc->getTournamentService()->viewCurrentReward(_leaderboardId, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, ViewReward)\n{\n\tJoinTournament();\n\n\tTestResult tr;\n\tm_bc->getTournamentService()->viewReward(_leaderboardId, -1, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nint32_t TestBCTournament::JoinTournament()\n{\n\tTestResult tr;\n\tm_bc->getTournamentService()->joinTournament(_leaderboardId, _tournamentCode, 100, &tr);\n\ttr.run(m_bc);\n\n\tm_bc->getTournamentService()->getTournamentStatus(_leaderboardId, -1, &tr);\n\ttr.run(m_bc);\n\treturn tr.m_response[\"data\"][\"versionId\"].asInt();\n}\n\nvoid TestBCTournament::LeaveTournament()\n{\n\tTestResult tr;\n\tm_bc->getTournamentService()->leaveTournament(_leaderboardId, &tr);\n\ttr.run(m_bc);\n}<commit_msg>Fix VS 2008<commit_after>#include \"gtest\/gtest.h\"\n#include \"braincloud\/BrainCloudClient.h\"\n#include \"TestResult.h\"\n#include \"TestBCTournament.h\"\n#include \"braincloud\/reason_codes.h\"\n#include \"braincloud\/BrainCloudSocialLeaderboard.h\"\n#include <time.h>\n\nusing namespace BrainCloud;\n\n\nTEST_F(TestBCTournament, ClaimTournamentReward)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\n\tm_bc->getTournamentService()->claimTournamentReward(_leaderboardId, version, &tr);\n\ttr.runExpectFail(m_bc, 400, VIEWING_REWARD_FOR_NON_PROCESSED_TOURNAMENTS);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, GetTournamentStatus)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\n\tm_bc->getTournamentService()->getTournamentStatus(_leaderboardId, version, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, JoinTournament)\n{\n\tJoinTournament();\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, LeaveTournament)\n{\n\tJoinTournament();\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, PostTournamentScore)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\ttime_t t = time(0);\n\tstruct tm * time = gmtime(&t);\n\n\tm_bc->getTournamentService()->postTournamentScore(_leaderboardId, 200, \"\", time, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, PostTournamentScoreWithResults)\n{\n\tint32_t version = JoinTournament();\n\n\tTestResult tr;\n\ttime_t t = time(0);\n\tstruct tm * time = gmtime(&t);\n\n\tm_bc->getTournamentService()->postTournamentScoreWithResults(_leaderboardId, 200, \"\", time, HIGH_TO_LOW, 10, 10, 0, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, ViewCurrentReward)\n{\n\tJoinTournament();\n\n\tTestResult tr;\n\tm_bc->getTournamentService()->viewCurrentReward(_leaderboardId, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nTEST_F(TestBCTournament, ViewReward)\n{\n\tJoinTournament();\n\n\tTestResult tr;\n\tm_bc->getTournamentService()->viewReward(_leaderboardId, -1, &tr);\n\ttr.run(m_bc);\n\n\tLeaveTournament();\n}\n\nint32_t TestBCTournament::JoinTournament()\n{\n\tTestResult tr;\n\tm_bc->getTournamentService()->joinTournament(_leaderboardId, _tournamentCode, 100, &tr);\n\ttr.run(m_bc);\n\n\tm_bc->getTournamentService()->getTournamentStatus(_leaderboardId, -1, &tr);\n\ttr.run(m_bc);\n\treturn tr.m_response[\"data\"][\"versionId\"].asInt();\n}\n\nvoid TestBCTournament::LeaveTournament()\n{\n\tTestResult tr;\n\tm_bc->getTournamentService()->leaveTournament(_leaderboardId, &tr);\n\ttr.run(m_bc);\n}<|endoftext|>"} {"text":"<commit_before>#include <mart-netlib\/tcp.hpp>\n\n#include <mart-common\/PrintWrappers.h>\n\n#include <catch2\/catch.hpp>\n\n#include <future>\n#include <iostream>\n\n\nnamespace mart::nw::ip::tcp {\n\nstd::ostream& operator<<( std::ostream& out, mart::nw::ip::tcp::endpoint ep )\n{\n\tout << ep.toStringEx();\n\treturn out;\n}\n\n} \/\/ namespace\n\n\nTEST_CASE( \"tcp_socket_simple_exchange\", \"[net]\" )\n{\n\tusing namespace mart::nw::ip;\n\ttcp::endpoint e1 = { mart::nw::ip::address_any, mart::nw::ip::port_nr{ 1583 } };\n\ttcp::endpoint e2 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1485 } };\n\ttcp::endpoint e3{ \"127.0.0.1:3495\" };\n\ttcp::Socket s1;\n\n\ttcp::Socket s2{};\n\n\n\ttcp::Socket s4( std::move( s1 ) );\n\ts2 = std::move( s4 );\n\n\t[[maybe_unused]] mart::nw::socks::RaiiSocket& raw_socket = s2.as_raii_socket();\n\n\tCHECK_NOTHROW( s2.bind( e1 ) );\n\t\/\/ socket can't be rebinded to a different one\n\tCHECK_THROWS( s2.bind( e2 ) );\n\tCHECK_THROWS( s2.connect( e2 ) );\n\tCHECK( s2.get_local_endpoint() == e1 );\n\tCHECK( !s2.get_remote_endpoint().valid() );\n\n\tCHECK_THROWS( s2.send( mart::view_bytes( 5 ) ) );\n}\n\nTEST_CASE( \"tcp_simple_exchange\", \"[net]\" )\n{\n\tusing namespace mart::nw::ip;\n\ttcp::endpoint e1 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1584 } };\n\ttcp::endpoint e2 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1486 } };\n\n\tauto s1_future = std::async( [&] {\n\t\ttcp::Acceptor ac( e1 );\n\t\treturn ac.accept( std::chrono::milliseconds( 1000 ) );\n\t} );\n\n\ttcp::Socket s2;\n\ts2.bind( e2 );\n\ts2.connect( e1 );\n\n\tauto s1 = s1_future.get();\n\tCHECK( s1.is_valid() );\n\n\tCHECK( s2.get_remote_endpoint() == e1 );\n\tCHECK( s1.get_remote_endpoint() == e2 );\n\n\tconst int data_orig = 0xffa1;\n\tint data_rec{};\n\ts1.send( mart::view_bytes( data_orig ) );\n\tauto rec = s2.recv( mart::view_bytes_mutable( data_rec ) );\n\n\tCHECK( rec.size_inBytes() == sizeof( int ) );\n\tCHECK( data_orig == data_rec );\n\n}<commit_msg>[test] Ensure acceptor runs asynchronously<commit_after>#include <mart-netlib\/tcp.hpp>\n\n#include <mart-common\/PrintWrappers.h>\n\n#include <catch2\/catch.hpp>\n\n#include <future>\n#include <iostream>\n\n\nnamespace mart::nw::ip::tcp {\n\nstd::ostream& operator<<( std::ostream& out, mart::nw::ip::tcp::endpoint ep )\n{\n\tout << ep.toStringEx();\n\treturn out;\n}\n\n} \/\/ namespace\n\n\nTEST_CASE( \"tcp_socket_simple_exchange\", \"[net]\" )\n{\n\tusing namespace mart::nw::ip;\n\ttcp::endpoint e1 = { mart::nw::ip::address_any, mart::nw::ip::port_nr{ 1583 } };\n\ttcp::endpoint e2 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1485 } };\n\ttcp::endpoint e3{ \"127.0.0.1:3495\" };\n\ttcp::Socket s1;\n\n\ttcp::Socket s2{};\n\n\n\ttcp::Socket s4( std::move( s1 ) );\n\ts2 = std::move( s4 );\n\n\t[[maybe_unused]] mart::nw::socks::RaiiSocket& raw_socket = s2.as_raii_socket();\n\n\tCHECK_NOTHROW( s2.bind( e1 ) );\n\t\/\/ socket can't be rebinded to a different one\n\tCHECK_THROWS( s2.bind( e2 ) );\n\tCHECK_THROWS( s2.connect( e2 ) );\n\tCHECK( s2.get_local_endpoint() == e1 );\n\tCHECK( !s2.get_remote_endpoint().valid() );\n\n\tCHECK_THROWS( s2.send( mart::view_bytes( 5 ) ) );\n}\n\nTEST_CASE( \"tcp_simple_exchange\", \"[net]\" )\n{\n\tusing namespace mart::nw::ip;\n\ttcp::endpoint e1 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1584 } };\n\ttcp::endpoint e2 = { mart::nw::ip::address_local_host, mart::nw::ip::port_nr{ 1486 } };\n\n\tauto s1_future = std::async( std::launch::async, [&] {\n\t\ttcp::Acceptor ac( e1 );\n\t\treturn ac.accept( std::chrono::milliseconds( 1000 ) );\n\t} );\n\n\ttcp::Socket s2;\n\ts2.bind( e2 );\n\ts2.connect( e1 );\n\n\tauto s1 = s1_future.get();\n\tCHECK( s1.is_valid() );\n\n\tCHECK( s2.get_remote_endpoint() == e1 );\n\tCHECK( s1.get_remote_endpoint() == e2 );\n\n\tconst int data_orig = 0xffa1;\n\tint data_rec{};\n\ts1.send( mart::view_bytes( data_orig ) );\n\tauto rec = s2.recv( mart::view_bytes_mutable( data_rec ) );\n\n\tCHECK( rec.size_inBytes() == sizeof( int ) );\n\tCHECK( data_orig == data_rec );\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) the FFLAS-FFPACK group\n * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>\n *\n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *.\n *\/\n#include <iomanip>\n#include <iostream>\n#include <random>\n\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"fflas-ffpack\/utils\/test-utils.h\"\n#include \"fflas-ffpack\/utils\/fflas_io.h\"\n#include \"fflas-ffpack\/utils\/fflas_memory.h\"\n\n#include <givaro\/modular.h>\n#include <recint\/rint.h>\n\n#include \"fflas-ffpack\/fflas\/fflas_transpose.h\"\n\nusing namespace std;\nusing namespace FFLAS;\nusing namespace FFPACK;\n\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\n\/******************************************************************************\/\ntemplate <typename Elt>\nclass Test {\n public:\n using Field = Modular<Elt>;\n using Elt_ptr = typename Field::Element_ptr;\n using Residu = typename Field::Residu_t;\n template <bool B, class T = void>\n using enable_if_t = typename std::enable_if<B, T>::type;\n template <typename Simd>\n using is_same_element = typename Simd::template is_same_element<Field>;\n template <typename E>\n using enable_if_no_simd_t = enable_if_t<Simd<E>::vect_size == 1>;\n template <typename E>\n using enable_if_simd128_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 16>;\n template <typename E>\n using enable_if_simd256_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 32>;\n template <typename E>\n using enable_if_simd512_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 64>;\n\n \/* ctor *\/\n Test () : F(cardinality()) {\n }\n\n \/* *\/\n template <typename _E = Elt,\n enable_if_t<!is_same<_E, Givaro::Integer>::value>* = nullptr>\n static Residu\n cardinality () {\n return Field::maxCardinality();\n }\n\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Givaro::Integer>::value>* = nullptr>\n static Residu\n cardinality () {\n \/* Test Givaro::Integer with a large (=more than a word) modulus *\/\n return Givaro::Integer (\"0x100000000000000000000000000000000\");\n }\n\n \/* main test function *\/\n template <typename Simd = NoSimd<Elt>,\n enable_if_t<is_same_element<Simd>::value>* = nullptr>\n bool test_ftranspose (size_t m, size_t n, Elt_ptr A, size_t lda,\n Elt_ptr B, size_t ldb) {\n Elt_ptr M, Mt;\n if (A == B) {\n M = fflas_new (F, ldb, lda);\n finit (F, ldb, lda, M, lda);\n fassign (F, m, n, A, lda, M, lda);\n Mt = M;\n }\n else {\n M = A;\n Mt = B;\n }\n ftranspose<Field, Simd> (F, m, n, M, lda, Mt, ldb);\n\n bool ok = true;\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n ok = ok && ((*(Mt+j*ldb+i)) == (*(A+i*lda+j)));\n\n if (!ok) {\n cerr << \"Error, with \" << m << \"x\" << n << \" matrix\"\n << (lda == n ? \"\" : \" with stride \" + to_string(lda))\n << (A == B ? \" (inplace variant)\" : \"\") << \" over \"\n << F.type_string() << \" using \" << Simd::type_string()\n << endl;\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n if ((*(Mt+j*ldb+i)) != (*(A+i*lda+j))) {\n cerr << \" at index (\" << j << \", \" << i\n << \") expected \" << *(A+i*lda+j) << \" got \"\n << *(Mt+j*ldb+i) << endl;\n }\n }\n\n if (A == B) {\n fflas_delete (M);\n }\n return ok;\n }\n\n \/* perform the tests for all sizes and types of matrices *\/\n template <typename Simd = NoSimd<Elt>,\n enable_if_t<is_same_element<Simd>::value>* = nullptr>\n bool doTests () {\n bool ok = true;\n\n \/* square matrices *\/\n size_t nrows[] = { 3*FFLAS_TRANSPOSE_BLOCKSIZE,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size+3 };\n for (auto m: nrows) {\n Elt_ptr M = fflas_new (F, m, m);\n Elt_ptr Mt = fflas_new (F, m, m);\n\n finit (F, m, m, M, m);\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < m; j++)\n\t\t F.assign (M[i*m+j], (uint64_t)(i << 8) + j);\n finit (F, m, m, Mt, m);\n\n \/* not inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, m, M, m, Mt, m);\n\n \/* not inplace submatrix *\/\n size_t s = m - FFLAS_TRANSPOSE_BLOCKSIZE;\n ok &= test_ftranspose<Simd> (s, s, M, m, Mt, m);\n\n \/* inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, m, M, m, M, m);\n\n \/* inplace submatrix *\/\n s = m - Simd::vect_size;\n ok &= test_ftranspose<Simd> (s, s, M, m, M, m);\n\n fflas_delete (M);\n fflas_delete (Mt);\n }\n\n \/* non square matrices *\/\n size_t ncols[] = { 2*FFLAS_TRANSPOSE_BLOCKSIZE,\n 4*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+2*Simd::vect_size+1};\n for (size_t i = 0; i < 3; i++) {\n size_t m = nrows[i];\n size_t n = ncols[i];\n\n Elt_ptr M = fflas_new (F, m, n);\n Elt_ptr Mt = fflas_new (F, n, m);\n\n finit (F, m, n, M, n);\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n\t\t F.assign (M[i*n+j], (uint64_t)(i << 8) + j);\n finit (F, n, m, Mt, m);\n\n \/* not inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, n, M, n, Mt, m);\n\n \/* not inplace submatrix *\/\n size_t s = m - Simd::vect_size;\n size_t t = n - 2*Simd::vect_size+1;\n ok &= test_ftranspose<Simd> (s, t, M, n, Mt, m);\n\n \/* inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, n, M, n, M, m);\n\n fflas_delete (M);\n fflas_delete (Mt);\n }\n\n \/* print results *\/\n std::cout << F.type_string()\n << string (36-F.type_string().size(), '.') << \" \"\n << Simd::type_string()\n << string (36-Simd::type_string().size(), '.') << \" \"\n << (ok ? \"PASSED\" : \"FAILED\")\n << endl;\n\n return ok;\n }\n\n \/* run tests: call doTests for all available Simd structs *\/\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_no_simd_t<_E>* = nullptr>\n bool run () {\n return doTests();\n }\n\n#ifdef __FFLASFFPACK_HAVE_SSE4_1_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd128_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>();\n }\n#endif\n\n#ifdef __FFLASFFPACK_HAVE_AVX_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd256_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>()\n & doTests<Simd256<Elt>>();\n }\n#endif\n\n#ifdef __FFLASFFPACK_HAVE_AVX512DQ_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd512_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>()\n & doTests<Simd256<Elt>>() & doTests<Simd512<Elt>>();\n }\n#endif\n\n protected:\n Field F;\n};\n\n\/******************************************************************************\/\nint main(int argc, char** argv)\n{\n std::cout << std::setprecision(17);\n std::cerr << std::setprecision(17);\n\n bool ok = true;\n\n ok &= Test<float>().run();\n ok &= Test<double>().run();\n ok &= Test<uint64_t>().run();\n ok &= Test<int64_t>().run();\n ok &= Test<uint32_t>().run();\n ok &= Test<int32_t>().run();\n ok &= Test<uint16_t>().run();\n ok &= Test<int16_t>().run();\n ok &= Test<Givaro::Integer>().run();\n ok &= Test<RecInt::rint<6>>().run();\n ok &= Test<RecInt::ruint<6>>().run();\n ok &= Test<RecInt::rint<7>>().run();\n ok &= Test<RecInt::ruint<7>>().run();\n ok &= Test<RecInt::rint<8>>().run();\n ok &= Test<RecInt::ruint<8>>().run();\n\n return !ok;\n}\n<commit_msg>Fix test-storage-transpose for simd512<commit_after>\/*\n * Copyright (C) the FFLAS-FFPACK group\n * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr>\n *\n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *.\n *\/\n#include <iomanip>\n#include <iostream>\n#include <random>\n\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"fflas-ffpack\/utils\/test-utils.h\"\n#include \"fflas-ffpack\/utils\/fflas_io.h\"\n#include \"fflas-ffpack\/utils\/fflas_memory.h\"\n\n#include <givaro\/modular.h>\n#include <recint\/rint.h>\n\n#include \"fflas-ffpack\/fflas\/fflas_transpose.h\"\n\nusing namespace std;\nusing namespace FFLAS;\nusing namespace FFPACK;\n\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\n\/******************************************************************************\/\ntemplate <typename Elt>\nclass Test {\n public:\n using Field = Modular<Elt>;\n using Elt_ptr = typename Field::Element_ptr;\n using Residu = typename Field::Residu_t;\n template <bool B, class T = void>\n using enable_if_t = typename std::enable_if<B, T>::type;\n template <typename Simd>\n using is_same_element = typename Simd::template is_same_element<Field>;\n template <typename E>\n using enable_if_no_simd_t = enable_if_t<Simd<E>::vect_size == 1>;\n template <typename E>\n using enable_if_simd128_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 16>;\n template <typename E>\n using enable_if_simd256_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 32>;\n template <typename E>\n using enable_if_simd512_t = enable_if_t<sizeof(E)*Simd<E>::vect_size == 64>;\n\n \/* ctor *\/\n Test () : F(cardinality()) {\n }\n\n \/* *\/\n template <typename _E = Elt,\n enable_if_t<!is_same<_E, Givaro::Integer>::value>* = nullptr>\n static Residu\n cardinality () {\n return Field::maxCardinality();\n }\n\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Givaro::Integer>::value>* = nullptr>\n static Residu\n cardinality () {\n \/* Test Givaro::Integer with a large (=more than a word) modulus *\/\n return Givaro::Integer (\"0x100000000000000000000000000000000\");\n }\n\n \/* main test function *\/\n template <typename Simd = NoSimd<Elt>,\n enable_if_t<is_same_element<Simd>::value>* = nullptr>\n bool test_ftranspose (size_t m, size_t n, Elt_ptr A, size_t lda,\n Elt_ptr B, size_t ldb) {\n Elt_ptr M, Mt;\n if (A == B) {\n M = fflas_new (F, ldb, lda);\n finit (F, ldb, lda, M, lda);\n fassign (F, m, n, A, lda, M, lda);\n Mt = M;\n }\n else {\n M = A;\n Mt = B;\n }\n ftranspose<Field, Simd> (F, m, n, M, lda, Mt, ldb);\n\n bool ok = true;\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n ok = ok && ((*(Mt+j*ldb+i)) == (*(A+i*lda+j)));\n\n if (!ok) {\n cerr << \"Error, with \" << m << \"x\" << n << \" matrix\"\n << (lda == n ? \"\" : \" with stride \" + to_string(lda))\n << (A == B ? \" (inplace variant)\" : \"\") << \" over \"\n << F.type_string() << \" using \" << Simd::type_string()\n << endl;\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n if ((*(Mt+j*ldb+i)) != (*(A+i*lda+j))) {\n cerr << \" at index (\" << j << \", \" << i\n << \") expected \" << *(A+i*lda+j) << \" got \"\n << *(Mt+j*ldb+i) << endl;\n }\n }\n\n if (A == B) {\n fflas_delete (M);\n }\n return ok;\n }\n\n \/* perform the tests for all sizes and types of matrices *\/\n template <typename Simd = NoSimd<Elt>,\n enable_if_t<is_same_element<Simd>::value>* = nullptr>\n bool doTests () {\n bool ok = true;\n\n \/* square matrices *\/\n size_t nrows[] = { 3*FFLAS_TRANSPOSE_BLOCKSIZE,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size+3 };\n for (auto m: nrows) {\n Elt_ptr M = fflas_new (F, m, m);\n Elt_ptr Mt = fflas_new (F, m, m);\n\n finit (F, m, m, M, m);\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < m; j++)\n\t\t F.assign (M[i*m+j], (uint64_t)(i << 8) + j);\n finit (F, m, m, Mt, m);\n\n \/* not inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, m, M, m, Mt, m);\n\n \/* not inplace submatrix *\/\n size_t s = m - FFLAS_TRANSPOSE_BLOCKSIZE;\n ok &= test_ftranspose<Simd> (s, s, M, m, Mt, m);\n\n \/* inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, m, M, m, M, m);\n\n \/* inplace submatrix *\/\n s = m - Simd::vect_size;\n ok &= test_ftranspose<Simd> (s, s, M, m, M, m);\n\n fflas_delete (M);\n fflas_delete (Mt);\n }\n\n \/* non square matrices *\/\n size_t ncols[] = { 2*FFLAS_TRANSPOSE_BLOCKSIZE,\n 4*FFLAS_TRANSPOSE_BLOCKSIZE+Simd::vect_size,\n 3*FFLAS_TRANSPOSE_BLOCKSIZE+2*Simd::vect_size+1};\n for (size_t i = 0; i < 3; i++) {\n size_t m = nrows[i];\n size_t n = ncols[i];\n\n Elt_ptr M = fflas_new (F, m, n);\n Elt_ptr Mt = fflas_new (F, n, m);\n\n finit (F, m, n, M, n);\n for (size_t i = 0; i < m; i++)\n for (size_t j = 0; j < n; j++)\n\t\t F.assign (M[i*n+j], (uint64_t)(i << 8) + j);\n finit (F, n, m, Mt, m);\n\n \/* not inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, n, M, n, Mt, m);\n\n \/* not inplace submatrix *\/\n size_t s = m - Simd::vect_size;\n size_t t = n - 2*Simd::vect_size+1;\n ok &= test_ftranspose<Simd> (s, t, M, n, Mt, m);\n\n \/* inplace full matrix *\/\n ok &= test_ftranspose<Simd> (m, n, M, n, M, m);\n\n fflas_delete (M);\n fflas_delete (Mt);\n }\n\n \/* print results *\/\n std::cout << F.type_string()\n << string (36-F.type_string().size(), '.') << \" \"\n << Simd::type_string()\n << string (36-Simd::type_string().size(), '.') << \" \"\n << (ok ? \"PASSED\" : \"FAILED\")\n << endl;\n\n return ok;\n }\n\n \/* run tests: call doTests for all available Simd structs *\/\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_no_simd_t<_E>* = nullptr>\n bool run () {\n return doTests();\n }\n\n#ifdef __FFLASFFPACK_HAVE_SSE4_1_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd128_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>();\n }\n#endif\n\n#ifdef __FFLASFFPACK_HAVE_AVX_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd256_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>()\n & doTests<Simd256<Elt>>();\n }\n#endif\n\n#ifdef __FFLASFFPACK_HAVE_AVX512DQ_INSTRUCTIONS\n template <typename _E = Elt,\n enable_if_t<is_same<_E, Elt>::value>* = nullptr,\n enable_if_t<Simd<_E>::vect_size != 1>* = nullptr,\n enable_if_simd512_t<_E>* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>()\n & doTests<Simd256<Elt>>() & doTests<Simd512<Elt>>();\n }\n\n \/* Workaround for Simd512<(u)int32\/16_t> which does not exist *\/\n template <typename _E = Elt,\n enable_if_t<is_same<_E, uint32_t>::value\n || is_same<_E, int32_t>::value\n || is_same<_E, uint16_t>::value\n || is_same<_E, int16_t>::value\n >* = nullptr>\n bool run () {\n return doTests() & doTests<Simd128<Elt>>()\n & doTests<Simd256<Elt>>();\n }\n#endif\n\n protected:\n Field F;\n};\n\n\/******************************************************************************\/\nint main(int argc, char** argv)\n{\n std::cout << std::setprecision(17);\n std::cerr << std::setprecision(17);\n\n bool ok = true;\n\n ok &= Test<float>().run();\n ok &= Test<double>().run();\n ok &= Test<uint64_t>().run();\n ok &= Test<int64_t>().run();\n ok &= Test<uint32_t>().run();\n ok &= Test<int32_t>().run();\n ok &= Test<uint16_t>().run();\n ok &= Test<int16_t>().run();\n ok &= Test<Givaro::Integer>().run();\n ok &= Test<RecInt::rint<6>>().run();\n ok &= Test<RecInt::ruint<6>>().run();\n ok &= Test<RecInt::rint<7>>().run();\n ok &= Test<RecInt::ruint<7>>().run();\n ok &= Test<RecInt::rint<8>>().run();\n ok &= Test<RecInt::ruint<8>>().run();\n\n return !ok;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <functional>\n#include <future>\n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"blockiterator.h\"\n#include \"gridinterpolator.h\"\n#include \"aggregateraster.h\"\n\nusing namespace Ilwis;\nusing namespace RasterOperations;\n\n\nIlwis::OperationImplementation *AggregateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new AggregateRaster(metaid, expr);\n}\n\nAggregateRaster::AggregateRaster()\n{\n}\n\nAggregateRaster::AggregateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) :\n OperationImplementation(metaid, expr),\n _method(NumericStatistics::pSUM)\n{\n}\n\nbool AggregateRaster::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n return false;\n\n IGridCoverage outputGC = _outputObj.get<GridCoverage>();\n\n\n BoxedAsyncFunc aggregateFun = [&](const Box3D<qint32>& box) -> bool {\n Size sz = outputGC->size();\n PixelIterator iterOut(outputGC, box);\n BlockIterator blockIter(_inputObj.get<GridCoverage>(),Size(_groupSize,_groupSize), Size(sz.xsize() * _groupSize, sz.ysize()*_groupSize));\n NumericStatistics stats;\n while(iterOut != iterOut.end()) {\n GridBlock& block = *blockIter;\n stats.calculate(block.begin(), block.end(), _method);\n double v = stats[_method];\n *iterOut = v;\n ++iterOut;\n if ( iterOut.ychanged()) {\n qDebug() << v;\n }\n ++blockIter;\n }\n return true;\n };\n ctx->_threaded = false;\n bool res = OperationHelperRaster::execute(ctx, aggregateFun, outputGC);\n\n if ( res && ctx != 0) {\n QVariant value;\n value.setValue<IGridCoverage>(outputGC);\n ctx->addOutput(symTable,value,outputGC->name(), itGRID, outputGC->resource() );\n }\n return res;\n}\n\nNumericStatistics::PropertySets AggregateRaster::toMethod(const QString& nm) {\n QString mname = nm.toLower();\n if ( mname == \"avg\")\n return NumericStatistics::pMEAN;\n else if ( mname == \"min\")\n return NumericStatistics::pMIN;\n else if ( mname == \"max\")\n return NumericStatistics::pMAX;\n else if ( mname == \"med\")\n return NumericStatistics::pMEDIAN;\n else if ( mname == \"pred\")\n return NumericStatistics::pPREDOMINANT;\n else if ( mname == \"std\")\n return NumericStatistics::pSTDEV;\n else if ( mname == \"sum\")\n return NumericStatistics::pSUM;\n\n return NumericStatistics::pLAST ;\n}\n\nIlwis::OperationImplementation::State AggregateRaster::prepare(ExecutionContext *, const SymbolTable & )\n{\n QString gc = _expression.parm(0).value();\n QString outputName = _expression.parm(0,false).value();\n int copylist = itDOMAIN | itCOORDSYSTEM;\n\n if (!_inputObj.prepare(gc, itGRID)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,gc,\"\");\n return sPREPAREFAILED;\n }\n\n _method = toMethod(_expression.parm(1).value());\n if ( _method == NumericStatistics::pLAST) {\n ERROR2(ERR_ILLEGAL_VALUE_2, \"parameter value\", \" aggregation method\");\n return sPREPAREFAILED;\n }\n bool ok;\n _groupSize = _expression.parm(2).value().toInt(&ok);\n if ( !ok || _groupSize < 2) {\n ERROR2(ERR_ILLEGAL_VALUE_2, \"aggregation group size\", QString::number(_groupSize));\n return sPREPAREFAILED;\n }\n\n _grouped = _expression.parm(3).value() == \"true\";\n if ( !_grouped)\n copylist |= itGEOREF;\n\n _outputObj = OperationHelperRaster::initialize(_inputObj,itGRID, copylist);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output gridcoverage\");\n return sPREPAREFAILED;\n }\n QString outputBaseName = outputName;\n int index = 0;\n if ( (index = outputName.lastIndexOf(\".\")) != -1) {\n outputBaseName = outputName.left(index);\n }\n IGridCoverage inputGC = _inputObj.get<GridCoverage>();\n IGridCoverage outputGC = _outputObj.get<GridCoverage>();\n if ( outputName != sUNDEF)\n _outputObj->setName(outputName);\n\n Box3D<qint32> box(inputGC->georeference()->size());\n if ( _grouped) {\n int xs = box.xlength();\n int ys = box.ylength();\n int newxs = xs \/ _groupSize;\n int newys = ys \/ _groupSize;\n box = Box3D<qint32>(Size(newxs, newys));\n\n }\n if ( _expression.parameterCount() == 5 || _grouped) {\n Box2D<double> envlope = inputGC->envelope();\n Resource res(QUrl(\"ilwis:\/\/internal\/georeference\"),itGEOREF);\n res.addProperty(\"size\", IVARIANT(box.size()));\n res.addProperty(\"envelope\", IVARIANT(envlope));\n res.addProperty(\"coordinatesystem\", IVARIANT(inputGC->coordinateSystem()));\n res.addProperty(\"name\", outputBaseName);\n res.addProperty(\"centerofpixel\",inputGC->georeference()->centerOfPixel());\n IGeoReference grf;\n grf.prepare(res);\n outputGC->georeference(grf);\n outputGC->envelope(envlope);\n }\n\n return sPREPARED;\n}\n\nquint64 AggregateRaster::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/aggregateraster\");\n Resource res(QUrl(url), itOPERATIONMETADATA);\n res.addProperty(\"namespace\",\"ilwis\");\n res.addProperty(\"longname\",\"aggregateraster raster coverage\");\n res.addProperty(\"syntax\",\"resample(inputgridcoverage,{Avg|Max|Med|Min|Prd|Std|Sum}, groupsize,changegeometry[,new georefname])\");\n res.addProperty(\"inparameters\",\"4|5\");\n res.addProperty(\"pin_1_type\", itGRID);\n res.addProperty(\"pin_1_name\", TR(\"input gridcoverage\"));\n res.addProperty(\"pin_1_desc\",TR(\"input gridcoverage with domain any domain\"));\n res.addProperty(\"pin_2_type\", itSTRING);\n res.addProperty(\"pin_2_name\", TR(\"Aggregation Method\"));\n res.addProperty(\"pin_2_desc\",TR(\"the method how pixels inside a group will be accumulated\"));\n res.addProperty(\"pin_3_type\", itINTEGER);\n res.addProperty(\"pin_3_name\", TR(\"Groupsize\"));\n res.addProperty(\"pin_3_desc\",TR(\"The size of the block used to aggregate\"));\n res.addProperty(\"pin_4_type\", itBOOL);\n res.addProperty(\"pin_4_name\", TR(\"change geometry\"));\n res.addProperty(\"pin_4_desc\",TR(\"The aggregation can either create a map with a reduced size proportional to de block size or use the same geometry size but fill all pixels in the block with the aggregate\"));\n res.addProperty(\"pin_5_type\", itSTRING);\n res.addProperty(\"pin_5_name\", TR(\"georeference name\"));\n res.addProperty(\"pin_5_desc\",TR(\"optional parameter indicating a name for the new geometry, else the name will come from the output grid\"));\n res.addProperty(\"outparameters\",1);\n res.addProperty(\"pout_1_type\", itGRID);\n res.addProperty(\"pout_1_name\", TR(\"output gridcoverage\"));\n res.addProperty(\"pout_1_desc\",TR(\"output gridcoverage with the domain of the input map\"));\n res.prepare();\n url += \"=\" + QString::number(res.id());\n res.setUrl(url);\n\n mastercatalog()->addItems({res});\n return res.id();\n}\n\n\n<commit_msg>correct shifting bounding box for multicore variant of this operation<commit_after>#include <functional>\n#include <future>\n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"blockiterator.h\"\n#include \"gridinterpolator.h\"\n#include \"aggregateraster.h\"\n\nusing namespace Ilwis;\nusing namespace RasterOperations;\n\n\nIlwis::OperationImplementation *AggregateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new AggregateRaster(metaid, expr);\n}\n\nAggregateRaster::AggregateRaster()\n{\n}\n\nAggregateRaster::AggregateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) :\n OperationImplementation(metaid, expr),\n _method(NumericStatistics::pSUM)\n{\n}\n\nbool AggregateRaster::execute(ExecutionContext *ctx, SymbolTable& symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n return false;\n\n IGridCoverage outputGC = _outputObj.get<GridCoverage>();\n\n\n BoxedAsyncFunc aggregateFun = [&](const Box3D<qint32>& box) -> bool {\n \/\/Size sz = outputGC->size();\n PixelIterator iterOut(outputGC, box);\n Box3D<qint32> inpBox(Point3D<qint32>(box.min_corner().x(), box.min_corner().y() * _groupSize),\n Point3D<qint32>((box.max_corner().x()+1) * _groupSize - 1, (box.max_corner().y() + 1) * _groupSize - 1));\n\n \/\/BlockIterator blockIter(_inputObj.get<GridCoverage>(),Size(_groupSize,_groupSize), Size(sz.xsize() * _groupSize, sz.ysize()*_groupSize));\n \/\/Box3D<qint32> sz2(Size(sz.xsize() * _groupSize, sz.ysize()*_groupSize));\n BlockIterator blockIter(_inputObj.get<GridCoverage>(),Size(_groupSize,_groupSize), inpBox);\n NumericStatistics stats;\n while(iterOut != iterOut.end()) {\n GridBlock& block = *blockIter;\n stats.calculate(block.begin(), block.end(), _method);\n double v = stats[_method];\n *iterOut = v;\n ++iterOut;\n ++blockIter;\n }\n return true;\n };\n \/\/ctx->_threaded = false;\n bool res = OperationHelperRaster::execute(ctx, aggregateFun, outputGC);\n\n if ( res && ctx != 0) {\n QVariant value;\n value.setValue<IGridCoverage>(outputGC);\n ctx->addOutput(symTable,value,outputGC->name(), itGRID, outputGC->resource() );\n }\n return res;\n}\n\nNumericStatistics::PropertySets AggregateRaster::toMethod(const QString& nm) {\n QString mname = nm.toLower();\n if ( mname == \"avg\")\n return NumericStatistics::pMEAN;\n else if ( mname == \"min\")\n return NumericStatistics::pMIN;\n else if ( mname == \"max\")\n return NumericStatistics::pMAX;\n else if ( mname == \"med\")\n return NumericStatistics::pMEDIAN;\n else if ( mname == \"pred\")\n return NumericStatistics::pPREDOMINANT;\n else if ( mname == \"std\")\n return NumericStatistics::pSTDEV;\n else if ( mname == \"sum\")\n return NumericStatistics::pSUM;\n\n return NumericStatistics::pLAST ;\n}\n\nIlwis::OperationImplementation::State AggregateRaster::prepare(ExecutionContext *, const SymbolTable & )\n{\n QString gc = _expression.parm(0).value();\n QString outputName = _expression.parm(0,false).value();\n int copylist = itDOMAIN | itCOORDSYSTEM;\n\n if (!_inputObj.prepare(gc, itGRID)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,gc,\"\");\n return sPREPAREFAILED;\n }\n\n _method = toMethod(_expression.parm(1).value());\n if ( _method == NumericStatistics::pLAST) {\n ERROR2(ERR_ILLEGAL_VALUE_2, \"parameter value\", \" aggregation method\");\n return sPREPAREFAILED;\n }\n bool ok;\n _groupSize = _expression.parm(2).value().toInt(&ok);\n if ( !ok || _groupSize < 2) {\n ERROR2(ERR_ILLEGAL_VALUE_2, \"aggregation group size\", QString::number(_groupSize));\n return sPREPAREFAILED;\n }\n\n _grouped = _expression.parm(3).value() == \"true\";\n if ( !_grouped)\n copylist |= itGEOREF;\n\n _outputObj = OperationHelperRaster::initialize(_inputObj,itGRID, copylist);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output gridcoverage\");\n return sPREPAREFAILED;\n }\n QString outputBaseName = outputName;\n int index = 0;\n if ( (index = outputName.lastIndexOf(\".\")) != -1) {\n outputBaseName = outputName.left(index);\n }\n IGridCoverage inputGC = _inputObj.get<GridCoverage>();\n IGridCoverage outputGC = _outputObj.get<GridCoverage>();\n if ( outputName != sUNDEF)\n _outputObj->setName(outputName);\n\n Box3D<qint32> box(inputGC->georeference()->size());\n if ( _grouped) {\n int xs = box.xlength();\n int ys = box.ylength();\n int newxs = xs \/ _groupSize;\n int newys = ys \/ _groupSize;\n box = Box3D<qint32>(Size(newxs, newys));\n\n }\n if ( _expression.parameterCount() == 5 || _grouped) {\n Box2D<double> envlope = inputGC->envelope();\n Resource res(QUrl(\"ilwis:\/\/internal\/georeference\"),itGEOREF);\n res.addProperty(\"size\", IVARIANT(box.size()));\n res.addProperty(\"envelope\", IVARIANT(envlope));\n res.addProperty(\"coordinatesystem\", IVARIANT(inputGC->coordinateSystem()));\n res.addProperty(\"name\", outputBaseName);\n res.addProperty(\"centerofpixel\",inputGC->georeference()->centerOfPixel());\n IGeoReference grf;\n grf.prepare(res);\n outputGC->georeference(grf);\n outputGC->envelope(envlope);\n }\n\n return sPREPARED;\n}\n\nquint64 AggregateRaster::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/aggregateraster\");\n Resource res(QUrl(url), itOPERATIONMETADATA);\n res.addProperty(\"namespace\",\"ilwis\");\n res.addProperty(\"longname\",\"aggregateraster raster coverage\");\n res.addProperty(\"syntax\",\"resample(inputgridcoverage,{Avg|Max|Med|Min|Prd|Std|Sum}, groupsize,changegeometry[,new georefname])\");\n res.addProperty(\"inparameters\",\"4|5\");\n res.addProperty(\"pin_1_type\", itGRID);\n res.addProperty(\"pin_1_name\", TR(\"input gridcoverage\"));\n res.addProperty(\"pin_1_desc\",TR(\"input gridcoverage with domain any domain\"));\n res.addProperty(\"pin_2_type\", itSTRING);\n res.addProperty(\"pin_2_name\", TR(\"Aggregation Method\"));\n res.addProperty(\"pin_2_desc\",TR(\"the method how pixels inside a group will be accumulated\"));\n res.addProperty(\"pin_3_type\", itINTEGER);\n res.addProperty(\"pin_3_name\", TR(\"Groupsize\"));\n res.addProperty(\"pin_3_desc\",TR(\"The size of the block used to aggregate\"));\n res.addProperty(\"pin_4_type\", itBOOL);\n res.addProperty(\"pin_4_name\", TR(\"change geometry\"));\n res.addProperty(\"pin_4_desc\",TR(\"The aggregation can either create a map with a reduced size proportional to de block size or use the same geometry size but fill all pixels in the block with the aggregate\"));\n res.addProperty(\"pin_5_type\", itSTRING);\n res.addProperty(\"pin_5_name\", TR(\"georeference name\"));\n res.addProperty(\"pin_5_desc\",TR(\"optional parameter indicating a name for the new geometry, else the name will come from the output grid\"));\n res.addProperty(\"outparameters\",1);\n res.addProperty(\"pout_1_type\", itGRID);\n res.addProperty(\"pout_1_name\", TR(\"output gridcoverage\"));\n res.addProperty(\"pout_1_desc\",TR(\"output gridcoverage with the domain of the input map\"));\n res.prepare();\n url += \"=\" + QString::number(res.id());\n res.setUrl(url);\n\n mastercatalog()->addItems({res});\n return res.id();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n MIT License\n\n Copyright (c) 2017-2018, Alexey Dynda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \"ssd1306_spi_hw.h\"\n#include \"ssd1306_spi.h\"\n\n#include \"intf\/ssd1306_interface.h\"\n#include \"lcd\/lcd_common.h\"\n#include \"hal\/io.h\"\n\n#include <stdlib.h>\n\n#ifdef SSD1306_SPI_SUPPORTED\n\/* STANDARD branch *\/\n #include <SPI.h>\n\nvoid ssd1306_spiConfigure_hw()\n{\n SPI.begin();\n}\n\nstatic void ssd1306_spiClose_hw()\n{\n}\n\nstatic void ssd1306_spiStart_hw()\n{\n SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));\n if (s_ssd1306_cs >= 0)\n {\n digitalWrite(s_ssd1306_cs,LOW);\n }\n}\n\nstatic void ssd1306_spiStop_hw()\n{\n if (s_ssd1306_cs >= 0)\n {\n digitalWrite(s_ssd1306_cs, HIGH);\n }\n if (g_lcd_type == LCD_TYPE_PCD8544)\n {\n digitalWrite(s_ssd1306_dc, LOW);\n SPI.transfer( 0x00 ); \/\/ Send NOP command to allow last data byte to pass (bug in PCD8544?)\n \/\/ ssd1306 E3h is NOP command\n }\n SPI.endTransaction();\n}\n\nstatic void ssd1306_spiSendByte_hw(uint8_t data)\n{\n SPI.transfer(data);\n}\n\nvoid ssd1306_spiInit_hw(int8_t cesPin, int8_t dcPin)\n{\n if (cesPin >=0) pinMode(cesPin, OUTPUT);\n if (dcPin >= 0) pinMode(dcPin, OUTPUT);\n if (cesPin) s_ssd1306_cs = cesPin;\n if (dcPin) s_ssd1306_dc = dcPin;\n ssd1306_startTransmission = ssd1306_spiStart_hw;\n ssd1306_endTransmission = ssd1306_spiStop_hw;\n ssd1306_sendByte = ssd1306_spiSendByte_hw;\n ssd1306_closeInterface = ssd1306_spiClose_hw;\n ssd1306_commandStart = ssd1306_spiCommandStart;\n ssd1306_dataStart = ssd1306_spiDataStart;\n}\n\n#endif\n\n\n<commit_msg>SPI speed increase<commit_after>\/*\n MIT License\n\n Copyright (c) 2017-2018, Alexey Dynda\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*\/\n\n#include \"ssd1306_spi_hw.h\"\n#include \"ssd1306_spi.h\"\n\n#include \"intf\/ssd1306_interface.h\"\n#include \"lcd\/lcd_common.h\"\n#include \"hal\/io.h\"\n\n#include <stdlib.h>\n\n#ifdef SSD1306_SPI_SUPPORTED\n\/* STANDARD branch *\/\n #include <SPI.h>\n\nvoid ssd1306_spiConfigure_hw()\n{\n SPI.begin();\n}\n\nstatic void ssd1306_spiClose_hw()\n{\n}\n\nstatic void ssd1306_spiStart_hw()\n{\n \/* anyway, oled ssd1331 cannot work faster, clock cycle should be > 150ns: *\n * 1s \/ 150ns ~ 6.7MHz *\/\n SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));\n if (s_ssd1306_cs >= 0)\n {\n digitalWrite(s_ssd1306_cs,LOW);\n }\n}\n\nstatic void ssd1306_spiStop_hw()\n{\n if (s_ssd1306_cs >= 0)\n {\n digitalWrite(s_ssd1306_cs, HIGH);\n }\n if (g_lcd_type == LCD_TYPE_PCD8544)\n {\n digitalWrite(s_ssd1306_dc, LOW);\n SPI.transfer( 0x00 ); \/\/ Send NOP command to allow last data byte to pass (bug in PCD8544?)\n \/\/ ssd1306 E3h is NOP command\n }\n SPI.endTransaction();\n}\n\nstatic void ssd1306_spiSendByte_hw(uint8_t data)\n{\n SPI.transfer(data);\n}\n\nvoid ssd1306_spiInit_hw(int8_t cesPin, int8_t dcPin)\n{\n if (cesPin >=0) pinMode(cesPin, OUTPUT);\n if (dcPin >= 0) pinMode(dcPin, OUTPUT);\n if (cesPin) s_ssd1306_cs = cesPin;\n if (dcPin) s_ssd1306_dc = dcPin;\n ssd1306_startTransmission = ssd1306_spiStart_hw;\n ssd1306_endTransmission = ssd1306_spiStop_hw;\n ssd1306_sendByte = ssd1306_spiSendByte_hw;\n ssd1306_closeInterface = ssd1306_spiClose_hw;\n ssd1306_commandStart = ssd1306_spiCommandStart;\n ssd1306_dataStart = ssd1306_spiDataStart;\n}\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Touhou Community Reliant Automatic Patcher\n * Main DLL\n *\n * ----\n *\n * Persistent string storage, and translation of hardcoded strings.\n *\/\n\n#include \"thcrap.h\"\n#include <unordered_map>\n\n\/\/\/ Detour chains\n\/\/\/ -------------\nW32U8_DETOUR_CHAIN_DEF(MessageBox);\nW32U8_DETOUR_CHAIN_DEF(FindFirstFile);\n\/\/\/ -------------\n\n\/\/ Since we can't use the jsondata module to make this repatchable,\n\/\/ we only need to keep the last parsed JSON object around to\n\/\/ provide the \"backing memory\" for the ID strings.\njson_t *backing_obj = nullptr;\n\n\/\/ Length-prefixed string object used for persistent storage\ntypedef struct {\n\tsize_t len;\n\tchar str;\n} storage_string_t;\n\nstd::unordered_map<size_t, storage_string_t *> strings_storage;\n\nSRWLOCK stringlocs_srwlock = {SRWLOCK_INIT};\nstd::unordered_map<const char *, const char *> stringlocs;\n\n#define addr_key_len 2 + (sizeof(void*) * 2) + 1\n\nvoid stringlocs_reparse(void)\n{\n\tjson_t* new_obj = stack_game_json_resolve(\"stringlocs.js\", NULL);\n\tconst char *key;\n\tconst json_t *val;\n\n\tAcquireSRWLockExclusive(&stringlocs_srwlock);\n\tstringlocs.clear();\n\n\tjson_object_foreach(new_obj, key, val) {\n\t\t\/\/ TODO: For now, we're nagging developers with one message box for\n\t\t\/\/ every single parse error. It'd certainly be better if we gathered\n\t\t\/\/ all errors into a single message box to be printed at the end of\n\t\t\/\/ the parsing, and even had a somewhat generic solution if we do\n\t\t\/\/ more of these conversions.\n#define stringlocs_log_error(msg) \\\n\tlog_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \\\n\t\t\"Error parsing stringlocs.js: \\\"%s\\\" \" msg\".\", key, sizeof(size_t) * 8 \\\n\t)\n\n\t\tif(!json_is_string(val)) {\n\t\t\tstringlocs_log_error(\"must be a JSON string\");\n\t\t\tcontinue;\n\t\t}\n\t\tstr_address_ret_t addr_ret;\n\t\tauto *addr = (const char *)str_address_value(key, NULL, &addr_ret);\n\t\tif(addr_ret.error == STR_ADDRESS_ERROR_NONE) {\n\t\t\tstringlocs[addr] = json_string_value(val);\n\t\t}\n\t\tif(addr_ret.error & STR_ADDRESS_ERROR_OVERFLOW) {\n\t\t\tstringlocs_log_error(\"exceeds %d bits\");\n\t\t}\n\t\tif(addr_ret.error & STR_ADDRESS_ERROR_GARBAGE) {\n\t\t\tstringlocs_log_error(\"has garbage at the end\");\n\t\t}\n#undef stringlocs_log_error\n\t}\n\n\tjson_decref(backing_obj);\n\tbacking_obj = new_obj;\n\n\tReleaseSRWLockExclusive(&stringlocs_srwlock);\n}\n\nconst char* strings_id(const char *str)\n{\n\tconst char *ret = nullptr;\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id_key = stringlocs.find(str);\n\tif(id_key != stringlocs.end()) {\n\t\tret = id_key->second;\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\treturn ret;\n}\n\nconst json_t* strings_get(const char *id)\n{\n\treturn json_object_get(jsondata_get(\"stringdefs.js\"), id);\n}\n\nstringref_t strings_get_fallback(const string_named_t& sn)\n{\n\tauto ret = strings_get(sn.id);\n\tif(!json_is_string(ret)) {\n\t\treturn sn.fallback;\n\t}\n\treturn ret;\n}\n\nconst char* strings_lookup(const char *in, size_t *out_len)\n{\n\tconst char *ret = in;\n\n\tif(!in) {\n\t\treturn in;\n\t}\n\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id = strings_id(in);\n\tif(id) {\n\t\tauto *new_str = json_string_value(strings_get(id));\n\t\tif(new_str && new_str[0]) {\n\t\t\tret = new_str;\n\t\t}\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\n\tif(out_len) {\n\t\t*out_len = strlen(ret);\n\t}\n\treturn ret;\n}\n\nvoid strings_va_lookup(va_list va, const char *format)\n{\n\tconst char *p = format;\n\twhile(*p) {\n\t\tprintf_format_t fmt;\n\t\tint i;\n\n\t\t\/\/ Skip characters before '%'\n\t\tfor(; *p && *p != '%'; p++);\n\t\tif(!*p) {\n\t\t\tbreak;\n\t\t}\n\t\t\/\/ *p == '%' here\n\t\tp++;\n\n\t\t\/\/ output a single '%' character\n\t\tif(*p == '%') {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tp = printf_format_parse(&fmt, p);\n\t\tfor(i = 0; i < fmt.argc_before_type; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t\tif(fmt.type == 's' || fmt.type == 'S') {\n\t\t\t*(const char**)va = strings_lookup(*(const char**)va, NULL);\n\t\t}\n\t\tfor(i = 0; i < fmt.type_size_in_ints; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t}\n}\n\nchar* strings_storage_get(const size_t slot, size_t min_len)\n{\n\tauto stored = strings_storage.find(slot);\n\tauto *ret = stored != strings_storage.end() ? stored->second : nullptr;\n\n\t\/\/ MSVCRT's realloc implementation moves the buffer every time, even if the\n\t\/\/ new length is shorter...\n\tif(ret == nullptr || (min_len && ret->len < min_len)) {\n\t\tauto *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t));\n\t\t\/\/ Yes, this correctly handles a realloc failure.\n\t\tif(ret_new) {\n\t\t\tret_new->len = min_len;\n\t\t\tif(!ret) {\n\t\t\t\tret_new->str = 0;\n\t\t\t}\n\t\t\tstrings_storage[slot] = ret_new;\n\t\t\tret = ret_new;\n\t\t}\n\t}\n\tif(ret) {\n\t\treturn &ret->str;\n\t}\n\treturn nullptr;\n}\n\nconst char* strings_vsprintf(const size_t slot, const char *format, va_list va)\n{\n\tchar *ret = NULL;\n\tsize_t str_len;\n\n\tformat = strings_lookup(format, NULL);\n\tstrings_va_lookup(va, format);\n\n\tif(!format) {\n\t\treturn NULL;\n\t}\n\tstr_len = _vscprintf(format, va) + 1;\n\n\tret = strings_storage_get(slot, str_len);\n\tif(ret) {\n\t\tvsprintf(ret, format, va);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn format;\n}\n\nconst char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va)\n{\n\treturn strings_vsprintf(slot, format, va);\n}\n\nconst char* strings_sprintf(const size_t slot, const char *format, ...)\n{\n\tva_list va;\n\tconst char *ret;\n\tva_start(va, format);\n\tret = strings_vsprintf(slot, format, va);\n\treturn ret;\n}\n\nconst char* strings_strclr(const size_t slot)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tif(ret) {\n\t\tret[0] = 0;\n\t}\n\treturn ret;\n}\n\nconst char* strings_strcat(const size_t slot, const char *src)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tsize_t ret_len = strlen(ret);\n\tsize_t src_len;\n\n\tsrc = strings_lookup(src, &src_len);\n\n\tret = strings_storage_get(slot, ret_len + src_len + 1);\n\tif(ret) {\n\t\tstrncpy(ret + ret_len, src, src_len + 1);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn src;\n}\n\nconst char* strings_replace(const size_t slot, const char *src, const char *dst)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tdst = dst ? dst : \"\";\n\tif(src && ret) {\n\t\tsize_t src_len = strlen(src);\n\t\tsize_t dst_len = strlen(dst);\n\t\twhile(ret) {\n\t\t\tchar *src_pos = NULL;\n\t\t\tchar *copy_pos = NULL;\n\t\t\tchar *rest_pos = NULL;\n\t\t\tsize_t ret_len = strlen(ret);\n\t\t\t\/\/ We do this first since the string address might change after\n\t\t\t\/\/ reallocation, thus invalidating the strstr() result\n\t\t\tret = strings_storage_get(slot, ret_len + dst_len);\n\t\t\tif(!ret) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsrc_pos = strstr(ret, src);\n\t\t\tif(!src_pos) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy_pos = src_pos + dst_len;\n\t\t\trest_pos = src_pos + src_len;\n\t\t\tmemmove(copy_pos, rest_pos, strlen(rest_pos) + 1);\n\t\t\tmemcpy(src_pos, dst, dst_len);\n\t\t}\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn ret ? ret : dst;\n}\n\n\/\/\/ String lookup hooks\n\/\/\/ -------------------\nint WINAPI strings_MessageBoxA(\n\tHWND hWnd,\n\tLPCSTR lpText,\n\tLPCSTR lpCaption,\n\tUINT uType\n)\n{\n\tlpText = strings_lookup(lpText, NULL);\n\tlpCaption = strings_lookup(lpCaption, NULL);\n\treturn chain_MessageBoxU(hWnd, lpText, lpCaption, uType);\n}\n\nHANDLE WINAPI strings_FindFirstFileA(\n\tLPCSTR lpFileName,\n\tLPWIN32_FIND_DATAA lpFindFileData\n)\n{\n\treturn chain_FindFirstFileU(strings_lookup(lpFileName, NULL), lpFindFileData);\n}\n\/\/\/ -------------------\n\nvoid strings_mod_init(void)\n{\n\tjsondata_add(\"stringdefs.js\");\n\tstringlocs_reparse();\n}\n\nvoid strings_mod_detour(void)\n{\n\tdetour_chain(\"user32.dll\", 1,\n\t\t\"MessageBoxA\", strings_MessageBoxA, &chain_MessageBoxU,\n\t\tNULL\n\t);\n\tdetour_chain(\"kernel32.dll\", 1,\n\t\t\"FindFirstFileA\", strings_FindFirstFileA, &chain_FindFirstFileU,\n\t\tNULL\n\t);\n}\n\nvoid strings_mod_repatch(json_t *files_changed)\n{\n\tconst char *key;\n\tconst json_t *val;\n\tjson_object_foreach(files_changed, key, val) {\n\t\tif(strstr(key, \"\/stringlocs.\")) {\n\t\t\tstringlocs_reparse();\n\t\t}\n\t}\n}\n\nvoid strings_mod_exit(void)\n{\n\tfor(auto& i : strings_storage) {\n\t\tSAFE_FREE(i.second);\n\t}\n\tstrings_storage.clear();\n\tstringlocs.clear();\n\tbacking_obj = json_decref_safe(backing_obj);\n}\n<commit_msg>Allow changing hardcoded stings for CreateFileA calls<commit_after>\/**\n * Touhou Community Reliant Automatic Patcher\n * Main DLL\n *\n * ----\n *\n * Persistent string storage, and translation of hardcoded strings.\n *\/\n\n#include \"thcrap.h\"\n#include <unordered_map>\n\n\/\/\/ Detour chains\n\/\/\/ -------------\nW32U8_DETOUR_CHAIN_DEF(MessageBox);\nW32U8_DETOUR_CHAIN_DEF(FindFirstFile);\nW32U8_DETOUR_CHAIN_DEF(CreateFile);\n\n\/\/\/ -------------\n\n\/\/ Since we can't use the jsondata module to make this repatchable,\n\/\/ we only need to keep the last parsed JSON object around to\n\/\/ provide the \"backing memory\" for the ID strings.\njson_t *backing_obj = nullptr;\n\n\/\/ Length-prefixed string object used for persistent storage\ntypedef struct {\n\tsize_t len;\n\tchar str;\n} storage_string_t;\n\nstd::unordered_map<size_t, storage_string_t *> strings_storage;\n\nSRWLOCK stringlocs_srwlock = {SRWLOCK_INIT};\nstd::unordered_map<const char *, const char *> stringlocs;\n\n#define addr_key_len 2 + (sizeof(void*) * 2) + 1\n\nvoid stringlocs_reparse(void)\n{\n\tjson_t* new_obj = stack_game_json_resolve(\"stringlocs.js\", NULL);\n\tconst char *key;\n\tconst json_t *val;\n\n\tAcquireSRWLockExclusive(&stringlocs_srwlock);\n\tstringlocs.clear();\n\n\tjson_object_foreach(new_obj, key, val) {\n\t\t\/\/ TODO: For now, we're nagging developers with one message box for\n\t\t\/\/ every single parse error. It'd certainly be better if we gathered\n\t\t\/\/ all errors into a single message box to be printed at the end of\n\t\t\/\/ the parsing, and even had a somewhat generic solution if we do\n\t\t\/\/ more of these conversions.\n#define stringlocs_log_error(msg) \\\n\tlog_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \\\n\t\t\"Error parsing stringlocs.js: \\\"%s\\\" \" msg\".\", key, sizeof(size_t) * 8 \\\n\t)\n\n\t\tif(!json_is_string(val)) {\n\t\t\tstringlocs_log_error(\"must be a JSON string\");\n\t\t\tcontinue;\n\t\t}\n\t\tstr_address_ret_t addr_ret;\n\t\tauto *addr = (const char *)str_address_value(key, NULL, &addr_ret);\n\t\tif(addr_ret.error == STR_ADDRESS_ERROR_NONE) {\n\t\t\tstringlocs[addr] = json_string_value(val);\n\t\t}\n\t\tif(addr_ret.error & STR_ADDRESS_ERROR_OVERFLOW) {\n\t\t\tstringlocs_log_error(\"exceeds %d bits\");\n\t\t}\n\t\tif(addr_ret.error & STR_ADDRESS_ERROR_GARBAGE) {\n\t\t\tstringlocs_log_error(\"has garbage at the end\");\n\t\t}\n#undef stringlocs_log_error\n\t}\n\n\tjson_decref(backing_obj);\n\tbacking_obj = new_obj;\n\n\tReleaseSRWLockExclusive(&stringlocs_srwlock);\n}\n\nconst char* strings_id(const char *str)\n{\n\tconst char *ret = nullptr;\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id_key = stringlocs.find(str);\n\tif(id_key != stringlocs.end()) {\n\t\tret = id_key->second;\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\treturn ret;\n}\n\nconst json_t* strings_get(const char *id)\n{\n\treturn json_object_get(jsondata_get(\"stringdefs.js\"), id);\n}\n\nstringref_t strings_get_fallback(const string_named_t& sn)\n{\n\tauto ret = strings_get(sn.id);\n\tif(!json_is_string(ret)) {\n\t\treturn sn.fallback;\n\t}\n\treturn ret;\n}\n\nconst char* strings_lookup(const char *in, size_t *out_len)\n{\n\tconst char *ret = in;\n\n\tif(!in) {\n\t\treturn in;\n\t}\n\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id = strings_id(in);\n\tif(id) {\n\t\tauto *new_str = json_string_value(strings_get(id));\n\t\tif(new_str && new_str[0]) {\n\t\t\tret = new_str;\n\t\t}\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\n\tif(out_len) {\n\t\t*out_len = strlen(ret);\n\t}\n\treturn ret;\n}\n\nvoid strings_va_lookup(va_list va, const char *format)\n{\n\tconst char *p = format;\n\twhile(*p) {\n\t\tprintf_format_t fmt;\n\t\tint i;\n\n\t\t\/\/ Skip characters before '%'\n\t\tfor(; *p && *p != '%'; p++);\n\t\tif(!*p) {\n\t\t\tbreak;\n\t\t}\n\t\t\/\/ *p == '%' here\n\t\tp++;\n\n\t\t\/\/ output a single '%' character\n\t\tif(*p == '%') {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tp = printf_format_parse(&fmt, p);\n\t\tfor(i = 0; i < fmt.argc_before_type; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t\tif(fmt.type == 's' || fmt.type == 'S') {\n\t\t\t*(const char**)va = strings_lookup(*(const char**)va, NULL);\n\t\t}\n\t\tfor(i = 0; i < fmt.type_size_in_ints; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t}\n}\n\nchar* strings_storage_get(const size_t slot, size_t min_len)\n{\n\tauto stored = strings_storage.find(slot);\n\tauto *ret = stored != strings_storage.end() ? stored->second : nullptr;\n\n\t\/\/ MSVCRT's realloc implementation moves the buffer every time, even if the\n\t\/\/ new length is shorter...\n\tif(ret == nullptr || (min_len && ret->len < min_len)) {\n\t\tauto *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t));\n\t\t\/\/ Yes, this correctly handles a realloc failure.\n\t\tif(ret_new) {\n\t\t\tret_new->len = min_len;\n\t\t\tif(!ret) {\n\t\t\t\tret_new->str = 0;\n\t\t\t}\n\t\t\tstrings_storage[slot] = ret_new;\n\t\t\tret = ret_new;\n\t\t}\n\t}\n\tif(ret) {\n\t\treturn &ret->str;\n\t}\n\treturn nullptr;\n}\n\nconst char* strings_vsprintf(const size_t slot, const char *format, va_list va)\n{\n\tchar *ret = NULL;\n\tsize_t str_len;\n\n\tformat = strings_lookup(format, NULL);\n\tstrings_va_lookup(va, format);\n\n\tif(!format) {\n\t\treturn NULL;\n\t}\n\tstr_len = _vscprintf(format, va) + 1;\n\n\tret = strings_storage_get(slot, str_len);\n\tif(ret) {\n\t\tvsprintf(ret, format, va);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn format;\n}\n\nconst char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va)\n{\n\treturn strings_vsprintf(slot, format, va);\n}\n\nconst char* strings_sprintf(const size_t slot, const char *format, ...)\n{\n\tva_list va;\n\tconst char *ret;\n\tva_start(va, format);\n\tret = strings_vsprintf(slot, format, va);\n\treturn ret;\n}\n\nconst char* strings_strclr(const size_t slot)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tif(ret) {\n\t\tret[0] = 0;\n\t}\n\treturn ret;\n}\n\nconst char* strings_strcat(const size_t slot, const char *src)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tsize_t ret_len = strlen(ret);\n\tsize_t src_len;\n\n\tsrc = strings_lookup(src, &src_len);\n\n\tret = strings_storage_get(slot, ret_len + src_len + 1);\n\tif(ret) {\n\t\tstrncpy(ret + ret_len, src, src_len + 1);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn src;\n}\n\nconst char* strings_replace(const size_t slot, const char *src, const char *dst)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tdst = dst ? dst : \"\";\n\tif(src && ret) {\n\t\tsize_t src_len = strlen(src);\n\t\tsize_t dst_len = strlen(dst);\n\t\twhile(ret) {\n\t\t\tchar *src_pos = NULL;\n\t\t\tchar *copy_pos = NULL;\n\t\t\tchar *rest_pos = NULL;\n\t\t\tsize_t ret_len = strlen(ret);\n\t\t\t\/\/ We do this first since the string address might change after\n\t\t\t\/\/ reallocation, thus invalidating the strstr() result\n\t\t\tret = strings_storage_get(slot, ret_len + dst_len);\n\t\t\tif(!ret) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsrc_pos = strstr(ret, src);\n\t\t\tif(!src_pos) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy_pos = src_pos + dst_len;\n\t\t\trest_pos = src_pos + src_len;\n\t\t\tmemmove(copy_pos, rest_pos, strlen(rest_pos) + 1);\n\t\t\tmemcpy(src_pos, dst, dst_len);\n\t\t}\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn ret ? ret : dst;\n}\n\n\/\/\/ String lookup hooks\n\/\/\/ -------------------\nint WINAPI strings_MessageBoxA(\n\tHWND hWnd,\n\tLPCSTR lpText,\n\tLPCSTR lpCaption,\n\tUINT uType\n)\n{\n\tlpText = strings_lookup(lpText, NULL);\n\tlpCaption = strings_lookup(lpCaption, NULL);\n\treturn chain_MessageBoxU(hWnd, lpText, lpCaption, uType);\n}\n\nHANDLE WINAPI strings_FindFirstFileA(\n\tLPCSTR lpFileName,\n\tLPWIN32_FIND_DATAA lpFindFileData\n)\n{\n\treturn chain_FindFirstFileU(strings_lookup(lpFileName, NULL), lpFindFileData);\n}\n\nHANDLE WINAPI strings_CreateFileA(\n\tLPCSTR lpFileName,\n\tDWORD dwDesiredAccess,\n\tDWORD dwShareMode,\n\tLPSECURITY_ATTRIBUTES lpSecurityAttributes,\n\tDWORD dwCreationDisposition,\n\tDWORD dwFlagsAndAttributes,\n\tHANDLE hTemplateFile\n)\n{\n\treturn chain_CreateFileU(\n\t\tstrings_lookup(lpFileName, NULL),\n\t\tdwDesiredAccess,\n\t\tdwShareMode,\n\t\tlpSecurityAttributes,\n\t\tdwCreationDisposition,\n\t\tdwFlagsAndAttributes,\n\t\thTemplateFile\n\t);\n}\n\/\/\/ -------------------\n\nvoid strings_mod_init(void)\n{\n\tjsondata_add(\"stringdefs.js\");\n\tstringlocs_reparse();\n}\n\nvoid strings_mod_detour(void)\n{\n\tdetour_chain(\"user32.dll\", 1,\n\t\t\"MessageBoxA\", strings_MessageBoxA, &chain_MessageBoxU,\n\t\tNULL\n\t);\n\tdetour_chain(\"kernel32.dll\", 2,\n\t\t\"FindFirstFileA\", strings_FindFirstFileA, &chain_FindFirstFileU,\n\t\t\"CreateFileA\", strings_CreateFileA, &chain_CreateFileU,\n\t\tNULL\n\t);\n}\n\nvoid strings_mod_repatch(json_t *files_changed)\n{\n\tconst char *key;\n\tconst json_t *val;\n\tjson_object_foreach(files_changed, key, val) {\n\t\tif(strstr(key, \"\/stringlocs.\")) {\n\t\t\tstringlocs_reparse();\n\t\t}\n\t}\n}\n\nvoid strings_mod_exit(void)\n{\n\tfor(auto& i : strings_storage) {\n\t\tSAFE_FREE(i.second);\n\t}\n\tstrings_storage.clear();\n\tstringlocs.clear();\n\tbacking_obj = json_decref_safe(backing_obj);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VG_GFF_READER_HPP_INCLUDED\n#define VG_GFF_READER_HPP_INCLUDED\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <map>\n\nnamespace vg {\n \n using namespace std;\n \n \/**\n * A package of the information contained in a GFF3 record. The null \".\" entries in a\n * a GFF are parsed into empty strings or the default values of the numerical fields\n * as given below.\n *\/\n struct GFFRecord {\n public:\n GFFRecord() = default;\n ~GFFRecord() = default;\n \n string sequence_id;\n string source;\n string type;\n \/\/ 0-based indexing, unlike the actual GFF standard\n int64_t start = -1;\n \/\/ 0-based, inclusive\n int64_t end = -1;\n double score = numeric_limits<double>::quiet_NaN();\n bool strand_is_rev = false;\n int32_t phase = -1;\n string attributes;\n \n map<string, string> parse_attributes();\n };\n \n \/**\n * A class that can parse and iterate over a GFF3 file.\n *\/\n class GFFReader {\n public:\n GFFReader(istream& in);\n ~GFFReader() = default;\n \n void for_each_gff_record(function<void(const GFFRecord&)>& lambda);\n \n private:\n istream& in;\n };\n\n}\n\n#endif\n<commit_msg>add gcc dependencies in header<commit_after>#ifndef VG_GFF_READER_HPP_INCLUDED\n#define VG_GFF_READER_HPP_INCLUDED\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <map>\n#include <limits>\n#include <functional>\n\nnamespace vg {\n \n using namespace std;\n \n \/**\n * A package of the information contained in a GFF3 record. The null \".\" entries in a\n * a GFF are parsed into empty strings or the default values of the numerical fields\n * as given below.\n *\/\n struct GFFRecord {\n public:\n GFFRecord() = default;\n ~GFFRecord() = default;\n \n string sequence_id;\n string source;\n string type;\n \/\/ 0-based indexing, unlike the actual GFF standard\n int64_t start = -1;\n \/\/ 0-based, inclusive\n int64_t end = -1;\n double score = numeric_limits<double>::quiet_NaN();\n bool strand_is_rev = false;\n int32_t phase = -1;\n string attributes;\n \n map<string, string> parse_attributes();\n };\n \n \/**\n * A class that can parse and iterate over a GFF3 file.\n *\/\n class GFFReader {\n public:\n GFFReader(istream& in);\n ~GFFReader() = default;\n \n void for_each_gff_record(function<void(const GFFRecord&)>& lambda);\n \n private:\n istream& in;\n };\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef thunder_utils_path_hpp__\n#define thunder_utils_path_hpp__\n\n#include <array>\n#include <iostream>\n\n#if defined(_WIN32)\n #include <direct.h>\n #include <windows.h>\n#elif defined(__linux__) || defined(__CYGWIN__)\n #include <limits.h>\n #include <unistd.h>\n #define HINSTANCE unsigned int\n#else\n #error This OS is currently not supported\n#endif\n\nnamespace thunder\n{\nnamespace utils\n{\nnamespace path\n{\n inline std::string get_executable_path(HINSTANCE instance = nullptr)\n {\n#if defined(_WIN32)\n constexpr auto pathlen = MAX_PATH;\n#elif defined(__linux__) || defined(__CYGWIN__)\n constexpr auto pathlen = PATH_MAX;\n#endif\n std::array<char, pathlen> buffer = { 0 };\n\n#if defined(_WIN32)\n if (::GetModuleFileNameA(instance, buffer.data(), pathlen) == 0)\n#elif defined(__linux__) || defined(__CYGWIN__)\n if (::readlink(\"\/proc\/self\/exe\", buffer, pathlen) == -1)\n#endif\n std::cerr << \"error while getting executable path\" << std::endl;\n\n auto executable_path = std::string(buffer.data());\n auto executable_directory = executable_path.substr(0, executable_path.find_last_of(\"\\\\\"));\n\n return std::move(executable_directory);\n }\n\n inline std::string get_working_directory()\n {\n#if defined(_WIN32)\n constexpr auto pathlen = MAX_PATH;\n#elif defined(__linux__) || defined(__CYGWIN__)\n constexpr auto pathlen = PATH_MAX;\n#endif\n std::string working_directory{ };\n std::array<char, pathlen> buffer = { 0 };\n \n#if defined(_WIN32)\n if ( ::_getcwd(buffer.data(), MAX_PATH) != nullptr )\n working_directory = std::string( buffer.data() );\n#elif defined(__linux__) || defined(__CYGWIN__)\n if ( ::getcwd(buffer, PATH_MAX) != nullptr )\n working_directory = std::string(buffer);\n#endif\n else\n std::cerr << \"could not get working directory\" << std::endl;\n\n return std::move(working_directory);\n }\n};\n};\n};\n\n#endif \/\/ thunder_utils_path_hpp__\n<commit_msg>Make utils::path::get_working_directory more general<commit_after>#ifndef thunder_utils_path_hpp__\n#define thunder_utils_path_hpp__\n\n#include <array>\n#include <iostream>\n\n#if defined(_WIN32)\n #include <direct.h>\n #include <windows.h>\n#elif defined(__linux__) || defined(__CYGWIN__)\n #include <limits.h>\n #include <unistd.h>\n #define HINSTANCE unsigned int\n#else\n #error This OS is currently not supported\n#endif\n\nnamespace thunder\n{\nnamespace utils\n{\nnamespace path\n{\n inline std::string get_executable_path(HINSTANCE instance = nullptr)\n {\n#if defined(_WIN32)\n constexpr auto pathlen = MAX_PATH;\n#elif defined(__linux__) || defined(__CYGWIN__)\n constexpr auto pathlen = PATH_MAX;\n#endif\n std::array<char, pathlen> buffer = { 0 };\n\n#if defined(_WIN32)\n if (::GetModuleFileNameA(instance, buffer.data(), pathlen) == 0)\n#elif defined(__linux__) || defined(__CYGWIN__)\n if (::readlink(\"\/proc\/self\/exe\", buffer, pathlen) == -1)\n#endif\n std::cerr << \"error while getting executable path\" << std::endl;\n\n auto executable_path = std::string(buffer.data());\n auto executable_directory = executable_path.substr(0, executable_path.find_last_of(\"\\\\\"));\n\n return std::move(executable_directory);\n }\n\n inline std::string get_working_directory()\n {\n#if defined(_WIN32)\n constexpr auto pathlen = MAX_PATH;\n#elif defined(__linux__) || defined(__CYGWIN__)\n constexpr auto pathlen = PATH_MAX;\n#endif\n std::string working_directory{ };\n std::array<char, pathlen> buffer = { 0 };\n \n#if defined(_WIN32)\n if ( ::_getcwd(buffer.data(), MAX_PATH) != nullptr )\n\t\t\tworking_directory = std::string{ buffer.data() };\n#elif defined(__linux__) || defined(__CYGWIN__)\n if ( ::getcwd(buffer, PATH_MAX) != nullptr )\n working_directory = std::string(buffer);\n#endif\n else\n std::cerr << \"could not get working directory\" << std::endl;\n\n\t\tworking_directory += '\/';\n\n return std::move(working_directory);\n }\n};\n};\n};\n\n#endif \/\/ thunder_utils_path_hpp__\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <random>\n\n#include \"os\/task_t.h\"\n#include \"os\/task_system_t.h\"\n#include \"os\/parse.h\"\n#include \"os\/generator.h\"\n#include \"os\/scheduler.h\"\n#include \"lib\/io.h\"\n#include \"lib\/num.h\"\n\nint main(){\n\tstd::cout << \"Hello world!\" << std::endl;\n\n\t{\n\t\tos::task_t task;\n\t\tstd::cout << task << std::endl;\n\t}\n\n\t{\n\t\tos::task_system_t task_system(5);\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tchar c = ifs.get();\n\t\twhile (ifs.good()){\n\t\t\tstd::cout << c;\n\t\t\tc = ifs.get();\n\t\t}\n\t\tifs.close();\n\t\tstd::cout << '\\n';\n\t}\n\n\t{\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tos::parse_task_system_stream(ifs, task_system);\n\t\tifs.close();\n\t\t\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tuint seed = std::chrono::system_clock::now().time_since_epoch().count();\n\t\tstd::default_random_engine generator(seed);\n\t\tstd::uniform_int_distribution<uint> distribution(0,100);\n\t\tuint usage = 70;\n\t\tuint n = 5;\n\t\tos::generate_task_system(generator, distribution, usage, n, task_system);\n\n\t\tstd::cout << task_system << std::endl;\n\t\tuint u = 0;\n\t\tfor(auto task : task_system){\n\t\t\tu += task.wcet;\n\t\t}\n\t\t\n\t\tstd::cout << u << std::endl;\n\t}\n\treturn 0;\n}<commit_msg>clean<commit_after>#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <random>\n\n#include \"os\/task_t.h\"\n#include \"os\/task_system_t.h\"\n#include \"os\/parse.h\"\n#include \"os\/generator.h\"\n#include \"os\/scheduler.h\"\n#include \"lib\/io.h\"\n#include \"lib\/num.h\"\n\nint main(){\n\tstd::cout << \"Hello world!\" << std::endl;\n\n\t{\n\t\tstd::cout << \"TASK PRINT TEST\" << std::endl;\n\t\tos::task_t task;\n\t\tstd::cout << task << std::endl;\n\t}\n\n\t{\n\t\tstd::cout << \"TASK SYSTEM PRINT TEST\" << std::endl;\n\t\tos::task_system_t task_system(5);\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tstd::cout << \"READ FILE TEST\" << std::endl;\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tchar c = ifs.get();\n\t\twhile (ifs.good()){\n\t\t\tstd::cout << c;\n\t\t\tc = ifs.get();\n\t\t}\n\t\tifs.close();\n\t\tstd::cout << '\\n';\n\t}\n\n\t{\n\t\tstd::cout << \"PARSE FILE TEST\" << std::endl;\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tos::parse_task_system_stream(ifs, task_system);\n\t\tifs.close();\n\t\t\n\t\tstd::cout << task_system << std::endl;\n\t}\n\n\t{\n\t\tstd::cout << \"GENERATE SYSTEM TEST\" << std::endl;\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tuint seed = std::chrono::system_clock::now().time_since_epoch().count();\n\t\tstd::default_random_engine generator(seed);\n\t\tstd::uniform_int_distribution<uint> distribution(0,100);\n\t\tuint usage = 70;\n\t\tuint n = 5;\n\t\tos::generate_task_system(generator, distribution, usage, n, task_system);\n\n\t\tstd::cout << task_system << std::endl;\n\t\tuint u = 0;\n\t\tfor(auto task : task_system){\n\t\t\tu += task.wcet;\n\t\t}\n\t\t\n\t\tstd::cout << u << std::endl;\n\t}\n\n\n\t{\n\t\tstd::cout << \"SCHEDULER TEST\" << std::endl;\n\t\t\n\t\tos::task_system_t task_system;\n\t\tstd::cout << task_system << std::endl;\n\n\t\tstd::ifstream ifs(\"system\/0\", std::ifstream::in);\n\t\tos::parse_task_system_stream(ifs, task_system);\n\t\tifs.close();\n\t\t\n\t\tstd::cout << task_system << std::endl;\n\t}\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * @file hgpu_timer.cpp\n * @author Vadim Demchik <vadimdi@yahoo.com>\n * @version 1.0\n *\n * @brief [HGPU library]\n * timer submodule\n *\n *\n * @section LICENSE\n *\n * Copyright (c) 2013, Vadim Demchik\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *****************************************************************************\/\n\n#include \"..\/include\/hgpu_timer.h\"\n\n\/\/ start timer\nHGPU_timer\nHGPU_timer_start(void){\n return clock();\n}\n\n\/\/ get timer value in seconds (time delta)\ndouble\nHGPU_timer_get(HGPU_timer timer){\n double result = ((double) (clock() - timer)) \/ CLOCKS_PER_SEC;\n return result;\n}\n\n\/\/ get timer value in seconds (from start)\ndouble\nHGPU_timer_get_from_start(void){\n return ((double) clock()) \/ CLOCKS_PER_SEC;\n}\n\n\/\/ get date-time string\nchar*\nHGPU_timer_get_current_datetime(void){\n time_t tim;\n\ttime(&tim);\n char* result = (char*) calloc(30,sizeof(char));\n#ifdef _WIN32\n ctime_s(result, 30, &tim);\n#else\n sprintf(result,\"%s\",ctime((const time_t*) &tim));\n#endif\n HGPU_string_char_replace(result,HGPU_CHAR_CR,0);\n HGPU_string_char_replace(result,HGPU_CHAR_NEWLINE,0);\n return result;\n}\n\n\n\/\/ get (HGPU_timer_deviation) from profiling data\nHGPU_timer_deviation\nHGPU_timer_deviation_get(double elapsed_time, double elapsed_time_squared, double number_of_elements){\n HGPU_timer_deviation execution_time;\n execution_time.mean = elapsed_time;\n execution_time.number_of_elements = number_of_elements;\n execution_time.deviation = number_of_elements < 2 ? 0.0 : sqrt(abs(elapsed_time_squared - pow(elapsed_time,2)) \/ number_of_elements);\n return execution_time;\n}\n<commit_msg>timer submodule<commit_after>\/******************************************************************************\n * @file hgpu_timer.cpp\n * @author Vadim Demchik <vadimdi@yahoo.com>\n * @version 1.0.2\n *\n * @brief [HGPU library]\n * timer submodule\n *\n *\n * @section LICENSE\n *\n * Copyright (c) 2013, 2014 Vadim Demchik\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *****************************************************************************\/\n\n#include \"..\/include\/hgpu_timer.h\"\n\n\/\/ start timer\nHGPU_timer\nHGPU_timer_start(void){\n#ifdef SAFE_LINUX_TIMER\n HGPU_timer timer;\n time(&timer);\n return (HGPU_timer) timer;\n#else\n return clock();\n#endif\n}\n\n\/\/ get timer value in seconds (time delta)\ndouble\nHGPU_timer_get(HGPU_timer timer){\n#ifdef SAFE_LINUX_TIMER\n double result = difftime(HGPU_timer_start(),timer);\n#else\n double result = ((double) (clock() - timer)) \/ CLOCKS_PER_SEC;\n#endif\n return result;\n}\n\n\/\/ get timer value in seconds (from start)\ndouble\nHGPU_timer_get_from_start(void){\n return ((double) clock()) \/ CLOCKS_PER_SEC;\n}\n\n\/\/ get date-time string\nchar*\nHGPU_timer_get_current_datetime(void){\n time_t tim;\n\ttime(&tim);\n char* result = (char*) calloc(30,sizeof(char));\n#ifdef _WIN32\n ctime_s(result, 30, &tim);\n#else\n sprintf(result,\"%s\",ctime((const time_t*) &tim));\n#endif\n HGPU_string_char_replace(result,HGPU_CHAR_CR,0);\n HGPU_string_char_replace(result,HGPU_CHAR_NEWLINE,0);\n return result;\n}\n\n\n\/\/ get (HGPU_timer_deviation) from profiling data\nHGPU_timer_deviation\nHGPU_timer_deviation_get(double elapsed_time, double elapsed_time_squared, double number_of_elements){\n HGPU_timer_deviation execution_time;\n execution_time.mean = elapsed_time;\n execution_time.number_of_elements = number_of_elements;\n execution_time.deviation = number_of_elements < 2 ? 0.0 : sqrt(abs(elapsed_time_squared - pow(elapsed_time,2)) \/ number_of_elements);\n return execution_time;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\\file\n * \\brief \"Hello World\" HTTP Server\n *\n * \\copyright\n * Copyright (c) 2015, ef.gy Project Members\n * \\copyright\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \\copyright\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \\copyright\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\see Project Documentation: http:\/\/ef.gy\/documentation\/libefgy\n * \\see Project Source Code: https:\/\/github.com\/ef-gy\/libefgy\n *\/\n\n#define ASIO_DISABLE_THREADS\n#include <ef.gy\/http.h>\n#include <iostream>\n\nusing namespace efgy;\nusing namespace asio;\nusing namespace std;\n\nusing asio::ip::tcp;\n\nstatic bool hello(typename net::http::server<tcp>::session &session,\n std::smatch &) {\n session.reply(200, \"Hello World!\");\n\n return true;\n}\n\nint main(int argc, char *argv[]) {\n try {\n if (argc != 3) {\n std::cerr << \"Usage: http-hello <host> <port>\\n\";\n return 1;\n }\n\n asio::io_service io_service;\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(argv[1], argv[2]);\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n tcp::resolver::iterator end;\n\n if (endpoint_iterator != end) {\n tcp::endpoint endpoint = *endpoint_iterator;\n net::http::server<tcp> s(io_service, endpoint, cout);\n\n s.processor.add(\"^\/$\", hello);\n\n io_service.run();\n }\n }\n catch (std::exception & e) {\n std::cerr << \"Exception: \" << e.what() << \"\\n\";\n }\n catch (std::system_error & e) {\n std::cerr << \"System Error: \" << e.what() << \"\\n\";\n }\n\n return 0;\n}\n<commit_msg>add a bit more documentation to the HTTP demo<commit_after>\/**\\file\n * \\brief \"Hello World\" HTTP Server\n *\n * This is an example HTTP server that serves a simple \"Hello World!\" on \/, and\n * a 404 on all other resources.\n *\n * Call it like this:\n * \\code\n * $ .\/http-hello localhost 8080\n * \\endcode\n *\n * With localhost and 8080 being a host name and port of your choosing. Then,\n * while the programme is running, open a browser and go to\n * http:\/\/localhost:8080\/ and you should see the familiar greeting.\n *\n * \\copyright\n * Copyright (c) 2015, ef.gy Project Members\n * \\copyright\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \\copyright\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \\copyright\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\see Project Documentation: http:\/\/ef.gy\/documentation\/libefgy\n * \\see Project Source Code: https:\/\/github.com\/ef-gy\/libefgy\n *\/\n\n#define ASIO_DISABLE_THREADS\n#include <ef.gy\/http.h>\n#include <iostream>\n\nusing namespace efgy;\nusing asio::ip::tcp;\n\n\/**\\brief Hello World request handler\n *\n * This function serves the familiar \"Hello World!\" when called.\n *\n * \\param[out] session The HTTP session to answer on.\n *\n * \\returns true (always, as we always reply).\n *\/\nstatic bool hello(typename net::http::server<tcp>::session &session,\n std::smatch &) {\n session.reply(200, \"Hello World!\");\n\n return true;\n}\n\n\/**\\brief Main function for the HTTP demo\n *\n * This is the main function for the HTTP Hello World demo.\n *\n * \\param[in] argc Process argument count.\n * \\param[in] argv Process argument vector.\n *\n * \\returns 0 when nothing bad happened, 1 otherwise.\n *\/\nint main(int argc, char *argv[]) {\n try {\n if (argc != 3) {\n std::cerr << \"Usage: http-hello <host> <port>\\n\";\n return 1;\n }\n\n asio::io_service io_service;\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(argv[1], argv[2]);\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n tcp::resolver::iterator end;\n\n if (endpoint_iterator != end) {\n tcp::endpoint endpoint = *endpoint_iterator;\n net::http::server<tcp> s(io_service, endpoint, std::cout);\n\n s.processor.add(\"^\/$\", hello);\n\n io_service.run();\n }\n\n return 0;\n }\n catch (std::exception & e) {\n std::cerr << \"Exception: \" << e.what() << \"\\n\";\n }\n catch (std::system_error & e) {\n std::cerr << \"System Error: \" << e.what() << \"\\n\";\n }\n\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* inchi_input.cc\n * Copyright 2014 Cubane Canada, Inc.\n *\n * Released under the MIT license -- see MIT-LICENSE for details\n *\/\n#include <node.h>\n#include <v8.h>\n#include <uv.h>\n#include <nan.h>\n\n#include <cstring>\n\n#include \".\/inchi_input.h\"\n\n#include \".\/using_v8.h\"\n\n\/**\n * Wrapper for INCHI_Input structure\n *\n * @module InChILib\n * @class InchiInput\n *\/\n\n\/* local (non-API) functions *\/\nstatic void populate_input(Handle<Value> val, InchiInput* in);\nstatic void populate_ret(Handle<Object> ret,\n const inchi_Output& out, int result);\nstatic void addstring(Handle<Object> ret,\n const char * name, const char * value);\n\n\n\n\/**\n * Create an InchiInput structure from a partially or fully specified\n * JavaScript object\n *\n * @method Create\n * @param {Handle<Object>} val Object handle that parallels an inchi_Input\n *\/\nInchiInput * InchiInput::Create(Handle<Value> val) {\n \/\/ TODO(SOM): validation\n\n \/\/ create an empty InchiInput\n InchiInput * input = new InchiInput;\n\n \/\/ populate it\n populate_input(val, input);\n\n \/\/ return it\n return input;\n}\n\nHandle<Object> InchiInput::GetINCHIData::GetResult() {\n Local<Object> ret = Object::New();\n\n populate_ret(ret, this->out_, result_);\n\n return ret;\n}\n\nstruct GetINCHIWorker : public NanAsyncWorker {\n InchiInput::GetINCHIData * data_;\n\n GetINCHIWorker(NanCallback * callback, InchiInput* input) :\n NanAsyncWorker(callback) {\n data_ = input->tearOffGetINCHIData();\n }\n ~GetINCHIWorker() {}\n\n void Execute() {\n data_->GetInchi();\n }\n\n void HandleOKCallback() {\n NanScope();\n\n Handle<Object> result = data_->GetResult();\n\n Local<Value> argv[] = {\n Local<Value>::New(v8::Null()),\n Local<Value>::New(result)\n };\n\n callback->Call(2, argv);\n }\n};\n\n\/**\n * calls the \"classic\" GetINCHI function\n * @method GetINCHI\n * @param {Object} molecule Description of molecule\n * @param {Function} callback Callback function\n *\/\nNAN_METHOD(GetINCHI) {\n NanScope();\n\n InchiInput * input = NULL;\n Handle<Object> ret;\n\n try {\n \/\/ TODO(SOM): validate args\n Handle<Value> mol = args[0];\n NanCallback * callback = new NanCallback(args[1].As<Function>());\n\n input = InchiInput::Create(mol);\n\n NanAsyncQueueWorker(new GetINCHIWorker(callback, input));\n } catch(...) {\n }\n\n delete input;\n\n NanReturnUndefined();\n};\n\n\n\nvoid add_atom(InchiInput* in, Handle<Object> atom) {\n Handle<String> elname_string = atom->Get(NanSymbol(\"elname\"))->ToString();\n\n char * elname = NanCString(elname_string, 0);\n int index = in->addAtom(elname);\n\n Handle<Array> neighbor =\n Handle<Array>::Cast(atom->Get(NanSymbol(\"neighbor\")));\n\n int bonds = neighbor->Length();\n for (int i = 0; i < bonds; ++i) {\n int bonded = neighbor->Get(i)->ToNumber()->Value();\n in->addBond(index, bonded);\n }\n}\n\nstatic void populate_input(Handle<Value> val, InchiInput* in) {\n \/\/ TODO(SOM): support validation, possibly return error code\n\n \/\/ expect args[0] to be an Object, call it 'mol'\n \/\/ expect mol.atom to be an Array\n \/\/ expect mol.options to be a string\n \/\/ expect mol.stereo0D to be an Array\n\n if (!val->IsObject()) {\n return;\n }\n Handle<Object> mol = val->ToObject();\n\n if (!mol->Has(NanSymbol(\"atom\")) || !mol->Get(NanSymbol(\"atom\"))->IsArray()) {\n return;\n }\n Handle<Array> atom = Handle<Array>::Cast(mol->Get(NanSymbol(\"atom\")));\n\n int atoms = atom->Length();\n for (int i = 0; i < atoms; i += 1) {\n add_atom(in, atom->Get(i)->ToObject());\n }\n}\n\nstatic void addstring(Handle<Object> ret,\n const char * name, const char * value) {\n if (value) {\n ret->Set(NanSymbol(name), String::New(value));\n } else {\n ret->Set(NanSymbol(name), String::New(\"\"));\n }\n}\n\nstatic void populate_ret(Handle<Object> ret,\n const inchi_Output& out, int result) {\n addstring(ret, \"inchi\", out.szInChI);\n addstring(ret, \"auxinfo\", out.szAuxInfo);\n addstring(ret, \"message\", out.szMessage);\n addstring(ret, \"log\", out.szLog);\n ret->Set(NanSymbol(\"code\"), Number::New(result));\n}\n<commit_msg>use NanNewLocal (0.11-friendly) to construct callback args<commit_after>\/* inchi_input.cc\n * Copyright 2014 Cubane Canada, Inc.\n *\n * Released under the MIT license -- see MIT-LICENSE for details\n *\/\n#include <node.h>\n#include <v8.h>\n#include <uv.h>\n#include <nan.h>\n\n#include <cstring>\n\n#include \".\/inchi_input.h\"\n\n#include \".\/using_v8.h\"\n\n\/**\n * Wrapper for INCHI_Input structure\n *\n * @module InChILib\n * @class InchiInput\n *\/\n\n\/* local (non-API) functions *\/\nstatic void populate_input(Handle<Value> val, InchiInput* in);\nstatic void populate_ret(Handle<Object> ret,\n const inchi_Output& out, int result);\nstatic void addstring(Handle<Object> ret,\n const char * name, const char * value);\n\n\n\n\/**\n * Create an InchiInput structure from a partially or fully specified\n * JavaScript object\n *\n * @method Create\n * @param {Handle<Object>} val Object handle that parallels an inchi_Input\n *\/\nInchiInput * InchiInput::Create(Handle<Value> val) {\n \/\/ TODO(SOM): validation\n\n \/\/ create an empty InchiInput\n InchiInput * input = new InchiInput;\n\n \/\/ populate it\n populate_input(val, input);\n\n \/\/ return it\n return input;\n}\n\nHandle<Object> InchiInput::GetINCHIData::GetResult() {\n Local<Object> ret = Object::New();\n\n populate_ret(ret, this->out_, result_);\n\n return ret;\n}\n\nstruct GetINCHIWorker : public NanAsyncWorker {\n InchiInput::GetINCHIData * data_;\n\n GetINCHIWorker(NanCallback * callback, InchiInput* input) :\n NanAsyncWorker(callback) {\n data_ = input->tearOffGetINCHIData();\n }\n ~GetINCHIWorker() {}\n\n void Execute() {\n data_->GetInchi();\n }\n\n void HandleOKCallback() {\n NanScope();\n\n Handle<Object> result = data_->GetResult();\n\n Local<Value> argv[] = {\n NanNewLocal<Value>(v8::Null()),\n NanNewLocal<Value>(result)\n };\n\n callback->Call(2, argv);\n }\n};\n\n\/**\n * calls the \"classic\" GetINCHI function\n * @method GetINCHI\n * @param {Object} molecule Description of molecule\n * @param {Function} callback Callback function\n *\/\nNAN_METHOD(GetINCHI) {\n NanScope();\n\n InchiInput * input = NULL;\n Handle<Object> ret;\n\n try {\n \/\/ TODO(SOM): validate args\n Handle<Value> mol = args[0];\n NanCallback * callback = new NanCallback(args[1].As<Function>());\n\n input = InchiInput::Create(mol);\n\n NanAsyncQueueWorker(new GetINCHIWorker(callback, input));\n } catch(...) {\n }\n\n delete input;\n\n NanReturnUndefined();\n};\n\n\n\nvoid add_atom(InchiInput* in, Handle<Object> atom) {\n Handle<String> elname_string = atom->Get(NanSymbol(\"elname\"))->ToString();\n\n char * elname = NanCString(elname_string, 0);\n int index = in->addAtom(elname);\n\n Handle<Array> neighbor =\n Handle<Array>::Cast(atom->Get(NanSymbol(\"neighbor\")));\n\n int bonds = neighbor->Length();\n for (int i = 0; i < bonds; ++i) {\n int bonded = neighbor->Get(i)->ToNumber()->Value();\n in->addBond(index, bonded);\n }\n}\n\nstatic void populate_input(Handle<Value> val, InchiInput* in) {\n \/\/ TODO(SOM): support validation, possibly return error code\n\n \/\/ expect args[0] to be an Object, call it 'mol'\n \/\/ expect mol.atom to be an Array\n \/\/ expect mol.options to be a string\n \/\/ expect mol.stereo0D to be an Array\n\n if (!val->IsObject()) {\n return;\n }\n Handle<Object> mol = val->ToObject();\n\n if (!mol->Has(NanSymbol(\"atom\")) || !mol->Get(NanSymbol(\"atom\"))->IsArray()) {\n return;\n }\n Handle<Array> atom = Handle<Array>::Cast(mol->Get(NanSymbol(\"atom\")));\n\n int atoms = atom->Length();\n for (int i = 0; i < atoms; i += 1) {\n add_atom(in, atom->Get(i)->ToObject());\n }\n}\n\nstatic void addstring(Handle<Object> ret,\n const char * name, const char * value) {\n if (value) {\n ret->Set(NanSymbol(name), String::New(value));\n } else {\n ret->Set(NanSymbol(name), String::New(\"\"));\n }\n}\n\nstatic void populate_ret(Handle<Object> ret,\n const inchi_Output& out, int result) {\n addstring(ret, \"inchi\", out.szInChI);\n addstring(ret, \"auxinfo\", out.szAuxInfo);\n addstring(ret, \"message\", out.szMessage);\n addstring(ret, \"log\", out.szLog);\n ret->Set(NanSymbol(\"code\"), Number::New(result));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/tooling\n\n#include \"backport.h\"\n#include \"tooling.h\"\n\n#ifdef QT_WIDGETS_LIB\n\n#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)\n#if 0 \/\/ The Qt-4 style hooks work just fine and are portable.\n#include <private\/qhooks_p.h>\n#endif\n#endif\n#include <QApplication>\n#include <QDebug>\n#include <QDesktopWidget>\n#include <QDir>\n#include <QElapsedTimer>\n#include <QEvent>\n#include <QFile>\n#include <QPainter>\n#include <QScreen>\n\n#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)\n#include <QWindow>\n#endif\n\nnamespace tooling {\n\nstruct Times {\n static int constexpr collect() { return 1000; }\n static int constexpr minCollect() { return 100; }\n static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }\n};\n\nstatic bool isProxied(QWidget *widget) {\n static EventLoopContext ctx;\n static PointerList<QWidget> proxied;\n Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());\n\n if (ctx.needsRearm()) {\n proxied = getProxiedWidgets();\n ctx.rearm();\n }\n return proxied.contains(widget);\n}\n\nstatic void takeScreenshot(int n, QWidget *w) {\n auto rect = shadowlessFrameGeometry(w->frameGeometry());\n if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);\n QPixmap pix;\n#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)\n auto *const win = w->windowHandle();\n auto *const screen = win->screen();\n pix = screen->grabWindow(0);\n#endif\n if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))\n pix = QPixmap::grabWindow(QApplication::desktop()->winId());\n\n if ((1)) {\n pix = pix.copy(rect);\n } else {\n QPainter p(&pix);\n p.drawRect(w->frameGeometry());\n p.end();\n }\n if (pix.isNull()) {\n qWarning() << \"Discarding null screenshot of\" << w;\n return;\n }\n auto const name = w->objectName();\n auto const fileName =\n QStringLiteral(\"screenshot_%1_%2%3.png\")\n .arg(n)\n .arg(QLatin1String(w->metaObject()->className()))\n .arg(name.isNull() ? QString() : QStringLiteral(\"_%1\").arg(name));\n QDir path = QCoreApplication::applicationDirPath();\n if (HostOsInfo::isMacHost() && path.path().endsWith(\".app\/Contents\/MacOS\")) {\n \/\/ store the widget in the app-containing folder, not in the bundle itself\n path.cdUp();\n path.cdUp();\n path.cdUp();\n }\n tooling::QSaveFile f(path.absoluteFilePath(fileName));\n if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, \"PNG\")) {\n qDebug() << \"Took screenshot of\" << w << \":\" << f.fileName();\n if (!showInGraphicalShell(w, f.fileName(), n == 1))\n qWarning()\n << \"Can't invoke the graphical file shell to show screenshot location.\";\n } else {\n qWarning() << \"Can't save screenshot\" << f.fileName()\n << \"Error:\" << f.errorString();\n }\n}\n\nclass ScreenshotTaker : public QObject {\n static int n;\n QAtomicInt eventCount = 0;\n enum Phase { Collecting, Collected, Screenshot };\n enum State { Initial, Updated, Painted, Ignored };\n Phase phase = Collecting;\n QBasicTimer timer;\n QElapsedTimer time;\n struct TopLevel {\n QPointer<QWidget> w = {};\n State state = Initial;\n TopLevel() = default;\n explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}\n operator QWidget *() const { return w; }\n QWidget *operator->() const { return w; }\n bool operator==(QWidget *o) const { return o == w; }\n };\n QVector<TopLevel> topLevels;\n int leftToPaint = 0;\n void timerEvent(QTimerEvent *ev) override {\n if (ev->timerId() == timer.timerId()) {\n if (phase == Collecting || phase == Collected)\n scheduleScreenshots();\n else if (phase == Screenshot)\n takeScreenshots();\n }\n }\n void scheduleScreenshots() {\n qDebug() << \"Deferring screenshots. Noted\" << topLevels.count() << \"widgets.\";\n qApp->removeEventFilter(this);\n timer.start(Times::screenshotDelay(), this);\n phase = Screenshot;\n }\n void takeScreenshots() {\n if (qApp->property(\"no_screenshots\").toBool())\n qDebug() << \"Screenshot: Disabled by application property\";\n else\n for (auto &tl : qAsConst(topLevels)) {\n if (!tl.w)\n continue;\n else if (!tl->isWindow()) {\n } else if (isProxied(tl))\n qDebug() << \"Skipping proxied widget\" << tl;\n else if (tl.state == Painted)\n takeScreenshot(++n, tl);\n }\n deleteLater();\n }\n bool eventFilter(QObject *o, QEvent *ev) override {\n static bool recursed;\n eventCount.fetchAndAddOrdered(1);\n if (recursed) return recursed = false;\n recursed = true;\n if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;\n auto *w = static_cast<QWidget *>(o);\n auto *window = w->window();\n auto i = std::find(topLevels.begin(), topLevels.end(), window);\n if (phase == Collecting && i == topLevels.end()) {\n topLevels.push_back(TopLevel(window));\n i = std::prev(topLevels.end());\n if (tooling::hasEventLoopSpunUp())\n qDebug() << \"Noting\" << window << \"for a screenshot\";\n leftToPaint++;\n } else if (i != topLevels.end()) {\n if (tooling::hasEventLoopSpunUp() && window->isVisible() &&\n i->state == Initial) {\n bool raise =\n QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();\n qDebug() << (raise ? \"Raising\" : \"Updating\") << window << \"for a screnshot\";\n if (raise) window->raise();\n window->update();\n i->state = Updated;\n }\n if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&\n i->state != Painted && i->state != Ignored) {\n i->state = Painted;\n (w != window ? qDebug() << window : qDebug()) << w << \"painted\";\n leftToPaint--;\n }\n if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {\n timer.stop();\n scheduleScreenshots();\n }\n }\n return recursed = false;\n }\n\n public:\n ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {\n if (parent) {\n Q_ASSERT(parent->isWindow());\n phase = Collected;\n topLevels.push_back(TopLevel(parent, Painted));\n } else {\n time.start();\n timer.start(Times::collect(), this);\n }\n qApp->installEventFilter(this);\n }\n ~ScreenshotTaker() override {\n qDebug() << \"Saw\" << eventCount << \"events before taking screenshots.\";\n }\n}; \/\/ namespace tooling\n\nint ScreenshotTaker::n;\n\nvoid takeScreenshot(QWidget *widget) {\n Q_ASSERT(widget && widget->isWindow());\n if (isProxied(widget)) {\n qDebug() << \"Skipping proxied widget\" << widget;\n return;\n }\n if (!widget->isVisible()) {\n qDebug() << \"Skipping hidden widget\" << widget;\n return;\n }\n new ScreenshotTaker(widget);\n}\n\nstatic bool takeScreenshots(const HookData &) {\n#ifdef NO_SCREENSHOTS\n return;\n#endif\n if (qApp->property(\"no_screenshots\").toBool()) {\n qDebug() << \"Screenshot: Disabled by application property\";\n return false;\n }\n qDebug() << \"Screenshot: Startup\";\n new ScreenshotTaker();\n return false;\n}\n\nstatic bool initialized = [] {\n registerHook(HasQApplicationHook, &takeScreenshots);\n return true;\n}();\n\n} \/\/ namespace tooling\n\n#endif \/\/ QT_WIDGETS_LIB\n<commit_msg>Fix savefile handling.<commit_after>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/tooling\n\n#include \"backport.h\"\n#include \"tooling.h\"\n\n#ifdef QT_WIDGETS_LIB\n\n#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)\n#if 0 \/\/ The Qt-4 style hooks work just fine and are portable.\n#include <private\/qhooks_p.h>\n#endif\n#endif\n#include <QApplication>\n#include <QDebug>\n#include <QDesktopWidget>\n#include <QDir>\n#include <QElapsedTimer>\n#include <QEvent>\n#include <QFile>\n#include <QPainter>\n#include <QScreen>\n\n#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)\n#include <QWindow>\n#endif\n\nnamespace tooling {\n\nstruct Times {\n static int constexpr collect() { return 1000; }\n static int constexpr minCollect() { return 100; }\n static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }\n};\n\nstatic bool isProxied(QWidget *widget) {\n static EventLoopContext ctx;\n static PointerList<QWidget> proxied;\n Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());\n\n if (ctx.needsRearm()) {\n proxied = getProxiedWidgets();\n ctx.rearm();\n }\n return proxied.contains(widget);\n}\n\nstatic void takeScreenshot(int n, QWidget *w) {\n auto rect = shadowlessFrameGeometry(w->frameGeometry());\n if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);\n QPixmap pix;\n#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)\n auto *const win = w->windowHandle();\n auto *const screen = win->screen();\n pix = screen->grabWindow(0);\n#endif\n if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))\n pix = QPixmap::grabWindow(QApplication::desktop()->winId());\n\n if ((1)) {\n pix = pix.copy(rect);\n } else {\n QPainter p(&pix);\n p.drawRect(w->frameGeometry());\n p.end();\n }\n if (pix.isNull()) {\n qWarning() << \"Discarding null screenshot of\" << w;\n return;\n }\n auto const name = w->objectName();\n auto const fileName =\n QStringLiteral(\"screenshot_%1_%2%3.png\")\n .arg(n)\n .arg(QLatin1String(w->metaObject()->className()))\n .arg(name.isNull() ? QString() : QStringLiteral(\"_%1\").arg(name));\n QDir path = QCoreApplication::applicationDirPath();\n if (HostOsInfo::isMacHost() && path.path().endsWith(\".app\/Contents\/MacOS\")) {\n \/\/ store the widget in the app-containing folder, not in the bundle itself\n path.cdUp();\n path.cdUp();\n path.cdUp();\n }\n tooling::QSaveFile f(path.absoluteFilePath(fileName));\n if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, \"PNG\") && f.commit()) {\n qDebug() << \"Took screenshot of\" << w << \":\" << f.fileName();\n if (!showInGraphicalShell(w, f.fileName(), n == 1))\n qWarning()\n << \"Can't invoke the graphical file shell to show screenshot location.\";\n } else {\n qWarning() << \"Can't save screenshot\" << f.fileName()\n << \"Error:\" << f.errorString();\n }\n}\n\nclass ScreenshotTaker : public QObject {\n static int n;\n QAtomicInt eventCount = 0;\n enum Phase { Collecting, Collected, Screenshot };\n enum State { Initial, Updated, Painted, Ignored };\n Phase phase = Collecting;\n QBasicTimer timer;\n QElapsedTimer time;\n struct TopLevel {\n QPointer<QWidget> w = {};\n State state = Initial;\n TopLevel() = default;\n explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}\n operator QWidget *() const { return w; }\n QWidget *operator->() const { return w; }\n bool operator==(QWidget *o) const { return o == w; }\n };\n QVector<TopLevel> topLevels;\n int leftToPaint = 0;\n void timerEvent(QTimerEvent *ev) override {\n if (ev->timerId() == timer.timerId()) {\n if (phase == Collecting || phase == Collected)\n scheduleScreenshots();\n else if (phase == Screenshot)\n takeScreenshots();\n }\n }\n void scheduleScreenshots() {\n qDebug() << \"Deferring screenshots. Noted\" << topLevels.count() << \"widgets.\";\n qApp->removeEventFilter(this);\n timer.start(Times::screenshotDelay(), this);\n phase = Screenshot;\n }\n void takeScreenshots() {\n if (qApp->property(\"no_screenshots\").toBool())\n qDebug() << \"Screenshot: Disabled by application property\";\n else\n for (auto &tl : qAsConst(topLevels)) {\n if (!tl.w)\n continue;\n else if (!tl->isWindow()) {\n } else if (isProxied(tl))\n qDebug() << \"Skipping proxied widget\" << tl;\n else if (tl.state == Painted)\n takeScreenshot(++n, tl);\n }\n deleteLater();\n }\n bool eventFilter(QObject *o, QEvent *ev) override {\n static bool recursed;\n eventCount.fetchAndAddOrdered(1);\n if (recursed) return recursed = false;\n recursed = true;\n if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;\n auto *w = static_cast<QWidget *>(o);\n auto *window = w->window();\n auto i = std::find(topLevels.begin(), topLevels.end(), window);\n if (phase == Collecting && i == topLevels.end()) {\n topLevels.push_back(TopLevel(window));\n i = std::prev(topLevels.end());\n if (tooling::hasEventLoopSpunUp())\n qDebug() << \"Noting\" << window << \"for a screenshot\";\n leftToPaint++;\n } else if (i != topLevels.end()) {\n if (tooling::hasEventLoopSpunUp() && window->isVisible() &&\n i->state == Initial) {\n bool raise =\n QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();\n qDebug() << (raise ? \"Raising\" : \"Updating\") << window << \"for a screnshot\";\n if (raise) window->raise();\n window->update();\n i->state = Updated;\n }\n if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&\n i->state != Painted && i->state != Ignored) {\n i->state = Painted;\n (w != window ? qDebug() << window : qDebug()) << w << \"painted\";\n leftToPaint--;\n }\n if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {\n timer.stop();\n scheduleScreenshots();\n }\n }\n return recursed = false;\n }\n\n public:\n ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {\n if (parent) {\n Q_ASSERT(parent->isWindow());\n phase = Collected;\n topLevels.push_back(TopLevel(parent, Painted));\n } else {\n time.start();\n timer.start(Times::collect(), this);\n }\n qApp->installEventFilter(this);\n }\n ~ScreenshotTaker() override {\n qDebug() << \"Saw\" << eventCount << \"events before taking screenshots.\";\n }\n}; \/\/ namespace tooling\n\nint ScreenshotTaker::n;\n\nvoid takeScreenshot(QWidget *widget) {\n Q_ASSERT(widget && widget->isWindow());\n if (isProxied(widget)) {\n qDebug() << \"Skipping proxied widget\" << widget;\n return;\n }\n if (!widget->isVisible()) {\n qDebug() << \"Skipping hidden widget\" << widget;\n return;\n }\n new ScreenshotTaker(widget);\n}\n\nstatic bool takeScreenshots(const HookData &) {\n#ifdef NO_SCREENSHOTS\n return;\n#endif\n if (qApp->property(\"no_screenshots\").toBool()) {\n qDebug() << \"Screenshot: Disabled by application property\";\n return false;\n }\n qDebug() << \"Screenshot: Startup\";\n new ScreenshotTaker();\n return false;\n}\n\nstatic bool initialized = [] {\n registerHook(HasQApplicationHook, &takeScreenshots);\n return true;\n}();\n\n} \/\/ namespace tooling\n\n#endif \/\/ QT_WIDGETS_LIB\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Lukasz Janyst <ljanyst@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/MetaProcessor\/MetaProcessor.h\"\n#include \"cling\/UserInterface\/UserInterface.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/HeaderSearchOptions.h\"\n\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nint main( int argc, char **argv ) {\n\n llvm::llvm_shutdown_obj shutdownTrigger;\n\n \/\/llvm::sys::PrintStackTraceOnErrorSignal();\n \/\/llvm::PrettyStackTraceProgram X(argc, argv);\n\n \/\/ Set up the interpreter\n cling::Interpreter interp(argc, argv);\n if (interp.getOptions().Help) {\n return 0;\n }\n\n clang::CompilerInstance* CI = interp.getCI();\n interp.AddIncludePath(\".\");\n\n for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {\n interp.loadFile(interp.getOptions().LibsToLoad[I]);\n }\n\n bool ret = true;\n const std::vector<clang::FrontendInputFile>& Inputs\n = CI->getInvocation().getFrontendOpts().Inputs;\n\n \/\/ Interactive means no input (or one input that's \"-\")\n bool Interactive = Inputs.empty() || (Inputs.size() == 1\n && Inputs[0].File == \"-\");\n\n cling::UserInterface ui(interp);\n \/\/ If we are not interactive we're supposed to parse files\n if (!Interactive) {\n for (size_t I = 0, N = Inputs.size(); I < N; ++I) {\n ui.getMetaProcessor()->process((\".x \" + Inputs[I].File).c_str());\n ret = !CI->getDiagnostics().getClient()->getNumErrors();\n }\n }\n else {\n cling::UserInterface ui(interp);\n ui.runInteractively(interp.getOptions().NoLogo);\n }\n\n \/\/ if we are running with -verify a reported has to be returned as unsuccess.\n \/\/ This is relevan especially for the test suite.\n if (CI->getDiagnosticOpts().VerifyDiagnostics)\n ret = !CI->getDiagnostics().getClient()->getNumErrors();\n\n return ret ? 0 : 1;\n}\n<commit_msg>unused include<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Lukasz Janyst <ljanyst@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/MetaProcessor\/MetaProcessor.h\"\n#include \"cling\/UserInterface\/UserInterface.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nint main( int argc, char **argv ) {\n\n llvm::llvm_shutdown_obj shutdownTrigger;\n\n \/\/llvm::sys::PrintStackTraceOnErrorSignal();\n \/\/llvm::PrettyStackTraceProgram X(argc, argv);\n\n \/\/ Set up the interpreter\n cling::Interpreter interp(argc, argv);\n if (interp.getOptions().Help) {\n return 0;\n }\n\n clang::CompilerInstance* CI = interp.getCI();\n interp.AddIncludePath(\".\");\n\n for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {\n interp.loadFile(interp.getOptions().LibsToLoad[I]);\n }\n\n bool ret = true;\n const std::vector<clang::FrontendInputFile>& Inputs\n = CI->getInvocation().getFrontendOpts().Inputs;\n\n \/\/ Interactive means no input (or one input that's \"-\")\n bool Interactive = Inputs.empty() || (Inputs.size() == 1\n && Inputs[0].File == \"-\");\n\n cling::UserInterface ui(interp);\n \/\/ If we are not interactive we're supposed to parse files\n if (!Interactive) {\n for (size_t I = 0, N = Inputs.size(); I < N; ++I) {\n ui.getMetaProcessor()->process((\".x \" + Inputs[I].File).c_str());\n ret = !CI->getDiagnostics().getClient()->getNumErrors();\n }\n }\n else {\n cling::UserInterface ui(interp);\n ui.runInteractively(interp.getOptions().NoLogo);\n }\n\n \/\/ if we are running with -verify a reported has to be returned as unsuccess.\n \/\/ This is relevan especially for the test suite.\n if (CI->getDiagnosticOpts().VerifyDiagnostics)\n ret = !CI->getDiagnostics().getClient()->getNumErrors();\n\n return ret ? 0 : 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This source file is part of MyGUI. For the latest info, see http:\/\/mygui.info\/\n * Distributed under the MIT License\n * (See accompanying file COPYING.MIT or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include \"MyGUI_Precompiled.h\"\n#include \"MyGUI_ScrollView.h\"\n#include \"MyGUI_SkinManager.h\"\n#include \"MyGUI_ISubWidgetText.h\"\n#include \"MyGUI_ScrollBar.h\"\n\nnamespace MyGUI\n{\n\n\tconst int SCROLL_VIEW_MOUSE_WHEEL = 50; \/\/ колличество пикселей для колеса мыши\n\tconst int SCROLL_VIEW_SCROLL_PAGE = 16; \/\/ колличество пикселей для кнопок скрола\n\n\tScrollView::ScrollView() :\n\t\tmContentAlign(Align::Center),\n\t\tmRealClient(nullptr)\n\t{\n\t\tmChangeContentByResize = false;\n\t\tmContentAlign = Align::Center;\n\t}\n\n\tvoid ScrollView::initialiseOverride()\n\t{\n\t\tBase::initialiseOverride();\n\n\t\t\/\/ FIXME нам нужен фокус клавы\n\t\tsetNeedKeyFocus(true);\n\n\t\t\/\/\/@wskin_child{ScrollView, Widget, Client} Клиентская зона.\n\t\tassignWidget(mClient, \"Client\");\n\t\tMyGUI::Widget* realClientOwner = this;\n\t\tif (mClient != nullptr)\n\t\t{\n\t\t\tmClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);\n\t\t\trealClientOwner = mClient;\n\t\t}\n\n\t\t\/\/ создаем холcт, реальный владелец детей\n\t\tmRealClient = realClientOwner->createWidget<Widget>(\"Default\", IntCoord(), Align::Default);\n\t\tmRealClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);\n\t\tsetWidgetClient(mRealClient);\n\n\t\t\/\/\/@wskin_child{ScrollView, ScrollBar, VScroll} Вертикальная полоса прокрутки.\n\t\tassignWidget(mVScroll, \"VScroll\");\n\t\tif (mVScroll != nullptr)\n\t\t{\n\t\t\tmVScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);\n\t\t}\n\n\t\t\/\/\/@wskin_child{ScrollView, ScrollBar, HScroll} Горизонтальная полоса прокрутки.\n\t\tassignWidget(mHScroll, \"HScroll\");\n\t\tif (mHScroll != nullptr)\n\t\t{\n\t\t\tmHScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);\n\t\t}\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::shutdownOverride()\n\t{\n\t\tmVScroll = nullptr;\n\t\tmHScroll = nullptr;\n\t\tmClient = nullptr;\n\t\tmRealClient = nullptr;\n\n\t\tBase::shutdownOverride();\n\t}\n\n\tvoid ScrollView::setPosition(const IntPoint& _point)\n\t{\n\t\tBase::setPosition(_point);\n\t}\n\n\tvoid ScrollView::setSize(const IntSize& _size)\n\t{\n\t\tBase::setSize(_size);\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCoord(const IntCoord& _coord)\n\t{\n\t\tBase::setCoord(_coord);\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::notifyScrollChangePosition(ScrollBar* _sender, size_t _position)\n\t{\n\t\tif (mRealClient == nullptr)\n\t\t\treturn;\n\n\t\tif (_sender == mVScroll)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tpoint.top = -(int)_position;\n\t\t\tmRealClient->setPosition(point);\n\t\t}\n\t\telse if (_sender == mHScroll)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tpoint.left = -(int)_position;\n\t\t\tmRealClient->setPosition(point);\n\t\t}\n\t}\n\n\tvoid ScrollView::notifyMouseWheel(Widget* _sender, int _rel)\n\t{\n\t\tif (mRealClient == nullptr)\n\t\t\treturn;\n\n\t\tif (mVRange != 0)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tint offset = -point.top;\n\t\t\tif (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;\n\t\t\telse offset -= SCROLL_VIEW_MOUSE_WHEEL;\n\n\t\t\tif (offset < 0) offset = 0;\n\t\t\telse if (offset > (int)mVRange) offset = mVRange;\n\n\t\t\tif (offset != point.top)\n\t\t\t{\n\t\t\t\tpoint.top = -offset;\n\t\t\t\tif (mVScroll != nullptr)\n\t\t\t\t{\n\t\t\t\t\tmVScroll->setScrollPosition(offset);\n\t\t\t\t}\n\t\t\t\tmRealClient->setPosition(point);\n\t\t\t}\n\t\t}\n\t\telse if (mHRange != 0)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tint offset = -point.left;\n\t\t\tif (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;\n\t\t\telse offset -= SCROLL_VIEW_MOUSE_WHEEL;\n\n\t\t\tif (offset < 0) offset = 0;\n\t\t\telse if (offset > (int)mHRange) offset = mHRange;\n\n\t\t\tif (offset != point.left)\n\t\t\t{\n\t\t\t\tpoint.left = -offset;\n\t\t\t\tif (mHScroll != nullptr)\n\t\t\t\t{\n\t\t\t\t\tmHScroll->setScrollPosition(offset);\n\t\t\t\t}\n\t\t\t\tmRealClient->setPosition(point);\n\t\t\t}\n\t\t}\n\t}\n\n\tIntSize ScrollView::getContentSize()\n\t{\n\t\treturn mRealClient == nullptr ? IntSize() : mRealClient->getSize();\n\t}\n\n\tIntPoint ScrollView::getContentPosition()\n\t{\n\t\treturn mRealClient == nullptr ? IntPoint() : (IntPoint() - mRealClient->getPosition());\n\t}\n\n\tvoid ScrollView::setContentPosition(const IntPoint& _point)\n\t{\n\t\tif (mRealClient != nullptr)\n\t\t\tmRealClient->setPosition(IntPoint() - _point);\n\t}\n\n\tIntSize ScrollView::getViewSize()\n\t{\n\t\treturn mClient == nullptr ? getSize() : mClient->getSize();\n\t}\n\n\tsize_t ScrollView::getVScrollPage()\n\t{\n\t\treturn SCROLL_VIEW_SCROLL_PAGE;\n\t}\n\n\tsize_t ScrollView::getHScrollPage()\n\t{\n\t\treturn SCROLL_VIEW_SCROLL_PAGE;\n\t}\n\n\tvoid ScrollView::updateView()\n\t{\n\t\tupdateScrollSize();\n\t\tupdateScrollPosition();\n\t}\n\n\tvoid ScrollView::setVisibleVScroll(bool _value)\n\t{\n\t\tmVisibleVScroll = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setVisibleHScroll(bool _value)\n\t{\n\t\tmVisibleHScroll = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCanvasAlign(Align _value)\n\t{\n\t\tmContentAlign = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCanvasSize(const IntSize& _value)\n\t{\n\t\tif (mRealClient != nullptr)\n\t\t\tmRealClient->setSize(_value);\n\t\tupdateView();\n\t}\n\n\tIntSize ScrollView::getCanvasSize()\n\t{\n\t\treturn mRealClient == nullptr ? IntSize() : mRealClient->getSize();\n\t}\n\n\tvoid ScrollView::setPropertyOverride(const std::string& _key, const std::string& _value)\n\t{\n\t\t\/\/\/ @wproperty{ScrollView, VisibleVScroll, bool} Видимость вертикальной полосы прокрутки.\n\t\tif (_key == \"VisibleVScroll\")\n\t\t\tsetVisibleVScroll(utility::parseValue<bool>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, VisibleHScroll, bool} Видимость горизонтальной полосы прокрутки.\n\t\telse if (_key == \"VisibleHScroll\")\n\t\t\tsetVisibleHScroll(utility::parseValue<bool>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, CanvasAlign, Align} Выравнивание содержимого.\n\t\telse if (_key == \"CanvasAlign\")\n\t\t\tsetCanvasAlign(utility::parseValue<Align>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, CanvasSize, int int} Размер содержимого.\n\t\telse if (_key == \"CanvasSize\")\n\t\t\tsetCanvasSize(utility::parseValue<IntSize>(_value));\n\n\t\telse\n\t\t{\n\t\t\tBase::setPropertyOverride(_key, _value);\n\t\t\treturn;\n\t\t}\n\n\t\teventChangeProperty(this, _key, _value);\n\t}\n\n\tvoid ScrollView::setPosition(int _left, int _top)\n\t{\n\t\tsetPosition(IntPoint(_left, _top));\n\t}\n\n\tvoid ScrollView::setSize(int _width, int _height)\n\t{\n\t\tsetSize(IntSize(_width, _height));\n\t}\n\n\tvoid ScrollView::setCoord(int _left, int _top, int _width, int _height)\n\t{\n\t\tsetCoord(IntCoord(_left, _top, _width, _height));\n\t}\n\n\tbool ScrollView::isVisibleVScroll() const\n\t{\n\t\treturn mVisibleVScroll;\n\t}\n\n\tbool ScrollView::isVisibleHScroll() const\n\t{\n\t\treturn mVisibleHScroll;\n\t}\n\n\tAlign ScrollView::getCanvasAlign() const\n\t{\n\t\treturn mContentAlign;\n\t}\n\n\tvoid ScrollView::setCanvasSize(int _width, int _height)\n\t{\n\t\tsetCanvasSize(IntSize(_width, _height));\n\t}\n\n\tAlign ScrollView::getContentAlign()\n\t{\n\t\treturn mContentAlign;\n\t}\n\n\tvoid ScrollView::setViewOffset(const IntPoint& _value)\n\t{\n\t\tIntPoint value = _value;\n\t\tIntPoint currentOffset = mRealClient->getPosition();\n\n\t\tif (mHRange != 0)\n\t\t{\n\t\t\tif (value.left > 0)\n\t\t\t\tvalue.left = 0;\n\t\t\telse if (value.left < -(int)mHRange)\n\t\t\t\tvalue.left = -(int)mHRange;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalue.left = currentOffset.left;\n\t\t}\n\n\t\tif (mVRange != 0)\n\t\t{\n\t\t\tif (value.top > 0)\n\t\t\t\tvalue.top = 0;\n\t\t\telse if (value.top < -(int)mVRange)\n\t\t\t\tvalue.top = -(int)mVRange;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalue.top = currentOffset.top;\n\t\t}\n\n\t\tif (mHScroll != nullptr)\n\t\t\tmHScroll->setScrollPosition(-value.left);\n\n\t\tif (mVScroll != nullptr)\n\t\t\tmVScroll->setScrollPosition(-value.top);\n\n\t\tmRealClient->setPosition(value);\n\t}\n\n\tIntPoint ScrollView::getViewOffset() const\n\t{\n\t\treturn mRealClient->getPosition();\n\t}\n\n\tIntCoord ScrollView::getViewCoord() const\n\t{\n\t\treturn mClient == nullptr ? getCoord() : mClient->getCoord();\n\t}\n\n\tScrollBar* ScrollView::getVScroll()\n\t{\n\t\treturn mVScroll;\n\t}\n\n} \/\/ namespace MyGUI\n<commit_msg>Made canvas size adjust by the scaling factor if it is set as a property.<commit_after>\/*\n * This source file is part of MyGUI. For the latest info, see http:\/\/mygui.info\/\n * Distributed under the MIT License\n * (See accompanying file COPYING.MIT or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include \"MyGUI_Precompiled.h\"\n#include \"MyGUI_ScrollView.h\"\n#include \"MyGUI_SkinManager.h\"\n#include \"MyGUI_ISubWidgetText.h\"\n#include \"MyGUI_ScrollBar.h\"\n#include \"MyGUI_Gui.h\"\n\nnamespace MyGUI\n{\n\n\tconst int SCROLL_VIEW_MOUSE_WHEEL = 50; \/\/ колличество пикселей для колеса мыши\n\tconst int SCROLL_VIEW_SCROLL_PAGE = 16; \/\/ колличество пикселей для кнопок скрола\n\n\tScrollView::ScrollView() :\n\t\tmContentAlign(Align::Center),\n\t\tmRealClient(nullptr)\n\t{\n\t\tmChangeContentByResize = false;\n\t\tmContentAlign = Align::Center;\n\t}\n\n\tvoid ScrollView::initialiseOverride()\n\t{\n\t\tBase::initialiseOverride();\n\n\t\t\/\/ FIXME нам нужен фокус клавы\n\t\tsetNeedKeyFocus(true);\n\n\t\t\/\/\/@wskin_child{ScrollView, Widget, Client} Клиентская зона.\n\t\tassignWidget(mClient, \"Client\");\n\t\tMyGUI::Widget* realClientOwner = this;\n\t\tif (mClient != nullptr)\n\t\t{\n\t\t\tmClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);\n\t\t\trealClientOwner = mClient;\n\t\t}\n\n\t\t\/\/ создаем холcт, реальный владелец детей\n\t\tmRealClient = realClientOwner->createWidget<Widget>(\"Default\", IntCoord(), Align::Default);\n\t\tmRealClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);\n\t\tsetWidgetClient(mRealClient);\n\n\t\t\/\/\/@wskin_child{ScrollView, ScrollBar, VScroll} Вертикальная полоса прокрутки.\n\t\tassignWidget(mVScroll, \"VScroll\");\n\t\tif (mVScroll != nullptr)\n\t\t{\n\t\t\tmVScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);\n\t\t}\n\n\t\t\/\/\/@wskin_child{ScrollView, ScrollBar, HScroll} Горизонтальная полоса прокрутки.\n\t\tassignWidget(mHScroll, \"HScroll\");\n\t\tif (mHScroll != nullptr)\n\t\t{\n\t\t\tmHScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);\n\t\t}\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::shutdownOverride()\n\t{\n\t\tmVScroll = nullptr;\n\t\tmHScroll = nullptr;\n\t\tmClient = nullptr;\n\t\tmRealClient = nullptr;\n\n\t\tBase::shutdownOverride();\n\t}\n\n\tvoid ScrollView::setPosition(const IntPoint& _point)\n\t{\n\t\tBase::setPosition(_point);\n\t}\n\n\tvoid ScrollView::setSize(const IntSize& _size)\n\t{\n\t\tBase::setSize(_size);\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCoord(const IntCoord& _coord)\n\t{\n\t\tBase::setCoord(_coord);\n\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::notifyScrollChangePosition(ScrollBar* _sender, size_t _position)\n\t{\n\t\tif (mRealClient == nullptr)\n\t\t\treturn;\n\n\t\tif (_sender == mVScroll)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tpoint.top = -(int)_position;\n\t\t\tmRealClient->setPosition(point);\n\t\t}\n\t\telse if (_sender == mHScroll)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tpoint.left = -(int)_position;\n\t\t\tmRealClient->setPosition(point);\n\t\t}\n\t}\n\n\tvoid ScrollView::notifyMouseWheel(Widget* _sender, int _rel)\n\t{\n\t\tif (mRealClient == nullptr)\n\t\t\treturn;\n\n\t\tif (mVRange != 0)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tint offset = -point.top;\n\t\t\tif (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;\n\t\t\telse offset -= SCROLL_VIEW_MOUSE_WHEEL;\n\n\t\t\tif (offset < 0) offset = 0;\n\t\t\telse if (offset > (int)mVRange) offset = mVRange;\n\n\t\t\tif (offset != point.top)\n\t\t\t{\n\t\t\t\tpoint.top = -offset;\n\t\t\t\tif (mVScroll != nullptr)\n\t\t\t\t{\n\t\t\t\t\tmVScroll->setScrollPosition(offset);\n\t\t\t\t}\n\t\t\t\tmRealClient->setPosition(point);\n\t\t\t}\n\t\t}\n\t\telse if (mHRange != 0)\n\t\t{\n\t\t\tIntPoint point = mRealClient->getPosition();\n\t\t\tint offset = -point.left;\n\t\t\tif (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;\n\t\t\telse offset -= SCROLL_VIEW_MOUSE_WHEEL;\n\n\t\t\tif (offset < 0) offset = 0;\n\t\t\telse if (offset > (int)mHRange) offset = mHRange;\n\n\t\t\tif (offset != point.left)\n\t\t\t{\n\t\t\t\tpoint.left = -offset;\n\t\t\t\tif (mHScroll != nullptr)\n\t\t\t\t{\n\t\t\t\t\tmHScroll->setScrollPosition(offset);\n\t\t\t\t}\n\t\t\t\tmRealClient->setPosition(point);\n\t\t\t}\n\t\t}\n\t}\n\n\tIntSize ScrollView::getContentSize()\n\t{\n\t\treturn mRealClient == nullptr ? IntSize() : mRealClient->getSize();\n\t}\n\n\tIntPoint ScrollView::getContentPosition()\n\t{\n\t\treturn mRealClient == nullptr ? IntPoint() : (IntPoint() - mRealClient->getPosition());\n\t}\n\n\tvoid ScrollView::setContentPosition(const IntPoint& _point)\n\t{\n\t\tif (mRealClient != nullptr)\n\t\t\tmRealClient->setPosition(IntPoint() - _point);\n\t}\n\n\tIntSize ScrollView::getViewSize()\n\t{\n\t\treturn mClient == nullptr ? getSize() : mClient->getSize();\n\t}\n\n\tsize_t ScrollView::getVScrollPage()\n\t{\n\t\treturn SCROLL_VIEW_SCROLL_PAGE;\n\t}\n\n\tsize_t ScrollView::getHScrollPage()\n\t{\n\t\treturn SCROLL_VIEW_SCROLL_PAGE;\n\t}\n\n\tvoid ScrollView::updateView()\n\t{\n\t\tupdateScrollSize();\n\t\tupdateScrollPosition();\n\t}\n\n\tvoid ScrollView::setVisibleVScroll(bool _value)\n\t{\n\t\tmVisibleVScroll = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setVisibleHScroll(bool _value)\n\t{\n\t\tmVisibleHScroll = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCanvasAlign(Align _value)\n\t{\n\t\tmContentAlign = _value;\n\t\tupdateView();\n\t}\n\n\tvoid ScrollView::setCanvasSize(const IntSize& _value)\n\t{\n\t\tif (mRealClient != nullptr)\n\t\t\tmRealClient->setSize(_value);\n\t\tupdateView();\n\t}\n\n\tIntSize ScrollView::getCanvasSize()\n\t{\n\t\treturn mRealClient == nullptr ? IntSize() : mRealClient->getSize();\n\t}\n\n\tvoid ScrollView::setPropertyOverride(const std::string& _key, const std::string& _value)\n\t{\n\t\t\/\/\/ @wproperty{ScrollView, VisibleVScroll, bool} Видимость вертикальной полосы прокрутки.\n\t\tif (_key == \"VisibleVScroll\")\n\t\t\tsetVisibleVScroll(utility::parseValue<bool>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, VisibleHScroll, bool} Видимость горизонтальной полосы прокрутки.\n\t\telse if (_key == \"VisibleHScroll\")\n\t\t\tsetVisibleHScroll(utility::parseValue<bool>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, CanvasAlign, Align} Выравнивание содержимого.\n\t\telse if (_key == \"CanvasAlign\")\n\t\t\tsetCanvasAlign(utility::parseValue<Align>(_value));\n\n\t\t\/\/\/ @wproperty{ScrollView, CanvasSize, int int} Размер содержимого.\n\t\telse if (_key == \"CanvasSize\")\n\t\t\tsetCanvasSize(utility::parseValue<IntSize>(_value) * Gui::getInstance().getScaleFactor());\n\n\t\telse\n\t\t{\n\t\t\tBase::setPropertyOverride(_key, _value);\n\t\t\treturn;\n\t\t}\n\n\t\teventChangeProperty(this, _key, _value);\n\t}\n\n\tvoid ScrollView::setPosition(int _left, int _top)\n\t{\n\t\tsetPosition(IntPoint(_left, _top));\n\t}\n\n\tvoid ScrollView::setSize(int _width, int _height)\n\t{\n\t\tsetSize(IntSize(_width, _height));\n\t}\n\n\tvoid ScrollView::setCoord(int _left, int _top, int _width, int _height)\n\t{\n\t\tsetCoord(IntCoord(_left, _top, _width, _height));\n\t}\n\n\tbool ScrollView::isVisibleVScroll() const\n\t{\n\t\treturn mVisibleVScroll;\n\t}\n\n\tbool ScrollView::isVisibleHScroll() const\n\t{\n\t\treturn mVisibleHScroll;\n\t}\n\n\tAlign ScrollView::getCanvasAlign() const\n\t{\n\t\treturn mContentAlign;\n\t}\n\n\tvoid ScrollView::setCanvasSize(int _width, int _height)\n\t{\n\t\tsetCanvasSize(IntSize(_width, _height));\n\t}\n\n\tAlign ScrollView::getContentAlign()\n\t{\n\t\treturn mContentAlign;\n\t}\n\n\tvoid ScrollView::setViewOffset(const IntPoint& _value)\n\t{\n\t\tIntPoint value = _value;\n\t\tIntPoint currentOffset = mRealClient->getPosition();\n\n\t\tif (mHRange != 0)\n\t\t{\n\t\t\tif (value.left > 0)\n\t\t\t\tvalue.left = 0;\n\t\t\telse if (value.left < -(int)mHRange)\n\t\t\t\tvalue.left = -(int)mHRange;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalue.left = currentOffset.left;\n\t\t}\n\n\t\tif (mVRange != 0)\n\t\t{\n\t\t\tif (value.top > 0)\n\t\t\t\tvalue.top = 0;\n\t\t\telse if (value.top < -(int)mVRange)\n\t\t\t\tvalue.top = -(int)mVRange;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalue.top = currentOffset.top;\n\t\t}\n\n\t\tif (mHScroll != nullptr)\n\t\t\tmHScroll->setScrollPosition(-value.left);\n\n\t\tif (mVScroll != nullptr)\n\t\t\tmVScroll->setScrollPosition(-value.top);\n\n\t\tmRealClient->setPosition(value);\n\t}\n\n\tIntPoint ScrollView::getViewOffset() const\n\t{\n\t\treturn mRealClient->getPosition();\n\t}\n\n\tIntCoord ScrollView::getViewCoord() const\n\t{\n\t\treturn mClient == nullptr ? getCoord() : mClient->getCoord();\n\t}\n\n\tScrollBar* ScrollView::getVScroll()\n\t{\n\t\treturn mVScroll;\n\t}\n\n} \/\/ namespace MyGUI\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\/\/ This is a simple OpenCL Hello World that tests you have a functioning OpenCL setup.\n\n#include \"cl.hpp\"\n#include <initializer_list>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\nstatic inline void assert_cl(cl_int rc, const char* file, int line) {\n if (rc != CL_SUCCESS) {\n fprintf(stderr, \"%s:%d, got OpenCL error code %d\\n\", file,line,rc);\n exit(1);\n }\n}\n#define cl_ok(err) assert_cl(err, __FILE__, __LINE__)\n\nint main(int argc, char** argv) {\n \/\/ Find any OpenCL platform+device with these substrings.\n const char* platform_match = argc > 1 ? argv[1] : \"\";\n const char* device_match = argc > 2 ? argv[2] : \"\";\n\n cl::Platform platform;\n {\n std::vector<cl::Platform> platforms;\n cl_ok(cl::Platform::get(&platforms));\n\n bool found = false;\n for (cl::Platform p : platforms) {\n std::string name;\n cl_ok(p.getInfo(CL_PLATFORM_NAME, &name));\n\n fprintf(stdout, \"Available platform %s\\n\", name.c_str());\n\n if (name.find(platform_match) != std::string::npos) {\n platform = p;\n found = true;\n }\n }\n if (!found) {\n fprintf(stderr, \"No platform containing '%s' found.\\n\", platform_match);\n exit(1);\n }\n }\n\n cl::Device device;\n {\n std::vector<cl::Device> devices;\n cl_ok(platform.getDevices(CL_DEVICE_TYPE_ALL, &devices));\n\n bool found = false;\n for (cl::Device d : devices) {\n std::string name,\n version,\n driver;\n cl_ok(d.getInfo(CL_DEVICE_NAME, &name));\n cl_ok(d.getInfo(CL_DEVICE_VERSION, &version));\n cl_ok(d.getInfo(CL_DRIVER_VERSION, &driver));\n\n fprintf(stdout, \"Available device %s%s, driver version %s\\n\"\n , version.c_str(), name.c_str(), driver.c_str());\n\n if (name.find(device_match) != std::string::npos) {\n device = d;\n found = true;\n }\n }\n if (!found) {\n fprintf(stderr, \"No device containing '%s' found.\\n\", device_match);\n exit(2);\n }\n }\n\n std::string name,\n vendor,\n extensions;\n cl_ok(device.getInfo(CL_DEVICE_NAME, &name));\n cl_ok(device.getInfo(CL_DEVICE_VENDOR, &vendor));\n cl_ok(device.getInfo(CL_DEVICE_EXTENSIONS, &extensions));\n\n fprintf(stdout, \"Using %s, vendor %s, extensions:\\n%s\\n\",\n name.c_str(), vendor.c_str(), extensions.c_str());\n\n std::vector<cl::Device> devices = { device };\n\n \/\/ Some APIs can't return their cl_int error but might still fail,\n \/\/ so they take a pointer. cl_ok() is really handy here too.\n cl_int ok;\n cl::Context ctx(devices,\n nullptr\/*optional cl_context_properties*\/,\n nullptr\/*optional error reporting callback*\/,\n nullptr\/*context arguement for error reporting callback*\/,\n &ok);\n cl_ok(ok);\n\n cl::Program program(ctx,\n \"__kernel void mul(__global const float* a, \"\n \" __global const float* b, \"\n \" __global float* dst) {\"\n \" int i = get_global_id(0); \"\n \" dst[i] = a[i] * b[i]; \"\n \"} \",\n \/*and build now*\/true,\n &ok);\n cl_ok(ok);\n\n std::vector<float> a,b,p;\n for (int i = 0; i < 1000; i++) {\n a.push_back(+i);\n b.push_back(-i);\n p.push_back( 0);\n }\n\n cl::Buffer A(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*a.size(), a.data()),\n B(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*b.size(), b.data()),\n P(ctx, CL_MEM_WRITE_ONLY| CL_MEM_HOST_READ_ONLY, sizeof(float)*p.size());\n\n cl::Kernel mul(program, \"mul\", &ok);\n cl_ok(ok);\n cl_ok(mul.setArg(0, A));\n cl_ok(mul.setArg(1, B));\n cl_ok(mul.setArg(2, P));\n\n cl::CommandQueue queue(ctx, device);\n\n cl_ok(queue.enqueueNDRangeKernel(mul, cl::NDRange(0) \/*offset*\/\n , cl::NDRange(1000) \/*size*\/));\n\n cl_ok(queue.enqueueReadBuffer(P, true\/*block until read is done*\/\n , 0 \/*offset in bytes*\/\n , sizeof(float)*p.size() \/*size in bytes*\/\n , p.data()));\n\n for (int i = 0; i < 1000; i++) {\n if (p[i] != a[i]*b[i]) {\n return 1;\n }\n }\n\n fprintf(stdout, \"OpenCL sez: %g x %g = %g\\n\", a[42], b[42], p[42]);\n return 0;\n}\n<commit_msg>run all available OpenCL devices<commit_after>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\/\/ This is a simple OpenCL Hello World that tests you have a functioning OpenCL setup.\n\n#include \"cl.hpp\"\n#include <initializer_list>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\nstatic inline void assert_cl(cl_int rc, const char* file, int line) {\n if (rc != CL_SUCCESS) {\n fprintf(stderr, \"%s:%d, got OpenCL error code %d\\n\", file,line,rc);\n exit(1);\n }\n}\n#define cl_ok(err) assert_cl(err, __FILE__, __LINE__)\n\nint main(int, char**) {\n std::vector<cl::Platform> platforms;\n cl_ok(cl::Platform::get(&platforms));\n\n std::vector<cl::Device> devices;\n for (cl::Platform platform : platforms) {\n std::vector<cl::Device> platform_devices;\n cl_ok(platform.getDevices(CL_DEVICE_TYPE_ALL, &platform_devices));\n devices.insert(devices.end(), platform_devices.begin(), platform_devices.end());\n }\n\n if (devices.empty()) {\n fprintf(stderr, \"No OpenCL devices available. :(\\n\");\n return 1;\n }\n\n \/\/ To keep things simple we'll only create single-device cl::Contexts.\n for (cl::Device device : devices) {\n std::string name,\n version,\n driver,\n vendor,\n extensions;\n cl_ok(device.getInfo(CL_DEVICE_NAME, &name));\n cl_ok(device.getInfo(CL_DEVICE_VERSION, &version));\n cl_ok(device.getInfo(CL_DEVICE_VENDOR, &vendor));\n cl_ok(device.getInfo(CL_DEVICE_EXTENSIONS, &extensions));\n cl_ok(device.getInfo(CL_DRIVER_VERSION, &driver));\n\n fprintf(stdout, \"Using %s%s, vendor %s, version %s, extensions:\\n%s\\n\",\n version.c_str(), name.c_str(), vendor.c_str(), driver.c_str(), extensions.c_str());\n\n std::vector<cl::Device> devices = { device };\n\n \/\/ Some APIs can't return their cl_int error but might still fail,\n \/\/ so they take a pointer. cl_ok() is really handy here too.\n cl_int ok;\n cl::Context ctx(devices,\n nullptr\/*optional cl_context_properties*\/,\n nullptr\/*optional error reporting callback*\/,\n nullptr\/*context argument for error reporting callback*\/,\n &ok);\n cl_ok(ok);\n\n cl::Program program(ctx,\n \"__kernel void mul(__global const float* a, \"\n \" __global const float* b, \"\n \" __global float* dst) {\"\n \" int i = get_global_id(0); \"\n \" dst[i] = a[i] * b[i]; \"\n \"} \",\n \/*and build now*\/true,\n &ok);\n cl_ok(ok);\n\n std::vector<float> a,b,p;\n for (int i = 0; i < 1000; i++) {\n a.push_back(+i);\n b.push_back(-i);\n p.push_back( 0);\n }\n\n cl::Buffer\n A(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*a.size(), a.data()),\n B(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*b.size(), b.data()),\n P(ctx, CL_MEM_WRITE_ONLY| CL_MEM_HOST_READ_ONLY, sizeof(float)*p.size());\n\n cl::Kernel mul(program, \"mul\", &ok);\n cl_ok(ok);\n cl_ok(mul.setArg(0, A));\n cl_ok(mul.setArg(1, B));\n cl_ok(mul.setArg(2, P));\n\n cl::CommandQueue queue(ctx, device);\n\n cl_ok(queue.enqueueNDRangeKernel(mul, cl::NDRange(0) \/*offset*\/\n , cl::NDRange(1000) \/*size*\/));\n\n cl_ok(queue.enqueueReadBuffer(P, true\/*block until read is done*\/\n , 0 \/*offset in bytes*\/\n , sizeof(float)*p.size() \/*size in bytes*\/\n , p.data()));\n\n fprintf(stdout, \"OpenCL sez: %g x %g = %g\\n\", a[42], b[42], p[42]);\n for (int i = 0; i < 1000; i++) {\n if (p[i] != a[i]*b[i]) {\n return 1;\n }\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sitkCastImageFilter.h\"\n#include \"sitkCastImageFilter.txx\"\n\n\nnamespace itk\n{\nnamespace simple\n{\n\n\nvoid CastImageFilter::RegisterMemberFactory2()\n{\n\n \/\/ cast between vector images\n m_DualMemberFactory->RegisterMemberFunctions<VectorPixelIDTypeList, VectorPixelIDTypeList, 2, CastAddressor<MemberFunctionType> > ();\n\n \/\/ basic to vector\n m_DualMemberFactory->RegisterMemberFunctions<BasicPixelIDTypeList, VectorPixelIDTypeList, 2, ToVectorAddressor<MemberFunctionType> > ();\n\n}\n\n} \/\/ end namespace simple\n} \/\/ end namespace itk\n<commit_msg>BUG: incorrect function name in CastImageFilter instiation file<commit_after>#include \"sitkCastImageFilter.h\"\n#include \"sitkCastImageFilter.txx\"\n\n\nnamespace itk\n{\nnamespace simple\n{\n\n\nvoid CastImageFilter::RegisterMemberFactory2v()\n{\n\n \/\/ cast between vector images\n m_DualMemberFactory->RegisterMemberFunctions<VectorPixelIDTypeList, VectorPixelIDTypeList, 2, CastAddressor<MemberFunctionType> > ();\n\n \/\/ basic to vector\n m_DualMemberFactory->RegisterMemberFunctions<BasicPixelIDTypeList, VectorPixelIDTypeList, 2, ToVectorAddressor<MemberFunctionType> > ();\n\n}\n\n} \/\/ end namespace simple\n} \/\/ end namespace itk\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbSpectralSensitivityReader.h\"\n\n#include \"base\/ossimFilename.h\"\n#include <fstream>\n#include \"otbSpotImageMetadataInterface.h\"\n#include \"itkExceptionObject.h\"\n\nnamespace otb\n{\nSpectralSensitivityReader\n::SpectralSensitivityReader() :\n m_FileName(\"\"),\n m_DataPath(\"\")\n{\n this->Superclass::SetNumberOfRequiredOutputs(1);\n this->Superclass::SetNthOutput(0, WavelengthSpectralBandVectorType::New().GetPointer());\n m_Image = ImageType::New();\n}\n\nSpectralSensitivityReader\n::~SpectralSensitivityReader()\n{\n}\n\nSpectralSensitivityReader::WavelengthSpectralBandVectorType *\nSpectralSensitivityReader\n::GetOutput()\n{\n if (this->GetNumberOfOutputs() < 1)\n {\n return 0;\n }\n return static_cast<WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));\n}\n\nconst SpectralSensitivityReader::WavelengthSpectralBandVectorType *\nSpectralSensitivityReader\n::GetOutput() const\n{\n if (this->GetNumberOfOutputs() < 1)\n {\n return 0;\n }\n return static_cast<const WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));\n}\n\nvoid\nSpectralSensitivityReader\n::FindFileName()\n{\n if (m_Image.IsNull())\n {\n itkExceptionMacro(<< \"An input image has to be set or set directly the filename\");\n }\n\n ossimString sensor(\"\");\n itk::OStringStream oss;\n\n try\n {\n SpotImageMetadataInterface::Pointer lImageMetadata = SpotImageMetadataInterface::New();\n sensor = ossimString(lImageMetadata->GetSensorID());\n sensor.upcase();\n \/\/ Suppress spaces\n for (unsigned int i = 0; i < sensor.size() - 1; i++)\n {\n if (sensor.compare(i, 1, \" \") == 0)\n {\n sensor.erase(i, 1);\n i--;\n }\n }\n\n oss.str(\"\");\n oss << lImageMetadata->GetInstrument();\n oss << lImageMetadata->GetInstrumentIndex();\n }\n catch (itk::ExceptionObject& err)\n {\n itkExceptionMacro(<< \"Invalid input image\");\n }\n\n std::string instrument = oss.str();\n\n oss.str(\"\");\n oss << m_DataPath;\n oss << \"\/\";\n oss << sensor;\n oss << \"\/\";\n oss << instrument;\n oss << \"\/rep6S.dat\";\n\n m_FileName = oss.str();\n}\n\nvoid\nSpectralSensitivityReader\n::GenerateData()\n{\n if (m_FileName == \"\") this->FindFileName();\n\n WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();\n\n ossimFilename fname(m_FileName);\n if (!fname.exists()) itkExceptionMacro(<< m_FileName << \" does not exist.\");\n\n std::ifstream file(fname.c_str());\n if (!file) itkExceptionMacro(<< \"Enable to read \" << fname << \" file.\");\n\n std::string line;\n ossimString separator = \" \";\n double mini = 0;\n double maxi = 0.;\n bool firstLine = true;\n\n unsigned int nbBands = 0;\n \/\/ used to store the coef\n std::vector<ValuesVectorType> valuesVector;\n\n while (std::getline(file, line))\n {\n ossimString osLine(line);\n\n \/\/ Suppress multiple spaces\n for (unsigned int i = 0; i < osLine.size() - 1; i++)\n {\n if (osLine.compare(i, 1, \" \") == 0 && osLine.compare(i + 1, 1, \" \") == 0)\n {\n osLine.erase(i + 1, 1);\n i--;\n }\n }\n \/\/ if the first character is a space, erase it\n if (osLine.compare(0, 1, \" \") == 0) osLine.erase(0, 1);\n\n std::vector<ossimString> keywordStrings = osLine.split(separator);\n\n if (keywordStrings.size() < 3) itkExceptionMacro(<< \"Invalid file format\");\n\n \/\/ Store min wavelength\n if (firstLine)\n {\n mini = keywordStrings[0].toDouble();\n nbBands = keywordStrings.size() - 2;\n for (unsigned int j = 0; j < nbBands; j++)\n {\n wavelengthSpectralBand->PushBack(FilterFunctionValues::New());\n ValuesVectorType temp;\n valuesVector.push_back(temp);\n }\n firstLine = false;\n }\n\n if (nbBands != keywordStrings.size() - 2) itkExceptionMacro(<< \"Invalid file format\");\n\n for (unsigned int i = 0; i < nbBands; i++)\n {\n valuesVector[i].push_back(keywordStrings[i + 2].toDouble());\n }\n\n maxi = keywordStrings[0].toDouble();\n } \/\/while ( std::getline( file, line ) )\n\n for (unsigned int j = 0; j < nbBands; j++)\n {\n wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(valuesVector[j]);\n wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(mini);\n wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(maxi);\n }\n}\n\n\/**PrintSelf method *\/\nvoid\nSpectralSensitivityReader\n::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n os << \"DataPath: \" << m_DataPath << std::endl;\n if (m_FileName != \"\") os << \"FileName: \" << m_FileName << std::endl;\n\n \/\/ Function values print :\n const WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();\n os << \"Filter function values: \" << std::endl;\n for (unsigned int i = 0; i < wavelengthSpectralBand->Size(); ++i)\n {\n os << indent << \"Channel \" << i + 1 << \" : \" << std::endl;\n os << indent << wavelengthSpectralBand->GetNthElement(i) << std::endl;\n }\n}\n\n} \/\/ end namespace otb\n<commit_msg>BUG: side effect of MetadataInterface redesign<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbSpectralSensitivityReader.h\"\n\n#include \"base\/ossimFilename.h\"\n#include <fstream>\n#include \"otbSpotImageMetadataInterface.h\"\n#include \"itkExceptionObject.h\"\n\nnamespace otb\n{\nSpectralSensitivityReader\n::SpectralSensitivityReader() :\n m_FileName(\"\"),\n m_DataPath(\"\")\n{\n this->Superclass::SetNumberOfRequiredOutputs(1);\n this->Superclass::SetNthOutput(0, WavelengthSpectralBandVectorType::New().GetPointer());\n m_Image = ImageType::New();\n}\n\nSpectralSensitivityReader\n::~SpectralSensitivityReader()\n{\n}\n\nSpectralSensitivityReader::WavelengthSpectralBandVectorType *\nSpectralSensitivityReader\n::GetOutput()\n{\n if (this->GetNumberOfOutputs() < 1)\n {\n return 0;\n }\n return static_cast<WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));\n}\n\nconst SpectralSensitivityReader::WavelengthSpectralBandVectorType *\nSpectralSensitivityReader\n::GetOutput() const\n{\n if (this->GetNumberOfOutputs() < 1)\n {\n return 0;\n }\n return static_cast<const WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));\n}\n\nvoid\nSpectralSensitivityReader\n::FindFileName()\n{\n if (m_Image.IsNull())\n {\n itkExceptionMacro(<< \"An input image has to be set or set directly the filename\");\n }\n\n ossimString sensor(\"\");\n itk::OStringStream oss;\n\n try\n {\n SpotImageMetadataInterface::Pointer lImageMetadata = SpotImageMetadataInterface::New();\n lImageMetadata->SetMetaDataDictionary(m_Image->GetMetaDataDictionary());\n sensor = ossimString(lImageMetadata->GetSensorID());\n sensor.upcase();\n \/\/ Suppress spaces\n for (unsigned int i = 0; i < sensor.size() - 1; i++)\n {\n if (sensor.compare(i, 1, \" \") == 0)\n {\n sensor.erase(i, 1);\n i--;\n }\n }\n\n oss.str(\"\");\n oss << lImageMetadata->GetInstrument();\n oss << lImageMetadata->GetInstrumentIndex();\n }\n catch (itk::ExceptionObject& err)\n {\n itkExceptionMacro(<< \"Invalid input image\");\n }\n\n std::string instrument = oss.str();\n\n oss.str(\"\");\n oss << m_DataPath;\n oss << \"\/\";\n oss << sensor;\n oss << \"\/\";\n oss << instrument;\n oss << \"\/rep6S.dat\";\n\n m_FileName = oss.str();\n}\n\nvoid\nSpectralSensitivityReader\n::GenerateData()\n{\n if (m_FileName == \"\") this->FindFileName();\n\n WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();\n\n ossimFilename fname(m_FileName);\n if (!fname.exists()) itkExceptionMacro(<< m_FileName << \" does not exist.\");\n\n std::ifstream file(fname.c_str());\n if (!file) itkExceptionMacro(<< \"Enable to read \" << fname << \" file.\");\n\n std::string line;\n ossimString separator = \" \";\n double mini = 0;\n double maxi = 0.;\n bool firstLine = true;\n\n unsigned int nbBands = 0;\n \/\/ used to store the coef\n std::vector<ValuesVectorType> valuesVector;\n\n while (std::getline(file, line))\n {\n ossimString osLine(line);\n\n \/\/ Suppress multiple spaces\n for (unsigned int i = 0; i < osLine.size() - 1; i++)\n {\n if (osLine.compare(i, 1, \" \") == 0 && osLine.compare(i + 1, 1, \" \") == 0)\n {\n osLine.erase(i + 1, 1);\n i--;\n }\n }\n \/\/ if the first character is a space, erase it\n if (osLine.compare(0, 1, \" \") == 0) osLine.erase(0, 1);\n\n std::vector<ossimString> keywordStrings = osLine.split(separator);\n\n if (keywordStrings.size() < 3) itkExceptionMacro(<< \"Invalid file format\");\n\n \/\/ Store min wavelength\n if (firstLine)\n {\n mini = keywordStrings[0].toDouble();\n nbBands = keywordStrings.size() - 2;\n for (unsigned int j = 0; j < nbBands; j++)\n {\n wavelengthSpectralBand->PushBack(FilterFunctionValues::New());\n ValuesVectorType temp;\n valuesVector.push_back(temp);\n }\n firstLine = false;\n }\n\n if (nbBands != keywordStrings.size() - 2) itkExceptionMacro(<< \"Invalid file format\");\n\n for (unsigned int i = 0; i < nbBands; i++)\n {\n valuesVector[i].push_back(keywordStrings[i + 2].toDouble());\n }\n\n maxi = keywordStrings[0].toDouble();\n } \/\/while ( std::getline( file, line ) )\n\n for (unsigned int j = 0; j < nbBands; j++)\n {\n wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(valuesVector[j]);\n wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(mini);\n wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(maxi);\n }\n}\n\n\/**PrintSelf method *\/\nvoid\nSpectralSensitivityReader\n::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n os << \"DataPath: \" << m_DataPath << std::endl;\n if (m_FileName != \"\") os << \"FileName: \" << m_FileName << std::endl;\n\n \/\/ Function values print :\n const WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();\n os << \"Filter function values: \" << std::endl;\n for (unsigned int i = 0; i < wavelengthSpectralBand->Size(); ++i)\n {\n os << indent << \"Channel \" << i + 1 << \" : \" << std::endl;\n os << indent << wavelengthSpectralBand->GetNthElement(i) << std::endl;\n }\n}\n\n} \/\/ end namespace otb\n<|endoftext|>"} {"text":"<commit_before>\/*\n * HyperbolicGenerator.cpp\n *\n * Created on: 20.05.2014\n * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu)\n * This generator is a simplified version of the model presented in\n * \"Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010.\" by\n * Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna\n *\n *\/\n\n#include <cstdlib>\n#include <random>\n#include <math.h>\n#include <assert.h>\n#include <omp.h>\n\n#include \"..\/graph\/GraphBuilder.h\"\n#include \"HyperbolicGenerator.h\"\n#include \"Quadtree\/Quadtree.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/auxiliary\/ProgressMeter.h\"\n\n\nnamespace NetworKit {\n\n\nHyperbolicGenerator::HyperbolicGenerator() {\n\tstretch = 1;\n\talpha = 1;\n\tfactor = 1;\n\tnodeCount = 10000;\n\tinitialize();\n}\n\/**\n * Construct a generator for n nodes and the parameters, t, alpha and s.\n *\/\nHyperbolicGenerator::HyperbolicGenerator(count n, double distanceFactor, double alpha, double stretchradius) {\n\tnodeCount = n;\n\tstretch = stretchradius;\n\tfactor = distanceFactor;\n\tthis->alpha = alpha;\n\tinitialize();\n}\n\/**\n * Construct a generator for n nodes and m edges\n *\/\nHyperbolicGenerator::HyperbolicGenerator(count n, count m) {\n\tnodeCount = n;\n\tdouble R = HyperbolicSpace::hyperbolicAreaToRadius(n);\n\tdouble targetR = 2*log(8*n \/ (M_PI*(m\/n)*2));\n\tstretch = targetR \/ R;\n\tfactor = 1;\n\talpha = 1;\n\tinitialize();\n}\n\nvoid HyperbolicGenerator::initialize() {\n\tcapacity = 1000;\n\ttheoreticalSplit = false;\n\tthreadtimers.resize(omp_get_max_threads());\n}\n\nGraph HyperbolicGenerator::generate() {\n\treturn generate(nodeCount, factor, alpha, stretch);\n}\n\nGraph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius) {\n\tdouble R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n);\n\tvector<double> angles(n);\n\tvector<double> radii(n);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\t\/\/sample points randomly\n\n\tHyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha);\n\tvector<index> permutation(n);\n\n\tindex p = 0;\n\tstd::generate(permutation.begin(), permutation.end(), [&p](){return p++;});\n\n\t\/\/can probably be parallelized easily, but doesn't bring much benefit\n\tstd::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);});\n\n\tvector<double> anglecopy(n);\n\tvector<double> radiicopy(n);\n\n\t#pragma omp parallel for\n\tfor (index j = 0; j < n; j++) {\n\t\tanglecopy[j] = angles[permutation[j]];\n\t\tradiicopy[j] = radii[permutation[j]];\n\t}\n\n\tINFO(\"Generated Points\");\n\treturn generate(anglecopy, radiicopy, r, R*distanceFactor);\n}\n\ndouble HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) {\n\tdouble R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n);\n\treturn (8 \/ M_PI) * n * exp(-R\/2)*(n\/2);\n}\n\nGraph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double R, double thresholdDistance) {\n\tAux::Timer timer;\n\ttimer.start();\n\tindex n = angles.size();\n\tassert(radii.size() == n);\n\tQuadtree<index> quad(R, theoreticalSplit, alpha, capacity);\n\n\t\/\/initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap\n\tfor (index i = 0; i < n; i++) {\n\t\tassert(radii[i] < R);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\n\tquad.trim();\n\ttimer.stop();\n\tINFO(\"Filled Quadtree, took \", timer.elapsedMilliseconds(), \" milliseconds.\");\n\n\treturn generate(angles, radii, quad, thresholdDistance);\n}\n\nGraph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) {\n\tindex n = angles.size();\n\tassert(radii.size() == n);\n\tAux::Timer timer;\n\ttimer.start();\n\tvector<double> empty;\n\tGraphBuilder result(n, false, false, true);\n\n\tAux::ProgressMeter progress(n, 10000);\n\t#pragma omp parallel\n\t{\n\t\tindex id = omp_get_thread_num();\n\t\tthreadtimers[id].start();\n\t\t#pragma omp for schedule(dynamic) nowait\n\t\tfor (index i = 0; i < n; i++) {\n\t\t\t\/\/get neighbours for node i\n\t\t\tcount expectedDegree = (4\/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])\/2);\n\t\t\tvector<index> near;\n\t\t\tnear.reserve(expectedDegree*1.1);\n\t\t\tquad.getElementsInHyperbolicCircle(i, HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, near);\n\t\t\t\/\/count realDegree = near.size();\n\t\t\t\/\/std::swap(expectedDegree, realDegree);\/\/dummy statement for debugging\n\t\t\t\/\/result.swapNeighborhood(i, near, empty, false);\n\n\t\t\tif (i % 10000 == 0) {\n\t\t\t\t#pragma omp critical (progress)\n\t\t\t\t{\n\t\t\t\t\tprogress.signal(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthreadtimers[id].stop();\n\t}\n\n\ttimer.stop();\n\tINFO(\"Generating Edges took \", timer.elapsedMilliseconds(), \" milliseconds.\");\n\treturn result.toGraph(true);\n}\n}\n<commit_msg>Don't forget to build actual graph<commit_after>\/*\n * HyperbolicGenerator.cpp\n *\n * Created on: 20.05.2014\n * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu)\n * This generator is a simplified version of the model presented in\n * \"Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010.\" by\n * Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna\n *\n *\/\n\n#include <cstdlib>\n#include <random>\n#include <math.h>\n#include <assert.h>\n#include <omp.h>\n\n#include \"..\/graph\/GraphBuilder.h\"\n#include \"HyperbolicGenerator.h\"\n#include \"Quadtree\/Quadtree.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/auxiliary\/ProgressMeter.h\"\n\n\nnamespace NetworKit {\n\n\nHyperbolicGenerator::HyperbolicGenerator() {\n\tstretch = 1;\n\talpha = 1;\n\tfactor = 1;\n\tnodeCount = 10000;\n\tinitialize();\n}\n\/**\n * Construct a generator for n nodes and the parameters, t, alpha and s.\n *\/\nHyperbolicGenerator::HyperbolicGenerator(count n, double distanceFactor, double alpha, double stretchradius) {\n\tnodeCount = n;\n\tstretch = stretchradius;\n\tfactor = distanceFactor;\n\tthis->alpha = alpha;\n\tinitialize();\n}\n\/**\n * Construct a generator for n nodes and m edges\n *\/\nHyperbolicGenerator::HyperbolicGenerator(count n, count m) {\n\tnodeCount = n;\n\tdouble R = HyperbolicSpace::hyperbolicAreaToRadius(n);\n\tdouble targetR = 2*log(8*n \/ (M_PI*(m\/n)*2));\n\tstretch = targetR \/ R;\n\tfactor = 1;\n\talpha = 1;\n\tinitialize();\n}\n\nvoid HyperbolicGenerator::initialize() {\n\tcapacity = 1000;\n\ttheoreticalSplit = false;\n\tthreadtimers.resize(omp_get_max_threads());\n}\n\nGraph HyperbolicGenerator::generate() {\n\treturn generate(nodeCount, factor, alpha, stretch);\n}\n\nGraph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius) {\n\tdouble R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n);\n\tvector<double> angles(n);\n\tvector<double> radii(n);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\t\/\/sample points randomly\n\n\tHyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha);\n\tvector<index> permutation(n);\n\n\tindex p = 0;\n\tstd::generate(permutation.begin(), permutation.end(), [&p](){return p++;});\n\n\t\/\/can probably be parallelized easily, but doesn't bring much benefit\n\tstd::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);});\n\n\tvector<double> anglecopy(n);\n\tvector<double> radiicopy(n);\n\n\t#pragma omp parallel for\n\tfor (index j = 0; j < n; j++) {\n\t\tanglecopy[j] = angles[permutation[j]];\n\t\tradiicopy[j] = radii[permutation[j]];\n\t}\n\n\tINFO(\"Generated Points\");\n\treturn generate(anglecopy, radiicopy, r, R*distanceFactor);\n}\n\ndouble HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) {\n\tdouble R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n);\n\treturn (8 \/ M_PI) * n * exp(-R\/2)*(n\/2);\n}\n\nGraph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double R, double thresholdDistance) {\n\tAux::Timer timer;\n\ttimer.start();\n\tindex n = angles.size();\n\tassert(radii.size() == n);\n\tQuadtree<index> quad(R, theoreticalSplit, alpha, capacity);\n\n\t\/\/initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap\n\tfor (index i = 0; i < n; i++) {\n\t\tassert(radii[i] < R);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\n\tquad.trim();\n\ttimer.stop();\n\tINFO(\"Filled Quadtree, took \", timer.elapsedMilliseconds(), \" milliseconds.\");\n\n\treturn generate(angles, radii, quad, thresholdDistance);\n}\n\nGraph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) {\n\tindex n = angles.size();\n\tassert(radii.size() == n);\n\tAux::Timer timer;\n\ttimer.start();\n\tvector<double> empty;\n\tGraphBuilder result(n, false, false, true);\n\n\tAux::ProgressMeter progress(n, 10000);\n\t#pragma omp parallel\n\t{\n\t\tindex id = omp_get_thread_num();\n\t\tthreadtimers[id].start();\n\t\t#pragma omp for schedule(dynamic) nowait\n\t\tfor (index i = 0; i < n; i++) {\n\t\t\t\/\/get neighbours for node i\n\t\t\tcount expectedDegree = (4\/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])\/2);\n\t\t\tvector<index> near;\n\t\t\tnear.reserve(expectedDegree*1.1);\n\t\t\tquad.getElementsInHyperbolicCircle(i, HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, near);\n\t\t\t\/\/count realDegree = near.size();\n\t\t\t\/\/std::swap(expectedDegree, realDegree);\/\/dummy statement for debugging\n\t\t\tresult.swapNeighborhood(i, near, empty, false);\n\n\t\t\tif (i % 10000 == 0) {\n\t\t\t\t#pragma omp critical (progress)\n\t\t\t\t{\n\t\t\t\t\tprogress.signal(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthreadtimers[id].stop();\n\t}\n\n\ttimer.stop();\n\tINFO(\"Generating Edges took \", timer.elapsedMilliseconds(), \" milliseconds.\");\n\treturn result.toGraph(true);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/resource_fetcher.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/message_loop.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLResponse.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebView.h\"\n#include \"webkit\/glue\/unittest_test_server.h\"\n#include \"webkit\/tools\/test_shell\/simple_resource_loader_bridge.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include <gtk\/gtk.h>\n#endif\n\nusing WebKit::WebFrame;\nusing WebKit::WebURLResponse;\nusing webkit_glue::ResourceFetcher;\nusing webkit_glue::ResourceFetcherWithTimeout;\n\nnamespace {\n\nclass ResourceFetcherTests : public TestShellTest {\n protected:\n UnittestTestServer test_server_;\n};\n\nstatic const int kMaxWaitTimeMs = 5000;\nstatic const int kWaitIntervalMs = 100;\n\nclass FetcherDelegate {\n public:\n FetcherDelegate()\n : timer_id_(0), completed_(false), time_elapsed_ms_(0) {\n \/\/ Start a repeating timer waiting for the download to complete. The\n \/\/ callback has to be a static function, so we hold on to our instance.\n FetcherDelegate::instance_ = this;\n CreateTimer(kWaitIntervalMs);\n }\n\n ResourceFetcher::Callback* NewCallback() {\n return ::NewCallback(this, &FetcherDelegate::OnURLFetchComplete);\n }\n\n void OnURLFetchComplete(const WebURLResponse& response,\n const std::string& data) {\n response_ = response;\n data_ = data;\n completed_ = true;\n DestroyTimer();\n MessageLoop::current()->Quit();\n }\n\n bool completed() const { return completed_; }\n bool timed_out() const { return time_elapsed_ms_ > kMaxWaitTimeMs; }\n\n int time_elapsed_ms() const { return time_elapsed_ms_; }\n std::string data() const { return data_; }\n const WebURLResponse& response() const { return response_; }\n\n \/\/ Wait for the request to complete or timeout. We use a loop here b\/c the\n \/\/ testing infrastructure (test_shell) can generate spurious calls to the\n \/\/ MessageLoop's Quit method.\n void WaitForResponse() {\n while (!completed() && !timed_out())\n MessageLoop::current()->Run();\n }\n\n void CreateTimer(int interval) {\n#if defined(OS_WIN)\n timer_id_ = ::SetTimer(NULL, NULL, interval,\n &FetcherDelegate::TimerCallback);\n#elif defined(TOOLKIT_USES_GTK)\n timer_id_ = g_timeout_add(interval, &FetcherDelegate::TimerCallback, NULL);\n#elif defined(OS_MACOSX)\n \/\/ CFAbsoluteTime is in seconds and |interval| is in ms, so make sure we\n \/\/ keep the units correct.\n CFTimeInterval interval_in_seconds = static_cast<double>(interval) \/ 1000.0;\n CFAbsoluteTime fire_date =\n CFAbsoluteTimeGetCurrent() + interval_in_seconds;\n timer_id_ = CFRunLoopTimerCreate(NULL, fire_date, interval_in_seconds, 0,\n 0, FetcherDelegate::TimerCallback, NULL);\n CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer_id_, kCFRunLoopCommonModes);\n#endif\n }\n\n void DestroyTimer() {\n#if defined(OS_WIN)\n ::KillTimer(NULL, timer_id_);\n#elif defined(TOOLKIT_USES_GTK)\n g_source_remove(timer_id_);\n#elif defined(OS_MACOSX)\n CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer_id_,\n kCFRunLoopCommonModes);\n CFRelease(timer_id_);\n#endif\n }\n\n#if defined(OS_WIN)\n \/\/ Static timer callback, just passes through to instance version.\n static VOID CALLBACK TimerCallback(HWND hwnd, UINT msg, UINT_PTR timer_id,\n DWORD ms) {\n instance_->TimerFired();\n }\n#elif defined(TOOLKIT_USES_GTK)\n static gboolean TimerCallback(gpointer data) {\n instance_->TimerFired();\n return true;\n }\n#elif defined(OS_MACOSX)\n static void TimerCallback(CFRunLoopTimerRef timer, void* info) {\n instance_->TimerFired();\n }\n#endif\n\n void TimerFired() {\n ASSERT_FALSE(completed_);\n\n if (timed_out()) {\n DestroyTimer();\n MessageLoop::current()->Quit();\n FAIL() << \"fetch timed out\";\n return;\n }\n\n time_elapsed_ms_ += kWaitIntervalMs;\n }\n\n static FetcherDelegate* instance_;\n\n private:\n#if defined(OS_WIN)\n UINT_PTR timer_id_;\n#elif defined(TOOLKIT_USES_GTK)\n guint timer_id_;\n#elif defined(OS_MACOSX)\n CFRunLoopTimerRef timer_id_;\n#endif\n bool completed_;\n int time_elapsed_ms_;\n WebURLResponse response_;\n std::string data_;\n};\n\nFetcherDelegate* FetcherDelegate::instance_ = NULL;\n\n\/\/ Test a fetch from the test server.\nTEST_F(ResourceFetcherTests, ResourceFetcherDownload) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n GURL url(test_server_.GetURL(\"files\/test_shell\/index.html\"));\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(\n url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n ASSERT_TRUE(delegate->completed());\n EXPECT_EQ(delegate->response().httpStatusCode(), 200);\n std::string text = delegate->data();\n EXPECT_TRUE(text.find(\"What is this page?\") != std::string::npos);\n\n \/\/ Test 404 response.\n url = test_server_.GetURL(\"files\/thisfiledoesntexist.html\");\n delegate.reset(new FetcherDelegate);\n fetcher.reset(new ResourceFetcher(url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n ASSERT_TRUE(delegate->completed());\n EXPECT_EQ(delegate->response().httpStatusCode(), 404);\n EXPECT_TRUE(delegate->data().find(\"Not Found.\") != std::string::npos);\n}\n\nTEST_F(ResourceFetcherTests, ResourceFetcherDidFail) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n \/\/ Try to fetch a page on a site that doesn't exist.\n GURL url(\"http:\/\/localhost:1339\/doesnotexist\");\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(\n url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n \/\/ When we fail, we still call the Delegate callback but we pass in empty\n \/\/ values.\n EXPECT_TRUE(delegate->completed());\n EXPECT_TRUE(delegate->response().isNull());\n EXPECT_EQ(delegate->data(), std::string());\n EXPECT_TRUE(delegate->time_elapsed_ms() < kMaxWaitTimeMs);\n}\n\nTEST_F(ResourceFetcherTests, ResourceFetcherTimeout) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n \/\/ Grab a page that takes at least 1 sec to respond, but set the fetcher to\n \/\/ timeout in 0 sec.\n GURL url(test_server_.GetURL(\"slow?1\"));\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(\n url, frame, 0, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n \/\/ When we timeout, we still call the Delegate callback but we pass in empty\n \/\/ values.\n EXPECT_TRUE(delegate->completed());\n EXPECT_TRUE(delegate->response().isNull());\n EXPECT_EQ(delegate->data(), std::string());\n EXPECT_TRUE(delegate->time_elapsed_ms() < kMaxWaitTimeMs);\n}\n\n} \/\/ namespace\n<commit_msg>Mark ResourceFetcherTests.ResourceFetcherDownload and ResourceFetcherDidFail as FLAKY<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/resource_fetcher.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/message_loop.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLResponse.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebView.h\"\n#include \"webkit\/glue\/unittest_test_server.h\"\n#include \"webkit\/tools\/test_shell\/simple_resource_loader_bridge.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include <gtk\/gtk.h>\n#endif\n\nusing WebKit::WebFrame;\nusing WebKit::WebURLResponse;\nusing webkit_glue::ResourceFetcher;\nusing webkit_glue::ResourceFetcherWithTimeout;\n\nnamespace {\n\nclass ResourceFetcherTests : public TestShellTest {\n protected:\n UnittestTestServer test_server_;\n};\n\nstatic const int kMaxWaitTimeMs = 5000;\nstatic const int kWaitIntervalMs = 100;\n\nclass FetcherDelegate {\n public:\n FetcherDelegate()\n : timer_id_(0), completed_(false), time_elapsed_ms_(0) {\n \/\/ Start a repeating timer waiting for the download to complete. The\n \/\/ callback has to be a static function, so we hold on to our instance.\n FetcherDelegate::instance_ = this;\n CreateTimer(kWaitIntervalMs);\n }\n\n ResourceFetcher::Callback* NewCallback() {\n return ::NewCallback(this, &FetcherDelegate::OnURLFetchComplete);\n }\n\n void OnURLFetchComplete(const WebURLResponse& response,\n const std::string& data) {\n response_ = response;\n data_ = data;\n completed_ = true;\n DestroyTimer();\n MessageLoop::current()->Quit();\n }\n\n bool completed() const { return completed_; }\n bool timed_out() const { return time_elapsed_ms_ > kMaxWaitTimeMs; }\n\n int time_elapsed_ms() const { return time_elapsed_ms_; }\n std::string data() const { return data_; }\n const WebURLResponse& response() const { return response_; }\n\n \/\/ Wait for the request to complete or timeout. We use a loop here b\/c the\n \/\/ testing infrastructure (test_shell) can generate spurious calls to the\n \/\/ MessageLoop's Quit method.\n void WaitForResponse() {\n while (!completed() && !timed_out())\n MessageLoop::current()->Run();\n }\n\n void CreateTimer(int interval) {\n#if defined(OS_WIN)\n timer_id_ = ::SetTimer(NULL, NULL, interval,\n &FetcherDelegate::TimerCallback);\n#elif defined(TOOLKIT_USES_GTK)\n timer_id_ = g_timeout_add(interval, &FetcherDelegate::TimerCallback, NULL);\n#elif defined(OS_MACOSX)\n \/\/ CFAbsoluteTime is in seconds and |interval| is in ms, so make sure we\n \/\/ keep the units correct.\n CFTimeInterval interval_in_seconds = static_cast<double>(interval) \/ 1000.0;\n CFAbsoluteTime fire_date =\n CFAbsoluteTimeGetCurrent() + interval_in_seconds;\n timer_id_ = CFRunLoopTimerCreate(NULL, fire_date, interval_in_seconds, 0,\n 0, FetcherDelegate::TimerCallback, NULL);\n CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer_id_, kCFRunLoopCommonModes);\n#endif\n }\n\n void DestroyTimer() {\n#if defined(OS_WIN)\n ::KillTimer(NULL, timer_id_);\n#elif defined(TOOLKIT_USES_GTK)\n g_source_remove(timer_id_);\n#elif defined(OS_MACOSX)\n CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer_id_,\n kCFRunLoopCommonModes);\n CFRelease(timer_id_);\n#endif\n }\n\n#if defined(OS_WIN)\n \/\/ Static timer callback, just passes through to instance version.\n static VOID CALLBACK TimerCallback(HWND hwnd, UINT msg, UINT_PTR timer_id,\n DWORD ms) {\n instance_->TimerFired();\n }\n#elif defined(TOOLKIT_USES_GTK)\n static gboolean TimerCallback(gpointer data) {\n instance_->TimerFired();\n return true;\n }\n#elif defined(OS_MACOSX)\n static void TimerCallback(CFRunLoopTimerRef timer, void* info) {\n instance_->TimerFired();\n }\n#endif\n\n void TimerFired() {\n ASSERT_FALSE(completed_);\n\n if (timed_out()) {\n DestroyTimer();\n MessageLoop::current()->Quit();\n FAIL() << \"fetch timed out\";\n return;\n }\n\n time_elapsed_ms_ += kWaitIntervalMs;\n }\n\n static FetcherDelegate* instance_;\n\n private:\n#if defined(OS_WIN)\n UINT_PTR timer_id_;\n#elif defined(TOOLKIT_USES_GTK)\n guint timer_id_;\n#elif defined(OS_MACOSX)\n CFRunLoopTimerRef timer_id_;\n#endif\n bool completed_;\n int time_elapsed_ms_;\n WebURLResponse response_;\n std::string data_;\n};\n\nFetcherDelegate* FetcherDelegate::instance_ = NULL;\n\n\/\/ Test a fetch from the test server.\n\/\/ Flaky, http:\/\/crbug.com\/51622.\nTEST_F(ResourceFetcherTests, FLAKY_ResourceFetcherDownload) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n GURL url(test_server_.GetURL(\"files\/test_shell\/index.html\"));\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(\n url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n ASSERT_TRUE(delegate->completed());\n EXPECT_EQ(delegate->response().httpStatusCode(), 200);\n std::string text = delegate->data();\n EXPECT_TRUE(text.find(\"What is this page?\") != std::string::npos);\n\n \/\/ Test 404 response.\n url = test_server_.GetURL(\"files\/thisfiledoesntexist.html\");\n delegate.reset(new FetcherDelegate);\n fetcher.reset(new ResourceFetcher(url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n ASSERT_TRUE(delegate->completed());\n EXPECT_EQ(delegate->response().httpStatusCode(), 404);\n EXPECT_TRUE(delegate->data().find(\"Not Found.\") != std::string::npos);\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51622.\nTEST_F(ResourceFetcherTests, FLAKY_ResourceFetcherDidFail) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n \/\/ Try to fetch a page on a site that doesn't exist.\n GURL url(\"http:\/\/localhost:1339\/doesnotexist\");\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(\n url, frame, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n \/\/ When we fail, we still call the Delegate callback but we pass in empty\n \/\/ values.\n EXPECT_TRUE(delegate->completed());\n EXPECT_TRUE(delegate->response().isNull());\n EXPECT_EQ(delegate->data(), std::string());\n EXPECT_TRUE(delegate->time_elapsed_ms() < kMaxWaitTimeMs);\n}\n\nTEST_F(ResourceFetcherTests, ResourceFetcherTimeout) {\n ASSERT_TRUE(test_server_.Start());\n\n WebFrame* frame = test_shell_->webView()->mainFrame();\n\n \/\/ Grab a page that takes at least 1 sec to respond, but set the fetcher to\n \/\/ timeout in 0 sec.\n GURL url(test_server_.GetURL(\"slow?1\"));\n scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);\n scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(\n url, frame, 0, delegate->NewCallback()));\n\n delegate->WaitForResponse();\n\n \/\/ When we timeout, we still call the Delegate callback but we pass in empty\n \/\/ values.\n EXPECT_TRUE(delegate->completed());\n EXPECT_TRUE(delegate->response().isNull());\n EXPECT_EQ(delegate->data(), std::string());\n EXPECT_TRUE(delegate->time_elapsed_ms() < kMaxWaitTimeMs);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <osquery\/core.h>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n\n#include \"osquery\/core\/conversions.h\"\n#include \"osquery\/events\/linux\/udev.h\"\n\nnamespace osquery {\nnamespace tables {\n\nconst std::string kUSBKeyVendorID = \"ID_VENDOR_ID\";\nconst std::string kUSBKeyVendor = \"ID_VENDOR_FROM_DATABASE\";\nconst std::string kUSBKeyModelID = \"ID_MODEL_ID\";\nconst std::string kUSBKeyModel = \"ID_MODEL_FROM_DATABASE\";\nconst std::string kUSBKeyDriver = \"ID_USB_DRIVER\";\nconst std::string kUSBKeySubsystem = \"SUBSYSTEM\";\nconst std::string kUSBKeySerial = \"ID_SERIAL_SHORT\";\nconst std::string kUSBKeyAddress = \"BUSNUM\";\nconst std::string kUSBKeyPort = \"DEVNUM\";\nconst std::string kUSBKeyType = \"TYPE\";\n\nQueryData genUSBDevices(QueryContext &context) {\n QueryData results;\n\n auto udev_handle = udev_new();\n if (udev_handle == nullptr) {\n VLOG(1) << \"Could not get udev handle\";\n return results;\n }\n\n \/\/ Perform enumeration\/search.\n auto enumerate = udev_enumerate_new(udev_handle);\n udev_enumerate_add_match_subsystem(enumerate, \"usb\");\n udev_enumerate_scan_devices(enumerate);\n\n \/\/ Get list entries and iterate over entries.\n struct udev_list_entry *device_entries, *entry;\n device_entries = udev_enumerate_get_list_entry(enumerate);\n\n udev_list_entry_foreach(entry, device_entries) {\n const char *path = udev_list_entry_get_name(entry);\n auto device = udev_device_new_from_syspath(udev_handle, path);\n\n Row r;\n \/\/ r[\"driver\"] = UdevEventPublisher::getValue(device, kUSBKeyDriver);\n r[\"vendor\"] = UdevEventPublisher::getValue(device, kUSBKeyVendor);\n r[\"model\"] = UdevEventPublisher::getValue(device, kUSBKeyModel);\n\n \/\/ USB-specific vendor\/model ID properties.\n r[\"model_id\"] = UdevEventPublisher::getValue(device, kUSBKeyModelID);\n r[\"vendor_id\"] = UdevEventPublisher::getValue(device, kUSBKeyVendorID);\n r[\"serial\"] = UdevEventPublisher::getValue(device, kUSBKeySerial);\n\n \/\/ This will be of the form class\/subclass\/protocol and has to be parsed\n auto devType = UdevEventPublisher::getValue(device, kUSBKeyType);\n auto classInfo = osquery::split(devType, \"\/\");\n if (classInfo.size() == 3) {\n r[\"class\"] = classInfo[0];\n r[\"subclass\"] = classInfo[1];\n r[\"protocol\"] = classInfo[2];\n } else {\n r[\"class\"] = \"\";\n r[\"subclass\"] = \"\";\n r[\"protocol\"] = \"\";\n }\n\n \/\/ Address\/port accessors.\n r[\"usb_address\"] = UdevEventPublisher::getValue(device, kUSBKeyAddress);\n r[\"usb_port\"] = UdevEventPublisher::getValue(device, kUSBKeyPort);\n\n \/\/ Removable detection.\n auto removable = UdevEventPublisher::getAttr(device, \"removable\");\n if (removable == \"unknown\") {\n r[\"removable\"] = \"-1\";\n } else {\n r[\"removable\"] = \"1\";\n }\n\n if (r[\"usb_address\"].size() > 0 && r[\"usb_port\"].size() > 0) {\n results.push_back(r);\n }\n udev_device_unref(device);\n }\n\n \/\/ Drop references to udev structs.\n udev_enumerate_unref(enumerate);\n udev_unref(udev_handle);\n\n return results;\n}\n}\n}\n<commit_msg>[usb_devices] fallback to ID_MODEL if ID_MODEL_FROM_DATABASE is absent (#3686)<commit_after>\/*\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <osquery\/core.h>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n\n#include \"osquery\/core\/conversions.h\"\n#include \"osquery\/events\/linux\/udev.h\"\n\nnamespace osquery {\nnamespace tables {\n\nconst std::string kUSBKeyVendorID = \"ID_VENDOR_ID\";\nconst std::string kUSBKeyVendor = \"ID_VENDOR_FROM_DATABASE\";\nconst std::string kUSBKeyModelID = \"ID_MODEL_ID\";\nconst std::string kUSBKeyModel = \"ID_MODEL_FROM_DATABASE\";\nconst std::string kUSBKeyModelFallback = \"ID_MODEL\";\nconst std::string kUSBKeyDriver = \"ID_USB_DRIVER\";\nconst std::string kUSBKeySubsystem = \"SUBSYSTEM\";\nconst std::string kUSBKeySerial = \"ID_SERIAL_SHORT\";\nconst std::string kUSBKeyAddress = \"BUSNUM\";\nconst std::string kUSBKeyPort = \"DEVNUM\";\nconst std::string kUSBKeyType = \"TYPE\";\n\nQueryData genUSBDevices(QueryContext &context) {\n QueryData results;\n\n auto udev_handle = udev_new();\n if (udev_handle == nullptr) {\n VLOG(1) << \"Could not get udev handle\";\n return results;\n }\n\n \/\/ Perform enumeration\/search.\n auto enumerate = udev_enumerate_new(udev_handle);\n udev_enumerate_add_match_subsystem(enumerate, \"usb\");\n udev_enumerate_scan_devices(enumerate);\n\n \/\/ Get list entries and iterate over entries.\n struct udev_list_entry *device_entries, *entry;\n device_entries = udev_enumerate_get_list_entry(enumerate);\n\n udev_list_entry_foreach(entry, device_entries) {\n const char *path = udev_list_entry_get_name(entry);\n auto device = udev_device_new_from_syspath(udev_handle, path);\n\n Row r;\n \/\/ r[\"driver\"] = UdevEventPublisher::getValue(device, kUSBKeyDriver);\n r[\"vendor\"] = UdevEventPublisher::getValue(device, kUSBKeyVendor);\n r[\"model\"] = UdevEventPublisher::getValue(device, kUSBKeyModel);\n if (r[\"model\"].empty()) {\n r[\"model\"] = UdevEventPublisher::getValue(device, kUSBKeyModelFallback);\n }\n\n \/\/ USB-specific vendor\/model ID properties.\n r[\"model_id\"] = UdevEventPublisher::getValue(device, kUSBKeyModelID);\n r[\"vendor_id\"] = UdevEventPublisher::getValue(device, kUSBKeyVendorID);\n r[\"serial\"] = UdevEventPublisher::getValue(device, kUSBKeySerial);\n\n \/\/ This will be of the form class\/subclass\/protocol and has to be parsed\n auto devType = UdevEventPublisher::getValue(device, kUSBKeyType);\n auto classInfo = osquery::split(devType, \"\/\");\n if (classInfo.size() == 3) {\n r[\"class\"] = classInfo[0];\n r[\"subclass\"] = classInfo[1];\n r[\"protocol\"] = classInfo[2];\n } else {\n r[\"class\"] = \"\";\n r[\"subclass\"] = \"\";\n r[\"protocol\"] = \"\";\n }\n\n \/\/ Address\/port accessors.\n r[\"usb_address\"] = UdevEventPublisher::getValue(device, kUSBKeyAddress);\n r[\"usb_port\"] = UdevEventPublisher::getValue(device, kUSBKeyPort);\n\n \/\/ Removable detection.\n auto removable = UdevEventPublisher::getAttr(device, \"removable\");\n if (removable == \"unknown\") {\n r[\"removable\"] = \"-1\";\n } else {\n r[\"removable\"] = \"1\";\n }\n\n if (r[\"usb_address\"].size() > 0 && r[\"usb_port\"].size() > 0) {\n results.push_back(r);\n }\n udev_device_unref(device);\n }\n\n \/\/ Drop references to udev structs.\n udev_enumerate_unref(enumerate);\n udev_unref(udev_handle);\n\n return results;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include \"CRC\/CRC.h\"\n\nnamespace\n{\n const size_t BufferSize = 8192;\n\n size_t getChunkSize(File::OffsetType currentPos, File::OffsetType maxPos)\n {\n if (currentPos + static_cast<File::OffsetType>(BufferSize) >= maxPos)\n return maxPos - currentPos;\n return BufferSize;\n }\n}\n\nCRC::CRC()\n{\n progressFunction = nullptr;\n}\n\nCRC::~CRC()\n{\n}\n\nCRCType CRC::getInitialXOR() const\n{\n return initialXOR;\n}\n\nCRCType CRC::getFinalXOR() const\n{\n return finalXOR;\n}\n\nvoid CRC::setInitialXOR(CRCType f)\n{\n initialXOR = f;\n}\n\nvoid CRC::setFinalXOR(CRCType f)\n{\n finalXOR = f;\n}\n\nvoid CRC::setProgressFunction(const CRC::ProgressFunction &f)\n{\n progressFunction = f;\n}\n\n\/**\n * Method that copies the input to the output, outputting\n * computed patch at given position along the way.\n *\/\nvoid CRC::applyPatch(\n CRCType finalChecksum,\n File::OffsetType targetPos,\n File &input,\n File &output,\n bool overwrite) const\n{\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n CRCType patch = computePatch(finalChecksum, targetPos, input, overwrite);\n\n input.seek(0, File::Origin::Start);\n File::OffsetType pos = input.tell();\n markProgress(ProgressType::WriteStart, 0, pos, input.getSize());\n\n \/\/output first half\n while (pos < targetPos)\n {\n markProgress(ProgressType::WriteProgress, 0, pos, input.getSize());\n auto chunkSize = getChunkSize(pos, targetPos);\n input.read(buffer.get(), chunkSize);\n output.write(buffer.get(), chunkSize);\n pos += chunkSize;\n }\n\n \/\/output patch\n assert(getNumBytes() < BufferSize);\n for (size_t i = 0; i < getNumBytes(); i++)\n buffer[i] = static_cast<uint8_t>(patch >> (i << 3));\n output.write(buffer.get(), getNumBytes());\n if (overwrite)\n {\n pos += getNumBytes();\n input.seek(pos, File::Origin::Start);\n }\n\n \/\/output second half\n while (pos < input.getSize())\n {\n markProgress(ProgressType::WriteProgress, 0, pos, input.getSize());\n auto chunkSize = getChunkSize(pos, input.getSize());\n input.read(buffer.get(), chunkSize);\n output.write(buffer.get(), chunkSize);\n pos += chunkSize;\n }\n\n markProgress(ProgressType::WriteEnd, 0, pos, input.getSize());\n}\n\n\/**\n * Computes the checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computeChecksum(File &input) const\n{\n CRCType checksum = getInitialXOR();\n checksum = computePartialChecksum(input, 0, input.getSize(), checksum);\n return checksum ^ getFinalXOR();\n}\n\n\/**\n * Computes partial checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computePartialChecksum(\n File &input,\n File::OffsetType startPos,\n File::OffsetType endPos,\n CRCType initialChecksum) const\n{\n assert(startPos <= endPos);\n if (startPos == endPos)\n return initialChecksum;\n\n CRCType checksum = initialChecksum;\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n File::OffsetType oldPos = input.tell();\n File::OffsetType pos = startPos;\n input.seek(pos, File::Origin::Start);\n markProgress(ProgressType::ChecksumStart, startPos, startPos, endPos);\n\n while (pos < endPos)\n {\n markProgress(ProgressType::ChecksumProgress, startPos, pos, endPos);\n auto chunkSize = getChunkSize(pos, endPos);\n input.read(buffer.get(), chunkSize);\n for (size_t i = 0; i < chunkSize; i++)\n checksum = makeNextChecksum(checksum, buffer[i]);\n pos += chunkSize;\n }\n\n markProgress(ProgressType::ChecksumEnd, startPos, endPos, endPos);\n input.seek(oldPos, File::Origin::Start);\n return checksum;\n}\n\n\/**\n * Computes reverse partial checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computeReversePartialChecksum(\n File &input,\n File::OffsetType startPos,\n File::OffsetType endPos,\n CRCType initialChecksum) const\n{\n assert(startPos >= endPos);\n if (startPos == endPos)\n return initialChecksum;\n\n CRCType checksum = initialChecksum;\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n File::OffsetType oldPos = input.tell();\n File::OffsetType pos = startPos;\n markProgress(ProgressType::ChecksumStart, startPos, startPos, endPos);\n\n while (pos > endPos)\n {\n markProgress(ProgressType::ChecksumProgress, startPos, pos, endPos);\n auto chunkSize = getChunkSize(endPos, pos);\n pos -= chunkSize;\n input.seek(pos, File::Origin::Start);\n input.read(buffer.get(), chunkSize);\n for (size_t i = 0, j = chunkSize - 1; i < chunkSize; i++, j--)\n checksum = makePrevChecksum(checksum, buffer[j]);\n }\n\n markProgress(ProgressType::ChecksumEnd, startPos, endPos, endPos);\n input.seek(oldPos, File::Origin::Start);\n return checksum;\n}\n\nvoid CRC::markProgress(\n ProgressType progressType,\n File::OffsetType startPos,\n File::OffsetType curPos,\n File::OffsetType endPos) const\n{\n if (progressFunction != nullptr)\n progressFunction(progressType, startPos, curPos, endPos);\n}\n\nCRCType CRC::computePatch(\n CRCType targetChecksum,\n File::OffsetType targetPos,\n File &inputFile,\n bool overwrite) const\n{\n uint32_t checksum1 = computePartialChecksum(\n inputFile,\n 0,\n targetPos,\n getInitialXOR());\n\n uint32_t checksum2 = computeReversePartialChecksum(\n inputFile,\n inputFile.getSize(),\n targetPos + (overwrite ? 4 : 0),\n static_cast<uint32_t>(targetChecksum ^ getFinalXOR()));\n\n uint32_t patch = checksum2;\n for (size_t i = 0, j = getNumBytes() - 1; i < getNumBytes(); i++, j--)\n patch = makePrevChecksum(patch, (checksum1 >> (j << 3)) & 0xff);\n\n return patch;\n}\n<commit_msg>Fixed hardcoded byte count in CRC patcher<commit_after>#include <cassert>\n#include \"CRC\/CRC.h\"\n\nnamespace\n{\n const size_t BufferSize = 8192;\n\n size_t getChunkSize(File::OffsetType currentPos, File::OffsetType maxPos)\n {\n if (currentPos + static_cast<File::OffsetType>(BufferSize) >= maxPos)\n return maxPos - currentPos;\n return BufferSize;\n }\n}\n\nCRC::CRC()\n{\n progressFunction = nullptr;\n}\n\nCRC::~CRC()\n{\n}\n\nCRCType CRC::getInitialXOR() const\n{\n return initialXOR;\n}\n\nCRCType CRC::getFinalXOR() const\n{\n return finalXOR;\n}\n\nvoid CRC::setInitialXOR(CRCType f)\n{\n initialXOR = f;\n}\n\nvoid CRC::setFinalXOR(CRCType f)\n{\n finalXOR = f;\n}\n\nvoid CRC::setProgressFunction(const CRC::ProgressFunction &f)\n{\n progressFunction = f;\n}\n\n\/**\n * Method that copies the input to the output, outputting\n * computed patch at given position along the way.\n *\/\nvoid CRC::applyPatch(\n CRCType finalChecksum,\n File::OffsetType targetPos,\n File &input,\n File &output,\n bool overwrite) const\n{\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n CRCType patch = computePatch(finalChecksum, targetPos, input, overwrite);\n\n input.seek(0, File::Origin::Start);\n File::OffsetType pos = input.tell();\n markProgress(ProgressType::WriteStart, 0, pos, input.getSize());\n\n \/\/output first half\n while (pos < targetPos)\n {\n markProgress(ProgressType::WriteProgress, 0, pos, input.getSize());\n auto chunkSize = getChunkSize(pos, targetPos);\n input.read(buffer.get(), chunkSize);\n output.write(buffer.get(), chunkSize);\n pos += chunkSize;\n }\n\n \/\/output patch\n assert(getNumBytes() < BufferSize);\n for (size_t i = 0; i < getNumBytes(); i++)\n buffer[i] = static_cast<uint8_t>(patch >> (i << 3));\n output.write(buffer.get(), getNumBytes());\n if (overwrite)\n {\n pos += getNumBytes();\n input.seek(pos, File::Origin::Start);\n }\n\n \/\/output second half\n while (pos < input.getSize())\n {\n markProgress(ProgressType::WriteProgress, 0, pos, input.getSize());\n auto chunkSize = getChunkSize(pos, input.getSize());\n input.read(buffer.get(), chunkSize);\n output.write(buffer.get(), chunkSize);\n pos += chunkSize;\n }\n\n markProgress(ProgressType::WriteEnd, 0, pos, input.getSize());\n}\n\n\/**\n * Computes the checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computeChecksum(File &input) const\n{\n CRCType checksum = getInitialXOR();\n checksum = computePartialChecksum(input, 0, input.getSize(), checksum);\n return checksum ^ getFinalXOR();\n}\n\n\/**\n * Computes partial checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computePartialChecksum(\n File &input,\n File::OffsetType startPos,\n File::OffsetType endPos,\n CRCType initialChecksum) const\n{\n assert(startPos <= endPos);\n if (startPos == endPos)\n return initialChecksum;\n\n CRCType checksum = initialChecksum;\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n File::OffsetType oldPos = input.tell();\n File::OffsetType pos = startPos;\n input.seek(pos, File::Origin::Start);\n markProgress(ProgressType::ChecksumStart, startPos, startPos, endPos);\n\n while (pos < endPos)\n {\n markProgress(ProgressType::ChecksumProgress, startPos, pos, endPos);\n auto chunkSize = getChunkSize(pos, endPos);\n input.read(buffer.get(), chunkSize);\n for (size_t i = 0; i < chunkSize; i++)\n checksum = makeNextChecksum(checksum, buffer[i]);\n pos += chunkSize;\n }\n\n markProgress(ProgressType::ChecksumEnd, startPos, endPos, endPos);\n input.seek(oldPos, File::Origin::Start);\n return checksum;\n}\n\n\/**\n * Computes reverse partial checksum of given file.\n * NOTICE: Leaves internal file pointer position intact.\n *\/\nCRCType CRC::computeReversePartialChecksum(\n File &input,\n File::OffsetType startPos,\n File::OffsetType endPos,\n CRCType initialChecksum) const\n{\n assert(startPos >= endPos);\n if (startPos == endPos)\n return initialChecksum;\n\n CRCType checksum = initialChecksum;\n std::unique_ptr<uint8_t[]> buffer(new uint8_t[BufferSize]);\n File::OffsetType oldPos = input.tell();\n File::OffsetType pos = startPos;\n markProgress(ProgressType::ChecksumStart, startPos, startPos, endPos);\n\n while (pos > endPos)\n {\n markProgress(ProgressType::ChecksumProgress, startPos, pos, endPos);\n auto chunkSize = getChunkSize(endPos, pos);\n pos -= chunkSize;\n input.seek(pos, File::Origin::Start);\n input.read(buffer.get(), chunkSize);\n for (size_t i = 0, j = chunkSize - 1; i < chunkSize; i++, j--)\n checksum = makePrevChecksum(checksum, buffer[j]);\n }\n\n markProgress(ProgressType::ChecksumEnd, startPos, endPos, endPos);\n input.seek(oldPos, File::Origin::Start);\n return checksum;\n}\n\nvoid CRC::markProgress(\n ProgressType progressType,\n File::OffsetType startPos,\n File::OffsetType curPos,\n File::OffsetType endPos) const\n{\n if (progressFunction != nullptr)\n progressFunction(progressType, startPos, curPos, endPos);\n}\n\nCRCType CRC::computePatch(\n CRCType targetChecksum,\n File::OffsetType targetPos,\n File &inputFile,\n bool overwrite) const\n{\n uint32_t checksum1 = computePartialChecksum(\n inputFile,\n 0,\n targetPos,\n getInitialXOR());\n\n uint32_t checksum2 = computeReversePartialChecksum(\n inputFile,\n inputFile.getSize(),\n targetPos + (overwrite ? getNumBytes() : 0),\n static_cast<uint32_t>(targetChecksum ^ getFinalXOR()));\n\n uint32_t patch = checksum2;\n for (size_t i = 0, j = getNumBytes() - 1; i < getNumBytes(); i++, j--)\n patch = makePrevChecksum(patch, (checksum1 >> (j << 3)) & 0xff);\n\n return patch;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Schulich Delta Hermes\n * Copyright (C) 2015 University of Calgary Solar Car Team\n *\n * This file is part of Schulich Delta Hermes\n *\n * Schulich Delta Hermes is free software:\n * you can redistribute it and\/or modify it under the terms\n * of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Schulich Delta Hermes is distributed\n * in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n * without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n * General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General\n * Public License along with Schulich Delta Hermes.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * For further contact, email <software@calgarysolarcar.ca>\n *\/\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include <QScopedPointer>\n#include <QDebug>\n#include <QByteArray>\n#include <string>\n\n#include <SimpleAmqpClient\/SimpleAmqpClient.h>\n\n#include \"CommunicationLayer\/CommDeviceControl\/UdpMessageForwarder.h\"\n#include \"InfrastructureLayer\/Settings\/MockSettings.h\"\n\nusing ::testing::Return;\n\nnamespace\n{\nconst QString MOCK_IP = QString(\"localhost\");\nconst quint16 MOCK_PORT = 5672;\nconst QString MOCK_QUEUE = \"test-queue\";\n\/\/ TODO fix exchange values\nconst QString MOCK_EXCHANGE = \"testExchange\";\nconst QString MOCK_ROUTING_KEY = \"x73F34rS0dl\";\nconst QString EXPECTED_1 = \"Message Test\";\nconst QString EXPECTED_2 = \"Second Message Test\";\nconst QString EXPECTED_3 = \"Sp3c1a1** Ch4r4c74r5__ 7357\";\n}\n\nclass UdpMessageForwarderTest : public ::testing::Test\n{\nprotected:\n\n QScopedPointer<MockSettings> settings_;\n QScopedPointer<UdpMessageForwarder> forwarder;\n AmqpClient::Channel::ptr_t receiver;\n\n \/\/ TODO any new tests?\n \/\/ TODO add documentation for rabbitMQ libraries\n \/\/ TODO fix travis\n \/\/ TODO Fix indentation\n \/\/ TODO fix .ini files\n \/\/ TODO fix exhange usage in test\n \/\/ TODO Only the receiver should be generating the queue\n \/\/ TODO Come up with official exchange name\n\n \/**\n * @brief SetUp will set up the receiver to verify messages are being sent, as well as mocking the settings to be used by the UdpMessageForwarder\n *\/\n virtual void SetUp()\n {\n settings_.reset(new MockSettings());\n\n ON_CALL(*settings_, ipAddress())\n .WillByDefault(Return(MOCK_IP));\n ON_CALL(*settings_, exchangeName())\n .WillByDefault(Return(MOCK_EXCHANGE));\n ON_CALL(*settings_, udpPort())\n .WillByDefault(Return(MOCK_PORT));\n ON_CALL(*settings_, routingKey())\n .WillByDefault(Return(MOCK_ROUTING_KEY));\n }\n\n virtual void TearDown() {\n \/\/ Delete exchange\n receiver->DeleteExchange(MOCK_EXCHANGE.toStdString());\n cleanReceiver();\n }\n\n \/\/ Test Methods\n\n void sendMessage(const QString& message);\n QString receiveMessage(bool setupConsume);\n \/**\n * @brief setup the receiver for usage\n *\/\n void setupReceiver();\n \/**\n * @brief reset the receiver (clear and delete queue)\n *\/\n void cleanReceiver();\n};\n\nvoid UdpMessageForwarderTest::sendMessage(const QString& message) {\n QByteArray expectedBytes = QByteArray();\n expectedBytes.append(message);\n forwarder->forwardData(expectedBytes);\n}\n\nQString UdpMessageForwarderTest::receiveMessage(bool setupConsume) {\n \/\/ Receive message from local server\n if (setupConsume) {\n receiver->BasicConsume(MOCK_QUEUE.toStdString());\n }\n return QString::fromStdString(receiver->BasicConsumeMessage()->Message()->Body());\n}\n\nvoid UdpMessageForwarderTest::setupReceiver() {\n receiver = Channel::Create(MOCK_IP.toStdString(), MOCK_PORT);\n \/\/ passive (false), durable (true), exclusive (false), auto_delete (false)\n receiver->DeclareQueue(MOCK_QUEUE.toStdString(), false, true, false, false);\n receiver->DeclareExchange(MOCK_EXCHANGE.toStdString(), AmqpClient::Channel::EXCHANGE_TYPE_FANOUT);\n receiver->BindQueue(MOCK_QUEUE.toStdString(), MOCK_EXCHANGE.toStdString(), MOCK_ROUTING_KEY.toStdString());\n}\n\nvoid UdpMessageForwarderTest::cleanReceiver() {\n receiver->PurgeQueue(MOCK_QUEUE.toStdString());\n receiver->DeleteQueue(MOCK_QUEUE.toStdString());\n receiver.reset();\n}\n\n\n\/**\n * @brief Send a single message representing a JSON string via UdpMessageForwarder and verify its success\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingMessage) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief Send a message before the receiver has setup\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingNoReceiver) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n setupReceiver();\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief Disconnect the receiver during delivery and ensure messages still arrive\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingReceiverDC) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n receiver.reset();\n sendMessage(EXPECTED_2);\n setupReceiver();\n ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_2.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief test sending message with special characters\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingSpecialChars) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_3);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_3.toStdString(), ACTUAL.toStdString());\n}\n<commit_msg>comment changes - TODO's<commit_after>\/**\n * Schulich Delta Hermes\n * Copyright (C) 2015 University of Calgary Solar Car Team\n *\n * This file is part of Schulich Delta Hermes\n *\n * Schulich Delta Hermes is free software:\n * you can redistribute it and\/or modify it under the terms\n * of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Schulich Delta Hermes is distributed\n * in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n * without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n * General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General\n * Public License along with Schulich Delta Hermes.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * For further contact, email <software@calgarysolarcar.ca>\n *\/\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include <QScopedPointer>\n#include <QDebug>\n#include <QByteArray>\n#include <string>\n\n#include <SimpleAmqpClient\/SimpleAmqpClient.h>\n\n#include \"CommunicationLayer\/CommDeviceControl\/UdpMessageForwarder.h\"\n#include \"InfrastructureLayer\/Settings\/MockSettings.h\"\n\nusing ::testing::Return;\n\nnamespace\n{\nconst QString MOCK_IP = QString(\"localhost\");\nconst quint16 MOCK_PORT = 5672;\nconst QString MOCK_QUEUE = \"test-queue\";\nconst QString MOCK_EXCHANGE = \"testExchange\";\nconst QString MOCK_ROUTING_KEY = \"x73F34rS0dl\";\nconst QString EXPECTED_1 = \"Message Test\";\nconst QString EXPECTED_2 = \"Second Message Test\";\nconst QString EXPECTED_3 = \"Sp3c1a1** Ch4r4c74r5__ 7357\";\n}\n\nclass UdpMessageForwarderTest : public ::testing::Test\n{\nprotected:\n\n QScopedPointer<MockSettings> settings_;\n QScopedPointer<UdpMessageForwarder> forwarder;\n AmqpClient::Channel::ptr_t receiver;\n\n \/\/ TODO add documentation for rabbitMQ libraries\n \/\/ TODO fix travis\n\n \/**\n * @brief SetUp will set up the receiver to verify messages are being sent, as well as mocking the settings to be used by the UdpMessageForwarder\n *\/\n virtual void SetUp()\n {\n settings_.reset(new MockSettings());\n\n ON_CALL(*settings_, ipAddress())\n .WillByDefault(Return(MOCK_IP));\n ON_CALL(*settings_, exchangeName())\n .WillByDefault(Return(MOCK_EXCHANGE));\n ON_CALL(*settings_, udpPort())\n .WillByDefault(Return(MOCK_PORT));\n ON_CALL(*settings_, routingKey())\n .WillByDefault(Return(MOCK_ROUTING_KEY));\n }\n\n virtual void TearDown() {\n \/\/ Delete exchange\n receiver->DeleteExchange(MOCK_EXCHANGE.toStdString());\n cleanReceiver();\n }\n\n \/\/ Test Methods\n\n void sendMessage(const QString& message);\n QString receiveMessage(bool setupConsume);\n \/**\n * @brief setup the receiver for usage\n *\/\n void setupReceiver();\n \/**\n * @brief reset the receiver (clear and delete queue)\n *\/\n void cleanReceiver();\n};\n\nvoid UdpMessageForwarderTest::sendMessage(const QString& message) {\n QByteArray expectedBytes = QByteArray();\n expectedBytes.append(message);\n forwarder->forwardData(expectedBytes);\n}\n\nQString UdpMessageForwarderTest::receiveMessage(bool setupConsume) {\n \/\/ Receive message from local server\n if (setupConsume) {\n receiver->BasicConsume(MOCK_QUEUE.toStdString());\n }\n return QString::fromStdString(receiver->BasicConsumeMessage()->Message()->Body());\n}\n\nvoid UdpMessageForwarderTest::setupReceiver() {\n receiver = Channel::Create(MOCK_IP.toStdString(), MOCK_PORT);\n \/\/ passive (false), durable (true), exclusive (false), auto_delete (false)\n receiver->DeclareQueue(MOCK_QUEUE.toStdString(), false, true, false, false);\n receiver->DeclareExchange(MOCK_EXCHANGE.toStdString(), AmqpClient::Channel::EXCHANGE_TYPE_FANOUT);\n receiver->BindQueue(MOCK_QUEUE.toStdString(), MOCK_EXCHANGE.toStdString(), MOCK_ROUTING_KEY.toStdString());\n}\n\nvoid UdpMessageForwarderTest::cleanReceiver() {\n receiver->PurgeQueue(MOCK_QUEUE.toStdString());\n receiver->DeleteQueue(MOCK_QUEUE.toStdString());\n receiver.reset();\n}\n\n\n\/**\n * @brief Send a single message representing a JSON string via UdpMessageForwarder and verify its success\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingMessage) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief Send a message before the receiver has setup\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingNoReceiver) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n setupReceiver();\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief Disconnect the receiver during delivery and ensure messages still arrive\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingReceiverDC) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_1);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_1.toStdString(), ACTUAL.toStdString());\n receiver.reset();\n sendMessage(EXPECTED_2);\n setupReceiver();\n ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_2.toStdString(), ACTUAL.toStdString());\n}\n\n\/**\n * @brief test sending message with special characters\n *\/\nTEST_F(UdpMessageForwarderTest, testSendingSpecialChars) {\n setupReceiver();\n forwarder.reset(new UdpMessageForwarder(*settings_));\n sendMessage(EXPECTED_3);\n QString ACTUAL = receiveMessage(true);\n EXPECT_EQ(EXPECTED_3.toStdString(), ACTUAL.toStdString());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/extensions\/HelperMacros.h>\n#include \"spotty_network_failure_test.h\"\n#include <errno.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <limits.h>\n#include <fcntl.h>\n#include <sys\/wait.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <assert.h>\n#include <string.h>\n#include <libcmm.h>\n#include <libcmm_irob.h>\n#include \"net_interface.h\"\n#include \"test_common.h\"\n#include \"cmm_socket_control.h\"\n#include \"libcmm_ipc.h\"\n#include \"timeops.h\"\n\n#include <string>\n#include <vector>\nusing std::string; using std::vector;\n\n#include \"proxy_socket.h\"\n\nCPPUNIT_TEST_SUITE_REGISTRATION(SpottyNetworkFailureTest);\n\n\/* In the process of revising this test as follows.\n *\n * What this test currently does:\n * 1) Fake a multisocket on the server end.\n * 2) Connect a real multisocket to the fake one.\n * 3) Shut down one of the TCP sockets.\n * 4) Try to send\/receive data.\n *\n * The trouble with this approach is that the multisocket can\n * detect the TCP connection being shut down and react to it.\n * I really want to test what happens when the TCP connection\n * just stops receiving any messages (including FIN, for example).\n *\n * What the revised test will do:\n * 1) Create a real multisocket on the server end.\n * 2) Create proxy sockets:\n * a) Between the IntNW listen socket and the client\n * b) Between the multisocket's internal listen socket \n * and the client's connecting csockets\n * 3) Rewrite the necessary messages to keep the multisocket\n * endpoints unaware of the proxy:\n * a) The listener port in the initial HELLO response\n * 4) Snoop on the csocket setup messages to determine which\n * one should be considered FG\n * 5) Stop proxying data on that csocket.\n * 6) Try to send\/receive FG data.\n *\/\n\nconst in_port_t SpottyNetworkFailureTest::PROXY_PORT = 4243;\nconst in_port_t SpottyNetworkFailureTest::INTNW_LISTEN_PORT = 42424;\n\nbool process_chunk(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test,\n SpottyNetworkFailureTest::chunk_proc_method_t processMethod)\n{\n return (test->*processMethod)(to_sock, chunk, len);\n}\n\nbool process_bootstrap(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test)\n{\n return process_chunk(to_sock, chunk, len, test, \n &SpottyNetworkFailureTest::processBootstrap);\n}\n\nbool process_data(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test)\n{\n return process_chunk(to_sock, chunk, len, test, \n &SpottyNetworkFailureTest::processData);\n}\n\nvoid\nSpottyNetworkFailureTest::setupReceiver()\n{\n bootstrap_done = false;\n fg_socket_rtt = INT_MAX;\n fg_proxy_thread = (pthread_t) -1;\n pthread_mutex_init(&proxy_threads_lock, NULL);\n \n setListenPort(PROXY_PORT);\n start_proxy_thread(&bootstrap_proxy_thread, TEST_PORT, PROXY_PORT, \n (chunk_proc_fn_t) process_bootstrap, this);\n start_proxy_thread(&internal_data_proxy_thread, \n INTNW_LISTEN_PORT + 1, INTNW_LISTEN_PORT,\n (chunk_proc_fn_t) process_data, this);\n\n EndToEndTestsBase::setupReceiver();\n}\n\nbool\nSpottyNetworkFailureTest::processBootstrap(int to_sock, char *chunk, size_t len)\n{\n \/\/ overwrite internal-listener port with the proxy's port\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n socklen_t addrlen = sizeof(addr);\n if (!bootstrap_done &&\n getsockname(to_sock, (struct sockaddr *) &addr, &addrlen) == 0 &&\n ntohs(addr.sin_port) == TEST_PORT) {\n \/\/ only modify the hello response, not the request\n struct CMMSocketControlHdr *hdr = (struct CMMSocketControlHdr *) chunk;\n if (ntohs(hdr->type) == CMM_CONTROL_MSG_HELLO) {\n in_port_t listener_port = ntohs(hdr->op.hello.listen_port);\n printf(\"Overwriting listener port %hu in hello response with proxy port %hu\\n\",\n listener_port, INTNW_LISTEN_PORT + 1);\n hdr->op.hello.listen_port = htons(INTNW_LISTEN_PORT + 1);\n bootstrap_done = true;\n }\n }\n\n return true;\n}\n\nbool\nSpottyNetworkFailureTest::processData(int to_sock, char *chunk, size_t len)\n{\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n socklen_t addrlen = sizeof(addr);\n\n int rc = getpeername(to_sock, (struct sockaddr *) &addr, &addrlen);\n if (rc != 0) {\n fprintf(stderr, \"Error: getpeername failed: %s\\n\", strerror(errno));\n } else {\n printf(\"In processData: checking message heading for %s:%hu\\n\",\n inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));\n }\n \n pthread_mutex_lock(&proxy_threads_lock);\n if (proxy_threads.size() < 2 &&\n ntohs(addr.sin_port) == INTNW_LISTEN_PORT) {\n \n printf(\"Looking for new_interface message\\n\");\n struct CMMSocketControlHdr *hdr = (struct CMMSocketControlHdr *) chunk;\n \/\/ XXX: make sure this is in fact the new_interface message for the new csocket\n \/\/ XXX: (probably not strictly necessary, since that message\n \/\/ XXX: is the first message on the csocket, but still\n \/\/ XXX: a good sanity check.)\n if (ntohs(hdr->type) == CMM_CONTROL_MSG_NEW_INTERFACE) {\n if (ntohl(hdr->op.new_interface.RTT) < fg_socket_rtt) {\n fg_socket_rtt = ntohl(hdr->op.new_interface.RTT);\n fg_proxy_thread = pthread_self();\n TIME(fg_proxy_start_time);\n printf(\"Now treating iface with RTT %d (%s) as FG\\n\",\n (int) fg_socket_rtt, inet_ntoa(hdr->op.new_interface.ip_addr));\n }\n proxy_threads.insert(pthread_self());\n }\n }\n \n bool ret = true;\n if (fg_proxy_thread == pthread_self()) {\n struct timeval now, diff;\n TIME(now);\n TIMEDIFF(fg_proxy_start_time, now, diff);\n pthread_mutex_unlock(&proxy_threads_lock);\n\n if (diff.tv_sec >= 1) {\n ret = false;\n } else {\n ret = true;\n }\n } else {\n pthread_mutex_unlock(&proxy_threads_lock);\n ret = true;\n }\n\n printf(\"%s a %d-byte message to %s:%hu\\n\", \n ret ? \"Proxying\" : \"Suppressing\", \n (int) len,\n inet_ntoa(addr.sin_addr),\n ntohs(addr.sin_port));\n return ret;\n}\n\n\nvoid\nSpottyNetworkFailureTest::tearDown()\n{\n if (isReceiver()) {\n EndToEndTestsBase::tearDown();\n stop_proxy_thread(internal_data_proxy_thread);\n stop_proxy_thread(bootstrap_proxy_thread);\n } else {\n EndToEndTestsBase::tearDown();\n }\n}\n\nint\nconnect_to_scout_control()\n{\n int sock = socket(PF_INET, SOCK_STREAM, 0);\n handle_error(sock < 0, \"creating scout control socket\");\n\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n addr.sin_port = htons(CONTROL_SOCKET_PORT);\n\n socklen_t addrlen = sizeof(addr);\n int rc = connect(sock, (struct sockaddr *)&addr, addrlen);\n handle_error(rc < 0, \"connecting scout control socket\");\n \n return sock;\n}\n\nvoid \nSpottyNetworkFailureTest::testOneNetworkFails()\n{\n const char expected_str[] = \"ABCDEFGHIJ\";\n const size_t len = strlen(expected_str);\n\n char buf[len + 1];\n memset(buf, 0, sizeof(buf));\n\n if (isReceiver()) {\n int rc = cmm_read(data_sock, buf, len, NULL);\n CPPUNIT_ASSERT_EQUAL((int)len, rc);\n CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));\n\n rc = cmm_write(data_sock, expected_str, len,\n CMM_LABEL_ONDEMAND, NULL, NULL);\n CPPUNIT_ASSERT_EQUAL((int) len, rc);\n } else {\n int scout_control_sock = connect_to_scout_control();\n \n sleep(1);\n int rc = cmm_write(data_sock, expected_str, len,\n CMM_LABEL_ONDEMAND, NULL, NULL);\n CPPUNIT_ASSERT_EQUAL((int)len, rc); \/\/ succeeds immediately without waiting for bytes to be sent\n \n sleep(5);\n char cmd[] = \"bg_down\\n\";\n rc = write(scout_control_sock, cmd, strlen(cmd));\n CPPUNIT_ASSERT_EQUAL((int) strlen(cmd), rc);\n\n sleep(1);\n memset(buf, 0, sizeof(buf));\n rc = cmm_recv(data_sock, buf, len, MSG_WAITALL, NULL);\n CPPUNIT_ASSERT_EQUAL((int) len, rc);\n CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));\n \n close(scout_control_sock);\n }\n}\n<commit_msg>Added timeout to the test. It now fails as expected.<commit_after>#include <cppunit\/extensions\/HelperMacros.h>\n#include \"spotty_network_failure_test.h\"\n#include <errno.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <limits.h>\n#include <fcntl.h>\n#include <sys\/wait.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <assert.h>\n#include <string.h>\n#include <libcmm.h>\n#include <libcmm_irob.h>\n#include \"net_interface.h\"\n#include \"test_common.h\"\n#include \"cmm_socket_control.h\"\n#include \"libcmm_ipc.h\"\n#include \"timeops.h\"\n\n#include <string>\n#include <vector>\nusing std::string; using std::vector;\n\n#include \"proxy_socket.h\"\n\nCPPUNIT_TEST_SUITE_REGISTRATION(SpottyNetworkFailureTest);\n\n\/* In the process of revising this test as follows.\n *\n * What this test currently does:\n * 1) Fake a multisocket on the server end.\n * 2) Connect a real multisocket to the fake one.\n * 3) Shut down one of the TCP sockets.\n * 4) Try to send\/receive data.\n *\n * The trouble with this approach is that the multisocket can\n * detect the TCP connection being shut down and react to it.\n * I really want to test what happens when the TCP connection\n * just stops receiving any messages (including FIN, for example).\n *\n * What the revised test will do:\n * 1) Create a real multisocket on the server end.\n * 2) Create proxy sockets:\n * a) Between the IntNW listen socket and the client\n * b) Between the multisocket's internal listen socket \n * and the client's connecting csockets\n * 3) Rewrite the necessary messages to keep the multisocket\n * endpoints unaware of the proxy:\n * a) The listener port in the initial HELLO response\n * 4) Snoop on the csocket setup messages to determine which\n * one should be considered FG\n * 5) Stop proxying data on that csocket.\n * 6) Try to send\/receive FG data.\n *\/\n\nconst in_port_t SpottyNetworkFailureTest::PROXY_PORT = 4243;\nconst in_port_t SpottyNetworkFailureTest::INTNW_LISTEN_PORT = 42424;\n\nbool process_chunk(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test,\n SpottyNetworkFailureTest::chunk_proc_method_t processMethod)\n{\n return (test->*processMethod)(to_sock, chunk, len);\n}\n\nbool process_bootstrap(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test)\n{\n return process_chunk(to_sock, chunk, len, test, \n &SpottyNetworkFailureTest::processBootstrap);\n}\n\nbool process_data(int to_sock, char *chunk, size_t len, \n SpottyNetworkFailureTest *test)\n{\n return process_chunk(to_sock, chunk, len, test, \n &SpottyNetworkFailureTest::processData);\n}\n\nvoid\nSpottyNetworkFailureTest::setupReceiver()\n{\n bootstrap_done = false;\n fg_socket_rtt = INT_MAX;\n fg_proxy_thread = (pthread_t) -1;\n pthread_mutex_init(&proxy_threads_lock, NULL);\n \n setListenPort(PROXY_PORT);\n start_proxy_thread(&bootstrap_proxy_thread, TEST_PORT, PROXY_PORT, \n (chunk_proc_fn_t) process_bootstrap, this);\n start_proxy_thread(&internal_data_proxy_thread, \n INTNW_LISTEN_PORT + 1, INTNW_LISTEN_PORT,\n (chunk_proc_fn_t) process_data, this);\n\n EndToEndTestsBase::setupReceiver();\n}\n\nbool\nSpottyNetworkFailureTest::processBootstrap(int to_sock, char *chunk, size_t len)\n{\n \/\/ overwrite internal-listener port with the proxy's port\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n socklen_t addrlen = sizeof(addr);\n if (!bootstrap_done &&\n getsockname(to_sock, (struct sockaddr *) &addr, &addrlen) == 0 &&\n ntohs(addr.sin_port) == TEST_PORT) {\n \/\/ only modify the hello response, not the request\n struct CMMSocketControlHdr *hdr = (struct CMMSocketControlHdr *) chunk;\n if (ntohs(hdr->type) == CMM_CONTROL_MSG_HELLO) {\n in_port_t listener_port = ntohs(hdr->op.hello.listen_port);\n printf(\"Overwriting listener port %hu in hello response with proxy port %hu\\n\",\n listener_port, INTNW_LISTEN_PORT + 1);\n hdr->op.hello.listen_port = htons(INTNW_LISTEN_PORT + 1);\n bootstrap_done = true;\n }\n }\n\n return true;\n}\n\nbool\nSpottyNetworkFailureTest::processData(int to_sock, char *chunk, size_t len)\n{\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n socklen_t addrlen = sizeof(addr);\n\n int rc = getpeername(to_sock, (struct sockaddr *) &addr, &addrlen);\n if (rc != 0) {\n fprintf(stderr, \"Error: getpeername failed: %s\\n\", strerror(errno));\n } else {\n printf(\"In processData: checking message heading for %s:%hu\\n\",\n inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));\n }\n \n pthread_mutex_lock(&proxy_threads_lock);\n if (proxy_threads.size() < 2 &&\n ntohs(addr.sin_port) == INTNW_LISTEN_PORT) {\n \n printf(\"Looking for new_interface message\\n\");\n struct CMMSocketControlHdr *hdr = (struct CMMSocketControlHdr *) chunk;\n \/\/ XXX: make sure this is in fact the new_interface message for the new csocket\n \/\/ XXX: (probably not strictly necessary, since that message\n \/\/ XXX: is the first message on the csocket, but still\n \/\/ XXX: a good sanity check.)\n if (ntohs(hdr->type) == CMM_CONTROL_MSG_NEW_INTERFACE) {\n if (ntohl(hdr->op.new_interface.RTT) < fg_socket_rtt) {\n fg_socket_rtt = ntohl(hdr->op.new_interface.RTT);\n fg_proxy_thread = pthread_self();\n TIME(fg_proxy_start_time);\n printf(\"Now treating iface with RTT %d (%s) as FG\\n\",\n (int) fg_socket_rtt, inet_ntoa(hdr->op.new_interface.ip_addr));\n }\n proxy_threads.insert(pthread_self());\n }\n }\n \n bool ret = true;\n if (fg_proxy_thread == pthread_self()) {\n struct timeval now, diff;\n TIME(now);\n TIMEDIFF(fg_proxy_start_time, now, diff);\n pthread_mutex_unlock(&proxy_threads_lock);\n\n if (diff.tv_sec >= 1) {\n ret = false;\n } else {\n ret = true;\n }\n } else {\n pthread_mutex_unlock(&proxy_threads_lock);\n ret = true;\n }\n\n printf(\"%s a %d-byte message to %s:%hu\\n\", \n ret ? \"Proxying\" : \"Suppressing\", \n (int) len,\n inet_ntoa(addr.sin_addr),\n ntohs(addr.sin_port));\n return ret;\n}\n\n\nvoid\nSpottyNetworkFailureTest::tearDown()\n{\n if (isReceiver()) {\n EndToEndTestsBase::tearDown();\n stop_proxy_thread(internal_data_proxy_thread);\n stop_proxy_thread(bootstrap_proxy_thread);\n } else {\n EndToEndTestsBase::tearDown();\n }\n}\n\nint\nconnect_to_scout_control()\n{\n int sock = socket(PF_INET, SOCK_STREAM, 0);\n handle_error(sock < 0, \"creating scout control socket\");\n\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n addr.sin_port = htons(CONTROL_SOCKET_PORT);\n\n socklen_t addrlen = sizeof(addr);\n int rc = connect(sock, (struct sockaddr *)&addr, addrlen);\n handle_error(rc < 0, \"connecting scout control socket\");\n \n return sock;\n}\n\nvoid \nSpottyNetworkFailureTest::testOneNetworkFails()\n{\n const char expected_str[] = \"ABCDEFGHIJ\";\n const size_t len = strlen(expected_str);\n\n char buf[len + 1];\n memset(buf, 0, sizeof(buf));\n\n if (isReceiver()) {\n fd_set readable;\n FD_ZERO(&readable);\n FD_SET(data_sock, &readable);\n struct timeval timeout = {4, 0};\n int rc = cmm_select(data_sock + 1, &readable, NULL, NULL, &timeout);\n CPPUNIT_ASSERT_EQUAL(1, rc);\n \n rc = cmm_read(data_sock, buf, len, NULL);\n CPPUNIT_ASSERT_EQUAL((int)len, rc);\n CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));\n\n rc = cmm_write(data_sock, expected_str, len,\n CMM_LABEL_ONDEMAND, NULL, NULL);\n CPPUNIT_ASSERT_EQUAL((int) len, rc);\n } else {\n int scout_control_sock = connect_to_scout_control();\n \n sleep(1);\n int rc = cmm_write(data_sock, expected_str, len,\n CMM_LABEL_ONDEMAND, NULL, NULL);\n CPPUNIT_ASSERT_EQUAL((int)len, rc); \/\/ succeeds immediately without waiting for bytes to be sent\n \n sleep(5);\n char cmd[] = \"bg_down\\n\";\n rc = write(scout_control_sock, cmd, strlen(cmd));\n CPPUNIT_ASSERT_EQUAL((int) strlen(cmd), rc);\n\n sleep(1);\n memset(buf, 0, sizeof(buf));\n rc = cmm_recv(data_sock, buf, len, MSG_WAITALL, NULL);\n CPPUNIT_ASSERT_EQUAL((int) len, rc);\n CPPUNIT_ASSERT_EQUAL(string(expected_str), string(buf));\n \n close(scout_control_sock);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2019-present Advanced Micro Devices, Inc. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/test_common.cpp EXCLUDE_HIP_PLATFORM nvcc vdi\n * TEST: %t\n * HIT_END\n *\/\n#include \"test_common.h\"\n\n\/\/typedef char T;\nconst char *sampleName = \"simpleTexture3D\";\n\n\/\/ Texture reference for 3D texture\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<float, hipTextureType3D, hipReadModeElementType> texf;\n\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<int, hipTextureType3D, hipReadModeElementType> texi;\n\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<char, hipTextureType3D, hipReadModeElementType> texc;\n\ntemplate <typename T>\n__global__ void simpleKernel3DArray(T* outputData, \n int width,\n int height,int depth)\n{\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < height; j++) {\n for (int k = 0; k < width; k++) {\n if(std::is_same<T, float>::value)\n outputData[i*width*height + j*width + k] = tex3D(texf, texf.textureObject, k, j, i);\n else if(std::is_same<T, int>::value)\n outputData[i*width*height + j*width + k] = tex3D(texi, texi.textureObject, k, j, i);\n else if(std::is_same<T, char>::value)\n outputData[i*width*height + j*width + k] = tex3D(texc, texc.textureObject, k, j, i);\n }\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/! Run a simple test for tex3D\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename T>\nvoid runTest(int width,int height,int depth,texture<T, hipTextureType3D, hipReadModeElementType> *tex)\n{\n unsigned int size = width * height * depth * sizeof(T);\n T* hData = (T*) malloc(size);\n memset(hData, 0, size);\n\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < height; j++) {\n for (int k = 0; k < width; k++) {\n hData[i*width*height + j*width +k] = i*width*height + j*width + k;\n }\n }\n }\n\n \/\/ Allocate array and copy image data\n hipChannelFormatDesc channelDesc = hipCreateChannelDesc(sizeof(T)*8, 0, 0, 0, hipChannelFormatKindSigned);\n hipArray *arr;\n\n HIPCHECK(hipMalloc3DArray(&arr, &channelDesc, make_hipExtent(width, height, depth), hipArrayCubemap));\n hipMemcpy3DParms myparms = {0};\n myparms.srcPos = make_hipPos(0,0,0);\n myparms.dstPos = make_hipPos(0,0,0);\n myparms.srcPtr = make_hipPitchedPtr(hData, width * sizeof(T), width, height);\n myparms.dstArray = arr;\n myparms.extent = make_hipExtent(width, height, depth);\n myparms.kind = hipMemcpyHostToDevice;\n HIPCHECK(hipMemcpy3D(&myparms));\n\n \/\/ set texture parameters\n tex->addressMode[0] = hipAddressModeWrap;\n tex->addressMode[1] = hipAddressModeWrap;\n tex->filterMode = hipFilterModePoint;\n tex->normalized = false;\n\n \/\/ Bind the array to the texture\n HIPCHECK(hipBindTextureToArray(*tex, arr, channelDesc));\n\n \/\/ Allocate device memory for result\n T* dData = NULL;\n hipMalloc((void **) &dData, size);\n\n hipLaunchKernelGGL(simpleKernel3DArray, dim3(1,1,1), dim3(1,1,1), 0, 0, dData, width, height, depth);\n HIPCHECK(hipDeviceSynchronize());\n\n \/\/ Allocate mem for the result on host side\n T *hOutputData = (T*) malloc(size);\n memset(hOutputData, 0, size);\n\n \/\/ copy result from device to host\n HIPCHECK(hipMemcpy(hOutputData, dData, size, hipMemcpyDeviceToHost));\n HipTest::checkArray(hData,hOutputData,width,height,depth); \n\n hipFree(dData);\n hipFreeArray(arr);\n free(hData);\n free(hOutputData);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Program main\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n printf(\"%s starting...\\n\", sampleName);\n for(int i=1;i<25;i++)\n {\n runTest<float>(i,i,i,&texf);\n runTest<int>(i+1,i,i,&texi);\n runTest<char>(i,i+1,i,&texc);\n }\n passed();\n}\n\n<commit_msg>Enable simpleTexture3D test for VDI<commit_after>\/*\nCopyright (c) 2019-present Advanced Micro Devices, Inc. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/test_common.cpp EXCLUDE_HIP_PLATFORM nvcc\n * TEST: %t\n * HIT_END\n *\/\n#include \"test_common.h\"\n\n\/\/typedef char T;\nconst char *sampleName = \"simpleTexture3D\";\n\n\/\/ Texture reference for 3D texture\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<float, hipTextureType3D, hipReadModeElementType> texf;\n\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<int, hipTextureType3D, hipReadModeElementType> texi;\n\n#if __HIP__\n__hip_pinned_shadow__\n#endif\ntexture<char, hipTextureType3D, hipReadModeElementType> texc;\n\ntemplate <typename T>\n__global__ void simpleKernel3DArray(T* outputData, \n int width,\n int height,int depth)\n{\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < height; j++) {\n for (int k = 0; k < width; k++) {\n if(std::is_same<T, float>::value)\n outputData[i*width*height + j*width + k] = tex3D(texf, k, j, i);\n else if(std::is_same<T, int>::value)\n outputData[i*width*height + j*width + k] = tex3D(texi, k, j, i);\n else if(std::is_same<T, char>::value)\n outputData[i*width*height + j*width + k] = tex3D(texc, k, j, i);\n }\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/! Run a simple test for tex3D\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename T>\nvoid runTest(int width,int height,int depth,texture<T, hipTextureType3D, hipReadModeElementType> *tex)\n{\n unsigned int size = width * height * depth * sizeof(T);\n T* hData = (T*) malloc(size);\n memset(hData, 0, size);\n\n for (int i = 0; i < depth; i++) {\n for (int j = 0; j < height; j++) {\n for (int k = 0; k < width; k++) {\n hData[i*width*height + j*width +k] = i*width*height + j*width + k;\n }\n }\n }\n\n \/\/ Allocate array and copy image data\n hipChannelFormatDesc channelDesc = hipCreateChannelDesc<T>();\n hipArray *arr;\n\n HIPCHECK(hipMalloc3DArray(&arr, &channelDesc, make_hipExtent(width, height, depth), hipArrayDefault));\n hipMemcpy3DParms myparms = {0};\n myparms.srcPos = make_hipPos(0,0,0);\n myparms.dstPos = make_hipPos(0,0,0);\n myparms.srcPtr = make_hipPitchedPtr(hData, width * sizeof(T), width, height);\n myparms.dstArray = arr;\n myparms.extent = make_hipExtent(width, height, depth);\n myparms.kind = hipMemcpyHostToDevice;\n HIPCHECK(hipMemcpy3D(&myparms));\n\n \/\/ set texture parameters\n tex->addressMode[0] = hipAddressModeWrap;\n tex->addressMode[1] = hipAddressModeWrap;\n tex->filterMode = hipFilterModePoint;\n tex->normalized = false;\n\n \/\/ Bind the array to the texture\n HIPCHECK(hipBindTextureToArray(*tex, arr, channelDesc));\n\n \/\/ Allocate device memory for result\n T* dData = NULL;\n hipMalloc((void **) &dData, size);\n\n hipLaunchKernelGGL(simpleKernel3DArray, dim3(1,1,1), dim3(1,1,1), 0, 0, dData, width, height, depth);\n HIPCHECK(hipDeviceSynchronize());\n\n \/\/ Allocate mem for the result on host side\n T *hOutputData = (T*) malloc(size);\n memset(hOutputData, 0, size);\n\n \/\/ copy result from device to host\n HIPCHECK(hipMemcpy(hOutputData, dData, size, hipMemcpyDeviceToHost));\n HipTest::checkArray(hData,hOutputData,width,height,depth); \n\n hipFree(dData);\n hipFreeArray(arr);\n free(hData);\n free(hOutputData);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Program main\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char **argv)\n{\n printf(\"%s starting...\\n\", sampleName);\n for(int i=1;i<25;i++)\n {\n runTest<float>(i,i,i,&texf);\n runTest<int>(i+1,i,i,&texi);\n runTest<char>(i,i+1,i,&texc);\n }\n passed();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX600, RX200 グループ・CMT I\/O 制御\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2013, 2020 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/intr_utils.hpp\"\n#include \"common\/vect.h\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief CMT I\/O クラス\n\t\t@param[in]\tCMT\tチャネルクラス\n\t\t@param[in]\tTASK\tタイマー動作クラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class CMT, class TASK = utils::null_task>\n\tclass cmt_io {\n\n\t\tuint8_t\t\tlevel_;\n\n\t\tvoid sleep_() const { asm(\"nop\"); }\n\n\t\tstatic TASK\ttask_;\n\n\t\tstatic volatile uint32_t counter_;\n\n\t\tstatic INTERRUPT_FUNC void i_task_()\n\t\t{\n\t\t\t++counter_;\n\t\t\ttask_();\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tcmt_io() : level_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 開始\n\t\t\t@param[in]\tfreq\tタイマー周波数\n\t\t\t@param[in]\tlevel\t割り込みレベル(0ならポーリング)\n\t\t\t@param[in]\ttask\t割り込み時に起動する関数 @n\n\t\t\t\t\t\t\t\t※割り込み関数は属性「INTERRUPT_FUNC」を付加する。\n\t\t\t@return タイマー周波数が範囲を超えた場合「false」を返す\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t freq, uint8_t level = 0, void (*task)() = nullptr) noexcept\n\t\t{\n\t\t\tif(freq == 0) return false;\n\n\t\t\tuint32_t cmcor = CMT::PCLK \/ freq \/ 4;\n\t\t\tif(cmcor & 1) {\n\t\t\t\tcmcor >>= 1;\n\t\t\t\t++cmcor;\n\t\t\t} else {\n\t\t\t\tcmcor >>= 1;\n\t\t\t}\n\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(cmcor > 65536) {\n\t\t\t\tcmcor >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3 || cmcor == 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tlevel_ = level;\n\n\t\t\tpower_mgr::turn(CMT::PERIPHERAL);\n\n\t\t\tCMT::enable(false);\n\n\t\t\tCMT::CMCNT = 0;\n\t\t CMT::CMCOR = cmcor - 1;\n\n\t\t\tcounter_ = 0;\n\n\t\t\tif(level_ > 0) {\n\t\t\t\tif(task != nullptr) {\n\t\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, task, level_);\n\t\t\t\t} else {\n\t\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, i_task_, level_);\n\t\t\t\t}\n\t\t\t CMT::CMCR = CMT::CMCR.CKS.b(cks) | CMT::CMCR.CMIE.b();\n\t\t\t} else {\n\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, nullptr, 0);\n\t\t\t CMT::CMCR = CMT::CMCR.CKS.b(cks);\n\t\t\t}\n\t\t\tCMT::enable();\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 廃棄(割り込みを停止して、ユニットを停止)\n\t\t\t@param[in]\tpower\t電源を停止しない場合「true」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid destroy(bool power = false) noexcept\n\t\t{\n\t\t CMT::CMCR.CMIE = 0;\n\t\t\tCMT::enable(false);\n\t\t\tpower_mgr::turn(CMT::PERIPHERAL, power);\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みと同期\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid sync() const noexcept\n\t\t{\n\t\t\tif(level_ > 0) {\n\t\t\t\tvolatile uint32_t cnt = counter_;\n\t\t\t\twhile(cnt == counter_) sleep_();\n\t\t\t} else {\n\t\t\t\tauto ref = CMT::CMCNT();\n\t\t\t\twhile(ref <= CMT::CMCNT()) sleep_();\n\t\t\t\ttask_();\n\t\t\t\t++counter_;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みカウンターの値を設定\n\t\t\t@param[in]\tn\t割り込みカウンターの値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void set_counter(uint32_t n) noexcept { counter_ = n; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みカウンターの値を取得\n\t\t\t@return 割り込みカウンターの値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint32_t get_counter() noexcept { return counter_; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief CMCNT レジスターの値を取得\n\t\t\t@return CMCNT レジスター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_cmt_count() const noexcept { return CMT::CMCNT(); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief CMCOR レジスターの値を取得\n\t\t\t@return CMCOR レジスター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_cmp_count() const noexcept { return CMT::CMCOR(); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TASK クラスの参照\n\t\t\t@return TASK クラス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic TASK& at_task() noexcept { return task_; }\n\t};\n\n\ttemplate <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0;\n\ttemplate <class CMT, class TASK> TASK cmt_io<CMT, TASK>::task_;\n}\n<commit_msg>Update: Add CMT real rate API<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX600, RX200 グループ・CMT I\/O 制御\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2013, 2020 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/intr_utils.hpp\"\n#include \"common\/vect.h\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief CMT I\/O クラス\n\t\t@param[in]\tCMT\tチャネルクラス\n\t\t@param[in]\tTASK\tタイマー動作クラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class CMT, class TASK = utils::null_task>\n\tclass cmt_io {\n\n\t\tuint8_t\t\tlevel_;\n\t\tuint32_t\trate_;\n\n\t\tvoid sleep_() const { asm(\"nop\"); }\n\n\t\tstatic TASK\ttask_;\n\n\t\tstatic volatile uint32_t counter_;\n\n\t\tstatic INTERRUPT_FUNC void i_task_()\n\t\t{\n\t\t\t++counter_;\n\t\t\ttask_();\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tcmt_io() : level_(0), rate_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 開始\n\t\t\t@param[in]\tfreq\tタイマー周波数\n\t\t\t@param[in]\tlevel\t割り込みレベル(0ならポーリング)\n\t\t\t@param[in]\ttask\t割り込み時に起動する関数 @n\n\t\t\t\t\t\t\t\t※割り込み関数は属性「INTERRUPT_FUNC」を付加する。\n\t\t\t@return タイマー周波数が範囲を超えた場合「false」を返す\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t freq, uint8_t level = 0, void (*task)() = nullptr) noexcept\n\t\t{\n\t\t\tif(freq == 0) return false;\n\n\t\t\tuint32_t cmcor = CMT::PCLK \/ freq \/ 4;\n\t\t\tcmcor++;\n\t\t\tcmcor >>= 1;\n\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(cmcor > 65536) {\n\t\t\t\tcmcor >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3 || cmcor == 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\trate_ = freq;\n\n\t\t\tlevel_ = level;\n\n\t\t\tpower_mgr::turn(CMT::PERIPHERAL);\n\n\t\t\tCMT::enable(false);\n\n\t\t\tCMT::CMCNT = 0;\n\t\t CMT::CMCOR = cmcor - 1;\n\n\t\t\tcounter_ = 0;\n\n\t\t\tif(level_ > 0) {\n\t\t\t\tif(task != nullptr) {\n\t\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, task, level_);\n\t\t\t\t} else {\n\t\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, i_task_, level_);\n\t\t\t\t}\n\t\t\t CMT::CMCR = CMT::CMCR.CKS.b(cks) | CMT::CMCR.CMIE.b();\n\t\t\t} else {\n\t\t\t\ticu_mgr::set_interrupt(CMT::IVEC, nullptr, 0);\n\t\t\t CMT::CMCR = CMT::CMCR.CKS.b(cks);\n\t\t\t}\n\t\t\tCMT::enable();\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 廃棄(割り込みを停止して、ユニットを停止)\n\t\t\t@param[in]\tpower\t電源を停止しない場合「true」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid destroy(bool power = false) noexcept\n\t\t{\n\t\t CMT::CMCR.CMIE = 0;\n\t\t\tCMT::enable(false);\n\t\t\tpower_mgr::turn(CMT::PERIPHERAL, power);\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みと同期\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid sync() const noexcept\n\t\t{\n\t\t\tif(level_ > 0) {\n\t\t\t\tvolatile uint32_t cnt = counter_;\n\t\t\t\twhile(cnt == counter_) sleep_();\n\t\t\t} else {\n\t\t\t\tauto ref = CMT::CMCNT();\n\t\t\t\twhile(ref <= CMT::CMCNT()) sleep_();\n\t\t\t\ttask_();\n\t\t\t\t++counter_;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みカウンターの値を設定\n\t\t\t@param[in]\tn\t割り込みカウンターの値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void set_counter(uint32_t n) noexcept { counter_ = n; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 割り込みカウンターの値を取得\n\t\t\t@return 割り込みカウンターの値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint32_t get_counter() noexcept { return counter_; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief CMCNT レジスターの値を取得\n\t\t\t@return CMCNT レジスター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_cmt_count() const noexcept { return CMT::CMCNT(); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief CMCOR レジスターの値を取得\n\t\t\t@return CMCOR レジスター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_cmp_count() const noexcept { return CMT::CMCOR(); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\t周期を取得\n\t\t\t@param[in]\treal\t「true」にした場合、内部で計算されたリアルな値\n\t\t\t@return 周期\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint32_t get_rate(bool real = false) const noexcept\n\t\t{\n\t\t\tif(real) {\n\t\t\t\tuint32_t rate = CMT::PCLK \/ (static_cast<uint32_t>(CMT::CMCOR()) + 1);\n\t\t\t\trate \/= 4 << (CMT::CMCR.CKS() * 2);\n\t\t\t\treturn rate;\n\t\t\t} else {\n\t\t\t\treturn rate_;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TASK クラスの参照\n\t\t\t@return TASK クラス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic TASK& at_task() noexcept { return task_; }\n\t};\n\n\ttemplate <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0;\n\ttemplate <class CMT, class TASK> TASK cmt_io<CMT, TASK>::task_;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX マイコン、デバイス固有ヘッダー\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/io_utils.hpp\"\r\n\r\n#if defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/power_mgr.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX62N)\r\n#include \"RX62x\/system.hpp\"\r\n#include \"RX62x\/icu.hpp\"\r\n#include \"RX62x\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/power_mgr.hpp\"\r\n#include \"RX600\/icu.hpp\"\r\n#include \"RX600\/icu_mgr.hpp\"\r\n#include \"RX600\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX72M)\r\n#include \"RX72M\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72M\/power_mgr.hpp\"\r\n#include \"RX72M\/icu.hpp\"\r\n#include \"RX72M\/icu_mgr.hpp\"\r\n#include \"RX72M\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX72N)\r\n#include \"RX72N\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72N\/power_mgr.hpp\"\r\n#include \"RX72N\/icu.hpp\"\r\n#include \"RX72N\/icu_mgr.hpp\"\r\n#include \"RX72N\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX65x\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX65x\/power_mgr.hpp\"\r\n#include \"RX65x\/icu.hpp\"\r\n#include \"RX65x\/icu_mgr.hpp\"\r\n#include \"RX65x\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX66T)\r\n#include \"RX66T\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX66T\/power_mgr.hpp\"\r\n#include \"RX66T\/icu.hpp\"\r\n#include \"RX66T\/icu_mgr.hpp\"\r\n#include \"RX66T\/port_map.hpp\"\r\n\r\n#elif defined(SIG_RX72T)\r\n#include \"RX72T\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72T\/power_mgr.hpp\"\r\n#include \"RX72T\/icu.hpp\"\r\n#include \"RX72T\/icu_mgr.hpp\"\r\n#include \"RX72T\/port_map.hpp\"\r\n\r\n#else\r\n# error \"device.hpp: Requires SIG_XXX to be defined\"\r\n#endif\r\n<commit_msg>Update: include path (port_map_mtu.hpp)<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX マイコン、デバイス固有ヘッダー\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/io_utils.hpp\"\r\n\r\n#if defined(SIG_RX24T)\r\n#include \"RX24T\/peripheral.hpp\"\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/power_mgr.hpp\"\r\n#include \"RX24T\/icu.hpp\"\r\n#include \"RX24T\/icu_mgr.hpp\"\r\n#include \"RX24T\/port_map.hpp\"\r\n#include \"RX24T\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX62N)\r\n#include \"RX62x\/system.hpp\"\r\n#include \"RX62x\/icu.hpp\"\r\n#include \"RX62x\/icu_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/power_mgr.hpp\"\r\n#include \"RX600\/icu.hpp\"\r\n#include \"RX600\/icu_mgr.hpp\"\r\n#include \"RX600\/port_map.hpp\"\r\n#include \"RX600\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX72M)\r\n#include \"RX72M\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72M\/power_mgr.hpp\"\r\n#include \"RX72M\/icu.hpp\"\r\n#include \"RX72M\/icu_mgr.hpp\"\r\n#include \"RX72M\/port_map.hpp\"\r\n#include \"RX72M\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX72N)\r\n#include \"RX72N\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72N\/power_mgr.hpp\"\r\n#include \"RX72N\/icu.hpp\"\r\n#include \"RX72N\/icu_mgr.hpp\"\r\n#include \"RX72N\/port_map.hpp\"\r\n#include \"RX72N\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX65x\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX65x\/power_mgr.hpp\"\r\n#include \"RX65x\/icu.hpp\"\r\n#include \"RX65x\/icu_mgr.hpp\"\r\n#include \"RX65x\/port_map.hpp\"\r\n#include \"RX65x\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX66T)\r\n#include \"RX66T\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX66T\/power_mgr.hpp\"\r\n#include \"RX66T\/icu.hpp\"\r\n#include \"RX66T\/icu_mgr.hpp\"\r\n#include \"RX66T\/port_map.hpp\"\r\n#include \"RX66T\/port_map_mtu.hpp\"\r\n\r\n#elif defined(SIG_RX72T)\r\n#include \"RX72T\/peripheral.hpp\"\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX72T\/power_mgr.hpp\"\r\n#include \"RX72T\/icu.hpp\"\r\n#include \"RX72T\/icu_mgr.hpp\"\r\n#include \"RX72T\/port_map.hpp\"\r\n#include \"RX72T\/port_map_mtu.hpp\"\r\n\r\n#else\r\n# error \"device.hpp: Requires SIG_XXX to be defined\"\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX グループ・SCI I\/O 制御\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2013, 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/vect.h\"\n\n\/\/\/ F_PCLKB はボーレートパラメーター計算で必要で、設定が無いとエラーにします。\n#ifndef F_PCLKB\n# error \"sci_io.hpp requires F_PCLKB to be defined\"\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief SCI I\/O 制御クラス\n\t\t@param[in]\tSCI\tSCI 定義クラス\n\t\t@param[in]\tRECV_BUFF\t受信バッファクラス\n\t\t@param[in]\tSEND_BUFF\t送信バッファクラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class SCI, class RECV_BUFF, class SEND_BUFF>\n\tclass sci_io {\n\n\t\tstatic RECV_BUFF recv_;\n\t\tstatic SEND_BUFF send_;\n\t\tstatic volatile bool send_stall_;\n\n\t\tuint8_t\tlevel_;\n\t\tbool\tcrlf_;\n\n\t\t\/\/ ※必要なら、実装する\n\t\tvoid sleep_() { asm(\"nop\"); }\n\n\t\tstatic INTERRUPT_FUNC void recv_task_()\n\t\t{\n\t\t\tbool err = false;\n\t\t\tif(SCI::SSR.ORER()) {\t\/\/\/< 受信オーバランエラー状態確認\n\t\t\t\tSCI::SSR.ORER = 0;\t\/\/\/< 受信オーバランエラークリア\n\t\t\t\terr = true;\n\t\t\t}\n\t\t\t\/\/\/< フレーミングエラー\/パリティエラー状態確認\n\t\t\tif(SCI::SSR() & (SCI::SSR.FER.b() | SCI::SSR.PER.b())) {\n\t\t\t\t\/\/ エラーフラグの消去\n\t\t\t\tSCI::SSR.FER = 0;\n\t\t\t\tSCI::SSR.PER = 0;\n\t\t\t\terr = true;\n\t\t\t}\n\t\t\tvolatile uint8_t data = SCI::RDR();\n\t\t\tif(!err) {\n\t\t\t\trecv_.put(data);\n\t\t\t}\n\t\t}\n\n\t\tstatic INTERRUPT_FUNC void send_task_()\n\t\t{\n#if SIG_RX64M\n\t\t\tif(send_.length() > 0) {\n\t\t\t\tSCI::TDR = send_.get();\n\t\t\t}\n\t\t\tif(send_.length() == 0) {\n\t\t\t\tSCI::SCR.TIE = 0;\n\t\t\t\tsend_stall_ = true;\n\t\t\t}\n#else\n\t\t\tSCI::TDR = send_.get();\n\t\t\tif(send_.length() == 0) {\n\t\t\t\tSCI::SCR.TEIE = 0;\n\t\t\t}\n#endif\n\t\t}\n\n\t\tvoid set_vector_(ICU::VECTOR rx_vec, ICU::VECTOR tx_vec) {\n\t\t\tif(level_) {\n\t\t\t\tset_interrupt_task(recv_task_, static_cast<uint32_t>(rx_vec));\n\t\t\t\tset_interrupt_task(send_task_, static_cast<uint32_t>(tx_vec));\n\t\t\t} else {\n\t\t\t\tset_interrupt_task(nullptr, static_cast<uint32_t>(rx_vec));\n\t\t\t\tset_interrupt_task(nullptr, static_cast<uint32_t>(tx_vec));\n\t\t\t}\n\t\t}\n\n\t\tvoid set_intr_() {\n#if SIG_RX64M\n\t\t\tset_vector_(SCI::get_rx_vec(), SCI::get_tx_vec());\n#else\n\t\t\tset_vector_(SCI::get_rx_vec(), SCI::get_te_vec());\n#endif\n\t\t\ticu_mgr::set_level(SCI::get_peripheral(), level_);\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tsci_io() : level_(0), crlf_(true) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief ボーレートを設定して、SCI を有効にする @n\n\t\t\t\t\t※RX63T では、ポーリングはサポート外\n\t\t\t@param[in]\tbaud\tボーレート\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合ポーリング)\n\t\t\t@return エラーなら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t baud, uint8_t level = 0) {\n\t\t\tsend_stall_ = true;\n#if SIG_RX63T\n\t\t\tif(level == 0) return false;\n#endif\n\t\t\tcrlf_ = true;\n\t\t\tlevel_ = level;\n\n\t\t\tSCI::SCR = 0x00;\t\t\t\/\/ TE, RE disable.\n\n\t\t\tport_map::turn(SCI::get_peripheral());\n\n\t\t\tuint32_t brr = F_PCLKB \/ baud \/ 16;\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(brr > 512) {\n\t\t\t\tbrr >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3) return false;\n\t\t\tbool abcs = true;\n\t\t\tif(brr > 256) { brr \/= 2; abcs = false; }\n\n\t\t\tpower_cfg::turn(SCI::get_peripheral());\n\n\t\t\tset_intr_();\n\n\t\t\t\/\/ 8 bits, 1 stop bit, no-parrity\n\t\t\tSCI::SMR = cks;\n\t\t\tSCI::SEMR.ABCS = abcs;\n\t\t\tif(brr) --brr;\n\t\t\tSCI::BRR = static_cast<uint8_t>(brr);\n\n\t\t\tif(level) {\n\t\t\t\tSCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b();\n\t\t\t} else {\n\t\t\t\tSCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 通信速度を設定して、SPI を有効にする\n\t\t\t@param[in]\tmaster\tマスターモードの場合「true」\n\t\t\t@param[in]\tbps\tビットレート\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合ポーリング)\n\t\t\t@return エラーなら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start_spi(bool master, uint32_t bps, uint8_t level = 0)\n\t\t{\n\t\t\tsend_stall_ = true;\n\t\t\tlevel_ = level;\n\n\t\t\tSCI::SCR = 0x00;\t\t\t\/\/ TE, RE disable.\n\n\t\t\tuint32_t brr = F_PCLKB \/ bps \/ 2;\n\t\t\tif(brr & 1) { brr >>= 1; ++brr; }\n\t\t\telse { brr >>= 1; }\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(brr > 256) {\n\t\t\t\tbrr >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3 || brr > 256) return false;\n\n\t\t\tpower_cfg::turn(SCI::get_peripheral());\n\n\t\t\tset_intr_();\n\n\t\t\t\/\/ LSB(0), MSB(1) first\n\t\t\tSCI::SCMR.SDIR = 1;\n\n\t\t\tSCI::SIMR1.IICM = 0;\n\t\t\tSCI::SMR = cks | SCI::SMR.CM.b();\n\t\t\tSCI::SPMR.SSE = 0;\t\t\/\/\/< SS 端子制御しない「0」\n\n\t\t\tif(master) {\n\t\t\t\tSCI::SPMR.MSS = 0;\n\t\t\t} else {\n\t\t\t\tSCI::SPMR.MSS = 1;\n\t\t\t}\n\n\t\t\t\/\/ クロックタイミング種別選択\n\t\t\tSCI::SPMR.CKPOL = 0;\n\t\t\tSCI::SPMR.CKPH = 0;\n\n\t\t\tif(brr) --brr;\n\t\t\tSCI::BRR = static_cast<uint8_t>(brr);\n\n\t\t\tuint8_t scr = 0;\n\t\t\tif(master) {\n\t\t\t\tscr = SCI::SCR.CKE.b(0b01);\n\t\t\t} else {\n\t\t\t\tscr = SCI::SCR.CKE.b(0b10);\n\t\t\t}\n\n\t\t\tif(level_) {\n\t\t\t\tSCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;\n\t\t\t} else {\n\t\t\t\tSCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tCRLF 自動送出\n\t\t\t@param[in]\tf\t「false」なら無効\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid auto_crlf(bool f = true) { crlf_ = f; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 出力バッファのサイズを返す\n\t\t\t@return バッファのサイズ\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint32_t send_length() const {\n\t\t\tif(level_) {\n\t\t\t\treturn send_.length();\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 文字出力\n\t\t\t@param[in]\tch\t文字コード\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid putch(char ch) {\n\t\t\tif(crlf_ && ch == '\\n') {\n\t\t\t\tputch('\\r');\n\t\t\t}\n\n\t\t\tif(level_) {\n\t\t\t\tvolatile bool b = SCI::SSR.ORER();\n\t\t\t\tif(b) {\n\t\t\t\t\tSCI::SSR.ORER = 0;\n\t\t\t\t}\n\t\t\t\t\/\/\/ 送信バッファの容量が7/8の場合は、空になるまで待つ。\n\t\t\t\tif(send_.length() >= (send_.size() * 7 \/ 8)) {\n\t\t\t\t\twhile(send_.length() != 0) sleep_();\n\t\t\t\t}\n\t\t\t\tsend_.put(ch);\n#if SIG_RX64M\n\t\t\t\tSCI::SCR.TIE = 0;\n\t\t\t\tif(send_stall_) {\n\t\t\t\t\twhile(SCI::SSR.TEND() == 0) sleep_();\n\t\t\t\t\tSCI::TDR = send_.get();\n\t\t\t\t\tif(send_.length() > 0) {\n\t\t\t\t\t\tsend_stall_ = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tSCI::SCR.TIE = !send_stall_;\n#else\n\t\t\t\tif(SCI::SCR.TEIE() == 0) {\n\t\t\t\t\tSCI::SCR.TEIE = 1;\n\t\t\t\t}\n#endif\n\t\t\t} else {\n\t\t\t\twhile(SCI::SSR.TEND() == 0) sleep_();\n\t\t\t\tSCI::TDR = ch;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 入力文字数を取得\n\t\t\t@return\t入力文字数\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint32_t recv_length() {\n\t\t\tif(level_) {\n\t\t\t\treturn recv_.length();\n\t\t\t} else {\n\t\t\t\tif(SCI::SSR.ORER()) {\t\/\/\/< 受信オーバランエラー状態確認\n\t\t\t\t\tSCI::SSR.ORER = 0;\t\/\/\/< 受信オーバランエラークリア\n\t\t\t\t}\n#if defined(SIG_RX64M) || defined(SIG_RX24T)\n\t\t\t\tauto n = SCI::SSR.RDRF();\n#else\n\t\t\t\tuint32_t n = 0;\n#endif\n\t\t\t\treturn n;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 文字入力\n\t\t\t@return 文字コード\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tchar getch() {\n\t\t\tif(level_) {\n\t\t\t\twhile(recv_.length() == 0) sleep_();\n\t\t\t\treturn recv_.get();\n\t\t\t} else {\n\t\t\t\tchar ch;\n\t\t\t\twhile(recv_length() == 0) sleep_();\n\t\t\t\tch = SCI::RDR();\t\/\/\/< 受信データ読み出し\n\t\t\t\treturn ch;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tuart文字列出力\n\t\t\t@param[in]\ts\t出力ストリング\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid puts(const char* s) {\n\t\t\tchar ch;\n\t\t\twhile((ch = *s++) != 0) {\n\t\t\t\tputch(ch);\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 送受信\n\t\t\t@param[in]\tch\t送信データ\n\t\t\t@return\t受信データ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tinline uint8_t xchg(uint8_t ch = 0xff)\n\t\t{\n\t\t\tif(level_) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tSCI::TDR = ch;\n\t\t\t\twhile(recv_length() == 0) sleep_();\n\t\t\t\treturn SCI::RDR();\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief シリアル送信\n\t\t\t@param[in]\tsrc\t送信ソース\n\t\t\t@param[in]\tcnt\t送信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid send(const void* src, uint16_t size)\n\t\t{\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\n\t\t\tauto end = p + size;\n\t\t\twhile(p < end) {\n\t\t\t\txchg(*p);\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief シリアル受信\n\t\t\t@param[out]\tdst\t受信先\n\t\t\t@param[in]\tcnt\t受信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid recv(void* dst, uint16_t size)\n\t\t{\n\t\t\tuint8_t* p = static_cast<uint8_t*>(dst);\n\t\t\tauto end = p + size;\n\t\t\twhile(p < end) {\n\t\t\t\t*p = xchg();\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tRECV_BUFF sci_io<SCI, RECV_BUFF, SEND_BUFF>::recv_;\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tSEND_BUFF sci_io<SCI, RECV_BUFF, SEND_BUFF>::send_;\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tvolatile bool sci_io<SCI, RECV_BUFF, SEND_BUFF>::send_stall_;\n}\n<commit_msg>update test interval for SPI<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX グループ・SCI I\/O 制御\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2013, 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/vect.h\"\n\n\/\/\/ F_PCLKB はボーレートパラメーター計算で必要で、設定が無いとエラーにします。\n#ifndef F_PCLKB\n# error \"sci_io.hpp requires F_PCLKB to be defined\"\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief SCI I\/O 制御クラス\n\t\t@param[in]\tSCI\tSCI 定義クラス\n\t\t@param[in]\tRECV_BUFF\t受信バッファクラス\n\t\t@param[in]\tSEND_BUFF\t送信バッファクラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class SCI, class RECV_BUFF, class SEND_BUFF>\n\tclass sci_io {\n\n\t\tstatic RECV_BUFF recv_;\n\t\tstatic SEND_BUFF send_;\n\t\tstatic volatile bool send_stall_;\n\n\t\tuint8_t\tlevel_;\n\t\tbool\tcrlf_;\n\n\t\t\/\/ ※必要なら、実装する\n\t\tvoid sleep_() { asm(\"nop\"); }\n\n\t\tstatic INTERRUPT_FUNC void recv_task_()\n\t\t{\n\t\t\tbool err = false;\n\t\t\tif(SCI::SSR.ORER()) {\t\/\/\/< 受信オーバランエラー状態確認\n\t\t\t\tSCI::SSR.ORER = 0;\t\/\/\/< 受信オーバランエラークリア\n\t\t\t\terr = true;\n\t\t\t}\n\t\t\t\/\/\/< フレーミングエラー\/パリティエラー状態確認\n\t\t\tif(SCI::SSR() & (SCI::SSR.FER.b() | SCI::SSR.PER.b())) {\n\t\t\t\t\/\/ エラーフラグの消去\n\t\t\t\tSCI::SSR.FER = 0;\n\t\t\t\tSCI::SSR.PER = 0;\n\t\t\t\terr = true;\n\t\t\t}\n\t\t\tvolatile uint8_t data = SCI::RDR();\n\t\t\tif(!err) {\n\t\t\t\trecv_.put(data);\n\t\t\t}\n\t\t}\n\n\t\tstatic INTERRUPT_FUNC void send_task_()\n\t\t{\n#if SIG_RX64M\n\t\t\tif(send_.length() > 0) {\n\t\t\t\tSCI::TDR = send_.get();\n\t\t\t}\n\t\t\tif(send_.length() == 0) {\n\t\t\t\tSCI::SCR.TIE = 0;\n\t\t\t\tsend_stall_ = true;\n\t\t\t}\n#else\n\t\t\tSCI::TDR = send_.get();\n\t\t\tif(send_.length() == 0) {\n\t\t\t\tSCI::SCR.TEIE = 0;\n\t\t\t}\n#endif\n\t\t}\n\n\t\tvoid set_vector_(ICU::VECTOR rx_vec, ICU::VECTOR tx_vec) {\n\t\t\tif(level_) {\n\t\t\t\tset_interrupt_task(recv_task_, static_cast<uint32_t>(rx_vec));\n\t\t\t\tset_interrupt_task(send_task_, static_cast<uint32_t>(tx_vec));\n\t\t\t} else {\n\t\t\t\tset_interrupt_task(nullptr, static_cast<uint32_t>(rx_vec));\n\t\t\t\tset_interrupt_task(nullptr, static_cast<uint32_t>(tx_vec));\n\t\t\t}\n\t\t}\n\n\t\tvoid set_intr_() {\n#if SIG_RX64M\n\t\t\tset_vector_(SCI::get_rx_vec(), SCI::get_tx_vec());\n#else\n\t\t\tset_vector_(SCI::get_rx_vec(), SCI::get_te_vec());\n#endif\n\t\t\ticu_mgr::set_level(SCI::get_peripheral(), level_);\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tsci_io() : level_(0), crlf_(true) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief ボーレートを設定して、SCI を有効にする @n\n\t\t\t\t\t※RX63T では、ポーリングはサポート外\n\t\t\t@param[in]\tbaud\tボーレート\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合ポーリング)\n\t\t\t@return エラーなら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t baud, uint8_t level = 0) {\n\t\t\tsend_stall_ = true;\n#if SIG_RX63T\n\t\t\tif(level == 0) return false;\n#endif\n\t\t\tcrlf_ = true;\n\t\t\tlevel_ = level;\n\n\t\t\tSCI::SCR = 0x00;\t\t\t\/\/ TE, RE disable.\n\n\t\t\tport_map::turn(SCI::get_peripheral());\n\n\t\t\tuint32_t brr = F_PCLKB \/ baud \/ 16;\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(brr > 512) {\n\t\t\t\tbrr >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3) return false;\n\t\t\tbool abcs = true;\n\t\t\tif(brr > 256) { brr \/= 2; abcs = false; }\n\n\t\t\tpower_cfg::turn(SCI::get_peripheral());\n\n\t\t\tset_intr_();\n\n\t\t\t\/\/ 8 bits, 1 stop bit, no-parrity\n\t\t\tSCI::SMR = cks;\n\t\t\tSCI::SEMR.ABCS = abcs;\n\t\t\tif(brr) --brr;\n\t\t\tSCI::BRR = static_cast<uint8_t>(brr);\n\n\t\t\tif(level) {\n\t\t\t\tSCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b();\n\t\t\t} else {\n\t\t\t\tSCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 通信速度を設定して、SPI を有効にする\n\t\t\t@param[in]\tmaster\tマスターモードの場合「true」\n\t\t\t@param[in]\tbps\tビットレート\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合ポーリング)\n\t\t\t@return エラーなら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start_spi(bool master, uint32_t bps, uint8_t level = 0)\n\t\t{\n\t\t\tsend_stall_ = true;\n\t\t\tlevel_ = level;\n\n\t\t\tSCI::SCR = 0x00;\t\t\t\/\/ TE, RE disable.\n\n\t\t\tuint32_t brr = F_PCLKB \/ bps \/ 2;\n\t\t\tif(brr & 1) { brr >>= 1; ++brr; }\n\t\t\telse { brr >>= 1; }\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(brr > 256) {\n\t\t\t\tbrr >>= 2;\n\t\t\t\t++cks;\n\t\t\t}\n\t\t\tif(cks > 3 || brr > 256) return false;\n\n\t\t\tpower_cfg::turn(SCI::get_peripheral());\n\n\t\t\tset_intr_();\n\n\t\t\t\/\/ LSB(0), MSB(1) first\n\t\t\tSCI::SCMR.SDIR = 1;\n\n\t\t\tSCI::SIMR1.IICM = 0;\n\t\t\tSCI::SMR = cks | SCI::SMR.CM.b();\n\t\t\tSCI::SPMR.SSE = 0;\t\t\/\/\/< SS 端子制御しない「0」\n\n\t\t\tif(master) {\n\t\t\t\tSCI::SPMR.MSS = 0;\n\t\t\t} else {\n\t\t\t\tSCI::SPMR.MSS = 1;\n\t\t\t}\n\n\t\t\t\/\/ クロックタイミング種別選択\n\t\t\tSCI::SPMR.CKPOL = 0;\n\t\t\tSCI::SPMR.CKPH = 0;\n\n\t\t\tif(brr) --brr;\nbrr = 1;\n\t\t\tSCI::BRR = static_cast<uint8_t>(brr);\n\n\t\t\tuint8_t scr = 0;\n\t\t\tif(master) {\n\t\t\t\tscr = SCI::SCR.CKE.b(0b01);\n\t\t\t} else {\n\t\t\t\tscr = SCI::SCR.CKE.b(0b10);\n\t\t\t}\n\n\t\t\tif(level_) {\n\t\t\t\tSCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;\n\t\t\t} else {\n\t\t\t\tSCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tCRLF 自動送出\n\t\t\t@param[in]\tf\t「false」なら無効\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid auto_crlf(bool f = true) { crlf_ = f; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 出力バッファのサイズを返す\n\t\t\t@return バッファのサイズ\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint32_t send_length() const {\n\t\t\tif(level_) {\n\t\t\t\treturn send_.length();\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 文字出力\n\t\t\t@param[in]\tch\t文字コード\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid putch(char ch) {\n\t\t\tif(crlf_ && ch == '\\n') {\n\t\t\t\tputch('\\r');\n\t\t\t}\n\n\t\t\tif(level_) {\n\t\t\t\tvolatile bool b = SCI::SSR.ORER();\n\t\t\t\tif(b) {\n\t\t\t\t\tSCI::SSR.ORER = 0;\n\t\t\t\t}\n\t\t\t\t\/\/\/ 送信バッファの容量が7/8の場合は、空になるまで待つ。\n\t\t\t\tif(send_.length() >= (send_.size() * 7 \/ 8)) {\n\t\t\t\t\twhile(send_.length() != 0) sleep_();\n\t\t\t\t}\n\t\t\t\tsend_.put(ch);\n#if SIG_RX64M\n\t\t\t\tSCI::SCR.TIE = 0;\n\t\t\t\tif(send_stall_) {\n\t\t\t\t\twhile(SCI::SSR.TEND() == 0) sleep_();\n\t\t\t\t\tSCI::TDR = send_.get();\n\t\t\t\t\tif(send_.length() > 0) {\n\t\t\t\t\t\tsend_stall_ = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tSCI::SCR.TIE = !send_stall_;\n#else\n\t\t\t\tif(SCI::SCR.TEIE() == 0) {\n\t\t\t\t\tSCI::SCR.TEIE = 1;\n\t\t\t\t}\n#endif\n\t\t\t} else {\n\t\t\t\twhile(SCI::SSR.TEND() == 0) sleep_();\n\t\t\t\tSCI::TDR = ch;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 入力文字数を取得\n\t\t\t@return\t入力文字数\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint32_t recv_length() {\n\t\t\tif(level_) {\n\t\t\t\treturn recv_.length();\n\t\t\t} else {\n\t\t\t\tif(SCI::SSR.ORER()) {\t\/\/\/< 受信オーバランエラー状態確認\n\t\t\t\t\tSCI::SSR.ORER = 0;\t\/\/\/< 受信オーバランエラークリア\n\t\t\t\t}\n#if defined(SIG_RX64M) || defined(SIG_RX24T)\n\t\t\t\tauto n = SCI::SSR.RDRF();\n#else\n\t\t\t\tuint32_t n = 0;\n#endif\n\t\t\t\treturn n;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tSCI 文字入力\n\t\t\t@return 文字コード\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tchar getch() {\n\t\t\tif(level_) {\n\t\t\t\twhile(recv_.length() == 0) sleep_();\n\t\t\t\treturn recv_.get();\n\t\t\t} else {\n\t\t\t\tchar ch;\n\t\t\t\twhile(recv_length() == 0) sleep_();\n\t\t\t\tch = SCI::RDR();\t\/\/\/< 受信データ読み出し\n\t\t\t\treturn ch;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tuart文字列出力\n\t\t\t@param[in]\ts\t出力ストリング\n\t\t *\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid puts(const char* s) {\n\t\t\tchar ch;\n\t\t\twhile((ch = *s++) != 0) {\n\t\t\t\tputch(ch);\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 送受信\n\t\t\t@param[in]\tch\t送信データ\n\t\t\t@return\t受信データ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tinline uint8_t xchg(uint8_t ch = 0xff)\n\t\t{\n\t\t\tif(level_) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tSCI::TDR = ch;\n\t\t\t\twhile(recv_length() == 0) sleep_();\n\t\t\t\treturn SCI::RDR();\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief シリアル送信\n\t\t\t@param[in]\tsrc\t送信ソース\n\t\t\t@param[in]\tcnt\t送信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid send(const void* src, uint16_t size)\n\t\t{\n\t\t\tconst uint8_t* p = static_cast<const uint8_t*>(src);\n\t\t\tauto end = p + size;\n\t\t\twhile(p < end) {\n\t\t\t\txchg(*p);\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief シリアル受信\n\t\t\t@param[out]\tdst\t受信先\n\t\t\t@param[in]\tcnt\t受信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid recv(void* dst, uint16_t size)\n\t\t{\n\t\t\tuint8_t* p = static_cast<uint8_t*>(dst);\n\t\t\tauto end = p + size;\n\t\t\twhile(p < end) {\n\t\t\t\t*p = xchg();\n\t\t\t\t++p;\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tRECV_BUFF sci_io<SCI, RECV_BUFF, SEND_BUFF>::recv_;\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tSEND_BUFF sci_io<SCI, RECV_BUFF, SEND_BUFF>::send_;\n\ttemplate<class SCI, class RECV_BUFF, class SEND_BUFF>\n\t\tvolatile bool sci_io<SCI, RECV_BUFF, SEND_BUFF>::send_stall_;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tR8C グループ・TimerRJ I\/O 制御 @n\n\t\t\tCopyright 2015 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/vect.h\"\n#include \"system.hpp\"\n#include \"intr.hpp\"\n#include \"timer_rj.hpp\"\n\n\/\/\/ F_CLK はタイマー周期計算で必要で、設定が無いとエラーにします。\n#ifndef F_CLK\n# error \"trj_io.hpp requires F_CLK to be defined\"\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief TimerRJ I\/O 制御クラス\n\t\t@param[in]\tTASK 割り込み内で実行されるクラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class TASK>\n\tclass trj_io {\n\n\t\tstatic TASK task_;\n\n\tpublic:\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief パルス計測モード\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class measurement {\n\t\t\tlow_width,\t\/\/\/< Low レベル幅測定\n\t\t\thigh_width,\t\/\/\/< High レベル幅測定\n\t\t\tfreq,\t\t\/\/\/< 周波数測定\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief フィルタータイプ\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class filter {\n\t\t\tnone,\t\t\/\/\/< 無し\n\t\t\tf1 = 1,\t\t\/\/\/< f1 フィルター\n\t\t\tf8 = 2,\t\t\/\/\/< f8 フィルター\n\t\t\tf32 = 3,\t\/\/\/< f32 フィルター\n\t\t};\n\n\t\tstatic volatile uint8_t trjmr_;\n\t\tstatic volatile uint16_t trj_;\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief パルス出力用割り込み関数\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tstatic INTERRUPT_FUNC void itask_out() {\n\t\t\tTRJMR = trjmr_;\n\t\t\tTRJ = trj_;\n\t\t\ttask_();\n\t\t\tvolatile uint8_t v = TRJIR();\n\t\t\tTRJIR = 0x00;\n\t\t}\n\n\tprivate:\n\t\tbool set_freq_(uint32_t freq, uint16_t& trj, uint8_t& tck) const {\n\t\t\tuint32_t tn = F_CLK \/ (freq * 2);\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(tn > 65536) {\n\t\t\t\ttn >>= 1;\n\t\t\t\t++cks;\n\t\t\t\tif(cks == 2) {\n\t\t\t\t\ttn >>= 1;\n\t\t\t\t}\n\t\t\t\tif(cks >= 3) return false;\n\t\t\t}\n\t\t\tif(tn) --tn;\n\t\t\telse return false;\n\n\t\t\tstatic const uint8_t tbl_[3] = { 0, 3, 1 }; \/\/ 1\/1, 1\/2, 1\/8\n\t\t\ttck = tbl_[cks];\n\t\t\ttrj = tn;\n\n\t\t\treturn true;\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttrj_io() { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief パルス出力の開始(TRJIO\/TRJO 端子から、パルスを出力)\n\t\t\t@param[in]\tfreq\t周波数\n\t\t\t@param[in]\tir_lvl\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t\t@return 設定範囲を超えたら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool pluse_out(uint32_t freq, uint8_t ir_lvl = 0) const {\n\t\t\tMSTCR.MSTTRJ = 0; \/\/ モジュールスタンバイ解除\n\n\t\t\tTRJCR.TSTART = 0; \/\/ カウンタを停止\n\n\t\t\tuint16_t trj;\n\t\t\tuint8_t tck;\n\t\t\tif(!set_freq_(freq, trj, tck)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tTRJMR = trjmr_ = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1); \/\/ パルス出力モード\n\t\t\tTRJ = trj_ = trj;\n\n\t\t\tTRJIOC.TEDGSEL = 1; \/\/ L から出力\n\t\t\tTRJIOC.TOPCR = 0; \/\/ トグル出力\n\n\t\t\tILVLB.B01 = ir_lvl;\n\t\t\tif(ir_lvl) {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(1);\n\t\t\t} else {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(0);\n\t\t\t}\n\n\t\t\tTRJCR.TSTART = 1; \/\/ カウンタを開始\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TRJ 出力周波数の再設定\n\t\t\t@param[in]\tfreq\t周波数\n\t\t\t@return 設定範囲を超えたら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool set_cycle(uint32_t freq) const {\n\t\t\tuint16_t trj;\n\t\t\tuint8_t tck;\n\t\t\tif(!set_freq_(freq, trj, tck)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ パルス出力モード\n\t\t\t\/\/ TRJ = 0 だと、割り込みが発生しないので、ダイレクト出力する\n\t\t\tif(trj_ != 0 && ILVLB.B01()) {\n\t\t\t\ttrjmr_ = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1);\n\t\t\t\ttrj_ = trj;\n\t\t\t\tdi();\n\t\t\t\tvolatile uint8_t v = TRJIR();\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(1);\n\t\t\t\tei();\n\t\t\t} else {\n\t\t\t\tTRJMR = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1);\n\t\t\t\tTRJ = trj;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief パルス計測の開始(TRJIO 端子から、パルスを入力)\n\t\t\t@param[in]\tmeasur\tパルス計測のモード\n\t\t\t@param[in]\tfil\t\t入力フィルター\n\t\t\t@param[in]\tir_lvl\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid pluse_inp(measurement measur, filter fil = filter::none, uint8_t ir_lvl = 0) const {\n\t\t\tMSTCR.MSTTRJ = 0; \/\/ モジュールスタンバイ解除\n\n\t\t\tTRJCR.TSTART = 0; \/\/ カウンタを停止\n\n\t\t\tTRJIOC = TRJIOC.TIPF.b(static_cast<uint8_t>(fil)) | TRJIOC.TOPCR.b(1);\n\/\/\t\t\tTRJMR = \n\n\t\t\tTRJ = 0;\n\n\t\t\tTRJCR.TSTART = 1; \/\/ カウンタを開始\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TRJ カウント値を取得\n\t\t\t@return カウント値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_count() const {\n\t\t\treturn TRJ();\n\t\t}\n\n\t};\n\n\t\/\/ スタティック実態定義\n\ttemplate<class TASK>\n\tvolatile uint8_t trj_io<TASK>::trjmr_;\n\ttemplate<class TASK>\n\tvolatile uint16_t trj_io<TASK>::trj_;\n\n}\n<commit_msg>Update TimerJ I\/O class<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tR8C グループ・TimerRJ I\/O 制御 @n\n\t\t\tCopyright 2015 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/vect.h\"\n#include \"system.hpp\"\n#include \"intr.hpp\"\n#include \"timer_rj.hpp\"\n\n\/\/\/ F_CLK はタイマー周期計算で必要で、設定が無いとエラーにします。\n#ifndef F_CLK\n# error \"trj_io.hpp requires F_CLK to be defined\"\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief TimerRJ I\/O 制御クラス\n\t\t@param[in]\tTASK 割り込み内で実行されるクラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class TASK>\n\tclass trj_io {\n\n\t\tstatic TASK task_;\n\n\tpublic:\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief パルス計測モード\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class measurement : uint8_t {\n\t\t\tlow_width,\t\/\/\/< Low レベル幅測定\n\t\t\thigh_width,\t\/\/\/< High レベル幅測定\n\t\t\tcount,\t\t\/\/\/< パルス数測定\n\t\t\tfreq,\t\t\/\/\/< 周期測定\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief フィルタータイプ\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class filter : uint8_t {\n\t\t\tnone,\t\t\/\/\/< 無し\n\t\t\tf1 = 1,\t\t\/\/\/< f1 フィルター\n\t\t\tf8 = 2,\t\t\/\/\/< f8 フィルター\n\t\t\tf32 = 3,\t\/\/\/< f32 フィルター\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief カウンターソース\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class source : uint8_t {\n\t\t\tf1 = 0,\t\t\/\/\/< f1\n\t\t\tf2 = 3,\t\t\/\/\/< f2\n\t\t\tf8 = 1,\t\t\/\/\/< f8\n\t\t\tfHOCO = 2\t\/\/\/< fHOCO\n\t\t};\n\n\n\t\tstatic volatile uint8_t trjmr_;\n\t\tstatic volatile uint16_t trj_;\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief パルス出力用割り込み関数\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tstatic INTERRUPT_FUNC void iout() {\n\t\t\tTRJMR = trjmr_;\n\t\t\tTRJ = trj_;\n\t\t\tvolatile uint8_t v = TRJIR();\n\t\t\tTRJIR = 0x00;\n\t\t\ttask_();\n\t\t}\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief パルス入力用割り込み関数\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tstatic INTERRUPT_FUNC void iinp() {\n\t\t\tuint8_t trjir = TRJIR.TRJIE.b(1);\n\t\t\tif(TRJCR.TEDGF()) {\n\t\t\t\tif(trjmr_ == 0) {\n\t\t\t\t\ttrj_ = TRJ();\n\t\t\t\t\ttrjir = 0x00;\n\t\t\t\t} else {\n\t\t\t\t\t--trjmr_;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvolatile uint8_t v = TRJIR();\n\t\t\tTRJIR = trjir;\n \t\t\ttask_();\n\t\t}\n\n\n\tprivate:\n\t\tbool set_freq_(uint32_t freq, uint16_t& trj, uint8_t& tck) const {\n\t\t\tuint32_t tn = F_CLK \/ (freq * 2);\n\t\t\tuint8_t cks = 0;\n\t\t\twhile(tn > 65536) {\n\t\t\t\ttn >>= 1;\n\t\t\t\t++cks;\n\t\t\t\tif(cks == 2) {\n\t\t\t\t\ttn >>= 1;\n\t\t\t\t}\n\t\t\t\tif(cks >= 3) return false;\n\t\t\t}\n\t\t\tif(tn) --tn;\n\t\t\telse return false;\n\n\t\t\tstatic const uint8_t tbl_[3] = { 0, 3, 1 }; \/\/ 1\/1, 1\/2, 1\/8\n\t\t\ttck = tbl_[cks];\n\t\t\ttrj = tn;\n\n\t\t\treturn true;\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttrj_io() { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief パルス出力の開始(TRJIO\/TRJO 端子から、パルスを出力)\n\t\t\t@param[in]\tfreq\t周波数\n\t\t\t@param[in]\tir_lvl\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t\t@return 設定範囲を超えたら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool pluse_out(uint32_t freq, uint8_t ir_lvl = 0) const {\n\t\t\tMSTCR.MSTTRJ = 0; \/\/ モジュールスタンバイ解除\n\n\t\t\tTRJCR.TSTART = 0; \/\/ カウンタを停止\n\n\t\t\tuint16_t trj;\n\t\t\tuint8_t tck;\n\t\t\tif(!set_freq_(freq, trj, tck)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tTRJMR = trjmr_ = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1); \/\/ パルス出力モード\n\t\t\tTRJ = trj_ = trj;\n\n\t\t\tTRJIOC.TEDGSEL = 1; \/\/ L から出力\n\t\t\tTRJIOC.TOPCR = 0; \/\/ トグル出力\n\n\t\t\tILVLB.B01 = ir_lvl;\n\t\t\tif(ir_lvl) {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(1);\n\t\t\t} else {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(0);\n\t\t\t}\n\n\t\t\tTRJCR.TSTART = 1; \/\/ カウンタを開始\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TRJ 出力周波数の再設定\n\t\t\t@param[in]\tfreq\t周波数\n\t\t\t@return 設定範囲を超えたら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool set_cycle(uint32_t freq) const {\n\t\t\tuint16_t trj;\n\t\t\tuint8_t tck;\n\t\t\tif(!set_freq_(freq, trj, tck)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ パルス出力モード\n\t\t\t\/\/ TRJ = 0 だと、割り込みが発生しないので、直接設定する\n\t\t\tif(trj_ != 0 && ILVLB.B01()) {\n\t\t\t\ttrjmr_ = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1);\n\t\t\t\ttrj_ = trj;\n\t\t\t\tdi();\n\t\t\t\tvolatile uint8_t v = TRJIR();\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(1);\n\t\t\t\tei();\n\t\t\t} else {\n\t\t\t\tTRJMR = TRJMR.TCK.b(tck) | TRJMR.TCKCUT.b(0) | TRJMR.TMOD.b(1);\n\t\t\t\tTRJ = trj;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief パルス計測の開始(TRJIO 端子から、パルスを入力)@n\n\t\t\t\t\t※VCOUT1 端子から入力する場合は、TRJIOSEL を設定する。\n\t\t\t@param[in]\tmeasur\tパルス計測のモード\n\t\t\t@param[in]\ts\t\tカウンターソース(countの場合は無効)\n\t\t\t@param[in]\tir_lvl\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid pluse_inp(measurement measur, source s, uint8_t ir_lvl = 0) const {\n\t\t\tMSTCR.MSTTRJ = 0; \/\/ モジュールスタンバイ解除\n\n\t\t\tTRJCR = 0x00; \/\/ カウンタ停止\n\n\t\t\tbool f = TRJIOC.TEDGSEL();\n\t\t\tuint8_t md = 3;\n\t\t\tif(measur == measurement::low_width) {\n\t\t\t\tf = 0;\n\t\t\t} else if(measur == measurement::high_width) {\n\t\t\t\tf = 1;\n\t\t\t} else if(measur == measurement::count) {\n\t\t\t\tmd = 2;\n\t\t\t} else if(measur == measurement::freq) {\n\t\t\t\tmd = 4;\n\t\t\t}\n\t\t\tTRJIOC = TRJIOC.TEDGSEL.b(f) | TRJIOC.TIPF.b(0) | TRJIOC.TOPCR.b(0);\n\t\t\tTRJMR = TRJMR.TMOD.b(md) | TRJMR.TCK.b(static_cast<uint8_t>(s))\n\t\t\t\t\t\t | TRJMR.TEDGPL.b(0) | TRJMR.TCKCUT.b(0);\n\n\t\t\tILVLB.B01 = ir_lvl;\n\t\t\tif(ir_lvl) {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(1);\n\t\t\t} else {\n\t\t\t\tTRJIR = TRJIR.TRJIE.b(0);\n\t\t\t}\n\n\t\t\ttrjmr_ = 2;\n\t\t\tTRJ = trj_ = 0xffff;\n\t\t\tTRJCR = TRJCR.TSTART.b(1); \/\/ カウンタを開始、アンダーフロー・クリア\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief TRJ カウント値を取得(割り込み内で設定された値)\n\t\t\t@param[out]\tcount\tカウント値\n\t\t\t@return アンダーフローの場合「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool get_count(uint16_t& count) const {\n\t\t\tif(ILVLB.B01()) {\n\t\t\t\tcount = ~trj_;\n\t\t\t} else {\n\t\t\t\tcount = ~TRJ();\n\t\t\t}\n\t\t\treturn !TRJCR.TUNDF();\n\t\t}\n\n\t};\n\n\t\/\/ スタティック実態定義\n\ttemplate<class TASK>\n\tvolatile uint8_t trj_io<TASK>::trjmr_;\n\ttemplate<class TASK>\n\tvolatile uint16_t trj_io<TASK>::trj_;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <kernel\/elf.hpp>\n#include <common>\n#include <cassert>\n#include <cstdio>\n#include <string>\n#include <unistd.h>\n#include <info>\n#include <vector>\n#include \"..\/..\/vmbuild\/elf.h\"\n\nstatic const char* null_stringz = \"(null)\";\nstatic const char* boot_stringz = \"Bootloader area\";\nextern \"C\" char _ELF_START_;\nstatic const uintptr_t ELF_START = reinterpret_cast<uintptr_t>(&_ELF_START_);\n\n#define frp(N, ra) \\\n (__builtin_frame_address(N) != nullptr) && \\\n (ra = __builtin_return_address(N)) != nullptr\n\nextern \"C\" char *\n__cxa_demangle(const char *name, char *buf, size_t *n, int *status);\n\ntemplate <typename N>\nstatic std::string to_hex_string(N n)\n{\n std::string buffer; buffer.reserve(64);\n snprintf((char*) buffer.data(), buffer.capacity(), \"%#x\", n);\n return buffer;\n}\n\nstatic Elf32_Ehdr& elf_header() {\n return *(Elf32_Ehdr*) ELF_START;\n}\n\nstruct SymTab {\n Elf32_Sym* base;\n uint32_t entries;\n};\nstruct StrTab {\n const char* base;\n uint32_t size;\n};\n\nclass ElfTables\n{\npublic:\n ElfTables() {}\n\n void set(void* syms, uint32_t entries, const char* string_table)\n {\n symtab.base = (Elf32_Sym*) syms;\n symtab.entries = entries;\n strtab = string_table;\n }\n\n func_offset getsym(Elf32_Addr addr)\n {\n \/\/ probably just a null pointer with ofs=addr\n if (UNLIKELY(addr < 0x7c00))\n return {null_stringz, 0, addr};\n \/\/ definitely in the bootloader\n if (UNLIKELY(addr < 0x7e00))\n return {boot_stringz, 0x7c00, addr - 0x7c00};\n \/\/ resolve manually from symtab\n auto* sym = getaddr(addr);\n \/\/ validate symbol address\n \/\/assert(sym >= symtab.base && sym < symtab.base + symtab.entries);\n if (LIKELY(sym)) {\n auto base = sym->st_value;\n auto offset = addr - base;\n \/\/ return string name for symbol\n return {demangle( sym_name(sym) ), base, offset};\n }\n \/\/ function or space not found\n return {to_hex_string(addr), addr, 0};\n }\n safe_func_offset getsym_safe(Elf32_Addr addr, char* buffer, size_t length)\n {\n \/\/ probably just a null pointer with ofs=addr\n if (addr < 0x7c00) return {null_stringz, 0, addr};\n \/\/ definitely in the bootloader\n if (addr < 0x7e00) return {boot_stringz, 0x7c00, addr - 0x7c00};\n \/\/ resolve manually from symtab\n auto* sym = getaddr(addr);\n if (sym) {\n auto base = sym->st_value;\n auto offset = addr - base;\n \/\/ return string name for symbol\n return {demangle_safe( sym_name(sym), buffer, length ), base, offset};\n }\n \/\/ function or space not found\n snprintf(buffer, length, \"%#x\", addr);\n return {buffer, addr, 0};\n }\n\n Elf32_Addr getaddr(const std::string& name)\n {\n for (size_t i = 0; i < symtab.entries; i++)\n {\n auto& sym = symtab.base[i];\n \/\/if (ELF32_ST_TYPE(sym.st_info) == STT_FUNC)\n if (demangle( sym_name(&sym) ) == name)\n return sym.st_value;\n }\n return 0;\n }\n Elf32_Sym* getaddr(Elf32_Addr addr)\n {\n for (size_t i = 0; i < symtab.entries; i++) {\n\n \/\/if (ELF32_ST_TYPE(symtab.base[i].st_info) == STT_FUNC)\n if (addr >= symtab.base[i].st_value\n && (addr < symtab.base[i].st_value + symtab.base[i].st_size))\n return &symtab.base[i];\n }\n return nullptr;\n }\n\n size_t end_of_file() const {\n auto& hdr = elf_header();\n return hdr.e_ehsize + (hdr.e_phnum * hdr.e_phentsize) + (hdr.e_shnum * hdr.e_shentsize);\n }\n\n const SymTab& get_symtab() const {\n return symtab;\n }\n\n const auto* get_strtab() const {\n return strtab;\n }\n\nprivate:\n const char* sym_name(Elf32_Sym* sym) const {\n return &strtab[sym->st_name];\n }\n std::string demangle(const char* name) const\n {\n if (name[0] == '_') {\n int status;\n \/\/ internally, demangle just returns buf when status is ok\n auto* res = __cxa_demangle(name, nullptr, 0, &status);\n if (status == 0) {\n std::string result(res);\n std::free(res);\n return result;\n }\n }\n return std::string(name);\n }\n const char* demangle_safe(const char* name, char* buffer, size_t buflen) const\n {\n int status;\n \/\/ internally, demangle just returns buf when status is ok\n auto* res = __cxa_demangle(name, (char*) buffer, &buflen, &status);\n if (status) return name;\n return res;\n }\n\n SymTab symtab;\n const char* strtab;\n};\nstatic ElfTables parser;\n\nElfTables& get_parser() {\n return parser;\n}\n\nsize_t Elf::end_of_file() {\n return get_parser().end_of_file();\n}\nconst char* Elf::get_strtab() {\n return get_parser().get_strtab();\n}\n\nfunc_offset Elf::resolve_symbol(uintptr_t addr)\n{\n return get_parser().getsym(addr);\n}\nfunc_offset Elf::resolve_symbol(void* addr)\n{\n return get_parser().getsym((uintptr_t) addr);\n}\n\nuintptr_t Elf::resolve_addr(uintptr_t addr)\n{\n auto* sym = get_parser().getaddr(addr);\n if (sym) return sym->st_value;\n return addr;\n}\nuintptr_t Elf::resolve_addr(void* addr)\n{\n auto* sym = get_parser().getaddr((uintptr_t) addr);\n if (sym) return sym->st_value;\n return (uintptr_t) addr;\n}\n\nsafe_func_offset Elf::safe_resolve_symbol(void* addr, char* buffer, size_t length)\n{\n return get_parser().getsym_safe((Elf32_Addr) addr, buffer, length);\n}\nuintptr_t Elf::resolve_name(const std::string& name)\n{\n return get_parser().getaddr(name);\n}\n\nfunc_offset Elf::get_current_function()\n{\n return resolve_symbol(__builtin_return_address(0));\n}\nstd::vector<func_offset> Elf::get_functions()\n{\n std::vector<func_offset> vec;\n #define ADD_TRACE(N, ra) \\\n vec.push_back(Elf::resolve_symbol(ra));\n\n void* ra;\n if (frp(0, ra)) {\n ADD_TRACE(0, ra);\n if (frp(1, ra)) {\n ADD_TRACE(1, ra);\n if (frp(2, ra)) {\n ADD_TRACE(2, ra);\n if (frp(3, ra)) {\n ADD_TRACE(3, ra);\n if (frp(4, ra)) {\n ADD_TRACE(4, ra);\n if (frp(5, ra)) {\n ADD_TRACE(5, ra);\n if (frp(6, ra)) {\n ADD_TRACE(6, ra);\n if (frp(7, ra)) {\n ADD_TRACE(7, ra);\n if (frp(8, ra)) {\n ADD_TRACE(8, ra);\n }}}}}}}}}\n return vec;\n}\n\nvoid print_backtrace()\n{\n char _symbol_buffer[512];\n char _btrace_buffer[512];\n\n if (Elf::get_strtab() == NULL) {\n int len = snprintf(_btrace_buffer, sizeof(_btrace_buffer),\n \"symtab or strtab is empty, indicating image may be stripped\\n\");\n write(1, _btrace_buffer, len);\n }\n\n #define PRINT_TRACE(N, ra) \\\n auto symb = Elf::safe_resolve_symbol( \\\n ra, _symbol_buffer, sizeof(_symbol_buffer)); \\\n int len = snprintf(_btrace_buffer, sizeof(_btrace_buffer),\\\n \"[%d] %8x + 0x%.3x: %s\\n\", \\\n N, symb.addr, symb.offset, symb.name);\\\n write(1, _btrace_buffer, len);\n\n printf(\"\\n\");\n void* ra;\n if (frp(0, ra)) {\n PRINT_TRACE(0, ra);\n if (frp(1, ra)) {\n PRINT_TRACE(1, ra);\n if (frp(2, ra)) {\n PRINT_TRACE(2, ra);\n if (frp(3, ra)) {\n PRINT_TRACE(3, ra);\n if (frp(4, ra)) {\n PRINT_TRACE(4, ra);\n if (frp(5, ra)) {\n PRINT_TRACE(5, ra);\n if (frp(6, ra)) {\n PRINT_TRACE(6, ra);\n if (frp(7, ra)) {\n PRINT_TRACE(7, ra);\n if (frp(8, ra)) {\n PRINT_TRACE(8, ra);\n }}}}}}}}}\n}\n\nvoid Elf::print_info()\n{\n auto& hdr = elf_header();\n \/\/ program headers\n auto* phdr = (Elf32_Phdr*) (ELF_START + hdr.e_phoff);\n printf(\"program headers offs=%#x at phys %p\\n\", hdr.e_phoff, phdr);\n \/\/ section headers\n auto* shdr = (Elf32_Shdr*) (ELF_START + hdr.e_shoff);\n printf(\"section headers offs=%#x at phys %p\\n\", hdr.e_shoff, shdr);\n for (Elf32_Half i = 0; i < hdr.e_shnum; i++)\n {\n uintptr_t start = ELF_START + shdr[i].sh_offset;\n uintptr_t end = start + shdr[i].sh_size;\n printf(\"sh from %#x to %#x\\n\", start, end);\n }\n\n}\n\nextern \"C\"\nvoid _print_elf_symbols()\n{\n const auto& symtab = parser.get_symtab();\n const char* strtab = parser.get_strtab();\n\n for (size_t i = 0; i < symtab.entries; i++)\n {\n printf(\"%8x: %s\\n\", symtab.base[i].st_value, &strtab[symtab.base[i].st_name]);\n }\n printf(\"*** %u entries\\n\", symtab.entries);\n}\nextern \"C\"\nvoid _validate_elf_symbols()\n{\n const auto& symtab = parser.get_symtab();\n const char* strtab = parser.get_strtab();\n if (symtab.entries == 0 || strtab == nullptr) return;\n\n for (size_t i = 1; i < symtab.entries; i++)\n {\n if (symtab.base[i].st_value != 0) {\n assert(symtab.base[i].st_value > 0x2000);\n const char* string = &strtab[symtab.base[i].st_name];\n assert(strlen(string));\n }\n }\n}\n\nstruct relocate_header {\n SymTab symtab;\n StrTab strtab;\n};\n\nextern \"C\"\nint _get_elf_section_size(const void* location)\n{\n auto& hdr = *(relocate_header*) location;\n return sizeof(relocate_header) + hdr.symtab.entries * sizeof(Elf32_Sym) + hdr.strtab.size;\n}\n\nextern \"C\"\nvoid _move_elf_symbols(void* old_location, void* new_location)\n{\n int size = _get_elf_section_size(old_location);\n memcpy(new_location, old_location, size);\n \/\/ update symbol info table\n auto* newhdr = (relocate_header*) new_location;\n const char* base = ((char*) newhdr) + sizeof(relocate_header);\n newhdr->symtab.base = (Elf32_Sym*) base;\n newhdr->strtab.base = &base[newhdr->symtab.entries * sizeof(Elf32_Sym)];\n}\n\n#include <malloc.h>\nextern \"C\"\nvoid* _relocate_to_heap(void* old_location)\n{\n int total = _get_elf_section_size(old_location);\n void* heap_location = malloc(total);\n\n _move_elf_symbols(old_location, heap_location);\n return heap_location;\n}\n\nextern \"C\"\nvoid _apply_parser_data(char* location)\n{\n if (location) {\n auto& hdr = *(relocate_header*) location;\n \/\/ apply changes to the symbol parser from custom location\n parser.set(hdr.symtab.base, hdr.symtab.entries, hdr.strtab.base);\n }\n else {\n \/\/ symbols and strings are stripped out\n parser.set(nullptr, 0, nullptr);\n }\n}\n<commit_msg>elf: Fix broken to_hex_string<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <kernel\/elf.hpp>\n#include <common>\n#include <cassert>\n#include <cstdio>\n#include <string>\n#include <unistd.h>\n#include <info>\n#include <vector>\n#include \"..\/..\/vmbuild\/elf.h\"\n\nstatic const char* null_stringz = \"(null)\";\nstatic const char* boot_stringz = \"Bootloader area\";\nextern \"C\" char _ELF_START_;\nstatic const uintptr_t ELF_START = reinterpret_cast<uintptr_t>(&_ELF_START_);\n\n#define frp(N, ra) \\\n (__builtin_frame_address(N) != nullptr) && \\\n (ra = __builtin_return_address(N)) != nullptr\n\nextern \"C\" char *\n__cxa_demangle(const char *name, char *buf, size_t *n, int *status);\n\ntemplate <typename N>\nstatic std::string to_hex_string(N n)\n{\n char buffer[16];\n int len = snprintf(buffer, sizeof(buffer), \"%#x\", n);\n return std::string(buffer, len);\n}\n\nstatic Elf32_Ehdr& elf_header() {\n return *(Elf32_Ehdr*) ELF_START;\n}\n\nstruct SymTab {\n Elf32_Sym* base;\n uint32_t entries;\n};\nstruct StrTab {\n const char* base;\n uint32_t size;\n};\n\nclass ElfTables\n{\npublic:\n ElfTables() {}\n\n void set(void* syms, uint32_t entries, const char* string_table)\n {\n symtab.base = (Elf32_Sym*) syms;\n symtab.entries = entries;\n strtab = string_table;\n }\n\n func_offset getsym(Elf32_Addr addr)\n {\n \/\/ probably just a null pointer with ofs=addr\n if (UNLIKELY(addr < 0x7c00))\n return {null_stringz, 0, addr};\n \/\/ definitely in the bootloader\n if (UNLIKELY(addr < 0x7e00))\n return {boot_stringz, 0x7c00, addr - 0x7c00};\n \/\/ resolve manually from symtab\n auto* sym = getaddr(addr);\n \/\/ validate symbol address\n \/\/assert(sym >= symtab.base && sym < symtab.base + symtab.entries);\n if (LIKELY(sym)) {\n auto base = sym->st_value;\n auto offset = addr - base;\n \/\/ return string name for symbol\n return {demangle( sym_name(sym) ), base, offset};\n }\n \/\/ function or space not found\n return {to_hex_string(addr), addr, 0};\n }\n safe_func_offset getsym_safe(Elf32_Addr addr, char* buffer, size_t length)\n {\n \/\/ probably just a null pointer with ofs=addr\n if (addr < 0x7c00) return {null_stringz, 0, addr};\n \/\/ definitely in the bootloader\n if (addr < 0x7e00) return {boot_stringz, 0x7c00, addr - 0x7c00};\n \/\/ resolve manually from symtab\n auto* sym = getaddr(addr);\n if (LIKELY(sym)) {\n auto base = sym->st_value;\n auto offset = addr - base;\n \/\/ return string name for symbol\n return {demangle_safe( sym_name(sym), buffer, length ), base, offset};\n }\n \/\/ function or space not found\n snprintf(buffer, length, \"0x%08x\", addr);\n return {buffer, addr, 0};\n }\n\n Elf32_Addr getaddr(const std::string& name)\n {\n for (size_t i = 0; i < symtab.entries; i++)\n {\n auto& sym = symtab.base[i];\n \/\/if (ELF32_ST_TYPE(sym.st_info) == STT_FUNC)\n if (demangle( sym_name(&sym) ) == name)\n return sym.st_value;\n }\n return 0;\n }\n Elf32_Sym* getaddr(Elf32_Addr addr)\n {\n for (size_t i = 0; i < symtab.entries; i++) {\n\n \/\/if (ELF32_ST_TYPE(symtab.base[i].st_info) == STT_FUNC)\n if (addr >= symtab.base[i].st_value\n && (addr < symtab.base[i].st_value + symtab.base[i].st_size))\n return &symtab.base[i];\n }\n return nullptr;\n }\n\n size_t end_of_file() const {\n auto& hdr = elf_header();\n return hdr.e_ehsize + (hdr.e_phnum * hdr.e_phentsize) + (hdr.e_shnum * hdr.e_shentsize);\n }\n\n const SymTab& get_symtab() const {\n return symtab;\n }\n\n const auto* get_strtab() const {\n return strtab;\n }\n\nprivate:\n const char* sym_name(Elf32_Sym* sym) const {\n return &strtab[sym->st_name];\n }\n std::string demangle(const char* name) const\n {\n if (name[0] == '_') {\n int status;\n \/\/ internally, demangle just returns buf when status is ok\n auto* res = __cxa_demangle(name, nullptr, 0, &status);\n if (status == 0) {\n std::string result(res);\n std::free(res);\n return result;\n }\n }\n return std::string(name);\n }\n const char* demangle_safe(const char* name, char* buffer, size_t buflen) const\n {\n int status;\n \/\/ internally, demangle just returns buf when status is ok\n auto* res = __cxa_demangle(name, (char*) buffer, &buflen, &status);\n if (status) return name;\n return res;\n }\n\n SymTab symtab;\n const char* strtab;\n};\nstatic ElfTables parser;\n\nElfTables& get_parser() {\n return parser;\n}\n\nsize_t Elf::end_of_file() {\n return get_parser().end_of_file();\n}\nconst char* Elf::get_strtab() {\n return get_parser().get_strtab();\n}\n\nfunc_offset Elf::resolve_symbol(uintptr_t addr)\n{\n return get_parser().getsym(addr);\n}\nfunc_offset Elf::resolve_symbol(void* addr)\n{\n return get_parser().getsym((uintptr_t) addr);\n}\n\nuintptr_t Elf::resolve_addr(uintptr_t addr)\n{\n auto* sym = get_parser().getaddr(addr);\n if (sym) return sym->st_value;\n return addr;\n}\nuintptr_t Elf::resolve_addr(void* addr)\n{\n auto* sym = get_parser().getaddr((uintptr_t) addr);\n if (sym) return sym->st_value;\n return (uintptr_t) addr;\n}\n\nsafe_func_offset Elf::safe_resolve_symbol(void* addr, char* buffer, size_t length)\n{\n return get_parser().getsym_safe((Elf32_Addr) addr, buffer, length);\n}\nuintptr_t Elf::resolve_name(const std::string& name)\n{\n return get_parser().getaddr(name);\n}\n\nfunc_offset Elf::get_current_function()\n{\n return resolve_symbol(__builtin_return_address(0));\n}\nstd::vector<func_offset> Elf::get_functions()\n{\n std::vector<func_offset> vec;\n #define ADD_TRACE(N, ra) \\\n vec.push_back(Elf::resolve_symbol(ra));\n\n void* ra;\n if (frp(0, ra)) {\n ADD_TRACE(0, ra);\n if (frp(1, ra)) {\n ADD_TRACE(1, ra);\n if (frp(2, ra)) {\n ADD_TRACE(2, ra);\n if (frp(3, ra)) {\n ADD_TRACE(3, ra);\n if (frp(4, ra)) {\n ADD_TRACE(4, ra);\n if (frp(5, ra)) {\n ADD_TRACE(5, ra);\n if (frp(6, ra)) {\n ADD_TRACE(6, ra);\n if (frp(7, ra)) {\n ADD_TRACE(7, ra);\n if (frp(8, ra)) {\n ADD_TRACE(8, ra);\n }}}}}}}}}\n return vec;\n}\n\nvoid print_backtrace()\n{\n char _symbol_buffer[512];\n char _btrace_buffer[512];\n\n if (Elf::get_strtab() == NULL) {\n int len = snprintf(_btrace_buffer, sizeof(_btrace_buffer),\n \"symtab or strtab is empty, indicating image may be stripped\\n\");\n write(1, _btrace_buffer, len);\n }\n\n #define PRINT_TRACE(N, ra) \\\n auto symb = Elf::safe_resolve_symbol( \\\n ra, _symbol_buffer, sizeof(_symbol_buffer)); \\\n int len = snprintf(_btrace_buffer, sizeof(_btrace_buffer),\\\n \"[%d] %8x + 0x%.3x: %s\\n\", \\\n N, symb.addr, symb.offset, symb.name);\\\n write(1, _btrace_buffer, len);\n\n printf(\"\\n\");\n void* ra;\n if (frp(0, ra)) {\n PRINT_TRACE(0, ra);\n if (frp(1, ra)) {\n PRINT_TRACE(1, ra);\n if (frp(2, ra)) {\n PRINT_TRACE(2, ra);\n if (frp(3, ra)) {\n PRINT_TRACE(3, ra);\n if (frp(4, ra)) {\n PRINT_TRACE(4, ra);\n if (frp(5, ra)) {\n PRINT_TRACE(5, ra);\n if (frp(6, ra)) {\n PRINT_TRACE(6, ra);\n if (frp(7, ra)) {\n PRINT_TRACE(7, ra);\n if (frp(8, ra)) {\n PRINT_TRACE(8, ra);\n }}}}}}}}}\n}\n\nvoid Elf::print_info()\n{\n auto& hdr = elf_header();\n \/\/ program headers\n auto* phdr = (Elf32_Phdr*) (ELF_START + hdr.e_phoff);\n printf(\"program headers offs=%#x at phys %p\\n\", hdr.e_phoff, phdr);\n \/\/ section headers\n auto* shdr = (Elf32_Shdr*) (ELF_START + hdr.e_shoff);\n printf(\"section headers offs=%#x at phys %p\\n\", hdr.e_shoff, shdr);\n for (Elf32_Half i = 0; i < hdr.e_shnum; i++)\n {\n uintptr_t start = ELF_START + shdr[i].sh_offset;\n uintptr_t end = start + shdr[i].sh_size;\n printf(\"sh from %#x to %#x\\n\", start, end);\n }\n\n}\n\nextern \"C\"\nvoid _print_elf_symbols()\n{\n const auto& symtab = parser.get_symtab();\n const char* strtab = parser.get_strtab();\n\n for (size_t i = 0; i < symtab.entries; i++)\n {\n printf(\"%8x: %s\\n\", symtab.base[i].st_value, &strtab[symtab.base[i].st_name]);\n }\n printf(\"*** %u entries\\n\", symtab.entries);\n}\nextern \"C\"\nvoid _validate_elf_symbols()\n{\n const auto& symtab = parser.get_symtab();\n const char* strtab = parser.get_strtab();\n if (symtab.entries == 0 || strtab == nullptr) return;\n\n for (size_t i = 1; i < symtab.entries; i++)\n {\n if (symtab.base[i].st_value != 0) {\n assert(symtab.base[i].st_value > 0x2000);\n const char* string = &strtab[symtab.base[i].st_name];\n assert(strlen(string));\n }\n }\n}\n\nstruct relocate_header {\n SymTab symtab;\n StrTab strtab;\n};\n\nextern \"C\"\nint _get_elf_section_size(const void* location)\n{\n auto& hdr = *(relocate_header*) location;\n return sizeof(relocate_header) + hdr.symtab.entries * sizeof(Elf32_Sym) + hdr.strtab.size;\n}\n\nextern \"C\"\nvoid _move_elf_symbols(void* old_location, void* new_location)\n{\n int size = _get_elf_section_size(old_location);\n memcpy(new_location, old_location, size);\n \/\/ update symbol info table\n auto* newhdr = (relocate_header*) new_location;\n const char* base = ((char*) newhdr) + sizeof(relocate_header);\n newhdr->symtab.base = (Elf32_Sym*) base;\n newhdr->strtab.base = &base[newhdr->symtab.entries * sizeof(Elf32_Sym)];\n}\n\n#include <malloc.h>\nextern \"C\"\nvoid* _relocate_to_heap(void* old_location)\n{\n int total = _get_elf_section_size(old_location);\n void* heap_location = malloc(total);\n\n _move_elf_symbols(old_location, heap_location);\n return heap_location;\n}\n\nextern \"C\"\nvoid _apply_parser_data(char* location)\n{\n if (location) {\n auto& hdr = *(relocate_header*) location;\n \/\/ apply changes to the symbol parser from custom location\n parser.set(hdr.symtab.base, hdr.symtab.entries, hdr.strtab.base);\n }\n else {\n \/\/ symbols and strings are stripped out\n parser.set(nullptr, 0, nullptr);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <thread>\n#include <cmath>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"Point.hpp\"\n#include \"Function.hpp\"\n#include \"SymbolicRegressionSolver.hpp\"\n#include \"Config.hpp\"\n\n#define OPTIMISE_CONFIG\n\nint amountOfSimulationsToPerform = 1;\nSymbolicRegressionSolver::Config config{};\nFunction fn{parse(\"+ 1 x\").statement, \"x\"};\nint initialPoint = -10;\nint endPoint = 10;\nint stepSize = 1;\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);\n\nvoid parseArguments(int argc, char *argv[]);\nvoid printValidFlags()\n{\n std::cout << \"-c <configuration-file> (TODO)\\n\";\n std::cout << \"-f <function>\\n\";\n std::cout << \"-i <initial-point>\\n\";\n std::cout << \"-e <end-point>\\n\";\n std::cout << \"-s <step size>\\n\";\n std::cout << \"-r <amount of times to redo simulation>\\n\";\n}\n\nstruct Result\n{\n Result(double var, double average, size_t totalSolutions) : var(var), average(average), totalSolutions(totalSolutions) { }\n double var;\n double average;\n size_t totalSolutions;\n};\n\nconstexpr const int AMOUNT_OF_THREADS = 4;\nstd::vector<Result> solutions[AMOUNT_OF_THREADS];\n\ntemplate <class T>\nvoid optimiseConfig(size_t id, const PointList& points, const T& start, const T& end, const T& step)\n{\n SymbolicRegressionSolver solver{config, points};\n auto& variableToModify = solver.config().keepPercentage;\n\n#ifdef OPTIMISE_CONFIG\n for(variableToModify = start; variableToModify <= end; variableToModify += step)\n {\n double currentAverage = 0;\n size_t totalSolutions = 0;\n#endif \/\/ OPTIMISE_CONFIG\n\n for(int i = 0; i < amountOfSimulationsToPerform; ++i)\n {\n auto solutions = solver.solve();\n\n#ifndef OPTIMISE_CONFIG\n for(auto& solution : solutions)\n {\n std::cout << solver.currentGeneration() << \",\";\n std::cout << solution.fitnessLevel << \",\";\n std::cout << solution.mutated << \",\"; \n std::cout << solution.mated << '\\n';\n }\n#else\n totalSolutions += solutions.size();\n currentAverage += solver.currentGeneration();\n#endif \/\/ OPTIMISE_CONFIG\n\n solver.reset();\n }\n \n#ifdef OPTIMISE_CONFIG\n\t\tcurrentAverage \/= amountOfSimulationsToPerform;\n\n solutions[id].emplace_back(variableToModify, currentAverage, totalSolutions);\n }\n#endif \/\/ OPTIMISE_CONFIG\n}\n\nint main(int argc, char *argv[])\n{\n parseArguments(argc, argv);\n\n#ifdef VERBOSE_LOG\n std::clog << \"function: \" << fn << '\\n';\n std::clog << \"initial point: \" << initialPoint << '\\n';\n std::clog << \"end point: \" << endPoint << '\\n';\n std::clog << \"step size: \" << stepSize << '\\n';\n#endif \/\/ VERBOSE_LOG\n\n std::vector<Point> points;\n points.reserve((endPoint - initialPoint)\/stepSize);\n\n VariableMap map;\n for(int i = initialPoint; i <= endPoint; i += stepSize)\n {\n points.emplace_back(i, fn(map, i));\n }\n\n std::vector<std::thread> threads;\n for(int i = 0; i < AMOUNT_OF_THREADS; ++i)\n {\n constexpr double STEP_SIZE = 0.01;\n double start = i * 1.0 \/ AMOUNT_OF_THREADS;\n double end = (i + 1) * 1.0 \/ AMOUNT_OF_THREADS;\n \n threads.emplace_back([=]() { optimiseConfig(i, points, start, end, STEP_SIZE); } );\n }\n\n for(auto& t : threads)\n {\n t.join();\n }\n\n std::vector<Result> sols;\n for(auto& sol : solutions)\n {\n \/\/std::cout << \"size of sol is: \" << sol.size() << '\\n';\n sols.insert(sols.end(), sol.begin(), sol.end());\n }\n std::sort(sols.begin(), sols.end(), [](const Result& r1, const Result& r2) { return r1.var < r2.var; });\n\n for(auto& sol : sols)\n {\n std::cout << sol.var << \", \" << sol.average << \", \" << sol.totalSolutions << '\\n';\n }\n\n return 0;\n}\n\n\nvoid parseArguments(int argc, char *argv[])\n{\n for(int i = 1; i < argc; ++i)\n {\n auto command = argv[i];\n auto commandSize = strlen(command);\n if(command[0] != '-')\n {\n std::cout << \"Invalid format: \" << command << \".\\n\";\n std::cout << \"Flags must be prefixed with \\\"-\\\" (without quotes).\\n\";\n std::exit(-2);\n break;\n }\n\n if(commandSize == 1 || commandSize > 2)\n {\n std::cout << \"Invalid flag: \\\"\" << command << \"\\\"\\n\";\n printValidFlags();\n std::exit(-5);\n }\n\n if(i + 1 >= argc)\n {\n std::cout << \"please provide info with a flag...\\n\";\n printValidFlags();\n std::exit(-6);\n }\n\n switch(command[1])\n {\n \/\/ assign function\n case 'f':\n {\n std::string functionAsString;\n for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)\n {\n functionAsString += argv[j];\n }\n fn = parse(functionAsString).statement;\n }\n break;\n case 'i':\n {\n std::string str = argv[++i];\n initialPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 'e':\n {\n std::string str = argv[++i];\n endPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 's':\n {\n std::string str = argv[++i];\n stepSize = boost::lexical_cast<int>(str);\n }\n break;\n case 'r':\n {\n std::string str = argv[++i];\n amountOfSimulationsToPerform = boost::lexical_cast<int>(str);\n }\n break;\n case 'c':\n {\n try \n {\n std::string filepath = argv[++i];\n std::ifstream file;\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.open(filepath);\n file >> config; \/\/ read the config\n } \n catch(boost::bad_lexical_cast& e)\n {\n std::cerr << e.what();\n std::exit(5);\n }\n catch(std::exception& e)\n {\n std::cerr << e.what();\n std::exit(6);\n }\n }\n break;\n default:\n std::cout << \"Invalid flag\\n\";\n printValidFlags();\n std::exit(-4);\n break;\n }\n }\n}\n\nnamespace \n{\nstd::string obtainValue(const std::string& line)\n{\n return std::string(line.begin() + line.find_last_of('=') + 1, line.end());\n}\n\ntemplate <class T>\nvoid read(std::string& buffer, std::istream& is, T& value)\n{\n std::getline(is, buffer);\n auto stringValue = obtainValue(buffer);\n stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());\n value = boost::lexical_cast<T>(stringValue);\n}\n}\n\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)\n{\n std::string buffer;\n\n read(buffer, is, config.initialPopulation);\n read(buffer, is, config.maxGenerations);\n read(buffer, is, config.initialMaxDepth);\n read(buffer, is, config.maxSolutionDepth);\n read(buffer, is, config.keepPercentage);\n read(buffer, is, config.mutationPercent);\n read(buffer, is, config.matePercent);\n\n\n \/\/ have to do this separately for const dist\n int a, b;\n read(buffer, is, a);\n read(buffer, is, b);\n\n config.constantDist = decltype(config.constantDist){a, b};\n\n read(buffer, is, config.solutionCriterea);\n read(buffer, is, config.chanceToChangeConstant);\n read(buffer, is, config.chanceToChangeVar);\n \n int nearestNeighbour = 0;\n read(buffer, is, nearestNeighbour);\n config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);\n\n read(buffer, is, config.chanceToUseNearestNeighbour);\n read(buffer, is, config.stepSize);\n \n int refillOption = 0;\n read(buffer, is, refillOption);\n config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);\n \n return is;\n}\n<commit_msg>Add MUTATE_MATE macro which does mutation\/mating optimisation as a pair<commit_after>#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <thread>\n#include <cmath>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"Point.hpp\"\n#include \"Function.hpp\"\n#include \"SymbolicRegressionSolver.hpp\"\n#include \"Config.hpp\"\n\n#define OPTIMISE_CONFIG\n\nint amountOfSimulationsToPerform = 1;\nSymbolicRegressionSolver::Config config{};\nFunction fn{parse(\"+ 1 x\").statement, \"x\"};\nint initialPoint = -10;\nint endPoint = 10;\nint stepSize = 1;\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);\n\nvoid parseArguments(int argc, char *argv[]);\nvoid printValidFlags()\n{\n std::cout << \"-c <configuration-file> (TODO)\\n\";\n std::cout << \"-f <function>\\n\";\n std::cout << \"-i <initial-point>\\n\";\n std::cout << \"-e <end-point>\\n\";\n std::cout << \"-s <step size>\\n\";\n std::cout << \"-r <amount of times to redo simulation>\\n\";\n}\n\n#define MUTATE_MATE\n\nstruct Result\n{\n Result(double var, double average, size_t totalSolutions) : var(var), average(average), totalSolutions(totalSolutions) { }\n Result(double var, double var2, double average, size_t totalSolutions) : var(var), var2(var2), average(average), totalSolutions(totalSolutions) { }\n double var;\n double var2;\n double average;\n size_t totalSolutions;\n};\n\nconstexpr const int AMOUNT_OF_THREADS = 4;\nstd::vector<Result> solutions[AMOUNT_OF_THREADS];\n\n\ntemplate <class T>\nvoid optimiseConfig(size_t id, const PointList& points, const T& start, const T& end, const T& step)\n{\n SymbolicRegressionSolver solver{config, points};\n#ifndef MUTATE_MATE\n auto& variableToModify = solver.config().keepPercentage;\n#else\n auto& variableToModify = solver.config().matePercent;\n#endif\n\n#ifdef OPTIMISE_CONFIG\n#ifdef MUTATE_MATE\n auto& var2 = solver.config().mutationPercent;\n for(var2 = start; var2 <= end; var2 += step)\n#endif\n#ifndef MUTATE_MATE\n for(variableToModify = start; variableToModify <= end; variableToModify += step)\n#else\n for(variableToModify = 0; variableToModify <= 1; variableToModify += step)\n#endif\n {\n double currentAverage = 0;\n size_t totalSolutions = 0;\n#endif \/\/ OPTIMISE_CONFIG\n\n for(int i = 0; i < amountOfSimulationsToPerform; ++i)\n {\n auto solutions = solver.solve();\n\n#ifndef OPTIMISE_CONFIG\n for(auto& solution : solutions)\n {\n std::cout << solver.currentGeneration() << \",\";\n std::cout << solution.fitnessLevel << \",\";\n std::cout << solution.mutated << \",\"; \n std::cout << solution.mated << '\\n';\n }\n#else\n totalSolutions += solutions.size();\n currentAverage += solver.currentGeneration();\n#endif \/\/ OPTIMISE_CONFIG\n\n solver.reset();\n }\n \n#ifdef OPTIMISE_CONFIG\n\t\tcurrentAverage \/= amountOfSimulationsToPerform;\n\n#ifndef MUTATE_MATE\n solutions[id].emplace_back(variableToModify, currentAverage, totalSolutions);\n#else\n solutions[id].emplace_back(var2, variableToModify, currentAverage, totalSolutions);\n#endif \n }\n#endif \/\/ OPTIMISE_CONFIG\n}\n\n\nint main(int argc, char *argv[])\n{\n parseArguments(argc, argv);\n\n#ifdef VERBOSE_LOG\n std::clog << \"function: \" << fn << '\\n';\n std::clog << \"initial point: \" << initialPoint << '\\n';\n std::clog << \"end point: \" << endPoint << '\\n';\n std::clog << \"step size: \" << stepSize << '\\n';\n#endif \/\/ VERBOSE_LOG\n\n std::vector<Point> points;\n points.reserve((endPoint - initialPoint)\/stepSize);\n\n VariableMap map;\n for(int i = initialPoint; i <= endPoint; i += stepSize)\n {\n points.emplace_back(i, fn(map, i));\n }\n\n std::vector<std::thread> threads;\n for(int i = 0; i < AMOUNT_OF_THREADS; ++i)\n {\n constexpr double STEP_SIZE = 0.05;\n double start = i * 1.0 \/ AMOUNT_OF_THREADS;\n double end = (i + 1) * 1.0 \/ AMOUNT_OF_THREADS;\n \n threads.emplace_back([=]() { optimiseConfig(i, points, start, end, STEP_SIZE); } );\n }\n\n for(auto& t : threads)\n {\n t.join();\n }\n\n std::vector<Result> sols;\n for(auto& sol : solutions)\n {\n \/\/std::cout << \"size of sol is: \" << sol.size() << '\\n';\n sols.insert(sols.end(), sol.begin(), sol.end());\n }\n std::sort(sols.begin(), sols.end(), [](const Result& r1, const Result& r2) { return r1.var < r2.var; });\n\n for(auto& sol : sols)\n {\n#ifndef MUTATE_MATE\n std::cout << sol.var << \", \" << sol.average << \", \" << sol.totalSolutions << '\\n';\n#else\n std::cout << sol.var << \", \" << sol.var2 << \", \" << sol.average << \", \" << sol.totalSolutions << '\\n';\n#endif \/\/ MUTATE_MATE\n }\n\n return 0;\n}\n\n\nvoid parseArguments(int argc, char *argv[])\n{\n for(int i = 1; i < argc; ++i)\n {\n auto command = argv[i];\n auto commandSize = strlen(command);\n if(command[0] != '-')\n {\n std::cout << \"Invalid format: \" << command << \".\\n\";\n std::cout << \"Flags must be prefixed with \\\"-\\\" (without quotes).\\n\";\n std::exit(-2);\n break;\n }\n\n if(commandSize == 1 || commandSize > 2)\n {\n std::cout << \"Invalid flag: \\\"\" << command << \"\\\"\\n\";\n printValidFlags();\n std::exit(-5);\n }\n\n if(i + 1 >= argc)\n {\n std::cout << \"please provide info with a flag...\\n\";\n printValidFlags();\n std::exit(-6);\n }\n\n switch(command[1])\n {\n \/\/ assign function\n case 'f':\n {\n std::string functionAsString;\n for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)\n {\n functionAsString += argv[j];\n }\n fn = parse(functionAsString).statement;\n }\n break;\n case 'i':\n {\n std::string str = argv[++i];\n initialPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 'e':\n {\n std::string str = argv[++i];\n endPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 's':\n {\n std::string str = argv[++i];\n stepSize = boost::lexical_cast<int>(str);\n }\n break;\n case 'r':\n {\n std::string str = argv[++i];\n amountOfSimulationsToPerform = boost::lexical_cast<int>(str);\n }\n break;\n case 'c':\n {\n try \n {\n std::string filepath = argv[++i];\n std::ifstream file;\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.open(filepath);\n file >> config; \/\/ read the config\n } \n catch(boost::bad_lexical_cast& e)\n {\n std::cerr << e.what();\n std::exit(5);\n }\n catch(std::exception& e)\n {\n std::cerr << e.what();\n std::exit(6);\n }\n }\n break;\n default:\n std::cout << \"Invalid flag\\n\";\n printValidFlags();\n std::exit(-4);\n break;\n }\n }\n}\n\nnamespace \n{\nstd::string obtainValue(const std::string& line)\n{\n return std::string(line.begin() + line.find_last_of('=') + 1, line.end());\n}\n\ntemplate <class T>\nvoid read(std::string& buffer, std::istream& is, T& value)\n{\n std::getline(is, buffer);\n auto stringValue = obtainValue(buffer);\n stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());\n value = boost::lexical_cast<T>(stringValue);\n}\n}\n\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)\n{\n std::string buffer;\n\n read(buffer, is, config.initialPopulation);\n read(buffer, is, config.maxGenerations);\n read(buffer, is, config.initialMaxDepth);\n read(buffer, is, config.maxSolutionDepth);\n read(buffer, is, config.keepPercentage);\n read(buffer, is, config.mutationPercent);\n read(buffer, is, config.matePercent);\n\n\n \/\/ have to do this separately for const dist\n int a, b;\n read(buffer, is, a);\n read(buffer, is, b);\n\n config.constantDist = decltype(config.constantDist){a, b};\n\n read(buffer, is, config.solutionCriterea);\n read(buffer, is, config.chanceToChangeConstant);\n read(buffer, is, config.chanceToChangeVar);\n \n int nearestNeighbour = 0;\n read(buffer, is, nearestNeighbour);\n config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);\n\n read(buffer, is, config.chanceToUseNearestNeighbour);\n read(buffer, is, config.stepSize);\n \n int refillOption = 0;\n read(buffer, is, refillOption);\n config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);\n \n return is;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Collection_inl_\n#define _Stroika_Foundation_Containers_Collection_inl_\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#include \"..\/Debug\/Assertions.h\"\n\n#include \"Factory\/Collection_Factory.h\"\n\nnamespace Stroika::Foundation::Containers {\n\n \/*\n ********************************************************************************\n ******************************** Collection<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Collection<T>::Collection ()\n : inherited (Factory::Collection_Factory<T>{}())\n {\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE>\n inline Collection<T>::Collection (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end)\n : Collection{}\n {\n AddAll (start, end);\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (const _CollectionRepSharedPtr& src) noexcept\n : inherited{src}\n {\n RequireNotNull (src);\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (_CollectionRepSharedPtr&& src) noexcept\n : inherited (RequireNotNull (src), move (src)))\n {\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (const initializer_list<T>& src)\n : Collection{}\n {\n AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterableOfT_v<CONTAINER_OF_ADDABLE, T> and not is_base_of_v<Collection<T>, Configuration::remove_cvref_t<CONTAINER_OF_ADDABLE>>>*>\n inline Collection<T>::Collection (CONTAINER_OF_ADDABLE&& src)\n : Collection{}\n {\n AddAll (forward<CONTAINER_OF_ADDABLE> (src));\n _AssertRepValidType ();\n }\n#if qDebug\n template <typename T>\n Collection<T>::~Collection ()\n {\n if (this->_GetSharingState () != Memory::SharedByValue_State::eNull) {\n \/\/ SharingState can be NULL because of MOVE semantics\n _SafeReadRepAccessor<_IRep>{this}._ConstGetRep ().AssertNoIteratorsReferenceOwner (this);\n }\n }\n#endif\n template <typename T>\n template <typename EQUALS_COMPARER>\n bool Collection<T>::Contains (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer) const\n {\n for (auto&& i : *this) {\n if (equalsComparer (i, item)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE>\n void Collection<T>::AddAll (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end)\n {\n _SafeReadWriteRepAccessor<_IRep> tmp{this};\n for (auto&& i = start; i != end; ++i) {\n tmp._GetWriteableRep ().Add (*i);\n }\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterableOfT_v<CONTAINER_OF_ADDABLE, T>>*>\n inline void Collection<T>::AddAll (CONTAINER_OF_ADDABLE&& c)\n {\n \/*\n * Because adding items to a Collection COULD result in those items appearing in a running iterator,\n * for the corner case of s.AddAll(s) - we want to assure we don't infinite loop.\n *\/\n if (static_cast<const void*> (this) == static_cast<const void*> (addressof (c))) {\n CONTAINER_OF_ADDABLE tmp = c;\n AddAll (std::begin (tmp), std::end (tmp));\n }\n else {\n AddAll (std::begin (c), std::end (c));\n }\n }\n template <typename T>\n inline void Collection<T>::Add (ArgByValueType<T> item)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Add (item);\n Ensure (not this->IsEmpty ());\n }\n template <typename T>\n inline void Collection<T>::Update (const Iterator<T>& i, ArgByValueType<T> newValue)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Update (i, newValue);\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n inline void Collection<T>::Remove (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer)\n {\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (equalsComparer (*i, item)) {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Remove (i);\n return;\n }\n }\n }\n template <typename T>\n inline void Collection<T>::RemoveAll ()\n {\n _SafeReadWriteRepAccessor<_IRep> tmp{this};\n if (not tmp._ConstGetRep ().IsEmpty ()) {\n tmp._UpdateRep (tmp._ConstGetRep ().CloneEmpty (this));\n }\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE, typename EQUALS_COMPARER>\n void Collection<T>::RemoveAll (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end, const EQUALS_COMPARER& equalsComparer)\n {\n for (auto i = start; i != end; ++i) {\n Remove (*i, equalsComparer);\n }\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, typename EQUALS_COMPARER>\n inline void Collection<T>::RemoveAll (const CONTAINER_OF_ADDABLE& c, const EQUALS_COMPARER& equalsComparer)\n {\n if (static_cast<const void*> (this) == static_cast<const void*> (addressof (c))) {\n RemoveAll (equalsComparer);\n }\n else {\n RemoveAll (std::begin (c), std::end (c), equalsComparer);\n }\n }\n template <typename T>\n template <typename PREDICATE>\n nonvirtual size_t Collection<T>::RemoveAll (const PREDICATE& p)\n {\n size_t nRemoved{};\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (p (*i)) {\n Remove (i);\n nRemoved++;\n }\n }\n return nRemoved;\n }\n template <typename T>\n inline void Collection<T>::Remove (const Iterator<T>& i)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Remove (i);\n }\n template <typename T>\n template <typename PREDICATE>\n nonvirtual bool Collection<T>::Remove (const PREDICATE& p)\n {\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (p (*i)) {\n Remove (i);\n return true;\n }\n }\n return false;\n }\n template <typename T>\n inline void Collection<T>::clear ()\n {\n RemoveAll ();\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n inline void Collection<T>::erase (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer)\n {\n Remove (item, equalsComparer);\n }\n template <typename T>\n inline void Collection<T>::erase (const Iterator<T>& i)\n {\n Remove (i);\n }\n template <typename T>\n inline Collection<T> Collection<T>::Where (const function<bool (ArgByValueType<T>)>& doToElement) const\n {\n return Iterable<T>::Where (doToElement, Collection<T>{});\n }\n template <typename T>\n inline Collection<T>& Collection<T>::operator+= (ArgByValueType<T> item)\n {\n Add (item);\n return *this;\n }\n template <typename T>\n inline Collection<T>& Collection<T>::operator+= (const Iterable<T>& items)\n {\n AddAll (items);\n return *this;\n }\n template <typename T>\n inline void Collection<T>::_AssertRepValidType () const\n {\n#if qDebug\n _SafeReadRepAccessor<_IRep>{this};\n#endif\n }\n\n \/*\n ********************************************************************************\n ********************************* operator+ ************************************\n ********************************************************************************\n *\/\n template <typename T>\n Collection<T> operator+ (const Iterable<T>& lhs, const Collection<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n template <typename T>\n Collection<T> operator+ (const Collection<T>& lhs, const Iterable<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n template <typename T>\n Collection<T> operator+ (const Collection<T>& lhs, const Collection<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Collection_inl_ *\/\n<commit_msg>fixed typo<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_Collection_inl_\n#define _Stroika_Foundation_Containers_Collection_inl_\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#include \"..\/Debug\/Assertions.h\"\n\n#include \"Factory\/Collection_Factory.h\"\n\nnamespace Stroika::Foundation::Containers {\n\n \/*\n ********************************************************************************\n ******************************** Collection<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Collection<T>::Collection ()\n : inherited (Factory::Collection_Factory<T>{}())\n {\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE>\n inline Collection<T>::Collection (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end)\n : Collection{}\n {\n AddAll (start, end);\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (const _CollectionRepSharedPtr& src) noexcept\n : inherited{src}\n {\n RequireNotNull (src);\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (_CollectionRepSharedPtr&& src) noexcept\n : inherited ((RequireNotNull (src), move (src)))\n {\n _AssertRepValidType ();\n }\n template <typename T>\n inline Collection<T>::Collection (const initializer_list<T>& src)\n : Collection{}\n {\n AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterableOfT_v<CONTAINER_OF_ADDABLE, T> and not is_base_of_v<Collection<T>, Configuration::remove_cvref_t<CONTAINER_OF_ADDABLE>>>*>\n inline Collection<T>::Collection (CONTAINER_OF_ADDABLE&& src)\n : Collection{}\n {\n AddAll (forward<CONTAINER_OF_ADDABLE> (src));\n _AssertRepValidType ();\n }\n#if qDebug\n template <typename T>\n Collection<T>::~Collection ()\n {\n if (this->_GetSharingState () != Memory::SharedByValue_State::eNull) {\n \/\/ SharingState can be NULL because of MOVE semantics\n _SafeReadRepAccessor<_IRep>{this}._ConstGetRep ().AssertNoIteratorsReferenceOwner (this);\n }\n }\n#endif\n template <typename T>\n template <typename EQUALS_COMPARER>\n bool Collection<T>::Contains (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer) const\n {\n for (auto&& i : *this) {\n if (equalsComparer (i, item)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE>\n void Collection<T>::AddAll (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end)\n {\n _SafeReadWriteRepAccessor<_IRep> tmp{this};\n for (auto&& i = start; i != end; ++i) {\n tmp._GetWriteableRep ().Add (*i);\n }\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterableOfT_v<CONTAINER_OF_ADDABLE, T>>*>\n inline void Collection<T>::AddAll (CONTAINER_OF_ADDABLE&& c)\n {\n \/*\n * Because adding items to a Collection COULD result in those items appearing in a running iterator,\n * for the corner case of s.AddAll(s) - we want to assure we don't infinite loop.\n *\/\n if (static_cast<const void*> (this) == static_cast<const void*> (addressof (c))) {\n CONTAINER_OF_ADDABLE tmp = c;\n AddAll (std::begin (tmp), std::end (tmp));\n }\n else {\n AddAll (std::begin (c), std::end (c));\n }\n }\n template <typename T>\n inline void Collection<T>::Add (ArgByValueType<T> item)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Add (item);\n Ensure (not this->IsEmpty ());\n }\n template <typename T>\n inline void Collection<T>::Update (const Iterator<T>& i, ArgByValueType<T> newValue)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Update (i, newValue);\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n inline void Collection<T>::Remove (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer)\n {\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (equalsComparer (*i, item)) {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Remove (i);\n return;\n }\n }\n }\n template <typename T>\n inline void Collection<T>::RemoveAll ()\n {\n _SafeReadWriteRepAccessor<_IRep> tmp{this};\n if (not tmp._ConstGetRep ().IsEmpty ()) {\n tmp._UpdateRep (tmp._ConstGetRep ().CloneEmpty (this));\n }\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_ADDABLE, typename EQUALS_COMPARER>\n void Collection<T>::RemoveAll (COPY_FROM_ITERATOR_OF_ADDABLE start, COPY_FROM_ITERATOR_OF_ADDABLE end, const EQUALS_COMPARER& equalsComparer)\n {\n for (auto i = start; i != end; ++i) {\n Remove (*i, equalsComparer);\n }\n }\n template <typename T>\n template <typename CONTAINER_OF_ADDABLE, typename EQUALS_COMPARER>\n inline void Collection<T>::RemoveAll (const CONTAINER_OF_ADDABLE& c, const EQUALS_COMPARER& equalsComparer)\n {\n if (static_cast<const void*> (this) == static_cast<const void*> (addressof (c))) {\n RemoveAll (equalsComparer);\n }\n else {\n RemoveAll (std::begin (c), std::end (c), equalsComparer);\n }\n }\n template <typename T>\n template <typename PREDICATE>\n nonvirtual size_t Collection<T>::RemoveAll (const PREDICATE& p)\n {\n size_t nRemoved{};\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (p (*i)) {\n Remove (i);\n nRemoved++;\n }\n }\n return nRemoved;\n }\n template <typename T>\n inline void Collection<T>::Remove (const Iterator<T>& i)\n {\n _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().Remove (i);\n }\n template <typename T>\n template <typename PREDICATE>\n nonvirtual bool Collection<T>::Remove (const PREDICATE& p)\n {\n for (Iterator<T> i = this->begin (); i != this->end (); ++i) {\n if (p (*i)) {\n Remove (i);\n return true;\n }\n }\n return false;\n }\n template <typename T>\n inline void Collection<T>::clear ()\n {\n RemoveAll ();\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n inline void Collection<T>::erase (ArgByValueType<T> item, const EQUALS_COMPARER& equalsComparer)\n {\n Remove (item, equalsComparer);\n }\n template <typename T>\n inline void Collection<T>::erase (const Iterator<T>& i)\n {\n Remove (i);\n }\n template <typename T>\n inline Collection<T> Collection<T>::Where (const function<bool (ArgByValueType<T>)>& doToElement) const\n {\n return Iterable<T>::Where (doToElement, Collection<T>{});\n }\n template <typename T>\n inline Collection<T>& Collection<T>::operator+= (ArgByValueType<T> item)\n {\n Add (item);\n return *this;\n }\n template <typename T>\n inline Collection<T>& Collection<T>::operator+= (const Iterable<T>& items)\n {\n AddAll (items);\n return *this;\n }\n template <typename T>\n inline void Collection<T>::_AssertRepValidType () const\n {\n#if qDebug\n _SafeReadRepAccessor<_IRep>{this};\n#endif\n }\n\n \/*\n ********************************************************************************\n ********************************* operator+ ************************************\n ********************************************************************************\n *\/\n template <typename T>\n Collection<T> operator+ (const Iterable<T>& lhs, const Collection<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n template <typename T>\n Collection<T> operator+ (const Collection<T>& lhs, const Iterable<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n template <typename T>\n Collection<T> operator+ (const Collection<T>& lhs, const Collection<T>& rhs)\n {\n Collection<T> result{lhs};\n result += rhs;\n return result;\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Collection_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"coins.h\"\n\n#include \"random.h\"\n\n#include <assert.h>\n\n\/**\n * calculate number of bytes for the bitmask, and its number of non-zero bytes\n * each bit in the bitmask represents the availability of one output, but the\n * availabilities of the first two outputs are encoded separately\n *\/\nvoid CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {\n unsigned int nLastUsedByte = 0;\n for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {\n bool fZero = true;\n for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {\n if (!vout[2+b*8+i].IsNull()) {\n fZero = false;\n continue;\n }\n }\n if (!fZero) {\n nLastUsedByte = b + 1;\n nNonzeroBytes++;\n }\n }\n nBytes += nLastUsedByte;\n}\n\nbool CCoins::Spend(const COutPoint &out, CTxInUndo &undo) {\n if (out.n >= vout.size())\n return false;\n if (vout[out.n].IsNull())\n return false;\n undo = CTxInUndo(vout[out.n]);\n vout[out.n].SetNull();\n Cleanup();\n if (vout.size() == 0) {\n undo.nHeight = nHeight;\n undo.fCoinBase = fCoinBase;\n undo.nVersion = this->nVersion;\n }\n return true;\n}\n\nbool CCoins::Spend(int nPos) {\n CTxInUndo undo;\n COutPoint out(0, nPos);\n return Spend(out, undo);\n}\n\n\nbool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }\nbool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }\nuint256 CCoinsView::GetBestBlock() const { return uint256(0); }\nbool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }\nbool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }\n\n\nCCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }\nbool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }\nbool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }\nuint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }\nvoid CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }\nbool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }\nbool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }\n\nCCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}\n\nCCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), hashBlock(0) { }\n\nCCoinsViewCache::~CCoinsViewCache()\n{\n assert(!hasModifier);\n}\n\nCCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {\n CCoinsMap::iterator it = cacheCoins.find(txid);\n if (it != cacheCoins.end())\n return it;\n CCoins tmp;\n if (!base->GetCoins(txid, tmp))\n return cacheCoins.end();\n CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;\n tmp.swap(ret->second.coins);\n if (ret->second.coins.IsPruned()) {\n \/\/ The parent only has an empty entry for this txid; we can consider our\n \/\/ version as fresh.\n ret->second.flags = CCoinsCacheEntry::FRESH;\n }\n return ret;\n}\n\nbool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n if (it != cacheCoins.end()) {\n coins = it->second.coins;\n return true;\n }\n return false;\n}\n\nCCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {\n assert(!hasModifier);\n std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));\n if (ret.second) {\n if (!base->GetCoins(txid, ret.first->second.coins)) {\n \/\/ The parent view does not have this entry; mark it as fresh.\n ret.first->second.coins.Clear();\n ret.first->second.flags = CCoinsCacheEntry::FRESH;\n } else if (ret.first->second.coins.IsPruned()) {\n \/\/ The parent view only has a pruned entry for this; mark it as fresh.\n ret.first->second.flags = CCoinsCacheEntry::FRESH;\n }\n }\n \/\/ Assume that whenever ModifyCoins is called, the entry will be modified.\n ret.first->second.flags |= CCoinsCacheEntry::DIRTY;\n return CCoinsModifier(*this, ret.first);\n}\n\nconst CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n if (it == cacheCoins.end()) {\n return NULL;\n } else {\n return &it->second.coins;\n }\n}\n\nbool CCoinsViewCache::HaveCoins(const uint256 &txid) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n \/\/ We're using vtx.empty() instead of IsPruned here for performance reasons,\n \/\/ as we only care about the case where a transaction was replaced entirely\n \/\/ in a reorganization (which wipes vout entirely, as opposed to spending\n \/\/ which just cleans individual outputs).\n return (it != cacheCoins.end() && !it->second.coins.vout.empty());\n}\n\nuint256 CCoinsViewCache::GetBestBlock() const {\n if (hashBlock == uint256(0))\n hashBlock = base->GetBestBlock();\n return hashBlock;\n}\n\nvoid CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {\n hashBlock = hashBlockIn;\n}\n\nbool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {\n assert(!hasModifier);\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {\n if (it->second.flags & CCoinsCacheEntry::DIRTY) { \/\/ Ignore non-dirty entries (optimization).\n CCoinsMap::iterator itUs = cacheCoins.find(it->first);\n if (itUs == cacheCoins.end()) {\n if (!it->second.coins.IsPruned()) {\n \/\/ The parent cache does not have an entry, while the child\n \/\/ cache does have (a non-pruned) one. Move the data up, and\n \/\/ mark it as fresh (if the grandparent did have it, we\n \/\/ would have pulled it in at first GetCoins).\n assert(it->second.flags & CCoinsCacheEntry::FRESH);\n CCoinsCacheEntry& entry = cacheCoins[it->first];\n entry.coins.swap(it->second.coins);\n entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;\n }\n } else {\n if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {\n \/\/ The grandparent does not have an entry, and the child is\n \/\/ modified and being pruned. This means we can just delete\n \/\/ it from the parent.\n cacheCoins.erase(itUs);\n } else {\n \/\/ A normal modification.\n itUs->second.coins.swap(it->second.coins);\n itUs->second.flags |= CCoinsCacheEntry::DIRTY;\n }\n }\n }\n CCoinsMap::iterator itOld = it++;\n mapCoins.erase(itOld);\n }\n hashBlock = hashBlockIn;\n return true;\n}\n\nbool CCoinsViewCache::Flush() {\n bool fOk = base->BatchWrite(cacheCoins, hashBlock);\n cacheCoins.clear();\n return fOk;\n}\n\nunsigned int CCoinsViewCache::GetCacheSize() const {\n return cacheCoins.size();\n}\n\nconst CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const\n{\n const CCoins* coins = AccessCoins(input.prevout.hash);\n assert(coins && coins->IsAvailable(input.prevout.n));\n return coins->vout[input.prevout.n];\n}\n\nCAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const\n{\n if (tx.IsCoinBase())\n return 0;\n\n CAmount nResult = 0;\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n nResult += GetOutputFor(tx.vin[i]).nValue;\n\n return nResult;\n}\n\nbool CCoinsViewCache::HaveInputs(const CTransaction& tx) const\n{\n if (!tx.IsCoinBase()) {\n for (unsigned int i = 0; i < tx.vin.size(); i++) {\n const COutPoint &prevout = tx.vin[i].prevout;\n const CCoins* coins = AccessCoins(prevout.hash);\n if (!coins || !coins->IsAvailable(prevout.n)) {\n return false;\n }\n }\n }\n return true;\n}\n\ndouble CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const\n{\n if (tx.IsCoinBase())\n return 0.0;\n double dResult = 0.0;\n BOOST_FOREACH(const CTxIn& txin, tx.vin)\n {\n const CCoins* coins = AccessCoins(txin.prevout.hash);\n assert(coins);\n if (!coins->IsAvailable(txin.prevout.n)) continue;\n if (coins->nHeight < nHeight) {\n dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);\n }\n }\n return tx.ComputePriority(dResult);\n}\n\nCCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_) : cache(cache_), it(it_) {\n assert(!cache.hasModifier);\n cache.hasModifier = true;\n}\n\nCCoinsModifier::~CCoinsModifier()\n{\n assert(cache.hasModifier);\n cache.hasModifier = false;\n it->second.coins.Cleanup();\n if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {\n cache.cacheCoins.erase(it);\n }\n}\n<commit_msg>Fix relaypriority calculation error Author: maiiz <maiiz@users.noreply.github.com> Github-Issue: https:\/\/github.com\/litecoin-project\/litecoin\/issues\/247 Rebased-From: 94a34a5d951cee59ef9c9274c5ad49ac2a91ab8a<commit_after>\/\/ Copyright (c) 2012-2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"coins.h\"\n\n#include \"random.h\"\n\n#include <assert.h>\n\n\/**\n * calculate number of bytes for the bitmask, and its number of non-zero bytes\n * each bit in the bitmask represents the availability of one output, but the\n * availabilities of the first two outputs are encoded separately\n *\/\nvoid CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {\n unsigned int nLastUsedByte = 0;\n for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {\n bool fZero = true;\n for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {\n if (!vout[2+b*8+i].IsNull()) {\n fZero = false;\n continue;\n }\n }\n if (!fZero) {\n nLastUsedByte = b + 1;\n nNonzeroBytes++;\n }\n }\n nBytes += nLastUsedByte;\n}\n\nbool CCoins::Spend(const COutPoint &out, CTxInUndo &undo) {\n if (out.n >= vout.size())\n return false;\n if (vout[out.n].IsNull())\n return false;\n undo = CTxInUndo(vout[out.n]);\n vout[out.n].SetNull();\n Cleanup();\n if (vout.size() == 0) {\n undo.nHeight = nHeight;\n undo.fCoinBase = fCoinBase;\n undo.nVersion = this->nVersion;\n }\n return true;\n}\n\nbool CCoins::Spend(int nPos) {\n CTxInUndo undo;\n COutPoint out(0, nPos);\n return Spend(out, undo);\n}\n\n\nbool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }\nbool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }\nuint256 CCoinsView::GetBestBlock() const { return uint256(0); }\nbool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }\nbool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }\n\n\nCCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }\nbool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }\nbool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }\nuint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }\nvoid CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }\nbool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }\nbool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }\n\nCCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}\n\nCCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), hashBlock(0) { }\n\nCCoinsViewCache::~CCoinsViewCache()\n{\n assert(!hasModifier);\n}\n\nCCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {\n CCoinsMap::iterator it = cacheCoins.find(txid);\n if (it != cacheCoins.end())\n return it;\n CCoins tmp;\n if (!base->GetCoins(txid, tmp))\n return cacheCoins.end();\n CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;\n tmp.swap(ret->second.coins);\n if (ret->second.coins.IsPruned()) {\n \/\/ The parent only has an empty entry for this txid; we can consider our\n \/\/ version as fresh.\n ret->second.flags = CCoinsCacheEntry::FRESH;\n }\n return ret;\n}\n\nbool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n if (it != cacheCoins.end()) {\n coins = it->second.coins;\n return true;\n }\n return false;\n}\n\nCCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {\n assert(!hasModifier);\n std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));\n if (ret.second) {\n if (!base->GetCoins(txid, ret.first->second.coins)) {\n \/\/ The parent view does not have this entry; mark it as fresh.\n ret.first->second.coins.Clear();\n ret.first->second.flags = CCoinsCacheEntry::FRESH;\n } else if (ret.first->second.coins.IsPruned()) {\n \/\/ The parent view only has a pruned entry for this; mark it as fresh.\n ret.first->second.flags = CCoinsCacheEntry::FRESH;\n }\n }\n \/\/ Assume that whenever ModifyCoins is called, the entry will be modified.\n ret.first->second.flags |= CCoinsCacheEntry::DIRTY;\n return CCoinsModifier(*this, ret.first);\n}\n\nconst CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n if (it == cacheCoins.end()) {\n return NULL;\n } else {\n return &it->second.coins;\n }\n}\n\nbool CCoinsViewCache::HaveCoins(const uint256 &txid) const {\n CCoinsMap::const_iterator it = FetchCoins(txid);\n \/\/ We're using vtx.empty() instead of IsPruned here for performance reasons,\n \/\/ as we only care about the case where a transaction was replaced entirely\n \/\/ in a reorganization (which wipes vout entirely, as opposed to spending\n \/\/ which just cleans individual outputs).\n return (it != cacheCoins.end() && !it->second.coins.vout.empty());\n}\n\nuint256 CCoinsViewCache::GetBestBlock() const {\n if (hashBlock == uint256(0))\n hashBlock = base->GetBestBlock();\n return hashBlock;\n}\n\nvoid CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {\n hashBlock = hashBlockIn;\n}\n\nbool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {\n assert(!hasModifier);\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {\n if (it->second.flags & CCoinsCacheEntry::DIRTY) { \/\/ Ignore non-dirty entries (optimization).\n CCoinsMap::iterator itUs = cacheCoins.find(it->first);\n if (itUs == cacheCoins.end()) {\n if (!it->second.coins.IsPruned()) {\n \/\/ The parent cache does not have an entry, while the child\n \/\/ cache does have (a non-pruned) one. Move the data up, and\n \/\/ mark it as fresh (if the grandparent did have it, we\n \/\/ would have pulled it in at first GetCoins).\n assert(it->second.flags & CCoinsCacheEntry::FRESH);\n CCoinsCacheEntry& entry = cacheCoins[it->first];\n entry.coins.swap(it->second.coins);\n entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;\n }\n } else {\n if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {\n \/\/ The grandparent does not have an entry, and the child is\n \/\/ modified and being pruned. This means we can just delete\n \/\/ it from the parent.\n cacheCoins.erase(itUs);\n } else {\n \/\/ A normal modification.\n itUs->second.coins.swap(it->second.coins);\n itUs->second.flags |= CCoinsCacheEntry::DIRTY;\n }\n }\n }\n CCoinsMap::iterator itOld = it++;\n mapCoins.erase(itOld);\n }\n hashBlock = hashBlockIn;\n return true;\n}\n\nbool CCoinsViewCache::Flush() {\n bool fOk = base->BatchWrite(cacheCoins, hashBlock);\n cacheCoins.clear();\n return fOk;\n}\n\nunsigned int CCoinsViewCache::GetCacheSize() const {\n return cacheCoins.size();\n}\n\nconst CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const\n{\n const CCoins* coins = AccessCoins(input.prevout.hash);\n assert(coins && coins->IsAvailable(input.prevout.n));\n return coins->vout[input.prevout.n];\n}\n\nCAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const\n{\n if (tx.IsCoinBase())\n return 0;\n\n CAmount nResult = 0;\n for (unsigned int i = 0; i < tx.vin.size(); i++)\n nResult += GetOutputFor(tx.vin[i]).nValue;\n\n return nResult;\n}\n\nbool CCoinsViewCache::HaveInputs(const CTransaction& tx) const\n{\n if (!tx.IsCoinBase()) {\n for (unsigned int i = 0; i < tx.vin.size(); i++) {\n const COutPoint &prevout = tx.vin[i].prevout;\n const CCoins* coins = AccessCoins(prevout.hash);\n if (!coins || !coins->IsAvailable(prevout.n)) {\n return false;\n }\n }\n }\n return true;\n}\n\ndouble CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const\n{\n if (tx.IsCoinBase())\n return 0.0;\n double dResult = 0.0;\n BOOST_FOREACH(const CTxIn& txin, tx.vin)\n {\n const CCoins* coins = AccessCoins(txin.prevout.hash);\n assert(coins);\n if (!coins->IsAvailable(txin.prevout.n)) continue;\n if (coins->nHeight <= nHeight) {\n dResult += (double)(coins->vout[txin.prevout.n].nValue) * (nHeight-coins->nHeight);\n }\n }\n return tx.ComputePriority(dResult);\n}\n\nCCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_) : cache(cache_), it(it_) {\n assert(!cache.hasModifier);\n cache.hasModifier = true;\n}\n\nCCoinsModifier::~CCoinsModifier()\n{\n assert(cache.hasModifier);\n cache.hasModifier = false;\n it->second.coins.Cleanup();\n if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {\n cache.cacheCoins.erase(it);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QtWidgets>\n#include \"mainwindow.h\"\n#include <QKeyEvent>\n\nWindow::Window(QWidget *parent) : QWidget(parent)\n{\n findButton = new QPushButton(tr(\"&Find\"), this);\n connect(findButton, &QAbstractButton::clicked, this, &Window::find);\n textLabel = new QLabel(tr(\"Search:\"));\n searchBox = new SearchBox();\n\n createFilesTable();\n\n QGridLayout *mainLayout = new QGridLayout;\n mainLayout->addWidget(textLabel, 0, 0);\n mainLayout->addWidget(searchBox, 0, 1, 1, 1);\n mainLayout ->addWidget(findButton, 0, 3);\n mainLayout->addWidget(filesTable, 1, 0, 1, 4);\n setLayout(mainLayout);\n\n setWindowTitle(tr(\"Find Recipes\"));\n resize(500, 300);\n}\n\nvoid Window::find()\n{\n filesTable->setRowCount(0);\n\n QString text = searchBox->text();\n\n currentDir = QDir(\".\");\n QStringList files;\n QString fileName = \"*\";\n files = currentDir.entryList(QStringList(fileName),\n QDir::Files | QDir::NoSymLinks);\n\n if (!text.isEmpty())\n files = findFiles(files, text);\n showFiles(files);\n}\n\nQStringList Window::findFiles(const QStringList &files, const QString &text)\n{\n QProgressDialog progressDialog(this);\n progressDialog.setCancelButtonText(tr(\"&Cancel\"));\n progressDialog.setRange(0, files.size());\n progressDialog.setWindowTitle(tr(\"Find Files\"));\n\n QStringList foundFiles;\n\n for (int i = 0; i < files.size(); ++i) {\n progressDialog.setValue(i);\n progressDialog.setLabelText(tr(\"Searching file number %1 of %2...\")\n .arg(i).arg(files.size()));\n qApp->processEvents();\n\n if (progressDialog.wasCanceled())\n break;\n\n QFile file(currentDir.absoluteFilePath(files[i]));\n\n if (file.open(QIODevice::ReadOnly)) {\n QString line;\n QTextStream in(&file);\n while (!in.atEnd()) {\n if (progressDialog.wasCanceled())\n break;\n line = in.readLine();\n if (line.contains(text)) {\n foundFiles << files[i];\n break;\n }\n }\n }\n }\n return foundFiles;\n}\n\nvoid Window::showFiles(const QStringList &files)\n{\n for (int i = 0; i < files.size(); ++i) {\n QFile file(currentDir.absoluteFilePath(files[i]));\n qint64 size = QFileInfo(file).size();\n\n QTableWidgetItem *fileNameItem = new QTableWidgetItem(files[i]);\n fileNameItem->setFlags(fileNameItem->flags() ^ Qt::ItemIsEditable);\n QTableWidgetItem *sizeItem = new QTableWidgetItem(tr(\"%1 KB\")\n .arg(int((size + 1023) \/ 1024)));\n sizeItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);\n sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);\n\n int row = filesTable->rowCount();\n filesTable->insertRow(row);\n filesTable->setItem(row, 0, fileNameItem);\n filesTable->setItem(row, 1, sizeItem);\n }\n}\n\nvoid Window::createFilesTable()\n{\n filesTable = new QTableWidget(0, 2);\n filesTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n\n QStringList labels;\n labels << tr(\"Filename\") << tr(\"Size\");\n filesTable->setHorizontalHeaderLabels(labels);\n filesTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);\n filesTable->verticalHeader()->hide();\n filesTable->setShowGrid(false);\n\n connect(filesTable, &QTableWidget::cellActivated,\n this, &Window::openFileOfItem);\n}\n\n\nvoid Window::openFileOfItem(int row, int \/* column *\/)\n{\n QTableWidgetItem *item = filesTable->item(row, 0);\n\n QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(item->text())));\n}\n<commit_msg>Add function to get all files in subdirectories and modify 'find' usage to use new function<commit_after>#include <QtWidgets>\n#include \"mainwindow.h\"\n#include <QKeyEvent>\n#include <QDebug>\n\n#include <fts_fuzzy_match.h>\n#include <glob.h>\n#include <string>\n\nWindow::Window(QWidget *parent) : QWidget(parent)\n{\n findButton = new QPushButton(tr(\"&Find\"), this);\n connect(findButton, &QAbstractButton::clicked, this, &Window::find);\n textLabel = new QLabel(tr(\"Search:\"));\n searchBox = new SearchBox();\n\n createFilesTable();\n\n QGridLayout *mainLayout = new QGridLayout;\n mainLayout->addWidget(textLabel, 0, 0);\n mainLayout->addWidget(searchBox, 0, 1, 1, 1);\n mainLayout ->addWidget(findButton, 0, 3);\n mainLayout->addWidget(filesTable, 1, 0, 1, 4);\n setLayout(mainLayout);\n\n setWindowTitle(tr(\"Find Recipes\"));\n resize(500, 300);\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; i<glob_result.gl_pathc; ++i){\n files << QString(glob_result.gl_pathv[i]);\n }\n globfree(&glob_result);\n return files;\n}\n\nvoid Window::find()\n{\n filesTable->setRowCount(0);\n\n QStringList files = globVector(\"*\/*.md\");\n QString text = searchBox->text();\n if(!text.isEmpty()){\n files = findFiles(files, text);\n }\n showFiles(files);\n}\n\n\/*\nvoid Window::find()\n{\n filesTable->setRowCount(0);\n\n QString text = searchBox->text();\n\n currentDir = QDir(\".\");\n QStringList files;\n QString fileName = \"*\";\n files = currentDir.entryList(QStringList(fileName),\n QDir::Files | QDir::NoSymLinks);\n\n if (!text.isEmpty())\n files = findFiles(files, text);\n showFiles(files);\n}\n*\/\n\nQStringList Window::findFiles(const QStringList &files, const QString &text)\n{\n QProgressDialog progressDialog(this);\n progressDialog.setCancelButtonText(tr(\"&Cancel\"));\n progressDialog.setRange(0, files.size());\n progressDialog.setWindowTitle(tr(\"Find Files\"));\n\n QStringList foundFiles;\n\n for (int i = 0; i < files.size(); ++i) {\n progressDialog.setValue(i);\n progressDialog.setLabelText(tr(\"Searching file number %1 of %2...\")\n .arg(i).arg(files.size()));\n qApp->processEvents();\n\n if (progressDialog.wasCanceled())\n break;\n\n QFile file(currentDir.absoluteFilePath(files[i]));\n\n if (file.open(QIODevice::ReadOnly)) {\n QString line;\n QTextStream in(&file);\n while (!in.atEnd()) {\n if (progressDialog.wasCanceled())\n break;\n line = in.readLine();\n if (line.contains(text)) {\n foundFiles << files[i];\n break;\n }\n }\n }\n }\n return foundFiles;\n}\n\nvoid Window::showFiles(const QStringList &files)\n{\n for (int i = 0; i < files.size(); ++i) {\n QFile file(currentDir.absoluteFilePath(files[i]));\n qint64 size = QFileInfo(file).size();\n\n QTableWidgetItem *fileNameItem = new QTableWidgetItem(files[i]);\n fileNameItem->setFlags(fileNameItem->flags() ^ Qt::ItemIsEditable);\n QTableWidgetItem *sizeItem = new QTableWidgetItem(tr(\"%1 KB\")\n .arg(int((size + 1023) \/ 1024)));\n sizeItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);\n sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);\n\n int row = filesTable->rowCount();\n filesTable->insertRow(row);\n filesTable->setItem(row, 0, fileNameItem);\n filesTable->setItem(row, 1, sizeItem);\n }\n}\n\nvoid Window::createFilesTable()\n{\n filesTable = new QTableWidget(0, 2);\n filesTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n\n QStringList labels;\n labels << tr(\"Filename\") << tr(\"Size\");\n filesTable->setHorizontalHeaderLabels(labels);\n filesTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);\n filesTable->verticalHeader()->hide();\n filesTable->setShowGrid(false);\n\n connect(filesTable, &QTableWidget::cellActivated,\n this, &Window::openFileOfItem);\n}\n\n\nvoid Window::openFileOfItem(int row, int \/* column *\/)\n{\n QTableWidgetItem *item = filesTable->item(row, 0);\n\n QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(item->text())));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"model.h\"\n#include \"model_io.h\"\n#include \"figurepainter.h\"\n#include \"build_info.h\"\n#include <sstream>\n#include <fstream>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QShortcut>\n#include <QScreen>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n modelWidget(nullptr),\n redoExtraShortcut(QKeySequence(\"Ctrl+Shift+Z\"), this),\n zoomInExtraShortcut(QKeySequence(\"Ctrl+=\"), this)\n{\n ui->setupUi(this);\n connect(&redoExtraShortcut , &QShortcut::activated, ui->actionRedo , &QAction::trigger);\n connect(&zoomInExtraShortcut, &QShortcut::activated, ui->actionZoomIn, &QAction::trigger);\n setModelWidget(new Ui::ModelWidget());\n setWindowIcon(QIcon(\":\/icon.ico\"));\n}\n\nMainWindow::~MainWindow() {\n delete ui;\n}\n\nvoid MainWindow::on_actionNew_triggered() {\n setModelWidget(new Ui::ModelWidget());\n currentFileName = QString();\n}\n\nvoid MainWindow::setModelWidget(Ui::ModelWidget *newWidget) {\n if (this->modelWidget) {\n ui->wrapperFrame->layout()->removeWidget(this->modelWidget);\n delete this->modelWidget;\n }\n\n this->modelWidget = newWidget;\n ui->wrapperFrame->layout()->addWidget(this->modelWidget);\n ui->actionSaveAs->setEnabled(true);\n ui->actionUndo->setEnabled(modelWidget->canUndo());\n connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() {\n ui->actionUndo->setEnabled(modelWidget->canUndo());\n });\n ui->actionRedo->setEnabled(modelWidget->canRedo());\n connect(modelWidget, &Ui::ModelWidget::canRedoChanged, [this]() {\n ui->actionRedo->setEnabled(modelWidget->canRedo());\n });\n connect(modelWidget, &Ui::ModelWidget::scaleFactorChanged, [this]() {\n ui->actionZoomOut->setEnabled(modelWidget->scaleFactor() > SCALE_FACTOR_STEP + 1e-8);\n });\n modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0);\n\n QScreen *screen = QApplication::screens().at(0);\n modelWidget->setScaleFactor(screen->logicalDotsPerInch() \/ 96.0);\n}\n\nvoid MainWindow::on_actionOpen_triggered() {\n QString filename = QFileDialog::getOpenFileName(\n this,\n \"Select file with a model\",\n QDir::currentPath(),\n \"Models (*.model)\"\n );\n if (filename == \"\") {\n return;\n }\n\n std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget());\n QFile file(filename);\n if (!file.open(QFile::ReadOnly)) {\n QMessageBox::critical(this, \"Error while opening model\", \"Unable to open file for reading\");\n return;\n }\n std::stringstream data;\n data << file.readAll().toStdString();\n file.close();\n try {\n Model model;\n data >> model;\n modelWidget->setModel(std::move(model));\n } catch (model_format_error &e) {\n QMessageBox::critical(this, \"Error while opening model\", e.what());\n return;\n }\n\n setModelWidget(modelWidget.release());\n currentFileName = filename;\n}\n\nvoid MainWindow::on_actionSave_triggered() {\n if (currentFileName == QString()) {\n ui->actionSaveAs->trigger();\n return;\n }\n Model &model = this->modelWidget->getModel();\n std::ofstream file(currentFileName.toStdString());\n file << model;\n}\n\nQString forceFileExtension(QString filename, QString selectedFilter) {\n QString extension = selectedFilter.mid(selectedFilter.indexOf(\"(*.\") + 3);\n extension.chop(1); \/\/ chop trailing )\n extension = (\".\" + extension).toLower();\n if (!filename.endsWith(extension)) {\n filename += extension;\n }\n return filename;\n}\n\nvoid MainWindow::on_actionSaveAs_triggered() {\n QString selectedFilter;\n QString filename = QFileDialog::getSaveFileName(\n this,\n \"Select file to save in\",\n QDir::currentPath(),\n \"Models (*.model);;SVG (*.svg);;PNG (*.png)\",\n &selectedFilter\n );\n if (filename == \"\") {\n return;\n }\n filename = forceFileExtension(filename, selectedFilter);\n Model &model = this->modelWidget->getModel();\n std::ofstream file(filename.toStdString());\n if (filename.toLower().endsWith(\".svg\")) {\n exportModelToSvg(model, file);\n } else if (filename.toLower().endsWith(\".png\")) {\n file.close();\n exportModelToImageFile(model, filename);\n } else {\n file << model;\n currentFileName = filename;\n }\n}\n\nvoid MainWindow::on_actionUndo_triggered() {\n \/\/ Extra check is added for symmetry with actionRedo\n if (!modelWidget->canUndo()) { return; }\n modelWidget->undo();\n}\n\nvoid MainWindow::on_actionRedo_triggered() {\n \/\/ Extra check is added because there is extra shortcut\n if (!modelWidget->canRedo()) { return; }\n modelWidget->redo();\n}\n\nvoid MainWindow::on_actionShowGrid_triggered() {\n if (ui->actionShowGrid->isChecked()) {\n defaultGridStep = QInputDialog::getInt(this, \"Grid step\", \"Specify grid step in pixels\", defaultGridStep, 1, int(1e9));\n }\n modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0);\n}\n\nvoid MainWindow::on_actionZoomIn_triggered() {\n modelWidget->setScaleFactor(modelWidget->scaleFactor() + SCALE_FACTOR_STEP);\n}\n\nvoid MainWindow::on_actionZoomOut_triggered() {\n modelWidget->setScaleFactor(modelWidget->scaleFactor() - SCALE_FACTOR_STEP);\n}\n\nvoid MainWindow::on_actionExit_triggered() {\n QApplication::exit();\n}\n\nvoid MainWindow::on_actionAbout_triggered() {\n QMessageBox::about(this, \"About Manugram\",\n QString()\n + \"Git commit hash: \" + GIT_LAST_SHA1 + \"\\n\"\n + \"Git commit date: \" + GIT_LAST_TIME + \"\\n\"\n + \"Build time: \" + BUILD_TIME\n );\n}\n<commit_msg>mainwindow: saving is now performed via stringstream and QFile (#45)<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"model.h\"\n#include \"model_io.h\"\n#include \"figurepainter.h\"\n#include \"build_info.h\"\n#include <sstream>\n#include <QByteArray>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QShortcut>\n#include <QScreen>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n modelWidget(nullptr),\n redoExtraShortcut(QKeySequence(\"Ctrl+Shift+Z\"), this),\n zoomInExtraShortcut(QKeySequence(\"Ctrl+=\"), this)\n{\n ui->setupUi(this);\n connect(&redoExtraShortcut , &QShortcut::activated, ui->actionRedo , &QAction::trigger);\n connect(&zoomInExtraShortcut, &QShortcut::activated, ui->actionZoomIn, &QAction::trigger);\n setModelWidget(new Ui::ModelWidget());\n setWindowIcon(QIcon(\":\/icon.ico\"));\n}\n\nMainWindow::~MainWindow() {\n delete ui;\n}\n\nvoid MainWindow::on_actionNew_triggered() {\n setModelWidget(new Ui::ModelWidget());\n currentFileName = QString();\n}\n\nvoid MainWindow::setModelWidget(Ui::ModelWidget *newWidget) {\n if (this->modelWidget) {\n ui->wrapperFrame->layout()->removeWidget(this->modelWidget);\n delete this->modelWidget;\n }\n\n this->modelWidget = newWidget;\n ui->wrapperFrame->layout()->addWidget(this->modelWidget);\n ui->actionSaveAs->setEnabled(true);\n ui->actionUndo->setEnabled(modelWidget->canUndo());\n connect(modelWidget, &Ui::ModelWidget::canUndoChanged, [this]() {\n ui->actionUndo->setEnabled(modelWidget->canUndo());\n });\n ui->actionRedo->setEnabled(modelWidget->canRedo());\n connect(modelWidget, &Ui::ModelWidget::canRedoChanged, [this]() {\n ui->actionRedo->setEnabled(modelWidget->canRedo());\n });\n connect(modelWidget, &Ui::ModelWidget::scaleFactorChanged, [this]() {\n ui->actionZoomOut->setEnabled(modelWidget->scaleFactor() > SCALE_FACTOR_STEP + 1e-8);\n });\n modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0);\n\n QScreen *screen = QApplication::screens().at(0);\n modelWidget->setScaleFactor(screen->logicalDotsPerInch() \/ 96.0);\n}\n\nvoid MainWindow::on_actionOpen_triggered() {\n QString filename = QFileDialog::getOpenFileName(\n this,\n \"Select file with a model\",\n QDir::currentPath(),\n \"Models (*.model)\"\n );\n if (filename == \"\") {\n return;\n }\n\n std::unique_ptr<Ui::ModelWidget> modelWidget(new Ui::ModelWidget());\n QFile file(filename);\n if (!file.open(QFile::ReadOnly)) {\n QMessageBox::critical(this, \"Error while opening model\", \"Unable to open file for reading\");\n return;\n }\n std::stringstream data;\n data << file.readAll().toStdString();\n file.close();\n try {\n Model model;\n data >> model;\n modelWidget->setModel(std::move(model));\n } catch (model_format_error &e) {\n QMessageBox::critical(this, \"Error while opening model\", e.what());\n return;\n }\n\n setModelWidget(modelWidget.release());\n currentFileName = filename;\n}\n\nbool saveDataToFile(const std::string &data, QString &fileName) {\n QFile file(fileName);\n if (!file.open(QFile::WriteOnly)) {\n return false;\n }\n QByteArray buffer(data.data(), data.length());\n return file.write(buffer) == buffer.size();\n}\n\nvoid MainWindow::on_actionSave_triggered() {\n if (currentFileName == QString()) {\n ui->actionSaveAs->trigger();\n return;\n }\n std::stringstream data;\n data << this->modelWidget->getModel();\n if (!saveDataToFile(data.str(), currentFileName)) {\n QMessageBox::critical(this, \"Error\", \"Unable to save model\");\n }\n}\n\nQString forceFileExtension(QString filename, QString selectedFilter) {\n QString extension = selectedFilter.mid(selectedFilter.indexOf(\"(*.\") + 3);\n extension.chop(1); \/\/ chop trailing )\n extension = (\".\" + extension).toLower();\n if (!filename.endsWith(extension)) {\n filename += extension;\n }\n return filename;\n}\n\nvoid MainWindow::on_actionSaveAs_triggered() {\n QString selectedFilter;\n QString filename = QFileDialog::getSaveFileName(\n this,\n \"Select file to save in\",\n QDir::currentPath(),\n \"Models (*.model);;SVG (*.svg);;PNG (*.png)\",\n &selectedFilter\n );\n if (filename == \"\") {\n return;\n }\n filename = forceFileExtension(filename, selectedFilter);\n Model &model = this->modelWidget->getModel();\n if (filename.toLower().endsWith(\".svg\")) {\n std::stringstream data;\n exportModelToSvg(model, data);\n if (!saveDataToFile(data.str(), filename)) {\n QMessageBox::critical(this, \"Error\", \"Unable to save model to SVG\");\n }\n } else if (filename.toLower().endsWith(\".png\")) {\n exportModelToImageFile(model, filename);\n } else {\n std::stringstream data;\n data << model;\n if (!saveDataToFile(data.str(), currentFileName)) {\n QMessageBox::critical(this, \"Error\", \"Unable to save model\");\n }\n currentFileName = filename;\n }\n}\n\nvoid MainWindow::on_actionUndo_triggered() {\n \/\/ Extra check is added for symmetry with actionRedo\n if (!modelWidget->canUndo()) { return; }\n modelWidget->undo();\n}\n\nvoid MainWindow::on_actionRedo_triggered() {\n \/\/ Extra check is added because there is extra shortcut\n if (!modelWidget->canRedo()) { return; }\n modelWidget->redo();\n}\n\nvoid MainWindow::on_actionShowGrid_triggered() {\n if (ui->actionShowGrid->isChecked()) {\n defaultGridStep = QInputDialog::getInt(this, \"Grid step\", \"Specify grid step in pixels\", defaultGridStep, 1, int(1e9));\n }\n modelWidget->setGridStep(ui->actionShowGrid->isChecked() ? defaultGridStep : 0);\n}\n\nvoid MainWindow::on_actionZoomIn_triggered() {\n modelWidget->setScaleFactor(modelWidget->scaleFactor() + SCALE_FACTOR_STEP);\n}\n\nvoid MainWindow::on_actionZoomOut_triggered() {\n modelWidget->setScaleFactor(modelWidget->scaleFactor() - SCALE_FACTOR_STEP);\n}\n\nvoid MainWindow::on_actionExit_triggered() {\n QApplication::exit();\n}\n\nvoid MainWindow::on_actionAbout_triggered() {\n QMessageBox::about(this, \"About Manugram\",\n QString()\n + \"Git commit hash: \" + GIT_LAST_SHA1 + \"\\n\"\n + \"Git commit date: \" + GIT_LAST_TIME + \"\\n\"\n + \"Build time: \" + BUILD_TIME\n );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QFileDialog>\n#include <QImageReader>\n#include <QLabel>\n#include <QMessageBox>\n#include <QTimer>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n setAttribute(Qt::WA_QuitOnClose);\n setWindowState(windowState() | Qt::WindowMaximized);\n setWindowTitle(appName());\n\n QActionGroup* modeActionGroup = new QActionGroup(this);\n toggleEtalonModeAction = new QAction(QIcon(\":\/pictures\/etalon.png\"), QString::fromUtf8(\"Включить\/выключить режим задания эталона\"), this);\n measureSegmentLengthAction = new QAction(QIcon(\":\/pictures\/segment_length.png\"), QString::fromUtf8(\"Измерение длин отрезков\"), modeActionGroup);\n measurePolylineLengthAction = new QAction(QIcon(\":\/pictures\/polyline_length.png\"), QString::fromUtf8(\"Измерение длин кривых\"), modeActionGroup);\n measureClosedPolylineLengthAction = new QAction(QIcon(\":\/pictures\/closed_polyline_length.png\"), QString::fromUtf8(\"Измерение длин замкнутых кривых\"), modeActionGroup);\n measureRectangleAreaAction = new QAction(QIcon(\":\/pictures\/rectangle_area.png\"), QString::fromUtf8(\"Измерение площадей прямоугольников\"), modeActionGroup);\n measurePolygonAreaAction = new QAction(QIcon(\":\/pictures\/polygon_area.png\"), QString::fromUtf8(\"Измерение площадей многоугольников\"), modeActionGroup);\n toggleRulerAction = new QAction(QIcon(\":\/pictures\/toggle_ruler.png\"), QString::fromUtf8(\"Показать\/скрыть масштабную линейку\"), this);\n aboutAction = new QAction(QIcon(\":\/pictures\/about.png\"), QString::fromUtf8(\"О программе\"), this);\n toggleEtalonModeAction->setCheckable(true);\n toggleEtalonModeAction->setChecked(true);\n foreach (QAction* action, modeActionGroup->actions())\n action->setCheckable(true);\n measureSegmentLengthAction->setChecked(true);\n toggleRulerAction->setCheckable(true);\n toggleRulerAction->setChecked(true);\n ui->mainToolBar->addAction(toggleEtalonModeAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addActions(modeActionGroup->actions());\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleRulerAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(aboutAction);\n ui->mainToolBar->setIconSize(QSize(32, 32));\n ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);\n\n QList<QByteArray> supportedFormatsList__ = QImageReader::supportedImageFormats();\n QSet<QString> supportedFormatsSet;\n foreach (const QByteArray& format, supportedFormatsList__)\n supportedFormatsSet.insert(QString(format).toLower());\n QStringList supportedFormatsList(supportedFormatsSet.toList());\n qSort(supportedFormatsList);\n QString allFormatsString;\n QStringList singleFormatsList;\n foreach (const QString& lowerFormat, supportedFormatsList) {\n QString upperFormat = lowerFormat.toUpper();\n allFormatsString += QString(\"*.%1 \").arg(lowerFormat);\n if (upperFormat == \"JPEG\")\n singleFormatsList += QString::fromUtf8(\"Изображения JPEG (*.jpeg *.jpg)\").arg(upperFormat);\n else if (upperFormat != \"JPG\")\n singleFormatsList += QString::fromUtf8(\"Изображения %1 (*.%2)\").arg(upperFormat).arg(lowerFormat);\n }\n allFormatsString = allFormatsString.trimmed();\n QString formatsList = QString::fromUtf8(\"Все изображения (%1);;\").arg(allFormatsString) + singleFormatsList.join(\";;\");\n\n QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8(\"Укажите путь к изображению — \") + appName(),\n QString(), formatsList, 0);\n if (imageFile.isEmpty()) {\n QTimer::singleShot(0, this, SLOT(close()));\n return;\n }\n\n QPixmap* image = new QPixmap;\n if (!image->load(imageFile)) {\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не могу открыть изображение \\\"%1\\\".\").arg(imageFile));\n delete image;\n QTimer::singleShot(0, this, SLOT(close()));\n return;\n }\n\n QFont statusBarFont = ui->statusBar->font();\n int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; \/\/ In contrast to ``labelFont.pointSize()'' it always works\n statusBarFont.setPointSize(newSize);\n ui->statusBar->setFont(statusBarFont);\n QLabel* scaleLabel = new QLabel(this);\n QLabel* statusLabel = new QLabel(this);\n ui->statusBar->addPermanentWidget(scaleLabel);\n ui->statusBar->addWidget(statusLabel);\n\n canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);\n ui->containingScrollArea->setBackgroundRole(QPalette::Dark);\n ui->containingScrollArea->setWidget(canvasWidget);\n\n connect(toggleEtalonModeAction, SIGNAL(toggled(bool)), this, SLOT(toggleEtalonDefinition(bool)));\n connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));\n connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));\n canvasWidget->toggleRuler(toggleRulerAction->isChecked());\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\n\nQString MainWindow::appName() const\n{\n return \"AreaMeasurement\";\n}\n\nQList<int> MainWindow::appVersion() const\n{\n \/\/ TODO: Don't forget to increment it!\n return QList<int>() << 0 << 4;\n}\n\nQString MainWindow::appVersionString() const\n{\n QString versionString;\n foreach (int x, appVersion())\n versionString += QString::number(x) + '.';\n return versionString.left(versionString.length() - 1);\n}\n\n\nvoid MainWindow::setMode(Mode newMode)\n{\n canvasWidget->setMode(newMode);\n}\n\nvoid MainWindow::updateMode(QAction* modeAction)\n{\n if (modeAction == measureSegmentLengthAction)\n return setMode(MEASURE_SEGMENT_LENGTH);\n if (modeAction == measurePolylineLengthAction)\n return setMode(MEASURE_POLYLINE_LENGTH);\n if (modeAction == measureClosedPolylineLengthAction)\n return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);\n if (modeAction == measureRectangleAreaAction)\n return setMode(MEASURE_RECTANGLE_AREA);\n if (modeAction == measurePolygonAreaAction)\n return setMode(MEASURE_POLYGON_AREA);\n abort();\n}\n\nvoid MainWindow::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n if (canvasWidget->isEtalonCorrect()) {\n toggleEtalonModeAction->setChecked(isDefiningEtalon);\n canvasWidget->toggleEtalonDefinition(isDefiningEtalon);\n }\n else\n toggleEtalonModeAction->setChecked(true);\n}\n\nvoid MainWindow::showAbout()\n{\n QString aboutText = QString::fromUtf8(\"Программа %1, версия %2.\\n\\n\"\n \"Приложение предназначено для измерения длин и площадей объектов на чертежах, картах и т.д.\\n\\n\"\n \"Автор — Матвеякин Андрей.\\n\\n\"\n \"Программа распространяется бесплатно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения.\"\n ).arg(appName()).arg(appVersionString());\n QMessageBox::about(this, QString::fromUtf8(\"О программе %1\").arg(appName()), aboutText);\n}\n<commit_msg>Remove line accidentaly copypasted from Qt help<commit_after>#include <QFileDialog>\n#include <QImageReader>\n#include <QLabel>\n#include <QMessageBox>\n#include <QTimer>\n\n#include \"canvaswidget.h\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n\nMainWindow::MainWindow(QWidget* parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n setAttribute(Qt::WA_QuitOnClose);\n setWindowState(windowState() | Qt::WindowMaximized);\n setWindowTitle(appName());\n\n QActionGroup* modeActionGroup = new QActionGroup(this);\n toggleEtalonModeAction = new QAction(QIcon(\":\/pictures\/etalon.png\"), QString::fromUtf8(\"Включить\/выключить режим задания эталона\"), this);\n measureSegmentLengthAction = new QAction(QIcon(\":\/pictures\/segment_length.png\"), QString::fromUtf8(\"Измерение длин отрезков\"), modeActionGroup);\n measurePolylineLengthAction = new QAction(QIcon(\":\/pictures\/polyline_length.png\"), QString::fromUtf8(\"Измерение длин кривых\"), modeActionGroup);\n measureClosedPolylineLengthAction = new QAction(QIcon(\":\/pictures\/closed_polyline_length.png\"), QString::fromUtf8(\"Измерение длин замкнутых кривых\"), modeActionGroup);\n measureRectangleAreaAction = new QAction(QIcon(\":\/pictures\/rectangle_area.png\"), QString::fromUtf8(\"Измерение площадей прямоугольников\"), modeActionGroup);\n measurePolygonAreaAction = new QAction(QIcon(\":\/pictures\/polygon_area.png\"), QString::fromUtf8(\"Измерение площадей многоугольников\"), modeActionGroup);\n toggleRulerAction = new QAction(QIcon(\":\/pictures\/toggle_ruler.png\"), QString::fromUtf8(\"Показать\/скрыть масштабную линейку\"), this);\n aboutAction = new QAction(QIcon(\":\/pictures\/about.png\"), QString::fromUtf8(\"О программе\"), this);\n toggleEtalonModeAction->setCheckable(true);\n toggleEtalonModeAction->setChecked(true);\n foreach (QAction* action, modeActionGroup->actions())\n action->setCheckable(true);\n measureSegmentLengthAction->setChecked(true);\n toggleRulerAction->setCheckable(true);\n toggleRulerAction->setChecked(true);\n ui->mainToolBar->addAction(toggleEtalonModeAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addActions(modeActionGroup->actions());\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(toggleRulerAction);\n ui->mainToolBar->addSeparator();\n ui->mainToolBar->addAction(aboutAction);\n ui->mainToolBar->setIconSize(QSize(32, 32));\n ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);\n\n QList<QByteArray> supportedFormatsList__ = QImageReader::supportedImageFormats();\n QSet<QString> supportedFormatsSet;\n foreach (const QByteArray& format, supportedFormatsList__)\n supportedFormatsSet.insert(QString(format).toLower());\n QStringList supportedFormatsList(supportedFormatsSet.toList());\n qSort(supportedFormatsList);\n QString allFormatsString;\n QStringList singleFormatsList;\n foreach (const QString& lowerFormat, supportedFormatsList) {\n QString upperFormat = lowerFormat.toUpper();\n allFormatsString += QString(\"*.%1 \").arg(lowerFormat);\n if (upperFormat == \"JPEG\")\n singleFormatsList += QString::fromUtf8(\"Изображения JPEG (*.jpeg *.jpg)\").arg(upperFormat);\n else if (upperFormat != \"JPG\")\n singleFormatsList += QString::fromUtf8(\"Изображения %1 (*.%2)\").arg(upperFormat).arg(lowerFormat);\n }\n allFormatsString = allFormatsString.trimmed();\n QString formatsList = QString::fromUtf8(\"Все изображения (%1);;\").arg(allFormatsString) + singleFormatsList.join(\";;\");\n\n QString imageFile = QFileDialog::getOpenFileName (this, QString::fromUtf8(\"Укажите путь к изображению — \") + appName(),\n QString(), formatsList, 0);\n if (imageFile.isEmpty()) {\n QTimer::singleShot(0, this, SLOT(close()));\n return;\n }\n\n QPixmap* image = new QPixmap;\n if (!image->load(imageFile)) {\n QMessageBox::warning(this, appName(), QString::fromUtf8(\"Не могу открыть изображение \\\"%1\\\".\").arg(imageFile));\n delete image;\n QTimer::singleShot(0, this, SLOT(close()));\n return;\n }\n\n QFont statusBarFont = ui->statusBar->font();\n int newSize = QFontInfo(statusBarFont).pointSize() * 1.5; \/\/ In contrast to ``labelFont.pointSize()'' it always works\n statusBarFont.setPointSize(newSize);\n ui->statusBar->setFont(statusBarFont);\n QLabel* scaleLabel = new QLabel(this);\n QLabel* statusLabel = new QLabel(this);\n ui->statusBar->addPermanentWidget(scaleLabel);\n ui->statusBar->addWidget(statusLabel);\n\n canvasWidget = new CanvasWidget(image, this, ui->containingScrollArea, scaleLabel, statusLabel, this);\n ui->containingScrollArea->setWidget(canvasWidget);\n\n connect(toggleEtalonModeAction, SIGNAL(toggled(bool)), this, SLOT(toggleEtalonDefinition(bool)));\n connect(modeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateMode(QAction*)));\n connect(toggleRulerAction, SIGNAL(toggled(bool)), canvasWidget, SLOT(toggleRuler(bool)));\n connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));\n canvasWidget->toggleRuler(toggleRulerAction->isChecked());\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\n\nQString MainWindow::appName() const\n{\n return \"AreaMeasurement\";\n}\n\nQList<int> MainWindow::appVersion() const\n{\n \/\/ TODO: Don't forget to increment it!\n return QList<int>() << 0 << 4;\n}\n\nQString MainWindow::appVersionString() const\n{\n QString versionString;\n foreach (int x, appVersion())\n versionString += QString::number(x) + '.';\n return versionString.left(versionString.length() - 1);\n}\n\n\nvoid MainWindow::setMode(Mode newMode)\n{\n canvasWidget->setMode(newMode);\n}\n\nvoid MainWindow::updateMode(QAction* modeAction)\n{\n if (modeAction == measureSegmentLengthAction)\n return setMode(MEASURE_SEGMENT_LENGTH);\n if (modeAction == measurePolylineLengthAction)\n return setMode(MEASURE_POLYLINE_LENGTH);\n if (modeAction == measureClosedPolylineLengthAction)\n return setMode(MEASURE_CLOSED_POLYLINE_LENGTH);\n if (modeAction == measureRectangleAreaAction)\n return setMode(MEASURE_RECTANGLE_AREA);\n if (modeAction == measurePolygonAreaAction)\n return setMode(MEASURE_POLYGON_AREA);\n abort();\n}\n\nvoid MainWindow::toggleEtalonDefinition(bool isDefiningEtalon)\n{\n if (canvasWidget->isEtalonCorrect()) {\n toggleEtalonModeAction->setChecked(isDefiningEtalon);\n canvasWidget->toggleEtalonDefinition(isDefiningEtalon);\n }\n else\n toggleEtalonModeAction->setChecked(true);\n}\n\nvoid MainWindow::showAbout()\n{\n QString aboutText = QString::fromUtf8(\"Программа %1, версия %2.\\n\\n\"\n \"Приложение предназначено для измерения длин и площадей объектов на чертежах, картах и т.д.\\n\\n\"\n \"Автор — Матвеякин Андрей.\\n\\n\"\n \"Программа распространяется бесплатно по принципу «как есть»: автор не несёт ответственности за возможный ущерб, нанесённый в результате работы приложения.\"\n ).arg(appName()).arg(appVersionString());\n QMessageBox::about(this, QString::fromUtf8(\"О программе %1\").arg(appName()), aboutText);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"d3d12.h\"\r\n\r\n\r\ninline ID3D12Resource *d3d_create_buffer(ID3D12Device *d3d, D3D12_HEAP_TYPE heap_type, u64 size)\r\n{\r\n assert(heap_type != D3D12_HEAP_TYPE_CUSTOM);\r\n\r\n D3D12_HEAP_PROPERTIES heap_props = { .Type = heap_type };\r\n D3D12_RESOURCE_DESC buffer_desc = {\r\n .Dimension = D3D12_RESOURCE_DIMENSION_BUFFER,\r\n .Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR,\r\n .Width = size,\r\n .Height = 1,\r\n .DepthOrArraySize = 1,\r\n .MipLevels = 1,\r\n .SampleDesc.Count = 1\r\n };\r\n D3D12_RESOURCE_STATES state =\r\n (heap_type == D3D12_HEAP_TYPE_UPLOAD) ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST;\r\n\r\n ID3D12Resource *res;\r\n VHR(ID3D12Device_CreateCommittedResource(d3d, &heap_props, D3D12_HEAP_FLAG_NONE, &buffer_desc, state, NULL,\r\n &IID_ID3D12Resource, &res));\r\n return res;\r\n}\r\n<commit_msg>Delete d3d12.inl<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2014-2020 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mcreq.h\"\n#include \"compress.h\"\n\n#include <snappy.h>\n#include <snappy-sinksource.h>\n\nclass FragBufSource : public snappy::Source\n{\n public:\n explicit FragBufSource(const lcb_FRAGBUF *buf_) : buf(buf_)\n {\n if (buf->total_length) {\n left = buf->total_length;\n } else {\n left = 0;\n for (unsigned int ii = 0; ii < buf->niov; ii++) {\n left += buf->iov[ii].iov_len;\n }\n }\n idx = 0;\n ptr = static_cast< const char * >(buf->iov[idx].iov_base);\n }\n\n virtual ~FragBufSource() {}\n\n virtual size_t Available() const\n {\n return left;\n }\n\n virtual const char *Peek(size_t *len)\n {\n *len =\n buf->iov[idx].iov_len - static_cast< size_t >((ptr - static_cast< const char * >(buf->iov[idx].iov_base)));\n return ptr;\n }\n\n virtual void Skip(size_t n)\n {\n do {\n size_t spanleft = buf->iov[idx].iov_len - (ptr - static_cast< const char * >(buf->iov[idx].iov_base));\n if (n < spanleft) {\n ptr += n;\n left -= n;\n break;\n }\n if (idx + 1 >= buf->niov) {\n left = 0;\n ptr = NULL;\n break;\n }\n left -= spanleft;\n n -= spanleft;\n ptr = static_cast< const char * >(buf->iov[++idx].iov_base);\n } while (n > 0);\n if (left == 0 || idx >= buf->niov) {\n ptr = NULL;\n left = 0;\n }\n }\n\n private:\n const lcb_FRAGBUF *buf;\n const char *ptr;\n size_t left;\n unsigned int idx;\n};\n\nint mcreq_compress_value(mc_PIPELINE *pl, mc_PACKET *pkt, const lcb_VALBUF *vbuf, lcb_settings *settings,\n int *should_compress)\n{\n size_t maxsize, compsize = 0, origsize = 0;\n\n snappy::Source *source = NULL;\n switch (vbuf->vtype) {\n case LCB_KV_COPY:\n case LCB_KV_CONTIG:\n origsize = vbuf->u_buf.contig.nbytes;\n if (origsize < settings->compress_min_size) {\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n source = new snappy::ByteArraySource(static_cast< const char * >(vbuf->u_buf.contig.bytes),\n vbuf->u_buf.contig.nbytes);\n break;\n\n case LCB_KV_IOV:\n case LCB_KV_IOVCOPY:\n if (vbuf->u_buf.multi.total_length == 0) {\n for (unsigned int ii = 0; ii < vbuf->u_buf.multi.niov; ii++) {\n origsize += vbuf->u_buf.multi.iov[ii].iov_len;\n }\n }\n if (origsize < settings->compress_min_size) {\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n source = new FragBufSource(&vbuf->u_buf.multi);\n break;\n\n default:\n return -1;\n }\n\n maxsize = snappy::MaxCompressedLength(source->Available());\n if (mcreq_reserve_value2(pl, pkt, maxsize) != LCB_SUCCESS) {\n return -1;\n }\n nb_SPAN *outspan = &pkt->u_value.single;\n snappy::UncheckedByteArraySink sink(SPAN_BUFFER(outspan));\n\n Compress(source, &sink);\n compsize = sink.CurrentDestination() - SPAN_BUFFER(outspan);\n delete source;\n\n if (compsize == 0 || (((float)compsize \/ origsize) > settings->compress_min_ratio)) {\n netbuf_mblock_release(&pl->nbmgr, outspan);\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n\n if (compsize < maxsize) {\n \/* chop off some bytes? *\/\n nb_SPAN trailspan = *outspan;\n trailspan.offset += compsize;\n trailspan.size = maxsize - compsize;\n netbuf_mblock_release(&pl->nbmgr, &trailspan);\n outspan->size = compsize;\n }\n return 0;\n}\n\nint mcreq_inflate_value(const void *compressed, lcb_SIZE ncompressed, const void **bytes, lcb_SIZE *nbytes,\n void **freeptr)\n{\n size_t compsize = 0;\n\n if (!snappy::GetUncompressedLength(static_cast< const char * >(compressed), (size_t)ncompressed, &compsize)) {\n return -1;\n }\n *freeptr = malloc(compsize);\n if (!snappy::RawUncompress(static_cast< const char * >(compressed), ncompressed, static_cast< char * >(*freeptr))) {\n free(*freeptr);\n *freeptr = NULL;\n return -1;\n }\n\n *bytes = *freeptr;\n *nbytes = compsize;\n return 0;\n}\n<commit_msg>[coverity] compress.cc ensure that we never divide by zero<commit_after>\/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2014-2020 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mcreq.h\"\n#include \"compress.h\"\n\n#include <snappy.h>\n#include <snappy-sinksource.h>\n\nclass FragBufSource : public snappy::Source\n{\n public:\n explicit FragBufSource(const lcb_FRAGBUF *buf_) : buf(buf_)\n {\n if (buf->total_length) {\n left = buf->total_length;\n } else {\n left = 0;\n for (unsigned int ii = 0; ii < buf->niov; ii++) {\n left += buf->iov[ii].iov_len;\n }\n }\n idx = 0;\n ptr = static_cast< const char * >(buf->iov[idx].iov_base);\n }\n\n virtual ~FragBufSource() {}\n\n virtual size_t Available() const\n {\n return left;\n }\n\n virtual const char *Peek(size_t *len)\n {\n *len =\n buf->iov[idx].iov_len - static_cast< size_t >((ptr - static_cast< const char * >(buf->iov[idx].iov_base)));\n return ptr;\n }\n\n virtual void Skip(size_t n)\n {\n do {\n size_t spanleft = buf->iov[idx].iov_len - (ptr - static_cast< const char * >(buf->iov[idx].iov_base));\n if (n < spanleft) {\n ptr += n;\n left -= n;\n break;\n }\n if (idx + 1 >= buf->niov) {\n left = 0;\n ptr = NULL;\n break;\n }\n left -= spanleft;\n n -= spanleft;\n ptr = static_cast< const char * >(buf->iov[++idx].iov_base);\n } while (n > 0);\n if (left == 0 || idx >= buf->niov) {\n ptr = NULL;\n left = 0;\n }\n }\n\n private:\n const lcb_FRAGBUF *buf;\n const char *ptr;\n size_t left;\n unsigned int idx;\n};\n\nint mcreq_compress_value(mc_PIPELINE *pl, mc_PACKET *pkt, const lcb_VALBUF *vbuf, lcb_settings *settings,\n int *should_compress)\n{\n size_t maxsize, compsize = 0, origsize = 0;\n\n snappy::Source *source = NULL;\n switch (vbuf->vtype) {\n case LCB_KV_COPY:\n case LCB_KV_CONTIG:\n origsize = vbuf->u_buf.contig.nbytes;\n if (origsize < settings->compress_min_size) {\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n source = new snappy::ByteArraySource(static_cast< const char * >(vbuf->u_buf.contig.bytes),\n vbuf->u_buf.contig.nbytes);\n break;\n\n case LCB_KV_IOV:\n case LCB_KV_IOVCOPY:\n if (vbuf->u_buf.multi.total_length == 0) {\n for (unsigned int ii = 0; ii < vbuf->u_buf.multi.niov; ii++) {\n origsize += vbuf->u_buf.multi.iov[ii].iov_len;\n }\n }\n if (origsize == 0 || origsize < settings->compress_min_size) {\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n source = new FragBufSource(&vbuf->u_buf.multi);\n break;\n\n default:\n return -1;\n }\n\n maxsize = snappy::MaxCompressedLength(source->Available());\n if (mcreq_reserve_value2(pl, pkt, maxsize) != LCB_SUCCESS) {\n return -1;\n }\n nb_SPAN *outspan = &pkt->u_value.single;\n snappy::UncheckedByteArraySink sink(SPAN_BUFFER(outspan));\n\n Compress(source, &sink);\n compsize = sink.CurrentDestination() - SPAN_BUFFER(outspan);\n delete source;\n\n if (compsize == 0 || (((float)compsize \/ origsize) > settings->compress_min_ratio)) {\n netbuf_mblock_release(&pl->nbmgr, outspan);\n *should_compress = 0;\n mcreq_reserve_value(pl, pkt, vbuf);\n return 0;\n }\n\n if (compsize < maxsize) {\n \/* chop off some bytes? *\/\n nb_SPAN trailspan = *outspan;\n trailspan.offset += compsize;\n trailspan.size = maxsize - compsize;\n netbuf_mblock_release(&pl->nbmgr, &trailspan);\n outspan->size = compsize;\n }\n return 0;\n}\n\nint mcreq_inflate_value(const void *compressed, lcb_SIZE ncompressed, const void **bytes, lcb_SIZE *nbytes,\n void **freeptr)\n{\n size_t compsize = 0;\n\n if (!snappy::GetUncompressedLength(static_cast< const char * >(compressed), (size_t)ncompressed, &compsize)) {\n return -1;\n }\n *freeptr = malloc(compsize);\n if (!snappy::RawUncompress(static_cast< const char * >(compressed), ncompressed, static_cast< char * >(*freeptr))) {\n free(*freeptr);\n *freeptr = NULL;\n return -1;\n }\n\n *bytes = *freeptr;\n *nbytes = compsize;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"JsonConverter.h\"\n#include <json\/writer.h>\n\n\/\/ #include \"abstractable.h\"\n#include \"miracle.h\"\n\nusing namespace std;\nusing namespace mgl;\nusing namespace Json;\nusing namespace libthing;\n\n\n\/\/\/\/ @param slices list of output slice (output )\nvoid mgl::miracleGrue(const GCoderConfig &gcoderCfg,\n const SlicerConfig &slicerCfg,\n const char *modelFile,\n const char *, \/\/ scadFileStr,\n const char *gcodeFile,\n int firstSliceIdx,\n int lastSliceIdx,\n Tomograph &tomograph,\n Regions ®ions,\n std::vector< SliceData > &slices,\n ProgressBar *progress)\n{\n\n\tMeshy mesh(slicerCfg.firstLayerZ, slicerCfg.layerH);\n\tmesh.readStlFile(modelFile);\n\n\tSlicer slicer(slicerCfg, progress);\n\n\tslicer.tomographyze(mesh, tomograph);\n\n\tRegioner regioner(slicerCfg, progress);\n\n\tregioner.generateSkeleton(tomograph, regions);\n\n\tPather pather(progress);\n\n\tpather.generatePaths(tomograph, regions, slices);\n\n\t\/\/ pather.writeGcode(gcodeFileStr, modelFile, slices);\n\tstd::ofstream gout(gcodeFile);\n\n GCoder gcoder(gcoderCfg, progress);\n gcoder.writeGcodeFile(slices, tomograph.layerMeasure, gout, modelFile, firstSliceIdx, lastSliceIdx);\n\n\tgout.close();\n\n}\n\n\n\n\n<commit_msg>[finishes 31345487] align the mesh to the bed after reading the stl<commit_after>\n\n#include \"JsonConverter.h\"\n#include <json\/writer.h>\n\n\/\/ #include \"abstractable.h\"\n#include \"miracle.h\"\n\nusing namespace std;\nusing namespace mgl;\nusing namespace Json;\nusing namespace libthing;\n\n\n\/\/\/\/ @param slices list of output slice (output )\nvoid mgl::miracleGrue(const GCoderConfig &gcoderCfg,\n const SlicerConfig &slicerCfg,\n const char *modelFile,\n const char *, \/\/ scadFileStr,\n const char *gcodeFile,\n int firstSliceIdx,\n int lastSliceIdx,\n Tomograph &tomograph,\n Regions ®ions,\n std::vector< SliceData > &slices,\n ProgressBar *progress)\n{\n\n\tMeshy mesh(slicerCfg.firstLayerZ, slicerCfg.layerH);\n\tmesh.readStlFile(modelFile);\n\tmesh.alignToPlate();\n\n\tSlicer slicer(slicerCfg, progress);\n\n\tslicer.tomographyze(mesh, tomograph);\n\n\tRegioner regioner(slicerCfg, progress);\n\n\tregioner.generateSkeleton(tomograph, regions);\n\n\tPather pather(progress);\n\n\tpather.generatePaths(tomograph, regions, slices);\n\n\t\/\/ pather.writeGcode(gcodeFileStr, modelFile, slices);\n\tstd::ofstream gout(gcodeFile);\n\n GCoder gcoder(gcoderCfg, progress);\n gcoder.writeGcodeFile(slices, tomograph.layerMeasure, gout, modelFile, firstSliceIdx, lastSliceIdx);\n\n\tgout.close();\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\n\/\/ Some useful functions\n\/\/==============================================================================\n\n#include \"utils.h\"\n\n\/\/==============================================================================\n\n#include <QCoreApplication>\n#include <QDate>\n#include <QDir>\n#include <QDirIterator>\n#include <QFile>\n#include <QFileInfo>\n#include <QProcess>\n#include <QResource>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\n\n\/\/==============================================================================\n\nQString exec(const QString &pProg, const QString &pArgs)\n{\n if (QFileInfo(pProg).exists()) {\n \/\/ The program exists, so we can execute it\n\n QProcess process;\n\n process.start(pProg, pArgs.split(' '));\n process.waitForFinished();\n\n return process.readAll().trimmed();\n } else {\n \/\/ The program doesn't exist, so...\n\n return QString();\n }\n}\n\n\/\/==============================================================================\n\nQString getOsName()\n{\n#ifdef Q_WS_WIN\n switch (QSysInfo::WindowsVersion) {\n case QSysInfo::WV_NT:\n return \"Microsoft Windows NT\";\n case QSysInfo::WV_2000:\n return \"Microsoft Windows 2000\";\n case QSysInfo::WV_XP:\n return \"Microsoft Windows XP\";\n case QSysInfo::WV_2003:\n return \"Microsoft Windows 2003\";\n case QSysInfo::WV_VISTA:\n return \"Microsoft Windows Vista\";\n case QSysInfo::WV_WINDOWS7:\n return \"Microsoft Windows 7\";\n default:\n return \"Microsoft Windows\";\n }\n#elif defined(Q_WS_MAC)\n \/\/ Note #1: the version of Qt that we use on OS X only supports Mac OS X\n \/\/ 10.5 and above, so...\n \/\/ Note #2: from version 10.7, Apple uses OS X rather than Mac OS X...\n\n switch (QSysInfo::MacintoshVersion) {\n case QSysInfo::MV_10_5:\n return \"Mac OS X 10.5 (Leopard)\";\n case QSysInfo::MV_10_6:\n return \"Mac OS X 10.6 (Snow Leopard)\";\n case QSysInfo::MV_10_7:\n return \"OS X 10.7 (Lion)\";\n case QSysInfo::MV_10_8:\n return \"OS X 10.8 (Mountain Lion)\";\n default:\n return \"Mac OS X\";\n }\n#else\n QString os = exec(\"\/bin\/uname\", \"-o\");\n\n if (os.isEmpty())\n \/\/ We couldn't find \/bin\/uname, so...\n\n return \"Unknown\";\n else\n return os+\" \"+exec(\"\/bin\/uname\", \"-r\");\n#endif\n}\n\n\/\/==============================================================================\n\nQString getAppVersion(QCoreApplication *pApp)\n{\n QString bitVersion;\n static int sizeOfPointer = sizeof(void *);\n\n switch (sizeOfPointer) {\n case 4:\n bitVersion = \" (32-bit)\";\n\n break;\n case 8:\n bitVersion = \" (64-bit)\";\n\n break;\n default:\n \/\/ Not a size that we could recognise, so...\n\n bitVersion = \"\";\n }\n\n return pApp->applicationName()+\" \"+pApp->applicationVersion()+bitVersion;\n}\n\n\/\/==============================================================================\n\nQString getAppCopyright(const bool &pHtml)\n{\n return QObject::tr(\"Copyright\")+\" \"+QString(pHtml?\"©\":\"\")+\"2011-\"+QString::number(QDate().year());\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Minor fix in the current year for our copyright information.<commit_after>\/\/==============================================================================\n\/\/ Some useful functions\n\/\/==============================================================================\n\n#include \"utils.h\"\n\n\/\/==============================================================================\n\n#include <QCoreApplication>\n#include <QDate>\n#include <QDir>\n#include <QDirIterator>\n#include <QFile>\n#include <QFileInfo>\n#include <QProcess>\n#include <QResource>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\n\n\/\/==============================================================================\n\nQString exec(const QString &pProg, const QString &pArgs)\n{\n if (QFileInfo(pProg).exists()) {\n \/\/ The program exists, so we can execute it\n\n QProcess process;\n\n process.start(pProg, pArgs.split(' '));\n process.waitForFinished();\n\n return process.readAll().trimmed();\n } else {\n \/\/ The program doesn't exist, so...\n\n return QString();\n }\n}\n\n\/\/==============================================================================\n\nQString getOsName()\n{\n#ifdef Q_WS_WIN\n switch (QSysInfo::WindowsVersion) {\n case QSysInfo::WV_NT:\n return \"Microsoft Windows NT\";\n case QSysInfo::WV_2000:\n return \"Microsoft Windows 2000\";\n case QSysInfo::WV_XP:\n return \"Microsoft Windows XP\";\n case QSysInfo::WV_2003:\n return \"Microsoft Windows 2003\";\n case QSysInfo::WV_VISTA:\n return \"Microsoft Windows Vista\";\n case QSysInfo::WV_WINDOWS7:\n return \"Microsoft Windows 7\";\n default:\n return \"Microsoft Windows\";\n }\n#elif defined(Q_WS_MAC)\n \/\/ Note #1: the version of Qt that we use on OS X only supports Mac OS X\n \/\/ 10.5 and above, so...\n \/\/ Note #2: from version 10.7, Apple uses OS X rather than Mac OS X...\n\n switch (QSysInfo::MacintoshVersion) {\n case QSysInfo::MV_10_5:\n return \"Mac OS X 10.5 (Leopard)\";\n case QSysInfo::MV_10_6:\n return \"Mac OS X 10.6 (Snow Leopard)\";\n case QSysInfo::MV_10_7:\n return \"OS X 10.7 (Lion)\";\n case QSysInfo::MV_10_8:\n return \"OS X 10.8 (Mountain Lion)\";\n default:\n return \"Mac OS X\";\n }\n#else\n QString os = exec(\"\/bin\/uname\", \"-o\");\n\n if (os.isEmpty())\n \/\/ We couldn't find \/bin\/uname, so...\n\n return \"Unknown\";\n else\n return os+\" \"+exec(\"\/bin\/uname\", \"-r\");\n#endif\n}\n\n\/\/==============================================================================\n\nQString getAppVersion(QCoreApplication *pApp)\n{\n QString bitVersion;\n static int sizeOfPointer = sizeof(void *);\n\n switch (sizeOfPointer) {\n case 4:\n bitVersion = \" (32-bit)\";\n\n break;\n case 8:\n bitVersion = \" (64-bit)\";\n\n break;\n default:\n \/\/ Not a size that we could recognise, so...\n\n bitVersion = \"\";\n }\n\n return pApp->applicationName()+\" \"+pApp->applicationVersion()+bitVersion;\n}\n\n\/\/==============================================================================\n\nQString getAppCopyright(const bool &pHtml)\n{\n return QObject::tr(\"Copyright\")+\" \"+QString(pHtml?\"©\":\"\")+\"2011-\"+QString::number(QDate().currentDate().year());\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * *\n * Copyright (C) 2007-2015 by frePPLe bv *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Affero General Public License as published *\n * by the Free Software Foundation; either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with this program. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n ***************************************************************************\/\n\n#define FREPPLE_CORE\n#include \"frepple\/model.h\"\n\nnamespace frepple {\n\ntemplate <class Item>\nTree utils::HasName<Item>::st;\nconst MetaCategory* Item::metadata;\nconst MetaClass *ItemMTO::metadata, *ItemMTS::metadata;\n\nint Item::initialize() {\n metadata =\n MetaCategory::registerCategory<Item>(\"item\", \"items\", reader, finder);\n registerFields<Item>(const_cast<MetaCategory*>(metadata));\n return FreppleCategory<Item>::initialize();\n}\n\nint ItemMTS::initialize() {\n ItemMTS::metadata = MetaClass::registerClass<ItemMTS>(\n \"item\", \"item_mts\", Object::create<ItemMTS>, true);\n return FreppleClass<ItemMTS, Item>::initialize();\n}\n\nint ItemMTO::initialize() {\n ItemMTO::metadata = MetaClass::registerClass<ItemMTO>(\n \"item\", \"item_mto\", Object::create<ItemMTO>);\n return FreppleClass<ItemMTO, Item>::initialize();\n}\n\nItem::~Item() {\n \/\/ Remove references from the buffers\n bufferIterator bufiter(this);\n while (Buffer* buf = bufiter.next()) buf->setItem(nullptr);\n\n \/\/ Remove references from the demands\n for (auto l = Demand::begin(); l != Demand::end(); ++l)\n if (l->getItem() == this) l->setItem(nullptr);\n\n \/\/ Remove all item operations referencing this item\n while (firstOperation) delete firstOperation;\n\n \/\/ The ItemSupplier objects are automatically deleted by the\n \/\/ destructor of the Association list class.\n}\n\nvoid Demand::setItem(Item* i) {\n \/\/ No change\n if (it == i) return;\n\n \/\/ Unlink from previous item\n if (it) {\n if (it->firstItemDemand == this)\n it->firstItemDemand = nextItemDemand;\n else {\n Demand* dmd = it->firstItemDemand;\n while (dmd && dmd->nextItemDemand != this) dmd = dmd->nextItemDemand;\n if (!dmd) throw LogicException(\"corrupted demand list for an item\");\n dmd->nextItemDemand = nextItemDemand;\n }\n }\n\n \/\/ Link at new item\n it = i;\n if (it) {\n nextItemDemand = it->firstItemDemand;\n it->firstItemDemand = this;\n }\n\n \/\/ Trigger recreation of the delivery operation\n if (oper && oper->getHidden()) oper = uninitializedDelivery;\n\n \/\/ Trigger level calculation\n HasLevel::triggerLazyRecomputation();\n\n \/\/ Mark as changed\n setChanged();\n}\n\nDate Item::findEarliestPurchaseOrder(const PooledString& batch) const {\n Date earliest = Date::infiniteFuture;\n bufferIterator buf_iter(this);\n while (Buffer* buf = buf_iter.next()) {\n if (buf->getBatch() != batch) continue;\n for (auto flpln = buf->getFlowPlans().begin();\n flpln != buf->getFlowPlans().end(); ++flpln) {\n if (flpln->getDate() >= earliest) break;\n auto opplan = flpln->getOperationPlan();\n if (opplan && opplan->getOperation()->hasType<OperationItemSupplier>() &&\n opplan->getProposed()) {\n earliest = flpln->getDate();\n break;\n }\n }\n }\n return earliest;\n}\n\n} \/\/ namespace frepple\n<commit_msg>small todo remarks<commit_after>\/***************************************************************************\n * *\n * Copyright (C) 2007-2015 by frePPLe bv *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Affero General Public License as published *\n * by the Free Software Foundation; either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with this program. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n * *\n ***************************************************************************\/\n\n#define FREPPLE_CORE\n#include \"frepple\/model.h\"\n\nnamespace frepple {\n\ntemplate <class Item>\nTree utils::HasName<Item>::st;\nconst MetaCategory* Item::metadata;\nconst MetaClass *ItemMTO::metadata, *ItemMTS::metadata;\n\nint Item::initialize() {\n metadata =\n MetaCategory::registerCategory<Item>(\"item\", \"items\", reader, finder);\n registerFields<Item>(const_cast<MetaCategory*>(metadata));\n return FreppleCategory<Item>::initialize();\n}\n\nint ItemMTS::initialize() {\n ItemMTS::metadata = MetaClass::registerClass<ItemMTS>(\n \"item\", \"item_mts\", Object::create<ItemMTS>, true);\n return FreppleClass<ItemMTS, Item>::initialize();\n}\n\nint ItemMTO::initialize() {\n ItemMTO::metadata = MetaClass::registerClass<ItemMTO>(\n \"item\", \"item_mto\", Object::create<ItemMTO>);\n return FreppleClass<ItemMTO, Item>::initialize();\n}\n\nItem::~Item() {\n \/\/ Remove references from the buffers\n \/\/ TODO deleting would be better than leaving buffers with a null item\n bufferIterator bufiter(this);\n while (Buffer* buf = bufiter.next()) buf->setItem(nullptr);\n\n \/\/ Remove references from the demands\n \/\/ TODO rewrite using item-based demand iterator\n for (auto l = Demand::begin(); l != Demand::end(); ++l)\n if (l->getItem() == this) l->setItem(nullptr);\n\n \/\/ Remove all item operations referencing this item\n while (firstOperation) delete firstOperation;\n\n \/\/ The ItemSupplier objects are automatically deleted by the\n \/\/ destructor of the Association list class.\n}\n\nvoid Demand::setItem(Item* i) {\n \/\/ No change\n if (it == i) return;\n\n \/\/ Unlink from previous item\n if (it) {\n if (it->firstItemDemand == this)\n it->firstItemDemand = nextItemDemand;\n else {\n Demand* dmd = it->firstItemDemand;\n while (dmd && dmd->nextItemDemand != this) dmd = dmd->nextItemDemand;\n if (!dmd) throw LogicException(\"corrupted demand list for an item\");\n dmd->nextItemDemand = nextItemDemand;\n }\n }\n\n \/\/ Link at new item\n it = i;\n if (it) {\n nextItemDemand = it->firstItemDemand;\n it->firstItemDemand = this;\n }\n\n \/\/ Trigger recreation of the delivery operation\n if (oper && oper->getHidden()) oper = uninitializedDelivery;\n\n \/\/ Trigger level calculation\n HasLevel::triggerLazyRecomputation();\n\n \/\/ Mark as changed\n setChanged();\n}\n\nDate Item::findEarliestPurchaseOrder(const PooledString& batch) const {\n Date earliest = Date::infiniteFuture;\n bufferIterator buf_iter(this);\n while (Buffer* buf = buf_iter.next()) {\n if (buf->getBatch() != batch) continue;\n for (auto flpln = buf->getFlowPlans().begin();\n flpln != buf->getFlowPlans().end(); ++flpln) {\n if (flpln->getDate() >= earliest) break;\n auto opplan = flpln->getOperationPlan();\n if (opplan && opplan->getOperation()->hasType<OperationItemSupplier>() &&\n opplan->getProposed()) {\n earliest = flpln->getDate();\n break;\n }\n }\n }\n return earliest;\n}\n\n} \/\/ namespace frepple\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"Type.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"mangling.hpp\"\n#include \"Variable.hpp\"\n\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\nbool mtac::is_single_int_register(std::shared_ptr<const Type> type){\n return type == INT || type == BOOL || type == CHAR || type->is_pointer(); \n}\n\nbool mtac::is_single_float_register(std::shared_ptr<const Type> type){\n return type == FLOAT;\n}\n\nbool mtac::is_recursive(mtac::Function& function){\n for(auto& basic_block : function){\n for(auto& quadruple : basic_block->statements){\n if(quadruple->op == mtac::Operator::CALL && quadruple->function().mangled_name() == function.definition().mangled_name()){\n return true;\n }\n }\n }\n\n return false;\n}\n\nnamespace {\n\nstruct VariableUsageCollector {\n mtac::VariableUsage& usage;\n int depth_factor;\n int current_depth;\n\n VariableUsageCollector(mtac::VariableUsage& usage, int depth_factor) : usage(usage), depth_factor(depth_factor) {}\n\n void inc_usage(std::shared_ptr<Variable> variable){\n usage[variable] += pow(depth_factor, current_depth);\n }\n\n template<typename T>\n void collect_optional(T& opt){\n if(opt){\n if(auto* variablePtr = boost::get<std::shared_ptr<Variable>>(&*opt)){\n inc_usage(*variablePtr);\n }\n }\n }\n\n void collect(std::shared_ptr<mtac::Quadruple> quadruple){\n current_depth = quadruple->depth;\n\n inc_usage(quadruple->result);\n collect_optional(quadruple->arg1);\n collect_optional(quadruple->arg2);\n }\n};\n\nstruct BasicBlockUsageCollector {\n std::unordered_set<mtac::basic_block_p>& usage;\n\n BasicBlockUsageCollector(std::unordered_set<mtac::basic_block_p>& usage) : usage(usage) {}\n\n void collect(std::shared_ptr<mtac::Quadruple> goto_){\n usage.insert(goto_->block);\n }\n};\n\n} \/\/end of anonymous namespace\n\nmtac::VariableUsage mtac::compute_variable_usage(mtac::Function& function){\n return compute_variable_usage_with_depth(function, 1);\n}\n\nmtac::VariableUsage mtac::compute_variable_usage_with_depth(mtac::Function& function, int factor){\n mtac::VariableUsage usage;\n\n VariableUsageCollector collector(usage, factor);\n\n for(auto& block : function){\n for(auto& quadruple : block->statements){\n collector.collect(quadruple);\n }\n }\n\n return usage;\n}\n\nvoid eddic::mtac::computeBlockUsage(mtac::Function& function, std::unordered_set<mtac::basic_block_p>& usage){\n BasicBlockUsageCollector collector(usage);\n\n for(auto& block : function){\n for(auto& quadruple : block->statements){\n collector.collect(quadruple);\n }\n }\n}\n\nbool eddic::mtac::safe(const std::string& function){\n \/\/These functions are considered as safe because they save\/restore all the registers and does not return anything \n return \n function == \"_F5printI\" || function == \"_F5printF\" || function == \"_F5printS\" || function == \"_F5printC\" ||\n function == \"_F7printlnI\" || function == \"_F7printlnF\" || function == \"_F7printlnS\" || function == \"_F7printlnC\" || \n function == \"_F7println\"; \n}\n\nbool eddic::mtac::erase_result(mtac::Operator op){\n return \n op != mtac::Operator::DOT_ASSIGN \n && op != mtac::Operator::DOT_FASSIGN \n && op != mtac::Operator::DOT_PASSIGN \n && op != mtac::Operator::RETURN\n && op != mtac::Operator::GOTO\n && op != mtac::Operator::NOP\n && op != mtac::Operator::PARAM\n && op != mtac::Operator::CALL\n && op != mtac::Operator::LABEL; \n}\n\nbool eddic::mtac::is_distributive(mtac::Operator op){\n return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;\n}\n\nbool eddic::mtac::is_expression(mtac::Operator op){\n return op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV;\n}\n\nunsigned int eddic::mtac::compute_member_offset(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member){\n return compute_member(context, type, member).first;\n}\n\nstd::pair<unsigned int, std::shared_ptr<const Type>> eddic::mtac::compute_member(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member){\n auto struct_type = context->get_struct(type);\n std::shared_ptr<const Type> member_type;\n unsigned int offset = 0;\n\n do {\n if(struct_type->member_exists(member)){\n member_type = (*struct_type)[member]->type;\n break;\n }\n\n offset += context->self_size_of_struct(struct_type);\n\n struct_type = context->get_struct(struct_type->parent_type);\n } while(struct_type);\n\n eddic_assert(member_type, \"The member must exist\");\n\n offset += context->member_offset(struct_type, member);\n\n return std::make_pair(offset, member_type);\n}\n\n\/\/TODO Use the copy constructor instead\n\nstd::shared_ptr<mtac::Quadruple> mtac::copy(const std::shared_ptr<mtac::Quadruple>& quadruple){\n return std::make_shared<mtac::Quadruple>(*quadruple);\n}\n<commit_msg>Fix erase_result<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"Type.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"mangling.hpp\"\n#include \"Variable.hpp\"\n\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\nbool mtac::is_single_int_register(std::shared_ptr<const Type> type){\n return type == INT || type == BOOL || type == CHAR || type->is_pointer(); \n}\n\nbool mtac::is_single_float_register(std::shared_ptr<const Type> type){\n return type == FLOAT;\n}\n\nbool mtac::is_recursive(mtac::Function& function){\n for(auto& basic_block : function){\n for(auto& quadruple : basic_block->statements){\n if(quadruple->op == mtac::Operator::CALL && quadruple->function().mangled_name() == function.definition().mangled_name()){\n return true;\n }\n }\n }\n\n return false;\n}\n\nnamespace {\n\nstruct VariableUsageCollector {\n mtac::VariableUsage& usage;\n int depth_factor;\n int current_depth;\n\n VariableUsageCollector(mtac::VariableUsage& usage, int depth_factor) : usage(usage), depth_factor(depth_factor) {}\n\n void inc_usage(std::shared_ptr<Variable> variable){\n usage[variable] += pow(depth_factor, current_depth);\n }\n\n template<typename T>\n void collect_optional(T& opt){\n if(opt){\n if(auto* variablePtr = boost::get<std::shared_ptr<Variable>>(&*opt)){\n inc_usage(*variablePtr);\n }\n }\n }\n\n void collect(std::shared_ptr<mtac::Quadruple> quadruple){\n current_depth = quadruple->depth;\n\n inc_usage(quadruple->result);\n collect_optional(quadruple->arg1);\n collect_optional(quadruple->arg2);\n }\n};\n\nstruct BasicBlockUsageCollector {\n std::unordered_set<mtac::basic_block_p>& usage;\n\n BasicBlockUsageCollector(std::unordered_set<mtac::basic_block_p>& usage) : usage(usage) {}\n\n void collect(std::shared_ptr<mtac::Quadruple> goto_){\n usage.insert(goto_->block);\n }\n};\n\n} \/\/end of anonymous namespace\n\nmtac::VariableUsage mtac::compute_variable_usage(mtac::Function& function){\n return compute_variable_usage_with_depth(function, 1);\n}\n\nmtac::VariableUsage mtac::compute_variable_usage_with_depth(mtac::Function& function, int factor){\n mtac::VariableUsage usage;\n\n VariableUsageCollector collector(usage, factor);\n\n for(auto& block : function){\n for(auto& quadruple : block->statements){\n collector.collect(quadruple);\n }\n }\n\n return usage;\n}\n\nvoid eddic::mtac::computeBlockUsage(mtac::Function& function, std::unordered_set<mtac::basic_block_p>& usage){\n BasicBlockUsageCollector collector(usage);\n\n for(auto& block : function){\n for(auto& quadruple : block->statements){\n collector.collect(quadruple);\n }\n }\n}\n\nbool eddic::mtac::safe(const std::string& function){\n \/\/These functions are considered as safe because they save\/restore all the registers and does not return anything \n return \n function == \"_F5printI\" || function == \"_F5printF\" || function == \"_F5printS\" || function == \"_F5printC\" ||\n function == \"_F7printlnI\" || function == \"_F7printlnF\" || function == \"_F7printlnS\" || function == \"_F7printlnC\" || \n function == \"_F7println\"; \n}\n\nbool eddic::mtac::erase_result(mtac::Operator op){\n return \n op != mtac::Operator::DOT_ASSIGN \n && op != mtac::Operator::DOT_FASSIGN \n && op != mtac::Operator::DOT_PASSIGN \n && op != mtac::Operator::RETURN\n && op != mtac::Operator::GOTO\n && op != mtac::Operator::NOP\n && op != mtac::Operator::PARAM\n && op != mtac::Operator::CALL\n && op != mtac::Operator::LABEL\n && !(op >= mtac::Operator::IF_UNARY && op <= mtac::Operator::IF_FALSE_FL);\n}\n\nbool eddic::mtac::is_distributive(mtac::Operator op){\n return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;\n}\n\nbool eddic::mtac::is_expression(mtac::Operator op){\n return op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV;\n}\n\nunsigned int eddic::mtac::compute_member_offset(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member){\n return compute_member(context, type, member).first;\n}\n\nstd::pair<unsigned int, std::shared_ptr<const Type>> eddic::mtac::compute_member(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member){\n auto struct_type = context->get_struct(type);\n std::shared_ptr<const Type> member_type;\n unsigned int offset = 0;\n\n do {\n if(struct_type->member_exists(member)){\n member_type = (*struct_type)[member]->type;\n break;\n }\n\n offset += context->self_size_of_struct(struct_type);\n\n struct_type = context->get_struct(struct_type->parent_type);\n } while(struct_type);\n\n eddic_assert(member_type, \"The member must exist\");\n\n offset += context->member_offset(struct_type, member);\n\n return std::make_pair(offset, member_type);\n}\n\n\/\/TODO Use the copy constructor instead\n\nstd::shared_ptr<mtac::Quadruple> mtac::copy(const std::shared_ptr<mtac::Quadruple>& quadruple){\n return std::make_shared<mtac::Quadruple>(*quadruple);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Embedded binary accessors\n *\n * Copyright (c) 2015 Daniel Verkamp\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"narf\/embed.h\"\n\n#include <zlib.h>\n#include <stdio.h>\n\n\nbool narf::embed::uncompress(void* dst, size_t dstSize, const void* src, size_t srcSize) {\n\tz_stream st;\n\n\tst.next_in = static_cast<z_const Bytef*>(const_cast<void*>(src));\n\tst.avail_in = static_cast<uInt>(srcSize);\n\n\tst.next_out = static_cast<Bytef*>(dst);\n\tst.avail_out = static_cast<uInt>(dstSize);\n\n\tst.zalloc = nullptr;\n\tst.zfree = nullptr;\n\n\tif (::inflateInit2(&st, 32) != Z_OK) { \/\/ 32 = autodetect zlib\/gzip\n\t\treturn false;\n\t}\n\n\tif (::inflate(&st, Z_FINISH) != Z_STREAM_END) {\n\t\treturn false;\n\t}\n\n\tif (st.total_out != dstSize) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n<commit_msg>embed: remove use of z_const<commit_after>\/*\n * Embedded binary accessors\n *\n * Copyright (c) 2015 Daniel Verkamp\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"narf\/embed.h\"\n\n#include <zlib.h>\n#include <stdio.h>\n\n\nbool narf::embed::uncompress(void* dst, size_t dstSize, const void* src, size_t srcSize) {\n\tz_stream st;\n\n\tst.next_in = static_cast<Bytef*>(const_cast<void*>(src));\n\tst.avail_in = static_cast<uInt>(srcSize);\n\n\tst.next_out = static_cast<Bytef*>(dst);\n\tst.avail_out = static_cast<uInt>(dstSize);\n\n\tst.zalloc = nullptr;\n\tst.zfree = nullptr;\n\n\tif (::inflateInit2(&st, 32) != Z_OK) { \/\/ 32 = autodetect zlib\/gzip\n\t\treturn false;\n\t}\n\n\tif (::inflate(&st, Z_FINISH) != Z_STREAM_END) {\n\t\treturn false;\n\t}\n\n\tif (st.total_out != dstSize) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"net\/telnet.h\"\n\n#include <arpa\/telnet.h>\n\nstatic constexpr std::size_t telnet_option_count = 256;\n\nstruct rethinkmud::net::connections::telnet::telnet_info\n{\n \/\/ What we do, and don't do\n bool options[telnet_option_count] = { false };\n\n \/\/ Options we have sent and are waiting for reply on\n bool sent_will[telnet_option_count] = { false };\n bool sent_wont[telnet_option_count] = { false };\n bool sent_do[telnet_option_count] = { false };\n bool sent_dont[telnet_option_count] = { false };\n};\n\nvoid rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info)\n{\n delete info;\n}\n\nvoid rethinkmud::net::connections::telnet::start()\n{\n std::clog << \"Starting telnet connection\\n\";\n info_.reset(new telnet_info);\n\n tcp::start();\n}\n\nvoid rethinkmud::net::connections::telnet::input(std::vector<char> data)\n{\n \/\/ Parse the input for telnet command sequence\n \/\/ Copy the non-telnet data to a new container\n \/\/ For now we assume that all sequences are complete\n\n std::string input;\n\n for (auto i = std::begin(data); i != std::end(data); ++i)\n {\n if (static_cast<unsigned char>(*i) == IAC)\n {\n \/\/ TODO: Handle the telnet stuff\n }\n else\n input += *i;\n }\n\n write(\"You wrote: \" + input);\n\n \/\/ TODO: Split the input into lines, and add each line into a queue\n}\n\nvoid rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option)\n{\n uint8_t const data[] = {\n IAC,\n command,\n option\n };\n write(data, sizeof(data));\n}\n\nvoid rethinkmud::net::connections::telnet::send_do(uint8_t option)\n{\n if (!info_->sent_do[option])\n {\n send_option(DO, option);\n info_->sent_do[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_dont(uint8_t option)\n{\n if (!info_->sent_dont[option])\n {\n send_option(DONT, option);\n info_->sent_dont[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_will(uint8_t option)\n{\n if (!info_->sent_will[option])\n {\n send_option(WILL, option);\n info_->sent_will[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_wont(uint8_t option)\n{\n if (!info_->sent_wont[option])\n {\n send_option(WONT, option);\n info_->sent_wont[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::echo_on()\n{\n send_wont(ECHO);\n send_do(ECHO);\n}\n\nvoid rethinkmud::net::connections::telnet::echo_off()\n{\n send_will(ECHO);\n send_dont(ECHO);\n}\n<commit_msg>Simple command handling for debugging purposes<commit_after>#include \"net\/telnet.h\"\n\n#include <arpa\/telnet.h>\n\nstatic constexpr std::size_t telnet_option_count = 256;\n\nstruct rethinkmud::net::connections::telnet::telnet_info\n{\n \/\/ What we do, and don't do\n bool options[telnet_option_count] = { false };\n\n \/\/ Options we have sent and are waiting for reply on\n bool sent_will[telnet_option_count] = { false };\n bool sent_wont[telnet_option_count] = { false };\n bool sent_do[telnet_option_count] = { false };\n bool sent_dont[telnet_option_count] = { false };\n};\n\nvoid rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info)\n{\n delete info;\n}\n\nvoid rethinkmud::net::connections::telnet::start()\n{\n std::clog << \"Starting telnet connection\\n\";\n info_.reset(new telnet_info);\n\n tcp::start();\n}\n\nvoid rethinkmud::net::connections::telnet::input(std::vector<char> data)\n{\n \/\/ Parse the input for telnet command sequence\n \/\/ Copy the non-telnet data to a new container\n \/\/ For now we assume that all sequences are complete\n\n std::string input;\n\n for (auto i = std::begin(data); i != std::end(data); ++i)\n {\n if (static_cast<unsigned char>(*i) == IAC)\n {\n \/\/ TODO: Handle the telnet stuff\n }\n else\n input += *i;\n }\n\n if (input == \"echo off\\r\\n\")\n echo_off();\n else if (input == \"echo on\\r\\n\")\n echo_on();\n else\n write(\"You wrote: \" + input);\n\n \/\/ TODO: Split the input into lines, and add each line into a queue\n}\n\nvoid rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option)\n{\n uint8_t const data[] = {\n IAC,\n command,\n option\n };\n write(data, sizeof(data));\n}\n\nvoid rethinkmud::net::connections::telnet::send_do(uint8_t option)\n{\n if (!info_->sent_do[option])\n {\n send_option(DO, option);\n info_->sent_do[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_dont(uint8_t option)\n{\n if (!info_->sent_dont[option])\n {\n send_option(DONT, option);\n info_->sent_dont[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_will(uint8_t option)\n{\n if (!info_->sent_will[option])\n {\n send_option(WILL, option);\n info_->sent_will[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::send_wont(uint8_t option)\n{\n if (!info_->sent_wont[option])\n {\n send_option(WONT, option);\n info_->sent_wont[option] = true;\n }\n}\n\nvoid rethinkmud::net::connections::telnet::echo_on()\n{\n send_wont(TELOPT_ECHO);\n send_do(TELOPT_ECHO);\n}\n\nvoid rethinkmud::net::connections::telnet::echo_off()\n{\n send_will(TELOPT_ECHO);\n send_dont(TELOPT_ECHO);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $RCSfile: $\n\/\/ $Revision: $ $Date: $\n\/\/ Auth: Samson Bonfante (bonfante@steptools.com)\n\/\/ \n\/\/ Copyright (c) 1991-2016 by STEP Tools Inc. \n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"nodeFinder.h\"\n#include \"nodeUtils.h\"\nFinder *Finder::_singleton = nullptr;\n\nNAN_METHOD(Finder::New)\n{\n\tif (info.IsConstructCall())\n\t{\n\t\tif (!info[0]->IsUndefined())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (_singleton == nullptr)\n\t\t\t_singleton = new Finder();\n\t\t_singleton->Wrap(info.This());\n\t\tinfo.GetReturnValue().Set(info.This());\n\t}\n\telse\n\t{\n\t\treturn;\n\t}\n}\n\nNAN_MODULE_INIT(Finder::Init)\n{\n\tv8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n\ttpl->SetClassName(Nan::New(\"Finder\").ToLocalChecked());\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureID\", GetFeatureID);\n\tNan::SetPrototypeMethod(tpl, \"GetMainWorkplan\", GetMainWorkplan);\n\tNan::SetPrototypeMethod(tpl, \"OpenProject\", OpenProject);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsP21\", SaveAsP21);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsModules\", SaveAsModules);\n\n\tconstructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());\n\tNan::Set(target, Nan::New(\"Finder\").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());\n}\n\nNAN_METHOD(Finder::GetMainWorkplan) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (!info[0]->IsUndefined()) \/\/Function shouldn't get any arguments.\n\t\treturn;\n\tint rtn = 0;\n\tint sz;\n\tif (!find->_find->main(rtn, sz))\n\t\treturn;\/\/Error in c++ code\n\tinfo.GetReturnValue().Set(rtn);\n\treturn;\n}\n\nNAN_METHOD(Finder::OpenProject) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (info.Length() != 1) \/\/Function should get one argument.\n\t\treturn;\n\tif (!info[0]->IsString())\n\t\treturn;\n\tchar * fname = 0;\n\tssize_t fnamelen = v8StringToChar(info[0], fname);\n\tif(!find->_find->search(fname)) \/\/TODO: Handle Error.\n\t\treturn;\n\treturn; \/\/Success finding, return.\n}\n\nNAN_METHOD(Finder::SaveAsP21)\n{\n\tFinder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\n\tif (!info[0]->IsUndefined())\n\t\treturn;\n\n\tif (!info[0]->IsString())\n\t\treturn;\n\n\tv8::Local<v8::String> file_name = info[0]->ToString();\n\tchar* file_name_utf8;\n\tv8StringToChar(file_name, file_name_utf8);\n\n\n\tif (!find->_find->save_file(file_name_utf8, false)) \/\/Throw Exception\n\t\treturn;\n}\n<commit_msg>Finder::SaveAsModules Implementation Added<commit_after>\/\/ $RCSfile: $\n\/\/ $Revision: $ $Date: $\n\/\/ Auth: Samson Bonfante (bonfante@steptools.com)\n\/\/ \n\/\/ Copyright (c) 1991-2016 by STEP Tools Inc. \n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"nodeFinder.h\"\n#include \"nodeUtils.h\"\nFinder *Finder::_singleton = nullptr;\n\nNAN_METHOD(Finder::New)\n{\n\tif (info.IsConstructCall())\n\t{\n\t\tif (!info[0]->IsUndefined())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (_singleton == nullptr)\n\t\t\t_singleton = new Finder();\n\t\t_singleton->Wrap(info.This());\n\t\tinfo.GetReturnValue().Set(info.This());\n\t}\n\telse\n\t{\n\t\treturn;\n\t}\n}\n\nNAN_MODULE_INIT(Finder::Init)\n{\n\tv8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n\ttpl->SetClassName(Nan::New(\"Finder\").ToLocalChecked());\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureID\", GetFeatureID);\n\tNan::SetPrototypeMethod(tpl, \"GetMainWorkplan\", GetMainWorkplan);\n\tNan::SetPrototypeMethod(tpl, \"OpenProject\", OpenProject);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsP21\", SaveAsP21);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsModules\", SaveAsModules);\n\n\tconstructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());\n\tNan::Set(target, Nan::New(\"Finder\").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());\n}\n\nNAN_METHOD(Finder::GetMainWorkplan) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (!info[0]->IsUndefined()) \/\/Function shouldn't get any arguments.\n\t\treturn;\n\tint rtn = 0;\n\tint sz;\n\tif (!find->_find->main(rtn, sz))\n\t\treturn;\/\/Error in c++ code\n\tinfo.GetReturnValue().Set(rtn);\n\treturn;\n}\n\nNAN_METHOD(Finder::OpenProject) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (info.Length() != 1) \/\/Function should get one argument.\n\t\treturn;\n\tif (!info[0]->IsString())\n\t\treturn;\n\tchar * fname = 0;\n\tssize_t fnamelen = v8StringToChar(info[0], fname);\n\tif(!find->_find->search(fname)) \/\/TODO: Handle Error.\n\t\treturn;\n\treturn; \/\/Success finding, return.\n}\n\nNAN_METHOD(Finder::SaveAsModules)\n{\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n\n if (!info[0]->IsUndefined())\n\treturn;\n\n if (!info[0]->IsString())\n\treturn;\n\n v8::Local<v8::String> file_name = info[0]->ToString();\n char* file_name_utf8;\n v8StringToChar(file_name, file_name_utf8);\n\n\n if (!find->_find->save_file(file_name_utf8, true)) \/\/Throw Exception\n\treturn;\n}\n\nNAN_METHOD(Finder::SaveAsP21)\n{\n\tFinder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\n\tif (!info[0]->IsUndefined())\n\t\treturn;\n\n\tif (!info[0]->IsString())\n\t\treturn;\n\n\tv8::Local<v8::String> file_name = info[0]->ToString();\n\tchar* file_name_utf8;\n\tv8StringToChar(file_name, file_name_utf8);\n\n\n\tif (!find->_find->save_file(file_name_utf8, false)) \/\/Throw Exception\n\t\treturn;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $RCSfile: $\n\/\/ $Revision: $ $Date: $\n\/\/ Auth: Samson Bonfante (bonfante@steptools.com)\n\/\/ \n\/\/ Copyright (c) 1991-2016 by STEP Tools Inc. \n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"nodeFinder.h\"\n#include \"nodeUtils.h\"\nFinder *Finder::_singleton = nullptr;\n\nNAN_METHOD(Finder::New)\n{\n\tif (info.IsConstructCall())\n\t{\n\t\tif (!info[0]->IsUndefined())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (_singleton == nullptr)\n\t\t\t_singleton = new Finder();\n\t\t_singleton->Wrap(info.This());\n\t\tinfo.GetReturnValue().Set(info.This());\n\t}\n\telse\n\t{\n\t\treturn;\n\t}\n}\n\nNAN_MODULE_INIT(Finder::Init)\n{\n\tv8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n\ttpl->SetClassName(Nan::New(\"Finder\").ToLocalChecked());\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsInches\", APIUnitsInches);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsMM\", APIUnitsMM);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsNative\", APIUnitsNative);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsFeed\", APIUnitsFeed);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsSpeed\", APIUnitsSpeed);\n\tNan::SetPrototypeMethod(tpl, \"GetCompoundFeatureCount\", GetCompoundFeatureCount);\n\tNan::SetPrototypeMethod(tpl, \"GetFaceEdgeCount\", GetFaceEdgeCount);\n\tNan::SetPrototypeMethod(tpl, \"GetFaceEdgeNextPoint\", GetFaceEdgeCount);\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureID\", GetFeatureID);\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureName\", GetFeatureName);\n\tNan::SetPrototypeMethod(tpl, \"GetMainWorkplan\", GetMainWorkplan);\n\tNan::SetPrototypeMethod(tpl, \"GetProcessFeed\", GetProcessFeed);\n\tNan::SetPrototypeMethod(tpl, \"GetProcessFeedUnit\", GetProcessFeedUnit);\n\tNan::SetPrototypeMethod(tpl, \"OpenProject\", OpenProject);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsModules\", SaveAsModules);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsP21\", SaveAsP21);\n\tconstructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());\n\tNan::Set(target, Nan::New(\"Finder\").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());\n}\n\nNAN_METHOD(Finder::APIUnitsFeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (!find) \/\/Throw Exception\n\treturn;\n if (info.Length() != 1) \/\/Function takes one argument\n\treturn;\n if (info[0]->IsUndefined()) \/\/Argument should exist\n\treturn;\n if (!info[0]->IsString()) \/\/Throw Exception\n\treturn;\n char * b;\n size_t len = v8StringToChar(info[0], b);\n if (!find->_find->api_unit_feed(b)) \/\/Throw Exception\n\treturn;\n delete[] b;\n}\nNAN_METHOD(Finder::APIUnitsInches) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_inch()) {\n\treturn; \/\/throw error\n }\n return;\n\n}\n\nNAN_METHOD(Finder::APIUnitsMM) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_mm()) {\n\treturn; \/\/throw error\n }\n return;\n}\n\nNAN_METHOD(Finder::APIUnitsNative) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_native()) {\n\treturn; \/\/throw error\n }\n return;\n}\n\nNAN_METHOD(Finder::APIUnitsSpeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (!find) \/\/Throw Exception\n\treturn;\n if (info.Length() != 1) \/\/Function takes one argument\n\treturn;\n if (info[0]->IsUndefined()) \/\/Argument should exist\n\treturn;\n if (!info[0]->IsString()) \/\/Throw Exception\n\treturn;\n char * b;\n size_t len = v8StringToChar(info[0], b);\n if (!find->_find->api_unit_speed(b)) \/\/Throw Exception\n\treturn;\n delete[] b;\n}\n\n\n\nNAN_METHOD(Finder::GetCompoundFeatureCount) {\n\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) {\n\treturn; \/\/Throw an exception\n }\n if (info.Length() != 1) { \/\/ Needs one argument\n\treturn; \/\/ Throw an exception\n }\n if (!info[0]->IsInt32()) { \/\/ argument of wrong type\n\treturn; \/\/Throw exception\n }\n int size = 0;\n int feature_id = 0;\n double x;\n double y;\n double z;\n\n if (!find->_find->first_feature_in_compound(info[0]->Int32Value(), feature_id, size, x, y, z)) {\n\treturn; \/\/throw Error\n }\n\n info.GetReturnValue().Set(size);\n return;\n}\n\nNAN_METHOD(Finder::GetExecutableDistance)\n{\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/ Throw exception\n\t\treturn;\n\n\tif (info.Length() != 1) \/\/ incorrect number of arguments\n\t\treturn;\n\n\tif (!info[0]->IsNumber()) \/\/ invalid argument\n\t\treturn;\n\n\t\/\/ get this executable's id\n\tint64_t exe_id = info[0]->IntegerValue();\n\n\tdouble distance = 0.0;\n\tdouble over_time, base_time;\n\n\tconst char *str1, *str2;\n\n\tif (!find->_find->compute_best_feed_time(\n\t\t(int)exe_id, distance, base_time, over_time, str1, str2\n\t\t))\t\/\/ cpp error\n\t\treturn;\n\n\tinfo.GetReturnValue().Set(distance);\n\treturn;\n}\n\nNAN_METHOD(Finder::GetFaceEdgeCount)\n{\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Needs one arg\n\treturn;\n\n int count = 0;\n double dummy1, dummy2, dummy3;\n if (!find->_find->first_face_edge_point(info[0]->Int32Value(), count, dummy1, dummy2, dummy3))\n\treturn;\n\n info.GetReturnValue().Set(count);\n return;\n}\n\n\/\/{ret_x1:double, ret_y1:double, ret_z1:double, ret_x2:double, ret_y2:double, ret_z2:double}\nNAN_METHOD(Finder::GetFaceEdgeNextPoint)\n{\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n if (info.Length() < 8) \/\/Needs 8 arg\n\treturn;\n\n double x1 = 0.0;\n double y1 = 0.0;\n double z1 = 0.0;\n double x2 = 0.0;\n double y2 = 0.0;\n double z2 = 0.0;\n\n if (!find->_find->next_face_edge_point(Nan::To<int32_t>(info[0]).FromJust(),\n\tNan::To<int32_t>(info[1]).FromJust(), x1, y1, z1, x2, y2, z2)) \/\/Throw Exception\n\treturn;\n\n v8::Local<v8::Object> jsonReturn = Nan::New<v8::Object>();\n jsonReturn->Set(CharTov8String(\"ret_x1\"), info[2]);\n jsonReturn->Set(CharTov8String(\"ret_y1\"), info[3]);\n jsonReturn->Set(CharTov8String(\"ret_z1\"), info[4]);\n jsonReturn->Set(CharTov8String(\"ret_x2\"), info[5]);\n jsonReturn->Set(CharTov8String(\"ret_y2\"), info[6]);\n jsonReturn->Set(CharTov8String(\"ret_z2\"), info[7]);\n\n info.GetReturnValue().Set(jsonReturn);\n return;\n}\n\nNAN_METHOD(Finder::GetFeatureID) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (info.Length() != 1)\n\treturn;\n if (info[0]->IsUndefined())\n\treturn;\n if (!info[0]->IsInt32())\n\treturn;\n\n int feature_id = 0;\n\n if (!find->_find->feature_id(info[0]->Int32Value(), feature_id))\n\treturn;\n\n info.GetReturnValue().Set(feature_id);\n return;\n}\n\nNAN_METHOD(Finder::GetFeatureName) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (info.Length() != 1)\n\treturn;\n if (info[0]->IsUndefined())\n\treturn;\n if (!info[0]->IsInt32())\n\treturn;\n\n const char * name = 0;\n\n if (!find->_find->feature_name(info[0]->Int32Value(), name))\n\treturn;\n\n info.GetReturnValue().Set(CharTov8String((char *)name));\n return;\n}\n\nNAN_METHOD(Finder::GetMainWorkplan) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (!info[0]->IsUndefined()) \/\/Function shouldn't get any arguments.\n\t\treturn;\n\tint rtn = 0;\n\tint sz;\n\tif (!find->_find->main(rtn, sz))\n\t\treturn;\/\/Error in c++ code\n\tinfo.GetReturnValue().Set(rtn);\n\treturn;\n}\n\nNAN_METHOD(Finder::GetProcessFeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (info.Length() != 1) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Throw Exception\n\treturn;\n if (!info[0]->IsInt32()) \/\/Throw Exception\n\treturn;\n double feed = 0.0;\n double dummy;\n int ws_id = info[0]->Int32Value();\n if (!find->_find->feed_speed(ws_id, feed, dummy)) \/\/Throw Exception\n\treturn;\n info.GetReturnValue().Set(feed);\n}\n\nNAN_METHOD(Finder::GetProcessFeedUnit) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (info.Length() != 1) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Throw Exception\n\treturn;\n if (!info[0]->IsInt32()) \/\/Throw Exception\n\treturn;\n const char* unit = \"\";\n const char* dummy = \"\";\n int ws_id = info[0]->Int32Value();\n if (!find->_find->feed_speed_unit(ws_id, (const char*&)unit, (const char*&)dummy)) \/\/Throw Exception\n\treturn;\n info.GetReturnValue().Set(CharTov8String((char *)unit));\n}\n\nNAN_METHOD(Finder::OpenProject) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (info.Length() != 1) \/\/Function should get one argument.\n\t\treturn;\n\tif (!info[0]->IsString())\n\t\treturn;\n\tchar * fname = 0;\n\tssize_t fnamelen = v8StringToChar(info[0], fname);\n\tif(!find->_find->search(fname)) \/\/TODO: Handle Error.\n\t\treturn;\n\treturn; \/\/Success finding, return.\n}\n\nNAN_METHOD(Finder::SaveAsModules)\n{\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n\n if (!info[0]->IsUndefined())\n\treturn;\n\n if (!info[0]->IsString())\n\treturn;\n\n char* file_name_utf8;\n v8StringToChar(info[0], file_name_utf8);\n\n\n if (!find->_find->save_file(file_name_utf8, true)) \/\/Throw Exception\n\treturn;\n}\n\nNAN_METHOD(Finder::SaveAsP21)\n{\n\tFinder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\n\tif (!info[0]->IsUndefined())\n\t\treturn;\n\n\tif (!info[0]->IsString())\n\t\treturn;\n\n\tchar* file_name_utf8;\n\tv8StringToChar(info[0], file_name_utf8);\n\n\n\tif (!find->_find->save_file(file_name_utf8, false)) \/\/Throw Exception\n\t\treturn;\n}<commit_msg>Added GetExecutableDistance to Init()<commit_after>\/\/ $RCSfile: $\n\/\/ $Revision: $ $Date: $\n\/\/ Auth: Samson Bonfante (bonfante@steptools.com)\n\/\/ \n\/\/ Copyright (c) 1991-2016 by STEP Tools Inc. \n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"nodeFinder.h\"\n#include \"nodeUtils.h\"\nFinder *Finder::_singleton = nullptr;\n\nNAN_METHOD(Finder::New)\n{\n\tif (info.IsConstructCall())\n\t{\n\t\tif (!info[0]->IsUndefined())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (_singleton == nullptr)\n\t\t\t_singleton = new Finder();\n\t\t_singleton->Wrap(info.This());\n\t\tinfo.GetReturnValue().Set(info.This());\n\t}\n\telse\n\t{\n\t\treturn;\n\t}\n}\n\nNAN_MODULE_INIT(Finder::Init)\n{\n\tv8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n\ttpl->SetClassName(Nan::New(\"Finder\").ToLocalChecked());\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsInches\", APIUnitsInches);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsMM\", APIUnitsMM);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsNative\", APIUnitsNative);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsFeed\", APIUnitsFeed);\n\tNan::SetPrototypeMethod(tpl, \"APIUnitsSpeed\", APIUnitsSpeed);\n\tNan::SetPrototypeMethod(tpl, \"GetCompoundFeatureCount\", GetCompoundFeatureCount);\n\tNan::SetPrototypeMethod(tpl, \"GetExecutableDistance\", GetExecutableDistance);\n\tNan::SetPrototypeMethod(tpl, \"GetFaceEdgeCount\", GetFaceEdgeCount);\n\tNan::SetPrototypeMethod(tpl, \"GetFaceEdgeNextPoint\", GetFaceEdgeCount);\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureID\", GetFeatureID);\n\tNan::SetPrototypeMethod(tpl, \"GetFeatureName\", GetFeatureName);\n\tNan::SetPrototypeMethod(tpl, \"GetMainWorkplan\", GetMainWorkplan);\n\tNan::SetPrototypeMethod(tpl, \"GetProcessFeed\", GetProcessFeed);\n\tNan::SetPrototypeMethod(tpl, \"GetProcessFeedUnit\", GetProcessFeedUnit);\n\tNan::SetPrototypeMethod(tpl, \"OpenProject\", OpenProject);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsModules\", SaveAsModules);\n\tNan::SetPrototypeMethod(tpl, \"SaveAsP21\", SaveAsP21);\n\tconstructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());\n\tNan::Set(target, Nan::New(\"Finder\").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());\n}\n\nNAN_METHOD(Finder::APIUnitsFeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (!find) \/\/Throw Exception\n\treturn;\n if (info.Length() != 1) \/\/Function takes one argument\n\treturn;\n if (info[0]->IsUndefined()) \/\/Argument should exist\n\treturn;\n if (!info[0]->IsString()) \/\/Throw Exception\n\treturn;\n char * b;\n size_t len = v8StringToChar(info[0], b);\n if (!find->_find->api_unit_feed(b)) \/\/Throw Exception\n\treturn;\n delete[] b;\n}\nNAN_METHOD(Finder::APIUnitsInches) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_inch()) {\n\treturn; \/\/throw error\n }\n return;\n\n}\n\nNAN_METHOD(Finder::APIUnitsMM) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_mm()) {\n\treturn; \/\/throw error\n }\n return;\n}\n\nNAN_METHOD(Finder::APIUnitsNative) {\n\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (find == 0) {\n\treturn; \/\/ Throw Exception\n }\n if (!(info[0]->IsUndefined())) { \/\/ function has 0 arguements\n\treturn; \/\/Throw Exeption\n }\n if (!find->_find->api_unit_native()) {\n\treturn; \/\/throw error\n }\n return;\n}\n\nNAN_METHOD(Finder::APIUnitsSpeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (!find) \/\/Throw Exception\n\treturn;\n if (info.Length() != 1) \/\/Function takes one argument\n\treturn;\n if (info[0]->IsUndefined()) \/\/Argument should exist\n\treturn;\n if (!info[0]->IsString()) \/\/Throw Exception\n\treturn;\n char * b;\n size_t len = v8StringToChar(info[0], b);\n if (!find->_find->api_unit_speed(b)) \/\/Throw Exception\n\treturn;\n delete[] b;\n}\n\n\n\nNAN_METHOD(Finder::GetCompoundFeatureCount) {\n\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) {\n\treturn; \/\/Throw an exception\n }\n if (info.Length() != 1) { \/\/ Needs one argument\n\treturn; \/\/ Throw an exception\n }\n if (!info[0]->IsInt32()) { \/\/ argument of wrong type\n\treturn; \/\/Throw exception\n }\n int size = 0;\n int feature_id = 0;\n double x;\n double y;\n double z;\n\n if (!find->_find->first_feature_in_compound(info[0]->Int32Value(), feature_id, size, x, y, z)) {\n\treturn; \/\/throw Error\n }\n\n info.GetReturnValue().Set(size);\n return;\n}\n\nNAN_METHOD(Finder::GetExecutableDistance)\n{\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/ Throw exception\n\t\treturn;\n\n\tif (info.Length() != 1) \/\/ incorrect number of arguments\n\t\treturn;\n\n\tif (!info[0]->IsNumber()) \/\/ invalid argument\n\t\treturn;\n\n\t\/\/ get this executable's id\n\tint64_t exe_id = info[0]->IntegerValue();\n\n\tdouble distance = 0.0;\n\tdouble over_time, base_time;\n\n\tconst char *str1, *str2;\n\n\tif (!find->_find->compute_best_feed_time(\n\t\t(int)exe_id, distance, base_time, over_time, str1, str2\n\t\t))\t\/\/ cpp error\n\t\treturn;\n\n\tinfo.GetReturnValue().Set(distance);\n\treturn;\n}\n\nNAN_METHOD(Finder::GetFaceEdgeCount)\n{\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Needs one arg\n\treturn;\n\n int count = 0;\n double dummy1, dummy2, dummy3;\n if (!find->_find->first_face_edge_point(info[0]->Int32Value(), count, dummy1, dummy2, dummy3))\n\treturn;\n\n info.GetReturnValue().Set(count);\n return;\n}\n\n\/\/{ret_x1:double, ret_y1:double, ret_z1:double, ret_x2:double, ret_y2:double, ret_z2:double}\nNAN_METHOD(Finder::GetFaceEdgeNextPoint)\n{\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n if (info.Length() < 8) \/\/Needs 8 arg\n\treturn;\n\n double x1 = 0.0;\n double y1 = 0.0;\n double z1 = 0.0;\n double x2 = 0.0;\n double y2 = 0.0;\n double z2 = 0.0;\n\n if (!find->_find->next_face_edge_point(Nan::To<int32_t>(info[0]).FromJust(),\n\tNan::To<int32_t>(info[1]).FromJust(), x1, y1, z1, x2, y2, z2)) \/\/Throw Exception\n\treturn;\n\n v8::Local<v8::Object> jsonReturn = Nan::New<v8::Object>();\n jsonReturn->Set(CharTov8String(\"ret_x1\"), info[2]);\n jsonReturn->Set(CharTov8String(\"ret_y1\"), info[3]);\n jsonReturn->Set(CharTov8String(\"ret_z1\"), info[4]);\n jsonReturn->Set(CharTov8String(\"ret_x2\"), info[5]);\n jsonReturn->Set(CharTov8String(\"ret_y2\"), info[6]);\n jsonReturn->Set(CharTov8String(\"ret_z2\"), info[7]);\n\n info.GetReturnValue().Set(jsonReturn);\n return;\n}\n\nNAN_METHOD(Finder::GetFeatureID) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (info.Length() != 1)\n\treturn;\n if (info[0]->IsUndefined())\n\treturn;\n if (!info[0]->IsInt32())\n\treturn;\n\n int feature_id = 0;\n\n if (!find->_find->feature_id(info[0]->Int32Value(), feature_id))\n\treturn;\n\n info.GetReturnValue().Set(feature_id);\n return;\n}\n\nNAN_METHOD(Finder::GetFeatureName) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\n if (info.Length() != 1)\n\treturn;\n if (info[0]->IsUndefined())\n\treturn;\n if (!info[0]->IsInt32())\n\treturn;\n\n const char * name = 0;\n\n if (!find->_find->feature_name(info[0]->Int32Value(), name))\n\treturn;\n\n info.GetReturnValue().Set(CharTov8String((char *)name));\n return;\n}\n\nNAN_METHOD(Finder::GetMainWorkplan) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (!info[0]->IsUndefined()) \/\/Function shouldn't get any arguments.\n\t\treturn;\n\tint rtn = 0;\n\tint sz;\n\tif (!find->_find->main(rtn, sz))\n\t\treturn;\/\/Error in c++ code\n\tinfo.GetReturnValue().Set(rtn);\n\treturn;\n}\n\nNAN_METHOD(Finder::GetProcessFeed) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (info.Length() != 1) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Throw Exception\n\treturn;\n if (!info[0]->IsInt32()) \/\/Throw Exception\n\treturn;\n double feed = 0.0;\n double dummy;\n int ws_id = info[0]->Int32Value();\n if (!find->_find->feed_speed(ws_id, feed, dummy)) \/\/Throw Exception\n\treturn;\n info.GetReturnValue().Set(feed);\n}\n\nNAN_METHOD(Finder::GetProcessFeedUnit) {\n Finder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (info.Length() != 1) \/\/Throw Exception\n\treturn;\n if (info[0]->IsUndefined()) \/\/Throw Exception\n\treturn;\n if (!info[0]->IsInt32()) \/\/Throw Exception\n\treturn;\n const char* unit = \"\";\n const char* dummy = \"\";\n int ws_id = info[0]->Int32Value();\n if (!find->_find->feed_speed_unit(ws_id, (const char*&)unit, (const char*&)dummy)) \/\/Throw Exception\n\treturn;\n info.GetReturnValue().Set(CharTov8String((char *)unit));\n}\n\nNAN_METHOD(Finder::OpenProject) {\n\tFinder* find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\tif (info.Length() != 1) \/\/Function should get one argument.\n\t\treturn;\n\tif (!info[0]->IsString())\n\t\treturn;\n\tchar * fname = 0;\n\tssize_t fnamelen = v8StringToChar(info[0], fname);\n\tif(!find->_find->search(fname)) \/\/TODO: Handle Error.\n\t\treturn;\n\treturn; \/\/Success finding, return.\n}\n\nNAN_METHOD(Finder::SaveAsModules)\n{\n Finder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n if (find == 0) \/\/Throw Exception\n\treturn;\n\n if (!info[0]->IsUndefined())\n\treturn;\n\n if (!info[0]->IsString())\n\treturn;\n\n char* file_name_utf8;\n v8StringToChar(info[0], file_name_utf8);\n\n\n if (!find->_find->save_file(file_name_utf8, true)) \/\/Throw Exception\n\treturn;\n}\n\nNAN_METHOD(Finder::SaveAsP21)\n{\n\tFinder * find = Nan::ObjectWrap::Unwrap<Finder>(info.This());\n\tif (find == 0) \/\/Throw Exception\n\t\treturn;\n\n\tif (!info[0]->IsUndefined())\n\t\treturn;\n\n\tif (!info[0]->IsString())\n\t\treturn;\n\n\tchar* file_name_utf8;\n\tv8StringToChar(info[0], file_name_utf8);\n\n\n\tif (!find->_find->save_file(file_name_utf8, false)) \/\/Throw Exception\n\t\treturn;\n}<|endoftext|>"} {"text":"<commit_before>#include <object\/global.hh>\n#include <object\/slot.hh>\n#include <object\/symbols.hh>\n\nnamespace object\n{\n rObject\n Slot::property_get(libport::Symbol k)\n {\n if (k == SYMBOL(changed))\n {\n if (!changed_)\n {\n CAPTURE_GLOBAL(Event);\n changed_ = Event->call(SYMBOL(new));\n }\n return changed_;\n }\n properties_type::iterator it = properties_.find(k);\n if (it == properties_.end())\n return 0;\n else\n return it->second;\n }\n\n bool\n Slot::property_has(libport::Symbol k)\n {\n return properties_.find(k) != properties_.end();\n }\n\n bool\n Slot::property_set(libport::Symbol k, rObject value)\n {\n bool res = !property_has(k);\n properties_[k] = value;\n return res;\n }\n\n void\n Slot::property_remove(libport::Symbol k)\n {\n properties_.erase(k);\n }\n\n Slot::properties_type&\n Slot::properties_get()\n {\n return properties_;\n }\n}\n\n<commit_msg>Add forgotten include.<commit_after>#include <object\/global.hh>\n#include <object\/slot.hh>\n#include <object\/slot.hxx>\n#include <object\/symbols.hh>\n\nnamespace object\n{\n rObject\n Slot::property_get(libport::Symbol k)\n {\n if (k == SYMBOL(changed))\n {\n if (!changed_)\n {\n CAPTURE_GLOBAL(Event);\n changed_ = Event->call(SYMBOL(new));\n }\n return changed_;\n }\n properties_type::iterator it = properties_.find(k);\n if (it == properties_.end())\n return 0;\n else\n return it->second;\n }\n\n bool\n Slot::property_has(libport::Symbol k)\n {\n return properties_.find(k) != properties_.end();\n }\n\n bool\n Slot::property_set(libport::Symbol k, rObject value)\n {\n bool res = !property_has(k);\n properties_[k] = value;\n return res;\n }\n\n void\n Slot::property_remove(libport::Symbol k)\n {\n properties_.erase(k);\n }\n\n Slot::properties_type&\n Slot::properties_get()\n {\n return properties_;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifdef COMPONENT_PARSER_H\n#ifndef COMPONENT_PARSER_OPERATION_H\n#define COMPONENT_PARSER_OPERATION_H\n\nnamespace Operations {\n\tconst Token nullval(\"null\", KEYWORD, CONSTANT);\n\n\tToken add(Token, Token);\n\tToken subtract(Token, Token);\n\tToken multiply(Token, Token);\n\tToken divide(Token, Token);\n\tToken modulo(Token, Token);\n\tToken mathOperator(String, Token, Token);\n\n\tToken compare(String, Token, Token);\n\tToken logical(String, Token, Token);\n\n\tint priority(String);\n\tint comparePriority(String, String);\n\n bool isInteger(Token);\n\tdouble toNumber(Token);\n\tString toString(Token);\n\tlong toInteger(Token);\n\n};\n\nToken Operations::mathOperator(String op, Token a, Token b) {\/*\n\tif (op == \"+\") return add(a, b);\n\tif (op == \"-\") return subtract(a, b);\n\tif (op == \"*\") return multiply(a, b);\n\tif (op == \"\/\") return divide(a, b);\n\tif (op == \"%\") return modulo(a, b);\n\t*\/\n\treturn nullval;\n}\n\nint Operations::priority(String op) {\n\tif (op == \".\") return 6;\n\tif (op == \"++\" || op == \"--\") return 5;\n\tif (op == \"*\" || op == \"\/\" || op == \"%\") return 4;\n if (op == \"+\" || op == \"-\") return 3;\n if (op.substr(0,2) == \"==\" || op.substr(0, 2) == \"!=\" || op[0] == '<' || op[0] == '>') return 2;\n if (op == \"!\" || op == \"&&\" || op == \"||\" || op == \"=\" || op[1] == '=') return 1;\n return 0;\n}\n\nint Operations::comparePriority(String a, String b) {\n\treturn priority(a) - priority(b);\n}\n\nbool Operations::isInteger(Token t) {\n if(t.value().indexOf(\".\") == -1) return true;\n return false;\n}\n\ndouble Operations::toNumber(Token t) {\n if(t.subtype() != NUMBER) return 0.0;\n double val = 0.0,beginning = 0;\n if(t.value()[0] == '-') beginning = 1;\n if(isInteger(t)){\n for(int i = t.value().length()-1, j = 1;i >= beginning;i--, j *= 10) {\n val += double((t.value()[i] - '0') * j);\n }\n if(beginning == 1) val *= -1.0;\n return val;\n }\n else{\n long long pos=t.value().indexOf(\".\");\n for(int i = pos-1, j = 1;i >= beginning;i--, j *= 10) {\n val += double((t.value()[i] - '0') * j);\n }\n double j = 0.1;\n for(int i = pos+1;i < t.value().length();i++, j \/= 10.0){\n val += double(t.value()[i]-'0') * j;\n }\n if(beginning == 1) val *= -1.0;\n return val;\n }\n}\n\nlong Operations::toInteger(Token t) {\n if(!isInteger(t)) return 0;\n return int(toNumber(t));\n}\n\nString Operations::toString(Token t) {\n if(t.subtype() != STRING) return \"\";\n return t.value().substr(1, t.value().length() - 2);\n}\n\n#endif \/* COMPONENT_PARSER_OPERATION_H *\/\n#endif \/* COMPONENT_PARSER_H *\/\n<commit_msg>remove deprecated functions<commit_after>#ifdef COMPONENT_PARSER_H\n#ifndef COMPONENT_PARSER_OPERATION_H\n#define COMPONENT_PARSER_OPERATION_H\n\nnamespace Operations {\n\tconst Token nullval(\"null\", KEYWORD, CONSTANT);\n\n\tToken add(Token, Token);\n\tToken subtract(Token, Token);\n\tToken multiply(Token, Token);\n\tToken divide(Token, Token);\n\tToken modulo(Token, Token);\n\tToken mathOperator(String, Token, Token);\n\n\tToken compare(String, Token, Token);\n\tToken logical(String, Token, Token);\n\n\tint priority(String);\n\tint comparePriority(Token, Token);\n\n};\n\nToken Operations::mathOperator(String op, Token a, Token b) {\/*\n\tif (op == \"+\") return add(a, b);\n\tif (op == \"-\") return subtract(a, b);\n\tif (op == \"*\") return multiply(a, b);\n\tif (op == \"\/\") return divide(a, b);\n\tif (op == \"%\") return modulo(a, b);\n\t*\/\n\treturn nullval;\n}\n\nint Operations::priority(String op) {\n\tif (op == \".\") return 6;\n\tif (op == \"++\" || op == \"--\") return 5;\n\tif (op == \"*\" || op == \"\/\" || op == \"%\") return 4;\n\tif (op == \"+\" || op == \"-\") return 3;\n\tif (op.substr(0,2) == \"==\" || op.substr(0, 2) == \"!=\" || op[0] == '<' || op[0] == '>') return 2;\n\tif (op == \"!\" || op == \"&&\" || op == \"||\" || op == \"=\" || op[1] == '=') return 1;\n\treturn 0;\n}\n\nint Operations::comparePriority(Token a, Token b) {\n\treturn priority(a.value()) - priority(b.value());\n}\n\n#endif \/* COMPONENT_PARSER_OPERATION_H *\/\n#endif \/* COMPONENT_PARSER_H *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n Parse gaps in a given BAM alignment and output the resulting gaps in BED or\n VCF formats.\n *\/\n#include <string>\n#include <tclap\/CmdLine.h>\n\nint main(int argc, char** argv) {\n try {\n TCLAP::CmdLine cmd(\"Parse gaps in BAM alignments\", ' ', \"0.1\");\n TCLAP::UnlabeledValueArg<std::string> arg_reference(\"reference\", \"path to a FASTA file for the reference used by the given BAM\", true, \"\", \"reference\");\n TCLAP::UnlabeledValueArg<std::string> arg_bam(\"bam\", \"path to a BAM file to parse\", true, \"\", \"bam\");\n\n cmd.add(arg_reference);\n cmd.add(arg_bam);\n cmd.parse(argc, argv);\n }\n catch (TCLAP::ArgException &e) {\n std::cerr << \"Error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n }\n\n return 0;\n}\n<commit_msg>open reference FASTA and BAM prior to parsing. closes #2.<commit_after>\/**\n Parse gaps in a given BAM alignment and output the resulting gaps in BED or\n VCF formats.\n *\/\n#include <string>\n#include <tclap\/CmdLine.h>\n#include <seqan\/sequence.h>\n#include <seqan\/seq_io.h>\n#include <seqan\/bam_io.h>\n\nusing namespace seqan;\n\nint main(int argc, char** argv) {\n try {\n TCLAP::CmdLine cmd(\"Parse gaps in BAM alignments\", ' ', \"0.1\");\n TCLAP::UnlabeledValueArg<std::string> arg_reference(\"reference\", \"path to a FASTA file for the reference used by the given BAM\", true, \"\", \"reference\");\n TCLAP::UnlabeledValueArg<std::string> arg_bam(\"bam\", \"path to a BAM file to parse\", true, \"\", \"bam\");\n\n cmd.add(arg_reference);\n cmd.add(arg_bam);\n cmd.parse(argc, argv);\n\n \/**\n Open the FASTA file for the given reference.\n *\/\n std::string reference_file_name = arg_reference.getValue();\n FaiIndex fai_index;\n if (!open(fai_index, toCString(reference_file_name))) {\n std::cerr << \"Error: Could not open FASTA index for reference: \" << reference_file_name << std::endl;\n return 1;\n }\n\n \/**\n Open the BAM file of alignments to the given reference.\n *\/\n std::string bam_file_name = arg_bam.getValue();\n BamFileIn bam_file_in;\n if (!open(bam_file_in, toCString(bam_file_name))) {\n std::cerr << \"Error: Could not open BAM: \" << bam_file_name << std::endl;\n return 1;\n }\n }\n catch (TCLAP::ArgException &e) {\n std::cerr << \"Error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"geo2emp.h\"\n\n#include <iostream>\n\n#include <Ni.h>\n#include <NgBody.h>\n#include <NgEmp.h>\n#include <NgString.h>\n\n\/** \n * Process a mesh-type naiad body\n *\/\nint loadMeshShape(GU_Detail& gdp, Ng::ShapeCPtr pShape);\nint loadParticleShape(GU_Detail& gdp, const Ng::Body* pBody);\nint loadFieldShape(GU_Detail& gdp, Ng::ShapeCPtr pShape);\n\n\n\/*************************************************************************************************\/\n\n\/** \n * Load all the Naiad bodies from the EMP file into the Houdini GDP\n *\n *\/\nint loadEmpBodies(std::string filen, GU_Detail& gdp)\n{\n\tNg::EmpReader* empReader = NULL;\t\n\n\tNiBegin(NI_BODY_ONLY);\n\n\t\/\/std::cout << \"loading emp bodies from: \" << filen << std::endl;\n\n\tunsigned int numBodies = 0;\n\ttry\n\t{\n\t\t\/\/std::cout << \"Create new emp reader.\" << std::endl;\n\t\tNg::String ngfilen = Ng::String(filen);\n\t\tempReader = new Ng::EmpReader( ngfilen );\n\t\t\/\/std::cout << \"getting body count...\" << std::endl;\n\t\t\/\/std::cout << \"body count: \" << empReader->bodyCount() << std::endl;\n\t\tnumBodies = empReader->bodyCount();\n\t\t\/\/std::cout << \"Found \" << numBodies << \" bodies in emp file \" << std::endl;\n\n\t}\n\tcatch( std::exception& e )\n\t{\n\t\t\/\/TODO: generate a proper error \/ exit code for Houdini. \n\t\t\/\/ return exit code?\n\t\t\/\/std::cout << \"exception! \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/Run through each body and process them according to their shape type.\n\tconst Ng::Body* pBody = 0;\n\tNg::Body::ConstShapeMapIter shapeIt;\n\tfor (int i = 0; i < numBodies; i++)\n\t{\n\t\tpBody = empReader->constBody(i);\n\t\t\/\/std::cout << i << \":\" << pBody->name() << std::endl;\n\t\t\/\/std::cout << \"number of shapes: \" << pBody->shape_count() << std::endl;\n\n\t\t\/\/Iterate over the shapes for this body.\n\t\tfor (shapeIt = pBody->beginShapes(); shapeIt != pBody->endShapes(); shapeIt++)\n\t\t{\n\t\t\t\/\/std::cout << \"Shape type: \" << shapeIt->first << std::endl;\n\t\t\tif (shapeIt->first == \"Particle\")\n\t\t\t{\n\t\t\t\tloadParticleShape(gdp, pBody);\n\t\t\t}\n\t\t\telse if (shapeIt->first == \"Field\")\n\t\t\t{\n\t\t\t\tloadFieldShape(gdp, shapeIt->second);\n\t\t\t}\n\t\t\telse if (shapeIt->first == \"Mesh\")\n\t\t\t{\n\t\t\t\tloadMeshShape(gdp, shapeIt->second);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/std::cout << \"Found unsupported shape type: \" << shapeIt->first << std::endl;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tNiEnd();\n\n\t\/\/Return success\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\nint loadMeshShape(GU_Detail& gdp, Ng::ShapeCPtr pShape)\n{\n\t\/\/std::cout << \"============= Loading mesh shape ===============\" << std::endl;\n\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\n\/**\n * Process a Naiad channel and add the attribute to the point\n *\/\nvoid processPointChannel(GU_Detail& gdp, GEO_Point* ppt, const Ng::ChannelCPtr& chan)\n{\n\t\/**\n\t * If the channel does not exist, then create it\n\t *\/\n\n\tif (chan->name() == \"position\")\n\t{\n\t\t\/\/Set the point position\n\t\t\/\/const Ng::ParticleChannel3f &chanPos = chan->constChannel3f( ppt->getNum() );\n\t\t\/\/ppt->setPos( chanPos[0], chanPos[1], chanPos[2] );\n\t}\n\n\t\n}\n\nint loadParticleShape(GU_Detail& gdp, const Ng::Body* pBody)\n{\n\tconst Ng::ParticleShape* pShape;\n\t\/\/std::cout << \"============= Loading particle shape ===============\" << std::endl;\n\n\tpShape = pBody->queryConstParticleShape();\n\n\tif (!pShape)\n\t{\n\t\t\/\/std::cout << \"Received NULL particle shape!\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/We have a valid particle shape. Start copying particle data over to the GDP\n\tint64_t size = pShape->size();\n\tint channelCount = pShape->channelCount();\n\tGEO_Point *ppt;\n\tstd::vector<std::string> houdiniNames; \/\/houdini names that correspond to naiad channels.\n\t\n\t\/\/std::cout << \"Size: \" << size << std::endl;\n\t\/\/std::cout << \"Channel count: \" << channelCount << std::endl;\n\n\t\/\/Iterate over the channels and create the corresponding attributes in the GDP\n\tfor (int i = 0; i < channelCount; i++)\n\t{\n\t\tconst Ng::ChannelCPtr& chan = pShape->channel(i);\n\n\t\tif ( chan->name() == \"position\" )\t\n\t\t\thoudiniNames.push_back(\"P\");\n\t\telse if (chan->name() == \"velocity\" )\n\t\t\thoudiniNames.push_back(\"v\");\n\t\telse\n\t\t\thoudiniNames.push_back( chan->name() );\n\n\t\t\/\/std::cout << \"channel: \" << chan->name() << \" size: \" << chan->size() << std::endl;\n\t}\t\n\n\t\/\/The channel values for particle shapes are stored in blocks\/tiles.\n\tconst Ng::TileLayout& layout = pBody->constLayout();\n\tunsigned int numBlocks = layout.tileCount();\n\n\t\/\/Get the block array for the positions channel\n\tconst em::block3_array3f& positionBlocks( pShape->constBlocks3f(\"position\") );\t\n\n\tfor (int blockIndex = 0; blockIndex < numBlocks; blockIndex ++)\n\t{\n\t\t\/\/Get a single block from the position blocks\n\t\tconst em::block3vec3f& posBlock = positionBlocks(blockIndex);\n\n\t\t\/\/std::cout << \"pos block index: \" << blockIndex << \" size: \" << posBlock.size() << std::endl;\n\t\t\/\/Iterate over all the points in the position block\n\t\tfor (int i = 0; i < posBlock.size(); i++)\n\t\t{\n\t\t\tppt = gdp.appendPoint();\n\t\t\t\/\/std::cout << \"pos: \" << i << \" \" << posBlock(i)[0] << posBlock(i)[1] << std::endl;\n\t\t\tppt->setPos( UT_Vector3( posBlock(i)[0], posBlock(i)[1], posBlock(i)[2] ) );\n\t\t}\n\n\t\t\n\t}\n\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\nint loadFieldShape(GU_Detail& gdp, Ng::ShapeCPtr pShape)\n{\n\t\/\/std::cout << \"============= Loading field shape ===============\" << std::endl;\n\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\n\n<commit_msg>Particles and their velocities can now be imported into Houdini. There is existing code to import any attributes present on the particles but is not complete yet.<commit_after>\n#include \"geo2emp.h\"\n\n#include <iostream>\n\n#include <GEO\/GEO_AttributeHandle.h>\n\n#include <Ni.h>\n#include <NgBody.h>\n#include <NgEmp.h>\n#include <NgString.h>\n\n\/** \n * Process a mesh-type naiad body\n *\/\nint loadMeshShape(GU_Detail& gdp, Ng::ShapeCPtr pShape);\nint loadParticleShape(GU_Detail& gdp, const Ng::Body* pBody);\nint loadFieldShape(GU_Detail& gdp, Ng::ShapeCPtr pShape);\n\n\n\/*************************************************************************************************\/\n\n\/** \n * Load all the Naiad bodies from the EMP file into the Houdini GDP\n *\n *\/\nint loadEmpBodies(std::string filen, GU_Detail& gdp)\n{\n\tNg::EmpReader* empReader = NULL;\t\n\n\tNiBegin(NI_BODY_ONLY);\n\n\t\/\/std::cout << \"loading emp bodies from: \" << filen << std::endl;\n\n\tunsigned int numBodies = 0;\n\ttry\n\t{\n\t\t\/\/std::cout << \"Create new emp reader.\" << std::endl;\n\t\tNg::String ngfilen = Ng::String(filen);\n\t\tempReader = new Ng::EmpReader( ngfilen );\n\t\t\/\/std::cout << \"getting body count...\" << std::endl;\n\t\t\/\/std::cout << \"body count: \" << empReader->bodyCount() << std::endl;\n\t\tnumBodies = empReader->bodyCount();\n\t\t\/\/std::cout << \"Found \" << numBodies << \" bodies in emp file \" << std::endl;\n\n\t}\n\tcatch( std::exception& e )\n\t{\n\t\t\/\/TODO: generate a proper error \/ exit code for Houdini. \n\t\t\/\/ return exit code?\n\t\t\/\/std::cout << \"exception! \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/Run through each body and process them according to their shape type.\n\tconst Ng::Body* pBody = 0;\n\tNg::Body::ConstShapeMapIter shapeIt;\n\tfor (int i = 0; i < numBodies; i++)\n\t{\n\t\tpBody = empReader->constBody(i);\n\t\t\/\/std::cout << i << \":\" << pBody->name() << std::endl;\n\t\t\/\/std::cout << \"number of shapes: \" << pBody->shape_count() << std::endl;\n\n\t\t\/\/Iterate over the shapes for this body.\n\t\tfor (shapeIt = pBody->beginShapes(); shapeIt != pBody->endShapes(); shapeIt++)\n\t\t{\n\t\t\t\/\/std::cout << \"Shape type: \" << shapeIt->first << std::endl;\n\t\t\tif (shapeIt->first == \"Particle\")\n\t\t\t{\n\t\t\t\tloadParticleShape(gdp, pBody);\n\t\t\t}\n\t\t\telse if (shapeIt->first == \"Field\")\n\t\t\t{\n\t\t\t\tloadFieldShape(gdp, shapeIt->second);\n\t\t\t}\n\t\t\telse if (shapeIt->first == \"Mesh\")\n\t\t\t{\n\t\t\t\tloadMeshShape(gdp, shapeIt->second);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/std::cout << \"Found unsupported shape type: \" << shapeIt->first << std::endl;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tNiEnd();\n\n\t\/\/Return success\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\nint loadMeshShape(GU_Detail& gdp, Ng::ShapeCPtr pShape)\n{\n\t\/\/std::cout << \"============= Loading mesh shape ===============\" << std::endl;\n\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\n\/**\n * Process a Naiad channel and add the attribute to the point\n *\/\nvoid processPointChannel(GU_Detail& gdp, GEO_Point* ppt, const Ng::ChannelCPtr& chan)\n{\n\t\/**\n\t * If the channel does not exist, then create it\n\t *\/\n\n\tif (chan->name() == \"position\")\n\t{\n\t\t\/\/Set the point position\n\t\t\/\/const Ng::ParticleChannel3f &chanPos = chan->constChannel3f( ppt->getNum() );\n\t\t\/\/ppt->setPos( chanPos[0], chanPos[1], chanPos[2] );\n\t}\n\n\t\n}\n\nint loadParticleShape(GU_Detail& gdp, const Ng::Body* pBody)\n{\n\tconst Ng::ParticleShape* pShape;\n\t\/\/std::cout << \"============= Loading particle shape ===============\" << std::endl;\n\n\tpShape = pBody->queryConstParticleShape();\n\n\tif (!pShape)\n\t{\n\t\t\/\/std::cout << \"Received NULL particle shape!\" << std::endl;\n\t\treturn 1;\n\t}\n\n\t\/\/We have a valid particle shape. Start copying particle data over to the GDP\n\tint64_t size = pShape->size();\n\tint channelCount = pShape->channelCount();\n\tint positionChannelIndex = 0;\n\tGEO_Point *ppt;\n\tGEO_AttributeHandle attr;\n\tstd::vector<std::string> houdiniNames; \/\/houdini names that correspond to naiad channels.\n\t\/\/Default values for attributes\n\tfloat zero3f[3] = {0,0,0};\n\tfloat zero1f = 0;\n\tint zero3i[3] = {0,0,0};\n\tint zero1i = 0;\n\n\t\n\t\/\/std::cout << \"Size: \" << size << std::endl;\n\t\/\/std::cout << \"Channel count: \" << channelCount << std::endl;\n\n\t\/\/Iterate over the channels and create the corresponding attributes in the GDP\n\tfor (int i = 0; i < channelCount; i++)\n\t{\n\t\tconst Ng::ChannelCPtr& chan = pShape->channel(i);\n\n\t\tif ( chan->name() == \"position\" )\t\n\t\t{\n\t\t\thoudiniNames.push_back(\"P\");\n\t\t\tpositionChannelIndex = i;\n\t\t\t\/\/std::cout << \"Setting position channel index: \" << i << std::endl;\n\t\t\t\/\/GDPs always have a P attribute, so no need to create on explicitly.\n\t\t}\n\t\telse if (chan->name() == \"velocity\" )\n\t\t{\n\t\t\thoudiniNames.push_back(\"v\");\n\t\t\tattr = gdp.getPointAttribute(\"v\");\n\t\t\tif ( !attr.isAttributeValid() )\n\t\t\t{\n\t\t\t\tgdp.addPointAttrib( \"v\", sizeof(float)*3, GB_ATTRIB_VECTOR, zero3f );\n\t\t\t\tattr = gdp.getPointAttribute( \"v\" );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\thoudiniNames.push_back( chan->name() );\n\t\t\tattr = gdp.getPointAttribute( chan->name().c_str() );\n\t\t\tif ( !attr.isAttributeValid() )\n\t\t\t{\n\t\t\t\t\/\/If the attribute doesn't exist yet, then create a new one based on the Naiad type. \n\t\t\t\t\/\/(Hopefully we don't have name clashes!!)\n\n\t\t\t\tint size;\n\t\t\t\tGB_AttribType type;\n\t\t\t\tvoid* data;\n\n\t\t\t\tswitch ( chan->type() )\n\t\t\t\t{\n\t\t\t\t\tcase Ng::ValueBase::FloatType:\n\t\t\t\t\t\t\/\/Create a single float attribute.\n\t\t\t\t\t\tsize = sizeof(float);\n\t\t\t\t\t\ttype = GB_ATTRIB_FLOAT;\n\t\t\t\t\t\tdata = &zero1f;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::IntType:\n\t\t\t\t\t\t\/\/Create a single float attribute.\n\t\t\t\t\t\tsize = sizeof(int);\n\t\t\t\t\t\ttype = GB_ATTRIB_INT;\n\t\t\t\t\t\tdata = &zero1i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::Vec3fType:\n\t\t\t\t\t\t\/\/Create a tuple of 3 floats.\n\t\t\t\t\t\tsize = sizeof(float)*3;\n\t\t\t\t\t\ttype = GB_ATTRIB_FLOAT;\n\t\t\t\t\t\tdata = zero3f;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::Vec3iType:\n\t\t\t\t\t\t\/\/Create a tuple of 3 ints.\n\t\t\t\t\t\tsize = sizeof(int)*3;\n\t\t\t\t\t\ttype = GB_ATTRIB_FLOAT;\n\t\t\t\t\t\tdata = zero3i;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t\/\/Unsupported type...now what??\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tgdp.addPointAttrib( chan->name().c_str(), size, type, data );\n\t\t\t\tattr = gdp.getPointAttribute( chan->name().c_str() );\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/std::cout << \"channel: \" << chan->name() << \" size: \" << chan->size() << std::endl;\n\t}\t\n\n\t\/\/The channel values for particle shapes are stored in blocks\/tiles.\n\tconst Ng::TileLayout& layout = pBody->constLayout();\n\tunsigned int numBlocks = layout.tileCount();\n\n\t\/\/Get the block array for the positions channel\n\tconst em::block3_array3f& positionBlocks( pShape->constBlocks3f(\"position\") );\t\n\n\tfor (int blockIndex = 0; blockIndex < numBlocks; blockIndex ++)\n\t{\n\t\t\/\/Get a single block from the position blocks\n\t\tconst em::block3vec3f& posBlock = positionBlocks(blockIndex);\n\n\t\t\/\/std::cout << \"taking block from positions...\" << blockIndex << std::endl;\n\t\t\/\/std::cout << \"block size:\" << posBlock.size() << std::endl;\n\t\t\/\/Iterate over all the points\/particles in the position block\n\t\tfor (int ptNum = 0; ptNum < posBlock.size(); ptNum++)\n\t\t{\n\t\t\tppt = gdp.appendPoint();\n\t\t\t\/\/std::cout << \"pos: \" << i << \" \" << posBlock(i)[0] << posBlock(i)[1] << std::endl;\n\t\t\tppt->setPos( UT_Vector3( posBlock(ptNum)[0], posBlock(ptNum)[1], posBlock(ptNum)[2] ) );\n\n\t\t\t\/\/Loop over the channels and add the attributes\n\t\t\tfor (int channelIndex = 0; channelIndex < channelCount; channelIndex++)\n\t\t\t{\n\t\t\t\t\/\/std::cout << \"processing channel index: \" << channelIndex << std::endl;\n\t\t\t\tif (channelIndex == positionChannelIndex)\n\t\t\t\t\t\/\/Skip special case channels. Currently, the only special case channel is positions.\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/TODO: normals and velocities should be added as VECTORS, not FLOATS\n\n\t\t\t\tconst Ng::ChannelCPtr& chan = pShape->channel(channelIndex);\n\t\t\t\t\/\/std::cout << \"inspecting channel: \" << channelIndex << \":\" << chan->name() << std::endl;\n\t\t\t\t\/\/Fill the attributes data in the Houdini GDP. (The attributes have been created in the first channel loop).\n\t\t\t\tswitch ( chan->type() )\n\t\t\t\t{\n\t\t\t\t\tcase Ng::ValueBase::FloatType:\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/std::cout << \"got float attrib: \" << chan->name() << std::endl;\n\t\t\t\t\t\t\/\/Get the created channel data\n\t\t\t\t\t\tconst em::block3f& channelData( pShape->constBlocks1f(chan->name())(blockIndex) );\n\t\t\t\t\t\t\/\/Get the Houdini point attribute using the name list we built earlier.\n\t\t\t\t\t\tattr = gdp.getPointAttribute( houdiniNames[channelIndex].c_str() );\n\t\t\t\t\t\tattr.setElement(ppt);\n\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::IntType:\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/std::cout << \"got int attrib: \" << chan->name() << std::endl;\n\t\t\t\t\t\t\/\/Get the created channel data\n\t\t\t\t\t\tconst em::block3f& channelData( pShape->constBlocks1f(chan->name())(blockIndex) );\n\t\t\t\t\t\t\/\/Get the Houdini point attribute using the name list we built earlier.\n\t\t\t\t\t\tattr = gdp.getPointAttribute( houdiniNames[channelIndex].c_str() );\n\t\t\t\t\t\tattr.setElement(ppt);\n\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::Vec3fType:\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/std::cout << \"got float3 attrib: \" << chan->name() << std::endl;\n\t\t\t\t\t\t\/\/Get the created channel data\n\t\t\t\t\t\tconst em::block3vec3f& channelData( pShape->constBlocks3f(channelIndex)(blockIndex) );\n\t\t\t\t\t\t\/\/Get the Houdini point attribute using the name list we built earlier.\n\t\t\t\t\t\tattr = gdp.getPointAttribute( houdiniNames[channelIndex].c_str() );\n\t\t\t\t\t\tattr.setElement(ppt);\n\t\t\t\t\t\tattr.setV3( UT_Vector3( channelData(ptNum)[0], channelData(ptNum)[1], channelData(ptNum)[2] ) );\n\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase Ng::ValueBase::Vec3iType:\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/std::cout << \"got int3 attrib: \" << chan->name() << std::endl;\n\t\t\t\t\t\t\/\/Get the created channel data\n\t\t\t\t\t\tconst em::block3vec3i& channelData( pShape->constBlocks3i(chan->name())(blockIndex) );\n\t\t\t\t\t\t\/\/Get the Houdini point attribute using the name list we built earlier.\n\t\t\t\t\t\tattr = gdp.getPointAttribute( houdiniNames[channelIndex].c_str() );\n\t\t\t\t\t\tattr.setElement(ppt);\n\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t\/\/std::cout << \"got non-float attrib.\" << chan->name() << std::endl;\n\t\t\t\t\t\tbreak;\n\n\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\t}\n\n\t\/\/std::cout << \"all done. \" << std::endl;\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\nint loadFieldShape(GU_Detail& gdp, Ng::ShapeCPtr pShape)\n{\n\t\/\/std::cout << \"============= Loading field shape ===============\" << std::endl;\n\n\treturn 0;\n}\n\n\/*************************************************************************************************\/\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"py-gil-lock.h\"\n#include <uv.h>\n\nnamespace GILLock {\nvoid Init() {\n static PyGILState_STATE gstate;\n gstate = PyGILState_Ensure();\n\n static uv_prepare_t gilrelease;\n static uv_check_t gilensure;\n\n uv_prepare_init(uv_default_loop(), &gilrelease);\n uv_check_init(uv_default_loop(), &gilensure);\n uv_prepare_start(&gilrelease, [] (uv_prepare_t *) {\n PyGILState_Release(gstate);\n });\n uv_check_start(&gilensure, [] (uv_check_t *) {\n gstate = PyGILState_Ensure();\n });\n}\n} \/\/ namespace GILLock\n<commit_msg>seems work<commit_after>#include \"py-gil-lock.h\"\n#include <uv.h>\n#include <iostream>\n\nnamespace GILLock {\nvoid Init() {\n static PyGILState_STATE gstate;\n gstate = PyGILState_Ensure();\n\n static uv_prepare_t gilrelease;\n static uv_check_t gilensure;\n\n uv_prepare_init(uv_default_loop(), &gilrelease);\n uv_check_init(uv_default_loop(), &gilensure);\n uv_prepare_start(&gilrelease, [] (uv_prepare_t *) {\n PyGILState_Release(gstate);\n });\n uv_check_start(&gilensure, [] (uv_check_t *) {\n if (uv_loop_alive(uv_default_loop())) {\n std::cout << \"alive\" << std::endl;\n gstate = PyGILState_Ensure();\n }\n });\n uv_unref((uv_handle_t *)&gilrelease);\n uv_unref((uv_handle_t *)&gilensure);\n}\n} \/\/ namespace GILLock\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n\n#include \"qca_plugin.h\"\n\n#include <QtCore>\n#include \"qcaprovider.h\"\n\n#define PLUGIN_SUBDIR \"crypto\"\n\nnamespace QCA {\n\nclass ProviderItem\n{\npublic:\n\tProvider *p;\n\tQString fname;\n\tint priority;\n\n\tstatic ProviderItem *load(const QString &fname)\n\t{\n\t\tQPluginLoader *lib = new QPluginLoader(fname);\n\t\tQCAPlugin *plugin = qobject_cast<QCAPlugin*>(lib->instance());\n\t\tif(!plugin || plugin->version() != QCA_PLUGIN_VERSION)\n\t\t{\n\t\t\tdelete lib;\n\t\t\treturn 0;\n\t\t}\n\n\t\tProvider *p = plugin->createProvider();\n\t\tif(!p)\n\t\t{\n\t\t\tdelete lib;\n\t\t\treturn 0;\n\t\t}\n\n\t\tProviderItem *i = new ProviderItem(lib, p);\n\t\ti->fname = fname;\n\t\treturn i;\n\t}\n\n\tstatic ProviderItem *loadStatic(QObject *instance)\n\t{\n\t\tQCAPlugin *plugin = qobject_cast<QCAPlugin*>(instance);\n\t\tif(!plugin || plugin->version() != QCA_PLUGIN_VERSION)\n\t\t\treturn 0;\n\n\t\tProvider *p = plugin->createProvider();\n\t\tif(!p)\n\t\t\treturn 0;\n\n\t\tProviderItem *i = new ProviderItem(0, p);\n\t\treturn i;\n\t}\n\n\tstatic ProviderItem *fromClass(Provider *p)\n\t{\n\t\tProviderItem *i = new ProviderItem(0, p);\n\t\treturn i;\n\t}\n\n\t~ProviderItem()\n\t{\n\t\tdelete p;\n\t\tdelete lib;\n\t}\n\n\tvoid ensureInit()\n\t{\n\t\tif(init_done)\n\t\t\treturn;\n\t\tinit_done = true;\n\t\tp->init();\n\t}\n\nprivate:\n\tQPluginLoader *lib;\n\tbool init_done;\n\n\tProviderItem(QPluginLoader *_lib, Provider *_p)\n\t{\n\t\tlib = _lib;\n\t\tp = _p;\n\t\tinit_done = false;\n\t}\n};\n\nProviderManager::ProviderManager()\n{\n\tdef = 0;\n\tscanned_static = false;\n}\n\nProviderManager::~ProviderManager()\n{\n\tdelete def;\n}\n\nvoid ProviderManager::scan()\n{\n\t\/\/ check static first, but only once\n\tif(!scanned_static)\n\t{\n\t\tQObjectList list = QPluginLoader::staticInstances();\n\t\tfor(int n = 0; n < list.count(); ++n)\n\t\t{\n\t\t\tQObject *instance = list[n];\n\t\t\tProviderItem *i = ProviderItem::loadStatic(instance);\n\t\t\tif(!i)\n\t\t\t\tcontinue;\n\n\t\t\tif(i->p && haveAlready(i->p->name()))\n\t\t\t{\n\t\t\t\tdelete i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taddItem(i, -1);\n\t\t}\n\t\tscanned_static = true;\n\t}\n\n\t\/\/ check plugin files\n\tQStringList dirs = QCoreApplication::libraryPaths();\n\tfor(QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it)\n\t{\n\t\tQDir libpath(*it);\n\t\tQDir dir(libpath.filePath(PLUGIN_SUBDIR));\n\t\tif(!dir.exists())\n\t\t\tcontinue;\n\n\t\tQStringList list = dir.entryList();\n\t\tfor(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)\n\t\t{\n\t\t\tQFileInfo fi(dir.filePath(*it));\n\t\t\tif(fi.isDir())\n\t\t\t\tcontinue;\n\t\t\tQString fname = fi.filePath();\n\n\t\t\tProviderItem *i = ProviderItem::load(fname);\n\t\t\tif(!i)\n\t\t\t\tcontinue;\n\n\t\t\tif(i->p && haveAlready(i->p->name()))\n\t\t\t{\n\t\t\t\tdelete i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taddItem(i, -1);\n\t\t}\n\t}\n}\n\nbool ProviderManager::add(Provider *p, int priority)\n{\n\tif(haveAlready(p->name()))\n\t\treturn false;\n\n\tProviderItem *i = ProviderItem::fromClass(p);\n\taddItem(i, priority);\n\treturn true;\n}\n\nvoid ProviderManager::unload(const QString &name)\n{\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p->name() == name)\n\t\t{\n\t\t\tdelete i;\n\t\t\tproviderItemList.removeAt(n);\n\t\t\tproviderList.removeAt(n);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid ProviderManager::unloadAll()\n{\n\tqDeleteAll(providerItemList);\n\tproviderItemList.clear();\n\tproviderList.clear();\n}\n\nvoid ProviderManager::setDefault(Provider *p)\n{\n\tif(def)\n\t\tdelete def;\n\tdef = p;\n\tif(def)\n\t\tdef->init();\n}\n\nProvider *ProviderManager::find(Provider *p) const\n{\n\tif(p == def)\n\t\treturn def;\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p == p)\n\t\t{\n\t\t\ti->ensureInit();\n\t\t\treturn i->p;\n\t\t}\n\t}\n\treturn 0;\n}\n\nProvider *ProviderManager::find(const QString &name) const\n{\n\tif(def && name == def->name())\n\t\treturn def;\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p->name() == name)\n\t\t{\n\t\t\ti->ensureInit();\n\t\t\treturn i->p;\n\t\t}\n\t}\n\treturn 0;\n}\n\nProvider *ProviderManager::findFor(const QString &name, const QString &type) const\n{\n\tif(name.isEmpty())\n\t{\n\t\t\/\/ find the first one that can do it\n\t\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t\t{\n\t\t\tProviderItem *i = providerItemList[n];\n\t\t\ti->ensureInit();\n\t\t\tif(i->p && i->p->features().contains(type))\n\t\t\t\treturn i->p;\n\t\t}\n\n\t\t\/\/ try the default provider as a last resort\n\t\tif(def && def->features().contains(type))\n\t\t\treturn def;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tProvider *p = find(name);\n\t\tif(p && p->features().contains(type))\n\t\t\treturn p;\n\t\treturn 0;\n\t}\n}\n\nvoid ProviderManager::changePriority(const QString &name, int priority)\n{\n\tProviderItem *i = 0;\n\tint n = 0;\n\tfor(; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *pi = providerItemList[n];\n\t\tif(pi->p && pi->p->name() == name)\n\t\t{\n\t\t\ti = pi;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!i)\n\t\treturn;\n\n\tproviderItemList.removeAt(n);\n\tproviderList.removeAt(n);\n\n\taddItem(i, priority);\n}\n\nint ProviderManager::getPriority(const QString &name)\n{\n\tProviderItem *i = 0;\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *pi = providerItemList[n];\n\t\tif(pi->p && pi->p->name() == name)\n\t\t{\n\t\t\ti = pi;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!i)\n\t\treturn -1;\n\n\treturn i->priority;\n}\n\nQStringList ProviderManager::allFeatures() const\n{\n\tQStringList list;\n\n\tif(def)\n\t\tlist = def->features();\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p)\n\t\t\tmergeFeatures(&list, i->p->features());\n\t}\n\n\treturn list;\n}\n\nconst ProviderList & ProviderManager::providers() const\n{\n\treturn providerList;\n}\n\nvoid ProviderManager::addItem(ProviderItem *item, int priority)\n{\n\tif(priority < 0)\n\t{\n\t\t\/\/ for -1, make the priority the same as the last item\n\t\tif(!providerItemList.isEmpty())\n\t\t{\n\t\t\tProviderItem *last = providerItemList.last();\n\t\t\titem->priority = last->priority;\n\t\t}\n\t\telse\n\t\t\titem->priority = 0;\n\n\t\tproviderItemList.append(item);\n\t\tproviderList.append(item->p);\n\t}\n\telse\n\t{\n\t\t\/\/ place the item before any other items with same or greater priority\n\t\tint n = 0;\n\t\tfor(; n < providerItemList.count(); ++n)\n\t\t{\n\t\t\tProviderItem *i = providerItemList[n];\n\t\t\tif(i->priority >= priority)\n\t\t\t\tbreak;\n\t\t}\n\n\t\titem->priority = priority;\n\t\tproviderItemList.insert(n, item);\n\t\tproviderList.insert(n, item->p);\n\t}\n}\n\nbool ProviderManager::haveAlready(const QString &name) const\n{\n\treturn ((def && name == def->name()) || find(name));\n}\n\nvoid ProviderManager::mergeFeatures(QStringList *a, const QStringList &b)\n{\n\tfor(QStringList::ConstIterator it = b.begin(); it != b.end(); ++it)\n\t{\n\t\tif(!a->contains(*it))\n\t\t\ta->append(*it);\n\t}\n}\n\n}\n<commit_msg>don't load plugins more than once. also, do moveToThread(0) on them<commit_after>\/*\n * Copyright (C) 2004 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n\n#include \"qca_plugin.h\"\n\n#include <QtCore>\n#include \"qcaprovider.h\"\n\n#define PLUGIN_SUBDIR \"crypto\"\n\nnamespace QCA {\n\nclass ProviderItem\n{\npublic:\n\tQString fname;\n\tProvider *p;\n\tint priority;\n\n\tstatic ProviderItem *load(const QString &fname)\n\t{\n\t\t\/\/printf(\"trying to load [%s]\\n\", qPrintable(fname));\n\t\tQPluginLoader *lib = new QPluginLoader(fname);\n\t\tQCAPlugin *plugin = qobject_cast<QCAPlugin*>(lib->instance());\n\t\tif(!plugin || plugin->version() != QCA_PLUGIN_VERSION)\n\t\t{\n\t\t\tdelete plugin;\n\t\t\tdelete lib;\n\t\t\treturn 0;\n\t\t}\n\t\t\/\/printf(\"success\\n\");\n\n\t\tProvider *p = plugin->createProvider();\n\t\tif(!p)\n\t\t{\n\t\t\tdelete plugin;\n\t\t\tdelete lib;\n\t\t\treturn 0;\n\t\t}\n\n\t\tProviderItem *i = new ProviderItem(lib, plugin, p);\n\t\ti->fname = fname;\n\t\treturn i;\n\t}\n\n\tstatic ProviderItem *loadStatic(QObject *instance)\n\t{\n\t\tQCAPlugin *plugin = qobject_cast<QCAPlugin*>(instance);\n\t\tif(!plugin || plugin->version() != QCA_PLUGIN_VERSION)\n\t\t{\n\t\t\tdelete plugin;\n\t\t\treturn 0;\n\t\t}\n\n\t\tProvider *p = plugin->createProvider();\n\t\tif(!p)\n\t\t{\n\t\t\tdelete plugin;\n\t\t\treturn 0;\n\t\t}\n\n\t\tProviderItem *i = new ProviderItem(0, plugin, p);\n\t\treturn i;\n\t}\n\n\tstatic ProviderItem *fromClass(Provider *p)\n\t{\n\t\tProviderItem *i = new ProviderItem(0, 0, p);\n\t\treturn i;\n\t}\n\n\t~ProviderItem()\n\t{\n\t\tdelete p;\n\t\tdelete qcaPlugin;\n\t\tdelete lib;\n\t}\n\n\tvoid ensureInit()\n\t{\n\t\tif(init_done)\n\t\t\treturn;\n\t\tinit_done = true;\n\t\tp->init();\n\t}\n\nprivate:\n\tQPluginLoader *lib;\n\tQCAPlugin *qcaPlugin;\n\tbool init_done;\n\n\tProviderItem(QPluginLoader *_lib, QCAPlugin *_qcaPlugin, Provider *_p)\n\t{\n\t\tlib = _lib;\n\t\tqcaPlugin = _qcaPlugin;\n\t\tp = _p;\n\t\tinit_done = false;\n\n\t\t\/\/ disassociate from threads\n\t\tif(qcaPlugin)\n\t\t\tqcaPlugin->moveToThread(0);\n\t\tif(lib)\n\t\t\tlib->moveToThread(0);\n\t}\n};\n\nProviderManager::ProviderManager()\n{\n\tdef = 0;\n\tscanned_static = false;\n}\n\nProviderManager::~ProviderManager()\n{\n\tdelete def;\n}\n\nvoid ProviderManager::scan()\n{\n\t\/\/ check static first, but only once\n\tif(!scanned_static)\n\t{\n\t\tQObjectList list = QPluginLoader::staticInstances();\n\t\tfor(int n = 0; n < list.count(); ++n)\n\t\t{\n\t\t\tQObject *instance = list[n];\n\t\t\tProviderItem *i = ProviderItem::loadStatic(instance);\n\t\t\tif(!i)\n\t\t\t\tcontinue;\n\n\t\t\tif(i->p && haveAlready(i->p->name()))\n\t\t\t{\n\t\t\t\tdelete i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taddItem(i, -1);\n\t\t}\n\t\tscanned_static = true;\n\t}\n\n\t\/\/ check plugin files\n\tQStringList dirs = QCoreApplication::libraryPaths();\n\tfor(QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it)\n\t{\n\t\tQDir libpath(*it);\n\t\tQDir dir(libpath.filePath(PLUGIN_SUBDIR));\n\t\tif(!dir.exists())\n\t\t\tcontinue;\n\n\t\tQStringList list = dir.entryList();\n\t\tfor(QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)\n\t\t{\n\t\t\tQFileInfo fi(dir.filePath(*it));\n\t\t\tif(fi.isDir())\n\t\t\t\tcontinue;\n\t\t\tQString fname = fi.filePath();\n\n\t\t\t\/\/ make sure we haven't loaded this file before\n\t\t\tbool haveFile = false;\n\t\t\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t\t\t{\n\t\t\t\tProviderItem *pi = providerItemList[n];\n\t\t\t\tif(!pi->fname.isEmpty() && pi->fname == fname)\n\t\t\t\t{\n\t\t\t\t\thaveFile = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(haveFile)\n\t\t\t\tcontinue;\n\n\t\t\tProviderItem *i = ProviderItem::load(fname);\n\t\t\tif(!i)\n\t\t\t\tcontinue;\n\n\t\t\tif(i->p && haveAlready(i->p->name()))\n\t\t\t{\n\t\t\t\tdelete i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taddItem(i, -1);\n\t\t}\n\t}\n}\n\nbool ProviderManager::add(Provider *p, int priority)\n{\n\tif(haveAlready(p->name()))\n\t\treturn false;\n\n\tProviderItem *i = ProviderItem::fromClass(p);\n\taddItem(i, priority);\n\treturn true;\n}\n\nvoid ProviderManager::unload(const QString &name)\n{\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p->name() == name)\n\t\t{\n\t\t\tdelete i;\n\t\t\tproviderItemList.removeAt(n);\n\t\t\tproviderList.removeAt(n);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid ProviderManager::unloadAll()\n{\n\tqDeleteAll(providerItemList);\n\tproviderItemList.clear();\n\tproviderList.clear();\n}\n\nvoid ProviderManager::setDefault(Provider *p)\n{\n\tif(def)\n\t\tdelete def;\n\tdef = p;\n\tif(def)\n\t\tdef->init();\n}\n\nProvider *ProviderManager::find(Provider *p) const\n{\n\tif(p == def)\n\t\treturn def;\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p == p)\n\t\t{\n\t\t\ti->ensureInit();\n\t\t\treturn i->p;\n\t\t}\n\t}\n\treturn 0;\n}\n\nProvider *ProviderManager::find(const QString &name) const\n{\n\tif(def && name == def->name())\n\t\treturn def;\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p && i->p->name() == name)\n\t\t{\n\t\t\ti->ensureInit();\n\t\t\treturn i->p;\n\t\t}\n\t}\n\treturn 0;\n}\n\nProvider *ProviderManager::findFor(const QString &name, const QString &type) const\n{\n\tif(name.isEmpty())\n\t{\n\t\t\/\/ find the first one that can do it\n\t\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t\t{\n\t\t\tProviderItem *i = providerItemList[n];\n\t\t\ti->ensureInit();\n\t\t\tif(i->p && i->p->features().contains(type))\n\t\t\t\treturn i->p;\n\t\t}\n\n\t\t\/\/ try the default provider as a last resort\n\t\tif(def && def->features().contains(type))\n\t\t\treturn def;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tProvider *p = find(name);\n\t\tif(p && p->features().contains(type))\n\t\t\treturn p;\n\t\treturn 0;\n\t}\n}\n\nvoid ProviderManager::changePriority(const QString &name, int priority)\n{\n\tProviderItem *i = 0;\n\tint n = 0;\n\tfor(; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *pi = providerItemList[n];\n\t\tif(pi->p && pi->p->name() == name)\n\t\t{\n\t\t\ti = pi;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!i)\n\t\treturn;\n\n\tproviderItemList.removeAt(n);\n\tproviderList.removeAt(n);\n\n\taddItem(i, priority);\n}\n\nint ProviderManager::getPriority(const QString &name)\n{\n\tProviderItem *i = 0;\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *pi = providerItemList[n];\n\t\tif(pi->p && pi->p->name() == name)\n\t\t{\n\t\t\ti = pi;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!i)\n\t\treturn -1;\n\n\treturn i->priority;\n}\n\nQStringList ProviderManager::allFeatures() const\n{\n\tQStringList list;\n\n\tif(def)\n\t\tlist = def->features();\n\n\tfor(int n = 0; n < providerItemList.count(); ++n)\n\t{\n\t\tProviderItem *i = providerItemList[n];\n\t\tif(i->p)\n\t\t\tmergeFeatures(&list, i->p->features());\n\t}\n\n\treturn list;\n}\n\nconst ProviderList & ProviderManager::providers() const\n{\n\treturn providerList;\n}\n\nvoid ProviderManager::addItem(ProviderItem *item, int priority)\n{\n\tif(priority < 0)\n\t{\n\t\t\/\/ for -1, make the priority the same as the last item\n\t\tif(!providerItemList.isEmpty())\n\t\t{\n\t\t\tProviderItem *last = providerItemList.last();\n\t\t\titem->priority = last->priority;\n\t\t}\n\t\telse\n\t\t\titem->priority = 0;\n\n\t\tproviderItemList.append(item);\n\t\tproviderList.append(item->p);\n\t}\n\telse\n\t{\n\t\t\/\/ place the item before any other items with same or greater priority\n\t\tint n = 0;\n\t\tfor(; n < providerItemList.count(); ++n)\n\t\t{\n\t\t\tProviderItem *i = providerItemList[n];\n\t\t\tif(i->priority >= priority)\n\t\t\t\tbreak;\n\t\t}\n\n\t\titem->priority = priority;\n\t\tproviderItemList.insert(n, item);\n\t\tproviderList.insert(n, item->p);\n\t}\n}\n\nbool ProviderManager::haveAlready(const QString &name) const\n{\n\treturn ((def && name == def->name()) || find(name));\n}\n\nvoid ProviderManager::mergeFeatures(QStringList *a, const QStringList &b)\n{\n\tfor(QStringList::ConstIterator it = b.begin(); it != b.end(); ++it)\n\t{\n\t\tif(!a->contains(*it))\n\t\t\ta->append(*it);\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * W.J. van der Laan 2011-2012\n *\/\n\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include \"ui_interface.h\"\n#include \"paymentserver.h\"\n#include \"splashscreen.h\"\n#include \"intro.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#if QT_VERSION < 0x050000\n#include <QTextCodec>\n#endif\n#include <QLocale>\n#include <QTimer>\n#include <QTranslator>\n#include <QLibraryInfo>\n#include <QSettings>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Declare meta types used for QMetaObject::invokeMethod\nQ_DECLARE_METATYPE(bool*)\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic SplashScreen *splashref;\n\nstatic bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & CClientUIInterface::MODAL);\n bool ret = false;\n \/\/ In case of modal message, use blocking connection to wait for user to click a button\n QMetaObject::invokeMethod(guiref, \"message\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(unsigned int, style),\n Q_ARG(bool*, &ret));\n return ret;\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n return false;\n }\n}\n\nstatic bool ThreadSafeAskFee(int64 nFeeRequired)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nstatic void InitMessage(const std::string &message)\n{\n if(splashref)\n {\n splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));\n qApp->processEvents();\n }\n printf(\"init message: %s\\n\", message.c_str());\n}\n\n\/*\n Translate string to current locale using Qt.\n *\/\nstatic std::string Translate(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occurred. Bitcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n\/** Set up translations *\/\nstatic void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)\n{\n QSettings settings;\n\n \/\/ Get desired locale (e.g. \"de_DE\")\n \/\/ 1) System default language\n QString lang_territory = QLocale::system().name();\n \/\/ 2) Language from QSettings\n QString lang_territory_qsettings = settings.value(\"language\", \"\").toString();\n if(!lang_territory_qsettings.isEmpty())\n lang_territory = lang_territory_qsettings;\n \/\/ 3) -lang command line argument\n lang_territory = QString::fromStdString(GetArg(\"-lang\", lang_territory.toStdString()));\n\n \/\/ Convert to \"de\" only by truncating \"_DE\"\n QString lang = lang_territory;\n lang.truncate(lang_territory.lastIndexOf('_'));\n\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n\n \/\/ Load e.g. qt_de.qm\n if (qtTranslatorBase.load(\"qt_\" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n QApplication::installTranslator(&qtTranslatorBase);\n\n \/\/ Load e.g. qt_de_DE.qm\n if (qtTranslator.load(\"qt_\" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n QApplication::installTranslator(&qtTranslator);\n\n \/\/ Load e.g. bitcoin_de.qm (shortcut \"de\" needs to be defined in bitcoin.qrc)\n if (translatorBase.load(lang, \":\/translations\/\"))\n QApplication::installTranslator(&translatorBase);\n\n \/\/ Load e.g. bitcoin_de_DE.qm (shortcut \"de_DE\" needs to be defined in bitcoin.qrc)\n if (translator.load(lang_territory, \":\/translations\/\"))\n QApplication::installTranslator(&translator);\n}\n\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n bool fMissingDatadir = false;\n bool fSelParFromCLFailed = false;\n\n fHaveGUI = true;\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n \/\/ ... then bitcoin.conf:\n if (!boost::filesystem::is_directory(GetDataDir(false))) {\n fMissingDatadir = true;\n } else {\n ReadConfigFile(mapArgs, mapMultiArgs);\n }\n \/\/ Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)\n if (!SelectParamsFromCommandLine()) {\n fSelParFromCLFailed = true;\n }\n\n#if QT_VERSION < 0x050000\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n#endif\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Register meta types used for QMetaObject::invokeMethod\n qRegisterMetaType< bool* >();\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n QApplication::setOrganizationName(\"Bitcoin\");\n QApplication::setOrganizationDomain(\"bitcoin.org\");\n if (TestNet()) \/\/ Separate UI settings for testnet\n QApplication::setApplicationName(\"Bitcoin-Qt-testnet\");\n else\n QApplication::setApplicationName(\"Bitcoin-Qt\");\n\n \/\/ Now that QSettings are accessible, initialize translations\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);\n\n \/\/ Now that translations are initialized check for errors and allow a translatable error message\n if (fMissingDatadir) {\n QMessageBox::critical(0, QObject::tr(\"Bitcoin\"),\n QObject::tr(\"Error: Specified data directory \\\"%1\\\" does not exist.\").arg(QString::fromStdString(mapArgs[\"-datadir\"])));\n return 1;\n }\n else if (fSelParFromCLFailed) {\n QMessageBox::critical(0, QObject::tr(\"Bitcoin\"), QObject::tr(\"Error: Invalid combination of -regtest and -testnet.\"));\n return 1;\n }\n\n \/\/ User language is set up: pick a data directory\n Intro::pickDataDirectory();\n\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n \/\/ ... but do it after creating app, so QCoreApplication::arguments is initialized:\n if (PaymentServer::ipcSendCommandLine())\n exit(0);\n PaymentServer* paymentServer = new PaymentServer(&app);\n\n \/\/ Install global event filter that makes sure that long tooltips can be word-wrapped\n app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));\n\n \/\/ ... now GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Subscribe to global signals from core\n uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);\n uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);\n uiInterface.InitMessage.connect(InitMessage);\n uiInterface.Translate.connect(Translate);\n\n \/\/ Show help message immediately after parsing command-line options (for \"-lang\") and setting locale,\n \/\/ but before showing splash screen.\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n GUIUtil::HelpMessageBox help;\n help.showOrPrint();\n return 1;\n }\n\n SplashScreen splash(QPixmap(), 0);\n if (GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\", false))\n {\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n#ifndef Q_OS_MAC\n \/\/ Regenerate startup link, to fix links to old versions\n \/\/ OSX: makes no sense on mac and might also scan\/mount external (and sleeping) volumes (can take up some secs)\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(true);\n#endif\n\n boost::thread_group threadGroup;\n\n BitcoinGUI window(TestNet(), 0);\n guiref = &window;\n\n QTimer* pollShutdownTimer = new QTimer(guiref);\n QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));\n pollShutdownTimer->start(200);\n\n if(AppInit2(threadGroup))\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if (splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n WalletModel walletModel(pwalletMain, &optionsModel);\n\n window.setClientModel(&clientModel);\n window.addWallet(\"~Default\", &walletModel);\n window.setCurrentWallet(\"~Default\");\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\", false))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Now that initialization\/startup is done, process any command-line\n \/\/ bitcoin: URIs\n QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));\n QTimer::singleShot(100, paymentServer, SLOT(uiReady()));\n\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.removeAllWallets();\n guiref = 0;\n }\n \/\/ Shutdown the core and its threads, but don't exit Bitcoin-Qt here\n threadGroup.interrupt_all();\n threadGroup.join_all();\n Shutdown();\n }\n else\n {\n threadGroup.interrupt_all();\n threadGroup.join_all();\n Shutdown();\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<commit_msg>Rework when payment server is started<commit_after>\/*\n * W.J. van der Laan 2011-2012\n *\/\n\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n#include \"init.h\"\n#include \"util.h\"\n#include \"ui_interface.h\"\n#include \"paymentserver.h\"\n#include \"splashscreen.h\"\n#include \"intro.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#if QT_VERSION < 0x050000\n#include <QTextCodec>\n#endif\n#include <QLocale>\n#include <QTimer>\n#include <QTranslator>\n#include <QLibraryInfo>\n#include <QSettings>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Declare meta types used for QMetaObject::invokeMethod\nQ_DECLARE_METATYPE(bool*)\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic SplashScreen *splashref;\n\nstatic bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & CClientUIInterface::MODAL);\n bool ret = false;\n \/\/ In case of modal message, use blocking connection to wait for user to click a button\n QMetaObject::invokeMethod(guiref, \"message\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(unsigned int, style),\n Q_ARG(bool*, &ret));\n return ret;\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n return false;\n }\n}\n\nstatic bool ThreadSafeAskFee(int64 nFeeRequired)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nstatic void InitMessage(const std::string &message)\n{\n if(splashref)\n {\n splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));\n qApp->processEvents();\n }\n printf(\"init message: %s\\n\", message.c_str());\n}\n\n\/*\n Translate string to current locale using Qt.\n *\/\nstatic std::string Translate(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occurred. Bitcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n\/** Set up translations *\/\nstatic void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)\n{\n QSettings settings;\n\n \/\/ Get desired locale (e.g. \"de_DE\")\n \/\/ 1) System default language\n QString lang_territory = QLocale::system().name();\n \/\/ 2) Language from QSettings\n QString lang_territory_qsettings = settings.value(\"language\", \"\").toString();\n if(!lang_territory_qsettings.isEmpty())\n lang_territory = lang_territory_qsettings;\n \/\/ 3) -lang command line argument\n lang_territory = QString::fromStdString(GetArg(\"-lang\", lang_territory.toStdString()));\n\n \/\/ Convert to \"de\" only by truncating \"_DE\"\n QString lang = lang_territory;\n lang.truncate(lang_territory.lastIndexOf('_'));\n\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n\n \/\/ Load e.g. qt_de.qm\n if (qtTranslatorBase.load(\"qt_\" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n QApplication::installTranslator(&qtTranslatorBase);\n\n \/\/ Load e.g. qt_de_DE.qm\n if (qtTranslator.load(\"qt_\" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n QApplication::installTranslator(&qtTranslator);\n\n \/\/ Load e.g. bitcoin_de.qm (shortcut \"de\" needs to be defined in bitcoin.qrc)\n if (translatorBase.load(lang, \":\/translations\/\"))\n QApplication::installTranslator(&translatorBase);\n\n \/\/ Load e.g. bitcoin_de_DE.qm (shortcut \"de_DE\" needs to be defined in bitcoin.qrc)\n if (translator.load(lang_territory, \":\/translations\/\"))\n QApplication::installTranslator(&translator);\n}\n\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n bool fMissingDatadir = false;\n bool fSelParFromCLFailed = false;\n\n fHaveGUI = true;\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n \/\/ ... then bitcoin.conf:\n if (!boost::filesystem::is_directory(GetDataDir(false))) {\n fMissingDatadir = true;\n } else {\n ReadConfigFile(mapArgs, mapMultiArgs);\n }\n \/\/ Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)\n if (!SelectParamsFromCommandLine()) {\n fSelParFromCLFailed = true;\n }\n\n#if QT_VERSION < 0x050000\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n#endif\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Register meta types used for QMetaObject::invokeMethod\n qRegisterMetaType< bool* >();\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n QApplication::setOrganizationName(\"Bitcoin\");\n QApplication::setOrganizationDomain(\"bitcoin.org\");\n if (TestNet()) \/\/ Separate UI settings for testnet\n QApplication::setApplicationName(\"Bitcoin-Qt-testnet\");\n else\n QApplication::setApplicationName(\"Bitcoin-Qt\");\n\n \/\/ Now that QSettings are accessible, initialize translations\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);\n\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n \/\/ ... but do it after creating app and setting up translations, so errors are\n \/\/ translated properly.\n if (PaymentServer::ipcSendCommandLine())\n exit(0);\n\n \/\/ Now that translations are initialized check for errors and allow a translatable error message\n if (fMissingDatadir) {\n QMessageBox::critical(0, QObject::tr(\"Bitcoin\"),\n QObject::tr(\"Error: Specified data directory \\\"%1\\\" does not exist.\").arg(QString::fromStdString(mapArgs[\"-datadir\"])));\n return 1;\n }\n else if (fSelParFromCLFailed) {\n QMessageBox::critical(0, QObject::tr(\"Bitcoin\"), QObject::tr(\"Error: Invalid combination of -regtest and -testnet.\"));\n return 1;\n }\n\n \/\/ Start up the payment server early, too, so impatient users that click on\n \/\/ bitcoin: links repeatedly have their payment requests routed to this process:\n PaymentServer* paymentServer = new PaymentServer(&app);\n\n \/\/ User language is set up: pick a data directory\n Intro::pickDataDirectory();\n\n \/\/ Install global event filter that makes sure that long tooltips can be word-wrapped\n app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));\n\n \/\/ ... now GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Subscribe to global signals from core\n uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);\n uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);\n uiInterface.InitMessage.connect(InitMessage);\n uiInterface.Translate.connect(Translate);\n\n \/\/ Show help message immediately after parsing command-line options (for \"-lang\") and setting locale,\n \/\/ but before showing splash screen.\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n GUIUtil::HelpMessageBox help;\n help.showOrPrint();\n return 1;\n }\n\n SplashScreen splash(QPixmap(), 0);\n if (GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\", false))\n {\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n#ifndef Q_OS_MAC\n \/\/ Regenerate startup link, to fix links to old versions\n \/\/ OSX: makes no sense on mac and might also scan\/mount external (and sleeping) volumes (can take up some secs)\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(true);\n#endif\n\n boost::thread_group threadGroup;\n\n BitcoinGUI window(TestNet(), 0);\n guiref = &window;\n\n QTimer* pollShutdownTimer = new QTimer(guiref);\n QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));\n pollShutdownTimer->start(200);\n\n if(AppInit2(threadGroup))\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if (splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n WalletModel walletModel(pwalletMain, &optionsModel);\n\n window.setClientModel(&clientModel);\n window.addWallet(\"~Default\", &walletModel);\n window.setCurrentWallet(\"~Default\");\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\", false))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Now that initialization\/startup is done, process any command-line\n \/\/ bitcoin: URIs\n QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));\n QTimer::singleShot(100, paymentServer, SLOT(uiReady()));\n\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.removeAllWallets();\n guiref = 0;\n }\n \/\/ Shutdown the core and its threads, but don't exit Bitcoin-Qt here\n threadGroup.interrupt_all();\n threadGroup.join_all();\n Shutdown();\n }\n else\n {\n threadGroup.interrupt_all();\n threadGroup.join_all();\n Shutdown();\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <iostream>\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate <class T>\n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair<std::string\n\t\t\t, libtorrent::entry> const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry()\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(data_type t)\n\t\t: m_type(undefined_t)\n\t{\n\t\tconstruct(t);\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(const entry& e)\n\t\t: m_type(undefined_t)\n\t{\n\t\tcopy(e);\n#ifndef NDEBUG\n\t\tm_type_queried = e.m_type_queried;\n#endif\n\t}\n\n\tentry::entry(dictionary_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tswitch(t)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(t == undefined_t);\n\t\t}\n\t\tm_type = t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tswitch (e.type())\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(e.type() == undefined_t);\n\t\t}\n\t\tm_type = e.type();\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast<integer_type*>(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast<string_type*>(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast<list_type*>(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast<dictionary_type*>(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t\tm_type = undefined_t;\n#ifndef NDEBUG\n\t\tm_type_queried = false;\n#endif\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast<unsigned char>(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast<unsigned int>((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"<uninitialized>\\n\";\n\t\t}\n\t}\n}\n\n<commit_msg>reverted last check in<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate <class T>\n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair<std::string\n\t\t\t, libtorrent::entry> const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry()\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(data_type t)\n\t\t: m_type(undefined_t)\n\t{\n\t\tconstruct(t);\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(const entry& e)\n\t\t: m_type(undefined_t)\n\t{\n\t\tcopy(e);\n#ifndef NDEBUG\n\t\tm_type_queried = e.m_type_queried;\n#endif\n\t}\n\n\tentry::entry(dictionary_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tswitch(t)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(t == undefined_t);\n\t\t}\n\t\tm_type = t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tswitch (e.type())\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(e.type() == undefined_t);\n\t\t}\n\t\tm_type = e.type();\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast<integer_type*>(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast<string_type*>(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast<list_type*>(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast<dictionary_type*>(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t\tm_type = undefined_t;\n#ifndef NDEBUG\n\t\tm_type_queried = false;\n#endif\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast<unsigned char>(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast<unsigned int>((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"<uninitialized>\\n\";\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate <class T>\n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair<std::string\n\t\t\t, libtorrent::entry> const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry()\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(data_type t)\n\t\t: m_type(undefined_t)\n\t{\n\t\tconstruct(t);\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(const entry& e)\n\t\t: m_type(undefined_t)\n\t{\n\t\tcopy(e);\n#ifndef NDEBUG\n\t\tm_type_queried = e.m_type_queried;\n#endif\n\t}\n\n\tentry::entry(dictionary_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tswitch(t)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(t == undefined_t);\n\t\t}\n\t\tm_type = t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tswitch (e.type())\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(e.type() == undefined_t);\n\t\t}\n\t\tm_type = e.type();\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast<integer_type*>(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast<string_type*>(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast<list_type*>(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast<dictionary_type*>(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t\tm_type = undefined_t;\n#ifndef NDEBUG\n\t\tm_type_queried = false;\n#endif\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast<unsigned char>(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast<unsigned int>((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"<uninitialized>\\n\";\n\t\t}\n\t}\n}\n\n<commit_msg>fixed include issue in entry.cpp<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <iostream>\n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate <class T>\n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair<std::string\n\t\t\t, libtorrent::entry> const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry()\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(data_type t)\n\t\t: m_type(undefined_t)\n\t{\n\t\tconstruct(t);\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tentry::entry(const entry& e)\n\t\t: m_type(undefined_t)\n\t{\n\t\tcopy(e);\n#ifndef NDEBUG\n\t\tm_type_queried = e.m_type_queried;\n#endif\n\t}\n\n\tentry::entry(dictionary_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t\t: m_type(undefined_t)\n\t{\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tswitch(t)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(t == undefined_t);\n\t\t}\n\t\tm_type = t;\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tswitch (e.type())\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(e.type() == undefined_t);\n\t\t}\n\t\tm_type = e.type();\n#ifndef NDEBUG\n\t\tm_type_queried = true;\n#endif\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast<integer_type*>(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast<string_type*>(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast<list_type*>(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast<dictionary_type*>(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t\tm_type = undefined_t;\n#ifndef NDEBUG\n\t\tm_type_queried = false;\n#endif\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast<unsigned char>(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast<unsigned int>((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"<uninitialized>\\n\";\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\nCopyright (c) 2019, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\t* Redistributions of source code must retain the above copyright\n\t notice, this list of conditions and the following disclaimer.\n\t* Redistributions in binary form must reproduce the above copyright\n\t notice, this list of conditions and the following disclaimer in the\n\t documentation and\/or other materials provided with the distribution.\n\t* Neither the name of the <organization> nor the\n\t names of its contributors may be used to endorse or promote products\n\t derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include <iostream>\n\n#include <config.h>\n\n#include \"connections.h\"\n#include \"eventapi.h\"\n#include \"threadpool.h\"\n#include \"exception.h\"\n\n#include \"event.h\"\n\nbool libhttppp::Event::_Run=true;\nbool libhttppp::Event::_Restart=false;\n\nlibhttppp::Event::Event(libhttppp::ServerSocket* serversocket) : EVENT(serversocket){\n libhttppp::CtrlHandler::initCtrlHandler();\n}\n\nlibhttppp::Event::~Event(){\n}\n\nlibhttppp::EventApi::~EventApi(){\n}\n\nvoid libhttppp::CtrlHandler::CTRLCloseEvent() {\n libhttppp::Event::_Run = false;\n}\n\nvoid libhttppp::CtrlHandler::CTRLBreakEvent() {\n libhttppp::Event::_Restart = true;\n libhttppp::Event::_Run=false;\n libhttppp::Event::_Run=true;\n}\n\nvoid libhttppp::CtrlHandler::CTRLTermEvent() {\n libhttppp::Event::_Run = false;\n}\n\nvoid libhttppp::CtrlHandler::SIGPIPEEvent() {\n return;\n}\n\nvoid libhttppp::Event::runEventloop(){\n CpuInfo cpuinfo;\n size_t thrs = cpuinfo.getCores();\n initEventHandler();\nMAINWORKERLOOP:\n ThreadPool thpool;\n for (size_t i = 0; i < thrs; i++) {\n Thread *cthread=thpool.addThread();\n cthread->Create(WorkerThread, (void*)this);\n }\n for (Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread()) {\n curth->Join();\n }\n if(libhttppp::Event::_Restart){\n libhttppp::Event::_Restart=false;\n goto MAINWORKERLOOP;\n }\n}\n\nvoid * libhttppp::Event::WorkerThread(void* wrkevent){\n Event *eventptr=((Event*)wrkevent);\n int lstate=LockState::NOLOCK;\n while (libhttppp::Event::_Run) {\n try {\n for (int i = 0; i < eventptr->waitEventHandler(); ++i) {\n if((lstate=eventptr->LockConnection(i))!=LockState::ERRLOCK){\n try{\n switch(eventptr->StatusEventHandler(i)){\n case EventApi::EventHandlerStatus::EVNOTREADY:\n eventptr->ConnectEventHandler(i);\n break;\n case EventApi::EventHandlerStatus::EVIN:\n eventptr->ReadEventHandler(i);\n break;\n case EventApi::EventHandlerStatus::EVOUT:\n eventptr->WriteEventHandler(i);\n break;\n default:\n eventptr->CloseEventHandler(i);\n break;\n }\n eventptr->UnlockConnection(i);\n }catch(HTTPException &e){\n switch(e.getErrorType()){\n case HTTPException::Critical:\n eventptr->UnlockConnection(i);\n throw e;\n break;\n case HTTPException::Error:\n try{\n eventptr->CloseEventHandler(i);\n }catch(HTTPException &e){\n if(e.getErrorType()==HTTPException::Critical){\n eventptr->UnlockConnection(i);\n throw e;\n }\n }\n break; \n }\n eventptr->UnlockConnection(i);\n }\n } \n }\n }catch(HTTPException &e){\n switch(e.getErrorType()){\n case HTTPException::Critical:\n throw e;\n break;\n default:\n Console con;\n con << e.what() << con.endl;\n }\n }\n }\n return NULL;\n}\n<commit_msg>multithreading works<commit_after>\/*******************************************************************************\nCopyright (c) 2019, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\t* Redistributions of source code must retain the above copyright\n\t notice, this list of conditions and the following disclaimer.\n\t* Redistributions in binary form must reproduce the above copyright\n\t notice, this list of conditions and the following disclaimer in the\n\t documentation and\/or other materials provided with the distribution.\n\t* Neither the name of the <organization> nor the\n\t names of its contributors may be used to endorse or promote products\n\t derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include <iostream>\n\n#include <config.h>\n\n#include \"connections.h\"\n#include \"eventapi.h\"\n#include \"threadpool.h\"\n#include \"exception.h\"\n\n#include \"event.h\"\n\nbool libhttppp::Event::_Run=true;\nbool libhttppp::Event::_Restart=false;\n\nlibhttppp::Event::Event(libhttppp::ServerSocket* serversocket) : EVENT(serversocket){\n libhttppp::CtrlHandler::initCtrlHandler();\n}\n\nlibhttppp::Event::~Event(){\n}\n\nlibhttppp::EventApi::~EventApi(){\n}\n\nvoid libhttppp::CtrlHandler::CTRLCloseEvent() {\n libhttppp::Event::_Run = false;\n}\n\nvoid libhttppp::CtrlHandler::CTRLBreakEvent() {\n libhttppp::Event::_Restart = true;\n libhttppp::Event::_Run=false;\n libhttppp::Event::_Run=true;\n}\n\nvoid libhttppp::CtrlHandler::CTRLTermEvent() {\n libhttppp::Event::_Run = false;\n}\n\nvoid libhttppp::CtrlHandler::SIGPIPEEvent() {\n return;\n}\n\nvoid libhttppp::Event::runEventloop(){\n CpuInfo cpuinfo;\n size_t thrs = cpuinfo.getCores();\n initEventHandler();\nMAINWORKERLOOP:\n ThreadPool thpool;\n for (size_t i = 0; i < thrs; i++) {\n Thread *cthread=thpool.addThread();\n cthread->Create(WorkerThread, (void*)this);\n }\n for (Thread *curth = thpool.getfirstThread(); curth; curth = curth->nextThread()) {\n curth->Join();\n }\n if(libhttppp::Event::_Restart){\n libhttppp::Event::_Restart=false;\n goto MAINWORKERLOOP;\n }\n}\n\nvoid * libhttppp::Event::WorkerThread(void* wrkevent){\n Event *eventptr=((Event*)wrkevent);\n int lstate=LockState::NOLOCK;\n while (libhttppp::Event::_Run) {\n try {\n for (int i = 0; i < eventptr->waitEventHandler(); ++i) {\n if((lstate=eventptr->LockConnection(i))!=LockState::ERRLOCK){\n try{\n switch(eventptr->StatusEventHandler(i)){\n case EventApi::EventHandlerStatus::EVNOTREADY:\n eventptr->ConnectEventHandler(i);\n break;\n case EventApi::EventHandlerStatus::EVIN:\n eventptr->ReadEventHandler(i);\n break;\n case EventApi::EventHandlerStatus::EVOUT:\n eventptr->WriteEventHandler(i);\n break;\n default:\n eventptr->CloseEventHandler(i);\n break;\n }\n eventptr->UnlockConnection(i);\n }catch(HTTPException &e){\n switch(e.getErrorType()){\n case HTTPException::Critical:\n eventptr->UnlockConnection(i);\n throw e;\n case HTTPException::Error:\n try{\n eventptr->CloseEventHandler(i);\n }catch(HTTPException &e){\n if(e.getErrorType()==HTTPException::Critical){\n eventptr->UnlockConnection(i);\n throw e;\n }\n }\n break; \n }\n eventptr->UnlockConnection(i);\n }\n } \n }\n }catch(HTTPException &e){\n switch(e.getErrorType()){\n case HTTPException::Critical:\n throw e;\n break;\n default:\n Console con;\n con << e.what() << con.endl;\n }\n }\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"command_line_efl.h\"\n\n#include <string>\n#include <cstring>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/content_client.h\"\n#include \"cc\/base\/switches.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"extensions\/common\/switches.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"url\/gurl.h\"\n\n\nint CommandLineEfl::argc_ = 0;\nchar** CommandLineEfl::argv_ = NULL;\nCommandLineEfl::ArgumentVector CommandLineEfl::original_arguments_;\n\nvoid CommandLineEfl::Init(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n argc_ = argc;\n argv_ = argv;\n\n \/\/ Unfortunately chromium modifies application's argument vector.\n \/\/ during initialization. This means that chromium after initialization\n \/\/ argv will only contain one valid entry, argv[0]. To be able to use\n \/\/ user provided arguments after initialization we need to make a copy\n \/\/ of them.\n \/\/ See: chromium\/src\/content\/common\/set_process_title_linux.cc\n for (int i = 0; i < argc; ++i)\n original_arguments_.push_back(std::string(argv[i]));\n}\n\ncontent::MainFunctionParams CommandLineEfl::GetDefaultPortParams() {\n CommandLine* p_command_line = CommandLine::ForCurrentProcess();\n\n p_command_line->AppendSwitch(switches::kNoSandbox);\n p_command_line->AppendSwitch(switches::kDisablePlugins);\n p_command_line->AppendSwitch(switches::kInProcessGPU);\n\n p_command_line->AppendSwitch(switches::kUseMobileUserAgent);\n p_command_line->AppendSwitch(switches::kEnableViewportMeta);\n#if defined(OS_TIZEN)\n p_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);\n p_command_line->AppendSwitch(switches::kTouchEvents);\n p_command_line->AppendSwitch(switches::kEnablePinch);\n p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationEGLName);\n p_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);\n p_command_line->AppendSwitch(switches::kEnableSpatialNavigation);\n#else\n p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationDesktopName);\n p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);\n#endif\n\n p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);\n p_command_line->AppendSwitch(switches::kDisableImplSidePainting);\n\n p_command_line->AppendSwitch(switches::kEnableThreadedCompositing);\n p_command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);\n\n#warning \"[M37] Investigae removed command line switches, are they still needed, do they have a replacement?\"\n \/\/p_command_line->AppendSwitch(switches::kForceCompositingMode);\n \/\/p_command_line->AppendSwitch(switches::kAllowWebUICompositing);\n \/\/p_command_line->AppendSwitch(cc::switches::kEnableMapImage);\n\n p_command_line->AppendSwitch(switches::kEnableImplSidePainting);\n\n \/\/ XXX: Skia benchmarking should be only used for testing,\n \/\/ when enabled the following warning is printed to stderr:\n \/\/ \"Enabling unsafe Skia benchmarking extension.\"\n \/\/ p_command_line->AppendSwitch(switches::kEnableSkiaBenchmarking);\n\n AppendUserArgs(*p_command_line);\n\n return content::MainFunctionParams(*p_command_line);\n}\n\nvoid CommandLineEfl::AppendProcessSpecificArgs(CommandLine& command_line) {\n std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType);\n\n if (process_type == switches::kRendererProcess) {\n command_line.AppendSwitch(switches::kDisablePlugins);\n }\n AppendUserArgs(command_line);\n}\n\nvoid CommandLineEfl::AppendUserArgs(CommandLine& command_line) {\n for (ArgumentVector::const_iterator it = original_arguments_.begin();\n it != original_arguments_.end(); ++it) {\n command_line.AppendSwitch(*it);\n }\n}\n<commit_msg>Temporarily disable zero copy as it causes browser crash during regression<commit_after>#include \"command_line_efl.h\"\n\n#include <string>\n#include <cstring>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/content_client.h\"\n#include \"cc\/base\/switches.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"extensions\/common\/switches.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"url\/gurl.h\"\n\n\nint CommandLineEfl::argc_ = 0;\nchar** CommandLineEfl::argv_ = NULL;\nCommandLineEfl::ArgumentVector CommandLineEfl::original_arguments_;\n\nvoid CommandLineEfl::Init(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n argc_ = argc;\n argv_ = argv;\n\n \/\/ Unfortunately chromium modifies application's argument vector.\n \/\/ during initialization. This means that chromium after initialization\n \/\/ argv will only contain one valid entry, argv[0]. To be able to use\n \/\/ user provided arguments after initialization we need to make a copy\n \/\/ of them.\n \/\/ See: chromium\/src\/content\/common\/set_process_title_linux.cc\n for (int i = 0; i < argc; ++i)\n original_arguments_.push_back(std::string(argv[i]));\n}\n\ncontent::MainFunctionParams CommandLineEfl::GetDefaultPortParams() {\n CommandLine* p_command_line = CommandLine::ForCurrentProcess();\n\n p_command_line->AppendSwitch(switches::kNoSandbox);\n p_command_line->AppendSwitch(switches::kDisablePlugins);\n p_command_line->AppendSwitch(switches::kInProcessGPU);\n\n p_command_line->AppendSwitch(switches::kUseMobileUserAgent);\n p_command_line->AppendSwitch(switches::kEnableViewportMeta);\n#if defined(OS_TIZEN)\n p_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);\n p_command_line->AppendSwitch(switches::kTouchEvents);\n p_command_line->AppendSwitch(switches::kEnablePinch);\n p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationEGLName);\n p_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);\n p_command_line->AppendSwitch(switches::kEnableSpatialNavigation);\n#else\n p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationDesktopName);\n p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);\n#endif\n\n p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);\n p_command_line->AppendSwitch(switches::kDisableImplSidePainting);\n\n p_command_line->AppendSwitch(switches::kEnableThreadedCompositing);\n p_command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);\n\n#warning \"[M37] Investigae removed command line switches, are they still needed, do they have a replacement?\"\n \/\/p_command_line->AppendSwitch(switches::kForceCompositingMode);\n \/\/p_command_line->AppendSwitch(switches::kAllowWebUICompositing);\n \/\/ [M37] Note: The commit \"Temporarily disable zero copy as it causes browser crash during regression\"\n \/\/ is to deprecate kEnableMapImage option.\n \/\/ But it was already deprecated during fixing M37 build as no command line option with such name (see above comment)\n \/\/ TODO: remove this commit if it turn out the option is unnecessary\n \/\/Disabling temporarily, as it causes browser crash ID:335 in regression\n \/\/p_command_line->AppendSwitch(cc::switches::kEnableMapImage);\n\n p_command_line->AppendSwitch(switches::kEnableImplSidePainting);\n\n \/\/ XXX: Skia benchmarking should be only used for testing,\n \/\/ when enabled the following warning is printed to stderr:\n \/\/ \"Enabling unsafe Skia benchmarking extension.\"\n \/\/ p_command_line->AppendSwitch(switches::kEnableSkiaBenchmarking);\n\n AppendUserArgs(*p_command_line);\n\n return content::MainFunctionParams(*p_command_line);\n}\n\nvoid CommandLineEfl::AppendProcessSpecificArgs(CommandLine& command_line) {\n std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType);\n\n if (process_type == switches::kRendererProcess) {\n command_line.AppendSwitch(switches::kDisablePlugins);\n }\n AppendUserArgs(command_line);\n}\n\nvoid CommandLineEfl::AppendUserArgs(CommandLine& command_line) {\n for (ArgumentVector::const_iterator it = original_arguments_.begin();\n it != original_arguments_.end(); ++it) {\n command_line.AppendSwitch(*it);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MATH_CORE_MATRIX_INL\n#define MATH_CORE_MATRIX_INL\n\n#include \"matrix.hpp\"\n\nusing namespace math::core;\n\n#endif\n<commit_msg>Implemented most of the matrix class.<commit_after>#ifndef MATH_CORE_MATRIX_INL\n#define MATH_CORE_MATRIX_INL\n\n#include <array>\n#include <cstddef>\n\n#include \"matrix.hpp\"\n\nusing namespace math::core;\n\n\/**\n * Set this matrix equal to another.\n * @param other Matrix to set equal to.\n * @return The modified vector.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M>& Matrix<T, N, M>::operator=(const Matrix<T, N, M>& other) {\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tthis->data[i] = other.data[i];\n\t}\n\treturn *this;\n}\n\n\/**\n * Access a matrix element using an index.\n * @param idx Location of element to access.\n * @return Accessed element.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nT Matrix<T, N, M>::operator[](const std::size_t idx) const {\n\treturn this->data.at(idx);\n}\n\n\/**\n * Add and modify a vector element by index.\n * @param idx Location of element to access.\n * @return Modified element.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nT& Matrix<T, N, M>::operator[](const std::size_t idx) {\n\treturn this->data.at(idx);\n}\n\n\/**\n * Negate a matrix.\n * @return The matrix negated.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M> Matrix<T, N, M>::operator-(void) const {\n\tMatrix<T, N, M> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tR.data[i] = -this->data[i];\n\t}\n\treturn R;\n}\n\n\/**\n * Matrix addition.\n * @param W Matrix to add.\n * @return The matrix sum.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M> Matrix<T, N, M>::operator+(const Matrix<T, N, M>& W) const {\n\tMatrix<T, N, M> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tR.data[i] = this->data[i] + W.data[i];\n\t}\n\treturn R;\n}\n\n\/**\n * Matrix addition. Copy the result into this matrix.\n * @param W Matrix to add.\n * @return The modified matrix (matrix sum).\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M>& Matrix<T, N, M>::operator+=(const Matrix<T, N, M>& W) {\n\treturn *this = *this + W;\n}\n\n\/**\n * Matrix subtraction.\n * @param W Matrix to subtract.\n * @return The matrix difference.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M> Matrix<T, N, M>::operator-(const Matrix<T, N, M>& W) const {\n\tMatrix<T, N, M> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tR.data[i] = this->data[i] - W.data[i];\n\t}\n\treturn R;\n}\n\n\/**\n * Matrix subtraction. Copy the result into this matrix.\n * @param W Matrix to subtract.\n * @return The modified matrix (matrix difference).\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M>& Matrix<T, N, M>::operator-=(const Matrix<T, N, M>& W) {\n\treturn *this = *this - W;\n}\n\n\/**\n * Matrix multiplication.\n * @param W Matrix to multiply by.\n * @return Matrix product.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\ntemplate<std::size_t P>\nMatrix<T, P, M> Matrix<T, N, M>::operator*(const Matrix<T, P, N>& W) const {\n\t\/\/ TODO\n\t(void)W;\n\treturn Matrix<T, P, M>();\n}\n\n\/**\n * Scalar multiplication.\n * @param s Scalar to multiply by.\n * @return Matrix-scalar product.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M> Matrix<T, N, M>::operator*(const T& s) const {\n\tMatrix<T, N, M> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tR.data[i] = this->data[i] * s;\n\t}\n\treturn R;\n}\n\n\/**\n * Scalar multiplication. Copy the result into this matrix.\n * @param s Scalar to multiply by.\n * @return The modified matrix (matrix-scalar product).\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M>& Matrix<T, N, M>::operator*=(const T& s) {\n\treturn *this = *this * s;\n}\n\n\/**\n * Scalar division.\n * @param s Scalar to divide by.\n * @return Matrix-scalar quotient.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M> Matrix<T, N, M>::operator\/(const T& s) const {\n\tMatrix<T, N, M> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tR.data[i] = this->data[i] \/ s;\n\t}\n\treturn R;\n}\n\n\/**\n * Scalar division. Copy the result into this matrix.\n * @param s Scalar to divide by.\n * @return The modified matrix (matrix-scalar quotient).\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, N, M>& Matrix<T, N, M>::operator\/=(const T& s) {\n\treturn *this = *this \/ s;\n}\n\n\/**\n * Traspose this matrix.\n * @return Matrix transpose.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nMatrix<T, M, N> Matrix<T, N, M>::transpose(void) const {\n\tMatrix<T, M, N> R;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tfor (std::size_t j = 0; j < M; j++) {\n\t\t\tR.data[j][i] = this->data[i][j];\n\t\t}\n\t}\n\treturn R;\n}\n\n\/**\n * Check matrix equality.\n * @param other Matrix to check equality with.\n * @return True if they are equal, otherwise false.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nbool Matrix<T, N, M>::operator==(const Matrix<T, N, M>& other) const {\n\tbool equal = true;\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tequal = equal && this->data[i] == other.data[i];\n\t}\n\treturn equal;\n}\n\n\/**\n * Check matrix inequality.\n * @param other Matrix to check inequality with.\n * @return False if they are equal, otherwise true.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\nbool Matrix<T, N, M>::operator!=(const Matrix<T, N, M>& other) const {\n\treturn !(*this == other);\n}\n\n\/**\n * Calculate this matrix determinant.\n * @return Matrix determinant.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\ntemplate<typename U, typename>\nT Matrix<T, N, M>::det(void) const {\n\t\/\/ TODO\n\treturn T();\n}\n\n\/**\n * Calculate the matrix inverse.\n * @return Matrix inverse.\n *\/\ntemplate<typename T, std::size_t N, std::size_t M>\ntemplate<typename U, typename>\nMatrix<T, N, M> Matrix<T, N, M>::inverse(void) const {\n\t\/\/ TODO\n\treturn Matrix<T, N, M>();\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_MAP_HXX\n#define _ABACLADE_MAP_HXX\n\n#ifndef _ABACLADE_HXX\n #error Please #include <abaclade.hxx> before this file\n#endif\n#ifdef ABC_CXX_PRAGMA_ONCE\n #pragma once\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::map\n\nnamespace abc {\n\ntemplate <typename TKey, typename TVal>\nclass map {\npublic:\n \/*! Constructor.\n\n TODO: comment signature.\n *\/\n map() {\n }\n map(map const & m) {\n }\n map(map && m) {\n }\n\n \/\/! Destructor.\n ~map() {\n }\n\n \/*! Assignment operator.\n\n TODO: comment signature.\n *\/\n map & operator=(map const & m) {\n return map_impl::operator=(m);\n }\n map & operator=(map && m) {\n return map_impl::operator=(std::move(m));\n }\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifndef _ABACLADE_MAP_HXX\n\n<commit_msg>Partial implementation of hopscotch hashing-based abc::map<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_MAP_HXX\n#define _ABACLADE_MAP_HXX\n\n#ifndef _ABACLADE_HXX\n #error Please #include <abaclade.hxx> before this file\n#endif\n#ifdef ABC_CXX_PRAGMA_ONCE\n #pragma once\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::map\n\nnamespace abc {\n\n\/\/! Key\/value map using a simplified hopscotch hashing collision resolution algorithm.\ntemplate <typename TKey, typename TValue, typename THasher = std::hash<TKey>>\nclass map : public THasher {\npublic:\n \/\/! Hash generator for TKey.\n typedef THasher hasher;\n\npublic:\n \/*! Constructor.\n\n @param m\n Source object.\n *\/\n map() :\n m_cBuckets(0),\n m_cUsedBuckets(0) {\n }\n map(map && m) :\n m_piHashes(std::move(m.m_piHashes)),\n m_pkeys(std::move(m.m_pkeys)),\n m_pvalues(std::move(m.m_pvalues)),\n m_cBuckets(m.m_cBuckets),\n m_cUsedBuckets(m.m_cUsedBuckets) {\n m.m_cBuckets = 0;\n m.m_cUsedBuckets = 0;\n }\n\n \/\/! Destructor.\n ~map() {\n clear();\n }\n\n \/*! Assignment operator.\n\n @param m\n Source object.\n *\/\n map & operator=(map && m) {\n m_piHashes = std::move(m.m_piHashes);\n m_pkeys = std::move(m.m_pkeys);\n m_pvalues = std::move(m.m_pvalues);\n m_cBuckets = m.m_cBuckets;\n m.m_cBuckets = 0;\n m_cUsedBuckets = m.m_cUsedBuckets;\n m.m_cUsedBuckets = 0;\n return *this;\n }\n\n void add(TKey key, TValue value) {\n }\n\n \/\/! Removes all elements from the map.\n void clear() {\n std::size_t * piHash = m_piHashes, * piHashesEnd = piHash + m_cBuckets;\n TKey * pkey = &get_key(0);\n TValue * pvalue = &get_value(0);\n for (; piHash < piHashesEnd; ++piHash, ++pkey, ++pvalue) {\n if (*piHash != smc_iEmptyBucket) {\n pkey->~TKey();\n pvalue->~TValue();\n }\n }\n m_cUsedBuckets = 0;\n }\n\n \/*! Removes a key\/value pair given the key, which must be in the map.\n\n @param key\n Key associated to the value to remove.\n *\/\n void remove(TKey const & key) {\n \/\/ Get the exact bucket in the neighborhood of the key’s hash.\n std::size_t iBucket = get_key_bucket_index(key);\n \/\/ Mark the bucket as free and destruct the corresponding key and value.\n m_piHashes[iBucket] = smc_iEmptyBucket;\n get_key(iBucket).~TKey();\n get_value(iBucket).~TValue();\n }\n\nprivate:\n void create_empty_buckets(std::size_t cBuckets = smc_cBucketsMin) {\n m_piHashes.reset(new std::size_t[cBuckets]);\n m_pkeys.reset(new std::max_align_t[ABC_ALIGNED_SIZE(sizeof(TKey) * cBuckets)]);\n m_pvalues.reset(new std::max_align_t[ABC_ALIGNED_SIZE(sizeof(TValue) * cBuckets)]);\n m_cBuckets = cBuckets;\n }\n\n std::size_t get_key_bucket_index(TKey const & key) const {\n return get_key_bucket_index(key, get_and_adjust_hash(key));\n }\n std::size_t get_key_bucket_index(TKey const & key, std::size_t iHash) const {\n \/\/ Get a range of indices representing the neighborhood.\n std::size_t iNeighborhoodBegin = hash_to_neighborhood_index(iHash);\n std::size_t iNeighborhoodEnd = iNeighborhoodBegin + smc_cNeighborhood;\n \/* Determine if we’ll need to check any buckets at the beginning of the array due to the\n neighborhood wrapping. *\/\n std::size_t iWrappedNeighborhoodEnd;\n if (iNeighborhoodEnd > m_cBuckets) {\n iWrappedNeighborhoodEnd = iNeighborhoodEnd - m_cBuckets;\n iNeighborhoodEnd = m_cBuckets;\n } else {\n iWrappedNeighborhoodEnd = 0;\n }\n \/\/ Scan till the end of the neighborhood (clipped to the end of the array).\n std::size_t iBucket = scan_buckets_for_key(key, iHash, iNeighborhoodBegin, iNeighborhoodEnd);\n if (iBucket == smc_iKeyNotFound && iWrappedNeighborhoodEnd) {\n \/\/ Scan the remaining buckets, if this neighborhood wraps.\n iBucket = scan_buckets_for_key(key, iHash, 0, iWrappedNeighborhoodEnd);\n if (iBucket == smc_iKeyNotFound) {\n \/\/ The specified key is not in the map.\n \/\/ TODO: throw proper exception.\n throw 0;\n }\n }\n return iBucket;\n }\n\n \/*! Calculates, adjusts and returns the hash value for the specified key.\n\n @param key\n Key to calculate a hash value for.\n @return\n Hash value of key.\n *\/\n std::size_t get_and_adjust_hash(TKey const & key) const {\n std::size_t iHash = hasher::operator()(key);\n return iHash == smc_iEmptyBucket ? smc_iZeroHash : iHash;\n }\n\n TKey & get_key(std::size_t i) const {\n return reinterpret_cast<TKey *>(m_pkeys.get())[i];\n }\n\n TValue & get_value(std::size_t i) const {\n return reinterpret_cast<TKey *>(m_pvalues.get())[i];\n }\n\n std::size_t hash_to_neighborhood_index(std::size_t iHash) const {\n if (!m_cBuckets) {\n \/\/ No buckets, no index can be returned. This means that iHash cannot be in the map.\n \/\/ TODO: throw proper exception.\n throw 0;\n }\n return iHash & (m_cBuckets - 1);\n }\n\n bool keys_equal(TKey const & key1, TKey const & key2) const {\n return key1 == key2;\n }\n\n \/*! Scans a range of buckets, looking for a specific key.\n\n @param key\n Key to scan for.\n @param iHash\n Hash of key.\n @param iBegin\n Start of the bucket range.\n @param iEnd\n End of the bucket range.\n @return\n Index of the bucket at which the key could be found, or smc_iKeyNotFound if the key was not\n found.\n *\/\n std::size_t scan_buckets_for_key(\n TKey const & key, std::size_t iHash, std::size_t iBegin, std::size_t iEnd\n ) const {\n std::size_t const * piHashesBegin = m_piHashes + iBegin, * piHashesEnd = m_piHashes + iEnd;\n TKey const * pkey = m_pkeys + iBegin;\n for (std::size_t const * piHash = piHashesBegin; piHash < piHashesEnd; ++piHash, ++pkey) {\n if (*piHash == iHash && keys_equal(*pkey == key)) {\n return piHash - piHashesBegin;\n }\n }\n return smc_iKeyNotFound;\n }\n\nprivate:\n \/\/! Array containing the hash of each key.\n std::unique_ptr<std::size_t[]> m_piHashes;\n \/\/! Array of keys.\n std::unique_ptr<std::max_align_t[]> m_pkeys;\n \/\/! Array of buckets.\n std::unique_ptr<std::max_align_t[]> m_pvalues;\n \/\/! Count of total buckets.\n std::size_t m_cBuckets;\n \/\/! Count of elements \/ occupied buckets.\n std::size_t m_cUsedBuckets;\n \/\/! Neighborhood size.\n static std::size_t const smc_cNeighborhood = sizeof(std::size_t) * CHAR_BIT;\n \/\/! Minimum bucket count.\n static std::size_t const smc_cBucketsMin = 8;\n \/\/! Special hash value used to indicate that a bucket is empty.\n static std::size_t const smc_iEmptyBucket = 0;\n \/*! Special index returned by scan_buckets_for_key() to indicate that the key could not be found\n in the specified range. *\/\n static std::size_t const smc_iKeyNotFound = numeric::max<std::size_t>::value;\n \/*! Hash value substituted when the hash function returns 0; this is so we can use 0 (aliased by\n smc_iEmptyBucket) as a special value. This specific value is merely the largest prime number that\n will fit in 2^16, which is the (future, if ever) minimum word size supported by Abaclade. *\/\n static std::size_t const smc_iZeroHash = 65521;\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifndef _ABACLADE_MAP_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * include\/arrays\/slice.hpp\n *\n * Copyright (C) 2018 Marvin Löbel <loebel.marvin@gmail.com>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#pragma once\n\n#include <cstring>\n#include <iostream>\n\n#include \"util\/common.hpp\"\n#include \"util\/debug_assert.hpp\"\n\ntemplate<typename T>\nclass Slice {\n T* m_ptr;\n size_t m_size;\npublic:\n inline Slice(T* ptr, size_t size):\n m_ptr(ptr), m_size(size) {}\n inline size_t size() const {\n return m_size;\n }\n inline T& operator[](size_t i) const {\n DCHECK(i < size());\n return m_ptr[i];\n }\n inline T* data() const {\n return m_ptr;\n }\n};\n\n\n\/******************************************************************************\/\n<commit_msg>Add slice() method to Slice<commit_after>\/*******************************************************************************\n * include\/arrays\/slice.hpp\n *\n * Copyright (C) 2018 Marvin Löbel <loebel.marvin@gmail.com>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#pragma once\n\n#include <cstring>\n#include <iostream>\n\n#include \"util\/common.hpp\"\n#include \"util\/debug_assert.hpp\"\n\ntemplate<typename T>\nclass Slice {\n T* m_ptr;\n size_t m_size;\npublic:\n inline Slice(T* ptr, size_t size):\n m_ptr(ptr), m_size(size) {}\n inline size_t size() const {\n return m_size;\n }\n inline T& operator[](size_t i) const {\n DCHECK(i < size());\n return m_ptr[i];\n }\n inline T* data() const {\n return m_ptr;\n }\n inline Slice slice(size_t start, size_t end) const {\n DCHECK(start <= m_size);\n DCHECK(end <= m_size);\n DCHECK(start <= end);\n return Slice { m_ptr + start, end - start };\n }\n};\n\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Flann LSH\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n\n#include <flann\/flann.hpp>\n\nusing namespace flann;\nusing namespace std;\n\nvoid load_from_file(Matrix<float>& dataset, const string& filename) {\n ifstream dfile(filename);\n if (!dfile.is_open()) {\n cout << \"unable to open data set file: \" << filename << endl;\n exit(1);\n }\n\n string line;\n\n int i = 0;\n while (dfile >> line) {\n for (unsigned j = 0; i < line.length(); i++) {\n dataset[i][j] = line[j]-'0';\n }\n i++;\n }\n\n dfile.close();\n}\n\nint main(int argc, char** argv) {\n int d = 10;\n Matrix<float> dataset(new float[16*d], 16, d);\n Matrix<float> query(new float[4*d], 4, d);\n load_from_file(dataset, \"data\/files\/d10nd16\");\n load_from_file(query, \"data\/files\/d10nq4\");\n\n Matrix<int> indices(new int[query.rows*d], query.rows, d);\n Matrix<float> dists(new float[query.rows*d], query.rows, d);\n\n \/\/ construct a hierarchical clustering index\n \/\/ default paramaters:\n \/\/ branching factor: 32\n \/\/ centers: random\n \/\/ number of parallel trees: 4\n \/\/ leaf_max_size: 100\n Index<L2<float>> index(dataset, flann::HierarchicalClusteringIndexParams());\n index.buildIndex();\n\n \/\/ do a radius search, using 128 checks\n \/\/ checks : specifies the maximum leafs to visit when searching for neigbors\n int n = index.radiusSearch(query, indices, dists, 3, flann::SearchParams(128));\n cout << \"number of nearest neighbors: \" << n << endl;\n\n delete[] dataset.ptr();\n delete[] query.ptr();\n delete[] indices.ptr();\n delete[] dists.ptr();\n \n return 0;\n}\n<commit_msg>fix a line in flann.cpp<commit_after>\/**\n * Flann LSH\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n\n#include <flann\/flann.hpp>\n\nusing namespace flann;\nusing namespace std;\n\nvoid load_from_file(Matrix<float>& dataset, const string& filename) {\n ifstream dfile(filename);\n if (!dfile.is_open()) {\n cout << \"unable to open data set file: \" << filename << endl;\n exit(1);\n }\n\n string line;\n\n int i = 0;\n while (dfile >> line) {\n for (unsigned j = 0; j < line.length(); j++) {\n dataset[i][j] = line[j]-'0';\n }\n i++;\n }\n\n dfile.close();\n}\n\nint main(int argc, char** argv) {\n int d = 10;\n Matrix<float> dataset(new float[16*d], 16, d);\n Matrix<float> query(new float[4*d], 4, d);\n load_from_file(dataset, \"data\/files\/d10nd16\");\n load_from_file(query, \"data\/files\/d10nq4\");\n\n Matrix<int> indices(new int[query.rows*d], query.rows, d);\n Matrix<float> dists(new float[query.rows*d], query.rows, d);\n\n \/\/ construct a hierarchical clustering index\n \/\/ default paramaters:\n \/\/ branching factor: 32\n \/\/ centers: random\n \/\/ number of parallel trees: 4\n \/\/ leaf_max_size: 100\n Index<L2<float>> index(dataset, flann::HierarchicalClusteringIndexParams());\n index.buildIndex();\n\n \/\/ do a radius search, using 128 checks\n \/\/ checks : specifies the maximum leafs to visit when searching for neigbors\n int n = index.radiusSearch(query, indices, dists, 3, flann::SearchParams(128));\n cout << \"number of nearest neighbors: \" << n << endl;\n\n delete[] dataset.ptr();\n delete[] query.ptr();\n delete[] indices.ptr();\n delete[] dists.ptr();\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Formatting library for C++\n\/\/\n\/\/ Copyright (c) 2012 - 2016, Victor Zverovich\n\/\/ All rights reserved.\n\/\/\n\/\/ For the license information refer to format.h.\n\n#include \"fmt\/format-inl.h\"\n\nFMT_BEGIN_NAMESPACE\ntemplate struct internal::basic_data<void>;\ntemplate internal::locale_ref::locale_ref(const std::locale &loc);\n\n\/\/ Explicit instantiations for char.\n\ntemplate FMT_API char internal::thousands_sep_impl(locale_ref);\n\ntemplate void internal::basic_buffer<char>::append(const char *, const char *);\n\ntemplate void internal::arg_map<format_context>::init(\n const basic_format_args<format_context> &args);\n\ntemplate FMT_API int internal::char_traits<char>::format_float(\n char *, std::size_t, const char *, int, double);\n\ntemplate FMT_API int internal::char_traits<char>::format_float(\n char *, std::size_t, const char *, int, long double);\n\ntemplate FMT_API std::string internal::vformat<char>(\n string_view, basic_format_args<format_context>);\n\ntemplate format_context::iterator internal::vformat_to(\n internal::buffer &, string_view, basic_format_args<format_context>);\n\ntemplate FMT_API void internal::sprintf_format(\n double, internal::buffer &, core_format_specs);\ntemplate FMT_API void internal::sprintf_format(\n long double, internal::buffer &, core_format_specs);\n\n\/\/ Explicit instantiations for wchar_t.\n\ntemplate FMT_API wchar_t internal::thousands_sep_impl(locale_ref);\n\ntemplate void internal::basic_buffer<wchar_t>::append(\n const wchar_t *, const wchar_t *);\n\ntemplate void internal::arg_map<wformat_context>::init(\n const basic_format_args<wformat_context> &);\n\ntemplate FMT_API int internal::char_traits<wchar_t>::format_float(\n wchar_t *, std::size_t, const wchar_t *, int, double);\n\ntemplate FMT_API int internal::char_traits<wchar_t>::format_float(\n wchar_t *, std::size_t, const wchar_t *, int, long double);\n\ntemplate FMT_API std::wstring internal::vformat<wchar_t>(\n wstring_view, basic_format_args<wformat_context>);\nFMT_END_NAMESPACE\n<commit_msg>Fix link error in windows with shared library.<commit_after>\/\/ Formatting library for C++\n\/\/\n\/\/ Copyright (c) 2012 - 2016, Victor Zverovich\n\/\/ All rights reserved.\n\/\/\n\/\/ For the license information refer to format.h.\n\n#include \"fmt\/format-inl.h\"\n\nFMT_BEGIN_NAMESPACE\ntemplate struct internal::basic_data<void>;\ntemplate internal::locale_ref::locale_ref(const std::locale &loc);\n\n\/\/ Explicit instantiations for char.\n\ntemplate FMT_API char internal::thousands_sep_impl(locale_ref);\n\ntemplate FMT_API void internal::basic_buffer<char>::append(const char *, const char *);\n\ntemplate void internal::arg_map<format_context>::init(\n const basic_format_args<format_context> &args);\n\ntemplate FMT_API int internal::char_traits<char>::format_float(\n char *, std::size_t, const char *, int, double);\n\ntemplate FMT_API int internal::char_traits<char>::format_float(\n char *, std::size_t, const char *, int, long double);\n\ntemplate FMT_API std::string internal::vformat<char>(\n string_view, basic_format_args<format_context>);\n\ntemplate format_context::iterator internal::vformat_to(\n internal::buffer &, string_view, basic_format_args<format_context>);\n\ntemplate FMT_API void internal::sprintf_format(\n double, internal::buffer &, core_format_specs);\ntemplate FMT_API void internal::sprintf_format(\n long double, internal::buffer &, core_format_specs);\n\n\/\/ Explicit instantiations for wchar_t.\n\ntemplate FMT_API wchar_t internal::thousands_sep_impl(locale_ref);\n\ntemplate void internal::basic_buffer<wchar_t>::append(\n const wchar_t *, const wchar_t *);\n\ntemplate void internal::arg_map<wformat_context>::init(\n const basic_format_args<wformat_context> &);\n\ntemplate FMT_API int internal::char_traits<wchar_t>::format_float(\n wchar_t *, std::size_t, const wchar_t *, int, double);\n\ntemplate FMT_API int internal::char_traits<wchar_t>::format_float(\n wchar_t *, std::size_t, const wchar_t *, int, long double);\n\ntemplate FMT_API std::wstring internal::vformat<wchar_t>(\n wstring_view, basic_format_args<wformat_context>);\nFMT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/* Reference documentation for libpqxx.\n *\n * Documentation is generated from header files. This header is here only to\n * provide parts of that documentation. There is no need to include it from\n * client code.\n *\n * Copyright 2001-2017, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\/\n\n\/** @mainpage\n * @author Jeroen T. Vermeulen\n *\n * Welcome to libpqxx, the C++ API to the PostgreSQL database management system.\n *\n * Compiling this package requires PostgreSQL to be installed -- including the\n * C headers for client development. The library builds on top of PostgreSQL's\n * standard C API, libpq. The libpq headers are not needed to compile client\n * programs, however.\n *\n * For a quick introduction to installing and using libpqxx, see the README.md\n * file; a more extensive tutorial is available in doc\/html\/Tutorial\/index.html.\n *\n * The latest information can be found at http:\/\/pqxx.org\/\n *\n * Some links that should help you find your bearings:\n * \\li \\ref gettingstarted\n * \\li \\ref threading\n * \\li \\ref connection\n * \\li \\ref transaction\n * \\li \\ref performance\n * \\li \\ref transactor\n *\n * @see http:\/\/pqxx.org\/\n *\/\n\n\/** @page gettingstarted Getting started\n * The most basic three types in libpqxx are the connection (which inherits its\n * API from pqxx::connection_base and its setup behaviour from\n * pqxx::connectionpolicy), the transaction (derived from\n * pqxx::transaction_base), and the result (pqxx::result).\n *\n * They fit together as follows:\n * \\li You connect to the database by creating a\n * connection object (see \\ref connection). The connection type you'll usually\n * want is pqxx::connection.\n * \\li You create a transaction object (see \\ref transaction) operating on that\n * connection. You'll usually want the pqxx::work variety. If you don't want\n * transactional behaviour, use pqxx::nontransaction. Once you're done you call\n * the transaction's @c commit function to make its work final. If you don't\n * call this, the work will be rolled back when the transaction object is\n * destroyed.\n * \\li Until then, use the transaction's @c exec() functions to execute\n * queries, which you pass in as simple strings.\n * \\li Most of the @c exec() functions return a pqxx::result object, which acts\n * as a standard container of rows. Each row in itself acts as a container of\n * fields. You can use array indexing and\/or iterators to access either.\n * \\li The field's data is stored as a text string. You can read it as such\n * using its @c c_str() function, or convert it to other types using its @c as()\n * and @c to() member functions. These are templated on the destination type:\n * @c myfield.as<int>(); or @c myfield.to(myint);\n * \\li After you've closed the transaction, the connection is free to run a next\n * transaction.\n *\n * Here's a very basic example. It connects to the default database (you'll\n * need to have one set up), queries it for a very simple result, converts it to\n * an @c int, and prints it out. It also contains some basic error handling.\n *\n * @code\n * #include <iostream>\n * #include <pqxx\/pqxx>\n *\n * int main()\n * {\n * try\n * {\n * \/\/ Connect to the database. In practice we may have to pass some\n * \/\/ arguments to say where the database server is, and so on.\n * pqxx::connection c;\n *\n * \/\/ Start a transaction. In libpqxx, you always work in one.\n * pqxx::work w(c);\n *\n * \/\/ work::exec1() executes a query returning a single row of data.\n * \/\/ We'll just ask the database to return the number 1 to us.\n * pqxx::row r = w.exec1(\"SELECT 1\");\n *\n * \/\/ Commit your transaction. If an exception occurred before this\n * \/\/ point, execution will have left the block, and the transaction will\n * \/\/ have been destroyed along the way. In that case, the failed\n * \/\/ transaction would implicitly abort instead of getting to this point.\n * w.commit();\n *\n * \/\/ Look at the first and only field in the row, parse it as an integer,\n * \/\/ and print it.\n * std::cout << r[0].as<int>() << std::endl;\n * }\n * catch (const std::exception &e)\n * {\n * std::cerr << e.what() << std::endl;\n * return 1;\n * }\n * }\n * @endcode\n *\n * This prints the number 1. Notice that you can keep the result object\n * around after the transaction (or even the connection) has been closed.\n *\n * Here's a slightly more complicated example. It takes an argument from the\n * command line and retrieves a string with that value. The interesting part is\n * that it uses the escaping-and-quoting function @c quote() to embed this\n * string value in SQL safely. It also reads the result field's value as a\n * plain C-style string using its @c c_str() function.\n *\n * @code\n * #include <iostream>\n * #include <stdexcept>\n * #include <pqxx\/pqxx>\n *\n * int main(int argc, char *argv[])\n * {\n * try\n * {\n * if (!argv[1]) throw std::runtime_error(\"Give me a string!\");\n *\n * pqxx::connection c;\n * pqxx::work w(c);\n *\n * \/\/ work::exec() returns a full result set, which can consist of any\n * \/\/ number of rows.\n * pqxx::result r = w.exec(\"SELECT \" + w.quote(argv[1]));\n *\n * \/\/ End our transaction here. We can still use the result afterwards.\n * w.commit();\n *\n * \/\/ Print the first field of the first row. Read it as a C string,\n * \/\/ just like std::string::c_str() does.\n * std::cout << r[0][0].c_str() << std::endl;\n * }\n * catch (const std::exception &e)\n * {\n * std::cerr << e.what() << std::endl;\n * return 1;\n * }\n * }\n * @endcode\n *\n * You can find more about converting field values to native types, or\n * converting values to strings for use with libpqxx, under\n * \\ref stringconversion. More about getting to the rows and fields of a\n * result is under \\ref accessingresults.\n *\n * If you want to handle exceptions thrown by libpqxx in more detail, for\n * example to print the SQL contents of a query that failed, see \\ref exception.\n *\/\n\n\/** @page accessingresults Accessing results and result rows\n *\n * Let's say you have a result object. For example, your program may have done:\n *\n * @code\n * pqxx::result r = w.exec(\"SELECT * FROM mytable\");\n * @endcode\n *\n * Now how do you access the data inside @c r?\n *\n * The simplest way is array indexing. A result acts as an array of rows,\n * and a row acts as an array of fields.\n *\n * @code\n * const int num_rows = r.size();\n * for (int rownum=0; rownum < num_rows; ++rownum)\n * {\n * const pqxx::row row = r[rownum];\n * const int num_cols = row.size();\n * for (int colnum=0; colnum < num_cols; ++colnum)\n * {\n * const pqxx::field field = row[colnum];\n * std::cout << field.c_str() << '\\t';\n * }\n *\n * std::cout << std::endl;\n * }\n * @endcode\n *\n * But results and rows also define @c const_iterator types:\n *\n * @code\n * for (const auto &row: r)\n * {\n * for (const auto &field: row) std::cout << field.c_str() << '\\t';\n * std::cout << std::endl;\n * }\n * @endcode\n *\n * They also have @c const_reverse_iterator types, which iterate backwards from\n * @c rbegin() to @c rend() exclusive.\n *\n * All these iterator types provide one extra bit of convenience that you won't\n * normally find in C++ iterators: referential transparency. You don't need to\n * dereference them to get to the row or field they refer to. That is, instead\n * of @c row->end() you can also choose to say @c row.end(). Similarly, you\n * may prefer @c field.c_str() over @c field->c_str().\n *\n * This becomes really helpful with the array-indexing operator. With regular\n * C++ iterators you would need ugly expressions like @c (*row)[0] or\n * @c row->operator[](0). With the iterator types defined by the result and\n * row classes you can simply say @c row[0].\n *\/\n\n\/** @page threading Thread safety\n *\n * This library does not contain any locking code to protect objects against\n * simultaneous modification in multi-threaded programs. Therefore it is up\n * to you, the user of the library, to ensure that your threaded client\n * programs perform no conflicting operations concurrently.\n *\n * Most of the time this isn't hard. Result sets are immutable, so you can\n * share them between threads without problem. The main rule is:\n *\n * \\li Treat a connection, together with any and all objects related to it, as\n * a \"world\" of its own. You should generally make sure that the same \"world\"\n * is never accessed by another thread while you're doing anything non-const\n * in there.\n *\n * That means: don't issue a query on a transaction while you're also opening\n * a subtransaction, don't access a cursor while you may also be committing,\n * and so on.\n *\n * In particular, cursors are tricky. It's easy to perform a non-const\n * operation without noticing. So, if you're going to share cursors or\n * cursor-related objects between threads, lock very conservatively!\n *\n * Use @c pqxx::describe_thread_safety to find out at runtime what level of\n * thread safety is implemented in your build and version of libpqxx. It\n * returns a pqxx::thread_safety_model describing what you can and cannot rely\n * on. A command-line utility @c tools\/pqxxthreadsafety prints out the same\n * information.\n *\/\n<commit_msg>Documentation: suggest easiest iterations first.<commit_after>\/* Reference documentation for libpqxx.\n *\n * Documentation is generated from header files. This header is here only to\n * provide parts of that documentation. There is no need to include it from\n * client code.\n *\n * Copyright 2001-2017, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\/\n\n\/** @mainpage\n * @author Jeroen T. Vermeulen\n *\n * Welcome to libpqxx, the C++ API to the PostgreSQL database management system.\n *\n * Compiling this package requires PostgreSQL to be installed -- including the\n * C headers for client development. The library builds on top of PostgreSQL's\n * standard C API, libpq. The libpq headers are not needed to compile client\n * programs, however.\n *\n * For a quick introduction to installing and using libpqxx, see the README.md\n * file; a more extensive tutorial is available in doc\/html\/Tutorial\/index.html.\n *\n * The latest information can be found at http:\/\/pqxx.org\/\n *\n * Some links that should help you find your bearings:\n * \\li \\ref gettingstarted\n * \\li \\ref threading\n * \\li \\ref connection\n * \\li \\ref transaction\n * \\li \\ref performance\n * \\li \\ref transactor\n *\n * @see http:\/\/pqxx.org\/\n *\/\n\n\/** @page gettingstarted Getting started\n * The most basic three types in libpqxx are the connection (which inherits its\n * API from pqxx::connection_base and its setup behaviour from\n * pqxx::connectionpolicy), the transaction (derived from\n * pqxx::transaction_base), and the result (pqxx::result).\n *\n * They fit together as follows:\n * \\li You connect to the database by creating a\n * connection object (see \\ref connection). The connection type you'll usually\n * want is pqxx::connection.\n * \\li You create a transaction object (see \\ref transaction) operating on that\n * connection. You'll usually want the pqxx::work variety. If you don't want\n * transactional behaviour, use pqxx::nontransaction. Once you're done you call\n * the transaction's @c commit function to make its work final. If you don't\n * call this, the work will be rolled back when the transaction object is\n * destroyed.\n * \\li Until then, use the transaction's @c exec() functions to execute\n * queries, which you pass in as simple strings.\n * \\li Most of the @c exec() functions return a pqxx::result object, which acts\n * as a standard container of rows. Each row in itself acts as a container of\n * fields. You can use array indexing and\/or iterators to access either.\n * \\li The field's data is stored as a text string. You can read it as such\n * using its @c c_str() function, or convert it to other types using its @c as()\n * and @c to() member functions. These are templated on the destination type:\n * @c myfield.as<int>(); or @c myfield.to(myint);\n * \\li After you've closed the transaction, the connection is free to run a next\n * transaction.\n *\n * Here's a very basic example. It connects to the default database (you'll\n * need to have one set up), queries it for a very simple result, converts it to\n * an @c int, and prints it out. It also contains some basic error handling.\n *\n * @code\n * #include <iostream>\n * #include <pqxx\/pqxx>\n *\n * int main()\n * {\n * try\n * {\n * \/\/ Connect to the database. In practice we may have to pass some\n * \/\/ arguments to say where the database server is, and so on.\n * pqxx::connection c;\n *\n * \/\/ Start a transaction. In libpqxx, you always work in one.\n * pqxx::work w(c);\n *\n * \/\/ work::exec1() executes a query returning a single row of data.\n * \/\/ We'll just ask the database to return the number 1 to us.\n * pqxx::row r = w.exec1(\"SELECT 1\");\n *\n * \/\/ Commit your transaction. If an exception occurred before this\n * \/\/ point, execution will have left the block, and the transaction will\n * \/\/ have been destroyed along the way. In that case, the failed\n * \/\/ transaction would implicitly abort instead of getting to this point.\n * w.commit();\n *\n * \/\/ Look at the first and only field in the row, parse it as an integer,\n * \/\/ and print it.\n * std::cout << r[0].as<int>() << std::endl;\n * }\n * catch (const std::exception &e)\n * {\n * std::cerr << e.what() << std::endl;\n * return 1;\n * }\n * }\n * @endcode\n *\n * This prints the number 1. Notice that you can keep the result object\n * around after the transaction (or even the connection) has been closed.\n *\n * Here's a slightly more complicated example. It takes an argument from the\n * command line and retrieves a string with that value. The interesting part is\n * that it uses the escaping-and-quoting function @c quote() to embed this\n * string value in SQL safely. It also reads the result field's value as a\n * plain C-style string using its @c c_str() function.\n *\n * @code\n * #include <iostream>\n * #include <stdexcept>\n * #include <pqxx\/pqxx>\n *\n * int main(int argc, char *argv[])\n * {\n * try\n * {\n * if (!argv[1]) throw std::runtime_error(\"Give me a string!\");\n *\n * pqxx::connection c;\n * pqxx::work w(c);\n *\n * \/\/ work::exec() returns a full result set, which can consist of any\n * \/\/ number of rows.\n * pqxx::result r = w.exec(\"SELECT \" + w.quote(argv[1]));\n *\n * \/\/ End our transaction here. We can still use the result afterwards.\n * w.commit();\n *\n * \/\/ Print the first field of the first row. Read it as a C string,\n * \/\/ just like std::string::c_str() does.\n * std::cout << r[0][0].c_str() << std::endl;\n * }\n * catch (const std::exception &e)\n * {\n * std::cerr << e.what() << std::endl;\n * return 1;\n * }\n * }\n * @endcode\n *\n * You can find more about converting field values to native types, or\n * converting values to strings for use with libpqxx, under\n * \\ref stringconversion. More about getting to the rows and fields of a\n * result is under \\ref accessingresults.\n *\n * If you want to handle exceptions thrown by libpqxx in more detail, for\n * example to print the SQL contents of a query that failed, see \\ref exception.\n *\/\n\n\/** @page accessingresults Accessing results and result rows\n *\n * Let's say you have a result object. For example, your program may have done:\n *\n * @code\n * pqxx::result r = w.exec(\"SELECT * FROM mytable\");\n * @endcode\n *\n * Now how do you access the data inside @c r?\n *\n * Result sets act as standard C++ containers of rows. Rows act as standard\n * C++ containers of fields. So the easiest way to go through them is:\n *\n * @code\n * for (const auto &row: r)\n * {\n * for (const auto &field: row) std::cout << field.c_str() << '\\t';\n * std::cout << std::endl;\n * }\n * @endcode\n *\n * But results and rows also support other kinds of access. Array-style\n * indexing, for instance:\n *\n * @code\n * const int num_rows = r.size();\n * for (int rownum=0; rownum < num_rows; ++rownum)\n * {\n * const pqxx::row row = r[rownum];\n * const int num_cols = row.size();\n * for (int colnum=0; colnum < num_cols; ++colnum)\n * {\n * const pqxx::field field = row[colnum];\n * std::cout << field.c_str() << '\\t';\n * }\n *\n * std::cout << std::endl;\n * }\n * @endcode\n *\n * And of course you can use classic \"begin\/end\" loops:\n *\n * @code\n * for (auto row = r.begin(); row != r.end(); row++)\n * {\n * for (auto field = row.begin(); field != row.end(); field++)\n * std::cout << field->c_str() << '\\t';\n * std::cout << std::endl;\n * }\n * @endcode\n *\n * Result sets are immutable, so all iterators on results and rows are actually\n * @c const_iterators. There are also @c const_reverse_iterator types, which\n * iterate backwards from @c rbegin() to @c rend() exclusive.\n *\n * All these iterator types provide one extra bit of convenience that you won't\n * normally find in C++ iterators: referential transparency. You don't need to\n * dereference them to get to the row or field they refer to. That is, instead\n * of @c row->end() you can also choose to say @c row.end(). Similarly, you\n * may prefer @c field.c_str() over @c field->c_str().\n *\n * This becomes really helpful with the array-indexing operator. With regular\n * C++ iterators you would need ugly expressions like @c (*row)[0] or\n * @c row->operator[](0). With the iterator types defined by the result and\n * row classes you can simply say @c row[0].\n *\/\n\n\/** @page threading Thread safety\n *\n * This library does not contain any locking code to protect objects against\n * simultaneous modification in multi-threaded programs. Therefore it is up\n * to you, the user of the library, to ensure that your threaded client\n * programs perform no conflicting operations concurrently.\n *\n * Most of the time this isn't hard. Result sets are immutable, so you can\n * share them between threads without problem. The main rule is:\n *\n * \\li Treat a connection, together with any and all objects related to it, as\n * a \"world\" of its own. You should generally make sure that the same \"world\"\n * is never accessed by another thread while you're doing anything non-const\n * in there.\n *\n * That means: don't issue a query on a transaction while you're also opening\n * a subtransaction, don't access a cursor while you may also be committing,\n * and so on.\n *\n * In particular, cursors are tricky. It's easy to perform a non-const\n * operation without noticing. So, if you're going to share cursors or\n * cursor-related objects between threads, lock very conservatively!\n *\n * Use @c pqxx::describe_thread_safety to find out at runtime what level of\n * thread safety is implemented in your build and version of libpqxx. It\n * returns a pqxx::thread_safety_model describing what you can and cannot rely\n * on. A command-line utility @c tools\/pqxxthreadsafety prints out the same\n * information.\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"hsApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid hsApp::setup()\n{\n\t\/\/ofBackground(34, 34, 34);\n\tofSetVerticalSync(true);\n\t\n\twidthi = 512;\n\twidthf = widthi;\n\t\n\tmesh.setMode(OF_PRIMITIVE_POINTS);\n\t\n\tfor(int y = 0; y < widthi; y++ )\n\t{\n\t\tfor(int x = 0; x < widthi; x++ )\n\t\t{\n\t\t\tofFloatColor color(x\/widthf,y\/widthf,1.f,0.5f);\n\t\t\tmesh.addColor(color);\n\t\t\tofVec3f pos(x-widthf\/2.f, y-widthf\/2.f, 0);\n\t\t\tmesh.addVertex(pos);\n\t\t}\n\t}\n\t\n\tofEnableDepthTest();\n\tglEnable(GL_POINT_SMOOTH); \/\/ use circular points instead of square points\n\tglPointSize(2); \/\/ make the points bigger\n\t\n\t\/\/ 2 output channels,\n\t\/\/ 0 input channels\n\t\/\/ 44100 samples per second\n\t\/\/ 512 samples per buffer\n\t\/\/ 4 num buffers (latency)\n\t\n\tint bufferSize\t\t= 512;\n\tsampleRate \t\t\t= 44100;\n\t\n\tphase1\t\t\t\t= 0;\n\tphase2\t\t\t\t= 0;\n\tphase3\t\t\t\t= 0;\n\t\n\tshape1\t\t\t\t= 0;\n\tshape2\t\t\t\t= 0;\n\tshape3\t\t\t\t= 0;\n\t\n\tfreeze1\t\t\t\t= 0;\n\tfreeze2\t\t\t\t= 0;\n\tfreeze3\t\t\t\t= 0;\n\t\n\tphaseAdder \t\t\t= 0.0f;\n\tvolume\t\t\t\t= 0.2f;\n\tbNoise \t\t\t\t= false;\n\t\n\tvoice1.assign(bufferSize, 0.0);\n\tvoice2.assign(bufferSize, 0.0);\n\tvoice3.assign(bufferSize, 0.0);\n\t\n\tvoices.push_back(&voice1);\n\tvoices.push_back(&voice2);\n\tvoices.push_back(&voice3);\n\t\t\n\tfrequency = targetFrequency = 110;\n\tnumerator1 = numerator2 = 2;\n\tdenominator1 = denominator2 = 3;\n\trotator = 0;\n\t\n\t\/\/soundStream.listDevices();\n\t\n\t\/\/if you want to set the device id to be different than the default\n\t\/\/soundStream.setDeviceID(1); \t\/\/note some devices are input only and some are output only\n\t\n\tsoundStream.setup(this, 2, 0, sampleRate, bufferSize, 4);\n\t\n\t\/\/\n\t\n\tplotHeight = 100;\n\t\n\t\/\/fft = ofxFft::create(bufferSize, OF_FFT_WINDOW_HAMMING, OF_FFT_FFTW);\n\tfft = ofxFft::create(bufferSize, OF_FFT_WINDOW_HAMMING);\n\t\n\tdrawBins.resize(fft->getBinSize());\n\tmiddleBins.resize(fft->getBinSize());\n\taudioBins.resize(fft->getBinSize());\n\t\n\tofSetFrameRate(30);\n}\n\n\n\/\/--------------------------------------------------------------\nvoid hsApp::update()\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::draw()\n{\n\tofBackground(34, 34, 34);\n\t\n\tint W = (ofGetWidth()-64.f)\/2.f;\n\tint H = 100;\n\t\n\tvector<ofVec3f>& verts = mesh.getVertices();\n\tvector<ofFloatColor>& color = mesh.getColors();\n\t\n\tfor(unsigned int i = 0; i < verts.size(); i++)\n\t{\n\t\tint j = ofMap(i, 0, verts.size(), 0, widthf);\n\t\t\n\t\tverts[i].x = voice1[j] * W;\n\t\tverts[i].y = voice2[j] * W;\n\t\tverts[i].z = voice3[j] * W;\n\t\t\n\t\tcolor[i].r = 1.f - voice1[j];\n\t\tcolor[i].g = 1.f - voice2[j];\n\t\tcolor[i].b = 1.f - voice3[j];\n\t}\n\t\n\tofPushMatrix();\n\tofTranslate(32+W\/2+ofGetWidth()\/2, 450, 0);\n\tofRotateY(pan*360);\n\tofRotateX(rotator);\n\trotator += 0.1f;\n\tmesh.draw();\n\tofPopMatrix();\n\t\n\t\/\/\n\t\n\tofSetColor(225);\n\tofDrawBitmapString(\"HyperScope\", 32, 32);\n\tofDrawBitmapString(\"press 'z' to unpause the audio, press 'x' to pause the audio\", 32, 92);\n\t\n\tofNoFill();\n\n\t\/\/ draw voices\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(32, 150, 0);\n\t\n\tfor(vector<float>::size_type i = 0; i != voices.size(); i++)\n\t{\n\t\tvector<float> voice = *voices[i];\n\t\t\n\t\tofSetColor(225);\n\t\tofDrawBitmapString(\"Voice \" + ofToString(i+1), 4, 18);\n\t\t\n\t\tofSetLineWidth(1);\n\t\tofRect(0, 0, W, H);\n\t\t\n\t\tofSetColor(245, 58, 135);\n\t\tofBeginShape();\n\t\tfor (unsigned int j = 0; j < voice.size(); j++)\n\t\t{\n\t\t\tfloat x = ofMap(j, 0, voice.size(), 0, W, true);\n\t\t\tofVertex(x, H\/2 - voice[j]*80.0f);\n\t\t}\n\t\tofEndShape(false);\n\t\t\n\t\tofTranslate(0, H, 0);\n\t}\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ draw output\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(32, 450, 0);\n\t\n\tofSetColor(225);\n\tofDrawBitmapString(\"Output\", 4, 18);\n\t\n\tofSetLineWidth(1);\n\tofRect(0, 0, W, 100);\n\t\n\tofSetColor(245, 58, 135);\n\tofSetLineWidth(1);\n\t\n\tofBeginShape();\n\tfor (unsigned int i = 0; i < voice3.size(); i++)\n\t{\n\t\tfloat x = ofMap(i, 0, voice3.size(), 0, W, true);\n\t\tofVertex(x, 50 -(voice1[i]+voice2[i]+voice3[i])*80.0f);\n\t}\n\tofEndShape(false);\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ again\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(32+W\/2+ofGetWidth()\/2, 250, 0);\n\tofRotateY(pan*360);\n\tofRotateX(rotator);\n\t\n\tofSetColor(245, 58, 135);\n\tofSetLineWidth(1);\n\t\n\tofBeginShape();\n\tfor (unsigned int i = 0; i < voice3.size(); i++)\n\t{\n\t\tofVertex(voice1[i]*W, voice2[i]*W, voice3[i]*W);\n\t}\n\tofEndShape(false);\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ draw info\n\t\n\tofSetColor(225);\n\tstring reportString = \"volume: (\"+ofToString(volume, 2)+\") modify with -\/+ keys\\n\";\/\/pan: (\"+ofToString(pan, 2)+\") modify with mouse x\\nsynthesis: \";\n\tif( !bNoise )\n\t{\n\t\treportString += \"sine wave (\" + ofToString(frequency, 2) + \" > \" + ofToString(targetFrequency, 2) + \"hz) modify with mouse y\";\n\t}\n\telse\n\t{\n\t\treportString += \"noise\";\n\t}\n\treportString += \"\\nratios = \" + ofToString(numerator1) + \":\" + ofToString(denominator1) + \", \" + ofToString(numerator2) + \":\" + ofToString(denominator2);\n\t\n\treportString += \"\\nchange ratios: 'q\/a':'w\/s', 'e\/d':'r\/f'\";\n\treportString += \"\\nchange waveforms: 'y\/h\/n'\";\n\treportString += \"\\nfreeze waveforms: 'u\/j\/m'\";\n\t\n\tofDrawBitmapString(reportString, 32, 579);\n\t\n\t\/\/ fft\n\t\n\tofSetColor(255);\n\tofPushMatrix();\n\tofTranslate(ofGetWidth() - (256+16), ofGetHeight() - 116);\n\t\n\tsoundMutex.lock();\n\tdrawBins = middleBins;\n\tsoundMutex.unlock();\n\t\n\tofDrawBitmapString(\"Frequency Domain\", 0, 0);\n\tplot(drawBins, -plotHeight, plotHeight \/ 2);\n\tofPopMatrix();\n\t\/\/string msg = ofToString((int) ofGetFrameRate()) + \" fps\";\n\t\/\/ofDrawBitmapString(msg, ofGetWidth() - 80, ofGetHeight() - 20);\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::plot(vector<float>& buffer, float scale, float offset)\n{\n\tofNoFill();\n\tint n = buffer.size()\/2;\n\tofRect(0, 0, n, plotHeight);\n\tglPushMatrix();\n\tglTranslatef(0, plotHeight \/ 2 + offset, 0);\n\tofBeginShape();\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tofVertex(i, sqrt(buffer[i]) * scale);\n\t}\n\tofEndShape();\n\tglPopMatrix();\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::keyPressed (int key)\n{\n\tif (key == '-' || key == '_' )\n\t{\n\t\tvolume -= 0.05;\n\t\tvolume = MAX(volume, 0);\n\t}\n\telse if (key == '+' || key == '=' )\n\t{\n\t\tvolume += 0.05;\n\t\tvolume = MIN(volume, 1);\n\t}\n\t\n\tif( key == 'z' )\n\t{\n\t\tsoundStream.start();\n\t}\n\t\n\tif( key == 'x' )\n\t{\n\t\tsoundStream.stop();\n\t}\n\t\n\tif( key == 'a' )\n\t{\n\t\tnumerator1--;\n\t\tif( numerator1 < 1 ) numerator1 = 1;\n\t}\n\t\n\tif( key == 'q' )\n\t{\n\t\tnumerator1++;\n\t}\n\t\n\tif( key == 's' )\n\t{\n\t\tdenominator1--;\n\t\tif( denominator1 < 1 ) denominator1 = 1;\n\t}\n\t\n\tif( key == 'w' )\n\t{\n\t\tdenominator1++;\n\t}\n\t\n\tif( key == 'd' )\n\t{\n\t\tnumerator2--;\n\t\tif( numerator2 < 1 ) numerator2 = 1;\n\t}\n\t\n\tif( key == 'e' )\n\t{\n\t\tnumerator2++;\n\t}\n\t\n\tif( key == 'f' )\n\t{\n\t\tdenominator2--;\n\t\tif( denominator2 < 1 ) denominator2 = 1;\n\t}\n\t\n\tif( key == 'r' )\n\t{\n\t\tdenominator2++;\n\t}\n\t\n\tint N_SHAPES = 3;\n\t\n\tif( key == 'y' )\n\t{\n\t\tshape1 = (shape1 + 1) % N_SHAPES;\n\t}\n\tif( key == 'h' )\n\t{\n\t\tshape2 = (shape2 + 1) % N_SHAPES;\n\t}\n\tif( key == 'n' )\n\t{\n\t\tshape3 = (shape3 + 1) % N_SHAPES;\n\t}\n\t\n\tif( key == 'u' )\n\t{\n\t\tfreeze1 = freeze1 ? 0 : 1;\n\t}\n\tif( key == 'j' )\n\t{\n\t\tfreeze2 = freeze2 ? 0 : 1;\n\t}\n\tif( key == 'm' )\n\t{\n\t\tfreeze3 = freeze3 ? 0 : 1;\n\t}\n\t\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::keyReleased (int key)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseMoved(int x, int y )\n{\n\tint width = ofGetWidth();\n\tpan = (float)x \/ (float)width;\n\tfloat height = (float)ofGetHeight();\n\ttargetFrequency = 27.f * (height-y);\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseDragged(int x, int y, int button)\n{\n\tint width = ofGetWidth();\n\tpan = (float)x \/ (float)width;\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mousePressed(int x, int y, int button)\n{\n\t\/\/bNoise = true;\n}\n\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseReleased(int x, int y, int button)\n{\n\t\/\/bNoise = false;\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::windowResized(int w, int h)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::audioOut(float * output, int bufferSize, int nChannels)\n{\n\twhile (phase1 > TWO_PI)\n\t{\n\t\tphase1 -= TWO_PI;\n\t}\n\twhile (phase2 > TWO_PI)\n\t{\n\t\tphase2 -= TWO_PI;\n\t}\n\twhile (phase3 > TWO_PI)\n\t{\n\t\tphase3 -= TWO_PI;\n\t}\n\t\n\tif ( bNoise == true)\n\t{\n\t\t\/\/ ---------------------- noise --------------\n\t\tfor (int i = 0; i < bufferSize; i++)\n\t\t{\n\t\t\tvoice1[i] = ofRandom(0, 1) * volume;\n\t\t\tvoice2[i] = ofRandom(0, 1) * volume;\n\t\t\tvoice3[i] = ofRandom(0, 1) * volume;\n\t\t\t\n\t\t\toutput[i*nChannels] = output[i*nChannels + 1] = voice1[i] + voice2[i] + voice3[i];\n\t\t}\n\t}\n\telse\n\t{\n\t\tfrequency = 0.98f * frequency + 0.02f * targetFrequency;\n\t\tphaseAdder = (frequency \/ (float) sampleRate) * TWO_PI;\n\t\t\n\t\tfor (int i = 0; i < bufferSize; i++)\n\t\t{\n\t\t\tphase1 += freeze1 ? 0 : phaseAdder;\n\t\t\tphase2 += freeze2 ? 0 : phaseAdder*float(numerator1)\/float(denominator1);\n\t\t\tphase3 += freeze3 ? 0 : (phaseAdder*float(numerator1)\/float(denominator1))*float(numerator2)\/float(denominator2);\n\t\t\t\n\t\t\t\/\/ sine wave\n\t\t\tfloat sample1 = sin(phase1);\n\t\t\tfloat sample2 = sin(phase2);\n\t\t\tfloat sample3 = sin(phase3);\n\t\t\t\n\t\t\t\/\/ square wave\n\t\t\tif( shape1 == 1 ) sample1 = sample1 > 0 ? 1 : -1;\n\t\t\tif( shape2 == 1 ) sample2 = sample2 > 0 ? 1 : -1;\n\t\t\tif( shape3 == 1 ) sample3 = sample3 > 0 ? 1 : -1;\n\t\t\t\n\t\t\t\/\/ sawtooth wave\n\t\t\tif( shape1 == 2 ) sample1 = (fmodf(phase1,TWO_PI) - PI)\/2.f;\n\t\t\tif( shape2 == 2 ) sample2 = (fmodf(phase2,TWO_PI) - PI)\/2.f;\n\t\t\tif( shape3 == 2 ) sample3 = (fmodf(phase3,TWO_PI) - PI)\/2.f;\n\t\t\t\n\t\t\t\/\/ scale by volume\n\t\t\tvoice1[i] = sample1 * volume;\n\t\t\tvoice2[i] = sample2 * volume;\n\t\t\tvoice3[i] = sample3 * volume;\n\t\t\t\n\t\t\toutput[i*nChannels] = output[i*nChannels + 1] = voice1[i] + voice2[i] + voice3[i];\n\t\t}\n\t}\n\t\n\t\/\/ fft\n\n\tfft->setSignal(output);\n\t\n\tfloat* curFft = fft->getAmplitude();\n\tmemcpy(&audioBins[0], curFft, sizeof(float) * fft->getBinSize());\n\t\t\n\tsoundMutex.lock();\n\tmiddleBins = audioBins;\n\tsoundMutex.unlock();\t\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::gotMessage(ofMessage msg)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::dragEvent(ofDragInfo dragInfo)\n{\n}\n<commit_msg>new layout<commit_after>#include \"hsApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid hsApp::setup()\n{\n\t\/\/ofBackground(34, 34, 34);\n\tofSetVerticalSync(true);\n\t\n\twidthi = 512;\n\twidthf = widthi;\n\t\n\tmesh.setMode(OF_PRIMITIVE_POINTS);\n\t\n\tfor(int y = 0; y < widthi; y++ )\n\t{\n\t\tfor(int x = 0; x < widthi; x++ )\n\t\t{\n\t\t\tofFloatColor color(x\/widthf,y\/widthf,1.f,0.5f);\n\t\t\tmesh.addColor(color);\n\t\t\tofVec3f pos(x-widthf\/2.f, y-widthf\/2.f, 0);\n\t\t\tmesh.addVertex(pos);\n\t\t}\n\t}\n\t\n\tofEnableDepthTest();\n\tglEnable(GL_POINT_SMOOTH); \/\/ use circular points instead of square points\n\tglPointSize(2); \/\/ make the points bigger\n\t\n\t\/\/ 2 output channels,\n\t\/\/ 0 input channels\n\t\/\/ 44100 samples per second\n\t\/\/ 512 samples per buffer\n\t\/\/ 4 num buffers (latency)\n\t\n\tint bufferSize\t\t= 512;\n\tsampleRate \t\t\t= 44100;\n\t\n\tphase1\t\t\t\t= 0;\n\tphase2\t\t\t\t= 0;\n\tphase3\t\t\t\t= 0;\n\t\n\tshape1\t\t\t\t= 0;\n\tshape2\t\t\t\t= 0;\n\tshape3\t\t\t\t= 0;\n\t\n\tfreeze1\t\t\t\t= 0;\n\tfreeze2\t\t\t\t= 0;\n\tfreeze3\t\t\t\t= 0;\n\t\n\tphaseAdder \t\t\t= 0.0f;\n\tvolume\t\t\t\t= 0.2f;\n\tbNoise \t\t\t\t= false;\n\t\n\tvoice1.assign(bufferSize, 0.0);\n\tvoice2.assign(bufferSize, 0.0);\n\tvoice3.assign(bufferSize, 0.0);\n\t\n\tvoices.push_back(&voice1);\n\tvoices.push_back(&voice2);\n\tvoices.push_back(&voice3);\n\t\t\n\tfrequency = targetFrequency = 110;\n\tnumerator1 = numerator2 = 2;\n\tdenominator1 = denominator2 = 3;\n\trotator = 0;\n\t\n\t\/\/soundStream.listDevices();\n\t\n\t\/\/if you want to set the device id to be different than the default\n\t\/\/soundStream.setDeviceID(1); \t\/\/note some devices are input only and some are output only\n\t\n\tsoundStream.setup(this, 2, 0, sampleRate, bufferSize, 4);\n\t\n\t\/\/\n\t\n\tplotHeight = 100;\n\t\n\t\/\/fft = ofxFft::create(bufferSize, OF_FFT_WINDOW_HAMMING, OF_FFT_FFTW);\n\tfft = ofxFft::create(bufferSize, OF_FFT_WINDOW_HAMMING);\n\t\n\tdrawBins.resize(fft->getBinSize());\n\tmiddleBins.resize(fft->getBinSize());\n\taudioBins.resize(fft->getBinSize());\n\t\n\tofSetFrameRate(30);\n}\n\n\n\/\/--------------------------------------------------------------\nvoid hsApp::update()\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::draw()\n{\n\tofBackground(34, 34, 34);\n\t\n\tint W = 256;\n\tint H = 64;\n\t\n\tvector<ofVec3f>& verts = mesh.getVertices();\n\tvector<ofFloatColor>& color = mesh.getColors();\n\t\n\tfor(unsigned int i = 0; i < verts.size(); i++)\n\t{\n\t\tint j = ofMap(i, 0, verts.size(), 0, widthf);\n\t\t\n\t\tverts[i].x = voice1[j] * W;\n\t\tverts[i].y = voice2[j] * W;\n\t\tverts[i].z = voice3[j] * W;\n\t\t\n\t\tcolor[i].r = 1.f - voice1[j];\n\t\tcolor[i].g = 1.f - voice2[j];\n\t\tcolor[i].b = 1.f - voice3[j];\n\t}\n\t\n\tofPushMatrix();\n\tofTranslate(512, 528, 0);\n\tofRotateY(pan*360);\n\tofRotateX(rotator);\n\trotator += 0.1f;\n\tmesh.draw();\n\tofPopMatrix();\n\t\n\t\/\/\n\t\n\tofSetColor(225);\n\tofDrawBitmapString(\"HyperScope\", 64, 64);\n\/\/\tofDrawBitmapString(\"press 'z' to unpause the audio, press 'x' to pause the audio\", 32, 92);\n\t\n\tofNoFill();\n\n\t\/\/ draw voices\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(64, 128, 0);\n\t\n\tfor(vector<float>::size_type i = 0; i != voices.size(); i++)\n\t{\n\t\tvector<float> voice = *voices[i];\n\t\t\n\t\tofSetColor(225);\n\t\tofDrawBitmapString(\"Voice \" + ofToString(i+1), 4, 18);\n\t\t\n\t\tofSetLineWidth(1);\n\t\t\/\/ofRect(0, 0, W, H);\n\t\t\n\t\tofSetColor(245, 58, 135);\n\t\tofBeginShape();\n\t\tfor (unsigned int j = 0; j < voice.size(); j++)\n\t\t{\n\t\t\tfloat x = ofMap(j, 0, voice.size(), 0, W, true);\n\t\t\tofVertex(x, H\/2 - voice[j]*80.0f);\n\t\t}\n\t\tofEndShape(false);\n\t\t\n\t\tofTranslate(0, H, 0);\n\t}\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ draw output\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(64, 368, 0);\n\t\n\tofSetColor(225);\n\tofDrawBitmapString(\"Output\", 4, 18);\n\t\n\tofSetLineWidth(1);\n\t\/\/ofRect(0, 0, W, 100);\n\t\n\tofSetColor(245, 58, 135);\n\tofSetLineWidth(1);\n\t\n\tofBeginShape();\n\tfor (unsigned int i = 0; i < voice3.size(); i++)\n\t{\n\t\tfloat x = ofMap(i, 0, voice3.size(), 0, W, true);\n\t\tofVertex(x, H\/2 -(voice1[i]+voice2[i]+voice3[i])*80.0f);\n\t}\n\tofEndShape(false);\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ again\n\t\n\tofPushStyle();\n\tofPushMatrix();\n\tofTranslate(512, 256, 0);\n\tofRotateY(pan*360);\n\tofRotateX(rotator);\n\t\n\tofSetColor(245, 58, 135);\n\tofSetLineWidth(1);\n\t\n\tofBeginShape();\n\tfor (unsigned int i = 0; i < voice3.size(); i++)\n\t{\n\t\tofVertex(voice1[i]*W, voice2[i]*W, voice3[i]*W);\n\t}\n\tofEndShape(false);\n\t\n\tofPopMatrix();\n\tofPopStyle();\n\t\n\t\/\/ draw info\n\t\n\tofSetColor(225);\n\tstring reportString = \"volume: (\"+ofToString(volume, 2)+\") modify with -\/+ keys\\n\";\/\/pan: (\"+ofToString(pan, 2)+\") modify with mouse x\\nsynthesis: \";\n\tif( !bNoise )\n\t{\n\t\treportString += \"sine wave (\" + ofToString(frequency, 2) + \" > \" + ofToString(targetFrequency, 2) + \"hz) modify with mouse y\";\n\t}\n\telse\n\t{\n\t\treportString += \"noise\";\n\t}\n\treportString += \"\\nratios = \" + ofToString(numerator1) + \":\" + ofToString(denominator1) + \", \" + ofToString(numerator2) + \":\" + ofToString(denominator2);\n\t\n\treportString += \"\\nchange ratios: 'q\/a':'w\/s', 'e\/d':'r\/f'\";\n\treportString += \"\\nchange waveforms: 'y\/h\/n'\";\n\treportString += \"\\nfreeze waveforms: 'u\/j\/m'\";\n\t\n\tofDrawBitmapString(reportString, 32, 579);\n\t\n\t\/\/ fft\n\t\n\tofSetColor(255);\n\tofPushMatrix();\n\tofTranslate(704, 128);\n\t\n\tsoundMutex.lock();\n\tdrawBins = middleBins;\n\tsoundMutex.unlock();\n\t\n\tofDrawBitmapString(\"Frequency Domain\", 4, 18);\n\tplot(drawBins, -plotHeight, plotHeight \/ 2);\n\tofPopMatrix();\n\t\/\/string msg = ofToString((int) ofGetFrameRate()) + \" fps\";\n\t\/\/ofDrawBitmapString(msg, ofGetWidth() - 80, ofGetHeight() - 20);\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::plot(vector<float>& buffer, float scale, float offset)\n{\n\tofNoFill();\n\tint n = buffer.size()\/2;\n\t\/\/ofRect(0, 0, n, plotHeight);\n\tglPushMatrix();\n\tglTranslatef(0, plotHeight \/ 2 + offset, 0);\n\tofBeginShape();\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tofVertex(i, sqrt(buffer[i]) * scale);\n\t}\n\tofEndShape();\n\tglPopMatrix();\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::keyPressed (int key)\n{\n\tif (key == '-' || key == '_' )\n\t{\n\t\tvolume -= 0.05;\n\t\tvolume = MAX(volume, 0);\n\t}\n\telse if (key == '+' || key == '=' )\n\t{\n\t\tvolume += 0.05;\n\t\tvolume = MIN(volume, 1);\n\t}\n\t\n\tif( key == 'z' )\n\t{\n\t\tsoundStream.start();\n\t}\n\t\n\tif( key == 'x' )\n\t{\n\t\tsoundStream.stop();\n\t}\n\t\n\tif( key == 'a' )\n\t{\n\t\tnumerator1--;\n\t\tif( numerator1 < 1 ) numerator1 = 1;\n\t}\n\t\n\tif( key == 'q' )\n\t{\n\t\tnumerator1++;\n\t}\n\t\n\tif( key == 's' )\n\t{\n\t\tdenominator1--;\n\t\tif( denominator1 < 1 ) denominator1 = 1;\n\t}\n\t\n\tif( key == 'w' )\n\t{\n\t\tdenominator1++;\n\t}\n\t\n\tif( key == 'd' )\n\t{\n\t\tnumerator2--;\n\t\tif( numerator2 < 1 ) numerator2 = 1;\n\t}\n\t\n\tif( key == 'e' )\n\t{\n\t\tnumerator2++;\n\t}\n\t\n\tif( key == 'f' )\n\t{\n\t\tdenominator2--;\n\t\tif( denominator2 < 1 ) denominator2 = 1;\n\t}\n\t\n\tif( key == 'r' )\n\t{\n\t\tdenominator2++;\n\t}\n\t\n\tint N_SHAPES = 3;\n\t\n\tif( key == 'y' )\n\t{\n\t\tshape1 = (shape1 + 1) % N_SHAPES;\n\t}\n\tif( key == 'h' )\n\t{\n\t\tshape2 = (shape2 + 1) % N_SHAPES;\n\t}\n\tif( key == 'n' )\n\t{\n\t\tshape3 = (shape3 + 1) % N_SHAPES;\n\t}\n\t\n\tif( key == 'u' )\n\t{\n\t\tfreeze1 = freeze1 ? 0 : 1;\n\t}\n\tif( key == 'j' )\n\t{\n\t\tfreeze2 = freeze2 ? 0 : 1;\n\t}\n\tif( key == 'm' )\n\t{\n\t\tfreeze3 = freeze3 ? 0 : 1;\n\t}\n\t\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::keyReleased (int key)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseMoved(int x, int y )\n{\n\tint width = ofGetWidth();\n\tpan = (float)x \/ (float)width;\n\tfloat height = (float)ofGetHeight();\n\ttargetFrequency = 27.f * (height-y);\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseDragged(int x, int y, int button)\n{\n\tint width = ofGetWidth();\n\tpan = (float)x \/ (float)width;\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mousePressed(int x, int y, int button)\n{\n\t\/\/bNoise = true;\n}\n\n\n\/\/--------------------------------------------------------------\nvoid hsApp::mouseReleased(int x, int y, int button)\n{\n\t\/\/bNoise = false;\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::windowResized(int w, int h)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::audioOut(float * output, int bufferSize, int nChannels)\n{\n\twhile (phase1 > TWO_PI)\n\t{\n\t\tphase1 -= TWO_PI;\n\t}\n\twhile (phase2 > TWO_PI)\n\t{\n\t\tphase2 -= TWO_PI;\n\t}\n\twhile (phase3 > TWO_PI)\n\t{\n\t\tphase3 -= TWO_PI;\n\t}\n\t\n\tif ( bNoise == true)\n\t{\n\t\t\/\/ ---------------------- noise --------------\n\t\tfor (int i = 0; i < bufferSize; i++)\n\t\t{\n\t\t\tvoice1[i] = ofRandom(0, 1) * volume;\n\t\t\tvoice2[i] = ofRandom(0, 1) * volume;\n\t\t\tvoice3[i] = ofRandom(0, 1) * volume;\n\t\t\t\n\t\t\toutput[i*nChannels] = output[i*nChannels + 1] = voice1[i] + voice2[i] + voice3[i];\n\t\t}\n\t}\n\telse\n\t{\n\t\tfrequency = 0.98f * frequency + 0.02f * targetFrequency;\n\t\tphaseAdder = (frequency \/ (float) sampleRate) * TWO_PI;\n\t\t\n\t\tfor (int i = 0; i < bufferSize; i++)\n\t\t{\n\t\t\tphase1 += freeze1 ? 0 : phaseAdder;\n\t\t\tphase2 += freeze2 ? 0 : phaseAdder*float(numerator1)\/float(denominator1);\n\t\t\tphase3 += freeze3 ? 0 : (phaseAdder*float(numerator1)\/float(denominator1))*float(numerator2)\/float(denominator2);\n\t\t\t\n\t\t\t\/\/ sine wave\n\t\t\tfloat sample1 = sin(phase1);\n\t\t\tfloat sample2 = sin(phase2);\n\t\t\tfloat sample3 = sin(phase3);\n\t\t\t\n\t\t\t\/\/ square wave\n\t\t\tif( shape1 == 1 ) sample1 = sample1 > 0 ? 1 : -1;\n\t\t\tif( shape2 == 1 ) sample2 = sample2 > 0 ? 1 : -1;\n\t\t\tif( shape3 == 1 ) sample3 = sample3 > 0 ? 1 : -1;\n\t\t\t\n\t\t\t\/\/ sawtooth wave\n\t\t\tif( shape1 == 2 ) sample1 = (fmodf(phase1,TWO_PI) - PI)\/2.f;\n\t\t\tif( shape2 == 2 ) sample2 = (fmodf(phase2,TWO_PI) - PI)\/2.f;\n\t\t\tif( shape3 == 2 ) sample3 = (fmodf(phase3,TWO_PI) - PI)\/2.f;\n\t\t\t\n\t\t\t\/\/ scale by volume\n\t\t\tvoice1[i] = sample1 * volume;\n\t\t\tvoice2[i] = sample2 * volume;\n\t\t\tvoice3[i] = sample3 * volume;\n\t\t\t\n\t\t\toutput[i*nChannels] = output[i*nChannels + 1] = voice1[i] + voice2[i] + voice3[i];\n\t\t}\n\t}\n\t\n\t\/\/ fft\n\n\tfft->setSignal(output);\n\t\n\tfloat* curFft = fft->getAmplitude();\n\tmemcpy(&audioBins[0], curFft, sizeof(float) * fft->getBinSize());\n\t\t\n\tsoundMutex.lock();\n\tmiddleBins = audioBins;\n\tsoundMutex.unlock();\t\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::gotMessage(ofMessage msg)\n{\n}\n\n\/\/--------------------------------------------------------------\nvoid hsApp::dragEvent(ofDragInfo dragInfo)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\nCopyright (c) 2014, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n#include <cstring>\n#include <cstdlib>\n\n#include \"os\/os.h\"\n#include \"utils.h\"\n#include \"httpd.h\"\n\n#define KTKEY 0\n#define KTSKEY 1\n\nlibhttppp::HTTPDCmd::HTTPDCmd() {\n _Key = NULL;\n _SKey = '\\0';\n _Value = NULL;\n _Help = NULL;\n _Found = false;\n _Required = false;\n _nextHTTPDCmd = NULL;\n}\n\nconst char *libhttppp::HTTPDCmd::getKey() {\n return _Key;\n}\n\nconst char libhttppp::HTTPDCmd::getShortkey() {\n return _SKey;\n}\n\nconst char *libhttppp::HTTPDCmd::getValue() {\n return _Value;\n}\n\nsize_t libhttppp::HTTPDCmd::getValueSize_t() {\n return atoi(_Value);\n}\n\nint libhttppp::HTTPDCmd::getValueInt() {\n return atoi(_Value);\n}\n\nconst char *libhttppp::HTTPDCmd::getHelp() {\n return _Help;\n}\n\nbool libhttppp::HTTPDCmd::getFound() {\n return _Found;\n}\n\nbool libhttppp::HTTPDCmd::getRequired() {\n return _Required;\n}\n\nlibhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {\n return _nextHTTPDCmd;\n}\n\nlibhttppp::HTTPDCmd::~HTTPDCmd() {\n delete[] _Key;\n delete[] _Value;\n delete[] _Help;\n delete _nextHTTPDCmd;\n}\n\nlibhttppp::HTTPDCmdController::HTTPDCmdController() {\n _firstHTTPDCmd = NULL;\n _lastHTTPDCmd = NULL;\n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {\n if (!key || !skey || !help) {\n _httpexception[HTTPException::Critical] << \"cmd parser key,skey or help not set!\";\n throw _httpexception;\n }\n \/*if key exist overwriting options*\/\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n \/*set new shortkey*\/\n curhttpdcmd->_SKey = skey;\n \/*set reqirement flag*\/\n curhttpdcmd->_Required = required;\n \/*set new value*\/\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[getlen(defaultvalue)+1];\n scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value);\n curhttpdcmd->_Value[getlen(defaultvalue)] = '\\0';\n \/*set new help*\/\n delete[] curhttpdcmd->_Help;\n curhttpdcmd->_Help = new char[getlen(help) + 1];\n scopy(help, help + getlen(help), curhttpdcmd->_Help);\n curhttpdcmd->_Help[getlen(help)] = '\\0';\n return;\n }\n }\n \/*create new key value store*\/\n if (!_firstHTTPDCmd) {\n _firstHTTPDCmd = new HTTPDCmd;\n _lastHTTPDCmd = _firstHTTPDCmd;\n }\n else {\n _lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;\n _lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;\n }\n \/*set new key*\/\n _lastHTTPDCmd->_Key = new char[getlen(key) + 1];\n scopy(key,key+getlen(key),_lastHTTPDCmd->_Key);\n _lastHTTPDCmd->_Key[getlen(key)] = '\\0';\n \/*set new shortkey*\/\n _lastHTTPDCmd->_SKey = skey;\n \/*set reqirement flag*\/\n _lastHTTPDCmd->_Required = required;\n \/*set new value*\/\n if (defaultvalue) {\n _lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1];\n scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value);\n _lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\\0';\n }\n \/*set new help*\/\n _lastHTTPDCmd->_Help = new char[getlen(help) + 1];\n scopy(help, help + getlen(help), _lastHTTPDCmd->_Help);\n _lastHTTPDCmd->_Help[getlen(help)] = '\\0';\n \n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {\n char buf[255];\n itoa(defaultvalue,buf);\n registerCmd(key,skey,required,buf,help);\n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {\n char buf[255];\n itoa(defaultvalue,buf);\n registerCmd(key, skey, required, buf, help);\n}\n\nvoid libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){\n for (int args = 1; args < argc; args++) {\n int keytype = -1;\n if (argv[args][0]=='-' && argv[args][1] == '-') {\n keytype = KTKEY;\n }else if (argv[args][0] == '-'){\n keytype = KTSKEY;\n }else {\n break;\n }\n \n size_t kendpos = getlen(argv[args]);\n for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) {\t\n switch (argv[args][cmdpos]) {\n case '=': {\n kendpos = cmdpos;\n };\n }\n }\n \n char *key = NULL;\n char skey = '0';\n if (keytype == KTKEY) {\n key = new char[kendpos-1];\n scopy(argv[args] +2, argv[args] +kendpos, key);\n key[kendpos - 2] = '\\0';\n } else if (keytype == KTSKEY){\n skey = argv[args][1];\n }\n \n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (keytype == KTKEY) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n curhttpdcmd->_Found = true;\n int valuesize = (getlen(argv[args]) - (kendpos+1));\n if (valuesize > 0) {\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[valuesize+1];\n scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value);\n curhttpdcmd->_Value[valuesize] = '\\0';\n }\n }\n } else if (keytype == KTSKEY) {\n if (curhttpdcmd->getShortkey()== skey) {\n curhttpdcmd->_Found = true;\n if (args<argc) {\n int valuesize = getlen(argv[++args]);\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[valuesize + 1];\n scopy(argv[args], argv[args] + getlen(argv[args]), curhttpdcmd->_Value);\n curhttpdcmd->_Value[valuesize] = '\\0';\n }\n }\n }\n }\n \n delete[] key;\n }\n}\n\nbool libhttppp::HTTPDCmdController::checkRequired() {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {\n return false;\n }\n }\n return true;\n}\n\nvoid libhttppp::HTTPDCmdController::printHelp() {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n Console con;\n con << \"--\" << curhttpdcmd->getKey() \n << \" -\" << curhttpdcmd->getShortkey()\n << \" \" << curhttpdcmd->getHelp() << Console::endl;\n }\n}\n\nlibhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n return curhttpdcmd;\n }\n }\n return NULL;\n}\n\nlibhttppp::HTTPDCmdController::~HTTPDCmdController() {\n delete _firstHTTPDCmd;\n _lastHTTPDCmd = NULL;\n}\n\n\nlibhttppp::HttpD::HttpD(int argc, char** argv){\n CmdController= new HTTPDCmdController;\n \/*Register Parameters*\/\n CmdController->registerCmd(\"help\", 'h', false, (const char*) NULL, \"Helpmenu\");\n CmdController->registerCmd(\"httpaddr\",'a', true,(const char*) NULL,\"Address to listen\");\n CmdController->registerCmd(\"httpport\", 'p', false, 8080, \"Port to listen\");\n CmdController->registerCmd(\"maxconnections\", 'm',false, MAXDEFAULTCONN, \"Max connections that can connect\");\n CmdController->registerCmd(\"httpscert\", 'c',false,(const char*) NULL, \"HTTPS Certfile\");\n CmdController->registerCmd(\"httpskey\", 'k',false, (const char*) NULL, \"HTTPS Keyfile\");\n \/*Parse Parameters*\/\n CmdController->parseCmd(argc,argv);\n\n if (CmdController->getHTTPDCmdbyKey(\"help\") && CmdController->getHTTPDCmdbyKey(\"help\")->getFound()) {\n CmdController->printHelp();\n throw _httpexception[HTTPException::Note] << \"Help Menu printed\";\n }\n\n if (!CmdController->checkRequired()) {\n CmdController->printHelp();\n _httpexception[HTTPException::Critical] << \"cmd parser not enough arguments given\";\n throw _httpexception;\n }\n \n \/*get port from console paramter*\/\n int port = 0;\n bool portset=false;\n if(CmdController->getHTTPDCmdbyKey(\"httpport\")){\n port = CmdController->getHTTPDCmdbyKey(\"httpport\")->getValueInt();\n portset = CmdController->getHTTPDCmdbyKey(\"httpport\")->getFound();\n }\n \n \/*get httpaddress from console paramter*\/\n const char *httpaddr = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpaddr\"))\n httpaddr = CmdController->getHTTPDCmdbyKey(\"httpaddr\")->getValue();\n \n \/*get max connections from console paramter*\/\n int maxconnections = 0;\n if (CmdController->getHTTPDCmdbyKey(\"maxconnections\"))\n maxconnections = CmdController->getHTTPDCmdbyKey(\"maxconnections\")->getValueInt();\n \n \/*get httpaddress from console paramter*\/\n const char *sslcertpath = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpscert\"))\n sslcertpath = CmdController->getHTTPDCmdbyKey(\"httpscert\")->getValue();\n \n \/*get httpaddress from console paramter*\/\n const char *sslkeypath = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpskey\"))\n sslkeypath = CmdController->getHTTPDCmdbyKey(\"httpskey\")->getValue();\n \n try {\n #ifndef Windows\n if (portset == true)\n _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);\n else\n _ServerSocket = new ServerSocket(httpaddr, maxconnections);\n #else\n _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);\n #endif\n \n \n if (sslcertpath && sslkeypath) {\n _ServerSocket->createContext();\n _ServerSocket->loadCertfile(sslcertpath);\n _ServerSocket->loadKeyfile(sslkeypath);\n }\n }catch (HTTPException &e) {\n throw e;\n }\n}\n\nlibhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){\n return _ServerSocket;\n}\n\nlibhttppp::HttpD::~HttpD(){\n delete _ServerSocket;\n delete CmdController;\n}\n<commit_msg>fixed len bug<commit_after>\/*******************************************************************************\nCopyright (c) 2014, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n#include <cstring>\n#include <cstdlib>\n\n#include \"os\/os.h\"\n#include \"utils.h\"\n#include \"httpd.h\"\n\n#define KTKEY 0\n#define KTSKEY 1\n\nlibhttppp::HTTPDCmd::HTTPDCmd() {\n _Key = NULL;\n _SKey = '\\0';\n _Value = NULL;\n _Help = NULL;\n _Found = false;\n _Required = false;\n _nextHTTPDCmd = NULL;\n}\n\nconst char *libhttppp::HTTPDCmd::getKey() {\n return _Key;\n}\n\nconst char libhttppp::HTTPDCmd::getShortkey() {\n return _SKey;\n}\n\nconst char *libhttppp::HTTPDCmd::getValue() {\n return _Value;\n}\n\nsize_t libhttppp::HTTPDCmd::getValueSize_t() {\n return atoi(_Value);\n}\n\nint libhttppp::HTTPDCmd::getValueInt() {\n return atoi(_Value);\n}\n\nconst char *libhttppp::HTTPDCmd::getHelp() {\n return _Help;\n}\n\nbool libhttppp::HTTPDCmd::getFound() {\n return _Found;\n}\n\nbool libhttppp::HTTPDCmd::getRequired() {\n return _Required;\n}\n\nlibhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {\n return _nextHTTPDCmd;\n}\n\nlibhttppp::HTTPDCmd::~HTTPDCmd() {\n delete[] _Key;\n delete[] _Value;\n delete[] _Help;\n delete _nextHTTPDCmd;\n}\n\nlibhttppp::HTTPDCmdController::HTTPDCmdController() {\n _firstHTTPDCmd = NULL;\n _lastHTTPDCmd = NULL;\n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {\n if (!key || !skey || !help) {\n _httpexception[HTTPException::Critical] << \"cmd parser key,skey or help not set!\";\n throw _httpexception;\n }\n \/*if key exist overwriting options*\/\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n \/*set new shortkey*\/\n curhttpdcmd->_SKey = skey;\n \/*set reqirement flag*\/\n curhttpdcmd->_Required = required;\n \/*set new value*\/\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[getlen(defaultvalue)+1];\n scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value);\n curhttpdcmd->_Value[getlen(defaultvalue)] = '\\0';\n \/*set new help*\/\n delete[] curhttpdcmd->_Help;\n curhttpdcmd->_Help = new char[getlen(help) + 1];\n scopy(help, help + getlen(help), curhttpdcmd->_Help);\n curhttpdcmd->_Help[getlen(help)] = '\\0';\n return;\n }\n }\n \/*create new key value store*\/\n if (!_firstHTTPDCmd) {\n _firstHTTPDCmd = new HTTPDCmd;\n _lastHTTPDCmd = _firstHTTPDCmd;\n }\n else {\n _lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;\n _lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;\n }\n \/*set new key*\/\n _lastHTTPDCmd->_Key = new char[getlen(key) + 1];\n scopy(key,key+getlen(key),_lastHTTPDCmd->_Key);\n _lastHTTPDCmd->_Key[getlen(key)] = '\\0';\n \/*set new shortkey*\/\n _lastHTTPDCmd->_SKey = skey;\n \/*set reqirement flag*\/\n _lastHTTPDCmd->_Required = required;\n \/*set new value*\/\n if (defaultvalue) {\n _lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1];\n scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value);\n _lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\\0';\n }\n \/*set new help*\/\n _lastHTTPDCmd->_Help = new char[getlen(help) + 1];\n scopy(help, help + getlen(help), _lastHTTPDCmd->_Help);\n _lastHTTPDCmd->_Help[getlen(help)] = '\\0';\n \n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {\n char buf[255];\n itoa(defaultvalue,buf);\n registerCmd(key,skey,required,buf,help);\n}\n\nvoid libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {\n char buf[255];\n itoa(defaultvalue,buf);\n registerCmd(key, skey, required, buf, help);\n}\n\nvoid libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){\n for (int args = 1; args < argc; args++) {\n int keytype = -1;\n if (argv[args][0]=='-' && argv[args][1] == '-') {\n keytype = KTKEY;\n }else if (argv[args][0] == '-'){\n keytype = KTSKEY;\n }else {\n break;\n }\n \n size_t kendpos = getlen(argv[args]);\n for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) {\t\n switch (argv[args][cmdpos]) {\n case '=': {\n kendpos = cmdpos;\n };\n }\n }\n \n char *key = NULL;\n char skey = '0';\n if (keytype == KTKEY) {\n key = new char[kendpos-1];\n scopy(argv[args] +2, argv[args] +kendpos, key);\n key[kendpos - 2] = '\\0';\n } else if (keytype == KTSKEY){\n skey = argv[args][1];\n }\n \n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (keytype == KTKEY) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n curhttpdcmd->_Found = true;\n int valuesize = (getlen(argv[args]) - (kendpos+1));\n if (valuesize > 0) {\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[valuesize+1];\n scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value);\n curhttpdcmd->_Value[valuesize] = '\\0';\n }\n }\n } else if (keytype == KTSKEY) {\n if (curhttpdcmd->getShortkey()== skey) {\n curhttpdcmd->_Found = true;\n if (++args<argc) {\n int valuesize = getlen(argv[args]);\n delete[] curhttpdcmd->_Value;\n curhttpdcmd->_Value = new char[valuesize + 1];\n scopy(argv[args], argv[args] + getlen(argv[args]), curhttpdcmd->_Value);\n curhttpdcmd->_Value[valuesize] = '\\0';\n }\n }\n }\n }\n \n delete[] key;\n }\n}\n\nbool libhttppp::HTTPDCmdController::checkRequired() {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {\n return false;\n }\n }\n return true;\n}\n\nvoid libhttppp::HTTPDCmdController::printHelp() {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n Console con;\n con << \"--\" << curhttpdcmd->getKey() \n << \" -\" << curhttpdcmd->getShortkey()\n << \" \" << curhttpdcmd->getHelp() << Console::endl;\n }\n}\n\nlibhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {\n for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {\n if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {\n return curhttpdcmd;\n }\n }\n return NULL;\n}\n\nlibhttppp::HTTPDCmdController::~HTTPDCmdController() {\n delete _firstHTTPDCmd;\n _lastHTTPDCmd = NULL;\n}\n\n\nlibhttppp::HttpD::HttpD(int argc, char** argv){\n CmdController= new HTTPDCmdController;\n \/*Register Parameters*\/\n CmdController->registerCmd(\"help\", 'h', false, (const char*) NULL, \"Helpmenu\");\n CmdController->registerCmd(\"httpaddr\",'a', true,(const char*) NULL,\"Address to listen\");\n CmdController->registerCmd(\"httpport\", 'p', false, 8080, \"Port to listen\");\n CmdController->registerCmd(\"maxconnections\", 'm',false, MAXDEFAULTCONN, \"Max connections that can connect\");\n CmdController->registerCmd(\"httpscert\", 'c',false,(const char*) NULL, \"HTTPS Certfile\");\n CmdController->registerCmd(\"httpskey\", 'k',false, (const char*) NULL, \"HTTPS Keyfile\");\n \/*Parse Parameters*\/\n CmdController->parseCmd(argc,argv);\n\n if (CmdController->getHTTPDCmdbyKey(\"help\") && CmdController->getHTTPDCmdbyKey(\"help\")->getFound()) {\n CmdController->printHelp();\n throw _httpexception[HTTPException::Note] << \"Help Menu printed\";\n }\n\n if (!CmdController->checkRequired()) {\n CmdController->printHelp();\n _httpexception[HTTPException::Critical] << \"cmd parser not enough arguments given\";\n throw _httpexception;\n }\n \n \/*get port from console paramter*\/\n int port = 0;\n bool portset=false;\n if(CmdController->getHTTPDCmdbyKey(\"httpport\")){\n port = CmdController->getHTTPDCmdbyKey(\"httpport\")->getValueInt();\n portset = CmdController->getHTTPDCmdbyKey(\"httpport\")->getFound();\n }\n \n \/*get httpaddress from console paramter*\/\n const char *httpaddr = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpaddr\"))\n httpaddr = CmdController->getHTTPDCmdbyKey(\"httpaddr\")->getValue();\n \n \/*get max connections from console paramter*\/\n int maxconnections = 0;\n if (CmdController->getHTTPDCmdbyKey(\"maxconnections\"))\n maxconnections = CmdController->getHTTPDCmdbyKey(\"maxconnections\")->getValueInt();\n \n \/*get httpaddress from console paramter*\/\n const char *sslcertpath = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpscert\"))\n sslcertpath = CmdController->getHTTPDCmdbyKey(\"httpscert\")->getValue();\n \n \/*get httpaddress from console paramter*\/\n const char *sslkeypath = NULL;\n if (CmdController->getHTTPDCmdbyKey(\"httpskey\"))\n sslkeypath = CmdController->getHTTPDCmdbyKey(\"httpskey\")->getValue();\n \n try {\n #ifndef Windows\n if (portset == true)\n _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);\n else\n _ServerSocket = new ServerSocket(httpaddr, maxconnections);\n #else\n _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);\n #endif\n \n \n if (sslcertpath && sslkeypath) {\n _ServerSocket->createContext();\n _ServerSocket->loadCertfile(sslcertpath);\n _ServerSocket->loadKeyfile(sslkeypath);\n }\n }catch (HTTPException &e) {\n throw e;\n }\n}\n\nlibhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){\n return _ServerSocket;\n}\n\nlibhttppp::HttpD::~HttpD(){\n delete _ServerSocket;\n delete CmdController;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef V_SMC_SAMPLER_HPP\n#define V_SMC_SAMPLER_HPP\n\n#include <vSMC\/config.hpp>\n\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <mkl_cblas.h>\n#include <boost\/function.hpp>\n#include <vDist\/rng\/gsl.hpp>\n#include <vDist\/tool\/buffer.hpp>\n#include <vSMC\/monitor.hpp>\n#include <vSMC\/particle.hpp>\n#include <vSMC\/path.hpp>\n\nnamespace vSMC {\n\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of initialization functor\n typedef boost::function<std::size_t\n (Particle<T> &, void *)> init_type;\n \/\/\/ The type of move functor\n typedef boost::function<std::size_t\n (std::size_t, Particle<T> &)> move_type;\n \/\/\/ The type of importance sampling integral functor\n typedef boost::function<void\n (std::size_t, Particle<T> &, double *, void *)> integral_type;\n\n \/\/\/ \\brief Sampler does not have a default constructor\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param mcmc The functor used to perform MCMC move\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed for the reampling RNG. See documentation of vDist\n \/\/\/ \\param brng The basic RNG for resampling RNG. See documentation of GSL\n Sampler (\n std::size_t N,\n const init_type &init,\n const move_type &move,\n const move_type &mcmc = NULL,\n ResampleScheme scheme = RESIDUAL,\n double threshold = 0.5,\n const int seed = V_DIST_SEED,\n const gsl_rng_type *brng = V_DIST_GSL_BRNG) :\n initialized_(false), init_(init), move_(move), mcmc_(mcmc),\n rng_(seed, brng), scheme_(scheme), threshold_(threshold * N),\n particle_(N), iter_num_(0), show_progress_(false) {}\n\n \/\/\/ \\brief Size of the particle set\n \/\/\/\n \/\/\/ \\return The number of particles\n std::size_t size () const\n {\n return particle_.size();\n }\n\n \/\/\/ \\brief Size of records\n \/\/\/\n \/\/\/ \\return The number of iterations recorded (including the\n \/\/\/ initialization step)\n std::size_t iter_size () const\n {\n return ess_.size();\n }\n\n \/\/\/ \\brief ESS\n \/\/\/\n \/\/\/ \\return The ESS value of the latest iteration\n double ess () const\n {\n return ess_.back();\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\return A const reference to the history of ESS\n const std::vector<double> &ess_history () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void ess_history (OIter first) const\n {\n for (std::vector<double>::const_iterator iter = ess_.begin();\n iter != ess_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Indicator of resampling\n \/\/\/\n \/\/\/ \\return A bool value, \\b true if the latest iteration was resampled\n bool resampled () const\n {\n return resampled_.back();\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\return A const reference to the history of resampling\n const std::vector<bool> &resampled_history () const\n {\n return resampled_;\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void resampled_history (OIter first) const\n {\n for (std::vector<bool>::const_iterator iter = resampled_.begin();\n iter != resampled_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Accept count\n \/\/\/\n \/\/\/ \\return The accept count of the latest iteration\n std::size_t accept () const\n {\n return accept_.back();\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\return A const reference to the history of accept count\n const std::vector<std::size_t> &accept_history () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void accept_history (OIter first) const\n {\n for (std::vector<std::size_t>::const_iterator iter = accept_.begin();\n iter != accept_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Read and write access to the particle set\n \/\/\/\n \/\/\/ \\return A reference to the latest particle set\n \/\/\/\n \/\/\/ \\note The Sampler class guarantee that during the life type of the\n \/\/\/ object, the reference returned by this member will no be a dangle\n \/\/\/ handler.\n Particle<T> &particle ()\n {\n return particle_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief Initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to the initialization\n \/\/\/ functor\n void initialize (void *param = NULL)\n {\n ess_.clear();\n resampled_.clear();\n accept_.clear();\n path_.clear();\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap)\n imap->second.clear();\n\n iter_num_ = 0;\n accept_.push_back(init_(particle_, param));\n post_move();\n particle_.reset_zconst();\n\n initialized_ = true;\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n if (!initialized_) {\n throw std::runtime_error(\n \"ERROR: vSMC::Sampler::iterate: \"\n \"Sampler has not been initialized yet\");\n }\n\n ++iter_num_;\n accept_.push_back(move_(iter_num_, particle_));\n if (mcmc_)\n accept_.back() = mcmc_(iter_num_, particle_);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (std::size_t n)\n {\n for (std::size_t i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n double integrate (typename Monitor<T>::integral_type integral)\n {\n buffer_.resize(size());\n integral(iter_num_, particle_, buffer_);\n\n return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n \/\/\/ \\param param Additional parameters passed to the integral functor\n double integrate (integral_type integral, void *param) const\n {\n buffer_.resize(size());\n integral(iter_num_, particle_, buffer_, param);\n\n return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Add a monitor, similar to \\b monitor in \\b BUGS\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param integral The functor used to compute the integrands\n void monitor (const std::string &name,\n const typename Monitor<T>::integral_type &integral)\n {\n monitor_.insert(std::make_pair(name, Monitor<T>(integral)));\n monitor_name_.insert(name);\n }\n\n \/\/\/ \\brief Read and write access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return An iterator point to the monitor for the given name\n typename std::map<std::string, Monitor<T> >::iterator\n monitor (const std::string &name)\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read only access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return An const_iterator point to the monitor for the given name\n typename std::map<std::string, Monitor<T> >::const_iterator\n monitor (const std::string &name) const\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read and write access to all monitors\n \/\/\/\n \/\/\/ \\return A reference to monitors\n std::map<std::string, Monitor<T> > &monitor ()\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Read only access to all monitors\n \/\/\/\n \/\/\/ \\return A const reference to monitors\n const std::map<std::string, Monitor<T> > &monitor () const\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Erase a named monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void erase_monitor (const std::string &name)\n {\n monitor_.erase(name);\n monitor_name_.erase(name);\n }\n\n \/\/\/ \\brief Erase (clear) all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n monitor_name_.clear();\n }\n\n \/\/\/ \\brief Read and write access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A reference to the Path sampling monitor\n Path<T> &path ()\n {\n return path_;\n }\n\n \/\/\/ \\brief Read only access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A const reference to the Path sampling monitor\n const Path<T> &path () const\n {\n return path_;\n }\n\n \/\/\/ \\brief Set the path sampling integral\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n \/\/\/\n \/\/\/ \\note Set integral = NULL will stop path sampling recording\n void path_sampling (const typename Path<T>::integral_type &integral)\n {\n path_.integral(integral);\n }\n\n \/\/\/ \\brief Path sampling estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log ratio of normalizing constants\n double path_sampling_zconst () const\n {\n return path_.zconst();\n }\n\n \/\/\/ \\brief Toggle whether or not record SMC normalizing constant\n \/\/\/\n \/\/\/ \\param estimate_zconst Start estimating normalzing constant if true.\n void zconst (bool estimate_zconst)\n {\n particle_.zconst(estimate_zconst);\n }\n\n \/\/\/ \\brief SMC estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The SMC normalizng constant estimate\n double zconst () const\n {\n return particle_.zconst();\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param output The ostream to which the contents are printed\n \/\/\/ \\param print_header Print header if \\b true\n void print (std::ostream &output = std::cout,\n bool print_header = true) const\n {\n print(output, print_header, !path_.index().empty(), monitor_name_);\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param output The ostream to which the contents are printed\n \/\/\/ \\param print_path Print path sampling history if \\b true\n \/\/\/ \\param print_monitor A set of monitor names to be printed\n \/\/\/ \\param print_header Print header if \\b true\n void print (std::ostream &output,\n bool print_header, bool print_path,\n const std::set<std::string> &print_monitor) const\n {\n if (print_header) {\n output << \"iter\\tESS\\tresample\\taccept\\t\";\n if (print_path)\n output << \"path.integrand\\tpath.width\\tpath.grid\\t\";\n }\n\n std::vector<std::size_t>::const_iterator iter_path_index\n = path_.index().begin();\n std::vector<double>::const_iterator iter_path_integrand\n = path_.integrand().begin();\n std::vector<double>::const_iterator iter_path_width\n = path_.width().begin();\n std::vector<double>::const_iterator iter_path_grid\n = path_.grid().begin();\n\n std::vector<bool> monitor_index_empty;\n std::vector<std::vector<std::size_t>::const_iterator>\n iter_monitor_index;\n std::vector<std::vector<double>::const_iterator>\n iter_monitor_record;\n for (typename std::map<std::string, Monitor<T> >::const_iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (print_monitor.count(imap->first)) {\n monitor_index_empty.push_back(imap->second.index().empty());\n iter_monitor_index.push_back(imap->second.index().begin());\n iter_monitor_record.push_back(imap->second.record().begin());\n if (print_header)\n output << imap->first << '\\t';\n }\n }\n\n if (print_header)\n output << '\\n';\n\n for (std::size_t i = 0; i != iter_size(); ++i) {\n output\n << i << '\\t' << ess_[i] \/ size()\n << '\\t' << resampled_[i]\n << '\\t' << static_cast<double>(accept_[i]) \/ size();\n\n if (print_path) {\n if (!path_.index().empty() && *iter_path_index == i) {\n output\n << '\\t' << *iter_path_integrand++\n << '\\t' << *iter_path_width++\n << '\\t' << *iter_path_grid++;\n ++iter_path_index;\n } else {\n output << '\\t' << '.' << '\\t' << '.' << '\\t' << '.';\n }\n }\n\n for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) {\n if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {\n output << '\\t' << *iter_monitor_record[m]++;\n ++iter_monitor_index[m];\n } else {\n output << '\\t' << '.';\n }\n }\n\n output << '\\n';\n }\n }\n\n private :\n\n \/\/\/ Initialization indicator\n bool initialized_;\n\n \/\/\/ Initialization and movement\n init_type init_;\n move_type move_;\n move_type mcmc_;\n\n \/\/\/ Resampling\n vDist::RngGSL rng_;\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n std::size_t iter_num_;\n std::vector<double> ess_;\n std::vector<bool> resampled_;\n std::vector<std::size_t> accept_;\n\n \/\/\/ Monte Carlo estimation by integration\n vDist::tool::Buffer<double> buffer_;\n std::map<std::string, Monitor<T> > monitor_;\n std::set<std::string> monitor_name_;\n\n \/\/\/ Path sampling\n Path<T> path_;\n\n \/\/\/ Whether to show prograss while iterating\n bool show_progress_;\n\n void post_move ()\n {\n ess_.push_back(particle_.ess());\n particle_.resampled(ess_.back() < threshold_);\n resampled_.push_back(particle_.resampled());\n if (particle_.resampled())\n particle_.resample(scheme_, rng_.get_rng());\n\n if (!path_.empty())\n path_.eval(iter_num_, particle_);\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (!imap->second.empty())\n imap->second.eval(iter_num_, particle_);\n }\n\n if (show_progress_) {\n if (iter_num_)\n std::cerr << '.';\n else\n std::cerr << '*';\n std::cerr.flush();\n }\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\nnamespace std {\n\ntemplate<typename T>\nstd::ostream & operator<< (std::ostream &output,\n const vSMC::Sampler<T> &sampler)\n{\n sampler.print(output);\n\n return output;\n}\n\n} \/\/ namespace std\n\n#endif \/\/ V_SMC_SAMPLER_HPP\n<commit_msg>documentation of the examples<commit_after>#ifndef V_SMC_SAMPLER_HPP\n#define V_SMC_SAMPLER_HPP\n\n#include <vSMC\/config.hpp>\n\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <mkl_cblas.h>\n#include <boost\/function.hpp>\n#include <vDist\/rng\/gsl.hpp>\n#include <vDist\/tool\/buffer.hpp>\n#include <vSMC\/monitor.hpp>\n#include <vSMC\/particle.hpp>\n#include <vSMC\/path.hpp>\n\n\/*************************************************************************\/\/**\n * \\page pf_seq Sequential implementation of particle filter example\n *\n * This example is implemented with sequential code. Most of the code is no\n * more complex than those found in SMCTC. This is only a proof of concept that\n * vSMC can also be used in a similar fashion as in SMCTC. But for sequential\n * implementation, SMCTC is much more stable and matured. For a vectorized\n * implementation, which really takes the advantage of vSMC, see \\ref pf_eigen.\n *\n * \\include pf\/pf_seq.cpp\n *\n * \\page pf_eigen Vectorized implementation of particle filter example\n *\n * This example is implemented with the Eigen library. Its syntax is quite\n * elegent and in most case its use shall be self-explained by the code. It\n * also use the vDist library for vectorized computation of pdf, kernel,\n * generating random variates, etc. For a sequential implementation without any\n * use of SIMD see \\ref pf_seq.\n *\n * \\include pf\/pf_eigen.cpp\n ****************************************************************************\/\n\nnamespace vSMC {\n\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of initialization functor\n typedef boost::function<std::size_t\n (Particle<T> &, void *)> init_type;\n \/\/\/ The type of move functor\n typedef boost::function<std::size_t\n (std::size_t, Particle<T> &)> move_type;\n \/\/\/ The type of importance sampling integral functor\n typedef boost::function<void\n (std::size_t, Particle<T> &, double *, void *)> integral_type;\n\n \/\/\/ \\brief Sampler does not have a default constructor\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param mcmc The functor used to perform MCMC move\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed for the reampling RNG. See documentation of vDist\n \/\/\/ \\param brng The basic RNG for resampling RNG. See documentation of GSL\n Sampler (\n std::size_t N,\n const init_type &init,\n const move_type &move,\n const move_type &mcmc = NULL,\n ResampleScheme scheme = RESIDUAL,\n double threshold = 0.5,\n const int seed = V_DIST_SEED,\n const gsl_rng_type *brng = V_DIST_GSL_BRNG) :\n initialized_(false), init_(init), move_(move), mcmc_(mcmc),\n rng_(seed, brng), scheme_(scheme), threshold_(threshold * N),\n particle_(N), iter_num_(0), show_progress_(false) {}\n\n \/\/\/ \\brief Size of the particle set\n \/\/\/\n \/\/\/ \\return The number of particles\n std::size_t size () const\n {\n return particle_.size();\n }\n\n \/\/\/ \\brief Size of records\n \/\/\/\n \/\/\/ \\return The number of iterations recorded (including the\n \/\/\/ initialization step)\n std::size_t iter_size () const\n {\n return ess_.size();\n }\n\n \/\/\/ \\brief ESS\n \/\/\/\n \/\/\/ \\return The ESS value of the latest iteration\n double ess () const\n {\n return ess_.back();\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\return A const reference to the history of ESS\n const std::vector<double> &ess_history () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void ess_history (OIter first) const\n {\n for (std::vector<double>::const_iterator iter = ess_.begin();\n iter != ess_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Indicator of resampling\n \/\/\/\n \/\/\/ \\return A bool value, \\b true if the latest iteration was resampled\n bool resampled () const\n {\n return resampled_.back();\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\return A const reference to the history of resampling\n const std::vector<bool> &resampled_history () const\n {\n return resampled_;\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void resampled_history (OIter first) const\n {\n for (std::vector<bool>::const_iterator iter = resampled_.begin();\n iter != resampled_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Accept count\n \/\/\/\n \/\/\/ \\return The accept count of the latest iteration\n std::size_t accept () const\n {\n return accept_.back();\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\return A const reference to the history of accept count\n const std::vector<std::size_t> &accept_history () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\param first An iterator point to where writing starts\n template<typename OIter>\n void accept_history (OIter first) const\n {\n for (std::vector<std::size_t>::const_iterator iter = accept_.begin();\n iter != accept_.end(); ++iter)\n *first++ = *iter;\n }\n\n \/\/\/ \\brief Read and write access to the particle set\n \/\/\/\n \/\/\/ \\return A reference to the latest particle set\n \/\/\/\n \/\/\/ \\note The Sampler class guarantee that during the life type of the\n \/\/\/ object, the reference returned by this member will no be a dangle\n \/\/\/ handler.\n Particle<T> &particle ()\n {\n return particle_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief Initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to the initialization\n \/\/\/ functor\n void initialize (void *param = NULL)\n {\n ess_.clear();\n resampled_.clear();\n accept_.clear();\n path_.clear();\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap)\n imap->second.clear();\n\n iter_num_ = 0;\n accept_.push_back(init_(particle_, param));\n post_move();\n particle_.reset_zconst();\n\n initialized_ = true;\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n if (!initialized_) {\n throw std::runtime_error(\n \"ERROR: vSMC::Sampler::iterate: \"\n \"Sampler has not been initialized yet\");\n }\n\n ++iter_num_;\n accept_.push_back(move_(iter_num_, particle_));\n if (mcmc_)\n accept_.back() = mcmc_(iter_num_, particle_);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (std::size_t n)\n {\n for (std::size_t i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n double integrate (typename Monitor<T>::integral_type integral)\n {\n buffer_.resize(size());\n integral(iter_num_, particle_, buffer_);\n\n return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n \/\/\/ \\param param Additional parameters passed to the integral functor\n double integrate (integral_type integral, void *param) const\n {\n buffer_.resize(size());\n integral(iter_num_, particle_, buffer_, param);\n\n return cblas_ddot(size(), particle_.weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Add a monitor, similar to \\b monitor in \\b BUGS\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param integral The functor used to compute the integrands\n void monitor (const std::string &name,\n const typename Monitor<T>::integral_type &integral)\n {\n monitor_.insert(std::make_pair(name, Monitor<T>(integral)));\n monitor_name_.insert(name);\n }\n\n \/\/\/ \\brief Read and write access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return An iterator point to the monitor for the given name\n typename std::map<std::string, Monitor<T> >::iterator\n monitor (const std::string &name)\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read only access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return An const_iterator point to the monitor for the given name\n typename std::map<std::string, Monitor<T> >::const_iterator\n monitor (const std::string &name) const\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read and write access to all monitors\n \/\/\/\n \/\/\/ \\return A reference to monitors\n std::map<std::string, Monitor<T> > &monitor ()\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Read only access to all monitors\n \/\/\/\n \/\/\/ \\return A const reference to monitors\n const std::map<std::string, Monitor<T> > &monitor () const\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Erase a named monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void erase_monitor (const std::string &name)\n {\n monitor_.erase(name);\n monitor_name_.erase(name);\n }\n\n \/\/\/ \\brief Erase (clear) all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n monitor_name_.clear();\n }\n\n \/\/\/ \\brief Read and write access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A reference to the Path sampling monitor\n Path<T> &path ()\n {\n return path_;\n }\n\n \/\/\/ \\brief Read only access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A const reference to the Path sampling monitor\n const Path<T> &path () const\n {\n return path_;\n }\n\n \/\/\/ \\brief Set the path sampling integral\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n \/\/\/\n \/\/\/ \\note Set integral = NULL will stop path sampling recording\n void path_sampling (const typename Path<T>::integral_type &integral)\n {\n path_.integral(integral);\n }\n\n \/\/\/ \\brief Path sampling estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log ratio of normalizing constants\n double path_sampling_zconst () const\n {\n return path_.zconst();\n }\n\n \/\/\/ \\brief Toggle whether or not record SMC normalizing constant\n \/\/\/\n \/\/\/ \\param estimate_zconst Start estimating normalzing constant if true.\n void zconst (bool estimate_zconst)\n {\n particle_.zconst(estimate_zconst);\n }\n\n \/\/\/ \\brief SMC estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The SMC normalizng constant estimate\n double zconst () const\n {\n return particle_.zconst();\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param output The ostream to which the contents are printed\n \/\/\/ \\param print_header Print header if \\b true\n void print (std::ostream &output = std::cout,\n bool print_header = true) const\n {\n print(output, print_header, !path_.index().empty(), monitor_name_);\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param output The ostream to which the contents are printed\n \/\/\/ \\param print_path Print path sampling history if \\b true\n \/\/\/ \\param print_monitor A set of monitor names to be printed\n \/\/\/ \\param print_header Print header if \\b true\n void print (std::ostream &output,\n bool print_header, bool print_path,\n const std::set<std::string> &print_monitor) const\n {\n if (print_header) {\n output << \"iter\\tESS\\tresample\\taccept\\t\";\n if (print_path)\n output << \"path.integrand\\tpath.width\\tpath.grid\\t\";\n }\n\n std::vector<std::size_t>::const_iterator iter_path_index\n = path_.index().begin();\n std::vector<double>::const_iterator iter_path_integrand\n = path_.integrand().begin();\n std::vector<double>::const_iterator iter_path_width\n = path_.width().begin();\n std::vector<double>::const_iterator iter_path_grid\n = path_.grid().begin();\n\n std::vector<bool> monitor_index_empty;\n std::vector<std::vector<std::size_t>::const_iterator>\n iter_monitor_index;\n std::vector<std::vector<double>::const_iterator>\n iter_monitor_record;\n for (typename std::map<std::string, Monitor<T> >::const_iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (print_monitor.count(imap->first)) {\n monitor_index_empty.push_back(imap->second.index().empty());\n iter_monitor_index.push_back(imap->second.index().begin());\n iter_monitor_record.push_back(imap->second.record().begin());\n if (print_header)\n output << imap->first << '\\t';\n }\n }\n\n if (print_header)\n output << '\\n';\n\n for (std::size_t i = 0; i != iter_size(); ++i) {\n output\n << i << '\\t' << ess_[i] \/ size()\n << '\\t' << resampled_[i]\n << '\\t' << static_cast<double>(accept_[i]) \/ size();\n\n if (print_path) {\n if (!path_.index().empty() && *iter_path_index == i) {\n output\n << '\\t' << *iter_path_integrand++\n << '\\t' << *iter_path_width++\n << '\\t' << *iter_path_grid++;\n ++iter_path_index;\n } else {\n output << '\\t' << '.' << '\\t' << '.' << '\\t' << '.';\n }\n }\n\n for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) {\n if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {\n output << '\\t' << *iter_monitor_record[m]++;\n ++iter_monitor_index[m];\n } else {\n output << '\\t' << '.';\n }\n }\n\n output << '\\n';\n }\n }\n\n private :\n\n \/\/\/ Initialization indicator\n bool initialized_;\n\n \/\/\/ Initialization and movement\n init_type init_;\n move_type move_;\n move_type mcmc_;\n\n \/\/\/ Resampling\n vDist::RngGSL rng_;\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n std::size_t iter_num_;\n std::vector<double> ess_;\n std::vector<bool> resampled_;\n std::vector<std::size_t> accept_;\n\n \/\/\/ Monte Carlo estimation by integration\n vDist::tool::Buffer<double> buffer_;\n std::map<std::string, Monitor<T> > monitor_;\n std::set<std::string> monitor_name_;\n\n \/\/\/ Path sampling\n Path<T> path_;\n\n \/\/\/ Whether to show prograss while iterating\n bool show_progress_;\n\n void post_move ()\n {\n ess_.push_back(particle_.ess());\n particle_.resampled(ess_.back() < threshold_);\n resampled_.push_back(particle_.resampled());\n if (particle_.resampled())\n particle_.resample(scheme_, rng_.get_rng());\n\n if (!path_.empty())\n path_.eval(iter_num_, particle_);\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (!imap->second.empty())\n imap->second.eval(iter_num_, particle_);\n }\n\n if (show_progress_) {\n if (iter_num_)\n std::cerr << '.';\n else\n std::cerr << '*';\n std::cerr.flush();\n }\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\nnamespace std {\n\ntemplate<typename T>\nstd::ostream & operator<< (std::ostream &output,\n const vSMC::Sampler<T> &sampler)\n{\n sampler.print(output);\n\n return output;\n}\n\n} \/\/ namespace std\n\n#endif \/\/ V_SMC_SAMPLER_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef V_SMC_SAMPLER_HPP\n#define V_SMC_SAMPLER_HPP\n\n#include <vSMC\/config.hpp>\n\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <mkl_cblas.h>\n#include <boost\/function.hpp>\n#include <vDist\/rng\/gsl.hpp>\n#include <vDist\/tool\/buffer.hpp>\n#include <vSMC\/history.hpp>\n#include <vSMC\/monitor.hpp>\n#include <vSMC\/particle.hpp>\n\nnamespace vSMC {\n\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of particle values\n typedef T value_type;\n \/\/\/ The type of partiles\n typedef Particle<T> particle_type;\n \/\/\/ The type of initialize callable objects\n typedef boost::function<std::size_t\n (Particle<T> &, void *)> init_type;\n \/\/\/ The type of move callable objects\n typedef boost::function<std::size_t\n (std::size_t, Particle<T> &)> move_type;\n \/\/\/ The type of importance sampling integral\n typedef boost::function<void\n (std::size_t, const Particle<T> &, double *, void *)> integral_type;\n \/\/\/ The type of path sampling integration\n typedef boost::function<double\n (std::size_t, const Particle<T> &, double *)> path_type;\n\n \/\/\/ \\brief Sampler does not have a default constructor\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param copy The functor used to copy particles within the sample\n \/\/\/ \\param mcmc The functor used to perform MCMC move\n \/\/\/ \\param mode The history storage mode. See HistoryMode\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed for the reampling RNG. See documentation of vDist\n \/\/\/ \\param brng The basic RNG for resampling RNG. See documentation of GSL\n Sampler (\n std::size_t N,\n const init_type &init,\n const move_type &move,\n const typename Particle<T>::copy_type ©,\n const move_type &mcmc = NULL,\n HistoryMode mode = HISTORY_NONE,\n ResampleScheme scheme = RESIDUAL,\n double threshold = 0.5,\n const int seed = V_DIST_SEED,\n const gsl_rng_type *brng = V_DIST_GSL_BRNG) :\n initialized_(false), init_(init), move_(move), mcmc_(mcmc),\n rng_(seed, brng), scheme_(scheme), threshold_(threshold * N),\n particle_(N, copy), iter_num_(0), history_(mode),\n buffer_(N), path_integral_(NULL), show_progress_(false) {}\n\n \/\/\/ \\brief Get ESS\n \/\/\/\n \/\/\/ \\return The ESS value of the latest iteration\n double get_ESS () const\n {\n return ess_.back();\n }\n\n \/\/\/ \\brief Get all ESS\n \/\/\/\n \/\/\/ \\return History of ESS for all iterations\n const std::vector<double> &get_ESS_history () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief Get indicator of resampling\n \/\/\/\n \/\/\/ \\return A bool value, \\b true if the latest iteration was resampled\n bool get_resample () const\n {\n return resample_.back();\n }\n\n \/\/\/ \\brief Get history of resampling\n \/\/\/\n \/\/\/ \\return History of resampling for all iterations\n const std::vector<bool> &get_resample_history () const\n {\n return resample_;\n }\n\n \/\/\/ \\brief Get accept count\n \/\/\/\n \/\/\/ \\return The accept count of the latest iteration\n std::size_t get_accept () const\n {\n return accept_.back();\n }\n\n \/\/\/ \\brief Get history of accept count\n \/\/\/\n \/\/\/ \\return History of accept count for all iterations\n const std::vector<std::size_t> &get_accept_history () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n \/\/\/ \\note Any operations that change the state of the sampler (e.g., an\n \/\/\/ iteration) may invalidate the reference.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief (Re)initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to initialization functor,\n \/\/\/ the default is NULL\n void initialize (void *param = NULL)\n {\n history_.clear();\n ess_.clear();\n resample_.clear();\n accept_.clear();\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap)\n imap->second.clear();\n\n path_sample_.clear();\n path_width_.clear();\n path_grid_.clear();\n\n iter_num_ = 0;\n accept_.push_back(init_(particle_, param));\n post_move();\n\n initialized_ = true;\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n if (!initialized_)\n throw std::runtime_error(\n \"ERROR: vSMC::Sampler::iterate: \"\n \"Sampler has not been initialized yet\");\n\n ++iter_num_;\n accept_.push_back(move_(iter_num_, particle_));\n if (mcmc_)\n accept_.back() = mcmc_(iter_num_, particle_);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (std::size_t n)\n {\n for (std::size_t i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param intgral The functor used to compute the integrands\n double integrate (typename Monitor<T>::integral_type integral) const\n {\n std::size_t n = particle_.size();\n integral(iter_num_, particle_, buffer_);\n\n return cblas_ddot(n, particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param intgral The functor used to compute the integrands\n \/\/\/ \\param param Additional parameters to be passed to integral\n double integrate (integral_type integral, void *param) const\n {\n std::size_t n = particle_.size();\n integral(iter_num_, particle_, buffer_, param);\n\n return cblas_ddot(n, particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Add a monitor, similar to \\b monitor in \\b BUGS\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param integral The functor used to compute the integrands\n void add_monitor (const std::string &name,\n const typename Monitor<T>::integral_type &integral)\n {\n monitor_.insert(\n typename std::map<std::string, Monitor<T> >::value_type(\n name, Monitor<T>(particle_.size(), integral)));\n }\n\n \/\/\/ \\brief Get the iteration index of a monitor\n \/\/\/\n \/\/\/ \\param The name of the monitor\n \/\/\/ \\return A vector of the monitor index\n typename Monitor<T>::index_type get_monitor_index (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get_index();\n }\n\n \/\/\/ \\brief Get the record of Monite Carlo integration of a monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return A vector of the monitor record\n typename Monitor<T>::record_type get_monitor_record (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get_record();\n }\n\n \/\/\/ \\brief Get both the iteration index and record of a monitor\n typename Monitor<T>::value_type get_monitor_value (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get();\n }\n\n \/\/\/ \\brief Erase a monitor by name \n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void erase_monitor (const std::string &name)\n {\n monitor_.erase(name);\n }\n\n \/\/\/ \\brief Clear all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n }\n\n \/\/\/ \\brief Set the path sampling integral\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n void set_path_sampling (path_type integral)\n {\n path_integral_ = integral;\n }\n\n \/\/\/ \\brief Stop path sampling\n void clear_path_sampling ()\n {\n path_integral_ = NULL;\n }\n\n \/\/\/ \\brief Get the results of path sampling\n double get_path_sampling () const\n {\n\tstd::size_t num = path_sample_.size();\n\tdouble sum = 0;\n\tfor (std::size_t i = 1; i != num; ++i)\n sum += (path_sample_[i-1] + path_sample_[i])\n * path_width_[i] * 0.5;\n return sum;\n }\n\n const std::vector<double> &get_path_sample_history () const\n {\n return path_sample_;\n }\n\n const std::vector<double> &get_path_width_history () const\n {\n return path_width_;\n }\n\n const std::vector<double> &get_path_grid_history () const\n {\n return path_grid_;\n }\n\n void toggle_show_progress ()\n {\n show_progress_ = !show_progress_;\n }\n\n private :\n\n \/\/\/ Initialization indicator\n bool initialized_;\n\n \/\/\/ Initialization and movement\n init_type init_;\n move_type move_;\n move_type mcmc_;\n\n \/\/\/ Resampling\n vDist::RngGSL rng_;\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n std::size_t iter_num_;\n std::vector<double> ess_;\n std::vector<bool> resample_;\n std::vector<std::size_t> accept_;\n\n \/\/\/ History\n History<T> history_;\n\n \/\/\/ Monte Carlo estimation by integration\n mutable vDist::tool::Buffer<double> buffer_;\n std::map<std::string, Monitor<T> > monitor_;\n\n \/\/\/ Path sampling\n path_type path_integral_;\n std::vector<double> path_sample_;\n std::vector<double> path_width_;\n std::vector<double> path_grid_;\n\n \/\/\/ Whether to show prograss while iterating\n bool show_progress_;\n\n void post_move ()\n {\n ess_.push_back(particle_.ESS());\n\n bool res_indicator = false;\n if (ess_.back() < threshold_) {\n res_indicator = true;\n particle_.resample(scheme_, rng_.get_rng());\n }\n resample_.push_back(res_indicator);\n\n if (history_.mode() != HISTORY_NONE)\n history_.push_back(particle_);\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (!imap->second.empty())\n imap->second.eval(iter_num_, particle_);\n }\n\n if (!path_integral_.empty()) {\n double width; \n path_sample_.push_back(eval_path(width));\n path_width_.push_back(width);\n path_grid_.push_back(path_grid_.size() ?\n path_grid_.back() + width : width);\n }\n\n if (show_progress_) {\n std::cerr << '.';\n std::cerr.flush();\n }\n }\n\n double eval_path (double &width)\n {\n width = path_integral_(iter_num_, particle_, buffer_);\n\n return cblas_ddot(particle_.size(),\n particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\n#endif \/\/ V_SMC_SAMPLER_HPP\n<commit_msg>documentation update<commit_after>#ifndef V_SMC_SAMPLER_HPP\n#define V_SMC_SAMPLER_HPP\n\n#include <vSMC\/config.hpp>\n\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <mkl_cblas.h>\n#include <boost\/function.hpp>\n#include <vDist\/rng\/gsl.hpp>\n#include <vDist\/tool\/buffer.hpp>\n#include <vSMC\/history.hpp>\n#include <vSMC\/monitor.hpp>\n#include <vSMC\/particle.hpp>\n\nnamespace vSMC {\n\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of particle values\n typedef T value_type;\n \/\/\/ The type of partiles\n typedef Particle<T> particle_type;\n \/\/\/ The type of initialize callable objects\n typedef boost::function<std::size_t\n (Particle<T> &, void *)> init_type;\n \/\/\/ The type of move callable objects\n typedef boost::function<std::size_t\n (std::size_t, Particle<T> &)> move_type;\n \/\/\/ The type of importance sampling integral\n typedef boost::function<void\n (std::size_t, const Particle<T> &, double *, void *)> integral_type;\n \/\/\/ The type of path sampling integration\n typedef boost::function<double\n (std::size_t, const Particle<T> &, double *)> path_type;\n\n \/\/\/ \\brief Sampler does not have a default constructor\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param copy The functor used to copy particles within the sample\n \/\/\/ \\param mcmc The functor used to perform MCMC move\n \/\/\/ \\param mode The history storage mode. See HistoryMode\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed for the reampling RNG. See documentation of vDist\n \/\/\/ \\param brng The basic RNG for resampling RNG. See documentation of GSL\n Sampler (\n std::size_t N,\n const init_type &init,\n const move_type &move,\n const typename Particle<T>::copy_type ©,\n const move_type &mcmc = NULL,\n HistoryMode mode = HISTORY_NONE,\n ResampleScheme scheme = RESIDUAL,\n double threshold = 0.5,\n const int seed = V_DIST_SEED,\n const gsl_rng_type *brng = V_DIST_GSL_BRNG) :\n initialized_(false), init_(init), move_(move), mcmc_(mcmc),\n rng_(seed, brng), scheme_(scheme), threshold_(threshold * N),\n particle_(N, copy), iter_num_(0), history_(mode),\n buffer_(N), path_integral_(NULL), show_progress_(false) {}\n\n \/\/\/ \\brief Get ESS\n \/\/\/\n \/\/\/ \\return The ESS value of the latest iteration\n double get_ESS () const\n {\n return ess_.back();\n }\n\n \/\/\/ \\brief Get all ESS\n \/\/\/\n \/\/\/ \\return History of ESS for all iterations\n const std::vector<double> &get_ESS_history () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief Get indicator of resampling\n \/\/\/\n \/\/\/ \\return A bool value, \\b true if the latest iteration was resampled\n bool get_resample () const\n {\n return resample_.back();\n }\n\n \/\/\/ \\brief Get history of resampling\n \/\/\/\n \/\/\/ \\return History of resampling for all iterations\n const std::vector<bool> &get_resample_history () const\n {\n return resample_;\n }\n\n \/\/\/ \\brief Get accept count\n \/\/\/\n \/\/\/ \\return The accept count of the latest iteration\n std::size_t get_accept () const\n {\n return accept_.back();\n }\n\n \/\/\/ \\brief Get history of accept count\n \/\/\/\n \/\/\/ \\return History of accept count for all iterations\n const std::vector<std::size_t> &get_accept_history () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n \/\/\/ \\note Any operations that change the state of the sampler (e.g., an\n \/\/\/ iteration) may invalidate the reference.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief (Re)initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to initialization functor,\n \/\/\/ the default is NULL\n void initialize (void *param = NULL)\n {\n history_.clear();\n ess_.clear();\n resample_.clear();\n accept_.clear();\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap)\n imap->second.clear();\n\n path_sample_.clear();\n path_width_.clear();\n path_grid_.clear();\n\n iter_num_ = 0;\n accept_.push_back(init_(particle_, param));\n post_move();\n\n initialized_ = true;\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n if (!initialized_)\n throw std::runtime_error(\n \"ERROR: vSMC::Sampler::iterate: \"\n \"Sampler has not been initialized yet\");\n\n ++iter_num_;\n accept_.push_back(move_(iter_num_, particle_));\n if (mcmc_)\n accept_.back() = mcmc_(iter_num_, particle_);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (std::size_t n)\n {\n for (std::size_t i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param intgral The functor used to compute the integrands\n double integrate (typename Monitor<T>::integral_type integral) const\n {\n std::size_t n = particle_.size();\n integral(iter_num_, particle_, buffer_);\n\n return cblas_ddot(n, particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Perform importance sampling integration\n \/\/\/\n \/\/\/ \\param intgral The functor used to compute the integrands\n \/\/\/ \\param param Additional parameters to be passed to integral\n double integrate (integral_type integral, void *param) const\n {\n std::size_t n = particle_.size();\n integral(iter_num_, particle_, buffer_, param);\n\n return cblas_ddot(n, particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n\n \/\/\/ \\brief Add a monitor, similar to \\b monitor in \\b BUGS\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param integral The functor used to compute the integrands\n void add_monitor (const std::string &name,\n const typename Monitor<T>::integral_type &integral)\n {\n monitor_.insert(\n typename std::map<std::string, Monitor<T> >::value_type(\n name, Monitor<T>(particle_.size(), integral)));\n }\n\n \/\/\/ \\brief Get the iteration index of a monitor\n \/\/\/\n \/\/\/ \\param The name of the monitor\n \/\/\/ \\return A vector of the monitor index\n typename Monitor<T>::index_type get_monitor_index (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get_index();\n }\n\n \/\/\/ \\brief Get the record of Monite Carlo integration of a monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return A vector of the monitor record\n typename Monitor<T>::record_type get_monitor_record (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get_record();\n }\n\n \/\/\/ \\brief Get both the iteration index and record of a monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\return A pair of vectors of the monitor record and index\n typename Monitor<T>::value_type get_monitor_value (\n const std::string &name) const\n {\n return monitor_.find(name)->second.get();\n }\n\n \/\/\/ \\brief Erase a monitor by name \n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void erase_monitor (const std::string &name)\n {\n monitor_.erase(name);\n }\n\n \/\/\/ \\brief Clear all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n }\n\n \/\/\/ \\brief Set the path sampling integral\n \/\/\/\n \/\/\/ \\param integral The functor used to compute the integrands\n void set_path_sampling (path_type integral)\n {\n path_integral_ = integral;\n }\n\n \/\/\/ \\brief Stop path sampling\n void clear_path_sampling ()\n {\n path_integral_ = NULL;\n }\n\n \/\/\/ \\brief Get the results of path sampling\n \/\/\/\n \/\/\/ \\return The path sampling integration result\n double get_path_sampling () const\n {\n\tstd::size_t num = path_sample_.size();\n\tdouble sum = 0;\n\tfor (std::size_t i = 1; i != num; ++i)\n sum += (path_sample_[i-1] + path_sample_[i])\n * path_width_[i] * 0.5;\n return sum;\n }\n\n \/\/\/ \\brief Get the history of path sampling integrand\n \/\/\/\n \/\/\/ \\return A vector of the path sampling integrand history\n const std::vector<double> &get_path_sample_history () const\n {\n return path_sample_;\n }\n\n \/\/\/ \\brief Get the history of path sampling width\n \/\/\/\n \/\/\/ \\return A vector of the path sampling width history\n const std::vector<double> &get_path_width_history () const\n {\n return path_width_;\n }\n\n \/\/\/ \\brief Get the history of path sampling grid\n \/\/\/\n \/\/\/ \\return A vector of the path sampling accumulative width history\n const std::vector<double> &get_path_grid_history () const\n {\n return path_grid_;\n }\n\n \/\/\/ \\brief Toggle whether or not show progress information while iterating\n void toggle_show_progress ()\n {\n show_progress_ = !show_progress_;\n }\n\n private :\n\n \/\/\/ Initialization indicator\n bool initialized_;\n\n \/\/\/ Initialization and movement\n init_type init_;\n move_type move_;\n move_type mcmc_;\n\n \/\/\/ Resampling\n vDist::RngGSL rng_;\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n std::size_t iter_num_;\n std::vector<double> ess_;\n std::vector<bool> resample_;\n std::vector<std::size_t> accept_;\n\n \/\/\/ History\n History<T> history_;\n\n \/\/\/ Monte Carlo estimation by integration\n mutable vDist::tool::Buffer<double> buffer_;\n std::map<std::string, Monitor<T> > monitor_;\n\n \/\/\/ Path sampling\n path_type path_integral_;\n std::vector<double> path_sample_;\n std::vector<double> path_width_;\n std::vector<double> path_grid_;\n\n \/\/\/ Whether to show prograss while iterating\n bool show_progress_;\n\n void post_move ()\n {\n ess_.push_back(particle_.ESS());\n\n bool res_indicator = false;\n if (ess_.back() < threshold_) {\n res_indicator = true;\n particle_.resample(scheme_, rng_.get_rng());\n }\n resample_.push_back(res_indicator);\n\n if (history_.mode() != HISTORY_NONE)\n history_.push_back(particle_);\n\n for (typename std::map<std::string, Monitor<T> >::iterator\n imap = monitor_.begin(); imap != monitor_.end(); ++imap) {\n if (!imap->second.empty())\n imap->second.eval(iter_num_, particle_);\n }\n\n if (!path_integral_.empty()) {\n double width; \n path_sample_.push_back(eval_path(width));\n path_width_.push_back(width);\n path_grid_.push_back(path_grid_.size() ?\n path_grid_.back() + width : width);\n }\n\n if (show_progress_) {\n std::cerr << '.';\n std::cerr.flush();\n }\n }\n\n double eval_path (double &width)\n {\n width = path_integral_(iter_num_, particle_, buffer_);\n\n return cblas_ddot(particle_.size(),\n particle_.get_weight_ptr(), 1, buffer_, 1);\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\n#endif \/\/ V_SMC_SAMPLER_HPP\n<|endoftext|>"} {"text":"<commit_before>\r\n#include <vector>\r\n#include <string>\r\n#include <unordered_map>\r\n#include <memory>\r\n#include <iostream>\r\n#include <cctype>\r\n#include <SDL.h>\r\n#include <SDL_opengl.h>\r\n#include <SDL_net.h>\r\n#include <SOIL.h>\r\n#include <res_path.h>\r\n#include <scheme-defs.h>\r\n#include <scheme-private.h>\r\n#include <scheme.h>\r\n\r\n#include \"hashstring.h\"\r\n#include \"locator.h\"\r\n#include \"servicecounter.h\"\r\n#include \"service.h\"\r\n#include \"servicecheckout.h\"\r\n#include \"scripting.h\"\r\n#include \"tinyscm_if.h\"\r\n#include \"image.h\"\r\n\r\nextern SDL_sem* global_lock;\r\n\r\nextern \"C\" {\r\n\tvoid register_image_functions(scheme* sc);\r\n}\r\n\r\nnamespace venk\r\n{\r\n\r\nconst char *ImageService::computeName(const char *name)\r\n{\r\n static char imageName[Image::maxImageNameLength];\r\n\r\n extern size_t strnlen(const char *string, size_t maxlen);\r\n\r\n \/\/ skip '.tga' \r\n int end = 0;\r\n while (isalnum(name[end]))\r\n end++;\r\n strncpy(imageName, name, end);\r\n imageName[end] = '\\0';\r\n return imageName;\r\n}\r\n\r\nbool ImageService::initialise(ImageService* self)\r\n{\r\n\t(void) self;\r\n\tServiceCheckout<ScriptingService> scripting;\r\n\tscheme* sc = scripting->get_scheme();\r\n\tregister_image_functions(sc);\r\n return true;\r\n}\r\n\r\nbool ImageService::shutdown(ImageService* self)\r\n{\r\n\tself->imageTable.clear();\r\n return true;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::loadImage(const char *filename)\r\n{\r\n\tSDL_assert((filename != nullptr) && (strlen(filename) < Image::maxImageNameLength));\r\n std::shared_ptr<Image> image = std::make_shared<Image>(filename);\r\n const char *imagename = computeName(filename);\r\n std::cerr << \"Loaded image \" << imagename << std::endl;\r\n imageTable.insert(ImageLookupTable_t::value_type(imagename, image));\r\n return image;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::makeImage(const char* name, const Uint8* mem, int width, int height, int channels)\r\n{\r\n std::shared_ptr<Image> image = std::make_shared<Image>(mem, height, width, channels);\r\n imageTable.insert(ImageLookupTable_t::value_type(name, image));\r\n return image;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::getImage(const char *name)\r\n{\r\n const char *imagename = computeName(name);\r\n return std::shared_ptr<Image>(imageTable.find(imagename)->second);\r\n}\r\n\r\nstd::function<const char*()> ImageService::enumerateImages()\r\n{\r\n\tImageLookupTable_t::iterator image_it = imageTable.begin();\r\n\tauto result = [=]() mutable -> const char*\r\n\t{\r\n\t\tif (image_it != imageTable.end()) {\r\n\t\t\tconst char* name = (image_it->first).c_str();\r\n\t\t\t++image_it;\t\t\t\t\r\n\t\t\treturn name;\r\n\t\t}\r\n\t\treturn nullptr;\r\n\t};\r\n\treturn result;\r\n}\r\n\/\/ -------------------- Image methods --------------------\r\n\r\nImage::Image(const Uint8* mem, int width, int height, int channels) : mWidth(width), mHeight(height), mChannels(channels)\r\n{\r\n\tSint64 size = width*height;\r\n\tmPixels = SOIL_load_image_from_memory((const unsigned char *)mem, size, &mWidth, &mHeight, &mChannels, SOIL_LOAD_AUTO);\r\n\treturn;\r\n}\r\n\r\nImage::Image(const std::string& fileName) : mPixels(nullptr)\r\n{\r\n std::string fullFileName = getResourcePath();\r\n fullFileName = fullFileName + \"images\/\" + fileName;\r\n SDL_RWops *rwops = SDL_RWFromFile(fullFileName.c_str(), \"rb\");\r\n if (rwops != nullptr)\r\n {\r\n Sint64 size = SDL_RWsize(rwops);\r\n if (size != -1L)\r\n {\r\n void *buf = SDL_malloc(size);\r\n size_t read = SDL_RWread(rwops, buf, 1, size);\r\n if (read == size)\r\n {\r\n mPixels = SOIL_load_image_from_memory((const unsigned char *)buf, size, &mWidth, &mHeight, &mChannels, SOIL_LOAD_AUTO);\r\n if (mPixels != nullptr)\r\n {\r\n SDL_RWclose(rwops);\r\n return;\r\n }\r\n else\r\n {\r\n std::cerr << \"Creating \" << fileName << \" failed\" << std::endl;\r\n }\r\n }\r\n else\r\n {\r\n std::cerr << \"Reading \" << fileName << \" failed\" << std::endl;\r\n }\r\n SDL_free(buf);\r\n }\r\n else\r\n {\r\n std::cerr << \"Probing \" << fileName << \" failed\" << std::endl;\r\n }\r\n }\r\n else\r\n {\r\n std::cerr << \"Opening \" << fileName << \" failed\" << std::endl;\r\n }\r\n SDL_RWclose(rwops);\r\n return;\r\n}\r\n\r\nstd::shared_ptr<SDL_Surface> Image::surface() const\r\n{\r\n#if SDL_BYTEORDER == SDL_BIG_ENDIAN\r\n Uint32 rmask = 0xff000000;\r\n Uint32 gmask = 0x00ff0000;\r\n Uint32 bmask = 0x0000ff00;\r\n Uint32 amask = 0x000000ff;\r\n#else\r\n Uint32 rmask = 0x000000ff;\r\n Uint32 gmask = 0x0000ff00;\r\n Uint32 bmask = 0x00ff0000;\r\n Uint32 amask = 0xff000000;\r\n#endif\r\n\r\n auto surface_deleter = [](SDL_Surface * s)\r\n {\r\n if (s) SDL_FreeSurface(s);\r\n };\r\n std::shared_ptr<SDL_Surface> result(\r\n\t\tSDL_CreateRGBSurfaceFrom(mPixels, mWidth, mHeight, mChannels * 8, mWidth * mChannels,\r\n\t\t\t\t\t\t\t\t rmask, gmask, bmask, amask ),\r\n\t\tsurface_deleter);\r\n return result;\r\n}\r\n\r\nImage::~Image()\r\n{\r\n if (mPixels != nullptr)\r\n SOIL_free_image_data(mPixels);\r\n}\r\n\r\n\/\/ Scheme bindings\r\n\r\nextern \"C\"\r\n{\r\n\tstatic const char* imageTag = \"IMAGE\";\r\n\r\n\t\/* to manage the lifetime of images in scheme *\/\r\n\ttypedef std::unordered_map< std::string, std::shared_ptr<Image> > SchemeImageTable_t;\r\n\tSchemeImageTable_t scheme_images;\r\n\r\n\t\/* this will get called when the scheme garbage collector wants it gone *\/\r\n\tvoid scheme_image_delete(void* ptr)\r\n\t{\r\n\t\tconst char *ref = (const char*) ptr;\r\n\t\tscheme_images.erase(ref);\r\n\t\tSDL_free(ptr);\r\n\t}\r\n\r\n\t\/* add an image in scheme vector form to the image management *\/\r\n\tpointer add_image_from_scheme(scheme *sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tpointer name_arg;\r\n\t\tif( is_string( name_arg = pair_car(args)) )\r\n\t\t{\r\n\t\t\tchar *name;\r\n\t\t\tname = string_value( name_arg );\r\n\t\t\tstd::cout << \"Creating image named \" << name << std::endl;\r\n\t\t\tif (scheme_images.find(name) != scheme_images.end() ) \r\n\t\t\t{\r\n\t\t\t\tstd::cout << \"Image named \" << name << \" already exists \" << std::endl;\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\r\n\t\t\t\/\/ to do - need height & width\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tlong width = 0;\r\n\t\t\tif ((args != nullptr) && (is_integer(pair_car(args))))\r\n\t\t\t{\r\n\t\t\t\twidth = ivalue(pair_car(args));\r\n\t\t\t} else {\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\r\n\t\t\t\/\/ to do - need height & width\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tlong height = 0;\r\n\t\t\tif ((args != nullptr) && (is_integer(pair_car(args))))\r\n\t\t\t{\r\n\t\t\t\theight = ivalue(pair_car(args));\r\n\t\t\t} else {\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\t\t\t\t\t\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tif (!is_pair(args))\r\n\t\t\t\tgoto bad_args;\r\n\t\t\tpointer image_arg = pair_car(args);\r\n\t\t\tif ( is_pair(image_arg) ) {\r\n\t\t\t\tint channel_size = height * width;\r\n\t\t\t\tint nchannels = list_length(sc, image_arg);\t\t\t\t\r\n\t\t\t\tint channeli = nchannels - 1;\r\n\t\t\t\tUint8 *buf = (Uint8*) SDL_malloc(nchannels * channel_size);\r\n\t\t\t\twhile ((image_arg != nullptr) && (image_arg != sc->NIL))\r\n\t\t\t\t{\t\r\n\t\t\t\t\tif (!is_pair(image_arg))\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (!is_pair(pair_car(image_arg)))\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\r\n\t\t\t\t\tpointer channel_name = pair_car(pair_car(image_arg));\r\n\t\t\t\t\tif (is_symbol(channel_name)) {\r\n\t\t\t\t\t\tstd::cout << \"Channel : \" << symname(channel_name) << std::endl;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpointer channel_data = pair_car(pair_cdr(image_arg));\r\n\t\t\t\t\tif (is_vector(channel_data)) {\r\n\t\t\t\t\t\tchannel_size = ivalue(channel_data);\r\n\t\t\t\t\t\tstd::cout << \"Size : \" << ivalue(channel_data) << \" bytes.\" << std::endl;\r\n\t\t\t\t\t\tfor(Sint32 i = 0; i < ivalue(channel_data); i++) {\r\n\t\t\t\t\t\t\tpointer element = vector_elem(channel_data,i);\r\n\t\t\t\t\t\t\tif (!is_number(element))\r\n\t\t\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\t\tbuf[i*nchannels+channeli] = (Uint8)(rvalue(element) * 255.0);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tchanneli--;\r\n\t\t\t\t\timage_arg = pair_cdr(image_arg);\r\n\t\t\t\t}\r\n\t\t\t\tServiceCheckout<ImageService> images;\r\n\t\t\t\t\/\/ to do -- table of scheme managed images \/ table or opaque type?\r\n\t\t\t\tstd::shared_ptr<Image> scheme_image = images->makeImage(name, buf, width, height, nchannels);\r\n\t\t\t\tSDL_free(buf);\t\t\t\r\n\t\t\t\tauto result = scheme_images.emplace(make_pair(name, scheme_image));\r\n\t\t\t\tif (!result.second) {\r\n\t\t\t\t\tstd::cout << \"image : \" << name << \" insertion failed\" << std::endl;\r\n\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t}\r\n\t\t\t\tconst char* ref = SDL_strdup(name);\r\n\t\t\t\trelease_global_lock();\r\n\t\t\t\treturn mk_opaque(sc, imageTag, (void*) ref, scheme_image_delete);\r\n\t\t\t}\r\n\t\t} \r\n bad_args:\r\n\t\trelease_global_lock();\r\n\t\tstd::cout << \"Bad arguments \" << std::endl;\r\n\t\treturn sc->F;\r\n\t}\r\n\r\n\tpointer image_names(scheme* sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tif(args != sc->NIL)\r\n\t\t{\r\n\t\t\treturn sc->F;\r\n\t\t}\t\t\r\n\t\tServiceCheckout<ImageService> images;\r\n\t\tauto enumerator = images->enumerateImages();\r\n\t\tconst char* name = nullptr;\r\n\t\tpointer result = sc->NIL;\r\n\t\twhile( (name = enumerator()) != nullptr )\r\n\t\t{\r\n\t\t\tresult = cons(sc, mk_string(sc, name), result);\r\n\t\t}\r\n\t\trelease_global_lock();\r\n\t\treturn result;\r\n\t}\r\n\r\n\tvoid register_image_functions(scheme* sc)\r\n\t{\r\n\t\t\/* inline lustration how to define a \"foreign\" function\r\n\t\t implemented in C *\/\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"image-names\"),mk_foreign_func(sc, image_names));\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"add-image\"),mk_foreign_func(sc, add_image_from_scheme));\r\n\t\t\r\n\t}\r\n}\r\n\r\n}\r\n\r\n\r\n<commit_msg>Added image loading from scheme.<commit_after>\r\n#include <vector>\r\n#include <string>\r\n#include <unordered_map>\r\n#include <memory>\r\n#include <iostream>\r\n#include <cctype>\r\n#include <SDL.h>\r\n#include <SDL_opengl.h>\r\n#include <SDL_net.h>\r\n#include <SOIL.h>\r\n#include <physfs.h>\r\n#include <res_path.h>\r\n#include <scheme-defs.h>\r\n#include <scheme-private.h>\r\n#include <scheme.h>\r\n\r\n#include \"hashstring.h\"\r\n#include \"locator.h\"\r\n#include \"servicecounter.h\"\r\n#include \"service.h\"\r\n#include \"servicecheckout.h\"\r\n#include \"scripting.h\"\r\n#include \"tinyscm_if.h\"\r\n#include \"image.h\"\r\n\r\nextern SDL_sem* global_lock;\r\n\r\nextern \"C\" {\r\n\tvoid register_image_functions(scheme* sc);\r\n}\r\n\r\nnamespace venk\r\n{\r\n\r\nconst char *ImageService::computeName(const char *name)\r\n{\r\n static char imageName[Image::maxImageNameLength];\r\n\r\n extern size_t strnlen(const char *string, size_t maxlen);\r\n\r\n \/\/ skip '.tga' \r\n int end = 0;\r\n while (isalnum(name[end]))\r\n end++;\r\n strncpy(imageName, name, end);\r\n imageName[end] = '\\0';\r\n return imageName;\r\n}\r\n\r\nbool ImageService::initialise(ImageService* self)\r\n{\r\n\t(void) self;\r\n\tServiceCheckout<ScriptingService> scripting;\r\n\tscheme* sc = scripting->get_scheme();\r\n\tregister_image_functions(sc);\r\n return true;\r\n}\r\n\r\nbool ImageService::shutdown(ImageService* self)\r\n{\r\n\tself->imageTable.clear();\r\n return true;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::loadImage(const char *filename)\r\n{\r\n\tSDL_assert((filename != nullptr) && (strlen(filename) < Image::maxImageNameLength));\r\n std::shared_ptr<Image> image = std::make_shared<Image>(filename);\r\n\tif (image) {\r\n\t\tconst char *imagename = computeName(filename);\r\n\t\tstd::cerr << \"Loaded image \" << imagename << std::endl;\r\n\t\timageTable.insert(ImageLookupTable_t::value_type(imagename, image));\r\n\t}\r\n return image;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::makeImage(const char* name, const Uint8* mem, int width, int height, int channels)\r\n{\r\n std::shared_ptr<Image> image = std::make_shared<Image>(mem, height, width, channels);\r\n imageTable.insert(ImageLookupTable_t::value_type(name, image));\r\n return image;\r\n}\r\n\r\nstd::shared_ptr<Image> ImageService::getImage(const char *name)\r\n{\r\n const char *imagename = computeName(name);\r\n return std::shared_ptr<Image>(imageTable.find(imagename)->second);\r\n}\r\n\r\nstd::function<const char*()> ImageService::enumerateImages()\r\n{\r\n\tImageLookupTable_t::iterator image_it = imageTable.begin();\r\n\tauto result = [=]() mutable -> const char*\r\n\t{\r\n\t\tif (image_it != imageTable.end()) {\r\n\t\t\tconst char* name = (image_it->first).c_str();\r\n\t\t\t++image_it;\t\t\t\t\r\n\t\t\treturn name;\r\n\t\t}\r\n\t\treturn nullptr;\r\n\t};\r\n\treturn result;\r\n}\r\n\/\/ -------------------- Image methods --------------------\r\n\r\nImage::Image(const Uint8* mem, int width, int height, int channels) : mWidth(width), mHeight(height), mChannels(channels)\r\n{\r\n\tSint64 size = width*height;\r\n\tmPixels = SOIL_load_image_from_memory((const unsigned char *)mem, size, &mWidth, &mHeight, &mChannels, SOIL_LOAD_AUTO);\r\n\treturn;\r\n}\r\n\r\nImage::Image(const std::string& fileName) : mPixels(nullptr)\r\n{\r\n std::string fullFileName = getResourcePath();\r\n fullFileName = fullFileName + \"images\/\" + fileName;\r\n SDL_RWops *rwops = SDL_RWFromFile(fullFileName.c_str(), \"rb\");\r\n if (rwops != nullptr)\r\n {\r\n Sint64 size = SDL_RWsize(rwops);\r\n if (size != -1L)\r\n {\r\n void *buf = SDL_malloc(size);\r\n size_t read = SDL_RWread(rwops, buf, 1, size);\r\n if (read == size)\r\n {\r\n mPixels = SOIL_load_image_from_memory((const unsigned char *)buf, size, &mWidth, &mHeight, &mChannels, SOIL_LOAD_AUTO);\r\n if (mPixels != nullptr)\r\n {\r\n SDL_RWclose(rwops);\r\n return;\r\n }\r\n else\r\n {\r\n std::cerr << \"Creating \" << fileName << \" failed\" << std::endl;\r\n }\r\n }\r\n else\r\n {\r\n std::cerr << \"Reading \" << fileName << \" failed\" << std::endl;\r\n }\r\n SDL_free(buf);\r\n }\r\n else\r\n {\r\n std::cerr << \"Probing \" << fileName << \" failed\" << std::endl;\r\n }\r\n\t\tSDL_RWclose(rwops);\t\t\r\n }\r\n else\r\n {\r\n std::cerr << \"Opening \" << fileName << \" failed\" << std::endl;\r\n }\r\n return;\r\n}\r\n\r\nstd::shared_ptr<SDL_Surface> Image::surface() const\r\n{\r\n#if SDL_BYTEORDER == SDL_BIG_ENDIAN\r\n Uint32 rmask = 0xff000000;\r\n Uint32 gmask = 0x00ff0000;\r\n Uint32 bmask = 0x0000ff00;\r\n Uint32 amask = 0x000000ff;\r\n#else\r\n Uint32 rmask = 0x000000ff;\r\n Uint32 gmask = 0x0000ff00;\r\n Uint32 bmask = 0x00ff0000;\r\n Uint32 amask = 0xff000000;\r\n#endif\r\n\r\n auto surface_deleter = [](SDL_Surface * s)\r\n {\r\n if (s) SDL_FreeSurface(s);\r\n };\r\n std::shared_ptr<SDL_Surface> result(\r\n\t\tSDL_CreateRGBSurfaceFrom(mPixels, mWidth, mHeight, mChannels * 8, mWidth * mChannels,\r\n\t\t\t\t\t\t\t\t rmask, gmask, bmask, amask ),\r\n\t\tsurface_deleter);\r\n return result;\r\n}\r\n\r\nImage::~Image()\r\n{\r\n if (mPixels != nullptr)\r\n SOIL_free_image_data(mPixels);\r\n}\r\n\r\n\/\/ Scheme bindings\r\n\r\nextern \"C\"\r\n{\r\n\tstatic const char* imageTag = \"IMAGE\";\r\n\r\n\t\/* to manage the lifetime of images in scheme *\/\r\n\ttypedef std::unordered_map< std::string, std::shared_ptr<Image> > SchemeImageTable_t;\r\n\tSchemeImageTable_t scheme_images;\r\n\r\n\t\/* this will get called when the scheme garbage collector wants it gone *\/\r\n\tvoid scheme_image_delete(void* ptr)\r\n\t{\r\n\t\tconst char *ref = (const char*) ptr;\r\n\t\tscheme_images.erase(ref);\r\n\t\tSDL_free(ptr);\r\n\t}\r\n\r\n\t\/* add an image in scheme vector form to the image management *\/\r\n\tpointer add_image_from_scheme(scheme *sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tpointer name_arg;\r\n\t\tif( is_string( name_arg = pair_car(args)) )\r\n\t\t{\r\n\t\t\tchar *name;\r\n\t\t\tname = string_value( name_arg );\r\n\t\t\tstd::cout << \"Creating image named \" << name << std::endl;\r\n\t\t\tif (scheme_images.find(name) != scheme_images.end() ) \r\n\t\t\t{\r\n\t\t\t\tstd::cout << \"Image named \" << name << \" already exists \" << std::endl;\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\r\n\t\t\t\/\/ to do - need height & width\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tlong width = 0;\r\n\t\t\tif ((args != nullptr) && (is_integer(pair_car(args))))\r\n\t\t\t{\r\n\t\t\t\twidth = ivalue(pair_car(args));\r\n\t\t\t} else {\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\r\n\t\t\t\/\/ to do - need height & width\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tlong height = 0;\r\n\t\t\tif ((args != nullptr) && (is_integer(pair_car(args))))\r\n\t\t\t{\r\n\t\t\t\theight = ivalue(pair_car(args));\r\n\t\t\t} else {\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\t\t\t\t\t\r\n\t\t\targs = pair_cdr(args);\r\n\t\t\tif (!is_pair(args))\r\n\t\t\t\tgoto bad_args;\r\n\t\t\tpointer image_arg = pair_car(args);\r\n\t\t\tif ( is_pair(image_arg) ) {\r\n\t\t\t\tint channel_size = height * width;\r\n\t\t\t\tint nchannels = list_length(sc, image_arg);\t\t\t\t\r\n\t\t\t\tint channeli = nchannels - 1;\r\n\t\t\t\tUint8 *buf = (Uint8*) SDL_malloc(nchannels * channel_size);\r\n\t\t\t\twhile ((image_arg != nullptr) && (image_arg != sc->NIL))\r\n\t\t\t\t{\t\r\n\t\t\t\t\tif (!is_pair(image_arg))\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (!is_pair(pair_car(image_arg)))\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\r\n\t\t\t\t\tpointer channel_name = pair_car(pair_car(image_arg));\r\n\t\t\t\t\tif (is_symbol(channel_name)) {\r\n\t\t\t\t\t\tstd::cout << \"Channel : \" << symname(channel_name) << std::endl;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpointer channel_data = pair_car(pair_cdr(image_arg));\r\n\t\t\t\t\tif (is_vector(channel_data)) {\r\n\t\t\t\t\t\tchannel_size = ivalue(channel_data);\r\n\t\t\t\t\t\tstd::cout << \"Size : \" << ivalue(channel_data) << \" bytes.\" << std::endl;\r\n\t\t\t\t\t\tfor(Sint32 i = 0; i < ivalue(channel_data); i++) {\r\n\t\t\t\t\t\t\tpointer element = vector_elem(channel_data,i);\r\n\t\t\t\t\t\t\tif (!is_number(element))\r\n\t\t\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t\t\tbuf[i*nchannels+channeli] = (Uint8)(rvalue(element) * 255.0);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tchanneli--;\r\n\t\t\t\t\timage_arg = pair_cdr(image_arg);\r\n\t\t\t\t}\r\n\t\t\t\tServiceCheckout<ImageService> images;\r\n\t\t\t\t\/\/ to do -- table of scheme managed images \/ table or opaque type?\r\n\t\t\t\tstd::shared_ptr<Image> scheme_image = images->makeImage(name, buf, width, height, nchannels);\r\n\t\t\t\tSDL_free(buf);\t\t\t\r\n\t\t\t\tauto result = scheme_images.emplace(make_pair(name, scheme_image));\r\n\t\t\t\tif (!result.second) {\r\n\t\t\t\t\tstd::cout << \"image : \" << name << \" insertion failed\" << std::endl;\r\n\t\t\t\t\tgoto bad_args;\r\n\t\t\t\t}\r\n\t\t\t\tconst char* ref = SDL_strdup(name);\r\n\t\t\t\trelease_global_lock();\r\n\t\t\t\treturn mk_opaque(sc, imageTag, (void*) ref, scheme_image_delete);\r\n\t\t\t}\r\n\t\t} \r\n bad_args:\r\n\t\trelease_global_lock();\r\n\t\tstd::cout << \"Bad arguments \" << std::endl;\r\n\t\treturn sc->F;\r\n\t}\r\n\r\n\tpointer image_names(scheme* sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tif(args != sc->NIL)\r\n\t\t{\r\n\t\t\trelease_global_lock();\r\n\t\t\treturn sc->F;\r\n\t\t}\t\t\r\n\t\tServiceCheckout<ImageService> images;\r\n\t\tauto enumerator = images->enumerateImages();\r\n\t\tconst char* name = nullptr;\r\n\t\tpointer result = sc->NIL;\r\n\t\twhile( (name = enumerator()) != nullptr )\r\n\t\t{\r\n\t\t\tresult = cons(sc, mk_string(sc, name), result);\r\n\t\t}\r\n\t\trelease_global_lock();\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpointer image_file_names(scheme* sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tif(args != sc->NIL)\r\n\t\t{\r\n\t\t\trelease_global_lock();\r\n\t\t\treturn sc->F;\r\n\t\t}\r\n\t\tpointer result = sc->NIL;\t\t\r\n\t\tchar** flist = PHYSFS_enumerateFiles(\"images\");\r\n\t\tfor(char** i = flist; *i != nullptr; i++) {\r\n\t\t\tresult = cons(sc, mk_string(sc, *i), result);\r\n\t\t}\r\n\t\tPHYSFS_freeList(flist);\t\t\t\t\r\n\t\trelease_global_lock();\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpointer load_image(scheme* sc, pointer args)\r\n\t{\r\n\t\thold_global_lock();\r\n\t\tif (is_string(pair_car(args))) {\r\n\t\t\tServiceCheckout<ImageService> images;\r\n\t\t\tchar *name = string_value(pair_car(args));\r\n\t\t\tstd::shared_ptr<Image> image = images->loadImage(name);\r\n\t\t\tauto result = scheme_images.insert(make_pair(name, image));\r\n\t\t\tif (!result.second) {\r\n\t\t\t\tstd::cout << \"image : \" << name << \" loading failed\" << std::endl;\r\n\t\t\t\tgoto bad_args;\r\n\t\t\t}\t\t\t\r\n\t\t\tconst char* ref = SDL_strdup(name);\t\t\t\r\n\t\t\trelease_global_lock();\r\n\t\t\treturn mk_opaque(sc, imageTag, (void*) ref, scheme_image_delete);\r\n\t\t}\r\n bad_args:\r\n\t\trelease_global_lock();\r\n\t\treturn sc->F;\r\n\t}\r\n\r\n\tvoid register_image_functions(scheme* sc)\r\n\t{\r\n\t\t\/* inline lustration how to define a \"foreign\" function\r\n\t\t implemented in C *\/\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"image-names\"),mk_foreign_func(sc, image_names));\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"image-file-names\"),mk_foreign_func(sc, image_file_names));\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"load-image\"),mk_foreign_func(sc, load_image));\t\t\r\n\t\tscheme_define(sc,sc->global_env,mk_symbol(sc,\"add-image\"),mk_foreign_func(sc, add_image_from_scheme));\r\n\t\t\r\n\t}\r\n}\r\n\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"indexer\/feature_meta.hpp\"\n\nnamespace feature\n{\nstring Metadata::GetWikiURL() const\n{\n string value = this->Get(FMD_WIKIPEDIA);\n string::size_type i = value.find(':');\n if (i == string::npos)\n return string();\n return \"https:\/\/\" + value.substr(0, i) + \".wikipedia.org\/wiki\/\" + value.substr(i + 1);\n}\n\nchar hex_to_dec(char ch)\n{\n if (ch >= '0' && ch <= '9')\n return ch - '0';\n if (ch >= 'a')\n ch -= 32;\n if (ch >= 'A' && ch <= 'F')\n return ch - 'A' + 10;\n return -1;\n}\n\nstring UriDecode(string const & sSrc)\n{\n \/\/ This code was slightly modified from\n \/\/ http:\/\/www.codeguru.com\/cpp\/cpp\/string\/conversions\/article.php\/c12759\n \/\/\n \/\/ Note from RFC1630: \"Sequences which start with a percent\n \/\/ sign but are not followed by two hexadecimal characters\n \/\/ (0-9, A-F) are reserved for future extension\"\n\n const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();\n const string::size_type SRC_LEN = sSrc.length();\n const unsigned char * const SRC_END = pSrc + SRC_LEN;\n \/\/ last decodable '%'\n const unsigned char * const SRC_LAST_DEC = SRC_END - 2;\n\n char * const pStart = new char[SRC_LEN];\n char * pEnd = pStart;\n\n while (pSrc < SRC_LAST_DEC)\n {\n if (*pSrc == '%')\n {\n char dec1 = hex_to_dec(*(pSrc + 1));\n char dec2 = hex_to_dec(*(pSrc + 2));\n if (-1 != dec1 && -1 != dec2)\n {\n *pEnd++ = (dec1 << 4) + dec2;\n pSrc += 2;\n }\n }\n else if (*pSrc == '_')\n *pEnd++ = ' ';\n else\n *pEnd++ = *pSrc;\n pSrc++;\n }\n\n \/\/ the last 2- chars\n while (pSrc < SRC_END)\n *pEnd++ = *pSrc++;\n\n string sResult(pStart, pEnd);\n delete [] pStart;\n return sResult;\n}\n\nstring Metadata::GetWikiTitle() const\n{\n string value = this->Get(FMD_WIKIPEDIA);\n return UriDecode(value);\n}\n} \/\/ namespace feature\n<commit_msg>[metadata] Review fixes<commit_after>#include \"indexer\/feature_meta.hpp\"\n\nnamespace feature\n{\nstring Metadata::GetWikiURL() const\n{\n string value = this->Get(FMD_WIKIPEDIA);\n string::size_type i = value.find(':');\n if (i == string::npos)\n return string();\n return \"https:\/\/\" + value.substr(0, i) + \".wikipedia.org\/wiki\/\" + value.substr(i + 1);\n}\n\nnamespace\n{\nchar HexToDec(char ch)\n{\n if (ch >= '0' && ch <= '9')\n return ch - '0';\n if (ch >= 'a')\n ch -= 'a' - 'A';\n if (ch >= 'A' && ch <= 'F')\n return ch - 'A' + 10;\n return -1;\n}\n\nstring UriDecode(string const & sSrc)\n{\n \/\/ This code was slightly modified from\n \/\/ http:\/\/www.codeguru.com\/cpp\/cpp\/string\/conversions\/article.php\/c12759\n \/\/\n \/\/ Note from RFC1630: \"Sequences which start with a percent\n \/\/ sign but are not followed by two hexadecimal characters\n \/\/ (0-9, A-F) are reserved for future extension\"\n\n unsigned char const * pSrc = (unsigned char const *)sSrc.c_str();\n string::size_type const srcLen = sSrc.length();\n unsigned char const * const srcEnd = pSrc + srcLen;\n \/\/ last decodable '%'\n unsigned char const * const srcLastDec = srcEnd - 2;\n\n char * const pStart = new char[srcLen];\n char * pEnd = pStart;\n\n while (pSrc < srcEnd)\n {\n if (*pSrc == '%')\n {\n if (pSrc < srcLastDec)\n {\n char dec1 = HexToDec(*(pSrc + 1));\n char dec2 = HexToDec(*(pSrc + 2));\n if (-1 != dec1 && -1 != dec2)\n {\n *pEnd++ = (dec1 << 4) + dec2;\n pSrc += 3;\n continue;\n }\n }\n }\n\n if (*pSrc == '_')\n *pEnd++ = ' ';\n else\n *pEnd++ = *pSrc;\n pSrc++;\n }\n\n string sResult(pStart, pEnd);\n delete [] pStart;\n return sResult;\n}\n}\n\nstring Metadata::GetWikiTitle() const\n{\n string value = this->Get(FMD_WIKIPEDIA);\n return UriDecode(value);\n}\n} \/\/ namespace feature\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of Poedit (http:\/\/www.poedit.net)\n *\n * Copyright (C) 2000-2013 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <wx\/xrc\/xmlres.h>\n#include <wx\/config.h>\n#include <wx\/listbox.h>\n#include <wx\/stattext.h>\n#include <wx\/intl.h>\n\n#include \"summarydlg.h\"\n#include \"utility.h\"\n\n\nMergeSummaryDialog::MergeSummaryDialog(wxWindow *parent)\n{\n wxXmlResource::Get()->LoadDialog(this, parent, \"summary\");\n\n RestoreWindowState(this, wxDefaultSize, WinState_Size);\n CentreOnParent();\n}\n\n\n\nMergeSummaryDialog::~MergeSummaryDialog()\n{\n SaveWindowState(this, WinState_Size);\n}\n\n\n\nvoid MergeSummaryDialog::TransferTo(const wxArrayString& snew, const wxArrayString& sobsolete)\n{\n wxString sum;\n sum.Printf(_(\"(%i new, %i obsolete)\"), \n snew.GetCount(), sobsolete.GetCount());\n XRCCTRL(*this, \"items_count\", wxStaticText)->SetLabel(sum);\n\n wxListBox *listbox;\n size_t i;\n \n listbox = XRCCTRL(*this, \"new_strings\", wxListBox);\n for (i = 0; i < snew.GetCount(); i++)\n {\n listbox->Append(snew[i]);\n }\n\n listbox = XRCCTRL(*this, \"obsolete_strings\", wxListBox);\n for (i = 0; i < sobsolete.GetCount(); i++)\n {\n listbox->Append(sobsolete[i]);\n }\n}\n<commit_msg>Fix incorrect printf() specifiers.<commit_after>\/*\n * This file is part of Poedit (http:\/\/www.poedit.net)\n *\n * Copyright (C) 2000-2013 Vaclav Slavik\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <wx\/xrc\/xmlres.h>\n#include <wx\/config.h>\n#include <wx\/listbox.h>\n#include <wx\/stattext.h>\n#include <wx\/intl.h>\n\n#include \"summarydlg.h\"\n#include \"utility.h\"\n\n\nMergeSummaryDialog::MergeSummaryDialog(wxWindow *parent)\n{\n wxXmlResource::Get()->LoadDialog(this, parent, \"summary\");\n\n RestoreWindowState(this, wxDefaultSize, WinState_Size);\n CentreOnParent();\n}\n\n\n\nMergeSummaryDialog::~MergeSummaryDialog()\n{\n SaveWindowState(this, WinState_Size);\n}\n\n\n\nvoid MergeSummaryDialog::TransferTo(const wxArrayString& snew, const wxArrayString& sobsolete)\n{\n wxString sum;\n sum.Printf(_(\"(%i new, %i obsolete)\"), \n (int)snew.GetCount(), (int)sobsolete.GetCount());\n XRCCTRL(*this, \"items_count\", wxStaticText)->SetLabel(sum);\n\n wxListBox *listbox;\n size_t i;\n \n listbox = XRCCTRL(*this, \"new_strings\", wxListBox);\n for (i = 0; i < snew.GetCount(); i++)\n {\n listbox->Append(snew[i]);\n }\n\n listbox = XRCCTRL(*this, \"obsolete_strings\", wxListBox);\n for (i = 0; i < sobsolete.GetCount(); i++)\n {\n listbox->Append(sobsolete[i]);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: accmap.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: mib $ $Date: 2002-04-11 13:53:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ACCMAP_HXX\n#define _ACCMAP_HXX\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_ \/\/autogen\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _VIEWSH_HXX\n#include \"viewsh.hxx\"\n#endif\n\nclass Rectangle;\nclass SwFrm;\nclass SwRootFrm;\nclass SwAccessibleContext;\nclass SwAccessibleContextMap_Impl;\nclass SwAccessibleEventList_Impl;\nclass SwAccessibleEventMap_Impl;\nstruct SwAccessibleEvent_Impl;\nclass SwRect;\nclass ViewShell;\n\n#define ACC_STATE_EDITABLE 0x01\n#define ACC_STATE_OPAQUE 0x02\n#define ACC_STATE_CARET 0x80\n\n#define ACC_STATE_MASK 0x7F\n\nclass SwAccessibleMap\n{\n ::vos::OMutex aMutex;\n ::vos::OMutex aEventMutex;\n SwAccessibleContextMap_Impl *pMap;\n SwAccessibleEventList_Impl *pEvents;\n SwAccessibleEventMap_Impl *pEventMap;\n ViewShell *pVSh;\n sal_Int32 nPara;\n sal_Int32 nFootnote;\n sal_Int32 nEndnote;\n\n static void FireEvent( const SwAccessibleEvent_Impl& rEvent );\n void AppendEvent( const SwAccessibleEvent_Impl& rEvent );\n\n void InvalidateCursorPosition(\n const ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible>& rAcc );\n\npublic:\n\n SwAccessibleMap( ViewShell *pSh );\n ~SwAccessibleMap();\n\n ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible> GetDocumentView();\n\n ::vos::ORef < SwAccessibleContext > GetContextImpl(\n const SwFrm *pFrm,\n sal_Bool bCreate = sal_True );\n ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible> GetContext(\n const SwFrm *pFrm,\n sal_Bool bCreate = sal_True );\n\n ViewShell *GetShell() const { return pVSh; }\n const SwRect& GetVisArea() const { return pVSh->VisArea(); }\n\n void RemoveContext( const SwFrm *pFrm );\n\n \/\/ Dispose frame and its children if bRecursive is set\n void Dispose( const SwFrm *pFrm, sal_Bool bRecursive=sal_False );\n\n void InvalidatePosOrSize( const SwFrm *pFrm, const SwRect& rOldFrm );\n\n void InvalidateContent( const SwFrm *pFrm );\n\n void InvalidateCursorPosition( const SwFrm *pFrm );\n\n void SetCursorContext(\n const ::vos::ORef < SwAccessibleContext >& rCursorContext );\n\n \/\/ Invalidate state of whole tree. If an action is open, this call\n \/\/ is processed when the last action ends.\n void InvalidateStates( sal_uInt8 nStates );\n\n void FireEvents();\n};\n\n#endif\n<commit_msg>#95586#: XAccessibleTable<commit_after>\/*************************************************************************\n *\n * $RCSfile: accmap.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: mib $ $Date: 2002-04-17 14:26:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ACCMAP_HXX\n#define _ACCMAP_HXX\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_ \/\/autogen\n#include <vos\/mutex.hxx>\n#endif\n#ifndef _VIEWSH_HXX\n#include \"viewsh.hxx\"\n#endif\n\nclass Rectangle;\nclass SwFrm;\nclass SwRootFrm;\nclass SwAccessibleContext;\nclass SwAccessibleContextMap_Impl;\nclass SwAccessibleEventList_Impl;\nclass SwAccessibleEventMap_Impl;\nstruct SwAccessibleEvent_Impl;\nclass SwRect;\nclass ViewShell;\n\n\/\/ real states for events\n#define ACC_STATE_EDITABLE 0x01\n#define ACC_STATE_OPAQUE 0x02\n\n\/\/ pseudo states for events\n#define ACC_STATE_CARET 0x80\n\n#define ACC_STATE_MASK 0x7F\n\nclass SwAccessibleMap\n{\n ::vos::OMutex maMutex;\n ::vos::OMutex maEventMutex;\n SwAccessibleContextMap_Impl *mpMap;\n SwAccessibleEventList_Impl *mpEvents;\n SwAccessibleEventMap_Impl *mpEventMap;\n ViewShell *mpVSh;\n sal_Int32 mnPara;\n sal_Int32 mnFootnote;\n sal_Int32 mnEndnote;\n\n static void FireEvent( const SwAccessibleEvent_Impl& rEvent );\n void AppendEvent( const SwAccessibleEvent_Impl& rEvent );\n\n void InvalidateCursorPosition(\n const ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible>& rAcc );\n\npublic:\n\n SwAccessibleMap( ViewShell *pSh );\n ~SwAccessibleMap();\n\n ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible> GetDocumentView();\n\n ::vos::ORef < SwAccessibleContext > GetContextImpl(\n const SwFrm *pFrm,\n sal_Bool bCreate = sal_True );\n ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::accessibility::XAccessible> GetContext(\n const SwFrm *pFrm,\n sal_Bool bCreate = sal_True );\n\n ViewShell *GetShell() const { return mpVSh; }\n const SwRect& GetVisArea() const { return mpVSh->VisArea(); }\n\n void RemoveContext( const SwFrm *pFrm );\n\n \/\/ Dispose frame and its children if bRecursive is set\n void Dispose( const SwFrm *pFrm, sal_Bool bRecursive=sal_False );\n\n void InvalidatePosOrSize( const SwFrm *pFrm, const SwRect& rOldFrm );\n\n void InvalidateContent( const SwFrm *pFrm );\n\n void InvalidateCursorPosition( const SwFrm *pFrm );\n\n void SetCursorContext(\n const ::vos::ORef < SwAccessibleContext >& rCursorContext );\n\n \/\/ Invalidate state of whole tree. If an action is open, this call\n \/\/ is processed when the last action ends.\n void InvalidateStates( sal_uInt8 nStates );\n\n void FireEvents();\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: calbck.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2006-02-09 14:53:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/*************************************************************\n#* Service-Klassen\n *************************************************************\/\n\n\/*\n#* Aendert sich ein Attribut in einem Format, so muss diese\n#* Aenderung an alle abhaengigen Formate und ueber sie an\n#* alle betroffenen Nodes propagiert werden. Dabei muss\n#* festgestellt werden, ob die Aenderung einen Effekt haben\n#* kann, oder ob das geaenderte Attribut von dem abhaengigen\n#* Format ueberdefiniert wird (so dass ohnehin der\n#* Attributwert des abhaengigen Formates den geaenderten\n#* Wert verdeckt). Weiterhin kann der betroffene Node\n#* feststellen, ob er von dem geaenderten Attribut Gebrauch\n#* macht (Beispiel: Linienabstand fuer Unterstreichung wurde\n#* geaendert, das Attribut Unterstreichung wurde aber nicht\n#* verwendet). So wird bei Aenderungen der minimale Aufwand\n#* zum Reformatieren erkannt.\n *\/\n#ifndef _CALBCK_HXX\n#define _CALBCK_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n#ifndef _RTTI_HXX\n#include <tools\/rtti.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SwModify;\nclass SwClientIter;\nclass SfxPoolItem;\nclass SvStream;\n\n\/\/ ----------\n\/\/ SwClient\n\/\/ ----------\n\nclass SW_DLLPUBLIC SwClient\n{\n friend class SwModify;\n friend class SwClientIter;\n\n SwClient *pLeft, *pRight; \/\/ fuer die AVL-Sortierung\n BOOL bModifyLocked : 1; \/\/ wird in SwModify::Modify benutzt,\n \/\/ eigentlich ein Member des SwModify\n \/\/ aber aus Platzgruenden hier.\n BOOL bInModify : 1; \/\/ ist in einem Modify. (Debug!!!)\n BOOL bInDocDTOR : 1; \/\/ Doc wird zerstoert, nicht \"abmelden\"\n BOOL bInCache : 1; \/\/ Ist im BorderAttrCache des Layout,\n \/\/ Traegt sich dann im Modify aus!\n BOOL bInSwFntCache : 1; \/\/ Ist im SwFont-Cache der Formatierung\n\nprotected:\n SwModify *pRegisteredIn;\n\n \/\/ single argument ctors shall be explicit.\n explicit SwClient(SwModify *pToRegisterIn);\n\npublic:\n inline SwClient();\n virtual ~SwClient();\n\n virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew);\n const SwModify* GetRegisteredIn() const { return pRegisteredIn; }\n\n \/\/rtti, abgeleitete moegens gleichtun oder nicht. Wenn sie es gleichtun\n \/\/kann ueber die Abhaengigkeitsliste eines Modify typsicher gecastet\n \/\/werden.\n TYPEINFO();\n\n void LockModify() { bModifyLocked = TRUE; }\n void UnlockModify() { bModifyLocked = FALSE; }\n void SetInCache( BOOL bNew ) { bInCache = bNew; }\n void SetInSwFntCache( BOOL bNew ) { bInSwFntCache = bNew; }\n int IsModifyLocked() const { return bModifyLocked; }\n int IsInDocDTOR() const { return bInDocDTOR; }\n int IsInCache() const { return bInCache; }\n int IsInSwFntCache() const { return bInSwFntCache; }\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem& ) const;\n\nprivate:\n SwClient( const SwClient& );\n SwClient &operator=( const SwClient& );\n};\n\ninline SwClient::SwClient() :\n pLeft(0), pRight(0), pRegisteredIn(0)\n{ bModifyLocked = bInModify = bInDocDTOR = bInCache = bInSwFntCache = FALSE; }\n\n\n\/\/ ----------\n\/\/ SwModify\n\/\/ ----------\n\n\/\/ Klasse hat eine doppelt Verkette Liste fuer die Abhaengigen.\n\nclass SW_DLLPUBLIC SwModify: public SwClient\n{\n friend SvStream& operator<<( SvStream& aS, SwModify & );\n\n friend class SwClientIter;\n SwClient* pRoot;\n\n SW_DLLPRIVATE SwClient *_Remove(SwClient *pDepend);\n\npublic:\n SwModify() : pRoot(0) {}\n\n \/\/ single argument ctors shall be explicit.\n explicit SwModify(SwModify *pToRegisterIn );\n virtual ~SwModify();\n\n virtual void Modify( SfxPoolItem *pOldValue, SfxPoolItem *pNewValue );\n void Add(SwClient *pDepend);\n SwClient *Remove(SwClient *pDepend)\n { return bInDocDTOR ? 0 : _Remove( pDepend ); }\n\n const SwClient* GetDepends() const { return pRoot; }\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem& ) const;\n\n void SetInDocDTOR() { bInDocDTOR = TRUE; }\n\n void CheckCaching( const USHORT nWhich );\n\n BOOL IsLastDepend() const\n { return pRoot && !pRoot->pLeft && !pRoot->pRight; }\n\nprivate:\n \/\/ forbidden and not implemented (see @ SwClient).\n SwModify & operator= (const SwModify &);\n\nprotected:\n \/\/ forbidden and not implemented (see @ SwClient),\n \/\/ but GCC >= 3.4 needs an accessible \"T (const T&)\"\n \/\/ to pass a \"T\" as a \"const T&\" argument\n SwModify (const SwModify &);\n};\n\n\/\/ ----------\n\/\/ SwDepend\n\/\/ ----------\n\n\/*\n * Sehr sinnvolle Klasse, wenn ein Objekt von mehreren Objekten\n * abhaengig ist. Diese sollte fuer jede Abhaengigkeit ein Objekt\n * der Klasse SwDepend als Member haben.\n *\/\nclass SwDepend: public SwClient\n{\n SwClient *pToTell;\n\npublic:\n SwDepend() : pToTell(0) {}\n SwDepend(SwClient *pTellHim, SwModify *pDepend);\n\n SwClient* GetToTell() { return pToTell; }\n virtual void Modify( SfxPoolItem *pOldValue, SfxPoolItem *pNewValue );\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem & ) const;\n\nprivate:\n \/\/ forbidden and not implemented (see @ SwClient).\n SwDepend (const SwDepend &);\n SwDepend & operator= (const SwDepend &);\n};\n\n\nclass SW_DLLPUBLIC SwClientIter\n{\n friend SwClient* SwModify::_Remove(SwClient *); \/\/ fuer Ptr-Korrektur\n friend void SwModify::Add(SwClient *); \/\/ nur fuer ASSERT !\n\n SwModify& rRoot;\n SwClient *pAkt, *pDelNext;\n \/\/ fuers Updaten der aller Iteratoren beim Einfuegen\/Loeschen von\n \/\/ Clients, wenn der Iterator gerade draufsteht.\n SwClientIter *pNxtIter;\n\n SwClient* mpWatchClient; \/\/ if set, SwModify::_Remove checks if this client is removed\n\n TypeId aSrchId; \/\/ fuer First\/Next - suche diesen Type\n\npublic:\n SwClientIter( SwModify& );\n ~SwClientIter();\n\n const SwModify& GetModify() const { return rRoot; }\n SwModify& GetModify() { return rRoot; }\n\n#ifndef CFRONT\n SwClient* operator++(int); \/\/ zum Naechsten\n SwClient* operator--(int); \/\/ zum Vorherigen\n#endif\n SwClient* operator++(); \/\/ zum Naechsten\n SwClient* operator--(); \/\/ zum Vorherigen\n\n SwClient* GoStart(); \/\/ zum Anfang\n SwClient* GoEnd(); \/\/ zum Ende\n\n inline SwClient* GoRoot(); \/\/ wieder ab Root (==Start) anfangen\n\n SwClient* operator()() const\n { return pDelNext == pAkt ? pAkt : pDelNext; }\n\n int IsChanged() const { return pDelNext != pAkt; }\n\n SwClient* First( TypeId nType );\n SwClient* Next();\n\n const SwClient* GetWatchClient() const { return mpWatchClient; }\n void SetWatchClient( SwClient* pWatch ) { mpWatchClient = pWatch; }\n};\n\ninline SwClient* SwClientIter::GoRoot() \/\/ wieder ab Root anfangen\n{\n pAkt = rRoot.pRoot;\n return (pDelNext = pAkt);\n}\n\n\n\n#endif\n<commit_msg>INTEGRATION: CWS writercorehandoff (1.2.462); FILE MERGED 2006\/03\/17 07:51:15 tra 1.2.462.4: RESYNC: (1.3-1.4); FILE MERGED 2005\/09\/13 11:15:44 tra 1.2.462.3: RESYNC: (1.2-1.3); FILE MERGED 2005\/06\/07 14:09:40 fme 1.2.462.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005\/06\/06 07:07:21 tra 1.2.462.1: Unnecessary includes removed #i50348#<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: calbck.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-08-14 15:17:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/*************************************************************\n#* Service-Klassen\n *************************************************************\/\n\n\/*\n#* Aendert sich ein Attribut in einem Format, so muss diese\n#* Aenderung an alle abhaengigen Formate und ueber sie an\n#* alle betroffenen Nodes propagiert werden. Dabei muss\n#* festgestellt werden, ob die Aenderung einen Effekt haben\n#* kann, oder ob das geaenderte Attribut von dem abhaengigen\n#* Format ueberdefiniert wird (so dass ohnehin der\n#* Attributwert des abhaengigen Formates den geaenderten\n#* Wert verdeckt). Weiterhin kann der betroffene Node\n#* feststellen, ob er von dem geaenderten Attribut Gebrauch\n#* macht (Beispiel: Linienabstand fuer Unterstreichung wurde\n#* geaendert, das Attribut Unterstreichung wurde aber nicht\n#* verwendet). So wird bei Aenderungen der minimale Aufwand\n#* zum Reformatieren erkannt.\n *\/\n#ifndef _CALBCK_HXX\n#define _CALBCK_HXX\n\n#ifndef _RTTI_HXX\n#include <tools\/rtti.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SwModify;\nclass SwClientIter;\nclass SfxPoolItem;\nclass SvStream;\n\n\/\/ ----------\n\/\/ SwClient\n\/\/ ----------\n\nclass SW_DLLPUBLIC SwClient\n{\n friend class SwModify;\n friend class SwClientIter;\n\n SwClient *pLeft, *pRight; \/\/ fuer die AVL-Sortierung\n BOOL bModifyLocked : 1; \/\/ wird in SwModify::Modify benutzt,\n \/\/ eigentlich ein Member des SwModify\n \/\/ aber aus Platzgruenden hier.\n BOOL bInModify : 1; \/\/ ist in einem Modify. (Debug!!!)\n BOOL bInDocDTOR : 1; \/\/ Doc wird zerstoert, nicht \"abmelden\"\n BOOL bInCache : 1; \/\/ Ist im BorderAttrCache des Layout,\n \/\/ Traegt sich dann im Modify aus!\n BOOL bInSwFntCache : 1; \/\/ Ist im SwFont-Cache der Formatierung\n\nprotected:\n SwModify *pRegisteredIn;\n\n \/\/ single argument ctors shall be explicit.\n explicit SwClient(SwModify *pToRegisterIn);\n\npublic:\n inline SwClient();\n virtual ~SwClient();\n\n virtual void Modify( SfxPoolItem *pOld, SfxPoolItem *pNew);\n const SwModify* GetRegisteredIn() const { return pRegisteredIn; }\n\n \/\/rtti, abgeleitete moegens gleichtun oder nicht. Wenn sie es gleichtun\n \/\/kann ueber die Abhaengigkeitsliste eines Modify typsicher gecastet\n \/\/werden.\n TYPEINFO();\n\n void LockModify() { bModifyLocked = TRUE; }\n void UnlockModify() { bModifyLocked = FALSE; }\n void SetInCache( BOOL bNew ) { bInCache = bNew; }\n void SetInSwFntCache( BOOL bNew ) { bInSwFntCache = bNew; }\n int IsModifyLocked() const { return bModifyLocked; }\n int IsInDocDTOR() const { return bInDocDTOR; }\n int IsInCache() const { return bInCache; }\n int IsInSwFntCache() const { return bInSwFntCache; }\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem& ) const;\n\nprivate:\n SwClient( const SwClient& );\n SwClient &operator=( const SwClient& );\n};\n\ninline SwClient::SwClient() :\n pLeft(0), pRight(0), pRegisteredIn(0)\n{ bModifyLocked = bInModify = bInDocDTOR = bInCache = bInSwFntCache = FALSE; }\n\n\n\/\/ ----------\n\/\/ SwModify\n\/\/ ----------\n\n\/\/ Klasse hat eine doppelt Verkette Liste fuer die Abhaengigen.\n\nclass SW_DLLPUBLIC SwModify: public SwClient\n{\n friend SvStream& operator<<( SvStream& aS, SwModify & );\n\n friend class SwClientIter;\n SwClient* pRoot;\n\n SW_DLLPRIVATE SwClient *_Remove(SwClient *pDepend);\n\npublic:\n SwModify() : pRoot(0) {}\n\n \/\/ single argument ctors shall be explicit.\n explicit SwModify(SwModify *pToRegisterIn );\n virtual ~SwModify();\n\n virtual void Modify( SfxPoolItem *pOldValue, SfxPoolItem *pNewValue );\n void Add(SwClient *pDepend);\n SwClient *Remove(SwClient *pDepend)\n { return bInDocDTOR ? 0 : _Remove( pDepend ); }\n\n const SwClient* GetDepends() const { return pRoot; }\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem& ) const;\n\n void SetInDocDTOR() { bInDocDTOR = TRUE; }\n\n void CheckCaching( const USHORT nWhich );\n\n BOOL IsLastDepend() const\n { return pRoot && !pRoot->pLeft && !pRoot->pRight; }\n\nprivate:\n \/\/ forbidden and not implemented (see @ SwClient).\n SwModify & operator= (const SwModify &);\n\nprotected:\n \/\/ forbidden and not implemented (see @ SwClient),\n \/\/ but GCC >= 3.4 needs an accessible \"T (const T&)\"\n \/\/ to pass a \"T\" as a \"const T&\" argument\n SwModify (const SwModify &);\n};\n\n\/\/ ----------\n\/\/ SwDepend\n\/\/ ----------\n\n\/*\n * Sehr sinnvolle Klasse, wenn ein Objekt von mehreren Objekten\n * abhaengig ist. Diese sollte fuer jede Abhaengigkeit ein Objekt\n * der Klasse SwDepend als Member haben.\n *\/\nclass SwDepend: public SwClient\n{\n SwClient *pToTell;\n\npublic:\n SwDepend() : pToTell(0) {}\n SwDepend(SwClient *pTellHim, SwModify *pDepend);\n\n SwClient* GetToTell() { return pToTell; }\n virtual void Modify( SfxPoolItem *pOldValue, SfxPoolItem *pNewValue );\n\n \/\/ erfrage vom Client Informationen\n virtual BOOL GetInfo( SfxPoolItem & ) const;\n\nprivate:\n \/\/ forbidden and not implemented (see @ SwClient).\n SwDepend (const SwDepend &);\n SwDepend & operator= (const SwDepend &);\n};\n\n\nclass SW_DLLPUBLIC SwClientIter\n{\n friend SwClient* SwModify::_Remove(SwClient *); \/\/ fuer Ptr-Korrektur\n friend void SwModify::Add(SwClient *); \/\/ nur fuer ASSERT !\n\n SwModify& rRoot;\n SwClient *pAkt, *pDelNext;\n \/\/ fuers Updaten der aller Iteratoren beim Einfuegen\/Loeschen von\n \/\/ Clients, wenn der Iterator gerade draufsteht.\n SwClientIter *pNxtIter;\n\n SwClient* mpWatchClient; \/\/ if set, SwModify::_Remove checks if this client is removed\n\n TypeId aSrchId; \/\/ fuer First\/Next - suche diesen Type\n\npublic:\n SwClientIter( SwModify& );\n ~SwClientIter();\n\n const SwModify& GetModify() const { return rRoot; }\n SwModify& GetModify() { return rRoot; }\n\n#ifndef CFRONT\n SwClient* operator++(int); \/\/ zum Naechsten\n SwClient* operator--(int); \/\/ zum Vorherigen\n#endif\n SwClient* operator++(); \/\/ zum Naechsten\n SwClient* operator--(); \/\/ zum Vorherigen\n\n SwClient* GoStart(); \/\/ zum Anfang\n SwClient* GoEnd(); \/\/ zum Ende\n\n inline SwClient* GoRoot(); \/\/ wieder ab Root (==Start) anfangen\n\n SwClient* operator()() const\n { return pDelNext == pAkt ? pAkt : pDelNext; }\n\n int IsChanged() const { return pDelNext != pAkt; }\n\n SwClient* First( TypeId nType );\n SwClient* Next();\n\n const SwClient* GetWatchClient() const { return mpWatchClient; }\n void SetWatchClient( SwClient* pWatch ) { mpWatchClient = pWatch; }\n};\n\ninline SwClient* SwClientIter::GoRoot() \/\/ wieder ab Root anfangen\n{\n pAkt = rRoot.pRoot;\n return (pDelNext = pAkt);\n}\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: flypos.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:47:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _FLYPOS_HXX\n#define _FLYPOS_HXX\n\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\nclass SwCntntNode;\nclass ViewShell;\nclass SwFrmFmt;\nclass SwNodeIndex;\n\n\/\/ Struktur zum Erfragen der akt. freifliegenden Rahmen am Dokument.\nclass SwPosFlyFrm\n{\n const SwFrmFmt* pFrmFmt; \/\/ das FlyFrmFmt\n\/\/ SwPosition* pPos; \/\/ Position in den ContentNode\n SwNodeIndex* pNdIdx; \/\/ es reicht ein Index auf den Node\n UINT32 nOrdNum;\npublic:\n SwPosFlyFrm( const SwNodeIndex& , const SwFrmFmt*, USHORT nArrPos );\n virtual ~SwPosFlyFrm(); \/\/ virtual fuer die Writer (DLL !!)\n\n \/\/ operatoren fuer das Sort-Array\n BOOL operator==( const SwPosFlyFrm& );\n BOOL operator<( const SwPosFlyFrm& );\n\n const SwFrmFmt& GetFmt() const { return *pFrmFmt; }\n const SwNodeIndex& GetNdIndex() const { return *pNdIdx; }\n UINT32 GetOrdNum() const { return nOrdNum; }\n};\n\ntypedef SwPosFlyFrm* SwPosFlyFrmPtr;\nSV_DECL_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr, 0, 40 )\n\n#endif \/\/ _FLYPOS_HXX\n<commit_msg>INTEGRATION: CWS writercorehandoff (1.2.802); FILE MERGED 2005\/09\/13 11:27:13 tra 1.2.802.2: RESYNC: (1.2-1.3); FILE MERGED 2005\/06\/07 14:09:53 fme 1.2.802.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: flypos.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-08-14 15:22:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _FLYPOS_HXX\n#define _FLYPOS_HXX\n\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\nclass SwFrmFmt;\nclass SwNodeIndex;\n\n\/\/ Struktur zum Erfragen der akt. freifliegenden Rahmen am Dokument.\nclass SwPosFlyFrm\n{\n const SwFrmFmt* pFrmFmt; \/\/ das FlyFrmFmt\n\/\/ SwPosition* pPos; \/\/ Position in den ContentNode\n SwNodeIndex* pNdIdx; \/\/ es reicht ein Index auf den Node\n UINT32 nOrdNum;\npublic:\n SwPosFlyFrm( const SwNodeIndex& , const SwFrmFmt*, USHORT nArrPos );\n virtual ~SwPosFlyFrm(); \/\/ virtual fuer die Writer (DLL !!)\n\n \/\/ operatoren fuer das Sort-Array\n BOOL operator==( const SwPosFlyFrm& );\n BOOL operator<( const SwPosFlyFrm& );\n\n const SwFrmFmt& GetFmt() const { return *pFrmFmt; }\n const SwNodeIndex& GetNdIndex() const { return *pNdIdx; }\n UINT32 GetOrdNum() const { return nOrdNum; }\n};\n\ntypedef SwPosFlyFrm* SwPosFlyFrmPtr;\nSV_DECL_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr, 0, 40 )\n\n#endif \/\/ _FLYPOS_HXX\n<|endoftext|>"} {"text":"<commit_before>#include \"taskqueuer.h\"\n\nWARNINGS_DISABLE\n#include <QCoreApplication>\n#include <QEventLoop>\n#include <QVariant>\nWARNINGS_ENABLE\n\n#include \"cmdlinetask.h\"\n\nTaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())\n{\n#ifdef QT_TESTLIB_LIB\n _fakeNextTask = false;\n#endif\n}\n\nTaskQueuer::~TaskQueuer()\n{\n \/\/ Wait up to 1 second to finish any background tasks\n _threadPool->waitForDone(1000);\n \/\/ Wait up to 1 second to delete objects scheduled with ->deleteLater()\n QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);\n}\n\nvoid TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)\n{\n \/\/ Clear the queue first, to avoid starting a queued task\n \/\/ after already clearing the running task(s).\n if(queued)\n {\n while(!_taskQueue.isEmpty())\n {\n CmdlineTask *task = _taskQueue.dequeue();\n if(task)\n {\n task->emitCanceled();\n task->deleteLater();\n }\n }\n emit message(\"Cleared queued tasks.\");\n }\n\n \/\/ Deal with a running backup.\n if(interrupt)\n {\n \/\/ Sending a SIGQUIT will cause the tarsnap binary to\n \/\/ create a checkpoint. Non-tarsnap binaries should be\n \/\/ receive a CmdlineTask::stop() instead of a SIGQUIT.\n if(!_runningTasks.isEmpty())\n _runningTasks.first()->sigquit();\n emit message(\"Interrupting current backup.\");\n }\n\n \/\/ Stop running tasks.\n if(running)\n {\n for(CmdlineTask *task : _runningTasks)\n {\n if(task)\n task->stop();\n }\n emit message(\"Stopped running tasks.\");\n }\n}\n\nvoid TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)\n{\n \/\/ Sanity check.\n Q_ASSERT(task != nullptr);\n\n \/\/ Add to list of backup tasks (if applicable).\n if(isBackup)\n _backupUuidList.append(task->uuid());\n\n \/\/ Add to the queue and trigger starting a new task.\n if(exclusive && !_runningTasks.isEmpty())\n _taskQueue.enqueue(task);\n else\n startTask(task);\n}\n\nvoid TaskQueuer::startTask(CmdlineTask *task)\n{\n \/\/ Ensure that we have a task, or bail.\n if(task == nullptr)\n {\n if(!_taskQueue.isEmpty())\n task = _taskQueue.dequeue();\n else\n return;\n }\n\n \/\/ Set up the task ending.\n connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);\n task->setAutoDelete(false);\n\n \/\/ Record this thread as \"running\", even though it hasn't actually\n \/\/ started yet. QThreadPool::start() is non-blocking, and in fact\n \/\/ explicitly states that a QRunnable can be added to an internal\n \/\/ run queue if it's exceeded QThreadPoll::maxThreadCount().\n \/\/\n \/\/ However, for the purpose of this TaskQueuer, the task should not\n \/\/ be recorded in our _taskQueue (because we've just dequeued()'d it).\n \/\/ The \"strictly correct\" solution would be to add a\n \/\/ _waitingForStart queue, and move items out of that queue when the\n \/\/ relevant CmdlineTask::started signal was emitted. At the moment,\n \/\/ I don't think that step is necessary, but I might need to revisit\n \/\/ that decision later.\n _runningTasks.append(task);\n\n \/\/ Start the task.\n#ifdef QT_TESTLIB_LIB\n if(_fakeNextTask)\n task->fake();\n#endif\n _threadPool->start(task);\n\n \/\/ Update the task numbers.\n bool backupTaskRunning = isBackupTaskRunning();\n emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\nvoid TaskQueuer::dequeueTask()\n{\n \/\/ Get the task.\n CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());\n\n \/\/ Sanity check.\n if(task == nullptr)\n return;\n\n \/\/ Clean up task.\n _runningTasks.removeOne(task);\n _backupUuidList.removeAll(task->uuid());\n task->deleteLater();\n\n \/\/ Start another task.\n if(_runningTasks.isEmpty())\n startTask(nullptr);\n\n \/\/ Update the task numbers.\n bool backupTaskRunning = isBackupTaskRunning();\n emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\nbool TaskQueuer::isBackupTaskRunning()\n{\n if(!_runningTasks.isEmpty() && !_backupUuidList.isEmpty())\n {\n for(CmdlineTask *task : _runningTasks)\n {\n if(task && _backupUuidList.contains(task->uuid()))\n {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid TaskQueuer::getTaskInfo()\n{\n bool backupTaskRunning = isBackupTaskRunning();\n emit taskInfo(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\n#ifdef QT_TESTLIB_LIB\nvoid TaskQueuer::fakeNextTask()\n{\n _fakeNextTask = true;\n}\n\nvoid TaskQueuer::waitUntilIdle()\n{\n while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))\n QCoreApplication::processEvents(QEventLoop::AllEvents, 100);\n}\n#endif\n<commit_msg>TaskQueuer: expand removing a finished task<commit_after>#include \"taskqueuer.h\"\n\nWARNINGS_DISABLE\n#include <QCoreApplication>\n#include <QEventLoop>\n#include <QVariant>\nWARNINGS_ENABLE\n\n#include \"cmdlinetask.h\"\n\nTaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())\n{\n#ifdef QT_TESTLIB_LIB\n _fakeNextTask = false;\n#endif\n}\n\nTaskQueuer::~TaskQueuer()\n{\n \/\/ Wait up to 1 second to finish any background tasks\n _threadPool->waitForDone(1000);\n \/\/ Wait up to 1 second to delete objects scheduled with ->deleteLater()\n QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);\n}\n\nvoid TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)\n{\n \/\/ Clear the queue first, to avoid starting a queued task\n \/\/ after already clearing the running task(s).\n if(queued)\n {\n while(!_taskQueue.isEmpty())\n {\n CmdlineTask *task = _taskQueue.dequeue();\n if(task)\n {\n task->emitCanceled();\n task->deleteLater();\n }\n }\n emit message(\"Cleared queued tasks.\");\n }\n\n \/\/ Deal with a running backup.\n if(interrupt)\n {\n \/\/ Sending a SIGQUIT will cause the tarsnap binary to\n \/\/ create a checkpoint. Non-tarsnap binaries should be\n \/\/ receive a CmdlineTask::stop() instead of a SIGQUIT.\n if(!_runningTasks.isEmpty())\n _runningTasks.first()->sigquit();\n emit message(\"Interrupting current backup.\");\n }\n\n \/\/ Stop running tasks.\n if(running)\n {\n for(CmdlineTask *task : _runningTasks)\n {\n if(task)\n task->stop();\n }\n emit message(\"Stopped running tasks.\");\n }\n}\n\nvoid TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)\n{\n \/\/ Sanity check.\n Q_ASSERT(task != nullptr);\n\n \/\/ Add to list of backup tasks (if applicable).\n if(isBackup)\n _backupUuidList.append(task->uuid());\n\n \/\/ Add to the queue and trigger starting a new task.\n if(exclusive && !_runningTasks.isEmpty())\n _taskQueue.enqueue(task);\n else\n startTask(task);\n}\n\nvoid TaskQueuer::startTask(CmdlineTask *task)\n{\n \/\/ Ensure that we have a task, or bail.\n if(task == nullptr)\n {\n if(!_taskQueue.isEmpty())\n task = _taskQueue.dequeue();\n else\n return;\n }\n\n \/\/ Set up the task ending.\n connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);\n task->setAutoDelete(false);\n\n \/\/ Record this thread as \"running\", even though it hasn't actually\n \/\/ started yet. QThreadPool::start() is non-blocking, and in fact\n \/\/ explicitly states that a QRunnable can be added to an internal\n \/\/ run queue if it's exceeded QThreadPoll::maxThreadCount().\n \/\/\n \/\/ However, for the purpose of this TaskQueuer, the task should not\n \/\/ be recorded in our _taskQueue (because we've just dequeued()'d it).\n \/\/ The \"strictly correct\" solution would be to add a\n \/\/ _waitingForStart queue, and move items out of that queue when the\n \/\/ relevant CmdlineTask::started signal was emitted. At the moment,\n \/\/ I don't think that step is necessary, but I might need to revisit\n \/\/ that decision later.\n _runningTasks.append(task);\n\n \/\/ Start the task.\n#ifdef QT_TESTLIB_LIB\n if(_fakeNextTask)\n task->fake();\n#endif\n _threadPool->start(task);\n\n \/\/ Update the task numbers.\n bool backupTaskRunning = isBackupTaskRunning();\n emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\nvoid TaskQueuer::dequeueTask()\n{\n \/\/ Get the task.\n CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());\n\n \/\/ Sanity check.\n if(task == nullptr)\n return;\n\n \/\/ Clean up task.\n for(CmdlineTask *t : _runningTasks)\n {\n if(t == task)\n {\n _runningTasks.removeOne(t);\n break;\n }\n }\n _backupUuidList.removeAll(task->uuid());\n task->deleteLater();\n\n \/\/ Start another task.\n if(_runningTasks.isEmpty())\n startTask(nullptr);\n\n \/\/ Update the task numbers.\n bool backupTaskRunning = isBackupTaskRunning();\n emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\nbool TaskQueuer::isBackupTaskRunning()\n{\n if(!_runningTasks.isEmpty() && !_backupUuidList.isEmpty())\n {\n for(CmdlineTask *task : _runningTasks)\n {\n if(task && _backupUuidList.contains(task->uuid()))\n {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid TaskQueuer::getTaskInfo()\n{\n bool backupTaskRunning = isBackupTaskRunning();\n emit taskInfo(backupTaskRunning, _runningTasks.count(), _taskQueue.count());\n}\n\n#ifdef QT_TESTLIB_LIB\nvoid TaskQueuer::fakeNextTask()\n{\n _fakeNextTask = true;\n}\n\nvoid TaskQueuer::waitUntilIdle()\n{\n while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))\n QCoreApplication::processEvents(QEventLoop::AllEvents, 100);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2011 Dreamhost\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"common\/armor.h\"\n#include \"config.h\"\n#include \"include\/buffer.h\"\n#include \"include\/encoding.h\"\n\n#include \"gtest\/gtest.h\"\n\nTEST(RoundTrip, SimpleRoundTrip) {\n static const int OUT_LEN = 4096;\n const char * const original = \"abracadabra\";\n const char * const correctly_encoded = \"YWJyYWNhZGFicmE=\";\n char out[OUT_LEN];\n memset(out, 0, sizeof(out));\n int alen = ceph_armor(out, out + OUT_LEN, original, original + strlen(original));\n ASSERT_STREQ(correctly_encoded, out);\n\n char out2[OUT_LEN];\n memset(out2, 0, sizeof(out2));\n ceph_unarmor(out2, out2 + OUT_LEN, out, out + alen);\n ASSERT_STREQ(original, out2);\n}\n\nTEST(RoundTrip, RandomRoundTrips) {\n static const int IN_MAX = 1024;\n static const int OUT_MAX = 4096;\n static const int ITERS = 1000;\n for (int i = 0; i < ITERS; ++i) {\n unsigned int seed = i;\n int in_len = rand_r(&seed) % IN_MAX;\n\n char in[IN_MAX];\n memset(in, 0, sizeof(in));\n for (int j = 0; i < in_len; ++j) {\n in[j] = rand_r(&seed) % 0xff;\n }\n char out[OUT_MAX];\n memset(out, 0, sizeof(out));\n int alen = ceph_armor(out, out + OUT_MAX, in, in + in_len);\n ASSERT_GE(alen, 0);\n\n char decoded[IN_MAX];\n memset(decoded, 0, sizeof(decoded));\n int blen = ceph_unarmor(decoded, decoded + OUT_MAX, out, out + alen);\n ASSERT_GE(blen, 0);\n\n ASSERT_EQ(memcmp(in, decoded, in_len), 0);\n }\n}\n\nTEST(FuzzEncoding, BadDecode1) {\n static const int OUT_LEN = 4096;\n const char * const bad_encoded = \"FAKEBASE64 foo\";\n char out[OUT_LEN];\n memset(out, 0, sizeof(out));\n int alen = ceph_unarmor(out, out + OUT_LEN, bad_encoded, bad_encoded + strlen(bad_encoded));\n ASSERT_LT(alen, 0);\n}\n\nTEST(FuzzEncoding, BadDecode2) {\n string str(\"FAKEBASE64 foo\");\n bool failed = false;\n try {\n bufferlist bl;\n bl.append(str);\n\n bufferlist cl;\n cl.decode_base64(bl);\n cl.hexdump(std::cerr);\n }\n catch (const buffer::error &err) {\n failed = true;\n }\n ASSERT_EQ(failed, true);\n}\n<commit_msg>units: RandomRoundTrips: fix endptr for buffer<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-\n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2011 Dreamhost\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software\n * Foundation. See file COPYING.\n *\n *\/\n\n#include \"common\/armor.h\"\n#include \"config.h\"\n#include \"include\/buffer.h\"\n#include \"include\/encoding.h\"\n\n#include \"gtest\/gtest.h\"\n\nTEST(RoundTrip, SimpleRoundTrip) {\n static const int OUT_LEN = 4096;\n const char * const original = \"abracadabra\";\n const char * const correctly_encoded = \"YWJyYWNhZGFicmE=\";\n char out[OUT_LEN];\n memset(out, 0, sizeof(out));\n int alen = ceph_armor(out, out + OUT_LEN, original, original + strlen(original));\n ASSERT_STREQ(correctly_encoded, out);\n\n char out2[OUT_LEN];\n memset(out2, 0, sizeof(out2));\n ceph_unarmor(out2, out2 + OUT_LEN, out, out + alen);\n ASSERT_STREQ(original, out2);\n}\n\nTEST(RoundTrip, RandomRoundTrips) {\n static const int IN_MAX = 1024;\n static const int OUT_MAX = 4096;\n static const int ITERS = 1000;\n for (int i = 0; i < ITERS; ++i) {\n unsigned int seed = i;\n int in_len = rand_r(&seed) % IN_MAX;\n\n char in[IN_MAX];\n memset(in, 0, sizeof(in));\n for (int j = 0; i < in_len; ++j) {\n in[j] = rand_r(&seed) % 0xff;\n }\n char out[OUT_MAX];\n memset(out, 0, sizeof(out));\n int alen = ceph_armor(out, out + OUT_MAX, in, in + in_len);\n ASSERT_GE(alen, 0);\n\n char decoded[IN_MAX];\n memset(decoded, 0, sizeof(decoded));\n int blen = ceph_unarmor(decoded, decoded + IN_MAX, out, out + alen);\n ASSERT_GE(blen, 0);\n\n ASSERT_EQ(memcmp(in, decoded, in_len), 0);\n }\n}\n\nTEST(FuzzEncoding, BadDecode1) {\n static const int OUT_LEN = 4096;\n const char * const bad_encoded = \"FAKEBASE64 foo\";\n char out[OUT_LEN];\n memset(out, 0, sizeof(out));\n int alen = ceph_unarmor(out, out + OUT_LEN, bad_encoded, bad_encoded + strlen(bad_encoded));\n ASSERT_LT(alen, 0);\n}\n\nTEST(FuzzEncoding, BadDecode2) {\n string str(\"FAKEBASE64 foo\");\n bool failed = false;\n try {\n bufferlist bl;\n bl.append(str);\n\n bufferlist cl;\n cl.decode_base64(bl);\n cl.hexdump(std::cerr);\n }\n catch (const buffer::error &err) {\n failed = true;\n }\n ASSERT_EQ(failed, true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"Model.hpp\"\n\nBOOST_AUTO_TEST_CASE (kill_test) {\n Implementation::Model* model =\n Abstract::makeModel<Implementation::Model>(\n MIN_WIDTH,\n MIN_HEIGHT,\n 0,\n 1\n );\n Abstract::Point coordinates(0, 0);\n model->createNewByCoordinates(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::BACTERIUM);\n model->killByCoordinates(coordinates);\n state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n delete model;\n}\n<commit_msg>Model tests: static function createBaseModel()<commit_after>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"Model.hpp\"\n\nstatic Implementation::Model* createBaseModel() {\n Implementation::Model* model =\n Abstract::makeModel<Implementation::Model>(\n MIN_WIDTH,\n MIN_HEIGHT,\n 0,\n 1\n );\n return model;\n}\n\nBOOST_AUTO_TEST_CASE (kill_test) {\n Implementation::Model* model =\n Abstract::makeModel<Implementation::Model>(\n MIN_WIDTH,\n MIN_HEIGHT,\n 0,\n 1\n );\n Abstract::Point coordinates(0, 0);\n model->createNewByCoordinates(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::BACTERIUM);\n model->killByCoordinates(coordinates);\n state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n delete model;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/include\/yal\/items.h\"\n\n#include <iomanip>\n#include <sstream>\n\n#include \"..\/include\/yal\/entries.h\"\n#include \"..\/include\/yal\/utils.h\"\n\nnamespace\n{\n fmt::BasicWriter<char>& appendZeroIfNeeded(fmt::BasicWriter<char>& stream, int value)\n {\n if (value < 10)\n {\n stream << '0';\n }\n stream << value;\n return stream;\n }\n\n const char* findEnd(const char* begin)\n {\n if (*begin == '}')\n {\n return begin + 1;\n }\n\n const char* end = begin + 1;\n while (*end && *end != '}')\n ++end;\n return end + 1;\n }\n\n std::string getFormat(const char* begin, const char* end)\n {\n std::string format = \"{\";\n format.append(begin, end);\n return format;\n }\n}\n\n#define YAL_FORMAT_VALUE(value) \\\n const char* end = findEnd(begin); \\\n if (begin + 1 != end) \\\n { \\\n formatter.writer().write(getFormat(begin, end), (value)); \\\n } \\\n else \\\n { \\\n formatter.writer() << (value); \\\n } \\\n begin = end;\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::SeverityItem& item)\n{\n using namespace artec::yal;\n\n YAL_FORMAT_VALUE(toString(item.entry.level))\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TextItem& item)\n{\n using namespace artec::yal;\n\n YAL_FORMAT_VALUE(item.entry.text)\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TimezoneItem& item)\n{\n \/\/TODO need to improve performance (localtime is very expensive)\n\n using namespace artec::yal;\n\n const auto time = ClockType::to_time_t(item.entry.time);\n const auto localtime = std::localtime(&time);\n\n std::stringstream buf;\n buf << std::put_time(localtime, \"%z\");\n formatter.writer() << buf.str();\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TimeItem& item)\n{\n using namespace artec::yal;\n\n const auto time = ClockType::to_time_t(item.entry.time);\n const auto upToSecond = ClockType::from_time_t(time);\n const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(item.entry.time - upToSecond).count();\n\n const auto utcTime = toDateTime(item.entry.time);\n\n appendZeroIfNeeded(formatter.writer(), utcTime.hour) << ':';\n appendZeroIfNeeded(formatter.writer(), utcTime.min) << ':';\n appendZeroIfNeeded(formatter.writer(), utcTime.sec) << '.' << microseconds;\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::DateItem& item)\n{\n using namespace artec::yal;\n\n const auto utcTime = toDateTime(item.entry.time);\n\n formatter.writer() << utcTime.year << '-';\n appendZeroIfNeeded(formatter.writer(), utcTime.month + 1) << '-';\n appendZeroIfNeeded(formatter.writer(), utcTime.day);\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::ThreadItem& item)\n{\n using namespace artec::yal;\n\n std::stringstream buf;\n buf << item.entry.thread;\n const auto tid = std::stoul(buf.str());\n\n YAL_FORMAT_VALUE(tid)\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::PlaceInCodeItem& item)\n{\n using namespace artec::yal;\n\n formatter.writer() << item.entry.file << ':' << item.entry.line;\n\n begin = findEnd(begin);\n}\n\n#undef YAL_FORMAT_VALUE\n<commit_msg>replace macro with function<commit_after>#include \"..\/include\/yal\/items.h\"\n\n#include <iomanip>\n#include <sstream>\n\n#include \"..\/include\/yal\/entries.h\"\n#include \"..\/include\/yal\/utils.h\"\n\nnamespace\n{\n fmt::BasicWriter<char>& appendZeroIfNeeded(fmt::BasicWriter<char>& stream, int value)\n {\n if (value < 10)\n {\n stream << '0';\n }\n stream << value;\n return stream;\n }\n\n const char* findEnd(const char* begin)\n {\n if (*begin == '}')\n {\n return begin + 1;\n }\n\n const char* end = begin + 1;\n while (*end && *end != '}')\n {\n ++end;\n }\n\n return end + 1;\n }\n\n std::string getFormat(const char* begin, const char* end)\n {\n std::string format = \"{\";\n format.append(begin, end);\n return format;\n }\n\n template <class T>\n void formatItem(fmt::BasicFormatter<char>& formatter, const char*& begin, const T& value)\n {\n const char* end = findEnd(begin);\n if (begin + 1 != end)\n {\n formatter.writer().write(getFormat(begin, end), (value));\n }\n else\n {\n formatter.writer() << (value);\n }\n begin = end;\n }\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::SeverityItem& item)\n{\n formatItem(formatter, begin, toString(item.entry.level));\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TextItem& item)\n{\n formatItem(formatter, begin, item.entry.text);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TimezoneItem& item)\n{\n \/\/TODO need to improve performance (localtime is very expensive)\n\n const auto time = artec::yal::ClockType::to_time_t(item.entry.time);\n const auto localtime = std::localtime(&time);\n\n std::stringstream buf;\n buf << std::put_time(localtime, \"%z\");\n formatter.writer() << buf.str();\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::TimeItem& item)\n{\n using namespace artec::yal;\n\n const auto time = ClockType::to_time_t(item.entry.time);\n const auto upToSecond = ClockType::from_time_t(time);\n const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(item.entry.time - upToSecond).count();\n\n const auto utcTime = toDateTime(item.entry.time);\n\n appendZeroIfNeeded(formatter.writer(), utcTime.hour) << ':';\n appendZeroIfNeeded(formatter.writer(), utcTime.min) << ':';\n appendZeroIfNeeded(formatter.writer(), utcTime.sec) << '.' << microseconds;\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::DateItem& item)\n{\n const auto utcTime = artec::yal::toDateTime(item.entry.time);\n\n formatter.writer() << utcTime.year << '-';\n appendZeroIfNeeded(formatter.writer(), utcTime.month + 1) << '-';\n appendZeroIfNeeded(formatter.writer(), utcTime.day);\n\n begin = findEnd(begin);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::ThreadItem& item)\n{\n std::stringstream buf;\n buf << item.entry.thread;\n const auto tid = std::stoul(buf.str());\n\n formatItem(formatter, begin, tid);\n}\n\nvoid fmt::format_arg(fmt::BasicFormatter<char>& formatter, const char*& begin, const artec::yal::PlaceInCodeItem& item)\n{\n formatter.writer() << item.entry.file << ':' << item.entry.line;\n begin = findEnd(begin);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <thread>\n#include <set>\n#include <signal.h>\n\n#include <cl\/cl.h>\n#include <ev3\/servo.h>\n\nusing namespace std;\nusing namespace ev3dev;\n\ncl::arg<std::string> port(\n ev3dev::OUTPUT_A,\n cl::name(\"port\"),\n cl::desc(\"Port the motor is attached to.\"));\n\ncl::arg<float> period(\n 4.0f,\n cl::name(\"period\"),\n cl::desc(\"Sine wave period, in s.\"));\ncl::arg<float> amplitude(\n 180.0f,\n cl::name(\"amplitude\"),\n cl::desc(\"Sine wave amplitude.\"));\ncl::boolean square_wave(\n cl::name(\"square-wave\"),\n cl::desc(\"Use a square wave instead of a sine wave.\"));\n\ncl::boolean use_servo(\n cl::name(\"servo\"),\n cl::desc(\"Use the ev3cv::servo class.\"));\n\ncl::group ev3cv_group(\"ev3cv::servo settings\");\ncl::arg<vector3i> K(\n vector3i(5000, 5000, 200),\n cl::name(\"K\"),\n cl::desc(\"PID parameters Kp, Ki, Kd.\"),\n ev3cv_group);\n\ncl::group ev3dev_group(\"ev3dev::motor settings\");\ncl::arg<std::string> regulation_mode(\n \"off\",\n cl::name(\"regulation-mode\"),\n ev3dev_group);\ncl::arg<std::string> stop_mode(\n \"coast\",\n cl::name(\"stop-mode\"),\n ev3dev_group);\ncl::arg<int> pulses_per_second_setpoint(\n 700,\n cl::name(\"pulses-per-second-setpoint\"),\n ev3dev_group);\ncl::arg<int> duty_cycle_setpoint(\n 100,\n cl::name(\"duty-cycle-setpoint\"),\n ev3dev_group);\n\nint setpoint_fn(int ms) {\n float sp = sin(ms*2.0f*pi\/(period*1000.0f));\n if (square_wave)\n sp = sp < 0.0f ? -1.0f : 1.0f;\n return sp*amplitude;\n}\n\n\/\/ Test and benchmark estimate_trajectory.\nint main(int argc, const char **argv) {\n cl::parse(argv[0], argc - 1, argv + 1);\n\n typedef chrono::high_resolution_clock clock;\n chrono::milliseconds T(20);\n \n if (use_servo) {\n \/\/ Use ev3cv::servo.\n servo m(*port);\n m.controller().set_K(K->x, K->y, K->z);\n m.run();\n\n auto t0 = clock::now();\n for (auto t = t0; ; t += T) {\n int ms = chrono::duration_cast<chrono::milliseconds>(t - t0).count();\n m.set_position_setpoint(setpoint_fn(ms));\n this_thread::sleep_until(t);\n }\n } else {\n \/\/ To compare against the stock controller\n motor m(*port);\n m.reset();\n m.set_run_mode(motor::run_mode_position);\n m.set_regulation_mode(regulation_mode);\n m.set_pulses_per_second_setpoint(pulses_per_second_setpoint);\n m.set_duty_cycle_setpoint(duty_cycle_setpoint);\n m.set_stop_mode(stop_mode);\n \n auto t0 = clock::now();\n for (auto t = t0; ; t += T) {\n int ms = chrono::duration_cast<chrono::milliseconds>(t - t0).count();\n m.set_position_setpoint(setpoint_fn(ms));\n m.run();\n this_thread::sleep_until(t);\n }\n }\n return 0;\n}\n\n<commit_msg>Use another motor as input to control the servo<commit_after>#include <thread>\n#include <set>\n#include <signal.h>\n\n#include <cl\/cl.h>\n#include <ev3\/servo.h>\n\nusing namespace std;\nusing namespace ev3dev;\n\ncl::arg<std::string> output_port(\n ev3dev::OUTPUT_A,\n cl::name(\"output-port\"),\n cl::desc(\"Port the motor is attached to.\"));\n\ncl::arg<std::string> input_port(\n ev3dev::OUTPUT_D,\n cl::name(\"input-port\"),\n cl::desc(\"Port the tacho is attached to.\"));\n\ncl::boolean use_servo(\n cl::name(\"servo\"),\n cl::desc(\"Use the ev3cv::servo class.\"));\n\ncl::arg<float> scale(\n 1.0f,\n cl::name(\"scale\"),\n cl::desc(\"Relative scale of the motion between the input and output.\"));\n\ncl::group ev3cv_group(\"ev3cv::servo settings\");\ncl::arg<vector3i> K(\n vector3i(5000, 5000, 200),\n cl::name(\"K\"),\n cl::desc(\"PID parameters Kp, Ki, Kd.\"),\n ev3cv_group);\n\ncl::group ev3dev_group(\"ev3dev::motor settings\");\ncl::arg<std::string> regulation_mode(\n \"off\",\n cl::name(\"regulation-mode\"),\n ev3dev_group);\ncl::arg<std::string> stop_mode(\n \"hold\",\n cl::name(\"stop-mode\"),\n ev3dev_group);\ncl::arg<int> ramp_up(\n 0,\n cl::name(\"ramp-up\"),\n ev3dev_group);\ncl::arg<int> ramp_down(\n 0,\n cl::name(\"ramp-down\"),\n ev3dev_group);\ncl::arg<int> pulses_per_second_setpoint(\n 700,\n cl::name(\"pulses-per-second-setpoint\"),\n ev3dev_group);\ncl::arg<int> duty_cycle_setpoint(\n 100,\n cl::name(\"duty-cycle-setpoint\"),\n ev3dev_group);\n\n\/\/ Test and benchmark estimate_trajectory.\nint main(int argc, const char **argv) {\n cl::parse(argv[0], argc - 1, argv + 1);\n\n typedef chrono::high_resolution_clock clock;\n chrono::milliseconds T(20);\n \n motor in(*input_port);\n in.reset();\n\n cout << \"Turn the motor connected to port \" << *input_port << \"...\" << endl;\n\n if (use_servo) {\n \/\/ Use ev3cv::servo.\n servo m(*output_port);\n m.controller().set_K(K->x, K->y, K->z);\n m.run();\n\n for (auto t = clock::now(); ; t += T) {\n m.set_position_setpoint(in.position()*scale);\n this_thread::sleep_until(t);\n }\n } else {\n \/\/ Compare against the stock controller\n motor m(*output_port);\n m.reset();\n m.set_run_mode(motor::run_mode_position);\n m.set_regulation_mode(regulation_mode);\n m.set_pulses_per_second_setpoint(pulses_per_second_setpoint);\n m.set_duty_cycle_setpoint(duty_cycle_setpoint);\n m.set_stop_mode(stop_mode);\n m.set_ramp_up(ramp_up);\n m.set_ramp_down(ramp_down);\n \n for (auto t = clock::now(); ; t += T) {\n m.set_position_setpoint(in.position()*scale);\n m.run();\n this_thread::sleep_until(t);\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"include\/types.h\"\n#include \"include\/rados\/librados.hpp\"\n\nusing namespace librados;\n\n#include <iostream>\n\n#include <stdlib.h>\n#include <time.h>\n\nvoid buf_to_hex(const unsigned char *buf, int len, char *str)\n{\n str[0] = '\\0';\n for (int i = 0; i < len; i++) {\n sprintf(&str[i*2], \"%02x\", (int)buf[i]);\n }\n}\n\nclass C_Watch : public WatchCtx {\npublic:\n C_Watch() {}\n void notify(uint8_t opcode, uint64_t ver) {\n cout << \"C_Watch::notify() opcode=\" << (int)opcode << \" ver=\" << ver << std::endl;\n }\n};\n\nvoid testradospp_milestone(void)\n{\n cout << \"*** press enter to continue ***\" << std::endl;\n getchar();\n}\n\nint main(int argc, const char **argv) \n{\n Rados rados;\n if (rados.init(NULL) < 0) {\n cerr << \"couldn't initialize rados!\" << std::endl;\n exit(1);\n }\n\n if (rados.conf_read_file(NULL)) {\n cerr << \"couldn't read configuration file.\" << std::endl;\n exit(1);\n }\n\n if (!rados.conf_set(\"config option that doesn't exist\",\n \"some random value\")) {\n printf(\"error: succeeded in setting nonexistent config option\\n\");\n exit(1);\n }\n if (rados.conf_set(\"log to stderr\", \"2\")) {\n printf(\"error: error setting log_to_stderr\\n\");\n exit(1);\n }\n rados.reopen_log();\n std::string tmp;\n if (rados.conf_get(\"log to stderr\", tmp)) {\n printf(\"error: failed to read log_to_stderr from config\\n\");\n exit(1);\n }\n if (tmp[0] != '2') {\n printf(\"error: new setting for log_to_stderr failed to take effect.\\n\");\n exit(1);\n }\n\n if (rados.connect()) {\n printf(\"error connecting\\n\");\n exit(1);\n }\n\n cout << \"rados_initialize completed\" << std::endl;\n testradospp_milestone();\n\n time_t tm;\n bufferlist bl, bl2, blf;\n char buf[128];\n\n time(&tm);\n snprintf(buf, 128, \"%s\", ctime(&tm));\n bl.append(buf, strlen(buf));\n blf.append(buf, 16);\n\n const char *oid = \"bar\";\n\n IoCtx io_ctx;\n int r = rados.ioctx_create(\"data\", io_ctx);\n cout << \"ioctx_create result = \" << r << std::endl;\n\n r = io_ctx.write(oid, bl, bl.length(), 0);\n uint64_t objver = io_ctx.get_last_version();\n cout << \"io_ctx.write returned \" << r << \" last_ver=\" << objver << std::endl;\n\n uint64_t stat_size;\n time_t stat_mtime;\n r = io_ctx.stat(oid, &stat_size, &stat_mtime);\n cout << \"io_ctx.stat size = \" << stat_size << \" mtime = \" << stat_mtime << std::endl;\n\n r = io_ctx.stat(oid, NULL, NULL);\n cout << \"io_ctx.stat(does_not_exist) = \" << r;\n\n uint64_t handle;\n C_Watch wc;\n r = io_ctx.watch(oid, objver, &handle, &wc);\n cout << \"io_ctx.watch returned \" << r << std::endl;\n\n testradospp_milestone();\n io_ctx.set_notify_timeout(7);\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n testradospp_milestone();\n\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n testradospp_milestone();\n\n r = io_ctx.unwatch(oid, handle);\n cout << \"io_ctx.unwatch returned \" << r << std::endl;\n cout << \"*** press enter to continue ***\" << std::endl;\n testradospp_milestone();\n\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n cout << \"*** press enter to continue ***\" << std::endl;\n testradospp_milestone();\n io_ctx.set_assert_version(objver);\n\n r = io_ctx.write(oid, bl, bl.length() - 1, 0);\n cout << \"io_ctx.write returned \" << r << std::endl;\n\n r = io_ctx.write(oid, bl, bl.length() - 2, 0);\n cout << \"io_ctx.write returned \" << r << std::endl;\n r = io_ctx.write(oid, bl, bl.length() - 3, 0);\n cout << \"rados.write returned \" << r << std::endl;\n r = io_ctx.append(oid, bl, bl.length());\n cout << \"rados.write returned \" << r << std::endl;\n r = io_ctx.write_full(oid, blf);\n cout << \"rados.write_full returned \" << r << std::endl;\n r = io_ctx.read(oid, bl, bl.length(), 0);\n cout << \"rados.read returned \" << r << std::endl;\n r = io_ctx.trunc(oid, 8);\n cout << \"rados.trunc returned \" << r << std::endl;\n r = io_ctx.read(oid, bl, bl.length(), 0);\n cout << \"rados.read returned \" << r << std::endl;\n r = io_ctx.exec(oid, \"crypto\", \"md5\", bl, bl2);\n cout << \"exec returned \" << r << \" buf size=\" << bl2.length() << std::endl;\n const unsigned char *md5 = (const unsigned char *)bl2.c_str();\n char md5_str[bl2.length()*2 + 1];\n buf_to_hex(md5, bl2.length(), md5_str);\n cout << \"md5 result=\" << md5_str << std::endl;\n\n r = io_ctx.exec(oid, \"crypto\", \"sha1\", bl, bl2);\n cout << \"exec returned \" << r << std::endl;\n const unsigned char *sha1 = (const unsigned char *)bl2.c_str();\n char sha1_str[bl2.length()*2 + 1];\n buf_to_hex(sha1, bl2.length(), sha1_str);\n cout << \"sha1 result=\" << sha1_str << std::endl;\n\n r = io_ctx.exec(oid, \"acl\", \"set\", bl, bl2);\n r = io_ctx.exec(oid, \"acl\", \"get\", bl, bl2);\n cout << \"exec returned \" << r << std::endl;\n if (bl2.length() > 0) {\n cout << \"attr=\" << bl2.c_str() << std::endl;\n }\n\n int size = io_ctx.read(oid, bl2, 128, 0);\n cout << \"read result=\" << bl2.c_str() << std::endl;\n cout << \"size=\" << size << std::endl;\n\n const char *oid2 = \"jjj10.rbd\";\n r = io_ctx.exec(oid2, \"rbd\", \"snap_list\", bl, bl2);\n cout << \"snap_list result=\" << r << std::endl;\n r = io_ctx.exec(oid2, \"rbd\", \"snap_add\", bl, bl2);\n cout << \"snap_add result=\" << r << std::endl;\n\n if (r > 0) {\n char *s = bl2.c_str();\n for (int i=0; i<r; i++, s += strlen(s) + 1)\n cout << s << std::endl;\n }\n\n cout << \"iterating over objects...\" << std::endl;\n int num_objs = 0;\n for (ObjectIterator iter = io_ctx.objects_begin();\n iter != io_ctx.objects_end(); ++iter) {\n num_objs++;\n cout << \"'\" << *iter << \"'\" << std::endl;\n }\n cout << \"iterated over \" << num_objs << \" objects.\" << std::endl;\n map<string, bufferlist> attrset;\n io_ctx.getxattrs(oid, attrset);\n\n map<string, bufferlist>::iterator it;\n for (it = attrset.begin(); it != attrset.end(); ++it) {\n cout << \"xattr: \" << it->first << std::endl;\n }\n\n r = io_ctx.remove(oid);\n cout << \"remove result=\" << r << std::endl;\n rados.shutdown();\n\n return 0;\n}\n\n<commit_msg>testradospp: zero terminate before printing strs<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"include\/types.h\"\n#include \"include\/rados\/librados.hpp\"\n\nusing namespace librados;\n\n#include <iostream>\n\n#include <stdlib.h>\n#include <time.h>\n\nvoid buf_to_hex(const unsigned char *buf, int len, char *str)\n{\n str[0] = '\\0';\n for (int i = 0; i < len; i++) {\n sprintf(&str[i*2], \"%02x\", (int)buf[i]);\n }\n}\n\nclass C_Watch : public WatchCtx {\npublic:\n C_Watch() {}\n void notify(uint8_t opcode, uint64_t ver) {\n cout << \"C_Watch::notify() opcode=\" << (int)opcode << \" ver=\" << ver << std::endl;\n }\n};\n\nvoid testradospp_milestone(void)\n{\n cout << \"*** press enter to continue ***\" << std::endl;\n getchar();\n}\n\nint main(int argc, const char **argv) \n{\n Rados rados;\n if (rados.init(NULL) < 0) {\n cerr << \"couldn't initialize rados!\" << std::endl;\n exit(1);\n }\n\n if (rados.conf_read_file(NULL)) {\n cerr << \"couldn't read configuration file.\" << std::endl;\n exit(1);\n }\n\n if (!rados.conf_set(\"config option that doesn't exist\",\n \"some random value\")) {\n printf(\"error: succeeded in setting nonexistent config option\\n\");\n exit(1);\n }\n if (rados.conf_set(\"log to stderr\", \"2\")) {\n printf(\"error: error setting log_to_stderr\\n\");\n exit(1);\n }\n rados.reopen_log();\n std::string tmp;\n if (rados.conf_get(\"log to stderr\", tmp)) {\n printf(\"error: failed to read log_to_stderr from config\\n\");\n exit(1);\n }\n if (tmp[0] != '2') {\n printf(\"error: new setting for log_to_stderr failed to take effect.\\n\");\n exit(1);\n }\n\n if (rados.connect()) {\n printf(\"error connecting\\n\");\n exit(1);\n }\n\n cout << \"rados_initialize completed\" << std::endl;\n testradospp_milestone();\n\n time_t tm;\n bufferlist bl, bl2, blf;\n char buf[128];\n\n time(&tm);\n snprintf(buf, 128, \"%s\", ctime(&tm));\n bl.append(buf, strlen(buf));\n blf.append(buf, 16);\n\n const char *oid = \"bar\";\n\n IoCtx io_ctx;\n int r = rados.ioctx_create(\"data\", io_ctx);\n cout << \"ioctx_create result = \" << r << std::endl;\n\n r = io_ctx.write(oid, bl, bl.length(), 0);\n uint64_t objver = io_ctx.get_last_version();\n cout << \"io_ctx.write returned \" << r << \" last_ver=\" << objver << std::endl;\n\n uint64_t stat_size;\n time_t stat_mtime;\n r = io_ctx.stat(oid, &stat_size, &stat_mtime);\n cout << \"io_ctx.stat size = \" << stat_size << \" mtime = \" << stat_mtime << std::endl;\n\n r = io_ctx.stat(oid, NULL, NULL);\n cout << \"io_ctx.stat(does_not_exist) = \" << r;\n\n uint64_t handle;\n C_Watch wc;\n r = io_ctx.watch(oid, objver, &handle, &wc);\n cout << \"io_ctx.watch returned \" << r << std::endl;\n\n testradospp_milestone();\n io_ctx.set_notify_timeout(7);\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n testradospp_milestone();\n\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n testradospp_milestone();\n\n r = io_ctx.unwatch(oid, handle);\n cout << \"io_ctx.unwatch returned \" << r << std::endl;\n cout << \"*** press enter to continue ***\" << std::endl;\n testradospp_milestone();\n\n r = io_ctx.notify(oid, objver);\n cout << \"io_ctx.notify returned \" << r << std::endl;\n cout << \"*** press enter to continue ***\" << std::endl;\n testradospp_milestone();\n io_ctx.set_assert_version(objver);\n\n r = io_ctx.write(oid, bl, bl.length() - 1, 0);\n cout << \"io_ctx.write returned \" << r << std::endl;\n\n r = io_ctx.write(oid, bl, bl.length() - 2, 0);\n cout << \"io_ctx.write returned \" << r << std::endl;\n r = io_ctx.write(oid, bl, bl.length() - 3, 0);\n cout << \"rados.write returned \" << r << std::endl;\n r = io_ctx.append(oid, bl, bl.length());\n cout << \"rados.write returned \" << r << std::endl;\n r = io_ctx.write_full(oid, blf);\n cout << \"rados.write_full returned \" << r << std::endl;\n r = io_ctx.read(oid, bl, bl.length(), 0);\n cout << \"rados.read returned \" << r << std::endl;\n r = io_ctx.trunc(oid, 8);\n cout << \"rados.trunc returned \" << r << std::endl;\n r = io_ctx.read(oid, bl, bl.length(), 0);\n cout << \"rados.read returned \" << r << std::endl;\n r = io_ctx.exec(oid, \"crypto\", \"md5\", bl, bl2);\n cout << \"exec returned \" << r << \" buf size=\" << bl2.length() << std::endl;\n const unsigned char *md5 = (const unsigned char *)bl2.c_str();\n char md5_str[bl2.length()*2 + 1];\n buf_to_hex(md5, bl2.length(), md5_str);\n cout << \"md5 result=\" << md5_str << std::endl;\n\n r = io_ctx.exec(oid, \"crypto\", \"sha1\", bl, bl2);\n cout << \"exec returned \" << r << std::endl;\n const unsigned char *sha1 = (const unsigned char *)bl2.c_str();\n char sha1_str[bl2.length()*2 + 1];\n buf_to_hex(sha1, bl2.length(), sha1_str);\n cout << \"sha1 result=\" << sha1_str << std::endl;\n\n r = io_ctx.exec(oid, \"acl\", \"set\", bl, bl2);\n r = io_ctx.exec(oid, \"acl\", \"get\", bl, bl2);\n cout << \"exec returned \" << r << std::endl;\n if (bl2.length() > 0) {\n cout << \"attr=\" << bl2.c_str() << std::endl;\n }\n\n int size = io_ctx.read(oid, bl2, 128, 0);\n if (size <= 0) {\n cout << \"failed to read oid \" << oid << \".\" << std::endl;\n exit(1);\n }\n if (size > 4096) {\n cout << \"read too many bytes from oid \" << oid << \".\" << std::endl;\n exit(1);\n }\n char rbuf[size + 1];\n memcpy(rbuf, bl2.c_str(), size);\n rbuf[size] = '\\0';\n cout << \"read result='\" << rbuf << \"'\" << std::endl;\n cout << \"size=\" << size << std::endl;\n\n const char *oid2 = \"jjj10.rbd\";\n r = io_ctx.exec(oid2, \"rbd\", \"snap_list\", bl, bl2);\n cout << \"snap_list result=\" << r << std::endl;\n r = io_ctx.exec(oid2, \"rbd\", \"snap_add\", bl, bl2);\n cout << \"snap_add result=\" << r << std::endl;\n\n if (r > 0) {\n char *s = bl2.c_str();\n for (int i=0; i<r; i++, s += strlen(s) + 1)\n cout << s << std::endl;\n }\n\n cout << \"iterating over objects...\" << std::endl;\n int num_objs = 0;\n for (ObjectIterator iter = io_ctx.objects_begin();\n iter != io_ctx.objects_end(); ++iter) {\n num_objs++;\n cout << \"'\" << *iter << \"'\" << std::endl;\n }\n cout << \"iterated over \" << num_objs << \" objects.\" << std::endl;\n map<string, bufferlist> attrset;\n io_ctx.getxattrs(oid, attrset);\n\n map<string, bufferlist>::iterator it;\n for (it = attrset.begin(); it != attrset.end(); ++it) {\n cout << \"xattr: \" << it->first << std::endl;\n }\n\n r = io_ctx.remove(oid);\n cout << \"remove result=\" << r << std::endl;\n rados.shutdown();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\nnamespace date {};\nusing namespace date;\n\n#include <sstream>\n#include <chrono>\n#include <date\/date.h> \/\/ This file is to allow std::chrono types to be output to a stream\n#include <thread>\n#include \"connector_test.hpp\"\n\n\nusing namespace std;\nusing namespace std::chrono;\n\nnamespace mtconnect {\n namespace test {\n \/\/ Registers the fixture into the 'registry'\n CPPUNIT_TEST_SUITE_REGISTRATION(ConnectorTest);\n \n void ConnectorTest::setUp()\n {\n CPPUNIT_ASSERT(!create_listener(m_server, 0, \"127.0.0.1\"));\n m_port = m_server->get_listening_port();\n m_connector.reset(new TestConnector(\"127.0.0.1\", m_port));\n m_connector->m_disconnected = true;\n }\n \n \n void ConnectorTest::thread()\n {\n m_connector->connect();\n }\n \n \n void ConnectorTest::tearDown()\n {\n m_server.reset();\n m_serverSocket.reset();\n stop();\n wait();\n m_connector.reset();\n }\n \n \n void ConnectorTest::testConnection()\n {\n CPPUNIT_ASSERT(m_connector->m_disconnected);\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(100ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testDataCapture()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n string command(\"Hello Connector\\n\");\n CPPUNIT_ASSERT((size_t) m_serverSocket->write(command.c_str(),\n command.length()) == command.length());\n this_thread::sleep_for(1000ms);\n \n \/\/ \\n is stripped from the posted data.\n CPPUNIT_ASSERT_EQUAL(command.substr(0, command.length() - 1), m_connector->m_data);\n }\n \n \n void ConnectorTest::testDisconnect()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(1000ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n m_serverSocket.reset();\n this_thread::sleep_for(1000ms);\n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testProtocolCommand()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n const auto cmd = \"* Hello Connector\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(cmd), (size_t) m_serverSocket->write(cmd, strlen(cmd)));\n this_thread::sleep_for(1000ms);\n \n \/\/ \\n is stripped from the posted data.\n CPPUNIT_ASSERT(strncmp(cmd, m_connector->m_command.c_str(), strlen(cmd) - 1) == 0);\n }\n \n \n void ConnectorTest::testHeartbeat()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n \/\/ Receive initial heartbeat request \"* PING\\n\"\n char buf[1024] = {0};\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 5000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(strcmp(buf, \"* PING\\n\") == 0);\n \n \/\/ Respond to the heartbeat of 1 second\n const auto pong = \"* PONG 1000\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(pong), (size_t) m_serverSocket->write(pong, strlen(pong)));\n this_thread::sleep_for(1000ms);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{1000}, m_connector->heartbeatFrequency());\n }\n \n \n void ConnectorTest::testHeartbeatPong()\n {\n testHeartbeat();\n \n auto last_heartbeat = system_clock::now();\n \n \/\/ Test to make sure we can send and receive 5 heartbeats\n for (int i = 0; i < 5; i++)\n {\n \/\/ Receive initial heartbeat request \"* PING\\n\"\n \n char buf[1024] = {0};\n CPPUNIT_ASSERT(m_serverSocket->read(buf, 1023, 1100) > 0);\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n auto now = system_clock::now();\n CPPUNIT_ASSERT(now - last_heartbeat < 2000ms);\n last_heartbeat = now;\n \n \/\/ Respond to the heartbeat of 1 second\n const auto pong = \"* PONG 1000\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(pong), (size_t) m_serverSocket->write(pong, strlen(pong)));\n this_thread::sleep_for(10ms);\n \n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n }\n }\n \n \n void ConnectorTest::testHeartbeatTimeout()\n {\n testHeartbeat();\n this_thread::sleep_for(2100ms);\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testLegacyTimeout()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n char buf[1024] = {0};\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 5000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n \/\/ Write some data...\n const auto cmd = \"* Hello Connector\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(cmd), (size_t) m_serverSocket->write(cmd, strlen(cmd)));\n \n \/\/ No pings, but timeout after 5 seconds of silence\n this_thread::sleep_for(11000ms);\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testParseBuffer()\n {\n \/\/ Test data fragmentation\n m_connector->pushData(\"Hello\");\n CPPUNIT_ASSERT_EQUAL((string) \"\", m_connector->m_data);\n \n m_connector->pushData(\" There\\n\");\n CPPUNIT_ASSERT_EQUAL((string) \"Hello There\", m_connector->m_data);\n m_connector->m_data.clear();\n \n m_connector->pushData(\"Hello\");\n CPPUNIT_ASSERT_EQUAL((string) \"\", m_connector->m_data);\n \n m_connector->pushData(\" There\\nAnd \");\n CPPUNIT_ASSERT_EQUAL((string) \"Hello There\", m_connector->m_data);\n \n m_connector->pushData(\"Again\\nXXX\");\n CPPUNIT_ASSERT_EQUAL((string) \"And Again\", m_connector->m_data);\n }\n \n \n void ConnectorTest::testParseBufferFraming()\n {\n m_connector->m_list.clear();\n m_connector->pushData(\"first\\nseco\");\n m_connector->pushData(\"nd\\nthird\\nfourth\\nfifth\");\n CPPUNIT_ASSERT_EQUAL((size_t) 4, m_connector->m_list.size());\n CPPUNIT_ASSERT_EQUAL((string) \"first\", m_connector->m_list[0]);\n CPPUNIT_ASSERT_EQUAL((string) \"second\", m_connector->m_list[1]);\n CPPUNIT_ASSERT_EQUAL((string) \"third\", m_connector->m_list[2]);\n CPPUNIT_ASSERT_EQUAL((string) \"fourth\", m_connector->m_list[3]);\n }\n \n \n void ConnectorTest::testSendCommand()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n \/\/ Receive initial heartbeat request \"* PING\\n\"\n char buf[1024];\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 1000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n m_connector->sendCommand(\"Hello There;\");\n \n CPPUNIT_ASSERT_EQUAL(15L, m_serverSocket->read(buf, 1023, 1000));\n buf[15] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* Hello There;\\n\"));\n }\n \n \n void ConnectorTest::testIPV6Connection()\n {\n#if !defined(WIN32) || (NTDDI_VERSION >= NTDDI_VISTA)\n m_connector.reset();\n \n CPPUNIT_ASSERT(!create_listener(m_server, 0, \"::1\"));\n m_port = m_server->get_listening_port();\n m_connector.reset(new TestConnector(\"::1\", m_port));\n m_connector->m_disconnected = true;\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(100ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n#endif\n }\n \n \n void ConnectorTest::testStartHeartbeats()\n {\n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n string line = \"* PONG \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONK \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG FLAB\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG 123\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{123}, m_connector->heartbeatFrequency());\n \n m_connector->resetHeartbeats();\n \n line = \"* PONG 456 \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{456}, m_connector->heartbeatFrequency());\n \n line = \"* PONG 323\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{323}, m_connector->heartbeatFrequency());\n }\n }\n}\n<commit_msg>Retry recv on timeout.<commit_after>\/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\nnamespace date {};\nusing namespace date;\n\n#include <sstream>\n#include <chrono>\n#include <date\/date.h> \/\/ This file is to allow std::chrono types to be output to a stream\n#include <thread>\n#include \"connector_test.hpp\"\n\n\nusing namespace std;\nusing namespace std::chrono;\n\nnamespace mtconnect {\n namespace test {\n \/\/ Registers the fixture into the 'registry'\n CPPUNIT_TEST_SUITE_REGISTRATION(ConnectorTest);\n \n void ConnectorTest::setUp()\n {\n CPPUNIT_ASSERT(!create_listener(m_server, 0, \"127.0.0.1\"));\n m_port = m_server->get_listening_port();\n m_connector.reset(new TestConnector(\"127.0.0.1\", m_port));\n m_connector->m_disconnected = true;\n }\n \n \n void ConnectorTest::thread()\n {\n m_connector->connect();\n }\n \n \n void ConnectorTest::tearDown()\n {\n m_server.reset();\n m_serverSocket.reset();\n stop();\n wait();\n m_connector.reset();\n }\n \n \n void ConnectorTest::testConnection()\n {\n CPPUNIT_ASSERT(m_connector->m_disconnected);\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(100ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testDataCapture()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n string command(\"Hello Connector\\n\");\n CPPUNIT_ASSERT((size_t) m_serverSocket->write(command.c_str(),\n command.length()) == command.length());\n this_thread::sleep_for(1000ms);\n \n \/\/ \\n is stripped from the posted data.\n CPPUNIT_ASSERT_EQUAL(command.substr(0, command.length() - 1), m_connector->m_data);\n }\n \n \n void ConnectorTest::testDisconnect()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(1000ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n m_serverSocket.reset();\n this_thread::sleep_for(1000ms);\n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testProtocolCommand()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n const auto cmd = \"* Hello Connector\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(cmd), (size_t) m_serverSocket->write(cmd, strlen(cmd)));\n this_thread::sleep_for(1000ms);\n \n \/\/ \\n is stripped from the posted data.\n CPPUNIT_ASSERT(strncmp(cmd, m_connector->m_command.c_str(), strlen(cmd) - 1) == 0);\n }\n \n \n void ConnectorTest::testHeartbeat()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n \/\/ Receive initial heartbeat request \"* PING\\n\"\n char buf[1024] = {0};\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 5000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(strcmp(buf, \"* PING\\n\") == 0);\n \n \/\/ Respond to the heartbeat of 1 second\n const auto pong = \"* PONG 1000\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(pong), (size_t) m_serverSocket->write(pong, strlen(pong)));\n this_thread::sleep_for(1000ms);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{1000}, m_connector->heartbeatFrequency());\n }\n \n \n void ConnectorTest::testHeartbeatPong()\n {\n testHeartbeat();\n \n auto last_heartbeat = system_clock::now();\n \n \/\/ Test to make sure we can send and receive 5 heartbeats\n for (int i = 0; i < 5; i++)\n {\n \/\/ Receive initial heartbeat request \"* PING\\n\"\n \n char buf[1024] = {0};\n CPPUNIT_ASSERT(m_serverSocket->read(buf, 1023, 1100) > 0);\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n auto now = system_clock::now();\n CPPUNIT_ASSERT(now - last_heartbeat < 2000ms);\n last_heartbeat = now;\n \n \/\/ Respond to the heartbeat of 1 second\n const auto pong = \"* PONG 1000\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(pong), (size_t) m_serverSocket->write(pong, strlen(pong)));\n this_thread::sleep_for(10ms);\n \n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n }\n }\n \n \n void ConnectorTest::testHeartbeatTimeout()\n {\n testHeartbeat();\n this_thread::sleep_for(2100ms);\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testLegacyTimeout()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n char buf[1024] = {0};\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 5000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n \/\/ Write some data...\n const auto cmd = \"* Hello Connector\\n\";\n CPPUNIT_ASSERT_EQUAL(strlen(cmd), (size_t) m_serverSocket->write(cmd, strlen(cmd)));\n \n \/\/ No pings, but timeout after 5 seconds of silence\n this_thread::sleep_for(11000ms);\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n }\n \n \n void ConnectorTest::testParseBuffer()\n {\n \/\/ Test data fragmentation\n m_connector->pushData(\"Hello\");\n CPPUNIT_ASSERT_EQUAL((string) \"\", m_connector->m_data);\n \n m_connector->pushData(\" There\\n\");\n CPPUNIT_ASSERT_EQUAL((string) \"Hello There\", m_connector->m_data);\n m_connector->m_data.clear();\n \n m_connector->pushData(\"Hello\");\n CPPUNIT_ASSERT_EQUAL((string) \"\", m_connector->m_data);\n \n m_connector->pushData(\" There\\nAnd \");\n CPPUNIT_ASSERT_EQUAL((string) \"Hello There\", m_connector->m_data);\n \n m_connector->pushData(\"Again\\nXXX\");\n CPPUNIT_ASSERT_EQUAL((string) \"And Again\", m_connector->m_data);\n }\n \n \n void ConnectorTest::testParseBufferFraming()\n {\n m_connector->m_list.clear();\n m_connector->pushData(\"first\\nseco\");\n m_connector->pushData(\"nd\\nthird\\nfourth\\nfifth\");\n CPPUNIT_ASSERT_EQUAL((size_t) 4, m_connector->m_list.size());\n CPPUNIT_ASSERT_EQUAL((string) \"first\", m_connector->m_list[0]);\n CPPUNIT_ASSERT_EQUAL((string) \"second\", m_connector->m_list[1]);\n CPPUNIT_ASSERT_EQUAL((string) \"third\", m_connector->m_list[2]);\n CPPUNIT_ASSERT_EQUAL((string) \"fourth\", m_connector->m_list[3]);\n }\n \n \n void ConnectorTest::testSendCommand()\n {\n \/\/ Start the accept thread\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n CPPUNIT_ASSERT(m_serverSocket.get());\n \n \/\/ Receive initial heartbeat request \"* PING\\n\"\n char buf[1024];\n CPPUNIT_ASSERT_EQUAL(7L, m_serverSocket->read(buf, 1023, 1000));\n buf[7] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* PING\\n\"));\n \n m_connector->sendCommand(\"Hello There;\");\n \n long len;\n int times = 0;\n do {\n len = m_serverSocket->read(buf, 1023, 1000);\n }\n while (times++ < 5 && (len == TIMEOUT || len == WOULDBLOCK));\n \n CPPUNIT_ASSERT_EQUAL(15L, len);\n buf[15] = '\\0';\n CPPUNIT_ASSERT(!strcmp(buf, \"* Hello There;\\n\"));\n }\n \n \n void ConnectorTest::testIPV6Connection()\n {\n#if !defined(WIN32) || (NTDDI_VERSION >= NTDDI_VISTA)\n m_connector.reset();\n \n CPPUNIT_ASSERT(!create_listener(m_server, 0, \"::1\"));\n m_port = m_server->get_listening_port();\n m_connector.reset(new TestConnector(\"::1\", m_port));\n m_connector->m_disconnected = true;\n \n CPPUNIT_ASSERT(m_connector->m_disconnected);\n start();\n \n CPPUNIT_ASSERT_EQUAL(0, m_server->accept(m_serverSocket));\n this_thread::sleep_for(100ms);\n CPPUNIT_ASSERT(m_serverSocket.get());\n CPPUNIT_ASSERT(!m_connector->m_disconnected);\n#endif\n }\n \n \n void ConnectorTest::testStartHeartbeats()\n {\n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n string line = \"* PONG \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONK \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG FLAB\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(!m_connector->heartbeats());\n \n line = \"* PONG 123\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{123}, m_connector->heartbeatFrequency());\n \n m_connector->resetHeartbeats();\n \n line = \"* PONG 456 \";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{456}, m_connector->heartbeatFrequency());\n \n line = \"* PONG 323\";\n m_connector->startHeartbeats(line);\n \n CPPUNIT_ASSERT(m_connector->heartbeats());\n CPPUNIT_ASSERT_EQUAL(std::chrono::milliseconds{323}, m_connector->heartbeatFrequency());\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"headings.h\"\n#include \"libaps2.h\"\n#include \"constants.h\"\n\n#include <concol.h>\n\nusing namespace std;\n\nint get_device_id() {\n cout << \"Choose device ID [0]: \";\n string input = \"\";\n getline(cin, input);\n\n if (input.length() == 0) {\n return 0;\n }\n int device_id;\n stringstream mystream(input);\n\n mystream >> device_id;\n return device_id;\n}\n\nuint64_t get_mac_input() {\n cout << \"New MAC address [ENTER to skip]: \";\n string input = \"\";\n getline(cin, input);\n\n if (input.length() == 0) {\n return 0;\n }\n stringstream mystream(input);\n uint64_t mac_addr;\n mystream >> std::hex >> mac_addr;\n\n cout << \"Received \" << hexn<12> << mac_addr << endl;\n return mac_addr;\n}\n\nstring get_ip_input() {\n cout << \"New IP address [ENTER to skip]: \";\n string input = \"\";\n getline(cin, input);\n return input;\n}\n\nbool spi_prompt() {\n cout << \"Do you want to program the SPI startup sequence? [y\/N]: \";\n string input = \"\";\n getline(cin, input);\n if (input.length() == 0) {\n return false;\n }\n stringstream mystream(input);\n char response;\n mystream >> response;\n switch (response) {\n case 'y':\n case 'Y':\n return true;\n break;\n case 'n':\n case 'N':\n default:\n return false;\n }\n}\n\nint main (int argc, char* argv[])\n{\n\n concol::concolinit();\n cout << concol::RED << \"BBN AP2 Flash Test Executable\" << concol::RESET << endl;\n\n\n int dbgLevel = 8;\n if (argc >= 2) {\n dbgLevel = atoi(argv[1]);\n }\n\n set_logging_level(dbgLevel);\n set_log(\"stdout\");\n\n cout << concol::RED << \"Enumerating devices\" << concol::RESET << endl;\n\n int numDevices = get_numDevices();\n\n cout << concol::RED << numDevices << \" APS device\" << (numDevices > 1 ? \"s\": \"\") << \" found\" << concol::RESET << endl;\n\n if (numDevices < 1)\n \treturn 0;\n\n cout << concol::RED << \"Attempting to get serials\" << concol::RESET << endl;\n\n const char ** serialBuffer = new const char*[numDevices];\n get_deviceSerials(serialBuffer);\n\n for (int cnt=0; cnt < numDevices; cnt++) {\n \tcout << concol::RED << \"Device \" << cnt << \" serial #: \" << serialBuffer[cnt] << concol::RESET << endl;\n }\n\n string deviceSerial;\n\n if (numDevices == 1) {\n deviceSerial = string(serialBuffer[0]);\n } else {\n deviceSerial = string(serialBuffer[get_device_id()]);\n }\n\n cout << concol::RED << \"Connecting to device serial #: \" << deviceSerial << concol::RESET << endl;\n\n connect_APS(deviceSerial.c_str());\n\n double uptime = get_uptime(deviceSerial.c_str());\n\n cout << concol::RED << \"Uptime for device \" << deviceSerial << \" is \" << uptime << \" seconds\" << concol::RESET << endl;\n\n cout << \"Programmed MAC and IP address at 0x00FF0000 are \" << endl;\n cout << \"MAC addr: \" << hexn<12> << get_mac_addr(deviceSerial.c_str()) << endl;\n cout << \"IP addr: \" << get_ip_addr(deviceSerial.c_str()) << endl;\n\n \/\/ write a new MAC address\n uint64_t mac_addr = get_mac_input();\n if (mac_addr != 0) {\n cout << concol::RED << \"Writing new MAC address\" << concol::RESET << endl;\n set_mac_addr(deviceSerial.c_str(), mac_addr);\n }\n\n \/\/ write a new IP address\n string ip_addr = get_ip_input();\n if (ip_addr != \"\") {\n cout << concol::RED << \"Writing new IP address\" << concol::RESET << endl;\n set_ip_addr(deviceSerial.c_str(), ip_addr.c_str());\n }\n\n \/\/ read SPI setup sequence\n uint32_t setup[32];\n read_flash(deviceSerial.c_str(), 0x0, 32, setup);\n cout << \"Programmed setup SPI sequence:\" << endl;\n for (size_t ct=0; ct < 32; ct++) {\n cout << hexn<8> << setup[ct] << \" \";\n if (ct % 4 == 3) cout << endl;\n }\n\n \/\/ write new SPI setup sequence\n if (spi_prompt()) {\n cout << concol::RED << \"Writing SPI startup sequence\" << concol::RESET << endl;\n write_SPI_setup(deviceSerial.c_str());\n }\n \/*\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n uint32_t buffer[4] = {0, 0, 0, 0};\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n\n cout << concol::RED << \"Erasing\/writing flash addr 0x00FA0000 (128 words)\" << concol::RESET << endl;\n vector<uint32_t> testData;\n for (size_t ct=0; ct<128; ct++){\n testData.push_back(0x00FA0000 + static_cast<uint32_t>(ct));\n }\n write_flash(deviceSerial.c_str(), 0x00FA0000, testData.data(), testData.size());\n\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n\n cout << concol::RED << \"Erasing\/writing flash addr 0x00FA0000 (2 words)\" << concol::RESET << endl;\n buffer[0] = 0xBADD1234;\n buffer[1] = 0x1234F00F;\n write_flash(deviceSerial.c_str(), 0x00FA0000, buffer, 2);\n\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n *\/\n\n disconnect_APS(deviceSerial.c_str());\n\n delete[] serialBuffer;\n\n cout << concol::RED << \"Finished!\" << concol::RESET << endl;\n\n return 0;\n}\n<commit_msg>Reduce default logging level<commit_after>#include <iostream>\n\n#include \"headings.h\"\n#include \"libaps2.h\"\n#include \"constants.h\"\n\n#include <concol.h>\n\nusing namespace std;\n\nint get_device_id() {\n cout << \"Choose device ID [0]: \";\n string input = \"\";\n getline(cin, input);\n\n if (input.length() == 0) {\n return 0;\n }\n int device_id;\n stringstream mystream(input);\n\n mystream >> device_id;\n return device_id;\n}\n\nuint64_t get_mac_input() {\n cout << \"New MAC address [ENTER to skip]: \";\n string input = \"\";\n getline(cin, input);\n\n if (input.length() == 0) {\n return 0;\n }\n stringstream mystream(input);\n uint64_t mac_addr;\n mystream >> std::hex >> mac_addr;\n\n cout << \"Received \" << hexn<12> << mac_addr << endl;\n return mac_addr;\n}\n\nstring get_ip_input() {\n cout << \"New IP address [ENTER to skip]: \";\n string input = \"\";\n getline(cin, input);\n return input;\n}\n\nbool spi_prompt() {\n cout << \"Do you want to program the SPI startup sequence? [y\/N]: \";\n string input = \"\";\n getline(cin, input);\n if (input.length() == 0) {\n return false;\n }\n stringstream mystream(input);\n char response;\n mystream >> response;\n switch (response) {\n case 'y':\n case 'Y':\n return true;\n break;\n case 'n':\n case 'N':\n default:\n return false;\n }\n}\n\nint main (int argc, char* argv[])\n{\n\n concol::concolinit();\n cout << concol::RED << \"BBN AP2 Flash Test Executable\" << concol::RESET << endl;\n\n\n int dbgLevel = 4;\n if (argc >= 2) {\n dbgLevel = atoi(argv[1]);\n }\n\n set_logging_level(dbgLevel);\n set_log(\"stdout\");\n\n cout << concol::RED << \"Enumerating devices\" << concol::RESET << endl;\n\n int numDevices = get_numDevices();\n\n cout << concol::RED << numDevices << \" APS device\" << (numDevices > 1 ? \"s\": \"\") << \" found\" << concol::RESET << endl;\n\n if (numDevices < 1)\n \treturn 0;\n\n cout << concol::RED << \"Attempting to get serials\" << concol::RESET << endl;\n\n const char ** serialBuffer = new const char*[numDevices];\n get_deviceSerials(serialBuffer);\n\n for (int cnt=0; cnt < numDevices; cnt++) {\n \tcout << concol::RED << \"Device \" << cnt << \" serial #: \" << serialBuffer[cnt] << concol::RESET << endl;\n }\n\n string deviceSerial;\n\n if (numDevices == 1) {\n deviceSerial = string(serialBuffer[0]);\n } else {\n deviceSerial = string(serialBuffer[get_device_id()]);\n }\n\n cout << concol::RED << \"Connecting to device serial #: \" << deviceSerial << concol::RESET << endl;\n\n connect_APS(deviceSerial.c_str());\n\n double uptime = get_uptime(deviceSerial.c_str());\n\n cout << concol::RED << \"Uptime for device \" << deviceSerial << \" is \" << uptime << \" seconds\" << concol::RESET << endl;\n\n cout << \"Programmed MAC and IP address at 0x00FF0000 are \" << endl;\n cout << \"MAC addr: \" << hexn<12> << get_mac_addr(deviceSerial.c_str()) << endl;\n cout << \"IP addr: \" << get_ip_addr(deviceSerial.c_str()) << endl;\n\n \/\/ write a new MAC address\n uint64_t mac_addr = get_mac_input();\n if (mac_addr != 0) {\n cout << concol::RED << \"Writing new MAC address\" << concol::RESET << endl;\n set_mac_addr(deviceSerial.c_str(), mac_addr);\n }\n\n \/\/ write a new IP address\n string ip_addr = get_ip_input();\n if (ip_addr != \"\") {\n cout << concol::RED << \"Writing new IP address\" << concol::RESET << endl;\n set_ip_addr(deviceSerial.c_str(), ip_addr.c_str());\n }\n\n \/\/ read SPI setup sequence\n uint32_t setup[32];\n read_flash(deviceSerial.c_str(), 0x0, 32, setup);\n cout << \"Programmed setup SPI sequence:\" << endl;\n for (size_t ct=0; ct < 32; ct++) {\n cout << hexn<8> << setup[ct] << \" \";\n if (ct % 4 == 3) cout << endl;\n }\n\n \/\/ write new SPI setup sequence\n if (spi_prompt()) {\n cout << concol::RED << \"Writing SPI startup sequence\" << concol::RESET << endl;\n write_SPI_setup(deviceSerial.c_str());\n }\n \/*\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n uint32_t buffer[4] = {0, 0, 0, 0};\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n\n cout << concol::RED << \"Erasing\/writing flash addr 0x00FA0000 (128 words)\" << concol::RESET << endl;\n vector<uint32_t> testData;\n for (size_t ct=0; ct<128; ct++){\n testData.push_back(0x00FA0000 + static_cast<uint32_t>(ct));\n }\n write_flash(deviceSerial.c_str(), 0x00FA0000, testData.data(), testData.size());\n\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n\n cout << concol::RED << \"Erasing\/writing flash addr 0x00FA0000 (2 words)\" << concol::RESET << endl;\n buffer[0] = 0xBADD1234;\n buffer[1] = 0x1234F00F;\n write_flash(deviceSerial.c_str(), 0x00FA0000, buffer, 2);\n\n cout << concol::RED << \"Reading flash addr 0x00FA0000\" << concol::RESET << endl;\n read_flash(deviceSerial.c_str(), 0x00FA0000, 4, buffer);\n cout << \"Received \" << hexn<8> << buffer[0] << \" \" << hexn<8> << buffer[1];\n cout << \" \" << hexn<8> << buffer[2] << \" \" << hexn<8> << buffer[3] << endl;\n *\/\n\n disconnect_APS(deviceSerial.c_str());\n\n delete[] serialBuffer;\n\n cout << concol::RED << \"Finished!\" << concol::RESET << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rubymotion.h\"\n#include \"motion-game.h\"\n#include <dlfcn.h>\n\n\/\/\/ @class Scene < Node\n\/\/\/ This class represents a scene, an independent screen or stage of the\n\/\/\/ application workflow. A scene is responsible for handling events from the\n\/\/\/ device, providing a physics world for the sprites, and also starting the\n\/\/\/ game loop.\n\/\/\/ An application must have at least one scene, and the +Scene+ class is\n\/\/\/ designed to be subclassed.\n\nVALUE rb_cScene = Qnil;\n\n#if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\nextern \"C\" {\n void rb_repl_new(VALUE);\n}\n#endif\n\nenum mc_Scene_EventType {\n ON_BEGIN,\n ON_MOVE,\n ON_END,\n ON_CANCEL\n};\n\nclass mc_Scene : public cocos2d::LayerColor {\n public:\n\tcocos2d::Scene *scene;\n\tVALUE obj;\n\tSEL update_sel;\n cocos2d::EventListenerTouchOneByOne *touch_listener;\n\n mc_Scene() {\n\tobj = Qnil;\n\ttouch_listener = NULL;\n#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV\n\tupdate_sel = rb_selector(\"update:\");\n#else\n\tupdate_sel = rb_selector(\"update\");\n#endif\n }\n\n static mc_Scene *create(void) {\n\tauto scene = new mc_Scene();\n\tscene->initWithColor(cocos2d::Color4B::BLACK);\n\treturn scene;\n }\n\n virtual void update(float delta) {\n\tLayerColor::update(delta);\n\tVALUE arg = DBL2NUM(delta);\n\trb_send(obj, update_sel, 1, &arg);\n }\n\n void setBackgroundColor(cocos2d::Color3B color) {\n\tsetColor(color);\n\tupdateColor();\n }\n\n#if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\n virtual void onEnter() {\n\tcocos2d::LayerColor::onEnter();\n\trb_repl_new(this->obj);\n }\n#endif\n};\n\n#define SCENE(obj) _COCOS_WRAP_GET(obj, mc_Scene)\n\nextern \"C\"\ncocos2d::Scene *\nrb_any_to_scene(VALUE obj)\n{\n if (rb_obj_is_kind_of(obj, rb_cScene)) {\n\treturn SCENE(obj)->scene;\n }\n rb_raise(rb_eArgError, \"expected Scene object\");\n}\n\nstatic VALUE\nscene_alloc(VALUE rcv, SEL sel)\n{\n auto layer = mc_Scene::create();\n\n auto scene = cocos2d::Scene::createWithPhysics();\n scene->addChild(layer);\n layer->scene = scene;\n\n VALUE obj = rb_cocos2d_object_new(layer, rcv);\n layer->obj = rb_retain(obj);\n return obj;\n}\n\n\/\/\/ @group Constructors\n\n\/\/\/ @method #initialize\n\/\/\/ The default initializer. Subclasses can construct the scene interface in\n\/\/\/ this method, as well as providing an implementation for {#update}, then\n\/\/\/ run the update loop by calling {#start_update}.\n\/\/\/ @return [Scene] the receiver.\n\nstatic VALUE\nscene_initialize(VALUE rcv, SEL sel)\n{\n return rcv;\n}\n\n\/\/\/ @group Update Loop\n\n\/\/\/ @method #start_update\n\/\/\/ Starts the update loop. The +#update+ method will be called on this object\n\/\/\/ for every frame.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_start_update(VALUE rcv, SEL sel)\n{\n SCENE(rcv)->scheduleUpdate();\n return rcv;\n}\n\n\/\/\/ @method #stop_update\n\/\/\/ Stops the update loop. The +#update+ method will no longer be called on\n\/\/\/ this object.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_stop_update(VALUE rcv, SEL sel)\n{\n SCENE(rcv)->unscheduleUpdate();\n return rcv;\n}\n\n\/\/\/ @method #update(delta)\n\/\/\/ The update loop method. Subclasses can provide a custom implementation of\n\/\/\/ this method. The default implementation is empty.\n\/\/\/ @param delta [Float] a value representing the amount of time, in seconds,\n\/\/\/ since the last time this method was called.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_update(VALUE rcv, SEL sel, VALUE delta)\n{\n \/\/ Do nothing.\n return rcv;\n}\n\n\/\/\/ @group Events\n\nstatic VALUE\nscene_add_listener(VALUE rcv, cocos2d::EventListener *listener)\n{\n auto scene = SCENE(rcv);\n scene->getEventDispatcher()->addEventListenerWithSceneGraphPriority(\n\t listener, scene);\n return rcv;\n}\n\nstatic VALUE\nscene_on_touch_event(VALUE rcv, SEL sel, mc_Scene_EventType type)\n{\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n auto scene = SCENE(rcv);\n if (scene->touch_listener == NULL) {\n\tscene->touch_listener = cocos2d::EventListenerTouchOneByOne::create();\n }\n else {\n\tscene->getEventDispatcher()->removeEventListener(scene->touch_listener);\n }\n auto lambda = [block](cocos2d::Touch *touch, cocos2d::Event *event) -> bool {\n\tVALUE touch_obj = rb_cocos2d_object_new(touch, rb_cTouch);\n\treturn RTEST(rb_block_call(block, 1, &touch_obj));\n };\n\n switch (type) {\n case ON_BEGIN:\n\tscene->touch_listener->onTouchBegan = lambda;\n\tbreak;\n case ON_MOVE:\n\tscene->touch_listener->onTouchMoved = lambda;\n\tbreak;\n case ON_END:\n\tscene->touch_listener->onTouchEnded = lambda;\n\tbreak;\n case ON_CANCEL:\n\tscene->touch_listener->onTouchCancelled = lambda;\n\tbreak;\n }\n\n return scene_add_listener(rcv, scene->touch_listener);\n}\n\n\/\/\/ @method #on_touch_begin\n\/\/\/ Starts listening for touch begin events on the receiver.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch begin\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_begin(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_BEGIN);\n}\n\n\/\/\/ @method #on_touch_end\n\/\/\/ Starts listening for touch end events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch end\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_end(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_END);\n}\n\n\/\/\/ @method #on_touch_move\n\/\/\/ Starts listening for touch move events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch move\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_move(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_MOVE);\n}\n\n\/\/\/ @method #on_touch_cancel\n\/\/\/ Starts listening for touch cancel events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch cancel\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_cancel(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_CANCEL);\n}\n\/\/\/ @method #on_accelerate\n\/\/\/ Starts listening for accelerometer events on the receiver.\n\/\/\/ @yield [Events::Acceleration] the given block will be yield when an\n\/\/\/ accelerometer event is received from the device.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_accelerate(VALUE rcv, SEL sel)\n{\n#if CC_TARGET_OS_APPLETV\n rb_raise(rb_eRuntimeError, \"Not supported in tvOS\");\n#else\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n cocos2d::Device::setAccelerometerEnabled(true);\n auto listener = cocos2d::EventListenerAcceleration::create(\n\t[block](cocos2d::Acceleration *acc, cocos2d::Event *event) {\n\t VALUE acc_obj = rb_cocos2d_object_new(acc, rb_cAcceleration);\n\t rb_block_call(block, 1, &acc_obj);\n\t});\n\n return scene_add_listener(rcv, listener);\n#endif\n}\n\n\/\/\/ @method #on_contact_begin\n\/\/\/ Starts listening for contact begin events from the physics engine.\n\/\/\/ @yield [Events::PhysicsContact] the given block will be yield when a\n\/\/\/ contact event is received from the physics engine.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_contact_begin(VALUE rcv, SEL sel)\n{\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n auto listener = cocos2d::EventListenerPhysicsContact::create();\n listener->onContactBegin = [block](cocos2d::PhysicsContact &contact) -> bool {\n\treturn RTEST(rb_block_call(block, 0, NULL));\n };\n\n return scene_add_listener(rcv, listener);\n}\n\n\/\/\/ @endgroup\n\n\/\/\/ @property #gravity\n\/\/\/ @return [Point] the gravity of the scene's physics world.\n\nstatic VALUE\nscene_gravity(VALUE rcv, SEL sel)\n{\n return rb_ccvec2_to_obj(SCENE(rcv)->scene->getPhysicsWorld()->getGravity());\n}\n\nstatic VALUE\nscene_gravity_set(VALUE rcv, SEL sel, VALUE arg)\n{\n SCENE(rcv)->scene->getPhysicsWorld()->setGravity(rb_any_to_ccvec2(arg));\n return rcv;\n}\n\n\/\/\/ @method #debug_physics?\n\/\/\/ @return [Boolean] whether the physics engine should draw debug lines.\n\nstatic VALUE\nscene_debug_physics(VALUE rcv, SEL sel)\n{\n return SCENE(rcv)->scene->getPhysicsWorld()->getDebugDrawMask()\n\t== cocos2d::PhysicsWorld::DEBUGDRAW_NONE ? Qfalse : Qtrue;\n}\n\n\/\/\/ @method #debug_physics=(value)\n\/\/\/ Set to draw the debug line.\n\/\/\/ @param value [Boolean] true if draw debug lines.\n\nstatic VALUE\nscene_debug_physics_set(VALUE rcv, SEL sel, VALUE arg)\n{\n SCENE(rcv)->scene->getPhysicsWorld()->setDebugDrawMask(RTEST(arg)\n\t ? cocos2d::PhysicsWorld::DEBUGDRAW_ALL\n\t : cocos2d::PhysicsWorld::DEBUGDRAW_NONE);\n return arg;\n}\n\n\/\/\/ @method #background_color=(color)\n\/\/\/ Set background color for scene.\n\/\/\/ @param color [Color] background color for scene.\n\nstatic VALUE\nscene_background_color_set(VALUE rcv, SEL sel, VALUE val)\n{\n SCENE(rcv)->setBackgroundColor(rb_any_to_cccolor3(val));\n return val;\n}\n\nextern \"C\"\nvoid\nInit_Layer(void)\n{\n rb_cScene = rb_define_class_under(rb_mMC, \"Scene\", rb_cNode);\n \/\/ rb_register_cocos2d_object_finalizer(rb_cScene); removed because rb_cScene inherits rb_cNode and it already has finalizer.\n\n rb_define_singleton_method(rb_cScene, \"alloc\", scene_alloc, 0);\n rb_define_method(rb_cScene, \"initialize\", scene_initialize, 0);\n rb_define_method(rb_cScene, \"start_update\", scene_start_update, 0);\n rb_define_method(rb_cScene, \"stop_update\", scene_stop_update, 0);\n rb_define_method(rb_cScene, \"update\", scene_update, 1);\n rb_define_method(rb_cScene, \"on_touch_begin\", scene_on_touch_begin, 0);\n rb_define_method(rb_cScene, \"on_touch_end\", scene_on_touch_end, 0);\n rb_define_method(rb_cScene, \"on_touch_move\", scene_on_touch_move, 0);\n rb_define_method(rb_cScene, \"on_touch_cancel\", scene_on_touch_cancel, 0);\n rb_define_method(rb_cScene, \"on_accelerate\", scene_on_accelerate, 0);\n rb_define_method(rb_cScene, \"on_contact_begin\", scene_on_contact_begin, 0);\n rb_define_method(rb_cScene, \"gravity\", scene_gravity, 0);\n rb_define_method(rb_cScene, \"gravity=\", scene_gravity_set, 1);\n rb_define_method(rb_cScene, \"debug_physics?\", scene_debug_physics, 0);\n rb_define_method(rb_cScene, \"debug_physics=\", scene_debug_physics_set, 1);\n rb_define_method(rb_cScene, \"background_color=\", scene_background_color_set, 1);\n rb_define_method(rb_cScene, \"color=\", scene_background_color_set, 1); \/\/ depricated\n}\n<commit_msg>[#69] add dummy implementation when call Scene#on_touch_{end, move, cancel} without #on_touch_begin<commit_after>#include \"rubymotion.h\"\n#include \"motion-game.h\"\n#include <dlfcn.h>\n\n\/\/\/ @class Scene < Node\n\/\/\/ This class represents a scene, an independent screen or stage of the\n\/\/\/ application workflow. A scene is responsible for handling events from the\n\/\/\/ device, providing a physics world for the sprites, and also starting the\n\/\/\/ game loop.\n\/\/\/ An application must have at least one scene, and the +Scene+ class is\n\/\/\/ designed to be subclassed.\n\nVALUE rb_cScene = Qnil;\n\n#if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\nextern \"C\" {\n void rb_repl_new(VALUE);\n}\n#endif\n\nenum mc_Scene_EventType {\n ON_BEGIN,\n ON_MOVE,\n ON_END,\n ON_CANCEL\n};\n\nclass mc_Scene : public cocos2d::LayerColor {\n public:\n\tcocos2d::Scene *scene;\n\tVALUE obj;\n\tSEL update_sel;\n cocos2d::EventListenerTouchOneByOne *touch_listener;\n\n mc_Scene() {\n\tobj = Qnil;\n\ttouch_listener = NULL;\n#if CC_TARGET_OS_IPHONE || CC_TARGET_OS_APPLETV\n\tupdate_sel = rb_selector(\"update:\");\n#else\n\tupdate_sel = rb_selector(\"update\");\n#endif\n }\n\n static mc_Scene *create(void) {\n\tauto scene = new mc_Scene();\n\tscene->initWithColor(cocos2d::Color4B::BLACK);\n\treturn scene;\n }\n\n virtual void update(float delta) {\n\tLayerColor::update(delta);\n\tVALUE arg = DBL2NUM(delta);\n\trb_send(obj, update_sel, 1, &arg);\n }\n\n void setBackgroundColor(cocos2d::Color3B color) {\n\tsetColor(color);\n\tupdateColor();\n }\n\n#if CC_TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\n virtual void onEnter() {\n\tcocos2d::LayerColor::onEnter();\n\trb_repl_new(this->obj);\n }\n#endif\n};\n\n#define SCENE(obj) _COCOS_WRAP_GET(obj, mc_Scene)\n\nextern \"C\"\ncocos2d::Scene *\nrb_any_to_scene(VALUE obj)\n{\n if (rb_obj_is_kind_of(obj, rb_cScene)) {\n\treturn SCENE(obj)->scene;\n }\n rb_raise(rb_eArgError, \"expected Scene object\");\n}\n\nstatic VALUE\nscene_alloc(VALUE rcv, SEL sel)\n{\n auto layer = mc_Scene::create();\n\n auto scene = cocos2d::Scene::createWithPhysics();\n scene->addChild(layer);\n layer->scene = scene;\n\n VALUE obj = rb_cocos2d_object_new(layer, rcv);\n layer->obj = rb_retain(obj);\n return obj;\n}\n\n\/\/\/ @group Constructors\n\n\/\/\/ @method #initialize\n\/\/\/ The default initializer. Subclasses can construct the scene interface in\n\/\/\/ this method, as well as providing an implementation for {#update}, then\n\/\/\/ run the update loop by calling {#start_update}.\n\/\/\/ @return [Scene] the receiver.\n\nstatic VALUE\nscene_initialize(VALUE rcv, SEL sel)\n{\n return rcv;\n}\n\n\/\/\/ @group Update Loop\n\n\/\/\/ @method #start_update\n\/\/\/ Starts the update loop. The +#update+ method will be called on this object\n\/\/\/ for every frame.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_start_update(VALUE rcv, SEL sel)\n{\n SCENE(rcv)->scheduleUpdate();\n return rcv;\n}\n\n\/\/\/ @method #stop_update\n\/\/\/ Stops the update loop. The +#update+ method will no longer be called on\n\/\/\/ this object.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_stop_update(VALUE rcv, SEL sel)\n{\n SCENE(rcv)->unscheduleUpdate();\n return rcv;\n}\n\n\/\/\/ @method #update(delta)\n\/\/\/ The update loop method. Subclasses can provide a custom implementation of\n\/\/\/ this method. The default implementation is empty.\n\/\/\/ @param delta [Float] a value representing the amount of time, in seconds,\n\/\/\/ since the last time this method was called.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_update(VALUE rcv, SEL sel, VALUE delta)\n{\n \/\/ Do nothing.\n return rcv;\n}\n\n\/\/\/ @group Events\n\nstatic VALUE\nscene_add_listener(VALUE rcv, cocos2d::EventListener *listener)\n{\n auto scene = SCENE(rcv);\n scene->getEventDispatcher()->addEventListenerWithSceneGraphPriority(\n\t listener, scene);\n return rcv;\n}\n\nstatic\nbool scene_onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {\n return true;\n}\n\nstatic VALUE\nscene_on_touch_event(VALUE rcv, SEL sel, mc_Scene_EventType type)\n{\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n auto scene = SCENE(rcv);\n if (scene->touch_listener == NULL) {\n\tscene->touch_listener = cocos2d::EventListenerTouchOneByOne::create();\n }\n else {\n\tscene->getEventDispatcher()->removeEventListener(scene->touch_listener);\n }\n auto lambda = [block](cocos2d::Touch *touch, cocos2d::Event *event) -> bool {\n\tVALUE touch_obj = rb_cocos2d_object_new(touch, rb_cTouch);\n\treturn RTEST(rb_block_call(block, 1, &touch_obj));\n };\n\n switch (type) {\n case ON_BEGIN:\n\tscene->touch_listener->onTouchBegan = lambda;\n\tbreak;\n case ON_MOVE:\n\tscene->touch_listener->onTouchMoved = lambda;\n\tbreak;\n case ON_END:\n\tscene->touch_listener->onTouchEnded = lambda;\n\tbreak;\n case ON_CANCEL:\n\tscene->touch_listener->onTouchCancelled = lambda;\n\tbreak;\n }\n if (scene->touch_listener->onTouchBegan == NULL) {\n\t\/\/ EventDispatcher will use the return value of 'onTouchBegan' to determine whether to pass following 'move', 'end'\n\t\/\/ message to 'EventListenerTouchOneByOne' or not. So 'onTouchBegan' needs to be set.\n\tscene->touch_listener->onTouchBegan = scene_onTouchBegan;\n }\n\n return scene_add_listener(rcv, scene->touch_listener);\n}\n\n\/\/\/ @method #on_touch_begin\n\/\/\/ Starts listening for touch begin events on the receiver.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch begin\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_begin(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_BEGIN);\n}\n\n\/\/\/ @method #on_touch_end\n\/\/\/ Starts listening for touch end events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch end\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_end(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_END);\n}\n\n\/\/\/ @method #on_touch_move\n\/\/\/ Starts listening for touch move events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch move\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_move(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_MOVE);\n}\n\n\/\/\/ @method #on_touch_cancel\n\/\/\/ Starts listening for touch cancel events on the receiver.\n\/\/\/ This method requires {#on_touch_begin} calling in order to catch the event.\n\/\/\/ @yield [Events::Touch] the given block will be yield when a touch cancel\n\/\/\/ event is received.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_touch_cancel(VALUE rcv, SEL sel)\n{\n return scene_on_touch_event(rcv, sel, mc_Scene_EventType::ON_CANCEL);\n}\n\/\/\/ @method #on_accelerate\n\/\/\/ Starts listening for accelerometer events on the receiver.\n\/\/\/ @yield [Events::Acceleration] the given block will be yield when an\n\/\/\/ accelerometer event is received from the device.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_accelerate(VALUE rcv, SEL sel)\n{\n#if CC_TARGET_OS_APPLETV\n rb_raise(rb_eRuntimeError, \"Not supported in tvOS\");\n#else\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n cocos2d::Device::setAccelerometerEnabled(true);\n auto listener = cocos2d::EventListenerAcceleration::create(\n\t[block](cocos2d::Acceleration *acc, cocos2d::Event *event) {\n\t VALUE acc_obj = rb_cocos2d_object_new(acc, rb_cAcceleration);\n\t rb_block_call(block, 1, &acc_obj);\n\t});\n\n return scene_add_listener(rcv, listener);\n#endif\n}\n\n\/\/\/ @method #on_contact_begin\n\/\/\/ Starts listening for contact begin events from the physics engine.\n\/\/\/ @yield [Events::PhysicsContact] the given block will be yield when a\n\/\/\/ contact event is received from the physics engine.\n\/\/\/ @return [self] the receiver.\n\nstatic VALUE\nscene_on_contact_begin(VALUE rcv, SEL sel)\n{\n VALUE block = rb_current_block();\n if (block == Qnil) {\n\trb_raise(rb_eArgError, \"block not given\");\n }\n block = rb_retain(block); \/\/ FIXME need release...\n\n auto listener = cocos2d::EventListenerPhysicsContact::create();\n listener->onContactBegin = [block](cocos2d::PhysicsContact &contact) -> bool {\n\treturn RTEST(rb_block_call(block, 0, NULL));\n };\n\n return scene_add_listener(rcv, listener);\n}\n\n\/\/\/ @endgroup\n\n\/\/\/ @property #gravity\n\/\/\/ @return [Point] the gravity of the scene's physics world.\n\nstatic VALUE\nscene_gravity(VALUE rcv, SEL sel)\n{\n return rb_ccvec2_to_obj(SCENE(rcv)->scene->getPhysicsWorld()->getGravity());\n}\n\nstatic VALUE\nscene_gravity_set(VALUE rcv, SEL sel, VALUE arg)\n{\n SCENE(rcv)->scene->getPhysicsWorld()->setGravity(rb_any_to_ccvec2(arg));\n return rcv;\n}\n\n\/\/\/ @method #debug_physics?\n\/\/\/ @return [Boolean] whether the physics engine should draw debug lines.\n\nstatic VALUE\nscene_debug_physics(VALUE rcv, SEL sel)\n{\n return SCENE(rcv)->scene->getPhysicsWorld()->getDebugDrawMask()\n\t== cocos2d::PhysicsWorld::DEBUGDRAW_NONE ? Qfalse : Qtrue;\n}\n\n\/\/\/ @method #debug_physics=(value)\n\/\/\/ Set to draw the debug line.\n\/\/\/ @param value [Boolean] true if draw debug lines.\n\nstatic VALUE\nscene_debug_physics_set(VALUE rcv, SEL sel, VALUE arg)\n{\n SCENE(rcv)->scene->getPhysicsWorld()->setDebugDrawMask(RTEST(arg)\n\t ? cocos2d::PhysicsWorld::DEBUGDRAW_ALL\n\t : cocos2d::PhysicsWorld::DEBUGDRAW_NONE);\n return arg;\n}\n\n\/\/\/ @method #background_color=(color)\n\/\/\/ Set background color for scene.\n\/\/\/ @param color [Color] background color for scene.\n\nstatic VALUE\nscene_background_color_set(VALUE rcv, SEL sel, VALUE val)\n{\n SCENE(rcv)->setBackgroundColor(rb_any_to_cccolor3(val));\n return val;\n}\n\nextern \"C\"\nvoid\nInit_Layer(void)\n{\n rb_cScene = rb_define_class_under(rb_mMC, \"Scene\", rb_cNode);\n \/\/ rb_register_cocos2d_object_finalizer(rb_cScene); removed because rb_cScene inherits rb_cNode and it already has finalizer.\n\n rb_define_singleton_method(rb_cScene, \"alloc\", scene_alloc, 0);\n rb_define_method(rb_cScene, \"initialize\", scene_initialize, 0);\n rb_define_method(rb_cScene, \"start_update\", scene_start_update, 0);\n rb_define_method(rb_cScene, \"stop_update\", scene_stop_update, 0);\n rb_define_method(rb_cScene, \"update\", scene_update, 1);\n rb_define_method(rb_cScene, \"on_touch_begin\", scene_on_touch_begin, 0);\n rb_define_method(rb_cScene, \"on_touch_end\", scene_on_touch_end, 0);\n rb_define_method(rb_cScene, \"on_touch_move\", scene_on_touch_move, 0);\n rb_define_method(rb_cScene, \"on_touch_cancel\", scene_on_touch_cancel, 0);\n rb_define_method(rb_cScene, \"on_accelerate\", scene_on_accelerate, 0);\n rb_define_method(rb_cScene, \"on_contact_begin\", scene_on_contact_begin, 0);\n rb_define_method(rb_cScene, \"gravity\", scene_gravity, 0);\n rb_define_method(rb_cScene, \"gravity=\", scene_gravity_set, 1);\n rb_define_method(rb_cScene, \"debug_physics?\", scene_debug_physics, 0);\n rb_define_method(rb_cScene, \"debug_physics=\", scene_debug_physics_set, 1);\n rb_define_method(rb_cScene, \"background_color=\", scene_background_color_set, 1);\n rb_define_method(rb_cScene, \"color=\", scene_background_color_set, 1); \/\/ depricated\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n level.cpp - description\n -------------------\n begin : mar avr 15 2003\n copyright : (C) 2003 by Michael CATANZARITI\n email : mcatan@free.fr\n ***************************************************************************\/\n\n\/***************************************************************************\n * Copyright (C) The Apache Software Foundation. All rights reserved. *\n * *\n * This software is published under the terms of the Apache Software *\n * License version 1.1, a copy of which has been included with this *\n * distribution in the LICENSE.txt file. *\n ***************************************************************************\/\n\n#include <log4cxx\/level.h>\n#include <log4cxx\/helpers\/stringhelper.h>\n \nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\n\nIMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass)\n\nconst LevelPtr Level::OFF(new Level(Level::OFF_INT, _T(\"OFF\"), 0));\nconst LevelPtr Level::FATAL(new Level(Level::FATAL_INT, _T(\"FATAL\"), 0));\nconst LevelPtr Level::ERROR(new Level(Level::ERROR_INT, _T(\"ERROR\"), 3));\nconst LevelPtr Level::WARN(new Level(Level::WARN_INT, _T(\"WARN\"), 4));\nconst LevelPtr Level::INFO(new Level(Level::INFO_INT, _T(\"INFO\"), 6));\nconst LevelPtr Level::DEBUG(new Level(Level::DEBUG_INT, _T(\"DEBUG\"), 7));\nconst LevelPtr Level::ALL(new Level(Level::ALL_INT, _T(\"ALL\"), 7));\n\nLevel::Level(int level, const String& levelStr, int syslogEquivalent)\n: level(level), levelStr(levelStr), syslogEquivalent(syslogEquivalent)\n{\n}\n\n\nconst LevelPtr& Level::toLevel(const String& sArg)\n{\n return toLevel(sArg, Level::DEBUG);\n}\n\nconst LevelPtr& Level::toLevel(int val)\n{\n return toLevel(val, Level::DEBUG);\n}\n\nconst LevelPtr& Level::toLevel(int val, const LevelPtr& defaultLevel)\n{\n switch(val)\n {\n case ALL_INT: return ALL;\n case DEBUG_INT: return DEBUG;\n case INFO_INT: return INFO;\n case WARN_INT: return WARN;\n case ERROR_INT: return ERROR;\n case FATAL_INT: return FATAL;\n case OFF_INT: return OFF;\n default: return defaultLevel;\n }\n}\n\nconst LevelPtr& Level::toLevel(const String& sArg, const LevelPtr& defaultLevel)\n{\n if (sArg.empty())\n {\n return defaultLevel;\n }\n\n String s = StringHelper::toUpperCase(sArg);\n\n if(s == (_T(\"ALL\"))) return ALL;\n if(s == (_T(\"DEBUG\"))) return DEBUG;\n if(s == (_T(\"INFO\"))) return INFO;\n if(s == (_T(\"WARN\"))) return WARN;\n if(s == (_T(\"ERROR\"))) return ERROR;\n if(s == (_T(\"FATAL\"))) return FATAL;\n if(s == (_T(\"OFF\"))) return OFF;\n \n return defaultLevel;\n}\n\nbool Level::equals(const LevelPtr& level) const\n{\n\treturn (this->level == level->level);\n}\n\nint Level::getSyslogEquivalent() const\n{\n\treturn syslogEquivalent;\n}\n\nbool Level::isGreaterOrEqual(const LevelPtr& level) const\n{\n return this->level >= level->level;\n}\n\nconst String& Level::toString() const\n{\n\treturn levelStr;\n}\n\nint Level::toInt() const\n{\n\treturn level;\n}\n\nconst LevelPtr& Level::getAllLevel()\n{\n\treturn ALL;\n}\n\nconst LevelPtr& Level::getFatalLevel()\n{\n\treturn FATAL;\n}\n\nconst LevelPtr& Level::getErrorLevel()\n{\n\treturn ERROR;\n}\n\nconst LevelPtr& Level::getWarnLevel()\n{\n\treturn WARN;\n}\n\nconst LevelPtr& Level::getInfoLevel()\n{\n\treturn INFO;\n}\n\nconst LevelPtr& Level::getDebugLevel()\n{\n\treturn DEBUG;\n}\n\nconst LevelPtr& Level::getOffLevel()\n{\n\treturn OFF;\n}\n\n\n\n<commit_msg>removed useless methods<commit_after>\/***************************************************************************\n level.cpp - description\n -------------------\n begin : mar avr 15 2003\n copyright : (C) 2003 by Michael CATANZARITI\n email : mcatan@free.fr\n ***************************************************************************\/\n\n\/***************************************************************************\n * Copyright (C) The Apache Software Foundation. All rights reserved. *\n * *\n * This software is published under the terms of the Apache Software *\n * License version 1.1, a copy of which has been included with this *\n * distribution in the LICENSE.txt file. *\n ***************************************************************************\/\n\n#include <log4cxx\/level.h>\n#include <log4cxx\/helpers\/stringhelper.h>\n \nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\n\nIMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass)\n\nconst LevelPtr Level::OFF(new Level(Level::OFF_INT, _T(\"OFF\"), 0));\nconst LevelPtr Level::FATAL(new Level(Level::FATAL_INT, _T(\"FATAL\"), 0));\nconst LevelPtr Level::ERROR(new Level(Level::ERROR_INT, _T(\"ERROR\"), 3));\nconst LevelPtr Level::WARN(new Level(Level::WARN_INT, _T(\"WARN\"), 4));\nconst LevelPtr Level::INFO(new Level(Level::INFO_INT, _T(\"INFO\"), 6));\nconst LevelPtr Level::DEBUG(new Level(Level::DEBUG_INT, _T(\"DEBUG\"), 7));\nconst LevelPtr Level::ALL(new Level(Level::ALL_INT, _T(\"ALL\"), 7));\n\nLevel::Level(int level, const String& levelStr, int syslogEquivalent)\n: level(level), levelStr(levelStr), syslogEquivalent(syslogEquivalent)\n{\n}\n\n\nconst LevelPtr& Level::toLevel(const String& sArg)\n{\n return toLevel(sArg, Level::DEBUG);\n}\n\nconst LevelPtr& Level::toLevel(int val)\n{\n return toLevel(val, Level::DEBUG);\n}\n\nconst LevelPtr& Level::toLevel(int val, const LevelPtr& defaultLevel)\n{\n switch(val)\n {\n case ALL_INT: return ALL;\n case DEBUG_INT: return DEBUG;\n case INFO_INT: return INFO;\n case WARN_INT: return WARN;\n case ERROR_INT: return ERROR;\n case FATAL_INT: return FATAL;\n case OFF_INT: return OFF;\n default: return defaultLevel;\n }\n}\n\nconst LevelPtr& Level::toLevel(const String& sArg, const LevelPtr& defaultLevel)\n{\n if (sArg.empty())\n {\n return defaultLevel;\n }\n\n String s = StringHelper::toUpperCase(sArg);\n\n if(s == (_T(\"ALL\"))) return ALL;\n if(s == (_T(\"DEBUG\"))) return DEBUG;\n if(s == (_T(\"INFO\"))) return INFO;\n if(s == (_T(\"WARN\"))) return WARN;\n if(s == (_T(\"ERROR\"))) return ERROR;\n if(s == (_T(\"FATAL\"))) return FATAL;\n if(s == (_T(\"OFF\"))) return OFF;\n \n return defaultLevel;\n}\n\nbool Level::equals(const LevelPtr& level) const\n{\n\treturn (this->level == level->level);\n}\n\nint Level::getSyslogEquivalent() const\n{\n\treturn syslogEquivalent;\n}\n\nbool Level::isGreaterOrEqual(const LevelPtr& level) const\n{\n return this->level >= level->level;\n}\n\nconst String& Level::toString() const\n{\n\treturn levelStr;\n}\n\nint Level::toInt() const\n{\n\treturn level;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * JSDX Framework\n *\n * Copyright(c) 2012 Fred Chien <fred@mandice.com>\n *\n *\/\n\n#include <v8.h>\n#include <node.h>\n#include <string.h>\n#include <clutter\/clutter.h>\n\n#include \"jsdx_toolkit.hpp\"\n#include \"actor.hpp\"\n#include \"texture.hpp\"\n#include \"media.hpp\"\n\nnamespace JSDXToolkit {\n \n\tusing namespace node;\n\tusing namespace v8;\n\n\tMedia::Media() : Texture() {\n\n\t\tnotify_state_cb = NULL;\n\t\tnotify_buffering_cb = NULL;\n\t\tsignal_eos_cb = NULL;\n\t\tsignal_error_cb = NULL;\n\t}\n\n\tvoid Media::PrototypeMethodsInit(Handle<FunctionTemplate> constructor_template)\n\t{\n\t\tHandleScope scope;\n\n\t\tconstructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol(\"playing\"), Media::PlayingGetter, Media::PlayingSetter);\n\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"loadFile\", Media::LoadFile);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"loadFileURI\", Media::LoadFileURI);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"play\", Media::Play);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"pause\", Media::Pause);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"setVolume\", Media::SetVolume);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getVolume\", Media::GetVolume);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"setProgress\", Media::SetProgress);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getProgress\", Media::GetProgress);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getBufferFill\", Media::GetBufferFill);\n\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"on\", Media::On);\n\t}\n\n\t\/* Accessors *\/\n\tHandle<Value> Media::PlayingGetter(Local<String> name, const AccessorInfo& info)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(info.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tBoolean::New(clutter_media_get_playing(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tvoid Media::PlayingSetter(Local<String> name, Local<Value> value, const AccessorInfo& info)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (value->IsBoolean()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(info.This())->_actor;\n\n\t\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), value->ToBoolean()->Value());\n\t\t}\n\t}\n\n\t\/* Methods *\/\n\tHandle<Value> Media::LoadFile(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsString()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_filename(CLUTTER_MEDIA(instance), *String::Utf8Value(args[0]->ToString()));\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::LoadFileURI(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsString()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_uri(CLUTTER_MEDIA(instance), *String::Utf8Value(args[0]->ToString()));\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::Play(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), TRUE);\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::Pause(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), FALSE);\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::SetVolume(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsNumber()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_audio_volume(CLUTTER_MEDIA(instance), args[0]->NumberValue());\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::GetVolume(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_audio_volume(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::SetProgress(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsNumber()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_progress(CLUTTER_MEDIA(instance), args[0]->NumberValue());\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::GetProgress(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_progress(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::GetBufferFill(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_buffer_fill(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::On(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\t\tLocal<Value> Event;\n\t\tLocal<Value> Options;\n\t\tLocal<Value> Callback;\n\n\t\tMedia *media = ObjectWrap::Unwrap<Media>(args.This());\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\/* Check arguments *\/\n\t\tif (args.Length() > 3) {\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"too much arguments\")));\n\t\t} else if (args.Length() < 2) {\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"too few arguments\")));\n\t\t}\n\n\t\tif (args.Length() == 2) {\n\t\t\tEvent = args[0];\n\t\t\tCallback = args[1];\n\t\t} else if (args.Length() == 3) {\n\t\t\tEvent = args[0];\n\t\t\tOptions = args[1];\n\t\t\tCallback = args[2];\n\n\t\t\tif (!Options->IsObject())\n\t\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\t\tString::New(\"options parameter must be object\")));\n\t\t}\n\n\t\tif (!Event->IsString())\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"first arguments must be string\")));\n\n\t\tif (!Callback->IsFunction())\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"require callback function\")));\n\n\t\tif (strcmp(*String::Utf8Value(Event->ToString()), \"state\") == 0) {\n\n\t\t\tif (!media->notify_state_cb) {\n\t\t\t\tmedia->notify_state_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->notify_state_cb->Holder.Dispose();\n\t\t\t\tmedia->notify_state_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->notify_state_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->notify_state_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tg_signal_connect(G_OBJECT(instance), \"notify::playing\", G_CALLBACK(Media::_NotifyStateCallback), (gpointer)media->notify_state_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"buffering\") == 0) {\n\n\t\t\tif (!media->notify_buffering_cb) {\n\t\t\t\tmedia->notify_buffering_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->notify_buffering_cb->Holder.Dispose();\n\t\t\t\tmedia->notify_buffering_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->notify_buffering_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->notify_buffering_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tg_signal_connect(G_OBJECT(instance), \"notify::buffer-fill\", G_CALLBACK(Media::_NotifyBufferingCallback), (gpointer)media->notify_buffering_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"eos\") == 0) {\n\n\t\t\tif (!media->signal_eos_cb) {\n\t\t\t\tmedia->signal_eos_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->signal_eos_cb->Holder.Dispose();\n\t\t\t\tmedia->signal_eos_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->signal_eos_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->signal_eos_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tg_signal_connect(G_OBJECT(instance), \"eos\", G_CALLBACK(Media::_SignalEOSCallback), (gpointer)media->signal_eos_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"error\") == 0) {\n\n\t\t\tif (!media->signal_error_cb) {\n\t\t\t\tmedia->signal_error_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->signal_error_cb->Holder.Dispose();\n\t\t\t\tmedia->signal_error_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->signal_error_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->signal_error_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tg_signal_connect(G_OBJECT(instance), \"error\", G_CALLBACK(Media::_SignalErrorCallback), (gpointer)media->signal_error_cb);\n\t\t} else {\n\t\t\tTexture::On(args);\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\t\/* Signal callback *\/\n\tvoid Media::_NotifyStateCallback(GObject *object, GParamSpec *pspec, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_NotifyBufferingCallback(GObject *object, GParamSpec *pspec, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_SignalEOSCallback(ClutterMedia *media, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_SignalErrorCallback(ClutterMedia *media, GError *error, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n}\n<commit_msg>allow event handler of media actor to be registered once only<commit_after>\/*\n * JSDX Framework\n *\n * Copyright(c) 2012 Fred Chien <fred@mandice.com>\n *\n *\/\n\n#include <v8.h>\n#include <node.h>\n#include <string.h>\n#include <clutter\/clutter.h>\n\n#include \"jsdx_toolkit.hpp\"\n#include \"actor.hpp\"\n#include \"texture.hpp\"\n#include \"media.hpp\"\n\nnamespace JSDXToolkit {\n \n\tusing namespace node;\n\tusing namespace v8;\n\n\tMedia::Media() : Texture() {\n\n\t\tnotify_state_cb = NULL;\n\t\tnotify_buffering_cb = NULL;\n\t\tsignal_eos_cb = NULL;\n\t\tsignal_error_cb = NULL;\n\t}\n\n\tvoid Media::PrototypeMethodsInit(Handle<FunctionTemplate> constructor_template)\n\t{\n\t\tHandleScope scope;\n\n\t\tconstructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol(\"playing\"), Media::PlayingGetter, Media::PlayingSetter);\n\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"loadFile\", Media::LoadFile);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"loadFileURI\", Media::LoadFileURI);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"play\", Media::Play);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"pause\", Media::Pause);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"setVolume\", Media::SetVolume);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getVolume\", Media::GetVolume);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"setProgress\", Media::SetProgress);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getProgress\", Media::GetProgress);\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"getBufferFill\", Media::GetBufferFill);\n\n\t\tNODE_SET_PROTOTYPE_METHOD(constructor_template, \"on\", Media::On);\n\t}\n\n\t\/* Accessors *\/\n\tHandle<Value> Media::PlayingGetter(Local<String> name, const AccessorInfo& info)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(info.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tBoolean::New(clutter_media_get_playing(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tvoid Media::PlayingSetter(Local<String> name, Local<Value> value, const AccessorInfo& info)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (value->IsBoolean()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(info.This())->_actor;\n\n\t\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), value->ToBoolean()->Value());\n\t\t}\n\t}\n\n\t\/* Methods *\/\n\tHandle<Value> Media::LoadFile(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsString()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_filename(CLUTTER_MEDIA(instance), *String::Utf8Value(args[0]->ToString()));\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::LoadFileURI(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsString()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_uri(CLUTTER_MEDIA(instance), *String::Utf8Value(args[0]->ToString()));\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::Play(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), TRUE);\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::Pause(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\tclutter_media_set_playing(CLUTTER_MEDIA(instance), FALSE);\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::SetVolume(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsNumber()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_audio_volume(CLUTTER_MEDIA(instance), args[0]->NumberValue());\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::GetVolume(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_audio_volume(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::SetProgress(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tif (args[0]->IsNumber()) {\n\t\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\tclutter_media_set_progress(CLUTTER_MEDIA(instance), args[0]->NumberValue());\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\tHandle<Value> Media::GetProgress(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_progress(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::GetBufferFill(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\treturn scope.Close(\n\t\t\tNumber::New(clutter_media_get_buffer_fill(CLUTTER_MEDIA(instance)))\n\t\t);\n\t}\n\n\tHandle<Value> Media::On(const Arguments &args)\n\t{\n\t\tHandleScope scope;\n\t\tLocal<Value> Event;\n\t\tLocal<Value> Options;\n\t\tLocal<Value> Callback;\n\n\t\tMedia *media = ObjectWrap::Unwrap<Media>(args.This());\n\t\tClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor;\n\n\t\t\/* Check arguments *\/\n\t\tif (args.Length() > 3) {\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"too much arguments\")));\n\t\t} else if (args.Length() < 2) {\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"too few arguments\")));\n\t\t}\n\n\t\tif (args.Length() == 2) {\n\t\t\tEvent = args[0];\n\t\t\tCallback = args[1];\n\t\t} else if (args.Length() == 3) {\n\t\t\tEvent = args[0];\n\t\t\tOptions = args[1];\n\t\t\tCallback = args[2];\n\n\t\t\tif (!Options->IsObject())\n\t\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\t\tString::New(\"options parameter must be object\")));\n\t\t}\n\n\t\tif (!Event->IsString())\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"first arguments must be string\")));\n\n\t\tif (!Callback->IsFunction())\n\t\t\treturn ThrowException(Exception::TypeError(\n\t\t\t\tString::New(\"require callback function\")));\n\n\t\tbool reg = FALSE;\n\t\tif (strcmp(*String::Utf8Value(Event->ToString()), \"state\") == 0) {\n\n\t\t\tif (!media->notify_state_cb) {\n\t\t\t\treg = TRUE;\n\t\t\t\tmedia->notify_state_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->notify_state_cb->Holder.Dispose();\n\t\t\t\tmedia->notify_state_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->notify_state_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->notify_state_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tif (reg)\n\t\t\t\tg_signal_connect(G_OBJECT(instance), \"notify::playing\", G_CALLBACK(Media::_NotifyStateCallback), (gpointer)media->notify_state_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"buffering\") == 0) {\n\n\t\t\tif (!media->notify_buffering_cb) {\n\t\t\t\treg = TRUE;\n\t\t\t\tmedia->notify_buffering_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->notify_buffering_cb->Holder.Dispose();\n\t\t\t\tmedia->notify_buffering_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->notify_buffering_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->notify_buffering_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tif (reg)\n\t\t\t\tg_signal_connect(G_OBJECT(instance), \"notify::buffer-fill\", G_CALLBACK(Media::_NotifyBufferingCallback), (gpointer)media->notify_buffering_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"eos\") == 0) {\n\n\t\t\tif (!media->signal_eos_cb) {\n\t\t\t\treg = TRUE;\n\t\t\t\tmedia->signal_eos_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->signal_eos_cb->Holder.Dispose();\n\t\t\t\tmedia->signal_eos_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->signal_eos_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->signal_eos_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tif (reg)\n\t\t\t\tg_signal_connect(G_OBJECT(instance), \"eos\", G_CALLBACK(Media::_SignalEOSCallback), (gpointer)media->signal_eos_cb);\n\n\t\t} else if (strcmp(*String::Utf8Value(Event->ToString()), \"error\") == 0) {\n\n\t\t\tif (!media->signal_error_cb) {\n\t\t\t\treg = TRUE;\n\t\t\t\tmedia->signal_error_cb = new NodeCallback;\n\t\t\t} else {\n\t\t\t\tmedia->signal_error_cb->Holder.Dispose();\n\t\t\t\tmedia->signal_error_cb->cb.Dispose();\n\t\t\t}\n\n\t\t\tmedia->signal_error_cb->Holder = Persistent<Object>::New(args.Holder());\n\t\t\tmedia->signal_error_cb->cb = Persistent<Function>::New(Handle<Function>::Cast(Callback));\n\n\t\t\tif (reg)\n\t\t\t\tg_signal_connect(G_OBJECT(instance), \"error\", G_CALLBACK(Media::_SignalErrorCallback), (gpointer)media->signal_error_cb);\n\n\t\t} else {\n\t\t\tTexture::On(args);\n\t\t}\n\n\t\treturn args.This();\n\t}\n\n\t\/* Signal callback *\/\n\tvoid Media::_NotifyStateCallback(GObject *object, GParamSpec *pspec, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_NotifyBufferingCallback(GObject *object, GParamSpec *pspec, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_SignalEOSCallback(ClutterMedia *media, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n\n\tvoid Media::_SignalErrorCallback(ClutterMedia *media, GError *error, gpointer user_data)\n\t{\n\t\tNodeCallback *cb = (NodeCallback *)user_data;\n\n\t\tcb->cb->Call(cb->Holder, 0, 0);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020 INRIA\n *\/\n\n#include \"eigenpy\/numpy.hpp\"\n\nnamespace eigenpy\n{\n void import_numpy()\n {\n if(_import_array() < 0)\n {\n PyErr_Print();\n PyErr_SetString(PyExc_ImportError, \"numpy.core.multiarray failed to import\");\n }\n }\n\n int PyArray_TypeNum(PyTypeObject * type)\n {\n return PyArray_TypeNumFromName(const_cast<char*>(type->tp_name));\n }\n\n#if defined _WIN32 || defined __CYGWIN__\n\n PyObject* call_PyArray_SimpleNew(int nd, npy_intp * shape, int np_type)\n {\n return PyArray_SimpleNew(nd,shape,np_type);\n }\n\n PyObject* call_PyArray_New(PyTypeObject * py_type_ptr, int nd, npy_intp * shape, int np_type, void * data_ptr, int options)\n {\n return PyArray_New(py_type_ptr,nd,shape,np_type,NULL,data_ptr,0,options,NULL);\n }\n \n int call_PyArray_ObjectType(PyObject * obj, int val)\n {\n return PyArray_ObjectType(obj,val);\n }\n\n PyTypeObject * getPyArrayType() { return &PyArray_Type; }\n \n int call_PyArray_TypeNumFromName(const std::string & name)\n {\n return getPyArrayType(name.c_str());\n }\n\n#endif\n}\n<commit_msg>core: fix Win32 issue<commit_after>\/*\n * Copyright 2020 INRIA\n *\/\n\n#include \"eigenpy\/numpy.hpp\"\n\nnamespace eigenpy\n{\n void import_numpy()\n {\n if(_import_array() < 0)\n {\n PyErr_Print();\n PyErr_SetString(PyExc_ImportError, \"numpy.core.multiarray failed to import\");\n }\n }\n\n int PyArray_TypeNum(PyTypeObject * type)\n {\n return PyArray_TypeNumFromName(const_cast<char*>(type->tp_name));\n }\n\n#if defined _WIN32 || defined __CYGWIN__\n\n PyObject* call_PyArray_SimpleNew(int nd, npy_intp * shape, int np_type)\n {\n return PyArray_SimpleNew(nd,shape,np_type);\n }\n\n PyObject* call_PyArray_New(PyTypeObject * py_type_ptr, int nd, npy_intp * shape, int np_type, void * data_ptr, int options)\n {\n return PyArray_New(py_type_ptr,nd,shape,np_type,NULL,data_ptr,0,options,NULL);\n }\n \n int call_PyArray_ObjectType(PyObject * obj, int val)\n {\n return PyArray_ObjectType(obj,val);\n }\n\n PyTypeObject * getPyArrayType() { return &PyArray_Type; }\n \n int call_PyArray_TypeNumFromName(const std::string & name)\n {\n return PyArray_TypeNumFromName(name.c_str());\n }\n\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ofApp.h\"\n\n#include \"Widget.hpp\"\n#include \"Label.hpp\"\n#include \"Button.hpp\"\n#include \"HorizontalPanel.hpp\"\n#include \"VerticalPanel.hpp\"\n\n\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n fonts.push_back(new ofTrueTypeFont());\n fonts.back()->load(\"HelveticaNeue\", 32);\n Panel *basePanel = new VerticalPanel(10, 10);\n \n basePanel->addWidget(new Label(\"hello\",\n fonts.back()));\n \n Panel *innerPanel = new HorizontalPanel();\n \n innerPanel->addWidget(\n new Button(\"Button1\",\n fonts.back(),\n [](){std::cout << \"B1\" << std::endl;}));\n innerPanel->addWidget(\n new Button(\"Button2\",\n fonts.back(),\n [](){std::cout << \"B2\" << std::endl;}));\n \n \n basePanel->addWidget(innerPanel);\n \n baseWidget = basePanel;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n baseWidget->draw();\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n baseWidget->mouseClicked(x,y);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<commit_msg>changed the font so it works on windows<commit_after>#include \"ofApp.h\"\n\n#include \"Widget.hpp\"\n#include \"Label.hpp\"\n#include \"Button.hpp\"\n#include \"HorizontalPanel.hpp\"\n#include \"VerticalPanel.hpp\"\n\n\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n fonts.push_back(new ofTrueTypeFont());\n fonts.back()->load(\"Arial\", 32);\n Panel *basePanel = new VerticalPanel(10, 10);\n \n basePanel->addWidget(new Label(\"hello\",\n fonts.back()));\n \n Panel *innerPanel = new HorizontalPanel();\n \n innerPanel->addWidget(\n new Button(\"Button1\",\n fonts.back(),\n [](){std::cout << \"B1\" << std::endl;}));\n innerPanel->addWidget(\n new Button(\"Button2\",\n fonts.back(),\n [](){std::cout << \"B2\" << std::endl;}));\n \n \n basePanel->addWidget(innerPanel);\n \n baseWidget = basePanel;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n baseWidget->draw();\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n baseWidget->mouseClicked(x,y);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"posit.h\"\n\n#include <cstdio>\n#include <cmath>\n\n#define POW2(n) \\\n (1 << n)\n\nPOSIT_UTYPE Posit::buildMask(unsigned size)\n{\n return POSIT_MASK << (POSIT_SIZE - size);\n}\n\nPosit::Posit(POSIT_UTYPE bits, unsigned nbits, unsigned es, bool nan) :\n mBits(bits),\n mNbits(nbits),\n mEs(es),\n mNan(nan)\n{\n}\n\nPosit::Posit(unsigned nbits, unsigned es, bool nan) :\n Posit(0, nbits, es, nan)\n{\n}\n\nPosit::Posit(unsigned nbits, unsigned es) :\n Posit(nbits, es, false)\n{\n}\n\nbool Posit::isZero()\n{\n return mBits == POSIT_ZERO;\n}\n\nbool Posit::isOne()\n{\n return mBits == POSIT_ONE || mBits == POSIT_MONE;\n}\n\nbool Posit::isInf()\n{\n return mBits == POSIT_INF;\n}\n\nbool Posit::isNeg()\n{\n return (POSIT_STYPE)mBits < 0 && mBits != POSIT_INF;\n}\n\nbool Posit::isNan()\n{\n return mNan;\n}\n\nunsigned Posit::nbits()\n{\n return mNbits;\n}\n\nunsigned Posit::rs()\n{\n signed lastBit = -1;\n unsigned rs = 0;\n\n \/\/ find a bit that changes, ignoring sign bit\n for (signed i = POSIT_SIZE - 2; i >= POSIT_SIZE - mNbits; i--) {\n bool bit = (mBits >> i) & 1;\n rs++;\n\n if (bit != lastBit && lastBit >= 0) {\n break;\n }\n\n lastBit = bit;\n }\n\n return rs;\n}\n\nunsigned Posit::es()\n{\n unsigned efs = mNbits - 1 - rs();\n unsigned es = mEs < efs ? mEs : efs;\n\n return (es >= 0 ? es : 0);\n}\n\nunsigned Posit::fs()\n{\n return mNbits - 1 - rs() - es();\n}\n\nunsigned Posit::useed()\n{\n return POW2(POW2(mEs));\n}\n\nsigned Posit::regime()\n{\n POSIT_UTYPE bits = (isNeg() ? neg().mBits : mBits) << 1;\n POSIT_UTYPE himask = 1 << (POSIT_SIZE - 1);\n signed r = 0;\n\n \/\/ out of bounds regime for error handling\n if (isZero()) {\n return -mNbits + 1;\n } else if (isInf()) {\n return mNbits - 1;\n }\n\n if (bits & himask) { \/\/ >0\n while (1) {\n bits <<= 1;\n if (!(bits & himask))\n break;\n r++;\n }\n } else { \/\/ <=0\n while (1) {\n bits <<= 1;\n r--;\n if (bits & himask)\n break;\n }\n }\n\n return r;\n}\n\nPOSIT_UTYPE Posit::exponent()\n{\n POSIT_UTYPE expBits = (mBits & (buildMask(mEs) >> (1 + rs())));\n\n return expBits >> (POSIT_SIZE - mNbits + fs());\n}\n\nPOSIT_UTYPE Posit::fraction()\n{\n POSIT_UTYPE fracBits = (mBits & (buildMask(fs()) >> (1 + rs() + es())));\n\n return fracBits >> (POSIT_SIZE - mNbits);\n}\n\nPosit Posit::zero()\n{\n return Posit(POSIT_ZERO, mNbits, mEs, false);\n}\n\nPosit Posit::one()\n{\n return Posit(POSIT_ONE, mNbits, mEs, false);\n}\n\nPosit Posit::inf()\n{\n return Posit(POSIT_INF, mNbits, mEs, false);\n}\n\nPosit Posit::nan()\n{\n return Posit(mNbits, mEs, true);\n}\n\nPosit Posit::neg()\n{\n Posit p = Posit(mNbits, mEs);\n POSIT_UTYPE mask = buildMask(mNbits);\n\n \/\/ reverse all bits and add one\n p.mBits = ((mBits ^ POSIT_MASK) + 1) & mask;\n\n return p;\n}\n\nPosit Posit::rec()\n{\n Posit p = Posit(mNbits, mEs);\n POSIT_UTYPE mask = buildMask(mNbits);\n\n \/\/ reverse all bits but the first one and add one\n p.mBits = ((mBits ^ (POSIT_MASK >> 1)) + 1) & mask;\n\n return p;\n}\n\nPosit Posit::add(Posit& p)\n{\n \/\/ fast exit\n if (isZero()) {\n return p;\n } else if (p.isZero()) {\n return *this;\n } else if (isInf() && p.isInf()) {\n return nan();\n } else if (isInf() || p.isInf()) {\n return inf();\n } else if (neg().eq(p)) {\n return zero();\n }\n\n \/\/ TODO implement\n return *this;\n}\n\nPosit Posit::sub(Posit& p)\n{\n \/\/ no loss on negation\n Posit np = p.neg();\n\n return add(np);\n}\n\nPosit Posit::mul(Posit& p)\n{\n \/\/ fast exit\n if (isZero()) {\n return (p.isInf() ? nan() : zero());\n } else if (p.isZero()) {\n return (isInf() ? nan() : zero());\n } else if (isOne()) {\n return (isNeg() ? p.neg() : p);\n } else if (p.isOne()) {\n return (p.isNeg() ? neg() : *this);\n } else if (isInf() || p.isInf()) {\n return inf();\n } else if (rec().eq(p)) {\n return one();\n } else if (rec().neg().eq(p)) {\n return one().neg();\n }\n\n \/\/ TODO implement\n return *this;\n}\n\nPosit Posit::div(Posit& p)\n{\n \/\/ no loss on reciprocation!\n Posit rp = p.rec();\n\n return mul(rp);\n}\n\nbool Posit::eq(Posit& p)\n{\n return mBits == p.mBits;\n}\n\nbool Posit::gt(Posit& p)\n{\n if (isInf() || p.isInf()) {\n return false;\n }\n\n return mBits > p.mBits;\n}\n\nbool Posit::ge(Posit& p)\n{\n return gt(p) || eq(p);\n}\n\nbool Posit::lt(Posit& p)\n{\n return !gt(p) && !eq(p);\n}\n\nbool Posit::le(Posit& p)\n{\n return !gt(p);\n}\n\nvoid Posit::set(int n)\n{\n \/\/ TODO implement\n}\n\nvoid Posit::set(float n)\n{\n \/\/ TODO implement\n}\n\nvoid Posit::set(double n)\n{\n \/\/ TODO implement\n}\n\nint Posit::getInt()\n{\n return (int)roundf(getFloat());\n}\n\nfloat Posit::getFloat()\n{\n if (isZero()) {\n return 0.f;\n } else if (isInf()) {\n return 1.f \/ 0.f;\n }\n\n Posit p = (isNeg() ? neg() : *this);\n\n return (isNeg() ? -1 : 1) *\n powf(p.useed(), p.regime()) *\n POW2(p.exponent()) *\n (1 + (float)p.fraction() \/ POW2(p.fs()));\n}\n\ndouble Posit::getDouble()\n{\n if (isZero()) {\n return 0.0;\n } else if (isInf()) {\n return 1.0 \/ 0.0;\n }\n\n Posit p = (isNeg() ? neg() : *this);\n\n return (isNeg() ? -1 : 1) *\n pow(p.useed(), p.regime()) *\n POW2(p.exponent()) *\n (1 + (double)p.fraction() \/ POW2(p.fs()));\n}\n\nvoid Posit::setBits(POSIT_UTYPE bits)\n{\n mBits = bits << (POSIT_SIZE - mNbits);\n}\n\nPOSIT_UTYPE Posit::getBits()\n{\n return mBits >> (POSIT_SIZE - mNbits);\n}\n\nvoid Posit::print()\n{\n Posit p = isNeg() || isInf() ? neg() : *this;\n\n printf(\"{%d, %d} \", mNbits, mEs);\n\n for (signed i = POSIT_SIZE - 1; i >= POSIT_SIZE - mNbits; i--) {\n printf(\"%d\", (mBits >> i) & 1);\n }\n\n printf(\" (%d) -> \", regime());\n printf(isNeg() || isInf() ? \"-\" : \"+\");\n\n for (signed i = POSIT_SIZE - 2; i >= POSIT_SIZE - mNbits; i--) {\n printf(\"%d\", (p.mBits >> i) & 1);\n\n if (i != POSIT_SIZE - mNbits &&\n (((unsigned)i == (POSIT_SIZE - 1 - p.rs())) ||\n ((unsigned)i == (POSIT_SIZE - 1 - p.rs() - mEs)))) {\n printf(\" \");\n }\n }\n\n printf(\" = %lg\\n\", getDouble());\n}\n<commit_msg>lib: silence warnings<commit_after>#include \"posit.h\"\n\n#include <cstdio>\n#include <cmath>\n\n#define POW2(n) \\\n (1 << n)\n\nPOSIT_UTYPE Posit::buildMask(unsigned size)\n{\n return POSIT_MASK << (POSIT_SIZE - size);\n}\n\nPosit::Posit(POSIT_UTYPE bits, unsigned nbits, unsigned es, bool nan) :\n mBits(bits),\n mNbits(nbits),\n mEs(es),\n mNan(nan)\n{\n}\n\nPosit::Posit(unsigned nbits, unsigned es, bool nan) :\n Posit(0, nbits, es, nan)\n{\n}\n\nPosit::Posit(unsigned nbits, unsigned es) :\n Posit(nbits, es, false)\n{\n}\n\nbool Posit::isZero()\n{\n return mBits == POSIT_ZERO;\n}\n\nbool Posit::isOne()\n{\n return mBits == POSIT_ONE || mBits == POSIT_MONE;\n}\n\nbool Posit::isInf()\n{\n return mBits == POSIT_INF;\n}\n\nbool Posit::isNeg()\n{\n return (POSIT_STYPE)mBits < 0 && mBits != POSIT_INF;\n}\n\nbool Posit::isNan()\n{\n return mNan;\n}\n\nunsigned Posit::nbits()\n{\n return mNbits;\n}\n\nunsigned Posit::rs()\n{\n signed lastBit = -1;\n unsigned rs = 0;\n\n \/\/ find a bit that changes, ignoring sign bit\n for (signed i = POSIT_SIZE - 2; i >= (signed)(POSIT_SIZE - mNbits); i--) {\n bool bit = (mBits >> i) & 1;\n rs++;\n\n if (bit != lastBit && lastBit >= 0) {\n break;\n }\n\n lastBit = bit;\n }\n\n return rs;\n}\n\nunsigned Posit::es()\n{\n unsigned efs = mNbits - 1 - rs();\n unsigned es = mEs < efs ? mEs : efs;\n\n return (es >= 0 ? es : 0);\n}\n\nunsigned Posit::fs()\n{\n return mNbits - 1 - rs() - es();\n}\n\nunsigned Posit::useed()\n{\n return POW2(POW2(mEs));\n}\n\nsigned Posit::regime()\n{\n POSIT_UTYPE bits = (isNeg() ? neg().mBits : mBits) << 1;\n POSIT_UTYPE himask = 1 << (POSIT_SIZE - 1);\n signed r = 0;\n\n \/\/ out of bounds regime for error handling\n if (isZero()) {\n return -mNbits + 1;\n } else if (isInf()) {\n return mNbits - 1;\n }\n\n if (bits & himask) { \/\/ >0\n while (1) {\n bits <<= 1;\n if (!(bits & himask))\n break;\n r++;\n }\n } else { \/\/ <=0\n while (1) {\n bits <<= 1;\n r--;\n if (bits & himask)\n break;\n }\n }\n\n return r;\n}\n\nPOSIT_UTYPE Posit::exponent()\n{\n POSIT_UTYPE expBits = (mBits & (buildMask(mEs) >> (1 + rs())));\n\n return expBits >> (POSIT_SIZE - mNbits + fs());\n}\n\nPOSIT_UTYPE Posit::fraction()\n{\n POSIT_UTYPE fracBits = (mBits & (buildMask(fs()) >> (1 + rs() + es())));\n\n return fracBits >> (POSIT_SIZE - mNbits);\n}\n\nPosit Posit::zero()\n{\n return Posit(POSIT_ZERO, mNbits, mEs, false);\n}\n\nPosit Posit::one()\n{\n return Posit(POSIT_ONE, mNbits, mEs, false);\n}\n\nPosit Posit::inf()\n{\n return Posit(POSIT_INF, mNbits, mEs, false);\n}\n\nPosit Posit::nan()\n{\n return Posit(mNbits, mEs, true);\n}\n\nPosit Posit::neg()\n{\n Posit p = Posit(mNbits, mEs);\n POSIT_UTYPE mask = buildMask(mNbits);\n\n \/\/ reverse all bits and add one\n p.mBits = ((mBits ^ POSIT_MASK) + 1) & mask;\n\n return p;\n}\n\nPosit Posit::rec()\n{\n Posit p = Posit(mNbits, mEs);\n POSIT_UTYPE mask = buildMask(mNbits);\n\n \/\/ reverse all bits but the first one and add one\n p.mBits = ((mBits ^ (POSIT_MASK >> 1)) + 1) & mask;\n\n return p;\n}\n\nPosit Posit::add(Posit& p)\n{\n \/\/ fast exit\n if (isZero()) {\n return p;\n } else if (p.isZero()) {\n return *this;\n } else if (isInf() && p.isInf()) {\n return nan();\n } else if (isInf() || p.isInf()) {\n return inf();\n } else if (neg().eq(p)) {\n return zero();\n }\n\n \/\/ TODO implement\n return *this;\n}\n\nPosit Posit::sub(Posit& p)\n{\n \/\/ no loss on negation\n Posit np = p.neg();\n\n return add(np);\n}\n\nPosit Posit::mul(Posit& p)\n{\n \/\/ fast exit\n if (isZero()) {\n return (p.isInf() ? nan() : zero());\n } else if (p.isZero()) {\n return (isInf() ? nan() : zero());\n } else if (isOne()) {\n return (isNeg() ? p.neg() : p);\n } else if (p.isOne()) {\n return (p.isNeg() ? neg() : *this);\n } else if (isInf() || p.isInf()) {\n return inf();\n } else if (rec().eq(p)) {\n return one();\n } else if (rec().neg().eq(p)) {\n return one().neg();\n }\n\n \/\/ TODO implement\n return *this;\n}\n\nPosit Posit::div(Posit& p)\n{\n \/\/ no loss on reciprocation!\n Posit rp = p.rec();\n\n return mul(rp);\n}\n\nbool Posit::eq(Posit& p)\n{\n return mBits == p.mBits;\n}\n\nbool Posit::gt(Posit& p)\n{\n if (isInf() || p.isInf()) {\n return false;\n }\n\n return mBits > p.mBits;\n}\n\nbool Posit::ge(Posit& p)\n{\n return gt(p) || eq(p);\n}\n\nbool Posit::lt(Posit& p)\n{\n return !gt(p) && !eq(p);\n}\n\nbool Posit::le(Posit& p)\n{\n return !gt(p);\n}\n\nvoid Posit::set(int n)\n{\n \/\/ TODO implement\n}\n\nvoid Posit::set(float n)\n{\n \/\/ TODO implement\n}\n\nvoid Posit::set(double n)\n{\n \/\/ TODO implement\n}\n\nint Posit::getInt()\n{\n return (int)roundf(getFloat());\n}\n\nfloat Posit::getFloat()\n{\n if (isZero()) {\n return 0.f;\n } else if (isInf()) {\n return 1.f \/ 0.f;\n }\n\n Posit p = (isNeg() ? neg() : *this);\n\n return (isNeg() ? -1 : 1) *\n powf(p.useed(), p.regime()) *\n POW2(p.exponent()) *\n (1 + (float)p.fraction() \/ POW2(p.fs()));\n}\n\ndouble Posit::getDouble()\n{\n if (isZero()) {\n return 0.0;\n } else if (isInf()) {\n return 1.0 \/ 0.0;\n }\n\n Posit p = (isNeg() ? neg() : *this);\n\n return (isNeg() ? -1 : 1) *\n pow(p.useed(), p.regime()) *\n POW2(p.exponent()) *\n (1 + (double)p.fraction() \/ POW2(p.fs()));\n}\n\nvoid Posit::setBits(POSIT_UTYPE bits)\n{\n mBits = bits << (POSIT_SIZE - mNbits);\n}\n\nPOSIT_UTYPE Posit::getBits()\n{\n return mBits >> (POSIT_SIZE - mNbits);\n}\n\nvoid Posit::print()\n{\n Posit p = isNeg() || isInf() ? neg() : *this;\n\n printf(\"{%d, %d} \", mNbits, mEs);\n\n for (signed i = POSIT_SIZE - 1; i >= (signed)(POSIT_SIZE - mNbits); i--) {\n printf(\"%d\", (mBits >> i) & 1);\n }\n\n printf(\" (%d) -> \", regime());\n printf(isNeg() || isInf() ? \"-\" : \"+\");\n\n for (signed i = POSIT_SIZE - 2; i >= (signed)(POSIT_SIZE - mNbits); i--) {\n printf(\"%d\", (p.mBits >> i) & 1);\n\n if (i != (signed)(POSIT_SIZE - mNbits) &&\n (((unsigned)i == (POSIT_SIZE - 1 - p.rs())) ||\n ((unsigned)i == (POSIT_SIZE - 1 - p.rs() - mEs)))) {\n printf(\" \");\n }\n }\n\n printf(\" = %lg\\n\", getDouble());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"order.h\"\n\nOrder::Order(vector<Task> tasks, vector<Maitenance> maitenance_v){\n\n}\n\nint Order::get_exectime(){\n\treturn exec_t;\n}\n\nvector<Task_t> Order::get_tasks(){\n\treturn machine1.get_tasks();\n}\n\n\n\n\n\n\/*\nOrder::Order(){\n\n}\nOrder::Order(vector<Task_t> task_m1_v, vector<Task_t> task_m2_v, vector<Maitenance> maitenance_v){\n\tmachine1.set_id(1);\n\tmachine1.set_start(0);\n\tmachine1.set_stop(0);\n\tmachine2.set_id(2);\n\tint n = 0;\n\tunsigned int size = (task_m1_v.size() >= task_m2_v.size())?(task_m1_v.size()):(task_m2_v.size());\n\n\tfor(unsigned int i = 0; i < size; i++){\n\t\tif (task_m1_v.size() < i){\n\t\t\twhile(!machine1.add(task_m1_v[i+n], maitenance_v)){\n\t\t\t\ttask_m1_v.push_back(task_m1_v[i+n]);\n\t\t\t\tn++;\n\t\t\t}\n\t\t\tn = 0;\n\t\t}\n\n\t\tif (task_m2_v.size() < i){\n\t\t\tif( i == 0 ){\n\t\t\t\tmachine2.set_start(machine1.get_sop());\n\t\t\t\tmachine2.set_stop(machine1.get_sop());\n\t\t\t}\n\n\t\t\tif(machine1.get_sop() <= machine2.get_sop()) machine2.add(task_m2_v[i], maitenance_v);\n\t\t\telse machine2.addt(machine1.get_sop(), task_m2_v[i]);\n\t\t}\n\t}\n\n\tthis->exec_t = machine2.get_sop();\n}\n\nvoid Order::initialization(vector<int> O, vector<Task> task_v, vector<Maitenance> maitenance_v){\n\tmachine1.set_id(1);\n\tmachine1.set_start(0);\n\tmachine1.set_stop(0);\n\tmachine2.set_id(2);\n\tint n, tmp;\n\tfor (vector<int>::size_type i = 0; i < O.size(); i++){\n\t\t\/\/Machine 1\n\t\tn = 1;\n\t\twhile(!machine1.add(O[i], task_v, maitenance_v)){\n\t\t\ttmp = O[i];\n\t\t\tO[i] = O[i + n];\n\t\t\tO[i + n] = tmp;\n\t\t\tn++;\n\t\t}\n\t\t\/\/ Machine 2\n\t\tif( i == 0 ){\n\t\t\tmachine2.set_start(machine1.get_sop());\n\t\t\tmachine2.set_stop(machine1.get_sop());\n\t\t}\n\t\tif(machine1.get_sop() <= machine2.get_sop()){\n\t\t\tmachine2.add(O[i], task_v, maitenance_v);\n\t\t}else{\n\t\t\tmachine2.addt(machine1.get_sop(), O[i], task_v);\n\t\t}\n\t}\n\n\tthis->exec_t = machine2.get_sop();\n}\n*\/\n<commit_msg>Further order fixes<commit_after>#include \"order.h\"\n\nOrder::Order(vector<Task> tasks, vector<Maitenance> maitenance_v){\n\n}\n\nint Order::get_exectime(){\n\treturn exec_t;\n}\n\nvector<Task> Order::get_tasks(){\n\treturn machine1.get_tasks();\n}\n\n\n\n\n\n\/*\nOrder::Order(){\n\n}\nOrder::Order(vector<Task_t> task_m1_v, vector<Task_t> task_m2_v, vector<Maitenance> maitenance_v){\n\tmachine1.set_id(1);\n\tmachine1.set_start(0);\n\tmachine1.set_stop(0);\n\tmachine2.set_id(2);\n\tint n = 0;\n\tunsigned int size = (task_m1_v.size() >= task_m2_v.size())?(task_m1_v.size()):(task_m2_v.size());\n\n\tfor(unsigned int i = 0; i < size; i++){\n\t\tif (task_m1_v.size() < i){\n\t\t\twhile(!machine1.add(task_m1_v[i+n], maitenance_v)){\n\t\t\t\ttask_m1_v.push_back(task_m1_v[i+n]);\n\t\t\t\tn++;\n\t\t\t}\n\t\t\tn = 0;\n\t\t}\n\n\t\tif (task_m2_v.size() < i){\n\t\t\tif( i == 0 ){\n\t\t\t\tmachine2.set_start(machine1.get_sop());\n\t\t\t\tmachine2.set_stop(machine1.get_sop());\n\t\t\t}\n\n\t\t\tif(machine1.get_sop() <= machine2.get_sop()) machine2.add(task_m2_v[i], maitenance_v);\n\t\t\telse machine2.addt(machine1.get_sop(), task_m2_v[i]);\n\t\t}\n\t}\n\n\tthis->exec_t = machine2.get_sop();\n}\n\nvoid Order::initialization(vector<int> O, vector<Task> task_v, vector<Maitenance> maitenance_v){\n\tmachine1.set_id(1);\n\tmachine1.set_start(0);\n\tmachine1.set_stop(0);\n\tmachine2.set_id(2);\n\tint n, tmp;\n\tfor (vector<int>::size_type i = 0; i < O.size(); i++){\n\t\t\/\/Machine 1\n\t\tn = 1;\n\t\twhile(!machine1.add(O[i], task_v, maitenance_v)){\n\t\t\ttmp = O[i];\n\t\t\tO[i] = O[i + n];\n\t\t\tO[i + n] = tmp;\n\t\t\tn++;\n\t\t}\n\t\t\/\/ Machine 2\n\t\tif( i == 0 ){\n\t\t\tmachine2.set_start(machine1.get_sop());\n\t\t\tmachine2.set_stop(machine1.get_sop());\n\t\t}\n\t\tif(machine1.get_sop() <= machine2.get_sop()){\n\t\t\tmachine2.add(O[i], task_v, maitenance_v);\n\t\t}else{\n\t\t\tmachine2.addt(machine1.get_sop(), O[i], task_v);\n\t\t}\n\t}\n\n\tthis->exec_t = machine2.get_sop();\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before>#include <cilantro\/voxel_grid.hpp>\n\/\/#include <cilantro\/pca.hpp>\n\nVoxelGrid::VoxelGrid(const std::vector<Eigen::Vector3f> &points, float bin_size)\n : input_points_(&points),\n input_normals_(NULL),\n input_colors_(NULL),\n bin_size_(bin_size),\n empty_indices_(0)\n{\n build_lookup_table_();\n}\n\nVoxelGrid::VoxelGrid(const PointCloud &cloud, float bin_size)\n : input_points_(&cloud.points),\n input_normals_(cloud.hasNormals()?&cloud.normals:NULL),\n input_colors_(cloud.hasColors()?&cloud.colors:NULL),\n bin_size_(bin_size),\n empty_indices_(0)\n{\n build_lookup_table_();\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledPoints(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> points;\n points.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_points(3, it->second.size());\n for (size_t i = 0; i < it->second.size(); i++) {\n bin_points.col(i) = (*input_points_)[it->second[i]];\n }\n points.emplace_back(bin_points.rowwise().mean());\n }\n\n return points;\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledNormals(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> normals;\n if (input_normals_ == NULL) {\n return normals;\n }\n\n\/\/ normals.reserve(grid_lookup_table_.size());\n\/\/ for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n\/\/ if (it->second.size() < min_points_in_bin) continue;\n\/\/\n\/\/ Eigen::MatrixXf bin_normals(3, it->second.size()*2);\n\/\/ Eigen::Vector3f ref_dir = (*input_normals_)[it->second[0]];\n\/\/ size_t pos = 0, neg = 0;\n\/\/ for (size_t i = 0; i < it->second.size(); i++) {\n\/\/ const Eigen::Vector3f& curr_normal = (*input_normals_)[it->second[i]];\n\/\/ if (ref_dir.dot(curr_normal) < 0.0f) neg++; else pos++;\n\/\/ bin_normals.col(2*i) = -curr_normal;\n\/\/ bin_normals.col(2*i+1) = curr_normal;\n\/\/ }\n\/\/ if (neg > pos) ref_dir = -ref_dir;\n\/\/\n\/\/ PCA3D pca(bin_normals.data(), 3, it->second.size()*2);\n\/\/ Eigen::Vector3f avg = pca.getEigenVectorsMatrix().col(0);\n\/\/ if (ref_dir.dot(avg) < 0.0f) {\n\/\/ normals.emplace_back(-avg);\n\/\/ } else {\n\/\/ normals.emplace_back(avg);\n\/\/ }\n\/\/ }\n\n normals.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_normals(3, it->second.size());\n Eigen::Vector3f ref_dir = (*input_normals_)[it->second[0]];\n size_t pos = 0, neg = 0;\n for (size_t i = 0; i < it->second.size(); i++) {\n const Eigen::Vector3f& curr_normal = (*input_normals_)[it->second[i]];\n if (ref_dir.dot(curr_normal) < 0.0f) {\n bin_normals.col(i) = -curr_normal;\n neg++;\n } else {\n bin_normals.col(i) = curr_normal;\n pos++;\n }\n }\n\n Eigen::Vector3f avg = bin_normals.rowwise().mean().normalized();\n if (neg > pos) {\n normals.emplace_back(-avg);\n } else {\n normals.emplace_back(avg);\n }\n }\n\n return normals;\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledColors(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> colors;\n if (input_colors_ == NULL) return colors;\n\n colors.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_colors(3, it->second.size());\n for (size_t i = 0; i < it->second.size(); i++) {\n bin_colors.col(i) = (*input_colors_)[it->second[i]];\n }\n colors.emplace_back(bin_colors.rowwise().mean());\n }\n\n return colors;\n}\n\nPointCloud VoxelGrid::getDownsampledCloud(size_t min_points_in_bin) const {\n return PointCloud(getDownsampledPoints(min_points_in_bin), getDownsampledNormals(min_points_in_bin), getDownsampledColors(min_points_in_bin));\n}\n\nconst std::vector<size_t>& VoxelGrid::getGridBinNeighbors(const Eigen::Vector3f &point) const {\n Eigen::Vector3i grid_coords = ((point-min_pt_)\/bin_size_).array().floor().cast<int>();\n if ((grid_coords.array() < Eigen::Vector3i::Zero().array()).any()) return empty_indices_;\n\n auto it = grid_lookup_table_.find(grid_coords);\n if (it == grid_lookup_table_.end()) return empty_indices_;\n\n return it->second;\n}\n\nconst std::vector<size_t>& VoxelGrid::getGridBinNeighbors(size_t point_ind) const {\n return VoxelGrid::getGridBinNeighbors((*input_points_)[point_ind]);\n}\n\nvoid VoxelGrid::build_lookup_table_() {\n if (input_points_->empty()) return;\n\n min_pt_ = Eigen::Map<Eigen::MatrixXf>((float *)input_points_->data(), 3, input_points_->size()).rowwise().minCoeff();\n Eigen::MatrixXi grid_coords = ((Eigen::Map<Eigen::MatrixXf>((float *)input_points_->data(), 3, input_points_->size()).colwise()-min_pt_)\/bin_size_).array().floor().cast<int>();\n\n \/\/ Build lookup table\n for (size_t i = 0; i < input_points_->size(); i++) {\n auto it = grid_lookup_table_.find(grid_coords.col(i));\n if (it == grid_lookup_table_.end()) {\n grid_lookup_table_.insert(std::pair<Eigen::Vector3i,std::vector<size_t> >(grid_coords.col(i), std::vector<size_t>(1, i)));\n } else {\n it->second.emplace_back(i);\n }\n }\n}\n<commit_msg>Minor change<commit_after>#include <cilantro\/voxel_grid.hpp>\n\/\/#include <cilantro\/pca.hpp>\n\nVoxelGrid::VoxelGrid(const std::vector<Eigen::Vector3f> &points, float bin_size)\n : input_points_(&points),\n input_normals_(NULL),\n input_colors_(NULL),\n bin_size_(bin_size),\n empty_indices_(0)\n{\n build_lookup_table_();\n}\n\nVoxelGrid::VoxelGrid(const PointCloud &cloud, float bin_size)\n : input_points_(&cloud.points),\n input_normals_(cloud.hasNormals()?&cloud.normals:NULL),\n input_colors_(cloud.hasColors()?&cloud.colors:NULL),\n bin_size_(bin_size),\n empty_indices_(0)\n{\n build_lookup_table_();\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledPoints(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> points;\n points.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_points(3, it->second.size());\n for (size_t i = 0; i < it->second.size(); i++) {\n bin_points.col(i) = (*input_points_)[it->second[i]];\n }\n points.emplace_back(bin_points.rowwise().mean());\n }\n\n return points;\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledNormals(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> normals;\n if (input_normals_ == NULL) {\n return normals;\n }\n\n\/\/ normals.reserve(grid_lookup_table_.size());\n\/\/ for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n\/\/ if (it->second.size() < min_points_in_bin) continue;\n\/\/\n\/\/ Eigen::MatrixXf bin_normals(3, it->second.size()*2);\n\/\/ Eigen::Vector3f ref_dir = (*input_normals_)[it->second[0]];\n\/\/ size_t pos = 0, neg = 0;\n\/\/ for (size_t i = 0; i < it->second.size(); i++) {\n\/\/ const Eigen::Vector3f& curr_normal = (*input_normals_)[it->second[i]];\n\/\/ if (ref_dir.dot(curr_normal) < 0.0f) neg++; else pos++;\n\/\/ bin_normals.col(2*i) = -curr_normal;\n\/\/ bin_normals.col(2*i+1) = curr_normal;\n\/\/ }\n\/\/ if (neg > pos) ref_dir = -ref_dir;\n\/\/\n\/\/ PCA3D pca(bin_normals.data(), 3, it->second.size()*2);\n\/\/ Eigen::Vector3f avg = pca.getEigenVectorsMatrix().col(0);\n\/\/ if (ref_dir.dot(avg) < 0.0f) {\n\/\/ normals.emplace_back(-avg);\n\/\/ } else {\n\/\/ normals.emplace_back(avg);\n\/\/ }\n\/\/ }\n\n normals.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_normals(3, it->second.size());\n Eigen::Vector3f ref_dir = (*input_normals_)[it->second[0]];\n size_t pos = 0, neg = 0;\n for (size_t i = 0; i < it->second.size(); i++) {\n const Eigen::Vector3f& curr_normal = (*input_normals_)[it->second[i]];\n if (ref_dir.dot(curr_normal) < 0.0f) {\n bin_normals.col(i) = -curr_normal;\n neg++;\n } else {\n bin_normals.col(i) = curr_normal;\n pos++;\n }\n }\n\n Eigen::Vector3f avg = bin_normals.rowwise().mean().normalized();\n if (neg > pos) {\n normals.emplace_back(-avg);\n } else {\n normals.emplace_back(avg);\n }\n }\n\n return normals;\n}\n\nstd::vector<Eigen::Vector3f> VoxelGrid::getDownsampledColors(size_t min_points_in_bin) const {\n std::vector<Eigen::Vector3f> colors;\n if (input_colors_ == NULL) return colors;\n\n colors.reserve(grid_lookup_table_.size());\n for (auto it = grid_lookup_table_.begin(); it != grid_lookup_table_.end(); ++it) {\n if (it->second.size() < min_points_in_bin) continue;\n\n Eigen::MatrixXf bin_colors(3, it->second.size());\n for (size_t i = 0; i < it->second.size(); i++) {\n bin_colors.col(i) = (*input_colors_)[it->second[i]];\n }\n colors.emplace_back(bin_colors.rowwise().mean());\n }\n\n return colors;\n}\n\nPointCloud VoxelGrid::getDownsampledCloud(size_t min_points_in_bin) const {\n return PointCloud(getDownsampledPoints(min_points_in_bin), getDownsampledNormals(min_points_in_bin), getDownsampledColors(min_points_in_bin));\n}\n\nconst std::vector<size_t>& VoxelGrid::getGridBinNeighbors(const Eigen::Vector3f &point) const {\n Eigen::Vector3i grid_coords = ((point-min_pt_)\/bin_size_).array().floor().cast<int>();\n if ((grid_coords.array() < 0).any()) return empty_indices_;\n\n auto it = grid_lookup_table_.find(grid_coords);\n if (it == grid_lookup_table_.end()) return empty_indices_;\n\n return it->second;\n}\n\nconst std::vector<size_t>& VoxelGrid::getGridBinNeighbors(size_t point_ind) const {\n return VoxelGrid::getGridBinNeighbors((*input_points_)[point_ind]);\n}\n\nvoid VoxelGrid::build_lookup_table_() {\n if (input_points_->empty()) return;\n\n min_pt_ = Eigen::Map<Eigen::MatrixXf>((float *)input_points_->data(), 3, input_points_->size()).rowwise().minCoeff();\n Eigen::MatrixXi grid_coords = ((Eigen::Map<Eigen::MatrixXf>((float *)input_points_->data(), 3, input_points_->size()).colwise()-min_pt_)\/bin_size_).array().floor().cast<int>();\n\n \/\/ Build lookup table\n for (size_t i = 0; i < input_points_->size(); i++) {\n auto it = grid_lookup_table_.find(grid_coords.col(i));\n if (it == grid_lookup_table_.end()) {\n grid_lookup_table_.insert(std::pair<Eigen::Vector3i,std::vector<size_t> >(grid_coords.col(i), std::vector<size_t>(1, i)));\n } else {\n it->second.emplace_back(i);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n#define METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n\n#include \"Methcla\/Audio\/AudioBus.hpp\"\n#include \"Methcla\/Audio\/Engine.hpp\"\n\n#include <boost\/intrusive\/list.hpp>\n#include <boost\/utility.hpp>\n#include <oscpp\/server.hpp>\n#include <thread>\n\nnamespace Methcla { namespace Audio {\n\nenum InputConnectionType\n{\n kIn\n , kInFeedback\n};\n\nenum OutputConnectionType\n{\n kOut\n , kReplaceOut\n};\n\nclass Synth;\n\ntemplate <typename BusId, typename ConnectionType>\nclass Connection : public boost::noncopyable\n , public boost::intrusive::list_base_hook<>\n{\npublic:\n Connection(size_t index, ConnectionType type)\n : m_index(index)\n , m_connected(false)\n , m_busId(0)\n , m_type(type)\n { }\n\n size_t index() const { return m_index; }\n bool isConnected() const { return m_connected; }\n BusId busId() const { return m_busId; }\n const ConnectionType& type() const { return m_type; }\n\n bool connect(const BusId& busId, const ConnectionType& type)\n {\n bool changed = false;\n if (!m_connected || (busId != m_busId)) {\n m_connected = true;\n m_busId = busId;\n changed = true;\n }\n m_type = type;\n return changed;\n }\n\nprivate:\n size_t m_index;\n bool m_connected;\n BusId m_busId;\n ConnectionType m_type;\n};\n\nclass AudioInputConnection : public Connection<AudioBusId,InputConnectionType>\n{\npublic:\n AudioInputConnection(size_t index)\n : Connection<AudioBusId,InputConnectionType>(index, kIn)\n { }\n\n void read(Environment& env, size_t numFrames, sample_t* dst)\n {\n if (isConnected()) {\n AudioBus* bus = env.audioBus(busId());\n\n if (bus != nullptr) {\n std::lock_guard<AudioBus::Lock> lock(bus->lock());\n if ((type() == kInFeedback) || (bus->epoch() == env.epoch())) {\n memcpy(dst, bus->data(), numFrames * sizeof(sample_t));\n } else {\n memset(dst, 0, numFrames * sizeof(sample_t));\n }\n } else {\n memset(dst, 0, numFrames * sizeof(sample_t));\n }\n }\n }\n};\n\nclass AudioOutputConnection : public Connection<AudioBusId,OutputConnectionType>\n{\npublic:\n AudioOutputConnection(size_t index)\n : Connection<AudioBusId,OutputConnectionType>(index, kOut)\n , m_offset(0)\n , m_buffer(0)\n { }\n\n bool connect(const AudioBusId& busId, const OutputConnectionType& type, size_t offset, sample_t* buffer)\n {\n BOOST_ASSERT((m_offset == 0) && (m_buffer == 0));\n m_offset = offset;\n m_buffer = buffer;\n return Connection<AudioBusId,OutputConnectionType>::connect(busId, type);\n }\n\n void release(Environment& env)\n {\n if (m_buffer != 0) {\n env.rtMem().free(m_buffer);\n m_offset = 0;\n m_buffer = 0;\n }\n }\n\n void write(Environment& env, size_t numFrames, const sample_t* src)\n {\n if (isConnected()) {\n AudioBus* bus = env.audioBus(busId());\n\n if (bus != nullptr) {\n const Epoch epoch = env.epoch();\n std::lock_guard<AudioBus::Lock> lock(bus->lock());\n if ((type() != kReplaceOut) && (bus->epoch() == epoch)) {\n \/\/ Accumulate\n sample_t* dst = bus->data();\n for (size_t i=0; i < numFrames; i++) {\n dst[i] += src[i];\n }\n } else {\n \/\/ Copy\n memcpy(bus->data(), src, numFrames * sizeof(sample_t));\n bus->setEpoch(epoch);\n }\n }\n }\n }\n\nprivate:\n size_t m_offset;\n sample_t* m_buffer;\n};\n\nclass Synth : public Node\n{\nprotected:\n enum Flags\n {\n kAudioInputConnectionsChanged\n , kAudioOutputConnectionsChanged\n , kControlInputConnectionsChanged\n , kControlOutputConnectionsChanged\n , kHasTriggerInput\n };\n\n Synth( Environment& env\n , Group* target\n , AddAction addAction\n , const SynthDef& synthDef\n , OSC::Server::ArgStream controls\n , OSC::Server::ArgStream args\n , size_t synthOffset\n , size_t audioInputConnectionsOffset\n , size_t audioOutputConnectionsOffset\n , size_t controlBufferOffset\n , size_t audioBufferOffset\n , size_t audioBufferSize\n );\n ~Synth();\n\npublic:\n static Synth* construct(Environment& env, Group* target, Node::AddAction addAction, const SynthDef& synthDef, OSC::Server::ArgStream controls, OSC::Server::ArgStream args);\n\n virtual bool isSynth() const override { return true; }\n\n \/\/* Return this synth's SynthDef.\n const SynthDef& synthDef() const { return m_synthDef; }\n\n \/\/* Return number of audio inputs.\n size_t numAudioInputs() const { return synthDef().numAudioInputs(); }\n\n \/\/* Map input to bus.\n void mapInput(size_t input, const AudioBusId& busId, InputConnectionType type);\n\n \/\/* Return number of audio outputs.\n size_t numAudioOutputs() const { return synthDef().numAudioOutputs(); }\n\n \/\/* Map output to bus.\n void mapOutput(size_t output, const AudioBusId& busId, OutputConnectionType type);\n\n typedef boost::intrusive::list<AudioInputConnection> AudioInputConnections;\n typedef boost::intrusive::list<AudioOutputConnection> AudioOutputConnections;\n \/\/ typedef boost::container::vector<Connection<ControlBus, InputConnectionType> > ControlInputConnections;\n \/\/ typedef boost::container::vector<Connection<ControlBus, OutputConnectionType> > ControlOutputConnections;\n\n size_t numControlInputs() const { return synthDef().numControlInputs(); }\n size_t numControlOutputs() const { return synthDef().numControlOutputs(); }\n\n float controlInput(size_t index) const\n {\n BOOST_ASSERT_MSG( index < numControlInputs(), \"control input index out of range\" );\n return m_controlBuffers[index];\n }\n\n float& controlInput(size_t index)\n {\n BOOST_ASSERT_MSG( index < numControlInputs(), \"control input index out of range\" );\n return m_controlBuffers[index];\n }\n\n float controlOutput(size_t index) const\n {\n BOOST_ASSERT_MSG( index < numControlOutputs(), \"control output index out of range\" );\n return m_controlBuffers[numControlInputs() + index];\n }\n\n \/\/\/ Sample offset for sample accurate synth scheduling.\n size_t sampleOffset() const { return 0; }\n\n \/\/\/ Sets up inputs and outputs and calls compute.\n virtual void process(size_t numFrames);\n\n template <class T> T* synth() { return static_cast<T*>(m_synth); }\n\nprivate:\n const SynthDef& m_synthDef;\n std::bitset<32> m_flags;\n Methcla_Synth* m_synth;\n AudioInputConnections m_audioInputConnections;\n AudioOutputConnections m_audioOutputConnections;\n sample_t* m_controlBuffers;\n sample_t* m_audioBuffers;\n};\n\n}; };\n\n#endif \/\/ METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n<commit_msg>Remove unused method<commit_after>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n#define METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n\n#include \"Methcla\/Audio\/AudioBus.hpp\"\n#include \"Methcla\/Audio\/Engine.hpp\"\n\n#include <boost\/intrusive\/list.hpp>\n#include <boost\/utility.hpp>\n#include <oscpp\/server.hpp>\n#include <thread>\n\nnamespace Methcla { namespace Audio {\n\nenum InputConnectionType\n{\n kIn\n , kInFeedback\n};\n\nenum OutputConnectionType\n{\n kOut\n , kReplaceOut\n};\n\nclass Synth;\n\ntemplate <typename BusId, typename ConnectionType>\nclass Connection : public boost::noncopyable\n , public boost::intrusive::list_base_hook<>\n{\npublic:\n Connection(size_t index, ConnectionType type)\n : m_index(index)\n , m_connected(false)\n , m_busId(0)\n , m_type(type)\n { }\n\n size_t index() const { return m_index; }\n bool isConnected() const { return m_connected; }\n BusId busId() const { return m_busId; }\n const ConnectionType& type() const { return m_type; }\n\n bool connect(const BusId& busId, const ConnectionType& type)\n {\n bool changed = false;\n if (!m_connected || (busId != m_busId)) {\n m_connected = true;\n m_busId = busId;\n changed = true;\n }\n m_type = type;\n return changed;\n }\n\nprivate:\n size_t m_index;\n bool m_connected;\n BusId m_busId;\n ConnectionType m_type;\n};\n\nclass AudioInputConnection : public Connection<AudioBusId,InputConnectionType>\n{\npublic:\n AudioInputConnection(size_t index)\n : Connection<AudioBusId,InputConnectionType>(index, kIn)\n { }\n\n void read(Environment& env, size_t numFrames, sample_t* dst)\n {\n if (isConnected()) {\n AudioBus* bus = env.audioBus(busId());\n\n if (bus != nullptr) {\n std::lock_guard<AudioBus::Lock> lock(bus->lock());\n if ((type() == kInFeedback) || (bus->epoch() == env.epoch())) {\n memcpy(dst, bus->data(), numFrames * sizeof(sample_t));\n } else {\n memset(dst, 0, numFrames * sizeof(sample_t));\n }\n } else {\n memset(dst, 0, numFrames * sizeof(sample_t));\n }\n }\n }\n};\n\nclass AudioOutputConnection : public Connection<AudioBusId,OutputConnectionType>\n{\npublic:\n AudioOutputConnection(size_t index)\n : Connection<AudioBusId,OutputConnectionType>(index, kOut)\n , m_offset(0)\n , m_buffer(0)\n { }\n\n bool connect(const AudioBusId& busId, const OutputConnectionType& type, size_t offset, sample_t* buffer)\n {\n BOOST_ASSERT((m_offset == 0) && (m_buffer == 0));\n m_offset = offset;\n m_buffer = buffer;\n return Connection<AudioBusId,OutputConnectionType>::connect(busId, type);\n }\n\n void release(Environment& env)\n {\n if (m_buffer != 0) {\n env.rtMem().free(m_buffer);\n m_offset = 0;\n m_buffer = 0;\n }\n }\n\n void write(Environment& env, size_t numFrames, const sample_t* src)\n {\n if (isConnected()) {\n AudioBus* bus = env.audioBus(busId());\n\n if (bus != nullptr) {\n const Epoch epoch = env.epoch();\n std::lock_guard<AudioBus::Lock> lock(bus->lock());\n if ((type() != kReplaceOut) && (bus->epoch() == epoch)) {\n \/\/ Accumulate\n sample_t* dst = bus->data();\n for (size_t i=0; i < numFrames; i++) {\n dst[i] += src[i];\n }\n } else {\n \/\/ Copy\n memcpy(bus->data(), src, numFrames * sizeof(sample_t));\n bus->setEpoch(epoch);\n }\n }\n }\n }\n\nprivate:\n size_t m_offset;\n sample_t* m_buffer;\n};\n\nclass Synth : public Node\n{\nprotected:\n enum Flags\n {\n kAudioInputConnectionsChanged\n , kAudioOutputConnectionsChanged\n , kControlInputConnectionsChanged\n , kControlOutputConnectionsChanged\n , kHasTriggerInput\n };\n\n Synth( Environment& env\n , Group* target\n , AddAction addAction\n , const SynthDef& synthDef\n , OSC::Server::ArgStream controls\n , OSC::Server::ArgStream args\n , size_t synthOffset\n , size_t audioInputConnectionsOffset\n , size_t audioOutputConnectionsOffset\n , size_t controlBufferOffset\n , size_t audioBufferOffset\n , size_t audioBufferSize\n );\n ~Synth();\n\npublic:\n static Synth* construct(Environment& env, Group* target, Node::AddAction addAction, const SynthDef& synthDef, OSC::Server::ArgStream controls, OSC::Server::ArgStream args);\n\n virtual bool isSynth() const override { return true; }\n\n \/\/* Return this synth's SynthDef.\n const SynthDef& synthDef() const { return m_synthDef; }\n\n \/\/* Return number of audio inputs.\n size_t numAudioInputs() const { return synthDef().numAudioInputs(); }\n\n \/\/* Map input to bus.\n void mapInput(size_t input, const AudioBusId& busId, InputConnectionType type);\n\n \/\/* Return number of audio outputs.\n size_t numAudioOutputs() const { return synthDef().numAudioOutputs(); }\n\n \/\/* Map output to bus.\n void mapOutput(size_t output, const AudioBusId& busId, OutputConnectionType type);\n\n typedef boost::intrusive::list<AudioInputConnection> AudioInputConnections;\n typedef boost::intrusive::list<AudioOutputConnection> AudioOutputConnections;\n \/\/ typedef boost::container::vector<Connection<ControlBus, InputConnectionType> > ControlInputConnections;\n \/\/ typedef boost::container::vector<Connection<ControlBus, OutputConnectionType> > ControlOutputConnections;\n\n size_t numControlInputs() const { return synthDef().numControlInputs(); }\n size_t numControlOutputs() const { return synthDef().numControlOutputs(); }\n\n float controlInput(size_t index) const\n {\n BOOST_ASSERT_MSG( index < numControlInputs(), \"control input index out of range\" );\n return m_controlBuffers[index];\n }\n\n float& controlInput(size_t index)\n {\n BOOST_ASSERT_MSG( index < numControlInputs(), \"control input index out of range\" );\n return m_controlBuffers[index];\n }\n\n float controlOutput(size_t index) const\n {\n BOOST_ASSERT_MSG( index < numControlOutputs(), \"control output index out of range\" );\n return m_controlBuffers[numControlInputs() + index];\n }\n\n \/\/\/ Sample offset for sample accurate synth scheduling.\n size_t sampleOffset() const { return 0; }\n\n \/\/\/ Sets up inputs and outputs and calls compute.\n virtual void process(size_t numFrames);\n\nprivate:\n const SynthDef& m_synthDef;\n std::bitset<32> m_flags;\n Methcla_Synth* m_synth;\n AudioInputConnections m_audioInputConnections;\n AudioOutputConnections m_audioOutputConnections;\n sample_t* m_controlBuffers;\n sample_t* m_audioBuffers;\n};\n\n}; };\n\n#endif \/\/ METHCLA_AUDIO_SYNTH_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>#include \"wave\/header.h\"\n\n#include \"wave\/header\/riff_header.h\"\n\nnamespace wave {\n Error Header::Init(std::ifstream* stream, uint64_t position) {\n position_ = position;\n if (!stream->is_open()) {\n return Error::kNotOpen;\n }\n \n \/\/ read chunk ID\n auto chunk_id_size = 4;\n stream->seekg(position_, std::ios::beg);\n char result[chunk_id_size];\n stream->read(result, chunk_id_size * sizeof(char));\n id_ = std::string(result, chunk_id_size);\n \n \/\/ and size\n stream->read(reinterpret_cast<char*>(&size_), sizeof(uint32_t));\n size_ += chunk_id_size * sizeof(char) + sizeof(uint32_t);\n \n return Error::kNoError;\n }\n\nstd::string Header::chunk_id() const {\n return id_;\n}\n\nuint32_t Header::chunk_size() const {\n if (chunk_id() == \"RIFF\") {\n return sizeof(wave::RIFFHeader);\n }\n return size_;\n}\n\nuint64_t Header::position() const {\n return position_;\n}\n}; \/\/ namespace wave\n<commit_msg>Fix error on windows<commit_after>#include \"wave\/header.h\"\n\n#include \"wave\/header\/riff_header.h\"\n\nnamespace wave {\n Error Header::Init(std::ifstream* stream, uint64_t position) {\n position_ = position;\n if (!stream->is_open()) {\n return Error::kNotOpen;\n }\n\n \/\/ read chunk ID\n const auto chunk_id_size = 4;\n stream->seekg(position_, std::ios::beg);\n char result[chunk_id_size];\n stream->read(result, chunk_id_size * sizeof(char));\n id_ = std::string(result, chunk_id_size);\n\n \/\/ and size\n stream->read(reinterpret_cast<char*>(&size_), sizeof(uint32_t));\n size_ += chunk_id_size * sizeof(char) + sizeof(uint32_t);\n\n return Error::kNoError;\n }\n\nstd::string Header::chunk_id() const {\n return id_;\n}\n\nuint32_t Header::chunk_size() const {\n if (chunk_id() == \"RIFF\") {\n return sizeof(wave::RIFFHeader);\n }\n return size_;\n}\n\nuint64_t Header::position() const {\n return position_;\n}\n}; \/\/ namespace wave\n<|endoftext|>"} {"text":"<commit_before>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"CoreConstants.hpp\"\n#include \"CoreGlobals.hpp\"\n#include \"Creator.hpp\"\n\nstatic void baseModelChecks(\n ModelPtr model,\n int width,\n int height,\n int bacteria_number\n) {\n BOOST_REQUIRE(model->getWidth() == width);\n BOOST_REQUIRE(model->getHeight() == height);\n BOOST_REQUIRE(model->getBacteriaNumber(0) == bacteria_number);\n}\n\nBOOST_AUTO_TEST_CASE (create_special_model_test) {\n Implementation::Unit unit(\n Abstract::Point(0, 0),\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n Units units(1, unit);\n ModelPtr model = Creator::createSpecialModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n 1,\n units\n );\n baseModelChecks(model, MIN_WIDTH, MIN_HEIGHT, 1);\n BOOST_REQUIRE(model->getCoordinates(0, 0) == unit.coordinates);\n BOOST_REQUIRE(model->getMass(0, 0) == unit.mass);\n BOOST_REQUIRE(model->getDirection(0, 0) == unit.direction);\n BOOST_REQUIRE(model->getInstruction(0, 0) == unit.instruction);\n}\n\nBOOST_AUTO_TEST_CASE (create_model_test) {\n ModelPtr model = Creator::createModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n 1,\n 1\n );\n baseModelChecks(model, MIN_WIDTH, MIN_HEIGHT, 1);\n}\n<commit_msg>Unit tests (creator): add create_core_objects_test<commit_after>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include <fstream>\n\n#include <QStringList>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"CoreConstants.hpp\"\n#include \"CoreGlobals.hpp\"\n#include \"Creator.hpp\"\n\nstatic void baseModelChecks(\n ModelPtr model,\n int width,\n int height,\n int bacteria_number\n) {\n BOOST_REQUIRE(model->getWidth() == width);\n BOOST_REQUIRE(model->getHeight() == height);\n BOOST_REQUIRE(model->getBacteriaNumber(0) == bacteria_number);\n}\n\nBOOST_AUTO_TEST_CASE (create_special_model_test) {\n Implementation::Unit unit(\n Abstract::Point(0, 0),\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n Units units(1, unit);\n ModelPtr model = Creator::createSpecialModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n 1,\n units\n );\n baseModelChecks(model, MIN_WIDTH, MIN_HEIGHT, 1);\n BOOST_REQUIRE(model->getCoordinates(0, 0) == unit.coordinates);\n BOOST_REQUIRE(model->getMass(0, 0) == unit.mass);\n BOOST_REQUIRE(model->getDirection(0, 0) == unit.direction);\n BOOST_REQUIRE(model->getInstruction(0, 0) == unit.instruction);\n}\n\nBOOST_AUTO_TEST_CASE (create_model_test) {\n ModelPtr model = Creator::createModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n 1,\n 1\n );\n baseModelChecks(model, MIN_WIDTH, MIN_HEIGHT, 1);\n}\n\nBOOST_AUTO_TEST_CASE (create_core_objects_test) {\n ModelPtr model = Creator::createModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n 1,\n 1\n );\n ChangerPtrs changers;\n std::ofstream bact_file(\"eat.bact\");\n if (bact_file.is_open()) {\n bact_file << \"eat\\n\";\n bact_file.close();\n } else {\n std::cerr << \"Error: Unable to open script file.\" << std::endl;\n }\n QStringList scripts(QString(\"eat.bact\"));\n InterpreterPtr interpreter = Creator::createCoreObjects(\n model,\n scripts,\n changers\n );\n BOOST_REQUIRE(changers[0]->getBacteriaNumber() == 1);\n interpreter->makeMove(*(changers[0].data()), 0);\n BOOST_REQUIRE(model->getMass(0, 0) == DEFAULT_MASS + EAT_MASS);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Remove unused local from CreateAttachment<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * @file steepest_descent.hpp\n * @author Marcus Edel\n *\n * Implementation of the steepest descent optimizer. The method of steepest\n * descent, also called the gradient descent method, is used to find the\n * nearest local minimum of a function which the assumtion that the gradient of\n * the function can be computed.\n *\/\n#ifndef __MLPACK_METHODS_ANN_OPTIMIZER_STEEPEST_DESCENT_HPP\n#define __MLPACK_METHODS_ANN_OPTIMIZER_STEEPEST_DESCENT_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * This class is used to update the weights using steepest descent.\n *\n * @tparam DataType Type of input data (should be arma::mat,\n * arma::spmat or arma::cube).\n *\/\ntemplate<typename DecomposableFunctionType, typename DataType>\nclass SteepestDescent\n{\n public:\n \/**\n * Construct the SteepestDescent optimizer with the given function and\n * parameters.\n *\n * @param function Function to be optimized (minimized).\n * @param lr The learning rate coefficient.\n * @param mom The momentum coefficient.\n *\/\n SteepestDescent(DecomposableFunctionType& function,\n const double lr = 1,\n const double mom = 0) :\n function(function),\n lr(lr),\n mom(mom),\n momWeights(function.Weights())\n\n {\n \/\/ Nothing to do here.\n }\n\n \/**\n * Optimize the given function using steepest descent.\n *\/\n void Optimize()\n {\n if (momWeights.n_elem == 0)\n {\n momWeights = function.Weights();\n momWeights.zeros();\n }\n\n Optimize(function.Weights(), gradient, momWeights);\n }\n\n \/*\n * Sum up all gradients and store the results in the gradients storage.\n *\/\n void Update()\n {\n if (gradient.n_elem != 0)\n {\n DataType outputGradient;\n function.Gradient(outputGradient);\n gradient += outputGradient;\n }\n else\n {\n function.Gradient(gradient);\n }\n }\n\n \/*\n * Reset the gradient storage.\n *\/\n void Reset()\n {\n gradient.zeros();\n }\n\n private:\n \/** Optimize the given function using steepest descent.\n *\n * @param weights The weights that should be updated.\n * @param gradient The gradient used to update the weights.\n * @param gradient The moving average over the root mean squared gradient used\n * to update the weights.\n *\/\n template<typename eT>\n void Optimize(arma::Cube<eT>& weights,\n arma::Cube<eT>& gradient,\n arma::Cube<eT>& momWeights)\n {\n for (size_t s = 0; s < weights.n_slices; s++)\n Optimize(weights.slice(s), gradient.slice(s), momWeights.slice(s));\n }\n\n \/**\n * Optimize the given function using steepest descent.\n *\n * @param weights The weights that should be updated.\n * @param gradient The gradient used to update the weights.\n * @param gradient The moving average over the root mean squared gradient used\n * to update the weights.\n *\/\n template<typename eT>\n void Optimize(arma::Mat<eT>& weights,\n arma::Mat<eT>& gradient,\n arma::Mat<eT>& momWeights)\n {\n if (mom > 0)\n {\n momWeights *= mom;\n momWeights += (lr * gradient);\n weights -= momWeights;\n }\n else\n {\n weights -= lr * gradient;\n }\n }\n\n \/\/! The instantiated function.\n DecomposableFunctionType& function;\n\n \/\/! The value used as learning rate.\n const double lr;\n\n \/\/! The value used as momentum.\n const double mom;\n\n \/\/! Momentum matrix.\n DataType momWeights;\n\n \/\/! The current gradient.\n DataType gradient;\n}; \/\/ class SteepestDescent\n\n}; \/\/ namespace ann\n}; \/\/ namespace mlpack\n\n#endif\n<commit_msg>Use the new optimizer interface.<commit_after>\/**\n * @file steepest_descent.hpp\n * @author Marcus Edel\n *\n * Implementation of the steepest descent optimizer. The method of steepest\n * descent, also called the gradient descent method, is used to find the\n * nearest local minimum of a function which the assumtion that the gradient of\n * the function can be computed.\n *\/\n#ifndef __MLPACK_METHODS_ANN_OPTIMIZER_STEEPEST_DESCENT_HPP\n#define __MLPACK_METHODS_ANN_OPTIMIZER_STEEPEST_DESCENT_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace ann \/** Artificial Neural Network. *\/ {\n\n\/**\n * This class is used to update the weights using steepest descent.\n *\n * @tparam DataType Type of input data (should be arma::mat,\n * arma::spmat or arma::cube).\n *\/\ntemplate<typename DecomposableFunctionType, typename DataType>\nclass SteepestDescent\n{\n public:\n \/**\n * Construct the SteepestDescent optimizer with the given function and\n * parameters.\n *\n * @param function Function to be optimized (minimized).\n * @param lr The learning rate coefficient.\n * @param mom The momentum coefficient.\n *\/\n SteepestDescent(DecomposableFunctionType& function,\n const double lr = 0.5,\n const double mom = 0) :\n function(function),\n lr(lr),\n mom(mom),\n momWeights(function.Weights())\n\n {\n \/\/ Nothing to do here.\n }\n\n \/**\n * Optimize the given function using steepest descent.\n *\/\n void Optimize()\n {\n if (momWeights.n_elem == 0)\n {\n momWeights = function.Weights();\n momWeights.zeros();\n }\n\n Optimize(function.Weights(), gradient, momWeights);\n }\n\n \/*\n * Sum up all gradients and store the results in the gradients storage.\n *\/\n void Update()\n {\n if (gradient.n_elem != 0)\n {\n DataType outputGradient = function.Gradient();\n gradient += outputGradient;\n }\n else\n {\n gradient = function.Gradient();\n }\n }\n\n \/*\n * Reset the gradient storage.\n *\/\n void Reset()\n {\n gradient.zeros();\n }\n\n private:\n \/** Optimize the given function using steepest descent.\n *\n * @param weights The weights that should be updated.\n * @param gradient The gradient used to update the weights.\n * @param gradient The moving average over the root mean squared gradient used\n * to update the weights.\n *\/\n template<typename eT>\n void Optimize(arma::Cube<eT>& weights,\n arma::Cube<eT>& gradient,\n arma::Cube<eT>& momWeights)\n {\n for (size_t s = 0; s < weights.n_slices; s++)\n Optimize(weights.slice(s), gradient.slice(s), momWeights.slice(s));\n }\n\n \/**\n * Optimize the given function using steepest descent.\n *\n * @param weights The weights that should be updated.\n * @param gradient The gradient used to update the weights.\n * @param gradient The moving average over the root mean squared gradient used\n * to update the weights.\n *\/\n template<typename eT>\n void Optimize(arma::Mat<eT>& weights,\n arma::Mat<eT>& gradient,\n arma::Mat<eT>& momWeights)\n {\n if (mom > 0)\n {\n momWeights *= mom;\n momWeights += (lr * gradient);\n weights -= momWeights;\n }\n else\n {\n weights -= lr * gradient;\n }\n }\n\n \/\/! The instantiated function.\n DecomposableFunctionType& function;\n\n \/\/! The value used as learning rate.\n const double lr;\n\n \/\/! The value used as momentum.\n const double mom;\n\n \/\/! Momentum matrix.\n DataType momWeights;\n\n \/\/! The current gradient.\n DataType gradient;\n}; \/\/ class SteepestDescent\n\n}; \/\/ namespace ann\n}; \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"RTClib.h\"\n#include \"accel.h\"\n#include \"daytimes.h\"\n#include \"ledctrl.h\"\n#include \"m0_hf_pwm.h\"\n#include \"mqtt_client.h\"\n#include \"netcfg.h\"\n#include \"proxim.h\"\n#include \"solenoids.h\"\n#include \"utils.h\"\n#include \"watchdog_timer.h\"\n\n\/\/ For float to string formatting\n#include <avr\/dtostrf.h>\n\n\/\/ Where to get the battery voltage\n#define VBATPIN A7\n\n\/\/ Customization for acceptable daylight times\nstatic const TimeSpan margin_after_sunrise(0, 0, 45, 0);\nstatic const TimeSpan margin_before_sunset(0, 2, 0, 0);\n\nstatic const unsigned long LOOP_PERIOD_MS = 25;\n\n\/\/ global objects...\nRTC_DS3231 rtc;\nAccel accel_sensor;\nProxim proxim_sensor;\nSolenoids& sol_actuators = Solenoids::Instance();\nLedCtrl& status_led = LedCtrl::Instance();\nWiFiClient wifi_client;\nMQTT_Client mqtt_client(wifi_client, status_led);\n\n\/\/ interupts function prototypes\nvoid proximThreshold() { proxim_sensor.new_state = true; }\n\nvoid accelReady() { accel_sensor.data_ready = true; }\n\nvoid setup() {\n wdt_configure(11);\n\n \/\/ HF PWM\n pwm_configure();\n\n \/\/ let things stabilize before pulling too much current\n \/\/ not necessary, but surprise the developer less also\n delay(1000);\n\n \/\/ Force unjam, no matter what, just in case we rebooted\n \/\/ Also this says Hi to the world\n sol_actuators.unjam();\n\n \/\/ start in unkown state\n status_led.warning();\n\n#ifdef USE_SERIAL\n Serial.begin(115200);\n while (!Serial) {\n ; \/\/ wait for serial port to connect to start the app\n }\n\/\/ Serial.print(\"sizeof(int)=\");\n\/\/ Serial.println(sizeof(int));\n#endif\n\n \/\/\n \/\/ Accelerometer setup\n \/\/\n if (!accel_sensor.begin(0x18)) {\n PRINTLN(\"Couldnt start accelerometer!\");\n while (1)\n ;\n }\n PRINTLN(\"LIS3DH found.\");\n\n \/\/ configure sensor\n accel_sensor.setDataRate(LIS3DH_DATARATE_10_HZ);\n accel_sensor.setRange(LIS3DH_RANGE_2_G);\n\n \/\/ attach hardware interrupt\n pinMode(A2, INPUT_PULLUP);\n attachInterrupt(A2, accelReady, RISING);\n delay(1); \/\/ for some reason, this delay is CRITICAL!\n accel_sensor.read(); \/\/ read reset the signal --> start interrupts\n\n \/\/\n \/\/ Proximity sensor setup\n \/\/\n if (!proxim_sensor.begin()) {\n PRINTLN(\"Proximity sensor not found!\");\n while (1)\n ;\n }\n PRINTLN(\"VCNL4010 found.\");\n\n \/\/ configure sensor\n proxim_sensor.setModulatorFrequency(VCNL4010_390K625);\n proxim_sensor.setLEDcurrent(16);\n proxim_sensor.setProximityRate(VCNL4010_62_5Hz);\n\n \/\/ prepare hardware interrupt\n pinMode(A1, INPUT_PULLUP);\n attachInterrupt(A1, proximThreshold, FALLING);\n delay(1);\n proxim_sensor.setProximThresholdInterrupt(3);\n proxim_sensor.setLowThreshold(0);\n proxim_sensor.setHighThreshold(Proxim::THRESHOLD);\n proxim_sensor.activateProximityThresholdInterrupt();\n\n \/\/ RTC\n if (!rtc.begin()) {\n PRINTLN(\"Couldn't find RTC!\");\n while (1)\n ;\n }\n\n \/\/ Configure pins for Adafruit ATWINC1500 Feather\n WiFi.setPins(8, 7, 4, 2);\n \/\/ Check for the presence of the shield\n PRINTLN(\"Connecting to the Wifi module...\");\n if (WiFi.status() == WL_NO_SHIELD) {\n PRINTLN(\"WiFi shield not present\");\n return; \/\/ don't continue\n }\n\n mqtt_client.connect_wifi(MY_WIFI_SSID, MY_WIFI_PASS);\n status_led.warning(); \/\/ not done yet with setup!\n mqtt_client.setServer(MQTT_SERVER, MQTT_PORT);\n mqtt_client.connect_client();\n status_led.warning(); \/\/ not done yet with setup!\n\n PRINTLN(\"MQTT client connected.\");\n const char* msg = \"Catdoor v2 started\";\n DateTime utc_time = rtc.now();\n unsigned int now = millis();\n DateTime local_time = utc_time.getLocalTime(TIME_ZONE_OFFSET);\n mqtt_client.sync_time(local_time, now);\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, msg);\n \/\/ start by flashing like in the darkness..\n status_led.alive();\n\n wdt_configure(4);\n}\n\nvoid loop() {\n static bool cat_exiting = false;\n static bool daylight = false;\n static bool rtc_read = true;\n static unsigned long last_time = millis();\n static unsigned long last_unjam = millis();\n unsigned long now = millis();\n unsigned long elapsed;\n unsigned long sleep_ms;\n static Solenoids::state_t prev_actuators_state = Solenoids::OFF;\n\n if ((now - last_time) > 10 * 1000) {\n if (rtc_read) {\n \/\/ Check RC every 20s\n DateTime ltime = rtc.now().getLocalTime(TIME_ZONE_OFFSET);\n mqtt_client.sync_time(ltime, now);\n uint16_t day = ltime.yDay();\n if (day == 366)\n day = 1; \/\/ We will be one day offset for all leap years...\n DateTime sunrise(ltime.year(), ltime.month(), ltime.day(),\n sunset_sunrise_times[day - 1][0],\n sunset_sunrise_times[day - 1][1], 0, TIME_ZONE_OFFSET);\n DateTime sunset(ltime.year(), ltime.month(), ltime.day(),\n sunset_sunrise_times[day - 1][2],\n sunset_sunrise_times[day - 1][3], 0, TIME_ZONE_OFFSET);\n DateTime morning = sunrise + margin_after_sunrise;\n DateTime afternoon = sunset - margin_before_sunset;\n if (false || (morning < ltime && ltime < afternoon)) {\n status_led.ok(); \/\/ safe to repeat without breaking the pattern\n if (!daylight) {\n daylight = true;\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, \"UNLOCKED\");\n }\n } \/\/ if daylight\n else {\n status_led.alive(); \/\/ safe to repeat without breaking the pattern\n if (daylight) {\n daylight = false;\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, \"LOCKED\");\n }\n } \/\/ else daylight\n rtc_read = false;\n mqtt_client.publish_timed_msg(now, TOPIC_HEARTBEAT,\n daylight ? \"DAYLIGHT\" : \"DARK\");\n } else {\n \/\/ alternate with reading the battery voltage\n float measuredvbat = analogRead(VBATPIN);\n measuredvbat *= 2; \/\/ we divided by 2, so multiply back\n measuredvbat *= 3.3; \/\/ Multiply by 3.3V, our reference voltage\n measuredvbat \/= 1024; \/\/ convert to voltage\n char num[6];\n dtostrf(measuredvbat, 5, 2, num);\n char str[12];\n sprintf(str, \"VBAT=%s\", num);\n mqtt_client.publish_timed_msg(now, TOPIC_BATTERY_V, str);\n rtc_read = true;\n }\n\n last_time = now;\n } \/\/ if 10s\n\n \/\/ Process accelerometer\n if (accel_sensor.data_ready) {\n accel_sensor.process();\n if (accel_sensor.new_state) {\n PRINTLN(ACCEL_STATES_NAMES[(uint8_t)accel_sensor.state]);\n accel_sensor.new_state = false;\n mqtt_client.publish_timed_msg(\n now, TOPIC_DOORSTATE,\n ACCEL_STATES_NAMES[(uint8_t)accel_sensor.state]);\n }\n }\n\n \/\/ Check if cat is in front of door\n if (proxim_sensor.new_state) {\n proxim_sensor.process();\n if (proxim_sensor.state == Proxim::CAT) {\n PRINTLN(\"CAT\");\n mqtt_client.publish_timed_msg(now, TOPIC_PROXIMITY, \"CAT\");\n if (daylight && accel_sensor.state == Accel::CLOSED) {\n \/\/ Retract the door locks!\n if (sol_actuators.state() == Solenoids::OFF) {\n sol_actuators.open();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"RETRACTED\");\n }\n }\n } else {\n PRINTLN(\"CLEAR\");\n mqtt_client.publish_timed_msg(now, TOPIC_PROXIMITY, \"CLEAR\");\n }\n }\n\n \/\/ Mark that cat is going out (to release the solenoids later)\n if (sol_actuators.state() == Solenoids::ON &&\n accel_sensor.state == Accel::OPEN_OUT) {\n cat_exiting = true;\n }\n\n \/\/ Release solenoids if cat finished exiting\n if (cat_exiting && accel_sensor.state == Accel::CLOSED &&\n sol_actuators.state() == Solenoids::ON &&\n proxim_sensor.state == Proxim::CLEAR) {\n sol_actuators.release();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"RELEASE\");\n cat_exiting = false;\n }\n\n \/\/ Detect jammed condition and try to resolve it\n if (accel_sensor.state == Accel::JAMMED &&\n sol_actuators.state() == Solenoids::OFF) {\n if ((now - last_unjam) > Solenoids::COOLDOWN_DURATION_MS) {\n last_unjam = now;\n sol_actuators.unjam();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"UNJAM\");\n }\n }\n\n \/\/ Check a hot release\n if (sol_actuators.state() != prev_actuators_state) {\n if (prev_actuators_state == Solenoids::ON &&\n sol_actuators.state() == Solenoids::HOT) {\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"HOT_RELEASE\");\n }\n prev_actuators_state = sol_actuators.state();\n }\n\n \/\/ Let the MQTT client do some work\n mqtt_client.loop();\n\n elapsed = millis() - now;\n if (elapsed > LOOP_PERIOD_MS) {\n PRINT(\"==== warning, loop overrun: \");\n PRINTLN(elapsed);\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, \"LOOP OVERRUN\");\n sleep_ms = 0;\n } else {\n sleep_ms = LOOP_PERIOD_MS - elapsed;\n }\n\n \/\/ Say we are still alive!\n wdt_reset();\n\n \/\/ Loop is variable period, but we do not really care...\n delay(sleep_ms);\n}\n<commit_msg>Added a solenoid release condition if the cat is not well decided + some tuning<commit_after>#include \"RTClib.h\"\n#include \"accel.h\"\n#include \"daytimes.h\"\n#include \"ledctrl.h\"\n#include \"m0_hf_pwm.h\"\n#include \"mqtt_client.h\"\n#include \"netcfg.h\"\n#include \"proxim.h\"\n#include \"solenoids.h\"\n#include \"utils.h\"\n#include \"watchdog_timer.h\"\n\n\/\/ For float to string formatting\n#include <avr\/dtostrf.h>\n\n\/\/ Where to get the battery voltage\n#define VBATPIN A7\n\n\/\/ Customization for acceptable daylight times\nstatic const TimeSpan margin_after_sunrise(0, 0, 45, 0);\nstatic const TimeSpan margin_before_sunset(0, 2, 0, 0);\n\nstatic const unsigned long LOOP_PERIOD_MS = 25;\n\n\/\/ global objects...\nRTC_DS3231 rtc;\nAccel accel_sensor;\nProxim proxim_sensor;\nSolenoids& sol_actuators = Solenoids::Instance();\nLedCtrl& status_led = LedCtrl::Instance();\nWiFiClient wifi_client;\nMQTT_Client mqtt_client(wifi_client, status_led);\n\n\/\/ interupts function prototypes\nvoid proximThreshold() { proxim_sensor.new_state = true; }\n\nvoid accelReady() { accel_sensor.data_ready = true; }\n\nvoid setup() {\n wdt_configure(11);\n\n \/\/ HF PWM\n pwm_configure();\n\n \/\/ let things stabilize before pulling too much current\n \/\/ not necessary, but surprise the developer less also\n delay(1000);\n\n \/\/ Force unjam, no matter what, just in case we rebooted\n \/\/ Also this says Hi to the world\n sol_actuators.unjam();\n\n \/\/ start in unkown state\n status_led.warning();\n\n#ifdef USE_SERIAL\n Serial.begin(115200);\n while (!Serial) {\n ; \/\/ wait for serial port to connect to start the app\n }\n\/\/ Serial.print(\"sizeof(int)=\");\n\/\/ Serial.println(sizeof(int));\n#endif\n\n \/\/\n \/\/ Accelerometer setup\n \/\/\n if (!accel_sensor.begin(0x18)) {\n PRINTLN(\"Couldnt start accelerometer!\");\n while (1)\n ;\n }\n PRINTLN(\"LIS3DH found.\");\n\n \/\/ configure sensor\n accel_sensor.setDataRate(LIS3DH_DATARATE_10_HZ);\n accel_sensor.setRange(LIS3DH_RANGE_2_G);\n\n \/\/ attach hardware interrupt\n pinMode(A2, INPUT_PULLUP);\n attachInterrupt(A2, accelReady, RISING);\n delay(1); \/\/ for some reason, this delay is CRITICAL!\n accel_sensor.read(); \/\/ read reset the signal --> start interrupts\n\n \/\/\n \/\/ Proximity sensor setup\n \/\/\n if (!proxim_sensor.begin()) {\n PRINTLN(\"Proximity sensor not found!\");\n while (1)\n ;\n }\n PRINTLN(\"VCNL4010 found.\");\n\n \/\/ configure sensor\n proxim_sensor.setModulatorFrequency(VCNL4010_390K625);\n proxim_sensor.setLEDcurrent(16);\n proxim_sensor.setProximityRate(VCNL4010_62_5Hz);\n\n \/\/ prepare hardware interrupt\n pinMode(A1, INPUT_PULLUP);\n attachInterrupt(A1, proximThreshold, FALLING);\n delay(1);\n proxim_sensor.setProximThresholdInterrupt(3);\n proxim_sensor.setLowThreshold(0);\n proxim_sensor.setHighThreshold(Proxim::THRESHOLD);\n proxim_sensor.activateProximityThresholdInterrupt();\n\n \/\/ RTC\n if (!rtc.begin()) {\n PRINTLN(\"Couldn't find RTC!\");\n while (1)\n ;\n }\n\n \/\/ Configure pins for Adafruit ATWINC1500 Feather\n WiFi.setPins(8, 7, 4, 2);\n \/\/ Check for the presence of the shield\n PRINTLN(\"Connecting to the Wifi module...\");\n if (WiFi.status() == WL_NO_SHIELD) {\n PRINTLN(\"WiFi shield not present\");\n return; \/\/ don't continue\n }\n\n mqtt_client.connect_wifi(MY_WIFI_SSID, MY_WIFI_PASS);\n status_led.warning(); \/\/ not done yet with setup!\n mqtt_client.setServer(MQTT_SERVER, MQTT_PORT);\n mqtt_client.connect_client();\n status_led.warning(); \/\/ not done yet with setup!\n\n PRINTLN(\"MQTT client connected.\");\n const char* msg = \"Catdoor v2 started\";\n DateTime utc_time = rtc.now();\n unsigned int now = millis();\n DateTime local_time = utc_time.getLocalTime(TIME_ZONE_OFFSET);\n mqtt_client.sync_time(local_time, now);\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, msg);\n \/\/ start by flashing like in the darkness..\n status_led.alive();\n\n wdt_configure(4);\n}\n\nvoid loop() {\n static bool cat_exiting = false;\n static bool daylight = false;\n static bool rtc_read = true;\n static unsigned long last_time = millis();\n static unsigned long last_unjam = last_time;\n static unsigned long door_clear_time = last_time;\n unsigned long now = millis();\n unsigned long elapsed;\n unsigned long sleep_ms;\n static Solenoids::state_t prev_actuators_state = Solenoids::OFF;\n static char buffer[24];\n\n if ((now - last_time) > 10 * 1000) {\n if (rtc_read) {\n \/\/ Check RC every 20s\n DateTime ltime = rtc.now().getLocalTime(TIME_ZONE_OFFSET);\n mqtt_client.sync_time(ltime, now);\n uint16_t day = ltime.yDay();\n if (day == 366)\n day = 1; \/\/ We will be one day offset for all leap years...\n DateTime sunrise(ltime.year(), ltime.month(), ltime.day(),\n sunset_sunrise_times[day - 1][0],\n sunset_sunrise_times[day - 1][1], 0, TIME_ZONE_OFFSET);\n DateTime sunset(ltime.year(), ltime.month(), ltime.day(),\n sunset_sunrise_times[day - 1][2],\n sunset_sunrise_times[day - 1][3], 0, TIME_ZONE_OFFSET);\n DateTime morning = sunrise + margin_after_sunrise;\n DateTime afternoon = sunset - margin_before_sunset;\n if (false || (morning < ltime && ltime < afternoon)) {\n status_led.ok(); \/\/ safe to repeat without breaking the pattern\n if (!daylight) {\n daylight = true;\n sprintf(buffer, \"%s %d:%d\", \"UNLOCKED\", afternoon.hour(),\n afternoon.minute());\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, buffer);\n }\n } \/\/ if daylight\n else {\n status_led.alive(); \/\/ safe to repeat without breaking the pattern\n if (daylight) {\n daylight = false;\n sprintf(buffer, \"%s %d:%d\", \"LOCKED\", morning.hour(),\n morning.minute());\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, buffer);\n }\n } \/\/ else daylight\n rtc_read = false;\n mqtt_client.publish_timed_msg(now, TOPIC_HEARTBEAT,\n daylight ? \"DAYLIGHT\" : \"DARK\");\n } else {\n \/\/ alternate with reading the battery voltage\n float measuredvbat = analogRead(VBATPIN);\n measuredvbat *= 2; \/\/ we divided by 2, so multiply back\n measuredvbat *= 3.3; \/\/ Multiply by 3.3V, our reference voltage\n measuredvbat \/= 1024; \/\/ convert to voltage\n char num[6];\n dtostrf(measuredvbat, 5, 2, num);\n \/\/ char str[12];\n \/\/ sprintf(str, \"VBAT %s\", num);\n mqtt_client.publish_timed_msg(now, TOPIC_BATTERY_V, num);\n rtc_read = true;\n }\n\n last_time = now;\n } \/\/ if 10s\n\n \/\/ Process accelerometer\n if (accel_sensor.data_ready) {\n accel_sensor.process();\n if (accel_sensor.new_state) {\n PRINTLN(ACCEL_STATES_NAMES[(uint8_t)accel_sensor.state]);\n accel_sensor.new_state = false;\n mqtt_client.publish_timed_msg(\n now, TOPIC_DOORSTATE,\n ACCEL_STATES_NAMES[(uint8_t)accel_sensor.state]);\n }\n }\n\n \/\/ Check if cat is in front of door\n if (proxim_sensor.new_state) {\n proxim_sensor.process();\n if (proxim_sensor.state == Proxim::CAT) {\n PRINTLN(\"CAT\");\n mqtt_client.publish_timed_msg(now, TOPIC_PROXIMITY, \"CAT\");\n if (daylight && accel_sensor.state == Accel::CLOSED) {\n \/\/ Retract the door locks!\n if (sol_actuators.state() == Solenoids::OFF) {\n sol_actuators.open();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"RETRACTED\");\n }\n }\n } else {\n PRINTLN(\"CLEAR\");\n door_clear_time = now;\n mqtt_client.publish_timed_msg(now, TOPIC_PROXIMITY, \"CLEAR\");\n }\n }\n\n \/\/ Relase if the cat give up after 12s (to avoid a HOT_RELEASE much later)\n if (proxim_sensor.state == Proxim::CLEAR &&\n sol_actuators.state() == Solenoids::ON &&\n accel_sensor.state == Accel::CLOSED && (now - door_clear_time) > 12000) {\n sol_actuators.release();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"RELEASE\");\n }\n\n \/\/ Mark that cat is going out (to release the solenoids later)\n if (sol_actuators.state() == Solenoids::ON &&\n accel_sensor.state == Accel::OPEN_OUT) {\n cat_exiting = true;\n }\n\n \/\/ Release solenoids if cat finished exiting\n if (cat_exiting && accel_sensor.state == Accel::CLOSED &&\n sol_actuators.state() == Solenoids::ON &&\n proxim_sensor.state == Proxim::CLEAR) {\n sol_actuators.release();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"RELEASE\");\n cat_exiting = false;\n }\n\n \/\/ Detect jammed condition and try to resolve it\n if (accel_sensor.state == Accel::JAMMED &&\n sol_actuators.state() == Solenoids::OFF) {\n if ((now - last_unjam) > Solenoids::COOLDOWN_DURATION_MS) {\n last_unjam = now;\n sol_actuators.unjam();\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"UNJAM\");\n }\n }\n\n \/\/ Check a hot release\n if (sol_actuators.state() != prev_actuators_state) {\n if (prev_actuators_state == Solenoids::ON &&\n sol_actuators.state() == Solenoids::HOT) {\n mqtt_client.publish_timed_msg(now, TOPIC_SOLENOIDS, \"HOT_RELEASE\");\n }\n prev_actuators_state = sol_actuators.state();\n }\n\n \/\/ Let the MQTT client do some work\n mqtt_client.loop();\n\n elapsed = millis() - now;\n if (elapsed > LOOP_PERIOD_MS) {\n PRINT(\"==== warning, loop overrun: \");\n PRINTLN(elapsed);\n mqtt_client.publish_timed_msg(now, TOPIC_MESSAGE, \"LOOP OVERRUN\");\n sleep_ms = 0;\n } else {\n sleep_ms = LOOP_PERIOD_MS - elapsed;\n }\n\n \/\/ Say we are still alive!\n wdt_reset();\n\n \/\/ Loop is variable period, but we do not really care...\n delay(sleep_ms);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtOpenGL module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qtextureglyphcache_gl_p.h\"\n#include \"qpaintengineex_opengl2_p.h\"\n\n#ifdef Q_WS_WIN\nextern Q_GUI_EXPORT bool qt_cleartype_enabled;\n#endif\n\nQGLTextureGlyphCache::QGLTextureGlyphCache(QGLContext *context, QFontEngineGlyphCache::Type type, const QTransform &matrix)\n : QTextureGlyphCache(type, matrix)\n , ctx(context)\n , m_width(0)\n , m_height(0)\n{\n glGenFramebuffers(1, &m_fbo);\n connect(QGLSignalProxy::instance(), SIGNAL(aboutToDestroyContext(const QGLContext*)),\n SLOT(contextDestroyed(const QGLContext*)));\n}\n\nQGLTextureGlyphCache::~QGLTextureGlyphCache()\n{\n if (ctx) {\n QGLShareContextScope scope(ctx);\n glDeleteFramebuffers(1, &m_fbo);\n\n if (m_width || m_height)\n glDeleteTextures(1, &m_texture);\n }\n}\n\nvoid QGLTextureGlyphCache::createTextureData(int width, int height)\n{\n glGenTextures(1, &m_texture);\n glBindTexture(GL_TEXTURE_2D, m_texture);\n\n m_width = width;\n m_height = height;\n\n QVarLengthArray<uchar> data(width * height);\n for (int i = 0; i < data.size(); ++i)\n data[i] = 0;\n\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]);\n else\n glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]);\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n}\n\nvoid QGLTextureGlyphCache::resizeTextureData(int width, int height)\n{\n \/\/ ### the QTextureGlyphCache API needs to be reworked to allow\n \/\/ ### resizeTextureData to fail\n\n int oldWidth = m_width;\n int oldHeight = m_height;\n\n GLuint oldTexture = m_texture;\n createTextureData(width, height);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fbo);\n\n GLuint tmp_texture;\n glGenTextures(1, &tmp_texture);\n glBindTexture(GL_TEXTURE_2D, tmp_texture);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,\n GL_RGBA, GL_UNSIGNED_BYTE, NULL);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n glBindTexture(GL_TEXTURE_2D, 0);\n glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,\n GL_TEXTURE_2D, tmp_texture, 0);\n\n glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);\n glBindTexture(GL_TEXTURE_2D, oldTexture);\n\n pex->transferMode(BrushDrawingMode);\n\n glDisable(GL_STENCIL_TEST);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_SCISSOR_TEST);\n glDisable(GL_BLEND);\n\n glViewport(0, 0, oldWidth, oldHeight);\n\n GLfloat* vertexCoordinateArray = pex->staticVertexCoordinateArray;\n vertexCoordinateArray[0] = -1.0f;\n vertexCoordinateArray[1] = -1.0f;\n vertexCoordinateArray[2] = 1.0f;\n vertexCoordinateArray[3] = -1.0f;\n vertexCoordinateArray[4] = 1.0f;\n vertexCoordinateArray[5] = 1.0f;\n vertexCoordinateArray[6] = -1.0f;\n vertexCoordinateArray[7] = 1.0f;\n\n GLfloat* textureCoordinateArray = pex->staticTextureCoordinateArray;\n textureCoordinateArray[0] = 0.0f;\n textureCoordinateArray[1] = 0.0f;\n textureCoordinateArray[2] = 1.0f;\n textureCoordinateArray[3] = 0.0f;\n textureCoordinateArray[4] = 1.0f;\n textureCoordinateArray[5] = 1.0f;\n textureCoordinateArray[6] = 0.0f;\n textureCoordinateArray[7] = 1.0f;\n\n pex->setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertexCoordinateArray);\n pex->setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, textureCoordinateArray);\n\n pex->shaderManager->useBlitProgram();\n pex->shaderManager->blitProgram()->setUniformValue(\"imageTexture\", QT_IMAGE_TEXTURE_UNIT);\n\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n glBindTexture(GL_TEXTURE_2D, m_texture);\n\n#ifdef QT_OPENGL_ES_2\n QDataBuffer<uchar> buffer(4*oldWidth*oldHeight);\n buffer.resize(4*oldWidth*oldHeight);\n glReadPixels(0, 0, oldWidth, oldHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());\n\n \/\/ do an in-place conversion from GL_RGBA to GL_ALPHA\n for (int i=0; i<oldWidth*oldHeight; ++i)\n buffer.data()[i] = buffer.at(4*i + 3);\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, oldWidth, oldHeight,\n GL_ALPHA, GL_UNSIGNED_BYTE, buffer.data());\n#else\n glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);\n#endif\n\n glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,\n GL_RENDERBUFFER_EXT, 0);\n glDeleteTextures(1, &tmp_texture);\n glDeleteTextures(1, &oldTexture);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo);\n\n glViewport(0, 0, pex->width, pex->height);\n pex->updateClipScissorTest();\n}\n\nvoid QGLTextureGlyphCache::fillTexture(const Coord &c, glyph_t glyph)\n{\n QImage mask = textureMapForGlyph(glyph);\n const int maskWidth = mask.width();\n const int maskHeight = mask.height();\n\n if (mask.format() == QImage::Format_Mono) {\n mask = mask.convertToFormat(QImage::Format_Indexed8);\n for (int y = 0; y < maskHeight; ++y) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < maskWidth; ++x)\n src[x] = -src[x]; \/\/ convert 0 and 1 into 0 and 255\n }\n }\n\n\n glBindTexture(GL_TEXTURE_2D, m_texture);\n if (mask.format() == QImage::Format_RGB32) {\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_BGRA, GL_UNSIGNED_BYTE, mask.bits());\n } else {\n#ifdef QT_OPENGL_ES2\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_ALPHA, GL_UNSIGNED_BYTE, mask.bits());\n#else\n \/\/ glTexSubImage2D() might cause some garbage to appear in the texture if the mask width is\n \/\/ not a multiple of four bytes. The bug appeared on a computer with 32-bit Windows Vista\n \/\/ and nVidia GeForce 8500GT. GL_UNPACK_ALIGNMENT is set to four bytes, 'mask' has a\n \/\/ multiple of four bytes per line, and most of the glyph shows up correctly in the\n \/\/ texture, which makes me think that this is a driver bug.\n \/\/ One workaround is to make sure the mask width is a multiple of four bytes, for instance\n \/\/ by converting it to a format with four bytes per pixel. Another is to copy one line at a\n \/\/ time.\n\n for (int i = 0; i < maskHeight; ++i)\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y + i, maskWidth, 1, GL_ALPHA, GL_UNSIGNED_BYTE, mask.scanLine(i));\n#endif\n }\n}\n\nint QGLTextureGlyphCache::glyphMargin() const\n{\n#if defined(Q_WS_MAC)\n return 2;\n#elif defined (Q_WS_X11)\n return 0;\n#else\n return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;\n#endif\n}\n<commit_msg>Fixed subpixel antialiased text drawing with the GL2 engine.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtOpenGL module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qtextureglyphcache_gl_p.h\"\n#include \"qpaintengineex_opengl2_p.h\"\n\n#ifdef Q_WS_WIN\nextern Q_GUI_EXPORT bool qt_cleartype_enabled;\n#endif\n\nQGLTextureGlyphCache::QGLTextureGlyphCache(QGLContext *context, QFontEngineGlyphCache::Type type, const QTransform &matrix)\n : QTextureGlyphCache(type, matrix)\n , ctx(context)\n , m_width(0)\n , m_height(0)\n{\n glGenFramebuffers(1, &m_fbo);\n connect(QGLSignalProxy::instance(), SIGNAL(aboutToDestroyContext(const QGLContext*)),\n SLOT(contextDestroyed(const QGLContext*)));\n}\n\nQGLTextureGlyphCache::~QGLTextureGlyphCache()\n{\n if (ctx) {\n QGLShareContextScope scope(ctx);\n glDeleteFramebuffers(1, &m_fbo);\n\n if (m_width || m_height)\n glDeleteTextures(1, &m_texture);\n }\n}\n\nvoid QGLTextureGlyphCache::createTextureData(int width, int height)\n{\n glGenTextures(1, &m_texture);\n glBindTexture(GL_TEXTURE_2D, m_texture);\n\n m_width = width;\n m_height = height;\n\n QVarLengthArray<uchar> data(width * height);\n for (int i = 0; i < data.size(); ++i)\n data[i] = 0;\n\n if (m_type == QFontEngineGlyphCache::Raster_RGBMask)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]);\n else\n glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]);\n\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n}\n\nvoid QGLTextureGlyphCache::resizeTextureData(int width, int height)\n{\n \/\/ ### the QTextureGlyphCache API needs to be reworked to allow\n \/\/ ### resizeTextureData to fail\n\n int oldWidth = m_width;\n int oldHeight = m_height;\n\n GLuint oldTexture = m_texture;\n createTextureData(width, height);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fbo);\n\n GLuint tmp_texture;\n glGenTextures(1, &tmp_texture);\n glBindTexture(GL_TEXTURE_2D, tmp_texture);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, oldWidth, oldHeight, 0,\n GL_RGBA, GL_UNSIGNED_BYTE, NULL);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n glBindTexture(GL_TEXTURE_2D, 0);\n glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,\n GL_TEXTURE_2D, tmp_texture, 0);\n\n glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT);\n glBindTexture(GL_TEXTURE_2D, oldTexture);\n\n pex->transferMode(BrushDrawingMode);\n\n glDisable(GL_STENCIL_TEST);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_SCISSOR_TEST);\n glDisable(GL_BLEND);\n\n glViewport(0, 0, oldWidth, oldHeight);\n\n GLfloat* vertexCoordinateArray = pex->staticVertexCoordinateArray;\n vertexCoordinateArray[0] = -1.0f;\n vertexCoordinateArray[1] = -1.0f;\n vertexCoordinateArray[2] = 1.0f;\n vertexCoordinateArray[3] = -1.0f;\n vertexCoordinateArray[4] = 1.0f;\n vertexCoordinateArray[5] = 1.0f;\n vertexCoordinateArray[6] = -1.0f;\n vertexCoordinateArray[7] = 1.0f;\n\n GLfloat* textureCoordinateArray = pex->staticTextureCoordinateArray;\n textureCoordinateArray[0] = 0.0f;\n textureCoordinateArray[1] = 0.0f;\n textureCoordinateArray[2] = 1.0f;\n textureCoordinateArray[3] = 0.0f;\n textureCoordinateArray[4] = 1.0f;\n textureCoordinateArray[5] = 1.0f;\n textureCoordinateArray[6] = 0.0f;\n textureCoordinateArray[7] = 1.0f;\n\n pex->setVertexAttributePointer(QT_VERTEX_COORDS_ATTR, vertexCoordinateArray);\n pex->setVertexAttributePointer(QT_TEXTURE_COORDS_ATTR, textureCoordinateArray);\n\n pex->shaderManager->useBlitProgram();\n pex->shaderManager->blitProgram()->setUniformValue(\"imageTexture\", QT_IMAGE_TEXTURE_UNIT);\n\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n glBindTexture(GL_TEXTURE_2D, m_texture);\n\n#ifdef QT_OPENGL_ES_2\n QDataBuffer<uchar> buffer(4*oldWidth*oldHeight);\n buffer.resize(4*oldWidth*oldHeight);\n glReadPixels(0, 0, oldWidth, oldHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());\n\n \/\/ do an in-place conversion from GL_RGBA to GL_ALPHA\n for (int i=0; i<oldWidth*oldHeight; ++i)\n buffer.data()[i] = buffer.at(4*i + 3);\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, oldWidth, oldHeight,\n GL_ALPHA, GL_UNSIGNED_BYTE, buffer.data());\n#else\n glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight);\n#endif\n\n glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,\n GL_RENDERBUFFER_EXT, 0);\n glDeleteTextures(1, &tmp_texture);\n glDeleteTextures(1, &oldTexture);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo);\n\n glViewport(0, 0, pex->width, pex->height);\n pex->updateClipScissorTest();\n}\n\nvoid QGLTextureGlyphCache::fillTexture(const Coord &c, glyph_t glyph)\n{\n QImage mask = textureMapForGlyph(glyph);\n const int maskWidth = mask.width();\n const int maskHeight = mask.height();\n\n if (mask.format() == QImage::Format_Mono) {\n mask = mask.convertToFormat(QImage::Format_Indexed8);\n for (int y = 0; y < maskHeight; ++y) {\n uchar *src = (uchar *) mask.scanLine(y);\n for (int x = 0; x < maskWidth; ++x)\n src[x] = -src[x]; \/\/ convert 0 and 1 into 0 and 255\n }\n } else if (mask.format() == QImage::Format_RGB32) {\n \/\/ Make the alpha component equal to the average of the RGB values.\n \/\/ This is needed when drawing sub-pixel antialiased text on translucent targets.\n for (int y = 0; y < maskHeight; ++y) {\n quint32 *src = (quint32 *) mask.scanLine(y);\n for (int x = 0; x < maskWidth; ++x) {\n uchar r = src[x] >> 16;\n uchar g = src[x] >> 8;\n uchar b = src[x];\n quint32 avg = (quint32(r) + quint32(g) + quint32(b) + 1) \/ 3; \/\/ \"+1\" for rounding.\n src[x] = (src[x] & 0x00ffffff) | (avg << 24);\n }\n }\n }\n\n glBindTexture(GL_TEXTURE_2D, m_texture);\n if (mask.format() == QImage::Format_RGB32) {\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_BGRA, GL_UNSIGNED_BYTE, mask.bits());\n } else {\n#ifdef QT_OPENGL_ES2\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_ALPHA, GL_UNSIGNED_BYTE, mask.bits());\n#else\n \/\/ glTexSubImage2D() might cause some garbage to appear in the texture if the mask width is\n \/\/ not a multiple of four bytes. The bug appeared on a computer with 32-bit Windows Vista\n \/\/ and nVidia GeForce 8500GT. GL_UNPACK_ALIGNMENT is set to four bytes, 'mask' has a\n \/\/ multiple of four bytes per line, and most of the glyph shows up correctly in the\n \/\/ texture, which makes me think that this is a driver bug.\n \/\/ One workaround is to make sure the mask width is a multiple of four bytes, for instance\n \/\/ by converting it to a format with four bytes per pixel. Another is to copy one line at a\n \/\/ time.\n\n for (int i = 0; i < maskHeight; ++i)\n glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y + i, maskWidth, 1, GL_ALPHA, GL_UNSIGNED_BYTE, mask.scanLine(i));\n#endif\n }\n}\n\nint QGLTextureGlyphCache::glyphMargin() const\n{\n#if defined(Q_WS_MAC)\n return 2;\n#elif defined (Q_WS_X11)\n return 0;\n#else\n return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: pumptest.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 17:24:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n\n#include <osl\/diagnose.h>\n#include <com\/sun\/star\/test\/XSimpleTest.hpp>\n\n#include <com\/sun\/star\/io\/XActiveDataSource.hpp>\n#include <com\/sun\/star\/io\/XActiveDataSink.hpp>\n#include <com\/sun\/star\/io\/XActiveDataControl.hpp>\n#include <com\/sun\/star\/io\/XConnectable.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n\n#include <uno\/dispatcher.h>\n#include <uno\/mapping.hxx>\n#include <cppuhelper\/implbase1.hxx>\n#include <cppuhelper\/factory.hxx>\n#include <osl\/mutex.hxx>\n#include <osl\/thread.h>\n#include <stl\/list>\n\n\n\n\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::test;\n\n#include \"testfactreg.hxx\"\n\nclass OPumpTest : public WeakImplHelper1 < XSimpleTest >\n{\npublic:\n OPumpTest( const Reference< XMultiServiceFactory > & rFactory );\n ~OPumpTest();\n\npublic: \/\/ implementation names\n static Sequence< OUString > getSupportedServiceNames_Static(void) throw();\n static OUString getImplementationName_Static() throw();\n\npublic:\n virtual void SAL_CALL testInvariant(const OUString& TestName, const Reference < XInterface >& TestObject)\n throw ( IllegalArgumentException, RuntimeException) ;\n\n virtual sal_Int32 SAL_CALL test( const OUString& TestName,\n const Reference < XInterface >& TestObject,\n sal_Int32 hTestHandle)\n throw ( IllegalArgumentException,\n RuntimeException);\n\n virtual sal_Bool SAL_CALL testPassed(void) throw ( RuntimeException) ;\n virtual Sequence< OUString > SAL_CALL getErrors(void) throw (RuntimeException) ;\n virtual Sequence< Any > SAL_CALL getErrorExceptions(void) throw (RuntimeException);\n virtual Sequence< OUString > SAL_CALL getWarnings(void) throw (RuntimeException);\n\nprivate:\n void testSimple( const Reference < XInterface > & );\n\nprivate:\n Sequence<Any> m_seqExceptions;\n Sequence<OUString> m_seqErrors;\n Sequence<OUString> m_seqWarnings;\n\n};\n\nOPumpTest::OPumpTest( const Reference< XMultiServiceFactory > &rFactory )\n{\n\n}\n\nOPumpTest::~OPumpTest()\n{\n\n}\n\n\n\nvoid OPumpTest::testInvariant( const OUString& TestName, const Reference < XInterface >& TestObject )\n throw ( IllegalArgumentException,\n RuntimeException)\n{\n Reference< XServiceInfo > info( TestObject, UNO_QUERY );\n\/\/ ERROR_ASSERT( info.is() , \"XServiceInfo not supported !\" );\n if( info.is() )\n {\n\/\/ ERROR_ASSERT( info->supportsService( TestName ), \"XServiceInfo test failed\" );\n ERROR_ASSERT( ! info->supportsService(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"bla bluzb\") ) ), \"XServiceInfo test failed\" );\n }\n\n Reference < XActiveDataSource > xActiveDataSource( TestObject, UNO_QUERY );\n Reference < XActiveDataSink > xActiveDataSink( TestObject, UNO_QUERY );\n Reference < XActiveDataControl > xActiveDataControl( TestObject , UNO_QUERY );\n Reference < XConnectable > xConnectable( TestObject , UNO_QUERY );\n\n ERROR_ASSERT( xActiveDataSource.is() && xActiveDataSink.is() && xActiveDataControl.is () &&\n xConnectable.is(), \"specified interface not supported\" );\n}\n\n\nsal_Int32 OPumpTest::test(\n const OUString& TestName,\n const Reference < XInterface >& TestObject,\n sal_Int32 hTestHandle)\n throw ( IllegalArgumentException, RuntimeException)\n{\n if( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.io.Pump\") ) == TestName ) {\n try\n {\n if( 0 == hTestHandle ) {\n testInvariant( TestName , TestObject );\n }\n }\n catch( Exception & e )\n {\n OString s = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n BUILD_ERROR( 0 , s.getStr() );\n }\n catch( ... )\n {\n BUILD_ERROR( 0 , \"unknown exception (Exception is not base class)\" );\n }\n\n hTestHandle ++;\n\n if( 1 == hTestHandle )\n {\n \/\/ all tests finished.\n hTestHandle = -1;\n }\n }\n else {\n throw IllegalArgumentException();\n }\n return hTestHandle;\n}\n\n\n\nsal_Bool OPumpTest::testPassed(void) throw (RuntimeException)\n{\n return m_seqErrors.getLength() == 0;\n}\n\n\nSequence< OUString > OPumpTest::getErrors(void) throw (RuntimeException)\n{\n return m_seqErrors;\n}\n\n\nSequence< Any > OPumpTest::getErrorExceptions(void) throw (RuntimeException)\n{\n return m_seqExceptions;\n}\n\n\nSequence< OUString > OPumpTest::getWarnings(void) throw (RuntimeException)\n{\n return m_seqWarnings;\n}\n\n\n\/***\n* the test methods\n*\n****\/\n\n\nvoid OPumpTest::testSimple( const Reference < XInterface > &r )\n{\n \/\/ jbu todo: add sensible test\n\n}\n\nReference< XInterface > SAL_CALL OPumpTest_CreateInstance( const Reference< XMultiServiceFactory > & rSMgr ) throw( Exception )\n{\n return *new OPumpTest( rSMgr );\n}\n\nSequence<OUString> OPumpTest_getSupportedServiceNames(void) throw()\n{\n OUString s = OPumpTest_getServiceName();\n Sequence< OUString > seq( &s , 1 );\n return seq;\n\n}\nOUString OPumpTest_getServiceName() throw()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"test.com.sun.star.io.Pump\" ) );\n}\n\nOUString OPumpTest_getImplementationName() throw()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"test.com.sun.star.comp.io.Pump\") );\n}\n<commit_msg>added a simple pumptest<commit_after>\/*************************************************************************\n *\n * $RCSfile: pumptest.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jbu $ $Date: 2001-01-25 14:06:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n\n#include <osl\/diagnose.h>\n#include <com\/sun\/star\/test\/XSimpleTest.hpp>\n\n#include <com\/sun\/star\/io\/XActiveDataSource.hpp>\n#include <com\/sun\/star\/io\/XActiveDataSink.hpp>\n#include <com\/sun\/star\/io\/XActiveDataControl.hpp>\n#include <com\/sun\/star\/io\/XConnectable.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n\n#include <uno\/dispatcher.h>\n#include <uno\/mapping.hxx>\n#include <cppuhelper\/implbase1.hxx>\n#include <cppuhelper\/factory.hxx>\n#include <osl\/mutex.hxx>\n#include <osl\/thread.h>\n#include <stl\/list>\n\n\n\n\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::test;\n\n#include \"testfactreg.hxx\"\n\nclass OPumpTest : public WeakImplHelper1 < XSimpleTest >\n{\npublic:\n OPumpTest( const Reference< XMultiServiceFactory > & rFactory );\n ~OPumpTest();\n\npublic: \/\/ implementation names\n static Sequence< OUString > getSupportedServiceNames_Static(void) throw();\n static OUString getImplementationName_Static() throw();\n\npublic:\n virtual void SAL_CALL testInvariant(const OUString& TestName, const Reference < XInterface >& TestObject)\n throw ( IllegalArgumentException, RuntimeException) ;\n\n virtual sal_Int32 SAL_CALL test( const OUString& TestName,\n const Reference < XInterface >& TestObject,\n sal_Int32 hTestHandle)\n throw ( IllegalArgumentException,\n RuntimeException);\n\n virtual sal_Bool SAL_CALL testPassed(void) throw ( RuntimeException) ;\n virtual Sequence< OUString > SAL_CALL getErrors(void) throw (RuntimeException) ;\n virtual Sequence< Any > SAL_CALL getErrorExceptions(void) throw (RuntimeException);\n virtual Sequence< OUString > SAL_CALL getWarnings(void) throw (RuntimeException);\n\nprivate:\n void testSimple( const Reference < XInterface > & );\n void testWrongUsage( const Reference < XInterface > & );\n\nprivate:\n Sequence<Any> m_seqExceptions;\n Sequence<OUString> m_seqErrors;\n Sequence<OUString> m_seqWarnings;\n Reference< XMultiServiceFactory > m_rSmgr;\n\n};\n\nOPumpTest::OPumpTest( const Reference< XMultiServiceFactory > &rFactory ) :\n m_rSmgr( rFactory )\n{\n\n}\n\nOPumpTest::~OPumpTest()\n{\n\n}\n\n\n\nvoid OPumpTest::testInvariant( const OUString& TestName, const Reference < XInterface >& TestObject )\n throw ( IllegalArgumentException,\n RuntimeException)\n{\n Reference< XServiceInfo > info( TestObject, UNO_QUERY );\n\/\/ ERROR_ASSERT( info.is() , \"XServiceInfo not supported !\" );\n if( info.is() )\n {\n\/\/ ERROR_ASSERT( info->supportsService( TestName ), \"XServiceInfo test failed\" );\n ERROR_ASSERT( ! info->supportsService(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"bla bluzb\") ) ), \"XServiceInfo test failed\" );\n }\n\n Reference < XActiveDataSource > xActiveDataSource( TestObject, UNO_QUERY );\n Reference < XActiveDataSink > xActiveDataSink( TestObject, UNO_QUERY );\n Reference < XActiveDataControl > xActiveDataControl( TestObject , UNO_QUERY );\n Reference < XConnectable > xConnectable( TestObject , UNO_QUERY );\n\n ERROR_ASSERT( xActiveDataSource.is() && xActiveDataSink.is() && xActiveDataControl.is () &&\n xConnectable.is(), \"specified interface not supported\" );\n}\n\n\nsal_Int32 OPumpTest::test(\n const OUString& TestName,\n const Reference < XInterface >& TestObject,\n sal_Int32 hTestHandle)\n throw ( IllegalArgumentException, RuntimeException)\n{\n if( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.io.Pump\") ) == TestName ) {\n try\n {\n if( 0 == hTestHandle ) {\n testInvariant( TestName , TestObject );\n }\n else if ( 1 == hTestHandle )\n {\n testWrongUsage( TestObject);\n }\n }\n catch( Exception & e )\n {\n OString s = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n BUILD_ERROR( 0 , s.getStr() );\n }\n catch( ... )\n {\n BUILD_ERROR( 0 , \"unknown exception (Exception is not base class)\" );\n }\n\n hTestHandle ++;\n\n if( 2 == hTestHandle )\n {\n \/\/ all tests finished.\n hTestHandle = -1;\n }\n }\n else {\n throw IllegalArgumentException();\n }\n return hTestHandle;\n}\n\n\n\nsal_Bool OPumpTest::testPassed(void) throw (RuntimeException)\n{\n return m_seqErrors.getLength() == 0;\n}\n\n\nSequence< OUString > OPumpTest::getErrors(void) throw (RuntimeException)\n{\n return m_seqErrors;\n}\n\n\nSequence< Any > OPumpTest::getErrorExceptions(void) throw (RuntimeException)\n{\n return m_seqExceptions;\n}\n\n\nSequence< OUString > OPumpTest::getWarnings(void) throw (RuntimeException)\n{\n return m_seqWarnings;\n}\n\n\n\/***\n* the test methods\n*\n****\/\n\n\nvoid OPumpTest::testSimple( const Reference < XInterface > &r )\n{\n \/\/ jbu todo: add sensible test\n\n}\n\nvoid OPumpTest::testWrongUsage( const Reference< XInterface > &r )\n{\n Reference< XActiveDataSource > rSource ( r, UNO_QUERY );\n Reference< XActiveDataSink > rSink( r , UNO_QUERY );\n Reference< XActiveDataControl > rControl( r, UNO_QUERY );\n\n Reference< XInputStream > rIn( m_rSmgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.io.DataInputStream\" )),UNO_QUERY);\n Reference< XOutputStream > rOut( m_rSmgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.io.DataOutputStream\" )),UNO_QUERY);\n\n rSink->setInputStream( rIn );\n rSource->setOutputStream( rOut );\n\n rControl->start();\n\n \/\/wait a second, so that the pumpthread can terminate\n TimeValue w = {1,1};\n osl_waitThread( &w );\n}\n\nReference< XInterface > SAL_CALL OPumpTest_CreateInstance( const Reference< XMultiServiceFactory > & rSMgr ) throw( Exception )\n{\n return *new OPumpTest( rSMgr );\n}\n\nSequence<OUString> OPumpTest_getSupportedServiceNames(void) throw()\n{\n OUString s = OPumpTest_getServiceName();\n Sequence< OUString > seq( &s , 1 );\n return seq;\n\n}\nOUString OPumpTest_getServiceName() throw()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"test.com.sun.star.io.Pump\" ) );\n}\n\nOUString OPumpTest_getImplementationName() throw()\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( \"test.com.sun.star.comp.io.Pump\") );\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <tools\/tempfile.hxx>\n#include \"comdep.hxx\"\n\n#include <rtl\/ustring.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <osl\/file.hxx>\n#include <rtl\/instance.hxx>\n#include <tools\/time.hxx>\n#include <tools\/debug.hxx>\n\n#include <stdio.h>\n\nusing namespace osl;\n\nnamespace { struct TempNameBase_Impl : public rtl::Static< ::rtl::OUString, TempNameBase_Impl > {}; }\n\nstruct TempFile_Impl\n{\n String aName;\n};\n\nOUString ConstructTempDir_Impl()\n{\n \/\/ use system directory\n ::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();\n if ( rTempNameBase_Impl.isEmpty() )\n osl::FileBase::getTempDirURL( rTempNameBase_Impl );\n OUString aName = rTempNameBase_Impl;\n\n \/\/ Make sure that directory ends with a separator\n if( !aName.endsWith( \"\/\" ) )\n aName += \"\/\";\n\n return aName;\n}\n\nvoid CreateTempName_Impl( String& rName, sal_Bool bKeep, sal_Bool bDir = sal_True )\n{\n \/\/ add a suitable tempname\n \/\/ Prefix can have 5 chars, leaving 3 for numbers. 26 ** 3 == 17576\n \/\/ ER 13.07.00 why not radix 36 [0-9A-Z] ?!?\n const unsigned nRadix = 26;\n String aName( rName );\n aName += rtl::OUString(\"sv\");\n\n rName.Erase();\n static unsigned long u = Time::GetSystemTicks();\n for ( unsigned long nOld = u; ++u != nOld; )\n {\n u %= (nRadix*nRadix*nRadix);\n rtl::OUString aTmp = rtl::OUStringBuffer(aName).\n append((sal_Int32)(unsigned)u, nRadix).\n append(\".tmp\").\n makeStringAndClear();\n\n if ( bDir )\n {\n FileBase::RC err = Directory::create( aTmp );\n if ( err == FileBase::E_None )\n {\n \/\/ !bKeep: only for creating a name, not a file or directory\n if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None )\n rName = aTmp;\n break;\n }\n else if ( err != FileBase::E_EXIST )\n {\n \/\/ if f.e. name contains invalid chars stop trying to create dirs\n break;\n }\n }\n else\n {\n DBG_ASSERT( bKeep, \"Too expensive, use directory for creating name!\" );\n File aFile( aTmp );\n FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);\n if ( err == FileBase::E_None )\n {\n rName = aTmp;\n aFile.close();\n break;\n }\n else if ( err != FileBase::E_EXIST )\n {\n \/\/ if f.e. name contains invalid chars stop trying to create files\n break;\n }\n }\n }\n}\n\nString TempFile::CreateTempName()\n{\n \/\/ get correct directory\n String aName = ConstructTempDir_Impl();\n\n \/\/ get TempFile name with default naming scheme\n CreateTempName_Impl( aName, sal_False );\n\n return aName;\n}\n\nTempFile::TempFile()\n : pImp( new TempFile_Impl )\n , bKillingFileEnabled( sal_False )\n{\n \/\/ get correct directory\n pImp->aName = ConstructTempDir_Impl();\n\n \/\/ get TempFile with default naming scheme\n CreateTempName_Impl( pImp->aName, sal_True );\n}\n\nTempFile::TempFile( const String& rLeadingChars, const String* pExtension )\n : pImp( new TempFile_Impl )\n , bKillingFileEnabled( sal_False )\n{\n \/\/ get correct directory\n String aName = ConstructTempDir_Impl();\n\n \/\/ now use special naming scheme ( name takes leading chars and an index counting up from zero\n aName += rLeadingChars;\n for ( sal_Int32 i=0;; i++ )\n {\n rtl::OUStringBuffer aTmpBuffer(aName);\n aTmpBuffer.append(i);\n if ( pExtension )\n aTmpBuffer.append(*pExtension);\n else\n aTmpBuffer.append(\".tmp\");\n rtl::OUString aTmp = aTmpBuffer.makeStringAndClear();\n\n File aFile( aTmp );\n FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);\n if ( err == FileBase::E_None )\n {\n pImp->aName = aTmp;\n aFile.close();\n break;\n }\n else if ( err != FileBase::E_EXIST )\n \/\/ if f.e. name contains invalid chars stop trying to create dirs\n break;\n }\n}\n\nTempFile::~TempFile()\n{\n if ( bKillingFileEnabled )\n {\n File::remove( pImp->aName );\n }\n\n delete pImp;\n}\n\nString TempFile::GetName() const\n{\n rtl::OUString aTmp;\n aTmp = pImp->aName;\n return aTmp;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>tools: TempFile: create a file in ctor, not a directory<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <tools\/tempfile.hxx>\n#include \"comdep.hxx\"\n\n#include <rtl\/ustring.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <osl\/file.hxx>\n#include <rtl\/instance.hxx>\n#include <tools\/time.hxx>\n#include <tools\/debug.hxx>\n\n#include <stdio.h>\n\nusing namespace osl;\n\nnamespace { struct TempNameBase_Impl : public rtl::Static< ::rtl::OUString, TempNameBase_Impl > {}; }\n\nstruct TempFile_Impl\n{\n String aName;\n};\n\nOUString ConstructTempDir_Impl()\n{\n \/\/ use system directory\n ::rtl::OUString& rTempNameBase_Impl = TempNameBase_Impl::get();\n if ( rTempNameBase_Impl.isEmpty() )\n osl::FileBase::getTempDirURL( rTempNameBase_Impl );\n OUString aName = rTempNameBase_Impl;\n\n \/\/ Make sure that directory ends with a separator\n if( !aName.endsWith( \"\/\" ) )\n aName += \"\/\";\n\n return aName;\n}\n\nvoid CreateTempName_Impl( String& rName, sal_Bool bKeep, sal_Bool bDir = sal_True )\n{\n \/\/ add a suitable tempname\n \/\/ Prefix can have 5 chars, leaving 3 for numbers. 26 ** 3 == 17576\n \/\/ ER 13.07.00 why not radix 36 [0-9A-Z] ?!?\n const unsigned nRadix = 26;\n String aName( rName );\n aName += rtl::OUString(\"sv\");\n\n rName.Erase();\n static unsigned long u = Time::GetSystemTicks();\n for ( unsigned long nOld = u; ++u != nOld; )\n {\n u %= (nRadix*nRadix*nRadix);\n rtl::OUString aTmp = rtl::OUStringBuffer(aName).\n append((sal_Int32)(unsigned)u, nRadix).\n append(\".tmp\").\n makeStringAndClear();\n\n if ( bDir )\n {\n FileBase::RC err = Directory::create( aTmp );\n if ( err == FileBase::E_None )\n {\n \/\/ !bKeep: only for creating a name, not a file or directory\n if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None )\n rName = aTmp;\n break;\n }\n else if ( err != FileBase::E_EXIST )\n {\n \/\/ if f.e. name contains invalid chars stop trying to create dirs\n break;\n }\n }\n else\n {\n DBG_ASSERT( bKeep, \"Too expensive, use directory for creating name!\" );\n File aFile( aTmp );\n FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);\n if ( err == FileBase::E_None )\n {\n rName = aTmp;\n aFile.close();\n break;\n }\n else if ( err != FileBase::E_EXIST )\n {\n \/\/ if f.e. name contains invalid chars stop trying to create files\n break;\n }\n }\n }\n}\n\nString TempFile::CreateTempName()\n{\n \/\/ get correct directory\n String aName = ConstructTempDir_Impl();\n\n \/\/ get TempFile name with default naming scheme\n CreateTempName_Impl( aName, sal_False );\n\n return aName;\n}\n\nTempFile::TempFile()\n : pImp( new TempFile_Impl )\n , bKillingFileEnabled( sal_False )\n{\n \/\/ get correct directory\n pImp->aName = ConstructTempDir_Impl();\n\n \/\/ get TempFile with default naming scheme\n CreateTempName_Impl( pImp->aName, sal_True, false );\n}\n\nTempFile::TempFile( const String& rLeadingChars, const String* pExtension )\n : pImp( new TempFile_Impl )\n , bKillingFileEnabled( sal_False )\n{\n \/\/ get correct directory\n String aName = ConstructTempDir_Impl();\n\n \/\/ now use special naming scheme ( name takes leading chars and an index counting up from zero\n aName += rLeadingChars;\n for ( sal_Int32 i=0;; i++ )\n {\n rtl::OUStringBuffer aTmpBuffer(aName);\n aTmpBuffer.append(i);\n if ( pExtension )\n aTmpBuffer.append(*pExtension);\n else\n aTmpBuffer.append(\".tmp\");\n rtl::OUString aTmp = aTmpBuffer.makeStringAndClear();\n\n File aFile( aTmp );\n FileBase::RC err = aFile.open(osl_File_OpenFlag_Create);\n if ( err == FileBase::E_None )\n {\n pImp->aName = aTmp;\n aFile.close();\n break;\n }\n else if ( err != FileBase::E_EXIST )\n \/\/ if f.e. name contains invalid chars stop trying to create dirs\n break;\n }\n}\n\nTempFile::~TempFile()\n{\n if ( bKillingFileEnabled )\n {\n File::remove( pImp->aName );\n }\n\n delete pImp;\n}\n\nString TempFile::GetName() const\n{\n rtl::OUString aTmp;\n aTmp = pImp->aName;\n return aTmp;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2021 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"indexer.h\"\n\nDevice to_device(GstDevice* device)\n{\n GstStructure* struc = gst_device_get_properties(device);\n gchar* display_name = gst_device_get_display_name(device);\n g_free(display_name);\n if (!struc)\n {\n qWarning(\"No properties to handle.\\n\");\n gst_object_unref(device);\n return Device();\n }\n\n GstCaps* caps = gst_device_get_caps(device);\n\n std::string name;\n const char* name_str = gst_structure_get_string(struc, \"model\");\n\n if (name_str)\n {\n name = name_str;\n }\n\n std::string serial;\n const char* serial_str = gst_structure_get_string(struc, \"serial\");\n\n if (serial_str)\n {\n serial = serial_str;\n }\n\n std::string type;\n const char* type_str = gst_structure_get_string(struc, \"type\");\n\n if (type_str)\n {\n type = type_str;\n }\n else\n {\n type = \"unknown\";\n }\n\n Device ret(name, serial, type, caps);\n\n gst_structure_free(struc);\n gst_caps_unref(caps);\n return ret;\n}\n\n\ngboolean Indexer::bus_function(GstBus* \/*bus*\/, GstMessage* message, gpointer user_data)\n{\n GstDevice* device;\n Indexer* self = static_cast<Indexer*>(user_data);\n\n switch (GST_MESSAGE_TYPE(message))\n {\n case GST_MESSAGE_DEVICE_ADDED:\n {\n gst_message_parse_device_added(message, &device);\n auto dev = to_device(device);\n emit self->new_device(dev);\n self->m_mutex.lock();\n self->m_device_list.push_back(dev);\n self->m_mutex.unlock();\n gst_object_unref(device);\n break;\n }\n case GST_MESSAGE_DEVICE_REMOVED:\n {\n gst_message_parse_device_removed(message, &device);\n Device dev = to_device(device);\n\n self->m_mutex.lock();\n\n self->m_device_list.erase(std::remove_if(self->m_device_list.begin(),\n self->m_device_list.end(),\n [&dev](const Device& d) {\n if (dev == d)\n {\n return true;\n }\n return false;\n }),\n self->m_device_list.end());\n\n self->m_mutex.unlock();\n qInfo(\"Device lost: %s\", dev.serial_long().c_str());\n emit self->device_lost(dev);\n gst_object_unref(device);\n break;\n }\n default:\n {\n break;\n }\n }\n\n return G_SOURCE_CONTINUE;\n}\n\n\nIndexer::Indexer()\n{\n\n p_monitor = gst_device_monitor_new();\n\n GstBus* bus = gst_device_monitor_get_bus(p_monitor);\n gst_bus_add_watch(bus, &Indexer::bus_function, this);\n gst_object_unref(bus);\n\n gst_device_monitor_add_filter(p_monitor, \"Video\/Source\/tcam\", NULL);\n gst_device_monitor_start(p_monitor);\n}\n\nIndexer::~Indexer()\n{\n gst_device_monitor_stop(p_monitor);\n\n gst_object_unref(p_monitor);\n}\n\nstd::vector<Device> Indexer::get_device_list()\n{\n QMutexLocker lock(&m_mutex);\n return m_device_list;\n}\n\nvoid Indexer::update()\n{}\n<commit_msg>tcam-capture: Retrieve complete device list before listening to events<commit_after>\/*\n * Copyright 2021 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"indexer.h\"\n\nDevice to_device(GstDevice* device)\n{\n GstStructure* struc = gst_device_get_properties(device);\n gchar* display_name = gst_device_get_display_name(device);\n g_free(display_name);\n if (!struc)\n {\n qWarning(\"No properties to handle.\\n\");\n gst_object_unref(device);\n return Device();\n }\n\n GstCaps* caps = gst_device_get_caps(device);\n\n std::string name;\n const char* name_str = gst_structure_get_string(struc, \"model\");\n\n if (name_str)\n {\n name = name_str;\n }\n\n std::string serial;\n const char* serial_str = gst_structure_get_string(struc, \"serial\");\n\n if (serial_str)\n {\n serial = serial_str;\n }\n\n std::string type;\n const char* type_str = gst_structure_get_string(struc, \"type\");\n\n if (type_str)\n {\n type = type_str;\n }\n else\n {\n type = \"unknown\";\n }\n\n Device ret(name, serial, type, caps);\n\n gst_structure_free(struc);\n gst_caps_unref(caps);\n return ret;\n}\n\n\ngboolean Indexer::bus_function(GstBus* \/*bus*\/, GstMessage* message, gpointer user_data)\n{\n GstDevice* device;\n Indexer* self = static_cast<Indexer*>(user_data);\n\n switch (GST_MESSAGE_TYPE(message))\n {\n case GST_MESSAGE_DEVICE_ADDED:\n {\n gst_message_parse_device_added(message, &device);\n auto dev = to_device(device);\n\n if (std::none_of(self->m_device_list.begin(), self->m_device_list.end(),\n [&dev](const Device& vec_dev)\n {\n if (vec_dev == dev)\n {\n return false;\n }\n return true;\n }))\n {\n emit self->new_device(dev);\n self->m_mutex.lock();\n\n self->m_device_list.push_back(dev);\n\n self->m_mutex.unlock();\n }\n gst_object_unref(device);\n break;\n }\n case GST_MESSAGE_DEVICE_REMOVED:\n {\n gst_message_parse_device_removed(message, &device);\n Device dev = to_device(device);\n\n self->m_mutex.lock();\n\n self->m_device_list.erase(std::remove_if(self->m_device_list.begin(),\n self->m_device_list.end(),\n [&dev](const Device& d) {\n if (dev == d)\n {\n return true;\n }\n return false;\n }),\n self->m_device_list.end());\n\n self->m_mutex.unlock();\n qInfo(\"Device lost: %s\", dev.serial_long().c_str());\n emit self->device_lost(dev);\n gst_object_unref(device);\n break;\n }\n default:\n {\n break;\n }\n }\n\n return G_SOURCE_CONTINUE;\n}\n\n\nIndexer::Indexer()\n{\n\n p_monitor = gst_device_monitor_new();\n\n GstBus* bus = gst_device_monitor_get_bus(p_monitor);\n gst_bus_add_watch(bus, &Indexer::bus_function, this);\n gst_object_unref(bus);\n\n gst_device_monitor_add_filter(p_monitor, \"Video\/Source\/tcam\", NULL);\n\n GList* devices = gst_device_monitor_get_devices(p_monitor);\n\n m_device_list.reserve(g_list_length(devices));\n for (GList* entry = devices; entry != nullptr; entry = entry->next)\n {\n GstDevice* dev = (GstDevice*)entry->data;\n\n auto device = to_device(dev);\n\n m_device_list.push_back(device);\n }\n\n g_list_free(devices);\n\n for (const auto& dev : m_device_list)\n {\n emit new_device(dev);\n }\n\n gst_device_monitor_start(p_monitor);\n}\n\nIndexer::~Indexer()\n{\n gst_device_monitor_stop(p_monitor);\n\n gst_object_unref(p_monitor);\n}\n\nstd::vector<Device> Indexer::get_device_list()\n{\n QMutexLocker lock(&m_mutex);\n return m_device_list;\n}\n\nvoid Indexer::update()\n{}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Very basic Telepathy-Qt <-> Telepathy-Farsight integration.\n *\n * Copyright (C) 2008-2009 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2009 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"farsight-channel.h\"\n#include \"_gen\/farsight-channel.moc.hpp\"\n\n#include <QDebug>\n\n#include <telepathy-farsight\/channel.h>\n#include <telepathy-glib\/channel.h>\n#include <telepathy-glib\/connection.h>\n#include <telepathy-glib\/dbus.h>\n#include <TelepathyQt4\/Client\/Connection>\n#include <TelepathyQt4\/Client\/StreamedMediaChannel>\n\nnamespace Telepathy {\nnamespace Client {\n\nstruct FarsightChannel::Private\n{\n Private(FarsightChannel *parent, StreamedMediaChannel *channel);\n ~Private();\n\n static gboolean busWatch(GstBus *bus,\n GstMessage *message, FarsightChannel::Private *self);\n static void onClosed(TfChannel *tfChannel,\n FarsightChannel::Private *self);\n static void onSessionCreated(TfChannel *tfChannel,\n FsConference *conference, FsParticipant *participant,\n FarsightChannel::Private *self);\n static void onStreamCreated(TfChannel *tfChannel,\n TfStream *stream, FarsightChannel::Private *self);\n static void onSrcPadAdded(TfStream *stream,\n GstPad *pad, FsCodec *codec, FarsightChannel::Private *self);\n static gboolean onRequestResource(TfStream *stream,\n guint direction, gpointer data);\n\n FarsightChannel *parent;\n StreamedMediaChannel *channel;\n Status status;\n TfChannel *tfChannel;\n GstBus *bus;\n GstElement *pipeline;\n GstElement *audio_input;\n GstElement *audio_output;\n};\n\nFarsightChannel::Private::Private(FarsightChannel *parent,\n StreamedMediaChannel *channel)\n : parent(parent),\n channel(channel),\n status(StatusDisconnected),\n tfChannel(0),\n bus(0),\n pipeline(0),\n audio_input(0),\n audio_output(0)\n{\n TpDBusDaemon *dbus = tp_dbus_daemon_dup(0);\n if (!dbus) {\n qWarning() << \"Unable to connect to D-Bus\";\n return;\n }\n\n Connection *connection = channel->connection();\n\n TpConnection *gconnection = tp_connection_new(dbus,\n connection->busName().toAscii(),\n connection->objectPath().toAscii(),\n 0);\n g_object_unref(dbus);\n dbus = 0;\n\n if (!gconnection) {\n qWarning() << \"Unable to construct TpConnection\";\n return;\n }\n\n TpChannel *gchannel = tp_channel_new(gconnection,\n channel->objectPath().toAscii(),\n TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA,\n (TpHandleType) channel->targetHandleType(),\n channel->targetHandle(),\n 0);\n g_object_unref(gconnection);\n gconnection = 0;\n\n if (!gchannel) {\n qWarning() << \"Unable to construct TpChannel\";\n return;\n }\n\n tfChannel = tf_channel_new(gchannel);\n g_object_unref(gchannel);\n gchannel = 0;\n\n if (!tfChannel) {\n qWarning() << \"Unable to construct TfChannel\";\n return;\n }\n\n \/* Set up the telepathy farsight channel *\/\n g_signal_connect(tfChannel, \"closed\",\n G_CALLBACK(&FarsightChannel::Private::onClosed), this);\n g_signal_connect(tfChannel, \"session-created\",\n G_CALLBACK(&FarsightChannel::Private::onSessionCreated), this);\n g_signal_connect(tfChannel, \"stream-created\",\n G_CALLBACK(&FarsightChannel::Private::onStreamCreated), this);\n\n pipeline = gst_pipeline_new (NULL);\n bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));\n\n audio_input = gst_element_factory_make(\"gconfaudiosrc\", NULL);\n gst_object_ref(audio_input);\n gst_object_sink(audio_input);\n\n audio_output = gst_bin_new(\"bin\");\n GstElement *resample = gst_element_factory_make(\"audioresample\", NULL);\n GstElement *audio_sink = gst_element_factory_make(\"gconfaudiosink\", NULL);\n gst_bin_add_many(GST_BIN(audio_output), resample, audio_sink, NULL);\n gst_element_link_many(resample, audio_sink, NULL);\n GstPad *sink = gst_element_get_static_pad(resample, \"sink\");\n GstPad *ghost = gst_ghost_pad_new(\"sink\", sink);\n gst_element_add_pad(GST_ELEMENT(audio_output), ghost);\n gst_object_unref(G_OBJECT(sink));\n gst_object_ref(audio_output);\n gst_object_sink(audio_output);\n\n gst_element_set_state(pipeline, GST_STATE_PLAYING);\n\n status = StatusConnecting;\n emit parent->statusChanged(status);\n}\n\nFarsightChannel::Private::~Private()\n{\n if (tfChannel) {\n g_object_unref(tfChannel);\n tfChannel = 0;\n }\n\n if (bus) {\n g_object_unref(bus);\n bus = 0;\n }\n\n gst_element_set_state(pipeline, GST_STATE_NULL);\n\n if (pipeline) {\n g_object_unref(pipeline);\n pipeline = 0;\n }\n\n if (audio_input) {\n g_object_unref(audio_input);\n audio_input = 0;\n }\n\n if (audio_output) {\n g_object_unref(audio_output);\n audio_output = 0;\n }\n}\n\ngboolean FarsightChannel::Private::busWatch(GstBus *bus,\n GstMessage *message, FarsightChannel::Private *self)\n{\n tf_channel_bus_message(self->tfChannel, message);\n return TRUE;\n}\n\nvoid FarsightChannel::Private::onClosed(TfChannel *tfChannel,\n FarsightChannel::Private *self)\n{\n self->status = StatusDisconnected;\n emit self->parent->statusChanged(self->status);\n}\n\nvoid FarsightChannel::Private::onSessionCreated(TfChannel *tfChannel,\n FsConference *conference, FsParticipant *participant,\n FarsightChannel::Private *self)\n{\n gst_bus_add_watch(self->bus,\n (GstBusFunc) &FarsightChannel::Private::busWatch, self);\n\n gst_bin_add(GST_BIN(self->pipeline), GST_ELEMENT(conference));\n gst_element_set_state(GST_ELEMENT(conference), GST_STATE_PLAYING);\n}\n\nvoid FarsightChannel::Private::onStreamCreated(TfChannel *tfChannel,\n TfStream *stream, FarsightChannel::Private *self)\n{\n guint media_type;\n GstPad *sink;\n\n g_signal_connect(stream, \"src-pad-added\",\n G_CALLBACK(&FarsightChannel::Private::onSrcPadAdded), self);\n g_signal_connect(stream, \"request-resource\",\n G_CALLBACK(&FarsightChannel::Private::onRequestResource), NULL);\n\n g_object_get(stream, \"media-type\", &media_type,\n \"sink-pad\", &sink, NULL);\n\n GstPad *pad;\n switch (media_type) {\n case TP_MEDIA_STREAM_TYPE_AUDIO:\n gst_bin_add(GST_BIN(self->pipeline), self->audio_input);\n gst_element_set_state(self->audio_input, GST_STATE_PLAYING);\n\n pad = gst_element_get_static_pad(self->audio_input, \"src\");\n gst_pad_link(pad, sink);\n break;\n case TP_MEDIA_STREAM_TYPE_VIDEO:\n \/\/ TODO\n break;\n default:\n Q_ASSERT(false);\n }\n\n gst_object_unref(sink);\n}\n\nvoid FarsightChannel::Private::onSrcPadAdded(TfStream *stream,\n GstPad *src, FsCodec *codec, FarsightChannel::Private *self)\n{\n guint media_type;\n\n g_object_get(stream, \"media-type\", &media_type, NULL);\n\n GstPad *pad;\n GstElement *element = 0;\n\n switch (media_type) {\n case TP_MEDIA_STREAM_TYPE_AUDIO:\n element = self->audio_output;\n g_object_ref(element);\n break;\n case TP_MEDIA_STREAM_TYPE_VIDEO:\n \/\/ TODO\n return;\n break;\n default:\n Q_ASSERT(false);\n }\n\n gst_bin_add(GST_BIN(self->pipeline), element);\n\n pad = gst_element_get_static_pad(element, \"sink\");\n gst_element_set_state(element, GST_STATE_PLAYING);\n\n gst_pad_link(src, pad);\n\n self->status = StatusConnected;\n emit self->parent->statusChanged(self->status);\n}\n\ngboolean FarsightChannel::Private::onRequestResource(TfStream *stream,\n guint direction, gpointer data)\n{\n return TRUE;\n}\n\nFarsightChannel::FarsightChannel(StreamedMediaChannel *channel, QObject *parent)\n : QObject(parent),\n mPriv(new Private(this, channel))\n{\n}\n\nFarsightChannel::~FarsightChannel()\n{\n delete mPriv;\n}\n\n}\n}\n<commit_msg>call example: Fixed farsight-channel coding style.<commit_after>\/*\n * Very basic Telepathy-Qt <-> Telepathy-Farsight integration.\n *\n * Copyright (C) 2008-2009 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2009 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"farsight-channel.h\"\n#include \"_gen\/farsight-channel.moc.hpp\"\n\n#include <QDebug>\n\n#include <telepathy-farsight\/channel.h>\n#include <telepathy-glib\/channel.h>\n#include <telepathy-glib\/connection.h>\n#include <telepathy-glib\/dbus.h>\n#include <TelepathyQt4\/Client\/Connection>\n#include <TelepathyQt4\/Client\/StreamedMediaChannel>\n\nnamespace Telepathy {\nnamespace Client {\n\nstruct FarsightChannel::Private\n{\n Private(FarsightChannel *parent, StreamedMediaChannel *channel);\n ~Private();\n\n static gboolean busWatch(GstBus *bus,\n GstMessage *message, FarsightChannel::Private *self);\n static void onClosed(TfChannel *tfChannel,\n FarsightChannel::Private *self);\n static void onSessionCreated(TfChannel *tfChannel,\n FsConference *conference, FsParticipant *participant,\n FarsightChannel::Private *self);\n static void onStreamCreated(TfChannel *tfChannel,\n TfStream *stream, FarsightChannel::Private *self);\n static void onSrcPadAdded(TfStream *stream,\n GstPad *pad, FsCodec *codec, FarsightChannel::Private *self);\n static gboolean onRequestResource(TfStream *stream,\n guint direction, gpointer data);\n\n FarsightChannel *parent;\n StreamedMediaChannel *channel;\n Status status;\n TfChannel *tfChannel;\n GstBus *bus;\n GstElement *pipeline;\n GstElement *audioInput;\n GstElement *audioOutput;\n};\n\nFarsightChannel::Private::Private(FarsightChannel *parent,\n StreamedMediaChannel *channel)\n : parent(parent),\n channel(channel),\n status(StatusDisconnected),\n tfChannel(0),\n bus(0),\n pipeline(0),\n audioInput(0),\n audioOutput(0)\n{\n TpDBusDaemon *dbus = tp_dbus_daemon_dup(0);\n if (!dbus) {\n qWarning() << \"Unable to connect to D-Bus\";\n return;\n }\n\n Connection *connection = channel->connection();\n\n TpConnection *gconnection = tp_connection_new(dbus,\n connection->busName().toAscii(),\n connection->objectPath().toAscii(),\n 0);\n g_object_unref(dbus);\n dbus = 0;\n\n if (!gconnection) {\n qWarning() << \"Unable to construct TpConnection\";\n return;\n }\n\n TpChannel *gchannel = tp_channel_new(gconnection,\n channel->objectPath().toAscii(),\n TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA,\n (TpHandleType) channel->targetHandleType(),\n channel->targetHandle(),\n 0);\n g_object_unref(gconnection);\n gconnection = 0;\n\n if (!gchannel) {\n qWarning() << \"Unable to construct TpChannel\";\n return;\n }\n\n tfChannel = tf_channel_new(gchannel);\n g_object_unref(gchannel);\n gchannel = 0;\n\n if (!tfChannel) {\n qWarning() << \"Unable to construct TfChannel\";\n return;\n }\n\n \/* Set up the telepathy farsight channel *\/\n g_signal_connect(tfChannel, \"closed\",\n G_CALLBACK(&FarsightChannel::Private::onClosed), this);\n g_signal_connect(tfChannel, \"session-created\",\n G_CALLBACK(&FarsightChannel::Private::onSessionCreated), this);\n g_signal_connect(tfChannel, \"stream-created\",\n G_CALLBACK(&FarsightChannel::Private::onStreamCreated), this);\n\n pipeline = gst_pipeline_new(NULL);\n bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));\n\n audioInput = gst_element_factory_make(\"gconfaudiosrc\", NULL);\n gst_object_ref(audioInput);\n gst_object_sink(audioInput);\n\n audioOutput = gst_bin_new(\"bin\");\n GstElement *resample = gst_element_factory_make(\"audioresample\", NULL);\n GstElement *audioSink = gst_element_factory_make(\"gconfaudiosink\", NULL);\n gst_bin_add_many(GST_BIN(audioOutput), resample, audioSink, NULL);\n gst_element_link_many(resample, audioSink, NULL);\n GstPad *sink = gst_element_get_static_pad(resample, \"sink\");\n GstPad *ghost = gst_ghost_pad_new(\"sink\", sink);\n gst_element_add_pad(GST_ELEMENT(audioOutput), ghost);\n gst_object_unref(G_OBJECT(sink));\n gst_object_ref(audioOutput);\n gst_object_sink(audioOutput);\n\n gst_element_set_state(pipeline, GST_STATE_PLAYING);\n\n status = StatusConnecting;\n emit parent->statusChanged(status);\n}\n\nFarsightChannel::Private::~Private()\n{\n if (tfChannel) {\n g_object_unref(tfChannel);\n tfChannel = 0;\n }\n\n if (bus) {\n g_object_unref(bus);\n bus = 0;\n }\n\n gst_element_set_state(pipeline, GST_STATE_NULL);\n\n if (pipeline) {\n g_object_unref(pipeline);\n pipeline = 0;\n }\n\n if (audioInput) {\n g_object_unref(audioInput);\n audioInput = 0;\n }\n\n if (audioOutput) {\n g_object_unref(audioOutput);\n audioOutput = 0;\n }\n}\n\ngboolean FarsightChannel::Private::busWatch(GstBus *bus,\n GstMessage *message, FarsightChannel::Private *self)\n{\n tf_channel_bus_message(self->tfChannel, message);\n return TRUE;\n}\n\nvoid FarsightChannel::Private::onClosed(TfChannel *tfChannel,\n FarsightChannel::Private *self)\n{\n self->status = StatusDisconnected;\n emit self->parent->statusChanged(self->status);\n}\n\nvoid FarsightChannel::Private::onSessionCreated(TfChannel *tfChannel,\n FsConference *conference, FsParticipant *participant,\n FarsightChannel::Private *self)\n{\n gst_bus_add_watch(self->bus,\n (GstBusFunc) &FarsightChannel::Private::busWatch, self);\n\n gst_bin_add(GST_BIN(self->pipeline), GST_ELEMENT(conference));\n gst_element_set_state(GST_ELEMENT(conference), GST_STATE_PLAYING);\n}\n\nvoid FarsightChannel::Private::onStreamCreated(TfChannel *tfChannel,\n TfStream *stream, FarsightChannel::Private *self)\n{\n guint media_type;\n GstPad *sink;\n\n g_signal_connect(stream, \"src-pad-added\",\n G_CALLBACK(&FarsightChannel::Private::onSrcPadAdded), self);\n g_signal_connect(stream, \"request-resource\",\n G_CALLBACK(&FarsightChannel::Private::onRequestResource), NULL);\n\n g_object_get(stream, \"media-type\", &media_type,\n \"sink-pad\", &sink, NULL);\n\n GstPad *pad;\n switch (media_type) {\n case TP_MEDIA_STREAM_TYPE_AUDIO:\n gst_bin_add(GST_BIN(self->pipeline), self->audioInput);\n gst_element_set_state(self->audioInput, GST_STATE_PLAYING);\n\n pad = gst_element_get_static_pad(self->audioInput, \"src\");\n gst_pad_link(pad, sink);\n break;\n case TP_MEDIA_STREAM_TYPE_VIDEO:\n \/\/ TODO\n break;\n default:\n Q_ASSERT(false);\n }\n\n gst_object_unref(sink);\n}\n\nvoid FarsightChannel::Private::onSrcPadAdded(TfStream *stream,\n GstPad *src, FsCodec *codec, FarsightChannel::Private *self)\n{\n guint media_type;\n\n g_object_get(stream, \"media-type\", &media_type, NULL);\n\n GstPad *pad;\n GstElement *element = 0;\n\n switch (media_type) {\n case TP_MEDIA_STREAM_TYPE_AUDIO:\n element = self->audioOutput;\n g_object_ref(element);\n break;\n case TP_MEDIA_STREAM_TYPE_VIDEO:\n \/\/ TODO\n return;\n break;\n default:\n Q_ASSERT(false);\n }\n\n gst_bin_add(GST_BIN(self->pipeline), element);\n\n pad = gst_element_get_static_pad(element, \"sink\");\n gst_element_set_state(element, GST_STATE_PLAYING);\n\n gst_pad_link(src, pad);\n\n self->status = StatusConnected;\n emit self->parent->statusChanged(self->status);\n}\n\ngboolean FarsightChannel::Private::onRequestResource(TfStream *stream,\n guint direction, gpointer data)\n{\n return TRUE;\n}\n\nFarsightChannel::FarsightChannel(StreamedMediaChannel *channel, QObject *parent)\n : QObject(parent),\n mPriv(new Private(this, channel))\n{\n}\n\nFarsightChannel::~FarsightChannel()\n{\n delete mPriv;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Real Logic Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef _SBE_HPP_\n#define _SBE_HPP_\n\n#include <string.h>\n#include <stdint.h>\n#include <limits.h>\n#include <stdexcept>\n\n\/*\n * Types used by C++ codec. Might have to be platform specific at some stage.\n *\/\ntypedef char sbe_char_t;\ntypedef ::int8_t sbe_int8_t;\ntypedef ::int16_t sbe_int16_t;\ntypedef ::int32_t sbe_int32_t;\ntypedef ::int64_t sbe_int64_t;\ntypedef ::uint8_t sbe_uint8_t;\ntypedef ::uint16_t sbe_uint16_t;\ntypedef ::uint32_t sbe_uint32_t;\ntypedef ::uint64_t sbe_uint64_t;\ntypedef float sbe_float_t;\ntypedef double sbe_double_t;\n\nnamespace sbe {\n\n\/*\n * Define some byte ordering macros\n *\/\n#if defined(WIN32) || defined(_WIN32)\n #define SBE_BIG_ENDIAN_ENCODE_16(v) _byteswap_ushort(v)\n #define SBE_BIG_ENDIAN_ENCODE_32(v) _byteswap_ulong(v)\n #define SBE_BIG_ENDIAN_ENCODE_64(v) _byteswap_uint64(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) (v)\n#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n #define SBE_BIG_ENDIAN_ENCODE_16(v) __builtin_bswap16(v) \n #define SBE_BIG_ENDIAN_ENCODE_32(v) __builtin_bswap32(v) \n #define SBE_BIG_ENDIAN_ENCODE_64(v) __builtin_bswap64(v) \n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) (v)\n#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) __builtin_bswap16(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) __builtin_bswap32(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) __builtin_bswap64(v)\n #define SBE_BIG_ENDIAN_ENCODE_16(v) (v)\n #define SBE_BIG_ENDIAN_ENCODE_32(v) (v)\n #define SBE_BIG_ENDIAN_ENCODE_64(v) (v)\n#else\n #error \"Byte Ordering of platform not determined. Set __BYTE_ORDER__ manually before including this file.\"\n#endif\n\n#if defined(SBE_NO_BOUNDS_CHECK)\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (false)\n#elif defined(_MSC_VER)\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (exp)\n#else\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (__builtin_expect(exp,c))\n#endif\n\n#if defined(__GNUC__)\n #define SBE_NULLVALUE_INT8 (INT8_MIN)\n #define SBE_NULLVALUE_INT16 (INT16_MIN)\n #define SBE_NULLVALUE_INT32 (INT32_MIN)\n #define SBE_NULLVALUE_INT64 (INT64_MIN)\n #define SBE_NULLVALUE_UINT8 (UINT8_MAX)\n #define SBE_NULLVALUE_UINT16 (UINT16_MAX)\n #define SBE_NULLVALUE_UINT32 (UINT32_MAX)\n #define SBE_NULLVALUE_UINT64 (UINT64_MAX)\n#elif defined(_MSC_VER)\n \/\/ Visual C++ does not handle minimum integer values properly\n \/\/ See: http:\/\/msdn.microsoft.com\/en-us\/library\/4kh09110.aspx\n #define SBE_NULLVALUE_INT8 (SCHAR_MIN)\n #define SBE_NULLVALUE_INT16 (SHRT_MIN)\n #define SBE_NULLVALUE_INT32 (LONG_MIN)\n #define SBE_NULLVALUE_INT64 (LLONG_MIN)\n #define SBE_NULLVALUE_UINT8 (UCHAR_MAX)\n #define SBE_NULLVALUE_UINT16 (USHRT_MAX)\n #define SBE_NULLVALUE_UINT32 (ULONG_MAX)\n #define SBE_NULLVALUE_UINT64 (ULLONG_MAX)\n#else\n #define SBE_NULLVALUE_INT8 (INT8_MIN)\n #define SBE_NULLVALUE_INT16 (INT16_MIN)\n #define SBE_NULLVALUE_INT32 (INT32_MIN)\n #define SBE_NULLVALUE_INT64 (INT64_MIN)\n #define SBE_NULLVALUE_UINT8 (UINT8_MAX)\n #define SBE_NULLVALUE_UINT16 (UINT16_MAX)\n #define SBE_NULLVALUE_UINT32 (UINT32_MAX)\n #define SBE_NULLVALUE_UINT64 (UINT64_MAX)\n#endif\n\nnamespace MetaAttribute {\n\nenum Attribute\n{\n EPOCH,\n TIME_UNIT,\n SEMANTIC_TYPE\n};\n\n}\n\n}\n\n#endif \/* _SBE_HPP_ *\/\n<commit_msg>[C++]: fix #275. Add __STDC_LIMIT_MACROS before inclusion of stdint.h to comply with C99 requirements.<commit_after>\/*\n * Copyright 2013 Real Logic Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef _SBE_HPP_\n#define _SBE_HPP_\n\n#include <string.h>\n#define __STDC_LIMIT_MACROS\n#include <stdint.h>\n#include <limits.h>\n#include <stdexcept>\n\n\/*\n * Types used by C++ codec. Might have to be platform specific at some stage.\n *\/\ntypedef char sbe_char_t;\ntypedef ::int8_t sbe_int8_t;\ntypedef ::int16_t sbe_int16_t;\ntypedef ::int32_t sbe_int32_t;\ntypedef ::int64_t sbe_int64_t;\ntypedef ::uint8_t sbe_uint8_t;\ntypedef ::uint16_t sbe_uint16_t;\ntypedef ::uint32_t sbe_uint32_t;\ntypedef ::uint64_t sbe_uint64_t;\ntypedef float sbe_float_t;\ntypedef double sbe_double_t;\n\nnamespace sbe {\n\n\/*\n * Define some byte ordering macros\n *\/\n#if defined(WIN32) || defined(_WIN32)\n #define SBE_BIG_ENDIAN_ENCODE_16(v) _byteswap_ushort(v)\n #define SBE_BIG_ENDIAN_ENCODE_32(v) _byteswap_ulong(v)\n #define SBE_BIG_ENDIAN_ENCODE_64(v) _byteswap_uint64(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) (v)\n#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n #define SBE_BIG_ENDIAN_ENCODE_16(v) __builtin_bswap16(v) \n #define SBE_BIG_ENDIAN_ENCODE_32(v) __builtin_bswap32(v) \n #define SBE_BIG_ENDIAN_ENCODE_64(v) __builtin_bswap64(v) \n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) (v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) (v)\n#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n #define SBE_LITTLE_ENDIAN_ENCODE_16(v) __builtin_bswap16(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_32(v) __builtin_bswap32(v)\n #define SBE_LITTLE_ENDIAN_ENCODE_64(v) __builtin_bswap64(v)\n #define SBE_BIG_ENDIAN_ENCODE_16(v) (v)\n #define SBE_BIG_ENDIAN_ENCODE_32(v) (v)\n #define SBE_BIG_ENDIAN_ENCODE_64(v) (v)\n#else\n #error \"Byte Ordering of platform not determined. Set __BYTE_ORDER__ manually before including this file.\"\n#endif\n\n#if defined(SBE_NO_BOUNDS_CHECK)\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (false)\n#elif defined(_MSC_VER)\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (exp)\n#else\n #define SBE_BOUNDS_CHECK_EXPECT(exp,c) (__builtin_expect(exp,c))\n#endif\n\n#if defined(__GNUC__)\n #define SBE_NULLVALUE_INT8 (INT8_MIN)\n #define SBE_NULLVALUE_INT16 (INT16_MIN)\n #define SBE_NULLVALUE_INT32 (INT32_MIN)\n #define SBE_NULLVALUE_INT64 (INT64_MIN)\n #define SBE_NULLVALUE_UINT8 (UINT8_MAX)\n #define SBE_NULLVALUE_UINT16 (UINT16_MAX)\n #define SBE_NULLVALUE_UINT32 (UINT32_MAX)\n #define SBE_NULLVALUE_UINT64 (UINT64_MAX)\n#elif defined(_MSC_VER)\n \/\/ Visual C++ does not handle minimum integer values properly\n \/\/ See: http:\/\/msdn.microsoft.com\/en-us\/library\/4kh09110.aspx\n #define SBE_NULLVALUE_INT8 (SCHAR_MIN)\n #define SBE_NULLVALUE_INT16 (SHRT_MIN)\n #define SBE_NULLVALUE_INT32 (LONG_MIN)\n #define SBE_NULLVALUE_INT64 (LLONG_MIN)\n #define SBE_NULLVALUE_UINT8 (UCHAR_MAX)\n #define SBE_NULLVALUE_UINT16 (USHRT_MAX)\n #define SBE_NULLVALUE_UINT32 (ULONG_MAX)\n #define SBE_NULLVALUE_UINT64 (ULLONG_MAX)\n#else\n #define SBE_NULLVALUE_INT8 (INT8_MIN)\n #define SBE_NULLVALUE_INT16 (INT16_MIN)\n #define SBE_NULLVALUE_INT32 (INT32_MIN)\n #define SBE_NULLVALUE_INT64 (INT64_MIN)\n #define SBE_NULLVALUE_UINT8 (UINT8_MAX)\n #define SBE_NULLVALUE_UINT16 (UINT16_MAX)\n #define SBE_NULLVALUE_UINT32 (UINT32_MAX)\n #define SBE_NULLVALUE_UINT64 (UINT64_MAX)\n#endif\n\nnamespace MetaAttribute {\n\nenum Attribute\n{\n EPOCH,\n TIME_UNIT,\n SEMANTIC_TYPE\n};\n\n}\n\n}\n\n#endif \/* _SBE_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2014-15 Ableton AG, Berlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"CssParser.hpp\"\n\n#include \"Warnings.hpp\"\n\nSUPPRESS_WARNINGS\n#include <boost\/variant\/get.hpp>\n#include <boost\/variant\/variant.hpp>\n#include <gtest\/gtest.h>\nRESTORE_WARNINGS\n\n\/\/========================================================================================\n\nusing namespace aqt::stylesheets;\n\nnamespace\n{\n\nstd::string selectorNames(const StyleSheet& ss,\n size_t propsetIndex,\n size_t selNumber,\n size_t selIndex0,\n size_t selIndex1)\n{\n return ss.propsets[propsetIndex].selectors[selNumber][selIndex0][selIndex1];\n}\n\nstd::string selectorName(const StyleSheet& ss,\n size_t propsetIndex,\n size_t selIndex0,\n size_t selIndex1)\n{\n return ss.propsets[propsetIndex].selectors[0][selIndex0][selIndex1];\n}\n\nstd::string getFirstValue(const PropertyValues& val, const std::string& def = \"\")\n{\n if (!val.empty()) {\n if (const std::string* str = boost::get<std::string>(&val[0])) {\n return *str;\n }\n }\n\n return def;\n}\n\nExpression getExpr(const PropertyValues& val, size_t idx, const Expression& def = {})\n{\n if (!val.empty()) {\n if (const Expression* expr = boost::get<Expression>(&val[idx])) {\n return *expr;\n }\n }\n\n return def;\n}\n\nsize_t getNumberOfValues(const PropertyValues& val)\n{\n return val.size();\n}\n\n} \/\/ anonymous namespace\n\nTEST(CssParserTest, ParserFromString_basic)\n{\n const std::string src =\n \"A { \\n\"\n \" background: red;\\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n\n EXPECT_EQ(ss.propsets[0].properties.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties[0].name, \"background\");\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"red\"));\n}\n\nTEST(CssParserTest, ParserFromString_selectors)\n{\n const std::string src =\n \"A.b { color: #123456; }\\n\"\n \".b { text: 'green'; }\\n\"\n \"A B.b { background: yellow; }\\n\"\n \"A B .b { foreground: black; }\\n\"\n \"A .b .c { foreground: black; }\\n\"\n \".b.a { text: 'a and b'; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 6);\n EXPECT_EQ(selectorName(ss, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 0, 0, 1), \".b\");\n\n EXPECT_EQ(selectorName(ss, 1, 0, 0), \".b\");\n\n EXPECT_EQ(selectorName(ss, 2, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 2, 1, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 2, 1, 1), \".b\");\n\n EXPECT_EQ(selectorName(ss, 3, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 3, 1, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 3, 2, 0), \".b\");\n\n EXPECT_EQ(ss.propsets[3].properties.size(), 1);\n EXPECT_EQ(ss.propsets[3].properties[0].name, \"foreground\");\n EXPECT_EQ(getFirstValue(ss.propsets[3].properties[0].values), std::string(\"black\"));\n\n EXPECT_EQ(selectorName(ss, 4, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 4, 1, 0), \".b\");\n EXPECT_EQ(selectorName(ss, 4, 2, 0), \".c\");\n\n EXPECT_EQ(selectorName(ss, 5, 0, 0), \".b\");\n EXPECT_EQ(selectorName(ss, 5, 0, 1), \".a\");\n}\n\nTEST(CssParserTest, ParserFromString_separatedSelectors)\n{\n const std::string src =\n \"A, B, C { foreground: black; }\\n\"\n \"A.a B.b, A.a C.c { foreground: black; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(selectorNames(ss, 0, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 0, 1, 0, 0), \"B\");\n EXPECT_EQ(selectorNames(ss, 0, 2, 0, 0), \"C\");\n\n EXPECT_EQ(selectorNames(ss, 1, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 0, 1), \".a\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 1, 0), \"B\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 1, 1), \".b\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 0, 1), \".a\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 1, 0), \"C\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 1, 1), \".c\");\n}\n\nTEST(CssParserTest, ParserFromString_childrenSelectors)\n{\n const std::string src = \"A.b > B.c { color: #123456; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(selectorName(ss, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 0, 0, 1), \".b\");\n EXPECT_EQ(selectorName(ss, 0, 1, 0), \">\");\n EXPECT_EQ(selectorName(ss, 0, 2, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 0, 2, 1), \".c\");\n}\n\nTEST(CssParserTest, ParserFromString_properties)\n{\n const std::string src =\n \"X {\\n\"\n \" abc: #123456; \\n\"\n \" def: 'string'; \\n\"\n \" ghi: \\\"string\\\"; \\n\"\n \" jkl: 1234; \\n\"\n \" mno: 123.45; \\n\"\n \" pqr: symbol; \\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 6);\n\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"#123456\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[1].values), std::string(\"string\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[2].values), std::string(\"string\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[3].values), std::string(\"1234\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[4].values), std::string(\"123.45\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[5].values), std::string(\"symbol\"));\n}\n\nTEST(CssParserTest, ParserFromString_stringProperties)\n{\n const std::string src =\n \"X {\\n\"\n \" def: 'str\\\"ing'; \\n\"\n \" ghi: \\\"str'ing\\\"; \\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"str\\\"ing\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[1].values), std::string(\"str'ing\"));\n}\n\nTEST(CssParserTest, ParserFromString_emptyString)\n{\n const std::string src = \"\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyWhitespace)\n{\n const std::string src =\n \"\\n\\n\\n\"\n \"\\t\\t \\n\\r\"\n \"\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyCppComment)\n{\n const std::string src = \"\/\/ Copyright 2014 by Yoyodyne Inc.\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyComment)\n{\n const std::string src = \"\/* Copyright 2014 by Yoyodyne Inc. *\/\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_crlfNewlines)\n{\n const std::string src =\n \"X {\\r\\n\"\n \"abc: #123456; \\r\\n\"\n \"def: 'string'; \\r\\n\"\n \"}\\r\\n\"\n \"X .a {\\r\\n\"\n \"xyz: red;\\r\\n\"\n \"}\\r\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_mixedNewlines)\n{\n const std::string src =\n \"X {\\r\\n\"\n \"abc: #123456; \\n\\r\"\n \"def: 'string'; \\n\"\n \"}\"\n \"X .a {\"\n \"xyz: red;\"\n \"}\\n\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_noNewlines)\n{\n const std::string src =\n \"X {\"\n \"abc: #123456;\"\n \"def: 'string';\"\n \"}\"\n \"X .a {\"\n \"xyz: red;\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_noSemicolons)\n{\n const std::string src =\n \"X {\"\n \" abc: #123456\"\n \" def: 'string'\"\n \"}\"\n \"X .a {\"\n \" xyz: red\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_multipleValues)\n{\n const std::string src =\n \"X {\"\n \" abc: a, b, c, d;\\n\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 1);\n EXPECT_EQ(getNumberOfValues(ss.propsets[0].properties[0].values), 4);\n}\n\nTEST(CssParserTest, ParserFromString_fontFaceDeclarations)\n{\n const std::string src =\n \"\/\/ Copyright\\n\"\n \"@font-face { src: url('..\/..\/Assets\/times.ttf'); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n EXPECT_EQ(ss.fontfaces.size(), 1);\n\n EXPECT_EQ(ss.fontfaces[0].url, \"..\/..\/Assets\/times.ttf\");\n}\n\n\/\/----------------------------------------------------------------------------------------\n\nTEST(CssParserTest, ParserFromString_Expressions)\n{\n const std::string src = \"foo { bar: url('hello world'); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(1, ss.propsets.size());\n EXPECT_EQ(1, ss.propsets[0].properties.size());\n EXPECT_EQ(1, getNumberOfValues(ss.propsets[0].properties[0].values));\n\n EXPECT_EQ(std::string(\"url\"), getExpr(ss.propsets[0].properties[0].values, 0).name);\n EXPECT_EQ((std::vector<std::string>{\"hello world\"}),\n getExpr(ss.propsets[0].properties[0].values, 0).args);\n}\n\nTEST(CssParserTest, ParserFromString_ExpressionsInLists)\n{\n const std::string src =\n \"foo { bar: rgba(123, 45, 92, 0.1), \"\n \" foo(), \"\n \" hsla(320, 100%, 20%, 0.3); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(1, ss.propsets.size());\n EXPECT_EQ(1, ss.propsets[0].properties.size());\n\n EXPECT_EQ(std::string(\"rgba\"), getExpr(ss.propsets[0].properties[0].values, 0).name);\n EXPECT_EQ((std::vector<std::string>{\"123\", \"45\", \"92\", \"0.1\"}),\n getExpr(ss.propsets[0].properties[0].values, 0).args);\n EXPECT_EQ(std::string(\"foo\"), getExpr(ss.propsets[0].properties[0].values, 1).name);\n EXPECT_TRUE(getExpr(ss.propsets[0].properties[0].values, 1).args.empty());\n\n EXPECT_EQ(std::string(\"hsla\"), getExpr(ss.propsets[0].properties[0].values, 2).name);\n EXPECT_EQ((std::vector<std::string>{\"320\", \"100%\", \"20%\", \"0.3\"}),\n getExpr(ss.propsets[0].properties[0].values, 2).args);\n}\n\n\/* Missing tests:\n\n pathological cases:\n - non closed }\n - non closed \"\n - non closed '\n - ambiguous selectors\n - no selectors\n - invalid chars in selector\n - invalid chars in propertyname\n *\/\n<commit_msg>Specify type for default value in method<commit_after>\/*\nCopyright (c) 2014-15 Ableton AG, Berlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"CssParser.hpp\"\n\n#include \"Warnings.hpp\"\n\nSUPPRESS_WARNINGS\n#include <boost\/variant\/get.hpp>\n#include <boost\/variant\/variant.hpp>\n#include <gtest\/gtest.h>\nRESTORE_WARNINGS\n\n\/\/========================================================================================\n\nusing namespace aqt::stylesheets;\n\nnamespace\n{\n\nstd::string selectorNames(const StyleSheet& ss,\n size_t propsetIndex,\n size_t selNumber,\n size_t selIndex0,\n size_t selIndex1)\n{\n return ss.propsets[propsetIndex].selectors[selNumber][selIndex0][selIndex1];\n}\n\nstd::string selectorName(const StyleSheet& ss,\n size_t propsetIndex,\n size_t selIndex0,\n size_t selIndex1)\n{\n return ss.propsets[propsetIndex].selectors[0][selIndex0][selIndex1];\n}\n\nstd::string getFirstValue(const PropertyValues& val, const std::string& def = \"\")\n{\n if (!val.empty()) {\n if (const std::string* str = boost::get<std::string>(&val[0])) {\n return *str;\n }\n }\n\n return def;\n}\n\nExpression getExpr(const PropertyValues& val, size_t idx, const Expression& def = Expression{})\n{\n if (!val.empty()) {\n if (const Expression* expr = boost::get<Expression>(&val[idx])) {\n return *expr;\n }\n }\n\n return def;\n}\n\nsize_t getNumberOfValues(const PropertyValues& val)\n{\n return val.size();\n}\n\n} \/\/ anonymous namespace\n\nTEST(CssParserTest, ParserFromString_basic)\n{\n const std::string src =\n \"A { \\n\"\n \" background: red;\\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n\n EXPECT_EQ(ss.propsets[0].properties.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties[0].name, \"background\");\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"red\"));\n}\n\nTEST(CssParserTest, ParserFromString_selectors)\n{\n const std::string src =\n \"A.b { color: #123456; }\\n\"\n \".b { text: 'green'; }\\n\"\n \"A B.b { background: yellow; }\\n\"\n \"A B .b { foreground: black; }\\n\"\n \"A .b .c { foreground: black; }\\n\"\n \".b.a { text: 'a and b'; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 6);\n EXPECT_EQ(selectorName(ss, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 0, 0, 1), \".b\");\n\n EXPECT_EQ(selectorName(ss, 1, 0, 0), \".b\");\n\n EXPECT_EQ(selectorName(ss, 2, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 2, 1, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 2, 1, 1), \".b\");\n\n EXPECT_EQ(selectorName(ss, 3, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 3, 1, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 3, 2, 0), \".b\");\n\n EXPECT_EQ(ss.propsets[3].properties.size(), 1);\n EXPECT_EQ(ss.propsets[3].properties[0].name, \"foreground\");\n EXPECT_EQ(getFirstValue(ss.propsets[3].properties[0].values), std::string(\"black\"));\n\n EXPECT_EQ(selectorName(ss, 4, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 4, 1, 0), \".b\");\n EXPECT_EQ(selectorName(ss, 4, 2, 0), \".c\");\n\n EXPECT_EQ(selectorName(ss, 5, 0, 0), \".b\");\n EXPECT_EQ(selectorName(ss, 5, 0, 1), \".a\");\n}\n\nTEST(CssParserTest, ParserFromString_separatedSelectors)\n{\n const std::string src =\n \"A, B, C { foreground: black; }\\n\"\n \"A.a B.b, A.a C.c { foreground: black; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(selectorNames(ss, 0, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 0, 1, 0, 0), \"B\");\n EXPECT_EQ(selectorNames(ss, 0, 2, 0, 0), \"C\");\n\n EXPECT_EQ(selectorNames(ss, 1, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 0, 1), \".a\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 1, 0), \"B\");\n EXPECT_EQ(selectorNames(ss, 1, 0, 1, 1), \".b\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 0, 0), \"A\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 0, 1), \".a\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 1, 0), \"C\");\n EXPECT_EQ(selectorNames(ss, 1, 1, 1, 1), \".c\");\n}\n\nTEST(CssParserTest, ParserFromString_childrenSelectors)\n{\n const std::string src = \"A.b > B.c { color: #123456; }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(selectorName(ss, 0, 0, 0), \"A\");\n EXPECT_EQ(selectorName(ss, 0, 0, 1), \".b\");\n EXPECT_EQ(selectorName(ss, 0, 1, 0), \">\");\n EXPECT_EQ(selectorName(ss, 0, 2, 0), \"B\");\n EXPECT_EQ(selectorName(ss, 0, 2, 1), \".c\");\n}\n\nTEST(CssParserTest, ParserFromString_properties)\n{\n const std::string src =\n \"X {\\n\"\n \" abc: #123456; \\n\"\n \" def: 'string'; \\n\"\n \" ghi: \\\"string\\\"; \\n\"\n \" jkl: 1234; \\n\"\n \" mno: 123.45; \\n\"\n \" pqr: symbol; \\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 6);\n\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"#123456\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[1].values), std::string(\"string\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[2].values), std::string(\"string\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[3].values), std::string(\"1234\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[4].values), std::string(\"123.45\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[5].values), std::string(\"symbol\"));\n}\n\nTEST(CssParserTest, ParserFromString_stringProperties)\n{\n const std::string src =\n \"X {\\n\"\n \" def: 'str\\\"ing'; \\n\"\n \" ghi: \\\"str'ing\\\"; \\n\"\n \"}\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[0].values), std::string(\"str\\\"ing\"));\n EXPECT_EQ(getFirstValue(ss.propsets[0].properties[1].values), std::string(\"str'ing\"));\n}\n\nTEST(CssParserTest, ParserFromString_emptyString)\n{\n const std::string src = \"\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyWhitespace)\n{\n const std::string src =\n \"\\n\\n\\n\"\n \"\\t\\t \\n\\r\"\n \"\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyCppComment)\n{\n const std::string src = \"\/\/ Copyright 2014 by Yoyodyne Inc.\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_onlyComment)\n{\n const std::string src = \"\/* Copyright 2014 by Yoyodyne Inc. *\/\\n\";\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n}\n\nTEST(CssParserTest, ParserFromString_crlfNewlines)\n{\n const std::string src =\n \"X {\\r\\n\"\n \"abc: #123456; \\r\\n\"\n \"def: 'string'; \\r\\n\"\n \"}\\r\\n\"\n \"X .a {\\r\\n\"\n \"xyz: red;\\r\\n\"\n \"}\\r\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_mixedNewlines)\n{\n const std::string src =\n \"X {\\r\\n\"\n \"abc: #123456; \\n\\r\"\n \"def: 'string'; \\n\"\n \"}\"\n \"X .a {\"\n \"xyz: red;\"\n \"}\\n\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_noNewlines)\n{\n const std::string src =\n \"X {\"\n \"abc: #123456;\"\n \"def: 'string';\"\n \"}\"\n \"X .a {\"\n \"xyz: red;\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_noSemicolons)\n{\n const std::string src =\n \"X {\"\n \" abc: #123456\"\n \" def: 'string'\"\n \"}\"\n \"X .a {\"\n \" xyz: red\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 2);\n EXPECT_EQ(ss.propsets[0].properties.size(), 2);\n EXPECT_EQ(ss.propsets[1].properties.size(), 1);\n}\n\nTEST(CssParserTest, ParserFromString_multipleValues)\n{\n const std::string src =\n \"X {\"\n \" abc: a, b, c, d;\\n\"\n \"}\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 1);\n EXPECT_EQ(ss.propsets[0].properties.size(), 1);\n EXPECT_EQ(getNumberOfValues(ss.propsets[0].properties[0].values), 4);\n}\n\nTEST(CssParserTest, ParserFromString_fontFaceDeclarations)\n{\n const std::string src =\n \"\/\/ Copyright\\n\"\n \"@font-face { src: url('..\/..\/Assets\/times.ttf'); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(ss.propsets.size(), 0);\n EXPECT_EQ(ss.fontfaces.size(), 1);\n\n EXPECT_EQ(ss.fontfaces[0].url, \"..\/..\/Assets\/times.ttf\");\n}\n\n\/\/----------------------------------------------------------------------------------------\n\nTEST(CssParserTest, ParserFromString_Expressions)\n{\n const std::string src = \"foo { bar: url('hello world'); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(1, ss.propsets.size());\n EXPECT_EQ(1, ss.propsets[0].properties.size());\n EXPECT_EQ(1, getNumberOfValues(ss.propsets[0].properties[0].values));\n\n EXPECT_EQ(std::string(\"url\"), getExpr(ss.propsets[0].properties[0].values, 0).name);\n EXPECT_EQ((std::vector<std::string>{\"hello world\"}),\n getExpr(ss.propsets[0].properties[0].values, 0).args);\n}\n\nTEST(CssParserTest, ParserFromString_ExpressionsInLists)\n{\n const std::string src =\n \"foo { bar: rgba(123, 45, 92, 0.1), \"\n \" foo(), \"\n \" hsla(320, 100%, 20%, 0.3); }\\n\";\n\n StyleSheet ss = parseStdString(src);\n EXPECT_EQ(1, ss.propsets.size());\n EXPECT_EQ(1, ss.propsets[0].properties.size());\n\n EXPECT_EQ(std::string(\"rgba\"), getExpr(ss.propsets[0].properties[0].values, 0).name);\n EXPECT_EQ((std::vector<std::string>{\"123\", \"45\", \"92\", \"0.1\"}),\n getExpr(ss.propsets[0].properties[0].values, 0).args);\n EXPECT_EQ(std::string(\"foo\"), getExpr(ss.propsets[0].properties[0].values, 1).name);\n EXPECT_TRUE(getExpr(ss.propsets[0].properties[0].values, 1).args.empty());\n\n EXPECT_EQ(std::string(\"hsla\"), getExpr(ss.propsets[0].properties[0].values, 2).name);\n EXPECT_EQ((std::vector<std::string>{\"320\", \"100%\", \"20%\", \"0.3\"}),\n getExpr(ss.propsets[0].properties[0].values, 2).args);\n}\n\n\/* Missing tests:\n\n pathological cases:\n - non closed }\n - non closed \"\n - non closed '\n - ambiguous selectors\n - no selectors\n - invalid chars in selector\n - invalid chars in propertyname\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"Mocks.hpp\"\n\n#include <boost\/asio.hpp>\n#include <boost\/lexical_cast.hpp>\n\nnamespace asio = boost::asio;\n\nnamespace blackhole {\n\nnamespace sink {\n\nclass boost_asio_backend_t {\n const std::string host;\n const std::uint16_t port;\n\n asio::io_service io_service;\n asio::ip::udp::endpoint endpoint;\n std::unique_ptr<asio::ip::udp::socket> socket;\n\npublic:\n boost_asio_backend_t(const std::string& host, std::uint16_t port) :\n host(host),\n port(port)\n {\n asio::ip::udp::resolver resolver(io_service);\n asio::ip::udp::resolver::query query(host, boost::lexical_cast<std::string>(port));\n asio::ip::udp::resolver::iterator it = resolver.resolve(query); \/\/!@todo: May throw! Whatever.\n std::vector<asio::ip::udp::endpoint> endpoints(it, asio::ip::udp::resolver::iterator());\n\n for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {\n try {\n socket = std::make_unique<asio::ip::udp::socket>(io_service);\n socket->open(it->protocol());\n endpoint = *it;\n break;\n } catch (const boost::system::system_error& err) {\n std::cout << err.what() << std::endl;\n continue;\n }\n }\n\n if (!socket) {\n throw error_t(\"couldn't open UDP socket at %s:%d\", host, port);\n }\n }\n\n ssize_t write(const std::string& message) {\n return socket->send_to(boost::asio::buffer(message.data(), message.size()), endpoint);\n }\n};\n\ntemplate<typename Backend = boost_asio_backend_t>\nclass socket_t {\n Backend m_backend;\n\npublic:\n socket_t(const std::string& host, std::uint16_t port) :\n m_backend(host, port)\n {\n }\n\n void consume(const std::string& message) {\n m_backend.write(message);\n }\n\n Backend& backend() {\n return m_backend;\n }\n};\n\nclass tcp_socket_t {\n const std::string host;\n const std::uint16_t port;\n\n asio::io_service io_service;\n std::unique_ptr<asio::ip::tcp::socket> socket;\n\npublic:\n tcp_socket_t(const std::string& host, std::uint16_t port) :\n host(host),\n port(port),\n socket(initialize(io_service, host, port))\n {\n }\n\n void consume(const std::string& message) {\n if (!socket) {\n socket = initialize(io_service, host, port);\n }\n\n try {\n socket->write_some(boost::asio::buffer(message.data(), message.size()));\n } catch (const boost::system::system_error& err) {\n socket.release();\n std::rethrow_exception(std::current_exception());\n }\n }\n\nprivate:\n static inline\n std::unique_ptr<asio::ip::tcp::socket>\n initialize(asio::io_service& io_service, const std::string& host, std::uint16_t port) {\n auto socket = std::make_unique<asio::ip::tcp::socket>(io_service);\n connect(io_service, *socket, host, port);\n return socket;\n }\n\n static inline\n void\n connect(asio::io_service& io_service, asio::ip::tcp::socket& socket, const std::string& host, std::uint16_t port) {\n try {\n asio::ip::tcp::resolver resolver(io_service);\n asio::ip::tcp::resolver::query query(host, boost::lexical_cast<std::string>(port));\n asio::ip::tcp::resolver::iterator it = resolver.resolve(query);\n\n try {\n asio::connect(socket, it);\n } catch (const boost::system::system_error& err) {\n throw error_t(\"couldn't connect to the %s:%d - %s\", host, port, err.what());\n }\n } catch (const boost::system::system_error& err) {\n throw error_t(\"couldn't resolve %s:%d - %s\", host, port, err.what());\n }\n }\n};\n\n} \/\/ namespace sink\n\n} \/\/ namespace blackhole\n\nTEST(socket_t, Class) {\n sink::socket_t<> sink(\"localhost\", 50030);\n UNUSED(sink);\n}\n\nTEST(socket_t, TestCanSendMessages) {\n sink::socket_t<NiceMock<mock::socket::backend_t>> sink(\"localhost\", 50030);\n EXPECT_CALL(sink.backend(), write(std::string(\"formatted message\"))).\n Times(1);\n sink.consume(\"formatted message\");\n}\n\nTEST(socket_t, ThrowsExceptionOnAnyWriteErrorOccurred) {\n \/\/ This behaviour is normal for blocking udp\/tcp socket sink.\n \/\/ When some network error occurs, message is on the half way to be dropped.\n \/\/ In case of UDP socket, handler will try to reopen socket immediately and rewrite again here\n \/\/ and every next message.\n \/\/ In case of TCP socket, handler will try to reconnect on every next message before sending.\n sink::socket_t<NiceMock<mock::socket::backend_t>> sink(\"localhost\", 50030);\n EXPECT_CALL(sink.backend(), write(_))\n .Times(1)\n .WillOnce(Throw(std::exception()));\n EXPECT_THROW(sink.consume(\"message\"), std::exception);\n}\n\nTEST(socket_t, ThrowsExceptionWhenCannotAcquireResource) {\n \/\/ This is initialization behaviour and cannot be caught by any log backend. If handler cannot\n \/\/ acquire resource needed, it can't continue its work, so it's neccessary to notify upper level\n \/\/ code about it.\n EXPECT_THROW(sink::socket_t<NiceMock<mock::socket::failing_backend_t>>(\"localhost\", 50030), std::exception); \/\/!@todo: Maybe some kind of typecheck here?\n}\n\nTEST(socket_t, Manual) {\n sink::tcp_socket_t sink(\"localhost\", 50030);\n int i = 0;\n while (true) {\n try {\n sink.consume(utils::format(\"{\\\"@message\\\": \\\"value = %d\\\"}\\n\", i));\n } catch (std::exception& e) {\n std::cout << utils::format(\"I've fucked up: %s\", e.what()) << std::endl;\n }\n\n i++;\n usleep(1000000);\n }\n}\n<commit_msg>Explicit is better than implicit.<commit_after>#include \"Mocks.hpp\"\n\n#include <boost\/asio.hpp>\n#include <boost\/lexical_cast.hpp>\n\nnamespace asio = boost::asio;\n\nnamespace blackhole {\n\nnamespace sink {\n\nclass boost_asio_backend_t {\n const std::string host;\n const std::uint16_t port;\n\n asio::io_service io_service;\n asio::ip::udp::endpoint endpoint;\n std::unique_ptr<asio::ip::udp::socket> socket;\n\npublic:\n boost_asio_backend_t(const std::string& host, std::uint16_t port) :\n host(host),\n port(port)\n {\n asio::ip::udp::resolver resolver(io_service);\n asio::ip::udp::resolver::query query(host, boost::lexical_cast<std::string>(port));\n asio::ip::udp::resolver::iterator it = resolver.resolve(query); \/\/!@todo: May throw! Whatever.\n std::vector<asio::ip::udp::endpoint> endpoints(it, asio::ip::udp::resolver::iterator());\n\n for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {\n try {\n socket = std::make_unique<asio::ip::udp::socket>(io_service);\n socket->open(it->protocol());\n endpoint = *it;\n break;\n } catch (const boost::system::system_error& err) {\n std::cout << err.what() << std::endl;\n continue;\n }\n }\n\n if (!socket) {\n throw error_t(\"couldn't open UDP socket at %s:%d\", host, port);\n }\n }\n\n ssize_t write(const std::string& message) {\n return socket->send_to(boost::asio::buffer(message.data(), message.size()), endpoint);\n }\n};\n\ntemplate<typename Backend = boost_asio_backend_t>\nclass socket_t {\n Backend m_backend;\n\npublic:\n socket_t(const std::string& host, std::uint16_t port) :\n m_backend(host, port)\n {\n }\n\n void consume(const std::string& message) {\n m_backend.write(message);\n }\n\n Backend& backend() {\n return m_backend;\n }\n};\n\nclass tcp_socket_t {\n const std::string host;\n const std::uint16_t port;\n\n asio::io_service io_service;\n std::unique_ptr<asio::ip::tcp::socket> socket;\n\npublic:\n tcp_socket_t(const std::string& host, std::uint16_t port) :\n host(host),\n port(port),\n socket(initialize(io_service, host, port))\n {\n }\n\n void consume(const std::string& message) {\n if (!socket) {\n socket = initialize(io_service, host, port);\n }\n\n try {\n socket->write_some(boost::asio::buffer(message.data(), message.size()));\n } catch (const boost::system::system_error& err) {\n socket.release();\n std::rethrow_exception(std::current_exception());\n }\n }\n\nprivate:\n static inline\n std::unique_ptr<asio::ip::tcp::socket>\n initialize(asio::io_service& io_service, const std::string& host, std::uint16_t port) {\n std::unique_ptr<asio::ip::tcp::socket> socket = std::make_unique<asio::ip::tcp::socket>(io_service);\n connect(io_service, *socket, host, port);\n return socket;\n }\n\n static inline\n void\n connect(asio::io_service& io_service, asio::ip::tcp::socket& socket, const std::string& host, std::uint16_t port) {\n try {\n asio::ip::tcp::resolver resolver(io_service);\n asio::ip::tcp::resolver::query query(host, boost::lexical_cast<std::string>(port));\n asio::ip::tcp::resolver::iterator it = resolver.resolve(query);\n\n try {\n asio::connect(socket, it);\n } catch (const boost::system::system_error& err) {\n throw error_t(\"couldn't connect to the %s:%d - %s\", host, port, err.what());\n }\n } catch (const boost::system::system_error& err) {\n throw error_t(\"couldn't resolve %s:%d - %s\", host, port, err.what());\n }\n }\n};\n\n} \/\/ namespace sink\n\n} \/\/ namespace blackhole\n\nTEST(socket_t, Class) {\n sink::socket_t<> sink(\"localhost\", 50030);\n UNUSED(sink);\n}\n\nTEST(socket_t, TestCanSendMessages) {\n sink::socket_t<NiceMock<mock::socket::backend_t>> sink(\"localhost\", 50030);\n EXPECT_CALL(sink.backend(), write(std::string(\"formatted message\"))).\n Times(1);\n sink.consume(\"formatted message\");\n}\n\nTEST(socket_t, ThrowsExceptionOnAnyWriteErrorOccurred) {\n \/\/ This behaviour is normal for blocking udp\/tcp socket sink.\n \/\/ When some network error occurs, message is on the half way to be dropped.\n \/\/ In case of UDP socket, handler will try to reopen socket immediately and rewrite again here\n \/\/ and every next message.\n \/\/ In case of TCP socket, handler will try to reconnect on every next message before sending.\n sink::socket_t<NiceMock<mock::socket::backend_t>> sink(\"localhost\", 50030);\n EXPECT_CALL(sink.backend(), write(_))\n .Times(1)\n .WillOnce(Throw(std::exception()));\n EXPECT_THROW(sink.consume(\"message\"), std::exception);\n}\n\nTEST(socket_t, ThrowsExceptionWhenCannotAcquireResource) {\n \/\/ This is initialization behaviour and cannot be caught by any log backend. If handler cannot\n \/\/ acquire resource needed, it can't continue its work, so it's neccessary to notify upper level\n \/\/ code about it.\n EXPECT_THROW(sink::socket_t<NiceMock<mock::socket::failing_backend_t>>(\"localhost\", 50030), std::exception); \/\/!@todo: Maybe some kind of typecheck here?\n}\n\nTEST(socket_t, Manual) {\n sink::tcp_socket_t sink(\"localhost\", 50030);\n int i = 0;\n while (true) {\n try {\n sink.consume(utils::format(\"{\\\"@message\\\": \\\"value = %d\\\"}\\n\", i));\n } catch (std::exception& e) {\n std::cout << utils::format(\"I've fucked up: %s\", e.what()) << std::endl;\n }\n\n i++;\n usleep(1000000);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -analyze -analyzer-check-objc-mem -analyzer-inline-call -analyzer-store region -verify %s\n\nstruct A {\n int x;\n A(int a) { x = a; }\n int getx() const { return x; }\n};\n\nvoid f1() {\n A x(3);\n if (x.getx() == 3) {\n int *p = 0;\n *p = 3; \/\/ expected-warning{{Dereference of null pointer}}\n } else {\n int *p = 0;\n *p = 3; \/\/ no-warning\n }\n}\n\nvoid f2() {\n const A &x = A(3);\n if (x.getx() == 3) {\n int *p = 0;\n *p = 3; \/\/ expected-warning{{Dereference of null pointer}}\n } else {\n int *p = 0;\n *p = 3; \/\/ no-warning\n }\n}\n\n<commit_msg>[analyzer] Disable a test until inlining CXXConstructExprs is fully investigated.<commit_after>\/\/ RUN: %clang_cc1 -analyze -analyzer-check-objc-mem -analyzer-inline-call -analyzer-store region -verify %s\n\/\/ XFAIL: *\n\nstruct A {\n int x;\n A(int a) { x = a; }\n int getx() const { return x; }\n};\n\nvoid f1() {\n A x(3);\n if (x.getx() == 3) {\n int *p = 0;\n *p = 3; \/\/ expected-warning{{Dereference of null pointer}}\n } else {\n int *p = 0;\n *p = 3; \/\/ no-warning\n }\n}\n\nvoid f2() {\n const A &x = A(3);\n if (x.getx() == 3) {\n int *p = 0;\n *p = 3; \/\/ expected-warning{{Dereference of null pointer}}\n } else {\n int *p = 0;\n *p = 3; \/\/ no-warning\n }\n}\n\nvoid f3() {\n const A &x = (A)3;\n if (x.getx() == 3) {\n int *p = 0;\n *p = 3; \/\/ expected-warning{{Dereference of null pointer}}\n } else {\n int *p = 0;\n *p = 3; \/\/ no-warning\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"find_hub.hpp\"\n\nvoid GraphProcessor::find_hub()\n{\n struct Result res = {};\n\n complete_graph g(cities_cnt);\n multi_array<int, 2> weights(extents[cities_cnt][cities_cnt]);\n Vertex roots[cities_cnt];\n vector<Edge> branching;\n\n int n = {0};\n std::generate(roots, roots + cities_cnt, [&n] { return n++; } );\n\n int *end = weights.origin() + cities_cnt * cities_cnt;\n for (int *it = weights.origin(); it != end; ++it)\n *it = INT_MAX;\n\n for (auto it = lines.begin(); it != lines.end(); ++it) {\n weights[it->from][it->to] = it->price;\n }\n\n unsigned long min_cost = ULONG_MAX;\n unsigned int best_depot = INT_MAX;\n vector<Edge> best_branching;\n\n for (int r = 0; r < cities_cnt; r++) {\n branching.clear();\n\n edmonds_optimum_branching<false, true, true>\n (g, identity_property_map(), weights.origin(),\n roots + r, roots + r + 1, back_inserter(branching));\n\n unsigned long total_cost = 0;\n for (auto& e : branching)\n total_cost += weights[source(e, g)][target(e, g)];\n\n #ifdef DEBUG\n std::cout << \"root: \" << r << std::endl;\n BOOST_FOREACH (Edge e, branching)\n std::cout << source(e, g) << \" -> \" << target(e, g) << \" : \" << weights[source(e, g)][target(e, g)] << std::endl;\n std::cout << total_cost << std::endl;\n #endif\n\n if (total_cost < min_cost) {\n min_cost = total_cost;\n best_depot = r;\n best_branching = branching;\n }\n }\n\n res.feasibility = best_branching.empty() ? false : true;\n res.total_cost = min_cost;\n res.depot_id = best_depot;\n\n BOOST_FOREACH (Edge e, best_branching)\n res.rec_offers.push_back(Line(source(e, g), target(e, g), weights[source(e, g)][target(e, g)]));\n\n last_res = res;\n}\n\nbool GraphProcessor::load_input()\n{\n if (!(std::cin >> cities_cnt))\n return false;\n\n unsigned int from, to, price;\n\n while (cin >> from >> to >> price)\n lines.push_back(Line(from, to, price));\n\n return true;\n}\n\nvoid GraphProcessor::send_result()\n{\n std::cout << last_res.feasibility << \" \" << last_res.total_cost << \" \" << last_res.depot_id << std::endl;\n\n for (auto it = last_res.rec_offers.begin(); it != last_res.rec_offers.end(); ++it) {\n std::cout << it->from << \" \" << it->to << \" \" << it->price << std::endl;\n }\n}\n\nint main(int argc, char *argv[])\n{\n GraphProcessor gp;\n\n if (!gp.load_input())\n return 1;\n gp.find_hub();\n gp.send_result();\n\n return 0;\n}\n<commit_msg>find_hub: extend possible weight to ULONG_MAX<commit_after>#include \"find_hub.hpp\"\n\nvoid GraphProcessor::find_hub()\n{\n struct Result res = {};\n\n complete_graph g(cities_cnt);\n multi_array<unsigned long, 2> weights(extents[cities_cnt][cities_cnt]);\n Vertex roots[cities_cnt];\n vector<Edge> branching;\n\n int n = {0};\n std::generate(roots, roots + cities_cnt, [&n] { return n++; } );\n\n unsigned long *end = weights.origin() + cities_cnt * cities_cnt;\n for (unsigned long *it = weights.origin(); it != end; ++it)\n *it = ULONG_MAX;\n\n for (auto it = lines.begin(); it != lines.end(); ++it) {\n weights[it->from][it->to] = it->price;\n }\n\n unsigned long min_cost = ULONG_MAX;\n unsigned int best_depot = INT_MAX;\n vector<Edge> best_branching;\n\n for (int r = 0; r < cities_cnt; r++) {\n branching.clear();\n\n edmonds_optimum_branching<false, true, true>\n (g, identity_property_map(), weights.origin(),\n roots + r, roots + r + 1, back_inserter(branching));\n\n unsigned long total_cost = 0;\n for (auto& e : branching)\n total_cost += weights[source(e, g)][target(e, g)];\n\n #ifdef DEBUG\n std::cout << \"root: \" << r << std::endl;\n BOOST_FOREACH (Edge e, branching)\n std::cout << source(e, g) << \" -> \" << target(e, g) << \" : \" << weights[source(e, g)][target(e, g)] << std::endl;\n std::cout << total_cost << std::endl;\n #endif\n\n if (total_cost < min_cost) {\n min_cost = total_cost;\n best_depot = r;\n best_branching = branching;\n }\n }\n\n res.feasibility = best_branching.empty() ? false : true;\n res.total_cost = min_cost;\n res.depot_id = best_depot;\n\n BOOST_FOREACH (Edge e, best_branching)\n res.rec_offers.push_back(Line(source(e, g), target(e, g), weights[source(e, g)][target(e, g)]));\n\n last_res = res;\n}\n\nbool GraphProcessor::load_input()\n{\n if (!(std::cin >> cities_cnt))\n return false;\n\n unsigned int from, to, price;\n\n while (cin >> from >> to >> price)\n lines.push_back(Line(from, to, price));\n\n return true;\n}\n\nvoid GraphProcessor::send_result()\n{\n std::cout << last_res.feasibility << \" \" << last_res.total_cost << \" \" << last_res.depot_id << std::endl;\n\n for (auto it = last_res.rec_offers.begin(); it != last_res.rec_offers.end(); ++it) {\n std::cout << it->from << \" \" << it->to << \" \" << it->price << std::endl;\n }\n}\n\nint main(int argc, char *argv[])\n{\n GraphProcessor gp;\n\n if (!gp.load_input())\n return 1;\n gp.find_hub();\n gp.send_result();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tightdb\/exceptions.hpp>\n#include <tightdb\/version.hpp>\n\nusing namespace tightdb;\n\nconst char* ExceptionWithVersionInWhat::message() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n static const char ver[] = TIGHTDB_VER_CHUNK;\n return what() + sizeof(ver);\n}\n\nconst char* Exception::version() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_STRING;\n}\n\nRuntimeError::RuntimeError(const std::string& message):\n std::runtime_error(std::string(TIGHTDB_VER_CHUNK) + \" \" + message)\n{\n}\n\nRuntimeError::RuntimeError(const RuntimeError& other):\n std::runtime_error(other)\n{\n}\n\nconst char* RuntimeError::message() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n static const char ver[] = TIGHTDB_VER_CHUNK;\n return what() + sizeof(ver);\n}\n\nconst char* RuntimeError::version() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_STRING;\n}\n\n\nconst char* LogicError::get_message_for_error(LogicError::error_kind kind) TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n switch (kind) {\n case LogicError::string_too_big:\n return TIGHTDB_VER_CHUNK \" String too big\";\n case LogicError::binary_too_big:\n return TIGHTDB_VER_CHUNK \" Binary too big\";\n case LogicError::table_name_too_long:\n return TIGHTDB_VER_CHUNK \" Table name too long\";\n case LogicError::column_name_too_long:\n return TIGHTDB_VER_CHUNK \" Column name too long\";\n case LogicError::table_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Table index out of range\";\n case LogicError::row_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Row index out of range\";\n case LogicError::column_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Column index out of range\";\n case LogicError::illegal_combination:\n return TIGHTDB_VER_CHUNK \" Illegal combination\";\n case LogicError::type_mismatch:\n return TIGHTDB_VER_CHUNK \" Type mismatch\";\n case LogicError::wrong_kind_of_table:\n return TIGHTDB_VER_CHUNK \" Wrong kind of table\";\n case LogicError::detached_accessor:\n return TIGHTDB_VER_CHUNK \" Detached accessor\";\n case LogicError::no_search_index:\n return TIGHTDB_VER_CHUNK \" Column has no search index\";\n case LogicError::no_primary_key:\n return TIGHTDB_VER_CHUNK \" Table has no primary key\";\n case LogicError::has_primary_key:\n return TIGHTDB_VER_CHUNK \" Primary key already added\";\n case LogicError::unique_constraint_violation:\n return TIGHTDB_VER_CHUNK \" Unique constraint violation\";\n }\n return TIGHTDB_VER_CHUNK \" Unknown error\";\n}\n\nconst char* NoSuchTable::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" No such table exists\";\n}\n\nconst char* TableNameInUse::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" The specified table name is already in use\";\n}\n\nconst char* CrossTableLinkTarget::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" Table is target of cross-table link columns\";\n}\n\nconst char* DescriptorMismatch::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" Table descriptor mismatch\";\n}\n<commit_msg>Guard against segfaults in RuntimeError::message() and Exception::message().<commit_after>#include <tightdb\/exceptions.hpp>\n#include <tightdb\/version.hpp>\n\nusing namespace tightdb;\n\nconst char* ExceptionWithVersionInWhat::message() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n const char* msg = what();\n size_t len = strlen(msg);\n static const char ver[] = TIGHTDB_VER_CHUNK;\n if (len > sizeof(ver)) {\n \/\/ Assume that what() actually included the version string.\n return msg + sizeof(ver);\n }\n return msg;\n}\n\nconst char* Exception::version() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_STRING;\n}\n\nRuntimeError::RuntimeError(const std::string& message):\n std::runtime_error(std::string(TIGHTDB_VER_CHUNK) + \" \" + message)\n{\n}\n\nRuntimeError::RuntimeError(const RuntimeError& other):\n std::runtime_error(other)\n{\n}\n\nconst char* RuntimeError::message() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n const char* msg = what();\n size_t len = strlen(msg);\n static const char ver[] = TIGHTDB_VER_CHUNK;\n if (len > sizeof(ver)) {\n \/\/ Assume that what() actually included the version string.\n return msg + sizeof(ver);\n }\n return msg;\n}\n\nconst char* RuntimeError::version() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_STRING;\n}\n\n\nconst char* LogicError::get_message_for_error(LogicError::error_kind kind) TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n switch (kind) {\n case LogicError::string_too_big:\n return TIGHTDB_VER_CHUNK \" String too big\";\n case LogicError::binary_too_big:\n return TIGHTDB_VER_CHUNK \" Binary too big\";\n case LogicError::table_name_too_long:\n return TIGHTDB_VER_CHUNK \" Table name too long\";\n case LogicError::column_name_too_long:\n return TIGHTDB_VER_CHUNK \" Column name too long\";\n case LogicError::table_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Table index out of range\";\n case LogicError::row_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Row index out of range\";\n case LogicError::column_index_out_of_range:\n return TIGHTDB_VER_CHUNK \" Column index out of range\";\n case LogicError::illegal_combination:\n return TIGHTDB_VER_CHUNK \" Illegal combination\";\n case LogicError::type_mismatch:\n return TIGHTDB_VER_CHUNK \" Type mismatch\";\n case LogicError::wrong_kind_of_table:\n return TIGHTDB_VER_CHUNK \" Wrong kind of table\";\n case LogicError::detached_accessor:\n return TIGHTDB_VER_CHUNK \" Detached accessor\";\n case LogicError::no_search_index:\n return TIGHTDB_VER_CHUNK \" Column has no search index\";\n case LogicError::no_primary_key:\n return TIGHTDB_VER_CHUNK \" Table has no primary key\";\n case LogicError::has_primary_key:\n return TIGHTDB_VER_CHUNK \" Primary key already added\";\n case LogicError::unique_constraint_violation:\n return TIGHTDB_VER_CHUNK \" Unique constraint violation\";\n }\n return TIGHTDB_VER_CHUNK \" Unknown error\";\n}\n\nconst char* NoSuchTable::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" No such table exists\";\n}\n\nconst char* TableNameInUse::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" The specified table name is already in use\";\n}\n\nconst char* CrossTableLinkTarget::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" Table is target of cross-table link columns\";\n}\n\nconst char* DescriptorMismatch::what() const TIGHTDB_NOEXCEPT_OR_NOTHROW\n{\n return TIGHTDB_VER_CHUNK \" Table descriptor mismatch\";\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_MATH_STEP_FUNCTION_HH__\n#define ALEPH_MATH_STEP_FUNCTION_HH__\n\n#include <algorithm>\n#include <iterator>\n#include <ostream>\n#include <set>\n\nnamespace aleph\n{\n\nnamespace math\n{\n\ntemplate <class T> class StepFunction\n{\npublic:\n\n \/**\n Auxiliary class for representing a point 'on' the step function;\n this assumes that the function consists of its non-zero points.\n *\/\n\n class Point\n {\n public:\n Point( T x, T y )\n : _x( x )\n , _y( y )\n {\n }\n\n T x() const noexcept { return _x; }\n T y() const noexcept { return _y; }\n\n bool operator<( const Point& other ) const\n {\n \/\/ Only compare by x coordinate; there must not be two or more\n \/\/ points with the same coordinate.\n return this->x() < other.x();\n }\n\n private:\n T _x = T();\n T _y = T();\n };\n\n \/** Adds a new point to the step function *\/\n void add( T x, T y ) noexcept\n {\n _points.insert( Point(x,y) );\n }\n\n \/** Returns the domain of the function *\/\n template <class OutputIterator> void domain( OutputIterator result )\n {\n for( auto&& p : _points )\n *result++ = p.x();\n }\n\n \/** Returns the image of the function *\/\n template <class OutputIterator> void image( OutputIterator result )\n {\n for( auto&& p : _points )\n *result++ = p.y();\n }\n\n \/** Returns the function value at a certain position *\/\n T operator()( T x ) const noexcept\n {\n \/\/ Find the point that is nearest to the query point and use its value as\n \/\/ the result. I don't want to do any interpolation here.\n auto it = std::lower_bound( _points.begin(), _points.end(),\n Point( x, T() ) );\n\n if( it != _points.end() )\n return it->y();\n else\n return T();\n }\n\n \/** Calculates the sum of this step function with another step function *\/\n StepFunction operator+( const StepFunction& other ) const noexcept\n {\n auto&& f = *this;\n auto&& g = other;\n\n std::set<T> domain;\n\n f.domain( std::inserter( domain, domain.begin() ) );\n g.domain( std::inserter( domain, domain.begin() ) );\n\n StepFunction<T> h;\n\n for( auto&& x : domain )\n {\n auto y1 = f(x);\n auto y2 = g(x);\n\n h.add( x, y1+y2 );\n }\n\n return h;\n }\n\n \/** Calculates the integral over the domain of the step function *\/\n T integral() const noexcept\n {\n if( _points.empty() )\n return T();\n\n auto cur = _points.begin();\n auto pre = _points.begin();\n\n std::advance( cur, 1 );\n\n T value = T();\n\n for( ; cur != _points.end(); )\n {\n auto c = this->operator()( pre->x() );\n auto t = cur->x() - pre->x();\n value += c*t;\n\n pre = cur++;\n }\n\n return value;\n }\n\n template <class U> friend std::ostream& operator<<( std::ostream&, const StepFunction<U>& f );\n\nprivate:\n\n \/** All non-zero points of the step function *\/\n std::set<Point> _points;\n};\n\n\/\/ TODO: This does not need to be a friend function; it suffices to be\n\/\/ implemented using the public interface of the class.\ntemplate <class T> std::ostream& operator<<( std::ostream& o, const StepFunction<T>& f )\n{\n for( auto&& p : f._points )\n o << p.x() << \"\\t\" << p.y() << \"\\n\";\n\n return o;\n}\n\n} \/\/ namespace math\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Scalar multiplication and division for step functions<commit_after>#ifndef ALEPH_MATH_STEP_FUNCTION_HH__\n#define ALEPH_MATH_STEP_FUNCTION_HH__\n\n#include <algorithm>\n#include <iterator>\n#include <ostream>\n#include <set>\n\nnamespace aleph\n{\n\nnamespace math\n{\n\ntemplate <class T> class StepFunction\n{\npublic:\n\n \/**\n Auxiliary class for representing a point 'on' the step function;\n this assumes that the function consists of its non-zero points.\n *\/\n\n class Point\n {\n public:\n Point( T x, T y )\n : _x( x )\n , _y( y )\n {\n }\n\n T& x() noexcept { return _x; }\n const T& x() const noexcept { return _x; }\n\n T& y() noexcept { return _y; }\n const T& y() const noexcept { return _y; }\n\n bool operator<( const Point& other ) const\n {\n \/\/ Only compare by x coordinate; there must not be two or more\n \/\/ points with the same coordinate.\n return this->x() < other.x();\n }\n\n private:\n T _x = T();\n T _y = T();\n };\n\n \/** Adds a new point to the step function *\/\n void add( T x, T y ) noexcept\n {\n _points.insert( Point(x,y) );\n }\n\n \/** Returns the domain of the function *\/\n template <class OutputIterator> void domain( OutputIterator result )\n {\n for( auto&& p : _points )\n *result++ = p.x();\n }\n\n \/** Returns the image of the function *\/\n template <class OutputIterator> void image( OutputIterator result )\n {\n for( auto&& p : _points )\n *result++ = p.y();\n }\n\n \/** Returns the function value at a certain position *\/\n T operator()( T x ) const noexcept\n {\n \/\/ Find the point that is nearest to the query point and use its value as\n \/\/ the result. I don't want to do any interpolation here.\n auto it = std::lower_bound( _points.begin(), _points.end(),\n Point( x, T() ) );\n\n if( it != _points.end() )\n return it->y();\n else\n return T();\n }\n\n \/** Calculates the sum of this step function with another step function *\/\n StepFunction operator+( const StepFunction& other ) const noexcept\n {\n auto&& f = *this;\n auto&& g = other;\n\n std::set<T> domain;\n\n f.domain( std::inserter( domain, domain.begin() ) );\n g.domain( std::inserter( domain, domain.begin() ) );\n\n StepFunction<T> h;\n\n for( auto&& x : domain )\n {\n auto y1 = f(x);\n auto y2 = g(x);\n\n h.add( x, y1+y2 );\n }\n\n return h;\n }\n\n \/** Multiplies the given step function with a scalar value *\/\n StepFunction operator*( T lambda ) const noexcept\n {\n StepFunction<T> f = *this;\n\n for( auto&& p : f._points )\n p.y() = p.y() * lambda;\n }\n\n \/** Divides the given step function by a scalar value *\/\n StepFunction operator\/( T lambda ) const\n {\n \/\/ TODO: What about division by zero?\n return this->operator*( 1\/lambda );\n }\n\n \/** Calculates the integral over the domain of the step function *\/\n T integral() const noexcept\n {\n if( _points.empty() )\n return T();\n\n auto cur = _points.begin();\n auto pre = _points.begin();\n\n std::advance( cur, 1 );\n\n T value = T();\n\n for( ; cur != _points.end(); )\n {\n auto c = this->operator()( pre->x() );\n auto t = cur->x() - pre->x();\n value += c*t;\n\n pre = cur++;\n }\n\n return value;\n }\n\n template <class U> friend std::ostream& operator<<( std::ostream&, const StepFunction<U>& f );\n\nprivate:\n\n \/** All non-zero points of the step function *\/\n std::set<Point> _points;\n};\n\n\/\/ TODO: This does not need to be a friend function; it suffices to be\n\/\/ implemented using the public interface of the class.\ntemplate <class T> std::ostream& operator<<( std::ostream& o, const StepFunction<T>& f )\n{\n for( auto&& p : f._points )\n o << p.x() << \"\\t\" << p.y() << \"\\n\";\n\n return o;\n}\n\n} \/\/ namespace math\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * redsea - RDS decoder\n * Copyright (c) Oona Räisänen OH2EIQ (windyoona@gmail.com)\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n#include <getopt.h>\n#include <iostream>\n\n#include \"config.h\"\n#include \"src\/channel.h\"\n#include \"src\/common.h\"\n#include \"src\/block_sync.h\"\n#include \"src\/groups.h\"\n#include \"src\/options.h\"\n#include \"src\/subcarrier.h\"\n\nnamespace redsea {\n\nvoid PrintUsage() {\n std::cout <<\n \"radio_command | redsea [OPTIONS]\\n\"\n \"\\n\"\n \"By default, a 171 kHz single-channel 16-bit MPX signal is expected via\\n\"\n \"stdin.\\n\"\n \"\\n\"\n \"-b, --input-bits Input is an unsynchronized ASCII bit stream\\n\"\n \" (011010110...). All characters but '0' and '1'\\n\"\n \" are ignored.\\n\"\n \"\\n\"\n \"-c, --channels CHANS Number of channels in the raw input signal. Each\\n\"\n \" channel is demodulated independently.\\n\"\n \"\\n\"\n \"-e, --feed-through Echo the input signal to stdout and print\\n\"\n \" decoded groups to stderr.\\n\"\n \"\\n\"\n \"-E, --bler Display the average block error rate, or the\\n\"\n \" percentage of blocks that had errors before\\n\"\n \" error correction. Averaged over the last 12\\n\"\n \" groups. For hex input, this is the percentage\\n\"\n \" of missing blocks.\\n\"\n \"\\n\"\n \"-f, --file FILENAME Use an audio file as MPX input. All formats\\n\"\n \" readable by libsndfile should work.\\n\"\n \"\\n\"\n \"-h, --input-hex The input is in the RDS Spy hex format.\\n\"\n \"\\n\"\n \"-l, --loctable DIR Load TMC location table from a directory in TMC\\n\"\n \" Exchange format.\\n\"\n \"\\n\"\n \"-p, --show-partial Under noisy conditions, redsea may not be able to\\n\"\n \" fully receive all information. Multi-group data\\n\"\n \" such as PS names, RadioText, and alternative\\n\"\n \" frequencies are especially vulnerable. This option\\n\"\n \" makes it display them even if not fully received,\\n\"\n \" as partial_{ps,radiotext,alt_kilohertz}.\\n\"\n \"\\n\"\n \"-r, --samplerate RATE Set stdin sample frequency in Hz. Will resample\\n\"\n \" (slow) if this differs from 171000 Hz.\\n\"\n \"\\n\"\n \"-t, --timestamp FORMAT Add time of decoding to JSON groups; see\\n\"\n \" man strftime for formatting options (or\\n\"\n \" try \\\"%c\\\").\\n\"\n \"\\n\"\n \"-u, --rbds RBDS mode; use North American program type names\\n\"\n \" and \\\"back-calculate\\\" the station's call sign from\\n\"\n \" its PI code. Note that this calculation gives an\\n\"\n \" incorrect call sign for most stations that transmit\\n\"\n \" TMC.\\n\"\n \"\\n\"\n \"-v, --version Print version string and exit.\\n\"\n \"\\n\"\n \"-x, --output-hex Output hex groups in the RDS Spy format,\\n\"\n \" suppressing JSON output.\\n\";\n}\n\nvoid PrintVersion() {\n#ifdef DEBUG\n std::cout << PACKAGE_STRING << \"-debug by OH2EIQ\" << '\\n';\n#else\n std::cout << PACKAGE_STRING << \" by OH2EIQ\" << '\\n';\n#endif\n}\n\n} \/\/ namespace redsea\n\nint main(int argc, char** argv) {\n redsea::Options options = redsea::GetOptions(argc, argv);\n\n if (options.print_usage)\n redsea::PrintUsage();\n\n if (options.print_version)\n redsea::PrintVersion();\n\n if (options.exit_failure)\n return EXIT_FAILURE;\n\n if (options.exit_success)\n return EXIT_SUCCESS;\n\n#ifndef HAVE_LIQUID\n if (options.input_type == redsea::InputType::MPX_stdin ||\n options.input_type == redsea::InputType::MPX_sndfile) {\n std::cerr << \"error: redsea was compiled without liquid-dsp\"\n << '\\n';\n return EXIT_FAILURE;\n }\n#endif\n\n redsea::MPXReader mpx(options);\n options.samplerate = mpx.samplerate();\n options.num_channels = mpx.num_channels();\n\n if (mpx.error())\n return EXIT_FAILURE;\n\n \/* When we don't have MPX input, there are no channels. But we want at least\n * 1 Channel anyway. Also, we need a sample rate for the Subcarrier\n * constructor.\n *\/\n if (options.input_type != redsea::InputType::MPX_sndfile &&\n options.input_type != redsea::InputType::MPX_stdin) {\n options.num_channels = 1;\n options.samplerate = redsea::kTargetSampleRate_Hz;\n }\n\n std::vector<redsea::Channel> channels;\n for (int n_channel = 0; n_channel < options.num_channels; n_channel++)\n channels.emplace_back(redsea::Channel(options, n_channel));\n\n redsea::AsciiBitReader ascii_reader(options);\n\n while (true) {\n bool eof = false;\n if (options.input_type == redsea::InputType::MPX_stdin ||\n options.input_type == redsea::InputType::MPX_sndfile) {\n eof = mpx.eof();\n } else if (options.input_type == redsea::InputType::ASCIIbits) {\n eof = ascii_reader.eof();\n } else if (options.input_type == redsea::InputType::Hex) {\n eof = std::cin.eof();\n }\n\n if (eof)\n break;\n\n if (options.input_type == redsea::InputType::MPX_stdin ||\n options.input_type == redsea::InputType::MPX_sndfile)\n mpx.FillBuffer();\n\n for (int n_channel = 0; n_channel < options.num_channels; n_channel++) {\n switch (options.input_type) {\n case redsea::InputType::MPX_stdin:\n case redsea::InputType::MPX_sndfile:\n channels[n_channel].ProcessChunk(mpx.ReadChunk(n_channel));\n break;\n\n case redsea::InputType::ASCIIbits:\n channels[n_channel].ProcessBit(ascii_reader.ReadNextBit());\n break;\n\n case redsea::InputType::Hex:\n channels[n_channel].ProcessGroup(redsea::ReadNextHexGroup(options));\n break;\n }\n }\n }\n\n return EXIT_SUCCESS;\n}\n<commit_msg>tidier flow in main()<commit_after>\/*\n * redsea - RDS decoder\n * Copyright (c) Oona Räisänen OH2EIQ (windyoona@gmail.com)\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n#include <iostream>\n\n#include \"config.h\"\n#include \"src\/channel.h\"\n#include \"src\/common.h\"\n#include \"src\/groups.h\"\n#include \"src\/options.h\"\n#include \"src\/subcarrier.h\"\n\nnamespace redsea {\n\nvoid PrintUsage() {\n std::cout <<\n \"radio_command | redsea [OPTIONS]\\n\"\n \"\\n\"\n \"By default, a 171 kHz single-channel 16-bit MPX signal is expected via\\n\"\n \"stdin.\\n\"\n \"\\n\"\n \"-b, --input-bits Input is an unsynchronized ASCII bit stream\\n\"\n \" (011010110...). All characters but '0' and '1'\\n\"\n \" are ignored.\\n\"\n \"\\n\"\n \"-c, --channels CHANS Number of channels in the raw input signal. Each\\n\"\n \" channel is demodulated independently.\\n\"\n \"\\n\"\n \"-e, --feed-through Echo the input signal to stdout and print\\n\"\n \" decoded groups to stderr.\\n\"\n \"\\n\"\n \"-E, --bler Display the average block error rate, or the\\n\"\n \" percentage of blocks that had errors before\\n\"\n \" error correction. Averaged over the last 12\\n\"\n \" groups. For hex input, this is the percentage\\n\"\n \" of missing blocks.\\n\"\n \"\\n\"\n \"-f, --file FILENAME Use an audio file as MPX input. All formats\\n\"\n \" readable by libsndfile should work.\\n\"\n \"\\n\"\n \"-h, --input-hex The input is in the RDS Spy hex format.\\n\"\n \"\\n\"\n \"-l, --loctable DIR Load TMC location table from a directory in TMC\\n\"\n \" Exchange format.\\n\"\n \"\\n\"\n \"-p, --show-partial Under noisy conditions, redsea may not be able to\\n\"\n \" fully receive all information. Multi-group data\\n\"\n \" such as PS names, RadioText, and alternative\\n\"\n \" frequencies are especially vulnerable. This option\\n\"\n \" makes it display them even if not fully received,\\n\"\n \" as partial_{ps,radiotext,alt_kilohertz}.\\n\"\n \"\\n\"\n \"-r, --samplerate RATE Set stdin sample frequency in Hz. Will resample\\n\"\n \" (slow) if this differs from 171000 Hz.\\n\"\n \"\\n\"\n \"-t, --timestamp FORMAT Add time of decoding to JSON groups; see\\n\"\n \" man strftime for formatting options (or\\n\"\n \" try \\\"%c\\\").\\n\"\n \"\\n\"\n \"-u, --rbds RBDS mode; use North American program type names\\n\"\n \" and \\\"back-calculate\\\" the station's call sign from\\n\"\n \" its PI code. Note that this calculation gives an\\n\"\n \" incorrect call sign for most stations that transmit\\n\"\n \" TMC.\\n\"\n \"\\n\"\n \"-v, --version Print version string and exit.\\n\"\n \"\\n\"\n \"-x, --output-hex Output hex groups in the RDS Spy format,\\n\"\n \" suppressing JSON output.\\n\";\n}\n\nvoid PrintVersion() {\n#ifdef DEBUG\n std::cout << PACKAGE_STRING << \"-debug by OH2EIQ\" << '\\n';\n#else\n std::cout << PACKAGE_STRING << \" by OH2EIQ\" << '\\n';\n#endif\n}\n\nint ProcessMPXInput(Options options) {\n\n#ifndef HAVE_LIQUID\n std::cerr << \"error: redsea was compiled without liquid-dsp\"\n << '\\n';\n return EXIT_FAILURE;\n#endif\n\n MPXReader mpx(options);\n options.samplerate = mpx.samplerate();\n options.num_channels = mpx.num_channels();\n\n if (mpx.error())\n return EXIT_FAILURE;\n\n std::vector<Channel> channels;\n for (int i = 0; i < options.num_channels; i++) {\n channels.emplace_back(options, i);\n }\n\n while (!mpx.eof()) {\n mpx.FillBuffer();\n for (int i = 0; i < options.num_channels; i++) {\n channels[i].ProcessChunk(mpx.ReadChunk(i));\n }\n }\n\n return EXIT_SUCCESS;\n}\n\nint ProcessASCIIBitsInput(Options options) {\n Channel channel(options, 0);\n AsciiBitReader ascii_reader(options);\n\n while (!ascii_reader.eof()) {\n channel.ProcessBit(ascii_reader.ReadBit());\n }\n\n return EXIT_SUCCESS;\n}\n\nint ProcessHexInput(Options options) {\n Channel channel(options, 0);\n\n while (!std::cin.eof()) {\n channel.ProcessGroup(ReadHexGroup(options));\n }\n\n return EXIT_SUCCESS;\n}\n\n} \/\/ namespace redsea\n\nint main(int argc, char** argv) {\n redsea::Options options = redsea::GetOptions(argc, argv);\n\n if (options.print_usage)\n redsea::PrintUsage();\n\n if (options.print_version)\n redsea::PrintVersion();\n\n if (options.exit_failure)\n return EXIT_FAILURE;\n\n if (options.exit_success)\n return EXIT_SUCCESS;\n\n switch (options.input_type) {\n case redsea::InputType::MPX_stdin:\n case redsea::InputType::MPX_sndfile:\n return ProcessMPXInput(options);\n break;\n\n case redsea::InputType::ASCIIbits:\n return ProcessASCIIBitsInput(options);\n break;\n\n case redsea::InputType::Hex:\n return ProcessHexInput(options);\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkNullCanvas.h\"\n\n#include \"SkCanvas.h\"\n#include \"SKNWayCanvas.h\"\n\n\nSkCanvas* SkCreateNullCanvas() {\n \/\/ An N-Way canvas forwards calls to N canvas's. When N == 0 it's\n \/\/ effectively a null canvas.\n return SkNEW(SkNWayCanvas);\n}\n<commit_msg>Fix SkNWayCanvas cons call when creating null canvas.<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkNullCanvas.h\"\n\n#include \"SkCanvas.h\"\n#include \"SKNWayCanvas.h\"\n\n\nSkCanvas* SkCreateNullCanvas() {\n \/\/ An N-Way canvas forwards calls to N canvas's. When N == 0 it's\n \/\/ effectively a null canvas.\n return SkNEW(SkNWayCanvas(0,0));\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef DELEGATE_HPP\n# define DELEGATE_HPP\n\n#include <cassert>\n\n#include <bitset>\n\n#include <memory>\n\n#include <new>\n\n#include <type_traits>\n\n#include <utility>\n\n#include \"lightptr.hpp\"\n\nnamespace\n{\n template <typename T>\n struct static_store\n {\n static constexpr ::std::size_t const max_instances = 64;\n\n static ::std::bitset<max_instances> memory_map_;\n static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type\n store_[max_instances];\n };\n\n template <typename T>\n ::std::bitset<static_store<T>::max_instances>\n static_store<T>::memory_map_{(unsigned long long)(-1)};\n\n template <typename T>\n typename ::std::aligned_storage<sizeof(T), alignof(T)>::type\n static_store<T>::store_[static_store<T>::max_instances];\n\n template <typename T, typename ...A>\n inline T* static_new(A&& ...args)\n {\n using static_store = static_store<T>;\n\n auto const i(__builtin_ffsll(static_store::memory_map_.to_ullong()));\n \/\/assert(static_store::max_instances != i);\n\n auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));\n\n static_store::memory_map_[i] = false;\n\n return p;\n }\n\n template <typename T>\n inline void static_delete(T const* const p)\n {\n using static_store = static_store<T>;\n\n auto const i(p - static_cast<T const*>(static_cast<void const*>(\n static_store::store_)));\n \/\/assert(!as_const(static_store::memory_map_)[i]);\n\n static_store::memory_map_[i] = true;\n\n static_cast<T const*>(static_cast<void const*>(\n &static_store::store_[i]))->~T();\n }\n}\n\ntemplate <typename T> class delegate;\n\ntemplate<class R, class ...A>\nclass delegate<R (A...)>\n{\n using stub_ptr_type = R (*)(void*, A&&...);\n\n delegate(void* const o, stub_ptr_type const m) noexcept\n : object_ptr_(o),\n stub_ptr_(m)\n {\n }\n\npublic:\n delegate() = default;\n\n delegate(delegate const&) = default;\n\n delegate(delegate&&) = default;\n\n delegate(::std::nullptr_t const) noexcept : delegate() { }\n\n template <class C>\n explicit delegate(C const* const o) noexcept\n : object_ptr_(const_cast<C*>(o))\n {\n }\n\n template <class C>\n explicit delegate(C const& o) noexcept\n : object_ptr_(const_cast<C*>(&o))\n {\n }\n\n delegate(R (* const function_ptr)(A...))\n {\n *this = from(function_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...))\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C& object, R (C::* const method_ptr)(A...))\n {\n *this = from(object, method_ptr);\n }\n\n template <class C>\n delegate(C const& object, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object, method_ptr);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate(T&& f)\n {\n *this = ::std::forward<T>(f);\n }\n\n delegate& operator=(delegate const&) = default;\n\n delegate& operator=(delegate&& rhs) = default;\n\n delegate& operator=(R (* const rhs)(A...))\n {\n return *this = from(rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...))\n {\n return *this = from(static_cast<C*>(object_ptr_), rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...) const)\n {\n return *this = from(static_cast<C const*>(object_ptr_), rhs);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate& operator=(T&& f)\n {\n using functor_type = typename ::std::decay<T>::type;\n\n store_.reset(static_new<functor_type>(::std::forward<T>(f)),\n functor_deleter<functor_type>);\n\n object_ptr_ = store_.get();\n\n stub_ptr_ = functor_stub<functor_type>;\n\n return *this;\n }\n\n template <R (* const function_ptr)(A...)>\n static delegate from() noexcept\n {\n return { nullptr, function_stub<function_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C* const object_ptr) noexcept\n {\n return { object_ptr, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const* const object_ptr) noexcept\n {\n return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C& object) noexcept\n {\n return { &object, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const& object) noexcept\n {\n return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };\n }\n\n template <typename T>\n static delegate from(T&& f)\n {\n return ::std::forward<T>(f);\n }\n\n static delegate from(R (* const function_ptr)(A...))\n {\n return [function_ptr](A&&... args) {\n return (*function_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C* const object_ptr,\n R (C::* const method_ptr)(A...))\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const* const object_ptr,\n R (C::* const method_ptr)(A...) const)\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C& object, R (C::* const method_ptr)(A...))\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const& object,\n R (C::* const method_ptr)(A...) const)\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n void reset() { stub_ptr_ = nullptr; store_.reset(); }\n\n void reset_stub() noexcept { stub_ptr_ = nullptr; }\n\n void swap(delegate& other) noexcept { ::std::swap(*this, other); }\n\n bool operator==(delegate const& rhs) const noexcept\n {\n return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);\n }\n\n bool operator!=(delegate const& rhs) const noexcept\n {\n return !operator==(rhs);\n }\n\n bool operator<(delegate const& rhs) const noexcept\n {\n return (object_ptr_ < rhs.object_ptr_) ||\n ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));\n }\n\n bool operator==(::std::nullptr_t const) const noexcept\n {\n return !stub_ptr_;\n }\n\n bool operator!=(::std::nullptr_t const) const noexcept\n {\n return stub_ptr_;\n }\n\n explicit operator bool() const noexcept { return stub_ptr_; }\n\n R operator()(A... args) const\n {\n\/\/ assert(stub_ptr);\n return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);\n }\n\nprivate:\n friend class ::std::hash<delegate>;\n\n void* object_ptr_;\n stub_ptr_type stub_ptr_{};\n\n light_ptr<void> store_;\n\n template <class T>\n static void functor_deleter(void* const p)\n {\n static_cast<T const*>(p)->~T();\n\n static_delete(static_cast<T const*>(p));\n }\n\n template <R (*function_ptr)(A...)>\n static R function_stub(void* const, A&&... args)\n {\n return function_ptr(::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...)>\n static R method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...) const>\n static R const_method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C const*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <typename T>\n static R functor_stub(void* const object_ptr, A&&... args)\n {\n return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);\n }\n};\n\nnamespace std\n{\n template <typename R, typename ...A>\n struct hash<delegate<R (A...)> >\n {\n size_t operator()(delegate<R (A...)> const& d) const noexcept\n {\n auto const seed(hash<void*>()(d.object_ptr_));\n\n return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +\n 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n };\n}\n\n#endif \/\/ DELEGATE_HPP\n<commit_msg>some fixes<commit_after>#pragma once\n#ifndef DELEGATE_HPP\n# define DELEGATE_HPP\n\n#include <cassert>\n\n#include <bitset>\n\n#include <memory>\n\n#include <new>\n\n#include <type_traits>\n\n#include <utility>\n\n#include \"lightptr.hpp\"\n\nnamespace\n{\n template <typename T>\n struct static_store\n {\n static constexpr ::std::size_t const max_instances = 64;\n\n static ::std::bitset<max_instances> memory_map_;\n static typename ::std::aligned_storage<sizeof(T),\n alignof(T)>::type* store_;\n };\n\n template <typename T>\n ::std::bitset<static_store<T>::max_instances>\n static_store<T>::memory_map_{(unsigned long long)(-1)};\n\n template <typename T>\n typename ::std::aligned_storage<sizeof(T), alignof(T)>::type*\n static_store<T>::store_{new typename\n ::std::aligned_storage<sizeof(T), alignof(T)>::type[\n static_store<T>::max_instances]};\n\n template <typename T, typename ...A>\n inline T* static_new(A&& ...args)\n {\n using static_store = static_store<T>;\n\n auto const i(__builtin_ffsll(static_store::memory_map_.to_ullong()));\n \/\/assert(static_store::max_instances != i);\n\n auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));\n\n static_store::memory_map_[i] = false;\n\n return p;\n }\n\n template <typename T>\n inline void static_delete(T const* const p)\n {\n using static_store = static_store<T>;\n\n auto const i(p - static_cast<T const*>(static_cast<void const*>(\n static_store::store_)));\n \/\/assert(!as_const(static_store::memory_map_)[i]);\n\n static_store::memory_map_[i] = true;\n\n static_cast<T const*>(static_cast<void const*>(\n &static_store::store_[i]))->~T();\n }\n}\n\ntemplate <typename T> class delegate;\n\ntemplate<class R, class ...A>\nclass delegate<R (A...)>\n{\n using stub_ptr_type = R (*)(void*, A&&...);\n\n delegate(void* const o, stub_ptr_type const m) noexcept\n : object_ptr_(o),\n stub_ptr_(m)\n {\n }\n\npublic:\n delegate() = default;\n\n delegate(delegate const&) = default;\n\n delegate(delegate&&) = default;\n\n delegate(::std::nullptr_t const) noexcept : delegate() { }\n\n template <class C>\n explicit delegate(C const* const o) noexcept\n : object_ptr_(const_cast<C*>(o))\n {\n }\n\n template <class C>\n explicit delegate(C const& o) noexcept\n : object_ptr_(const_cast<C*>(&o))\n {\n }\n\n delegate(R (* const function_ptr)(A...))\n {\n *this = from(function_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...))\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C& object, R (C::* const method_ptr)(A...))\n {\n *this = from(object, method_ptr);\n }\n\n template <class C>\n delegate(C const& object, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object, method_ptr);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate(T&& f)\n {\n *this = ::std::forward<T>(f);\n }\n\n delegate& operator=(delegate const&) = default;\n\n delegate& operator=(delegate&& rhs) = default;\n\n delegate& operator=(R (* const rhs)(A...))\n {\n return *this = from(rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...))\n {\n return *this = from(static_cast<C*>(object_ptr_), rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...) const)\n {\n return *this = from(static_cast<C const*>(object_ptr_), rhs);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate& operator=(T&& f)\n {\n using functor_type = typename ::std::decay<T>::type;\n\n store_.reset(static_new<functor_type>(::std::forward<T>(f)),\n functor_deleter<functor_type>);\n\n object_ptr_ = store_.get();\n\n stub_ptr_ = functor_stub<functor_type>;\n\n return *this;\n }\n\n template <R (* const function_ptr)(A...)>\n static delegate from() noexcept\n {\n return { nullptr, function_stub<function_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C* const object_ptr) noexcept\n {\n return { object_ptr, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const* const object_ptr) noexcept\n {\n return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C& object) noexcept\n {\n return { &object, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const& object) noexcept\n {\n return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };\n }\n\n template <typename T>\n static delegate from(T&& f)\n {\n return ::std::forward<T>(f);\n }\n\n static delegate from(R (* const function_ptr)(A...))\n {\n return [function_ptr](A&&... args) {\n return (*function_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C* const object_ptr,\n R (C::* const method_ptr)(A...))\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const* const object_ptr,\n R (C::* const method_ptr)(A...) const)\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C& object, R (C::* const method_ptr)(A...))\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const& object,\n R (C::* const method_ptr)(A...) const)\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n void reset() { stub_ptr_ = nullptr; store_.reset(); }\n\n void reset_stub() noexcept { stub_ptr_ = nullptr; }\n\n void swap(delegate& other) noexcept { ::std::swap(*this, other); }\n\n bool operator==(delegate const& rhs) const noexcept\n {\n return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);\n }\n\n bool operator!=(delegate const& rhs) const noexcept\n {\n return !operator==(rhs);\n }\n\n bool operator<(delegate const& rhs) const noexcept\n {\n return (object_ptr_ < rhs.object_ptr_) ||\n ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));\n }\n\n bool operator==(::std::nullptr_t const) const noexcept\n {\n return !stub_ptr_;\n }\n\n bool operator!=(::std::nullptr_t const) const noexcept\n {\n return stub_ptr_;\n }\n\n explicit operator bool() const noexcept { return stub_ptr_; }\n\n R operator()(A... args) const\n {\n\/\/ assert(stub_ptr);\n return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);\n }\n\nprivate:\n friend class ::std::hash<delegate>;\n\n void* object_ptr_;\n stub_ptr_type stub_ptr_{};\n\n light_ptr<void> store_;\n\n template <class T>\n static void functor_deleter(void* const p)\n {\n static_cast<T const*>(p)->~T();\n\n static_delete(static_cast<T const*>(p));\n }\n\n template <R (*function_ptr)(A...)>\n static R function_stub(void* const, A&&... args)\n {\n return function_ptr(::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...)>\n static R method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...) const>\n static R const_method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C const*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <typename T>\n static R functor_stub(void* const object_ptr, A&&... args)\n {\n return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);\n }\n};\n\nnamespace std\n{\n template <typename R, typename ...A>\n struct hash<delegate<R (A...)> >\n {\n size_t operator()(delegate<R (A...)> const& d) const noexcept\n {\n auto const seed(hash<void*>()(d.object_ptr_));\n\n return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +\n 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n };\n}\n\n#endif \/\/ DELEGATE_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef DELEGATE_HPP\n# define DELEGATE_HPP\n\n#include <cassert>\n\n#include <memory>\n\n#include <new>\n\n#include <type_traits>\n\n#include <utility>\n\ntemplate <typename T> class delegate;\n\ntemplate<class R, class ...A>\nclass delegate<R (A...)>\n{\n using stub_ptr_type = R (*)(void*, A&&...);\n\n delegate(void* const o, stub_ptr_type const m) noexcept\n : object_ptr_(o),\n stub_ptr_(m)\n {\n }\n\npublic:\n static constexpr auto const max_stores = 200;\n\n delegate() = default;\n\n delegate(delegate const&) = default;\n\n delegate(delegate&&) = default;\n\n delegate(::std::nullptr_t const) noexcept : delegate() { }\n\n template <class C>\n explicit delegate(C const* const o) noexcept\n : object_ptr_(const_cast<C*>(o))\n {\n }\n\n template <class C>\n explicit delegate(C const& o) noexcept\n : object_ptr_(const_cast<C*>(&o))\n {\n }\n\n delegate(R (* const function_ptr)(A...))\n {\n *this = from(function_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...))\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object_ptr, method_ptr);\n }\n\n template <class C>\n delegate(C& object, R (C::* const method_ptr)(A...))\n {\n *this = from(object, method_ptr);\n }\n\n template <class C>\n delegate(C const& object, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object, method_ptr);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate(T&& f)\n {\n using functor_type = typename ::std::decay<T>::type;\n\n alignas(functor_type) static char store_[max_stores][sizeof(T)];\n static ::std::size_t store_index;\n\n assert(store_index != max_stores);\n new (store_[store_index++]) functor_type(::std::forward<T>(f));\n\n object_ptr_ = store_;\n\n stub_ptr_ = functor_stub<functor_type>;\n\n deleter_ = deleter_stub<functor_type>;\n }\n\n delegate& operator=(delegate const&) = default;\n\n delegate& operator=(delegate&& rhs) = default;\n\n delegate& operator=(R (* const rhs)(A...))\n {\n return *this = from(rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...))\n {\n return *this = from(static_cast<C*>(object_ptr_), rhs);\n }\n\n template <class C>\n delegate& operator=(R (C::* const rhs)(A...) const)\n {\n return *this = from(static_cast<C const*>(object_ptr_), rhs);\n }\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<delegate, typename ::std::decay<T>::type>{}\n >::type\n >\n delegate& operator=(T&& f)\n {\n using functor_type = typename ::std::decay<T>::type;\n\n alignas(functor_type) static char store_[max_stores][sizeof(T)];\n static ::std::size_t store_index;\n\n deleter_(store_);\n\n assert(store_index != max_stores);\n new (store_[store_index++]) functor_type(::std::forward<T>(f));\n\n object_ptr_ = store_;\n\n stub_ptr_ = functor_stub<functor_type>;\n\n deleter_ = deleter_stub<functor_type>;\n\n return *this;\n }\n\n template <R (* const function_ptr)(A...)>\n static delegate from() noexcept\n {\n return { nullptr, function_stub<function_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C* const object_ptr) noexcept\n {\n return { object_ptr, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const* const object_ptr) noexcept\n {\n return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...)>\n static delegate from(C& object) noexcept\n {\n return { &object, method_stub<C, method_ptr> };\n }\n\n template <class C, R (C::* const method_ptr)(A...) const>\n static delegate from(C const& object) noexcept\n {\n return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };\n }\n\n template <typename T>\n static delegate from(T&& f)\n {\n return ::std::forward<T>(f);\n }\n\n static delegate from(R (* const function_ptr)(A...))\n {\n return [function_ptr](A&&... args) {\n return (*function_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C* const object_ptr,\n R (C::* const method_ptr)(A...))\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const* const object_ptr,\n R (C::* const method_ptr)(A...) const)\n {\n return [object_ptr, method_ptr](A&&... args) {\n return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C& object, R (C::* const method_ptr)(A...))\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n template <class C>\n static delegate from(C const& object,\n R (C::* const method_ptr)(A...) const)\n {\n return [&object, method_ptr](A&&... args) {\n return (object.*method_ptr)(::std::forward<A>(args)...); };\n }\n\n void reset() { stub_ptr_ = nullptr; }\n\n void reset_stub() noexcept { stub_ptr_ = nullptr; }\n\n void swap(delegate& other) noexcept { ::std::swap(*this, other); }\n\n bool operator==(delegate const& rhs) const noexcept\n {\n return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);\n }\n\n bool operator!=(delegate const& rhs) const noexcept\n {\n return !operator==(rhs);\n }\n\n bool operator<(delegate const& rhs) const noexcept\n {\n return (object_ptr_ < rhs.object_ptr_) ||\n ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));\n }\n\n bool operator==(::std::nullptr_t const) const noexcept\n {\n return !stub_ptr_;\n }\n\n bool operator!=(::std::nullptr_t const) const noexcept\n {\n return stub_ptr_;\n }\n\n explicit operator bool() const noexcept { return stub_ptr_; }\n\n R operator()(A... args) const\n {\n\/\/ assert(stub_ptr);\n return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);\n }\n\nprivate:\n friend class ::std::hash<delegate>;\n\n using deleter_type = void (*)(void const*);\n\n void* object_ptr_;\n stub_ptr_type stub_ptr_{};\n\n deleter_type deleter_{default_deleter_stub};\n\n static void default_deleter_stub(void const* const) { }\n\n template <class T>\n static void deleter_stub(void const* const p)\n {\n static_cast<T const*>(p)->~T();\n }\n\n template <R (*function_ptr)(A...)>\n static R function_stub(void* const, A&&... args)\n {\n return function_ptr(::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...)>\n static R method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <class C, R (C::*method_ptr)(A...) const>\n static R const_method_stub(void* const object_ptr, A&&... args)\n {\n return (static_cast<C const*>(object_ptr)->*method_ptr)(\n ::std::forward<A>(args)...);\n }\n\n template <typename T>\n static R functor_stub(void* const object_ptr, A&&... args)\n {\n return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);\n }\n};\n\nnamespace std\n{\n template <typename R, typename ...A>\n struct hash<delegate<R (A...)> >\n {\n size_t operator()(delegate<R (A...)> const& d) const noexcept\n {\n auto const seed(hash<void*>()(d.object_ptr_));\n\n return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +\n 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n };\n}\n\n#endif \/\/ DELEGATE_HPP\n<commit_msg>strips2<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2018, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \".\/input_parser.h\"\n\n\/\/ Helper to get optional array of coordinates.\ninline std::array<coordinate_t, 2>\nparse_coordinates(const rapidjson::Value& object, const char* key) {\n if (!object[key].IsArray() or (object[key].Size() < 2) or\n !object[key][0].IsNumber() or !object[key][1].IsNumber()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" array.\");\n }\n return {object[key][0].GetDouble(), object[key][1].GetDouble()};\n}\n\ninline boost::optional<amount_t> get_amount(const rapidjson::Value& object,\n const char* key) {\n if (!object.HasMember(key)) {\n return boost::none;\n }\n\n if (!object[key].IsArray()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" array.\");\n }\n amount_t amount;\n for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) {\n if (!object[key][i].IsInt64()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" value.\");\n }\n amount.push_back(object[key][i].GetInt64());\n }\n\n return amount;\n}\n\ninline bool valid_vehicle(const rapidjson::Value& v) {\n return v.IsObject() and v.HasMember(\"id\") and v[\"id\"].IsUint64();\n}\n\ninput parse(const cl_args_t& cl_args) {\n BOOST_LOG_TRIVIAL(info) << \"[Loading] Parsing input.\";\n\n \/\/ Set relevant wrapper to retrieve the matrix and geometry.\n std::unique_ptr<routing_io<cost_t>> routing_wrapper;\n if (!cl_args.use_libosrm) {\n \/\/ Use osrm-routed.\n routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address,\n cl_args.osrm_port,\n cl_args.osrm_profile);\n } else {\n#if LIBOSRM\n \/\/ Use libosrm.\n if (cl_args.osrm_profile.empty()) {\n throw custom_exception(\"-l flag requires -m.\");\n }\n routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);\n#else\n throw custom_exception(\"libosrm must be installed to use -l.\");\n#endif\n }\n\n \/\/ Custom input object embedding jobs, vehicles and matrix.\n input input_data(std::move(routing_wrapper), cl_args.geometry);\n\n \/\/ Input json object.\n rapidjson::Document json_input;\n\n \/\/ Parsing input string to populate the input object.\n if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {\n std::string error_msg =\n std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +\n \" (offset: \" + std::to_string(json_input.GetErrorOffset()) + \")\";\n throw custom_exception(error_msg);\n }\n\n \/\/ Main Checks for valid json input.\n if (!json_input.HasMember(\"jobs\") or !json_input[\"jobs\"].IsArray() or\n json_input[\"jobs\"].Empty()) {\n throw custom_exception(\"Invalid jobs.\");\n }\n\n if (!json_input.HasMember(\"vehicles\") or !json_input[\"vehicles\"].IsArray() or\n json_input[\"vehicles\"].Empty()) {\n throw custom_exception(\"Invalid vehicles.\");\n }\n\n \/\/ Switch input type: explicit matrix or using OSRM.\n if (json_input.HasMember(\"matrix\")) {\n if (!json_input[\"matrix\"].IsArray()) {\n throw custom_exception(\"Invalid matrix.\");\n }\n\n \/\/ Load custom matrix while checking if it is square.\n rapidjson::SizeType matrix_size = json_input[\"matrix\"].Size();\n\n matrix<cost_t> matrix_input(matrix_size);\n for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {\n if (!json_input[\"matrix\"][i].IsArray() or\n (json_input[\"matrix\"][i].Size() != matrix_size)) {\n throw custom_exception(\"Invalid matrix line \" + std::to_string(i) +\n \".\");\n }\n for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {\n if (!json_input[\"matrix\"][i][j].IsUint()) {\n throw custom_exception(\"Invalid matrix entry (\" + std::to_string(i) +\n \",\" + std::to_string(j) + \").\");\n }\n cost_t cost = json_input[\"matrix\"][i][j].GetUint();\n matrix_input[i][j] = cost;\n }\n }\n input_data.set_matrix(std::move(matrix_input));\n\n \/\/ Add all vehicles.\n for (rapidjson::SizeType i = 0; i < json_input[\"vehicles\"].Size(); ++i) {\n if (!valid_vehicle(json_input[\"vehicles\"][i])) {\n throw custom_exception(\"Invalid vehicle at \" + std::to_string(i) + \".\");\n }\n auto v_id = json_input[\"vehicles\"][i][\"id\"].GetUint();\n\n \/\/ Check if vehicle has start_index or end_index.\n bool has_start_index = json_input[\"vehicles\"][i].HasMember(\"start_index\");\n index_t start_index = 0; \/\/ Initial value actually never used.\n if (has_start_index) {\n if (!json_input[\"vehicles\"][i][\"start_index\"].IsUint()) {\n throw custom_exception(\"Invalid start_index for vehicle \" +\n std::to_string(v_id) + \".\");\n }\n start_index = json_input[\"vehicles\"][i][\"start_index\"].GetUint();\n\n if (matrix_size <= start_index) {\n throw custom_exception(\n \"start_index exceeding matrix size for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n }\n\n bool has_start_coords = json_input[\"vehicles\"][i].HasMember(\"start\");\n\n bool has_end_index = json_input[\"vehicles\"][i].HasMember(\"end_index\");\n index_t end_index = 0; \/\/ Initial value actually never used.\n if (has_end_index) {\n if (!json_input[\"vehicles\"][i][\"end_index\"].IsUint()) {\n throw custom_exception(\"Invalid end_index for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n end_index = json_input[\"vehicles\"][i][\"end_index\"].GetUint();\n\n if (matrix_size <= end_index) {\n throw custom_exception(\"end_index exceeding matrix size for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n }\n\n bool has_end_coords = json_input[\"vehicles\"][i].HasMember(\"end\");\n\n \/\/ Add vehicle to input\n boost::optional<location_t> start;\n if (has_start_index) {\n if (has_start_coords) {\n start = boost::optional<location_t>(location_t(\n {start_index,\n parse_coordinates(json_input[\"vehicles\"][i], \"start\")}));\n } else {\n start = boost::optional<location_t>(start_index);\n }\n }\n\n boost::optional<location_t> end;\n if (has_end_index) {\n if (has_end_coords) {\n end = boost::optional<location_t>(location_t(\n {end_index, parse_coordinates(json_input[\"vehicles\"][i], \"end\")}));\n } else {\n end = boost::optional<location_t>(end_index);\n }\n }\n\n std::vector<skill_t> v_skills;\n\n vehicle_t current_v(v_id,\n start,\n end,\n get_amount(json_input[\"vehicles\"][i], \"capacity\"),\n v_skills);\n\n input_data.add_vehicle(current_v);\n }\n\n \/\/ Add the jobs\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()) {\n throw custom_exception(\"Invalid job.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\") or\n !json_input[\"jobs\"][i][\"id\"].IsUint64()) {\n throw custom_exception(\"Invalid id for job at \" + std::to_string(i) +\n \".\");\n }\n auto j_id = json_input[\"jobs\"][i][\"id\"].GetUint64();\n if (!json_input[\"jobs\"][i].HasMember(\"location_index\") or\n !json_input[\"jobs\"][i][\"location_index\"].IsUint()) {\n throw custom_exception(\"Invalid location_index for job \" +\n std::to_string(j_id) + \".\");\n }\n if (matrix_size <= json_input[\"jobs\"][i][\"location_index\"].GetUint()) {\n throw custom_exception(\"location_index exceeding matrix size for job \" +\n std::to_string(j_id) + \".\");\n }\n\n std::vector<skill_t> job_skills;\n\n if (json_input[\"jobs\"][i].HasMember(\"location\")) {\n job_t current_job(j_id,\n get_amount(json_input[\"jobs\"][i], \"amount\"),\n job_skills,\n json_input[\"jobs\"][i][\"location_index\"].GetUint(),\n parse_coordinates(json_input[\"jobs\"][i], \"location\"));\n input_data.add_job(current_job);\n } else {\n job_t current_job(json_input[\"jobs\"][i][\"id\"].GetUint64(),\n get_amount(json_input[\"jobs\"][i], \"amount\"),\n job_skills,\n json_input[\"jobs\"][i][\"location_index\"].GetUint());\n input_data.add_job(current_job);\n }\n }\n } else {\n \/\/ Adding vehicles and jobs only, matrix will be computed using\n \/\/ OSRM upon solving.\n\n \/\/ All vehicles.\n for (rapidjson::SizeType i = 0; i < json_input[\"vehicles\"].Size(); ++i) {\n if (!valid_vehicle(json_input[\"vehicles\"][i])) {\n throw custom_exception(\"Invalid vehicle at \" + std::to_string(i) + \".\");\n }\n\n \/\/ Start def is a ugly workaround as using plain:\n \/\/\n \/\/ boost::optional<location_t> start;\n \/\/\n \/\/ will raise a false positive -Wmaybe-uninitialized with gcc,\n \/\/ see https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=47679\n\n auto start([]() -> boost::optional<location_t> { return boost::none; }());\n if (json_input[\"vehicles\"][i].HasMember(\"start\")) {\n start = boost::optional<location_t>(\n parse_coordinates(json_input[\"vehicles\"][i], \"start\"));\n }\n\n boost::optional<location_t> end;\n if (json_input[\"vehicles\"][i].HasMember(\"end\")) {\n end = boost::optional<location_t>(\n parse_coordinates(json_input[\"vehicles\"][i], \"end\"));\n }\n\n std::vector<skill_t> v_skills;\n\n vehicle_t current_v(json_input[\"vehicles\"][i][\"id\"].GetUint(),\n start,\n end,\n get_amount(json_input[\"vehicles\"][i], \"capacity\"),\n v_skills);\n\n input_data.add_vehicle(current_v);\n }\n\n \/\/ Getting jobs.\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()) {\n throw custom_exception(\"Invalid job.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\") or\n !json_input[\"jobs\"][i][\"id\"].IsUint64()) {\n throw custom_exception(\"Invalid id for job at \" + std::to_string(i) +\n \".\");\n }\n auto j_id = json_input[\"jobs\"][i][\"id\"].GetUint64();\n if (!json_input[\"jobs\"][i].HasMember(\"location\") or\n !json_input[\"jobs\"][i][\"location\"].IsArray()) {\n throw custom_exception(\"Invalid location for job \" +\n std::to_string(j_id) + \".\");\n }\n\n std::vector<skill_t> job_skills;\n\n job_t current_job(j_id,\n get_amount(json_input[\"jobs\"][i], \"amount\"),\n job_skills,\n parse_coordinates(json_input[\"jobs\"][i], \"location\"));\n\n input_data.add_job(current_job);\n }\n }\n\n return input_data;\n}\n<commit_msg>Parse skills for jobs and vehicles in json input.<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2018, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \".\/input_parser.h\"\n\n\/\/ Helper to get optional array of coordinates.\ninline std::array<coordinate_t, 2>\nparse_coordinates(const rapidjson::Value& object, const char* key) {\n if (!object[key].IsArray() or (object[key].Size() < 2) or\n !object[key][0].IsNumber() or !object[key][1].IsNumber()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" array.\");\n }\n return {object[key][0].GetDouble(), object[key][1].GetDouble()};\n}\n\ninline boost::optional<amount_t> get_amount(const rapidjson::Value& object,\n const char* key) {\n if (!object.HasMember(key)) {\n return boost::none;\n }\n\n if (!object[key].IsArray()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" array.\");\n }\n amount_t amount;\n for (rapidjson::SizeType i = 0; i < object[key].Size(); ++i) {\n if (!object[key][i].IsInt64()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" value.\");\n }\n amount.push_back(object[key][i].GetInt64());\n }\n\n return amount;\n}\n\ninline std::vector<skill_t> get_skills(const rapidjson::Value& object) {\n std::vector<skill_t> skills;\n if (object.HasMember(\"skills\")) {\n if (!object[\"skills\"].IsArray()) {\n throw custom_exception(\"Invalid skills object.\");\n }\n for (rapidjson::SizeType i = 0; i < object[\"skills\"].Size(); ++i) {\n if (!object[\"skills\"][i].IsUint()) {\n throw custom_exception(\"Invalid skill value.\");\n }\n skills.push_back(object[\"skills\"][i].GetUint());\n }\n }\n\n return skills;\n}\n\ninline bool valid_vehicle(const rapidjson::Value& v) {\n return v.IsObject() and v.HasMember(\"id\") and v[\"id\"].IsUint64();\n}\n\ninput parse(const cl_args_t& cl_args) {\n BOOST_LOG_TRIVIAL(info) << \"[Loading] Parsing input.\";\n\n \/\/ Set relevant wrapper to retrieve the matrix and geometry.\n std::unique_ptr<routing_io<cost_t>> routing_wrapper;\n if (!cl_args.use_libosrm) {\n \/\/ Use osrm-routed.\n routing_wrapper = std::make_unique<routed_wrapper>(cl_args.osrm_address,\n cl_args.osrm_port,\n cl_args.osrm_profile);\n } else {\n#if LIBOSRM\n \/\/ Use libosrm.\n if (cl_args.osrm_profile.empty()) {\n throw custom_exception(\"-l flag requires -m.\");\n }\n routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);\n#else\n throw custom_exception(\"libosrm must be installed to use -l.\");\n#endif\n }\n\n \/\/ Custom input object embedding jobs, vehicles and matrix.\n input input_data(std::move(routing_wrapper), cl_args.geometry);\n\n \/\/ Input json object.\n rapidjson::Document json_input;\n\n \/\/ Parsing input string to populate the input object.\n if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {\n std::string error_msg =\n std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +\n \" (offset: \" + std::to_string(json_input.GetErrorOffset()) + \")\";\n throw custom_exception(error_msg);\n }\n\n \/\/ Main Checks for valid json input.\n if (!json_input.HasMember(\"jobs\") or !json_input[\"jobs\"].IsArray() or\n json_input[\"jobs\"].Empty()) {\n throw custom_exception(\"Invalid jobs.\");\n }\n\n if (!json_input.HasMember(\"vehicles\") or !json_input[\"vehicles\"].IsArray() or\n json_input[\"vehicles\"].Empty()) {\n throw custom_exception(\"Invalid vehicles.\");\n }\n\n \/\/ Switch input type: explicit matrix or using OSRM.\n if (json_input.HasMember(\"matrix\")) {\n if (!json_input[\"matrix\"].IsArray()) {\n throw custom_exception(\"Invalid matrix.\");\n }\n\n \/\/ Load custom matrix while checking if it is square.\n rapidjson::SizeType matrix_size = json_input[\"matrix\"].Size();\n\n matrix<cost_t> matrix_input(matrix_size);\n for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {\n if (!json_input[\"matrix\"][i].IsArray() or\n (json_input[\"matrix\"][i].Size() != matrix_size)) {\n throw custom_exception(\"Invalid matrix line \" + std::to_string(i) +\n \".\");\n }\n for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {\n if (!json_input[\"matrix\"][i][j].IsUint()) {\n throw custom_exception(\"Invalid matrix entry (\" + std::to_string(i) +\n \",\" + std::to_string(j) + \").\");\n }\n cost_t cost = json_input[\"matrix\"][i][j].GetUint();\n matrix_input[i][j] = cost;\n }\n }\n input_data.set_matrix(std::move(matrix_input));\n\n \/\/ Add all vehicles.\n for (rapidjson::SizeType i = 0; i < json_input[\"vehicles\"].Size(); ++i) {\n auto& json_vehicle = json_input[\"vehicles\"][i];\n if (!valid_vehicle(json_vehicle)) {\n throw custom_exception(\"Invalid vehicle at \" + std::to_string(i) + \".\");\n }\n auto v_id = json_vehicle[\"id\"].GetUint();\n\n \/\/ Check if vehicle has start_index or end_index.\n bool has_start_index = json_vehicle.HasMember(\"start_index\");\n index_t start_index = 0; \/\/ Initial value actually never used.\n if (has_start_index) {\n if (!json_vehicle[\"start_index\"].IsUint()) {\n throw custom_exception(\"Invalid start_index for vehicle \" +\n std::to_string(v_id) + \".\");\n }\n start_index = json_vehicle[\"start_index\"].GetUint();\n\n if (matrix_size <= start_index) {\n throw custom_exception(\n \"start_index exceeding matrix size for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n }\n\n bool has_start_coords = json_vehicle.HasMember(\"start\");\n\n bool has_end_index = json_vehicle.HasMember(\"end_index\");\n index_t end_index = 0; \/\/ Initial value actually never used.\n if (has_end_index) {\n if (!json_vehicle[\"end_index\"].IsUint()) {\n throw custom_exception(\"Invalid end_index for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n end_index = json_vehicle[\"end_index\"].GetUint();\n\n if (matrix_size <= end_index) {\n throw custom_exception(\"end_index exceeding matrix size for vehicle\" +\n std::to_string(v_id) + \".\");\n }\n }\n\n bool has_end_coords = json_vehicle.HasMember(\"end\");\n\n \/\/ Add vehicle to input\n boost::optional<location_t> start;\n if (has_start_index) {\n if (has_start_coords) {\n start = boost::optional<location_t>(location_t(\n {start_index, parse_coordinates(json_vehicle, \"start\")}));\n } else {\n start = boost::optional<location_t>(start_index);\n }\n }\n\n boost::optional<location_t> end;\n if (has_end_index) {\n if (has_end_coords) {\n end = boost::optional<location_t>(\n location_t({end_index, parse_coordinates(json_vehicle, \"end\")}));\n } else {\n end = boost::optional<location_t>(end_index);\n }\n }\n\n vehicle_t current_v(v_id,\n start,\n end,\n get_amount(json_vehicle, \"capacity\"),\n get_skills(json_vehicle));\n\n input_data.add_vehicle(current_v);\n }\n\n \/\/ Add the jobs\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n auto& json_job = json_input[\"jobs\"][i];\n if (!json_job.IsObject()) {\n throw custom_exception(\"Invalid job.\");\n }\n if (!json_job.HasMember(\"id\") or !json_job[\"id\"].IsUint64()) {\n throw custom_exception(\"Invalid id for job at \" + std::to_string(i) +\n \".\");\n }\n auto j_id = json_job[\"id\"].GetUint64();\n if (!json_job.HasMember(\"location_index\") or\n !json_job[\"location_index\"].IsUint()) {\n throw custom_exception(\"Invalid location_index for job \" +\n std::to_string(j_id) + \".\");\n }\n if (matrix_size <= json_job[\"location_index\"].GetUint()) {\n throw custom_exception(\"location_index exceeding matrix size for job \" +\n std::to_string(j_id) + \".\");\n }\n\n if (json_job.HasMember(\"location\")) {\n job_t current_job(j_id,\n get_amount(json_job, \"amount\"),\n get_skills(json_job),\n json_job[\"location_index\"].GetUint(),\n parse_coordinates(json_job, \"location\"));\n input_data.add_job(current_job);\n } else {\n job_t current_job(json_job[\"id\"].GetUint64(),\n get_amount(json_job, \"amount\"),\n get_skills(json_job),\n json_job[\"location_index\"].GetUint());\n input_data.add_job(current_job);\n }\n }\n } else {\n \/\/ Adding vehicles and jobs only, matrix will be computed using\n \/\/ OSRM upon solving.\n\n \/\/ All vehicles.\n for (rapidjson::SizeType i = 0; i < json_input[\"vehicles\"].Size(); ++i) {\n auto& json_vehicle = json_input[\"vehicles\"][i];\n if (!valid_vehicle(json_vehicle)) {\n throw custom_exception(\"Invalid vehicle at \" + std::to_string(i) + \".\");\n }\n\n \/\/ Start def is a ugly workaround as using plain:\n \/\/\n \/\/ boost::optional<location_t> start;\n \/\/\n \/\/ will raise a false positive -Wmaybe-uninitialized with gcc,\n \/\/ see https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=47679\n\n auto start([]() -> boost::optional<location_t> { return boost::none; }());\n if (json_vehicle.HasMember(\"start\")) {\n start =\n boost::optional<location_t>(parse_coordinates(json_vehicle, \"start\"));\n }\n\n boost::optional<location_t> end;\n if (json_vehicle.HasMember(\"end\")) {\n end =\n boost::optional<location_t>(parse_coordinates(json_vehicle, \"end\"));\n }\n\n vehicle_t current_v(json_vehicle[\"id\"].GetUint(),\n start,\n end,\n get_amount(json_vehicle, \"capacity\"),\n get_skills(json_vehicle));\n\n input_data.add_vehicle(current_v);\n }\n\n \/\/ Getting jobs.\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n auto& json_job = json_input[\"jobs\"][i];\n if (!json_job.IsObject()) {\n throw custom_exception(\"Invalid job.\");\n }\n if (!json_job.HasMember(\"id\") or !json_job[\"id\"].IsUint64()) {\n throw custom_exception(\"Invalid id for job at \" + std::to_string(i) +\n \".\");\n }\n auto j_id = json_job[\"id\"].GetUint64();\n if (!json_job.HasMember(\"location\") or !json_job[\"location\"].IsArray()) {\n throw custom_exception(\"Invalid location for job \" +\n std::to_string(j_id) + \".\");\n }\n\n job_t current_job(j_id,\n get_amount(json_job, \"amount\"),\n get_skills(json_job),\n parse_coordinates(json_job, \"location\"));\n\n input_data.add_job(current_job);\n }\n }\n\n return input_data;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"sparse.h\"\n\ntemplate<typename Scalar> void\ninitSPD(double density,\n Matrix<Scalar,Dynamic,Dynamic>& refMat,\n SparseMatrix<Scalar>& sparseMat)\n{\n Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols());\n initSparse(density,refMat,sparseMat);\n refMat = refMat * refMat.adjoint();\n for (int k=0; k<2; ++k)\n {\n initSparse(density,aux,sparseMat,ForceNonZeroDiag);\n refMat += aux * aux.adjoint();\n }\n sparseMat.setZero();\n for (int j=0 ; j<sparseMat.cols(); ++j)\n for (int i=j ; i<sparseMat.rows(); ++i)\n if (refMat(i,j)!=Scalar(0))\n sparseMat.insert(i,j) = refMat(i,j);\n sparseMat.finalize();\n}\n\ntemplate<typename Scalar> void sparse_solvers(int rows, int cols)\n{\n double density = std::max(8.\/(rows*cols), 0.01);\n typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;\n typedef Matrix<Scalar,Dynamic,1> DenseVector;\n \/\/ Scalar eps = 1e-6;\n\n DenseVector vec1 = DenseVector::Random(rows);\n\n std::vector<Vector2i> zeroCoords;\n std::vector<Vector2i> nonzeroCoords;\n\n \/\/ test triangular solver\n {\n DenseVector vec2 = vec1, vec3 = vec1;\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols);\n\n \/\/ lower - dense\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2),\n m2.template triangular<LowerTriangular>().solve(vec3));\n\n \/\/ upper - dense\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<UpperTriangular>().solveTriangular(vec2),\n m2.template triangular<UpperTriangular>().solve(vec3));\n \n \/\/ TODO test row major\n \n SparseMatrix<Scalar> matB(rows, rows);\n DenseMatrix refMatB = DenseMatrix::Zero(rows, rows);\n \n \/\/ lower - sparse\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular);\n initSparse<Scalar>(density, refMatB, matB);\n refMat2.template marked<LowerTriangular>().solveTriangularInPlace(refMatB);\n m2.template triangular<LowerTriangular>().solveInPlace(matB);\n VERIFY_IS_APPROX(matB.toDense(), refMatB);\n\n \/\/ upper - sparse\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular);\n initSparse<Scalar>(density, refMatB, matB);\n refMat2.template marked<UpperTriangular>().solveTriangularInPlace(refMatB);\n m2.template triangular<UpperTriangular>().solveInPlace(matB);\n VERIFY_IS_APPROX(matB, refMatB);\n \n \/\/ test deprecated API\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2),\n m2.template marked<LowerTriangular>().solveTriangular(vec3));\n }\n\n \/\/ test LLT\n {\n \/\/ TODO fix the issue with complex (see SparseLLT::solveInPlace)\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n initSPD(density, refMat2, m2);\n\n refMat2.llt().solve(b, &refX);\n typedef SparseMatrix<Scalar,LowerTriangular|SelfAdjoint> SparseSelfAdjointMatrix;\n if (!NumTraits<Scalar>::IsComplex)\n {\n x = b;\n SparseLLT<SparseSelfAdjointMatrix> (m2).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: default\");\n }\n #ifdef EIGEN_CHOLMOD_SUPPORT\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Cholmod>(m2).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: cholmod\");\n #endif\n if (!NumTraits<Scalar>::IsComplex)\n {\n #ifdef EIGEN_TAUCS_SUPPORT\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,IncompleteFactorization).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (IncompleteFactorization)\");\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalMultifrontal).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (SupernodalMultifrontal)\");\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalLeftLooking).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (SupernodalLeftLooking)\");\n #endif\n }\n }\n\n \/\/ test LDLT\n if (!NumTraits<Scalar>::IsComplex)\n {\n \/\/ TODO fix the issue with complex (see SparseLDLT::solveInPlace)\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n \/\/initSPD(density, refMat2, m2);\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, 0, 0);\n refMat2 += refMat2.adjoint();\n refMat2.diagonal() *= 0.5;\n\n refMat2.ldlt().solve(b, &refX);\n typedef SparseMatrix<Scalar,UpperTriangular|SelfAdjoint> SparseSelfAdjointMatrix;\n x = b;\n SparseLDLT<SparseSelfAdjointMatrix> ldlt(m2);\n if (ldlt.succeeded())\n ldlt.solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LDLT: default\");\n }\n\n \/\/ test LU\n {\n static int count = 0;\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag, &zeroCoords, &nonzeroCoords);\n\n LU<DenseMatrix> refLu(refMat2);\n refLu.solve(b, &refX);\n #if defined(EIGEN_SUPERLU_SUPPORT) || defined(EIGEN_UMFPACK_SUPPORT)\n Scalar refDet = refLu.determinant();\n #endif\n x.setZero();\n \/\/ \/\/ SparseLU<SparseMatrix<Scalar> > (m2).solve(b,&x);\n \/\/ \/\/ VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: default\");\n #ifdef EIGEN_SUPERLU_SUPPORT\n {\n x.setZero();\n SparseLU<SparseMatrix<Scalar>,SuperLU> slu(m2);\n if (slu.succeeded())\n {\n if (slu.solve(b,&x)) {\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: SuperLU\");\n }\n \/\/ std::cerr << refDet << \" == \" << slu.determinant() << \"\\n\";\n if (slu.solve(b, &x, SvTranspose)) {\n VERIFY(b.isApprox(m2.transpose() * x, test_precision<Scalar>()));\n }\n\n if (slu.solve(b, &x, SvAdjoint)) {\n\/\/ VERIFY(b.isApprox(m2.adjoint() * x, test_precision<Scalar>()));\n }\n\n if (count==0) {\n VERIFY_IS_APPROX(refDet,slu.determinant()); \/\/ FIXME det is not very stable for complex\n }\n }\n }\n #endif\n #ifdef EIGEN_UMFPACK_SUPPORT\n {\n \/\/ check solve\n x.setZero();\n SparseLU<SparseMatrix<Scalar>,UmfPack> slu(m2);\n if (slu.succeeded()) {\n if (slu.solve(b,&x)) {\n if (count==0) {\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: umfpack\"); \/\/ FIXME solve is not very stable for complex\n }\n }\n VERIFY_IS_APPROX(refDet,slu.determinant());\n \/\/ TODO check the extracted data\n \/\/std::cerr << slu.matrixL() << \"\\n\";\n }\n }\n #endif\n count++;\n }\n\n}\n\nvoid test_sparse_solvers()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( sparse_solvers<double>(8, 8) );\n CALL_SUBTEST( sparse_solvers<std::complex<double> >(16, 16) );\n CALL_SUBTEST( sparse_solvers<double>(101, 101) );\n }\n}\n<commit_msg>enable testing of complex numbers for taucs<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"sparse.h\"\n\ntemplate<typename Scalar> void\ninitSPD(double density,\n Matrix<Scalar,Dynamic,Dynamic>& refMat,\n SparseMatrix<Scalar>& sparseMat)\n{\n Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols());\n initSparse(density,refMat,sparseMat);\n refMat = refMat * refMat.adjoint();\n for (int k=0; k<2; ++k)\n {\n initSparse(density,aux,sparseMat,ForceNonZeroDiag);\n refMat += aux * aux.adjoint();\n }\n sparseMat.setZero();\n for (int j=0 ; j<sparseMat.cols(); ++j)\n for (int i=j ; i<sparseMat.rows(); ++i)\n if (refMat(i,j)!=Scalar(0))\n sparseMat.insert(i,j) = refMat(i,j);\n sparseMat.finalize();\n}\n\ntemplate<typename Scalar> void sparse_solvers(int rows, int cols)\n{\n double density = std::max(8.\/(rows*cols), 0.01);\n typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;\n typedef Matrix<Scalar,Dynamic,1> DenseVector;\n \/\/ Scalar eps = 1e-6;\n\n DenseVector vec1 = DenseVector::Random(rows);\n\n std::vector<Vector2i> zeroCoords;\n std::vector<Vector2i> nonzeroCoords;\n\n \/\/ test triangular solver\n {\n DenseVector vec2 = vec1, vec3 = vec1;\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols);\n\n \/\/ lower - dense\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2),\n m2.template triangular<LowerTriangular>().solve(vec3));\n\n \/\/ upper - dense\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<UpperTriangular>().solveTriangular(vec2),\n m2.template triangular<UpperTriangular>().solve(vec3));\n \n \/\/ TODO test row major\n \n SparseMatrix<Scalar> matB(rows, rows);\n DenseMatrix refMatB = DenseMatrix::Zero(rows, rows);\n \n \/\/ lower - sparse\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular);\n initSparse<Scalar>(density, refMatB, matB);\n refMat2.template marked<LowerTriangular>().solveTriangularInPlace(refMatB);\n m2.template triangular<LowerTriangular>().solveInPlace(matB);\n VERIFY_IS_APPROX(matB.toDense(), refMatB);\n\n \/\/ upper - sparse\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular);\n initSparse<Scalar>(density, refMatB, matB);\n refMat2.template marked<UpperTriangular>().solveTriangularInPlace(refMatB);\n m2.template triangular<UpperTriangular>().solveInPlace(matB);\n VERIFY_IS_APPROX(matB, refMatB);\n \n \/\/ test deprecated API\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords);\n VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2),\n m2.template marked<LowerTriangular>().solveTriangular(vec3));\n }\n\n \/\/ test LLT\n {\n \/\/ TODO fix the issue with complex (see SparseLLT::solveInPlace)\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n initSPD(density, refMat2, m2);\n\n refMat2.llt().solve(b, &refX);\n typedef SparseMatrix<Scalar,LowerTriangular|SelfAdjoint> SparseSelfAdjointMatrix;\n if (!NumTraits<Scalar>::IsComplex)\n {\n x = b;\n SparseLLT<SparseSelfAdjointMatrix> (m2).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: default\");\n }\n #ifdef EIGEN_CHOLMOD_SUPPORT\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Cholmod>(m2).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: cholmod\");\n #endif\n \n #ifdef EIGEN_TAUCS_SUPPORT\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,IncompleteFactorization).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (IncompleteFactorization)\");\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalMultifrontal).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (SupernodalMultifrontal)\");\n x = b;\n SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalLeftLooking).solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LLT: taucs (SupernodalLeftLooking)\");\n #endif\n }\n\n \/\/ test LDLT\n if (!NumTraits<Scalar>::IsComplex)\n {\n \/\/ TODO fix the issue with complex (see SparseLDLT::solveInPlace)\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n \/\/initSPD(density, refMat2, m2);\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, 0, 0);\n refMat2 += refMat2.adjoint();\n refMat2.diagonal() *= 0.5;\n\n refMat2.ldlt().solve(b, &refX);\n typedef SparseMatrix<Scalar,UpperTriangular|SelfAdjoint> SparseSelfAdjointMatrix;\n x = b;\n SparseLDLT<SparseSelfAdjointMatrix> ldlt(m2);\n if (ldlt.succeeded())\n ldlt.solveInPlace(x);\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LDLT: default\");\n }\n\n \/\/ test LU\n {\n static int count = 0;\n SparseMatrix<Scalar> m2(rows, cols);\n DenseMatrix refMat2(rows, cols);\n\n DenseVector b = DenseVector::Random(cols);\n DenseVector refX(cols), x(cols);\n\n initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag, &zeroCoords, &nonzeroCoords);\n\n LU<DenseMatrix> refLu(refMat2);\n refLu.solve(b, &refX);\n #if defined(EIGEN_SUPERLU_SUPPORT) || defined(EIGEN_UMFPACK_SUPPORT)\n Scalar refDet = refLu.determinant();\n #endif\n x.setZero();\n \/\/ \/\/ SparseLU<SparseMatrix<Scalar> > (m2).solve(b,&x);\n \/\/ \/\/ VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: default\");\n #ifdef EIGEN_SUPERLU_SUPPORT\n {\n x.setZero();\n SparseLU<SparseMatrix<Scalar>,SuperLU> slu(m2);\n if (slu.succeeded())\n {\n if (slu.solve(b,&x)) {\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: SuperLU\");\n }\n \/\/ std::cerr << refDet << \" == \" << slu.determinant() << \"\\n\";\n if (slu.solve(b, &x, SvTranspose)) {\n VERIFY(b.isApprox(m2.transpose() * x, test_precision<Scalar>()));\n }\n\n if (slu.solve(b, &x, SvAdjoint)) {\n\/\/ VERIFY(b.isApprox(m2.adjoint() * x, test_precision<Scalar>()));\n }\n\n if (count==0) {\n VERIFY_IS_APPROX(refDet,slu.determinant()); \/\/ FIXME det is not very stable for complex\n }\n }\n }\n #endif\n #ifdef EIGEN_UMFPACK_SUPPORT\n {\n \/\/ check solve\n x.setZero();\n SparseLU<SparseMatrix<Scalar>,UmfPack> slu(m2);\n if (slu.succeeded()) {\n if (slu.solve(b,&x)) {\n if (count==0) {\n VERIFY(refX.isApprox(x,test_precision<Scalar>()) && \"LU: umfpack\"); \/\/ FIXME solve is not very stable for complex\n }\n }\n VERIFY_IS_APPROX(refDet,slu.determinant());\n \/\/ TODO check the extracted data\n \/\/std::cerr << slu.matrixL() << \"\\n\";\n }\n }\n #endif\n count++;\n }\n\n}\n\nvoid test_sparse_solvers()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( sparse_solvers<double>(8, 8) );\n CALL_SUBTEST( sparse_solvers<std::complex<double> >(16, 16) );\n CALL_SUBTEST( sparse_solvers<double>(101, 101) );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"common_defines.hpp\"\n\n#ifdef new\n#undef new\n#endif\n\n#include <functional>\nusing std::greater;\nusing std::less;\nusing std::greater;\nusing std::equal_to;\n\n#ifdef DEBUG_NEW\n#define new DEBUG_NEW\n#endif\n<commit_msg>Remove duplicating 'using' entry.<commit_after>#pragma once\n#include \"common_defines.hpp\"\n\n#ifdef new\n#undef new\n#endif\n\n#include <functional>\n\nusing std::less;\nusing std::greater;\nusing std::equal_to;\n\n#ifdef DEBUG_NEW\n#define new DEBUG_NEW\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <gtest\/gtest.h>\n#include <thread>\n#include <chrono>\n#include <msgrpc\/thrift_struct\/thrift_codec.h>\n\nusing namespace std;\nusing namespace std::chrono;\n\n#include \"demo\/demo_api_declare.h\"\n\n#if 0\n #define ___methods_of_interface___IBuzzMath(_, ...) \\\n _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\\\n _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__)\n\n ___as_interface(IBuzzMath, __with_interface_id(1))\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace msgrpc {\n template <typename T> struct Ret {};\n\n typedef unsigned short msg_id_t;\n typedef unsigned short service_id_t; \/\/TODO: how to deal with different service id types\n\n struct MsgChannel {\n virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0;\n };\n\n struct Config {\n void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) {\n instance().msg_channel_ = msg_channel;\n request_msg_id_ = request_msg_id;\n response_msg_id_ = response_msg_id;\n }\n\n static inline Config& instance() {\n static thread_local Config instance;\n return instance;\n }\n\n MsgChannel* msg_channel_;\n msg_id_t request_msg_id_;\n msg_id_t response_msg_id_;\n };\n}\n\nnamespace msgrpc {\n \/*TODO: using static_assert to assure name length of interface and method*\/\n const size_t k_max_interface_name_len = 40;\n const size_t k_max_method_name_len = 40;\n\n \/*TODO: consider make msgHeader encoded through thrift*\/\n struct MsgHeader {\n unsigned char msgrpc_version_;\n unsigned char method_index_in_interface_;\n unsigned short interface_index_in_service_;\n };\n\n struct Request : MsgHeader {\n };\n\n struct RpcInvokeHandler {\n void handleInvoke(const MsgHeader& msg_header) {\n }\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"test_util\/UdpChannel.h\"\nnamespace demo {\n const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101;\n const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102;\n\n struct UdpMsgChannel : msgrpc::MsgChannel {\n virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const {\n size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len;\n char* mem = (char*)malloc(msg_len_with_msgid);\n if (mem) {\n *(msgrpc::msg_id_t*)(mem) = msg_id;\n memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len);\n cout << \"send msg len: \" << msg_len_with_msgid << endl;\n g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id));\n free(mem);\n } else {\n cout << \"send msg failed: allocation failure.\" << endl;\n }\n return 0;\n }\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nusing namespace demo;\n\nconst msgrpc::service_id_t k_remote_service_id = 2222;\nconst msgrpc::service_id_t k_loacl_service_id = 3333;\n\nstruct IBuzzMath {\n virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0;\n virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct IBuzzMathStub : IBuzzMath {\n virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&);\n virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&);\n};\n\nmsgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) {\n uint8_t* pbuf; uint32_t len;\n \/*TODO: extract interface for encode\/decode for other protocol adoption such as protobuf*\/\n if (!ThriftEncoder::encode(req, &pbuf, &len)) {\n \/*TODO: how to do with log, maybe should extract logging interface*\/\n cout << \"encode failed.\" << endl;\n return msgrpc::Ret<ResponseBar>();\n }\n\n \/\/TODO: find k_remote_service_id by interface name \"IBuzzMath\"\n size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len;\n\n char* mem = (char*)malloc(msg_len_with_header);\n if (!mem) {\n cout << \"alloc mem failed, during sending rpc request.\" << endl;\n return msgrpc::Ret<ResponseBar>();\n }\n\n auto header = (msgrpc::MsgHeader*)mem;\n header->msgrpc_version_ = 0;\n header->interface_index_in_service_ = 1;\n header->method_index_in_interface_ = 1;\n memcpy(header + 1, (const char*)pbuf, len);\n\n cout << \"stub sending msg with length: \" << msg_len_with_header << endl;\n msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header);\n free(mem);\n return msgrpc::Ret<ResponseBar>();\n}\n\nmsgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) {\n return msgrpc::Ret<ResponseBar>();\n}\n\nvoid local_service() {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);\n\n UdpChannel channel(k_loacl_service_id,\n [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {\n if (0 == strcmp(msg, \"init\")) {\n\n IBuzzMathStub buzzMath;\n RequestFoo foo; foo.fooa = 97; foo.__set_foob(98);\n buzzMath.negative_fields(foo);\n\n } else {\n cout << \"local received msg: \" << string(msg, len) << endl;\n channel.close();\n }\n }\n );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct IBuzzMathImpl {\n bool onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); \/\/todo:remote_id\n bool do_negative_fields(const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len);\n bool do_plus1_to_fields(const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len);\n\n bool negative_fields(const RequestFoo& req, ResponseBar& rsp);\n bool plus1_to_fields(const RequestFoo& req, ResponseBar& rsp);\n\n template<typename REQ, typename RSP>\n bool invoke_templated_method(bool (IBuzzMathImpl::*method_impl)(const REQ&, RSP&), const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len);\n\n};\n\nbool IBuzzMathImpl::onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) {\n cout << (int)msg_header.msgrpc_version_ << endl;\n cout << (int)msg_header.interface_index_in_service_ << endl;\n cout << (int)msg_header.method_index_in_interface_ << endl;\n\n this->invoke_templated_method(&IBuzzMathImpl::negative_fields, msg, len, pout_buf, out_buf_len);\n return true;\n}\n\ntemplate<typename REQ, typename RSP>\nbool IBuzzMathImpl::invoke_templated_method(bool (IBuzzMathImpl::*method_impl)(const REQ&, RSP&), const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) {\n REQ req;\n if (! ThriftDecoder::decode(req, (uint8_t*)msg, len)) {\n cout << \"decode failed on remote side.\" << endl;\n return false;\n }\n\n RSP rsp;\n if (! (this->*method_impl)(req, rsp)) {\n return false;\n }\n\n if (! ThriftEncoder::encode(rsp, &pout_buf, &out_buf_len)) {\n cout << \"encode failed on remtoe side.\" << endl;\n return false;\n }\n\n return true;\n}\n\n\nbool IBuzzMathImpl::negative_fields(const RequestFoo& req, ResponseBar& rsp) {\n rsp.__set_bara(req.get_foob());\n if (req.__isset.foob) {\n rsp.__set_barb(req.fooa);\n }\n return true;\n}\n\nbool IBuzzMathImpl::plus1_to_fields(const RequestFoo& req, ResponseBar& rsp) {\n rsp.__set_bara(1 + req.fooa);\n if (req.__isset.foob) {\n rsp.__set_barb(1 + req.get_foob());\n }\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid remote_service() {\n msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);\n\n UdpChannel channel(k_remote_service_id,\n [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {\n if (0 == strcmp(msg, \"init\")) {\n return;\n }\n cout << \"remote received msg with length: \" << len << endl;\n\n \/*TODO: should first check msg_id == msgrpc_msg_request_id *\/\n if (len < sizeof(msgrpc::MsgHeader)) {\n cout << \"invalid msg: without sufficient msg header info.\" << endl;\n return;\n }\n\n auto msg_header = (msgrpc::MsgHeader*)msg;\n msg += sizeof(msgrpc::MsgHeader);\n\n \/*TODO: search interface implementation instance to handle tbis rpc request*\/\n IBuzzMathImpl buzzMath;\n uint8_t* pout_buf; uint32_t out_buf_len;\n if (buzzMath.onRpcInvoke(*msg_header, msg, len - sizeof(msgrpc::MsgHeader), pout_buf, out_buf_len)) {\n \/*TODO: send out msg with msgheader*\/\n msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pout_buf, out_buf_len);\n }\n\n channel.close();\n }\n );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) {\n demo::RequestFoo req;\n req.fooa = 1;\n req.__set_foob(2);\n\n std::thread local_thread(local_service);\n std::thread remote_thread(remote_service);\n\n local_thread.join();\n remote_thread.join();\n};\n<commit_msg>extract templated method for rpc reqeust decoding and response encoding.<commit_after>#include <iostream>\n#include <gtest\/gtest.h>\n#include <thread>\n#include <chrono>\n#include <msgrpc\/thrift_struct\/thrift_codec.h>\n\nusing namespace std;\nusing namespace std::chrono;\n\n#include \"demo\/demo_api_declare.h\"\n\n#if 0\n #define ___methods_of_interface___IBuzzMath(_, ...) \\\n _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\\\n _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__)\n\n ___as_interface(IBuzzMath, __with_interface_id(1))\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace msgrpc {\n template <typename T> struct Ret {};\n\n typedef unsigned short msg_id_t;\n typedef unsigned short service_id_t; \/\/TODO: how to deal with different service id types\n\n struct MsgChannel {\n virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0;\n };\n\n struct Config {\n void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) {\n instance().msg_channel_ = msg_channel;\n request_msg_id_ = request_msg_id;\n response_msg_id_ = response_msg_id;\n }\n\n static inline Config& instance() {\n static thread_local Config instance;\n return instance;\n }\n\n MsgChannel* msg_channel_;\n msg_id_t request_msg_id_;\n msg_id_t response_msg_id_;\n };\n}\n\nnamespace msgrpc {\n \/*TODO: using static_assert to assure name length of interface and method*\/\n const size_t k_max_interface_name_len = 40;\n const size_t k_max_method_name_len = 40;\n\n \/*TODO: consider make msgHeader encoded through thrift*\/\n struct MsgHeader {\n unsigned char msgrpc_version_;\n unsigned char method_index_in_interface_;\n unsigned short interface_index_in_service_;\n \/*TODO: call sequence number*\/\n };\n\n \/*TODO: define response header*\/\n \/*response code: success, failed, not_implemented*\/\n\n struct Request : MsgHeader {\n };\n\n struct RpcInvokeHandler {\n void handleInvoke(const MsgHeader& msg_header) {\n }\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"test_util\/UdpChannel.h\"\nnamespace demo {\n const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101;\n const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102;\n\n struct UdpMsgChannel : msgrpc::MsgChannel {\n virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const {\n size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len;\n char* mem = (char*)malloc(msg_len_with_msgid);\n if (mem) {\n *(msgrpc::msg_id_t*)(mem) = msg_id;\n memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len);\n cout << \"send msg len: \" << msg_len_with_msgid << endl;\n g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id));\n free(mem);\n } else {\n cout << \"send msg failed: allocation failure.\" << endl;\n }\n return 0;\n }\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nusing namespace demo;\n\nconst msgrpc::service_id_t k_remote_service_id = 2222;\nconst msgrpc::service_id_t k_loacl_service_id = 3333;\n\nstruct IBuzzMath {\n virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0;\n virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct IBuzzMathStub : IBuzzMath {\n virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&);\n virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&);\n};\n\nmsgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) {\n uint8_t* pbuf; uint32_t len;\n \/*TODO: extract interface for encode\/decode for other protocol adoption such as protobuf*\/\n if (!ThriftEncoder::encode(req, &pbuf, &len)) {\n \/*TODO: how to do with log, maybe should extract logging interface*\/\n cout << \"encode failed.\" << endl;\n return msgrpc::Ret<ResponseBar>();\n }\n\n \/\/TODO: find k_remote_service_id by interface name \"IBuzzMath\"\n size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len;\n\n char* mem = (char*)malloc(msg_len_with_header);\n if (!mem) {\n cout << \"alloc mem failed, during sending rpc request.\" << endl;\n return msgrpc::Ret<ResponseBar>();\n }\n\n auto header = (msgrpc::MsgHeader*)mem;\n header->msgrpc_version_ = 0;\n header->interface_index_in_service_ = 1;\n header->method_index_in_interface_ = 1;\n memcpy(header + 1, (const char*)pbuf, len);\n\n cout << \"stub sending msg with length: \" << msg_len_with_header << endl;\n msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header);\n free(mem);\n return msgrpc::Ret<ResponseBar>();\n}\n\nmsgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) {\n return msgrpc::Ret<ResponseBar>();\n}\n\nvoid local_service() {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);\n\n UdpChannel channel(k_loacl_service_id,\n [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {\n if (0 == strcmp(msg, \"init\")) {\n\n IBuzzMathStub buzzMath;\n RequestFoo foo; foo.fooa = 97; foo.__set_foob(98);\n buzzMath.negative_fields(foo);\n\n } else {\n cout << \"local received msg: \" << string(msg, len) << endl;\n channel.close();\n }\n }\n );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace msgrpc {\n\n template<typename T>\n struct InterfaceImplBase {\n template<typename REQ, typename RSP>\n bool invoke_templated_method( bool (T::*method_impl)(const REQ &, RSP &)\n , const char *msg, size_t len\n , uint8_t *&pout_buf, uint32_t &out_buf_len) {\n REQ req;\n if (!ThriftDecoder::decode(req, (uint8_t *) msg, len)) {\n cout << \"decode failed on remote side.\" << endl;\n return false;\n }\n\n RSP rsp;\n if (!((T*)this->*method_impl)(req, rsp)) {\n return false;\n }\n\n if (!ThriftEncoder::encode(rsp, &pout_buf, &out_buf_len)) {\n cout << \"encode failed on remtoe side.\" << endl;\n return false;\n }\n\n return true;\n }\n };\n}\n\nstruct IBuzzMathImpl : msgrpc::InterfaceImplBase<IBuzzMathImpl> {\n bool onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); \/\/todo:remote_id\n \/\/TODO: try to unify with stub's signature\n bool negative_fields(const RequestFoo& req, ResponseBar& rsp);\n bool plus1_to_fields(const RequestFoo& req, ResponseBar& rsp);\n};\n\nbool IBuzzMathImpl::onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) {\n cout << (int)msg_header.msgrpc_version_ << endl;\n cout << (int)msg_header.interface_index_in_service_ << endl;\n cout << (int)msg_header.method_index_in_interface_ << endl;\n\n if (msg_header.method_index_in_interface_ == 1) {\n this->invoke_templated_method(&IBuzzMathImpl::negative_fields, msg, len, pout_buf, out_buf_len);\n } else\n\n if (msg_header.method_index_in_interface_ == 2) {\n this->invoke_templated_method(&IBuzzMathImpl::plus1_to_fields, msg, len, pout_buf, out_buf_len);\n } else\n\n {\n \/*TODO: return method not implemented code*\/\n return false;\n }\n\n return true;\n}\n\nbool IBuzzMathImpl::negative_fields(const RequestFoo& req, ResponseBar& rsp) {\n rsp.__set_bara(req.get_foob());\n if (req.__isset.foob) {\n rsp.__set_barb(req.fooa);\n }\n return true;\n}\n\nbool IBuzzMathImpl::plus1_to_fields(const RequestFoo& req, ResponseBar& rsp) {\n rsp.__set_bara(1 + req.fooa);\n if (req.__isset.foob) {\n rsp.__set_barb(1 + req.get_foob());\n }\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid remote_service() {\n msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id);\n\n UdpChannel channel(k_remote_service_id,\n [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) {\n if (0 == strcmp(msg, \"init\")) {\n return;\n }\n cout << \"remote received msg with length: \" << len << endl;\n\n \/*TODO: should first check msg_id == msgrpc_msg_request_id *\/\n if (len < sizeof(msgrpc::MsgHeader)) {\n cout << \"invalid msg: without sufficient msg header info.\" << endl;\n return;\n }\n\n auto msg_header = (msgrpc::MsgHeader*)msg;\n msg += sizeof(msgrpc::MsgHeader);\n\n \/*TODO: search interface implementation instance to handle tbis rpc request*\/\n IBuzzMathImpl buzzMath;\n uint8_t* pout_buf; uint32_t out_buf_len;\n if (buzzMath.onRpcInvoke(*msg_header, msg, len - sizeof(msgrpc::MsgHeader), pout_buf, out_buf_len)) {\n \/*TODO: send out msg with msgheader*\/\n msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pout_buf, out_buf_len);\n }\n\n channel.close();\n }\n );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) {\n demo::RequestFoo req;\n req.fooa = 1;\n req.__set_foob(2);\n\n std::thread local_thread(local_service);\n std::thread remote_thread(remote_service);\n\n local_thread.join();\n remote_thread.join();\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include <google\/protobuf\/text_format.h>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/strip.h\"\n#include \"src\/config.pb.h\"\n#include \"src\/execute_linter.h\"\n\nABSL_FLAG(std::string, config, \"\",\n \"A prototxt file having configuration options.\");\n\nABSL_FLAG(bool, quick, false,\n \"This flag will read from standart input. It will read one\"\n \"statement and continue until reading semicolon ';'\");\n\nnamespace zetasql::linter {\nnamespace {\n\nstd::string ReadFile(const char* filename) {\n std::ifstream file(filename);\n std::string str = \"\";\n for (std::string line; std::getline(file, line);) {\n str += line + \"\\n\";\n }\n return str;\n}\n\nConfig ReadFromConfigFile(const char* filename) {\n Config config;\n std::string str = ReadFile(filename);\n if (!google::protobuf::TextFormat::ParseFromString(str, &config)) {\n std::cerr << \"Configuration file couldn't be parsed.\" << std::endl;\n config = Config();\n }\n return config;\n}\n\nbool HasValidExtension(char* filename_char) {\n std::string filename(filename_char);\n std::vector<std::string> supported_extensions{\".sql\", \".sqlm\", \".sqlp\",\n \".sqlt\", \".gsql\"};\n\n std::string extension_str = absl::StrJoin(supported_extensions.begin(),\n supported_extensions.end(), \", \");\n\n bool ok = false;\n std::size_t last_dot = filename.find_last_of(\".\");\n std::string extension = filename.substr(last_dot);\n\n for (std::string supported_extension : supported_extensions)\n if (supported_extension == extension) ok = true;\n if (!ok) {\n std::cerr << \"Ignoring \" << filename << \"; not have a valid extension (\"\n << extension_str << \")\" << std::endl;\n return 0;\n }\n return 1;\n}\n\nvoid quick_run(Config config) {\n std::string str = \"\";\n for (std::string line; std::getline(std::cin, line);) {\n bool end = false;\n for (char c : line) {\n str += c;\n if (c == ';') {\n end = true;\n break;\n }\n }\n str += \"\\n\";\n }\n zetasql::linter::LinterResult result =\n zetasql::linter::RunChecks(absl::string_view(str), config, \"\");\n\n result.PrintResult();\n}\n\nvoid run(std::vector<char*> sql_files, Config config) {\n bool runner = true;\n for (char* filename : sql_files) {\n \/\/ The first argument is '.\/runner'.\n if (runner || !HasValidExtension(filename)) {\n runner = false;\n continue;\n }\n std::string str = ReadFile(filename);\n LinterResult result = RunChecks(absl::string_view(str), config, filename);\n\n result.PrintResult();\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace zetasql::linter\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n std::cerr << \"Usage: .\/runner --config=<config_file> <file_names>\\n\"\n << std::endl;\n return 1;\n }\n\n std::vector<char*> sql_files = absl::ParseCommandLine(argc, argv);\n\n std::string config_file = absl::GetFlag(FLAGS_config);\n bool quick = absl::GetFlag(FLAGS_quick);\n\n zetasql::linter::Config config =\n zetasql::linter::ReadFromConfigFile(config_file.c_str());\n\n if (quick)\n zetasql::linter::quick_run(config);\n else\n zetasql::linter::run(sql_files, config);\n\n return 0;\n}\n<commit_msg>don't use char *<commit_after>\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include <google\/protobuf\/text_format.h>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/strip.h\"\n#include \"src\/config.pb.h\"\n#include \"src\/execute_linter.h\"\n\nABSL_FLAG(std::string, config, \"\",\n \"A prototxt file having configuration options.\");\n\nABSL_FLAG(bool, quick, false,\n \"This flag will read from standart input. It will read one\"\n \"statement and continue until reading semicolon ';'\");\n\nnamespace zetasql::linter {\nnamespace {\n\nstd::string ReadFile(std::string filename) {\n std::ifstream file(filename.c_str());\n std::string str = \"\";\n for (std::string line; std::getline(file, line);) {\n str += line + \"\\n\";\n }\n return str;\n}\n\nConfig ReadFromConfigFile(std::string filename) {\n Config config;\n std::string str = ReadFile(filename);\n if (!google::protobuf::TextFormat::ParseFromString(str, &config)) {\n std::cerr << \"Configuration file couldn't be parsed.\" << std::endl;\n config = Config();\n }\n return config;\n}\n\nbool HasValidExtension(std::string filename) {\n std::vector<std::string> supported_extensions{\".sql\", \".sqlm\", \".sqlp\",\n \".sqlt\", \".gsql\"};\n\n std::string extension_str = absl::StrJoin(supported_extensions.begin(),\n supported_extensions.end(), \", \");\n\n bool ok = false;\n std::size_t last_dot = filename.find_last_of(\".\");\n std::string extension = filename.substr(last_dot);\n\n for (std::string supported_extension : supported_extensions)\n if (supported_extension == extension) ok = true;\n if (!ok) {\n std::cerr << \"Ignoring \" << filename << \"; not have a valid extension (\"\n << extension_str << \")\" << std::endl;\n return 0;\n }\n return 1;\n}\n\nvoid quick_run(Config config) {\n std::string str = \"\";\n for (std::string line; std::getline(std::cin, line);) {\n bool end = false;\n for (char c : line) {\n str += c;\n if (c == ';') {\n end = true;\n break;\n }\n }\n str += \"\\n\";\n }\n zetasql::linter::LinterResult result =\n zetasql::linter::RunChecks(absl::string_view(str), config, \"\");\n\n result.PrintResult();\n}\n\nvoid run(std::vector<std::string> sql_files, Config config) {\n bool runner = true;\n for (std::string filename : sql_files) {\n \/\/ The first argument is '.\/runner'.\n if (runner || !HasValidExtension(filename)) {\n runner = false;\n continue;\n }\n std::string str = ReadFile(filename);\n LinterResult result = RunChecks(absl::string_view(str), config, filename);\n\n result.PrintResult();\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace zetasql::linter\n\nint main(int argc, char* argv[]) {\n if (argc < 2) {\n std::cerr << \"Usage: .\/runner --config=<config_file> <file_names>\\n\"\n << std::endl;\n return 1;\n }\n\n std::vector<std::string> sql_files;\n for (char* file : absl::ParseCommandLine(argc, argv))\n sql_files.push_back(std::string(file));\n\n std::string config_file = absl::GetFlag(FLAGS_config);\n bool quick = absl::GetFlag(FLAGS_quick);\n\n zetasql::linter::Config config =\n zetasql::linter::ReadFromConfigFile(config_file.c_str());\n\n if (quick)\n zetasql::linter::quick_run(config);\n else\n zetasql::linter::run(sql_files, config);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \"libtorrent\/socket_io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\n#include <string>\n\nusing namespace libtorrent;\nusing namespace libtorrent::detail;\n\nint test_main()\n{\n\t\/\/ test address_to_bytes\n\tTEST_EQUAL(address_to_bytes(address_v4::from_string(\"10.11.12.13\")), \"\\x0a\\x0b\\x0c\\x0d\");\n\tTEST_EQUAL(address_to_bytes(address_v4::from_string(\"16.5.127.1\")), \"\\x10\\x05\\x7f\\x01\");\n\n\t\/\/ test endpoint_to_bytes\n\tTEST_EQUAL(endpoint_to_bytes(udp::endpoint(address_v4::from_string(\"10.11.12.13\"), 8080)), \"\\x0a\\x0b\\x0c\\x0d\\x1f\\x90\");\n\tTEST_EQUAL(endpoint_to_bytes(udp::endpoint(address_v4::from_string(\"16.5.127.1\"), 12345)), \"\\x10\\x05\\x7f\\x01\\x30\\x39\");\n\n\tstd::string buf;\n\tstd::back_insert_iterator<std::string> out1(buf);\n\twrite_address(address_v4::from_string(\"16.5.128.1\"), out1);\n\tTEST_EQUAL(buf, \"\\x10\\x05\\x80\\x01\");\n\tstd::string::iterator in = buf.begin();\n\taddress addr4 = read_v4_address(in);\n\tTEST_EQUAL(addr4, address_v4::from_string(\"16.5.128.1\"));\n\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out2(buf);\n\twrite_endpoint(udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337), out2);\n\tTEST_EQUAL(buf, \"\\x10\\x05\\x80\\x01\\x05\\x39\");\n\tin = buf.begin();\n\tudp::endpoint ep4 = read_v4_endpoint<udp::endpoint>(in);\n\tTEST_EQUAL(ep4, udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\n#if TORRENT_USE_IPV6\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out3(buf);\n\twrite_address(address_v6::from_string(\"1000::ffff\"), out3);\n\tTEST_CHECK(std::equal(buf.begin(), buf.end(), \"\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\"));\n\tin = buf.begin();\n\taddress addr6 = read_v6_address(in); \n\tTEST_EQUAL(addr6, address_v6::from_string(\"1000::ffff\"));\n\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out4(buf);\n\twrite_endpoint(udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337), out4);\n\tTEST_CHECK(std::equal(buf.begin(), buf.end(), \"\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\\x05\\x39\"));\n\tTEST_EQUAL(buf.size(), 18);\n\tin = buf.begin();\n\tudp::endpoint ep6 = read_v6_endpoint<udp::endpoint>(in); \n\tTEST_EQUAL(ep6, udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n#endif\n\n\tchar const eplist[] = \"l6:\\x10\\x05\\x80\\x01\\x05\\x39\" \"18:\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\\x05\\x39\" \"e\";\n\tlazy_entry e;\n\terror_code ec;\n\tlazy_bdecode(eplist, eplist + sizeof(eplist)-1, e, ec);\n\tTEST_CHECK(!ec);\n\tstd::vector<udp::endpoint> list;\n\tread_endpoint_list<udp::endpoint>(&e, list);\n\n\tTEST_EQUAL(list.size(), 2);\n\tTEST_EQUAL(list[0], udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\tTEST_EQUAL(list[1], udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n\n\tentry e2 = bdecode(eplist, eplist + sizeof(eplist)-1);\n\tlist.clear();\n\tread_endpoint_list<udp::endpoint>(&e2, list);\n\n\tTEST_EQUAL(list.size(), 2);\n\tTEST_EQUAL(list[0], udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\tTEST_EQUAL(list[1], udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n\n\treturn 0;\n}\n\n<commit_msg>fix non-ipv6 build of unit tests<commit_after>\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \"libtorrent\/socket_io.hpp\"\n#include \"libtorrent\/socket.hpp\"\n\n#include <string>\n\nusing namespace libtorrent;\nusing namespace libtorrent::detail;\n\nint test_main()\n{\n\t\/\/ test address_to_bytes\n\tTEST_EQUAL(address_to_bytes(address_v4::from_string(\"10.11.12.13\")), \"\\x0a\\x0b\\x0c\\x0d\");\n\tTEST_EQUAL(address_to_bytes(address_v4::from_string(\"16.5.127.1\")), \"\\x10\\x05\\x7f\\x01\");\n\n\t\/\/ test endpoint_to_bytes\n\tTEST_EQUAL(endpoint_to_bytes(udp::endpoint(address_v4::from_string(\"10.11.12.13\"), 8080)), \"\\x0a\\x0b\\x0c\\x0d\\x1f\\x90\");\n\tTEST_EQUAL(endpoint_to_bytes(udp::endpoint(address_v4::from_string(\"16.5.127.1\"), 12345)), \"\\x10\\x05\\x7f\\x01\\x30\\x39\");\n\n\tstd::string buf;\n\tstd::back_insert_iterator<std::string> out1(buf);\n\twrite_address(address_v4::from_string(\"16.5.128.1\"), out1);\n\tTEST_EQUAL(buf, \"\\x10\\x05\\x80\\x01\");\n\tstd::string::iterator in = buf.begin();\n\taddress addr4 = read_v4_address(in);\n\tTEST_EQUAL(addr4, address_v4::from_string(\"16.5.128.1\"));\n\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out2(buf);\n\twrite_endpoint(udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337), out2);\n\tTEST_EQUAL(buf, \"\\x10\\x05\\x80\\x01\\x05\\x39\");\n\tin = buf.begin();\n\tudp::endpoint ep4 = read_v4_endpoint<udp::endpoint>(in);\n\tTEST_EQUAL(ep4, udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\n#if TORRENT_USE_IPV6\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out3(buf);\n\twrite_address(address_v6::from_string(\"1000::ffff\"), out3);\n\tTEST_CHECK(std::equal(buf.begin(), buf.end(), \"\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\"));\n\tin = buf.begin();\n\taddress addr6 = read_v6_address(in); \n\tTEST_EQUAL(addr6, address_v6::from_string(\"1000::ffff\"));\n\n\tbuf.clear();\n\tstd::back_insert_iterator<std::string> out4(buf);\n\twrite_endpoint(udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337), out4);\n\tTEST_CHECK(std::equal(buf.begin(), buf.end(), \"\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\\x05\\x39\"));\n\tTEST_EQUAL(buf.size(), 18);\n\tin = buf.begin();\n\tudp::endpoint ep6 = read_v6_endpoint<udp::endpoint>(in); \n\tTEST_EQUAL(ep6, udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n#endif\n\n\tchar const eplist[] = \"l6:\\x10\\x05\\x80\\x01\\x05\\x39\" \"18:\\x10\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\\x05\\x39\" \"e\";\n\tlazy_entry e;\n\terror_code ec;\n\tlazy_bdecode(eplist, eplist + sizeof(eplist)-1, e, ec);\n\tTEST_CHECK(!ec);\n\tstd::vector<udp::endpoint> list;\n\tread_endpoint_list<udp::endpoint>(&e, list);\n\n#if TORRENT_USE_IPV6\n\tTEST_EQUAL(list.size(), 2);\n\tTEST_EQUAL(list[1], udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n#else\n\tTEST_EQUAL(list.size(), 1);\n#endif\n\tTEST_EQUAL(list[0], udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\n\tentry e2 = bdecode(eplist, eplist + sizeof(eplist)-1);\n\tlist.clear();\n\tread_endpoint_list<udp::endpoint>(&e2, list);\n\n#if TORRENT_USE_IPV6\n\tTEST_EQUAL(list.size(), 2);\n\tTEST_EQUAL(list[1], udp::endpoint(address_v6::from_string(\"1000::ffff\"), 1337));\n#else\n\tTEST_EQUAL(list.size(), 1);\n#endif\n\tTEST_EQUAL(list[0], udp::endpoint(address_v4::from_string(\"16.5.128.1\"), 1337));\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \".\/scene.h\"\n#include <Eigen\/Core>\n#include <Eigen\/Geometry>\n#include <string>\n#include <vector>\n#include \".\/graphics\/gl.h\"\n#include \".\/input\/invoke_manager.h\"\n#include \".\/graphics\/render_data.h\"\n#include \".\/graphics\/managers.h\"\n#include \".\/graphics\/volume_manager.h\"\n#include \".\/graphics\/shader_program.h\"\n#include \".\/camera_controllers.h\"\n#include \".\/nodes.h\"\n#include \".\/labelling\/labeller_frame_data.h\"\n#include \".\/label_node.h\"\n#include \".\/eigen_qdebug.h\"\n#include \".\/utils\/path_helper.h\"\n#include \".\/placement\/to_gray.h\"\n#include \".\/placement\/distance_transform.h\"\n#include \".\/placement\/occupancy.h\"\n#include \".\/placement\/apollonius.h\"\n#include \".\/texture_mapper_manager.h\"\n#include \".\/constraint_buffer.h\"\n\nScene::Scene(std::shared_ptr<InvokeManager> invokeManager,\n std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,\n std::shared_ptr<Forces::Labeller> forcesLabeller,\n std::shared_ptr<Placement::Labeller> placementLabeller,\n std::shared_ptr<TextureMapperManager> textureMapperManager)\n\n : nodes(nodes), labels(labels), forcesLabeller(forcesLabeller),\n placementLabeller(placementLabeller), frustumOptimizer(nodes),\n textureMapperManager(textureMapperManager)\n{\n cameraControllers =\n std::make_shared<CameraControllers>(invokeManager, camera);\n\n fbo = std::make_shared<Graphics::FrameBufferObject>();\n constraintBuffer = std::make_shared<ConstraintBuffer>();\n managers = std::make_shared<Graphics::Managers>();\n}\n\nScene::~Scene()\n{\n nodes->clear();\n qInfo() << \"Destructor of Scene\"\n << \"Remaining managers instances\" << managers.use_count();\n}\n\nvoid Scene::initialize()\n{\n glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));\n\n quad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/textureForRenderBuffer.frag\");\n positionQuad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/positionRenderTarget.frag\");\n distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/distanceTransform.frag\");\n\n fbo->initialize(gl, width, height);\n constraintBuffer->initialize(gl, width, height);\n haBuffer =\n std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));\n managers->getShaderManager()->initialize(gl, haBuffer);\n\n managers->getObjectManager()->initialize(gl, 128, 10000000);\n haBuffer->initialize(gl, managers);\n quad->initialize(gl, managers);\n positionQuad->initialize(gl, managers);\n distanceTransformQuad->initialize(gl, managers);\n\n managers->getTextureManager()->initialize(gl, true, 8);\n\n textureMapperManager->resize(width, height);\n textureMapperManager->initialize(gl, fbo);\n\n placementLabeller->initialize(\n textureMapperManager->getOccupancyTextureMapper(),\n textureMapperManager->getDistanceTransformTextureMapper(),\n textureMapperManager->getApolloniusTextureMapper());\n}\n\nvoid Scene::cleanup()\n{\n placementLabeller->cleanup();\n textureMapperManager->cleanup();\n}\n\nvoid Scene::update(double frameTime, QSet<Qt::Key> keysPressed)\n{\n this->frameTime = frameTime;\n cameraControllers->update(frameTime);\n\n frustumOptimizer.update(camera.getViewMatrix());\n camera.updateNearAndFarPlanes(frustumOptimizer.getNear(),\n frustumOptimizer.getFar());\n haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),\n frustumOptimizer.getFar());\n\n \/*\n auto newPositions = forcesLabeller->update(LabellerFrameData(\n frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));\n *\/\n auto newPositions = placementLabeller->getLastPlacementResult();\n for (auto &labelNode : nodes->getLabelNodes())\n {\n labelNode->labelPosition = newPositions[labelNode->label.id];\n }\n}\n\nvoid Scene::render()\n{\n if (shouldResize)\n {\n camera.resize(width, height);\n fbo->resize(width, height);\n shouldResize = false;\n }\n glAssert(gl->glViewport(0, 0, width, height));\n glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n\n fbo->bind();\n glAssert(gl->glViewport(0, 0, width, height));\n glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n\n RenderData renderData;\n renderData.projectionMatrix = camera.getProjectionMatrix();\n renderData.viewMatrix = camera.getViewMatrix();\n renderData.cameraPosition = camera.getPosition();\n renderData.modelMatrix = Eigen::Matrix4f::Identity();\n renderData.windowPixelSize = Eigen::Vector2f(width, height);\n\n haBuffer->clearAndPrepare(managers);\n\n nodes->render(gl, managers, renderData);\n\n managers->getObjectManager()->render(renderData);\n\n haBuffer->render(managers, renderData);\n\n \/\/ doPick();\n\n fbo->unbind();\n\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n renderScreenQuad();\n\n textureMapperManager->update();\n\n renderDebuggingViews(renderData);\n\n glAssert(gl->glEnable(GL_DEPTH_TEST));\n\n nodes->renderLabels(gl, managers, renderData);\n}\n\nvoid Scene::renderDebuggingViews(const RenderData &renderData)\n{\n fbo->bindDepthTexture(GL_TEXTURE0);\n auto transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n\n placementLabeller->update(LabellerFrameData(\n frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));\n\n textureMapperManager->bindOccupancyTexture();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n textureMapperManager->bindDistanceTransform();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(distanceTransformQuad, transformation.matrix());\n\n textureMapperManager->bindApollonius();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n constraintBuffer->bindTexture(GL_TEXTURE0);\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n}\n\nvoid Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,\n Eigen::Matrix4f modelMatrix)\n{\n RenderData renderData;\n renderData.projectionMatrix = Eigen::Matrix4f::Identity();\n renderData.viewMatrix = Eigen::Matrix4f::Identity();\n renderData.modelMatrix = modelMatrix;\n\n quad->getShaderProgram()->bind();\n quad->getShaderProgram()->setUniform(\"textureSampler\", 0);\n quad->renderImmediately(gl, managers, renderData);\n}\n\nvoid Scene::renderScreenQuad()\n{\n fbo->bindColorTexture(GL_TEXTURE0);\n\n renderQuad(quad, Eigen::Matrix4f::Identity());\n}\n\nvoid Scene::resize(int width, int height)\n{\n this->width = width;\n this->height = height;\n\n placementLabeller->resize(width, height);\n\n shouldResize = true;\n\n forcesLabeller->resize(width, height);\n}\n\nvoid Scene::pick(int id, Eigen::Vector2f position)\n{\n pickingPosition = position;\n performPicking = true;\n pickingLabelId = id;\n}\n\nvoid Scene::doPick()\n{\n if (!performPicking)\n return;\n\n float depth = -2.0f;\n\n fbo->bindDepthTexture(GL_TEXTURE0);\n\n glAssert(gl->glReadPixels(pickingPosition.x(),\n height - pickingPosition.y() - 1, 1, 1,\n GL_DEPTH_COMPONENT, GL_FLOAT, &depth));\n Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f \/ width - 1.0f,\n pickingPosition.y() * -2.0f \/ height + 1.0f,\n depth * 2.0f - 1.0f, 1.0f);\n\n Eigen::Matrix4f viewProjection =\n camera.getProjectionMatrix() * camera.getViewMatrix();\n Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC;\n positionWorld = positionWorld \/ positionWorld.w();\n\n qWarning() << \"picked:\" << positionWorld;\n\n performPicking = false;\n auto label = labels->getById(pickingLabelId);\n label.anchorPosition = toVector3f(positionWorld);\n\n labels->update(label);\n}\n\n<commit_msg>Call PlacementLabeller::update outside of renderDebuggingViews.<commit_after>#include \".\/scene.h\"\n#include <Eigen\/Core>\n#include <Eigen\/Geometry>\n#include <string>\n#include <vector>\n#include \".\/graphics\/gl.h\"\n#include \".\/input\/invoke_manager.h\"\n#include \".\/graphics\/render_data.h\"\n#include \".\/graphics\/managers.h\"\n#include \".\/graphics\/volume_manager.h\"\n#include \".\/graphics\/shader_program.h\"\n#include \".\/camera_controllers.h\"\n#include \".\/nodes.h\"\n#include \".\/labelling\/labeller_frame_data.h\"\n#include \".\/label_node.h\"\n#include \".\/eigen_qdebug.h\"\n#include \".\/utils\/path_helper.h\"\n#include \".\/placement\/to_gray.h\"\n#include \".\/placement\/distance_transform.h\"\n#include \".\/placement\/occupancy.h\"\n#include \".\/placement\/apollonius.h\"\n#include \".\/texture_mapper_manager.h\"\n#include \".\/constraint_buffer.h\"\n\nScene::Scene(std::shared_ptr<InvokeManager> invokeManager,\n std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,\n std::shared_ptr<Forces::Labeller> forcesLabeller,\n std::shared_ptr<Placement::Labeller> placementLabeller,\n std::shared_ptr<TextureMapperManager> textureMapperManager)\n\n : nodes(nodes), labels(labels), forcesLabeller(forcesLabeller),\n placementLabeller(placementLabeller), frustumOptimizer(nodes),\n textureMapperManager(textureMapperManager)\n{\n cameraControllers =\n std::make_shared<CameraControllers>(invokeManager, camera);\n\n fbo = std::make_shared<Graphics::FrameBufferObject>();\n constraintBuffer = std::make_shared<ConstraintBuffer>();\n managers = std::make_shared<Graphics::Managers>();\n}\n\nScene::~Scene()\n{\n nodes->clear();\n qInfo() << \"Destructor of Scene\"\n << \"Remaining managers instances\" << managers.use_count();\n}\n\nvoid Scene::initialize()\n{\n glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));\n\n quad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/textureForRenderBuffer.frag\");\n positionQuad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/positionRenderTarget.frag\");\n distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(\n \":shader\/pass.vert\", \":shader\/distanceTransform.frag\");\n\n fbo->initialize(gl, width, height);\n constraintBuffer->initialize(gl, width, height);\n haBuffer =\n std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));\n managers->getShaderManager()->initialize(gl, haBuffer);\n\n managers->getObjectManager()->initialize(gl, 128, 10000000);\n haBuffer->initialize(gl, managers);\n quad->initialize(gl, managers);\n positionQuad->initialize(gl, managers);\n distanceTransformQuad->initialize(gl, managers);\n\n managers->getTextureManager()->initialize(gl, true, 8);\n\n textureMapperManager->resize(width, height);\n textureMapperManager->initialize(gl, fbo);\n\n placementLabeller->initialize(\n textureMapperManager->getOccupancyTextureMapper(),\n textureMapperManager->getDistanceTransformTextureMapper(),\n textureMapperManager->getApolloniusTextureMapper());\n}\n\nvoid Scene::cleanup()\n{\n placementLabeller->cleanup();\n textureMapperManager->cleanup();\n}\n\nvoid Scene::update(double frameTime, QSet<Qt::Key> keysPressed)\n{\n this->frameTime = frameTime;\n cameraControllers->update(frameTime);\n\n frustumOptimizer.update(camera.getViewMatrix());\n camera.updateNearAndFarPlanes(frustumOptimizer.getNear(),\n frustumOptimizer.getFar());\n haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),\n frustumOptimizer.getFar());\n\n \/*\n auto newPositions = forcesLabeller->update(LabellerFrameData(\n frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));\n *\/\n auto newPositions = placementLabeller->getLastPlacementResult();\n for (auto &labelNode : nodes->getLabelNodes())\n {\n labelNode->labelPosition = newPositions[labelNode->label.id];\n }\n}\n\nvoid Scene::render()\n{\n if (shouldResize)\n {\n camera.resize(width, height);\n fbo->resize(width, height);\n shouldResize = false;\n }\n glAssert(gl->glViewport(0, 0, width, height));\n glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n\n fbo->bind();\n glAssert(gl->glViewport(0, 0, width, height));\n glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n\n RenderData renderData;\n renderData.projectionMatrix = camera.getProjectionMatrix();\n renderData.viewMatrix = camera.getViewMatrix();\n renderData.cameraPosition = camera.getPosition();\n renderData.modelMatrix = Eigen::Matrix4f::Identity();\n renderData.windowPixelSize = Eigen::Vector2f(width, height);\n\n haBuffer->clearAndPrepare(managers);\n\n nodes->render(gl, managers, renderData);\n\n managers->getObjectManager()->render(renderData);\n\n haBuffer->render(managers, renderData);\n\n \/\/ doPick();\n\n fbo->unbind();\n\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n renderScreenQuad();\n\n textureMapperManager->update();\n\n placementLabeller->update(LabellerFrameData(\n frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));\n\n renderDebuggingViews(renderData);\n\n glAssert(gl->glEnable(GL_DEPTH_TEST));\n\n nodes->renderLabels(gl, managers, renderData);\n}\n\nvoid Scene::renderDebuggingViews(const RenderData &renderData)\n{\n fbo->bindDepthTexture(GL_TEXTURE0);\n auto transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n textureMapperManager->bindOccupancyTexture();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n textureMapperManager->bindDistanceTransform();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(distanceTransformQuad, transformation.matrix());\n\n textureMapperManager->bindApollonius();\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n\n constraintBuffer->bindTexture(GL_TEXTURE0);\n transformation =\n Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *\n Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));\n renderQuad(quad, transformation.matrix());\n}\n\nvoid Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,\n Eigen::Matrix4f modelMatrix)\n{\n RenderData renderData;\n renderData.projectionMatrix = Eigen::Matrix4f::Identity();\n renderData.viewMatrix = Eigen::Matrix4f::Identity();\n renderData.modelMatrix = modelMatrix;\n\n quad->getShaderProgram()->bind();\n quad->getShaderProgram()->setUniform(\"textureSampler\", 0);\n quad->renderImmediately(gl, managers, renderData);\n}\n\nvoid Scene::renderScreenQuad()\n{\n fbo->bindColorTexture(GL_TEXTURE0);\n\n renderQuad(quad, Eigen::Matrix4f::Identity());\n}\n\nvoid Scene::resize(int width, int height)\n{\n this->width = width;\n this->height = height;\n\n placementLabeller->resize(width, height);\n\n shouldResize = true;\n\n forcesLabeller->resize(width, height);\n}\n\nvoid Scene::pick(int id, Eigen::Vector2f position)\n{\n pickingPosition = position;\n performPicking = true;\n pickingLabelId = id;\n}\n\nvoid Scene::doPick()\n{\n if (!performPicking)\n return;\n\n float depth = -2.0f;\n\n fbo->bindDepthTexture(GL_TEXTURE0);\n\n glAssert(gl->glReadPixels(pickingPosition.x(),\n height - pickingPosition.y() - 1, 1, 1,\n GL_DEPTH_COMPONENT, GL_FLOAT, &depth));\n Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f \/ width - 1.0f,\n pickingPosition.y() * -2.0f \/ height + 1.0f,\n depth * 2.0f - 1.0f, 1.0f);\n\n Eigen::Matrix4f viewProjection =\n camera.getProjectionMatrix() * camera.getViewMatrix();\n Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC;\n positionWorld = positionWorld \/ positionWorld.w();\n\n qWarning() << \"picked:\" << positionWorld;\n\n performPicking = false;\n auto label = labels->getById(pickingLabelId);\n label.anchorPosition = toVector3f(positionWorld);\n\n labels->update(label);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: globdoc.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 08:42:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWGLOBDOCSH_HXX\n#define _SWGLOBDOCSH_HXX\n\n#ifndef SW_SWDLL_HXX\n#include <swdll.hxx>\n#endif\n#include \"docsh.hxx\"\n\nclass SwGlobalDocShell : public SwDocShell\n{\npublic:\n\n SFX_DECL_OBJECTFACTORY(SwGlobalDocShell);\n TYPEINFO();\n\n SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n ~SwGlobalDocShell();\n\n virtual void FillClass( SvGlobalName * pClassName,\n ULONG * pClipFormat,\n String * pAppName,\n String * pLongUserName,\n String * pUserName,\n long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS mav09 (1.4.242); FILE MERGED 2004\/08\/12 17:11:45 mav 1.4.242.2: #i27773# introduce version back 2004\/05\/18 16:43:03 mba 1.4.242.1: RESYNC to m39<commit_after>\/*************************************************************************\n *\n * $RCSfile: globdoc.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 18:58:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWGLOBDOCSH_HXX\n#define _SWGLOBDOCSH_HXX\n\n#ifndef SW_SWDLL_HXX\n#include <swdll.hxx>\n#endif\n#include \"docsh.hxx\"\n\nclass SwGlobalDocShell : public SwDocShell\n{\npublic:\n\n SFX_DECL_OBJECTFACTORY();\n TYPEINFO();\n\n SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n ~SwGlobalDocShell();\n\n virtual void FillClass( SvGlobalName * pClassName,\n ULONG * pClipFormat,\n String * pAppName,\n String * pLongUserName,\n String * pUserName,\n sal_Int32 nFileFormat ) const;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: globdoc.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: jp $ $Date: 2001-07-05 17:29:32 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWGLOBDOCSH_HXX\n#define _SWGLOBDOCSH_HXX\n\n#ifndef SW_SWDLL_HXX\n#include <swdll.hxx>\n#endif\n#include \"docsh.hxx\"\n\nclass SwGlobalDocShell : public SwDocShell\n{\npublic:\n\n SFX_DECL_OBJECTFACTORY_DLL(SwGlobalDocShell, SW_DLL());\n TYPEINFO();\n\n SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n ~SwGlobalDocShell();\n\n virtual void FillClass( SvGlobalName * pClassName,\n ULONG * pClipFormat,\n String * pAppName,\n String * pLongUserName,\n String * pUserName,\n long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS fwkq1 (1.3.276); FILE MERGED 2003\/07\/15 06:35:53 mba 1.3.276.1: #110843#: get rid of factories<commit_after>\/*************************************************************************\n *\n * $RCSfile: globdoc.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 08:42:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWGLOBDOCSH_HXX\n#define _SWGLOBDOCSH_HXX\n\n#ifndef SW_SWDLL_HXX\n#include <swdll.hxx>\n#endif\n#include \"docsh.hxx\"\n\nclass SwGlobalDocShell : public SwDocShell\n{\npublic:\n\n SFX_DECL_OBJECTFACTORY(SwGlobalDocShell);\n TYPEINFO();\n\n SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);\n ~SwGlobalDocShell();\n\n virtual void FillClass( SvGlobalName * pClassName,\n ULONG * pClipFormat,\n String * pAppName,\n String * pLongUserName,\n String * pUserName,\n long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_TEST_UTIL_TEST_PATH_HPP\n#define REALM_TEST_UTIL_TEST_PATH_HPP\n\n#include <string>\n\n#include <realm\/util\/features.h>\n\n#include \"unit_test.hpp\"\n\n#define TEST_PATH_HELPER(class_name, var_name, suffix) \\\n class_name var_name(realm::test_util::get_test_path(test_details, \".\" #var_name \".\" suffix))\n\n#define TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, \"test\");\n\n#define GROUP_TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, \"realm\");\n\n#define SHARED_GROUP_TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::SharedGroupTestPathGuard, var_name, \"realm\");\n\nnamespace realm {\nnamespace test_util {\n\n\/\/\/ Disable removal of test files. If called, the call must complete\n\/\/\/ before any TestPathGuard object is created.\nvoid keep_test_files();\n\n\/\/\/ By default, test files are placed in the current working\n\/\/\/ directory. Use this function to set a path prefix. The specified\n\/\/\/ prefix must contain a final `\/`.\nvoid set_test_path_prefix(const std::string&);\nstd::string get_test_path_prefix();\n\nstd::string get_test_path(const unit_test::TestDetails&, const std::string& suffix);\n\nstd::string get_test_resource_path();\nvoid set_test_resource_path(const std::string&);\n\n\n\/\/\/ Constructor and destructor removes file if it exists.\nclass TestPathGuard {\npublic:\n TestPathGuard(const std::string& path);\n ~TestPathGuard() noexcept;\n operator std::string() const\n {\n return m_path;\n }\n const char* c_str() const\n {\n return m_path.c_str();\n }\nprotected:\n std::string m_path;\n};\n\nclass SharedGroupTestPathGuard: public TestPathGuard {\npublic:\n SharedGroupTestPathGuard(const std::string& path);\n std::string get_lock_path() const\n {\n return m_path + \".lock\";\n }\n ~SharedGroupTestPathGuard();\n};\n\n} \/\/ namespace test_util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_TEST_UTIL_TEST_PATH_HPP\n<commit_msg>Prevent copy of TestPathGuard as it has unfortunate side effects; such as deleting the associated Realm files<commit_after>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_TEST_UTIL_TEST_PATH_HPP\n#define REALM_TEST_UTIL_TEST_PATH_HPP\n\n#include <string>\n\n#include <realm\/util\/features.h>\n\n#include \"unit_test.hpp\"\n\n#define TEST_PATH_HELPER(class_name, var_name, suffix) \\\n class_name var_name(realm::test_util::get_test_path(test_details, \".\" #var_name \".\" suffix))\n\n#define TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, \"test\");\n\n#define GROUP_TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, \"realm\");\n\n#define SHARED_GROUP_TEST_PATH(var_name) \\\n TEST_PATH_HELPER(realm::test_util::SharedGroupTestPathGuard, var_name, \"realm\");\n\nnamespace realm {\nnamespace test_util {\n\n\/\/\/ Disable removal of test files. If called, the call must complete\n\/\/\/ before any TestPathGuard object is created.\nvoid keep_test_files();\n\n\/\/\/ By default, test files are placed in the current working\n\/\/\/ directory. Use this function to set a path prefix. The specified\n\/\/\/ prefix must contain a final `\/`.\nvoid set_test_path_prefix(const std::string&);\nstd::string get_test_path_prefix();\n\nstd::string get_test_path(const unit_test::TestDetails&, const std::string& suffix);\n\nstd::string get_test_resource_path();\nvoid set_test_resource_path(const std::string&);\n\n\n\/\/\/ Constructor and destructor removes file if it exists.\nclass TestPathGuard {\npublic:\n TestPathGuard(const std::string& path);\n ~TestPathGuard() noexcept;\n operator std::string() const\n {\n return m_path;\n }\n const char* c_str() const\n {\n return m_path.c_str();\n }\n TestPathGuard(const TestPathGuard&) = delete;\n TestPathGuard& operator=(const TestPathGuard&) = delete;\nprotected:\n std::string m_path;\n};\n\nclass SharedGroupTestPathGuard: public TestPathGuard {\npublic:\n SharedGroupTestPathGuard(const std::string& path);\n std::string get_lock_path() const\n {\n return m_path + \".lock\";\n }\n ~SharedGroupTestPathGuard();\n};\n\n} \/\/ namespace test_util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_TEST_UTIL_TEST_PATH_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <string>\n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n#include \".\/vpx_config.h\"\n#include \"test\/codec_factory.h\"\n#include \"test\/decode_test_driver.h\"\n#include \"test\/md5_helper.h\"\n#if CONFIG_WEBM_IO\n#include \"test\/webm_video_source.h\"\n#endif\n#include \"vp9\/decoder\/vp9_thread.h\"\n\nnamespace {\n\nusing std::string;\n\nclass VP9WorkerThreadTest : public ::testing::TestWithParam<bool> {\n protected:\n virtual ~VP9WorkerThreadTest() {}\n virtual void SetUp() {\n vp9_worker_init(&worker_);\n }\n\n virtual void TearDown() {\n vp9_worker_end(&worker_);\n }\n\n VP9Worker worker_;\n};\n\nint ThreadHook(void* data, void* return_value) {\n int* const hook_data = reinterpret_cast<int*>(data);\n *hook_data = 5;\n return *reinterpret_cast<int*>(return_value);\n}\n\nTEST_P(VP9WorkerThreadTest, HookSuccess) {\n EXPECT_NE(vp9_worker_sync(&worker_), 0); \/\/ should be a no-op.\n\n for (int i = 0; i < 2; ++i) {\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n\n int hook_data = 0;\n int return_value = 1; \/\/ return successfully from the hook\n worker_.hook = ThreadHook;\n worker_.data1 = &hook_data;\n worker_.data2 = &return_value;\n\n const bool synchronous = GetParam();\n if (synchronous) {\n vp9_worker_execute(&worker_);\n } else {\n vp9_worker_launch(&worker_);\n }\n EXPECT_NE(vp9_worker_sync(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n EXPECT_EQ(5, hook_data);\n\n EXPECT_NE(vp9_worker_sync(&worker_), 0); \/\/ should be a no-op.\n }\n}\n\nTEST_P(VP9WorkerThreadTest, HookFailure) {\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n\n int hook_data = 0;\n int return_value = 0; \/\/ return failure from the hook\n worker_.hook = ThreadHook;\n worker_.data1 = &hook_data;\n worker_.data2 = &return_value;\n\n const bool synchronous = GetParam();\n if (synchronous) {\n vp9_worker_execute(&worker_);\n } else {\n vp9_worker_launch(&worker_);\n }\n EXPECT_FALSE(vp9_worker_sync(&worker_));\n EXPECT_EQ(1, worker_.had_error);\n\n \/\/ Ensure _reset() clears the error and _launch() can be called again.\n return_value = 1;\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n vp9_worker_launch(&worker_);\n EXPECT_NE(vp9_worker_sync(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Multi-threaded decode tests\n\n#if CONFIG_WEBM_IO\n\/\/ Decodes |filename| with |num_threads|. Returns the md5 of the decoded frames.\nstring DecodeFile(const string& filename, int num_threads) {\n libvpx_test::WebMVideoSource video(filename);\n video.Init();\n\n vpx_codec_dec_cfg_t cfg = {0};\n cfg.threads = num_threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n libvpx_test::MD5 md5;\n for (video.Begin(); video.cxdata(); video.Next()) {\n const vpx_codec_err_t res =\n decoder.DecodeFrame(video.cxdata(), video.frame_size());\n if (res != VPX_CODEC_OK) {\n EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();\n break;\n }\n\n libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();\n const vpx_image_t *img = NULL;\n\n \/\/ Get decompressed data\n while ((img = dec_iter.Next())) {\n md5.Add(img);\n }\n }\n return string(md5.Get());\n}\n\nTEST(VP9DecodeMTTest, MTDecode) {\n \/\/ no tiles or frame parallel; this exercises loop filter threading.\n EXPECT_STREQ(\"b35a1b707b28e82be025d960aba039bc\",\n DecodeFile(\"vp90-2-03-size-226x226.webm\", 2).c_str());\n}\n\nTEST(VP9DecodeMTTest, MTDecode2) {\n static const struct {\n const char *name;\n const char *expected_md5;\n } files[] = {\n { \"vp90-2-08-tile_1x2_frame_parallel.webm\",\n \"68ede6abd66bae0a2edf2eb9232241b6\" },\n { \"vp90-2-08-tile_1x4_frame_parallel.webm\",\n \"368ebc6ebf3a5e478d85b2c3149b2848\" },\n { \"vp90-2-08-tile_1x8_frame_parallel.webm\",\n \"17e439da2388aff3a0f69cb22579c6c1\" },\n };\n\n for (int i = 0; i < static_cast<int>(sizeof(files) \/ sizeof(files[0])); ++i) {\n for (int t = 2; t <= 8; ++t) {\n EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())\n << \"threads = \" << t;\n }\n }\n}\n\n\/\/ Test tile quantity changes within one file.\nTEST(VP9DecodeMTTest, MTDecode3) {\n static const struct {\n const char *name;\n const char *expected_md5;\n } files[] = {\n { \"vp90-2-14-resize-fp-tiles-1-16.webm\",\n \"0cd5e632c326297e975f38949c31ea94\" },\n { \"vp90-2-14-resize-fp-tiles-1-2-4-8-16.webm\",\n \"5c78a96a42e7f4a4f6b2edcdb791e44c\" },\n { \"vp90-2-14-resize-fp-tiles-1-2.webm\",\n \"e030450ae85c3277be2a418769df98e2\" },\n { \"vp90-2-14-resize-fp-tiles-1-4.webm\",\n \"312eed4e2b64eb7a4e7f18916606a430\" },\n { \"vp90-2-14-resize-fp-tiles-16-1.webm\",\n \"1755c16d8af16a9cb3fe7338d90abe52\" },\n { \"vp90-2-14-resize-fp-tiles-16-2.webm\",\n \"500300592d3fcb6f12fab25e48aaf4df\" },\n { \"vp90-2-14-resize-fp-tiles-16-4.webm\",\n \"47c48379fa6331215d91c67648e1af6e\" },\n { \"vp90-2-14-resize-fp-tiles-16-8-4-2-1.webm\",\n \"eecf17290739bc708506fa4827665989\" },\n { \"vp90-2-14-resize-fp-tiles-16-8.webm\",\n \"29b6bb54e4c26b5ca85d5de5fed94e76\" },\n { \"vp90-2-14-resize-fp-tiles-1-8.webm\",\n \"1b6f175e08cd82cf84bb800ac6d1caa3\" },\n { \"vp90-2-14-resize-fp-tiles-2-16.webm\",\n \"ca3b03e4197995d8d5444ede7a6c0804\" },\n { \"vp90-2-14-resize-fp-tiles-2-1.webm\",\n \"99aec065369d70bbb78ccdff65afed3f\" },\n { \"vp90-2-14-resize-fp-tiles-2-4.webm\",\n \"22d0ebdb49b87d2920a85aea32e1afd5\" },\n { \"vp90-2-14-resize-fp-tiles-2-8.webm\",\n \"c2115cf051c62e0f7db1d4a783831541\" },\n { \"vp90-2-14-resize-fp-tiles-4-16.webm\",\n \"c690d7e1719b31367564cac0af0939cb\" },\n { \"vp90-2-14-resize-fp-tiles-4-1.webm\",\n \"a926020b2cc3e15ad4cc271853a0ff26\" },\n { \"vp90-2-14-resize-fp-tiles-4-2.webm\",\n \"42699063d9e581f1993d0cf890c2be78\" },\n { \"vp90-2-14-resize-fp-tiles-4-8.webm\",\n \"7f76d96036382f45121e3d5aa6f8ec52\" },\n { \"vp90-2-14-resize-fp-tiles-8-16.webm\",\n \"76a43fcdd7e658542913ea43216ec55d\" },\n { \"vp90-2-14-resize-fp-tiles-8-1.webm\",\n \"8e3fbe89486ca60a59299dea9da91378\" },\n { \"vp90-2-14-resize-fp-tiles-8-2.webm\",\n \"ae96f21f21b6370cc0125621b441fc52\" },\n { \"vp90-2-14-resize-fp-tiles-8-4.webm\",\n \"3eb4f24f10640d42218f7fd7b9fd30d4\" },\n };\n\n for (int i = 0; i < static_cast<int>(sizeof(files) \/ sizeof(files[0])); ++i) {\n for (int t = 2; t <= 8; ++t) {\n EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())\n << \"threads = \" << t;\n }\n }\n}\n#endif \/\/ CONFIG_WEBM_IO\n\nINSTANTIATE_TEST_CASE_P(Synchronous, VP9WorkerThreadTest, ::testing::Bool());\n\n} \/\/ namespace\n<commit_msg>vp9_thread_test: add 'Thread' to test names<commit_after>\/*\n * Copyright (c) 2013 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <string>\n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n#include \".\/vpx_config.h\"\n#include \"test\/codec_factory.h\"\n#include \"test\/decode_test_driver.h\"\n#include \"test\/md5_helper.h\"\n#if CONFIG_WEBM_IO\n#include \"test\/webm_video_source.h\"\n#endif\n#include \"vp9\/decoder\/vp9_thread.h\"\n\nnamespace {\n\nusing std::string;\n\nclass VP9WorkerThreadTest : public ::testing::TestWithParam<bool> {\n protected:\n virtual ~VP9WorkerThreadTest() {}\n virtual void SetUp() {\n vp9_worker_init(&worker_);\n }\n\n virtual void TearDown() {\n vp9_worker_end(&worker_);\n }\n\n VP9Worker worker_;\n};\n\nint ThreadHook(void* data, void* return_value) {\n int* const hook_data = reinterpret_cast<int*>(data);\n *hook_data = 5;\n return *reinterpret_cast<int*>(return_value);\n}\n\nTEST_P(VP9WorkerThreadTest, HookSuccess) {\n EXPECT_NE(vp9_worker_sync(&worker_), 0); \/\/ should be a no-op.\n\n for (int i = 0; i < 2; ++i) {\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n\n int hook_data = 0;\n int return_value = 1; \/\/ return successfully from the hook\n worker_.hook = ThreadHook;\n worker_.data1 = &hook_data;\n worker_.data2 = &return_value;\n\n const bool synchronous = GetParam();\n if (synchronous) {\n vp9_worker_execute(&worker_);\n } else {\n vp9_worker_launch(&worker_);\n }\n EXPECT_NE(vp9_worker_sync(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n EXPECT_EQ(5, hook_data);\n\n EXPECT_NE(vp9_worker_sync(&worker_), 0); \/\/ should be a no-op.\n }\n}\n\nTEST_P(VP9WorkerThreadTest, HookFailure) {\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n\n int hook_data = 0;\n int return_value = 0; \/\/ return failure from the hook\n worker_.hook = ThreadHook;\n worker_.data1 = &hook_data;\n worker_.data2 = &return_value;\n\n const bool synchronous = GetParam();\n if (synchronous) {\n vp9_worker_execute(&worker_);\n } else {\n vp9_worker_launch(&worker_);\n }\n EXPECT_FALSE(vp9_worker_sync(&worker_));\n EXPECT_EQ(1, worker_.had_error);\n\n \/\/ Ensure _reset() clears the error and _launch() can be called again.\n return_value = 1;\n EXPECT_NE(vp9_worker_reset(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n vp9_worker_launch(&worker_);\n EXPECT_NE(vp9_worker_sync(&worker_), 0);\n EXPECT_FALSE(worker_.had_error);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Multi-threaded decode tests\n\n#if CONFIG_WEBM_IO\n\/\/ Decodes |filename| with |num_threads|. Returns the md5 of the decoded frames.\nstring DecodeFile(const string& filename, int num_threads) {\n libvpx_test::WebMVideoSource video(filename);\n video.Init();\n\n vpx_codec_dec_cfg_t cfg = {0};\n cfg.threads = num_threads;\n libvpx_test::VP9Decoder decoder(cfg, 0);\n\n libvpx_test::MD5 md5;\n for (video.Begin(); video.cxdata(); video.Next()) {\n const vpx_codec_err_t res =\n decoder.DecodeFrame(video.cxdata(), video.frame_size());\n if (res != VPX_CODEC_OK) {\n EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();\n break;\n }\n\n libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();\n const vpx_image_t *img = NULL;\n\n \/\/ Get decompressed data\n while ((img = dec_iter.Next())) {\n md5.Add(img);\n }\n }\n return string(md5.Get());\n}\n\nTEST(VP9DecodeMultiThreadedTest, Decode) {\n \/\/ no tiles or frame parallel; this exercises loop filter threading.\n EXPECT_STREQ(\"b35a1b707b28e82be025d960aba039bc\",\n DecodeFile(\"vp90-2-03-size-226x226.webm\", 2).c_str());\n}\n\nTEST(VP9DecodeMultiThreadedTest, Decode2) {\n static const struct {\n const char *name;\n const char *expected_md5;\n } files[] = {\n { \"vp90-2-08-tile_1x2_frame_parallel.webm\",\n \"68ede6abd66bae0a2edf2eb9232241b6\" },\n { \"vp90-2-08-tile_1x4_frame_parallel.webm\",\n \"368ebc6ebf3a5e478d85b2c3149b2848\" },\n { \"vp90-2-08-tile_1x8_frame_parallel.webm\",\n \"17e439da2388aff3a0f69cb22579c6c1\" },\n };\n\n for (int i = 0; i < static_cast<int>(sizeof(files) \/ sizeof(files[0])); ++i) {\n for (int t = 2; t <= 8; ++t) {\n EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())\n << \"threads = \" << t;\n }\n }\n}\n\n\/\/ Test tile quantity changes within one file.\nTEST(VP9DecodeMultiThreadedTest, Decode3) {\n static const struct {\n const char *name;\n const char *expected_md5;\n } files[] = {\n { \"vp90-2-14-resize-fp-tiles-1-16.webm\",\n \"0cd5e632c326297e975f38949c31ea94\" },\n { \"vp90-2-14-resize-fp-tiles-1-2-4-8-16.webm\",\n \"5c78a96a42e7f4a4f6b2edcdb791e44c\" },\n { \"vp90-2-14-resize-fp-tiles-1-2.webm\",\n \"e030450ae85c3277be2a418769df98e2\" },\n { \"vp90-2-14-resize-fp-tiles-1-4.webm\",\n \"312eed4e2b64eb7a4e7f18916606a430\" },\n { \"vp90-2-14-resize-fp-tiles-16-1.webm\",\n \"1755c16d8af16a9cb3fe7338d90abe52\" },\n { \"vp90-2-14-resize-fp-tiles-16-2.webm\",\n \"500300592d3fcb6f12fab25e48aaf4df\" },\n { \"vp90-2-14-resize-fp-tiles-16-4.webm\",\n \"47c48379fa6331215d91c67648e1af6e\" },\n { \"vp90-2-14-resize-fp-tiles-16-8-4-2-1.webm\",\n \"eecf17290739bc708506fa4827665989\" },\n { \"vp90-2-14-resize-fp-tiles-16-8.webm\",\n \"29b6bb54e4c26b5ca85d5de5fed94e76\" },\n { \"vp90-2-14-resize-fp-tiles-1-8.webm\",\n \"1b6f175e08cd82cf84bb800ac6d1caa3\" },\n { \"vp90-2-14-resize-fp-tiles-2-16.webm\",\n \"ca3b03e4197995d8d5444ede7a6c0804\" },\n { \"vp90-2-14-resize-fp-tiles-2-1.webm\",\n \"99aec065369d70bbb78ccdff65afed3f\" },\n { \"vp90-2-14-resize-fp-tiles-2-4.webm\",\n \"22d0ebdb49b87d2920a85aea32e1afd5\" },\n { \"vp90-2-14-resize-fp-tiles-2-8.webm\",\n \"c2115cf051c62e0f7db1d4a783831541\" },\n { \"vp90-2-14-resize-fp-tiles-4-16.webm\",\n \"c690d7e1719b31367564cac0af0939cb\" },\n { \"vp90-2-14-resize-fp-tiles-4-1.webm\",\n \"a926020b2cc3e15ad4cc271853a0ff26\" },\n { \"vp90-2-14-resize-fp-tiles-4-2.webm\",\n \"42699063d9e581f1993d0cf890c2be78\" },\n { \"vp90-2-14-resize-fp-tiles-4-8.webm\",\n \"7f76d96036382f45121e3d5aa6f8ec52\" },\n { \"vp90-2-14-resize-fp-tiles-8-16.webm\",\n \"76a43fcdd7e658542913ea43216ec55d\" },\n { \"vp90-2-14-resize-fp-tiles-8-1.webm\",\n \"8e3fbe89486ca60a59299dea9da91378\" },\n { \"vp90-2-14-resize-fp-tiles-8-2.webm\",\n \"ae96f21f21b6370cc0125621b441fc52\" },\n { \"vp90-2-14-resize-fp-tiles-8-4.webm\",\n \"3eb4f24f10640d42218f7fd7b9fd30d4\" },\n };\n\n for (int i = 0; i < static_cast<int>(sizeof(files) \/ sizeof(files[0])); ++i) {\n for (int t = 2; t <= 8; ++t) {\n EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())\n << \"threads = \" << t;\n }\n }\n}\n#endif \/\/ CONFIG_WEBM_IO\n\nINSTANTIATE_TEST_CASE_P(Synchronous, VP9WorkerThreadTest, ::testing::Bool());\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.\n\/\/\n\/\/ This file is part of the hpp-corbaserver.\n\/\/\n\/\/ This software is provided \"as is\" without warranty of any kind,\n\/\/ either expressed or implied, including but not limited to the\n\/\/ implied warranties of fitness for a particular purpose.\n\/\/\n\/\/ See the COPYING file for more information.\n\n#include <errno.h>\n#include <pthread.h>\n#include <iostream>\n\n#include <hpp\/util\/debug.hh>\n#include \"hpp\/corbaserver\/server.hh\"\n\n#include \"server-private.hh\"\n\n\nnamespace hpp\n{\n namespace corbaServer\n {\n using CORBA::Exception;\n using CORBA::Object_var;\n using CORBA::SystemException;\n using CORBA::ORB_init;\n using CORBA::PolicyList;\n using omniORB::fatalException;\n\n namespace\n {\n \/\/\/ \\brief Forward logging messages to hpp logging mechanism.\n \/\/\/ If debug is disabled, CORBA logging will be disabled too.\n \/\/\/\n \/\/\/ Tracing has to be enabled in your ``omniORB.cfg'' to use this\n \/\/\/ feature.\n \/\/\/ See ``omniORB configuration and API'' > ``Tracing options''\n \/\/\/ section of omniORB manual for more information.\n void logFunction (const char* msg);\n\n void logFunction (const char* hppDebugStatement (msg))\n {\n\thppDout (info, \"omniORB: \" << msg);\n }\n\n void usage (const char* app)\n {\n std::cerr << \"Usage: \" << app << \" [options] ...\" << '\\n'\n << \" --name <name>\" << '\\n'\n << \" --help\" << '\\n'\n << \" --single-thread\" << '\\n'\n << \" --multi-thread\" << std::endl;\n }\n } \/\/ end of anonymous namespace.\n\n\n Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,\n\t\t const char *argv[], bool inMultiThread) :\n multiThread_ (inMultiThread),\n problemSolverMap_ (new ProblemSolverMap (problemSolver))\n {\n \/\/ Register log function.\n omniORB::setLogFunction (&logFunction);\n\n private_ = new impl::Server;\n\n parseArguments (argc, argv);\n\n initORBandServers (argc, argv, multiThread_);\n }\n\n Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,\n\t\t const char *argv[], bool inMultiThread) :\n multiThread_ (inMultiThread),\n problemSolverMap_ (problemSolverMap)\n {\n \/\/ Register log function.\n omniORB::setLogFunction (&logFunction);\n\n private_ = new impl::Server;\n\n parseArguments (argc, argv);\n\n initORBandServers (argc, argv, multiThread_);\n }\n\n \/\/\/ \\brief Shutdown CORBA server\n Server::~Server()\n {\n private_->deactivateAndDestroyServers();\n delete private_;\n private_ = NULL;\n }\n\n \/\/\/ CORBA SERVER INITIALIZATION\n\n void Server::initORBandServers(int argc, const char* argv[],\n\t\t\t\t bool inMultiThread)\n {\n Object_var obj;\n PortableServer::ThreadPolicy_var threadPolicy;\n PortableServer::POA_var rootPoa;\n\n \/\/\/ ORB init\n private_->orb_ = ORB_init (argc, const_cast<char **> (argv));\n if (is_nil(private_->orb_)) {\n\tstd::string msg (\"failed to initialize ORB\");\n\thppDout (error, msg.c_str ());\n\tthrow std::runtime_error (msg.c_str ());\n }\n \/\/\/ ORB init\n obj = private_->orb_->resolve_initial_references(\"RootPOA\");\n\n \/\/\/ Create thread policy\n\n \/\/\n \/\/ Make the CORBA object single-threaded to avoid GUI krash\n \/\/\n \/\/ Create a sigle threaded policy object\n rootPoa = PortableServer::POA::_narrow(obj);\n\n if (inMultiThread) {\n\tthreadPolicy = rootPoa->create_thread_policy\n\t (PortableServer::ORB_CTRL_MODEL);\n }\n else {\n\tthreadPolicy = rootPoa->create_thread_policy\n\t (PortableServer::MAIN_THREAD_MODEL);\n }\n \/\/\/ Duplicate thread policy\n PolicyList policyList;\n policyList.length(1);\n policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);\n\n try {\n private_->poa_ = rootPoa->create_POA\n (\"child\", PortableServer::POAManager::_nil(), policyList);\n } catch (PortableServer::POA::AdapterAlreadyExists& \/*e*\/) {\n private_->poa_ = rootPoa->find_POA (\"child\", false);\n }\n\n \/\/ Destroy policy object\n threadPolicy->destroy();\n private_->createAndActivateServers(this);\n }\n\n void Server::parseArguments (int argc, const char* argv[])\n {\n mainContextId_ = \"hpp\";\n\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"--name\") == 0) {\n if (i < argc - 1) {\n mainContextId_.append(argv[i+1]);\n ++i;\n }\n else usage(argv[0]);\n std::cout << \"Server main context: \" << mainContextId_;\n } else if (strcmp(argv[i], \"--help\") == 0) {\n usage(argv[0]);\n } else if (strcmp(argv[i], \"--single-thread\") == 0) {\n multiThread_ = false;\n } else if (strcmp(argv[i], \"--multi-thread\") == 0) {\n multiThread_ = true;\n }\n }\n }\n\n void Server::startCorbaServer()\n {\n \/\/ Obtain a reference to objects, and register them in\n \/\/ the naming service.\n Object_var robotObj = private_->robotServant_->_this();\n Object_var obstacleObj = private_->obstacleServant_->_this();\n Object_var problemObj = private_->problemServant_->_this();\n\n private_->createHppContext (mainContextId());\n \/\/ Bind robotObj with name Robot to the hppContext:\n CosNaming::Name objectName;\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"robot\"; \/\/ string copied\n\n private_->bindObjectToName(robotObj, objectName);\n private_->robotServant_->_remove_ref();\n\n \/\/ Bind obstacleObj with name Obstacle to the hppContext:\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"obstacle\"; \/\/ string copied\n\n private_->bindObjectToName(obstacleObj, objectName);\n private_->obstacleServant_->_remove_ref();\n\n \/\/ Bind problemObj with name Problem to the hppContext:\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"problem\"; \/\/ string copied\n\n private_->bindObjectToName(problemObj, objectName);\n private_->problemServant_->_remove_ref();\n\n PortableServer::POAManager_var pman = private_->poa_->the_POAManager();\n pman->activate();\n }\n\n core::ProblemSolverPtr_t Server::problemSolver ()\n {\n return problemSolverMap_->selected();\n }\n\n ProblemSolverMapPtr_t Server::problemSolverMap ()\n {\n return problemSolverMap_;\n }\n\n \/\/\/ \\brief If CORBA requests are pending, process them\n int Server::processRequest (bool loop)\n {\n if (loop)\n\t{\n\t hppDout (info, \"start processing CORBA requests for ever.\");\n\t private_->orb_->run();\n\t}\n else\n\t{\n\t if (private_->orb_->work_pending())\n\t private_->orb_->perform_work();\n\t}\n return 0;\n }\n\n void Server::requestShutdown (bool wait)\n {\n private_->orb_->shutdown (wait);\n }\n\n } \/\/ end of namespace corbaServer.\n} \/\/ end of namespace hpp.\n<commit_msg>Improve output when parsing arguments<commit_after>\/\/ Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.\n\/\/\n\/\/ This file is part of the hpp-corbaserver.\n\/\/\n\/\/ This software is provided \"as is\" without warranty of any kind,\n\/\/ either expressed or implied, including but not limited to the\n\/\/ implied warranties of fitness for a particular purpose.\n\/\/\n\/\/ See the COPYING file for more information.\n\n#include <errno.h>\n#include <pthread.h>\n#include <iostream>\n\n#include <hpp\/util\/debug.hh>\n#include \"hpp\/corbaserver\/server.hh\"\n\n#include \"server-private.hh\"\n\n\nnamespace hpp\n{\n namespace corbaServer\n {\n using CORBA::Exception;\n using CORBA::Object_var;\n using CORBA::SystemException;\n using CORBA::ORB_init;\n using CORBA::PolicyList;\n using omniORB::fatalException;\n\n namespace\n {\n \/\/\/ \\brief Forward logging messages to hpp logging mechanism.\n \/\/\/ If debug is disabled, CORBA logging will be disabled too.\n \/\/\/\n \/\/\/ Tracing has to be enabled in your ``omniORB.cfg'' to use this\n \/\/\/ feature.\n \/\/\/ See ``omniORB configuration and API'' > ``Tracing options''\n \/\/\/ section of omniORB manual for more information.\n void logFunction (const char* msg);\n\n void logFunction (const char* hppDebugStatement (msg))\n {\n\thppDout (info, \"omniORB: \" << msg);\n }\n\n void usage (const char* app)\n {\n std::cerr << \"Usage: \" << app << \" [options] ...\" << '\\n'\n << \" --name <name>\" << '\\n'\n << \" --help\" << '\\n'\n << \" --single-thread\" << '\\n'\n << \" --multi-thread\" << std::endl;\n }\n } \/\/ end of anonymous namespace.\n\n\n Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,\n\t\t const char *argv[], bool inMultiThread) :\n multiThread_ (inMultiThread),\n problemSolverMap_ (new ProblemSolverMap (problemSolver))\n {\n \/\/ Register log function.\n omniORB::setLogFunction (&logFunction);\n\n private_ = new impl::Server;\n\n parseArguments (argc, argv);\n\n initORBandServers (argc, argv, multiThread_);\n }\n\n Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,\n\t\t const char *argv[], bool inMultiThread) :\n multiThread_ (inMultiThread),\n problemSolverMap_ (problemSolverMap)\n {\n \/\/ Register log function.\n omniORB::setLogFunction (&logFunction);\n\n private_ = new impl::Server;\n\n parseArguments (argc, argv);\n\n initORBandServers (argc, argv, multiThread_);\n }\n\n \/\/\/ \\brief Shutdown CORBA server\n Server::~Server()\n {\n private_->deactivateAndDestroyServers();\n delete private_;\n private_ = NULL;\n }\n\n \/\/\/ CORBA SERVER INITIALIZATION\n\n void Server::initORBandServers(int argc, const char* argv[],\n\t\t\t\t bool inMultiThread)\n {\n Object_var obj;\n PortableServer::ThreadPolicy_var threadPolicy;\n PortableServer::POA_var rootPoa;\n\n \/\/\/ ORB init\n private_->orb_ = ORB_init (argc, const_cast<char **> (argv));\n if (is_nil(private_->orb_)) {\n\tstd::string msg (\"failed to initialize ORB\");\n\thppDout (error, msg.c_str ());\n\tthrow std::runtime_error (msg.c_str ());\n }\n \/\/\/ ORB init\n obj = private_->orb_->resolve_initial_references(\"RootPOA\");\n\n \/\/\/ Create thread policy\n\n \/\/\n \/\/ Make the CORBA object single-threaded to avoid GUI krash\n \/\/\n \/\/ Create a sigle threaded policy object\n rootPoa = PortableServer::POA::_narrow(obj);\n\n if (inMultiThread) {\n\tthreadPolicy = rootPoa->create_thread_policy\n\t (PortableServer::ORB_CTRL_MODEL);\n }\n else {\n\tthreadPolicy = rootPoa->create_thread_policy\n\t (PortableServer::MAIN_THREAD_MODEL);\n }\n \/\/\/ Duplicate thread policy\n PolicyList policyList;\n policyList.length(1);\n policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);\n\n try {\n private_->poa_ = rootPoa->create_POA\n (\"child\", PortableServer::POAManager::_nil(), policyList);\n } catch (PortableServer::POA::AdapterAlreadyExists& \/*e*\/) {\n private_->poa_ = rootPoa->find_POA (\"child\", false);\n }\n\n \/\/ Destroy policy object\n threadPolicy->destroy();\n private_->createAndActivateServers(this);\n }\n\n void Server::parseArguments (int argc, const char* argv[])\n {\n mainContextId_ = \"hpp\";\n\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"--name\") == 0) {\n if (i < argc - 1) {\n mainContextId_.append(argv[i+1]);\n ++i;\n }\n else usage(argv[0]);\n std::cout << \"Server main context: \" << mainContextId_ << std::endl;\n } else if (strcmp(argv[i], \"--help\") == 0) {\n usage(argv[0]);\n } else if (strcmp(argv[i], \"--single-thread\") == 0) {\n multiThread_ = false;\n std::cout << \"Switched to single thread mode.\" << std::endl;\n } else if (strcmp(argv[i], \"--multi-thread\") == 0) {\n std::cout << \"Switched to multi-thread mode.\" << std::endl;\n multiThread_ = true;\n }\n }\n }\n\n void Server::startCorbaServer()\n {\n \/\/ Obtain a reference to objects, and register them in\n \/\/ the naming service.\n Object_var robotObj = private_->robotServant_->_this();\n Object_var obstacleObj = private_->obstacleServant_->_this();\n Object_var problemObj = private_->problemServant_->_this();\n\n private_->createHppContext (mainContextId());\n \/\/ Bind robotObj with name Robot to the hppContext:\n CosNaming::Name objectName;\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"robot\"; \/\/ string copied\n\n private_->bindObjectToName(robotObj, objectName);\n private_->robotServant_->_remove_ref();\n\n \/\/ Bind obstacleObj with name Obstacle to the hppContext:\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"obstacle\"; \/\/ string copied\n\n private_->bindObjectToName(obstacleObj, objectName);\n private_->obstacleServant_->_remove_ref();\n\n \/\/ Bind problemObj with name Problem to the hppContext:\n objectName.length(1);\n objectName[0].id = (const char*) \"basic\"; \/\/ string copied\n objectName[0].kind = (const char*) \"problem\"; \/\/ string copied\n\n private_->bindObjectToName(problemObj, objectName);\n private_->problemServant_->_remove_ref();\n\n PortableServer::POAManager_var pman = private_->poa_->the_POAManager();\n pman->activate();\n }\n\n core::ProblemSolverPtr_t Server::problemSolver ()\n {\n return problemSolverMap_->selected();\n }\n\n ProblemSolverMapPtr_t Server::problemSolverMap ()\n {\n return problemSolverMap_;\n }\n\n \/\/\/ \\brief If CORBA requests are pending, process them\n int Server::processRequest (bool loop)\n {\n if (loop)\n\t{\n\t hppDout (info, \"start processing CORBA requests for ever.\");\n\t private_->orb_->run();\n\t}\n else\n\t{\n\t if (private_->orb_->work_pending())\n\t private_->orb_->perform_work();\n\t}\n return 0;\n }\n\n void Server::requestShutdown (bool wait)\n {\n private_->orb_->shutdown (wait);\n }\n\n } \/\/ end of namespace corbaServer.\n} \/\/ end of namespace hpp.\n<|endoftext|>"} {"text":"<commit_before>#include \"SysControl.h\"\n#include \"ControlsApp.h\"\n#include \"ControlsXPad360.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Input.h\"\n#include \"ObjectGui.h\"\n#include \"WidgetLabel.h\"\n\n\n\/\/解决跨平台字符集兼容问题\n#ifdef _WIN32\n#pragma execution_character_set(\"utf-8\")\n#endif\n\nusing namespace MathLib;\n\nclass CSysControlLocal : public CSysControl\n{\npublic:\n\tCSysControlLocal();\n\tvirtual ~CSysControlLocal();\n\n\tvirtual void Init();\t\/\/角色要初始化,着色器要初始化,\n\tvirtual void Update(float ifps);\n\tvirtual void Shutdown();\n\n\tvirtual int GetState(int state);\t\t\/\/鼠标状态,键盘状态,人物状态,子弹状态等等。\n\tvirtual int ClearState(int state);\n\n\tvirtual float GetMouseDX();\n\tvirtual float GetMouseDY();\n\n\tvirtual void SetMouseGrab(int g);\t\t\/\/设置是否显示鼠标\n\tvirtual int GetMouseGrab();\t\t\t\/\/获取鼠标状态,是显示呢还是不显示的状态。\n\n\n\tvirtual void SetControlMode(ControlMode mode);\t\t\t\/\/控制模式\n\tvirtual ControlMode GetControlMode() const;\t\t\t\t\/\/获取控制模式\n\nprivate:\n\tvoid Update_Mouse(float ifps);\n\tvoid Update_Keyboard(float ifps);\n\tvoid Update_XPad360(float ifps);\n\n\n\tCControlsApp *m_pControlsApp;\t\t\/\/控制游戏中移动\n\tCControlsXPad360 *m_pControlsXPad360;\n\tControlMode m_nControlMode;\t\t\t\/\/控制模式\n\n\tint m_nOldMouseX;\t\t\t\/\/上一个鼠标坐标X\n\tint m_nOldMouseY;\t\t\t\/\/上一个鼠标坐标Y\n\n\tCObjectGui *m_pTest3DUI;\n\tCWidgetLabel *m_pTestMessageLabel;\n\n\n\n\n};\n\n\n\nCSysControlLocal::CSysControlLocal()\n{\n\n}\nCSysControlLocal::~CSysControlLocal()\n{\n\n}\n\nvoid CSysControlLocal::Init()\n{\n\tm_pControlsApp = new CControlsApp;\n\tm_pControlsXPad360 = new CControlsXPad360(0);\n\n\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\n\tSetControlMode(CONTROL_KEYBORAD_MOUSE);\n\n\tm_pTest3DUI = new CObjectGui(2.0f, 1.0f, \"data\/core\/gui\/\");\n\tm_pTest3DUI->SetMouseShow(0);\n\tm_pTest3DUI->SetBackground(1);\n\tm_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTest3DUI->SetScreenSize(800, 400);\n\tm_pTest3DUI->SetControlDistance(1000.0f);\n\tm_pTest3DUI->CreateMaterial(\"gui_base\");\t \/\/show in game\t\n\n\n\tm_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel->SetFontSize(80);\t\t\/\/设置字体大小\n\tm_pTestMessageLabel->SetFontOutline(1);\t\t\/\/设置字体轮廓\n\tm_pTestMessageLabel->SetText(\"两个黄鹂鸣翠柳\\n一行白鹭上青天\\n窗含西岭千秋雪\\n门泊东吴万里船\");\n\n\n\tvoid CSysControlLocal::Update(float ifps)\n\t{\n\t\tUpdate_Mouse(ifps);\n\t\tUpdate_Keyboard(ifps);\n\t\tUpdate_XPad360(ifps);\n\t}\n\n\n\tm_nOldMouseX = 0;\n\tm_nOldMouseY = 0;\n}\nvoid CSysControlLocal::Shutdown()\n{\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\tdelete m_pControlsApp;\n\tm_pControlsApp = NULL;\n\tdelete m_pControlsXPad360;\n\tm_pControlsXPad360 = NULL;\n\tdelete m_pTestMessageLabel;\n\tm_pTestMessageLabel = NULL;\n\tdelete m_pTest3DUI;\n\tm_pTest3DUI = NULL;\n\n}\n\nint CSysControlLocal::GetState(int state)\n{\n\n\treturn m_pControlsApp->GetState(state);\n}\n\nint CSysControlLocal::ClearState(int state)\n{\n\treturn m_pControlsApp->ClearState(state);\n}\n\nfloat CSysControlLocal::GetMouseDX()\n{\n\treturn m_pControlsApp->GetMouseDX();\n}\n\nfloat CSysControlLocal::GetMouseDY()\n{\n\treturn m_pControlsApp->GetMouseDY();\n}\nvoid CSysControlLocal::SetMouseGrab(int g)\n{\n\tg_Engine.pApp->SetMouseGrab(g);\n\tg_Engine.pGui->SetMouseShow(!g);\n}\nint CSysControlLocal::GetMouseGrab()\n{\n\treturn g_Engine.pApp->GetMouseGrab();\n}\n\nvoid CSysControlLocal::SetControlMode(ControlMode mode)\n{\n\tm_nControlMode = mode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\nvoid CSysControlLocal::Update_Mouse(float ifps)\n{\n\tfloat dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1f这个数值越大,鼠标移动越快\n\tfloat dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1这个数值越小,鼠标移动越慢\n\n\tm_pControlsApp->SetMouseDX(dx);\n\tm_pControlsApp->SetMouseDY(dy);\n\n\tif (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())\n\t{\n\t\tg_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() \/ 2, g_Engine.pApp->GetHeight() \/ 2);\n\t}\n\n\tm_nOldMouseX = g_Engine.pApp->GetMouseX();\n\tm_nOldMouseY = g_Engine.pApp->GetMouseY();\n}\n\nvoid CSysControlLocal::Update_Keyboard(float ifps)\t\t\/\/键盘按键响应wsad\n{\n\n\n\tif (g_Engine.pInput->IsKeyDown('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\tif (g_Engine.pInput->IsKeyDown('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\n\tif (g_Engine.pInput->IsKeyUp('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\telse if (g_Engine.pInput->IsKeyUp('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\n\tif (g_Engine.pInput->IsKeyUp('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\telse if (g_Engine.pInput->IsKeyUp('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\tif (g_Engine.pInput->IsKeyDown(' '))\t\t\/\/空格跳跃\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n}\nvoid CSysControlLocal::Update_XPad360(float ifps)\n{\n\tm_pControlsXPad360->UpdateEvents();\n\tCUtilStr strMessage;\n\tstrMessage = CUtilStr(\"测试3D UI\\n\"),\n\tstrMessage += CUtilStr(m_pControlsXPad360->GetName()) + \"\\n\";\n\n\n\tstrMessage += CUtilStr::Format(\"\\n手柄测试\\n\");\n\tstrMessage += CUtilStr::Format(\"LeftX: %5.2f\\n\", m_pControlsXPad360->GetLeftX());\n\tstrMessage += CUtilStr::Format(\"LeftY: %5.2f\\n\", m_pControlsXPad360->GetLeftY());\n\tstrMessage += CUtilStr::Format(\"RightX: %5.2f\\n\", m_pControlsXPad360->GetRightX());\n\tstrMessage += CUtilStr::Format(\"RightY: %5.2f\\n\", m_pControlsXPad360->GetRightY());\n\tstrMessage += \"\\nTriggers:\\n\";\n\tstrMessage += CUtilStr::Format(\"Left: %5.2f\\n\", m_pControlsXPad360->GetLeftTrigger());\n\tstrMessage += CUtilStr::Format(\"Right: %5.2f\\n\", m_pControlsXPad360->GetRightTrigger());\n\n\tstrMessage += CUtilStr::Format(\"\\nButtons:\\n\");\n\tfor (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)\n\t{\n\t\tstrMessage += CUtilStr::Format(\"%d \", m_pControlsXPad360->GetButton(i));\n\t}\n\tm_pTestMessageLabel->SetText(strMessage.Get());\n\n\tconst float fPadThreshold = 0.5f;\n\tif (m_pControlsXPad360->GetLeftX() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\telse if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\t}\n\tif (m_pControlsXPad360->GetLeftY() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\telse if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\t}\n\tif (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n\t\/\/update jump\n\t\/\/ LT RT\n\tif (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_FIRE, 1);\n\t\t\/\/震动\n\t\tm_pControlsXPad360->SetLeftMotor(0.3f);\n\t\tm_pControlsXPad360->SetRightMotor(0.3f);\n\t}\n}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"SysControl.h\"\n#include \"ControlsApp.h\"\n#include \"ControlsXPad360.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Input.h\"\n#include \"ObjectGui.h\"\n#include \"WidgetLabel.h\"\n\n\n\/\/解决跨平台字符集兼容问题\n#ifdef _WIN32\n#pragma execution_character_set(\"utf-8\")\n#endif\n\nusing namespace MathLib;\n\nclass CSysControlLocal : public CSysControl\n{\npublic:\n\tCSysControlLocal();\n\tvirtual ~CSysControlLocal();\n\n\tvirtual void Init();\t\/\/角色要初始化,着色器要初始化,\n\tvirtual void Update(float ifps);\n\tvirtual void Shutdown();\n\n\tvirtual int GetState(int state);\t\t\/\/鼠标状态,键盘状态,人物状态,子弹状态等等。\n\tvirtual int ClearState(int state);\n\n\tvirtual float GetMouseDX();\n\tvirtual float GetMouseDY();\n\n\tvirtual void SetMouseGrab(int g);\t\t\/\/设置是否显示鼠标\n\tvirtual int GetMouseGrab();\t\t\t\/\/获取鼠标状态,是显示呢还是不显示的状态。\n\n\n\tvirtual void SetControlMode(ControlMode mode);\t\t\t\/\/控制模式\n\tvirtual ControlMode GetControlMode() const;\t\t\t\t\/\/获取控制模式\n\nprivate:\n\tvoid Update_Mouse(float ifps);\n\tvoid Update_Keyboard(float ifps);\n\tvoid Update_XPad360(float ifps);\n\n\n\tCControlsApp *m_pControlsApp;\t\t\/\/控制游戏中移动\n\tCControlsXPad360 *m_pControlsXPad360;\n\tControlMode m_nControlMode;\t\t\t\/\/控制模式\n\n\tint m_nOldMouseX;\t\t\t\/\/上一个鼠标坐标X\n\tint m_nOldMouseY;\t\t\t\/\/上一个鼠标坐标Y\n\n\tCObjectGui *m_pTest3DUI;\n\tCWidgetLabel *m_pTestMessageLabel;\n\n\n\n\n};\n\n\n\nCSysControlLocal::CSysControlLocal()\n{\n\n}\nCSysControlLocal::~CSysControlLocal()\n{\n\n}\n\nvoid CSysControlLocal::Init()\n{\n\tm_pControlsApp = new CControlsApp;\n\tm_pControlsXPad360 = new CControlsXPad360(0);\n\n\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\n\tSetControlMode(CONTROL_KEYBORAD_MOUSE);\n\n\tm_pTest3DUI = new CObjectGui(2.0f, 1.0f, \"data\/core\/gui\/\");\n\tm_pTest3DUI->SetMouseShow(0);\n\tm_pTest3DUI->SetBackground(1);\n\tm_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTest3DUI->SetScreenSize(800, 400);\n\tm_pTest3DUI->SetControlDistance(1000.0f);\n\tm_pTest3DUI->CreateMaterial(\"gui_base\");\t \/\/show in game\t\n\n\n\tm_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel->SetFontSize(80);\t\t\/\/设置字体大小\n\tm_pTestMessageLabel->SetFontOutline(1);\t\t\/\/设置字体轮廓\n\tm_pTestMessageLabel->SetText(\"两个黄鹂鸣翠柳\\n一行白鹭上青天\\n窗含西岭千秋雪\\n门泊东吴万里船\");\n\n\n\tvoid CSysControlLocal::Update(float ifps)\n\t{\n\t\tUpdate_Mouse(ifps);\n\t\tUpdate_Keyboard(ifps);\n\t\tUpdate_XPad360(ifps);\n\t}\n\n\n\tm_nOldMouseX = 0;\n\tm_nOldMouseY = 0;\n}\nvoid CSysControlLocal::Shutdown()\n{\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\tdelete m_pControlsApp;\n\tm_pControlsApp = NULL;\n\tdelete m_pControlsXPad360;\n\tm_pControlsXPad360 = NULL;\n\tdelete m_pTestMessageLabel;\n\tm_pTestMessageLabel = NULL;\n\tdelete m_pTest3DUI;\n\tm_pTest3DUI = NULL;\n\n}\n\nint CSysControlLocal::GetState(int state)\n{\n\n\treturn m_pControlsApp->GetState(state);\n}\n\nint CSysControlLocal::ClearState(int state)\n{\n\treturn m_pControlsApp->ClearState(state);\n}\n\nfloat CSysControlLocal::GetMouseDX()\n{\n\treturn m_pControlsApp->GetMouseDX();\n}\n\nfloat CSysControlLocal::GetMouseDY()\n{\n\treturn m_pControlsApp->GetMouseDY();\n}\nvoid CSysControlLocal::SetMouseGrab(int g)\n{\n\tg_Engine.pApp->SetMouseGrab(g);\n\tg_Engine.pGui->SetMouseShow(!g);\n}\nint CSysControlLocal::GetMouseGrab()\n{\n\treturn g_Engine.pApp->GetMouseGrab();\n}\n\nvoid CSysControlLocal::SetControlMode(ControlMode mode)\n{\n\tm_nControlMode = mode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\nvoid CSysControlLocal::Update_Mouse(float ifps)\n{\n\tfloat dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1f这个数值越大,鼠标移动越快\n\tfloat dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1这个数值越小,鼠标移动越慢\n\n\tm_pControlsApp->SetMouseDX(dx);\n\tm_pControlsApp->SetMouseDY(dy);\n\n\tif (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())\n\t{\n\t\tg_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() \/ 2, g_Engine.pApp->GetHeight() \/ 2);\n\t}\n\n\tm_nOldMouseX = g_Engine.pApp->GetMouseX();\n\tm_nOldMouseY = g_Engine.pApp->GetMouseY();\n}\n\nvoid CSysControlLocal::Update_Keyboard(float ifps)\t\t\/\/键盘按键响应wsad\n{\n\n\n\tif (g_Engine.pInput->IsKeyDown('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\tif (g_Engine.pInput->IsKeyDown('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\n\tif (g_Engine.pInput->IsKeyUp('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\telse if (g_Engine.pInput->IsKeyUp('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\n\tif (g_Engine.pInput->IsKeyUp('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\telse if (g_Engine.pInput->IsKeyUp('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\tif (g_Engine.pInput->IsKeyDown(' '))\t\t\/\/空格跳跃\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n}\nvoid CSysControlLocal::Update_XPad360(float ifps)\n{\n\tm_pControlsXPad360->UpdateEvents();\n\tCUtilStr strMessage;\n\tstrMessage = CUtilStr(\"测试3D UI\\n\"),\n\tstrMessage += CUtilStr(m_pControlsXPad360->GetName()) + \"\\n\";\n\n\n\tstrMessage += CUtilStr::Format(\"\\n手柄测试\\n\");\n\tstrMessage += CUtilStr::Format(\"LeftX: %5.2f\\n\", m_pControlsXPad360->GetLeftX());\n\tstrMessage += CUtilStr::Format(\"LeftY: %5.2f\\n\", m_pControlsXPad360->GetLeftY());\n\tstrMessage += CUtilStr::Format(\"RightX: %5.2f\\n\", m_pControlsXPad360->GetRightX());\n\tstrMessage += CUtilStr::Format(\"RightY: %5.2f\\n\", m_pControlsXPad360->GetRightY());\n\tstrMessage += \"\\nTriggers:\\n\";\n\tstrMessage += CUtilStr::Format(\"Left: %5.2f\\n\", m_pControlsXPad360->GetLeftTrigger());\n\tstrMessage += CUtilStr::Format(\"Right: %5.2f\\n\", m_pControlsXPad360->GetRightTrigger());\n\n\tstrMessage += CUtilStr::Format(\"\\nButtons:\\n\");\n\tfor (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)\n\t{\n\t\tstrMessage += CUtilStr::Format(\"%d \", m_pControlsXPad360->GetButton(i));\n\t}\n\tm_pTestMessageLabel->SetText(strMessage.Get());\n\n\tconst float fPadThreshold = 0.5f;\n\tif (m_pControlsXPad360->GetLeftX() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\telse if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\t}\n\tif (m_pControlsXPad360->GetLeftY() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\telse if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\t}\n\tif (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n\t\/\/update jump\n\t\/\/ LT RT\n\tif (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_FIRE, 1);\n\t\t\/\/震动\n\t\tm_pControlsXPad360->SetLeftMotor(0.3f);\n\t\tm_pControlsXPad360->SetRightMotor(0.3f);\n\telse if (m_pControlsXPad360->GetRightTrigger() < fPadThreshold && m_pControlsXPad360->GetLeftTrigger() < fPadThreshold)\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_FIRE, 0);\n\n\t\tm_pControlsXPad360->SetLeftMotor(0.0f);\n\t\tm_pControlsXPad360->SetRightMotor(0.0f);\n\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. (\"Apple\") in\n consideration of your agreement to the following terms, and your use, installation,\n modification or redistribution of this Apple software constitutes acceptance of these\n terms. If you do not agree with these terms, please do not use, install, modify or\n redistribute this Apple software.\n\n In consideration of your agreement to abide by the following terms, and subject to these\n terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in\n this original Apple software (the \"Apple Software\"), to use, reproduce, modify and\n redistribute the Apple Software, with or without modifications, in source and\/or binary\n forms; provided that if you redistribute the Apple Software in its entirety and without\n modifications, you must retain this notice and the following text and disclaimers in all\n such redistributions of the Apple Software. Neither the name, trademarks, service marks\n or logos of Apple Computer, Inc. may be used to endorse or promote products derived from\n the Apple Software without specific prior written permission from Apple. Except as expressly\n stated in this notice, no other rights or licenses, express or implied, are granted by Apple\n herein, including but not limited to any patent rights that may be infringed by your\n derivative works or by other works in which the Apple Software may be incorporated.\n\n The Apple Software is provided by Apple on an \"AS IS\" basis. APPLE MAKES NO WARRANTIES,\n EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS\n USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.\n\n IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,\n REPRODUCTION, MODIFICATION AND\/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND\n WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR\n OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"webkit\/tools\/pepper_test_plugin\/plugin_object.h\"\n\n#ifdef WIN32\n#define NPAPI WINAPI\n#else\n#define NPAPI\n#endif\n\nnamespace {\n\nvoid Log(NPP instance, const char* format, ...) {\n va_list args;\n va_start(args, format);\n std::string message(\"PLUGIN: \");\n StringAppendV(&message, format, args);\n va_end(args);\n\n NPObject* window_object = 0;\n NPError error = browser->getvalue(instance, NPNVWindowNPObject,\n &window_object);\n if (error != NPERR_NO_ERROR) {\n LOG(ERROR) << \"Failed to retrieve window object while logging: \"\n << message;\n return;\n }\n\n NPVariant console_variant;\n if (!browser->getproperty(instance, window_object,\n browser->getstringidentifier(\"console\"),\n &console_variant)) {\n LOG(ERROR) << \"Failed to retrieve console object while logging: \"\n << message;\n browser->releaseobject(window_object);\n return;\n }\n\n NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);\n\n NPVariant message_variant;\n STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);\n\n NPVariant result;\n if (!browser->invoke(instance, console_object,\n browser->getstringidentifier(\"log\"),\n &message_variant, 1, &result)) {\n fprintf(stderr, \"Failed to invoke console.log while logging: %s\\n\",\n message);\n browser->releaseobject(console_object);\n browser->releaseobject(window_object);\n return;\n }\n\n browser->releasevariantvalue(&result);\n browser->releaseobject(console_object);\n browser->releaseobject(window_object);\n}\n\n} \/\/ namespace\n\n\/\/ Plugin entry points\nextern \"C\" {\n\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nNPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs\n#if defined(OS_LINUX)\n , NPPluginFuncs* plugin_funcs\n#endif\n );\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nNPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);\n\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nvoid NPAPI NP_Shutdown() {\n}\n\n#if defined(OS_LINUX)\nNPError NP_GetValue(NPP instance, NPPVariable variable, void* value);\nconst char* NP_GetMIMEDescription();\n#endif\n\n} \/\/ extern \"C\"\n\n\/\/ Plugin entry points\nNPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs\n#if defined(OS_LINUX)\n , NPPluginFuncs* plugin_funcs\n#endif\n ) {\n browser = browser_funcs;\n#if defined(OS_LINUX)\n return NP_GetEntryPoints(plugin_funcs);\n#else\n return NPERR_NO_ERROR;\n#endif\n}\n\n\/\/ Entrypoints -----------------------------------------------------------------\n\nNPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {\n plugin_funcs->version = 11;\n plugin_funcs->size = sizeof(plugin_funcs);\n plugin_funcs->newp = NPP_New;\n plugin_funcs->destroy = NPP_Destroy;\n plugin_funcs->setwindow = NPP_SetWindow;\n plugin_funcs->newstream = NPP_NewStream;\n plugin_funcs->destroystream = NPP_DestroyStream;\n plugin_funcs->asfile = NPP_StreamAsFile;\n plugin_funcs->writeready = NPP_WriteReady;\n plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;\n plugin_funcs->print = NPP_Print;\n plugin_funcs->event = NPP_HandleEvent;\n plugin_funcs->urlnotify = NPP_URLNotify;\n plugin_funcs->getvalue = NPP_GetValue;\n plugin_funcs->setvalue = NPP_SetValue;\n\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_New(NPMIMEType pluginType,\n NPP instance,\n uint16 mode,\n int16 argc, char* argn[], char* argv[],\n NPSavedData* saved) {\n if (browser->version >= 14) {\n PluginObject* obj = reinterpret_cast<PluginObject*>(\n browser->createobject(instance, PluginObject::GetPluginClass()));\n instance->pdata = obj;\n }\n\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_Destroy(NPP instance, NPSavedData** save) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n if (obj)\n browser->releaseobject(obj->header());\n\n fflush(stdout);\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_SetWindow(NPP instance, NPWindow* window) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n if (obj)\n obj->SetWindow(*window);\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_NewStream(NPP instance,\n NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype) {\n *stype = NP_ASFILEONLY;\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {\n return NPERR_NO_ERROR;\n}\n\nvoid NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {\n}\n\nint32 NPP_Write(NPP instance,\n NPStream* stream,\n int32 offset,\n int32 len,\n void* buffer) {\n return 0;\n}\n\nint32 NPP_WriteReady(NPP instance, NPStream* stream) {\n return 0;\n}\n\nvoid NPP_Print(NPP instance, NPPrint* platformPrint) {\n}\n\nint16 NPP_HandleEvent(NPP instance, void* event) {\n return 0;\n}\n\nvoid NPP_URLNotify(NPP instance, const char* url, NPReason reason,\n void* notify_data) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n}\n\nNPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {\n NPError err = NPERR_NO_ERROR;\n\n switch (variable) {\n#if defined(OS_LINUX)\n case NPPVpluginNameString:\n *((const char**)value) = \"Pepper Test PlugIn\";\n break;\n case NPPVpluginDescriptionString:\n *((const char**)value) = \"Simple Pepper plug-in for manual testing.\";\n break;\n case NPPVpluginNeedsXEmbed:\n *((NPBool*)value) = TRUE;\n break;\n#endif\n case NPPVpluginScriptableNPObject: {\n void** v = (void**)value;\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n \/\/ Return value is expected to be retained\n browser->retainobject((NPObject*)obj);\n *v = obj;\n break;\n }\n default:\n fprintf(stderr, \"Unhandled variable to NPP_GetValue\\n\");\n err = NPERR_GENERIC_ERROR;\n break;\n }\n\n return err;\n}\n\nNPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {\n return NPERR_GENERIC_ERROR;\n}\n\n#if defined(OS_LINUX)\nNPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {\n return NPP_GetValue(instance, variable, value);\n}\n\nconst char* NP_GetMIMEDescription() {\n return \"pepper-application\/x-pepper-test-plugin pepper test;\";\n}\n#endif\n<commit_msg>Fix a compilation failure on Linux. It still doesn't link correctly yet on Linux.<commit_after>\/*\n IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. (\"Apple\") in\n consideration of your agreement to the following terms, and your use, installation,\n modification or redistribution of this Apple software constitutes acceptance of these\n terms. If you do not agree with these terms, please do not use, install, modify or\n redistribute this Apple software.\n\n In consideration of your agreement to abide by the following terms, and subject to these\n terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in\n this original Apple software (the \"Apple Software\"), to use, reproduce, modify and\n redistribute the Apple Software, with or without modifications, in source and\/or binary\n forms; provided that if you redistribute the Apple Software in its entirety and without\n modifications, you must retain this notice and the following text and disclaimers in all\n such redistributions of the Apple Software. Neither the name, trademarks, service marks\n or logos of Apple Computer, Inc. may be used to endorse or promote products derived from\n the Apple Software without specific prior written permission from Apple. Except as expressly\n stated in this notice, no other rights or licenses, express or implied, are granted by Apple\n herein, including but not limited to any patent rights that may be infringed by your\n derivative works or by other works in which the Apple Software may be incorporated.\n\n The Apple Software is provided by Apple on an \"AS IS\" basis. APPLE MAKES NO WARRANTIES,\n EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS\n USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.\n\n IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,\n REPRODUCTION, MODIFICATION AND\/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND\n WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR\n OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"webkit\/tools\/pepper_test_plugin\/plugin_object.h\"\n\n#ifdef WIN32\n#define NPAPI WINAPI\n#else\n#define NPAPI\n#endif\n\nnamespace {\n\nvoid Log(NPP instance, const char* format, ...) {\n va_list args;\n va_start(args, format);\n std::string message(\"PLUGIN: \");\n StringAppendV(&message, format, args);\n va_end(args);\n\n NPObject* window_object = 0;\n NPError error = browser->getvalue(instance, NPNVWindowNPObject,\n &window_object);\n if (error != NPERR_NO_ERROR) {\n LOG(ERROR) << \"Failed to retrieve window object while logging: \"\n << message;\n return;\n }\n\n NPVariant console_variant;\n if (!browser->getproperty(instance, window_object,\n browser->getstringidentifier(\"console\"),\n &console_variant)) {\n LOG(ERROR) << \"Failed to retrieve console object while logging: \"\n << message;\n browser->releaseobject(window_object);\n return;\n }\n\n NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);\n\n NPVariant message_variant;\n STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);\n\n NPVariant result;\n if (!browser->invoke(instance, console_object,\n browser->getstringidentifier(\"log\"),\n &message_variant, 1, &result)) {\n fprintf(stderr, \"Failed to invoke console.log while logging: %s\\n\",\n message.c_str());\n browser->releaseobject(console_object);\n browser->releaseobject(window_object);\n return;\n }\n\n browser->releasevariantvalue(&result);\n browser->releaseobject(console_object);\n browser->releaseobject(window_object);\n}\n\n} \/\/ namespace\n\n\/\/ Plugin entry points\nextern \"C\" {\n\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nNPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs\n#if defined(OS_LINUX)\n , NPPluginFuncs* plugin_funcs\n#endif\n );\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nNPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);\n\n#if defined(OS_WIN)\n\/\/__declspec(dllexport)\n#endif\nvoid NPAPI NP_Shutdown() {\n}\n\n#if defined(OS_LINUX)\nNPError NP_GetValue(NPP instance, NPPVariable variable, void* value);\nconst char* NP_GetMIMEDescription();\n#endif\n\n} \/\/ extern \"C\"\n\n\/\/ Plugin entry points\nNPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs\n#if defined(OS_LINUX)\n , NPPluginFuncs* plugin_funcs\n#endif\n ) {\n browser = browser_funcs;\n#if defined(OS_LINUX)\n return NP_GetEntryPoints(plugin_funcs);\n#else\n return NPERR_NO_ERROR;\n#endif\n}\n\n\/\/ Entrypoints -----------------------------------------------------------------\n\nNPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {\n plugin_funcs->version = 11;\n plugin_funcs->size = sizeof(plugin_funcs);\n plugin_funcs->newp = NPP_New;\n plugin_funcs->destroy = NPP_Destroy;\n plugin_funcs->setwindow = NPP_SetWindow;\n plugin_funcs->newstream = NPP_NewStream;\n plugin_funcs->destroystream = NPP_DestroyStream;\n plugin_funcs->asfile = NPP_StreamAsFile;\n plugin_funcs->writeready = NPP_WriteReady;\n plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;\n plugin_funcs->print = NPP_Print;\n plugin_funcs->event = NPP_HandleEvent;\n plugin_funcs->urlnotify = NPP_URLNotify;\n plugin_funcs->getvalue = NPP_GetValue;\n plugin_funcs->setvalue = NPP_SetValue;\n\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_New(NPMIMEType pluginType,\n NPP instance,\n uint16 mode,\n int16 argc, char* argn[], char* argv[],\n NPSavedData* saved) {\n if (browser->version >= 14) {\n PluginObject* obj = reinterpret_cast<PluginObject*>(\n browser->createobject(instance, PluginObject::GetPluginClass()));\n instance->pdata = obj;\n }\n\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_Destroy(NPP instance, NPSavedData** save) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n if (obj)\n browser->releaseobject(obj->header());\n\n fflush(stdout);\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_SetWindow(NPP instance, NPWindow* window) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n if (obj)\n obj->SetWindow(*window);\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_NewStream(NPP instance,\n NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype) {\n *stype = NP_ASFILEONLY;\n return NPERR_NO_ERROR;\n}\n\nNPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {\n return NPERR_NO_ERROR;\n}\n\nvoid NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {\n}\n\nint32 NPP_Write(NPP instance,\n NPStream* stream,\n int32 offset,\n int32 len,\n void* buffer) {\n return 0;\n}\n\nint32 NPP_WriteReady(NPP instance, NPStream* stream) {\n return 0;\n}\n\nvoid NPP_Print(NPP instance, NPPrint* platformPrint) {\n}\n\nint16 NPP_HandleEvent(NPP instance, void* event) {\n return 0;\n}\n\nvoid NPP_URLNotify(NPP instance, const char* url, NPReason reason,\n void* notify_data) {\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n}\n\nNPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {\n NPError err = NPERR_NO_ERROR;\n\n switch (variable) {\n#if defined(OS_LINUX)\n case NPPVpluginNameString:\n *((const char**)value) = \"Pepper Test PlugIn\";\n break;\n case NPPVpluginDescriptionString:\n *((const char**)value) = \"Simple Pepper plug-in for manual testing.\";\n break;\n case NPPVpluginNeedsXEmbed:\n *((NPBool*)value) = TRUE;\n break;\n#endif\n case NPPVpluginScriptableNPObject: {\n void** v = (void**)value;\n PluginObject* obj = static_cast<PluginObject*>(instance->pdata);\n \/\/ Return value is expected to be retained\n browser->retainobject((NPObject*)obj);\n *v = obj;\n break;\n }\n default:\n fprintf(stderr, \"Unhandled variable to NPP_GetValue\\n\");\n err = NPERR_GENERIC_ERROR;\n break;\n }\n\n return err;\n}\n\nNPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {\n return NPERR_GENERIC_ERROR;\n}\n\n#if defined(OS_LINUX)\nNPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {\n return NPP_GetValue(instance, variable, value);\n}\n\nconst char* NP_GetMIMEDescription() {\n return \"pepper-application\/x-pepper-test-plugin pepper test;\";\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/test\/unit_test.hpp>\n#include <iostream>\n#include \"submodular-ibfs.hpp\"\n#include \"higher-order.hpp\"\n#include \"gen-random.hpp\"\n#include \"QPBO.h\"\n\ntypedef SubmodularIBFS::NodeId NodeId;\ntypedef SubmodularIBFS::CliqueId CliqueId;\n\n\/* Sets up a submodular flow problem with a single clique. The clique has 4\n* nodes, and is equal to -1 when all 4 nodes are set to 1, 0 otherwise.\n*\/\nvoid SetupMinimalFlow(SubmodularIBFS& sf) {\n\n sf.AddNode(4);\n\n std::vector<NodeId> nodes = {0, 1, 2, 3};\n const size_t numAssignments = 1 << 4;\n std::vector<REAL> energyTable(numAssignments, 0);\n energyTable[0xf] = -1;\n sf.AddClique(nodes, energyTable);\n}\n\nBOOST_AUTO_TEST_SUITE(ibfsSetupTests)\n\nBOOST_AUTO_TEST_CASE(defaultConstructor) {\n SubmodularIBFS sf;\n\n BOOST_CHECK_EQUAL(sf.GetConstantTerm(), 0);\n BOOST_CHECK_EQUAL(sf.GetNumNodes(), 0);\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), 0);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 0);\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(minimalFlowSetup) {\n SubmodularIBFS sf;\n SetupMinimalFlow(sf);\n\n BOOST_CHECK_EQUAL(sf.GetConstantTerm(), -1);\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), 1);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), 1);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 4);\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n\n std::vector<int>& labels = sf.GetLabels();\n const uint32_t max_assgn = 1 << 4;\n for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {\n for (NodeId i = 0; i < 4; ++i) {\n if (assgn & (1 << i))\n labels[i] = 1;\n else\n labels[i] = 0;\n }\n if (assgn == 0xf)\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);\n else\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(randomFlowSetup) {\n SubmodularIBFS sf;\n const size_t n = 100;\n const size_t k = 4;\n const size_t m = 100;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), n);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), n);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), n);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), n);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), n);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), m);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), m);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), n);\n\n}\n\n\/* Check that for a clique c, the energy is always >= 0, and is equal to 0 at\n* the all 0 and all 1 labelings.\n*\/\nvoid CheckNormalized(const SubmodularIBFS::Clique& c, std::vector<int>& labels) {\n const size_t n = c.Nodes().size();\n BOOST_REQUIRE_LT(n, 32);\n const uint32_t max_assgn = 1 << n;\n for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {\n for (size_t i = 0; i < n; ++i) {\n if (assgn & (1 << i))\n labels[c.Nodes()[i]] = 1;\n else\n labels[c.Nodes()[i]] = 0;\n }\n if (assgn == 0)\n BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);\n else if (assgn == max_assgn - 1)\n BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);\n else\n BOOST_CHECK_GE(c.ComputeEnergy(labels), 0);\n }\n}\n\n\/* Check that all source-sink capacities are >= 0, and that cliques\n* are normalized (i.e., are >= 0 for all labelings)\n*\/\nBOOST_AUTO_TEST_CASE(randomFlowNormalized) {\n SubmodularIBFS sf;\n const size_t n = 100;\n const size_t k = 4;\n const size_t m = 100;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n for (size_t i = 0; i < n; ++i) {\n BOOST_CHECK_GE(sf.GetC_si()[i], 0);\n BOOST_CHECK_GE(sf.GetC_it()[i], 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_si()[i], 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_it()[i], 0);\n }\n\n for (const SubmodularIBFS::CliquePtr& cp : sf.GetCliques()) {\n const SubmodularIBFS::Clique& c = *cp;\n BOOST_CHECK_EQUAL(c.Nodes().size(), 4);\n CheckNormalized(c, sf.GetLabels());\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\n\/\/BOOST_AUTO_TEST_SUITE(flowInvariants)\n\/\/BOOST_AUTO_TEST_SUITE_END()\n\n\n\nvoid CheckCut(SubmodularIBFS& sf) {\n auto& phi_si = sf.GetPhi_si();\n auto& phi_it = sf.GetPhi_it();\n auto& c_si = sf.GetC_si();\n auto& c_it = sf.GetC_it();\n auto& nodes = sf.GetNodes();\n for (SubmodularIBFS::NodeId i = 0; i < sf.GetNumNodes(); ++i) {\n int label = sf.GetLabel(i);\n if (label == 0) {\n BOOST_CHECK_EQUAL(phi_si[i], c_si[i]);\n } else {\n BOOST_CHECK_EQUAL(phi_it[i], c_it[i]);\n }\n for (auto arc : nodes[i].out_arcs) {\n auto j = arc.j;\n if (j >= sf.GetNumNodes())\n continue;\n int label_j = sf.GetLabel(j);\n if (label == 1 && label_j == 0) {\n BOOST_CHECK_EQUAL(sf.ResCap(arc), 0);\n if (sf.ResCap(arc) != 0)\n std::cout << \"Bad Arc: \" << arc.i << \", \" << arc.j << \"\\n\";\n }\n }\n\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(ibfsFlowTests)\n\n\/* Sanity check to make sure basic flow computation working on a minimally\n* sized graph.\n*\/\nBOOST_AUTO_TEST_CASE(minimalFlow) {\n SubmodularIBFS sf;\n SetupMinimalFlow(sf);\n\n sf.Solve();\n CheckCut(sf);\n\n \/\/ Minimum energy is -1 with all 4 nodes labeled 1. Check that this\n \/\/ was the answer we found.\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);\n for (NodeId i = 0; i < 4; ++i) {\n BOOST_CHECK_EQUAL(sf.GetLabel(i), 1);\n }\n}\n\nBOOST_AUTO_TEST_CASE(makeSureToSearchSource) {\nSubmodularIBFS crf;\ncrf.AddNode(3);\ncrf.AddUnaryTerm(0, 12, 6);\ncrf.AddUnaryTerm(1, 8, 8);\ncrf.AddUnaryTerm(2, 6, 12);\nNodeId node_array[3] = {0, 1, 2};\nstd::vector<NodeId> node(node_array, node_array + 3);\nREAL energy_array[8] = {0, 3, 1, 2, 0, 2, 0, 0};\nstd::vector<REAL> energy(energy_array, energy_array + 8);\ncrf.AddClique(node, energy);\ncrf.Solve();\n BOOST_CHECK_EQUAL(crf.GetLabel(0), 1);\n BOOST_CHECK_EQUAL(crf.GetLabel(1), 1);\n BOOST_CHECK_EQUAL(crf.GetLabel(2), 0);\n BOOST_CHECK_EQUAL(crf.ComputeEnergy(), 22);\n\n std::vector<int> label;\n label.push_back(1);\n label.push_back(0);\n label.push_back(0);\n BOOST_CHECK_EQUAL(crf.ComputeEnergy(label), 23);\n}\n\n\/* More complicated test case on a larger graph.\n*\n* GenRandom generates a random submodular function that can be turned into\n* a submodular quadratic function by HigherOrderEnergy. We generate the\n* same energy function for both SubmodularIBFS and HigherOrderEnergy\n* and then check that they give the same answer.\n*\/\nBOOST_AUTO_TEST_CASE(identicalToHigherOrder) {\n SubmodularIBFS sf;\n HigherOrderEnergy<REAL, 4> ho;\n\n const size_t n = 2000;\n const size_t k = 4;\n const size_t m = 2000;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n GenRandom(ho, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n sf.Solve();\n CheckCut(sf);\n\n QPBO<REAL> qr(n, 0);\n ho.ToQuadratic(qr);\n qr.Solve();\n\n std::vector<int> qr_labels;\n for (size_t i = 0; i < n; ++i)\n qr_labels.push_back(qr.GetLabel(i));\n\n \/\/ If this test fails, there's a problem in the higher-order code. Email me\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(qr_labels)*2, qr.ComputeTwiceEnergy());\n\n BOOST_CHECK_EQUAL(sf.ComputeEnergy()*2, qr.ComputeTwiceEnergy());\n for (size_t i = 0; i < n; ++i) {\n BOOST_REQUIRE(qr.GetLabel(i) >= 0);\n BOOST_WARN_EQUAL(sf.GetLabel(i), qr.GetLabel(i));\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Fixing strange merge error<commit_after>#include <boost\/test\/unit_test.hpp>\n#include <iostream>\n#include \"submodular-ibfs.hpp\"\n#include \"higher-order.hpp\"\n#include \"gen-random.hpp\"\n#include \"QPBO.h\"\n\ntypedef SubmodularIBFS::NodeId NodeId;\ntypedef SubmodularIBFS::CliqueId CliqueId;\n\n\/* Sets up a submodular flow problem with a single clique. The clique has 4\n* nodes, and is equal to -1 when all 4 nodes are set to 1, 0 otherwise.\n*\/\nvoid SetupMinimalFlow(SubmodularIBFS& sf) {\n\n sf.AddNode(4);\n\n std::vector<NodeId> nodes = {0, 1, 2, 3};\n const size_t numAssignments = 1 << 4;\n std::vector<REAL> energyTable(numAssignments, 0);\n energyTable[0xf] = -1;\n sf.AddClique(nodes, energyTable);\n}\n\nBOOST_AUTO_TEST_SUITE(ibfsSetupTests)\n\nBOOST_AUTO_TEST_CASE(defaultConstructor) {\n SubmodularIBFS sf;\n\n BOOST_CHECK_EQUAL(sf.GetConstantTerm(), 0);\n BOOST_CHECK_EQUAL(sf.GetNumNodes(), 0);\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), 0);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), 0);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 0);\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(minimalFlowSetup) {\n SubmodularIBFS sf;\n SetupMinimalFlow(sf);\n\n BOOST_CHECK_EQUAL(sf.GetConstantTerm(), -1);\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), 4);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), 1);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), 1);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 4);\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n\n std::vector<int>& labels = sf.GetLabels();\n const uint32_t max_assgn = 1 << 4;\n for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {\n for (NodeId i = 0; i < 4; ++i) {\n if (assgn & (1 << i))\n labels[i] = 1;\n else\n labels[i] = 0;\n }\n if (assgn == 0xf)\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);\n else\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(randomFlowSetup) {\n SubmodularIBFS sf;\n const size_t n = 100;\n const size_t k = 4;\n const size_t m = 100;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n BOOST_CHECK_EQUAL(sf.GetC_si().size(), n);\n BOOST_CHECK_EQUAL(sf.GetC_it().size(), n);\n BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), n);\n BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), n);\n BOOST_CHECK_EQUAL(sf.GetLabels().size(), n);\n BOOST_CHECK_EQUAL(sf.GetNumCliques(), m);\n BOOST_CHECK_EQUAL(sf.GetCliques().size(), m);\n BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), n);\n\n}\n\n\/* Check that for a clique c, the energy is always >= 0, and is equal to 0 at\n* the all 0 and all 1 labelings.\n*\/\nvoid CheckNormalized(const SubmodularIBFS::Clique& c, std::vector<int>& labels) {\n const size_t n = c.Nodes().size();\n BOOST_REQUIRE_LT(n, 32);\n const uint32_t max_assgn = 1 << n;\n for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {\n for (size_t i = 0; i < n; ++i) {\n if (assgn & (1 << i))\n labels[c.Nodes()[i]] = 1;\n else\n labels[c.Nodes()[i]] = 0;\n }\n if (assgn == 0)\n BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);\n else if (assgn == max_assgn - 1)\n BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);\n else\n BOOST_CHECK_GE(c.ComputeEnergy(labels), 0);\n }\n}\n\n\/* Check that all source-sink capacities are >= 0, and that cliques\n* are normalized (i.e., are >= 0 for all labelings)\n*\/\nBOOST_AUTO_TEST_CASE(randomFlowNormalized) {\n SubmodularIBFS sf;\n const size_t n = 100;\n const size_t k = 4;\n const size_t m = 100;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n for (size_t i = 0; i < n; ++i) {\n BOOST_CHECK_GE(sf.GetC_si()[i], 0);\n BOOST_CHECK_GE(sf.GetC_it()[i], 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_si()[i], 0);\n BOOST_CHECK_EQUAL(sf.GetPhi_it()[i], 0);\n }\n\n for (const SubmodularIBFS::CliquePtr& cp : sf.GetCliques()) {\n const SubmodularIBFS::Clique& c = *cp;\n BOOST_CHECK_EQUAL(c.Nodes().size(), 4);\n CheckNormalized(c, sf.GetLabels());\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n\n\/\/BOOST_AUTO_TEST_SUITE(flowInvariants)\n\/\/BOOST_AUTO_TEST_SUITE_END()\n\n\n\nvoid CheckCut(SubmodularIBFS& sf) {\n auto& phi_si = sf.GetPhi_si();\n auto& phi_it = sf.GetPhi_it();\n auto& c_si = sf.GetC_si();\n auto& c_it = sf.GetC_it();\n auto& nodes = sf.GetNodes();\n for (SubmodularIBFS::NodeId i = 0; i < sf.GetNumNodes(); ++i) {\n int label = sf.GetLabel(i);\n if (label == 0) {\n BOOST_CHECK_EQUAL(phi_si[i], c_si[i]);\n } else {\n BOOST_CHECK_EQUAL(phi_it[i], c_it[i]);\n }\n for (auto arc : nodes[i].out_arcs) {\n auto j = arc.j;\n if (j >= sf.GetNumNodes())\n continue;\n int label_j = sf.GetLabel(j);\n if (label == 1 && label_j == 0) {\n BOOST_CHECK_EQUAL(sf.ResCap(arc), 0);\n if (sf.ResCap(arc) != 0)\n std::cout << \"Bad Arc: \" << arc.i << \", \" << arc.j << \"\\n\";\n }\n }\n\n }\n}\n\n\nBOOST_AUTO_TEST_SUITE(ibfsFlowTests)\n\n\/* Sanity check to make sure basic flow computation working on a minimally\n* sized graph.\n*\/\nBOOST_AUTO_TEST_CASE(minimalFlow) {\n SubmodularIBFS sf;\n SetupMinimalFlow(sf);\n\n sf.Solve();\n CheckCut(sf);\n\n \/\/ Minimum energy is -1 with all 4 nodes labeled 1. Check that this\n \/\/ was the answer we found.\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);\n for (NodeId i = 0; i < 4; ++i) {\n BOOST_CHECK_EQUAL(sf.GetLabel(i), 1);\n }\n}\n\nBOOST_AUTO_TEST_CASE(makeSureToSearchSource) {\n\tSubmodularIBFS crf;\n\tcrf.AddNode(3);\n\tcrf.AddUnaryTerm(0, 12, 6);\n\tcrf.AddUnaryTerm(1, 8, 8);\n\tcrf.AddUnaryTerm(2, 6, 12);\n\tNodeId node_array[3] = {0, 1, 2};\n\tstd::vector<NodeId> node(node_array, node_array + 3);\n\tREAL energy_array[8] = {0, 3, 1, 2, 0, 2, 0, 0};\n\tstd::vector<REAL> energy(energy_array, energy_array + 8);\n\tcrf.AddClique(node, energy);\n\tcrf.Solve();\n BOOST_CHECK_EQUAL(crf.GetLabel(0), 1);\n BOOST_CHECK_EQUAL(crf.GetLabel(1), 1);\n BOOST_CHECK_EQUAL(crf.GetLabel(2), 0);\n BOOST_CHECK_EQUAL(crf.ComputeEnergy(), 22);\n\n std::vector<int> label;\n label.push_back(1);\n label.push_back(0);\n label.push_back(0);\n BOOST_CHECK_EQUAL(crf.ComputeEnergy(label), 23);\n}\n\n\/* More complicated test case on a larger graph.\n*\n* GenRandom generates a random submodular function that can be turned into\n* a submodular quadratic function by HigherOrderEnergy. We generate the\n* same energy function for both SubmodularIBFS and HigherOrderEnergy\n* and then check that they give the same answer.\n*\/\nBOOST_AUTO_TEST_CASE(identicalToHigherOrder) {\n SubmodularIBFS sf;\n HigherOrderEnergy<REAL, 4> ho;\n\n const size_t n = 2000;\n const size_t k = 4;\n const size_t m = 2000;\n const REAL clique_range = 100;\n const REAL unary_mean = 800;\n const REAL unary_var = 1600;\n const unsigned int seed = 0;\n\n GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);\n GenRandom(ho, n, k, m, clique_range, unary_mean, unary_var, seed);\n\n sf.Solve();\n CheckCut(sf);\n\n QPBO<REAL> qr(n, 0);\n ho.ToQuadratic(qr);\n qr.Solve();\n\n std::vector<int> qr_labels;\n for (size_t i = 0; i < n; ++i)\n qr_labels.push_back(qr.GetLabel(i));\n\n \/\/ If this test fails, there's a problem in the higher-order code. Email me\n BOOST_CHECK_EQUAL(sf.ComputeEnergy(qr_labels)*2, qr.ComputeTwiceEnergy());\n\n BOOST_CHECK_EQUAL(sf.ComputeEnergy()*2, qr.ComputeTwiceEnergy());\n for (size_t i = 0; i < n; ++i) {\n BOOST_REQUIRE(qr.GetLabel(i) >= 0);\n BOOST_WARN_EQUAL(sf.GetLabel(i), qr.GetLabel(i));\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/socket_io.hpp\" \/\/ print_endpoint\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/http_connection.hpp\"\n#include \"setup_transfer.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <boost\/optional.hpp>\n\nusing namespace libtorrent;\n\nio_service ios;\nconnection_queue cq(ios);\n\nint connect_handler_called = 0;\nint handler_called = 0;\nint data_size = 0;\nint http_status = 0;\nerror_code g_error_code;\nchar data_buffer[4000];\n\nvoid print_http_header(http_parser const& p)\n{\n\tstd::cerr << \" < \" << p.status_code() << \" \" << p.message() << std::endl;\n\n\tfor (std::multimap<std::string, std::string>::const_iterator i\n\t\t= p.headers().begin(), end(p.headers().end()); i != end; ++i)\n\t{\n\t\tstd::cerr << \" < \" << i->first << \": \" << i->second << std::endl;\n\t}\n}\n\nvoid http_connect_handler(http_connection& c)\n{\n\t++connect_handler_called;\n\tTEST_CHECK(c.socket().is_open());\n\terror_code ec;\n\tstd::cerr << \"connected to: \" << print_endpoint(c.socket().remote_endpoint(ec))\n\t\t<< std::endl;\n\/\/ this is not necessarily true when using a proxy and proxying hostnames\n\/\/\tTEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string(\"127.0.0.1\", ec));\n}\n\nvoid http_handler(error_code const& ec, http_parser const& parser\n\t, char const* data, int size, http_connection& c)\n{\n\t++handler_called;\n\tdata_size = size;\n\tg_error_code = ec;\n\tTORRENT_ASSERT(size == 0 || parser.finished());\n\n\tif (parser.header_finished())\n\t{\n\t\thttp_status = parser.status_code();\n\t\tif (http_status == 200)\n\t\t{\n\t\t\tTEST_CHECK(memcmp(data, data_buffer, size) == 0);\n\t\t}\n\t}\n\tprint_http_header(parser);\n}\n\nvoid reset_globals()\n{\n\tconnect_handler_called = 0;\n\thandler_called = 0;\n\tdata_size = 0;\n\thttp_status = 0;\n\tg_error_code = error_code();\n}\n\nvoid run_test(std::string const& url, int size, int status, int connected\n\t, boost::optional<error_code> ec, proxy_settings const& ps)\n{\n\treset_globals();\n\n\tstd::cerr << \" ===== TESTING: \" << url << \" =====\" << std::endl;\n\n\tstd::cerr << \" expecting: size: \" << size\n\t\t<< \" status: \" << status\n\t\t<< \" connected: \" << connected\n\t\t<< \" error: \" << (ec?ec->message():\"no error\") << std::endl;\n\n\tboost::shared_ptr<http_connection> h(new http_connection(ios, cq\n\t\t, &::http_handler, true, 1024*1024, &::http_connect_handler));\n\th->get(url, seconds(1), 0, &ps);\n\tios.reset();\n\terror_code e;\n\tios.run(e);\n\n\tstd::cerr << \"connect_handler_called: \" << connect_handler_called << std::endl;\n\tstd::cerr << \"handler_called: \" << handler_called << std::endl;\n\tstd::cerr << \"status: \" << http_status << std::endl;\n\tstd::cerr << \"size: \" << data_size << std::endl;\n\tstd::cerr << \"error_code: \" << g_error_code.message() << std::endl;\n\tTEST_CHECK(connect_handler_called == connected);\n\tTEST_CHECK(handler_called == 1);\t\n\tTEST_CHECK(data_size == size || size == -1);\n\tTEST_CHECK(!ec || g_error_code == *ec);\n\tTEST_CHECK(http_status == status || status == -1);\n}\n\nvoid run_suite(std::string const& protocol, proxy_settings ps, int port)\n{\n\tif (ps.type != proxy_settings::none)\n\t{\n\t\tps.port = start_proxy(ps.type);\n\t}\n\tchar const* test_name[] = {\"no\", \"SOCKS4\", \"SOCKS5\"\n\t\t, \"SOCKS5 password protected\", \"HTTP\", \"HTTP password protected\"};\n\n\tprintf(\"\\n\\n********************** using %s proxy **********************\\n\"\n\t\t, test_name[ps.type]);\n\n\ttypedef boost::optional<error_code> err;\n\t\/\/ this requires the hosts file to be modified\n\/\/\trun_test(protocol + \":\/\/test.dns.ts:8001\/test_file\", 3216, 200, 1, error_code(), ps);\n\n\tchar url[256];\n\tsnprintf(url, sizeof(url), \"%s:\/\/127.0.0.1:%d\/\", protocol.c_str(), port);\n\tstd::string url_base(url);\n\n\trun_test(url_base + \"relative\/redirect\", 3216, 200, 2, error_code(), ps);\n\trun_test(url_base + \"redirect\", 3216, 200, 2, error_code(), ps);\n\trun_test(url_base + \"infinite_redirect\", 0, 301, 6, error_code(), ps);\n\trun_test(url_base + \"test_file\", 3216, 200, 1, error_code(), ps);\n\trun_test(url_base + \"test_file.gz\", 3216, 200, 1, error_code(), ps);\n\trun_test(url_base + \"non-existing-file\", -1, 404, 1, err(), ps);\n\n\t\/\/ only run the tests to handle NX_DOMAIN if we have a proper internet\n\t\/\/ connection that doesn't inject false DNS responses (like Comcast does)\n\thostent* h = gethostbyname(\"non-existent-domain.se\");\n\tif (h == 0 && h_errno == HOST_NOT_FOUND)\n\t{\n\t\t\/\/ if we're going through an http proxy, we won't get the same error as if the hostname\n\t\t\/\/ resolution failed\n\t\tif ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != \"https\")\n\t\t\trun_test(protocol + \":\/\/non-existent-domain.se\/non-existing-file\", -1, 502, 1, err(), ps);\n\t\telse\n\t\t\trun_test(protocol + \":\/\/non-existent-domain.se\/non-existing-file\", -1, -1, 0, err(), ps);\n\t}\n\n\tif (ps.type != proxy_settings::none)\n\t\tstop_proxy(ps.port);\n}\n\nint test_main()\n{\n\tstd::srand(std::time(0));\n\tstd::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);\n\terror_code ec;\n\tfile test_file(\"test_file\", file::write_only, ec);\n\tTEST_CHECK(!ec);\n\tif (ec) fprintf(stderr, \"file error: %s\\n\", ec.message().c_str());\n\tfile::iovec_t b = { data_buffer, 3216};\n\ttest_file.writev(0, &b, 1, ec);\n\tTEST_CHECK(!ec);\n\tif (ec) fprintf(stderr, \"file error: %s\\n\", ec.message().c_str());\n\ttest_file.close();\n\tstd::system(\"gzip -9 -c test_file > test_file.gz\");\n\t\n\tproxy_settings ps;\n\tps.hostname = \"127.0.0.1\";\n\tps.port = 8034;\n\tps.username = \"testuser\";\n\tps.password = \"testpass\";\n\tint port = 0;\n\t\n\tport = start_web_server();\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tps.type = (proxy_settings::proxy_type)i;\n\t\trun_suite(\"http\", ps, port);\n\t}\n\tstop_web_server();\n\n#ifdef TORRENT_USE_OPENSSL\n\tport = start_web_server(true);\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tps.type = (proxy_settings::proxy_type)i;\n\t\trun_suite(\"https\", ps, port);\n\t}\n\tstop_web_server();\n#endif\n\n\t\/\/ test chunked encoding\n\tport = start_web_server(false, true);\n\tps.type = proxy_settings::none;\n\trun_suite(\"http\", ps, port);\n\n\tstop_web_server();\n\n\tstd::remove(\"test_file\");\n\treturn 0;\n}\n\n<commit_msg>debug output for test_http_connection<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/socket_io.hpp\" \/\/ print_endpoint\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/http_connection.hpp\"\n#include \"setup_transfer.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <boost\/optional.hpp>\n\nusing namespace libtorrent;\n\nio_service ios;\nconnection_queue cq(ios);\n\nint connect_handler_called = 0;\nint handler_called = 0;\nint data_size = 0;\nint http_status = 0;\nerror_code g_error_code;\nchar data_buffer[4000];\n\nvoid print_http_header(http_parser const& p)\n{\n\tstd::cerr << \" < \" << p.status_code() << \" \" << p.message() << std::endl;\n\n\tfor (std::multimap<std::string, std::string>::const_iterator i\n\t\t= p.headers().begin(), end(p.headers().end()); i != end; ++i)\n\t{\n\t\tstd::cerr << \" < \" << i->first << \": \" << i->second << std::endl;\n\t}\n}\n\nvoid http_connect_handler(http_connection& c)\n{\n\t++connect_handler_called;\n\tTEST_CHECK(c.socket().is_open());\n\terror_code ec;\n\tstd::cerr << \"connected to: \" << print_endpoint(c.socket().remote_endpoint(ec))\n\t\t<< std::endl;\n\/\/ this is not necessarily true when using a proxy and proxying hostnames\n\/\/\tTEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string(\"127.0.0.1\", ec));\n}\n\nvoid http_handler(error_code const& ec, http_parser const& parser\n\t, char const* data, int size, http_connection& c)\n{\n\t++handler_called;\n\tdata_size = size;\n\tg_error_code = ec;\n\tTORRENT_ASSERT(size == 0 || parser.finished());\n\n\tif (parser.header_finished())\n\t{\n\t\thttp_status = parser.status_code();\n\t\tif (http_status == 200)\n\t\t{\n\t\t\tTEST_CHECK(memcmp(data, data_buffer, size) == 0);\n\t\t}\n\t}\n\tprint_http_header(parser);\n}\n\nvoid reset_globals()\n{\n\tconnect_handler_called = 0;\n\thandler_called = 0;\n\tdata_size = 0;\n\thttp_status = 0;\n\tg_error_code = error_code();\n}\n\nvoid run_test(std::string const& url, int size, int status, int connected\n\t, boost::optional<error_code> ec, proxy_settings const& ps)\n{\n\treset_globals();\n\n\tstd::cerr << \" ===== TESTING: \" << url << \" =====\" << std::endl;\n\n\tstd::cerr << \" expecting: size: \" << size\n\t\t<< \" status: \" << status\n\t\t<< \" connected: \" << connected\n\t\t<< \" error: \" << (ec?ec->message():\"no error\") << std::endl;\n\n\tboost::shared_ptr<http_connection> h(new http_connection(ios, cq\n\t\t, &::http_handler, true, 1024*1024, &::http_connect_handler));\n\th->get(url, seconds(1), 0, &ps);\n\tios.reset();\n\terror_code e;\n\tios.run(e);\n\n\tstd::cerr << \"connect_handler_called: \" << connect_handler_called << std::endl;\n\tstd::cerr << \"handler_called: \" << handler_called << std::endl;\n\tstd::cerr << \"status: \" << http_status << std::endl;\n\tstd::cerr << \"size: \" << data_size << std::endl;\n\tstd::cerr << \"error_code: \" << g_error_code.message() << std::endl;\n\tTEST_CHECK(connect_handler_called == connected);\n\tTEST_CHECK(handler_called == 1);\t\n\tTEST_CHECK(data_size == size || size == -1);\n\tTEST_CHECK(!ec || g_error_code == *ec);\n\tTEST_CHECK(http_status == status || status == -1);\n}\n\nvoid run_suite(std::string const& protocol, proxy_settings ps, int port)\n{\n\tif (ps.type != proxy_settings::none)\n\t{\n\t\tps.port = start_proxy(ps.type);\n\t}\n\tchar const* test_name[] = {\"no\", \"SOCKS4\", \"SOCKS5\"\n\t\t, \"SOCKS5 password protected\", \"HTTP\", \"HTTP password protected\"};\n\n\tprintf(\"\\n\\n********************** using %s proxy **********************\\n\"\n\t\t, test_name[ps.type]);\n\n\ttypedef boost::optional<error_code> err;\n\t\/\/ this requires the hosts file to be modified\n\/\/\trun_test(protocol + \":\/\/test.dns.ts:8001\/test_file\", 3216, 200, 1, error_code(), ps);\n\n\tchar url[256];\n\tsnprintf(url, sizeof(url), \"%s:\/\/127.0.0.1:%d\/\", protocol.c_str(), port);\n\tstd::string url_base(url);\n\n\trun_test(url_base + \"relative\/redirect\", 3216, 200, 2, error_code(), ps);\n\trun_test(url_base + \"redirect\", 3216, 200, 2, error_code(), ps);\n\trun_test(url_base + \"infinite_redirect\", 0, 301, 6, error_code(), ps);\n\trun_test(url_base + \"test_file\", 3216, 200, 1, error_code(), ps);\n\trun_test(url_base + \"test_file.gz\", 3216, 200, 1, error_code(), ps);\n\trun_test(url_base + \"non-existing-file\", -1, 404, 1, err(), ps);\n\n\t\/\/ only run the tests to handle NX_DOMAIN if we have a proper internet\n\t\/\/ connection that doesn't inject false DNS responses (like Comcast does)\n\thostent* h = gethostbyname(\"non-existent-domain.se\");\n\tprintf(\"gethostbyname(\\\"non-existent-domain.se\\\") = %p. h_errno = %d\\n\", h, h_errno);\n\tif (h == 0 && h_errno == HOST_NOT_FOUND)\n\t{\n\t\t\/\/ if we're going through an http proxy, we won't get the same error as if the hostname\n\t\t\/\/ resolution failed\n\t\tif ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != \"https\")\n\t\t\trun_test(protocol + \":\/\/non-existent-domain.se\/non-existing-file\", -1, 502, 1, err(), ps);\n\t\telse\n\t\t\trun_test(protocol + \":\/\/non-existent-domain.se\/non-existing-file\", -1, -1, 0, err(), ps);\n\t}\n\n\tif (ps.type != proxy_settings::none)\n\t\tstop_proxy(ps.port);\n}\n\nint test_main()\n{\n\tstd::srand(std::time(0));\n\tstd::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);\n\terror_code ec;\n\tfile test_file(\"test_file\", file::write_only, ec);\n\tTEST_CHECK(!ec);\n\tif (ec) fprintf(stderr, \"file error: %s\\n\", ec.message().c_str());\n\tfile::iovec_t b = { data_buffer, 3216};\n\ttest_file.writev(0, &b, 1, ec);\n\tTEST_CHECK(!ec);\n\tif (ec) fprintf(stderr, \"file error: %s\\n\", ec.message().c_str());\n\ttest_file.close();\n\tstd::system(\"gzip -9 -c test_file > test_file.gz\");\n\t\n\tproxy_settings ps;\n\tps.hostname = \"127.0.0.1\";\n\tps.port = 8034;\n\tps.username = \"testuser\";\n\tps.password = \"testpass\";\n\tint port = 0;\n\t\n\tport = start_web_server();\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tps.type = (proxy_settings::proxy_type)i;\n\t\trun_suite(\"http\", ps, port);\n\t}\n\tstop_web_server();\n\n#ifdef TORRENT_USE_OPENSSL\n\tport = start_web_server(true);\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tps.type = (proxy_settings::proxy_type)i;\n\t\trun_suite(\"https\", ps, port);\n\t}\n\tstop_web_server();\n#endif\n\n\t\/\/ test chunked encoding\n\tport = start_web_server(false, true);\n\tps.type = proxy_settings::none;\n\trun_suite(\"http\", ps, port);\n\n\tstop_web_server();\n\n\tstd::remove(\"test_file\");\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"mock_network_manager.hpp\"\n#include \"mock_syscall.hpp\"\n\n#include <arpa\/inet.h>\n#include <net\/if.h>\n#include <netinet\/in.h>\n#include <stdlib.h>\n\n#include <exception>\n#include <experimental\/filesystem>\n#include <sdbusplus\/bus.hpp>\n#include <xyz\/openbmc_project\/Common\/error.hpp>\n\n#include <gtest\/gtest.h>\n\nnamespace phosphor\n{\nnamespace network\n{\n\nstd::unique_ptr<Timer> refreshObjectTimer = nullptr;\nstd::unique_ptr<Timer> restartTimer = nullptr;\n\nnamespace fs = std::experimental::filesystem;\n\nclass TestNetworkManager : public testing::Test\n{\n public:\n sdbusplus::bus::bus bus;\n Manager manager;\n std::string confDir;\n TestNetworkManager() :\n bus(sdbusplus::bus::new_default()),\n manager(bus, \"\/xyz\/openbmc_test\/abc\", \"\/tmp\")\n {\n setConfDir();\n }\n\n ~TestNetworkManager()\n {\n if (confDir != \"\")\n {\n fs::remove_all(confDir);\n }\n }\n\n void setConfDir()\n {\n char tmp[] = \"\/tmp\/NetworkManager.XXXXXX\";\n confDir = mkdtemp(tmp);\n manager.setConfDir(confDir);\n }\n\n void createInterfaces()\n {\n manager.createInterfaces();\n }\n};\n\n\/\/ getifaddrs will not return any interface\nTEST_F(TestNetworkManager, NoInterface)\n{\n using namespace sdbusplus::xyz::openbmc_project::Common::Error;\n EXPECT_THROW(createInterfaces(), InternalFailure);\n}\n\n\/\/ getifaddrs returns single interface.\nTEST_F(TestNetworkManager, WithSingleInterface)\n{\n bool caughtException = false;\n try\n {\n mock_clear();\n\n \/\/ Adds the following ip in the getifaddrs list.\n mock_addIF(\"igb1\", 2);\n mock_addIP(\"igb1\", \"192.0.2.3\", \"255.255.255.128\",\n IFF_UP | IFF_RUNNING);\n\n \/\/ Now create the interfaces which will call the mocked getifaddrs\n \/\/ which returns the above interface detail.\n createInterfaces();\n EXPECT_EQ(1, manager.getInterfaceCount());\n EXPECT_EQ(true, manager.hasInterface(\"igb1\"));\n }\n catch (std::exception& e)\n {\n caughtException = true;\n }\n EXPECT_EQ(false, caughtException);\n}\n\n\/\/ getifaddrs returns two interfaces.\nTEST_F(TestNetworkManager, WithMultipleInterfaces)\n{\n try\n {\n mock_clear();\n\n mock_addIF(\"igb0\", 1);\n mock_addIP(\"igb0\", \"192.0.2.2\", \"255.255.255.128\",\n IFF_UP | IFF_RUNNING);\n\n mock_addIF(\"igb1\", 2);\n mock_addIP(\"igb1\", \"192.0.2.3\", \"255.255.255.128\",\n IFF_UP | IFF_RUNNING);\n\n createInterfaces();\n EXPECT_EQ(2, manager.getInterfaceCount());\n EXPECT_EQ(true, manager.hasInterface(\"igb0\"));\n }\n catch (std::exception& e)\n {\n }\n}\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n<commit_msg>test: Don't catch exceptions needlessly<commit_after>#include \"mock_network_manager.hpp\"\n#include \"mock_syscall.hpp\"\n\n#include <arpa\/inet.h>\n#include <net\/if.h>\n#include <netinet\/in.h>\n#include <stdlib.h>\n\n#include <exception>\n#include <experimental\/filesystem>\n#include <sdbusplus\/bus.hpp>\n#include <xyz\/openbmc_project\/Common\/error.hpp>\n\n#include <gtest\/gtest.h>\n\nnamespace phosphor\n{\nnamespace network\n{\n\nstd::unique_ptr<Timer> refreshObjectTimer = nullptr;\nstd::unique_ptr<Timer> restartTimer = nullptr;\n\nnamespace fs = std::experimental::filesystem;\n\nclass TestNetworkManager : public testing::Test\n{\n public:\n sdbusplus::bus::bus bus;\n Manager manager;\n std::string confDir;\n TestNetworkManager() :\n bus(sdbusplus::bus::new_default()),\n manager(bus, \"\/xyz\/openbmc_test\/abc\", \"\/tmp\")\n {\n setConfDir();\n }\n\n ~TestNetworkManager()\n {\n if (confDir != \"\")\n {\n fs::remove_all(confDir);\n }\n }\n\n void setConfDir()\n {\n char tmp[] = \"\/tmp\/NetworkManager.XXXXXX\";\n confDir = mkdtemp(tmp);\n manager.setConfDir(confDir);\n }\n\n void createInterfaces()\n {\n manager.createInterfaces();\n }\n};\n\n\/\/ getifaddrs will not return any interface\nTEST_F(TestNetworkManager, NoInterface)\n{\n using namespace sdbusplus::xyz::openbmc_project::Common::Error;\n EXPECT_THROW(createInterfaces(), InternalFailure);\n}\n\n\/\/ getifaddrs returns single interface.\nTEST_F(TestNetworkManager, WithSingleInterface)\n{\n mock_clear();\n\n \/\/ Adds the following ip in the getifaddrs list.\n mock_addIF(\"igb1\", 2);\n mock_addIP(\"igb1\", \"192.0.2.3\", \"255.255.255.128\", IFF_UP | IFF_RUNNING);\n\n \/\/ Now create the interfaces which will call the mocked getifaddrs\n \/\/ which returns the above interface detail.\n createInterfaces();\n EXPECT_EQ(1, manager.getInterfaceCount());\n EXPECT_EQ(true, manager.hasInterface(\"igb1\"));\n}\n\n\/\/ getifaddrs returns two interfaces.\nTEST_F(TestNetworkManager, WithMultipleInterfaces)\n{\n mock_clear();\n\n mock_addIF(\"igb0\", 1);\n mock_addIP(\"igb0\", \"192.0.2.2\", \"255.255.255.128\", IFF_UP | IFF_RUNNING);\n\n mock_addIF(\"igb1\", 2);\n mock_addIP(\"igb1\", \"192.0.2.3\", \"255.255.255.128\", IFF_UP | IFF_RUNNING);\n\n createInterfaces();\n EXPECT_EQ(2, manager.getInterfaceCount());\n EXPECT_EQ(true, manager.hasInterface(\"igb0\"));\n EXPECT_EQ(true, manager.hasInterface(\"igb1\"));\n}\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n<|endoftext|>"} {"text":"<commit_before>#include \"utils\/test_main.hxx\"\n\n#include \"dcc\/Packet.hxx\"\n#include \"dcc\/Loco.hxx\"\n#include \"dcc\/UpdateLoop.hxx\"\n\nusing ::testing::StrictMock;\nusing ::testing::ElementsAre;\nusing ::testing::SaveArg;\nusing ::testing::Mock;\nusing ::testing::_;\n\nnamespace dcc {\n\nclass PacketTest : public ::testing::Test {\nprotected:\n vector<uint8_t> get_packet() {\n return vector<uint8_t>(pkt_.payload + 0, pkt_.payload + pkt_.dlc);\n }\n\n vector<uint8_t> packet(const std::initializer_list<int>& data) {\n vector<uint8_t> v;\n for (int b : data) {\n v.push_back(b & 0xff);\n }\n return v;\n }\n\n Packet pkt_;\n};\n\nTEST_F(PacketTest, ChecksumRegular) {\n pkt_.dlc = 3;\n pkt_.payload[0] = 0xA0;\n pkt_.payload[1] = 0x53;\n pkt_.payload[2] = 0x0F;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(4, pkt_.dlc);\n EXPECT_EQ(0xFC, pkt_.payload[3]);\n}\n\nTEST_F(PacketTest, ChecksumEmpty) {\n pkt_.dlc = 0;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(1, pkt_.dlc);\n EXPECT_EQ(0, pkt_.payload[3]);\n}\n\nTEST_F(PacketTest, ChecksumFF) {\n pkt_.dlc = 3;\n pkt_.payload[0] = 0xFF;\n pkt_.payload[1] = 0xFF;\n pkt_.payload[2] = 0xFF;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(4, pkt_.dlc);\n EXPECT_EQ(0xFF, pkt_.payload[3]);\n}\n\n\nTEST_F(PacketTest, DccSpeed28) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 6);\n EXPECT_THAT(get_packet(), ElementsAre(0b00110111, 0b01110100, 0b01000011));\n}\n\nTEST_F(PacketTest, DccSpeed28_zero) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 0);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100000, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_reversezero) {\n pkt_.set_dcc_speed28(DccShortAddress(55), false, 0);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01000000, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_estop) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, Packet::EMERGENCY_STOP);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100001, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_step123) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 1);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100010, _));\n\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 2);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01110010, _));\n\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 3);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100011, _));\n}\n\nTEST_F(PacketTest, DccIdle) {\n pkt_.set_dcc_idle();\n EXPECT_THAT(get_packet(), ElementsAre(0xff, 0, 0xff));\n}\n\nTEST_F(PacketTest, DccReset) {\n pkt_.set_dcc_reset_all_decoders();\n EXPECT_THAT(get_packet(), ElementsAre(0, 0, 0));\n}\n\nclass MockUpdateLoop;\nMockUpdateLoop* g_update_loop = nullptr;\n\nclass MockUpdateLoop {\npublic:\n MockUpdateLoop() {\n HASSERT(!g_update_loop);\n g_update_loop = this;\n }\n ~MockUpdateLoop() {\n g_update_loop = nullptr;\n }\n MOCK_METHOD2(send_update, void(PacketSource* source, unsigned code));\n};\n\nvoid packet_processor_notify_update(PacketSource* source, unsigned code) {\n HASSERT(g_update_loop);\n g_update_loop->send_update(source, code);\n}\n\nclass Train28Test : public PacketTest {\nprotected:\n Train28Test()\n : code_(0), train_(DccShortAddress(55)) {}\n\n void do_refresh() {\n new (&pkt_) Packet();\n train_.get_next_packet(0, &pkt_);\n }\n\n void do_callback() {\n Mock::VerifyAndClear(&loop_);\n new (&pkt_) Packet();\n train_.get_next_packet(code_, &pkt_);\n code_ = 0;\n }\n\n unsigned code_;\n StrictMock<MockUpdateLoop> loop_;\n Dcc28Train train_;\n};\n\nTEST_F(Train28Test, DefaultPacket) {\n do_refresh();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100000, _));\n}\n\nTEST_F(Train28Test, SetSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).WillOnce(SaveArg<1>(&code_));\n train_.set_speed(SpeedType(37.5));\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01110011, _));\n}\n\n} \/\/ namespace dcc\n<commit_msg>Adds more tests to speed setting functions.<commit_after>#include \"utils\/test_main.hxx\"\n\n#include \"dcc\/Packet.hxx\"\n#include \"dcc\/Loco.hxx\"\n#include \"dcc\/UpdateLoop.hxx\"\n\nusing ::testing::StrictMock;\nusing ::testing::ElementsAre;\nusing ::testing::SaveArg;\nusing ::testing::Mock;\nusing ::testing::_;\n\nnamespace dcc {\n\nclass PacketTest : public ::testing::Test {\nprotected:\n vector<uint8_t> get_packet() {\n return vector<uint8_t>(pkt_.payload + 0, pkt_.payload + pkt_.dlc);\n }\n\n vector<uint8_t> packet(const std::initializer_list<int>& data) {\n vector<uint8_t> v;\n for (int b : data) {\n v.push_back(b & 0xff);\n }\n return v;\n }\n\n Packet pkt_;\n};\n\nTEST_F(PacketTest, ChecksumRegular) {\n pkt_.dlc = 3;\n pkt_.payload[0] = 0xA0;\n pkt_.payload[1] = 0x53;\n pkt_.payload[2] = 0x0F;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(4, pkt_.dlc);\n EXPECT_EQ(0xFC, pkt_.payload[3]);\n}\n\nTEST_F(PacketTest, ChecksumEmpty) {\n pkt_.dlc = 0;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(1, pkt_.dlc);\n EXPECT_EQ(0, pkt_.payload[3]);\n}\n\nTEST_F(PacketTest, ChecksumFF) {\n pkt_.dlc = 3;\n pkt_.payload[0] = 0xFF;\n pkt_.payload[1] = 0xFF;\n pkt_.payload[2] = 0xFF;\n pkt_.add_dcc_checksum();\n EXPECT_EQ(4, pkt_.dlc);\n EXPECT_EQ(0xFF, pkt_.payload[3]);\n}\n\n\nTEST_F(PacketTest, DccSpeed28) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 6);\n EXPECT_THAT(get_packet(), ElementsAre(0b00110111, 0b01110100, 0b01000011));\n}\n\nTEST_F(PacketTest, DccSpeed28_zero) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 0);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100000, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_reversezero) {\n pkt_.set_dcc_speed28(DccShortAddress(55), false, 0);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01000000, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_estop) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, Packet::EMERGENCY_STOP);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100001, _));\n}\n\nTEST_F(PacketTest, DccSpeed28_step123) {\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 1);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100010, _));\n\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 2);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01110010, _));\n\n pkt_.set_dcc_speed28(DccShortAddress(55), true, 3);\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100011, _));\n}\n\nTEST_F(PacketTest, DccIdle) {\n pkt_.set_dcc_idle();\n EXPECT_THAT(get_packet(), ElementsAre(0xff, 0, 0xff));\n}\n\nTEST_F(PacketTest, DccReset) {\n pkt_.set_dcc_reset_all_decoders();\n EXPECT_THAT(get_packet(), ElementsAre(0, 0, 0));\n}\n\nclass MockUpdateLoop;\nMockUpdateLoop* g_update_loop = nullptr;\n\nclass MockUpdateLoop {\npublic:\n MockUpdateLoop() {\n HASSERT(!g_update_loop);\n g_update_loop = this;\n }\n ~MockUpdateLoop() {\n g_update_loop = nullptr;\n }\n MOCK_METHOD2(send_update, void(PacketSource* source, unsigned code));\n};\n\nvoid packet_processor_notify_update(PacketSource* source, unsigned code) {\n HASSERT(g_update_loop);\n g_update_loop->send_update(source, code);\n}\n\nclass Train28Test : public PacketTest {\nprotected:\n Train28Test()\n : code_(0), train_(DccShortAddress(55)) {}\n\n void do_refresh() {\n new (&pkt_) Packet();\n train_.get_next_packet(0, &pkt_);\n }\n\n void do_callback() {\n Mock::VerifyAndClear(&loop_);\n new (&pkt_) Packet();\n train_.get_next_packet(code_, &pkt_);\n code_ = 0;\n }\n\n unsigned code_;\n StrictMock<MockUpdateLoop> loop_;\n Dcc28Train train_;\n};\n\nTEST_F(Train28Test, DefaultPacket) {\n do_refresh();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100000, _));\n}\n\nTEST_F(Train28Test, SetSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).WillOnce(SaveArg<1>(&code_));\n train_.set_speed(SpeedType(37.5));\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01101011, _));\n}\n\nTEST_F(Train28Test, MaxSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).WillOnce(SaveArg<1>(&code_));\n SpeedType s;\n s.set_mph(128);\n train_.set_speed(s);\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01111111, _));\n}\n\nTEST_F(Train28Test, BelowMaxSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).WillOnce(SaveArg<1>(&code_));\n SpeedType s;\n s.set_mph(123.42);\n train_.set_speed(s);\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01101111, _));\n}\n\nTEST_F(Train28Test, MinSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).WillOnce(SaveArg<1>(&code_));\n SpeedType s;\n \/\/ Even the smallest nonzero velocity should set the train in motion. \n s.set_mph(0.001);\n train_.set_speed(s);\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100010, _));\n\n SpeedType ss = train_.get_speed();\n EXPECT_NEAR(0.001, ss.mph(), 1e-7);\n}\n\nTEST_F(Train28Test, ZeroSpeed) {\n EXPECT_CALL(loop_, send_update(&train_, _)).Times(2).WillRepeatedly(SaveArg<1>(&code_));\n SpeedType s;\n \/\/ Even the smallest nonzero velocity should set the train in motion. \n s.set_mph(0.001);\n train_.set_speed(s);\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100010, _));\n\n s.set_mph(0);\n train_.set_speed(s);\n do_callback();\n EXPECT_THAT(get_packet(), ElementsAre(55, 0b01100000, _));\n}\n\n} \/\/ namespace dcc\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cstdint>\n#include <cstring> \/\/ memcpy\n\n#include <visionaray\/math\/math.h>\n\n#include <gtest\/gtest.h>\n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test snorm initialization (single values, arrays)\n\/\/\n\nTEST(Snorm, Initialization)\n{\n \/\/ Some convenience -----------------------------------\n\n static const int8_t max8 = numeric_limits<int8_t>::max();\n static const int16_t max16 = numeric_limits<int16_t>::max();\n static const int32_t max32 = numeric_limits<int32_t>::max();\n\n static const int8_t low8 = numeric_limits<int8_t>::lowest();\n static const int16_t low16 = numeric_limits<int16_t>::lowest();\n static const int32_t low32 = numeric_limits<int32_t>::lowest();\n\n\n \/\/ Test initialization --------------------------------\n\n snorm< 8> sn8;\n snorm<16> sn16;\n snorm<32> sn32;\n snorm< 8> sn8s[4];\n snorm<16> sn16s[4];\n snorm<32> sn32s[4];\n\n \/\/ init with -1\n\n sn8 = -1.0f;\n sn16 = -1.0f;\n sn32 = -1.0f;\n\n\/\/ EXPECT_EQ(int8_t(sn8), low8); \/\/ TODO: why does intX_t(snX) yield lowX + 1?? \n\/\/ EXPECT_EQ(int16_t(sn16), low16); \/\/ TODO: why does intX_t(snX) yield lowX + 1??\n\/\/ EXPECT_EQ(int32_t(sn32), low32); \/\/ TODO: why does intX_t(snX) yield lowX + 1??\n\n EXPECT_FLOAT_EQ(float(sn8), -1.0f);\n EXPECT_FLOAT_EQ(float(sn16), -1.0f);\n EXPECT_FLOAT_EQ(float(sn32), -1.0f);\n\n\n \/\/ init with 1\n\n sn8 = 1.0f;\n sn16 = 1.0f;\n sn32 = 1.0f;\n\n EXPECT_EQ(int8_t(sn8), max8);\n EXPECT_EQ(int16_t(sn16), max16);\n EXPECT_EQ(int32_t(sn32), max32);\n\n EXPECT_FLOAT_EQ(float(sn8), 1.0f);\n EXPECT_FLOAT_EQ(float(sn16), 1.0f);\n EXPECT_FLOAT_EQ(float(sn32), 1.0f);\n\n\n \/\/ init with byte arrays\n\n int8_t arr8[] = { low8, 0, int8_t(max8 \/ 2), max8 };\n int16_t arr16[] = { low16, 0, int8_t(max16 \/ 2), max16 };\n int32_t arr32[] = { low32, 0, int8_t(max32 \/ 2), max32 };\n\n std::memcpy(sn8s, arr8, sizeof(arr8));\n std::memcpy(sn16s, arr16, sizeof(arr16));\n std::memcpy(sn32s, arr32, sizeof(arr32));\n\n for (int i = 0; i < 4; ++i)\n {\n EXPECT_EQ(int8_t(sn8s[i]), arr8[i]);\n EXPECT_EQ(int16_t(sn16s[i]), arr16[i]);\n EXPECT_EQ(int32_t(sn32s[i]), arr32[i]);\n\n\/\/ EXPECT_FLOAT_EQ(float(sn8s[i]), static_cast<float>(arr8[i]) \/ max8); \/\/ TODO\n\/\/ EXPECT_FLOAT_EQ(float(sn16s[i]), static_cast<float>(arr16[i]) \/ max8); \/\/ TODO\n\/\/ EXPECT_FLOAT_EQ(float(sn32s[i]), static_cast<float>(arr32[i]) \/ max8); \/\/ TODO\n }\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test comparison operators\n\/\/\n\ntemplate <unsigned Bits>\nstatic void test_cmp()\n{\n \/\/ negative numbers -----------------------------------\n\n snorm<Bits> a;\n snorm<Bits> b;\n\n a = -1.0f;\n b = -0.5f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_TRUE( a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_FALSE(a >= b);\n\n a = -0.5f;\n b = -1.0f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_FALSE(a < b);\n EXPECT_FALSE(a <= b);\n EXPECT_TRUE( a > b);\n EXPECT_TRUE( a >= b);\n\n a = -1.0f;\n b = -1.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n\n \/\/ all zeros ------------------------------------------\n\n a = 0.0f;\n b = 0.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n\n \/\/ positive numbers -----------------------------------\n\n a = 0.5f;\n b = 1.0f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_TRUE( a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_FALSE(a >= b);\n\n a = 1.0f;\n b = 0.5f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_FALSE(a < b);\n EXPECT_FALSE(a <= b);\n EXPECT_TRUE( a > b);\n EXPECT_TRUE( a >= b);\n\n a = 1.0f;\n b = 1.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n}\n\nTEST(Snorm, Comparisons)\n{\n test_cmp< 8>();\n test_cmp<16>();\n test_cmp<32>();\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test numeric limits\n\/\/ All representations (norm, int, float)\n\/\/\n\nTEST(Snorm, NumericLimits)\n{\n \/\/ Some convenience -----------------------------------\n\n static const int8_t int8_max = numeric_limits<int8_t>::max();\n static const int16_t int16_max = numeric_limits<int16_t>::max();\n static const int32_t int32_max = numeric_limits<int32_t>::max();\n\n\/\/ static const int8_t int8_low = numeric_limits<int8_t>::lowest();\n\/\/ static const int16_t int16_low = numeric_limits<int16_t>::lowest();\n\/\/ static const int32_t int32_low = numeric_limits<int32_t>::lowest();\n\/\/\n\/\/ static const int8_t int8_min = numeric_limits<int8_t>::min();\n\/\/ static const int16_t int16_min = numeric_limits<int16_t>::min();\n\/\/ static const int32_t int32_min = numeric_limits<int32_t>::min();\n\n\n \/\/ Normalized reprentation ----------------------------\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::max() == snorm< 8>(1.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::max() == snorm<16>(1.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::max() == snorm<32>(1.0f));\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::lowest() == snorm< 8>(-1.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::lowest() == snorm<16>(-1.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::lowest() == snorm<32>(-1.0f));\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::min() == snorm< 8>(0.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::min() == snorm<16>(0.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::min() == snorm<32>(0.0f));\n\n\n \/\/ Integer representation -----------------------------\n\n EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::max()), int8_max);\n EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::max()), int16_max);\n EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::max()), int32_max);\n\n\/\/ EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::lowest()), int8_low);\n\/\/ EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::lowest()), int16_low);\n\/\/ EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::lowest()), int32_low);\n\/\/\n\/\/ EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::min()), int8_min);\n\/\/ EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::min()), int16_min);\n\/\/ EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::min()), int32_min);\n\n\n \/\/ Float representation -------------------------------\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::max()), 1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::max()), 1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::max()), 1.0f);\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::lowest()), -1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::lowest()), -1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::lowest()), -1.0f);\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::min()), 0.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::min()), 0.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::min()), 0.0f);\n}\n<commit_msg>Enable (more) snorm unit tests related to INT_MIN<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <cstdint>\n#include <cstring> \/\/ memcpy\n\n#include <visionaray\/math\/math.h>\n\n#include <gtest\/gtest.h>\n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test snorm initialization (single values, arrays)\n\/\/\n\nTEST(Snorm, Initialization)\n{\n \/\/ Some convenience -----------------------------------\n\n static const int8_t max8 = numeric_limits<int8_t>::max();\n static const int16_t max16 = numeric_limits<int16_t>::max();\n static const int32_t max32 = numeric_limits<int32_t>::max();\n\n \/\/\n \/\/ cf. OpenGL 4.4, 2.3.4.1, p. 23:\n \/\/\n \/\/ Only the range [−2^(b−1) + 1, 2^(b−1) − 1] is used to represent signed fixed-point\n \/\/ values in the range [−1, 1]. For example, if b = 8, then the integer value −127\n \/\/ corresponds to −1.0 and the value 127 corresponds to 1.0.\n \/\/\n\n static const int8_t low8 = numeric_limits<int8_t>::lowest() + 1;\n static const int16_t low16 = numeric_limits<int16_t>::lowest() + 1;\n static const int32_t low32 = numeric_limits<int32_t>::lowest() + 1;\n\n\n \/\/ Test initialization --------------------------------\n\n snorm< 8> sn8;\n snorm<16> sn16;\n snorm<32> sn32;\n snorm< 8> sn8s[4];\n snorm<16> sn16s[4];\n snorm<32> sn32s[4];\n\n \/\/ init with -1\n\n sn8 = -1.0f;\n sn16 = -1.0f;\n sn32 = -1.0f;\n\n EXPECT_EQ(int8_t(sn8), low8);\n EXPECT_EQ(int16_t(sn16), low16);\n EXPECT_EQ(int32_t(sn32), low32);\n\n EXPECT_FLOAT_EQ(float(sn8), -1.0f);\n EXPECT_FLOAT_EQ(float(sn16), -1.0f);\n EXPECT_FLOAT_EQ(float(sn32), -1.0f);\n\n\n \/\/ init with 1\n\n sn8 = 1.0f;\n sn16 = 1.0f;\n sn32 = 1.0f;\n\n EXPECT_EQ(int8_t(sn8), max8);\n EXPECT_EQ(int16_t(sn16), max16);\n EXPECT_EQ(int32_t(sn32), max32);\n\n EXPECT_FLOAT_EQ(float(sn8), 1.0f);\n EXPECT_FLOAT_EQ(float(sn16), 1.0f);\n EXPECT_FLOAT_EQ(float(sn32), 1.0f);\n\n\n \/\/ init with byte arrays\n\n int8_t arr8[] = { low8, 0, int8_t(max8 \/ 2), max8 };\n int16_t arr16[] = { low16, 0, int8_t(max16 \/ 2), max16 };\n int32_t arr32[] = { low32, 0, int8_t(max32 \/ 2), max32 };\n\n std::memcpy(sn8s, arr8, sizeof(arr8));\n std::memcpy(sn16s, arr16, sizeof(arr16));\n std::memcpy(sn32s, arr32, sizeof(arr32));\n\n for (int i = 0; i < 4; ++i)\n {\n EXPECT_EQ(int8_t(sn8s[i]), arr8[i]);\n EXPECT_EQ(int16_t(sn16s[i]), arr16[i]);\n EXPECT_EQ(int32_t(sn32s[i]), arr32[i]);\n\n\/\/ EXPECT_FLOAT_EQ(float(sn8s[i]), static_cast<float>(arr8[i]) \/ max8);\n\/\/ EXPECT_FLOAT_EQ(float(sn16s[i]), static_cast<float>(arr16[i]) \/ max8);\n\/\/ EXPECT_FLOAT_EQ(float(sn32s[i]), static_cast<float>(arr32[i]) \/ max8);\n }\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test comparison operators\n\/\/\n\ntemplate <unsigned Bits>\nstatic void test_cmp()\n{\n \/\/ negative numbers -----------------------------------\n\n snorm<Bits> a;\n snorm<Bits> b;\n\n a = -1.0f;\n b = -0.5f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_TRUE( a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_FALSE(a >= b);\n\n a = -0.5f;\n b = -1.0f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_FALSE(a < b);\n EXPECT_FALSE(a <= b);\n EXPECT_TRUE( a > b);\n EXPECT_TRUE( a >= b);\n\n a = -1.0f;\n b = -1.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n\n \/\/ all zeros ------------------------------------------\n\n a = 0.0f;\n b = 0.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n\n \/\/ positive numbers -----------------------------------\n\n a = 0.5f;\n b = 1.0f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_TRUE( a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_FALSE(a >= b);\n\n a = 1.0f;\n b = 0.5f;\n\n EXPECT_FALSE(a == b);\n EXPECT_TRUE( a != b);\n EXPECT_FALSE(a < b);\n EXPECT_FALSE(a <= b);\n EXPECT_TRUE( a > b);\n EXPECT_TRUE( a >= b);\n\n a = 1.0f;\n b = 1.0f;\n\n EXPECT_TRUE( a == b);\n EXPECT_FALSE(a != b);\n EXPECT_FALSE(a < b);\n EXPECT_TRUE( a <= b);\n EXPECT_FALSE(a > b);\n EXPECT_TRUE( a >= b);\n}\n\nTEST(Snorm, Comparisons)\n{\n test_cmp< 8>();\n test_cmp<16>();\n test_cmp<32>();\n}\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Test numeric limits\n\/\/ All representations (norm, int, float)\n\/\/\n\nTEST(Snorm, NumericLimits)\n{\n \/\/ Some convenience -----------------------------------\n\n static const int8_t int8_max = numeric_limits<int8_t>::max();\n static const int16_t int16_max = numeric_limits<int16_t>::max();\n static const int32_t int32_max = numeric_limits<int32_t>::max();\n\n \/\/\n \/\/ cf. OpenGL 4.4, 2.3.4.1, p. 23:\n \/\/\n \/\/ Only the range [−2^(b−1) + 1, 2^(b−1) − 1] is used to represent signed fixed-point\n \/\/ values in the range [−1, 1]. For example, if b = 8, then the integer value −127\n \/\/ corresponds to −1.0 and the value 127 corresponds to 1.0.\n \/\/\n\n static const int8_t int8_low = numeric_limits<int8_t>::lowest() + 1;\n static const int16_t int16_low = numeric_limits<int16_t>::lowest() + 1;\n static const int32_t int32_low = numeric_limits<int32_t>::lowest() + 1;\n\n\/\/ static const int8_t int8_min = numeric_limits<int8_t>::min();\n\/\/ static const int16_t int16_min = numeric_limits<int16_t>::min();\n\/\/ static const int32_t int32_min = numeric_limits<int32_t>::min();\n\n\n \/\/ Normalized reprentation ----------------------------\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::max() == snorm< 8>(1.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::max() == snorm<16>(1.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::max() == snorm<32>(1.0f));\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::lowest() == snorm< 8>(-1.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::lowest() == snorm<16>(-1.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::lowest() == snorm<32>(-1.0f));\n\n EXPECT_TRUE(numeric_limits<snorm< 8>>::min() == snorm< 8>(0.0f));\n EXPECT_TRUE(numeric_limits<snorm<16>>::min() == snorm<16>(0.0f));\n EXPECT_TRUE(numeric_limits<snorm<32>>::min() == snorm<32>(0.0f));\n\n\n \/\/ Integer representation -----------------------------\n\n EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::max()), int8_max);\n EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::max()), int16_max);\n EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::max()), int32_max);\n\n EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::lowest()), int8_low);\n EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::lowest()), int16_low);\n EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::lowest()), int32_low);\n\n\/\/ EXPECT_EQ(static_cast< int8_t>(numeric_limits<snorm< 8>>::min()), int8_min);\n\/\/ EXPECT_EQ(static_cast<int16_t>(numeric_limits<snorm<16>>::min()), int16_min);\n\/\/ EXPECT_EQ(static_cast<int32_t>(numeric_limits<snorm<32>>::min()), int32_min);\n\n\n \/\/ Float representation -------------------------------\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::max()), 1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::max()), 1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::max()), 1.0f);\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::lowest()), -1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::lowest()), -1.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::lowest()), -1.0f);\n\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm< 8>>::min()), 0.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<16>>::min()), 0.0f);\n EXPECT_FLOAT_EQ(static_cast<float>(numeric_limits<snorm<32>>::min()), 0.0f);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n\n\/\/ Loriano: let's try Armadillo quick code \n#include <armadillo>\n\n#define ENTDIM 8\n#define COORDIM (ENTDIM-2)\n#define PARAMDIM 5\n\nnamespace \n{\n int numofline (const char * fname) \n { \n int number_of_lines = 0;\n std::string line;\n std::ifstream myfile(fname);\n \n while (std::getline(myfile, line))\n ++number_of_lines;\n\n myfile.close();\n \n return number_of_lines;\n }\n}\n\nint main (int argc, char ** argv)\n{\n if (argc != 2)\n {\n std::cerr << \"usage: \" << argv[0] << \" coordinatesfile \" << std::endl;\n return 1;\n }\n\n int num_of_line = numofline(argv[1]);\n std::cout << \"file has \" << num_of_line << \" line \" << std::endl;\n int num_of_ent = (num_of_line-1)\/ENTDIM;\n std::cout << \" \" << num_of_ent << \" entries \" << std::endl;\n\n \/\/ non perfomante ma easy to go\n arma::mat param = arma::zeros<arma::mat>(num_of_ent,PARAMDIM);\n arma::mat coord = arma::zeros<arma::mat>(num_of_ent,3*COORDIM);\n\n \/\/ leggere file coordinate tracce simulate plus parametri\n std::string line;\n std::ifstream mytfp;\n mytfp.open (argv[1], std::ios::in);\n\n std::getline (mytfp, line);\n \/\/std::cout << line << std::endl;\n \n for (int i = 0; i < num_of_ent; ++i)\n {\n int fake1, fake2;\n mytfp >> fake1 >> fake2 ;\n#ifdef DEBUG \n std::cout << fake1 << \" \" << fake2 << std::endl;\n#endif\n for (int j = 0; j < COORDIM; ++j)\n {\n int a, b, c;\n mytfp >> coord(i, j*3) >> \n coord(i, j*3+1) >> \n coord(i, j*3+2) >> \n a >> b >> c; \n }\n mytfp >> param(i,0) >> \n param(i,1) >> \n param(i,2) >> \n param(i,3) >> \n param(i,4);\n }\n\n mytfp.close();\n\n#ifdef DEBUG\n for (int i = 0; i < num_of_ent; ++i)\n {\n for (int j = 0; j < COORDIM; ++j)\n {\n std::cout << coord(i, j*3) << \" \" <<\n coord(i, j*3+1) << \" \" <<\n coord(i, j*3+2) << std::endl;\n }\n std::cout << param(i,0) << \" \" <<\n param(i,1) << \" \" <<\n param(i,2) << \" \" <<\n param(i,3) << \" \" <<\n param(i,4) << std::endl;\n }\n#endif\n \n arma::mat coeff;\n arma::mat score;\n arma::vec latent;\n\n arma::princomp(coeff, score, latent, coord);\n\n std::cout << \"Eigenvalue: \" << std::endl;\n std::cout << latent;\n\n std::cout << \"Eigenvector: \" << std::endl;\n std::cout << score << std::endl;\n\n double sum = 1.0e0;\n arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM);\n arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n\n hca = arma::cov(coord);\n\n \/* correlation matrix ricorda su dati standardizzati coincide con la matrice \n * di covarianza : \n * z = x -<x> \/ sigma *\/\n arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<(3*COORDIM); ++j)\n corr(i,j) = hca(i,j) \/ sqrt(hca(i,i)*hca(j,j));\n\n std::cout << \"Correlation matrix: \" << std::endl;\n std::cout << corr;\n\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=i+1; j<(3*COORDIM); ++j)\n if (hca(i,j) != hca(j,i))\n std::cout << i << \" \" << j << \" \" << \n hca(i,j) << \" ERROR\" << std::endl;;\n\n arma::vec eigval = arma::zeros<arma::mat>(3*COORDIM);\n arma::mat eigvec = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n\n arma::eig_sym(eigval, eigvec, hca);\n\n double totval = 0.0e0;\n for (int i=0; i<(3*COORDIM); ++i)\n totval += eigval(i);\n\n std::cout << \"Eigenvalues: \" << std::endl;\n int j = 1;\n double totvar = 0.0e0; \n for (int i=(3*COORDIM-1); i>=0; --i)\n {\n if (j <= PARAMDIM)\n totvar += 100.0e0*(eigval(i)\/totval);\n ++j;\n\n std::cout << i+1 << \" ==> \" << 100.0e0*(eigval(i)\/totval) \n << \" ==> \" << eigval(i) << std::endl;\n\n }\n std::cout << \"PARAMDIM eigenvalues: \" << totvar << std::endl;\n\n arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n hcai = hca.i(); \n\n\/\/#ifdef DEBUG\n \/\/std::cout << hca * hcai ;\n\/\/#endif\n \n \/\/ and so on ...\n arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM);\n arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM);\n\n coordm.fill(0.0e0);\n sum = 1.0e0;\n \n for (int l=0; l<num_of_ent; ++l) \n {\n sum += 1.0e0;\n for (int i=0; i<(3*COORDIM); ++i)\n coordm(i) += (coord(l,i)-coordm(i))\/sum;\n\n for (int i=0; i<PARAMDIM; ++i)\n paramm(i) += (param(l,i)-paramm(i))\/sum;\n\n for (int i=0; i<(3*COORDIM); ++i)\n {\n for (int j=0; j<PARAMDIM; ++j)\n {\n hcap(i,j) += ((coord(l,i) - coordm(i))*\n (param(l,j) - paramm(j))-\n (sum-1.0e0)*hcap(i,j)\/sum)\/(sum-1.0e0);\n }\n }\n }\n\n \/* correlation matrix\n double pstdev[PARAMDIM];\n for (int i=0; i<PARAMDIM; ++i)\n {\n arma::running_stat<double> stats;\n\n for (int l=0; l<num_of_ent; ++l) \n stats(param(l,i));\n\n#ifdef DEBUG\n std::cout << \"mean = \" << stats.mean() << std::endl;\n std::cout << \" \" << paramm(i) << std::endl;\n std::cout << \"stdev = \" << stats.stddev() << std::endl;\n#endif\n\n pstdev[i] = stats.stddev();\n }\n\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<PARAMDIM; ++j)\n hcap(i,j) = hcap(i,j) \/ (cstdev[i]*pstdev[j]);\n *\/\n\n arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM);\n\n for (int i=0; i<PARAMDIM; ++i)\n for (int l=0; l<(3*COORDIM); ++l)\n for (int m=0; m<(3*COORDIM); ++m)\n cmtx(i,l) += hcai(l,m) * hcap (m,i);\n\n#ifdef DEBUG\n std::cout << \"C matrix: \" << std::endl;\n std::cout << cmtx;\n#endif \n\n arma::mat q = arma::zeros<arma::mat>(PARAMDIM);\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n q(i) = paramm(i);\n for (int l=0; l<(3*COORDIM); ++l)\n q(i) -= cmtx(i,l)*coordm[l];\n }\n\n#ifdef DEBUG\n std::cout << \"Q vector: \" << std::endl;\n for (int i=0; i<PARAMDIM; ++i)\n std::cout << q(i) << std::endl;\n#endif\n\n arma::mat a = arma::zeros<arma::mat>((3*COORDIM),(3*COORDIM));\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<(3*COORDIM); ++j)\n a(i,j) = eigvec(i,j)\/sqrt(eigval(i));\n\n arma::mat k = arma::zeros<arma::mat>(3*COORDIM);\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<(3*COORDIM); ++j)\n k(i) += a(i,j)*coordm(j);\n\n\n \/\/test back\n arma::running_stat<double> chi2stats;\n arma::running_stat<double> pc[PARAMDIM];\n for (int l=0; l<num_of_ent; ++l)\n {\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n double p = q(i);\n for (int k=0; k<(3*COORDIM); ++k)\n p += cmtx(i,k)*coord(l,k);\n \n pc[i](fabs(p - param(l,i))\/(fabs(p + param(l,i))\/2.0));\n }\n\n \/* chi**2 *\/\n double chi2 = 0.0e0;\n for (int i=0; i<(3*COORDIM)-PARAMDIM; ++i)\n {\n double v = k(i);\n \n for (int j=0; j<(3*COORDIM); ++j)\n v += a(i,j) * coord(l,j);\n \n chi2 += (v*v);\n } \n chi2stats(chi2);\n }\n std::cout << \"chi2 mean = \" << chi2stats.mean() << std::endl;\n std::cout << \"chi2 stdev = \" << chi2stats.stddev() << std::endl;\n std::cout << \"chi2 min = \" << chi2stats.min() << std::endl;\n std::cout << \"chi2 max = \" << chi2stats.max() << std::endl;\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n std::cout << pc[i].mean() << \" \" << pc[i].stddev() << std::endl;\n\n arma::running_stat<double> stats;\n\n for (int l=0; l<num_of_ent; ++l) \n stats(param(l,i));\n\n std::cout << \" mean = \" << stats.mean() << std::endl;\n std::cout << \" stdev = \" << stats.stddev() << std::endl;\n std::cout << \" min = \" << stats.min() << std::endl;\n std::cout << \" max = \" << stats.max() << std::endl;\n }\n\n return 0;\n}\n<commit_msg>add chi2 as eq 10 an removed some non arma style code<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n\n\/\/ Loriano: let's try Armadillo quick code \n#include <armadillo>\n\n#define ENTDIM 8\n#define COORDIM (ENTDIM-2)\n#define PARAMDIM 5\n\nnamespace \n{\n int numofline (const char * fname) \n { \n int number_of_lines = 0;\n std::string line;\n std::ifstream myfile(fname);\n \n while (std::getline(myfile, line))\n ++number_of_lines;\n\n myfile.close();\n \n return number_of_lines;\n }\n}\n\nint main (int argc, char ** argv)\n{\n if (argc != 2)\n {\n std::cerr << \"usage: \" << argv[0] << \" coordinatesfile \" << std::endl;\n return 1;\n }\n\n int num_of_line = numofline(argv[1]);\n std::cout << \"file has \" << num_of_line << \" line \" << std::endl;\n int num_of_ent = (num_of_line-1)\/ENTDIM;\n std::cout << \" \" << num_of_ent << \" entries \" << std::endl;\n\n \/\/ non perfomante ma easy to go\n arma::mat param = arma::zeros<arma::mat>(num_of_ent,PARAMDIM);\n arma::mat coord = arma::zeros<arma::mat>(num_of_ent,3*COORDIM);\n\n \/\/ leggere file coordinate tracce simulate plus parametri\n std::string line;\n std::ifstream mytfp;\n mytfp.open (argv[1], std::ios::in);\n\n std::getline (mytfp, line);\n \/\/std::cout << line << std::endl;\n \n for (int i = 0; i < num_of_ent; ++i)\n {\n int fake1, fake2;\n mytfp >> fake1 >> fake2 ;\n#ifdef DEBUG \n std::cout << fake1 << \" \" << fake2 << std::endl;\n#endif\n for (int j = 0; j < COORDIM; ++j)\n {\n int a, b, c;\n mytfp >> coord(i, j*3) >> \n coord(i, j*3+1) >> \n coord(i, j*3+2) >> \n a >> b >> c; \n }\n mytfp >> param(i,0) >> \n param(i,1) >> \n param(i,2) >> \n param(i,3) >> \n param(i,4);\n }\n\n mytfp.close();\n\n#ifdef DEBUG\n for (int i = 0; i < num_of_ent; ++i)\n {\n for (int j = 0; j < COORDIM; ++j)\n {\n std::cout << coord(i, j*3) << \" \" <<\n coord(i, j*3+1) << \" \" <<\n coord(i, j*3+2) << std::endl;\n }\n std::cout << param(i,0) << \" \" <<\n param(i,1) << \" \" <<\n param(i,2) << \" \" <<\n param(i,3) << \" \" <<\n param(i,4) << std::endl;\n }\n#endif\n \n \/\/ projection \n arma::mat score;\n \/\/ ordered \n arma::vec eigval;\n \/\/ by row or by column ?\n arma::mat eigvec;\n\n arma::princomp(eigvec, score, eigval, coord);\n\n double totval = 0.0e0;\n for (int i=0; i<(3*COORDIM); ++i)\n totval += eigval(i);\n\n std::cout << \"Eigenvalues: \" << std::endl;\n double totvar = 0.0e0; \n for (int i=0; i<(3*COORDIM); ++i)\n {\n if (i < PARAMDIM)\n totvar += 100.0e0*(eigval(i)\/totval);\n\n std::cout << i+1 << \" ==> \" << 100.0e0*(eigval(i)\/totval) \n << \"% value: \" << eigval(i) << std::endl;\n }\n std::cout << \"PARAMDIM eigenvalues: \" << totvar << std::endl;\n\n arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n v = arma::cov(coord);\n\n#ifdef DEBUG\n \/* correlation matrix ricorda su dati standardizzati coincide con la matrice \n * di covarianza : \n * z = x -<x> \/ sigma *\/\n arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<(3*COORDIM); ++j)\n corr(i,j) = v(i,j) \/ sqrt(v(i,i)*v(j,j));\n\n std::cout << \"Correlation matrix: \" << std::endl;\n std::cout << corr;\n#endif\n\n arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM);\n vi = v.i(); \n\n#ifdef DEBUG\n std::cout << \"inverse by cov matrix: \" << std::endl;\n std::cout << v * vi ;\n#endif\n \n \/\/ and so on ...\n arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM);\n arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM);\n arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM);\n double sum = 1.0e0;\n \n for (int l=0; l<num_of_ent; ++l) \n {\n sum += 1.0e0;\n for (int i=0; i<(3*COORDIM); ++i)\n coordm(i) += (coord(l,i)-coordm(i))\/sum;\n\n for (int i=0; i<PARAMDIM; ++i)\n paramm(i) += (param(l,i)-paramm(i))\/sum;\n\n for (int i=0; i<(3*COORDIM); ++i)\n {\n for (int j=0; j<PARAMDIM; ++j)\n {\n hcap(i,j) += ((coord(l,i) - coordm(i))*\n (param(l,j) - paramm(j))-\n (sum-1.0e0)*hcap(i,j)\/sum)\/(sum-1.0e0);\n }\n }\n }\n\n arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM);\n\n for (int i=0; i<PARAMDIM; ++i)\n for (int l=0; l<(3*COORDIM); ++l)\n for (int m=0; m<(3*COORDIM); ++m)\n cmtx(i,l) += vi(l,m) * hcap (m,i);\n\n#ifdef DEBUG\n std::cout << \"C matrix: \" << std::endl;\n std::cout << cmtx;\n#endif \n\n arma::mat q = arma::zeros<arma::mat>(PARAMDIM);\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n q(i) = paramm(i);\n for (int l=0; l<(3*COORDIM); ++l)\n q(i) -= cmtx(i,l)*coordm[l];\n }\n\n#ifdef DEBUG\n std::cout << \"Q vector: \" << std::endl;\n for (int i=0; i<PARAMDIM; ++i)\n std::cout << q(i) << std::endl;\n#endif\n\n \/\/test back\n arma::running_stat<double> chi2stats;\n arma::running_stat<double> pc[PARAMDIM];\n for (int l=0; l<num_of_ent; ++l)\n {\n\n std::cout << \"Track: \" << l+1 << std::endl;\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n double p = q(i);\n for (int k=0; k<(3*COORDIM); ++k)\n p += cmtx(i,k)*coord(l,k);\n \n std::cout << \" computed \" << p << \" real \" << param(l,i) << std::endl;\n \n pc[i](fabs(p - param(l,i))\/(fabs(p + param(l,i))\/2.0));\n }\n\n \/* chi**2 *\/\n double chi2 = 0.0e0;\n for (int i=0; i<(3*COORDIM); ++i)\n for (int j=0; j<(3*COORDIM); ++j)\n chi2 += (coord(l,i) - coordm(i)) * \n vi(i, j) * (coord(l,j) - coordm(j)); \n std::cout << \" chi2: \" << chi2 << std::endl;\n chi2stats(chi2);\n }\n std::cout << \"chi2 mean = \" << chi2stats.mean() << std::endl;\n std::cout << \"chi2 stdev = \" << chi2stats.stddev() << std::endl;\n std::cout << \"chi2 min = \" << chi2stats.min() << std::endl;\n std::cout << \"chi2 max = \" << chi2stats.max() << std::endl;\n\n for (int i=0; i<PARAMDIM; ++i)\n {\n std::cout << pc[i].mean() << \" \" << pc[i].stddev() << std::endl;\n\n arma::running_stat<double> stats;\n\n for (int l=0; l<num_of_ent; ++l) \n stats(param(l,i));\n\n std::cout << \" mean = \" << stats.mean() << std::endl;\n std::cout << \" stdev = \" << stats.stddev() << std::endl;\n std::cout << \" min = \" << stats.min() << std::endl;\n std::cout << \" max = \" << stats.max() << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QtCore\/QEventLoop>\n#include <QtTest\/QtTest>\n\n#include <TelepathyQt4\/Debug>\n#include <TelepathyQt4\/Types>\n#include <TelepathyQt4\/Client\/Account>\n#include <TelepathyQt4\/Client\/AccountManager>\n#include <TelepathyQt4\/Client\/ConnectionManager>\n#include <TelepathyQt4\/Client\/PendingAccount>\n#include <TelepathyQt4\/Client\/PendingOperation>\n\nusing namespace Telepathy;\nusing namespace Telepathy::Client;\n\nclass TestAccountBasics : public QObject\n{\n Q_OBJECT\n\npublic:\n TestAccountBasics(QObject *parent = 0);\n ~TestAccountBasics();\n\nprotected Q_SLOTS:\n void expectSuccessfulCall(Telepathy::Client::PendingOperation *);\n void onAccountCreated(Telepathy::Client::PendingOperation *);\n void onAccountReady(Telepathy::Client::PendingOperation *);\n void onAvatarChanged(const Telepathy::Avatar &);\n\nprivate Q_SLOTS:\n void init();\n\n void testBasics();\n\n void cleanup();\n\nprivate:\n QEventLoop *mLoop;\n AccountManager *mAM;\n};\n\nTestAccountBasics::TestAccountBasics(QObject *parent)\n : QObject(parent),\n mLoop(new QEventLoop(this)),\n mAM(0)\n{\n}\n\nTestAccountBasics::~TestAccountBasics()\n{\n delete mLoop;\n}\n\nvoid TestAccountBasics::expectSuccessfulCall(PendingOperation *operation)\n{\n if (operation->isError()) {\n qWarning().nospace() << operation->errorName()\n << \": \" << operation->errorMessage();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid TestAccountBasics::onAccountCreated(Telepathy::Client::PendingOperation *operation)\n{\n if (operation->isError()) {\n qWarning().nospace() << operation->errorName()\n << \": \" << operation->errorMessage();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid TestAccountBasics::onAccountReady(Telepathy::Client::PendingOperation *operation)\n{\n if (operation->isError()) {\n qWarning().nospace() << operation->errorName()\n << \": \" << operation->errorMessage();\n mLoop->exit(1);\n return;\n }\n\n mLoop->exit(0);\n}\n\nvoid TestAccountBasics::onAvatarChanged(const Telepathy::Avatar &avatar)\n{\n qDebug() << \"on avatar changed\";\n QCOMPARE(avatar.avatarData, QByteArray(\"asdfg\"));\n QCOMPARE(avatar.MIMEType, QString(\"image\/jpeg\"));\n mLoop->exit(0);\n}\n\nvoid TestAccountBasics::init()\n{\n Telepathy::registerTypes();\n Telepathy::enableDebug(true);\n Telepathy::enableWarnings(true);\n}\n\nvoid TestAccountBasics::testBasics()\n{\n mAM = new AccountManager();\n QCOMPARE(mAM->isReady(), false);\n\n connect(mAM->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n qDebug() << \"enter main loop\";\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mAM->isReady(), true);\n\n QVariantMap parameters;\n parameters[\"account\"] = \"foobar\";\n PendingAccount *pacc = mAM->createAccount(\"foo\",\n \"bar\", \"foobar\", parameters);\n connect(pacc,\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(onAccountCreated(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(mAM->interfaces(), QStringList());\n\n QCOMPARE(mAM->validAccountPaths(),\n QStringList() <<\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n QCOMPARE(mAM->invalidAccountPaths(),\n QStringList());\n QCOMPARE(mAM->allAccountPaths(),\n QStringList() <<\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n\n Account *acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n connect(acc->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(onAccountReady(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->displayName(), QString(\"foobar (account 0)\"));\n\n connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n\n connect(acc,\n SIGNAL(avatarChanged(const Telepathy::Avatar &)),\n SLOT(onAvatarChanged(const Telepathy::Avatar &)));\n\n Telepathy::Avatar avatar = { QByteArray(\"asdfg\"), \"image\/jpeg\" };\n connect(acc->setAvatar(avatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n \/\/ wait for avatarChanged signal\n QCOMPARE(mLoop->exec(), 0);\n\n pacc = mAM->createAccount(\"spurious\",\n \"normal\", \"foobar\", parameters);\n connect(pacc,\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(onAccountCreated(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/spurious\/normal\/Account0\");\n connect(acc->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(onAccountReady(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/spurious\/normal\/Account0\");\n connect(acc->becomeReady(Account::FeatureProtocolInfo),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n ProtocolInfo *protocolInfo = acc->protocolInfo();\n QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0));\n QCOMPARE(protocolInfo->hasParameter(\"account\"), true);\n QCOMPARE(protocolInfo->hasParameter(\"password\"), true);\n QCOMPARE(protocolInfo->hasParameter(\"register\"), true);\n\n connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n\n connect(acc->becomeReady(Account::FeatureProtocolInfo | Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n this,\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *)));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n protocolInfo = acc->protocolInfo();\n QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0));\n}\n\nvoid TestAccountBasics::cleanup()\n{\n if (mAM) {\n delete mAM;\n mAM = 0;\n }\n}\n\nQTEST_MAIN(TestAccountBasics)\n\n#include \"_gen\/account-basics.cpp.moc.hpp\"\n<commit_msg>Changed tests\/dbus\/account-basics.cpp to inherit Test.<commit_after>#include <QtCore\/QEventLoop>\n#include <QtTest\/QtTest>\n\n#include <TelepathyQt4\/Debug>\n#include <TelepathyQt4\/Types>\n#include <TelepathyQt4\/Client\/Account>\n#include <TelepathyQt4\/Client\/AccountManager>\n#include <TelepathyQt4\/Client\/ConnectionManager>\n#include <TelepathyQt4\/Client\/PendingAccount>\n#include <TelepathyQt4\/Client\/PendingOperation>\n\n#include <tests\/lib\/test.h>\n\nusing namespace Telepathy::Client;\n\nclass TestAccountBasics : public Test\n{\n Q_OBJECT\n\npublic:\n TestAccountBasics(QObject *parent = 0)\n : Test(parent), mAM(0)\n { }\n\nprotected Q_SLOTS:\n void onAvatarChanged(const Telepathy::Avatar &);\n\nprivate Q_SLOTS:\n void initTestCase();\n\n void testBasics();\n\n void cleanupTestCase();\n\nprivate:\n AccountManager *mAM;\n};\n\nvoid TestAccountBasics::onAvatarChanged(const Telepathy::Avatar &avatar)\n{\n qDebug() << \"on avatar changed\";\n QCOMPARE(avatar.avatarData, QByteArray(\"asdfg\"));\n QCOMPARE(avatar.MIMEType, QString(\"image\/jpeg\"));\n mLoop->exit(0);\n}\n\nvoid TestAccountBasics::initTestCase()\n{\n initTestCaseImpl();\n\n mAM = new AccountManager();\n QCOMPARE(mAM->isReady(), false);\n}\n\nvoid TestAccountBasics::testBasics()\n{\n QVERIFY(connect(mAM->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mAM->isReady(), true);\n\n QVariantMap parameters;\n parameters[\"account\"] = \"foobar\";\n PendingAccount *pacc = mAM->createAccount(\"foo\",\n \"bar\", \"foobar\", parameters);\n QVERIFY(connect(pacc,\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(mAM->interfaces(), QStringList());\n\n QCOMPARE(mAM->validAccountPaths(),\n QStringList() <<\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n QCOMPARE(mAM->invalidAccountPaths(),\n QStringList());\n QCOMPARE(mAM->allAccountPaths(),\n QStringList() <<\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n\n Account *acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/foo\/bar\/Account0\");\n QVERIFY(connect(acc->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->displayName(), QString(\"foobar (account 0)\"));\n\n QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n\n QVERIFY(connect(acc,\n SIGNAL(avatarChanged(const Telepathy::Avatar &)),\n SLOT(onAvatarChanged(const Telepathy::Avatar &))));\n\n Telepathy::Avatar avatar = { QByteArray(\"asdfg\"), \"image\/jpeg\" };\n QVERIFY(connect(acc->setAvatar(avatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n \/\/ wait for avatarChanged signal\n QCOMPARE(mLoop->exec(), 0);\n\n pacc = mAM->createAccount(\"spurious\",\n \"normal\", \"foobar\", parameters);\n QVERIFY(connect(pacc,\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/spurious\/normal\/Account0\");\n QVERIFY(connect(acc->becomeReady(),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n acc = mAM->accountForPath(\n \"\/org\/freedesktop\/Telepathy\/Account\/spurious\/normal\/Account0\");\n QVERIFY(connect(acc->becomeReady(Account::FeatureProtocolInfo),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n ProtocolInfo *protocolInfo = acc->protocolInfo();\n QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0));\n QCOMPARE(protocolInfo->hasParameter(\"account\"), true);\n QCOMPARE(protocolInfo->hasParameter(\"password\"), true);\n QCOMPARE(protocolInfo->hasParameter(\"register\"), true);\n\n QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n\n QVERIFY(connect(acc->becomeReady(Account::FeatureProtocolInfo | Account::FeatureAvatar),\n SIGNAL(finished(Telepathy::Client::PendingOperation *)),\n SLOT(expectSuccessfulCall(Telepathy::Client::PendingOperation *))));\n QCOMPARE(mLoop->exec(), 0);\n\n QCOMPARE(acc->avatar().MIMEType, QString(\"image\/png\"));\n protocolInfo = acc->protocolInfo();\n QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0));\n}\n\nvoid TestAccountBasics::cleanupTestCase()\n{\n if (mAM) {\n delete mAM;\n mAM = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestAccountBasics)\n#include \"_gen\/account-basics.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ device_test.cpp\n\/\/\n\/\/ Identification: tests\/logging\/device_test.cpp\n\/\/\n\/\/ Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"harness.h\"\n\n#include <iostream>\n#include <fcntl.h>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cassert>\n#include <getopt.h>\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include \"backend\/common\/timer.h\"\n#include \"backend\/common\/types.h\"\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Device Test\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass DeviceTest : public PelotonTest {};\n\n#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) \/\/ 512 MB\n#define DATA_FILE_NAME \"peloton.pmem\"\n\nTEST_F(DeviceTest, BenchmarkTest) {\n\n std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR};\n int data_fd;\n size_t data_file_len = DATA_FILE_LEN;\n oid_t num_trials = 3;\n std::size_t begin_chunk_size = 9, end_chunk_size = 21; \/\/ lg base 2\n\n \/\/ Go over all the dirs\n for(auto data_file_dir : data_file_dirs){\n\n \/\/ Create a data file\n std::string data_file_name = data_file_dir + DATA_FILE_NAME;\n std::cout << \"Data File Name : \" << data_file_name << \"\\n\";\n\n if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) {\n perror(data_file_name.c_str());\n exit(EXIT_FAILURE);\n }\n\n \/\/ Allocate the data file\n if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) {\n perror(\"posix_fallocate\");\n exit(EXIT_FAILURE);\n }\n\n \/\/ Go over all the chunk sizes\n for(oid_t chunk_size_itr = begin_chunk_size;\n chunk_size_itr <= end_chunk_size;\n chunk_size_itr++){\n\n \/\/ READS\n for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {\n\n }\n\n \/\/ WRITES\n for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {\n\n }\n\n }\n\n \/\/ Close the pmem file\n close(data_fd);\n }\n\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n\n<commit_msg>Fixed device test<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ device_test.cpp\n\/\/\n\/\/ Identification: tests\/logging\/device_test.cpp\n\/\/\n\/\/ Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"harness.h\"\n\n#include <iostream>\n#include <fcntl.h>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cassert>\n#include <getopt.h>\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include \"backend\/common\/timer.h\"\n#include \"backend\/common\/types.h\"\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Device Test\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass DeviceTest : public PelotonTest {};\n\n#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) \/\/ 512 MB\n#define DATA_FILE_NAME \"peloton.pmem\"\n\nTEST_F(DeviceTest, BenchmarkTest) {\n\n std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR};\n int data_fd;\n size_t data_file_len = DATA_FILE_LEN;\n oid_t num_trials = 3;\n std::size_t begin_chunk_size = 9, end_chunk_size = 21; \/\/ lg base 2\n\n \/\/ Go over all the dirs\n for(auto data_file_dir : data_file_dirs){\n\n \/\/ Create a data file\n std::string data_file_name = data_file_dir + DATA_FILE_NAME;\n std::cout << \"Data File Name : \" << data_file_name << \"\\n\";\n\n if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) {\n LOG_ERROR(\"%s: No such file or directory\", data_file_name.c_str());\n return;\n }\n\n \/\/ Allocate the data file\n if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) {\n LOG_ERROR(\"%s: posix_fallocate\", data_file_name.c_str());\n return;\n }\n\n \/\/ Go over all the chunk sizes\n for(oid_t chunk_size_itr = begin_chunk_size;\n chunk_size_itr <= end_chunk_size;\n chunk_size_itr++){\n\n \/\/ READS\n for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {\n\n }\n\n \/\/ WRITES\n for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {\n\n }\n\n }\n\n \/\/ Close the pmem file\n close(data_fd);\n }\n\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ math_cart_mat33_baseline.cc -- representative small test computations\n\n#include <cmath>\n#include <stdio.h>\n#include <gtest\/gtest.h>\n\n#include \"math\/Cart3f.h\"\n\nusing namespace cart3;\n\n#if 0\nvoid print_cart3f(Cart3f& vec)\n{\n printf(\"%4.2f %4.2f %4.2f\\n\", vec[0], vec[1], vec[2]);\n}\n\nvoid print_cart3f(const Cart3f& vec)\n{\n Cart3f v = vec;\n print_cart3f(v);\n}\n#endif \/\/ 0\n\nconst Cart3f vector_100 = Cart3f(1.0, 0.0, 0.0);\nconst Cart3f vector_010 = Cart3f(0.0, 1.0, 0.0);\nconst Cart3f vector_zero = Cart3f(0.0, 0.0, 0.0);\n\nconst Mat33f matrix_zero = Mat33f(\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0);\n\nconst Mat33f matrix_ones = Mat33f(\n 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0);\n\nconst Mat33f matrix_ident = Mat33f(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0);\n\nconst Mat33f matrix_twist = Mat33f(\n 0.0, 1.0, 2.0,\n 1.0, 1.0, 1.0,\n 2.0, 1.0, 0.0);\n\nTEST(MathCartMat33Baseline, First)\n{\n Mat33f a = matrix_ident;\n EXPECT_EQ(a, matrix_ident); \/\/ deceptively simple, lots happening\n}\n\nTEST(MathCartMat33Baseline, Construct)\n{\n \/\/ construct from scalars\n Mat33f a = Mat33f(\n 0.0, 1.0, 2.0,\n 3.0, 4.0, 5.0,\n 6.0, 7.0, 8.0);\n EXPECT_EQ(a[0][0], 0.0);\n EXPECT_EQ(a[0][2], 2.0);\n EXPECT_EQ(a[2][1], 7.0);\n\n \/\/ construct from vectors\n Mat33f b = Mat33f(vector_100, vector_010, vector_zero);\n EXPECT_EQ(b, Mat33f(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0));\n EXPECT_NE(b, matrix_zero);\n}\n\nTEST(MathCartMat33Baseline, CompoundAsgnAdd)\n{\n Mat33f sum = matrix_zero;\n sum += matrix_ident;\n sum += matrix_ones;\n\n EXPECT_EQ(matrix_zero, Mat33f(\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0 ));\n EXPECT_EQ(sum, Mat33f(\n 2.0, 1.0, 1.0,\n 1.0, 2.0, 1.0,\n 1.0, 1.0, 2.0 ));\n\n Mat33f diff = matrix_ones;\n diff -= matrix_ident;\n EXPECT_EQ(diff, Mat33f(\n 0.0, 1.0, 1.0,\n 1.0, 0.0, 1.0,\n 1.0, 1.0, 0.0 ));\n}\n\n\nTEST(MathCartMat33Baseline, CompoundAsgnMult)\n{\n Mat33f sum = matrix_zero;\n Mat33f result = matrix_twist;\n result *= 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 2.0, 4.0,\n 2.0, 2.0, 2.0,\n 4.0, 2.0, 0.0 ));\n result \/= 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 1.0, 2.0,\n 1.0, 1.0, 1.0,\n 2.0, 1.0, 0.0 ));\n}\n\n\nTEST(MathCartMat33Baseline, Index)\n{\n enum { x=0, y=1, z=2 };\n Mat33f a = Mat33f(\n 0.0, 1.0, 2.0,\n 3.0, 4.0, 5.0,\n 6.0, 7.0, 8.0);\n EXPECT_EQ(a[x][x], 0.0);\n EXPECT_EQ(a[x][z], 2.0);\n EXPECT_EQ(a[y][x], 3.0);\n EXPECT_EQ(a[z][y], 7.0);\n\n float axz = a[x][z];\n a[z][x] = a[x][z];\n EXPECT_EQ(axz, 2.0);\n EXPECT_EQ(a[z], Cart3f(2.0, 7.0, 8.0));\n}\n\nTEST(MathCartMat33Baseline, BinAdd)\n{\n Mat33f result = matrix_ones + matrix_ident;\n EXPECT_EQ(result, Mat33f(\n 2.0, 1.0, 1.0,\n 1.0, 2.0, 1.0,\n 1.0, 1.0, 2.0 ));\n\n result = matrix_ones - matrix_ident;\n EXPECT_EQ(result, Mat33f(\n 0.0, 1.0, 1.0,\n 1.0, 0.0, 1.0,\n 1.0, 1.0, 0.0 ));\n}\n\nTEST(MathCartMat33Baseline, BinMult)\n{\n Mat33f result = matrix_twist * 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 2.0, 4.0,\n 2.0, 2.0, 2.0,\n 4.0, 2.0, 0.0 ));\n\n result = matrix_twist \/ 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 0.5, 1.0,\n 0.5, 0.5, 0.5,\n 1.0, 0.5, 0.0 ));\n}\n\n\nTEST(MathCartMat33Baseline, BinMultDot)\n{\n Mat33f rot30cclock = Mat33f(\n \/\/ rotate 30 degrees (pi\/6) counterclockwise\n 0.500, -0.866, 0.0,\n 0.866, 0.500, 0.0,\n 0.0, 0.0, 1.0);\n Cart3f xseg = Cart3f(1.0, 0.0, 0.0);\n \/\/print_cart3f(xseg);\n\n \/\/ v = m * v\n Cart3f vresult = rot30cclock * xseg;\n \/\/print_cart3f(vresult);\n EXPECT_EQ(vresult, Cart3f(0.5, 0.866, 0.0));\n\n \/\/ m = m * m\n Mat33f mresult = rot30cclock * matrix_ident;\n \/\/print_cart3f(mresult[0]);\n \/\/print_cart3f(mresult[1]);\n \/\/print_cart3f(mresult[2]);\n EXPECT_EQ(mresult, rot30cclock);\n}\n\nTEST(MathCartMat33Baseline, Unary)\n{\n Mat33f result = -matrix_twist;\n EXPECT_EQ(result, Mat33f(\n 0.0, -1.0, -2.0,\n -1.0, -1.0, -1.0,\n -2.0, -1.0, -0.0));\n}\n\n<commit_msg>Rename testsuite to indicate type\/precision.<commit_after>\/\/ math_cart_mat33_baseline.cc -- representative small test computations\n\n#include <cmath>\n#include <stdio.h>\n#include <gtest\/gtest.h>\n\n#include \"math\/Cart3f.h\"\n\nusing namespace cart3;\n\n#if 0\nvoid print_cart3f(Cart3f& vec)\n{\n printf(\"%4.2f %4.2f %4.2f\\n\", vec[0], vec[1], vec[2]);\n}\n\nvoid print_cart3f(const Cart3f& vec)\n{\n Cart3f v = vec;\n print_cart3f(v);\n}\n#endif \/\/ 0\n\nconst Cart3f vector_100 = Cart3f(1.0, 0.0, 0.0);\nconst Cart3f vector_010 = Cart3f(0.0, 1.0, 0.0);\nconst Cart3f vector_zero = Cart3f(0.0, 0.0, 0.0);\n\nconst Mat33f matrix_zero = Mat33f(\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0);\n\nconst Mat33f matrix_ones = Mat33f(\n 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0);\n\nconst Mat33f matrix_ident = Mat33f(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0);\n\nconst Mat33f matrix_twist = Mat33f(\n 0.0, 1.0, 2.0,\n 1.0, 1.0, 1.0,\n 2.0, 1.0, 0.0);\n\nTEST(MathMat33fBaseline, First)\n{\n Mat33f a = matrix_ident;\n EXPECT_EQ(a, matrix_ident); \/\/ deceptively simple, lots happening\n}\n\nTEST(MathMat33fBaseline, Construct)\n{\n \/\/ construct from scalars\n Mat33f a = Mat33f(\n 0.0, 1.0, 2.0,\n 3.0, 4.0, 5.0,\n 6.0, 7.0, 8.0);\n EXPECT_EQ(a[0][0], 0.0);\n EXPECT_EQ(a[0][2], 2.0);\n EXPECT_EQ(a[2][1], 7.0);\n\n \/\/ construct from vectors\n Mat33f b = Mat33f(vector_100, vector_010, vector_zero);\n EXPECT_EQ(b, Mat33f(\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0));\n EXPECT_NE(b, matrix_zero);\n}\n\nTEST(MathMat33fBaseline, CompoundAsgnAdd)\n{\n Mat33f sum = matrix_zero;\n sum += matrix_ident;\n sum += matrix_ones;\n\n EXPECT_EQ(matrix_zero, Mat33f(\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0 ));\n EXPECT_EQ(sum, Mat33f(\n 2.0, 1.0, 1.0,\n 1.0, 2.0, 1.0,\n 1.0, 1.0, 2.0 ));\n\n Mat33f diff = matrix_ones;\n diff -= matrix_ident;\n EXPECT_EQ(diff, Mat33f(\n 0.0, 1.0, 1.0,\n 1.0, 0.0, 1.0,\n 1.0, 1.0, 0.0 ));\n}\n\n\nTEST(MathMat33fBaseline, CompoundAsgnMult)\n{\n Mat33f sum = matrix_zero;\n Mat33f result = matrix_twist;\n result *= 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 2.0, 4.0,\n 2.0, 2.0, 2.0,\n 4.0, 2.0, 0.0 ));\n result \/= 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 1.0, 2.0,\n 1.0, 1.0, 1.0,\n 2.0, 1.0, 0.0 ));\n}\n\n\nTEST(MathMat33fBaseline, Index)\n{\n enum { x=0, y=1, z=2 };\n Mat33f a = Mat33f(\n 0.0, 1.0, 2.0,\n 3.0, 4.0, 5.0,\n 6.0, 7.0, 8.0);\n EXPECT_EQ(a[x][x], 0.0);\n EXPECT_EQ(a[x][z], 2.0);\n EXPECT_EQ(a[y][x], 3.0);\n EXPECT_EQ(a[z][y], 7.0);\n\n float axz = a[x][z];\n a[z][x] = a[x][z];\n EXPECT_EQ(axz, 2.0);\n EXPECT_EQ(a[z], Cart3f(2.0, 7.0, 8.0));\n}\n\nTEST(MathMat33fBaseline, BinAdd)\n{\n Mat33f result = matrix_ones + matrix_ident;\n EXPECT_EQ(result, Mat33f(\n 2.0, 1.0, 1.0,\n 1.0, 2.0, 1.0,\n 1.0, 1.0, 2.0 ));\n\n result = matrix_ones - matrix_ident;\n EXPECT_EQ(result, Mat33f(\n 0.0, 1.0, 1.0,\n 1.0, 0.0, 1.0,\n 1.0, 1.0, 0.0 ));\n}\n\nTEST(MathMat33fBaseline, BinMult)\n{\n Mat33f result = matrix_twist * 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 2.0, 4.0,\n 2.0, 2.0, 2.0,\n 4.0, 2.0, 0.0 ));\n\n result = matrix_twist \/ 2.0;\n EXPECT_EQ(result, Mat33f(\n 0.0, 0.5, 1.0,\n 0.5, 0.5, 0.5,\n 1.0, 0.5, 0.0 ));\n}\n\n\nTEST(MathMat33fBaseline, BinMultDot)\n{\n Mat33f rot30cclock = Mat33f(\n \/\/ rotate 30 degrees (pi\/6) counterclockwise\n 0.500, -0.866, 0.0,\n 0.866, 0.500, 0.0,\n 0.0, 0.0, 1.0);\n Cart3f xseg = Cart3f(1.0, 0.0, 0.0);\n \/\/print_cart3f(xseg);\n\n \/\/ v = m * v\n Cart3f vresult = rot30cclock * xseg;\n \/\/print_cart3f(vresult);\n EXPECT_EQ(vresult, Cart3f(0.5, 0.866, 0.0));\n\n \/\/ m = m * m\n Mat33f mresult = rot30cclock * matrix_ident;\n \/\/print_cart3f(mresult[0]);\n \/\/print_cart3f(mresult[1]);\n \/\/print_cart3f(mresult[2]);\n EXPECT_EQ(mresult, rot30cclock);\n}\n\nTEST(MathMat33fBaseline, Unary)\n{\n Mat33f result = -matrix_twist;\n EXPECT_EQ(result, Mat33f(\n 0.0, -1.0, -2.0,\n -1.0, -1.0, -1.0,\n -2.0, -1.0, -0.0));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <memory>\n\n#include <gtest\/gtest.h>\n\n#include \"utils\/make_unique.h\"\n\nTEST(MakeUnique, succeed) {\n std::unique_ptr<int> unique_int = phosphor::utils::make_unique<int>(5);\n ASSERT_NE(unique_int.get(), nullptr);\n EXPECT_EQ(*unique_int, 5);\n}\n<commit_msg>Improve branch coverage of polyfill test<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <memory>\n\n#include <gtest\/gtest.h>\n\n#include \"utils\/make_unique.h\"\n\nTEST(MakeUnique, succeed) {\n std::unique_ptr<int> unique_int = phosphor::utils::make_unique<int>(5);\n ASSERT_NE(unique_int.get(), nullptr);\n EXPECT_EQ(*unique_int, 5);\n}\n\n\/* Used for full branch\/line coverage of make_unique *\/\nstruct AlwaysThrow {\n AlwaysThrow() {\n throw std::runtime_error(\"AlwaysThrow::AlwaysThrow: Fake exception\");\n }\n};\n\nTEST(MakeUnique, fail) {\n EXPECT_THROW(phosphor::utils::make_unique<AlwaysThrow>(), std::runtime_error);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015-2016 Alexander Saprykin <xelfium@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#ifndef PLIB_TESTS_STATIC\n# define BOOST_TEST_DYN_LINK\n#endif\n\n#define BOOST_TEST_MODULE plibraryloader_test\n\n#include \"plib.h\"\n\n#ifdef PLIB_TESTS_STATIC\n# include <boost\/test\/included\/unit_test.hpp>\n#else\n# include <boost\/test\/unit_test.hpp>\n#endif\n\nBOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE (plibraryloader_general_test)\n{\n\tPLibraryLoader\t*loader;\n\tpchar\t\t*err_msg;\n\tvoid\t\t(*shutdown_func) (void);\n\n\tp_lib_init ();\n\n\t\/* We assume that 2nd argument is a PLib library path *\/\n\tBOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);\n\n\t\/* Invalid usage *\/\n\tBOOST_CHECK (p_library_loader_new (NULL) == NULL);\n\tBOOST_CHECK (p_library_loader_new (\".\/unexistent_file.nofile\") == NULL);\n\tBOOST_CHECK (p_library_loader_get_symbol (NULL, NULL) == NULL);\n\tBOOST_CHECK (p_library_loader_get_symbol (NULL, \"unexistent_symbol\") == NULL);\n\tp_library_loader_free (NULL);\n\n\t\/* General tests *\/\n\terr_msg = p_library_loader_get_last_error ();\n\tp_free (err_msg);\n\n\tloader = p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]);\n\tBOOST_REQUIRE (loader != NULL);\n\n\tshutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, \"p_lib_shutdown\");\n\n\tif (shutdown_func == NULL)\n\t\tshutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, \"_p_lib_shutdown\");\n\n\tBOOST_REQUIRE (shutdown_func != NULL);\n\n\terr_msg = p_library_loader_get_last_error ();\n\tp_free (err_msg);\n\n\tp_library_loader_free (loader);\n\n\t\/* We have already loaded reference to PLib, it's OK *\/\n\tshutdown_func ();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>tests: Add check for error message when failed to load shared library<commit_after>\/*\n * Copyright (C) 2015-2016 Alexander Saprykin <xelfium@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#ifndef PLIB_TESTS_STATIC\n# define BOOST_TEST_DYN_LINK\n#endif\n\n#define BOOST_TEST_MODULE plibraryloader_test\n\n#include \"plib.h\"\n\n#ifdef PLIB_TESTS_STATIC\n# include <boost\/test\/included\/unit_test.hpp>\n#else\n# include <boost\/test\/unit_test.hpp>\n#endif\n\nBOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE (plibraryloader_general_test)\n{\n\tPLibraryLoader\t*loader;\n\tpchar\t\t*err_msg;\n\tvoid\t\t(*shutdown_func) (void);\n\n\tp_lib_init ();\n\n\t\/* We assume that 2nd argument is a PLib library path *\/\n\tBOOST_REQUIRE (boost::unit_test::framework::master_test_suite().argc == 2);\n\n\t\/* Invalid usage *\/\n\tBOOST_CHECK (p_library_loader_new (NULL) == NULL);\n\tBOOST_CHECK (p_library_loader_new (\".\/unexistent_file.nofile\") == NULL);\n\tBOOST_CHECK (p_library_loader_get_symbol (NULL, NULL) == NULL);\n\tBOOST_CHECK (p_library_loader_get_symbol (NULL, \"unexistent_symbol\") == NULL);\n\n\tp_library_loader_free (NULL);\n\n\t\/* General tests *\/\n\terr_msg = p_library_loader_get_last_error ();\n\tp_free (err_msg);\n\n\tloader = p_library_loader_new (boost::unit_test::framework::master_test_suite().argv[1]);\n\tBOOST_REQUIRE (loader != NULL);\n\n\tBOOST_CHECK (p_library_loader_get_symbol (loader, \"there_is_no_such_a_symbol\") == (PFuncAddr) NULL);\n\n\terr_msg = p_library_loader_get_last_error ();\n\tBOOST_CHECK (err_msg != NULL);\n\tp_free (err_msg);\n\n\tshutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, \"p_lib_shutdown\");\n\n\tif (shutdown_func == NULL)\n\t\tshutdown_func = (void (*) (void)) p_library_loader_get_symbol (loader, \"_p_lib_shutdown\");\n\n\tBOOST_REQUIRE (shutdown_func != NULL);\n\n\terr_msg = p_library_loader_get_last_error ();\n\tp_free (err_msg);\n\n\tp_library_loader_free (loader);\n\n\t\/* We have already loaded reference to PLib, it's OK *\/\n\tshutdown_func ();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************\n *\n * Round for C\n *\n * Copyright (C) Satoshi Konno 2015\n *\n * This is licensed under BSD-style license, see file COPYING.\n *\n ******************************************************************\/\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <round\/util\/semaphore.h>\n#include <round\/util\/thread.h>\n#include <round\/util\/timer.h>\n\nBOOST_AUTO_TEST_SUITE(semaphore)\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreBasicTest) {\n RoundSemaphore *sem = round_semaphore_new(1);\n BOOST_CHECK(sem);\n \n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK(round_semaphore_delete(sem));\n}\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreMaxCountTest)\n{\n for (size_t semMaxCount = 1; semMaxCount<10; semMaxCount++) {\n RoundSemaphore *sem = round_semaphore_new(semMaxCount);\n BOOST_CHECK(sem);\n\n for (size_t n=0; n<semMaxCount; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n }\n \n for (size_t n=0; n<semMaxCount; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n }\n \n BOOST_CHECK(round_semaphore_delete(sem));\n }\n}\n\nstatic const int SEMAPHORE_THREAD_TEST_LOOP_NUM = 10;\n\nvoid RoundSemaphorePostThread(RoundThread *thread)\n{\n RoundSemaphore *sem = (RoundSemaphore *)round_thread_getuserdata(thread);\n for (int n = 0; n < SEMAPHORE_THREAD_TEST_LOOP_NUM; n++) {\n round_sleep(100);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n }\n}\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreThreadTest)\n{\n RoundSemaphore *sem = round_semaphore_new(0);\n \n RoundThread *thread = round_thread_new();\n round_thread_setaction(thread, RoundSemaphorePostThread);\n round_thread_setuserdata(thread, sem);\n BOOST_CHECK(round_thread_start(thread));\n \n for (int n = 0; n < SEMAPHORE_THREAD_TEST_LOOP_NUM; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n }\n\n BOOST_CHECK(round_thread_stop(thread));\n BOOST_CHECK(round_thread_delete(thread));\n BOOST_CHECK(round_semaphore_delete(sem));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>* Added a unit test for round_semaphore_timedwait().<commit_after>\/******************************************************************\n *\n * Round for C\n *\n * Copyright (C) Satoshi Konno 2015\n *\n * This is licensed under BSD-style license, see file COPYING.\n *\n ******************************************************************\/\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <round\/util\/semaphore.h>\n#include <round\/util\/thread.h>\n#include <round\/util\/timer.h>\n\nBOOST_AUTO_TEST_SUITE(semaphore)\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreBasicTest) {\n RoundSemaphore *sem = round_semaphore_new(0);\n BOOST_CHECK(sem);\n \n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n\n BOOST_CHECK(round_semaphore_delete(sem));\n}\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreMaxCountTest)\n{\n for (size_t semMaxCount = 1; semMaxCount<10; semMaxCount++) {\n RoundSemaphore *sem = round_semaphore_new(semMaxCount);\n BOOST_CHECK(sem);\n\n for (size_t n=0; n<semMaxCount; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n }\n \n for (size_t n=0; n<semMaxCount; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n }\n \n BOOST_CHECK(round_semaphore_delete(sem));\n }\n}\n\nstatic const int SEMAPHORE_THREAD_TEST_LOOP_NUM = 10;\n\nvoid RoundSemaphorePostThread(RoundThread *thread)\n{\n RoundSemaphore *sem = (RoundSemaphore *)round_thread_getuserdata(thread);\n for (int n = 0; n < SEMAPHORE_THREAD_TEST_LOOP_NUM; n++) {\n round_sleep(100);\n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n }\n}\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreThreadTest)\n{\n RoundSemaphore *sem = round_semaphore_new(0);\n \n RoundThread *thread = round_thread_new();\n round_thread_setaction(thread, RoundSemaphorePostThread);\n round_thread_setuserdata(thread, sem);\n BOOST_CHECK(round_thread_start(thread));\n \n for (int n = 0; n < SEMAPHORE_THREAD_TEST_LOOP_NUM; n++) {\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n }\n\n BOOST_CHECK(round_thread_stop(thread));\n BOOST_CHECK(round_thread_delete(thread));\n BOOST_CHECK(round_semaphore_delete(sem));\n}\n\nBOOST_AUTO_TEST_CASE(RoundSemaphoreTimeoutTest) {\n RoundSemaphore *sem = round_semaphore_new(0);\n BOOST_CHECK(sem);\n \n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n \n BOOST_CHECK_EQUAL(round_semaphore_timedwait(sem, 1), false);\n \n BOOST_CHECK_EQUAL(round_semaphore_post(sem), true);\n BOOST_CHECK_EQUAL(round_semaphore_wait(sem), true);\n \n BOOST_CHECK(round_semaphore_delete(sem));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include <CoreGraphics\/CoreGraphics.h>\n#include <iostream>\n#include <spdlog\/spdlog.h>\n\nnamespace {\nCFMachPortRef eventtap_;\n\nCGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {\n switch (type) {\n case kCGEventKeyDown:\n std::cout << \"kCGEventKeyDown\" << std::endl;\n break;\n case kCGEventKeyUp:\n std::cout << \"kCGEventKeyUp\" << std::endl;\n default:\n std::cout << \"callback:\" << type << std::endl;\n break;\n }\n return event;\n}\n}\n\nclass logger final {\npublic:\n static spdlog::logger& get_logger(void) {\n static std::shared_ptr<spdlog::logger> logger;\n if (!logger) {\n logger = spdlog::stdout_logger_mt(\"eventtap\", true);\n }\n return *logger;\n }\n};\n\nint main(int argc, const char* argv[]) {\n if (getuid() != 0) {\n logger::get_logger().error(\"eventtap requires root privilege to use kCGHIDEventTap.\");\n return 0;\n }\n\n eventtap_ = CGEventTapCreate(kCGHIDEventTap,\n kCGHeadInsertEventTap,\n kCGEventTapOptionDefault,\n CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp),\n callback,\n nullptr);\n\n auto run_loop_source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventtap_, 0);\n CFRunLoopAddSource(CFRunLoopGetCurrent(), run_loop_source, kCFRunLoopCommonModes);\n CGEventTapEnable(eventtap_, 1);\n CFRelease(run_loop_source);\n\n CFRunLoopRun();\n\n return 0;\n}\n<commit_msg>update eventtap<commit_after>#include <CoreGraphics\/CoreGraphics.h>\n#include <iostream>\n#include <spdlog\/spdlog.h>\n\nnamespace {\nCFMachPortRef eventtap_;\n\nCGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {\n std::cout << \"CGEventGetFlags 0x\" << std::hex << CGEventGetFlags(event) << std::dec << std::endl;\n\n switch (type) {\n case kCGEventKeyDown:\n std::cout << \"kCGEventKeyDown\" << std::endl;\n break;\n case kCGEventKeyUp:\n std::cout << \"kCGEventKeyUp\" << std::endl;\n default:\n std::cout << \"callback:\" << type << std::endl;\n break;\n }\n return event;\n}\n}\n\nclass logger final {\npublic:\n static spdlog::logger& get_logger(void) {\n static std::shared_ptr<spdlog::logger> logger;\n if (!logger) {\n logger = spdlog::stdout_logger_mt(\"eventtap\", true);\n }\n return *logger;\n }\n};\n\nint main(int argc, const char* argv[]) {\n if (getuid() != 0) {\n logger::get_logger().error(\"eventtap requires root privilege to use kCGHIDEventTap.\");\n return 0;\n }\n\n eventtap_ = CGEventTapCreate(kCGHIDEventTap,\n kCGHeadInsertEventTap,\n kCGEventTapOptionDefault,\n CGEventMaskBit(kCGEventLeftMouseDown) |\n CGEventMaskBit(kCGEventLeftMouseUp) |\n CGEventMaskBit(kCGEventRightMouseDown) |\n CGEventMaskBit(kCGEventRightMouseUp) |\n CGEventMaskBit(kCGEventMouseMoved) |\n CGEventMaskBit(kCGEventLeftMouseDragged) |\n CGEventMaskBit(kCGEventRightMouseDragged) |\n CGEventMaskBit(kCGEventKeyDown) |\n CGEventMaskBit(kCGEventKeyUp),\n callback,\n nullptr);\n\n auto run_loop_source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventtap_, 0);\n CFRunLoopAddSource(CFRunLoopGetCurrent(), run_loop_source, kCFRunLoopCommonModes);\n CGEventTapEnable(eventtap_, true);\n CFRelease(run_loop_source);\n\n CFRunLoopRun();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/**\n * THIS IS WORK IN PROGRESS!\n *\/\n\n#include \"Freelist.h\"\n#include \"WTPExceptions.h\"\n#include \"WorkerThreadPool.h\"\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <errno.h>\n#include <string>\n#include <stdio.h>\n#include <iostream>\n#include <cstdlib>\n#include <sstream>\n#include <assert.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <map>\n\nusing namespace std;\nusing namespace WTP;\nWorkerThreadPool *wtp = NULL;\nint globerr = 0;\nint rndfd = 0;\nFreelist freelist;\n\nclass DirProcessor : public WorkItem {\npublic:\n static void procdir(int dirfd, int level, int nsubdirs, int nfiles, uint64_t filesize);\n static void randfile(int fd, uint64_t size);\n\n void setParams(int dirfd, int level, int nsubdirs, int nfiles,\n uint64_t filesize) {\n _dirfd = dirfd;\n _level = level;\n _nsubdirs=nsubdirs;\n _nfiles=nfiles;\n _filesize=filesize;\n }\n void run() {\n procdir(_dirfd, _level, _nsubdirs, _nfiles, _filesize);\n }\n\n void reset() {\n _dirfd = -1;\n _level = 0;\n _nsubdirs=0;\n _nfiles=0;\n _filesize=0;\n }\n\nprivate:\n int _dirfd, _level, _nsubdirs, _nfiles;\n uint64_t _filesize;\n};\n\nvoid DirProcessor::randfile(int fd, uint64_t size)\n{\n uint64_t remaining = size;\n char *buf = new char[4000];\n while (remaining > 0) {\n int toread = remaining > 4000 ? 4000 : remaining;\n int in = read(rndfd, buf, toread);\n if (in < 0)\n throw string(\"Failed to read \/dev\/urandom\");\n int wrote = write(fd, buf, in);\n if (wrote < 0)\n throw string(\"Failed to write to file\");\n remaining -= wrote;\n }\n\n delete[] buf;\n}\n\nvoid DirProcessor::procdir(int dirfd, int level, int nsubdirs, int nfiles, uint64_t filesize)\n{\n int fd = 0;\n int i = 0, rc = 0;\n ostringstream ost;\n\n if (globerr)\n return;\n \/\/ Create subdirs\n if (level > 0) {\n for (i=0; i< nsubdirs; i++) {\n ost << \"dir\" << i; \n const string& dirname = ost.str();\n const char *dirname_c = dirname.c_str();\n rc = mkdirat(dirfd, dirname_c, 0777); \n if (rc < 0) {\n perror(\"mkdirat\");\n throw string(\"mkdirat() failed\");\n }\n fd = openat(dirfd, dirname_c, O_RDONLY);\n if (fd < 0) {\n perror(\"openat\");\n throw string(\"openat() failed for subdir\");\n }\n ost.clear(); ost.str(\"\");\n \/*\n * If a DP object is available from freelist, use that.\n * else do recursive processing.\n *\/\n DirProcessor *dp = dynamic_cast<DirProcessor *>(freelist.getItem());\n if (dp) {\n dp->setParams(fd, level-1, nsubdirs, nfiles, filesize);\n wtp->addWorkItem(dp);\n } else {\n procdir(fd, level-1, nsubdirs, nfiles, filesize);\n }\n \n }\n }\n\n\n for (i=0; i<nfiles; i++) {\n ost << \"file\" << i;\n const string& filename = ost.str();\n int fd = openat(dirfd, filename.c_str(),\n O_CREAT | O_WRONLY | O_TRUNC, 0666);\n if (fd < 0) \n throw string(\"openat() failed\");\n randfile(fd, filesize);\n close(fd);\n ost.clear(); ost.str(\"\");\n }\n\n close(dirfd);\n\n}\n\nint usage_exit(const string& progname, const string& err)\n{\n cerr << \"Error: \" << string(err) << endl;\n cerr << \"Usage: \" << progname << \n \" --height=height --nfiles=files-perdir --height=tree-height\" <<\n \" topdir\" << endl;\n\n exit(-1);\n\n}\n\nstatic std::map<string, int *> valmap;\nvoid setGlobalVal(const string& progname, const string& optname, const string& optvalstr)\n{\n std::map<string, int *>::iterator iter = valmap.find(optname);\n assert (iter != valmap.end());\n int *valptr = valmap[optname];\n *valptr = atoi(optvalstr.c_str());\n if (*valptr <= 0)\n usage_exit(progname, string(\"Option argument must be positive integer\"));\n}\n\nint main(int argc, char *argv[])\n{\n\n int ndirs = 4;\n int nfiles = 6;\n int height = 6;\n int filesize = 8000;\n const string progname(argv[0]);\n\n valmap[string(\"ndirs\")] = &ndirs;\n valmap[string(\"nfiles\")] = &nfiles;\n valmap[string(\"height\")] = &height;\n valmap[string(\"filesize\")] = &filesize;\n\n int option_index = 0;\n const char *topdir = NULL;\n struct option longopts[] = {\n {\"ndirs\", required_argument, 0, 0},\n {\"nfiles\", required_argument, 0, 0},\n {\"height\", required_argument, 0, 0},\n {\"filesize\", required_argument, 0, 0},\n {0, 0, 0, 0}\n };\n\n while (1) {\n int c = getopt_long(argc, argv, \"\", longopts, &option_index);\n if (c == -1)\n break;\n if (c != 0)\n usage_exit(progname, string(\"Command line parse error\"));\n string optname(longopts[option_index].name);\n string optvalstr(optarg);\n\n setGlobalVal(progname, optname, optvalstr);\n\n }\n\n if (optind == (argc-1)) {\n topdir = argv[optind];\n } else {\n usage_exit(progname, string(\"Insufficient arguments\"));\n }\n\ntry {\n rndfd = open(\"\/dev\/urandom\", O_RDONLY);\n if (rndfd < 0) {\n perror(\"\/dev\/urandom\");\n throw string(\"Failed to open \/dev\/urandom\");\n }\n int rc = mkdir(topdir, 0777);\n if (rc < 0)\n throw string(\"Failed to create top level dir\");\n int dirfd = open(topdir, O_RDONLY);\n if (dirfd < 0)\n throw string(\"Failed to open top level dir.\");\n\n int i=0;\n for (i=0; i< 1000; i++) {\n DirProcessor *dp = new DirProcessor();\n freelist.addItem(dp);\n }\n\n wtp = new WorkerThreadPool(16);\n wtp->startThreads();\n\n DirProcessor *dp = new DirProcessor();\n dp->setParams(dirfd, height, ndirs, nfiles, filesize);\n\n wtp->addWorkItem(dp);\n\n cout << \"Waiting for empty\\n\";\n wtp->waitEmpty();\n cout << \"WTP empty. Waiting for shutdown.\\n\";\n wtp->shutDown();\n delete wtp;\n\n if (globerr < 0)\n cout << \"Failure\" << endl;\n\n} catch (InternalError& exc) {\n cout << \"WTP internal bug or system is in unstable state: \" << exc.getMessage() << endl;\n} catch (CallerError& exc) {\n cout << \"Illegal use of WTP library: \" << exc.getMessage() << endl;\n} catch(std::string& err) {\n cout << err << endl;\n}\n\n}\n<commit_msg>Added cpulite. This feature runs treebuild without some cpu-intensive activities, like generating random numbers.<commit_after>\n\/**\n * THIS IS WORK IN PROGRESS!\n *\/\n\n#include \"Freelist.h\"\n#include \"WTPExceptions.h\"\n#include \"WorkerThreadPool.h\"\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <errno.h>\n#include <string>\n#include <stdio.h>\n#include <iostream>\n#include <cstdlib>\n#include <sstream>\n#include <assert.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <map>\n\nusing namespace std;\nusing namespace WTP;\nWorkerThreadPool *wtp = NULL;\nint globerr = 0;\nint rndfd = 0;\nFreelist freelist;\nint cpulite = 0;\nchar *litebuf = NULL;\n\nclass DirProcessor : public WorkItem {\npublic:\n static void procdir(int dirfd, int level, int nsubdirs, int nfiles, uint64_t filesize);\n static void randfile(int fd, uint64_t size);\n static void randfile_lite(int fd, uint64_t size);\n\n void setParams(int dirfd, int level, int nsubdirs, int nfiles,\n uint64_t filesize) {\n _dirfd = dirfd;\n _level = level;\n _nsubdirs=nsubdirs;\n _nfiles=nfiles;\n _filesize=filesize;\n }\n void run() {\n procdir(_dirfd, _level, _nsubdirs, _nfiles, _filesize);\n }\n\n void reset() {\n _dirfd = -1;\n _level = 0;\n _nsubdirs=0;\n _nfiles=0;\n _filesize=0;\n }\n\nprivate:\n int _dirfd, _level, _nsubdirs, _nfiles;\n uint64_t _filesize;\n};\n\nvoid DirProcessor::randfile_lite(int fd, uint64_t size)\n{\n uint64_t remaining = size;\n while (remaining > 0) {\n int towrite = remaining > 4000 ? 4000 : remaining;\n int wrote = write(fd, litebuf, towrite);\n if (wrote < 0)\n throw string(\"Failed to write to file\");\n remaining -= wrote;\n }\n\n}\nvoid DirProcessor::randfile(int fd, uint64_t size)\n{\n uint64_t remaining = size;\n char *buf = new char[4000];\n while (remaining > 0) {\n int toread = remaining > 4000 ? 4000 : remaining;\n int in = read(rndfd, buf, toread);\n if (in < 0)\n throw string(\"Failed to read \/dev\/urandom\");\n int wrote = write(fd, buf, in);\n if (wrote < 0)\n throw string(\"Failed to write to file\");\n remaining -= wrote;\n }\n\n delete[] buf;\n}\n\nvoid DirProcessor::procdir(int dirfd, int level, int nsubdirs, int nfiles, uint64_t filesize)\n{\n int fd = 0;\n int i = 0, rc = 0;\n ostringstream ost;\n\n if (globerr)\n return;\n \/\/ Create subdirs\n if (level > 0) {\n for (i=0; i< nsubdirs; i++) {\n ost << \"dir\" << i; \n const string& dirname = ost.str();\n const char *dirname_c = dirname.c_str();\n rc = mkdirat(dirfd, dirname_c, 0777); \n if (rc < 0) {\n perror(\"mkdirat\");\n throw string(\"mkdirat() failed\");\n }\n fd = openat(dirfd, dirname_c, O_RDONLY);\n if (fd < 0) {\n perror(\"openat\");\n throw string(\"openat() failed for subdir\");\n }\n ost.clear(); ost.str(\"\");\n \/*\n * If a DP object is available from freelist, use that.\n * else do recursive processing.\n *\/\n DirProcessor *dp = dynamic_cast<DirProcessor *>(freelist.getItem());\n if (dp) {\n dp->setParams(fd, level-1, nsubdirs, nfiles, filesize);\n wtp->addWorkItem(dp);\n } else {\n procdir(fd, level-1, nsubdirs, nfiles, filesize);\n }\n \n }\n }\n\n\n for (i=0; i<nfiles; i++) {\n ost << \"file\" << i;\n const string& filename = ost.str();\n int fd = openat(dirfd, filename.c_str(),\n O_CREAT | O_WRONLY | O_TRUNC, 0666);\n if (fd < 0) \n throw string(\"openat() failed\");\n if (cpulite)\n randfile_lite(fd, filesize);\n else\n randfile(fd, filesize);\n close(fd);\n ost.clear(); ost.str(\"\");\n }\n\n close(dirfd);\n\n}\n\nint usage_exit(const string& progname, const string& err)\n{\n cerr << \"Error: \" << string(err) << endl;\n cerr << \"Usage: \" << progname << \n \" --height=height --nfiles=files-perdir --height=tree-height\" <<\n \" topdir\" << endl;\n\n exit(-1);\n\n}\n\nstatic std::map<string, int *> valmap;\nvoid setGlobalVal(const string& progname, const string& optname, const string& optvalstr)\n{\n std::map<string, int *>::iterator iter = valmap.find(optname);\n assert (iter != valmap.end());\n int *valptr = valmap[optname];\n *valptr = atoi(optvalstr.c_str());\n if (*valptr <= 0)\n usage_exit(progname, string(\"Option argument must be positive integer\"));\n}\n\nint main(int argc, char *argv[])\n{\n\n int ndirs = 4;\n int nfiles = 6;\n int height = 6;\n int filesize = 8000;\n const string progname(argv[0]);\n\n valmap[string(\"ndirs\")] = &ndirs;\n valmap[string(\"nfiles\")] = &nfiles;\n valmap[string(\"height\")] = &height;\n valmap[string(\"filesize\")] = &filesize;\n valmap[string(\"cpulite\")] = &cpulite;\n\n int option_index = 0;\n const char *topdir = NULL;\n struct option longopts[] = {\n {\"ndirs\", required_argument, 0, 0},\n {\"nfiles\", required_argument, 0, 0},\n {\"height\", required_argument, 0, 0},\n {\"filesize\", required_argument, 0, 0},\n {\"cpulite\", optional_argument, 0, 0},\n {0, 0, 0, 0}\n };\n\n while (1) {\n int c = getopt_long(argc, argv, \"\", longopts, &option_index);\n if (c == -1)\n break;\n if (c != 0)\n usage_exit(progname, string(\"Command line parse error\"));\n string optname(longopts[option_index].name);\n string optvalstr(optarg);\n\n setGlobalVal(progname, optname, optvalstr);\n\n }\n\n if (optind == (argc-1)) {\n topdir = argv[optind];\n } else {\n usage_exit(progname, string(\"Insufficient arguments\"));\n }\n\ntry {\n rndfd = open(\"\/dev\/urandom\", O_RDONLY);\n if (rndfd < 0) {\n perror(\"\/dev\/urandom\");\n throw string(\"Failed to open \/dev\/urandom\");\n }\n if (cpulite) {\n\t litebuf = new char[4000];\n read(rndfd, litebuf, 4000);\n close(rndfd);\n\t}\n int rc = mkdir(topdir, 0777);\n if (rc < 0)\n throw string(\"Failed to create top level dir\");\n int dirfd = open(topdir, O_RDONLY);\n if (dirfd < 0)\n throw string(\"Failed to open top level dir.\");\n\n int i=0;\n for (i=0; i< 1000; i++) {\n DirProcessor *dp = new DirProcessor();\n freelist.addItem(dp);\n }\n\n wtp = new WorkerThreadPool(16);\n wtp->startThreads();\n\n DirProcessor *dp = new DirProcessor();\n dp->setParams(dirfd, height, ndirs, nfiles, filesize);\n\n wtp->addWorkItem(dp);\n\n cout << \"Waiting for empty\\n\";\n wtp->waitEmpty();\n cout << \"WTP empty. Waiting for shutdown.\\n\";\n wtp->shutDown();\n delete wtp;\n if (cpulite)\n delete[] litebuf;\n\n if (globerr < 0)\n cout << \"Failure\" << endl;\n\n} catch (InternalError& exc) {\n cout << \"WTP internal bug or system is in unstable state: \" << exc.getMessage() << endl;\n} catch (CallerError& exc) {\n cout << \"Illegal use of WTP library: \" << exc.getMessage() << endl;\n} catch(std::string& err) {\n cout << err << endl;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n#include \"ds3.h\"\n#include \"test.h\"\n#include <boost\/test\/unit_test.hpp>\n\n#define FILE_TEMPLATE \"bulk-XXXXXX\"\n\nBOOST_AUTO_TEST_CASE( bulk_get ) {\n uint64_t i, n;\n uint64_t file_index = 0;\n ds3_request* request = NULL;\n ds3_error* error = NULL;\n ds3_bulk_response* completed_job = NULL;\n ds3_get_bucket_response* response = NULL;\n ds3_bulk_response* bulk_response = NULL;\n ds3_bulk_object_list* object_list = NULL;\n ds3_get_available_chunks_response* chunk_response = NULL;\n bool retry_get;\n\n ds3_client* client = get_client();\n const char* bucket_name = \"unit_test_bucket\";\n\n char** tmp_files;\n\n populate_with_objects(client, bucket_name);\n\n request = ds3_init_get_bucket(bucket_name);\n error = ds3_get_bucket(client, request, &response);\n\n ds3_free_request(request);\n\n BOOST_REQUIRE(error == NULL);\n\n tmp_files = (char**) calloc(response->num_objects, sizeof(char*));\n\n object_list = ds3_convert_object_list(response->objects, response->num_objects);\n\n request = ds3_init_get_bulk(bucket_name, object_list, NONE);\n error = ds3_bulk(client, request, &bulk_response);\n\n ds3_free_request(request);\n ds3_free_bulk_object_list(object_list);\n\n BOOST_REQUIRE(error == NULL);\n\n do {\n retry_get = false;\n request = ds3_init_get_available_chunks(bulk_response->job_id->value);\n\n error = ds3_get_available_chunks(client, request, &chunk_response);\n\n ds3_free_request(request);\n\n BOOST_REQUIRE(error == NULL);\n\n BOOST_REQUIRE(chunk_response != NULL);\n\n if (chunk_response->object_list->list_size == 0) {\n \/\/ if this happens we need to try the request\n retry_get = true;\n BOOST_TEST_MESSAGE( \"Hit retry, sleeping for: \" << chunk_response->retry_after) ;\n sleep(chunk_response->retry_after);\n }\n\n } while(retry_get);\n\n BOOST_REQUIRE(error == NULL);\n\n for (i = 0; i < chunk_response->object_list->list_size; i++) {\n ds3_bulk_object_list* chunk_object_list = chunk_response->object_list->list[i];\n for(n = 0; n < chunk_object_list->size; n++, file_index++) {\n FILE* w_file;\n ds3_bulk_object current_obj = chunk_object_list->list[n];\n request = ds3_init_get_object_for_job(bucket_name, current_obj.name->value, current_obj.offset, bulk_response->job_id->value);\n tmp_files[file_index] = (char*) calloc(13, sizeof(char));\n memcpy(tmp_files[file_index], FILE_TEMPLATE, 12);\n w_file = fopen(tmp_files[file_index], \"w+\");\n error = ds3_get_object(client, request, w_file, ds3_write_to_file);\n fclose(w_file);\n handle_error(error);\n }\n }\n\n for (i = 0; i <= file_index;i++) {\n unlink(tmp_files[i]);\n }\n\n free(tmp_files);\n \n \/\/ check to make sure that the 'job' has completed\n request = ds3_init_get_job(bulk_response->job_id->value);\n error = ds3_get_job(client, request, &completed_job);\n\n BOOST_CHECK(completed_job != NULL);\n BOOST_CHECK(completed_job->status == COMPLETED);\n \n ds3_free_request(request);\n ds3_free_available_chunks_response(chunk_response);\n ds3_free_bulk_response(completed_job);\n ds3_free_bulk_response(bulk_response);\n\n clear_bucket(client, bucket_name);\n \n handle_error(error);\n}\n\nBOOST_AUTO_TEST_CASE( convert_list_helper ) {\n const char* books[4] ={\"beowulf.txt\", \"sherlock_holmes.txt\", \"tale_of_two_cities.txt\", \"ulysses.txt\"};\n ds3_bulk_object_list* obj_list;\n\n obj_list = ds3_convert_file_list_with_basepath(books, 4, \"resources\/\");\n\n BOOST_CHECK(strcmp(obj_list->list[0].name->value, \"beowulf.txt\") == 0);\n BOOST_CHECK(obj_list->list[0].length == 294059);\n}\n\nBOOST_AUTO_TEST_CASE( directory_size ) {\n const char* books[1] ={\"resources\"};\n ds3_bulk_object_list* obj_list;\n\n obj_list = ds3_convert_file_list_with_basepath(books, 1, NULL);\n\n BOOST_CHECK(strcmp(obj_list->list[0].name->value, \"resources\") == 0);\n BOOST_CHECK(obj_list->list[0].length == 0);\n}\n<commit_msg>Added a missing free in the bulk_get integration test.<commit_after>#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n#include \"ds3.h\"\n#include \"test.h\"\n#include <boost\/test\/unit_test.hpp>\n\n#define FILE_TEMPLATE \"bulk-XXXXXX\"\n\nBOOST_AUTO_TEST_CASE( bulk_get ) {\n uint64_t i, n;\n uint64_t file_index = 0;\n ds3_request* request = NULL;\n ds3_error* error = NULL;\n ds3_bulk_response* completed_job = NULL;\n ds3_get_bucket_response* response = NULL;\n ds3_bulk_response* bulk_response = NULL;\n ds3_bulk_object_list* object_list = NULL;\n ds3_get_available_chunks_response* chunk_response = NULL;\n bool retry_get;\n\n ds3_client* client = get_client();\n const char* bucket_name = \"unit_test_bucket\";\n\n char** tmp_files;\n\n populate_with_objects(client, bucket_name);\n\n request = ds3_init_get_bucket(bucket_name);\n error = ds3_get_bucket(client, request, &response);\n\n ds3_free_request(request);\n\n BOOST_REQUIRE(error == NULL);\n\n tmp_files = (char**) calloc(response->num_objects, sizeof(char*));\n\n object_list = ds3_convert_object_list(response->objects, response->num_objects);\n\n request = ds3_init_get_bulk(bucket_name, object_list, NONE);\n error = ds3_bulk(client, request, &bulk_response);\n\n ds3_free_request(request);\n ds3_free_bulk_object_list(object_list);\n\n BOOST_REQUIRE(error == NULL);\n\n do {\n retry_get = false;\n request = ds3_init_get_available_chunks(bulk_response->job_id->value);\n\n error = ds3_get_available_chunks(client, request, &chunk_response);\n\n ds3_free_request(request);\n\n BOOST_REQUIRE(error == NULL);\n\n BOOST_REQUIRE(chunk_response != NULL);\n\n if (chunk_response->object_list->list_size == 0) {\n \/\/ if this happens we need to try the request\n retry_get = true;\n BOOST_TEST_MESSAGE( \"Hit retry, sleeping for: \" << chunk_response->retry_after) ;\n sleep(chunk_response->retry_after);\n }\n\n } while(retry_get);\n\n BOOST_REQUIRE(error == NULL);\n\n for (i = 0; i < chunk_response->object_list->list_size; i++) {\n ds3_bulk_object_list* chunk_object_list = chunk_response->object_list->list[i];\n for(n = 0; n < chunk_object_list->size; n++, file_index++) {\n FILE* w_file;\n ds3_bulk_object current_obj = chunk_object_list->list[n];\n request = ds3_init_get_object_for_job(bucket_name, current_obj.name->value, current_obj.offset, bulk_response->job_id->value);\n tmp_files[file_index] = (char*) calloc(13, sizeof(char));\n memcpy(tmp_files[file_index], FILE_TEMPLATE, 12);\n w_file = fopen(tmp_files[file_index], \"w+\");\n error = ds3_get_object(client, request, w_file, ds3_write_to_file);\n ds3_free_request(request);\n fclose(w_file);\n handle_error(error);\n }\n }\n\n for (i = 0; i <= file_index;i++) {\n unlink(tmp_files[i]);\n }\n\n free(tmp_files);\n\n \/\/ check to make sure that the 'job' has completed\n request = ds3_init_get_job(bulk_response->job_id->value);\n error = ds3_get_job(client, request, &completed_job);\n\n BOOST_CHECK(completed_job != NULL);\n BOOST_CHECK(completed_job->status == COMPLETED);\n\n ds3_free_request(request);\n ds3_free_available_chunks_response(chunk_response);\n ds3_free_bulk_response(completed_job);\n ds3_free_bulk_response(bulk_response);\n\n clear_bucket(client, bucket_name);\n \n handle_error(error);\n}\n\nBOOST_AUTO_TEST_CASE( convert_list_helper ) {\n const char* books[4] ={\"beowulf.txt\", \"sherlock_holmes.txt\", \"tale_of_two_cities.txt\", \"ulysses.txt\"};\n ds3_bulk_object_list* obj_list;\n\n obj_list = ds3_convert_file_list_with_basepath(books, 4, \"resources\/\");\n\n BOOST_CHECK(strcmp(obj_list->list[0].name->value, \"beowulf.txt\") == 0);\n BOOST_CHECK(obj_list->list[0].length == 294059);\n}\n\nBOOST_AUTO_TEST_CASE( directory_size ) {\n const char* books[1] ={\"resources\"};\n ds3_bulk_object_list* obj_list;\n\n obj_list = ds3_convert_file_list_with_basepath(books, 1, NULL);\n\n BOOST_CHECK(strcmp(obj_list->list[0].name->value, \"resources\") == 0);\n BOOST_CHECK(obj_list->list[0].length == 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#if EIGEN_ALIGN\n#define ALIGNMENT 16\n#else\n#define ALIGNMENT 1\n#endif\n\nvoid check_handmade_aligned_malloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n char *p = (char*)internal::handmade_aligned_malloc(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::handmade_aligned_free(p);\n }\n}\n\nvoid check_aligned_malloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n char *p = (char*)internal::aligned_malloc(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::aligned_free(p);\n }\n}\n\nvoid check_aligned_new()\n{\n for(int i = 1; i < 1000; i++)\n {\n float *p = internal::aligned_new<float>(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::aligned_delete(p,i);\n }\n}\n\nvoid check_aligned_stack_alloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n ei_declare_aligned_stack_constructed_variable(float,p,i,0);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n }\n}\n\n\n\/\/ test compilation with both a struct and a class...\nstruct MyStruct\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n char dummychar;\n Vector4f avec;\n};\n\nclass MyClassA\n{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n char dummychar;\n Vector4f avec;\n};\n\ntemplate<typename T> void check_dynaligned()\n{\n T* obj = new T;\n VERIFY(size_t(obj)%ALIGNMENT==0);\n delete obj;\n}\n\nvoid test_dynalloc()\n{\n \/\/ low level dynamic memory allocation\n CALL_SUBTEST(check_handmade_aligned_malloc());\n CALL_SUBTEST(check_aligned_malloc());\n CALL_SUBTEST(check_aligned_new());\n CALL_SUBTEST(check_aligned_stack_alloc());\n\n for (int i=0; i<g_repeat*100; ++i)\n {\n CALL_SUBTEST(check_dynaligned<Vector4f>() );\n CALL_SUBTEST(check_dynaligned<Vector2d>() );\n CALL_SUBTEST(check_dynaligned<Matrix4f>() );\n CALL_SUBTEST(check_dynaligned<Vector4d>() );\n CALL_SUBTEST(check_dynaligned<Vector4i>() );\n }\n \n \/\/ check static allocation, who knows ?\n #if EIGEN_ALIGN_STATICALLY\n {\n MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);\n MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);\n }\n \n \/\/ dynamic allocation, single object\n for (int i=0; i<g_repeat*100; ++i)\n {\n MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n delete foo0;\n delete fooA;\n }\n\n \/\/ dynamic allocation, array\n const int N = 10;\n for (int i=0; i<g_repeat*100; ++i)\n {\n MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n delete[] foo0;\n delete[] fooA;\n }\n #endif\n \n}\n<commit_msg>Check that NeedsToAlign is properly sets before checking alignment<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#if EIGEN_ALIGN\n#define ALIGNMENT 16\n#else\n#define ALIGNMENT 1\n#endif\n\nvoid check_handmade_aligned_malloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n char *p = (char*)internal::handmade_aligned_malloc(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::handmade_aligned_free(p);\n }\n}\n\nvoid check_aligned_malloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n char *p = (char*)internal::aligned_malloc(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::aligned_free(p);\n }\n}\n\nvoid check_aligned_new()\n{\n for(int i = 1; i < 1000; i++)\n {\n float *p = internal::aligned_new<float>(i);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n internal::aligned_delete(p,i);\n }\n}\n\nvoid check_aligned_stack_alloc()\n{\n for(int i = 1; i < 1000; i++)\n {\n ei_declare_aligned_stack_constructed_variable(float,p,i,0);\n VERIFY(size_t(p)%ALIGNMENT==0);\n \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n for(int j = 0; j < i; j++) p[j]=0;\n }\n}\n\n\n\/\/ test compilation with both a struct and a class...\nstruct MyStruct\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n char dummychar;\n Vector4f avec;\n};\n\nclass MyClassA\n{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n char dummychar;\n Vector4f avec;\n};\n\ntemplate<typename T> void check_dynaligned()\n{\n T* obj = new T;\n VERIFY(T::NeedsToAlign==1);\n VERIFY(size_t(obj)%ALIGNMENT==0);\n delete obj;\n}\n\nvoid test_dynalloc()\n{\n \/\/ low level dynamic memory allocation\n CALL_SUBTEST(check_handmade_aligned_malloc());\n CALL_SUBTEST(check_aligned_malloc());\n CALL_SUBTEST(check_aligned_new());\n CALL_SUBTEST(check_aligned_stack_alloc());\n\n for (int i=0; i<g_repeat*100; ++i)\n {\n CALL_SUBTEST(check_dynaligned<Vector4f>() );\n CALL_SUBTEST(check_dynaligned<Vector2d>() );\n CALL_SUBTEST(check_dynaligned<Matrix4f>() );\n CALL_SUBTEST(check_dynaligned<Vector4d>() );\n CALL_SUBTEST(check_dynaligned<Vector4i>() );\n }\n \n \/\/ check static allocation, who knows ?\n #if EIGEN_ALIGN_STATICALLY\n {\n MyStruct foo0; VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);\n MyClassA fooA; VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);\n }\n \n \/\/ dynamic allocation, single object\n for (int i=0; i<g_repeat*100; ++i)\n {\n MyStruct *foo0 = new MyStruct(); VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n MyClassA *fooA = new MyClassA(); VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n delete foo0;\n delete fooA;\n }\n\n \/\/ dynamic allocation, array\n const int N = 10;\n for (int i=0; i<g_repeat*100; ++i)\n {\n MyStruct *foo0 = new MyStruct[N]; VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n MyClassA *fooA = new MyClassA[N]; VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n delete[] foo0;\n delete[] fooA;\n }\n #endif\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2001 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT)\n#ident \"$Id: load_module.cc,v 1.3 2001\/11\/16 05:07:19 steve Exp $\"\n#endif\n\n# include \"config.h\"\n# include \"util.h\"\n# include \"parse_api.h\"\n# include \"compiler.h\"\n# include <iostream.h>\n\n\nconst char dir_character = '\/';\n\nbool load_module(const char*type)\n{\n char path[4096];\n\n for (list<const char*>::iterator cur = library_dirs.begin()\n\t\t ; cur != library_dirs.end()\n\t\t ; cur ++ ) {\n\t for (list<const char*>::iterator suf = library_suff.begin()\n\t\t ; suf != library_suff.end()\n\t\t ; suf ++ ) {\n\n\t\t sprintf(path, \"%s%c%s%s\", *cur, dir_character, type, *suf);\n\n\t\t FILE*file = fopen(path, \"r\");\n\t\t if (file == 0)\n\t\t\tcontinue;\n\n\t\t if (verbose_flag) {\n\t\t\tcerr << \"Loading library file \" << path << \".\" << endl;\n\t\t }\n\n\t\t pform_parse(path, file);\n\t\t return true;\n\t }\n }\n\n return false;\n}\n\n\/*\n * $Log: load_module.cc,v $\n * Revision 1.3 2001\/11\/16 05:07:19 steve\n * Add support for +libext+ in command files.\n *\n * Revision 1.2 2001\/10\/22 02:05:21 steve\n * Handle activating tasks in another root.\n *\n * Revision 1.1 2001\/10\/20 23:02:40 steve\n * Add automatic module libraries.\n *\n *\/\n\n<commit_msg> Close library files after parsing.<commit_after>\/*\n * Copyright (c) 2001 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT)\n#ident \"$Id: load_module.cc,v 1.4 2001\/11\/20 23:36:34 steve Exp $\"\n#endif\n\n# include \"config.h\"\n# include \"util.h\"\n# include \"parse_api.h\"\n# include \"compiler.h\"\n# include <iostream.h>\n\n\nconst char dir_character = '\/';\n\nbool load_module(const char*type)\n{\n char path[4096];\n\n for (list<const char*>::iterator cur = library_dirs.begin()\n\t\t ; cur != library_dirs.end()\n\t\t ; cur ++ ) {\n\t for (list<const char*>::iterator suf = library_suff.begin()\n\t\t ; suf != library_suff.end()\n\t\t ; suf ++ ) {\n\n\t\t sprintf(path, \"%s%c%s%s\", *cur, dir_character, type, *suf);\n\n\t\t FILE*file = fopen(path, \"r\");\n\t\t if (file == 0)\n\t\t\tcontinue;\n\n\t\t if (verbose_flag) {\n\t\t\tcerr << \"Loading library file \" << path << \".\" << endl;\n\t\t }\n\n\t\t pform_parse(path, file);\n\n\t\t fclose(file);\n\t\t return true;\n\t }\n }\n\n return false;\n}\n\n\/*\n * $Log: load_module.cc,v $\n * Revision 1.4 2001\/11\/20 23:36:34 steve\n * Close library files after parsing.\n *\n * Revision 1.3 2001\/11\/16 05:07:19 steve\n * Add support for +libext+ in command files.\n *\n * Revision 1.2 2001\/10\/22 02:05:21 steve\n * Handle activating tasks in another root.\n *\n * Revision 1.1 2001\/10\/20 23:02:40 steve\n * Add automatic module libraries.\n *\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_OS_WINDOWS_FD_HPP__\n#define __STOUT_OS_WINDOWS_FD_HPP__\n\n#include <fcntl.h> \/\/ For `O_RDWR`.\n#include <io.h> \/\/ For `_open_osfhandle`.\n\n#include <array>\n#include <memory>\n#include <ostream>\n#include <type_traits>\n\n#include <stout\/check.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/try.hpp>\n#include <stout\/unreachable.hpp>\n#include <stout\/windows.hpp> \/\/ For `WinSock2.h`.\n\nnamespace os {\n\n\/\/ The `WindowsFD` class exists to provide an common interface with the POSIX\n\/\/ file descriptor. While the bare `int` representation of the POSIX file\n\/\/ descriptor API is undesirable, we rendezvous there in order to maintain the\n\/\/ existing code in Mesos.\n\/\/\n\/\/ In the platform-agnostic code paths, the `int_fd` type is aliased to\n\/\/ `WindowsFD`. The `os::*` functions return a type appropriate to the platform,\n\/\/ which allows us to write code like this:\n\/\/\n\/\/ Try<int_fd> fd = os::open(...);\n\/\/\n\/\/ The `WindowsFD` constructs off one of:\n\/\/ (1) `HANDLE` - from the Win32 API\n\/\/ (2) `SOCKET` - from the WinSock API\n\/\/\n\/\/ The `os::*` functions then take an instance of `WindowsFD`, examines\n\/\/ the state and dispatches to the appropriate API.\n\nclass WindowsFD\n{\npublic:\n enum class Type\n {\n HANDLE,\n SOCKET\n };\n\n \/\/ The `HANDLE` here is expected to be file handles. Specifically,\n \/\/ `HANDLE`s returned by file API such as `CreateFile`. There are\n \/\/ APIs that return `HANDLE`s with different error values, and\n \/\/ therefore must be handled accordingly. For example, a thread API\n \/\/ such as `CreateThread` returns `NULL` as the error value, rather\n \/\/ than `INVALID_HANDLE_VALUE`.\n \/\/\n \/\/ TODO(mpark): Consider adding a second parameter which tells us\n \/\/ what the error values are.\n static_assert(\n std::is_same<HANDLE, void*>::value,\n \"Expected `HANDLE` to be of type `void*`.\");\n explicit WindowsFD(HANDLE handle, bool overlapped = false)\n : type_(Type::HANDLE), handle_(handle), overlapped_(overlapped)\n {}\n\n \/\/ The `SOCKET` here is expected to be Windows sockets, such as that\n \/\/ used by the Windows Sockets 2 library. The only expected error\n \/\/ value is `INVALID_SOCKET`.\n \/\/\n \/\/ Note that sockets should almost always be overlapped. We do provide\n \/\/ a way in stout to create non-overlapped sockets, so for completeness, we\n \/\/ have an overlapped parameter in the constructor.\n static_assert(\n std::is_same<SOCKET, unsigned __int64>::value,\n \"Expected `SOCKET` to be of type `unsigned __int64`.\");\n explicit WindowsFD(SOCKET socket, bool overlapped = true)\n : type_(Type::SOCKET), socket_(socket), overlapped_(overlapped)\n {}\n\n \/\/ On Windows, libevent's `evutil_socket_t` is set to `intptr_t`.\n explicit WindowsFD(intptr_t socket) : WindowsFD(static_cast<SOCKET>(socket))\n {}\n\n \/\/ This constructor is provided in so that the canonical integer\n \/\/ file descriptors representing `stdin` (0), `stdout` (1), and\n \/\/ `stderr` (2), and the invalid value of -1 can be used.\n WindowsFD(int crt) : WindowsFD(INVALID_HANDLE_VALUE)\n {\n if (crt == -1) {\n \/\/ No-op, already `INVALID_HANDLE_VALUE`.\n } else if (crt == 0) {\n handle_ = ::GetStdHandle(STD_INPUT_HANDLE);\n } else if (crt == 1) {\n handle_ = ::GetStdHandle(STD_OUTPUT_HANDLE);\n } else if (crt == 2) {\n handle_ = ::GetStdHandle(STD_ERROR_HANDLE);\n } else {\n \/\/ This would be better enforced at compile-time, but not\n \/\/ currently possible, so this is a sanity check.\n LOG(FATAL) << \"Unexpected construction of `WindowsFD`\";\n }\n }\n\n \/\/ Default construct with invalid handle semantics.\n WindowsFD() : WindowsFD(INVALID_HANDLE_VALUE) {}\n\n WindowsFD(const WindowsFD&) = default;\n WindowsFD(WindowsFD&&) = default;\n\n WindowsFD& operator=(const WindowsFD&) = default;\n WindowsFD& operator=(WindowsFD&&) = default;\n\n ~WindowsFD() = default;\n\n bool is_valid() const\n {\n switch (type()) {\n case Type::HANDLE: {\n \/\/ Remember that both of these values can represent an invalid\n \/\/ handle.\n return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;\n }\n case Type::SOCKET: {\n \/\/ Only this value is used for an invalid socket.\n return socket_ != INVALID_SOCKET;\n }\n default: {\n return false;\n }\n }\n }\n\n \/\/ NOTE: This allocates a C run-time file descriptor and associates\n \/\/ it with the handle. At this point, the `HANDLE` should no longer\n \/\/ be closed via `CloseHandle`, but instead close the returned `int`\n \/\/ with `_close`. This method should almost never be used, and\n \/\/ exists only for compatibility with 3rdparty dependencies.\n int crt() const\n {\n CHECK_EQ(Type::HANDLE, type());\n \/\/ TODO(andschwa): Consider if we should overwrite `handle_`.\n return ::_open_osfhandle(reinterpret_cast<intptr_t>(handle_), O_RDWR);\n }\n\n operator HANDLE() const\n {\n CHECK_EQ(Type::HANDLE, type());\n return handle_;\n }\n\n operator SOCKET() const\n {\n CHECK_EQ(Type::SOCKET, type());\n return socket_;\n }\n\n \/\/ On Windows, libevent's `evutil_socket_t` is set to `intptr_t`.\n operator intptr_t() const\n {\n CHECK_EQ(Type::SOCKET, type());\n return static_cast<intptr_t>(socket_);\n }\n\n Type type() const { return type_; }\n\n bool is_overlapped() const { return overlapped_; }\n\nprivate:\n Type type_;\n\n union\n {\n HANDLE handle_;\n SOCKET socket_;\n };\n\n bool overlapped_;\n\n \/\/ NOTE: This function is provided only for checking validity, thus\n \/\/ it is private. It provides a view of a `WindowsFD` as an `int`.\n \/\/\n \/\/ TODO(andschwa): Fix all uses of this conversion to use `is_valid`\n \/\/ directly instead, then remove the comparison operators. This\n \/\/ would require writing an `int_fd` class for POSIX too, instead of\n \/\/ just using `int`.\n int get_valid() const\n {\n if (is_valid()) {\n return 0;\n } else {\n return -1;\n }\n }\n\n \/\/ NOTE: These operators are used solely to support checking a\n \/\/ `WindowsFD` against e.g. -1 or 0 for validity. Nothing else\n \/\/ should have access to `get_valid()`.\n friend bool operator<(int left, const WindowsFD& right);\n friend bool operator<(const WindowsFD& left, int right);\n friend bool operator>(int left, const WindowsFD& right);\n friend bool operator>(const WindowsFD& left, int right);\n friend bool operator<=(int left, const WindowsFD& right);\n friend bool operator<=(const WindowsFD& left, int right);\n friend bool operator>=(int left, const WindowsFD& right);\n friend bool operator>=(const WindowsFD& left, int right);\n friend bool operator==(int left, const WindowsFD& right);\n friend bool operator==(const WindowsFD& left, int right);\n friend bool operator!=(int left, const WindowsFD& right);\n friend bool operator!=(const WindowsFD& left, int right);\n};\n\n\ninline std::ostream& operator<<(std::ostream& stream, const WindowsFD::Type& fd)\n{\n switch (fd) {\n case WindowsFD::Type::HANDLE: {\n stream << \"WindowsFD::Type::HANDLE\";\n return stream;\n }\n case WindowsFD::Type::SOCKET: {\n stream << \"WindowsFD::Type::SOCKET\";\n return stream;\n }\n default: {\n stream << \"WindowsFD::Type::UNKNOWN\";\n return stream;\n }\n }\n}\n\n\ninline std::ostream& operator<<(std::ostream& stream, const WindowsFD& fd)\n{\n stream << fd.type() << \"=\";\n switch (fd.type()) {\n case WindowsFD::Type::HANDLE: {\n stream << static_cast<HANDLE>(fd);\n return stream;\n }\n case WindowsFD::Type::SOCKET: {\n stream << static_cast<SOCKET>(fd);\n return stream;\n }\n default: {\n stream << \"UNKNOWN\";\n return stream;\n }\n }\n}\n\n\n\/\/ NOTE: The following operators implement all the comparisons\n\/\/ possible a `WindowsFD` type and an `int`. The point of this is that\n\/\/ the `WindowsFD` type must act like an `int` for compatibility\n\/\/ reasons (e.g. checking validity through `fd < 0`), without actually\n\/\/ being castable to an `int` to avoid ambiguous types.\ninline bool operator<(int left, const WindowsFD& right)\n{\n return left < right.get_valid();\n}\n\n\ninline bool operator<(const WindowsFD& left, int right)\n{\n return left.get_valid() < right;\n}\n\n\ninline bool operator>(int left, const WindowsFD& right)\n{\n return left > right.get_valid();\n}\n\n\ninline bool operator>(const WindowsFD& left, int right)\n{\n return left.get_valid() > right;\n}\n\n\ninline bool operator<=(int left, const WindowsFD& right)\n{\n return left <= right.get_valid();\n}\n\n\ninline bool operator<=(const WindowsFD& left, int right)\n{\n return left.get_valid() <= right;\n}\n\n\ninline bool operator>=(int left, const WindowsFD& right)\n{\n return left >= right.get_valid();\n}\n\n\ninline bool operator>=(const WindowsFD& left, int right)\n{\n return left.get_valid() >= right;\n}\n\n\ninline bool operator==(int left, const WindowsFD& right)\n{\n return left == right.get_valid();\n}\n\n\ninline bool operator==(const WindowsFD& left, int right)\n{\n return left.get_valid() == right;\n}\n\n\ninline bool operator!=(int left, const WindowsFD& right)\n{\n return left != right.get_valid();\n}\n\n\ninline bool operator!=(const WindowsFD& left, int right)\n{\n return left.get_valid() != right;\n}\n\n\n\/\/ NOTE: This operator exists so that `WindowsFD` can be used in an\n\/\/ `unordered_map` (and other STL containers requiring equality).\ninline bool operator==(const WindowsFD& left, const WindowsFD& right)\n{\n \/\/ This is `true` even if the types mismatch because we want\n \/\/ `WindowsFD(-1)` to compare as equivalent to an invalid `HANDLE`\n \/\/ or `SOCKET`, even though it is technically of type `HANDLE`.\n if (!left.is_valid() && !right.is_valid()) {\n return true;\n }\n\n \/\/ Otherwise mismatched types are not equivalent.\n if (left.type() != right.type()) {\n return false;\n }\n\n switch (left.type()) {\n case WindowsFD::Type::HANDLE: {\n return static_cast<HANDLE>(left) == static_cast<HANDLE>(right);\n }\n case WindowsFD::Type::SOCKET: {\n return static_cast<SOCKET>(left) == static_cast<SOCKET>(right);\n }\n }\n\n UNREACHABLE();\n}\n\n} \/\/ namespace os {\n\nnamespace std {\n\n\/\/ NOTE: This specialization exists so that `WindowsFD` can be used in\n\/\/ an `unordered_map` (and other STL containers requiring a hash).\ntemplate <>\nstruct hash<os::WindowsFD>\n{\n using argument_type = os::WindowsFD;\n using result_type = size_t;\n\n result_type operator()(const argument_type& fd) const noexcept\n {\n switch (fd.type()) {\n case os::WindowsFD::Type::HANDLE: {\n return std::hash<HANDLE>{}(static_cast<HANDLE>(fd));\n }\n case os::WindowsFD::Type::SOCKET: {\n return std::hash<SOCKET>{}(static_cast<SOCKET>(fd));\n }\n }\n\n UNREACHABLE();\n }\n};\n\n} \/\/ namespace std {\n\n#endif \/\/ __STOUT_OS_WINDOWS_FD_HPP__\n<commit_msg>Windows: Made socket `int_fd` castable to `HANDLE` type.<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_OS_WINDOWS_FD_HPP__\n#define __STOUT_OS_WINDOWS_FD_HPP__\n\n#include <fcntl.h> \/\/ For `O_RDWR`.\n#include <io.h> \/\/ For `_open_osfhandle`.\n\n#include <array>\n#include <memory>\n#include <ostream>\n#include <type_traits>\n\n#include <stout\/check.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/try.hpp>\n#include <stout\/unreachable.hpp>\n#include <stout\/windows.hpp> \/\/ For `WinSock2.h`.\n\nnamespace os {\n\n\/\/ The `WindowsFD` class exists to provide an common interface with the POSIX\n\/\/ file descriptor. While the bare `int` representation of the POSIX file\n\/\/ descriptor API is undesirable, we rendezvous there in order to maintain the\n\/\/ existing code in Mesos.\n\/\/\n\/\/ In the platform-agnostic code paths, the `int_fd` type is aliased to\n\/\/ `WindowsFD`. The `os::*` functions return a type appropriate to the platform,\n\/\/ which allows us to write code like this:\n\/\/\n\/\/ Try<int_fd> fd = os::open(...);\n\/\/\n\/\/ The `WindowsFD` constructs off one of:\n\/\/ (1) `HANDLE` - from the Win32 API\n\/\/ (2) `SOCKET` - from the WinSock API\n\/\/\n\/\/ The `os::*` functions then take an instance of `WindowsFD`, examines\n\/\/ the state and dispatches to the appropriate API.\n\nclass WindowsFD\n{\npublic:\n enum class Type\n {\n HANDLE,\n SOCKET\n };\n\n \/\/ The `HANDLE` here is expected to be file handles. Specifically,\n \/\/ `HANDLE`s returned by file API such as `CreateFile`. There are\n \/\/ APIs that return `HANDLE`s with different error values, and\n \/\/ therefore must be handled accordingly. For example, a thread API\n \/\/ such as `CreateThread` returns `NULL` as the error value, rather\n \/\/ than `INVALID_HANDLE_VALUE`.\n \/\/\n \/\/ TODO(mpark): Consider adding a second parameter which tells us\n \/\/ what the error values are.\n static_assert(\n std::is_same<HANDLE, void*>::value,\n \"Expected `HANDLE` to be of type `void*`.\");\n explicit WindowsFD(HANDLE handle, bool overlapped = false)\n : type_(Type::HANDLE), handle_(handle), overlapped_(overlapped)\n {}\n\n \/\/ The `SOCKET` here is expected to be Windows sockets, such as that\n \/\/ used by the Windows Sockets 2 library. The only expected error\n \/\/ value is `INVALID_SOCKET`.\n \/\/\n \/\/ Note that sockets should almost always be overlapped. We do provide\n \/\/ a way in stout to create non-overlapped sockets, so for completeness, we\n \/\/ have an overlapped parameter in the constructor.\n static_assert(\n std::is_same<SOCKET, unsigned __int64>::value,\n \"Expected `SOCKET` to be of type `unsigned __int64`.\");\n explicit WindowsFD(SOCKET socket, bool overlapped = true)\n : type_(Type::SOCKET), socket_(socket), overlapped_(overlapped)\n {}\n\n \/\/ On Windows, libevent's `evutil_socket_t` is set to `intptr_t`.\n explicit WindowsFD(intptr_t socket) : WindowsFD(static_cast<SOCKET>(socket))\n {}\n\n \/\/ This constructor is provided in so that the canonical integer\n \/\/ file descriptors representing `stdin` (0), `stdout` (1), and\n \/\/ `stderr` (2), and the invalid value of -1 can be used.\n WindowsFD(int crt) : WindowsFD(INVALID_HANDLE_VALUE)\n {\n if (crt == -1) {\n \/\/ No-op, already `INVALID_HANDLE_VALUE`.\n } else if (crt == 0) {\n handle_ = ::GetStdHandle(STD_INPUT_HANDLE);\n } else if (crt == 1) {\n handle_ = ::GetStdHandle(STD_OUTPUT_HANDLE);\n } else if (crt == 2) {\n handle_ = ::GetStdHandle(STD_ERROR_HANDLE);\n } else {\n \/\/ This would be better enforced at compile-time, but not\n \/\/ currently possible, so this is a sanity check.\n LOG(FATAL) << \"Unexpected construction of `WindowsFD`\";\n }\n }\n\n \/\/ Default construct with invalid handle semantics.\n WindowsFD() : WindowsFD(INVALID_HANDLE_VALUE) {}\n\n WindowsFD(const WindowsFD&) = default;\n WindowsFD(WindowsFD&&) = default;\n\n WindowsFD& operator=(const WindowsFD&) = default;\n WindowsFD& operator=(WindowsFD&&) = default;\n\n ~WindowsFD() = default;\n\n bool is_valid() const\n {\n switch (type()) {\n case Type::HANDLE: {\n \/\/ Remember that both of these values can represent an invalid\n \/\/ handle.\n return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;\n }\n case Type::SOCKET: {\n \/\/ Only this value is used for an invalid socket.\n return socket_ != INVALID_SOCKET;\n }\n default: {\n return false;\n }\n }\n }\n\n \/\/ NOTE: This allocates a C run-time file descriptor and associates\n \/\/ it with the handle. At this point, the `HANDLE` should no longer\n \/\/ be closed via `CloseHandle`, but instead close the returned `int`\n \/\/ with `_close`. This method should almost never be used, and\n \/\/ exists only for compatibility with 3rdparty dependencies.\n int crt() const\n {\n CHECK_EQ(Type::HANDLE, type());\n \/\/ TODO(andschwa): Consider if we should overwrite `handle_`.\n return ::_open_osfhandle(reinterpret_cast<intptr_t>(handle_), O_RDWR);\n }\n\n operator HANDLE() const\n {\n \/\/ A `SOCKET` can be treated as a regular file `HANDLE` [1]. There are\n \/\/ many Win32 functions that work on a `SOCKET` but have the `HANDLE`\n \/\/ type as a function parameter like `CreateIoCompletionPort`, so we need\n \/\/ to be able to cast a `SOCKET` based `int_fd` to a `HANDLE`.\n \/\/\n \/\/ [1]: https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms740522(v=vs.85).aspx \/\/ NOLINT(whitespace\/line_length)\n if (type() == Type::SOCKET) {\n return reinterpret_cast<HANDLE>(socket_);\n }\n return handle_;\n }\n\n operator SOCKET() const\n {\n CHECK_EQ(Type::SOCKET, type());\n return socket_;\n }\n\n \/\/ On Windows, libevent's `evutil_socket_t` is set to `intptr_t`.\n operator intptr_t() const\n {\n CHECK_EQ(Type::SOCKET, type());\n return static_cast<intptr_t>(socket_);\n }\n\n Type type() const { return type_; }\n\n bool is_overlapped() const { return overlapped_; }\n\nprivate:\n Type type_;\n\n union\n {\n HANDLE handle_;\n SOCKET socket_;\n };\n\n bool overlapped_;\n\n \/\/ NOTE: This function is provided only for checking validity, thus\n \/\/ it is private. It provides a view of a `WindowsFD` as an `int`.\n \/\/\n \/\/ TODO(andschwa): Fix all uses of this conversion to use `is_valid`\n \/\/ directly instead, then remove the comparison operators. This\n \/\/ would require writing an `int_fd` class for POSIX too, instead of\n \/\/ just using `int`.\n int get_valid() const\n {\n if (is_valid()) {\n return 0;\n } else {\n return -1;\n }\n }\n\n \/\/ NOTE: These operators are used solely to support checking a\n \/\/ `WindowsFD` against e.g. -1 or 0 for validity. Nothing else\n \/\/ should have access to `get_valid()`.\n friend bool operator<(int left, const WindowsFD& right);\n friend bool operator<(const WindowsFD& left, int right);\n friend bool operator>(int left, const WindowsFD& right);\n friend bool operator>(const WindowsFD& left, int right);\n friend bool operator<=(int left, const WindowsFD& right);\n friend bool operator<=(const WindowsFD& left, int right);\n friend bool operator>=(int left, const WindowsFD& right);\n friend bool operator>=(const WindowsFD& left, int right);\n friend bool operator==(int left, const WindowsFD& right);\n friend bool operator==(const WindowsFD& left, int right);\n friend bool operator!=(int left, const WindowsFD& right);\n friend bool operator!=(const WindowsFD& left, int right);\n};\n\n\ninline std::ostream& operator<<(std::ostream& stream, const WindowsFD::Type& fd)\n{\n switch (fd) {\n case WindowsFD::Type::HANDLE: {\n stream << \"WindowsFD::Type::HANDLE\";\n return stream;\n }\n case WindowsFD::Type::SOCKET: {\n stream << \"WindowsFD::Type::SOCKET\";\n return stream;\n }\n default: {\n stream << \"WindowsFD::Type::UNKNOWN\";\n return stream;\n }\n }\n}\n\n\ninline std::ostream& operator<<(std::ostream& stream, const WindowsFD& fd)\n{\n stream << fd.type() << \"=\";\n switch (fd.type()) {\n case WindowsFD::Type::HANDLE: {\n stream << static_cast<HANDLE>(fd);\n return stream;\n }\n case WindowsFD::Type::SOCKET: {\n stream << static_cast<SOCKET>(fd);\n return stream;\n }\n default: {\n stream << \"UNKNOWN\";\n return stream;\n }\n }\n}\n\n\n\/\/ NOTE: The following operators implement all the comparisons\n\/\/ possible a `WindowsFD` type and an `int`. The point of this is that\n\/\/ the `WindowsFD` type must act like an `int` for compatibility\n\/\/ reasons (e.g. checking validity through `fd < 0`), without actually\n\/\/ being castable to an `int` to avoid ambiguous types.\ninline bool operator<(int left, const WindowsFD& right)\n{\n return left < right.get_valid();\n}\n\n\ninline bool operator<(const WindowsFD& left, int right)\n{\n return left.get_valid() < right;\n}\n\n\ninline bool operator>(int left, const WindowsFD& right)\n{\n return left > right.get_valid();\n}\n\n\ninline bool operator>(const WindowsFD& left, int right)\n{\n return left.get_valid() > right;\n}\n\n\ninline bool operator<=(int left, const WindowsFD& right)\n{\n return left <= right.get_valid();\n}\n\n\ninline bool operator<=(const WindowsFD& left, int right)\n{\n return left.get_valid() <= right;\n}\n\n\ninline bool operator>=(int left, const WindowsFD& right)\n{\n return left >= right.get_valid();\n}\n\n\ninline bool operator>=(const WindowsFD& left, int right)\n{\n return left.get_valid() >= right;\n}\n\n\ninline bool operator==(int left, const WindowsFD& right)\n{\n return left == right.get_valid();\n}\n\n\ninline bool operator==(const WindowsFD& left, int right)\n{\n return left.get_valid() == right;\n}\n\n\ninline bool operator!=(int left, const WindowsFD& right)\n{\n return left != right.get_valid();\n}\n\n\ninline bool operator!=(const WindowsFD& left, int right)\n{\n return left.get_valid() != right;\n}\n\n\n\/\/ NOTE: This operator exists so that `WindowsFD` can be used in an\n\/\/ `unordered_map` (and other STL containers requiring equality).\ninline bool operator==(const WindowsFD& left, const WindowsFD& right)\n{\n \/\/ This is `true` even if the types mismatch because we want\n \/\/ `WindowsFD(-1)` to compare as equivalent to an invalid `HANDLE`\n \/\/ or `SOCKET`, even though it is technically of type `HANDLE`.\n if (!left.is_valid() && !right.is_valid()) {\n return true;\n }\n\n \/\/ Otherwise mismatched types are not equivalent.\n if (left.type() != right.type()) {\n return false;\n }\n\n switch (left.type()) {\n case WindowsFD::Type::HANDLE: {\n return static_cast<HANDLE>(left) == static_cast<HANDLE>(right);\n }\n case WindowsFD::Type::SOCKET: {\n return static_cast<SOCKET>(left) == static_cast<SOCKET>(right);\n }\n }\n\n UNREACHABLE();\n}\n\n} \/\/ namespace os {\n\nnamespace std {\n\n\/\/ NOTE: This specialization exists so that `WindowsFD` can be used in\n\/\/ an `unordered_map` (and other STL containers requiring a hash).\ntemplate <>\nstruct hash<os::WindowsFD>\n{\n using argument_type = os::WindowsFD;\n using result_type = size_t;\n\n result_type operator()(const argument_type& fd) const noexcept\n {\n switch (fd.type()) {\n case os::WindowsFD::Type::HANDLE: {\n return std::hash<HANDLE>{}(static_cast<HANDLE>(fd));\n }\n case os::WindowsFD::Type::SOCKET: {\n return std::hash<SOCKET>{}(static_cast<SOCKET>(fd));\n }\n }\n\n UNREACHABLE();\n }\n};\n\n} \/\/ namespace std {\n\n#endif \/\/ __STOUT_OS_WINDOWS_FD_HPP__\n<|endoftext|>"} {"text":"<commit_before>#ifndef RADIUMENGINE_TASK_QUEUE_HPP_\n#define RADIUMENGINE_TASK_QUEUE_HPP_\n\n#include <Core\/CoreMacros.hpp>\n\n#include <memory>\n#include <vector>\n#include <deque>\n#include <thread>\n#include <mutex>\n\nnamespace Ra { namespace Core { class Task; } }\n\nnamespace Ra { namespace Core \n{\n\n class TaskQueue\n {\n public:\n typedef uint TaskId;\n enum { InvalidTaskId = TaskId(-1) };\n public:\n \/\/ Constructor and destructor.\n TaskQueue(int numThreads);\n ~TaskQueue();\n\n \/\/ Note : functions are not thread safe and should only be called from the main thread.\n\n \/\/\/ Registers a task to be executed.\n \/\/\/ Task must have been created with new and be initialized with its parameter.\n \/\/\/ The task queue assumes ownership of the task.\n TaskId registerTask(Task * task);\n\n \/\/\/ Add dependency between two tasks. A task will be executed only when all\n \/\/\/ its dependencies are satisfied.\n void addDependency(TaskId predecessor, TaskId successor);\n \n \/\/\/ Puts the task on the queue to be executed. A task can only be queued if it has\n \/\/\/ no dependencies.\n void queueTask(TaskId task);\n\n \/\/\/ Executes the task queue. Blocks until all tasks in queue and dependencies are finished.\n void processTaskQueue();\n\n \/\/\/ Erases all tasks. Will assert if tasks are unprocessed.\n void flushTaskQueue();\n\n private:\n \/\/\/ Function called by a new thread given a new task. \n void runTask(TaskId task);\n\n private:\n \/\/\/ Maximum number of concurently running tasks.\n const uint m_numThreads; \n \/\/\/ Storage for the tasks (task will be deleted\n std::vector< std::unique_ptr<Task> > m_tasks;\n \/\/\/ For each task, stores which tasks depend on it.\n std::vector< std::vector <TaskId> > m_dependencies;\n\n \/\/ mutex protected variables.\n\n \/\/\/ Global mutex over thread-sensitive variables.\n std::mutex m_taskQueueMutex;\n \/\/\/ Number of tasks each task is waiting on.\n std::vector<uint> m_remainingDependencies;\n \/\/\/ Queue holding the pending tasks.\n std::deque<TaskId> m_taskQueue;\n \/\/\/ Number of tasks currently being processed.\n uint m_processingTasks;\n\n };\n\n}}\n\n#endif \/\/ RADIUMENGINE_TASK_QUEUE_HPP_<commit_msg>Minor comment fix.<commit_after>#ifndef RADIUMENGINE_TASK_QUEUE_HPP_\n#define RADIUMENGINE_TASK_QUEUE_HPP_\n\n#include <Core\/CoreMacros.hpp>\n\n#include <memory>\n#include <vector>\n#include <deque>\n#include <thread>\n#include <mutex>\n\nnamespace Ra { namespace Core { class Task; } }\n\nnamespace Ra { namespace Core \n{\n\n class TaskQueue\n {\n public:\n typedef uint TaskId;\n enum { InvalidTaskId = TaskId(-1) };\n public:\n \/\/ Constructor and destructor.\n TaskQueue(int numThreads);\n ~TaskQueue();\n\n \/\/ Note : functions are not thread safe and should only be called from the main thread.\n\n \/\/\/ Registers a task to be executed.\n \/\/\/ Task must have been created with new and be initialized with its parameter.\n \/\/\/ The task queue assumes ownership of the task.\n TaskId registerTask(Task * task);\n\n \/\/\/ Add dependency between two tasks. A task will be executed only when all\n \/\/\/ its dependencies are satisfied.\n void addDependency(TaskId predecessor, TaskId successor);\n \n \/\/\/ Puts the task on the queue to be executed. A task can only be queued if it has\n \/\/\/ no dependencies.\n void queueTask(TaskId task);\n\n \/\/\/ Executes the task queue. Blocks until all tasks in queue and dependencies are finished.\n void processTaskQueue();\n\n \/\/\/ Erases all tasks. Will assert if tasks are unprocessed.\n void flushTaskQueue();\n\n private:\n \/\/\/ Function called by a new thread given a new task. \n void runTask(TaskId task);\n\n private:\n \/\/\/ Maximum number of concurently running tasks.\n const uint m_numThreads; \n \/\/\/ Storage for the tasks (task will be deleted by flushQueue)\n std::vector< std::unique_ptr<Task> > m_tasks;\n \/\/\/ For each task, stores which tasks depend on it.\n std::vector< std::vector <TaskId> > m_dependencies;\n\n \/\/ mutex protected variables.\n\n \/\/\/ Global mutex over thread-sensitive variables.\n std::mutex m_taskQueueMutex;\n \/\/\/ Number of tasks each task is waiting on.\n std::vector<uint> m_remainingDependencies;\n \/\/\/ Queue holding the pending tasks.\n std::deque<TaskId> m_taskQueue;\n \/\/\/ Number of tasks currently being processed.\n uint m_processingTasks;\n\n };\n\n}}\n\n#endif \/\/ RADIUMENGINE_TASK_QUEUE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/*\n * Brief description of this file:\n *\n * This file contains the code for the user defined qoi routine.\n *\/\n\n#include <queso\/GslVector.h>\n#include <queso\/GslMatrix.h>\n#include <gravity_qoi.h>\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nQoi<P_V, P_M, Q_V, Q_M>::Qoi(const char * prefix,\n const QUESO::VectorSet<P_V, P_M> & domainSet,\n const QUESO::VectorSet<Q_V, Q_M> & imageSet)\n : QUESO::BaseVectorFunction<P_V, P_M, Q_V, Q_M>(prefix, domainSet, imageSet),\n m_angle(M_PI \/ 4.0),\n m_initialVelocity(5.0),\n m_initialHeight(0.0)\n{\n}\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nQoi<P_V, P_M, Q_V, Q_M>::~Qoi()\n{\n \/\/ Deconstruct here\n}\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nvoid\nQoi<P_V, P_M, Q_V, Q_M>::compute(const P_V & domainVector,\n const P_V * domainDirection,\n Q_V & imageVector, QUESO::DistArray<P_V *> * gradVectors,\n QUESO::DistArray<P_M *> * hessianMatrices,\n QUESO::DistArray<P_V *> * hessianEffects) const\n{\n double g = domainVector[0]; \/\/ Sample of the RV 'gravity acceleration'\n double distanceTraveled = 0.0;\n double aux = m_initialVelocity * std::sin(m_angle);\n distanceTraveled = (m_initialVelocity * std::cos(m_angle) \/ g) *\n (aux + std::sqrt(std::pow(aux, 2) + 2.0 * g * m_initialHeight));\n\n imageVector[0] = distanceTraveled;\n}\n\ntemplate class Qoi<QUESO::GslVector, QUESO::GslMatrix, QUESO::GslVector,\n QUESO::GslMatrix>;\n<commit_msg>Add back in the error messages<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/*\n * Brief description of this file:\n *\n * This file contains the code for the user defined qoi routine.\n *\/\n\n#include <queso\/GslVector.h>\n#include <queso\/GslMatrix.h>\n#include <gravity_qoi.h>\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nQoi<P_V, P_M, Q_V, Q_M>::Qoi(const char * prefix,\n const QUESO::VectorSet<P_V, P_M> & domainSet,\n const QUESO::VectorSet<Q_V, Q_M> & imageSet)\n : QUESO::BaseVectorFunction<P_V, P_M, Q_V, Q_M>(prefix, domainSet, imageSet),\n m_angle(M_PI \/ 4.0),\n m_initialVelocity(5.0),\n m_initialHeight(0.0)\n{\n}\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nQoi<P_V, P_M, Q_V, Q_M>::~Qoi()\n{\n \/\/ Deconstruct here\n}\n\ntemplate<class P_V, class P_M, class Q_V, class Q_M>\nvoid\nQoi<P_V, P_M, Q_V, Q_M>::compute(const P_V & domainVector,\n const P_V * domainDirection,\n Q_V & imageVector, QUESO::DistArray<P_V *> * gradVectors,\n QUESO::DistArray<P_M *> * hessianMatrices,\n QUESO::DistArray<P_V *> * hessianEffects) const\n{\n if (domainVector.sizeLocal() != 1) {\n queso_error_msg(\"domainVector does not have size 1\");\n }\n if (imageVector.sizeLocal() != 1) {\n queso_error_msg(\"imageVector does not have size 1\");\n }\n\n double g = domainVector[0]; \/\/ Sample of the RV 'gravity acceleration'\n double distanceTraveled = 0.0;\n double aux = m_initialVelocity * std::sin(m_angle);\n distanceTraveled = (m_initialVelocity * std::cos(m_angle) \/ g) *\n (aux + std::sqrt(std::pow(aux, 2) + 2.0 * g * m_initialHeight));\n\n imageVector[0] = distanceTraveled;\n}\n\ntemplate class Qoi<QUESO::GslVector, QUESO::GslMatrix, QUESO::GslVector,\n QUESO::GslMatrix>;\n<|endoftext|>"} {"text":"<commit_before>\/**\n\\description The is the main for the new version of the mert algorithm develloppped during the 2nd MT marathon\n*\/\n\n#include <limits>\n#include \"Data.h\"\n#include \"Point.h\"\n#include \"Scorer.h\"\n#include \"ScoreData.h\"\n#include \"FeatureData.h\"\n#include \"Optimizer.h\"\n#include \"getopt.h\"\n#include \"Types.h\"\n#include <unistd.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include \"Util.h\"\n\n\nfloat min_interval = 1e-3;\n\nusing namespace std;\n\nvoid usage(void) {\n cerr<<\"usage: mert -d <dimensions> (mandatory )\"<<endl;\n cerr<<\"[-n retry ntimes (default 1)]\"<<endl;\n cerr<<\"[-o\\tthe indexes to optimize(default all)]\"<<endl;\n cerr<<\"[-t\\tthe optimizer(default Powell)]\"<<endl;\n cerr<<\"[--sctype] the scorer type (default BLEU)\"<<endl;\n cerr<<\"[--scfile] the scorer data file (default score.data)\"<<endl;\n cerr<<\"[--ffile] the feature data file data file (default feature.data)\"<<endl;\n cerr<<\"[-v] verbose level\"<<endl;\n exit(1);\n}\n\nstatic struct option long_options[] =\n {\n {\"pdim\", 1, 0, 'd'},\n {\"ntry\",1,0,'n'},\n {\"optimize\",1,0,'o'},\n {\"type\",1,0,'t'},\n {\"sctype\",1,0,'s'},\n {\"scfile\",1,0,'S'},\n {\"ffile\",1,0,'F'},\n {\"verbose\",1,0,'v'},\n {0, 0, 0, 0}\n };\nint option_index;\n\nint main (int argc, char **argv) {\n int c,pdim,i;\n pdim=-1;\n int ntry=1;\n string type(\"powell\");\n string scorertype(\"BLEU\");\n string scorerfile(\"statscore.data\");\n string featurefile(\"features.data\");\n vector<unsigned> tooptimize;\n vector<parameter_t> start;\n while ((c=getopt_long (argc, argv, \"d:n:t:s:S:F:v:\", long_options, &option_index)) != -1) {\n switch (c) {\n case 'd':\n pdim = strtol(optarg, NULL, 10);\n break;\n case 'n':\n ntry=strtol(optarg, NULL, 10);\n break;\n case 't':\n type=string(optarg);\n break;\n case's':\n\tscorertype=string(optarg);\n break;\n case 'S':\n scorerfile=string(optarg);\n case 'F':\n featurefile=string(optarg);\n break;\n case 'v':\n setverboselevel(strtol(optarg,NULL,10));\n break;\n default:\n usage();\n }\n }\n if (pdim < 0)\n usage();\n if(tooptimize.empty()){\n tooptimize.resize(pdim);\/\/We'll optimize on everything\n for(i=0;i<pdim;i++)\n tooptimize[i]=i;\n }\n ifstream opt(\"init.opt\");\n if(opt.fail()){\n cerr<<\"could not open init.opt\"<<endl;\n exit(3);\n }\n start.resize(pdim);\/\/to do:read from file\n int j;\n for( j=0;j<pdim&&!opt.fail();j++)\n opt>>start[j];\n if(j<pdim){\n cerr<<\"error could not initialize start point with init.opt\"<<endl;\n exit(3);\n }\n\n opt.close();\n \/\/it make sense to know what parameter set were used to generate the nbest\n ScorerFactory SF;\n Scorer *TheScorer=SF.getScorer(scorertype);\n ScoreData *SD=new ScoreData(*TheScorer);\n SD->load(scorerfile);\n FeatureData *FD=new FeatureData();\n FD->load(featurefile);\n Optimizer *O=OptimizerFactory::BuildOptimizer(pdim,tooptimize,start,type);\n O->SetScorer(TheScorer);\n O->SetFData(FD);\n Point P(start);\/\/Generate from the full feature set. Warning: must ne done after Optimiezr initialiazation\n Point bestP=P; \n statscore_t best=O->Run(P);\n statscore_t mean=best;\n statscore_t var=best*best;\n \n vector<parameter_t> min(Point::getdim());\n vector<parameter_t> max(Point::getdim());\n \n for(int d=0;d<Point::getdim();d++){\n min[d]=0.0;\n max[d]=1.0;\n }\n \/\/note: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result!\n \n for(int i=1;i<ntry;i++){\n P.Randomize(min,max);\n statscore_t score=O->Run(P);\n if(score>best){\n best=score;\n bestP=P;\n }\n mean+=score;\n var+=(score*score);\n }\n mean\/=(float)ntry;\n var\/=(float)ntry;\n var=sqrt(abs(var-mean*mean));\n if(ntry>1)\n cerr<<\"variance of the score (for \"<<ntry<<\" try):\"<<var<<endl;\n cerr<<\"best score\"<<best<<endl;\n ofstream res(\"weights.txt\");\n res<<bestP<<endl;\n}\n<commit_msg>Save correct weight set!<commit_after>\/**\n\\description The is the main for the new version of the mert algorithm develloppped during the 2nd MT marathon\n*\/\n\n#include <limits>\n#include \"Data.h\"\n#include \"Point.h\"\n#include \"Scorer.h\"\n#include \"ScoreData.h\"\n#include \"FeatureData.h\"\n#include \"Optimizer.h\"\n#include \"getopt.h\"\n#include \"Types.h\"\n#include <unistd.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include \"Util.h\"\n\n\nfloat min_interval = 1e-3;\n\nusing namespace std;\n\nvoid usage(void) {\n cerr<<\"usage: mert -d <dimensions> (mandatory )\"<<endl;\n cerr<<\"[-n retry ntimes (default 1)]\"<<endl;\n cerr<<\"[-o\\tthe indexes to optimize(default all)]\"<<endl;\n cerr<<\"[-t\\tthe optimizer(default Powell)]\"<<endl;\n cerr<<\"[--sctype] the scorer type (default BLEU)\"<<endl;\n cerr<<\"[--scfile] the scorer data file (default score.data)\"<<endl;\n cerr<<\"[--ffile] the feature data file data file (default feature.data)\"<<endl;\n cerr<<\"[-v] verbose level\"<<endl;\n exit(1);\n}\n\nstatic struct option long_options[] =\n {\n {\"pdim\", 1, 0, 'd'},\n {\"ntry\",1,0,'n'},\n {\"optimize\",1,0,'o'},\n {\"type\",1,0,'t'},\n {\"sctype\",1,0,'s'},\n {\"scfile\",1,0,'S'},\n {\"ffile\",1,0,'F'},\n {\"verbose\",1,0,'v'},\n {0, 0, 0, 0}\n };\nint option_index;\n\nint main (int argc, char **argv) {\n int c,pdim,i;\n pdim=-1;\n int ntry=1;\n string type(\"powell\");\n string scorertype(\"BLEU\");\n string scorerfile(\"statscore.data\");\n string featurefile(\"features.data\");\n vector<unsigned> tooptimize;\n vector<parameter_t> start;\n while ((c=getopt_long (argc, argv, \"d:n:t:s:S:F:v:\", long_options, &option_index)) != -1) {\n switch (c) {\n case 'd':\n pdim = strtol(optarg, NULL, 10);\n break;\n case 'n':\n ntry=strtol(optarg, NULL, 10);\n break;\n case 't':\n type=string(optarg);\n break;\n case's':\n\tscorertype=string(optarg);\n break;\n case 'S':\n scorerfile=string(optarg);\n case 'F':\n featurefile=string(optarg);\n break;\n case 'v':\n setverboselevel(strtol(optarg,NULL,10));\n break;\n default:\n usage();\n }\n }\n if (pdim < 0)\n usage();\n if(tooptimize.empty()){\n tooptimize.resize(pdim);\/\/We'll optimize on everything\n for(i=0;i<pdim;i++)\n tooptimize[i]=i;\n }\n ifstream opt(\"init.opt\");\n if(opt.fail()){\n cerr<<\"could not open init.opt\"<<endl;\n exit(3);\n }\n start.resize(pdim);\/\/to do:read from file\n int j;\n for( j=0;j<pdim&&!opt.fail();j++)\n opt>>start[j];\n if(j<pdim){\n cerr<<\"error could not initialize start point with init.opt\"<<endl;\n exit(3);\n }\n\n opt.close();\n \/\/it make sense to know what parameter set were used to generate the nbest\n ScorerFactory SF;\n Scorer *TheScorer=SF.getScorer(scorertype);\n ScoreData *SD=new ScoreData(*TheScorer);\n SD->load(scorerfile);\n FeatureData *FD=new FeatureData();\n FD->load(featurefile);\n Optimizer *O=OptimizerFactory::BuildOptimizer(pdim,tooptimize,start,type);\n O->SetScorer(TheScorer);\n O->SetFData(FD);\n Point P(start);\/\/Generate from the full feature set. Warning: must ne done after Optimiezr initialiazation\n statscore_t best=O->Run(P);\n Point bestP=P; \n statscore_t mean=best;\n statscore_t var=best*best;\n \n vector<parameter_t> min(Point::getdim());\n vector<parameter_t> max(Point::getdim());\n \n for(int d=0;d<Point::getdim();d++){\n min[d]=0.0;\n max[d]=1.0;\n }\n \/\/note: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result!\n \n for(int i=1;i<ntry;i++){\n P.Randomize(min,max);\n statscore_t score=O->Run(P);\n if(score>best){\n best=score;\n bestP=P;\n }\n mean+=score;\n var+=(score*score);\n }\n mean\/=(float)ntry;\n var\/=(float)ntry;\n var=sqrt(abs(var-mean*mean));\n if(ntry>1)\n cerr<<\"variance of the score (for \"<<ntry<<\" try):\"<<var<<endl;\n cerr<<\"best score\"<<best<<endl;\n ofstream res(\"weights.txt\");\n res<<bestP<<endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file snake.cpp\n * @brief Arquivo com as funcoes que implementam\n a resolucao do labirinto.\n * @author Daniel Barbosa (nome@email.com)\n * @author Jaine Budke (jainebudke@hotmail.com)\n * @since 30\/05\/2017\n * @date 19\/06\/2017\n *\/\n\n\n#include \"snake.h\"\n\n\n\n\/** @brief Tenta encontrar caminho para chegar na maçã.\n @return 1 se for possível, 0 se for impossível. *\/\nbool Snake::solveMaze(){\n\n\n \/\/ TODO\n \/\/ FAZER ESSA PARTE ACHANDO REALMENTE DIRECAO VALIDA PARA A SNAKE\n\n \/\/ recuperar a posicao inicial automaticamente tbm\n\n \/* \n Game::Position posInicial;\n posInicial.x = 3; \/\/ coluna\n posInicial.y = 5; \/\/ linha\n\n Game::Direction dir1;\n Game::Direction dir2;\n\n dir1.x = posInicial.x + 1;\n dir1.y = posInicial.y;\n\n dir2.x = posInicial.x + 2;\n dir2.y = dir1.y;\n\n listDirections.push_back( dir1 );\n listDirections.push_back( dir2 );\n *\/\n\n \n\n\n \/\/ VER JEITO DE RECUPERAR ISSO\n \/\/std::vector<Game::Position> tamanhos = gm.getSizeBoards();\n \/\/Game::Position tam = tamanhos[ gm.getCurrentLevel() ];\n\n\n\n int map[13][44]; \/\/ criando um mapa do labirinto\n for( int i=0 ; i < 13 ; i++ ){\n for( int j=0 ; j < 44 ; j++ ){\n map[i][j] = 0;\n }\n }\n\n for( int i=0 ; i < 13 ; i++ ){\n map[i][0] = 1;\n map[i][43] = 1;\n }\n\n for( int j=0 ; j < 44 ; j++ ){\n map[0][j] = 1;\n map[12][j] = 1;\n }\n\n Game::Position maca;\n maca.y = 6;\n maca.x = 38;\n\n\n int visited = 110;\n\n\n Game::Position posInicial;\n posInicial.x = 3; \/\/ coluna\n posInicial.y = 5; \/\/ linha\n\n std::stack< Game::Position > marked;\n\n Game::Position currentPosition;\n\n \/\/ Tornar initialPosition a celula atual e marcar como visitada\n currentPosition = posInicial;\n map[posInicial.y][posInicial.x] = 1;\n visited += 1;\n\n \/\/ buscar celulas ainda não visitadas\n while( visited <= 44*13 ){\n\n \/\/ verifica se os vizinhos estao livres ou tem maçã\n \/\/ Vizinhos:\n Game::Position north, south, east, west;\n north.x = currentPosition.x; \/\/ persiste coluna\n if( (currentPosition.y)+1 == 0 or (currentPosition.y)+1 == 1 ){\n north.y = (currentPosition.y)+1; \/\/ incrementa linha\n } else {\n north.x = 0;\n north.y = 0;\n }\n\n\n south.x = currentPosition.x; \/\/ persiste coluna\n if( (currentPosition.y)-1 == 0 or (currentPosition.y)-1 == 1 ){\n south.y = (currentPosition.y)-1; \/\/ decrementa linha\n } else {\n south.x = 0;\n south.y = 0;\n }\n \n\n if( (currentPosition.x)-1 == 0 or (currentPosition.x)-1 == 1 ){\n east.x = (currentPosition.x)-1; \/\/ decrementa coluna\n } else {\n east.x = 0;\n east.y = 0;\n }\n east.y = currentPosition.y; \/\/ persiste linha\n\n\n if( (currentPosition.x)+1 == 0 or (currentPosition.x)+1 == 1 ){\n west.x = (currentPosition.x)+1; \/\/ incrementa coluna\n } else {\n west.x = 0;\n west.y = 0;\n }\n west.y = currentPosition.y; \/\/ persiste linha\n\n\n if( map[north.y][north.x] == 0 \n or map[south.y][south.x] == 0\n or map[east.y][east.x] == 0\n or map[west.y][west.x] == 0 ){ \/\/ vizinhos não sao parede nem foram visitados\n \n \/\/ escolhe um dos vizinhos\n Game::Position vizinho;\n if( map[north.y][north.x] == 0 ){\n vizinho = north;\n visited += 1;\n map[north.y][north.x] = 1;\n std::cout << \"TESTE1\\n\";\n } else if( map[south.y][south.x] == 0 ){\n vizinho = south;\n visited += 1;\n map[south.y][south.x] = 1;\n std::cout << \"TESTE2\\n\";\n } else if( map[east.y][east.x] == 0 ){\n vizinho = east;\n visited += 1;\n map[east.y][east.x] = 1;\n std::cout << \"TESTE3\\n\";\n } else if( map[west.y][west.x] == 0 ){\n vizinho = west;\n visited += 1;\n map[west.y][west.x] = 1;\n std::cout << \"TESTE4\\n\";\n }\n\n std::cout << \"TESTE5\\n\";\n\n \/\/ dá o push da posicao atual pra pilha\n marked.push( currentPosition );\n\n \/\/ posicao atual agora é o vizinho escolhido\n currentPosition = vizinho;\n\n } else if( !(marked.empty()) ){ \/\/ se a pilha não estiver vazia\n\n \/\/ tira o ultimo elemento da pilha\n marked.pop();\n\n \/\/ vê e salva quem é o proximo\n Game::Position newPosition = marked.top();\n\n \/\/ torna nova célula a atual\n currentPosition = newPosition;\n std::cout << \"TESTE6\\n\";\n\n } else if( currentPosition.x == maca.x and currentPosition.y == maca.y ){\n \n while( !(marked.empty()) ){\n \/\/ ve quem é o prox \n Game::Position dir = marked.top();\n\n std::cout << dir.y << \" ; \" <<dir.x << \" - \";\n \/\/ add na lista\n listDirections.push_back( dir );\n \/\/ tira ele \n marked.pop();\n\n }\n std::cout << \"TESTE7\\n\";\n\n return true;\n }\n\n\n }\n\n return false;\n\n}<commit_msg>snaze<commit_after>\/**\n * @file snake.cpp\n * @brief Arquivo com as funcoes que implementam\n a resolucao do labirinto.\n * @author Daniel Barbosa (nome@email.com)\n * @author Jaine Budke (jainebudke@hotmail.com)\n * @since 30\/05\/2017\n * @date 19\/06\/2017\n *\/\n\n\n#include \"snake.h\"\n\n\n\n\/** @brief Tenta encontrar caminho para chegar na maçã.\n @return 1 se for possível, 0 se for impossível. *\/\nbool Snake::solveMaze(){\n\n\n \/\/ TODO\n \/\/ FAZER ESSA PARTE ACHANDO REALMENTE DIRECAO VALIDA PARA A SNAKE\n\n \/\/ recuperar a posicao inicial automaticamente tbm\n\n \/*\n Game::Position posInicial;\n posInicial.x = 3; \/\/ coluna\n posInicial.y = 5; \/\/ linha\n\n Game::Position dir1;\n Game::Position dir2;\n\n dir1.x = posInicial.x + 1;\n dir1.y = posInicial.y;\n\n dir2.x = posInicial.x + 2;\n dir2.y = dir1.y;\n\n listDirections.push_back( dir1 );\n listDirections.push_back( dir2 );\n *\/\n\n \n\n\n \/\/ VER JEITO DE RECUPERAR ISSO\n \/\/std::vector<Game::Position> tamanhos = gm.getSizeBoards();\n \/\/Game::Position tam = tamanhos[ gm.getCurrentLevel() ];\n\n int map[13][44]; \/\/ criando um mapa do labirinto\n for( int i=0 ; i < 13 ; i++ ){\n for( int j=0 ; j < 44 ; j++ ){\n map[i][j] = 0;\n }\n }\n\n for( int i=0 ; i < 13 ; i++ ){\n map[i][0] = 1;\n map[i][43] = 1;\n }\n\n for( int j=0 ; j < 44 ; j++ ){\n map[0][j] = 1;\n map[12][j] = 1;\n }\n\n Game::Position maca;\n maca.y = 6;\n maca.x = 38;\n\n\n int visited = 110;\n\n\n Game::Position posInicial;\n posInicial.x = 3; \/\/ coluna\n posInicial.y = 5; \/\/ linha\n\n std::stack< Game::Position > marked;\n\n Game::Position currentPosition;\n\n \/\/ Tornar initialPosition a celula atual e marcar como visitada\n currentPosition = posInicial;\n map[posInicial.y][posInicial.x] = 1;\n visited += 1;\n\n \/\/ buscar celulas ainda não visitadas\n while( visited <= 44*13 ){\n\n \/\/ verifica se os vizinhos estao livres ou tem maçã\n \/\/ Vizinhos:\n Game::Position north, south, east, west;\n north.x = currentPosition.x; \/\/ persiste coluna\n if( (currentPosition.y)+1 == 0 or (currentPosition.y)+1 == 1 ){\n north.y = (currentPosition.y)+1; \/\/ incrementa linha\n } else {\n north.x = 0;\n north.y = 0;\n }\n\n\n south.x = currentPosition.x; \/\/ persiste coluna\n if( (currentPosition.y)-1 == 0 or (currentPosition.y)-1 == 1 ){\n south.y = (currentPosition.y)-1; \/\/ decrementa linha\n } else {\n south.x = 0;\n south.y = 0;\n }\n \n\n if( (currentPosition.x)-1 == 0 or (currentPosition.x)-1 == 1 ){\n east.x = (currentPosition.x)-1; \/\/ decrementa coluna\n } else {\n east.x = 0;\n east.y = 0;\n }\n east.y = currentPosition.y; \/\/ persiste linha\n\n\n if( (currentPosition.x)+1 == 0 or (currentPosition.x)+1 == 1 ){\n west.x = (currentPosition.x)+1; \/\/ incrementa coluna\n } else {\n west.x = 0;\n west.y = 0;\n }\n west.y = currentPosition.y; \/\/ persiste linha\n\n\n if( map[north.y][north.x] == 0 \n or map[south.y][south.x] == 0\n or map[east.y][east.x] == 0\n or map[west.y][west.x] == 0 ){ \/\/ vizinhos não sao parede nem foram visitados\n \n \/\/ escolhe um dos vizinhos\n Game::Position vizinho;\n if( map[north.y][north.x] == 0 ){\n vizinho = north;\n visited += 1;\n map[north.y][north.x] = 1;\n std::cout << \"TESTE1\\n\";\n } else if( map[south.y][south.x] == 0 ){\n vizinho = south;\n visited += 1;\n map[south.y][south.x] = 1;\n std::cout << \"TESTE2\\n\";\n } else if( map[east.y][east.x] == 0 ){\n vizinho = east;\n visited += 1;\n map[east.y][east.x] = 1;\n std::cout << \"TESTE3\\n\";\n } else if( map[west.y][west.x] == 0 ){\n vizinho = west;\n visited += 1;\n map[west.y][west.x] = 1;\n std::cout << \"TESTE4\\n\";\n }\n\n std::cout << \"TESTE5\\n\";\n\n \/\/ dá o push da posicao atual pra pilha\n marked.push( currentPosition );\n\n \/\/ posicao atual agora é o vizinho escolhido\n currentPosition = vizinho;\n\n } else if( !(marked.empty()) ){ \/\/ se a pilha não estiver vazia\n\n \/\/ tira o ultimo elemento da pilha\n marked.pop();\n\n \/\/ vê e salva quem é o proximo\n Game::Position newPosition = marked.top();\n\n \/\/ torna nova célula a atual\n currentPosition = newPosition;\n std::cout << \"TESTE6\\n\";\n\n } else if( currentPosition.x == maca.x and currentPosition.y == maca.y ){\n \n while( !(marked.empty()) ){\n \/\/ ve quem é o prox \n Game::Position dir = marked.top();\n\n std::cout << dir.y << \" ; \" <<dir.x << \" - \";\n \/\/ add na lista\n listDirections.push_back( dir );\n \/\/ tira ele \n marked.pop();\n\n }\n std::cout << \"TESTE7\\n\";\n\n return true;\n }\n\n\n }\n\n return false;\n\n}<|endoftext|>"} {"text":"<commit_before>#include <osg\/Notify>\n#include <osg\/MatrixTransform>\n#include <osg\/PositionAttitudeTransform>\n#include <osg\/Geometry>\n#include <osg\/Geode>\n\n#include <osgUtil\/Optimizer>\n\n#include <osgDB\/Registry>\n#include <osgDB\/ReadFile>\n\n#include <osgGA\/TrackballManipulator>\n#include <osgGA\/FlightManipulator>\n#include <osgGA\/DriveManipulator>\n\n#include <osgSim\/OverlayNode>\n\n#include <osgViewer\/Viewer>\n#include <iostream>\n\nosg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)\n{\n \/\/ set up the animation path \n osg::AnimationPath* animationPath = new osg::AnimationPath;\n animationPath->setLoopMode(osg::AnimationPath::LOOP);\n \n int numSamples = 40;\n float yaw = 0.0f;\n float yaw_delta = 2.0f*osg::PI\/((float)numSamples-1.0f);\n float roll = osg::inDegrees(30.0f);\n \n double time=0.0f;\n double time_delta = looptime\/(double)numSamples;\n for(int i=0;i<numSamples;++i)\n {\n osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));\n osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));\n \n animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));\n\n yaw += yaw_delta;\n time += time_delta;\n\n }\n return animationPath; \n}\n\nosg::Node* createBase(const osg::Vec3& center,float radius)\n{\n\n \n\n int numTilesX = 10;\n int numTilesY = 10;\n \n float width = 2*radius;\n float height = 2*radius;\n \n osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));\n osg::Vec3 dx(osg::Vec3(width\/((float)numTilesX),0.0,0.0f));\n osg::Vec3 dy(osg::Vec3(0.0f,height\/((float)numTilesY),0.0f));\n \n \/\/ fill in vertices for grid, note numTilesX+1 * numTilesY+1...\n osg::Vec3Array* coords = new osg::Vec3Array;\n int iy;\n for(iy=0;iy<=numTilesY;++iy)\n {\n for(int ix=0;ix<=numTilesX;++ix)\n {\n coords->push_back(v000+dx*(float)ix+dy*(float)iy);\n }\n }\n \n \/\/Just two colours - black and white.\n osg::Vec4Array* colors = new osg::Vec4Array;\n colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); \/\/ white\n colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); \/\/ black\n int numColors=colors->size();\n \n \n int numIndicesPerRow=numTilesX+1;\n osg::UByteArray* coordIndices = new osg::UByteArray; \/\/ assumes we are using less than 256 points...\n osg::UByteArray* colorIndices = new osg::UByteArray;\n for(iy=0;iy<numTilesY;++iy)\n {\n for(int ix=0;ix<numTilesX;++ix)\n {\n \/\/ four vertices per quad.\n coordIndices->push_back(ix +(iy+1)*numIndicesPerRow);\n coordIndices->push_back(ix +iy*numIndicesPerRow);\n coordIndices->push_back((ix+1)+iy*numIndicesPerRow);\n coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);\n \n \/\/ one color per quad\n colorIndices->push_back((ix+iy)%numColors);\n }\n }\n \n\n \/\/ set up a single normal\n osg::Vec3Array* normals = new osg::Vec3Array;\n normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));\n \n\n osg::Geometry* geom = new osg::Geometry;\n geom->setVertexArray(coords);\n geom->setVertexIndices(coordIndices);\n \n geom->setColorArray(colors);\n geom->setColorIndices(colorIndices);\n geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);\n \n geom->setNormalArray(normals);\n geom->setNormalBinding(osg::Geometry::BIND_OVERALL);\n \n geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));\n \n osg::Geode* geode = new osg::Geode;\n geode->addDrawable(geom);\n \n return geode;\n}\n\nosg::Node* createMovingModel(const osg::Vec3& center, float radius)\n{\n float animationLength = 10.0f;\n\n osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);\n\n osg::Group* model = new osg::Group;\n\n osg::Node* glider = osgDB::readNodeFile(\"glider.osg\");\n if (glider)\n {\n const osg::BoundingSphere& bs = glider->getBound();\n\n float size = radius\/bs.radius()*0.3f;\n osg::MatrixTransform* positioned = new osg::MatrixTransform;\n positioned->setDataVariance(osg::Object::STATIC);\n positioned->setMatrix(osg::Matrix::translate(-bs.center())*\n osg::Matrix::scale(size,size,size)*\n osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));\n \n positioned->addChild(glider);\n \n osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform; \n xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));\n xform->addChild(positioned);\n\n model->addChild(xform);\n }\n \n osg::Node* cessna = osgDB::readNodeFile(\"cessna.osg\");\n if (cessna)\n {\n const osg::BoundingSphere& bs = cessna->getBound();\n\n float size = radius\/bs.radius()*0.3f;\n osg::MatrixTransform* positioned = new osg::MatrixTransform;\n positioned->setDataVariance(osg::Object::STATIC);\n positioned->setMatrix(osg::Matrix::translate(-bs.center())*\n osg::Matrix::scale(size,size,size)*\n osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));\n \n positioned->addChild(cessna);\n \n osg::MatrixTransform* xform = new osg::MatrixTransform;\n xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));\n xform->addChild(positioned);\n\n model->addChild(xform);\n }\n \n return model;\n}\n\nosg::Node* createModel(bool overlay, osgSim::OverlayNode::OverlayTechnique technique)\n{\n osg::Vec3 center(0.0f,0.0f,0.0f);\n float radius = 100.0f;\n\n osg::Group* root = new osg::Group;\n\n float baseHeight = center.z()-radius*0.6;\n osg::Node* baseModel = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius);\n osg::Node* movingModel = createMovingModel(center,radius*0.8f);\n\n if (overlay)\n {\n osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);\n overlayNode->setContinuousUpdate(true);\n overlayNode->setOverlaySubgraph(movingModel);\n overlayNode->setOverlayBaseHeight(baseHeight);\n overlayNode->addChild(baseModel);\n root->addChild(overlayNode);\n }\n else\n {\n \n root->addChild(baseModel);\n }\n \n root->addChild(movingModel);\n\n return root;\n}\n\n\nint main( int argc, char **argv )\n{\n \n bool overlay = false;\n osg::ArgumentParser arguments(&argc,argv);\n while (arguments.read(\"--overlay\")) overlay = true;\n \n osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;\n while (arguments.read(\"--object\")) { technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }\n while (arguments.read(\"--ortho\") || arguments.read(\"--orthographic\")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }\n while (arguments.read(\"--persp\") || arguments.read(\"--perspective\")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY; overlay=true; }\n \n\n \/\/ initialize the viewer.\n osgViewer::Viewer viewer;\n\n \/\/ load the nodes from the commandline arguments.\n osg::Node* model = createModel(overlay, technique);\n if (!model)\n {\n return 1;\n }\n \n \/\/ tilt the scene so the default eye position is looking down on the model.\n osg::MatrixTransform* rootnode = new osg::MatrixTransform;\n rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));\n rootnode->addChild(model);\n\n \/\/ run optimization over the scene graph\n osgUtil::Optimizer optimzer;\n optimzer.optimize(rootnode);\n \n \/\/ set the scene to render\n viewer.setSceneData(rootnode);\n\n viewer.setCameraManipulator(new osgGA::TrackballManipulator());\n\n#if 0\n\n \/\/ use of custom simulation time.\n \n viewer.realize();\n \n double simulationTime = 100.0;\n \n while (!viewer.done())\n {\n viewer.frame(simulationTime);\n simulationTime -= 0.01;\n }\n \n return 0;\n#else\n\n \/\/ normal viewer usage.\n\n viewer.setUpViewOnSingleScreen(1);\n\n return viewer.run();\n\n#endif\n}\n<commit_msg>Improved the accuracy of the overlaynode settings<commit_after>#include <osg\/Notify>\n#include <osg\/MatrixTransform>\n#include <osg\/PositionAttitudeTransform>\n#include <osg\/Geometry>\n#include <osg\/Geode>\n\n#include <osgUtil\/Optimizer>\n\n#include <osgDB\/Registry>\n#include <osgDB\/ReadFile>\n\n#include <osgGA\/TrackballManipulator>\n#include <osgGA\/FlightManipulator>\n#include <osgGA\/DriveManipulator>\n\n#include <osgSim\/OverlayNode>\n\n#include <osgViewer\/Viewer>\n#include <iostream>\n\nosg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)\n{\n \/\/ set up the animation path \n osg::AnimationPath* animationPath = new osg::AnimationPath;\n animationPath->setLoopMode(osg::AnimationPath::LOOP);\n \n int numSamples = 40;\n float yaw = 0.0f;\n float yaw_delta = 2.0f*osg::PI\/((float)numSamples-1.0f);\n float roll = osg::inDegrees(30.0f);\n \n double time=0.0f;\n double time_delta = looptime\/(double)numSamples;\n for(int i=0;i<numSamples;++i)\n {\n osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));\n osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));\n \n animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));\n\n yaw += yaw_delta;\n time += time_delta;\n\n }\n return animationPath; \n}\n\nosg::Node* createBase(const osg::Vec3& center,float radius)\n{\n\n \n\n int numTilesX = 10;\n int numTilesY = 10;\n \n float width = 2*radius;\n float height = 2*radius;\n \n osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));\n osg::Vec3 dx(osg::Vec3(width\/((float)numTilesX),0.0,0.0f));\n osg::Vec3 dy(osg::Vec3(0.0f,height\/((float)numTilesY),0.0f));\n \n \/\/ fill in vertices for grid, note numTilesX+1 * numTilesY+1...\n osg::Vec3Array* coords = new osg::Vec3Array;\n int iy;\n for(iy=0;iy<=numTilesY;++iy)\n {\n for(int ix=0;ix<=numTilesX;++ix)\n {\n coords->push_back(v000+dx*(float)ix+dy*(float)iy);\n }\n }\n \n \/\/Just two colours - black and white.\n osg::Vec4Array* colors = new osg::Vec4Array;\n colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); \/\/ white\n colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); \/\/ black\n int numColors=colors->size();\n \n \n int numIndicesPerRow=numTilesX+1;\n osg::UByteArray* coordIndices = new osg::UByteArray; \/\/ assumes we are using less than 256 points...\n osg::UByteArray* colorIndices = new osg::UByteArray;\n for(iy=0;iy<numTilesY;++iy)\n {\n for(int ix=0;ix<numTilesX;++ix)\n {\n \/\/ four vertices per quad.\n coordIndices->push_back(ix +(iy+1)*numIndicesPerRow);\n coordIndices->push_back(ix +iy*numIndicesPerRow);\n coordIndices->push_back((ix+1)+iy*numIndicesPerRow);\n coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);\n \n \/\/ one color per quad\n colorIndices->push_back((ix+iy)%numColors);\n }\n }\n \n\n \/\/ set up a single normal\n osg::Vec3Array* normals = new osg::Vec3Array;\n normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));\n \n\n osg::Geometry* geom = new osg::Geometry;\n geom->setVertexArray(coords);\n geom->setVertexIndices(coordIndices);\n \n geom->setColorArray(colors);\n geom->setColorIndices(colorIndices);\n geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);\n \n geom->setNormalArray(normals);\n geom->setNormalBinding(osg::Geometry::BIND_OVERALL);\n \n geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));\n \n osg::Geode* geode = new osg::Geode;\n geode->addDrawable(geom);\n \n return geode;\n}\n\nosg::Node* createMovingModel(const osg::Vec3& center, float radius)\n{\n float animationLength = 10.0f;\n\n osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);\n\n osg::Group* model = new osg::Group;\n\n osg::Node* glider = osgDB::readNodeFile(\"glider.osg\");\n if (glider)\n {\n const osg::BoundingSphere& bs = glider->getBound();\n\n float size = radius\/bs.radius()*0.3f;\n osg::MatrixTransform* positioned = new osg::MatrixTransform;\n positioned->setDataVariance(osg::Object::STATIC);\n positioned->setMatrix(osg::Matrix::translate(-bs.center())*\n osg::Matrix::scale(size,size,size)*\n osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));\n \n positioned->addChild(glider);\n \n osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform; \n xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));\n xform->addChild(positioned);\n\n model->addChild(xform);\n }\n \n osg::Node* cessna = osgDB::readNodeFile(\"cessna.osg\");\n if (cessna)\n {\n const osg::BoundingSphere& bs = cessna->getBound();\n\n float size = radius\/bs.radius()*0.3f;\n osg::MatrixTransform* positioned = new osg::MatrixTransform;\n positioned->setDataVariance(osg::Object::STATIC);\n positioned->setMatrix(osg::Matrix::translate(-bs.center())*\n osg::Matrix::scale(size,size,size)*\n osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));\n \n positioned->addChild(cessna);\n \n osg::MatrixTransform* xform = new osg::MatrixTransform;\n xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));\n xform->addChild(positioned);\n\n model->addChild(xform);\n }\n \n return model;\n}\n\nosg::Node* createModel(bool overlay, osgSim::OverlayNode::OverlayTechnique technique)\n{\n osg::Vec3 center(0.0f,0.0f,0.0f);\n float radius = 100.0f;\n\n osg::Group* root = new osg::Group;\n\n float baseHeight = center.z()-radius*0.5;\n osg::Node* baseModel = createBase(osg::Vec3(center.x(), center.y(), baseHeight),radius);\n osg::Node* movingModel = createMovingModel(center,radius*0.8f);\n\n if (overlay)\n {\n osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);\n overlayNode->setContinuousUpdate(true);\n overlayNode->setOverlaySubgraph(movingModel);\n overlayNode->setOverlayBaseHeight(baseHeight-0.01);\n overlayNode->addChild(baseModel);\n root->addChild(overlayNode);\n }\n else\n {\n \n root->addChild(baseModel);\n }\n \n root->addChild(movingModel);\n\n return root;\n}\n\n\nint main( int argc, char **argv )\n{\n \n bool overlay = false;\n osg::ArgumentParser arguments(&argc,argv);\n while (arguments.read(\"--overlay\")) overlay = true;\n \n osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;\n while (arguments.read(\"--object\")) { technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }\n while (arguments.read(\"--ortho\") || arguments.read(\"--orthographic\")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY; overlay=true; }\n while (arguments.read(\"--persp\") || arguments.read(\"--perspective\")) { technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY; overlay=true; }\n \n\n \/\/ initialize the viewer.\n osgViewer::Viewer viewer;\n\n \/\/ load the nodes from the commandline arguments.\n osg::Node* model = createModel(overlay, technique);\n if (!model)\n {\n return 1;\n }\n \n \/\/ tilt the scene so the default eye position is looking down on the model.\n osg::MatrixTransform* rootnode = new osg::MatrixTransform;\n rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));\n rootnode->addChild(model);\n\n \/\/ run optimization over the scene graph\n osgUtil::Optimizer optimzer;\n optimzer.optimize(rootnode);\n \n \/\/ set the scene to render\n viewer.setSceneData(rootnode);\n\n viewer.setCameraManipulator(new osgGA::TrackballManipulator());\n\n#if 1\n\n \/\/ use of custom simulation time.\n \n viewer.realize();\n \n double simulationTime = 0.0;\n \n while (!viewer.done())\n {\n viewer.frame(simulationTime);\n simulationTime += 0.001;\n }\n \n return 0;\n#else\n\n \/\/ normal viewer usage.\n\n viewer.setUpViewOnSingleScreen(1);\n\n return viewer.run();\n\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"helper.h\"\n#include \"solid.h\"\n#include \"vertex.h\"\n#include \"edge.h\"\n#include \"face.h\"\n#include \"buffermesh.h\"\n\n#include <TopoDS.hxx>\n#include <TopExp_Explorer.hxx>\n\n#include <BRepMesh_IncrementalMesh.hxx>\n#include <Poly_Array1OfTriangle.hxx>\n#include <TColgp_Array1OfPnt.hxx>\n\nNan::Persistent<v8::Function> moxcad::Solid::constructor;\n\nmoxcad::Solid::Solid()\n{\n}\n\nmoxcad::Solid::~Solid()\n{\n}\n\nvoid moxcad::Solid::Init(v8::Local<v8::Object> namespc)\n{\n DEFINE_FUNCTION_TEMPLATE(\"Solid\", tpl);\n\n Nan::SetPrototypeMethod(tpl, \"numFaces\", numFaces);\n Nan::SetPrototypeMethod(tpl, \"numEdges\", numEdges);\n Nan::SetPrototypeMethod(tpl, \"numVertices\", numVertices);\n Nan::SetPrototypeMethod(tpl, \"numShells\", numShells);\n\n Nan::SetPrototypeMethod(tpl, \"eachVertex\", eachVertex);\n Nan::SetPrototypeMethod(tpl, \"eachEdge\", eachEdge);\n Nan::SetPrototypeMethod(tpl, \"eachFace\", eachFace);\n\n Nan::SetPrototypeMethod(tpl, \"tessellate\", tessellate);\n\n constructor.Reset(tpl->GetFunction());\n namespc->Set(Nan::New(\"Solid\").ToLocalChecked(), tpl->GetFunction());\n}\n\nNAN_METHOD(moxcad::Solid::New)\n{\n ALLOW_ONLY_CONSTRUCTOR(info);\n Solid *obj = new Solid();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::numFaces)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numEdges)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_EDGE);\n unsigned int i=0;\n while(exp.More()) {\n TopoDS_Edge topoEdge = TopoDS::Edge(exp.Current());\n if(topoEdge.Orientation() == TopAbs_FORWARD) {\n i++;\n }\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numVertices)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_VERTEX);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numShells)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_SHELL);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n\n}\n\nNAN_METHOD(moxcad::Solid::eachVertex)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over vertices\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_VERTEX);\n while(exp.More()) {\n TopoDS_Vertex topoVtx = TopoDS::Vertex(exp.Current());\n\n \/\/ Package the vertex into Javascript object and invoke callback with it\n v8::Local<v8::Object> vtxInstance = moxcad::Vertex::NewInstance();\n moxcad::Vertex *vtx = ObjectWrap::Unwrap<moxcad::Vertex>(vtxInstance);\n vtx->setOCC(topoVtx);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { vtxInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::eachEdge)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over edges\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_EDGE);\n while(exp.More()) {\n TopoDS_Edge topoEdge = TopoDS::Edge(exp.Current());\n\n if(topoEdge.Orientation() == TopAbs_FORWARD) {\n \/\/ Package the edge into Javascript object and invoke callback with it\n v8::Local<v8::Object> edgeInstance = moxcad::Edge::NewInstance();\n moxcad::Edge *edge = ObjectWrap::Unwrap<moxcad::Edge>(edgeInstance);\n edge->setOCC(topoEdge);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { edgeInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n }\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::eachFace)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over faces\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n while(exp.More()) {\n TopoDS_Face topoFace = TopoDS::Face(exp.Current());\n\n \/\/ Package the face into Javascript object and invoke callback with it\n v8::Local<v8::Object> faceInstance = moxcad::Face::NewInstance();\n moxcad::Face *face = ObjectWrap::Unwrap<moxcad::Face>(faceInstance);\n face->setOCC(topoFace);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { faceInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::tessellate)\n{\n v8::Local<v8::Object> buffers = Nan::New<v8::Object>();\n\n v8::Local<v8::Array> faceBuffers = Nan::New<v8::Array>();\n\n \/\/v8::Local<v8::Object> bufferMeshHdl = moxcad::BufferMesh::NewInstance();\n \/\/moxcad::BufferMesh *bufferMesh =\n \/\/ ObjectWrap::Unwrap<moxcad::BufferMesh>(bufferMeshHdl);\n\n v8::Isolate* isolate = info.GetIsolate();\n\n GET_SELF(moxcad::Solid, self);\n\n const Standard_Real aLinearDeflection = 0.01;\n const Standard_Real anAngularDeflection = 0.5;\n\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n int i = 0;\n while(exp.More()) {\n TopoDS_Face topoFace = TopoDS::Face(exp.Current());\n BRepMesh_IncrementalMesh aMesh(topoFace, aLinearDeflection, Standard_False, anAngularDeflection);\n aMesh.Perform();\n TopLoc_Location l;\n const Handle(Poly_Triangulation)& pt = BRep_Tool::Triangulation(topoFace, l);\n const Poly_Array1OfTriangle& polyarr = pt->Triangles();\n\n \/\/ Indices\n v8::Local<v8::Uint32Array> idxArr =\n v8::Uint32Array::New(v8::ArrayBuffer::New(isolate, 4*polyarr.Size()),0,polyarr.Size());\n for(Standard_Integer i=polyarr.Lower(), idx=0; i<=polyarr.Upper(); i++, idx++) {\n const Poly_Triangle& ptri = polyarr.Value(i);\n idxArr->Set(Nan::GetCurrentContext(), 3*idx, Nan::New<v8::Uint32>(ptri.Value(1)));\n idxArr->Set(Nan::GetCurrentContext(), 3*idx+1, Nan::New<v8::Uint32>(ptri.Value(2)));\n idxArr->Set(Nan::GetCurrentContext(), 3*idx+2, Nan::New<v8::Uint32>(ptri.Value(3)));\n }\n\n \/\/ Vertices\n const TColgp_Array1OfPnt& nodes = pt->Nodes();\n int nReals = nodes.Size() * 3;\n v8::Local<v8::Float32Array> vtxArr =\n v8::Float32Array::New(v8::ArrayBuffer::New(isolate, 4*nReals),0,nReals);\n for(Standard_Integer i=nodes.Lower(), idx=0; i<=nodes.Upper(); i++, idx++) {\n const gp_Pnt& pnt = nodes.Value(i);\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx, Nan::New<v8::Number>(pnt.X()));\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx+1, Nan::New<v8::Number>(pnt.Y()));\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx+2, Nan::New<v8::Number>(pnt.Z()));\n }\n\n v8::Local<v8::Object> buffers = Nan::New<v8::Object>();\n buffers->Set(Nan::New(\"vtx\").ToLocalChecked(), vtxArr);\n buffers->Set(Nan::New(\"idx\").ToLocalChecked(), idxArr);\n\n faceBuffers->Set(i, buffers);\n\n \/\/bufferMesh->addFace(topoFace);\n exp.Next();\n\n i++;\n }\n\n buffers->Set(Nan::New(\"faceBuffers\").ToLocalChecked(), faceBuffers);\n\n \/\/info.GetReturnValue().Set(bufferMeshHdl);\n info.GetReturnValue().Set(buffers);\n}\n\nv8::Local<v8::Object> moxcad::Solid::NewInstance()\n{\n Nan::EscapableHandleScope scope;\n\n const unsigned argc = 1;\n v8::Local<v8::Value> argv[1] = {Nan::New(\"xxx\").ToLocalChecked()};\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n v8::Local<v8::Object> instance = cons->NewInstance(argc, argv);\n\n return scope.Escape(instance);\n}\n<commit_msg>Fixes to get the buffer data loading in Three.js<commit_after>\n#include \"helper.h\"\n#include \"solid.h\"\n#include \"vertex.h\"\n#include \"edge.h\"\n#include \"face.h\"\n#include \"buffermesh.h\"\n\n#include <TopoDS.hxx>\n#include <TopExp_Explorer.hxx>\n\n#include <BRepMesh_IncrementalMesh.hxx>\n#include <Poly_Array1OfTriangle.hxx>\n#include <TColgp_Array1OfPnt.hxx>\n\nNan::Persistent<v8::Function> moxcad::Solid::constructor;\n\nmoxcad::Solid::Solid()\n{\n}\n\nmoxcad::Solid::~Solid()\n{\n}\n\nvoid moxcad::Solid::Init(v8::Local<v8::Object> namespc)\n{\n DEFINE_FUNCTION_TEMPLATE(\"Solid\", tpl);\n\n Nan::SetPrototypeMethod(tpl, \"numFaces\", numFaces);\n Nan::SetPrototypeMethod(tpl, \"numEdges\", numEdges);\n Nan::SetPrototypeMethod(tpl, \"numVertices\", numVertices);\n Nan::SetPrototypeMethod(tpl, \"numShells\", numShells);\n\n Nan::SetPrototypeMethod(tpl, \"eachVertex\", eachVertex);\n Nan::SetPrototypeMethod(tpl, \"eachEdge\", eachEdge);\n Nan::SetPrototypeMethod(tpl, \"eachFace\", eachFace);\n\n Nan::SetPrototypeMethod(tpl, \"tessellate\", tessellate);\n\n constructor.Reset(tpl->GetFunction());\n namespc->Set(Nan::New(\"Solid\").ToLocalChecked(), tpl->GetFunction());\n}\n\nNAN_METHOD(moxcad::Solid::New)\n{\n ALLOW_ONLY_CONSTRUCTOR(info);\n Solid *obj = new Solid();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::numFaces)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numEdges)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_EDGE);\n unsigned int i=0;\n while(exp.More()) {\n TopoDS_Edge topoEdge = TopoDS::Edge(exp.Current());\n if(topoEdge.Orientation() == TopAbs_FORWARD) {\n i++;\n }\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numVertices)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_VERTEX);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n}\n\nNAN_METHOD(moxcad::Solid::numShells)\n{\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_SHELL);\n unsigned int i=0;\n while(exp.More()) {\n i++;\n exp.Next();\n }\n info.GetReturnValue().Set(Nan::New<v8::Uint32>(i));\n\n}\n\nNAN_METHOD(moxcad::Solid::eachVertex)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over vertices\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_VERTEX);\n while(exp.More()) {\n TopoDS_Vertex topoVtx = TopoDS::Vertex(exp.Current());\n\n \/\/ Package the vertex into Javascript object and invoke callback with it\n v8::Local<v8::Object> vtxInstance = moxcad::Vertex::NewInstance();\n moxcad::Vertex *vtx = ObjectWrap::Unwrap<moxcad::Vertex>(vtxInstance);\n vtx->setOCC(topoVtx);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { vtxInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::eachEdge)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over edges\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_EDGE);\n while(exp.More()) {\n TopoDS_Edge topoEdge = TopoDS::Edge(exp.Current());\n\n if(topoEdge.Orientation() == TopAbs_FORWARD) {\n \/\/ Package the edge into Javascript object and invoke callback with it\n v8::Local<v8::Object> edgeInstance = moxcad::Edge::NewInstance();\n moxcad::Edge *edge = ObjectWrap::Unwrap<moxcad::Edge>(edgeInstance);\n edge->setOCC(topoEdge);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { edgeInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n }\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::eachFace)\n{\n \/\/ Extract callback function\n v8::Local<v8::Function> cb = info[0].As<v8::Function>();\n\n \/\/ Iterate over faces\n GET_SELF(moxcad::Solid, self);\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n while(exp.More()) {\n TopoDS_Face topoFace = TopoDS::Face(exp.Current());\n\n \/\/ Package the face into Javascript object and invoke callback with it\n v8::Local<v8::Object> faceInstance = moxcad::Face::NewInstance();\n moxcad::Face *face = ObjectWrap::Unwrap<moxcad::Face>(faceInstance);\n face->setOCC(topoFace);\n\n \/\/ Invoke callback\n const unsigned int argc = 1;\n v8::Local<v8::Value> argv[] = { faceInstance };\n Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);\n\n exp.Next();\n }\n info.GetReturnValue().Set(info.This());\n}\n\nNAN_METHOD(moxcad::Solid::tessellate)\n{\n v8::Local<v8::Object> buffers = Nan::New<v8::Object>();\n\n v8::Local<v8::Array> faceBuffers = Nan::New<v8::Array>();\n\n \/\/v8::Local<v8::Object> bufferMeshHdl = moxcad::BufferMesh::NewInstance();\n \/\/moxcad::BufferMesh *bufferMesh =\n \/\/ ObjectWrap::Unwrap<moxcad::BufferMesh>(bufferMeshHdl);\n\n v8::Isolate* isolate = info.GetIsolate();\n\n GET_SELF(moxcad::Solid, self);\n\n const Standard_Real aLinearDeflection = 0.01;\n const Standard_Real anAngularDeflection = 0.5;\n\n TopExp_Explorer exp(self->m_solid, TopAbs_FACE);\n int i = 0;\n while(exp.More()) {\n TopoDS_Face topoFace = TopoDS::Face(exp.Current());\n BRepMesh_IncrementalMesh aMesh(topoFace, aLinearDeflection, Standard_False, anAngularDeflection);\n aMesh.Perform();\n TopLoc_Location l;\n const Handle(Poly_Triangulation)& pt = BRep_Tool::Triangulation(topoFace, l);\n const Poly_Array1OfTriangle& polyarr = pt->Triangles();\n\n \/\/ Indices\n v8::Local<v8::Array> idxArr = Nan::New<v8::Array>();\n for(Standard_Integer i=polyarr.Lower(), idx=0; i<=polyarr.Upper(); i++, idx++) {\n const Poly_Triangle& ptri = polyarr.Value(i);\n idxArr->Set(Nan::GetCurrentContext(), 3*idx, Nan::New<v8::Uint32>(ptri.Value(1)-1));\n idxArr->Set(Nan::GetCurrentContext(), 3*idx+1, Nan::New<v8::Uint32>(ptri.Value(2)-1));\n idxArr->Set(Nan::GetCurrentContext(), 3*idx+2, Nan::New<v8::Uint32>(ptri.Value(3)-1));\n }\n\n \/\/ Vertices\n const TColgp_Array1OfPnt& nodes = pt->Nodes();\n int nReals = nodes.Size() * 3;\n v8::Local<v8::Array> vtxArr = Nan::New<v8::Array>();\n for(Standard_Integer i=nodes.Lower(), idx=0; i<=nodes.Upper(); i++, idx++) {\n const gp_Pnt& pnt = nodes.Value(i);\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx, Nan::New<v8::Number>(pnt.X()));\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx+1, Nan::New<v8::Number>(pnt.Y()));\n vtxArr->Set(Nan::GetCurrentContext(), 3*idx+2, Nan::New<v8::Number>(pnt.Z()));\n }\n\n v8::Local<v8::Object> buffers = Nan::New<v8::Object>();\n buffers->Set(Nan::New(\"vtx\").ToLocalChecked(), vtxArr);\n buffers->Set(Nan::New(\"idx\").ToLocalChecked(), idxArr);\n\n faceBuffers->Set(i, buffers);\n\n \/\/bufferMesh->addFace(topoFace);\n exp.Next();\n\n i++;\n }\n\n buffers->Set(Nan::New(\"faceBuffers\").ToLocalChecked(), faceBuffers);\n\n \/\/info.GetReturnValue().Set(bufferMeshHdl);\n info.GetReturnValue().Set(buffers);\n}\n\nv8::Local<v8::Object> moxcad::Solid::NewInstance()\n{\n Nan::EscapableHandleScope scope;\n\n const unsigned argc = 1;\n v8::Local<v8::Value> argv[1] = {Nan::New(\"xxx\").ToLocalChecked()};\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n v8::Local<v8::Object> instance = cons->NewInstance(argc, argv);\n\n return scope.Escape(instance);\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <stdint.h>\n#include <memory>\n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size) noexcept\n : backref(backref)\n , size(size)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n {\n *backref = this;\n memcpy(data, o.data, size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n void* p = current_allocator().alloc(standard_migrator<blob_storage>,\n sizeof(blob_storage) + size, alignof(blob_storage));\n new (p) blob_storage(&_u.ptr, size);\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n memcpy(data(), v.data(), v.size());\n }\n\n ~managed_bytes() {\n if (external()) {\n current_allocator().destroy(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(static_cast<bytes_view>(o)) {}\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n \/\/ FIXME: not exception safe\n this->~managed_bytes();\n new (this) managed_bytes(o);\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n return static_cast<bytes_view>(*this) == static_cast<bytes_view>(o);\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return size() == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return const_cast<managed_bytes*>(this)->data();\n }\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash<managed_bytes> {\n size_t operator()(managed_bytes v) const {\n return hash<bytes_view>()(v);\n }\n};\n\n}\n<commit_msg>managed_bytes: simplify empty()<commit_after>#pragma once\n\n#include <stdint.h>\n#include <memory>\n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size) noexcept\n : backref(backref)\n , size(size)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n {\n *backref = this;\n memcpy(data, o.data, size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n void* p = current_allocator().alloc(standard_migrator<blob_storage>,\n sizeof(blob_storage) + size, alignof(blob_storage));\n new (p) blob_storage(&_u.ptr, size);\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n memcpy(data(), v.data(), v.size());\n }\n\n ~managed_bytes() {\n if (external()) {\n current_allocator().destroy(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(static_cast<bytes_view>(o)) {}\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n \/\/ FIXME: not exception safe\n this->~managed_bytes();\n new (this) managed_bytes(o);\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n return static_cast<bytes_view>(*this) == static_cast<bytes_view>(o);\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return const_cast<managed_bytes*>(this)->data();\n }\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash<managed_bytes> {\n size_t operator()(managed_bytes v) const {\n return hash<bytes_view>()(v);\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"state.h\"\n\n#include <iostream>\n#include <fstream> \/\/for ifstream, ofstream\n#include <thread>\n#include <string>\n\n#include \"catch.hpp\"\n#include \"compileflags.h\"\n#include \"filesystem.h\"\n#include \"gparse\/com.h\"\n\n\/\/MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='\"path\"')\n#include MACHINE_PATH\n\n\n\/\/This test must be contained in a class so as to have access to special functions in the State (if it ever needs that)\nstruct TestClass {\n TestClass() {\n GIVEN(\"A State with Driver, Filesystem & Com interfaces\") {\n \/\/setup code:\n std::ofstream inputFile;\n \/\/disable buffering before opening\n inputFile.rdbuf()->pubsetbuf(0, 0);\n inputFile.open(\"PRINTIPI_TEST_INPUT\", std::fstream::out | std::fstream::trunc);\n std::ifstream outputFile;\n outputFile.rdbuf()->pubsetbuf(0, 0);\n \/\/must open with the ::out flag to automatically create the file if it doesn't exist\n outputFile.open(\"PRINTIPI_TEST_OUTPUT\", std::fstream::in | std::fstream::out | std::fstream::trunc);\n\n machines::MACHINE driver;\n FileSystem fs(\"\/tmp\/\");\n gparse::Com com = gparse::Com(\"PRINTIPI_TEST_INPUT\", \"PRINTIPI_TEST_OUTPUT\");\n State<machines::MACHINE> state(driver, fs, com, true);\n\n std::thread eventThread([&](){ \n state.eventLoop(); \n });\n\n \/\/convenience function to read and wait for the next line from Printipi's output\n auto readLine = [&]() {\n std::string tempRead;\n do {\n if (outputFile.eof()) {\n outputFile.clear();\n }\n } while (!std::getline(outputFile, tempRead));\n return tempRead;\n };\n\n \/\/@cmd g-code command to send to printer (a newline character will be appended)\n \/\/@expect expected response\n auto sendCommand = [&](const std::string &cmd, const std::string &expect) {\n INFO(\"Sending command: '\" + cmd + \"'\");\n inputFile << cmd << '\\n';\n INFO(\"It should be acknowledged with '\" + expect + \"'\");\n REQUIRE(readLine() == expect);\n };\n\n \/\/Verify that the position as reported by the motion planner is near (@x, @y, @z)\n auto verifyPosition = [&](float x, float y, float z) {\n \tVector4f actualPos = state.motionPlanner().actualCartesianPosition();\n INFO(\"Actual position: \" + std::string(actualPos));\n REQUIRE(actualPos.xyz().distance(x, y, z) <= 4);\n };\n\n bool hasExited = false;\n auto exitOnce = [&]() {\n if (!hasExited) {\n sendCommand(\"M0\", \"ok\");\n eventThread.join();\n hasExited = true;\n }\n };\n\n \/\/each WHEN\/THEN case corresponds to a single test;\n \/\/the above setup code and the teardown code further below are re-run for EVERY 'when' case.\n \/\/This is also repeated recursively.\n\n \/\/test homing\n WHEN(\"The machine is homed\") {\n sendCommand(\"G28\", \"ok\");\n }\n \/\/test G1 movement\n WHEN(\"The machine is homed & moved to (40, -10, 50)\") {\n sendCommand(\"G28\", \"ok\");\n sendCommand(\"G1 X40 Y-10 Z50\", \"ok\");\n \/\/test G1 movement\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G1 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n \t\/\/test successive G1 movements\n \tWHEN(\"The machine is moved to another absolute position afterward, (-30, 20, 80) at F=3000\") {\n \t\tsendCommand(\"G1 X-30 Y20 Z80 F3000\", \"ok\");\n \t\tTHEN(\"The actual position should be near (-30, 20, 80)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(-30, 20, 80);\n \t\t}\n \t}\n \t\/\/test G91 (relative) movement\n \tWHEN(\"The machine is moved a RELATIVE amount (-70, 30, 30) at F=3000\") {\n \t\t\/\/put into relative movement mode\n \t\tsendCommand(\"G91\", \"ok\");\n \t\tsendCommand(\"G1 X-70 Y30 Z30 F3000\", \"ok\");\n \t\tTHEN(\"The actual position should be near (-30, 20, 80)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(-30, 20, 80);\n \t\t}\n \t}\n \t\/\/test comment parsing\n \tWHEN(\"A movement command to (30, 10, 30) is coupled with a comment\") {\n \t\tsendCommand(\"G1 X30 Y10 Z30; HELLO, I am a comment!\", \"ok\");\n \t\tTHEN(\"The actual position should be near (30, 10, 30)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(30, 10, 30);\n \t\t}\n \t}\n }\n \/\/test automatic homing\n WHEN(\"The machine is moved to (40, -10, 50) before being homed\") {\n \tsendCommand(\"G1 X40 Y-10 Z50\", \"ok\");\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G1 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n }\n \/\/test automatic homing using G0\n WHEN(\"The machine is moved to (40, -10, 50) before being homed, using G0 command\") {\n \tsendCommand(\"G0 X40 Y-10 Z50\", \"ok\");\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G0 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n }\n \/\/test using inch coordinates\n WHEN(\"The machine is moved to (-1, 2, 1) in inches\") {\n \t\/\/home machine\n \tsendCommand(\"G28\", \"ok\");\n \t\/\/put into inches mode\n \tsendCommand(\"G20\", \"ok\");\n \t\/\/move absolute\n \tsendCommand(\"G1 X-1 Y2 Z1\", \"ok\");\n \tTHEN(\"The actual position (in mm) should be near (-1, 2, 1)*25.4\") {\n \t\texitOnce(); \/\/force the G1 code to complete\n \t\tverifyPosition(-1*25.4, 2*25.4, 1*25.4);\n \t}\n }\n \/\/test M18; let steppers move freely\n WHEN(\"The M18 command is sent to let the steppers move freely\") {\n \tsendCommand(\"M18\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n \/\/test gcode printing from file\n WHEN(\"Commands are read from a file with M32\") {\n \t\/\/home\n \tsendCommand(\"G28\", \"ok\");\n \t\/\/\"initialize\" the SD card\n \tsendCommand(\"M21\", \"ok\");\n \tstd::ofstream gfile(\"\/tmp\/test-printipi-m32.gcode\", std::fstream::out | std::fstream::trunc);\n \t\/\/test newlines \/ whitespace\n \tgfile << \"\\n\";\n \tgfile << \" \\t \\n\";\n \t\/\/test comment & G90\n \tgfile << \"G90 \\t ; comment \\n\";\n \tgfile << \"G1 X40 Y-10 Z50\";\n \tAND_WHEN(\"The file is terminated with a newline\") {\n\t \t\/\/test ending the file WITHOUT a newline\n\t \tgfile << \"\\n\" << std::flush;\n\t \t\/\/load & run the file\n\t \tsendCommand(\"M32 \/test-printipi-m32.gcode\", \"ok\");\n\t \tTHEN(\"The actual position should be near (40, -10, 50)\") {\n\t \t\t\/\/note: Printipi is able to monitor multiple file inputs simultaneously,\n\t \t\t\/\/ if we send it M0 immediately, it may not have read the G1 from the file, and so it will exit\n\t \t\t\/\/ there is no way to query the status of this file read, so we must just sleep & hopr\n\t \t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\t exitOnce(); \/\/force the G0 code to complete\n\t\t verifyPosition(40, -10, 50);\n\t \t}\n\t }\n\t AND_WHEN(\"The file does NOT end on an empty line\") {\n\t \t\/\/test ending the file WITHOUT a newline\n\t \tgfile << std::flush;\n\t \t\/\/load & run the file\n\t \tsendCommand(\"M32 \/test-printipi-m32.gcode\", \"ok\");\n\t \tTHEN(\"The actual position should be near (40, -10, 50)\") {\n\t \t\t\/\/note: Printipi is able to monitor multiple file inputs simultaneously,\n\t \t\t\/\/ if we send it M0 immediately, it may not have read the G1 from the file, and so it will exit\n\t \t\t\/\/ there is no way to query the status of this file read, so we must just sleep & hopr\n\t \t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\t exitOnce(); \/\/force the G0 code to complete\n\t\t verifyPosition(40, -10, 50);\n\t \t}\n\t }\n }\n \/\/test M84; stop idle hold (same as M18)\n WHEN(\"The M84 command is sent to stop the idle hold\") {\n \tsendCommand(\"M84\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n WHEN(\"The M106 command is sent to activate fans\") {\n \tsendCommand(\"M106\", \"ok\");\n \tWHEN(\"The M107 command is sent to disactivate fans\") {\n \t\tsendCommand(\"M107\", \"ok\");\n \t\t\/\/\"then the machine shouldn't crash\"\n \t}\n }\n WHEN(\"The M106 command is sent to activate fans at a specific PWM between 0.0-1.0\") {\n \tsendCommand(\"M106 S0.7\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n WHEN(\"The M106 command is sent to activate fans at a specific PWM between 0-255\") {\n \tsendCommand(\"M106 S64\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\", and S64 should be interpreted as 64\/255 duty cycle.\n }\n WHEN(\"The M117 command is sent\") {\n \tsendCommand(\"M117 Hello, World!\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n \/\/Teardown code:\n exitOnce();\n }\n }\n};\n\n\nSCENARIO(\"State will respond correctly to gcode commands\", \"[state]\") {\n TestClass();\n}<commit_msg>Don't write to \/tmp folder; that requires root permissions<commit_after>#include \"state.h\"\n\n#include <iostream>\n#include <fstream> \/\/for ifstream, ofstream\n#include <thread>\n#include <string>\n\n#include \"catch.hpp\"\n#include \"compileflags.h\"\n#include \"filesystem.h\"\n#include \"gparse\/com.h\"\n\n\/\/MACHINE_PATH is calculated in the Makefile and then passed as a define through the make system (ie gcc -DMACHINEPATH='\"path\"')\n#include MACHINE_PATH\n\n\n\/\/This test must be contained in a class so as to have access to special functions in the State (if it ever needs that)\nstruct TestClass {\n TestClass() {\n GIVEN(\"A State with Driver, Filesystem & Com interfaces\") {\n \/\/setup code:\n std::ofstream inputFile;\n \/\/disable buffering before opening\n inputFile.rdbuf()->pubsetbuf(0, 0);\n inputFile.open(\"PRINTIPI_TEST_INPUT\", std::fstream::out | std::fstream::trunc);\n std::ifstream outputFile;\n outputFile.rdbuf()->pubsetbuf(0, 0);\n \/\/must open with the ::out flag to automatically create the file if it doesn't exist\n outputFile.open(\"PRINTIPI_TEST_OUTPUT\", std::fstream::in | std::fstream::out | std::fstream::trunc);\n\n machines::MACHINE driver;\n FileSystem fs(\".\/\");\n gparse::Com com = gparse::Com(\"PRINTIPI_TEST_INPUT\", \"PRINTIPI_TEST_OUTPUT\");\n State<machines::MACHINE> state(driver, fs, com, true);\n\n std::thread eventThread([&](){ \n state.eventLoop(); \n });\n\n \/\/convenience function to read and wait for the next line from Printipi's output\n auto readLine = [&]() {\n std::string tempRead;\n do {\n if (outputFile.eof()) {\n outputFile.clear();\n }\n } while (!std::getline(outputFile, tempRead));\n return tempRead;\n };\n\n \/\/@cmd g-code command to send to printer (a newline character will be appended)\n \/\/@expect expected response\n auto sendCommand = [&](const std::string &cmd, const std::string &expect) {\n INFO(\"Sending command: '\" + cmd + \"'\");\n inputFile << cmd << '\\n';\n INFO(\"It should be acknowledged with '\" + expect + \"'\");\n REQUIRE(readLine() == expect);\n };\n\n \/\/Verify that the position as reported by the motion planner is near (@x, @y, @z)\n auto verifyPosition = [&](float x, float y, float z) {\n \tVector4f actualPos = state.motionPlanner().actualCartesianPosition();\n INFO(\"Actual position: \" + std::string(actualPos));\n REQUIRE(actualPos.xyz().distance(x, y, z) <= 4);\n };\n\n bool hasExited = false;\n auto exitOnce = [&]() {\n if (!hasExited) {\n sendCommand(\"M0\", \"ok\");\n eventThread.join();\n hasExited = true;\n }\n };\n\n \/\/each WHEN\/THEN case corresponds to a single test;\n \/\/the above setup code and the teardown code further below are re-run for EVERY 'when' case.\n \/\/This is also repeated recursively.\n\n \/\/test homing\n WHEN(\"The machine is homed\") {\n sendCommand(\"G28\", \"ok\");\n }\n \/\/test G1 movement\n WHEN(\"The machine is homed & moved to (40, -10, 50)\") {\n sendCommand(\"G28\", \"ok\");\n sendCommand(\"G1 X40 Y-10 Z50\", \"ok\");\n \/\/test G1 movement\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G1 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n \t\/\/test successive G1 movements\n \tWHEN(\"The machine is moved to another absolute position afterward, (-30, 20, 80) at F=3000\") {\n \t\tsendCommand(\"G1 X-30 Y20 Z80 F3000\", \"ok\");\n \t\tTHEN(\"The actual position should be near (-30, 20, 80)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(-30, 20, 80);\n \t\t}\n \t}\n \t\/\/test G91 (relative) movement\n \tWHEN(\"The machine is moved a RELATIVE amount (-70, 30, 30) at F=3000\") {\n \t\t\/\/put into relative movement mode\n \t\tsendCommand(\"G91\", \"ok\");\n \t\tsendCommand(\"G1 X-70 Y30 Z30 F3000\", \"ok\");\n \t\tTHEN(\"The actual position should be near (-30, 20, 80)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(-30, 20, 80);\n \t\t}\n \t}\n \t\/\/test comment parsing\n \tWHEN(\"A movement command to (30, 10, 30) is coupled with a comment\") {\n \t\tsendCommand(\"G1 X30 Y10 Z30; HELLO, I am a comment!\", \"ok\");\n \t\tTHEN(\"The actual position should be near (30, 10, 30)\") {\n\t \t\texitOnce(); \/\/force the G1 code to complete\n\t \t\tverifyPosition(30, 10, 30);\n \t\t}\n \t}\n }\n \/\/test automatic homing\n WHEN(\"The machine is moved to (40, -10, 50) before being homed\") {\n \tsendCommand(\"G1 X40 Y-10 Z50\", \"ok\");\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G1 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n }\n \/\/test automatic homing using G0\n WHEN(\"The machine is moved to (40, -10, 50) before being homed, using G0 command\") {\n \tsendCommand(\"G0 X40 Y-10 Z50\", \"ok\");\n THEN(\"The actual position should be near (40, -10, 50)\") {\n\t exitOnce(); \/\/force the G0 code to complete\n\t verifyPosition(40, -10, 50);\n \t}\n }\n \/\/test using inch coordinates\n WHEN(\"The machine is moved to (-1, 2, 1) in inches\") {\n \t\/\/home machine\n \tsendCommand(\"G28\", \"ok\");\n \t\/\/put into inches mode\n \tsendCommand(\"G20\", \"ok\");\n \t\/\/move absolute\n \tsendCommand(\"G1 X-1 Y2 Z1\", \"ok\");\n \tTHEN(\"The actual position (in mm) should be near (-1, 2, 1)*25.4\") {\n \t\texitOnce(); \/\/force the G1 code to complete\n \t\tverifyPosition(-1*25.4, 2*25.4, 1*25.4);\n \t}\n }\n \/\/test M18; let steppers move freely\n WHEN(\"The M18 command is sent to let the steppers move freely\") {\n \tsendCommand(\"M18\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n \/\/test gcode printing from file\n WHEN(\"Commands are read from a file with M32\") {\n \t\/\/home\n \tsendCommand(\"G28\", \"ok\");\n \t\/\/\"initialize\" the SD card\n \tsendCommand(\"M21\", \"ok\");\n \tstd::ofstream gfile(\"test-printipi-m32.gcode\", std::fstream::out | std::fstream::trunc);\n \t\/\/test newlines \/ whitespace\n \tgfile << \"\\n\";\n \tgfile << \" \\t \\n\";\n \t\/\/test comment & G90\n \tgfile << \"G90 \\t ; comment \\n\";\n \tgfile << \"G1 X40 Y-10 Z50\";\n \tAND_WHEN(\"The file is terminated with a newline\") {\n\t \t\/\/test ending the file WITHOUT a newline\n\t \tgfile << \"\\n\" << std::flush;\n\t \t\/\/load & run the file\n\t \tsendCommand(\"M32 \/test-printipi-m32.gcode\", \"ok\");\n\t \tTHEN(\"The actual position should be near (40, -10, 50)\") {\n\t \t\t\/\/note: Printipi is able to monitor multiple file inputs simultaneously,\n\t \t\t\/\/ if we send it M0 immediately, it may not have read the G1 from the file, and so it will exit\n\t \t\t\/\/ there is no way to query the status of this file read, so we must just sleep & hopr\n\t \t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\t exitOnce(); \/\/force the G0 code to complete\n\t\t verifyPosition(40, -10, 50);\n\t \t}\n\t }\n\t AND_WHEN(\"The file does NOT end on an empty line\") {\n\t \t\/\/test ending the file WITHOUT a newline\n\t \tgfile << std::flush;\n\t \t\/\/load & run the file\n\t \tsendCommand(\"M32 \/test-printipi-m32.gcode\", \"ok\");\n\t \tTHEN(\"The actual position should be near (40, -10, 50)\") {\n\t \t\t\/\/note: Printipi is able to monitor multiple file inputs simultaneously,\n\t \t\t\/\/ if we send it M0 immediately, it may not have read the G1 from the file, and so it will exit\n\t \t\t\/\/ there is no way to query the status of this file read, so we must just sleep & hopr\n\t \t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\t exitOnce(); \/\/force the G0 code to complete\n\t\t verifyPosition(40, -10, 50);\n\t \t}\n\t }\n }\n \/\/test M84; stop idle hold (same as M18)\n WHEN(\"The M84 command is sent to stop the idle hold\") {\n \tsendCommand(\"M84\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n WHEN(\"The M106 command is sent to activate fans\") {\n \tsendCommand(\"M106\", \"ok\");\n \tWHEN(\"The M107 command is sent to disactivate fans\") {\n \t\tsendCommand(\"M107\", \"ok\");\n \t\t\/\/\"then the machine shouldn't crash\"\n \t}\n }\n WHEN(\"The M106 command is sent to activate fans at a specific PWM between 0.0-1.0\") {\n \tsendCommand(\"M106 S0.7\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n WHEN(\"The M106 command is sent to activate fans at a specific PWM between 0-255\") {\n \tsendCommand(\"M106 S64\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\", and S64 should be interpreted as 64\/255 duty cycle.\n }\n WHEN(\"The M117 command is sent\") {\n \tsendCommand(\"M117 Hello, World!\", \"ok\");\n \t\/\/\"then the machine shouldn't crash\"\n }\n \/\/Teardown code:\n exitOnce();\n }\n }\n};\n\n\nSCENARIO(\"State will respond correctly to gcode commands\", \"[state]\") {\n TestClass();\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"WrapHelper.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/MathHelper.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"..\/player\/PythonLogSink.h\"\n#include \"..\/player\/PublisherDefinitionRegistry.h\"\n\n#include <boost\/version.hpp>\n\nusing namespace avg;\nusing namespace std;\nusing namespace boost::python;\n\nnamespace Vec2Helper\n{\n int len(const glm::vec2&) \n {\n return 2;\n }\n\n float getX(const glm::vec2& pt)\n {\n return pt.x;\n }\n\n float getY(const glm::vec2& pt)\n {\n return pt.y;\n }\n\n void setX(glm::vec2& pt, float val)\n {\n pt.x = val;\n }\n\n void setY(glm::vec2& pt, float val)\n {\n pt.y = val;\n }\n\n void checkItemRange(int i) {\n if (i != 0 && i != 1) {\n throw std::out_of_range(\"Index out of range for Point2D. Must be 0 or 1.\");\n }\n }\n\n float getItem(const glm::vec2& pt, int i)\n {\n checkItemRange(i);\n if (i==0) {\n return pt.x;\n } else {\n return pt.y;\n }\n }\n\n void setItem(glm::vec2& pt, int i, float val)\n {\n checkItemRange(i);\n if (i==0) {\n pt.x = val;\n } else {\n pt.y = val;\n }\n }\n\n string str(const glm::vec2& pt)\n {\n stringstream st;\n st << \"(\" << pt.x << \",\" << pt.y << \")\";\n return st.str();\n }\n\n string repr(const glm::vec2& pt)\n {\n stringstream st;\n st << \"avg.Point2D(\" << pt.x << \",\" << pt.y << \")\";\n return st.str();\n }\n\n long getHash(const glm::vec2& pt)\n {\n \/\/ Wild guess at what could constitute a good hash function.\n \/\/ Will generate very bad hashes if most values are in a range < 0.1,\n \/\/ but this is meant for pixel values anyway, right? ;-).\n return long(pt.x*42+pt.y*23);\n }\n \n glm::vec2 safeGetNormalized(const glm::vec2& pt)\n {\n if (pt.x==0 && pt.y==0) {\n throw Exception(AVG_ERR_OUT_OF_RANGE, \"Can't normalize (0,0).\");\n } else {\n float invNorm = 1\/sqrt(pt.x*pt.x+pt.y*pt.y);\n return glm::vec2(pt.x*invNorm, pt.y*invNorm);\n }\n }\n\n float getNorm(const glm::vec2& pt)\n {\n return glm::length(pt);\n }\n \n float vecAngle(const glm::vec2& pt1, const glm::vec2& pt2)\n {\n float angle = fmod((atan2(pt1.y, pt1.x) - atan2(pt2.y, pt2.x)), float(2*M_PI));\n if (angle < 0) {\n angle += 2*M_PI;\n }\n return angle;\n }\n}\n\n\/\/ The ConstVec2 stuff is there so that vec2 attributes behave sensibly. That is,\n\/\/ node.pos.x = 30 causes an error instead of failing silently.\nConstVec2::ConstVec2()\n{\n}\n\nConstVec2::ConstVec2(const glm::vec2& other)\n{\n x = other.x;\n y = other.y;\n}\n\nglm::vec2 ConstVec2::toVec2() const\n{\n return glm::vec2(x,y);\n}\n\nvoid checkEmptyArgs(const boost::python::tuple &args, int numArgs)\n{\n if (boost::python::len(args) != numArgs) {\n throw avg::Exception(AVG_ERR_INVALID_ARGS, \n \"Nodes must be constructed using named parameters. Positional parameters are not supported.\");\n }\n}\n\ntemplate<class VEC2>\nstruct Vec2_to_python_tuple\n{\n static PyObject* convert (VEC2 v)\n {\n return boost::python::incref(boost::python::make_tuple(v.x, v.y).ptr());\n }\n};\n\ntemplate<class VEC3>\nstruct Vec3_to_python_tuple\n{\n static PyObject* convert (VEC3 v)\n {\n return boost::python::incref(boost::python::make_tuple(v.x, v.y, v.z).ptr());\n }\n};\n\ntemplate<class VEC2, class ATTR>\nstruct vec2_from_python\n{\n vec2_from_python() \n {\n boost::python::converter::registry::push_back(\n &convertible, &construct, boost::python::type_id<VEC2>());\n }\n \n static void* convertible(PyObject* obj_ptr)\n {\n \/\/ Using PySequence_Check here causes infinite recursion.\n if (!PyTuple_Check(obj_ptr) && !PyList_Check(obj_ptr)) {\n return 0;\n }\n if (PySequence_Size(obj_ptr) != 2) {\n return 0;\n }\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n VEC2 pt;\n PyObject * pEntry = PySequence_GetItem(obj_ptr, 0);\n pt.x = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 1);\n pt.y = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<VEC2>*)data)\n ->storage.bytes;\n new (storage) VEC2(pt);\n data->convertible = storage;\n }\n};\n\ntemplate<class VEC3, class ATTR>\nstruct vec3_from_python\n{\n vec3_from_python() \n {\n boost::python::converter::registry::push_back(\n &convertible, &construct, boost::python::type_id<VEC3>());\n }\n \n static void* convertible(PyObject* obj_ptr)\n {\n if (!PySequence_Check(obj_ptr)) {\n return 0;\n }\n if (PySequence_Size(obj_ptr) != 3) {\n return 0;\n }\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n VEC3 t;\n PyObject * pEntry = PySequence_GetItem(obj_ptr, 0);\n t.x = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 1);\n t.y = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 2);\n t.z = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<VEC3>*)\n data)->storage.bytes;\n new (storage) VEC3(t);\n data->convertible = storage;\n }\n};\n\nstruct UTF8String_to_unicode\n{\n static PyObject *convert(const UTF8String & s)\n {\n const char * pStr = s.c_str();\n return PyUnicode_DecodeUTF8(pStr, strlen(pStr), \"ignore\");\n }\n};\n\nstruct UTF8String_from_unicode\n{\n UTF8String_from_unicode()\n {\n boost::python::converter::registry::push_back(\n &convertible,\n &construct,\n boost::python::type_id<UTF8String>());\n }\n\n static void* convertible(PyObject* obj_ptr)\n {\n if (!PyUnicode_Check(obj_ptr)) return 0;\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n PyObject * pPyUTF8 = PyUnicode_AsUTF8String(obj_ptr);\n char * psz = PyString_AsString(pPyUTF8);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<UTF8String>*)data)\n ->storage.bytes;\n new (storage) UTF8String(psz);\n data->convertible = storage;\n Py_DECREF(pPyUTF8);\n }\n};\n\nstruct UTF8String_from_string\n{\n UTF8String_from_string()\n {\n boost::python::converter::registry::push_back(\n &convertible,\n &construct,\n boost::python::type_id<UTF8String>());\n }\n\n static void* convertible(PyObject* obj_ptr)\n {\n if (!PyString_Check(obj_ptr)) return 0;\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n const char * psz = PyString_AsString(obj_ptr);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<UTF8String>*)data)\n ->storage.bytes;\n new (storage) UTF8String(psz);\n data->convertible = storage;\n }\n};\n\nvoid exportMessages(object& nodeClass, const string& sClassName)\n{\n PublisherDefinitionPtr pPubDef = PublisherDefinitionRegistry::get()\n ->getDefinition(sClassName);\n const vector<MessageID>& messageIDs = pPubDef->getMessageIDs();\n for (unsigned i=0; i<messageIDs.size(); ++i) {\n string sName = messageIDs[i].m_sName;\n nodeClass.attr(sName.c_str()) = messageIDs[i];\n }\n};\n\nstruct type_info_to_string{\n static PyObject* convert(const std::type_info& info)\n {\n boost::python::object result(ObjectCounter::get()->demangle(info.name()));\n return boost::python::incref(result.ptr());\n }\n};\n\n\nvoid export_base()\n{\n \/\/ Exceptions\n\n translateException<exception>(PyExc_RuntimeError);\n translateException<Exception>(PyExc_RuntimeError);\n to_python_converter< exception, Exception_to_python_exception<exception> >();\n to_python_converter< Exception, Exception_to_python_exception<Exception> >();\n \n \/\/ vec2\n to_python_converter<IntPoint, Vec2_to_python_tuple<IntPoint> >();\n vec2_from_python<IntPoint, int>();\n vec2_from_python<glm::vec2, float>();\n vec2_from_python<ConstVec2, float>();\n \n \/\/ vector<vec2>\n to_python_converter<vector<glm::vec2>, to_list<vector<glm::vec2> > >(); \n from_python_sequence<vector<IntPoint>, variable_capacity_policy>();\n from_python_sequence<vector<glm::vec2>, variable_capacity_policy>();\n\n \/\/ vec3\n to_python_converter<glm::ivec3, Vec3_to_python_tuple<glm::ivec3> >();\n to_python_converter<glm::vec3, Vec3_to_python_tuple<glm::vec3> >();\n vec3_from_python<glm::ivec3, int>();\n vec3_from_python<glm::vec3, float>();\n \n \/\/ vector<vec3>\n to_python_converter<vector<glm::ivec3>, to_list<vector<glm::ivec3> > >(); \n to_python_converter<vector<glm::vec3>, to_list<vector<glm::vec3> > >(); \n from_python_sequence<vector<glm::ivec3>, variable_capacity_policy>();\n from_python_sequence<vector<glm::vec3>, variable_capacity_policy>();\n\n \/\/ string\n to_python_converter<UTF8String, UTF8String_to_unicode>();\n UTF8String_from_unicode();\n UTF8String_from_string();\n\n to_python_converter<vector<string>, to_list<vector<string> > >(); \n from_python_sequence<vector<string>, variable_capacity_policy>();\n \n from_python_sequence<vector<float>, variable_capacity_policy>();\n from_python_sequence<vector<int>, variable_capacity_policy>();\n\n to_python_converter<std::type_info, type_info_to_string>();\n \/\/Maps\n to_python_converter<TypeMap, to_dict<TypeMap> >();\n}\n\nnamespace {\n std::map<PyObject *, LogSinkPtr> m_pyObjectMap;\n}\n\nvoid addPythonLogger(PyObject * self, PyObject * pyLogger)\n{\n Logger * logger = Logger::get();\n LogSinkPtr logSink(new PythonLogSink(pyLogger));\n logger->addLogSink(logSink);\n m_pyObjectMap[pyLogger] = logSink;\n}\n\nvoid removePythonLogger(PyObject * self, PyObject * pyLogger)\n{\n Logger* logger = Logger::get();\n std::map<PyObject *, LogSinkPtr>::iterator it;\n it = m_pyObjectMap.find(pyLogger);\n if( it !=m_pyObjectMap.end() ){\n logger->removeLogSink(it->second);\n m_pyObjectMap.erase(it);\n }\n}\n\nvoid pytrace(PyObject * self, size_t category, const UTF8String& sMsg, unsigned severity)\n{\n avgDeprecationWarning(string(\"1.8\"), \"logger.trace\",\n \"any of the logging convenience functions\");\n Logger::get()->trace(sMsg, category, severity);\n}\n\n<commit_msg>Fixed #397<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"WrapHelper.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/MathHelper.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"..\/player\/PythonLogSink.h\"\n#include \"..\/player\/PublisherDefinitionRegistry.h\"\n\n#include <boost\/version.hpp>\n\nusing namespace avg;\nusing namespace std;\nusing namespace boost::python;\n\nnamespace Vec2Helper\n{\n int len(const glm::vec2&) \n {\n return 2;\n }\n\n float getX(const glm::vec2& pt)\n {\n return pt.x;\n }\n\n float getY(const glm::vec2& pt)\n {\n return pt.y;\n }\n\n void setX(glm::vec2& pt, float val)\n {\n pt.x = val;\n }\n\n void setY(glm::vec2& pt, float val)\n {\n pt.y = val;\n }\n\n void checkItemRange(int i) {\n if (i != 0 && i != 1) {\n throw std::out_of_range(\"Index out of range for Point2D. Must be 0 or 1.\");\n }\n }\n\n float getItem(const glm::vec2& pt, int i)\n {\n checkItemRange(i);\n if (i==0) {\n return pt.x;\n } else {\n return pt.y;\n }\n }\n\n void setItem(glm::vec2& pt, int i, float val)\n {\n checkItemRange(i);\n if (i==0) {\n pt.x = val;\n } else {\n pt.y = val;\n }\n }\n\n string str(const glm::vec2& pt)\n {\n stringstream st;\n st << \"(\" << pt.x << \",\" << pt.y << \")\";\n return st.str();\n }\n\n string repr(const glm::vec2& pt)\n {\n stringstream st;\n st << \"avg.Point2D(\" << pt.x << \",\" << pt.y << \")\";\n return st.str();\n }\n\n long getHash(const glm::vec2& pt)\n {\n \/\/ Wild guess at what could constitute a good hash function.\n \/\/ Will generate very bad hashes if most values are in a range < 0.1,\n \/\/ but this is meant for pixel values anyway, right? ;-).\n return long(pt.x*42+pt.y*23);\n }\n \n glm::vec2 safeGetNormalized(const glm::vec2& pt)\n {\n if (pt.x==0 && pt.y==0) {\n throw Exception(AVG_ERR_OUT_OF_RANGE, \"Can't normalize (0,0).\");\n } else {\n float invNorm = 1\/sqrt(pt.x*pt.x+pt.y*pt.y);\n return glm::vec2(pt.x*invNorm, pt.y*invNorm);\n }\n }\n\n float getNorm(const glm::vec2& pt)\n {\n return glm::length(pt);\n }\n \n float vecAngle(const glm::vec2& pt1, const glm::vec2& pt2)\n {\n float angle = fmod((atan2(pt1.y, pt1.x) - atan2(pt2.y, pt2.x)), float(2*M_PI));\n if (angle < 0) {\n angle += 2*M_PI;\n }\n return angle;\n }\n}\n\n\/\/ The ConstVec2 stuff is there so that vec2 attributes behave sensibly. That is,\n\/\/ node.pos.x = 30 causes an error instead of failing silently.\nConstVec2::ConstVec2()\n{\n}\n\nConstVec2::ConstVec2(const glm::vec2& other)\n{\n x = other.x;\n y = other.y;\n}\n\nglm::vec2 ConstVec2::toVec2() const\n{\n return glm::vec2(x,y);\n}\n\nvoid checkEmptyArgs(const boost::python::tuple &args, int numArgs)\n{\n if (boost::python::len(args) != numArgs) {\n throw avg::Exception(AVG_ERR_INVALID_ARGS, \n \"Nodes must be constructed using named parameters. Positional parameters are not supported.\");\n }\n}\n\ntemplate<class VEC2>\nstruct Vec2_to_python_tuple\n{\n static PyObject* convert (VEC2 v)\n {\n return boost::python::incref(boost::python::make_tuple(v.x, v.y).ptr());\n }\n};\n\ntemplate<class VEC3>\nstruct Vec3_to_python_tuple\n{\n static PyObject* convert (VEC3 v)\n {\n return boost::python::incref(boost::python::make_tuple(v.x, v.y, v.z).ptr());\n }\n};\n\ntemplate<class VEC2, class ATTR>\nstruct vec2_from_python\n{\n vec2_from_python() \n {\n boost::python::converter::registry::push_back(\n &convertible, &construct, boost::python::type_id<VEC2>());\n }\n \n static void* convertible(PyObject* obj_ptr)\n {\n \/\/ Using PySequence_Check here causes infinite recursion.\n if (!PyTuple_Check(obj_ptr) && !PyList_Check(obj_ptr)) {\n return 0;\n }\n if (PySequence_Size(obj_ptr) != 2) {\n return 0;\n }\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n VEC2 pt;\n PyObject * pEntry = PySequence_GetItem(obj_ptr, 0);\n pt.x = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 1);\n pt.y = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<VEC2>*)data)\n ->storage.bytes;\n new (storage) VEC2(pt);\n data->convertible = storage;\n }\n};\n\ntemplate<class VEC3, class ATTR>\nstruct vec3_from_python\n{\n vec3_from_python() \n {\n boost::python::converter::registry::push_back(\n &convertible, &construct, boost::python::type_id<VEC3>());\n }\n \n static void* convertible(PyObject* obj_ptr)\n {\n if (!PySequence_Check(obj_ptr)) {\n return 0;\n }\n if (PySequence_Size(obj_ptr) != 3) {\n return 0;\n }\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n VEC3 t;\n PyObject * pEntry = PySequence_GetItem(obj_ptr, 0);\n t.x = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 1);\n t.y = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n pEntry = PySequence_GetItem(obj_ptr, 2);\n t.z = (ATTR)PyFloat_AsDouble(pEntry);\n Py_DECREF(pEntry);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<VEC3>*)\n data)->storage.bytes;\n new (storage) VEC3(t);\n data->convertible = storage;\n }\n};\n\nstruct UTF8String_to_unicode\n{\n static PyObject *convert(const UTF8String & s)\n {\n const char * pStr = s.c_str();\n return PyUnicode_DecodeUTF8(pStr, strlen(pStr), \"ignore\");\n }\n};\n\nstruct UTF8String_from_unicode\n{\n UTF8String_from_unicode()\n {\n boost::python::converter::registry::push_back(\n &convertible,\n &construct,\n boost::python::type_id<UTF8String>());\n }\n\n static void* convertible(PyObject* obj_ptr)\n {\n if (!PyUnicode_Check(obj_ptr)) return 0;\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n PyObject * pPyUTF8 = PyUnicode_AsUTF8String(obj_ptr);\n char * psz = PyString_AsString(pPyUTF8);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<UTF8String>*)data)\n ->storage.bytes;\n new (storage) UTF8String(psz);\n data->convertible = storage;\n Py_DECREF(pPyUTF8);\n }\n};\n\nstruct UTF8String_from_string\n{\n UTF8String_from_string()\n {\n boost::python::converter::registry::push_back(\n &convertible,\n &construct,\n boost::python::type_id<UTF8String>());\n }\n\n static void* convertible(PyObject* obj_ptr)\n {\n if (!PyString_Check(obj_ptr)) return 0;\n return obj_ptr;\n }\n\n static void construct(PyObject* obj_ptr,\n boost::python::converter::rvalue_from_python_stage1_data* data)\n {\n const char * psz = PyString_AsString(obj_ptr);\n void* storage = (\n (boost::python::converter::rvalue_from_python_storage<UTF8String>*)data)\n ->storage.bytes;\n new (storage) UTF8String(psz);\n data->convertible = storage;\n }\n};\n\nvoid exportMessages(object& nodeClass, const string& sClassName)\n{\n PublisherDefinitionPtr pPubDef = PublisherDefinitionRegistry::get()\n ->getDefinition(sClassName);\n const vector<MessageID>& messageIDs = pPubDef->getMessageIDs();\n for (unsigned i=0; i<messageIDs.size(); ++i) {\n string sName = messageIDs[i].m_sName;\n nodeClass.attr(sName.c_str()) = messageIDs[i];\n }\n};\n\nstruct type_info_to_string{\n static PyObject* convert(const std::type_info& info)\n {\n boost::python::object result(ObjectCounter::get()->demangle(info.name()));\n return boost::python::incref(result.ptr());\n }\n};\n\n\nvoid export_base()\n{\n \/\/ Exceptions\n\n translateException<exception>(PyExc_RuntimeError);\n translateException<out_of_range>(PyExc_IndexError);\n translateException<Exception>(PyExc_RuntimeError);\n to_python_converter< exception, Exception_to_python_exception<exception> >();\n to_python_converter< Exception, Exception_to_python_exception<Exception> >();\n \n \/\/ vec2\n to_python_converter<IntPoint, Vec2_to_python_tuple<IntPoint> >();\n vec2_from_python<IntPoint, int>();\n vec2_from_python<glm::vec2, float>();\n vec2_from_python<ConstVec2, float>();\n \n \/\/ vector<vec2>\n to_python_converter<vector<glm::vec2>, to_list<vector<glm::vec2> > >(); \n from_python_sequence<vector<IntPoint>, variable_capacity_policy>();\n from_python_sequence<vector<glm::vec2>, variable_capacity_policy>();\n\n \/\/ vec3\n to_python_converter<glm::ivec3, Vec3_to_python_tuple<glm::ivec3> >();\n to_python_converter<glm::vec3, Vec3_to_python_tuple<glm::vec3> >();\n vec3_from_python<glm::ivec3, int>();\n vec3_from_python<glm::vec3, float>();\n \n \/\/ vector<vec3>\n to_python_converter<vector<glm::ivec3>, to_list<vector<glm::ivec3> > >(); \n to_python_converter<vector<glm::vec3>, to_list<vector<glm::vec3> > >(); \n from_python_sequence<vector<glm::ivec3>, variable_capacity_policy>();\n from_python_sequence<vector<glm::vec3>, variable_capacity_policy>();\n\n \/\/ string\n to_python_converter<UTF8String, UTF8String_to_unicode>();\n UTF8String_from_unicode();\n UTF8String_from_string();\n\n to_python_converter<vector<string>, to_list<vector<string> > >(); \n from_python_sequence<vector<string>, variable_capacity_policy>();\n \n from_python_sequence<vector<float>, variable_capacity_policy>();\n from_python_sequence<vector<int>, variable_capacity_policy>();\n\n to_python_converter<std::type_info, type_info_to_string>();\n \/\/Maps\n to_python_converter<TypeMap, to_dict<TypeMap> >();\n}\n\nnamespace {\n std::map<PyObject *, LogSinkPtr> m_pyObjectMap;\n}\n\nvoid addPythonLogger(PyObject * self, PyObject * pyLogger)\n{\n Logger * logger = Logger::get();\n LogSinkPtr logSink(new PythonLogSink(pyLogger));\n logger->addLogSink(logSink);\n m_pyObjectMap[pyLogger] = logSink;\n}\n\nvoid removePythonLogger(PyObject * self, PyObject * pyLogger)\n{\n Logger* logger = Logger::get();\n std::map<PyObject *, LogSinkPtr>::iterator it;\n it = m_pyObjectMap.find(pyLogger);\n if( it !=m_pyObjectMap.end() ){\n logger->removeLogSink(it->second);\n m_pyObjectMap.erase(it);\n }\n}\n\nvoid pytrace(PyObject * self, size_t category, const UTF8String& sMsg, unsigned severity)\n{\n avgDeprecationWarning(string(\"1.8\"), \"logger.trace\",\n \"any of the logging convenience functions\");\n Logger::get()->trace(sMsg, category, severity);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"commandsfile.h\"\n#include \"command_p.h\"\n#include <coreplugin\/dialogs\/shortcutsettings.h>\n\n#include <app\/app_version.h>\n\n#include <utils\/qtcassert.h>\n\n#include <utils\/fileutils.h>\n\n#include <QKeySequence>\n#include <QFile>\n#include <QXmlStreamAttributes>\n#include <QXmlStreamWriter>\n#include <QXmlStreamReader>\n#include <QDebug>\n#include <QDateTime>\n\nnamespace Core {\nnamespace Internal {\n\nstruct Context \/\/ XML parsing context with strings.\n{\n Context();\n\n const QString mappingElement;\n const QString shortCutElement;\n const QString idAttribute;\n const QString keyElement;\n const QString valueAttribute;\n};\n\nContext::Context() :\n mappingElement(QLatin1String(\"mapping\")),\n shortCutElement(QLatin1String(\"shortcut\")),\n idAttribute(QLatin1String(\"id\")),\n keyElement(QLatin1String(\"key\")),\n valueAttribute(QLatin1String(\"value\"))\n{\n}\n\n\/*!\n \\class CommandsFile\n \\brief The CommandsFile class provides a collection of import and export commands.\n \\inheaderfile commandsfile.h\n*\/\n\n\/*!\n ...\n*\/\nCommandsFile::CommandsFile(const QString &filename)\n : m_filename(filename)\n{\n\n}\n\n\/*!\n ...\n*\/\nQMap<QString, QKeySequence> CommandsFile::importCommands() const\n{\n QMap<QString, QKeySequence> result;\n\n QFile file(m_filename);\n if (!file.open(QIODevice::ReadOnly|QIODevice::Text))\n return result;\n\n Context ctx;\n QXmlStreamReader r(&file);\n\n QString currentId;\n\n while (!r.atEnd()) {\n switch (r.readNext()) {\n case QXmlStreamReader::StartElement: {\n const QStringRef name = r.name();\n if (name == ctx.shortCutElement) {\n currentId = r.attributes().value(ctx.idAttribute).toString();\n } else if (name == ctx.keyElement) {\n QTC_ASSERT(!currentId.isEmpty(), return result);\n const QXmlStreamAttributes attributes = r.attributes();\n if (attributes.hasAttribute(ctx.valueAttribute)) {\n const QString keyString = attributes.value(ctx.valueAttribute).toString();\n result.insert(currentId, QKeySequence(keyString));\n } else {\n result.insert(currentId, QKeySequence());\n }\n currentId.clear();\n } \/\/ if key element\n } \/\/ case QXmlStreamReader::StartElement\n default:\n break;\n } \/\/ switch\n } \/\/ while !atEnd\n file.close();\n return result;\n}\n\n\/*!\n ...\n*\/\n\nbool CommandsFile::exportCommands(const QList<ShortcutItem *> &items)\n{\n Utils::FileSaver saver(m_filename, QIODevice::Text);\n if (!saver.hasError()) {\n const Context ctx;\n QXmlStreamWriter w(saver.file());\n w.setAutoFormatting(true);\n w.setAutoFormattingIndent(1); \/\/ Historical, used to be QDom.\n w.writeStartDocument();\n w.writeDTD(QLatin1String(\"<!DOCTYPE KeyboardMappingScheme>\"));\n w.writeComment(QString::fromLatin1(\" Written by Qt Creator %1, %2. \").\n arg(QLatin1String(Constants::IDE_VERSION_LONG),\n QDateTime::currentDateTime().toString(Qt::ISODate)));\n w.writeStartElement(ctx.mappingElement);\n foreach (const ShortcutItem *item, items) {\n const Id id = item->m_cmd->id();\n if (item->m_key.isEmpty()) {\n w.writeEmptyElement(ctx.shortCutElement);\n w.writeAttribute(ctx.idAttribute, id.toString());\n } else {\n w.writeStartElement(ctx.shortCutElement);\n w.writeAttribute(ctx.idAttribute, id.toString());\n w.writeEmptyElement(ctx.keyElement);\n w.writeAttribute(ctx.valueAttribute, item->m_key.toString());\n w.writeEndElement(); \/\/ Shortcut\n }\n }\n w.writeEndElement();\n w.writeEndDocument();\n\n saver.setResult(&w);\n }\n return saver.finalize();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Core\n<commit_msg>Fix importing empty shortcuts from keyboard shortcut settings<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"commandsfile.h\"\n#include \"command_p.h\"\n#include <coreplugin\/dialogs\/shortcutsettings.h>\n\n#include <app\/app_version.h>\n\n#include <utils\/qtcassert.h>\n\n#include <utils\/fileutils.h>\n\n#include <QKeySequence>\n#include <QFile>\n#include <QXmlStreamAttributes>\n#include <QXmlStreamWriter>\n#include <QXmlStreamReader>\n#include <QDebug>\n#include <QDateTime>\n\nnamespace Core {\nnamespace Internal {\n\nstruct Context \/\/ XML parsing context with strings.\n{\n Context();\n\n const QString mappingElement;\n const QString shortCutElement;\n const QString idAttribute;\n const QString keyElement;\n const QString valueAttribute;\n};\n\nContext::Context() :\n mappingElement(QLatin1String(\"mapping\")),\n shortCutElement(QLatin1String(\"shortcut\")),\n idAttribute(QLatin1String(\"id\")),\n keyElement(QLatin1String(\"key\")),\n valueAttribute(QLatin1String(\"value\"))\n{\n}\n\n\/*!\n \\class CommandsFile\n \\brief The CommandsFile class provides a collection of import and export commands.\n \\inheaderfile commandsfile.h\n*\/\n\n\/*!\n ...\n*\/\nCommandsFile::CommandsFile(const QString &filename)\n : m_filename(filename)\n{\n\n}\n\n\/*!\n ...\n*\/\nQMap<QString, QKeySequence> CommandsFile::importCommands() const\n{\n QMap<QString, QKeySequence> result;\n\n QFile file(m_filename);\n if (!file.open(QIODevice::ReadOnly|QIODevice::Text))\n return result;\n\n Context ctx;\n QXmlStreamReader r(&file);\n\n QString currentId;\n\n while (!r.atEnd()) {\n switch (r.readNext()) {\n case QXmlStreamReader::StartElement: {\n const QStringRef name = r.name();\n if (name == ctx.shortCutElement) {\n if (!currentId.isEmpty()) \/\/ shortcut element without key element == empty shortcut\n result.insert(currentId, QKeySequence());\n currentId = r.attributes().value(ctx.idAttribute).toString();\n } else if (name == ctx.keyElement) {\n QTC_ASSERT(!currentId.isEmpty(), return result);\n const QXmlStreamAttributes attributes = r.attributes();\n if (attributes.hasAttribute(ctx.valueAttribute)) {\n const QString keyString = attributes.value(ctx.valueAttribute).toString();\n result.insert(currentId, QKeySequence(keyString));\n } else {\n result.insert(currentId, QKeySequence());\n }\n currentId.clear();\n } \/\/ if key element\n } \/\/ case QXmlStreamReader::StartElement\n default:\n break;\n } \/\/ switch\n } \/\/ while !atEnd\n file.close();\n return result;\n}\n\n\/*!\n ...\n*\/\n\nbool CommandsFile::exportCommands(const QList<ShortcutItem *> &items)\n{\n Utils::FileSaver saver(m_filename, QIODevice::Text);\n if (!saver.hasError()) {\n const Context ctx;\n QXmlStreamWriter w(saver.file());\n w.setAutoFormatting(true);\n w.setAutoFormattingIndent(1); \/\/ Historical, used to be QDom.\n w.writeStartDocument();\n w.writeDTD(QLatin1String(\"<!DOCTYPE KeyboardMappingScheme>\"));\n w.writeComment(QString::fromLatin1(\" Written by Qt Creator %1, %2. \").\n arg(QLatin1String(Constants::IDE_VERSION_LONG),\n QDateTime::currentDateTime().toString(Qt::ISODate)));\n w.writeStartElement(ctx.mappingElement);\n foreach (const ShortcutItem *item, items) {\n const Id id = item->m_cmd->id();\n if (item->m_key.isEmpty()) {\n w.writeEmptyElement(ctx.shortCutElement);\n w.writeAttribute(ctx.idAttribute, id.toString());\n } else {\n w.writeStartElement(ctx.shortCutElement);\n w.writeAttribute(ctx.idAttribute, id.toString());\n w.writeEmptyElement(ctx.keyElement);\n w.writeAttribute(ctx.valueAttribute, item->m_key.toString());\n w.writeEndElement(); \/\/ Shortcut\n }\n }\n w.writeEndElement();\n w.writeEndDocument();\n\n saver.setResult(&w);\n }\n return saver.finalize();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Core\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/ Copyright 2010 Bastian Holst <bastianholst@gmx.de>\n\/\/ Copyright 2013 Mohammed Nafees <nafees.technocool@gmail.com>\n\/\/\n\n#include \"NavigationFloatItem.h\"\n\n#include <QtCore\/qmath.h>\n#include <QtCore\/QRect>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QToolButton>\n#include <QtGui\/QSlider>\n#include <QtGui\/QWidget>\n#include <QtGui\/QPainter>\n\n#include \"ui_navigation.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleWidget.h\"\n#include \"WidgetGraphicsItem.h\"\n#include \"MarbleGraphicsGridLayout.h\"\n\nusing namespace Marble;\n\/* TRANSLATOR Marble::NavigationFloatItem *\/\n\nNavigationFloatItem::NavigationFloatItem()\n : AbstractFloatItem( 0 )\n{\n}\n\nNavigationFloatItem::NavigationFloatItem( const MarbleModel *marbleModel )\n : AbstractFloatItem( marbleModel, QPointF( -10, -30 ) ),\n m_marbleWidget( 0 ),\n m_widgetItem( 0 ),\n m_navigationWidget( 0 ),\n m_oldViewportRadius( 0 )\n{\n \/\/ Plugin is enabled by default\n setEnabled( true );\n setVisible( false );\n\n setCacheMode( NoCache );\n setBackground( QBrush( QColor( Qt::transparent ) ) );\n setFrame( NoFrame );\n}\n\nNavigationFloatItem::~NavigationFloatItem()\n{\n delete m_navigationWidget;\n}\n\nQStringList NavigationFloatItem::backendTypes() const\n{\n return QStringList(\"navigation\");\n}\n\nQString NavigationFloatItem::name() const\n{\n return tr(\"Navigation\");\n}\n\nQString NavigationFloatItem::guiString() const\n{\n return tr(\"&Navigation\");\n}\n\nQString NavigationFloatItem::nameId() const\n{\n return QString(\"navigation\");\n}\n\nQString NavigationFloatItem::version() const\n{\n return \"1.0\";\n}\n\nQString NavigationFloatItem::description() const\n{\n return tr(\"A mouse control to zoom and move the map\");\n}\n\nQString NavigationFloatItem::copyrightYears() const\n{\n return \"2008, 2010, 2013\";\n}\n\nQList<PluginAuthor> NavigationFloatItem::pluginAuthors() const\n{\n return QList<PluginAuthor>()\n << PluginAuthor( QString::fromUtf8( \"Dennis Nienhüser\" ), \"earthwings@gentoo.org\" )\n << PluginAuthor( \"Bastian Holst\", \"bastianholst@gmx.de\" )\n << PluginAuthor( \"Mohammed Nafees\", \"nafees.technocool@gmail.com\" );\n}\n\nQIcon NavigationFloatItem::icon() const\n{\n return QIcon(\":\/icons\/navigation.png\");\n}\n\nvoid NavigationFloatItem::initialize()\n{\n QWidget *navigationParent = new QWidget( 0 );\n navigationParent->setAttribute( Qt::WA_NoSystemBackground, true );\n\n m_navigationWidget = new Ui::Navigation;\n m_navigationWidget->setupUi( navigationParent );\n\n m_widgetItem = new WidgetGraphicsItem( this );\n m_widgetItem->setWidget( navigationParent );\n\n MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );\n layout->addItem( m_widgetItem, 0, 0 );\n\n setLayout( layout );\n}\n\nbool NavigationFloatItem::isInitialized() const\n{\n return m_widgetItem;\n}\n\nvoid NavigationFloatItem::changeViewport( ViewportParams *viewport )\n{\n if ( viewport->radius() != m_oldViewportRadius ) {\n const qreal zoomValue = (200.0 * qLn( viewport->radius() ) ); \/\/ copied from MarbleWidgetPrivate::zoom()\n setZoomSliderValue( zoomValue );\n\n m_oldViewportRadius = viewport->radius();\n \/\/ The slider depends on the map state (zoom factor)\n update();\n }\n}\n\nbool NavigationFloatItem::eventFilter( QObject *object, QEvent *e )\n{\n if ( !enabled() || !visible() ) {\n return false;\n }\n\n MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);\n if ( !widget ) {\n return AbstractFloatItem::eventFilter( object, e );\n }\n\n if ( m_marbleWidget != widget ) {\n \/\/ Delayed initialization\n m_marbleWidget = widget;\n\n m_maxZoom = m_marbleWidget->maximumZoom();\n m_minZoom = m_marbleWidget->minimumZoom();\n\n m_navigationWidget->arrowDisc->setMarbleWidget( m_marbleWidget );\n connect( m_navigationWidget->arrowDisc, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n\n connect( m_navigationWidget->homeButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->homeButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(goHome()) );\n\n connect( m_navigationWidget->zoomInButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->zoomInButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(zoomIn()) );\n\n connect( m_navigationWidget->zoomOutButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->zoomOutButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(zoomOut()) );\n\n connect( m_marbleWidget, SIGNAL(zoomChanged(int)), SLOT(updateButtons(int)) );\n updateButtons( m_marbleWidget->zoom() );\n connect( m_marbleWidget, SIGNAL(themeChanged(QString)), this, SLOT(selectTheme(QString)) );\n\n }\n\n return AbstractFloatItem::eventFilter(object, e);\n}\n\nvoid NavigationFloatItem::setZoomSliderValue( int level )\n{\n}\n\nvoid NavigationFloatItem::setMarbleZoomValue( int level )\n{\n \/\/ There exists a circular signal\/slot connection between MarbleWidget and this widget's\n \/\/ zoom slider. MarbleWidget prevents recursion, but it still loops one time unless\n \/\/ disconnected here.\n \/\/ The circular signal\/slot connection results into the Marble Globe flickering, when the\n \/\/ zoom slider is used.\n\n if( !m_marbleWidget ) {\n return;\n }\n\n disconnect( m_marbleWidget, SIGNAL(zoomChanged(int)),\n this, SLOT(setZoomSliderValue(int)) );\n m_marbleWidget->zoomView( level );\n connect( m_marbleWidget, SIGNAL(zoomChanged(int)),\n this, SLOT(setZoomSliderValue(int)) );\n}\n\nvoid NavigationFloatItem::selectTheme( QString )\n{\n if ( m_marbleWidget ) {\n m_maxZoom = m_marbleWidget->maximumZoom();\n m_minZoom = m_marbleWidget->minimumZoom();\n updateButtons( m_marbleWidget->zoom() );\n }\n}\n\nvoid NavigationFloatItem::adjustForAnimation()\n{\n if ( !m_marbleWidget ) {\n return;\n }\n\n m_marbleWidget->setViewContext( Animation );\n}\n\nvoid NavigationFloatItem::adjustForStill()\n{\n if ( !m_marbleWidget ) {\n return;\n }\n\n m_marbleWidget->setViewContext( Still );\n}\n\nvoid NavigationFloatItem::updateButtons( int zoomValue )\n{\n bool const zoomInEnabled = m_navigationWidget->zoomInButton->isEnabled();\n bool const zoomOutEnabled = m_navigationWidget->zoomOutButton->isEnabled();\n m_navigationWidget->zoomInButton->setEnabled( zoomValue < m_maxZoom );\n m_navigationWidget->zoomOutButton->setEnabled( zoomValue > m_minZoom );\n if ( zoomInEnabled != m_navigationWidget->zoomInButton->isEnabled() ||\n zoomOutEnabled != m_navigationWidget->zoomOutButton->isEnabled() ) {\n update();\n }\n}\n\nQ_EXPORT_PLUGIN2( NavigationFloatItem, Marble::NavigationFloatItem )\n\n#include \"NavigationFloatItem.moc\"\n<commit_msg>Navigation float item is visible by default now.<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/ Copyright 2010 Bastian Holst <bastianholst@gmx.de>\n\/\/ Copyright 2013 Mohammed Nafees <nafees.technocool@gmail.com>\n\/\/\n\n#include \"NavigationFloatItem.h\"\n\n#include <QtCore\/qmath.h>\n#include <QtCore\/QRect>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QToolButton>\n#include <QtGui\/QSlider>\n#include <QtGui\/QWidget>\n#include <QtGui\/QPainter>\n\n#include \"ui_navigation.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleWidget.h\"\n#include \"WidgetGraphicsItem.h\"\n#include \"MarbleGraphicsGridLayout.h\"\n\nusing namespace Marble;\n\/* TRANSLATOR Marble::NavigationFloatItem *\/\n\nNavigationFloatItem::NavigationFloatItem()\n : AbstractFloatItem( 0 )\n{\n}\n\nNavigationFloatItem::NavigationFloatItem( const MarbleModel *marbleModel )\n : AbstractFloatItem( marbleModel, QPointF( -10, -30 ) ),\n m_marbleWidget( 0 ),\n m_widgetItem( 0 ),\n m_navigationWidget( 0 ),\n m_oldViewportRadius( 0 )\n{\n \/\/ Plugin is visible by default\n setEnabled( true );\n setVisible( true );\n\n setCacheMode( NoCache );\n setBackground( QBrush( QColor( Qt::transparent ) ) );\n setFrame( NoFrame );\n}\n\nNavigationFloatItem::~NavigationFloatItem()\n{\n delete m_navigationWidget;\n}\n\nQStringList NavigationFloatItem::backendTypes() const\n{\n return QStringList(\"navigation\");\n}\n\nQString NavigationFloatItem::name() const\n{\n return tr(\"Navigation\");\n}\n\nQString NavigationFloatItem::guiString() const\n{\n return tr(\"&Navigation\");\n}\n\nQString NavigationFloatItem::nameId() const\n{\n return QString(\"navigation\");\n}\n\nQString NavigationFloatItem::version() const\n{\n return \"1.0\";\n}\n\nQString NavigationFloatItem::description() const\n{\n return tr(\"A mouse control to zoom and move the map\");\n}\n\nQString NavigationFloatItem::copyrightYears() const\n{\n return \"2008, 2010, 2013\";\n}\n\nQList<PluginAuthor> NavigationFloatItem::pluginAuthors() const\n{\n return QList<PluginAuthor>()\n << PluginAuthor( QString::fromUtf8( \"Dennis Nienhüser\" ), \"earthwings@gentoo.org\" )\n << PluginAuthor( \"Bastian Holst\", \"bastianholst@gmx.de\" )\n << PluginAuthor( \"Mohammed Nafees\", \"nafees.technocool@gmail.com\" );\n}\n\nQIcon NavigationFloatItem::icon() const\n{\n return QIcon(\":\/icons\/navigation.png\");\n}\n\nvoid NavigationFloatItem::initialize()\n{\n QWidget *navigationParent = new QWidget( 0 );\n navigationParent->setAttribute( Qt::WA_NoSystemBackground, true );\n\n m_navigationWidget = new Ui::Navigation;\n m_navigationWidget->setupUi( navigationParent );\n\n m_widgetItem = new WidgetGraphicsItem( this );\n m_widgetItem->setWidget( navigationParent );\n\n MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );\n layout->addItem( m_widgetItem, 0, 0 );\n\n setLayout( layout );\n}\n\nbool NavigationFloatItem::isInitialized() const\n{\n return m_widgetItem;\n}\n\nvoid NavigationFloatItem::changeViewport( ViewportParams *viewport )\n{\n if ( viewport->radius() != m_oldViewportRadius ) {\n const qreal zoomValue = (200.0 * qLn( viewport->radius() ) ); \/\/ copied from MarbleWidgetPrivate::zoom()\n setZoomSliderValue( zoomValue );\n\n m_oldViewportRadius = viewport->radius();\n \/\/ The slider depends on the map state (zoom factor)\n update();\n }\n}\n\nbool NavigationFloatItem::eventFilter( QObject *object, QEvent *e )\n{\n if ( !enabled() || !visible() ) {\n return false;\n }\n\n MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object);\n if ( !widget ) {\n return AbstractFloatItem::eventFilter( object, e );\n }\n\n if ( m_marbleWidget != widget ) {\n \/\/ Delayed initialization\n m_marbleWidget = widget;\n\n m_maxZoom = m_marbleWidget->maximumZoom();\n m_minZoom = m_marbleWidget->minimumZoom();\n\n m_navigationWidget->arrowDisc->setMarbleWidget( m_marbleWidget );\n connect( m_navigationWidget->arrowDisc, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n\n connect( m_navigationWidget->homeButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->homeButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(goHome()) );\n\n connect( m_navigationWidget->zoomInButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->zoomInButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(zoomIn()) );\n\n connect( m_navigationWidget->zoomOutButton, SIGNAL(repaintNeeded()), SIGNAL(repaintNeeded()) );\n connect( m_navigationWidget->zoomOutButton, SIGNAL(clicked()),\n m_marbleWidget, SLOT(zoomOut()) );\n\n connect( m_marbleWidget, SIGNAL(zoomChanged(int)), SLOT(updateButtons(int)) );\n updateButtons( m_marbleWidget->zoom() );\n connect( m_marbleWidget, SIGNAL(themeChanged(QString)), this, SLOT(selectTheme(QString)) );\n\n }\n\n return AbstractFloatItem::eventFilter(object, e);\n}\n\nvoid NavigationFloatItem::setZoomSliderValue( int level )\n{\n}\n\nvoid NavigationFloatItem::setMarbleZoomValue( int level )\n{\n \/\/ There exists a circular signal\/slot connection between MarbleWidget and this widget's\n \/\/ zoom slider. MarbleWidget prevents recursion, but it still loops one time unless\n \/\/ disconnected here.\n \/\/ The circular signal\/slot connection results into the Marble Globe flickering, when the\n \/\/ zoom slider is used.\n\n if( !m_marbleWidget ) {\n return;\n }\n\n disconnect( m_marbleWidget, SIGNAL(zoomChanged(int)),\n this, SLOT(setZoomSliderValue(int)) );\n m_marbleWidget->zoomView( level );\n connect( m_marbleWidget, SIGNAL(zoomChanged(int)),\n this, SLOT(setZoomSliderValue(int)) );\n}\n\nvoid NavigationFloatItem::selectTheme( QString )\n{\n if ( m_marbleWidget ) {\n m_maxZoom = m_marbleWidget->maximumZoom();\n m_minZoom = m_marbleWidget->minimumZoom();\n updateButtons( m_marbleWidget->zoom() );\n }\n}\n\nvoid NavigationFloatItem::adjustForAnimation()\n{\n if ( !m_marbleWidget ) {\n return;\n }\n\n m_marbleWidget->setViewContext( Animation );\n}\n\nvoid NavigationFloatItem::adjustForStill()\n{\n if ( !m_marbleWidget ) {\n return;\n }\n\n m_marbleWidget->setViewContext( Still );\n}\n\nvoid NavigationFloatItem::updateButtons( int zoomValue )\n{\n bool const zoomInEnabled = m_navigationWidget->zoomInButton->isEnabled();\n bool const zoomOutEnabled = m_navigationWidget->zoomOutButton->isEnabled();\n m_navigationWidget->zoomInButton->setEnabled( zoomValue < m_maxZoom );\n m_navigationWidget->zoomOutButton->setEnabled( zoomValue > m_minZoom );\n if ( zoomInEnabled != m_navigationWidget->zoomInButton->isEnabled() ||\n zoomOutEnabled != m_navigationWidget->zoomOutButton->isEnabled() ) {\n update();\n }\n}\n\nQ_EXPORT_PLUGIN2( NavigationFloatItem, Marble::NavigationFloatItem )\n\n#include \"NavigationFloatItem.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n#include \"sparse.h\"\n#include <Eigen\/SparseQR>\n\n\ntemplate<typename MatrixType,typename DenseMat>\nint generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)\n{\n eigen_assert(maxRows >= maxCols);\n typedef typename MatrixType::Scalar Scalar;\n int rows = internal::random<int>(1,maxRows);\n int cols = internal::random<int>(1,rows);\n double density = (std::max)(8.\/(rows*cols), 0.01);\n \n A.resize(rows,rows);\n dA.resize(rows,rows);\n initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);\n A.makeCompressed();\n int nop = internal::random<int>(0, internal::random<double>(0,1) > 0.5 ? cols\/2 : 0);\n for(int k=0; k<nop; ++k)\n {\n int j0 = internal::random<int>(0,cols-1);\n int j1 = internal::random<int>(0,cols-1);\n Scalar s = internal::random<Scalar>();\n A.col(j0) = s * A.col(j1);\n dA.col(j0) = s * dA.col(j1);\n }\n return rows;\n}\n\ntemplate<typename Scalar> void test_sparseqr_scalar()\n{\n typedef SparseMatrix<Scalar,ColMajor> MatrixType; \n typedef Matrix<Scalar,Dynamic,Dynamic> DenseMat;\n typedef Matrix<Scalar,Dynamic,1> DenseVector;\n MatrixType A;\n DenseMat dA;\n DenseVector refX,x,b; \n SparseQR<MatrixType, AMDOrdering<int> > solver; \n generate_sparse_rectangular_problem(A,dA);\n \n int n = A.cols();\n b = DenseVector::Random(n);\n solver.compute(A);\n if (solver.info() != Success)\n {\n std::cerr << \"sparse QR factorization failed\\n\";\n exit(0);\n return;\n }\n x = solver.solve(b);\n if (solver.info() != Success)\n {\n std::cerr << \"sparse QR factorization failed\\n\";\n exit(0);\n return;\n } \n \/\/Compare with a dense QR solver\n ColPivHouseholderQR<DenseMat> dqr(dA);\n refX = dqr.solve(b);\n \n VERIFY_IS_EQUAL(dqr.rank(), solver.rank());\n \n if(solver.rank()<A.cols())\n VERIFY((dA * refX - b).norm() * 2 > (A * x - b).norm() );\n else\n VERIFY_IS_APPROX(x, refX);\n}\nvoid test_sparseqr()\n{\n for(int i=0; i<g_repeat; ++i)\n {\n CALL_SUBTEST_1(test_sparseqr_scalar<double>());\n CALL_SUBTEST_2(test_sparseqr_scalar<std::complex<double> >());\n }\n}<commit_msg>Fix no newline warning.<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n#include \"sparse.h\"\n#include <Eigen\/SparseQR>\n\n\ntemplate<typename MatrixType,typename DenseMat>\nint generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)\n{\n eigen_assert(maxRows >= maxCols);\n typedef typename MatrixType::Scalar Scalar;\n int rows = internal::random<int>(1,maxRows);\n int cols = internal::random<int>(1,rows);\n double density = (std::max)(8.\/(rows*cols), 0.01);\n \n A.resize(rows,rows);\n dA.resize(rows,rows);\n initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);\n A.makeCompressed();\n int nop = internal::random<int>(0, internal::random<double>(0,1) > 0.5 ? cols\/2 : 0);\n for(int k=0; k<nop; ++k)\n {\n int j0 = internal::random<int>(0,cols-1);\n int j1 = internal::random<int>(0,cols-1);\n Scalar s = internal::random<Scalar>();\n A.col(j0) = s * A.col(j1);\n dA.col(j0) = s * dA.col(j1);\n }\n return rows;\n}\n\ntemplate<typename Scalar> void test_sparseqr_scalar()\n{\n typedef SparseMatrix<Scalar,ColMajor> MatrixType; \n typedef Matrix<Scalar,Dynamic,Dynamic> DenseMat;\n typedef Matrix<Scalar,Dynamic,1> DenseVector;\n MatrixType A;\n DenseMat dA;\n DenseVector refX,x,b; \n SparseQR<MatrixType, AMDOrdering<int> > solver; \n generate_sparse_rectangular_problem(A,dA);\n \n int n = A.cols();\n b = DenseVector::Random(n);\n solver.compute(A);\n if (solver.info() != Success)\n {\n std::cerr << \"sparse QR factorization failed\\n\";\n exit(0);\n return;\n }\n x = solver.solve(b);\n if (solver.info() != Success)\n {\n std::cerr << \"sparse QR factorization failed\\n\";\n exit(0);\n return;\n } \n \/\/Compare with a dense QR solver\n ColPivHouseholderQR<DenseMat> dqr(dA);\n refX = dqr.solve(b);\n \n VERIFY_IS_EQUAL(dqr.rank(), solver.rank());\n \n if(solver.rank()<A.cols())\n VERIFY((dA * refX - b).norm() * 2 > (A * x - b).norm() );\n else\n VERIFY_IS_APPROX(x, refX);\n}\nvoid test_sparseqr()\n{\n for(int i=0; i<g_repeat; ++i)\n {\n CALL_SUBTEST_1(test_sparseqr_scalar<double>());\n CALL_SUBTEST_2(test_sparseqr_scalar<std::complex<double> >());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n\n#include \"catch.hpp\"\n\n#include \"variant.hpp\"\n#include \"variant_io.hpp\"\n\nstruct some_struct {\n int a;\n bool b;\n std::string c;\n};\n\nusing variant_internal_index_type = size_t;\n\nTEST_CASE( \"size of variants\" ) {\n constexpr const auto min_overhead = sizeof(variant_internal_index_type);\n\n using std::max_align_t; \/\/ workaround for bug in GCC <= 4.8 where max_align_t is not in std\n constexpr const auto max_overhead = alignof(max_align_t) + min_overhead;\n\n using v1 = mapbox::util::variant<int>;\n using v2 = mapbox::util::variant<int, bool, int64_t>;\n using v3 = mapbox::util::variant<int, std::string>;\n using v4 = mapbox::util::variant<std::string, std::string>;\n using v5 = mapbox::util::variant<some_struct>;\n\n constexpr const auto si = sizeof(int);\n constexpr const auto sb = sizeof(bool);\n constexpr const auto si64 = sizeof(int64_t);\n constexpr const auto sd = sizeof(double);\n constexpr const auto sstr = sizeof(std::string);\n constexpr const auto spi = sizeof(std::pair<int, int>);\n constexpr const auto ss = sizeof(some_struct);\n\n REQUIRE(sizeof(v1) <= max_overhead + si );\n REQUIRE(sizeof(v2) <= max_overhead + std::max({si, sb, si64}));\n REQUIRE(sizeof(v3) <= max_overhead + std::max({si, sstr}) );\n REQUIRE(sizeof(v4) <= max_overhead + sstr );\n REQUIRE(sizeof(v5) <= max_overhead + ss );\n\n REQUIRE(sizeof(v1) >= min_overhead + si );\n REQUIRE(sizeof(v2) >= min_overhead + std::max({si, sb, si64}));\n REQUIRE(sizeof(v3) >= min_overhead + std::max({si, sstr}) );\n REQUIRE(sizeof(v4) >= min_overhead + sstr );\n REQUIRE(sizeof(v5) >= min_overhead + ss );\n}\n\n<commit_msg>Fix for the workaround in 86a78c2adfde1de718231ea8f95af4745e838779.<commit_after>\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n\n#include \"catch.hpp\"\n\n#include \"variant.hpp\"\n#include \"variant_io.hpp\"\n\nstruct some_struct {\n int a;\n bool b;\n std::string c;\n};\n\nusing variant_internal_index_type = size_t;\n\nTEST_CASE( \"size of variants\" ) {\n constexpr const auto min_overhead = sizeof(variant_internal_index_type);\n\n using namespace std; \/\/ workaround for bug in GCC <= 4.8 where max_align_t is not in std\n constexpr const auto max_overhead = alignof(max_align_t) + min_overhead;\n\n using v1 = mapbox::util::variant<int>;\n using v2 = mapbox::util::variant<int, bool, int64_t>;\n using v3 = mapbox::util::variant<int, std::string>;\n using v4 = mapbox::util::variant<std::string, std::string>;\n using v5 = mapbox::util::variant<some_struct>;\n\n constexpr const auto si = sizeof(int);\n constexpr const auto sb = sizeof(bool);\n constexpr const auto si64 = sizeof(int64_t);\n constexpr const auto sd = sizeof(double);\n constexpr const auto sstr = sizeof(std::string);\n constexpr const auto spi = sizeof(std::pair<int, int>);\n constexpr const auto ss = sizeof(some_struct);\n\n REQUIRE(sizeof(v1) <= max_overhead + si );\n REQUIRE(sizeof(v2) <= max_overhead + std::max({si, sb, si64}));\n REQUIRE(sizeof(v3) <= max_overhead + std::max({si, sstr}) );\n REQUIRE(sizeof(v4) <= max_overhead + sstr );\n REQUIRE(sizeof(v5) <= max_overhead + ss );\n\n REQUIRE(sizeof(v1) >= min_overhead + si );\n REQUIRE(sizeof(v2) >= min_overhead + std::max({si, sb, si64}));\n REQUIRE(sizeof(v3) >= min_overhead + std::max({si, sstr}) );\n REQUIRE(sizeof(v4) >= min_overhead + sstr );\n REQUIRE(sizeof(v5) >= min_overhead + ss );\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <clocale>\n#include <locale>\n\n#include \"interp.hxx\"\n#include \"common.hxx\"\n\nusing namespace std;\nusing namespace tglng;\n\nint main(int argc, const char*const* argv) {\n wstring out;\n Interpreter interp;\n\n setlocale(LC_ALL, \"\");\n setlocale(LC_NUMERIC, \"C\");\n locale::global(locale(\"\"));\n\n \/\/Try to read from standard configuration file.\n \/\/TODO: Change this to something more sensible\n {\n wifstream in(\"rc.default\");\n if (!interp.exec(out, in, Interpreter::ParseModeCommand)) {\n wcerr << L\"Error reading user library.\" << endl;\n return EXIT_EXEC_ERROR_IN_USER_LIBRARY;\n }\n }\n\n if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) {\n wcout << out;\n Interpreter::freeGlobalBindings();\n return 0;\n } else {\n wcerr << L\"Failed.\" << endl;\n return EXIT_EXEC_ERROR_IN_INPUT;\n }\n}\n<commit_msg>Sort-of work around GNU C++ locale being broken on non-GNU libc.<commit_after>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <clocale>\n#include <locale>\n#include <exception>\n#include <stdexcept>\n\n#include \"interp.hxx\"\n#include \"common.hxx\"\n\nusing namespace std;\nusing namespace tglng;\n\nint main(int argc, const char*const* argv) {\n wstring out;\n Interpreter interp;\n\n setlocale(LC_ALL, \"\");\n setlocale(LC_NUMERIC, \"C\");\n try {\n locale::global(locale(\"\"));\n } catch (runtime_error& re) {\n \/*\n When GNU libstdc++ is used on top of a non-GNU libc, no locales other\n than \"C\" are supported. On some versions of libstdc++, trying to set the\n default locale throws a runtime_error().\n\n See:\n http:\/\/gcc.gnu.org\/ml\/libstdc++\/2003-02\/msg00345.html\n\n Unfortunately, no --use-my-systems-libc-dammit option seems to exist yet,\n especially not one usable at compilation time.\n\n If we catch the runtime_error, just ignore it and carry on --- there's\n nothing else we can do.\n *\/\n }\n\n \/\/Try to read from standard configuration file.\n \/\/TODO: Change this to something more sensible\n {\n wifstream in(\"rc.default\");\n if (!interp.exec(out, in, Interpreter::ParseModeCommand)) {\n wcerr << L\"Error reading user library.\" << endl;\n return EXIT_EXEC_ERROR_IN_USER_LIBRARY;\n }\n }\n\n if (interp.exec(out, wcin, Interpreter::ParseModeLiteral)) {\n wcout << out;\n Interpreter::freeGlobalBindings();\n return 0;\n } else {\n wcerr << L\"Failed.\" << endl;\n return EXIT_EXEC_ERROR_IN_INPUT;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gst\/gst.h>\n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include <jsonrpc\/JsonSerializer.hpp>\n#include <KurentoException.hpp>\n#include <gst\/gst.h>\n#include <boost\/uuid\/uuid.hpp>\n#include <boost\/uuid\/uuid_generators.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)\n{\n id = createId();\n this->config = config;\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent)\n{\n this->parent = parent;\n id = createId();\n this->config = config;\n}\n\nstd::shared_ptr<MediaPipeline>\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::stringstream ss;\n boost::uuids::uuid uuid = boost::uuids::random_generator() ();\n\n ss << uuid;\n\n if (parent) {\n std::shared_ptr<MediaPipelineImpl> pipeline;\n\n pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n ss.str();\n } else {\n return ss.str();\n }\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n<commit_msg>MediaObjectImpl: Improve UUID generation<commit_after>#include <gst\/gst.h>\n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include <jsonrpc\/JsonSerializer.hpp>\n#include <KurentoException.hpp>\n#include <gst\/gst.h>\n#include <boost\/uuid\/uuid.hpp>\n#include <boost\/uuid\/uuid_generators.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <chrono>\n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nclass RandomGeneratorBase\n{\nprotected:\n RandomGeneratorBase () {\n std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();\n std::chrono::duration<time_t> time = std::chrono::duration_cast<std::chrono::duration<time_t>> (now.time_since_epoch () );\n\n ran.seed (time.count() );\n }\n\n boost::mt19937 ran;\n};\n\nclass RandomGenerator : RandomGeneratorBase\n{\n boost::mt19937 ran;\n boost::uuids::basic_random_generator<boost::mt19937> gen;\n\npublic:\n RandomGenerator () : RandomGeneratorBase(), gen (&ran) {\n }\n\n std::string getUUID () {\n std::stringstream ss;\n boost::uuids::uuid uuid = gen ();\n\n ss << uuid;\n return ss.str();\n }\n};\n\nstatic RandomGenerator gen;\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)\n{\n id = createId();\n this->config = config;\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent)\n{\n this->parent = parent;\n id = createId();\n this->config = config;\n}\n\nstd::shared_ptr<MediaPipeline>\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::string uuid = gen.getUUID ();\n\n if (parent) {\n std::shared_ptr<MediaPipelineImpl> pipeline;\n\n pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n uuid;\n } else {\n return uuid;\n }\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"<commit_before>#include <QGuiApplication>\n#include <QQmlApplicationEngine>\n\nint main(int argc, char *argv[])\n{\n QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\n QGuiApplication app(argc, argv);\n\n QQmlApplicationEngine engine;\n engine.load(QUrl(QStringLiteral(\"qrc:\/main.qml\")));\n if (engine.rootObjects().isEmpty())\n return -1;\n\n return app.exec();\n}\n<commit_msg>qt: qml: fix warning message<commit_after>#include <QGuiApplication>\n#include <QQmlApplicationEngine>\n#include <QtWebView>\n\nint main(int argc, char *argv[])\n{\n QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\n QGuiApplication app(argc, argv);\n\n QtWebView::initialize();\n\n QQmlApplicationEngine engine;\n engine.load(QUrl(QStringLiteral(\"qrc:\/main.qml\")));\n if (engine.rootObjects().isEmpty())\n return -1;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nModule: FGMatrix.cpp\nAuthor: Originally by Tony Peden [formatted here (and broken??) by JSB]\nDate started: 1998\nPurpose: FGMatrix class\nCalled by: Various\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\n\nHISTORY\n--------------------------------------------------------------------------------\n??\/??\/?? TP Created\n03\/16\/2000 JSB Added exception throwing\n\n********************************************************************************\nINCLUDES\n*******************************************************************************\/\n\n#include \"FGMatrix.h\"\n\n\/*******************************************************************************\n************************************ CODE **************************************\n*******************************************************************************\/\n\ndouble** FGalloc(int rows, int cols)\n{\n double **A;\n\n A = new double *[rows+1];\n if (!A) return NULL;\n\n for (int i=0; i <= rows; i++){\n A[i] = new double [cols+1];\n if (!A[i]) return NULL;\n }\n return A;\n}\n\n\/******************************************************************************\/\n\nvoid dealloc(double **A, int rows)\n{\n for(int i=0;i<= rows;i++) delete[] A[i];\n delete[] A;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c)\n{\n data = FGalloc(rows,cols);\n InitMatrix();\n rowCtr = colCtr = 1;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::FGMatrix(const FGMatrix& M)\n{\n data = NULL;\n rowCtr = colCtr = 1;\n *this = M;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::~FGMatrix(void)\n{\n dealloc(data,rows);\n rowCtr = colCtr = 1;\n rows = cols = 0;\n}\n\n\/******************************************************************************\/\n\nostream& operator<<(ostream& os, const FGMatrix& M)\n{\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n if (i == M.Rows() && j == M.Cols())\n os << M.data[i][j];\n else\n os << M.data[i][j] << \", \";\n }\n }\n return os;\n}\n\n\/******************************************************************************\/\n\nFGMatrix& FGMatrix::operator<<(const float ff)\n{\n data[rowCtr][colCtr] = ff;\n if (++colCtr > Cols()) {\n colCtr = 1;\n if (++rowCtr > Rows())\n rowCtr = 1;\n }\n return *this;\n}\n\n\/******************************************************************************\/\n\nistream& operator>>(istream& is, FGMatrix& M)\n{\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n is >> M.data[i][j];\n }\n }\n return is;\n}\n\n\/******************************************************************************\/\n\nFGMatrix& FGMatrix::operator=(const FGMatrix& M)\n{\n if (&M != this) {\n if (data != NULL) dealloc(data,rows);\n\n width = M.width;\n prec = M.prec;\n delim = M.delim;\n origin = M.origin;\n rows = M.rows;\n cols = M.cols;\n\n data = FGalloc(rows,cols);\n for (unsigned int i=0; i<=rows; i++) {\n for (unsigned int j=0; j<=cols; j++) {\n data[i][j] = M.data[i][j];\n }\n }\n }\n return *this;\n}\n\n\/******************************************************************************\/\n\nunsigned int FGMatrix::Rows(void) const\n{\n return rows;\n}\n\n\/******************************************************************************\/\n\nunsigned int FGMatrix::Cols(void) const\n{\n return cols;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::SetOParams(char delim,int width,int prec,int origin)\n{\n FGMatrix::delim = delim;\n FGMatrix::width = width;\n FGMatrix::prec = prec;\n FGMatrix::origin = origin;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::InitMatrix(double value)\n{\n if (data) {\n for (unsigned int i=0;i<=rows;i++) {\n for (unsigned int j=0;j<=cols;j++) {\n operator()(i,j) = value;\n }\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::InitMatrix(void)\n{\n this->InitMatrix(0);\n}\n\n\/\/ *****************************************************************************\n\/\/ binary operators ************************************************************\n\/\/ *****************************************************************************\n\nFGMatrix FGMatrix::operator-(const FGMatrix& M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator -\";\n throw mE;\n }\n\n FGMatrix Diff(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Diff(i,j) = data[i][j] - M(i,j);\n }\n }\n return Diff;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator-=(const FGMatrix &M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator -=\";\n throw mE;\n }\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j] -= M(i,j);\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator+(const FGMatrix& M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator +\";\n throw mE;\n }\n\n FGMatrix Sum(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Sum(i,j) = data[i][j] + M(i,j);\n }\n }\n return Sum;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator+=(const FGMatrix &M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator +=\";\n throw mE;\n }\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j]+=M(i,j);\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix operator*(double scalar, FGMatrix &M)\n{\n FGMatrix Product(M.Rows(), M.Cols());\n\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n Product(i,j) = scalar*M(i,j);\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator*=(const double scalar)\n{\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j] *= scalar;\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator*(const FGMatrix& M)\n{\n if (Cols() != M.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator *\";\n throw mE;\n }\n\n FGMatrix Product(Rows(), M.Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n Product(i,j) = 0;\n for (unsigned int k=1; k<=Cols(); k++) {\n Product(i,j) += data[i][k] * M(k,j);\n }\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator*=(const FGMatrix& M)\n{\n if (Cols() != M.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator *=\";\n throw mE;\n }\n\n double **prod;\n\n prod = FGalloc(Rows(), M.Cols());\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n prod[i][j] = 0;\n for (unsigned int k=1; k<=Cols(); k++) {\n prod[i][j] += data[i][k] * M(k,j);\n }\n }\n }\n dealloc(data, Rows());\n data = prod;\n cols = M.cols;\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator\/(const double scalar)\n{\n FGMatrix Quot(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Quot(i,j) = data[i][j]\/scalar;\n }\n }\n return Quot;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator\/=(const double scalar)\n{\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j]\/=scalar;\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::T(void)\n{\n if (rows==cols)\n TransposeSquare();\n else\n TransposeNonSquare();\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGMatrix::operator*(const FGColumnVector& Col)\n{\n FGColumnVector Product(Col.Rows());\n\n if (Cols() != Col.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n for (unsigned int i=1;i<=Rows();i++) {\n Product(i) = 0.00;\n for (unsigned int j=1;j<=Cols();j++) {\n Product(i) += Col(j)*data[i][j];\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::TransposeSquare(void)\n{\n for (unsigned int i=1; i<=rows; i++) {\n for (unsigned int j=i+1; j<=cols; j++) {\n double tmp = data[i][j];\n data[i][j] = data[j][i];\n data[j][i] = tmp;\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::TransposeNonSquare(void)\n{\n double **tran;\n\n tran = FGalloc(rows,cols);\n\n for (unsigned int i=1; i<=rows; i++) {\n for (unsigned int j=1; j<=cols; j++) {\n tran[j][i] = data[i][j];\n }\n }\n\n dealloc(data,rows);\n\n data = tran;\n unsigned int m = rows;\n rows = cols;\n cols = m;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector::FGColumnVector(void):FGMatrix(3,1) { }\nFGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { }\nFGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { }\nFGColumnVector::~FGColumnVector() { }\n\n\/******************************************************************************\/\n\ndouble& FGColumnVector::operator()(int m) const\n{\n return FGMatrix::operator()(m,1);\n}\n\n\/******************************************************************************\/\n\nFGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col)\n{\n FGColumnVector Product(Col.Rows());\n\n if (Mat.Cols() != Col.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n for (unsigned int i=1;i<=Mat.Rows();i++) {\n Product(i) = 0.00;\n for (unsigned int j=1;j<=Mat.Cols();j++) {\n Product(i) += Col(j)*Mat(i,j);\n }\n }\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator+(const FGColumnVector& C)\n{\n if (Rows() != C.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n FGColumnVector Sum(C.Rows());\n\n for (unsigned int i=1; i<=C.Rows(); i++) {\n Sum(i) = C(i) + data[i][1];\n }\n\n return Sum;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator*(const double scalar)\n{\n FGColumnVector Product(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1];\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator-(const FGColumnVector& V)\n{\n if ((Rows() != V.Rows()) || (Cols() != V.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator -\";\n throw mE;\n }\n\n FGColumnVector Diff(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n Diff(i) = data[i][1] - V(i);\n }\n\n return Diff;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator\/(const double scalar)\n{\n FGColumnVector Quotient(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] \/ scalar;\n\n return Quotient;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector operator*(const double scalar, const FGColumnVector& C)\n{\n FGColumnVector Product(C.Rows());\n\n for (unsigned int i=1; i<=C.Rows(); i++) {\n Product(i) = scalar * C(i);\n }\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nfloat FGColumnVector::Magnitude(void)\n{\n double num=0.0;\n\n if ((data[1][1] == 0.00) &&\n (data[2][1] == 0.00) &&\n (data[3][1] == 0.00))\n {\n return 0.00;\n } else {\n for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1];\n return sqrt(num);\n }\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::Normalize(void)\n{\n double Mag = Magnitude();\n\n for (unsigned int i=1; i<=Rows(); i++)\n for (unsigned int j=1; j<=Cols(); j++)\n data[i][j] = data[i][j]\/Mag;\n\n return *this;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator*(const FGColumnVector& V)\n{\n if (Rows() != 3 || V.Rows() != 3) {\n MatrixException mE;\n mE.Message = \"Invalid row count in vector cross product function\";\n throw mE;\n }\n\n FGColumnVector Product(3);\n\n Product(1) = data[2][1] * V(3) - data[3][1] * V(2);\n Product(2) = data[3][1] * V(1) - data[1][1] * V(3);\n Product(3) = data[1][1] * V(2) - data[2][1] * V(1);\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V)\n{\n if (Rows() != 3 || V.Rows() != 3) {\n MatrixException mE;\n mE.Message = \"Invalid row count in vector cross product function\";\n throw mE;\n }\n\n FGColumnVector Product(3);\n\n Product(1) = data[1][1] * V(1);\n Product(2) = data[2][1] * V(2);\n Product(3) = data[3][1] * V(3);\n\n return Product;\n}\n\n\/******************************************************************************\/\n<commit_msg>Added check for 0 magnitude in Normalize()<commit_after>\/*******************************************************************************\n\nModule: FGMatrix.cpp\nAuthor: Originally by Tony Peden [formatted here (and broken??) by JSB]\nDate started: 1998\nPurpose: FGMatrix class\nCalled by: Various\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\n\nHISTORY\n--------------------------------------------------------------------------------\n??\/??\/?? TP Created\n03\/16\/2000 JSB Added exception throwing\n\n********************************************************************************\nINCLUDES\n*******************************************************************************\/\n\n#include \"FGMatrix.h\"\n\n\/*******************************************************************************\n************************************ CODE **************************************\n*******************************************************************************\/\n\ndouble** FGalloc(int rows, int cols)\n{\n double **A;\n\n A = new double *[rows+1];\n if (!A) return NULL;\n\n for (int i=0; i <= rows; i++){\n A[i] = new double [cols+1];\n if (!A[i]) return NULL;\n }\n return A;\n}\n\n\/******************************************************************************\/\n\nvoid dealloc(double **A, int rows)\n{\n for(int i=0;i<= rows;i++) delete[] A[i];\n delete[] A;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c)\n{\n data = FGalloc(rows,cols);\n InitMatrix();\n rowCtr = colCtr = 1;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::FGMatrix(const FGMatrix& M)\n{\n data = NULL;\n rowCtr = colCtr = 1;\n *this = M;\n}\n\n\/******************************************************************************\/\n\nFGMatrix::~FGMatrix(void)\n{\n dealloc(data,rows);\n rowCtr = colCtr = 1;\n rows = cols = 0;\n}\n\n\/******************************************************************************\/\n\nostream& operator<<(ostream& os, const FGMatrix& M)\n{\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n if (i == M.Rows() && j == M.Cols())\n os << M.data[i][j];\n else\n os << M.data[i][j] << \", \";\n }\n }\n return os;\n}\n\n\/******************************************************************************\/\n\nFGMatrix& FGMatrix::operator<<(const float ff)\n{\n data[rowCtr][colCtr] = ff;\n if (++colCtr > Cols()) {\n colCtr = 1;\n if (++rowCtr > Rows())\n rowCtr = 1;\n }\n return *this;\n}\n\n\/******************************************************************************\/\n\nistream& operator>>(istream& is, FGMatrix& M)\n{\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n is >> M.data[i][j];\n }\n }\n return is;\n}\n\n\/******************************************************************************\/\n\nFGMatrix& FGMatrix::operator=(const FGMatrix& M)\n{\n if (&M != this) {\n if (data != NULL) dealloc(data,rows);\n\n width = M.width;\n prec = M.prec;\n delim = M.delim;\n origin = M.origin;\n rows = M.rows;\n cols = M.cols;\n\n data = FGalloc(rows,cols);\n for (unsigned int i=0; i<=rows; i++) {\n for (unsigned int j=0; j<=cols; j++) {\n data[i][j] = M.data[i][j];\n }\n }\n }\n return *this;\n}\n\n\/******************************************************************************\/\n\nunsigned int FGMatrix::Rows(void) const\n{\n return rows;\n}\n\n\/******************************************************************************\/\n\nunsigned int FGMatrix::Cols(void) const\n{\n return cols;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::SetOParams(char delim,int width,int prec,int origin)\n{\n FGMatrix::delim = delim;\n FGMatrix::width = width;\n FGMatrix::prec = prec;\n FGMatrix::origin = origin;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::InitMatrix(double value)\n{\n if (data) {\n for (unsigned int i=0;i<=rows;i++) {\n for (unsigned int j=0;j<=cols;j++) {\n operator()(i,j) = value;\n }\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::InitMatrix(void)\n{\n this->InitMatrix(0);\n}\n\n\/\/ *****************************************************************************\n\/\/ binary operators ************************************************************\n\/\/ *****************************************************************************\n\nFGMatrix FGMatrix::operator-(const FGMatrix& M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator -\";\n throw mE;\n }\n\n FGMatrix Diff(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Diff(i,j) = data[i][j] - M(i,j);\n }\n }\n return Diff;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator-=(const FGMatrix &M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator -=\";\n throw mE;\n }\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j] -= M(i,j);\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator+(const FGMatrix& M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator +\";\n throw mE;\n }\n\n FGMatrix Sum(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Sum(i,j) = data[i][j] + M(i,j);\n }\n }\n return Sum;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator+=(const FGMatrix &M)\n{\n if ((Rows() != M.Rows()) || (Cols() != M.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator +=\";\n throw mE;\n }\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j]+=M(i,j);\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix operator*(double scalar, FGMatrix &M)\n{\n FGMatrix Product(M.Rows(), M.Cols());\n\n for (unsigned int i=1; i<=M.Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n Product(i,j) = scalar*M(i,j);\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator*=(const double scalar)\n{\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j] *= scalar;\n }\n }\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator*(const FGMatrix& M)\n{\n if (Cols() != M.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator *\";\n throw mE;\n }\n\n FGMatrix Product(Rows(), M.Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n Product(i,j) = 0;\n for (unsigned int k=1; k<=Cols(); k++) {\n Product(i,j) += data[i][k] * M(k,j);\n }\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator*=(const FGMatrix& M)\n{\n if (Cols() != M.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Matrix operator *=\";\n throw mE;\n }\n\n double **prod;\n\n prod = FGalloc(Rows(), M.Cols());\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=M.Cols(); j++) {\n prod[i][j] = 0;\n for (unsigned int k=1; k<=Cols(); k++) {\n prod[i][j] += data[i][k] * M(k,j);\n }\n }\n }\n dealloc(data, Rows());\n data = prod;\n cols = M.cols;\n}\n\n\/******************************************************************************\/\n\nFGMatrix FGMatrix::operator\/(const double scalar)\n{\n FGMatrix Quot(Rows(), Cols());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n Quot(i,j) = data[i][j]\/scalar;\n }\n }\n return Quot;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::operator\/=(const double scalar)\n{\n for (unsigned int i=1; i<=Rows(); i++) {\n for (unsigned int j=1; j<=Cols(); j++) {\n data[i][j]\/=scalar;\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::T(void)\n{\n if (rows==cols)\n TransposeSquare();\n else\n TransposeNonSquare();\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGMatrix::operator*(const FGColumnVector& Col)\n{\n FGColumnVector Product(Col.Rows());\n\n if (Cols() != Col.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n for (unsigned int i=1;i<=Rows();i++) {\n Product(i) = 0.00;\n for (unsigned int j=1;j<=Cols();j++) {\n Product(i) += Col(j)*data[i][j];\n }\n }\n return Product;\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::TransposeSquare(void)\n{\n for (unsigned int i=1; i<=rows; i++) {\n for (unsigned int j=i+1; j<=cols; j++) {\n double tmp = data[i][j];\n data[i][j] = data[j][i];\n data[j][i] = tmp;\n }\n }\n}\n\n\/******************************************************************************\/\n\nvoid FGMatrix::TransposeNonSquare(void)\n{\n double **tran;\n\n tran = FGalloc(rows,cols);\n\n for (unsigned int i=1; i<=rows; i++) {\n for (unsigned int j=1; j<=cols; j++) {\n tran[j][i] = data[i][j];\n }\n }\n\n dealloc(data,rows);\n\n data = tran;\n unsigned int m = rows;\n rows = cols;\n cols = m;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector::FGColumnVector(void):FGMatrix(3,1) { }\nFGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { }\nFGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { }\nFGColumnVector::~FGColumnVector() { }\n\n\/******************************************************************************\/\n\ndouble& FGColumnVector::operator()(int m) const\n{\n return FGMatrix::operator()(m,1);\n}\n\n\/******************************************************************************\/\n\nFGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col)\n{\n FGColumnVector Product(Col.Rows());\n\n if (Mat.Cols() != Col.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n for (unsigned int i=1;i<=Mat.Rows();i++) {\n Product(i) = 0.00;\n for (unsigned int j=1;j<=Mat.Cols();j++) {\n Product(i) += Col(j)*Mat(i,j);\n }\n }\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator+(const FGColumnVector& C)\n{\n if (Rows() != C.Rows()) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator *\";\n throw mE;\n }\n\n FGColumnVector Sum(C.Rows());\n\n for (unsigned int i=1; i<=C.Rows(); i++) {\n Sum(i) = C(i) + data[i][1];\n }\n\n return Sum;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator*(const double scalar)\n{\n FGColumnVector Product(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1];\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator-(const FGColumnVector& V)\n{\n if ((Rows() != V.Rows()) || (Cols() != V.Cols())) {\n MatrixException mE;\n mE.Message = \"Invalid row\/column match in Column Vector operator -\";\n throw mE;\n }\n\n FGColumnVector Diff(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) {\n Diff(i) = data[i][1] - V(i);\n }\n\n return Diff;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator\/(const double scalar)\n{\n FGColumnVector Quotient(Rows());\n\n for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] \/ scalar;\n\n return Quotient;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector operator*(const double scalar, const FGColumnVector& C)\n{\n FGColumnVector Product(C.Rows());\n\n for (unsigned int i=1; i<=C.Rows(); i++) {\n Product(i) = scalar * C(i);\n }\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nfloat FGColumnVector::Magnitude(void)\n{\n double num=0.0;\n\n if ((data[1][1] == 0.00) &&\n (data[2][1] == 0.00) &&\n (data[3][1] == 0.00))\n {\n return 0.00;\n } else {\n for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1];\n return sqrt(num);\n }\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::Normalize(void)\n{\n double Mag = Magnitude();\n\n if(Mag != 0 {\n for (unsigned int i=1; i<=Rows(); i++)\n for (unsigned int j=1; j<=Cols(); j++)\n data[i][j] = data[i][j]\/Mag;\n } \n\n return *this;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::operator*(const FGColumnVector& V)\n{\n if (Rows() != 3 || V.Rows() != 3) {\n MatrixException mE;\n mE.Message = \"Invalid row count in vector cross product function\";\n throw mE;\n }\n\n FGColumnVector Product(3);\n\n Product(1) = data[2][1] * V(3) - data[3][1] * V(2);\n Product(2) = data[3][1] * V(1) - data[1][1] * V(3);\n Product(3) = data[1][1] * V(2) - data[2][1] * V(1);\n\n return Product;\n}\n\n\/******************************************************************************\/\n\nFGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V)\n{\n if (Rows() != 3 || V.Rows() != 3) {\n MatrixException mE;\n mE.Message = \"Invalid row count in vector cross product function\";\n throw mE;\n }\n\n FGColumnVector Product(3);\n\n Product(1) = data[1][1] * V(1);\n Product(2) = data[2][1] * V(2);\n Product(3) = data[3][1] * V(3);\n\n return Product;\n}\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011, The University of Oxford\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. Neither the name of the University of Oxford nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"sky\/oskar_SkyModel.h\"\n#include \"sky\/oskar_load_sources.h\"\n#include \"sky\/oskar_date_time_to_mjd.h\"\n\n#include \"station\/oskar_StationModel.h\"\n\n#include \"interferometry\/oskar_TelescopeModel.h\"\n#include \"interferometry\/oskar_interferometer1_scalar.h\"\n#include \"interferometry\/oskar_VisData.h\"\n\n#include \"apps\/lib\/oskar_load_telescope.h\"\n#include \"apps\/lib\/oskar_load_stations.h\"\n#include \"apps\/lib\/oskar_Settings.h\"\n\n#ifndef OSKAR_NO_MS\n#include \"apps\/lib\/oskar_write_ms.h\"\n#endif\n\n#include \"utility\/oskar_cuda_device_info.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <math.h>\n\n#include <QtCore\/QTime>\n\nusing namespace std;\n\nint sim1_d(const oskar_Settings& settings);\nint sim1_f(const oskar_Settings& settings);\n\n\nint main(int argc, char** argv)\n{\n \/\/ $> oskar_sim1_scalar settings_file.txt\n if (argc != 2)\n {\n fprintf(stderr, \"ERROR: Missing command line arguments.\\n\");\n fprintf(stderr, \"Usage: $ oskar_sim1_scalar [settings file]\\n\");\n return EXIT_FAILURE;\n }\n\n oskar_Settings settings;\n if (!settings.load(QString(argv[1]))) return EXIT_FAILURE;\n settings.print();\n\n QTime timer;\n timer.start();\n\n \/\/ Double precision.\n if (settings.double_precision())\n {\n sim1_d(settings);\n }\n\n \/\/ Single precision.\n else\n {\n sim1_f(settings);\n }\n\n printf(\"= Completed simulation after %f seconds.\\n\", timer.elapsed() \/ 1.0e3);\n\n return EXIT_SUCCESS;\n}\n\n\n\nint sim1_d(const oskar_Settings& settings)\n{\n \/\/ ============== Load input data =========================================\n oskar_SkyModelGlobal_d sky;\n oskar_load_sources_d(settings.sky_file().toLatin1().data(), &sky);\n oskar_TelescopeModel_d telescope;\n oskar_load_telescope_d(settings.telescope_file().toLatin1().data(),\n settings.longitude_rad(), settings.latitude_rad(), &telescope);\n oskar_StationModel_d* stations;\n const char* station_dir = settings.station_dir().toLatin1().data();\n unsigned num_stations = oskar_load_stations_d(station_dir, &stations,\n &telescope.identical_stations);\n if (num_stations != telescope.num_antennas)\n {\n fprintf(stderr, \"ERROR: Error loading telescope geometry.\\n\");\n return EXIT_FAILURE;\n }\n\n \/\/ ============== Simulation loop =========================================\n int error_code = 0;\n for (unsigned i = 0; i < settings.obs().num_channels(); ++i)\n {\n unsigned year = settings.obs().start_time_utc_year();\n unsigned month = settings.obs().start_time_utc_month();\n unsigned day = settings.obs().start_time_utc_day();\n unsigned hour = settings.obs().start_time_utc_hour();\n unsigned minute = settings.obs().start_time_utc_minute();\n double second = settings.obs().start_time_utc_second();\n double day_fraction = (hour + minute\/60 + second\/3600) \/ 24.0;\n double start_time_mjd_utc = oskar_date_time_to_mjd_d(\n year, month, day, day_fraction);\n printf(\"- %i\/%i\/%i %i:%i:%f -> mjd %f\\n\", day, month, year, hour, minute,\n second, start_time_mjd_utc);\n\n double frequency = settings.obs().frequency(i);\n printf(\"- Frequency: %e\\n\", frequency);\n\n \/\/ Allocate memory for frequency scaled sky model.\n oskar_SkyModelGlobal_d sky_temp;\n sky_temp.num_sources = sky.num_sources;\n sky_temp.Dec = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.RA = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.I = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.Q = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.U = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.V = (double*) malloc(sky.num_sources * sizeof(double));\n memcpy(sky_temp.Dec, sky.Dec, sky.num_sources * sizeof(double));\n memcpy(sky_temp.RA, sky.RA, sky.num_sources * sizeof(double));\n memcpy(sky_temp.I, sky.I, sky.num_sources * sizeof(double));\n for (int s = 0; s < sky.num_sources; ++s)\n {\n\/\/ sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);\n sky_temp.I[s] *= pow(frequency \/ settings.obs().start_frequency(), -0.7);\n }\n\n \/\/ Allocate visibility data.\n oskar_VisData_d vis;\n int num_baselines = num_stations * (num_stations-1) \/ 2;\n oskar_allocate_vis_data_d(num_baselines * settings.obs().num_vis_dumps(), &vis);\n\n error_code = oskar_interferometer1_scalar_d(telescope, stations, sky,\n settings.obs().ra0_rad(), settings.obs().dec0_rad(),\n settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),\n settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),\n settings.obs().num_fringe_ave(), frequency,\n settings.obs().channel_bandwidth(),\n settings.disable_station_beam(), &vis);\n\n printf(\"= Number of visibility points generated: %i\\n\", vis.num_samples);\n\n \/\/ Write visibility binary file.\n if (!settings.obs().oskar_vis_filename().isEmpty())\n {\n QString vis_file = settings.obs().oskar_vis_filename() + \"_channel_\" + QString::number(i) + \".dat\";\n printf(\"= Writing OSKAR visibility data file: %s\\n\",\n vis_file.toLatin1().data());\n oskar_write_vis_data_d(vis_file.toLatin1().data(), &vis);\n }\n\n \/\/ Write MS.\n#ifndef OSKAR_NO_MS\n if (!settings.obs().ms_filename().isEmpty())\n {\n QString ms_file = settings.obs().ms_filename() + \"_channel_\" + QString::number(i) + \".ms\";\n printf(\"= Writing Measurement Set: %s\\n\", ms_file.toLatin1().data());\n oskar_write_ms_d(ms_file.toLatin1().data(), &settings, &vis, true);\n }\n#endif\n\n free(sky_temp.RA);\n free(sky_temp.Dec);\n free(sky_temp.I);\n free(sky_temp.Q);\n free(sky_temp.U);\n free(sky_temp.V);\n oskar_free_vis_data_d(&vis);\n }\n\n \/\/ ============== Cleanup =================================================\n free(sky.RA);\n free(sky.Dec);\n free(sky.I);\n free(sky.Q);\n free(sky.U);\n free(sky.V);\n free(telescope.antenna_x);\n free(telescope.antenna_y);\n free(telescope.antenna_z);\n for (unsigned i = 0; i < num_stations; ++i)\n {\n free(stations[i].antenna_x);\n free(stations[i].antenna_y);\n }\n free(stations);\n\n return EXIT_SUCCESS;\n}\n\n\n\n\nint sim1_f(const oskar_Settings& settings)\n{\n \/\/ ============== Load input data =========================================\n oskar_SkyModelGlobal_f sky;\n oskar_load_sources_f(settings.sky_file().toLatin1().data(), &sky);\n oskar_TelescopeModel_f telescope;\n oskar_load_telescope_f(settings.telescope_file().toLatin1().data(),\n settings.longitude_rad(), settings.latitude_rad(), &telescope);\n oskar_StationModel_f* stations;\n const char* station_dir = settings.station_dir().toLatin1().data();\n unsigned num_stations = oskar_load_stations_f(station_dir, &stations,\n &telescope.identical_stations);\n if (num_stations != telescope.num_antennas)\n {\n fprintf(stderr, \"ERROR: Error loading telescope geometry.\\n\");\n return EXIT_FAILURE;\n }\n\n \/\/ ============== Simulation loop =========================================\n int error_code = 0;\n for (unsigned i = 0; i < settings.obs().num_channels(); ++i)\n {\n float frequency = settings.obs().frequency(i);\n printf(\"- Frequency: %e\\n\", frequency);\n\n \/\/ Allocate memory for frequency scaled sky model.\n oskar_SkyModelGlobal_f sky_temp;\n sky_temp.num_sources = sky.num_sources;\n sky_temp.Dec = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.RA = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.I = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.Q = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.U = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.V = (float*) malloc(sky.num_sources * sizeof(float));\n memcpy(sky_temp.Dec, sky.Dec, sky.num_sources * sizeof(float));\n memcpy(sky_temp.RA, sky.RA, sky.num_sources * sizeof(float));\n memcpy(sky_temp.I, sky.I, sky.num_sources * sizeof(float));\n for (int s = 0; s < sky.num_sources; ++s)\n {\n\/\/ sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);\n sky_temp.I[s] *= pow(frequency \/ settings.obs().start_frequency(), -0.7);\n }\n\n \/\/ Allocate visibility data.\n oskar_VisData_f vis;\n int num_baselines = num_stations * (num_stations-1) \/ 2;\n oskar_allocate_vis_data_f(num_baselines * settings.obs().num_vis_dumps(), &vis);\n\n error_code = oskar_interferometer1_scalar_f(telescope, stations, sky,\n settings.obs().ra0_rad(), settings.obs().dec0_rad(),\n settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),\n settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),\n settings.obs().num_fringe_ave(), frequency, settings.obs().channel_bandwidth(),\n settings.disable_station_beam(), &vis);\n\n printf(\"= Number of visibility points generated: %i\\n\", vis.num_samples);\n\n \/\/ Write visibility binary file.\n if (!settings.obs().oskar_vis_filename().isEmpty())\n {\n QString vis_file = settings.obs().oskar_vis_filename() + \"_channel_\" + QString::number(i) + \".dat\";\n printf(\"= Writing OSKAR visibility data file: %s\\n\",\n vis_file.toLatin1().data());\n oskar_write_vis_data_f(vis_file.toLatin1().data(), &vis);\n }\n\n \/\/ Write MS.\n#ifndef OSKAR_NO_MS\n if (!settings.obs().ms_filename().isEmpty())\n {\n QString ms_file = settings.obs().ms_filename() + \"_channel_\" + QString::number(i) + \".ms\";\n printf(\"= Writing Measurement Set: %s\\n\", ms_file.toLatin1().data());\n oskar_write_ms_f(ms_file.toLatin1().data(), &settings, &vis, true);\n }\n#endif\n\n free(sky_temp.RA);\n free(sky_temp.Dec);\n free(sky_temp.I);\n free(sky_temp.Q);\n free(sky_temp.U);\n free(sky_temp.V);\n oskar_free_vis_data_f(&vis);\n }\n\n \/\/ ============== Cleanup =================================================\n free(sky.RA);\n free(sky.Dec);\n free(sky.I);\n free(sky.Q);\n free(sky.U);\n free(sky.V);\n free(telescope.antenna_x);\n free(telescope.antenna_y);\n free(telescope.antenna_z);\n for (unsigned i = 0; i < num_stations; ++i)\n {\n free(stations[i].antenna_x);\n free(stations[i].antenna_y);\n }\n free(stations);\n\n return EXIT_SUCCESS;\n}\n\n<commit_msg>fixed time for float version of sim 1 script<commit_after>\/*\n * Copyright (c) 2011, The University of Oxford\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * 3. Neither the name of the University of Oxford nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"sky\/oskar_SkyModel.h\"\n#include \"sky\/oskar_load_sources.h\"\n#include \"sky\/oskar_date_time_to_mjd.h\"\n\n#include \"station\/oskar_StationModel.h\"\n\n#include \"interferometry\/oskar_TelescopeModel.h\"\n#include \"interferometry\/oskar_interferometer1_scalar.h\"\n#include \"interferometry\/oskar_VisData.h\"\n\n#include \"apps\/lib\/oskar_load_telescope.h\"\n#include \"apps\/lib\/oskar_load_stations.h\"\n#include \"apps\/lib\/oskar_Settings.h\"\n\n#ifndef OSKAR_NO_MS\n#include \"apps\/lib\/oskar_write_ms.h\"\n#endif\n\n#include \"utility\/oskar_cuda_device_info.h\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <math.h>\n\n#include <QtCore\/QTime>\n\nusing namespace std;\n\nint sim1_d(const oskar_Settings& settings);\nint sim1_f(const oskar_Settings& settings);\n\n\nint main(int argc, char** argv)\n{\n \/\/ $> oskar_sim1_scalar settings_file.txt\n if (argc != 2)\n {\n fprintf(stderr, \"ERROR: Missing command line arguments.\\n\");\n fprintf(stderr, \"Usage: $ oskar_sim1_scalar [settings file]\\n\");\n return EXIT_FAILURE;\n }\n\n oskar_Settings settings;\n if (!settings.load(QString(argv[1]))) return EXIT_FAILURE;\n settings.print();\n\n QTime timer;\n timer.start();\n\n \/\/ Double precision.\n if (settings.double_precision())\n {\n sim1_d(settings);\n }\n\n \/\/ Single precision.\n else\n {\n sim1_f(settings);\n }\n\n printf(\"= Completed simulation after %f seconds.\\n\", timer.elapsed() \/ 1.0e3);\n\n return EXIT_SUCCESS;\n}\n\n\n\nint sim1_d(const oskar_Settings& settings)\n{\n \/\/ ============== Load input data =========================================\n oskar_SkyModelGlobal_d sky;\n oskar_load_sources_d(settings.sky_file().toLatin1().data(), &sky);\n oskar_TelescopeModel_d telescope;\n oskar_load_telescope_d(settings.telescope_file().toLatin1().data(),\n settings.longitude_rad(), settings.latitude_rad(), &telescope);\n oskar_StationModel_d* stations;\n const char* station_dir = settings.station_dir().toLatin1().data();\n unsigned num_stations = oskar_load_stations_d(station_dir, &stations,\n &telescope.identical_stations);\n if (num_stations != telescope.num_antennas)\n {\n fprintf(stderr, \"ERROR: Error loading telescope geometry.\\n\");\n return EXIT_FAILURE;\n }\n\n \/\/ ============== Simulation loop =========================================\n int error_code = 0;\n for (unsigned i = 0; i < settings.obs().num_channels(); ++i)\n {\n unsigned year = settings.obs().start_time_utc_year();\n unsigned month = settings.obs().start_time_utc_month();\n unsigned day = settings.obs().start_time_utc_day();\n unsigned hour = settings.obs().start_time_utc_hour();\n unsigned minute = settings.obs().start_time_utc_minute();\n double second = settings.obs().start_time_utc_second();\n double day_fraction = (hour + minute\/60 + second\/3600) \/ 24.0;\n double start_time_mjd_utc = oskar_date_time_to_mjd_d(\n year, month, day, day_fraction);\n printf(\"- %i\/%i\/%i %i:%i:%f -> mjd %f\\n\", day, month, year, hour, minute,\n second, start_time_mjd_utc);\n\n double frequency = settings.obs().frequency(i);\n printf(\"- Frequency: %e\\n\", frequency);\n\n \/\/ Allocate memory for frequency scaled sky model.\n oskar_SkyModelGlobal_d sky_temp;\n sky_temp.num_sources = sky.num_sources;\n sky_temp.Dec = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.RA = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.I = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.Q = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.U = (double*) malloc(sky.num_sources * sizeof(double));\n sky_temp.V = (double*) malloc(sky.num_sources * sizeof(double));\n memcpy(sky_temp.Dec, sky.Dec, sky.num_sources * sizeof(double));\n memcpy(sky_temp.RA, sky.RA, sky.num_sources * sizeof(double));\n memcpy(sky_temp.I, sky.I, sky.num_sources * sizeof(double));\n for (int s = 0; s < sky.num_sources; ++s)\n {\n\/\/ sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);\n sky_temp.I[s] *= pow(frequency \/ settings.obs().start_frequency(), -0.7);\n }\n\n \/\/ Allocate visibility data.\n oskar_VisData_d vis;\n int num_baselines = num_stations * (num_stations-1) \/ 2;\n oskar_allocate_vis_data_d(num_baselines * settings.obs().num_vis_dumps(), &vis);\n\n error_code = oskar_interferometer1_scalar_d(telescope, stations, sky,\n settings.obs().ra0_rad(), settings.obs().dec0_rad(),\n settings.obs().start_time_utc_mjd(), settings.obs().obs_length_days(),\n settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),\n settings.obs().num_fringe_ave(), frequency,\n settings.obs().channel_bandwidth(),\n settings.disable_station_beam(), &vis);\n\n printf(\"= Number of visibility points generated: %i\\n\", vis.num_samples);\n\n \/\/ Write visibility binary file.\n if (!settings.obs().oskar_vis_filename().isEmpty())\n {\n QString vis_file = settings.obs().oskar_vis_filename() + \"_channel_\" + QString::number(i) + \".dat\";\n printf(\"= Writing OSKAR visibility data file: %s\\n\",\n vis_file.toLatin1().data());\n oskar_write_vis_data_d(vis_file.toLatin1().data(), &vis);\n }\n\n \/\/ Write MS.\n#ifndef OSKAR_NO_MS\n if (!settings.obs().ms_filename().isEmpty())\n {\n QString ms_file = settings.obs().ms_filename() + \"_channel_\" + QString::number(i) + \".ms\";\n printf(\"= Writing Measurement Set: %s\\n\", ms_file.toLatin1().data());\n oskar_write_ms_d(ms_file.toLatin1().data(), &settings, &vis, true);\n }\n#endif\n\n free(sky_temp.RA);\n free(sky_temp.Dec);\n free(sky_temp.I);\n free(sky_temp.Q);\n free(sky_temp.U);\n free(sky_temp.V);\n oskar_free_vis_data_d(&vis);\n }\n\n \/\/ ============== Cleanup =================================================\n free(sky.RA);\n free(sky.Dec);\n free(sky.I);\n free(sky.Q);\n free(sky.U);\n free(sky.V);\n free(telescope.antenna_x);\n free(telescope.antenna_y);\n free(telescope.antenna_z);\n for (unsigned i = 0; i < num_stations; ++i)\n {\n free(stations[i].antenna_x);\n free(stations[i].antenna_y);\n }\n free(stations);\n\n return EXIT_SUCCESS;\n}\n\n\n\n\nint sim1_f(const oskar_Settings& settings)\n{\n \/\/ ============== Load input data =========================================\n oskar_SkyModelGlobal_f sky;\n oskar_load_sources_f(settings.sky_file().toLatin1().data(), &sky);\n oskar_TelescopeModel_f telescope;\n oskar_load_telescope_f(settings.telescope_file().toLatin1().data(),\n settings.longitude_rad(), settings.latitude_rad(), &telescope);\n oskar_StationModel_f* stations;\n const char* station_dir = settings.station_dir().toLatin1().data();\n unsigned num_stations = oskar_load_stations_f(station_dir, &stations,\n &telescope.identical_stations);\n if (num_stations != telescope.num_antennas)\n {\n fprintf(stderr, \"ERROR: Error loading telescope geometry.\\n\");\n return EXIT_FAILURE;\n }\n\n \/\/ ============== Simulation loop =========================================\n int error_code = 0;\n for (unsigned i = 0; i < settings.obs().num_channels(); ++i)\n {\n unsigned year = settings.obs().start_time_utc_year();\n unsigned month = settings.obs().start_time_utc_month();\n unsigned day = settings.obs().start_time_utc_day();\n unsigned hour = settings.obs().start_time_utc_hour();\n unsigned minute = settings.obs().start_time_utc_minute();\n float second = settings.obs().start_time_utc_second();\n float day_fraction = (hour + minute\/60 + second\/3600) \/ 24.0;\n float start_time_mjd_utc = oskar_date_time_to_mjd_d(\n year, month, day, day_fraction);\n printf(\"- %i\/%i\/%i %i:%i:%f -> mjd %f\\n\", day, month, year, hour, minute,\n second, start_time_mjd_utc);\n\n float frequency = settings.obs().frequency(i);\n printf(\"- Frequency: %e\\n\", frequency);\n\n \/\/ Allocate memory for frequency scaled sky model.\n oskar_SkyModelGlobal_f sky_temp;\n sky_temp.num_sources = sky.num_sources;\n sky_temp.Dec = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.RA = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.I = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.Q = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.U = (float*) malloc(sky.num_sources * sizeof(float));\n sky_temp.V = (float*) malloc(sky.num_sources * sizeof(float));\n memcpy(sky_temp.Dec, sky.Dec, sky.num_sources * sizeof(float));\n memcpy(sky_temp.RA, sky.RA, sky.num_sources * sizeof(float));\n memcpy(sky_temp.I, sky.I, sky.num_sources * sizeof(float));\n for (int s = 0; s < sky.num_sources; ++s)\n {\n\/\/ sky_temp.I[s] = 1.0e6 * pow(frequency, -0.7);\n sky_temp.I[s] *= pow(frequency \/ settings.obs().start_frequency(), -0.7);\n }\n\n \/\/ Allocate visibility data.\n oskar_VisData_f vis;\n int num_baselines = num_stations * (num_stations-1) \/ 2;\n oskar_allocate_vis_data_f(num_baselines * settings.obs().num_vis_dumps(), &vis);\n\n error_code = oskar_interferometer1_scalar_f(telescope, stations, sky,\n settings.obs().ra0_rad(), settings.obs().dec0_rad(),\n start_time_mjd_utc, settings.obs().obs_length_days(),\n settings.obs().num_vis_dumps(), settings.obs().num_vis_ave(),\n settings.obs().num_fringe_ave(), frequency, settings.obs().channel_bandwidth(),\n settings.disable_station_beam(), &vis);\n\n printf(\"= Number of visibility points generated: %i\\n\", vis.num_samples);\n\n \/\/ Write visibility binary file.\n if (!settings.obs().oskar_vis_filename().isEmpty())\n {\n QString vis_file = settings.obs().oskar_vis_filename() + \"_channel_\" + QString::number(i) + \".dat\";\n printf(\"= Writing OSKAR visibility data file: %s\\n\",\n vis_file.toLatin1().data());\n oskar_write_vis_data_f(vis_file.toLatin1().data(), &vis);\n }\n\n \/\/ Write MS.\n#ifndef OSKAR_NO_MS\n if (!settings.obs().ms_filename().isEmpty())\n {\n QString ms_file = settings.obs().ms_filename() + \"_channel_\" + QString::number(i) + \".ms\";\n printf(\"= Writing Measurement Set: %s\\n\", ms_file.toLatin1().data());\n oskar_write_ms_f(ms_file.toLatin1().data(), &settings, &vis, true);\n }\n#endif\n\n free(sky_temp.RA);\n free(sky_temp.Dec);\n free(sky_temp.I);\n free(sky_temp.Q);\n free(sky_temp.U);\n free(sky_temp.V);\n oskar_free_vis_data_f(&vis);\n }\n\n \/\/ ============== Cleanup =================================================\n free(sky.RA);\n free(sky.Dec);\n free(sky.I);\n free(sky.Q);\n free(sky.U);\n free(sky.V);\n free(telescope.antenna_x);\n free(telescope.antenna_y);\n free(telescope.antenna_z);\n for (unsigned i = 0; i < num_stations; ++i)\n {\n free(stations[i].antenna_x);\n free(stations[i].antenna_y);\n }\n free(stations);\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief basic exceptions\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Exceptions.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public types\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief base class for all errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTriagensError::TriagensError (string const& type, string const& details, char const* file, int line)\n : _type(\"unknown\"),\n _details(details),\n _file(file),\n _line(line) {\n _message = \"exception in '\" + _file + \"' at line \" + StringUtils::itoa(_line) + \": \"\n + \"type = '\" + _type + \"'\";\n\n if (! details.empty()) {\n _message += \" details = '\" + _details + \"'\";\n }\n\n#ifdef TRI_ENABLE_MAINTAINER_MODE\n#if HAVE_BACKTRACE\n _getBacktrace(_message);\n#endif\n#endif\n\n}\n\n\n\nTriagensError::~TriagensError () throw () {\n}\n\n\n\nchar const * TriagensError::what () const throw() {\n return _message.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for internal errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nInternalError::InternalError (string const& details, char const* file, int line)\n : TriagensError(\"internal error\", details, file, line) {\n}\n\n\n\nInternalError::InternalError (std::exception const& ex, char const* file, int line)\n : TriagensError(\"internal exception\", ex.what(), file, line) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for out-of-memory errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOutOfMemoryError::OutOfMemoryError (char const* file, int line)\n : TriagensError(\"out-of-memory\", \"\", file, line) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for file errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFileError::FileError (string const& func,\n string const& details,\n string const& filename,\n string const& mode,\n int error,\n char const* file,\n int line)\n : TriagensError(\"file-error\", details, file, line),\n _filename(filename),\n _mode(mode),\n _error(error) {\n if (! mode.empty()) {\n _message += \" mode = '\" + _mode + \"'\";\n }\n\n if (_error != 0) {\n _message += \" errno = \" + StringUtils::itoa(_error) + \"\"\n + \" error = '\" + strerror(_error) + \"'\";\n }\n\n if (! _filename.empty()) {\n _message += \" file = '\" + _filename + \"'\";\n }\n}\n\n\n\nFileError::~FileError () throw () {\n}\n\n\n\nvoid FileError::setFilename (string const& filename) {\n _filename = filename;\n\n if (! _filename.empty()) {\n _message += \" file = '\" + _filename + \"'\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for parse errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParseError::ParseError (string const& details,\n int lineNumber,\n char const* file,\n int line)\n : TriagensError(\"parse-error\", details, file, line),\n _lineNumber(lineNumber) {\n if (_lineNumber != -1) {\n _message += \" line-number = '\" + StringUtils::itoa(_lineNumber) + \"'\";\n }\n}\n\n\n\nvoid ParseError::setLineNumber (int lineNumber) {\n _lineNumber = lineNumber;\n\n if (_lineNumber != -1) {\n _message += \" line-number = '\" + StringUtils::itoa(_lineNumber) + \"'\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for parameter errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParameterError::ParameterError (string const& parameter,\n string const& details,\n string const& func,\n char const* file,\n int line)\n : TriagensError(\"parameter-error\", details, file, line),\n _parameter(parameter),\n _func(func) {\n _message += \" parameter = '\" + _parameter + \"'\";\n\n if (! _func.empty()) {\n _message += \" func = '\" + _func + \"'\";\n }\n}\n\n\n\nParameterError::~ParameterError () throw () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>Fix a but where a type argument was unused.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief basic exceptions\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Exceptions.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public types\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief base class for all errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTriagensError::TriagensError (string const& type, string const& details, char const* file, int line)\n : _type(type),\n _details(details),\n _file(file),\n _line(line) {\n _message = \"exception in '\" + _file + \"' at line \" + StringUtils::itoa(_line) + \": \"\n + \"type = '\" + _type + \"'\";\n\n if (! details.empty()) {\n _message += \" details = '\" + _details + \"'\";\n }\n\n#ifdef TRI_ENABLE_MAINTAINER_MODE\n#if HAVE_BACKTRACE\n _getBacktrace(_message);\n#endif\n#endif\n\n}\n\n\n\nTriagensError::~TriagensError () throw () {\n}\n\n\n\nchar const * TriagensError::what () const throw() {\n return _message.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for internal errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nInternalError::InternalError (string const& details, char const* file, int line)\n : TriagensError(\"internal error\", details, file, line) {\n}\n\n\n\nInternalError::InternalError (std::exception const& ex, char const* file, int line)\n : TriagensError(\"internal exception\", ex.what(), file, line) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for out-of-memory errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOutOfMemoryError::OutOfMemoryError (char const* file, int line)\n : TriagensError(\"out-of-memory\", \"\", file, line) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for file errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFileError::FileError (string const& func,\n string const& details,\n string const& filename,\n string const& mode,\n int error,\n char const* file,\n int line)\n : TriagensError(\"file-error\", details, file, line),\n _filename(filename),\n _mode(mode),\n _error(error) {\n if (! mode.empty()) {\n _message += \" mode = '\" + _mode + \"'\";\n }\n\n if (_error != 0) {\n _message += \" errno = \" + StringUtils::itoa(_error) + \"\"\n + \" error = '\" + strerror(_error) + \"'\";\n }\n\n if (! _filename.empty()) {\n _message += \" file = '\" + _filename + \"'\";\n }\n}\n\n\n\nFileError::~FileError () throw () {\n}\n\n\n\nvoid FileError::setFilename (string const& filename) {\n _filename = filename;\n\n if (! _filename.empty()) {\n _message += \" file = '\" + _filename + \"'\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for parse errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParseError::ParseError (string const& details,\n int lineNumber,\n char const* file,\n int line)\n : TriagensError(\"parse-error\", details, file, line),\n _lineNumber(lineNumber) {\n if (_lineNumber != -1) {\n _message += \" line-number = '\" + StringUtils::itoa(_lineNumber) + \"'\";\n }\n}\n\n\n\nvoid ParseError::setLineNumber (int lineNumber) {\n _lineNumber = lineNumber;\n\n if (_lineNumber != -1) {\n _message += \" line-number = '\" + StringUtils::itoa(_lineNumber) + \"'\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief exception for parameter errors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nParameterError::ParameterError (string const& parameter,\n string const& details,\n string const& func,\n char const* file,\n int line)\n : TriagensError(\"parameter-error\", details, file, line),\n _parameter(parameter),\n _func(func) {\n _message += \" parameter = '\" + _parameter + \"'\";\n\n if (! _func.empty()) {\n _message += \" func = '\" + _func + \"'\";\n }\n}\n\n\n\nParameterError::~ParameterError () throw () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/github.com\/meyburgh\/forirony\n#include \"Leap.h\" \/\/ the leap sdk header\n#include <string.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\nnamespace\n{\n\tvoid LeapVideo()\n\t{\n\t\tLeap::Controller controller;\n\t\tcontroller.setPolicy(Leap::Controller::POLICY_IMAGES);\n\t\t\n\t\tcv::String const windowName[] = { \"0\", \"1\" };\n\t\t\n\t\twhile (controller.isConnected())\n\t\t{\n\t\t\tLeap::Frame const frame = controller.frame(0);\n\n\t\t\tLeap::ImageList const & imageList = frame.images();\n\t\t\tuint8_t const imageCount = imageList.count();\n\n\t\t\tfor (uint8_t imageIndex = 0; imageIndex < imageCount; ++imageIndex)\n\t\t\t{\n\t\t\t\tLeap::Image const & image = imageList[imageIndex];\n\t\t\t\t\/\/Leap::Vector v = image.rectify() \/\/ you can rectify the video images this way, but it's slow, best to use a shader\n\n\t\t\t\t\/\/image.data() points at width * height * bytes per pixel, 8-bit intensity values\n\t\t\t\tuint32_t const rows = image.height();\n\t\t\t\tuint32_t const columns = image.width();\n\t\t\t\tcv::Mat const mat(rows, columns, CV_8UC1);\n\t\t\t\tuint32_t const imageSize = sizeof(uint8_t) * rows * columns * image.bytesPerPixel();\n\t\t\t\tmemcpy(mat.data, image.data(), imageSize);\n\t\t\t\t\n\t\t\t\tcv::imshow(windowName[imageIndex], mat);\n\t\t\t\tcv::waitKey(16); \/\/ 60 fps poor man's frame limiter\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int const argc, char const * const * const argv)\n{\n\tLeapVideo();\n\n\treturn 0;\n}\n<commit_msg>controller isconnected is unreliable initially, so just keep trying<commit_after>\/\/ https:\/\/github.com\/meyburgh\/forirony\n#include \"Leap.h\" \/\/ the leap sdk header\n#include <string.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\nnamespace\n{\n\tvoid LeapVideo()\n\t{\n\t\tLeap::Controller controller;\n\t\tcontroller.setPolicy(Leap::Controller::POLICY_IMAGES);\n\t\t\n\t\tcv::String const windowName[] = { \"0\", \"1\" };\n\t\t\n\t\tfor (;;)\n\t\t{\n\t\t\tLeap::Frame const frame = controller.frame(0);\n\n\t\t\tLeap::ImageList const & imageList = frame.images();\n\t\t\tuint8_t const imageCount = imageList.count();\n\n\t\t\tfor (uint8_t imageIndex = 0; imageIndex < imageCount; ++imageIndex)\n\t\t\t{\n\t\t\t\tLeap::Image const & image = imageList[imageIndex];\n\t\t\t\t\/\/Leap::Vector v = image.rectify() \/\/ you can rectify the video images this way, but it's slow, best to use a shader\n\n\t\t\t\t\/\/image.data() points at width * height * bytes per pixel, 8-bit intensity values\n\t\t\t\tuint32_t const rows = image.height();\n\t\t\t\tuint32_t const columns = image.width();\n\t\t\t\tcv::Mat const mat(rows, columns, CV_8UC1);\n\t\t\t\tuint32_t const imageSize = sizeof(uint8_t) * rows * columns * image.bytesPerPixel();\n\t\t\t\tmemcpy(mat.data, image.data(), imageSize);\n\t\t\t\t\n\t\t\t\tcv::imshow(windowName[imageIndex], mat);\n\t\t\t\tcv::waitKey(16); \/\/ 60 fps poor man's frame limiter\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int const argc, char const * const * const argv)\n{\n\tLeapVideo();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include <inttypes.h>\n\n#include <algorithm>\n#include <atomic>\n#include <queue>\n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue<ClockPath> queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n \/\/ Too many logs maybe emitted when path is invalid.\n static std::atomic<uint32_t> dlog_count = 0;\n if (dlog_count++ < 10) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n }\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast<size_t>(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits<int64_t>::min();\n const int64_t kInt64Max = std::numeric_limits<int64_t>::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<commit_msg>Fix clock_tracker.cc am: 5dc147f282 am: f2faa3dd19 am: caf328c24a am: 55af9a1d07 am: 3e6b048077<commit_after>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include <inttypes.h>\n\n#include <algorithm>\n#include <atomic>\n#include <queue>\n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue<ClockPath> queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n \/\/ Too many logs maybe emitted when path is invalid.\n static std::atomic<uint32_t> dlog_count(0);\n if (dlog_count++ < 10) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n }\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast<size_t>(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits<int64_t>::min();\n const int64_t kInt64Max = std::numeric_limits<int64_t>::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Main driver function for a vehicle specified through JSON files.\n\/\/\n\/\/ If using the Irrlicht interface, driver inputs are obtained from the keyboard.\n\/\/\n\/\/ The vehicle reference frame has Z up, X towards the front of the vehicle, and\n\/\/ Y pointing to the left.\n\/\/\n\/\/ =============================================================================\n\n#include <vector>\n\n#include \"core\/ChFileutils.h\"\n#include \"core\/ChStream.h\"\n#include \"core\/ChRealtimeStep.h\"\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChLinkDistance.h\"\n\n#include \"ChronoT_config.h\"\n\n#include \"utils\/ChUtilsInputOutput.h\"\n#include \"utils\/ChUtilsData.h\"\n\n#include \"subsys\/vehicle\/Vehicle.h\"\n#include \"subsys\/powertrain\/SimplePowertrain.h\"\n#include \"subsys\/driver\/ChDataDriver.h\"\n#include \"subsys\/tire\/RigidTire.h\"\n#include \"subsys\/terrain\/RigidTerrain.h\"\n\n\/\/ If Irrlicht support is available...\n#if IRRLICHT_ENABLED\n \/\/ ...include additional headers\n# include \"unit_IRRLICHT\/ChIrrApp.h\"\n# include \"subsys\/driver\/ChIrrGuiDriver.h\"\n\n \/\/ ...and specify whether the demo should actually use Irrlicht\n# define USE_IRRLICHT\n#endif\n\nusing namespace chrono;\n\n\/\/ =============================================================================\n\n\/\/ JSON file for vehicle model\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"hmmwv\/vehicle\/HMMWV_Vehicle.json\");\nstd::string vehicle_file = utils::GetModelDataFile(\"hmmwv\/vehicle\/HMMWV_Vehicle_A.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_DoubleWishbones.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_MultiLinks.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_SolidAxles.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_ThreeAxles.json\");\n\n\/\/ JSON files for tire models (rigid) and powertrain (simple)\nstd::string rigidtire_file = utils::GetModelDataFile(\"hmmwv\/tire\/HMMWV_RigidTire.json\");\nstd::string simplepowertrain_file = utils::GetModelDataFile(\"hmmwv\/powertrain\/HMMWV_SimplePowertrain.json\");\n\n\/\/ Driver input file (if not using Irrlicht)\nstd::string driver_file = utils::GetModelDataFile(\"generic\/driver\/Sample_Maneuver.txt\");\n\n\/\/ Initial vehicle position\nChVector<> initLoc(0, 0, 1.0);\n\n\/\/ Initial vehicle orientation\nChQuaternion<> initRot(1, 0, 0, 0);\n\/\/ChQuaternion<> initRot(0.866025, 0, 0, 0.5);\n\/\/ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068);\n\/\/ChQuaternion<> initRot(0.25882, 0, 0, 0.965926);\n\/\/ChQuaternion<> initRot(0, 0, 0, 1);\n\n\/\/ Rigid terrain dimensions\ndouble terrainHeight = 0;\ndouble terrainLength = 100.0; \/\/ size in X direction\ndouble terrainWidth = 100.0; \/\/ size in Y direction\n\n\/\/ Simulation step size\ndouble step_size = 0.001;\n\n\/\/ Time interval between two render frames\ndouble render_step_size = 1.0 \/ 50; \/\/ FPS = 50\n\n\/\/ Time interval between two output frames\ndouble output_step_size = 1.0 \/ 1; \/\/ once a second\n\n#ifdef USE_IRRLICHT\n \/\/ Point on chassis tracked by the camera\n ChVector<> trackPoint(0.0, 0.0, 1.75);\n#else\n double tend = 20.0;\n\n const std::string out_dir = \"..\/VEHICLE\";\n const std::string pov_dir = out_dir + \"\/POVRAY\";\n#endif\n\n\/\/ =============================================================================\n\nint main(int argc, char* argv[])\n{\n SetChronoDataPath(CHRONO_DATA_DIR);\n\n \/\/ --------------------------\n \/\/ Create the various modules\n \/\/ --------------------------\n\n \/\/ Create the vehicle system\n Vehicle vehicle(vehicle_file, false);\n vehicle.Initialize(ChCoordsys<>(initLoc, initRot));\n\n \/\/ Create the ground\n RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);\n\n \/\/ Create and initialize the powertrain system\n SimplePowertrain powertrain(simplepowertrain_file);\n powertrain.Initialize();\n\n \/\/ Create and initialize the tires\n int num_axles = vehicle.GetNumberAxles();\n int num_wheels = 2 * num_axles;\n std::vector<ChSharedPtr<ChTire> > tires(num_wheels);\n\n for (int i = 0; i < num_wheels; i++) {\n ChSharedPtr<RigidTire> tire(new RigidTire(rigidtire_file, terrain));\n tire->Initialize(vehicle.GetWheelBody(i));\n tires[i] = tire;\n }\n\n#ifdef USE_IRRLICHT\n irr::ChIrrApp application(&vehicle,\n L\"Vehicle demo\",\n irr::core::dimension2d<irr::u32>(1000, 800),\n false,\n true);\n\n \/\/ make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up) \n std::string mtexturedir = GetChronoDataFile(\"skybox\/\");\n std::string str_lf = mtexturedir + \"sky_lf.jpg\";\n std::string str_up = mtexturedir + \"sky_up.jpg\";\n std::string str_dn = mtexturedir + \"sky_dn.jpg\";\n irr::video::ITexture* map_skybox_side = \n application.GetVideoDriver()->getTexture(str_lf.c_str());\n irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(\n application.GetVideoDriver()->getTexture(str_up.c_str()),\n application.GetVideoDriver()->getTexture(str_dn.c_str()),\n map_skybox_side,\n map_skybox_side,\n map_skybox_side,\n map_skybox_side);\n mbox->setRotation( irr::core::vector3df(90,0,0));\n \n bool do_shadows = true; \/\/ shadow map is experimental\n irr::scene::ILightSceneNode* mlight = 0;\n\n if (do_shadows)\n {\n mlight = application.AddLightWithShadow(\n irr::core::vector3df(10.f, 30.f, 60.f),\n irr::core::vector3df(0.f, 0.f, 0.f),\n 150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);\n }\n else\n {\n application.AddTypicalLights(\n irr::core::vector3df(30.f, -30.f, 100.f),\n irr::core::vector3df(30.f, 50.f, 100.f),\n 250, 130);\n }\n\n application.SetTimestep(step_size);\n\n ChIrrGuiDriver driver(application, vehicle, powertrain, trackPoint, 6.0, 0.5, true);\n\n \/\/ Set the time response for steering and throttle keyboard inputs.\n \/\/ NOTE: this is not exact, since we do not render quite at the specified FPS.\n double steering_time = 1.0; \/\/ time to go from 0 to +1 (or from 0 to -1)\n double throttle_time = 1.0; \/\/ time to go from 0 to +1\n double braking_time = 0.3; \/\/ time to go from 0 to +1\n driver.SetSteeringDelta(render_step_size \/ steering_time);\n driver.SetThrottleDelta(render_step_size \/ throttle_time);\n driver.SetBrakingDelta(render_step_size \/ braking_time);\n\n \/\/ Set up the assets for rendering\n application.AssetBindAll();\n application.AssetUpdateAll();\n if (do_shadows)\n {\n application.AddShadowAll();\n }\n#else\n ChDataDriver driver(driver_file);\n#endif\n\n\n \/\/ ---------------\n \/\/ Simulation loop\n \/\/ ---------------\n\n \/\/ Inter-module communication data\n ChTireForces tire_forces(num_wheels);\n ChWheelStates wheel_states(num_wheels);\n double driveshaft_speed;\n double powertrain_torque;\n double throttle_input;\n double steering_input;\n double braking_input;\n\n \/\/ Number of simulation steps between two 3D view render frames\n int render_steps = (int)std::ceil(render_step_size \/ step_size);\n\n \/\/ Number of simulation steps between two output frames\n int output_steps = (int)std::ceil(output_step_size \/ step_size);\n\n \/\/ Initialize simulation frame counter and simulation time\n int step_number = 0;\n double time = 0;\n\n#ifdef USE_IRRLICHT\n\n ChRealtimeStepTimer realtime_timer;\n\n while (application.GetDevice()->run())\n {\n \/\/ update the position of the shadow mapping so that it follows the car\n if (do_shadows)\n {\n ChVector<> lightaim = vehicle.GetChassisPos();\n ChVector<> lightpos = vehicle.GetChassisPos() + ChVector<>(10, 30, 60);\n irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);\n irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);\n application.GetEffects()->getShadowLight(0).setPosition(mlightpos);\n application.GetEffects()->getShadowLight(0).setTarget(mlightaim);\n mlight->setPosition(mlightpos);\n }\n\n \/\/ Render scene\n if (step_number % render_steps == 0) {\n application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));\n driver.DrawAll();\n application.GetVideoDriver()->endScene();\n }\n\n \/\/ Collect output data from modules (for inter-module communication)\n throttle_input = driver.GetThrottle();\n steering_input = driver.GetSteering();\n braking_input = driver.GetBraking();\n powertrain_torque = powertrain.GetOutputTorque();\n driveshaft_speed = vehicle.GetDriveshaftSpeed();\n for (int i = 0; i < num_wheels; i++) {\n tire_forces[i] = tires[i]->GetTireForce();\n wheel_states[i] = vehicle.GetWheelState(i);\n }\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Advance simulation for one timestep for all modules\n double step = realtime_timer.SuggestSimulationStep(step_size);\n driver.Advance(step);\n powertrain.Advance(step);\n vehicle.Advance(step);\n terrain.Advance(step);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Advance(step);\n\n \/\/ Increment frame number\n step_number++;\n }\n\n application.GetDevice()->drop();\n\n#else\n\n int render_frame = 0;\n\n if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {\n std::cout << \"Error creating directory \" << out_dir << std::endl;\n return 1;\n }\n if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {\n std::cout << \"Error creating directory \" << pov_dir << std::endl;\n return 1;\n }\n\n vehicle.ExportMeshPovray(out_dir);\n\n char filename[100];\n\n while (time < tend)\n {\n if (step_number % render_steps == 0) {\n \/\/ Output render data\n sprintf(filename, \"%s\/data_%03d.dat\", pov_dir.c_str(), render_frame + 1);\n utils::WriteShapesPovray(&vehicle, filename);\n std::cout << \"Output frame: \" << render_frame << std::endl;\n std::cout << \"Sim frame: \" << step_number << std::endl;\n std::cout << \"Time: \" << time << std::endl;\n std::cout << \" throttle: \" << driver.GetThrottle()\n << \" steering: \" << driver.GetSteering()\n << \" braking: \" << driver.GetBraking() << std::endl;\n std::cout << std::endl;\n render_frame++;\n }\n\n \/\/ Collect output data from modules (for inter-module communication)\n throttle_input = driver.GetThrottle();\n steering_input = driver.GetSteering();\n braking_input = driver.GetBraking();\n powertrain_torque = powertrain.GetOutputTorque();\n driveshaft_speed = vehicle.GetDriveshaftSpeed();\n for (int i = 0; i < num_wheels; i++) {\n tire_forces[i] = tires[i]->GetTireForce();\n wheel_states[i] = vehicle.GetWheelState(i);\n }\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Advance simulation for one timestep for all modules\n driver.Advance(step_size);\n powertrain.Advance(step_size);\n vehicle.Advance(step_size);\n terrain.Advance(step_size);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Advance(step_size);\n\n \/\/ Increment frame number\n step_number++;\n }\n\n#endif\n\n return 0;\n}\n<commit_msg>Removed the ADAMS HMMWV from the demo_Vehicle choices.<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ Main driver function for a vehicle specified through JSON files.\n\/\/\n\/\/ If using the Irrlicht interface, driver inputs are obtained from the keyboard.\n\/\/\n\/\/ The vehicle reference frame has Z up, X towards the front of the vehicle, and\n\/\/ Y pointing to the left.\n\/\/\n\/\/ =============================================================================\n\n#include <vector>\n\n#include \"core\/ChFileutils.h\"\n#include \"core\/ChStream.h\"\n#include \"core\/ChRealtimeStep.h\"\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChLinkDistance.h\"\n\n#include \"ChronoT_config.h\"\n\n#include \"utils\/ChUtilsInputOutput.h\"\n#include \"utils\/ChUtilsData.h\"\n\n#include \"subsys\/vehicle\/Vehicle.h\"\n#include \"subsys\/powertrain\/SimplePowertrain.h\"\n#include \"subsys\/driver\/ChDataDriver.h\"\n#include \"subsys\/tire\/RigidTire.h\"\n#include \"subsys\/terrain\/RigidTerrain.h\"\n\n\/\/ If Irrlicht support is available...\n#if IRRLICHT_ENABLED\n \/\/ ...include additional headers\n# include \"unit_IRRLICHT\/ChIrrApp.h\"\n# include \"subsys\/driver\/ChIrrGuiDriver.h\"\n\n \/\/ ...and specify whether the demo should actually use Irrlicht\n# define USE_IRRLICHT\n#endif\n\nusing namespace chrono;\n\n\/\/ =============================================================================\n\n\/\/ JSON file for vehicle model\nstd::string vehicle_file = utils::GetModelDataFile(\"hmmwv\/vehicle\/HMMWV_Vehicle.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_DoubleWishbones.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_MultiLinks.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_SolidAxles.json\");\n\/\/std::string vehicle_file = utils::GetModelDataFile(\"generic\/vehicle\/Vehicle_ThreeAxles.json\");\n\n\/\/ JSON files for tire models (rigid) and powertrain (simple)\nstd::string rigidtire_file = utils::GetModelDataFile(\"hmmwv\/tire\/HMMWV_RigidTire.json\");\nstd::string simplepowertrain_file = utils::GetModelDataFile(\"hmmwv\/powertrain\/HMMWV_SimplePowertrain.json\");\n\n\/\/ Driver input file (if not using Irrlicht)\nstd::string driver_file = utils::GetModelDataFile(\"generic\/driver\/Sample_Maneuver.txt\");\n\n\/\/ Initial vehicle position\nChVector<> initLoc(0, 0, 1.0);\n\n\/\/ Initial vehicle orientation\nChQuaternion<> initRot(1, 0, 0, 0);\n\/\/ChQuaternion<> initRot(0.866025, 0, 0, 0.5);\n\/\/ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068);\n\/\/ChQuaternion<> initRot(0.25882, 0, 0, 0.965926);\n\/\/ChQuaternion<> initRot(0, 0, 0, 1);\n\n\/\/ Rigid terrain dimensions\ndouble terrainHeight = 0;\ndouble terrainLength = 100.0; \/\/ size in X direction\ndouble terrainWidth = 100.0; \/\/ size in Y direction\n\n\/\/ Simulation step size\ndouble step_size = 0.001;\n\n\/\/ Time interval between two render frames\ndouble render_step_size = 1.0 \/ 50; \/\/ FPS = 50\n\n\/\/ Time interval between two output frames\ndouble output_step_size = 1.0 \/ 1; \/\/ once a second\n\n#ifdef USE_IRRLICHT\n \/\/ Point on chassis tracked by the camera\n ChVector<> trackPoint(0.0, 0.0, 1.75);\n#else\n double tend = 20.0;\n\n const std::string out_dir = \"..\/VEHICLE\";\n const std::string pov_dir = out_dir + \"\/POVRAY\";\n#endif\n\n\/\/ =============================================================================\n\nint main(int argc, char* argv[])\n{\n SetChronoDataPath(CHRONO_DATA_DIR);\n\n \/\/ --------------------------\n \/\/ Create the various modules\n \/\/ --------------------------\n\n \/\/ Create the vehicle system\n Vehicle vehicle(vehicle_file, false);\n vehicle.Initialize(ChCoordsys<>(initLoc, initRot));\n\n \/\/ Create the ground\n RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);\n\n \/\/ Create and initialize the powertrain system\n SimplePowertrain powertrain(simplepowertrain_file);\n powertrain.Initialize();\n\n \/\/ Create and initialize the tires\n int num_axles = vehicle.GetNumberAxles();\n int num_wheels = 2 * num_axles;\n std::vector<ChSharedPtr<ChTire> > tires(num_wheels);\n\n for (int i = 0; i < num_wheels; i++) {\n ChSharedPtr<RigidTire> tire(new RigidTire(rigidtire_file, terrain));\n tire->Initialize(vehicle.GetWheelBody(i));\n tires[i] = tire;\n }\n\n#ifdef USE_IRRLICHT\n irr::ChIrrApp application(&vehicle,\n L\"Vehicle demo\",\n irr::core::dimension2d<irr::u32>(1000, 800),\n false,\n true);\n\n \/\/ make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up) \n std::string mtexturedir = GetChronoDataFile(\"skybox\/\");\n std::string str_lf = mtexturedir + \"sky_lf.jpg\";\n std::string str_up = mtexturedir + \"sky_up.jpg\";\n std::string str_dn = mtexturedir + \"sky_dn.jpg\";\n irr::video::ITexture* map_skybox_side = \n application.GetVideoDriver()->getTexture(str_lf.c_str());\n irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(\n application.GetVideoDriver()->getTexture(str_up.c_str()),\n application.GetVideoDriver()->getTexture(str_dn.c_str()),\n map_skybox_side,\n map_skybox_side,\n map_skybox_side,\n map_skybox_side);\n mbox->setRotation( irr::core::vector3df(90,0,0));\n \n bool do_shadows = true; \/\/ shadow map is experimental\n irr::scene::ILightSceneNode* mlight = 0;\n\n if (do_shadows)\n {\n mlight = application.AddLightWithShadow(\n irr::core::vector3df(10.f, 30.f, 60.f),\n irr::core::vector3df(0.f, 0.f, 0.f),\n 150, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);\n }\n else\n {\n application.AddTypicalLights(\n irr::core::vector3df(30.f, -30.f, 100.f),\n irr::core::vector3df(30.f, 50.f, 100.f),\n 250, 130);\n }\n\n application.SetTimestep(step_size);\n\n ChIrrGuiDriver driver(application, vehicle, powertrain, trackPoint, 6.0, 0.5, true);\n\n \/\/ Set the time response for steering and throttle keyboard inputs.\n \/\/ NOTE: this is not exact, since we do not render quite at the specified FPS.\n double steering_time = 1.0; \/\/ time to go from 0 to +1 (or from 0 to -1)\n double throttle_time = 1.0; \/\/ time to go from 0 to +1\n double braking_time = 0.3; \/\/ time to go from 0 to +1\n driver.SetSteeringDelta(render_step_size \/ steering_time);\n driver.SetThrottleDelta(render_step_size \/ throttle_time);\n driver.SetBrakingDelta(render_step_size \/ braking_time);\n\n \/\/ Set up the assets for rendering\n application.AssetBindAll();\n application.AssetUpdateAll();\n if (do_shadows)\n {\n application.AddShadowAll();\n }\n#else\n ChDataDriver driver(driver_file);\n#endif\n\n\n \/\/ ---------------\n \/\/ Simulation loop\n \/\/ ---------------\n\n \/\/ Inter-module communication data\n ChTireForces tire_forces(num_wheels);\n ChWheelStates wheel_states(num_wheels);\n double driveshaft_speed;\n double powertrain_torque;\n double throttle_input;\n double steering_input;\n double braking_input;\n\n \/\/ Number of simulation steps between two 3D view render frames\n int render_steps = (int)std::ceil(render_step_size \/ step_size);\n\n \/\/ Number of simulation steps between two output frames\n int output_steps = (int)std::ceil(output_step_size \/ step_size);\n\n \/\/ Initialize simulation frame counter and simulation time\n int step_number = 0;\n double time = 0;\n\n#ifdef USE_IRRLICHT\n\n ChRealtimeStepTimer realtime_timer;\n\n while (application.GetDevice()->run())\n {\n \/\/ update the position of the shadow mapping so that it follows the car\n if (do_shadows)\n {\n ChVector<> lightaim = vehicle.GetChassisPos();\n ChVector<> lightpos = vehicle.GetChassisPos() + ChVector<>(10, 30, 60);\n irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);\n irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);\n application.GetEffects()->getShadowLight(0).setPosition(mlightpos);\n application.GetEffects()->getShadowLight(0).setTarget(mlightaim);\n mlight->setPosition(mlightpos);\n }\n\n \/\/ Render scene\n if (step_number % render_steps == 0) {\n application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));\n driver.DrawAll();\n application.GetVideoDriver()->endScene();\n }\n\n \/\/ Collect output data from modules (for inter-module communication)\n throttle_input = driver.GetThrottle();\n steering_input = driver.GetSteering();\n braking_input = driver.GetBraking();\n powertrain_torque = powertrain.GetOutputTorque();\n driveshaft_speed = vehicle.GetDriveshaftSpeed();\n for (int i = 0; i < num_wheels; i++) {\n tire_forces[i] = tires[i]->GetTireForce();\n wheel_states[i] = vehicle.GetWheelState(i);\n }\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Advance simulation for one timestep for all modules\n double step = realtime_timer.SuggestSimulationStep(step_size);\n driver.Advance(step);\n powertrain.Advance(step);\n vehicle.Advance(step);\n terrain.Advance(step);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Advance(step);\n\n \/\/ Increment frame number\n step_number++;\n }\n\n application.GetDevice()->drop();\n\n#else\n\n int render_frame = 0;\n\n if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {\n std::cout << \"Error creating directory \" << out_dir << std::endl;\n return 1;\n }\n if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {\n std::cout << \"Error creating directory \" << pov_dir << std::endl;\n return 1;\n }\n\n vehicle.ExportMeshPovray(out_dir);\n\n char filename[100];\n\n while (time < tend)\n {\n if (step_number % render_steps == 0) {\n \/\/ Output render data\n sprintf(filename, \"%s\/data_%03d.dat\", pov_dir.c_str(), render_frame + 1);\n utils::WriteShapesPovray(&vehicle, filename);\n std::cout << \"Output frame: \" << render_frame << std::endl;\n std::cout << \"Sim frame: \" << step_number << std::endl;\n std::cout << \"Time: \" << time << std::endl;\n std::cout << \" throttle: \" << driver.GetThrottle()\n << \" steering: \" << driver.GetSteering()\n << \" braking: \" << driver.GetBraking() << std::endl;\n std::cout << std::endl;\n render_frame++;\n }\n\n \/\/ Collect output data from modules (for inter-module communication)\n throttle_input = driver.GetThrottle();\n steering_input = driver.GetSteering();\n braking_input = driver.GetBraking();\n powertrain_torque = powertrain.GetOutputTorque();\n driveshaft_speed = vehicle.GetDriveshaftSpeed();\n for (int i = 0; i < num_wheels; i++) {\n tire_forces[i] = tires[i]->GetTireForce();\n wheel_states[i] = vehicle.GetWheelState(i);\n }\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Update modules (process inputs from other modules)\n time = vehicle.GetChTime();\n driver.Update(time);\n powertrain.Update(time, throttle_input, driveshaft_speed);\n vehicle.Update(time, steering_input, braking_input, powertrain_torque, tire_forces);\n terrain.Update(time);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Update(time, wheel_states[i]);\n\n \/\/ Advance simulation for one timestep for all modules\n driver.Advance(step_size);\n powertrain.Advance(step_size);\n vehicle.Advance(step_size);\n terrain.Advance(step_size);\n for (int i = 0; i < num_wheels; i++)\n tires[i]->Advance(step_size);\n\n \/\/ Increment frame number\n step_number++;\n }\n\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n\n#include \"types.h\"\n\nnamespace bpftrace {\n\nstd::ostream &operator<<(std::ostream &os, Type type)\n{\n os << typestr(type);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const SizedType &type)\n{\n if (type.type == Type::cast)\n {\n os << type.cast_type;\n }\n else if (type.type == Type::integer)\n {\n os << (type.is_signed ? \"\" : \"unsigned \") << \"int\" << 8*type.size;\n }\n else\n {\n os << type.type;\n }\n\n if (type.is_pointer)\n os << \"*\";\n\n return os;\n}\n\nbool SizedType::IsEqual(const SizedType &t) const\n{\n return type == t.type && size == t.size && is_signed == t.is_signed;\n}\n\nbool SizedType::operator!=(const SizedType &t) const\n{\n return !IsEqual(t);\n}\n\nbool SizedType::operator==(const SizedType &t) const\n{\n return IsEqual(t);\n}\n\nbool SizedType::IsArray() const\n{\n return type == Type::array || type == Type::string ||\n type == Type::usym || type == Type::inet ||\n (type == Type::cast && !is_pointer);\n}\n\nbool SizedType::IsStack() const\n{\n return type == Type::ustack || type == Type::kstack;\n}\n\nstd::string typestr(Type t)\n{\n switch (t)\n {\n case Type::none: return \"none\"; break;\n case Type::integer: return \"integer\"; break;\n case Type::hist: return \"hist\"; break;\n case Type::lhist: return \"lhist\"; break;\n case Type::count: return \"count\"; break;\n case Type::sum: return \"sum\"; break;\n case Type::min: return \"min\"; break;\n case Type::max: return \"max\"; break;\n case Type::avg: return \"avg\"; break;\n case Type::stats: return \"stats\"; break;\n case Type::kstack: return \"kstack\"; break;\n case Type::ustack: return \"ustack\"; break;\n case Type::string: return \"string\"; break;\n case Type::ksym: return \"ksym\"; break;\n case Type::usym: return \"usym\"; break;\n case Type::cast: return \"cast\"; break;\n case Type::join: return \"join\"; break;\n case Type::probe: return \"probe\"; break;\n case Type::username: return \"username\"; break;\n case Type::inet: return \"inet\"; break;\n case Type::stack_mode:return \"stack mode\";break;\n case Type::array: return \"array\"; break;\n default:\n std::cerr << \"call or probe type not found\" << std::endl;\n abort();\n }\n}\n\nProbeType probetype(const std::string &probeName)\n{\n ProbeType retType = ProbeType::invalid;\n\n auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(),\n [&probeName] (const ProbeItem& p) {\n return (p.name == probeName ||\n p.abbr == probeName);\n });\n\n if (v != PROBE_LIST.end())\n retType = v->type;\n\n return retType;\n}\n\nstd::string probetypeName(const std::string &probeName)\n{\n std::string res = probeName;\n\n auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(),\n [&probeName] (const ProbeItem& p) {\n return (p.name == probeName ||\n p.abbr == probeName);\n });\n\n if (v != PROBE_LIST.end())\n res = v->name;\n\n return res;\n}\n\nstd::string probetypeName(ProbeType t)\n{\n switch (t)\n {\n case ProbeType::invalid: return \"invalid\"; break;\n case ProbeType::kprobe: return \"kprobe\"; break;\n case ProbeType::kretprobe: return \"kretprobe\"; break;\n case ProbeType::uprobe: return \"uprobe\"; break;\n case ProbeType::uretprobe: return \"uretprobe\"; break;\n case ProbeType::usdt: return \"usdt\"; break;\n case ProbeType::tracepoint: return \"tracepoint\"; break;\n case ProbeType::profile: return \"profile\"; break;\n case ProbeType::interval: return \"interval\"; break;\n case ProbeType::software: return \"software\"; break;\n case ProbeType::hardware: return \"hardware\"; break;\n default:\n std::cerr << \"probe type not found\" << std::endl;\n abort();\n }\n}\n\nuint64_t asyncactionint(AsyncAction a)\n{\n return (uint64_t)a;\n}\n\n} \/\/ namespace bpftrace\n<commit_msg>Print Type::string and Type::array size information along with type information<commit_after>#include <iostream>\n#include <algorithm>\n\n#include \"types.h\"\n\nnamespace bpftrace {\n\nstd::ostream &operator<<(std::ostream &os, Type type)\n{\n os << typestr(type);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const SizedType &type)\n{\n if (type.type == Type::cast)\n {\n os << type.cast_type;\n }\n else if (type.type == Type::integer)\n {\n os << (type.is_signed ? \"\" : \"unsigned \") << \"int\" << 8*type.size;\n }\n else if (type.type == Type::array)\n {\n os << (type.is_signed ? \"\" : \"unsigned \") << \"int\" << 8 * type.pointee_size;\n os << \"[\" << type.size << \"]\";\n }\n else if (type.type == Type::string)\n {\n os << type.type << \"[\" << type.size << \"]\";\n }\n else\n {\n os << type.type;\n }\n\n if (type.is_pointer)\n os << \"*\";\n\n return os;\n}\n\nbool SizedType::IsEqual(const SizedType &t) const\n{\n return type == t.type && size == t.size && is_signed == t.is_signed;\n}\n\nbool SizedType::operator!=(const SizedType &t) const\n{\n return !IsEqual(t);\n}\n\nbool SizedType::operator==(const SizedType &t) const\n{\n return IsEqual(t);\n}\n\nbool SizedType::IsArray() const\n{\n return type == Type::array || type == Type::string ||\n type == Type::usym || type == Type::inet ||\n (type == Type::cast && !is_pointer);\n}\n\nbool SizedType::IsStack() const\n{\n return type == Type::ustack || type == Type::kstack;\n}\n\nstd::string typestr(Type t)\n{\n switch (t)\n {\n case Type::none: return \"none\"; break;\n case Type::integer: return \"integer\"; break;\n case Type::hist: return \"hist\"; break;\n case Type::lhist: return \"lhist\"; break;\n case Type::count: return \"count\"; break;\n case Type::sum: return \"sum\"; break;\n case Type::min: return \"min\"; break;\n case Type::max: return \"max\"; break;\n case Type::avg: return \"avg\"; break;\n case Type::stats: return \"stats\"; break;\n case Type::kstack: return \"kstack\"; break;\n case Type::ustack: return \"ustack\"; break;\n case Type::string: return \"string\"; break;\n case Type::ksym: return \"ksym\"; break;\n case Type::usym: return \"usym\"; break;\n case Type::cast: return \"cast\"; break;\n case Type::join: return \"join\"; break;\n case Type::probe: return \"probe\"; break;\n case Type::username: return \"username\"; break;\n case Type::inet: return \"inet\"; break;\n case Type::stack_mode:return \"stack mode\";break;\n case Type::array: return \"array\"; break;\n default:\n std::cerr << \"call or probe type not found\" << std::endl;\n abort();\n }\n}\n\nProbeType probetype(const std::string &probeName)\n{\n ProbeType retType = ProbeType::invalid;\n\n auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(),\n [&probeName] (const ProbeItem& p) {\n return (p.name == probeName ||\n p.abbr == probeName);\n });\n\n if (v != PROBE_LIST.end())\n retType = v->type;\n\n return retType;\n}\n\nstd::string probetypeName(const std::string &probeName)\n{\n std::string res = probeName;\n\n auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(),\n [&probeName] (const ProbeItem& p) {\n return (p.name == probeName ||\n p.abbr == probeName);\n });\n\n if (v != PROBE_LIST.end())\n res = v->name;\n\n return res;\n}\n\nstd::string probetypeName(ProbeType t)\n{\n switch (t)\n {\n case ProbeType::invalid: return \"invalid\"; break;\n case ProbeType::kprobe: return \"kprobe\"; break;\n case ProbeType::kretprobe: return \"kretprobe\"; break;\n case ProbeType::uprobe: return \"uprobe\"; break;\n case ProbeType::uretprobe: return \"uretprobe\"; break;\n case ProbeType::usdt: return \"usdt\"; break;\n case ProbeType::tracepoint: return \"tracepoint\"; break;\n case ProbeType::profile: return \"profile\"; break;\n case ProbeType::interval: return \"interval\"; break;\n case ProbeType::software: return \"software\"; break;\n case ProbeType::hardware: return \"hardware\"; break;\n default:\n std::cerr << \"probe type not found\" << std::endl;\n abort();\n }\n}\n\nuint64_t asyncactionint(AsyncAction a)\n{\n return (uint64_t)a;\n}\n\n} \/\/ namespace bpftrace\n<|endoftext|>"} {"text":"<commit_before>#include \"include\/udata.h\"\n#include <include\/udata_accessors.h>\n#include <stdio.h>\n#include <cstring>\n\nUserData *getDefaultUserData() {\n UserData *udata = new UserData;\n memset(udata, 0, sizeof(*udata));\n\n return udata;\n}\n\nvoid freeUserData(UserData *udata) {\n if(udata) {\n#ifdef AMICI_WITHOUT_MATLAB\n if(qpositivex) delete[] qpositivex;\n if(p) delete[] p;\n if(k) delete[] k;\n if(ts) delete[] ts;\n if(pbar) delete[] pbar;\n if(xbar) delete[] xbar;\n if(idlist) delete[] idlist;\n if(sx0data) delete sx0data;\n if(z2event) delete[] z2event;\n#endif\n if(plist) delete[] plist;\n if(h) delete[] h;\n if(tmp_dxdotdp) delete[] tmp_dxdotdp;\n if(w_tmp) delete[] w_tmp;\n if(dwdx_tmp) delete[] dwdx_tmp;\n if(dwdp_tmp) delete[] dwdp_tmp;\n if(M_tmp) delete[] M_tmp;\n if(dfdx_tmp) delete[] dfdx_tmp;\n if(stau_tmp) delete[] stau_tmp;\n if(tmp_J) SparseDestroyMat(tmp_J);\n\n delete udata;\n }\n}\n\n#ifdef AMICI_WITHOUT_MATLAB\nvoid printUserData(UserData *udata) {\n printf(\"am_qpositivex: %p\\n\", udata->am_qpositivex);\n printf(\"am_plist: %p\\n\", udata->am_plist);\n printf(\"am_np: %d\\n\", udata->am_np);\n printf(\"am_ny: %d\\n\", udata->am_ny);\n printf(\"am_nytrue: %d\\n\", udata->am_nytrue);\n printf(\"am_nx: %d\\n\", udata->am_nx);\n printf(\"am_nxtrue: %d\\n\", udata->am_nxtrue);\n printf(\"am_nz: %d\\n\", udata->am_nz);\n printf(\"am_nztrue: %d\\n\", udata->am_nztrue);\n printf(\"am_ne: %d\\n\", udata->am_ne);\n printf(\"am_nt: %d\\n\", udata->am_nt);\n printf(\"am_ng: %d\\n\", udata->am_ng);\n printf(\"am_nw: %d\\n\", udata->am_nw);\n printf(\"am_ndwdx: %d\\n\", udata->am_ndwdx);\n printf(\"am_nnz: %d\\n\", udata->am_nnz);\n printf(\"am_nmaxevent: %d\\n\", udata->am_nmaxevent);\n printf(\"am_pscale: %d\\n\", (int)udata->am_pscale);\n printf(\"am_p: %p\\n\", udata->am_p);\n printf(\"am_k: %p\\n\", udata->am_k);\n printf(\"am_tstart: %e\\n\", udata->am_tstart);\n printf(\"am_ts: %p\\n\", udata->am_ts);\n printf(\"am_pbar: %p\\n\", udata->am_pbar);\n printf(\"am_xbar: %p\\n\", udata->am_xbar);\n printf(\"am_idlist: %p\\n\", udata->am_idlist);\n printf(\"am_sensi: %d\\n\", udata->am_sensi);\n printf(\"am_atol: %e\\n\", udata->am_atol);\n printf(\"am_rtol: %e\\n\", udata->am_rtol);\n printf(\"am_maxsteps: %d\\n\", udata->am_maxsteps);\n printf(\"am_ism: %d\\n\", udata->am_ism);\n printf(\"am_sensi_meth: %d\\n\", udata->am_sensi_meth);\n printf(\"am_linsol: %d\\n\", udata->am_linsol);\n printf(\"am_interpType: %d\\n\", udata->am_interpType);\n printf(\"am_lmm: %d\\n\", udata->am_lmm);\n printf(\"am_iter: %d\\n\", udata->am_iter);\n printf(\"am_stldet: %d\\n\", udata->am_stldet);\n printf(\"am_ubw: %d\\n\", udata->am_ubw);\n printf(\"am_lbw: %d\\n\", udata->am_lbw);\n printf(\"am_x0data: %p\\n\", udata->am_x0data);\n printf(\"am_sx0data: %p\\n\", udata->am_sx0data);\n printf(\"am_ordering: %d\\n\", udata->am_ordering);\n printf(\"am_z2event: %p\\n\", udata->am_z2event);\n printf(\"am_h: %p\\n\", udata->am_h);\n}\n#endif\n<commit_msg>Fix delete<commit_after>#include \"include\/udata.h\"\n#include <include\/udata_accessors.h>\n#include <stdio.h>\n#include <cstring>\n\nUserData *getDefaultUserData() {\n UserData *udata = new UserData;\n memset(udata, 0, sizeof(*udata));\n\n return udata;\n}\n\nvoid freeUserData(UserData *udata) {\n if(udata) {\n#ifdef AMICI_WITHOUT_MATLAB\n if(qpositivex) delete[] qpositivex;\n if(p) delete[] p;\n if(k) delete[] k;\n if(ts) delete[] ts;\n if(pbar) delete[] pbar;\n if(xbar) delete[] xbar;\n if(idlist) delete[] idlist;\n if(x0data) delete[] x0data;\n if(sx0data) delete[] sx0data;\n if(z2event) delete[] z2event;\n#endif\n if(plist) delete[] plist;\n if(h) delete[] h;\n if(tmp_dxdotdp) delete[] tmp_dxdotdp;\n if(w_tmp) delete[] w_tmp;\n if(dwdx_tmp) delete[] dwdx_tmp;\n if(dwdp_tmp) delete[] dwdp_tmp;\n if(M_tmp) delete[] M_tmp;\n if(dfdx_tmp) delete[] dfdx_tmp;\n if(stau_tmp) delete[] stau_tmp;\n if(tmp_J) SparseDestroyMat(tmp_J);\n\n delete udata;\n }\n}\n\n#ifdef AMICI_WITHOUT_MATLAB\nvoid printUserData(UserData *udata) {\n printf(\"am_qpositivex: %p\\n\", udata->am_qpositivex);\n printf(\"am_plist: %p\\n\", udata->am_plist);\n printf(\"am_np: %d\\n\", udata->am_np);\n printf(\"am_ny: %d\\n\", udata->am_ny);\n printf(\"am_nytrue: %d\\n\", udata->am_nytrue);\n printf(\"am_nx: %d\\n\", udata->am_nx);\n printf(\"am_nxtrue: %d\\n\", udata->am_nxtrue);\n printf(\"am_nz: %d\\n\", udata->am_nz);\n printf(\"am_nztrue: %d\\n\", udata->am_nztrue);\n printf(\"am_ne: %d\\n\", udata->am_ne);\n printf(\"am_nt: %d\\n\", udata->am_nt);\n printf(\"am_ng: %d\\n\", udata->am_ng);\n printf(\"am_nw: %d\\n\", udata->am_nw);\n printf(\"am_ndwdx: %d\\n\", udata->am_ndwdx);\n printf(\"am_nnz: %d\\n\", udata->am_nnz);\n printf(\"am_nmaxevent: %d\\n\", udata->am_nmaxevent);\n printf(\"am_pscale: %d\\n\", (int)udata->am_pscale);\n printf(\"am_p: %p\\n\", udata->am_p);\n printf(\"am_k: %p\\n\", udata->am_k);\n printf(\"am_tstart: %e\\n\", udata->am_tstart);\n printf(\"am_ts: %p\\n\", udata->am_ts);\n printf(\"am_pbar: %p\\n\", udata->am_pbar);\n printf(\"am_xbar: %p\\n\", udata->am_xbar);\n printf(\"am_idlist: %p\\n\", udata->am_idlist);\n printf(\"am_sensi: %d\\n\", udata->am_sensi);\n printf(\"am_atol: %e\\n\", udata->am_atol);\n printf(\"am_rtol: %e\\n\", udata->am_rtol);\n printf(\"am_maxsteps: %d\\n\", udata->am_maxsteps);\n printf(\"am_ism: %d\\n\", udata->am_ism);\n printf(\"am_sensi_meth: %d\\n\", udata->am_sensi_meth);\n printf(\"am_linsol: %d\\n\", udata->am_linsol);\n printf(\"am_interpType: %d\\n\", udata->am_interpType);\n printf(\"am_lmm: %d\\n\", udata->am_lmm);\n printf(\"am_iter: %d\\n\", udata->am_iter);\n printf(\"am_stldet: %d\\n\", udata->am_stldet);\n printf(\"am_ubw: %d\\n\", udata->am_ubw);\n printf(\"am_lbw: %d\\n\", udata->am_lbw);\n printf(\"am_x0data: %p\\n\", udata->am_x0data);\n printf(\"am_sx0data: %p\\n\", udata->am_sx0data);\n printf(\"am_ordering: %d\\n\", udata->am_ordering);\n printf(\"am_z2event: %p\\n\", udata->am_z2event);\n printf(\"am_h: %p\\n\", udata->am_h);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*-\n * Copyright 2017 Shivansh Rai\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * $FreeBSD$\n *\/\n\n#include <array>\n#include <cstdlib>\n#include <fcntl.h>\n#include <fstream>\n#include <iostream>\n#include <pthread.h>\n#include <signal.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include \"utils.h\"\n#include \"logging.h\"\n\n#define READ 0 \t\/* Pipe descriptor: read end. *\/\n#define WRITE 1 \t\/* Pipe descriptor: write end. *\/\n#define BUFSIZE 128 \t\/* Buffer size (used for buffering output\n\t\t\t * from a utility's execution).\n\t\t\t *\/\n#define TIMEOUT 2 \t\/* threshold (seconds) for a function call to return. *\/\n\n\/*\n * Insert a list of user-defined option definitions\n * into a hashmap. These specific option definitions\n * are the ones which one can be easily tested.\n *\/\nvoid\nutils::OptDefinition::InsertOpts()\n{\n\t\/* Option definitions. *\/\n\tOptRelation h_def; \/* '-h' *\/\n\th_def.type = 's';\n\th_def.value = \"h\";\n\th_def.keyword = \"help\";\n\n\tOptRelation v_def; \/* '-v' *\/\n\tv_def.type = 's';\n\tv_def.value = \"v\";\n\tv_def.keyword = \"version\";\n\n\t\/*\n\t * \"opt_map\" contains all the options\n\t * which can be easily tested.\n\t *\/\n\topt_map.insert(std::make_pair<std::string, OptRelation>\n\t\t (\"h\", (OptRelation)h_def));\n\topt_map.insert(std::make_pair<std::string, OptRelation>\n\t\t (\"v\", (OptRelation)v_def));\n};\n\n\/*\n * For the utility under test, find the supported options\n * present in the hashmap generated by InsertOpts()\n * and return them in a form of list of option relations.\n *\/\nstd::list<utils::OptRelation *>\nutils::OptDefinition::CheckOpts(std::string utility)\n{\n\tstd::string line; \/* An individual line in a man-page. *\/\n\tstd::string opt_name; \/* Name of the option. *\/\n\tstd::string opt_identifier = \".It Fl\"; \/* Identifier for an option in man page. *\/\n\tstd::string buffer; \/* Option description extracted from man-page. *\/\n\tstd::string opt_string; \/* Identified option names. *\/\n\tint opt_position; \/* Starting index of the (identified) option. *\/\n\tint space_index; \/* First occurrence of space character\n\t\t\t\t\t * in a multi-word option definition.\n\t\t\t\t\t *\/\n\tstd::list<OptRelation *> identified_opt_list; \/* List of identified option relations. *\/\n\tstd::list<std::string> supported_sections = { \"1\", \"8\" };\n\n\t\/* Generate the hashmap opt_map. *\/\n\tInsertOpts();\n\n\tfor (const auto §ion : supported_sections) {\n\t\tstd::ifstream infile(\"groff\/\" + utility + \".\" + section);\n\n\t\t\/*\n\t\t * Search for all the options accepted by the\n\t\t * utility and collect those present in \"opt_map\".\n\t\t *\/\n\t\twhile (std::getline(infile, line)) {\n\t\t\tif ((opt_position = line.find(opt_identifier)) != std::string::npos) {\n\t\t\t\t\/* Locate the position of option name. *\/\n\t\t\t\topt_position += opt_identifier.length() + 1;\n\n\t\t\t\tif (opt_position > line.length()) {\n\t\t\t\t\t\/*\n\t\t\t\t\t * This condition will trigger when a utility\n\t\t\t\t\t * supports an empty argument, e.g. tset(issue #9)\n\t\t\t\t\t *\/\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/*\n\t\t\t\t * Check for long options ; While here, also sanitize\n\t\t\t\t * multi-word option definitions in a man page to properly\n\t\t\t\t * extract short options from option definitions such as:\n\t\t\t\t * \t.It Fl r Ar seconds (taken from date(1)).\n\t\t\t\t *\/\n\t\t\t\tif ((space_index = line.find(\" \", opt_position + 1, 1))\n\t\t\t\t\t\t!= std::string::npos)\n\t\t\t\t\topt_name = line.substr(opt_position, space_index - opt_position);\n\t\t\t\telse\n\t\t\t\t\topt_name = line.substr(opt_position);\n\n\t\t\t\t\/*\n\t\t\t\t * Check if the identified option matches the identifier.\n\t\t\t\t * \"opt_list.back()\" is the previously checked option, the\n\t\t\t\t * description of which is now stored in \"buffer\".\n\t\t\t\t *\/\n\t\t\t\tif (!opt_list.empty() &&\n\t\t\t\t\t\t(opt_map_iter = opt_map.find(opt_list.back()))\n\t\t\t\t\t\t!= opt_map.end() &&\n\t\t\t\t\t\tbuffer.find((opt_map_iter->second).keyword) != std::string::npos) {\n\t\t\t\t\tidentified_opt_list.push_back(&(opt_map_iter->second));\n\n\t\t\t\t\t\/*\n\t\t\t\t\t * Since the usage of the option under test\n\t\t\t\t\t * is known, we remove it from \"opt_list\".\n\t\t\t\t\t *\/\n\t\t\t\t\topt_list.pop_back();\n\t\t\t\t}\n\n\t\t\t\t\/* Update the list of valid options. *\/\n\t\t\t\topt_list.push_back(opt_name);\n\n\t\t\t\t\/* Empty the buffer for next option's description. *\/\n\t\t\t\tbuffer.clear();\n\t\t\t} else {\n\t\t\t\t\/*\n\t\t\t\t * Collect the option description until next\n\t\t\t\t * valid option definition is encountered.\n\t\t\t\t *\/\n\t\t\t\tbuffer.append(line);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn identified_opt_list;\n}\n\n\/*\n * When pclose() is called on the stream returned by popen(),\n * it waits indefinitely for the created shell process to\n * terminate in cases where the shell command waits for the\n * user input via a blocking read (e.g. passwd(1)).\n * Hence, we define a custom function which alongside\n * returning the read-write file descriptors, also returns\n * the pid of the newly created (child) shell process. This\n * pid can later be used for sending a signal to the child.\n *\n * NOTE For the sake of completeness, we also specify actions\n * to be taken corresponding to the \"w\" (write) type. However,\n * in this context only the \"r\" (read) type will be required.\n *\/\n\nutils::PipeDescriptor*\nutils::POpen(const char *command)\n{\n\tint pdes[2];\n\tchar *argv[4];\n\tpid_t child_pid;\n\tPipeDescriptor *pipe_descr = (PipeDescriptor *)malloc(sizeof(PipeDescriptor));\n\n\t\/* Create a pipe with ~\n\t * - pdes[READ]: read end\n\t * - pdes[WRITE]: write end\n\t *\/\n\tif (pipe2(pdes, O_CLOEXEC) < 0)\n\t\treturn NULL;\n\n\tpipe_descr->readfd = pdes[READ];\n\tpipe_descr->writefd = pdes[WRITE];\n\n\targv[0] = (char *)\"sh\"; \t\/* Type-cast to avoid compiler warning [-Wwrite-strings]. *\/\n\targv[1] = (char *)\"-c\";\n\targv[2] = (char *)command;\n\targv[3] = NULL;\n\n\tswitch (child_pid = vfork()) {\n\t\tcase -1: \t\t\/* Error. *\/\n\t\t\treturn NULL;\n\t\tcase 0: \t\t\/* Child. *\/\n\t\t\t\/*\n\t\t\t * TODO Verify if the following operations on both read\n\t\t\t * and write file-descriptors (irrespective of the value\n\t\t\t * of 'type', which is no longer being used) is safe.\n\t\t\t *\/\n\t\t\tif (pdes[WRITE] != STDOUT_FILENO)\n\t\t\t\tdup2(pdes[WRITE], STDOUT_FILENO);\n\t\t\telse\n\t\t\t\tfcntl(pdes[WRITE], F_SETFD, 0);\n\t\t\tif (pdes[READ] != STDIN_FILENO)\n\t\t\t\tdup2(pdes[READ], STDIN_FILENO);\n\t\t\telse\n\t\t\t\tfcntl(pdes[READ], F_SETFD, 0);\n\n\t\t\t\/*\n\t\t\t * For current usecase, it might so happen that the child gets\n\t\t\t * stuck on a blocking read (e.g. passwd(1)) waiting for user\n\t\t\t * input. In that case the child will be killed via a signal.\n\t\t\t * To avoid any effect on the parent's execution, we place the\n\t\t\t * child in a separate process group with pgid set as \"child_pid\".\n\t\t\t *\/\n\t\t\tsetpgid(child_pid, child_pid);\n\t\t\texecve(\"\/bin\/sh\", argv, NULL);\n\t\t\texit(127);\n\t}\n\n\tpipe_descr->pid = child_pid;\n\n\treturn pipe_descr;\n}\n\n\/*\n * Executes the passed argument \"command\" in a shell\n * and returns its output and the exit status.\n *\/\nstd::pair<std::string, int>\nutils::Execute(std::string command)\n{\n\tint result;\n\tstd::array<char, BUFSIZE> buffer;\n\tstd::string usage_output;\n\tstruct timeval tv;\n\tfd_set readfds;\n\tFILE *pipe;\n\tPipeDescriptor *pipe_descr;\n\n\tDEBUGP(\"Executing: %s\\n\", command.c_str());\n\n\tpipe_descr = utils::POpen(command.c_str());\n\tif (pipe_descr == NULL) {\n\t\tperror(\"utils::POpen()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* Close the unrequired file-descriptor. *\/\n\tclose(pipe_descr->writefd);\n\n\tpipe = fdopen(pipe_descr->readfd, \"r\");\n\tfree(pipe_descr);\n\tif (pipe == NULL) {\n\t\tclose(pipe_descr->readfd);\n\t\tperror(\"fdopen()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/*\n\t * Set a timeout value for the spawned shell\n\t * process to complete its execution.\n\t *\/\n\ttv.tv_sec = TIMEOUT;\n\ttv.tv_usec = 0;\n\n\tFD_ZERO(&readfds);\n\tFD_SET(fileno(pipe), &readfds);\n\tresult = select(fileno(pipe) + 1, &readfds, NULL, NULL, &tv);\n\n\tif (result > 0) {\n\t\twhile (!feof(pipe))\n\t\t\tif (fgets(buffer.data(), BUFSIZE, pipe) != NULL)\n\t\t\t\tusage_output += buffer.data();\n\t} else if (result == -1) {\n\t\tperror(\"select()\");\n\t\tif (kill(pipe_descr->pid, SIGTERM) < 0)\n\t\t\tperror(\"kill()\");\n\t} else if (result == 0) {\n\t\t\/*\n\t\t * We gave a relaxed value of 2 seconds for the shell process\n\t\t * to complete it's execution. If at this point it is still\n\t\t * alive, it (most probably) is stuck on a blocking read\n\t\t * waiting for the user input. Since few of the utilities\n\t\t * performing such blocking reads don't respond to SIGINT\n\t\t * (e.g. pax(1)), we terminate the shell process via SIGTERM.\n\t\t *\/\n\t\tif (kill(pipe_descr->pid, SIGTERM) < 0)\n\t\t\tperror(\"kill()\");\n\t}\n\n\treturn std::make_pair<std::string, int>\n\t\t((std::string)usage_output, WEXITSTATUS(pclose(pipe)));\n}\n<commit_msg>Update TIMEOUT to 1 second<commit_after>\/*-\n * Copyright 2017 Shivansh Rai\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * $FreeBSD$\n *\/\n\n#include <array>\n#include <cstdlib>\n#include <fcntl.h>\n#include <fstream>\n#include <iostream>\n#include <pthread.h>\n#include <signal.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include \"utils.h\"\n#include \"logging.h\"\n\n#define READ 0 \t\/* Pipe descriptor: read end. *\/\n#define WRITE 1 \t\/* Pipe descriptor: write end. *\/\n#define BUFSIZE 128 \t\/* Buffer size (used for buffering output\n\t\t\t * from a utility's execution).\n\t\t\t *\/\n#define TIMEOUT 1 \t\/* threshold (seconds) for a function call to return. *\/\n\n\/*\n * Insert a list of user-defined option definitions\n * into a hashmap. These specific option definitions\n * are the ones which one can be easily tested.\n *\/\nvoid\nutils::OptDefinition::InsertOpts()\n{\n\t\/* Option definitions. *\/\n\tOptRelation h_def; \/* '-h' *\/\n\th_def.type = 's';\n\th_def.value = \"h\";\n\th_def.keyword = \"help\";\n\n\tOptRelation v_def; \/* '-v' *\/\n\tv_def.type = 's';\n\tv_def.value = \"v\";\n\tv_def.keyword = \"version\";\n\n\t\/*\n\t * \"opt_map\" contains all the options\n\t * which can be easily tested.\n\t *\/\n\topt_map.insert(std::make_pair<std::string, OptRelation>\n\t\t (\"h\", (OptRelation)h_def));\n\topt_map.insert(std::make_pair<std::string, OptRelation>\n\t\t (\"v\", (OptRelation)v_def));\n};\n\n\/*\n * For the utility under test, find the supported options\n * present in the hashmap generated by InsertOpts()\n * and return them in a form of list of option relations.\n *\/\nstd::list<utils::OptRelation *>\nutils::OptDefinition::CheckOpts(std::string utility)\n{\n\tstd::string line; \/* An individual line in a man-page. *\/\n\tstd::string opt_name; \/* Name of the option. *\/\n\tstd::string opt_identifier = \".It Fl\"; \/* Identifier for an option in man page. *\/\n\tstd::string buffer; \/* Option description extracted from man-page. *\/\n\tstd::string opt_string; \/* Identified option names. *\/\n\tint opt_position; \/* Starting index of the (identified) option. *\/\n\tint space_index; \/* First occurrence of space character\n\t\t\t\t\t * in a multi-word option definition.\n\t\t\t\t\t *\/\n\tstd::list<OptRelation *> identified_opt_list; \/* List of identified option relations. *\/\n\tstd::list<std::string> supported_sections = { \"1\", \"8\" };\n\n\t\/* Generate the hashmap opt_map. *\/\n\tInsertOpts();\n\n\tfor (const auto §ion : supported_sections) {\n\t\tstd::ifstream infile(\"groff\/\" + utility + \".\" + section);\n\n\t\t\/*\n\t\t * Search for all the options accepted by the\n\t\t * utility and collect those present in \"opt_map\".\n\t\t *\/\n\t\twhile (std::getline(infile, line)) {\n\t\t\tif ((opt_position = line.find(opt_identifier)) != std::string::npos) {\n\t\t\t\t\/* Locate the position of option name. *\/\n\t\t\t\topt_position += opt_identifier.length() + 1;\n\n\t\t\t\tif (opt_position > line.length()) {\n\t\t\t\t\t\/*\n\t\t\t\t\t * This condition will trigger when a utility\n\t\t\t\t\t * supports an empty argument, e.g. tset(issue #9)\n\t\t\t\t\t *\/\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/*\n\t\t\t\t * Check for long options ; While here, also sanitize\n\t\t\t\t * multi-word option definitions in a man page to properly\n\t\t\t\t * extract short options from option definitions such as:\n\t\t\t\t * \t.It Fl r Ar seconds (taken from date(1)).\n\t\t\t\t *\/\n\t\t\t\tif ((space_index = line.find(\" \", opt_position + 1, 1))\n\t\t\t\t\t\t!= std::string::npos)\n\t\t\t\t\topt_name = line.substr(opt_position, space_index - opt_position);\n\t\t\t\telse\n\t\t\t\t\topt_name = line.substr(opt_position);\n\n\t\t\t\t\/*\n\t\t\t\t * Check if the identified option matches the identifier.\n\t\t\t\t * \"opt_list.back()\" is the previously checked option, the\n\t\t\t\t * description of which is now stored in \"buffer\".\n\t\t\t\t *\/\n\t\t\t\tif (!opt_list.empty() &&\n\t\t\t\t\t\t(opt_map_iter = opt_map.find(opt_list.back()))\n\t\t\t\t\t\t!= opt_map.end() &&\n\t\t\t\t\t\tbuffer.find((opt_map_iter->second).keyword) != std::string::npos) {\n\t\t\t\t\tidentified_opt_list.push_back(&(opt_map_iter->second));\n\n\t\t\t\t\t\/*\n\t\t\t\t\t * Since the usage of the option under test\n\t\t\t\t\t * is known, we remove it from \"opt_list\".\n\t\t\t\t\t *\/\n\t\t\t\t\topt_list.pop_back();\n\t\t\t\t}\n\n\t\t\t\t\/* Update the list of valid options. *\/\n\t\t\t\topt_list.push_back(opt_name);\n\n\t\t\t\t\/* Empty the buffer for next option's description. *\/\n\t\t\t\tbuffer.clear();\n\t\t\t} else {\n\t\t\t\t\/*\n\t\t\t\t * Collect the option description until next\n\t\t\t\t * valid option definition is encountered.\n\t\t\t\t *\/\n\t\t\t\tbuffer.append(line);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn identified_opt_list;\n}\n\n\/*\n * When pclose() is called on the stream returned by popen(),\n * it waits indefinitely for the created shell process to\n * terminate in cases where the shell command waits for the\n * user input via a blocking read (e.g. passwd(1)).\n * Hence, we define a custom function which alongside\n * returning the read-write file descriptors, also returns\n * the pid of the newly created (child) shell process. This\n * pid can later be used for sending a signal to the child.\n *\n * NOTE For the sake of completeness, we also specify actions\n * to be taken corresponding to the \"w\" (write) type. However,\n * in this context only the \"r\" (read) type will be required.\n *\/\n\nutils::PipeDescriptor*\nutils::POpen(const char *command)\n{\n\tint pdes[2];\n\tchar *argv[4];\n\tpid_t child_pid;\n\tPipeDescriptor *pipe_descr = (PipeDescriptor *)malloc(sizeof(PipeDescriptor));\n\n\t\/* Create a pipe with ~\n\t * - pdes[READ]: read end\n\t * - pdes[WRITE]: write end\n\t *\/\n\tif (pipe2(pdes, O_CLOEXEC) < 0)\n\t\treturn NULL;\n\n\tpipe_descr->readfd = pdes[READ];\n\tpipe_descr->writefd = pdes[WRITE];\n\n\targv[0] = (char *)\"sh\"; \t\/* Type-cast to avoid compiler warning [-Wwrite-strings]. *\/\n\targv[1] = (char *)\"-c\";\n\targv[2] = (char *)command;\n\targv[3] = NULL;\n\n\tswitch (child_pid = vfork()) {\n\t\tcase -1: \t\t\/* Error. *\/\n\t\t\treturn NULL;\n\t\tcase 0: \t\t\/* Child. *\/\n\t\t\t\/*\n\t\t\t * TODO Verify if the following operations on both read\n\t\t\t * and write file-descriptors (irrespective of the value\n\t\t\t * of 'type', which is no longer being used) is safe.\n\t\t\t *\/\n\t\t\tif (pdes[WRITE] != STDOUT_FILENO)\n\t\t\t\tdup2(pdes[WRITE], STDOUT_FILENO);\n\t\t\telse\n\t\t\t\tfcntl(pdes[WRITE], F_SETFD, 0);\n\t\t\tif (pdes[READ] != STDIN_FILENO)\n\t\t\t\tdup2(pdes[READ], STDIN_FILENO);\n\t\t\telse\n\t\t\t\tfcntl(pdes[READ], F_SETFD, 0);\n\n\t\t\t\/*\n\t\t\t * For current usecase, it might so happen that the child gets\n\t\t\t * stuck on a blocking read (e.g. passwd(1)) waiting for user\n\t\t\t * input. In that case the child will be killed via a signal.\n\t\t\t * To avoid any effect on the parent's execution, we place the\n\t\t\t * child in a separate process group with pgid set as \"child_pid\".\n\t\t\t *\/\n\t\t\tsetpgid(child_pid, child_pid);\n\t\t\texecve(\"\/bin\/sh\", argv, NULL);\n\t\t\texit(127);\n\t}\n\n\tpipe_descr->pid = child_pid;\n\n\treturn pipe_descr;\n}\n\n\/*\n * Executes the passed argument \"command\" in a shell\n * and returns its output and the exit status.\n *\/\nstd::pair<std::string, int>\nutils::Execute(std::string command)\n{\n\tint result;\n\tstd::array<char, BUFSIZE> buffer;\n\tstd::string usage_output;\n\tstruct timeval tv;\n\tfd_set readfds;\n\tFILE *pipe;\n\tPipeDescriptor *pipe_descr;\n\n\tDEBUGP(\"Executing: %s\\n\", command.c_str());\n\n\tpipe_descr = utils::POpen(command.c_str());\n\tif (pipe_descr == NULL) {\n\t\tperror(\"utils::POpen()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* Close the unrequired file-descriptor. *\/\n\tclose(pipe_descr->writefd);\n\n\tpipe = fdopen(pipe_descr->readfd, \"r\");\n\tfree(pipe_descr);\n\tif (pipe == NULL) {\n\t\tclose(pipe_descr->readfd);\n\t\tperror(\"fdopen()\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/*\n\t * Set a timeout value for the spawned shell\n\t * process to complete its execution.\n\t *\/\n\ttv.tv_sec = TIMEOUT;\n\ttv.tv_usec = 0;\n\n\tFD_ZERO(&readfds);\n\tFD_SET(fileno(pipe), &readfds);\n\tresult = select(fileno(pipe) + 1, &readfds, NULL, NULL, &tv);\n\n\tif (result > 0) {\n\t\twhile (!feof(pipe))\n\t\t\tif (fgets(buffer.data(), BUFSIZE, pipe) != NULL)\n\t\t\t\tusage_output += buffer.data();\n\t} else if (result == -1) {\n\t\tperror(\"select()\");\n\t\tif (kill(pipe_descr->pid, SIGTERM) < 0)\n\t\t\tperror(\"kill()\");\n\t} else if (result == 0) {\n\t\t\/*\n\t\t * We gave a relaxed value of 2 seconds for the shell process\n\t\t * to complete it's execution. If at this point it is still\n\t\t * alive, it (most probably) is stuck on a blocking read\n\t\t * waiting for the user input. Since few of the utilities\n\t\t * performing such blocking reads don't respond to SIGINT\n\t\t * (e.g. pax(1)), we terminate the shell process via SIGTERM.\n\t\t *\/\n\t\tif (kill(pipe_descr->pid, SIGTERM) < 0)\n\t\t\tperror(\"kill()\");\n\t}\n\n\treturn std::make_pair<std::string, int>\n\t\t((std::string)usage_output, WEXITSTATUS(pclose(pipe)));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014, Chris Pearce & Yun Sing Koh\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\r\n#include <time.h>\r\n#include \"utils.h\"\r\n#include \"debug.h\"\r\n#include \"Options.h\"\r\n#include <string>\r\n#include <vector>\r\n#include <stdarg.h>\r\n#include <fstream>\r\n#include \"InvertedDataSetIndex.h\"\r\n#include \"List.h\"\r\n#include \"PatternStream.h\"\r\n#include \"ItemMap.h\"\r\n#include <memory>\r\n\r\nusing namespace std;\r\n\r\n\/*\r\nUsage:\r\n\r\n vector<string> tokens;\r\n\t string str(\"Split,me up!Word2 Word3.\");\r\n\t Tokenize(str, tokens, \",<'> \" );\r\n\t vector <string>::iterator iter;\r\n\t for(iter = tokens.begin();iter!=tokens.end();iter++){\r\n\t \t\tcout<< (*iter) << endl;\r\n\t}\r\n\r\n*\/\r\n\r\nvoid Tokenize(const string& str,\r\n vector<string>& tokens,\r\n const string& delimiters) {\r\n \/\/ Skip delimiters at beginning.\r\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\r\n \/\/ Find first \"non-delimiter\".\r\n string::size_type pos = str.find_first_of(delimiters, lastPos);\r\n while (string::npos != pos || string::npos != lastPos) {\r\n \/\/ Found a token, add it to the vector.\r\n tokens.push_back(str.substr(lastPos, pos - lastPos));\r\n \/\/ Skip delimiters. Note the \"not_of\"\r\n lastPos = str.find_first_not_of(delimiters, pos);\r\n \/\/ Find next \"non-delimiter\"\r\n pos = str.find_first_of(delimiters, lastPos);\r\n }\r\n}\r\n\r\n\r\n\/\/ Trims leading and trailing whitespace.\r\nstring& TrimWhiteSpace(string& str) {\r\n char const* delims = \" \\t\\r\\n\";\r\n\r\n \/\/ trim leading whitespace\r\n string::size_type notwhite = str.find_first_not_of(delims);\r\n str.erase(0, notwhite);\r\n\r\n \/\/ trim trailing whitespace\r\n notwhite = str.find_last_not_of(delims);\r\n str.erase(notwhite + 1);\r\n\r\n return str;\r\n}\r\n\r\nstring TrimWhiteSpace(const string& str) {\r\n string s = str;\r\n return TrimWhiteSpace(s);\r\n}\r\n\r\n\r\n\r\n\r\nunsigned countUsingLoop(unsigned x) {\r\n unsigned r = 0;\r\n while (x != 0) {\r\n x = x & (x - 1);\r\n r++;\r\n }\r\n return r;\r\n}\r\n\r\n\r\nunsigned gBitCountLookupTable[256];\r\n\r\nunsigned PopulationCount(unsigned x) {\r\n return\r\n gBitCountLookupTable[x & 0xFF] +\r\n gBitCountLookupTable[(x & 0xFF00) >> 8] +\r\n gBitCountLookupTable[(x & 0xFF0000) >> 16] +\r\n gBitCountLookupTable[(x & 0xFF000000) >> 24];\r\n}\r\n\r\nvoid InitializePopulationCount() {\r\n for (int i = 0; i < 256; i++) {\r\n gBitCountLookupTable[i] = countUsingLoop(i);\r\n }\r\n}\r\n\r\nstatic FILE* gOutputLog = 0;\r\n\r\nbool InitLog(Options& options) {\r\n if (gOutputLog == 0) {\r\n string filename = GetOutputLogFileName(options.outputFilePrefix);\r\n gOutputLog = fopen(filename.c_str(), \"w\");\r\n if (!gOutputLog) {\r\n cerr << \"Fail: Can't open log file '\" << filename << \"'\\n\";\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nvoid CloseLog() {\r\n fclose(gOutputLog);\r\n}\r\n\r\nvoid Log(const char* msg, ...) {\r\n va_list argp;\r\n va_start(argp, msg);\r\n vfprintf(stdout, msg, argp);\r\n if (gOutputLog) {\r\n vfprintf(gOutputLog, msg, argp);\r\n }\r\n va_end(argp);\r\n}\r\n\r\n\r\nbool DumpItemSets(vector<ItemSet>& aResult,\r\n DataSet* aIndex,\r\n Options& options) {\r\n if (options.countItemSetsOnly) {\r\n return true;\r\n }\r\n\r\n string filename = GetOutputItemsetsFileName(options.outputFilePrefix);\r\n ofstream out(filename.c_str());\r\n ASSERT(out);\r\n if (!out) {\r\n cerr << \"Fail: Can't open '\" << filename << \"' for writing\\n\";\r\n return false;\r\n }\r\n for (unsigned i = 0; i < aResult.size(); i++) {\r\n string s = aResult[i];\r\n double sup = aIndex->Support(aResult[i]);\r\n if (sup < options.minSup) {\r\n cerr << \"WARNING: itemset \" << s << \" has support of \"\r\n << sup << \", but minsup=\" << options.minSup << endl;\r\n }\r\n out << s << \",\" << sup << \"\\n\";\r\n }\r\n out.close();\r\n return true;\r\n}\r\n\r\ndouble Confidence(Rule& r, DataSet* aIndex) {\r\n ItemSet AB(r.mAntecedent, r.mConsequent);\r\n return (double)aIndex->Support(AB) \/ (double)aIndex->Support(r.mAntecedent);\r\n}\r\n\r\ndouble Lift(Rule& r, DataSet* aIndex) {\r\n return Confidence(r, aIndex) \/ (double)aIndex->Support(r.mConsequent);\r\n}\r\n\r\nvoid GenerateRulesRecursize(long& aNumRules,\r\n double minConf,\r\n double minLift,\r\n DataSet* aIndex,\r\n set<Item>::iterator itr,\r\n set<Item>::iterator end,\r\n ItemSet& aAntecedent,\r\n ItemSet& aConsequent,\r\n bool aCountRulesOnly,\r\n ostream& out) {\r\n if (itr == end) {\r\n if (aConsequent.Size() == 0 || aAntecedent.Size() == 0) {\r\n return;\r\n }\r\n\r\n \/\/ Calculate the confidence, lift, and support of the rule.\r\n double confidence = 0;\r\n double support = 0;\r\n double lift = 0;\r\n\r\n {\r\n ItemSet AB(aAntecedent, aConsequent);\r\n support = aIndex->Support(AB);\r\n confidence = support \/ (double)aIndex->Support(aAntecedent);\r\n lift = confidence \/ (double)aIndex->Support(aConsequent);\r\n }\r\n\r\n if (confidence > minConf &&\r\n lift > minLift) {\r\n aNumRules++;\r\n Rule r;\r\n r.mAntecedent = aAntecedent;\r\n r.mConsequent = aConsequent;\r\n string s = r;\r\n if (!aCountRulesOnly) {\r\n out << s << \",\" << confidence << \",\" << lift << \",\" << support* aIndex->NumTransactions() << endl;\r\n }\r\n }\r\n return;\r\n }\r\n\r\n Item item = *itr;\r\n itr++;\r\n\r\n aAntecedent.mItems.insert(item);\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex, itr, end, aAntecedent, aConsequent, aCountRulesOnly, out);\r\n aAntecedent.mItems.erase(item);\r\n\r\n aConsequent.mItems.insert(item);\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex, itr, end, aAntecedent, aConsequent, aCountRulesOnly, out);\r\n aConsequent.mItems.erase(item);\r\n}\r\n\r\nvoid GenerateRules(PatternInputStream& input,\r\n double minConf,\r\n double minLift,\r\n long& aNumRules,\r\n DataSet* aIndex,\r\n string aOutputPrefix,\r\n bool countRulesOnly) {\r\n time_t startTime = time(0);\r\n\r\n aNumRules = 0;\r\n\r\n string filename = GetOutputRuleFileName(aOutputPrefix);\r\n ofstream out(filename);\r\n ASSERT(out.is_open());\r\n\r\n ItemSet candidate;\r\n while (!(candidate = input.Read()).IsNull()) {\r\n ItemSet antecedent, consequent;\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex,\r\n candidate.mItems.begin(), candidate.mItems.end(),\r\n antecedent, consequent, countRulesOnly, out);\r\n }\r\n\r\n time_t timeTaken = time(0) - startTime;\r\n Log(\"Generated %d rules in %lld seconds%s\\n\", aNumRules, timeTaken,\r\n (countRulesOnly ? \" (not saved to disk)\" : \"\"));\r\n}\r\n\r\n\r\nvoid GenerateRules(const vector<ItemSet>& aItemsets,\r\n double minConf,\r\n double minLift,\r\n long& aNumRules,\r\n DataSet* aIndex,\r\n string aOutputPrefix,\r\n bool countRulesOnly) {\r\n time_t startTime = time(0);\r\n\r\n aNumRules = 0;\r\n\r\n string filename = GetOutputRuleFileName(aOutputPrefix);\r\n ofstream out(filename);\r\n ASSERT(out.is_open());\r\n\r\n for (unsigned i = 0; i < aItemsets.size(); i++) {\r\n ItemSet candidate = aItemsets[i];\r\n ItemSet antecedent, consequent;\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex,\r\n candidate.mItems.begin(), candidate.mItems.end(),\r\n antecedent, consequent, countRulesOnly, out);\r\n }\r\n\r\n time_t timeTaken = time(0) - startTime;\r\n Log(\"Generated %d rules in %lld seconds\\n\", aNumRules, timeTaken);\r\n}\r\n\r\n\r\nvoid List_Test() {\r\n List<int> list;\r\n for (int i = 0; i <= 20; i++) {\r\n list.Append(i);\r\n }\r\n ASSERT(list.GetSize() == 21);\r\n\r\n {\r\n vector<int> L;\r\n List<int>::Iterator* itr = list.Begin();\r\n while (itr->HasNext()) {\r\n L.push_back(itr->Next());\r\n }\r\n for (int i = 0; i <= 20; i++) {\r\n ASSERT(L[i] == i);\r\n }\r\n delete itr;\r\n }\r\n\r\n List<int>::Iterator* itr = list.Begin();\r\n int expected = 0;\r\n while (itr->HasNext()) {\r\n List<int>::Token token = itr->GetToken();\r\n ASSERT(token.IsInList());\r\n int x = itr->Next();\r\n if (expected % 2 == 0) {\r\n list.Erase(token);\r\n ASSERT(!token.IsInList());\r\n }\r\n ASSERT(x == expected);\r\n expected++;\r\n }\r\n ASSERT(expected == 21);\r\n ASSERT(list.GetSize() == 10);\r\n ASSERT(!itr->HasNext());\r\n for (int i = 21; i <= 40; i++) {\r\n list.Append(i);\r\n }\r\n ASSERT(itr->HasNext());\r\n while (itr->HasNext()) {\r\n int x = itr->Next();\r\n ASSERT(x == expected);\r\n expected++;\r\n }\r\n ASSERT(!itr->HasNext());\r\n\r\n list.Prepend(-1);\r\n ASSERT(!itr->HasNext());\r\n itr = list.Begin();\r\n ASSERT(itr->Next() == -1);\r\n delete itr;\r\n}\r\n\r\nvoid ItemMap_Test() {\r\n ItemMap<unsigned> m;\r\n for (unsigned i = 1; i < 1000; ++i) {\r\n Item item(i);\r\n m.Set(item, i);\r\n }\r\n\r\n ItemMap<unsigned>::Iterator itr = m.GetIterator();\r\n unsigned expected = 1;\r\n while (itr.HasNext()) {\r\n Item item = itr.GetKey();\r\n unsigned value = itr.GetValue();\r\n ASSERT(item.GetId() == expected);\r\n ASSERT(value == expected);\r\n itr.Next();\r\n expected++;\r\n }\r\n ASSERT(expected == 1000);\r\n}\r\n\r\n\/\/ Converts a string in \"a,b,c\" form to a vector of items [a,b,c].\r\n\/\/ Useful for testing.\r\nstd::vector<Item> ToItemVector(const std::string& _items) {\r\n std::vector<Item> items;\r\n std::vector<std::string> tokens;\r\n Tokenize(_items, tokens, \", \");\r\n items.reserve(tokens.size());\r\n for (const string& token : tokens) {\r\n items.push_back(Item(token));\r\n }\r\n return move(items);\r\n}\r\n<commit_msg>Make ItemMap_Test() not depend on the order of iteration.<commit_after>\/\/ Copyright 2014, Chris Pearce & Yun Sing Koh\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\r\n#include <time.h>\r\n#include \"utils.h\"\r\n#include \"debug.h\"\r\n#include \"Options.h\"\r\n#include <string>\r\n#include <vector>\r\n#include <stdarg.h>\r\n#include <fstream>\r\n#include \"InvertedDataSetIndex.h\"\r\n#include \"List.h\"\r\n#include \"PatternStream.h\"\r\n#include \"ItemMap.h\"\r\n#include <memory>\r\n\r\nusing namespace std;\r\n\r\n\/*\r\nUsage:\r\n\r\n vector<string> tokens;\r\n\t string str(\"Split,me up!Word2 Word3.\");\r\n\t Tokenize(str, tokens, \",<'> \" );\r\n\t vector <string>::iterator iter;\r\n\t for(iter = tokens.begin();iter!=tokens.end();iter++){\r\n\t \t\tcout<< (*iter) << endl;\r\n\t}\r\n\r\n*\/\r\n\r\nvoid Tokenize(const string& str,\r\n vector<string>& tokens,\r\n const string& delimiters) {\r\n \/\/ Skip delimiters at beginning.\r\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\r\n \/\/ Find first \"non-delimiter\".\r\n string::size_type pos = str.find_first_of(delimiters, lastPos);\r\n while (string::npos != pos || string::npos != lastPos) {\r\n \/\/ Found a token, add it to the vector.\r\n tokens.push_back(str.substr(lastPos, pos - lastPos));\r\n \/\/ Skip delimiters. Note the \"not_of\"\r\n lastPos = str.find_first_not_of(delimiters, pos);\r\n \/\/ Find next \"non-delimiter\"\r\n pos = str.find_first_of(delimiters, lastPos);\r\n }\r\n}\r\n\r\n\r\n\/\/ Trims leading and trailing whitespace.\r\nstring& TrimWhiteSpace(string& str) {\r\n char const* delims = \" \\t\\r\\n\";\r\n\r\n \/\/ trim leading whitespace\r\n string::size_type notwhite = str.find_first_not_of(delims);\r\n str.erase(0, notwhite);\r\n\r\n \/\/ trim trailing whitespace\r\n notwhite = str.find_last_not_of(delims);\r\n str.erase(notwhite + 1);\r\n\r\n return str;\r\n}\r\n\r\nstring TrimWhiteSpace(const string& str) {\r\n string s = str;\r\n return TrimWhiteSpace(s);\r\n}\r\n\r\n\r\n\r\n\r\nunsigned countUsingLoop(unsigned x) {\r\n unsigned r = 0;\r\n while (x != 0) {\r\n x = x & (x - 1);\r\n r++;\r\n }\r\n return r;\r\n}\r\n\r\n\r\nunsigned gBitCountLookupTable[256];\r\n\r\nunsigned PopulationCount(unsigned x) {\r\n return\r\n gBitCountLookupTable[x & 0xFF] +\r\n gBitCountLookupTable[(x & 0xFF00) >> 8] +\r\n gBitCountLookupTable[(x & 0xFF0000) >> 16] +\r\n gBitCountLookupTable[(x & 0xFF000000) >> 24];\r\n}\r\n\r\nvoid InitializePopulationCount() {\r\n for (int i = 0; i < 256; i++) {\r\n gBitCountLookupTable[i] = countUsingLoop(i);\r\n }\r\n}\r\n\r\nstatic FILE* gOutputLog = 0;\r\n\r\nbool InitLog(Options& options) {\r\n if (gOutputLog == 0) {\r\n string filename = GetOutputLogFileName(options.outputFilePrefix);\r\n gOutputLog = fopen(filename.c_str(), \"w\");\r\n if (!gOutputLog) {\r\n cerr << \"Fail: Can't open log file '\" << filename << \"'\\n\";\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\nvoid CloseLog() {\r\n fclose(gOutputLog);\r\n}\r\n\r\nvoid Log(const char* msg, ...) {\r\n va_list argp;\r\n va_start(argp, msg);\r\n vfprintf(stdout, msg, argp);\r\n if (gOutputLog) {\r\n vfprintf(gOutputLog, msg, argp);\r\n }\r\n va_end(argp);\r\n}\r\n\r\n\r\nbool DumpItemSets(vector<ItemSet>& aResult,\r\n DataSet* aIndex,\r\n Options& options) {\r\n if (options.countItemSetsOnly) {\r\n return true;\r\n }\r\n\r\n string filename = GetOutputItemsetsFileName(options.outputFilePrefix);\r\n ofstream out(filename.c_str());\r\n ASSERT(out);\r\n if (!out) {\r\n cerr << \"Fail: Can't open '\" << filename << \"' for writing\\n\";\r\n return false;\r\n }\r\n for (unsigned i = 0; i < aResult.size(); i++) {\r\n string s = aResult[i];\r\n double sup = aIndex->Support(aResult[i]);\r\n if (sup < options.minSup) {\r\n cerr << \"WARNING: itemset \" << s << \" has support of \"\r\n << sup << \", but minsup=\" << options.minSup << endl;\r\n }\r\n out << s << \",\" << sup << \"\\n\";\r\n }\r\n out.close();\r\n return true;\r\n}\r\n\r\ndouble Confidence(Rule& r, DataSet* aIndex) {\r\n ItemSet AB(r.mAntecedent, r.mConsequent);\r\n return (double)aIndex->Support(AB) \/ (double)aIndex->Support(r.mAntecedent);\r\n}\r\n\r\ndouble Lift(Rule& r, DataSet* aIndex) {\r\n return Confidence(r, aIndex) \/ (double)aIndex->Support(r.mConsequent);\r\n}\r\n\r\nvoid GenerateRulesRecursize(long& aNumRules,\r\n double minConf,\r\n double minLift,\r\n DataSet* aIndex,\r\n set<Item>::iterator itr,\r\n set<Item>::iterator end,\r\n ItemSet& aAntecedent,\r\n ItemSet& aConsequent,\r\n bool aCountRulesOnly,\r\n ostream& out) {\r\n if (itr == end) {\r\n if (aConsequent.Size() == 0 || aAntecedent.Size() == 0) {\r\n return;\r\n }\r\n\r\n \/\/ Calculate the confidence, lift, and support of the rule.\r\n double confidence = 0;\r\n double support = 0;\r\n double lift = 0;\r\n\r\n {\r\n ItemSet AB(aAntecedent, aConsequent);\r\n support = aIndex->Support(AB);\r\n confidence = support \/ (double)aIndex->Support(aAntecedent);\r\n lift = confidence \/ (double)aIndex->Support(aConsequent);\r\n }\r\n\r\n if (confidence > minConf &&\r\n lift > minLift) {\r\n aNumRules++;\r\n Rule r;\r\n r.mAntecedent = aAntecedent;\r\n r.mConsequent = aConsequent;\r\n string s = r;\r\n if (!aCountRulesOnly) {\r\n out << s << \",\" << confidence << \",\" << lift << \",\" << support* aIndex->NumTransactions() << endl;\r\n }\r\n }\r\n return;\r\n }\r\n\r\n Item item = *itr;\r\n itr++;\r\n\r\n aAntecedent.mItems.insert(item);\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex, itr, end, aAntecedent, aConsequent, aCountRulesOnly, out);\r\n aAntecedent.mItems.erase(item);\r\n\r\n aConsequent.mItems.insert(item);\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex, itr, end, aAntecedent, aConsequent, aCountRulesOnly, out);\r\n aConsequent.mItems.erase(item);\r\n}\r\n\r\nvoid GenerateRules(PatternInputStream& input,\r\n double minConf,\r\n double minLift,\r\n long& aNumRules,\r\n DataSet* aIndex,\r\n string aOutputPrefix,\r\n bool countRulesOnly) {\r\n time_t startTime = time(0);\r\n\r\n aNumRules = 0;\r\n\r\n string filename = GetOutputRuleFileName(aOutputPrefix);\r\n ofstream out(filename);\r\n ASSERT(out.is_open());\r\n\r\n ItemSet candidate;\r\n while (!(candidate = input.Read()).IsNull()) {\r\n ItemSet antecedent, consequent;\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex,\r\n candidate.mItems.begin(), candidate.mItems.end(),\r\n antecedent, consequent, countRulesOnly, out);\r\n }\r\n\r\n time_t timeTaken = time(0) - startTime;\r\n Log(\"Generated %d rules in %lld seconds%s\\n\", aNumRules, timeTaken,\r\n (countRulesOnly ? \" (not saved to disk)\" : \"\"));\r\n}\r\n\r\n\r\nvoid GenerateRules(const vector<ItemSet>& aItemsets,\r\n double minConf,\r\n double minLift,\r\n long& aNumRules,\r\n DataSet* aIndex,\r\n string aOutputPrefix,\r\n bool countRulesOnly) {\r\n time_t startTime = time(0);\r\n\r\n aNumRules = 0;\r\n\r\n string filename = GetOutputRuleFileName(aOutputPrefix);\r\n ofstream out(filename);\r\n ASSERT(out.is_open());\r\n\r\n for (unsigned i = 0; i < aItemsets.size(); i++) {\r\n ItemSet candidate = aItemsets[i];\r\n ItemSet antecedent, consequent;\r\n GenerateRulesRecursize(aNumRules, minConf, minLift, aIndex,\r\n candidate.mItems.begin(), candidate.mItems.end(),\r\n antecedent, consequent, countRulesOnly, out);\r\n }\r\n\r\n time_t timeTaken = time(0) - startTime;\r\n Log(\"Generated %d rules in %lld seconds\\n\", aNumRules, timeTaken);\r\n}\r\n\r\n\r\nvoid List_Test() {\r\n List<int> list;\r\n for (int i = 0; i <= 20; i++) {\r\n list.Append(i);\r\n }\r\n ASSERT(list.GetSize() == 21);\r\n\r\n {\r\n vector<int> L;\r\n List<int>::Iterator* itr = list.Begin();\r\n while (itr->HasNext()) {\r\n L.push_back(itr->Next());\r\n }\r\n for (int i = 0; i <= 20; i++) {\r\n ASSERT(L[i] == i);\r\n }\r\n delete itr;\r\n }\r\n\r\n List<int>::Iterator* itr = list.Begin();\r\n int expected = 0;\r\n while (itr->HasNext()) {\r\n List<int>::Token token = itr->GetToken();\r\n ASSERT(token.IsInList());\r\n int x = itr->Next();\r\n if (expected % 2 == 0) {\r\n list.Erase(token);\r\n ASSERT(!token.IsInList());\r\n }\r\n ASSERT(x == expected);\r\n expected++;\r\n }\r\n ASSERT(expected == 21);\r\n ASSERT(list.GetSize() == 10);\r\n ASSERT(!itr->HasNext());\r\n for (int i = 21; i <= 40; i++) {\r\n list.Append(i);\r\n }\r\n ASSERT(itr->HasNext());\r\n while (itr->HasNext()) {\r\n int x = itr->Next();\r\n ASSERT(x == expected);\r\n expected++;\r\n }\r\n ASSERT(!itr->HasNext());\r\n\r\n list.Prepend(-1);\r\n ASSERT(!itr->HasNext());\r\n itr = list.Begin();\r\n ASSERT(itr->Next() == -1);\r\n delete itr;\r\n}\r\n\r\nvoid ItemMap_Test() {\r\n std::map<int, unsigned> expected;\r\n ItemMap<unsigned> m;\r\n for (unsigned i = 1; i < 1000; ++i) {\r\n Item item(i);\r\n m.Set(item, i);\r\n expected[item.GetId()] = i;\r\n }\r\n\r\n ItemMap<unsigned>::Iterator itr = m.GetIterator();\r\n int count = 0;\r\n while (itr.HasNext()) {\r\n Item item = itr.GetKey();\r\n unsigned value = itr.GetValue();\r\n ASSERT(value == expected[item.GetId()]);\r\n itr.Next();\r\n count++;\r\n }\r\n ASSERT(count == expected.size());\r\n}\r\n\r\n\/\/ Converts a string in \"a,b,c\" form to a vector of items [a,b,c].\r\n\/\/ Useful for testing.\r\nstd::vector<Item> ToItemVector(const std::string& _items) {\r\n std::vector<Item> items;\r\n std::vector<std::string> tokens;\r\n Tokenize(_items, tokens, \", \");\r\n items.reserve(tokens.size());\r\n for (const string& token : tokens) {\r\n items.push_back(Item(token));\r\n }\r\n return move(items);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\n\/* Callable objects that encapsulate an object's method. These are almost certainly duplicates\nof something in Boost... *\/\n\ntemplate<class obj_t, class ret_t>\nstruct no_arg_method_caller_t {\n obj_t *obj;\n ret_t (obj_t::*m)();\n no_arg_method_caller_t(obj_t *o, ret_t (obj_t::*m)()) : obj(o), m(m) { }\n ret_t operator()() { return (obj->*m)(); }\n};\n\ntemplate<class obj_t, class arg1_t, class ret_t>\nstruct one_arg_method_caller_t {\n obj_t *obj;\n ret_t (obj_t::*m)(arg1_t);\n arg1_t arg1;\n one_arg_method_caller_t(obj_t *o, ret_t (obj_t::*m)(arg1_t), arg1_t a1) : obj(o), m(m), arg1(a1) { }\n ret_t operator()() { return (obj->*m)(arg1); }\n};\n\ntemplate<class obj_t, class arg1_t, class arg2_t, class ret_t>\nstruct two_arg_method_caller_t {\n obj_t *obj;\n ret_t (obj_t::*m)(arg1_t, arg2_t);\n arg1_t arg1;\n arg2_t arg2;\n two_arg_method_caller_t(obj_t *o, ret_t (obj_t::*m)(arg1_t, arg2_t), arg1_t a1, arg2_t a2)\n : obj(o), m(m), arg1(a1), arg2(a2) { }\n ret_t operator()() { return (obj->*m)(arg1, arg2); }\n};\n\ntemplate<class obj_t, class arg1_t, class arg2_t, class arg3_t, class arg4_t, class ret_t>\nstruct four_arg_method_caller_t {\n obj_t *obj;\n ret_t (obj_t::*m)(arg1_t, arg2_t, arg3_t, arg4_t);\n arg1_t arg1;\n arg2_t arg2;\n arg3_t arg3;\n arg4_t arg4;\n four_arg_method_caller_t(obj_t *o, ret_t(obj_t::*m)(arg1_t, arg2_t, arg3_t, arg4_t), arg1_t a1, arg2_t a2, arg3_t a3, arg4_t a4)\n : obj(o), m(m), arg1(a1), arg2(a2), arg3(a3), arg4(a4) { }\n ret_t operator()() { return (obj->*m)(arg1, arg2, arg3, arg4); }\n};\n\n\/* Functions to do something on another core in a way that is more convenient than\ncontinue_on_thread() is. *\/\n\ntemplate<class callable_t>\nstruct thread_doer_t :\n public thread_message_t,\n public home_thread_mixin_t\n{\n callable_t callable;\n int thread;\n enum state_t {\n state_go_to_core,\n state_go_home\n } state;\n \n thread_doer_t(const callable_t &callable, int thread)\n : callable(callable), thread(thread), state(state_go_to_core) { }\n \n void run() {\n state = state_go_to_core;\n if (continue_on_thread(thread, this)) {\n do_perform_job();\n }\n }\n \n void do_perform_job() {\n rassert(thread == get_thread_id());\n callable();\n do_return_home();\n }\n \n void do_return_home() {\n state = state_go_home;\n if (continue_on_thread(home_thread, this)) delete this;\n }\n \n void on_thread_switch() {\n switch (state) {\n case state_go_to_core:\n do_perform_job();\n return;\n case state_go_home:\n delete this;\n return;\n default:\n unreachable(\"Bad state.\");\n }\n }\n};\n\ntemplate<class callable_t>\nvoid do_on_thread(int thread, const callable_t &callable) {\n thread_doer_t<callable_t> *fsm = new thread_doer_t<callable_t>(callable, thread);\n fsm->run();\n}\ntemplate<class obj_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)()) {\n do_on_thread(thread, no_arg_method_caller_t<obj_t, void>(obj, on_other_core));\n}\ntemplate<class obj_t, class arg1_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t), arg1_t arg1) {\n do_on_thread(thread, one_arg_method_caller_t<obj_t, arg1_t, void>(obj, on_other_core, arg1));\n}\ntemplate<class obj_t, class arg1_t, class arg2_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t, arg2_t), arg1_t arg1, arg2_t arg2) {\n do_on_thread(thread, two_arg_method_caller_t<obj_t, arg1_t, arg2_t, void>(obj, on_other_core, arg1, arg2));\n}\ntemplate<class obj_t, class arg1_t, class arg2_t, class arg3_t, class arg4_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t, arg2_t, arg3_t, arg4_t), arg1_t arg1, arg2_t arg2, arg3_t arg3, arg4_t arg4) {\n do_on_thread(thread, four_arg_method_caller_t<obj_t, arg1_t, arg2_t, arg3_t, arg4_t, void>(obj, on_other_core, arg1, arg2, arg3, arg4));\n}\n\ntemplate<class callable_t>\nstruct later_doer_t :\n public thread_message_t\n{\n callable_t callable;\n \n later_doer_t(const callable_t &callable)\n : callable(callable) {\n call_later_on_this_thread(this);\n }\n \n void on_thread_switch() {\n callable();\n delete this;\n }\n};\n\n\ntemplate<class callable_t>\nvoid do_later(const callable_t &callable) {\n new later_doer_t<callable_t>(callable);\n}\n\ntemplate<class obj_t>\nvoid do_later(obj_t *obj, void (obj_t::*later)()) {\n return do_later(no_arg_method_caller_t<obj_t, void>(obj, later));\n}\n\ntemplate<class obj_t, class arg1_t>\nvoid do_later(obj_t *obj, void (obj_t::*later)(arg1_t), arg1_t arg1) {\n return do_later(one_arg_method_caller_t<obj_t, arg1_t, void>(obj, later, arg1));\n}\n<commit_msg>Got rid of no_arg, one_arg, *method_caller_t in utils.tcc.<commit_after>#include <boost\/bind.hpp>\n\n\/* Functions to do something on another core in a way that is more convenient than\ncontinue_on_thread() is. *\/\n\ntemplate<class callable_t>\nstruct thread_doer_t :\n public thread_message_t,\n public home_thread_mixin_t\n{\n callable_t callable;\n int thread;\n enum state_t {\n state_go_to_core,\n state_go_home\n } state;\n \n thread_doer_t(const callable_t &callable, int thread)\n : callable(callable), thread(thread), state(state_go_to_core) { }\n \n void run() {\n state = state_go_to_core;\n if (continue_on_thread(thread, this)) {\n do_perform_job();\n }\n }\n \n void do_perform_job() {\n rassert(thread == get_thread_id());\n callable();\n do_return_home();\n }\n \n void do_return_home() {\n state = state_go_home;\n if (continue_on_thread(home_thread, this)) delete this;\n }\n \n void on_thread_switch() {\n switch (state) {\n case state_go_to_core:\n do_perform_job();\n return;\n case state_go_home:\n delete this;\n return;\n default:\n unreachable(\"Bad state.\");\n }\n }\n};\n\ntemplate<class callable_t>\nvoid do_on_thread(int thread, const callable_t &callable) {\n thread_doer_t<callable_t> *fsm = new thread_doer_t<callable_t>(callable, thread);\n fsm->run();\n}\ntemplate<class obj_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)()) {\n do_on_thread(thread, boost::bind(on_other_core, obj));\n}\ntemplate<class obj_t, class arg1_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t), arg1_t arg1) {\n do_on_thread(thread, boost::bind(on_other_core, obj, arg1));\n}\ntemplate<class obj_t, class arg1_t, class arg2_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t, arg2_t), arg1_t arg1, arg2_t arg2) {\n do_on_thread(thread, boost::bind(on_other_core, obj, arg1, arg2));\n}\ntemplate<class obj_t, class arg1_t, class arg2_t, class arg3_t, class arg4_t>\nvoid do_on_thread(int thread, obj_t *obj, void (obj_t::*on_other_core)(arg1_t, arg2_t, arg3_t, arg4_t), arg1_t arg1, arg2_t arg2, arg3_t arg3, arg4_t arg4) {\n do_on_thread(thread, boost::bind(on_other_core, obj, arg1, arg2, arg3, arg4));\n}\n\ntemplate<class callable_t>\nstruct later_doer_t :\n public thread_message_t\n{\n callable_t callable;\n \n later_doer_t(const callable_t &callable)\n : callable(callable) {\n call_later_on_this_thread(this);\n }\n \n void on_thread_switch() {\n callable();\n delete this;\n }\n};\n\n\ntemplate<class callable_t>\nvoid do_later(const callable_t &callable) {\n new later_doer_t<callable_t>(callable);\n}\n\ntemplate<class obj_t>\nvoid do_later(obj_t *obj, void (obj_t::*later)()) {\n return do_later(boost::bind(later, obj));\n}\n\ntemplate<class obj_t, class arg1_t>\nvoid do_later(obj_t *obj, void (obj_t::*later)(arg1_t), arg1_t arg1) {\n return do_later(boost::bind(later, obj, arg1));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===---- QueryParser.cpp - clang-query command parser --------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"QueryParser.h\"\n#include \"Query.h\"\n#include \"QuerySession.h\"\n#include \"clang\/ASTMatchers\/Dynamic\/Parser.h\"\n#include \"clang\/Basic\/CharInfo.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include <set>\n\nusing namespace llvm;\nusing namespace clang::ast_matchers::dynamic;\n\nnamespace clang {\nnamespace query {\n\n\/\/ Lex any amount of whitespace followed by a \"word\" (any sequence of\n\/\/ non-whitespace characters) from the start of region [Begin,End). If no word\n\/\/ is found before End, return StringRef(). Begin is adjusted to exclude the\n\/\/ lexed region.\nStringRef QueryParser::lexWord() {\n while (true) {\n if (Begin == End)\n return StringRef(Begin, 0);\n\n if (!isWhitespace(*Begin))\n break;\n\n ++Begin;\n }\n\n const char *WordBegin = Begin;\n\n while (true) {\n ++Begin;\n\n if (Begin == End || isWhitespace(*Begin))\n return StringRef(WordBegin, Begin - WordBegin);\n }\n}\n\n\/\/ This is the StringSwitch-alike used by lexOrCompleteWord below. See that\n\/\/ function for details.\ntemplate <typename T> struct QueryParser::LexOrCompleteWord {\n StringSwitch<T> Switch;\n\n QueryParser *P;\n StringRef Word;\n \/\/ Set to the completion point offset in Word, or StringRef::npos if\n \/\/ completion point not in Word.\n size_t WordCompletionPos;\n\n LexOrCompleteWord(QueryParser *P, StringRef Word, size_t WCP)\n : Switch(Word), P(P), Word(Word), WordCompletionPos(WCP) {}\n\n template <unsigned N>\n LexOrCompleteWord &Case(const char (&S)[N], const T &Value,\n bool IsCompletion = true) {\n StringRef CaseStr(S, N - 1);\n\n if (WordCompletionPos == StringRef::npos)\n Switch.Case(S, Value);\n else if (N != 1 && IsCompletion && WordCompletionPos <= CaseStr.size() &&\n CaseStr.substr(0, WordCompletionPos) ==\n Word.substr(0, WordCompletionPos))\n P->Completions.push_back(LineEditor::Completion(\n (CaseStr.substr(WordCompletionPos) + \" \").str(), CaseStr));\n return *this;\n }\n\n T Default(const T& Value) const {\n return Switch.Default(Value);\n }\n};\n\n\/\/ Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object\n\/\/ that can be used like a llvm::StringSwitch<T>, but adds cases as possible\n\/\/ completions if the lexed word contains the completion point.\ntemplate <typename T>\nQueryParser::LexOrCompleteWord<T>\nQueryParser::lexOrCompleteWord(StringRef &Word) {\n Word = lexWord();\n size_t WordCompletionPos = StringRef::npos;\n if (CompletionPos && CompletionPos <= Word.data() + Word.size()) {\n if (CompletionPos < Word.data())\n WordCompletionPos = 0;\n else\n WordCompletionPos = CompletionPos - Word.data();\n }\n return LexOrCompleteWord<T>(this, Word, WordCompletionPos);\n}\n\nQueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {\n StringRef ValStr;\n unsigned Value = lexOrCompleteWord<unsigned>(ValStr)\n .Case(\"false\", 0)\n .Case(\"true\", 1)\n .Default(~0u);\n if (Value == ~0u) {\n return new InvalidQuery(\"expected 'true' or 'false', got '\" + ValStr + \"'\");\n }\n return new SetQuery<bool>(Var, Value);\n}\n\nQueryRef QueryParser::parseSetOutputKind() {\n StringRef ValStr;\n unsigned OutKind = lexOrCompleteWord<unsigned>(ValStr)\n .Case(\"diag\", OK_Diag)\n .Case(\"print\", OK_Print)\n .Case(\"dump\", OK_Dump)\n .Default(~0u);\n if (OutKind == ~0u) {\n return new InvalidQuery(\"expected 'diag', 'print' or 'dump', got '\" +\n ValStr + \"'\");\n }\n return new SetQuery<OutputKind>(&QuerySession::OutKind, OutputKind(OutKind));\n}\n\nQueryRef QueryParser::endQuery(QueryRef Q) {\n const char *Extra = Begin;\n if (!lexWord().empty())\n return new InvalidQuery(\"unexpected extra input: '\" +\n StringRef(Extra, End - Extra) + \"'\");\n return Q;\n}\n\nnamespace {\n\nenum ParsedQueryKind {\n PQK_Invalid,\n PQK_NoOp,\n PQK_Help,\n PQK_Let,\n PQK_Match,\n PQK_Set,\n PQK_Unlet,\n};\n\nenum ParsedQueryVariable {\n PQV_Invalid,\n PQV_Output,\n PQV_BindRoot\n};\n\nQueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {\n std::string ErrStr;\n llvm::raw_string_ostream OS(ErrStr);\n Diag.printToStreamFull(OS);\n return new InvalidQuery(OS.str());\n}\n\nclass QuerySessionSema : public Parser::RegistrySema {\npublic:\n QuerySessionSema(const QuerySession &QS) : QS(QS) {}\n\n ast_matchers::dynamic::VariantValue getNamedValue(StringRef Name) override {\n return QS.NamedValues.lookup(Name);\n }\n\nprivate:\n const QuerySession &QS;\n};\n\n} \/\/ namespace\n\nQueryRef QueryParser::completeMatcherExpression() {\n std::vector<MatcherCompletion> Comps = Parser::completeExpression(\n StringRef(Begin, End - Begin), CompletionPos - Begin);\n for (std::vector<MatcherCompletion>::iterator I = Comps.begin(),\n E = Comps.end();\n I != E; ++I) {\n Completions.push_back(LineEditor::Completion(I->TypedText, I->MatcherDecl));\n }\n return QueryRef();\n}\n\nQueryRef QueryParser::doParse() {\n StringRef CommandStr;\n ParsedQueryKind QKind = lexOrCompleteWord<ParsedQueryKind>(CommandStr)\n .Case(\"\", PQK_NoOp)\n .Case(\"help\", PQK_Help)\n .Case(\"m\", PQK_Match, \/*IsCompletion=*\/false)\n .Case(\"let\", PQK_Let)\n .Case(\"match\", PQK_Match)\n .Case(\"set\", PQK_Set)\n .Case(\"unlet\", PQK_Unlet)\n .Default(PQK_Invalid);\n\n QuerySessionSema S(QS);\n\n switch (QKind) {\n case PQK_NoOp:\n return new NoOpQuery;\n\n case PQK_Help:\n return endQuery(new HelpQuery);\n\n case PQK_Let: {\n StringRef Name = lexWord();\n\n if (Name.empty())\n return new InvalidQuery(\"expected variable name\");\n\n if (CompletionPos)\n return completeMatcherExpression();\n\n Diagnostics Diag;\n ast_matchers::dynamic::VariantValue Value;\n if (!Parser::parseExpression(StringRef(Begin, End - Begin), &S, &Value,\n &Diag)) {\n return makeInvalidQueryFromDiagnostics(Diag);\n }\n\n return new LetQuery(Name, Value);\n }\n\n case PQK_Match: {\n if (CompletionPos)\n return completeMatcherExpression();\n\n Diagnostics Diag;\n Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(\n StringRef(Begin, End - Begin), &S, &Diag);\n if (!Matcher) {\n return makeInvalidQueryFromDiagnostics(Diag);\n }\n return new MatchQuery(*Matcher);\n }\n\n case PQK_Set: {\n StringRef VarStr;\n ParsedQueryVariable Var = lexOrCompleteWord<ParsedQueryVariable>(VarStr)\n .Case(\"output\", PQV_Output)\n .Case(\"bind-root\", PQV_BindRoot)\n .Default(PQV_Invalid);\n if (VarStr.empty())\n return new InvalidQuery(\"expected variable name\");\n if (Var == PQV_Invalid)\n return new InvalidQuery(\"unknown variable: '\" + VarStr + \"'\");\n\n QueryRef Q;\n switch (Var) {\n case PQV_Output:\n Q = parseSetOutputKind();\n break;\n case PQV_BindRoot:\n Q = parseSetBool(&QuerySession::BindRoot);\n break;\n case PQV_Invalid:\n llvm_unreachable(\"Invalid query kind\");\n }\n\n return endQuery(Q);\n }\n\n case PQK_Unlet: {\n StringRef Name = lexWord();\n\n if (Name.empty())\n return new InvalidQuery(\"expected variable name\");\n\n return endQuery(new LetQuery(Name, VariantValue()));\n }\n\n case PQK_Invalid:\n return new InvalidQuery(\"unknown command: \" + CommandStr);\n }\n\n llvm_unreachable(\"Invalid query kind\");\n}\n\nQueryRef QueryParser::parse(StringRef Line, const QuerySession &QS) {\n return QueryParser(Line, QS).doParse();\n}\n\nstd::vector<LineEditor::Completion>\nQueryParser::complete(StringRef Line, size_t Pos, const QuerySession &QS) {\n QueryParser P(Line, QS);\n P.CompletionPos = Line.data() + Pos;\n\n P.doParse();\n return P.Completions;\n}\n\n} \/\/ namespace query\n} \/\/ namespace clang\n<commit_msg>[clang-query] Use the new API for named values from the Parser.<commit_after>\/\/===---- QueryParser.cpp - clang-query command parser --------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"QueryParser.h\"\n#include \"Query.h\"\n#include \"QuerySession.h\"\n#include \"clang\/ASTMatchers\/Dynamic\/Parser.h\"\n#include \"clang\/Basic\/CharInfo.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include <set>\n\nusing namespace llvm;\nusing namespace clang::ast_matchers::dynamic;\n\nnamespace clang {\nnamespace query {\n\n\/\/ Lex any amount of whitespace followed by a \"word\" (any sequence of\n\/\/ non-whitespace characters) from the start of region [Begin,End). If no word\n\/\/ is found before End, return StringRef(). Begin is adjusted to exclude the\n\/\/ lexed region.\nStringRef QueryParser::lexWord() {\n while (true) {\n if (Begin == End)\n return StringRef(Begin, 0);\n\n if (!isWhitespace(*Begin))\n break;\n\n ++Begin;\n }\n\n const char *WordBegin = Begin;\n\n while (true) {\n ++Begin;\n\n if (Begin == End || isWhitespace(*Begin))\n return StringRef(WordBegin, Begin - WordBegin);\n }\n}\n\n\/\/ This is the StringSwitch-alike used by lexOrCompleteWord below. See that\n\/\/ function for details.\ntemplate <typename T> struct QueryParser::LexOrCompleteWord {\n StringSwitch<T> Switch;\n\n QueryParser *P;\n StringRef Word;\n \/\/ Set to the completion point offset in Word, or StringRef::npos if\n \/\/ completion point not in Word.\n size_t WordCompletionPos;\n\n LexOrCompleteWord(QueryParser *P, StringRef Word, size_t WCP)\n : Switch(Word), P(P), Word(Word), WordCompletionPos(WCP) {}\n\n template <unsigned N>\n LexOrCompleteWord &Case(const char (&S)[N], const T &Value,\n bool IsCompletion = true) {\n StringRef CaseStr(S, N - 1);\n\n if (WordCompletionPos == StringRef::npos)\n Switch.Case(S, Value);\n else if (N != 1 && IsCompletion && WordCompletionPos <= CaseStr.size() &&\n CaseStr.substr(0, WordCompletionPos) ==\n Word.substr(0, WordCompletionPos))\n P->Completions.push_back(LineEditor::Completion(\n (CaseStr.substr(WordCompletionPos) + \" \").str(), CaseStr));\n return *this;\n }\n\n T Default(const T& Value) const {\n return Switch.Default(Value);\n }\n};\n\n\/\/ Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object\n\/\/ that can be used like a llvm::StringSwitch<T>, but adds cases as possible\n\/\/ completions if the lexed word contains the completion point.\ntemplate <typename T>\nQueryParser::LexOrCompleteWord<T>\nQueryParser::lexOrCompleteWord(StringRef &Word) {\n Word = lexWord();\n size_t WordCompletionPos = StringRef::npos;\n if (CompletionPos && CompletionPos <= Word.data() + Word.size()) {\n if (CompletionPos < Word.data())\n WordCompletionPos = 0;\n else\n WordCompletionPos = CompletionPos - Word.data();\n }\n return LexOrCompleteWord<T>(this, Word, WordCompletionPos);\n}\n\nQueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {\n StringRef ValStr;\n unsigned Value = lexOrCompleteWord<unsigned>(ValStr)\n .Case(\"false\", 0)\n .Case(\"true\", 1)\n .Default(~0u);\n if (Value == ~0u) {\n return new InvalidQuery(\"expected 'true' or 'false', got '\" + ValStr + \"'\");\n }\n return new SetQuery<bool>(Var, Value);\n}\n\nQueryRef QueryParser::parseSetOutputKind() {\n StringRef ValStr;\n unsigned OutKind = lexOrCompleteWord<unsigned>(ValStr)\n .Case(\"diag\", OK_Diag)\n .Case(\"print\", OK_Print)\n .Case(\"dump\", OK_Dump)\n .Default(~0u);\n if (OutKind == ~0u) {\n return new InvalidQuery(\"expected 'diag', 'print' or 'dump', got '\" +\n ValStr + \"'\");\n }\n return new SetQuery<OutputKind>(&QuerySession::OutKind, OutputKind(OutKind));\n}\n\nQueryRef QueryParser::endQuery(QueryRef Q) {\n const char *Extra = Begin;\n if (!lexWord().empty())\n return new InvalidQuery(\"unexpected extra input: '\" +\n StringRef(Extra, End - Extra) + \"'\");\n return Q;\n}\n\nnamespace {\n\nenum ParsedQueryKind {\n PQK_Invalid,\n PQK_NoOp,\n PQK_Help,\n PQK_Let,\n PQK_Match,\n PQK_Set,\n PQK_Unlet,\n};\n\nenum ParsedQueryVariable {\n PQV_Invalid,\n PQV_Output,\n PQV_BindRoot\n};\n\nQueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {\n std::string ErrStr;\n llvm::raw_string_ostream OS(ErrStr);\n Diag.printToStreamFull(OS);\n return new InvalidQuery(OS.str());\n}\n\n} \/\/ namespace\n\nQueryRef QueryParser::completeMatcherExpression() {\n std::vector<MatcherCompletion> Comps = Parser::completeExpression(\n StringRef(Begin, End - Begin), CompletionPos - Begin, nullptr,\n &QS.NamedValues);\n for (std::vector<MatcherCompletion>::iterator I = Comps.begin(),\n E = Comps.end();\n I != E; ++I) {\n Completions.push_back(LineEditor::Completion(I->TypedText, I->MatcherDecl));\n }\n return QueryRef();\n}\n\nQueryRef QueryParser::doParse() {\n StringRef CommandStr;\n ParsedQueryKind QKind = lexOrCompleteWord<ParsedQueryKind>(CommandStr)\n .Case(\"\", PQK_NoOp)\n .Case(\"help\", PQK_Help)\n .Case(\"m\", PQK_Match, \/*IsCompletion=*\/false)\n .Case(\"let\", PQK_Let)\n .Case(\"match\", PQK_Match)\n .Case(\"set\", PQK_Set)\n .Case(\"unlet\", PQK_Unlet)\n .Default(PQK_Invalid);\n\n switch (QKind) {\n case PQK_NoOp:\n return new NoOpQuery;\n\n case PQK_Help:\n return endQuery(new HelpQuery);\n\n case PQK_Let: {\n StringRef Name = lexWord();\n\n if (Name.empty())\n return new InvalidQuery(\"expected variable name\");\n\n if (CompletionPos)\n return completeMatcherExpression();\n\n Diagnostics Diag;\n ast_matchers::dynamic::VariantValue Value;\n if (!Parser::parseExpression(StringRef(Begin, End - Begin), nullptr,\n &QS.NamedValues, &Value, &Diag)) {\n return makeInvalidQueryFromDiagnostics(Diag);\n }\n\n return new LetQuery(Name, Value);\n }\n\n case PQK_Match: {\n if (CompletionPos)\n return completeMatcherExpression();\n\n Diagnostics Diag;\n Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(\n StringRef(Begin, End - Begin), nullptr, &QS.NamedValues, &Diag);\n if (!Matcher) {\n return makeInvalidQueryFromDiagnostics(Diag);\n }\n return new MatchQuery(*Matcher);\n }\n\n case PQK_Set: {\n StringRef VarStr;\n ParsedQueryVariable Var = lexOrCompleteWord<ParsedQueryVariable>(VarStr)\n .Case(\"output\", PQV_Output)\n .Case(\"bind-root\", PQV_BindRoot)\n .Default(PQV_Invalid);\n if (VarStr.empty())\n return new InvalidQuery(\"expected variable name\");\n if (Var == PQV_Invalid)\n return new InvalidQuery(\"unknown variable: '\" + VarStr + \"'\");\n\n QueryRef Q;\n switch (Var) {\n case PQV_Output:\n Q = parseSetOutputKind();\n break;\n case PQV_BindRoot:\n Q = parseSetBool(&QuerySession::BindRoot);\n break;\n case PQV_Invalid:\n llvm_unreachable(\"Invalid query kind\");\n }\n\n return endQuery(Q);\n }\n\n case PQK_Unlet: {\n StringRef Name = lexWord();\n\n if (Name.empty())\n return new InvalidQuery(\"expected variable name\");\n\n return endQuery(new LetQuery(Name, VariantValue()));\n }\n\n case PQK_Invalid:\n return new InvalidQuery(\"unknown command: \" + CommandStr);\n }\n\n llvm_unreachable(\"Invalid query kind\");\n}\n\nQueryRef QueryParser::parse(StringRef Line, const QuerySession &QS) {\n return QueryParser(Line, QS).doParse();\n}\n\nstd::vector<LineEditor::Completion>\nQueryParser::complete(StringRef Line, size_t Pos, const QuerySession &QS) {\n QueryParser P(Line, QS);\n P.CompletionPos = Line.data() + Pos;\n\n P.doParse();\n return P.Completions;\n}\n\n} \/\/ namespace query\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n** Author: Andreas Hartmetz, KDAB (andreas.hartmetz@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"analyzerruncontrol.h\"\n#include \"ianalyzertool.h\"\n#include \"analyzermanager.h\"\n#include \"analyzerstartparameters.h\"\n\n#include <QDebug>\n#include <QAction>\n\nusing namespace ProjectExplorer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AnalyzerRunControl\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace Analyzer {\n\nAnalyzerRunControl::AnalyzerRunControl(const AnalyzerStartParameters &sp,\n ProjectExplorer::RunConfiguration *runConfiguration)\n : RunControl(runConfiguration, sp.runMode)\n{\n m_runConfig = runConfiguration;\n m_sp = sp;\n\n connect(this, SIGNAL(finished()), SLOT(runControlFinished()));\n connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), SLOT(stopIt()));\n}\n\nvoid AnalyzerRunControl::stopIt()\n{\n if (stop() == RunControl::StoppedSynchronously)\n AnalyzerManager::handleToolFinished();\n}\n\nvoid AnalyzerRunControl::runControlFinished()\n{\n m_isRunning = false;\n AnalyzerManager::handleToolFinished();\n emit finished();\n}\n\nvoid AnalyzerRunControl::start()\n{\n AnalyzerManager::handleToolStarted();\n\n if (startEngine()) {\n m_isRunning = true;\n emit started();\n }\n}\n\nRunControl::StopResult AnalyzerRunControl::stop()\n{\n if (!m_isRunning)\n return StoppedSynchronously;\n\n stopEngine();\n m_isRunning = false;\n return AsynchronousStop;\n}\n\nbool AnalyzerRunControl::isRunning() const\n{\n return m_isRunning;\n}\n\nQString AnalyzerRunControl::displayName() const\n{\n return m_runConfig ? m_runConfig->displayName() : m_sp.displayName;\n}\n\nQIcon AnalyzerRunControl::icon() const\n{\n return QIcon(QLatin1String(\":\/images\/analyzer_start_small.png\"));\n}\n\n} \/\/ namespace Analyzer\n<commit_msg>Analyzer: Fix endless loop after finishing<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n** Author: Andreas Hartmetz, KDAB (andreas.hartmetz@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"analyzerruncontrol.h\"\n#include \"ianalyzertool.h\"\n#include \"analyzermanager.h\"\n#include \"analyzerstartparameters.h\"\n\n#include <QDebug>\n#include <QAction>\n\nusing namespace ProjectExplorer;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ AnalyzerRunControl\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace Analyzer {\n\nAnalyzerRunControl::AnalyzerRunControl(const AnalyzerStartParameters &sp,\n ProjectExplorer::RunConfiguration *runConfiguration)\n : RunControl(runConfiguration, sp.runMode)\n{\n m_runConfig = runConfiguration;\n m_sp = sp;\n\n connect(this, SIGNAL(finished()), SLOT(runControlFinished()));\n connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), SLOT(stopIt()));\n}\n\nvoid AnalyzerRunControl::stopIt()\n{\n if (stop() == RunControl::StoppedSynchronously)\n AnalyzerManager::handleToolFinished();\n}\n\nvoid AnalyzerRunControl::runControlFinished()\n{\n m_isRunning = false;\n AnalyzerManager::handleToolFinished();\n}\n\nvoid AnalyzerRunControl::start()\n{\n AnalyzerManager::handleToolStarted();\n\n if (startEngine()) {\n m_isRunning = true;\n emit started();\n }\n}\n\nRunControl::StopResult AnalyzerRunControl::stop()\n{\n if (!m_isRunning)\n return StoppedSynchronously;\n\n stopEngine();\n m_isRunning = false;\n return AsynchronousStop;\n}\n\nbool AnalyzerRunControl::isRunning() const\n{\n return m_isRunning;\n}\n\nQString AnalyzerRunControl::displayName() const\n{\n return m_runConfig ? m_runConfig->displayName() : m_sp.displayName;\n}\n\nQIcon AnalyzerRunControl::icon() const\n{\n return QIcon(QLatin1String(\":\/images\/analyzer_start_small.png\"));\n}\n\n} \/\/ namespace Analyzer\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n#include \"qmljsclientproxy.h\"\n#include \"qmljsdebuggerclient.h\"\n#include \"qmljsprivateapi.h\"\n#include \"qmljsdesigndebugclient.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QUrl>\n#include <QAbstractSocket>\n#include <QDebug>\n\nusing namespace QmlJSInspector::Internal;\n\nClientProxy *ClientProxy::m_instance = 0;\n\nClientProxy::ClientProxy(QObject *parent) :\n QObject(parent),\n m_conn(0),\n m_client(0),\n m_designClient(0),\n m_engineQuery(0),\n m_contextQuery(0),\n m_objectTreeQuery(0)\n{\n Q_ASSERT(! m_instance);\n m_instance = this;\n}\n\nClientProxy *ClientProxy::instance()\n{\n return m_instance;\n}\n\nbool ClientProxy::connectToViewer(const QString &host, quint16 port)\n{\n if (m_conn && m_conn->state() != QAbstractSocket::UnconnectedState)\n return false;\n\n if (m_designClient) {\n\n disconnect(m_designClient, SIGNAL(currentObjectsChanged(QList<int>)),\n this, SLOT(onCurrentObjectsChanged(QList<int>)));\n disconnect(m_designClient,\n SIGNAL(colorPickerActivated()), this, SIGNAL(colorPickerActivated()));\n disconnect(m_designClient,\n SIGNAL(zoomToolActivated()), this, SIGNAL(zoomToolActivated()));\n disconnect(m_designClient,\n SIGNAL(selectToolActivated()), this, SIGNAL(selectToolActivated()));\n disconnect(m_designClient,\n SIGNAL(selectMarqueeToolActivated()), this, SIGNAL(selectMarqueeToolActivated()));\n disconnect(m_designClient,\n SIGNAL(animationSpeedChanged(qreal)), this, SIGNAL(animationSpeedChanged(qreal)));\n disconnect(m_designClient,\n SIGNAL(designModeBehaviorChanged(bool)), this, SIGNAL(designModeBehaviorChanged(bool)));\n\n emit aboutToDisconnect();\n\n delete m_client;\n m_client = 0;\n\n delete m_designClient;\n m_designClient = 0;\n }\n\n if (m_conn) {\n m_conn->disconnectFromHost();\n delete m_conn;\n m_conn = 0;\n }\n\n m_conn = new QDeclarativeDebugConnection(this);\n connect(m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),\n SLOT(connectionStateChanged()));\n connect(m_conn, SIGNAL(error(QAbstractSocket::SocketError)),\n SLOT(connectionError()));\n\n emit connectionStatusMessage(tr(\"[Inspector] set to connect to debug server %1:%2\").arg(host).arg(port));\n m_conn->connectToHost(host, port);\n\n\n \/\/ blocks until connected; if no connection is available, will fail immediately\n if (!m_conn->waitForConnected())\n return false;\n\n return true;\n}\n\nvoid ClientProxy::refreshObjectTree()\n{\n if (!m_objectTreeQuery) {\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched(m_objectTreeQuery->state());\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n }\n}\n\nvoid ClientProxy::onCurrentObjectsChanged(const QList<int> &debugIds)\n{\n QList<QDeclarativeDebugObjectReference> selectedItems;\n\n foreach(int debugId, debugIds) {\n QDeclarativeDebugObjectReference ref = objectReferenceForId(debugId);\n if (ref.debugId() != -1) {\n selectedItems << ref;\n } else {\n \/\/ ### FIXME right now, there's no way in the protocol to\n \/\/ a) get some item and know its parent (although that's possible by adding it to a separate plugin)\n \/\/ b) add children to part of an existing tree.\n \/\/ So the only choice that remains is to update the complete tree when we have an unknown debug id.\n if (!m_objectTreeQuery)\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n break;\n }\n }\n\n if (m_objectTreeQuery) {\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched(m_objectTreeQuery->state());\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n } else {\n emit selectedItemsChanged(selectedItems);\n }\n}\n\nvoid ClientProxy::disconnectFromViewer()\n{\n m_conn->disconnectFromHost();\n emit disconnected();\n}\n\nvoid ClientProxy::connectionError()\n{\n emit connectionStatusMessage(tr(\"[Inspector] error: (%1) %2\", \"%1=error code, %2=error message\")\n .arg(m_conn->error()).arg(m_conn->errorString()));\n}\n\nvoid ClientProxy::connectionStateChanged()\n{\n switch (m_conn->state()) {\n case QAbstractSocket::UnconnectedState:\n {\n emit connectionStatusMessage(tr(\"[Inspector] disconnected.\\n\\n\"));\n\n delete m_engineQuery;\n m_engineQuery = 0;\n delete m_contextQuery;\n m_contextQuery = 0;\n\n if (m_objectTreeQuery) {\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n }\n\n emit disconnected();\n\n break;\n }\n case QAbstractSocket::HostLookupState:\n emit connectionStatusMessage(tr(\"[Inspector] resolving host...\"));\n break;\n case QAbstractSocket::ConnectingState:\n emit connectionStatusMessage(tr(\"[Inspector] connecting to debug server...\"));\n break;\n case QAbstractSocket::ConnectedState:\n {\n emit connectionStatusMessage(tr(\"[Inspector] connected.\\n\"));\n\n if (!m_client) {\n m_client = new QDeclarativeEngineDebug(m_conn, this);\n m_designClient = new QmlJSDesignDebugClient(m_conn, this);\n emit connected(m_client);\n\n connect(m_designClient,\n SIGNAL(currentObjectsChanged(QList<int>)),\n SLOT(onCurrentObjectsChanged(QList<int>)));\n connect(m_designClient,\n SIGNAL(colorPickerActivated()), SIGNAL(colorPickerActivated()));\n connect(m_designClient,\n SIGNAL(zoomToolActivated()), SIGNAL(zoomToolActivated()));\n connect(m_designClient,\n SIGNAL(selectToolActivated()), SIGNAL(selectToolActivated()));\n connect(m_designClient,\n SIGNAL(selectMarqueeToolActivated()), SIGNAL(selectMarqueeToolActivated()));\n connect(m_designClient,\n SIGNAL(animationSpeedChanged(qreal)), SIGNAL(animationSpeedChanged(qreal)));\n connect(m_designClient,\n SIGNAL(designModeBehaviorChanged(bool)), SIGNAL(designModeBehaviorChanged(bool)));\n connect(m_designClient, SIGNAL(reloaded()), this, SIGNAL(serverReloaded()));\n }\n\n (void) new DebuggerClient(m_conn);\n\n reloadEngines();\n\n break;\n }\n case QAbstractSocket::ClosingState:\n emit connectionStatusMessage(tr(\"[Inspector] closing...\"));\n break;\n case QAbstractSocket::BoundState:\n case QAbstractSocket::ListeningState:\n break;\n }\n}\n\nbool ClientProxy::isConnected() const\n{\n return (m_conn && m_client && m_conn->state() == QAbstractSocket::ConnectedState);\n}\n\nbool ClientProxy::isUnconnected() const\n{\n return (!m_conn || m_conn->state() == QAbstractSocket::UnconnectedState);\n}\n\nvoid ClientProxy::setSelectedItemsByObjectId(const QList<QDeclarativeDebugObjectReference> &objectRefs)\n{\n if (isConnected() && m_designClient)\n m_designClient->setSelectedItemsByObjectId(objectRefs);\n}\n\nQDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId) const\n{\n return objectReferenceForId(debugId, m_rootObject);\n}\n\nQDeclarativeDebugObjectReference QmlJSInspector::Internal::ClientProxy::rootObjectReference() const\n{\n return m_rootObject;\n}\n\n\nQDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId,\n const QDeclarativeDebugObjectReference &objectRef) const\n{\n if (objectRef.debugId() == debugId)\n return objectRef;\n\n foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {\n QDeclarativeDebugObjectReference result = objectReferenceForId(debugId, child);\n if (result.debugId() == debugId)\n return result;\n }\n\n return QDeclarativeDebugObjectReference();\n}\n\nQList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences(const QUrl &url) const\n{\n return objectReferences(url, m_rootObject);\n}\n\nQList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences(const QUrl &url,\n const QDeclarativeDebugObjectReference &objectRef) const\n{\n QList<QDeclarativeDebugObjectReference> result;\n if (objectRef.source().url() == url || url.isEmpty())\n result.append(objectRef);\n\n foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {\n result.append(objectReferences(url, child));\n }\n\n return result;\n}\n\nbool ClientProxy::setBindingForObject(int objectDebugId,\n const QString &propertyName,\n const QVariant &value,\n bool isLiteralValue)\n{\n qDebug() << \"setBindingForObject():\" << objectDebugId << propertyName << value;\n if (objectDebugId == -1)\n return false;\n\n if (propertyName == QLatin1String(\"id\"))\n return false; \/\/ Crashes the QMLViewer.\n\n return m_client->setBindingForObject(objectDebugId, propertyName, value.toString(), isLiteralValue);\n}\n\nbool ClientProxy::setMethodBodyForObject(int objectDebugId, const QString &methodName, const QString &methodBody)\n{\n qDebug() << \"setMethodBodyForObject():\" << objectDebugId << methodName << methodBody;\n if (objectDebugId == -1)\n return 0;\n return m_client->setMethodBody(objectDebugId, methodName, methodBody);\n}\n\nbool ClientProxy::resetBindingForObject(int objectDebugId, const QString& propertyName)\n{\n qDebug() << \"resetBindingForObject():\" << objectDebugId << propertyName;\n if (objectDebugId == -1)\n return false;\n \/\/ if (propertyName == QLatin1String(\"id\")) return false;\n return m_client->resetBindingForObject(objectDebugId, propertyName);\n}\n\n\nvoid ClientProxy::queryEngineContext(int id)\n{\n if (id < 0)\n return;\n\n if (m_contextQuery) {\n delete m_contextQuery;\n m_contextQuery = 0;\n }\n\n m_contextQuery = m_client->queryRootContexts(QDeclarativeDebugEngineReference(id), this);\n if (!m_contextQuery->isWaiting())\n contextChanged();\n else\n connect(m_contextQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n this, SLOT(contextChanged()));\n}\n\nvoid ClientProxy::contextChanged()\n{\n if (m_contextQuery) {\n\n if (m_contextQuery->rootContext().objects().isEmpty()) {\n m_rootObject = QDeclarativeDebugObjectReference();\n emit objectTreeUpdated(m_rootObject);\n } else {\n m_rootObject = m_contextQuery->rootContext().objects().first();\n }\n\n delete m_contextQuery;\n m_contextQuery = 0;\n\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched();\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n }\n\n}\n\nvoid ClientProxy::objectTreeFetched(QDeclarativeDebugQuery::State state)\n{\n if (state == QDeclarativeDebugQuery::Error) {\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n }\n\n if (state != QDeclarativeDebugQuery::Completed) {\n m_rootObject = QDeclarativeDebugObjectReference();\n return;\n }\n\n m_rootObject = m_objectTreeQuery->object();\n\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n\n emit objectTreeUpdated(m_rootObject);\n\n if (isDesignClientConnected() && !m_designClient->selectedItemIds().isEmpty()) {\n onCurrentObjectsChanged(m_designClient->selectedItemIds());\n }\n\n}\n\nvoid ClientProxy::reloadQmlViewer()\n{\n if (isDesignClientConnected())\n m_designClient->reloadViewer();\n}\n\nvoid ClientProxy::setDesignModeBehavior(bool inDesignMode)\n{\n if (isDesignClientConnected())\n m_designClient->setDesignModeBehavior(inDesignMode);\n}\n\nvoid ClientProxy::setAnimationSpeed(qreal slowdownFactor)\n{\n if (isDesignClientConnected())\n m_designClient->setAnimationSpeed(slowdownFactor);\n}\n\nvoid ClientProxy::changeToColorPickerTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToColorPickerTool();\n}\n\nvoid ClientProxy::changeToZoomTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToZoomTool();\n}\nvoid ClientProxy::changeToSelectTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToSelectTool();\n}\n\nvoid ClientProxy::changeToSelectMarqueeTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToSelectMarqueeTool();\n}\n\nvoid ClientProxy::createQmlObject(const QString &qmlText, int parentDebugId,\n const QStringList &imports, const QString &filename)\n{\n if (isDesignClientConnected())\n m_designClient->createQmlObject(qmlText, parentDebugId, imports, filename);\n}\n\nvoid QmlJSInspector::Internal::ClientProxy::destroyQmlObject(int debugId)\n{\n if (isDesignClientConnected())\n m_designClient->destroyQmlObject(debugId);\n}\n\n\nbool ClientProxy::isDesignClientConnected() const\n{\n return (m_designClient && m_conn->isConnected());\n}\n\nvoid ClientProxy::reloadEngines()\n{\n if (m_engineQuery) {\n emit connectionStatusMessage(\"[Inspector] Waiting for response to previous engine query\");\n return;\n }\n\n emit aboutToReloadEngines();\n\n m_engineQuery = m_client->queryAvailableEngines(this);\n if (!m_engineQuery->isWaiting())\n updateEngineList();\n else\n connect(m_engineQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n this, SLOT(updateEngineList()));\n}\n\nQList<QDeclarativeDebugEngineReference> ClientProxy::engines() const\n{\n return m_engines;\n}\n\nvoid ClientProxy::updateEngineList()\n{\n m_engines = m_engineQuery->engines();\n delete m_engineQuery;\n m_engineQuery = 0;\n\n emit enginesChanged();\n}\n<commit_msg>QML Live Preview: Apparently, the interresting root object is the last.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n#include \"qmljsclientproxy.h\"\n#include \"qmljsdebuggerclient.h\"\n#include \"qmljsprivateapi.h\"\n#include \"qmljsdesigndebugclient.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QUrl>\n#include <QAbstractSocket>\n#include <QDebug>\n\nusing namespace QmlJSInspector::Internal;\n\nClientProxy *ClientProxy::m_instance = 0;\n\nClientProxy::ClientProxy(QObject *parent) :\n QObject(parent),\n m_conn(0),\n m_client(0),\n m_designClient(0),\n m_engineQuery(0),\n m_contextQuery(0),\n m_objectTreeQuery(0)\n{\n Q_ASSERT(! m_instance);\n m_instance = this;\n}\n\nClientProxy *ClientProxy::instance()\n{\n return m_instance;\n}\n\nbool ClientProxy::connectToViewer(const QString &host, quint16 port)\n{\n if (m_conn && m_conn->state() != QAbstractSocket::UnconnectedState)\n return false;\n\n if (m_designClient) {\n\n disconnect(m_designClient, SIGNAL(currentObjectsChanged(QList<int>)),\n this, SLOT(onCurrentObjectsChanged(QList<int>)));\n disconnect(m_designClient,\n SIGNAL(colorPickerActivated()), this, SIGNAL(colorPickerActivated()));\n disconnect(m_designClient,\n SIGNAL(zoomToolActivated()), this, SIGNAL(zoomToolActivated()));\n disconnect(m_designClient,\n SIGNAL(selectToolActivated()), this, SIGNAL(selectToolActivated()));\n disconnect(m_designClient,\n SIGNAL(selectMarqueeToolActivated()), this, SIGNAL(selectMarqueeToolActivated()));\n disconnect(m_designClient,\n SIGNAL(animationSpeedChanged(qreal)), this, SIGNAL(animationSpeedChanged(qreal)));\n disconnect(m_designClient,\n SIGNAL(designModeBehaviorChanged(bool)), this, SIGNAL(designModeBehaviorChanged(bool)));\n\n emit aboutToDisconnect();\n\n delete m_client;\n m_client = 0;\n\n delete m_designClient;\n m_designClient = 0;\n }\n\n if (m_conn) {\n m_conn->disconnectFromHost();\n delete m_conn;\n m_conn = 0;\n }\n\n m_conn = new QDeclarativeDebugConnection(this);\n connect(m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),\n SLOT(connectionStateChanged()));\n connect(m_conn, SIGNAL(error(QAbstractSocket::SocketError)),\n SLOT(connectionError()));\n\n emit connectionStatusMessage(tr(\"[Inspector] set to connect to debug server %1:%2\").arg(host).arg(port));\n m_conn->connectToHost(host, port);\n\n\n \/\/ blocks until connected; if no connection is available, will fail immediately\n if (!m_conn->waitForConnected())\n return false;\n\n return true;\n}\n\nvoid ClientProxy::refreshObjectTree()\n{\n if (!m_objectTreeQuery) {\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched(m_objectTreeQuery->state());\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n }\n}\n\nvoid ClientProxy::onCurrentObjectsChanged(const QList<int> &debugIds)\n{\n QList<QDeclarativeDebugObjectReference> selectedItems;\n\n foreach(int debugId, debugIds) {\n QDeclarativeDebugObjectReference ref = objectReferenceForId(debugId);\n if (ref.debugId() != -1) {\n selectedItems << ref;\n } else {\n \/\/ ### FIXME right now, there's no way in the protocol to\n \/\/ a) get some item and know its parent (although that's possible by adding it to a separate plugin)\n \/\/ b) add children to part of an existing tree.\n \/\/ So the only choice that remains is to update the complete tree when we have an unknown debug id.\n if (!m_objectTreeQuery)\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n break;\n }\n }\n\n if (m_objectTreeQuery) {\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched(m_objectTreeQuery->state());\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n } else {\n emit selectedItemsChanged(selectedItems);\n }\n}\n\nvoid ClientProxy::disconnectFromViewer()\n{\n m_conn->disconnectFromHost();\n emit disconnected();\n}\n\nvoid ClientProxy::connectionError()\n{\n emit connectionStatusMessage(tr(\"[Inspector] error: (%1) %2\", \"%1=error code, %2=error message\")\n .arg(m_conn->error()).arg(m_conn->errorString()));\n}\n\nvoid ClientProxy::connectionStateChanged()\n{\n switch (m_conn->state()) {\n case QAbstractSocket::UnconnectedState:\n {\n emit connectionStatusMessage(tr(\"[Inspector] disconnected.\\n\\n\"));\n\n delete m_engineQuery;\n m_engineQuery = 0;\n delete m_contextQuery;\n m_contextQuery = 0;\n\n if (m_objectTreeQuery) {\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n }\n\n emit disconnected();\n\n break;\n }\n case QAbstractSocket::HostLookupState:\n emit connectionStatusMessage(tr(\"[Inspector] resolving host...\"));\n break;\n case QAbstractSocket::ConnectingState:\n emit connectionStatusMessage(tr(\"[Inspector] connecting to debug server...\"));\n break;\n case QAbstractSocket::ConnectedState:\n {\n emit connectionStatusMessage(tr(\"[Inspector] connected.\\n\"));\n\n if (!m_client) {\n m_client = new QDeclarativeEngineDebug(m_conn, this);\n m_designClient = new QmlJSDesignDebugClient(m_conn, this);\n emit connected(m_client);\n\n connect(m_designClient,\n SIGNAL(currentObjectsChanged(QList<int>)),\n SLOT(onCurrentObjectsChanged(QList<int>)));\n connect(m_designClient,\n SIGNAL(colorPickerActivated()), SIGNAL(colorPickerActivated()));\n connect(m_designClient,\n SIGNAL(zoomToolActivated()), SIGNAL(zoomToolActivated()));\n connect(m_designClient,\n SIGNAL(selectToolActivated()), SIGNAL(selectToolActivated()));\n connect(m_designClient,\n SIGNAL(selectMarqueeToolActivated()), SIGNAL(selectMarqueeToolActivated()));\n connect(m_designClient,\n SIGNAL(animationSpeedChanged(qreal)), SIGNAL(animationSpeedChanged(qreal)));\n connect(m_designClient,\n SIGNAL(designModeBehaviorChanged(bool)), SIGNAL(designModeBehaviorChanged(bool)));\n connect(m_designClient, SIGNAL(reloaded()), this, SIGNAL(serverReloaded()));\n }\n\n (void) new DebuggerClient(m_conn);\n\n reloadEngines();\n\n break;\n }\n case QAbstractSocket::ClosingState:\n emit connectionStatusMessage(tr(\"[Inspector] closing...\"));\n break;\n case QAbstractSocket::BoundState:\n case QAbstractSocket::ListeningState:\n break;\n }\n}\n\nbool ClientProxy::isConnected() const\n{\n return (m_conn && m_client && m_conn->state() == QAbstractSocket::ConnectedState);\n}\n\nbool ClientProxy::isUnconnected() const\n{\n return (!m_conn || m_conn->state() == QAbstractSocket::UnconnectedState);\n}\n\nvoid ClientProxy::setSelectedItemsByObjectId(const QList<QDeclarativeDebugObjectReference> &objectRefs)\n{\n if (isConnected() && m_designClient)\n m_designClient->setSelectedItemsByObjectId(objectRefs);\n}\n\nQDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId) const\n{\n return objectReferenceForId(debugId, m_rootObject);\n}\n\nQDeclarativeDebugObjectReference QmlJSInspector::Internal::ClientProxy::rootObjectReference() const\n{\n return m_rootObject;\n}\n\n\nQDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId,\n const QDeclarativeDebugObjectReference &objectRef) const\n{\n if (objectRef.debugId() == debugId)\n return objectRef;\n\n foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {\n QDeclarativeDebugObjectReference result = objectReferenceForId(debugId, child);\n if (result.debugId() == debugId)\n return result;\n }\n\n return QDeclarativeDebugObjectReference();\n}\n\nQList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences(const QUrl &url) const\n{\n return objectReferences(url, m_rootObject);\n}\n\nQList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences(const QUrl &url,\n const QDeclarativeDebugObjectReference &objectRef) const\n{\n QList<QDeclarativeDebugObjectReference> result;\n if (objectRef.source().url() == url || url.isEmpty())\n result.append(objectRef);\n\n foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {\n result.append(objectReferences(url, child));\n }\n\n return result;\n}\n\nbool ClientProxy::setBindingForObject(int objectDebugId,\n const QString &propertyName,\n const QVariant &value,\n bool isLiteralValue)\n{\n qDebug() << \"setBindingForObject():\" << objectDebugId << propertyName << value;\n if (objectDebugId == -1)\n return false;\n\n if (propertyName == QLatin1String(\"id\"))\n return false; \/\/ Crashes the QMLViewer.\n\n return m_client->setBindingForObject(objectDebugId, propertyName, value.toString(), isLiteralValue);\n}\n\nbool ClientProxy::setMethodBodyForObject(int objectDebugId, const QString &methodName, const QString &methodBody)\n{\n qDebug() << \"setMethodBodyForObject():\" << objectDebugId << methodName << methodBody;\n if (objectDebugId == -1)\n return 0;\n return m_client->setMethodBody(objectDebugId, methodName, methodBody);\n}\n\nbool ClientProxy::resetBindingForObject(int objectDebugId, const QString& propertyName)\n{\n qDebug() << \"resetBindingForObject():\" << objectDebugId << propertyName;\n if (objectDebugId == -1)\n return false;\n \/\/ if (propertyName == QLatin1String(\"id\")) return false;\n return m_client->resetBindingForObject(objectDebugId, propertyName);\n}\n\n\nvoid ClientProxy::queryEngineContext(int id)\n{\n if (id < 0)\n return;\n\n if (m_contextQuery) {\n delete m_contextQuery;\n m_contextQuery = 0;\n }\n\n m_contextQuery = m_client->queryRootContexts(QDeclarativeDebugEngineReference(id), this);\n if (!m_contextQuery->isWaiting())\n contextChanged();\n else\n connect(m_contextQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n this, SLOT(contextChanged()));\n}\n\nvoid ClientProxy::contextChanged()\n{\n if (m_contextQuery) {\n\n if (m_contextQuery->rootContext().objects().isEmpty()) {\n m_rootObject = QDeclarativeDebugObjectReference();\n emit objectTreeUpdated(m_rootObject);\n } else {\n m_rootObject = m_contextQuery->rootContext().objects().last();\n }\n\n delete m_contextQuery;\n m_contextQuery = 0;\n\n m_objectTreeQuery = m_client->queryObjectRecursive(m_rootObject, this);\n if (!m_objectTreeQuery->isWaiting()) {\n objectTreeFetched();\n } else {\n connect(m_objectTreeQuery,\n SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));\n }\n }\n\n}\n\nvoid ClientProxy::objectTreeFetched(QDeclarativeDebugQuery::State state)\n{\n if (state == QDeclarativeDebugQuery::Error) {\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n }\n\n if (state != QDeclarativeDebugQuery::Completed) {\n m_rootObject = QDeclarativeDebugObjectReference();\n return;\n }\n\n m_rootObject = m_objectTreeQuery->object();\n\n delete m_objectTreeQuery;\n m_objectTreeQuery = 0;\n\n emit objectTreeUpdated(m_rootObject);\n\n if (isDesignClientConnected() && !m_designClient->selectedItemIds().isEmpty()) {\n onCurrentObjectsChanged(m_designClient->selectedItemIds());\n }\n\n}\n\nvoid ClientProxy::reloadQmlViewer()\n{\n if (isDesignClientConnected())\n m_designClient->reloadViewer();\n}\n\nvoid ClientProxy::setDesignModeBehavior(bool inDesignMode)\n{\n if (isDesignClientConnected())\n m_designClient->setDesignModeBehavior(inDesignMode);\n}\n\nvoid ClientProxy::setAnimationSpeed(qreal slowdownFactor)\n{\n if (isDesignClientConnected())\n m_designClient->setAnimationSpeed(slowdownFactor);\n}\n\nvoid ClientProxy::changeToColorPickerTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToColorPickerTool();\n}\n\nvoid ClientProxy::changeToZoomTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToZoomTool();\n}\nvoid ClientProxy::changeToSelectTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToSelectTool();\n}\n\nvoid ClientProxy::changeToSelectMarqueeTool()\n{\n if (isDesignClientConnected())\n m_designClient->changeToSelectMarqueeTool();\n}\n\nvoid ClientProxy::createQmlObject(const QString &qmlText, int parentDebugId,\n const QStringList &imports, const QString &filename)\n{\n if (isDesignClientConnected())\n m_designClient->createQmlObject(qmlText, parentDebugId, imports, filename);\n}\n\nvoid QmlJSInspector::Internal::ClientProxy::destroyQmlObject(int debugId)\n{\n if (isDesignClientConnected())\n m_designClient->destroyQmlObject(debugId);\n}\n\n\nbool ClientProxy::isDesignClientConnected() const\n{\n return (m_designClient && m_conn->isConnected());\n}\n\nvoid ClientProxy::reloadEngines()\n{\n if (m_engineQuery) {\n emit connectionStatusMessage(\"[Inspector] Waiting for response to previous engine query\");\n return;\n }\n\n emit aboutToReloadEngines();\n\n m_engineQuery = m_client->queryAvailableEngines(this);\n if (!m_engineQuery->isWaiting())\n updateEngineList();\n else\n connect(m_engineQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),\n this, SLOT(updateEngineList()));\n}\n\nQList<QDeclarativeDebugEngineReference> ClientProxy::engines() const\n{\n return m_engines;\n}\n\nvoid ClientProxy::updateEngineList()\n{\n m_engines = m_engineQuery->engines();\n delete m_engineQuery;\n m_engineQuery = 0;\n\n emit enginesChanged();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ file : memory_allocator.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/persistence\/persistence\/tools\/memory_allocator.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 22\/09\/2014 11:00:31\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__\n# define __N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__\n\n#include <cstdlib>\n#include <new>\n#include <cstddef>\n#include <cstring>\n\n\nnamespace neam\n{\n namespace cr\n {\n \/\/\/ \\brief a chunked memory pool that can produce contiguous output.\n \/\/\/ \\note if an allocation size is < sizeof(uint64_t), then you could assume the allocation will never fail:\n \/\/\/ if the allocation fails, the function return a pointer to a valid area (an internal field) and set the \\e failed flag to true.\n \/\/\/ so allocation of very small size will alway give a valid pointer.\n class memory_allocator\n {\n public:\n \/\/\/ \\brief default constructor\n memory_allocator()\n {\n failed = false;\n }\n\n \/\/\/ \\brief a sub-memory_allocator: manage an allocated area of another memory_allocator\n \/\/\/ \\param[in,out] fallback is used when the allocated memory is greater than the \\p size of the \\p area\n \/\/\/ is nullptr, when the user request an allocation of size greater than the remaining area space, the allocation will fail.\n memory_allocator(void *area, size_t size, memory_allocator *fallback, bool unstack_fallbacks = true)\n\n {\n if (unstack_fallbacks)\n {\n while (fallback->fallback_allocator)\n fallback = fallback->fallback_allocator;\n }\n fallback_allocator = fallback;\n\n first = new(std::nothrow) memory_chunk;\n last = first;\n first->data = reinterpret_cast<uint8_t *>(area);\n first->size = size;\n first->do_not_destroy = true;\n\n use_fallback = true;\n failed = false;\n }\n\n ~memory_allocator()\n {\n clear();\n }\n\n \/\/\/ \\brief return whether or not an allocation has failed.\n bool has_failed() const\n {\n return failed;\n }\n\n \/\/\/ \\brief unset the failed flag\n void clear_failed()\n {\n failed = false;\n }\n\n \/\/\/ \\brief allocate \\e count bytes at the end of the pool\n \/\/\/ \\return \\b nullptr if allocation failed.\n void *allocate(size_t count)\n {\n if (!first || last->end_offset + count > last->size) \/\/ allocate a chunk (no chunk or no place in the last chunk)\n {\n if (use_fallback) \/\/ shortcut here when we have to use the fallback\n {\n last->end_offset = last->size; \/\/ make sure we won't allocate anything else.\n if (!fallback_allocator)\n {\n failed = true;\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n return nullptr;\n }\n\n void *ptr = fallback_allocator->allocate(count);\n if (!ptr)\n {\n failed = true;\n return nullptr;\n }\n return ptr;\n }\n\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n failed = true;\n delete nchk;\n\n \/\/ never fail for small allocations\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n return nullptr;\n }\n\n nchk->end_offset = count;\n if (first)\n {\n last->next = nchk;\n nchk->prev = last;\n last = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n pool_size += count;\n return nchk->data;\n }\n\n \/\/ there is enough room in the last chunk\n void *data = last->data + last->end_offset;\n last->end_offset += count;\n pool_size += count;\n return data;\n }\n\n \/\/\/ \\brief allocate \\e count bytes at the front of the pool\n \/\/\/ \\return \\b nullptr if allocation failed.\n void *allocate_front(size_t count)\n {\n if (!first || first->start_offset < count) \/\/ allocate a chunk (no chunk or no place left in the first chunk)\n {\n if (use_fallback) \/\/ shortcut here when we have to use the fallback\n {\n failed = false;\n return nullptr;\n }\n\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n failed = true;\n delete nchk;\n\n \/\/ never fail for small allocations\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n\n return nullptr;\n }\n\n nchk->end_offset = nchk->size;\n nchk->start_offset = count;\n if (first)\n {\n first->prev = nchk;\n nchk->next = first;\n first = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n pool_size += count;\n return nchk->data;\n }\n\n \/\/ there is enough room in the last chunk\n first->start_offset -= count;\n pool_size += count;\n return first->data + first->start_offset;\n }\n\n \/\/\/ \\brief remove \\e count bytes at the end of the pool\n void pop(size_t count)\n {\n if (!last)\n return;\n if (count >= pool_size)\n return clear();\n\n while (count)\n {\n if (last != first && (last->end_offset - last->start_offset) < count)\n {\n pool_size -= last->end_offset - last->start_offset;\n count -= last->end_offset - last->start_offset;\n last->prev->next = nullptr;\n memory_chunk *lst = last;\n last = last->prev;\n delete lst;\n }\n else if (last == first && (last->end_offset - last->start_offset) < count)\n {\n if (use_fallback)\n {\n full_allocator = false;\n first->end_offset = 0;\n }\n else\n {\n delete first;\n first = nullptr;\n last = nullptr;\n }\n pool_size = 0;\n return;\n }\n else\n {\n last->end_offset -= count;\n pool_size -= count;\n return;\n }\n }\n }\n\n \/\/\/ \\brief remove \\e count bytes at the start of the pool\n void pop_front(size_t count)\n {\n if (!first || !pool_size)\n return;\n if (count >= pool_size)\n return clear();\n\n while (count)\n {\n if (last != first && (first->end_offset - first->start_offset) < count)\n {\n pool_size -= first->end_offset - first->start_offset;\n count -= first->end_offset - first->start_offset;\n first->prev->next = nullptr;\n memory_chunk *lst = first;\n first = first->prev;\n delete lst;\n }\n else if (last == first && (last->end_offset - last->start_offset) < count)\n {\n delete first;\n first = nullptr;\n last = nullptr;\n pool_size = 0;\n return;\n }\n else\n {\n first->start_offset += count;\n pool_size -= count;\n return;\n }\n }\n }\n\n \/\/\/ \\brief makes sure there will be enough contiguous space.\n \/\/\/ Don't mark memory as allocated, but can skip the end of a chunk if there isn't enough space.\n \/\/\/ \\note doesn't set the failed flag is any memory allocation failure occurs.\n bool preallocate_contiguous(size_t count)\n {\n if (use_fallback)\n {\n if (last->end_offset + count <= last->size) \/\/ already preallocated, already contiguous\n return true;\n else \/\/ use the fallback, mark the buffer as full, _here will return fallback's _here.\n {\n if (!fallback_allocator)\n return false;\n last->end_offset = last->size; \/\/ make it full (no further allocations will takes place on this allocator)\n full_allocator = true;\n return fallback_allocator->preallocate_contiguous(count);\n }\n }\n\n if (!first || last->end_offset + count > last->size) \/\/ allocate a chunk (no chunk or no place in the last chunk)\n {\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n delete nchk;\n\n return false;\n }\n\n nchk->end_offset = 0;\n if (first)\n {\n last->next = nchk;\n nchk->prev = last;\n last = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n }\n return true;\n }\n\n \/\/\/ \\brief make the data contiguous.\n \/\/\/ \\note don't free the memory !!!\n void *get_contiguous_data()\n {\n \/\/ easy cases:\n if (!first)\n return nullptr;\n if (!first->next && first->start_offset == 0) \/\/ already contiguous\n return first->data;\n\n memory_chunk *new_chk = new memory_chunk;\n new_chk->data = reinterpret_cast<uint8_t *>(operator new(pool_size, std::nothrow));\n if (!new_chk->data)\n {\n delete new_chk;\n return nullptr;\n }\n\n new_chk->size = pool_size;\n new_chk->start_offset = 0;\n new_chk->end_offset = pool_size;\n\n size_t idx = 0;\n memory_chunk *next = nullptr;\n for (memory_chunk *chr = first; chr; chr = next)\n {\n memcpy(new_chk->data + idx, chr->data + chr->start_offset, chr->end_offset - chr->start_offset);\n idx += chr->end_offset - chr->start_offset;\n next = chr->next;\n delete chr;\n }\n\n first = new_chk;\n last = new_chk;\n return new_chk->data;\n }\n\n \/\/\/ \\brief give the the data ownership, return the pointer to the data and clear the pool\n \/\/\/ \\note it's up to the user to delete this pointer.\n \/\/\/ \\see get_contiguous_data()\n \/\/\/ \\see clear()\n void *give_up_data()\n {\n void *ret = get_contiguous_data();\n if (first)\n first->data = nullptr;\n clear();\n return ret;\n }\n\n \/\/\/ \\brief empty the memory pool, delete every allocated memory.\n void clear()\n {\n memory_chunk *next = nullptr;\n for (memory_chunk *chr = first; chr; chr = next)\n {\n next = chr->next;\n delete chr;\n }\n first = nullptr;\n last = nullptr;\n pool_size = 0;\n failed = false;\n }\n\n \/\/\/ \\brief return the size of the pool\n size_t size() const\n {\n return pool_size;\n }\n\n \/\/\/ \\brief returns the current pointer.\n void *_here()\n {\n if (full_allocator)\n {\n if (fallback_allocator)\n return fallback_allocator->_here();\n }\n\n if (!last)\n return nullptr;\n return last->data + last->end_offset;\n }\n\n private:\n struct memory_chunk\n {\n uint8_t *data = nullptr;\n\n size_t start_offset = 0;\n size_t end_offset = 0;\n size_t size = 0;\n\n bool do_not_destroy = false;\n\n memory_chunk *next = nullptr;\n memory_chunk *prev = nullptr;\n\n ~memory_chunk()\n {\n if (!do_not_destroy)\n delete data;\n }\n };\n\n private:\n constexpr static size_t chunk_size = 8192 * 10; \/\/ 10 * 8Kio per-chunk\n\n private:\n memory_chunk *first = nullptr;\n memory_chunk *last = nullptr;\n size_t pool_size = 0;\n bool failed = false;\n uint64_t fallback_small; \/\/\/< \\brief used when running out of memory and if the allocated size is lower than\n\n bool use_fallback = false;\n memory_allocator *fallback_allocator = nullptr;\n bool full_allocator = false; \/\/\/< \\brief _here will return fallback_allocator->_here() or nullptr.\n };\n } \/\/ namespace cr\n} \/\/ namespace neam\n\n#endif \/*__N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<commit_msg>[MEM\/ALLOC]: Improve the memory allocator<commit_after>\/\/\n\/\/ file : memory_allocator.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/persistence\/persistence\/tools\/memory_allocator.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 22\/09\/2014 11:00:31\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__\n# define __N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__\n\n#include <cstdlib>\n#include <new>\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n\n\nnamespace neam\n{\n namespace cr\n {\n \/\/\/ \\brief a chunked memory pool that can produce contiguous output.\n \/\/\/ \\note if an allocation size is < sizeof(uint64_t), then you could assume the allocation will never fail:\n \/\/\/ if the allocation fails, the function return a pointer to a valid area (an internal field) and set the \\e failed flag to true.\n \/\/\/ so allocation of very small size will alway give a valid pointer.\n class memory_allocator\n {\n public:\n \/\/\/ \\brief default constructor\n memory_allocator()\n {\n failed = false;\n }\n\n \/\/\/ \\brief a sub-memory_allocator: manage an allocated area of another memory_allocator\n \/\/\/ \\param[in,out] fallback is used when the allocated memory is greater than the \\p size of the \\p area\n \/\/\/ is nullptr, when the user request an allocation of size greater than the remaining area space, the allocation will fail.\n memory_allocator(void *area, size_t size, memory_allocator *fallback, bool unstack_fallbacks = true)\n\n {\n if (unstack_fallbacks)\n {\n while (fallback->fallback_allocator)\n fallback = fallback->fallback_allocator;\n }\n fallback_allocator = fallback;\n\n first = new(std::nothrow) memory_chunk;\n last = first;\n first->data = reinterpret_cast<uint8_t *>(area);\n first->size = size;\n first->do_not_destroy = true;\n\n use_fallback = true;\n failed = false;\n }\n\n \/\/\/ \\brief Move constructor\n memory_allocator(memory_allocator &&o)\n : first(o.first), last(o.last), pool_size(o.pool_size), failed(o.failed),\n use_fallback(o.use_fallback), fallback_allocator(o.fallback_allocator),\n full_allocator(o.full_allocator)\n {\n o.first = nullptr;\n o.last = nullptr;\n o.pool_size = 0;\n o.failed = true; \/\/ Set the failed flag. Just in case.\n o.fallback_allocator = nullptr;\n }\n\n \/\/\/ \\brief Move\/affectation operator\n memory_allocator &operator = (memory_allocator &&o)\n {\n if (&o == this)\n return *this;\n\n clear();\n first = o.first;\n last = o.last;\n pool_size = o.pool_size;\n failed = o.failed;\n use_fallback = o.use_fallback;\n fallback_allocator = o.fallback_allocator;\n full_allocator = o.full_allocator;\n\n o.first = nullptr;\n o.last = nullptr;\n o.pool_size = 0;\n o.failed = true; \/\/ Set the failed flag. Just in case.\n o.fallback_allocator = nullptr;\n return *this;\n }\n\n ~memory_allocator()\n {\n clear();\n }\n\n \/\/\/ \\brief return whether or not an allocation has failed.\n bool has_failed() const\n {\n return failed;\n }\n\n \/\/\/ \\brief unset the failed flag\n void clear_failed()\n {\n failed = false;\n }\n\n \/\/\/ \\brief allocate \\e count bytes at the end of the pool\n \/\/\/ \\return \\b nullptr if allocation failed.\n void *allocate(size_t count)\n {\n if (!first || last->end_offset + count > last->size) \/\/ allocate a chunk (no chunk or no place in the last chunk)\n {\n if (use_fallback) \/\/ shortcut here when we have to use the fallback\n {\n last->end_offset = last->size; \/\/ make sure we won't allocate anything else.\n if (!fallback_allocator)\n {\n failed = true;\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n return nullptr;\n }\n\n void *ptr = fallback_allocator->allocate(count);\n if (!ptr)\n {\n failed = true;\n return nullptr;\n }\n return ptr;\n }\n\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n failed = true;\n delete nchk;\n\n \/\/ never fail for small allocations\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n return nullptr;\n }\n\n nchk->end_offset = count;\n if (first)\n {\n last->next = nchk;\n nchk->prev = last;\n last = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n pool_size += count;\n return nchk->data;\n }\n\n \/\/ there is enough room in the last chunk\n void *data = last->data + last->end_offset;\n last->end_offset += count;\n pool_size += count;\n return data;\n }\n\n \/\/\/ \\brief allocate \\e count bytes at the front of the pool\n \/\/\/ \\return \\b nullptr if allocation failed.\n void *allocate_front(size_t count)\n {\n if (!first || first->start_offset < count) \/\/ allocate a chunk (no chunk or no place left in the first chunk)\n {\n if (use_fallback) \/\/ shortcut here when we have to use the fallback\n {\n failed = false;\n return nullptr;\n }\n\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n failed = true;\n delete nchk;\n\n \/\/ never fail for small allocations\n if (count <= sizeof(fallback_small))\n return &fallback_small;\n\n return nullptr;\n }\n\n nchk->end_offset = nchk->size;\n nchk->start_offset = count;\n if (first)\n {\n first->prev = nchk;\n nchk->next = first;\n first = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n pool_size += count;\n return nchk->data;\n }\n\n \/\/ there is enough room in the last chunk\n first->start_offset -= count;\n pool_size += count;\n return first->data + first->start_offset;\n }\n\n \/\/\/ \\brief remove \\e count bytes at the end of the pool\n void pop(size_t count)\n {\n if (!last)\n return;\n if (count >= pool_size)\n return clear();\n\n while (count)\n {\n if (last != first && (last->end_offset - last->start_offset) < count)\n {\n pool_size -= last->end_offset - last->start_offset;\n count -= last->end_offset - last->start_offset;\n last->prev->next = nullptr;\n memory_chunk *lst = last;\n last = last->prev;\n delete lst;\n }\n else if (last == first && (last->end_offset - last->start_offset) < count)\n {\n if (use_fallback)\n {\n full_allocator = false;\n first->end_offset = 0;\n }\n else\n {\n delete first;\n first = nullptr;\n last = nullptr;\n }\n pool_size = 0;\n return;\n }\n else\n {\n last->end_offset -= count;\n pool_size -= count;\n return;\n }\n }\n }\n\n \/\/\/ \\brief remove \\e count bytes at the start of the pool\n void pop_front(size_t count)\n {\n if (!first || !pool_size)\n return;\n if (count >= pool_size)\n return clear();\n\n while (count)\n {\n if (last != first && (first->end_offset - first->start_offset) < count)\n {\n pool_size -= first->end_offset - first->start_offset;\n count -= first->end_offset - first->start_offset;\n first->prev->next = nullptr;\n memory_chunk *lst = first;\n first = first->prev;\n delete lst;\n }\n else if (last == first && (last->end_offset - last->start_offset) < count)\n {\n delete first;\n first = nullptr;\n last = nullptr;\n pool_size = 0;\n return;\n }\n else\n {\n first->start_offset += count;\n pool_size -= count;\n return;\n }\n }\n }\n\n \/\/\/ \\brief makes sure there will be enough contiguous space.\n \/\/\/ Don't mark memory as allocated, but can skip the end of a chunk if there isn't enough space.\n \/\/\/ \\note doesn't set the failed flag is any memory allocation failure occurs.\n bool preallocate_contiguous(size_t count)\n {\n if (use_fallback)\n {\n if (last->end_offset + count <= last->size) \/\/ already preallocated, already contiguous\n return true;\n else \/\/ use the fallback, mark the buffer as full, _here will return fallback's _here.\n {\n if (!fallback_allocator)\n return false;\n last->end_offset = last->size; \/\/ make it full (no further allocations will takes place on this allocator)\n full_allocator = true;\n return fallback_allocator->preallocate_contiguous(count);\n }\n }\n\n if (!first || last->end_offset + count > last->size) \/\/ allocate a chunk (no chunk or no place in the last chunk)\n {\n memory_chunk *nchk = new(std::nothrow) memory_chunk;\n if (nchk)\n {\n nchk->size = count > chunk_size ? count : chunk_size;\n nchk->data = reinterpret_cast<uint8_t *>(operator new(nchk->size, std::nothrow));\n }\n if (!nchk || !nchk->data)\n {\n delete nchk;\n\n return false;\n }\n\n nchk->end_offset = 0;\n if (first)\n {\n last->next = nchk;\n nchk->prev = last;\n last = nchk;\n }\n else\n {\n first = nchk;\n last = nchk;\n }\n }\n return true;\n }\n\n \/\/\/ \\brief Check if the data is already contiguous\n bool is_data_contiguous() const\n {\n if (!first)\n return true;\n if (!first->next && first->start_offset == 0) \/\/ already contiguous\n return true;\n return false;\n }\n\n \/\/\/ \\brief make the data contiguous.\n \/\/\/ \\note don't free the memory !!!\n void *get_contiguous_data()\n {\n \/\/ easy cases:\n if (!first)\n return nullptr;\n if (!first->next && first->start_offset == 0) \/\/ already contiguous\n return first->data;\n\n memory_chunk *new_chk = new memory_chunk;\n new_chk->data = reinterpret_cast<uint8_t *>(operator new(pool_size, std::nothrow));\n if (!new_chk->data)\n {\n delete new_chk;\n return nullptr;\n }\n\n new_chk->size = pool_size;\n new_chk->start_offset = 0;\n new_chk->end_offset = pool_size;\n\n size_t idx = 0;\n memory_chunk *next = nullptr;\n for (memory_chunk *chr = first; chr; chr = next)\n {\n memcpy(new_chk->data + idx, chr->data + chr->start_offset, chr->end_offset - chr->start_offset);\n idx += chr->end_offset - chr->start_offset;\n next = chr->next;\n delete chr;\n }\n\n first = new_chk;\n last = new_chk;\n return new_chk->data;\n }\n\n \/\/\/ \\brief Like get_contiguous_data() but does not clear the memory_allocator\n \/\/\/ \\note As you have the ownership of the memory, it's your duty to free it\n void *get_contiguous_data_copy() const\n {\n uint8_t *data = reinterpret_cast<uint8_t *>(operator new(pool_size, std::nothrow));\n if (!data)\n return nullptr;\n\n size_t idx = 0;\n memory_chunk *next = nullptr;\n for (memory_chunk *chr = first; chr; chr = next)\n {\n memcpy(data + idx, chr->data + chr->start_offset, chr->end_offset - chr->start_offset);\n idx += chr->end_offset - chr->start_offset;\n next = chr->next;\n delete chr;\n }\n\n return data;\n }\n\n \/\/\/ \\brief give the the data ownership, return the pointer to the data and clear the pool\n \/\/\/ \\note it's up to the user to delete this pointer.\n \/\/\/ \\see get_contiguous_data()\n \/\/\/ \\see clear()\n void *give_up_data()\n {\n void *ret = get_contiguous_data();\n if (first)\n first->data = nullptr;\n clear();\n return ret;\n }\n\n \/\/\/ \\brief empty the memory pool, delete every allocated memory.\n void clear()\n {\n memory_chunk *next = nullptr;\n for (memory_chunk *chr = first; chr; chr = next)\n {\n next = chr->next;\n delete chr;\n }\n first = nullptr;\n last = nullptr;\n pool_size = 0;\n failed = false;\n }\n\n \/\/\/ \\brief return the size of the pool\n size_t size() const\n {\n return pool_size;\n }\n\n \/\/\/ \\brief returns the current pointer.\n void *_here()\n {\n if (full_allocator)\n {\n if (fallback_allocator)\n return fallback_allocator->_here();\n }\n\n if (!last)\n return nullptr;\n return last->data + last->end_offset;\n }\n\n private:\n struct memory_chunk\n {\n uint8_t *data = nullptr;\n\n size_t start_offset = 0;\n size_t end_offset = 0;\n size_t size = 0;\n\n bool do_not_destroy = false;\n\n memory_chunk *next = nullptr;\n memory_chunk *prev = nullptr;\n\n ~memory_chunk()\n {\n if (!do_not_destroy)\n delete data;\n }\n };\n\n private:\n constexpr static size_t chunk_size = 8192 * 10; \/\/ 10 * 8Kio per-chunk\n\n private:\n memory_chunk *first = nullptr;\n memory_chunk *last = nullptr;\n size_t pool_size = 0;\n bool failed = false;\n uint64_t fallback_small; \/\/\/< \\brief used when running out of memory and if the allocated size is lower than\n\n bool use_fallback = false;\n memory_allocator *fallback_allocator = nullptr;\n bool full_allocator = false; \/\/\/< \\brief _here will return fallback_allocator->_here() or nullptr.\n };\n } \/\/ namespace cr\n} \/\/ namespace neam\n\n#endif \/*__N_2080522430493415542_1720253011__MEMORY_ALLOCATOR_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<|endoftext|>"} {"text":"<commit_before>#include \"main_window.moc.hpp\"\n\n#include <string.h>\n#include <stdlib.h>\n#include <iostream>\n\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QPushButton>\n#include <QLabel>\n#include <QCheckBox>\n\nThreadWindowImpl::ThreadWindowImpl(std::shared_ptr<Plugin> *plugs, QWidget *parent)\n : QWidget(parent), plugins(plugs)\n{\n setAttribute(Qt::WA_QuitOnClose, false);\n QVBoxLayout *vbox = new QVBoxLayout;\n vbox->addWidget(new QLabel(\"DSP plugin config:\", this));\n \n tab = new QTabWidget(this);\n for (unsigned i = 0; i < MetaDSP::max_plugs; i++)\n tab->addTab(new PluginSettings(plugins[i], tab), QString::fromStdString(plugins[i]->ident()));\n\n vbox->addWidget(tab);\n\n setWindowTitle(\"SSNES Meta DSP\");\n setLayout(vbox);\n}\n\nvoid MetaApplication::show()\n{\n impl->show();\n}\n\nMetaApplication::MetaApplication(std::shared_ptr<Plugin> *plugs)\n : plugins(plugs)\n{\n static int argc = 1;\n static const char *appname = \"ssnes-dsp\";\n static char *argv[] = { const_cast<char*>(appname), NULL };\n\n app = new QApplication(argc, argv);\n impl = new ThreadWindowImpl(plugins);\n}\n\nMetaApplication::~MetaApplication()\n{\n delete impl;\n delete app;\n}\n\nPluginSettings::PluginSettings(std::shared_ptr<Plugin> &plug, QWidget *parent)\n : QWidget(parent), plugin(plug)\n{\n QVBoxLayout *vbox = new QVBoxLayout;\n\n QCheckBox *box = new QCheckBox(\"Enable\", this);\n box->setCheckState(Qt::Checked);\n connect(box, SIGNAL(stateChanged(int)), this, SLOT(enable(int)));\n vbox->addWidget(box);\n\n auto list = plugin->options();\n for (auto itr = list.begin(); itr != list.end(); ++itr)\n vbox->addWidget(new PluginSetting(plugin, *itr, this));\n\n setLayout(vbox);\n}\n\nvoid PluginSettings::enable(int val)\n{\n Global::lock();\n if (val == Qt::Checked)\n plugin->enabled(true);\n else if (val == Qt::Unchecked)\n plugin->enabled(false);\n Global::unlock();\n}\n\nPluginSetting::PluginSetting(std::shared_ptr<Plugin> &plug,\n const PluginOption &opt, QWidget *parent)\n : QWidget(parent), plugin(plug)\n{\n id = opt.id;\n min = opt.min;\n max = opt.max;\n current = opt.current;\n\n QHBoxLayout *hbox = new QHBoxLayout;\n hbox->addWidget(new QLabel(QString::fromStdString(opt.description), this));\n slider = new QSlider(Qt::Horizontal, this);\n slider->setMinimum(0);\n slider->setMaximum(Intervals);\n connect(slider, SIGNAL(valueChanged(int)), this, SLOT(updated()));\n hbox->addWidget(slider);\n\n value = new QLabel(QString::number(current, 'f', 1));\n hbox->addWidget(value);\n\n val2slide(current);\n setLayout(hbox);\n}\n\nvoid PluginSetting::updated()\n{\n current = slide2val();\n value->setText(QString::number(current, 'f', 1));\n\n Global::lock();\n plugin->set_option(id, current);\n Global::unlock();\n}\n\ndouble PluginSetting::slide2val() const\n{\n int pos = slider->value();\n return min + (max - min) * pos \/ Intervals;\n}\n\nvoid PluginSetting::val2slide(double val)\n{\n int value = (val - min) * Intervals \/ (max - min);\n slider->setValue(value);\n}\n\n\nnamespace Global\n{\n static QMutex g_lock;\n\n void lock()\n {\n g_lock.lock();\n }\n\n void unlock()\n {\n g_lock.unlock();\n }\n}\n<commit_msg>Do not lock needlessly.<commit_after>#include \"main_window.moc.hpp\"\n\n#include <string.h>\n#include <stdlib.h>\n#include <iostream>\n\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QPushButton>\n#include <QLabel>\n#include <QCheckBox>\n\nThreadWindowImpl::ThreadWindowImpl(std::shared_ptr<Plugin> *plugs, QWidget *parent)\n : QWidget(parent), plugins(plugs)\n{\n setAttribute(Qt::WA_QuitOnClose, false);\n QVBoxLayout *vbox = new QVBoxLayout;\n vbox->addWidget(new QLabel(\"DSP plugin config:\", this));\n \n tab = new QTabWidget(this);\n for (unsigned i = 0; i < MetaDSP::max_plugs; i++)\n tab->addTab(new PluginSettings(plugins[i], tab), QString::fromStdString(plugins[i]->ident()));\n\n vbox->addWidget(tab);\n\n setWindowTitle(\"SSNES Meta DSP\");\n setLayout(vbox);\n}\n\nvoid MetaApplication::show()\n{\n impl->show();\n}\n\nMetaApplication::MetaApplication(std::shared_ptr<Plugin> *plugs)\n : plugins(plugs)\n{\n static int argc = 1;\n static const char *appname = \"ssnes-dsp\";\n static char *argv[] = { const_cast<char*>(appname), NULL };\n\n app = new QApplication(argc, argv);\n impl = new ThreadWindowImpl(plugins);\n}\n\nMetaApplication::~MetaApplication()\n{\n delete impl;\n delete app;\n}\n\nPluginSettings::PluginSettings(std::shared_ptr<Plugin> &plug, QWidget *parent)\n : QWidget(parent), plugin(plug)\n{\n QVBoxLayout *vbox = new QVBoxLayout;\n\n QCheckBox *box = new QCheckBox(\"Enable\", this);\n box->setCheckState(Qt::Checked);\n connect(box, SIGNAL(stateChanged(int)), this, SLOT(enable(int)));\n vbox->addWidget(box);\n\n auto list = plugin->options();\n for (auto itr = list.begin(); itr != list.end(); ++itr)\n vbox->addWidget(new PluginSetting(plugin, *itr, this));\n\n setLayout(vbox);\n}\n\nvoid PluginSettings::enable(int val)\n{\n Global::lock();\n if (val == Qt::Checked)\n plugin->enabled(true);\n else if (val == Qt::Unchecked)\n plugin->enabled(false);\n Global::unlock();\n}\n\nPluginSetting::PluginSetting(std::shared_ptr<Plugin> &plug,\n const PluginOption &opt, QWidget *parent)\n : QWidget(parent), plugin(plug)\n{\n id = opt.id;\n min = opt.min;\n max = opt.max;\n current = opt.current;\n\n QHBoxLayout *hbox = new QHBoxLayout;\n hbox->addWidget(new QLabel(QString::fromStdString(opt.description), this));\n slider = new QSlider(Qt::Horizontal, this);\n slider->setMinimum(0);\n slider->setMaximum(Intervals);\n connect(slider, SIGNAL(valueChanged(int)), this, SLOT(updated()));\n hbox->addWidget(slider);\n\n value = new QLabel(QString::number(current, 'f', 1));\n hbox->addWidget(value);\n\n val2slide(current);\n setLayout(hbox);\n}\n\nvoid PluginSetting::updated()\n{\n current = slide2val();\n value->setText(QString::number(current, 'f', 1));\n\n Global::lock();\n plugin->set_option(id, current);\n Global::unlock();\n}\n\ndouble PluginSetting::slide2val() const\n{\n int pos = slider->value();\n return min + (max - min) * pos \/ Intervals;\n}\n\nvoid PluginSetting::val2slide(double val)\n{\n int value = (val - min) * Intervals \/ (max - min);\n slider->setValue(value);\n}\n\n\nnamespace Global\n{\n#ifdef META_THREADED\n static QMutex g_lock;\n\n void lock()\n {\n g_lock.lock();\n }\n\n void unlock()\n {\n g_lock.unlock();\n }\n#else\n void lock() {}\n void unlock() {}\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n * filename: Element.cpp\n * created: 28\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/Element.h\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/timer.hpp>\n\nBOOST_AUTO_TEST_SUITE(Element)\n\nBOOST_AUTO_TEST_CASE(RelativeSizing)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));\n root->addChild(child);\n \n BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));\n BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));\n \n CEGUI::Element* innerChild = new CEGUI::Element();\n child->addChild(innerChild);\n innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));\n BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));\n \n delete innerChild;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(TopLeftAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 25.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);\n BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 25));\n \n child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 5, 60, 30));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Split Element top left alignment test case into 2<commit_after>\/***********************************************************************\n * filename: Element.cpp\n * created: 28\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/Element.h\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/timer.hpp>\n\nBOOST_AUTO_TEST_SUITE(Element)\n\nBOOST_AUTO_TEST_CASE(RelativeSizing)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));\n root->addChild(child);\n \n BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));\n BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));\n \n CEGUI::Element* innerChild = new CEGUI::Element();\n child->addChild(innerChild);\n innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));\n BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));\n \n delete innerChild;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(LeftAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0));\n \n child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0));\n}\n\nBOOST_AUTO_TEST_CASE(TopAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 25.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);\n BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 25));\n \n child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 30));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"g_json.h\"\n\n\/\/ TILE PARSING\nstatic unordered_map<const char*, jsonParseFunc> tileParseFields;\n\nvoid ParseSubtile(cJSON* json, void* ptTile, int tileNum) {\n\tTile* t = (Tile*)ptTile;\n\tif(!t) {\n\t\treturn;\n\t}\n\tcJSON* jsonNode = cJSON_GetObjectItem(json, \"low\");\n\tif(jsonNode) {\n\t\tt->lowmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"high\");\n\tif(jsonNode) {\n\t\tt->highmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"light\");\n\tif(jsonNode) {\n\t\tt->lightmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"vis\");\n\tif(jsonNode) {\n\t\tt->vismask |= (1 << tileNum);\n\t}\n}\n\nvoid InitTileParseFields() {\n#define SUBTILE_PARSER(x) [](cJSON* j, void* p) -> void { ParseSubtile(j, p, x); }\n#define INT_PARSER(x) [](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; t->##x## = cJSON_ToInteger(j); }\n#define NAME_PARSER [](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; strcpy(t->name, cJSON_ToString(j)); }\n#define MAT_PARSER \\\n\t[](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; t->materialHandle = trap->RegisterMaterial(cJSON_ToString(j)); }\n\n\ttileParseFields[\"subtile0\"] = SUBTILE_PARSER(0);\n\ttileParseFields[\"subtile1\"] = SUBTILE_PARSER(1);\n\ttileParseFields[\"subtile2\"] = SUBTILE_PARSER(2);\n\ttileParseFields[\"subtile3\"] = SUBTILE_PARSER(3);\n\ttileParseFields[\"subtile4\"] = SUBTILE_PARSER(4);\n\ttileParseFields[\"subtile5\"] = SUBTILE_PARSER(5);\n\ttileParseFields[\"subtile6\"] = SUBTILE_PARSER(6);\n\ttileParseFields[\"subtile7\"] = SUBTILE_PARSER(7);\n\ttileParseFields[\"subtile8\"] = SUBTILE_PARSER(8);\n\ttileParseFields[\"subtile9\"] = SUBTILE_PARSER(9);\n\ttileParseFields[\"subtile10\"] = SUBTILE_PARSER(10);\n\ttileParseFields[\"subtile11\"] = SUBTILE_PARSER(11);\n\ttileParseFields[\"subtile12\"] = SUBTILE_PARSER(12);\n\ttileParseFields[\"subtile13\"] = SUBTILE_PARSER(13);\n\ttileParseFields[\"subtile14\"] = SUBTILE_PARSER(14);\n\ttileParseFields[\"subtile15\"] = SUBTILE_PARSER(15);\n\ttileParseFields[\"lowmask\"] = INT_PARSER(lowmask);\n\ttileParseFields[\"highmask\"] = INT_PARSER(highmask);\n\ttileParseFields[\"lightmask\"] = INT_PARSER(lightmask);\n\ttileParseFields[\"vismask\"] = INT_PARSER(vismask);\n\ttileParseFields[\"name\"] = NAME_PARSER;\n\ttileParseFields[\"material\"] = MAT_PARSER;\n}\n\n\/\/ LEVEL PARSING\nstatic unordered_map<const char*, jsonParseFunc> levelParseFields;\nvoid InitLevelParseFields() {\n#define NAME_PARSER [](cJSON* j, void* p) -> void { MapDatum* t = (MapDatum*)p; strcpy(t->name, cJSON_ToString(j)); }\n#define LEVEL_PARSER [](cJSON* j, void* p) -> void { MapDatum* t = (MapDatum*)p; t->nDungeonLevel = cJSON_ToInteger(j); }\n#define VIS_PARSER(x) [](cJSON* j, void*p) -> void { MapDatum* t = (MapDatum*)p; t->iLink[x] = cJSON_ToInteger(j); }\n\tlevelParseFields[\"name\"] = NAME_PARSER;\n\tlevelParseFields[\"level\"] = LEVEL_PARSER;\n\tlevelParseFields[\"vis0\"] = VIS_PARSER(0);\n\tlevelParseFields[\"vis1\"] = VIS_PARSER(1);\n\tlevelParseFields[\"vis2\"] = VIS_PARSER(2);\n\tlevelParseFields[\"vis3\"] = VIS_PARSER(3);\n\tlevelParseFields[\"vis4\"] = VIS_PARSER(4);\n\tlevelParseFields[\"vis5\"] = VIS_PARSER(5);\n\tlevelParseFields[\"vis6\"] = VIS_PARSER(6);\n\tlevelParseFields[\"vis7\"] = VIS_PARSER(7);\n\tlevelParseFields[\"vis8\"] = VIS_PARSER(8);\n\tlevelParseFields[\"vis9\"] = VIS_PARSER(9);\n}\n\nWorldspace world;\nvector<MapDatum> vMapData;\n\nMapLoader::MapLoader(const string& presetsPath, const string& tilePath) {\n\t\/\/ Load the tiles.\n\tInitTileParseFields();\n\tvector<string> paths;\n\tint numFiles = trap->ListFilesInDir(tilePath.c_str(), paths, \".json\");\n\tif(numFiles <= 0) {\n\t\tR_Error(\"MapLoader could not load tiles (missing?)\");\n\t}\n\tfor(auto it = paths.begin(); it != paths.end(); ++it) {\n\t\tTile t;\n\t\tJSON_ParseFile((char*)it->c_str(), tileParseFields, &t);\n\t\tvTiles.push_back(t);\n\t\tmTileResolver.insert(make_pair(t.name, vTiles.end()-1));\n\t}\n\n\t\/\/ Load the Levels.json\n\tJSON_ParseMultifile<MapDatum>(\"levels\/Levels.json\", levelParseFields, vMapData);\n\n\t\/\/ Finally, start loading the maps which are important.\n}\n\nMapLoader::~MapLoader() {\n\tmTileResolver.clear();\n\tvTiles.clear();\n\ttileParseFields.clear();\n}\n\nMapLoader* maps;\nvoid InitLevels() {\n\tmaps = new MapLoader(\"levels\/preset\", \"levels\/tiles\");\n}\n\nvoid ShutdownLevels() {\n\tdelete maps;\n}<commit_msg>Fixed silly mistake with Levels.json parsing<commit_after>#include \"g_json.h\"\n\n\/\/ TILE PARSING\nstatic unordered_map<const char*, jsonParseFunc> tileParseFields;\n\nvoid ParseSubtile(cJSON* json, void* ptTile, int tileNum) {\n\tTile* t = (Tile*)ptTile;\n\tif(!t) {\n\t\treturn;\n\t}\n\tcJSON* jsonNode = cJSON_GetObjectItem(json, \"low\");\n\tif(jsonNode) {\n\t\tt->lowmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"high\");\n\tif(jsonNode) {\n\t\tt->highmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"light\");\n\tif(jsonNode) {\n\t\tt->lightmask |= (1 << tileNum);\n\t}\n\n\tjsonNode = cJSON_GetObjectItem(json, \"vis\");\n\tif(jsonNode) {\n\t\tt->vismask |= (1 << tileNum);\n\t}\n}\n\nvoid InitTileParseFields() {\n#define SUBTILE_PARSER(x) [](cJSON* j, void* p) -> void { ParseSubtile(j, p, x); }\n#define INT_PARSER(x) [](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; t->##x## = cJSON_ToInteger(j); }\n#define NAME_PARSER [](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; strcpy(t->name, cJSON_ToString(j)); }\n#define MAT_PARSER \\\n\t[](cJSON* j, void* p) -> void { Tile* t = (Tile*)p; t->materialHandle = trap->RegisterMaterial(cJSON_ToString(j)); }\n\n\ttileParseFields[\"subtile0\"] = SUBTILE_PARSER(0);\n\ttileParseFields[\"subtile1\"] = SUBTILE_PARSER(1);\n\ttileParseFields[\"subtile2\"] = SUBTILE_PARSER(2);\n\ttileParseFields[\"subtile3\"] = SUBTILE_PARSER(3);\n\ttileParseFields[\"subtile4\"] = SUBTILE_PARSER(4);\n\ttileParseFields[\"subtile5\"] = SUBTILE_PARSER(5);\n\ttileParseFields[\"subtile6\"] = SUBTILE_PARSER(6);\n\ttileParseFields[\"subtile7\"] = SUBTILE_PARSER(7);\n\ttileParseFields[\"subtile8\"] = SUBTILE_PARSER(8);\n\ttileParseFields[\"subtile9\"] = SUBTILE_PARSER(9);\n\ttileParseFields[\"subtile10\"] = SUBTILE_PARSER(10);\n\ttileParseFields[\"subtile11\"] = SUBTILE_PARSER(11);\n\ttileParseFields[\"subtile12\"] = SUBTILE_PARSER(12);\n\ttileParseFields[\"subtile13\"] = SUBTILE_PARSER(13);\n\ttileParseFields[\"subtile14\"] = SUBTILE_PARSER(14);\n\ttileParseFields[\"subtile15\"] = SUBTILE_PARSER(15);\n\ttileParseFields[\"lowmask\"] = INT_PARSER(lowmask);\n\ttileParseFields[\"highmask\"] = INT_PARSER(highmask);\n\ttileParseFields[\"lightmask\"] = INT_PARSER(lightmask);\n\ttileParseFields[\"vismask\"] = INT_PARSER(vismask);\n\ttileParseFields[\"name\"] = NAME_PARSER;\n\ttileParseFields[\"material\"] = MAT_PARSER;\n}\n\n\/\/ LEVEL PARSING\nstatic unordered_map<const char*, jsonParseFunc> levelParseFields;\nvoid InitLevelParseFields() {\n#define NAME_PARSER [](cJSON* j, void* p) -> void { MapDatum* t = (MapDatum*)p; strcpy(t->name, cJSON_ToString(j)); }\n#define LEVEL_PARSER [](cJSON* j, void* p) -> void { MapDatum* t = (MapDatum*)p; t->nDungeonLevel = cJSON_ToInteger(j); }\n#define VIS_PARSER(x) [](cJSON* j, void*p) -> void { MapDatum* t = (MapDatum*)p; t->iLink[x] = cJSON_ToInteger(j); }\n\tlevelParseFields[\"name\"] = NAME_PARSER;\n\tlevelParseFields[\"level\"] = LEVEL_PARSER;\n\tlevelParseFields[\"vis0\"] = VIS_PARSER(0);\n\tlevelParseFields[\"vis1\"] = VIS_PARSER(1);\n\tlevelParseFields[\"vis2\"] = VIS_PARSER(2);\n\tlevelParseFields[\"vis3\"] = VIS_PARSER(3);\n\tlevelParseFields[\"vis4\"] = VIS_PARSER(4);\n\tlevelParseFields[\"vis5\"] = VIS_PARSER(5);\n\tlevelParseFields[\"vis6\"] = VIS_PARSER(6);\n\tlevelParseFields[\"vis7\"] = VIS_PARSER(7);\n\tlevelParseFields[\"vis8\"] = VIS_PARSER(8);\n\tlevelParseFields[\"vis9\"] = VIS_PARSER(9);\n}\n\nWorldspace world;\nvector<MapDatum> vMapData;\n\nMapLoader::MapLoader(const string& presetsPath, const string& tilePath) {\n\t\/\/ Load the tiles.\n\tInitTileParseFields();\n\tvector<string> paths;\n\tint numFiles = trap->ListFilesInDir(tilePath.c_str(), paths, \".json\");\n\tif(numFiles <= 0) {\n\t\tR_Error(\"MapLoader could not load tiles (missing?)\");\n\t}\n\tfor(auto it = paths.begin(); it != paths.end(); ++it) {\n\t\tTile t;\n\t\tJSON_ParseFile((char*)it->c_str(), tileParseFields, &t);\n\t\tvTiles.push_back(t);\n\t\tmTileResolver.insert(make_pair(t.name, vTiles.end()-1));\n\t}\n\n\t\/\/ Load the Levels.json\n\tInitLevelParseFields();\n\tJSON_ParseMultifile<MapDatum>(\"levels\/Levels.json\", levelParseFields, vMapData);\n\n\t\/\/ Finally, start loading the maps which are important.\n}\n\nMapLoader::~MapLoader() {\n\tmTileResolver.clear();\n\tvTiles.clear();\n\ttileParseFields.clear();\n}\n\nMapLoader* maps;\nvoid InitLevels() {\n\tmaps = new MapLoader(\"levels\/preset\", \"levels\/tiles\");\n}\n\nvoid ShutdownLevels() {\n\tdelete maps;\n}<|endoftext|>"} {"text":"<commit_before>#include <exception>\n#include <QAction>\n#include <QClipboard>\n#include <QCursor>\n#include <QDebug>\n#include <QFile>\n#include <QFileDialog>\n#include <QMap>\n#include <QMapIterator>\n#include <QMenu>\n#include <QMessageBox>\n#include <QModelIndex>\n#include <QString>\n#include <QStringList>\n#include <QTableWidgetItem>\n#include <QTableWidgetSelectionRange>\n#include <QTextStream>\n#include \"columnmappingdialog.hpp\"\n#include \"mainwindow.hpp\"\n#include \"sfcsv\/sfcsv.h\"\n#include \"ui_mainwindow.h\"\n\nstatic QStringList parseCsv(const QString& in) {\n QStringList result;\n std::vector<std::string> parsed;\n const std::string line = in.toStdString();\n sfcsv::parse_line(line, std::back_inserter(parsed), ',');\n for(auto&& res : parsed) {\n result.append(QString::fromStdString(res));\n }\n\n return result;\n}\n\nQStringList parseFile(const QString& in) {\n QStringList results;\n QFile inFile(in);\n if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n throw std::runtime_error(\"Unable to open file\");\n }\n\n QTextStream stream(&inFile);\n while(!stream.atEnd()) {\n const QString line = stream.readLine().remove(\"\\n\");\n results << line;\n }\n\n return results;\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n config(\"config.ini\", QSettings::IniFormat)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n\n config.remove(\"has_header\");\n}\n\nvoid MainWindow::on_actionOpen_triggered()\n{\n const QString openedFile =\n QFileDialog::getOpenFileName(this, tr(\"Open...\"),\n config.value(\"last_opened\").toString());\n if(openedFile.isEmpty()) {\n return;\n }\n\n config.setValue(\"last_opened\", openedFile);\n\n \/\/ Read first row from CSV file\n QString firstRow;\n QFile inFile(config.value(\"last_opened\").toString());\n if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n throw std::runtime_error(\"Unable to open file\");\n }\n\n firstRow = inFile.readLine();\n firstRow.remove('\\n');\n\n const QStringList source = parseCsv(firstRow);\n config.setValue(\"source_keys\", source);\n\n try {\n ColumnMappingDialog dlg;\n const auto ok = dlg.exec();\n if(!ok) {\n return;\n }\n\n \/\/ Get all rows\n QStringList lines = parseFile(openedFile);\n if(lines.isEmpty()) {\n QMessageBox::critical(this, tr(\"Empty CSV\"),\n tr(\"CSV file does not contain any data\"));\n return;\n }\n\n \/\/ Set header\n ui->tableCsv->clear();\n ui->tableCsv->setRowCount(lines.size());\n ui->tableCsv->setColumnCount(lines.size());\n const bool hasHeader = config.value(\"has_header\", false).toBool();\n if(hasHeader) {\n const QStringList labels = parseCsv(lines.at(0));\n ui->tableCsv->setColumnCount(labels.size());\n ui->tableCsv->setHorizontalHeaderLabels(labels);\n lines.removeAt(0);\n if(lines.isEmpty()) {\n QMessageBox::critical(this, tr(\"Empty CSV\"),\n tr(\"CSV file contains only a header\"));\n return;\n }\n }\n\n \/\/ Display data\n for(int i = 0, size = lines.size(); i < size; ++i) {\n const QStringList parsed = parseCsv(lines.at(i));\n for(int j = 0, jsize = parsed.size(); j < jsize; ++j) {\n auto item = new QTableWidgetItem(parsed.at(j));\n ui->tableCsv->setItem(i, j, item);\n }\n }\n\n }\n catch(std::exception &ex) {\n QMessageBox::critical(this, tr(\"Error\"), QString(ex.what()));\n }\n}\n\nvoid MainWindow::on_tableCsv_customContextMenuRequested(const QPoint &pos)\n{\n Q_UNUSED(pos);\n\n QMenu menu;\n auto cbAction = new QAction(tr(\"Copy to clipboard\"), this);\n cbAction->setData(\"clipboard\");\n menu.addAction(cbAction);\n auto selected = menu.exec(QCursor::pos());\n if(selected && selected->data().toString() == \"clipboard\") {\n const auto ranges = ui->tableCsv->selectedRanges();\n QString parsedTpl;\n for(const auto& range : ranges) {\n const QStringList list = config.value(\"mapped_keys\").toStringList();\n QMap<QString, QString> mappings;\n for(int rIdx = range.topRow(), rEnd = range.bottomRow(); rIdx <= rEnd; ++rIdx) {\n for(int i = 0, end = ui->tableCsv->columnCount(); i != end; ++i) {\n mappings.insert(list.at(i), ui->tableCsv->item(rIdx, i)->text());\n }\n\n QString tpl = ui->templateEdit->toPlainText();\n QMapIterator<QString, QString> iter(mappings);\n while(iter.hasNext()) {\n iter.next();\n const QString var = tr(\"$%1\").arg(iter.key());\n tpl.replace(var, iter.value());\n }\n\n parsedTpl.append(tpl);\n }\n }\n\n auto clipboard = QApplication::clipboard();\n clipboard->setText(parsedTpl);\n }\n}\n\nvoid MainWindow::on_actionMappings_triggered()\n{\n\n}\n<commit_msg>Remove keys after closing app<commit_after>#include <exception>\n#include <QAction>\n#include <QClipboard>\n#include <QCursor>\n#include <QDebug>\n#include <QFile>\n#include <QFileDialog>\n#include <QMap>\n#include <QMapIterator>\n#include <QMenu>\n#include <QMessageBox>\n#include <QModelIndex>\n#include <QString>\n#include <QStringList>\n#include <QTableWidgetItem>\n#include <QTableWidgetSelectionRange>\n#include <QTextStream>\n#include \"columnmappingdialog.hpp\"\n#include \"mainwindow.hpp\"\n#include \"sfcsv\/sfcsv.h\"\n#include \"ui_mainwindow.h\"\n\nstatic QStringList parseCsv(const QString& in) {\n QStringList result;\n std::vector<std::string> parsed;\n const std::string line = in.toStdString();\n sfcsv::parse_line(line, std::back_inserter(parsed), ',');\n for(auto&& res : parsed) {\n result.append(QString::fromStdString(res));\n }\n\n return result;\n}\n\nQStringList parseFile(const QString& in) {\n QStringList results;\n QFile inFile(in);\n if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n throw std::runtime_error(\"Unable to open file\");\n }\n\n QTextStream stream(&inFile);\n while(!stream.atEnd()) {\n const QString line = stream.readLine().remove(\"\\n\");\n results << line;\n }\n\n return results;\n}\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n config(\"config.ini\", QSettings::IniFormat)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n\n config.remove(\"has_header\");\n config.remove(\"source_keys\");\n config.remove(\"mapped_keys\");\n}\n\nvoid MainWindow::on_actionOpen_triggered()\n{\n const QString openedFile =\n QFileDialog::getOpenFileName(this, tr(\"Open...\"),\n config.value(\"last_opened\").toString());\n if(openedFile.isEmpty()) {\n return;\n }\n\n config.setValue(\"last_opened\", openedFile);\n\n \/\/ Read first row from CSV file\n QString firstRow;\n QFile inFile(config.value(\"last_opened\").toString());\n if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n throw std::runtime_error(\"Unable to open file\");\n }\n\n firstRow = inFile.readLine();\n firstRow.remove('\\n');\n\n const QStringList source = parseCsv(firstRow);\n config.setValue(\"source_keys\", source);\n\n try {\n ColumnMappingDialog dlg;\n const auto ok = dlg.exec();\n if(!ok) {\n return;\n }\n\n \/\/ Get all rows\n QStringList lines = parseFile(openedFile);\n if(lines.isEmpty()) {\n QMessageBox::critical(this, tr(\"Empty CSV\"),\n tr(\"CSV file does not contain any data\"));\n return;\n }\n\n \/\/ Set header\n ui->tableCsv->clear();\n ui->tableCsv->setRowCount(lines.size());\n ui->tableCsv->setColumnCount(lines.size());\n const bool hasHeader = config.value(\"has_header\", false).toBool();\n if(hasHeader) {\n const QStringList labels = parseCsv(lines.at(0));\n ui->tableCsv->setColumnCount(labels.size());\n ui->tableCsv->setHorizontalHeaderLabels(labels);\n lines.removeAt(0);\n if(lines.isEmpty()) {\n QMessageBox::critical(this, tr(\"Empty CSV\"),\n tr(\"CSV file contains only a header\"));\n return;\n }\n }\n\n \/\/ Display data\n for(int i = 0, size = lines.size(); i < size; ++i) {\n const QStringList parsed = parseCsv(lines.at(i));\n for(int j = 0, jsize = parsed.size(); j < jsize; ++j) {\n auto item = new QTableWidgetItem(parsed.at(j));\n ui->tableCsv->setItem(i, j, item);\n }\n }\n\n }\n catch(std::exception &ex) {\n QMessageBox::critical(this, tr(\"Error\"), QString(ex.what()));\n }\n}\n\nvoid MainWindow::on_tableCsv_customContextMenuRequested(const QPoint &pos)\n{\n Q_UNUSED(pos);\n\n QMenu menu;\n auto cbAction = new QAction(tr(\"Copy to clipboard\"), this);\n cbAction->setData(\"clipboard\");\n menu.addAction(cbAction);\n auto selected = menu.exec(QCursor::pos());\n if(selected && selected->data().toString() == \"clipboard\") {\n const auto ranges = ui->tableCsv->selectedRanges();\n QString parsedTpl;\n for(const auto& range : ranges) {\n const QStringList list = config.value(\"mapped_keys\").toStringList();\n QMap<QString, QString> mappings;\n for(int rIdx = range.topRow(), rEnd = range.bottomRow(); rIdx <= rEnd; ++rIdx) {\n for(int i = 0, end = ui->tableCsv->columnCount(); i != end; ++i) {\n mappings.insert(list.at(i), ui->tableCsv->item(rIdx, i)->text());\n }\n\n QString tpl = ui->templateEdit->toPlainText();\n QMapIterator<QString, QString> iter(mappings);\n while(iter.hasNext()) {\n iter.next();\n const QString var = tr(\"$%1\").arg(iter.key());\n tpl.replace(var, iter.value());\n }\n\n parsedTpl.append(tpl);\n }\n }\n\n auto clipboard = QApplication::clipboard();\n clipboard->setText(parsedTpl);\n }\n}\n\nvoid MainWindow::on_actionMappings_triggered()\n{\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <stdio.h>\n#include <QScrollBar>\n#include <QFileDialog>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include \"hardware\/camera\/qopencvcamera.h\"\n#include \"hardware\/projector\/seconddisplayprojector.h\"\n#include \"geom\/triangulator.h\"\n#include \"hardware\/projector\/gridpattern.h\"\n#include \"hardware\/projector\/flatcolorpattern.h\"\n#include \"hardware\/standards\/dotmatrixstandard.h\"\n#include \"hardware\/standards\/chessboardstandard.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n calib(new CalibrationDialog),\n debugWin(new QPlainTextEdit),\n graycode(new GrayCodePattern(1,false)),\n dbgIm(new ImageViewWidget),\n singleCal(new SingleCalibrationDialog),\n bg(0),\n singleCal2(new SingleCalibrationDialog),\n sinusoidPower(6),\n sinusoidShifts(8)\n{\n ui->setupUi(this);\n\n debugWin->setPlainText(QString(\"ScanStudio started.\"));\n debugWin->setWindowTitle(QString(\"Debugging info\"));\n debugWin->setWindowIcon(\n QIcon(tr(\":\/icons\/oxygen\/camera-web-64.png\")));\n debugWin->setWindowFlags(Qt::WindowStaysOnTopHint);\n debugWin->setReadOnly(true);\n\n connect(&stdSettings,SIGNAL(accept()),this,SLOT(adjustCalStd()));\n connect(&camSettings,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(&camSettings,\n SIGNAL(acceptedCameras(QCamera*,QCamera*)),\n this,\n SLOT(cameraSettingsChanged(QCamera*,QCamera*)));\n\n ui->modelView->zoomFit();\n dbgIm->setWindowTitle(\"Debugging -- camera view\");\n\n QOpenCVCamera *capCam = new QOpenCVCamera(2);\n connect(capCam,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n capCam->setResolution(1600,1200);\n capCam->setPrincipalPoint(800,600);\n capCam->setFocalLength(1300);\n capCam->setPosition(cv::Vec3d(-0.25,-0.01,0));\n capCam->setOrientation(cv::Vec3d(0,M_PI\/12,0));\n\n camera = capCam;\n\n QOpenCVCamera *capCam2 = new QOpenCVCamera(1);\n connect(capCam2,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n capCam2->setResolution(1600,1200);\n capCam2->setPrincipalPoint(800,600);\n capCam2->setFocalLength(1300);\n capCam2->setPosition(cv::Vec3d(0.2,0,0));\n capCam2->setOrientation(cv::Vec3d(0,-0.1,0));\n\n camera2 = capCam2;\n\n SecondDisplayProjector *pj = new SecondDisplayProjector();\n pj->setScreen(1);\n pj->setResolution(848,480);\n pj->setPrincipalPoint(848\/2,480\/2);\n pj->setPosition(cv::Vec3d(0.0,0,0));\n pj->setOrientation(cv::Vec3d(-0*M_PI\/180,0.0,0.0));\n pj->setFocalLength(3600);\n\n GridPattern *grid = new GridPattern();\n pj->queue(grid);\n\/\/ FlatColorPattern *flat = new FlatColorPattern();\n\/\/ pj->queue(flat);\n\n projector = pj;\n capCam->connectProjector(pj);\n capCam2->connectProjector(pj);\n\n\n compiler = new BinaryCompiler(capCam);\n compiler->setProjector(pj);\n\n fringer = new PhaseCompiler(capCam);\n fringer->setProjector(pj);\n\n singleCal->setCamera(capCam);\n singleCal2->setCamera(capCam2);\n\n \/\/ debug our components\n\n connect(pj,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n\/\/ connect(compiler,\n\/\/ SIGNAL(visualBinaryFrame(cv::Mat)),\n\/\/ this,\n\/\/ SLOT(debugImage(cv::Mat)));\n connect(compiler,\n SIGNAL(visualBinaryFrame(cv::Mat)),\n this,\n SLOT(writeDebugImg1(cv::Mat)));\n connect(compiler,\n SIGNAL(binaryFrameCaptured(cv::Mat,bool)),\n this,\n SLOT(binaryImageCaptured(cv::Mat,bool)));\n connect(compiler,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(calib,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(fringer, SIGNAL(phaseMapCaptured(cv::Mat,bool)),\n this, SLOT(phaseMapCaptured(cv::Mat,bool)));\n\n connect(ui->analysis, SIGNAL(plotCrossSection(QString,cv::Mat)),\n ui->plot, SLOT(plotLine(QString,cv::Mat)));\n connect(ui->analysis, SIGNAL(cropXChanged(int,int)),\n ui->plot, SLOT(setXRange(int,int)));\n\n\n\n\/\/ standard = new DotMatrixStandard(cv::Size(6,7),\n\/\/ 0.91*20e-3, 0.91*17e-3,\n\/\/ 0.91*10e-3);\n standard = new ChessboardStandard(cv::Size(9,12),20e-3);\n singleCal->setStandard(standard);\n\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n QCoreApplication::exit(0);\n\n}\n\nvoid MainWindow::debug(QString str)\n{\n debugWin->setPlainText(QString(\"%1\\n%2\")\n .arg(debugWin->toPlainText())\n .arg(str));\n QScrollBar *sb = debugWin->verticalScrollBar();\n sb->setValue(sb->maximum());\n}\n\nvoid MainWindow::debug(const char *str)\n{\n debug(QString(str));\n}\n\nvoid MainWindow::showDebug()\n{\n debugWin->show();\n}\n\nvoid MainWindow::cameraSettingsChanged(QCamera *first, QCamera *)\n{\n QOpenCVCamera *cv = dynamic_cast<QOpenCVCamera*>(first);\n if(!cv) return;\n connect(first,\n SIGNAL(frameCaptured(cv::Mat,QCamera::FrameType,QCamera*)),\n this,\n SLOT(debugImage(cv::Mat,QCamera::FrameType,QCamera*)));\n cv->startStream();\n}\n\nvoid MainWindow::debugImage(cv::Mat im,\n QCamera*,\n QProjector::Pattern*)\n{\n debug(\"User interface displays image.\");\n if(im.channels()==3){\n cv::Mat3b img;\n im.convertTo(img,CV_8UC3);\n dbgIm->displayImage(img,true);\n dbgIm->show();\n return;\n }\n cv::Mat_<double> m;\n im.convertTo(m,CV_64F);\n dbgIm->displayImage(m,true);\n dbgIm->show();\n dbgIm->raise();\n}\n\nvoid MainWindow::debugImage(cv::Mat im)\n{\n debugImage(im,0,0);\n}\n\nvoid MainWindow::binaryImageCaptured(cv::Mat binary, bool)\n{\n \/\/ do nothing if the calibration dialog is open\n \/\/ hacky; fix later\n if(calib->isVisible()) return;\n binary.convertTo(lastBinaryFrame,CV_64F);\n ui->analysis->setBinary(lastBinaryFrame);\n computeCombinedGeometry();\n\n geom = Triangulator::computeSheet(\n lastBinaryFrame,\n camera,\n projector,\n 1);\n\/\/ geom->removeNonManifold();\n\/\/ std::cout << \"foreground: \" << geom << '\\n';\n\/\/ if(bg) geom->removeBackground(bg,0.005);\n ui->modelView->setData(geom);\n}\n\nvoid MainWindow::writeDebugImg1(cv::Mat im)\n{\n cv::imwrite(\"\/home\/ryan\/Documents\/mqp-data\/debug\/cam1.png\",im);\n}\n\nvoid MainWindow::writeDebugImg2(cv::Mat im)\n{\n cv::imwrite(\"\/home\/ryan\/Documents\/mqp-data\/debug\/cam2.png\",im);\n}\n\nvoid MainWindow::saveSTL()\n{\n QString fnm;\n fnm = QFileDialog::getSaveFileName(\n this,\n tr(\"Save STL\"),\n QDir::homePath(),\n tr(\"Standard Tesselation Language(*.stl)\"));\n if(fnm.length()>0){\n if(!fnm.endsWith(\".stl\")){\n fnm = fnm.append(\".stl\");\n }\n geom->saveSTL(fnm.toLocal8Bit().data());\n }\n}\n\nvoid MainWindow::setAsBackground()\n{\n std::cout << \"background: \" << geom << '\\n';\n bg = geom;\n ui->modelView->setBackground(geom);\n ui->modelView->setData(0);\n}\n\nvoid MainWindow::setShifts(int shifts)\n{\n sinusoidShifts = shifts;\n}\n\nvoid MainWindow::setBits(int bits)\n{\n sinusoidPower = bits;\n}\n\nvoid MainWindow::showAbout()\n{\n about.show();\n}\n\nvoid MainWindow::setFullScreen(bool fs)\n{\n if(fs){\n showFullScreen();\n }else{\n showNormal();\n }\n}\n\nvoid MainWindow::showCameraSettings()\n{\n debug(\"Showing camera settings.\");\n singleCal->open();\n}\n\nvoid MainWindow::showCamera2Settings()\n{\n debug(\"Showing camera 2 settings.\");\n singleCal2->open();\n}\n\nvoid MainWindow::showProjectorSettings()\n{\n projSettings.show();\n}\n\nvoid MainWindow::showCalStdSettings()\n{\n debug(\"Show calibration standard settings.\");\n stdSettings.show();\n}\n\nvoid MainWindow::showCalibrationDialog()\n{\n calib->setLeft(camera);\n calib->setRight(camera2);\n calib->setProjector(projector);\n calib->setBinary(compiler);\n calib->show();\n}\n\nvoid MainWindow::quitProgram()\n{\n QCoreApplication::exit(0);\n}\n\nvoid MainWindow::adjustCalStd()\n{\n enableCalibrate();\n}\n\nvoid MainWindow::takeFrame()\n{\n compiler->requestFrame(10);\n fringer->requestFrame(1<<(sinusoidPower-1),sinusoidShifts);\n}\n\nvoid MainWindow::phaseMapCaptured(cv::Mat ph, bool)\n{\n lastPhaseMap = ph;\n ui->analysis->setPhaseMap(ph);\n computeCombinedGeometry();\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *)\n{\n quitProgram();\n}\n\nvoid MainWindow::enableCalibrate()\n{\n\/\/ ui->actionCalibrate->setEnabled(true);\n}\n\nvoid MainWindow::computeCombinedGeometry()\n{\n return;\n lastCombined = Triangulator::combineBinaryAndPhase(\n lastBinaryFrame,\n lastPhaseMap,\n sinusoidPower);\n geom = Triangulator::computeSheet(\n lastPhaseMap,\n camera,\n projector,\n 1);\n ui->modelView->setData(geom);\n}\n<commit_msg>stash<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <stdio.h>\n#include <QScrollBar>\n#include <QFileDialog>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include \"hardware\/camera\/qopencvcamera.h\"\n#include \"hardware\/projector\/seconddisplayprojector.h\"\n#include \"geom\/triangulator.h\"\n#include \"hardware\/projector\/gridpattern.h\"\n#include \"hardware\/projector\/flatcolorpattern.h\"\n#include \"hardware\/standards\/dotmatrixstandard.h\"\n#include \"hardware\/standards\/chessboardstandard.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n calib(new CalibrationDialog),\n debugWin(new QPlainTextEdit),\n graycode(new GrayCodePattern(1,false)),\n dbgIm(new ImageViewWidget),\n singleCal(new SingleCalibrationDialog),\n bg(0),\n singleCal2(new SingleCalibrationDialog),\n sinusoidPower(6),\n sinusoidShifts(8)\n{\n ui->setupUi(this);\n\n debugWin->setPlainText(QString(\"ScanStudio started.\"));\n debugWin->setWindowTitle(QString(\"Debugging info\"));\n debugWin->setWindowIcon(\n QIcon(tr(\":\/icons\/oxygen\/camera-web-64.png\")));\n debugWin->setWindowFlags(Qt::WindowStaysOnTopHint);\n debugWin->setReadOnly(true);\n\n connect(&stdSettings,SIGNAL(accept()),this,SLOT(adjustCalStd()));\n connect(&camSettings,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(&camSettings,\n SIGNAL(acceptedCameras(QCamera*,QCamera*)),\n this,\n SLOT(cameraSettingsChanged(QCamera*,QCamera*)));\n\n ui->modelView->zoomFit();\n dbgIm->setWindowTitle(\"Debugging -- camera view\");\n\n QOpenCVCamera *capCam = new QOpenCVCamera(2);\n connect(capCam,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n capCam->setResolution(1600,1200);\n capCam->setPrincipalPoint(800,600);\n capCam->setFocalLength(1300);\n capCam->setPosition(cv::Vec3d(-0.25,-0.01,0));\n capCam->setOrientation(cv::Vec3d(0,M_PI\/12,0));\n\n camera = capCam;\n\n QOpenCVCamera *capCam2 = new QOpenCVCamera(1);\n connect(capCam2,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n capCam2->setResolution(1600,1200);\n capCam2->setPrincipalPoint(800,600);\n capCam2->setFocalLength(1300);\n capCam2->setPosition(cv::Vec3d(0.2,0,0));\n capCam2->setOrientation(cv::Vec3d(0,-0.1,0));\n\n camera2 = capCam2;\n\n SecondDisplayProjector *pj = new SecondDisplayProjector();\n pj->setScreen(1);\n pj->setResolution(848,480);\n pj->setPrincipalPoint(848\/2,480\/2);\n pj->setPosition(cv::Vec3d(0.0,0,0));\n pj->setOrientation(cv::Vec3d(-0*M_PI\/180,0.0,0.0));\n pj->setFocalLength(3600);\n\n GridPattern *grid = new GridPattern();\n pj->queue(grid);\n\/\/ FlatColorPattern *flat = new FlatColorPattern();\n\/\/ pj->queue(flat);\n\n projector = pj;\n capCam->connectProjector(pj);\n capCam2->connectProjector(pj);\n\n\n compiler = new BinaryCompiler(capCam);\n compiler->setProjector(pj);\n\n fringer = new PhaseCompiler(capCam);\n fringer->setProjector(pj);\n\n singleCal->setCamera(capCam);\n singleCal2->setCamera(capCam2);\n\n \/\/ debug our components\n\n connect(pj,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n\/\/ connect(compiler,\n\/\/ SIGNAL(visualBinaryFrame(cv::Mat)),\n\/\/ this,\n\/\/ SLOT(debugImage(cv::Mat)));\n connect(compiler,\n SIGNAL(visualBinaryFrame(cv::Mat)),\n this,\n SLOT(writeDebugImg1(cv::Mat)));\n connect(compiler,\n SIGNAL(binaryFrameCaptured(cv::Mat,bool)),\n this,\n SLOT(binaryImageCaptured(cv::Mat,bool)));\n connect(compiler,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(calib,\n SIGNAL(debug(QString)),\n this,\n SLOT(debug(QString)));\n connect(fringer, SIGNAL(phaseMapCaptured(cv::Mat,bool)),\n this, SLOT(phaseMapCaptured(cv::Mat,bool)));\n\n connect(ui->analysis, SIGNAL(plotCrossSection(QString,cv::Mat)),\n ui->plot, SLOT(plotLine(QString,cv::Mat)));\n connect(ui->analysis, SIGNAL(cropXChanged(int,int)),\n ui->plot, SLOT(setXRange(int,int)));\n\n\n\n\/\/ standard = new DotMatrixStandard(cv::Size(6,7),\n\/\/ 0.91*20e-3, 0.91*17e-3,\n\/\/ 0.91*10e-3);\n standard = new ChessboardStandard(cv::Size(9,12),20e-3);\n singleCal->setStandard(standard);\n\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n QCoreApplication::exit(0);\n\n}\n\nvoid MainWindow::debug(QString str)\n{\n debugWin->setPlainText(QString(\"%1\\n%2\")\n .arg(debugWin->toPlainText())\n .arg(str));\n QScrollBar *sb = debugWin->verticalScrollBar();\n sb->setValue(sb->maximum());\n}\n\nvoid MainWindow::debug(const char *str)\n{\n debug(QString(str));\n}\n\nvoid MainWindow::showDebug()\n{\n debugWin->show();\n}\n\nvoid MainWindow::cameraSettingsChanged(QCamera *first, QCamera *)\n{\n QOpenCVCamera *cv = dynamic_cast<QOpenCVCamera*>(first);\n if(!cv) return;\n connect(first,\n SIGNAL(frameCaptured(cv::Mat,QCamera::FrameType,QCamera*)),\n this,\n SLOT(debugImage(cv::Mat,QCamera::FrameType,QCamera*)));\n cv->startStream();\n}\n\nvoid MainWindow::debugImage(cv::Mat im,\n QCamera*,\n QProjector::Pattern*)\n{\n debug(\"User interface displays image.\");\n if(im.channels()==3){\n cv::Mat3b img;\n im.convertTo(img,CV_8UC3);\n dbgIm->displayImage(img,true);\n dbgIm->show();\n return;\n }\n cv::Mat_<double> m;\n im.convertTo(m,CV_64F);\n dbgIm->displayImage(m,true);\n dbgIm->show();\n dbgIm->raise();\n}\n\nvoid MainWindow::debugImage(cv::Mat im)\n{\n debugImage(im,0,0);\n}\n\nvoid MainWindow::binaryImageCaptured(cv::Mat binary, bool)\n{\n \/\/ do nothing if the calibration dialog is open\n \/\/ hacky; fix later\n if(calib->isVisible()) return;\n binary.convertTo(lastBinaryFrame,CV_64F);\n ui->analysis->setBinary(lastBinaryFrame);\n computeCombinedGeometry();\n\n geom = Triangulator::computeSheet(\n lastBinaryFrame,\n camera,\n projector,\n 1);\n\/\/ geom->removeNonManifold();\n\/\/ std::cout << \"foreground: \" << geom << '\\n';\n\/\/ if(bg) geom->removeBackground(bg,0.005);\n ui->modelView->setData(geom);\n}\n\nvoid MainWindow::writeDebugImg1(cv::Mat im)\n{\n cv::imwrite(\"\/home\/ryan\/Documents\/mqp-data\/debug\/cam1.png\",im);\n}\n\nvoid MainWindow::writeDebugImg2(cv::Mat im)\n{\n cv::imwrite(\"\/home\/ryan\/Documents\/mqp-data\/debug\/cam2.png\",im);\n}\n\nvoid MainWindow::saveSTL()\n{\n QString fnm;\n fnm = QFileDialog::getSaveFileName(\n this,\n tr(\"Save STL\"),\n QDir::homePath(),\n tr(\"Standard Tesselation Language(*.stl)\"));\n if(fnm.length()>0){\n if(!fnm.endsWith(\".stl\")){\n fnm = fnm.append(\".stl\");\n }\n geom->saveSTL(fnm.toLocal8Bit().data());\n }\n}\n\nvoid MainWindow::setAsBackground()\n{\n std::cout << \"background: \" << geom << '\\n';\n bg = geom;\n ui->modelView->setBackground(geom);\n ui->modelView->setData(0);\n}\n\nvoid MainWindow::setShifts(int shifts)\n{\n sinusoidShifts = shifts;\n}\n\nvoid MainWindow::setBits(int bits)\n{\n sinusoidPower = bits;\n}\n\nvoid MainWindow::showAbout()\n{\n about.show();\n}\n\nvoid MainWindow::setFullScreen(bool fs)\n{\n if(fs){\n showFullScreen();\n }else{\n showNormal();\n }\n}\n\nvoid MainWindow::showCameraSettings()\n{\n debug(\"Showing camera settings.\");\n singleCal->open();\n}\n\nvoid MainWindow::showCamera2Settings()\n{\n debug(\"Showing camera 2 settings.\");\n singleCal2->open();\n}\n\nvoid MainWindow::showProjectorSettings()\n{\n projSettings.show();\n}\n\nvoid MainWindow::showCalStdSettings()\n{\n debug(\"Show calibration standard settings.\");\n stdSettings.show();\n}\n\nvoid MainWindow::showCalibrationDialog()\n{\n calib->setLeft(camera);\n calib->setRight(camera2);\n calib->setProjector(projector);\n calib->setBinary(compiler);\n calib->show();\n}\n\nvoid MainWindow::quitProgram()\n{\n QCoreApplication::exit(0);\n}\n\nvoid MainWindow::adjustCalStd()\n{\n enableCalibrate();\n}\n\nvoid MainWindow::takeFrame()\n{\n compiler->requestFrame(10);\n\/\/ fringer->requestFrame(1<<(sinusoidPower-1),sinusoidShifts);\n}\n\nvoid MainWindow::phaseMapCaptured(cv::Mat ph, bool)\n{\n lastPhaseMap = ph;\n ui->analysis->setPhaseMap(ph);\n computeCombinedGeometry();\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *)\n{\n quitProgram();\n}\n\nvoid MainWindow::enableCalibrate()\n{\n\/\/ ui->actionCalibrate->setEnabled(true);\n}\n\nvoid MainWindow::computeCombinedGeometry()\n{\n return;\n lastCombined = Triangulator::combineBinaryAndPhase(\n lastBinaryFrame,\n lastPhaseMap,\n sinusoidPower);\n geom = Triangulator::computeSheet(\n lastPhaseMap,\n camera,\n projector,\n 1);\n ui->modelView->setData(geom);\n}\n<|endoftext|>"} {"text":"<commit_before>#define FTS_FUZZY_MATCH_IMPLEMENTATION\n#include <QtWidgets>\n#include \"mainwindow.h\"\n#include <fts_fuzzy_match.h>\n#include <glob.h>\n#include <string>\n#include <map>\n#include <database.h>\n\nWindow::Window(QWidget *parent) : QMainWindow(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n searchBox->setClearButtonEnabled(true);\n recipeBox = new QComboBox();\n populateRecipeBox(recipeBox);\n createRecipeListWidget();\n numResults = new QLabel();\n recipeView = new QWebEngineView();\n\n \/\/ Set layout\n centralWidget = new QWidget();\n QGridLayout *sidebar = new QGridLayout();\n sidebar->addWidget(searchBox, 0, 0, 1, 2);\n sidebar->addWidget(numResults, 1, 0, 1, 1);\n sidebar->addWidget(recipeBox, 1, 1, 1, 1);\n sidebar->addWidget(recipeList, 2, 0, 1, 2);\n\n QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);\n mainLayout->addLayout(sidebar, 1);\n mainLayout->addWidget(recipeView, 3);\n\n centralWidget->setLayout(mainLayout);\n centralWidget->show();\n setCentralWidget(centralWidget);\n\n \/\/ Create menus\n optionsMenu = new QMenu(\"Options\");\n updateDb = new QAction(\"Update database\", this);\n connect(updateDb, &QAction::triggered, this, &Window::updateDatabase);\n cleanDb = new QAction(\"Clean database\", this);\n connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase);\n optionsMenu->addAction(updateDb);\n optionsMenu->addAction(cleanDb);\n menuBar()->addMenu(optionsMenu);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(940, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Update on startup\n updateDatabase();\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; i<glob_result.gl_pathc; ++i){\n files << QString(glob_result.gl_pathv[i]);\n }\n globfree(&glob_result);\n return files;\n}\n\nvoid SearchBox::recipeFiterChanged(QString newFilter){\n Q_UNUSED(newFilter);\n \/\/ When the recipe filter changes, emit this signal to call updateRecipeDisplay\n emit inputText(text());\n}\n\nvoid SearchBox::keyPressEvent(QKeyEvent *evt){\n QLineEdit::keyPressEvent(evt);\n setPlaceholderText(\"Search for recipes\");\n \/\/ When the search changes, emit this signal to call updateRecipeDisplay\n emit inputText(text());\n}\n\nvoid Window::populateRecipeBox(QComboBox* box){\n \/\/ Open database\n db.open();\n \/\/ Prepare query\n QSqlQuery query = QSqlQuery();\n query.prepare(\"SELECT CATEGORY, COUNT(*) FROM RECIPES GROUP BY CATEGORY ORDER BY CATEGORY\");\n query.setForwardOnly(true);\n query.exec();\n\n box->addItem(\"All Recipes\");\n while(query.next()){\n box->addItem(query.value(\"CATEGORY\").toString());\n }\n db.close();\n}\n\nvoid Window::updateRecipesDiplay(QString searchText){\n recipeList->clear();\n QList<QListWidgetItem*> recipes;\n\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n for (int i=0; i<recipes.size(); ++i){\n recipeList->addItem(recipes[i]);\n }\n recipeList->sortItems();\n\n }else{\n recipes = getMatchingRecipes(searchText);\n for (int i=0; i<recipes.size(); ++i){\n recipeList->addItem(recipes[i]);\n }\n }\n\n recipeList->setDragEnabled(false);\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList<QListWidgetItem*> Window::getAllRecipes(){\n QList<QListWidgetItem*> recipes;\n\n \/\/ Open database and execute query\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES WHERE CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(\"TITLE\").toString();\n QString img_path = query.value(\"IMG_PATH\").toString();\n QString html_path = query.value(\"HTML_PATH\").toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){\n QList<QListWidgetItem*> recipes;\n\n \/\/ Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order.\n std::map<double, QStringList> matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n\n QString title = iter->second[0];\n QString img_path = iter->second[1];\n QString html_path = iter->second[2];\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map<double, QStringList> Window::findMatches(QString text)\n{\n \/\/ Open database\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText();\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES WHERE CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n \/\/ Get matching files and their scores\n std::map<double, QStringList> matchingFiles;\n std::string txtstr = text.toStdString();\n while(query.next()){\n int score;\n QString title = query.value(\"TITLE\").toString();\n QString img_path = query.value(\"IMG_PATH\").toString().replace(\"\\'\", \"\").replace(\",\", \"\");\n QString file_path = query.value(\"HTML_PATH\").toString();\n\n std::string titlestr = title.toStdString();\n if (fts::fuzzy_match(txtstr.c_str(), titlestr.c_str(), score)){\n \/\/ If a map entry already has the current score, increase score by 0.01.\n double dbscore = (double)score;\n if (matchingFiles.count(dbscore) > 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = QStringList() << title << img_path << file_path;\n }\n }\n db.close();\n return matchingFiles;\n}\n\nvoid Window::createRecipeListWidget()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setGridSize(QSize(212, int(212\/1.51)) );\n recipeList->setIconSize(QSize(199, int(199\/1.78)) );\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n recipeList->horizontalScrollBar()->setEnabled(false);\n recipeList->horizontalScrollBar()->setVisible(false);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QString url = \"file:\/\/\" + currentDir.absoluteFilePath(path);\n recipeView->load(url);\n}\n\nvoid Window::updateDatabase(){\n int num_updates = db_ops::update_database(&db);\n QString updated_text;\n if (num_updates == 0){\n updated_text = \"Search for recipes\";\n }else{\n updated_text = \"Search for recipes - Updated!\";\n }\n searchBox->setPlaceholderText(updated_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::cleanDatabase(){\n int num_removals = db_ops::clean_database(&db);\n QString cleaned_text;\n if (num_removals == 1){\n cleaned_text = QString(\"Search for recipes - Removed 1 recipe!\");\n }else{\n cleaned_text = QString(\"Search for recipes - Removed %1 recipes!\").arg(num_removals);\n }\n searchBox->setPlaceholderText(cleaned_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n Q_UNUSED(event);\n int iconWidth, iconHeight, gridWidth, gridHeight;\n double gridRatio = 1.51;\n double iconRatio = 1.78;\n QSize recipeListSize = recipeList->size();\n\n \/\/ Set gridwith based on recipeList size and ensure it doesn't go below minimum value\n gridWidth = qMax(int(recipeListSize.width()) - 17.0, 212.0);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n recipeList->setUniformItemSizes(true);\n}\n\n<commit_msg>Add recipe count to combobox for recipe categories<commit_after>#define FTS_FUZZY_MATCH_IMPLEMENTATION\n#include <QtWidgets>\n#include \"mainwindow.h\"\n#include <fts_fuzzy_match.h>\n#include <glob.h>\n#include <string>\n#include <map>\n#include <database.h>\n\nWindow::Window(QWidget *parent) : QMainWindow(parent)\n{\n \/\/ Initalise database\n db.setDatabaseName(\"recipes.db\");\n\n \/\/ Initialise widgets\n searchBox = new SearchBox();\n searchBox->setPlaceholderText(\"Search for recipes\");\n searchBox->setClearButtonEnabled(true);\n recipeBox = new QComboBox();\n populateRecipeBox(recipeBox);\n createRecipeListWidget();\n numResults = new QLabel();\n recipeView = new QWebEngineView();\n\n \/\/ Set layout\n centralWidget = new QWidget();\n QGridLayout *sidebar = new QGridLayout();\n sidebar->addWidget(searchBox, 0, 0, 1, 2);\n sidebar->addWidget(numResults, 1, 0, 1, 1);\n sidebar->addWidget(recipeBox, 1, 1, 1, 1);\n sidebar->addWidget(recipeList, 2, 0, 1, 2);\n\n QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);\n mainLayout->addLayout(sidebar, 1);\n mainLayout->addWidget(recipeView, 3);\n\n centralWidget->setLayout(mainLayout);\n centralWidget->show();\n setCentralWidget(centralWidget);\n\n \/\/ Create menus\n optionsMenu = new QMenu(\"Options\");\n updateDb = new QAction(\"Update database\", this);\n connect(updateDb, &QAction::triggered, this, &Window::updateDatabase);\n cleanDb = new QAction(\"Clean database\", this);\n connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase);\n optionsMenu->addAction(updateDb);\n optionsMenu->addAction(cleanDb);\n menuBar()->addMenu(optionsMenu);\n\n \/\/ Set window paramters\n setWindowTitle(tr(\"Find Recipes\"));\n setMinimumSize(940, 400);\n\n \/\/ Set signals\n connect(recipeList, &QListWidget::itemClicked, this, &Window::openFile);\n connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString)));\n connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus()));\n connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString)));\n\n \/\/ Update on startup\n updateDatabase();\n}\n\n\/\/ Get list of files according to glob patternn\nQStringList globVector(const std::string& pattern){\n glob_t glob_result;\n glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);\n QStringList files;\n for(unsigned int i=0; i<glob_result.gl_pathc; ++i){\n files << QString(glob_result.gl_pathv[i]);\n }\n globfree(&glob_result);\n return files;\n}\n\nvoid SearchBox::recipeFiterChanged(QString newFilter){\n Q_UNUSED(newFilter);\n \/\/ When the recipe filter changes, emit this signal to call updateRecipeDisplay\n emit inputText(text());\n}\n\nvoid SearchBox::keyPressEvent(QKeyEvent *evt){\n QLineEdit::keyPressEvent(evt);\n setPlaceholderText(\"Search for recipes\");\n \/\/ When the search changes, emit this signal to call updateRecipeDisplay\n emit inputText(text());\n}\n\nvoid Window::populateRecipeBox(QComboBox* box){\n \/\/ Open database\n db.open();\n \/\/ Prepare query\n QSqlQuery query = QSqlQuery();\n query.prepare(\"SELECT CATEGORY, COUNT(*) FROM RECIPES GROUP BY CATEGORY ORDER BY CATEGORY\");\n query.setForwardOnly(true);\n query.exec();\n\n box->addItem(\"All Recipes\");\n while(query.next()){\n QString entry = query.value(\"CATEGORY\").toString() + \" [\" + query.value(1).toString() + \"]\";\n box->addItem(entry);\n }\n db.close();\n}\n\nvoid Window::updateRecipesDiplay(QString searchText){\n recipeList->clear();\n QList<QListWidgetItem*> recipes;\n\n if (searchText.isEmpty()) {\n recipes = getAllRecipes();\n for (int i=0; i<recipes.size(); ++i){\n recipeList->addItem(recipes[i]);\n }\n recipeList->sortItems();\n\n }else{\n recipes = getMatchingRecipes(searchText);\n for (int i=0; i<recipes.size(); ++i){\n recipeList->addItem(recipes[i]);\n }\n }\n\n recipeList->setDragEnabled(false);\n\n QString text = QString(\"%1 recipes\").arg(recipes.size());\n if (recipes.size() == 1){\n text = \"1 recipe\";\n }\n numResults->setText(text);\n}\n\nQList<QListWidgetItem*> Window::getAllRecipes(){\n QList<QListWidgetItem*> recipes;\n\n \/\/ Open database and execute query\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText().split(\" [\")[0];\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES WHERE CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n while(query.next()){\n \/\/ Extract info from query results\n QString title = query.value(\"TITLE\").toString();\n QString img_path = query.value(\"IMG_PATH\").toString();\n QString html_path = query.value(\"HTML_PATH\").toString();\n\n \/\/ Create QListWidgetItems\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n db.close();\n return recipes;\n}\n\n\nQList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){\n QList<QListWidgetItem*> recipes;\n\n \/\/ Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order.\n std::map<double, QStringList> matchingRecipes = findMatches(searchText);\n \/\/ Build QListWidgetItems and add to QList\n \/\/ By default the map should be in ascending order, so use reverse iterator to get highest matches first\n for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){\n\n QString title = iter->second[0];\n QString img_path = iter->second[1];\n QString html_path = iter->second[2];\n\n QListWidgetItem *recipe = new QListWidgetItem;\n recipe->setText(title);\n recipe->setData(Qt::UserRole, html_path);\n\n QImage *img = new QImage();\n bool loaded = img->load(img_path);\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }else{\n \/\/ If image doesn't exist, use placeholder image\n bool loaded = img->load(\".\/images\/Placeholder.jpg\");\n if (loaded){\n recipe->setIcon(QPixmap::fromImage(*img));\n }\n }\n recipes.append(recipe);\n }\n\n return recipes;\n}\n\nstd::map<double, QStringList> Window::findMatches(QString text)\n{\n \/\/ Open database\n db.open();\n \/\/ Prepare query based on filter\n QSqlQuery query = QSqlQuery();\n if(recipeBox->currentText() != \"All Recipes\"){\n QString category = recipeBox->currentText().split(\" [\")[0];\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES WHERE CATEGORY = :category\");\n query.bindValue(\":category\", category);\n query.setForwardOnly(true);\n }else{\n query.prepare(\"SELECT TITLE, IMG_PATH, HTML_PATH FROM RECIPES\");\n query.setForwardOnly(true);\n }\n \/\/ Execute query\n query.exec();\n\n \/\/ Get matching files and their scores\n std::map<double, QStringList> matchingFiles;\n std::string txtstr = text.toStdString();\n while(query.next()){\n int score;\n QString title = query.value(\"TITLE\").toString();\n QString img_path = query.value(\"IMG_PATH\").toString().replace(\"\\'\", \"\").replace(\",\", \"\");\n QString file_path = query.value(\"HTML_PATH\").toString();\n\n std::string titlestr = title.toStdString();\n if (fts::fuzzy_match(txtstr.c_str(), titlestr.c_str(), score)){\n \/\/ If a map entry already has the current score, increase score by 0.01.\n double dbscore = (double)score;\n if (matchingFiles.count(dbscore) > 0){\n dbscore += 0.01;\n }\n matchingFiles[dbscore] = QStringList() << title << img_path << file_path;\n }\n }\n db.close();\n return matchingFiles;\n}\n\nvoid Window::createRecipeListWidget()\n{\n recipeList = new QListWidget();\n recipeList->setViewMode(QListView::IconMode);\n recipeList->setGridSize(QSize(212, int(212\/1.51)) );\n recipeList->setIconSize(QSize(199, int(199\/1.78)) );\n recipeList->setWordWrap(true);\n recipeList->setTextElideMode(Qt::ElideNone);\n recipeList->horizontalScrollBar()->setEnabled(false);\n recipeList->horizontalScrollBar()->setVisible(false);\n}\n\nvoid Window::openFile(QListWidgetItem *recipe)\n{\n \/\/ Read hidden data to find full file path\n QString path = recipe->data(Qt::UserRole).toString();\n QString url = \"file:\/\/\" + currentDir.absoluteFilePath(path);\n recipeView->load(url);\n}\n\nvoid Window::updateDatabase(){\n int num_updates = db_ops::update_database(&db);\n QString updated_text;\n if (num_updates == 0){\n updated_text = \"Search for recipes\";\n }else{\n updated_text = \"Search for recipes - Updated!\";\n }\n searchBox->setPlaceholderText(updated_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::cleanDatabase(){\n int num_removals = db_ops::clean_database(&db);\n QString cleaned_text;\n if (num_removals == 1){\n cleaned_text = QString(\"Search for recipes - Removed 1 recipe!\");\n }else{\n cleaned_text = QString(\"Search for recipes - Removed %1 recipes!\").arg(num_removals);\n }\n searchBox->setPlaceholderText(cleaned_text);\n \/\/ Repopulate list\n updateRecipesDiplay(\"\");\n}\n\nvoid Window::resizeEvent(QResizeEvent *event){\n Q_UNUSED(event);\n int iconWidth, iconHeight, gridWidth, gridHeight;\n double gridRatio = 1.51;\n double iconRatio = 1.78;\n QSize recipeListSize = recipeList->size();\n\n \/\/ Set gridwith based on recipeList size and ensure it doesn't go below minimum value\n gridWidth = qMax(int(recipeListSize.width()) - 17.0, 212.0);\n \/\/ Calculate other parameters based on ratios of default values.\n gridHeight = int(gridWidth\/gridRatio);\n iconWidth = gridWidth - 13;\n iconHeight = int(iconWidth\/iconRatio);\n\n recipeList->setIconSize(QSize(iconWidth, iconHeight));\n recipeList->setGridSize(QSize(gridWidth, gridHeight));\n recipeList->setUniformItemSizes(true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * <!--\n * Copyright 2015 Develer S.r.l. (http:\/\/www.develer.com\/)\n * -->\n *\n * \\brief main cutecom-ng window\n *\n * \\author Aurelien Rainone <aurelien@develer.org>\n *\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"connectdialog.h\"\n#include \"sessionmanager.h\"\n#include \"outputmanager.h\"\n\n#include <QTextEdit>\n#include <QScrollBar>\n\nconst QString LINE_ENDING = \"\\r\\n\";\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n connect(ui->connectButton, &QAbstractButton::clicked, this, &MainWindow::openConnectionDialog);\n\n \/\/ create session and output managers\n output_mgr = new OutputManager(this);\n session_mgr = new SessionManager(this);\n\n \/\/ handle new user input, and send it to the serial port via MainWindow::handleReturnPressed\n connect(ui->textInput, &QLineEdit::returnPressed, this, &MainWindow::handleReturnPressed);\n\n \/\/ let output manager handle new data coming from serial port\n connect(session_mgr, &SessionManager::dataReceived, output_mgr, &OutputManager::handleNewData);\n\n \/\/ get data formatted for display and show it in output view\n connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::openConnectionDialog()\n{\n ConnectDialog dialog(this);\n\n connect(&dialog, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession);\n dialog.exec();\n}\n\nvoid MainWindow::handleReturnPressed()\n{\n \/\/ if session is not open, this also keeps user input\n if (session_mgr->isSessionOpen())\n {\n QString line = ui->textInput->text() + LINE_ENDING;\n session_mgr->sendToSerial(line.toLocal8Bit());\n ui->textInput->clear();\n }\n}\n\nvoid MainWindow::addDataToView(const QString & textdata)\n{\n \/\/ save current text selection\n QTextCursor cursor = ui->textOutput->textCursor();\n\n \/\/ insert data at end of 'edit' (but this clears any selection)\n ui->textOutput->moveCursor(QTextCursor::End);\n ui->textOutput->insertPlainText (textdata);\n\n \/\/ revert text selection\n ui->textOutput->setTextCursor(cursor);\n\n \/\/ push scroll to the bottom\n QScrollBar *vbar = ui->textOutput->verticalScrollBar();\n vbar->setValue(vbar->maximum());\n}\n<commit_msg>remove unused include, fix coding style<commit_after>\/**\n * \\file\n * <!--\n * Copyright 2015 Develer S.r.l. (http:\/\/www.develer.com\/)\n * -->\n *\n * \\brief main cutecom-ng window\n *\n * \\author Aurelien Rainone <aurelien@develer.org>\n *\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"connectdialog.h\"\n#include \"sessionmanager.h\"\n#include \"outputmanager.h\"\n\n#include <QScrollBar>\n\nconst QString LINE_ENDING = \"\\r\\n\";\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n connect(ui->connectButton, &QAbstractButton::clicked, this, &MainWindow::openConnectionDialog);\n\n \/\/ create session and output managers\n output_mgr = new OutputManager(this);\n session_mgr = new SessionManager(this);\n\n \/\/ handle new user input, and send it to the serial port via MainWindow::handleReturnPressed\n connect(ui->textInput, &QLineEdit::returnPressed, this, &MainWindow::handleReturnPressed);\n\n \/\/ let output manager handle new data coming from serial port\n connect(session_mgr, &SessionManager::dataReceived, output_mgr, &OutputManager::handleNewData);\n\n \/\/ get data formatted for display and show it in output view\n connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::openConnectionDialog()\n{\n ConnectDialog dialog(this);\n\n connect(&dialog, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession);\n dialog.exec();\n}\n\nvoid MainWindow::handleReturnPressed()\n{\n \/\/ if session is not open, this also keeps user input\n if (session_mgr->isSessionOpen())\n {\n QString line = ui->textInput->text() + LINE_ENDING;\n session_mgr->sendToSerial(line.toLocal8Bit());\n ui->textInput->clear();\n }\n}\n\nvoid MainWindow::addDataToView(const QString & textdata)\n{\n \/\/ save current text selection\n QTextCursor cursor = ui->textOutput->textCursor();\n\n \/\/ insert data at end of 'edit' (but this clears any selection)\n ui->textOutput->moveCursor(QTextCursor::End);\n ui->textOutput->insertPlainText(textdata);\n\n \/\/ revert text selection\n ui->textOutput->setTextCursor(cursor);\n\n \/\/ push scroll to the bottom\n QScrollBar *vbar = ui->textOutput->verticalScrollBar();\n vbar->setValue(vbar->maximum());\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n#define STDIO_DELIM \"{}\"\n#define STDIO_MAXBUF 8096\n\n\/\/ flush(void)\n\/\/ Flushes output buffer (forcefully)\nstatic CLEVER_FUNCTION(flush) {\n\tfflush(stdout);\n}\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = CLEVER_ARG_COUNT(); i < size; ++i) {\n\t\tCLEVER_ARG_DUMP(i);\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = CLEVER_ARG_COUNT(); i < size; ++i) {\n\t\tCLEVER_ARG_DUMP(i);\n\t\t::std::cout << '\\n';\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tif (CLEVER_ARG_COUNT() > 0) {\n\t\tchar* point = strtok((char*)CLEVER_ARG_PSTR(0), STDIO_DELIM);\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\t\t\t\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\tCLEVER_ARG_DUMP(arg);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t::std::cout << point;\n\t\t\t\t}\n\t\t\t} while((point = strtok(NULL, STDIO_DELIM)));\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\taddFunction(new Function(\"print\", &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\", &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\", &CLEVER_FUNC_NAME(printf)));\n\taddFunction(new Function(\"flush\", &CLEVER_FUNC_NAME(flush)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<commit_msg>-whitespace<commit_after>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n#define STDIO_DELIM \"{}\"\n#define STDIO_MAXBUF 8096\n\n\/\/ flush(void)\n\/\/ Flushes output buffer (forcefully)\nstatic CLEVER_FUNCTION(flush) {\n\tfflush(stdout);\n}\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = CLEVER_ARG_COUNT(); i < size; ++i) {\n\t\tCLEVER_ARG_DUMP(i);\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = CLEVER_ARG_COUNT(); i < size; ++i) {\n\t\tCLEVER_ARG_DUMP(i);\n\t\t::std::cout << '\\n';\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tif (CLEVER_ARG_COUNT() > 0) {\n\t\tchar* point = strtok((char*)CLEVER_ARG_PSTR(0), STDIO_DELIM);\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\tCLEVER_ARG_DUMP(arg);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t::std::cout << point;\n\t\t\t\t}\n\t\t\t} while((point = strtok(NULL, STDIO_DELIM)));\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\taddFunction(new Function(\"print\", &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\", &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\", &CLEVER_FUNC_NAME(printf)));\n\taddFunction(new Function(\"flush\", &CLEVER_FUNC_NAME(flush)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n#define STDIO_DELIM \"{}\"\n#define STDIO_MAXBUF 8096\n\n\/\/ flush(void)\n\/\/ Flushes output buffer (forcefully)\nstatic CLEVER_FUNCTION(flush) {\n\tfflush(stdout);\n}\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = CARG_COUNT(); i < size; ++i) {\n\t\tCARG_DUMP(i);\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = CARG_COUNT(); i < size; ++i) {\n\t\tCARG_DUMP(i);\n\t\t::std::cout << ::std::endl;\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tif (CARG_COUNT() > 0) {\n\t\tchar* point = strtok(CARG_PSTR(0), STDIO_DELIM);\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\tCARG_DUMP(arg);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t::std::cout << point;\n\t\t\t\t}\n\t\t\t} while((point = strtok(NULL, STDIO_DELIM)));\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\taddFunction(new Function(\"print\", &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\", &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\", &CLEVER_FUNC_NAME(printf)));\n\taddFunction(new Function(\"flush\", &CLEVER_FUNC_NAME(flush)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<commit_msg>swapsies<commit_after>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n#define STDIO_DELIM \"{}\"\n#define STDIO_MAXBUF 8096\n\n\/\/ flush(void)\n\/\/ Flushes output buffer (forcefully)\nstatic CLEVER_FUNCTION(flush) {\n\tfflush(stdout);\n}\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = CARG_COUNT(); i < size; ++i) {\n\t\tCARG_DUMP(i);\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = CARG_COUNT(); i < size; ++i) {\n\t\tCARG_DUMP(i);\n\t\t::std::cout << '\\n';\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tif (CARG_COUNT() > 0) {\n\t\tchar* point = strtok(CARG_PSTR(0), STDIO_DELIM);\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\tCARG_DUMP(arg);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t::std::cout << point;\n\t\t\t\t}\n\t\t\t} while((point = strtok(NULL, STDIO_DELIM)));\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\taddFunction(new Function(\"print\", &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\", &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\", &CLEVER_FUNC_NAME(printf)));\n\taddFunction(new Function(\"flush\", &CLEVER_FUNC_NAME(flush)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"watchman\/fs\/Pipe.h\"\n#ifdef _WIN32\n#include <event2\/util.h> \/\/ @manual\n#endif\n#include <folly\/Exception.h>\n#include <folly\/String.h>\n#include <system_error>\n\nnamespace watchman {\n\nPipe::Pipe() {\n#ifdef _WIN32\n HANDLE readPipe;\n HANDLE writePipe;\n auto sec = SECURITY_ATTRIBUTES();\n\n sec.nLength = sizeof(sec);\n sec.bInheritHandle = FALSE; \/\/ O_CLOEXEC equivalent\n constexpr DWORD kPipeSize = 64 * 1024;\n\n if (!CreatePipe(&readPipe, &writePipe, &sec, kPipeSize)) {\n throw std::system_error(\n GetLastError(), std::system_category(), \"CreatePipe failed\");\n }\n read = FileDescriptor(intptr_t(readPipe), FileDescriptor::FDType::Pipe);\n write = FileDescriptor(intptr_t(writePipe), FileDescriptor::FDType::Pipe);\n\n#else\n int fds[2];\n int res;\n#if HAVE_PIPE2\n res = pipe2(fds, O_NONBLOCK | O_CLOEXEC);\n#else\n res = pipe(fds);\n#endif\n\n if (res) {\n throw std::system_error(\n errno,\n std::system_category(),\n std::string(\"pipe error: \") + folly::errnoStr(errno));\n }\n read = FileDescriptor(fds[0], FileDescriptor::FDType::Pipe);\n write = FileDescriptor(fds[1], FileDescriptor::FDType::Pipe);\n\n#if !HAVE_PIPE2\n read.setCloExec();\n read.setNonBlock();\n write.setCloExec();\n write.setNonBlock();\n#endif\n#endif\n}\n\nSocketPair::SocketPair() {\n FileDescriptor::system_handle_type pair[2];\n\n#ifdef _WIN32\n \/\/ The win32 libevent implementation will attempt to use unix domain sockets\n \/\/ if available, but will fall back to using loopback TCP sockets.\n auto r = evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair);\n#else\n auto r = ::socketpair(\n AF_UNIX,\n#ifdef SOCK_NONBLOCK\n SOCK_NONBLOCK |\n#endif\n#ifdef SOCK_CLOEXEC\n SOCK_CLOEXEC |\n#endif\n SOCK_STREAM,\n 0,\n pair);\n#endif\n folly::checkUnixError(r, \"socketpair failed\");\n\n read = FileDescriptor(pair[0], FileDescriptor::FDType::Socket);\n write = FileDescriptor(pair[1], FileDescriptor::FDType::Socket);\n\n read.setNonBlock();\n write.setNonBlock();\n read.setCloExec();\n write.setCloExec();\n}\n} \/\/ namespace watchman\n<commit_msg>enable more tests on @mode\/win<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"watchman\/fs\/Pipe.h\"\n#include <folly\/Exception.h>\n#include <folly\/String.h>\n#include <folly\/portability\/Event.h>\n#include <system_error>\n\nnamespace watchman {\n\nPipe::Pipe() {\n#ifdef _WIN32\n HANDLE readPipe;\n HANDLE writePipe;\n auto sec = SECURITY_ATTRIBUTES();\n\n sec.nLength = sizeof(sec);\n sec.bInheritHandle = FALSE; \/\/ O_CLOEXEC equivalent\n constexpr DWORD kPipeSize = 64 * 1024;\n\n if (!CreatePipe(&readPipe, &writePipe, &sec, kPipeSize)) {\n throw std::system_error(\n GetLastError(), std::system_category(), \"CreatePipe failed\");\n }\n read = FileDescriptor(intptr_t(readPipe), FileDescriptor::FDType::Pipe);\n write = FileDescriptor(intptr_t(writePipe), FileDescriptor::FDType::Pipe);\n\n#else\n int fds[2];\n int res;\n#if HAVE_PIPE2\n res = pipe2(fds, O_NONBLOCK | O_CLOEXEC);\n#else\n res = pipe(fds);\n#endif\n\n if (res) {\n throw std::system_error(\n errno,\n std::system_category(),\n std::string(\"pipe error: \") + folly::errnoStr(errno));\n }\n read = FileDescriptor(fds[0], FileDescriptor::FDType::Pipe);\n write = FileDescriptor(fds[1], FileDescriptor::FDType::Pipe);\n\n#if !HAVE_PIPE2\n read.setCloExec();\n read.setNonBlock();\n write.setCloExec();\n write.setNonBlock();\n#endif\n#endif\n}\n\nSocketPair::SocketPair() {\n FileDescriptor::system_handle_type pair[2];\n\n#ifdef _WIN32\n \/\/ The win32 libevent implementation will attempt to use unix domain sockets\n \/\/ if available, but will fall back to using loopback TCP sockets.\n auto r = evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair);\n#else\n auto r = ::socketpair(\n AF_UNIX,\n#ifdef SOCK_NONBLOCK\n SOCK_NONBLOCK |\n#endif\n#ifdef SOCK_CLOEXEC\n SOCK_CLOEXEC |\n#endif\n SOCK_STREAM,\n 0,\n pair);\n#endif\n folly::checkUnixError(r, \"socketpair failed\");\n\n read = FileDescriptor(pair[0], FileDescriptor::FDType::Socket);\n write = FileDescriptor(pair[1], FileDescriptor::FDType::Socket);\n\n read.setNonBlock();\n write.setNonBlock();\n read.setCloExec();\n write.setCloExec();\n}\n} \/\/ namespace watchman\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2015 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <stdio.h>\n#include <sstream>\n#include \"array.h\"\n#include \"value-macros.h\"\n\nusing namespace valueobj;\n\nnamespace valueobj {\n\ntemplate <typename T>\nconst ValueBase* Array::push(T val)\n{\n\treturn push<T>(val, \"\");\n}\n\ntemplate <typename T>\nconst ValueBase* Array::set(std::string key, T val)\n{\n\tif (!key.length()) return NULL;\n\tconst ValueBase* v = push<T>(val, key);\n\tif (v) updateIndex(key, v);\n\treturn v;\n}\n\ntemplate <typename T>\nconst ValueBase* Array::set(int key, T val)\n{\n\treturn set<T>(intToStr(key), val);\n}\n\ntemplate <typename T>\nconst ValueBase* Array::pushByRef(T& val, std::string idx)\n{\n\tValue<T> *v = new Value<T>(idx, val);\n\tvector.push_back(v);\n\t++(*v); \/\/ increment refcount\n\treturn v;\n}\n\ntemplate <typename T>\nconst ValueBase* Array::push(T val, std::string idx)\n{\n\treturn pushByRef<T>(val, idx);\n}\n\n\ntemplate <typename T>\nconst T& Array::get(unsigned int &idx, T& def) const\n{\n\tif (idx <= vector.size()) {\n\t\tValue<T> *val = (Value<T>*)vector[idx];\n\t\tif (val->checkType(typeid(T)))\n\t\t\treturn val->get();\n\t}\n\treturn def;\n}\n}\n\n#define IMPL_ARRAY_TMPL(T) \\\ntemplate const ValueBase* Array::push(T val); \\\ntemplate const ValueBase* Array::set(std::string key, T val); \\\ntemplate const ValueBase* Array::set(int key, T val); \\\ntemplate const ValueBase* Array::pushByRef(T& val, std::string idx); \\\ntemplate const ValueBase* Array::push(T val, std::string idx); \\\ntemplate const T& Array::get(unsigned int &idx, T& def) const\n\n#if 1 \/\/ we only need Array::push(unsigned int) but implementing them all for the sake of completeness\nIMPL_ARRAY_TMPL(unsigned int);\n#else\ntemplate const ValueBase* Array::push(unsigned int val);\n#endif\n\n#define DBG 0\n\nstatic ReferencedValueUndefined& valueUndefined = ReferencedValueUndefined::instance();\n\nArray::Array(std::string idx)\n : idxField(idx)\n{\n#if DBG\n\tfprintf(stderr, \"%s\\n\", __func__);\n#endif\n}\n\nArray::~Array()\n{\n#if DBG\n\tfprintf(stderr, \"%s\\n\", __func__);\n#endif\n\tclear();\n}\n\nArray::Array(const Array &obj)\n{\n\tfor (KeyValueVector::const_iterator it = obj.vector.begin(); it != obj.vector.end(); ++it) {\n\t\tValueBase *v = *it;\n\t\tpush(v);\n\t\tconst std::string& n = v->getName();\n\t\tif (n.length()) updateIndex(n, v);\n\t}\n#if DBG\n\tfprintf(stderr, \"%s(copy) %lu\\n\", __func__, vector.size());\n#endif\n}\n\nconst std::string Array::toJson() const\n{\n\tstd::stringstream s;\n\n\tif (!vector.size()) return \"[]\";\n\n\tint count = 0;\n\n\ts << \"[ \";\n\n\tfor (KeyValueVector::const_iterator it = vector.begin(); it != vector.end(); ++it) {\n\t\tif (count) s << \", \";\n\n\t\ts << (*it)->toJson();\n\n\t\tcount++;\n\t}\n\ts << \" ]\";\n\n\treturn s.str();\n\n}\n\nsize_t Array::size() const\n{\n\treturn vector.size();\n}\n\nconst std::string &Array::getIndex() const\n{\n\treturn idxField;\n}\n\nconst ValueBase* Array::get(unsigned int idx) const\n{\n\tif (idx <= vector.size())\n\t\treturn vector[idx];\n\n\treturn &valueUndefined;\n}\n\nvoid Array::updateIndex(std::string key, const ValueBase *val)\n{\n\tif (key.length()) indices[key] = val;\n}\n\nstd::string &Array::assignIndex(Object &obj, std::string &index)\n{\n\tif (idxField.length()) {\n\t\tconst ValueBase *val = obj.get(idxField);\n\t\tindex = (typeid(std::string) == val->getType()) ?\n\t\t\tobj.get<std::string>(idxField) : val->toJson();\n\t}\n\n\treturn index;\n}\n\nconst ValueBase* Array::getByName(std::string idx) const\n{\n\tstd::map<std::string, const ValueBase*>::const_iterator it = indices.find(idx);\n\tif (it == indices.end())\n\t\treturn &valueUndefined;\n\n\treturn it->second;\n}\n\nconst ValueBase* Array::getByName(unsigned int idx) const\n{\n\treturn getByName(intToStr(idx));\n}\n\nvoid Array::clear()\n{\n\tfor (KeyValueVector::iterator it = vector.begin(); it != vector.end(); ++it)\n\t{\n\t\t\/\/ decrement refcount. if refcount becomes zero, delete\n\t\tif (0 == (--(**it)).getRefCnt()) delete *it;\n\t}\n\tvector.clear();\n\tindices.clear();\n}\n\nconst std::string Array::intToStr(int i) const\n{\n\tstd::stringstream s;\n\ts << i;\n\treturn s.str();\n}\n\nconst ValueBase* Array::pushObject(Object &val, std::string idx)\n{\n\tbool extractIndex = (!idx.length());\n\n\tif (extractIndex) assignIndex(val, idx);\n\n\tconst ValueBase *v = pushByRef<Object>(val, idx);\n\n\tif (extractIndex) updateIndex(idx, v);\n\n\treturn v;\n}\n\n#ifndef USING_INLINE_PUSH\nconst ValueBase *Array::push(char *val, std::string idx)\n{\n\treturn push<std::string>(std::string(val), idx);\n}\n\nconst ValueBase *Array::push(const char *val, std::string idx)\n{\n\treturn push<std::string>(std::string(val), idx);\n}\n\nconst ValueBase *Array::push(std::string &val, std::string idx)\n{\n\treturn pushByRef<std::string>(val, idx);\n}\n\nconst ValueBase *Array::push(Array &val, std::string idx)\n{\n\treturn pushByRef<Array>(val, idx);\n}\n\nconst ValueBase *Array::push(Array *val, std::string idx)\n{\n\treturn pushByRef<Array>(*val, idx);\n}\n#endif\n\nconst ValueBase* Array::push(Object &o)\n{\n\treturn pushObject(o, \"\");\n}\n\nconst ValueBase *Array::push(Object *o)\n{\n\treturn push(*o);\n}\n\nconst ValueBase* Array::push(ValueBase *val)\n{\n\tvector.push_back(val);\n\t++(*val);\n\treturn val;\n}\n\nDEFINE_DEFAULT_GETTERS(Array, unsigned int)\nTO_JSON_TPL(Array, VALUE.toJson().c_str())\n<commit_msg>value\/array: implement array template for all types<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2015 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <stdio.h>\n#include <sstream>\n#include \"array.h\"\n#include \"value-macros.h\"\n\nusing namespace valueobj;\n\nnamespace valueobj {\n\ntemplate <typename T>\nconst ValueBase* Array::push(T val)\n{\n\treturn push<T>(val, \"\");\n}\n\ntemplate <typename T>\nconst ValueBase* Array::set(std::string key, T val)\n{\n\tif (!key.length()) return NULL;\n\tconst ValueBase* v = push<T>(val, key);\n\tif (v) updateIndex(key, v);\n\treturn v;\n}\n\ntemplate <typename T>\nconst ValueBase* Array::set(int key, T val)\n{\n\treturn set<T>(intToStr(key), val);\n}\n\ntemplate <typename T>\nconst ValueBase* Array::pushByRef(T& val, std::string idx)\n{\n\tValue<T> *v = new Value<T>(idx, val);\n\tvector.push_back(v);\n\t++(*v); \/\/ increment refcount\n\treturn v;\n}\n\ntemplate <typename T>\nconst ValueBase* Array::push(T val, std::string idx)\n{\n\treturn pushByRef<T>(val, idx);\n}\n\n\ntemplate <typename T>\nconst T& Array::get(unsigned int &idx, T& def) const\n{\n\tif (idx <= vector.size()) {\n\t\tValue<T> *val = (Value<T>*)vector[idx];\n\t\tif (val->checkType(typeid(T)))\n\t\t\treturn val->get();\n\t}\n\treturn def;\n}\n}\n\n#define IMPL_ARRAY_TMPL(T) \\\ntemplate const ValueBase* Array::push(T val); \\\ntemplate const ValueBase* Array::set(std::string key, T val); \\\ntemplate const ValueBase* Array::set(int key, T val); \\\ntemplate const ValueBase* Array::pushByRef(T& val, std::string idx); \\\ntemplate const ValueBase* Array::push(T val, std::string idx); \\\ntemplate const T& Array::get(unsigned int &idx, T& def) const\n\nIMPL_ARRAY_TMPL(int);\nIMPL_ARRAY_TMPL(long);\nIMPL_ARRAY_TMPL(short);\nIMPL_ARRAY_TMPL(char);\nIMPL_ARRAY_TMPL(unsigned int);\nIMPL_ARRAY_TMPL(unsigned long);\nIMPL_ARRAY_TMPL(unsigned long long);\nIMPL_ARRAY_TMPL(unsigned short);\nIMPL_ARRAY_TMPL(unsigned char);\nIMPL_ARRAY_TMPL(std::string);\nIMPL_ARRAY_TMPL(bool);\nIMPL_ARRAY_TMPL(double);\nIMPL_ARRAY_TMPL(Array);\nIMPL_ARRAY_TMPL(Object);\n\n#define DBG 0\n\nstatic ReferencedValueUndefined& valueUndefined = ReferencedValueUndefined::instance();\n\nArray::Array(std::string idx)\n : idxField(idx)\n{\n#if DBG\n\tfprintf(stderr, \"%s\\n\", __func__);\n#endif\n}\n\nArray::~Array()\n{\n#if DBG\n\tfprintf(stderr, \"%s\\n\", __func__);\n#endif\n\tclear();\n}\n\nArray::Array(const Array &obj)\n{\n\tfor (KeyValueVector::const_iterator it = obj.vector.begin(); it != obj.vector.end(); ++it) {\n\t\tValueBase *v = *it;\n\t\tpush(v);\n\t\tconst std::string& n = v->getName();\n\t\tif (n.length()) updateIndex(n, v);\n\t}\n#if DBG\n\tfprintf(stderr, \"%s(copy) %lu\\n\", __func__, vector.size());\n#endif\n}\n\nconst std::string Array::toJson() const\n{\n\tstd::stringstream s;\n\n\tif (!vector.size()) return \"[]\";\n\n\tint count = 0;\n\n\ts << \"[ \";\n\n\tfor (KeyValueVector::const_iterator it = vector.begin(); it != vector.end(); ++it) {\n\t\tif (count) s << \", \";\n\n\t\ts << (*it)->toJson();\n\n\t\tcount++;\n\t}\n\ts << \" ]\";\n\n\treturn s.str();\n\n}\n\nsize_t Array::size() const\n{\n\treturn vector.size();\n}\n\nconst std::string &Array::getIndex() const\n{\n\treturn idxField;\n}\n\nconst ValueBase* Array::get(unsigned int idx) const\n{\n\tif (idx <= vector.size())\n\t\treturn vector[idx];\n\n\treturn &valueUndefined;\n}\n\nvoid Array::updateIndex(std::string key, const ValueBase *val)\n{\n\tif (key.length()) indices[key] = val;\n}\n\nstd::string &Array::assignIndex(Object &obj, std::string &index)\n{\n\tif (idxField.length()) {\n\t\tconst ValueBase *val = obj.get(idxField);\n\t\tindex = (typeid(std::string) == val->getType()) ?\n\t\t\tobj.get<std::string>(idxField) : val->toJson();\n\t}\n\n\treturn index;\n}\n\nconst ValueBase* Array::getByName(std::string idx) const\n{\n\tstd::map<std::string, const ValueBase*>::const_iterator it = indices.find(idx);\n\tif (it == indices.end())\n\t\treturn &valueUndefined;\n\n\treturn it->second;\n}\n\nconst ValueBase* Array::getByName(unsigned int idx) const\n{\n\treturn getByName(intToStr(idx));\n}\n\nvoid Array::clear()\n{\n\tfor (KeyValueVector::iterator it = vector.begin(); it != vector.end(); ++it)\n\t{\n\t\t\/\/ decrement refcount. if refcount becomes zero, delete\n\t\tif (0 == (--(**it)).getRefCnt()) delete *it;\n\t}\n\tvector.clear();\n\tindices.clear();\n}\n\nconst std::string Array::intToStr(int i) const\n{\n\tstd::stringstream s;\n\ts << i;\n\treturn s.str();\n}\n\nconst ValueBase* Array::pushObject(Object &val, std::string idx)\n{\n\tbool extractIndex = (!idx.length());\n\n\tif (extractIndex) assignIndex(val, idx);\n\n\tconst ValueBase *v = pushByRef<Object>(val, idx);\n\n\tif (extractIndex) updateIndex(idx, v);\n\n\treturn v;\n}\n\n#ifndef USING_INLINE_PUSH\nconst ValueBase *Array::push(char *val, std::string idx)\n{\n\treturn push<std::string>(std::string(val), idx);\n}\n\nconst ValueBase *Array::push(const char *val, std::string idx)\n{\n\treturn push<std::string>(std::string(val), idx);\n}\n\nconst ValueBase *Array::push(std::string &val, std::string idx)\n{\n\treturn pushByRef<std::string>(val, idx);\n}\n\nconst ValueBase *Array::push(Array &val, std::string idx)\n{\n\treturn pushByRef<Array>(val, idx);\n}\n\nconst ValueBase *Array::push(Array *val, std::string idx)\n{\n\treturn pushByRef<Array>(*val, idx);\n}\n#endif\n\nconst ValueBase* Array::push(Object &o)\n{\n\treturn pushObject(o, \"\");\n}\n\nconst ValueBase *Array::push(Object *o)\n{\n\treturn push(*o);\n}\n\nconst ValueBase* Array::push(ValueBase *val)\n{\n\tvector.push_back(val);\n\t++(*val);\n\treturn val;\n}\n\nDEFINE_DEFAULT_GETTERS(Array, unsigned int)\nTO_JSON_TPL(Array, VALUE.toJson().c_str())\n<|endoftext|>"} {"text":"<commit_before>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * Libmemcached library\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * Copyright (C) 2006-2009 Brian Aker All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <libmemcached\/common.h>\n\n#include <libmemcached\/options.hpp>\n#include <libmemcached\/virtual_bucket.h>\n\n#if 0\nstatic const memcached_st global_copy= {\n .state= {\n .is_purging= false, \/\/ .is_purging\n .is_processing_input= false, \/\/ is_processing_input\n .is_time_for_rebuild= false,\n },\n .flags= {\n .auto_eject_hosts= false,\n .binary_protocol= false,\n .buffer_requests= false,\n .hash_with_namespace= false,\n .no_block= false,\n .no_reply= false,\n .randomize_replica_read= false,\n .support_cas= false,\n .tcp_nodelay= false,\n .use_sort_hosts= false,\n .use_udp= false,\n .verify_key= false,\n .tcp_keepalive= false,\n },\n};\n#endif\n\nstatic inline bool _memcached_init(memcached_st *self)\n{\n self->state.is_purging= false;\n self->state.is_processing_input= false;\n self->state.is_time_for_rebuild= false;\n\n self->flags.auto_eject_hosts= false;\n self->flags.binary_protocol= false;\n self->flags.buffer_requests= false;\n self->flags.hash_with_namespace= false;\n self->flags.no_block= false;\n self->flags.no_reply= false;\n self->flags.randomize_replica_read= false;\n self->flags.support_cas= false;\n self->flags.tcp_nodelay= false;\n self->flags.use_sort_hosts= false;\n self->flags.use_udp= false;\n self->flags.verify_key= false;\n self->flags.tcp_keepalive= false;\n\n self->virtual_bucket= NULL;\n\n self->distribution= MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA_SPY;\n\n if (hashkit_create(&self->hashkit) == NULL)\n {\n return false;\n }\n\n self->server_info.version= 0;\n\n self->ketama.continuum= NULL;\n self->ketama.continuum_count= 0;\n self->ketama.continuum_points_counter= 0;\n self->ketama.next_distribution_rebuild= 0;\n self->ketama.weighted= false;\n\n self->number_of_hosts= 0;\n self->servers= NULL;\n self->last_disconnected_server= NULL;\n\n self->snd_timeout= 0;\n self->rcv_timeout= 0;\n self->server_failure_limit= MEMCACHED_SERVER_FAILURE_LIMIT;\n self->query_id= 1; \/\/ 0 is considered invalid\n\n \/* TODO, Document why we picked these defaults *\/\n self->io_msg_watermark= 500;\n self->io_bytes_watermark= 65 * 1024;\n\n self->tcp_keepidle= 0;\n\n self->io_key_prefetch= 0;\n self->poll_timeout= MEMCACHED_DEFAULT_TIMEOUT;\n self->connect_timeout= MEMCACHED_DEFAULT_CONNECT_TIMEOUT;\n self->retry_timeout= MEMCACHED_SERVER_FAILURE_RETRY_TIMEOUT;\n\n self->send_size= -1;\n self->recv_size= -1;\n\n self->user_data= NULL;\n self->number_of_replicas= 0;\n\n self->allocators= memcached_allocators_return_default();\n\n self->on_clone= NULL;\n self->on_cleanup= NULL;\n self->get_key_failure= NULL;\n self->delete_trigger= NULL;\n self->callbacks= NULL;\n self->sasl.callbacks= NULL;\n self->sasl.is_allocated= false;\n\n self->error_messages= NULL;\n self->_namespace= NULL;\n self->configure.initial_pool_size= 1;\n self->configure.max_pool_size= 1;\n self->configure.version= -1;\n self->configure.filename= NULL;\n\n return true;\n}\n\nstatic void _free(memcached_st *ptr, bool release_st)\n{\n \/* If we have anything open, lets close it now *\/\n send_quit(ptr);\n memcached_server_list_free(memcached_server_list(ptr));\n memcached_result_free(&ptr->result);\n\n memcached_virtual_bucket_free(ptr);\n\n memcached_server_free(ptr->last_disconnected_server);\n\n if (ptr->on_cleanup)\n {\n ptr->on_cleanup(ptr);\n }\n\n libmemcached_free(ptr, ptr->ketama.continuum);\n\n memcached_array_free(ptr->_namespace);\n ptr->_namespace= NULL;\n\n memcached_error_free(*ptr);\n\n if (LIBMEMCACHED_WITH_SASL_SUPPORT and ptr->sasl.callbacks)\n {\n memcached_destroy_sasl_auth_data(ptr);\n }\n\n if (release_st)\n {\n memcached_array_free(ptr->configure.filename);\n ptr->configure.filename= NULL;\n }\n\n if (memcached_is_allocated(ptr) && release_st)\n {\n libmemcached_free(ptr, ptr);\n }\n}\n\nmemcached_st *memcached_create(memcached_st *ptr)\n{\n if (ptr)\n {\n ptr->options.is_allocated= false;\n }\n else\n {\n ptr= (memcached_st *)malloc(sizeof(memcached_st));\n\n if (ptr == NULL)\n {\n return NULL; \/* MEMCACHED_MEMORY_ALLOCATION_FAILURE *\/\n }\n\n ptr->options.is_allocated= true;\n }\n\n#if 0\n memcached_set_purging(ptr, false);\n memcached_set_processing_input(ptr, false);\n#endif\n\n if (_memcached_init(ptr) == false)\n {\n memcached_free(ptr);\n return NULL;\n }\n\n if (memcached_result_create(ptr, &ptr->result) == NULL)\n {\n memcached_free(ptr);\n return NULL;\n }\n\n WATCHPOINT_ASSERT_INITIALIZED(&ptr->result);\n\n return ptr;\n}\n\nmemcached_st *memcached(const char *string, size_t length)\n{\n memcached_st *self= memcached_create(NULL);\n if (self == NULL)\n {\n return NULL;\n }\n\n if (length == 0)\n {\n return self;\n }\n\n memcached_return_t rc= memcached_parse_configuration(self, string, length);\n if (memcached_success(rc) and memcached_parse_filename(self))\n {\n rc= memcached_parse_configure_file(*self, memcached_parse_filename(self), memcached_parse_filename_length(self));\n }\n \n if (memcached_failed(rc))\n {\n memcached_free(self);\n return NULL;\n }\n\n return self;\n}\n\nmemcached_return_t memcached_reset(memcached_st *ptr)\n{\n WATCHPOINT_ASSERT(ptr);\n if (not ptr)\n {\n return MEMCACHED_INVALID_ARGUMENTS;\n }\n\n bool stored_is_allocated= memcached_is_allocated(ptr);\n uint64_t query_id= ptr->query_id;\n _free(ptr, false);\n memcached_create(ptr);\n memcached_set_allocated(ptr, stored_is_allocated);\n ptr->query_id= query_id;\n\n if (ptr->configure.filename)\n {\n return memcached_parse_configure_file(*ptr, memcached_param_array(ptr->configure.filename));\n }\n\n return MEMCACHED_SUCCESS;\n}\n\nvoid memcached_servers_reset(memcached_st *self)\n{\n if (self)\n {\n memcached_server_list_free(memcached_server_list(self));\n\n memcached_server_list_set(self, NULL);\n self->number_of_hosts= 0;\n memcached_server_free(self->last_disconnected_server);\n self->last_disconnected_server= NULL;\n }\n}\n\nvoid memcached_reset_last_disconnected_server(memcached_st *self)\n{\n if (self)\n {\n memcached_server_free(self->last_disconnected_server);\n self->last_disconnected_server= NULL;\n }\n}\n\nvoid memcached_free(memcached_st *ptr)\n{\n if (ptr)\n {\n _free(ptr, true);\n }\n}\n\n\/*\n clone is the destination, while source is the structure to clone.\n If source is NULL the call is the same as if a memcached_create() was\n called.\n*\/\nmemcached_st *memcached_clone(memcached_st *clone, const memcached_st *source)\n{\n if (source == NULL)\n {\n return memcached_create(clone);\n }\n\n if (clone and memcached_is_allocated(clone))\n {\n return NULL;\n }\n\n memcached_st *new_clone= memcached_create(clone);\n\n if (new_clone == NULL)\n {\n return NULL;\n }\n\n new_clone->flags= source->flags;\n new_clone->send_size= source->send_size;\n new_clone->recv_size= source->recv_size;\n new_clone->poll_timeout= source->poll_timeout;\n new_clone->connect_timeout= source->connect_timeout;\n new_clone->retry_timeout= source->retry_timeout;\n new_clone->distribution= source->distribution;\n\n if (hashkit_clone(&new_clone->hashkit, &source->hashkit) == NULL)\n {\n memcached_free(new_clone);\n return NULL;\n }\n\n new_clone->user_data= source->user_data;\n\n new_clone->snd_timeout= source->snd_timeout;\n new_clone->rcv_timeout= source->rcv_timeout;\n\n new_clone->on_clone= source->on_clone;\n new_clone->on_cleanup= source->on_cleanup;\n\n new_clone->allocators= source->allocators;\n\n new_clone->get_key_failure= source->get_key_failure;\n new_clone->delete_trigger= source->delete_trigger;\n new_clone->server_failure_limit= source->server_failure_limit;\n new_clone->io_msg_watermark= source->io_msg_watermark;\n new_clone->io_bytes_watermark= source->io_bytes_watermark;\n new_clone->io_key_prefetch= source->io_key_prefetch;\n new_clone->number_of_replicas= source->number_of_replicas;\n new_clone->tcp_keepidle= source->tcp_keepidle;\n\n if (memcached_server_count(source))\n {\n if (memcached_failed(memcached_push(new_clone, source)))\n {\n return NULL;\n }\n }\n\n\n new_clone->_namespace= memcached_array_clone(new_clone, source->_namespace);\n new_clone->configure.filename= memcached_array_clone(new_clone, source->_namespace);\n\n if (LIBMEMCACHED_WITH_SASL_SUPPORT and source->sasl.callbacks)\n {\n if (memcached_failed(memcached_clone_sasl(new_clone, source)))\n {\n memcached_free(new_clone);\n return NULL;\n }\n }\n\n if (memcached_failed(run_distribution(new_clone)))\n {\n memcached_free(new_clone);\n\n return NULL;\n }\n\n if (source->on_clone)\n {\n source->on_clone(new_clone, source);\n }\n\n return new_clone;\n}\n\nvoid *memcached_get_user_data(const memcached_st *ptr)\n{\n return ptr->user_data;\n}\n\nvoid *memcached_set_user_data(memcached_st *ptr, void *data)\n{\n void *ret= ptr->user_data;\n ptr->user_data= data;\n\n return ret;\n}\n\nmemcached_return_t memcached_push(memcached_st *destination, const memcached_st *source)\n{\n return memcached_server_push(destination, source->servers);\n}\n\nmemcached_server_write_instance_st memcached_server_instance_fetch(memcached_st *ptr, uint32_t server_key)\n{\n return &ptr->servers[server_key];\n}\n\nmemcached_server_instance_st memcached_server_instance_by_position(const memcached_st *ptr, uint32_t server_key)\n{\n return &ptr->servers[server_key];\n}\n\nuint64_t memcached_query_id(const memcached_st *self)\n{\n if (not self)\n return 0;\n\n return self->query_id;\n}\n<commit_msg>Reverse patch<commit_after>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * Libmemcached library\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * Copyright (C) 2006-2009 Brian Aker All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <libmemcached\/common.h>\n\n#include <libmemcached\/options.hpp>\n#include <libmemcached\/virtual_bucket.h>\n\n#if 0\nstatic const memcached_st global_copy= {\n .state= {\n .is_purging= false, \/\/ .is_purging\n .is_processing_input= false, \/\/ is_processing_input\n .is_time_for_rebuild= false,\n },\n .flags= {\n .auto_eject_hosts= false,\n .binary_protocol= false,\n .buffer_requests= false,\n .hash_with_namespace= false,\n .no_block= false,\n .no_reply= false,\n .randomize_replica_read= false,\n .support_cas= false,\n .tcp_nodelay= false,\n .use_sort_hosts= false,\n .use_udp= false,\n .verify_key= false,\n .tcp_keepalive= false,\n },\n};\n#endif\n\nstatic inline bool _memcached_init(memcached_st *self)\n{\n self->state.is_purging= false;\n self->state.is_processing_input= false;\n self->state.is_time_for_rebuild= false;\n\n self->flags.auto_eject_hosts= false;\n self->flags.binary_protocol= false;\n self->flags.buffer_requests= false;\n self->flags.hash_with_namespace= false;\n self->flags.no_block= false;\n self->flags.no_reply= false;\n self->flags.randomize_replica_read= false;\n self->flags.support_cas= false;\n self->flags.tcp_nodelay= false;\n self->flags.use_sort_hosts= false;\n self->flags.use_udp= false;\n self->flags.verify_key= false;\n self->flags.tcp_keepalive= false;\n\n self->virtual_bucket= NULL;\n\n self->distribution= MEMCACHED_DISTRIBUTION_MODULA;\n\n if (hashkit_create(&self->hashkit) == NULL)\n {\n return false;\n }\n\n self->server_info.version= 0;\n\n self->ketama.continuum= NULL;\n self->ketama.continuum_count= 0;\n self->ketama.continuum_points_counter= 0;\n self->ketama.next_distribution_rebuild= 0;\n self->ketama.weighted= false;\n\n self->number_of_hosts= 0;\n self->servers= NULL;\n self->last_disconnected_server= NULL;\n\n self->snd_timeout= 0;\n self->rcv_timeout= 0;\n self->server_failure_limit= MEMCACHED_SERVER_FAILURE_LIMIT;\n self->query_id= 1; \/\/ 0 is considered invalid\n\n \/* TODO, Document why we picked these defaults *\/\n self->io_msg_watermark= 500;\n self->io_bytes_watermark= 65 * 1024;\n\n self->tcp_keepidle= 0;\n\n self->io_key_prefetch= 0;\n self->poll_timeout= MEMCACHED_DEFAULT_TIMEOUT;\n self->connect_timeout= MEMCACHED_DEFAULT_CONNECT_TIMEOUT;\n self->retry_timeout= MEMCACHED_SERVER_FAILURE_RETRY_TIMEOUT;\n\n self->send_size= -1;\n self->recv_size= -1;\n\n self->user_data= NULL;\n self->number_of_replicas= 0;\n\n self->allocators= memcached_allocators_return_default();\n\n self->on_clone= NULL;\n self->on_cleanup= NULL;\n self->get_key_failure= NULL;\n self->delete_trigger= NULL;\n self->callbacks= NULL;\n self->sasl.callbacks= NULL;\n self->sasl.is_allocated= false;\n\n self->error_messages= NULL;\n self->_namespace= NULL;\n self->configure.initial_pool_size= 1;\n self->configure.max_pool_size= 1;\n self->configure.version= -1;\n self->configure.filename= NULL;\n\n return true;\n}\n\nstatic void _free(memcached_st *ptr, bool release_st)\n{\n \/* If we have anything open, lets close it now *\/\n send_quit(ptr);\n memcached_server_list_free(memcached_server_list(ptr));\n memcached_result_free(&ptr->result);\n\n memcached_virtual_bucket_free(ptr);\n\n memcached_server_free(ptr->last_disconnected_server);\n\n if (ptr->on_cleanup)\n {\n ptr->on_cleanup(ptr);\n }\n\n libmemcached_free(ptr, ptr->ketama.continuum);\n\n memcached_array_free(ptr->_namespace);\n ptr->_namespace= NULL;\n\n memcached_error_free(*ptr);\n\n if (LIBMEMCACHED_WITH_SASL_SUPPORT and ptr->sasl.callbacks)\n {\n memcached_destroy_sasl_auth_data(ptr);\n }\n\n if (release_st)\n {\n memcached_array_free(ptr->configure.filename);\n ptr->configure.filename= NULL;\n }\n\n if (memcached_is_allocated(ptr) && release_st)\n {\n libmemcached_free(ptr, ptr);\n }\n}\n\nmemcached_st *memcached_create(memcached_st *ptr)\n{\n if (ptr)\n {\n ptr->options.is_allocated= false;\n }\n else\n {\n ptr= (memcached_st *)malloc(sizeof(memcached_st));\n\n if (ptr == NULL)\n {\n return NULL; \/* MEMCACHED_MEMORY_ALLOCATION_FAILURE *\/\n }\n\n ptr->options.is_allocated= true;\n }\n\n#if 0\n memcached_set_purging(ptr, false);\n memcached_set_processing_input(ptr, false);\n#endif\n\n if (_memcached_init(ptr) == false)\n {\n memcached_free(ptr);\n return NULL;\n }\n\n if (memcached_result_create(ptr, &ptr->result) == NULL)\n {\n memcached_free(ptr);\n return NULL;\n }\n\n WATCHPOINT_ASSERT_INITIALIZED(&ptr->result);\n\n return ptr;\n}\n\nmemcached_st *memcached(const char *string, size_t length)\n{\n memcached_st *self= memcached_create(NULL);\n if (self == NULL)\n {\n return NULL;\n }\n\n if (length == 0)\n {\n return self;\n }\n\n memcached_return_t rc= memcached_parse_configuration(self, string, length);\n if (memcached_success(rc) and memcached_parse_filename(self))\n {\n rc= memcached_parse_configure_file(*self, memcached_parse_filename(self), memcached_parse_filename_length(self));\n }\n \n if (memcached_failed(rc))\n {\n memcached_free(self);\n return NULL;\n }\n\n return self;\n}\n\nmemcached_return_t memcached_reset(memcached_st *ptr)\n{\n WATCHPOINT_ASSERT(ptr);\n if (not ptr)\n {\n return MEMCACHED_INVALID_ARGUMENTS;\n }\n\n bool stored_is_allocated= memcached_is_allocated(ptr);\n uint64_t query_id= ptr->query_id;\n _free(ptr, false);\n memcached_create(ptr);\n memcached_set_allocated(ptr, stored_is_allocated);\n ptr->query_id= query_id;\n\n if (ptr->configure.filename)\n {\n return memcached_parse_configure_file(*ptr, memcached_param_array(ptr->configure.filename));\n }\n\n return MEMCACHED_SUCCESS;\n}\n\nvoid memcached_servers_reset(memcached_st *self)\n{\n if (self)\n {\n memcached_server_list_free(memcached_server_list(self));\n\n memcached_server_list_set(self, NULL);\n self->number_of_hosts= 0;\n memcached_server_free(self->last_disconnected_server);\n self->last_disconnected_server= NULL;\n }\n}\n\nvoid memcached_reset_last_disconnected_server(memcached_st *self)\n{\n if (self)\n {\n memcached_server_free(self->last_disconnected_server);\n self->last_disconnected_server= NULL;\n }\n}\n\nvoid memcached_free(memcached_st *ptr)\n{\n if (ptr)\n {\n _free(ptr, true);\n }\n}\n\n\/*\n clone is the destination, while source is the structure to clone.\n If source is NULL the call is the same as if a memcached_create() was\n called.\n*\/\nmemcached_st *memcached_clone(memcached_st *clone, const memcached_st *source)\n{\n if (source == NULL)\n {\n return memcached_create(clone);\n }\n\n if (clone and memcached_is_allocated(clone))\n {\n return NULL;\n }\n\n memcached_st *new_clone= memcached_create(clone);\n\n if (new_clone == NULL)\n {\n return NULL;\n }\n\n new_clone->flags= source->flags;\n new_clone->send_size= source->send_size;\n new_clone->recv_size= source->recv_size;\n new_clone->poll_timeout= source->poll_timeout;\n new_clone->connect_timeout= source->connect_timeout;\n new_clone->retry_timeout= source->retry_timeout;\n new_clone->distribution= source->distribution;\n\n if (hashkit_clone(&new_clone->hashkit, &source->hashkit) == NULL)\n {\n memcached_free(new_clone);\n return NULL;\n }\n\n new_clone->user_data= source->user_data;\n\n new_clone->snd_timeout= source->snd_timeout;\n new_clone->rcv_timeout= source->rcv_timeout;\n\n new_clone->on_clone= source->on_clone;\n new_clone->on_cleanup= source->on_cleanup;\n\n new_clone->allocators= source->allocators;\n\n new_clone->get_key_failure= source->get_key_failure;\n new_clone->delete_trigger= source->delete_trigger;\n new_clone->server_failure_limit= source->server_failure_limit;\n new_clone->io_msg_watermark= source->io_msg_watermark;\n new_clone->io_bytes_watermark= source->io_bytes_watermark;\n new_clone->io_key_prefetch= source->io_key_prefetch;\n new_clone->number_of_replicas= source->number_of_replicas;\n new_clone->tcp_keepidle= source->tcp_keepidle;\n\n if (memcached_server_count(source))\n {\n if (memcached_failed(memcached_push(new_clone, source)))\n {\n return NULL;\n }\n }\n\n\n new_clone->_namespace= memcached_array_clone(new_clone, source->_namespace);\n new_clone->configure.filename= memcached_array_clone(new_clone, source->_namespace);\n\n if (LIBMEMCACHED_WITH_SASL_SUPPORT and source->sasl.callbacks)\n {\n if (memcached_failed(memcached_clone_sasl(new_clone, source)))\n {\n memcached_free(new_clone);\n return NULL;\n }\n }\n\n if (memcached_failed(run_distribution(new_clone)))\n {\n memcached_free(new_clone);\n\n return NULL;\n }\n\n if (source->on_clone)\n {\n source->on_clone(new_clone, source);\n }\n\n return new_clone;\n}\n\nvoid *memcached_get_user_data(const memcached_st *ptr)\n{\n return ptr->user_data;\n}\n\nvoid *memcached_set_user_data(memcached_st *ptr, void *data)\n{\n void *ret= ptr->user_data;\n ptr->user_data= data;\n\n return ret;\n}\n\nmemcached_return_t memcached_push(memcached_st *destination, const memcached_st *source)\n{\n return memcached_server_push(destination, source->servers);\n}\n\nmemcached_server_write_instance_st memcached_server_instance_fetch(memcached_st *ptr, uint32_t server_key)\n{\n return &ptr->servers[server_key];\n}\n\nmemcached_server_instance_st memcached_server_instance_by_position(const memcached_st *ptr, uint32_t server_key)\n{\n return &ptr->servers[server_key];\n}\n\nuint64_t memcached_query_id(const memcached_st *self)\n{\n if (not self)\n return 0;\n\n return self->query_id;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"libpldm\/base.h\"\n\n#include \"base.hpp\"\n\n#include <array>\n#include <cstring>\n#include <map>\n#include <stdexcept>\n#include <vector>\n\n#include \"libpldm\/bios.h\"\n#include \"libpldm\/platform.h\"\n\nnamespace pldm\n{\n\nusing Type = uint8_t;\n\nnamespace responder\n{\n\nusing Cmd = std::vector<uint8_t>;\n\nstatic const std::map<Type, Cmd> capabilities{\n {PLDM_BASE,\n {PLDM_GET_TID, PLDM_GET_PLDM_VERSION, PLDM_GET_PLDM_TYPES,\n PLDM_GET_PLDM_COMMANDS}},\n {PLDM_PLATFORM, {PLDM_SET_STATE_EFFECTER_STATES}},\n {PLDM_BIOS,\n {PLDM_GET_DATE_TIME, PLDM_GET_BIOS_TABLE,\n PLDM_GET_BIOS_ATTRIBUTE_CURRENT_VALUE_BY_HANDLE}},\n};\n\nstatic const std::map<Type, ver32_t> versions{\n {PLDM_BASE, {0xF1, 0xF0, 0xF0, 0x00}},\n {PLDM_PLATFORM, {0xF1, 0xF1, 0xF1, 0x00}},\n {PLDM_BIOS, {0xF1, 0xF0, 0xF0, 0x00}},\n {PLDM_FRU, {0xF1, 0xF0, 0xF0, 0x00}},\n};\n\nnamespace base\n{\n\nResponse Handler::getPLDMTypes(const pldm_msg* request,\n size_t \/*payloadLength*\/)\n{\n \/\/ DSP0240 has this as a bitfield8[N], where N = 0 to 7\n std::array<bitfield8_t, 8> types{};\n for (const auto& type : capabilities)\n {\n auto index = type.first \/ 8;\n \/\/ <Type Number> = <Array Index> * 8 + <bit position>\n auto bit = type.first - (index * 8);\n types[index].byte |= 1 << bit;\n }\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_TYPES_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n auto rc = encode_get_types_resp(request->hdr.instance_id, PLDM_SUCCESS,\n types.data(), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getPLDMCommands(const pldm_msg* request, size_t payloadLength)\n{\n ver32_t version{};\n Type type;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_COMMANDS_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n\n auto rc = decode_get_commands_req(request, payloadLength, &type, &version);\n\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n \/\/ DSP0240 has this as a bitfield8[N], where N = 0 to 31\n std::array<bitfield8_t, 32> cmds{};\n if (capabilities.find(type) == capabilities.end())\n {\n return CmdHandler::ccOnlyResponse(request,\n PLDM_ERROR_INVALID_PLDM_TYPE);\n }\n\n for (const auto& cmd : capabilities.at(type))\n {\n auto index = cmd \/ 8;\n \/\/ <Type Number> = <Array Index> * 8 + <bit position>\n auto bit = cmd - (index * 8);\n cmds[index].byte |= 1 << bit;\n }\n\n rc = encode_get_commands_resp(request->hdr.instance_id, PLDM_SUCCESS,\n cmds.data(), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getPLDMVersion(const pldm_msg* request, size_t payloadLength)\n{\n uint32_t transferHandle;\n Type type;\n uint8_t transferFlag;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_VERSION_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n\n uint8_t rc = decode_get_version_req(request, payloadLength, &transferHandle,\n &transferFlag, &type);\n\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n ver32_t version{};\n auto search = versions.find(type);\n\n if (search == versions.end())\n {\n return CmdHandler::ccOnlyResponse(request,\n PLDM_ERROR_INVALID_PLDM_TYPE);\n }\n\n memcpy(&version, &(search->second), sizeof(version));\n rc = encode_get_version_resp(request->hdr.instance_id, PLDM_SUCCESS, 0,\n PLDM_START_AND_END, &version,\n sizeof(pldm_version), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getTID(const pldm_msg* request, size_t \/*payloadLength*\/)\n{\n \/\/ assigned 1 to the bmc as the PLDM terminus\n uint8_t tid = 1;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_TID_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n auto rc = encode_get_tid_resp(request->hdr.instance_id, PLDM_SUCCESS, tid,\n responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\n} \/\/ namespace base\n} \/\/ namespace responder\n} \/\/ namespace pldm\n<commit_msg>Update the PLDM version for Platform Spec<commit_after>#include \"libpldm\/base.h\"\n\n#include \"base.hpp\"\n\n#include <array>\n#include <cstring>\n#include <map>\n#include <stdexcept>\n#include <vector>\n\n#include \"libpldm\/bios.h\"\n#include \"libpldm\/platform.h\"\n\nnamespace pldm\n{\n\nusing Type = uint8_t;\n\nnamespace responder\n{\n\nusing Cmd = std::vector<uint8_t>;\n\nstatic const std::map<Type, Cmd> capabilities{\n {PLDM_BASE,\n {PLDM_GET_TID, PLDM_GET_PLDM_VERSION, PLDM_GET_PLDM_TYPES,\n PLDM_GET_PLDM_COMMANDS}},\n {PLDM_PLATFORM, {PLDM_SET_STATE_EFFECTER_STATES}},\n {PLDM_BIOS,\n {PLDM_GET_DATE_TIME, PLDM_GET_BIOS_TABLE,\n PLDM_GET_BIOS_ATTRIBUTE_CURRENT_VALUE_BY_HANDLE}},\n};\n\nstatic const std::map<Type, ver32_t> versions{\n {PLDM_BASE, {0xF1, 0xF0, 0xF0, 0x00}},\n {PLDM_PLATFORM, {0xF1, 0xF2, 0xF0, 0x00}},\n {PLDM_BIOS, {0xF1, 0xF0, 0xF0, 0x00}},\n {PLDM_FRU, {0xF1, 0xF0, 0xF0, 0x00}},\n};\n\nnamespace base\n{\n\nResponse Handler::getPLDMTypes(const pldm_msg* request,\n size_t \/*payloadLength*\/)\n{\n \/\/ DSP0240 has this as a bitfield8[N], where N = 0 to 7\n std::array<bitfield8_t, 8> types{};\n for (const auto& type : capabilities)\n {\n auto index = type.first \/ 8;\n \/\/ <Type Number> = <Array Index> * 8 + <bit position>\n auto bit = type.first - (index * 8);\n types[index].byte |= 1 << bit;\n }\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_TYPES_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n auto rc = encode_get_types_resp(request->hdr.instance_id, PLDM_SUCCESS,\n types.data(), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getPLDMCommands(const pldm_msg* request, size_t payloadLength)\n{\n ver32_t version{};\n Type type;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_COMMANDS_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n\n auto rc = decode_get_commands_req(request, payloadLength, &type, &version);\n\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n \/\/ DSP0240 has this as a bitfield8[N], where N = 0 to 31\n std::array<bitfield8_t, 32> cmds{};\n if (capabilities.find(type) == capabilities.end())\n {\n return CmdHandler::ccOnlyResponse(request,\n PLDM_ERROR_INVALID_PLDM_TYPE);\n }\n\n for (const auto& cmd : capabilities.at(type))\n {\n auto index = cmd \/ 8;\n \/\/ <Type Number> = <Array Index> * 8 + <bit position>\n auto bit = cmd - (index * 8);\n cmds[index].byte |= 1 << bit;\n }\n\n rc = encode_get_commands_resp(request->hdr.instance_id, PLDM_SUCCESS,\n cmds.data(), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getPLDMVersion(const pldm_msg* request, size_t payloadLength)\n{\n uint32_t transferHandle;\n Type type;\n uint8_t transferFlag;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_VERSION_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n\n uint8_t rc = decode_get_version_req(request, payloadLength, &transferHandle,\n &transferFlag, &type);\n\n if (rc != PLDM_SUCCESS)\n {\n return CmdHandler::ccOnlyResponse(request, rc);\n }\n\n ver32_t version{};\n auto search = versions.find(type);\n\n if (search == versions.end())\n {\n return CmdHandler::ccOnlyResponse(request,\n PLDM_ERROR_INVALID_PLDM_TYPE);\n }\n\n memcpy(&version, &(search->second), sizeof(version));\n rc = encode_get_version_resp(request->hdr.instance_id, PLDM_SUCCESS, 0,\n PLDM_START_AND_END, &version,\n sizeof(pldm_version), responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\nResponse Handler::getTID(const pldm_msg* request, size_t \/*payloadLength*\/)\n{\n \/\/ assigned 1 to the bmc as the PLDM terminus\n uint8_t tid = 1;\n\n Response response(sizeof(pldm_msg_hdr) + PLDM_GET_TID_RESP_BYTES, 0);\n auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());\n auto rc = encode_get_tid_resp(request->hdr.instance_id, PLDM_SUCCESS, tid,\n responsePtr);\n if (rc != PLDM_SUCCESS)\n {\n return ccOnlyResponse(request, rc);\n }\n\n return response;\n}\n\n} \/\/ namespace base\n} \/\/ namespace responder\n} \/\/ namespace pldm\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#pragma once\n\n#include <chrono>\n#include <cstdint>\n#include <string_view>\n\n#include <caf\/atom.hpp>\n#include <caf\/fwd.hpp>\n\nnamespace vast::defaults {\n\nnamespace command {\n\n\/\/\/ Path to persistent state.\nconstexpr std::string_view directory = \"vast\";\n\n\/\/\/ Hostname or IP address of a remote node.\nconstexpr std::string_view endpoint_host = \"\";\n\n\/\/\/ TCP port address of a remote node.\nconstexpr uint16_t endpoint_port = 42000;\n\n\/\/\/ Server ID for the consensus module.\nconstexpr std::string_view id = \"\";\n\n\/\/\/ Path for reading input events or `-` for reading from STDIN.\nconstexpr std::string_view read_path = \"-\";\n\n\/\/\/ Path to alternate schema.\n\n\/\/\/ Path for writing query results or `-` for writing to STDOUT.\nconstexpr std::string_view write_path = \"-\";\n\n\/\/\/ Inverse factor by which to delay packets. For example, if 5, then for two\n\/\/\/ packets spaced *t* seconds apart, the source will sleep for *t\/5* seconds.\nconstexpr int64_t pseudo_realtime_factor = 0;\n\n\/\/\/ Number of bytes to keep per event.\nconstexpr size_t cutoff = std::numeric_limits<size_t>::max();\n\n\/\/\/ Flow table expiration interval.\nconstexpr size_t flow_expiry = 10;\n\n\/\/\/ Flush to disk after that many packets.\nconstexpr size_t flush_interval = 10000;\n\n\/\/\/ Maximum number of results.\nconstexpr size_t max_events = 0;\n\n\/\/\/ Maximum flow lifetime before eviction.\nconstexpr size_t max_flow_age = 60;\n\n\/\/\/ Number of concurrent flows to track.\nconstexpr size_t max_flows = 1 << 20;\n\n\/\/\/ Number of events generated by the test source.\nconstexpr size_t generated_events = 100;\n\n\/\/\/ The unique ID of this node.\nconstexpr std::string_view node_id = \"node\";\n\n\/\/\/ @returns the table slice type from `options` if available, otherwise the\n\/\/\/ type configured in the actor system, or ::system::table_slice_type\n\/\/\/ if no user-defined option is available.\ncaf::atom_value table_slice_type(caf::actor_system& sys,\n caf::settings& options);\n\n} \/\/ namespace command\n\nnamespace system {\n\n\/\/\/ The default table slice type.\nconstexpr caf::atom_value table_slice_type = caf::atom(\"default\");\n\n\/\/\/ Maximum size for sources that generate table slices.\nconstexpr size_t table_slice_size = 100;\n\n\/\/\/ Maximum number of events per INDEX partition.\nconstexpr size_t max_partition_size = 1 << 20;\n\n\/\/\/ Maximum number of in-memory INDEX partitions.\nconstexpr size_t max_in_mem_partitions = 10;\n\n\/\/\/ Number of immediately scheduled INDEX partitions.\nconstexpr size_t taste_partitions = 5;\n\n\/\/\/ Maximum number of concurrent INDEX queries.\nconstexpr size_t num_query_supervisors = 10;\n\n\/\/\/ Number of cached ARCHIVE segments.\nconstexpr size_t segments = 10;\n\n\/\/\/ Maximum size of ARCHIVE segments in MB.\nconstexpr size_t max_segment_size = 128;\n\n\/\/\/ Number of initial IDs to request in the IMPORTER.\nconstexpr size_t initially_requested_ids = 128;\n\n\/\/\/ Rate at which telemetry data is sent to the ACCOUNTANT.\nconstexpr std::chrono::milliseconds telemetry_rate = std::chrono::milliseconds{\n 1000};\n\n} \/\/ namespace system\n\n} \/\/ namespace vast::defaults\n<commit_msg>Integrate review suggestions<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#pragma once\n\n#include <chrono>\n#include <cstdint>\n#include <string_view>\n\n#include <caf\/atom.hpp>\n#include <caf\/fwd.hpp>\n\nnamespace vast::defaults {\n\nnamespace command {\n\n\/\/\/ Path to persistent state.\nconstexpr std::string_view directory = \"vast\";\n\n\/\/\/ Hostname or IP address of a remote node.\nconstexpr std::string_view endpoint_host = \"\";\n\n\/\/\/ TCP port address of a remote node.\nconstexpr uint16_t endpoint_port = 42000;\n\n\/\/\/ Server ID for the consensus module.\nconstexpr std::string_view id = \"\";\n\n\/\/\/ Path for reading input events or `-` for reading from STDIN.\nconstexpr std::string_view read_path = \"-\";\n\n\/\/\/ Path to alternate schema.\n\n\/\/\/ Path for writing query results or `-` for writing to STDOUT.\nconstexpr std::string_view write_path = \"-\";\n\n\/\/\/ Inverse factor by which to delay packets. For example, if 5, then for two\n\/\/\/ packets spaced *t* seconds apart, the source will sleep for *t\/5* seconds.\nconstexpr int64_t pseudo_realtime_factor = 0;\n\n\/\/\/ Number of bytes to keep per event.\nconstexpr size_t cutoff = std::numeric_limits<size_t>::max();\n\n\/\/\/ Flow table expiration interval.\nconstexpr size_t flow_expiry = 10;\n\n\/\/\/ Flush to disk after that many packets.\nconstexpr size_t flush_interval = 10'000;\n\n\/\/\/ Maximum number of results.\nconstexpr size_t max_events = 0;\n\n\/\/\/ Maximum flow lifetime before eviction.\nconstexpr size_t max_flow_age = 60;\n\n\/\/\/ Number of concurrent flows to track.\nconstexpr size_t max_flows = 1'048'576; \/\/ 1_Mi\n\n\/\/\/ Number of events generated by the test source.\nconstexpr size_t generated_events = 100;\n\n\/\/\/ The unique ID of this node.\nconstexpr std::string_view node_id = \"node\";\n\n\/\/\/ @returns the table slice type from `options` if available, otherwise the\n\/\/\/ type configured in the actor system, or ::system::table_slice_type\n\/\/\/ if no user-defined option is available.\ncaf::atom_value table_slice_type(caf::actor_system& sys,\n caf::settings& options);\n\n} \/\/ namespace command\n\nnamespace system {\n\n\/\/\/ The default table slice type.\nconstexpr caf::atom_value table_slice_type = caf::atom(\"default\");\n\n\/\/\/ Maximum size for sources that generate table slices.\nconstexpr size_t table_slice_size = 100;\n\n\/\/\/ Maximum number of events per INDEX partition.\nconstexpr size_t max_partition_size = 1'048'576; \/\/ 1_Mi\n\n\/\/\/ Maximum number of in-memory INDEX partitions.\nconstexpr size_t max_in_mem_partitions = 10;\n\n\/\/\/ Number of immediately scheduled INDEX partitions.\nconstexpr size_t taste_partitions = 5;\n\n\/\/\/ Maximum number of concurrent INDEX queries.\nconstexpr size_t num_query_supervisors = 10;\n\n\/\/\/ Number of cached ARCHIVE segments.\nconstexpr size_t segments = 10;\n\n\/\/\/ Maximum size of ARCHIVE segments in MB.\nconstexpr size_t max_segment_size = 128;\n\n\/\/\/ Number of initial IDs to request in the IMPORTER.\nconstexpr size_t initially_requested_ids = 128;\n\n\/\/\/ Rate at which telemetry data is sent to the ACCOUNTANT.\nconstexpr std::chrono::milliseconds telemetry_rate = std::chrono::milliseconds{\n 1000};\n\n} \/\/ namespace system\n\n} \/\/ namespace vast::defaults\n<|endoftext|>"} {"text":"<commit_before>#ifndef MATMETHODS_HPP\n#define MATMETHODS_HPP\n#include <boost\/random\/mersenne_twister.hpp>\n#include <boost\/random\/uniform_int_distribution.hpp>\n#include <boost\/timer\/timer.hpp>\n#include \"armadillo\"\n\nusing namespace arma;\nusing namespace std;\nusing boost::timer::auto_cpu_timer;\n\n\numat GenBoot (size_t colsize, size_t bootstrapnumber){\n boost::random::mt19937 rng;\n\n boost::random::uniform_int_distribution<> samples(0,colsize-1);\n\n umat samplemat(bootstrapnumber,colsize);\n \n for(umat::iterator it=samplemat.begin(); it!=samplemat.end();++it){\n (*it) = samples(rng);\n }\n return(samplemat);\n}\n\nvoid doBoot(mat &A, mat &B,cube &C,umat &BootMat, mat &Summaries){\n auto_cpu_timer timerInd;\n timerInd.stop();\n auto_cpu_timer timerCor;\n\n timerCor.stop();\n auto_cpu_timer timerMedian;\n timerMedian.stop();\n \n if(A.n_rows!=BootMat.n_cols){\n\n for(int i=1; i<C.n_slices; ++i){\n cout<<\"Boot(incorrect indices): \"<<i<<endl;\n\n C.slice(i) = cor(A.rows(BootMat(i,span(0,A.n_rows))),B.rows(BootMat(i,span(0,B.n_rows))));\n }\n }\n else{\n \n timerInd.resume();\n mat tA = A.rows(BootMat.row(0));\n mat tB = B.rows(BootMat.row(0));\n timerInd.stop();\n\n timerCor.resume();\n C.slice(0) = cor(tA,tB);\n timerCor.stop();\n for(int i=0; i<C.n_slices; ++i){\n cout<<\"Boot: \"<<i<<endl;\n timerInd.resume();\n tA = A.rows(BootMat.row(i));\n tB = B.rows(BootMat.row(i));\n timerInd.stop();\n timerCor.resume();\n C.slice(i) = cor(tA,tB);\n timerCor.stop();\n }\n }\n timerMedian.resume();\n mat S = mat(C.n_rows,C.n_slices);\n for(int i=0; i< C.n_cols; i++){\n S = C(span::all,span(i,i),span::all);\n Summaries.col(i)=median(S,1);\n }\n timerMedian.stop();\n timerInd.report();\n timerCor.report();\n timerMedian.report();\n \n}\n\nuvec trainindex(const size_t totalsize,const int ksize,const int k){\n uvec returnvec(totalsize-ksize);\n int j=0;\n for(int i=0; i<totalsize; i++){\n if(i <(k*ksize)||i>((k+1)*ksize)-1){\n returnvec(j)=i;\n j++;\n }\n }\n return(returnvec);\n}\n \n\nuvec testindex(const size_t totalsize,const int ksize,const int k){\n uvec returnvec(ksize);\n int j=0;\n for( int i=0; i<totalsize; i++){\n if(i>=(k*ksize)&&i<=((k+1)*ksize-1)){\n returnvec(j)=i;\n j++;\n }\n }\n return(returnvec);\n}\n\ndouble RMSE(mat &Est, const mat &True){\n Est = sqrt(pow((Est-True),2));\n Est.elem(find_nonfinite(Est)).zeros();\n return(mean(mean(Est)));\n}\n \n \n\n\n\nvoid KfoldCV (const mat &A,const mat &B, const int kfold, const int chunknum, const int bsi,const string file){\n\n mat testA,testB,trainA,trainB;\n int kfoldIterations = (int) ceil((double)A.n_rows\/(double)kfold);\n if(kfoldIterations<1){\n cerr<<\"Must have at least one iteration of cross-validation, not \"<<kfoldIterations<<endl;\n throw 12;\n }\n \n int iter_k = kfold;\n\n\n cout<<\"Begin \"<<iter_k<<\"-fold cross validation. There are \"<<A.n_rows<<\" samples\"<<endl;\n uvec testi = testindex(A.n_rows,iter_k,0);\n uvec traini = trainindex(A.n_rows,iter_k,0);\n\n try{\n testA = A.rows(testi);\n testB = B.rows(testi);\n\n trainA = A.rows(traini);\n trainB = B.rows(traini);\n } catch(...){\n cerr<<\"Error indexing training and testing sets:\"<<endl;\n cerr<<\"Training: \"<<traini<<endl;\n cerr<<\"Testing: \"<<testi<<endl;\n throw 4;\n }\n cout<<\"Initiating variables and starting kfold: 0\"<<endl;\n mat Point(A.n_cols,B.n_cols);\n mat Summaries(A.n_cols,B.n_cols);\n umat BootMat = GenBoot(trainA.n_rows,bsi);\n cube C(A.n_cols,B.n_cols,bsi);\n doBoot(trainA,trainB,C,BootMat,Summaries);\n Point = cor(trainA,trainB);\n mat TrueCor = cor(testA,testB);\n double pointSumRMSE = RMSE(Point,TrueCor);\n double bootSumRMSE = RMSE(Summaries,TrueCor);\n for(int i=1; i<kfoldIterations; i++){\n cout<<\"Starting kfold: \"<<i<<endl;\n testi = testindex(A.n_rows,iter_k,0);\n traini = trainindex(A.n_rows,iter_k,0);\n testA = A.rows(testi);\n testB = B.rows(testi);\n trainA = A.rows(traini);\n trainB = B.rows(traini);\n doBoot(trainA,trainB,C,BootMat,Summaries);\n Point = cor(trainA,trainB);\n TrueCor = cor(testA,testB);\n pointSumRMSE += RMSE(Point,TrueCor);\n bootSumRMSE += RMSE(Summaries,TrueCor);\n }\n pointSumRMSE = pointSumRMSE\/kfoldIterations;\n bootSumRMSE = bootSumRMSE\/kfoldIterations;\n\n ofstream outputfile;\n outputfile.open(file,std::ofstream::out|std::ofstream::app);\n \n if(chunknum==0){\n outputfile<<\"Chunk\\tSize\\tbsi\\tPointSumRMSE\\tBootSumRMSE\"<<endl;\n }\n outputfile<<chunknum<<\"\\t\"<<Point.n_elem<<\"\\t\"<<bsi<<\"\\t\"<<pointSumRMSE<<\"\\t\"<<bootSumRMSE<<endl;\n outputfile.close();\n}\n \n \n \n\n\n \n \n \n \n\n \n \n\n\n\n\n \n \n\n \n\n\n\/\/void ComputeQuantiles(const running_stat_vec<rowvec> &stats, const mat &Co, mat &Quant, const vector<double> quantiles){\n \n\n \n \n\n\n#endif\n\n\n<commit_msg>Trace RMSE with each bootstrap iteration<commit_after>#ifndef MATMETHODS_HPP\n#define MATMETHODS_HPP\n#include <boost\/random\/mersenne_twister.hpp>\n#include <boost\/random\/uniform_int_distribution.hpp>\n#include <boost\/timer\/timer.hpp>\n#include \"armadillo\"\n\nusing namespace arma;\nusing namespace std;\nusing boost::timer::auto_cpu_timer;\n\n\numat GenBoot (size_t colsize, size_t bootstrapnumber){\n boost::random::mt19937 rng;\n\n boost::random::uniform_int_distribution<> samples(0,colsize-1);\n\n umat samplemat(bootstrapnumber,colsize);\n \n for(umat::iterator it=samplemat.begin(); it!=samplemat.end();++it){\n (*it) = samples(rng);\n }\n return(samplemat);\n}\n\nvoid doBoot(mat &A, mat &B,cube &C,umat &BootMat, mat &Summaries){\n auto_cpu_timer timerInd;\n timerInd.stop();\n auto_cpu_timer timerCor;\n\n timerCor.stop();\n auto_cpu_timer timerMedian;\n timerMedian.stop();\n \n if(A.n_rows!=BootMat.n_cols){\n for(int i=1; i<C.n_slices; ++i){\n cout<<\"Boot(incorrect indices): \"<<i<<endl;\n C.slice(i) = cor(A.rows(BootMat(i,span(0,A.n_rows))),B.rows(BootMat(i,span(0,B.n_rows))));\n }\n }\n else{\n timerInd.resume();\n mat tA = A.rows(BootMat.row(0));\n mat tB = B.rows(BootMat.row(0));\n timerInd.stop();\n timerCor.resume();\n C.slice(0) = cor(tA,tB);\n timerCor.stop();\n for(int i=1; i<C.n_slices; ++i){\n cout<<\"Boot: \"<<i<<endl;\n timerInd.resume();\n tA = A.rows(BootMat.row(i));\n tB = B.rows(BootMat.row(i));\n timerInd.stop();\n timerCor.resume();\n C.slice(i) = cor(tA,tB);\n timerCor.stop();\n }\n }\n timerMedian.resume();\n for(int i=0; i<C.n_slices; i++){\n mat S = mat(C.n_rows,C.n_slices);\n for(int j=0; j< C.n_cols; j++){\n S = C(span::all,span(i,i),span(0,i));\n Summaries.slice(i).col(j)=median(S,1);\n }\n }\n timerMedian.stop();\n timerInd.report();\n timerCor.report();\n timerMedian.report();\n \n}\n\nuvec trainindex(const size_t totalsize,const int ksize,const int k){\n uvec returnvec(totalsize-ksize);\n int j=0;\n for(int i=0; i<totalsize; i++){\n if(i <(k*ksize)||i>((k+1)*ksize)-1){\n returnvec(j)=i;\n j++;\n }\n }\n return(returnvec);\n}\n \n\nuvec testindex(const size_t totalsize,const int ksize,const int k){\n uvec returnvec(ksize);\n int j=0;\n for( int i=0; i<totalsize; i++){\n if(i>=(k*ksize)&&i<=((k+1)*ksize-1)){\n returnvec(j)=i;\n j++;\n }\n }\n return(returnvec);\n}\n\ndouble RMSE(mat &Est, const mat &True){\n Est = sqrt(pow((Est-True),2));\n Est.elem(find_nonfinite(Est)).zeros();\n return(mean(mean(Est)));\n}\n \n \n\n\n\nvoid KfoldCV (const mat &A,const mat &B, const int kfold, const int chunknum, const int bsi,const string file){\n\n mat testA,testB,trainA,trainB;\n int kfoldIterations = (int) ceil((double)A.n_rows\/(double)kfold);\n if(kfoldIterations<1){\n cerr<<\"Must have at least one iteration of cross-validation, not \"<<kfoldIterations<<endl;\n throw 12;\n }\n \n int iter_k = kfold;\n\n\n cout<<\"Begin \"<<iter_k<<\"-fold cross validation. There are \"<<A.n_rows<<\" samples\"<<endl;\n uvec testi = testindex(A.n_rows,iter_k,0);\n uvec traini = trainindex(A.n_rows,iter_k,0);\n\n try{\n testA = A.rows(testi);\n testB = B.rows(testi);\n\n trainA = A.rows(traini);\n trainB = B.rows(traini);\n } catch(...){\n cerr<<\"Error indexing training and testing sets:\"<<endl;\n cerr<<\"Training: \"<<traini<<endl;\n cerr<<\"Testing: \"<<testi<<endl;\n throw 4;\n }\n cout<<\"Initiating variables and starting kfold: 0\"<<endl;\n mat Point(A.n_cols,B.n_cols);\n cube Summaries(A.n_cols,B.n_cols,bsi);\n umat BootMat = GenBoot(trainA.n_rows,bsi);\n cube C(A.n_cols,B.n_cols,bsi);\n doBoot(trainA,trainB,C,BootMat,Summaries);\n Point = cor(trainA,trainB);\n mat TrueCor = cor(testA,testB);\n double pointSumRMSE = RMSE(Point,TrueCor);\n vector<double> bootSumRMSE(bsi);\n for(int i=0; i<bootSumRMSE.size(); i++){\n bootSumRMSE[i]=RMSE(Summaries.slice(i),TrueCor);\n }\n double bootSumRMSE = RMSE(Summaries,TrueCor);\n for(int i=1; i<kfoldIterations; i++){\n cout<<\"Starting kfold: \"<<i<<endl;\n testi = testindex(A.n_rows,iter_k,0);\n traini = trainindex(A.n_rows,iter_k,0);\n testA = A.rows(testi);\n testB = B.rows(testi);\n trainA = A.rows(traini);\n trainB = B.rows(traini);\n doBoot(trainA,trainB,C,BootMat,Summaries);\n Point = cor(trainA,trainB);\n TrueCor = cor(testA,testB);\n pointSumRMSE += RMSE(Point,TrueCor);\n for(int j=0; j<bootSumRMSE.size(); j++){\n bootSumRMSE[i] += RMSE(Summaries.slice(j),TrueCor);\n }\n }\n pointSumRMSE = pointSumRMSE\/kfoldIterations;\n for(int j=0; j<bootSumRMSE.size(); j++){ \n bootSumRMSE[i] = bootSumRMSE[i]\/kfoldIterations;\n }\n \n ofstream outputfile;\n outputfile.open(file,std::ofstream::out|std::ofstream::app);\n \n if(chunknum==0){\n outputfile<<\"Chunk\\tSize\\tbsi\\tPointSumRMSE\\tBootSumRMSE\"<<endl;\n }\n for(int j=0; j<bootSumRMSE.size(); j++){\n outputfile<<chunknum<<\"\\t\"<<Point.n_elem<<\"\\t\"<<j+1<<\"\\t\"<<pointSumRMSE<<\"\\t\"<<bootSumRMSE[i]<<endl;\n }\n outputfile.close();\n}\n \n \n \n\n\n \n \n \n \n\n \n \n\n\n\n\n \n \n\n \n\n\n\/\/void ComputeQuantiles(const running_stat_vec<rowvec> &stats, const mat &Co, mat &Quant, const vector<double> quantiles){\n \n\n \n \n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/********************************************************************\n* @file : time_format.hpp\n* @author : zapline <zhuxianzhang@kingsoft.com>\n* @date : 2012\/11\/19 20:40\n* @brief : time format convert\n* \n* \n*********************************************************************\/\n\n#ifndef _TIME_FORMAT_HPP_\n#define _TIME_FORMAT_HPP_\n\n#include <time.h>\n\n#ifndef _FILETIME_\n#define _FILETIME_\ntypedef struct _FILETIME\n{\n DWORD dwLowDateTime;\n DWORD dwHighDateTime;\n} \tFILETIME;\n#endif\n\n#define TIME_STRING_MAX_LEN 28\n\nnamespace zl\n{\n\n FILETIME Time642FileTime(__time64_t tm)\n {\n FILETIME ft;\n LONGLONG ll;\n ll = tm*10000000 + 116444736000000000;\n ft.dwLowDateTime = (DWORD)ll;\n ft.dwHighDateTime = (DWORD)(ll >> 32);\n return ft;\n }\n\n __time64_t FileTime2Time64(const FILETIME* pft)\n {\n __time64_t cTime = pft->dwHighDateTime;\n cTime = (cTime<<32) + pft->dwLowDateTime; \n return ((cTime - 116444736000000000)\/10000000);\n }\n\n void Time2Str(const SYSTEMTIME& stTime, wchar_t* strTime \/* [TIME_STRING_MAX_LEN] *\/ )\n {\n ::wsprintfW(strTime, L\"%d-%d-%d %d:%d:%d:%d %d\",\n stTime.wYear, stTime.wMonth, stTime.wDay,\n stTime.wHour, stTime.wMinute, stTime.wSecond,\n stTime.wMilliseconds, stTime.wDayOfWeek);\n }\n\n BOOL Str2Time(const wchar_t* strTime, SYSTEMTIME& stTime)\n {\n int nYear = 0;\n int nMonth = 0;\n int nDay = 0;\n int nHour = 0;\n int nMinute = 0;\n int nSecond = 0;\n int nMilliseconds = 0;\n int nDayOfWeek = 0;\n if (::swscanf_s(strTime, L\"%d-%d-%d %d:%d:%d:%d %d\",\n &nYear, &nMonth, &nDay,\n &nHour, &nMinute, &nSecond,\n &nMilliseconds, &nDayOfWeek) == -1)\n {\n return FALSE;\n }\n stTime.wYear = nYear;\n stTime.wMonth = nMonth;\n stTime.wDayOfWeek = nDayOfWeek;\n stTime.wDay = nDay;\n stTime.wHour = nHour;\n stTime.wMinute = nMinute;\n stTime.wSecond = nSecond;\n stTime.wMilliseconds = nMilliseconds;\n return TRUE;\n }\n\n}\n\n#endif\n<commit_msg>add header file<commit_after>\/********************************************************************\n* @file : time_format.hpp\n* @author : zapline <zhuxianzhang@kingsoft.com>\n* @date : 2012\/11\/19 20:40\n* @brief : time format convert\n* \n* \n*********************************************************************\/\n\n#ifndef _TIME_FORMAT_HPP_\n#define _TIME_FORMAT_HPP_\n\n#include <time.h>\n#include <stdio.h>\n\n#ifndef _FILETIME_\n#define _FILETIME_\ntypedef struct _FILETIME\n{\n DWORD dwLowDateTime;\n DWORD dwHighDateTime;\n} \tFILETIME;\n#endif\n\n#define TIME_STRING_MAX_LEN 28\n\nnamespace zl\n{\n\n FILETIME Time642FileTime(__time64_t tm)\n {\n FILETIME ft;\n LONGLONG ll;\n ll = tm*10000000 + 116444736000000000;\n ft.dwLowDateTime = (DWORD)ll;\n ft.dwHighDateTime = (DWORD)(ll >> 32);\n return ft;\n }\n\n __time64_t FileTime2Time64(const FILETIME* pft)\n {\n __time64_t cTime = pft->dwHighDateTime;\n cTime = (cTime<<32) + pft->dwLowDateTime; \n return ((cTime - 116444736000000000)\/10000000);\n }\n\n void Time2Str(const SYSTEMTIME& stTime, wchar_t* strTime \/* [TIME_STRING_MAX_LEN] *\/ )\n {\n ::wsprintfW(strTime, L\"%d-%d-%d %d:%d:%d:%d %d\",\n stTime.wYear, stTime.wMonth, stTime.wDay,\n stTime.wHour, stTime.wMinute, stTime.wSecond,\n stTime.wMilliseconds, stTime.wDayOfWeek);\n }\n\n BOOL Str2Time(const wchar_t* strTime, SYSTEMTIME& stTime)\n {\n int nYear = 0;\n int nMonth = 0;\n int nDay = 0;\n int nHour = 0;\n int nMinute = 0;\n int nSecond = 0;\n int nMilliseconds = 0;\n int nDayOfWeek = 0;\n if (::swscanf_s(strTime, L\"%d-%d-%d %d:%d:%d:%d %d\",\n &nYear, &nMonth, &nDay,\n &nHour, &nMinute, &nSecond,\n &nMilliseconds, &nDayOfWeek) == -1)\n {\n return FALSE;\n }\n stTime.wYear = nYear;\n stTime.wMonth = nMonth;\n stTime.wDayOfWeek = nDayOfWeek;\n stTime.wDay = nDay;\n stTime.wHour = nHour;\n stTime.wMinute = nMinute;\n stTime.wSecond = nSecond;\n stTime.wMilliseconds = nMilliseconds;\n return TRUE;\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Processor.h\"\n#include <sim\/config.h>\n\n#include <sys\/time.h>\n#include <ctime>\n\nnamespace Simulator\n{\n\n#define NUM_COUNTERS 18\n\nsize_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer); }\n\nResult Processor::PerfCounters::Write(MemAddr \/*address*\/, const void * \/*data*\/, MemSize \/*size*\/, LFID \/*fid*\/, TID \/*tid*\/)\n{\n return FAILED;\n}\n\nResult Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& \/*writeback*\/)\n{\n if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address \/ sizeof(Integer) >= NUM_COUNTERS)\n {\n throw exceptf<InvalidArgumentException>(*this, \"Invalid read to performance counter address by F%u\/T%u: %#016llx\/%u\",\n (unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);\n }\n address \/= sizeof(Integer);\n\n Processor& cpu = *static_cast<Processor*>(GetParent());\n\n const size_t placeSize = cpu.m_familyTable[fid].placeSize;\n const size_t placeStart = (cpu.m_pid \/ placeSize) * placeSize;\n const size_t placeEnd = placeStart + placeSize;\n Integer value;\n\n switch (address)\n {\n case 0:\n {\n \/\/ Return the number of elapsed cycles\n value = (Integer)GetKernel()->GetCycleNo();\n }\n break;\n case 1:\n {\n \/\/ Return the number of executed instructions on all cores\n Integer ops = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n ops += cpu.m_grid[i]->GetPipeline().GetOp();\n }\n value = ops;\n }\n break;\n case 2:\n {\n \/\/ Return the number of issued FP instructions on all cores\n Integer flops = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n flops += cpu.m_grid[i]->GetPipeline().GetFlop();\n }\n value = flops;\n }\n break;\n case 3:\n {\n \/\/ Return the number of completed loads on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 4:\n {\n \/\/ Return the number of completed stores on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 5:\n {\n \/\/ Return the number of successfully loaded bytes on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 6:\n {\n \/\/ Return the number of successfully stored bytes on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);\n }\n value = (Integer)n;\n }\n break;\n case 7:\n {\n \/\/ Return the number of memory loads overall from L1 to L2 (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);\n value = (Integer)n;\n }\n break;\n case 8:\n {\n \/\/ Return the number of memory stores overall from L1 to L2 (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);\n value = (Integer)n;\n }\n break;\n case 9:\n {\n value = (Integer)placeSize;\n }\n break;\n case 10:\n {\n \/\/ Return the total cumulative allocated thread slots\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();\n }\n value = alloc;\n }\n break;\n case 11:\n {\n \/\/ Return the total cumulative allocated thread slots\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();\n }\n value = alloc;\n }\n break;\n case 12:\n {\n \/\/ Return the total cumulative exclusive allocate queue size\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();\n }\n value = alloc;\n }\n break;\n case 13:\n {\n \/\/ Return the Unix time\n value = (Integer)time(0);\n }\n break;\n case 14:\n {\n \/\/ Return the local date as a packed struct\n \/\/ bits 0-4: day in month\n \/\/ bits 5-8: month in year\n \/\/ bits 9-31: year from 1900\n time_t c = time(0);\n struct tm * tm = gmtime(&c);\n value = (Integer)tm->tm_mday |\n ((Integer)tm->tm_mon << 5) |\n ((Integer)tm->tm_year << 9);\n }\n break;\n case 15:\n {\n \/\/ Return the local time as a packed struct\n \/\/ bits 0-14 = microseconds \/ 2^5 (topmost 15 bits)\n \/\/ bits 15-20 = seconds\n \/\/ bits 21-26 = minutes\n \/\/ bits 27-31 = hours\n struct timeval tv;\n gettimeofday(&tv, 0);\n struct tm * tm = gmtime(&tv.tv_sec);\n\n \/\/ get topmost 15 bits of precision of the usec field\n \/\/ usec is 0-999999; so it has 20 bits of value\n Integer usec = (tv.tv_usec >> (20-15)) & 0x7fff;\n value = usec | (tm->tm_sec << 15) | (tm->tm_min << 21) | (tm->tm_hour << 27);\n }\n break;\n case 16:\n {\n \/\/ Return the number of memory loads overall from external memory (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);\n value = (Integer)n;\n }\n break;\n case 17:\n {\n \/\/ Return the number of memory stores overall to external memory (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);\n value = (Integer)n;\n }\n break;\n case 18:\n {\n \/\/ Return the number of created families\n Integer tc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n tc += cpu.m_grid[i]->GetTotalFamiliesCreated();\n }\n value = tc;\n }\n break;\n case 19:\n {\n \/\/ Return the number of created threads\n Integer fc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n fc += cpu.m_grid[i]->GetTotalFamiliesCreated();\n }\n value = fc;\n }\n break;\n default:\n value = 0;\n }\n\n DebugIOWrite(\"Read counter %u by F%u\/T%u: %#016llx (%llu)\",\n (unsigned)address, (unsigned)fid, (unsigned)tid,\n (unsigned long long)value, (unsigned long long)value);\n\n COMMIT{\n if (address == 0)\n {\n ++m_nCycleSampleOps;\n }\n else\n {\n ++m_nOtherSampleOps;\n }\n }\n\n SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));\n\n return SUCCESS;\n}\n\nProcessor::PerfCounters::PerfCounters(Processor& parent, Config& config)\n : Processor::MMIOComponent(\"perfcounters\", parent, parent.GetClock()),\n m_nCycleSampleOps(0),\n m_nOtherSampleOps(0)\n{\n parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);\n parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, \"MMIO_BaseAddr\"));\n\n RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);\n RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);\n}\n\n}\n<commit_msg>Fix the sampling of the number of threads created.<commit_after>#include \"Processor.h\"\n#include <sim\/config.h>\n\n#include <sys\/time.h>\n#include <ctime>\n\nnamespace Simulator\n{\n\n#define NUM_COUNTERS 18\n\nsize_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer); }\n\nResult Processor::PerfCounters::Write(MemAddr \/*address*\/, const void * \/*data*\/, MemSize \/*size*\/, LFID \/*fid*\/, TID \/*tid*\/)\n{\n return FAILED;\n}\n\nResult Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& \/*writeback*\/)\n{\n if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address \/ sizeof(Integer) >= NUM_COUNTERS)\n {\n throw exceptf<InvalidArgumentException>(*this, \"Invalid read to performance counter address by F%u\/T%u: %#016llx\/%u\",\n (unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);\n }\n address \/= sizeof(Integer);\n\n Processor& cpu = *static_cast<Processor*>(GetParent());\n\n const size_t placeSize = cpu.m_familyTable[fid].placeSize;\n const size_t placeStart = (cpu.m_pid \/ placeSize) * placeSize;\n const size_t placeEnd = placeStart + placeSize;\n Integer value;\n\n switch (address)\n {\n case 0:\n {\n \/\/ Return the number of elapsed cycles\n value = (Integer)GetKernel()->GetCycleNo();\n }\n break;\n case 1:\n {\n \/\/ Return the number of executed instructions on all cores\n Integer ops = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n ops += cpu.m_grid[i]->GetPipeline().GetOp();\n }\n value = ops;\n }\n break;\n case 2:\n {\n \/\/ Return the number of issued FP instructions on all cores\n Integer flops = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n flops += cpu.m_grid[i]->GetPipeline().GetFlop();\n }\n value = flops;\n }\n break;\n case 3:\n {\n \/\/ Return the number of completed loads on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 4:\n {\n \/\/ Return the number of completed stores on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 5:\n {\n \/\/ Return the number of successfully loaded bytes on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);\n }\n value = (Integer)n;\n }\n break;\n case 6:\n {\n \/\/ Return the number of successfully stored bytes on all cores\n uint64_t n = 0, dummy;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);\n }\n value = (Integer)n;\n }\n break;\n case 7:\n {\n \/\/ Return the number of memory loads overall from L1 to L2 (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);\n value = (Integer)n;\n }\n break;\n case 8:\n {\n \/\/ Return the number of memory stores overall from L1 to L2 (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);\n value = (Integer)n;\n }\n break;\n case 9:\n {\n value = (Integer)placeSize;\n }\n break;\n case 10:\n {\n \/\/ Return the total cumulative allocated thread slots\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();\n }\n value = alloc;\n }\n break;\n case 11:\n {\n \/\/ Return the total cumulative allocated thread slots\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();\n }\n value = alloc;\n }\n break;\n case 12:\n {\n \/\/ Return the total cumulative exclusive allocate queue size\n Integer alloc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();\n }\n value = alloc;\n }\n break;\n case 13:\n {\n \/\/ Return the Unix time\n value = (Integer)time(0);\n }\n break;\n case 14:\n {\n \/\/ Return the local date as a packed struct\n \/\/ bits 0-4: day in month\n \/\/ bits 5-8: month in year\n \/\/ bits 9-31: year from 1900\n time_t c = time(0);\n struct tm * tm = gmtime(&c);\n value = (Integer)tm->tm_mday |\n ((Integer)tm->tm_mon << 5) |\n ((Integer)tm->tm_year << 9);\n }\n break;\n case 15:\n {\n \/\/ Return the local time as a packed struct\n \/\/ bits 0-14 = microseconds \/ 2^5 (topmost 15 bits)\n \/\/ bits 15-20 = seconds\n \/\/ bits 21-26 = minutes\n \/\/ bits 27-31 = hours\n struct timeval tv;\n gettimeofday(&tv, 0);\n struct tm * tm = gmtime(&tv.tv_sec);\n\n \/\/ get topmost 15 bits of precision of the usec field\n \/\/ usec is 0-999999; so it has 20 bits of value\n Integer usec = (tv.tv_usec >> (20-15)) & 0x7fff;\n value = usec | (tm->tm_sec << 15) | (tm->tm_min << 21) | (tm->tm_hour << 27);\n }\n break;\n case 16:\n {\n \/\/ Return the number of memory loads overall from external memory (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);\n value = (Integer)n;\n }\n break;\n case 17:\n {\n \/\/ Return the number of memory stores overall to external memory (cache lines)\n uint64_t n = 0, dummy;\n cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);\n value = (Integer)n;\n }\n break;\n case 18:\n {\n \/\/ Return the number of created families\n Integer tc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n tc += cpu.m_grid[i]->GetTotalFamiliesCreated();\n }\n value = tc;\n }\n break;\n case 19:\n {\n \/\/ Return the number of created threads\n Integer fc = 0;\n for (size_t i = placeStart; i < placeEnd; ++i)\n {\n fc += cpu.m_grid[i]->GetTotalThreadsCreated();\n }\n value = fc;\n }\n break;\n default:\n value = 0;\n }\n\n DebugIOWrite(\"Read counter %u by F%u\/T%u: %#016llx (%llu)\",\n (unsigned)address, (unsigned)fid, (unsigned)tid,\n (unsigned long long)value, (unsigned long long)value);\n\n COMMIT{\n if (address == 0)\n {\n ++m_nCycleSampleOps;\n }\n else\n {\n ++m_nOtherSampleOps;\n }\n }\n\n SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));\n\n return SUCCESS;\n}\n\nProcessor::PerfCounters::PerfCounters(Processor& parent, Config& config)\n : Processor::MMIOComponent(\"perfcounters\", parent, parent.GetClock()),\n m_nCycleSampleOps(0),\n m_nOtherSampleOps(0)\n{\n parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);\n parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, \"MMIO_BaseAddr\"));\n\n RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);\n RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>[BackgroundSync] Use appopriate type parameters for WebCallbacks (1\/4)<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap\n *\n * Copyright (C) 2015 Hacker, J.R. <r00tkillah@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mac.h\"\n#include \"util.h\"\n#include <Arduino.h>\n\nBlinkerMac mac;\nMemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback);\n\nBlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false))\n{\n}\n\nvoid BlinkerMac::begin()\n{\n serial.begin(IR_BAUD);\n reset();\n buf = FrameFactory.alloc();\n eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent,\n &MACRelayCB);\n}\n\nvoid BlinkerMac::reset()\n{\n rx_blink = false;\n packet_in_progress = false;\n buf_pos = 0;\n prefix_state = 0;\n reset_codec_state();\n}\n\nvoid BlinkerMac::write_prefix()\n{\n for (uint8_t i = 0; i < preamble_count; i++) {\n (*this)(preamble_byte);\n }\n for (uint8_t i = 0; i < sizeof(packet_prefix); i++) {\n (*this)(packet_prefix[i]);\n }\n}\n\nbool BlinkerMac::prefix_hit(uint8_t input)\n{\n if (prefix_state == 0) {\n if (input == packet_prefix[0]) {\n prefix_state = 1;\n }\n } else if (prefix_state == 1) {\n if (input == packet_prefix[1]) {\n prefix_state = 2;\n } else {\n prefix_state = 0;\n }\n } else if (prefix_state == 2) {\n if (input == packet_prefix[2]) {\n prefix_state = 3;\n } else {\n prefix_state = 0;\n }\n } else if (prefix_state == 3) {\n prefix_state = 0;\n if (input == packet_prefix[3]) {\n return true;\n }\n }\n return false;\n}\n\nbool BlinkerMac::blink()\n{\n rx_blink = rx_blink ? false : true;\n return rx_blink;\n}\n\nbool BlinkerMac::stalled()\n{\n const unsigned long now = millis();\n\n if (now - last_rx_time > 250) {\n return true;\n }\n last_rx_time = now;\n return false;\n}\n\n\/\/expectation here is that hton is done\n\/\/and crc is calculated\nvoid BlinkerMac::send_frame(IRFrame &frame)\n{\n debug(\"Sending packet\");\n\n write_prefix();\n for (uint16_t i = 0; i < sizeof(IRFrame); i++) {\n encode_byte(frame.blob()[i], *this);\n }\n serial.flush();\n\n \/\/ while this is happening, you'll get crap that is your own packet.\n \/\/ clear out any remaining input\n while(serial.available()) {\n (void)serial.read();\n delay(1);\n }\n}\n\nvoid BlinkerMac::recv(const uint8_t c)\n{\n digitalWrite(13, blink());\n\n \/\/ if you haven't gotten a byte in a while, then what you have\n \/\/ is probably garbage.\n if (packet_in_progress && stalled()) {\n debug(\"aborting rcv\");\n IRFrame::hexdump(buf);\n reset();\n return;\n }\n if (!packet_in_progress) {\n packet_in_progress = prefix_hit(c);\n last_rx_time = millis();\n return; \/\/the next byte should be the first byte of a packet\n }\n\n debugstart(\"%d\", buf_pos);\n debugcont(\" \");\n \/\/geting a packet\n uint8_t input;\n if (decode_byte(c, input)) {\n buf->blob()[buf_pos] = input;\n buf_pos++;\n } else {\n return; \/\/ was a stuffed byte\n }\n\n if (buf_pos >= sizeof(IRFrame)) {\n \/\/whole packet recieved!\n buf_pos = 0;\n packet_in_progress = false;\n\n if (buf->valid()) {\n buf->ntoh();\n\n if (buf->destination != address) {\n if (buf->hops < MAX_HOPS) {\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf);\n debugend();\n reset();\n return;\n } else {\n debugcont(\"too many hops.. eating\");\n debugend();\n reset();\n return;\n }\n }\n\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf);\n debugend();\n reset();\n return;\n } else {\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf);\n debugend();\n reset();\n }\n }\n return;\n}\n\nvoid BlinkerMac::relayCallback(int event, int param)\n{\n \/\/niave approach.. just send it back out this is kind of wrong we\n \/\/should wait a random time before retransmit and as we get\n \/\/packets, we should cancel retransmit if we saw a neighbor do it\n \/\/first. but when we see that neighbor do it, we schedule a new\n \/\/one to retransmit.\n\n IRFrame *buf = (IRFrame*)param;\n debug(\"Packet from 0x%04x to 0x%04x hop %d\",\n buf->source, buf->destination,\n buf->hops);\n\n buf->hops++;\n buf->hton();\n buf->calculate_crc();\n debug(\"Retransmitting packet...\");\n send_frame(*buf);\n debug(\"done\");\n reset();\n\n FrameFactory.free(buf);\n}\n\n\n\/*\n * Editor modelines - https:\/\/www.wireshark.org\/tools\/modelines.html\n *\n * Local variables:\n * mode: c++\n * c-basic-offset: 4\n * tab-width: 8\n * indent-tabs-mode: nil\n * End:\n *\n * vi: set shiftwidth=4 tabstop=8 expandtab:\n * :indentSize=4:tabSize=8:noTabs=true:\n *\/\n<commit_msg>don't relay your own packets<commit_after>\/*\n * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap\n *\n * Copyright (C) 2015 Hacker, J.R. <r00tkillah@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mac.h\"\n#include \"util.h\"\n#include <Arduino.h>\n\nBlinkerMac mac;\nMemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback);\n\nBlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false))\n{\n}\n\nvoid BlinkerMac::begin()\n{\n serial.begin(IR_BAUD);\n reset();\n buf = FrameFactory.alloc();\n eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent,\n &MACRelayCB);\n}\n\nvoid BlinkerMac::reset()\n{\n rx_blink = false;\n packet_in_progress = false;\n buf_pos = 0;\n prefix_state = 0;\n reset_codec_state();\n}\n\nvoid BlinkerMac::write_prefix()\n{\n for (uint8_t i = 0; i < preamble_count; i++) {\n (*this)(preamble_byte);\n }\n for (uint8_t i = 0; i < sizeof(packet_prefix); i++) {\n (*this)(packet_prefix[i]);\n }\n}\n\nbool BlinkerMac::prefix_hit(uint8_t input)\n{\n if (prefix_state == 0) {\n if (input == packet_prefix[0]) {\n prefix_state = 1;\n }\n } else if (prefix_state == 1) {\n if (input == packet_prefix[1]) {\n prefix_state = 2;\n } else {\n prefix_state = 0;\n }\n } else if (prefix_state == 2) {\n if (input == packet_prefix[2]) {\n prefix_state = 3;\n } else {\n prefix_state = 0;\n }\n } else if (prefix_state == 3) {\n prefix_state = 0;\n if (input == packet_prefix[3]) {\n return true;\n }\n }\n return false;\n}\n\nbool BlinkerMac::blink()\n{\n rx_blink = rx_blink ? false : true;\n return rx_blink;\n}\n\nbool BlinkerMac::stalled()\n{\n const unsigned long now = millis();\n\n if (now - last_rx_time > 250) {\n return true;\n }\n last_rx_time = now;\n return false;\n}\n\n\/\/expectation here is that hton is done\n\/\/and crc is calculated\nvoid BlinkerMac::send_frame(IRFrame &frame)\n{\n debug(\"Sending packet\");\n\n write_prefix();\n for (uint16_t i = 0; i < sizeof(IRFrame); i++) {\n encode_byte(frame.blob()[i], *this);\n }\n serial.flush();\n\n \/\/ while this is happening, you'll get crap that is your own packet.\n \/\/ clear out any remaining input\n while(serial.available()) {\n (void)serial.read();\n delay(1);\n }\n}\n\nvoid BlinkerMac::recv(const uint8_t c)\n{\n digitalWrite(13, blink());\n\n \/\/ if you haven't gotten a byte in a while, then what you have\n \/\/ is probably garbage.\n if (packet_in_progress && stalled()) {\n debug(\"aborting rcv\");\n IRFrame::hexdump(buf);\n reset();\n return;\n }\n if (!packet_in_progress) {\n packet_in_progress = prefix_hit(c);\n last_rx_time = millis();\n return; \/\/the next byte should be the first byte of a packet\n }\n\n debugstart(\"%d\", buf_pos);\n debugcont(\" \");\n \/\/geting a packet\n uint8_t input;\n if (decode_byte(c, input)) {\n buf->blob()[buf_pos] = input;\n buf_pos++;\n } else {\n return; \/\/ was a stuffed byte\n }\n\n if (buf_pos >= sizeof(IRFrame)) {\n \/\/whole packet recieved!\n buf_pos = 0;\n packet_in_progress = false;\n\n if (buf->valid()) {\n buf->ntoh();\n\n if (buf->source == address) {\n \/\/ don't relay our own packets\n debugend();\n reset();\n return;\n }\n\n if (buf->destination != address) {\n if (buf->hops < MAX_HOPS) {\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf);\n debugend();\n reset();\n return;\n } else {\n debugcont(\"too many hops.. eating\");\n debugend();\n reset();\n return;\n }\n }\n\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf);\n debugend();\n reset();\n return;\n } else {\n auto newbuf = FrameFactory.alloc();\n IRFrame::copy(newbuf, buf);\n eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf);\n debugend();\n reset();\n }\n }\n return;\n}\n\nvoid BlinkerMac::relayCallback(int event, int param)\n{\n \/\/niave approach.. just send it back out this is kind of wrong we\n \/\/should wait a random time before retransmit and as we get\n \/\/packets, we should cancel retransmit if we saw a neighbor do it\n \/\/first. but when we see that neighbor do it, we schedule a new\n \/\/one to retransmit.\n\n IRFrame *buf = (IRFrame*)param;\n debug(\"Packet from 0x%04x to 0x%04x hop %d\",\n buf->source, buf->destination,\n buf->hops);\n\n buf->hops++;\n buf->hton();\n buf->calculate_crc();\n debug(\"Retransmitting packet...\");\n send_frame(*buf);\n debug(\"done\");\n reset();\n\n FrameFactory.free(buf);\n}\n\n\n\/*\n * Editor modelines - https:\/\/www.wireshark.org\/tools\/modelines.html\n *\n * Local variables:\n * mode: c++\n * c-basic-offset: 4\n * tab-width: 8\n * indent-tabs-mode: nil\n * End:\n *\n * vi: set shiftwidth=4 tabstop=8 expandtab:\n * :indentSize=4:tabSize=8:noTabs=true:\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nFor more information, please see: http:\/\/software.sci.utah.edu\n\nThe MIT License\n\nCopyright (c) 2012 Scientific Computing and Imaging Institute,\nUniversity of Utah.\n\nLicense for the specific language governing rights and limitations under\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Interface\/Modules\/Forward\/BuildBEMatrixDialog.h>\n#include <Core\/Algorithms\/Legacy\/Forward\/BuildBEMatrixAlgo.h>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Forward;\n\nnamespace TableColumns\n{\n const int FieldName = 0;\n const int FieldType = 1;\n const int BoundaryCondition = 2;\n const int InsideConductivity = 3;\n const int OutsideConductivity = 4;\n};\n\nBuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state,\n QWidget* parent \/* = 0 *\/)\n : ModuleDialogGeneric(state, parent)\n{\n setupUi(this);\n setWindowTitle(QString::fromStdString(name));\n fixSize();\n\n tableWidget->resizeColumnsToContents();\n\n connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int)));\n}\n\nvoid BuildBEMatrixDialog::updateFromPortChange(int numPorts)\n{\n \/\/std::cout << \"updateFromPortChange \" << numPorts << std::endl;\n auto oldRowCount = tableWidget->rowCount();\n tableWidget->setRowCount(numPorts - 1);\n tableWidget->blockSignals(true);\n for (int i = oldRowCount; i < tableWidget->rowCount(); ++i)\n {\n using namespace TableColumns;\n tableWidget->setItem(i, FieldName, new QTableWidgetItem(\"field\" + QString::number(i)));\n tableWidget->setItem(i, FieldType, new QTableWidgetItem(\"[populated on execute]\"));\n tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i));\n tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity));\n tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity));\n\n \/\/ type is readonly\n auto type = tableWidget->item(i, FieldType);\n type->setFlags(type->flags() & ~Qt::ItemIsEditable);\n }\n pull();\n tableWidget->resizeColumnsToContents();\n tableWidget->blockSignals(false);\n}\n\nQComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const\n{\n QStringList bcList;\n bcList << \"Measurement (Neumann)\" << \"Source (Dirichlet)\";\n QComboBox* bcBox = new QComboBox();\n bcBox->addItems(bcList);\n bcBox->setCurrentIndex(i == 0 ? 0 : 1);\n connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions()));\n return bcBox;\n}\n\nQDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const\n{\n auto spin = new QDoubleSpinBox();\n spin->setValue((row + col + 1) % 2);\n const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides());\n connect(spin, SIGNAL(valueChanged(double)), this, slot);\n return spin;\n}\n\nvoid BuildBEMatrixDialog::pushTable(int row, int col)\n{\n using namespace TableColumns;\n if (FieldName == col)\n pushNames();\n else if (BoundaryCondition == col)\n pushBoundaryConditions();\n else if (InsideConductivity == col)\n pushInsides();\n else if (OutsideConductivity == col)\n pushOutsides();\n}\n\nvoid BuildBEMatrixDialog::pushNames()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto item = tableWidget->item(i, FieldName);\n names.push_back(makeVariable(\"\", item->text().toStdString()));\n }\n state_->setValue(Parameters::FieldNameList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushBoundaryConditions()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition));\n names.push_back(makeVariable(\"\", box->currentText().toStdString()));\n }\n state_->setValue(Parameters::BoundaryConditionList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushInsides()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity));\n names.push_back(makeVariable(\"\", box->value()));\n }\n state_->setValue(Parameters::InsideConductivityList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushOutsides()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity));\n names.push_back(makeVariable(\"\", box->value()));\n }\n state_->setValue(Parameters::OutsideConductivityList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pull()\n{\n \/\/std::cout << \"BE pull\" << std::endl;\n pullNames();\n pullFieldTypes();\n pullBoundaryConditions();\n pullInsides();\n pullOutsides();\n}\n\nvoid BuildBEMatrixDialog::pullNames()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto nameList = state_->getValue(Parameters::FieldNameList).toVector();\n const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto item = tableWidget->item(row, FieldName);\n item->setText(QString::fromStdString(nameList[row].toString()));\n }\n}\n\nvoid BuildBEMatrixDialog::pullFieldTypes()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto typeList = optional_any_cast_or_default<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList));\n const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto item = tableWidget->item(row, FieldName);\n item->setText(QString::fromStdString(typeList[row]));\n }\n}\n\nvoid BuildBEMatrixDialog::pullBoundaryConditions()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector();\n const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition));\n auto str = QString::fromStdString(bdyList[row].toString());\n box->setCurrentIndex(box->findText(str));\n }\n}\n\nvoid BuildBEMatrixDialog::pullInsides()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto condList = state_->getValue(Parameters::InsideConductivityList).toVector();\n const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity));\n box->setValue(condList[row].toDouble());\n }\n}\n\nvoid BuildBEMatrixDialog::pullOutsides()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector();\n const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity));\n box->setValue(condList[row].toDouble());\n }\n}\n<commit_msg>Wrong column<commit_after>\/*\nFor more information, please see: http:\/\/software.sci.utah.edu\n\nThe MIT License\n\nCopyright (c) 2012 Scientific Computing and Imaging Institute,\nUniversity of Utah.\n\nLicense for the specific language governing rights and limitations under\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Interface\/Modules\/Forward\/BuildBEMatrixDialog.h>\n#include <Core\/Algorithms\/Legacy\/Forward\/BuildBEMatrixAlgo.h>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Forward;\n\nnamespace TableColumns\n{\n const int FieldName = 0;\n const int FieldType = 1;\n const int BoundaryCondition = 2;\n const int InsideConductivity = 3;\n const int OutsideConductivity = 4;\n};\n\nBuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state,\n QWidget* parent \/* = 0 *\/)\n : ModuleDialogGeneric(state, parent)\n{\n setupUi(this);\n setWindowTitle(QString::fromStdString(name));\n fixSize();\n\n tableWidget->resizeColumnsToContents();\n\n connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int)));\n}\n\nvoid BuildBEMatrixDialog::updateFromPortChange(int numPorts)\n{\n \/\/std::cout << \"updateFromPortChange \" << numPorts << std::endl;\n auto oldRowCount = tableWidget->rowCount();\n tableWidget->setRowCount(numPorts - 1);\n tableWidget->blockSignals(true);\n for (int i = oldRowCount; i < tableWidget->rowCount(); ++i)\n {\n using namespace TableColumns;\n tableWidget->setItem(i, FieldName, new QTableWidgetItem(\"field\" + QString::number(i)));\n tableWidget->setItem(i, FieldType, new QTableWidgetItem(\"[populated on execute]\"));\n tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i));\n tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity));\n tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity));\n\n \/\/ type is readonly\n auto type = tableWidget->item(i, FieldType);\n type->setFlags(type->flags() & ~Qt::ItemIsEditable);\n }\n pull();\n tableWidget->resizeColumnsToContents();\n tableWidget->blockSignals(false);\n}\n\nQComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const\n{\n QStringList bcList;\n bcList << \"Measurement (Neumann)\" << \"Source (Dirichlet)\";\n QComboBox* bcBox = new QComboBox();\n bcBox->addItems(bcList);\n bcBox->setCurrentIndex(i == 0 ? 0 : 1);\n connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions()));\n return bcBox;\n}\n\nQDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const\n{\n auto spin = new QDoubleSpinBox();\n spin->setValue((row + col + 1) % 2);\n const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides());\n connect(spin, SIGNAL(valueChanged(double)), this, slot);\n return spin;\n}\n\nvoid BuildBEMatrixDialog::pushTable(int row, int col)\n{\n using namespace TableColumns;\n if (FieldName == col)\n pushNames();\n else if (BoundaryCondition == col)\n pushBoundaryConditions();\n else if (InsideConductivity == col)\n pushInsides();\n else if (OutsideConductivity == col)\n pushOutsides();\n}\n\nvoid BuildBEMatrixDialog::pushNames()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto item = tableWidget->item(i, FieldName);\n names.push_back(makeVariable(\"\", item->text().toStdString()));\n }\n state_->setValue(Parameters::FieldNameList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushBoundaryConditions()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition));\n names.push_back(makeVariable(\"\", box->currentText().toStdString()));\n }\n state_->setValue(Parameters::BoundaryConditionList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushInsides()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity));\n names.push_back(makeVariable(\"\", box->value()));\n }\n state_->setValue(Parameters::InsideConductivityList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pushOutsides()\n{\n using namespace TableColumns;\n if (!pulling_)\n {\n VariableList names;\n for (int i = 0; i < tableWidget->rowCount(); ++i)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity));\n names.push_back(makeVariable(\"\", box->value()));\n }\n state_->setValue(Parameters::OutsideConductivityList, names);\n }\n}\n\nvoid BuildBEMatrixDialog::pull()\n{\n \/\/std::cout << \"BE pull\" << std::endl;\n pullNames();\n pullFieldTypes();\n pullBoundaryConditions();\n pullInsides();\n pullOutsides();\n}\n\nvoid BuildBEMatrixDialog::pullNames()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto nameList = state_->getValue(Parameters::FieldNameList).toVector();\n const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto item = tableWidget->item(row, FieldName);\n item->setText(QString::fromStdString(nameList[row].toString()));\n }\n}\n\nvoid BuildBEMatrixDialog::pullFieldTypes()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto typeList = optional_any_cast_or_default<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList));\n const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto item = tableWidget->item(row, FieldType);\n item->setText(QString::fromStdString(typeList[row]));\n }\n}\n\nvoid BuildBEMatrixDialog::pullBoundaryConditions()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector();\n const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition));\n auto str = QString::fromStdString(bdyList[row].toString());\n box->setCurrentIndex(box->findText(str));\n }\n}\n\nvoid BuildBEMatrixDialog::pullInsides()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto condList = state_->getValue(Parameters::InsideConductivityList).toVector();\n const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity));\n box->setValue(condList[row].toDouble());\n }\n}\n\nvoid BuildBEMatrixDialog::pullOutsides()\n{\n using namespace TableColumns;\n Pulling p(this);\n auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector();\n const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount());\n for (int row = 0; row < rows; ++row)\n {\n auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity));\n box->setValue(condList[row].toDouble());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"OSPRayCamera.h\"\n#include <Interface\/Modules\/Render\/ES\/RendererInterfaceCollaborators.h>\n\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace SCIRun::Render;\nusing namespace SCIRun::Core::Geometry;\n\nOSPRayCamera::OSPRayCamera()\n{\n camera_ = ospNewCamera(\"perspective\");\n}\n\nOSPRayCamera::~OSPRayCamera()\n{\n ospRelease(camera_);\n}\n\nOSPCamera OSPRayCamera::getOSPCamera()\n{\n glm::vec3 dir = target_ - pos_;\n float dist = glm::length(dir);\n dir = dir\/dist;\n\n ospSetParam(camera_, \"position\", OSP_VEC3F, glm::value_ptr(pos_));\n ospSetParam(camera_, \"direction\", OSP_VEC3F, glm::value_ptr(dir));\n ospSetParam(camera_, \"up\", OSP_VEC3F, glm::value_ptr(up_));\n ospSetParam(camera_, \"aspect\", OSP_FLOAT, &aspect_);\n ospSetParam(camera_, \"fovy\", OSP_FLOAT, &fovy_);\n ospSetParam(camera_, \"apertureRadius\", OSP_FLOAT, &aperture_);\n ospSetParam(camera_, \"focusDistance\", OSP_FLOAT, &dist);\n ospCommit(camera_);\n\n return camera_;\n}\n\nvoid OSPRayCamera::mousePress(float x, float y, MouseButton btn)\n{\n switch(btn)\n {\n case MouseButton::LEFT:\n case MouseButton::RIGHT:\n lookat_.doReferenceDown(glm::vec2(x, -y));\n break;\n\n default:break;\n }\n}\n\nvoid OSPRayCamera::mouseMove(float x, float y, MouseButton btn)\n{\n switch (btn)\n {\n case MouseButton::LEFT:\n lookat_.doRotation(glm::vec2(x, -y));\n pos_ = lookat_.getPos();\n up_ = lookat_.getUp();\n break;\n\n case MouseButton::RIGHT:\n lookat_.doPan(glm::vec2(x, -y));\n pos_ = lookat_.getPos();\n target_ = lookat_.getTarget();\n break;\n\n default:\n break;\n }\n}\n\nvoid OSPRayCamera::mouseRelease()\n{\n\n}\n\nvoid OSPRayCamera::mouseWheel(int delta)\n{\n lookat_.doZoom(-delta\/100.0f);\n pos_ = lookat_.getPos();\n}\n\nfloat OSPRayCamera::toRadians(float v)\n{\n const static float HALF_TURN_DEGREES = 180;\n const static float TO_RADIAN_OPERATOR = glm::pi<float>() \/ HALF_TURN_DEGREES;\n return TO_RADIAN_OPERATOR * v;\n}\n\nvoid OSPRayCamera::autoView()\n{\n if(!sceneBBox_.valid()) return;\n\n \/\/ Convert core geom bbox to AABB.\n Core::Geometry::Point bboxMin = sceneBBox_.get_min();\n Core::Geometry::Point bboxMax = sceneBBox_.get_max();\n glm::vec3 min(bboxMin.x(), bboxMin.y(), bboxMin.z());\n glm::vec3 max(bboxMax.x(), bboxMax.y(), bboxMax.z());\n\n spire::AABB aabb(min, max);\n\n \/\/ The arcball class expects fov in radians\n lookat_.autoview(aabb, toRadians(fovy_));\n pos_ = lookat_.getPos();\n}\n\nvoid OSPRayCamera::setSceneBoundingBox(const BBox& bbox)\n{\n sceneBBox_ = bbox;\n}\n<commit_msg>Set target on autoview<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"OSPRayCamera.h\"\n#include <Interface\/Modules\/Render\/ES\/RendererInterfaceCollaborators.h>\n\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace SCIRun::Render;\nusing namespace SCIRun::Core::Geometry;\n\nOSPRayCamera::OSPRayCamera()\n{\n camera_ = ospNewCamera(\"perspective\");\n}\n\nOSPRayCamera::~OSPRayCamera()\n{\n ospRelease(camera_);\n}\n\nOSPCamera OSPRayCamera::getOSPCamera()\n{\n glm::vec3 dir = target_ - pos_;\n float dist = glm::length(dir);\n dir = dir\/dist;\n\n ospSetParam(camera_, \"position\", OSP_VEC3F, glm::value_ptr(pos_));\n ospSetParam(camera_, \"direction\", OSP_VEC3F, glm::value_ptr(dir));\n ospSetParam(camera_, \"up\", OSP_VEC3F, glm::value_ptr(up_));\n ospSetParam(camera_, \"aspect\", OSP_FLOAT, &aspect_);\n ospSetParam(camera_, \"fovy\", OSP_FLOAT, &fovy_);\n ospSetParam(camera_, \"apertureRadius\", OSP_FLOAT, &aperture_);\n ospSetParam(camera_, \"focusDistance\", OSP_FLOAT, &dist);\n ospCommit(camera_);\n\n return camera_;\n}\n\nvoid OSPRayCamera::mousePress(float x, float y, MouseButton btn)\n{\n switch(btn)\n {\n case MouseButton::LEFT:\n case MouseButton::RIGHT:\n lookat_.doReferenceDown(glm::vec2(x, -y));\n break;\n\n default:break;\n }\n}\n\nvoid OSPRayCamera::mouseMove(float x, float y, MouseButton btn)\n{\n switch (btn)\n {\n case MouseButton::LEFT:\n lookat_.doRotation(glm::vec2(x, -y));\n pos_ = lookat_.getPos();\n up_ = lookat_.getUp();\n break;\n\n case MouseButton::RIGHT:\n lookat_.doPan(glm::vec2(x, -y));\n pos_ = lookat_.getPos();\n target_ = lookat_.getTarget();\n break;\n\n default:\n break;\n }\n}\n\nvoid OSPRayCamera::mouseRelease()\n{\n\n}\n\nvoid OSPRayCamera::mouseWheel(int delta)\n{\n lookat_.doZoom(-delta\/100.0f);\n pos_ = lookat_.getPos();\n}\n\nfloat OSPRayCamera::toRadians(float v)\n{\n const static float HALF_TURN_DEGREES = 180;\n const static float TO_RADIAN_OPERATOR = glm::pi<float>() \/ HALF_TURN_DEGREES;\n return TO_RADIAN_OPERATOR * v;\n}\n\nvoid OSPRayCamera::autoView()\n{\n if(!sceneBBox_.valid()) return;\n\n \/\/ Convert core geom bbox to AABB.\n Core::Geometry::Point bboxMin = sceneBBox_.get_min();\n Core::Geometry::Point bboxMax = sceneBBox_.get_max();\n glm::vec3 min(bboxMin.x(), bboxMin.y(), bboxMin.z());\n glm::vec3 max(bboxMax.x(), bboxMax.y(), bboxMax.z());\n\n spire::AABB aabb(min, max);\n\n \/\/ The arcball class expects fov in radians\n lookat_.autoview(aabb, toRadians(fovy_));\n pos_ = lookat_.getPos();\n target_ = lookat_.getTarget();\n}\n\nvoid OSPRayCamera::setSceneBoundingBox(const BBox& bbox)\n{\n sceneBBox_ = bbox;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gridModel.h\"\n#include \"cellutils.h\"\n#include \"gridCell.h\"\n#include \"inexcitablecell.h\"\n\nusing namespace std;\nusing namespace LongQt;\n\nGridModel::GridModel(shared_ptr<GridProtocol> proto, QObject* parent)\n : QAbstractTableModel(parent) {\n if (proto) {\n this->proto = proto;\n } else {\n this->proto.reset(new GridProtocol());\n }\n this->grid = proto->gridCell()->getGrid();\n cellMap = CellUtils::cellMap;\n cellMap[\"Inexcitable Cell\"] = []() { return make_shared<InexcitableCell>(); };\n}\nbool GridModel::setProtocol(shared_ptr<GridProtocol> proto) {\n this->proto = proto;\n this->grid = proto->gridCell()->getGrid();\n QAbstractItemModel::resetInternalData();\n return true;\n}\nint GridModel::rowCount(const QModelIndex&) const {\n return this->grid->rowCount();\n}\nint GridModel::columnCount(const QModelIndex&) const {\n return this->grid->columnCount();\n}\nQVariant GridModel::data(const QModelIndex& index, int role) const {\n switch (role) {\n case Qt::DisplayRole:\n return this->dataDisplay(index);\n break;\n case Qt::ToolTipRole:\n return this->dataToolTip(index);\n break;\n case Qt::StatusTipRole:\n return this->dataStatusTip(index);\n break;\n default:\n return QVariant();\n }\n}\nQVariant GridModel::dataDisplay(const QModelIndex& index) const {\n if (index.internalPointer() == 0) {\n shared_ptr<Node> n = (*this->grid)(index.row(), index.column());\n if (!n) {\n return QVariant();\n }\n return QString(n->cell->type());\n } else {\n pair<int, int> p = make_pair(index.parent().row(), index.parent().column());\n if (index.row() == 0) {\n if (index.column() == 0) {\n return this->proto->getStimNodes().count(p) > 0;\n } else if (index.column() == 1) {\n return this->proto->gridMeasureMgr().dataNodes().count(p) > 0;\n }\n } else if (index.row() == 1) {\n switch (index.column()) {\n case 0: \/\/ top\n return grid->columns.at(p.second).B.at(p.first);\n break;\n case 1: \/\/ right\n return grid->rows.at(p.first).B.at(p.second + 1);\n break;\n case 2: \/\/ bottom\n return grid->columns.at(p.second).B.at(p.first + 1);\n break;\n case 3: \/\/ left\n return grid->rows.at(p.first).B.at(p.second);\n break;\n }\n }\n }\n return QVariant();\n}\nQVariant GridModel::dataToolTip(const QModelIndex& index) const {\n return this->data(index);\n}\nQVariant GridModel::dataStatusTip(const QModelIndex& index) const {\n QString statusTip = \"\";\n statusTip +=\n \"Top: \" + QString::number(index.child(1, 0).data().toDouble()) + \" \";\n statusTip +=\n \"Right: \" + QString::number(index.child(1, 1).data().toDouble()) + \" \";\n statusTip +=\n \"Bottom: \" + QString::number(index.child(1, 2).data().toDouble()) + \" \";\n statusTip +=\n \"Left: \" + QString::number(index.child(1, 3).data().toDouble()) + \" \";\n\n return statusTip;\n}\nbool GridModel::setData(const QModelIndex& index, const QVariant& value, int) {\n bool success = false;\n if (index.internalPointer() == 0) {\n CellInfo info;\n info.row = index.row();\n info.col = index.column();\n try {\n info.cell = this->cellMap.at(value.toString().toStdString())();\n info.dx = proto->cell()->par(\"dx\");\n info.dy = proto->cell()->par(\"dy\");\n info.np = proto->cell()->par(\"np\");\n if (info.cell->par(\"dtmin\") < proto->cell()->par(\"dtmin\")) {\n proto->cell()->setPar(\"dtmin\", info.cell->par(\"dtmin\"));\n }\n if (info.cell->par(\"dtmed\") < proto->cell()->par(\"dtmed\")) {\n proto->cell()->setPar(\"dtmed\", info.cell->par(\"dtmed\"));\n }\n if (info.cell->par(\"dtmax\") < proto->cell()->par(\"dtmax\")) {\n proto->cell()->setPar(\"dtmax\", info.cell->par(\"dtmax\"));\n }\n this->grid->setCellTypes(info);\n emit cellChanged(proto->cell());\n emit dataChanged(index, index);\n } catch (const std::out_of_range&) {\n Logger::getInstance()->write(\n \"{} not a valid cell type or ({},{}) out of range\",\n qUtf8Printable(value.toString()), info.col, info.row);\n }\n success = true;\n } else {\n pair<int, int> p = make_pair(index.parent().row(), index.parent().column());\n if (index.row() == 0) {\n if (index.column() == 0) {\n if (value.toBool()) {\n this->proto->getStimNodes().insert(p);\n } else {\n this->proto->getStimNodes().erase(p);\n }\n success = true;\n } else if (index.column() == 1) {\n if (value.toBool()) {\n auto nodes = this->proto->gridMeasureMgr().dataNodes();\n nodes.insert(p);\n this->proto->gridMeasureMgr().dataNodes(nodes);\n } else {\n auto nodes = this->proto->gridMeasureMgr().dataNodes();\n nodes.erase(p);\n this->proto->gridMeasureMgr().dataNodes(nodes);\n }\n success = true;\n }\n } else if (index.row() == 1) {\n CellInfo u;\n u.row = index.parent().row();\n u.col = index.parent().column();\n u.dx = proto->cell()->par(\"dx\");\n u.dy = proto->cell()->par(\"dy\");\n u.np = proto->cell()->par(\"np\");\n \/\/ this works because column is setup follow cellutils_side.h:Side\n double val = value.toDouble();\n if (this->percent) {\n val \/= 100;\n }\n u.c[index.column()] = val;\n u.c_perc = this->percent;\n try {\n grid->setCellTypes(u);\n success = true;\n } catch (std::out_of_range) {\n Logger::getInstance()->write(\"({},{}) out of range\", u.col, u.row);\n success = false;\n }\n }\n if (success) {\n emit dataChanged(index.parent(), index.parent());\n }\n }\n return success;\n}\nQt::ItemFlags GridModel::flags(const QModelIndex& index) const {\n if (!index.isValid()) return Qt::ItemIsEnabled;\n\n return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;\n}\nbool GridModel::insertRows(int row, int count, const QModelIndex& parent) {\n this->beginInsertRows(parent, row, row + count - 1);\n this->grid->addRows(static_cast<unsigned int>(count));\n this->endInsertRows();\n return true;\n}\nbool GridModel::removeRows(int row, int count, const QModelIndex& parent) {\n \/\/ imput must not be within grid size\n \/\/ sanitize inputs\n if (row < 0) {\n row = 0;\n }\n if (row > this->rowCount()) {\n row = this->rowCount() - 1;\n }\n int last = row + count - 1;\n if (last >= this->rowCount()) {\n last = this->rowCount() - 1;\n }\n this->beginRemoveRows(parent, row, last);\n this->grid->removeRows(static_cast<unsigned int>(count), row);\n this->endRemoveRows();\n return true;\n}\nbool GridModel::insertColumns(int column, int count,\n const QModelIndex& parent) {\n this->beginInsertColumns(parent, column, column + count - 1);\n this->grid->addColumns(static_cast<unsigned int>(count));\n this->endInsertColumns();\n return true;\n}\nbool GridModel::removeColumns(int column, int count,\n const QModelIndex& parent) {\n \/\/ imput must not be within grid size\n \/\/ sanitize inputs\n if (column < 0) {\n column = 0;\n }\n if (column > this->columnCount()) {\n column = this->columnCount() - 1;\n }\n int last = column + count - 1;\n if (last >= this->columnCount()) {\n last = this->columnCount() - 1;\n }\n this->beginRemoveColumns(parent, column, last);\n this->grid->removeColumns(static_cast<unsigned int>(count), column);\n this->endRemoveColumns();\n return true;\n}\nQModelIndex GridModel::index(int row, int column,\n const QModelIndex& parent) const {\n if (!parent.isValid()) {\n return QAbstractTableModel::index(row, column, parent);\n }\n auto pos = new QPair<int, int>(parent.row(), parent.column());\n connect(this, &QObject::destroyed, [pos]() { delete pos; });\n return QAbstractTableModel::createIndex(row, column, pos);\n}\nQModelIndex GridModel::parent(const QModelIndex& index) const {\n QPair<int, int>* p = 0;\n if ((p = static_cast<QPair<int, int>*>(index.internalPointer()))) {\n return this->index(p->first, p->second, QModelIndex());\n }\n return QModelIndex();\n}\n\nQVariant GridModel::headerData(int section, Qt::Orientation o, int role) const {\n if (role == Qt::DisplayRole) {\n return section;\n }\n return QAbstractTableModel::headerData(section, o, role);\n}\n\nvoid GridModel::reloadModel() {\n this->beginResetModel();\n this->endResetModel();\n}\n\nvoid GridModel::clear() {\n this->grid->reset();\n this->beginResetModel();\n this->endResetModel();\n}\n\nbool GridModel::getPercent() { return this->percent; }\n\nvoid GridModel::setPercent(bool percent) { this->percent = percent; }\n<commit_msg>moved dx, dy, np from gridcell to grid<commit_after>#include \"gridModel.h\"\n#include \"cellutils.h\"\n#include \"gridCell.h\"\n#include \"inexcitablecell.h\"\n\nusing namespace std;\nusing namespace LongQt;\n\nGridModel::GridModel(shared_ptr<GridProtocol> proto, QObject* parent)\n : QAbstractTableModel(parent) {\n if (proto) {\n this->proto = proto;\n } else {\n this->proto.reset(new GridProtocol());\n }\n this->grid = proto->gridCell()->getGrid();\n cellMap = CellUtils::cellMap;\n cellMap[\"Inexcitable Cell\"] = []() { return make_shared<InexcitableCell>(); };\n}\nbool GridModel::setProtocol(shared_ptr<GridProtocol> proto) {\n this->proto = proto;\n this->grid = proto->gridCell()->getGrid();\n QAbstractItemModel::resetInternalData();\n return true;\n}\nint GridModel::rowCount(const QModelIndex&) const {\n return this->grid->rowCount();\n}\nint GridModel::columnCount(const QModelIndex&) const {\n return this->grid->columnCount();\n}\nQVariant GridModel::data(const QModelIndex& index, int role) const {\n switch (role) {\n case Qt::DisplayRole:\n return this->dataDisplay(index);\n break;\n case Qt::ToolTipRole:\n return this->dataToolTip(index);\n break;\n case Qt::StatusTipRole:\n return this->dataStatusTip(index);\n break;\n default:\n return QVariant();\n }\n}\nQVariant GridModel::dataDisplay(const QModelIndex& index) const {\n if (index.internalPointer() == 0) {\n shared_ptr<Node> n = (*this->grid)(index.row(), index.column());\n if (!n) {\n return QVariant();\n }\n return QString(n->cell->type());\n } else {\n pair<int, int> p = make_pair(index.parent().row(), index.parent().column());\n if (index.row() == 0) {\n if (index.column() == 0) {\n return this->proto->getStimNodes().count(p) > 0;\n } else if (index.column() == 1) {\n return this->proto->gridMeasureMgr().dataNodes().count(p) > 0;\n }\n } else if (index.row() == 1) {\n switch (index.column()) {\n case 0: \/\/ top\n return grid->columns.at(p.second).B.at(p.first);\n break;\n case 1: \/\/ right\n return grid->rows.at(p.first).B.at(p.second + 1);\n break;\n case 2: \/\/ bottom\n return grid->columns.at(p.second).B.at(p.first + 1);\n break;\n case 3: \/\/ left\n return grid->rows.at(p.first).B.at(p.second);\n break;\n }\n }\n }\n return QVariant();\n}\nQVariant GridModel::dataToolTip(const QModelIndex& index) const {\n return this->data(index);\n}\nQVariant GridModel::dataStatusTip(const QModelIndex& index) const {\n QString statusTip = \"\";\n statusTip +=\n \"Top: \" + QString::number(index.child(1, 0).data().toDouble()) + \" \";\n statusTip +=\n \"Right: \" + QString::number(index.child(1, 1).data().toDouble()) + \" \";\n statusTip +=\n \"Bottom: \" + QString::number(index.child(1, 2).data().toDouble()) + \" \";\n statusTip +=\n \"Left: \" + QString::number(index.child(1, 3).data().toDouble()) + \" \";\n\n return statusTip;\n}\nbool GridModel::setData(const QModelIndex& index, const QVariant& value, int) {\n bool success = false;\n if (index.internalPointer() == 0) {\n CellInfo info;\n info.row = index.row();\n info.col = index.column();\n try {\n info.cell = this->cellMap.at(value.toString().toStdString())();\n if (info.cell->par(\"dtmin\") < proto->cell()->par(\"dtmin\")) {\n proto->cell()->setPar(\"dtmin\", info.cell->par(\"dtmin\"));\n }\n if (info.cell->par(\"dtmed\") < proto->cell()->par(\"dtmed\")) {\n proto->cell()->setPar(\"dtmed\", info.cell->par(\"dtmed\"));\n }\n if (info.cell->par(\"dtmax\") < proto->cell()->par(\"dtmax\")) {\n proto->cell()->setPar(\"dtmax\", info.cell->par(\"dtmax\"));\n }\n this->grid->setCellTypes(info);\n emit cellChanged(proto->cell());\n emit dataChanged(index, index);\n } catch (const std::out_of_range&) {\n Logger::getInstance()->write(\n \"{} not a valid cell type or ({},{}) out of range\",\n qUtf8Printable(value.toString()), info.col, info.row);\n }\n success = true;\n } else {\n pair<int, int> p = make_pair(index.parent().row(), index.parent().column());\n if (index.row() == 0) {\n if (index.column() == 0) {\n if (value.toBool()) {\n this->proto->getStimNodes().insert(p);\n } else {\n this->proto->getStimNodes().erase(p);\n }\n success = true;\n } else if (index.column() == 1) {\n if (value.toBool()) {\n auto nodes = this->proto->gridMeasureMgr().dataNodes();\n nodes.insert(p);\n this->proto->gridMeasureMgr().dataNodes(nodes);\n } else {\n auto nodes = this->proto->gridMeasureMgr().dataNodes();\n nodes.erase(p);\n this->proto->gridMeasureMgr().dataNodes(nodes);\n }\n success = true;\n }\n } else if (index.row() == 1) {\n CellInfo u;\n u.row = index.parent().row();\n u.col = index.parent().column();\n \/\/ this works because column is setup follow cellutils_side.h:Side\n double val = value.toDouble();\n if (this->percent) {\n val \/= 100;\n }\n u.c[index.column()] = val;\n u.c_perc = this->percent;\n try {\n grid->setCellTypes(u);\n success = true;\n } catch (std::out_of_range) {\n Logger::getInstance()->write(\"({},{}) out of range\", u.col, u.row);\n success = false;\n }\n }\n if (success) {\n emit dataChanged(index.parent(), index.parent());\n }\n }\n return success;\n}\nQt::ItemFlags GridModel::flags(const QModelIndex& index) const {\n if (!index.isValid()) return Qt::ItemIsEnabled;\n\n return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;\n}\nbool GridModel::insertRows(int row, int count, const QModelIndex& parent) {\n this->beginInsertRows(parent, row, row + count - 1);\n this->grid->addRows(static_cast<unsigned int>(count));\n this->endInsertRows();\n return true;\n}\nbool GridModel::removeRows(int row, int count, const QModelIndex& parent) {\n \/\/ imput must not be within grid size\n \/\/ sanitize inputs\n if (row < 0) {\n row = 0;\n }\n if (row > this->rowCount()) {\n row = this->rowCount() - 1;\n }\n int last = row + count - 1;\n if (last >= this->rowCount()) {\n last = this->rowCount() - 1;\n }\n this->beginRemoveRows(parent, row, last);\n this->grid->removeRows(static_cast<unsigned int>(count), row);\n this->endRemoveRows();\n return true;\n}\nbool GridModel::insertColumns(int column, int count,\n const QModelIndex& parent) {\n this->beginInsertColumns(parent, column, column + count - 1);\n this->grid->addColumns(static_cast<unsigned int>(count));\n this->endInsertColumns();\n return true;\n}\nbool GridModel::removeColumns(int column, int count,\n const QModelIndex& parent) {\n \/\/ imput must not be within grid size\n \/\/ sanitize inputs\n if (column < 0) {\n column = 0;\n }\n if (column > this->columnCount()) {\n column = this->columnCount() - 1;\n }\n int last = column + count - 1;\n if (last >= this->columnCount()) {\n last = this->columnCount() - 1;\n }\n this->beginRemoveColumns(parent, column, last);\n this->grid->removeColumns(static_cast<unsigned int>(count), column);\n this->endRemoveColumns();\n return true;\n}\nQModelIndex GridModel::index(int row, int column,\n const QModelIndex& parent) const {\n if (!parent.isValid()) {\n return QAbstractTableModel::index(row, column, parent);\n }\n auto pos = new QPair<int, int>(parent.row(), parent.column());\n connect(this, &QObject::destroyed, [pos]() { delete pos; });\n return QAbstractTableModel::createIndex(row, column, pos);\n}\nQModelIndex GridModel::parent(const QModelIndex& index) const {\n QPair<int, int>* p = 0;\n if ((p = static_cast<QPair<int, int>*>(index.internalPointer()))) {\n return this->index(p->first, p->second, QModelIndex());\n }\n return QModelIndex();\n}\n\nQVariant GridModel::headerData(int section, Qt::Orientation o, int role) const {\n if (role == Qt::DisplayRole) {\n return section;\n }\n return QAbstractTableModel::headerData(section, o, role);\n}\n\nvoid GridModel::reloadModel() {\n this->beginResetModel();\n this->endResetModel();\n}\n\nvoid GridModel::clear() {\n this->grid->reset();\n this->beginResetModel();\n this->endResetModel();\n}\n\nbool GridModel::getPercent() { return this->percent; }\n\nvoid GridModel::setPercent(bool percent) { this->percent = percent; }\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n\n#include <getopt.h>\n\n#include <ft2build.h>\n#include FT_FREETYPE_H\n\nint main(int argc, char **argv) {\n\n int c;\n\n char *text_file_name;\n char *font_file_name;\n\n while (1) {\n static struct option long_options[] = { { \"font\", required_argument,\n NULL, 'f' }, { \"text\", required_argument, NULL, 't' }, { 0, 0,\n 0, 0 } };\n\n int option_index = 0;\n\n c = getopt_long(argc, argv, \"f:t:\", long_options, &option_index);\n\n if (c == -1) {\n break;\n }\n\n switch (c) {\n case 0:\n break;\n\n case 't':\n text_file_name = optarg;\n break;\n\n case 'f':\n font_file_name = optarg;\n break;\n\n case '?':\n \/* getopt_long already printed an error message. *\/\n break;\n\n default:\n return 1;\n }\n }\n\n return 0;\n}\n\n<commit_msg>can't read debian latex arphic font files??<commit_after>#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n\n#include <getopt.h>\n\n#include <ft2build.h>\n#include FT_FREETYPE_H\n\nint main(int argc, char **argv) {\n\n char *text_file_name;\n char *font_file_name;\n\n int c;\n\n while (1) {\n static struct option long_options[] = { { \"font\", required_argument,\n NULL, 'f' }, { \"text\", required_argument, NULL, 't' }, { NULL,\n 0, NULL, 0 } };\n\n int option_index = 0;\n\n c = getopt_long(argc, argv, \"f:t:\", long_options, &option_index);\n\n if (c == -1) {\n break;\n }\n\n switch (c) {\n case 0:\n break;\n\n case 't':\n text_file_name = optarg;\n break;\n\n case 'f':\n font_file_name = optarg;\n break;\n\n case '?':\n \/* getopt_long already printed an error message. *\/\n break;\n\n default:\n return 1;\n }\n }\n\n FT_Library library;\n FT_Face face;\n\n int error;\n\n error = FT_Init_FreeType(&library);\n if (error) {\n std::cerr << \"font library init failed at \" << __FILE__ << \" \"\n << __LINE__ << std::endl;\n return 1;\n }\n\n error = FT_New_Face(library, font_file_name, 0, &face);\n if (error == FT_Err_Unknown_File_Format) {\n std::cerr << \"unknown font file format\" << std::endl;\n } else if (error) {\n std::cerr << \"error reading font file\" << std::endl;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"newCore.h\"\n#include <stdlib.h>\n\nusing namespace std;\nint ask =1; \nint answer=0;\nvoid NewCore::init(){\n\n\tmngrSub = handle.subscribe<std_msgs::String>(\"\/tawi\/core\/launch\", 10, &NewCore::launchCallback, this);\n\tmngrPub = handle.advertise<std_msgs::String>(\"\/tawi\/core\/launch\", 100);\n\n\tmathSub = handle.subscribe<std_msgs::String>(\"\/display\", 10, &NewCore::mathCallback, this);\n\tserSub = handle.subscribe<std_msgs::String>(\"\/tawi\/arduino\/serial\", 100,&NewCore::serialCallback,this);\n\tmathPub = handle.advertise<std_msgs::String>(\"\/questions\", 100);\n\n\tballPub = handle.advertise<std_msgs::Int16>(\"\/tawi\/core\/ballcount\", 100);\n\tnmbrPub = handle.advertise<std_msgs::Int16>(\"\/tawi\/core\/number\", 100);\n}\n\nvoid NewCore::launchCallback(const std_msgs::String::ConstPtr &msg){\n\tif(\"donelaunching\" == msg->data){\n\t\tstopLaunch();\n\t}\n\n\tif(\"doneconveying\" == msg->data){\n\t\tstopConvey();\n\t}\n}\n\nvoid NewCore::stopLaunch(){\n\tballCount = 0;\n}\n\nvoid NewCore::stopConvey(){\n\t\/\/Waittime currently hardcoded in converyorDriver.cpp\n\t\/\/This method is currently not used\n}\n\nvoid NewCore::startLaunch(){\n\tstd_msgs::String launchmsg;\n\tlaunchmsg.data = \"startlaunch\";\n\tmngrPub.publish(launchmsg);\n}\n\nvoid NewCore::startConvey(){\n\tstd_msgs::String conveymsg;\n\tconveymsg.data = \"startconveyor\";\n\tmngrPub.publish(conveymsg);\n}\n\nvoid NewCore::spin(){\n\tros::Rate rate(10);\n\n\twhile(ros::ok()){\n\n\t\tif (ask){\n\t\t\taskMath();}\n\t\tros::spinOnce();\n\t\trate.sleep();\n\t}\n}\n\nvoid NewCore::acceptBall(){\n\tROS_INFO(\"Ball accepted. Publishing to LaunchManager\");\n\tballCount++;\n\tstd_msgs::Int16 balls;\n\tballs.data = ballCount;\n\tballPub.publish(balls);\n}\n\nvoid NewCore::writeSerial(string shit){\n\tROS_INFO(\"NewCore: Writing on serial through system call:%s\", shit.c_str());\n\tstd::stringstream sysCall;\n sysCall<<\"\/home\/ubuntu\/robotica-minor-5\/com\/arduino-serial\/arduino-serial --port=\/dev\/ttyACM0 --send=\\\"\"<<shit<<\"\\\"\"; \n\tstring temp= sysCall.str();\n\tROS_INFO(\"NewCOre: syscall: %s\", temp.c_str());\n\tsystem(temp.c_str());\n\n}\n\nvoid NewCore::deleteBall(const int ballnumber){ \/\/written by bob, muchos bugs\n\tstd_msgs::Int16 number;\n\tnumber.data = ballnumber;\n\tnmbrPub.publish(number);\n}\nint getAnsweri(int firstnumber, int operation , int secondnumber){\n switch(operation){\n case 'D':\n answer = firstnumber + secondnumber;\n break;\n case 'E':\n answer = firstnumber - secondnumber;\n break;\n case 'F':\n answer = firstnumber * secondnumber;\n break;\n }\n return answer;\n}\nint getAnswer(string s){\n\treturn getAnsweri(s[1]-48,s[2]-48,s[3]-48);\n}\n\nvoid NewCore::mathCallback(const std_msgs::String::ConstPtr& msg){\n\tROS_INFO(\"ask= %d\",ask);\n\tanswer=getAnswer(msg->data);\n\tif(ask>0){\n\t\tROS_INFO(\"NewCore: mathCallback: \tnewSum: %s\",msg->data.c_str());\n\t\task=0;\n\t\twriteSerial(msg->data);\n\t}\n}\n\nint stringToAscii(string s){\n\tint sum = 0;\n \tfor (unsigned int i = 0; i < 1; i++) {\n \tsum += s[i];\n \t}\n \treturn sum;\n}\n\nvoid NewCore::serialCallback(const std_msgs::String::ConstPtr& msg){\n\tROS_INFO(\"msg-data is %d. Looking for %d\", stringToAscii(msg->data), stringToAscii(\"c\"));\n\tif(msg->data.find('c') != std::string::npos){\n\t\tacceptBall();\n\t\tNewCore::startConvey();\n\t\task=1;\n\t}\n\telse{\n\t\tif('n' == msg->data[0]){\n\t\t\t\n\t\t\task=1;\n\t\t\tNewCore::deleteBall(answer);\n\t\t}\n\t\tROS_INFO(\"NewCore: SerialCallback: message was not c\");\n\t}\n}\n\nvoid NewCore::askMath(){\n\tROS_INFO(\"asking for something\");\n\tstd_msgs::String question;\n\tif (rand() %2){ \n\t\tquestion.data = \"1digitAddition\";\n\t}\n\telse{\n\t\tquestion.data = \"1digitSubstraction\";\n\t}\n\tmathPub.publish(question);\n}\n\nint main(int argc, char **argv){\n\t\n\tros::init(argc, argv, \"newCore\");\n\tNewCore nc;\n\tnc.init();\n\n\tnc.spin();\n}\n<commit_msg>better remove<commit_after>#include \"newCore.h\"\n#include <stdlib.h>\n\nusing namespace std;\nint ask =1; \nint answer=0;\nvoid NewCore::init(){\n\n\tmngrSub = handle.subscribe<std_msgs::String>(\"\/tawi\/core\/launch\", 10, &NewCore::launchCallback, this);\n\tmngrPub = handle.advertise<std_msgs::String>(\"\/tawi\/core\/launch\", 100);\n\n\tmathSub = handle.subscribe<std_msgs::String>(\"\/display\", 10, &NewCore::mathCallback, this);\n\tserSub = handle.subscribe<std_msgs::String>(\"\/tawi\/arduino\/serial\", 100,&NewCore::serialCallback,this);\n\tmathPub = handle.advertise<std_msgs::String>(\"\/questions\", 100);\n\n\tballPub = handle.advertise<std_msgs::Int16>(\"\/tawi\/core\/ballcount\", 100);\n\tnmbrPub = handle.advertise<std_msgs::Int16>(\"\/tawi\/core\/number\", 100);\n}\n\nvoid NewCore::launchCallback(const std_msgs::String::ConstPtr &msg){\n\tif(\"donelaunching\" == msg->data){\n\t\tstopLaunch();\n\t}\n\n\tif(\"doneconveying\" == msg->data){\n\t\tstopConvey();\n\t}\n}\n\nvoid NewCore::stopLaunch(){\n\tballCount = 0;\n}\n\nvoid NewCore::stopConvey(){\n\t\/\/Waittime currently hardcoded in converyorDriver.cpp\n\t\/\/This method is currently not used\n}\n\nvoid NewCore::startLaunch(){\n\tstd_msgs::String launchmsg;\n\tlaunchmsg.data = \"startlaunch\";\n\tmngrPub.publish(launchmsg);\n}\n\nvoid NewCore::startConvey(){\n\tstd_msgs::String conveymsg;\n\tconveymsg.data = \"startconveyor\";\n\tmngrPub.publish(conveymsg);\n}\n\nvoid NewCore::spin(){\n\tros::Rate rate(10);\n\n\twhile(ros::ok()){\n\n\t\tif (ask){\n\t\t\taskMath();}\n\t\tros::spinOnce();\n\t\trate.sleep();\n\t}\n}\n\nvoid NewCore::acceptBall(){\n\tROS_INFO(\"Ball accepted. Publishing to LaunchManager\");\n\tballCount++;\n\tstd_msgs::Int16 balls;\n\tballs.data = ballCount;\n\tballPub.publish(balls);\n}\n\nvoid NewCore::writeSerial(string shit){\n\tROS_INFO(\"NewCore: Writing on serial through system call:%s\", shit.c_str());\n\tstd::stringstream sysCall;\n sysCall<<\"\/home\/ubuntu\/robotica-minor-5\/com\/arduino-serial\/arduino-serial --port=\/dev\/ttyACM0 --send=\\\"\"<<shit<<\"\\\"\"; \n\tstring temp= sysCall.str();\n\tROS_INFO(\"NewCOre: syscall: %s\", temp.c_str());\n\tsystem(temp.c_str());\n\n}\n\nvoid NewCore::deleteBall(const int ballnumber){ \/\/written by bob, muchos bugs\n\tstd_msgs::Int16 number;\n\tnumber.data = ballnumber;\n\tnmbrPub.publish(number);\n}\nint getAnsweri(int firstnumber, int operation , int secondnumber){\n switch(operation){\n case 'D':\n answer = firstnumber + secondnumber;\n break;\n case 'E':\n answer = firstnumber - secondnumber;\n break;\n case 'F':\n answer = firstnumber * secondnumber;\n break;\n }\n return answer;\n}\nint getAnswer(string s){\n\treturn getAnsweri(s[1]-48,s[2]-48,s[3]-48);\n}\n\nvoid NewCore::mathCallback(const std_msgs::String::ConstPtr& msg){\n\tROS_INFO(\"ask= %d\",ask);\n\tanswer=getAnswer(msg->data);\n\tif(ask>0){\n\t\tROS_INFO(\"NewCore: mathCallback: \tnewSum: %s\",msg->data.c_str());\n\t\task=0;\n\t\twriteSerial(msg->data);\n\t}\n}\n\nint stringToAscii(string s){\n\tint sum = 0;\n \tfor (unsigned int i = 0; i < 1; i++) {\n \tsum += s[i];\n \t}\n \treturn sum;\n}\n\nvoid NewCore::serialCallback(const std_msgs::String::ConstPtr& msg){\n\tROS_INFO(\"msg-data is %d. Looking for %d\", stringToAscii(msg->data), stringToAscii(\"c\"));\n\tif(msg->data.find('c') != std::string::npos){\n\t\tacceptBall();\n\t\tNewCore::startConvey();\n\t\task=1;\n\t\tdeleteBall(answer);\n\t}\n\telse{\n\t\tif('n' == msg->data[0]){\n\t\t\t\n\t\t\task=1;\n\t\t\tNewCore::deleteBall(answer);\n\t\t}\n\t\tROS_INFO(\"NewCore: SerialCallback: message was not c\");\n\t}\n}\n\nvoid NewCore::askMath(){\n\tROS_INFO(\"asking for something\");\n\tstd_msgs::String question;\n\tif (rand() %2){ \n\t\tquestion.data = \"1digitAddition\";\n\t}\n\telse{\n\t\tquestion.data = \"1digitSubstraction\";\n\t}\n\tmathPub.publish(question);\n}\n\nint main(int argc, char **argv){\n\t\n\tros::init(argc, argv, \"newCore\");\n\tNewCore nc;\n\tnc.init();\n\n\tnc.spin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n#include \"http\/httpd.hh\"\n#include \"api\/api.hh\"\n#include \"db\/config.hh\"\n#include \"service\/storage_service.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"utils\/runtime.hh\"\n#include \"dns.hh\"\n#include \"log.hh\"\n#include \"debug.hh\"\n#include \"init.hh\"\n#include <cstdio>\n\nnamespace bpo = boost::program_options;\n\nstatic future<>\nread_config(bpo::variables_map& opts, db::config& cfg) {\n if (opts.count(\"options-file\") == 0) {\n return make_ready_future<>();\n }\n return cfg.read_from_file(opts[\"options-file\"].as<sstring>());\n}\n\nstatic void do_help_loggers() {\n print(\"Available loggers:\\n\");\n for (auto&& name : logging::logger_registry().get_all_logger_names()) {\n print(\" %s\\n\", name);\n }\n}\n\nstatic void apply_logger_settings(sstring default_level, db::config::string_map levels,\n bool log_to_stdout, bool log_to_syslog) {\n logging::logger_registry().set_all_loggers_level(boost::lexical_cast<logging::log_level>(std::string(default_level)));\n for (auto&& kv: levels) {\n auto&& k = kv.first;\n auto&& v = kv.second;\n logging::logger_registry().set_logger_level(k, boost::lexical_cast<logging::log_level>(std::string(v)));\n }\n logging::logger::set_stdout_enabled(log_to_stdout);\n logging::logger::set_syslog_enabled(log_to_syslog);\n}\n\nint main(int ac, char** av) {\n runtime::init_uptime();\n std::setvbuf(stdout, nullptr, _IOLBF, 1000);\n app_template app;\n auto opt_add = app.add_options();\n\n auto cfg = make_lw_shared<db::config>();\n bool help_loggers = false;\n cfg->add_options(opt_add)\n (\"api-port\", bpo::value<uint16_t>()->default_value(10000), \"Http Rest API port\")\n (\"api-dir\", bpo::value<sstring>()->default_value(\"swagger-ui\/dist\/\"),\n \"The directory location of the API GUI\")\n \/\/ TODO : default, always read?\n (\"options-file\", bpo::value<sstring>(), \"cassandra.yaml file to read options from\")\n (\"help-loggers\", bpo::bool_switch(&help_loggers), \"print a list of logger names and exit\")\n ;\n\n distributed<database> db;\n debug::db = &db;\n distributed<cql3::query_processor> qp;\n auto& proxy = service::get_storage_proxy();\n api::http_context ctx(db, proxy);\n\n return app.run(ac, av, [&] {\n if (help_loggers) {\n do_help_loggers();\n engine().exit(1);\n return make_ready_future<>();\n }\n auto&& opts = app.configuration();\n\n return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &ctx, &opts]() {\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n dht::set_global_partitioner(cfg->partitioner());\n uint16_t thrift_port = cfg->rpc_port();\n uint16_t cql_port = cfg->native_transport_port();\n uint16_t api_port = opts[\"api-port\"].as<uint16_t>();\n ctx.api_dir = opts[\"api-dir\"].as<sstring>();\n sstring listen_address = cfg->listen_address();\n sstring rpc_address = cfg->rpc_address();\n auto seed_provider= cfg->seed_provider();\n using namespace locator;\n return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then([] {\n engine().at_exit([] { return i_endpoint_snitch::stop_snitch(); });\n }).then([] {\n return service::init_storage_service().then([] {\n engine().at_exit([] { return service::deinit_storage_service(); });\n });\n }).then([&db, cfg] {\n return db.start(std::move(*cfg)).then([&db] {\n engine().at_exit([&db] { return db.stop(); });\n });\n }).then([listen_address, seed_provider] {\n return init_ms_fd_gossiper(listen_address, seed_provider);\n }).then([&db] {\n return streaming::stream_session::init_streaming_service(db);\n }).then([&proxy, &db] {\n return proxy.start(std::ref(db)).then([&proxy] {\n engine().at_exit([&proxy] { return proxy.stop(); });\n });\n }).then([&db, &proxy, &qp] {\n return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {\n engine().at_exit([&qp] { return qp.stop(); });\n });\n }).then([&db] {\n return parallel_for_each(db.local().get_config().data_file_directories(), [] (sstring datadir) {\n return recursive_touch_directory(datadir).then_wrapped([datadir] (future<> f) {\n try {\n f.get();\n } catch (std::system_error& e) {\n fprint(std::cerr, \"Directory \\\"%s\\\" not found. Tried to created it but failed: %s\\n\", datadir, e.what());\n throw;\n }\n });\n });\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.init_system_keyspace();\n });\n }).then([&db, &proxy] {\n return db.invoke_on_all([&proxy] (database& db) {\n return db.load_sstables(proxy);\n });\n }).then([&db, &qp] {\n return db::system_keyspace::setup(db, qp);\n }).then([] {\n auto& ss = service::get_local_storage_service();\n return ss.init_server();\n }).then([rpc_address] {\n return dns::gethostbyname(rpc_address);\n }).then([&db, &proxy, &qp, cql_port, thrift_port] (dns::hostent e) {\n auto rpc_address = e.addresses[0].in.s_addr;\n auto cserver = new distributed<cql_server>;\n cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address] () mutable {\n engine().at_exit([server] {\n return server->stop();\n });\n server->invoke_on_all(&cql_server::listen, ipv4_addr{rpc_address, cql_port});\n }).then([cql_port] {\n std::cout << \"CQL server listening on port \" << cql_port << \" ...\\n\";\n });\n auto tserver = new distributed<thrift_server>;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address] () mutable {\n engine().at_exit([server] {\n return server->stop();\n });\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{rpc_address, thrift_port});\n }).then([thrift_port] {\n std::cout << \"Thrift server listening on port \" << thrift_port << \" ...\\n\";\n });\n }).then([&db, api_port, &ctx]{\n ctx.http_server.start().then([api_port, &ctx] {\n return set_server(ctx);\n }).then([&ctx, api_port] {\n ctx.http_server.listen(api_port);\n }).then([api_port] {\n std::cout << \"Seastar HTTP server listening on port \" << api_port << \" ...\\n\";\n });\n }).or_terminate();\n });\n });\n}\n\nnamespace debug {\n\nseastar::sharded<database>* db;\n\n}\n<commit_msg>main: Introduce api-address option<commit_after>\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n#include \"http\/httpd.hh\"\n#include \"api\/api.hh\"\n#include \"db\/config.hh\"\n#include \"service\/storage_service.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"utils\/runtime.hh\"\n#include \"dns.hh\"\n#include \"log.hh\"\n#include \"debug.hh\"\n#include \"init.hh\"\n#include <cstdio>\n\nnamespace bpo = boost::program_options;\n\nstatic future<>\nread_config(bpo::variables_map& opts, db::config& cfg) {\n if (opts.count(\"options-file\") == 0) {\n return make_ready_future<>();\n }\n return cfg.read_from_file(opts[\"options-file\"].as<sstring>());\n}\n\nstatic void do_help_loggers() {\n print(\"Available loggers:\\n\");\n for (auto&& name : logging::logger_registry().get_all_logger_names()) {\n print(\" %s\\n\", name);\n }\n}\n\nstatic void apply_logger_settings(sstring default_level, db::config::string_map levels,\n bool log_to_stdout, bool log_to_syslog) {\n logging::logger_registry().set_all_loggers_level(boost::lexical_cast<logging::log_level>(std::string(default_level)));\n for (auto&& kv: levels) {\n auto&& k = kv.first;\n auto&& v = kv.second;\n logging::logger_registry().set_logger_level(k, boost::lexical_cast<logging::log_level>(std::string(v)));\n }\n logging::logger::set_stdout_enabled(log_to_stdout);\n logging::logger::set_syslog_enabled(log_to_syslog);\n}\n\nint main(int ac, char** av) {\n runtime::init_uptime();\n std::setvbuf(stdout, nullptr, _IOLBF, 1000);\n app_template app;\n auto opt_add = app.add_options();\n\n auto cfg = make_lw_shared<db::config>();\n bool help_loggers = false;\n cfg->add_options(opt_add)\n (\"api-address\", bpo::value<sstring>(), \"Http Rest API address\")\n (\"api-port\", bpo::value<uint16_t>()->default_value(10000), \"Http Rest API port\")\n (\"api-dir\", bpo::value<sstring>()->default_value(\"swagger-ui\/dist\/\"),\n \"The directory location of the API GUI\")\n \/\/ TODO : default, always read?\n (\"options-file\", bpo::value<sstring>(), \"cassandra.yaml file to read options from\")\n (\"help-loggers\", bpo::bool_switch(&help_loggers), \"print a list of logger names and exit\")\n ;\n\n distributed<database> db;\n debug::db = &db;\n distributed<cql3::query_processor> qp;\n auto& proxy = service::get_storage_proxy();\n api::http_context ctx(db, proxy);\n\n return app.run(ac, av, [&] {\n if (help_loggers) {\n do_help_loggers();\n engine().exit(1);\n return make_ready_future<>();\n }\n auto&& opts = app.configuration();\n\n return read_config(opts, *cfg).then([&cfg, &db, &qp, &proxy, &ctx, &opts]() {\n apply_logger_settings(cfg->default_log_level(), cfg->logger_log_level(),\n cfg->log_to_stdout(), cfg->log_to_syslog());\n dht::set_global_partitioner(cfg->partitioner());\n uint16_t thrift_port = cfg->rpc_port();\n uint16_t cql_port = cfg->native_transport_port();\n uint16_t api_port = opts[\"api-port\"].as<uint16_t>();\n ctx.api_dir = opts[\"api-dir\"].as<sstring>();\n sstring listen_address = cfg->listen_address();\n sstring rpc_address = cfg->rpc_address();\n sstring api_address = opts.count(\"api-address\") ? opts[\"api-address\"].as<sstring>() : rpc_address;\n auto seed_provider= cfg->seed_provider();\n using namespace locator;\n return i_endpoint_snitch::create_snitch(cfg->endpoint_snitch()).then([] {\n engine().at_exit([] { return i_endpoint_snitch::stop_snitch(); });\n }).then([] {\n return service::init_storage_service().then([] {\n engine().at_exit([] { return service::deinit_storage_service(); });\n });\n }).then([&db, cfg] {\n return db.start(std::move(*cfg)).then([&db] {\n engine().at_exit([&db] { return db.stop(); });\n });\n }).then([listen_address, seed_provider] {\n return init_ms_fd_gossiper(listen_address, seed_provider);\n }).then([&db] {\n return streaming::stream_session::init_streaming_service(db);\n }).then([&proxy, &db] {\n return proxy.start(std::ref(db)).then([&proxy] {\n engine().at_exit([&proxy] { return proxy.stop(); });\n });\n }).then([&db, &proxy, &qp] {\n return qp.start(std::ref(proxy), std::ref(db)).then([&qp] {\n engine().at_exit([&qp] { return qp.stop(); });\n });\n }).then([&db] {\n return parallel_for_each(db.local().get_config().data_file_directories(), [] (sstring datadir) {\n return recursive_touch_directory(datadir).then_wrapped([datadir] (future<> f) {\n try {\n f.get();\n } catch (std::system_error& e) {\n fprint(std::cerr, \"Directory \\\"%s\\\" not found. Tried to created it but failed: %s\\n\", datadir, e.what());\n throw;\n }\n });\n });\n }).then([&db] {\n return db.invoke_on_all([] (database& db) {\n return db.init_system_keyspace();\n });\n }).then([&db, &proxy] {\n return db.invoke_on_all([&proxy] (database& db) {\n return db.load_sstables(proxy);\n });\n }).then([&db, &qp] {\n return db::system_keyspace::setup(db, qp);\n }).then([] {\n auto& ss = service::get_local_storage_service();\n return ss.init_server();\n }).then([rpc_address] {\n return dns::gethostbyname(rpc_address);\n }).then([&db, &proxy, &qp, cql_port, thrift_port] (dns::hostent e) {\n auto rpc_address = e.addresses[0].in.s_addr;\n auto cserver = new distributed<cql_server>;\n cserver->start(std::ref(proxy), std::ref(qp)).then([server = std::move(cserver), cql_port, rpc_address] () mutable {\n engine().at_exit([server] {\n return server->stop();\n });\n server->invoke_on_all(&cql_server::listen, ipv4_addr{rpc_address, cql_port});\n }).then([cql_port] {\n std::cout << \"CQL server listening on port \" << cql_port << \" ...\\n\";\n });\n auto tserver = new distributed<thrift_server>;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port, rpc_address] () mutable {\n engine().at_exit([server] {\n return server->stop();\n });\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{rpc_address, thrift_port});\n }).then([thrift_port] {\n std::cout << \"Thrift server listening on port \" << thrift_port << \" ...\\n\";\n });\n }).then([api_address] {\n return dns::gethostbyname(api_address);\n }).then([&db, api_address, api_port, &ctx] (dns::hostent e){\n auto ip = e.addresses[0].in.s_addr;\n ctx.http_server.start().then([api_address, api_port, ip, &ctx] {\n return set_server(ctx);\n }).then([api_address, api_port, ip, &ctx] {\n ctx.http_server.listen(ipv4_addr{ip, api_port});\n }).then([api_address, api_port] {\n print(\"Seastar HTTP server listening on %s:%s ...\\n\", api_address, api_port);\n });\n }).or_terminate();\n });\n });\n}\n\nnamespace debug {\n\nseastar::sharded<database>* db;\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <string.h>\n#include <cstring>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/wait.h>\nusing namespace std;\n\nint main(){\n\n string COLON = \";\";\n string PIPE = \"||\";\n string AND = \"&&\";\n \n char HOSTNAME[128];\n gethostname(HOSTNAME, sizeof HOSTNAME);\n \n while (1){\n string i;\n cout << getlogin() << \"@\" << HOSTNAME << \"$ \";\n getline(cin, i);\n \n string w = \"\";\n vector <string> word;\n vector< vector<string> > comm;\n bool quote = false;\n \n for (unsigned j = 0; j < i.size(); ++j){\n if (j == i.size() - 1){\n if(i.at(j)!='\\\"') w.push_back(i.at(j));\n word.push_back(w);\n comm.push_back(word);\n }\n else{\n if (quote){ \/\/In quotes\n \/\/ if ((i.at(j) == '\\\"' && i.at(j - 1) != '\\\\') || j == i.size() - 1){\n if(i.at(j) == '\\\"' && i.at(j-1) != '\\\\'){\n \/\/ w.push_back(i.at(j));\n word.push_back(w);\n w.clear();\n quote = !quote;\n }\n else{\n w.push_back(i.at(j));\n }\n }\n else{ \/\/Not in quotes\n if (i.at(j) == '\\\"'){\n quote = !quote;\n j++;\n w.push_back(i.at(j));\n }\n else if (i.at(j) == ';'){\n word.push_back(w);\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(COLON);\n comm.push_back(word);\n word.clear();\n w.clear();\n }\n else if ((i.at(j) == '&' && i.at(j + 1) == '&')){\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(AND);\n comm.push_back(word);\n word.clear();\n w.clear();\n j+=1;\n }\n else if ((i.at(j) == '|' && i.at(j + 1) == '|')){\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(PIPE);\n comm.push_back(word);\n word.clear();\n w.clear();\n j+=1;\n }\n else if (i.at(j) == ' '){\n if (!(w.empty())){\n word.push_back(w);\n w.clear();\n }\n }\n else if (i.at(j) == '#'){\n if (!(w.empty())){\n word.push_back(w);\n }\n break;\n }\n else{\n w.push_back(i.at(j));\n }\n }\n }\n }\n \n \/\/ for (unsigned l = 0; l < comm.size(); ++l){\n \/\/ for (unsigned m = 0; m < comm.at(l).size(); ++m){\n \/\/ cout << comm.at(l).at(m) << \" \";\n \/\/ }\n \/\/ cout << endl;\n \/\/ }\n \n bool didItExecute = true;\n bool shouldItExecute = true;\n \n for (unsigned first = 0; first < comm.size(); first++){\n for (unsigned second = 0; second < comm.at(first).size(); second++){\n if (comm.at(first).at(second) == \"exit\"){\n exit(0);\n }\n }\n }\n \n for (unsigned j = 0; j < comm.size(); ++j){\n if (comm.at(j).size() == 1 && comm.at(j).at(0) == \";\"){\n shouldItExecute = true;\n }\n \n else if (comm.at(j).size() == 1 && comm.at(j).at(0) == \"||\"){\n if (didItExecute){\n shouldItExecute = false;\n }\n else{\n shouldItExecute = true;\n }\n }\n \n else if (comm.at(j).size() == 1 && comm.at(j).at(0) == \"&&\"){\n if (didItExecute){\n shouldItExecute = true;\n }\n else{\n shouldItExecute = false;\n }\n }\n \n else{\n unsigned size = comm.at(j).size() + 1;\n char**args = new char*[size];\n \n for (unsigned i = 0; i < size - 1; ++i){\n const char *mystr = comm.at(j).at(i).c_str();\n args[i] = const_cast<char *> (&mystr[0]);\n }\n \n args[size - 1] = 0;\n \n if (shouldItExecute){\n int status;\n pid_t c_pid, pid; \/\/ Where c_pid is child\n c_pid = fork();\n if (c_pid < 0)\n {\n perror(\"fork failed\");\n exit(1);\n }\n else if (c_pid == 0) \/\/ Child process\n {\n execvp(args[0], args);\n perror(\"-bash\");\n exit(1);\n }\n else if (c_pid > 0)\n {\n if ( (pid = wait(&status)) < 0)\n {\n perror(\"wait\");\n exit(1);\n }\n \n if (WEXITSTATUS(status) != 0){\n didItExecute = false;\n }\n else{\n didItExecute = true;\n }\n delete [] args;\n } \n }\n }\n }\n }\n return 0;\n}\n<commit_msg>added comments<commit_after>#include <iostream>\n#include <vector>\n#include <string.h>\n#include <cstring>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/wait.h>\nusing namespace std;\n\nint main(){\n\n string COLON = \";\";\n string PIPE = \"||\";\n string AND = \"&&\";\n \n char HOSTNAME[128];\n gethostname(HOSTNAME, sizeof HOSTNAME);\n \n \/\/Loop will only break if the user enters 'exit' in the inputted command.\n while (1){\n string i;\n cout << getlogin() << \"@\" << HOSTNAME << \"$ \";\n getline(cin, i);\n string w = \"\";\n vector <string> word; \/\/This will an individual command after parsing. \n vector< vector<string> > comm; \/\/After parsing this will hold commands in the order they were inputed.\n bool quote = false; \n \n \/* This for loop will iterate through the inputed string and separate commands\n by the connectors. When a connector is found vector word which holds a \n single command will be pushed back into vector comm which will eventually\n hold all the concatenated commands. After word is pushed back, the \n appropriate connector will be pushed into comm as well.\n *\/\n for (unsigned j = 0; j < i.size(); ++j){\n \/\/If the end is reached pushes data into comm.\n if (j == i.size() - 1){\n if(i.at(j)!='\\\"') w.push_back(i.at(j));\n word.push_back(w);\n comm.push_back(word);\n }\n else{\n if (quote){ \/\/In quotes\n \/\/ if ((i.at(j) == '\\\"' && i.at(j - 1) != '\\\\') || j == i.size() - 1){\n if(i.at(j) == '\\\"' && i.at(j-1) != '\\\\'){\n \/\/ w.push_back(i.at(j));\n word.push_back(w);\n w.clear();\n quote = !quote;\n }\n else{\n w.push_back(i.at(j));\n }\n }\n else{ \/\/Not in quotes\n if (i.at(j) == '\\\"'){\n quote = !quote;\n j++;\n w.push_back(i.at(j));\n }\n \/\/If semicolon is found push created vector into com.\n else if (i.at(j) == ';'){\n word.push_back(w);\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(COLON);\n comm.push_back(word);\n word.clear();\n w.clear();\n }\n \/\/If && is found push created vector into com.\n else if ((i.at(j) == '&' && i.at(j + 1) == '&')){\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(AND);\n comm.push_back(word);\n word.clear();\n w.clear();\n j+=1;\n }\n \/\/If || is found push created vector into com.\n else if ((i.at(j) == '|' && i.at(j + 1) == '|')){\n comm.push_back(word);\n word.clear();\n w.clear();\n word.push_back(PIPE);\n comm.push_back(word);\n word.clear();\n w.clear();\n j+=1;\n }\n \/\/If a space is found push created word into word.\n else if (i.at(j) == ' '){\n if (!(w.empty())){\n word.push_back(w);\n w.clear();\n }\n }\n \/\/If a # is found outside of quotes, stops parsing process and\n \/\/begins execution.\n else if (i.at(j) == '#'){\n if (!(w.empty())){\n word.push_back(w);\n }\n break;\n }\n else{\n w.push_back(i.at(j));\n }\n }\n }\n }\n \n bool didItExecute = true; \/\/Checks if the current command executed or not.\n bool shouldItExecute = true; \/\/Determines if the current command should execute or not.\n \n \/\/Commands are executed here.\n for (unsigned j = 0; j < comm.size(); ++j){\n \/\/If command is exit, execution is stopped and outer while loop restarts.\n if (comm.at(j).size() == 1 && comm.at(j).at(0) == \"exit\"){\n exit(0);\n }\n \/\/If a semicolon is found, automatically set shouldItExecute to true\n \/\/so next command will execute.\n else if (comm.at(j).size() == 1 && comm.at(j).at(0) == \";\"){\n shouldItExecute = true;\n }\n \/\/If || is found checks didItExecute to see if previous command executed.\n \/\/If it did it will set shouldItExecute to false, true otherwise.\n else if (comm.at(j).size() == 1 && comm.at(j).at(0) == \"||\"){\n if (didItExecute){\n shouldItExecute = false;\n }\n else{\n shouldItExecute = true;\n }\n }\n \/\/If && is found checks didItExecute to see if previous command executed.\n \/\/If it did it will set shouldItExecute to true, false otherwise.\n else if (comm.at(j).size() == 1 && comm.at(j).at(0) == \"&&\"){\n if (didItExecute){\n shouldItExecute = true;\n }\n else{\n shouldItExecute = false;\n }\n }\n else{\n unsigned size = comm.at(j).size() + 1;\n char**args = new char*[size]; \/\/Creates args of type char** which will be inputed to execvp.\n args[size - 1] = 0;\n \/\/stores each command in comm into char to beable to be executed.\n for (unsigned i = 0; i < size - 1; ++i){\n const char *mystr = comm.at(j).at(i).c_str();\n args[i] = const_cast<char *> (&mystr[0]);\n }\n \/\/If shouldItExecute is true, which would be set by the connectors\n \/\/above, then the current command is executed.\n if (shouldItExecute){\n int status;\n pid_t pid;\n pid = fork(); \/\/Forks a child process.\n if (pid < 0) \/\/Fork failed, exits program.\n {\n perror(\"Fork Failed\");\n exit(1);\n }\n else if (pid == 0) \/\/Fork is successful.\n {\n if (execvp(args[0], args) < 0){ \/\/executes the command.\n perror(\"-bash\"); \/\/Execution failed if it takes this branch.\n didItExecute = false; \/\/Update execution information for following commands.\n }\n else{\n didItExecute = true; \/\/Execution successful. Updates execution info.\n }\n }\n else\n { \/\/Makes the parent wait until child process completes.\n while ( wait(&status) != pid)\n {\n perror(\"wait\");\n }\n didItExecute = true;\n delete [] args;\n } \n }\n }\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"Feeder.h\"\n#include \"Environment.h\"\n#include \"Script.h\"\n#include <fstream>\n#include <unistd.h>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <signal.h>\n#include <string.h>\nusing namespace std;\n\nint scriptPos(int argc, char const* argv[]);\nvoid parseErrorMsg(Element *e);\nvoid execErrorMsg(Element *e);\nvoid setFlags(int argc, char const* argv[],Environment *e);\n\nstatic void sig_int(int sig)\n{\n\tElement::m_signal = sig;\n}\n\nint main(int argc, char const* argv[])\n{\n\tif(argc <= 1)\n\t\texit(0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ set signals\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstruct sigaction sig;\n\tmemset(&sig,'\\0',sizeof(sig));\n\n\tsig.sa_handler = sig_int;\n\tsigaction(SIGINT,&sig,NULL);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ initialization of top level objects \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tint script_pos = scriptPos(argc,argv);\n\tifstream ifs(argv[script_pos]);\n\tFeeder feeder(&ifs);\n\tEnvironment env(argc,argv,script_pos);\n\n\t\/\/ set tmpdir\n\tstring tmp_k = \"tmpdir\";\n\tstring tmp_v = \"\/tmp\/\";\n\tenv.setImportPath(&tmp_k,&tmp_v);\n\tScript s(&feeder,&env);\n\n\tsetFlags(argc,argv,&env);\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ parse\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ttry{\n\t\ts.parse();\n\t}\n\tcatch(Element *e){\n\t\tparseErrorMsg(e);\n\t\tenv.removeFiles();\n\t\texit(e->getExitStatus());\n\t}\n\tcatch(...){\n\t\tcerr << \"\\nParse error\" << endl;\n\t\tcerr << \"unknown error\" << endl;\n\t\tenv.removeFiles();\n\t\texit(1);\n\t}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ exec\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ttry{\n\t\tint status = s.exec();\n\t\tenv.removeFiles();\n\n\t\tif(status == 0)\n\t\t\texit(0);\n\t}\n\tcatch(Element *e){\n\t\texecErrorMsg(e);\n\t\tenv.removeFiles();\n\t\tint es = e->getExitStatus();\n\t\tif(es == 127)\n\t\t\t_exit(es);\n\t\telse\n\t\t\texit(es);\n\t}\n\tcatch(...){\n\t\tcerr << \"\\nExecution error\" << endl;\n\t\tcerr << \"unknown error\" << endl;\n\t\tenv.removeFiles();\n\t\texit(1);\n\t}\n\n\tcerr << \"unknown error (uncatched)\" << endl;\n\tenv.removeFiles();\n\texit(1);\n}\n\nint scriptPos(int argc, char const* argv[])\n{\n\tstring com = string(argv[0]);\n\tbool shebang = com.substr(com.find_last_of('\/') + 1) != \"glue\";\n\n\tif(shebang)\n\t\treturn 0;\n\n\tint i=1;\n\tfor(;i<argc;i++){\n\t\tif(argv[i][0] != '-')\n\t\t\tbreak;\n\t}\n\treturn i;\n}\n\nvoid parseErrorMsg(Element *e)\n{\n\tcerr << \"\\nParse error at \" ;\n\tcerr << e->pos() << endl;\n\te->printErrorPart();\n\tcerr << \"\\n\\t\" << e->m_error_msg << endl;\n\tcerr << \"\\t\";\n\n\tcerr << '\\n';\n\tcerr << \"\\tprocess_level \" << e->getLevel() << endl;\n\tcerr << \"\\texit_status \" << e->getExitStatus() << endl;\n\tcerr << \"\\tpid \" << getpid() << '\\n' << endl;\n}\n\nvoid execErrorMsg(Element *e)\n{\n\tcerr << \"\\nExecution error at \" ;\n\tcerr << e->pos() << endl;\n\te->printErrorPart();\n\tcerr << \"\\n\\t\" << e->m_error_msg << endl;\n\tcerr << \"\\t\\n\";\n\tcerr << \"\\tprocess_level \" << e->getLevel() << endl;\n\tcerr << \"\\texit_status \" << e->getExitStatus() << endl;\n\tcerr << \"\\tpid \" << getpid() << '\\n' << endl;\n}\n\nvoid setFlags(int argc, char const* argv[],Environment *e)\n{\n\tint result = 0;\n\twhile((result = getopt(argc,(char**)argv,\"v\"))!=-1){\n\t\tswitch(result){\n\t\tcase 'v':\n\t\t\te->m_v_opt = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n}\n<commit_msg>Add usage<commit_after>#include <iostream>\n#include \"Feeder.h\"\n#include \"Environment.h\"\n#include \"Script.h\"\n#include <fstream>\n#include <unistd.h>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <signal.h>\n#include <string.h>\n#include <getopt.h>\n#include <unistd.h>\nusing namespace std;\n\nint scriptPos(int argc, char const* argv[]);\nvoid parseErrorMsg(Element *e);\nvoid execErrorMsg(Element *e);\nbool setFlags(int argc, char const* argv[],Environment *e);\n\nstatic void sig_int(int sig)\n{\n\tElement::m_signal = sig;\n}\n\nint main(int argc, char const* argv[])\n{\n\tif(argc <= 1)\n\t\texit(0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ set signals\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstruct sigaction sig;\n\tmemset(&sig,'\\0',sizeof(sig));\n\n\tsig.sa_handler = sig_int;\n\tsigaction(SIGINT,&sig,NULL);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ initialization of top level objects \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tint script_pos = scriptPos(argc,argv);\n\n\tifstream ifs(argv[script_pos]);\n\tFeeder feeder(&ifs);\n\tEnvironment env(argc,argv,script_pos);\n\n\tif(!setFlags(argc,argv,&env))\n\t\texit(1);\n\n\t\/\/ set tmpdir\n\tstring tmp_k = \"tmpdir\";\n\tstring tmp_v = \"\/tmp\/\";\n\tenv.setImportPath(&tmp_k,&tmp_v);\n\tScript s(&feeder,&env);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ parse\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ttry{\n\t\ts.parse();\n\t}\n\tcatch(Element *e){\n\t\tparseErrorMsg(e);\n\t\tenv.removeFiles();\n\t\texit(e->getExitStatus());\n\t}\n\tcatch(...){\n\t\tcerr << \"\\nParse error\" << endl;\n\t\tcerr << \"unknown error\" << endl;\n\t\tenv.removeFiles();\n\t\texit(1);\n\t}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ exec\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ttry{\n\t\tint status = s.exec();\n\t\tenv.removeFiles();\n\n\t\tif(status == 0)\n\t\t\texit(0);\n\t}\n\tcatch(Element *e){\n\t\texecErrorMsg(e);\n\t\tenv.removeFiles();\n\t\tint es = e->getExitStatus();\n\t\tif(es == 127)\n\t\t\t_exit(es);\n\t\telse\n\t\t\texit(es);\n\t}\n\tcatch(...){\n\t\tcerr << \"\\nExecution error\" << endl;\n\t\tcerr << \"unknown error\" << endl;\n\t\tenv.removeFiles();\n\t\texit(1);\n\t}\n\n\tcerr << \"unknown error (uncatched)\" << endl;\n\tenv.removeFiles();\n\texit(1);\n}\n\nint scriptPos(int argc, char const* argv[])\n{\n\tstring com = string(argv[0]);\n\tbool shebang = com.substr(com.find_last_of('\/') + 1) != \"glue\";\n\n\tif(shebang)\n\t\treturn 0;\n\n\tint i=1;\n\tfor(;i<argc;i++){\n\t\tif(argv[i][0] != '-')\n\t\t\tbreak;\n\t}\n\treturn i;\n}\n\nvoid parseErrorMsg(Element *e)\n{\n\tcerr << \"\\nParse error at \" ;\n\tcerr << e->pos() << endl;\n\te->printErrorPart();\n\tcerr << \"\\n\\t\" << e->m_error_msg << endl;\n\tcerr << \"\\t\";\n\n\tcerr << '\\n';\n\tcerr << \"\\tprocess_level \" << e->getLevel() << endl;\n\tcerr << \"\\texit_status \" << e->getExitStatus() << endl;\n\tcerr << \"\\tpid \" << getpid() << '\\n' << endl;\n}\n\nvoid execErrorMsg(Element *e)\n{\n\tcerr << \"\\nExecution error at \" ;\n\tcerr << e->pos() << endl;\n\te->printErrorPart();\n\tcerr << \"\\n\\t\" << e->m_error_msg << endl;\n\tcerr << \"\\t\\n\";\n\tcerr << \"\\tprocess_level \" << e->getLevel() << endl;\n\tcerr << \"\\texit_status \" << e->getExitStatus() << endl;\n\tcerr << \"\\tpid \" << getpid() << '\\n' << endl;\n}\n\nvoid usage(void)\n{\n\tcerr << \"GlueLang (master branch)\" << endl;\n\tcerr << \"Usage: glue [OPTION] [FILE]\" << endl;\n\tcerr << endl;\n\tcerr << \"Copyright (C) 2015 Ryuichi Ueda\" << endl;\n\tcerr << \"GlueLang repo. <https:\/\/github.com\/ryuichiueda\/GlueLang>\" << endl;\n}\n\nbool setFlags(int argc, char const* argv[],Environment *e)\n{\n\tstruct option long_opts[] = {\n\t\t{\"help\",0,NULL,'h'},\n\t\t{\"usage\",0,NULL,'h'},\n\t\t{\"verbose\",0,NULL,'v'},\n\t\t{0,0,0,0}\n\t};\n\n\tint opt = 0;\n\tint idx = 0;\n\twhile((opt = getopt_long(argc,(char *const *)argv,\"hv\",long_opts,&idx)) != -1){\n\t\tswitch (opt){\n\t\tcase 'h':\n\t\t\tusage();\n\t\t\treturn false;\n\t\tcase 'v':\n\t\t\te->m_v_opt = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * wheel.cpp\n *\n * Created on: Sep 2, 2014\n * Author: posborne\n *\/\n\n#include <functional>\n#include \"wheel.h\"\n\n\/\/ TODO: only necessary as mbed does not allow for passing a data pointer\n\/\/ along with interrupt registrations. Obviously, this breaks if we ever\n\/\/ have more than one wheel sensor created.\nstatic BicycleWheel* g_wheel; \/* global wheel reference *\/\n\n\/*\n * ISR called when we receive an rising edge on the reed sensor\n *\/\nstatic void reedSwitchRisingInterrupt()\n{\n if (g_wheel != NULL) {\n g_wheel->onRisingInterrupt();\n }\n}\n\n\/*\n * ISR called when we receive an falling edge on the reed sensor\n *\/\nstatic void reedSwitchFallingInterrupt()\n{\n if (g_wheel != NULL) {\n g_wheel->onFallingInterrupt();\n }\n}\n\n\nBicycleWheel::BicycleWheel(PinName reedSwitchPin, DebugSerialPort& debugSerialPort, MulticolorLED& debugLED) :\n m_reedSwitchPin(reedSwitchPin),\n m_reedSwitchGPIO(m_reedSwitchPin),\n m_reedSwitchInterrupt(m_reedSwitchPin),\n m_debugSerialPort(debugSerialPort),\n m_led(debugLED)\n{\n g_wheel = this;\n}\n\nBicycleWheel::~BicycleWheel()\n{\n g_wheel = NULL;\n}\n\nvoid BicycleWheel::init()\n{\n m_led.show(0.0, 0.0, 0.0);\n m_reedSwitchInterrupt.rise(reedSwitchRisingInterrupt);\n m_reedSwitchInterrupt.fall(reedSwitchFallingInterrupt);\n}\n\nvoid BicycleWheel::onFallingInterrupt()\n{\n m_debugSerialPort.writeln(\"Reed Switch Rising Edge\");\n m_led.show(0, 0, 0.05); \/\/ subtle blue\n}\n\nvoid BicycleWheel::onRisingInterrupt()\n{\n m_debugSerialPort.writeln(\"Reed Switch Falling Edge\");\n m_led.show(0.01, 0.05, 0.0); \/\/ subtle yellow\n}\n<commit_msg>transistor: temporary hack using transistor as switch to emulate reed switch<commit_after>\/*\n * wheel.cpp\n *\n * Created on: Sep 2, 2014\n * Author: posborne\n *\/\n\n#include <functional>\n#include \"wheel.h\"\n\nstatic DigitalOut tpin(PTD4);\n\n\/\/ TODO: only necessary as mbed does not allow for passing a data pointer\n\/\/ along with interrupt registrations. Obviously, this breaks if we ever\n\/\/ have more than one wheel sensor created.\nstatic BicycleWheel* g_wheel; \/* global wheel reference *\/\n\n\/*\n * ISR called when we receive an rising edge on the reed sensor\n *\/\nstatic void reedSwitchRisingInterrupt()\n{\n if (g_wheel != NULL) {\n g_wheel->onRisingInterrupt();\n }\n}\n\n\/*\n * ISR called when we receive an falling edge on the reed sensor\n *\/\nstatic void reedSwitchFallingInterrupt()\n{\n if (g_wheel != NULL) {\n g_wheel->onFallingInterrupt();\n }\n}\n\n\nBicycleWheel::BicycleWheel(PinName reedSwitchPin, DebugSerialPort& debugSerialPort, MulticolorLED& debugLED) :\n m_reedSwitchPin(reedSwitchPin),\n m_reedSwitchGPIO(m_reedSwitchPin),\n m_reedSwitchInterrupt(m_reedSwitchPin),\n m_debugSerialPort(debugSerialPort),\n m_led(debugLED)\n{\n g_wheel = this;\n}\n\nBicycleWheel::~BicycleWheel()\n{\n g_wheel = NULL;\n}\n\nvoid BicycleWheel::init()\n{\n m_led.show(0.0, 0.0, 0.0);\n m_reedSwitchInterrupt.rise(reedSwitchRisingInterrupt);\n m_reedSwitchInterrupt.fall(reedSwitchFallingInterrupt);\n}\n\nvoid BicycleWheel::onFallingInterrupt()\n{\n tpin = 0;\n m_debugSerialPort.writeln(\"Reed Switch Rising Edge\");\n m_led.show(0, 0, 0.05); \/\/ subtle blue\n}\n\nvoid BicycleWheel::onRisingInterrupt()\n{\n tpin = 1;\n m_debugSerialPort.writeln(\"Reed Switch Falling Edge\");\n m_led.show(0.01, 0.05, 0.0); \/\/ subtle yellow\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <experimental\/string_view>\n#include <unordered_map>\n#include <vector>\n\n#include <fcntl.h>\n#include <netdb.h>\n#include <netinet\/tcp.h>\n\n#include <sys\/stat.h>\n#include <unistd.h>\n\n#include \"core\/yta_event_loop.h\"\n#include \"http\/yta_http.hpp\"\n\n#include \"args.h\"\n#include \"picohttpparser\/picohttpparser.h\"\n\nconst std::size_t MAX_URL_SIXE = 512;\nconst std::size_t MAX_HEADERS = 20;\nconst std::size_t MAX_BUFFER_SIZE = 1024;\n\ntypedef unsigned char byte;\n\nstruct parser_data {\n const char* method = nullptr;\n std::size_t method_len = 0;\n const char* path = nullptr;\n std::size_t path_len = 0;\n int pret = 0;\n int minor_version = 0;\n std::array<phr_header, MAX_HEADERS> headers;\n std::size_t num_headers = MAX_HEADERS;\n};\n\nstruct user_data {\n std::size_t counter;\n\n std::array<char, MAX_BUFFER_SIZE> buf;\n std::array<char, MAX_BUFFER_SIZE> response_buf;\n\n bool finalized;\n\n std::size_t response_size;\n bool content;\n std::experimental::string_view extension;\n\n int file_fd;\n std::size_t file_size;\n std::size_t offset = 0;\n\n parser_data parser;\n\n struct stat file_stat;\n};\n\nvoid return_400(user_data* udata) {\n auto ret = yta::http::serve_400(udata->response_buf.data());\n udata->response_size = ret - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n}\n\nvoid return_404(user_data* udata) {\n auto ret = yta::http::serve_404(udata->response_buf.data());\n udata->response_size = ret - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n}\n\nstd::unordered_map<std::experimental::string_view, std::experimental::string_view>\n mime_types{ { \".html\", \"text\/html\" },\n { \".css\", \"text\/css\" },\n { \".png\", \"image\/png\" },\n { \".jpg\", \"image\/jpeg\" },\n { \".jpeg\", \"image\/jpeg\" },\n { \".txt\", \"text\/plain\" },\n { \".js\", \"application\/x-javascript\" },\n { \".json\", \"application\/json\" },\n { \".pdf\", \"application\/pdf\" },\n { \".zip\", \"application\/zip\" },\n { \".woff\", \"application\/font-woff\" },\n { \".woff2\", \"application\/font-woff2\" },\n { \".opus\", \"audio\/opus\" },\n { \".mp4\", \"video\/mp4\" },\n { \".mpeg\", \"video\/mpeg\" },\n { \".mpg\", \"video\/mpeg\" },\n { \".mp3\", \"audio\/mpeg\" } };\n\nint parse_url(yta_ctx* ctx, const char* path, size_t length) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n \/\/ parse query string\n auto pos = std::find(path, path + length, '?');\n if (pos != path + length) {\n length = pos - path;\n }\n\n \/\/ clean path buffer is MAX_URL_SICE\n \/\/ leave space for appended index.html\n if ((length > (MAX_URL_SIXE - 20)) || (length == 0)) {\n return_404(udata);\n return 0;\n }\n\n char normalized_path[MAX_URL_SIXE] = { 0 };\n \/\/ prepend . for current directory\n normalized_path[0] = '.';\n std::size_t new_length = 1;\n\n \/\/ clean path\n new_length += yta::http::clean_path(path, length, normalized_path + 1);\n\n \/\/ clean_path removes trailing slash except for root;\n \/\/ put the trailing slash back if necessary.\n if (path[length - 1] == '\/' && new_length != 2) {\n normalized_path[new_length] = '\/';\n ++new_length;\n }\n\n \/\/ append index.html to urls with trailing slashes\n if (normalized_path[new_length - 1] == '\/') {\n const char index_html[] = \"index.html\";\n std::copy(std::begin(index_html), std::end(index_html),\n normalized_path + new_length);\n new_length += 10;\n }\n\n int ffd = open(normalized_path, O_RDONLY);\n\n if (ffd == -1) {\n return_404(udata);\n return 0;\n }\n\n struct stat file_stat;\n int status = fstat(ffd, &file_stat);\n\n if (status != 0 || !S_ISREG(file_stat.st_mode)) {\n return_404(udata);\n close(ffd);\n return 0;\n }\n\n std::experimental::string_view path_view(normalized_path, new_length);\n auto filetype_begin = path_view.rfind('.');\n auto file_begin = path_view.rfind('\/');\n\n \/\/ we always find . at the beginning because of .\/FILENAME\n if (file_begin < filetype_begin) {\n auto it = mime_types.find(path_view.substr(filetype_begin));\n if (it != mime_types.end()) {\n udata->extension = it->second;\n } else {\n udata->extension = { \"text\/plain\" };\n }\n } else {\n udata->extension = { \"text\/plain\" };\n }\n\n udata->file_fd = ffd;\n udata->file_size = file_stat.st_size;\n udata->file_stat = file_stat;\n\n return 0;\n}\n\ntypedef bool (*header_handler)(yta_ctx*, std::experimental::string_view);\n\nbool handle_if_modified_since(yta_ctx* ctx, std::experimental::string_view value) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n tm stamp;\n if (strptime(value.data(), yta::http::http_time_format(), &stamp) == NULL) {\n auto end = yta::http::serve_400(udata->response_buf.data());\n udata->response_size = end - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n return true;\n }\n time_t time = timegm(&stamp);\n\n \/\/ not modified\n if (time >= udata->file_stat.st_mtime) {\n auto end = yta::http::serve_304(udata->response_buf.data());\n udata->response_size = end - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n return true;\n }\n\n return false;\n}\n\nbool handle_range(yta_ctx* ctx, std::experimental::string_view value) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n \/\/ 7 bytes=X-\n if (value.size() < 8) {\n return_400(udata);\n return true;\n }\n\n auto iter = value.begin();\n\n if (!std::equal(iter, iter + 6, \"bytes=\")) {\n return_400(udata);\n return true;\n }\n\n std::advance(iter, 6);\n\n auto sep = std::find(iter, value.end(), '-');\n\n if (sep == value.end()) {\n return_400(udata);\n return true;\n }\n\n \/\/ Range: bytes=-123\n if (sep == iter) {\n \/\/ this should be supported by rfc\n return_400(udata);\n return true;\n }\n\n \/\/ TODO: think of something smarter to not create temp std::string\n \/\/ boost::lexical_cast would work\n auto val = std::string(iter, sep);\n int start_value = std::stoi(val);\n int end_value = 0;\n\n if (std::next(sep, 1) == value.end()) { \/\/ Range: bytes=123-\n end_value = udata->file_stat.st_size - 1;\n } else { \/\/ Range: bytes=123-200\n auto val = std::string(sep + 1, value.end());\n end_value = std::stoi(val);\n }\n\n \/\/ sanity checks\n if (end_value <= start_value) {\n end_value = udata->file_stat.st_size - 1;\n }\n\n if (start_value < 0) {\n start_value = 0;\n }\n\n if (end_value >= udata->file_stat.st_size) {\n end_value = udata->file_stat.st_size - 1;\n }\n\n udata->file_size = end_value - start_value + 1;\n udata->offset = start_value;\n\n auto end = yta::http::serve_206(udata->response_buf.data(), udata->file_size,\n &udata->file_stat.st_mtime, start_value, end_value,\n udata->file_stat.st_size);\n udata->response_size = end - udata->response_buf.data();\n udata->content = true;\n udata->finalized = true;\n\n return true;\n}\n\nstd::unordered_map<std::experimental::string_view, header_handler> header_callbacks{\n { \"If-Modified-Since\", handle_if_modified_since }, { \"Range\", handle_range }\n};\n\nint parse_headers(yta_ctx* ctx) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n for (std::size_t i = 0; (i < udata->parser.num_headers) && !udata->finalized; ++i) {\n std::experimental::string_view header(udata->parser.headers[i].name,\n udata->parser.headers[i].name_len);\n auto it = header_callbacks.find(header);\n if (it != header_callbacks.end()) {\n std::experimental::string_view value(udata->parser.headers[i].value,\n udata->parser.headers[i].value_len);\n auto done = it->second(ctx, value);\n if (done) {\n return 0;\n }\n }\n }\n\n if (!udata->finalized) {\n auto end = yta::http::serve_200(udata->response_buf.data(), udata->file_size,\n &udata->file_stat.st_mtime, udata->extension);\n udata->response_size = end - udata->response_buf.data();\n udata->content = true;\n udata->finalized = true;\n }\n return 0;\n}\n\nvoid accept_logic(yta_ctx* ctx, user_data* udata);\n\nyta_callback_status http_finish_callback(yta_ctx* ctx, void*, size_t) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n if (udata->file_fd != 0) {\n close(udata->file_fd);\n udata->file_fd = 0;\n }\n\n \/\/ uncork\n int enable = 0;\n if (setsockopt(ctx->fd, IPPROTO_TCP, TCP_CORK, &enable, sizeof(enable)) < 0) {\n fprintf(stderr, \"error setting TCP_CORK\");\n exit(1);\n }\n\n accept_logic(ctx, udata);\n return YTA_OK;\n}\n\nyta_callback_status write_header_callback(yta_ctx* ctx, void*, size_t) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n if (udata->content) {\n yta_async_sendfile(ctx, http_finish_callback, udata->file_fd, udata->file_size,\n udata->offset);\n return YTA_OK;\n } else {\n return http_finish_callback(ctx, NULL, 0);\n }\n}\n\nyta_callback_status read_callback_http(yta_ctx* ctx, void* buf, size_t read) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n std::size_t prev_count = udata->counter;\n udata->counter += read;\n\n int parsed = phr_parse_request(\n udata->buf.data(), udata->counter, &udata->parser.method,\n &udata->parser.method_len, &udata->parser.path, &udata->parser.path_len,\n &udata->parser.minor_version, udata->parser.headers.data(),\n &udata->parser.num_headers, prev_count);\n\n if (parsed == -1) {\n return_400(udata);\n } else if (parsed > 0) {\n parse_url(ctx, udata->parser.path, udata->parser.path_len);\n parse_headers(ctx);\n }\n\n if (udata->finalized) {\n \/\/ cork\n int enable = 1;\n if (setsockopt(ctx->fd, IPPROTO_TCP, TCP_CORK, &enable, sizeof(enable)) < 0) {\n fprintf(stderr, \"error setting TCP_CORK\");\n exit(1);\n }\n\n yta_async_write(ctx, write_header_callback, udata->response_buf.data(),\n udata->response_size);\n return YTA_OK;\n }\n\n if (udata->counter == MAX_BUFFER_SIZE) {\n return http_finish_callback(ctx, NULL, 0);\n }\n\n yta_async_read(ctx, read_callback_http, (char*)buf + read,\n MAX_BUFFER_SIZE - udata->counter);\n return YTA_OK;\n}\n\nyta_callback_status http_cleanup(yta_ctx* ctx) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n if (udata->file_fd != 0) {\n close(udata->file_fd);\n udata->file_fd = 0;\n }\n\n delete udata;\n\n return YTA_EXIT;\n}\n\nyta_callback_status timer_callback(yta_ctx* \/* ctx *\/) {\n printf(\"Force closing http connection\\n\");\n return YTA_EXIT;\n}\n\nvoid accept_logic(yta_ctx* ctx, user_data* udata) {\n udata->parser = parser_data{};\n udata->counter = 0;\n udata->finalized = false;\n udata->file_fd = 0;\n yta_async_read(ctx, read_callback_http, udata->buf.data(), MAX_BUFFER_SIZE);\n}\n\nyta_callback_status accept_callback_http(yta_ctx* ctx) {\n user_data* udata = new user_data;\n if (udata == nullptr) {\n return YTA_EXIT;\n }\n ctx->user_data = udata;\n yta_set_close_callback(ctx, http_cleanup);\n yta_async_timer(ctx, timer_callback, 300, 0);\n accept_logic(ctx, udata);\n return YTA_OK;\n}\n\nint main(int argc, char** argv) {\n auto opts = get_program_opts(argc, argv);\n\n yta_run(argv, opts.host.c_str(), opts.port.c_str(), opts.pid_file.c_str(),\n opts.daemonize, opts.workers, accept_callback_http);\n\n return 0;\n}\n<commit_msg>support svg content type<commit_after>#include <algorithm>\n#include <experimental\/string_view>\n#include <unordered_map>\n#include <vector>\n\n#include <fcntl.h>\n#include <netdb.h>\n#include <netinet\/tcp.h>\n\n#include <sys\/stat.h>\n#include <unistd.h>\n\n#include \"core\/yta_event_loop.h\"\n#include \"http\/yta_http.hpp\"\n\n#include \"args.h\"\n#include \"picohttpparser\/picohttpparser.h\"\n\nconst std::size_t MAX_URL_SIXE = 512;\nconst std::size_t MAX_HEADERS = 20;\nconst std::size_t MAX_BUFFER_SIZE = 1024;\n\ntypedef unsigned char byte;\n\nstruct parser_data {\n const char* method = nullptr;\n std::size_t method_len = 0;\n const char* path = nullptr;\n std::size_t path_len = 0;\n int pret = 0;\n int minor_version = 0;\n std::array<phr_header, MAX_HEADERS> headers;\n std::size_t num_headers = MAX_HEADERS;\n};\n\nstruct user_data {\n std::size_t counter;\n\n std::array<char, MAX_BUFFER_SIZE> buf;\n std::array<char, MAX_BUFFER_SIZE> response_buf;\n\n bool finalized;\n\n std::size_t response_size;\n bool content;\n std::experimental::string_view extension;\n\n int file_fd;\n std::size_t file_size;\n std::size_t offset = 0;\n\n parser_data parser;\n\n struct stat file_stat;\n};\n\nvoid return_400(user_data* udata) {\n auto ret = yta::http::serve_400(udata->response_buf.data());\n udata->response_size = ret - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n}\n\nvoid return_404(user_data* udata) {\n auto ret = yta::http::serve_404(udata->response_buf.data());\n udata->response_size = ret - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n}\n\nstd::unordered_map<std::experimental::string_view, std::experimental::string_view>\n mime_types{ { \".html\", \"text\/html\" },\n { \".css\", \"text\/css\" },\n { \".png\", \"image\/png\" },\n { \".jpg\", \"image\/jpeg\" },\n { \".jpeg\", \"image\/jpeg\" },\n { \".svg\", \"image\/svg+xml\" },\n { \".txt\", \"text\/plain\" },\n { \".js\", \"application\/x-javascript\" },\n { \".json\", \"application\/json\" },\n { \".pdf\", \"application\/pdf\" },\n { \".zip\", \"application\/zip\" },\n { \".woff\", \"application\/font-woff\" },\n { \".woff2\", \"application\/font-woff2\" },\n { \".opus\", \"audio\/opus\" },\n { \".mp4\", \"video\/mp4\" },\n { \".mpeg\", \"video\/mpeg\" },\n { \".mpg\", \"video\/mpeg\" },\n { \".mp3\", \"audio\/mpeg\" } };\n\nint parse_url(yta_ctx* ctx, const char* path, size_t length) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n \/\/ parse query string\n auto pos = std::find(path, path + length, '?');\n if (pos != path + length) {\n length = pos - path;\n }\n\n \/\/ clean path buffer is MAX_URL_SICE\n \/\/ leave space for appended index.html\n if ((length > (MAX_URL_SIXE - 20)) || (length == 0)) {\n return_404(udata);\n return 0;\n }\n\n char normalized_path[MAX_URL_SIXE] = { 0 };\n \/\/ prepend . for current directory\n normalized_path[0] = '.';\n std::size_t new_length = 1;\n\n \/\/ clean path\n new_length += yta::http::clean_path(path, length, normalized_path + 1);\n\n \/\/ clean_path removes trailing slash except for root;\n \/\/ put the trailing slash back if necessary.\n if (path[length - 1] == '\/' && new_length != 2) {\n normalized_path[new_length] = '\/';\n ++new_length;\n }\n\n \/\/ append index.html to urls with trailing slashes\n if (normalized_path[new_length - 1] == '\/') {\n const char index_html[] = \"index.html\";\n std::copy(std::begin(index_html), std::end(index_html),\n normalized_path + new_length);\n new_length += 10;\n }\n\n int ffd = open(normalized_path, O_RDONLY);\n\n if (ffd == -1) {\n return_404(udata);\n return 0;\n }\n\n struct stat file_stat;\n int status = fstat(ffd, &file_stat);\n\n if (status != 0 || !S_ISREG(file_stat.st_mode)) {\n return_404(udata);\n close(ffd);\n return 0;\n }\n\n std::experimental::string_view path_view(normalized_path, new_length);\n auto filetype_begin = path_view.rfind('.');\n auto file_begin = path_view.rfind('\/');\n\n \/\/ we always find . at the beginning because of .\/FILENAME\n if (file_begin < filetype_begin) {\n auto it = mime_types.find(path_view.substr(filetype_begin));\n if (it != mime_types.end()) {\n udata->extension = it->second;\n } else {\n udata->extension = { \"text\/plain\" };\n }\n } else {\n udata->extension = { \"text\/plain\" };\n }\n\n udata->file_fd = ffd;\n udata->file_size = file_stat.st_size;\n udata->file_stat = file_stat;\n\n return 0;\n}\n\ntypedef bool (*header_handler)(yta_ctx*, std::experimental::string_view);\n\nbool handle_if_modified_since(yta_ctx* ctx, std::experimental::string_view value) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n tm stamp;\n if (strptime(value.data(), yta::http::http_time_format(), &stamp) == NULL) {\n auto end = yta::http::serve_400(udata->response_buf.data());\n udata->response_size = end - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n return true;\n }\n time_t time = timegm(&stamp);\n\n \/\/ not modified\n if (time >= udata->file_stat.st_mtime) {\n auto end = yta::http::serve_304(udata->response_buf.data());\n udata->response_size = end - udata->response_buf.data();\n udata->content = false;\n udata->finalized = true;\n return true;\n }\n\n return false;\n}\n\nbool handle_range(yta_ctx* ctx, std::experimental::string_view value) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n \/\/ 7 bytes=X-\n if (value.size() < 8) {\n return_400(udata);\n return true;\n }\n\n auto iter = value.begin();\n\n if (!std::equal(iter, iter + 6, \"bytes=\")) {\n return_400(udata);\n return true;\n }\n\n std::advance(iter, 6);\n\n auto sep = std::find(iter, value.end(), '-');\n\n if (sep == value.end()) {\n return_400(udata);\n return true;\n }\n\n \/\/ Range: bytes=-123\n if (sep == iter) {\n \/\/ this should be supported by rfc\n return_400(udata);\n return true;\n }\n\n \/\/ TODO: think of something smarter to not create temp std::string\n \/\/ boost::lexical_cast would work\n auto val = std::string(iter, sep);\n int start_value = std::stoi(val);\n int end_value = 0;\n\n if (std::next(sep, 1) == value.end()) { \/\/ Range: bytes=123-\n end_value = udata->file_stat.st_size - 1;\n } else { \/\/ Range: bytes=123-200\n auto val = std::string(sep + 1, value.end());\n end_value = std::stoi(val);\n }\n\n \/\/ sanity checks\n if (end_value <= start_value) {\n end_value = udata->file_stat.st_size - 1;\n }\n\n if (start_value < 0) {\n start_value = 0;\n }\n\n if (end_value >= udata->file_stat.st_size) {\n end_value = udata->file_stat.st_size - 1;\n }\n\n udata->file_size = end_value - start_value + 1;\n udata->offset = start_value;\n\n auto end = yta::http::serve_206(udata->response_buf.data(), udata->file_size,\n &udata->file_stat.st_mtime, start_value, end_value,\n udata->file_stat.st_size);\n udata->response_size = end - udata->response_buf.data();\n udata->content = true;\n udata->finalized = true;\n\n return true;\n}\n\nstd::unordered_map<std::experimental::string_view, header_handler> header_callbacks{\n { \"If-Modified-Since\", handle_if_modified_since }, { \"Range\", handle_range }\n};\n\nint parse_headers(yta_ctx* ctx) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n for (std::size_t i = 0; (i < udata->parser.num_headers) && !udata->finalized; ++i) {\n std::experimental::string_view header(udata->parser.headers[i].name,\n udata->parser.headers[i].name_len);\n auto it = header_callbacks.find(header);\n if (it != header_callbacks.end()) {\n std::experimental::string_view value(udata->parser.headers[i].value,\n udata->parser.headers[i].value_len);\n auto done = it->second(ctx, value);\n if (done) {\n return 0;\n }\n }\n }\n\n if (!udata->finalized) {\n auto end = yta::http::serve_200(udata->response_buf.data(), udata->file_size,\n &udata->file_stat.st_mtime, udata->extension);\n udata->response_size = end - udata->response_buf.data();\n udata->content = true;\n udata->finalized = true;\n }\n return 0;\n}\n\nvoid accept_logic(yta_ctx* ctx, user_data* udata);\n\nyta_callback_status http_finish_callback(yta_ctx* ctx, void*, size_t) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n if (udata->file_fd != 0) {\n close(udata->file_fd);\n udata->file_fd = 0;\n }\n\n \/\/ uncork\n int enable = 0;\n if (setsockopt(ctx->fd, IPPROTO_TCP, TCP_CORK, &enable, sizeof(enable)) < 0) {\n fprintf(stderr, \"error setting TCP_CORK\");\n exit(1);\n }\n\n accept_logic(ctx, udata);\n return YTA_OK;\n}\n\nyta_callback_status write_header_callback(yta_ctx* ctx, void*, size_t) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n if (udata->content) {\n yta_async_sendfile(ctx, http_finish_callback, udata->file_fd, udata->file_size,\n udata->offset);\n return YTA_OK;\n } else {\n return http_finish_callback(ctx, NULL, 0);\n }\n}\n\nyta_callback_status read_callback_http(yta_ctx* ctx, void* buf, size_t read) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n std::size_t prev_count = udata->counter;\n udata->counter += read;\n\n int parsed = phr_parse_request(\n udata->buf.data(), udata->counter, &udata->parser.method,\n &udata->parser.method_len, &udata->parser.path, &udata->parser.path_len,\n &udata->parser.minor_version, udata->parser.headers.data(),\n &udata->parser.num_headers, prev_count);\n\n if (parsed == -1) {\n return_400(udata);\n } else if (parsed > 0) {\n parse_url(ctx, udata->parser.path, udata->parser.path_len);\n parse_headers(ctx);\n }\n\n if (udata->finalized) {\n \/\/ cork\n int enable = 1;\n if (setsockopt(ctx->fd, IPPROTO_TCP, TCP_CORK, &enable, sizeof(enable)) < 0) {\n fprintf(stderr, \"error setting TCP_CORK\");\n exit(1);\n }\n\n yta_async_write(ctx, write_header_callback, udata->response_buf.data(),\n udata->response_size);\n return YTA_OK;\n }\n\n if (udata->counter == MAX_BUFFER_SIZE) {\n return http_finish_callback(ctx, NULL, 0);\n }\n\n yta_async_read(ctx, read_callback_http, (char*)buf + read,\n MAX_BUFFER_SIZE - udata->counter);\n return YTA_OK;\n}\n\nyta_callback_status http_cleanup(yta_ctx* ctx) {\n user_data* udata = static_cast<user_data*>(ctx->user_data);\n\n if (udata->file_fd != 0) {\n close(udata->file_fd);\n udata->file_fd = 0;\n }\n\n delete udata;\n\n return YTA_EXIT;\n}\n\nyta_callback_status timer_callback(yta_ctx* \/* ctx *\/) {\n printf(\"Force closing http connection\\n\");\n return YTA_EXIT;\n}\n\nvoid accept_logic(yta_ctx* ctx, user_data* udata) {\n udata->parser = parser_data{};\n udata->counter = 0;\n udata->finalized = false;\n udata->file_fd = 0;\n yta_async_read(ctx, read_callback_http, udata->buf.data(), MAX_BUFFER_SIZE);\n}\n\nyta_callback_status accept_callback_http(yta_ctx* ctx) {\n user_data* udata = new user_data;\n if (udata == nullptr) {\n return YTA_EXIT;\n }\n ctx->user_data = udata;\n yta_set_close_callback(ctx, http_cleanup);\n yta_async_timer(ctx, timer_callback, 300, 0);\n accept_logic(ctx, udata);\n return YTA_OK;\n}\n\nint main(int argc, char** argv) {\n auto opts = get_program_opts(argc, argv);\n\n yta_run(argv, opts.host.c_str(), opts.port.c_str(), opts.pid_file.c_str(),\n opts.daemonize, opts.workers, accept_callback_http);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Game.hpp\"\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tCONSTRUCTOR\n******************************************************************************\/\n\nGame::Game (int enemyNbr) : _enemyNbr(0), _enemyNbrMax(enemyNbr)\n{\n\tstd::srand(std::time(NULL) + std::clock());\n\tinitscr();\n\tnodelay(stdscr, TRUE);\n\tkeypad(stdscr, TRUE);\n\tcurs_set(0);\n\tthis->_box = stdscr;\n\tthis->_map = new AEntity(getmaxx(stdscr) - 1, getmaxy(stdscr) - 1, 0, 1);\n\tthis->_hero = new Hero(*new AEntity(3, 3, 1, 5));\n\tthis->_initEnemy();\n\n\tthis->_putEntity(this->_hero->getShape(), (this->_map->getSizeX() - this->_hero->getShape().getSizeX()) \/ 2,\n\tthis->_map->getSizeY() - this->_hero->getShape().getSizeY());\n\n\tstd::cout << \"Init Game Constructor\" << std::endl;\n\n\treturn ;\n}\n\nGame::Game( Game const & src )\n{\n\tstd::cout << \"Copy Game Constructor\" << std::endl;\n\t*this = src;\n\treturn ;\n}\n\/******************************************************************************\n** \t\t\t\t\t\t\tDESTRUCTOR\n******************************************************************************\/\nGame::~Game( void )\n{\n\treturn ;\n}\n\/******************************************************************************\n** \t\t\t\t\t\t\tOPERATOR OVERLOAD\n******************************************************************************\/\nGame & Game::operator=( Game const & rhs )\n{\n\tthis->_box = rhs._box;\n\tthis->_map = rhs._map;\n\tthis->_hero = rhs._hero;\n\tthis->_enemies = rhs._enemies;\n\tthis->_enemyNbr = rhs._enemyNbr;\n\tthis->_enemyNbrMax = rhs._enemyNbrMax;\n\n\treturn *this;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\tPRIVATE MEMBER FUNCTION\n******************************************************************************\/\nvoid \t\tGame::_initEnemy(void)\n{\n\tthis->_enemies = new Enemy*[this->_enemyNbrMax];\n\tfor (int i = 0; i < this->_enemyNbrMax; i++) {\n\t\tthis->_enemies[i] = NULL;\n\t}\n\n\treturn ;\n}\n\nvoid \t\tGame::_newWave(void)\n{\n\tthis->_enemyNbr = rand() % this->_enemyNbrMax;\n\tEnemy* (Game::*Func[])(void) const = {&Game::_callD7, &Game::_callVor_cha};\n\n\tfor (int i = 0; i < this->_enemyNbr; i++) {\n\t\tif (!this->_enemies[i]) {\n\t\t\tthis->_enemies[i] = (this->*Func[rand() % 2])();\n\t\t\tthis->_putEntity(this->_enemies[i]->getShape(), ((this->_map->getSizeX() \/ (this->_enemyNbr)) * (i)) + 1, 5);\n\t\t}\n\t}\n\n\treturn ;\n}\n\nvoid \t\tGame::_putEntity(AEntity &entity, int x, int y)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tentity.setPosX(x);\n\tentity.setPosY(y);\n\n\tfor (i = 0; i < entity.getSizeX(); i++) {\n\t\tfor (j = 0; j < entity.getSizeY(); j++) {\n\n\t\t\tif (entity.getDefinition()[i][j] != this->_map->getDefinition()[i + x][j + y] && this->_map->getDefinition()[i + x][j + y] != 0) {\n\t\t\t\tendwin();\n\t\t\t\treturn exit(0);\n\t\t\t}\n\n\t\t\tif (entity.getDefinition()[i][j] != 0) {\n\t\t\t\tthis->_map->setDefinition(i + x, j + y, entity.getDefinition()[i][j]);\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nvoid \t\tGame::_deleteEntity(AEntity &entity)\n{\n\tint i = 0;\n\tint j = 0;\n\tint x = entity.getPosX();\n\tint y = entity.getPosY();\n\n\tfor (i = 0; i < entity.getSizeX(); i++) {\n\t\tfor (j = 0; j < entity.getSizeY(); j++) {\n\t\t\tif (entity.getDefinition()[i][j] != 0) {\n\t\t\t\tthis->_map->setDefinition(i + x, j + y, 0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool \t\tGame::_moveEntityUp(AEntity &entity)\n{\n\tif (entity.getPosY() > 1) {\n\t\tentity.setPosY(entity.getPosY() - 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityDown(AEntity &entity)\n{\n\tif (entity.getPosY() + entity.getSizeY() < this->_map->getSizeY()) {\n\t\tentity.setPosY(entity.getPosY() + 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityLeft(AEntity &entity)\n{\n\tif (entity.getPosX() > 1) {\n\t\tentity.setPosX(entity.getPosX() - 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityRight(AEntity &entity)\n{\n\tif (entity.getPosX() + entity.getSizeX() < this->_map->getSizeX()) {\n\t\tentity.setPosX(entity.getPosX() + 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nEnemy*\t\t\tGame::_callD7(void) const\n{\n\treturn new D7(new IWeapon(), 0x0);\n}\n\nEnemy*\tGame::_callVor_cha(void) const\n{\n\treturn new Vor_cha(new IWeapon(), 0x0);\n}\n\n\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tGETTEUR\n******************************************************************************\/\nWINDOW*\t\tGame::getBox(void)\n{\n\treturn this->_box;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tSETTEUR\n******************************************************************************\/\nvoid \t\tGame::setBox(WINDOW* box)\n{\n\tthis->_box = box;\n\n\treturn ;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\tPUBLIC MEMBER FUNCTION\n******************************************************************************\/\nvoid Game::printMap(void)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tfor (i = 0; i < this->_map->getSizeX(); i++) {\n\t\tfor (j = 0; j < this->_map->getSizeY(); j++) {\n\t\t\tif (this->_map->getDefinition()[i][j] == 1) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '#');\n\t\t\t}\n\t\t\telse if (this->_map->getDefinition()[i][j] == 2) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '@');\n\t\t\t}\n\t\t\telse if (this->_map->getDefinition()[i][j] == 3) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '*');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmvwaddch(this->getBox(), j, i, ' ');\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Game::eraseMap(void)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tfor (i = 0; i < this->_map->getSizeX(); i++) {\n\t\tfor (j = 0; j < this->_map->getSizeY(); j++) {\n\t\t\tif (this->_map->getDefinition()[i][j] != 0) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, ' ');\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid \t\tGame::moveEntity(AEntity &entity, int vecteur)\n{\n\tthis->_deleteEntity(entity);\n\n\tswitch (vecteur)\n\t{\n\tcase 1: \/\/ haut\n\t\tthis->_moveEntityUp(entity);\n\t\tbreak;\n\n\tcase 2: \/\/ bas\n\t\tthis->_moveEntityDown(entity);\n\t\tbreak;\n\n\tcase 3: \/\/ gauche\n\t\tthis->_moveEntityLeft(entity);\n\t\tbreak;\n\n\tcase 4: \/\/ droite\n\t\tthis->_moveEntityRight(entity);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tthis->_putEntity(entity, entity.getPosX(), entity.getPosY());\n\n\treturn ;\n\n}\n\nvoid \t\tGame::moveEnemies(void)\n{\n\tint i = 0;\n\n\tfor (i = 0; i < this->_enemyNbrMax; i++) {\n\t\tif (this->_enemies[i] != NULL && this->_enemies[i]->move())\n\t\t{\n\t\t\tthis->_deleteEntity(this->_enemies[i]->getShape());\n\t\t\tif (this->_enemies[i]->enemyMove(this->_map->getSizeX(), this->_map->getSizeY())) {\n\t\t\t\tthis->_putEntity(this->_enemies[i]->getShape(), this->_enemies[i]->getShape().getPosX(), this->_enemies[i]->getShape().getPosY());\n\t\t\t}else{\n\t\t\t\tthis->_enemyNbr--;\n\t\t\t\tdelete this->_enemies[i];\n\t\t\t\tthis->_enemies[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ;\n}\n\nvoid Game::play(int ch)\n{\n\tif (ch == 27) {\n\t\tendwin();\n\t\treturn exit(0);\n\t}\n\tif (ch == 259) {\n\t\tthis->moveEntity(this->_hero->getShape(), 1);\n\t}\n\tif (ch == 258) {\n\t\tthis->moveEntity(this->_hero->getShape(), 2);\n\t}\n\tif (ch == 260) {\n\t\tthis->moveEntity(this->_hero->getShape(), 3);\n\t}\n\tif (ch == 261) {\n\t\tthis->moveEntity(this->_hero->getShape(), 4);\n\t}\n\n\tif (this->_enemyNbr == 0) {\n\t\tthis->_newWave();\n\t}\n\telse {\n\t\tthis->moveEnemies();\n\t}\n\n}\n<commit_msg>set enemy at 0<commit_after>#include \"Game.hpp\"\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tCONSTRUCTOR\n******************************************************************************\/\n\nGame::Game (int enemyNbr) : _enemyNbr(0), _enemyNbrMax(enemyNbr)\n{\n\tstd::srand(std::time(NULL) + std::clock());\n\tinitscr();\n\tnodelay(stdscr, TRUE);\n\tkeypad(stdscr, TRUE);\n\tcurs_set(0);\n\tthis->_box = stdscr;\n\tthis->_map = new AEntity(getmaxx(stdscr) - 1, getmaxy(stdscr) - 1, 0, 1);\n\tthis->_hero = new Hero(*new AEntity(3, 3, 1, 5));\n\tthis->_initEnemy();\n\n\tthis->_putEntity(this->_hero->getShape(), (this->_map->getSizeX() - this->_hero->getShape().getSizeX()) \/ 2,\n\tthis->_map->getSizeY() - this->_hero->getShape().getSizeY());\n\n\tstd::cout << \"Init Game Constructor\" << std::endl;\n\n\treturn ;\n}\n\nGame::Game( Game const & src )\n{\n\tstd::cout << \"Copy Game Constructor\" << std::endl;\n\t*this = src;\n\treturn ;\n}\n\/******************************************************************************\n** \t\t\t\t\t\t\tDESTRUCTOR\n******************************************************************************\/\nGame::~Game( void )\n{\n\treturn ;\n}\n\/******************************************************************************\n** \t\t\t\t\t\t\tOPERATOR OVERLOAD\n******************************************************************************\/\nGame & Game::operator=( Game const & rhs )\n{\n\tthis->_box = rhs._box;\n\tthis->_map = rhs._map;\n\tthis->_hero = rhs._hero;\n\tthis->_enemies = rhs._enemies;\n\tthis->_enemyNbr = rhs._enemyNbr;\n\tthis->_enemyNbrMax = rhs._enemyNbrMax;\n\n\treturn *this;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\tPRIVATE MEMBER FUNCTION\n******************************************************************************\/\nvoid \t\tGame::_initEnemy(void)\n{\n\tthis->_enemies = new Enemy*[this->_enemyNbrMax];\n\tfor (int i = 0; i < this->_enemyNbrMax; i++) {\n\t\tthis->_enemies[i] = NULL;\n\t}\n\n\treturn ;\n}\n\nvoid \t\tGame::_newWave(void)\n{\n\tthis->_enemyNbr = rand() % this->_enemyNbrMax;\n\tEnemy* (Game::*Func[])(void) const = {&Game::_callD7, &Game::_callVor_cha};\n\n\tfor (int i = 0; i < this->_enemyNbr; i++) {\n\t\tif (!this->_enemies[i]) {\n\t\t\tthis->_enemies[i] = (this->*Func[rand() % 2])();\n\t\t\tthis->_putEntity(this->_enemies[i]->getShape(), ((this->_map->getSizeX() \/ (this->_enemyNbr)) * (i)) + 1, 0);\n\t\t}\n\t}\n\n\treturn ;\n}\n\nvoid \t\tGame::_putEntity(AEntity &entity, int x, int y)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tentity.setPosX(x);\n\tentity.setPosY(y);\n\n\tfor (i = 0; i < entity.getSizeX(); i++) {\n\t\tfor (j = 0; j < entity.getSizeY(); j++) {\n\n\t\t\tif (entity.getDefinition()[i][j] != this->_map->getDefinition()[i + x][j + y] && this->_map->getDefinition()[i + x][j + y] != 0) {\n\t\t\t\tendwin();\n\t\t\t\treturn exit(0);\n\t\t\t}\n\n\t\t\tif (entity.getDefinition()[i][j] != 0) {\n\t\t\t\tthis->_map->setDefinition(i + x, j + y, entity.getDefinition()[i][j]);\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nvoid \t\tGame::_deleteEntity(AEntity &entity)\n{\n\tint i = 0;\n\tint j = 0;\n\tint x = entity.getPosX();\n\tint y = entity.getPosY();\n\n\tfor (i = 0; i < entity.getSizeX(); i++) {\n\t\tfor (j = 0; j < entity.getSizeY(); j++) {\n\t\t\tif (entity.getDefinition()[i][j] != 0) {\n\t\t\t\tthis->_map->setDefinition(i + x, j + y, 0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool \t\tGame::_moveEntityUp(AEntity &entity)\n{\n\tif (entity.getPosY() > 1) {\n\t\tentity.setPosY(entity.getPosY() - 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityDown(AEntity &entity)\n{\n\tif (entity.getPosY() + entity.getSizeY() < this->_map->getSizeY()) {\n\t\tentity.setPosY(entity.getPosY() + 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityLeft(AEntity &entity)\n{\n\tif (entity.getPosX() > 1) {\n\t\tentity.setPosX(entity.getPosX() - 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nbool \t\tGame::_moveEntityRight(AEntity &entity)\n{\n\tif (entity.getPosX() + entity.getSizeX() < this->_map->getSizeX()) {\n\t\tentity.setPosX(entity.getPosX() + 1);\n\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\nEnemy*\t\t\tGame::_callD7(void) const\n{\n\treturn new D7(new IWeapon(), 0x0);\n}\n\nEnemy*\tGame::_callVor_cha(void) const\n{\n\treturn new Vor_cha(new IWeapon(), 0x0);\n}\n\n\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tGETTEUR\n******************************************************************************\/\nWINDOW*\t\tGame::getBox(void)\n{\n\treturn this->_box;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\t\tSETTEUR\n******************************************************************************\/\nvoid \t\tGame::setBox(WINDOW* box)\n{\n\tthis->_box = box;\n\n\treturn ;\n}\n\n\/******************************************************************************\n** \t\t\t\t\t\t\tPUBLIC MEMBER FUNCTION\n******************************************************************************\/\nvoid Game::printMap(void)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tfor (i = 0; i < this->_map->getSizeX(); i++) {\n\t\tfor (j = 0; j < this->_map->getSizeY(); j++) {\n\t\t\tif (this->_map->getDefinition()[i][j] == 1) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '#');\n\t\t\t}\n\t\t\telse if (this->_map->getDefinition()[i][j] == 2) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '@');\n\t\t\t}\n\t\t\telse if (this->_map->getDefinition()[i][j] == 3) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, '*');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmvwaddch(this->getBox(), j, i, ' ');\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Game::eraseMap(void)\n{\n\tint i = 0;\n\tint j = 0;\n\n\tfor (i = 0; i < this->_map->getSizeX(); i++) {\n\t\tfor (j = 0; j < this->_map->getSizeY(); j++) {\n\t\t\tif (this->_map->getDefinition()[i][j] != 0) {\n\t\t\t\tmvwaddch(this->getBox(), j, i, ' ');\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid \t\tGame::moveEntity(AEntity &entity, int vecteur)\n{\n\tthis->_deleteEntity(entity);\n\n\tswitch (vecteur)\n\t{\n\tcase 1: \/\/ haut\n\t\tthis->_moveEntityUp(entity);\n\t\tbreak;\n\n\tcase 2: \/\/ bas\n\t\tthis->_moveEntityDown(entity);\n\t\tbreak;\n\n\tcase 3: \/\/ gauche\n\t\tthis->_moveEntityLeft(entity);\n\t\tbreak;\n\n\tcase 4: \/\/ droite\n\t\tthis->_moveEntityRight(entity);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tthis->_putEntity(entity, entity.getPosX(), entity.getPosY());\n\n\treturn ;\n\n}\n\nvoid \t\tGame::moveEnemies(void)\n{\n\tint i = 0;\n\n\tfor (i = 0; i < this->_enemyNbrMax; i++) {\n\t\tif (this->_enemies[i] != NULL && this->_enemies[i]->move())\n\t\t{\n\t\t\tthis->_deleteEntity(this->_enemies[i]->getShape());\n\t\t\tif (this->_enemies[i]->enemyMove(this->_map->getSizeX(), this->_map->getSizeY())) {\n\t\t\t\tthis->_putEntity(this->_enemies[i]->getShape(), this->_enemies[i]->getShape().getPosX(), this->_enemies[i]->getShape().getPosY());\n\t\t\t}else{\n\t\t\t\tthis->_enemyNbr--;\n\t\t\t\tdelete this->_enemies[i];\n\t\t\t\tthis->_enemies[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ;\n}\n\nvoid Game::play(int ch)\n{\n\tif (ch == 27) {\n\t\tendwin();\n\t\treturn exit(0);\n\t}\n\tif (ch == 259) {\n\t\tthis->moveEntity(this->_hero->getShape(), 1);\n\t}\n\tif (ch == 258) {\n\t\tthis->moveEntity(this->_hero->getShape(), 2);\n\t}\n\tif (ch == 260) {\n\t\tthis->moveEntity(this->_hero->getShape(), 3);\n\t}\n\tif (ch == 261) {\n\t\tthis->moveEntity(this->_hero->getShape(), 4);\n\t}\n\n\tif (this->_enemyNbr == 0) {\n\t\tthis->_newWave();\n\t}\n\telse {\n\t\tthis->moveEnemies();\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2013, 2014 Andreas Hartmetz <ahartmetz@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"peeraddress.h\"\n\n#include \"stringtools.h\"\n\n#include <cassert>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <pwd.h>\n#include <unistd.h>\n\nusing namespace std;\n\nstatic string homeDir()\n{\n const char *home = getenv(\"HOME\"); \/\/ this overrides the entry in \/etc\/passwd\n if (!home) {\n \/\/ from \/etc\/passwd (or a similar mechanism)\n \/\/ ### user's storage is static; consider using getpwuid_r though!\n struct passwd *user = getpwuid(getuid());\n if (user) {\n home = user->pw_dir;\n }\n }\n assert(home);\n return string(home);\n}\n\nstatic string sessionInfoFile()\n{\n static const int numMachineUuidFilenames = 2;\n static const char *machineUuidFilenames[numMachineUuidFilenames] = {\n \"\/var\/lib\/dbus\/machine-id\",\n \"\/etc\/machine-id\"\n };\n\n string uuid;\n for (int i = 0; i < numMachineUuidFilenames && uuid.empty(); i++) {\n ifstream uuidFile(machineUuidFilenames[i]);\n uuidFile >> uuid;\n \/\/ TODO check that uuid consists of lowercase hex chars\n }\n if (uuid.length() != 32) {\n return string();\n }\n\n const char *displayChar = getenv(\"DISPLAY\");\n if (!displayChar) {\n \/\/ TODO error message \"no X11 session blah\"\n return string();\n }\n string display = displayChar;\n \/\/ TODO from the original: \"Note that we leave the hostname in the display most of the time\"\n size_t lastColon = display.rfind(':');\n if (lastColon == string::npos) {\n return string();\n }\n display.erase(0, lastColon + 1);\n\n static const char *pathInHome = \"\/.dbus\/session-bus\/\";\n string ret = homeDir() + pathInHome + uuid + '-' + display;\n return ret;\n}\n\nclass PeerAddress::Private\n{\npublic:\n Private()\n : m_peerType(NoPeer),\n m_socketType(NoSocket),\n m_port(-1)\n {}\n\n void fetchSessionBusInfo();\n void parseSessionBusInfo(std::string info);\n\n PeerAddress::PeerType m_peerType;\n PeerAddress::SocketType m_socketType;\n std::string m_path;\n int m_port;\n std::string m_guid;\n};\n\nPeerAddress::PeerAddress()\n : d(new Private)\n{\n}\n\nPeerAddress::PeerAddress(PeerType bus)\n : d(new Private)\n{\n if (bus == SessionBus) {\n d->fetchSessionBusInfo();\n } else if (bus == SystemBus) {\n \/\/ TODO non-Linux\n d->m_path = \"\/var\/run\/dbus\/system_bus_socket\";\n } else {\n \/\/ TODO error\n }\n}\n\nPeerAddress::PeerAddress(const PeerAddress &other)\n : d(new Private(*other.d))\n{\n}\n\nPeerAddress &PeerAddress::operator=(const PeerAddress &other)\n{\n *d = *other.d;\n return *this;\n}\n\nPeerAddress::~PeerAddress()\n{\n delete d;\n d = 0;\n}\n\nPeerAddress::PeerType PeerAddress::peerType() const\n{\n return d->m_peerType;\n}\n\nPeerAddress::SocketType PeerAddress::socketType() const\n{\n return d->m_socketType;\n}\n\nstring PeerAddress::path() const\n{\n return d->m_path;\n}\n\nint PeerAddress::port() const\n{\n return d->m_port;\n}\n\nstring PeerAddress::guid() const\n{\n return d->m_guid;\n}\n\n\nvoid PeerAddress::Private::fetchSessionBusInfo()\n{\n ifstream infoFile(sessionInfoFile().c_str());\n string line;\n\n \/\/ TODO: on X, the spec requires a special way to find the session bus\n\n \/\/ try the environment variable\n const char *envAddress = getenv(\"DBUS_SESSION_BUS_ADDRESS\");\n if (envAddress) {\n line = envAddress;\n } else {\n \/\/ try it using a byzantine system involving files...\n string busAddressPrefix = \"DBUS_SESSION_BUS_ADDRESS=\";\n while (getline(infoFile, line)) {\n \/\/ TODO do we need any of the other information in the file?\n if (line.find(busAddressPrefix) == 0 ) {\n line = line.substr(busAddressPrefix.length());\n break;\n }\n }\n }\n\n parseSessionBusInfo(line);\n}\n\nvoid PeerAddress::Private::parseSessionBusInfo(string info)\n{\n SocketType provisionalType = NoSocket;\n\n string unixAddressLiteral = \"unix:\";\n string guidLiteral = \"guid=\";\n\n if (info.find(unixAddressLiteral) == 0) {\n provisionalType = UnixSocket;\n info.erase(0, unixAddressLiteral.length());\n }\n\n \/\/ TODO is there any escaping?\n const vector<string> parts = split(info, ',');\n\n if (provisionalType == UnixSocket) {\n string pathLiteral = \"path=\";\n string abstractLiteral = \"abstract=\";\n \/\/ TODO what about \"tmpdir=...\"?\n\n for (int i = 0; i < parts.size(); i++) {\n const string &part = parts[i];\n if (part.find(pathLiteral) == 0) {\n if (m_socketType != NoSocket) {\n goto invalid; \/\/ error - duplicate path specification\n }\n m_socketType = UnixSocket;\n m_path = part.substr(pathLiteral.length());\n } else if (part.find(abstractLiteral) == 0) {\n if (m_socketType != NoSocket) {\n goto invalid;\n }\n m_socketType = AbstractUnixSocket;\n m_path = part.substr(abstractLiteral.length());\n }\n }\n } else {\n \/\/ TODO\n }\n\n for (int i = 0; i < parts.size(); i++) {\n const string &part = parts[i];\n if (part.find(guidLiteral) == 0) {\n m_guid = part.substr(guidLiteral.length());\n }\n }\n\n return;\ninvalid:\n m_socketType = NoSocket;\n m_path.clear();\n}\n<commit_msg>PeerAddress: initialize more variables in PeerType constructor.<commit_after>\/*\n Copyright (C) 2013, 2014 Andreas Hartmetz <ahartmetz@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"peeraddress.h\"\n\n#include \"stringtools.h\"\n\n#include <cassert>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <pwd.h>\n#include <unistd.h>\n\nusing namespace std;\n\nstatic string homeDir()\n{\n const char *home = getenv(\"HOME\"); \/\/ this overrides the entry in \/etc\/passwd\n if (!home) {\n \/\/ from \/etc\/passwd (or a similar mechanism)\n \/\/ ### user's storage is static; consider using getpwuid_r though!\n struct passwd *user = getpwuid(getuid());\n if (user) {\n home = user->pw_dir;\n }\n }\n assert(home);\n return string(home);\n}\n\nstatic string sessionInfoFile()\n{\n static const int numMachineUuidFilenames = 2;\n static const char *machineUuidFilenames[numMachineUuidFilenames] = {\n \"\/var\/lib\/dbus\/machine-id\",\n \"\/etc\/machine-id\"\n };\n\n string uuid;\n for (int i = 0; i < numMachineUuidFilenames && uuid.empty(); i++) {\n ifstream uuidFile(machineUuidFilenames[i]);\n uuidFile >> uuid;\n \/\/ TODO check that uuid consists of lowercase hex chars\n }\n if (uuid.length() != 32) {\n return string();\n }\n\n const char *displayChar = getenv(\"DISPLAY\");\n if (!displayChar) {\n \/\/ TODO error message \"no X11 session blah\"\n return string();\n }\n string display = displayChar;\n \/\/ TODO from the original: \"Note that we leave the hostname in the display most of the time\"\n size_t lastColon = display.rfind(':');\n if (lastColon == string::npos) {\n return string();\n }\n display.erase(0, lastColon + 1);\n\n static const char *pathInHome = \"\/.dbus\/session-bus\/\";\n string ret = homeDir() + pathInHome + uuid + '-' + display;\n return ret;\n}\n\nclass PeerAddress::Private\n{\npublic:\n Private()\n : m_peerType(NoPeer),\n m_socketType(NoSocket),\n m_port(-1)\n {}\n\n void fetchSessionBusInfo();\n void parseSessionBusInfo(std::string info);\n\n PeerAddress::PeerType m_peerType;\n PeerAddress::SocketType m_socketType;\n std::string m_path;\n int m_port;\n std::string m_guid;\n};\n\nPeerAddress::PeerAddress()\n : d(new Private)\n{\n}\n\nPeerAddress::PeerAddress(PeerType bus)\n : d(new Private)\n{\n d->m_peerType = bus;\n if (bus == SessionBus) {\n d->fetchSessionBusInfo();\n } else if (bus == SystemBus) {\n \/\/ TODO non-Linux\n d->m_socketType = UnixSocket;\n d->m_path = \"\/var\/run\/dbus\/system_bus_socket\";\n } else {\n \/\/ TODO error\n }\n}\n\nPeerAddress::PeerAddress(const PeerAddress &other)\n : d(new Private(*other.d))\n{\n}\n\nPeerAddress &PeerAddress::operator=(const PeerAddress &other)\n{\n *d = *other.d;\n return *this;\n}\n\nPeerAddress::~PeerAddress()\n{\n delete d;\n d = 0;\n}\n\nPeerAddress::PeerType PeerAddress::peerType() const\n{\n return d->m_peerType;\n}\n\nPeerAddress::SocketType PeerAddress::socketType() const\n{\n return d->m_socketType;\n}\n\nstring PeerAddress::path() const\n{\n return d->m_path;\n}\n\nint PeerAddress::port() const\n{\n return d->m_port;\n}\n\nstring PeerAddress::guid() const\n{\n return d->m_guid;\n}\n\n\nvoid PeerAddress::Private::fetchSessionBusInfo()\n{\n ifstream infoFile(sessionInfoFile().c_str());\n string line;\n\n \/\/ TODO: on X, the spec requires a special way to find the session bus\n\n \/\/ try the environment variable\n const char *envAddress = getenv(\"DBUS_SESSION_BUS_ADDRESS\");\n if (envAddress) {\n line = envAddress;\n } else {\n \/\/ try it using a byzantine system involving files...\n string busAddressPrefix = \"DBUS_SESSION_BUS_ADDRESS=\";\n while (getline(infoFile, line)) {\n \/\/ TODO do we need any of the other information in the file?\n if (line.find(busAddressPrefix) == 0 ) {\n line = line.substr(busAddressPrefix.length());\n break;\n }\n }\n }\n\n parseSessionBusInfo(line);\n}\n\nvoid PeerAddress::Private::parseSessionBusInfo(string info)\n{\n SocketType provisionalType = NoSocket;\n\n string unixAddressLiteral = \"unix:\";\n string guidLiteral = \"guid=\";\n\n if (info.find(unixAddressLiteral) == 0) {\n provisionalType = UnixSocket;\n info.erase(0, unixAddressLiteral.length());\n }\n\n \/\/ TODO is there any escaping?\n const vector<string> parts = split(info, ',');\n\n if (provisionalType == UnixSocket) {\n string pathLiteral = \"path=\";\n string abstractLiteral = \"abstract=\";\n \/\/ TODO what about \"tmpdir=...\"?\n\n for (int i = 0; i < parts.size(); i++) {\n const string &part = parts[i];\n if (part.find(pathLiteral) == 0) {\n if (m_socketType != NoSocket) {\n goto invalid; \/\/ error - duplicate path specification\n }\n m_socketType = UnixSocket;\n m_path = part.substr(pathLiteral.length());\n } else if (part.find(abstractLiteral) == 0) {\n if (m_socketType != NoSocket) {\n goto invalid;\n }\n m_socketType = AbstractUnixSocket;\n m_path = part.substr(abstractLiteral.length());\n }\n }\n } else {\n \/\/ TODO\n }\n\n for (int i = 0; i < parts.size(); i++) {\n const string &part = parts[i];\n if (part.find(guidLiteral) == 0) {\n m_guid = part.substr(guidLiteral.length());\n }\n }\n\n return;\ninvalid:\n m_socketType = NoSocket;\n m_path.clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2022 Red Hat, Inc.\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#pragma once\n\n#ifndef __URIPARSER_H_\n#define __URIPARSER_H_\n\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n\nnamespace lsm_uri {\n\nusing query_key_value = std::unordered_map<std::string, std::string>;\n\nstruct uri {\n bool valid = false;\n std::string scheme;\n std::string username;\n std::string host;\n long port = -1;\n std::string path;\n query_key_value query;\n std::string fragment;\n};\n\ninline bool verify_scheme(std::string s) {\n if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {\n return std::isalnum(c) || c == '+' || c == '.' ||\n c == '-';\n }) != s.end()) {\n return false;\n }\n\n return true;\n}\n\ninline std::tuple<std::string, std::string> pair(std::string s) {\n auto i = s.find(\"=\");\n if (i == std::string::npos) {\n return {s, \"\"};\n }\n return {s.substr(0, i), s.substr(i + 1)};\n}\n\ninline query_key_value parse_qs(std::string qs) {\n query_key_value rc;\n\n std::string key;\n std::string value;\n\n if (!qs.length())\n return rc;\n\n std::size_t amp;\n do {\n amp = qs.find(\"&\");\n\n if (amp == std::string::npos) {\n \/\/ No separator found\n std::tie(key, value) = pair(qs);\n rc[key] = value;\n\n } else {\n \/\/ & found\n std::tie(key, value) = pair(qs.substr(0, amp));\n rc[key] = value;\n qs = qs.substr(amp + 1);\n }\n\n } while (amp != std::string::npos);\n\n return rc;\n}\n\ninline long port(std::string s) {\n long rc = -1;\n\n if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {\n return std::isdigit(c);\n }) != s.end()) {\n return rc;\n }\n\n \/\/ Convert string to long\n try {\n rc = std::stol(s);\n } catch (const std::invalid_argument &ia) {\n }\n\n return rc;\n}\n\ninline struct uri parse(std::string uri) {\n struct uri rc;\n\n std::size_t req;\n\n \/\/ Library requires :\/\/ in uri\n if (uri.empty() || ((req = uri.find(\":\/\/\")) == std::string::npos)) {\n return rc;\n }\n\n std::string scheme_tmp = uri.substr(0, req);\n if (!verify_scheme(scheme_tmp)) {\n return rc;\n }\n\n rc.scheme = scheme_tmp;\n\n auto remainder = uri.substr(req + 3);\n\n \/\/ Check to see if we have a fragment\n auto frag = remainder.rfind(\"#\");\n if (frag != std::string::npos) {\n rc.fragment = remainder.substr(frag + 1);\n remainder = remainder.substr(0, frag);\n }\n\n \/\/ Check for query string\n auto qs = remainder.rfind(\"?\");\n if (qs != std::string::npos) {\n rc.query = parse_qs(remainder.substr(qs + 1));\n remainder = remainder.substr(0, qs);\n }\n\n \/\/ process location & path\n auto path_start = remainder.find(\"\/\");\n if (path_start != std::string::npos) {\n rc.path = remainder.substr(path_start);\n remainder = remainder.substr(0, path_start);\n }\n\n \/\/ process username, port, then host\n auto username = remainder.find(\"@\");\n if (username != std::string::npos) {\n rc.username = remainder.substr(0, username);\n remainder = remainder.substr(username + 1);\n }\n\n \/\/ Check for port on host\n auto port_del = remainder.rfind(\":\");\n if (port_del != std::string::npos) {\n \/\/ Check if this is a valid port, could be ipv6 addr.\n long tmp_port = port(remainder.substr(port_del + 1));\n if (tmp_port != -1) {\n rc.port = tmp_port;\n remainder = remainder.substr(0, port_del);\n }\n }\n\n \/\/ Only part left should be host, which is a ipv4, hostname, or ipv6\n rc.host = remainder;\n rc.valid = true;\n return rc;\n}\n\n} \/\/ namespace lsm_uri\n\n#endif<commit_msg>EL7: Use alt. tuple syntax<commit_after>\/*\n * Copyright (C) 2022 Red Hat, Inc.\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#pragma once\n\n#ifndef __URIPARSER_H_\n#define __URIPARSER_H_\n\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n\nnamespace lsm_uri {\n\nusing query_key_value = std::unordered_map<std::string, std::string>;\n\nstruct uri {\n bool valid = false;\n std::string scheme;\n std::string username;\n std::string host;\n long port = -1;\n std::string path;\n query_key_value query;\n std::string fragment;\n};\n\ninline bool verify_scheme(std::string s) {\n if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {\n return std::isalnum(c) || c == '+' || c == '.' ||\n c == '-';\n }) != s.end()) {\n return false;\n }\n\n return true;\n}\n\ninline std::tuple<std::string, std::string> pair(std::string s) {\n auto i = s.find(\"=\");\n if (i == std::string::npos) {\n return std::make_tuple(s, \"\");\n }\n return std::make_tuple(s.substr(0, i), s.substr(i + 1));\n}\n\ninline query_key_value parse_qs(std::string qs) {\n query_key_value rc;\n\n std::string key;\n std::string value;\n\n if (!qs.length())\n return rc;\n\n std::size_t amp;\n do {\n amp = qs.find(\"&\");\n\n if (amp == std::string::npos) {\n \/\/ No separator found\n std::tie(key, value) = pair(qs);\n rc[key] = value;\n\n } else {\n \/\/ & found\n std::tie(key, value) = pair(qs.substr(0, amp));\n rc[key] = value;\n qs = qs.substr(amp + 1);\n }\n\n } while (amp != std::string::npos);\n\n return rc;\n}\n\ninline long port(std::string s) {\n long rc = -1;\n\n if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {\n return std::isdigit(c);\n }) != s.end()) {\n return rc;\n }\n\n \/\/ Convert string to long\n try {\n rc = std::stol(s);\n } catch (const std::invalid_argument &ia) {\n }\n\n return rc;\n}\n\ninline struct uri parse(std::string uri) {\n struct uri rc;\n\n std::size_t req;\n\n \/\/ Library requires :\/\/ in uri\n if (uri.empty() || ((req = uri.find(\":\/\/\")) == std::string::npos)) {\n return rc;\n }\n\n std::string scheme_tmp = uri.substr(0, req);\n if (!verify_scheme(scheme_tmp)) {\n return rc;\n }\n\n rc.scheme = scheme_tmp;\n\n auto remainder = uri.substr(req + 3);\n\n \/\/ Check to see if we have a fragment\n auto frag = remainder.rfind(\"#\");\n if (frag != std::string::npos) {\n rc.fragment = remainder.substr(frag + 1);\n remainder = remainder.substr(0, frag);\n }\n\n \/\/ Check for query string\n auto qs = remainder.rfind(\"?\");\n if (qs != std::string::npos) {\n rc.query = parse_qs(remainder.substr(qs + 1));\n remainder = remainder.substr(0, qs);\n }\n\n \/\/ process location & path\n auto path_start = remainder.find(\"\/\");\n if (path_start != std::string::npos) {\n rc.path = remainder.substr(path_start);\n remainder = remainder.substr(0, path_start);\n }\n\n \/\/ process username, port, then host\n auto username = remainder.find(\"@\");\n if (username != std::string::npos) {\n rc.username = remainder.substr(0, username);\n remainder = remainder.substr(username + 1);\n }\n\n \/\/ Check for port on host\n auto port_del = remainder.rfind(\":\");\n if (port_del != std::string::npos) {\n \/\/ Check if this is a valid port, could be ipv6 addr.\n long tmp_port = port(remainder.substr(port_del + 1));\n if (tmp_port != -1) {\n rc.port = tmp_port;\n remainder = remainder.substr(0, port_del);\n }\n }\n\n \/\/ Only part left should be host, which is a ipv4, hostname, or ipv6\n rc.host = remainder;\n rc.valid = true;\n return rc;\n}\n\n} \/\/ namespace lsm_uri\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"android\/log.h\"\n#include \"gvr_cpp_stack_trace.h\"\n\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\n#include <unwind.h>\n#include <dlfcn.h>\n\n#define TAG \"gvrf\"\n\nnamespace {\n\n struct BacktraceState\n {\n void** current;\n void** end;\n };\n\n static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg)\n {\n BacktraceState* state = static_cast<BacktraceState*>(arg);\n uintptr_t pc = _Unwind_GetIP(context);\n if (pc) {\n if (state->current == state->end) {\n return _URC_END_OF_STACK;\n } else {\n *state->current++ = reinterpret_cast<void*>(pc);\n }\n }\n return _URC_NO_REASON;\n }\n\n size_t captureBacktrace(void** buffer, size_t max)\n {\n BacktraceState state = {buffer, buffer + max};\n _Unwind_Backtrace(unwindCallback, &state);\n\n return state.current - buffer;\n }\n\n void dumpBacktrace(std::ostream& os, void** addrs, size_t count)\n {\n for (size_t idx = 0; idx < count; ++idx) {\n const void* addr = addrs[idx];\n const char* symbol = \"\";\n\n Dl_info info;\n if (dladdr(addr, &info) && info.dli_sname) {\n symbol = info.dli_sname;\n }\n\n os << \" #\" << std::setw(2) << idx << \": \" << addr << \" \" << symbol << \"\\n\";\n }\n }\n\n} \/\/ namespace\n\nvoid printStackTrace(unsigned int max_frames)\n{\n void* buffer[max_frames];\n std::ostringstream oss;\n\n dumpBacktrace(oss, buffer, captureBacktrace(buffer, max_frames));\n\n __android_log_print(ANDROID_LOG_DEBUG, TAG, \"%s\", oss.str().c_str());\n}\n<commit_msg>Use log macro for stack trace<commit_after>\/* Copyright 2015 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"util\/gvr_log.h\"\n#include \"gvr_cpp_stack_trace.h\"\n\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\n#include <unwind.h>\n#include <dlfcn.h>\n\nnamespace {\n\n struct BacktraceState\n {\n void** current;\n void** end;\n };\n\n static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg)\n {\n BacktraceState* state = static_cast<BacktraceState*>(arg);\n uintptr_t pc = _Unwind_GetIP(context);\n if (pc) {\n if (state->current == state->end) {\n return _URC_END_OF_STACK;\n } else {\n *state->current++ = reinterpret_cast<void*>(pc);\n }\n }\n return _URC_NO_REASON;\n }\n\n size_t captureBacktrace(void** buffer, size_t max)\n {\n BacktraceState state = {buffer, buffer + max};\n _Unwind_Backtrace(unwindCallback, &state);\n\n return state.current - buffer;\n }\n\n void dumpBacktrace(std::ostream& os, void** addrs, size_t count)\n {\n for (size_t idx = 0; idx < count; ++idx) {\n const void* addr = addrs[idx];\n const char* symbol = \"\";\n\n Dl_info info;\n if (dladdr(addr, &info) && info.dli_sname) {\n symbol = info.dli_sname;\n }\n\n os << \" #\" << std::setw(2) << idx << \": \" << addr << \" \" << symbol << \"\\n\";\n }\n }\n\n} \/\/ namespace\n\nvoid printStackTrace(unsigned int max_frames)\n{\n void* buffer[max_frames];\n std::ostringstream oss;\n\n dumpBacktrace(oss, buffer, captureBacktrace(buffer, max_frames));\n\n LOGD(\"%s\", oss.str().c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n#include \"valueproperties.hxx\"\n#include \"strings.hxx\"\n#include <com\/sun\/star\/form\/FormComponentType.hpp>\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::form;\n\n \/\/=====================================================================\n \/\/= OValuePropertiesMetaData\n \/\/=====================================================================\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getValuePropertyNames(\n OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,\n sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)\n {\n \/\/ reset the pointers in case we can't determine the property names\n _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::TEXTFIELD:\n if (OControlElement::FORMATTED_TEXT == _eType)\n {\n _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;\n _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;\n }\n else\n {\n if (OControlElement::PASSWORD != _eType)\n \/\/ no CurrentValue\" for passwords\n _rpCurrentValuePropertyName = PROPERTY_TEXT;\n _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;\n }\n break;\n\n case FormComponentType::DATEFIELD:\n _rpCurrentValuePropertyName = PROPERTY_DATE;\n _rpValuePropertyName = PROPERTY_DEFAULT_DATE;\n break;\n\n case FormComponentType::TIMEFIELD:\n _rpCurrentValuePropertyName = PROPERTY_TIME;\n _rpValuePropertyName = PROPERTY_DEFAULT_TIME;\n break;\n\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n _rpCurrentValuePropertyName = PROPERTY_VALUE;\n _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;\n break;\n\n case FormComponentType::PATTERNFIELD:\n case FormComponentType::FILECONTROL:\n case FormComponentType::COMBOBOX:\n _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;\n \/\/ NO BREAK!!\n case FormComponentType::COMMANDBUTTON:\n _rpCurrentValuePropertyName = PROPERTY_TEXT;\n break;\n\n case FormComponentType::CHECKBOX:\n case FormComponentType::RADIOBUTTON:\n _rpValuePropertyName = PROPERTY_REFVALUE;\n break;\n\n case FormComponentType::HIDDENCONTROL:\n _rpValuePropertyName = PROPERTY_HIDDEN_VALUE;\n break;\n\n case FormComponentType::SCROLLBAR:\n _rpCurrentValuePropertyName = PROPERTY_SCROLLVALUE;\n _rpValuePropertyName = PROPERTY_SCROLLVALUE_DEFAULT;\n break;\n\n case FormComponentType::SPINBUTTON:\n _rpCurrentValuePropertyName = PROPERTY_SPINVALUE;\n _rpValuePropertyName = PROPERTY_DEFAULT_SPINVALUE;\n break;\n }\n }\n\n\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,\n sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)\n {\n _rpMinValuePropertyName = _rpMinValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::DATEFIELD:\n _rpMinValuePropertyName = PROPERTY_DATE_MIN;\n _rpMaxValuePropertyName = PROPERTY_DATE_MAX;\n break;\n\n case FormComponentType::TIMEFIELD:\n _rpMinValuePropertyName = PROPERTY_TIME_MIN;\n _rpMaxValuePropertyName = PROPERTY_TIME_MAX;\n break;\n\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n _rpMinValuePropertyName = PROPERTY_VALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;\n break;\n\n case FormComponentType::TEXTFIELD:\n _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;\n _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;\n break;\n\n case FormComponentType::SCROLLBAR:\n _rpMinValuePropertyName = PROPERTY_SCROLLVALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_SCROLLVALUE_MAX;\n break;\n\n case FormComponentType::SPINBUTTON:\n _rpMinValuePropertyName = PROPERTY_SPINVALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_SPINVALUE_MAX;\n break;\n }\n }\n\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getRuntimeValuePropertyNames(\n OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,\n sal_Char const * & _rpValuePropertyName, sal_Char const * & _rpDefaultValuePropertyName )\n {\n \/\/ reset the pointers in case we can't determine the property names\n _rpValuePropertyName = _rpDefaultValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::TEXTFIELD:\n if (OControlElement::FORMATTED_TEXT == _eType)\n {\n _rpValuePropertyName = PROPERTY_EFFECTIVE_VALUE;\n _rpDefaultValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;\n }\n else\n {\n _rpValuePropertyName = PROPERTY_TEXT;\n _rpDefaultValuePropertyName = PROPERTY_DEFAULT_TEXT;\n }\n break;\n\n case FormComponentType::DATEFIELD:\n case FormComponentType::TIMEFIELD:\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n case FormComponentType::PATTERNFIELD:\n case FormComponentType::FILECONTROL:\n case FormComponentType::COMBOBOX:\n case FormComponentType::SCROLLBAR:\n case FormComponentType::SPINBUTTON:\n \/\/ For these types, the runtime properties are the same as the ones which in the XML\n \/\/ stream are named \"value properties\"\n getValuePropertyNames( _eType, _nFormComponentType, _rpValuePropertyName, _rpDefaultValuePropertyName );\n break;\n\n case FormComponentType::CHECKBOX:\n case FormComponentType::RADIOBUTTON:\n _rpValuePropertyName = PROPERTY_STATE;\n _rpDefaultValuePropertyName = PROPERTY_DEFAULT_STATE;\n break;\n }\n }\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n\n<commit_msg>sw33bf04: #i111381#: OValuePropertiesMetaData: apply patch by tono<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmloff.hxx\"\n#include \"valueproperties.hxx\"\n#include \"strings.hxx\"\n#include <com\/sun\/star\/form\/FormComponentType.hpp>\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::form;\n\n \/\/=====================================================================\n \/\/= OValuePropertiesMetaData\n \/\/=====================================================================\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getValuePropertyNames(\n OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,\n sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)\n {\n \/\/ reset the pointers in case we can't determine the property names\n _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::TEXTFIELD:\n if (OControlElement::FORMATTED_TEXT == _eType)\n {\n _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;\n _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;\n }\n else\n {\n if (OControlElement::PASSWORD != _eType)\n \/\/ no CurrentValue\" for passwords\n _rpCurrentValuePropertyName = PROPERTY_TEXT;\n _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;\n }\n break;\n\n case FormComponentType::DATEFIELD:\n _rpCurrentValuePropertyName = PROPERTY_DATE;\n _rpValuePropertyName = PROPERTY_DEFAULT_DATE;\n break;\n\n case FormComponentType::TIMEFIELD:\n _rpCurrentValuePropertyName = PROPERTY_TIME;\n _rpValuePropertyName = PROPERTY_DEFAULT_TIME;\n break;\n\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n _rpCurrentValuePropertyName = PROPERTY_VALUE;\n _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;\n break;\n\n case FormComponentType::PATTERNFIELD:\n case FormComponentType::FILECONTROL:\n case FormComponentType::COMBOBOX:\n _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;\n \/\/ NO BREAK!!\n case FormComponentType::COMMANDBUTTON:\n _rpCurrentValuePropertyName = PROPERTY_TEXT;\n break;\n\n case FormComponentType::CHECKBOX:\n case FormComponentType::RADIOBUTTON:\n _rpValuePropertyName = PROPERTY_REFVALUE;\n break;\n\n case FormComponentType::HIDDENCONTROL:\n _rpValuePropertyName = PROPERTY_HIDDEN_VALUE;\n break;\n\n case FormComponentType::SCROLLBAR:\n _rpCurrentValuePropertyName = PROPERTY_SCROLLVALUE;\n _rpValuePropertyName = PROPERTY_SCROLLVALUE_DEFAULT;\n break;\n\n case FormComponentType::SPINBUTTON:\n _rpCurrentValuePropertyName = PROPERTY_SPINVALUE;\n _rpValuePropertyName = PROPERTY_DEFAULT_SPINVALUE;\n break;\n }\n }\n\n\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,\n sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)\n {\n _rpMinValuePropertyName = _rpMaxValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::DATEFIELD:\n _rpMinValuePropertyName = PROPERTY_DATE_MIN;\n _rpMaxValuePropertyName = PROPERTY_DATE_MAX;\n break;\n\n case FormComponentType::TIMEFIELD:\n _rpMinValuePropertyName = PROPERTY_TIME_MIN;\n _rpMaxValuePropertyName = PROPERTY_TIME_MAX;\n break;\n\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n _rpMinValuePropertyName = PROPERTY_VALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;\n break;\n\n case FormComponentType::TEXTFIELD:\n _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;\n _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;\n break;\n\n case FormComponentType::SCROLLBAR:\n _rpMinValuePropertyName = PROPERTY_SCROLLVALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_SCROLLVALUE_MAX;\n break;\n\n case FormComponentType::SPINBUTTON:\n _rpMinValuePropertyName = PROPERTY_SPINVALUE_MIN;\n _rpMaxValuePropertyName = PROPERTY_SPINVALUE_MAX;\n break;\n }\n }\n\n \/\/---------------------------------------------------------------------\n void OValuePropertiesMetaData::getRuntimeValuePropertyNames(\n OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,\n sal_Char const * & _rpValuePropertyName, sal_Char const * & _rpDefaultValuePropertyName )\n {\n \/\/ reset the pointers in case we can't determine the property names\n _rpValuePropertyName = _rpDefaultValuePropertyName = NULL;\n switch (_nFormComponentType)\n {\n case FormComponentType::TEXTFIELD:\n if (OControlElement::FORMATTED_TEXT == _eType)\n {\n _rpValuePropertyName = PROPERTY_EFFECTIVE_VALUE;\n _rpDefaultValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;\n }\n else\n {\n _rpValuePropertyName = PROPERTY_TEXT;\n _rpDefaultValuePropertyName = PROPERTY_DEFAULT_TEXT;\n }\n break;\n\n case FormComponentType::DATEFIELD:\n case FormComponentType::TIMEFIELD:\n case FormComponentType::NUMERICFIELD:\n case FormComponentType::CURRENCYFIELD:\n case FormComponentType::PATTERNFIELD:\n case FormComponentType::FILECONTROL:\n case FormComponentType::COMBOBOX:\n case FormComponentType::SCROLLBAR:\n case FormComponentType::SPINBUTTON:\n \/\/ For these types, the runtime properties are the same as the ones which in the XML\n \/\/ stream are named \"value properties\"\n getValuePropertyNames( _eType, _nFormComponentType, _rpValuePropertyName, _rpDefaultValuePropertyName );\n break;\n\n case FormComponentType::CHECKBOX:\n case FormComponentType::RADIOBUTTON:\n _rpValuePropertyName = PROPERTY_STATE;\n _rpDefaultValuePropertyName = PROPERTY_DEFAULT_STATE;\n break;\n }\n }\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: saxhelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2007-02-14 15:32:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmlsecurity.hxx\"\n\n#include <rtl\/ustring.hxx>\n\n#include \"saxhelper.hxx\"\n#include \"libxml\/parserInternals.h\"\n\n#ifndef XMLSEC_NO_XSLT\n#include \"libxslt\/xslt.h\"\n#endif\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssxs = com::sun::star::xml::sax;\nnamespace cssxcsax = com::sun::star::xml::csax;\n\n\/**\n * The return value is NULL terminated. The application has the responsibilty to\n * deallocte the return value.\n *\/\nxmlChar* ous_to_xmlstr( const rtl::OUString& oustr )\n{\n rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;\n return xmlStrndup( ( xmlChar* )ostr.getStr(), ( int )ostr.getLength() ) ;\n}\n\n\/**\n * The return value is NULL terminated. The application has the responsibilty to\n * deallocte the return value.\n *\/\nxmlChar* ous_to_nxmlstr( const rtl::OUString& oustr, int& length )\n{\n rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;\n length = ostr.getLength();\n\n return xmlStrndup( ( xmlChar* )ostr.getStr(), length ) ;\n}\n\n\/**\n * The input parameter isn't necessaryly NULL terminated.\n *\/\nrtl::OUString xmlchar_to_ous( const xmlChar* pChar, int length )\n{\n if( pChar != NULL )\n {\n return rtl::OUString( ( sal_Char* )pChar , length , RTL_TEXTENCODING_UTF8 ) ;\n }\n else\n {\n return rtl::OUString() ;\n }\n}\n\n\/**\n * The input parameter is NULL terminated\n *\/\nrtl::OUString xmlstr_to_ous( const xmlChar* pStr )\n{\n if( pStr != NULL )\n {\n return xmlchar_to_ous( pStr , xmlStrlen( pStr ) ) ;\n }\n else\n {\n return rtl::OUString() ;\n }\n}\n\n\/**\n * The return value and the referenced value must be NULL terminated.\n * The application has the responsibilty to deallocte the return value.\n *\/\nconst xmlChar** attrlist_to_nxmlstr( const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )\n{\n xmlChar* attname = NULL ;\n xmlChar* attvalue = NULL ;\n const xmlChar** attrs = NULL ;\n rtl::OUString oustr ;\n\n sal_Int32 nLength = aAttributes.getLength();;\n\n if( nLength != 0 )\n {\n attrs = ( const xmlChar** )xmlMalloc( ( nLength * 2 + 2 ) * sizeof( xmlChar* ) ) ;\n }\n else\n {\n return NULL ;\n }\n\n for( int i = 0 , j = 0 ; j < nLength ; ++j )\n {\n attname = ous_to_xmlstr( aAttributes[j].sName ) ;\n attvalue = ous_to_xmlstr( aAttributes[j].sValue ) ;\n\n if( attname != NULL && attvalue != NULL )\n {\n attrs[i++] = attname ;\n attrs[i++] = attvalue ;\n attrs[i] = NULL ;\n attrs[i+1] = NULL ;\n }\n else\n {\n if( attname != NULL )\n xmlFree( attname ) ;\n if( attvalue != NULL )\n xmlFree( attvalue ) ;\n }\n }\n\n return attrs ;\n}\n\n\/**\n * Constructor\n *\n * In this constructor, a libxml sax parser context is initialized. a libxml\n * default sax handler is initialized with the context.\n *\/\nSAXHelper::SAXHelper( )\n : m_pParserCtxt( NULL ),\n m_pSaxHandler( NULL )\n{\n xmlInitParser() ;\n LIBXML_TEST_VERSION ;\n\n \/*\n * compile error:\n * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS ;\n *\/\n xmlSubstituteEntitiesDefault( 1 ) ;\n\n#ifndef XMLSEC_NO_XSLT\n xmlIndentTreeOutput = 1 ;\n#endif \/* XMLSEC_NO_XSLT *\/\n\n m_pParserCtxt = xmlNewParserCtxt() ;\n\n \/*\n * i41748\n *\n * mmi : re-initialize the SAX handler to version 1\n *\/\n\n xmlSAXVersion(m_pParserCtxt->sax, 1);\n\n \/* end *\/\n\n if( m_pParserCtxt->inputTab[0] != NULL )\n {\n m_pParserCtxt->inputTab[0] = NULL ;\n }\n\n if( m_pParserCtxt == NULL )\n {\n#ifndef XMLSEC_NO_XSLT\n xsltCleanupGlobals() ;\n#endif\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n throw cssu::RuntimeException() ;\n }\n else if( m_pParserCtxt->sax == NULL )\n {\n xmlFreeParserCtxt( m_pParserCtxt ) ;\n\n#ifndef XMLSEC_NO_XSLT\n xsltCleanupGlobals() ;\n#endif\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n m_pParserCtxt = NULL ;\n throw cssu::RuntimeException() ;\n }\n else\n {\n m_pSaxHandler = m_pParserCtxt->sax ;\n\n \/\/Adjust the context\n m_pParserCtxt->recovery = 1 ;\n }\n}\n\n\/**\n * Destructor\n *\n * In this destructor, a libxml sax parser context is desturcted. The XML tree\n * in the context is not deallocated because the tree is bind with a document\n * model by the setTargetDocument method, which delegate the target document to\n * destruct the xml tree.\n *\/\nSAXHelper::~SAXHelper() {\n if( m_pParserCtxt != NULL )\n {\n \/*\n * In the situation that no object refer the Document, this destructor\n * must deallocate the Document memory\n *\/\n if( m_pSaxHandler == m_pParserCtxt->sax )\n {\n m_pSaxHandler = NULL ;\n }\n\n xmlFreeParserCtxt( m_pParserCtxt ) ;\n m_pParserCtxt = NULL ;\n }\n\n if( m_pSaxHandler != NULL )\n {\n xmlFree( m_pSaxHandler ) ;\n m_pSaxHandler = NULL ;\n }\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n}\n\nxmlNodePtr SAXHelper::getCurrentNode()\n{\n return m_pParserCtxt->node;\n}\n\nvoid SAXHelper::setCurrentNode(const xmlNodePtr pNode)\n{\n \/*\n * This is really a black trick.\n * When the current node is replaced, the nodeTab\n * stack's top has to been replaced with the same\n * node, in order to make compatibility.\n *\/\n m_pParserCtxt->nodeTab[m_pParserCtxt->nodeNr - 1]\n = m_pParserCtxt->node\n = pNode;\n}\n\nxmlDocPtr SAXHelper::getDocument()\n{\n return m_pParserCtxt->myDoc;\n}\n\n\/**\n * XDocumentHandler -- start an xml document\n *\/\nvoid SAXHelper::startDocument( void )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n \/*\n * Adjust inputTab\n *\/\n xmlParserInputPtr pInput = xmlNewInputStream( m_pParserCtxt ) ;\n\n if( m_pParserCtxt->inputTab != NULL && m_pParserCtxt->inputMax != 0 )\n {\n m_pParserCtxt->inputTab[0] = pInput ;\n m_pParserCtxt->input = pInput ;\n }\n\n m_pSaxHandler->startDocument( m_pParserCtxt ) ;\n\n if( m_pParserCtxt == NULL || m_pParserCtxt->myDoc == NULL )\n {\n throw cssu::RuntimeException() ;\n }\n}\n\n\/**\n * XDocumentHandler -- end an xml document\n *\/\nvoid SAXHelper::endDocument( void )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n m_pSaxHandler->endDocument( m_pParserCtxt ) ;\n}\n\n\/**\n * XDocumentHandler -- start an xml element\n *\/\nvoid SAXHelper::startElement(\n const rtl::OUString& aName,\n const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* fullName = NULL ;\n const xmlChar** attrs = NULL ;\n\n fullName = ous_to_xmlstr( aName ) ;\n attrs = attrlist_to_nxmlstr( aAttributes ) ;\n\n if( fullName != NULL || attrs != NULL )\n {\n m_pSaxHandler->startElement( m_pParserCtxt , fullName , attrs ) ;\n }\n\n if( fullName != NULL )\n {\n xmlFree( ( xmlChar* )fullName ) ;\n fullName = NULL ;\n }\n\n if( attrs != NULL )\n {\n for( int i = 0 ; attrs[i] != NULL ; ++i )\n {\n xmlFree( ( xmlChar* )attrs[i] ) ;\n attrs[i] = NULL ;\n }\n\n xmlFree( ( void* ) attrs ) ;\n attrs = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- end an xml element\n *\/\nvoid SAXHelper::endElement( const rtl::OUString& aName )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n xmlChar* fullname = NULL ;\n\n fullname = ous_to_xmlstr( aName ) ;\n m_pSaxHandler->endElement( m_pParserCtxt , fullname ) ;\n\n if( fullname != NULL )\n {\n xmlFree( ( xmlChar* )fullname ) ;\n fullname = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- an xml element or cdata characters\n *\/\nvoid SAXHelper::characters( const rtl::OUString& aChars )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* chars = NULL ;\n int length = 0 ;\n\n chars = ous_to_nxmlstr( aChars, length ) ;\n m_pSaxHandler->characters( m_pParserCtxt , chars , length ) ;\n\n if( chars != NULL )\n {\n xmlFree( ( xmlChar* )chars ) ;\n }\n}\n\n\/**\n * XDocumentHandler -- ignorable xml white space\n *\/\nvoid SAXHelper::ignorableWhitespace( const rtl::OUString& aWhitespaces )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* chars = NULL ;\n int length = 0 ;\n\n chars = ous_to_nxmlstr( aWhitespaces, length ) ;\n m_pSaxHandler->ignorableWhitespace( m_pParserCtxt , chars , length ) ;\n\n if( chars != NULL )\n {\n xmlFree( ( xmlChar* )chars ) ;\n }\n}\n\n\/**\n * XDocumentHandler -- preaorocessing instruction\n *\/\nvoid SAXHelper::processingInstruction(\n const rtl::OUString& aTarget,\n const rtl::OUString& aData )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n xmlChar* target = NULL ;\n xmlChar* data = NULL ;\n\n target = ous_to_xmlstr( aTarget ) ;\n data = ous_to_xmlstr( aData ) ;\n\n m_pSaxHandler->processingInstruction( m_pParserCtxt , target , data ) ;\n\n if( target != NULL )\n {\n xmlFree( ( xmlChar* )target ) ;\n target = NULL ;\n }\n\n if( data != NULL )\n {\n xmlFree( ( xmlChar* )data ) ;\n data = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- set document locator\n * In this case, locator is useless.\n *\/\nvoid SAXHelper::setDocumentLocator(\n const cssu::Reference< cssxs::XLocator > & xLocator )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n \/\/--Pseudo code if necessary\n \/\/--m_pSaxLocator is a member defined as xmlSAXHabdlerPtr\n \/\/--m_pSaxLocatorHdl is a member defined as Sax_Locator\n\n \/\/if( m_pSaxLocator != NULL ) {\n \/\/ \/\/Deallocate the memory\n \/\/}\n \/\/if( m_pSaxLocatorHdl != NULL ) {\n \/\/ \/\/Deallocate the memory\n \/\/}\n\n \/\/m_pSaxLocatorHdl = new Sax_Locator( xLocator ) ;\n \/\/m_pSaxLocator = { m_pSaxLocatorHdl->getPublicId , m_pSaxLocatorHdl->getSystemId , m_pSaxLocatorHdl->getLineNumber , m_pSaxLocatorHdl->getColumnNumber } ;\n\n \/\/m_pSaxHandler->setDocumentLocator( m_pParserCtxt , m_pSaxLocator ) ;\n}\n\n<commit_msg>INTEGRATION: CWS jl51 (1.4.30); FILE MERGED 2007\/04\/02 14:04:00 jl 1.4.30.2: RESYNC: (1.4-1.5); FILE MERGED 2007\/02\/05 13:54:21 jl 1.4.30.1: #i69228 warning free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: saxhelper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: ihi $ $Date: 2007-04-17 10:22:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmlsecurity.hxx\"\n\n#include <rtl\/ustring.hxx>\n\n#include \"saxhelper.hxx\"\n#include \"libxml\/parserInternals.h\"\n\n#ifndef XMLSEC_NO_XSLT\n#include \"libxslt\/xslt.h\"\n#endif\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssxs = com::sun::star::xml::sax;\nnamespace cssxcsax = com::sun::star::xml::csax;\n\n\/**\n * The return value is NULL terminated. The application has the responsibilty to\n * deallocte the return value.\n *\/\nxmlChar* ous_to_xmlstr( const rtl::OUString& oustr )\n{\n rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;\n return xmlStrndup( ( xmlChar* )ostr.getStr(), ( int )ostr.getLength() ) ;\n}\n\n\/**\n * The return value is NULL terminated. The application has the responsibilty to\n * deallocte the return value.\n *\/\nxmlChar* ous_to_nxmlstr( const rtl::OUString& oustr, int& length )\n{\n rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;\n length = ostr.getLength();\n\n return xmlStrndup( ( xmlChar* )ostr.getStr(), length ) ;\n}\n\n\/**\n * The input parameter isn't necessaryly NULL terminated.\n *\/\nrtl::OUString xmlchar_to_ous( const xmlChar* pChar, int length )\n{\n if( pChar != NULL )\n {\n return rtl::OUString( ( sal_Char* )pChar , length , RTL_TEXTENCODING_UTF8 ) ;\n }\n else\n {\n return rtl::OUString() ;\n }\n}\n\n\/**\n * The input parameter is NULL terminated\n *\/\nrtl::OUString xmlstr_to_ous( const xmlChar* pStr )\n{\n if( pStr != NULL )\n {\n return xmlchar_to_ous( pStr , xmlStrlen( pStr ) ) ;\n }\n else\n {\n return rtl::OUString() ;\n }\n}\n\n\/**\n * The return value and the referenced value must be NULL terminated.\n * The application has the responsibilty to deallocte the return value.\n *\/\nconst xmlChar** attrlist_to_nxmlstr( const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )\n{\n xmlChar* attname = NULL ;\n xmlChar* attvalue = NULL ;\n const xmlChar** attrs = NULL ;\n rtl::OUString oustr ;\n\n sal_Int32 nLength = aAttributes.getLength();;\n\n if( nLength != 0 )\n {\n attrs = ( const xmlChar** )xmlMalloc( ( nLength * 2 + 2 ) * sizeof( xmlChar* ) ) ;\n }\n else\n {\n return NULL ;\n }\n\n for( int i = 0 , j = 0 ; j < nLength ; ++j )\n {\n attname = ous_to_xmlstr( aAttributes[j].sName ) ;\n attvalue = ous_to_xmlstr( aAttributes[j].sValue ) ;\n\n if( attname != NULL && attvalue != NULL )\n {\n attrs[i++] = attname ;\n attrs[i++] = attvalue ;\n attrs[i] = NULL ;\n attrs[i+1] = NULL ;\n }\n else\n {\n if( attname != NULL )\n xmlFree( attname ) ;\n if( attvalue != NULL )\n xmlFree( attvalue ) ;\n }\n }\n\n return attrs ;\n}\n\n\/**\n * Constructor\n *\n * In this constructor, a libxml sax parser context is initialized. a libxml\n * default sax handler is initialized with the context.\n *\/\nSAXHelper::SAXHelper( )\n : m_pParserCtxt( NULL ),\n m_pSaxHandler( NULL )\n{\n xmlInitParser() ;\n LIBXML_TEST_VERSION ;\n\n \/*\n * compile error:\n * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS ;\n *\/\n xmlSubstituteEntitiesDefault( 1 ) ;\n\n#ifndef XMLSEC_NO_XSLT\n xmlIndentTreeOutput = 1 ;\n#endif \/* XMLSEC_NO_XSLT *\/\n\n m_pParserCtxt = xmlNewParserCtxt() ;\n\n \/*\n * i41748\n *\n * mmi : re-initialize the SAX handler to version 1\n *\/\n\n xmlSAXVersion(m_pParserCtxt->sax, 1);\n\n \/* end *\/\n\n if( m_pParserCtxt->inputTab[0] != NULL )\n {\n m_pParserCtxt->inputTab[0] = NULL ;\n }\n\n if( m_pParserCtxt == NULL )\n {\n#ifndef XMLSEC_NO_XSLT\n xsltCleanupGlobals() ;\n#endif\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n throw cssu::RuntimeException() ;\n }\n else if( m_pParserCtxt->sax == NULL )\n {\n xmlFreeParserCtxt( m_pParserCtxt ) ;\n\n#ifndef XMLSEC_NO_XSLT\n xsltCleanupGlobals() ;\n#endif\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n m_pParserCtxt = NULL ;\n throw cssu::RuntimeException() ;\n }\n else\n {\n m_pSaxHandler = m_pParserCtxt->sax ;\n\n \/\/Adjust the context\n m_pParserCtxt->recovery = 1 ;\n }\n}\n\n\/**\n * Destructor\n *\n * In this destructor, a libxml sax parser context is desturcted. The XML tree\n * in the context is not deallocated because the tree is bind with a document\n * model by the setTargetDocument method, which delegate the target document to\n * destruct the xml tree.\n *\/\nSAXHelper::~SAXHelper() {\n if( m_pParserCtxt != NULL )\n {\n \/*\n * In the situation that no object refer the Document, this destructor\n * must deallocate the Document memory\n *\/\n if( m_pSaxHandler == m_pParserCtxt->sax )\n {\n m_pSaxHandler = NULL ;\n }\n\n xmlFreeParserCtxt( m_pParserCtxt ) ;\n m_pParserCtxt = NULL ;\n }\n\n if( m_pSaxHandler != NULL )\n {\n xmlFree( m_pSaxHandler ) ;\n m_pSaxHandler = NULL ;\n }\n\/\/ see issue i74334, we cannot call xmlCleanupParser when libxml is still used\n\/\/ in other parts of the office.\n\/\/ xmlCleanupParser() ;\n}\n\nxmlNodePtr SAXHelper::getCurrentNode()\n{\n return m_pParserCtxt->node;\n}\n\nvoid SAXHelper::setCurrentNode(const xmlNodePtr pNode)\n{\n \/*\n * This is really a black trick.\n * When the current node is replaced, the nodeTab\n * stack's top has to been replaced with the same\n * node, in order to make compatibility.\n *\/\n m_pParserCtxt->nodeTab[m_pParserCtxt->nodeNr - 1]\n = m_pParserCtxt->node\n = pNode;\n}\n\nxmlDocPtr SAXHelper::getDocument()\n{\n return m_pParserCtxt->myDoc;\n}\n\n\/**\n * XDocumentHandler -- start an xml document\n *\/\nvoid SAXHelper::startDocument( void )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n \/*\n * Adjust inputTab\n *\/\n xmlParserInputPtr pInput = xmlNewInputStream( m_pParserCtxt ) ;\n\n if( m_pParserCtxt->inputTab != NULL && m_pParserCtxt->inputMax != 0 )\n {\n m_pParserCtxt->inputTab[0] = pInput ;\n m_pParserCtxt->input = pInput ;\n }\n\n m_pSaxHandler->startDocument( m_pParserCtxt ) ;\n\n if( m_pParserCtxt == NULL || m_pParserCtxt->myDoc == NULL )\n {\n throw cssu::RuntimeException() ;\n }\n}\n\n\/**\n * XDocumentHandler -- end an xml document\n *\/\nvoid SAXHelper::endDocument( void )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n m_pSaxHandler->endDocument( m_pParserCtxt ) ;\n}\n\n\/**\n * XDocumentHandler -- start an xml element\n *\/\nvoid SAXHelper::startElement(\n const rtl::OUString& aName,\n const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* fullName = NULL ;\n const xmlChar** attrs = NULL ;\n\n fullName = ous_to_xmlstr( aName ) ;\n attrs = attrlist_to_nxmlstr( aAttributes ) ;\n\n if( fullName != NULL || attrs != NULL )\n {\n m_pSaxHandler->startElement( m_pParserCtxt , fullName , attrs ) ;\n }\n\n if( fullName != NULL )\n {\n xmlFree( ( xmlChar* )fullName ) ;\n fullName = NULL ;\n }\n\n if( attrs != NULL )\n {\n for( int i = 0 ; attrs[i] != NULL ; ++i )\n {\n xmlFree( ( xmlChar* )attrs[i] ) ;\n attrs[i] = NULL ;\n }\n\n xmlFree( ( void* ) attrs ) ;\n attrs = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- end an xml element\n *\/\nvoid SAXHelper::endElement( const rtl::OUString& aName )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n xmlChar* fullname = NULL ;\n\n fullname = ous_to_xmlstr( aName ) ;\n m_pSaxHandler->endElement( m_pParserCtxt , fullname ) ;\n\n if( fullname != NULL )\n {\n xmlFree( ( xmlChar* )fullname ) ;\n fullname = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- an xml element or cdata characters\n *\/\nvoid SAXHelper::characters( const rtl::OUString& aChars )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* chars = NULL ;\n int length = 0 ;\n\n chars = ous_to_nxmlstr( aChars, length ) ;\n m_pSaxHandler->characters( m_pParserCtxt , chars , length ) ;\n\n if( chars != NULL )\n {\n xmlFree( ( xmlChar* )chars ) ;\n }\n}\n\n\/**\n * XDocumentHandler -- ignorable xml white space\n *\/\nvoid SAXHelper::ignorableWhitespace( const rtl::OUString& aWhitespaces )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n const xmlChar* chars = NULL ;\n int length = 0 ;\n\n chars = ous_to_nxmlstr( aWhitespaces, length ) ;\n m_pSaxHandler->ignorableWhitespace( m_pParserCtxt , chars , length ) ;\n\n if( chars != NULL )\n {\n xmlFree( ( xmlChar* )chars ) ;\n }\n}\n\n\/**\n * XDocumentHandler -- preaorocessing instruction\n *\/\nvoid SAXHelper::processingInstruction(\n const rtl::OUString& aTarget,\n const rtl::OUString& aData )\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n xmlChar* target = NULL ;\n xmlChar* data = NULL ;\n\n target = ous_to_xmlstr( aTarget ) ;\n data = ous_to_xmlstr( aData ) ;\n\n m_pSaxHandler->processingInstruction( m_pParserCtxt , target , data ) ;\n\n if( target != NULL )\n {\n xmlFree( ( xmlChar* )target ) ;\n target = NULL ;\n }\n\n if( data != NULL )\n {\n xmlFree( ( xmlChar* )data ) ;\n data = NULL ;\n }\n}\n\n\/**\n * XDocumentHandler -- set document locator\n * In this case, locator is useless.\n *\/\nvoid SAXHelper::setDocumentLocator(\n const cssu::Reference< cssxs::XLocator > &)\n throw( cssxs::SAXException , cssu::RuntimeException )\n{\n \/\/--Pseudo code if necessary\n \/\/--m_pSaxLocator is a member defined as xmlSAXHabdlerPtr\n \/\/--m_pSaxLocatorHdl is a member defined as Sax_Locator\n\n \/\/if( m_pSaxLocator != NULL ) {\n \/\/ \/\/Deallocate the memory\n \/\/}\n \/\/if( m_pSaxLocatorHdl != NULL ) {\n \/\/ \/\/Deallocate the memory\n \/\/}\n\n \/\/m_pSaxLocatorHdl = new Sax_Locator( xLocator ) ;\n \/\/m_pSaxLocator = { m_pSaxLocatorHdl->getPublicId , m_pSaxLocatorHdl->getSystemId , m_pSaxLocatorHdl->getLineNumber , m_pSaxLocatorHdl->getColumnNumber } ;\n\n \/\/m_pSaxHandler->setDocumentLocator( m_pParserCtxt , m_pSaxLocator ) ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <util\/ScanQuery.hpp>\n\n#include <util\/Record.hpp>\n\n#include <gtest\/gtest.h>\n\n#include <cstdint>\n#include <cstring>\n#include <memory>\n#include <vector>\n\nusing namespace tell::store;\n\nnamespace {\n\nint64_t gTupleLargenumber = 0x7FFFFFFF00000001;\n\nint32_t gTuple1Number = 12;\ncrossbow::string gTuple1Text = crossbow::string(\"Bacon ipsum dolor amet\");\n\nint32_t gTuple2Number = 13;\ncrossbow::string gTuple2Text = crossbow::string(\"t-bone chicken prosciutto\");\n\n\/**\n * @brief Test fixture for testing the ScanQuery class\n *\n * Creates a schema with 3 fields and creates two sample tuples.\n *\/\nclass ScanQueryTest : public ::testing::Test {\nprotected:\n ScanQueryTest() {\n mSchema.addField(FieldType::BIGINT, \"largenumber\", true);\n mSchema.addField(FieldType::INT, \"number\", true);\n mSchema.addField(FieldType::TEXT, \"text\", true);\n Record record(mSchema);\n\n GenericTuple insertTuple1({\n std::make_pair<crossbow::string, boost::any>(\"largenumber\", gTupleLargenumber),\n std::make_pair<crossbow::string, boost::any>(\"number\", gTuple1Number),\n std::make_pair<crossbow::string, boost::any>(\"text\", gTuple1Text),\n });\n mTuple1.reset(record.create(insertTuple1, mTuple1Size));\n\n GenericTuple insertTuple2({\n std::make_pair<crossbow::string, boost::any>(\"largenumber\", gTupleLargenumber),\n std::make_pair<crossbow::string, boost::any>(\"number\", gTuple2Number),\n std::make_pair<crossbow::string, boost::any>(\"text\", gTuple2Text),\n });\n mTuple2.reset(record.create(insertTuple2, mTuple2Size));\n }\n\n bool checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize, const Record& record);\n\n ScanQuery mQuery;\n std::vector<bool> mQueryBitMap;\n\n Schema mSchema;\n\n uint64_t mTuple1Size;\n std::unique_ptr<char[]> mTuple1;\n\n uint64_t mTuple2Size;\n std::unique_ptr<char[]> mTuple2;\n};\n\nbool ScanQueryTest::checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize,\n const Record& record) {\n mQueryBitMap.clear();\n mQuery.query = qbuffer;\n auto q = mQuery.check(tuple, mQueryBitMap, record);\n EXPECT_EQ(qbuffer + qsize, q) << \"Returned pointer does not point at end of qbuffer\";\n EXPECT_EQ(bitmapSize, mQueryBitMap.size()) << \"Query bitmap does not contain the expected number of elements\";\n\n for (auto res : mQueryBitMap) {\n if (!res) {\n return false;\n }\n }\n return true;\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for a query with no predicates\n *\n * The query is equal to \"SELECT *\".\n *\/\nTEST_F(ScanQueryTest, noPredicates) {\n Record record(mSchema);\n\n size_t qsize = 8;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 0, record));\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 0, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for a simple EQUAL predicate\n *\n * The query is equal to \"SELECT * WHERE number == 12\".\n *\/\nTEST_F(ScanQueryTest, singlePredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n\n size_t qsize = 24;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));\n EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for two simple EQUAL predicates linked by an AND.\n *\n * The query is equal to \"SELECT * WHERE number = 12 AND largenumber = 0x7FFFFFFF00000001\".\n *\/\nTEST_F(ScanQueryTest, andPredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n Record::id_t largenumberField;\n ASSERT_TRUE(record.idOf(\"largenumber\", largenumberField)) << \"Field not found\";\n\n size_t qsize = 48;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = largenumberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x1u;\n *reinterpret_cast<int64_t*>(qbuffer.get() + 40) = gTupleLargenumber;\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 2, record));\n EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 2, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR.\n *\n * The query is equal to \"SELECT * WHERE number = 12 OR text = 't-bone chicken prosciutto'\".\n *\/\nTEST_F(ScanQueryTest, orPredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n Record::id_t textField;\n ASSERT_TRUE(record.idOf(\"text\", textField)) << \"Field not found\";\n\n size_t qsize = 44 + gTuple2Text.length();\n qsize += ((qsize % 8 != 0) ? (8 - (qsize % 8)) : 0);\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = textField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x0u;\n *reinterpret_cast<uint32_t*>(qbuffer.get() + 40) = gTuple2Text.length();\n memcpy(qbuffer.get() + 44, gTuple2Text.data(), gTuple2Text.length());\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));\n}\n\n} \/\/ anonymous namespace\n<commit_msg>Add one more test case for ScanQuery<commit_after>#include <util\/ScanQuery.hpp>\n\n#include <util\/Record.hpp>\n\n#include <gtest\/gtest.h>\n\n#include <cstdint>\n#include <cstring>\n#include <memory>\n#include <vector>\n\nusing namespace tell::store;\n\nnamespace {\n\nint64_t gTupleLargenumber = 0x7FFFFFFF00000001;\n\nint32_t gTuple1Number = 12;\ncrossbow::string gTuple1Text = crossbow::string(\"Bacon ipsum dolor amet\");\n\nint32_t gTuple2Number = 13;\ncrossbow::string gTuple2Text = crossbow::string(\"t-bone chicken prosciutto\");\n\n\/**\n * @brief Test fixture for testing the ScanQuery class\n *\n * Creates a schema with 3 fields and creates two sample tuples.\n *\/\nclass ScanQueryTest : public ::testing::Test {\nprotected:\n ScanQueryTest() {\n mSchema.addField(FieldType::BIGINT, \"largenumber\", true);\n mSchema.addField(FieldType::INT, \"number\", true);\n mSchema.addField(FieldType::TEXT, \"text\", true);\n Record record(mSchema);\n\n GenericTuple insertTuple1({\n std::make_pair<crossbow::string, boost::any>(\"largenumber\", gTupleLargenumber),\n std::make_pair<crossbow::string, boost::any>(\"number\", gTuple1Number),\n std::make_pair<crossbow::string, boost::any>(\"text\", gTuple1Text),\n });\n mTuple1.reset(record.create(insertTuple1, mTuple1Size));\n\n GenericTuple insertTuple2({\n std::make_pair<crossbow::string, boost::any>(\"largenumber\", gTupleLargenumber),\n std::make_pair<crossbow::string, boost::any>(\"number\", gTuple2Number),\n std::make_pair<crossbow::string, boost::any>(\"text\", gTuple2Text),\n });\n mTuple2.reset(record.create(insertTuple2, mTuple2Size));\n }\n\n bool checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize, const Record& record);\n\n ScanQuery mQuery;\n std::vector<bool> mQueryBitMap;\n\n Schema mSchema;\n\n uint64_t mTuple1Size;\n std::unique_ptr<char[]> mTuple1;\n\n uint64_t mTuple2Size;\n std::unique_ptr<char[]> mTuple2;\n};\n\nbool ScanQueryTest::checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize,\n const Record& record) {\n mQueryBitMap.clear();\n mQuery.query = qbuffer;\n auto q = mQuery.check(tuple, mQueryBitMap, record);\n EXPECT_EQ(qbuffer + qsize, q) << \"Returned pointer does not point at end of qbuffer\";\n EXPECT_EQ(bitmapSize, mQueryBitMap.size()) << \"Query bitmap does not contain the expected number of elements\";\n\n for (auto res : mQueryBitMap) {\n if (!res) {\n return false;\n }\n }\n return true;\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for a query with no predicates\n *\n * The query is equal to \"SELECT *\".\n *\/\nTEST_F(ScanQueryTest, noPredicates) {\n Record record(mSchema);\n\n size_t qsize = 8;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 0, record));\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 0, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for a simple EQUAL predicate\n *\n * The query is equal to \"SELECT * WHERE number == 12\".\n *\/\nTEST_F(ScanQueryTest, singlePredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n\n size_t qsize = 24;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));\n EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for two simple EQUAL predicates linked by an AND.\n *\n * The query is equal to \"SELECT * WHERE number = 12 AND largenumber = 0x7FFFFFFF00000001\".\n *\/\nTEST_F(ScanQueryTest, andPredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n Record::id_t largenumberField;\n ASSERT_TRUE(record.idOf(\"largenumber\", largenumberField)) << \"Field not found\";\n\n size_t qsize = 48;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = largenumberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x1u;\n *reinterpret_cast<int64_t*>(qbuffer.get() + 40) = gTupleLargenumber;\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 2, record));\n EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 2, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR.\n *\n * The query is equal to \"SELECT * WHERE number = 12 OR text = 't-bone chicken prosciutto'\".\n *\/\nTEST_F(ScanQueryTest, orPredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n Record::id_t textField;\n ASSERT_TRUE(record.idOf(\"text\", textField)) << \"Field not found\";\n\n size_t qsize = 44 + gTuple2Text.length();\n qsize += ((qsize % 8 != 0) ? (8 - (qsize % 8)) : 0);\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = textField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x0u;\n *reinterpret_cast<uint32_t*>(qbuffer.get() + 40) = gTuple2Text.length();\n memcpy(qbuffer.get() + 44, gTuple2Text.data(), gTuple2Text.length());\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));\n}\n\n\/**\n * @class ScanQuery\n * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR on the same column.\n *\n * The query is equal to \"SELECT * WHERE number = 12 OR number = 13\".\n *\/\nTEST_F(ScanQueryTest, sameColumnPredicate) {\n Record record(mSchema);\n Record::id_t numberField;\n ASSERT_TRUE(record.idOf(\"number\", numberField)) << \"Field not found\";\n\n size_t qsize = 32;\n std::unique_ptr<char[]> qbuffer(new char[qsize]);\n memset(qbuffer.get(), 0, qsize);\n *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;\n *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x2u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;\n *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 24) = to_underlying(PredicateType::EQUAL);\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 25) = 0x0u;\n *reinterpret_cast<uint8_t*>(qbuffer.get() + 28) = gTuple2Number;\n\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));\n EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));\n}\n\n} \/\/ anonymous namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright(c) 2016, Jeff Hutchinson\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met :\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and \/ or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of threadGL nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/-----------------------------------------------------------------------------\n\n#include <stdio.h>\n#include \"jbl\/types.h\"\n#include \"jbl\/thread.h\"\n#include \"jbl\/mutex.h\"\n#include \"jbl\/conditionVariable.h\"\n#include \"jbl\/stack.h\"\n\nMutex mutex;\nS32 inc = 0;\n\nMutex pcMutex;\nConditionVariable cv;\nStack<S32> stack;\nMutex pcDoneMtx;\nbool pcDone = false;\n\nvoid incriment()\n{\n\tLockGuard g(&mutex);\n\t++inc;\n\tprintf(\"inc is now: %d\\n\", inc);\n}\n\nvoid myThreadFn(void *arg)\n{\n\tS32 x = *(S32*)arg;\n\tfor (S32 i = 0; i < x; ++i)\n\t\tincriment();\n\tThread::sleep(1000);\n}\n\nvoid producer(void *)\n{\n\tfor (S32 i = 0; i < 20; ++i)\n\t{\n\t\tpcMutex.lock();\n\t\tstack.push(i);\n\t\tpcMutex.unlock();\n\t\tcv.signal();\n\t\tThread::sleep(500);\n\t}\n\tpcDoneMtx.lock();\n\tpcDone = true;\n\tcv.signal();\n\tpcDoneMtx.unlock();\n}\n\nvoid consumer(void *)\n{\n\twhile (true)\n\t{\n\t\tpcMutex.lock();\n\t\tcv.wait(&pcMutex);\n\t\n\t\tpcDoneMtx.lock();\n\t\tif (pcDone)\n\t\t{\n\t\t\tpcDoneMtx.unlock();\n\t\t\tpcMutex.unlock();\n\t\t\tbreak;\n\t\t}\n\t\tpcDoneMtx.unlock();\n\t\n\t\tprintf(\"%d\\n\", stack.getTop());\n\t\tstack.pop();\n\t\tpcMutex.unlock();\n\t}\n}\n\nS32 main(S32 argc, const char **argv)\n{\n\tS32 x = 20;\n\tThread t(myThreadFn, &x);\n\tThread t2(myThreadFn, &x);\n\tt.join();\n\tt2.join();\n\n\tprintf(\"Testing producer consumer condition variable.\\n\");\n\tThread c(consumer, nullptr);\n\tThread p(producer, nullptr);\n\tc.join();\n\tp.join();\n\t\n#ifdef _WIN32\n system(\"pause\");\n#endif\n\treturn 0;\n}<commit_msg>preven spurious wakeup. Also, we only read pcDone in the consumer, so no need to have a lock around it.<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright(c) 2016, Jeff Hutchinson\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met :\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and \/ or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of threadGL nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/-----------------------------------------------------------------------------\n\n#include <stdio.h>\n#include \"jbl\/types.h\"\n#include \"jbl\/thread.h\"\n#include \"jbl\/mutex.h\"\n#include \"jbl\/conditionVariable.h\"\n#include \"jbl\/stack.h\"\n\nMutex mutex;\nS32 inc = 0;\n\nMutex pcMutex;\nConditionVariable cv;\nStack<S32> stack;\nvolatile bool pcDone = false;\n\nvoid incriment()\n{\n\tLockGuard g(&mutex);\n\t++inc;\n\tprintf(\"inc is now: %d\\n\", inc);\n}\n\nvoid myThreadFn(void *arg)\n{\n\tS32 x = *(S32*)arg;\n\tfor (S32 i = 0; i < x; ++i)\n\t\tincriment();\n\tThread::sleep(1000);\n}\n\nvoid producer(void *)\n{\n\tfor (S32 i = 0; i < 20; ++i)\n\t{\n\t\tpcMutex.lock();\n\t\tstack.push(i);\n\t\tpcMutex.unlock();\n\t\tcv.signal();\n\t\tThread::sleep(750);\n\t}\n\tpcDone = true;\n\tcv.signal();\n}\n\nvoid consumer(void *)\n{\n\twhile (true)\n\t{\n\t\tpcMutex.lock();\n\t\twhile (!pcDone && stack.isEmpty())\n\t\t\tcv.wait(&pcMutex);\n\n\t\tif (pcDone)\n\t\t{\n\t\t\tpcMutex.unlock();\n\t\t\tbreak;\n\t\t}\n\t\n\t\tprintf(\"%d\\n\", stack.getTop());\n\t\tstack.pop();\n\t\tpcMutex.unlock();\n\t}\n}\n\nS32 main(S32 argc, const char **argv)\n{\n\tS32 x = 20;\n\tThread t(myThreadFn, &x);\n\tThread t2(myThreadFn, &x);\n\tt.join();\n\tt2.join();\n\n\tprintf(\"Testing producer consumer condition variable.\\n\");\n\tThread c(consumer, nullptr);\n\tThread p(producer, nullptr);\n\tc.join();\n\tp.join();\n\t\n#ifdef _WIN32\n system(\"pause\");\n#endif\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * MIT License\n *\n * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <signal.h>\n#include <string>\n#include <iostream>\n#include \"Util\/MD5.h\"\n#include \"Util\/logger.h\"\n#include \"Http\/WebSocketClient.h\"\nusing namespace std;\nusing namespace toolkit;\nusing namespace mediakit;\n\nclass EchoTcpClient : public TcpClient {\npublic:\n EchoTcpClient(const EventPoller::Ptr &poller = nullptr){\n InfoL;\n }\n ~EchoTcpClient() override {\n InfoL;\n }\nprotected:\n void onRecv(const Buffer::Ptr &pBuf) override {\n DebugL << pBuf->toString();\n }\n \/\/被动断开连接回调\n void onErr(const SockException &ex) override {\n WarnL << ex.what();\n }\n \/\/tcp连接成功后每2秒触发一次该事件\n void onManager() override {\n send(\"echo test!\");\n DebugL << \"send echo test\";\n }\n \/\/连接服务器结果回调\n void onConnect(const SockException &ex) override{\n DebugL << ex.what();\n }\n\n \/\/数据全部发送完毕后回调\n void onFlush() override{\n DebugL;\n }\n};\n\nint main(int argc, char *argv[]) {\n \/\/设置退出信号处理函数\n static semaphore sem;\n signal(SIGINT, [](int) { sem.post(); });\/\/ 设置退出信号\n\n \/\/设置日志\n Logger::Instance().add(std::make_shared<ConsoleChannel>());\n Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());\n\n WebSocketClient<EchoTcpClient>::Ptr client = std::make_shared<WebSocketClient<EchoTcpClient> >();\n client->startConnect(\"127.0.0.1\",80);\n\n sem.wait();\n return 0;\n}\n\n<commit_msg>替换websocket测试服务器<commit_after>\/*\n * MIT License\n *\n * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <signal.h>\n#include <string>\n#include <iostream>\n#include \"Util\/MD5.h\"\n#include \"Util\/logger.h\"\n#include \"Http\/WebSocketClient.h\"\nusing namespace std;\nusing namespace toolkit;\nusing namespace mediakit;\n\nclass EchoTcpClient : public TcpClient {\npublic:\n EchoTcpClient(const EventPoller::Ptr &poller = nullptr){\n InfoL;\n }\n ~EchoTcpClient() override {\n InfoL;\n }\nprotected:\n void onRecv(const Buffer::Ptr &pBuf) override {\n DebugL << pBuf->toString();\n }\n \/\/被动断开连接回调\n void onErr(const SockException &ex) override {\n WarnL << ex.what();\n }\n \/\/tcp连接成功后每2秒触发一次该事件\n void onManager() override {\n send(\"echo test!\");\n DebugL << \"send echo test\";\n }\n \/\/连接服务器结果回调\n void onConnect(const SockException &ex) override{\n DebugL << ex.what();\n }\n\n \/\/数据全部发送完毕后回调\n void onFlush() override{\n DebugL;\n }\n};\n\nint main(int argc, char *argv[]) {\n \/\/设置退出信号处理函数\n static semaphore sem;\n signal(SIGINT, [](int) { sem.post(); });\/\/ 设置退出信号\n\n \/\/设置日志\n Logger::Instance().add(std::make_shared<ConsoleChannel>());\n Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());\n\n WebSocketClient<EchoTcpClient>::Ptr client = std::make_shared<WebSocketClient<EchoTcpClient> >();\n client->startConnect(\"121.40.165.18\",8800);\n\n sem.wait();\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <QtGlobal>\n#include <QFileInfo>\n#include <QDir>\n#include <QProcess>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string.h>\n#include <QtDebug>\n\n\nvoid runModelMoc(const QString& header, const QStringList& arguments)\n{\n QFile inf(header);\n if(!inf.open(QFile::ReadOnly))\n qFatal(\"Could not open header file for reading\");\n\n QTextStream in(&inf);\n\n QProcess p;\n p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);\n if(!p.waitForStarted()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n\n QString spaces = \"\\\\s*\";\n QString comma = \",\";\n QString colon = \":\";\n QString parenO = \"\\\\(\";\n QString parenC = \"\\\\)\";\n QString emptyParen = \"\\\\(\\\\)\";\n QString angleO = \"<\";\n QString angleC = \">\";\n QString braceO = \"\\\\{\";\n QString nameSpace = \"(?:\\\\w+::)\";\n QString typeName = \"\\\\w+\";\n QString pointer = \"\\\\*\";\n QString templateName = \"\\\\w+\";\n QString plainParam = \"(\\\\w+)\";\n QString boolParam = \"(true|false)\";\n QString anyParam = \"(.+)\";\n\n QRegExp propertyRegExp(\n spaces+\n \"M_MODEL_PROPERTY\"+\n spaces+parenO+spaces+\n \"(\"+\n \"(?:\"+\n nameSpace+\"{,1}\"+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n \")\"+\n \"|\"+\n \"(?:\"+\n templateName+\n angleO+\n spaces+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n angleC+\n \")\"+\n \")\"+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n anyParam+\n spaces+parenC+spaces );\n\n QRegExp propertyPtrRegExp(\n spaces+\n \"M_MODEL_PTR_PROPERTY\"+\n spaces+parenO+spaces+\n \"(\"+\n \"(?:\"+\n nameSpace+\"{,1}\"+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n \")\"+\n \"|\"+\n \"(?:\"+\n templateName+\n angleO+\n spaces+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n angleC+\n \")\"+\n \")\"+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n boolParam+\n spaces+comma+spaces+\n anyParam+\n spaces+parenC+spaces );\n\n QString line;\n while(true) {\n line = in.readLine();\n if(line.isNull()) {\n break;\n }\n\n line.replace(propertyRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n line.replace(propertyPtrRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n p.write(QString(line + \"\\n\").toLatin1());\n }\n p.closeWriteChannel();\n\n if(!p.waitForFinished()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n}\n\nvoid runStyleMoc(const QString& header, const QStringList& arguments)\n{\n QFile inf(header);\n if(!inf.open(QFile::ReadOnly))\n qFatal(\"Could not open header file for reading\");\n\n QTextStream in(&inf);\n\n QProcess p;\n p.start(QString(QT_MOC_PATH), arguments);\n if(!p.waitForStarted()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n\n\n QRegExp attributeRegExp(\"\\\\s*M_STYLE_ATTRIBUTE\\\\s*\\\\(\\\\s*(\\\\w+\\\\:*\\\\w*)\\\\s*,\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)\\\\s*\");\n QRegExp attributePtrRegExp(\"\\\\s*M_STYLE_PTR_ATTRIBUTE\\\\s*\\\\(\\\\s*(\\\\w+\\\\:*\\\\w*\\\\s*\\\\*+)\\\\s*,\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)\\\\s*\");\n\n\n QString line;\n while(true) {\n line = in.readLine();\n if(line.isNull()) {\n break;\n }\n\n line.replace(attributeRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n line.replace(attributePtrRegExp, \" Q_PROPERTY(const \\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n p.write(QString(line + \"\\n\").toLatin1());\n }\n p.closeWriteChannel();\n\n if(!p.waitForFinished()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n}\n\nenum HeaderType {\n Model,\n Style\n};\n\nint main(int argc, const char *argv[])\n{\n HeaderType type=Model;\n QStringList commandLineParameters;\n QString filename;\n char* mocArgv[argc+1];\n int result;\n pid_t pid;\n\n mocArgv[0] = strdup(QT_MOC_PATH);\n mocArgv[argc] = NULL;\n\n for(int i=1; i<argc; ++i) {\n if(QString(argv[i]).endsWith(\"style.h\")) {\n type = Style;\n filename = argv[i];\n } else if(QString(argv[i]).endsWith(\"model.h\")) {\n type = Model;\n filename = argv[i];\n } else {\n commandLineParameters << QString(argv[i]);\n mocArgv[i] = (char*) argv[i];\n }\n }\n\n if(filename.isEmpty()) {\n if((pid = fork()) == 0) {\n exit(execv(QT_MOC_PATH, mocArgv));\n }\n waitpid(pid, &result, 0);\n if(result != 0) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n } else {\n commandLineParameters << \"-f\" + filename;\n if(type == Model) {\n runModelMoc(filename, commandLineParameters);\n } else if(type == Style) {\n runStyleMoc(filename, commandLineParameters);\n }\n }\n\n free(mocArgv[0]);\n return 0; \/\/success\n}\n\n<commit_msg>Changes: Make mmoc work under windows<commit_after>#include <QtGlobal>\n#include <QFileInfo>\n#include <QDir>\n#include <QProcess>\n#include <QtDebug>\n\n\nvoid runModelMoc(const QString& header, const QStringList& arguments)\n{\n QFile inf(header);\n if(!inf.open(QFile::ReadOnly))\n qFatal(\"Could not open header file for reading\");\n\n QTextStream in(&inf);\n\n QProcess p;\n p.setProcessChannelMode( QProcess::ForwardedChannels );\n p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);\n if(!p.waitForStarted()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n\n QString spaces = \"\\\\s*\";\n QString comma = \",\";\n QString colon = \":\";\n QString parenO = \"\\\\(\";\n QString parenC = \"\\\\)\";\n QString emptyParen = \"\\\\(\\\\)\";\n QString angleO = \"<\";\n QString angleC = \">\";\n QString braceO = \"\\\\{\";\n QString nameSpace = \"(?:\\\\w+::)\";\n QString typeName = \"\\\\w+\";\n QString pointer = \"\\\\*\";\n QString templateName = \"\\\\w+\";\n QString plainParam = \"(\\\\w+)\";\n QString boolParam = \"(true|false)\";\n QString anyParam = \"(.+)\";\n\n QRegExp propertyRegExp(\n spaces+\n \"M_MODEL_PROPERTY\"+\n spaces+parenO+spaces+\n \"(\"+\n \"(?:\"+\n nameSpace+\"{,1}\"+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n \")\"+\n \"|\"+\n \"(?:\"+\n templateName+\n angleO+\n spaces+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n angleC+\n \")\"+\n \")\"+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n anyParam+\n spaces+parenC+spaces );\n\n QRegExp propertyPtrRegExp(\n spaces+\n \"M_MODEL_PTR_PROPERTY\"+\n spaces+parenO+spaces+\n \"(\"+\n \"(?:\"+\n nameSpace+\"{,1}\"+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n \")\"+\n \"|\"+\n \"(?:\"+\n templateName+\n angleO+\n spaces+\n typeName+\n spaces+\n pointer+\"{,1}\"+\n spaces+\n angleC+\n \")\"+\n \")\"+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n plainParam+\n spaces+comma+spaces+\n boolParam+\n spaces+comma+spaces+\n anyParam+\n spaces+parenC+spaces );\n\n QString line;\n while(true) {\n line = in.readLine();\n if(line.isNull()) {\n break;\n }\n\n line.replace(propertyRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n line.replace(propertyPtrRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n p.write(QString(line + \"\\n\").toLatin1());\n }\n p.closeWriteChannel();\n\n if(!p.waitForFinished()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n}\n\nvoid runStyleMoc(const QString& header, const QStringList& arguments)\n{\n QFile inf(header);\n if(!inf.open(QFile::ReadOnly))\n qFatal(\"Could not open header file for reading\");\n\n QTextStream in(&inf);\n\n QProcess p;\n p.setProcessChannelMode( QProcess::ForwardedChannels );\n p.start(QString(QT_MOC_PATH), arguments);\n if(!p.waitForStarted()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n\n\n QRegExp attributeRegExp(\"\\\\s*M_STYLE_ATTRIBUTE\\\\s*\\\\(\\\\s*(\\\\w+\\\\:*\\\\w*)\\\\s*,\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)\\\\s*\");\n QRegExp attributePtrRegExp(\"\\\\s*M_STYLE_PTR_ATTRIBUTE\\\\s*\\\\(\\\\s*(\\\\w+\\\\:*\\\\w*\\\\s*\\\\*+)\\\\s*,\\\\s*(\\\\w+)\\\\s*,\\\\s*(\\\\w+)\\\\s*\\\\)\\\\s*\");\n\n\n QString line;\n while(true) {\n line = in.readLine();\n if(line.isNull()) {\n break;\n }\n\n line.replace(attributeRegExp, \" Q_PROPERTY(\\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n line.replace(attributePtrRegExp, \" Q_PROPERTY(const \\\\1 \\\\2 READ \\\\2 WRITE set\\\\3)\");\n p.write(QString(line + \"\\n\").toLatin1());\n }\n p.closeWriteChannel();\n\n if(!p.waitForFinished()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n}\n\nvoid runQtMoc(const QStringList& arguments)\n{\n QProcess p;\n p.setProcessChannelMode( QProcess::ForwardedChannels );\n p.start(QString(QT_MOC_PATH), arguments);\n\n if(!p.waitForStarted()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n\n if(!p.waitForFinished()) {\n qFatal(\"mmoc: failed to run command '%s'\", QT_MOC_PATH);\n }\n}\n\nenum HeaderType {\n Model,\n Style\n};\n\nint main(int argc, const char *argv[])\n{\n HeaderType type=Model;\n QStringList commandLineParameters;\n QString filename;\n\n for(int i=1; i<argc; ++i) {\n if(QString(argv[i]).endsWith(\"style.h\")) {\n type = Style;\n filename = argv[i];\n } else if(QString(argv[i]).endsWith(\"model.h\")) {\n type = Model;\n filename = argv[i];\n } else {\n commandLineParameters << QString(argv[i]);\n }\n }\n\n if(filename.isEmpty()) {\n runQtMoc(commandLineParameters);\n } else {\n commandLineParameters << \"-f\" + filename;\n if(type == Model) {\n runModelMoc(filename, commandLineParameters);\n } else if(type == Style) {\n runStyleMoc(filename, commandLineParameters);\n }\n }\n\n return 0; \/\/success\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"CTR.h\"\n\nstd::string & CTR::increment_IV(std::string & IV){\n std::string::size_type i = IV.size();\n while ((i > 0) && (IV[i - 1] == 0xff)){\n IV[i - 1] = 0;\n i--;\n }\n\n if (i){\n IV[i - 1]++;\n }\n\n return IV;\n}\n\nCTR::CTR(SymAlg * instance, const std::string & iv)\n : algo(instance)\n{\n blocksize = algo -> blocksize() >> 3;\n const_IV = iv;\n if (const_IV == \"\"){\n const_IV = std::string(blocksize, 0);\n }\n}\n\nstd::string CTR::encrypt(const std::string & data){\n const std::string temp = pkcs5(data, blocksize);\n std::string out = \"\";\n std::string IV = const_IV;\n for(std::string::size_type x = 0; x < temp.size(); x += blocksize){\n out += xor_strings(algo -> encrypt(IV), temp.substr(0, blocksize));\n increment_IV(IV);\n }\n return out;\n}\n\nstd::string CTR::decrypt(const std::string & data){\n std::string out = \"\";\n std::string IV = const_IV;\n for(std::string::size_type x = 0; x < data.size(); x += blocksize){\n out += xor_strings(algo -> encrypt(IV), data.substr(x, blocksize));\n increment_IV(IV);\n }\n return remove_pkcs5(out);\n}\n<commit_msg>cast comparison values<commit_after>#include \"CTR.h\"\n\nstd::string & CTR::increment_IV(std::string & IV){\n std::string::size_type i = IV.size();\n while ((i > 0) && ((uint8_t) IV[i - 1] == (uint8_t) 0xff)){\n IV[i - 1] = 0;\n i--;\n }\n\n if (i){\n IV[i - 1]++;\n }\n\n return IV;\n}\n\nCTR::CTR(SymAlg * instance, const std::string & iv)\n : algo(instance)\n{\n blocksize = algo -> blocksize() >> 3;\n const_IV = iv;\n if (const_IV == \"\"){\n const_IV = std::string(blocksize, 0);\n }\n}\n\nstd::string CTR::encrypt(const std::string & data){\n const std::string temp = pkcs5(data, blocksize);\n std::string out = \"\";\n std::string IV = const_IV;\n for(std::string::size_type x = 0; x < temp.size(); x += blocksize){\n out += xor_strings(algo -> encrypt(IV), temp.substr(0, blocksize));\n increment_IV(IV);\n }\n return out;\n}\n\nstd::string CTR::decrypt(const std::string & data){\n std::string out = \"\";\n std::string IV = const_IV;\n for(std::string::size_type x = 0; x < data.size(); x += blocksize){\n out += xor_strings(algo -> encrypt(IV), data.substr(x, blocksize));\n increment_IV(IV);\n }\n return remove_pkcs5(out);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"multivalue.h\"\n\n#include \"length.h\"\n\n#include <assert.h>\n\n\nvoid\nStringList::unserialise(const std::string & serialised)\n{\n\tconst char * ptr = serialised.data();\n\tconst char * end = serialised.data() + serialised.size();\n\tunserialise(&ptr, end);\n}\n\n\nvoid\nStringList::unserialise(const char ** ptr, const char * end)\n{\n\tclear();\n\tsize_t length = decode_length(ptr, end, true);\n\tif (length == -1 || length != end - *ptr) {\n\t\tpush_back(std::string(*ptr, end - *ptr));\n\t} else {\n\t\tsize_t currlen;\n\t\twhile (*ptr != end) {\n\t\t\tcurrlen = decode_length(ptr, end, true);\n\t\t\tif (currlen == -1) {\n\t\t\t\t\/\/ FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.\n\t\t\t\tthrow Xapian::NetworkError(\"Decoding error of serialised MultiValueCountMatchSpy\");\n\t\t\t}\n\t\t\tpush_back(std::string(*ptr, currlen));\n\t\t\t*ptr += currlen;\n\t\t}\t\n\t}\n}\n\n\nstd::string\nStringList::serialise() const\n{\n\tstd::string serialised, values;\n\tStringList::const_iterator i(begin());\n\tif (size() > 1) {\n\t\tfor (; i != end(); i++) {\n\t\t\tvalues.append(encode_length((*i).size()));\n\t\t\tvalues.append(*i);\n\t\t}\n\t\tserialised.append(MULTIVALUE_MAGIC);\n\t\tserialised.append(encode_length(values.size()));\n\t} else if (i != end()) {\n\t\tvalues.assign(*i);\n\t}\n\tserialised.append(values);\n\treturn serialised;\n}\n\n\nvoid\nMultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {\n\tassert(internal.get());\n\t++(internal->total);\n\tStringList list;\n\tlist.unserialise(doc.get_value(internal->slot));\n\tStringList::const_iterator i(list.begin());\n\tfor (; i != list.end(); i++) {\n\t\tstd::string val(*i);\n\t\tif (!val.empty()) ++(internal->values[val]);\n\t}\n}\n\n\nXapian::MatchSpy *\nMultiValueCountMatchSpy::clone() const {\n\tassert(internal.get());\n\treturn new MultiValueCountMatchSpy(internal->slot);\n}\n\n\nstd::string\nMultiValueCountMatchSpy::name() const {\n\treturn \"Xapian::MultiValueCountMatchSpy\";\n}\n\n\nstd::string\nMultiValueCountMatchSpy::serialise() const {\n\tassert(internal.get());\n\tstd::string result;\n\tresult += encode_length(internal->slot);\n\treturn result;\n}\n\n\nXapian::MatchSpy *\nMultiValueCountMatchSpy::unserialise(const std::string & s,\n\t\t\t\t\t\t\t\t\t const Xapian::Registry &) const{\n\tconst char * p = s.data();\n\tconst char * end = p + s.size();\n\n\tXapian::valueno new_slot = decode_length(&p, end, false);\n\tif (new_slot == -1) {\n\t\tthrow Xapian::NetworkError(\"Decoding error of serialised MultiValueCountMatchSpy\");\n\t}\n\tif (p != end) {\n\t\tthrow Xapian::NetworkError(\"Junk at end of serialised MultiValueCountMatchSpy\");\n\t}\n\n\treturn new MultiValueCountMatchSpy(new_slot);\n}\n\n\nstd::string\nMultiValueCountMatchSpy::get_description() const {\n\tchar buffer[20];\n\tstd::string d = \"MultiValueCountMatchSpy(\";\n\tif (internal.get()) {\n\t\tsnprintf(buffer, sizeof(buffer), \"%u\", internal->total);\n\t\td += buffer;\n\t\td += \" docs seen, looking in \";\n\t\tsnprintf(buffer, sizeof(buffer), \"%lu\", internal->values.size());\n\t\td += buffer;\n\t\td += \" slots)\";\n\t} else {\n\t\td += \")\";\n\t}\n\treturn d;\n}<commit_msg>Don't append MULTIVALUE_MAGIC<commit_after>\/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"multivalue.h\"\n\n#include \"length.h\"\n\n#include <assert.h>\n\n\nvoid\nStringList::unserialise(const std::string & serialised)\n{\n\tconst char * ptr = serialised.data();\n\tconst char * end = serialised.data() + serialised.size();\n\tunserialise(&ptr, end);\n}\n\n\nvoid\nStringList::unserialise(const char ** ptr, const char * end)\n{\n\tclear();\n\tsize_t length = decode_length(ptr, end, true);\n\tif (length == -1 || length != end - *ptr) {\n\t\tpush_back(std::string(*ptr, end - *ptr));\n\t} else {\n\t\tsize_t currlen;\n\t\twhile (*ptr != end) {\n\t\t\tcurrlen = decode_length(ptr, end, true);\n\t\t\tif (currlen == -1) {\n\t\t\t\t\/\/ FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.\n\t\t\t\tthrow Xapian::NetworkError(\"Decoding error of serialised MultiValueCountMatchSpy\");\n\t\t\t}\n\t\t\tpush_back(std::string(*ptr, currlen));\n\t\t\t*ptr += currlen;\n\t\t}\t\n\t}\n}\n\n\nstd::string\nStringList::serialise() const\n{\n\tstd::string serialised, values;\n\tStringList::const_iterator i(begin());\n\tif (size() > 1) {\n\t\tfor (; i != end(); i++) {\n\t\t\tvalues.append(encode_length((*i).size()));\n\t\t\tvalues.append(*i);\n\t\t}\n\t\tserialised.append(encode_length(values.size()));\n\t} else if (i != end()) {\n\t\tvalues.assign(*i);\n\t}\n\tserialised.append(values);\n\treturn serialised;\n}\n\n\nvoid\nMultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {\n\tassert(internal.get());\n\t++(internal->total);\n\tStringList list;\n\tlist.unserialise(doc.get_value(internal->slot));\n\tStringList::const_iterator i(list.begin());\n\tfor (; i != list.end(); i++) {\n\t\tstd::string val(*i);\n\t\tif (!val.empty()) ++(internal->values[val]);\n\t}\n}\n\n\nXapian::MatchSpy *\nMultiValueCountMatchSpy::clone() const {\n\tassert(internal.get());\n\treturn new MultiValueCountMatchSpy(internal->slot);\n}\n\n\nstd::string\nMultiValueCountMatchSpy::name() const {\n\treturn \"Xapian::MultiValueCountMatchSpy\";\n}\n\n\nstd::string\nMultiValueCountMatchSpy::serialise() const {\n\tassert(internal.get());\n\tstd::string result;\n\tresult += encode_length(internal->slot);\n\treturn result;\n}\n\n\nXapian::MatchSpy *\nMultiValueCountMatchSpy::unserialise(const std::string & s,\n\t\t\t\t\t\t\t\t\t const Xapian::Registry &) const{\n\tconst char * p = s.data();\n\tconst char * end = p + s.size();\n\n\tXapian::valueno new_slot = decode_length(&p, end, false);\n\tif (new_slot == -1) {\n\t\tthrow Xapian::NetworkError(\"Decoding error of serialised MultiValueCountMatchSpy\");\n\t}\n\tif (p != end) {\n\t\tthrow Xapian::NetworkError(\"Junk at end of serialised MultiValueCountMatchSpy\");\n\t}\n\n\treturn new MultiValueCountMatchSpy(new_slot);\n}\n\n\nstd::string\nMultiValueCountMatchSpy::get_description() const {\n\tchar buffer[20];\n\tstd::string d = \"MultiValueCountMatchSpy(\";\n\tif (internal.get()) {\n\t\tsnprintf(buffer, sizeof(buffer), \"%u\", internal->total);\n\t\td += buffer;\n\t\td += \" docs seen, looking in \";\n\t\tsnprintf(buffer, sizeof(buffer), \"%lu\", internal->values.size());\n\t\td += buffer;\n\t\td += \" slots)\";\n\t} else {\n\t\td += \")\";\n\t}\n\treturn d;\n}<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/#include <unistd.h>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tt -= 1;\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(sin((PI) * abs(1\/t)));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(4\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<commit_msg>Update pwm.cpp<commit_after>\/\/\r\n\/\/#include <unistd.h>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 1000;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tt -= 1;\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(sin((PI\/2)\/t));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(4\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestPruneTreeFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkPruneTreeFilter.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTree.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestPruneTreeFilter(int argc, char* argv[])\n{\n vtkNew<vtkMutableDirectedGraph> graph;\n vtkIdType root = graph->AddVertex();\n vtkIdType internalOne = graph->AddChild(root);\n vtkIdType internalTwo = graph->AddChild(internalOne);\n vtkIdType a = graph->AddChild(internalTwo);\n graph->AddChild(internalTwo);\n graph->AddChild(internalOne);\n graph->AddChild(a);\n graph->AddChild(a);\n\n vtkNew<vtkTree> tree;\n tree->ShallowCopy(graph.GetPointer());\n\n vtkNew<vtkPruneTreeFilter> filter;\n filter->SetInputData(tree.GetPointer());\n filter->SetParentVertex(internalTwo);\n vtkTree *prunedTree = filter->GetOutput();\n filter->Update();\n\n if (prunedTree->GetNumberOfVertices() == 3)\n {\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}\n<commit_msg>Fix \"unreferenced formal parameter\" warnings<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestPruneTreeFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkPruneTreeFilter.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTree.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestPruneTreeFilter(int, char*[])\n{\n vtkNew<vtkMutableDirectedGraph> graph;\n vtkIdType root = graph->AddVertex();\n vtkIdType internalOne = graph->AddChild(root);\n vtkIdType internalTwo = graph->AddChild(internalOne);\n vtkIdType a = graph->AddChild(internalTwo);\n graph->AddChild(internalTwo);\n graph->AddChild(internalOne);\n graph->AddChild(a);\n graph->AddChild(a);\n\n vtkNew<vtkTree> tree;\n tree->ShallowCopy(graph.GetPointer());\n\n vtkNew<vtkPruneTreeFilter> filter;\n filter->SetInputData(tree.GetPointer());\n filter->SetParentVertex(internalTwo);\n vtkTree *prunedTree = filter->GetOutput();\n filter->Update();\n\n if (prunedTree->GetNumberOfVertices() == 3)\n {\n return EXIT_SUCCESS;\n }\n\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: format.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: obo $ $Date: 2005-05-03 13:52:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SVX_SCRIPTTYPEITEM_HXX\n#include <svx\/scripttypeitem.hxx>\n#endif\n\n#ifndef FORMAT_HXX\n#include \"format.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Latin default-fonts\nstatic const USHORT aLatinDefFnts[FNT_END] =\n{\n DEFAULTFONT_SERIF, \/\/ FNT_VARIABLE\n DEFAULTFONT_SERIF, \/\/ FNT_FUNCTION\n DEFAULTFONT_SERIF, \/\/ FNT_NUMBER\n DEFAULTFONT_SERIF, \/\/ FNT_TEXT\n DEFAULTFONT_SERIF, \/\/ FNT_SERIF\n DEFAULTFONT_SANS, \/\/ FNT_SANS\n DEFAULTFONT_FIXED \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\/\/ CJK default-fonts\n\/\/! we use non-asian fonts for variables, functions and numbers since they\n\/\/! look better and even in asia only latin letters will be used for those.\n\/\/! At least that's what I was told...\nstatic const USHORT aCJKDefFnts[FNT_END] =\n{\n DEFAULTFONT_SERIF, \/\/ FNT_VARIABLE\n DEFAULTFONT_SERIF, \/\/ FNT_FUNCTION\n DEFAULTFONT_SERIF, \/\/ FNT_NUMBER\n DEFAULTFONT_CJK_TEXT, \/\/ FNT_TEXT\n DEFAULTFONT_CJK_TEXT, \/\/ FNT_SERIF\n DEFAULTFONT_CJK_DISPLAY, \/\/ FNT_SANS\n DEFAULTFONT_CJK_TEXT \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\/\/ CTL default-fonts\nstatic const USHORT aCTLDefFnts[FNT_END] =\n{\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_VARIABLE\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_FUNCTION\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_NUMBER\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_TEXT\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_SERIF\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_SANS\n DEFAULTFONT_CTL_TEXT \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\nString GetDefaultFontName( LanguageType nLang, USHORT nIdent )\n{\n DBG_ASSERT( FNT_BEGIN <= nIdent && nIdent <= FNT_END,\n \"index out opd range\" );\n\n if (FNT_MATH == nIdent)\n return String::CreateFromAscii( FNTNAME_MATH );\n else\n {\n const USHORT *pTable;\n switch ( SvtLanguageOptions::GetScriptTypeOfLanguage( nLang ) )\n {\n case SCRIPTTYPE_LATIN : pTable = aLatinDefFnts; break;\n case SCRIPTTYPE_ASIAN : pTable = aCJKDefFnts; break;\n case SCRIPTTYPE_COMPLEX : pTable = aCTLDefFnts; break;\n default :\n pTable = aLatinDefFnts;\n DBG_ERROR( \"unknown script-type\" );\n }\n\n return Application::GetDefaultDevice()->GetDefaultFont(\n pTable[ nIdent ], nLang,\n DEFAULTFONT_FLAGS_ONLYONE ).GetName();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSmFormat::SmFormat()\n: aBaseSize(0, SmPtsTo100th_mm(12))\n{\n nVersion = SM_FMT_VERSION_NOW;\n\n eHorAlign = AlignCenter;\n bIsTextmode = bScaleNormalBrackets = FALSE;\n\n vSize[SIZ_TEXT] = 100;\n vSize[SIZ_INDEX] = 60;\n vSize[SIZ_FUNCTION] =\n vSize[SIZ_OPERATOR] = 100;\n vSize[SIZ_LIMITS] = 60;\n\n vDist[DIS_HORIZONTAL] = 10;\n vDist[DIS_VERTICAL] = 5;\n vDist[DIS_ROOT] = 0;\n vDist[DIS_SUPERSCRIPT] =\n vDist[DIS_SUBSCRIPT] = 20;\n vDist[DIS_NUMERATOR] =\n vDist[DIS_DENOMINATOR] = 0;\n vDist[DIS_FRACTION] = 10;\n vDist[DIS_STROKEWIDTH] = 5;\n vDist[DIS_UPPERLIMIT] =\n vDist[DIS_LOWERLIMIT] = 0;\n vDist[DIS_BRACKETSIZE] =\n vDist[DIS_BRACKETSPACE] = 5;\n vDist[DIS_MATRIXROW] = 3;\n vDist[DIS_MATRIXCOL] = 30;\n vDist[DIS_ORNAMENTSIZE] =\n vDist[DIS_ORNAMENTSPACE] = 0;\n vDist[DIS_OPERATORSIZE] = 50;\n vDist[DIS_OPERATORSPACE] = 20;\n vDist[DIS_LEFTSPACE] =\n vDist[DIS_RIGHTSPACE] = 100;\n vDist[DIS_TOPSPACE] =\n vDist[DIS_BOTTOMSPACE] =\n vDist[DIS_NORMALBRACKETSIZE] = 0;\n\n vFont[FNT_VARIABLE] =\n vFont[FNT_FUNCTION] =\n vFont[FNT_NUMBER] =\n vFont[FNT_TEXT] =\n vFont[FNT_SERIF] = SmFace(C2S(FNTNAME_TIMES), aBaseSize);\n vFont[FNT_SANS] = SmFace(C2S(FNTNAME_HELV), aBaseSize);\n vFont[FNT_FIXED] = SmFace(C2S(FNTNAME_COUR), aBaseSize);\n vFont[FNT_MATH] = SmFace(C2S(FNTNAME_MATH), aBaseSize);\n\n vFont[FNT_MATH].SetCharSet( RTL_TEXTENCODING_UNICODE );\n\n vFont[FNT_VARIABLE].SetItalic(ITALIC_NORMAL);\n vFont[FNT_FUNCTION].SetItalic(ITALIC_NONE);\n vFont[FNT_NUMBER] .SetItalic(ITALIC_NONE);\n vFont[FNT_TEXT] .SetItalic(ITALIC_NONE);\n vFont[FNT_SERIF] .SetItalic(ITALIC_NONE);\n vFont[FNT_SANS] .SetItalic(ITALIC_NONE);\n vFont[FNT_FIXED] .SetItalic(ITALIC_NONE);\n\n for ( USHORT i = FNT_BEGIN; i <= FNT_END; i++ )\n {\n SmFace &rFace = vFont[i];\n rFace.SetTransparent( TRUE );\n rFace.SetAlign( ALIGN_BASELINE );\n rFace.SetColor( COL_AUTO );\n bDefaultFont[i] = FALSE;\n }\n}\n\n\nvoid SmFormat::SetFont(USHORT nIdent, const SmFace &rFont, BOOL bDefault )\n{\n vFont[nIdent] = rFont;\n vFont[nIdent].SetTransparent( TRUE );\n vFont[nIdent].SetAlign( ALIGN_BASELINE );\n\n bDefaultFont[nIdent] = bDefault;\n}\n\nSmFormat & SmFormat::operator = (const SmFormat &rFormat)\n{\n SetBaseSize(rFormat.GetBaseSize());\n SetVersion (rFormat.GetVersion());\n SetHorAlign(rFormat.GetHorAlign());\n SetTextmode(rFormat.IsTextmode());\n SetScaleNormalBrackets(rFormat.IsScaleNormalBrackets());\n\n USHORT i;\n for (i = FNT_BEGIN; i <= FNT_END; i++)\n {\n SetFont(i, rFormat.GetFont(i));\n SetDefaultFont(i, rFormat.IsDefaultFont(i));\n }\n for (i = SIZ_BEGIN; i <= SIZ_END; i++)\n SetRelSize(i, rFormat.GetRelSize(i));\n for (i = DIS_BEGIN; i <= DIS_END; i++)\n SetDistance(i, rFormat.GetDistance(i));\n\n return *this;\n}\n\n\nBOOL SmFormat::operator == (const SmFormat &rFormat) const\n{\n BOOL bRes = aBaseSize == rFormat.aBaseSize &&\n eHorAlign == rFormat.eHorAlign &&\n bIsTextmode == rFormat.bIsTextmode &&\n bScaleNormalBrackets == rFormat.bScaleNormalBrackets;\n\n USHORT i;\n for (i = 0; i <= SIZ_END && bRes; ++i)\n {\n if (vSize[i] != rFormat.vSize[i])\n bRes = FALSE;\n }\n for (i = 0; i <= DIS_END && bRes; ++i)\n {\n if (vDist[i] != rFormat.vDist[i])\n bRes = FALSE;\n }\n for (i = 0; i <= FNT_END && bRes; ++i)\n {\n if (vFont[i] != rFormat.vFont[i] ||\n bDefaultFont[i] != rFormat.bDefaultFont[i])\n bRes = FALSE;\n }\n\n return bRes;\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.10.56); FILE MERGED 2005\/09\/05 17:37:31 rt 1.10.56.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: format.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 15:07:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SVX_SCRIPTTYPEITEM_HXX\n#include <svx\/scripttypeitem.hxx>\n#endif\n\n#ifndef FORMAT_HXX\n#include \"format.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Latin default-fonts\nstatic const USHORT aLatinDefFnts[FNT_END] =\n{\n DEFAULTFONT_SERIF, \/\/ FNT_VARIABLE\n DEFAULTFONT_SERIF, \/\/ FNT_FUNCTION\n DEFAULTFONT_SERIF, \/\/ FNT_NUMBER\n DEFAULTFONT_SERIF, \/\/ FNT_TEXT\n DEFAULTFONT_SERIF, \/\/ FNT_SERIF\n DEFAULTFONT_SANS, \/\/ FNT_SANS\n DEFAULTFONT_FIXED \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\/\/ CJK default-fonts\n\/\/! we use non-asian fonts for variables, functions and numbers since they\n\/\/! look better and even in asia only latin letters will be used for those.\n\/\/! At least that's what I was told...\nstatic const USHORT aCJKDefFnts[FNT_END] =\n{\n DEFAULTFONT_SERIF, \/\/ FNT_VARIABLE\n DEFAULTFONT_SERIF, \/\/ FNT_FUNCTION\n DEFAULTFONT_SERIF, \/\/ FNT_NUMBER\n DEFAULTFONT_CJK_TEXT, \/\/ FNT_TEXT\n DEFAULTFONT_CJK_TEXT, \/\/ FNT_SERIF\n DEFAULTFONT_CJK_DISPLAY, \/\/ FNT_SANS\n DEFAULTFONT_CJK_TEXT \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\/\/ CTL default-fonts\nstatic const USHORT aCTLDefFnts[FNT_END] =\n{\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_VARIABLE\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_FUNCTION\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_NUMBER\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_TEXT\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_SERIF\n DEFAULTFONT_CTL_TEXT, \/\/ FNT_SANS\n DEFAULTFONT_CTL_TEXT \/\/ FNT_FIXED\n \/\/StarSymbol, \/\/ FNT_MATH\n};\n\n\nString GetDefaultFontName( LanguageType nLang, USHORT nIdent )\n{\n DBG_ASSERT( FNT_BEGIN <= nIdent && nIdent <= FNT_END,\n \"index out opd range\" );\n\n if (FNT_MATH == nIdent)\n return String::CreateFromAscii( FNTNAME_MATH );\n else\n {\n const USHORT *pTable;\n switch ( SvtLanguageOptions::GetScriptTypeOfLanguage( nLang ) )\n {\n case SCRIPTTYPE_LATIN : pTable = aLatinDefFnts; break;\n case SCRIPTTYPE_ASIAN : pTable = aCJKDefFnts; break;\n case SCRIPTTYPE_COMPLEX : pTable = aCTLDefFnts; break;\n default :\n pTable = aLatinDefFnts;\n DBG_ERROR( \"unknown script-type\" );\n }\n\n return Application::GetDefaultDevice()->GetDefaultFont(\n pTable[ nIdent ], nLang,\n DEFAULTFONT_FLAGS_ONLYONE ).GetName();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSmFormat::SmFormat()\n: aBaseSize(0, SmPtsTo100th_mm(12))\n{\n nVersion = SM_FMT_VERSION_NOW;\n\n eHorAlign = AlignCenter;\n bIsTextmode = bScaleNormalBrackets = FALSE;\n\n vSize[SIZ_TEXT] = 100;\n vSize[SIZ_INDEX] = 60;\n vSize[SIZ_FUNCTION] =\n vSize[SIZ_OPERATOR] = 100;\n vSize[SIZ_LIMITS] = 60;\n\n vDist[DIS_HORIZONTAL] = 10;\n vDist[DIS_VERTICAL] = 5;\n vDist[DIS_ROOT] = 0;\n vDist[DIS_SUPERSCRIPT] =\n vDist[DIS_SUBSCRIPT] = 20;\n vDist[DIS_NUMERATOR] =\n vDist[DIS_DENOMINATOR] = 0;\n vDist[DIS_FRACTION] = 10;\n vDist[DIS_STROKEWIDTH] = 5;\n vDist[DIS_UPPERLIMIT] =\n vDist[DIS_LOWERLIMIT] = 0;\n vDist[DIS_BRACKETSIZE] =\n vDist[DIS_BRACKETSPACE] = 5;\n vDist[DIS_MATRIXROW] = 3;\n vDist[DIS_MATRIXCOL] = 30;\n vDist[DIS_ORNAMENTSIZE] =\n vDist[DIS_ORNAMENTSPACE] = 0;\n vDist[DIS_OPERATORSIZE] = 50;\n vDist[DIS_OPERATORSPACE] = 20;\n vDist[DIS_LEFTSPACE] =\n vDist[DIS_RIGHTSPACE] = 100;\n vDist[DIS_TOPSPACE] =\n vDist[DIS_BOTTOMSPACE] =\n vDist[DIS_NORMALBRACKETSIZE] = 0;\n\n vFont[FNT_VARIABLE] =\n vFont[FNT_FUNCTION] =\n vFont[FNT_NUMBER] =\n vFont[FNT_TEXT] =\n vFont[FNT_SERIF] = SmFace(C2S(FNTNAME_TIMES), aBaseSize);\n vFont[FNT_SANS] = SmFace(C2S(FNTNAME_HELV), aBaseSize);\n vFont[FNT_FIXED] = SmFace(C2S(FNTNAME_COUR), aBaseSize);\n vFont[FNT_MATH] = SmFace(C2S(FNTNAME_MATH), aBaseSize);\n\n vFont[FNT_MATH].SetCharSet( RTL_TEXTENCODING_UNICODE );\n\n vFont[FNT_VARIABLE].SetItalic(ITALIC_NORMAL);\n vFont[FNT_FUNCTION].SetItalic(ITALIC_NONE);\n vFont[FNT_NUMBER] .SetItalic(ITALIC_NONE);\n vFont[FNT_TEXT] .SetItalic(ITALIC_NONE);\n vFont[FNT_SERIF] .SetItalic(ITALIC_NONE);\n vFont[FNT_SANS] .SetItalic(ITALIC_NONE);\n vFont[FNT_FIXED] .SetItalic(ITALIC_NONE);\n\n for ( USHORT i = FNT_BEGIN; i <= FNT_END; i++ )\n {\n SmFace &rFace = vFont[i];\n rFace.SetTransparent( TRUE );\n rFace.SetAlign( ALIGN_BASELINE );\n rFace.SetColor( COL_AUTO );\n bDefaultFont[i] = FALSE;\n }\n}\n\n\nvoid SmFormat::SetFont(USHORT nIdent, const SmFace &rFont, BOOL bDefault )\n{\n vFont[nIdent] = rFont;\n vFont[nIdent].SetTransparent( TRUE );\n vFont[nIdent].SetAlign( ALIGN_BASELINE );\n\n bDefaultFont[nIdent] = bDefault;\n}\n\nSmFormat & SmFormat::operator = (const SmFormat &rFormat)\n{\n SetBaseSize(rFormat.GetBaseSize());\n SetVersion (rFormat.GetVersion());\n SetHorAlign(rFormat.GetHorAlign());\n SetTextmode(rFormat.IsTextmode());\n SetScaleNormalBrackets(rFormat.IsScaleNormalBrackets());\n\n USHORT i;\n for (i = FNT_BEGIN; i <= FNT_END; i++)\n {\n SetFont(i, rFormat.GetFont(i));\n SetDefaultFont(i, rFormat.IsDefaultFont(i));\n }\n for (i = SIZ_BEGIN; i <= SIZ_END; i++)\n SetRelSize(i, rFormat.GetRelSize(i));\n for (i = DIS_BEGIN; i <= DIS_END; i++)\n SetDistance(i, rFormat.GetDistance(i));\n\n return *this;\n}\n\n\nBOOL SmFormat::operator == (const SmFormat &rFormat) const\n{\n BOOL bRes = aBaseSize == rFormat.aBaseSize &&\n eHorAlign == rFormat.eHorAlign &&\n bIsTextmode == rFormat.bIsTextmode &&\n bScaleNormalBrackets == rFormat.bScaleNormalBrackets;\n\n USHORT i;\n for (i = 0; i <= SIZ_END && bRes; ++i)\n {\n if (vSize[i] != rFormat.vSize[i])\n bRes = FALSE;\n }\n for (i = 0; i <= DIS_END && bRes; ++i)\n {\n if (vDist[i] != rFormat.vDist[i])\n bRes = FALSE;\n }\n for (i = 0; i <= FNT_END && bRes; ++i)\n {\n if (vFont[i] != rFormat.vFont[i] ||\n bDefaultFont[i] != rFormat.bDefaultFont[i])\n bRes = FALSE;\n }\n\n return bRes;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"util\/exception.hh\"\n#include \"moses\/FF\/Factory.h\"\n#include \"moses\/StaticData.h\"\n\n#include \"moses\/TranslationModel\/PhraseDictionaryTreeAdaptor.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMemory.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMultiModel.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMultiModelCounts.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryScope3.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryTransliteration.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryDynamicCacheBased.h\"\n\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryOnDisk.h\"\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryFuzzyMatch.h\"\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryALSuffixArray.h\"\n\n#include \"moses\/FF\/LexicalReordering\/LexicalReordering.h\"\n\n#include \"moses\/FF\/BleuScoreFeature.h\"\n#include \"moses\/FF\/TargetWordInsertionFeature.h\"\n#include \"moses\/FF\/SourceWordDeletionFeature.h\"\n#include \"moses\/FF\/GlobalLexicalModel.h\"\n#include \"moses\/FF\/GlobalLexicalModelUnlimited.h\"\n#include \"moses\/FF\/Model1Feature.h\"\n#include \"moses\/FF\/UnknownWordPenaltyProducer.h\"\n#include \"moses\/FF\/WordTranslationFeature.h\"\n#include \"moses\/FF\/TargetBigramFeature.h\"\n#include \"moses\/FF\/TargetNgramFeature.h\"\n#include \"moses\/FF\/PhraseBoundaryFeature.h\"\n#include \"moses\/FF\/PhrasePairFeature.h\"\n#include \"moses\/FF\/RulePairUnlexicalizedSource.h\"\n#include \"moses\/FF\/PhraseLengthFeature.h\"\n#include \"moses\/FF\/DistortionScoreProducer.h\"\n#include \"moses\/FF\/SparseHieroReorderingFeature.h\"\n#include \"moses\/FF\/WordPenaltyProducer.h\"\n#include \"moses\/FF\/InputFeature.h\"\n#include \"moses\/FF\/PhrasePenalty.h\"\n#include \"moses\/FF\/OSM-Feature\/OpSequenceModel.h\"\n#include \"moses\/FF\/ControlRecombination.h\"\n#include \"moses\/FF\/ConstrainedDecoding.h\"\n#include \"moses\/FF\/SoftSourceSyntacticConstraintsFeature.h\"\n#include \"moses\/FF\/CoveredReferenceFeature.h\"\n#include \"moses\/FF\/TreeStructureFeature.h\"\n#include \"moses\/FF\/SoftMatchingFeature.h\"\n#include \"moses\/FF\/DynamicCacheBasedLanguageModel.h\"\n#include \"moses\/FF\/SourceGHKMTreeInputMatchFeature.h\"\n#include \"moses\/FF\/HyperParameterAsWeight.h\"\n#include \"moses\/FF\/SetSourcePhrase.h\"\n#include \"moses\/FF\/PhraseOrientationFeature.h\"\n#include \"moses\/FF\/UnalignedWordCountFeature.h\"\n#include \"CountNonTerms.h\"\n#include \"ReferenceComparison.h\"\n#include \"RuleScope.h\"\n#include \"MaxSpanFreeNonTermSource.h\"\n#include \"NieceTerminal.h\"\n#include \"SpanLength.h\"\n#include \"SyntaxRHS.h\"\n\n#include \"moses\/FF\/SkeletonStatelessFF.h\"\n#include \"moses\/FF\/SkeletonStatefulFF.h\"\n#include \"moses\/LM\/SkeletonLM.h\"\n#include \"moses\/FF\/SkeletonTranslationOptionListFeature.h\"\n#include \"moses\/LM\/BilingualLM.h\"\n#include \"moses\/TranslationModel\/SkeletonPT.h\"\n#include \"moses\/Syntax\/InputWeightFF.h\"\n#include \"moses\/Syntax\/RuleTableFF.h\"\n\n#ifdef HAVE_VW\n#include \"moses\/FF\/VW\/VW.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceBagOfWords.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceBigrams.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceIndicator.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourcePhraseInternal.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceWindow.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetBigrams.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetIndicator.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceExternalFeatures.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetPhraseInternal.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetPhraseScores.h\"\n#endif\n\n#ifdef HAVE_CMPH\n#include \"moses\/TranslationModel\/CompactPT\/PhraseDictionaryCompact.h\"\n#endif\n#ifdef PT_UG\n#include \"moses\/TranslationModel\/UG\/mmsapt.h\"\n#endif\n#ifdef HAVE_PROBINGPT\n#include \"moses\/TranslationModel\/ProbingPT\/ProbingPT.h\"\n#endif\n\n#include \"moses\/LM\/Ken.h\"\n#ifdef LM_IRST\n#include \"moses\/LM\/IRST.h\"\n#endif\n\n#ifdef LM_SRI\n#include \"moses\/LM\/SRI.h\"\n#endif\n\n#ifdef LM_MAXENT_SRI\n#include \"moses\/LM\/MaxEntSRI.h\"\n#endif\n\n#ifdef LM_RAND\n#include \"moses\/LM\/Rand.h\"\n#endif\n\n#ifdef HAVE_SYNLM\n#include \"moses\/SyntacticLanguageModel.h\"\n#endif\n\n#ifdef LM_NEURAL\n#include \"moses\/LM\/NeuralLMWrapper.h\"\n#include \"moses\/LM\/RDLM.h\"\n#include \"moses\/LM\/bilingual-lm\/BiLM_NPLM.h\"\n#endif\n\n#ifdef LM_DALM\n#include \"moses\/LM\/DALMWrapper.h\"\n#endif\n\n#ifdef LM_OXLM\n#include \"moses\/LM\/oxlm\/OxLM.h\"\n#include \"moses\/LM\/oxlm\/SourceOxLM.h\"\n#endif\n\n#include \"util\/exception.hh\"\n\n#include <vector>\n\nnamespace Moses\n{\n\nclass FeatureFactory\n{\npublic:\n virtual ~FeatureFactory() {}\n\n virtual void Create(const std::string &line) = 0;\n\nprotected:\n template <class F> static void DefaultSetup(F *feature);\n\n FeatureFactory() {}\n};\n\ntemplate <class F>\nvoid\nFeatureFactory\n::DefaultSetup(F *feature)\n{\n StaticData &static_data = StaticData::InstanceNonConst();\n const std::string &featureName = feature->GetScoreProducerDescription();\n std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);\n\n\n if (feature->GetNumScoreComponents()) {\n if (weights.size() == 0) {\n weights = feature->DefaultWeights();\n if (weights.size() == 0) {\n TRACE_ERR(\"WARNING: No weights specified in config file for FF \"\n << featureName << \". This FF does not supply default values.\\n\"\n << \"WARNING: Auto-initializing all weights for this FF to 1.0\");\n weights.assign(feature->GetNumScoreComponents(),1.0);\n } else {\n VERBOSE(2,\"WARNING: No weights specified in config file for FF \"\n << featureName << \". Using default values supplied by FF.\");\n }\n }\n UTIL_THROW_IF2(weights.size() != feature->GetNumScoreComponents(),\n \"FATAL ERROR: Mismatch in number of features and number \"\n << \"of weights for Feature Function \" << featureName\n << \" (features: \" << feature->GetNumScoreComponents()\n << \" vs. weights: \" << weights.size() << \")\");\n static_data.SetWeights(feature, weights);\n } else if (feature->IsTuneable())\n static_data.SetWeights(feature, weights);\n}\n\nnamespace\n{\n\ntemplate <class F>\nclass DefaultFeatureFactory : public FeatureFactory\n{\npublic:\n void Create(const std::string &line) {\n DefaultSetup(new F(line));\n }\n};\n\nclass KenFactory : public FeatureFactory\n{\npublic:\n void Create(const std::string &line) {\n DefaultSetup(ConstructKenLM(line));\n }\n};\n\n} \/\/ namespace\n\nFeatureRegistry::FeatureRegistry()\n{\n\/\/ Feature with same name as class\n#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());\n\/\/ Feature with different name than class.\n#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());\n\n MOSES_FNAME2(\"PhraseDictionaryBinary\", PhraseDictionaryTreeAdaptor);\n MOSES_FNAME(PhraseDictionaryOnDisk);\n MOSES_FNAME(PhraseDictionaryMemory);\n MOSES_FNAME(PhraseDictionaryScope3);\n MOSES_FNAME(PhraseDictionaryMultiModel);\n MOSES_FNAME(PhraseDictionaryMultiModelCounts);\n MOSES_FNAME(PhraseDictionaryALSuffixArray);\n \/\/ MOSES_FNAME(PhraseDictionaryDynSuffixArray);\n MOSES_FNAME(PhraseDictionaryTransliteration);\n MOSES_FNAME(PhraseDictionaryDynamicCacheBased);\n MOSES_FNAME(PhraseDictionaryFuzzyMatch);\n MOSES_FNAME2(\"RuleTable\", Syntax::RuleTableFF);\n MOSES_FNAME2(\"SyntaxInputWeight\", Syntax::InputWeightFF);\n\n MOSES_FNAME(GlobalLexicalModel);\n \/\/MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original\n MOSES_FNAME(Model1Feature);\n MOSES_FNAME(SourceWordDeletionFeature);\n MOSES_FNAME(TargetWordInsertionFeature);\n MOSES_FNAME(PhraseBoundaryFeature);\n MOSES_FNAME(PhraseLengthFeature);\n MOSES_FNAME(WordTranslationFeature);\n MOSES_FNAME(TargetBigramFeature);\n MOSES_FNAME(TargetNgramFeature);\n MOSES_FNAME(PhrasePairFeature);\n MOSES_FNAME(RulePairUnlexicalizedSource);\n MOSES_FNAME(LexicalReordering);\n MOSES_FNAME2(\"Generation\", GenerationDictionary);\n MOSES_FNAME(BleuScoreFeature);\n MOSES_FNAME2(\"Distortion\", DistortionScoreProducer);\n MOSES_FNAME2(\"WordPenalty\", WordPenaltyProducer);\n MOSES_FNAME(InputFeature);\n MOSES_FNAME(OpSequenceModel);\n MOSES_FNAME(PhrasePenalty);\n MOSES_FNAME2(\"UnknownWordPenalty\", UnknownWordPenaltyProducer);\n MOSES_FNAME(ControlRecombination);\n MOSES_FNAME(ConstrainedDecoding);\n MOSES_FNAME(CoveredReferenceFeature);\n MOSES_FNAME(SourceGHKMTreeInputMatchFeature);\n MOSES_FNAME(SoftSourceSyntacticConstraintsFeature);\n MOSES_FNAME(TreeStructureFeature);\n MOSES_FNAME(SoftMatchingFeature);\n MOSES_FNAME(DynamicCacheBasedLanguageModel);\n MOSES_FNAME(HyperParameterAsWeight);\n MOSES_FNAME(SetSourcePhrase);\n MOSES_FNAME(CountNonTerms);\n MOSES_FNAME(ReferenceComparison);\n MOSES_FNAME(RuleScope);\n MOSES_FNAME(MaxSpanFreeNonTermSource);\n MOSES_FNAME(NieceTerminal);\n MOSES_FNAME(SparseHieroReorderingFeature);\n MOSES_FNAME(SpanLength);\n MOSES_FNAME(SyntaxRHS);\n MOSES_FNAME(PhraseOrientationFeature);\n MOSES_FNAME(UnalignedWordCountFeature);\n\n MOSES_FNAME(SkeletonStatelessFF);\n MOSES_FNAME(SkeletonStatefulFF);\n MOSES_FNAME(SkeletonLM);\n MOSES_FNAME(SkeletonTranslationOptionListFeature);\n MOSES_FNAME(SkeletonPT);\n\n#ifdef HAVE_VW\n MOSES_FNAME(VW);\n MOSES_FNAME(VWFeatureSourceBagOfWords);\n MOSES_FNAME(VWFeatureSourceBigrams);\n MOSES_FNAME(VWFeatureSourceIndicator);\n MOSES_FNAME(VWFeatureSourcePhraseInternal);\n MOSES_FNAME(VWFeatureSourceWindow);\n MOSES_FNAME(VWFeatureTargetBigrams);\n MOSES_FNAME(VWFeatureTargetPhraseInternal);\n MOSES_FNAME(VWFeatureTargetIndicator);\n MOSES_FNAME(VWFeatureSourceExternalFeatures);\n MOSES_FNAME(VWFeatureTargetPhraseScores);\n#endif\n\n#ifdef HAVE_CMPH\n MOSES_FNAME(PhraseDictionaryCompact);\n#endif\n#ifdef PT_UG\n MOSES_FNAME(Mmsapt);\n MOSES_FNAME2(\"PhraseDictionaryBitextSampling\",Mmsapt); \/\/ that's an alias for Mmsapt!\n#endif\n#ifdef HAVE_PROBINGPT\n MOSES_FNAME(ProbingPT);\n#endif\n\n#ifdef HAVE_SYNLM\n MOSES_FNAME(SyntacticLanguageModel);\n#endif\n#ifdef LM_IRST\n MOSES_FNAME2(\"IRSTLM\", LanguageModelIRST);\n#endif\n#ifdef LM_SRI\n MOSES_FNAME2(\"SRILM\", LanguageModelSRI);\n#endif\n#ifdef LM_MAXENT_SRI\n MOSES_FNAME2(\"MaxEntLM\", LanguageModelMaxEntSRI);\n#endif\n#ifdef LM_RAND\n MOSES_FNAME2(\"RANDLM\", LanguageModelRandLM);\n#endif\n#ifdef LM_NEURAL\n MOSES_FNAME2(\"NeuralLM\", NeuralLMWrapper);\n MOSES_FNAME(RDLM);\n MOSES_FNAME2(\"BilingualNPLM\", BilingualLM_NPLM);\n#endif\n#ifdef LM_DALM\n MOSES_FNAME2(\"DALM\", LanguageModelDALM);\n#endif\n#ifdef LM_OXLM\n MOSES_FNAME2(\"OxLM\", OxLM<oxlm::LM>);\n MOSES_FNAME2(\"OxFactoredLM\", OxLM<oxlm::FactoredLM>);\n MOSES_FNAME2(\"OxFactoredMaxentLM\", OxLM<oxlm::FactoredMaxentLM>);\n MOSES_FNAME2(\"OxSourceFactoredLM\", SourceOxLM);\n MOSES_FNAME2(\"OxTreeLM\", OxLM<oxlm::FactoredTreeLM>);\n#endif\n\n Add(\"KENLM\", new KenFactory());\n}\n\nFeatureRegistry::~FeatureRegistry()\n{\n}\n\nvoid FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)\n{\n std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));\n UTIL_THROW_IF2(!registry_.insert(to_ins).second, \"Duplicate feature name \" << name);\n}\n\nnamespace\n{\nclass UnknownFeatureException : public util::Exception {};\n}\n\nvoid FeatureRegistry::Construct(const std::string &name, const std::string &line)\n{\n Map::iterator i = registry_.find(name);\n UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, \"Feature name \" << name << \" is not registered.\");\n i->second->Create(line);\n}\n\nvoid FeatureRegistry::PrintFF() const\n{\n std::vector<std::string> ffs;\n std::cerr << \"Available feature functions:\" << std::endl;\n Map::const_iterator iter;\n for (iter = registry_.begin(); iter != registry_.end(); ++iter) {\n const std::string &ffName = iter->first;\n ffs.push_back(ffName);\n }\n\n std::vector<std::string>::const_iterator iterVec;\n std::sort(ffs.begin(), ffs.end());\n for (iterVec = ffs.begin(); iterVec != ffs.end(); ++iterVec) {\n const std::string &ffName = *iterVec;\n std::cerr << ffName << \" \";\n }\n\n std::cerr << std::endl;\n}\n\n} \/\/ namespace Moses\n<commit_msg>registered coarsebilm in factory<commit_after>#include \"util\/exception.hh\"\n#include \"moses\/FF\/Factory.h\"\n#include \"moses\/StaticData.h\"\n\n#include \"moses\/TranslationModel\/PhraseDictionaryTreeAdaptor.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMemory.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMultiModel.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryMultiModelCounts.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryScope3.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryTransliteration.h\"\n#include \"moses\/TranslationModel\/PhraseDictionaryDynamicCacheBased.h\"\n\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryOnDisk.h\"\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryFuzzyMatch.h\"\n#include \"moses\/TranslationModel\/RuleTable\/PhraseDictionaryALSuffixArray.h\"\n\n#include \"moses\/FF\/LexicalReordering\/LexicalReordering.h\"\n\n#include \"moses\/FF\/BleuScoreFeature.h\"\n#include \"moses\/FF\/CoarseBiLM.h\"\n#include \"moses\/FF\/TargetWordInsertionFeature.h\"\n#include \"moses\/FF\/SourceWordDeletionFeature.h\"\n#include \"moses\/FF\/GlobalLexicalModel.h\"\n#include \"moses\/FF\/GlobalLexicalModelUnlimited.h\"\n#include \"moses\/FF\/Model1Feature.h\"\n#include \"moses\/FF\/UnknownWordPenaltyProducer.h\"\n#include \"moses\/FF\/WordTranslationFeature.h\"\n#include \"moses\/FF\/TargetBigramFeature.h\"\n#include \"moses\/FF\/TargetNgramFeature.h\"\n#include \"moses\/FF\/PhraseBoundaryFeature.h\"\n#include \"moses\/FF\/PhrasePairFeature.h\"\n#include \"moses\/FF\/RulePairUnlexicalizedSource.h\"\n#include \"moses\/FF\/PhraseLengthFeature.h\"\n#include \"moses\/FF\/DistortionScoreProducer.h\"\n#include \"moses\/FF\/SparseHieroReorderingFeature.h\"\n#include \"moses\/FF\/WordPenaltyProducer.h\"\n#include \"moses\/FF\/InputFeature.h\"\n#include \"moses\/FF\/PhrasePenalty.h\"\n#include \"moses\/FF\/OSM-Feature\/OpSequenceModel.h\"\n#include \"moses\/FF\/ControlRecombination.h\"\n#include \"moses\/FF\/ConstrainedDecoding.h\"\n#include \"moses\/FF\/SoftSourceSyntacticConstraintsFeature.h\"\n#include \"moses\/FF\/CoveredReferenceFeature.h\"\n#include \"moses\/FF\/TreeStructureFeature.h\"\n#include \"moses\/FF\/SoftMatchingFeature.h\"\n#include \"moses\/FF\/DynamicCacheBasedLanguageModel.h\"\n#include \"moses\/FF\/SourceGHKMTreeInputMatchFeature.h\"\n#include \"moses\/FF\/HyperParameterAsWeight.h\"\n#include \"moses\/FF\/SetSourcePhrase.h\"\n#include \"moses\/FF\/PhraseOrientationFeature.h\"\n#include \"moses\/FF\/UnalignedWordCountFeature.h\"\n#include \"CountNonTerms.h\"\n#include \"ReferenceComparison.h\"\n#include \"RuleScope.h\"\n#include \"MaxSpanFreeNonTermSource.h\"\n#include \"NieceTerminal.h\"\n#include \"SpanLength.h\"\n#include \"SyntaxRHS.h\"\n\n#include \"moses\/FF\/SkeletonStatelessFF.h\"\n#include \"moses\/FF\/SkeletonStatefulFF.h\"\n#include \"moses\/LM\/SkeletonLM.h\"\n#include \"moses\/FF\/SkeletonTranslationOptionListFeature.h\"\n#include \"moses\/LM\/BilingualLM.h\"\n#include \"moses\/TranslationModel\/SkeletonPT.h\"\n#include \"moses\/Syntax\/InputWeightFF.h\"\n#include \"moses\/Syntax\/RuleTableFF.h\"\n\n#ifdef HAVE_VW\n#include \"moses\/FF\/VW\/VW.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceBagOfWords.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceBigrams.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceIndicator.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourcePhraseInternal.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceWindow.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetBigrams.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetIndicator.h\"\n#include \"moses\/FF\/VW\/VWFeatureSourceExternalFeatures.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetPhraseInternal.h\"\n#include \"moses\/FF\/VW\/VWFeatureTargetPhraseScores.h\"\n#endif\n\n#ifdef HAVE_CMPH\n#include \"moses\/TranslationModel\/CompactPT\/PhraseDictionaryCompact.h\"\n#endif\n#ifdef PT_UG\n#include \"moses\/TranslationModel\/UG\/mmsapt.h\"\n#endif\n#ifdef HAVE_PROBINGPT\n#include \"moses\/TranslationModel\/ProbingPT\/ProbingPT.h\"\n#endif\n\n#include \"moses\/LM\/Ken.h\"\n#ifdef LM_IRST\n#include \"moses\/LM\/IRST.h\"\n#endif\n\n#ifdef LM_SRI\n#include \"moses\/LM\/SRI.h\"\n#endif\n\n#ifdef LM_MAXENT_SRI\n#include \"moses\/LM\/MaxEntSRI.h\"\n#endif\n\n#ifdef LM_RAND\n#include \"moses\/LM\/Rand.h\"\n#endif\n\n#ifdef HAVE_SYNLM\n#include \"moses\/SyntacticLanguageModel.h\"\n#endif\n\n#ifdef LM_NEURAL\n#include \"moses\/LM\/NeuralLMWrapper.h\"\n#include \"moses\/LM\/RDLM.h\"\n#include \"moses\/LM\/bilingual-lm\/BiLM_NPLM.h\"\n#endif\n\n#ifdef LM_DALM\n#include \"moses\/LM\/DALMWrapper.h\"\n#endif\n\n#ifdef LM_OXLM\n#include \"moses\/LM\/oxlm\/OxLM.h\"\n#include \"moses\/LM\/oxlm\/SourceOxLM.h\"\n#endif\n\n#include \"util\/exception.hh\"\n\n#include <vector>\n\nnamespace Moses\n{\n\nclass FeatureFactory\n{\npublic:\n virtual ~FeatureFactory() {}\n\n virtual void Create(const std::string &line) = 0;\n\nprotected:\n template <class F> static void DefaultSetup(F *feature);\n\n FeatureFactory() {}\n};\n\ntemplate <class F>\nvoid\nFeatureFactory\n::DefaultSetup(F *feature)\n{\n StaticData &static_data = StaticData::InstanceNonConst();\n const std::string &featureName = feature->GetScoreProducerDescription();\n std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);\n\n\n if (feature->GetNumScoreComponents()) {\n if (weights.size() == 0) {\n weights = feature->DefaultWeights();\n if (weights.size() == 0) {\n TRACE_ERR(\"WARNING: No weights specified in config file for FF \"\n << featureName << \". This FF does not supply default values.\\n\"\n << \"WARNING: Auto-initializing all weights for this FF to 1.0\");\n weights.assign(feature->GetNumScoreComponents(),1.0);\n } else {\n VERBOSE(2,\"WARNING: No weights specified in config file for FF \"\n << featureName << \". Using default values supplied by FF.\");\n }\n }\n UTIL_THROW_IF2(weights.size() != feature->GetNumScoreComponents(),\n \"FATAL ERROR: Mismatch in number of features and number \"\n << \"of weights for Feature Function \" << featureName\n << \" (features: \" << feature->GetNumScoreComponents()\n << \" vs. weights: \" << weights.size() << \")\");\n static_data.SetWeights(feature, weights);\n } else if (feature->IsTuneable())\n static_data.SetWeights(feature, weights);\n}\n\nnamespace\n{\n\ntemplate <class F>\nclass DefaultFeatureFactory : public FeatureFactory\n{\npublic:\n void Create(const std::string &line) {\n DefaultSetup(new F(line));\n }\n};\n\nclass KenFactory : public FeatureFactory\n{\npublic:\n void Create(const std::string &line) {\n DefaultSetup(ConstructKenLM(line));\n }\n};\n\n} \/\/ namespace\n\nFeatureRegistry::FeatureRegistry()\n{\n\/\/ Feature with same name as class\n#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());\n\/\/ Feature with different name than class.\n#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());\n\n MOSES_FNAME2(\"PhraseDictionaryBinary\", PhraseDictionaryTreeAdaptor);\n MOSES_FNAME(PhraseDictionaryOnDisk);\n MOSES_FNAME(PhraseDictionaryMemory);\n MOSES_FNAME(PhraseDictionaryScope3);\n MOSES_FNAME(PhraseDictionaryMultiModel);\n MOSES_FNAME(PhraseDictionaryMultiModelCounts);\n MOSES_FNAME(PhraseDictionaryALSuffixArray);\n \/\/ MOSES_FNAME(PhraseDictionaryDynSuffixArray);\n MOSES_FNAME(PhraseDictionaryTransliteration);\n MOSES_FNAME(PhraseDictionaryDynamicCacheBased);\n MOSES_FNAME(PhraseDictionaryFuzzyMatch);\n MOSES_FNAME2(\"RuleTable\", Syntax::RuleTableFF);\n MOSES_FNAME2(\"SyntaxInputWeight\", Syntax::InputWeightFF);\n\n MOSES_FNAME(GlobalLexicalModel);\n \/\/MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original\n MOSES_FNAME(Model1Feature);\n MOSES_FNAME(SourceWordDeletionFeature);\n MOSES_FNAME(TargetWordInsertionFeature);\n MOSES_FNAME(PhraseBoundaryFeature);\n MOSES_FNAME(PhraseLengthFeature);\n MOSES_FNAME(WordTranslationFeature);\n MOSES_FNAME(TargetBigramFeature);\n MOSES_FNAME(TargetNgramFeature);\n MOSES_FNAME(PhrasePairFeature);\n MOSES_FNAME(RulePairUnlexicalizedSource);\n MOSES_FNAME(LexicalReordering);\n MOSES_FNAME2(\"Generation\", GenerationDictionary);\n MOSES_FNAME(BleuScoreFeature);\n MOSES_FNAME2(\"Distortion\", DistortionScoreProducer);\n MOSES_FNAME2(\"WordPenalty\", WordPenaltyProducer);\n MOSES_FNAME(InputFeature);\n MOSES_FNAME(OpSequenceModel);\n MOSES_FNAME(PhrasePenalty);\n MOSES_FNAME2(\"UnknownWordPenalty\", UnknownWordPenaltyProducer);\n MOSES_FNAME(ControlRecombination);\n MOSES_FNAME(ConstrainedDecoding);\n MOSES_FNAME(CoveredReferenceFeature);\n MOSES_FNAME(SourceGHKMTreeInputMatchFeature);\n MOSES_FNAME(SoftSourceSyntacticConstraintsFeature);\n MOSES_FNAME(TreeStructureFeature);\n MOSES_FNAME(SoftMatchingFeature);\n MOSES_FNAME(DynamicCacheBasedLanguageModel);\n MOSES_FNAME(HyperParameterAsWeight);\n MOSES_FNAME(SetSourcePhrase);\n MOSES_FNAME(CountNonTerms);\n MOSES_FNAME(ReferenceComparison);\n MOSES_FNAME(RuleScope);\n MOSES_FNAME(MaxSpanFreeNonTermSource);\n MOSES_FNAME(NieceTerminal);\n MOSES_FNAME(SparseHieroReorderingFeature);\n MOSES_FNAME(SpanLength);\n MOSES_FNAME(SyntaxRHS);\n MOSES_FNAME(PhraseOrientationFeature);\n MOSES_FNAME(UnalignedWordCountFeature);\n MOSES_FNAME(CoarseBiLM);\n\n MOSES_FNAME(SkeletonStatelessFF);\n MOSES_FNAME(SkeletonStatefulFF);\n MOSES_FNAME(SkeletonLM);\n MOSES_FNAME(SkeletonTranslationOptionListFeature);\n MOSES_FNAME(SkeletonPT);\n\n#ifdef HAVE_VW\n MOSES_FNAME(VW);\n MOSES_FNAME(VWFeatureSourceBagOfWords);\n MOSES_FNAME(VWFeatureSourceBigrams);\n MOSES_FNAME(VWFeatureSourceIndicator);\n MOSES_FNAME(VWFeatureSourcePhraseInternal);\n MOSES_FNAME(VWFeatureSourceWindow);\n MOSES_FNAME(VWFeatureTargetBigrams);\n MOSES_FNAME(VWFeatureTargetPhraseInternal);\n MOSES_FNAME(VWFeatureTargetIndicator);\n MOSES_FNAME(VWFeatureSourceExternalFeatures);\n MOSES_FNAME(VWFeatureTargetPhraseScores);\n#endif\n\n#ifdef HAVE_CMPH\n MOSES_FNAME(PhraseDictionaryCompact);\n#endif\n#ifdef PT_UG\n MOSES_FNAME(Mmsapt);\n MOSES_FNAME2(\"PhraseDictionaryBitextSampling\",Mmsapt); \/\/ that's an alias for Mmsapt!\n#endif\n#ifdef HAVE_PROBINGPT\n MOSES_FNAME(ProbingPT);\n#endif\n\n#ifdef HAVE_SYNLM\n MOSES_FNAME(SyntacticLanguageModel);\n#endif\n#ifdef LM_IRST\n MOSES_FNAME2(\"IRSTLM\", LanguageModelIRST);\n#endif\n#ifdef LM_SRI\n MOSES_FNAME2(\"SRILM\", LanguageModelSRI);\n#endif\n#ifdef LM_MAXENT_SRI\n MOSES_FNAME2(\"MaxEntLM\", LanguageModelMaxEntSRI);\n#endif\n#ifdef LM_RAND\n MOSES_FNAME2(\"RANDLM\", LanguageModelRandLM);\n#endif\n#ifdef LM_NEURAL\n MOSES_FNAME2(\"NeuralLM\", NeuralLMWrapper);\n MOSES_FNAME(RDLM);\n MOSES_FNAME2(\"BilingualNPLM\", BilingualLM_NPLM);\n#endif\n#ifdef LM_DALM\n MOSES_FNAME2(\"DALM\", LanguageModelDALM);\n#endif\n#ifdef LM_OXLM\n MOSES_FNAME2(\"OxLM\", OxLM<oxlm::LM>);\n MOSES_FNAME2(\"OxFactoredLM\", OxLM<oxlm::FactoredLM>);\n MOSES_FNAME2(\"OxFactoredMaxentLM\", OxLM<oxlm::FactoredMaxentLM>);\n MOSES_FNAME2(\"OxSourceFactoredLM\", SourceOxLM);\n MOSES_FNAME2(\"OxTreeLM\", OxLM<oxlm::FactoredTreeLM>);\n#endif\n\n Add(\"KENLM\", new KenFactory());\n}\n\nFeatureRegistry::~FeatureRegistry()\n{\n}\n\nvoid FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)\n{\n std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));\n UTIL_THROW_IF2(!registry_.insert(to_ins).second, \"Duplicate feature name \" << name);\n}\n\nnamespace\n{\nclass UnknownFeatureException : public util::Exception {};\n}\n\nvoid FeatureRegistry::Construct(const std::string &name, const std::string &line)\n{\n Map::iterator i = registry_.find(name);\n UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, \"Feature name \" << name << \" is not registered.\");\n i->second->Create(line);\n}\n\nvoid FeatureRegistry::PrintFF() const\n{\n std::vector<std::string> ffs;\n std::cerr << \"Available feature functions:\" << std::endl;\n Map::const_iterator iter;\n for (iter = registry_.begin(); iter != registry_.end(); ++iter) {\n const std::string &ffName = iter->first;\n ffs.push_back(ffName);\n }\n\n std::vector<std::string>::const_iterator iterVec;\n std::sort(ffs.begin(), ffs.end());\n for (iterVec = ffs.begin(); iterVec != ffs.end(); ++iterVec) {\n const std::string &ffName = *iterVec;\n std::cerr << ffName << \" \";\n }\n\n std::cerr << std::endl;\n}\n\n} \/\/ namespace Moses\n<|endoftext|>"} {"text":"<commit_before>\/* \nCopyright (c) 2016 Ingo Wald\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n\/\/ ospray pixel \n#include \"ospray\/fb\/PixelOp.h\"\n#include \"ospray\/fb\/FrameBuffer.h\"\n#include \"ospray\/mpi\/MPICommon.h\"\n\/\/ displaywald client\n#include \"..\/client\/Client.h\"\n\nnamespace ospray {\n namespace dw {\n\n void foo()\n {\n }\n\n struct DisplayWaldPixelOp : public ospray::PixelOp \n {\n struct Instance : public ospray::PixelOp::Instance \n {\n Instance(FrameBuffer *fb, \n PixelOp::Instance *prev,\n dw::Client *client)\n : client(client)\n {\n fb->pixelOp = this;\n }\n\n \/\/ \/*! gets called every time the frame buffer got 'commit'ted *\/\n \/\/ virtual void commitNotify() {}\n \/\/ \/*! gets called once at the end of the frame *\/\n virtual void endFrame() \n { client->endFrame(); }\n \n virtual int clampColorComponent(float c)\n {\n int r = 255*c;\n if (r < 0) r = 0;\n if (r > 255) r = 255;\n }\n \n virtual float simpleGammaCorrection(float c, float gamma)\n {\n return exp(c, 1.0f\/gamma);\n }\n \n virtual unsigned int packColor(float r, float g, float b, float a)\n {\n return (a<<32) | (b<<24) | (g<<16) | (r<<8);\n }\n \n \/*! called right after the tile got accumulated; i.e., the\n tile's RGBA values already contain the accu-buffer blended\n values (assuming an accubuffer exists), and this function\n defines how these pixels are being processed before written\n into the color buffer *\/\n virtual void postAccum(Tile &tile) \n {\n PlainTile plainTile(vec2i(TILE_SIZE));\n plainTile.pitch = TILE_SIZE;\n for (int i=0;i<TILE_SIZE*TILE_SIZE;i++) {\n \/\/int r = std::min(255,int(255.f*tile.r[i]));\n \/\/int g = std::min(255,int(255.f*tile.g[i]));\n \/\/int b = std::min(255,int(255.f*tile.b[i]));\n \n float gamma = 1.8;\n int r = clampColorComponent(simpleGammaCorrection(tile.r[i], gamma);\n int g = clampColorComponent(simpleGammaCorrection(tile.g[i], gamma);\n int b = clampColorComponent(simpleGammaCorrection(tile.b[i], gamma);\n \n int rgba = (b<<24)|(g<<16)|(r<<8);\n plainTile.pixel[i] = rgba;\n }\n plainTile.region = tile.region;\n bool stereo = client->getWallConfig()->doStereo();\n if (!stereo) {\n plainTile.eye = 0;\n client->writeTile(plainTile);\n } else {\n int trueScreenWidth = client->getWallConfig()->totalPixels().x;\n if (plainTile.region.upper.x <= trueScreenWidth) {\n \/\/ all on left eye\n plainTile.eye = 0;\n client->writeTile(plainTile);\n } else if (plainTile.region.lower.x >= trueScreenWidth) {\n \/\/ all on right eye - just shift coordinates\n plainTile.region.lower.x -= trueScreenWidth;\n plainTile.region.upper.x -= trueScreenWidth;\n plainTile.eye = 1;\n client->writeTile(plainTile);\n } else {\n \/\/ overlaps both sides - split it up\n const int original_lower_x = plainTile.region.lower.x;\n const int original_upper_x = plainTile.region.upper.x;\n \/\/ first, 'clip' the tile and write 'clipped' one to the left side\n plainTile.region.lower.x = original_lower_x - trueScreenWidth;\n plainTile.region.upper.x = trueScreenWidth;\n plainTile.eye = 0;\n client->writeTile(plainTile);\n\n \/\/ now, move right true to the left, clip on lower side, and shift pixels\n plainTile.region.lower.x = 0;\n plainTile.region.upper.x = original_upper_x - trueScreenWidth;\n \/\/ since pixels didn't start at 'trueWidth' but at 'lower.x', we have to shift\n int numPixelsInRegion = plainTile.region.size().y*plainTile.pitch;\n int shift = trueScreenWidth - original_lower_x;\n plainTile.eye = 1;\n for (int i=0;i<numPixelsInRegion;i++)\n plainTile.pixel[i] = plainTile.pixel[i+shift];\n client->writeTile(plainTile);\n }\n \n }\n }\n \n \/\/! \\brief common function to help printf-debugging \n \/*! Every derived class should overrride this! *\/\n virtual std::string toString() const;\n\n dw::Client *client;\n };\n \n \/\/! \\brief common function to help printf-debugging \n \/*! Every derived class should overrride this! *\/\n virtual std::string toString() const;\n \n \/*! \\brief commit the object's outstanding changes (such as changed\n * parameters etc) *\/\n virtual void commit()\n {\n std::string streamName = getParamString(\"streamName\",\"\");\n std::cout << \"#osp:dw: trying to establish connection to display wall service at MPI port \" << streamName << std::endl;\n client = new dw::Client(mpi::worker.comm,streamName);\n }\n\n \/\/! \\brief create an instance of this pixel op\n virtual ospray::PixelOp::Instance *createInstance(FrameBuffer *fb, \n PixelOp::Instance *prev)\n {\n return new Instance(fb,prev,client);\n }\n \n dw::Client *client;\n };\n \n \/\/! \\brief common function to help printf-debugging \n std::string DisplayWaldPixelOp::toString() const \n { return \"ospray::dw::DisplayWaldPixelOp (displayWald module)\"; }\n\n \/\/! \\brief common function to help printf-debugging \n std::string DisplayWaldPixelOp::Instance::toString() const \n { return \"ospray::dw::DisplayWaldPixelOp::Instance (displayWald module)\"; }\n\n extern \"C\" void ospray_init_module_displayWald()\n {\n printf(\"loading the 'displayWald' module...\\n\");\n }\n\n OSP_REGISTER_PIXEL_OP(DisplayWaldPixelOp,display_wald);\n\n } \/\/ ::ospray::dw\n} \/\/ ::ospray\n<commit_msg>update missing )<commit_after>\/* \nCopyright (c) 2016 Ingo Wald\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n\/\/ ospray pixel \n#include \"ospray\/fb\/PixelOp.h\"\n#include \"ospray\/fb\/FrameBuffer.h\"\n#include \"ospray\/mpi\/MPICommon.h\"\n\/\/ displaywald client\n#include \"..\/client\/Client.h\"\n\nnamespace ospray {\n namespace dw {\n\n void foo()\n {\n }\n\n struct DisplayWaldPixelOp : public ospray::PixelOp \n {\n struct Instance : public ospray::PixelOp::Instance \n {\n Instance(FrameBuffer *fb, \n PixelOp::Instance *prev,\n dw::Client *client)\n : client(client)\n {\n fb->pixelOp = this;\n }\n\n \/\/ \/*! gets called every time the frame buffer got 'commit'ted *\/\n \/\/ virtual void commitNotify() {}\n \/\/ \/*! gets called once at the end of the frame *\/\n virtual void endFrame() \n { client->endFrame(); }\n \n virtual int clampColorComponent(float c)\n {\n int r = 255*c;\n if (r < 0) r = 0;\n if (r > 255) r = 255;\n }\n \n virtual float simpleGammaCorrection(float c, float gamma)\n {\n return exp(c, 1.0f\/gamma);\n }\n \n virtual unsigned int packColor(float r, float g, float b, float a)\n {\n return (a<<32) | (b<<24) | (g<<16) | (r<<8);\n }\n \n \/*! called right after the tile got accumulated; i.e., the\n tile's RGBA values already contain the accu-buffer blended\n values (assuming an accubuffer exists), and this function\n defines how these pixels are being processed before written\n into the color buffer *\/\n virtual void postAccum(Tile &tile) \n {\n PlainTile plainTile(vec2i(TILE_SIZE));\n plainTile.pitch = TILE_SIZE;\n for (int i=0;i<TILE_SIZE*TILE_SIZE;i++) {\n \/\/int r = std::min(255,int(255.f*tile.r[i]));\n \/\/int g = std::min(255,int(255.f*tile.g[i]));\n \/\/int b = std::min(255,int(255.f*tile.b[i]));\n \n float gamma = 1.8;\n int r = clampColorComponent(simpleGammaCorrection(tile.r[i], gamma));\n int g = clampColorComponent(simpleGammaCorrection(tile.g[i], gamma));\n int b = clampColorComponent(simpleGammaCorrection(tile.b[i], gamma));\n \n int rgba = (b<<24)|(g<<16)|(r<<8);\n plainTile.pixel[i] = rgba;\n }\n plainTile.region = tile.region;\n bool stereo = client->getWallConfig()->doStereo();\n if (!stereo) {\n plainTile.eye = 0;\n client->writeTile(plainTile);\n } else {\n int trueScreenWidth = client->getWallConfig()->totalPixels().x;\n if (plainTile.region.upper.x <= trueScreenWidth) {\n \/\/ all on left eye\n plainTile.eye = 0;\n client->writeTile(plainTile);\n } else if (plainTile.region.lower.x >= trueScreenWidth) {\n \/\/ all on right eye - just shift coordinates\n plainTile.region.lower.x -= trueScreenWidth;\n plainTile.region.upper.x -= trueScreenWidth;\n plainTile.eye = 1;\n client->writeTile(plainTile);\n } else {\n \/\/ overlaps both sides - split it up\n const int original_lower_x = plainTile.region.lower.x;\n const int original_upper_x = plainTile.region.upper.x;\n \/\/ first, 'clip' the tile and write 'clipped' one to the left side\n plainTile.region.lower.x = original_lower_x - trueScreenWidth;\n plainTile.region.upper.x = trueScreenWidth;\n plainTile.eye = 0;\n client->writeTile(plainTile);\n\n \/\/ now, move right true to the left, clip on lower side, and shift pixels\n plainTile.region.lower.x = 0;\n plainTile.region.upper.x = original_upper_x - trueScreenWidth;\n \/\/ since pixels didn't start at 'trueWidth' but at 'lower.x', we have to shift\n int numPixelsInRegion = plainTile.region.size().y*plainTile.pitch;\n int shift = trueScreenWidth - original_lower_x;\n plainTile.eye = 1;\n for (int i=0;i<numPixelsInRegion;i++)\n plainTile.pixel[i] = plainTile.pixel[i+shift];\n client->writeTile(plainTile);\n }\n \n }\n }\n \n \/\/! \\brief common function to help printf-debugging \n \/*! Every derived class should overrride this! *\/\n virtual std::string toString() const;\n\n dw::Client *client;\n };\n \n \/\/! \\brief common function to help printf-debugging \n \/*! Every derived class should overrride this! *\/\n virtual std::string toString() const;\n \n \/*! \\brief commit the object's outstanding changes (such as changed\n * parameters etc) *\/\n virtual void commit()\n {\n std::string streamName = getParamString(\"streamName\",\"\");\n std::cout << \"#osp:dw: trying to establish connection to display wall service at MPI port \" << streamName << std::endl;\n client = new dw::Client(mpi::worker.comm,streamName);\n }\n\n \/\/! \\brief create an instance of this pixel op\n virtual ospray::PixelOp::Instance *createInstance(FrameBuffer *fb, \n PixelOp::Instance *prev)\n {\n return new Instance(fb,prev,client);\n }\n \n dw::Client *client;\n };\n \n \/\/! \\brief common function to help printf-debugging \n std::string DisplayWaldPixelOp::toString() const \n { return \"ospray::dw::DisplayWaldPixelOp (displayWald module)\"; }\n\n \/\/! \\brief common function to help printf-debugging \n std::string DisplayWaldPixelOp::Instance::toString() const \n { return \"ospray::dw::DisplayWaldPixelOp::Instance (displayWald module)\"; }\n\n extern \"C\" void ospray_init_module_displayWald()\n {\n printf(\"loading the 'displayWald' module...\\n\");\n }\n\n OSP_REGISTER_PIXEL_OP(DisplayWaldPixelOp,display_wald);\n\n } \/\/ ::ospray::dw\n} \/\/ ::ospray\n<|endoftext|>"} {"text":"<commit_before>#include \"AudioMonitorServer.hpp\"\r\n\r\n\/*Constructor of AudioMonitorServer, create the server socket and initialize the data\r\n * structure*\/\r\n\r\nAudioMonitorServer::AudioMonitorServer(int prt,int dbg):\r\n debug(1),port(prt){\r\n\r\n \/* socket factory*\/\r\n if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)\r\n {\r\n perror(\"socket\");\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n\r\n \/* init local addr structure and other params *\/\r\n my_addr.sin_family = AF_INET;\r\n my_addr.sin_port = htons(port);\r\n my_addr.sin_addr.s_addr = htonl(INADDR_ANY);\r\n addrlen = sizeof(struct sockaddr_in);\r\n\r\n \/* bind addr structure with socket *\/\r\n if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)\r\n {\r\n perror(\"bind\");\r\n close(servSockfd);\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n \/*Set servSockfd to be non-blocking*\/\r\n fcntl(servSockfd,F_SETFL,O_NONBLOCK);\r\n\r\n \/* set the socket in passive mode (only used for accept())\r\n * and set the list size for pending connection*\/\r\n listen(servSockfd,SOMAXCONN);\r\n\r\n max_select=servSockfd;\r\n\r\n list_client=new std::vector<EASEAClientData>;\r\n }\r\n\r\n\/**\r\n * \/brief Destructor of AudioMonitorServer\r\n **\/\r\nAudioMonitorServer::~AudioMonitorServer(){\r\n \/*close every opened socket*\/\r\n unsigned int i;\r\n\r\n for(i=0;i<list_client->size();i++){\r\n close(list_client->at(i).getSocket());\r\n }\r\n\r\n}\r\n\r\n\r\nvoid AudioMonitorServer::signalHandler(){\r\n \/*Signal handler in case of ^C, to close the sockets*\/\r\n \/\/terminaison.sa_handler=sigIntEvent;\r\n sigfillset(&terminaison.sa_mask);\r\n terminaison.sa_flags=0;\r\n\r\n sigaction(SIGINT,&terminaison,NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid AudioMonitorServer::sigIntEvent(int sig){\r\n unsigned int i;\r\n\r\n close(servSockfd);\t\r\n\r\n for(i=0;i<list_client->size();i++){\r\n \/\/send(list_client[i].getSocket(),\"000\/END\",8,0);\r\n close(list_client->at(i).getSocket());\r\n }\r\n\r\n exit(0);\r\n}\r\n\r\n\r\nvoid AudioMonitorServer::buildSocketList(){\r\n unsigned int i;\r\n\r\n FD_ZERO(&rdclient);\r\n FD_SET(servSockfd,&rdclient);\r\n\r\n for(i=0;i<list_client->size();i++){\r\n FD_SET(list_client->at(i).getSocket(),&rdclient);\r\n }\r\n\r\n}\r\n\r\nvoid AudioMonitorServer::newClient(){\r\n int tmp_sockfd;\r\n EASEAClientData* new_client;\r\n \r\n tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);\r\n\r\n \/*selected need to know the highest numerical socket value*\/\r\n if(tmp_sockfd>max_select){\r\n max_select=tmp_sockfd;\r\n }\r\n\r\n if (debug) {\r\n std::cout<<\"nouveaux client\"<<std::endl;\r\n }\r\n\r\n \/*Adding the newly connected client to the list of client*\/\r\n new_client = new EASEAClientData(tmp_sockfd);\r\n new_client->setIP(inet_ntoa(my_addr.sin_addr));\r\n new_client->setPort(ntohs(my_addr.sin_port));\r\n list_client->push_back(*new_client);\t\r\n\r\n}\r\n\r\nvoid AudioMonitorServer::recvSomething(){\r\n if(FD_ISSET(servSockfd,&rdclient))\r\n newClient();\r\n else\r\n recvFromClient();\r\n\r\n}\r\n\r\n\/* Case new data from known client*\/\r\n\/* Check whose fd changed and received from them*\/\r\nvoid AudioMonitorServer::recvFromClient(){\r\n char buf[1024];\r\n float* dec=(float*)buf;\r\n unsigned int i; \r\n EASEAClientData* changedClient;\r\n memset(buf,'\\0',1024); \/\/reset buffer\r\n \r\n for(i=0;i<list_client->size();i++){\r\n if(list_client->at(i).getSocket()!=0){\r\n if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){\r\n \r\n changedClient=&list_client->at(i);\r\n \r\n if(recv(changedClient->getSocket(),buf,1024,0)==0){\r\n \/\/client_disconnected=true;\r\n }\/\/Envoi de packet vide => deconnecte\/fini;\r\n else {\r\n if (!changedClient->toIgnore()) {\r\n changedClient->addData(dec[0],dec[1],dec[2],dec[3]);\r\n\r\n if (debug){\r\n std::cout<<\"I have received something from \"<<\r\n changedClient->getIP()<<\":\"<<changedClient->getPort()\r\n <<std::endl;\r\n std::cout<<dec[0]<<\" \"<<dec[1]<<\" \"<<dec[2]<<\" \"<<dec[3]<<std::endl;\r\n }\r\n\r\n compo->notify(changedClient);\r\n }\r\n else{\r\n list_client->at(i).setIgnoreFlag(false);\r\n }\r\n }\r\n\r\n }\r\n }\r\n }\r\n\r\n}\r\n\r\n\r\n\/**\r\n * \/brief Start the server, which will never stop listening \r\n **\/\r\nvoid AudioMonitorServer::start(){\r\n\r\n\r\n debug=1; \r\n\r\n while(1){\r\n\r\n buildSocketList();\r\n\r\n if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){\r\n recvSomething();\r\n }\r\n }\r\n}\r\n\r\n\r\n\/**\r\n* \/brief Add a Compositor\r\n**\/\r\nvoid AudioMonitorServer::setCompositor(Compositor* compo){\r\n this->compo=compo;\r\n}\r\n<commit_msg>Now keep track of individuals migration<commit_after>#include \"AudioMonitorServer.hpp\"\r\n\r\n\/*Constructor of AudioMonitorServer, create the server socket and initialize the data\r\n * structure*\/\r\n\r\nAudioMonitorServer::AudioMonitorServer(int prt,int dbg):\r\n debug(1),port(prt){\r\n\r\n \/* socket factory*\/\r\n if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)\r\n {\r\n perror(\"socket\");\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n\r\n \/* init local addr structure and other params *\/\r\n my_addr.sin_family = AF_INET;\r\n my_addr.sin_port = htons(port);\r\n my_addr.sin_addr.s_addr = htonl(INADDR_ANY);\r\n addrlen = sizeof(struct sockaddr_in);\r\n\r\n \/* bind addr structure with socket *\/\r\n if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)\r\n {\r\n perror(\"bind\");\r\n close(servSockfd);\r\n exit(EXIT_FAILURE);\r\n }\r\n\r\n \/*Set servSockfd to be non-blocking*\/\r\n fcntl(servSockfd,F_SETFL,O_NONBLOCK);\r\n\r\n \/* set the socket in passive mode (only used for accept())\r\n * and set the list size for pending connection*\/\r\n listen(servSockfd,SOMAXCONN);\r\n\r\n max_select=servSockfd;\r\n\r\n list_client=new std::vector<EASEAClientData>;\r\n }\r\n\r\n\/**\r\n * \/brief Destructor of AudioMonitorServer\r\n **\/\r\nAudioMonitorServer::~AudioMonitorServer(){\r\n \/*close every opened socket*\/\r\n unsigned int i;\r\n\r\n for(i=0;i<list_client->size();i++){\r\n close(list_client->at(i).getSocket());\r\n }\r\n\r\n}\r\n\r\n\r\nvoid AudioMonitorServer::signalHandler(){\r\n \/*Signal handler in case of ^C, to close the sockets*\/\r\n \/\/terminaison.sa_handler=sigIntEvent;\r\n sigfillset(&terminaison.sa_mask);\r\n terminaison.sa_flags=0;\r\n\r\n sigaction(SIGINT,&terminaison,NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid AudioMonitorServer::sigIntEvent(int sig){\r\n unsigned int i;\r\n\r\n close(servSockfd);\t\r\n\r\n for(i=0;i<list_client->size();i++){\r\n \/\/send(list_client[i].getSocket(),\"000\/END\",8,0);\r\n close(list_client->at(i).getSocket());\r\n }\r\n\r\n exit(0);\r\n}\r\n\r\n\r\nvoid AudioMonitorServer::buildSocketList(){\r\n unsigned int i;\r\n\r\n FD_ZERO(&rdclient);\r\n FD_SET(servSockfd,&rdclient);\r\n\r\n for(i=0;i<list_client->size();i++){\r\n FD_SET(list_client->at(i).getSocket(),&rdclient);\r\n }\r\n\r\n}\r\n\r\nvoid AudioMonitorServer::newClient(){\r\n int tmp_sockfd;\r\n EASEAClientData* new_client;\r\n \r\n tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);\r\n\r\n \/*selected need to know the highest numerical socket value*\/\r\n if(tmp_sockfd>max_select){\r\n max_select=tmp_sockfd;\r\n }\r\n\r\n if (debug) {\r\n std::cout<<\"nouveaux client\"<<std::endl;\r\n }\r\n\r\n \/*Adding the newly connected client to the list of client*\/\r\n new_client = new EASEAClientData(tmp_sockfd);\r\n new_client->setIP(inet_ntoa(my_addr.sin_addr));\r\n new_client->setPort(ntohs(my_addr.sin_port));\r\n list_client->push_back(*new_client);\t\r\n\r\n}\r\n\r\nvoid AudioMonitorServer::recvSomething(){\r\n if(FD_ISSET(servSockfd,&rdclient))\r\n newClient();\r\n else\r\n recvFromClient();\r\n\r\n}\r\n\r\n\/*FAIRE DES STRUCTS POUR L'ENVOI\/RECEPTION*\/\r\n\/* Case new data from known client*\/\r\n\/* Check whose fd changed and received from them*\/\r\nvoid AudioMonitorServer::recvFromClient(){\r\n char buf[1024];\r\n float* dec=(float*)buf;\r\n\r\n unsigned int i; \r\n EASEAClientData* changedClient;\r\n memset(buf,'\\0',1024); \/\/reset buffer\r\n \r\n for(i=0;i<list_client->size();i++){\r\n if(list_client->at(i).getSocket()!=0){\r\n if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){\r\n \r\n changedClient=&list_client->at(i);\r\n \/*TRES CRADE: FAIRE UN *HEADER* QUI CONTIENT UN CODE IDENTIFICATEUR PLUTOT*\/\r\n if(recv(changedClient->getSocket(),buf,1024,0)==sizeof(bool)){\r\n \r\n if ((bool*)buf[0]) {\r\n compo->aReception();\r\n }\r\n if (!(bool*)buf[0]) {\r\n compo->aSending();\r\n }\r\n\r\n }\r\n else {\r\n if (!changedClient->toIgnore()) {\r\n changedClient->addData(dec[0],dec[1],dec[2],dec[3]);\r\n \r\n if (debug){\r\n std::cout<<\"I have received something from \"<<\r\n changedClient->getIP()<<\":\"<<changedClient->getPort()\r\n <<std::endl;\r\n std::cout<<dec[0]<<\" \"<<dec[1]<<\" \"<<dec[2]<<\" \"<<dec[3]<<std::endl;\r\n }\r\n\r\n compo->notify(changedClient);\r\n }\r\n else{\r\n list_client->at(i).setIgnoreFlag(false);\r\n }\r\n }\r\n\r\n }\r\n }\r\n }\r\n\r\n}\r\n\r\n\r\n\/**\r\n * \/brief Start the server, which will never stop listening \r\n **\/\r\nvoid AudioMonitorServer::start(){\r\n\r\n\r\n debug=1; \r\n\r\n while(1){\r\n\r\n buildSocketList();\r\n\r\n if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){\r\n recvSomething();\r\n }\r\n }\r\n}\r\n\r\n\r\n\/**\r\n* \/brief Add a Compositor\r\n**\/\r\nvoid AudioMonitorServer::setCompositor(Compositor* compo){\r\n this->compo=compo;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <errno.h>\n#include <time.h>\n#include <limits.h>\n#include <ctype.h>\n#include <mongoose.h>\n#include <json.hpp>\n\n#if defined(_WIN32)\n#pragma comment(lib, \"ws2_32.lib\")\n\/\/#pragma comment(lib, \"libtesseract302.lib\")\n\/\/#pragma comment(lib, \"liblept168.lib\")\n#endif\n\n\/** SHA256 *\/\n#define SHA256_BLOCK_SIZE 32 \n\ntypedef struct\n{\n unsigned char data[64];\n unsigned int datalen;\n unsigned long long bitlen;\n unsigned int state[8];\n} SHA256_CTX;\n\n\/*********************** FUNCTION DECLARATIONS **********************\/\nextern \"C\" {\n void sha256_init(SHA256_CTX *ctx);\n void sha256_update(SHA256_CTX *ctx, const unsigned char data[], size_t len);\n void sha256_final(SHA256_CTX *ctx, unsigned char hash[]);\n}\n\nstatic void\nto_hexstring(unsigned char hash[SHA256_BLOCK_SIZE], char hex[SHA256_BLOCK_SIZE * 2 + 1])\n{\n static const char hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n for (auto i = 0; i < SHA256_BLOCK_SIZE; ++i) {\n const char b = hash[i];\n hex[i * 2] = hex_chars[(b & 0xf0) >> 4];\n hex[i * 2 + 1] = hex_chars[(b & 0x0f) >> 0];\n }\n}\n\/***********\/\nstatic const char *s_http_port = \"9090\";\n\nstruct FileWriterData\n{\n FILE *fd;\n size_t bytes_left;\n SHA256_CTX ctx;\n char hash[SHA256_BLOCK_SIZE * 2 + 1];\n char mime[256];\n};\n\nstruct FileObject\n{\n std::string hash;\n std::string mime;\n std::string content;\n std::string created_at;\n\n std::string json;\n};\n\nchar* \ntime_to_string(const struct tm *timeptr)\n{\n static char result[40];\n sprintf(result, \"%.2d:%.2d:%.2d %.2d.%.2d.%.4d\",\n timeptr->tm_hour,\n timeptr->tm_min, \n timeptr->tm_sec,\n timeptr->tm_mday,\n timeptr->tm_mon + 1,\n 1900 + timeptr->tm_year);\n return result;\n}\n\nvoid\nrecognizer_push(const char * const hash);\nvoid\nrecognizer_start();\n\nstatic void\nload_file_object(const char * const hash, struct FileObject *fo)\n{\n *fo = {};\n std::string filename(hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"r\");\n if (fd != nullptr) {\n char buffer[256];\n std::string content;\n int ret;\n\n while ((ret = fread(buffer, 1, sizeof(buffer), fd)) > 0) {\n content += std::string(buffer, ret);\n }\n fclose(fd);\n\n auto jsonObject = nlohmann::json::parse(content);\n fo->hash = jsonObject[\"filename\"].get<std::string>();\n fo->mime = jsonObject[\"content_type\"].get<std::string>();\n if (!jsonObject[\"content\"].is_null()) {\n fo->content = jsonObject[\"content\"].get<std::string>();\n }\n fo->created_at = jsonObject[\"created_at\"].get<std::string>();\n fo->json = content;\n }\n}\n\nstatic std::string\nto_json(const char * const hash, const char * const mime, const char * const content = nullptr, bool store = true)\n{\n time_t rawtime;\n struct tm *timeinfo;\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n nlohmann::json jsonObject = {\n { \"filename\", hash },\n { \"content_type\", mime },\n { \"created_at\", time_to_string(timeinfo) }\n };\n if (content != nullptr)\n jsonObject[\"content\"] = content;\n auto simplify = jsonObject.dump(2);\n if (store) {\n std::string filename(hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"w\");\n if (fd != nullptr) {\n fwrite(simplify.c_str(), 1, simplify.size(), fd);\n fclose(fd);\n }\n }\n return simplify;\n}\n\nstatic void\nsave_object(FileObject &object)\n{\n nlohmann::json jsonObject = {\n { \"filename\", object.hash },\n { \"content_type\", object.mime },\n { \"created_at\", object.created_at },\n { \"content\", object.content },\n };\n std::string filename(object.hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"w\");\n auto simplify = jsonObject.dump(2);\n if (fd != nullptr) {\n fwrite(simplify.c_str(), 1, simplify.size(), fd);\n fclose(fd);\n }\n}\n\nvoid\nsave_content(const char * const hash, const std::string &content)\n{\n FileObject object;\n\n load_file_object(hash, &object);\n object.content = content;\n save_object(object);\n}\n\n\n\nstatic void handle_request(struct mg_connection *nc)\n{\n\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\"\n \"<html><body>Upload example.\"\n \"<form method=\\\"POST\\\" action=\\\"\/upload\\\" \"\n \" enctype=\\\"multipart\/form-data\\\">\"\n \"<input type=\\\"file\\\" name=\\\"file\\\" \/> <br\/>\"\n \"<input type=\\\"submit\\\" value=\\\"Upload\\\" \/>\"\n \"<\/form><\/body><\/html>\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n}\n\nstatic void handle_recv(struct mg_connection *nc)\n{\n auto data = static_cast<struct FileWriterData *>(nc->user_data);\n\n if (data == nullptr) {\n \/\/ This is a new connection, try to parse HTTP request.\n struct http_message hm;\n int req_len = mg_parse_http(nc->recv_mbuf.buf, nc->recv_mbuf.len, &hm,\n 1 \/* is_req *\/);\n\n if (req_len < 0 ||\n (req_len == 0 && nc->recv_mbuf.len >= MG_MAX_HTTP_REQUEST_SIZE)) {\n nc->flags |= MG_F_CLOSE_IMMEDIATELY;\n } else if (req_len == 0) {\n \/\/ Request is not complete yet, do nothing.\n } else if (mg_vcasecmp(&hm.method, \"POST\") == 0 &&\n mg_vcmp(&hm.uri, \"\/new\") == 0) {\n \/\/ This is the request that we don't want to buffer in memory.\n\n if (hm.body.len == static_cast<size_t>(~0) || hm.body.len == 0) {\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 411 Content-Length required\\r\\n\"\n \"Content-Length: 0\\r\\n\\r\\n\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n return;\n }\n\n \/\/ Reset proto_handler so Mongoose's http_handler() won't get confused\n \/\/ once we start removing data from the buffer.\n nc->proto_handler = nullptr;\n\n \/\/ Headers will be inaccessible later, so put everything we need into\n \/\/ user_data.\n data = static_cast<struct FileWriterData *>(calloc(1, sizeof(struct FileWriterData)));\n {\n for (auto i = 0; i < MG_MAX_HTTP_HEADERS && hm.header_names[i].p != nullptr; ++i) {\n auto n = hm.header_names[i];\n if (!strnicmp(n.p, \"Content-Type\", n.len)) {\n n = hm.header_values[i];\n auto it = n.p;\n auto len = n.len - (it - n.p);\n while (it && *it == ' ' && (it - n.p) < n.len)\n ++it;\n auto start = it;\n it = n.p + n.len - 1;\n while (it && (*it == '\\r' || *it == '\\n' || *it == ' ') && it > n.p)\n --it, --len;\n strncpy(data->mime, start, len);\n }\n }\n }\n data->bytes_left = hm.body.len;\n data->fd = tmpfile();\n sha256_init(&data->ctx);\n if (data->fd == nullptr) {\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 500 Failed to open a file\\r\\n\"\n \"Content-Length: 0\\r\\n\\r\\n\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n return;\n }\n nc->user_data = static_cast<void *>(data);\n\n \/\/ Remove the headers from the buffer.\n mbuf_remove(&nc->recv_mbuf, hm.body.p - nc->recv_mbuf.buf);\n\n \/\/ Invoke itself again to write the piece of the body that is already in\n \/\/ the buffer.\n handle_recv(nc);\n }\n } else { \/\/ data != NULL\n size_t to_write = data->bytes_left, written = 0;\n if (nc->recv_mbuf.len < to_write)\n to_write = nc->recv_mbuf.len;\n written = fwrite(nc->recv_mbuf.buf, 1, to_write, data->fd);\n sha256_update(&data->ctx, reinterpret_cast<unsigned char * const>(nc->recv_mbuf.buf), written);\n mbuf_remove(&nc->recv_mbuf, written);\n data->bytes_left -= written;\n if (data->bytes_left <= 0) {\n FileObject object;\n std::string json;\n long size;\n unsigned char digest[SHA256_BLOCK_SIZE];\n\n \/\/ Request is complete, do something meaningful here.\n sha256_final(&data->ctx, digest);\n to_hexstring(digest, data->hash);\n load_file_object(data->hash, &object);\n {\n size = ftell(data->fd);\n fseek(data->fd, 0, SEEK_SET);\n auto fd = fopen(data->hash, \"wb\");\n if (fd) {\n char buffer[256];\n int readed;\n while ((readed = fread(buffer, 1, sizeof(buffer), data->fd)) > 0) {\n fwrite(buffer, 1, readed, fd);\n }\n fclose(fd);\n }\n }\n if (!object.hash.empty()) {\n fprintf(stdout, \"%s already stored at %s\\n\", data->hash, object.created_at.c_str());\n json = object.json;\n } else {\n json = to_json(data->hash, data->mime);\n recognizer_push(data->hash);\n }\n mg_printf(nc,\n \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: application\/json; charset=utf-8\\r\\n\"\n \"Connection: close\\r\\n\\r\\n\"\n \"%s\",\n json.c_str());\n nc->flags |= MG_F_SEND_AND_CLOSE;\n \/\/ handle_close will free the resources.\n }\n }\n}\n\n\/\/ Make sure we free all allocated resources\nstatic void handle_close(struct mg_connection *nc)\n{\n auto data = static_cast<struct FileWriterData *>(nc->user_data);\n\n if (data != nullptr) {\n \n fclose(data->fd);\n free(data);\n nc->user_data = nullptr;\n }\n}\n\nstatic void ev_handler(struct mg_connection *nc, int ev, void *ev_data)\n{\n (void)ev_data;\n switch (ev) {\n case MG_EV_HTTP_REQUEST:\n \/\/ Invoked when the full HTTP request is in the buffer (including body).\n handle_request(nc);\n break;\n case MG_EV_RECV:\n \/\/ Invoked every time new data arrives.\n handle_recv(nc);\n break;\n case MG_EV_CLOSE:\n handle_close(nc);\n break;\n }\n}\n\nint main(void)\n{\n struct mg_mgr mgr;\n struct mg_connection *nc;\n\n mg_mgr_init(&mgr, nullptr);\n nc = mg_bind(&mgr, s_http_port, ev_handler);\n\n \/\/ Set up HTTP server parameters\n mg_set_protocol_http_websocket(nc);\n mg_enable_multithreading(nc);\n\n printf(\"Starting web server on port %s\\n\", s_http_port);\n recognizer_start();\n for (;;) {\n mg_mgr_poll(&mgr, 1000);\n }\n mg_mgr_free(&mgr);\n\n return EXIT_SUCCESS;\n}\n<commit_msg>FIX: strnicmp on linux<commit_after>#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <errno.h>\n#include <time.h>\n#include <limits.h>\n#include <ctype.h>\n#include <mongoose.h>\n#include <json.hpp>\n\n#if defined(_WIN32)\n#pragma comment(lib, \"ws2_32.lib\")\n\/\/#pragma comment(lib, \"libtesseract302.lib\")\n\/\/#pragma comment(lib, \"liblept168.lib\")\n#else\n#define strnicmp strncasecmp\n#endif\n\n\/** SHA256 *\/\n#define SHA256_BLOCK_SIZE 32 \n\ntypedef struct\n{\n unsigned char data[64];\n unsigned int datalen;\n unsigned long long bitlen;\n unsigned int state[8];\n} SHA256_CTX;\n\n\/*********************** FUNCTION DECLARATIONS **********************\/\nextern \"C\" {\n void sha256_init(SHA256_CTX *ctx);\n void sha256_update(SHA256_CTX *ctx, const unsigned char data[], size_t len);\n void sha256_final(SHA256_CTX *ctx, unsigned char hash[]);\n}\n\nstatic void\nto_hexstring(unsigned char hash[SHA256_BLOCK_SIZE], char hex[SHA256_BLOCK_SIZE * 2 + 1])\n{\n static const char hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n for (auto i = 0; i < SHA256_BLOCK_SIZE; ++i) {\n const char b = hash[i];\n hex[i * 2] = hex_chars[(b & 0xf0) >> 4];\n hex[i * 2 + 1] = hex_chars[(b & 0x0f) >> 0];\n }\n}\n\/***********\/\nstatic const char *s_http_port = \"9090\";\n\nstruct FileWriterData\n{\n FILE *fd;\n size_t bytes_left;\n SHA256_CTX ctx;\n char hash[SHA256_BLOCK_SIZE * 2 + 1];\n char mime[256];\n};\n\nstruct FileObject\n{\n std::string hash;\n std::string mime;\n std::string content;\n std::string created_at;\n\n std::string json;\n};\n\nchar* \ntime_to_string(const struct tm *timeptr)\n{\n static char result[40];\n sprintf(result, \"%.2d:%.2d:%.2d %.2d.%.2d.%.4d\",\n timeptr->tm_hour,\n timeptr->tm_min, \n timeptr->tm_sec,\n timeptr->tm_mday,\n timeptr->tm_mon + 1,\n 1900 + timeptr->tm_year);\n return result;\n}\n\nvoid\nrecognizer_push(const char * const hash);\nvoid\nrecognizer_start();\n\nstatic void\nload_file_object(const char * const hash, struct FileObject *fo)\n{\n *fo = {};\n std::string filename(hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"r\");\n if (fd != nullptr) {\n char buffer[256];\n std::string content;\n int ret;\n\n while ((ret = fread(buffer, 1, sizeof(buffer), fd)) > 0) {\n content += std::string(buffer, ret);\n }\n fclose(fd);\n\n auto jsonObject = nlohmann::json::parse(content);\n fo->hash = jsonObject[\"filename\"].get<std::string>();\n fo->mime = jsonObject[\"content_type\"].get<std::string>();\n if (!jsonObject[\"content\"].is_null()) {\n fo->content = jsonObject[\"content\"].get<std::string>();\n }\n fo->created_at = jsonObject[\"created_at\"].get<std::string>();\n fo->json = content;\n }\n}\n\nstatic std::string\nto_json(const char * const hash, const char * const mime, const char * const content = nullptr, bool store = true)\n{\n time_t rawtime;\n struct tm *timeinfo;\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n nlohmann::json jsonObject = {\n { \"filename\", hash },\n { \"content_type\", mime },\n { \"created_at\", time_to_string(timeinfo) }\n };\n if (content != nullptr)\n jsonObject[\"content\"] = content;\n auto simplify = jsonObject.dump(2);\n if (store) {\n std::string filename(hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"w\");\n if (fd != nullptr) {\n fwrite(simplify.c_str(), 1, simplify.size(), fd);\n fclose(fd);\n }\n }\n return simplify;\n}\n\nstatic void\nsave_object(FileObject &object)\n{\n nlohmann::json jsonObject = {\n { \"filename\", object.hash },\n { \"content_type\", object.mime },\n { \"created_at\", object.created_at },\n { \"content\", object.content },\n };\n std::string filename(object.hash);\n FILE *fd;\n filename += \".json\";\n fd = fopen(filename.c_str(), \"w\");\n auto simplify = jsonObject.dump(2);\n if (fd != nullptr) {\n fwrite(simplify.c_str(), 1, simplify.size(), fd);\n fclose(fd);\n }\n}\n\nvoid\nsave_content(const char * const hash, const std::string &content)\n{\n FileObject object;\n\n load_file_object(hash, &object);\n object.content = content;\n save_object(object);\n}\n\n\n\nstatic void handle_request(struct mg_connection *nc)\n{\n\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\"\n \"<html><body>Upload example.\"\n \"<form method=\\\"POST\\\" action=\\\"\/upload\\\" \"\n \" enctype=\\\"multipart\/form-data\\\">\"\n \"<input type=\\\"file\\\" name=\\\"file\\\" \/> <br\/>\"\n \"<input type=\\\"submit\\\" value=\\\"Upload\\\" \/>\"\n \"<\/form><\/body><\/html>\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n}\n\nstatic void handle_recv(struct mg_connection *nc)\n{\n auto data = static_cast<struct FileWriterData *>(nc->user_data);\n\n if (data == nullptr) {\n \/\/ This is a new connection, try to parse HTTP request.\n struct http_message hm;\n int req_len = mg_parse_http(nc->recv_mbuf.buf, nc->recv_mbuf.len, &hm,\n 1 \/* is_req *\/);\n\n if (req_len < 0 ||\n (req_len == 0 && nc->recv_mbuf.len >= MG_MAX_HTTP_REQUEST_SIZE)) {\n nc->flags |= MG_F_CLOSE_IMMEDIATELY;\n } else if (req_len == 0) {\n \/\/ Request is not complete yet, do nothing.\n } else if (mg_vcasecmp(&hm.method, \"POST\") == 0 &&\n mg_vcmp(&hm.uri, \"\/new\") == 0) {\n \/\/ This is the request that we don't want to buffer in memory.\n\n if (hm.body.len == static_cast<size_t>(~0) || hm.body.len == 0) {\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 411 Content-Length required\\r\\n\"\n \"Content-Length: 0\\r\\n\\r\\n\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n return;\n }\n\n \/\/ Reset proto_handler so Mongoose's http_handler() won't get confused\n \/\/ once we start removing data from the buffer.\n nc->proto_handler = nullptr;\n\n \/\/ Headers will be inaccessible later, so put everything we need into\n \/\/ user_data.\n data = static_cast<struct FileWriterData *>(calloc(1, sizeof(struct FileWriterData)));\n {\n for (auto i = 0; i < MG_MAX_HTTP_HEADERS && hm.header_names[i].p != nullptr; ++i) {\n auto n = hm.header_names[i];\n if (!strnicmp(n.p, \"Content-Type\", n.len)) {\n n = hm.header_values[i];\n auto it = n.p;\n auto len = n.len - (it - n.p);\n while (it && *it == ' ' && (it - n.p) < n.len)\n ++it;\n auto start = it;\n it = n.p + n.len - 1;\n while (it && (*it == '\\r' || *it == '\\n' || *it == ' ') && it > n.p)\n --it, --len;\n strncpy(data->mime, start, len);\n }\n }\n }\n data->bytes_left = hm.body.len;\n data->fd = tmpfile();\n sha256_init(&data->ctx);\n if (data->fd == nullptr) {\n mg_printf(nc, \"%s\",\n \"HTTP\/1.1 500 Failed to open a file\\r\\n\"\n \"Content-Length: 0\\r\\n\\r\\n\");\n nc->flags |= MG_F_SEND_AND_CLOSE;\n return;\n }\n nc->user_data = static_cast<void *>(data);\n\n \/\/ Remove the headers from the buffer.\n mbuf_remove(&nc->recv_mbuf, hm.body.p - nc->recv_mbuf.buf);\n\n \/\/ Invoke itself again to write the piece of the body that is already in\n \/\/ the buffer.\n handle_recv(nc);\n }\n } else { \/\/ data != NULL\n size_t to_write = data->bytes_left, written = 0;\n if (nc->recv_mbuf.len < to_write)\n to_write = nc->recv_mbuf.len;\n written = fwrite(nc->recv_mbuf.buf, 1, to_write, data->fd);\n sha256_update(&data->ctx, reinterpret_cast<unsigned char * const>(nc->recv_mbuf.buf), written);\n mbuf_remove(&nc->recv_mbuf, written);\n data->bytes_left -= written;\n if (data->bytes_left <= 0) {\n FileObject object;\n std::string json;\n long size;\n unsigned char digest[SHA256_BLOCK_SIZE];\n\n \/\/ Request is complete, do something meaningful here.\n sha256_final(&data->ctx, digest);\n to_hexstring(digest, data->hash);\n load_file_object(data->hash, &object);\n {\n size = ftell(data->fd);\n fseek(data->fd, 0, SEEK_SET);\n auto fd = fopen(data->hash, \"wb\");\n if (fd) {\n char buffer[256];\n int readed;\n while ((readed = fread(buffer, 1, sizeof(buffer), data->fd)) > 0) {\n fwrite(buffer, 1, readed, fd);\n }\n fclose(fd);\n }\n }\n if (!object.hash.empty()) {\n fprintf(stdout, \"%s already stored at %s\\n\", data->hash, object.created_at.c_str());\n json = object.json;\n } else {\n json = to_json(data->hash, data->mime);\n recognizer_push(data->hash);\n }\n mg_printf(nc,\n \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: application\/json; charset=utf-8\\r\\n\"\n \"Connection: close\\r\\n\\r\\n\"\n \"%s\",\n json.c_str());\n nc->flags |= MG_F_SEND_AND_CLOSE;\n \/\/ handle_close will free the resources.\n }\n }\n}\n\n\/\/ Make sure we free all allocated resources\nstatic void handle_close(struct mg_connection *nc)\n{\n auto data = static_cast<struct FileWriterData *>(nc->user_data);\n\n if (data != nullptr) {\n \n fclose(data->fd);\n free(data);\n nc->user_data = nullptr;\n }\n}\n\nstatic void ev_handler(struct mg_connection *nc, int ev, void *ev_data)\n{\n (void)ev_data;\n switch (ev) {\n case MG_EV_HTTP_REQUEST:\n \/\/ Invoked when the full HTTP request is in the buffer (including body).\n handle_request(nc);\n break;\n case MG_EV_RECV:\n \/\/ Invoked every time new data arrives.\n handle_recv(nc);\n break;\n case MG_EV_CLOSE:\n handle_close(nc);\n break;\n }\n}\n\nint main(void)\n{\n struct mg_mgr mgr;\n struct mg_connection *nc;\n\n mg_mgr_init(&mgr, nullptr);\n nc = mg_bind(&mgr, s_http_port, ev_handler);\n\n \/\/ Set up HTTP server parameters\n mg_set_protocol_http_websocket(nc);\n mg_enable_multithreading(nc);\n\n printf(\"Starting web server on port %s\\n\", s_http_port);\n recognizer_start();\n for (;;) {\n mg_mgr_poll(&mgr, 1000);\n }\n mg_mgr_free(&mgr);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"player.h\"\n#include \"Hand.h\"\n\nconst char* Player::VERSION = \"Non-Default C++ folding player\";\n\nint minimum_raise;\nint in_action;\nint our_bet;\nint current_buy_in;\nHand2 hole_cards;\n\nint toAction(HoleCardRank rank) {\n std::cerr << \"XXXXXXXXX action is \" << int(rank) << std::endl;\n\n switch (rank) {\n case HoleCardRank::ALLIN:\n return 5000;\n case HoleCardRank::RAISABLE:\n return current_buy_in - our_bet + 3*minimum_raise;\n default:\n std::cerr << \"Unknown action\" << std::endl;\n case HoleCardRank::FOLDABLE:\n return 0;\n case HoleCardRank::CALLABLE:\n return current_buy_in - our_bet;\n }\n}\n\nint preFlop(json::Value game_state) {\n return toAction(rankHoleCard(hole_cards));\n}\n\nint flop(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in flop()\" << std::endl;\n return preFlop(game_state);\n }\n\n int rank = game_state[\"eval\"][\"rank\"].ToInt();\n\n switch (rank) {\n default:\n std::cerr << \"Unknown rank\" << std::endl;\n case 0: return toAction(HoleCardRank::FOLDABLE);\n case 1: return toAction(HoleCardRank::CALLABLE);\n case 2: return toAction(HoleCardRank::CALLABLE);\n case 3: return toAction(HoleCardRank::RAISABLE);\n case 4: return toAction(HoleCardRank::RAISABLE);\n case 5: return toAction(HoleCardRank::ALLIN);\n case 6: return toAction(HoleCardRank::ALLIN);\n case 7: return toAction(HoleCardRank::ALLIN);\n case 8: return toAction(HoleCardRank::ALLIN);\n }\n}\n\nint turn(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in turn()\" << std::endl;\n return preFlop(game_state);\n }\n return flop(game_state);\n}\n\nint river(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in river()\" << std::endl;\n return preFlop(game_state);\n }\n return flop(game_state);\n}\n\nint Player::betRequest(json::Value game_state) {\n minimum_raise = game_state[\"minimum_raise\"].ToInt();\n in_action = game_state[\"in_action\"].ToInt();\n our_bet = game_state[\"players\"][in_action][\"bet\"];\n current_buy_in = game_state[\"current_buy_in\"];\n\n hole_cards = parseHand(game_state[\"players\"][in_action][\"hole_cards\"]);\n\n std::cerr << \"XXXXXXXXXX Our hand is = \" << hole_cards << std::endl;\n\n switch (game_state[\"community_cards\"].ToArray().size()) {\n default:\n case 0:\n return preFlop(game_state);\n case 3:\n return flop(game_state);\n case 4:\n return turn(game_state);\n case 5:\n return river(game_state);\n }\n\n}\n\nvoid Player::showdown(json::Value game_state)\n{\n}\n<commit_msg>Pwnies<commit_after>#include <iostream>\n\n#include \"player.h\"\n#include \"Hand.h\"\n\nconst char* Player::VERSION = \"Pwnies\";\n\nint minimum_raise;\nint in_action;\nint our_bet;\nint current_buy_in;\nHand2 hole_cards;\n\nint toAction(HoleCardRank rank) {\n std::cerr << \"XXXXXXXXX action is \" << int(rank) << std::endl;\n\n switch (rank) {\n case HoleCardRank::ALLIN:\n return 5000;\n case HoleCardRank::RAISABLE:\n return current_buy_in - our_bet + 3*minimum_raise;\n default:\n std::cerr << \"Unknown action\" << std::endl;\n case HoleCardRank::FOLDABLE:\n return 0;\n case HoleCardRank::CALLABLE:\n return current_buy_in - our_bet;\n }\n}\n\nint preFlop(json::Value game_state) {\n return toAction(rankHoleCard(hole_cards));\n}\n\nint flop(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in flop()\" << std::endl;\n return preFlop(game_state);\n }\n\n int rank = game_state[\"eval\"][\"rank\"].ToInt();\n\n switch (rank) {\n default:\n std::cerr << \"Unknown rank\" << std::endl;\n case 0: return toAction(HoleCardRank::FOLDABLE);\n case 1: return toAction(HoleCardRank::CALLABLE);\n case 2: return toAction(HoleCardRank::CALLABLE);\n case 3: return toAction(HoleCardRank::RAISABLE);\n case 4: return toAction(HoleCardRank::RAISABLE);\n case 5: return toAction(HoleCardRank::ALLIN);\n case 6: return toAction(HoleCardRank::ALLIN);\n case 7: return toAction(HoleCardRank::ALLIN);\n case 8: return toAction(HoleCardRank::ALLIN);\n }\n}\n\nint turn(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in turn()\" << std::endl;\n return preFlop(game_state);\n }\n return flop(game_state);\n}\n\nint river(json::Value game_state) {\n if (!game_state.HasKey(\"eval\")) {\n std::cerr << \"NO eval in river()\" << std::endl;\n return preFlop(game_state);\n }\n return flop(game_state);\n}\n\nint Player::betRequest(json::Value game_state) {\n minimum_raise = game_state[\"minimum_raise\"].ToInt();\n in_action = game_state[\"in_action\"].ToInt();\n our_bet = game_state[\"players\"][in_action][\"bet\"];\n current_buy_in = game_state[\"current_buy_in\"];\n\n hole_cards = parseHand(game_state[\"players\"][in_action][\"hole_cards\"]);\n\n std::cerr << \"XXXXXXXXXX Our hand is = \" << hole_cards << std::endl;\n\n switch (game_state[\"community_cards\"].ToArray().size()) {\n default:\n case 0:\n return preFlop(game_state);\n case 3:\n return flop(game_state);\n case 4:\n return turn(game_state);\n case 5:\n return river(game_state);\n }\n\n}\n\nvoid Player::showdown(json::Value game_state)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include \"Experience.h\"\n#include \"StateSpace.h\"\n#include \"Action.h\"\n\n\/\/utility calculation function\ndouble q();\n\n\/\/reward function based off raw position and velocity\ndouble state_reward(const double theta, const double theta_dot);\n\nint main()\n{\n\tstd::srand(std::time(NULL));\n\t\n\t\/\/create the state space\n\tStateSpace space(100,50);\n\t\n\t\/\/array to hold the current state of the robot\n\tdouble current_state[2]={0,0};\n\tdouble last_state[2]={0,0};\n\t\n\t\/\/create pointers to the possible actions as well as pointers to hold the chosen action and the previous action\n\tAction* actions[2],chosen_action;\n\tactions[0]=new action(FORWARDS);\n\tactions[1]=new action(BACKWARDS);\n\t\n\t\/\/evaluate state\n\tcurrent_state[0]=getPosition();\/\/!\n\tcurrent_state[1]=getVelocity();\/\/!\n\t\n\twhile(true)\n\t{\n\t\t\/\/evaluate q of last action\n\t\t\/\/current_state>>old_state\n\t\t\n\t\tchosen_action=selectAction(\/*...*\/);\n\t\t\n\t\t\/\/>>current_state\n\t}\n\t\n\tdelete actions[0];\n\tdelete actions[1];\n\t\n\treturn 1;\n}\n\ndouble q()\n{\n\treturn \/\/StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action) + learningrate(state_reward(newstate[0], newstate[1]) + gamma(StateSpace[newstate[0],newstate[1]].GetExperience().GetHighestUtility()) - StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action); \/\/ Utility calculation pseudocode\n}\n\ndouble state_reward(const double theta, const double theta_dot)\n{\n\treturn 180+theta_dot*theta\/std::abs(theta_dot);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nAction * selectAction(PriorityQueue<Action *,double> a_queue, double temp)\n{\n typedef PriorityQueue<Action *,double> PQ;\n typedef std::vector< std::pair<Action *, double> > Vec_Pair;\n typedef std::pair<Action *, double> Pair;\n \n double sum= 0;\n int i = 0;\n \n int size = a_queue.getSize();\n Vec_Pair action_vec(size);\n Pair pear;\n \n \/\/Calculate partition function by iterating over action-values\n\tfor(PQ::constIter iter = a_queue.begin(); iter < a_queue.end(); iter++)\n\t{\n\t\tsum += std::exp((iter->second)\/temp);\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/ temp) \/ sum;\n\t i++;\n\t}\n\t\/\/calculate cumulative probability distribution \n for(std::vector< std::pair<int, double> >::iterator it = action_vec.begin()+1; it < action_vec.end(); it++)\n\t{\n\t it->second += (it-1)->second;\n\t}\n \/\/seed random number generator\n\tsrand(time(NULL));\n\t\/\/generate RN between 0 and 1 \n\tdouble rand_num = (double)rand()\/ (RAND_MAX);\n\t\n\t\/\/select action based on probability \n for(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)\n {\n \/\/if RN falls within cumulative probability bin return the corresponding action\n if(rand_num < it->second){return it->first};\n }\n return -1;\n}\n<commit_msg>added Q update function<commit_after>#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include \"Experience.h\"\n#include \"StateSpace.h\"\n#include \"Action.h\"\n\n\/\/utility calculation function\ndouble q();\n\n\/\/reward function based off raw position and velocity\ndouble state_reward(const double theta, const double theta_dot);\n\nint main()\n{\n\tstd::srand(std::time(NULL));\n\t\n\t\/\/create the state space\n\tStateSpace space(100,50);\n\t\n\t\/\/array to hold the current state of the robot\n\tdouble current_state[2]={0,0};\n\tdouble last_state[2]={0,0};\n\t\n\t\/\/create pointers to the possible actions as well as pointers to hold the chosen action and the previous action\n\tAction* actions[2],chosen_action;\n\tactions[0]=new action(FORWARDS);\n\tactions[1]=new action(BACKWARDS);\n\t\n\t\/\/evaluate state\n\tcurrent_state[0]=getPosition();\/\/!\n\tcurrent_state[1]=getVelocity();\/\/!\n\t\n\twhile(true)\n\t{\n\t\t\/\/evaluate q of last action\n\t\t\/\/current_state>>old_state\n\t\t\n\t\tchosen_action=selectAction(\/*...*\/);\n\t\t\n\t\t\/\/>>current_state\n\t}\n\t\n\tdelete actions[0];\n\tdelete actions[1];\n\t\n\treturn 1;\n}\n\ndouble q()\n{\n\treturn \/\/StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action) + learningrate(state_reward(newstate[0], newstate[1]) + gamma(StateSpace[newstate[0],newstate[1]].GetExperience().GetHighestUtility()) - StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action); \/\/ Utility calculation pseudocode\n}\n\ndouble state_reward(const double theta, const double theta_dot)\n{\n\treturn 180+theta_dot*theta\/std::abs(theta_dot);\n}\n\/\/updates Q value for a state-action \nvoid updateQ(StateSpace * space, Action * action, State * current_state,\n State * old_state, double alpha, double gamma)\n{\n \/\/oldQ value \n double oldQ = (*space).StateSearch(old_state).search(action).second;\n \/\/reward given to current state \n double R = new_state->getReward();\n \/\/optimal Q value for new state i.e. first element \n double maxQ = (*space).StateSearch(current_state)[0].second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ;\n \n \/\/updates Q value\n (*space).StateSearch(old_state).search(action).second = newQ;\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nAction * selectAction(PriorityQueue<Action *,double> a_queue, double temp)\n{\n typedef PriorityQueue<Action *,double> PQ;\n typedef std::vector< std::pair<Action *, double> > Vec_Pair;\n typedef std::pair<Action *, double> Pair;\n \n double sum= 0;\n int i = 0;\n \n int size = a_queue.getSize();\n Vec_Pair action_vec(size);\n Pair pear;\n \n \/\/Calculate partition function by iterating over action-values\n\tfor(PQ::constIter iter = a_queue.begin(); iter < a_queue.end(); iter++)\n\t{\n\t\tsum += std::exp((iter->second)\/temp);\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/ temp) \/ sum;\n\t i++;\n\t}\n\t\/\/calculate cumulative probability distribution \n for(std::vector< std::pair<int, double> >::iterator it = action_vec.begin()+1; it < action_vec.end(); it++)\n\t{\n\t it->second += (it-1)->second;\n\t}\n \/\/seed random number generator\n\tsrand(time(NULL));\n\t\/\/generate RN between 0 and 1 \n\tdouble rand_num = (double)rand()\/ (RAND_MAX);\n\t\n\t\/\/select action based on probability \n for(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)\n {\n \/\/if RN falls within cumulative probability bin return the corresponding action\n if(rand_num < it->second){return it->first};\n }\n return -1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/wrdTest.hpp\"\n\nusing namespace wrd;\nusing namespace std;\n\nstruct primitiveObjTest : public wrdTest {};\n\nTEST_F(primitiveObjTest, testCreateWIntInMgd) {\n wInt origin(1);\n\n tstr<wInt> inst = origin.run(narr({origin}));\n ASSERT_TRUE(inst);\n ASSERT_EQ(origin.get(), inst->get());\n ASSERT_NE(&origin, &(*inst));\n}\n\nTEST_F(primitiveObjTest, testCloneWIntInMgd) {\n wInt origin(1);\n\n tstr<wInt> inst(origin.clone());\n ASSERT_TRUE(inst);\n ASSERT_EQ(origin.get(), inst->get());\n ASSERT_NE(&origin, &(*inst));\n}\n\nTEST_F(primitiveObjTest, testDefaultCtor) {\n wInt origin(1);\n\n tstr<wInt> inst = origin.run(narr());\n ASSERT_TRUE(inst);\n ASSERT_EQ(inst->get(), 0);\n}\n<commit_msg>wrd: test: verify primitive types uses dummy subs<commit_after>#include \"..\/..\/wrdTest.hpp\"\n\nusing namespace wrd;\nusing namespace std;\n\nstruct primitiveObjTest : public wrdTest {};\n\nTEST_F(primitiveObjTest, testCreateWIntInMgd) {\n wInt origin(1);\n\n tstr<wInt> inst = origin.run(narr({origin}));\n ASSERT_TRUE(inst);\n ASSERT_EQ(origin.get(), inst->get());\n ASSERT_NE(&origin, &(*inst));\n}\n\nTEST_F(primitiveObjTest, testCloneWIntInMgd) {\n wInt origin(1);\n\n tstr<wInt> inst(origin.clone());\n ASSERT_TRUE(inst);\n ASSERT_EQ(origin.get(), inst->get());\n ASSERT_NE(&origin, &(*inst));\n}\n\nTEST_F(primitiveObjTest, testDefaultCtor) {\n wInt origin(1);\n\n tstr<wInt> inst = origin.run(narr());\n ASSERT_TRUE(inst);\n ASSERT_EQ(inst->get(), 0);\n}\n\nTEST_F(primitiveObjTest, subsIsDummy) {\n wInt val(2);\n ASSERT_EQ(val.subs().len(), 0);\n\n bicontainable& subs = val.subs();\n ASSERT_FALSE(nul(subs));\n subs.add(\"not work\", new wInt(3));\n ASSERT_EQ(subs.len(), 0);\n ASSERT_FALSE(subs.has(\"not work\"));\n ASSERT_TRUE(subs.begin().isEnd());\n}\n<|endoftext|>"} {"text":"<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)\n #include <TMath.h>\n #include <TROOT.h>\n #include <Riostream.h>\n #include <TCanvas.h>\n\n #include <TString.h>\n\n #include <TFile.h>\n #include <TList.h>\n #include <TH1F.h>\n #include <TH1D.h>\n #include <TF2.h>\n #include <TFitResult.h>\n #include <TFitResultPtr.h>\n #include <TH2F.h>\n #include <TH3F.h>\n#endif\n \nextern TROOT *gROOT;\n\/\/extern TFile *gFile;\n\n\nvoid PostProcessCTau() {\n \/\/-----------------------------------------------------------------\n \/\/ PostProcess the histograms produced by AliAnalysisTaskCTau* \n \/\/ Produce:\n \/\/ -- V0 particle spectra (not corrected for the feeddown)\n \/\/ -- Estimated (anti)Lambda feed-down spectra (from Xi's only)\n \/\/ -- V0 particle c*tau distributions (feeddown corrected) \n \/\/-----------------------------------------------------------------\n\n TString name(\"cTau_0090\"); \/\/centrality\n \/\/TString name(\"cTau_0005\"); \/\/centrality\n \/\/TString name(\"cTau_2040\"); \/\/centrality\n \/\/TString name(\"cTau_4060\"); \/\/centrality\n \/\/TString name(\"cTau_6080\"); \/\/centrality\n \/\/TString name(\"cTau_8090\"); \/\/centrality\n\n\n \/\/+++++ Real data histograms\n TFile::Open(\"new\/real\/all\/\" + name + \".root\");\n TList *list=(TList *)gFile->Get(name); \n\n TH2F *fK0sSi=(TH2F*)list->FindObject(\"fK0sSi\");fK0sSi->Sumw2();\n TH2F *fLambdaSi=(TH2F*)list->FindObject(\"fLambdaSi\");fLambdaSi->Sumw2();\n TH1F *fXiSiP=(TH1F*)list->FindObject(\"fXiSiP\"); fXiSiP->Sumw2();\n TH2F *fLambdaBarSi=\n (TH2F*)list->FindObject(\"fLambdaBarSi\"); fLambdaBarSi->Sumw2();\n TH1F *fXiBarSiP=(TH1F*)list->FindObject(\"fXiBarSiP\"); fXiBarSiP->Sumw2();\n\n TH1F *fMult=(TH1F*)list->FindObject(\"fMult\");\n \/\/+++++\n\n const Double_t nEvents=fMult->Integral();\n\n \/\/+++++ MC histograms\n TFile::Open(\"new\/mc_b_plus\/all\/\" + name + \"_mc.root\");\n TList *listmc=(TList *)gFile->Get(name+\"_mc\"); \n\n TH2F *fK0sMC=(TH2F*)listmc->FindObject(\"fK0sMC\"); fK0sMC->Sumw2();\n TH2F *fK0sAs=(TH2F*)listmc->FindObject(\"fK0sAs\"); fK0sAs->Sumw2();\n\n TH2F *fLambdaMC=(TH2F*)listmc->FindObject(\"fLambdaMC\"); fLambdaMC->Sumw2();\n TH2F *fLambdaAs=(TH2F*)listmc->FindObject(\"fLambdaAs\"); fLambdaAs->Sumw2();\n\n TH2F *fLambdaBarMC=\n (TH2F*)listmc->FindObject(\"fLambdaBarMC\"); fLambdaBarMC->Sumw2();\n TH2F *fLambdaBarAs=\n (TH2F*)listmc->FindObject(\"fLambdaBarAs\"); fLambdaBarAs->Sumw2();\n\n TH1F *fXiSiPMC=(TH1F*)listmc->FindObject(\"fXiSiP\");fXiSiPMC->Sumw2();\n TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject(\"fLambdaFromXi\");\n fLambdaFromXi->Sumw2();\n\n TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject(\"fXiBarSiP\");fXiBarSiPMC->Sumw2();\n TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject(\"fLambdaBarFromXiBar\");\n fLambdaBarFromXiBar->Sumw2();\n \/\/+++++\n\n\n Double_t myExp2(Double_t *v, Double_t *p);\n void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);\n void Normalise(Double_t, Double_t, Double_t, Double_t, TH1 *h);\n\n const Int_t iMax=3; \/\/ Number of V0 particles\n const TString pnam[]={\"K^{0}_{S}\", \"#Lambda\", \"#bar{#Lambda}\"};\n const Double_t brch[]={0.69, 0.64, 0.64};\n const Double_t mass[]={0.4977, 1.115, 1.115};\n const Double_t ctau[]={2.68, 7.89, 7.89};\n\n const TH2 *in[]={\n fK0sSi,fK0sAs,fK0sMC,\n fLambdaSi,fLambdaAs,fLambdaMC,\n fLambdaBarSi,fLambdaBarAs,fLambdaBarMC\n };\n TH1 *fd[]={\n 0,0,0,\n fLambdaFromXi,fXiSiP,fXiSiPMC,\n fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC\n };\n Double_t wbx=fK0sSi->GetBinWidth(3);\n Int_t nbx=fLambdaFromXi->GetNbinsX();\n Int_t nby=fLambdaFromXi->GetNbinsY();\n Int_t nbz=fLambdaFromXi->GetNbinsZ();\n \n for (Int_t i=0; i<iMax; i++) {\n TH2 *cr=(TH2*)in[i*3 + 0]->Clone();\n Correct(cr, in[i*3 + 1], in[i*3 + 2]);\n\n \/\/++++ pT spectrum\n TH1 *pt=cr->ProjectionX(\"_px\",0,-1,\"e\");\n TString ptName = pnam[i] + \" p_{T} spectrum\";\n pt->SetTitle(ptName.Data());\n Normalise(brch[i], 2*0.5, wbx, nEvents, pt); \n Double_t eipt=0., ipt=pt->IntegralAndError(1, nbx, eipt);\n\n new TCanvas; \n pt->Draw(); \n\n if (i>0) {\n \/\/++++ feeddown\n\t TH3 *fd3=(TH3*)fd[3*i + 0];\n\t TH1 *rl =(TH1*)fd[3*i + 1];\n\t TH1 *mc =(TH1*)fd[3*i + 2];\n rl->Divide(mc);\n \n for (Int_t k=1; k<=nbx; k++) {\n for (Int_t l=1; l<=nby; l++) {\n for (Int_t m=1; m<=nbz; m++) {\n Float_t c=fd3->GetBinContent(k,l,m);\n c *= rl->GetBinContent(m);\n fd3->SetBinContent(k,l,m,c);\n\t\t }\n\t }\n\t }\n\n TH2 *fd2=(TH2*)fd3->Project3D(\"yxe\");\n Correct(fd2, in[i*3 + 1], in[i*3 + 2]);\n\n TH1 *fd1=fd2->ProjectionX(\"_px\",0,-1,\"e\");\n Normalise(brch[i], 2*0.5, wbx, nEvents, fd1);\n Double_t eifd=0., ifd=fd1->IntegralAndError(1, nbx, eifd);\n\n Double_t f=ifd\/ipt;\n Double_t ef=1\/ipt*TMath::Sqrt(eifd*eifd + f*f*eipt*eipt);\n cout<<endl<<\"Global FD correction: \"<<f<<\"+\/-\"<<ef<<endl;\n\n \/\/new TCanvas();\n fd1->Draw(\"same\");\n\n cr->Add(fd2,-1);\n } \n \/\/continue;\n \n \/\/++++ c*tau\n TF2 *f2=new TF2(\"myexpo2\",myExp2,0.,10.,0.,100.,1+1+1+nbx);\n f2->SetParameter(0, ctau[i]);\n f2->FixParameter(1, ctau[i]);\n f2->FixParameter(2, mass[i]);\n for (Int_t p=1+1+1; p<=nbx+1+1; p++) \n f2->SetParameter(p,fK0sSi->GetBinContent(p,1));\n\n new TCanvas; \n TFitResultPtr r=cr->Fit(f2,\"SQ\");\n\n Int_t status = r;\n Double_t chi2 = r->Chi2()\/r->Ndf(); \n Double_t slope = r->Parameter(0); \n Double_t error = r->ParError(0); \n cout<<endl<<pnam[i]<<\" \\tstatus: \"<<status<<\" chi2\/ndf: \"<<chi2<<\n\t\"\\tc*tau: \"<<slope<<\"+\/-\"<<error<<endl<<endl;\n }\n\n return;\n} \n\nDouble_t myExp2(Double_t *v, Double_t *p) {\n Double_t pt=v[0];\n Double_t lt=v[1];\n\n Double_t ctau=p[1];\n Double_t mass=p[2];\n Double_t ct=mass*lt\/pt;\n if ((lt < 2) || (ct > 2.5*ctau)) {\n TF1::RejectPoint();\n return 0; \n }\n\n Int_t i=pt\/0.1 + 1 + 1;\n return p[i]*TMath::Exp(-ct\/p[0]);\n}\n\nvoid Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {\n TH1 *eff = (TH1*)as->Clone();\n eff->Divide(as,mc,1,1,\"b\");\n rw->Divide(eff);\n delete eff;\n} \n\nvoid Normalise(Double_t br, Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {\n pt->Scale(1\/br); \/\/ branching ratio\n pt->Scale(1\/yw); \/\/ rapidity window\n pt->Scale(1\/bw); \/\/ bin width \n pt->Scale(1\/ne); \/\/ number of events\n}\n<commit_msg>Optional possibility to correct in 1D and a more stable calculation of the global FD correction<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)\n #include <TMath.h>\n #include <TROOT.h>\n #include <Riostream.h>\n #include <TCanvas.h>\n\n #include <TString.h>\n\n #include <TFile.h>\n #include <TList.h>\n #include <TH1F.h>\n #include <TH1D.h>\n #include <TF2.h>\n #include <TFitResult.h>\n #include <TFitResultPtr.h>\n #include <TH2F.h>\n #include <TH3F.h>\n#endif\n \nextern TROOT *gROOT;\n\/\/extern TFile *gFile;\n\n\nvoid PostProcessCTau(Int_t corrType=1) {\n \/\/-----------------------------------------------------------------\n \/\/ PostProcess the histograms produced by AliAnalysisTaskCTau* \n \/\/ Produce:\n \/\/ -- V0 particle spectra (not corrected for the feeddown)\n \/\/ -- Estimated (anti)Lambda feed-down spectra (from Xi's only)\n \/\/ -- V0 particle c*tau distributions (feeddown corrected) \n \/\/-----------------------------------------------------------------\n\n TString name(\"cTau_0090\"); \/\/centrality\n \/\/TString name(\"cTau_0005\"); \/\/centrality\n \/\/TString name(\"cTau_2040\"); \/\/centrality\n \/\/TString name(\"cTau_4060\"); \/\/centrality\n \/\/TString name(\"cTau_6080\"); \/\/centrality\n \/\/TString name(\"cTau_8090\"); \/\/centrality\n\n\n \/\/+++++ Real data histograms\n TFile::Open(\"new\/real\/all\/\" + name + \".root\");\n TList *list=(TList *)gFile->Get(name); \n\n TH2F *fK0sSi=(TH2F*)list->FindObject(\"fK0sSi\");fK0sSi->Sumw2();\n TH2F *fLambdaSi=(TH2F*)list->FindObject(\"fLambdaSi\");fLambdaSi->Sumw2();\n TH1F *fXiSiP=(TH1F*)list->FindObject(\"fXiSiP\"); fXiSiP->Sumw2();\n TH2F *fLambdaBarSi=\n (TH2F*)list->FindObject(\"fLambdaBarSi\"); fLambdaBarSi->Sumw2();\n TH1F *fXiBarSiP=(TH1F*)list->FindObject(\"fXiBarSiP\"); fXiBarSiP->Sumw2();\n\n TH1F *fMult=(TH1F*)list->FindObject(\"fMult\");\n \/\/+++++\n\n const Double_t nEvents=fMult->Integral();\n\n \/\/+++++ MC histograms\n TFile::Open(\"new\/mc_b_plus\/all\/\" + name + \"_mc.root\");\n TList *listmc=(TList *)gFile->Get(name+\"_mc\"); \n\n TH2F *fK0sMC=(TH2F*)listmc->FindObject(\"fK0sMC\"); fK0sMC->Sumw2();\n TH2F *fK0sAs=(TH2F*)listmc->FindObject(\"fK0sAs\"); fK0sAs->Sumw2();\n\n TH2F *fLambdaMC=(TH2F*)listmc->FindObject(\"fLambdaMC\"); fLambdaMC->Sumw2();\n TH2F *fLambdaAs=(TH2F*)listmc->FindObject(\"fLambdaAs\"); fLambdaAs->Sumw2();\n\n TH2F *fLambdaBarMC=\n (TH2F*)listmc->FindObject(\"fLambdaBarMC\"); fLambdaBarMC->Sumw2();\n TH2F *fLambdaBarAs=\n (TH2F*)listmc->FindObject(\"fLambdaBarAs\"); fLambdaBarAs->Sumw2();\n\n TH1F *fXiSiPMC=(TH1F*)listmc->FindObject(\"fXiSiP\");fXiSiPMC->Sumw2();\n TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject(\"fLambdaFromXi\");\n fLambdaFromXi->Sumw2();\n\n TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject(\"fXiBarSiP\");fXiBarSiPMC->Sumw2();\n TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject(\"fLambdaBarFromXiBar\");\n fLambdaBarFromXiBar->Sumw2();\n \/\/+++++\n\n\n Double_t myExp2(Double_t *v, Double_t *p);\n void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);\n void Normalise(Double_t, Double_t, Double_t, Double_t, TH1 *h);\n\n const Int_t iMax=3; \/\/ Number of V0 particles\n const TString pnam[]={\"K^{0}_{S}\", \"#Lambda\", \"#bar{#Lambda}\"};\n const Double_t brch[]={0.69, 0.64, 0.64};\n const Double_t mass[]={0.4977, 1.115, 1.115};\n const Double_t ctau[]={2.68, 7.89, 7.89};\n const Double_t yWin=2*0.5; \/\/ rapidity window\n const Double_t wbx=fK0sSi->GetBinWidth(3);\n const Int_t nbx=fLambdaFromXi->GetNbinsX();\n const Int_t nby=fLambdaFromXi->GetNbinsY();\n const Int_t nbz=fLambdaFromXi->GetNbinsZ();\n\n const TH2 *in[]={\n fK0sSi,fK0sAs,fK0sMC,\n fLambdaSi,fLambdaAs,fLambdaMC,\n fLambdaBarSi,fLambdaBarAs,fLambdaBarMC\n };\n TH1 *fd[]={\n 0,0,0,\n fLambdaFromXi,fXiSiP,fXiSiPMC,\n fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC\n };\n \n for (Int_t i=0; i<iMax; i++) {\n const TH2 *ptRw=in[3*i+0], *ptAs=in[3*i+1], *ptMc=in[3*i+2];\n TH1 *ptAsPx=0, *ptMcPx=0, *pt=0;\n\n TH2 *cr=(TH2*)ptRw->Clone();\n Correct(cr, ptAs, ptMc);\n\n \/\/++++ pT spectrum\n if (corrType==1) {\n pt =ptRw->ProjectionX(\"_px\",0,-1,\"e\"); \n ptAsPx=ptAs->ProjectionX(\"_px\",0,-1,\"e\"); \n ptMcPx=ptMc->ProjectionX(\"_px\",0,-1,\"e\"); \n Correct(pt, ptAsPx, ptMcPx);\n } else {\n pt=cr->ProjectionX(\"_px\",0,-1,\"e\");\n }\n TString ptName = pnam[i] + \" p_{T} spectrum\";\n pt->SetTitle(ptName.Data());\n Normalise(brch[i], yWin, wbx, nEvents, pt); \n\n new TCanvas; \n pt->Draw(); \n\n if (i>0) {\n \/\/++++ feeddown\n\t TH3 *fd3=(TH3*)fd[3*i + 0];\n\t TH1 *rl =(TH1*)fd[3*i + 1];\n\t TH1 *mc =(TH1*)fd[3*i + 2];\n\n Double_t nLambdaFromXiMc=fd3->Integral();\n Double_t nXiMc=mc->Integral();\n Double_t nXiRl=rl->Integral();\n Double_t f=(nLambdaFromXiMc*nXiRl\/nXiMc)\/ptRw->Integral();\n Double_t ef=f*TMath::Sqrt(nXiMc)\/nXiMc;\n cout<<endl<<\"Global FD correction: \"<<f<<\"+\/-\"<<ef<<endl;\n\n rl->Divide(mc);\n \n for (Int_t k=1; k<=nbx; k++) {\n for (Int_t l=1; l<=nby; l++) {\n for (Int_t m=1; m<=nbz; m++) {\n Float_t c=fd3->GetBinContent(k,l,m);\n c *= rl->GetBinContent(m);\n fd3->SetBinContent(k,l,m,c);\n\t\t }\n\t }\n\t }\n\n TH2 *fd2=(TH2*)fd3->Project3D(\"yxe\");\n Correct(fd2, ptAs, ptMc);\n\n TH1 *fd1=0;\n if (corrType==1) {\n fd1=(TH1*)fd3->Project3D(\"x\");\n Correct(fd1, ptAsPx, ptMcPx);\n } else {\n fd1=fd2->ProjectionX(\"_px\",0,-1,\"e\");\n\t }\n Normalise(brch[i], yWin, wbx, nEvents, fd1);\n\n \/\/new TCanvas();\n fd1->Draw(\"same\");\n\n cr->Add(fd2,-1);\n } \n \/\/continue;\n \n \/\/++++ c*tau\n TF2 *f2=new TF2(\"myexpo2\",myExp2,0.,10.,0.,100.,1+1+1+nbx);\n f2->SetParameter(0, ctau[i]);\n f2->FixParameter(1, ctau[i]);\n f2->FixParameter(2, mass[i]);\n for (Int_t p=1+1+1; p<=nbx+1+1; p++) \n f2->SetParameter(p,fK0sSi->GetBinContent(p,1));\n\n new TCanvas; \n TFitResultPtr r=cr->Fit(f2,\"SQ\");\n\n Int_t status = r;\n Double_t chi2 = r->Chi2()\/r->Ndf(); \n Double_t slope = r->Parameter(0); \n Double_t error = r->ParError(0); \n cout<<endl<<pnam[i]<<\" \\tstatus: \"<<status<<\" chi2\/ndf: \"<<chi2<<\n\t\"\\tc*tau: \"<<slope<<\"+\/-\"<<error<<endl<<endl;\n }\n\n return;\n} \n\nDouble_t myExp2(Double_t *v, Double_t *p) {\n Double_t pt=v[0];\n Double_t lt=v[1];\n\n Double_t ctau=p[1];\n Double_t mass=p[2];\n Double_t ct=mass*lt\/pt;\n if ((lt < 2) || (ct > 2.5*ctau)) {\n TF1::RejectPoint();\n return 0; \n }\n\n Int_t i=pt\/0.1 + 1 + 1;\n return p[i]*TMath::Exp(-ct\/p[0]);\n}\n\nvoid Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {\n TH1 *eff = (TH1*)as->Clone();\n eff->Divide(as,mc,1,1,\"b\");\n rw->Divide(eff);\n delete eff;\n} \n\nvoid Normalise(Double_t br, Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {\n pt->Scale(1\/br); \/\/ branching ratio\n pt->Scale(1\/yw); \/\/ rapidity window\n pt->Scale(1\/bw); \/\/ bin width \n pt->Scale(1\/ne); \/\/ number of events\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This software is released under the BSD License.\n |\n | Copyright (c) 2015, Kevin P. Barry [ta0kira@gmail.com]\n | All rights reserved.\n |\n | Redistribution and use in source and binary forms, with or without\n | modification, are permitted provided that the following conditions are met:\n |\n | - Redistributions of source code must retain the above copyright notice, this\n | list of conditions and the following disclaimer.\n |\n | - Redistributions in binary form must reproduce the above copyright notice,\n | this list of conditions and the following disclaimer in the documentation\n | and\/or other materials provided with the distribution.\n |\n | - Neither the name of the Locking Container Project nor the names of its\n | contributors may be used to endorse or promote products derived from this\n | software without specific prior written permission.\n |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n | POSSIBILITY OF SUCH DAMAGE.\n +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\n\n#ifndef authorization_hpp\n#define authorization_hpp\n\n#include <assert.h>\n\n\n\/*! \\class lock_auth_base\n * \\brief Base class for lock authorization classes.\n *\n * @see lock_auth\n *\/\n\nclass lock_base;\n\nclass lock_auth_base {\npublic:\n typedef long count_type;\n typedef std::shared_ptr <lock_auth_base> auth_type;\n\n virtual count_type reading_count() const { return 0; }\n virtual count_type writing_count() const { return 0; }\n\n \/*! Attempt to predict if a read authorization would be granted.*\/\n inline bool guess_read_allowed(bool lock_out = true, bool in_use = true) const {\n return this->test_auth(true, lock_out, in_use);\n }\n\n \/*! Attempt to predict if a write authorization would be granted.*\/\n inline bool guess_write_allowed(bool lock_out = true, bool in_use = true) const {\n return this->test_auth(false, lock_out, in_use);\n }\n\n virtual inline ~lock_auth_base() {}\n\nprivate:\n friend class lock_base;\n\n \/*! Obtain lock authorization.*\/\n virtual bool register_auth(bool read, bool lock_out, bool in_use) = 0;\n\n \/*! Test lock authorization.*\/\n virtual bool test_auth(bool read, bool lock_out, bool in_use) const = 0;\n\n \/*! Release lock authorization.*\/\n virtual void release_auth(bool read) = 0;\n};\n\n\n\/*! \\class lock_auth\n * \\brief Lock authorization object.\n *\n * @see locking_container::auth_type\n * @see locking_container::get_new_auth\n * @see locking_container::get_auth\n * @see locking_container::get_auth_const\n *\n * This class is used by \\ref locking_container to prevent deadlocks. To prevent\n * deadlocks, create one \\ref lock_auth instance per thread, and pass it to the\n * \\ref locking_container when getting a proxy object. This will prevent the\n * thread from obtaining an new incompatible lock type when it already holds a\n * lock.\n *\/\n\ntemplate <class> class lock_auth;\n\n\/*! \\class lock_auth <rw_lock>\n *\n * This auth. type allows the caller to hold multiple read locks, or a single\n * write lock, but not both. Note that if another thread is waiting for a write\n * lock on a w_lock or rw_lock container and the caller already has a read lock\n * then the lock will be rejected. Three exceptions to these rules are: 1) if\n * the container to be locked currently has no other locks; 2) if the call isn't\n * blocking and it's for a write lock; 3) if the container uses a rw_lock, the\n * caller has a write lock on the container, and the caller is requesting a read\n * lock. (The 3rd case is what allows multi-lock to work.)\n *\/\n\nclass rw_lock;\n\ntemplate <>\nclass lock_auth <rw_lock> : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth() : reading(0), writing(0) {}\n\n count_type reading_count() const { return reading; }\n count_type writing_count() const { return writing; }\n\n ~lock_auth() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n assert(!this->reading_count() && !this->writing_count());\n }\n\nprivate:\n lock_auth(const lock_auth&);\n lock_auth &operator = (const lock_auth&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n if (read) {\n ++reading;\n assert(reading > 0);\n } else {\n ++writing;\n assert(writing > 0);\n }\n return true;\n }\n\n bool test_auth(bool read, bool lock_out, bool in_use) const {\n if (writing && in_use) return false;\n if (reading && !read && in_use) return false;\n if ((reading || writing) && lock_out) return false;\n return true;\n }\n\n void release_auth(bool read) {\n if (read) {\n \/\/NOTE: don't check 'writing' because there are a few exceptions!\n assert(reading > 0);\n --reading;\n } else {\n \/\/NOTE: don't check 'reading' because there are a few exceptions!\n assert(writing > 0);\n --writing;\n }\n }\n\n count_type reading, writing;\n};\n\n\/*! \\class lock_auth <r_lock>\n *\n * This auth. type allows the caller to hold multiple read locks, but no write\n * locks. Note that if another thread is waiting for a write lock on the\n * container and the caller already has a read lock then the lock will be\n * rejected. Use this auth. type if you want to ensure that a thread doesn't\n * obtain a write lock on any container. Using this auth. type with containers\n * that use any combination of r_lock and rw_lock should result in the same\n * behavior as using it with only r_lock containers.\n *\/\n\nclass r_lock;\n\ntemplate <>\nclass lock_auth <r_lock> : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth() : reading(0) {}\n\n count_type reading_count() const { return reading; }\n\n ~lock_auth() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'writing_count', since it's overrides will be ignored here\n assert(!this->reading_count());\n }\n\nprivate:\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n ++reading;\n assert(reading > 0);\n return true;\n }\n\n bool test_auth(bool read, bool lock_out, bool \/*in_use*\/) const {\n if (!read) return false;\n if (reading && lock_out) return false;\n return true;\n }\n\n void release_auth(bool read) {\n assert(read);\n assert(reading > 0);\n --reading;\n }\n\n count_type reading;\n};\n\n\/*! \\class lock_auth <w_lock>\n *\n * This auth. type allows the caller to hold no more than one lock at a time,\n * regardless of lock type. An exception to this behavior is if the container to\n * be locked currently has no other locks. Use this auth. type if you are only\n * using containers that use w_lock, or if you want to disallow multiple read\n * locks on containers that use rw_lock or r_lock. Using this auth. type with\n * containers that use any combination of w_lock and rw_lock should result in\n * the same behavior as using it with only w_lock containers.\n *\/\n\nclass w_lock;\n\ntemplate <>\nclass lock_auth <w_lock> : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth() : writing(0) {}\n\n count_type writing_count() const { return writing; }\n\n ~lock_auth() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'reading_count', since it's overrides will be ignored here\n assert(!this->writing_count());\n }\n\nprivate:\n lock_auth(const lock_auth&);\n lock_auth &operator = (const lock_auth&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n ++writing;\n assert(writing > 0);\n return true;\n }\n\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool in_use) const {\n return !writing || !in_use;\n }\n\n void release_auth(bool \/*read*\/) {\n assert(writing > 0);\n --writing;\n }\n\n count_type writing;\n};\n\n\/*! \\class lock_auth <dumb_lock>\n *\n * This auth. type only allows the caller to hold one lock at a time. Unlike\n * lock_auth <w_lock>, it doesn't matter if the container is in use. (One caveat\n * to this is that r_lock doesn't actually lock; therefore, this auth. can\n * potentially hold multiple locks on r_lock containers at one time.) This is\n * useful if you want to ensure that the caller can only hold a single lock at\n * any given time. This auth. type will not work with multi-locking.\n *\/\n\nclass dumb_lock;\n\ntemplate <>\nclass lock_auth <dumb_lock> : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth() : writing(false) {}\n\n count_type writing_count() const { return writing? 1 : 0; }\n\n ~lock_auth() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'reading_count', since it's overrides will be ignored here\n assert(!this->writing_count());\n }\n\nprivate:\n lock_auth(const lock_auth&);\n lock_auth &operator = (const lock_auth&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n writing = true;\n return true;\n }\n\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) const {\n return !writing;\n }\n\n void release_auth(bool \/*read*\/) {\n assert(writing);\n writing = false;\n }\n\n bool writing;\n};\n\n\/*! \\class lock_auth <broken_lock>\n *\n * This auth. type doesn't allow the caller to obtain any locks.\n *\/\n\nstruct broken_lock;\n\ntemplate <>\nclass lock_auth <broken_lock> : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\nprivate:\n bool register_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) { return false; }\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) const { return false; }\n void release_auth(bool \/*read*\/) { assert(false); }\n};\n\n#endif \/\/authorization_hpp\n<commit_msg>revised definitions of lock_auth to allow inheritance<commit_after>\/* This software is released under the BSD License.\n |\n | Copyright (c) 2015, Kevin P. Barry [ta0kira@gmail.com]\n | All rights reserved.\n |\n | Redistribution and use in source and binary forms, with or without\n | modification, are permitted provided that the following conditions are met:\n |\n | - Redistributions of source code must retain the above copyright notice, this\n | list of conditions and the following disclaimer.\n |\n | - Redistributions in binary form must reproduce the above copyright notice,\n | this list of conditions and the following disclaimer in the documentation\n | and\/or other materials provided with the distribution.\n |\n | - Neither the name of the Locking Container Project nor the names of its\n | contributors may be used to endorse or promote products derived from this\n | software without specific prior written permission.\n |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n | POSSIBILITY OF SUCH DAMAGE.\n +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\n\n#ifndef authorization_hpp\n#define authorization_hpp\n\n#include <assert.h>\n\n\n\/*! \\class lock_auth_base\n * \\brief Base class for lock authorization classes.\n *\n * @see lock_auth\n *\/\n\nclass lock_base;\n\nclass lock_auth_base {\npublic:\n typedef long count_type;\n typedef std::shared_ptr <lock_auth_base> auth_type;\n\n virtual count_type reading_count() const { return 0; }\n virtual count_type writing_count() const { return 0; }\n\n \/*! Attempt to predict if a read authorization would be granted.*\/\n inline bool guess_read_allowed(bool lock_out = true, bool in_use = true) const {\n return this->test_auth(true, lock_out, in_use);\n }\n\n \/*! Attempt to predict if a write authorization would be granted.*\/\n inline bool guess_write_allowed(bool lock_out = true, bool in_use = true) const {\n return this->test_auth(false, lock_out, in_use);\n }\n\n virtual inline ~lock_auth_base() {}\n\nprivate:\n friend class lock_base;\n\n \/*! Obtain lock authorization.*\/\n virtual bool register_auth(bool read, bool lock_out, bool in_use) = 0;\n\n \/*! Test lock authorization.*\/\n virtual bool test_auth(bool read, bool lock_out, bool in_use) const = 0;\n\n \/*! Release lock authorization.*\/\n virtual void release_auth(bool read) = 0;\n};\n\n\n\/*! \\class lock_auth\n * \\brief Lock authorization object.\n *\n * @see locking_container::auth_type\n * @see locking_container::get_new_auth\n * @see locking_container::get_auth\n * @see locking_container::get_auth_const\n *\n * This class is used by \\ref locking_container to prevent deadlocks. To prevent\n * deadlocks, create one \\ref lock_auth instance per thread, and pass it to the\n * \\ref locking_container when getting a proxy object. This will prevent the\n * thread from obtaining an new incompatible lock type when it already holds a\n * lock.\n *\/\n\ntemplate <class> class lock_auth;\n\n\n\/*! \\class lock_auth_rw_lock\n *\n * This auth. type allows the caller to hold multiple read locks, or a single\n * write lock, but not both. Note that if another thread is waiting for a write\n * lock on a w_lock or rw_lock container and the caller already has a read lock\n * then the lock will be rejected. Three exceptions to these rules are: 1) if\n * the container to be locked currently has no other locks; 2) if the call isn't\n * blocking and it's for a write lock; 3) if the container uses a rw_lock, the\n * caller has a write lock on the container, and the caller is requesting a read\n * lock. (The 3rd case is what allows multi-lock to work.)\n *\/\n\nclass lock_auth_rw_lock : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth_rw_lock() : reading(0), writing(0) {}\n\n count_type reading_count() const { return reading; }\n count_type writing_count() const { return writing; }\n\n ~lock_auth_rw_lock() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n assert(!this->reading_count() && !this->writing_count());\n }\n\nprivate:\n lock_auth_rw_lock(const lock_auth_rw_lock&);\n lock_auth_rw_lock &operator = (const lock_auth_rw_lock&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n if (read) {\n ++reading;\n assert(reading > 0);\n } else {\n ++writing;\n assert(writing > 0);\n }\n return true;\n }\n\n bool test_auth(bool read, bool lock_out, bool in_use) const {\n if (writing && in_use) return false;\n if (reading && !read && in_use) return false;\n if ((reading || writing) && lock_out) return false;\n return true;\n }\n\n void release_auth(bool read) {\n if (read) {\n \/\/NOTE: don't check 'writing' because there are a few exceptions!\n assert(reading > 0);\n --reading;\n } else {\n \/\/NOTE: don't check 'reading' because there are a few exceptions!\n assert(writing > 0);\n --writing;\n }\n }\n\n count_type reading, writing;\n};\n\nclass rw_lock;\n\ntemplate <>\nclass lock_auth <rw_lock> : public lock_auth_rw_lock {};\n\n\n\/*! \\class lock_auth_r_lock\n *\n * This auth. type allows the caller to hold multiple read locks, but no write\n * locks. Note that if another thread is waiting for a write lock on the\n * container and the caller already has a read lock then the lock will be\n * rejected. Use this auth. type if you want to ensure that a thread doesn't\n * obtain a write lock on any container. Using this auth. type with containers\n * that use any combination of r_lock and rw_lock should result in the same\n * behavior as using it with only r_lock containers.\n *\/\n\nclass lock_auth_r_lock : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth_r_lock() : reading(0) {}\n\n count_type reading_count() const { return reading; }\n\n ~lock_auth_r_lock() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'writing_count', since it's overrides will be ignored here\n assert(!this->reading_count());\n }\n\nprivate:\n lock_auth_r_lock(const lock_auth_r_lock&);\n lock_auth_r_lock &operator = (const lock_auth_r_lock&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n ++reading;\n assert(reading > 0);\n return true;\n }\n\n bool test_auth(bool read, bool lock_out, bool \/*in_use*\/) const {\n if (!read) return false;\n if (reading && lock_out) return false;\n return true;\n }\n\n void release_auth(bool read) {\n assert(read);\n assert(reading > 0);\n --reading;\n }\n\n count_type reading;\n};\n\nclass r_lock;\n\ntemplate <>\nclass lock_auth <r_lock> : public lock_auth_r_lock {};\n\n\n\/*! \\class lock_auth_w_lock\n *\n * This auth. type allows the caller to hold no more than one lock at a time,\n * regardless of lock type. An exception to this behavior is if the container to\n * be locked currently has no other locks. Use this auth. type if you are only\n * using containers that use w_lock, or if you want to disallow multiple read\n * locks on containers that use rw_lock or r_lock. Using this auth. type with\n * containers that use any combination of w_lock and rw_lock should result in\n * the same behavior as using it with only w_lock containers.\n *\/\n\nclass lock_auth_w_lock : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth_w_lock() : writing(0) {}\n\n count_type writing_count() const { return writing; }\n\n ~lock_auth_w_lock() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'reading_count', since it's overrides will be ignored here\n assert(!this->writing_count());\n }\n\nprivate:\n lock_auth_w_lock(const lock_auth_w_lock&);\n lock_auth_w_lock &operator = (const lock_auth_w_lock&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n ++writing;\n assert(writing > 0);\n return true;\n }\n\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool in_use) const {\n return !writing || !in_use;\n }\n\n void release_auth(bool \/*read*\/) {\n assert(writing > 0);\n --writing;\n }\n\n count_type writing;\n};\n\nclass w_lock;\n\ntemplate <>\nclass lock_auth <w_lock> : public lock_auth_w_lock {};\n\n\n\/*! \\class lock_auth_dumb_lock\n *\n * This auth. type only allows the caller to hold one lock at a time. Unlike\n * lock_auth_w_lock, it doesn't matter if the container is in use. (One caveat\n * to this is that r_lock doesn't actually lock; therefore, this auth. can\n * potentially hold multiple locks on r_lock containers at one time.) This is\n * useful if you want to ensure that the caller can only hold a single lock at\n * any given time. This auth. type will not work with multi-locking.\n *\/\n\nclass lock_auth_dumb_lock : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\n lock_auth_dumb_lock() : writing(false) {}\n\n count_type writing_count() const { return writing? 1 : 0; }\n\n ~lock_auth_dumb_lock() {\n \/\/NOTE: this can't be in '~lock_auth_base'!\n \/\/NOTE: no point checking 'reading_count', since it's overrides will be ignored here\n assert(!this->writing_count());\n }\n\nprivate:\n lock_auth_dumb_lock(const lock_auth_dumb_lock&);\n lock_auth_dumb_lock &operator = (const lock_auth_dumb_lock&);\n\n bool register_auth(bool read, bool lock_out, bool in_use) {\n if (!this->test_auth(read, lock_out, in_use)) return false;\n writing = true;\n return true;\n }\n\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) const {\n return !writing;\n }\n\n void release_auth(bool \/*read*\/) {\n assert(writing);\n writing = false;\n }\n\n bool writing;\n};\n\nclass dumb_lock;\n\ntemplate <>\nclass lock_auth <dumb_lock> : public lock_auth_dumb_lock {};\n\n\n\/*! \\class lock_auth_broken_lock\n *\n * This auth. type doesn't allow the caller to obtain any locks.\n *\/\n\nclass lock_auth_broken_lock : public lock_auth_base {\npublic:\n using lock_auth_base::count_type;\n\nprivate:\n bool register_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) { return false; }\n bool test_auth(bool \/*read*\/, bool \/*lock_out*\/, bool \/*in_use*\/) const { return false; }\n void release_auth(bool \/*read*\/) { assert(false); }\n};\n\nstruct broken_lock;\n\ntemplate <>\nclass lock_auth <broken_lock> : public lock_auth_broken_lock {};\n\n#endif \/\/authorization_hpp\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"loginform.h\"\n#include \"ui_loginform.h\"\n\n#include <QtCore\/QDebug>\n#include <QtGui\/QCompleter>\n#include <QtCore\/QAbstractListModel>\n#include <QtCore\/QModelIndex>\n#include <QtCore\/QFile>\n#include <QtCore\/QTextStream>\n#include <QtCore\/QStringList>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QMenu>\n#include <QtCore\/QProcess>\n#include <lxqt\/lxqtsettings.h>\n\nLoginForm::LoginForm(QWidget *parent) : \n QWidget(parent), \n ui(new Ui::LoginForm), \n m_Greeter(),\n m_LoginData(&m_Greeter),\n m_powerManager(this, true),\n m_otherUserComboIndex(-1)\n{\n if (!m_Greeter.connectSync())\n {\n close();\n }\n\n ui->setupUi(this);\n\n setupAppearence(); \n fillUserAndSessionCombos();\n setupConnections();\n initializeControls();\n ui->formFrame->adjustSize();\n adjustSize(); \n}\n\nLoginForm::~LoginForm()\n{\n delete ui;\n}\n\nvoid LoginForm::setFocus(Qt::FocusReason reason)\n{\n if (ui->userCombo->currentIndex() == -1)\n {\n ui->userCombo->setFocus(reason);\n }\n else if (ui->userCombo->currentIndex() == m_otherUserComboIndex)\n {\n ui->otherUserInput->setFocus(reason);\n }\n else \n {\n ui->passwordInput->setFocus(reason);\n }\n}\n\nvoid LoginForm::setupAppearence()\n{\n QPixmap icon(\":\/resources\/helix_1120.png\");\n ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n ui->hostnameLabel->setText(m_Greeter.hostname());\n}\n\nvoid LoginForm::fillUserAndSessionCombos()\n{\n ui->userCombo->clear(); \n for (int i = 0; i < m_LoginData.numberOfUsers(); i++)\n {\n qDebug() << \"Adding user\" << m_LoginData.userFullName(i);\n ui->userCombo->addItem(m_LoginData.userFullName(i));\n }\n ui->userCombo->addItem(tr(\"other...\"));\n m_otherUserComboIndex = ui->userCombo->count() - 1;\n\n ui->sessionCombo->clear();\n for (int i = 0; i < m_LoginData.numberOfSessions(); i++)\n {\n qDebug() << \"Adding session\" << m_LoginData.sessionFullName(i);\n ui->sessionCombo->addItem(m_LoginData.sessionFullName(i));\n }\n}\n\nvoid LoginForm::setupConnections()\n{\n ui->userCombo->setCurrentIndex(-1);\n connect(ui->userCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(userComboCurrentIndexChanged()));\n connect(ui->otherUserInput, SIGNAL(editingFinished()), this, SLOT(otherUserEditingFinished()));\n connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(loginClicked()));\n connect(ui->leaveButton, SIGNAL(clicked()), this, SLOT(leaveClicked()));\n\n\n connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::Greeter::PromptType)),\n this, SLOT(onPrompt(QString,QLightDM::Greeter::PromptType)));\n\n connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationComplete()));\n}\n\nvoid LoginForm::initializeControls()\n{\n QMenu* leaveMenu = new QMenu(this);\n ui->leaveButton->setMenu(leaveMenu);\n \n foreach (QAction *action, m_powerManager.availableActions())\n {\n leaveMenu->addAction(action);\n }\n\n qDebug() << \"showManualLoginHint:\" << m_Greeter.showManualLoginHint();\n\n ui->sessionCombo->setCurrentIndex(m_LoginData.suggestedSession());\n\n if (m_Greeter.showManualLoginHint()) \n {\n ui->userCombo->setCurrentIndex(m_otherUserComboIndex);\n }\n else \n {\n ui->userCombo->setCurrentIndex(m_LoginData.suggestedUser());\n }\n\n ui->userCombo->setVisible(! m_Greeter.hideUsersHint());\n\n ui->otherUserInput->setVisible(ui->userCombo->currentIndex() == m_otherUserComboIndex);\n ui->otherUserInput->clear(); \n QStringList completions;\n for (int i = 0; i < m_LoginData.numberOfUsers(); i++) \n {\n completions << m_LoginData.userName(i);\n }\n QCompleter *completer = new QCompleter(completions, ui->otherUserInput);\n completer->setCompletionMode(QCompleter::InlineCompletion);\n ui->otherUserInput->setCompleter(completer);\n\n ui->passwordInput->setEnabled(false);\n ui->passwordInput->clear();\n}\n\nvoid LoginForm::setSessionCombo(int session_index)\n{\n if (0 <= session_index && session_index < ui->sessionCombo->count())\n {\n ui->sessionCombo->setCurrentIndex(session_index);\n }\n}\n\nvoid LoginForm::userComboCurrentIndexChanged()\n{\n\n qDebug() << \"userComboCurrentIndexChanged:\" << ui->userCombo->currentIndex();\n qDebug() << \"setVisible...\";\n if (ui->userCombo->currentIndex() == m_otherUserComboIndex)\n {\n ui->otherUserInput->show();\n ui->otherUserInput->setFocus();\n }\n else\n {\n ui->otherUserInput->hide();\n qDebug() << \"Start authentication..\";\n if (ui->userCombo->currentIndex() > -1)\n {\n setUser(m_LoginData.userName(ui->userCombo->currentIndex()));\n }\n }\n ui->formFrame->adjustSize();\n adjustSize();\n}\n\nvoid LoginForm::otherUserEditingFinished()\n{\n if (ui->otherUserInput->text().isNull() || ui->otherUserInput->text().isEmpty())\n {\n return;\n }\n\n qDebug() << \"Authenticating with otherUser...\";\n\n setUser(ui->otherUserInput->text()) ;\n}\n\nvoid LoginForm::loginClicked()\n{\n qDebug() << \"loginClicked\";\n m_Greeter.respond(ui->passwordInput->text().trimmed());\n ui->passwordInput->clear();\n ui->passwordInput->setEnabled(false);\n}\n\nvoid LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType)\n{\n qDebug() << \"onPrompt\";\n ui->passwordInput->setEnabled(true);\n ui->passwordInput->setFocus();\n}\n\nvoid LoginForm::setUser(QString user)\n{\n m_user = user;\n setSessionCombo(m_LoginData.userSession(m_user));\n\n if (m_Greeter.inAuthentication()) \n {\n m_Greeter.cancelAuthentication();\n }\n m_Greeter.authenticate(m_user);\n}\n\nvoid LoginForm::authenticationComplete()\n{\n if (m_Greeter.isAuthenticated())\n {\n qDebug() << \"Authenticated... starting session\" << m_LoginData.sessionName(ui->sessionCombo->currentIndex());\n m_LoginData.setLastUser(m_user);\n m_Greeter.startSessionSync(m_LoginData.sessionName(ui->sessionCombo->currentIndex()));\n initializeControls(); \/\/ We should not arrive here...\n }\n else \n {\n qDebug() << \"Not authenticated\";\n ui->passwordInput->clear();\n setUser(m_user);\n }\n}\n\n<commit_msg>Remove connect to non-existing slot in loginform.cpp<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"loginform.h\"\n#include \"ui_loginform.h\"\n\n#include <QtCore\/QDebug>\n#include <QtGui\/QCompleter>\n#include <QtCore\/QAbstractListModel>\n#include <QtCore\/QModelIndex>\n#include <QtCore\/QFile>\n#include <QtCore\/QTextStream>\n#include <QtCore\/QStringList>\n#include <QtGui\/QPixmap>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QMenu>\n#include <QtCore\/QProcess>\n#include <lxqt\/lxqtsettings.h>\n\nLoginForm::LoginForm(QWidget *parent) : \n QWidget(parent), \n ui(new Ui::LoginForm), \n m_Greeter(),\n m_LoginData(&m_Greeter),\n m_powerManager(this, true),\n m_otherUserComboIndex(-1)\n{\n if (!m_Greeter.connectSync())\n {\n close();\n }\n\n ui->setupUi(this);\n\n setupAppearence(); \n fillUserAndSessionCombos();\n setupConnections();\n initializeControls();\n ui->formFrame->adjustSize();\n adjustSize(); \n}\n\nLoginForm::~LoginForm()\n{\n delete ui;\n}\n\nvoid LoginForm::setFocus(Qt::FocusReason reason)\n{\n if (ui->userCombo->currentIndex() == -1)\n {\n ui->userCombo->setFocus(reason);\n }\n else if (ui->userCombo->currentIndex() == m_otherUserComboIndex)\n {\n ui->otherUserInput->setFocus(reason);\n }\n else \n {\n ui->passwordInput->setFocus(reason);\n }\n}\n\nvoid LoginForm::setupAppearence()\n{\n QPixmap icon(\":\/resources\/helix_1120.png\");\n ui->iconLabel->setPixmap(icon.scaled(ui->iconLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n ui->hostnameLabel->setText(m_Greeter.hostname());\n}\n\nvoid LoginForm::fillUserAndSessionCombos()\n{\n ui->userCombo->clear(); \n for (int i = 0; i < m_LoginData.numberOfUsers(); i++)\n {\n qDebug() << \"Adding user\" << m_LoginData.userFullName(i);\n ui->userCombo->addItem(m_LoginData.userFullName(i));\n }\n ui->userCombo->addItem(tr(\"other...\"));\n m_otherUserComboIndex = ui->userCombo->count() - 1;\n\n ui->sessionCombo->clear();\n for (int i = 0; i < m_LoginData.numberOfSessions(); i++)\n {\n qDebug() << \"Adding session\" << m_LoginData.sessionFullName(i);\n ui->sessionCombo->addItem(m_LoginData.sessionFullName(i));\n }\n}\n\nvoid LoginForm::setupConnections()\n{\n ui->userCombo->setCurrentIndex(-1);\n connect(ui->userCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(userComboCurrentIndexChanged()));\n connect(ui->otherUserInput, SIGNAL(editingFinished()), this, SLOT(otherUserEditingFinished()));\n connect(ui->loginButton, SIGNAL(clicked(bool)), this, SLOT(loginClicked()));\n\n connect(&m_Greeter, SIGNAL(showPrompt(QString,QLightDM::Greeter::PromptType)),\n this, SLOT(onPrompt(QString,QLightDM::Greeter::PromptType)));\n\n connect(&m_Greeter, SIGNAL(authenticationComplete()), this, SLOT(authenticationComplete()));\n}\n\nvoid LoginForm::initializeControls()\n{\n QMenu* leaveMenu = new QMenu(this);\n ui->leaveButton->setMenu(leaveMenu);\n \n foreach (QAction *action, m_powerManager.availableActions())\n {\n leaveMenu->addAction(action);\n }\n\n qDebug() << \"showManualLoginHint:\" << m_Greeter.showManualLoginHint();\n\n ui->sessionCombo->setCurrentIndex(m_LoginData.suggestedSession());\n\n if (m_Greeter.showManualLoginHint()) \n {\n ui->userCombo->setCurrentIndex(m_otherUserComboIndex);\n }\n else \n {\n ui->userCombo->setCurrentIndex(m_LoginData.suggestedUser());\n }\n\n ui->userCombo->setVisible(! m_Greeter.hideUsersHint());\n\n ui->otherUserInput->setVisible(ui->userCombo->currentIndex() == m_otherUserComboIndex);\n ui->otherUserInput->clear(); \n QStringList completions;\n for (int i = 0; i < m_LoginData.numberOfUsers(); i++) \n {\n completions << m_LoginData.userName(i);\n }\n QCompleter *completer = new QCompleter(completions, ui->otherUserInput);\n completer->setCompletionMode(QCompleter::InlineCompletion);\n ui->otherUserInput->setCompleter(completer);\n\n ui->passwordInput->setEnabled(false);\n ui->passwordInput->clear();\n}\n\nvoid LoginForm::setSessionCombo(int session_index)\n{\n if (0 <= session_index && session_index < ui->sessionCombo->count())\n {\n ui->sessionCombo->setCurrentIndex(session_index);\n }\n}\n\nvoid LoginForm::userComboCurrentIndexChanged()\n{\n\n qDebug() << \"userComboCurrentIndexChanged:\" << ui->userCombo->currentIndex();\n qDebug() << \"setVisible...\";\n if (ui->userCombo->currentIndex() == m_otherUserComboIndex)\n {\n ui->otherUserInput->show();\n ui->otherUserInput->setFocus();\n }\n else\n {\n ui->otherUserInput->hide();\n qDebug() << \"Start authentication..\";\n if (ui->userCombo->currentIndex() > -1)\n {\n setUser(m_LoginData.userName(ui->userCombo->currentIndex()));\n }\n }\n ui->formFrame->adjustSize();\n adjustSize();\n}\n\nvoid LoginForm::otherUserEditingFinished()\n{\n if (ui->otherUserInput->text().isNull() || ui->otherUserInput->text().isEmpty())\n {\n return;\n }\n\n qDebug() << \"Authenticating with otherUser...\";\n\n setUser(ui->otherUserInput->text()) ;\n}\n\nvoid LoginForm::loginClicked()\n{\n qDebug() << \"loginClicked\";\n m_Greeter.respond(ui->passwordInput->text().trimmed());\n ui->passwordInput->clear();\n ui->passwordInput->setEnabled(false);\n}\n\nvoid LoginForm::onPrompt(QString prompt, QLightDM::Greeter::PromptType promptType)\n{\n qDebug() << \"onPrompt\";\n ui->passwordInput->setEnabled(true);\n ui->passwordInput->setFocus();\n}\n\nvoid LoginForm::setUser(QString user)\n{\n m_user = user;\n setSessionCombo(m_LoginData.userSession(m_user));\n\n if (m_Greeter.inAuthentication()) \n {\n m_Greeter.cancelAuthentication();\n }\n m_Greeter.authenticate(m_user);\n}\n\nvoid LoginForm::authenticationComplete()\n{\n if (m_Greeter.isAuthenticated())\n {\n qDebug() << \"Authenticated... starting session\" << m_LoginData.sessionName(ui->sessionCombo->currentIndex());\n m_LoginData.setLastUser(m_user);\n m_Greeter.startSessionSync(m_LoginData.sessionName(ui->sessionCombo->currentIndex()));\n initializeControls(); \/\/ We should not arrive here...\n }\n else \n {\n qDebug() << \"Not authenticated\";\n ui->passwordInput->clear();\n setUser(m_user);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"localsocket.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include \"sys\/uio.h\"\n#include <sys\/un.h>\n#include <unistd.h>\n\n#include <cassert>\n#include <climits>\n#include <cstdlib>\n#include <cstring>\n\n\/\/ HACK, put this somewhere else (get the value from original d-bus? or is it infinite?)\nstatic const int maxFds = 12;\n\nusing namespace std;\n\nLocalSocket::LocalSocket(int fd)\n : m_fd(fd)\n{}\n\nLocalSocket::LocalSocket(const string &socketFilePath)\n : m_fd(-1)\n{\n const int fd = socket(PF_UNIX, SOCK_STREAM, 0);\n if (fd < 0) {\n return;\n }\n \/\/ don't let forks inherit the file descriptor - that can cause confusion...\n fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n struct sockaddr_un addr;\n addr.sun_family = PF_UNIX;\n bool ok = socketFilePath.length() < sizeof(addr.sun_path);\n if (ok) {\n memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length());\n }\n\n ok = ok && (connect(fd, (struct sockaddr *)&addr, sizeof(sa_family_t) + socketFilePath.length()) == 0);\n\n if (ok) {\n m_fd = fd;\n } else {\n ::close(fd);\n }\n}\n\nLocalSocket::~LocalSocket()\n{\n close();\n}\n\nvoid LocalSocket::close()\n{\n setEventDispatcher(0);\n if (m_fd >= 0) {\n ::close(m_fd);\n }\n m_fd = -1;\n}\n\nint LocalSocket::write(array a)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n \/\/ sendmsg boilerplate\n struct msghdr send_msg; \/\/ C convention makes them stand out (too many similar variables...)\n struct iovec iov;\n\n send_msg.msg_name = 0;\n send_msg.msg_namelen = 0;\n send_msg.msg_flags = 0;\n send_msg.msg_iov = &iov;\n send_msg.msg_iovlen = 1;\n\n iov.iov_base = a.begin;\n iov.iov_len = a.length;\n\n \/\/ we can only send a fixed number of fds anyway due to the non-flexible size of the control message\n \/\/ receive buffer, so we set an arbitrary limit.\n const int numFds = 0; \/\/ TODO - how many should we get? do we need to know?\n assert(numFds <= maxFds);\n\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n\n if (numFds) {\n \/\/ fill in a control message\n send_msg.msg_control = cmsgBuf;\n send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds);\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg);\n c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds);\n c_msg->cmsg_level = SOL_SOCKET;\n c_msg->cmsg_type = SCM_RIGHTS;\n\n \/\/ set the control data to pass - this is why we don't use the simpler write()\n for (int i = 0; i < numFds; i++) {\n \/\/ TODO\n \/\/ reinterpret_cast<int *>(CMSG_DATA(c_msg))[i] = message.m_fileDescriptors[i];\n }\n } else {\n \/\/ no file descriptor to send, no control message\n send_msg.msg_control = 0;\n send_msg.msg_controllen = 0;\n }\n\n while (iov.iov_len > 0) {\n int nbytes = sendmsg(m_fd, &send_msg, 0);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n } else {\n close();\n return false;\n }\n }\n\n iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes;\n iov.iov_len -= nbytes;\n \/\/ sendmsg() should always send the number of bytes asked for or block, so...\n if (nbytes != 0) {\n assert(iov.iov_len == 0);\n }\n }\n\n return a.length - iov.iov_len; \/\/ \"- iov.iov_len\" is for later, TODO revisit\n}\n\nint LocalSocket::availableBytesForReading()\n{\n int available = 0;\n if (ioctl(m_fd, FIONREAD, &available) < 0) {\n available = 0;\n }\n return available;\n}\n\narray LocalSocket::read(byte *buffer, int maxSize)\n{\n array ret;\n if (maxSize <= 0) {\n return ret;\n }\n\n \/\/ recvmsg-with-control-message boilerplate\n struct msghdr recv_msg;\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n memset(cmsgBuf, 0, sizeof(cmsgBuf));\n\n recv_msg.msg_control = cmsgBuf;\n recv_msg.msg_controllen = sizeof(cmsgBuf);\n recv_msg.msg_name = 0;\n recv_msg.msg_namelen = 0;\n recv_msg.msg_flags = 0;\n\n struct iovec iov;\n recv_msg.msg_iov = &iov;\n recv_msg.msg_iovlen = 1;\n\n \/\/ end boilerplate\n\n ret.begin = buffer;\n ret.length = 0;\n iov.iov_base = ret.begin;\n iov.iov_len = maxSize;\n while (iov.iov_len > 0) {\n int nbytes = recvmsg(m_fd, &recv_msg, 0);\n if (nbytes < 0 && errno != EINTR) {\n close();\n return ret;\n }\n ret.length += nbytes;\n iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes;\n iov.iov_len -= nbytes;\n }\n\n \/\/ done reading \"regular data\", now read any file descriptors passed via control messages\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg);\n if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) {\n const int len = c_msg->cmsg_len \/ sizeof(int);\n int *data = reinterpret_cast<int *>(CMSG_DATA(c_msg));\n for (int i = 0; i < len; i++) {\n \/\/ TODO\n \/\/ message.appendFileDescriptor(data[i]);\n }\n }\n\n return ret;\n}\n\nbool LocalSocket::isOpen()\n{\n return m_fd != -1;\n}\n\nint LocalSocket::fileDescriptor() const\n{\n return m_fd;\n}\n\nvoid LocalSocket::notifyRead()\n{\n if (availableBytesForReading()) {\n IConnection::notifyRead();\n } else {\n \/\/ This should really only happen in error cases! ### TODO test?\n close();\n }\n}\n<commit_msg>Non-blocking reading and writing in LocalSocket.<commit_after>#include \"localsocket.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include \"sys\/uio.h\"\n#include <sys\/un.h>\n#include <unistd.h>\n\n#include <cassert>\n#include <climits>\n#include <cstdlib>\n#include <cstring>\n\n\/\/ HACK, put this somewhere else (get the value from original d-bus? or is it infinite?)\nstatic const int maxFds = 12;\n\nusing namespace std;\n\nLocalSocket::LocalSocket(int fd)\n : m_fd(fd)\n{}\n\nLocalSocket::LocalSocket(const string &socketFilePath)\n : m_fd(-1)\n{\n const int fd = socket(PF_UNIX, SOCK_STREAM, 0);\n if (fd < 0) {\n return;\n }\n \/\/ don't let forks inherit the file descriptor - that can cause confusion...\n fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n struct sockaddr_un addr;\n addr.sun_family = PF_UNIX;\n bool ok = socketFilePath.length() < sizeof(addr.sun_path);\n if (ok) {\n memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length());\n }\n\n ok = ok && (connect(fd, (struct sockaddr *)&addr, sizeof(sa_family_t) + socketFilePath.length()) == 0);\n\n if (ok) {\n m_fd = fd;\n } else {\n ::close(fd);\n }\n}\n\nLocalSocket::~LocalSocket()\n{\n close();\n}\n\nvoid LocalSocket::close()\n{\n setEventDispatcher(0);\n if (m_fd >= 0) {\n ::close(m_fd);\n }\n m_fd = -1;\n}\n\nint LocalSocket::write(array a)\n{\n if (m_fd < 0) {\n return 0; \/\/ TODO -1?\n }\n\n \/\/ sendmsg boilerplate\n struct msghdr send_msg;\n struct iovec iov;\n\n send_msg.msg_name = 0;\n send_msg.msg_namelen = 0;\n send_msg.msg_flags = 0;\n send_msg.msg_iov = &iov;\n send_msg.msg_iovlen = 1;\n\n iov.iov_base = a.begin;\n iov.iov_len = a.length;\n\n \/\/ we can only send a fixed number of fds anyway due to the non-flexible size of the control message\n \/\/ receive buffer, so we set an arbitrary limit.\n const int numFds = 0; \/\/ TODO - how many should we get? do we need to know?\n assert(numFds <= maxFds);\n\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n\n if (numFds) {\n \/\/ fill in a control message\n send_msg.msg_control = cmsgBuf;\n send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds);\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg);\n c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds);\n c_msg->cmsg_level = SOL_SOCKET;\n c_msg->cmsg_type = SCM_RIGHTS;\n\n \/\/ set the control data to pass - this is why we don't use the simpler write()\n for (int i = 0; i < numFds; i++) {\n \/\/ TODO\n \/\/ reinterpret_cast<int *>(CMSG_DATA(c_msg))[i] = message.m_fileDescriptors[i];\n }\n } else {\n \/\/ no file descriptor to send, no control message\n send_msg.msg_control = 0;\n send_msg.msg_controllen = 0;\n }\n\n while (iov.iov_len > 0) {\n int nbytes = sendmsg(m_fd, &send_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ if we were notified for writing, we must have written at least one byte before getting\n \/\/ EAGAIN aka EWOULDBLOCK\n if (errno == EAGAIN && iov.iov_len < a.length) {\n break;\n }\n close();\n return false;\n }\n\n iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes;\n iov.iov_len -= nbytes;\n \/\/ sendmsg() should always send the number of bytes asked for or block, so...\n if (nbytes != 0) {\n assert(iov.iov_len == 0);\n }\n }\n\n return a.length - iov.iov_len; \/\/ \"- iov.iov_len\" is for later, TODO revisit\n}\n\nint LocalSocket::availableBytesForReading()\n{\n int available = 0;\n if (ioctl(m_fd, FIONREAD, &available) < 0) {\n available = 0;\n }\n return available;\n}\n\narray LocalSocket::read(byte *buffer, int maxSize)\n{\n array ret;\n if (maxSize <= 0) {\n return ret;\n }\n\n \/\/ recvmsg-with-control-message boilerplate\n struct msghdr recv_msg;\n char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)];\n memset(cmsgBuf, 0, sizeof(cmsgBuf));\n\n recv_msg.msg_control = cmsgBuf;\n recv_msg.msg_controllen = sizeof(cmsgBuf);\n recv_msg.msg_name = 0;\n recv_msg.msg_namelen = 0;\n recv_msg.msg_flags = 0;\n\n struct iovec iov;\n recv_msg.msg_iov = &iov;\n recv_msg.msg_iovlen = 1;\n\n \/\/ end boilerplate\n\n ret.begin = buffer;\n ret.length = 0;\n iov.iov_base = ret.begin;\n iov.iov_len = maxSize;\n while (iov.iov_len > 0) {\n int nbytes = recvmsg(m_fd, &recv_msg, MSG_DONTWAIT);\n if (nbytes < 0) {\n if (errno == EINTR) {\n continue;\n }\n \/\/ if we were notified for reading, we must have read at least one byte before getting\n \/\/ EAGAIN aka EWOULDBLOCK\n if (errno == EAGAIN && iov.iov_len < maxSize) {\n break;\n }\n close();\n return ret;\n }\n ret.length += nbytes;\n iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes;\n iov.iov_len -= nbytes;\n }\n\n \/\/ done reading \"regular data\", now read any file descriptors passed via control messages\n\n struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg);\n if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) {\n const int len = c_msg->cmsg_len \/ sizeof(int);\n int *data = reinterpret_cast<int *>(CMSG_DATA(c_msg));\n for (int i = 0; i < len; i++) {\n \/\/ TODO\n \/\/ message.appendFileDescriptor(data[i]);\n }\n }\n\n return ret;\n}\n\nbool LocalSocket::isOpen()\n{\n return m_fd != -1;\n}\n\nint LocalSocket::fileDescriptor() const\n{\n return m_fd;\n}\n\nvoid LocalSocket::notifyRead()\n{\n if (availableBytesForReading()) {\n IConnection::notifyRead();\n } else {\n \/\/ This should really only happen in error cases! ### TODO test?\n close();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vpr\/vprConfig.h>\n\n#include <cppunit\/TestSuite.h>\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/MetricRegistry.h>\n\n\/\/ Common (sim and real) tests.\n#include <TestCases\/Socket\/SocketTest.h>\n#include <TestCases\/Socket\/NonBlockingSocketsTest.h>\n#include <TestCases\/Socket\/SocketCopyConstructorTest.h>\n#include <TestCases\/Socket\/SocketConnectorAcceptorTest.h>\n\n#include <TestCases\/Thread\/ThreadTest.h>\n\n#include <TestCases\/IO\/Socket\/InetAddrTest.h>\n#include <TestCases\/IO\/SelectorTest.h>\n\n#include <TestCases\/IO\/Stats\/SocketBandwidthIOStatsTest.h>\n\n#include <TestCases\/Util\/ReturnStatusTest.h>\n#include <TestCases\/Util\/IntervalTest.h>\n#include <TestCases\/Util\/GUIDTest.h>\n\n\/\/ Simulator tests.\n#ifdef VPR_SIMULATOR\n# include <TestCases\/Simulator\/SimSelectorTest.h>\n# include <TestCases\/Simulator\/SocketSimulatorTest.h>\n\n\/\/ Real tests.\n#else\n#endif\n\n#include <TestCases\/BoostTest.h>\n#include <TestCases\/SystemTest.h>\n\n#include <vpr\/Thread\/Thread.h>\n#include <vpr\/Util\/Debug.h>\n#include <vpr\/System.h>\n\n\/\/#define vprtest_RANDOM_SEED 1\n\n#ifdef VPR_SIMULATOR\nstatic void run (void* arg)\n{\n while ( true )\n {\n vpr::sim::Controller::instance()->processNextEvent();\n vpr::Thread::yield();\n }\n}\n#endif\n\nint main (int ac, char **av)\n{\n vprDEBUG(vprDBG_ALL,0) << \"\\n\\n-----------------------------------------\\n\" << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,0) << \"Starting test\\n\" << vprDEBUG_FLUSH; \/\/ Do this here to get init text out of the way\n\n \/\/ Init random number generation\n unsigned int random_seed;\n\n#ifdef vprtest_RANDOM_SEED\n timeval cur_time;\n vpr::System::gettimeofday(&cur_time);\n random_seed = cur_time.tv_usec;\n vprDEBUG(vprDBG_ALL,0) << \"timeval.usec: \" << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;\n#else\n random_seed = 1; \/\/ Use this for repeatability\n#endif\n\n vprDEBUG(vprDBG_ALL,0) << \" Random seed: \" << random_seed << std::endl\n << vprDEBUG_FLUSH;\n\n srandom(random_seed);\n srand(random_seed);\n\n#ifdef VPR_SIMULATOR \/\/ ------ CONFIGURE SIM NETWORK ------ \/\/\n std::string path_base(GRAPH_PATH);\n\n vpr::sim::Controller::instance()->constructNetwork(path_base.append(\"\/test\/TestSuite\/test_network.vsn\"));\n\n vpr::Thread sim_thread(run);\n#endif\n\n \/\/ -------- CONFIGURE METRIC REGISTRY ------- \/\/\n CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();\n std::string metric_prefix; \/\/ Prefix for all metric labels (mode\/hostname)\n\n std::string host_name = vpr::System::getHostname();\n metric_prefix = host_name + \"\/\";\n#ifdef _DEBUG\n metric_prefix += \"Debug\/\";\n#endif\n#ifdef _OPT\n metric_prefix += \"Opt\/\";\n#endif\n#ifdef VPR_SIMULATOR\n metric_prefix += \"Sim\/\";\n#endif\n\n std::cout << \"Setting up metrics for host: \" << host_name << std::endl;\n std::cout << \" prefix: \" << metric_prefix << std::endl;\n\n metric_reg->setPrefix(metric_prefix);\n metric_reg->setFilename(\"vapor_metrics.txt\");\n metric_reg->setMetric(\"Main\/MetricTest\", 1221.75f);\n\n CppUnit::TextTestRunner runner;\n\n \/\/------------------------------------\n \/\/ noninteractive\n \/\/------------------------------------\n \/\/ create non-interactive test suite\n CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite(\"noninteractive\");\n\n \/\/ add tests to the suite\n#ifdef VPR_SIMULATOR\n \/\/ Simulator tests.\n noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());\n noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());\n#else\n \/\/ Real tests.\n#endif\n\n \/\/ Common tests (both real and simulator).\n noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());\n noninteractive_suite->addTest(vprTest::BoostTest::suite());\n noninteractive_suite->addTest(vprTest::SystemTest::suite());\n noninteractive_suite->addTest(vprTest::IntervalTest::suite());\n noninteractive_suite->addTest(vprTest::GUIDTest::suite());\n noninteractive_suite->addTest(vprTest::InetAddrTest::suite());\n noninteractive_suite->addTest(vprTest::SocketTest::suite());\n noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());\n\/\/ noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());\n noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());\n noninteractive_suite->addTest(vprTest::SelectorTest::suite());\n\n \/\/ Add the test suite to the runner\n runner.addTest( noninteractive_suite );\n\n \/\/ ------------------------------\n \/\/ METRICS\n \/\/ ------------------------------\n CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite(\"metrics\");\n\n metrics_suite->addTest(vprTest::IntervalTest::metric_suite());\n metrics_suite->addTest(vprTest::GUIDTest::metric_suite());\n metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());\n\n runner.addTest(metrics_suite);\n\n \/\/noninteractive_suite->addTest(metrics_suite);\n\n\n \/\/ -------------------------------\n \/\/ INTERACTIVE\n \/\/ -------------------------------\n CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite(\"interactive\");\n\n interactive_suite->addTest(vprTest::ThreadTest::suite());\n\n runner.addTest(interactive_suite);\n\n \/\/ run all test suites\n if ( ac > 1 )\n {\n if ( strcmp(av[1], \"interactive\") == 0 )\n {\n runner.run(\"interactive\");\n }\n else if ( strcmp(av[1], \"noninteractive\") == 0 )\n {\n runner.run(\"noninteractive\");\n }\n else if ( strcmp(av[1], \"metrics\") == 0 )\n {\n runner.run(\"metrics\");\n }\n else if ( strcmp(av[1], \"all\") == 0 )\n {\n runner.run(\"noninteractive\");\n runner.run(\"metrics\");\n runner.run(\"interactive\");\n }\n }\n else\n {\n runner.run(\"noninteractive\");\n runner.run(\"metrics\");\n runner.run(\"interactive\");\n }\n\n return 0;\n}\n<commit_msg>Added a missing header in the simulator case.<commit_after>#include <vpr\/vprConfig.h>\n\n#include <cppunit\/TestSuite.h>\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/MetricRegistry.h>\n\n\/\/ Common (sim and real) tests.\n#include <TestCases\/Socket\/SocketTest.h>\n#include <TestCases\/Socket\/NonBlockingSocketsTest.h>\n#include <TestCases\/Socket\/SocketCopyConstructorTest.h>\n#include <TestCases\/Socket\/SocketConnectorAcceptorTest.h>\n\n#include <TestCases\/Thread\/ThreadTest.h>\n\n#include <TestCases\/IO\/Socket\/InetAddrTest.h>\n#include <TestCases\/IO\/SelectorTest.h>\n\n#include <TestCases\/IO\/Stats\/SocketBandwidthIOStatsTest.h>\n\n#include <TestCases\/Util\/ReturnStatusTest.h>\n#include <TestCases\/Util\/IntervalTest.h>\n#include <TestCases\/Util\/GUIDTest.h>\n\n\/\/ Simulator tests.\n#ifdef VPR_SIMULATOR\n# include <vpr\/md\/SIM\/Controller.h>\n\n# include <TestCases\/Simulator\/SimSelectorTest.h>\n# include <TestCases\/Simulator\/SocketSimulatorTest.h>\n\n\/\/ Real tests.\n#else\n#endif\n\n#include <TestCases\/BoostTest.h>\n#include <TestCases\/SystemTest.h>\n\n#include <vpr\/Thread\/Thread.h>\n#include <vpr\/Util\/Debug.h>\n#include <vpr\/System.h>\n\n\/\/#define vprtest_RANDOM_SEED 1\n\n#ifdef VPR_SIMULATOR\nstatic void run (void* arg)\n{\n while ( true )\n {\n vpr::sim::Controller::instance()->processNextEvent();\n vpr::Thread::yield();\n }\n}\n#endif\n\nint main (int ac, char **av)\n{\n vprDEBUG(vprDBG_ALL,0) << \"\\n\\n-----------------------------------------\\n\" << vprDEBUG_FLUSH;\n vprDEBUG(vprDBG_ALL,0) << \"Starting test\\n\" << vprDEBUG_FLUSH; \/\/ Do this here to get init text out of the way\n\n \/\/ Init random number generation\n unsigned int random_seed;\n\n#ifdef vprtest_RANDOM_SEED\n timeval cur_time;\n vpr::System::gettimeofday(&cur_time);\n random_seed = cur_time.tv_usec;\n vprDEBUG(vprDBG_ALL,0) << \"timeval.usec: \" << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;\n#else\n random_seed = 1; \/\/ Use this for repeatability\n#endif\n\n vprDEBUG(vprDBG_ALL,0) << \" Random seed: \" << random_seed << std::endl\n << vprDEBUG_FLUSH;\n\n srandom(random_seed);\n srand(random_seed);\n\n#ifdef VPR_SIMULATOR \/\/ ------ CONFIGURE SIM NETWORK ------ \/\/\n std::string path_base(GRAPH_PATH);\n\n vpr::sim::Controller::instance()->constructNetwork(path_base.append(\"\/test\/TestSuite\/test_network.vsn\"));\n\n vpr::Thread sim_thread(run);\n#endif\n\n \/\/ -------- CONFIGURE METRIC REGISTRY ------- \/\/\n CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();\n std::string metric_prefix; \/\/ Prefix for all metric labels (mode\/hostname)\n\n std::string host_name = vpr::System::getHostname();\n metric_prefix = host_name + \"\/\";\n#ifdef _DEBUG\n metric_prefix += \"Debug\/\";\n#endif\n#ifdef _OPT\n metric_prefix += \"Opt\/\";\n#endif\n#ifdef VPR_SIMULATOR\n metric_prefix += \"Sim\/\";\n#endif\n\n std::cout << \"Setting up metrics for host: \" << host_name << std::endl;\n std::cout << \" prefix: \" << metric_prefix << std::endl;\n\n metric_reg->setPrefix(metric_prefix);\n metric_reg->setFilename(\"vapor_metrics.txt\");\n metric_reg->setMetric(\"Main\/MetricTest\", 1221.75f);\n\n CppUnit::TextTestRunner runner;\n\n \/\/------------------------------------\n \/\/ noninteractive\n \/\/------------------------------------\n \/\/ create non-interactive test suite\n CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite(\"noninteractive\");\n\n \/\/ add tests to the suite\n#ifdef VPR_SIMULATOR\n \/\/ Simulator tests.\n noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());\n noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());\n#else\n \/\/ Real tests.\n#endif\n\n \/\/ Common tests (both real and simulator).\n noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());\n noninteractive_suite->addTest(vprTest::BoostTest::suite());\n noninteractive_suite->addTest(vprTest::SystemTest::suite());\n noninteractive_suite->addTest(vprTest::IntervalTest::suite());\n noninteractive_suite->addTest(vprTest::GUIDTest::suite());\n noninteractive_suite->addTest(vprTest::InetAddrTest::suite());\n noninteractive_suite->addTest(vprTest::SocketTest::suite());\n noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());\n\/\/ noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());\n noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());\n noninteractive_suite->addTest(vprTest::SelectorTest::suite());\n\n \/\/ Add the test suite to the runner\n runner.addTest( noninteractive_suite );\n\n \/\/ ------------------------------\n \/\/ METRICS\n \/\/ ------------------------------\n CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite(\"metrics\");\n\n metrics_suite->addTest(vprTest::IntervalTest::metric_suite());\n metrics_suite->addTest(vprTest::GUIDTest::metric_suite());\n metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());\n\n runner.addTest(metrics_suite);\n\n \/\/noninteractive_suite->addTest(metrics_suite);\n\n\n \/\/ -------------------------------\n \/\/ INTERACTIVE\n \/\/ -------------------------------\n CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite(\"interactive\");\n\n interactive_suite->addTest(vprTest::ThreadTest::suite());\n\n runner.addTest(interactive_suite);\n\n \/\/ run all test suites\n if ( ac > 1 )\n {\n if ( strcmp(av[1], \"interactive\") == 0 )\n {\n runner.run(\"interactive\");\n }\n else if ( strcmp(av[1], \"noninteractive\") == 0 )\n {\n runner.run(\"noninteractive\");\n }\n else if ( strcmp(av[1], \"metrics\") == 0 )\n {\n runner.run(\"metrics\");\n }\n else if ( strcmp(av[1], \"all\") == 0 )\n {\n runner.run(\"noninteractive\");\n runner.run(\"metrics\");\n runner.run(\"interactive\");\n }\n }\n else\n {\n runner.run(\"noninteractive\");\n runner.run(\"metrics\");\n runner.run(\"interactive\");\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <omp.h>\n#include <stdio.h>\n\n#include \"main\/algorithms\/BruteForceSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingParallelSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingLowMemorySolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingLowMemoryParallelSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannParallelSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannSolverRLP.h\"\n#include \"main\/algorithms\/NemhauserUllmannRLPParallelSolver.h\"\nusing namespace std;\n\n#define PRINT_VERBOSE\n\nstatic const char* FIRST_KNAPSACK_INPUT_FILE = \"res\/firstFileExample.txt\";\nstatic const char* SECOND_KNAPSACK_INPUT_FILE = \"res\/secondFileExample.txt\";\nstatic const char* THIRD_KNAPSACK_INPUT_FILE = \"res\/thirdFileExample.txt\";\nstatic const char* FOURTH_KNAPSACK_INPUT_FILE = \"res\/fourthFileExample.txt\";\nstatic const char* FIFTH_KNAPSACK_INPUT_FILE = \"res\/fifthFileExample.txt\";\nstatic const char* SIXTH_KNAPSACK_INPUT_FILE = \"res\/sixthFileExample.txt\";\nstatic const char* SEVENTH_KNAPSACK_INPUT_FILE = \"res\/seventhFileExample.txt\";\nstatic const char* DP_INPUT_FILE = \"res\/dynamicProgrammingExample.txt\";\nstatic const char* SECOND_DP_INPUT_FILE = \"res\/secondDynamicProgrammingExample.txt\";\nstatic const char* KNAPSACK_OUTPUT_FILE = \"knapSackOut.txt\";\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the brute force algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeBruteForceSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new BruteForceSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanSolver(const char* inputFile, const int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanParallelSolver(const char* inputFile, int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the rlp improved version of the nemhauser ullman algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanRLPSolver(const char* inputFile, int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannSolverRLP(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel rlp improved version of the nemhauser ullman algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanRLPParallelSolver(const char* inputFile, int numOfExecutions=1) {\n\tbool sortInputByWorth = false;\n\tKnapSackSolver* solver = new NemhauserUllmannRLPParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions, sortInputByWorth);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingParallelSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the low memory version of the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingLowMemorySolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingLowMemorySolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel low memory version of the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingLowMemoryParallelSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingLowMemoryParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Can be used to check if open mp is supported by the current environment\n *\/\nvoid checkForOpenMP(){\n\tint id;\n\t#pragma omp parallel private(id)\n\t{\n\t\tid = omp_get_thread_num();\n\t\tprintf(\"%d: Hello World!\\n\", id);\n\t}\n}\n\n\/**\n * Entry point of the application.\n * Can be used to determine which algorithm should be performed how often.\n * The problem which the specific algorithm shall solve, can be determined\n * by changing the respective input file parameter.\n *\/\nint main(int argc, char* argv[]){\n\n\tint numberOfExecutions = 1;\n\tconst char* inputFile = FIRST_KNAPSACK_INPUT_FILE;\n\n\t\/\/ Command line argumennts: program [nrOfExecutions] [filePath]\n\tif (3 == argc) {\n\t\tnumberOfExecutions = std::atoi(argv[1]);\n\t\tinputFile = argv[2];\n\n\texecuteBruteForceSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanParallelSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanRLPSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanRLPParallelSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingParallelSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingLowMemorySolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingLowMemoryParallelSolver(inputFile, numberOfExecutions);\n\n}\n<commit_msg>Oops there was a syntax error in Main.cpp<commit_after>#include <omp.h>\n#include <stdio.h>\n\n#include \"main\/algorithms\/BruteForceSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingParallelSolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingLowMemorySolver.h\"\n#include \"main\/algorithms\/DynamicProgrammingLowMemoryParallelSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannParallelSolver.h\"\n#include \"main\/algorithms\/NemhauserUllmannSolverRLP.h\"\n#include \"main\/algorithms\/NemhauserUllmannRLPParallelSolver.h\"\nusing namespace std;\n\n#define PRINT_VERBOSE\n\nstatic const char* FIRST_KNAPSACK_INPUT_FILE = \"res\/firstFileExample.txt\";\nstatic const char* SECOND_KNAPSACK_INPUT_FILE = \"res\/secondFileExample.txt\";\nstatic const char* THIRD_KNAPSACK_INPUT_FILE = \"res\/thirdFileExample.txt\";\nstatic const char* FOURTH_KNAPSACK_INPUT_FILE = \"res\/fourthFileExample.txt\";\nstatic const char* FIFTH_KNAPSACK_INPUT_FILE = \"res\/fifthFileExample.txt\";\nstatic const char* SIXTH_KNAPSACK_INPUT_FILE = \"res\/sixthFileExample.txt\";\nstatic const char* SEVENTH_KNAPSACK_INPUT_FILE = \"res\/seventhFileExample.txt\";\nstatic const char* DP_INPUT_FILE = \"res\/dynamicProgrammingExample.txt\";\nstatic const char* SECOND_DP_INPUT_FILE = \"res\/secondDynamicProgrammingExample.txt\";\nstatic const char* KNAPSACK_OUTPUT_FILE = \"knapSackOut.txt\";\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the brute force algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeBruteForceSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new BruteForceSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanSolver(const char* inputFile, const int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanParallelSolver(const char* inputFile, int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the rlp improved version of the nemhauser ullman algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanRLPSolver(const char* inputFile, int numOfExecutions=1) {\n\tKnapSackSolver* solver = new NemhauserUllmannSolverRLP(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel rlp improved version of the nemhauser ullman algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeNemhauserUllmanRLPParallelSolver(const char* inputFile, int numOfExecutions=1) {\n\tbool sortInputByWorth = false;\n\tKnapSackSolver* solver = new NemhauserUllmannRLPParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions, sortInputByWorth);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingParallelSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the low memory version of the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingLowMemorySolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingLowMemorySolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Solves the knapsack problem found within the given input file\n * by applying the parallel low memory version of the dynamic programming algorithm n times,\n * where n equals the numOfExecutions parameter.\n *\/\nvoid executeDynamicProgrammingLowMemoryParallelSolver(const char* inputFile, int numOfExecutions=1){\n\tKnapSackSolver* solver = new DynamicProgrammingLowMemoryParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);\n\tsolver->start();\n\tdelete solver;\n}\n\n\/**\n * Can be used to check if open mp is supported by the current environment\n *\/\nvoid checkForOpenMP(){\n\tint id;\n\t#pragma omp parallel private(id)\n\t{\n\t\tid = omp_get_thread_num();\n\t\tprintf(\"%d: Hello World!\\n\", id);\n\t}\n}\n\n\/**\n * Entry point of the application.\n * Can be used to determine which algorithm should be performed how often.\n * The problem which the specific algorithm shall solve, can be determined\n * by changing the respective input file parameter.\n *\/\nint main(int argc, char* argv[]){\n\n\tint numberOfExecutions = 1;\n\tconst char* inputFile = FIRST_KNAPSACK_INPUT_FILE;\n\n\t\/\/ Command line argumennts: program [nrOfExecutions] [filePath]\n\tif (3 == argc) {\n\t\tnumberOfExecutions = std::atoi(argv[1]);\n\t\tinputFile = argv[2];\n\t}\n\n\texecuteBruteForceSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanParallelSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanRLPSolver(inputFile, numberOfExecutions);\n\texecuteNemhauserUllmanRLPParallelSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingParallelSolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingLowMemorySolver(inputFile, numberOfExecutions);\n\texecuteDynamicProgrammingLowMemoryParallelSolver(inputFile, numberOfExecutions);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 Vicente Romero Calero\n\/\/\n\/\/ Distributed under the MIT software license, see the file LICENSE\n\/\/\n\/\/ Author: Vicente Romero <vteromero@gmail.com>\n\/\/\n\/\/ This file tests the BST class\n\n#include <stdio.h>\n\n#include \"structures\/bst.h\"\n\nvoid PrintValue(const int &value)\n{\n printf(\"%d \", value);\n}\n\nvoid CheckValue(BST<int>& bst, const int& value)\n{\n BSTNode<int> *node = bst.Search(value);\n if(node == NULL)\n printf(\"Value %d doesn't exist!\\n\", value);\n else\n printf(\"Value %d exist!\\n\", value);\n}\n\nint main()\n{\n BST<int> bst;\n void (*p_funct)(const int&) = PrintValue;\n\n printf(\"\\n****** Inserting values ******\\n\");\n bst.Insert(44);\n bst.Insert(4);\n bst.Insert(3);\n bst.Insert(13);\n bst.Insert(-10);\n bst.Insert(-22);\n bst.Insert(9);\n\n printf(\"In-order tree walk: \");\n bst.InOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Reverse in-order tree walk: \");\n bst.ReverseInOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Pre-order tree walk: \");\n bst.PreOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Post-order tree walk: \");\n bst.PostOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Size: %d\\n\", bst.size());\n printf(\"Minimum: %d\\n\", bst.Minimum());\n printf(\"Maximum: %d\\n\", bst.Maximum());\n\n printf(\"\\n****** Deleting values ******\\n\");\n bst.Delete(-10);\n bst.Delete(13);\n bst.Delete(44);\n\n printf(\"In-order tree walk: \");\n bst.InOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Reverse in-order tree walk: \");\n bst.ReverseInOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Pre-order tree walk: \");\n bst.PreOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Post-order tree walk: \");\n bst.PostOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Size: %d\\n\", bst.size());\n printf(\"Minimum: %d\\n\", bst.Minimum());\n printf(\"Maximum: %d\\n\", bst.Maximum());\n\n printf(\"\\n****** Checking values ******\\n\");\n CheckValue(bst, 1000);\n CheckValue(bst, 3);\n\n printf(\"\\n****** Accessing through position ******\\n\");\n printf(\"Value at 0: %d\\n\", bst.Get(0));\n printf(\"Value at 2: %d\\n\", bst.Get(2));\n\n return 0;\n}\n<commit_msg>normalization of directory names<commit_after>\/\/ Copyright (c) 2013 Vicente Romero Calero\n\/\/\n\/\/ Distributed under the MIT software license, see the file LICENSE\n\/\/\n\/\/ Author: Vicente Romero <vteromero@gmail.com>\n\/\/\n\/\/ This file tests the BST class\n\n#include <stdio.h>\n\n#include \"structure\/bst.h\"\n\nvoid PrintValue(const int &value)\n{\n printf(\"%d \", value);\n}\n\nvoid CheckValue(BST<int>& bst, const int& value)\n{\n BSTNode<int> *node = bst.Search(value);\n if(node == NULL)\n printf(\"Value %d doesn't exist!\\n\", value);\n else\n printf(\"Value %d exist!\\n\", value);\n}\n\nint main()\n{\n BST<int> bst;\n void (*p_funct)(const int&) = PrintValue;\n\n printf(\"\\n****** Inserting values ******\\n\");\n bst.Insert(44);\n bst.Insert(4);\n bst.Insert(3);\n bst.Insert(13);\n bst.Insert(-10);\n bst.Insert(-22);\n bst.Insert(9);\n\n printf(\"In-order tree walk: \");\n bst.InOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Reverse in-order tree walk: \");\n bst.ReverseInOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Pre-order tree walk: \");\n bst.PreOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Post-order tree walk: \");\n bst.PostOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Size: %d\\n\", bst.size());\n printf(\"Minimum: %d\\n\", bst.Minimum());\n printf(\"Maximum: %d\\n\", bst.Maximum());\n\n printf(\"\\n****** Deleting values ******\\n\");\n bst.Delete(-10);\n bst.Delete(13);\n bst.Delete(44);\n\n printf(\"In-order tree walk: \");\n bst.InOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Reverse in-order tree walk: \");\n bst.ReverseInOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Pre-order tree walk: \");\n bst.PreOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Post-order tree walk: \");\n bst.PostOrderWalk(p_funct);\n printf(\"\\n\");\n\n printf(\"Size: %d\\n\", bst.size());\n printf(\"Minimum: %d\\n\", bst.Minimum());\n printf(\"Maximum: %d\\n\", bst.Maximum());\n\n printf(\"\\n****** Checking values ******\\n\");\n CheckValue(bst, 1000);\n CheckValue(bst, 3);\n\n printf(\"\\n****** Accessing through position ******\\n\");\n printf(\"Value at 0: %d\\n\", bst.Get(0));\n printf(\"Value at 2: %d\\n\", bst.Get(2));\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: linguprops.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: tl $ $Date: 2001-05-08 12:34:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVTOOLS_LINGUPROPS_HXX_\n#define _SVTOOLS_LINGUPROPS_HXX_\n\n\n\/\/ UNO property names for general options\n#define UPN_IS_GERMAN_PRE_REFORM \"IsGermanPreReform\"\n#define UPN_IS_USE_DICTIONARY_LIST \"IsUseDictionaryList\"\n#define UPN_IS_IGNORE_CONTROL_CHARACTERS \"IsIgnoreControlCharacters\"\n#define UPN_ACTIVE_DICTIONARIES \"ActiveDictionaries\"\n\n\/\/ UNO property names for SpellChecker\n#define UPN_IS_SPELL_UPPER_CASE \"IsSpellUpperCase\"\n#define UPN_IS_SPELL_WITH_DIGITS \"IsSpellWithDigits\"\n#define UPN_IS_SPELL_CAPITALIZATION \"IsSpellCapitalization\"\n\n\/\/ UNO property names for Hyphenator\n#define UPN_HYPH_MIN_LEADING \"HyphMinLeading\"\n#define UPN_HYPH_MIN_TRAILING \"HyphMinTrailing\"\n#define UPN_HYPH_MIN_WORD_LENGTH \"HyphMinWordLength\"\n\n\/\/ UNO property names for Lingu\n\/\/ (those not covered by the SpellChecker and Hyphenator\n\/\/ properties and more likely to be used in other modules only)\n#define UPN_DEFAULT_LANGUAGE \"DefaultLanguage\"\n#define UPN_DEFAULT_LOCALE \"DefaultLocale\"\n#define UPN_DEFAULT_LOCALE_CJK \"DefaultLocale_CJK\"\n#define UPN_DEFAULT_LOCALE_CTL \"DefaultLocale_CTL\"\n#define UPN_IS_HYPH_AUTO \"IsHyphAuto\"\n#define UPN_IS_HYPH_SPECIAL \"IsHyphSpecial\"\n#define UPN_IS_SPELL_AUTO \"IsSpellAuto\"\n#define UPN_IS_SPELL_HIDE \"IsSpellHide\"\n#define UPN_IS_SPELL_IN_ALL_LANGUAGES \"IsSpellInAllLanguages\"\n#define UPN_IS_SPELL_SPECIAL \"IsSpellSpecial\"\n#define UPN_IS_WRAP_REVERSE \"IsWrapReverse\"\n\n\/\/ uno property handles\n#define UPH_IS_GERMAN_PRE_REFORM 0\n#define UPH_IS_USE_DICTIONARY_LIST 1\n#define UPH_IS_IGNORE_CONTROL_CHARACTERS 2\n#define UPH_IS_SPELL_UPPER_CASE 3\n#define UPH_IS_SPELL_WITH_DIGITS 4\n#define UPH_IS_SPELL_CAPITALIZATION 5\n#define UPH_HYPH_MIN_LEADING 6\n#define UPH_HYPH_MIN_TRAILING 7\n#define UPH_HYPH_MIN_WORD_LENGTH 8\n#define UPH_DEFAULT_LOCALE 9\n#define UPH_IS_SPELL_AUTO 10\n#define UPH_IS_SPELL_HIDE 11\n#define UPH_IS_SPELL_IN_ALL_LANGUAGES 12\n#define UPH_IS_SPELL_SPECIAL 13\n#define UPH_IS_HYPH_AUTO 14\n#define UPH_IS_HYPH_SPECIAL 15\n#define UPH_IS_WRAP_REVERSE 16\n#define UPH_DEFAULT_LANGUAGE 21\n#define UPH_DEFAULT_LOCALE_CJK 22\n#define UPH_DEFAULT_LOCALE_CTL 23\n#define UPH_ACTIVE_DICTIONARIES 24\n\n#endif\n\n<commit_msg>INTEGRATION: CWS tl01 (1.3.284); FILE MERGED 2003\/08\/01 11:28:59 tl 1.3.284.2: #110762# API for Hangul\/Hanja user dictionaries 2003\/07\/29 09:20:42 tl 1.3.284.1: #110762# Hangul\/Hanja text conversion user dictionaries<commit_after>\/*************************************************************************\n *\n * $RCSfile: linguprops.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-04-27 15:59:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVTOOLS_LINGUPROPS_HXX_\n#define _SVTOOLS_LINGUPROPS_HXX_\n\n\n\/\/ UNO property names for general options\n#define UPN_IS_GERMAN_PRE_REFORM \"IsGermanPreReform\"\n#define UPN_IS_USE_DICTIONARY_LIST \"IsUseDictionaryList\"\n#define UPN_IS_IGNORE_CONTROL_CHARACTERS \"IsIgnoreControlCharacters\"\n#define UPN_ACTIVE_DICTIONARIES \"ActiveDictionaries\"\n\n\/\/ UNO property names for SpellChecker\n#define UPN_IS_SPELL_UPPER_CASE \"IsSpellUpperCase\"\n#define UPN_IS_SPELL_WITH_DIGITS \"IsSpellWithDigits\"\n#define UPN_IS_SPELL_CAPITALIZATION \"IsSpellCapitalization\"\n\n\/\/ UNO property names for Hyphenator\n#define UPN_HYPH_MIN_LEADING \"HyphMinLeading\"\n#define UPN_HYPH_MIN_TRAILING \"HyphMinTrailing\"\n#define UPN_HYPH_MIN_WORD_LENGTH \"HyphMinWordLength\"\n\n\/\/ UNO property names for Lingu\n\/\/ (those not covered by the SpellChecker and Hyphenator\n\/\/ properties and more likely to be used in other modules only)\n#define UPN_DEFAULT_LANGUAGE \"DefaultLanguage\"\n#define UPN_DEFAULT_LOCALE \"DefaultLocale\"\n#define UPN_DEFAULT_LOCALE_CJK \"DefaultLocale_CJK\"\n#define UPN_DEFAULT_LOCALE_CTL \"DefaultLocale_CTL\"\n#define UPN_IS_HYPH_AUTO \"IsHyphAuto\"\n#define UPN_IS_HYPH_SPECIAL \"IsHyphSpecial\"\n#define UPN_IS_SPELL_AUTO \"IsSpellAuto\"\n#define UPN_IS_SPELL_HIDE \"IsSpellHide\"\n#define UPN_IS_SPELL_IN_ALL_LANGUAGES \"IsSpellInAllLanguages\"\n#define UPN_IS_SPELL_SPECIAL \"IsSpellSpecial\"\n#define UPN_IS_WRAP_REVERSE \"IsWrapReverse\"\n\n\/\/ UNO property names for text conversion options\n#define UPN_ACTIVE_CONVERSION_DICTIONARIES \"ActiveConversionDictionaries\"\n#define UPN_IS_IGNORE_POST_POSITIONAL_WORD \"IsIgnorePostPositionalWord\"\n#define UPN_IS_AUTO_CLOSE_DIALOG \"IsAutoCloseDialog\"\n#define UPN_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST \"IsShowEntriesRecentlyUsedFirst\"\n#define UPN_IS_AUTO_REPLACE_UNIQUE_ENTRIES \"IsAutoReplaceUniqueEntries\"\n\n\/\/ uno property handles\n#define UPH_IS_GERMAN_PRE_REFORM 0\n#define UPH_IS_USE_DICTIONARY_LIST 1\n#define UPH_IS_IGNORE_CONTROL_CHARACTERS 2\n#define UPH_IS_SPELL_UPPER_CASE 3\n#define UPH_IS_SPELL_WITH_DIGITS 4\n#define UPH_IS_SPELL_CAPITALIZATION 5\n#define UPH_HYPH_MIN_LEADING 6\n#define UPH_HYPH_MIN_TRAILING 7\n#define UPH_HYPH_MIN_WORD_LENGTH 8\n#define UPH_DEFAULT_LOCALE 9\n#define UPH_IS_SPELL_AUTO 10\n#define UPH_IS_SPELL_HIDE 11\n#define UPH_IS_SPELL_IN_ALL_LANGUAGES 12\n#define UPH_IS_SPELL_SPECIAL 13\n#define UPH_IS_HYPH_AUTO 14\n#define UPH_IS_HYPH_SPECIAL 15\n#define UPH_IS_WRAP_REVERSE 16\n#define UPH_DEFAULT_LANGUAGE 21\n#define UPH_DEFAULT_LOCALE_CJK 22\n#define UPH_DEFAULT_LOCALE_CTL 23\n#define UPH_ACTIVE_DICTIONARIES 24\n#define UPH_ACTIVE_CONVERSION_DICTIONARIES 25\n#define UPH_IS_IGNORE_POST_POSITIONAL_WORD 26\n#define UPH_IS_AUTO_CLOSE_DIALOG 27\n#define UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST 28\n#define UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES 29\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"lib\/pool.hpp\"\n\nint main(int argc, char **argv) {\n return 0;\n}\n<commit_msg>Add parallel merge sort<commit_after>#include <future>\n#include <cstdio>\n#include <cstdlib>\n#include <time.h>\n\n#define PRINT true\n\nvoid merge_sort(int array[], const int left, const int right) {\n if (right - left < 1) return;\n const int middle = (left + right) \/ 2;\n auto lh = std::async(std::launch::async, [array, left, middle]() {\n merge_sort(array, left, middle);\n });\n auto rh = std::async(std::launch::async, [array, middle, right]() {\n merge_sort(array, middle + 1, right);\n });\n lh.get();\n rh.get();\n int temp[right - left + 1];\n int k = 0, l = left, m = middle + 1;\n while (l <= middle && m <= right) {\n if (array[l] < array[m]) {\n temp[k++] = array[l++];\n } else {\n temp[k++] = array[m++];\n }\n }\n while (l <= middle) temp[k++] = array[l++];\n while (m <= right) temp[k++] = array[m++];\n for (int v = 0, i = left; i <= right; ++i, ++v) array[i] = temp[v];\n}\n\nint main(int argc, char **argv) {\n srand(time(nullptr));\n int array_size = 100;\n int *arr = new int[array_size];\n for (int i = 0; i < array_size; ++i) arr[i] = rand() % 1000;\n merge_sort(arr, 0, array_size - 1);\n#if PRINT\n for (int i = 0; i < array_size; ++i) printf(\"%d \", arr[i]);\n puts(\"\");\n#endif\n delete[] arr;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <cstdio>\n#include <cstdint>\n#include <cstring>\n#include <cassert>\n#include <algorithm>\n\n#include \"input_data.cpp\"\n#include \"gettime.cpp\"\n#include \"quicksort.cpp\"\n\n\nclass PerformanceTest final {\n\n int iterations;\n InputData& input;\n uint32_t* tmp;\n\npublic:\n PerformanceTest(int n, InputData& input)\n : iterations(n)\n , input(input) {\n \n assert(iterations > 0);\n tmp = new uint32_t[input.count()];\n }\n\n ~PerformanceTest() {\n delete[] tmp;\n }\n\npublic:\n template <typename SORT_FUNCTION>\n uint32_t run(SORT_FUNCTION sort) {\n\n uint32_t time = 0;\n\n int k = iterations;\n while (k--) {\n memcpy(tmp, input.pointer(), input.size());\n\n const uint32_t t1 = get_time();\n sort(input.pointer(), 0, input.count() - 1);\n const uint32_t t2 = get_time();\n\n const uint32_t dt = t2 - t1;\n\n if (time == 0) {\n time = dt;\n } else if (dt < time) {\n time = dt;\n }\n }\n\n return time;\n }\n};\n\n\nvoid std_sort_wrapper(uint32_t* array, int left, int right) {\n \n std::sort(array + left, array + right + 1);\n}\n\n\ntemplate <typename SORT_FUNCTION>\nuint32_t measure(const char* name, SORT_FUNCTION sort, InputData& data, uint32_t ref) {\n\n PerformanceTest test(3, data);\n\n printf(\"%30s ... \", name); fflush(stdout);\n uint32_t time = test.run(sort);\n if (ref > 0) {\n printf(\"%0.4f s (%0.2f)\\n\", time\/1000000.0, ref\/double(time));\n } else {\n printf(\"%0.4f s\\n\", time\/1000000.0);\n }\n\n return time;\n}\n\n\nint main(int argc, char* argv[]) {\n\n#define M 1000000\n size_t count = 10*M;\n\n if (argc > 1 && atoi(argv[1]) > 0) {\n count = atoi(argv[1]) * M;\n }\n\n InputRandom data(count);\n\n printf(\"items count: %lu (%lu bytes)\\n\", data.count(), data.size());\n\n uint32_t ref = 0;\n ref = measure(\"std::sort\", std_sort_wrapper, data, 0);\n measure(\"quick sort\", quicksort, data, ref);\n measure(\"AVX512 quick sort\", avx512_quicksort, data, ref);\n measure(\"AVX512 + popcnt quick sort\", avx512_popcnt_quicksort, data, ref);\n}\n<commit_msg>AVX512 quicksort: speed util parses cmd line<commit_after>#include <cstdlib>\n#include <cstdio>\n#include <cstdint>\n#include <cstring>\n#include <cassert>\n#include <algorithm>\n#include <memory>\n\n#include \"input_data.cpp\"\n#include \"gettime.cpp\"\n#include \"quicksort.cpp\"\n\n\nclass PerformanceTest final {\n\n int iterations;\n InputData& input;\n uint32_t* tmp;\n\npublic:\n PerformanceTest(int n, InputData& input)\n : iterations(n)\n , input(input) {\n \n assert(iterations > 0);\n tmp = new uint32_t[input.count()];\n }\n\n ~PerformanceTest() {\n delete[] tmp;\n }\n\npublic:\n template <typename SORT_FUNCTION>\n uint32_t run(SORT_FUNCTION sort) {\n\n uint32_t time = 0;\n\n int k = iterations;\n while (k--) {\n memcpy(tmp, input.pointer(), input.size());\n\n const uint32_t t1 = get_time();\n sort(input.pointer(), 0, input.count() - 1);\n const uint32_t t2 = get_time();\n\n const uint32_t dt = t2 - t1;\n\n if (time == 0) {\n time = dt;\n } else if (dt < time) {\n time = dt;\n }\n }\n\n return time;\n }\n};\n\n\nenum class InputType {\n random,\n ascending,\n descending,\n};\n\n\nconst char* as_string(InputType type) {\n switch (type) {\n case InputType::random:\n return \"random\";\n\n case InputType::ascending:\n return \"ascending\";\n\n case InputType::descending:\n return \"descending\";\n\n default:\n return \"<unknown>\";\n }\n}\n\n\nvoid std_sort_wrapper(uint32_t* array, int left, int right) {\n \n std::sort(array + left, array + right + 1);\n}\n\n\nclass Test {\n\n std::unique_ptr<InputData> data;\n InputType type;\n size_t count;\n int iterations;\n\npublic:\n Test(InputType type, size_t count, int iterations)\n : type(type)\n , count(count)\n , iterations(iterations) {\n\n switch (type) {\n case InputType::random:\n data.reset(new InputRandom(count));\n break;\n\n case InputType::ascending:\n data.reset(new InputAscending(count));\n break;\n\n case InputType::descending:\n data.reset(new InputDescending(count));\n break;\n }\n }\n\n void run() {\n\n printf(\"items count: %lu (%lu bytes), input %s\\n\", data->count(), data->size(), as_string(type));\n\n uint32_t ref = 0;\n ref = measure(\"std::sort\", std_sort_wrapper, ref);\n measure(\"quick sort\", quicksort, ref);\n measure(\"AVX512 quick sort\", avx512_quicksort, ref);\n measure(\"AVX512 + popcnt quick sort\", avx512_popcnt_quicksort, ref);\n }\n\nprivate:\n template <typename SORT_FUNCTION>\n uint32_t measure(const char* name, SORT_FUNCTION sort, uint32_t ref) {\n\n PerformanceTest test(iterations, *data);\n\n printf(\"%30s ... \", name); fflush(stdout);\n uint32_t time = test.run(sort);\n if (ref > 0) {\n printf(\"%0.4f s (%0.2f)\\n\", time\/1000000.0, ref\/double(time));\n } else {\n printf(\"%0.4f s\\n\", time\/1000000.0);\n }\n\n return time;\n }\n};\n\n\n\/\/ ------------------------------------------------------------\n\n\nvoid usage() {\n puts(\"usage:\");\n puts(\"speed SIZE ITERATIONS INPUT\");\n puts(\"\");\n puts(\"where\");\n puts(\"* SIZE - number of 32-bit elements\");\n puts(\"* ITERATIONS - number of iterations\");\n puts(\"* INPUT - one of:\");\n puts(\" ascending (or asc)\");\n puts(\" descending (or dsc, desc)\");\n puts(\" random (or rnd, rand)\");\n}\n\n\nint main(int argc, char* argv[]) {\n\n if (argc < 4) {\n usage();\n return EXIT_FAILURE;\n }\n\n int count = atoi(argv[1]);\n int iterations = atoi(argv[2]);\n InputType type;\n\n#define is_keyword(key) (strcmp(argv[3], key) == 0)\n if (is_keyword(\"descending\") || is_keyword(\"dsc\") || is_keyword(\"dsc\")) {\n type = InputType::descending;\n } else if (is_keyword(\"ascending\") || is_keyword(\"asc\")) {\n type = InputType::ascending;\n } else if (is_keyword(\"random\") || is_keyword(\"rand\") || is_keyword(\"rnd\")) {\n type = InputType::ascending;\n } else {\n usage();\n return EXIT_FAILURE;\n }\n#undef is_keyword\n\n Test test(type, count, iterations);\n test.run();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ KMail Account Manager\n\n#include \"accountmanager.h\"\n\n#include \"kmaccount.h\"\n#include \"kmacctmaildir.h\"\n#include \"kmacctlocal.h\"\n#include \"popaccount.h\"\n#include \"kmacctimap.h\"\n#include \"networkaccount.h\"\n#include \"kmacctcachedimap.h\"\n#include \"broadcaststatus.h\"\n#include \"kmfiltermgr.h\"\n#include \"globalsettings.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <QRegExp>\n#include <krandom.h>\n#include <kconfiggroup.h>\n\nusing namespace KMail;\n\n\/\/-----------------------------------------------------------------------------\nAccountManager::AccountManager()\n :QObject(), mNewMailArrived( false ), mInteractive( false ),\n mTotalNewMailsArrived( 0 ), mDisplaySummary( false )\n{\n mAcctChecking.clear();\n mAcctTodo.clear();\n}\n\n\/\/-----------------------------------------------------------------------------\nAccountManager::~AccountManager()\n{\n writeConfig( false );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::writeConfig( bool withSync )\n{\n KConfig* config = KMKernel::config();\n\n \/\/ Delete all account enabled groups in the config file\n \/\/ and replace them with new account groups\n uint accounts = 0;\n QStringList accountGroups =\n config->groupList().filter( QRegExp( \"Account \\\\d+\" ) );\n AccountList::ConstIterator enabledAccountIt = mAcctList.constBegin();\n foreach ( const QString& groupName, accountGroups ) {\n KConfigGroup group(config, groupName);\n uint id = group.readEntry( \"Id\", 0 );\n if ( mDisabledAccounts.contains( id ) )\n accounts++;\n else {\n config->deleteGroup( groupName );\n if ( enabledAccountIt != mAcctList.constEnd() ) {\n (*enabledAccountIt)->writeConfig( group );\n ++enabledAccountIt;\n accounts++;\n }\n }\n }\n\n KConfigGroup group(config, \"General\");\n group.writeEntry(\"accounts\", accounts);\n\n if (withSync) config->sync();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::readConfig(void)\n{\n KConfig* config = KMKernel::config();\n KMAccount* acct;\n QString acctName;\n QString groupName;\n int i, num;\n\n for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )\n delete *it;\n mAcctList.clear();\n\n KConfigGroup general(config, \"General\");\n num = general.readEntry( \"accounts\", 0 );\n\n for (i=1; i<=num; i++)\n {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroup group(config, groupName);\n uint id = group.readEntry( \"Id\", 0 );\n if ( !group.readEntry(\"Enabled\", true) ) {\n mDisabledAccounts += id;\n continue;\n }\n\n KAccount::Type acctType = KAccount::typeForName( group.readEntry( \"Type\" ) );\n acctName = group.readEntry(\"Name\");\n if (acctName.isEmpty()) acctName = i18n(\"Account %1\", i);\n acct = create(acctType, acctName, id);\n if (!acct) continue;\n add(acct);\n acct->readConfig(group);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::singleCheckMail(KMAccount *account, bool interactive)\n{\n mNewMailArrived = false;\n mInteractive = interactive;\n\n \/\/ queue the account\n mAcctTodo.append(account);\n\n if (account->checkingMail())\n {\n kDebug(5006) <<\"account\" << account->name() <<\" busy, queuing\";\n return;\n }\n\n processNextCheck( false );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::processNextCheck( bool _newMail )\n{\n kDebug(5006) <<\"processNextCheck, remaining\" << mAcctTodo.count();\n if ( _newMail )\n mNewMailArrived = true;\n\n for ( AccountList::Iterator it( mAcctChecking.begin() ), end( mAcctChecking.end() ); it != end; ) {\n KMAccount* acct = *it;\n ++it;\n if ( acct->checkingMail() )\n continue;\n \/\/ check done\n kDebug(5006) <<\"account\" << acct->name() <<\" finished check\";\n mAcctChecking.removeAll( acct );\n kmkernel->filterMgr()->deref();\n disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n }\n if ( mAcctChecking.isEmpty() ) {\n \/\/ all checks finished, display summary\n if ( mDisplaySummary )\n KPIM::BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(\n mTotalNewMailsArrived );\n emit checkedMail( mNewMailArrived, mInteractive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n mDisplaySummary = false;\n }\n if ( mAcctTodo.isEmpty() ) return;\n\n QString accountHostName;\n\n KMAccount *curAccount = 0;\n for ( AccountList::Iterator it ( mAcctTodo.begin() ), last ( mAcctTodo.end() ); it != last; ) {\n KMAccount *acct = *it;\n ++it;\n if ( !acct->checkingMail() && acct->mailCheckCanProceed() ) {\n curAccount = acct;\n mAcctTodo.removeAll( acct );\n break;\n }\n }\n if ( !curAccount ) return; \/\/ no account or all of them are already checking\n\n if ( curAccount->type() != KAccount::Imap && \n curAccount->type() != KAccount::DImap &&\n curAccount->folder() == 0 ) {\n QString tmp = i18n(\"Account %1 has no mailbox defined:\\n\"\n \"mail checking aborted;\\n\"\n \"check your account settings.\",\n curAccount->name());\n KMessageBox::information(0,tmp);\n emit checkedMail( false, mInteractive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n return;\n }\n\n connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n\n KPIM::BroadcastStatus::instance()->setStatusMsg(\n i18n(\"Checking account %1 for new mail\", curAccount->name()));\n\n kDebug(5006) <<\"processing next mail check for\" << curAccount->name();\n\n curAccount->setCheckingMail( true );\n mAcctChecking.append( curAccount );\n kmkernel->filterMgr()->ref();\n curAccount->processNewMail( mInteractive );\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::create( const KAccount::Type aType,\n const QString &aName, uint id )\n{\n KMAccount* act = 0;\n if ( id == 0 )\n id = createId();\n\n if ( aType == KAccount::Local) {\n act = new KMAcctLocal(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Maildir) {\n act = new KMAcctMaildir(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Pop) {\n act = new KMail::PopAccount(this, aName.isEmpty() ? i18n(\"POP Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Imap) {\n act = new KMAcctImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n } else if (aType == KAccount::DImap) {\n act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n }\n if ( !act ) {\n kWarning(5006) <<\"Attempt to instantiate a non-existing account type!\";\n return 0;\n }\n act->setType( aType );\n connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),\n this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );\n return act;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::add( KMAccount *account )\n{\n if ( account ) {\n mAcctList.append( account );\n emit accountAdded( account );\n account->installTimer();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::findByName(const QString &aName) const\n{\n if ( aName.isEmpty() ) return 0;\n\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( (*it)->name() == aName ) return (*it);\n }\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::find( const uint id ) const\n{\n if (id == 0) return 0;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( (*it)->id() == id ) return (*it);\n }\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::first()\n{\n if ( !mAcctList.empty() ) {\n mPtrListInterfaceProxyIterator = mAcctList.begin();\n return *mPtrListInterfaceProxyIterator;\n } else {\n return 0;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::next()\n{\n ++mPtrListInterfaceProxyIterator;\n if ( mPtrListInterfaceProxyIterator == mAcctList.end() )\n return 0;\n else\n return *mPtrListInterfaceProxyIterator;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool AccountManager::remove( KMAccount* acct )\n{\n if( !acct )\n return false;\n mAcctList.removeAll( acct );\n emit accountRemoved( acct );\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::checkMail( bool _interactive )\n{\n mNewMailArrived = false;\n\n if ( mAcctList.isEmpty() ) {\n KMessageBox::information( 0,i18n(\"You need to add an account in the network \"\n \"section of the settings in order to receive mail.\") );\n return;\n }\n mDisplaySummary = true;\n\n mTotalNewMailsArrived=0;\n mTotalNewInFolder.clear();\n\n for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( !(*it)->checkExclude() )\n singleCheckMail( (*it), _interactive);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::singleInvalidateIMAPFolders(KMAccount *account) {\n account->invalidateIMAPFolders();\n}\n\n\nvoid AccountManager::invalidateIMAPFolders()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )\n singleInvalidateIMAPFolders( *it );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQStringList AccountManager::getAccounts() const\n{\n QStringList strList;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n strList.append( (*it)->name() );\n }\n return strList;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::intCheckMail(int item, bool _interactive)\n{\n mNewMailArrived = false;\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n if ( KMAccount *acct = mAcctList[ item ] )\n singleCheckMail( acct, _interactive );\n mDisplaySummary = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )\n{\n for ( QMap<QString, int>::const_iterator it = newInFolder.begin();\n it != newInFolder.end(); ++it ) {\n mTotalNewMailsArrived += it.value();\n if ( !mTotalNewInFolder.contains( it.key() ) )\n mTotalNewInFolder[it.key()] = it.value();\n else\n mTotalNewInFolder[it.key()] += it.value();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nuint AccountManager::createId()\n{\n QList<uint> usedIds;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n usedIds << (*it)->id();\n }\n\n usedIds << 0; \/\/ 0 is default for unknown\n int newId;\n do\n {\n newId = KRandom::random();\n } while ( usedIds.contains(newId) );\n\n return newId;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::cancelMailCheck()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n (*it)->cancelMailCheck();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::readPasswords()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n NetworkAccount *acct = dynamic_cast<NetworkAccount*>( (*it) );\n if ( acct )\n acct->readPassword();\n }\n}\n\n#include \"accountmanager.moc\"\n<commit_msg>Store new account settings.<commit_after>\/\/ KMail Account Manager\n\n#include \"accountmanager.h\"\n\n#include \"kmaccount.h\"\n#include \"kmacctmaildir.h\"\n#include \"kmacctlocal.h\"\n#include \"popaccount.h\"\n#include \"kmacctimap.h\"\n#include \"networkaccount.h\"\n#include \"kmacctcachedimap.h\"\n#include \"broadcaststatus.h\"\n#include \"kmfiltermgr.h\"\n#include \"globalsettings.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <QRegExp>\n#include <krandom.h>\n#include <kconfiggroup.h>\n\nusing namespace KMail;\n\n\/\/-----------------------------------------------------------------------------\nAccountManager::AccountManager()\n :QObject(), mNewMailArrived( false ), mInteractive( false ),\n mTotalNewMailsArrived( 0 ), mDisplaySummary( false )\n{\n mAcctChecking.clear();\n mAcctTodo.clear();\n}\n\n\/\/-----------------------------------------------------------------------------\nAccountManager::~AccountManager()\n{\n writeConfig( false );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::writeConfig( bool withSync )\n{\n KConfig* config = KMKernel::config();\n\n \/\/ Delete all accounts for groups in the config file not having \n \/\/ Enabled=false flag (accountGroups) \n \/\/ and replace them with account groups existing in memory (mAcctList)\n uint accounts = 0;\n QStringList accountGroups =\n config->groupList().filter( QRegExp( \"Account \\\\d+\" ) );\n AccountList::ConstIterator enabledAccountIt = mAcctList.constBegin();\n for ( QStringList::ConstIterator it = accountGroups.constBegin() ;; ) {\n QString groupName;\n bool appendNewGroup = false;\n if ( it == accountGroups.constEnd() ) {\n if ( enabledAccountIt == mAcctList.constEnd() )\n break;\n appendNewGroup = true;\n groupName.sprintf( \"Account %d\", accounts + 1 );\n }\n else {\n groupName = *it;\n ++it;\n }\n\n KConfigGroup group(config, groupName);\n uint id = group.readEntry( \"Id\", 0 );\n if ( mDisabledAccounts.contains( id ) )\n accounts++; \/\/ do not modify disabled account - skip\n else {\n if ( appendNewGroup ) {\n (*enabledAccountIt)->writeConfig( group );\n ++enabledAccountIt;\n accounts++;\n }\n else \/\/ no such account on the list - disabled \/ enabled\n config->deleteGroup( groupName );\n }\n }\n\n KConfigGroup group(config, \"General\");\n group.writeEntry(\"accounts\", accounts);\n\n if (withSync) config->sync();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::readConfig(void)\n{\n KConfig* config = KMKernel::config();\n KMAccount* acct;\n QString acctName;\n QString groupName;\n int i, num;\n\n for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )\n delete *it;\n mAcctList.clear();\n\n KConfigGroup general(config, \"General\");\n num = general.readEntry( \"accounts\", 0 );\n\n for (i=1; i<=num; i++)\n {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroup group(config, groupName);\n uint id = group.readEntry( \"Id\", 0 );\n if ( !group.readEntry(\"Enabled\", true) ) {\n mDisabledAccounts += id;\n continue;\n }\n\n KAccount::Type acctType = KAccount::typeForName( group.readEntry( \"Type\" ) );\n acctName = group.readEntry(\"Name\");\n if (acctName.isEmpty()) acctName = i18n(\"Account %1\", i);\n acct = create(acctType, acctName, id);\n if (!acct) continue;\n add(acct);\n acct->readConfig(group);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::singleCheckMail(KMAccount *account, bool interactive)\n{\n mNewMailArrived = false;\n mInteractive = interactive;\n\n \/\/ queue the account\n mAcctTodo.append(account);\n\n if (account->checkingMail())\n {\n kDebug(5006) <<\"account\" << account->name() <<\" busy, queuing\";\n return;\n }\n\n processNextCheck( false );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::processNextCheck( bool _newMail )\n{\n kDebug(5006) <<\"processNextCheck, remaining\" << mAcctTodo.count();\n if ( _newMail )\n mNewMailArrived = true;\n\n for ( AccountList::Iterator it( mAcctChecking.begin() ), end( mAcctChecking.end() ); it != end; ) {\n KMAccount* acct = *it;\n ++it;\n if ( acct->checkingMail() )\n continue;\n \/\/ check done\n kDebug(5006) <<\"account\" << acct->name() <<\" finished check\";\n mAcctChecking.removeAll( acct );\n kmkernel->filterMgr()->deref();\n disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n }\n if ( mAcctChecking.isEmpty() ) {\n \/\/ all checks finished, display summary\n if ( mDisplaySummary )\n KPIM::BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(\n mTotalNewMailsArrived );\n emit checkedMail( mNewMailArrived, mInteractive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n mDisplaySummary = false;\n }\n if ( mAcctTodo.isEmpty() ) return;\n\n QString accountHostName;\n\n KMAccount *curAccount = 0;\n for ( AccountList::Iterator it ( mAcctTodo.begin() ), last ( mAcctTodo.end() ); it != last; ) {\n KMAccount *acct = *it;\n ++it;\n if ( !acct->checkingMail() && acct->mailCheckCanProceed() ) {\n curAccount = acct;\n mAcctTodo.removeAll( acct );\n break;\n }\n }\n if ( !curAccount ) return; \/\/ no account or all of them are already checking\n\n if ( curAccount->type() != KAccount::Imap && \n curAccount->type() != KAccount::DImap &&\n curAccount->folder() == 0 ) {\n QString tmp = i18n(\"Account %1 has no mailbox defined:\\n\"\n \"mail checking aborted;\\n\"\n \"check your account settings.\",\n curAccount->name());\n KMessageBox::information(0,tmp);\n emit checkedMail( false, mInteractive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n return;\n }\n\n connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n\n KPIM::BroadcastStatus::instance()->setStatusMsg(\n i18n(\"Checking account %1 for new mail\", curAccount->name()));\n\n kDebug(5006) <<\"processing next mail check for\" << curAccount->name();\n\n curAccount->setCheckingMail( true );\n mAcctChecking.append( curAccount );\n kmkernel->filterMgr()->ref();\n curAccount->processNewMail( mInteractive );\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::create( const KAccount::Type aType,\n const QString &aName, uint id )\n{\n KMAccount* act = 0;\n if ( id == 0 )\n id = createId();\n\n if ( aType == KAccount::Local) {\n act = new KMAcctLocal(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Maildir) {\n act = new KMAcctMaildir(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Pop) {\n act = new KMail::PopAccount(this, aName.isEmpty() ? i18n(\"POP Account\") : aName, id);\n act->setFolder( kmkernel->inboxFolder() );\n } else if ( aType == KAccount::Imap) {\n act = new KMAcctImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n } else if (aType == KAccount::DImap) {\n act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n }\n if ( !act ) {\n kWarning(5006) <<\"Attempt to instantiate a non-existing account type!\";\n return 0;\n }\n act->setType( aType );\n connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),\n this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );\n return act;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::add( KMAccount *account )\n{\n if ( account ) {\n mAcctList.append( account );\n emit accountAdded( account );\n account->installTimer();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::findByName(const QString &aName) const\n{\n if ( aName.isEmpty() ) return 0;\n\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( (*it)->name() == aName ) return (*it);\n }\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::find( const uint id ) const\n{\n if (id == 0) return 0;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( (*it)->id() == id ) return (*it);\n }\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::first()\n{\n if ( !mAcctList.empty() ) {\n mPtrListInterfaceProxyIterator = mAcctList.begin();\n return *mPtrListInterfaceProxyIterator;\n } else {\n return 0;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* AccountManager::next()\n{\n ++mPtrListInterfaceProxyIterator;\n if ( mPtrListInterfaceProxyIterator == mAcctList.end() )\n return 0;\n else\n return *mPtrListInterfaceProxyIterator;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool AccountManager::remove( KMAccount* acct )\n{\n if( !acct )\n return false;\n mAcctList.removeAll( acct );\n emit accountRemoved( acct );\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::checkMail( bool _interactive )\n{\n mNewMailArrived = false;\n\n if ( mAcctList.isEmpty() ) {\n KMessageBox::information( 0,i18n(\"You need to add an account in the network \"\n \"section of the settings in order to receive mail.\") );\n return;\n }\n mDisplaySummary = true;\n\n mTotalNewMailsArrived=0;\n mTotalNewInFolder.clear();\n\n for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n if ( !(*it)->checkExclude() )\n singleCheckMail( (*it), _interactive);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::singleInvalidateIMAPFolders(KMAccount *account) {\n account->invalidateIMAPFolders();\n}\n\n\nvoid AccountManager::invalidateIMAPFolders()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )\n singleInvalidateIMAPFolders( *it );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQStringList AccountManager::getAccounts() const\n{\n QStringList strList;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n strList.append( (*it)->name() );\n }\n return strList;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::intCheckMail(int item, bool _interactive)\n{\n mNewMailArrived = false;\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n if ( KMAccount *acct = mAcctList[ item ] )\n singleCheckMail( acct, _interactive );\n mDisplaySummary = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )\n{\n for ( QMap<QString, int>::const_iterator it = newInFolder.begin();\n it != newInFolder.end(); ++it ) {\n mTotalNewMailsArrived += it.value();\n if ( !mTotalNewInFolder.contains( it.key() ) )\n mTotalNewInFolder[it.key()] = it.value();\n else\n mTotalNewInFolder[it.key()] += it.value();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nuint AccountManager::createId()\n{\n QList<uint> usedIds;\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n usedIds << (*it)->id();\n }\n\n usedIds << 0; \/\/ 0 is default for unknown\n int newId;\n do\n {\n newId = KRandom::random();\n } while ( usedIds.contains(newId) );\n\n return newId;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::cancelMailCheck()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n (*it)->cancelMailCheck();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid AccountManager::readPasswords()\n{\n for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {\n NetworkAccount *acct = dynamic_cast<NetworkAccount*>( (*it) );\n if ( acct )\n acct->readPassword();\n }\n}\n\n#include \"accountmanager.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/** -*- c++ -*-\n * progressdialog.cpp\n *\n * Copyright (c) 2004 Till Adam <adam@kde.org>\n * based on imapprogressdialog.cpp ,which is\n * Copyright (c) 2002-2003 Klaralvdalens Datakonsult AB\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qlayout.h>\n#include <qprogressbar.h>\n#include <qtimer.h>\n#include <qheader.h>\n#include <qobject.h>\n\n#include <kpushbutton.h>\n#include <klocale.h>\n#include <kdialog.h>\n#include <kstdguiitem.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"progressdialog.h\"\n#include \"progressmanager.h\"\nusing KMail::ProgressItem;\nusing KMail::ProgressManager;\n\nnamespace KMail {\n\nTransactionItemListView::TransactionItemListView( QWidget * parent,\n const char * name,\n WFlags f )\n : QListView( parent, name, f ) {\n\n connect ( header(),SIGNAL( sizeChange ( int, int, int ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( header(),SIGNAL( indexChange ( int, int, int ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( this, SIGNAL( expanded( QListViewItem * ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( this, SIGNAL( collapsed( QListViewItem * ) ),\n this, SLOT( slotAdjustGeometry() ) );\n\n}\n\nvoid TransactionItemListView::resizeEvent( QResizeEvent* e )\n{\n slotAdjustGeometry();\n QListView::resizeEvent( e );\n}\n\nvoid TransactionItemListView::slotAdjustGeometry() {\n for (QListViewItemIterator it( this ); it.current(); it++) {\n TransactionItem *i = static_cast<TransactionItem*>( it.current() );\n i->adjustGeometry();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nTransactionItem::TransactionItem ( QListViewItem* parent,\n ProgressItem *i )\n : QListViewItem( parent ), mCancelButton( 0 )\n{\n init( i);\n}\n\nTransactionItem::TransactionItem( QListView* parent,\n QListViewItem* lastItem,\n ProgressItem *i )\n : QListViewItem( parent, lastItem ), mCancelButton( 0 )\n{\n init( i );\n}\n\nvoid TransactionItem::init ( ProgressItem *item )\n{\n mItem = item;\n mProgress = new QProgressBar( 100, listView()->viewport() );\n mProgress->setProgress( item->progress() );\n mProgress->show();\n if ( item->canBeCanceled() ) {\n mCancelButton = new QPushButton( SmallIcon( \"cancel\" ), QString::null,\n listView()->viewport() );\n mCancelButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,\n QSizePolicy::Minimum ) );\n\n mCancelButton->show();\n connect ( mCancelButton, SIGNAL( clicked() ),\n this, SLOT( slotItemCanceled() ));\n\n }\n adjustGeometry();\n setText( 0, item->label() );\n setText( 4, item->status() );\n setSelectable( false );\n}\n\nTransactionItem::~TransactionItem()\n{\n delete mCancelButton;\n delete mProgress;\n}\n\nvoid TransactionItem::setProgress( int progress )\n{\n mProgress->setProgress( progress );\n}\n\nvoid TransactionItem::setStatus( const QString& status )\n{\n setText( 3, status );\n}\n\nvoid TransactionItem::adjustGeometry()\n{\n QRect r = listView()->itemRect( this );\n QHeader *h = listView()->header();\n if ( mCancelButton ) {\n r.setLeft( h->sectionPos( 1 ) - h->offset() );\n r.setWidth( h->sectionSize( 1 ));\n mCancelButton->setGeometry( r );\n }\n r.setLeft( h->sectionPos( 2 ) - h->offset() );\n r.setWidth( h->sectionSize( 2 ));\n mProgress->setGeometry( r );\n}\n\nvoid TransactionItem::slotItemCanceled()\n{\n item()->setStatus( i18n(\"cancelling ... \") );\n item()->cancel();\n}\n\n\n\nProgressDialog::ProgressDialog( QWidget* parent, const char* name, bool modal, WFlags fl )\n : QDialog( parent, name, modal, fl )\n{\n setCaption( i18n(\"Progress\") );\n resize( 600, 400 );\n\n\n QBoxLayout* topLayout = new QVBoxLayout( this, KDialog::marginHint(), KDialog::spacingHint(),\n \"topLayout\");\n\n mListView = new TransactionItemListView( this, \"SyncEditorListView\" );\n mListView->addColumn( i18n( \"Transaction\" ) );\n mListView->setColumnWidth( 0, 100 );\n mListView->setColumnWidthMode(0, QListView::Maximum);\n mListView->addColumn( QString::null );\n mListView->setColumnWidth( 1, 25 );\n mListView->addColumn( i18n( \"Progress\" ) );\n mListView->setColumnWidth( 2, 180 );\n mListView->addColumn( i18n( \"Status\" ) );\n mListView->setColumnWidth( 3, 100 );\n mListView->setColumnWidthMode(3, QListView::Maximum);\n mListView->setSorting( -1, false );\n\n mListView->setRootIsDecorated( true );\n\n topLayout->addWidget( mListView );\n\n QBoxLayout* bottomLayout = new QHBoxLayout( topLayout, KDialog::spacingHint(), \"bottomLayout\");\n bottomLayout->addStretch();\n\n KPushButton* pbClose = new KPushButton( KStdGuiItem::close(), this );\n bottomLayout->addWidget( pbClose );\n\n connect(pbClose, SIGNAL(clicked()), this, SLOT(close()) );\n\n \/*\n * Get the singleton ProgressManager item which will inform us of\n * appearing and vanishing items.\n *\/\n ProgressManager *pm = ProgressManager::instance();\n connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),\n this, SLOT( slotTransactionAdded( ProgressItem* ) ) );\n connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),\n this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );\n connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),\n this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );\n connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),\n this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );\n}\n\nvoid ProgressDialog::clear()\n{\n QListViewItem* item;\n while( ( item = mListView->firstChild() ) != 0 ) delete item;\n mPreviousItem = 0;\n}\n\n\nvoid ProgressDialog::closeEvent( QCloseEvent* e )\n{\n e->accept();\n hide();\n}\n\n\nvoid ProgressDialog::showEvent( QShowEvent* e )\n{\n mListView->slotAdjustGeometry();\n QDialog::showEvent( e );\n}\n\n\n\/*\n * Destructor\n *\/\nProgressDialog::~ProgressDialog()\n{\n \/\/ no need to delete child widgets.\n}\n\nvoid ProgressDialog::slotTransactionAdded( ProgressItem *item )\n{\n TransactionItem *parent = 0;\n TransactionItem *ti = 0;\n if ( item->parent() ) {\n parent = mTransactionsToListviewItems[ item->parent() ];\n ti = new TransactionItem( parent, item );\n } else {\n ti = new TransactionItem( mListView, mListView->lastItem(), item );\n }\n mTransactionsToListviewItems.replace( item, ti );\n \/\/ First item to appear, show.\n \/\/ FIXME Maybe it's better to only auto show if the dialog was timed out\n \/\/ and not closed by the user. dunno\n \/\/ if ( mTransactionsToListviewItems.size() == 1 ) show();\n}\n\nvoid ProgressDialog::slotTransactionCompleted( ProgressItem *item )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n mTransactionsToListviewItems.remove( item );\n delete ti;\n }\n \/\/ This was the last item, hide.\n if ( mTransactionsToListviewItems.size() == 0 )\n QTimer::singleShot( 3000, this, SLOT( slotHide() ) );\n}\n\nvoid ProgressDialog::slotTransactionCanceled( ProgressItem * )\n{\n}\n\nvoid ProgressDialog::slotTransactionProgress( ProgressItem *item,\n unsigned int progress )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n ti->setProgress( progress );\n }\n}\n\nvoid ProgressDialog::slotTransactionStatus( ProgressItem *item,\n const QString& status )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n ti->setStatus( status );\n }\n}\n\n\nvoid ProgressDialog::slotHide()\n{\n \/\/ check if a new item showed up since we started the timer. If not, hide\n if ( mTransactionsToListviewItems.size() == 0 )\n hide();\n}\n\n}\n#include \"progressdialog.moc\"\n<commit_msg>Update the listview geometry when an item goes away.<commit_after>\/** -*- c++ -*-\n * progressdialog.cpp\n *\n * Copyright (c) 2004 Till Adam <adam@kde.org>\n * based on imapprogressdialog.cpp ,which is\n * Copyright (c) 2002-2003 Klaralvdalens Datakonsult AB\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qlayout.h>\n#include <qprogressbar.h>\n#include <qtimer.h>\n#include <qheader.h>\n#include <qobject.h>\n\n#include <kpushbutton.h>\n#include <klocale.h>\n#include <kdialog.h>\n#include <kstdguiitem.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"progressdialog.h\"\n#include \"progressmanager.h\"\nusing KMail::ProgressItem;\nusing KMail::ProgressManager;\n\nnamespace KMail {\n\nTransactionItemListView::TransactionItemListView( QWidget * parent,\n const char * name,\n WFlags f )\n : QListView( parent, name, f ) {\n\n connect ( header(),SIGNAL( sizeChange ( int, int, int ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( header(),SIGNAL( indexChange ( int, int, int ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( this, SIGNAL( expanded( QListViewItem * ) ),\n this, SLOT( slotAdjustGeometry() ) );\n connect ( this, SIGNAL( collapsed( QListViewItem * ) ),\n this, SLOT( slotAdjustGeometry() ) );\n\n}\n\nvoid TransactionItemListView::resizeEvent( QResizeEvent* e )\n{\n slotAdjustGeometry();\n QListView::resizeEvent( e );\n}\n\nvoid TransactionItemListView::slotAdjustGeometry() {\n for (QListViewItemIterator it( this ); it.current(); it++) {\n TransactionItem *i = static_cast<TransactionItem*>( it.current() );\n i->adjustGeometry();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nTransactionItem::TransactionItem ( QListViewItem* parent,\n ProgressItem *i )\n : QListViewItem( parent ), mCancelButton( 0 )\n{\n init( i);\n}\n\nTransactionItem::TransactionItem( QListView* parent,\n QListViewItem* lastItem,\n ProgressItem *i )\n : QListViewItem( parent, lastItem ), mCancelButton( 0 )\n{\n init( i );\n}\n\nvoid TransactionItem::init ( ProgressItem *item )\n{\n mItem = item;\n mProgress = new QProgressBar( 100, listView()->viewport() );\n mProgress->setProgress( item->progress() );\n mProgress->show();\n if ( item->canBeCanceled() ) {\n mCancelButton = new QPushButton( SmallIcon( \"cancel\" ), QString::null,\n listView()->viewport() );\n mCancelButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,\n QSizePolicy::Minimum ) );\n\n mCancelButton->show();\n connect ( mCancelButton, SIGNAL( clicked() ),\n this, SLOT( slotItemCanceled() ));\n\n }\n adjustGeometry();\n setText( 0, item->label() );\n setText( 4, item->status() );\n setSelectable( false );\n}\n\nTransactionItem::~TransactionItem()\n{\n delete mCancelButton;\n delete mProgress;\n}\n\nvoid TransactionItem::setProgress( int progress )\n{\n mProgress->setProgress( progress );\n}\n\nvoid TransactionItem::setStatus( const QString& status )\n{\n setText( 3, status );\n}\n\nvoid TransactionItem::adjustGeometry()\n{\n QRect r = listView()->itemRect( this );\n QHeader *h = listView()->header();\n if ( mCancelButton ) {\n r.setLeft( h->sectionPos( 1 ) - h->offset() );\n r.setWidth( h->sectionSize( 1 ));\n mCancelButton->setGeometry( r );\n }\n r.setLeft( h->sectionPos( 2 ) - h->offset() );\n r.setWidth( h->sectionSize( 2 ));\n mProgress->setGeometry( r );\n}\n\nvoid TransactionItem::slotItemCanceled()\n{\n item()->setStatus( i18n(\"cancelling ... \") );\n item()->cancel();\n}\n\n\n\nProgressDialog::ProgressDialog( QWidget* parent, const char* name, bool modal, WFlags fl )\n : QDialog( parent, name, modal, fl )\n{\n setCaption( i18n(\"Progress\") );\n resize( 600, 400 );\n\n\n QBoxLayout* topLayout = new QVBoxLayout( this, KDialog::marginHint(), KDialog::spacingHint(),\n \"topLayout\");\n\n mListView = new TransactionItemListView( this, \"SyncEditorListView\" );\n mListView->addColumn( i18n( \"Transaction\" ) );\n mListView->setColumnWidth( 0, 100 );\n mListView->setColumnWidthMode(0, QListView::Maximum);\n mListView->addColumn( QString::null );\n mListView->setColumnWidth( 1, 25 );\n mListView->addColumn( i18n( \"Progress\" ) );\n mListView->setColumnWidth( 2, 180 );\n mListView->addColumn( i18n( \"Status\" ) );\n mListView->setColumnWidth( 3, 100 );\n mListView->setColumnWidthMode(3, QListView::Maximum);\n mListView->setSorting( -1, false );\n\n mListView->setRootIsDecorated( true );\n\n topLayout->addWidget( mListView );\n\n QBoxLayout* bottomLayout = new QHBoxLayout( topLayout, KDialog::spacingHint(), \"bottomLayout\");\n bottomLayout->addStretch();\n\n KPushButton* pbClose = new KPushButton( KStdGuiItem::close(), this );\n bottomLayout->addWidget( pbClose );\n\n connect(pbClose, SIGNAL(clicked()), this, SLOT(close()) );\n\n \/*\n * Get the singleton ProgressManager item which will inform us of\n * appearing and vanishing items.\n *\/\n ProgressManager *pm = ProgressManager::instance();\n connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),\n this, SLOT( slotTransactionAdded( ProgressItem* ) ) );\n connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),\n this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );\n connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),\n this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );\n connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),\n this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );\n}\n\nvoid ProgressDialog::clear()\n{\n QListViewItem* item;\n while( ( item = mListView->firstChild() ) != 0 ) delete item;\n mPreviousItem = 0;\n}\n\n\nvoid ProgressDialog::closeEvent( QCloseEvent* e )\n{\n e->accept();\n hide();\n}\n\n\nvoid ProgressDialog::showEvent( QShowEvent* e )\n{\n mListView->slotAdjustGeometry();\n QDialog::showEvent( e );\n}\n\n\n\/*\n * Destructor\n *\/\nProgressDialog::~ProgressDialog()\n{\n \/\/ no need to delete child widgets.\n}\n\nvoid ProgressDialog::slotTransactionAdded( ProgressItem *item )\n{\n TransactionItem *parent = 0;\n TransactionItem *ti = 0;\n if ( item->parent() ) {\n parent = mTransactionsToListviewItems[ item->parent() ];\n ti = new TransactionItem( parent, item );\n } else {\n ti = new TransactionItem( mListView, mListView->lastItem(), item );\n }\n mTransactionsToListviewItems.replace( item, ti );\n \/\/ First item to appear, show.\n \/\/ FIXME Maybe it's better to only auto show if the dialog was timed out\n \/\/ and not closed by the user. dunno\n \/\/ if ( mTransactionsToListviewItems.size() == 1 ) show();\n}\n\nvoid ProgressDialog::slotTransactionCompleted( ProgressItem *item )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n mTransactionsToListviewItems.remove( item );\n delete ti;\n }\n mListView->slotAdjustGeometry();\n \/\/ This was the last item, hide.\n if ( mTransactionsToListviewItems.size() == 0 )\n QTimer::singleShot( 3000, this, SLOT( slotHide() ) );\n}\n\nvoid ProgressDialog::slotTransactionCanceled( ProgressItem * )\n{\n}\n\nvoid ProgressDialog::slotTransactionProgress( ProgressItem *item,\n unsigned int progress )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n ti->setProgress( progress );\n }\n}\n\nvoid ProgressDialog::slotTransactionStatus( ProgressItem *item,\n const QString& status )\n{\n TransactionItem *ti = mTransactionsToListviewItems[ item ];\n if ( ti ) {\n ti->setStatus( status );\n }\n}\n\n\nvoid ProgressDialog::slotHide()\n{\n \/\/ check if a new item showed up since we started the timer. If not, hide\n if ( mTransactionsToListviewItems.size() == 0 )\n hide();\n}\n\n}\n#include \"progressdialog.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2012 ARM Limited\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"Thread.h\"\n\n#include \"mbed_error.h\"\n#include \"rtos_idle.h\"\n\n\/\/ rt_tid2ptcb is an internal function which we exposed to get TCB for thread id\n#undef NULL \/\/Workaround for conflicting macros in rt_TypeDef.h and stdio.h\n#include \"rt_TypeDef.h\"\n\nextern \"C\" P_TCB rt_tid2ptcb(osThreadId thread_id);\n\nnamespace rtos {\n\nThread::Thread(osPriority priority,\n uint32_t stack_size, unsigned char *stack_pointer):\n _tid(NULL), _dynamic_stack(stack_pointer == NULL) {\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.tpriority = priority;\n _thread_def.stacksize = stack_size;\n _thread_def.stack_pointer = (uint32_t*)stack_pointer;\n#endif\n}\n\nThread::Thread(void (*task)(void const *argument), void *argument,\n osPriority priority, uint32_t stack_size, unsigned char *stack_pointer):\n _tid(NULL), _dynamic_stack(stack_pointer == NULL) {\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.tpriority = priority;\n _thread_def.stacksize = stack_size;\n _thread_def.stack_pointer = (uint32_t*)stack_pointer;\n#endif\n switch (start(task, argument)) {\n case osErrorResource:\n error(\"OS ran out of threads!\\n\");\n break;\n case osErrorParameter:\n error(\"Thread already running!\\n\");\n break;\n case osErrorNoMemory:\n error(\"Error allocating the stack memory\\n\");\n default:\n break;\n }\n}\n\nosStatus Thread::start(void (*task)(void const *argument), void *argument) {\n if (_tid != NULL) {\n return osErrorParameter;\n }\n\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.pthread = task;\n if (_thread_def.stack_pointer == NULL) {\n _thread_def.stack_pointer = new uint32_t[_thread_def.stacksize\/sizeof(uint32_t)];\n if (_thread_def.stack_pointer == NULL)\n return osErrorNoMemory;\n }\n\n \/\/Fill the stack with a magic word for maximum usage checking\n for (uint32_t i = 0; i < (_thread_def.stacksize \/ sizeof(uint32_t)); i++) {\n _thread_def.stack_pointer[i] = 0xE25A2EA5;\n }\n#endif\n _tid = osThreadCreate(&_thread_def, argument);\n if (_tid == NULL) {\n if (_dynamic_stack) delete[] (_thread_def.stack_pointer);\n return osErrorResource;\n }\n return osOK;\n}\n\nosStatus Thread::terminate() {\n return osThreadTerminate(_tid);\n}\n\nosStatus Thread::join() {\n while (true) {\n uint8_t state = get_state();\n if (state == Thread::Inactive || state == osErrorParameter) {\n return osOK;\n }\n\n osStatus status = yield();\n if (status != osOK) {\n return status;\n }\n }\n}\n\nosStatus Thread::set_priority(osPriority priority) {\n return osThreadSetPriority(_tid, priority);\n}\n\nosPriority Thread::get_priority() {\n return osThreadGetPriority(_tid);\n}\n\nint32_t Thread::signal_set(int32_t signals) {\n return osSignalSet(_tid, signals);\n}\n\nint32_t Thread::signal_clr(int32_t signals) {\n return osSignalClear(_tid, signals);\n}\n\nThread::State Thread::get_state() {\n#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM)\n#ifdef CMSIS_OS_RTX\n return ((State)_thread_def.tcb.state);\n#endif\n#else\n uint8_t status;\n status = osThreadGetState(_tid);\n return ((State)status);\n#endif\n}\n\nuint32_t Thread::stack_size() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n return _thread_def.tcb.priv_stack;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n return tcb->priv_stack;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::free_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t bottom = (uint32_t)_thread_def.tcb.stack;\n return _thread_def.tcb.tsk_stack - bottom;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t bottom = (uint32_t)tcb->stack;\n return tcb->tsk_stack - bottom;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::used_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;\n return top - _thread_def.tcb.tsk_stack;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack;\n return top - tcb->tsk_stack;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::max_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t high_mark = 0;\n while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)\n high_mark++;\n return _thread_def.tcb.priv_stack - (high_mark * 4);\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t high_mark = 0;\n while (tcb->stack[high_mark] == 0xE25A2EA5)\n high_mark++;\n return tcb->priv_stack - (high_mark * 4);\n#endif\n#else\n return 0;\n#endif\n}\n\nosEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {\n return osSignalWait(signals, millisec);\n}\n\nosStatus Thread::wait(uint32_t millisec) {\n return osDelay(millisec);\n}\n\nosStatus Thread::yield() {\n return osThreadYield();\n}\n\nosThreadId Thread::gettid() {\n return osThreadGetId();\n}\n\nvoid Thread::attach_idle_hook(void (*fptr)(void)) {\n rtos_attach_idle_hook(fptr);\n}\n\nThread::~Thread() {\n terminate();\n#ifdef __MBED_CMSIS_RTOS_CM\n if (_dynamic_stack) {\n delete[] (_thread_def.stack_pointer);\n }\n#endif\n}\n\n}\n<commit_msg>Fixed NULL usage on non-pointer member in thread<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2012 ARM Limited\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"Thread.h\"\n\n#include \"mbed_error.h\"\n#include \"rtos_idle.h\"\n\n\/\/ rt_tid2ptcb is an internal function which we exposed to get TCB for thread id\n#undef NULL \/\/Workaround for conflicting macros in rt_TypeDef.h and stdio.h\n#include \"rt_TypeDef.h\"\n\nextern \"C\" P_TCB rt_tid2ptcb(osThreadId thread_id);\n\nnamespace rtos {\n\nThread::Thread(osPriority priority,\n uint32_t stack_size, unsigned char *stack_pointer):\n _tid(0), _dynamic_stack(stack_pointer == NULL) {\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.tpriority = priority;\n _thread_def.stacksize = stack_size;\n _thread_def.stack_pointer = (uint32_t*)stack_pointer;\n#endif\n}\n\nThread::Thread(void (*task)(void const *argument), void *argument,\n osPriority priority, uint32_t stack_size, unsigned char *stack_pointer):\n _tid(0), _dynamic_stack(stack_pointer == NULL) {\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.tpriority = priority;\n _thread_def.stacksize = stack_size;\n _thread_def.stack_pointer = (uint32_t*)stack_pointer;\n#endif\n switch (start(task, argument)) {\n case osErrorResource:\n error(\"OS ran out of threads!\\n\");\n break;\n case osErrorParameter:\n error(\"Thread already running!\\n\");\n break;\n case osErrorNoMemory:\n error(\"Error allocating the stack memory\\n\");\n default:\n break;\n }\n}\n\nosStatus Thread::start(void (*task)(void const *argument), void *argument) {\n if (_tid != NULL) {\n return osErrorParameter;\n }\n\n#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)\n _thread_def.pthread = task;\n if (_thread_def.stack_pointer == NULL) {\n _thread_def.stack_pointer = new uint32_t[_thread_def.stacksize\/sizeof(uint32_t)];\n if (_thread_def.stack_pointer == NULL)\n return osErrorNoMemory;\n }\n\n \/\/Fill the stack with a magic word for maximum usage checking\n for (uint32_t i = 0; i < (_thread_def.stacksize \/ sizeof(uint32_t)); i++) {\n _thread_def.stack_pointer[i] = 0xE25A2EA5;\n }\n#endif\n _tid = osThreadCreate(&_thread_def, argument);\n if (_tid == NULL) {\n if (_dynamic_stack) delete[] (_thread_def.stack_pointer);\n return osErrorResource;\n }\n return osOK;\n}\n\nosStatus Thread::terminate() {\n return osThreadTerminate(_tid);\n}\n\nosStatus Thread::join() {\n while (true) {\n uint8_t state = get_state();\n if (state == Thread::Inactive || state == osErrorParameter) {\n return osOK;\n }\n\n osStatus status = yield();\n if (status != osOK) {\n return status;\n }\n }\n}\n\nosStatus Thread::set_priority(osPriority priority) {\n return osThreadSetPriority(_tid, priority);\n}\n\nosPriority Thread::get_priority() {\n return osThreadGetPriority(_tid);\n}\n\nint32_t Thread::signal_set(int32_t signals) {\n return osSignalSet(_tid, signals);\n}\n\nint32_t Thread::signal_clr(int32_t signals) {\n return osSignalClear(_tid, signals);\n}\n\nThread::State Thread::get_state() {\n#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM)\n#ifdef CMSIS_OS_RTX\n return ((State)_thread_def.tcb.state);\n#endif\n#else\n uint8_t status;\n status = osThreadGetState(_tid);\n return ((State)status);\n#endif\n}\n\nuint32_t Thread::stack_size() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n return _thread_def.tcb.priv_stack;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n return tcb->priv_stack;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::free_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t bottom = (uint32_t)_thread_def.tcb.stack;\n return _thread_def.tcb.tsk_stack - bottom;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t bottom = (uint32_t)tcb->stack;\n return tcb->tsk_stack - bottom;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::used_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;\n return top - _thread_def.tcb.tsk_stack;\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack;\n return top - tcb->tsk_stack;\n#endif\n#else\n return 0;\n#endif\n}\n\nuint32_t Thread::max_stack() {\n#ifndef __MBED_CMSIS_RTOS_CA9\n#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)\n uint32_t high_mark = 0;\n while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)\n high_mark++;\n return _thread_def.tcb.priv_stack - (high_mark * 4);\n#else\n P_TCB tcb = rt_tid2ptcb(_tid);\n uint32_t high_mark = 0;\n while (tcb->stack[high_mark] == 0xE25A2EA5)\n high_mark++;\n return tcb->priv_stack - (high_mark * 4);\n#endif\n#else\n return 0;\n#endif\n}\n\nosEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {\n return osSignalWait(signals, millisec);\n}\n\nosStatus Thread::wait(uint32_t millisec) {\n return osDelay(millisec);\n}\n\nosStatus Thread::yield() {\n return osThreadYield();\n}\n\nosThreadId Thread::gettid() {\n return osThreadGetId();\n}\n\nvoid Thread::attach_idle_hook(void (*fptr)(void)) {\n rtos_attach_idle_hook(fptr);\n}\n\nThread::~Thread() {\n terminate();\n#ifdef __MBED_CMSIS_RTOS_CM\n if (_dynamic_stack) {\n delete[] (_thread_def.stack_pointer);\n }\n#endif\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Final.<commit_after><|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n * Copyright (C) 2011 Andreas Kling <awesomekling@gmail.com> *\n * Copyright (C) 2011 Instituto Nokia de Tecnologia (INdT) *\n * *\n * This file may be used under the terms of the GNU Lesser *\n * General Public License version 2.1 as published by the Free Software *\n * Foundation and appearing in the file LICENSE.LGPL included in the *\n * packaging of this file. Please review the following information to *\n * ensure the GNU Lesser General Public License version 2.1 requirements *\n * will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Lesser General Public License for more details. *\n ****************************************************************************\/\n\n#include \"MainView.h\"\n\n#include \"BrowserWindow.h\"\n#include \"DeclarativeDesktopWebView.h\"\n#include \"TripleClickMonitor.h\"\n\n#include <QtDeclarative\/QDeclarativeEngine>\n#include <QtDeclarative\/QDeclarativeItem>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QToolBar>\n#include <QtGui\/QVBoxLayout>\n\n#include <QUrl>\n\n\/\/ Keeping this feature commented out until we have support for it in the new API.\n\/\/QWKPage* newPageCallback(QWKPage* parentPage)\n\/\/{\n\/\/ BrowserWindow* window = BrowserWindow::create(parentPage->context());\n\/\/ PageWidget* page = window->openNewTab();\n\/\/ window->show();\n\/\/ return page->page();\n\/\/}\n\nMainView::MainView(QWidget* parent)\n : QDeclarativeView(parent)\n , m_tabWidget(0)\n{\n setResizeMode(QDeclarativeView::SizeRootObjectToView);\n setSource(QUrl(\"qrc:\/qml\/main.qml\"));\n\n connect(engine(), SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));\n\n m_tabWidget = qobject_cast<QDeclarativeItem*>(rootObject());\n Q_ASSERT(m_tabWidget);\n\n connect(m_tabWidget, SIGNAL(tabAdded(QVariant)), this, SLOT(onTabAdded(QVariant)));\n connect(m_tabWidget, SIGNAL(currentTabChanged()), this, SLOT(onCurrentTabChanged()));\n\n onTabAdded(m_tabWidget->property(\"currentActiveTab\"));\n\n QAction* focusLocationBarAction = new QAction(this);\n focusLocationBarAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L));\n connect(focusLocationBarAction, SIGNAL(triggered()), this, SLOT(focusUrlBarRequested()));\n addAction(focusLocationBarAction);\n\n QAction* newTabAction = new QAction(this);\n newTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T));\n connect(newTabAction, SIGNAL(triggered()), this, SLOT(newTabRequested()));\n addAction(newTabAction);\n\n QAction* closeTabAction = new QAction(this);\n closeTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_W));\n connect(closeTabAction, SIGNAL(triggered()), this, SLOT(closeTabRequested()));\n addAction(closeTabAction);\n\n\/\/ page()->setCreateNewPageFunction(newPageCallback);\n}\n\nMainView::~MainView()\n{\n}\n\nvoid MainView::openInNewTab(const QString& urlFromUserInput)\n{\n QUrl url = QUrl::fromUserInput(urlFromUserInput);\n if (!url.isEmpty()) {\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n QObject* mainView = currentActiveTab->property(\"mainView\").value<QObject*>();\n QObject* urlEdit = mainView->findChild<QDeclarativeItem*>(\"urlEdit\");\n urlEdit->setProperty(\"text\", url.toString());\n getWebViewForUrlEdit(urlEdit)->setUrl(url);\n }\n}\n\nvoid MainView::jumpToNextTab()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"jumpToNextTab\");\n}\n\nvoid MainView::jumpToPreviousTab()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"jumpToPreviousTab\");\n}\n\nvoid MainView::onTabAdded(QVariant tab)\n{\n QObject* mainView = tab.value<QObject*>()->property(\"mainView\").value<QObject*>();\n QDeclarativeItem* urlEdit = mainView->findChild<QDeclarativeItem*>(\"urlEdit\");\n connect(urlEdit, SIGNAL(urlEntered(QString)), this, SLOT(onUrlChanged(QString)));\n QObject* webView = getWebViewForUrlEdit(urlEdit);\n connect(webView, SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));\n QDeclarativeItem* urlInput = urlEdit->findChild<QDeclarativeItem*>(\"urlInput\");\n TripleClickMonitor* urlEditMonitor = new TripleClickMonitor(mainView);\n urlInput->installEventFilter(urlEditMonitor);\n connect(urlEditMonitor, SIGNAL(tripleClicked()), urlInput, SLOT(selectAll()));\n}\n\nvoid MainView::onCurrentTabChanged()\n{\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n emit titleChanged(currentActiveTab->property(\"text\").toString());\n}\n\nvoid MainView::onTitleChanged(const QString& title)\n{\n emit titleChanged(title);\n}\n\nDeclarativeDesktopWebView* MainView::getWebViewForUrlEdit(QObject* urlEdit)\n{\n QObject* view = urlEdit->property(\"view\").value<QObject*>();\n return qobject_cast<DeclarativeDesktopWebView* >(view);\n}\n\nvoid MainView::onUrlChanged(const QString& url)\n{\n getWebViewForUrlEdit(sender())->setUrl(QUrl::fromUserInput(url));\n}\n\nvoid MainView::newTabRequested()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"addNewTab\");\n}\n\nvoid MainView::closeTabRequested()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"closeTab\", Q_ARG(QVariant, m_tabWidget->property(\"currentActiveTab\")));\n}\n\nvoid MainView::focusUrlBarRequested()\n{\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n QObject* mainView = currentActiveTab->property(\"mainView\").value<QObject*>();\n QMetaObject::invokeMethod(mainView, \"focusUrlBar\");\n}\n<commit_msg>Remove commented code<commit_after>\/****************************************************************************\n * Copyright (C) 2011 Andreas Kling <awesomekling@gmail.com> *\n * Copyright (C) 2011 Instituto Nokia de Tecnologia (INdT) *\n * *\n * This file may be used under the terms of the GNU Lesser *\n * General Public License version 2.1 as published by the Free Software *\n * Foundation and appearing in the file LICENSE.LGPL included in the *\n * packaging of this file. Please review the following information to *\n * ensure the GNU Lesser General Public License version 2.1 requirements *\n * will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Lesser General Public License for more details. *\n ****************************************************************************\/\n\n#include \"MainView.h\"\n\n#include \"BrowserWindow.h\"\n#include \"DeclarativeDesktopWebView.h\"\n#include \"TripleClickMonitor.h\"\n\n#include <QtDeclarative\/QDeclarativeEngine>\n#include <QtDeclarative\/QDeclarativeItem>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QToolBar>\n#include <QtGui\/QVBoxLayout>\n\n#include <QUrl>\n\nMainView::MainView(QWidget* parent)\n : QDeclarativeView(parent)\n , m_tabWidget(0)\n{\n setResizeMode(QDeclarativeView::SizeRootObjectToView);\n setSource(QUrl(\"qrc:\/qml\/main.qml\"));\n\n connect(engine(), SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));\n\n m_tabWidget = qobject_cast<QDeclarativeItem*>(rootObject());\n Q_ASSERT(m_tabWidget);\n\n connect(m_tabWidget, SIGNAL(tabAdded(QVariant)), this, SLOT(onTabAdded(QVariant)));\n connect(m_tabWidget, SIGNAL(currentTabChanged()), this, SLOT(onCurrentTabChanged()));\n\n onTabAdded(m_tabWidget->property(\"currentActiveTab\"));\n\n QAction* focusLocationBarAction = new QAction(this);\n focusLocationBarAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L));\n connect(focusLocationBarAction, SIGNAL(triggered()), this, SLOT(focusUrlBarRequested()));\n addAction(focusLocationBarAction);\n\n QAction* newTabAction = new QAction(this);\n newTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T));\n connect(newTabAction, SIGNAL(triggered()), this, SLOT(newTabRequested()));\n addAction(newTabAction);\n\n QAction* closeTabAction = new QAction(this);\n closeTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_W));\n connect(closeTabAction, SIGNAL(triggered()), this, SLOT(closeTabRequested()));\n addAction(closeTabAction);\n}\n\nMainView::~MainView()\n{\n}\n\nvoid MainView::openInNewTab(const QString& urlFromUserInput)\n{\n QUrl url = QUrl::fromUserInput(urlFromUserInput);\n if (!url.isEmpty()) {\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n QObject* mainView = currentActiveTab->property(\"mainView\").value<QObject*>();\n QObject* urlEdit = mainView->findChild<QDeclarativeItem*>(\"urlEdit\");\n urlEdit->setProperty(\"text\", url.toString());\n getWebViewForUrlEdit(urlEdit)->setUrl(url);\n }\n}\n\nvoid MainView::jumpToNextTab()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"jumpToNextTab\");\n}\n\nvoid MainView::jumpToPreviousTab()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"jumpToPreviousTab\");\n}\n\nvoid MainView::onTabAdded(QVariant tab)\n{\n QObject* mainView = tab.value<QObject*>()->property(\"mainView\").value<QObject*>();\n QDeclarativeItem* urlEdit = mainView->findChild<QDeclarativeItem*>(\"urlEdit\");\n connect(urlEdit, SIGNAL(urlEntered(QString)), this, SLOT(onUrlChanged(QString)));\n QObject* webView = getWebViewForUrlEdit(urlEdit);\n connect(webView, SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));\n QDeclarativeItem* urlInput = urlEdit->findChild<QDeclarativeItem*>(\"urlInput\");\n TripleClickMonitor* urlEditMonitor = new TripleClickMonitor(mainView);\n urlInput->installEventFilter(urlEditMonitor);\n connect(urlEditMonitor, SIGNAL(tripleClicked()), urlInput, SLOT(selectAll()));\n}\n\nvoid MainView::onCurrentTabChanged()\n{\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n emit titleChanged(currentActiveTab->property(\"text\").toString());\n}\n\nvoid MainView::onTitleChanged(const QString& title)\n{\n emit titleChanged(title);\n}\n\nDeclarativeDesktopWebView* MainView::getWebViewForUrlEdit(QObject* urlEdit)\n{\n QObject* view = urlEdit->property(\"view\").value<QObject*>();\n return qobject_cast<DeclarativeDesktopWebView* >(view);\n}\n\nvoid MainView::onUrlChanged(const QString& url)\n{\n getWebViewForUrlEdit(sender())->setUrl(QUrl::fromUserInput(url));\n}\n\nvoid MainView::newTabRequested()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"addNewTab\");\n}\n\nvoid MainView::closeTabRequested()\n{\n QMetaObject::invokeMethod(m_tabWidget, \"closeTab\", Q_ARG(QVariant, m_tabWidget->property(\"currentActiveTab\")));\n}\n\nvoid MainView::focusUrlBarRequested()\n{\n QObject* currentActiveTab = m_tabWidget->property(\"currentActiveTab\").value<QObject*>();\n QObject* mainView = currentActiveTab->property(\"mainView\").value<QObject*>();\n QMetaObject::invokeMethod(mainView, \"focusUrlBar\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Neohuman.h\"\n#include <iostream>\n\n#include \"BWEM\/bwem.h\"\n\nusing namespace BWAPI;\nusing namespace Filter;\n\nusing namespace BWEM;\nusing namespace BWEM::BWAPI_ext;\nusing namespace BWEM::utils;\n\n#define MIN(a, b) (((a) < (b) ? (a) : (b)))\n#define MAX(a, b) (((a) < (b) ? (b) : (a)))\n\n#define SATRUATION_RADIUS 350\n#define WORKERAGGRORADIUS 200\n\n#define SHOWTHINGS\n\nnamespace { auto & BWEMMap = Map::Instance(); }\n\nbool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {\n\t_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});\n}\n\nstd::pair <int, int> Neohuman::getQueuedResources() {\n\tstd::pair <int, int> resources;\n\tfor (auto &o : _buildingQueue)\n\t\tresources.first += o.second.mineralPrice(),\n\t\tresources.second += o.second.gasPrice();\n\treturn resources;\n}\n\nstd::pair <int, int> Neohuman::getSpendableResources() const {\n\tstd::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };\n\tauto queued = this->getQueuedResources();\n\tresult.first -= queued.first, result.second -= queued.second;\n\treturn result;\n}\n\nvoid Neohuman::onStart() {\n\tBroodwar << \"The map is totally not \" << Broodwar->mapName() << \"!\" << std::endl;\n\n\t\/\/Broodwar->enableFlag(Flag::UserInput);\n\n\t\/\/ Uncomment the following line and the bot will know about everything through the fog of war (cheat).\n\t\/\/Broodwar->enableFlag(Flag::CompleteMapInformation);\n\n\t\/\/ Set the command optimization level so that common commands can be grouped\n\t\/\/ and reduce the bot's APM (Actions Per Minute).\n\tBroodwar->setCommandOptimizationLevel(2);\n\n\t\/\/ Check if this is a replay\n\tif (!Broodwar->isReplay()) {\n\t\tif (Broodwar->enemy())\n\t\t\tBroodwar << \"The matchup is me (\" << Broodwar->self()->getRace() << \") vs \" << Broodwar->enemy()->getRace() << std::endl;\n\t}\n\n\tBWEMMap.Initialize();\n\tBWEMMap.EnableAutomaticPathAnalysis();\n\n}\n\nvoid Neohuman::onEnd(bool didWin) {\n\t\/\/ Called when the game ends\n\tif (didWin) {\n\n\t} else {\n\n\t}\n}\n\nint Neohuman::randint(int min, int max) {\n\tstd::uniform_int_distribution<int> dist(min, max);\n\treturn dist(_rand);\n}\n\ntemplate <typename T>\nT Neohuman::randele(std::vector <T> &v) {\n\treturn v[randint(0, v.size())];\n}\n\nvoid Neohuman::onFrame() {\n\t\/\/ Called once every game frame\n\tint constructingLine = 0;\n\tint availableMinerals = Broodwar->self()->minerals();\n\n#ifdef SHOWTHINGS\n\n\t\/\/ Display the game frame rate as text in the upper left area of the screen\n\tBroodwar->drawTextScreen(200, 0, \"FPS: %d\", Broodwar->getFPS());\n\tBroodwar->drawTextScreen(200, 12, \"Average FPS: %f\", Broodwar->getAverageFPS());\n\tBroodwar->drawTextScreen(200, 24, \"I want %d more supply (%d queued, %d in production)\", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);\n\tBroodwar->drawTextScreen(200, 36, \"I have %d barracks!\", _nBarracks);\n\n#endif\n\n\ttry {\n\t\t\/\/BWEM::utils::gridMapExample(BWEMMap);\n\t\t\/\/BWEM::utils::drawMap(BWEMMap);\n\t} catch (const std::exception & e) {\n\t\tBroodwar << \"EXCEPTION: \" << e.what() << std::endl;\n\t}\n\n\t\/\/ Return if the game is a replay or is paused\n\tif (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())\n\t\treturn;\n\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->exists() && u->isBeingConstructed()) {\n\t\t\tBroodwar->drawTextScreen(0, constructingLine, \"%s\", u->getType().c_str());\n\t\t\tconstructingLine += 12;\n\t\t}\n\t}\n\n#ifdef SHOWTHINGS\n\n\t\/\/ Show worker info\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->getType().isResourceDepot()) {\n\t\t\tBroodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);\n\t\t\tauto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));\n\t\t\tauto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));\n\t\t\tauto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);\n\t\t\tauto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));\n\t\t\tBroodwar->drawTextMap(u->getPosition() + Position(0, 30), \"%cWorkers: %d\/%d\", Text::White, workers.size(), 2*mineralFields.size());\n\t\t}\n\t}\n\n#endif\n\n\t\/\/ Prevent spamming by only running our onFrame once every number of latency frames.\n\t\/\/ Latency frames are the number of frames before commands are processed.\n\tif (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)\n\t\treturn;\n\t\n\t_supplyBeingMade = 0;\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())\n\t\t\t_supplyBeingMade += 8;\n\t}\n\n\tavailableMinerals -= 100*_queuedSupply\/8;\n\n\tif (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {\n\t\t_queuedSupply = 0;\n\t\t_timeLastQueuedSupply = Broodwar->elapsedTime();\n\t}\n\n\t_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) \/ 8, 0);\n\t_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) \/ 2 + _nSupplyOverhead;\n\n\t_nBarracks = 0;\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\/\/ If a cc is under construction\n\t\tif (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)\n\t\t\tavailableMinerals += 400;\n\t\t\/\/ If a barracks is under construction\n\t\tif (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)\n\t\t\tavailableMinerals += 150;\n\n\t\tif (u->getType() == UnitTypes::Terran_Barracks) {\n\t\t\t++_nBarracks;\n\t\t}\n\t}\n\n\tif (_isExpanding) {\n\t\tavailableMinerals -= 400;\n\t}\n\n\tif (_isBuildingBarracks) {\n\t\tavailableMinerals -= 150;\n\t}\n\n\tint nWorkers = 0;\n\tfor (auto &u : Broodwar->getAllUnits()) {\n\t\tif (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {\n\t\t\t++nWorkers;\n\t\t}\n\t}\n\n\t\/\/ Check if supply should be increased\n\tif (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {\n\t\t\/\/ Find unit to build our supply!\n\t\tfor (auto &unit : Broodwar->self()->getUnits()) {\n\t\t\tif (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {\n\t\t\t\t\/\/ We have found our candidate!\n\t\t\t\tauto supplyType = unit->getType().getRace().getSupplyProvider();\n\t\t\t\tauto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());\n\n\t\t\t\tif (unit->build(supplyType, buildPos)) {\n\t\t\t\t\t_queuedSupply += 8;\n\t\t\t\t\t_timeLastQueuedSupply = Broodwar->elapsedTime();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {\n\t\t\/\/ Build barracks!\n\t\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\tif (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {\n\t\t\t\tauto buildingType = UnitTypes::Terran_Barracks;\n\t\t\t\tauto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());\n\n\t\t\t\tif (u->build(buildingType, buildingPos)) {\n\t\t\t\t\t_isBuildingBarracks = true;\n\t\t\t\t\tavailableMinerals -= 150;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*if (!_isExpanding && availableMinerals >= 400){\n\t\t\/\/ Expand!\n\t\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\tif (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {\n\t\t\t\t\/\/ Builder found!\n\t\t\t\tauto buildingType = u->getType().getRace().getCenter();\n\t\t\t\tauto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());\n\n\t\t\t\tif (u->build(buildingType, buildPos)) {\n\t\t\t\t\t_isExpanding = true;\n\t\t\t\t\tavailableMinerals -= 400;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}*\/\n\n\t\/\/ Iterate through all the units that we own\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\/\/ Ignore the unit if it no longer exists\n\t\t\/\/ Make sure to include this block when handling any Unit pointer!\n\t\tif (!u->exists())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it has one of the following status ailments\n\t\tif (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it is in one of the following states\n\t\tif (u->isLoaded() || !u->isPowered() || u->isStuck())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it is incomplete or busy constructing\n\t\tif (!u->isCompleted() || u->isConstructing())\n\t\t\tcontinue;\n\n\t\t\/\/ If the unit is a worker unit\n\t\tif (u->getType().isWorker()) {\n\t\t\tauto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);\n\t\t\tif (enemyUnit)\n\t\t\t\tu->attack(enemyUnit);\n\n\t\t\t\/\/ if our worker is idle\n\t\t\tif (u->isIdle()) {\n\t\t\t\t\/\/ Order workers carrying a resource to return them to the center,\n\t\t\t\t\/\/ otherwise find a mineral patch to harvest.\n\t\t\t\tif (u->isCarryingGas() || u->isCarryingMinerals())\n\t\t\t\t\tu->returnCargo();\n\n\t\t\t\telse if (!u->getPowerUp()) {\n\t\t\t\t\t\/\/ Probably need to set up some better logic for this\n\t\t\t\t\tauto preferredMiningLocation = u->getClosestUnit(IsMineralField);\n\t\t\t\t\tu->gather(preferredMiningLocation);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (u->getType().isResourceDepot()) {\n\t\t\tauto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));\n\t\t\tif (u->isIdle()) {\n\t\t\t\tauto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));\n\t\t\t\tif (nWorkers >= 70)\n\t\t\t\t\tcontinue;\n\t\t\t\tauto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));\n\t\t\t\tif (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {\n\t\t\t\t\tif (u->train(u->getType().getRace().getWorker())) {\n\t\t\t\t\t\tPosition pos = u->getPosition();\n\t\t\t\t\t\tError lastErr = Broodwar->getLastError();\n\t\t\t\t\t\tBroodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), \"%c%s\", Text::Red, lastErr.c_str()); }, \/\/ action\n\t\t\t\t\t\t\tnullptr, \/\/ condition\n\t\t\t\t\t\t\tBroodwar->getLatencyFrames()); \/\/ frames to run\n\t\t\t\t\t} else {\n\t\t\t\t\t\tavailableMinerals -= 50;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (u->getType() == UnitTypes::Terran_Barracks) {\n\t\t\tif (u->isIdle() && availableMinerals >= 50)\n\t\t\t\tif (!u->train(UnitTypes::Terran_Marine))\n\t\t\t\t\tavailableMinerals -= 50;\n\t\t} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {\n\t\t\tauto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);\n\t\t\tif (enemyUnit) {\n\t\t\t\tu->attack(enemyUnit->getPosition());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tenemyUnit = u->getClosestUnit(IsEnemy);\n\t\t\tif (enemyUnit) {\n\t\t\t\tu->attack(enemyUnit->getPosition());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);\n\t\t\tif (closestMarine) {\n\t\t\t\tauto walk = u->getPosition() - closestMarine->getPosition();\n\t\t\t\tu->move(u->getPosition() + walk);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Neohuman::onSendText(std::string text) {\n\tBroodwar->sendText(\"%s\", text.c_str());\n}\n\nvoid Neohuman::onReceiveText(Player player, std::string text) {\n\tBroodwar << player->getName() << \" said \\\"\" << text << \"\\\"\" << std::endl;\n}\n\nvoid Neohuman::onPlayerLeft(Player player) {\n\tBroodwar->sendText(\"Goodbye %s!\", player->getName().c_str());\n}\n\nvoid Neohuman::onNukeDetect(Position target) {\n\tif (target) {\n\t\tBroodwar << \"Nuclear Launch Detected at \" << target << std::endl;\n\t} else {\n\t\tBroodwar->sendText(\"Where's the nuke?\");\n\t}\n\t\/\/ You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!\n}\n\nvoid Neohuman::onUnitDiscover(Unit unit) {\n}\n\nvoid Neohuman::onUnitEvade(Unit unit) {\n}\n\nvoid Neohuman::onUnitShow(Unit unit) {\n}\n\nvoid Neohuman::onUnitHide(Unit unit) {\n}\n\nvoid Neohuman::onUnitCreate(Unit unit) {\n}\n\nvoid Neohuman::onUnitDestroy(Unit unit) {\n\ttry {\n\t\tif (unit->getType().isMineralField())\t\t\tBWEMMap.OnMineralDestroyed(unit);\n\t\telse if (unit->getType().isSpecialBuilding())\tBWEMMap.OnStaticBuildingDestroyed(unit);\n\t} catch (const std::exception & e) {\n\t\tBroodwar << \"EXCEPTION: \" << e.what() << std::endl;\n\t}\n}\n\nvoid Neohuman::onUnitMorph(Unit unit) {\n\tthis->onUnitComplete(unit);\n}\n\nvoid Neohuman::onUnitRenegade(Unit unit){\n}\n\nvoid Neohuman::onSaveGame(std::string gameName){\n}\n\nvoid Neohuman::onUnitComplete(Unit unit){\n\tif (unit->getType() == unit->getType().getRace().getCenter())\n\t\t_isExpanding = false;\n\tif (unit->getType() == UnitTypes::Terran_Barracks)\n\t\t_isBuildingBarracks = false;\n}\n<commit_msg>And some more small edits<commit_after>#include \"Neohuman.h\"\n#include <iostream>\n\n#include \"BWEM\/bwem.h\"\n\nusing namespace BWAPI;\nusing namespace Filter;\n\nusing namespace BWEM;\nusing namespace BWEM::BWAPI_ext;\nusing namespace BWEM::utils;\n\n#define MIN(a, b) (((a) < (b) ? (a) : (b)))\n#define MAX(a, b) (((a) < (b) ? (b) : (a)))\n\n#define SATRUATION_RADIUS 350\n#define WORKERAGGRORADIUS 200\n\n#define SHOWTHINGS\n\nnamespace { auto & BWEMMap = Map::Instance(); }\n\nbool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {\n\t_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});\n\treturn Broodwar->canBuildHere(at, building);\n}\n\nstd::pair <int, int> Neohuman::getQueuedResources() const {\n\tstd::pair <int, int> resources;\n\tfor (auto &o : _buildingQueue)\n\t\tresources.first += o.second.mineralPrice(),\n\t\tresources.second += o.second.gasPrice();\n\treturn resources;\n}\n\nstd::pair <int, int> Neohuman::getSpendableResources() const {\n\tstd::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };\n\tauto queued = this->getQueuedResources();\n\tresult.first -= queued.first, result.second -= queued.second;\n\treturn result;\n}\n\nvoid Neohuman::onStart() {\n\tBroodwar << \"The map is totally not \" << Broodwar->mapName() << \"!\" << std::endl;\n\n\t\/\/Broodwar->enableFlag(Flag::UserInput);\n\n\t\/\/ Uncomment the following line and the bot will know about everything through the fog of war (cheat).\n\t\/\/Broodwar->enableFlag(Flag::CompleteMapInformation);\n\n\t\/\/ Set the command optimization level so that common commands can be grouped\n\t\/\/ and reduce the bot's APM (Actions Per Minute).\n\tBroodwar->setCommandOptimizationLevel(2);\n\n\t\/\/ Check if this is a replay\n\tif (!Broodwar->isReplay()) {\n\t\tif (Broodwar->enemy())\n\t\t\tBroodwar << \"The matchup is me (\" << Broodwar->self()->getRace() << \") vs \" << Broodwar->enemy()->getRace() << std::endl;\n\t}\n\n\tBWEMMap.Initialize();\n\tBWEMMap.EnableAutomaticPathAnalysis();\n\n}\n\nvoid Neohuman::onEnd(bool didWin) {\n\t\/\/ Called when the game ends\n\tif (didWin) {\n\n\t} else {\n\n\t}\n}\n\nint Neohuman::randint(int min, int max) {\n\tstd::uniform_int_distribution<int> dist(min, max);\n\treturn dist(_rand);\n}\n\ntemplate <typename T>\nT Neohuman::randele(std::vector <T> &v) {\n\treturn v[randint(0, v.size())];\n}\n\nvoid Neohuman::onFrame() {\n\t\/\/ Called once every game frame\n\tint constructingLine = 0;\n\tint availableMinerals = Broodwar->self()->minerals();\n\n#ifdef SHOWTHINGS\n\n\t\/\/ Display the game frame rate as text in the upper left area of the screen\n\tBroodwar->drawTextScreen(200, 0, \"FPS: %d\", Broodwar->getFPS());\n\tBroodwar->drawTextScreen(200, 12, \"Average FPS: %f\", Broodwar->getAverageFPS());\n\tBroodwar->drawTextScreen(200, 24, \"I want %d more supply (%d queued, %d in production)\", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);\n\tBroodwar->drawTextScreen(200, 36, \"I have %d barracks!\", _nBarracks);\n\n#endif\n\n\ttry {\n\t\t\/\/BWEM::utils::gridMapExample(BWEMMap);\n\t\t\/\/BWEM::utils::drawMap(BWEMMap);\n\t} catch (const std::exception & e) {\n\t\tBroodwar << \"EXCEPTION: \" << e.what() << std::endl;\n\t}\n\n\t\/\/ Return if the game is a replay or is paused\n\tif (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())\n\t\treturn;\n\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->exists() && u->isBeingConstructed()) {\n\t\t\tBroodwar->drawTextScreen(0, constructingLine, \"%s\", u->getType().c_str());\n\t\t\tconstructingLine += 12;\n\t\t}\n\t}\n\n#ifdef SHOWTHINGS\n\n\t\/\/ Show worker info\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->getType().isResourceDepot()) {\n\t\t\tBroodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);\n\t\t\tauto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));\n\t\t\tauto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));\n\t\t\tauto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);\n\t\t\tauto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));\n\t\t\tBroodwar->drawTextMap(u->getPosition() + Position(0, 30), \"%cWorkers: %d\/%d\", Text::White, workers.size(), 2*mineralFields.size());\n\t\t}\n\t}\n\n#endif\n\n\t\/\/ Prevent spamming by only running our onFrame once every number of latency frames.\n\t\/\/ Latency frames are the number of frames before commands are processed.\n\tif (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)\n\t\treturn;\n\t\n\t_supplyBeingMade = 0;\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\tif (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())\n\t\t\t_supplyBeingMade += 8;\n\t}\n\n\tavailableMinerals -= 100*_queuedSupply\/8;\n\n\tif (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {\n\t\t_queuedSupply = 0;\n\t\t_timeLastQueuedSupply = Broodwar->elapsedTime();\n\t}\n\n\t_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) \/ 8, 0);\n\t_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) \/ 2 + _nSupplyOverhead;\n\n\t_nBarracks = 0;\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\/\/ If a cc is under construction\n\t\tif (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)\n\t\t\tavailableMinerals += 400;\n\t\t\/\/ If a barracks is under construction\n\t\tif (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)\n\t\t\tavailableMinerals += 150;\n\n\t\tif (u->getType() == UnitTypes::Terran_Barracks) {\n\t\t\t++_nBarracks;\n\t\t}\n\t}\n\n\tif (_isExpanding) {\n\t\tavailableMinerals -= 400;\n\t}\n\n\tif (_isBuildingBarracks) {\n\t\tavailableMinerals -= 150;\n\t}\n\n\tint nWorkers = 0;\n\tfor (auto &u : Broodwar->getAllUnits()) {\n\t\tif (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {\n\t\t\t++nWorkers;\n\t\t}\n\t}\n\n\t\/\/ Check if supply should be increased\n\tif (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {\n\t\t\/\/ Find unit to build our supply!\n\t\tfor (auto &unit : Broodwar->self()->getUnits()) {\n\t\t\tif (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {\n\t\t\t\t\/\/ We have found our candidate!\n\t\t\t\tauto supplyType = unit->getType().getRace().getSupplyProvider();\n\t\t\t\tauto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());\n\n\t\t\t\tif (unit->build(supplyType, buildPos)) {\n\t\t\t\t\t_queuedSupply += 8;\n\t\t\t\t\t_timeLastQueuedSupply = Broodwar->elapsedTime();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {\n\t\t\/\/ Build barracks!\n\t\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\tif (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {\n\t\t\t\tauto buildingType = UnitTypes::Terran_Barracks;\n\t\t\t\tauto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());\n\n\t\t\t\tif (u->build(buildingType, buildingPos)) {\n\t\t\t\t\t_isBuildingBarracks = true;\n\t\t\t\t\tavailableMinerals -= 150;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*if (!_isExpanding && availableMinerals >= 400){\n\t\t\/\/ Expand!\n\t\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\tif (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {\n\t\t\t\t\/\/ Builder found!\n\t\t\t\tauto buildingType = u->getType().getRace().getCenter();\n\t\t\t\tauto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());\n\n\t\t\t\tif (u->build(buildingType, buildPos)) {\n\t\t\t\t\t_isExpanding = true;\n\t\t\t\t\tavailableMinerals -= 400;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}*\/\n\n\t\/\/ Iterate through all the units that we own\n\tfor (auto &u : Broodwar->self()->getUnits()) {\n\t\t\/\/ Ignore the unit if it no longer exists\n\t\t\/\/ Make sure to include this block when handling any Unit pointer!\n\t\tif (!u->exists())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it has one of the following status ailments\n\t\tif (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it is in one of the following states\n\t\tif (u->isLoaded() || !u->isPowered() || u->isStuck())\n\t\t\tcontinue;\n\n\t\t\/\/ Ignore the unit if it is incomplete or busy constructing\n\t\tif (!u->isCompleted() || u->isConstructing())\n\t\t\tcontinue;\n\n\t\t\/\/ If the unit is a worker unit\n\t\tif (u->getType().isWorker()) {\n\t\t\tauto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);\n\t\t\tif (enemyUnit)\n\t\t\t\tu->attack(enemyUnit);\n\n\t\t\t\/\/ if our worker is idle\n\t\t\tif (u->isIdle()) {\n\t\t\t\t\/\/ Order workers carrying a resource to return them to the center,\n\t\t\t\t\/\/ otherwise find a mineral patch to harvest.\n\t\t\t\tif (u->isCarryingGas() || u->isCarryingMinerals())\n\t\t\t\t\tu->returnCargo();\n\n\t\t\t\telse if (!u->getPowerUp()) {\n\t\t\t\t\t\/\/ Probably need to set up some better logic for this\n\t\t\t\t\tauto preferredMiningLocation = u->getClosestUnit(IsMineralField);\n\t\t\t\t\tu->gather(preferredMiningLocation);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (u->getType().isResourceDepot()) {\n\t\t\tauto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));\n\t\t\tif (u->isIdle()) {\n\t\t\t\tauto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));\n\t\t\t\tif (nWorkers >= 70)\n\t\t\t\t\tcontinue;\n\t\t\t\tauto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));\n\t\t\t\tif (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {\n\t\t\t\t\tif (u->train(u->getType().getRace().getWorker())) {\n\t\t\t\t\t\tPosition pos = u->getPosition();\n\t\t\t\t\t\tError lastErr = Broodwar->getLastError();\n\t\t\t\t\t\tBroodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), \"%c%s\", Text::Red, lastErr.c_str()); }, \/\/ action\n\t\t\t\t\t\t\tnullptr, \/\/ condition\n\t\t\t\t\t\t\tBroodwar->getLatencyFrames()); \/\/ frames to run\n\t\t\t\t\t} else {\n\t\t\t\t\t\tavailableMinerals -= 50;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (u->getType() == UnitTypes::Terran_Barracks) {\n\t\t\tif (u->isIdle() && availableMinerals >= 50)\n\t\t\t\tif (!u->train(UnitTypes::Terran_Marine))\n\t\t\t\t\tavailableMinerals -= 50;\n\t\t} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {\n\t\t\tauto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);\n\t\t\tif (enemyUnit) {\n\t\t\t\tu->attack(enemyUnit->getPosition());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tenemyUnit = u->getClosestUnit(IsEnemy);\n\t\t\tif (enemyUnit) {\n\t\t\t\tu->attack(enemyUnit->getPosition());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tauto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);\n\t\t\tif (closestMarine) {\n\t\t\t\tauto walk = u->getPosition() - closestMarine->getPosition();\n\t\t\t\tu->move(u->getPosition() + walk);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Neohuman::onSendText(std::string text) {\n\tBroodwar->sendText(\"%s\", text.c_str());\n}\n\nvoid Neohuman::onReceiveText(Player player, std::string text) {\n\tBroodwar << player->getName() << \" said \\\"\" << text << \"\\\"\" << std::endl;\n}\n\nvoid Neohuman::onPlayerLeft(Player player) {\n\tBroodwar->sendText(\"Goodbye %s!\", player->getName().c_str());\n}\n\nvoid Neohuman::onNukeDetect(Position target) {\n\tif (target) {\n\t\tBroodwar << \"Nuclear Launch Detected at \" << target << std::endl;\n\t} else {\n\t\tBroodwar->sendText(\"Where's the nuke?\");\n\t}\n\t\/\/ You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!\n}\n\nvoid Neohuman::onUnitDiscover(Unit unit) {\n}\n\nvoid Neohuman::onUnitEvade(Unit unit) {\n}\n\nvoid Neohuman::onUnitShow(Unit unit) {\n}\n\nvoid Neohuman::onUnitHide(Unit unit) {\n}\n\nvoid Neohuman::onUnitCreate(Unit unit) {\n}\n\nvoid Neohuman::onUnitDestroy(Unit unit) {\n\ttry {\n\t\tif (unit->getType().isMineralField())\t\t\tBWEMMap.OnMineralDestroyed(unit);\n\t\telse if (unit->getType().isSpecialBuilding())\tBWEMMap.OnStaticBuildingDestroyed(unit);\n\t} catch (const std::exception & e) {\n\t\tBroodwar << \"EXCEPTION: \" << e.what() << std::endl;\n\t}\n}\n\nvoid Neohuman::onUnitMorph(Unit unit) {\n\tthis->onUnitComplete(unit);\n}\n\nvoid Neohuman::onUnitRenegade(Unit unit){\n}\n\nvoid Neohuman::onSaveGame(std::string gameName){\n}\n\nvoid Neohuman::onUnitComplete(Unit unit){\n\tif (unit->getType() == unit->getType().getRace().getCenter())\n\t\t_isExpanding = false;\n\tif (unit->getType() == UnitTypes::Terran_Barracks)\n\t\t_isBuildingBarracks = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"OrbitCaptureClient\/CaptureClient.h\"\n\n#include \"FunctionUtils.h\"\n#include \"OrbitBase\/Logging.h\"\n\n#include \"absl\/flags\/flag.h\"\n\nABSL_DECLARE_FLAG(uint16_t, sampling_rate);\nABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);\n\nusing orbit_client_protos::FunctionInfo;\n\nvoid CaptureClient::Capture(\n int32_t pid, const std::map<uint64_t, FunctionInfo*>& selected_functions) {\n CHECK(reader_writer_ == nullptr);\n\n event_processor_.emplace(capture_listener_);\n\n grpc::ClientContext context;\n reader_writer_ = capture_service_->Capture(&context);\n\n CaptureRequest request;\n CaptureOptions* capture_options = request.mutable_capture_options();\n capture_options->set_trace_context_switches(true);\n capture_options->set_pid(pid);\n uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);\n if (sampling_rate == 0) {\n capture_options->set_unwinding_method(CaptureOptions::kUndefined);\n } else {\n capture_options->set_sampling_rate(sampling_rate);\n if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {\n capture_options->set_unwinding_method(CaptureOptions::kFramePointers);\n } else {\n capture_options->set_unwinding_method(CaptureOptions::kDwarf);\n }\n }\n capture_options->set_trace_gpu_driver(true);\n for (const auto& pair : selected_functions) {\n const FunctionInfo& function = *pair.second;\n CaptureOptions::InstrumentedFunction* instrumented_function =\n capture_options->add_instrumented_functions();\n instrumented_function->set_file_path(function.loaded_module_path());\n instrumented_function->set_file_offset(FunctionUtils::Offset(function));\n instrumented_function->set_absolute_address(\n FunctionUtils::GetAbsoluteAddress(function));\n }\n\n if (!reader_writer_->Write(request)) {\n ERROR(\"Sending CaptureRequest on Capture's gRPC stream\");\n reader_writer_->WritesDone();\n FinishCapture();\n return;\n }\n LOG(\"Sent CaptureRequest on Capture's gRPC stream: asking to start \"\n \"capturing\");\n\n CaptureResponse response;\n while (reader_writer_->Read(&response)) {\n event_processor_->ProcessEvents(response.capture_events());\n }\n LOG(\"Finished reading from Capture's gRPC stream: all capture data has been \"\n \"received\");\n FinishCapture();\n}\n\nvoid CaptureClient::StopCapture() {\n CHECK(reader_writer_ != nullptr);\n\n if (!reader_writer_->WritesDone()) {\n ERROR(\"Finishing writing on Capture's gRPC stream\");\n FinishCapture();\n }\n LOG(\"Finished writing on Capture's gRPC stream: asking to stop capturing\");\n}\n\nvoid CaptureClient::FinishCapture() {\n if (reader_writer_ == nullptr) {\n return;\n }\n\n grpc::Status status = reader_writer_->Finish();\n if (!status.ok()) {\n ERROR(\"Finishing gRPC call to Capture: %s\", status.error_message());\n }\n reader_writer_.reset();\n event_processor_.reset();\n}<commit_msg>check selected functions for nullptr when start a capture<commit_after>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"OrbitCaptureClient\/CaptureClient.h\"\n\n#include \"FunctionUtils.h\"\n#include \"OrbitBase\/Logging.h\"\n\n#include \"absl\/flags\/flag.h\"\n\nABSL_DECLARE_FLAG(uint16_t, sampling_rate);\nABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);\n\nusing orbit_client_protos::FunctionInfo;\n\nvoid CaptureClient::Capture(\n int32_t pid, const std::map<uint64_t, FunctionInfo*>& selected_functions) {\n CHECK(reader_writer_ == nullptr);\n\n event_processor_.emplace(capture_listener_);\n\n grpc::ClientContext context;\n reader_writer_ = capture_service_->Capture(&context);\n\n CaptureRequest request;\n CaptureOptions* capture_options = request.mutable_capture_options();\n capture_options->set_trace_context_switches(true);\n capture_options->set_pid(pid);\n uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);\n if (sampling_rate == 0) {\n capture_options->set_unwinding_method(CaptureOptions::kUndefined);\n } else {\n capture_options->set_sampling_rate(sampling_rate);\n if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {\n capture_options->set_unwinding_method(CaptureOptions::kFramePointers);\n } else {\n capture_options->set_unwinding_method(CaptureOptions::kDwarf);\n }\n }\n capture_options->set_trace_gpu_driver(true);\n for (const auto& pair : selected_functions) {\n const FunctionInfo* function = pair.second;\n if (function == nullptr) {\n continue;\n }\n CaptureOptions::InstrumentedFunction* instrumented_function =\n capture_options->add_instrumented_functions();\n instrumented_function->set_file_path(function->loaded_module_path());\n instrumented_function->set_file_offset(FunctionUtils::Offset(*function));\n instrumented_function->set_absolute_address(\n FunctionUtils::GetAbsoluteAddress(*function));\n }\n\n if (!reader_writer_->Write(request)) {\n ERROR(\"Sending CaptureRequest on Capture's gRPC stream\");\n reader_writer_->WritesDone();\n FinishCapture();\n return;\n }\n LOG(\"Sent CaptureRequest on Capture's gRPC stream: asking to start \"\n \"capturing\");\n\n CaptureResponse response;\n while (reader_writer_->Read(&response)) {\n event_processor_->ProcessEvents(response.capture_events());\n }\n LOG(\"Finished reading from Capture's gRPC stream: all capture data has been \"\n \"received\");\n FinishCapture();\n}\n\nvoid CaptureClient::StopCapture() {\n CHECK(reader_writer_ != nullptr);\n\n if (!reader_writer_->WritesDone()) {\n ERROR(\"Finishing writing on Capture's gRPC stream\");\n FinishCapture();\n }\n LOG(\"Finished writing on Capture's gRPC stream: asking to stop capturing\");\n}\n\nvoid CaptureClient::FinishCapture() {\n if (reader_writer_ == nullptr) {\n return;\n }\n\n grpc::Status status = reader_writer_->Finish();\n if (!status.ok()) {\n ERROR(\"Finishing gRPC call to Capture: %s\", status.error_message());\n }\n reader_writer_.reset();\n event_processor_.reset();\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting arm_neon.h, which includes\n\/\/ a declaration and definition of each function specified by the ARM NEON \n\/\/ compiler interface. See ARM document DUI0348B.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"NeonEmitter.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include <string>\n\nusing namespace llvm;\n\nvoid NeonEmitter::run(raw_ostream &OS) {\n EmitSourceFileHeader(\"ARM NEON Header\", OS);\n \n \/\/ FIXME: emit license into file?\n \n OS << \"#ifndef __ARM_NEON_H\\n\";\n OS << \"#define __ARM_NEON_H\\n\\n\";\n \n OS << \"#ifndef __ARM_NEON__\\n\";\n OS << \"#error \\\"NEON support not enabled\\\"\\n\";\n OS << \"#endif\\n\\n\";\n\n OS << \"#include <stdint.h>\\n\\n\";\n \n \/\/ EmitTypedefs(OS);\n \n \/\/ Process Records\n \n std::vector<Record*> RV = Records.getAllDerivedDefinitions(\"Inst\");\n \n \/\/ Unique the pattern types, and assign them \n \n \/\/ emit #define directives for uniq'd prototypes\n \n \/\/ emit record directives\n \n for (unsigned i = 0, e = RV.size(); i != e; ++i) {\n Record *R = RV[i];\n \n OS << LowercaseString(R->getName()) << \"\\n\";\n\n std::string Types = R->getValueAsString(\"Types\");\n std::string Pattern = R->getValueAsString(\"Pattern\");\n \n OS << Types << \"\\n\" << Pattern << \"\\n\\n\";\n }\n \n OS << \"#endif \/* __ARM_NEON_H *\/\\n\";\n}\n<commit_msg>Comment out some code in prep for actual .td file checkpoint.<commit_after>\/\/===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting arm_neon.h, which includes\n\/\/ a declaration and definition of each function specified by the ARM NEON \n\/\/ compiler interface. See ARM document DUI0348B.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"NeonEmitter.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include <string>\n\nusing namespace llvm;\n\nvoid NeonEmitter::run(raw_ostream &OS) {\n EmitSourceFileHeader(\"ARM NEON Header\", OS);\n \n \/\/ FIXME: emit license into file?\n \n OS << \"#ifndef __ARM_NEON_H\\n\";\n OS << \"#define __ARM_NEON_H\\n\\n\";\n \n OS << \"#ifndef __ARM_NEON__\\n\";\n OS << \"#error \\\"NEON support not enabled\\\"\\n\";\n OS << \"#endif\\n\\n\";\n\n OS << \"#include <stdint.h>\\n\\n\";\n \n \/\/ EmitTypedefs(OS);\n \n \/\/ Process Records\n \n std::vector<Record*> RV = Records.getAllDerivedDefinitions(\"Inst\");\n \n \/\/ Unique the pattern types, and assign them \n \n \/\/ emit #define directives for uniq'd prototypes\n \n \/\/ emit record directives\n \n for (unsigned i = 0, e = RV.size(); i != e; ++i) {\n Record *R = RV[i];\n \n OS << LowercaseString(R->getName()) << \"\\n\";\n\n std::string Types = R->getValueAsString(\"Types\");\n \/\/std::string Pattern = R->getValueAsString(\"Pattern\");\n \/\/OS << Types << \"\\n\" << Pattern << \"\\n\\n\";\n }\n \n OS << \"#endif \/* __ARM_NEON_H *\/\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX\n#define INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX\n\n#include <sal\/types.h>\n\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/uno\/Sequence.h>\n\n#include <com\/sun\/star\/uno\/XInterface.hpp>\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEventTarget.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEventListener.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEvent.hpp>\n\n#include <cppuhelper\/implbase3.hxx>\n\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::xml::dom;\nusing namespace com::sun::star::xml::dom::events;\n\nnamespace DOM { namespace events\n{\n\n typedef ::cppu::WeakImplHelper3\n < ::com::sun::star::xml::dom::events::XEventListener\n , ::com::sun::star::lang::XInitialization\n , ::com::sun::star::lang::XServiceInfo\n > CTestListener_Base;\n\n class CTestListener\n : public CTestListener_Base\n {\n\n private:\n Reference< ::com::sun::star::lang::XMultiServiceFactory > m_factory;\n Reference <XEventTarget> m_target;\n OUString m_type;\n sal_Bool m_capture;\n OUString m_name;\n\n public:\n\n \/\/ static helpers for service info and component management\n static const char* aImplementationName;\n static const char* aSupportedServiceNames[];\n static OUString _getImplementationName();\n static Sequence< OUString > _getSupportedServiceNames();\n static Reference< XInterface > _getInstance(\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n rSMgr);\n\n CTestListener(\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n rSMgr)\n : m_factory(rSMgr){};\n\n virtual ~CTestListener();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName()\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n\n \/\/ XEventListener\n virtual void SAL_CALL initialize(const Sequence< Any >& args) throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n\n };\n}}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>coverity#708568 Uninitialized scalar field<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX\n#define INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX\n\n#include <sal\/types.h>\n\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/uno\/Sequence.h>\n\n#include <com\/sun\/star\/uno\/XInterface.hpp>\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEventTarget.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEventListener.hpp>\n#include <com\/sun\/star\/xml\/dom\/events\/XEvent.hpp>\n\n#include <cppuhelper\/implbase3.hxx>\n\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::xml::dom;\nusing namespace com::sun::star::xml::dom::events;\n\nnamespace DOM { namespace events\n{\n\n typedef ::cppu::WeakImplHelper3\n < ::com::sun::star::xml::dom::events::XEventListener\n , ::com::sun::star::lang::XInitialization\n , ::com::sun::star::lang::XServiceInfo\n > CTestListener_Base;\n\n class CTestListener\n : public CTestListener_Base\n {\n\n private:\n Reference< ::com::sun::star::lang::XMultiServiceFactory > m_factory;\n Reference <XEventTarget> m_target;\n OUString m_type;\n sal_Bool m_capture;\n OUString m_name;\n\n public:\n\n \/\/ static helpers for service info and component management\n static const char* aImplementationName;\n static const char* aSupportedServiceNames[];\n static OUString _getImplementationName();\n static Sequence< OUString > _getSupportedServiceNames();\n static Reference< XInterface > _getInstance(\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n rSMgr);\n\n CTestListener(\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n rSMgr)\n : m_factory(rSMgr)\n , m_capture(sal_False)\n {\n }\n\n virtual ~CTestListener();\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName()\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()\n throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n\n \/\/ XEventListener\n virtual void SAL_CALL initialize(const Sequence< Any >& args) throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException, std::exception) SAL_OVERRIDE;\n\n\n };\n}}\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).\n\/\/ \n\/\/ Usage:\n\/\/ AddTrainPerformanceTRD.C(MC, friends, tasks)\n\/\/ tasks : \"ALL\" or one\/more of the following:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"MULT\" : TRD single track selection\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"CLRES\": clusters Resolution\n\/\/ \"CAL\" : TRD calibration\n\/\/ \"ALGN\" : TRD alignment\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"PIDR\" : TRD PID - reference data\n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/\n\/\/ In compiled mode : \n\/\/ Don't forget to load first the libraries\n\/\/ gSystem->Load(\"libMemStat.so\")\n\/\/ gSystem->Load(\"libMemStatGui.so\")\n\/\/ gSystem->Load(\"libANALYSIS.so\")\n\/\/ gSystem->Load(\"libANALYSISalice.so\")\n\/\/ gSystem->Load(\"libPWG1.so\");\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n\/\/#ifndef __CINT__\n#include <Riostream.h>\n\n#include \"TStopwatch.h\"\n#include \"TMemStat.h\"\n#include \"TMemStatViewerGUI.h\"\n\n#include \"TROOT.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \"TError.h\"\n#include \"TChain.h\"\n#include \"TGrid.h\"\n#include \"TAlienCollection.h\"\n#include \"TGridCollection.h\"\n#include \"TGridResult.h\"\n#include \"TGeoGlobalMagField.h\"\n\n#include \"AliMagF.h\"\n#include \"AliTracker.h\"\n#include \"AliLog.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPManager.h\"\n#include \"AliGeomManager.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliESDInputHandler.h\"\n\n#include \"TRD\/AliTRDtrackerV1.h\"\n#include \"TRD\/AliTRDcalibDB.h\"\n\n#include \"PWG1\/TRD\/macros\/AliTRDperformanceTrain.h\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckESD.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDinfoGen.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckDET.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDefficiency.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDresolution.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckPID.C\"\n#endif\n\n#include \"..\/TRD\/macros\/AliTRDperformanceTrain.h\"\n\n\nBool_t AddTrainPerformanceTRD(Bool_t mc, Bool_t fr, Char_t *trd=\"ALL\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if(!mgr) { \n Error(\"AddTrainPerformanceTRD\", \"AliAnalysisManager not set!\");\n return kFALSE;\n }\n\n \/\/ TRD data containers\n AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0};\n\n \/\/ initialize TRD settings\n AliTRDcalibDB *cal = AliTRDcalibDB::Instance();\n AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins());\n\n for(Int_t it=0; it<NTRDQATASKS; it++){\n if(gROOT->LoadMacro(Form(\"$ALICE_ROOT\/PWG1\/TRD\/macros\/Add%s.C+\", TString(fgkTRDtaskClassName[it])(3,20).Data()))) {\n Error(\"AddTrainPerformanceTRD()\", Form(\"Error loading %s task.\", fgkTRDtaskClassName[it]));\n return kFALSE;\n } \n\n switch(it){\n case kCheckESD:\n AddTRDcheckESD(mgr); break;\n case kInfoGen:\n AddTRDinfoGen(mgr, trd, 0x0, ci); break;\n case kCheckDET:\n AddTRDcheckDET(mgr, trd, ci); break;\n case kEfficiency:\n AddTRDefficiency(mgr, trd, ci); break;\n case kResolution:\n AddTRDresolution(mgr, trd, ci); break;\n case kCheckPID:\n AddTRDcheckPID(mgr, trd, ci); break;\n default:\n Warning(\"AddTrainPerformanceTRD()\", Form(\"No performance task registered at slot %d.\", it)); \n }\n }\n return kTRUE;\n}\n\n<commit_msg>update for AliTRDcalibDB::GetNumberOfTimeBinsDCS()<commit_after>\/\/ Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).\n\/\/ \n\/\/ Usage:\n\/\/ AddTrainPerformanceTRD.C(MC, friends, tasks)\n\/\/ tasks : \"ALL\" or one\/more of the following:\n\/\/ \"EFF\" : TRD Tracking Efficiency \n\/\/ \"EFFC\" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations\n\/\/ \"MULT\" : TRD single track selection\n\/\/ \"RES\" : TRD tracking Resolution\n\/\/ \"CLRES\": clusters Resolution\n\/\/ \"CAL\" : TRD calibration\n\/\/ \"ALGN\" : TRD alignment\n\/\/ \"PID\" : TRD PID - pion efficiency \n\/\/ \"PIDR\" : TRD PID - reference data\n\/\/ \"DET\" : Basic TRD Detector checks\n\/\/ \"NOFR\" : Data set does not have AliESDfriends.root \n\/\/ \"NOMC\" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely\n\/\/ on MC information are switched off\n\/\/\n\/\/ In compiled mode : \n\/\/ Don't forget to load first the libraries\n\/\/ gSystem->Load(\"libMemStat.so\")\n\/\/ gSystem->Load(\"libMemStatGui.so\")\n\/\/ gSystem->Load(\"libANALYSIS.so\")\n\/\/ gSystem->Load(\"libANALYSISalice.so\")\n\/\/ gSystem->Load(\"libPWG1.so\");\n\/\/\n\/\/ Authors:\n\/\/ Alex Bercuci (A.Bercuci@gsi.de) \n\/\/ Markus Fasel (m.Fasel@gsi.de) \n\n#if ! defined (__CINT__) || defined (__MAKECINT__)\n\/\/#ifndef __CINT__\n#include <Riostream.h>\n\n#include \"TStopwatch.h\"\n#include \"TMemStat.h\"\n#include \"TMemStatViewerGUI.h\"\n\n#include \"TROOT.h\"\n#include \"TClass.h\"\n#include \"TSystem.h\"\n#include \"TError.h\"\n#include \"TChain.h\"\n#include \"TGrid.h\"\n#include \"TAlienCollection.h\"\n#include \"TGridCollection.h\"\n#include \"TGridResult.h\"\n#include \"TGeoGlobalMagField.h\"\n\n#include \"AliMagF.h\"\n#include \"AliTracker.h\"\n#include \"AliLog.h\"\n#include \"AliCDBManager.h\"\n#include \"AliGRPManager.h\"\n#include \"AliGeomManager.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliESDInputHandler.h\"\n\n#include \"TRD\/AliTRDtrackerV1.h\"\n#include \"TRD\/AliTRDcalibDB.h\"\n\n#include \"PWG1\/TRD\/macros\/AliTRDperformanceTrain.h\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckESD.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDinfoGen.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckDET.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDefficiency.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDresolution.C\"\n#include \"PWG1\/TRD\/macros\/AddTRDcheckPID.C\"\n#endif\n\n#include \"..\/TRD\/macros\/AliTRDperformanceTrain.h\"\n\n\nBool_t AddTrainPerformanceTRD(Bool_t mc, Bool_t fr, Char_t *trd=\"ALL\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if(!mgr) { \n Error(\"AddTrainPerformanceTRD\", \"AliAnalysisManager not set!\");\n return kFALSE;\n }\n\n \/\/ TRD data containers\n AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0};\n\n \/\/ initialize TRD settings\n AliTRDcalibDB *cal = AliTRDcalibDB::Instance();\n AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBinsDCS());\n for(Int_t it=0; it<NTRDQATASKS; it++){\n if(gROOT->LoadMacro(Form(\"$ALICE_ROOT\/PWG1\/TRD\/macros\/Add%s.C+\", TString(fgkTRDtaskClassName[it])(3,20).Data()))) {\n Error(\"AddTrainPerformanceTRD()\", Form(\"Error loading %s task.\", fgkTRDtaskClassName[it]));\n return kFALSE;\n } \n\n switch(it){\n case kCheckESD:\n AddTRDcheckESD(mgr); break;\n case kInfoGen:\n AddTRDinfoGen(mgr, trd, 0x0, ci); break;\n case kCheckDET:\n AddTRDcheckDET(mgr, trd, ci); break;\n case kEfficiency:\n AddTRDefficiency(mgr, trd, ci); break;\n case kResolution:\n AddTRDresolution(mgr, trd, ci); break;\n case kCheckPID:\n AddTRDcheckPID(mgr, trd, ci); break;\n default:\n Warning(\"AddTrainPerformanceTRD()\", Form(\"No performance task registered at slot %d.\", it)); \n }\n }\n return kTRUE;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Author: Andrey Ivanov. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/ Analysis task for Long Range Correlation (LRC) analysis using TPC data\n\/\/ This includes a TList of AliLRCBase objects that are processing LRC analysis\n\/\/ for a given Eta window \n\/\/ This task is worcking with ESD data only\n\n\/\/ Author : Andrey Ivanov , St.Peterburg State University\n\/\/ Email: Andrey.Ivanov@cern.ch\n\n#include <AliAnalysisManager.h>\n#include <AliESDInputHandler.h>\n#include \"AliAnalysisTaskLRC.h\"\n#include <AliLRCBase.h>\n#include <AliVEvent.h>\n#include <AliMCEvent.h>\n#include <AliESDEvent.h> \n#include <AliPID.h>\n\n#include <AliRunLoader.h>\n#include <AliRun.h>\n#include <AliStack.h>\n#include <AliESDtrackCuts.h>\n#include <AliPhysicsSelection.h>\n#include <TParticle.h>\n#include <TH1.h>\n#include <TH2.h>\n\n\nClassImp(AliAnalysisTaskLRC)\n\n\/\/________________________________________________________________________\nAliAnalysisTaskLRC::AliAnalysisTaskLRC(const char *name,Bool_t runKine) \n : AliAnalysisTaskSE(name),fEsdTrackCuts(0),fMaxPtLimit(5.0),fMinPtLimit(0.0),fMinAceptedTracksCut(0),fMaxAceptedTracksCut(0),fCheckForkVtx(kTRUE),fCheckForVtxPosition(kFALSE),fVxMax(0),fVyMax(0),fVzMax(0),fLRCproc(0),fOutList(0),fRunKine(0),fShowEventStats(kFALSE),fShowPerTrackStats(kFALSE),fHistEventCutStats(0),fHistTrackCutStats(0),fHistVx(0),fHistVy(0),fHistVz(0),fHistEtaVsZvCoverage(0),fHistEtaVsZvCoverageAcepted(0),fHistAceptedMult(0)\n{\n \/\/Init\n fRunKine=runKine;\n\n \/\/ Output slot #1 writes into a TList container for common task data and QA\n DefineOutput(1, TList::Class());\n\n \/\/Defining output slots for each LRC processor (required to avoid TList of TLists on merging)\n for(Int_t i=0; i < fLRCproc.GetEntries(); i++)\n {\n DefineOutput(Proc(i)->GetOutputSlotNumber(),TList::Class());\n }\n}\n\n\n\/\/ --------------------------------------- Setters ------------------\n\n void AliAnalysisTaskLRC::SetMaxPtLimit(Double_t MaxPtLimit)\n {\n \/\/Sets Max Pt filter\n fMaxPtLimit=MaxPtLimit;\n }\n void AliAnalysisTaskLRC::SetMinPtLimit(Double_t MinPtLimit)\n {\n \/\/Sets Min Pt filter \n fMinPtLimit=MinPtLimit;\n }\n AliLRCBase* AliAnalysisTaskLRC::Proc(Int_t index) \n {\n \/\/ Get Processor i\n return (dynamic_cast<AliLRCBase*> (fLRCproc.At(index)));\n }\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::UserCreateOutputObjects()\n{\n \/\/Disabling \"replacing existing TH2D ...etc\" warning\n \n Bool_t lTH1oldStatus = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n \n Bool_t lTH2oldStatus = TH2::AddDirectoryStatus();\n TH2::AddDirectory(kFALSE);\n \n \n \/\/LRC processors init\n Int_t lLrcNum=fLRCproc.GetEntries();\n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->InitDataMembers();\n else continue;\n }\n \n\n \/\/ --------- Output list\n \n fOutList = new TList();\n \n fOutList->Add( fEsdTrackCuts );\n\n \/\/Event level QA\n fHistEventCutStats = new TH1D(\"fHistEventCutStats\",\"Event statistics;;N_{events}\", 7,-0.5,6.5);\n TString gEventCutBinNames[7] = {\"Total\",\"No trigger\",\"No vertex\",\"Bad vertex position\",\"HighMult cut\",\"LowMult cut\",\"Analyzed\"};\n for(Int_t i = 1; i <= 7; i++)fHistEventCutStats->GetXaxis()->SetBinLabel(i,gEventCutBinNames[i-1].Data());\n fOutList->Add(fHistEventCutStats);\n\n \/\/Track level QA\n fHistTrackCutStats = new TH1D(\"fHistTrackCutStats\",\"Event statistics;;N_{events}\", 5,-0.5,4.5);\n TString gTrackCutBinNames[5] = {\"Total\",\"AliESDtrackCuts\",\"HighPt cut\",\"LowPt cut\",\"Good\"};\n for(Int_t i = 1; i <= 5; i++)fHistTrackCutStats->GetXaxis()->SetBinLabel(i,gTrackCutBinNames[i-1].Data());\n fOutList->Add(fHistTrackCutStats);\n\n\n \/\/Vertex distributions\n fHistVx = new TH1D(\"fHistVx\",\"Primary vertex distribution - x coordinate;V_{x} (cm);Entries\",100,-0.5,0.5);\n fOutList->Add(fHistVx);\n fHistVy = new TH1D(\"fHistVy\",\"Primary vertex distribution - y coordinate;V_{y} (cm);Entries\",100,-0.5,0.5);\n fOutList->Add(fHistVy);\n fHistVz = new TH1D(\"fHistVz\",\"Primary vertex distribution - z coordinate;V_{z} (cm);Entries\",100,-20.,20.);\n fOutList->Add(fHistVz);\n\n \/\/Eta vs Zv\n fHistEtaVsZvCoverage = new TH2D(\"fHistEtaVsZvCoverage\",\"TPC tracks ETA vs Zv;V_{z} (cm);ETA\",100,-20,20,50,-2,2);\n fHistEtaVsZvCoverageAcepted = new TH2D(\"fHistEtaVsZvCoverage\",\"Acepted TPC tracks ETA vs Zv;V_{z} (cm);ETA\",100,-20,20,50,-2,2);\n fOutList->Add(fHistEtaVsZvCoverage);\n fOutList->Add(fHistEtaVsZvCoverageAcepted);\n\n fHistAceptedMult = new TH1D(\"fHistAceptedMult\",\"N_{ch} - accepted tracks;N_{ch} acepted;Entries\",401,-0.5,400.5);\n fOutList->Add(fHistAceptedMult);\n \n \/\/ Returning TH1,TH2 AddDirectory status \n TH1::AddDirectory(lTH1oldStatus);\n TH2::AddDirectory(lTH2oldStatus);\n \n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::UserExec(Option_t *) \n{\n \/\/ Main loop\n \/\/ Called for each event\n\n AliVEvent *event = InputEvent();\n AliESDEvent *fESD = 0x0;\n fESD=dynamic_cast<AliESDEvent*> (event) ;\n AliStack *stack = 0x0;\n AliMCEvent *eventMC = 0x0;\n if( fRunKine ) \n {\n\teventMC=MCEvent(); \n\tstack=eventMC->Stack();\n\tPrintf(\"Number of primaries: %d\",stack->GetNprimary());\n }\n\n\n if (!event) {\n Printf(\"ERROR: Could not retrieve event\");\n return;\n }\n if((fESD)&&(!fEsdTrackCuts)){ AliDebug(AliLog::kError, \"No ESD track cuts avalible\"); return;}\n\n \/\/ Numbrt of processors attached\n Int_t lLrcNum=fLRCproc.GetEntries();\n \n\n\/\/ Processing event selection \nfHistEventCutStats->Fill(0);\n\nBool_t lTrigger=kTRUE;\nBool_t lVertexPresent=kTRUE;\nBool_t lVertexAceptable=kTRUE;\n\n\n\/\/Trigger\n if(fESD){\n\tif(fShowEventStats)Printf(\"Trigger classes: %s:\", fESD->GetFiredTriggerClasses().Data());\n\t\n \tlTrigger=((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();\n \tif(!lTrigger){\n \t\tif(fShowEventStats)Printf(\"Rejected!\");\n\t\tfHistEventCutStats->Fill(1);\n \t\tPostData(1, fOutList);\n\t\treturn;\n\t}\n }\n\n\/\/ Vertex present\nconst AliESDVertex *vertex = fESD->GetPrimaryVertex();\n if(vertex) {\n lVertexPresent=((vertex)&&(vertex->GetNContributors() > 0)&&(vertex->GetZRes() != 0));\n if((!lVertexPresent)&&fCheckForkVtx)\n {if(fShowEventStats)Printf(\"No vertex\");\n fHistEventCutStats->Fill(2);\n PostData(1, fOutList);\n return;\n }\n\n \/\/ Vertex in range \n lVertexAceptable=(TMath::Abs(vertex->GetXv()) < fVxMax) && (TMath::Abs(vertex->GetYv()) < fVyMax); \n if(lVertexAceptable)\n if(fVzMax>0) \/\/ fVzMax < 0 -> select Zv outside selected range\n { lVertexAceptable = (TMath::Abs(vertex->GetZv()) < fVzMax);}\n else\n { lVertexAceptable = (TMath::Abs(vertex->GetZv()) > -fVzMax);}\n \n if((!lVertexAceptable) && fCheckForVtxPosition) \n {if(fShowEventStats)Printf(\"Vertex out of range\");\n fHistEventCutStats->Fill(3);\n PostData(1, fOutList);\n return;\n }\n \n fHistVx->Fill(vertex->GetXv());\n fHistVy->Fill(vertex->GetYv());\n fHistVz->Fill(vertex->GetZv());\n \n\nint lNchTrigger=0;\n\/\/ Pre event loop \nif(fESD && !fRunKine )\n\tfor (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++)\n\t\tif(fEsdTrackCuts->AcceptTrack(fESD->GetTrack(iTracks)))lNchTrigger++;\n\n\/\/if(fRunKine)lNchTrigger=eventMC->GetNumberOfPrimaries();\n\n\/\/ Nch bins cut\n\nif( (lNchTrigger > fMaxAceptedTracksCut) && (fMaxAceptedTracksCut != 0))\n\t{\n\tfHistEventCutStats->Fill(4);\n \tPostData(1, fOutList);\n\treturn;\n\t}\n\n\nif(lNchTrigger < fMinAceptedTracksCut)\n\t{\t\n\tfHistEventCutStats->Fill(5);\n\t PostData(1, fOutList);\n\treturn;\n\t}\nfHistAceptedMult->Fill(lNchTrigger);\nfHistEventCutStats->Fill(6);\n\n\n \/\/Track variables\n double lPt; \/\/ Temp Pt\n double lEta;\t \/\/ Temp ETA\t\n double lPhi; \/\/ Temp Phi\n \n \/\/Track selection counters \n int lNaccept=0;\n int lPtOver=0;\n int lPtUnder=0;\n int lNoCharge=0;\n int lCutfail=0;\n int lDecay=0;\n\n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->StartEvent();\n else continue;\n }\n\n \/\/ Track loop -----------------------------------------------------------------\n for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++) {\n \n AliVParticle* track = event->GetTrack(iTracks);\n if (!track) {\n Printf(\"ERROR: Could not receive track %d\", iTracks);\n continue;\n }\n\n \n fHistTrackCutStats->Fill(0);\n fHistEtaVsZvCoverage->Fill(vertex->GetZv(),track->Eta());\n\t\n lPt=track->Pt();\n lEta=track->Eta();\n lPhi=track->Phi();\n \n \/\/ ESD track cuts\n if(fESD && !fRunKine )\n {\n \tAliESDtrack* lESDtarck= fESD->GetTrack(iTracks);\n\tif(fShowPerTrackStats)printf(\"ESD Track N%d , Eta=%f, Pt=%f , TPC Nclusters =%d Sigma=%f \", iTracks , lEta , lPt, lESDtarck-> GetTPCNcls(),fEsdTrackCuts->GetSigmaToVertex( lESDtarck) );\n\tif(!fEsdTrackCuts->AcceptTrack(lESDtarck))\n\t\t{\t\n\t\tlCutfail++;\n\t\tif(fShowPerTrackStats)Printf(\"Rejected by cuts\");\n\t\tfHistTrackCutStats->Fill(1);\n\t\tcontinue;\n\t\t}\n\telse\n\t\t{\n\t\tif(fShowPerTrackStats)Printf(\"OK\");\n\t\t}\t\n \n }\n \/\/ end of ESD tack cuts\n\n if(lPt>fMaxPtLimit)\n\t{lPtOver++; \n\tfHistTrackCutStats->Fill(2);\n\tcontinue;} \/\/ Dropping traks with hi Pt\n \n\tif(lPt<fMinPtLimit)\n\t{lPtUnder++;\n\tfHistTrackCutStats->Fill(3);\n\tcontinue;} \/\/ Dropping traks with lo Pt\n\n \n\tfHistTrackCutStats->Fill(4);\n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->AddTrackPtEta(lPt,lEta,lPhi);\n else continue;\n }\n\n lNaccept++;\n fHistEtaVsZvCoverageAcepted->Fill(vertex->GetZv(),track->Eta());\n \n } \/\/end of track loop \n \n \n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->FinishEvent();\n else continue;\n }\n\n \/\/Debuging output of track filter\n if(fShowPerTrackStats)Printf(\"NofTracks= %d , accepted %d , LowPt %d, HighPt %d, LowCharge %d, ESD cut fail %d , Decay Filer %d\", event->GetNumberOfTracks(), lNaccept, lPtUnder, lPtOver ,lNoCharge , lCutfail , lDecay);\n \n \/\/ Post output data.\n \n PostData(1, fOutList);\n \n for(Int_t i=0; i < fLRCproc.GetEntries(); i++)\n {\n PostData(Proc(i)->GetOutputSlotNumber(),Proc(i)->CreateOutput());\n }\n \n }\/\/vertex\n \n} \n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::Terminate(Option_t *) \n{\n \/\/ Draw result to the screen\n \/\/ Called once at the end of the query\n\/\/fOutList = dynamic_cast<TList*> (GetOutputData(0));\n\n\/\/fEsdTrackCuts->DrawHistograms();\n\n \n}\n\n\nvoid AliAnalysisTaskLRC::AddLRCProcess(AliLRCBase *newProc)\n{\n\/\/ Add new AliLRCBase (Main LRC processor per ETA window) to the processing list\n\/\/ Used to add new ETA window to AnalysisTask \nif(!newProc)\n{Printf(\"ERROR:No AliLRCBase object - NULL pointer!\");\nreturn;\n}\n\n\nfLRCproc.Add(newProc);\nnewProc->SetOutputSlotNumber(fLRCproc.GetEntries()+1);\nDefineOutput(newProc->GetOutputSlotNumber(),TList::Class());\nreturn ;\n}\n\n<commit_msg>Coverity (LRC task)<commit_after>\/**************************************************************************\n * Author: Andrey Ivanov. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/ Analysis task for Long Range Correlation (LRC) analysis using TPC data\n\/\/ This includes a TList of AliLRCBase objects that are processing LRC analysis\n\/\/ for a given Eta window \n\/\/ This task is worcking with ESD data only\n\n\/\/ Author : Andrey Ivanov , St.Peterburg State University\n\/\/ Email: Andrey.Ivanov@cern.ch\n\n#include <AliAnalysisManager.h>\n#include <AliESDInputHandler.h>\n#include \"AliAnalysisTaskLRC.h\"\n#include <AliLRCBase.h>\n#include <AliVEvent.h>\n#include <AliMCEvent.h>\n#include <AliESDEvent.h> \n#include <AliPID.h>\n\n#include <AliRunLoader.h>\n#include <AliRun.h>\n#include <AliStack.h>\n#include <AliESDtrackCuts.h>\n#include <AliPhysicsSelection.h>\n#include <TParticle.h>\n#include <TH1.h>\n#include <TH2.h>\n\n\nClassImp(AliAnalysisTaskLRC)\n\n\/\/________________________________________________________________________\nAliAnalysisTaskLRC::AliAnalysisTaskLRC(const char *name,Bool_t runKine) \n : AliAnalysisTaskSE(name),fEsdTrackCuts(0),fMaxPtLimit(5.0),fMinPtLimit(0.0),fMinAceptedTracksCut(0),fMaxAceptedTracksCut(0),fCheckForkVtx(kTRUE),fCheckForVtxPosition(kFALSE),fVxMax(0),fVyMax(0),fVzMax(0),fLRCproc(0),fOutList(0),fRunKine(0),fShowEventStats(kFALSE),fShowPerTrackStats(kFALSE),fHistEventCutStats(0),fHistTrackCutStats(0),fHistVx(0),fHistVy(0),fHistVz(0),fHistEtaVsZvCoverage(0),fHistEtaVsZvCoverageAcepted(0),fHistAceptedMult(0)\n{\n \/\/Init\n fRunKine=runKine;\n\n \/\/ Output slot #1 writes into a TList container for common task data and QA\n DefineOutput(1, TList::Class());\n\n \/\/Defining output slots for each LRC processor (required to avoid TList of TLists on merging)\n for(Int_t i=0; i < fLRCproc.GetEntries(); i++)\n {\n DefineOutput(Proc(i)->GetOutputSlotNumber(),TList::Class());\n }\n}\n\n\n\/\/ --------------------------------------- Setters ------------------\n\n void AliAnalysisTaskLRC::SetMaxPtLimit(Double_t MaxPtLimit)\n {\n \/\/Sets Max Pt filter\n fMaxPtLimit=MaxPtLimit;\n }\n void AliAnalysisTaskLRC::SetMinPtLimit(Double_t MinPtLimit)\n {\n \/\/Sets Min Pt filter \n fMinPtLimit=MinPtLimit;\n }\n AliLRCBase* AliAnalysisTaskLRC::Proc(Int_t index) \n {\n \/\/ Get Processor i\n return (dynamic_cast<AliLRCBase*> (fLRCproc.At(index)));\n }\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::UserCreateOutputObjects()\n{\n \/\/Disabling \"replacing existing TH2D ...etc\" warning\n \n Bool_t lTH1oldStatus = TH1::AddDirectoryStatus();\n TH1::AddDirectory(kFALSE);\n \n Bool_t lTH2oldStatus = TH2::AddDirectoryStatus();\n TH2::AddDirectory(kFALSE);\n \n \n \/\/LRC processors init\n Int_t lLrcNum=fLRCproc.GetEntries();\n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->InitDataMembers();\n else continue;\n }\n \n\n \/\/ --------- Output list\n \n fOutList = new TList();\n \n fOutList->Add( fEsdTrackCuts );\n\n \/\/Event level QA\n fHistEventCutStats = new TH1D(\"fHistEventCutStats\",\"Event statistics;;N_{events}\", 7,-0.5,6.5);\n TString gEventCutBinNames[7] = {\"Total\",\"No trigger\",\"No vertex\",\"Bad vertex position\",\"HighMult cut\",\"LowMult cut\",\"Analyzed\"};\n for(Int_t i = 1; i <= 7; i++)fHistEventCutStats->GetXaxis()->SetBinLabel(i,gEventCutBinNames[i-1].Data());\n fOutList->Add(fHistEventCutStats);\n\n \/\/Track level QA\n fHistTrackCutStats = new TH1D(\"fHistTrackCutStats\",\"Event statistics;;N_{events}\", 5,-0.5,4.5);\n TString gTrackCutBinNames[5] = {\"Total\",\"AliESDtrackCuts\",\"HighPt cut\",\"LowPt cut\",\"Good\"};\n for(Int_t i = 1; i <= 5; i++)fHistTrackCutStats->GetXaxis()->SetBinLabel(i,gTrackCutBinNames[i-1].Data());\n fOutList->Add(fHistTrackCutStats);\n\n\n \/\/Vertex distributions\n fHistVx = new TH1D(\"fHistVx\",\"Primary vertex distribution - x coordinate;V_{x} (cm);Entries\",100,-0.5,0.5);\n fOutList->Add(fHistVx);\n fHistVy = new TH1D(\"fHistVy\",\"Primary vertex distribution - y coordinate;V_{y} (cm);Entries\",100,-0.5,0.5);\n fOutList->Add(fHistVy);\n fHistVz = new TH1D(\"fHistVz\",\"Primary vertex distribution - z coordinate;V_{z} (cm);Entries\",100,-20.,20.);\n fOutList->Add(fHistVz);\n\n \/\/Eta vs Zv\n fHistEtaVsZvCoverage = new TH2D(\"fHistEtaVsZvCoverage\",\"TPC tracks ETA vs Zv;V_{z} (cm);ETA\",100,-20,20,50,-2,2);\n fHistEtaVsZvCoverageAcepted = new TH2D(\"fHistEtaVsZvCoverage\",\"Acepted TPC tracks ETA vs Zv;V_{z} (cm);ETA\",100,-20,20,50,-2,2);\n fOutList->Add(fHistEtaVsZvCoverage);\n fOutList->Add(fHistEtaVsZvCoverageAcepted);\n\n fHistAceptedMult = new TH1D(\"fHistAceptedMult\",\"N_{ch} - accepted tracks;N_{ch} acepted;Entries\",401,-0.5,400.5);\n fOutList->Add(fHistAceptedMult);\n \n \/\/ Returning TH1,TH2 AddDirectory status \n TH1::AddDirectory(lTH1oldStatus);\n TH2::AddDirectory(lTH2oldStatus);\n \n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::UserExec(Option_t *) \n{\n \/\/ Main loop\n \/\/ Called for each event\n\n AliVEvent *event = InputEvent();\n AliESDEvent *fESD = 0x0;\n fESD=dynamic_cast<AliESDEvent*> (event) ;\n AliStack *stack = 0x0;\n AliMCEvent *eventMC = 0x0;\n if( fRunKine ) \n {\n\teventMC=MCEvent(); \n\tstack=eventMC->Stack();\n\tPrintf(\"Number of primaries: %d\",stack->GetNprimary());\n }\n\n\n if (!event) {\n Printf(\"ERROR: Could not retrieve event\");\n return;\n }\n if((fESD)&&(!fEsdTrackCuts)){ AliDebug(AliLog::kError, \"No ESD track cuts avalible\"); return;}\n\n \/\/ Numbrt of processors attached\n Int_t lLrcNum=fLRCproc.GetEntries();\n \n\n\/\/ Processing event selection \nfHistEventCutStats->Fill(0);\n\nBool_t lTrigger=kTRUE;\nBool_t lVertexPresent=kTRUE;\nBool_t lVertexAceptable=kTRUE;\n\n\n\/\/Trigger\n if(fESD){\n\tif(fShowEventStats)Printf(\"Trigger classes: %s:\", fESD->GetFiredTriggerClasses().Data());\n\t\n \tlTrigger=((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();\n \tif(!lTrigger){\n \t\tif(fShowEventStats)Printf(\"Rejected!\");\n\t\tfHistEventCutStats->Fill(1);\n \t\tPostData(1, fOutList);\n\t\treturn;\n\t}\n }\n\n\/\/ Vertex present\nconst AliESDVertex *vertex = fESD->GetPrimaryVertex();\n if(vertex) {\n lVertexPresent=((vertex)&&(vertex->GetNContributors() > 0)&&(vertex->GetZRes() != 0));\n if((!lVertexPresent)&&fCheckForkVtx)\n {if(fShowEventStats)Printf(\"No vertex\");\n fHistEventCutStats->Fill(2);\n PostData(1, fOutList);\n return;\n }\n\n \/\/ Vertex in range \n lVertexAceptable=(TMath::Abs(vertex->GetXv()) < fVxMax) && (TMath::Abs(vertex->GetYv()) < fVyMax); \n if(lVertexAceptable) {\n if(fVzMax>0) \/\/ fVzMax < 0 -> select Zv outside selected range\n { lVertexAceptable = (TMath::Abs(vertex->GetZv()) < fVzMax);}\n else\n { lVertexAceptable = (TMath::Abs(vertex->GetZv()) > -fVzMax);}\n }\n if((!lVertexAceptable) && fCheckForVtxPosition) \n {if(fShowEventStats)Printf(\"Vertex out of range\");\n fHistEventCutStats->Fill(3);\n PostData(1, fOutList);\n return;\n }\n \n fHistVx->Fill(vertex->GetXv());\n fHistVy->Fill(vertex->GetYv());\n fHistVz->Fill(vertex->GetZv());\n \n\nint lNchTrigger=0;\n\/\/ Pre event loop \nif(fESD && !fRunKine )\n\tfor (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++)\n\t\tif(fEsdTrackCuts->AcceptTrack(fESD->GetTrack(iTracks)))lNchTrigger++;\n\n\/\/if(fRunKine)lNchTrigger=eventMC->GetNumberOfPrimaries();\n\n\/\/ Nch bins cut\n\nif( (lNchTrigger > fMaxAceptedTracksCut) && (fMaxAceptedTracksCut != 0))\n\t{\n\tfHistEventCutStats->Fill(4);\n \tPostData(1, fOutList);\n\treturn;\n\t}\n\n\nif(lNchTrigger < fMinAceptedTracksCut)\n\t{\t\n\tfHistEventCutStats->Fill(5);\n\t PostData(1, fOutList);\n\treturn;\n\t}\nfHistAceptedMult->Fill(lNchTrigger);\nfHistEventCutStats->Fill(6);\n\n\n \/\/Track variables\n double lPt; \/\/ Temp Pt\n double lEta;\t \/\/ Temp ETA\t\n double lPhi; \/\/ Temp Phi\n \n \/\/Track selection counters \n int lNaccept=0;\n int lPtOver=0;\n int lPtUnder=0;\n int lNoCharge=0;\n int lCutfail=0;\n int lDecay=0;\n\n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->StartEvent();\n else continue;\n }\n\n \/\/ Track loop -----------------------------------------------------------------\n for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++) {\n \n AliVParticle* track = event->GetTrack(iTracks);\n if (!track) {\n Printf(\"ERROR: Could not receive track %d\", iTracks);\n continue;\n }\n\n \n fHistTrackCutStats->Fill(0);\n fHistEtaVsZvCoverage->Fill(vertex->GetZv(),track->Eta());\n\t\n lPt=track->Pt();\n lEta=track->Eta();\n lPhi=track->Phi();\n \n \/\/ ESD track cuts\n if(fESD && !fRunKine )\n {\n \tAliESDtrack* lESDtarck= fESD->GetTrack(iTracks);\n\tif(fShowPerTrackStats)printf(\"ESD Track N%d , Eta=%f, Pt=%f , TPC Nclusters =%d Sigma=%f \", iTracks , lEta , lPt, lESDtarck-> GetTPCNcls(),fEsdTrackCuts->GetSigmaToVertex( lESDtarck) );\n\tif(!fEsdTrackCuts->AcceptTrack(lESDtarck))\n\t\t{\t\n\t\tlCutfail++;\n\t\tif(fShowPerTrackStats)Printf(\"Rejected by cuts\");\n\t\tfHistTrackCutStats->Fill(1);\n\t\tcontinue;\n\t\t}\n\telse\n\t\t{\n\t\tif(fShowPerTrackStats)Printf(\"OK\");\n\t\t}\t\n \n }\n \/\/ end of ESD tack cuts\n\n if(lPt>fMaxPtLimit)\n\t{lPtOver++; \n\tfHistTrackCutStats->Fill(2);\n\tcontinue;} \/\/ Dropping traks with hi Pt\n \n\tif(lPt<fMinPtLimit)\n\t{lPtUnder++;\n\tfHistTrackCutStats->Fill(3);\n\tcontinue;} \/\/ Dropping traks with lo Pt\n\n \n\tfHistTrackCutStats->Fill(4);\n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->AddTrackPtEta(lPt,lEta,lPhi);\n else continue;\n }\n\n lNaccept++;\n fHistEtaVsZvCoverageAcepted->Fill(vertex->GetZv(),track->Eta());\n \n } \/\/end of track loop \n \n \n \n for(Int_t i=0; i < lLrcNum; i++)\n {\n AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));\n if(lrcBase)\n lrcBase->FinishEvent();\n else continue;\n }\n\n \/\/Debuging output of track filter\n if(fShowPerTrackStats)Printf(\"NofTracks= %d , accepted %d , LowPt %d, HighPt %d, LowCharge %d, ESD cut fail %d , Decay Filer %d\", event->GetNumberOfTracks(), lNaccept, lPtUnder, lPtOver ,lNoCharge , lCutfail , lDecay);\n \n \/\/ Post output data.\n \n PostData(1, fOutList);\n \n for(Int_t i=0; i < fLRCproc.GetEntries(); i++)\n {\n PostData(Proc(i)->GetOutputSlotNumber(),Proc(i)->CreateOutput());\n }\n \n }\/\/vertex\n \n} \n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskLRC::Terminate(Option_t *) \n{\n \/\/ Draw result to the screen\n \/\/ Called once at the end of the query\n\/\/fOutList = dynamic_cast<TList*> (GetOutputData(0));\n\n\/\/fEsdTrackCuts->DrawHistograms();\n\n \n}\n\n\nvoid AliAnalysisTaskLRC::AddLRCProcess(AliLRCBase *newProc)\n{\n\/\/ Add new AliLRCBase (Main LRC processor per ETA window) to the processing list\n\/\/ Used to add new ETA window to AnalysisTask \nif(!newProc)\n{Printf(\"ERROR:No AliLRCBase object - NULL pointer!\");\nreturn;\n}\n\n\nfLRCproc.Add(newProc);\nnewProc->SetOutputSlotNumber(fLRCproc.GetEntries()+1);\nDefineOutput(newProc->GetOutputSlotNumber(),TList::Class());\nreturn ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/registration\/transforms.h>\n#include <vtkPLYReader.h>\n#include <vtkOBJReader.h>\n#include <vtkTriangle.h>\n#include <vtkTriangleFilter.h>\n#include <vtkPolyDataMapper.h>\n#include <pcl\/filters\/voxel_grid.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n\ninline double\nuniform_deviate (int seed)\n{\n double ran = seed * (1.0 \/ (RAND_MAX + 1.0));\n return ran;\n}\n\ninline void\nrandomPointTriangle (float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3,\n Eigen::Vector4f& p)\n{\n float r1 = uniform_deviate (rand ());\n float r2 = uniform_deviate (rand ());\n float r1sqr = sqrt (r1);\n float OneMinR1Sqr = (1 - r1sqr);\n float OneMinR2 = (1 - r2);\n a1 *= OneMinR1Sqr;\n a2 *= OneMinR1Sqr;\n a3 *= OneMinR1Sqr;\n b1 *= OneMinR2;\n b2 *= OneMinR2;\n b3 *= OneMinR2;\n c1 = r1sqr * (r2 * c1 + b1) + a1;\n c2 = r1sqr * (r2 * c2 + b2) + a2;\n c3 = r1sqr * (r2 * c3 + b3) + a3;\n p[0] = c1;\n p[1] = c2;\n p[2] = c3;\n p[3] = 0;\n}\n\ninline void\nrandPSurface (vtkPolyData * polydata, std::vector<double> * cumulativeAreas, double totalArea, Eigen::Vector4f& p)\n{\n float r = uniform_deviate (rand ()) * totalArea;\n\n std::vector<double>::iterator low = std::lower_bound (cumulativeAreas->begin (), cumulativeAreas->end (), r);\n vtkIdType el = (vtkIdType)(low - cumulativeAreas->begin ());\n\n double A[3], B[3], C[3];\n vtkIdType npts = 0;\n vtkIdType *ptIds = NULL;\n polydata->GetCellPoints (el, npts, ptIds);\n polydata->GetPoint (ptIds[0], A);\n polydata->GetPoint (ptIds[1], B);\n polydata->GetPoint (ptIds[2], C);\n randomPointTriangle (A[0], A[1], A[2], B[0], B[1], B[2], C[0], C[1], C[2], p);\n}\n\nvoid\nuniform_sampling (vtkSmartPointer<vtkPolyData> polydata, size_t n_samples, pcl::PointCloud<pcl::PointXYZ> & cloud_out)\n{\n polydata->BuildCells ();\n vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();\n\n double p1[3], p2[3], p3[3], totalArea = 0;\n std::vector<double> cumulativeAreas (cells->GetNumberOfCells (), 0);\n size_t i = 0;\n vtkIdType npts = 0, *ptIds = NULL;\n for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds); i++)\n {\n polydata->GetPoint (ptIds[0], p1);\n polydata->GetPoint (ptIds[1], p2);\n polydata->GetPoint (ptIds[2], p3);\n totalArea += vtkTriangle::TriangleArea (p1, p2, p3);\n cumulativeAreas[i] = totalArea;\n }\n\n cloud_out.points.resize (n_samples);\n cloud_out.width = n_samples;\n cloud_out.height = 1;\n\n for (i = 0; i < n_samples; i++)\n {\n Eigen::Vector4f p;\n randPSurface (polydata, &cumulativeAreas, totalArea, p);\n cloud_out.points[i].x = p[0];\n cloud_out.points[i].y = p[1];\n cloud_out.points[i].z = p[2];\n }\n}\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_number_samples = 100000;\nfloat default_leaf_size = 0.01;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.{ply,obj} output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -n_samples X = number of samples (default: \");\n print_value (\"%d\", default_number_samples);\n print_info (\")\\n\");\n print_info (\n \" -leaf_size X = the XYZ leaf size for the VoxelGrid -- for data reduction (default: \");\n print_value (\"%f\", default_leaf_size);\n print_info (\" m)\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char **argv)\n{\n print_info (\"Convert a CAD model to a point cloud using ray tracing operations. For more information, use: %s -h\\n\",\n argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse command line arguments\n int SAMPLE_POINTS_ = default_number_samples;\n parse_argument (argc, argv, \"-n_samples\", SAMPLE_POINTS_);\n double leaf_size = default_leaf_size;\n parse_argument (argc, argv, \"-leaf_size\", leaf_size);\n\n \/\/ Parse the command line arguments for .ply and PCD files\n std::vector<int> pcd_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (pcd_file_indices.size () != 1)\n {\n print_error (\"Need a single output PCD file to continue.\\n\");\n return (-1);\n }\n std::vector<int> ply_file_indices = parse_file_extension_argument (argc, argv, \".ply\");\n std::vector<int> obj_file_indices = parse_file_extension_argument (argc, argv, \".obj\");\n if (ply_file_indices.size () != 1 && obj_file_indices.size () != 1)\n {\n print_error (\"Need a single input PLY\/OBJ file to continue.\\n\");\n return (-1);\n }\n\n vtkSmartPointer<vtkPolyData> polydata1;\n if (ply_file_indices.size () == 1)\n {\n vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();\n readerQuery->SetFileName (argv[ply_file_indices[0]]);\n }\n else if (obj_file_indices.size () == 1)\n {\n vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();\n readerQuery->SetFileName (argv[obj_file_indices[0]]);\n polydata1 = readerQuery->GetOutput ();\n polydata1->Update ();\n }\n\n \/\/make sure that the polygons are triangles!\n vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New ();\n triangleFilter->SetInput (polydata1);\n triangleFilter->Update ();\n\n vtkSmartPointer<vtkPolyDataMapper> triangleMapper = vtkSmartPointer<vtkPolyDataMapper>::New ();\n triangleMapper->SetInputConnection (triangleFilter->GetOutputPort ());\n triangleMapper->Update();\n polydata1 = triangleMapper->GetInput();\n polydata1->Update ();\n\n bool INTER_VIS = false;\n bool VIS = true;\n\n if (INTER_VIS)\n {\n visualization::PCLVisualizer vis;\n vis.addModelFromPolyData (polydata1, \"mesh1\", 0);\n vis.setRepresentationToSurfaceForAllActors ();\n vis.spin();\n }\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_1 (new pcl::PointCloud<pcl::PointXYZ>);\n uniform_sampling (polydata1, SAMPLE_POINTS_, *cloud_1);\n\n if (INTER_VIS)\n {\n visualization::PCLVisualizer vis_sampled;\n vis_sampled.addPointCloud (cloud_1);\n vis_sampled.spin ();\n }\n\n \/\/ Voxelgrid\n VoxelGrid<PointXYZ> grid_;\n grid_.setInputCloud (cloud_1);\n grid_.setLeafSize (leaf_size, leaf_size, leaf_size);\n grid_.filter (*cloud_1);\n\n if (VIS)\n {\n visualization::PCLVisualizer vis3 (\"VOXELIZED SAMPLES CLOUD\");\n vis3.addPointCloud (cloud_1);\n vis3.spin ();\n }\n\n savePCDFileASCII (argv[pcd_file_indices[0]], *cloud_1);\n}\n<commit_msg>Changed description.<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <pcl\/visualization\/pcl_visualizer.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/registration\/transforms.h>\n#include <vtkPLYReader.h>\n#include <vtkOBJReader.h>\n#include <vtkTriangle.h>\n#include <vtkTriangleFilter.h>\n#include <vtkPolyDataMapper.h>\n#include <pcl\/filters\/voxel_grid.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n\ninline double\nuniform_deviate (int seed)\n{\n double ran = seed * (1.0 \/ (RAND_MAX + 1.0));\n return ran;\n}\n\ninline void\nrandomPointTriangle (float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3,\n Eigen::Vector4f& p)\n{\n float r1 = uniform_deviate (rand ());\n float r2 = uniform_deviate (rand ());\n float r1sqr = sqrt (r1);\n float OneMinR1Sqr = (1 - r1sqr);\n float OneMinR2 = (1 - r2);\n a1 *= OneMinR1Sqr;\n a2 *= OneMinR1Sqr;\n a3 *= OneMinR1Sqr;\n b1 *= OneMinR2;\n b2 *= OneMinR2;\n b3 *= OneMinR2;\n c1 = r1sqr * (r2 * c1 + b1) + a1;\n c2 = r1sqr * (r2 * c2 + b2) + a2;\n c3 = r1sqr * (r2 * c3 + b3) + a3;\n p[0] = c1;\n p[1] = c2;\n p[2] = c3;\n p[3] = 0;\n}\n\ninline void\nrandPSurface (vtkPolyData * polydata, std::vector<double> * cumulativeAreas, double totalArea, Eigen::Vector4f& p)\n{\n float r = uniform_deviate (rand ()) * totalArea;\n\n std::vector<double>::iterator low = std::lower_bound (cumulativeAreas->begin (), cumulativeAreas->end (), r);\n vtkIdType el = (vtkIdType)(low - cumulativeAreas->begin ());\n\n double A[3], B[3], C[3];\n vtkIdType npts = 0;\n vtkIdType *ptIds = NULL;\n polydata->GetCellPoints (el, npts, ptIds);\n polydata->GetPoint (ptIds[0], A);\n polydata->GetPoint (ptIds[1], B);\n polydata->GetPoint (ptIds[2], C);\n randomPointTriangle (A[0], A[1], A[2], B[0], B[1], B[2], C[0], C[1], C[2], p);\n}\n\nvoid\nuniform_sampling (vtkSmartPointer<vtkPolyData> polydata, size_t n_samples, pcl::PointCloud<pcl::PointXYZ> & cloud_out)\n{\n polydata->BuildCells ();\n vtkSmartPointer<vtkCellArray> cells = polydata->GetPolys ();\n\n double p1[3], p2[3], p3[3], totalArea = 0;\n std::vector<double> cumulativeAreas (cells->GetNumberOfCells (), 0);\n size_t i = 0;\n vtkIdType npts = 0, *ptIds = NULL;\n for (cells->InitTraversal (); cells->GetNextCell (npts, ptIds); i++)\n {\n polydata->GetPoint (ptIds[0], p1);\n polydata->GetPoint (ptIds[1], p2);\n polydata->GetPoint (ptIds[2], p3);\n totalArea += vtkTriangle::TriangleArea (p1, p2, p3);\n cumulativeAreas[i] = totalArea;\n }\n\n cloud_out.points.resize (n_samples);\n cloud_out.width = n_samples;\n cloud_out.height = 1;\n\n for (i = 0; i < n_samples; i++)\n {\n Eigen::Vector4f p;\n randPSurface (polydata, &cumulativeAreas, totalArea, p);\n cloud_out.points[i].x = p[0];\n cloud_out.points[i].y = p[1];\n cloud_out.points[i].z = p[2];\n }\n}\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_number_samples = 100000;\nfloat default_leaf_size = 0.01;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.{ply,obj} output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -n_samples X = number of samples (default: \");\n print_value (\"%d\", default_number_samples);\n print_info (\")\\n\");\n print_info (\n \" -leaf_size X = the XYZ leaf size for the VoxelGrid -- for data reduction (default: \");\n print_value (\"%f\", default_leaf_size);\n print_info (\" m)\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char **argv)\n{\n print_info (\"Convert a CAD model to a point cloud using uniform sampling. For more information, use: %s -h\\n\",\n argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse command line arguments\n int SAMPLE_POINTS_ = default_number_samples;\n parse_argument (argc, argv, \"-n_samples\", SAMPLE_POINTS_);\n double leaf_size = default_leaf_size;\n parse_argument (argc, argv, \"-leaf_size\", leaf_size);\n\n \/\/ Parse the command line arguments for .ply and PCD files\n std::vector<int> pcd_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (pcd_file_indices.size () != 1)\n {\n print_error (\"Need a single output PCD file to continue.\\n\");\n return (-1);\n }\n std::vector<int> ply_file_indices = parse_file_extension_argument (argc, argv, \".ply\");\n std::vector<int> obj_file_indices = parse_file_extension_argument (argc, argv, \".obj\");\n if (ply_file_indices.size () != 1 && obj_file_indices.size () != 1)\n {\n print_error (\"Need a single input PLY\/OBJ file to continue.\\n\");\n return (-1);\n }\n\n vtkSmartPointer<vtkPolyData> polydata1;\n if (ply_file_indices.size () == 1)\n {\n vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();\n readerQuery->SetFileName (argv[ply_file_indices[0]]);\n }\n else if (obj_file_indices.size () == 1)\n {\n vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();\n readerQuery->SetFileName (argv[obj_file_indices[0]]);\n polydata1 = readerQuery->GetOutput ();\n polydata1->Update ();\n }\n\n \/\/make sure that the polygons are triangles!\n vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New ();\n triangleFilter->SetInput (polydata1);\n triangleFilter->Update ();\n\n vtkSmartPointer<vtkPolyDataMapper> triangleMapper = vtkSmartPointer<vtkPolyDataMapper>::New ();\n triangleMapper->SetInputConnection (triangleFilter->GetOutputPort ());\n triangleMapper->Update();\n polydata1 = triangleMapper->GetInput();\n polydata1->Update ();\n\n bool INTER_VIS = false;\n bool VIS = true;\n\n if (INTER_VIS)\n {\n visualization::PCLVisualizer vis;\n vis.addModelFromPolyData (polydata1, \"mesh1\", 0);\n vis.setRepresentationToSurfaceForAllActors ();\n vis.spin();\n }\n\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_1 (new pcl::PointCloud<pcl::PointXYZ>);\n uniform_sampling (polydata1, SAMPLE_POINTS_, *cloud_1);\n\n if (INTER_VIS)\n {\n visualization::PCLVisualizer vis_sampled;\n vis_sampled.addPointCloud (cloud_1);\n vis_sampled.spin ();\n }\n\n \/\/ Voxelgrid\n VoxelGrid<PointXYZ> grid_;\n grid_.setInputCloud (cloud_1);\n grid_.setLeafSize (leaf_size, leaf_size, leaf_size);\n grid_.filter (*cloud_1);\n\n if (VIS)\n {\n visualization::PCLVisualizer vis3 (\"VOXELIZED SAMPLES CLOUD\");\n vis3.addPointCloud (cloud_1);\n vis3.spin ();\n }\n\n savePCDFileASCII (argv[pcd_file_indices[0]], *cloud_1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: salbmp.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: pluby $ $Date: 2000-12-01 18:03:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define _SV_SALBMP_CXX\n\n#ifndef _SV_SALBMP_HXX\n#include <salbmp.hxx>\n#endif\n#ifndef _SV_SALBTYPE_HXX\n#include <salbtype.hxx>\n#endif\n\n\/\/ ==================================================================\n\nSalBitmap::SalBitmap() :\n mnBitCount ( 0 )\n{\n}\n\n\/\/ ------------------------------------------------------------------\n\nSalBitmap::~SalBitmap()\n{\n Destroy();\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )\n{\n maSize = rSize;\n mnBitCount = nBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBitmap )\n{\n maSize = rSalBitmap.maSize;\n mnBitCount = 1;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )\n{\n maSize = rSalBmp.maSize;\n mnBitCount = rSalBmp.mnBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )\n{\n maSize = rSalBmp.maSize;\n mnBitCount = nNewBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SalBitmap::Destroy()\n{\n}\n\n\/\/ ------------------------------------------------------------------\n\nBitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )\n{\n BitmapBuffer *pBuffer = new BitmapBuffer();\n\n \/\/ Stub code: we have not yet written any interfaces to native bitmaps.\n pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;\n pBuffer->mnWidth = maSize.Width();\n pBuffer->mnHeight = maSize.Height();\n pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );\n pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];\n\n return pBuffer;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )\n{\n delete pBuffer;\n}\n<commit_msg>Added more stub code to eliminate numerous \"missing palette\" messages<commit_after>\/*************************************************************************\n *\n * $RCSfile: salbmp.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: pluby $ $Date: 2000-12-31 20:54:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define _SV_SALBMP_CXX\n\n#ifndef _SV_SALBMP_HXX\n#include <salbmp.hxx>\n#endif\n#ifndef _SV_SALBTYPE_HXX\n#include <salbtype.hxx>\n#endif\n\n\/\/ ==================================================================\n\nSalBitmap::SalBitmap() :\n mhPixMap( 0 ),\n mnBitCount( 0 )\n{\n}\n\n\/\/ ------------------------------------------------------------------\n\nSalBitmap::~SalBitmap()\n{\n Destroy();\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )\n{\n maSize = rSize;\n mnBitCount = nBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBitmap )\n{\n maSize = rSalBitmap.maSize;\n mnBitCount = 1;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )\n{\n maSize = rSalBmp.maSize;\n mnBitCount = rSalBmp.mnBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )\n{\n maSize = rSalBmp.maSize;\n mnBitCount = nNewBitCount;\n return TRUE;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SalBitmap::Destroy()\n{\n maSize = Size();\n mnBitCount = 0;\n}\n\n\/\/ ------------------------------------------------------------------\n\nBitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )\n{\n BitmapBuffer *pBuffer = new BitmapBuffer();\n\n \/\/ Stub code: we have not yet written any interfaces to native bitmaps.\n pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;\n pBuffer->mnWidth = maSize.Width();\n pBuffer->mnHeight = maSize.Height();\n pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );\n pBuffer->mnFormat |= BMP_FORMAT_16BIT_TC_MASK;\n pBuffer->maColorMask = ColorMask( 0x7b00, 0x03e0, 0x001f);\n pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];\n\n return pBuffer;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )\n{\n delete pBuffer;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: imgctrl.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 11:53:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n\n#ifndef _SV_EVENT_HXX\n#include <event.hxx>\n#endif\n#include <imgctrl.hxx>\n\n\/\/ -----------------------------------------------------------------------\n\nImageControl::ImageControl( Window* pParent, WinBits nStyle ) :\n FixedImage( pParent, nStyle )\n{\n mbScaleImage = TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::SetScaleImage( BOOL bScale )\n{\n if ( bScale != mbScaleImage )\n {\n mbScaleImage = bScale;\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImageControl::IsScaleImage() const\n{\n \/\/ Make inline when changing member from dummy...\n return mbScaleImage;\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::Resize()\n{\n Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::UserDraw( const UserDrawEvent& rUDEvt )\n{\n USHORT nStyle = 0;\n BitmapEx* pBitmap = &maBmp;\n Color aCol;\n if( !!maBmpHC && ImplGetCurrentBackgroundColor( aCol ) )\n {\n if( aCol.IsDark() )\n pBitmap = &maBmpHC;\n \/\/ #99902 no col transform required\n \/\/if( aCol.IsBright() )\n \/\/ nStyle |= IMAGE_DRAW_COLORTRANSFORM;\n }\n\n if( nStyle & IMAGE_DRAW_COLORTRANSFORM )\n {\n \/\/ only images support IMAGE_DRAW_COLORTRANSFORM\n Image aImage( maBmp );\n if ( !!aImage )\n {\n if ( mbScaleImage )\n rUDEvt.GetDevice()->DrawImage( rUDEvt.GetRect().TopLeft(),\n rUDEvt.GetRect().GetSize(),\n aImage, nStyle );\n else\n {\n \/\/ Center...\n Point aPos( rUDEvt.GetRect().TopLeft() );\n aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) \/ 2;\n aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) \/ 2;\n rUDEvt.GetDevice()->DrawImage( aPos, aImage, nStyle );\n }\n }\n }\n else\n {\n if ( mbScaleImage )\n {\n maBmp.Draw( rUDEvt.GetDevice(),\n rUDEvt.GetRect().TopLeft(),\n rUDEvt.GetRect().GetSize() );\n }\n else\n {\n \/\/ Center...\n Point aPos( rUDEvt.GetRect().TopLeft() );\n aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) \/ 2;\n aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) \/ 2;\n maBmp.Draw( rUDEvt.GetDevice(), aPos );\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::SetBitmap( const BitmapEx& rBmp )\n{\n maBmp = rBmp;\n StateChanged( STATE_CHANGE_DATA );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImageControl::SetModeBitmap( const BitmapEx& rBitmap, BmpColorMode eMode )\n{\n if( eMode == BMP_COLOR_NORMAL )\n SetBitmap( rBitmap );\n else if( eMode == BMP_COLOR_HIGHCONTRAST )\n {\n maBmpHC = rBitmap;\n StateChanged( STATE_CHANGE_DATA );\n }\n else\n return FALSE;\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nconst BitmapEx& ImageControl::GetModeBitmap( BmpColorMode eMode ) const\n{\n if( eMode == BMP_COLOR_HIGHCONTRAST )\n return maBmpHC;\n else\n return maBmp;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::Paint( const Rectangle& rRect )\n{\n FixedImage::Paint( rRect );\n if( HasFocus() )\n {\n Window *pWin = GetWindow( WINDOW_BORDER );\n\n BOOL bFlat = (GetBorderStyle() == 2);\n Rectangle aRect( Point(0,0), pWin->GetOutputSizePixel() );\n Color oldLineCol = pWin->GetLineColor();\n Color oldFillCol = pWin->GetFillColor();\n pWin->SetFillColor();\n pWin->SetLineColor( bFlat ? COL_WHITE : COL_BLACK );\n pWin->DrawRect( aRect );\n aRect.nLeft++;\n aRect.nRight--;\n aRect.nTop++;\n aRect.nBottom--;\n pWin->SetLineColor( bFlat ? COL_BLACK : COL_WHITE );\n pWin->DrawRect( aRect );\n pWin->SetLineColor( oldLineCol );\n pWin->SetFillColor( oldFillCol );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::GetFocus()\n{\n FixedImage::GetFocus();\n GetWindow( WINDOW_BORDER )->Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::LoseFocus()\n{\n FixedImage::GetFocus();\n GetWindow( WINDOW_BORDER )->Invalidate();\n}\n\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.10.240); FILE MERGED 2007\/06\/04 13:29:33 vg 1.10.240.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: imgctrl.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 20:06:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n\n#ifndef _SV_EVENT_HXX\n#include <vcl\/event.hxx>\n#endif\n#include <vcl\/imgctrl.hxx>\n\n\/\/ -----------------------------------------------------------------------\n\nImageControl::ImageControl( Window* pParent, WinBits nStyle ) :\n FixedImage( pParent, nStyle )\n{\n mbScaleImage = TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::SetScaleImage( BOOL bScale )\n{\n if ( bScale != mbScaleImage )\n {\n mbScaleImage = bScale;\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImageControl::IsScaleImage() const\n{\n \/\/ Make inline when changing member from dummy...\n return mbScaleImage;\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::Resize()\n{\n Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::UserDraw( const UserDrawEvent& rUDEvt )\n{\n USHORT nStyle = 0;\n BitmapEx* pBitmap = &maBmp;\n Color aCol;\n if( !!maBmpHC && ImplGetCurrentBackgroundColor( aCol ) )\n {\n if( aCol.IsDark() )\n pBitmap = &maBmpHC;\n \/\/ #99902 no col transform required\n \/\/if( aCol.IsBright() )\n \/\/ nStyle |= IMAGE_DRAW_COLORTRANSFORM;\n }\n\n if( nStyle & IMAGE_DRAW_COLORTRANSFORM )\n {\n \/\/ only images support IMAGE_DRAW_COLORTRANSFORM\n Image aImage( maBmp );\n if ( !!aImage )\n {\n if ( mbScaleImage )\n rUDEvt.GetDevice()->DrawImage( rUDEvt.GetRect().TopLeft(),\n rUDEvt.GetRect().GetSize(),\n aImage, nStyle );\n else\n {\n \/\/ Center...\n Point aPos( rUDEvt.GetRect().TopLeft() );\n aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) \/ 2;\n aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) \/ 2;\n rUDEvt.GetDevice()->DrawImage( aPos, aImage, nStyle );\n }\n }\n }\n else\n {\n if ( mbScaleImage )\n {\n maBmp.Draw( rUDEvt.GetDevice(),\n rUDEvt.GetRect().TopLeft(),\n rUDEvt.GetRect().GetSize() );\n }\n else\n {\n \/\/ Center...\n Point aPos( rUDEvt.GetRect().TopLeft() );\n aPos.X() += ( rUDEvt.GetRect().GetWidth() - maBmp.GetSizePixel().Width() ) \/ 2;\n aPos.Y() += ( rUDEvt.GetRect().GetHeight() - maBmp.GetSizePixel().Height() ) \/ 2;\n maBmp.Draw( rUDEvt.GetDevice(), aPos );\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::SetBitmap( const BitmapEx& rBmp )\n{\n maBmp = rBmp;\n StateChanged( STATE_CHANGE_DATA );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImageControl::SetModeBitmap( const BitmapEx& rBitmap, BmpColorMode eMode )\n{\n if( eMode == BMP_COLOR_NORMAL )\n SetBitmap( rBitmap );\n else if( eMode == BMP_COLOR_HIGHCONTRAST )\n {\n maBmpHC = rBitmap;\n StateChanged( STATE_CHANGE_DATA );\n }\n else\n return FALSE;\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nconst BitmapEx& ImageControl::GetModeBitmap( BmpColorMode eMode ) const\n{\n if( eMode == BMP_COLOR_HIGHCONTRAST )\n return maBmpHC;\n else\n return maBmp;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::Paint( const Rectangle& rRect )\n{\n FixedImage::Paint( rRect );\n if( HasFocus() )\n {\n Window *pWin = GetWindow( WINDOW_BORDER );\n\n BOOL bFlat = (GetBorderStyle() == 2);\n Rectangle aRect( Point(0,0), pWin->GetOutputSizePixel() );\n Color oldLineCol = pWin->GetLineColor();\n Color oldFillCol = pWin->GetFillColor();\n pWin->SetFillColor();\n pWin->SetLineColor( bFlat ? COL_WHITE : COL_BLACK );\n pWin->DrawRect( aRect );\n aRect.nLeft++;\n aRect.nRight--;\n aRect.nTop++;\n aRect.nBottom--;\n pWin->SetLineColor( bFlat ? COL_BLACK : COL_WHITE );\n pWin->DrawRect( aRect );\n pWin->SetLineColor( oldLineCol );\n pWin->SetFillColor( oldFillCol );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::GetFocus()\n{\n FixedImage::GetFocus();\n GetWindow( WINDOW_BORDER )->Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImageControl::LoseFocus()\n{\n FixedImage::GetFocus();\n GetWindow( WINDOW_BORDER )->Invalidate();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n\/\/ This module\n#include \"ParameterDialog.h\"\n\/\/ This application\n#include \"ConfigFile.h\"\n#include \"DeferredParameterEdit.h\"\n#include \"SimpleParameter.h\"\n#include \"SimpleParameterEdit.h\"\n#include \"params\/Generator.h\"\n#include \"params\/Type.h\"\n\/\/ The Qt library\n#include <QAction>\n#include <QFrame>\n#include <QGridLayout>\n#include <QGroupBox>\n#include <qlabel.h>\n#include <qlayout.h>\n#include <qmessagebox.h>\n#include <qobject.h>\n#include <QScrollArea>\n#include <qstring.h>\n#include <qtooltip.h>\n\/\/ The C++ Standard Library\n#include <cassert>\n#include <typeinfo>\n\nParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,\n\t\t\t\t QDomNode const& _parentNode, \n\t\t\t\t QDomNode const& _node,\n\t\t\t\t ItemXML * _parentItem,\n\t\t\t\t ItemXML * _item,\n\t\t\t\t QWidget * _parent, const char * _name) :\n Super(_parentNode, _node, _parentItem, _item, _parent, _name),\n config_(ConfigFile::instance()),\n parameterType_(_parameterType),\n params_(config_->description().getFullParameterSet(parameterType_))\n{\n assert(!_node.isNull());\n\n initDialog();\n\n QSize s = frame_->sizeHint();\n\n if (s.width() > 800 || \n s.height() > 600) {\n\n \/\/ Replace the Frame with one in a ScrollArea\n delete frame_;\n \/\/ Create the ScrollArea as a child of the GroupBox\n QScrollArea * const sv = new QScrollArea;\n assert(sv != NULL);\n\n \/\/ Create the Frame as a child of the ScrollArea's viewport\n QWidget * const pFrameParent = sv->viewport();\n frame_ = new QFrame(pFrameParent);\n sv->setWidget(frame_);\n\n \/\/ Set the resize policy\n \/\/\/ @todo What is the counterpart of\n \/\/\/ Q3ScrollView::setResizePolicy(Q3ScrollView::AutoOneFit)?\n sv->setWidgetResizable(true);\n \n \/\/ Add the ScrollArea to the GroupBox's layout\n assert(groupBox_ != NULL);\n assert(groupBox_->layout() != NULL);\n groupBox_->layout()->addWidget(sv);\n\n initDialog();\n\n frame_->sizeHint();\n }\n\n groupBox_->sizeHint(); \/\/ we seem to need this to get the right size (hutz)\n groupBox_->setTitle(\"Parameters\");\n}\n\nvoid\nParameterDialog::setXML()\n{\n setModified(false);\n EditVector::const_iterator first, last = editFelds_.end();\n for (first = editFelds_.begin(); first != last; ++first) {\n if ((*first)->modified()) {\n (*first)->setXML();\n setModified(true);\n }\n }\n}\n\nvoid\nParameterDialog::initDialog()\n{\n editFelds_.clear();\n\n \/\/ The GridLayout is a child of the ScrollView's viewport\n QWidget * const pGridLayoutParent = frame_;\n QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);\n assert(gridLayout != 0);\n \/\/ Specify the margin but not the number of rows (params_.size(),\n \/\/ columns (3)\n const int margin = 5;\n gridLayout->setContentsMargins(margin, margin, margin, margin);\n const int spacing = 5;\n gridLayout->setSpacing(spacing);\n\n \/\/ add parameter structs:\n \/\/ Sequential position of the current parameter\n unsigned long i = 0;\n \/\/ For each parameter\n Miro::CFG::ParameterVector::const_iterator first, last = params_.end();\n for (first = params_.begin(); first != last; ++first, ++i) {\n\n \/\/ Create a Label the text of which is the parameter named capitalized.\n \/\/ Add the label to the Layout\n QLabel * name = new QLabel(frame_);\n QString n = first->name_;\n n[0] = n[0].upper();\n name->setText(n);\n gridLayout->addWidget(name, i, 0);\n\n\n \/\/ Search the QDomNode for a child the name of which is the parameter\n \/\/ name capitalized. If found, store it in parameterNode.\n QDomNode parameterNode;\n assert(parameterNode.isNull());\n\n if (!node_.isNull()) {\n parameterNode = node_.firstChild();\n while(!parameterNode.isNull()) {\n\tQDomElement e = parameterNode.toElement();\n\tif (!e.isNull() &&\n\t e.attribute(\"name\") == n)\n\t break;\n\tparameterNode = parameterNode.nextSibling();\n }\n }\n\n \/\/ If there is an existing entry and we know our QTreeWidget,\n \/\/ get the corresponding QTreeWidgetItem\n\n ItemXML * childItem = NULL;\n if (!parameterNode.isNull() &&\n\titem_ != NULL) {\n \/\/ The QDomNode was found and this dialog has a parameter ItemXML\n if (!item_->children().isEmpty()) {\n\t\/\/ The parameter ItemXML has children\n\tQObjectList childList = item_->children();\n\t\/\/ For each child of the parameter ItemXML\n QListIterator<QObject*> it(childList);\n while (it.hasNext()) {\n QObject * const c = it.next();\n\t childItem = dynamic_cast<ItemXML *>(c);\n\t \/\/ The child of the parameter ItemXML must be an ItemXML\n\t assert(childItem != NULL);\n\t \/\/ Looking for a child ItemXML whose name is that of the parameter\n\t if (childItem->node().toElement().attribute(\"name\") == n) {\n\t break;\n\t }\n\t childItem = NULL;\n\t}\n }\n }\n\n \/\/ create the dialog\n\n ParameterEdit * value;\n SimpleParameter::Type editType =\n SimpleParameter::typeFromName(first->type_);\n if (editType != SimpleParameter::NONE) {\n value = new SimpleParameterEdit(editType,\n\t\t\t\t *first,\n\t\t\t\t node_,\n\t\t\t\t parameterNode,\n\t\t\t\t item_,\n\t\t\t\t childItem,\n\t\t\t\t frame_,\n\t\t\t\t n.latin1());\n\n \/\/ add measure\n QLabel * measure = new QLabel(frame_);\n if (!first->measure_.isEmpty()) {\n\tmeasure->setText(first->measure_);\n\tQToolTip::add(measure, (first->type_ != \"angle\")? first->type_ : QString(\"double\"));\n }\n else\n\tmeasure->setText(first->type_);\n gridLayout->addWidget(measure, i, 2);\n }\n else {\n DeferredParameterEdit::EditType deferredEditType =\n\tDeferredParameterEdit::editType(first->type_);\n\n value = new DeferredParameterEdit(deferredEditType,\n\t\t\t\t\t*first,\n\t\t\t\t\tnode_,\n\t\t\t\t\tparameterNode,\n\t\t\t\t\titem_,\n\t\t\t\t\tchildItem,\n\t\t\t\t\tframe_,\n\t\t\t\t\tn.latin1());\n }\n\n gridLayout->addWidget(value->editWidget(), i, 1);\n editFelds_.push_back(value);\n\n }\n}\n<commit_msg>Removed obsolete #include<commit_after>\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n\/\/ This module\n#include \"ParameterDialog.h\"\n\/\/ This application\n#include \"ConfigFile.h\"\n#include \"DeferredParameterEdit.h\"\n#include \"SimpleParameter.h\"\n#include \"SimpleParameterEdit.h\"\n#include \"params\/Generator.h\"\n#include \"params\/Type.h\"\n\/\/ The Qt library\n#include <QAction>\n#include <QFrame>\n#include <QGridLayout>\n#include <QGroupBox>\n#include <qlabel.h>\n#include <qlayout.h>\n#include <qmessagebox.h>\n#include <qobject.h>\n#include <QScrollArea>\n#include <qstring.h>\n#include <qtooltip.h>\n\/\/ The C++ Standard Library\n#include <cassert>\n\nParameterDialog::ParameterDialog(Miro::CFG::Type const& _parameterType,\n\t\t\t\t QDomNode const& _parentNode, \n\t\t\t\t QDomNode const& _node,\n\t\t\t\t ItemXML * _parentItem,\n\t\t\t\t ItemXML * _item,\n\t\t\t\t QWidget * _parent, const char * _name) :\n Super(_parentNode, _node, _parentItem, _item, _parent, _name),\n config_(ConfigFile::instance()),\n parameterType_(_parameterType),\n params_(config_->description().getFullParameterSet(parameterType_))\n{\n assert(!_node.isNull());\n\n initDialog();\n\n QSize s = frame_->sizeHint();\n\n if (s.width() > 800 || \n s.height() > 600) {\n\n \/\/ Replace the Frame with one in a ScrollArea\n delete frame_;\n \/\/ Create the ScrollArea as a child of the GroupBox\n QScrollArea * const sv = new QScrollArea;\n assert(sv != NULL);\n\n \/\/ Create the Frame as a child of the ScrollArea's viewport\n QWidget * const pFrameParent = sv->viewport();\n frame_ = new QFrame(pFrameParent);\n sv->setWidget(frame_);\n\n \/\/ Set the resize policy\n \/\/\/ @todo What is the counterpart of\n \/\/\/ Q3ScrollView::setResizePolicy(Q3ScrollView::AutoOneFit)?\n sv->setWidgetResizable(true);\n \n \/\/ Add the ScrollArea to the GroupBox's layout\n assert(groupBox_ != NULL);\n assert(groupBox_->layout() != NULL);\n groupBox_->layout()->addWidget(sv);\n\n initDialog();\n\n frame_->sizeHint();\n }\n\n groupBox_->sizeHint(); \/\/ we seem to need this to get the right size (hutz)\n groupBox_->setTitle(\"Parameters\");\n}\n\nvoid\nParameterDialog::setXML()\n{\n setModified(false);\n EditVector::const_iterator first, last = editFelds_.end();\n for (first = editFelds_.begin(); first != last; ++first) {\n if ((*first)->modified()) {\n (*first)->setXML();\n setModified(true);\n }\n }\n}\n\nvoid\nParameterDialog::initDialog()\n{\n editFelds_.clear();\n\n \/\/ The GridLayout is a child of the ScrollView's viewport\n QWidget * const pGridLayoutParent = frame_;\n QGridLayout * const gridLayout = new QGridLayout(pGridLayoutParent);\n assert(gridLayout != 0);\n \/\/ Specify the margin but not the number of rows (params_.size(),\n \/\/ columns (3)\n const int margin = 5;\n gridLayout->setContentsMargins(margin, margin, margin, margin);\n const int spacing = 5;\n gridLayout->setSpacing(spacing);\n\n \/\/ add parameter structs:\n \/\/ Sequential position of the current parameter\n unsigned long i = 0;\n \/\/ For each parameter\n Miro::CFG::ParameterVector::const_iterator first, last = params_.end();\n for (first = params_.begin(); first != last; ++first, ++i) {\n\n \/\/ Create a Label the text of which is the parameter named capitalized.\n \/\/ Add the label to the Layout\n QLabel * name = new QLabel(frame_);\n QString n = first->name_;\n n[0] = n[0].upper();\n name->setText(n);\n gridLayout->addWidget(name, i, 0);\n\n\n \/\/ Search the QDomNode for a child the name of which is the parameter\n \/\/ name capitalized. If found, store it in parameterNode.\n QDomNode parameterNode;\n assert(parameterNode.isNull());\n\n if (!node_.isNull()) {\n parameterNode = node_.firstChild();\n while(!parameterNode.isNull()) {\n\tQDomElement e = parameterNode.toElement();\n\tif (!e.isNull() &&\n\t e.attribute(\"name\") == n)\n\t break;\n\tparameterNode = parameterNode.nextSibling();\n }\n }\n\n \/\/ If there is an existing entry and we know our QTreeWidget,\n \/\/ get the corresponding QTreeWidgetItem\n\n ItemXML * childItem = NULL;\n if (!parameterNode.isNull() &&\n\titem_ != NULL) {\n \/\/ The QDomNode was found and this dialog has a parameter ItemXML\n if (!item_->children().isEmpty()) {\n\t\/\/ The parameter ItemXML has children\n\tQObjectList childList = item_->children();\n\t\/\/ For each child of the parameter ItemXML\n QListIterator<QObject*> it(childList);\n while (it.hasNext()) {\n QObject * const c = it.next();\n\t childItem = dynamic_cast<ItemXML *>(c);\n\t \/\/ The child of the parameter ItemXML must be an ItemXML\n\t assert(childItem != NULL);\n\t \/\/ Looking for a child ItemXML whose name is that of the parameter\n\t if (childItem->node().toElement().attribute(\"name\") == n) {\n\t break;\n\t }\n\t childItem = NULL;\n\t}\n }\n }\n\n \/\/ create the dialog\n\n ParameterEdit * value;\n SimpleParameter::Type editType =\n SimpleParameter::typeFromName(first->type_);\n if (editType != SimpleParameter::NONE) {\n value = new SimpleParameterEdit(editType,\n\t\t\t\t *first,\n\t\t\t\t node_,\n\t\t\t\t parameterNode,\n\t\t\t\t item_,\n\t\t\t\t childItem,\n\t\t\t\t frame_,\n\t\t\t\t n.latin1());\n\n \/\/ add measure\n QLabel * measure = new QLabel(frame_);\n if (!first->measure_.isEmpty()) {\n\tmeasure->setText(first->measure_);\n\tQToolTip::add(measure, (first->type_ != \"angle\")? first->type_ : QString(\"double\"));\n }\n else\n\tmeasure->setText(first->type_);\n gridLayout->addWidget(measure, i, 2);\n }\n else {\n DeferredParameterEdit::EditType deferredEditType =\n\tDeferredParameterEdit::editType(first->type_);\n\n value = new DeferredParameterEdit(deferredEditType,\n\t\t\t\t\t*first,\n\t\t\t\t\tnode_,\n\t\t\t\t\tparameterNode,\n\t\t\t\t\titem_,\n\t\t\t\t\tchildItem,\n\t\t\t\t\tframe_,\n\t\t\t\t\tn.latin1());\n }\n\n gridLayout->addWidget(value->editWidget(), i, 1);\n editFelds_.push_back(value);\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/point_types.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n#include <pcl\/surface\/mls.h>\n#include <pcl\/filters\/voxel_grid.h>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_polynomial_order = 2;\nbool default_use_polynomial_fit = false;\ndouble default_search_radius = 0.0,\n default_sqr_gauss_param = 0.0;\n\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -search_radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: \");\n print_value (\"%f\", default_search_radius); print_info (\")\\n\");\n print_info (\" -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: \");\n print_value (\"%f\", default_sqr_gauss_param); print_info (\")\\n\");\n print_info (\" -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: \");\n print_value (\"%d\", default_use_polynomial_fit); print_info (\")\\n\");\n print_info (\" -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: \");\n print_value (\"%d\", default_polynomial_order); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,\n bool use_polynomial_fit, int polynomial_order)\n{\n\n PointCloud<PointXYZ>::Ptr xyz_cloud_pre (new pcl::PointCloud<PointXYZ> ()),\n xyz_cloud (new pcl::PointCloud<PointXYZ> ());\n fromROSMsg (*input, *xyz_cloud_pre);\n\n \/\/ Filter the NaNs from the cloud\n for (size_t i = 0; i < xyz_cloud_pre->size (); ++i)\n if (pcl_isfinite (xyz_cloud_pre->points[i].x))\n xyz_cloud->push_back (xyz_cloud_pre->points[i]);\n xyz_cloud->header = xyz_cloud_pre->header;\n xyz_cloud->height = 1;\n xyz_cloud->width = static_cast<uint32_t> (xyz_cloud->size ());\n xyz_cloud->is_dense = false;\n \n \n\n PointCloud<PointNormal>::Ptr xyz_cloud_smoothed (new PointCloud<PointNormal> ());\n\n MovingLeastSquares<PointXYZ, PointNormal> mls;\n mls.setInputCloud (xyz_cloud);\n mls.setSearchRadius (search_radius);\n if (sqr_gauss_param_set) mls.setSqrGaussParam (sqr_gauss_param);\n mls.setPolynomialFit (use_polynomial_fit);\n mls.setPolynomialOrder (polynomial_order);\n\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::SAMPLE_LOCAL_PLANE);\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::RANDOM_UNIFORM_DENSITY);\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::VOXEL_GRID_DILATION);\n mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::NONE);\n mls.setPointDensity (60000 * int (search_radius)); \/\/ 300 points in a 5 cm radius\n mls.setUpsamplingRadius (0.025);\n mls.setUpsamplingStepSize (0.015);\n mls.setDilationIterations (2);\n mls.setDilationVoxelSize (0.01f);\n\n search::KdTree<PointXYZ>::Ptr tree (new search::KdTree<PointXYZ> ());\n mls.setSearchMethod (tree);\n mls.setComputeNormals (true);\n\n PCL_INFO (\"Computing smoothed surface and normals with search_radius %f , sqr_gaussian_param %f, polynomial fitting %d, polynomial order %d\\n\",\n mls.getSearchRadius(), mls.getSqrGaussParam(), mls.getPolynomialFit(), mls.getPolynomialOrder());\n TicToc tt;\n tt.tic ();\n mls.process (*xyz_cloud_smoothed);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", xyz_cloud_smoothed->width * xyz_cloud_smoothed->height); print_info (\" points]\\n\");\n\n toROSMsg (*xyz_cloud_smoothed, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),\n Eigen::Quaternionf::Identity (), true);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n double search_radius = default_search_radius;\n double sqr_gauss_param = default_sqr_gauss_param;\n bool sqr_gauss_param_set = true;\n int polynomial_order = default_polynomial_order;\n bool use_polynomial_fit = default_use_polynomial_fit;\n\n parse_argument (argc, argv, \"-search_radius\", search_radius);\n if (parse_argument (argc, argv, \"-sqr_gauss_param\", sqr_gauss_param) == -1)\n sqr_gauss_param_set = false;\n if (parse_argument (argc, argv, \"-polynomial_order\", polynomial_order) != -1 )\n use_polynomial_fit = true;\n parse_argument (argc, argv, \"-use_polynomial_fit\", use_polynomial_fit);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud))\n return (-1);\n\n \/\/ Do the smoothing\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, search_radius, sqr_gauss_param_set, sqr_gauss_param,\n use_polynomial_fit, polynomial_order);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n<commit_msg>search_radius -> radius<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/point_types.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n#include <pcl\/surface\/mls.h>\n#include <pcl\/filters\/voxel_grid.h>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_polynomial_order = 2;\nbool default_use_polynomial_fit = false;\ndouble default_search_radius = 0.0,\n default_sqr_gauss_param = 0.0;\n\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: \");\n print_value (\"%f\", default_search_radius); print_info (\")\\n\");\n print_info (\" -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: \");\n print_value (\"%f\", default_sqr_gauss_param); print_info (\")\\n\");\n print_info (\" -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: \");\n print_value (\"%d\", default_use_polynomial_fit); print_info (\")\\n\");\n print_info (\" -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: \");\n print_value (\"%d\", default_polynomial_order); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,\n bool use_polynomial_fit, int polynomial_order)\n{\n\n PointCloud<PointXYZ>::Ptr xyz_cloud_pre (new pcl::PointCloud<PointXYZ> ()),\n xyz_cloud (new pcl::PointCloud<PointXYZ> ());\n fromROSMsg (*input, *xyz_cloud_pre);\n\n \/\/ Filter the NaNs from the cloud\n for (size_t i = 0; i < xyz_cloud_pre->size (); ++i)\n if (pcl_isfinite (xyz_cloud_pre->points[i].x))\n xyz_cloud->push_back (xyz_cloud_pre->points[i]);\n xyz_cloud->header = xyz_cloud_pre->header;\n xyz_cloud->height = 1;\n xyz_cloud->width = static_cast<uint32_t> (xyz_cloud->size ());\n xyz_cloud->is_dense = false;\n \n \n\n PointCloud<PointNormal>::Ptr xyz_cloud_smoothed (new PointCloud<PointNormal> ());\n\n MovingLeastSquares<PointXYZ, PointNormal> mls;\n mls.setInputCloud (xyz_cloud);\n mls.setSearchRadius (search_radius);\n if (sqr_gauss_param_set) mls.setSqrGaussParam (sqr_gauss_param);\n mls.setPolynomialFit (use_polynomial_fit);\n mls.setPolynomialOrder (polynomial_order);\n\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::SAMPLE_LOCAL_PLANE);\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::RANDOM_UNIFORM_DENSITY);\n\/\/ mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::VOXEL_GRID_DILATION);\n mls.setUpsamplingMethod (MovingLeastSquares<PointXYZ, PointNormal>::NONE);\n mls.setPointDensity (60000 * int (search_radius)); \/\/ 300 points in a 5 cm radius\n mls.setUpsamplingRadius (0.025);\n mls.setUpsamplingStepSize (0.015);\n mls.setDilationIterations (2);\n mls.setDilationVoxelSize (0.01f);\n\n search::KdTree<PointXYZ>::Ptr tree (new search::KdTree<PointXYZ> ());\n mls.setSearchMethod (tree);\n mls.setComputeNormals (true);\n\n PCL_INFO (\"Computing smoothed surface and normals with search_radius %f , sqr_gaussian_param %f, polynomial fitting %d, polynomial order %d\\n\",\n mls.getSearchRadius(), mls.getSqrGaussParam(), mls.getPolynomialFit(), mls.getPolynomialOrder());\n TicToc tt;\n tt.tic ();\n mls.process (*xyz_cloud_smoothed);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", xyz_cloud_smoothed->width * xyz_cloud_smoothed->height); print_info (\" points]\\n\");\n\n toROSMsg (*xyz_cloud_smoothed, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n\n pcl::io::savePCDFile (filename, output, Eigen::Vector4f::Zero (),\n Eigen::Quaternionf::Identity (), true);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Moving Least Squares smoothing of a point cloud. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n double search_radius = default_search_radius;\n double sqr_gauss_param = default_sqr_gauss_param;\n bool sqr_gauss_param_set = true;\n int polynomial_order = default_polynomial_order;\n bool use_polynomial_fit = default_use_polynomial_fit;\n\n parse_argument (argc, argv, \"-radius\", search_radius);\n if (parse_argument (argc, argv, \"-sqr_gauss_param\", sqr_gauss_param) == -1)\n sqr_gauss_param_set = false;\n if (parse_argument (argc, argv, \"-polynomial_order\", polynomial_order) != -1 )\n use_polynomial_fit = true;\n parse_argument (argc, argv, \"-use_polynomial_fit\", use_polynomial_fit);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud))\n return (-1);\n\n \/\/ Do the smoothing\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, search_radius, sqr_gauss_param_set, sqr_gauss_param,\n use_polynomial_fit, polynomial_order);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cstring>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing namespace std;\n\nbool CompareCharacters(const char *expected, char **actual) {\n const size_t length = strlen(expected);\n bool result = true;\n for (size_t i = 0; i < length; ++i) {\n result &= expected[i] == (*actual)[i];\n }\n\n \/*\n char buf[length + 1];\n for (size_t i = 0; i < length; ++i) {\n buf[i] = (*actual)[i];\n }\n buf[length] = '\\0';\n cerr << \"expected: \" << expected << \", actual: \" << buf << endl;\n *\/\n *actual += length;\n return result;\n}\n\nstring ReadString(size_t size, char **buf) {\n string str(*buf, 0, size);\n *buf += size;\n return str;\n}\n\nint ReadNumber(char **buf, size_t size) {\n int result;\n unsigned int mask;\n switch (size) {\n case 2:\n result = static_cast<int>(*reinterpret_cast<short *>(*buf));\n break;\n case 3:\n\/\/ result = (*buf)[0] | ((*buf)[1] << 8) | ((*buf)[2] << 16) | (-(((*buf)[2] & 0x80) << 17));\n mask = ((*buf)[2] & 0x80) ? 0xFF000000 : 0x0;\n result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | mask);\n\/\/ result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | (-(((*buf)[2] & 0x80) << 17)));\n break;\n case 4:\n result = *reinterpret_cast<int *>(*buf);\n break;\n }\n *buf += size;\n return result; \n}\n\nshort ReadShort(char **buf) {\n const short result = *reinterpret_cast<short *>(*buf);\n *buf += 2;\n return result;\n}\n\nunsigned int ReadUnsignedInt(char **buf) {\n const unsigned int result = *reinterpret_cast<int *>(*buf);\n *buf += 4;\n return result;\n}\n\nunsigned short ReadUnsignedShort(char **buf) {\n const unsigned short result = *reinterpret_cast<unsigned short *>(*buf);\n *buf += 2;\n return result;\n}\n\nstring SamplingToTime(size_t sampling_counter, size_t sampling_rate) {\n stringstream ss;\n const int milli_seconds = 1000 * sampling_counter \/ sampling_rate;\n const int seconds = milli_seconds \/ 1000;\n ss << seconds << \".\" << setfill('0') << setw(3) << (milli_seconds % 1000);\n \/*\n const int minutes = seconds \/ 60;\n const int hours = minutes \/ 60;\n ss << setfill('0') << setw(2) << hours\n << \":\"\n << setfill('0') << setw(2) << minutes % 60\n << \":\"\n << setfill('0') << setw(2) << seconds % 60\n << \".\"\n << setfill('0') << setw(3) << milli_seconds % 1000;\n *\/\n return ss.str();\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" filename\" << endl;\n return -1;\n }\n\n ifstream ifs(argv[1]);\n if (!ifs) {\n cerr << \"Failed to open file: \" << argv[1] << endl;\n return -1;\n }\n ifs.seekg(0, std::ios::end);\n const size_t file_size = static_cast<size_t>(ifs.tellg());\n ifs.seekg(0, std::ios::beg);\n\n char *file_buf_head = new char[file_size + 1]; \/\/ + 1 is for 24bit PCM (ReadNumber)\n char *file_buf_ptr = file_buf_head;\n if (!ifs.read(file_buf_head, file_size)) {\n cerr << \"Failed to read the file.\" << endl;\n return -1;\n }\n\n if (!CompareCharacters(\"RIFF\", &file_buf_ptr)) {\n cerr << \"Invalid RIFF format.\" << endl;\n return -1;\n }\n\n if (ReadUnsignedInt(&file_buf_ptr) + 8 != file_size) {\n cerr << \"Invalid file size.\" << endl;\n cerr << \"pos: \" << (file_buf_ptr - file_buf_head) << endl;\n return -1;\n }\n\n if (!CompareCharacters(\"WAVEfmt \", &file_buf_ptr)) {\n cerr << \"Invalid WAVE format.\" << endl;\n cerr << \"pos: \" << (file_buf_ptr - file_buf_head) << endl;\n return -1;\n }\n\n const size_t fmt_size = ReadUnsignedInt(&file_buf_ptr);\n const unsigned short format_id = ReadUnsignedShort(&file_buf_ptr);\n \/\/ ffmpeg output invalid format_id for 24bit or 32bit PCM.\n \/\/ if (format_id != 1) {\n \/\/ cerr << \"Invalid format ID: \" << format_id << endl;\n \/\/ return -1;\n \/\/ }\n\n const int channel_num = ReadUnsignedShort(&file_buf_ptr);\n const int sampling_rate = ReadUnsignedInt(&file_buf_ptr);\n const int sampling_bytes =\n ReadUnsignedInt(&file_buf_ptr) \/ channel_num \/ sampling_rate;\n if (sampling_bytes < 2 || 4 < sampling_bytes) {\n cerr << \"Unsupported sampling bytes: \" << sampling_bytes << endl;\n return -1;\n }\n if (ReadUnsignedShort(&file_buf_ptr) != channel_num * sampling_bytes) {\n cerr << \"Invalid block size.\" << endl;\n return -1;\n }\n if (ReadUnsignedShort(&file_buf_ptr) != sampling_bytes * 8) {\n cerr << \"Invalid sampling bits.\" << endl;\n return -1;\n }\n\n const size_t extend_header_size = ReadUnsignedShort(&file_buf_ptr);\n file_buf_ptr += extend_header_size;\n\n while (true) {\n if (file_buf_ptr - file_buf_head > 1024 - 4) {\n cerr << \"Too big header.\" << endl;\n return -1;\n }\n if (CompareCharacters(\"data\", &file_buf_ptr)) {\n break;\n }\n size_t chunk_size = ReadUnsignedInt(&file_buf_ptr);\n file_buf_ptr += chunk_size;\n }\n\n const size_t data_size = ReadUnsignedInt(&file_buf_ptr);\n if (data_size + (file_buf_ptr - file_buf_head) != file_size) {\n cerr << \"Invalid data size.\" << endl;\n return -1;\n }\n\n vector<pair<size_t, size_t> > mute_ranges;\n const int kVolumeThreshold = 12 * (1 << ((sampling_bytes - 2) * 8));\n const int kVolumeDiffThreshold = 2;\n const int minimum_mute_chunk_threshold = sampling_rate \/ 100; \/\/ 10msec\n int mute_counter = 0;\n const size_t max_sampling_count = data_size \/ (sampling_bytes * channel_num);\n\n for (size_t sampling_counter = 0; sampling_counter < max_sampling_count;\n ++sampling_counter) {\n const int left_sound = ReadNumber(&file_buf_ptr, sampling_bytes);\n const int right_sound = ReadNumber(&file_buf_ptr, sampling_bytes);\n\n \/\/ TODO: It may be better to use the differences from the previous values.\n if (abs(left_sound) <= kVolumeThreshold && abs(right_sound) <= kVolumeThreshold) { \n ++mute_counter;\n if (mute_counter == minimum_mute_chunk_threshold) {\n mute_ranges.push_back(make_pair(sampling_counter - minimum_mute_chunk_threshold + 1, 0));\n }\n } else {\n if (mute_counter >= minimum_mute_chunk_threshold) {\n mute_counter = 0;\n mute_ranges.back().second = sampling_counter - 1;\n }\n }\n }\n\n const size_t concat_threshold = sampling_rate \/ 1000; \/\/ 1msec\n for (size_t i = 1; i < mute_ranges.size(); ++i) {\n if (mute_ranges[i].first - mute_ranges[i - 1].second < concat_threshold) {\n mute_ranges[i - 1].second = mute_ranges[i].second;\n mute_ranges.erase(mute_ranges.begin() + i);\n --i;\n }\n }\n const size_t mute_chunk_threshold = sampling_rate * 0.3; \/\/ 300msec\n for (int i = 0; i < static_cast<int>(mute_ranges.size()); ++i) {\n if (mute_ranges[i].second - mute_ranges[i].first < mute_chunk_threshold) {\n mute_ranges.erase(mute_ranges.begin() + i);\n --i;\n }\n }\n\n cout << \"all 0.000 \" << SamplingToTime(max_sampling_count, sampling_rate) << endl;\n \/\/ Margin for body.\n \/\/ Silence ranges in some body have high-level noise.\n \/\/ On the other hand, CM doesn't have.\n \/\/ This margin improves the handling of such kind of body.\n const size_t margin = sampling_rate * 1001.0 \/ 30000.0 + 5;\n for (size_t i = 0; i < mute_ranges.size(); ++i) {\n const pair<size_t, size_t> &range = mute_ranges[i];\n const size_t start = (range.first > margin) ? range.first - margin : 0;\n const size_t end = min(max_sampling_count, range.second + margin);\n cout << SamplingToTime(start, sampling_rate) << \" \"\n << SamplingToTime(end, sampling_rate) << endl;\n }\n\n delete [] file_buf_head;\n\n return 0;\n}\n<commit_msg>Handle a last silence range correctly by silence_detector.<commit_after>#include <cmath>\n#include <cstring>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing namespace std;\n\nbool CompareCharacters(const char *expected, char **actual) {\n const size_t length = strlen(expected);\n bool result = true;\n for (size_t i = 0; i < length; ++i) {\n result &= expected[i] == (*actual)[i];\n }\n\n *actual += length;\n return result;\n}\n\nstring ReadString(size_t size, char **buf) {\n string str(*buf, 0, size);\n *buf += size;\n return str;\n}\n\nint ReadNumber(char **buf, size_t size) {\n int result;\n unsigned int mask;\n switch (size) {\n case 2:\n result = static_cast<int>(*reinterpret_cast<short *>(*buf));\n break;\n case 3:\n mask = ((*buf)[2] & 0x80) ? 0xFF000000 : 0x0;\n result = static_cast<int>((*reinterpret_cast<unsigned int *>(*buf) & 0x00FFFFFF) | mask);\n break;\n case 4:\n result = *reinterpret_cast<int *>(*buf);\n break;\n }\n *buf += size;\n return result; \n}\n\nshort ReadShort(char **buf) {\n const short result = *reinterpret_cast<short *>(*buf);\n *buf += 2;\n return result;\n}\n\nunsigned int ReadUnsignedInt(char **buf) {\n const unsigned int result = *reinterpret_cast<int *>(*buf);\n *buf += 4;\n return result;\n}\n\nunsigned short ReadUnsignedShort(char **buf) {\n const unsigned short result = *reinterpret_cast<unsigned short *>(*buf);\n *buf += 2;\n return result;\n}\n\nstring SamplingToTime(size_t sampling_counter, size_t sampling_rate) {\n stringstream ss;\n const int milli_seconds = 1000 * sampling_counter \/ sampling_rate;\n const int seconds = milli_seconds \/ 1000;\n ss << seconds << \".\" << setfill('0') << setw(3) << (milli_seconds % 1000);\n return ss.str();\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" filename\" << endl;\n return -1;\n }\n\n ifstream ifs(argv[1]);\n if (!ifs) {\n cerr << \"Failed to open file: \" << argv[1] << endl;\n return -1;\n }\n ifs.seekg(0, std::ios::end);\n const size_t file_size = static_cast<size_t>(ifs.tellg());\n ifs.seekg(0, std::ios::beg);\n\n char *file_buf_head = new char[file_size + 1]; \/\/ + 1 is for 24bit PCM (ReadNumber)\n char *file_buf_ptr = file_buf_head;\n if (!ifs.read(file_buf_head, file_size)) {\n cerr << \"Failed to read the file.\" << endl;\n return -1;\n }\n\n if (!CompareCharacters(\"RIFF\", &file_buf_ptr)) {\n cerr << \"Invalid RIFF format.\" << endl;\n return -1;\n }\n\n if (ReadUnsignedInt(&file_buf_ptr) + 8 != file_size) {\n cerr << \"Invalid file size.\" << endl;\n cerr << \"pos: \" << (file_buf_ptr - file_buf_head) << endl;\n return -1;\n }\n\n if (!CompareCharacters(\"WAVEfmt \", &file_buf_ptr)) {\n cerr << \"Invalid WAVE format.\" << endl;\n cerr << \"pos: \" << (file_buf_ptr - file_buf_head) << endl;\n return -1;\n }\n\n const size_t fmt_size = ReadUnsignedInt(&file_buf_ptr);\n const unsigned short format_id = ReadUnsignedShort(&file_buf_ptr);\n\n const int channel_num = ReadUnsignedShort(&file_buf_ptr);\n const int sampling_rate = ReadUnsignedInt(&file_buf_ptr);\n const int sampling_bytes =\n ReadUnsignedInt(&file_buf_ptr) \/ channel_num \/ sampling_rate;\n if (sampling_bytes < 2 || 4 < sampling_bytes) {\n cerr << \"Unsupported sampling bytes: \" << sampling_bytes << endl;\n return -1;\n }\n if (ReadUnsignedShort(&file_buf_ptr) != channel_num * sampling_bytes) {\n cerr << \"Invalid block size.\" << endl;\n return -1;\n }\n if (ReadUnsignedShort(&file_buf_ptr) != sampling_bytes * 8) {\n cerr << \"Invalid sampling bits.\" << endl;\n return -1;\n }\n\n const size_t extend_header_size = ReadUnsignedShort(&file_buf_ptr);\n file_buf_ptr += extend_header_size;\n\n while (true) {\n if (file_buf_ptr - file_buf_head > 1024 - 4) {\n cerr << \"Too big header.\" << endl;\n return -1;\n }\n if (CompareCharacters(\"data\", &file_buf_ptr)) {\n break;\n }\n size_t chunk_size = ReadUnsignedInt(&file_buf_ptr);\n file_buf_ptr += chunk_size;\n }\n\n const size_t data_size = ReadUnsignedInt(&file_buf_ptr);\n if (data_size + (file_buf_ptr - file_buf_head) != file_size) {\n cerr << \"Invalid data size.\" << endl;\n return -1;\n }\n\n vector<pair<size_t, size_t> > mute_ranges;\n const int kVolumeThreshold = 12 * (1 << ((sampling_bytes - 2) * 8));\n const int kVolumeDiffThreshold = 2;\n const int minimum_mute_chunk_threshold = sampling_rate \/ 100; \/\/ 10msec\n int mute_counter = 0;\n const size_t max_sampling_count = data_size \/ (sampling_bytes * channel_num);\n\n for (size_t sampling_counter = 0; sampling_counter < max_sampling_count;\n ++sampling_counter) {\n const int left_sound = ReadNumber(&file_buf_ptr, sampling_bytes);\n const int right_sound = ReadNumber(&file_buf_ptr, sampling_bytes);\n\n if (abs(left_sound) <= kVolumeThreshold && abs(right_sound) <= kVolumeThreshold) { \n ++mute_counter;\n if (mute_counter == minimum_mute_chunk_threshold) {\n mute_ranges.push_back(make_pair(sampling_counter - minimum_mute_chunk_threshold + 1,\n max_sampling_count));\n }\n } else {\n if (mute_counter >= minimum_mute_chunk_threshold) {\n mute_counter = 0;\n mute_ranges.back().second = sampling_counter - 1;\n }\n }\n }\n\n const size_t concat_threshold = sampling_rate \/ 1000; \/\/ 1msec\n for (size_t i = 1; i < mute_ranges.size(); ++i) {\n if (mute_ranges[i].first - mute_ranges[i - 1].second < concat_threshold) {\n mute_ranges[i - 1].second = mute_ranges[i].second;\n mute_ranges.erase(mute_ranges.begin() + i);\n --i;\n }\n }\n const size_t mute_chunk_threshold = sampling_rate * 0.3; \/\/ 300msec\n for (int i = 0; i < static_cast<int>(mute_ranges.size()); ++i) {\n if (mute_ranges[i].second - mute_ranges[i].first < mute_chunk_threshold) {\n mute_ranges.erase(mute_ranges.begin() + i);\n --i;\n }\n }\n\n cout << \"all 0.000 \" << SamplingToTime(max_sampling_count, sampling_rate) << endl;\n \/\/ Margin for body.\n \/\/ Silence ranges in some body have high-level noise.\n \/\/ On the other hand, CM doesn't have.\n \/\/ This margin improves the handling of such kind of body.\n const size_t margin = sampling_rate * 1001.0 \/ 30000.0 + 5;\n for (size_t i = 0; i < mute_ranges.size(); ++i) {\n const pair<size_t, size_t> &range = mute_ranges[i];\n const size_t start = (range.first > margin) ? range.first - margin : 0;\n const size_t end = min(max_sampling_count, range.second + margin);\n cout << SamplingToTime(start, sampling_rate) << \" \"\n << SamplingToTime(end, sampling_rate) << endl;\n }\n\n delete [] file_buf_head;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Non-metric Space Library\n *\n * Authors: Bilegsaikhan Naidan (https:\/\/github.com\/bileg), Leonid Boytsov (http:\/\/boytsov.info).\n * With contributions from Lawrence Cayton (http:\/\/lcayton.com\/) and others.\n *\n * For the complete list of contributors and further details see:\n * https:\/\/github.com\/searchivarius\/NonMetricSpaceLib \n * \n * Copyright (c) 2014\n *\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n#ifndef _MSC_VER\n\n#include <sys\/time.h>\n\n#include \"logging.h\"\n#include \"ztimer.h\"\n#include \"bunit.h\"\n\nnamespace similarity {\n\nconst unsigned TIMER_ERR_TOL = 1000;\n\n\/*\n * These test is intended to run only on Unix-like systems.\n *\/\n\n\/**\n * author: Preston Bannister\n *\/\nclass WallClockTimerBannister {\npublic:\n struct timeval t1, t2;\n WallClockTimerBannister() :\n t1(), t2() {\n gettimeofday(&t1, 0);\n t2 = t1;\n }\n void reset() {\n gettimeofday(&t1, 0);\n t2 = t1;\n }\n uint64_t elapsed() {\n return ((t2.tv_sec - t1.tv_sec) * 1000ULL * 1000ULL) + ((t2.tv_usec - t1. tv_usec));\n }\n uint64_t split() {\n gettimeofday(&t2, 0);\n return elapsed();\n }\n};\n\nvoid BurnCPU(size_t qty = 10000000000) {\n size_t sum = 0;\n for (size_t i = 0; i < qty; ++i) {\n sum += i;\n sum *= qty;\n }\n LOG(LIB_INFO) << \"Ignore: \" << sum;\n}\n\n#ifdef DISABLE_LONG_TESTS\nTEST(DISABLE_TestTimer) {\n#else\nTEST(TestTimer) {\n#endif\n WallClockTimerBannister oldz;\n WallClockTimer z;\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n\n z.reset();\n oldz.reset();\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n}\n\n} \/\/ namespace similarity\n#endif\n\n<commit_msg>Further decreasing tolerance threshold in timer testing.<commit_after>\/**\n * Non-metric Space Library\n *\n * Authors: Bilegsaikhan Naidan (https:\/\/github.com\/bileg), Leonid Boytsov (http:\/\/boytsov.info).\n * With contributions from Lawrence Cayton (http:\/\/lcayton.com\/) and others.\n *\n * For the complete list of contributors and further details see:\n * https:\/\/github.com\/searchivarius\/NonMetricSpaceLib \n * \n * Copyright (c) 2014\n *\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n#ifndef _MSC_VER\n\n#include <sys\/time.h>\n\n#include \"logging.h\"\n#include \"ztimer.h\"\n#include \"bunit.h\"\n\nnamespace similarity {\n\nconst unsigned TIMER_ERR_TOL = 2000;\n\n\/*\n * These test is intended to run only on Unix-like systems.\n *\/\n\n\/**\n * author: Preston Bannister\n *\/\nclass WallClockTimerBannister {\npublic:\n struct timeval t1, t2;\n WallClockTimerBannister() :\n t1(), t2() {\n gettimeofday(&t1, 0);\n t2 = t1;\n }\n void reset() {\n gettimeofday(&t1, 0);\n t2 = t1;\n }\n uint64_t elapsed() {\n return ((t2.tv_sec - t1.tv_sec) * 1000ULL * 1000ULL) + ((t2.tv_usec - t1. tv_usec));\n }\n uint64_t split() {\n gettimeofday(&t2, 0);\n return elapsed();\n }\n};\n\nvoid BurnCPU(size_t qty = 10000000000) {\n size_t sum = 0;\n for (size_t i = 0; i < qty; ++i) {\n sum += i;\n sum *= qty;\n }\n LOG(LIB_INFO) << \"Ignore: \" << sum;\n}\n\n#ifdef DISABLE_LONG_TESTS\nTEST(DISABLE_TestTimer) {\n#else\nTEST(TestTimer) {\n#endif\n WallClockTimerBannister oldz;\n WallClockTimer z;\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n\n z.reset();\n oldz.reset();\n\n BurnCPU();\n oldz.split();\n z.split();\n\n LOG(LIB_INFO) << \"Timer: \" << z.elapsed() << \" : \" << oldz.elapsed();\n \/\/ We expect both timers to differ in at most 0.1 ms\n EXPECT_EQ(std::abs(static_cast<int64_t>(z.elapsed()) - static_cast<int64_t>(oldz.elapsed())) < TIMER_ERR_TOL, true);\n}\n\n} \/\/ namespace similarity\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef IOX_POSH_POPO_WAITSET_CONDITION_HPP\n#define IOX_POSH_POPO_WAITSET_CONDITION_HPP\n\n#include \"iceoryx_posh\/iceoryx_posh_types.hpp\"\n#include \"iceoryx_posh\/mepoo\/memory_info.hpp\"\n\nnamespace iox\n{\nnamespace popo\n{\nstruct ConditionVariableWaiter\n{\n ConditionVariablewaiters(const mepoo::MemoryInfo& memoryInfo = mepoo::MemoryInfo()) noexcept\n : m_memoryInfo(memoryInfo)\n {\n }\n\n mepoo::MemoryInfo m_memoryInfo;\n};\n\n} \/\/ namespace popo\n} \/\/ namespace iox\n\n#endif \/\/ IOX_POSH_POPO_WAITSET_CONDITION_HPP\n<commit_msg>iox-#25: Fix typo<commit_after>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef IOX_POSH_POPO_WAITSET_CONDITION_HPP\n#define IOX_POSH_POPO_WAITSET_CONDITION_HPP\n\n#include \"iceoryx_posh\/iceoryx_posh_types.hpp\"\n#include \"iceoryx_posh\/mepoo\/memory_info.hpp\"\n\nnamespace iox\n{\nnamespace popo\n{\nstruct ConditionVariableWaiter\n{\n ConditionVariableWaiter(const mepoo::MemoryInfo& memoryInfo = mepoo::MemoryInfo()) noexcept\n : m_memoryInfo(memoryInfo)\n {\n }\n\n mepoo::MemoryInfo m_memoryInfo;\n};\n\n} \/\/ namespace popo\n} \/\/ namespace iox\n\n#endif \/\/ IOX_POSH_POPO_WAITSET_CONDITION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#ifdef USE_WEBSOCKETS\n\n#include \"deconz\/dbg_trace.h\"\n#include \"websocket_server.h\"\n\n\/*! Constructor.\n *\/\nWebSocketServer::WebSocketServer(QObject *parent, quint16 port) :\n QObject(parent)\n{\n srv = new QWebSocketServer(\"deconz\", QWebSocketServer::NonSecureMode, this);\n\n quint16 p = 0;\n quint16 ports[] = { 443, 443, 8080, 8088, 20877, 0 }; \/\/ start with proxy frinedly ports first, use random port as fallback\n if (port > 0)\n {\n ports[0] = port;\n }\n\n while (!srv->listen(QHostAddress::AnyIPv4, ports[p]))\n {\n if (ports[p] == 0)\n {\n DBG_Printf(DBG_ERROR, \"giveup starting websocket server on port %u. error: %s\\n\", ports[p], qPrintable(srv->errorString()));\n break;\n }\n\n DBG_Printf(DBG_ERROR, \"failed to start websocket server on port %u. error: %s\\n\", ports[p], qPrintable(srv->errorString()));\n p++;\n }\n\n if (srv->isListening())\n {\n DBG_Printf(DBG_INFO, \"started websocket server at port %u\\n\", srv->serverPort());\n connect(srv, SIGNAL(newConnection()), this, SLOT(onNewConnection()));\n }\n}\n\n\/*! Returns the websocket server port.\n \\return the active server port, or 0 if not active\n *\/\nquint16 WebSocketServer::port() const\n{\n return srv->isListening() ? srv->serverPort() : 0;\n}\n\n\/*! Handler for new client connections.\n *\/\nvoid WebSocketServer::onNewConnection()\n{\n while (srv->hasPendingConnections())\n {\n QWebSocket *sock = srv->nextPendingConnection();\n DBG_Printf(DBG_INFO, \"New websocket %s:%u (state: %d) \\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state());\n connect(sock, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));\n connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));\n clients.push_back(sock);\n }\n}\n\n\/*! Handle websocket disconnected signal.\n *\/\nvoid WebSocketServer::onSocketDisconnected()\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = qobject_cast<QWebSocket*>(sender());\n DBG_Assert(sock);\n if (sock && clients[i] == sock)\n {\n DBG_Printf(DBG_INFO, \"Websocket disconnected %s:%u, state: %d, close-code: %d, reason: %s\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state(), sock->closeCode(), qPrintable(sock->closeReason()));\n sock->deleteLater();\n clients[i] = clients.back();\n clients.pop_back();\n }\n }\n}\n\n\/*! Handle websocket error signal.\n \\param err - the error which occured\n *\/\nvoid WebSocketServer::onSocketError(QAbstractSocket::SocketError err)\n{\n Q_UNUSED(err);\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = qobject_cast<QWebSocket*>(sender());\n DBG_Assert(sock);\n if (sock && clients[i] == sock)\n {\n DBG_Printf(DBG_INFO, \"Remove websocket %s:%u after error %s, close-code: %d, reason: %s\\n\",\n qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(sock->errorString()), sock->closeCode(), qPrintable(sock->closeReason()));\n sock->deleteLater();\n clients[i] = clients.back();\n clients.pop_back();\n }\n }\n}\n\n\/*! Broadcasts a message to all connected clients.\n \\param msg the message as JSON string\n *\/\nvoid WebSocketServer::broadcastTextMessage(const QString &msg)\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = clients[i];\n\n if (sock->state() != QAbstractSocket::ConnectedState)\n {\n DBG_Printf(DBG_INFO, \"Websocket %s:%u unexpected state: %d\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state());\n }\n\n qint64 ret = sock->sendTextMessage(msg);\n DBG_Printf(DBG_INFO_L2, \"Websocket %s:%u send message: %s (ret = %d)\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(msg), ret);\n sock->flush();\n }\n}\n\n\/*! Flush the sockets of all connected clients.\n *\/\nvoid WebSocketServer::flush()\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = clients[i];\n\n if (sock->state() == QAbstractSocket::ConnectedState)\n {\n sock->flush();\n }\n }\n}\n\n#else \/\/ no websockets\n WebSocketServer::WebSocketServer(QObject *parent) :\n QObject(parent)\n { }\n void WebSocketServer::onNewConnection() { }\n void WebSocketServer::broadcastTextMessage(const QString &) { }\n quint16 WebSocketServer::port() const { return 0; }\n#endif\n<commit_msg>Enable websocket server to listen on IP specified<commit_after>\/*\n * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#ifdef USE_WEBSOCKETS\n\n#include \"de_web_plugin.h\"\n#include \"de_web_plugin_private.h\"\n#include \"deconz\/dbg_trace.h\"\n#include \"websocket_server.h\"\n\n\/*! Constructor.\n *\/\nWebSocketServer::WebSocketServer(QObject *parent, quint16 port) :\n QObject(parent)\n{\n srv = new QWebSocketServer(\"deconz\", QWebSocketServer::NonSecureMode, this);\n\n quint16 p = 0;\n quint16 ports[] = { 443, 443, 8080, 8088, 20877, 0 }; \/\/ start with proxy frinedly ports first, use random port as fallback\n if (port > 0)\n {\n ports[0] = port;\n }\n\n QHostAddress address;\n if (deCONZ::appArgumentString(\"--http-listen\", 0).isEmpty()) \/\/ Tie websocket server to specified IP, if any\n {\n address = QHostAddress::AnyIPv4;\n }\n else\n {\n address = deCONZ::appArgumentString(\"--http-listen\", 0);\n }\n\n while (!srv->listen(address, ports[p]))\n {\n if (ports[p] == 0)\n {\n DBG_Printf(DBG_ERROR, \"Giveup starting websocket server on %s, port: %u. error: %s\\n\", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString()));\n break;\n }\n\n DBG_Printf(DBG_ERROR, \"Failed to start websocket server on %s, port: %u. error: %s\\n\", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString()));\n p++;\n }\n\n if (srv->isListening())\n {\n DBG_Printf(DBG_INFO, \"Started websocket server on %s, port: %u\\n\", qPrintable(address.toString()), srv->serverPort());\n connect(srv, SIGNAL(newConnection()), this, SLOT(onNewConnection()));\n }\n}\n\n\/*! Returns the websocket server port.\n \\return the active server port, or 0 if not active\n *\/\nquint16 WebSocketServer::port() const\n{\n return srv->isListening() ? srv->serverPort() : 0;\n}\n\n\/*! Handler for new client connections.\n *\/\nvoid WebSocketServer::onNewConnection()\n{\n while (srv->hasPendingConnections())\n {\n QWebSocket *sock = srv->nextPendingConnection();\n DBG_Printf(DBG_INFO, \"New websocket %s:%u (state: %d) \\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state());\n connect(sock, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected()));\n connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));\n clients.push_back(sock);\n }\n}\n\n\/*! Handle websocket disconnected signal.\n *\/\nvoid WebSocketServer::onSocketDisconnected()\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = qobject_cast<QWebSocket*>(sender());\n DBG_Assert(sock);\n if (sock && clients[i] == sock)\n {\n DBG_Printf(DBG_INFO, \"Websocket disconnected %s:%u, state: %d, close-code: %d, reason: %s\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state(), sock->closeCode(), qPrintable(sock->closeReason()));\n sock->deleteLater();\n clients[i] = clients.back();\n clients.pop_back();\n }\n }\n}\n\n\/*! Handle websocket error signal.\n \\param err - the error which occured\n *\/\nvoid WebSocketServer::onSocketError(QAbstractSocket::SocketError err)\n{\n Q_UNUSED(err);\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = qobject_cast<QWebSocket*>(sender());\n DBG_Assert(sock);\n if (sock && clients[i] == sock)\n {\n DBG_Printf(DBG_INFO, \"Remove websocket %s:%u after error %s, close-code: %d, reason: %s\\n\",\n qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(sock->errorString()), sock->closeCode(), qPrintable(sock->closeReason()));\n sock->deleteLater();\n clients[i] = clients.back();\n clients.pop_back();\n }\n }\n}\n\n\/*! Broadcasts a message to all connected clients.\n \\param msg the message as JSON string\n *\/\nvoid WebSocketServer::broadcastTextMessage(const QString &msg)\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = clients[i];\n\n if (sock->state() != QAbstractSocket::ConnectedState)\n {\n DBG_Printf(DBG_INFO, \"Websocket %s:%u unexpected state: %d\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state());\n }\n\n qint64 ret = sock->sendTextMessage(msg);\n DBG_Printf(DBG_INFO_L2, \"Websocket %s:%u send message: %s (ret = %d)\\n\", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(msg), ret);\n sock->flush();\n }\n}\n\n\/*! Flush the sockets of all connected clients.\n *\/\nvoid WebSocketServer::flush()\n{\n for (size_t i = 0; i < clients.size(); i++)\n {\n QWebSocket *sock = clients[i];\n\n if (sock->state() == QAbstractSocket::ConnectedState)\n {\n sock->flush();\n }\n }\n}\n\n#else \/\/ no websockets\n WebSocketServer::WebSocketServer(QObject *parent) :\n QObject(parent)\n { }\n void WebSocketServer::onNewConnection() { }\n void WebSocketServer::broadcastTextMessage(const QString &) { }\n quint16 WebSocketServer::port() const { return 0; }\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 koolkdev\n *\n * This software may be modified and distributed under the terms\n * of the MIT license. See the LICENSE file for details.\n *\/\n\n#include <cstdio>\n#include <vector>\n#include <fstream>\n#include <memory>\n#include <iostream>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n\n#include <wfslib\/WfsLib.h>\n\nvoid dumpdir(const boost::filesystem::path& target, const std::shared_ptr<Directory>& dir, const boost::filesystem::path& path, bool verbos) {\n\tif (!boost::filesystem::exists(target \/ path)) {\n\t\tif (!boost::filesystem::create_directories(target \/ path)) {\n\t\t\tstd::cerr << \"Error: Failed to create directory \" << (target \/ path) << std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\tfor (auto item : *dir) {\n\t\tboost::filesystem::path npath = path \/ item->GetRealName();\n\t\tif (verbos)\n\t\t\tstd::cout << \"Dumping \" << npath << std::endl;\n\t\tif (item->IsDirectory()) dumpdir(target, std::dynamic_pointer_cast<Directory>(item), npath, verbos);\n\t\telse if (item->IsFile()) {\n\t\t\tauto file = std::dynamic_pointer_cast<File>(item);\n\t\t\tstd::ofstream output_file((target \/ npath).string(), std::ios::binary | std::ios::out);\n\t\t\tsize_t to_read = file->GetSize();\n\t\t\tFile::stream stream(file);\n\t\t\tstd::vector<char> data(0x2000);\n\t\t\twhile (to_read > 0) {\n\t\t\t\tstream.read(&*data.begin(), std::min(data.size(), to_read));\n\t\t\t\tauto read = stream.gcount();\n\t\t\t\tif (read <= 0) {\n\t\t\t\t\tstd::cerr << \"Error: Failed to read \" << npath << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput_file.write((char*)&*data.begin(), read);\n\t\t\t\tto_read -= static_cast<size_t>(read);\n\t\t\t}\n\t\t\toutput_file.close();\n\t\t}\n\t\telse {\n\t\t\tprintf(\"Test\\n\");\n\t\t}\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\ttry {\n\t\tboost::program_options::options_description desc(\"Allowed options\");\n\t\tstd::string wfs_path;\n\t\tdesc.add_options()\n\t\t\t(\"help\", \"produce help message\")\n\t\t\t(\"input\", boost::program_options::value<std::string>(), \"input file\")\n\t\t\t(\"output\", boost::program_options::value<std::string>(), \"ouput directory\")\n\t\t\t(\"otp\", boost::program_options::value<std::string>(), \"otp file\")\n\t\t\t(\"seeprom\", boost::program_options::value<std::string>(), \"seeprom file (required if usb)\")\n\t\t\t(\"dump-path\", boost::program_options::value<std::string>(&wfs_path)->default_value(\"\/\"), \"directory to dump (default: \\\"\/\\\")\")\n\t\t\t(\"mlc\", \"device is mlc (default: device is usb)\")\n\t\t\t(\"usb\", \"device is usb\")\n\t\t\t(\"verbos\", \"verbos output\")\n\t\t\t;\n\n\t\tboost::program_options::variables_map vm;\n\t\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n\t\tboost::program_options::notify(vm);\n\n\t\tbool bad = false;\n\t\tif (!vm.count(\"input\")) { std::cerr << \"Missing input file (--input)\" << std::endl; bad = true; }\n\t\tif (!vm.count(\"output\")) { std::cerr << \"Missing output directory (--output)\" << std::endl; bad = true; }\n\t\tif (!vm.count(\"otp\")) { std::cerr << \"Missing otp file (--otp)\" << std::endl; bad = true; }\n\t\tif ((!vm.count(\"seeprom\") && !vm.count(\"mlc\"))) { std::cerr << \"Missing seeprom file (--seeprom)\" << std::endl; bad = true; }\n\t\tif (vm.count(\"mlc\") + vm.count(\"usb\") > 1) { std::cerr << \"Can't specify both --mlc and --usb\" << std::endl; bad = true; }\n\t\tif (vm.count(\"help\") || bad) {\n\t\t\tstd::cout << \"Usage: wfs-extract --input <input file> --output <output directory> --otp <opt path> [--seeprom <seeprom path>] [--mlc] [--usb] [--dump-path <directory to dump>] [--verbos]\" << std::endl;\n\t\t\tstd::cout << desc << \"\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\t\tstd::vector<uint8_t> key;\n\t\tstd::unique_ptr<OTP> otp;\n\t\t\/\/ open otp\n\t\ttry {\n\t\t\totp.reset(OTP::LoadFromFile(vm[\"otp\"].as<std::string>()));\n\t\t}\n\t\tcatch (std::exception& e) {\n\t\t\tstd::cerr << \"Failed to open OTP: \" << e.what() << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (vm.count(\"mlc\")) {\n\t\t\t\/\/ mlc\n\t\t\tkey = otp->GetMLCKey();\n\t\t}\n\t\telse {\n\t\t\t\/\/ usb\n\t\t\tstd::unique_ptr<SEEPROM> seeprom;\n\t\t\ttry {\n\t\t\t\tseeprom.reset(SEEPROM::LoadFromFile(vm[\"seeprom\"].as<std::string>()));\n\t\t\t}\n\t\t\tcatch (std::exception& e) {\n\t\t\t\tstd::cerr << \"Failed to open SEEPROM: \" << e.what() << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tkey = seeprom->GetUSBKey(*otp);\n\t\t}\n\t\tauto device = std::make_shared<FileDevice>(vm[\"input\"].as<std::string>(), 9);\n\t\tWfs::DetectDeviceSectorSizeAndCount(device, key);\n\t\tauto dir = Wfs(device, key).GetDirectory(vm[\"dump-path\"].as<std::string>());\n\t\tif (!dir) {\n\t\t\tstd::cerr << \"Error: Didn't find directory \" << vm[\"dump-path\"].as<std::string>() << \" in wfs\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tstd::cout << \"Dumping...\" << std::endl;\n\t\tdumpdir(boost::filesystem::path(vm[\"output\"].as<std::string>()), dir, boost::filesystem::path(\"\"), !!vm.count(\"verbos\"));\n\t\tstd::cout << \"Done!\" << std::endl;\n\t}\n\tcatch (std::exception& e) {\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}<commit_msg>Undo accidental commit<commit_after>\/*\n * Copyright (C) 2017 koolkdev\n *\n * This software may be modified and distributed under the terms\n * of the MIT license. See the LICENSE file for details.\n *\/\n\n#include <cstdio>\n#include <vector>\n#include <fstream>\n#include <memory>\n#include <iostream>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n\n#include <wfslib\/WfsLib.h>\n\nvoid dumpdir(const boost::filesystem::path& target, const std::shared_ptr<Directory>& dir, const boost::filesystem::path& path, bool verbos) {\n\tif (!boost::filesystem::exists(target \/ path)) {\n\t\tif (!boost::filesystem::create_directories(target \/ path)) {\n\t\t\tstd::cerr << \"Error: Failed to create directory \" << (target \/ path) << std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\tfor (auto item : *dir) {\n\t\tboost::filesystem::path npath = path \/ item->GetRealName();\n\t\tif (verbos)\n\t\t\tstd::cout << \"Dumping \" << npath << std::endl;\n\t\tif (item->IsDirectory()) dumpdir(target, std::dynamic_pointer_cast<Directory>(item), npath, verbos);\n\t\telse if (item->IsFile()) {\n\t\t\tauto file = std::dynamic_pointer_cast<File>(item);\n\t\t\tstd::ofstream output_file((target \/ npath).string(), std::ios::binary | std::ios::out);\n\t\t\tsize_t to_read = file->GetSize();\n\t\t\tFile::stream stream(file);\n\t\t\tstd::vector<char> data(0x2000);\n\t\t\twhile (to_read > 0) {\n\t\t\t\tstream.read(&*data.begin(), std::min(data.size(), to_read));\n\t\t\t\tauto read = stream.gcount();\n\t\t\t\tif (read <= 0) {\n\t\t\t\t\tstd::cerr << \"Error: Failed to read \" << npath << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput_file.write((char*)&*data.begin(), read);\n\t\t\t\tto_read -= static_cast<size_t>(read);\n\t\t\t}\n\t\t\toutput_file.close();\n\t\t}\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\ttry {\n\t\tboost::program_options::options_description desc(\"Allowed options\");\n\t\tstd::string wfs_path;\n\t\tdesc.add_options()\n\t\t\t(\"help\", \"produce help message\")\n\t\t\t(\"input\", boost::program_options::value<std::string>(), \"input file\")\n\t\t\t(\"output\", boost::program_options::value<std::string>(), \"ouput directory\")\n\t\t\t(\"otp\", boost::program_options::value<std::string>(), \"otp file\")\n\t\t\t(\"seeprom\", boost::program_options::value<std::string>(), \"seeprom file (required if usb)\")\n\t\t\t(\"dump-path\", boost::program_options::value<std::string>(&wfs_path)->default_value(\"\/\"), \"directory to dump (default: \\\"\/\\\")\")\n\t\t\t(\"mlc\", \"device is mlc (default: device is usb)\")\n\t\t\t(\"usb\", \"device is usb\")\n\t\t\t(\"verbos\", \"verbos output\")\n\t\t\t;\n\n\t\tboost::program_options::variables_map vm;\n\t\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n\t\tboost::program_options::notify(vm);\n\n\t\tbool bad = false;\n\t\tif (!vm.count(\"input\")) { std::cerr << \"Missing input file (--input)\" << std::endl; bad = true; }\n\t\tif (!vm.count(\"output\")) { std::cerr << \"Missing output directory (--output)\" << std::endl; bad = true; }\n\t\tif (!vm.count(\"otp\")) { std::cerr << \"Missing otp file (--otp)\" << std::endl; bad = true; }\n\t\tif ((!vm.count(\"seeprom\") && !vm.count(\"mlc\"))) { std::cerr << \"Missing seeprom file (--seeprom)\" << std::endl; bad = true; }\n\t\tif (vm.count(\"mlc\") + vm.count(\"usb\") > 1) { std::cerr << \"Can't specify both --mlc and --usb\" << std::endl; bad = true; }\n\t\tif (vm.count(\"help\") || bad) {\n\t\t\tstd::cout << \"Usage: wfs-extract --input <input file> --output <output directory> --otp <opt path> [--seeprom <seeprom path>] [--mlc] [--usb] [--dump-path <directory to dump>] [--verbos]\" << std::endl;\n\t\t\tstd::cout << desc << \"\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\t\tstd::vector<uint8_t> key;\n\t\tstd::unique_ptr<OTP> otp;\n\t\t\/\/ open otp\n\t\ttry {\n\t\t\totp.reset(OTP::LoadFromFile(vm[\"otp\"].as<std::string>()));\n\t\t}\n\t\tcatch (std::exception& e) {\n\t\t\tstd::cerr << \"Failed to open OTP: \" << e.what() << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (vm.count(\"mlc\")) {\n\t\t\t\/\/ mlc\n\t\t\tkey = otp->GetMLCKey();\n\t\t}\n\t\telse {\n\t\t\t\/\/ usb\n\t\t\tstd::unique_ptr<SEEPROM> seeprom;\n\t\t\ttry {\n\t\t\t\tseeprom.reset(SEEPROM::LoadFromFile(vm[\"seeprom\"].as<std::string>()));\n\t\t\t}\n\t\t\tcatch (std::exception& e) {\n\t\t\t\tstd::cerr << \"Failed to open SEEPROM: \" << e.what() << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tkey = seeprom->GetUSBKey(*otp);\n\t\t}\n\t\tauto device = std::make_shared<FileDevice>(vm[\"input\"].as<std::string>(), 9);\n\t\tWfs::DetectDeviceSectorSizeAndCount(device, key);\n\t\tauto dir = Wfs(device, key).GetDirectory(vm[\"dump-path\"].as<std::string>());\n\t\tif (!dir) {\n\t\t\tstd::cerr << \"Error: Didn't find directory \" << vm[\"dump-path\"].as<std::string>() << \" in wfs\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tstd::cout << \"Dumping...\" << std::endl;\n\t\tdumpdir(boost::filesystem::path(vm[\"output\"].as<std::string>()), dir, boost::filesystem::path(\"\"), !!vm.count(\"verbos\"));\n\t\tstd::cout << \"Done!\" << std::endl;\n\t}\n\tcatch (std::exception& e) {\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_MATH_HH\n#define DUNE_STUFF_MATH_HH\n\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <cstring>\n#include <iostream>\n#include <boost\/format.hpp>\n\nnamespace Stuff {\n\n\/** \\todo DOCME **\/\ntemplate <class SomeRangeType, class OtherRangeType >\nstatic double colonProduct( const SomeRangeType& arg1,\n\t\t\t\t\t\tconst OtherRangeType& arg2 )\n{\n\tdune_static_assert( SomeRangeType::cols == SomeRangeType::rows\n\t\t\t&& OtherRangeType::cols == OtherRangeType::rows\n\t\t\t&& int(OtherRangeType::cols) == int(SomeRangeType::rows), \"RangeTypes_dont_fit\" );\n\n\tdouble ret = 0.0;\n\t\/\/ iterators\n\ttypedef typename SomeRangeType::ConstRowIterator\n\t\tConstRowIteratorType;\n\ttypedef typename SomeRangeType::row_type::ConstIterator\n\t\tConstIteratorType;\n\tConstRowIteratorType arg1RowItEnd = arg1.end();\n\tConstRowIteratorType arg2RowItEnd = arg2.end();\n\tConstRowIteratorType arg2RowIt = arg2.begin();\n\tfor ( ConstRowIteratorType arg1RowIt = arg1.begin();\n\t\t\targ1RowIt != arg1RowItEnd, arg2RowIt != arg2RowItEnd;\n\t\t\t++arg1RowIt, ++arg2RowIt ) {\n\t\tConstIteratorType row1ItEnd = arg1RowIt->end();\n\t\tConstIteratorType row2ItEnd = arg2RowIt->end();\n\t\tConstIteratorType row2It = arg2RowIt->begin();\n\t\tfor ( ConstIteratorType row1It = arg1RowIt->begin();\n\t\t\t\trow1It != row1ItEnd, row2It != row2ItEnd;\n\t\t\t\t++row1It, ++row2It ) {\n\t\t\tret += *row1It * *row2It;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\/**\n * \\brief dyadic product\n *\n * Implements \\f$\\left(arg_{1} \\otimes arg_{2}\\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\\f$\n *\t\t\tRangeType1 should be fieldmatrix, RangeType2 fieldvector\n **\/\ntemplate <class RangeType1, class RangeType2 >\nstatic RangeType1 dyadicProduct( const RangeType2& arg1,\n\t\t\t\t\t\t\t\tconst RangeType2& arg2 )\n{\n\tRangeType1 ret( 0.0 );\n\ttypedef typename RangeType1::RowIterator\n\t\tMatrixRowIteratorType;\n\ttypedef typename RangeType2::ConstIterator\n\t\tConstVectorIteratorType;\n\ttypedef typename RangeType2::Iterator\n\t\tVectorIteratorType;\n\tMatrixRowIteratorType rItEnd = ret.end();\n\tConstVectorIteratorType arg1It = arg1.begin();\n\tfor ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {\n\t\tConstVectorIteratorType arg2It = arg2.begin();\n\t\tVectorIteratorType vItEnd = rIt->end();\n\t\tfor ( VectorIteratorType vIt = rIt->begin();\n\t\t\t\tvIt != vItEnd;\n\t\t\t\t++vIt ) {\n\t\t\t*vIt = *arg1It * *arg2It;\n\t\t\t++arg2It;\n\t\t}\n\t\t++arg1It;\n\t}\n\treturn ret;\n}\n\n\/** \\brief a vector wrapper for continiously updating min,max,avg of some element type vector\n \\todo find use? it's only used in minimal as testcase for itself...\n **\/\ntemplate < class ElementType >\nclass MinMaxAvg {\n\tprotected:\n\t\ttypedef MinMaxAvg< ElementType >\n\t\t\tThisType;\n\t\ttypedef std::vector< ElementType >\n\t\t\tElementsVec;\n\t\ttypedef typename ElementsVec::const_iterator\n\t\t\tElementsVecConstIterator;\n\n\tpublic:\n\t\tMinMaxAvg()\n\t\t\t: min_ ( std::numeric_limits< ElementType >::max() ),\n\t\t\tmax_ ( std::numeric_limits< ElementType >::min() ),\n\t\t\tavg_ ( ( min_ + max_ ) \/ 2.0 )\n\t\t{}\n\n\t\tMinMaxAvg( const ElementsVec& elements )\n\t\t{\n\t\t\tfor ( ElementsVecConstIterator it = elements.begin(); it != elements.end(); ++it ) {\n\t\t\t\tpush( *it );\n\t\t\t}\n\t\t}\n\n\t\tElementType min () const { return min_; }\n\t\tElementType max () const { return max_; }\n\t\tElementType average () const { return avg_; }\n\n\t\tvoid push( const ElementType& el ) {\n\t\t\tsize_t num = elements_.size();\n\t\t\telements_.push_back( el );\n\t\t\tmax_ = std::max( el, max_ );\n\t\t\tmin_ = std::min( el, min_ );\n\t\t\tif ( num > 0 ) {\n\t\t\t\tavg_ *= ( num \/ double( num + 1 ) );\n\t\t\t\tavg_ += ( el \/ double( num + 1 ) );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tavg_ = el;\n\t\t\t}\n\t\t}\n\n\t\ttemplate < class Stream >\n\t\tvoid output( Stream& stream ) {\n\t\t\tstream << boost::format( \"min: %e\\tmax: %e\\tavg: %e\\n\" ) % min_ % max_ % avg_;\n\t\t}\n\n\tprotected:\n\t\tElementsVec elements_;\n\t\tElementType min_,max_,avg_;\n\n\t\tMinMaxAvg( const ThisType& other );\n};\n\n\/\/! bound \\param var in [\\param min,\\param max]\ntemplate <typename T> T clamp(const T var,const T min,const T max)\n{\n\treturn ( (var < min) ? min : ( var > max ) ? max : var );\n}\n\n\/\/! docme\nclass MovingAverage\n{\n\tdouble avg_;\n\tsize_t steps_;\npublic:\n\tMovingAverage()\n\t\t:avg_(0.0),steps_(0)\n\t{}\n\tMovingAverage& operator += (double val)\n\t{\n\t\tavg_ += ( val - avg_ ) \/ ++steps_;\n\t\treturn *this;\n\t}\n\toperator double () { return avg_; }\n};\n\n\/\/! no-branch sign function\nlong sign(long x) { return long(x!=0) | (long(x>=0)-1); }\n\n} \/\/end namespace Stuff\n\n#endif \/\/ DUNE_STUFF_MATH_HH\n<commit_msg>move MinMaxAvg to boost::accumulator based implementation<commit_after>#ifndef DUNE_STUFF_MATH_HH\n#define DUNE_STUFF_MATH_HH\n\n#include <vector>\n#include <limits>\n#include <algorithm>\n#include <cstring>\n#include <iostream>\n#include \"static_assert.hh\"\n#include <boost\/format.hpp>\n#include <boost\/static_assert.hpp>\n#include <boost\/fusion\/include\/void.hpp>\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics\/stats.hpp>\n#include <boost\/accumulators\/statistics\/max.hpp>\n#include <boost\/accumulators\/statistics\/min.hpp>\n#include <boost\/accumulators\/statistics\/mean.hpp>\n\nnamespace Stuff {\n\n\/** \\todo DOCME **\/\ntemplate <class SomeRangeType, class OtherRangeType >\nstatic double colonProduct( const SomeRangeType& arg1,\n\t\t\t\t\t\tconst OtherRangeType& arg2 )\n{\n\tdune_static_assert( SomeRangeType::cols == SomeRangeType::rows\n\t\t\t&& OtherRangeType::cols == OtherRangeType::rows\n\t\t\t&& int(OtherRangeType::cols) == int(SomeRangeType::rows), \"RangeTypes_dont_fit\" );\n\n\tdouble ret = 0.0;\n\t\/\/ iterators\n\ttypedef typename SomeRangeType::ConstRowIterator\n\t\tConstRowIteratorType;\n\ttypedef typename SomeRangeType::row_type::ConstIterator\n\t\tConstIteratorType;\n\tConstRowIteratorType arg1RowItEnd = arg1.end();\n\tConstRowIteratorType arg2RowItEnd = arg2.end();\n\tConstRowIteratorType arg2RowIt = arg2.begin();\n\tfor ( ConstRowIteratorType arg1RowIt = arg1.begin();\n\t\t\targ1RowIt != arg1RowItEnd, arg2RowIt != arg2RowItEnd;\n\t\t\t++arg1RowIt, ++arg2RowIt ) {\n\t\tConstIteratorType row1ItEnd = arg1RowIt->end();\n\t\tConstIteratorType row2ItEnd = arg2RowIt->end();\n\t\tConstIteratorType row2It = arg2RowIt->begin();\n\t\tfor ( ConstIteratorType row1It = arg1RowIt->begin();\n\t\t\t\trow1It != row1ItEnd, row2It != row2ItEnd;\n\t\t\t\t++row1It, ++row2It ) {\n\t\t\tret += *row1It * *row2It;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\/**\n * \\brief dyadic product\n *\n * Implements \\f$\\left(arg_{1} \\otimes arg_{2}\\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\\f$\n *\t\t\tRangeType1 should be fieldmatrix, RangeType2 fieldvector\n **\/\ntemplate <class RangeType1, class RangeType2 >\nstatic RangeType1 dyadicProduct( const RangeType2& arg1,\n\t\t\t\t\t\t\t\tconst RangeType2& arg2 )\n{\n\tRangeType1 ret( 0.0 );\n\ttypedef typename RangeType1::RowIterator\n\t\tMatrixRowIteratorType;\n\ttypedef typename RangeType2::ConstIterator\n\t\tConstVectorIteratorType;\n\ttypedef typename RangeType2::Iterator\n\t\tVectorIteratorType;\n\tMatrixRowIteratorType rItEnd = ret.end();\n\tConstVectorIteratorType arg1It = arg1.begin();\n\tfor ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {\n\t\tConstVectorIteratorType arg2It = arg2.begin();\n\t\tVectorIteratorType vItEnd = rIt->end();\n\t\tfor ( VectorIteratorType vIt = rIt->begin();\n\t\t\t\tvIt != vItEnd;\n\t\t\t\t++vIt ) {\n\t\t\t*vIt = *arg1It * *arg2It;\n\t\t\t++arg2It;\n\t\t}\n\t\t++arg1It;\n\t}\n\treturn ret;\n}\n\n\/** \\brief a vector wrapper for continiously updating min,max,avg of some element type vector\n \\todo find use? it's only used in minimal as testcase for itself...\n **\/\ntemplate < class ElementType >\nclass MinMaxAvg {\n\tprotected:\n\t\ttypedef MinMaxAvg< ElementType >\n\t\t\tThisType;\n\t\ttypedef std::vector< ElementType >\n\t\t\tElementsVec;\n\t\ttypedef typename ElementsVec::const_iterator\n\t\t\tElementsVecConstIterator;\n\n\tpublic:\n\t\tMinMaxAvg()\n\t\t{}\n\n\t\ttemplate < class stl_container_type >\n\t\tMinMaxAvg( const stl_container_type& elements )\n\t\t{\n\t\t\tdune_static_assert( (boost::is_same< ElementType, typename stl_container_type::value_type >::value),\n\t\t\t\t\t\t\t\t \"cannot assign mismatching types\" );\n\t\t\tacc_ = std::for_each( elements.begin(), elements.end(), acc_ );\n\t\t}\n\n\t\tElementType min () const { return boost::accumulators::min(acc_); }\n\t\tElementType max () const { return boost::accumulators::max(acc_); }\n\t\tElementType average () const { return boost::accumulators::mean(acc_); }\n\n\t\tvoid push( const ElementType& el ) {\n\t\t\tacc_( el );\n\t\t}\n\n\t\ttemplate < class Stream >\n\t\tvoid output( Stream& stream ) {\n\t\t\tstream << boost::format( \"min: %e\\tmax: %e\\tavg: %e\\n\" ) % min() % max() % average();\n\t\t}\n\n\tprotected:\n\t\ttypedef boost::accumulators::stats<\n\t\t\t\tboost::accumulators::tag::max,\n\t\t\t\tboost::accumulators::tag::min,\n\t\t\t\tboost::accumulators::tag::mean >\n\t\t\tStatsType;\n\t\tboost::accumulators::accumulator_set< ElementType,StatsType > acc_;\n\n\t\tMinMaxAvg( const ThisType& other );\n};\n\n\/\/! bound \\param var in [\\param min,\\param max]\ntemplate <typename T> T clamp(const T var,const T min,const T max)\n{\n\treturn ( (var < min) ? min : ( var > max ) ? max : var );\n}\n\n\/\/! docme\nclass MovingAverage\n{\n\tdouble avg_;\n\tsize_t steps_;\npublic:\n\tMovingAverage()\n\t\t:avg_(0.0),steps_(0)\n\t{}\n\tMovingAverage& operator += (double val)\n\t{\n\t\tavg_ += ( val - avg_ ) \/ ++steps_;\n\t\treturn *this;\n\t}\n\toperator double () { return avg_; }\n};\n\n\/\/! no-branch sign function\nlong sign(long x) { return long(x!=0) | (long(x>=0)-1); }\n\n} \/\/end namespace Stuff\n\n#endif \/\/ DUNE_STUFF_MATH_HH\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#46808, Remove unnecessary call to getProcessServiceFactory<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include <Python.h>\n#include <fstream>\n#include <vector>\n\n#include \"paddle\/framework\/net.h\"\n#include \"paddle\/framework\/op_registry.h\"\n#include \"paddle\/framework\/operator.h\"\n#include \"paddle\/framework\/scope.h\"\n#include \"paddle\/platform\/enforce.h\"\n#include \"paddle\/platform\/place.h\"\n#include \"paddle\/pybind\/tensor_bind.h\"\n#include \"pybind11\/numpy.h\"\n#include \"pybind11\/pybind11.h\"\n#include \"pybind11\/stl.h\"\n\nnamespace py = pybind11;\nnamespace pd = paddle::framework;\n\nUSE_OP(add_two);\nUSE_OP(onehot_cross_entropy);\nUSE_OP_WITHOUT_KERNEL(fc);\nUSE_OP(sgd);\nUSE_OP(mul);\nUSE_OP(mean);\nUSE_OP(sigmoid);\nUSE_OP(softmax);\nUSE_OP(rowwise_add);\nUSE_OP_WITHOUT_KERNEL(recurrent_op);\n\ntemplate <typename ClassType>\nvoid ExposeOperator(ClassType& m) {\n m.def(\"infer_shape\", &ClassType::type::InferShape)\n .def(\"run\", &ClassType::type::Run)\n .def(\"outputs\",\n [](const typename ClassType::type& op) -> std::vector<std::string> {\n return op.outputs_;\n })\n .def(\"__str__\", &ClassType::type::DebugString);\n}\n\nstatic size_t UniqueIntegerGenerator() {\n static std::atomic<size_t> generator;\n return generator.fetch_add(1);\n}\n\nbool IsCompileGPU() {\n#ifdef PADDLE_ONLY_CPU\n return false;\n#else\n return true;\n#endif\n}\n\nPYBIND11_PLUGIN(core) {\n py::module m(\"core\", \"C++ core of PaddlePaddle\");\n\n py::class_<pd::Tensor>(m, \"Tensor\", py::buffer_protocol())\n .def_buffer([](pd::Tensor& self) -> py::buffer_info {\n return paddle::pybind::CastToPyBuffer(self);\n })\n .def(\"get_dims\",\n [](const pd::Tensor& self) { return pd::vectorize(self.dims()); })\n .def(\"set_dims\",\n [](pd::Tensor& self, const std::vector<int>& dim) {\n self.Resize(pd::make_ddim(dim));\n })\n .def(\"alloc_float\",\n [](pd::Tensor& self, paddle::platform::GPUPlace& place) {\n self.mutable_data<float>(place);\n })\n .def(\"alloc_float\",\n [](pd::Tensor& self, paddle::platform::CPUPlace& place) {\n self.mutable_data<float>(place);\n })\n .def(\"alloc_int\",\n [](pd::Tensor& self, paddle::platform::CPUPlace& place) {\n self.mutable_data<int>(place);\n })\n .def(\"alloc_int\",\n [](pd::Tensor& self, paddle::platform::GPUPlace& place) {\n self.mutable_data<int>(place);\n })\n .def(\"set\", paddle::pybind::PyCPUTensorSetFromArray<float>)\n .def(\"set\", paddle::pybind::PyCPUTensorSetFromArray<int>)\n#ifndef PADDLE_ONLY_CPU\n .def(\"set\", paddle::pybind::PyCUDATensorSetFromArray<float>)\n .def(\"set\", paddle::pybind::PyCUDATensorSetFromArray<int>)\n#endif\n .def(\"shape\",\n [](pd::Tensor& self) { return pd::vectorize(self.dims()); });\n\n py::class_<pd::Variable>(m, \"Variable\", R\"DOC(Variable Class.\n\nAll parameter, weight, gradient are variables in Paddle.\n)DOC\")\n .def(\"is_int\", [](const pd::Variable& var) { return var.IsType<int>(); })\n .def(\"set_int\",\n [](pd::Variable& var, int val) -> void {\n *var.GetMutable<int>() = val;\n })\n .def(\"get_int\",\n [](const pd::Variable& var) -> int { return var.Get<int>(); })\n .def(\"get_tensor\",\n [](pd::Variable& self) -> pd::Tensor* {\n return self.GetMutable<pd::Tensor>();\n },\n py::return_value_policy::reference)\n .def(\"get_net\",\n [](pd::Variable& self) -> pd::NetOp* {\n return self.GetMutable<pd::NetOp>();\n },\n py::return_value_policy::reference);\n\n py::class_<pd::Scope>(m, \"Scope\", \"\")\n .def(\"new_var\",\n [](pd::Scope& self, const std::string& name) -> pd::Variable* {\n return self.NewVar(name);\n },\n py::return_value_policy::reference)\n .def(\"find_var\", &pd::Scope::FindVar, py::return_value_policy::reference)\n .def(py::init<>())\n .def(\"new_scope\",\n [](pd::Scope& self) -> pd::Scope* { return &self.NewScope(); },\n py::return_value_policy::reference)\n .def(\"drop_kids\", &pd::Scope::DropKids);\n\n \/\/! @note: Be careful! PyBind will return std::string as an unicode, not\n \/\/! Python str. If you want a str object, you should cast them in Python.\n m.def(\"get_all_op_protos\", []() -> std::vector<py::bytes> {\n auto& protos = pd::OpRegistry::protos();\n std::vector<py::bytes> ret_values;\n for (auto it = protos.begin(); it != protos.end(); ++it) {\n PADDLE_ENFORCE(it->second.IsInitialized(),\n \"OpProto must all be initialized\");\n std::string str;\n PADDLE_ENFORCE(it->second.SerializeToString(&str),\n \"Serialize OpProto Error. This could be a bug of Paddle.\");\n ret_values.push_back(py::bytes(str));\n }\n return ret_values;\n });\n m.def_submodule(\n \"var_names\",\n \"The module will return special predefined variable name in Paddle\")\n .def(\"empty\", pd::OperatorBase::EMPTY_VAR_NAME)\n .def(\"temp\", pd::OperatorBase::TMP_VAR_NAME);\n \/\/clang-format off\n py::class_<paddle::platform::DeviceContext>(m, \"DeviceContext\")\n .def_static(\"create\",\n [](paddle::platform::CPUPlace& place)\n -> paddle::platform::DeviceContext* {\n return new paddle::platform::CPUDeviceContext();\n })\n .def_static(\"create\",\n [](paddle::platform::GPUPlace& place)\n -> paddle::platform::DeviceContext* {\n#ifdef PADDLE_ONLY_CPU\n PADDLE_THROW(\"GPUPlace is not supported in CPU device.\");\n#else\n return new paddle::platform::CUDADeviceContext(place);\n#endif\n });\n \/\/clang-format on\n\n py::class_<paddle::platform::GPUPlace>(m, \"GPUPlace\").def(py::init<int>());\n\n py::class_<paddle::platform::CPUPlace>(m, \"CPUPlace\").def(py::init<>());\n\n py::class_<pd::OperatorBase, std::shared_ptr<pd::OperatorBase>> operator_base(\n m, \"Operator\");\n\n operator_base.def_static(\"create\", [](py::bytes protobin) {\n pd::OpDesc desc;\n PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),\n \"Cannot parse user input to OpDesc\");\n PADDLE_ENFORCE(desc.IsInitialized(),\n \"User OpDesc is not initialized, reason %s\",\n desc.InitializationErrorString());\n return pd::OpRegistry::CreateOp(desc);\n });\n ExposeOperator(operator_base);\n\n py::class_<pd::NetOp, std::shared_ptr<pd::NetOp>> net(m, \"Net\");\n\n net.def_static(\"create\",\n []() -> std::shared_ptr<pd::NetOp> {\n auto retv = std::make_shared<pd::NetOp>();\n retv->type_ = \"plain_net\";\n return retv;\n })\n .def(\"add_op\", &pd::NetOp::AddOp)\n .def(\"add_op\",\n [](pd::NetOp& self, const std::shared_ptr<pd::NetOp>& net) -> void {\n self.AddOp(std::static_pointer_cast<pd::OperatorBase>(net));\n })\n .def(\"complete_add_op\", &pd::NetOp::CompleteAddOp)\n .def(\"complete_add_op\",\n [](std::shared_ptr<pd::NetOp>& self) { self->CompleteAddOp(); });\n ExposeOperator(net);\n\n m.def(\"unique_integer\", UniqueIntegerGenerator);\n\n m.def(\"is_compile_gpu\", IsCompileGPU);\n\n return m.ptr();\n}\n<commit_msg>pass pre commit<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include <Python.h>\n#include <fstream>\n#include <vector>\n\n#include \"paddle\/framework\/net.h\"\n#include \"paddle\/framework\/op_registry.h\"\n#include \"paddle\/framework\/operator.h\"\n#include \"paddle\/framework\/scope.h\"\n#include \"paddle\/platform\/enforce.h\"\n#include \"paddle\/platform\/place.h\"\n#include \"paddle\/pybind\/tensor_bind.h\"\n#include \"pybind11\/numpy.h\"\n#include \"pybind11\/pybind11.h\"\n#include \"pybind11\/stl.h\"\n\nnamespace py = pybind11;\nnamespace pd = paddle::framework;\n\nUSE_OP(add_two);\nUSE_OP(onehot_cross_entropy);\nUSE_OP_WITHOUT_KERNEL(fc);\nUSE_OP(sgd);\nUSE_OP(mul);\nUSE_OP(mean);\nUSE_OP(sigmoid);\nUSE_OP(softmax);\nUSE_OP(rowwise_add);\nUSE_OP_WITHOUT_KERNEL(recurrent_op);\n\ntemplate <typename ClassType>\nvoid ExposeOperator(ClassType& m) {\n m.def(\"infer_shape\", &ClassType::type::InferShape)\n .def(\"run\", &ClassType::type::Run)\n .def(\"outputs\",\n [](const typename ClassType::type& op) -> std::vector<std::string> {\n return op.outputs_;\n })\n .def(\"__str__\", &ClassType::type::DebugString);\n}\n\nstatic size_t UniqueIntegerGenerator() {\n static std::atomic<size_t> generator;\n return generator.fetch_add(1);\n}\n\nbool IsCompileGPU() {\n#ifdef PADDLE_ONLY_CPU\n return false;\n#else\n return true;\n#endif\n}\n\nPYBIND11_PLUGIN(core) {\n py::module m(\"core\", \"C++ core of PaddlePaddle\");\n\n py::class_<pd::Tensor>(m, \"Tensor\", py::buffer_protocol())\n .def_buffer([](pd::Tensor& self) -> py::buffer_info {\n return paddle::pybind::CastToPyBuffer(self);\n })\n .def(\"get_dims\",\n [](const pd::Tensor& self) { return pd::vectorize(self.dims()); })\n .def(\"set_dims\",\n [](pd::Tensor& self, const std::vector<int>& dim) {\n self.Resize(pd::make_ddim(dim));\n })\n .def(\"alloc_float\",\n [](pd::Tensor& self, paddle::platform::GPUPlace& place) {\n self.mutable_data<float>(place);\n })\n .def(\"alloc_float\",\n [](pd::Tensor& self, paddle::platform::CPUPlace& place) {\n self.mutable_data<float>(place);\n })\n .def(\"alloc_int\",\n [](pd::Tensor& self, paddle::platform::CPUPlace& place) {\n self.mutable_data<int>(place);\n })\n .def(\"alloc_int\",\n [](pd::Tensor& self, paddle::platform::GPUPlace& place) {\n self.mutable_data<int>(place);\n })\n .def(\"set\", paddle::pybind::PyCPUTensorSetFromArray<float>)\n .def(\"set\", paddle::pybind::PyCPUTensorSetFromArray<int>)\n#ifndef PADDLE_ONLY_CPU\n .def(\"set\", paddle::pybind::PyCUDATensorSetFromArray<float>)\n .def(\"set\", paddle::pybind::PyCUDATensorSetFromArray<int>)\n#endif\n .def(\"shape\",\n [](pd::Tensor& self) { return pd::vectorize(self.dims()); });\n\n py::class_<pd::Variable>(m, \"Variable\", R\"DOC(Variable Class.\n\nAll parameter, weight, gradient are variables in Paddle.\n)DOC\")\n .def(\"is_int\", [](const pd::Variable& var) { return var.IsType<int>(); })\n .def(\"set_int\",\n [](pd::Variable& var, int val) -> void {\n *var.GetMutable<int>() = val;\n })\n .def(\"get_int\",\n [](const pd::Variable& var) -> int { return var.Get<int>(); })\n .def(\"get_tensor\",\n [](pd::Variable& self) -> pd::Tensor* {\n return self.GetMutable<pd::Tensor>();\n },\n py::return_value_policy::reference)\n .def(\"get_net\",\n [](pd::Variable& self) -> pd::NetOp* {\n return self.GetMutable<pd::NetOp>();\n },\n py::return_value_policy::reference);\n\n py::class_<pd::Scope>(m, \"Scope\", \"\")\n .def(\"new_var\",\n [](pd::Scope& self, const std::string& name) -> pd::Variable* {\n return self.NewVar(name);\n },\n py::return_value_policy::reference)\n .def(\"find_var\", &pd::Scope::FindVar, py::return_value_policy::reference)\n .def(py::init<>())\n .def(\"new_scope\",\n [](pd::Scope& self) -> pd::Scope* { return &self.NewScope(); },\n py::return_value_policy::reference)\n .def(\"drop_kids\", &pd::Scope::DropKids);\n\n \/\/! @note: Be careful! PyBind will return std::string as an unicode, not\n \/\/! Python str. If you want a str object, you should cast them in Python.\n m.def(\"get_all_op_protos\", []() -> std::vector<py::bytes> {\n auto& protos = pd::OpRegistry::protos();\n std::vector<py::bytes> ret_values;\n for (auto it = protos.begin(); it != protos.end(); ++it) {\n PADDLE_ENFORCE(it->second.IsInitialized(),\n \"OpProto must all be initialized\");\n std::string str;\n PADDLE_ENFORCE(it->second.SerializeToString(&str),\n \"Serialize OpProto Error. This could be a bug of Paddle.\");\n ret_values.push_back(py::bytes(str));\n }\n return ret_values;\n });\n m.def_submodule(\n \"var_names\",\n \"The module will return special predefined variable name in Paddle\")\n .def(\"empty\", pd::OperatorBase::EMPTY_VAR_NAME)\n .def(\"temp\", pd::OperatorBase::TMP_VAR_NAME);\n \/\/ clang-format off\n py::class_<paddle::platform::DeviceContext>(m, \"DeviceContext\")\n .def_static(\"create\",\n [](paddle::platform::CPUPlace& place)\n -> paddle::platform::DeviceContext* {\n return new paddle::platform::CPUDeviceContext();\n })\n .def_static(\"create\",\n [](paddle::platform::GPUPlace& place)\n -> paddle::platform::DeviceContext* {\n#ifdef PADDLE_ONLY_CPU\n PADDLE_THROW(\"GPUPlace is not supported in CPU device.\");\n#else\n return new paddle::platform::CUDADeviceContext(place);\n#endif\n });\n \/\/ clang-format on\n\n py::class_<paddle::platform::GPUPlace>(m, \"GPUPlace\").def(py::init<int>());\n\n py::class_<paddle::platform::CPUPlace>(m, \"CPUPlace\").def(py::init<>());\n\n py::class_<pd::OperatorBase, std::shared_ptr<pd::OperatorBase>> operator_base(\n m, \"Operator\");\n\n operator_base.def_static(\"create\", [](py::bytes protobin) {\n pd::OpDesc desc;\n PADDLE_ENFORCE(desc.ParsePartialFromString(protobin),\n \"Cannot parse user input to OpDesc\");\n PADDLE_ENFORCE(desc.IsInitialized(),\n \"User OpDesc is not initialized, reason %s\",\n desc.InitializationErrorString());\n return pd::OpRegistry::CreateOp(desc);\n });\n ExposeOperator(operator_base);\n\n py::class_<pd::NetOp, std::shared_ptr<pd::NetOp>> net(m, \"Net\");\n\n net.def_static(\"create\",\n []() -> std::shared_ptr<pd::NetOp> {\n auto retv = std::make_shared<pd::NetOp>();\n retv->type_ = \"plain_net\";\n return retv;\n })\n .def(\"add_op\", &pd::NetOp::AddOp)\n .def(\"add_op\",\n [](pd::NetOp& self, const std::shared_ptr<pd::NetOp>& net) -> void {\n self.AddOp(std::static_pointer_cast<pd::OperatorBase>(net));\n })\n .def(\"complete_add_op\", &pd::NetOp::CompleteAddOp)\n .def(\"complete_add_op\",\n [](std::shared_ptr<pd::NetOp>& self) { self->CompleteAddOp(); });\n ExposeOperator(net);\n\n m.def(\"unique_integer\", UniqueIntegerGenerator);\n\n m.def(\"is_compile_gpu\", IsCompileGPU);\n\n return m.ptr();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"officecfg\/Office\/Common.hxx\"\n\n#include \"comphelper\/processfactory.hxx\"\n\n#include \"osl\/module.h\"\n#include \"osl\/process.h\"\n\n#include \"rtl\/ustrbuf.hxx\"\n\n#include \"salinst.hxx\"\n#include \"generic\/gensys.h\"\n#include \"generic\/gendata.hxx\"\n#include \"unx\/desktops.hxx\"\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include <cstdio>\n#include <unistd.h>\n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nextern \"C\" {\ntypedef SalInstance*(*salFactoryProc)( oslModule pModule);\n}\n\nstatic oslModule pCloseModule = NULL;\n\nstatic SalInstance* tryInstance( const OUString& rModuleBase, bool bForce = false )\n{\n SalInstance* pInst = NULL;\n#if !defined(ANDROID)\n if (!bForce && rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk3\")))\n {\n \/\/ Disable gtk3 plugin load except in experimental mode for now.\n using namespace com::sun::star;\n uno::Reference< uno::XComponentContext > xContext = comphelper::getProcessComponentContext();\n if (!xContext.is() || !officecfg::Office::Common::Misc::ExperimentalMode::get(xContext))\n return NULL;\n }\n#endif\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"vclplug_\" );\n aModName.append( rModuleBase );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n if( aMod )\n {\n salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, \"create_SalInstance\" );\n if( aProc )\n {\n pInst = aProc( aMod );\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"sal plugin %s produced instance %p\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(),\n pInst );\n#endif\n if( pInst )\n {\n pCloseModule = aMod;\n\n#ifndef ANDROID\n \/*\n * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can\n * not access the 'gnome_accessibility_module_shutdown' anymore.\n * So make sure libgtk+ & co are still mapped into memory when\n * atk-bridge's atexit handler gets called.\n * #i109007# KDE3 seems to have the same problem.\n\t\t * And same applies for KDE4.\n *\/\n if( rModuleBase == \"gtk\" || rModuleBase == \"gtk3\" || rModuleBase == \"tde\" || rModuleBase == \"kde\" || rModuleBase == \"kde4\" )\n {\n pCloseModule = NULL;\n }\n#endif\n GetSalData()->m_pPlugin = aMod;\n }\n else\n osl_unloadModule( aMod );\n }\n else\n {\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"could not load symbol %s from shared object %s\\n\",\n \"create_SalInstance\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n osl_unloadModule( aMod );\n }\n }\n#if OSL_DEBUG_LEVEL > 1\n else\n std::fprintf( stderr, \"could not load shared object %s\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n\n return pInst;\n}\n\n#if !defined(ANDROID)\n\nstatic DesktopType get_desktop_environment()\n{\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"desktop_detector\" );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n DesktopType ret = DESKTOP_UNKNOWN;\n if( aMod )\n {\n DesktopType (*pSym)() = (DesktopType(*)())\n osl_getAsciiFunctionSymbol( aMod, \"get_desktop_environment\" );\n if( pSym )\n ret = pSym();\n }\n osl_unloadModule( aMod );\n return ret;\n}\n\n#else\n\n#define get_desktop_environment() DESKTOP_NONE \/\/ For now...\n\n#endif\n\nstatic SalInstance* autodetect_plugin()\n{\n static const char* pTDEFallbackList[] =\n {\n \"tde\", \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pKDEFallbackList[] =\n {\n \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pStandardFallbackList[] =\n {\n \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pHeadlessFallbackList[] =\n {\n \"svp\", 0\n };\n\n DesktopType desktop = get_desktop_environment();\n const char ** pList = pStandardFallbackList;\n int nListEntry = 0;\n\n \/\/ no server at all: dummy plugin\n if ( desktop == DESKTOP_NONE )\n pList = pHeadlessFallbackList;\n else if ( desktop == DESKTOP_GNOME )\n pList = pStandardFallbackList;\n else if( desktop == DESKTOP_TDE )\n pList = pTDEFallbackList;\n else if( desktop == DESKTOP_KDE )\n {\n pList = pKDEFallbackList;\n nListEntry = 1;\n }\n else if( desktop == DESKTOP_KDE4 )\n pList = pKDEFallbackList;\n\n SalInstance* pInst = NULL;\n while( pList[nListEntry] && pInst == NULL )\n {\n rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) );\n pInst = tryInstance( aTry );\n #if OSL_DEBUG_LEVEL > 1\n if( pInst )\n std::fprintf( stderr, \"plugin autodetection: %s\\n\", pList[nListEntry] );\n #endif\n nListEntry++;\n }\n\n return pInst;\n}\n\nstatic SalInstance* check_headless_plugin()\n{\n int nParams = osl_getCommandArgCount();\n OUString aParam;\n for( int i = 0; i < nParams; i++ )\n {\n osl_getCommandArg( i, &aParam.pData );\n if( aParam == \"-headless\" || aParam == \"--headless\" )\n {\n return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( \"svp\" ) ) );\n }\n }\n return NULL;\n}\n\nSalInstance *CreateSalInstance()\n{\n SalInstance* pInst = NULL;\n\n static const char* pUsePlugin = getenv( \"SAL_USE_VCLPLUGIN\" );\n\n pInst = check_headless_plugin();\n\n if( !pInst && pUsePlugin && *pUsePlugin )\n pInst = tryInstance( OUString::createFromAscii( pUsePlugin ), true );\n\n if( ! pInst )\n pInst = autodetect_plugin();\n\n \/\/ fallback, try everything\n const char* pPlugin[] = { \"gtk3\", \"gtk\", \"kde4\", \"kde\", \"tde\", \"gen\", 0 };\n\n for ( int i = 0; !pInst && pPlugin[ i ]; ++i )\n pInst = tryInstance( OUString::createFromAscii( pPlugin[ i ] ) );\n\n if( ! pInst )\n {\n std::fprintf( stderr, \"no suitable windowing system found, exiting.\\n\" );\n _exit( 1 );\n }\n\n \/\/ acquire SolarMutex\n pInst->AcquireYieldMutex( 1 );\n\n return pInst;\n}\n\nvoid DestroySalInstance( SalInstance *pInst )\n{\n \/\/ release SolarMutex\n pInst->ReleaseYieldMutex();\n\n delete pInst;\n if( pCloseModule )\n osl_unloadModule( pCloseModule );\n}\n\nvoid InitSalData()\n{\n}\n\nvoid DeInitSalData()\n{\n}\n\nvoid InitSalMain()\n{\n}\n\nvoid DeInitSalMain()\n{\n}\n\nvoid SalAbort( const rtl::OUString& rErrorText, bool bDumpCore )\n{\n if( rErrorText.isEmpty() )\n std::fprintf( stderr, \"Application Error\\n\" );\n else\n std::fprintf( stderr, \"%s\\n\", rtl::OUStringToOString(rErrorText, osl_getThreadTextEncoding()).getStr() );\n if( bDumpCore )\n abort();\n else\n _exit(1);\n}\n\nstatic const char * desktop_strings[] = { \"none\", \"unknown\", \"GNOME\", \"TDE\", \"KDE\", \"KDE4\" };\n\nconst OUString& SalGetDesktopEnvironment()\n{\n static rtl::OUString aRet;\n if( aRet.isEmpty())\n {\n rtl::OUStringBuffer buf( 8 );\n buf.appendAscii( desktop_strings[ get_desktop_environment() ] );\n aRet = buf.makeStringAndClear();\n }\n return aRet;\n}\n\nSalData::SalData() :\n m_pInstance(NULL),\n m_pPlugin(NULL),\n m_pPIManager(NULL)\n{\n}\n\nSalData::~SalData()\n{\n psp::PrinterInfoManager::release();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Enable experimental gtk3 plugin only via SAL_USE_VCLPLUGIN<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"osl\/module.h\"\n#include \"osl\/process.h\"\n\n#include \"rtl\/ustrbuf.hxx\"\n\n#include \"salinst.hxx\"\n#include \"generic\/gensys.h\"\n#include \"generic\/gendata.hxx\"\n#include \"unx\/desktops.hxx\"\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include <cstdio>\n#include <unistd.h>\n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nextern \"C\" {\ntypedef SalInstance*(*salFactoryProc)( oslModule pModule);\n}\n\nstatic oslModule pCloseModule = NULL;\n\nstatic SalInstance* tryInstance( const OUString& rModuleBase, bool bForce = false )\n{\n SalInstance* pInst = NULL;\n \/\/ Disable gtk3 plugin for now unless explicitly requested via\n \/\/ SAL_USE_VCLPLUGIN=gtk3 (would ideally depend on experimental mode, but\n \/\/ reading the experimental mode setting requires the UNO service manager\n \/\/ which has not yet been instantiated):\n if (!bForce && rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk3\")))\n {\n return NULL;\n }\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"vclplug_\" );\n aModName.append( rModuleBase );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n if( aMod )\n {\n salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, \"create_SalInstance\" );\n if( aProc )\n {\n pInst = aProc( aMod );\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"sal plugin %s produced instance %p\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(),\n pInst );\n#endif\n if( pInst )\n {\n pCloseModule = aMod;\n\n#ifndef ANDROID\n \/*\n * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can\n * not access the 'gnome_accessibility_module_shutdown' anymore.\n * So make sure libgtk+ & co are still mapped into memory when\n * atk-bridge's atexit handler gets called.\n * #i109007# KDE3 seems to have the same problem.\n\t\t * And same applies for KDE4.\n *\/\n if( rModuleBase == \"gtk\" || rModuleBase == \"gtk3\" || rModuleBase == \"tde\" || rModuleBase == \"kde\" || rModuleBase == \"kde4\" )\n {\n pCloseModule = NULL;\n }\n#endif\n GetSalData()->m_pPlugin = aMod;\n }\n else\n osl_unloadModule( aMod );\n }\n else\n {\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"could not load symbol %s from shared object %s\\n\",\n \"create_SalInstance\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n osl_unloadModule( aMod );\n }\n }\n#if OSL_DEBUG_LEVEL > 1\n else\n std::fprintf( stderr, \"could not load shared object %s\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n\n return pInst;\n}\n\n#if !defined(ANDROID)\n\nstatic DesktopType get_desktop_environment()\n{\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"desktop_detector\" );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n DesktopType ret = DESKTOP_UNKNOWN;\n if( aMod )\n {\n DesktopType (*pSym)() = (DesktopType(*)())\n osl_getAsciiFunctionSymbol( aMod, \"get_desktop_environment\" );\n if( pSym )\n ret = pSym();\n }\n osl_unloadModule( aMod );\n return ret;\n}\n\n#else\n\n#define get_desktop_environment() DESKTOP_NONE \/\/ For now...\n\n#endif\n\nstatic SalInstance* autodetect_plugin()\n{\n static const char* pTDEFallbackList[] =\n {\n \"tde\", \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pKDEFallbackList[] =\n {\n \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pStandardFallbackList[] =\n {\n \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pHeadlessFallbackList[] =\n {\n \"svp\", 0\n };\n\n DesktopType desktop = get_desktop_environment();\n const char ** pList = pStandardFallbackList;\n int nListEntry = 0;\n\n \/\/ no server at all: dummy plugin\n if ( desktop == DESKTOP_NONE )\n pList = pHeadlessFallbackList;\n else if ( desktop == DESKTOP_GNOME )\n pList = pStandardFallbackList;\n else if( desktop == DESKTOP_TDE )\n pList = pTDEFallbackList;\n else if( desktop == DESKTOP_KDE )\n {\n pList = pKDEFallbackList;\n nListEntry = 1;\n }\n else if( desktop == DESKTOP_KDE4 )\n pList = pKDEFallbackList;\n\n SalInstance* pInst = NULL;\n while( pList[nListEntry] && pInst == NULL )\n {\n rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) );\n pInst = tryInstance( aTry );\n #if OSL_DEBUG_LEVEL > 1\n if( pInst )\n std::fprintf( stderr, \"plugin autodetection: %s\\n\", pList[nListEntry] );\n #endif\n nListEntry++;\n }\n\n return pInst;\n}\n\nstatic SalInstance* check_headless_plugin()\n{\n int nParams = osl_getCommandArgCount();\n OUString aParam;\n for( int i = 0; i < nParams; i++ )\n {\n osl_getCommandArg( i, &aParam.pData );\n if( aParam == \"-headless\" || aParam == \"--headless\" )\n {\n return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( \"svp\" ) ) );\n }\n }\n return NULL;\n}\n\nSalInstance *CreateSalInstance()\n{\n SalInstance* pInst = NULL;\n\n static const char* pUsePlugin = getenv( \"SAL_USE_VCLPLUGIN\" );\n\n pInst = check_headless_plugin();\n\n if( !pInst && pUsePlugin && *pUsePlugin )\n pInst = tryInstance( OUString::createFromAscii( pUsePlugin ), true );\n\n if( ! pInst )\n pInst = autodetect_plugin();\n\n \/\/ fallback, try everything\n const char* pPlugin[] = { \"gtk3\", \"gtk\", \"kde4\", \"kde\", \"tde\", \"gen\", 0 };\n\n for ( int i = 0; !pInst && pPlugin[ i ]; ++i )\n pInst = tryInstance( OUString::createFromAscii( pPlugin[ i ] ) );\n\n if( ! pInst )\n {\n std::fprintf( stderr, \"no suitable windowing system found, exiting.\\n\" );\n _exit( 1 );\n }\n\n \/\/ acquire SolarMutex\n pInst->AcquireYieldMutex( 1 );\n\n return pInst;\n}\n\nvoid DestroySalInstance( SalInstance *pInst )\n{\n \/\/ release SolarMutex\n pInst->ReleaseYieldMutex();\n\n delete pInst;\n if( pCloseModule )\n osl_unloadModule( pCloseModule );\n}\n\nvoid InitSalData()\n{\n}\n\nvoid DeInitSalData()\n{\n}\n\nvoid InitSalMain()\n{\n}\n\nvoid DeInitSalMain()\n{\n}\n\nvoid SalAbort( const rtl::OUString& rErrorText, bool bDumpCore )\n{\n if( rErrorText.isEmpty() )\n std::fprintf( stderr, \"Application Error\\n\" );\n else\n std::fprintf( stderr, \"%s\\n\", rtl::OUStringToOString(rErrorText, osl_getThreadTextEncoding()).getStr() );\n if( bDumpCore )\n abort();\n else\n _exit(1);\n}\n\nstatic const char * desktop_strings[] = { \"none\", \"unknown\", \"GNOME\", \"TDE\", \"KDE\", \"KDE4\" };\n\nconst OUString& SalGetDesktopEnvironment()\n{\n static rtl::OUString aRet;\n if( aRet.isEmpty())\n {\n rtl::OUStringBuffer buf( 8 );\n buf.appendAscii( desktop_strings[ get_desktop_environment() ] );\n aRet = buf.makeStringAndClear();\n }\n return aRet;\n}\n\nSalData::SalData() :\n m_pInstance(NULL),\n m_pPlugin(NULL),\n m_pPIManager(NULL)\n{\n}\n\nSalData::~SalData()\n{\n psp::PrinterInfoManager::release();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <agency\/detail\/tuple.hpp>\n#include <agency\/detail\/integer_sequence.hpp>\n#include <agency\/coordinate.hpp>\n#include <utility>\n#include <type_traits>\n\nnamespace agency\n{\nnamespace detail\n{\nnamespace new_executor_traits_detail\n{\n\n\ntemplate<class T, class Executor>\nusing shared_parameter_container = typename new_executor_traits<Executor>::template container<T>;\n\n\ntemplate<class Executor, class T>\nshared_parameter_container<T,Executor> make_shared_parameter_container(Executor&, size_t n, const T& shared_init)\n{\n return shared_parameter_container<T,Executor>(n, shared_init);\n}\n\n\ntemplate<size_t depth, class Shape>\n__AGENCY_ANNOTATION\nsize_t number_of_groups_at_depth(const Shape& shape)\n{\n \/\/ to compute the number of groups at a particular depth given a shape,\n \/\/ take the first depth elements of shape and return shape_size\n return detail::shape_size(detail::tuple_take<depth>(shape));\n}\n\n\ntemplate<class Executor, class... Types>\nusing tuple_of_shared_parameter_containers = detail::tuple<shared_parameter_container<Types,Executor>...>;\n\ntemplate<class Executor, class... Types>\nstruct tuple_of_shared_parameter_containers_war_nvbug1665680\n{\n using type = detail::tuple<shared_parameter_container<Types,Executor>...>;\n};\n\n\ntemplate<size_t... Indices, class Executor, class... Types>\ntuple_of_shared_parameter_containers<Executor,Types...>\n make_tuple_of_shared_parameter_containers(detail::index_sequence<Indices...>, Executor& ex, typename new_executor_traits<Executor>::shape_type shape, const Types&... shared_inits)\n{\n return detail::make_tuple(make_shared_parameter_container(ex, number_of_groups_at_depth<Indices>(shape), shared_inits)...);\n}\n\n\ntemplate<class Executor, class... Types>\ntuple_of_shared_parameter_containers<Executor, typename std::decay<Types>::type...>\n make_tuple_of_shared_parameter_containers(Executor& ex, typename new_executor_traits<Executor>::shape_type shape, Types&&... shared_inits)\n{\n return make_tuple_of_shared_parameter_containers(detail::make_index_sequence<sizeof...(shared_inits)>(), ex, shape, std::forward<Types>(shared_inits)...);\n}\n\n\n} \/\/ end new_executor_traits_detail\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Workaround nvbug 1665680<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <agency\/detail\/tuple.hpp>\n#include <agency\/detail\/integer_sequence.hpp>\n#include <agency\/coordinate.hpp>\n#include <utility>\n#include <type_traits>\n\nnamespace agency\n{\nnamespace detail\n{\nnamespace new_executor_traits_detail\n{\n\n\ntemplate<class T, class Executor>\nusing shared_parameter_container = typename new_executor_traits<Executor>::template container<T>;\n\n\ntemplate<class Executor, class T>\nshared_parameter_container<T,Executor> make_shared_parameter_container(Executor&, size_t n, const T& shared_init)\n{\n return shared_parameter_container<T,Executor>(n, shared_init);\n}\n\n\ntemplate<size_t depth, class Shape>\n__AGENCY_ANNOTATION\nsize_t number_of_groups_at_depth(const Shape& shape)\n{\n \/\/ to compute the number of groups at a particular depth given a shape,\n \/\/ take the first depth elements of shape and return shape_size\n return detail::shape_size(detail::tuple_take<depth>(shape));\n}\n\n\ntemplate<class Executor, class... Types>\nusing tuple_of_shared_parameter_containers = detail::tuple<shared_parameter_container<Types,Executor>...>;\n\ntemplate<class Executor, class... Types>\nstruct tuple_of_shared_parameter_containers_war_nvbug1665680\n{\n using type = detail::tuple<shared_parameter_container<Types,Executor>...>;\n};\n\n\ntemplate<size_t... Indices, class Executor, class... Types>\n\/\/tuple_of_shared_parameter_containers<Executor,Types...>\ntypename tuple_of_shared_parameter_containers_war_nvbug1665680<Executor,Types...>::type\n make_tuple_of_shared_parameter_containers(detail::index_sequence<Indices...>, Executor& ex, typename new_executor_traits<Executor>::shape_type shape, const Types&... shared_inits)\n{\n return detail::make_tuple(make_shared_parameter_container(ex, number_of_groups_at_depth<Indices>(shape), shared_inits)...);\n}\n\n\ntemplate<class Executor, class... Types>\n\/\/tuple_of_shared_parameter_containers<Executor, typename std::decay<Types>::type...>\ntypename tuple_of_shared_parameter_containers_war_nvbug1665680<Executor,typename std::decay<Types>::type...>::type\n make_tuple_of_shared_parameter_containers(Executor& ex, typename new_executor_traits<Executor>::shape_type shape, Types&&... shared_inits)\n{\n return make_tuple_of_shared_parameter_containers(detail::make_index_sequence<sizeof...(shared_inits)>(), ex, shape, std::forward<Types>(shared_inits)...);\n}\n\n\n} \/\/ end new_executor_traits_detail\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright since 2016 : Evgenii Shatunov (github.com\/FrankStain\/jnipp-test)\r\n\/\/ Apache 2.0 License\r\n#include <main.h>\r\n#include <gtest\/gtest.h>\r\n\r\n\r\n#define DECLARE_TEST_ENV( NAME, RET, ... )\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tjnipp::ClassHandle class_handle{ \"com\/pfs\/jnipptest\/TestFunctionDerivedContainer\" };\t\t\t\t\t\t\\\r\n\tjnipp::ClassHandle base_class_handle{ \"com\/pfs\/jnipptest\/TestFunctionContainer\" };\t\t\t\t\t\t\t\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tjnipp::FunctionHandle<RET, ##__VA_ARGS__>\tfunc{ base_class_handle, NAME };\t\t\t\t\t\t\t\t\\\r\n\tjnipp::FieldHandle<bool>\t\t\t\t\tcall_check{ base_class_handle, \"m_is_called\" };\t\t\t\t\t\\\r\n\tjnipp::ObjectHandle\t\t\t\t\t\t\ttest_object{ jnipp::ObjectHandle::NewObject( class_handle ) };\t\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( func );\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( call_check );\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( test_object )\r\n\r\n#define EXAMINE_CALL_FLAG( ... )\t\t\t\t\t\t\t\t\t\t\\\r\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\t\tbool is_called = false;\t\t\t\t\t\t\t\t\t\t\t\\\r\n\t\tEXPECT_TRUE( call_check.GetValue( test_object, is_called ) );\t\\\r\n\t\tEXPECT_TRUE( is_called );\t\t\t\t\t\t\t\t\t\t\\\r\n\t}\r\n\r\n\r\n\/\/TEST( TestFunctionHandle, CheckFunctionIds )\r\n\/\/{\r\n\/\/\tjnipp::ClassHandle base_class{ \"com\/pfs\/jnipptest\/TestFunctionContainer\" };\r\n\/\/\tjnipp::ClassHandle derived_class{ \"com\/pfs\/jnipptest\/TestFunctionDerivedContainer\" };\r\n\/\/\r\n\/\/\tjnipp::FunctionHandle<void>\tderived_class_func{ derived_class, \"VoidNoArguments\" };\r\n\/\/\tjnipp::FunctionHandle<void>\tbase_class_func{ base_class, \"VoidNoArguments\" };\r\n\/\/\r\n\/\/\tEXPECT_EQ( *base_class_func, *derived_class_func );\r\n\/\/};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidNoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidNoArguments\", void );\r\n\r\n\tfunc.CallNonVirtual( test_object, class_handle );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidOneArgument )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidOneArgument\", void, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, class_handle, \"1\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidTwoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidTwoArguments\", void, const char*, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, class_handle, \"1\", \"2\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidThreeArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidThreeArguments\", void, const char*, const char*, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, class_handle, \"1\", \"2\", \"3\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringNoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringNoArguments\", std::string );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, class_handle );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"Jni++\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringOneArgument )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringOneArgument\", std::string, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, class_handle, \"1\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringTwoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringTwoArguments\", std::string, const char*, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, class_handle, \"1\", \"2\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1 2\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringThreeArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringThreeArguments\", std::string, const char*, const char*, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, class_handle, \"1\", \"2\", \"3\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1 2 3\", ret.c_str() );\r\n};\r\n<commit_msg>Tests of non-virtual call refactored.<commit_after>\/\/ Copyright since 2016 : Evgenii Shatunov (github.com\/FrankStain\/jnipp-test)\r\n\/\/ Apache 2.0 License\r\n#include <main.h>\r\n#include <gtest\/gtest.h>\r\n\r\n\r\n#define DECLARE_TEST_ENV( NAME, RET, ... )\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tjnipp::ClassHandle derived_class{ \"com\/pfs\/jnipptest\/TestFunctionDerivedContainer\" };\t\t\t\t\t\t\\\r\n\tjnipp::ClassHandle basic_class{ derived_class.GetParentClassHandle() };\t\t\t\t\t\t\t\t\t\t\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tjnipp::FunctionHandle<RET, ##__VA_ARGS__>\tfunc{ basic_class, NAME };\t\t\t\t\t\t\t\t\t\t\\\r\n\tjnipp::FieldHandle<bool>\t\t\t\t\tcall_check{ basic_class, \"m_is_called\" };\t\t\t\t\t\t\\\r\n\tjnipp::ObjectHandle\t\t\t\t\t\t\ttest_object{ jnipp::ObjectHandle::NewObject( derived_class ) };\t\\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( func );\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( call_check );\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\tEXPECT_TRUE( test_object )\r\n\r\n#define EXAMINE_CALL_FLAG( ... )\t\t\t\t\t\t\t\t\t\t\\\r\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\r\n\t\tbool is_called = false;\t\t\t\t\t\t\t\t\t\t\t\\\r\n\t\tEXPECT_TRUE( call_check.GetValue( test_object, is_called ) );\t\\\r\n\t\tEXPECT_TRUE( is_called );\t\t\t\t\t\t\t\t\t\t\\\r\n\t}\r\n\r\n\r\n\/\/TEST( TestFunctionHandle, CheckFunctionIds )\r\n\/\/{\r\n\/\/\tjnipp::ClassHandle base_class{ \"com\/pfs\/jnipptest\/TestFunctionContainer\" };\r\n\/\/\tjnipp::ClassHandle derived_class{ \"com\/pfs\/jnipptest\/TestFunctionDerivedContainer\" };\r\n\/\/\r\n\/\/\tjnipp::FunctionHandle<void>\tderived_class_func{ derived_class, \"VoidNoArguments\" };\r\n\/\/\tjnipp::FunctionHandle<void>\tbase_class_func{ base_class, \"VoidNoArguments\" };\r\n\/\/\r\n\/\/\tEXPECT_EQ( *base_class_func, *derived_class_func );\r\n\/\/};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidNoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidNoArguments\", void );\r\n\r\n\tfunc.CallNonVirtual( test_object );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidOneArgument )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidOneArgument\", void, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, \"1\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidTwoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidTwoArguments\", void, const char*, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, \"1\", \"2\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvVoidThreeArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"VoidThreeArguments\", void, const char*, const char*, const char* );\r\n\r\n\tfunc.CallNonVirtual( test_object, \"1\", \"2\", \"3\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringNoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringNoArguments\", std::string );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"Jni++\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringOneArgument )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringOneArgument\", std::string, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, \"1\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringTwoArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringTwoArguments\", std::string, const char*, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, \"1\", \"2\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1 2\", ret.c_str() );\r\n};\r\n\r\nTEST( TestFunctionHandle, CallNvStringThreeArguments )\r\n{\r\n\tDECLARE_TEST_ENV( \"StringThreeArguments\", std::string, const char*, const char*, const char* );\r\n\r\n\tauto ret = func.CallNonVirtual( test_object, \"1\", \"2\", \"3\" );\r\n\r\n\tEXAMINE_CALL_FLAG();\r\n\tEXPECT_STREQ( \"1 2 3\", ret.c_str() );\r\n};\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"integrators\/explicit_embedded_runge_kutta_nyström_integrator.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <ctime>\n#include <vector>\n\n#include \"glog\/logging.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\n\nusing quantities::Difference;\nusing quantities::Quotient;\n\nnamespace integrators {\n\ntemplate<typename Position>\nvoid ExplicitEmbeddedRungeKuttaNyströmIntegrator::Solve(\n RightHandSideComputation<Position> compute_acceleration,\n SystemState<Position, Variation<Position>> const& initial_value,\n Time const& t_final,\n Time const& first_time_step,\n Difference<Position> const& position_tolerance,\n Variation<Position> const& velocity_tolerance,\n double const safety_factor,\n not_null<Solution<Position, Variation<Position>>*> const solution) const {\n int const dimension = initial_value.positions.size();\n CHECK_EQ(initial_value.momenta.size(), dimension);\n CHECK_NE(first_time_step, Time());\n bool const forward = first_time_step > Time();\n if (forward) {\n CHECK_LT(initial_value.time, t_final);\n } else {\n \/\/ Integrating backward.\n CHECK_GT(initial_value.time, t_final);\n }\n using Displacement = Difference<Position>;\n using Velocity = Variation<Position>;\n using Acceleration = Variation<Velocity>;\n \/\/ The timestep.\n Time h = first_time_step;\n DoublePrecision<Time> t;\n std::vector<Displacement> ∆q(dimension);\n std::vector<Velocity> ∆v(dimension);\n std::vector<DoublePrecision<Position>> q(dimension);\n std::vector<DoublePrecision<Position>> v(dimension);\n \/\/ The low-order integration is not performed using compensated summation.\n std::vector<Position> q_low_order(dimension);\n std::vector<Velocity> v_low_order(dimension);\n \/\/ TODO(egg): this is a rectangular container, use something more appropriate.\n std::vector<std::vector<Acceleration>> g(stages_);\n for (auto& g_stage : g) {\n g_stage.resize(dimension);\n }\n Time t_stage;\n std::vector<Displacement> q_stage(dimension);\n\n for (int k = 0; k < dimension; ++k) {\n ∆q[k] *= h;\n }\n for (int i = 0; i < stages_; ++i) {\n t_stage = t.value + c[i] * h;\n for (int k = 0; k < dimension; ++k) {\n for (int j = 0; j < i; ++j) {\n q_stage[k] += g[j][k] * a[i][j]\n }\n q_stage[k] *= h;\n q_stage[k] += c[i] * v[k].value;\n q_stage[k] *= h;\n q_stage[k] += q[k].value;\n }\n compute_acceleration(t_stage, q_stage, &g[i]);\n }\n for (int k = 0; k < dimension; ++k) {\n for (int i = 0; i < stages_; ++i) {\n ∆q[k] += b_hat_[i] * g[i][k];\n }\n ∆q[k] *= h;\n ∆q[k] += v[k].value;\n ∆q[k] *= h;\n }\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\n<commit_msg>some implementation<commit_after>#pragma once\n\n#include \"integrators\/explicit_embedded_runge_kutta_nyström_integrator.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <ctime>\n#include <vector>\n\n#include \"glog\/logging.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\n\nusing quantities::Difference;\nusing quantities::Quotient;\n\nnamespace integrators {\n\ntemplate<typename Position>\nvoid ExplicitEmbeddedRungeKuttaNyströmIntegrator::Solve(\n RightHandSideComputation<Position> compute_acceleration,\n SystemState<Position, Variation<Position>> const& initial_value,\n Time const& t_final,\n Time const& first_time_step,\n Difference<Position> const& position_tolerance,\n Variation<Position> const& velocity_tolerance,\n double const safety_factor,\n not_null<Solution<Position, Variation<Position>>*> const solution) const {\n int const dimension = initial_value.positions.size();\n CHECK_EQ(initial_value.momenta.size(), dimension);\n CHECK_NE(first_time_step, Time());\n bool const forward = first_time_step > Time();\n if (forward) {\n CHECK_LT(initial_value.time, t_final);\n } else {\n \/\/ Integrating backward.\n CHECK_GT(initial_value.time, t_final);\n }\n using Displacement = Difference<Position>;\n using Velocity = Variation<Position>;\n using Acceleration = Variation<Velocity>;\n \/\/ The timestep.\n Time h = first_time_step;\n DoublePrecision<Time> t;\n std::vector<Displacement> ∆q(dimension);\n std::vector<Velocity> ∆v(dimension);\n std::vector<DoublePrecision<Position>> q(dimension);\n std::vector<DoublePrecision<Position>> v(dimension);\n std::vector<Position> ∆q_low_order(dimension);\n std::vector<Velocity> ∆v_low_order(dimension);\n \/\/ TODO(egg): this is a rectangular container, use something more appropriate.\n std::vector<std::vector<Acceleration>> g(stages_);\n for (auto& g_stage : g) {\n g_stage.resize(dimension);\n }\n Time t_stage;\n std::vector<Position> q_stage(dimension);\n\n std::fill(∆q.begin(), ∆q.end(), Displacement());\n\n for (int i = 0; i < stages_; ++i) {\n t_stage = t.value + c[i] * h;\n for (int k = 0; k < dimension; ++k) {\n Acceleration ∑_a_ij_g_j;\n for (int j = 0; j < i; ++j) {\n ∑_a_ij_g_j += g[j][k] * a[i][j]\n }\n q_stage[k] = q[k].value + h * (c[i] * v[k].value + h * ∑_a_ij_g_j);\n }\n compute_acceleration(t_stage, q_stage, &g[i]);\n }\n\n for (int k = 0; k < dimension; ++k) {\n Acceleration ∑_b_hat_i_g_i;\n Acceleration ∑_b_i_g_i;\n Acceleration ∑_b_prime_hat_i_g_i;\n Acceleration ∑_b_prime_i_g_i;\n \/\/ TODO(egg): this would be more readable if it were aligned on the += \/ =.\n for (int i = 0; i < stages_; ++i) {\n ∑_b_hat_i_g_i += b_hat_[i] * g[i][k];\n ∑_b_i_g_i += b_[i] * g[i][k];\n ∑_b_prime_hat_i_g_i += b_prime_hat_[i] * g[i][k];\n ∑_b_prime_i_g_i += b_prime_[i] * g[i][k];\n }\n ∆q[k] = h * (h * (∑_b_hat_i_g_i) + v[k].value);\n ∆q_low_order[k] = h * (h * (∑_b_i_g_i) + v[k].value);\n ∆v[k] = h * ∑_b_prime_hat_i_g_i;\n ∆v_low_order[k] = h * ∑_b_prime_i_g_i;\n }\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file get-set-blob.cpp\n * \\author Denis Martinez\n * \\date 2009-09-06\n *\/\n\n#include <ppasskeeper.h>\n#include \"unittest.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\nppk_entry* app_entry, * net_entry, * item_entry;\nppk_data* data;\nstd::vector<ppk_entry*> entries;\n\nvoid delete_all()\n{\n\tdelete app_entry;\n\tdelete net_entry;\n\tdelete item_entry;\n\tdelete data;\n}\n\nstd::string readFile(std::string filepath)\n{\n\t\/\/open the file\n\tstd::ifstream inputfile(filepath.c_str());\n\tif(inputfile.is_open())\n\t{\n\t\t\/\/Read the password from the file\n\t\tstd::ostringstream pwd_s;\n\t\tpwd_s << inputfile.rdbuf();\n\n\t\t\/\/close the file\n\t\tinputfile.close();\n\n\t\treturn pwd_s.str();\n\t}\n\telse\n\t\treturn std::string();\n}\n\nvoid run(int argc, char** argv)\n{\n\tchar *module_id = argv[1];\n\n\tapp_entry=ppk_application_entry_new(\"test\",\"utstblob_write_string\");\n\tnet_entry=ppk_network_entry_new(NULL, \"test\", \"utstblob_write_string\", 99);\n\titem_entry=ppk_item_entry_new(\"utstblob_write_string\");\n\tentries.push_back(app_entry);\n\tentries.push_back(net_entry);\n\tentries.push_back(item_entry);\n\n\tFAILIF(ppk_is_locked()==PPK_TRUE);\n\tFAILIF(ppk_module_is_available(module_id)==PPK_FALSE);\n\n\tsize_t max_size=ppk_module_max_data_size(module_id, ppk_blob);\n\tif(max_size==0)\n\t{\n\t\tstd::cerr << \"* No blob support in \" << module_id << std::endl;\n\t\tdelete_all();\n\t\treturn;\n\t}\n\t\n\t\/\/If the module doesn't support writing\/listing\n\tppk_boolean writable=ppk_module_is_writable(module_id);\n\tif(writable==PPK_FALSE)\n\t{\n\t\tstd::cerr << \"* The module \" << module_id << \" is read-only\" << std::endl;\n\t}\n\n\tstd::string file=readFile(argv[0]);\n\tbool read_file_ok = file != std::string();\n\tFAILIF(! read_file_ok);\n\n\tif (max_size<file.size())\n\t\tfile=file.substr(0, max_size);\n\n\tdata=ppk_blob_data_new(file.data(), file.size());\n\n\tfor (int i = 0; i < entries.size(); ++i)\n\t{\n\t\tppk_entry* entry = entries[i];\n\n\t\t\/* Write *\/\n\t\tprintf(\"Set entry !\\n\");\n\t\tppk_error res=ppk_module_set_entry(module_id, entry, data, ppk_wf_none);\n\t\tASSERT(writable == PPK_TRUE && res == PPK_OK);\n\t\tif(res == PPK_OK)\n\t\t{\n\t\t\t\/* Read *\/\n\t\t\tprintf(\"read\\n\");\n\t\t\tppk_data* edata;\n\t\t\tres=ppk_module_get_entry(module_id, entry, &edata, ppk_rf_none);\n\t\t\tASSERT(res == PPK_OK);\n\t\t\tif (res != PPK_OK)\n\t\t\t\tcontinue;\n\n\t\t\t\/* Delete *\/\n\t\t\tprintf(\"delete\\n\");\n\t\t\tres=ppk_module_remove_entry(module_id, entry, ppk_rf_none);\n\t\t\tASSERT(writable == PPK_TRUE && res == PPK_OK);\n\n\t\t\tprintf(\"Test la correspondance\\n\");\n\t\t\tbool valid_type = edata->type == ppk_blob;\n\t\t\tASSERT(valid_type);\n\t\t\tif (valid_type)\n\t\t\t{\n\t\t\t\tstd::string res;\n\t\t\t\tres.assign((const char*)edata->blob.data, edata->blob.size);\n\t\t\t\tppk_data_free(edata);\n\n\t\t\t\tbool same_data = res == file;\n\t\t\t\tASSERT(same_data);\n\t\t\t\tif(! same_data)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"* Before : size = \" << file.size() << \" and data = \" << (const char*)file.data() << std::endl;\n\t\t\t\t\tstd::cerr << \"* After : size = \" << edata->blob.size << \" and data = \" << (const char*)edata->blob.data << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete_all();\n}\n<commit_msg>Unittest: Get rid of some printf<commit_after>\/**\n * \\file get-set-blob.cpp\n * \\author Denis Martinez\n * \\date 2009-09-06\n *\/\n\n#include <ppasskeeper.h>\n#include \"unittest.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\nppk_entry* app_entry, * net_entry, * item_entry;\nppk_data* data;\nstd::vector<ppk_entry*> entries;\n\nvoid delete_all()\n{\n\tdelete app_entry;\n\tdelete net_entry;\n\tdelete item_entry;\n\tdelete data;\n}\n\nstd::string readFile(std::string filepath)\n{\n\t\/\/open the file\n\tstd::ifstream inputfile(filepath.c_str());\n\tif(inputfile.is_open())\n\t{\n\t\t\/\/Read the password from the file\n\t\tstd::ostringstream pwd_s;\n\t\tpwd_s << inputfile.rdbuf();\n\n\t\t\/\/close the file\n\t\tinputfile.close();\n\n\t\treturn pwd_s.str();\n\t}\n\telse\n\t\treturn std::string();\n}\n\nvoid run(int argc, char** argv)\n{\n\tchar *module_id = argv[1];\n\n\tapp_entry=ppk_application_entry_new(\"test\",\"utstblob_write_string\");\n\tnet_entry=ppk_network_entry_new(NULL, \"test\", \"utstblob_write_string\", 99);\n\titem_entry=ppk_item_entry_new(\"utstblob_write_string\");\n\tentries.push_back(app_entry);\n\tentries.push_back(net_entry);\n\tentries.push_back(item_entry);\n\n\tFAILIF(ppk_is_locked()==PPK_TRUE);\n\tFAILIF(ppk_module_is_available(module_id)==PPK_FALSE);\n\n\tsize_t max_size=ppk_module_max_data_size(module_id, ppk_blob);\n\tif(max_size==0)\n\t{\n\t\tstd::cerr << \"* No blob support in \" << module_id << std::endl;\n\t\tdelete_all();\n\t\treturn;\n\t}\n\t\n\t\/\/If the module doesn't support writing\/listing\n\tppk_boolean writable=ppk_module_is_writable(module_id);\n\tif(writable==PPK_FALSE)\n\t{\n\t\tstd::cerr << \"* The module \" << module_id << \" is read-only\" << std::endl;\n\t}\n\n\tstd::string file=readFile(argv[0]);\n\tbool read_file_ok = file != std::string();\n\tFAILIF(! read_file_ok);\n\n\tif (max_size<file.size())\n\t\tfile=file.substr(0, max_size);\n\n\tdata=ppk_blob_data_new(file.data(), file.size());\n\n\tfor (int i = 0; i < entries.size(); ++i)\n\t{\n\t\tppk_entry* entry = entries[i];\n\n\t\t\/* Write *\/\n\t\tppk_error res=ppk_module_set_entry(module_id, entry, data, ppk_wf_none);\n\t\tASSERT(writable == PPK_TRUE && res == PPK_OK);\n\t\tif(res == PPK_OK)\n\t\t{\n\t\t\t\/* Read *\/\n\t\t\tppk_data* edata;\n\t\t\tres=ppk_module_get_entry(module_id, entry, &edata, ppk_rf_none);\n\t\t\tASSERT(res == PPK_OK);\n\t\t\tif (res != PPK_OK)\n\t\t\t\tcontinue;\n\n\t\t\t\/* Delete *\/\n\t\t\tres=ppk_module_remove_entry(module_id, entry, ppk_rf_none);\n\t\t\tASSERT(writable == PPK_TRUE && res == PPK_OK);\n\n\t\t\tbool valid_type = edata->type == ppk_blob;\n\t\t\tASSERT(valid_type);\n\t\t\tif (valid_type)\n\t\t\t{\n\t\t\t\tstd::string res;\n\t\t\t\tres.assign((const char*)edata->blob.data, edata->blob.size);\n\t\t\t\tppk_data_free(edata);\n\n\t\t\t\tbool same_data = res == file;\n\t\t\t\tASSERT(same_data);\n\t\t\t\tif(! same_data)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"* Before : size = \" << file.size() << \" and data = \" << (const char*)file.data() << std::endl;\n\t\t\t\t\tstd::cerr << \"* After : size = \" << edata->blob.size << \" and data = \" << (const char*)edata->blob.data << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdelete_all();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <unordered_set>\n\n#include \"taichi\/ir\/ir.h\"\n#include \"taichi\/ir\/analysis.h\"\n#include \"taichi\/ir\/visitors.h\"\n#include \"taichi\/ir\/transforms.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass IRVerifier : public BasicStmtVisitor {\n private:\n Block *current_block;\n \/\/ each scope corresponds to an unordered_set\n std::vector<std::unordered_set<Stmt *>> visible_stmts;\n\n public:\n using BasicStmtVisitor::visit;\n\n explicit IRVerifier(IRNode *root) : current_block(nullptr) {\n allow_undefined_visitor = true;\n invoke_default_visitor = true;\n if (!root->is<Block>()) {\n visible_stmts.emplace_back();\n current_block = root->as<Stmt>()->parent;\n } else\n current_block = nullptr;\n }\n\n void basic_verify(Stmt *stmt) {\n TI_ASSERT_INFO(stmt->parent == current_block,\n \"stmt({})->parent({}) != current_block({})\", stmt->id,\n fmt::ptr(stmt->parent), fmt::ptr(current_block));\n for (auto &op : stmt->get_operands()) {\n if (op == nullptr)\n continue;\n bool found = false;\n for (int depth = (int)visible_stmts.size() - 1; depth >= 0; depth--) {\n if (visible_stmts[depth].find(op) != visible_stmts[depth].end()) {\n found = true;\n break;\n }\n }\n TI_ASSERT_INFO(\n found,\n \"IR broken: stmt {} cannot have operand {}.\"\n \" If you are using autodiff, please check\"\n \" https:\/\/taichi.readthedocs.io\/en\/stable\/\"\n \"differentiable_programming.html#kernel-simplicity-rule.\"\n \" If it doesn't help, please report this bug by opening an issue at\"\n \" https:\/\/github.com\/taichi-dev\/taichi to help us improve.\"\n \" Thanks in advance!\",\n stmt->id, op->id);\n }\n visible_stmts.back().insert(stmt);\n }\n\n void preprocess_container_stmt(Stmt *stmt) override {\n basic_verify(stmt);\n }\n\n void visit(Stmt *stmt) override {\n basic_verify(stmt);\n }\n\n void visit(Block *block) override {\n TI_ASSERT(block->parent == current_block);\n auto backup_block = current_block;\n current_block = block;\n visible_stmts.emplace_back();\n for (auto &stmt : block->statements) {\n stmt->accept(this);\n }\n current_block = backup_block;\n visible_stmts.pop_back();\n }\n\n void visit(LocalLoadStmt *stmt) override {\n basic_verify(stmt);\n for (int i = 0; i < stmt->width(); i++) {\n TI_ASSERT(stmt->ptr[i].var->is<AllocaStmt>());\n }\n }\n\n void visit(LocalStoreStmt *stmt) override {\n basic_verify(stmt);\n TI_ASSERT(stmt->ptr->is<AllocaStmt>());\n }\n\n void visit(LoopIndexStmt *stmt) override {\n basic_verify(stmt);\n TI_ASSERT(stmt->loop);\n if (stmt->loop->is<OffloadedStmt>()) {\n TI_ASSERT(stmt->loop->as<OffloadedStmt>()->task_type ==\n OffloadedStmt::TaskType::struct_for ||\n stmt->loop->as<OffloadedStmt>()->task_type ==\n OffloadedStmt::TaskType::range_for);\n } else {\n TI_ASSERT(stmt->loop->is<StructForStmt>() ||\n stmt->loop->is<RangeForStmt>());\n }\n }\n\n static void run(IRNode *root) {\n IRVerifier verifier(root);\n root->accept(&verifier);\n }\n};\n\nnamespace irpass::analysis {\nvoid verify(IRNode *root) {\n TI_AUTO_PROF;\n if (!root->is<Block>()) {\n TI_WARN(\"IR root is not a Block. Skipping verification.\");\n \/\/ TODO: support this case\n } else {\n IRVerifier::run(root);\n }\n}\n} \/\/ namespace irpass::analysis\n\nTLANG_NAMESPACE_END\n<commit_msg>[ir] Restore verification for OffloadedStmt (#1790)<commit_after>#include <vector>\n#include <unordered_set>\n\n#include \"taichi\/ir\/ir.h\"\n#include \"taichi\/ir\/analysis.h\"\n#include \"taichi\/ir\/visitors.h\"\n#include \"taichi\/ir\/transforms.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass IRVerifier : public BasicStmtVisitor {\n private:\n Block *current_block;\n \/\/ each scope corresponds to an unordered_set\n std::vector<std::unordered_set<Stmt *>> visible_stmts;\n\n public:\n using BasicStmtVisitor::visit;\n\n explicit IRVerifier(IRNode *root) : current_block(nullptr) {\n allow_undefined_visitor = true;\n invoke_default_visitor = true;\n if (!root->is<Block>()) {\n visible_stmts.emplace_back();\n current_block = nullptr;\n } else\n current_block = nullptr;\n }\n\n void basic_verify(Stmt *stmt) {\n if (current_block != nullptr) {\n \/\/ Temporary fix for root being OffloadedStmt\n TI_ASSERT_INFO(stmt->parent == current_block,\n \"stmt({})->parent({}) != current_block({})\", stmt->id,\n fmt::ptr(stmt->parent), fmt::ptr(current_block));\n }\n for (auto &op : stmt->get_operands()) {\n if (op == nullptr)\n continue;\n bool found = false;\n for (int depth = (int)visible_stmts.size() - 1; depth >= 0; depth--) {\n if (visible_stmts[depth].find(op) != visible_stmts[depth].end()) {\n found = true;\n break;\n }\n }\n TI_ASSERT_INFO(\n found,\n \"IR broken: stmt {} cannot have operand {}.\"\n \" If you are using autodiff, please check\"\n \" https:\/\/taichi.readthedocs.io\/en\/stable\/\"\n \"differentiable_programming.html#kernel-simplicity-rule.\"\n \" If it doesn't help, please report this bug by opening an issue at\"\n \" https:\/\/github.com\/taichi-dev\/taichi to help us improve.\"\n \" Thanks in advance!\",\n stmt->id, op->id);\n }\n visible_stmts.back().insert(stmt);\n }\n\n void preprocess_container_stmt(Stmt *stmt) override {\n basic_verify(stmt);\n }\n\n void visit(Stmt *stmt) override {\n basic_verify(stmt);\n }\n\n void visit(Block *block) override {\n TI_ASSERT(block->parent == current_block);\n auto backup_block = current_block;\n current_block = block;\n visible_stmts.emplace_back();\n for (auto &stmt : block->statements) {\n stmt->accept(this);\n }\n current_block = backup_block;\n visible_stmts.pop_back();\n }\n\n void visit(LocalLoadStmt *stmt) override {\n basic_verify(stmt);\n for (int i = 0; i < stmt->width(); i++) {\n TI_ASSERT(stmt->ptr[i].var->is<AllocaStmt>());\n }\n }\n\n void visit(LocalStoreStmt *stmt) override {\n basic_verify(stmt);\n TI_ASSERT(stmt->ptr->is<AllocaStmt>());\n }\n\n void visit(LoopIndexStmt *stmt) override {\n basic_verify(stmt);\n TI_ASSERT(stmt->loop);\n if (stmt->loop->is<OffloadedStmt>()) {\n TI_ASSERT(stmt->loop->as<OffloadedStmt>()->task_type ==\n OffloadedStmt::TaskType::struct_for ||\n stmt->loop->as<OffloadedStmt>()->task_type ==\n OffloadedStmt::TaskType::range_for);\n } else {\n TI_ASSERT(stmt->loop->is<StructForStmt>() ||\n stmt->loop->is<RangeForStmt>());\n }\n }\n\n static void run(IRNode *root) {\n IRVerifier verifier(root);\n root->accept(&verifier);\n }\n};\n\nnamespace irpass::analysis {\nvoid verify(IRNode *root) {\n TI_AUTO_PROF;\n if (!root->is<Block>() && !root->is<OffloadedStmt>()) {\n TI_WARN(\n \"IR root is neither a Block nor an OffloadedStmt.\"\n \" Skipping verification.\");\n } else {\n IRVerifier::run(root);\n }\n}\n} \/\/ namespace irpass::analysis\n\nTLANG_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"common.hh\"\n#include \"harness.hh\"\n\nint main(int argc, char* argv[]) {\n TADPOLE_UNUSED(argc), TADPOLE_UNUSED(argv);\n\n#if defined(_TADPOLE_RUN_HARNESS)\n tadpole::harness::run_all_harness();\n#endif\n\n return 0;\n}\n<commit_msg>:construction: chore(eval): add eval for tadpole interpreter<commit_after>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"common.hh\"\n#include \"colorful.hh\"\n#include \"harness.hh\"\n#include \"vm.hh\"\n\nnamespace tp = tadpole;\n\nstatic int eval(tp::TadpoleVM& vm, const tp::str_t& source_bytes) {\n tp::InterpretRet r = vm.interpret(source_bytes);\n if (r == tp::InterpretRet::ERUNTIME)\n return -1;\n else if (r == tp::InterpretRet::ECOMPILE)\n return -2;\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n TADPOLE_UNUSED(argc), TADPOLE_UNUSED(argv);\n\n#if defined(_TADPOLE_RUN_HARNESS)\n tp::harness::run_all_harness();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file translation_db_tool.cc\n * \\brief A tool for reading\/editing of the \"translations\" SQL table.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <set>\n#include <cstdlib>\n#include <cstring>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"SimpleXmlParser.h\"\n#include \"SqlUtil.h\"\n#include \"StringUtil.h\"\n#include \"TranslationUtil.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" command [args]\\n\\n\";\n std::cerr << \" Possible commands are:\\n\";\n std::cerr << \" get_missing language_code\\n\";\n std::cerr << \" insert token language_code text translator\\n\";\n std::cerr << \" insert ppn gnd_code language_code text translator\\n\";\n std::cerr << \" update token language_code text translator\\n\";\n std::cerr << \" update ppn gnd_code language_code text translator\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ExecSqlOrDie(const std::string &select_statement, DbConnection * const connection) {\n if (unlikely(not connection->query(select_statement)))\n Error(\"SQL Statement failed: \" + select_statement + \" (\" + connection->getLastErrorMessage() + \")\");\n}\n\n\n\/\/ Replaces a comma with \"\\,\" and a slash with \"\\\\\".\nstd::string EscapeCommasAndBackslashes(const std::string &text) {\n std::string escaped_text;\n for (const auto ch : text) {\n if (unlikely(ch == ',' or ch == '\\\\'))\n escaped_text += '\\\\';\n escaped_text += ch;\n }\n\n return escaped_text;\n}\n\n\nunsigned GetMissing(DbConnection * const connection, const std::string &table_name,\n const std::string &table_key_name, const std::string &category,\n const std::string &language_code, const std::string &additional_condition = \"\")\n{\n \/\/ Find a token\/ppn where \"language_code\" is missing:\n ExecSqlOrDie(\"SELECT distinct \" + table_key_name + \" FROM \" + table_name + \" WHERE \" + table_key_name +\n \" NOT IN (SELECT distinct \" + table_key_name + \" FROM \" + table_name +\n \" WHERE language_code = \\\"\" + language_code + \"\\\") \"\n + (additional_condition.empty() ? \"\" : \" AND (\" + additional_condition + \")\")\n + \" ORDER BY RAND();\", connection);\n DbResultSet keys_result_set(connection->getLastResultSet());\n if (keys_result_set.empty())\n return 0;\n\n \/\/ Print the contents of all rows with the token from the last query on stdout:\n DbRow row(keys_result_set.getNextRow());\n const std::string matching_key(row[table_key_name]);\n ExecSqlOrDie(\"SELECT * FROM \" + table_name + \" WHERE \" + table_key_name + \"='\" + matching_key + \"';\", connection);\n DbResultSet result_set(connection->getLastResultSet());\n if (result_set.empty())\n return 0;\n\n const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));\n const bool has_gnd_code(column_names.find(\"gnd_code\") != column_names.cend());\n\n while (row = result_set.getNextRow())\n std::cout << EscapeCommasAndBackslashes(row[table_key_name]) << ',' << keys_result_set.size() << ',' << row[\"language_code\"] << ','\n << EscapeCommasAndBackslashes(row[\"translation\"]) << ',' << category\n << (has_gnd_code ? \",\" + row[\"gnd_code\"] : \"\") << '\\n';\n\n return result_set.size();\n}\n\n\nunsigned GetMissingVuFindTranslations(DbConnection * const connection, const std::string &language_code) {\n return GetMissing(connection, \"vufind_translations\", \"token\", \"vufind_translations\", language_code);\n}\n\n\nunsigned GetMissingKeywordTranslations(DbConnection * const connection, const std::string &language_code) {\n return GetMissing(connection, \"keyword_translations\", \"ppn\", \"keyword_translations\", language_code, \"status != \\\"reliable_synonym\\\" AND status != \\\"unreliable_synonym\\\"\");\n}\n\n\nunsigned GetExisting(DbConnection * const connection, const std::string &table_name,\n const std::string &table_key_name, const std::string &category,\n const std::string &language_code, const std::string &index_value)\n{\n \/\/ Find a token\/ppn where \"language_code\" is missing:\n ExecSqlOrDie(\"SELECT distinct \" + table_key_name + \" FROM \" + table_name + \" WHERE \" + table_key_name +\n \" NOT IN (SELECT distinct \" + table_key_name + \" FROM \" + table_name +\n \" WHERE language_code = \\\"\" + language_code + \"\\\") ORDER BY RAND();\", connection);\n DbResultSet keys_result_set(connection->getLastResultSet());\n const size_t count(keys_result_set.size());\n\n ExecSqlOrDie(\"SELECT * FROM \" + table_name + \" WHERE \" + table_key_name + \"='\" + index_value + \"';\", connection);\n DbResultSet result_set(connection->getLastResultSet());\n if (result_set.empty())\n return 0;\n\n const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));\n const bool has_gnd_code(column_names.find(\"gnd_code\") != column_names.cend());\n\n while (const DbRow row = result_set.getNextRow())\n std::cout << EscapeCommasAndBackslashes(row[table_key_name]) << ',' << count << ',' << row[\"language_code\"] << ','\n << EscapeCommasAndBackslashes(row[\"translation\"]) << ',' << category\n << (has_gnd_code ? \",\" + row[\"gnd_code\"] : \"\") << '\\n';\n\n return result_set.size();\n}\n\n\nunsigned GetExistingVuFindTranslations(DbConnection * const connection, const std::string &language_code, const std::string &index_value) {\n return GetExisting(connection, \"vufind_translations\", \"token\", \"vufind_translations\", language_code, index_value);\n}\n\n\nunsigned GetExistingKeywordTranslations(DbConnection * const connection, const std::string &language_code, const std::string &index_value) {\n return GetExisting(connection, \"keyword_translations\", \"ppn\", \"keyword_translations\", language_code, index_value);\n}\n\n\n\nvoid InsertIntoVuFindTranslations(DbConnection * const connection, const std::string &token,\n const std::string &language_code, const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"INSERT INTO vufind_translations SET token=\\\"\" + token + \"\\\",language_code=\\\"\" + language_code\n + \"\\\",translation=\\\"\" + connection->escapeString(text) + \"\\\",translator=\\\"\" + translator + \"\\\";\", connection);\n}\n\n\nvoid InsertIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,\n const std::string &gnd_code, const std::string &language_code,\n const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"INSERT INTO keyword_translations SET ppn=\\\"\" + ppn + \"\\\",gnd_code=\\\"\" + gnd_code\n + \"\\\",language_code=\\\"\" + language_code + \"\\\",translation=\\\"\"\n + connection->escapeString(text) + \"\\\",origin=\\\"150\\\",status=\\\"new\\\"\" + \",translator=\\\"\" + translator + \"\\\";\", connection);\n}\n\n\nvoid UpdateIntoVuFindTranslations(DbConnection * const connection, const std::string &token,\n const std::string &language_code, const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"UPDATE vufind_translations SET translation=\\\"\" + connection->escapeString(text) + \"\\\", translator=\\\"\" + translator\n + \"\\\" WHERE token=\\\"\" + token + \"\\\" AND language_code=\\\"\" + language_code\n + \"\\\";\", connection);\n}\n\n\nvoid UpdateIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,\n const std::string &gnd_code, const std::string &language_code,\n const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"UPDATE keyword_translations SET translation=\\\"\" \n + connection->escapeString(text) \n + \"\\\", translator=\\\"\" + translator\n + \"\\\" WHERE ppn=\\\"\" + ppn + \"\\\" AND gnd_code=\\\"\" + gnd_code\n + \"\\\" AND language_code=\\\"\" + language_code + \"\\\";\", connection);\n}\n\n\nvoid ValidateKeywordTranslation(DbConnection * const connection, const std::string &ppn, const std::string &translation) {\n const std::string query(\"SELECT translation FROM keyword_translations WHERE ppn = \\\"\" + ppn + \"\\\";\");\n ExecSqlOrDie(query, connection);\n DbResultSet result_set(connection->getLastResultSet());\n\n while (const DbRow row = result_set.getNextRow()) {\n if (row[\"translation\"].find(\"<\") < row[\"translation\"].find(\">\")\n and not(translation.find(\"<\") < translation.find(\">\"))) {\n std::cout << \"Your translation has to have a tag enclosed by '<' and '>'!\";\n return;\n }\n }\n}\n\n\nconst std::string CONF_FILE_PATH(\"\/var\/lib\/tuelib\/translations.conf\");\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n try {\n if (argc < 2)\n Usage();\n\n const IniFile ini_file(CONF_FILE_PATH);\n const std::string sql_database(ini_file.getString(\"Database\", \"sql_database\"));\n const std::string sql_username(ini_file.getString(\"Database\", \"sql_username\"));\n const std::string sql_password(ini_file.getString(\"Database\", \"sql_password\"));\n DbConnection db_connection(sql_database, sql_username, sql_password);\n\n if (std::strcmp(argv[1], \"get_missing\") == 0) {\n if (argc != 3)\n Error(\"\\\"get_missing\\\" requires exactly one argument: language_code!\");\n const std::string language_code(argv[2]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n if (not GetMissingVuFindTranslations(&db_connection, language_code))\n GetMissingKeywordTranslations(&db_connection, language_code);\n } else if (std::strcmp(argv[1], \"get_existing\") == 0) {\n if (argc != 5)\n Error(\"\\\"get_existing\\\" requires exactly three arguments: language_code category index!\");\n const std::string language_code(argv[2]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n const std::string category(argv[3]);\n const std::string index_value(argv[4]);\n if (category == \"vufind_translations\")\n GetExistingVuFindTranslations(&db_connection, language_code, index_value);\n else\n GetExistingKeywordTranslations(&db_connection, language_code, index_value);\n } else if (std::strcmp(argv[1], \"insert\") == 0) {\n if (argc != 6 and argc != 7)\n Error(\"\\\"insert\\\" requires four or five arguments: token or ppn, gnd_code (if ppn), \"\n \"language_code, text, and translator!\");\n\n const std::string language_code(argv[(argc == 6) ? 3 : 4]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n\n if (argc == 6)\n InsertIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4], argv[5]);\n else\n InsertIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5], argv[6]);\n } else if (std::strcmp(argv[1], \"update\") == 0) {\n if (argc != 6 and argc != 7)\n Error(\"\\\"update\\\" requires four or five arguments: token or ppn, gnd_code (if ppn), \"\n \"language_code, text and translator!\");\n\n const std::string language_code(argv[(argc == 6) ? 3 : 4]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n\n if (argc == 6)\n UpdateIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4], argv[5]);\n else\n UpdateIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5], argv[6]);\n } else if (std::strcmp(argv[1], \"validate_keyword\") == 0) {\n if (argc != 4)\n Error(\"\\\"get_missing\\\" requires exactly two argument: ppn translation!\");\n const std::string ppn(argv[2]);\n const std::string translation(argv[3]);\n ValidateKeywordTranslation(&db_connection, ppn, translation);\n } else\n Error(\"unknown command \\\"\" + std::string(argv[1]) + \"\\\"!\");\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()) + \" (login is \" + MiscUtil::GetUserName() + \")\");\n }\n}\n<commit_msg>Workaround to prevent MACS translations from being overwritten even on iterative writes<commit_after>\/** \\file translation_db_tool.cc\n * \\brief A tool for reading\/editing of the \"translations\" SQL table.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <set>\n#include <cstdlib>\n#include <cstring>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"DbRow.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"SimpleXmlParser.h\"\n#include \"SqlUtil.h\"\n#include \"StringUtil.h\"\n#include \"TranslationUtil.h\"\n#include \"util.h\"\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" command [args]\\n\\n\";\n std::cerr << \" Possible commands are:\\n\";\n std::cerr << \" get_missing language_code\\n\";\n std::cerr << \" insert token language_code text translator\\n\";\n std::cerr << \" insert ppn gnd_code language_code text translator\\n\";\n std::cerr << \" update token language_code text translator\\n\";\n std::cerr << \" update ppn gnd_code language_code text translator\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid ExecSqlOrDie(const std::string &select_statement, DbConnection * const connection) {\n if (unlikely(not connection->query(select_statement)))\n Error(\"SQL Statement failed: \" + select_statement + \" (\" + connection->getLastErrorMessage() + \")\");\n}\n\n\n\/\/ Replaces a comma with \"\\,\" and a slash with \"\\\\\".\nstd::string EscapeCommasAndBackslashes(const std::string &text) {\n std::string escaped_text;\n for (const auto ch : text) {\n if (unlikely(ch == ',' or ch == '\\\\'))\n escaped_text += '\\\\';\n escaped_text += ch;\n }\n\n return escaped_text;\n}\n\n\nunsigned GetMissing(DbConnection * const connection, const std::string &table_name,\n const std::string &table_key_name, const std::string &category,\n const std::string &language_code, const std::string &additional_condition = \"\")\n{\n \/\/ Find a token\/ppn where \"language_code\" is missing:\n ExecSqlOrDie(\"SELECT distinct \" + table_key_name + \" FROM \" + table_name + \" WHERE \" + table_key_name +\n \" NOT IN (SELECT distinct \" + table_key_name + \" FROM \" + table_name +\n \" WHERE language_code = \\\"\" + language_code + \"\\\") \"\n + (additional_condition.empty() ? \"\" : \" AND (\" + additional_condition + \")\")\n + \" ORDER BY RAND();\", connection);\n DbResultSet keys_result_set(connection->getLastResultSet());\n if (keys_result_set.empty())\n return 0;\n\n \/\/ Print the contents of all rows with the token from the last query on stdout:\n DbRow row(keys_result_set.getNextRow());\n const std::string matching_key(row[table_key_name]);\n ExecSqlOrDie(\"SELECT * FROM \" + table_name + \" WHERE \" + table_key_name + \"='\" + matching_key + \"';\", connection);\n DbResultSet result_set(connection->getLastResultSet());\n if (result_set.empty())\n return 0;\n\n const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));\n const bool has_gnd_code(column_names.find(\"gnd_code\") != column_names.cend());\n\n while (row = result_set.getNextRow())\n std::cout << EscapeCommasAndBackslashes(row[table_key_name]) << ',' << keys_result_set.size() << ',' << row[\"language_code\"] << ','\n << EscapeCommasAndBackslashes(row[\"translation\"]) << ',' << category\n << (has_gnd_code ? \",\" + row[\"gnd_code\"] : \"\") << '\\n';\n\n return result_set.size();\n}\n\n\nunsigned GetMissingVuFindTranslations(DbConnection * const connection, const std::string &language_code) {\n return GetMissing(connection, \"vufind_translations\", \"token\", \"vufind_translations\", language_code);\n}\n\n\nunsigned GetMissingKeywordTranslations(DbConnection * const connection, const std::string &language_code) {\n return GetMissing(connection, \"keyword_translations\", \"ppn\", \"keyword_translations\", language_code, \"status != \\\"reliable_synonym\\\" AND status != \\\"unreliable_synonym\\\"\");\n}\n\n\nunsigned GetExisting(DbConnection * const connection, const std::string &table_name,\n const std::string &table_key_name, const std::string &category,\n const std::string &language_code, const std::string &index_value)\n{\n \/\/ Find a token\/ppn where \"language_code\" is missing:\n ExecSqlOrDie(\"SELECT distinct \" + table_key_name + \" FROM \" + table_name + \" WHERE \" + table_key_name +\n \" NOT IN (SELECT distinct \" + table_key_name + \" FROM \" + table_name +\n \" WHERE language_code = \\\"\" + language_code + \"\\\") ORDER BY RAND();\", connection);\n DbResultSet keys_result_set(connection->getLastResultSet());\n const size_t count(keys_result_set.size());\n\n ExecSqlOrDie(\"SELECT * FROM \" + table_name + \" WHERE \" + table_key_name + \"='\" + index_value + \"';\", connection);\n DbResultSet result_set(connection->getLastResultSet());\n if (result_set.empty())\n return 0;\n\n const std::set<std::string> column_names(SqlUtil::GetColumnNames(connection, table_name));\n const bool has_gnd_code(column_names.find(\"gnd_code\") != column_names.cend());\n\n while (const DbRow row = result_set.getNextRow())\n std::cout << EscapeCommasAndBackslashes(row[table_key_name]) << ',' << count << ',' << row[\"language_code\"] << ','\n << EscapeCommasAndBackslashes(row[\"translation\"]) << ',' << category\n << (has_gnd_code ? \",\" + row[\"gnd_code\"] : \"\") << '\\n';\n\n return result_set.size();\n}\n\n\nunsigned GetExistingVuFindTranslations(DbConnection * const connection, const std::string &language_code, const std::string &index_value) {\n return GetExisting(connection, \"vufind_translations\", \"token\", \"vufind_translations\", language_code, index_value);\n}\n\n\nunsigned GetExistingKeywordTranslations(DbConnection * const connection, const std::string &language_code, const std::string &index_value) {\n return GetExisting(connection, \"keyword_translations\", \"ppn\", \"keyword_translations\", language_code, index_value);\n}\n\n\n\nvoid InsertIntoVuFindTranslations(DbConnection * const connection, const std::string &token,\n const std::string &language_code, const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"INSERT INTO vufind_translations SET token=\\\"\" + token + \"\\\",language_code=\\\"\" + language_code\n + \"\\\",translation=\\\"\" + connection->escapeString(text) + \"\\\",translator=\\\"\" + translator + \"\\\";\", connection);\n}\n\n\nvoid InsertIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,\n const std::string &gnd_code, const std::string &language_code,\n const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"INSERT INTO keyword_translations SET ppn=\\\"\" + ppn + \"\\\",gnd_code=\\\"\" + gnd_code\n + \"\\\",language_code=\\\"\" + language_code + \"\\\",translation=\\\"\"\n + connection->escapeString(text) + \"\\\",origin=\\\"150\\\",status=\\\"new\\\"\" + \",translator=\\\"\" + translator + \"\\\";\", connection);\n}\n\n\nvoid UpdateIntoVuFindTranslations(DbConnection * const connection, const std::string &token,\n const std::string &language_code, const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"UPDATE vufind_translations SET translation=\\\"\" + connection->escapeString(text) + \"\\\", translator=\\\"\" + translator\n + \"\\\" WHERE token=\\\"\" + token + \"\\\" AND language_code=\\\"\" + language_code\n + \"\\\";\", connection);\n}\n\n\nvoid UpdateIntoKeywordTranslations(DbConnection * const connection, const std::string &ppn,\n const std::string &gnd_code, const std::string &language_code,\n const std::string &text, const std::string &translator)\n{\n ExecSqlOrDie(\"UPDATE keyword_translations SET translation=\\\"\" \n + connection->escapeString(text) \n + \"\\\", translator=\\\"\" + translator\n + \"\\\" WHERE ppn=\\\"\" + ppn + \"\\\" AND gnd_code=\\\"\" + gnd_code\n + \"\\\" AND language_code=\\\"\" + language_code + \"\\\"\" + \"AND status != \\\"unreliable\\\";\", connection);\n}\n\n\nvoid ValidateKeywordTranslation(DbConnection * const connection, const std::string &ppn, const std::string &translation) {\n const std::string query(\"SELECT translation FROM keyword_translations WHERE ppn = \\\"\" + ppn + \"\\\";\");\n ExecSqlOrDie(query, connection);\n DbResultSet result_set(connection->getLastResultSet());\n\n while (const DbRow row = result_set.getNextRow()) {\n if (row[\"translation\"].find(\"<\") < row[\"translation\"].find(\">\")\n and not(translation.find(\"<\") < translation.find(\">\"))) {\n std::cout << \"Your translation has to have a tag enclosed by '<' and '>'!\";\n return;\n }\n }\n}\n\n\nconst std::string CONF_FILE_PATH(\"\/var\/lib\/tuelib\/translations.conf\");\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n try {\n if (argc < 2)\n Usage();\n\n const IniFile ini_file(CONF_FILE_PATH);\n const std::string sql_database(ini_file.getString(\"Database\", \"sql_database\"));\n const std::string sql_username(ini_file.getString(\"Database\", \"sql_username\"));\n const std::string sql_password(ini_file.getString(\"Database\", \"sql_password\"));\n DbConnection db_connection(sql_database, sql_username, sql_password);\n\n if (std::strcmp(argv[1], \"get_missing\") == 0) {\n if (argc != 3)\n Error(\"\\\"get_missing\\\" requires exactly one argument: language_code!\");\n const std::string language_code(argv[2]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n if (not GetMissingVuFindTranslations(&db_connection, language_code))\n GetMissingKeywordTranslations(&db_connection, language_code);\n } else if (std::strcmp(argv[1], \"get_existing\") == 0) {\n if (argc != 5)\n Error(\"\\\"get_existing\\\" requires exactly three arguments: language_code category index!\");\n const std::string language_code(argv[2]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n const std::string category(argv[3]);\n const std::string index_value(argv[4]);\n if (category == \"vufind_translations\")\n GetExistingVuFindTranslations(&db_connection, language_code, index_value);\n else\n GetExistingKeywordTranslations(&db_connection, language_code, index_value);\n } else if (std::strcmp(argv[1], \"insert\") == 0) {\n if (argc != 6 and argc != 7)\n Error(\"\\\"insert\\\" requires four or five arguments: token or ppn, gnd_code (if ppn), \"\n \"language_code, text, and translator!\");\n\n const std::string language_code(argv[(argc == 6) ? 3 : 4]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n\n if (argc == 6)\n InsertIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4], argv[5]);\n else\n InsertIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5], argv[6]);\n } else if (std::strcmp(argv[1], \"update\") == 0) {\n if (argc != 6 and argc != 7)\n Error(\"\\\"update\\\" requires four or five arguments: token or ppn, gnd_code (if ppn), \"\n \"language_code, text and translator!\");\n\n const std::string language_code(argv[(argc == 6) ? 3 : 4]);\n if (not TranslationUtil::IsValidFake3LetterEnglishLanguagesCode(language_code))\n Error(\"\\\"\" + language_code + \"\\\" is not a valid fake 3-letter english language code!\");\n\n if (argc == 6)\n UpdateIntoVuFindTranslations(&db_connection, argv[2], language_code, argv[4], argv[5]);\n else\n UpdateIntoKeywordTranslations(&db_connection, argv[2], argv[3], language_code, argv[5], argv[6]);\n } else if (std::strcmp(argv[1], \"validate_keyword\") == 0) {\n if (argc != 4)\n Error(\"\\\"get_missing\\\" requires exactly two argument: ppn translation!\");\n const std::string ppn(argv[2]);\n const std::string translation(argv[3]);\n ValidateKeywordTranslation(&db_connection, ppn, translation);\n } else\n Error(\"unknown command \\\"\" + std::string(argv[1]) + \"\\\"!\");\n } catch (const std::exception &x) {\n Error(\"caught exception: \" + std::string(x.what()) + \" (login is \" + MiscUtil::GetUserName() + \")\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- CacheTest.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/Cache.h\"\n#include \"gtest\/gtest.h\"\n\n#if defined(__APPLE__)\n#define USES_LIBCACHE 1\n#else\n#define USES_LIBCACHE 0\n#endif\n\nnamespace {\nstruct Counter {\n mutable int enter = 0;\n mutable int exit = 0;\n};\n}\n\nnamespace swift {\nnamespace sys {\ntemplate <>\nstruct CacheValueInfo<Counter>{\n static void *enterCache(const Counter &value) {\n return const_cast<Counter *>(&value);\n }\n static void retain(void *ptr) {\n static_cast<Counter*>(ptr)->enter+= 1;\n }\n static void release(void *ptr) {\n static_cast<Counter*>(ptr)->exit += 1;\n }\n static const Counter &getFromCache(void *ptr) {\n return *static_cast<Counter *>(ptr);\n }\n static size_t getCost(const Counter &value) {\n return 0;\n }\n};\n}\n}\n\nnamespace {\nstruct KeyCounter {\n int key = 0;\n mutable int enter = 0;\n mutable int exit = 0;\n};\n}\n\nnamespace swift {\nnamespace sys {\ntemplate <>\nstruct CacheKeyInfo<KeyCounter> {\n static uintptr_t getHashValue(const KeyCounter &value) {\n return llvm::DenseMapInfo<int>::getHashValue(value.key);\n }\n static bool isEqual(void *lhs, void *rhs) {\n return static_cast<KeyCounter *>(lhs)->key ==\n static_cast<KeyCounter *>(rhs)->key;\n }\n static void *enterCache(const KeyCounter &value) {\n value.enter += 1;\n return const_cast<KeyCounter *>(&value);\n }\n static void exitCache(void *value) {\n static_cast<KeyCounter *>(value)->exit += 1;\n }\n static const void *getLookupKey(const KeyCounter *value) {\n return value;\n }\n static const KeyCounter &getFromCache(void *value) {\n return *static_cast<KeyCounter *>(value);\n }\n};\n}\n}\n\n\nnamespace {\nstruct RefCntToken : llvm::RefCountedBase<RefCntToken> {\n bool &freed;\n RefCntToken(bool &freed) : freed(freed) {}\n ~RefCntToken() { freed = true; }\n};\n}\n\nTEST(Cache, sameKey) {\n Counter c1, c2;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c1);\n EXPECT_EQ(1, c1.enter);\n EXPECT_EQ(0, c1.exit);\n\n cache.set(\"a\", c2);\n EXPECT_EQ(1, c1.enter);\n EXPECT_EQ(1, c1.exit);\n EXPECT_EQ(1, c2.enter);\n EXPECT_EQ(0, c2.exit);\n}\n\nTEST(Cache, sameValue) {\n Counter c;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.set(\"b\", c);\n#if USES_LIBCACHE\n EXPECT_EQ(1, c.enter); \/\/ value is shared.\n#else\n EXPECT_EQ(2, c.enter);\n#endif\n EXPECT_EQ(0, c.exit);\n\n cache.remove(\"a\");\n#if USES_LIBCACHE\n EXPECT_EQ(1, c.enter); \/\/ value is shared.\n EXPECT_EQ(0, c.exit);\n#else\n EXPECT_EQ(2, c.enter);\n EXPECT_EQ(1, c.exit);\n#endif\n\n cache.remove(\"b\");\n EXPECT_EQ(c.enter, c.exit);\n}\n\nTEST(Cache, sameKeyValue) {\n Counter c;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.remove(\"a\");\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(1, c.exit);\n}\n\nTEST(Cache, sameKeyValueDestroysKey) {\n swift::sys::Cache<KeyCounter, Counter> cache(__func__);\n KeyCounter k1, k2;\n Counter c;\n cache.set(k1, c);\n cache.set(k2, c);\n EXPECT_EQ(1, k1.enter);\n EXPECT_EQ(1, k1.exit);\n EXPECT_EQ(1, k2.enter);\n EXPECT_EQ(0, k2.exit);\n}\n\nTEST(Cache, sameKeyIntrusiveRefCountPter) {\n bool freed1 = false;\n bool freed2 = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c1(new RefCntToken(freed1));\n llvm::IntrusiveRefCntPtr<RefCntToken> c2(new RefCntToken(freed2));\n cache.set(\"a\", c1);\n cache.set(\"a\", c2);\n }\n EXPECT_TRUE(freed1);\n EXPECT_FALSE(freed2);\n cache.remove(\"a\");\n EXPECT_TRUE(freed2);\n}\n\nTEST(Cache, sameValueIntrusiveRefCountPter) {\n bool freed = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c(new RefCntToken(freed));\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n\n cache.set(\"b\", c);\n EXPECT_FALSE(freed);\n\n cache.remove(\"a\");\n EXPECT_FALSE(freed);\n\n cache.remove(\"b\");\n EXPECT_FALSE(freed);\n }\n EXPECT_TRUE(freed);\n}\n\nTEST(Cache, sameKeyValueIntrusiveRefCountPter) {\n bool freed = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c(new RefCntToken(freed));\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n }\n EXPECT_FALSE(freed);\n cache.remove(\"a\");\n EXPECT_TRUE(freed);\n}\n\nTEST(Cache, copyValue) {\n struct S {\n int ident, copy;\n S(int ident) : ident(ident), copy(0) {}\n S(const S &other) : ident(other.ident), copy(other.copy+1) {}\n S(S &&other) : ident(other.ident), copy(other.copy) {}\n };\n swift::sys::Cache<const char *, struct S> cache(__func__);\n S s{0};\n EXPECT_EQ(0, s.ident);\n EXPECT_EQ(0, s.copy);\n cache.set(\"a\", s);\n EXPECT_EQ(0, cache.get(\"a\")->ident);\n EXPECT_EQ(2, cache.get(\"a\")->copy); \/\/ return by value causes 2nd copy\n cache.set(\"b\", *cache.get(\"a\"));\n EXPECT_EQ(0, cache.get(\"b\")->ident);\n EXPECT_EQ(4, cache.get(\"b\")->copy); \/\/ return by value causes 2nd copy\n}\n<commit_msg>fix ASAN in cache test<commit_after>\/\/===--- CacheTest.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Basic\/Cache.h\"\n#include \"gtest\/gtest.h\"\n\n#if defined(__APPLE__)\n#define USES_LIBCACHE 1\n#else\n#define USES_LIBCACHE 0\n#endif\n\nnamespace {\nstruct Counter {\n mutable int enter = 0;\n mutable int exit = 0;\n};\n}\n\nnamespace swift {\nnamespace sys {\ntemplate <>\nstruct CacheValueInfo<Counter>{\n static void *enterCache(const Counter &value) {\n return const_cast<Counter *>(&value);\n }\n static void retain(void *ptr) {\n static_cast<Counter*>(ptr)->enter+= 1;\n }\n static void release(void *ptr) {\n static_cast<Counter*>(ptr)->exit += 1;\n }\n static const Counter &getFromCache(void *ptr) {\n return *static_cast<Counter *>(ptr);\n }\n static size_t getCost(const Counter &value) {\n return 0;\n }\n};\n}\n}\n\nnamespace {\nstruct KeyCounter {\n int key = 0;\n mutable int enter = 0;\n mutable int exit = 0;\n};\n}\n\nnamespace swift {\nnamespace sys {\ntemplate <>\nstruct CacheKeyInfo<KeyCounter> {\n static uintptr_t getHashValue(const KeyCounter &value) {\n return llvm::DenseMapInfo<int>::getHashValue(value.key);\n }\n static bool isEqual(void *lhs, void *rhs) {\n return static_cast<KeyCounter *>(lhs)->key ==\n static_cast<KeyCounter *>(rhs)->key;\n }\n static void *enterCache(const KeyCounter &value) {\n value.enter += 1;\n return const_cast<KeyCounter *>(&value);\n }\n static void exitCache(void *value) {\n static_cast<KeyCounter *>(value)->exit += 1;\n }\n static const void *getLookupKey(const KeyCounter *value) {\n return value;\n }\n static const KeyCounter &getFromCache(void *value) {\n return *static_cast<KeyCounter *>(value);\n }\n};\n}\n}\n\n\nnamespace {\nstruct RefCntToken : llvm::RefCountedBase<RefCntToken> {\n bool &freed;\n RefCntToken(bool &freed) : freed(freed) {}\n ~RefCntToken() { freed = true; }\n};\n}\n\nTEST(Cache, sameKey) {\n Counter c1, c2;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c1);\n EXPECT_EQ(1, c1.enter);\n EXPECT_EQ(0, c1.exit);\n\n cache.set(\"a\", c2);\n EXPECT_EQ(1, c1.enter);\n EXPECT_EQ(1, c1.exit);\n EXPECT_EQ(1, c2.enter);\n EXPECT_EQ(0, c2.exit);\n}\n\nTEST(Cache, sameValue) {\n Counter c;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.set(\"b\", c);\n#if USES_LIBCACHE\n EXPECT_EQ(1, c.enter); \/\/ value is shared.\n#else\n EXPECT_EQ(2, c.enter);\n#endif\n EXPECT_EQ(0, c.exit);\n\n cache.remove(\"a\");\n#if USES_LIBCACHE\n EXPECT_EQ(1, c.enter); \/\/ value is shared.\n EXPECT_EQ(0, c.exit);\n#else\n EXPECT_EQ(2, c.enter);\n EXPECT_EQ(1, c.exit);\n#endif\n\n cache.remove(\"b\");\n EXPECT_EQ(c.enter, c.exit);\n}\n\nTEST(Cache, sameKeyValue) {\n Counter c;\n swift::sys::Cache<const char *, Counter> cache(__func__);\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.set(\"a\", c);\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(0, c.exit);\n\n cache.remove(\"a\");\n EXPECT_EQ(1, c.enter);\n EXPECT_EQ(1, c.exit);\n}\n\nTEST(Cache, sameKeyValueDestroysKey) {\n KeyCounter k1, k2;\n Counter c;\n swift::sys::Cache<KeyCounter, Counter> cache(__func__);\n cache.set(k1, c);\n cache.set(k2, c);\n EXPECT_EQ(1, k1.enter);\n EXPECT_EQ(1, k1.exit);\n EXPECT_EQ(1, k2.enter);\n EXPECT_EQ(0, k2.exit);\n}\n\nTEST(Cache, sameKeyIntrusiveRefCountPter) {\n bool freed1 = false;\n bool freed2 = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c1(new RefCntToken(freed1));\n llvm::IntrusiveRefCntPtr<RefCntToken> c2(new RefCntToken(freed2));\n cache.set(\"a\", c1);\n cache.set(\"a\", c2);\n }\n EXPECT_TRUE(freed1);\n EXPECT_FALSE(freed2);\n cache.remove(\"a\");\n EXPECT_TRUE(freed2);\n}\n\nTEST(Cache, sameValueIntrusiveRefCountPter) {\n bool freed = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c(new RefCntToken(freed));\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n\n cache.set(\"b\", c);\n EXPECT_FALSE(freed);\n\n cache.remove(\"a\");\n EXPECT_FALSE(freed);\n\n cache.remove(\"b\");\n EXPECT_FALSE(freed);\n }\n EXPECT_TRUE(freed);\n}\n\nTEST(Cache, sameKeyValueIntrusiveRefCountPter) {\n bool freed = false;\n swift::sys::Cache<const char *, llvm::IntrusiveRefCntPtr<RefCntToken>> cache(__func__);\n {\n llvm::IntrusiveRefCntPtr<RefCntToken> c(new RefCntToken(freed));\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n cache.set(\"a\", c);\n EXPECT_FALSE(freed);\n }\n EXPECT_FALSE(freed);\n cache.remove(\"a\");\n EXPECT_TRUE(freed);\n}\n\nTEST(Cache, copyValue) {\n struct S {\n int ident, copy;\n S(int ident) : ident(ident), copy(0) {}\n S(const S &other) : ident(other.ident), copy(other.copy+1) {}\n S(S &&other) : ident(other.ident), copy(other.copy) {}\n };\n swift::sys::Cache<const char *, struct S> cache(__func__);\n S s{0};\n EXPECT_EQ(0, s.ident);\n EXPECT_EQ(0, s.copy);\n cache.set(\"a\", s);\n EXPECT_EQ(0, cache.get(\"a\")->ident);\n EXPECT_EQ(2, cache.get(\"a\")->copy); \/\/ return by value causes 2nd copy\n cache.set(\"b\", *cache.get(\"a\"));\n EXPECT_EQ(0, cache.get(\"b\")->ident);\n EXPECT_EQ(4, cache.get(\"b\")->copy); \/\/ return by value causes 2nd copy\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SocketTest.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <cstdio>\n#include <functional>\n#include <thread>\n\n#include \"gtest\/gtest.h\"\n\n#include \"lldb\/Host\/Config.h\"\n#include \"lldb\/Host\/Socket.h\"\n#include \"lldb\/Host\/common\/TCPSocket.h\"\n#include \"lldb\/Host\/common\/UDPSocket.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#ifndef LLDB_DISABLE_POSIX\n#include \"lldb\/Host\/posix\/DomainSocket.h\"\n#endif\n\nusing namespace lldb_private;\n\nclass SocketTest : public testing::Test {\npublic:\n void SetUp() override {\n#if defined(_MSC_VER)\n WSADATA data;\n ::WSAStartup(MAKEWORD(2, 2), &data);\n#endif\n }\n\n void TearDown() override {\n#if defined(_MSC_VER)\n ::WSACleanup();\n#endif\n }\n\nprotected:\n static void AcceptThread(Socket *listen_socket,\n bool child_processes_inherit, Socket **accept_socket,\n Status *error) {\n *error = listen_socket->Accept(*accept_socket);\n }\n\n template <typename SocketType>\n void CreateConnectedSockets(\n llvm::StringRef listen_remote_address,\n const std::function<std::string(const SocketType &)> &get_connect_addr,\n std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {\n bool child_processes_inherit = false;\n Status error;\n std::unique_ptr<SocketType> listen_socket_up(\n new SocketType(true, child_processes_inherit));\n EXPECT_FALSE(error.Fail());\n error = listen_socket_up->Listen(listen_remote_address, 5);\n EXPECT_FALSE(error.Fail());\n EXPECT_TRUE(listen_socket_up->IsValid());\n\n Status accept_error;\n Socket *accept_socket;\n std::thread accept_thread(AcceptThread, listen_socket_up.get(),\n child_processes_inherit, &accept_socket,\n &accept_error);\n\n std::string connect_remote_address = get_connect_addr(*listen_socket_up);\n std::unique_ptr<SocketType> connect_socket_up(\n new SocketType(true, child_processes_inherit));\n EXPECT_FALSE(error.Fail());\n error = connect_socket_up->Connect(connect_remote_address);\n EXPECT_FALSE(error.Fail());\n EXPECT_TRUE(connect_socket_up->IsValid());\n\n a_up->swap(connect_socket_up);\n EXPECT_TRUE(error.Success());\n EXPECT_NE(nullptr, a_up->get());\n EXPECT_TRUE((*a_up)->IsValid());\n\n accept_thread.join();\n b_up->reset(static_cast<SocketType *>(accept_socket));\n EXPECT_TRUE(accept_error.Success());\n EXPECT_NE(nullptr, b_up->get());\n EXPECT_TRUE((*b_up)->IsValid());\n\n listen_socket_up.reset();\n }\n};\n\nTEST_F(SocketTest, DecodeHostAndPort) {\n std::string host_str;\n std::string port_str;\n int32_t port;\n Status error;\n EXPECT_TRUE(Socket::DecodeHostAndPort(\"localhost:1138\", host_str, port_str,\n port, &error));\n EXPECT_STREQ(\"localhost\", host_str.c_str());\n EXPECT_STREQ(\"1138\", port_str.c_str());\n EXPECT_EQ(1138, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:65536\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:65536'\",\n error.AsCString());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:-1138\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:-1138'\",\n error.AsCString());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:65536\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:65536'\",\n error.AsCString());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"*:0\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"*\", host_str.c_str());\n EXPECT_STREQ(\"0\", port_str.c_str());\n EXPECT_EQ(0, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"*:65535\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"*\", host_str.c_str());\n EXPECT_STREQ(\"65535\", port_str.c_str());\n EXPECT_EQ(65535, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"[::1]:12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"::1\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"[abcd:12fg:AF58::1]:12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"abcd:12fg:AF58::1\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n}\n\n#ifndef LLDB_DISABLE_POSIX\nTEST_F(SocketTest, DomainListenConnectAccept) {\n llvm::SmallString<64> Path;\n std::error_code EC = llvm::sys::fs::createUniqueDirectory(\"DomainListenConnectAccept\", Path);\n ASSERT_FALSE(EC);\n llvm::sys::path::append(Path, \"test\");\n\n std::unique_ptr<DomainSocket> socket_a_up;\n std::unique_ptr<DomainSocket> socket_b_up;\n CreateConnectedSockets<DomainSocket>(\n Path, [=](const DomainSocket &) { return Path.str().str(); },\n &socket_a_up, &socket_b_up);\n}\n#endif\n\nTEST_F(SocketTest, TCPListen0ConnectAccept) {\n std::unique_ptr<TCPSocket> socket_a_up;\n std::unique_ptr<TCPSocket> socket_b_up;\n CreateConnectedSockets<TCPSocket>(\n \"127.0.0.1:0\",\n [=](const TCPSocket &s) {\n char connect_remote_address[64];\n snprintf(connect_remote_address, sizeof(connect_remote_address),\n \"localhost:%u\", s.GetLocalPortNumber());\n return std::string(connect_remote_address);\n },\n &socket_a_up, &socket_b_up);\n}\n\nTEST_F(SocketTest, TCPGetAddress) {\n std::unique_ptr<TCPSocket> socket_a_up;\n std::unique_ptr<TCPSocket> socket_b_up;\n CreateConnectedSockets<TCPSocket>(\n \"127.0.0.1:0\",\n [=](const TCPSocket &s) {\n char connect_remote_address[64];\n snprintf(connect_remote_address, sizeof(connect_remote_address),\n \"localhost:%u\", s.GetLocalPortNumber());\n return std::string(connect_remote_address);\n },\n &socket_a_up, &socket_b_up);\n\n EXPECT_EQ(socket_a_up->GetLocalPortNumber(),\n socket_b_up->GetRemotePortNumber());\n EXPECT_EQ(socket_b_up->GetLocalPortNumber(),\n socket_a_up->GetRemotePortNumber());\n EXPECT_NE(socket_a_up->GetLocalPortNumber(),\n socket_b_up->GetLocalPortNumber());\n EXPECT_STREQ(\"127.0.0.1\", socket_a_up->GetRemoteIPAddress().c_str());\n EXPECT_STREQ(\"127.0.0.1\", socket_b_up->GetRemoteIPAddress().c_str());\n}\n\nTEST_F(SocketTest, UDPConnect) {\n Socket *socket;\n\n bool child_processes_inherit = false;\n auto error = UDPSocket::Connect(\"127.0.0.1:0\", child_processes_inherit,\n socket);\n\n std::unique_ptr<Socket> socket_up(socket);\n\n EXPECT_TRUE(error.Success());\n EXPECT_TRUE(socket_up->IsValid());\n}\n\nTEST_F(SocketTest, TCPListen0GetPort) {\n Socket *server_socket;\n Predicate<uint16_t> port_predicate;\n port_predicate.SetValue(0, eBroadcastNever);\n Status err =\n Socket::TcpListen(\"10.10.12.3:0\", false, server_socket, &port_predicate);\n std::unique_ptr<TCPSocket> socket_up((TCPSocket*)server_socket);\n EXPECT_TRUE(socket_up->IsValid());\n EXPECT_NE(socket_up->GetLocalPortNumber(), 0);\n}\n<commit_msg>Temporarily add redundant checks to better debug bot failures<commit_after>\/\/===-- SocketTest.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <cstdio>\n#include <functional>\n#include <thread>\n\n#include \"gtest\/gtest.h\"\n\n#include \"lldb\/Host\/Config.h\"\n#include \"lldb\/Host\/Socket.h\"\n#include \"lldb\/Host\/common\/TCPSocket.h\"\n#include \"lldb\/Host\/common\/UDPSocket.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n\n#ifndef LLDB_DISABLE_POSIX\n#include \"lldb\/Host\/posix\/DomainSocket.h\"\n#endif\n\nusing namespace lldb_private;\n\nclass SocketTest : public testing::Test {\npublic:\n void SetUp() override {\n#if defined(_MSC_VER)\n WSADATA data;\n ::WSAStartup(MAKEWORD(2, 2), &data);\n#endif\n }\n\n void TearDown() override {\n#if defined(_MSC_VER)\n ::WSACleanup();\n#endif\n }\n\nprotected:\n static void AcceptThread(Socket *listen_socket,\n bool child_processes_inherit, Socket **accept_socket,\n Status *error) {\n *error = listen_socket->Accept(*accept_socket);\n }\n\n template <typename SocketType>\n void CreateConnectedSockets(\n llvm::StringRef listen_remote_address,\n const std::function<std::string(const SocketType &)> &get_connect_addr,\n std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {\n bool child_processes_inherit = false;\n Status error;\n std::unique_ptr<SocketType> listen_socket_up(\n new SocketType(true, child_processes_inherit));\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_FALSE(error.Fail());\n error = listen_socket_up->Listen(listen_remote_address, 5);\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_FALSE(error.Fail());\n EXPECT_TRUE(listen_socket_up->IsValid());\n\n Status accept_error;\n Socket *accept_socket;\n std::thread accept_thread(AcceptThread, listen_socket_up.get(),\n child_processes_inherit, &accept_socket,\n &accept_error);\n\n std::string connect_remote_address = get_connect_addr(*listen_socket_up);\n std::unique_ptr<SocketType> connect_socket_up(\n new SocketType(true, child_processes_inherit));\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_FALSE(error.Fail());\n error = connect_socket_up->Connect(connect_remote_address);\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_FALSE(error.Fail());\n EXPECT_TRUE(connect_socket_up->IsValid());\n\n a_up->swap(connect_socket_up);\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_TRUE(error.Success());\n EXPECT_NE(nullptr, a_up->get());\n EXPECT_TRUE((*a_up)->IsValid());\n\n accept_thread.join();\n b_up->reset(static_cast<SocketType *>(accept_socket));\n EXPECT_EQ(nullptr, error.AsCString(nullptr));\n EXPECT_TRUE(accept_error.Success());\n EXPECT_NE(nullptr, b_up->get());\n EXPECT_TRUE((*b_up)->IsValid());\n\n listen_socket_up.reset();\n }\n};\n\nTEST_F(SocketTest, DecodeHostAndPort) {\n std::string host_str;\n std::string port_str;\n int32_t port;\n Status error;\n EXPECT_TRUE(Socket::DecodeHostAndPort(\"localhost:1138\", host_str, port_str,\n port, &error));\n EXPECT_STREQ(\"localhost\", host_str.c_str());\n EXPECT_STREQ(\"1138\", port_str.c_str());\n EXPECT_EQ(1138, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:65536\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:65536'\",\n error.AsCString());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:-1138\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:-1138'\",\n error.AsCString());\n\n EXPECT_FALSE(Socket::DecodeHostAndPort(\"google.com:65536\", host_str, port_str,\n port, &error));\n EXPECT_TRUE(error.Fail());\n EXPECT_STREQ(\"invalid host:port specification: 'google.com:65536'\",\n error.AsCString());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"*:0\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"*\", host_str.c_str());\n EXPECT_STREQ(\"0\", port_str.c_str());\n EXPECT_EQ(0, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"*:65535\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"*\", host_str.c_str());\n EXPECT_STREQ(\"65535\", port_str.c_str());\n EXPECT_EQ(65535, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"[::1]:12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"::1\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n\n EXPECT_TRUE(\n Socket::DecodeHostAndPort(\"[abcd:12fg:AF58::1]:12345\", host_str, port_str, port, &error));\n EXPECT_STREQ(\"abcd:12fg:AF58::1\", host_str.c_str());\n EXPECT_STREQ(\"12345\", port_str.c_str());\n EXPECT_EQ(12345, port);\n EXPECT_TRUE(error.Success());\n}\n\n#ifndef LLDB_DISABLE_POSIX\nTEST_F(SocketTest, DomainListenConnectAccept) {\n llvm::SmallString<64> Path;\n std::error_code EC = llvm::sys::fs::createUniqueDirectory(\"DomainListenConnectAccept\", Path);\n ASSERT_FALSE(EC);\n llvm::sys::path::append(Path, \"test\");\n\n std::unique_ptr<DomainSocket> socket_a_up;\n std::unique_ptr<DomainSocket> socket_b_up;\n CreateConnectedSockets<DomainSocket>(\n Path, [=](const DomainSocket &) { return Path.str().str(); },\n &socket_a_up, &socket_b_up);\n}\n#endif\n\nTEST_F(SocketTest, TCPListen0ConnectAccept) {\n std::unique_ptr<TCPSocket> socket_a_up;\n std::unique_ptr<TCPSocket> socket_b_up;\n CreateConnectedSockets<TCPSocket>(\n \"127.0.0.1:0\",\n [=](const TCPSocket &s) {\n char connect_remote_address[64];\n snprintf(connect_remote_address, sizeof(connect_remote_address),\n \"localhost:%u\", s.GetLocalPortNumber());\n return std::string(connect_remote_address);\n },\n &socket_a_up, &socket_b_up);\n}\n\nTEST_F(SocketTest, TCPGetAddress) {\n std::unique_ptr<TCPSocket> socket_a_up;\n std::unique_ptr<TCPSocket> socket_b_up;\n CreateConnectedSockets<TCPSocket>(\n \"127.0.0.1:0\",\n [=](const TCPSocket &s) {\n char connect_remote_address[64];\n snprintf(connect_remote_address, sizeof(connect_remote_address),\n \"localhost:%u\", s.GetLocalPortNumber());\n return std::string(connect_remote_address);\n },\n &socket_a_up, &socket_b_up);\n\n EXPECT_EQ(socket_a_up->GetLocalPortNumber(),\n socket_b_up->GetRemotePortNumber());\n EXPECT_EQ(socket_b_up->GetLocalPortNumber(),\n socket_a_up->GetRemotePortNumber());\n EXPECT_NE(socket_a_up->GetLocalPortNumber(),\n socket_b_up->GetLocalPortNumber());\n EXPECT_STREQ(\"127.0.0.1\", socket_a_up->GetRemoteIPAddress().c_str());\n EXPECT_STREQ(\"127.0.0.1\", socket_b_up->GetRemoteIPAddress().c_str());\n}\n\nTEST_F(SocketTest, UDPConnect) {\n Socket *socket;\n\n bool child_processes_inherit = false;\n auto error = UDPSocket::Connect(\"127.0.0.1:0\", child_processes_inherit,\n socket);\n\n std::unique_ptr<Socket> socket_up(socket);\n\n EXPECT_TRUE(error.Success());\n EXPECT_TRUE(socket_up->IsValid());\n}\n\nTEST_F(SocketTest, TCPListen0GetPort) {\n Socket *server_socket;\n Predicate<uint16_t> port_predicate;\n port_predicate.SetValue(0, eBroadcastNever);\n Status err =\n Socket::TcpListen(\"10.10.12.3:0\", false, server_socket, &port_predicate);\n std::unique_ptr<TCPSocket> socket_up((TCPSocket*)server_socket);\n EXPECT_TRUE(socket_up->IsValid());\n EXPECT_NE(socket_up->GetLocalPortNumber(), 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- llvm\/unittest\/IR\/VerifierTest.cpp - Verifier unit tests --*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/DIBuilder.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalAlias.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace llvm {\nnamespace {\n\nTEST(VerifierTest, Branch_i1) {\n LLVMContext C;\n Module M(\"M\", C);\n FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), \/*isVarArg=*\/false);\n Function *F = cast<Function>(M.getOrInsertFunction(\"foo\", FTy));\n BasicBlock *Entry = BasicBlock::Create(C, \"entry\", F);\n BasicBlock *Exit = BasicBlock::Create(C, \"exit\", F);\n ReturnInst::Create(C, Exit);\n\n \/\/ To avoid triggering an assertion in BranchInst::Create, we first create\n \/\/ a branch with an 'i1' condition ...\n\n Constant *False = ConstantInt::getFalse(C);\n BranchInst *BI = BranchInst::Create(Exit, Exit, False, Entry);\n\n \/\/ ... then use setOperand to redirect it to a value of different type.\n\n Constant *Zero32 = ConstantInt::get(IntegerType::get(C, 32), 0);\n BI->setOperand(0, Zero32);\n\n EXPECT_TRUE(verifyFunction(*F));\n}\n\nTEST(VerifierTest, InvalidRetAttribute) {\n LLVMContext C;\n Module M(\"M\", C);\n FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), \/*isVarArg=*\/false);\n Function *F = cast<Function>(M.getOrInsertFunction(\"foo\", FTy));\n AttributeSet AS = F->getAttributes();\n F->setAttributes(AS.addAttribute(C, AttributeSet::ReturnIndex,\n Attribute::UWTable));\n\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).startswith(\n \"Attribute 'uwtable' only applies to functions!\"));\n}\n\nTEST(VerifierTest, CrossModuleRef) {\n LLVMContext C;\n Module M1(\"M1\", C);\n Module M2(\"M2\", C);\n Module M3(\"M3\", C);\n FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), \/*isVarArg=*\/false);\n Function *F1 = cast<Function>(M1.getOrInsertFunction(\"foo1\", FTy));\n Function *F2 = cast<Function>(M2.getOrInsertFunction(\"foo2\", FTy));\n Function *F3 = cast<Function>(M3.getOrInsertFunction(\"foo3\", FTy));\n\n BasicBlock *Entry1 = BasicBlock::Create(C, \"entry\", F1);\n BasicBlock *Entry3 = BasicBlock::Create(C, \"entry\", F3);\n\n \/\/ BAD: Referencing function in another module\n CallInst::Create(F2,\"call\",Entry1);\n\n \/\/ BAD: Referencing personality routine in another module\n F3->setPersonalityFn(F2);\n\n \/\/ Fill in the body\n Constant *ConstZero = ConstantInt::get(Type::getInt32Ty(C), 0);\n ReturnInst::Create(C, ConstZero, Entry1);\n ReturnInst::Create(C, ConstZero, Entry3);\n\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M2, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str())\n .equals(\"Global is used by function in a different module\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"\n \"i32 ()* @foo3\\n\"\n \"; ModuleID = 'M3'\\n\"\n \"Global is referenced in a different module!\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"\n \" %call = call i32 @foo2()\\n\"\n \"i32 ()* @foo1\\n\"\n \"; ModuleID = 'M1'\\n\"));\n\n Error.clear();\n EXPECT_TRUE(verifyModule(M1, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).equals(\n \"Referencing function in another module!\\n\"\n \" %call = call i32 @foo2()\\n\"\n \"; ModuleID = 'M1'\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"));\n\n Error.clear();\n EXPECT_TRUE(verifyModule(M3, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).startswith(\n \"Referencing personality function in another module!\"));\n\n \/\/ Erase bad methods to avoid triggering an assertion failure on destruction\n F1->eraseFromParent();\n F3->eraseFromParent();\n}\n\nTEST(VerifierTest, InvalidVariableLinkage) {\n LLVMContext C;\n Module M(\"M\", C);\n new GlobalVariable(M, Type::getInt8Ty(C), false,\n GlobalValue::LinkOnceODRLinkage, nullptr, \"Some Global\");\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(\n StringRef(ErrorOS.str()).startswith(\"Global is external, but doesn't \"\n \"have external or weak linkage!\"));\n}\n\nTEST(VerifierTest, InvalidFunctionLinkage) {\n LLVMContext C;\n Module M(\"M\", C);\n\n FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), \/*isVarArg=*\/false);\n Function::Create(FTy, GlobalValue::LinkOnceODRLinkage, \"foo\", &M);\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(\n StringRef(ErrorOS.str()).startswith(\"Global is external, but doesn't \"\n \"have external or weak linkage!\"));\n}\n\n#ifndef _MSC_VER\n\/\/ FIXME: This test causes an ICE in MSVC 2013.\nTEST(VerifierTest, StripInvalidDebugInfo) {\n {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\", \"unittest\",\n false, \"\", 0);\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it by inserting non-CU node to the list of CUs.\n auto *File = DIB.createFile(\"not-a-CU.f\", \".\");\n NamedMDNode *NMD = M.getOrInsertNamedMetadata(\"llvm.dbg.cu\");\n NMD->addOperand(File);\n EXPECT_TRUE(verifyModule(M));\n\n ModulePassManager MPM(true);\n MPM.addPass(VerifierPass(false));\n ModuleAnalysisManager MAM(true);\n MAM.registerPass([&] { return VerifierAnalysis(); });\n MPM.run(M, MAM);\n EXPECT_FALSE(verifyModule(M));\n }\n {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n auto *CU = DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\",\n \"unittest\", false, \"\", 0);\n new GlobalVariable(M, Type::getInt8Ty(C), false,\n GlobalValue::ExternalLinkage, nullptr, \"g\");\n\n auto *F = cast<Function>(M.getOrInsertFunction(\n \"f\", FunctionType::get(Type::getVoidTy(C), false)));\n IRBuilder<> Builder(BasicBlock::Create(C, \"\", F));\n Builder.CreateUnreachable();\n F->setSubprogram(DIB.createFunction(CU, \"f\", \"f\",\n DIB.createFile(\"broken.c\", \"\/\"), 1,\n nullptr, true, true, 1));\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it by not listing the CU at all.\n M.eraseNamedMetadata(M.getOrInsertNamedMetadata(\"llvm.dbg.cu\"));\n EXPECT_TRUE(verifyModule(M));\n\n ModulePassManager MPM(true);\n MPM.addPass(VerifierPass(false));\n ModuleAnalysisManager MAM(true);\n MAM.registerPass([&] { return VerifierAnalysis(); });\n MPM.run(M, MAM);\n EXPECT_FALSE(verifyModule(M));\n }\n}\n#endif\n\nTEST(VerifierTest, StripInvalidDebugInfoLegacy) {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\",\n \"unittest\", false, \"\", 0);\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it.\n auto *File = DIB.createFile(\"not-a-CU.f\", \".\");\n NamedMDNode *NMD = M.getOrInsertNamedMetadata(\"llvm.dbg.cu\");\n NMD->addOperand(File);\n EXPECT_TRUE(verifyModule(M));\n\n legacy::PassManager Passes;\n Passes.add(createVerifierPass(false));\n Passes.run(M);\n EXPECT_FALSE(verifyModule(M));\n}\n\n} \/\/ end anonymous namespace\n} \/\/ end namespace llvm\n<commit_msg>[unittests] Remove an MSVC 2013 workaround, NFCI.<commit_after>\/\/===- llvm\/unittest\/IR\/VerifierTest.cpp - Verifier unit tests --*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/DIBuilder.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalAlias.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace llvm {\nnamespace {\n\nTEST(VerifierTest, Branch_i1) {\n LLVMContext C;\n Module M(\"M\", C);\n FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), \/*isVarArg=*\/false);\n Function *F = cast<Function>(M.getOrInsertFunction(\"foo\", FTy));\n BasicBlock *Entry = BasicBlock::Create(C, \"entry\", F);\n BasicBlock *Exit = BasicBlock::Create(C, \"exit\", F);\n ReturnInst::Create(C, Exit);\n\n \/\/ To avoid triggering an assertion in BranchInst::Create, we first create\n \/\/ a branch with an 'i1' condition ...\n\n Constant *False = ConstantInt::getFalse(C);\n BranchInst *BI = BranchInst::Create(Exit, Exit, False, Entry);\n\n \/\/ ... then use setOperand to redirect it to a value of different type.\n\n Constant *Zero32 = ConstantInt::get(IntegerType::get(C, 32), 0);\n BI->setOperand(0, Zero32);\n\n EXPECT_TRUE(verifyFunction(*F));\n}\n\nTEST(VerifierTest, InvalidRetAttribute) {\n LLVMContext C;\n Module M(\"M\", C);\n FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), \/*isVarArg=*\/false);\n Function *F = cast<Function>(M.getOrInsertFunction(\"foo\", FTy));\n AttributeSet AS = F->getAttributes();\n F->setAttributes(AS.addAttribute(C, AttributeSet::ReturnIndex,\n Attribute::UWTable));\n\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).startswith(\n \"Attribute 'uwtable' only applies to functions!\"));\n}\n\nTEST(VerifierTest, CrossModuleRef) {\n LLVMContext C;\n Module M1(\"M1\", C);\n Module M2(\"M2\", C);\n Module M3(\"M3\", C);\n FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), \/*isVarArg=*\/false);\n Function *F1 = cast<Function>(M1.getOrInsertFunction(\"foo1\", FTy));\n Function *F2 = cast<Function>(M2.getOrInsertFunction(\"foo2\", FTy));\n Function *F3 = cast<Function>(M3.getOrInsertFunction(\"foo3\", FTy));\n\n BasicBlock *Entry1 = BasicBlock::Create(C, \"entry\", F1);\n BasicBlock *Entry3 = BasicBlock::Create(C, \"entry\", F3);\n\n \/\/ BAD: Referencing function in another module\n CallInst::Create(F2,\"call\",Entry1);\n\n \/\/ BAD: Referencing personality routine in another module\n F3->setPersonalityFn(F2);\n\n \/\/ Fill in the body\n Constant *ConstZero = ConstantInt::get(Type::getInt32Ty(C), 0);\n ReturnInst::Create(C, ConstZero, Entry1);\n ReturnInst::Create(C, ConstZero, Entry3);\n\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M2, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str())\n .equals(\"Global is used by function in a different module\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"\n \"i32 ()* @foo3\\n\"\n \"; ModuleID = 'M3'\\n\"\n \"Global is referenced in a different module!\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"\n \" %call = call i32 @foo2()\\n\"\n \"i32 ()* @foo1\\n\"\n \"; ModuleID = 'M1'\\n\"));\n\n Error.clear();\n EXPECT_TRUE(verifyModule(M1, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).equals(\n \"Referencing function in another module!\\n\"\n \" %call = call i32 @foo2()\\n\"\n \"; ModuleID = 'M1'\\n\"\n \"i32 ()* @foo2\\n\"\n \"; ModuleID = 'M2'\\n\"));\n\n Error.clear();\n EXPECT_TRUE(verifyModule(M3, &ErrorOS));\n EXPECT_TRUE(StringRef(ErrorOS.str()).startswith(\n \"Referencing personality function in another module!\"));\n\n \/\/ Erase bad methods to avoid triggering an assertion failure on destruction\n F1->eraseFromParent();\n F3->eraseFromParent();\n}\n\nTEST(VerifierTest, InvalidVariableLinkage) {\n LLVMContext C;\n Module M(\"M\", C);\n new GlobalVariable(M, Type::getInt8Ty(C), false,\n GlobalValue::LinkOnceODRLinkage, nullptr, \"Some Global\");\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(\n StringRef(ErrorOS.str()).startswith(\"Global is external, but doesn't \"\n \"have external or weak linkage!\"));\n}\n\nTEST(VerifierTest, InvalidFunctionLinkage) {\n LLVMContext C;\n Module M(\"M\", C);\n\n FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), \/*isVarArg=*\/false);\n Function::Create(FTy, GlobalValue::LinkOnceODRLinkage, \"foo\", &M);\n std::string Error;\n raw_string_ostream ErrorOS(Error);\n EXPECT_TRUE(verifyModule(M, &ErrorOS));\n EXPECT_TRUE(\n StringRef(ErrorOS.str()).startswith(\"Global is external, but doesn't \"\n \"have external or weak linkage!\"));\n}\n\nTEST(VerifierTest, StripInvalidDebugInfo) {\n {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\", \"unittest\",\n false, \"\", 0);\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it by inserting non-CU node to the list of CUs.\n auto *File = DIB.createFile(\"not-a-CU.f\", \".\");\n NamedMDNode *NMD = M.getOrInsertNamedMetadata(\"llvm.dbg.cu\");\n NMD->addOperand(File);\n EXPECT_TRUE(verifyModule(M));\n\n ModulePassManager MPM(true);\n MPM.addPass(VerifierPass(false));\n ModuleAnalysisManager MAM(true);\n MAM.registerPass([&] { return VerifierAnalysis(); });\n MPM.run(M, MAM);\n EXPECT_FALSE(verifyModule(M));\n }\n {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n auto *CU = DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\",\n \"unittest\", false, \"\", 0);\n new GlobalVariable(M, Type::getInt8Ty(C), false,\n GlobalValue::ExternalLinkage, nullptr, \"g\");\n\n auto *F = cast<Function>(M.getOrInsertFunction(\n \"f\", FunctionType::get(Type::getVoidTy(C), false)));\n IRBuilder<> Builder(BasicBlock::Create(C, \"\", F));\n Builder.CreateUnreachable();\n F->setSubprogram(DIB.createFunction(CU, \"f\", \"f\",\n DIB.createFile(\"broken.c\", \"\/\"), 1,\n nullptr, true, true, 1));\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it by not listing the CU at all.\n M.eraseNamedMetadata(M.getOrInsertNamedMetadata(\"llvm.dbg.cu\"));\n EXPECT_TRUE(verifyModule(M));\n\n ModulePassManager MPM(true);\n MPM.addPass(VerifierPass(false));\n ModuleAnalysisManager MAM(true);\n MAM.registerPass([&] { return VerifierAnalysis(); });\n MPM.run(M, MAM);\n EXPECT_FALSE(verifyModule(M));\n }\n}\n\nTEST(VerifierTest, StripInvalidDebugInfoLegacy) {\n LLVMContext C;\n Module M(\"M\", C);\n DIBuilder DIB(M);\n DIB.createCompileUnit(dwarf::DW_LANG_C89, \"broken.c\", \"\/\",\n \"unittest\", false, \"\", 0);\n DIB.finalize();\n EXPECT_FALSE(verifyModule(M));\n\n \/\/ Now break it.\n auto *File = DIB.createFile(\"not-a-CU.f\", \".\");\n NamedMDNode *NMD = M.getOrInsertNamedMetadata(\"llvm.dbg.cu\");\n NMD->addOperand(File);\n EXPECT_TRUE(verifyModule(M));\n\n legacy::PassManager Passes;\n Passes.add(createVerifierPass(false));\n Passes.run(M);\n EXPECT_FALSE(verifyModule(M));\n}\n\n} \/\/ end anonymous namespace\n} \/\/ end namespace llvm\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Licensed to Qualys, Inc. (QUALYS) under one or more\n\/\/ contributor license agreements. See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ QUALYS licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file\n\/\/\/ @brief IronBee --- Lock Test Functions\n\/\/\/\n\/\/\/ @author Nick LeRoy <nleroy@qualys.com>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ironbee_config_auto.h\"\n\n#include <ironbee\/types.h>\n#include <ironbee\/mm.h>\n#include <ironbee\/util.h>\n#include <ironbee\/lock.h>\n\n#include \"gtest\/gtest.h\"\n#include \"simple_fixture.hpp\"\n\n#include <stdexcept>\n#include <math.h>\n#include <pthread.h>\n\nusing namespace std;\n\n\/* -- Tests -- *\/\ntypedef void *(* thread_start_fn)(void *thread_data);\n\nclass Thread\n{\npublic:\n explicit\n Thread(int num) :\n m_handle(0),\n m_num(num),\n m_started(false),\n m_running(false),\n m_errors(0)\n {\n }\n Thread() :\n m_handle(0),\n m_num(-1),\n m_started(false),\n m_running(false),\n m_errors(0)\n {\n }\n\n void ThreadNum(int num) { m_num = num; };\n bool IsRunning() const { return m_running; };\n int ThreadNum() const { return m_num; };\n uint64_t ThreadId() const { return (uint64_t)m_handle; };\n uint64_t Errors() const { return m_errors; };\n void Error() { ++m_errors; };\n\n ib_status_t Create(thread_start_fn fn)\n {\n pthread_t handle;\n pthread_attr_t attr;\n int status;\n\n if (m_num < 0) {\n return IB_EINVAL;\n }\n if (m_started || m_running) {\n return IB_EINVAL;\n }\n\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n m_started = true;\n status = pthread_create(&handle, &attr, fn, this);\n if (status) {\n m_started = false;\n return IB_EUNKNOWN;\n }\n\n m_handle = handle;\n return IB_OK;\n }\n\n ib_status_t Join()\n {\n int status;\n\n if (! m_started) {\n return IB_OK;\n }\n status = pthread_join(m_handle, NULL);\n if (status != 0) {\n return IB_EUNKNOWN;\n }\n m_running = false;\n m_started = false;\n\n return IB_OK;\n }\n\n ib_status_t Running(bool run)\n {\n if (!m_started) {\n return IB_EINVAL;\n }\n if (run == m_running) {\n return IB_EINVAL;\n }\n m_running = run;\n return IB_OK;\n }\n\nprivate:\n pthread_t m_handle;\n int m_num;\n bool m_started;\n bool m_running;\n uint64_t m_errors;\n};\n\nclass TestIBUtilLock : public SimpleFixture\n{\npublic:\n TestIBUtilLock() :\n m_max_threads(0),\n m_threads(NULL),\n m_lock_enabled(true),\n m_shared(0)\n {\n TestIBUtilLock::m_self = this;\n TestParams(100, 0.0005, true);\n }\n ~TestIBUtilLock()\n {\n if (m_threads != NULL) {\n delete []m_threads;\n }\n }\n\n virtual void SetUp()\n {\n SimpleFixture::SetUp();\n }\n virtual void TearDown()\n {\n SimpleFixture::TearDown();\n DestroyLock( );\n }\n\n ib_status_t CreateLock()\n {\n return ib_lock_create_malloc(&m_lock);\n }\n ib_status_t DestroyLock()\n {\n ib_lock_destroy_malloc(m_lock);\n return IB_OK;\n }\n ib_status_t LockLock()\n {\n return ib_lock_lock(m_lock);\n }\n ib_status_t UnlockLock()\n {\n return ib_lock_unlock(m_lock);\n }\n\n void InitThreads(size_t max_threads)\n {\n m_max_threads = max_threads;\n m_threads = new Thread[max_threads];\n\n for (int num = 0; num < (int)max_threads; ++num) {\n m_threads[num].ThreadNum(num);\n }\n\n }\n void TestParams(size_t loops, double seconds, bool lock)\n {\n Loops(loops);\n SleepTime(seconds);\n m_lock_enabled = lock;\n }\n\n void Loops(size_t loops) { m_loops = loops; };\n void SleepTime(double sec) { m_sleeptime = sec; };\n\n ib_status_t CreateThread(size_t num)\n {\n if(m_threads == NULL) {\n throw std::runtime_error(\"Thread handles not initialized.\");\n }\n if (num >= m_max_threads) {\n throw std::runtime_error(\"Thread number greater than max.\");\n }\n Thread *thread = &m_threads[num];\n if (thread->IsRunning()) {\n throw std::runtime_error(\"Thread already running.\");\n }\n return thread->Create(TestIBUtilLock::StartThread);\n }\n\n ib_status_t CreateAllThreads()\n {\n if(m_threads == NULL) {\n throw std::runtime_error(\"Thread handles not initialized.\");\n }\n\n size_t num;\n for (num = 0; num < m_max_threads; ++num) {\n ib_status_t rc = CreateThread(num);\n if (rc != IB_OK) {\n return rc;\n }\n }\n return IB_OK;\n }\n\n ib_status_t StartTest(size_t threads,\n size_t loops,\n double seconds,\n bool lock)\n {\n InitThreads(threads);\n TestParams(loops, seconds, lock);\n printf(\"Starting: %zd threads, %d loops, %.8fs sleep, locks %s\\n\",\n m_max_threads, m_loops, m_sleeptime,\n m_lock_enabled ? \"enabled\" : \"disabled\");\n return CreateAllThreads( );\n }\n\n static void *StartThread(void *data)\n {\n Thread *thread = (Thread *)data;\n m_self->RunThread(thread);\n return NULL;\n }\n\n void RunThread(Thread *thread)\n {\n ib_status_t rc;\n int n;\n struct timespec ts;\n\n ts.tv_sec = (time_t)trunc(m_sleeptime);\n ts.tv_nsec = (long)(round((m_sleeptime - ts.tv_sec) * 1e9));\n\n thread->Running(true);\n\n for (n = 0; n < m_loops; ++n) {\n if (m_lock_enabled) {\n rc = LockLock( );\n if (rc != IB_OK) {\n thread->Error();\n break;\n }\n }\n \/\/ This code is an intentional race condition if m_lock_enabled is\n \/\/ false. It is possible for it to fail to cause errors, but, at\n \/\/ least in common environments, that is very unlikely.\n if (++m_shared != 1) {\n thread->Error();\n }\n nanosleep(&ts, NULL);\n if (--m_shared != 0) {\n thread->Error();\n }\n\n if (m_lock_enabled) {\n rc = UnlockLock( );\n if (rc != IB_OK) {\n thread->Error();\n break;\n }\n }\n }\n thread->Running(false);\n }\n\n ib_status_t WaitForThreads(uint64_t *errors)\n {\n ib_status_t rc = IB_OK;\n size_t num;\n\n *errors = 0;\n for (num = 0; num < m_max_threads; ++num) {\n Thread *thread = &m_threads[num];\n ib_status_t irc = thread->Join();\n if (irc != IB_OK) {\n rc = irc;\n }\n *errors += thread->Errors();\n }\n return rc;\n }\n\nprivate:\n static TestIBUtilLock *m_self;\n size_t m_max_threads;\n Thread *m_threads;\n ib_lock_t *m_lock;\n bool m_lock_enabled;\n int m_loops;\n double m_sleeptime;\n volatile int m_shared;\n};\nTestIBUtilLock *TestIBUtilLock::m_self = NULL;\n\nTEST(test_util_lock, misc)\n{\n int test = 0;\n\n for (int n=0; n<100; ++n) {\n int t;\n t = ++test;\n ASSERT_EQ(1, t);\n t = --test;\n ASSERT_EQ(0, t);\n }\n}\n\nTEST_F(TestIBUtilLock, test_create)\n{\n ib_status_t rc;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = LockLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = UnlockLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n}\n\n\/\/ The following test is a true positive for a thread race condition.\n\/\/ Disable it for thread sanitizer.\nTEST_F(TestIBUtilLock, test_lock_disabled)\n{\n#ifdef IB_THREAD_SANITIZER_WORKAROUND\n cout << \"Test skipped due to thread sanitizer.\" << endl;\n return;\n#else\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(5, 100, 0.0000005, false);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_NE(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n#endif\n}\n\nTEST_F(TestIBUtilLock, test_short)\n{\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(5, 100, 0.0000005, true);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n}\n\n\/\/ This test is too intense for the thread sanitizer.\nTEST_F(TestIBUtilLock, test_long)\n{\n#ifdef IB_THREAD_SANITIZER_WORKAROUND\n cout << \"Test skipped due to thread sanitizer.\" << endl;\n return;\n#else\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(20, 1000, 0.00005, true);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n#endif\n}\n<commit_msg>test_util_lock.cpp: Remove a double-free for a test mutex.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Licensed to Qualys, Inc. (QUALYS) under one or more\n\/\/ contributor license agreements. See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ QUALYS licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file\n\/\/\/ @brief IronBee --- Lock Test Functions\n\/\/\/\n\/\/\/ @author Nick LeRoy <nleroy@qualys.com>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ironbee_config_auto.h\"\n\n#include <ironbee\/types.h>\n#include <ironbee\/mm.h>\n#include <ironbee\/util.h>\n#include <ironbee\/lock.h>\n\n#include \"gtest\/gtest.h\"\n#include \"simple_fixture.hpp\"\n\n#include <stdexcept>\n#include <math.h>\n#include <pthread.h>\n\nusing namespace std;\n\n\/* -- Tests -- *\/\ntypedef void *(* thread_start_fn)(void *thread_data);\n\nclass Thread\n{\npublic:\n explicit\n Thread(int num) :\n m_handle(0),\n m_num(num),\n m_started(false),\n m_running(false),\n m_errors(0)\n {\n }\n Thread() :\n m_handle(0),\n m_num(-1),\n m_started(false),\n m_running(false),\n m_errors(0)\n {\n }\n\n void ThreadNum(int num) { m_num = num; };\n bool IsRunning() const { return m_running; };\n int ThreadNum() const { return m_num; };\n uint64_t ThreadId() const { return (uint64_t)m_handle; };\n uint64_t Errors() const { return m_errors; };\n void Error() { ++m_errors; };\n\n ib_status_t Create(thread_start_fn fn)\n {\n pthread_t handle;\n pthread_attr_t attr;\n int status;\n\n if (m_num < 0) {\n return IB_EINVAL;\n }\n if (m_started || m_running) {\n return IB_EINVAL;\n }\n\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n m_started = true;\n status = pthread_create(&handle, &attr, fn, this);\n if (status) {\n m_started = false;\n return IB_EUNKNOWN;\n }\n\n m_handle = handle;\n return IB_OK;\n }\n\n ib_status_t Join()\n {\n int status;\n\n if (! m_started) {\n return IB_OK;\n }\n status = pthread_join(m_handle, NULL);\n if (status != 0) {\n return IB_EUNKNOWN;\n }\n m_running = false;\n m_started = false;\n\n return IB_OK;\n }\n\n ib_status_t Running(bool run)\n {\n if (!m_started) {\n return IB_EINVAL;\n }\n if (run == m_running) {\n return IB_EINVAL;\n }\n m_running = run;\n return IB_OK;\n }\n\nprivate:\n pthread_t m_handle;\n int m_num;\n bool m_started;\n bool m_running;\n uint64_t m_errors;\n};\n\nclass TestIBUtilLock : public SimpleFixture\n{\npublic:\n TestIBUtilLock() :\n m_max_threads(0),\n m_threads(NULL),\n m_lock_enabled(true),\n m_shared(0)\n {\n TestIBUtilLock::m_self = this;\n TestParams(100, 0.0005, true);\n }\n ~TestIBUtilLock()\n {\n if (m_threads != NULL) {\n delete []m_threads;\n }\n }\n\n virtual void SetUp()\n {\n SimpleFixture::SetUp();\n }\n virtual void TearDown()\n {\n SimpleFixture::TearDown();\n DestroyLock( );\n }\n\n ib_status_t CreateLock()\n {\n return ib_lock_create_malloc(&m_lock);\n }\n ib_status_t DestroyLock()\n {\n ib_lock_destroy_malloc(m_lock);\n m_lock = NULL;\n return IB_OK;\n }\n ib_status_t LockLock()\n {\n return ib_lock_lock(m_lock);\n }\n ib_status_t UnlockLock()\n {\n return ib_lock_unlock(m_lock);\n }\n\n void InitThreads(size_t max_threads)\n {\n m_max_threads = max_threads;\n m_threads = new Thread[max_threads];\n\n for (int num = 0; num < (int)max_threads; ++num) {\n m_threads[num].ThreadNum(num);\n }\n\n }\n void TestParams(size_t loops, double seconds, bool lock)\n {\n Loops(loops);\n SleepTime(seconds);\n m_lock_enabled = lock;\n }\n\n void Loops(size_t loops) { m_loops = loops; };\n void SleepTime(double sec) { m_sleeptime = sec; };\n\n ib_status_t CreateThread(size_t num)\n {\n if(m_threads == NULL) {\n throw std::runtime_error(\"Thread handles not initialized.\");\n }\n if (num >= m_max_threads) {\n throw std::runtime_error(\"Thread number greater than max.\");\n }\n Thread *thread = &m_threads[num];\n if (thread->IsRunning()) {\n throw std::runtime_error(\"Thread already running.\");\n }\n return thread->Create(TestIBUtilLock::StartThread);\n }\n\n ib_status_t CreateAllThreads()\n {\n if(m_threads == NULL) {\n throw std::runtime_error(\"Thread handles not initialized.\");\n }\n\n size_t num;\n for (num = 0; num < m_max_threads; ++num) {\n ib_status_t rc = CreateThread(num);\n if (rc != IB_OK) {\n return rc;\n }\n }\n return IB_OK;\n }\n\n ib_status_t StartTest(size_t threads,\n size_t loops,\n double seconds,\n bool lock)\n {\n InitThreads(threads);\n TestParams(loops, seconds, lock);\n printf(\"Starting: %zd threads, %d loops, %.8fs sleep, locks %s\\n\",\n m_max_threads, m_loops, m_sleeptime,\n m_lock_enabled ? \"enabled\" : \"disabled\");\n return CreateAllThreads( );\n }\n\n static void *StartThread(void *data)\n {\n Thread *thread = (Thread *)data;\n m_self->RunThread(thread);\n return NULL;\n }\n\n void RunThread(Thread *thread)\n {\n ib_status_t rc;\n int n;\n struct timespec ts;\n\n ts.tv_sec = (time_t)trunc(m_sleeptime);\n ts.tv_nsec = (long)(round((m_sleeptime - ts.tv_sec) * 1e9));\n\n thread->Running(true);\n\n for (n = 0; n < m_loops; ++n) {\n if (m_lock_enabled) {\n rc = LockLock( );\n if (rc != IB_OK) {\n thread->Error();\n break;\n }\n }\n \/\/ This code is an intentional race condition if m_lock_enabled is\n \/\/ false. It is possible for it to fail to cause errors, but, at\n \/\/ least in common environments, that is very unlikely.\n if (++m_shared != 1) {\n thread->Error();\n }\n nanosleep(&ts, NULL);\n if (--m_shared != 0) {\n thread->Error();\n }\n\n if (m_lock_enabled) {\n rc = UnlockLock( );\n if (rc != IB_OK) {\n thread->Error();\n break;\n }\n }\n }\n thread->Running(false);\n }\n\n ib_status_t WaitForThreads(uint64_t *errors)\n {\n ib_status_t rc = IB_OK;\n size_t num;\n\n *errors = 0;\n for (num = 0; num < m_max_threads; ++num) {\n Thread *thread = &m_threads[num];\n ib_status_t irc = thread->Join();\n if (irc != IB_OK) {\n rc = irc;\n }\n *errors += thread->Errors();\n }\n return rc;\n }\n\nprivate:\n static TestIBUtilLock *m_self;\n size_t m_max_threads;\n Thread *m_threads;\n ib_lock_t *m_lock;\n bool m_lock_enabled;\n int m_loops;\n double m_sleeptime;\n volatile int m_shared;\n};\nTestIBUtilLock *TestIBUtilLock::m_self = NULL;\n\nTEST(test_util_lock, misc)\n{\n int test = 0;\n\n for (int n=0; n<100; ++n) {\n int t;\n t = ++test;\n ASSERT_EQ(1, t);\n t = --test;\n ASSERT_EQ(0, t);\n }\n}\n\nTEST_F(TestIBUtilLock, test_create)\n{\n ib_status_t rc;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = LockLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = UnlockLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n}\n\n\/\/ The following test is a true positive for a thread race condition.\n\/\/ Disable it for thread sanitizer.\nTEST_F(TestIBUtilLock, test_lock_disabled)\n{\n#ifdef IB_THREAD_SANITIZER_WORKAROUND\n cout << \"Test skipped due to thread sanitizer.\" << endl;\n return;\n#else\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(5, 100, 0.0000005, false);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_NE(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n#endif\n}\n\nTEST_F(TestIBUtilLock, test_short)\n{\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(5, 100, 0.0000005, true);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n}\n\n\/\/ This test is too intense for the thread sanitizer.\nTEST_F(TestIBUtilLock, test_long)\n{\n#ifdef IB_THREAD_SANITIZER_WORKAROUND\n cout << \"Test skipped due to thread sanitizer.\" << endl;\n return;\n#else\n ib_status_t rc;\n uint64_t errors;\n\n rc = CreateLock( );\n ASSERT_EQ(IB_OK, rc);\n\n rc = StartTest(20, 1000, 0.00005, true);\n ASSERT_EQ(IB_OK, rc);\n\n rc = WaitForThreads( &errors );\n ASSERT_EQ(IB_OK, rc);\n ASSERT_EQ(0LU, errors);\n\n rc = DestroyLock( );\n ASSERT_EQ(IB_OK, rc);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2009 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/noncopyable.hpp>\n#include <mapnik\/util\/variant.hpp>\n\/\/ boost\n#include <memory>\n\/\/sqlite3\n#include <sqlite3.h>\n\n\/\/stl\n#ifdef MAPNIK_DEBUG\n#include <iostream>\n#include <cassert>\n#endif\n#include <string>\n#include <vector>\n\nnamespace mapnik { namespace sqlite {\n\n class database : private mapnik::noncopyable\n {\n friend class prepared_statement;\n\n struct database_closer\n {\n void operator () (sqlite3 * db)\n {\n#ifdef MAPNIK_DEBUG\n std::cerr << \"close database \" << db << \"\\n\";\n#endif\n sqlite3_close(db);\n }\n };\n\n using sqlite_db = std::shared_ptr<sqlite3>;\n sqlite_db db_;\n\n public:\n database(std::string const& name);\n ~database();\n bool execute(std::string const& sql);\n };\n\n struct null_type {};\n struct blob\n {\n blob(const char* buf, unsigned size)\n : buf_(buf), size_(size) {}\n\n const char * buf_;\n unsigned size_;\n };\n\n using value_type = mapnik::util::variant<int,double,std::string, blob,null_type>;\n using record_type = std::vector<value_type>;\n\n class prepared_statement : mapnik::noncopyable\n {\n struct binder : public mapnik::util::static_visitor<bool>\n {\n binder(sqlite3_stmt * stmt, unsigned index)\n : stmt_(stmt), index_(index) {}\n\n bool operator() (null_type )\n {\n if (sqlite3_bind_null(stmt_, index_) != SQLITE_OK)\n {\n std::cerr << \"cannot bind nullptr\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (int val)\n {\n if (sqlite3_bind_int(stmt_, index_ , val ) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (double val)\n {\n if (sqlite3_bind_double(stmt_, index_ , val ) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (std::string const& val)\n {\n if (sqlite3_bind_text(stmt_, index_, val.c_str(), val.length(), SQLITE_STATIC) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (blob const& val)\n {\n if (sqlite3_bind_blob(stmt_, index_, val.buf_, val.size_, SQLITE_STATIC) != SQLITE_OK)\n {\n std::cerr << \"cannot bind BLOB\\n\";\n return false;\n }\n return true;\n }\n\n sqlite3_stmt * stmt_;\n unsigned index_;\n };\n public:\n prepared_statement(database & db, std::string const& sql)\n : db_(db.db_.get()), stmt_(0)\n {\n const char * tail;\n \/\/char * err_msg;\n int res = sqlite3_prepare_v2(db_, sql.c_str(),-1, &stmt_,&tail);\n if (res != SQLITE_OK)\n {\n std::cerr << \"ERR:\"<< res << \"\\n\";\n throw;\n }\n }\n\n ~prepared_statement()\n {\n int res = sqlite3_finalize(stmt_);\n if (res != SQLITE_OK)\n {\n std::cerr << \"ERR:\" << res << \"\\n\";\n }\n }\n\n bool insert_record(record_type const& rec) const\n {\n#ifdef MAPNIK_DEBUG\n assert( unsigned(sqlite3_bind_parameter_count(stmt_)) == rec.size());\n#endif\n record_type::const_iterator itr = rec.begin();\n record_type::const_iterator end = rec.end();\n int count = 1;\n for (; itr!=end;++itr)\n {\n binder op(stmt_,count++);\n if (!util::apply_visitor(op,*itr))\n {\n return false;\n }\n }\n\n sqlite3_step(stmt_);\n sqlite3_reset(stmt_);\n\n return true;\n }\n\n private:\n sqlite3 * db_;\n sqlite3_stmt * stmt_;\n };\n }\n}\n<commit_msg>we do need <iostrea> in non-debug<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2009 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/noncopyable.hpp>\n#include <mapnik\/util\/variant.hpp>\n\/\/ boost\n#include <memory>\n\/\/sqlite3\n#include <sqlite3.h>\n\n\/\/stl\n#ifdef MAPNIK_DEBUG\n#include <cassert>\n#endif\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nnamespace mapnik { namespace sqlite {\n\n class database : private mapnik::noncopyable\n {\n friend class prepared_statement;\n\n struct database_closer\n {\n void operator () (sqlite3 * db)\n {\n#ifdef MAPNIK_DEBUG\n std::cerr << \"close database \" << db << \"\\n\";\n#endif\n sqlite3_close(db);\n }\n };\n\n using sqlite_db = std::shared_ptr<sqlite3>;\n sqlite_db db_;\n\n public:\n database(std::string const& name);\n ~database();\n bool execute(std::string const& sql);\n };\n\n struct null_type {};\n struct blob\n {\n blob(const char* buf, unsigned size)\n : buf_(buf), size_(size) {}\n\n const char * buf_;\n unsigned size_;\n };\n\n using value_type = mapnik::util::variant<int,double,std::string, blob,null_type>;\n using record_type = std::vector<value_type>;\n\n class prepared_statement : mapnik::noncopyable\n {\n struct binder : public mapnik::util::static_visitor<bool>\n {\n binder(sqlite3_stmt * stmt, unsigned index)\n : stmt_(stmt), index_(index) {}\n\n bool operator() (null_type )\n {\n if (sqlite3_bind_null(stmt_, index_) != SQLITE_OK)\n {\n std::cerr << \"cannot bind nullptr\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (int val)\n {\n if (sqlite3_bind_int(stmt_, index_ , val ) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (double val)\n {\n if (sqlite3_bind_double(stmt_, index_ , val ) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (std::string const& val)\n {\n if (sqlite3_bind_text(stmt_, index_, val.c_str(), val.length(), SQLITE_STATIC) != SQLITE_OK)\n {\n std::cerr << \"cannot bind \" << val << \"\\n\";\n return false;\n }\n return true;\n }\n\n bool operator() (blob const& val)\n {\n if (sqlite3_bind_blob(stmt_, index_, val.buf_, val.size_, SQLITE_STATIC) != SQLITE_OK)\n {\n std::cerr << \"cannot bind BLOB\\n\";\n return false;\n }\n return true;\n }\n\n sqlite3_stmt * stmt_;\n unsigned index_;\n };\n public:\n prepared_statement(database & db, std::string const& sql)\n : db_(db.db_.get()), stmt_(0)\n {\n const char * tail;\n \/\/char * err_msg;\n int res = sqlite3_prepare_v2(db_, sql.c_str(),-1, &stmt_,&tail);\n if (res != SQLITE_OK)\n {\n std::cerr << \"ERR:\"<< res << \"\\n\";\n throw;\n }\n }\n\n ~prepared_statement()\n {\n int res = sqlite3_finalize(stmt_);\n if (res != SQLITE_OK)\n {\n std::cerr << \"ERR:\" << res << \"\\n\";\n }\n }\n\n bool insert_record(record_type const& rec) const\n {\n#ifdef MAPNIK_DEBUG\n assert( unsigned(sqlite3_bind_parameter_count(stmt_)) == rec.size());\n#endif\n record_type::const_iterator itr = rec.begin();\n record_type::const_iterator end = rec.end();\n int count = 1;\n for (; itr!=end;++itr)\n {\n binder op(stmt_,count++);\n if (!util::apply_visitor(op,*itr))\n {\n return false;\n }\n }\n\n sqlite3_step(stmt_);\n sqlite3_reset(stmt_);\n\n return true;\n }\n\n private:\n sqlite3 * db_;\n sqlite3_stmt * stmt_;\n };\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/test:$Name: $:$Id: MainEvent.cxx,v 1.15 2001\/04\/20 17:56:50 rdm Exp $\n\/\/ Author: Rene Brun 19\/01\/97\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ A simple example with a ROOT tree\n\/\/ =================================\n\/\/\n\/\/ This program creates :\n\/\/ - a ROOT file\n\/\/ - a tree\n\/\/ Additional arguments can be passed to the program to control the flow\n\/\/ of execution. (see comments describing the arguments in the code).\n\/\/ Event nevent comp split fill\n\/\/ All arguments are optional. Default is:\n\/\/ Event 400 1 1 1\n\/\/\n\/\/ In this example, the tree consists of one single \"super branch\"\n\/\/ The statement ***tree->Branch(\"event\", event, 64000,split);*** below\n\/\/ will parse the structure described in Event.h and will make\n\/\/ a new branch for each data member of the class if split is set to 1.\n\/\/ - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex\n\/\/ ,fFlag and fTemperature.\n\/\/ - 3 branches corresponding to the members of the subobject EventHeader.\n\/\/ - one branch for each data member of the class Track of TClonesArray.\n\/\/ - one branch for the object fH (histogram of class TH1F).\n\/\/\n\/\/ if split = 0 only one single branch is created and the complete event\n\/\/ is serialized in one single buffer.\n\/\/ if split = -1 the event is split using the old TBranchObject mechanism\n\/\/ if split > 0 the event is split ising the new TBranchElement mechanism.\n\/\/\n\/\/ if comp = 0 no compression at all.\n\/\/ if comp = 1 event is compressed.\n\/\/ if comp = 2 same as 1. In addition branches with floats in the TClonesArray\n\/\/ are also compressed.\n\/\/ The 4th argument fill can be set to 0 if one wants to time\n\/\/ the percentage of time spent in creating the event structure and\n\/\/ not write the event in the file.\n\/\/ In this example, one loops over nevent events.\n\/\/ The branch \"event\" is created at the first event.\n\/\/ The branch address is set for all other events.\n\/\/ For each event, the event header is filled and ntrack tracks\n\/\/ are generated and added to the TClonesArray list.\n\/\/ For each event the event histogram is saved as well as the list\n\/\/ of all tracks.\n\/\/\n\/\/ The number of events can be given as the first argument to the program.\n\/\/ By default 400 events are generated.\n\/\/ The compression option can be activated\/deactivated via the second argument.\n\/\/\n\/\/ ---Running\/Linking instructions----\n\/\/ This program consists of the following files and procedures.\n\/\/ - Event.h event class description\n\/\/ - Event.C event class implementation\n\/\/ - MainEvent.C the main program to demo this class might be used (this file)\n\/\/ - EventCint.C the CINT dictionary for the event and Track classes\n\/\/ this file is automatically generated by rootcint (see Makefile),\n\/\/ when the class definition in Event.h is modified.\n\/\/\n\/\/ ---Analyzing the Event.root file with the interactive root\n\/\/ example of a simple session\n\/\/ Root > TFile f(\"Event.root\")\n\/\/ Root > T.Draw(\"fNtrack\") \/\/histogram the number of tracks per event\n\/\/ Root > T.Draw(\"fPx\") \/\/histogram fPx for all tracks in all events\n\/\/ Root > T.Draw(\"fXfirst:fYfirst\",\"fNtrack>600\")\n\/\/ \/\/scatter-plot for x versus y of first point of each track\n\/\/ Root > T.Draw(\"fH.GetRMS()\") \/\/histogram of the RMS of the event histogram\n\/\/\n\/\/ Look also in the same directory at the following macros:\n\/\/ - eventa.C an example how to read the tree\n\/\/ - eventb.C how to read events conditionally\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdlib.h>\n\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TNetFile.h\"\n#include \"TRandom.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TClonesArray.h\"\n#include \"TStopwatch.h\"\n\n#include \"Event.h\"\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n Int_t nevent = 400; \/\/ by default create 400 events\n Int_t comp = 1; \/\/ by default file is compressed\n Int_t split = 1; \/\/ by default, split Event in sub branches\n Int_t write = 1; \/\/ by default the tree is filled\n Int_t hfill = 0; \/\/ by default histograms are not filled\n Int_t read = 0;\n Int_t arg4 = 1;\n Int_t arg5 = 600; \/\/default number of tracks per event\n Int_t netf = 0;\n\n if (argc > 1) nevent = atoi(argv[1]);\n if (argc > 2) comp = atoi(argv[2]);\n if (argc > 3) split = atoi(argv[3]);\n if (argc > 4) arg4 = atoi(argv[4]);\n if (argc > 5) arg5 = atoi(argv[5]);\n if (arg4 == 0) { write = 0; hfill = 0; read = 1;}\n if (arg4 == 1) { write = 1; hfill = 0;}\n if (arg4 == 2) { write = 0; hfill = 0;}\n if (arg4 == 10) { write = 0; hfill = 1;}\n if (arg4 == 11) { write = 1; hfill = 1;}\n if (arg4 == 20) { write = 0; read = 1;} \/\/read sequential\n if (arg4 == 25) { write = 0; read = 2;} \/\/read random\n if (arg4 >= 30) { netf = 1; } \/\/use TNetFile\n if (arg4 == 30) { write = 0; read = 1;} \/\/netfile + read sequential\n if (arg4 == 35) { write = 0; read = 2;} \/\/netfile + read random\n if (arg4 == 36) { write = 1; } \/\/netfile + write sequential\n Int_t branchStyle = 1; \/\/new style by default\n if (split < 0) {branchStyle = 0; split = -split;}\n \n TFile *hfile;\n TTree *tree;\n Event *event = 0;\n\n \/\/ Fill event, header and tracks with some random numbers\n \/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n Int_t nb = 0;\n Int_t ev;\n Int_t bufsize;\n Double_t told = 0;\n Double_t tnew = 0;\n Int_t printev = 100;\n if (arg5 < 100) printev = 1000;\n if (arg5 < 10) printev = 10000;\n\n Track::Class()->IgnoreTObjectStreamer();\n\n\/\/ Read case\n if (read) {\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\");\n tree = (TTree*)hfile->Get(\"T\");\n TBranch *branch = tree->GetBranch(\"event\");\n branch->SetAddress(&event);\n Int_t nentries = (Int_t)tree->GetEntries();\n nevent = TMath::Max(nevent,nentries);\n if (read == 1) { \/\/read sequential\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n told=tnew;\n timer.Continue();\n }\n nb += tree->GetEntry(ev); \/\/read complete event in memory\n }\n } else { \/\/read random\n Int_t evrandom;\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) cout<<\"event=\"<<ev<<endl;\n evrandom = Int_t(nevent*gRandom->Rndm(1));\n nb += tree->GetEntry(evrandom); \/\/read complete event in memory\n }\n }\n } else {\n\/\/ Write case\n \/\/ Create a new ROOT binary machine independent file.\n \/\/ Note that this file may contain any kind of ROOT objects, histograms,\n \/\/ pictures, graphics objects, detector geometries, tracks, events, etc..\n \/\/ This file is now becoming the current directory.\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->SetCompressionLevel(comp);\n\n \/\/ Create histogram to show write_time in function of time\n Float_t curtime = -0.5;\n Int_t ntime = nevent\/printev;\n TH1F *htime = new TH1F(\"htime\",\"Real-Time to write versus time\",ntime,0,ntime);\n HistogramManager *hm = 0;\n if (hfill) {\n TDirectory *hdir = new TDirectory(\"histograms\", \"all histograms\");\n hm = new HistogramManager(hdir);\n }\n\n \/\/ Create a ROOT Tree and one superbranch\n TTree *tree = new TTree(\"T\",\"An example of a ROOT tree\");\n tree->SetAutoSave(1000000000); \/\/ autosave when 1 Gbyte written\n bufsize = 64000;\n if (split) bufsize \/= 4;\n event = new Event();\n TTree::SetBranchStyle(branchStyle);\n TBranch *branch = tree->Branch(\"event\", \"Event\", &event, bufsize,split);\n branch->SetAutoDelete(kFALSE);\n char etype[20];\n\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n htime->Fill(curtime,tnew-told);\n curtime += 1;\n told=tnew;\n timer.Continue();\n }\n\n Float_t sigmat, sigmas;\n gRandom->Rannor(sigmat,sigmas);\n Int_t ntrack = Int_t(arg5 +arg5*sigmat\/120.);\n Float_t random = gRandom->Rndm(1);\n\n sprintf(etype,\"type%d\",ev%5);\n event->SetType(etype);\n event->SetHeader(ev, 200, 960312, random);\n event->SetNseg(Int_t(10*ntrack+20*sigmas));\n event->SetNvertex(Int_t(1+20*gRandom->Rndm()));\n event->SetFlag(UInt_t(random+0.5));\n event->SetTemperature(random+20.);\n\n for(UChar_t m = 0; m < 10; m++) {\n event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));\n }\n for(UChar_t i0 = 0; i0 < 4; i0++) {\n for(UChar_t i1 = 0; i1 < 4; i1++) {\n event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));\n }\n }\n\n \/\/ Create and Fill the Track objects\n for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random);\n\n if (write) nb += tree->Fill(); \/\/fill the tree\n\n if (hm) hm->Hfill(event); \/\/fill histograms\n\n event->Clear();\n }\n if (write) {\n hfile->Write();\n tree->Print();\n }\n }\n\n \/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n\n\n printf(\"\\n%d events and %d bytes processed.\\n\",nevent,nb);\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n if (read) {\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n } else {\n printf(\"compression level=%d, split=%d, arg4=%d\\n\",comp,split,arg4);\n printf(\"You write %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You write %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n \/\/printf(\"file compression factor = %f\\n\",hfile.GetCompressionFactor());\n }\n hfile->Close();\n return 0;\n}\n<commit_msg>From Philippe: The following convention is now used for split: \/\/ if split = 0 only one single branch is created and the complete event \/\/ is serialized in one single buffer. \/\/ if split = -2 the event is split using the old TBranchObject mechanism \/\/ if split = -1 the event is streamed using the old TBranchObject mechanism \/\/ if split > 0 the event is split ising the new TBranchElement mechanism.<commit_after>\/\/ @(#)root\/test:$Name: $:$Id: MainEvent.cxx,v 1.16 2001\/04\/24 14:32:46 brun Exp $\n\/\/ Author: Rene Brun 19\/01\/97\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ A simple example with a ROOT tree\n\/\/ =================================\n\/\/\n\/\/ This program creates :\n\/\/ - a ROOT file\n\/\/ - a tree\n\/\/ Additional arguments can be passed to the program to control the flow\n\/\/ of execution. (see comments describing the arguments in the code).\n\/\/ Event nevent comp split fill\n\/\/ All arguments are optional. Default is:\n\/\/ Event 400 1 1 1\n\/\/\n\/\/ In this example, the tree consists of one single \"super branch\"\n\/\/ The statement ***tree->Branch(\"event\", event, 64000,split);*** below\n\/\/ will parse the structure described in Event.h and will make\n\/\/ a new branch for each data member of the class if split is set to 1.\n\/\/ - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex\n\/\/ ,fFlag and fTemperature.\n\/\/ - 3 branches corresponding to the members of the subobject EventHeader.\n\/\/ - one branch for each data member of the class Track of TClonesArray.\n\/\/ - one branch for the object fH (histogram of class TH1F).\n\/\/\n\/\/ if split = 0 only one single branch is created and the complete event\n\/\/ is serialized in one single buffer.\n\/\/ if split = -2 the event is split using the old TBranchObject mechanism\n\/\/ if split = -1 the event is streamed using the old TBranchObject mechanism\n\/\/ if split > 0 the event is split ising the new TBranchElement mechanism.\n\/\/\n\/\/ if comp = 0 no compression at all.\n\/\/ if comp = 1 event is compressed.\n\/\/ if comp = 2 same as 1. In addition branches with floats in the TClonesArray\n\/\/ are also compressed.\n\/\/ The 4th argument fill can be set to 0 if one wants to time\n\/\/ the percentage of time spent in creating the event structure and\n\/\/ not write the event in the file.\n\/\/ In this example, one loops over nevent events.\n\/\/ The branch \"event\" is created at the first event.\n\/\/ The branch address is set for all other events.\n\/\/ For each event, the event header is filled and ntrack tracks\n\/\/ are generated and added to the TClonesArray list.\n\/\/ For each event the event histogram is saved as well as the list\n\/\/ of all tracks.\n\/\/\n\/\/ The number of events can be given as the first argument to the program.\n\/\/ By default 400 events are generated.\n\/\/ The compression option can be activated\/deactivated via the second argument.\n\/\/\n\/\/ ---Running\/Linking instructions----\n\/\/ This program consists of the following files and procedures.\n\/\/ - Event.h event class description\n\/\/ - Event.C event class implementation\n\/\/ - MainEvent.C the main program to demo this class might be used (this file)\n\/\/ - EventCint.C the CINT dictionary for the event and Track classes\n\/\/ this file is automatically generated by rootcint (see Makefile),\n\/\/ when the class definition in Event.h is modified.\n\/\/\n\/\/ ---Analyzing the Event.root file with the interactive root\n\/\/ example of a simple session\n\/\/ Root > TFile f(\"Event.root\")\n\/\/ Root > T.Draw(\"fNtrack\") \/\/histogram the number of tracks per event\n\/\/ Root > T.Draw(\"fPx\") \/\/histogram fPx for all tracks in all events\n\/\/ Root > T.Draw(\"fXfirst:fYfirst\",\"fNtrack>600\")\n\/\/ \/\/scatter-plot for x versus y of first point of each track\n\/\/ Root > T.Draw(\"fH.GetRMS()\") \/\/histogram of the RMS of the event histogram\n\/\/\n\/\/ Look also in the same directory at the following macros:\n\/\/ - eventa.C an example how to read the tree\n\/\/ - eventb.C how to read events conditionally\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdlib.h>\n\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TNetFile.h\"\n#include \"TRandom.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TClonesArray.h\"\n#include \"TStopwatch.h\"\n\n#include \"Event.h\"\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n Int_t nevent = 400; \/\/ by default create 400 events\n Int_t comp = 1; \/\/ by default file is compressed\n Int_t split = 1; \/\/ by default, split Event in sub branches\n Int_t write = 1; \/\/ by default the tree is filled\n Int_t hfill = 0; \/\/ by default histograms are not filled\n Int_t read = 0;\n Int_t arg4 = 1;\n Int_t arg5 = 600; \/\/default number of tracks per event\n Int_t netf = 0;\n\n if (argc > 1) nevent = atoi(argv[1]);\n if (argc > 2) comp = atoi(argv[2]);\n if (argc > 3) split = atoi(argv[3]);\n if (argc > 4) arg4 = atoi(argv[4]);\n if (argc > 5) arg5 = atoi(argv[5]);\n if (arg4 == 0) { write = 0; hfill = 0; read = 1;}\n if (arg4 == 1) { write = 1; hfill = 0;}\n if (arg4 == 2) { write = 0; hfill = 0;}\n if (arg4 == 10) { write = 0; hfill = 1;}\n if (arg4 == 11) { write = 1; hfill = 1;}\n if (arg4 == 20) { write = 0; read = 1;} \/\/read sequential\n if (arg4 == 25) { write = 0; read = 2;} \/\/read random\n if (arg4 >= 30) { netf = 1; } \/\/use TNetFile\n if (arg4 == 30) { write = 0; read = 1;} \/\/netfile + read sequential\n if (arg4 == 35) { write = 0; read = 2;} \/\/netfile + read random\n if (arg4 == 36) { write = 1; } \/\/netfile + write sequential\n Int_t branchStyle = 1; \/\/new style by default\n if (split < 0) {branchStyle = 0; split = 1-split;}\n \n TFile *hfile;\n TTree *tree;\n Event *event = 0;\n\n \/\/ Fill event, header and tracks with some random numbers\n \/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n Int_t nb = 0;\n Int_t ev;\n Int_t bufsize;\n Double_t told = 0;\n Double_t tnew = 0;\n Int_t printev = 100;\n if (arg5 < 100) printev = 1000;\n if (arg5 < 10) printev = 10000;\n\n Track::Class()->IgnoreTObjectStreamer();\n\n\/\/ Read case\n if (read) {\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\");\n tree = (TTree*)hfile->Get(\"T\");\n TBranch *branch = tree->GetBranch(\"event\");\n branch->SetAddress(&event);\n Int_t nentries = (Int_t)tree->GetEntries();\n nevent = TMath::Max(nevent,nentries);\n if (read == 1) { \/\/read sequential\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n told=tnew;\n timer.Continue();\n }\n nb += tree->GetEntry(ev); \/\/read complete event in memory\n }\n } else { \/\/read random\n Int_t evrandom;\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) cout<<\"event=\"<<ev<<endl;\n evrandom = Int_t(nevent*gRandom->Rndm(1));\n nb += tree->GetEntry(evrandom); \/\/read complete event in memory\n }\n }\n } else {\n\/\/ Write case\n \/\/ Create a new ROOT binary machine independent file.\n \/\/ Note that this file may contain any kind of ROOT objects, histograms,\n \/\/ pictures, graphics objects, detector geometries, tracks, events, etc..\n \/\/ This file is now becoming the current directory.\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->SetCompressionLevel(comp);\n\n \/\/ Create histogram to show write_time in function of time\n Float_t curtime = -0.5;\n Int_t ntime = nevent\/printev;\n TH1F *htime = new TH1F(\"htime\",\"Real-Time to write versus time\",ntime,0,ntime);\n HistogramManager *hm = 0;\n if (hfill) {\n TDirectory *hdir = new TDirectory(\"histograms\", \"all histograms\");\n hm = new HistogramManager(hdir);\n }\n\n \/\/ Create a ROOT Tree and one superbranch\n TTree *tree = new TTree(\"T\",\"An example of a ROOT tree\");\n tree->SetAutoSave(1000000000); \/\/ autosave when 1 Gbyte written\n bufsize = 64000;\n if (split) bufsize \/= 4;\n event = new Event();\n TTree::SetBranchStyle(branchStyle);\n TBranch *branch = tree->Branch(\"event\", \"Event\", &event, bufsize,split);\n branch->SetAutoDelete(kFALSE);\n char etype[20];\n\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n htime->Fill(curtime,tnew-told);\n curtime += 1;\n told=tnew;\n timer.Continue();\n }\n\n Float_t sigmat, sigmas;\n gRandom->Rannor(sigmat,sigmas);\n Int_t ntrack = Int_t(arg5 +arg5*sigmat\/120.);\n Float_t random = gRandom->Rndm(1);\n\n sprintf(etype,\"type%d\",ev%5);\n event->SetType(etype);\n event->SetHeader(ev, 200, 960312, random);\n event->SetNseg(Int_t(10*ntrack+20*sigmas));\n event->SetNvertex(Int_t(1+20*gRandom->Rndm()));\n event->SetFlag(UInt_t(random+0.5));\n event->SetTemperature(random+20.);\n\n for(UChar_t m = 0; m < 10; m++) {\n event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));\n }\n for(UChar_t i0 = 0; i0 < 4; i0++) {\n for(UChar_t i1 = 0; i1 < 4; i1++) {\n event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));\n }\n }\n\n \/\/ Create and Fill the Track objects\n for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random);\n\n if (write) nb += tree->Fill(); \/\/fill the tree\n\n if (hm) hm->Hfill(event); \/\/fill histograms\n\n event->Clear();\n }\n if (write) {\n hfile->Write();\n tree->Print();\n }\n }\n\n \/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n\n\n printf(\"\\n%d events and %d bytes processed.\\n\",nevent,nb);\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n if (read) {\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n } else {\n printf(\"compression level=%d, split=%d, arg4=%d\\n\",comp,split,arg4);\n printf(\"You write %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You write %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n \/\/printf(\"file compression factor = %f\\n\",hfile.GetCompressionFactor());\n }\n hfile->Close();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"orc\/OrcFile.hh\"\n#include \"wrap\/gtest-wrapper.h\"\n#include \"TestDriver.hh\"\n\n#include <sstream>\n\nTEST(Reader, simpleTest) {\n orc::ReaderOptions opts;\n std::ostringstream filename;\n filename << exampleDirectory << \"\/demo-11-none.orc\";\n std::unique_ptr<orc::Reader> reader = \n orc::createReader(orc::readLocalFile(filename.str()), opts);\n\n EXPECT_EQ(orc::CompressionKind_NONE, reader->getCompression());\n EXPECT_EQ(256 * 1024, reader->getCompressionSize());\n EXPECT_EQ(385, reader->getNumberOfStripes());\n EXPECT_EQ(1920800, reader->getNumberOfRows());\n EXPECT_EQ(10000, reader->getRowIndexStride());\n EXPECT_EQ(5069718, reader->getContentLength());\n EXPECT_EQ(filename.str(), reader->getStreamName());\n EXPECT_EQ(0, reader->getMetadataKeys().size());\n EXPECT_EQ(false, reader->hasMetadataValue(\"foo\"));\n EXPECT_EQ(18446744073709551615UL, reader->getRowNumber());\n\n const orc::Type& rootType = reader->getType();\n EXPECT_EQ(0, rootType.getColumnId());\n EXPECT_EQ(orc::STRUCT, rootType.getKind());\n ASSERT_EQ(9, rootType.getSubtypeCount());\n EXPECT_EQ(\"_col0\", rootType.getFieldName(0));\n EXPECT_EQ(\"_col1\", rootType.getFieldName(1));\n EXPECT_EQ(\"_col2\", rootType.getFieldName(2));\n EXPECT_EQ(\"_col3\", rootType.getFieldName(3));\n EXPECT_EQ(\"_col4\", rootType.getFieldName(4));\n EXPECT_EQ(\"_col5\", rootType.getFieldName(5));\n EXPECT_EQ(\"_col6\", rootType.getFieldName(6));\n EXPECT_EQ(\"_col7\", rootType.getFieldName(7));\n EXPECT_EQ(\"_col8\", rootType.getFieldName(8));\n EXPECT_EQ(orc::INT, rootType.getSubtype(0).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(1).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(2).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(3).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(4).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(5).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(6).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(7).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(8).getKind());\n for(unsigned int i=0; i < 9; ++i) {\n EXPECT_EQ(i + 1, rootType.getSubtype(i).getColumnId()) << \"fail on \" << i;\n }\n const bool* selected = reader->getSelectedColumns();\n for(int i=0; i < 10; ++i) {\n EXPECT_EQ(true, selected[i]) << \"fail on \" << i;\n }\n\n unsigned long rowCount = 0;\n std::unique_ptr<orc::ColumnVectorBatch> batch = reader->createRowBatch(1024);\n while (reader->next(*batch)) {\n EXPECT_EQ(rowCount, reader->getRowNumber());\n rowCount += batch->numElements;\n }\n EXPECT_EQ(1920800, rowCount);\n EXPECT_EQ(1920000, reader->getRowNumber());\n}\n<commit_msg>Correct unit test to use proper assertion macro.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"orc\/OrcFile.hh\"\n#include \"wrap\/gtest-wrapper.h\"\n#include \"TestDriver.hh\"\n\n#include <sstream>\n\nTEST(Reader, simpleTest) {\n orc::ReaderOptions opts;\n std::ostringstream filename;\n filename << exampleDirectory << \"\/demo-11-none.orc\";\n std::unique_ptr<orc::Reader> reader = \n orc::createReader(orc::readLocalFile(filename.str()), opts);\n\n EXPECT_EQ(orc::CompressionKind_NONE, reader->getCompression());\n EXPECT_EQ(256 * 1024, reader->getCompressionSize());\n EXPECT_EQ(385, reader->getNumberOfStripes());\n EXPECT_EQ(1920800, reader->getNumberOfRows());\n EXPECT_EQ(10000, reader->getRowIndexStride());\n EXPECT_EQ(5069718, reader->getContentLength());\n EXPECT_EQ(filename.str(), reader->getStreamName());\n EXPECT_EQ(0, reader->getMetadataKeys().size());\n EXPECT_FALSE(reader->hasMetadataValue(\"foo\"));\n EXPECT_EQ(18446744073709551615UL, reader->getRowNumber());\n\n const orc::Type& rootType = reader->getType();\n EXPECT_EQ(0, rootType.getColumnId());\n EXPECT_EQ(orc::STRUCT, rootType.getKind());\n ASSERT_EQ(9, rootType.getSubtypeCount());\n EXPECT_EQ(\"_col0\", rootType.getFieldName(0));\n EXPECT_EQ(\"_col1\", rootType.getFieldName(1));\n EXPECT_EQ(\"_col2\", rootType.getFieldName(2));\n EXPECT_EQ(\"_col3\", rootType.getFieldName(3));\n EXPECT_EQ(\"_col4\", rootType.getFieldName(4));\n EXPECT_EQ(\"_col5\", rootType.getFieldName(5));\n EXPECT_EQ(\"_col6\", rootType.getFieldName(6));\n EXPECT_EQ(\"_col7\", rootType.getFieldName(7));\n EXPECT_EQ(\"_col8\", rootType.getFieldName(8));\n EXPECT_EQ(orc::INT, rootType.getSubtype(0).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(1).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(2).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(3).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(4).getKind());\n EXPECT_EQ(orc::STRING, rootType.getSubtype(5).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(6).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(7).getKind());\n EXPECT_EQ(orc::INT, rootType.getSubtype(8).getKind());\n for(unsigned int i=0; i < 9; ++i) {\n EXPECT_EQ(i + 1, rootType.getSubtype(i).getColumnId()) << \"fail on \" << i;\n }\n const bool* selected = reader->getSelectedColumns();\n for(int i=0; i < 10; ++i) {\n EXPECT_EQ(true, selected[i]) << \"fail on \" << i;\n }\n\n unsigned long rowCount = 0;\n std::unique_ptr<orc::ColumnVectorBatch> batch = reader->createRowBatch(1024);\n while (reader->next(*batch)) {\n EXPECT_EQ(rowCount, reader->getRowNumber());\n rowCount += batch->numElements;\n }\n EXPECT_EQ(1920800, rowCount);\n EXPECT_EQ(1920000, reader->getRowNumber());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019 Kacper Kasper <kacperkasper@gmail.com>\n * All rights reserved. Distributed under the terms of the MIT license.\n *\/\n\n\n#include <gtest\/gtest.h>\n\n#include \"support\/Utils.h\"\n\n\/\/ GetFileName\n\nTEST(GetFileNameTest, HandlesNoExtension) {\n\tconst std::string name = \"test\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \"test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesDotFile) {\n\t\/\/ FIXME: that's wrong\n\tconst std::string name = \".test\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \".test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesDotFileWithExtension) {\n\tconst std::string name = \".test.second\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \".test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesDotFileWithEmptyExtension) {\n\tconst std::string name = \".test.\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \".test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesFileWithEmptyExtension) {\n\tconst std::string name = \"test.\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \"test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesFileWithExtension) {\n\tconst std::string name = \"test.txt\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \"test\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesFileWithLongerExtension) {\n\tconst std::string name = \"testing.extension\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \"testing\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileNameTest, HandlesFileWithTwoExtensions) {\n\tconst std::string name = \"testing.long.extension\";\n\tconst std::string result = GetFileName(name);\n\tconst std::string expected = \"testing.long\";\n\tASSERT_EQ(result, expected);\n}\n\n\/\/ GetFileExtension\n\nTEST(GetFileExtensionTest, HandlesNoExtension) {\n\tconst std::string name = \"test\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesDotFile) {\n\tconst std::string name = \".test\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesDotFileWithExtension) {\n\tconst std::string name = \".test.second\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"second\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesDotFileWithEmptyExtension) {\n\tconst std::string name = \".test.\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithEmptyExtension) {\n\tconst std::string name = \"test.\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithExtension) {\n\tconst std::string name = \"test.txt\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"txt\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithLongerExtension) {\n\tconst std::string name = \"testing.extension\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"extension\";\n\tASSERT_EQ(result, expected);\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithTwoExtensions) {\n\tconst std::string name = \"testing.long.extension\";\n\tconst std::string result = GetFileExtension(name);\n\tconst std::string expected = \"extension\";\n\tASSERT_EQ(result, expected);\n}\n<commit_msg>Make unit tests less verbose<commit_after>\/*\n * Copyright 2019 Kacper Kasper <kacperkasper@gmail.com>\n * All rights reserved. Distributed under the terms of the MIT license.\n *\/\n\n\n#include <gtest\/gtest.h>\n\n#include \"support\/Utils.h\"\n\n\/\/ GetFileName\n\nTEST(GetFileNameTest, HandlesNoExtension) {\n\tconst std::string result = GetFileName(\"test\");\n\tASSERT_EQ(result, \"test\");\n}\n\nTEST(GetFileNameTest, HandlesDotFile) {\n\tconst std::string result = GetFileName(\".test\");\n\tASSERT_EQ(result, \".test\");\n}\n\nTEST(GetFileNameTest, HandlesDotFileWithExtension) {\n\tconst std::string result = GetFileName(\".test.second\");\n\tASSERT_EQ(result, \".test\");\n}\n\nTEST(GetFileNameTest, HandlesDotFileWithEmptyExtension) {\n\tconst std::string result = GetFileName(\".test.\");\n\tASSERT_EQ(result, \".test\");\n}\n\nTEST(GetFileNameTest, HandlesFileWithEmptyExtension) {\n\tconst std::string result = GetFileName(\"test.\");\n\tASSERT_EQ(result, \"test\");\n}\n\nTEST(GetFileNameTest, HandlesFileWithExtension) {\n\tconst std::string result = GetFileName(\"test.txt\");\n\tASSERT_EQ(result, \"test\");\n}\n\nTEST(GetFileNameTest, HandlesFileWithLongerExtension) {\n\tconst std::string result = GetFileName(\"testing.extension\");\n\tASSERT_EQ(result, \"testing\");\n}\n\nTEST(GetFileNameTest, HandlesFileWithTwoExtensions) {\n\tconst std::string result = GetFileName(\"testing.long.extension\");\n\tASSERT_EQ(result, \"testing.long\");\n}\n\n\/\/ GetFileExtension\n\nTEST(GetFileExtensionTest, HandlesNoExtension) {\n\tconst std::string result = GetFileExtension(\"test\");\n\tASSERT_EQ(result, \"\");\n}\n\nTEST(GetFileExtensionTest, HandlesDotFile) {\n\tconst std::string result = GetFileExtension(\".test\");\n\tASSERT_EQ(result, \"\");\n}\n\nTEST(GetFileExtensionTest, HandlesDotFileWithExtension) {\n\tconst std::string result = GetFileExtension(\".test.second\");\n\tASSERT_EQ(result, \"second\");\n}\n\nTEST(GetFileExtensionTest, HandlesDotFileWithEmptyExtension) {\n\tconst std::string result = GetFileExtension(\".test.\");\n\tASSERT_EQ(result, \"\");\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithEmptyExtension) {\n\tconst std::string result = GetFileExtension(\"test.\");\n\tASSERT_EQ(result, \"\");\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithExtension) {\n\tconst std::string result = GetFileExtension(\"test.txt\");\n\tASSERT_EQ(result, \"txt\");\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithLongerExtension) {\n\tconst std::string result = GetFileExtension(\"testing.extension\");\n\tASSERT_EQ(result, \"extension\");\n}\n\nTEST(GetFileExtensionTest, HandlesFileWithTwoExtensions) {\n\tconst std::string result = GetFileExtension(\"testing.long.extension\");\n\tASSERT_EQ(result, \"extension\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Substitution.cpp - Type substitutions ----------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Substitution class and operations on it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Substitution.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/GenericEnvironment.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/SubstitutionMap.h\"\n#include \"swift\/AST\/Types.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n\nusing namespace swift;\n\nbool Substitution::operator==(const Substitution &other) const {\n \/\/ The archetypes may be missing, but we can compare them directly\n \/\/ because archetypes are always canonical.\n return\n Replacement->isEqual(other.Replacement) &&\n Conformance.equals(other.Conformance);\n}\n\nSubstitution::Substitution(Type Replacement,\n ArrayRef<ProtocolConformanceRef> Conformance)\n : Replacement(Replacement), Conformance(Conformance)\n{\n \/\/ The replacement type must be materializable.\n assert(Replacement->isMaterializable()\n && \"cannot substitute with a non-materializable type\");\n}\n\nSubstitution Substitution::subst(ModuleDecl *module,\n const SubstitutionMap &subMap) const {\n return subst(module, QuerySubstitutionMap{subMap},\n LookUpConformanceInSubstitutionMap(subMap));\n}\n\nSubstitution Substitution::subst(ModuleDecl *module,\n TypeSubstitutionFn subs,\n LookupConformanceFn conformances) const {\n \/\/ Substitute the replacement.\n Type substReplacement = Replacement.subst(subs, conformances, None);\n assert(substReplacement && \"substitution replacement failed\");\n\n if (substReplacement->isEqual(Replacement))\n return *this;\n\n if (Conformance.empty()) {\n return {substReplacement, Conformance};\n }\n\n bool conformancesChanged = false;\n SmallVector<ProtocolConformanceRef, 4> substConformances;\n substConformances.reserve(Conformance.size());\n\n for (auto c : Conformance) {\n \/\/ If we have a concrete conformance, we need to substitute the\n \/\/ conformance to apply to the new type.\n if (c.isConcrete()) {\n auto substC = c.getConcrete()->subst(module, substReplacement,\n subs, conformances);\n substConformances.push_back(ProtocolConformanceRef(substC));\n if (c != substConformances.back())\n conformancesChanged = true;\n continue;\n }\n\n \/\/ Otherwise, we may need to fill in the conformance.\n ProtocolDecl *proto = c.getAbstract();\n Optional<ProtocolConformanceRef> conformance;\n\n \/\/ If the original type was an archetype, check the conformance map.\n if (Replacement->is<SubstitutableType>()\n || Replacement->is<DependentMemberType>()) {\n conformance = conformances(Replacement->getCanonicalType(),\n substReplacement,\n proto->getDeclaredType());\n }\n\n \/\/ If that didn't find anything, we can still synthesize AnyObject\n \/\/ conformances from thin air. FIXME: gross.\n if (!conformance &&\n proto->isSpecificProtocol(KnownProtocolKind::AnyObject)) {\n auto classDecl\n = substReplacement->getClassOrBoundGenericClass();\n assert(classDecl);\n SmallVector<ProtocolConformance *, 1> lookupResults;\n classDecl->lookupConformance(classDecl->getParentModule(),\n proto, lookupResults);\n conformance = ProtocolConformanceRef(lookupResults.front());\n }\n\n assert(conformance);\n if (conformance->isConcrete())\n conformancesChanged = true;\n substConformances.push_back(*conformance);\n }\n assert(substConformances.size() == Conformance.size());\n\n ArrayRef<ProtocolConformanceRef> substConfs;\n if (conformancesChanged)\n substConfs = Replacement->getASTContext().AllocateCopy(substConformances);\n else\n substConfs = Conformance;\n\n return Substitution{substReplacement, substConfs};\n}\n<commit_msg>Handle archetypes inside Substitution::subst<commit_after>\/\/===--- Substitution.cpp - Type substitutions ----------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Substitution class and operations on it.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Substitution.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/GenericEnvironment.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/ProtocolConformance.h\"\n#include \"swift\/AST\/SubstitutionMap.h\"\n#include \"swift\/AST\/Types.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n\nusing namespace swift;\n\nbool Substitution::operator==(const Substitution &other) const {\n \/\/ The archetypes may be missing, but we can compare them directly\n \/\/ because archetypes are always canonical.\n return\n Replacement->isEqual(other.Replacement) &&\n Conformance.equals(other.Conformance);\n}\n\nSubstitution::Substitution(Type Replacement,\n ArrayRef<ProtocolConformanceRef> Conformance)\n : Replacement(Replacement), Conformance(Conformance)\n{\n \/\/ The replacement type must be materializable.\n assert(Replacement->isMaterializable()\n && \"cannot substitute with a non-materializable type\");\n}\n\nSubstitution Substitution::subst(ModuleDecl *module,\n const SubstitutionMap &subMap) const {\n return subst(module, QuerySubstitutionMap{subMap},\n LookUpConformanceInSubstitutionMap(subMap));\n}\n\nSubstitution Substitution::subst(ModuleDecl *module,\n TypeSubstitutionFn subs,\n LookupConformanceFn conformances) const {\n \/\/ Substitute the replacement.\n Type substReplacement = Replacement.subst(subs, conformances, None);\n assert(substReplacement && \"substitution replacement failed\");\n\n if (substReplacement->isEqual(Replacement))\n return *this;\n\n if (Conformance.empty()) {\n return {substReplacement, Conformance};\n }\n\n bool conformancesChanged = false;\n SmallVector<ProtocolConformanceRef, 4> substConformances;\n substConformances.reserve(Conformance.size());\n\n for (auto c : Conformance) {\n \/\/ If we have a concrete conformance, we need to substitute the\n \/\/ conformance to apply to the new type.\n if (c.isConcrete()) {\n auto substC = c.getConcrete()->subst(module, substReplacement,\n subs, conformances);\n substConformances.push_back(ProtocolConformanceRef(substC));\n if (c != substConformances.back())\n conformancesChanged = true;\n continue;\n }\n\n \/\/ Otherwise, we may need to fill in the conformance.\n ProtocolDecl *proto = c.getAbstract();\n Optional<ProtocolConformanceRef> conformance;\n\n \/\/ If the original type was an archetype, check the conformance map.\n if (Replacement->is<SubstitutableType>()\n || Replacement->is<DependentMemberType>()) {\n conformance = conformances(Replacement->getCanonicalType(),\n substReplacement,\n proto->getDeclaredType());\n }\n\n \/\/ If that didn't find anything, we can still synthesize AnyObject\n \/\/ conformances from thin air. FIXME: gross.\n if (!conformance &&\n proto->isSpecificProtocol(KnownProtocolKind::AnyObject)) {\n auto archetype =\n dyn_cast<ArchetypeType>(substReplacement->getCanonicalType());\n \/\/ If classDecl is not nullptr, it is a concrete class.\n auto classDecl = substReplacement->getClassOrBoundGenericClass();\n if (!classDecl && archetype->getSuperclass()) {\n \/\/ Replacement type is an archetype with a superclass constraint.\n classDecl = archetype->getSuperclass()->getClassOrBoundGenericClass();\n assert(classDecl);\n }\n if (classDecl) {\n \/\/ Create a concrete conformance based on the conforming class.\n SmallVector<ProtocolConformance *, 1> lookupResults;\n classDecl->lookupConformance(classDecl->getParentModule(), proto,\n lookupResults);\n conformance = ProtocolConformanceRef(lookupResults.front());\n } else if (archetype && archetype->requiresClass()) {\n \/\/ Replacement type is an archetype with a class constraint.\n \/\/ Create an abstract conformance.\n conformance = ProtocolConformanceRef(proto);\n }\n }\n\n assert(conformance);\n if (conformance->isConcrete())\n conformancesChanged = true;\n substConformances.push_back(*conformance);\n }\n assert(substConformances.size() == Conformance.size());\n\n ArrayRef<ProtocolConformanceRef> substConfs;\n if (conformancesChanged)\n substConfs = Replacement->getASTContext().AllocateCopy(substConformances);\n else\n substConfs = Conformance;\n\n return Substitution{substReplacement, substConfs};\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %check_clang_tidy %s readability-deleted-default %t\n\nclass NoDefault {\npublic:\n NoDefault() = delete;\n NoDefault(NoDefault &&Other) = delete;\n NoDefault(const NoDefault &Other) = delete;\n};\n\nclass MissingEverything {\npublic:\n MissingEverything() = default;\n \/\/ CHECK-MESSAGES: warning: default constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is lacking a default constructor; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything(MissingEverything &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is neither copyable nor movable; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything(const MissingEverything &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is not copyable; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything &operator=(MissingEverything &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted, probably because a base class or a non-static data member is not assignable, e.g. because the latter is marked 'const'; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything &operator=(const MissingEverything &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted, probably because a base class or a non-static data member is not assignable, e.g. because the latter is marked 'const'; definition can either be removed or explicitly deleted [readability-deleted-default]\n\nprivate:\n NoDefault ND;\n};\n\nclass NotAssignable {\npublic:\n NotAssignable(NotAssignable &&Other) = default;\n NotAssignable(const NotAssignable &Other) = default;\n NotAssignable &operator=(NotAssignable &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted\n NotAssignable &operator=(const NotAssignable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted\n\nprivate:\n const int I = 0;\n};\n\nclass Movable {\npublic:\n Movable() = default;\n Movable(Movable &&Other) = default;\n Movable(const Movable &Other) = delete;\n Movable &operator=(Movable &&Other) = default;\n Movable &operator=(const Movable &Other) = delete;\n};\n\nclass NotCopyable {\npublic:\n NotCopyable(NotCopyable &&Other) = default;\n NotCopyable(const NotCopyable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy constructor is explicitly defaulted but implicitly deleted\n NotCopyable &operator=(NotCopyable &&Other) = default;\n NotCopyable &operator=(const NotCopyable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted\nprivate:\n Movable M;\n};\n\ntemplate <typename T> class Templated {\npublic:\n \/\/ No warning here, it is a templated class.\n Templated() = default;\n Templated(Templated &&Other) = default;\n Templated(const Templated &Other) = default;\n Templated &operator=(Templated &&Other) = default;\n Templated &operator=(const Templated &Other) = default;\n\n class InnerTemplated {\n public:\n \/\/ This class is not in itself templated, but we still don't have warning.\n InnerTemplated() = default;\n InnerTemplated(InnerTemplated &&Other) = default;\n InnerTemplated(const InnerTemplated &Other) = default;\n InnerTemplated &operator=(InnerTemplated &&Other) = default;\n InnerTemplated &operator=(const InnerTemplated &Other) = default;\n\n private:\n T TVar;\n };\n\n class InnerNotTemplated {\n public:\n \/\/ This one could technically have warnings, but currently doesn't.\n InnerNotTemplated() = default;\n InnerNotTemplated(InnerNotTemplated &&Other) = default;\n InnerNotTemplated(const InnerNotTemplated &Other) = default;\n InnerNotTemplated &operator=(InnerNotTemplated &&Other) = default;\n InnerNotTemplated &operator=(const InnerNotTemplated &Other) = default;\n\n private:\n int I;\n };\n\nprivate:\n const T TVar{};\n};\n\nint FunctionWithInnerClass() {\n class InnerNotAssignable {\n public:\n InnerNotAssignable &operator=(InnerNotAssignable &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted\n private:\n const int I = 0;\n };\n return 1;\n};\n\ntemplate <typename T>\nint TemplateFunctionWithInnerClass() {\n class InnerNotAssignable {\n public:\n InnerNotAssignable &operator=(InnerNotAssignable &&Other) = default;\n private:\n const T TVar{};\n };\n return 1;\n};\n\nvoid Foo() {\n Templated<const int> V1;\n Templated<int>::InnerTemplated V2;\n Templated<float>::InnerNotTemplated V3;\n TemplateFunctionWithInnerClass<int>();\n}\n<commit_msg>clang-tools-extra\/test\/clang-tidy\/readability-deleted-default.cpp: Add -fno-ms-compatibility.<commit_after>\/\/ RUN: %check_clang_tidy %s readability-deleted-default %t -- -- -std=c++11 -fno-ms-compatibility\n\nclass NoDefault {\npublic:\n NoDefault() = delete;\n NoDefault(NoDefault &&Other) = delete;\n NoDefault(const NoDefault &Other) = delete;\n};\n\nclass MissingEverything {\npublic:\n MissingEverything() = default;\n \/\/ CHECK-MESSAGES: warning: default constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is lacking a default constructor; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything(MissingEverything &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is neither copyable nor movable; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything(const MissingEverything &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy constructor is explicitly defaulted but implicitly deleted, probably because a non-static data member or a base class is not copyable; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything &operator=(MissingEverything &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted, probably because a base class or a non-static data member is not assignable, e.g. because the latter is marked 'const'; definition can either be removed or explicitly deleted [readability-deleted-default]\n MissingEverything &operator=(const MissingEverything &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted, probably because a base class or a non-static data member is not assignable, e.g. because the latter is marked 'const'; definition can either be removed or explicitly deleted [readability-deleted-default]\n\nprivate:\n NoDefault ND;\n};\n\nclass NotAssignable {\npublic:\n NotAssignable(NotAssignable &&Other) = default;\n NotAssignable(const NotAssignable &Other) = default;\n NotAssignable &operator=(NotAssignable &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted\n NotAssignable &operator=(const NotAssignable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted\n\nprivate:\n const int I = 0;\n};\n\nclass Movable {\npublic:\n Movable() = default;\n Movable(Movable &&Other) = default;\n Movable(const Movable &Other) = delete;\n Movable &operator=(Movable &&Other) = default;\n Movable &operator=(const Movable &Other) = delete;\n};\n\nclass NotCopyable {\npublic:\n NotCopyable(NotCopyable &&Other) = default;\n NotCopyable(const NotCopyable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy constructor is explicitly defaulted but implicitly deleted\n NotCopyable &operator=(NotCopyable &&Other) = default;\n NotCopyable &operator=(const NotCopyable &Other) = default;\n \/\/ CHECK-MESSAGES: warning: copy assignment operator is explicitly defaulted but implicitly deleted\nprivate:\n Movable M;\n};\n\ntemplate <typename T> class Templated {\npublic:\n \/\/ No warning here, it is a templated class.\n Templated() = default;\n Templated(Templated &&Other) = default;\n Templated(const Templated &Other) = default;\n Templated &operator=(Templated &&Other) = default;\n Templated &operator=(const Templated &Other) = default;\n\n class InnerTemplated {\n public:\n \/\/ This class is not in itself templated, but we still don't have warning.\n InnerTemplated() = default;\n InnerTemplated(InnerTemplated &&Other) = default;\n InnerTemplated(const InnerTemplated &Other) = default;\n InnerTemplated &operator=(InnerTemplated &&Other) = default;\n InnerTemplated &operator=(const InnerTemplated &Other) = default;\n\n private:\n T TVar;\n };\n\n class InnerNotTemplated {\n public:\n \/\/ This one could technically have warnings, but currently doesn't.\n InnerNotTemplated() = default;\n InnerNotTemplated(InnerNotTemplated &&Other) = default;\n InnerNotTemplated(const InnerNotTemplated &Other) = default;\n InnerNotTemplated &operator=(InnerNotTemplated &&Other) = default;\n InnerNotTemplated &operator=(const InnerNotTemplated &Other) = default;\n\n private:\n int I;\n };\n\nprivate:\n const T TVar{};\n};\n\nint FunctionWithInnerClass() {\n class InnerNotAssignable {\n public:\n InnerNotAssignable &operator=(InnerNotAssignable &&Other) = default;\n \/\/ CHECK-MESSAGES: warning: move assignment operator is explicitly defaulted but implicitly deleted\n private:\n const int I = 0;\n };\n return 1;\n};\n\ntemplate <typename T>\nint TemplateFunctionWithInnerClass() {\n class InnerNotAssignable {\n public:\n InnerNotAssignable &operator=(InnerNotAssignable &&Other) = default;\n private:\n const T TVar{};\n };\n return 1;\n};\n\nvoid Foo() {\n Templated<const int> V1;\n Templated<int>::InnerTemplated V2;\n Templated<float>::InnerNotTemplated V3;\n TemplateFunctionWithInnerClass<int>();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements bookkeeping for \"interesting\" users of expressions\n\/\/ computed from induction variables.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"iv-users\"\n#include \"llvm\/Analysis\/IVUsers.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/ScalarEvolutionExpressions.h\"\n#include \"llvm\/Assembly\/AsmAnnotationWriter.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <algorithm>\nusing namespace llvm;\n\nchar IVUsers::ID = 0;\nstatic RegisterPass<IVUsers>\nX(\"iv-users\", \"Induction Variable Users\", false, true);\n\nPass *llvm::createIVUsersPass() {\n return new IVUsers();\n}\n\n\/\/\/ isInteresting - Test whether the given expression is \"interesting\" when\n\/\/\/ used by the given expression, within the context of analyzing the\n\/\/\/ given loop.\nstatic bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L) {\n \/\/ Anything loop-invariant is interesting.\n if (!isa<SCEVUnknown>(S) && S->isLoopInvariant(L))\n return true;\n\n \/\/ An addrec is interesting if it's affine or if it has an interesting start.\n if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {\n \/\/ Keep things simple. Don't touch loop-variant strides.\n if (AR->getLoop() == L)\n return AR->isAffine() || !L->contains(I);\n \/\/ Otherwise recurse to see if the start value is interesting.\n return isInteresting(AR->getStart(), I, L);\n }\n\n \/\/ An add is interesting if any of its operands is.\n if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end();\n OI != OE; ++OI)\n if (isInteresting(*OI, I, L))\n return true;\n return false;\n }\n\n \/\/ Nothing else is interesting here.\n return false;\n}\n\n\/\/\/ AddUsersIfInteresting - Inspect the specified instruction. If it is a\n\/\/\/ reducible SCEV, recursively add its users to the IVUsesByStride set and\n\/\/\/ return true. Otherwise, return false.\nbool IVUsers::AddUsersIfInteresting(Instruction *I) {\n if (!SE->isSCEVable(I->getType()))\n return false; \/\/ Void and FP expressions cannot be reduced.\n\n \/\/ LSR is not APInt clean, do not touch integers bigger than 64-bits.\n if (SE->getTypeSizeInBits(I->getType()) > 64)\n return false;\n\n if (!Processed.insert(I))\n return true; \/\/ Instruction already handled.\n\n \/\/ Get the symbolic expression for this instruction.\n const SCEV *ISE = SE->getSCEV(I);\n if (isa<SCEVCouldNotCompute>(ISE)) return false;\n\n \/\/ If we've come to an uninteresting expression, stop the traversal and\n \/\/ call this a user.\n if (!isInteresting(ISE, I, L))\n return false;\n\n SmallPtrSet<Instruction *, 4> UniqueUsers;\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end();\n UI != E; ++UI) {\n Instruction *User = cast<Instruction>(*UI);\n if (!UniqueUsers.insert(User))\n continue;\n\n \/\/ Do not infinitely recurse on PHI nodes.\n if (isa<PHINode>(User) && Processed.count(User))\n continue;\n\n \/\/ Descend recursively, but not into PHI nodes outside the current loop.\n \/\/ It's important to see the entire expression outside the loop to get\n \/\/ choices that depend on addressing mode use right, although we won't\n \/\/ consider references outside the loop in all cases.\n \/\/ If User is already in Processed, we don't want to recurse into it again,\n \/\/ but do want to record a second reference in the same instruction.\n bool AddUserToIVUsers = false;\n if (LI->getLoopFor(User->getParent()) != L) {\n if (isa<PHINode>(User) || Processed.count(User) ||\n !AddUsersIfInteresting(User)) {\n DEBUG(dbgs() << \"FOUND USER in other loop: \" << *User << '\\n'\n << \" OF SCEV: \" << *ISE << '\\n');\n AddUserToIVUsers = true;\n }\n } else if (Processed.count(User) ||\n !AddUsersIfInteresting(User)) {\n DEBUG(dbgs() << \"FOUND USER: \" << *User << '\\n'\n << \" OF SCEV: \" << *ISE << '\\n');\n AddUserToIVUsers = true;\n }\n\n if (AddUserToIVUsers) {\n \/\/ Okay, we found a user that we cannot reduce.\n IVUses.push_back(new IVStrideUse(this, ISE, User, I));\n IVStrideUse &NewUse = IVUses.back();\n \/\/ Transform the expression into a normalized form.\n NewUse.Expr =\n TransformForPostIncUse(NormalizeAutodetect, NewUse.Expr,\n User, I,\n NewUse.PostIncLoops,\n *SE, *DT);\n DEBUG(dbgs() << \" NORMALIZED TO: \" << *NewUse.Expr << '\\n');\n }\n }\n return true;\n}\n\nIVStrideUse &IVUsers::AddUser(const SCEV *Expr,\n Instruction *User, Value *Operand) {\n IVUses.push_back(new IVStrideUse(this, Expr, User, Operand));\n return IVUses.back();\n}\n\nIVUsers::IVUsers()\n : LoopPass(&ID) {\n}\n\nvoid IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LoopInfo>();\n AU.addRequired<DominatorTree>();\n AU.addRequired<ScalarEvolution>();\n AU.setPreservesAll();\n}\n\nbool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {\n\n L = l;\n LI = &getAnalysis<LoopInfo>();\n DT = &getAnalysis<DominatorTree>();\n SE = &getAnalysis<ScalarEvolution>();\n\n \/\/ Find all uses of induction variables in this loop, and categorize\n \/\/ them by stride. Start by finding all of the PHI nodes in the header for\n \/\/ this loop. If they are induction variables, inspect their uses.\n for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)\n AddUsersIfInteresting(I);\n\n return false;\n}\n\n\/\/\/ getReplacementExpr - Return a SCEV expression which computes the\n\/\/\/ value of the OperandValToReplace of the given IVStrideUse.\nconst SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {\n PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(U.PostIncLoops);\n return TransformForPostIncUse(Denormalize, U.getExpr(),\n U.getUser(), U.getOperandValToReplace(),\n Loops, *SE, *DT);\n}\n\nvoid IVUsers::print(raw_ostream &OS, const Module *M) const {\n OS << \"IV Users for loop \";\n WriteAsOperand(OS, L->getHeader(), false);\n if (SE->hasLoopInvariantBackedgeTakenCount(L)) {\n OS << \" with backedge-taken count \"\n << *SE->getBackedgeTakenCount(L);\n }\n OS << \":\\n\";\n\n \/\/ Use a default AssemblyAnnotationWriter to suppress the default info\n \/\/ comments, which aren't relevant here.\n AssemblyAnnotationWriter Annotator;\n for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),\n E = IVUses.end(); UI != E; ++UI) {\n OS << \" \";\n WriteAsOperand(OS, UI->getOperandValToReplace(), false);\n OS << \" = \"\n << *getReplacementExpr(*UI);\n for (PostIncLoopSet::const_iterator\n I = UI->PostIncLoops.begin(),\n E = UI->PostIncLoops.end(); I != E; ++I) {\n OS << \" (post-inc with loop \";\n WriteAsOperand(OS, (*I)->getHeader(), false);\n OS << \")\";\n }\n OS << \" in \";\n UI->getUser()->print(OS, &Annotator);\n OS << '\\n';\n }\n}\n\nvoid IVUsers::dump() const {\n print(dbgs());\n}\n\nvoid IVUsers::releaseMemory() {\n Processed.clear();\n IVUses.clear();\n}\n\nstatic const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) {\n if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {\n if (AR->getLoop() == L)\n return AR;\n return findAddRecForLoop(AR->getStart(), L);\n }\n\n if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();\n I != E; ++I)\n if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))\n return AR;\n return 0;\n }\n\n return 0;\n}\n\nconst SCEV *IVStrideUse::getStride(const Loop *L) const {\n if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(), L))\n return AR->getStepRecurrence(*Parent->SE);\n return 0;\n}\n\nvoid IVStrideUse::transformToPostInc(const Loop *L) {\n PostIncLoopSet Loops;\n Loops.insert(L);\n Expr = TransformForPostIncUse(Normalize, Expr,\n getUser(), getOperandValToReplace(),\n Loops, *Parent->SE, *Parent->DT);\n PostIncLoops.insert(L);\n}\n\nvoid IVStrideUse::deleted() {\n \/\/ Remove this user from the list.\n Parent->IVUses.erase(this);\n \/\/ this now dangles!\n}\n<commit_msg>Delete a dead check.<commit_after>\/\/===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements bookkeeping for \"interesting\" users of expressions\n\/\/ computed from induction variables.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"iv-users\"\n#include \"llvm\/Analysis\/IVUsers.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Analysis\/Dominators.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/ScalarEvolutionExpressions.h\"\n#include \"llvm\/Assembly\/AsmAnnotationWriter.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <algorithm>\nusing namespace llvm;\n\nchar IVUsers::ID = 0;\nstatic RegisterPass<IVUsers>\nX(\"iv-users\", \"Induction Variable Users\", false, true);\n\nPass *llvm::createIVUsersPass() {\n return new IVUsers();\n}\n\n\/\/\/ isInteresting - Test whether the given expression is \"interesting\" when\n\/\/\/ used by the given expression, within the context of analyzing the\n\/\/\/ given loop.\nstatic bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L) {\n \/\/ Anything loop-invariant is interesting.\n if (!isa<SCEVUnknown>(S) && S->isLoopInvariant(L))\n return true;\n\n \/\/ An addrec is interesting if it's affine or if it has an interesting start.\n if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {\n \/\/ Keep things simple. Don't touch loop-variant strides.\n if (AR->getLoop() == L)\n return AR->isAffine() || !L->contains(I);\n \/\/ Otherwise recurse to see if the start value is interesting.\n return isInteresting(AR->getStart(), I, L);\n }\n\n \/\/ An add is interesting if any of its operands is.\n if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end();\n OI != OE; ++OI)\n if (isInteresting(*OI, I, L))\n return true;\n return false;\n }\n\n \/\/ Nothing else is interesting here.\n return false;\n}\n\n\/\/\/ AddUsersIfInteresting - Inspect the specified instruction. If it is a\n\/\/\/ reducible SCEV, recursively add its users to the IVUsesByStride set and\n\/\/\/ return true. Otherwise, return false.\nbool IVUsers::AddUsersIfInteresting(Instruction *I) {\n if (!SE->isSCEVable(I->getType()))\n return false; \/\/ Void and FP expressions cannot be reduced.\n\n \/\/ LSR is not APInt clean, do not touch integers bigger than 64-bits.\n if (SE->getTypeSizeInBits(I->getType()) > 64)\n return false;\n\n if (!Processed.insert(I))\n return true; \/\/ Instruction already handled.\n\n \/\/ Get the symbolic expression for this instruction.\n const SCEV *ISE = SE->getSCEV(I);\n\n \/\/ If we've come to an uninteresting expression, stop the traversal and\n \/\/ call this a user.\n if (!isInteresting(ISE, I, L))\n return false;\n\n SmallPtrSet<Instruction *, 4> UniqueUsers;\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end();\n UI != E; ++UI) {\n Instruction *User = cast<Instruction>(*UI);\n if (!UniqueUsers.insert(User))\n continue;\n\n \/\/ Do not infinitely recurse on PHI nodes.\n if (isa<PHINode>(User) && Processed.count(User))\n continue;\n\n \/\/ Descend recursively, but not into PHI nodes outside the current loop.\n \/\/ It's important to see the entire expression outside the loop to get\n \/\/ choices that depend on addressing mode use right, although we won't\n \/\/ consider references outside the loop in all cases.\n \/\/ If User is already in Processed, we don't want to recurse into it again,\n \/\/ but do want to record a second reference in the same instruction.\n bool AddUserToIVUsers = false;\n if (LI->getLoopFor(User->getParent()) != L) {\n if (isa<PHINode>(User) || Processed.count(User) ||\n !AddUsersIfInteresting(User)) {\n DEBUG(dbgs() << \"FOUND USER in other loop: \" << *User << '\\n'\n << \" OF SCEV: \" << *ISE << '\\n');\n AddUserToIVUsers = true;\n }\n } else if (Processed.count(User) ||\n !AddUsersIfInteresting(User)) {\n DEBUG(dbgs() << \"FOUND USER: \" << *User << '\\n'\n << \" OF SCEV: \" << *ISE << '\\n');\n AddUserToIVUsers = true;\n }\n\n if (AddUserToIVUsers) {\n \/\/ Okay, we found a user that we cannot reduce.\n IVUses.push_back(new IVStrideUse(this, ISE, User, I));\n IVStrideUse &NewUse = IVUses.back();\n \/\/ Transform the expression into a normalized form.\n NewUse.Expr =\n TransformForPostIncUse(NormalizeAutodetect, NewUse.Expr,\n User, I,\n NewUse.PostIncLoops,\n *SE, *DT);\n DEBUG(dbgs() << \" NORMALIZED TO: \" << *NewUse.Expr << '\\n');\n }\n }\n return true;\n}\n\nIVStrideUse &IVUsers::AddUser(const SCEV *Expr,\n Instruction *User, Value *Operand) {\n IVUses.push_back(new IVStrideUse(this, Expr, User, Operand));\n return IVUses.back();\n}\n\nIVUsers::IVUsers()\n : LoopPass(&ID) {\n}\n\nvoid IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LoopInfo>();\n AU.addRequired<DominatorTree>();\n AU.addRequired<ScalarEvolution>();\n AU.setPreservesAll();\n}\n\nbool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {\n\n L = l;\n LI = &getAnalysis<LoopInfo>();\n DT = &getAnalysis<DominatorTree>();\n SE = &getAnalysis<ScalarEvolution>();\n\n \/\/ Find all uses of induction variables in this loop, and categorize\n \/\/ them by stride. Start by finding all of the PHI nodes in the header for\n \/\/ this loop. If they are induction variables, inspect their uses.\n for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)\n AddUsersIfInteresting(I);\n\n return false;\n}\n\n\/\/\/ getReplacementExpr - Return a SCEV expression which computes the\n\/\/\/ value of the OperandValToReplace of the given IVStrideUse.\nconst SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {\n PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(U.PostIncLoops);\n return TransformForPostIncUse(Denormalize, U.getExpr(),\n U.getUser(), U.getOperandValToReplace(),\n Loops, *SE, *DT);\n}\n\nvoid IVUsers::print(raw_ostream &OS, const Module *M) const {\n OS << \"IV Users for loop \";\n WriteAsOperand(OS, L->getHeader(), false);\n if (SE->hasLoopInvariantBackedgeTakenCount(L)) {\n OS << \" with backedge-taken count \"\n << *SE->getBackedgeTakenCount(L);\n }\n OS << \":\\n\";\n\n \/\/ Use a default AssemblyAnnotationWriter to suppress the default info\n \/\/ comments, which aren't relevant here.\n AssemblyAnnotationWriter Annotator;\n for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),\n E = IVUses.end(); UI != E; ++UI) {\n OS << \" \";\n WriteAsOperand(OS, UI->getOperandValToReplace(), false);\n OS << \" = \"\n << *getReplacementExpr(*UI);\n for (PostIncLoopSet::const_iterator\n I = UI->PostIncLoops.begin(),\n E = UI->PostIncLoops.end(); I != E; ++I) {\n OS << \" (post-inc with loop \";\n WriteAsOperand(OS, (*I)->getHeader(), false);\n OS << \")\";\n }\n OS << \" in \";\n UI->getUser()->print(OS, &Annotator);\n OS << '\\n';\n }\n}\n\nvoid IVUsers::dump() const {\n print(dbgs());\n}\n\nvoid IVUsers::releaseMemory() {\n Processed.clear();\n IVUses.clear();\n}\n\nstatic const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) {\n if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {\n if (AR->getLoop() == L)\n return AR;\n return findAddRecForLoop(AR->getStart(), L);\n }\n\n if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {\n for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();\n I != E; ++I)\n if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))\n return AR;\n return 0;\n }\n\n return 0;\n}\n\nconst SCEV *IVStrideUse::getStride(const Loop *L) const {\n if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(), L))\n return AR->getStepRecurrence(*Parent->SE);\n return 0;\n}\n\nvoid IVStrideUse::transformToPostInc(const Loop *L) {\n PostIncLoopSet Loops;\n Loops.insert(L);\n Expr = TransformForPostIncUse(Normalize, Expr,\n getUser(), getOperandValToReplace(),\n Loops, *Parent->SE, *Parent->DT);\n PostIncLoops.insert(L);\n}\n\nvoid IVStrideUse::deleted() {\n \/\/ Remove this user from the list.\n Parent->IVUses.erase(this);\n \/\/ this now dangles!\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"tbb.h\"\n\nint main(int argc, char* argv[])\n{\n return 0;\n}\n<commit_msg>TBB headers in tbb\/*<commit_after>#include \"tbb\/tbb.h\"\n\nint main(int argc, char* argv[])\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- TargetInfo.cpp - Information about Target machine ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the TargetInfo and TargetInfoImpl interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/Builtins.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\nusing namespace clang;\n\n\/\/ TargetInfo Constructor.\nTargetInfo::TargetInfo(const std::string &T) : Triple(T) {\n \/\/ Set defaults. These should be overridden by concrete targets as needed.\n CharIsSigned = true;\n WCharWidth = WCharAlign = 32;\n FloatFormat = &llvm::APFloat::IEEEsingle;\n DoubleFormat = &llvm::APFloat::IEEEdouble;\n LongDoubleFormat = &llvm::APFloat::IEEEdouble;\n}\n\n\/\/ Out of line virtual dtor for TargetInfo.\nTargetInfo::~TargetInfo() {}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\n\nstatic void removeGCCRegisterPrefix(const char *&Name) {\n if (Name[0] == '%' || Name[0] == '#')\n Name++;\n}\n\n\/\/\/ isValidGCCRegisterName - Returns whether the passed in string\n\/\/\/ is a valid register name according to GCC. This is used by Sema for\n\/\/\/ inline asm statements.\nbool TargetInfo::isValidGCCRegisterName(const char *Name) const {\n const char * const *Names;\n unsigned NumNames;\n \n \/\/ Get rid of any register prefix.\n removeGCCRegisterPrefix(Name);\n\n \n if (strcmp(Name, \"memory\") == 0 ||\n strcmp(Name, \"cc\") == 0)\n return true;\n \n getGCCRegNames(Names, NumNames);\n \n \/\/ If we have a number it maps to an entry in the register name array.\n if (isdigit(Name[0])) {\n char *End;\n int n = (int)strtol(Name, &End, 0);\n if (*End == 0)\n return n >= 0 && (unsigned)n < NumNames;\n }\n\n \/\/ Check register names.\n for (unsigned i = 0; i < NumNames; i++) {\n if (strcmp(Name, Names[i]) == 0)\n return true;\n }\n \n \/\/ Now check aliases.\n const GCCRegAlias *Aliases;\n unsigned NumAliases;\n \n getGCCRegAliases(Aliases, NumAliases);\n for (unsigned i = 0; i < NumAliases; i++) {\n for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n if (!Aliases[i].Aliases[j])\n break;\n if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n return true;\n }\n }\n \n return false;\n}\n\nconst char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const {\n assert(isValidGCCRegisterName(Name) && \"Invalid register passed in\");\n \n removeGCCRegisterPrefix(Name);\n \n const char * const *Names;\n unsigned NumNames;\n\n getGCCRegNames(Names, NumNames);\n\n \/\/ First, check if we have a number.\n if (isdigit(Name[0])) {\n char *End;\n int n = (int)strtol(Name, &End, 0);\n if (*End == 0) {\n assert(n >= 0 && (unsigned)n < NumNames && \n \"Out of bounds register number!\");\n return Names[n];\n }\n }\n \n \/\/ Now check aliases.\n const GCCRegAlias *Aliases;\n unsigned NumAliases;\n \n getGCCRegAliases(Aliases, NumAliases);\n for (unsigned i = 0; i < NumAliases; i++) {\n for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n if (!Aliases[i].Aliases[j])\n break;\n if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n return Aliases[i].Register;\n }\n }\n \n return Name;\n}\n\nbool TargetInfo::validateOutputConstraint(const char *Name, \n ConstraintInfo &info) const\n{\n \/\/ An output constraint must start with '=' or '+'\n if (*Name != '=' && *Name != '+')\n return false;\n\n if (*Name == '+')\n info = CI_ReadWrite;\n else\n info = CI_None;\n\n Name++;\n while (*Name) {\n switch (*Name) {\n default:\n if (!validateAsmConstraint(*Name, info)) {\n \/\/ FIXME: This assert is in place temporarily \n \/\/ so we can add more constraints as we hit it.\n \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n assert(0 && \"Unknown output constraint type!\");\n }\n case '&': \/\/ early clobber.\n break;\n case 'r': \/\/ general register.\n info = (ConstraintInfo)(info|CI_AllowsRegister);\n break;\n case 'm': \/\/ memory operand.\n info = (ConstraintInfo)(info|CI_AllowsMemory);\n break;\n case 'g': \/\/ general register, memory operand or immediate integer.\n info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n break;\n }\n \n Name++;\n }\n \n return true;\n}\n\nbool TargetInfo::validateInputConstraint(const char *Name,\n unsigned NumOutputs,\n ConstraintInfo &info) const {\n while (*Name) {\n switch (*Name) {\n default:\n \/\/ Check if we have a matching constraint\n if (*Name >= '0' && *Name <= '9') {\n unsigned i = *Name - '0';\n \n \/\/ Check if matching constraint is out of bounds.\n if (i >= NumOutputs)\n return false;\n } else if (!validateAsmConstraint(*Name, info)) {\n \/\/ FIXME: This assert is in place temporarily \n \/\/ so we can add more constraints as we hit it.\n \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n assert(0 && \"Unknown input constraint type!\");\n } \n case '%': \/\/ commutative\n \/\/ FIXME: Fail if % is used with the last operand.\n break;\n case 'i': \/\/ immediate integer.\n case 'I':\n case 'n': \/\/ immediate integer with a known value.\n break;\n case 'r': \/\/ general register.\n info = (ConstraintInfo)(info|CI_AllowsRegister);\n break;\n case 'm': \/\/ memory operand.\n info = (ConstraintInfo)(info|CI_AllowsMemory);\n break;\n case 'g': \/\/ general register, memory operand or immediate integer.\n info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n break;\n }\n \n Name++;\n }\n \n return true;\n}\n<commit_msg>add a missing #include<commit_after>\/\/===--- TargetInfo.cpp - Information about Target machine ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the TargetInfo and TargetInfoImpl interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/Builtins.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include <cstdlib>\nusing namespace clang;\n\n\/\/ TargetInfo Constructor.\nTargetInfo::TargetInfo(const std::string &T) : Triple(T) {\n \/\/ Set defaults. These should be overridden by concrete targets as needed.\n CharIsSigned = true;\n WCharWidth = WCharAlign = 32;\n FloatFormat = &llvm::APFloat::IEEEsingle;\n DoubleFormat = &llvm::APFloat::IEEEdouble;\n LongDoubleFormat = &llvm::APFloat::IEEEdouble;\n}\n\n\/\/ Out of line virtual dtor for TargetInfo.\nTargetInfo::~TargetInfo() {}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\n\nstatic void removeGCCRegisterPrefix(const char *&Name) {\n if (Name[0] == '%' || Name[0] == '#')\n Name++;\n}\n\n\/\/\/ isValidGCCRegisterName - Returns whether the passed in string\n\/\/\/ is a valid register name according to GCC. This is used by Sema for\n\/\/\/ inline asm statements.\nbool TargetInfo::isValidGCCRegisterName(const char *Name) const {\n const char * const *Names;\n unsigned NumNames;\n \n \/\/ Get rid of any register prefix.\n removeGCCRegisterPrefix(Name);\n\n \n if (strcmp(Name, \"memory\") == 0 ||\n strcmp(Name, \"cc\") == 0)\n return true;\n \n getGCCRegNames(Names, NumNames);\n \n \/\/ If we have a number it maps to an entry in the register name array.\n if (isdigit(Name[0])) {\n char *End;\n int n = (int)strtol(Name, &End, 0);\n if (*End == 0)\n return n >= 0 && (unsigned)n < NumNames;\n }\n\n \/\/ Check register names.\n for (unsigned i = 0; i < NumNames; i++) {\n if (strcmp(Name, Names[i]) == 0)\n return true;\n }\n \n \/\/ Now check aliases.\n const GCCRegAlias *Aliases;\n unsigned NumAliases;\n \n getGCCRegAliases(Aliases, NumAliases);\n for (unsigned i = 0; i < NumAliases; i++) {\n for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n if (!Aliases[i].Aliases[j])\n break;\n if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n return true;\n }\n }\n \n return false;\n}\n\nconst char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const {\n assert(isValidGCCRegisterName(Name) && \"Invalid register passed in\");\n \n removeGCCRegisterPrefix(Name);\n \n const char * const *Names;\n unsigned NumNames;\n\n getGCCRegNames(Names, NumNames);\n\n \/\/ First, check if we have a number.\n if (isdigit(Name[0])) {\n char *End;\n int n = (int)strtol(Name, &End, 0);\n if (*End == 0) {\n assert(n >= 0 && (unsigned)n < NumNames && \n \"Out of bounds register number!\");\n return Names[n];\n }\n }\n \n \/\/ Now check aliases.\n const GCCRegAlias *Aliases;\n unsigned NumAliases;\n \n getGCCRegAliases(Aliases, NumAliases);\n for (unsigned i = 0; i < NumAliases; i++) {\n for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n if (!Aliases[i].Aliases[j])\n break;\n if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n return Aliases[i].Register;\n }\n }\n \n return Name;\n}\n\nbool TargetInfo::validateOutputConstraint(const char *Name, \n ConstraintInfo &info) const\n{\n \/\/ An output constraint must start with '=' or '+'\n if (*Name != '=' && *Name != '+')\n return false;\n\n if (*Name == '+')\n info = CI_ReadWrite;\n else\n info = CI_None;\n\n Name++;\n while (*Name) {\n switch (*Name) {\n default:\n if (!validateAsmConstraint(*Name, info)) {\n \/\/ FIXME: This assert is in place temporarily \n \/\/ so we can add more constraints as we hit it.\n \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n assert(0 && \"Unknown output constraint type!\");\n }\n case '&': \/\/ early clobber.\n break;\n case 'r': \/\/ general register.\n info = (ConstraintInfo)(info|CI_AllowsRegister);\n break;\n case 'm': \/\/ memory operand.\n info = (ConstraintInfo)(info|CI_AllowsMemory);\n break;\n case 'g': \/\/ general register, memory operand or immediate integer.\n info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n break;\n }\n \n Name++;\n }\n \n return true;\n}\n\nbool TargetInfo::validateInputConstraint(const char *Name,\n unsigned NumOutputs,\n ConstraintInfo &info) const {\n while (*Name) {\n switch (*Name) {\n default:\n \/\/ Check if we have a matching constraint\n if (*Name >= '0' && *Name <= '9') {\n unsigned i = *Name - '0';\n \n \/\/ Check if matching constraint is out of bounds.\n if (i >= NumOutputs)\n return false;\n } else if (!validateAsmConstraint(*Name, info)) {\n \/\/ FIXME: This assert is in place temporarily \n \/\/ so we can add more constraints as we hit it.\n \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n assert(0 && \"Unknown input constraint type!\");\n } \n case '%': \/\/ commutative\n \/\/ FIXME: Fail if % is used with the last operand.\n break;\n case 'i': \/\/ immediate integer.\n case 'I':\n case 'n': \/\/ immediate integer with a known value.\n break;\n case 'r': \/\/ general register.\n info = (ConstraintInfo)(info|CI_AllowsRegister);\n break;\n case 'm': \/\/ memory operand.\n info = (ConstraintInfo)(info|CI_AllowsMemory);\n break;\n case 'g': \/\/ general register, memory operand or immediate integer.\n info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n break;\n }\n \n Name++;\n }\n \n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief vocbase traversals\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Michael Hackstein\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Traverser.h\"\n\n#include \"Basics\/Thread.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\n\nclass Searcher : public Thread {\n\n Traverser* _traverser;\n Traverser::ThreadInfo& _myInfo;\n Traverser::ThreadInfo& _peerInfo;\n Traverser::VertexId _start;\n Traverser::ExpanderFunction _expander;\n string _id;\n\n public:\n\n Searcher (Traverser* traverser, Traverser::ThreadInfo& myInfo, \n Traverser::ThreadInfo& peerInfo, Traverser::VertexId start,\n Traverser::ExpanderFunction expander, string id)\n : Thread(id), _traverser(traverser), _myInfo(myInfo), \n _peerInfo(peerInfo), _start(start), _expander(expander), _id(id) {\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Insert a neighbor to the todo list.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n private:\n\n void insertNeighbor (Traverser::VertexId& neighbor,\n Traverser::VertexId& predecessor,\n Traverser::EdgeId& edge,\n Traverser::EdgeWeight weight) {\n\n std::lock_guard<std::mutex> guard(_myInfo._mutex);\n Traverser::Step* s = _myInfo._pq.find(neighbor);\n\n \/\/ Not found, so insert it:\n if (s == nullptr) {\n _myInfo._pq.insert(neighbor, \n Traverser::Step(neighbor, predecessor, \n weight, edge));\n return;\n }\n if (s->_done) {\n return;\n }\n if (s->_weight > weight) {\n _myInfo._pq.lowerWeight(neighbor, weight);\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Lookup our current vertex in the data of our peer.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void lookupPeer (Traverser::VertexId& vertex,\n Traverser::EdgeWeight weight) {\n\n std::lock_guard<std::mutex> guard(_peerInfo._mutex);\n Traverser::Step* s = _peerInfo._pq.find(vertex);\n if (s == nullptr) {\n \/\/ Not found, nothing more to do\n return;\n }\n Traverser::EdgeWeight total = s->_weight + weight;\n\n \/\/ Update the highscore:\n std::lock_guard<std::mutex> guard2(_traverser->_resultMutex);\n if (!_traverser->_highscoreSet || total < _traverser->_highscore) {\n _traverser->_highscoreSet = true;\n _traverser->_highscore = total;\n }\n\n \/\/ Now the highscore is set!\n\n \/\/ Did we find a solution together with the other thread?\n if (s->_done) {\n if (total <= _traverser->_highscore) {\n _traverser->_intermediate = vertex;\n _traverser->_bingo = true;\n }\n \/\/ We found a way, but somebody else found a better way, so\n \/\/ this is not the shortest path\n return;\n }\n\n \/\/ Did we find a solution on our own? This is for the single thread\n \/\/ case and for the case that the other thread is too slow to even\n \/\/ finish its own start vertex!\n if (s->_weight == 0) {\n \/\/ We have found the target, we have finished all vertices with\n \/\/ a smaller weight than this one (and did not succeed), so this\n \/\/ must be a best solution:\n _traverser->_intermediate = vertex;\n _traverser->_bingo = true;\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Search graph starting at Start following edges of the given\n\/\/\/ direction only\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n public:\n\n virtual void run () {\n\n Traverser::VertexId v;\n Traverser::Step s;\n bool b = _myInfo._pq.popMinimal(v, s, true);\n \n std::vector<Traverser::Step> neighbors;\n\n \/\/ Iterate while no bingo found and\n \/\/ there still is a vertex on the stack.\n while (!_traverser->_bingo && b) {\n neighbors.clear();\n _expander(v, neighbors);\n for (auto& neighbor : neighbors) {\n insertNeighbor(neighbor._vertex, v, neighbor._edge, \n s._weight + neighbor._weight);\n }\n lookupPeer(v, s._weight);\n\n std::lock_guard<std::mutex> guard(_myInfo._mutex);\n Traverser::Step* s2 = _myInfo._pq.find(v);\n s2->_done = true;\n b = _myInfo._pq.popMinimal(v, s, true);\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief return the shortest path between the start and target vertex.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTraverser::Path* Traverser::shortestPath (VertexId const& start,\n VertexId const& target) {\n\n \/\/ For the result:\n std::deque<VertexId> r_vertices;\n std::deque<VertexId> r_edges;\n _highscoreSet = false;\n _highscore = 0;\n _bingo = false;\n\n \/\/ Forward with initialization:\n string empty;\n ThreadInfo forward;\n forward._pq.insert(start, Step(start, empty, 0, empty));\n\n \/\/ backward with initialization:\n ThreadInfo backward;\n backward._pq.insert(target, Step(target, empty, 0, empty));\n\n \/\/ Now the searcher threads:\n Searcher forwardSearcher(this, forward, backward, start,\n _forwardExpander, \"Forward\");\n \/\/Searcher backwardSearcher(this, backward, forward, target,\n \/\/ _backwardExpander, \"Backward\");\n forwardSearcher.start();\n \/\/backwardSearcher.start();\n forwardSearcher.join();\n \/\/backwardSearcher.join();\n\n if (!_bingo || _intermediate == \"\") {\n return nullptr;\n }\n\n Step* s = forward._pq.find(_intermediate);\n r_vertices.push_back(_intermediate);\n\n \/\/ FORWARD Go path back from intermediate -> start.\n \/\/ Insert all vertices and edges at front of vector\n \/\/ Do NOT! insert the intermediate vertex\n while (s->_predecessor != \"\") {\n r_edges.push_front(s->_edge);\n r_vertices.push_front(s->_predecessor);\n s = forward._pq.find(s->_predecessor);\n }\n\n \/\/ BACKWARD Go path back from intermediate -> target.\n \/\/ Insert all vertices and edges at back of vector\n \/\/ Also insert the intermediate vertex\n s = backward._pq.find(_intermediate);\n while (s->_predecessor != \"\") {\n r_edges.push_back(s->_edge);\n r_vertices.push_back(s->_predecessor);\n s = backward._pq.find(s->_predecessor);\n }\n return new Path(r_vertices, r_edges, _highscore);\n};\n\n<commit_msg>Switch on second thread.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief vocbase traversals\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Michael Hackstein\n\/\/\/ @author Max Neunhoeffer\n\/\/\/ @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Traverser.h\"\n\n#include \"Basics\/Thread.h\"\n\nusing namespace std;\nusing namespace triagens::basics;\n\nclass Searcher : public Thread {\n\n Traverser* _traverser;\n Traverser::ThreadInfo& _myInfo;\n Traverser::ThreadInfo& _peerInfo;\n Traverser::VertexId _start;\n Traverser::ExpanderFunction _expander;\n string _id;\n\n public:\n\n Searcher (Traverser* traverser, Traverser::ThreadInfo& myInfo, \n Traverser::ThreadInfo& peerInfo, Traverser::VertexId start,\n Traverser::ExpanderFunction expander, string id)\n : Thread(id), _traverser(traverser), _myInfo(myInfo), \n _peerInfo(peerInfo), _start(start), _expander(expander), _id(id) {\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Insert a neighbor to the todo list.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n private:\n\n void insertNeighbor (Traverser::VertexId& neighbor,\n Traverser::VertexId& predecessor,\n Traverser::EdgeId& edge,\n Traverser::EdgeWeight weight) {\n\n std::lock_guard<std::mutex> guard(_myInfo._mutex);\n Traverser::Step* s = _myInfo._pq.find(neighbor);\n\n \/\/ Not found, so insert it:\n if (s == nullptr) {\n _myInfo._pq.insert(neighbor, \n Traverser::Step(neighbor, predecessor, \n weight, edge));\n return;\n }\n if (s->_done) {\n return;\n }\n if (s->_weight > weight) {\n _myInfo._pq.lowerWeight(neighbor, weight);\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Lookup our current vertex in the data of our peer.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n void lookupPeer (Traverser::VertexId& vertex,\n Traverser::EdgeWeight weight) {\n\n std::lock_guard<std::mutex> guard(_peerInfo._mutex);\n Traverser::Step* s = _peerInfo._pq.find(vertex);\n if (s == nullptr) {\n \/\/ Not found, nothing more to do\n return;\n }\n Traverser::EdgeWeight total = s->_weight + weight;\n\n \/\/ Update the highscore:\n std::lock_guard<std::mutex> guard2(_traverser->_resultMutex);\n if (!_traverser->_highscoreSet || total < _traverser->_highscore) {\n _traverser->_highscoreSet = true;\n _traverser->_highscore = total;\n }\n\n \/\/ Now the highscore is set!\n\n \/\/ Did we find a solution together with the other thread?\n if (s->_done) {\n if (total <= _traverser->_highscore) {\n _traverser->_intermediate = vertex;\n _traverser->_bingo = true;\n }\n \/\/ We found a way, but somebody else found a better way, so\n \/\/ this is not the shortest path\n return;\n }\n\n \/\/ Did we find a solution on our own? This is for the single thread\n \/\/ case and for the case that the other thread is too slow to even\n \/\/ finish its own start vertex!\n if (s->_weight == 0) {\n \/\/ We have found the target, we have finished all vertices with\n \/\/ a smaller weight than this one (and did not succeed), so this\n \/\/ must be a best solution:\n _traverser->_intermediate = vertex;\n _traverser->_bingo = true;\n }\n }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief Search graph starting at Start following edges of the given\n\/\/\/ direction only\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n public:\n\n virtual void run () {\n\n Traverser::VertexId v;\n Traverser::Step s;\n bool b = _myInfo._pq.popMinimal(v, s, true);\n \n std::vector<Traverser::Step> neighbors;\n\n \/\/ Iterate while no bingo found and\n \/\/ there still is a vertex on the stack.\n while (!_traverser->_bingo && b) {\n neighbors.clear();\n _expander(v, neighbors);\n for (auto& neighbor : neighbors) {\n insertNeighbor(neighbor._vertex, v, neighbor._edge, \n s._weight + neighbor._weight);\n }\n lookupPeer(v, s._weight);\n\n std::lock_guard<std::mutex> guard(_myInfo._mutex);\n Traverser::Step* s2 = _myInfo._pq.find(v);\n s2->_done = true;\n b = _myInfo._pq.popMinimal(v, s, true);\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief return the shortest path between the start and target vertex.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTraverser::Path* Traverser::shortestPath (VertexId const& start,\n VertexId const& target) {\n\n \/\/ For the result:\n std::deque<VertexId> r_vertices;\n std::deque<VertexId> r_edges;\n _highscoreSet = false;\n _highscore = 0;\n _bingo = false;\n\n \/\/ Forward with initialization:\n string empty;\n ThreadInfo forward;\n forward._pq.insert(start, Step(start, empty, 0, empty));\n\n \/\/ backward with initialization:\n ThreadInfo backward;\n backward._pq.insert(target, Step(target, empty, 0, empty));\n\n \/\/ Now the searcher threads:\n Searcher forwardSearcher(this, forward, backward, start,\n _forwardExpander, \"Forward\");\n Searcher backwardSearcher(this, backward, forward, target,\n _backwardExpander, \"Backward\");\n forwardSearcher.start();\n backwardSearcher.start();\n forwardSearcher.join();\n backwardSearcher.join();\n\n if (!_bingo || _intermediate == \"\") {\n return nullptr;\n }\n\n Step* s = forward._pq.find(_intermediate);\n r_vertices.push_back(_intermediate);\n\n \/\/ FORWARD Go path back from intermediate -> start.\n \/\/ Insert all vertices and edges at front of vector\n \/\/ Do NOT! insert the intermediate vertex\n while (s->_predecessor != \"\") {\n r_edges.push_front(s->_edge);\n r_vertices.push_front(s->_predecessor);\n s = forward._pq.find(s->_predecessor);\n }\n\n \/\/ BACKWARD Go path back from intermediate -> target.\n \/\/ Insert all vertices and edges at back of vector\n \/\/ Also insert the intermediate vertex\n s = backward._pq.find(_intermediate);\n while (s->_predecessor != \"\") {\n r_edges.push_back(s->_edge);\n r_vertices.push_back(s->_predecessor);\n s = backward._pq.find(s->_predecessor);\n }\n return new Path(r_vertices, r_edges, _highscore);\n};\n\n<|endoftext|>"} {"text":"<commit_before>#include \"unit-tests.h\"\n#include <src\/MIDI.h>\n\nBEGIN_MIDI_NAMESPACE\n\nEND_MIDI_NAMESPACE\n\n\/\/ -----------------------------------------------------------------------------\n\nBEGIN_UNNAMED_NAMESPACE\n\nusing namespace testing;\n\nTEST(SysExCodec, Encoder)\n{\n \/\/ ASCII content\n {\n const byte input[] = \"Hello, World!\";\n byte buffer[32];\n memset(buffer, 0, 32 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer, 13);\n EXPECT_EQ(encodedSize, 15);\n const byte expected[32] = {\n 0, 'H', 'e', 'l', 'l', 'o', ',', ' ',\n 0, 'W', 'o', 'r', 'l', 'd', '!', 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n \/\/ Non-ASCII content\n {\n const byte input[] = {\n 182, 236, 167, 177, 61, 91, 120, \/\/ 01111000 -> 120\n 107, 94, 209, 87, 94 \/\/ 000100xx -> 16\n };\n byte buffer[32];\n memset(buffer, 0, 32 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer, 12);\n EXPECT_EQ(encodedSize, 14);\n const byte expected[32] = {\n \/\/ MSB Data\n 120, 54, 108, 39, 49, 61, 91, 120,\n 16, 107, 94, 81, 87, 94, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n}\n\nTEST(SysExCodec, Decoder)\n{\n \/\/ ASCII content\n {\n const byte input[] = {\n 0, 'H', 'e', 'l', 'l', 'o', ',', ' ',\n 0, 'W', 'o', 'r', 'l', 'd', '!',\n };\n byte buffer[32];\n memset(buffer, 0, 32 * sizeof(byte));\n const unsigned decodedSize = midi::decodeSysEx(input, buffer, 15);\n EXPECT_EQ(decodedSize, 13);\n const byte expected[32] = {\n 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',\n 'o', 'r', 'l', 'd', '!', 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n \/\/ Non-ASCII content\n {\n const byte input[] = {\n \/\/ MSB Data\n 120, 54, 108, 39, 49, 61, 91, 120,\n 16, 107, 94, 81, 87, 94,\n };\n byte buffer[32];\n memset(buffer, 0, 32 * sizeof(byte));\n const unsigned encodedSize = midi::decodeSysEx(input, buffer, 14);\n EXPECT_EQ(encodedSize, 12);\n const byte expected[32] = {\n 182, 236, 167, 177, 61, 91, 120,\n 107, 94, 209, 87, 94, 0, 0,\n 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0\n };\n EXPECT_THAT(input, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n}\n\nTEST(SysExCodec, Codec)\n{\n\n}\n\nEND_UNNAMED_NAMESPACE\n<commit_msg>Smaller buffers, added full codec test.<commit_after>#include \"unit-tests.h\"\n#include <src\/MIDI.h>\n\nBEGIN_MIDI_NAMESPACE\n\nEND_MIDI_NAMESPACE\n\n\/\/ -----------------------------------------------------------------------------\n\nBEGIN_UNNAMED_NAMESPACE\n\nusing namespace testing;\n\nTEST(SysExCodec, Encoder)\n{\n \/\/ ASCII content\n {\n const byte input[] = \"Hello, World!\";\n byte buffer[16];\n memset(buffer, 0, 16 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer, 13);\n EXPECT_EQ(encodedSize, 15);\n const byte expected[16] = {\n 0, 'H', 'e', 'l', 'l', 'o', ',', ' ',\n 0, 'W', 'o', 'r', 'l', 'd', '!', 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n \/\/ Non-ASCII content\n {\n const byte input[] = {\n 182, 236, 167, 177, 61, 91, 120, \/\/ 01111000 -> 120\n 107, 94, 209, 87, 94 \/\/ 000100xx -> 16\n };\n byte buffer[16];\n memset(buffer, 0, 16 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer, 12);\n EXPECT_EQ(encodedSize, 14);\n const byte expected[16] = {\n \/\/ MSB Data\n 120, 54, 108, 39, 49, 61, 91, 120,\n 16, 107, 94, 81, 87, 94, 0, 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n}\n\nTEST(SysExCodec, Decoder)\n{\n \/\/ ASCII content\n {\n const byte input[] = {\n 0, 'H', 'e', 'l', 'l', 'o', ',', ' ',\n 0, 'W', 'o', 'r', 'l', 'd', '!',\n };\n byte buffer[16];\n memset(buffer, 0, 16 * sizeof(byte));\n const unsigned decodedSize = midi::decodeSysEx(input, buffer, 15);\n EXPECT_EQ(decodedSize, 13);\n const byte expected[16] = {\n 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',\n 'o', 'r', 'l', 'd', '!', 0, 0, 0,\n };\n EXPECT_THAT(buffer, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n \/\/ Non-ASCII content\n {\n const byte input[] = {\n \/\/ MSB Data\n 120, 54, 108, 39, 49, 61, 91, 120,\n 16, 107, 94, 81, 87, 94,\n };\n byte buffer[16];\n memset(buffer, 0, 16 * sizeof(byte));\n const unsigned encodedSize = midi::decodeSysEx(input, buffer, 14);\n EXPECT_EQ(encodedSize, 12);\n const byte expected[16] = {\n 182, 236, 167, 177, 61, 91, 120,\n 107, 94, 209, 87, 94, 0, 0,\n 0, 0,\n };\n EXPECT_THAT(input, Each(Le(0x7f))); \/\/ All elements are <= 127\n EXPECT_THAT(buffer, ContainerEq(expected));\n }\n}\n\nTEST(SysExCodec, Codec)\n{\n \/\/ ASCII content\n {\n const byte input[] = \"Hello, World!\";\n byte buffer1[16];\n byte buffer2[16];\n memset(buffer1, 0, 16 * sizeof(byte));\n memset(buffer2, 0, 16 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer1, 13);\n EXPECT_EQ(encodedSize, 15);\n const unsigned decodedSize = midi::decodeSysEx(buffer1, buffer2, encodedSize);\n EXPECT_EQ(decodedSize, 13);\n EXPECT_STREQ(reinterpret_cast<const char*>(buffer2),\n reinterpret_cast<const char*>(input));\n }\n \/\/ Non-ASCII content\n {\n const byte input[] = {\n \/\/ MSB Data\n 182, 236, 167, 177, 61, 91, 120,\n 107, 94, 209, 87, 94\n };\n byte buffer1[14];\n byte buffer2[12];\n memset(buffer1, 0, 14 * sizeof(byte));\n memset(buffer2, 0, 12 * sizeof(byte));\n const unsigned encodedSize = midi::encodeSysEx(input, buffer1, 12);\n EXPECT_EQ(encodedSize, 14);\n const unsigned decodedSize = midi::decodeSysEx(buffer1, buffer2, encodedSize);\n EXPECT_EQ(decodedSize, 12);\n EXPECT_THAT(buffer2, ContainerEq(input));\n }\n}\n\nEND_UNNAMED_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>#include \"rtkTest.h\"\n#include \"rtkDrawEllipsoidImageFilter.h\"\n#include \"rtkRayEllipsoidIntersectionImageFilter.h\"\n#include \"rtkConstantImageSource.h\"\n#include \"rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h\"\n#include <itkAdditiveGaussianNoiseImageFilter.h>\n\n#ifdef USE_CUDA\n #include \"itkCudaImage.h\"\n#endif\n\n\/**\n * \\file rtkregularizedconjugategradienttest.cxx\n *\n * \\brief Functional test for ADMMTotalVariation reconstruction\n *\n * This test generates the projections of an ellipsoid and reconstructs the CT\n * image using the ADMMTotalVariation algorithm with different backprojectors (Voxel-Based,\n * Joseph). The generated results are compared to the\n * expected results (analytical calculation).\n *\n * \\author Cyril Mory\n *\/\n\nint main(int, char** )\n{\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n#ifdef USE_CUDA\n typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n#endif\n\n#if FAST_TESTS_NO_CHECKS\n const unsigned int NumberOfProjectionImages = 3;\n#else\n const unsigned int NumberOfProjectionImages = 90;\n#endif\n\n \/\/ Constant image sources\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::PointType origin;\n ConstantImageSourceType::SizeType size;\n ConstantImageSourceType::SpacingType spacing;\n\n ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();\n origin[0] = -127.;\n origin[1] = -127.;\n origin[2] = -127.;\n#if FAST_TESTS_NO_CHECKS\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n spacing[0] = 252.;\n spacing[1] = 252.;\n spacing[2] = 252.;\n#else\n size[0] = 64;\n size[1] = 64;\n size[2] = 64;\n spacing[0] = 4.;\n spacing[1] = 4.;\n spacing[2] = 4.;\n#endif\n tomographySource->SetOrigin( origin );\n tomographySource->SetSpacing( spacing );\n tomographySource->SetSize( size );\n tomographySource->SetConstant( 0. );\n\n ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();\n origin[0] = -255.;\n origin[1] = -255.;\n origin[2] = -255.;\n#if FAST_TESTS_NO_CHECKS\n size[0] = 2;\n size[1] = 2;\n size[2] = NumberOfProjectionImages;\n spacing[0] = 504.;\n spacing[1] = 504.;\n spacing[2] = 504.;\n#else\n size[0] = 64;\n size[1] = 64;\n size[2] = NumberOfProjectionImages;\n spacing[0] = 8.;\n spacing[1] = 8.;\n spacing[2] = 8.;\n#endif\n projectionsSource->SetOrigin( origin );\n projectionsSource->SetSpacing( spacing );\n projectionsSource->SetSize( size );\n projectionsSource->SetConstant( 0. );\n\n \/\/ Geometry object\n typedef rtk::ThreeDCircularProjectionGeometry GeometryType;\n GeometryType::Pointer geometry = GeometryType::New();\n for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)\n geometry->AddProjection(600., 1200., noProj*360.\/NumberOfProjectionImages);\n\n \/\/ Create ellipsoid PROJECTIONS\n typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;\n REIType::Pointer rei;\n\n rei = REIType::New();\n REIType::VectorType semiprincipalaxis, center;\n semiprincipalaxis.Fill(90.);\n center.Fill(0.);\n rei->SetAngle(0.);\n rei->SetDensity(1.);\n rei->SetCenter(center);\n rei->SetAxis(semiprincipalaxis);\n\n rei->SetInput( projectionsSource->GetOutput() );\n rei->SetGeometry( geometry );\n\n \/\/Update\n TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() );\n\n \/\/ Create REFERENCE object (3D ellipsoid).\n typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;\n DEType::Pointer dsl = DEType::New();\n dsl->SetInput( tomographySource->GetOutput() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )\n\n \/\/ Create the weights map\n ConstantImageSourceType::Pointer uniformWeightsSource = ConstantImageSourceType::New();\n uniformWeightsSource->SetInformationFromImage(projectionsSource->GetOutput());\n uniformWeightsSource->SetConstant(1.0);\n\n \/\/ Regularized CG reconstruction filter\n typedef rtk::RegularizedConjugateGradientConeBeamReconstructionFilter<OutputImageType> RegularizedCGType;\n RegularizedCGType::Pointer regularizedConjugateGradient = RegularizedCGType::New();\n regularizedConjugateGradient->SetInputVolume(tomographySource->GetOutput() );\n regularizedConjugateGradient->SetInputProjectionStack(rei->GetOutput());\n regularizedConjugateGradient->SetInputWeights( uniformWeightsSource->GetOutput());\n regularizedConjugateGradient->SetPreconditioned(false);\n regularizedConjugateGradient->SetGeometry( geometry );\n regularizedConjugateGradient->SetMainLoop_iterations( 2 );\n regularizedConjugateGradient->SetCudaConjugateGradient(false);\n\n regularizedConjugateGradient->SetGammaTV(1);\n regularizedConjugateGradient->SetTV_iterations( 3 );\n\n regularizedConjugateGradient->SetSoftThresholdWavelets(0.1);\n regularizedConjugateGradient->SetOrder(3);\n regularizedConjugateGradient->SetNumberOfLevels(3);\n\n \/\/ In all cases except CUDA, use the Joseph forward projector and Voxel-based back projector\n regularizedConjugateGradient->SetForwardProjectionFilter(0);\n regularizedConjugateGradient->SetBackProjectionFilter( 0 );\n\n std::cout << \"\\n\\n****** Case 1: Positivity + TV regularization ******\" << std::endl;\n\n regularizedConjugateGradient->SetPerformPositivity(true);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n std::cout << \"\\n\\n****** Case 2: Wavelets ******\" << std::endl;\n\n regularizedConjugateGradient->SetPerformPositivity(false);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n#ifdef USE_CUDA\n std::cout << \"\\n\\n****** Case 3: CUDA Voxel-Based Backprojector and CUDA Forward projector, all regularization steps on ******\" << std::endl;\n\n regularizedConjugateGradient->SetForwardProjectionFilter( 2 );\n regularizedConjugateGradient->SetBackProjectionFilter( 2 );\n regularizedConjugateGradient->SetCudaConjugateGradient(true);\n regularizedConjugateGradient->SetPerformPositivity(true);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n#endif\n\n std::cout << \"\\n\\n****** Image-domain sparsity ******\" << std::endl;\n\n \/\/ Replace the ellise with a very small one\n semiprincipalaxis.Fill(9.);\n rei->SetAxis(semiprincipalaxis);\n dsl->SetAxis(semiprincipalaxis);\n\n \/\/ Add gaussian noise on the projections\n typedef itk::AdditiveGaussianNoiseImageFilter<OutputImageType> GaussianNoiseFilterType;\n GaussianNoiseFilterType::Pointer gaussian = GaussianNoiseFilterType::New();\n gaussian->SetStandardDeviation(1);\n gaussian->SetMean(0.);\n gaussian->SetInput(rei->GetOutput());\n\n regularizedConjugateGradient->SetInputProjectionStack(gaussian->GetOutput());\n regularizedConjugateGradient->SetPerformPositivity(false);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformSoftThresholdOnImage(true);\n regularizedConjugateGradient->SetSoftThresholdOnImage(0.01);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.004, 47, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>COMP: In rtkregularizedconjugategradienttest.cxx, ignore the last test if ITK is too old (AdditiveGaussianNoiseImageFilter was added around version 4.5)<commit_after>#include \"rtkTest.h\"\n#include \"rtkDrawEllipsoidImageFilter.h\"\n#include \"rtkRayEllipsoidIntersectionImageFilter.h\"\n#include \"rtkConstantImageSource.h\"\n#include \"rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h\"\n\n#if ITK_VERSION_MAJOR > 4 || (ITK_VERSION_MAJOR == 4 && ITK_VERSION_MINOR >= 6)\n #include <itkAdditiveGaussianNoiseImageFilter.h>\n#endif\n\n#ifdef USE_CUDA\n #include \"itkCudaImage.h\"\n#endif\n\n\/**\n * \\file rtkregularizedconjugategradienttest.cxx\n *\n * \\brief Functional test for ADMMTotalVariation reconstruction\n *\n * This test generates the projections of an ellipsoid and reconstructs the CT\n * image using the ADMMTotalVariation algorithm with different backprojectors (Voxel-Based,\n * Joseph). The generated results are compared to the\n * expected results (analytical calculation).\n *\n * \\author Cyril Mory\n *\/\n\nint main(int, char** )\n{\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n#ifdef USE_CUDA\n typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n#endif\n\n#if FAST_TESTS_NO_CHECKS\n const unsigned int NumberOfProjectionImages = 3;\n#else\n const unsigned int NumberOfProjectionImages = 90;\n#endif\n\n \/\/ Constant image sources\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::PointType origin;\n ConstantImageSourceType::SizeType size;\n ConstantImageSourceType::SpacingType spacing;\n\n ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New();\n origin[0] = -127.;\n origin[1] = -127.;\n origin[2] = -127.;\n#if FAST_TESTS_NO_CHECKS\n size[0] = 2;\n size[1] = 2;\n size[2] = 2;\n spacing[0] = 252.;\n spacing[1] = 252.;\n spacing[2] = 252.;\n#else\n size[0] = 64;\n size[1] = 64;\n size[2] = 64;\n spacing[0] = 4.;\n spacing[1] = 4.;\n spacing[2] = 4.;\n#endif\n tomographySource->SetOrigin( origin );\n tomographySource->SetSpacing( spacing );\n tomographySource->SetSize( size );\n tomographySource->SetConstant( 0. );\n\n ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();\n origin[0] = -255.;\n origin[1] = -255.;\n origin[2] = -255.;\n#if FAST_TESTS_NO_CHECKS\n size[0] = 2;\n size[1] = 2;\n size[2] = NumberOfProjectionImages;\n spacing[0] = 504.;\n spacing[1] = 504.;\n spacing[2] = 504.;\n#else\n size[0] = 64;\n size[1] = 64;\n size[2] = NumberOfProjectionImages;\n spacing[0] = 8.;\n spacing[1] = 8.;\n spacing[2] = 8.;\n#endif\n projectionsSource->SetOrigin( origin );\n projectionsSource->SetSpacing( spacing );\n projectionsSource->SetSize( size );\n projectionsSource->SetConstant( 0. );\n\n \/\/ Geometry object\n typedef rtk::ThreeDCircularProjectionGeometry GeometryType;\n GeometryType::Pointer geometry = GeometryType::New();\n for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)\n geometry->AddProjection(600., 1200., noProj*360.\/NumberOfProjectionImages);\n\n \/\/ Create ellipsoid PROJECTIONS\n typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;\n REIType::Pointer rei;\n\n rei = REIType::New();\n REIType::VectorType semiprincipalaxis, center;\n semiprincipalaxis.Fill(90.);\n center.Fill(0.);\n rei->SetAngle(0.);\n rei->SetDensity(1.);\n rei->SetCenter(center);\n rei->SetAxis(semiprincipalaxis);\n\n rei->SetInput( projectionsSource->GetOutput() );\n rei->SetGeometry( geometry );\n\n \/\/Update\n TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() );\n\n \/\/ Create REFERENCE object (3D ellipsoid).\n typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;\n DEType::Pointer dsl = DEType::New();\n dsl->SetInput( tomographySource->GetOutput() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )\n\n \/\/ Create the weights map\n ConstantImageSourceType::Pointer uniformWeightsSource = ConstantImageSourceType::New();\n uniformWeightsSource->SetInformationFromImage(projectionsSource->GetOutput());\n uniformWeightsSource->SetConstant(1.0);\n\n \/\/ Regularized CG reconstruction filter\n typedef rtk::RegularizedConjugateGradientConeBeamReconstructionFilter<OutputImageType> RegularizedCGType;\n RegularizedCGType::Pointer regularizedConjugateGradient = RegularizedCGType::New();\n regularizedConjugateGradient->SetInputVolume(tomographySource->GetOutput() );\n regularizedConjugateGradient->SetInputProjectionStack(rei->GetOutput());\n regularizedConjugateGradient->SetInputWeights( uniformWeightsSource->GetOutput());\n regularizedConjugateGradient->SetPreconditioned(false);\n regularizedConjugateGradient->SetGeometry( geometry );\n regularizedConjugateGradient->SetMainLoop_iterations( 2 );\n regularizedConjugateGradient->SetCudaConjugateGradient(false);\n\n regularizedConjugateGradient->SetGammaTV(1);\n regularizedConjugateGradient->SetTV_iterations( 3 );\n\n regularizedConjugateGradient->SetSoftThresholdWavelets(0.1);\n regularizedConjugateGradient->SetOrder(3);\n regularizedConjugateGradient->SetNumberOfLevels(3);\n\n \/\/ In all cases except CUDA, use the Joseph forward projector and Voxel-based back projector\n regularizedConjugateGradient->SetForwardProjectionFilter(0);\n regularizedConjugateGradient->SetBackProjectionFilter( 0 );\n\n std::cout << \"\\n\\n****** Case 1: Positivity + TV regularization ******\" << std::endl;\n\n regularizedConjugateGradient->SetPerformPositivity(true);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n std::cout << \"\\n\\n****** Case 2: Wavelets ******\" << std::endl;\n\n regularizedConjugateGradient->SetPerformPositivity(false);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n#ifdef USE_CUDA\n std::cout << \"\\n\\n****** Case 3: CUDA Voxel-Based Backprojector and CUDA Forward projector, all regularization steps on ******\" << std::endl;\n\n regularizedConjugateGradient->SetForwardProjectionFilter( 2 );\n regularizedConjugateGradient->SetBackProjectionFilter( 2 );\n regularizedConjugateGradient->SetCudaConjugateGradient(true);\n regularizedConjugateGradient->SetPerformPositivity(true);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n#endif\n\n#if ITK_VERSION_MAJOR > 4 || (ITK_VERSION_MAJOR == 4 && ITK_VERSION_MINOR >= 6)\n std::cout << \"\\n\\n****** Image-domain sparsity ******\" << std::endl;\n\n \/\/ Replace the ellise with a very small one\n semiprincipalaxis.Fill(9.);\n rei->SetAxis(semiprincipalaxis);\n dsl->SetAxis(semiprincipalaxis);\n\n \/\/ Add gaussian noise on the projections\n typedef itk::AdditiveGaussianNoiseImageFilter<OutputImageType> GaussianNoiseFilterType;\n GaussianNoiseFilterType::Pointer gaussian = GaussianNoiseFilterType::New();\n gaussian->SetStandardDeviation(1);\n gaussian->SetMean(0.);\n gaussian->SetInput(rei->GetOutput());\n\n regularizedConjugateGradient->SetInputProjectionStack(gaussian->GetOutput());\n regularizedConjugateGradient->SetPerformPositivity(false);\n regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);\n regularizedConjugateGradient->SetPerformSoftThresholdOnImage(true);\n regularizedConjugateGradient->SetSoftThresholdOnImage(0.01);\n\n TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() );\n\n CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.004, 47, 2.0);\n std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n#endif\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mpi.h\"\n\nint main(int argc, char **argv) {\n\n MPI_Init(&argc, &argv);\n\n MPI_Finalize();\n\n return 0;\n}\n<commit_msg>[BROKEN] Fix style in init_test<commit_after>#include \"mpi.h\"\n\nint main(int argc, char **argv)\n{\n MPI_Init(&argc, &argv);\n\n MPI_Finalize();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#define START 0\n#define ENTRY 0\n\n#include \"timings.h\"\n#include <inttypes.h>\n\n#define START_NO 1000000000\n\n#include <libcpu.h>\n#include \"arch\/arm\/arm_types.h\"\n#include \"arch\/m88k\/m88k_isa.h\"\n\n#define RET_MAGIC 0x4D495354\n\nstatic void\ndebug_function(cpu_t *cpu) {\n\tfprintf(stderr, \"%s:%u\\n\", __FILE__, __LINE__);\n}\n\nint fib(int n)\n{\n int f2=0;\n int f1=1;\n int fib=0;\n int i;\n \n if (n==0 || n==1)\n return n;\n for(i=2;i<=n;i++){\n fib=f1+f2; \/*sum*\/\n f2=f1;\n f1=fib;\n }\n return fib;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define SINGLESTEP_NONE\t0\n#define SINGLESTEP_STEP\t1\n#define SINGLESTEP_BB\t2\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint\nmain(int argc, char **argv)\n{\n\tchar *s_arch;\n\tchar *executable;\n\tcpu_arch_t arch;\n\tcpu_t *cpu;\n\tuint8_t *RAM;\n\tFILE *f;\n\tint ramsize;\n\tint r1, r2;\n\tuint64_t t1, t2, t3, t4;\n\tunsigned start_no = START_NO;\n\n\tint singlestep = SINGLESTEP_NONE;\n\tint log = 1;\n\tint print_ir = 1;\n\n\t\/* parameter parsing *\/\n\tif (argc < 3) {\n\t\tprintf(\"Usage: %s executable [arch] [itercount] [entries]\\n\", argv[0]);\n\t\treturn 0;\n\t}\n\ts_arch = argv[1];\n\texecutable = argv[2];\n\tif (argc >= 4)\n\t\tstart_no = atoi(argv[3]);\n\tif (!strcmp(\"mips\", s_arch))\n\t\tarch = CPU_ARCH_MIPS;\n\telse if (!strcmp(\"m88k\", s_arch))\n\t\tarch = CPU_ARCH_M88K;\n\telse if (!strcmp(\"arm\", s_arch))\n\t\tarch = CPU_ARCH_ARM;\n\telse if (!strcmp(\"fapra\", s_arch))\n\t\tarch = CPU_ARCH_FAPRA;\n\telse {\n\t\tprintf(\"unknown architecture '%s'!\\n\", s_arch);\n\t\treturn 0;\n\t}\n\n\tramsize = 5*1024*1024;\n\tRAM = (uint8_t*)malloc(ramsize);\n\n\tcpu = cpu_new(arch, 0, 0);\n\n\tcpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);\n\tcpu_set_flags_debug(cpu, 0\n\t\t| (print_ir? CPU_DEBUG_PRINT_IR : 0)\n\t\t| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)\n\t\t| (log? CPU_DEBUG_LOG :0)\n\t\t| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP : 0)\n\t\t| (singlestep == SINGLESTEP_BB? CPU_DEBUG_SINGLESTEP_BB : 0)\n\t\t);\n\n\tcpu_set_ram(cpu, RAM);\n\t\n\t\/* load code *\/\n\tif (!(f = fopen(executable, \"rb\"))) {\n\t\tprintf(\"Could not open %s!\\n\", executable);\n\t\treturn 2;\n\t}\n\tcpu->code_start = START;\n\tcpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);\n\tfclose(f);\n\tcpu->code_entry = cpu->code_start + ENTRY;\n\n\tcpu_tag(cpu, cpu->code_entry);\n\n\tcpu_translate(cpu); \/* force translation now *\/\n\n\tprintf(\"\\n*** Executing...\\n\");\n\n\tprintf(\"number of iterations: %u\\n\", start_no);\n\n\tuint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;\n\tswitch (arch) {\n\t\tcase CPU_ARCH_M88K:\n\t\t\treg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;\n\t\t\treg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];\n\t\t\treg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];\n\t\t\treg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_MIPS:\n\t\t\treg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];\n\t\t\treg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];\n\t\t\treg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_ARM:\n\t\t\treg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];\n\t\t\treg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];\n\t\t\treg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_FAPRA:\n\t\t\treg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];\n\t\t\treg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];\n\t\t\treg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"architecture %u not handled.\\n\", arch);\n\t\t\texit(EXIT_FAILURE);\n\t}\n\n\t*reg_pc = cpu->code_entry;\n\t*reg_lr = RET_MAGIC;\n\t*reg_param = start_no;\n\n\tprintf(\"GUEST run...\"); fflush(stdout);\n\n\tt1 = abs_time();\n\tcpu_run(cpu, debug_function);\n\tt2 = abs_time();\n\tr1 = *reg_result;\n\n\tprintf(\"done!\\n\");\n\n\tprintf(\"HOST run...\"); fflush(stdout);\n\tt3 = abs_time();\n\tr2 = fib(start_no);\n\tt4 = abs_time();\n\tprintf(\"done!\\n\");\n\n cpu_free(cpu);\n\n\tprintf(\"Time GUEST: %\"PRId64\"\\n\", t2-t1);\n\tprintf(\"Time HOST: %\"PRId64\"\\n\", t4-t3);\n\tprintf(\"Result HOST: %d\\n\", r2);\n\tprintf(\"Result GUEST: %d\\n\", r1);\n\tprintf(\"GUEST required \\033[1m%.2f%%\\033[22m of HOST time.\\n\", (float)(t2-t1)\/(float)(t4-t3)*100);\n\tif (r1 == r2)\n\t\tprintf(\"\\033[1mSUCCESS!\\033[22m\\n\\n\");\n\telse\n\t\tprintf(\"\\033[1mFAILED!\\033[22m\\n\\n\");\n\n\treturn 0;\n}\n\/\/printf(\"%d\\n\", __LINE__);\n<commit_msg>fix build<commit_after>#define START 0\n#define ENTRY 0\n\n#include \"timings.h\"\n#include <inttypes.h>\n#include <cinttypes>\n\n#define START_NO 1000000000\n\n#include <libcpu.h>\n#include \"arch\/arm\/arm_types.h\"\n#include \"arch\/m88k\/m88k_isa.h\"\n\n#define RET_MAGIC 0x4D495354\n\nstatic void\ndebug_function(cpu_t *cpu) {\n\tfprintf(stderr, \"%s:%u\\n\", __FILE__, __LINE__);\n}\n\nint fib(int n)\n{\n int f2=0;\n int f1=1;\n int fib=0;\n int i;\n \n if (n==0 || n==1)\n return n;\n for(i=2;i<=n;i++){\n fib=f1+f2; \/*sum*\/\n f2=f1;\n f1=fib;\n }\n return fib;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define SINGLESTEP_NONE\t0\n#define SINGLESTEP_STEP\t1\n#define SINGLESTEP_BB\t2\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint\nmain(int argc, char **argv)\n{\n\tchar *s_arch;\n\tchar *executable;\n\tcpu_arch_t arch;\n\tcpu_t *cpu;\n\tuint8_t *RAM;\n\tFILE *f;\n\tint ramsize;\n\tint r1, r2;\n\tuint64_t t1, t2, t3, t4;\n\tunsigned start_no = START_NO;\n\n\tint singlestep = SINGLESTEP_NONE;\n\tint log = 1;\n\tint print_ir = 1;\n\n\t\/* parameter parsing *\/\n\tif (argc < 3) {\n\t\tprintf(\"Usage: %s executable [arch] [itercount] [entries]\\n\", argv[0]);\n\t\treturn 0;\n\t}\n\ts_arch = argv[1];\n\texecutable = argv[2];\n\tif (argc >= 4)\n\t\tstart_no = atoi(argv[3]);\n\tif (!strcmp(\"mips\", s_arch))\n\t\tarch = CPU_ARCH_MIPS;\n\telse if (!strcmp(\"m88k\", s_arch))\n\t\tarch = CPU_ARCH_M88K;\n\telse if (!strcmp(\"arm\", s_arch))\n\t\tarch = CPU_ARCH_ARM;\n\telse if (!strcmp(\"fapra\", s_arch))\n\t\tarch = CPU_ARCH_FAPRA;\n\telse {\n\t\tprintf(\"unknown architecture '%s'!\\n\", s_arch);\n\t\treturn 0;\n\t}\n\n\tramsize = 5*1024*1024;\n\tRAM = (uint8_t*)malloc(ramsize);\n\n\tcpu = cpu_new(arch, 0, 0);\n\n\tcpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);\n\tcpu_set_flags_debug(cpu, 0\n\t\t| (print_ir? CPU_DEBUG_PRINT_IR : 0)\n\t\t| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)\n\t\t| (log? CPU_DEBUG_LOG :0)\n\t\t| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP : 0)\n\t\t| (singlestep == SINGLESTEP_BB? CPU_DEBUG_SINGLESTEP_BB : 0)\n\t\t);\n\n\tcpu_set_ram(cpu, RAM);\n\t\n\t\/* load code *\/\n\tif (!(f = fopen(executable, \"rb\"))) {\n\t\tprintf(\"Could not open %s!\\n\", executable);\n\t\treturn 2;\n\t}\n\tcpu->code_start = START;\n\tcpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);\n\tfclose(f);\n\tcpu->code_entry = cpu->code_start + ENTRY;\n\n\tcpu_tag(cpu, cpu->code_entry);\n\n\tcpu_translate(cpu); \/* force translation now *\/\n\n\tprintf(\"\\n*** Executing...\\n\");\n\n\tprintf(\"number of iterations: %u\\n\", start_no);\n\n\tuint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;\n\tswitch (arch) {\n\t\tcase CPU_ARCH_M88K:\n\t\t\treg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;\n\t\t\treg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];\n\t\t\treg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];\n\t\t\treg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_MIPS:\n\t\t\treg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];\n\t\t\treg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];\n\t\t\treg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_ARM:\n\t\t\treg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];\n\t\t\treg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];\n\t\t\treg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];\n\t\t\tbreak;\n\t\tcase CPU_ARCH_FAPRA:\n\t\t\treg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;\n\t\t\treg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];\n\t\t\treg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];\n\t\t\treg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"architecture %u not handled.\\n\", arch);\n\t\t\texit(EXIT_FAILURE);\n\t}\n\n\t*reg_pc = cpu->code_entry;\n\t*reg_lr = RET_MAGIC;\n\t*reg_param = start_no;\n\n\tprintf(\"GUEST run...\"); fflush(stdout);\n\n\tt1 = abs_time();\n\tcpu_run(cpu, debug_function);\n\tt2 = abs_time();\n\tr1 = *reg_result;\n\n\tprintf(\"done!\\n\");\n\n\tprintf(\"HOST run...\"); fflush(stdout);\n\tt3 = abs_time();\n\tr2 = fib(start_no);\n\tt4 = abs_time();\n\tprintf(\"done!\\n\");\n\n cpu_free(cpu);\n\n\tprintf(\"Time GUEST: %\" PRId64 \"\\n\", t2-t1);\n\tprintf(\"Time HOST: %\" PRId64 \"\\n\", t4-t3);\n\tprintf(\"Result HOST: %d\\n\", r2);\n\tprintf(\"Result GUEST: %d\\n\", r1);\n\tprintf(\"GUEST required \\033[1m%.2f%%\\033[22m of HOST time.\\n\", (float)(t2-t1)\/(float)(t4-t3)*100);\n\tif (r1 == r2)\n\t\tprintf(\"\\033[1mSUCCESS!\\033[22m\\n\\n\");\n\telse\n\t\tprintf(\"\\033[1mFAILED!\\033[22m\\n\\n\");\n\n\treturn 0;\n}\n\/\/printf(\"%d\\n\", __LINE__);\n<|endoftext|>"} {"text":"<commit_before>#include <side.hh>\n\n#include <gtest\/gtest.h>\n\nusing namespace Rubik;\n\nnamespace SideData\n{\n const Side::Data top =\n {\n 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9,\n };\n const Side::Data bottom =\n {\n 9, 8, 7,\n 6, 5, 4,\n 3, 2, 1,\n };\n const Side::Data right =\n {\n 3, 6, 9,\n 2, 5, 8,\n 1, 4, 7,\n };\n const Side::Data left =\n {\n 7, 4, 1,\n 8, 5, 2,\n 9, 6, 3,\n };\n}\n\nTEST(Side, Initialize)\n{\n Side::Data data = {0};\n Orientation orientation = top(1).left(2).bottom(3).right(4);\n \n Side::Ptr side = Side::create(data, orientation);\n\n EXPECT_EQ(data, side->data());\n}\n\nclass PerspectiveData\n{\npublic:\n Side::Data top;\n Side::Data bottom;\n Side::Data left;\n Side::Data right;\n\npublic:\n PerspectiveData(Side::Data const& top, Side::Data const& bottom, Side::Data const& left, Side::Data const& right)\n :top(top), bottom(bottom), left(left), right(right)\n {}\n};\n\nstd::ostream& operator<<(std::ostream& os, PerspectiveData const& data)\n{\n os << std::endl;\n os << \"Top: \" << data.top ;\n os << \"Bottom: \" << data.bottom;\n os << \"Left: \" << data.left;\n os << \"Right: \" << data.right;\n return os;\n}\n\nclass SidePerspective : public testing::TestWithParam<PerspectiveData>\n{\nprotected:\n PerspectiveData const& data;\n Orientation const orientation;\n Side::Ptr const side;\n \npublic:\n SidePerspective()\n : data(GetParam()),\n orientation(top(1).left(2).bottom(3).right(4)),\n side(Side::create(data.top, orientation))\n {}\n};\n\nINSTANTIATE_TEST_CASE_P(Combinatorial, SidePerspective,\n testing::Values(PerspectiveData(SideData::top, SideData::bottom, SideData::left, SideData::right),\n PerspectiveData(SideData::left, SideData::right, SideData::bottom, SideData::top)\n ));\n \nTEST_P(SidePerspective, Top)\n{\n EXPECT_EQ(data.top, side->data(orientation.top()));\n}\n\nTEST_P(SidePerspective, Bottom)\n{\n EXPECT_EQ(data.bottom, side->data(orientation.bottom()));\n}\n\nTEST_P(SidePerspective, Right)\n{\n EXPECT_EQ(data.right, side->data(orientation.right()));\n}\n\nTEST_P(SidePerspective, Left)\n{\n EXPECT_EQ(data.left, side->data(orientation.left()));\n}\n\n<commit_msg>Refactor: Parametrize tests over Orientations<commit_after>#include <side.hh>\n\n#include <tuple>\n\n#include <gtest\/gtest.h>\n\nusing namespace Rubik;\n\nnamespace SideData\n{\n const Side::Data top =\n {\n 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9,\n };\n const Side::Data bottom =\n {\n 9, 8, 7,\n 6, 5, 4,\n 3, 2, 1,\n };\n const Side::Data right =\n {\n 3, 6, 9,\n 2, 5, 8,\n 1, 4, 7,\n };\n const Side::Data left =\n {\n 7, 4, 1,\n 8, 5, 2,\n 9, 6, 3,\n };\n}\n\nTEST(Side, Initialize)\n{\n Side::Data data = {0};\n Orientation orientation = top(1).left(2).bottom(3).right(4);\n \n Side::Ptr side = Side::create(data, orientation);\n\n EXPECT_EQ(data, side->data());\n}\n\nclass PerspectiveData\n{\npublic:\n Side::Data top;\n Side::Data bottom;\n Side::Data left;\n Side::Data right;\n\npublic:\n PerspectiveData()\n {}\n \n PerspectiveData(Side::Data const& top, Side::Data const& bottom, Side::Data const& left, Side::Data const& right)\n :top(top), bottom(bottom), left(left), right(right)\n {}\n};\n\nstd::ostream& operator<<(std::ostream& os, PerspectiveData const& data)\n{\n os << std::endl;\n os << \"Top: \" << data.top ;\n os << \"Bottom: \" << data.bottom;\n os << \"Left: \" << data.left;\n os << \"Right: \" << data.right;\n return os;\n}\n\nclass SidePerspective : public testing::TestWithParam<std::tr1::tuple<Orientation,PerspectiveData> >\n{\nprotected:\n Orientation const orientation;\n PerspectiveData const data;\n Side::Ptr const side;\n \npublic:\n SidePerspective()\n : orientation(std::tr1::get<0>(GetParam())),\n data(std::tr1::get<1>(GetParam())),\n side(Side::create(data.top, orientation))\n {}\n};\n\nINSTANTIATE_TEST_CASE_P\n(Combinatorial, SidePerspective,\n testing::Combine(\n testing::Values(top(1).left(2).bottom(3).right(4)),\n testing::Values(PerspectiveData(SideData::top, SideData::bottom, SideData::left, SideData::right),\n PerspectiveData(SideData::left, SideData::right, SideData::bottom, SideData::top)\n )));\n \nTEST_P(SidePerspective, Top)\n{\n EXPECT_EQ(data.top, side->data(orientation.top()));\n}\n\nTEST_P(SidePerspective, Bottom)\n{\n EXPECT_EQ(data.bottom, side->data(orientation.bottom()));\n}\n\nTEST_P(SidePerspective, Right)\n{\n EXPECT_EQ(data.right, side->data(orientation.right()));\n}\n\nTEST_P(SidePerspective, Left)\n{\n EXPECT_EQ(data.left, side->data(orientation.left()));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/file.hpp\"\n#include \"test.hpp\"\n#include <vector>\n#include <set>\n\nusing namespace libtorrent;\n\nint touch_file(std::string const& filename, int size)\n{\n\tusing namespace libtorrent;\n\n\tstd::vector<char> v;\n\tv.resize(size);\n\tfor (int i = 0; i < size; ++i)\n\t\tv[i] = i & 255;\n\n\tfile f;\n\terror_code ec;\n\tif (!f.open(filename, file::write_only, ec)) return -1;\n\tif (ec) return -1;\n\tfile::iovec_t b = {&v[0], v.size()};\n\tsize_type written = f.writev(0, &b, 1, ec);\n\tif (written != int(v.size())) return -3;\n\tif (ec) return -3;\n\treturn 0;\n}\n\nint test_main()\n{\n\terror_code ec;\n\n\tcreate_directory(\"file_test_dir\", ec);\n\tif (ec) fprintf(stderr, \"create_directory: %s\\n\", ec.message().c_str());\n\tTEST_CHECK(!ec);\n\n\tstd::string cwd = current_working_directory();\n\n\ttouch_file(combine_path(\"file_test_dir\", \"abc\"), 10);\n\ttouch_file(combine_path(\"file_test_dir\", \"def\"), 100);\n\ttouch_file(combine_path(\"file_test_dir\", \"ghi\"), 1000);\n\n\tstd::set<std::string> files;\n\tfor (directory i(\"file_test_dir\", ec); !i.done(); i.next(ec))\n\t{\n\t\tstd::string f = i.file();\n\t\tTEST_CHECK(files.count(f) == 0);\n\t\tfiles.insert(f);\n\t\tfprintf(stderr, \" %s\\n\", f.c_str());\n\t}\n\n\tTEST_CHECK(files.count(\"abc\") == 1);\n\tTEST_CHECK(files.count(\"def\") == 1);\n\tTEST_CHECK(files.count(\"ghi\") == 1);\n\tTEST_CHECK(files.count(\"..\") == 1);\n\tTEST_CHECK(files.count(\".\") == 1);\n\n\tremove_all(\"file_test_dir\", ec);\n\tif (ec) fprintf(stderr, \"create_directory: %s\\n\", ec.message().c_str());\n\n\treturn 0;\n}\n\n<commit_msg>expand file test<commit_after>\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/file.hpp\"\n#include \"test.hpp\"\n#include <vector>\n#include <set>\n\nusing namespace libtorrent;\n\nint touch_file(std::string const& filename, int size)\n{\n\tusing namespace libtorrent;\n\n\tstd::vector<char> v;\n\tv.resize(size);\n\tfor (int i = 0; i < size; ++i)\n\t\tv[i] = i & 255;\n\n\tfile f;\n\terror_code ec;\n\tif (!f.open(filename, file::write_only, ec)) return -1;\n\tif (ec) return -1;\n\tfile::iovec_t b = {&v[0], v.size()};\n\tsize_type written = f.writev(0, &b, 1, ec);\n\tif (written != int(v.size())) return -3;\n\tif (ec) return -3;\n\treturn 0;\n}\n\nint test_main()\n{\n\terror_code ec;\n\n\tcreate_directory(\"file_test_dir\", ec);\n\tif (ec) fprintf(stderr, \"create_directory: %s\\n\", ec.message().c_str());\n\tTEST_CHECK(!ec);\n\n\tstd::string cwd = current_working_directory();\n\n\ttouch_file(combine_path(\"file_test_dir\", \"abc\"), 10);\n\ttouch_file(combine_path(\"file_test_dir\", \"def\"), 100);\n\ttouch_file(combine_path(\"file_test_dir\", \"ghi\"), 1000);\n\n\tstd::set<std::string> files;\n\tfor (directory i(\"file_test_dir\", ec); !i.done(); i.next(ec))\n\t{\n\t\tstd::string f = i.file();\n\t\tTEST_CHECK(files.count(f) == 0);\n\t\tfiles.insert(f);\n\t\tfprintf(stderr, \" %s\\n\", f.c_str());\n\t}\n\n\tTEST_CHECK(files.count(\"abc\") == 1);\n\tTEST_CHECK(files.count(\"def\") == 1);\n\tTEST_CHECK(files.count(\"ghi\") == 1);\n\tTEST_CHECK(files.count(\"..\") == 1);\n\tTEST_CHECK(files.count(\".\") == 1);\n\tfiles.clear();\n\n\trecursive_copy(\"file_test_dir\", \"file_test_dir2\", ec);\n\n\tfor (directory i(\"file_test_dir2\", ec); !i.done(); i.next(ec))\n\t{\n\t\tstd::string f = i.file();\n\t\tTEST_CHECK(files.count(f) == 0);\n\t\tfiles.insert(f);\n\t\tfprintf(stderr, \" %s\\n\", f.c_str());\n\t}\n\n\tremove_all(\"file_test_dir\", ec);\n\tif (ec) fprintf(stderr, \"remove_all: %s\\n\", ec.message().c_str());\n\tremove_all(\"file_test_dir2\", ec);\n\tif (ec) fprintf(stderr, \"remove_all: %s\\n\", ec.message().c_str());\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\nhttps:\/\/github.com\/ETLCPP\/etl\nhttp:\/\/www.etlcpp.com\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <string>\n#include <vector>\n#include <stdint.h>\n\n#include \"..\/hash.h\"\n\nnamespace\n{\n SUITE(test_hash)\n {\n \/\/*************************************************************************\n TEST(test_hash_bool)\n {\n size_t hash = etl::hash<bool>()(false);\n CHECK_EQUAL(0, hash);\n\n hash = etl::hash<bool>()(true);\n CHECK_EQUAL(1, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_char)\n {\n size_t hash = etl::hash<char>()((char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_signed_char)\n {\n size_t hash = etl::hash<signed char>()((signed char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_char)\n {\n size_t hash = etl::hash<unsigned char>()((unsigned char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_short)\n {\n size_t hash = etl::hash<short>()((short)(0x5AA5));\n\n CHECK_EQUAL(0x5AA5, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_short)\n {\n size_t hash = etl::hash<unsigned short>()((unsigned short)(0x5AA5));\n\n CHECK_EQUAL(0x5AA5, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_int)\n {\n size_t hash = etl::hash<int>()((int)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_int)\n {\n size_t hash = etl::hash<unsigned int>()((unsigned int)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_long)\n {\n size_t hash = etl::hash<long>()((long)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_long)\n {\n size_t hash = etl::hash<unsigned long>()((unsigned long)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_long_long)\n {\n size_t hash = etl::hash<long long>()((long long)(0x5AA555AA3CC333CC));\n\n CHECK_EQUAL(0xEC6A8D69, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_long_long)\n {\n size_t hash = etl::hash<unsigned long long>()((unsigned long long)(0x5AA555AA3CC333CC));\n\n CHECK_EQUAL(0xEC6A8D69, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_float)\n {\n size_t hash = etl::hash<float>()((float)(1.2345));\n\n CHECK_EQUAL(0x3F9E0419, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_double)\n {\n size_t hash = etl::hash<double>()((double)(1.2345));\n\n CHECK_EQUAL(0x86FBF224, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_pointer)\n {\n int i;\n size_t hash = etl::hash<int*>()(&i);\n\n CHECK_EQUAL(size_t(&i), hash);\n }\n };\n}\n\n<commit_msg>Modified for 64 bit 'size_t' compatibilty<commit_after>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\nhttps:\/\/github.com\/ETLCPP\/etl\nhttp:\/\/www.etlcpp.com\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <string>\n#include <vector>\n#include <stdint.h>\n\n#include \"..\/hash.h\"\n\nnamespace\n{\n SUITE(test_hash)\n {\n \/\/*************************************************************************\n TEST(test_hash_bool)\n {\n size_t hash = etl::hash<bool>()(false);\n CHECK_EQUAL(0, hash);\n\n hash = etl::hash<bool>()(true);\n CHECK_EQUAL(1, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_char)\n {\n size_t hash = etl::hash<char>()((char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_signed_char)\n {\n size_t hash = etl::hash<signed char>()((signed char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_char)\n {\n size_t hash = etl::hash<unsigned char>()((unsigned char)(0x5A));\n\n CHECK_EQUAL(0x5A, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_short)\n {\n size_t hash = etl::hash<short>()((short)(0x5AA5));\n\n CHECK_EQUAL(0x5AA5, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_short)\n {\n size_t hash = etl::hash<unsigned short>()((unsigned short)(0x5AA5));\n\n CHECK_EQUAL(0x5AA5, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_int)\n {\n size_t hash = etl::hash<int>()((int)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_int)\n {\n size_t hash = etl::hash<unsigned int>()((unsigned int)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_long)\n {\n size_t hash = etl::hash<long>()((long)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_long)\n {\n size_t hash = etl::hash<unsigned long>()((unsigned long)(0x5AA555AA));\n\n CHECK_EQUAL(0x5AA555AA, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_long_long)\n {\n size_t hash = etl::hash<long long>()((long long)(0x5AA555AA3CC333CC));\n\n if (sizeof(size_t) == sizeof(long long))\n CHECK_EQUAL(0x5AA555AA3CC333CC, hash);\n else\n CHECK_EQUAL(0xEC6A8D69, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_unsigned_long_long)\n {\n size_t hash = etl::hash<unsigned long long>()((unsigned long long)(0x5AA555AA3CC333CC));\n\n if (sizeof(size_t) == sizeof(unsigned long long))\n CHECK_EQUAL(0x5AA555AA3CC333CC, hash);\n else\n CHECK_EQUAL(0xEC6A8D69, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_float)\n {\n size_t hash = etl::hash<float>()((float)(1.2345));\n\n if (sizeof(size_t) == sizeof(long long))\n CHECK_EQUAL(0x884B5E3F478AF88F, hash);\n else\n CHECK_EQUAL(0x3F9E0419, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_double)\n {\n size_t hash = etl::hash<double>()((double)(1.2345));\n\n if (sizeof(size_t) == sizeof(long long))\n CHECK_EQUAL(0x3FF3C083126E978D, hash);\n else\n CHECK_EQUAL(0x86FBF224, hash);\n }\n\n \/\/*************************************************************************\n TEST(test_hash_pointer)\n {\n int i;\n size_t hash = etl::hash<int*>()(&i);\n\n CHECK_EQUAL(size_t(&i), hash);\n }\n };\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"libtorrent\/upnp.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/ref.hpp>\n#include <boost\/intrusive_ptr.hpp>\n\nusing namespace libtorrent;\n\nvoid callback(int tcp, int udp, std::string const& err)\n{\n\tstd::cerr << \"tcp: \" << tcp << \", udp: \" << udp << \", error: \\\"\" << err << \"\\\"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n\tio_service ios;\n\tstd::string user_agent = \"test agent\";\n\n\tif (argc != 3)\n\t{\n\t\tstd::cerr << \"usage: \" << argv[0] << \" tcp-port udp-port\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tconnection_queue cc(ios);\n\tboost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback);\n\n\tdeadline_timer timer(ios);\n\ttimer.expires_from_now(seconds(2));\n\ttimer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));\n\n\tstd::cerr << \"broadcasting for UPnP device\" << std::endl;\n\n\tios.reset();\n\tios.run();\n\n\tupnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2]));\n\ttimer.expires_from_now(seconds(5));\n\ttimer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));\n\tstd::cerr << \"mapping ports TCP: \" << argv[1]\n\t\t<< \" UDP: \" << argv[2] << std::endl;\n\n\tios.reset();\n\tios.run();\n\tstd::cerr << \"removing mappings\" << std::endl;\n\tupnp_handler->close();\n\n\tios.reset();\n\tios.run();\n\tstd::cerr << \"closing\" << std::endl;\n}\n\n\n<commit_msg>fixed test_upnp<commit_after>#include \"libtorrent\/upnp.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/ref.hpp>\n#include <boost\/intrusive_ptr.hpp>\n\nusing namespace libtorrent;\n\nvoid callback(int tcp, int udp, std::string const& err)\n{\n\tstd::cerr << \"tcp: \" << tcp << \", udp: \" << udp << \", error: \\\"\" << err << \"\\\"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n\tio_service ios;\n\tstd::string user_agent = \"test agent\";\n\n\tif (argc != 3)\n\t{\n\t\tstd::cerr << \"usage: \" << argv[0] << \" tcp-port udp-port\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tconnection_queue cc(ios);\n\tboost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback);\n\tupnp_handler->discover_device();\n\n\tdeadline_timer timer(ios);\n\ttimer.expires_from_now(seconds(2));\n\ttimer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));\n\n\tstd::cerr << \"broadcasting for UPnP device\" << std::endl;\n\n\tios.reset();\n\tios.run();\n\n\tupnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2]));\n\ttimer.expires_from_now(seconds(5));\n\ttimer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));\n\tstd::cerr << \"mapping ports TCP: \" << argv[1]\n\t\t<< \" UDP: \" << argv[2] << std::endl;\n\n\tios.reset();\n\tios.run();\n\tstd::cerr << \"router: \" << upnp_handler->router_model() << std::endl;\n\tstd::cerr << \"removing mappings\" << std::endl;\n\tupnp_handler->close();\n\n\tios.reset();\n\tios.run();\n\tstd::cerr << \"closing\" << std::endl;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n Filename:\n main.cpp\n Author:\n Vincent Heins \/ TheMysteriousVincent\n Description:\n Tests the functionality of the first layer for receiving input data.\n*\/\n\n#include <iostream>\n#include <string.h>\n#include <map>\n#include \"handler.h\"\n#include <thread>\n#include <chrono>\n#include <ctime>\n\nHandler *hndl = new Handler();\n\nvoid makeRequest() {\n char *output = new char[8192];\n int outputSize = 8192;\n const char *function = \"SENDRQ\";\n const char *args[12];\n const char *tmp1 = \"\\\"#url\\\"\";\n const char *tmp2 = \"\\\"https:\/\/httpbins.org\/post\\\"\";\n const char *tmp3 = \"\\\"#postData\\\"\";\n const char *tmp4 = \"\\\"{\\\"test\\\":2}\\\"\";\n const char *tmp5 = \"\\\"\\\"\";\n const char *tmp6 = \"\\\"\\\"\";\n const char *tmp7 = \"\\\"#jsonToArray\\\"\";\n const char *tmp8 = \"\\\"#headers\\\"\";\n const char *tmp9 = \"\\\"Content-Type\\\"\";\n const char *tmp10 = \"\\\"application\/json\\\"\";\n const char *tmp11 = \"\\\"#timeout\\\"\";\n const char *tmp12 = \"\\\"10\\\"\";\n args[0] = tmp1;\n args[1] = tmp2;\n args[2] = tmp3;\n args[3] = tmp4;\n args[4] = tmp5;\n args[5] = tmp6;\n args[6] = tmp7;\n args[7] = tmp8;\n args[8] = tmp9;\n args[9] = tmp10;\n args[10] = tmp11;\n args[11] = tmp12;\n\n hndl->CallExtensionArgs(output, outputSize, function, args, 12);\n\n std::this_thread::sleep_for(std::chrono::seconds(1));\n\n auto start = std::chrono::high_resolution_clock::now();\n const char *args2[1];\n args2[0] = std::string(output).c_str();\n std::cout << args2[0] << std::endl;\n hndl->CallExtensionArgs(output, outputSize, \"GETRQ\", args2, 1);\n args2[0] = std::string(output).c_str();\n std::cout << args2[0] << std::endl;\n auto finish = std::chrono::high_resolution_clock::now();\n std::cout << \"Time Results:\" << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << std::endl << \"---\" << std::endl;\n\n std::cout << output << std::endl;\n}\n\nint main() {\n makeRequest();\n return 0;\n}\n<commit_msg>update test<commit_after>\n\/*\n Filename:\n main.cpp\n Author:\n Vincent Heins \/ TheMysteriousVincent\n Description:\n Tests the functionality of the first layer for receiving input data.\n*\/\n\n#include <iostream>\n#include <string.h>\n#include <map>\n#include \"handler.h\"\n#include <thread>\n#include <chrono>\n#include <ctime>\n\nHandler *hndl = new Handler();\n\nvoid makeRequest() {\n char *output = new char[8192];\n int outputSize = 8192;\n const char *function = \"SENDRQ\";\n const char *args[12];\n const char *tmp1 = \"\\\"#url\\\"\";\n const char *tmp2 = \"\\\"https:\/\/httpbins.org\/delay\/10\\\"\";\n const char *tmp3 = \"\\\"#postData\\\"\";\n const char *tmp4 = \"\\\"{\\\"test\\\":2}\\\"\";\n const char *tmp5 = \"\\\"\\\"\";\n const char *tmp6 = \"\\\"\\\"\";\n const char *tmp7 = \"\\\"#jsonToArray\\\"\";\n const char *tmp8 = \"\\\"#headers\\\"\";\n const char *tmp9 = \"\\\"Content-Type\\\"\";\n const char *tmp10 = \"\\\"application\/json\\\"\";\n const char *tmp11 = \"\\\"#timeout\\\"\";\n const char *tmp12 = \"\\\"5\\\"\";\n args[0] = tmp1;\n args[1] = tmp2;\n args[2] = tmp3;\n args[3] = tmp4;\n args[4] = tmp5;\n args[5] = tmp6;\n args[6] = tmp7;\n args[7] = tmp8;\n args[8] = tmp9;\n args[9] = tmp10;\n args[10] = tmp11;\n args[11] = tmp12;\n\n hndl->CallExtensionArgs(output, outputSize, function, args, 12);\n\n std::this_thread::sleep_for(std::chrono::seconds(1));\n\n auto start = std::chrono::high_resolution_clock::now();\n const char *args2[1];\n args2[0] = std::string(output).c_str();\n std::cout << args2[0] << std::endl;\n hndl->CallExtensionArgs(output, outputSize, \"GETRQ\", args2, 1);\n args2[0] = std::string(output).c_str();\n std::cout << args2[0] << std::endl;\n auto finish = std::chrono::high_resolution_clock::now();\n std::cout << \"Time Results:\" << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << std::endl << \"---\" << std::endl;\n\n std::cout << output << std::endl;\n}\n\nint main() {\n makeRequest();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2017 Cory Sherman\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n#include \"gtest\/gtest.h\"\n\n#include \"cgs\/meta.hpp\"\nusing cgs::is_constexpr;\n\nconstexpr int safe_v() { return 0; }\nconstexpr int safe_p(void*) { return 0; }\nconstexpr int safe_fi(float, int) { return 0; }\n\n\/\/ constexpr if i != 0\nconstexpr int safe_if_nonzero(int i)\n{\n if(i == 0) {\n throw i;\n }\n return i;\n}\n\n\/\/ constexpr if i == 0\nconstexpr int safe_if_zero(int i)\n{\n if(i != 0) {\n throw i;\n }\n return i;\n}\n\nint unsafe_v()\n{\n throw 0;\n}\n\nint unsafe_i(int i)\n{\n throw 0;\n}\n\nTEST(Meta, IsConstexpr)\n{\n EXPECT_TRUE( (is_constexpr<safe_v>()) );\n EXPECT_TRUE( (is_constexpr<safe_p>(nullptr)) );\n EXPECT_TRUE( (is_constexpr<safe_fi>(0.0f, 0)) );\n\n EXPECT_FALSE( (is_constexpr<unsafe_v>()) );\n EXPECT_FALSE( (is_constexpr<safe_if_nonzero>(0)) );\n\n \/\/ can also check at compile time\n static_assert(is_constexpr<safe_fi>(0.0f, 0));\n static_assert(!is_constexpr<unsafe_v>());\n}\n\nTEST(Meta, IsConstexprSafeIfZero)\n{\n \/\/ false positive for is_constexpr<safe_if_zero>\n \/\/\n \/\/ We pass default constructed arguments,\n \/\/ so we are testing if unsafe_inot(0), which IS constexpr,\n \/\/ even though unsafe_inot is not generally constexpr\n \/\/ see GitHub issue #1\n \/\/\n \/\/ I don't think it is possible to test if a function is generally constexpr.\n \/\/\n \/\/ It might be possible check if Func is constexpr with provided values.\n \/\/ I haven't figured it out yet.\n\n EXPECT_FALSE( (is_constexpr<safe_if_zero>(0)) );\n}\n<commit_msg>add direct test cases for issue #1<commit_after>\/*\n Copyright 2017 Cory Sherman\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n#include \"gtest\/gtest.h\"\n\n#include \"cgs\/meta.hpp\"\nusing cgs::is_constexpr;\n\nconstexpr int safe_v() { return 0; }\nconstexpr int safe_p(void*) { return 0; }\nconstexpr int safe_fi(float, int) { return 0; }\n\n\/\/ constexpr if i != 0\nconstexpr int safe_if_nonzero(int i)\n{\n if(i == 0) {\n throw i;\n }\n return i;\n}\n\n\/\/ constexpr if i == 0\nconstexpr int safe_if_zero(int i)\n{\n if(i != 0) {\n throw i;\n }\n return i;\n}\n\nint unsafe_v()\n{\n throw 0;\n}\n\nint unsafe_i(int i)\n{\n throw 0;\n}\n\nTEST(Meta, IsConstexpr)\n{\n EXPECT_TRUE( (is_constexpr<safe_v>()) );\n EXPECT_TRUE( (is_constexpr<safe_p>(nullptr)) );\n EXPECT_TRUE( (is_constexpr<safe_fi>(0.0f, 0)) );\n\n EXPECT_FALSE( (is_constexpr<unsafe_v>()) );\n EXPECT_FALSE( (is_constexpr<safe_if_nonzero>(0)) );\n\n \/\/ can also check at compile time\n static_assert(is_constexpr<safe_fi>(0.0f, 0));\n static_assert(!is_constexpr<unsafe_v>());\n}\n\nTEST(Meta, IsConstexprNonDefault)\n{\n \/\/ false results for is_constexpr, when the parameter values effect constexpr-ness\n \/\/\n \/\/ We pass default constructed arguments,\n \/\/ so we are testing if unsafe_inot(0), which IS constexpr,\n \/\/ even though unsafe_inot is not generally constexpr\n \/\/ see GitHub issue #1\n \/\/\n \/\/ I don't think it is possible to test if a function is generally constexpr.\n \/\/\n \/\/ It might be possible check if Func is constexpr with provided values.\n \/\/ I haven't figured it out yet.\n\n EXPECT_TRUE( (is_constexpr<safe_if_nonzero>(5)) );\n EXPECT_FALSE( (is_constexpr<safe_if_zero>(5)) );\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief wasteTime() implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-11-04\n *\/\n\n#include \"wasteTime.hpp\"\n\nnamespace distortos\n{\n\nnamespace test\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid wasteTime(const TickClock::duration duration)\n{\n\t\/\/\/ \\todo implementat something more precise and reliable\n\tfor (TickClock::duration d {}; d <= duration; ++d)\n\t\twasteTime(TickClock::now() + decltype(duration){1});\n}\n\nvoid wasteTime(const TickClock::time_point timePoint)\n{\n\twhile (timePoint > TickClock::now());\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<commit_msg>test: comment fix in wasteTime()<commit_after>\/**\n * \\file\n * \\brief wasteTime() implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-11-06\n *\/\n\n#include \"wasteTime.hpp\"\n\nnamespace distortos\n{\n\nnamespace test\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid wasteTime(const TickClock::duration duration)\n{\n\t\/\/\/ \\todo implement something more precise and reliable\n\tfor (TickClock::duration d {}; d <= duration; ++d)\n\t\twasteTime(TickClock::now() + decltype(duration){1});\n}\n\nvoid wasteTime(const TickClock::time_point timePoint)\n{\n\twhile (timePoint > TickClock::now());\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <iostream>\n#include \"sslpkix\/sslpkix.h\"\n\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\nstatic void rsa_callback(int p, int n, void *arg) {\n\t(void)n;\n\t(void)arg;\n\tchar c;\n\tswitch (p) {\n\t\tdefault: c = 'B'; break;\n\t\tcase 0: c = '.'; break;\n\t\tcase 1: c = '+'; break;\n\t\tcase 2: c = '*'; break;\n\t\tcase 3: c = '\\n'; break;\n\t}\n\tfputc(c, stderr);\n}\n\nTEST_CASE(\"certificate\/creation\/1\", \"Certificate creation\")\n{\n\t\/\/\n\t\/\/ Create issuer\n\t\/\/\n\n\tsslpkix::CertificateName issuer;\n\tREQUIRE(issuer.create());\n\tREQUIRE(issuer.set_common_name(\"janeroe.example.com\"));\n\tREQUIRE(issuer.set_email(\"jane.roe@example.com\"));\n\tREQUIRE(issuer.set_country(\"US\"));\n\tREQUIRE(issuer.set_state(\"CA\"));\n\tREQUIRE(issuer.set_locality(\"Palo Alto\"));\n\tREQUIRE(issuer.set_organization(\"Jane Roe's CA Pty.\"));\n\n\t\/\/\n\t\/\/ Create subject\n\t\/\/\n\n\tsslpkix::CertificateName subject;\n\tREQUIRE(subject.create());\n\tREQUIRE(subject.set_common_name(\"johndoe.example.com\"));\n\tREQUIRE(subject.set_email(\"john.doe@example.com\"));\n\tREQUIRE(subject.set_country(\"BR\"));\n\tREQUIRE(subject.set_state(\"RS\"));\n\tREQUIRE(subject.set_locality(\"Porto Alegre\"));\n\tREQUIRE(subject.set_organization(\"John Doe's Company Pty.\"));\n\n\t\/\/\n\t\/\/ Add a custom extensions - This is not required.\n\t\/\/\n\n\tint nid;\n\tconst char *oid = \"1.2.3.4.5.31\";\n\tconst char *short_name = \"CTE\";\n\tconst char *long_name = \"customTextEntry\";\n\tconst char *value = \"Some value here\";\n\tREQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));\n\tREQUIRE(subject.add_entry(short_name, value));\n\tREQUIRE(subject.entry_value(nid) == value);\n\n\t\/\/\n\t\/\/ Generate the key pair\n\t\/\/\n\n\tsslpkix::PrivateKey key;\n\tREQUIRE(key.create());\n\tRSA *rsa_key = RSA_generate_key(1024, RSA_F4, rsa_callback, NULL);\n\tREQUIRE(rsa_key != NULL);\n\tREQUIRE(key.copy(rsa_key));\n\tRSA_free(rsa_key);\n\trsa_key = NULL;\n\n\tsslpkix::FileSink key_file;\n\tREQUIRE(key_file.open(\"JohnDoe.key\", \"wb\"));\n\tREQUIRE(key.save(key_file));\n\tkey_file.close();\n\n\t\/\/\n\t\/\/ Create the certificate\n\t\/\/\n\n\tsslpkix::Certificate cert;\n\tREQUIRE(cert.create());\n\n\t\/\/ Adjust version\n\tREQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));\n\n\t\/\/ Adjust keys\n\tREQUIRE(cert.set_pubkey(key));\n\n\t\/\/ Use a hardcoded serial - Never do this in production code!\n\tREQUIRE(cert.set_serial(31337L));\n\n\t\/\/ Adjust issuer and subject\n\tREQUIRE(cert.set_issuer(issuer));\n\tREQUIRE(cert.set_subject(subject));\n\n\t\/\/ Valid for 5 days from now\n\tREQUIRE(cert.set_valid_since(0));\n\tREQUIRE(cert.set_valid_until(5));\n\n\t\/\/ Self-sign this certificate\n\tREQUIRE(cert.sign(key));\n\n\t\/\/ Save it\n\tsslpkix::FileSink cert_file;\n\tREQUIRE(cert_file.open(\"JohnDoe.crt\", \"wb\"));\n\tREQUIRE(cert.save(cert_file));\n\tcert_file.close();\n}\n\nTEST_CASE(\"iosink\/operators\", \"IoSink operators\")\n{\n\tsslpkix::FileSink cert_file;\n\tREQUIRE(cert_file.open(\"JohnDoe.crt\", \"rb\"));\n\tstd::string cert_string;\n\tcert_file >> cert_string; \/\/ IoSink to std::string\n\t\/\/std::cout << cert_string << std::endl;\n\tcert_file.close();\n\t\/\/ TODO(jweyrich): Test whether operator>> was successful. How?\n\n\tstd::stringstream sstream;\n\n\tsslpkix::MemorySink cert_mem;\n\tREQUIRE(cert_mem.open_rw());\n\tcert_mem << cert_string; \/\/ std::string to IoSink\n\tsstream << cert_mem; \/\/ IoSink to std::stringstream\n\tcert_mem.close();\n\tREQUIRE(sstream.str() == cert_string);\n\n\t\/\/ Reset the stringstream\n\tsstream.str(std::string());\n\n\tsslpkix::MemorySink key_mem;\n\tREQUIRE(key_mem.open_rw());\n\tstd::filebuf fbuf;\n\tfbuf.open(\"JohnDoe.key\", std::ios::in);\n\tstd::istream istream(&fbuf);\n\tistream >> key_mem; \/\/ std::istream to IoSink\n\tstd::string key_string;\n\tkey_mem >> key_string; \/\/ IoSink to std::string\n\t\/\/std::cout << key_string << std::endl;\n\n\tistream.clear(); \/\/ Clear EOF flag (required before C++11)\n\tistream.seekg(0); \/\/ Rewind the std::iostream\n\tsstream << istream.rdbuf(); \/\/ std::istream to std::stringstream\n\t\/\/std::cout << sstream.str() << std::endl;\n\n\tREQUIRE(sstream.str() == key_string);\n\n\tfbuf.close();\n\tkey_mem.close();\n}\n\nTEST_CASE(\"certificate_name\/entries\", \"CertificateName entries\")\n{\n\tsslpkix::CertificateName name;\n\tREQUIRE(name.create());\n\tREQUIRE(name.set_common_name(\"John Doe\"));\n\tREQUIRE(name.common_name() == \"John Doe\");\n\tREQUIRE(name.set_country(\"BR\"));\n\tREQUIRE(name.country() == \"BR\");\n\tREQUIRE(name.set_email(\"john.doe@example.com\"));\n\tREQUIRE(name.email() == \"john.doe@example.com\");\n\tREQUIRE(name.set_locality(\"Sao Paulo\"));\n\tREQUIRE(name.locality() == \"Sao Paulo\");\n\tREQUIRE(name.set_organization(\"Independent\"));\n\tREQUIRE(name.organization() == \"Independent\");\n\tREQUIRE(name.set_state(\"SP\"));\n\tREQUIRE(name.state() == \"SP\");\n}\n\nTEST_CASE(\"key\/generation\/rsa\", \"RSA key generation\")\n{\n\tsslpkix::PrivateKey key;\n\tREQUIRE(key.create());\n\tRSA *rsa_key = RSA_generate_key(512, RSA_F4, rsa_callback, NULL);\n\tREQUIRE(rsa_key != NULL);\n\tREQUIRE(key.copy(rsa_key));\n\tRSA_free(rsa_key);\n\trsa_key = NULL;\n}\n\nTEST_CASE(\"certificate_name\/extensions\", \"CertificateName extension\")\n{\n\tint nid;\n\tconst char *oid = \"1.2.3.4.5.31\";\n\tconst char *short_name = \"CTE\";\n\tconst char *long_name = \"customTextEntry\";\n\tconst char *value = \"Some value here\";\n\n\tREQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));\n\tsslpkix::CertificateName name;\n\tREQUIRE(name.create());\n\tREQUIRE(name.add_entry(short_name, value));\n\tint index;\n\tREQUIRE((index = name.find_entry(nid)) != -1);\n\tREQUIRE(name.entry(index) != NULL);\n\tREQUIRE(name.entry_count() == 1);\n\tREQUIRE(name.entry_value(nid) == value);\n}\n\nint main(int argc, char *const argv[])\n{\n\tbool success = sslpkix::startup();\n\tif (!success) {\n\t\tstd::cerr << \"ERROR: Failed to initialize SSLPKIX.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint result = Catch::Session().run(argc, argv);\n\n\tsslpkix::shutdown();\n\n\treturn result;\n}\n<commit_msg>Replace deprecated RSA_generate_key by RSA_generate_key_ex.<commit_after>#include <cstdlib>\n#include <iostream>\n#include \"sslpkix\/sslpkix.h\"\n\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\nstatic void rsa_callback(int p, int n, void *arg) {\n\t(void)n;\n\t(void)arg;\n\tchar c;\n\tswitch (p) {\n\t\tdefault: c = 'B'; break;\n\t\tcase 0: c = '.'; break;\n\t\tcase 1: c = '+'; break;\n\t\tcase 2: c = '*'; break;\n\t\tcase 3: c = '\\n'; break;\n\t}\n\tfputc(c, stderr);\n}\n\nTEST_CASE(\"certificate\/creation\/1\", \"Certificate creation\")\n{\n\t\/\/\n\t\/\/ Create issuer\n\t\/\/\n\n\tsslpkix::CertificateName issuer;\n\tREQUIRE(issuer.create());\n\tREQUIRE(issuer.set_common_name(\"janeroe.example.com\"));\n\tREQUIRE(issuer.set_email(\"jane.roe@example.com\"));\n\tREQUIRE(issuer.set_country(\"US\"));\n\tREQUIRE(issuer.set_state(\"CA\"));\n\tREQUIRE(issuer.set_locality(\"Palo Alto\"));\n\tREQUIRE(issuer.set_organization(\"Jane Roe's CA Pty.\"));\n\n\t\/\/\n\t\/\/ Create subject\n\t\/\/\n\n\tsslpkix::CertificateName subject;\n\tREQUIRE(subject.create());\n\tREQUIRE(subject.set_common_name(\"johndoe.example.com\"));\n\tREQUIRE(subject.set_email(\"john.doe@example.com\"));\n\tREQUIRE(subject.set_country(\"BR\"));\n\tREQUIRE(subject.set_state(\"RS\"));\n\tREQUIRE(subject.set_locality(\"Porto Alegre\"));\n\tREQUIRE(subject.set_organization(\"John Doe's Company Pty.\"));\n\n\t\/\/\n\t\/\/ Add a custom extensions - This is not required.\n\t\/\/\n\n\tint nid;\n\tconst char *oid = \"1.2.3.4.5.31\";\n\tconst char *short_name = \"CTE\";\n\tconst char *long_name = \"customTextEntry\";\n\tconst char *value = \"Some value here\";\n\tREQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));\n\tREQUIRE(subject.add_entry(short_name, value));\n\tREQUIRE(subject.entry_value(nid) == value);\n\n\t\/\/\n\t\/\/ Generate the key pair\n\t\/\/\n\n\tsslpkix::PrivateKey key;\n\tREQUIRE(key.create());\n\tRSA *rsa_keypair = RSA_new();\n\tREQUIRE(rsa_keypair != NULL);\n\tBIGNUM *f4 = BN_new();\n\tREQUIRE(f4 != NULL);\n\tREQUIRE(BN_set_word(f4, RSA_F4) != 0);\n\tREQUIRE(RSA_generate_key_ex(rsa_keypair, 1024, f4, NULL) != 0);\n\tREQUIRE(key.copy(rsa_keypair));\n\tBN_free(f4);\n\tf4 = NULL;\n\tRSA_free(rsa_keypair);\n\trsa_keypair = NULL;\n\n\tsslpkix::FileSink key_file;\n\tREQUIRE(key_file.open(\"JohnDoe.key\", \"wb\"));\n\tREQUIRE(key.save(key_file));\n\tkey_file.close();\n\n\t\/\/\n\t\/\/ Create the certificate\n\t\/\/\n\n\tsslpkix::Certificate cert;\n\tREQUIRE(cert.create());\n\n\t\/\/ Adjust version\n\tREQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));\n\n\t\/\/ Adjust keys\n\tREQUIRE(cert.set_pubkey(key));\n\n\t\/\/ Use a hardcoded serial - Never do this in production code!\n\tREQUIRE(cert.set_serial(31337L));\n\n\t\/\/ Adjust issuer and subject\n\tREQUIRE(cert.set_issuer(issuer));\n\tREQUIRE(cert.set_subject(subject));\n\n\t\/\/ Valid for 5 days from now\n\tREQUIRE(cert.set_valid_since(0));\n\tREQUIRE(cert.set_valid_until(5));\n\n\t\/\/ Self-sign this certificate\n\tREQUIRE(cert.sign(key));\n\n\t\/\/ Save it\n\tsslpkix::FileSink cert_file;\n\tREQUIRE(cert_file.open(\"JohnDoe.crt\", \"wb\"));\n\tREQUIRE(cert.save(cert_file));\n\tcert_file.close();\n}\n\nTEST_CASE(\"iosink\/operators\", \"IoSink operators\")\n{\n\tsslpkix::FileSink cert_file;\n\tREQUIRE(cert_file.open(\"JohnDoe.crt\", \"rb\"));\n\tstd::string cert_string;\n\tcert_file >> cert_string; \/\/ IoSink to std::string\n\t\/\/std::cout << cert_string << std::endl;\n\tcert_file.close();\n\t\/\/ TODO(jweyrich): Test whether operator>> was successful. How?\n\n\tstd::stringstream sstream;\n\n\tsslpkix::MemorySink cert_mem;\n\tREQUIRE(cert_mem.open_rw());\n\tcert_mem << cert_string; \/\/ std::string to IoSink\n\tsstream << cert_mem; \/\/ IoSink to std::stringstream\n\tcert_mem.close();\n\tREQUIRE(sstream.str() == cert_string);\n\n\t\/\/ Reset the stringstream\n\tsstream.str(std::string());\n\n\tsslpkix::MemorySink key_mem;\n\tREQUIRE(key_mem.open_rw());\n\tstd::filebuf fbuf;\n\tfbuf.open(\"JohnDoe.key\", std::ios::in);\n\tstd::istream istream(&fbuf);\n\tistream >> key_mem; \/\/ std::istream to IoSink\n\tstd::string key_string;\n\tkey_mem >> key_string; \/\/ IoSink to std::string\n\t\/\/std::cout << key_string << std::endl;\n\n\tistream.clear(); \/\/ Clear EOF flag (required before C++11)\n\tistream.seekg(0); \/\/ Rewind the std::iostream\n\tsstream << istream.rdbuf(); \/\/ std::istream to std::stringstream\n\t\/\/std::cout << sstream.str() << std::endl;\n\n\tREQUIRE(sstream.str() == key_string);\n\n\tfbuf.close();\n\tkey_mem.close();\n}\n\nTEST_CASE(\"certificate_name\/entries\", \"CertificateName entries\")\n{\n\tsslpkix::CertificateName name;\n\tREQUIRE(name.create());\n\tREQUIRE(name.set_common_name(\"John Doe\"));\n\tREQUIRE(name.common_name() == \"John Doe\");\n\tREQUIRE(name.set_country(\"BR\"));\n\tREQUIRE(name.country() == \"BR\");\n\tREQUIRE(name.set_email(\"john.doe@example.com\"));\n\tREQUIRE(name.email() == \"john.doe@example.com\");\n\tREQUIRE(name.set_locality(\"Sao Paulo\"));\n\tREQUIRE(name.locality() == \"Sao Paulo\");\n\tREQUIRE(name.set_organization(\"Independent\"));\n\tREQUIRE(name.organization() == \"Independent\");\n\tREQUIRE(name.set_state(\"SP\"));\n\tREQUIRE(name.state() == \"SP\");\n}\n\nTEST_CASE(\"key\/generation\/rsa\", \"RSA key generation\")\n{\n\tsslpkix::PrivateKey key;\n\tREQUIRE(key.create());\n\tRSA *rsa_keypair = RSA_new();\n\tREQUIRE(rsa_keypair != NULL);\n\tBIGNUM *f4 = BN_new();\n\tREQUIRE(f4 != NULL);\n\tREQUIRE(BN_set_word(f4, RSA_F4) != 0);\n\tREQUIRE(RSA_generate_key_ex(rsa_keypair, 512, f4, NULL) != 0);\n\tREQUIRE(key.copy(rsa_keypair));\n\tBN_free(f4);\n\tf4 = NULL;\n\tRSA_free(rsa_keypair);\n\trsa_keypair = NULL;\n}\n\nTEST_CASE(\"certificate_name\/extensions\", \"CertificateName extension\")\n{\n\tint nid;\n\tconst char *oid = \"1.2.3.4.5.31\";\n\tconst char *short_name = \"CTE\";\n\tconst char *long_name = \"customTextEntry\";\n\tconst char *value = \"Some value here\";\n\n\tREQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));\n\tsslpkix::CertificateName name;\n\tREQUIRE(name.create());\n\tREQUIRE(name.add_entry(short_name, value));\n\tint index;\n\tREQUIRE((index = name.find_entry(nid)) != -1);\n\tREQUIRE(name.entry(index) != NULL);\n\tREQUIRE(name.entry_count() == 1);\n\tREQUIRE(name.entry_value(nid) == value);\n}\n\nint main(int argc, char *const argv[])\n{\n\tbool success = sslpkix::startup();\n\tif (!success) {\n\t\tstd::cerr << \"ERROR: Failed to initialize SSLPKIX.\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint result = Catch::Session().run(argc, argv);\n\n\tsslpkix::shutdown();\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017-2018 Leonid Yuriev <leo@yuriev.ru>\n * and other libmdbx authors: please see AUTHORS file.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted only as authorized by the OpenLDAP\n * Public License.\n *\n * A copy of this license is available in the file LICENSE in the\n * top-level directory of the distribution or, alternatively, at\n * <http:\/\/www.OpenLDAP.org\/license.html>.\n *\/\n\n#include \"test.h\"\n#include <float.h>\n#if defined(HAVE_IEEE754_H) || __has_include(<ieee754.h>)\n#include <ieee754.h>\n#endif\n\nstd::string format(const char *fmt, ...) {\n va_list ap, ones;\n va_start(ap, fmt);\n va_copy(ones, ap);\n#ifdef _MSC_VER\n int needed = _vscprintf(fmt, ap);\n#else\n int needed = vsnprintf(nullptr, 0, fmt, ap);\n#endif\n assert(needed >= 0);\n va_end(ap);\n std::string result;\n result.reserve((size_t)needed + 1);\n result.resize((size_t)needed, '\\0');\n int actual = vsnprintf((char *)result.data(), result.capacity(), fmt, ones);\n assert(actual == needed);\n (void)actual;\n va_end(ones);\n return result;\n}\n\nstd::string data2hex(const void *ptr, size_t bytes, simple_checksum &checksum) {\n std::string result;\n if (bytes > 0) {\n const uint8_t *data = (const uint8_t *)ptr;\n checksum.push(data, bytes);\n result.reserve(bytes * 2);\n const uint8_t *const end = data + bytes;\n do {\n char h = *data >> 4;\n char l = *data & 15;\n result.push_back((l < 10) ? l + '0' : l - 10 + 'a');\n result.push_back((h < 10) ? h + '0' : h - 10 + 'a');\n } while (++data < end);\n }\n assert(result.size() == bytes * 2);\n return result;\n}\n\nbool hex2data(const char *hex_begin, const char *hex_end, void *ptr,\n size_t bytes, simple_checksum &checksum) {\n if (bytes * 2 != (size_t)(hex_end - hex_begin))\n return false;\n\n uint8_t *data = (uint8_t *)ptr;\n for (const char *hex = hex_begin; hex != hex_end; hex += 2, ++data) {\n unsigned l = hex[0], h = hex[1];\n\n if (l >= '0' && l <= '9')\n l = l - '0';\n else if (l >= 'A' && l <= 'F')\n l = l - 'A' + 10;\n else if (l >= 'a' && l <= 'f')\n l = l - 'a' + 10;\n else\n return false;\n\n if (h >= '0' && h <= '9')\n h = h - '0';\n else if (h >= 'A' && h <= 'F')\n h = h - 'A' + 10;\n else if (h >= 'a' && h <= 'f')\n h = h - 'a' + 10;\n else\n return false;\n\n uint32_t c = l + (h << 4);\n checksum.push(c);\n *data = (uint8_t)c;\n }\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\/* TODO: replace my 'libmera' fomr t1ha. *\/\nuint64_t entropy_ticks(void) {\n#if defined(__GNUC__) || defined(__clang__)\n#if defined(__ia64__)\n uint64_t ticks;\n __asm __volatile(\"mov %0=ar.itc\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__hppa__)\n uint64_t ticks;\n __asm __volatile(\"mfctl 16, %0\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__s390__)\n uint64_t ticks;\n __asm __volatile(\"stck 0(%0)\" : : \"a\"(&(ticks)) : \"memory\", \"cc\");\n return ticks;\n#elif defined(__alpha__)\n uint64_t ticks;\n __asm __volatile(\"rpcc %0\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__sparc_v9__)\n uint64_t ticks;\n __asm __volatile(\"rd %%tick, %0\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__powerpc64__) || defined(__ppc64__)\n uint64_t ticks;\n __asm __volatile(\"mfspr %0, 268\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__ppc__) || defined(__powerpc__)\n unsigned tbl, tbu;\n\n \/* LY: Here not a problem if a high-part (tbu)\n * would been updated during reading. *\/\n __asm __volatile(\"mftb %0\" : \"=r\"(tbl));\n __asm __volatile(\"mftbu %0\" : \"=r\"(tbu));\n\n return (((uin64_t)tbu0) << 32) | tbl;\n#endif \/* arch selector *\/\n#endif \/* __GNUC__ || __clang__ *\/\n\n#if defined(__e2k__) || defined(__ia32__)\n return __rdtsc();\n#elif defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS)\n LARGE_INTEGER PerformanceCount;\n if (QueryPerformanceCounter(&PerformanceCount))\n return PerformanceCount.QuadPart;\n return GetTickCount64();\n#else\n struct timespec ts;\n#if defined(CLOCK_MONOTONIC_COARSE)\n clockid_t clock = CLOCK_MONOTONIC_COARSE;\n#elif defined(CLOCK_MONOTONIC_RAW)\n clockid_t clock = CLOCK_MONOTONIC_RAW;\n#else\n clockid_t clock = CLOCK_MONOTONIC;\n#endif\n int rc = clock_gettime(clock, &ts);\n if (unlikely(rc))\n failure_perror(\"clock_gettime()\", rc);\n\n return (((uint64_t)ts.tv_sec) << 32) + ts.tv_nsec;\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\n\nstatic __inline uint64_t bleach64(uint64_t dirty) {\n return mul_64x64_high(bswap64(dirty), UINT64_C(17048867929148541611));\n}\n\nstatic __inline uint32_t bleach32(uint32_t dirty) {\n return (uint32_t)((bswap32(dirty) * UINT64_C(2175734609)) >> 32);\n}\n\nuint64_t prng64_careless(uint64_t &state) {\n state = state * UINT64_C(6364136223846793005) + 1;\n return state;\n}\n\nuint64_t prng64_white(uint64_t &state) {\n state = state * UINT64_C(6364136223846793005) + UINT64_C(1442695040888963407);\n return bleach64(state);\n}\n\nuint32_t prng32(uint64_t &state) {\n return (uint32_t)(prng64_careless(state) >> 32);\n}\n\nvoid prng_fill(uint64_t &state, void *ptr, size_t bytes) {\n while (bytes >= 4) {\n *((uint32_t *)ptr) = prng32(state);\n ptr = (uint32_t *)ptr + 1;\n bytes -= 4;\n }\n\n switch (bytes & 3) {\n case 3: {\n uint32_t u32 = prng32(state);\n memcpy(ptr, &u32, 3);\n } break;\n case 2:\n *((uint16_t *)ptr) = (uint16_t)prng32(state);\n break;\n case 1:\n *((uint8_t *)ptr) = (uint8_t)prng32(state);\n break;\n case 0:\n break;\n }\n}\n\nstatic __thread uint64_t prng_state;\n\nvoid prng_seed(uint64_t seed) { prng_state = bleach64(seed); }\n\nuint32_t prng32(void) { return prng32(prng_state); }\n\nuint64_t prng64(void) { return prng64_white(prng_state); }\n\nvoid prng_fill(void *ptr, size_t bytes) { prng_fill(prng_state, ptr, bytes); }\n\nuint64_t entropy_white() { return bleach64(entropy_ticks()); }\n\ndouble double_from_lower(uint64_t salt) {\n#ifdef IEEE754_DOUBLE_BIAS\n ieee754_double r;\n r.ieee.negative = 0;\n r.ieee.exponent = IEEE754_DOUBLE_BIAS;\n r.ieee.mantissa0 = (unsigned)(salt >> 32);\n r.ieee.mantissa1 = (unsigned)salt;\n return r.d;\n#else\n const uint64_t top = (UINT64_C(1) << DBL_MANT_DIG) - 1;\n const double scale = 1.0 \/ (double)top;\n return (salt & top) * scale;\n#endif\n}\n\ndouble double_from_upper(uint64_t salt) {\n#ifdef IEEE754_DOUBLE_BIAS\n ieee754_double r;\n r.ieee.negative = 0;\n r.ieee.exponent = IEEE754_DOUBLE_BIAS;\n salt >>= 64 - DBL_MANT_DIG;\n r.ieee.mantissa0 = (unsigned)(salt >> 32);\n r.ieee.mantissa1 = (unsigned)salt;\n return r.d;\n#else\n const uint64_t top = (UINT64_C(1) << DBL_MANT_DIG) - 1;\n const double scale = 1.0 \/ (double)top;\n return (salt >> (64 - DBL_MANT_DIG)) * scale;\n#endif\n}\n\nbool flipcoin() { return bleach32((uint32_t)entropy_ticks()) & 1; }\n\nbool jitter(unsigned probability_percent) {\n const uint32_t top = UINT32_MAX - UINT32_MAX % 100;\n uint32_t dice, edge = (top) \/ 100 * probability_percent;\n do\n dice = bleach32((uint32_t)entropy_ticks());\n while (dice >= top);\n return dice < edge;\n}\n\nvoid jitter_delay(bool extra) {\n unsigned dice = entropy_white() & 3;\n if (dice == 0) {\n log_trace(\"== jitter.no-delay\");\n } else {\n log_trace(\">> jitter.delay: dice %u\", dice);\n do {\n cpu_relax();\n memory_barrier();\n cpu_relax();\n if (dice > 1) {\n osal_yield();\n cpu_relax();\n if (dice > 2) {\n unsigned us = entropy_white() &\n (extra ? 0xfffff \/* 1.05 s *\/ : 0x3ff \/* 1 ms *\/);\n log_trace(\"== jitter.delay: %0.6f\", us \/ 1000000.0);\n osal_udelay(us);\n }\n }\n } while (flipcoin());\n log_trace(\"<< jitter.delay: dice %u\", dice);\n }\n}\n<commit_msg>mdbx-tests: fix entropy_ticks() for multiarch.<commit_after>\/*\n * Copyright 2017-2018 Leonid Yuriev <leo@yuriev.ru>\n * and other libmdbx authors: please see AUTHORS file.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted only as authorized by the OpenLDAP\n * Public License.\n *\n * A copy of this license is available in the file LICENSE in the\n * top-level directory of the distribution or, alternatively, at\n * <http:\/\/www.OpenLDAP.org\/license.html>.\n *\/\n\n#include \"test.h\"\n#include <float.h>\n#if defined(HAVE_IEEE754_H) || __has_include(<ieee754.h>)\n#include <ieee754.h>\n#endif\n\nstd::string format(const char *fmt, ...) {\n va_list ap, ones;\n va_start(ap, fmt);\n va_copy(ones, ap);\n#ifdef _MSC_VER\n int needed = _vscprintf(fmt, ap);\n#else\n int needed = vsnprintf(nullptr, 0, fmt, ap);\n#endif\n assert(needed >= 0);\n va_end(ap);\n std::string result;\n result.reserve((size_t)needed + 1);\n result.resize((size_t)needed, '\\0');\n int actual = vsnprintf((char *)result.data(), result.capacity(), fmt, ones);\n assert(actual == needed);\n (void)actual;\n va_end(ones);\n return result;\n}\n\nstd::string data2hex(const void *ptr, size_t bytes, simple_checksum &checksum) {\n std::string result;\n if (bytes > 0) {\n const uint8_t *data = (const uint8_t *)ptr;\n checksum.push(data, bytes);\n result.reserve(bytes * 2);\n const uint8_t *const end = data + bytes;\n do {\n char h = *data >> 4;\n char l = *data & 15;\n result.push_back((l < 10) ? l + '0' : l - 10 + 'a');\n result.push_back((h < 10) ? h + '0' : h - 10 + 'a');\n } while (++data < end);\n }\n assert(result.size() == bytes * 2);\n return result;\n}\n\nbool hex2data(const char *hex_begin, const char *hex_end, void *ptr,\n size_t bytes, simple_checksum &checksum) {\n if (bytes * 2 != (size_t)(hex_end - hex_begin))\n return false;\n\n uint8_t *data = (uint8_t *)ptr;\n for (const char *hex = hex_begin; hex != hex_end; hex += 2, ++data) {\n unsigned l = hex[0], h = hex[1];\n\n if (l >= '0' && l <= '9')\n l = l - '0';\n else if (l >= 'A' && l <= 'F')\n l = l - 'A' + 10;\n else if (l >= 'a' && l <= 'f')\n l = l - 'a' + 10;\n else\n return false;\n\n if (h >= '0' && h <= '9')\n h = h - '0';\n else if (h >= 'A' && h <= 'F')\n h = h - 'A' + 10;\n else if (h >= 'a' && h <= 'f')\n h = h - 'a' + 10;\n else\n return false;\n\n uint32_t c = l + (h << 4);\n checksum.push(c);\n *data = (uint8_t)c;\n }\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\/* TODO: replace my 'libmera' fomr t1ha. *\/\nuint64_t entropy_ticks(void) {\n#if defined(EMSCRIPTEN)\n return (uint64_t)emscripten_get_now();\n#endif \/* EMSCRIPTEN *\/\n\n#if defined(__APPLE__) || defined(__MACH__)\n return mach_absolute_time();\n#endif \/* defined(__APPLE__) || defined(__MACH__) *\/\n\n#if defined(__sun__) || defined(__sun)\n return gethrtime();\n#endif \/* __sun__ *\/\n\n#if defined(__GNUC__) || defined(__clang__)\n\n#if defined(__ia64__)\n uint64_t ticks;\n __asm __volatile(\"mov %0=ar.itc\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__hppa__)\n uint64_t ticks;\n __asm __volatile(\"mfctl 16, %0\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__s390__)\n uint64_t ticks;\n __asm __volatile(\"stck 0(%0)\" : : \"a\"(&(ticks)) : \"memory\", \"cc\");\n return ticks;\n#elif defined(__alpha__)\n uint64_t ticks;\n __asm __volatile(\"rpcc %0\" : \"=r\"(ticks));\n return ticks;\n#elif defined(__sparc__) || defined(__sparc) || defined(__sparc64__) || \\\n defined(__sparc64) || defined(__sparc_v8plus__) || \\\n defined(__sparc_v8plus) || defined(__sparc_v8plusa__) || \\\n defined(__sparc_v8plusa) || defined(__sparc_v9__) || defined(__sparc_v9)\n\n union {\n uint64_t u64;\n struct {\n#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n uint32_t h, l;\n#else\n uint32_t l, h;\n#endif\n } u32;\n } cycles;\n\n#if defined(__sparc_v8plus__) || defined(__sparc_v8plusa__) || \\\n defined(__sparc_v9__) || defined(__sparc_v8plus) || \\\n defined(__sparc_v8plusa) || defined(__sparc_v9)\n\n#if UINTPTR_MAX > 0xffffFFFFul || ULONG_MAX > 0xffffFFFFul || \\\n defined(__sparc64__) || defined(__sparc64)\n __asm __volatile(\"rd %%tick, %0\" : \"=r\"(cycles.u64));\n#else\n __asm __volatile(\"rd %%tick, %1; srlx %1, 32, %0\"\n : \"=r\"(cycles.u32.h), \"=r\"(cycles.u32.l));\n#endif \/* __sparc64__ *\/\n\n#else\n __asm __volatile(\".byte 0x83, 0x41, 0x00, 0x00; mov %%g1, %0\"\n : \"=r\"(cycles.u64)\n :\n : \"%g1\");\n#endif \/* __sparc8plus__ || __sparc_v9__ *\/\n return cycles.u64;\n\n#elif (defined(__powerpc64__) || defined(__ppc64__) || defined(__ppc64) || \\\n defined(__powerpc64))\n uint64_t ticks;\n __asm __volatile(\"mfspr %0, 268\" : \"=r\"(ticks));\n return ticks;\n#elif (defined(__powerpc__) || defined(__ppc__) || defined(__powerpc) || \\\n defined(__ppc))\n#if UINTPTR_MAX > 0xffffFFFFul || ULONG_MAX > 0xffffFFFFul\n uint64_t ticks;\n __asm __volatile(\"mftb %0\" : \"=r\"(ticks));\n *now = ticks;\n#else\n uint64_t ticks;\n uint32_t low, high_before, high_after;\n __asm __volatile(\"mftbu %0; mftb %1; mftbu %2\"\n : \"=r\"(high_before), \"=r\"(low), \"=r\"(high_after));\n ticks = (uint64_t)high_after << 32;\n ticks |= low & \/* zeroes if high part has changed *\/\n ~(high_before - high_after);\n#endif\n#elif defined(__aarch64__) || (defined(__ARM_ARCH) && __ARM_ARCH > 7)\n uint64_t virtual_timer;\n __asm __volatile(\"mrs %0, cntvct_el0\" : \"=r\"(virtual_timer));\n return virtual_timer;\n#elif defined(__ARM_ARCH) && __ARM_ARCH > 5 && __ARM_ARCH < 8\n unsigned long pmccntr;\n __asm __volatile(\"mrc p15, 0, %0, c9, c13, 0\" : \"=r\"(pmccntr));\n return pmccntr;\n#elif defined(__mips__) || defined(__mips) || defined(_R4000)\n unsigned count;\n __asm __volatile(\"rdhwr %0, $2\" : \"=r\"(count));\n return count;\n#endif \/* arch selector *\/\n#endif \/* __GNUC__ || __clang__ *\/\n\n#if defined(__e2k__) || defined(__ia32__)\n return __rdtsc();\n#elif defined(_M_ARM)\n return __rdpmccntr64();\n#elif defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS)\n LARGE_INTEGER PerformanceCount;\n if (QueryPerformanceCounter(&PerformanceCount))\n return PerformanceCount.QuadPart;\n return GetTickCount64();\n#else\n struct timespec ts;\n#if defined(CLOCK_MONOTONIC_COARSE)\n clockid_t clock = CLOCK_MONOTONIC_COARSE;\n#elif defined(CLOCK_MONOTONIC_RAW)\n clockid_t clock = CLOCK_MONOTONIC_RAW;\n#else\n clockid_t clock = CLOCK_MONOTONIC;\n#endif\n int rc = clock_gettime(clock, &ts);\n if (unlikely(rc))\n failure_perror(\"clock_gettime()\", rc);\n\n return (((uint64_t)ts.tv_sec) << 32) + ts.tv_nsec;\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\n\nstatic __inline uint64_t bleach64(uint64_t dirty) {\n return mul_64x64_high(bswap64(dirty), UINT64_C(17048867929148541611));\n}\n\nstatic __inline uint32_t bleach32(uint32_t dirty) {\n return (uint32_t)((bswap32(dirty) * UINT64_C(2175734609)) >> 32);\n}\n\nuint64_t prng64_careless(uint64_t &state) {\n state = state * UINT64_C(6364136223846793005) + 1;\n return state;\n}\n\nuint64_t prng64_white(uint64_t &state) {\n state = state * UINT64_C(6364136223846793005) + UINT64_C(1442695040888963407);\n return bleach64(state);\n}\n\nuint32_t prng32(uint64_t &state) {\n return (uint32_t)(prng64_careless(state) >> 32);\n}\n\nvoid prng_fill(uint64_t &state, void *ptr, size_t bytes) {\n while (bytes >= 4) {\n *((uint32_t *)ptr) = prng32(state);\n ptr = (uint32_t *)ptr + 1;\n bytes -= 4;\n }\n\n switch (bytes & 3) {\n case 3: {\n uint32_t u32 = prng32(state);\n memcpy(ptr, &u32, 3);\n } break;\n case 2:\n *((uint16_t *)ptr) = (uint16_t)prng32(state);\n break;\n case 1:\n *((uint8_t *)ptr) = (uint8_t)prng32(state);\n break;\n case 0:\n break;\n }\n}\n\nstatic __thread uint64_t prng_state;\n\nvoid prng_seed(uint64_t seed) { prng_state = bleach64(seed); }\n\nuint32_t prng32(void) { return prng32(prng_state); }\n\nuint64_t prng64(void) { return prng64_white(prng_state); }\n\nvoid prng_fill(void *ptr, size_t bytes) { prng_fill(prng_state, ptr, bytes); }\n\nuint64_t entropy_white() { return bleach64(entropy_ticks()); }\n\ndouble double_from_lower(uint64_t salt) {\n#ifdef IEEE754_DOUBLE_BIAS\n ieee754_double r;\n r.ieee.negative = 0;\n r.ieee.exponent = IEEE754_DOUBLE_BIAS;\n r.ieee.mantissa0 = (unsigned)(salt >> 32);\n r.ieee.mantissa1 = (unsigned)salt;\n return r.d;\n#else\n const uint64_t top = (UINT64_C(1) << DBL_MANT_DIG) - 1;\n const double scale = 1.0 \/ (double)top;\n return (salt & top) * scale;\n#endif\n}\n\ndouble double_from_upper(uint64_t salt) {\n#ifdef IEEE754_DOUBLE_BIAS\n ieee754_double r;\n r.ieee.negative = 0;\n r.ieee.exponent = IEEE754_DOUBLE_BIAS;\n salt >>= 64 - DBL_MANT_DIG;\n r.ieee.mantissa0 = (unsigned)(salt >> 32);\n r.ieee.mantissa1 = (unsigned)salt;\n return r.d;\n#else\n const uint64_t top = (UINT64_C(1) << DBL_MANT_DIG) - 1;\n const double scale = 1.0 \/ (double)top;\n return (salt >> (64 - DBL_MANT_DIG)) * scale;\n#endif\n}\n\nbool flipcoin() { return bleach32((uint32_t)entropy_ticks()) & 1; }\n\nbool jitter(unsigned probability_percent) {\n const uint32_t top = UINT32_MAX - UINT32_MAX % 100;\n uint32_t dice, edge = (top) \/ 100 * probability_percent;\n do\n dice = bleach32((uint32_t)entropy_ticks());\n while (dice >= top);\n return dice < edge;\n}\n\nvoid jitter_delay(bool extra) {\n unsigned dice = entropy_white() & 3;\n if (dice == 0) {\n log_trace(\"== jitter.no-delay\");\n } else {\n log_trace(\">> jitter.delay: dice %u\", dice);\n do {\n cpu_relax();\n memory_barrier();\n cpu_relax();\n if (dice > 1) {\n osal_yield();\n cpu_relax();\n if (dice > 2) {\n unsigned us = entropy_white() &\n (extra ? 0xfffff \/* 1.05 s *\/ : 0x3ff \/* 1 ms *\/);\n log_trace(\"== jitter.delay: %0.6f\", us \/ 1000000.0);\n osal_udelay(us);\n }\n }\n } while (flipcoin());\n log_trace(\"<< jitter.delay: dice %u\", dice);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <v8.h>\n#include <nan.h>\n\n#ifdef _WIN32\n#include \"notificationstate-query.h\"\n#endif\n\nusing namespace v8;\n\nvoid GetNotificationState(const v8::FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n int returnValue = -1;\n\n #ifdef _WIN32\n returnValue = queryUserNotificationState();\n #endif\n\n args.GetReturnValue().Set(Int32::New(isolate, returnValue));\n}\n\nNAN_MODULE_INIT(Init) {\n Nan::Set(target, Nan::New<String>(\"getNotificationState\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<FunctionTemplate>(GetNotificationState)).ToLocalChecked());\n}\n\nNODE_MODULE(quiethours, Init)\n<commit_msg>fix: Better Node 12 compilation, part 234<commit_after>#include <node.h>\n#include <v8.h>\n#include <nan.h>\n\n#ifdef _WIN32\n#include \"notificationstate-query.h\"\n#endif\n\nusing namespace v8;\n\nNAN_METHOD(GetNotificationState) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n int returnValue = -1;\n\n #ifdef TARGET_OS_MAC\n returnValue = queryUserNotificationState();\n #endif\n\n info.GetReturnValue().Set(Int32::New(isolate, returnValue));\n}\n\nNAN_MODULE_INIT(Init) {\n Nan::SetMethod(target, \"getNotificationState\", GetNotificationState);\n}\n\nNODE_MODULE(quiethours, Init)\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of cpp-ethereum.\n \n cpp-ethereum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n cpp-ethereum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/** @file RLPXHandshake.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @date 2015\n *\/\n\n#include \"Host.h\"\n#include \"Session.h\"\n#include \"Peer.h\"\n#include \"RLPxHandshake.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace CryptoPP;\n\nvoid RLPXHandshake::writeAuth()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.egress sending auth to \" << m_socket->remoteEndpoint();\n\tm_auth.resize(Signature::size + h256::size + Public::size + h256::size + 1);\n\tbytesRef sig(&m_auth[0], Signature::size);\n\tbytesRef hepubk(&m_auth[Signature::size], h256::size);\n\tbytesRef pubk(&m_auth[Signature::size + h256::size], Public::size);\n\tbytesRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size);\n\t\n\t\/\/ E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)\n\tSecret staticShared;\n\tcrypto::ecdh::agree(m_host->m_alias.sec(), m_remote, staticShared);\n\tsign(m_ecdhe.seckey(), staticShared ^ m_nonce).ref().copyTo(sig);\n\tsha3(m_ecdhe.pubkey().ref(), hepubk);\n\tm_host->m_alias.pub().ref().copyTo(pubk);\n\tm_nonce.ref().copyTo(nonce);\n\tm_auth[m_auth.size() - 1] = 0x0;\n\tencryptECIES(m_remote, &m_auth, m_authCipher);\n\n\tauto self(shared_from_this());\n\tba::async_write(m_socket->ref(), ba::buffer(m_authCipher), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\ttransition(ec);\n\t});\n}\n\nvoid RLPXHandshake::writeAck()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.ingress sending ack to \" << m_socket->remoteEndpoint();\n\tm_ack.resize(Public::size + h256::size + 1);\n\tbytesRef epubk(&m_ack[0], Public::size);\n\tbytesRef nonce(&m_ack[Public::size], h256::size);\n\tm_ecdhe.pubkey().ref().copyTo(epubk);\n\tm_nonce.ref().copyTo(nonce);\n\tm_ack[m_ack.size() - 1] = 0x0;\n\tencryptECIES(m_remote, &m_ack, m_ackCipher);\n\t\n\tauto self(shared_from_this());\n\tba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\ttransition(ec);\n\t});\n}\n\nvoid RLPXHandshake::readAuth()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.ingress recving auth from \" << m_socket->remoteEndpoint();\n\tm_authCipher.resize(307);\n\tauto self(shared_from_this());\n\tba::async_read(m_socket->ref(), ba::buffer(m_authCipher, 307), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\tif (ec)\n\t\t\ttransition(ec);\n\t\telse if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_authCipher), m_auth))\n\t\t{\n\t\t\tbytesConstRef sig(&m_auth[0], Signature::size);\n\t\t\tbytesConstRef hepubk(&m_auth[Signature::size], h256::size);\n\t\t\tbytesConstRef pubk(&m_auth[Signature::size + h256::size], Public::size);\n\t\t\tbytesConstRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size);\n\t\t\tpubk.copyTo(m_remote.ref());\n\t\t\tnonce.copyTo(m_remoteNonce.ref());\n\t\t\t\n\t\t\tSecret sharedSecret;\n\t\t\tcrypto::ecdh::agree(m_host->m_alias.sec(), m_remote, sharedSecret);\n\t\t\tm_remoteEphemeral = recover(*(Signature*)sig.data(), sharedSecret ^ m_remoteNonce);\n\n\t\t\tif (sha3(m_remoteEphemeral) != *(h256*)hepubk.data())\n\t\t\t\tclog(NetP2PConnect) << \"p2p.connect.ingress auth failed (invalid: hash mismatch) for\" << m_socket->remoteEndpoint();\n\t\t\t\n\t\t\ttransition();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclog(NetP2PConnect) << \"p2p.connect.ingress recving auth decrypt failed for\" << m_socket->remoteEndpoint();\n\t\t\tm_nextState = Error;\n\t\t\ttransition();\n\t\t}\n\t});\n}\n\nvoid RLPXHandshake::readAck()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.egress recving ack from \" << m_socket->remoteEndpoint();\n\tm_ackCipher.resize(210);\n\tauto self(shared_from_this());\n\tba::async_read(m_socket->ref(), ba::buffer(m_ackCipher, 210), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\tif (ec)\n\t\t\ttransition(ec);\n\t\telse if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_ackCipher), m_ack))\n\t\t{\n\t\t\tbytesConstRef(&m_ack).cropped(0, Public::size).copyTo(m_remoteEphemeral.ref());\n\t\t\tbytesConstRef(&m_ack).cropped(Public::size, h256::size).copyTo(m_remoteNonce.ref());\n\t\t\ttransition();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclog(NetP2PConnect) << \"p2p.connect.egress recving ack decrypt failed for \" << m_socket->remoteEndpoint();\n\t\t\tm_nextState = Error;\n\t\t\ttransition();\n\t\t}\n\t});\n}\n\nvoid RLPXHandshake::error()\n{\n\tm_idleTimer.cancel();\n\t\n\tauto connected = m_socket->isConnected();\n\tif (connected && !m_socket->remoteEndpoint().address().is_unspecified())\n\t\tclog(NetP2PConnect) << \"Disconnecting \" << m_socket->remoteEndpoint() << \" (Handshake Failed)\";\n\telse\n\t\tclog(NetP2PConnect) << \"Handshake Failed (Connection reset by peer)\";\n\n\tm_socket->close();\n\tif (m_io != nullptr)\n\t\tdelete m_io;\n}\n\nvoid RLPXHandshake::transition(boost::system::error_code _ech)\n{\n\tif (_ech || m_nextState == Error || m_cancel)\n\t{\n\t\tclog(NetP2PConnect) << \"Handshake Failed (I\/O Error:\" << _ech.message() << \")\";\n\t\treturn error();\n\t}\n\t\n\tauto self(shared_from_this());\n\tif (m_nextState == New)\n\t{\n\t\tm_nextState = AckAuth;\n\t\tif (m_originated)\n\t\t\twriteAuth();\n\t\telse\n\t\t\treadAuth();\n\t}\n\telse if (m_nextState == AckAuth)\n\t{\n\t\tm_nextState = WriteHello;\n\t\tif (m_originated)\n\t\t\treadAck();\n\t\telse\n\t\t\twriteAck();\n\t}\n\telse if (m_nextState == WriteHello)\n\t{\n\t\tm_nextState = ReadHello;\n\t\tclog(NetP2PConnect) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"sending capabilities handshake\";\n\n\t\t\/\/\/ This pointer will be freed if there is an error otherwise\n\t\t\/\/\/ it will be passed to Host which will take ownership.\n\t\tm_io = new RLPXFrameIO(*this);\n\n\t\t\/\/ old packet format\n\t\t\/\/ 5 arguments, HelloPacket\n\t\tRLPStream s;\n\t\ts.append((unsigned)0).appendList(5)\n\t\t<< dev::p2p::c_protocolVersion\n\t\t<< m_host->m_clientVersion\n\t\t<< m_host->caps()\n\t\t<< m_host->listenPort()\n\t\t<< m_host->id();\n\t\tbytes packet;\n\t\ts.swapOut(packet);\n\t\tm_io->writeSingleFramePacket(&packet, m_handshakeOutBuffer);\n\t\tba::async_write(m_socket->ref(), ba::buffer(m_handshakeOutBuffer), [this, self](boost::system::error_code ec, std::size_t)\n\t\t{\n\t\t\ttransition(ec);\n\t\t});\n\t}\n\telse if (m_nextState == ReadHello)\n\t{\n\t\t\/\/ Authenticate and decrypt initial hello frame with initial RLPXFrameIO\n\t\t\/\/ and request m_host to start session.\n\t\tm_nextState = StartSession;\n\t\t\n\t\t\/\/ read frame header\n\t\tm_handshakeInBuffer.resize(h256::size);\n\t\tba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, h256::size), [this, self](boost::system::error_code ec, std::size_t)\n\t\t{\n\t\t\tif (ec)\n\t\t\t\ttransition(ec);\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/\/ authenticate and decrypt header\n\t\t\t\tif (!m_io->authAndDecryptHeader(bytesRef(m_handshakeInBuffer.data(), h256::size)))\n\t\t\t\t{\n\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\ttransition();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tclog(NetP2PNote) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"recvd hello header\";\n\t\t\t\t\n\t\t\t\t\/\/\/ check frame size\n\t\t\t\tbytes& header = m_handshakeInBuffer;\n\t\t\t\tuint32_t frameSize = (uint32_t)(header[2]) | (uint32_t)(header[1])<<8 | (uint32_t)(header[0])<<16;\n\t\t\t\tif (frameSize > 1024)\n\t\t\t\t{\n\t\t\t\t\t\/\/ all future frames: 16777216\n\t\t\t\t\tclog(NetP2PWarn) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame is too large\" << frameSize;\n\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\ttransition();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/\/ rlp of header has protocol-type, sequence-id[, total-packet-size]\n\t\t\t\tbytes headerRLP(header.size() - 3 - h128::size);\n\t\t\t\tbytesConstRef(&header).cropped(3).copyTo(&headerRLP);\n\t\t\t\t\n\t\t\t\t\/\/\/ read padded frame and mac\n\t\t\t\tm_handshakeInBuffer.resize(frameSize + ((16 - (frameSize % 16)) % 16) + h128::size);\n\t\t\t\tba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, m_handshakeInBuffer.size()), [this, self, headerRLP](boost::system::error_code ec, std::size_t)\n\t\t\t\t{\n\t\t\t\t\tif (ec)\n\t\t\t\t\t\ttransition(ec);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbytesRef frame(&m_handshakeInBuffer);\n\t\t\t\t\t\tif (!m_io->authAndDecryptFrame(frame))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: decrypt failed\";\n\t\t\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\t\t\ttransition();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tPacketType packetType = (PacketType)(frame[0] == 0x80 ? 0x0 : frame[0]);\n\t\t\t\t\t\tif (packetType != 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: invalid packet type\";\n\t\t\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\t\t\ttransition();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: success. starting session.\";\n\t\t\t\t\t\tRLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall);\n\t\t\t\t\t\tm_host->startPeerSession(m_remote, rlp, m_io, m_socket->remoteEndpoint());\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\t\n\tm_idleTimer.expires_from_now(c_timeout);\n\tm_idleTimer.async_wait([this, self](boost::system::error_code const& _ec)\n\t{\n\t\tif (!_ec)\n\t\t{\n\t\t\tif (!m_socket->remoteEndpoint().address().is_unspecified())\n\t\t\t\tclog(NetP2PConnect) << \"Disconnecting \" << m_socket->remoteEndpoint() << \" (Handshake Timeout)\";\n\t\t\tcancel();\n\t\t}\n\t});\n}\n<commit_msg>Log warning and disconnect when remote passes bad rlp during handshake.<commit_after>\/*\n This file is part of cpp-ethereum.\n \n cpp-ethereum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n cpp-ethereum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/** @file RLPXHandshake.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @date 2015\n *\/\n\n#include \"Host.h\"\n#include \"Session.h\"\n#include \"Peer.h\"\n#include \"RLPxHandshake.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace CryptoPP;\n\nvoid RLPXHandshake::writeAuth()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.egress sending auth to \" << m_socket->remoteEndpoint();\n\tm_auth.resize(Signature::size + h256::size + Public::size + h256::size + 1);\n\tbytesRef sig(&m_auth[0], Signature::size);\n\tbytesRef hepubk(&m_auth[Signature::size], h256::size);\n\tbytesRef pubk(&m_auth[Signature::size + h256::size], Public::size);\n\tbytesRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size);\n\t\n\t\/\/ E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)\n\tSecret staticShared;\n\tcrypto::ecdh::agree(m_host->m_alias.sec(), m_remote, staticShared);\n\tsign(m_ecdhe.seckey(), staticShared ^ m_nonce).ref().copyTo(sig);\n\tsha3(m_ecdhe.pubkey().ref(), hepubk);\n\tm_host->m_alias.pub().ref().copyTo(pubk);\n\tm_nonce.ref().copyTo(nonce);\n\tm_auth[m_auth.size() - 1] = 0x0;\n\tencryptECIES(m_remote, &m_auth, m_authCipher);\n\n\tauto self(shared_from_this());\n\tba::async_write(m_socket->ref(), ba::buffer(m_authCipher), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\ttransition(ec);\n\t});\n}\n\nvoid RLPXHandshake::writeAck()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.ingress sending ack to \" << m_socket->remoteEndpoint();\n\tm_ack.resize(Public::size + h256::size + 1);\n\tbytesRef epubk(&m_ack[0], Public::size);\n\tbytesRef nonce(&m_ack[Public::size], h256::size);\n\tm_ecdhe.pubkey().ref().copyTo(epubk);\n\tm_nonce.ref().copyTo(nonce);\n\tm_ack[m_ack.size() - 1] = 0x0;\n\tencryptECIES(m_remote, &m_ack, m_ackCipher);\n\t\n\tauto self(shared_from_this());\n\tba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\ttransition(ec);\n\t});\n}\n\nvoid RLPXHandshake::readAuth()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.ingress recving auth from \" << m_socket->remoteEndpoint();\n\tm_authCipher.resize(307);\n\tauto self(shared_from_this());\n\tba::async_read(m_socket->ref(), ba::buffer(m_authCipher, 307), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\tif (ec)\n\t\t\ttransition(ec);\n\t\telse if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_authCipher), m_auth))\n\t\t{\n\t\t\tbytesConstRef sig(&m_auth[0], Signature::size);\n\t\t\tbytesConstRef hepubk(&m_auth[Signature::size], h256::size);\n\t\t\tbytesConstRef pubk(&m_auth[Signature::size + h256::size], Public::size);\n\t\t\tbytesConstRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size);\n\t\t\tpubk.copyTo(m_remote.ref());\n\t\t\tnonce.copyTo(m_remoteNonce.ref());\n\t\t\t\n\t\t\tSecret sharedSecret;\n\t\t\tcrypto::ecdh::agree(m_host->m_alias.sec(), m_remote, sharedSecret);\n\t\t\tm_remoteEphemeral = recover(*(Signature*)sig.data(), sharedSecret ^ m_remoteNonce);\n\n\t\t\tif (sha3(m_remoteEphemeral) != *(h256*)hepubk.data())\n\t\t\t\tclog(NetP2PConnect) << \"p2p.connect.ingress auth failed (invalid: hash mismatch) for\" << m_socket->remoteEndpoint();\n\t\t\t\n\t\t\ttransition();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclog(NetP2PConnect) << \"p2p.connect.ingress recving auth decrypt failed for\" << m_socket->remoteEndpoint();\n\t\t\tm_nextState = Error;\n\t\t\ttransition();\n\t\t}\n\t});\n}\n\nvoid RLPXHandshake::readAck()\n{\n\tclog(NetP2PConnect) << \"p2p.connect.egress recving ack from \" << m_socket->remoteEndpoint();\n\tm_ackCipher.resize(210);\n\tauto self(shared_from_this());\n\tba::async_read(m_socket->ref(), ba::buffer(m_ackCipher, 210), [this, self](boost::system::error_code ec, std::size_t)\n\t{\n\t\tif (ec)\n\t\t\ttransition(ec);\n\t\telse if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_ackCipher), m_ack))\n\t\t{\n\t\t\tbytesConstRef(&m_ack).cropped(0, Public::size).copyTo(m_remoteEphemeral.ref());\n\t\t\tbytesConstRef(&m_ack).cropped(Public::size, h256::size).copyTo(m_remoteNonce.ref());\n\t\t\ttransition();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclog(NetP2PConnect) << \"p2p.connect.egress recving ack decrypt failed for \" << m_socket->remoteEndpoint();\n\t\t\tm_nextState = Error;\n\t\t\ttransition();\n\t\t}\n\t});\n}\n\nvoid RLPXHandshake::error()\n{\n\tm_idleTimer.cancel();\n\t\n\tauto connected = m_socket->isConnected();\n\tif (connected && !m_socket->remoteEndpoint().address().is_unspecified())\n\t\tclog(NetP2PConnect) << \"Disconnecting \" << m_socket->remoteEndpoint() << \" (Handshake Failed)\";\n\telse\n\t\tclog(NetP2PConnect) << \"Handshake Failed (Connection reset by peer)\";\n\n\tm_socket->close();\n\tif (m_io != nullptr)\n\t\tdelete m_io;\n}\n\nvoid RLPXHandshake::transition(boost::system::error_code _ech)\n{\n\tif (_ech || m_nextState == Error || m_cancel)\n\t{\n\t\tclog(NetP2PConnect) << \"Handshake Failed (I\/O Error:\" << _ech.message() << \")\";\n\t\treturn error();\n\t}\n\t\n\tauto self(shared_from_this());\n\tif (m_nextState == New)\n\t{\n\t\tm_nextState = AckAuth;\n\t\tif (m_originated)\n\t\t\twriteAuth();\n\t\telse\n\t\t\treadAuth();\n\t}\n\telse if (m_nextState == AckAuth)\n\t{\n\t\tm_nextState = WriteHello;\n\t\tif (m_originated)\n\t\t\treadAck();\n\t\telse\n\t\t\twriteAck();\n\t}\n\telse if (m_nextState == WriteHello)\n\t{\n\t\tm_nextState = ReadHello;\n\t\tclog(NetP2PConnect) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"sending capabilities handshake\";\n\n\t\t\/\/\/ This pointer will be freed if there is an error otherwise\n\t\t\/\/\/ it will be passed to Host which will take ownership.\n\t\tm_io = new RLPXFrameIO(*this);\n\n\t\t\/\/ old packet format\n\t\t\/\/ 5 arguments, HelloPacket\n\t\tRLPStream s;\n\t\ts.append((unsigned)0).appendList(5)\n\t\t<< dev::p2p::c_protocolVersion\n\t\t<< m_host->m_clientVersion\n\t\t<< m_host->caps()\n\t\t<< m_host->listenPort()\n\t\t<< m_host->id();\n\t\tbytes packet;\n\t\ts.swapOut(packet);\n\t\tm_io->writeSingleFramePacket(&packet, m_handshakeOutBuffer);\n\t\tba::async_write(m_socket->ref(), ba::buffer(m_handshakeOutBuffer), [this, self](boost::system::error_code ec, std::size_t)\n\t\t{\n\t\t\ttransition(ec);\n\t\t});\n\t}\n\telse if (m_nextState == ReadHello)\n\t{\n\t\t\/\/ Authenticate and decrypt initial hello frame with initial RLPXFrameIO\n\t\t\/\/ and request m_host to start session.\n\t\tm_nextState = StartSession;\n\t\t\n\t\t\/\/ read frame header\n\t\tm_handshakeInBuffer.resize(h256::size);\n\t\tba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, h256::size), [this, self](boost::system::error_code ec, std::size_t)\n\t\t{\n\t\t\tif (ec)\n\t\t\t\ttransition(ec);\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/\/ authenticate and decrypt header\n\t\t\t\tif (!m_io->authAndDecryptHeader(bytesRef(m_handshakeInBuffer.data(), h256::size)))\n\t\t\t\t{\n\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\ttransition();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tclog(NetP2PNote) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"recvd hello header\";\n\t\t\t\t\n\t\t\t\t\/\/\/ check frame size\n\t\t\t\tbytes& header = m_handshakeInBuffer;\n\t\t\t\tuint32_t frameSize = (uint32_t)(header[2]) | (uint32_t)(header[1])<<8 | (uint32_t)(header[0])<<16;\n\t\t\t\tif (frameSize > 1024)\n\t\t\t\t{\n\t\t\t\t\t\/\/ all future frames: 16777216\n\t\t\t\t\tclog(NetP2PWarn) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame is too large\" << frameSize;\n\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\ttransition();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/\/ rlp of header has protocol-type, sequence-id[, total-packet-size]\n\t\t\t\tbytes headerRLP(header.size() - 3 - h128::size);\n\t\t\t\tbytesConstRef(&header).cropped(3).copyTo(&headerRLP);\n\t\t\t\t\n\t\t\t\t\/\/\/ read padded frame and mac\n\t\t\t\tm_handshakeInBuffer.resize(frameSize + ((16 - (frameSize % 16)) % 16) + h128::size);\n\t\t\t\tba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, m_handshakeInBuffer.size()), [this, self, headerRLP](boost::system::error_code ec, std::size_t)\n\t\t\t\t{\n\t\t\t\t\tif (ec)\n\t\t\t\t\t\ttransition(ec);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbytesRef frame(&m_handshakeInBuffer);\n\t\t\t\t\t\tif (!m_io->authAndDecryptFrame(frame))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: decrypt failed\";\n\t\t\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\t\t\ttransition();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tPacketType packetType = (PacketType)(frame[0] == 0x80 ? 0x0 : frame[0]);\n\t\t\t\t\t\tif (packetType != 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: invalid packet type\";\n\t\t\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\t\t\ttransition();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tclog(NetTriviaSummary) << (m_originated ? \"p2p.connect.egress\" : \"p2p.connect.ingress\") << \"hello frame: success. starting session.\";\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall);\n\t\t\t\t\t\t\tm_host->startPeerSession(m_remote, rlp, m_io, m_socket->remoteEndpoint());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (std::exception const& _e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tclog(NetWarn) << \"Handshake causing an exception:\" << _e.what();\n\t\t\t\t\t\t\tm_nextState = Error;\n\t\t\t\t\t\t\ttransition();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\t\n\tm_idleTimer.expires_from_now(c_timeout);\n\tm_idleTimer.async_wait([this, self](boost::system::error_code const& _ec)\n\t{\n\t\tif (!_ec)\n\t\t{\n\t\t\tif (!m_socket->remoteEndpoint().address().is_unspecified())\n\t\t\t\tclog(NetP2PConnect) << \"Disconnecting \" << m_socket->remoteEndpoint() << \" (Handshake Timeout)\";\n\t\t\tcancel();\n\t\t}\n\t});\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef PUBNUB__PubNub_hpp\n#define PUBNUB__PubNub_hpp\n\n#include <string>\n#include <vector>\n\n#include <json.h>\n\n#include <pubnub.h>\n\n\n\/** PubNub structures and constants *\/\n\nstruct pubnub;\nclass PubNub;\n\n\n\/* Callback functions to user code upon completion of various methods. *\/\n\/* Note that if the function wants to preserve the response, it should\n * bump its reference count, otherwise it will be auto-released after\n * callback is done. channels[], on the other hand, are dynamically\n * allocated and both the array and its individual items must be free()d\n * by the callee; to ease iteration by user code, there is guaranteed to\n * be as many elements as there are messages in the channels list, and\n * an extra NULL pointer at the end of the array. *\/\ntypedef void (*PubNub_publish_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_subscribe_cb)(PubNub &p, enum pubnub_res result, std::vector<std::string> &channels, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_history_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_here_now_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_time_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\n\n\n\/* Only one method may operate on a single context at once - this means\n * that if a subscribe is in progress, you cannot publish in the same\n * context; either wait or use multiple contexts. If the same context\n * is used in multiple threads, the application must ensure locking to\n * prevent improper concurrent access. *\/\n\nclass PubNub {\npublic:\n\n\t\/** PubNub context methods *\/\n\n\t\/* Initialize the PubNub context and set the compulsory parameters\n\t * @publish_key and @subscribe_key.\n\t *\n\t * @cb is a set of callbacks implementing libpubnub's needs for\n\t * socket and timer handling, plus default completion callbacks\n\t * for the API requests. Typically, @cb value will be a structure\n\t * exported by one of the frontends and @cb_data will be the\n\t * appropriate frontend context. However, you can also customize\n\t * these or pass your own structure.\n\t *\n\t * This function will also initialize the libcurl library. This has\n\t * an important connotation for multi-threaded programs, as the first\n\t * call to this function will imply curl_global_init() call and that\n\t * function is completely thread unsafe. If you need to call\n\t * pubnub_init() with other threads already running (and not even\n\t * necessarily doing anything PubNub-related), call curl_global_init()\n\t * early before spawning other threads.\n\t *\n\t * One PubNub context can service only a single request at a time\n\t * (and you must not access it from multiple threads at once), however\n\t * you can maintain as many contexts as you wish. *\/\n\tPubNub(const std::string &publish_key, const std::string &subscribe_key,\n\t\tconst struct pubnub_callbacks *cb, void *cb_data);\n\n\t\/* You can also create a PubNub wrapper class from an existing pubnub\n\t * context. @p_autodestroy determines whether PubNub destructor will\n\t * call pubnub_done(p). *\/\n\tPubNub(struct pubnub *p, bool p_autodestroy = false);\n\n\t\/* Deinitialize our PubNub context, freeing all memory that is\n\t * associated with it. *\/\n\t~PubNub();\n\n\n\t\/* Set the secret key that is used for signing published messages\n\t * to confirm they are genuine. Using the secret key is optional. *\/\n\tvoid set_secret_key(const std::string &secret_key);\n\n\t\/* Set the cipher key that is used for symmetric encryption of messages\n\t * passed over the network (publish, subscribe, history). Using the\n\t * cipher key is optional. *\/\n\tvoid set_cipher_key(const std::string &cipher_key);\n\n\t\/* Set the origin server name. By default, http:\/\/pubsub.pubnub.com\/\n\t * is used. *\/\n\tvoid set_origin(const std::string &origin);\n\n\t\/* Retrieve the currently used UUID of this PubNub context. This UUID\n\t * is visible to other clients via the here_now call and is normally\n\t * autogenerated randomly during pubnub_init(). *\/\n\tstd::string current_uuid();\n\n\t\/* Set the UUID of this PubNub context that is asserted during the\n\t * subscribe call to identify us. This replaces the autogenerated\n\t * UUID. *\/\n\tvoid set_uuid(const std::string &uuid);\n\n\t\/* This function selects the value of CURLOPT_NOSIGNAL which involves\n\t * a tradeoff:\n\t *\n\t * (i) nosignal is true (DEFAULT) - the library is thread safe and does\n\t * not modify signal handlers, however timeout handling will be broken\n\t * with regards to DNS requests\n\t *\n\t * (ii) nosignal is false - DNS requests will be timing out properly,\n\t * but the library will install custom SIGPIPE (and possibly SIGCHLD)\n\t * handlers and won't be thread safe *\/\n\tvoid set_nosignal(bool nosignal);\n\n\t\/* Set PubNub error retry policy regarding error handling.\n\t *\n\t * The call may be retried if the error is possibly recoverable\n\t * and retry is enabled for that error. This is controlled by\n\t * @retry_mask; if PNR_xxx-th bit is set, the call is retried in case\n\t * of the PNR_xxx result; this is the case for recoverable errors,\n\t * specifically PNR_OK and PNR_OCCUPIED bits are always ignored (this\n\t * may be further extended in the future). For example,\n\t *\n\t * \tpubnub_error_policy(p, 0, ...);\n\t * will turn off automatic error retry for all errors,\n\t *\n\t * \tpubnub_error_policy(p, ~0, ...);\n\t * will turn it on for all recoverable errors (this is the DEFAULT),\n\t *\n\t * \tpubnub_error_policy(p, ~(1<<PNR_TIMEOUT), ...);\n\t * will turn it on for all errors *except* PNR_TIMEOUT, and so on.\n\t *\n\t * If the call is not automatically retried after an error, the error\n\t * is reported to the application via its specified callback instead\n\t * (if you use the pubnub_sync frontend, it can be obtained from\n\t * pubnub_last_result(); for future compatibility, you should ideally\n\t * check it even when relying on automatic error retry).\n\t *\n\t * A message about the error is printed on stderr if @print is true\n\t * (the DEFAULT); this applies even to errors after which we do not\n\t * retry for whatever reason. *\/\n\tvoid error_policy(unsigned int retry_mask, bool print);\n\n\n\t\/** PubNub API requests *\/\n\n\t\/* All the API request functions accept the @timeout [s] parameter\n\t * and callback parameters @cb and @cb_data.\n\t *\n\t * The @timeout [s] parameter describes how long to wait for request\n\t * fulfillment before the PNR_TIMEOUT error is generated. Supply -1\n\t * if in doubt to obtain the optimal default value. (Note that normally,\n\t * PNR_TIMEOUT will just print a message and retry the request; see\n\t * pubnub_error_policy() above.)\n\t *\n\t * If you are using the pubnub_sync frontend, the function calls\n\t * will block until the request is fulfilled and you should pass\n\t * NULL for @cb and @cb_data. If you are using the pubnub_libevent\n\t * or a custom frontend, the function calls will return immediately\n\t * and @cb shall point to a function that will be called upon\n\t * completion (with @cb_data as its last parameter). *\/\n\n\t\/* Publish the @message JSON object on @channel. The response\n\t * will usually be just a success confirmation. *\/\n\tvoid publish(const std::string &channel, json_object &message,\n\t\t\tlong timeout = -1, PubNub_publish_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Subscribe to @channel. The response will be a JSON array with\n\t * one received message per item.\n\t *\n\t * Messages published on @channel since the last subscribe call\n\t * are returned. The first call will typically just establish\n\t * the context and return immediately with an empty response array.\n\t * Usually, you would issue the subscribe request in a loop. *\/\n\tvoid subscribe(const std::string &channel,\n\t\t\tlong timeout = -1, PubNub_subscribe_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Subscribe to a set of @channels. The response will contain\n\t * received messages from any of these channels; use the channels\n\t * callback parameter (or pubnub_sync_last_channels()) to determine\n\t * the originating channel of each message. *\/\n\tvoid subscribe_multi(const std::vector<std::string> &channels,\n\t\t\tlong timeout = -1, PubNub_subscribe_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* List the last @limit messages that appeared on a @channel.\n\t * You do not need to be subscribed to the channel. The response\n\t * will be a JSON array with one message per item. *\/\n\tvoid history(const std::string &channel, int limit,\n\t\t\tlong timeout = -1, PubNub_history_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* List the clients subscribed to @channel. The response will be\n\t * a JSON object with attributes \"occupancy\" (number of clients)\n\t * and \"uuids\" (array of client UUIDs). *\/\n\tvoid here_now(const std::string &channel,\n\t\t\tlong timeout = -1, PubNub_here_now_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Retrieve the server timestamp (number of microseconds since\n\t * 1970-01-01), stored as JSON value in the response. You can use\n\t * this as a sort of \"ping\" message e.g. to estimate network lag,\n\t * or if you do not trust the system time. *\/\n\tvoid time(long timeout = -1, PubNub_time_cb cb = NULL, void *cb_data = NULL);\n\nprotected:\n\tstruct pubnub *p;\n\tbool p_autodestroy;\n};\n\n#endif\n<commit_msg>libpubnub-cpp\/pubnub.hpp: Mention enum pubnub_res, referring pubnub.h<commit_after>#ifndef PUBNUB__PubNub_hpp\n#define PUBNUB__PubNub_hpp\n\n#include <string>\n#include <vector>\n\n#include <json.h>\n\n#include <pubnub.h>\n\n\n\/** PubNub structures and constants *\/\n\nstruct pubnub;\nclass PubNub;\n\n\n\/* The PubNub methods return result codes as listed in enum pubnub_res.\n * Please refer to pubnub.h for their listing and brief description. *\/\n\n\/* Callback functions to user code upon completion of various methods. *\/\n\/* Note that if the function wants to preserve the response, it should\n * bump its reference count, otherwise it will be auto-released after\n * callback is done. channels[], on the other hand, are dynamically\n * allocated and both the array and its individual items must be free()d\n * by the callee; to ease iteration by user code, there is guaranteed to\n * be as many elements as there are messages in the channels list, and\n * an extra NULL pointer at the end of the array. *\/\ntypedef void (*PubNub_publish_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_subscribe_cb)(PubNub &p, enum pubnub_res result, std::vector<std::string> &channels, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_history_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_here_now_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\ntypedef void (*PubNub_time_cb)(PubNub &p, enum pubnub_res result, json_object *response, void *ctx_data, void *call_data);\n\n\n\/* Only one method may operate on a single context at once - this means\n * that if a subscribe is in progress, you cannot publish in the same\n * context; either wait or use multiple contexts. If the same context\n * is used in multiple threads, the application must ensure locking to\n * prevent improper concurrent access. *\/\n\nclass PubNub {\npublic:\n\n\t\/** PubNub context methods *\/\n\n\t\/* Initialize the PubNub context and set the compulsory parameters\n\t * @publish_key and @subscribe_key.\n\t *\n\t * @cb is a set of callbacks implementing libpubnub's needs for\n\t * socket and timer handling, plus default completion callbacks\n\t * for the API requests. Typically, @cb value will be a structure\n\t * exported by one of the frontends and @cb_data will be the\n\t * appropriate frontend context. However, you can also customize\n\t * these or pass your own structure.\n\t *\n\t * This function will also initialize the libcurl library. This has\n\t * an important connotation for multi-threaded programs, as the first\n\t * call to this function will imply curl_global_init() call and that\n\t * function is completely thread unsafe. If you need to call\n\t * pubnub_init() with other threads already running (and not even\n\t * necessarily doing anything PubNub-related), call curl_global_init()\n\t * early before spawning other threads.\n\t *\n\t * One PubNub context can service only a single request at a time\n\t * (and you must not access it from multiple threads at once), however\n\t * you can maintain as many contexts as you wish. *\/\n\tPubNub(const std::string &publish_key, const std::string &subscribe_key,\n\t\tconst struct pubnub_callbacks *cb, void *cb_data);\n\n\t\/* You can also create a PubNub wrapper class from an existing pubnub\n\t * context. @p_autodestroy determines whether PubNub destructor will\n\t * call pubnub_done(p). *\/\n\tPubNub(struct pubnub *p, bool p_autodestroy = false);\n\n\t\/* Deinitialize our PubNub context, freeing all memory that is\n\t * associated with it. *\/\n\t~PubNub();\n\n\n\t\/* Set the secret key that is used for signing published messages\n\t * to confirm they are genuine. Using the secret key is optional. *\/\n\tvoid set_secret_key(const std::string &secret_key);\n\n\t\/* Set the cipher key that is used for symmetric encryption of messages\n\t * passed over the network (publish, subscribe, history). Using the\n\t * cipher key is optional. *\/\n\tvoid set_cipher_key(const std::string &cipher_key);\n\n\t\/* Set the origin server name. By default, http:\/\/pubsub.pubnub.com\/\n\t * is used. *\/\n\tvoid set_origin(const std::string &origin);\n\n\t\/* Retrieve the currently used UUID of this PubNub context. This UUID\n\t * is visible to other clients via the here_now call and is normally\n\t * autogenerated randomly during pubnub_init(). *\/\n\tstd::string current_uuid();\n\n\t\/* Set the UUID of this PubNub context that is asserted during the\n\t * subscribe call to identify us. This replaces the autogenerated\n\t * UUID. *\/\n\tvoid set_uuid(const std::string &uuid);\n\n\t\/* This function selects the value of CURLOPT_NOSIGNAL which involves\n\t * a tradeoff:\n\t *\n\t * (i) nosignal is true (DEFAULT) - the library is thread safe and does\n\t * not modify signal handlers, however timeout handling will be broken\n\t * with regards to DNS requests\n\t *\n\t * (ii) nosignal is false - DNS requests will be timing out properly,\n\t * but the library will install custom SIGPIPE (and possibly SIGCHLD)\n\t * handlers and won't be thread safe *\/\n\tvoid set_nosignal(bool nosignal);\n\n\t\/* Set PubNub error retry policy regarding error handling.\n\t *\n\t * The call may be retried if the error is possibly recoverable\n\t * and retry is enabled for that error. This is controlled by\n\t * @retry_mask; if PNR_xxx-th bit is set, the call is retried in case\n\t * of the PNR_xxx result; this is the case for recoverable errors,\n\t * specifically PNR_OK and PNR_OCCUPIED bits are always ignored (this\n\t * may be further extended in the future). For example,\n\t *\n\t * \tpubnub_error_policy(p, 0, ...);\n\t * will turn off automatic error retry for all errors,\n\t *\n\t * \tpubnub_error_policy(p, ~0, ...);\n\t * will turn it on for all recoverable errors (this is the DEFAULT),\n\t *\n\t * \tpubnub_error_policy(p, ~(1<<PNR_TIMEOUT), ...);\n\t * will turn it on for all errors *except* PNR_TIMEOUT, and so on.\n\t *\n\t * If the call is not automatically retried after an error, the error\n\t * is reported to the application via its specified callback instead\n\t * (if you use the pubnub_sync frontend, it can be obtained from\n\t * pubnub_last_result(); for future compatibility, you should ideally\n\t * check it even when relying on automatic error retry).\n\t *\n\t * A message about the error is printed on stderr if @print is true\n\t * (the DEFAULT); this applies even to errors after which we do not\n\t * retry for whatever reason. *\/\n\tvoid error_policy(unsigned int retry_mask, bool print);\n\n\n\t\/** PubNub API requests *\/\n\n\t\/* All the API request functions accept the @timeout [s] parameter\n\t * and callback parameters @cb and @cb_data.\n\t *\n\t * The @timeout [s] parameter describes how long to wait for request\n\t * fulfillment before the PNR_TIMEOUT error is generated. Supply -1\n\t * if in doubt to obtain the optimal default value. (Note that normally,\n\t * PNR_TIMEOUT will just print a message and retry the request; see\n\t * pubnub_error_policy() above.)\n\t *\n\t * If you are using the pubnub_sync frontend, the function calls\n\t * will block until the request is fulfilled and you should pass\n\t * NULL for @cb and @cb_data. If you are using the pubnub_libevent\n\t * or a custom frontend, the function calls will return immediately\n\t * and @cb shall point to a function that will be called upon\n\t * completion (with @cb_data as its last parameter). *\/\n\n\t\/* Publish the @message JSON object on @channel. The response\n\t * will usually be just a success confirmation. *\/\n\tvoid publish(const std::string &channel, json_object &message,\n\t\t\tlong timeout = -1, PubNub_publish_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Subscribe to @channel. The response will be a JSON array with\n\t * one received message per item.\n\t *\n\t * Messages published on @channel since the last subscribe call\n\t * are returned. The first call will typically just establish\n\t * the context and return immediately with an empty response array.\n\t * Usually, you would issue the subscribe request in a loop. *\/\n\tvoid subscribe(const std::string &channel,\n\t\t\tlong timeout = -1, PubNub_subscribe_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Subscribe to a set of @channels. The response will contain\n\t * received messages from any of these channels; use the channels\n\t * callback parameter (or pubnub_sync_last_channels()) to determine\n\t * the originating channel of each message. *\/\n\tvoid subscribe_multi(const std::vector<std::string> &channels,\n\t\t\tlong timeout = -1, PubNub_subscribe_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* List the last @limit messages that appeared on a @channel.\n\t * You do not need to be subscribed to the channel. The response\n\t * will be a JSON array with one message per item. *\/\n\tvoid history(const std::string &channel, int limit,\n\t\t\tlong timeout = -1, PubNub_history_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* List the clients subscribed to @channel. The response will be\n\t * a JSON object with attributes \"occupancy\" (number of clients)\n\t * and \"uuids\" (array of client UUIDs). *\/\n\tvoid here_now(const std::string &channel,\n\t\t\tlong timeout = -1, PubNub_here_now_cb cb = NULL, void *cb_data = NULL);\n\n\t\/* Retrieve the server timestamp (number of microseconds since\n\t * 1970-01-01), stored as JSON value in the response. You can use\n\t * this as a sort of \"ping\" message e.g. to estimate network lag,\n\t * or if you do not trust the system time. *\/\n\tvoid time(long timeout = -1, PubNub_time_cb cb = NULL, void *cb_data = NULL);\n\nprotected:\n\tstruct pubnub *p;\n\tbool p_autodestroy;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/foreach.hpp>\n#include \"bayesian\/graph.hpp\"\n#include \"bayesian\/bp.hpp\"\n\nnamespace bn {\n\nmatrix_type bp::operator()(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ 前後の要素に伝播させる\n auto const e_minus = propagate_forward(graph, node, condition);\n auto const e_plus = propagate_backward(graph, node, condition);\n\n \/\/ 掛け算\n auto const elem_num = node->selectable_num;\n double sum = 0.0;\n matrix_type mat(elem_num, 1);\n for(std::size_t i = 0; i < e_minus.height(); ++i)\n {\n double const product = e_minus[i][0] * e_plus[0][i];\n sum += product;\n mat[i][0] = product;\n }\n\n \/\/ 正規化\n for(std::size_t i = 0; i < e_minus.height(); ++i)\n {\n mat[i][0] \/= sum;\n }\n\n return mat;\n}\n\nstd::pair<bool, int> find_condition(\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n for(auto const& c : condition)\n {\n if(c.first == node)\n {\n return std::make_pair(true, c.second);\n }\n }\n\n return std::make_pair(false, 0);\n}\n\n\/\/ 下流要素の確率推論\nmatrix_type bp::propagate_forward(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ node ∈ condition\n auto is_condition = find_condition(node, condition);\n if(is_condition.first)\n {\n auto const elem_num = node->selectable_num;\n matrix_type mat(elem_num, 1);\n for(int i = 0; i < elem_num; ++i)\n {\n mat[i][0] = (i == is_condition.second) ? 1 : 0;\n }\n return mat;\n }\n\n \/\/ conditionに含まれないから伝播 (e-要素)\n auto const out_edges = graph.out_edges(node);\n if(!out_edges.empty())\n {\n auto const elem_num = node->selectable_num;\n matrix_type mat(elem_num, 1, 1);\n\n BOOST_FOREACH(auto const& edge, out_edges)\n {\n if(!edge->likelihood.first) throw std::runtime_error(\"no set edge of likelihood\");\n mat = mat % (edge->likelihood.second * propagate_forward(graph, graph.target(edge), condition));\n }\n\n return mat;\n }\n\n \/\/ 末端は全ての確率が等しいとする\n auto const elem_num = node->selectable_num;\n matrix_type mat(elem_num, 1);\n for(int i = 0; i < elem_num; ++i)\n {\n mat[i][0] = 1.0;\n }\n return mat;\n}\n\n\/\/ 上流要素の確率推論\nmatrix_type bp::propagate_backward(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ node ∈ condition\n auto is_condition = find_condition(node, condition);\n if(is_condition.first)\n {\n auto const elem_num = node->selectable_num;\n matrix_type mat(1, elem_num);\n for(int i = 0; i < elem_num; ++i)\n {\n mat[0][i] = (i == is_condition.second) ? 1 : 0;\n }\n return mat;\n }\n\n \/\/ conditionに含まれないから伝播 (e+要素)\n auto const in_edges = graph.in_edges(node);\n if(!in_edges.empty())\n {\n auto const elem_num = node->selectable_num;\n matrix_type mat(1, elem_num, 1);\n\n BOOST_FOREACH(auto const& edge, in_edges)\n {\n if(!edge->likelihood.first) throw std::runtime_error(\"no set edge of likelihood\");\n mat = mat % (propagate_backward(graph, graph.source(edge), condition) * edge->likelihood.second);\n }\n\n return mat;\n }\n\n \/\/ 最上位ノードは事前確率を割り当てる\n auto& e = node->evidence;\n if(e.first)\n {\n return e.second;\n }\n else\n {\n throw std::runtime_error(\"highest node doesn't have prior probability.\");\n }\n}\n\n} \/\/ namespace bn\n\n<commit_msg>refactoring: bp process's duplicated code.<commit_after>#include <boost\/foreach.hpp>\n#include \"bayesian\/graph.hpp\"\n#include \"bayesian\/bp.hpp\"\n\nnamespace bn {\n\nmatrix_type bp::operator()(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n \/\/ 前後の要素に伝播させる\n auto const e_minus = propagate_forward(graph, node, condition);\n auto const e_plus = propagate_backward(graph, node, condition);\n\n \/\/ 掛け算\n auto const elem_num = node->selectable_num;\n double sum = 0.0;\n matrix_type mat(elem_num, 1);\n for(std::size_t i = 0; i < e_minus.height(); ++i)\n {\n double const product = e_minus[i][0] * e_plus[0][i];\n sum += product;\n mat[i][0] = product;\n }\n\n \/\/ 正規化\n for(std::size_t i = 0; i < e_minus.height(); ++i)\n {\n mat[i][0] \/= sum;\n }\n\n return mat;\n}\n\nstd::pair<bool, int> find_condition(\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n for(auto const& c : condition)\n {\n if(c.first == node)\n {\n return std::make_pair(true, c.second);\n }\n }\n\n return std::make_pair(false, 0);\n}\n\n\/\/ 下流要素の確率推論\nmatrix_type bp::propagate_forward(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n auto const elem_num = node->selectable_num;\n matrix_type mat(elem_num, 1, 1);\n\n \/\/ node ∈ condition\n auto is_condition = find_condition(node, condition);\n if(is_condition.first)\n {\n for(int i = 0; i < elem_num; ++i)\n {\n mat[i][0] = (i == is_condition.second) ? 1 : 0;\n }\n return mat;\n }\n\n \/\/ conditionに含まれないから伝播 (e-要素)\n auto const out_edges = graph.out_edges(node);\n if(!out_edges.empty())\n {\n BOOST_FOREACH(auto const& edge, out_edges)\n {\n if(!edge->likelihood.first) throw std::runtime_error(\"no set edge of likelihood\");\n mat = mat % (edge->likelihood.second * propagate_forward(graph, graph.target(edge), condition));\n }\n\n return mat;\n }\n\n \/\/ 末端は全ての確率が等しいとする\n for(int i = 0; i < elem_num; ++i)\n {\n mat[i][0] = 1.0;\n }\n return mat;\n}\n\n\/\/ 上流要素の確率推論\nmatrix_type bp::propagate_backward(\n graph_t const& graph,\n vertex_type const& node,\n std::vector<std::pair<vertex_type, int>> const& condition\n )\n{\n auto const elem_num = node->selectable_num;\n matrix_type mat(1, elem_num, 1);\n\n \/\/ node ∈ condition\n auto is_condition = find_condition(node, condition);\n if(is_condition.first)\n {\n for(int i = 0; i < elem_num; ++i)\n {\n mat[0][i] = (i == is_condition.second) ? 1 : 0;\n }\n return mat;\n }\n\n \/\/ conditionに含まれないから伝播 (e+要素)\n auto const in_edges = graph.in_edges(node);\n if(!in_edges.empty())\n {\n BOOST_FOREACH(auto const& edge, in_edges)\n {\n if(!edge->likelihood.first) throw std::runtime_error(\"no set edge of likelihood\");\n mat = mat % (propagate_backward(graph, graph.source(edge), condition) * edge->likelihood.second);\n }\n\n return mat;\n }\n\n \/\/ 最上位ノードは事前確率を割り当てる\n auto& e = node->evidence;\n if(e.first)\n {\n return e.second;\n }\n else\n {\n throw std::runtime_error(\"highest node doesn't have prior probability.\");\n }\n}\n\n} \/\/ namespace bn\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Crystal Space input library\n Copyright (C) 1998 by Jorrit Tyberghein\n Written by Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"sysdef.h\"\n#include \"cssys\/system.h\"\n#include \"csinput\/csinput.h\"\n#include \"csutil\/inifile.h\"\n#include \"isystem.h\"\n\n\/\/ This array defines first 32..128 character codes with SHIFT key applied\nchar ShiftedKey [128-32] =\n{\n ' ', '!', '\"', '#', '$', '%', '&', '\"', '(', ')', '*', '+', '<', '_', '>', '?',\n ')', '!', '@', '#', '$', '%', '^', '&', '*', '(', ':', ':', '<', '+', '>', '?',\n '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',\n 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '^', '_',\n '~', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',\n 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127\n};\n\n\/\/ And this one performs backward conversion\nchar UnshiftedKey [128-32] =\n{\n ' ', '1', '\\'','3', '4', '5', '7', '\\'','9', '0', '8', '=', ',', '-', '.', '\/',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ';', ';', ',', '=', '.', '\/',\n '2', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\\\',']', '6', '-',\n '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\\\',']', '`', 127\n};\n\n\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/> Keyboard driver <--\/\/--\/\/\n\ncsKeyboardDriver::csKeyboardDriver ()\n{\n EventQueue = NULL;\n Reset ();\n}\n\ncsKeyboardDriver::~csKeyboardDriver ()\n{\n Close ();\n}\n\nbool csKeyboardDriver::Open (csEventQueue *EvQueue)\n{\n EventQueue = EvQueue;\n Reset ();\n return (EvQueue != NULL);\n}\n\nvoid csKeyboardDriver::Close ()\n{\n \/\/ no-op\n}\n\nvoid csKeyboardDriver::Reset ()\n{\n memset (KeyState, 0, sizeof (KeyState));\n}\n\nvoid csKeyboardDriver::do_keypress (time_t evtime, int key)\n{\n int smask = (GetKeyState (CSKEY_SHIFT) ? CSMASK_SHIFT : 0)\n | (GetKeyState (CSKEY_CTRL) ? CSMASK_CTRL : 0)\n | (GetKeyState (CSKEY_ALT) ? CSMASK_ALT : 0);\n if (!GetKeyState (key))\n smask |= CSMASK_FIRST;\n if ((key >= 32) && (key < 128))\n if (GetKeyState (CSKEY_SHIFT))\n key = ShiftedKey [key - 32];\n if (EventQueue)\n CHKB (EventQueue->Put (new csEvent (evtime, csevKeyDown, key, smask)));\n SetKeyState (key, true);\n}\n\nvoid csKeyboardDriver::do_keyrelease (time_t evtime, int key)\n{\n if ((key >= 32) && (key < 128))\n if (GetKeyState (CSKEY_SHIFT))\n key = ShiftedKey [key - 32];\n if (EventQueue)\n CHKB (EventQueue->Put (new csEvent (evtime, csevKeyUp, key, 0)));\n SetKeyState (key, false);\n}\n\nvoid csKeyboardDriver::SetKeyState (int key, bool state)\n{\n int idx = (key < 256) ? key : (256 + key - CSKEY_FIRST);\n KeyState [idx] = state;\n}\n\nbool csKeyboardDriver::GetKeyState (int key)\n{\n int idx = (key < 256) ? key : (256 + key - CSKEY_FIRST);\n return KeyState [idx];\n}\n\n\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--> Mouse driver <--\/\/--\/\/\n\ntime_t csMouseDriver::DoubleClickTime;\nsize_t csMouseDriver::DoubleClickDist;\n\ncsMouseDriver::csMouseDriver ()\n{\n EventQueue = NULL;\n Reset ();\n}\n\ncsMouseDriver::~csMouseDriver ()\n{\n Close ();\n}\n\nbool csMouseDriver::Open (iSystem* System, csEventQueue *EvQueue)\n{\n EventQueue = EvQueue;\n Reset ();\n DoubleClickTime = System->ConfigGetInt (\"MouseDriver\", \"DoubleClockTime\", 300);\n DoubleClickDist = System->ConfigGetInt (\"MouseDriver\", \"DoubleClickDist\", 2);\n LastMouseX = LastMouseY = -99999;\n return (EvQueue != NULL);\n}\n\nvoid csMouseDriver::Close ()\n{\n \/\/ no-op\n}\n\nvoid csMouseDriver::Reset ()\n{\n if (EventQueue)\n {\n for (int i = 1; i < 10; i++)\n if (Button[i])\n do_buttonrelease (SysGetTime (), i, 0, 0);\n }\n else\n memset (Button, 0, sizeof (Button));\n LastClickButton = -1;\n}\n\nvoid csMouseDriver::do_buttonpress (time_t evtime, int button, int x, int y, bool shift,\n bool alt, bool ctrl)\n{\n int smask = (shift ? CSMASK_SHIFT : 0)\n | (alt ? CSMASK_ALT : 0)\n | (ctrl ? CSMASK_CTRL : 0);\n Button [button] = true;\n\n int ev = csevMouseDown;\n\n if ((button == LastClickButton)\n && (evtime - LastClickTime <= DoubleClickTime)\n && (unsigned (ABS (x - LastClickX)) <= DoubleClickDist)\n && (unsigned (ABS (y - LastClickY)) <= DoubleClickDist))\n ev = csevMouseDoubleClick;\n LastClickButton = button;\n LastClickTime = evtime;\n LastMouseX = LastClickX = x;\n LastMouseY = LastClickY = y;\n\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, ev, x, y, button, smask)));\n }\n}\n\nvoid csMouseDriver::do_buttonrelease (time_t evtime, int button, int x, int y)\n{\n Button [button] = false;\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, csevMouseUp, x, y, button, 0)));\n }\n}\n\nvoid csMouseDriver::do_mousemotion (time_t evtime, int x, int y)\n{\n if ((x != LastMouseX)\n || (y != LastMouseY))\n {\n LastMouseX = x;\n LastMouseY = y;\n\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, csevMouseMove, x, y, 0, 0)));\n }\n }\n}\n<commit_msg>Added Event.Key.ShiftKeys filling for csKeyUp messages as suggested by W.C.A. Wijngaards <wouterw@karveel.cs.vu.nl><commit_after>\/*\n Crystal Space input library\n Copyright (C) 1998 by Jorrit Tyberghein\n Written by Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"sysdef.h\"\n#include \"cssys\/system.h\"\n#include \"csinput\/csinput.h\"\n#include \"csutil\/inifile.h\"\n#include \"isystem.h\"\n\n\/\/ This array defines first 32..128 character codes with SHIFT key applied\nchar ShiftedKey [128-32] =\n{\n ' ', '!', '\"', '#', '$', '%', '&', '\"', '(', ')', '*', '+', '<', '_', '>', '?',\n ')', '!', '@', '#', '$', '%', '^', '&', '*', '(', ':', ':', '<', '+', '>', '?',\n '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',\n 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '^', '_',\n '~', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',\n 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127\n};\n\n\/\/ And this one performs backward conversion\nchar UnshiftedKey [128-32] =\n{\n ' ', '1', '\\'','3', '4', '5', '7', '\\'','9', '0', '8', '=', ',', '-', '.', '\/',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ';', ';', ',', '=', '.', '\/',\n '2', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\\\',']', '6', '-',\n '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\\\',']', '`', 127\n};\n\n\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/> Keyboard driver <--\/\/--\/\/\n\ncsKeyboardDriver::csKeyboardDriver ()\n{\n EventQueue = NULL;\n Reset ();\n}\n\ncsKeyboardDriver::~csKeyboardDriver ()\n{\n Close ();\n}\n\nbool csKeyboardDriver::Open (csEventQueue *EvQueue)\n{\n EventQueue = EvQueue;\n Reset ();\n return (EvQueue != NULL);\n}\n\nvoid csKeyboardDriver::Close ()\n{\n \/\/ no-op\n}\n\nvoid csKeyboardDriver::Reset ()\n{\n memset (KeyState, 0, sizeof (KeyState));\n}\n\nvoid csKeyboardDriver::do_keypress (time_t evtime, int key)\n{\n int smask = (GetKeyState (CSKEY_SHIFT) ? CSMASK_SHIFT : 0)\n | (GetKeyState (CSKEY_CTRL) ? CSMASK_CTRL : 0)\n | (GetKeyState (CSKEY_ALT) ? CSMASK_ALT : 0);\n if (!GetKeyState (key))\n smask |= CSMASK_FIRST;\n if ((key >= 32) && (key < 128))\n if (GetKeyState (CSKEY_SHIFT))\n key = ShiftedKey [key - 32];\n if (EventQueue)\n CHKB (EventQueue->Put (new csEvent (evtime, csevKeyDown, key, smask)));\n SetKeyState (key, true);\n}\n\nvoid csKeyboardDriver::do_keyrelease (time_t evtime, int key)\n{\n int smask = (GetKeyState (CSKEY_SHIFT) ? CSMASK_SHIFT : 0)\n | (GetKeyState (CSKEY_CTRL) ? CSMASK_CTRL : 0)\n | (GetKeyState (CSKEY_ALT) ? CSMASK_ALT : 0);\n if ((key >= 32) && (key < 128))\n if (GetKeyState (CSKEY_SHIFT))\n key = ShiftedKey [key - 32];\n if (EventQueue)\n CHKB (EventQueue->Put (new csEvent (evtime, csevKeyUp, key, smask)));\n SetKeyState (key, false);\n}\n\nvoid csKeyboardDriver::SetKeyState (int key, bool state)\n{\n int idx = (key < 256) ? key : (256 + key - CSKEY_FIRST);\n KeyState [idx] = state;\n}\n\nbool csKeyboardDriver::GetKeyState (int key)\n{\n int idx = (key < 256) ? key : (256 + key - CSKEY_FIRST);\n return KeyState [idx];\n}\n\n\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--\/\/--> Mouse driver <--\/\/--\/\/\n\ntime_t csMouseDriver::DoubleClickTime;\nsize_t csMouseDriver::DoubleClickDist;\n\ncsMouseDriver::csMouseDriver ()\n{\n EventQueue = NULL;\n Reset ();\n}\n\ncsMouseDriver::~csMouseDriver ()\n{\n Close ();\n}\n\nbool csMouseDriver::Open (iSystem* System, csEventQueue *EvQueue)\n{\n EventQueue = EvQueue;\n Reset ();\n DoubleClickTime = System->ConfigGetInt (\"MouseDriver\", \"DoubleClockTime\", 300);\n DoubleClickDist = System->ConfigGetInt (\"MouseDriver\", \"DoubleClickDist\", 2);\n LastMouseX = LastMouseY = -99999;\n return (EvQueue != NULL);\n}\n\nvoid csMouseDriver::Close ()\n{\n \/\/ no-op\n}\n\nvoid csMouseDriver::Reset ()\n{\n if (EventQueue)\n {\n for (int i = 1; i < 10; i++)\n if (Button[i])\n do_buttonrelease (SysGetTime (), i, 0, 0);\n }\n else\n memset (Button, 0, sizeof (Button));\n LastClickButton = -1;\n}\n\nvoid csMouseDriver::do_buttonpress (time_t evtime, int button, int x, int y, bool shift,\n bool alt, bool ctrl)\n{\n int smask = (shift ? CSMASK_SHIFT : 0)\n | (alt ? CSMASK_ALT : 0)\n | (ctrl ? CSMASK_CTRL : 0);\n Button [button] = true;\n\n int ev = csevMouseDown;\n\n if ((button == LastClickButton)\n && (evtime - LastClickTime <= DoubleClickTime)\n && (unsigned (ABS (x - LastClickX)) <= DoubleClickDist)\n && (unsigned (ABS (y - LastClickY)) <= DoubleClickDist))\n ev = csevMouseDoubleClick;\n LastClickButton = button;\n LastClickTime = evtime;\n LastMouseX = LastClickX = x;\n LastMouseY = LastClickY = y;\n\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, ev, x, y, button, smask)));\n }\n}\n\nvoid csMouseDriver::do_buttonrelease (time_t evtime, int button, int x, int y)\n{\n Button [button] = false;\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, csevMouseUp, x, y, button, 0)));\n }\n}\n\nvoid csMouseDriver::do_mousemotion (time_t evtime, int x, int y)\n{\n if ((x != LastMouseX)\n || (y != LastMouseY))\n {\n LastMouseX = x;\n LastMouseY = y;\n\n if (EventQueue)\n {\n CHK (EventQueue->Put (new csEvent (evtime, csevMouseMove, x, y, 0, 0)));\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -fexceptions -fcxx-exceptions -fms-extensions -fms-compatibility -fms-compatibility-version=19 -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s\nstruct S {\n S();\n ~S();\n};\n\n\/\/ CHECK-DAG: @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\" = linkonce_odr thread_local global %struct.S zeroinitializer\n\/\/ CHECK-DAG: @\"\\01??__J?1??f@@YAAAUS@@XZ@51\" = linkonce_odr thread_local global i32 0\n\/\/ CHECK-DAG: @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\" = linkonce_odr global %struct.S zeroinitializer\n\/\/ CHECK-DAG: @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" = linkonce_odr global i32 0\n\/\/ CHECK-DAG: @_Init_thread_epoch = external thread_local global i32, align 4\n\n\/\/ CHECK-LABEL: define {{.*}} @\"\\01?f@@YAAAUS@@XZ\"()\nextern inline S &f() {\n static thread_local S s;\n\/\/ CHECK: %[[guard:.*]] = load i32, i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: %[[mask:.*]] = and i32 %[[guard]], 1\n\/\/ CHECK-NEXT: %[[cmp:.*]] = icmp ne i32 %[[mask]], 0\n\/\/ CHECK-NEXT: br i1 %[[cmp]], label %[[init_end:.*]], label %[[init:.*]]\n\/\/\n\/\/ CHECK: [[init]]:\n\/\/ CHECK-NEXT: %[[or:.*]] = or i32 %[[guard]], 1\n\/\/ CHECK-NEXT: store i32 %[[or]], i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: invoke {{.*}} @\"\\01??0S@@QAE@XZ\"(%struct.S* @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\")\n\/\/ CHECK-NEXT: to label %[[invoke_cont:.*]] unwind label %[[lpad:.*]]\n\/\/\n\/\/ CHECK: [[invoke_cont]]:\n\/\/ CHECK-NEXT: call i32 @__tlregdtor(void ()* @\"\\01??__Fs@?1??f@@YAAAUS@@XZ@YAXXZ\")\n\/\/ CHECK-NEXT: br label %[[init_end:.*]]\n\n\/\/ CHECK: [[init_end]]:\n\/\/ CHECK-NEXT: ret %struct.S* @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\"\n\n\/\/ CHECK: [[lpad:.*]]:\n\/\/ CHECK-NEXT: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)\n\/\/ CHECK-NEXT: cleanup\n\/\/ CHECK: %[[guard:.*]] = load i32, i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: %[[mask:.*]] = and i32 %[[guard]], -2\n\/\/ CHECK-NEXT: store i32 %[[mask]], i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: br label %[[eh_resume:.*]]\n\/\/\n\/\/ CHECK: [[eh_resume]]:\n\/\/ CHECK: resume { i8*, i32 }\n return s;\n}\n\n\n\/\/ CHECK-LABEL: define {{.*}} @\"\\01?g@@YAAAUS@@XZ\"()\nextern inline S &g() {\n static S s;\n\/\/ CHECK: %[[guard:.*]] = load atomic i32, i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" unordered, align 4\n\/\/ CHECK-NEXT: %[[epoch:.*]] = load i32, i32* @_Init_thread_epoch\n\/\/ CHECK-NEXT: %[[cmp:.*]] = icmp sgt i32 %[[guard]], %[[epoch]]\n\/\/ CHECK-NEXT: br i1 %[[cmp]], label %[[init_attempt:.*]], label %[[init_end:.*]]\n\/\/\n\/\/ CHECK: [[init_attempt]]:\n\/\/ CHECK-NEXT: call void @_Init_thread_header(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: %[[guard2:.*]] = load atomic i32, i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" unordered, align 4\n\/\/ CHECK-NEXT: %[[cmp2:.*]] = icmp eq i32 %[[guard2]], -1\n\/\/ CHECK-NEXT: br i1 %[[cmp2]], label %[[init:.*]], label %[[init_end:.*]]\n\/\/\n\/\/ CHECK: [[init]]:\n\/\/ CHECK-NEXT: invoke {{.*}} @\"\\01??0S@@QAE@XZ\"(%struct.S* @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\")\n\/\/ CHECK-NEXT: to label %[[invoke_cont:.*]] unwind label %[[lpad:.*]]\n\/\/\n\/\/ CHECK: [[invoke_cont]]:\n\/\/ CHECK-NEXT: call i32 @atexit(void ()* @\"\\01??__Fs@?1??g@@YAAAUS@@XZ@YAXXZ\")\n\/\/ CHECK-NEXT: call void @_Init_thread_footer(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: br label %init.end\n\/\/\n\/\/ CHECK: [[init_end]]:\n\/\/ CHECK-NEXT: ret %struct.S* @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\"\n\/\/\n\/\/ CHECK: [[lpad]]:\n\/\/ CHECK: call void @_Init_thread_abort(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: br label %[[eh_resume:.*]]\n\/\/\n\/\/ CHECK: [[eh_resume]]:\n\/\/ CHECK: resume { i8*, i32 }\n return s;\n}\n<commit_msg>Mark clang\/test\/CodeGenCXX\/microsoft-abi-thread-safe-statics.cpp as REQUIRES:asserts. It relies on label names.<commit_after>\/\/ RUN: %clang_cc1 -fexceptions -fcxx-exceptions -fms-extensions -fms-compatibility -fms-compatibility-version=19 -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s\nstruct S {\n S();\n ~S();\n};\n\n\/\/ CHECK-DAG: @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\" = linkonce_odr thread_local global %struct.S zeroinitializer\n\/\/ CHECK-DAG: @\"\\01??__J?1??f@@YAAAUS@@XZ@51\" = linkonce_odr thread_local global i32 0\n\/\/ CHECK-DAG: @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\" = linkonce_odr global %struct.S zeroinitializer\n\/\/ CHECK-DAG: @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" = linkonce_odr global i32 0\n\/\/ CHECK-DAG: @_Init_thread_epoch = external thread_local global i32, align 4\n\n\/\/ CHECK-LABEL: define {{.*}} @\"\\01?f@@YAAAUS@@XZ\"()\nextern inline S &f() {\n static thread_local S s;\n\/\/ CHECK: %[[guard:.*]] = load i32, i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: %[[mask:.*]] = and i32 %[[guard]], 1\n\/\/ CHECK-NEXT: %[[cmp:.*]] = icmp ne i32 %[[mask]], 0\n\/\/ CHECK-NEXT: br i1 %[[cmp]], label %[[init_end:.*]], label %[[init:.*]]\n\/\/\n\/\/ CHECK: [[init]]:\n\/\/ CHECK-NEXT: %[[or:.*]] = or i32 %[[guard]], 1\n\/\/ CHECK-NEXT: store i32 %[[or]], i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: invoke {{.*}} @\"\\01??0S@@QAE@XZ\"(%struct.S* @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\")\n\/\/ CHECK-NEXT: to label %[[invoke_cont:.*]] unwind label %[[lpad:.*]]\n\/\/\n\/\/ CHECK: [[invoke_cont]]:\n\/\/ CHECK-NEXT: call i32 @__tlregdtor(void ()* @\"\\01??__Fs@?1??f@@YAAAUS@@XZ@YAXXZ\")\n\/\/ CHECK-NEXT: br label %[[init_end:.*]]\n\n\/\/ CHECK: [[init_end]]:\n\/\/ CHECK-NEXT: ret %struct.S* @\"\\01?s@?1??f@@YAAAUS@@XZ@4U2@A\"\n\n\/\/ CHECK: [[lpad:.*]]:\n\/\/ CHECK-NEXT: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)\n\/\/ CHECK-NEXT: cleanup\n\/\/ CHECK: %[[guard:.*]] = load i32, i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: %[[mask:.*]] = and i32 %[[guard]], -2\n\/\/ CHECK-NEXT: store i32 %[[mask]], i32* @\"\\01??__J?1??f@@YAAAUS@@XZ@51\"\n\/\/ CHECK-NEXT: br label %[[eh_resume:.*]]\n\/\/\n\/\/ CHECK: [[eh_resume]]:\n\/\/ CHECK: resume { i8*, i32 }\n return s;\n}\n\n\n\/\/ CHECK-LABEL: define {{.*}} @\"\\01?g@@YAAAUS@@XZ\"()\nextern inline S &g() {\n static S s;\n\/\/ CHECK: %[[guard:.*]] = load atomic i32, i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" unordered, align 4\n\/\/ CHECK-NEXT: %[[epoch:.*]] = load i32, i32* @_Init_thread_epoch\n\/\/ CHECK-NEXT: %[[cmp:.*]] = icmp sgt i32 %[[guard]], %[[epoch]]\n\/\/ CHECK-NEXT: br i1 %[[cmp]], label %[[init_attempt:.*]], label %[[init_end:.*]]\n\/\/\n\/\/ CHECK: [[init_attempt]]:\n\/\/ CHECK-NEXT: call void @_Init_thread_header(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: %[[guard2:.*]] = load atomic i32, i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\" unordered, align 4\n\/\/ CHECK-NEXT: %[[cmp2:.*]] = icmp eq i32 %[[guard2]], -1\n\/\/ CHECK-NEXT: br i1 %[[cmp2]], label %[[init:.*]], label %[[init_end:.*]]\n\/\/\n\/\/ CHECK: [[init]]:\n\/\/ CHECK-NEXT: invoke {{.*}} @\"\\01??0S@@QAE@XZ\"(%struct.S* @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\")\n\/\/ CHECK-NEXT: to label %[[invoke_cont:.*]] unwind label %[[lpad:.*]]\n\/\/\n\/\/ CHECK: [[invoke_cont]]:\n\/\/ CHECK-NEXT: call i32 @atexit(void ()* @\"\\01??__Fs@?1??g@@YAAAUS@@XZ@YAXXZ\")\n\/\/ CHECK-NEXT: call void @_Init_thread_footer(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: br label %init.end\n\/\/\n\/\/ CHECK: [[init_end]]:\n\/\/ CHECK-NEXT: ret %struct.S* @\"\\01?s@?1??g@@YAAAUS@@XZ@4U2@A\"\n\/\/\n\/\/ CHECK: [[lpad]]:\n\/\/ CHECK: call void @_Init_thread_abort(i32* @\"\\01?$TSS0@?1??g@@YAAAUS@@XZ\")\n\/\/ CHECK-NEXT: br label %[[eh_resume:.*]]\n\/\/\n\/\/ CHECK: [[eh_resume]]:\n\/\/ CHECK: resume { i8*, i32 }\n return s;\n}\n\n\/\/ REQUIRES: asserts\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %check_clang_tidy %s misc-suspicious-enum-usage %t -- -config=\"{CheckOptions: [{key: misc-suspicious-enum-usage.StrictMode, value: 1}]}\" --\n\nenum A {\n A = 1,\n B = 2,\n C = 4,\n D = 8,\n E = 16,\n F = 32,\n G = 63\n};\n\n\/\/ CHECK-MESSAGES: :[[@LINE+2]]:1: warning: enum type seems like a bitmask (contains mostly power-of-2 literals) but a literal is not power-of-2\n\/\/ CHECK-MESSAGES: :76:7: note: used here as a bitmask\nenum X {\n X = 8,\n Y = 16,\n Z = 4,\n ZZ = 3\n \/\/ CHECK-MESSAGES: :[[@LINE-1]]:3: warning: enum type seems like a bitmask (contains mostly power-of-2 literals), but this literal is not a power-of-2 [misc-suspicious-enum-usage]\n\/\/ CHECK-MESSAGES: :70:13: note: used here as a bitmask\n};\n\/\/ CHECK-MESSAGES: :[[@LINE+2]]:1: warning: enum type seems like a bitmask (contains mostly power-of-2 literals) but some literals are not power-of-2\n\/\/ CHECK-MESSAGES: :73:8: note: used here as a bitmask\nenum PP {\n P = 2,\n Q = 3,\n \/\/ CHECK-MESSAGES: :[[@LINE-1]]:3: warning: enum type seems like a bitmask (contains mostly power-of-2 literals), but this literal is not a power-of-2\n \/\/ CHECK-MESSAGES: :65:11: note: used here as a bitmask\n R = 4,\n S = 8,\n T = 16,\n U = 31\n};\n\nenum {\n H,\n I,\n J,\n K,\n L\n};\n\nenum Days {\n Monday,\n Tuesday,\n Wednesday,\n Thursday,\n Friday,\n Saturday,\n Sunday\n};\n\nDays bestDay() {\n return Friday;\n}\n\nint trigger() {\n if (bestDay() | A)\n return 1;\n \/\/ CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different enum types\n if (I | Y)\n return 1;\n \/\/ CHECK-MESSAGES: :[[@LINE-2]]:9: warning: enum values are from different enum types\n if (P + Q == R)\n return 1;\n else if ((Q | R) == T)\n return 1;\n else\n int k = ZZ | Z;\n unsigned p = R;\n PP pp = Q;\n p |= pp;\n \n enum X x = Z;\n p = x | Z;\n return 0;\n}\n\nint dont_trigger() {\n int a = 1, b = 5;\n int c = a + b;\n int d = c | H, e = b * a;\n a = B | C;\n b = X | Z;\n\n unsigned bitflag;\n enum A aa = B;\n bitflag = aa | C;\n\n if (Tuesday != Monday + 1 ||\n Friday - Thursday != 1 ||\n Sunday + Wednesday == (Sunday | Wednesday))\n return 1;\n if (H + I + L == 42)\n return 1;\n return 42;\n}\n<commit_msg>Fix another nondeterminism in a tidy test.<commit_after>\/\/ RUN: %check_clang_tidy %s misc-suspicious-enum-usage %t -- -config=\"{CheckOptions: [{key: misc-suspicious-enum-usage.StrictMode, value: 1}]}\" --\n\nenum A {\n A = 1,\n B = 2,\n C = 4,\n D = 8,\n E = 16,\n F = 32,\n G = 63\n};\n\n\/\/ CHECK-MESSAGES: :[[@LINE+2]]:1: warning: enum type seems like a bitmask (contains mostly power-of-2 literals) but a literal is not power-of-2\n\/\/ CHECK-MESSAGES: :76:7: note: used here as a bitmask\nenum X {\n X = 8,\n Y = 16,\n Z = 4,\n ZZ = 3\n \/\/ CHECK-MESSAGES: :[[@LINE-1]]:3: warning: enum type seems like a bitmask (contains mostly power-of-2 literals), but this literal is not a power-of-2 [misc-suspicious-enum-usage]\n\/\/ CHECK-MESSAGES: :70:13: note: used here as a bitmask\n};\n\/\/ CHECK-MESSAGES: :[[@LINE+2]]:1: warning: enum type seems like a bitmask (contains mostly power-of-2 literals) but some literals are not power-of-2\n\/\/ CHECK-MESSAGES: :73:8: note: used here as a bitmask\nenum PP {\n P = 2,\n Q = 3,\n \/\/ CHECK-MESSAGES: :[[@LINE-1]]:3: warning: enum type seems like a bitmask (contains mostly power-of-2 literals), but this literal is not a power-of-2\n \/\/ CHECK-MESSAGES: :65:11: note: used here as a bitmask\n R = 4,\n S = 8,\n T = 16,\n U = 31\n};\n\nenum {\n H,\n I,\n J,\n K,\n L\n};\n\nenum Days {\n Monday,\n Tuesday,\n Wednesday,\n Thursday,\n Friday,\n Saturday,\n Sunday\n};\n\nDays bestDay() {\n return Friday;\n}\n\nint trigger() {\n if (bestDay() | A)\n return 1;\n \/\/ CHECK-MESSAGES: :[[@LINE-2]]:17: warning: enum values are from different enum types\n if (I | Y)\n return 1;\n \/\/ CHECK-MESSAGES: :[[@LINE-2]]:9: warning: enum values are from different enum types\n if (P + Q == R)\n return 1;\n else if ((S | R) == T)\n return 1;\n else\n int k = ZZ | Z;\n unsigned p = R;\n PP pp = Q;\n p |= pp;\n \n enum X x = Z;\n p = x | Z;\n return 0;\n}\n\nint dont_trigger() {\n int a = 1, b = 5;\n int c = a + b;\n int d = c | H, e = b * a;\n a = B | C;\n b = X | Z;\n\n unsigned bitflag;\n enum A aa = B;\n bitflag = aa | C;\n\n if (Tuesday != Monday + 1 ||\n Friday - Thursday != 1 ||\n Sunday + Wednesday == (Sunday | Wednesday))\n return 1;\n if (H + I + L == 42)\n return 1;\n return 42;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/textfield\/textfield.h\"\n\n#if defined(OS_LINUX)\n#include <gdk\/gdkkeysyms.h>\n#endif\n\n#include \"app\/gfx\/insets.h\"\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#include \"base\/win_util.h\"\n#endif\n\n#include \"base\/keyboard_codes.h\"\n#include \"base\/string_util.h\"\n#include \"views\/controls\/textfield\/native_textfield_wrapper.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n\/\/ TODO(beng): this should be removed when the OS_WIN hack from\n\/\/ ViewHierarchyChanged is removed.\n#include \"views\/controls\/textfield\/native_textfield_win.h\"\n#endif\n\nnamespace views {\n\n\/\/ static\nconst char Textfield::kViewClassName[] = \"views\/Textfield\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield\n\nTextfield::Textfield()\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(STYLE_DEFAULT),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::Textfield(StyleFlags style)\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(style),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::~Textfield() {\n}\n\nvoid Textfield::SetController(Controller* controller) {\n controller_ = controller;\n}\n\nTextfield::Controller* Textfield::GetController() const {\n return controller_;\n}\n\nvoid Textfield::SetReadOnly(bool read_only) {\n read_only_ = read_only;\n if (native_wrapper_) {\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n }\n}\n\nbool Textfield::IsPassword() const {\n return style_ & STYLE_PASSWORD;\n}\n\nbool Textfield::IsMultiLine() const {\n return !!(style_ & STYLE_MULTILINE);\n}\n\nvoid Textfield::SetText(const string16& text) {\n text_ = text;\n if (native_wrapper_)\n native_wrapper_->UpdateText();\n}\n\nvoid Textfield::AppendText(const string16& text) {\n text_ += text;\n if (native_wrapper_)\n native_wrapper_->AppendText(text);\n}\n\nvoid Textfield::SelectAll() {\n if (native_wrapper_)\n native_wrapper_->SelectAll();\n}\n\nstring16 Textfield::GetSelectedText() const {\n if (native_wrapper_)\n return native_wrapper_->GetSelectedText();\n return string16();\n}\n\nvoid Textfield::ClearSelection() const {\n if (native_wrapper_)\n native_wrapper_->ClearSelection();\n}\n\nvoid Textfield::SetTextColor(SkColor color) {\n text_color_ = color;\n use_default_text_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::UseDefaultTextColor() {\n use_default_text_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::SetBackgroundColor(SkColor color) {\n background_color_ = color;\n use_default_background_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::UseDefaultBackgroundColor() {\n use_default_background_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::SetFont(const gfx::Font& font) {\n font_ = font;\n if (native_wrapper_)\n native_wrapper_->UpdateFont();\n}\n\nvoid Textfield::SetHorizontalMargins(int left, int right) {\n if (native_wrapper_)\n native_wrapper_->SetHorizontalMargins(left, right);\n}\n\nvoid Textfield::SetHeightInLines(int num_lines) {\n DCHECK(IsMultiLine());\n num_lines_ = num_lines;\n}\n\nvoid Textfield::RemoveBorder() {\n if (!draw_border_)\n return;\n\n draw_border_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBorder();\n}\n\n\nvoid Textfield::SyncText() {\n if (native_wrapper_)\n text_ = native_wrapper_->GetText();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield, View overrides:\n\nvoid Textfield::Layout() {\n if (native_wrapper_) {\n native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));\n native_wrapper_->GetView()->Layout();\n }\n}\n\ngfx::Size Textfield::GetPreferredSize() {\n gfx::Insets insets;\n if (draw_border_ && native_wrapper_)\n insets = native_wrapper_->CalculateInsets();\n return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +\n insets.width(),\n num_lines_ * font_.height() + insets.height());\n}\n\nbool Textfield::IsFocusable() const {\n return IsEnabled() && !read_only_;\n}\n\nvoid Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {\n SelectAll();\n}\n\nbool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {\n#if defined(OS_WIN)\n \/\/ TODO(hamaji): Figure out which keyboard combinations we need to add here,\n \/\/ similar to LocationBarView::SkipDefaultKeyEventProcessing.\n base::KeyboardCode key = e.GetKeyCode();\n if (key == base::VKEY_BACK)\n return true; \/\/ We'll handle BackSpace ourselves.\n\n \/\/ We don't translate accelerators for ALT + NumPad digit, they are used for\n \/\/ entering special characters. We do translate alt-home.\n if (e.IsAltDown() && (key != base::VKEY_HOME) &&\n win_util::IsNumPadDigit(key, e.IsExtendedKey()))\n return true;\n#endif\n return false;\n}\n\nvoid Textfield::SetEnabled(bool enabled) {\n View::SetEnabled(enabled);\n if (native_wrapper_)\n native_wrapper_->UpdateEnabled();\n}\n\nvoid Textfield::Focus() {\n if (native_wrapper_) {\n \/\/ Forward the focus to the wrapper if it exists.\n native_wrapper_->SetFocus();\n } else {\n \/\/ If there is no wrapper, cause the RootView to be focused so that we still\n \/\/ get keyboard messages.\n View::Focus();\n }\n}\n\nvoid Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {\n initialized_ = true;\n\n \/\/ The native wrapper's lifetime will be managed by the view hierarchy after\n \/\/ we call AddChildView.\n native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);\n AddChildView(native_wrapper_->GetView());\n \/\/ TODO(beng): Move this initialization to NativeTextfieldWin once it\n \/\/ subclasses NativeControlWin.\n native_wrapper_->UpdateText();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateFont();\n native_wrapper_->UpdateEnabled();\n native_wrapper_->UpdateBorder();\n\n#if defined(OS_WIN)\n \/\/ TODO(beng): remove this once NativeTextfieldWin subclasses\n \/\/ NativeControlWin. This is currently called to perform post-AddChildView\n \/\/ initialization for the wrapper. The GTK version subclasses things\n \/\/ correctly and doesn't need this.\n \/\/\n \/\/ Remove the include for native_textfield_win.h above when you fix this.\n static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();\n#endif\n }\n}\n\nstd::string Textfield::GetClassName() const {\n return kViewClassName;\n}\n\nNativeTextfieldWrapper* Textfield::CreateWrapper() {\n NativeTextfieldWrapper* native_wrapper =\n NativeTextfieldWrapper::CreateWrapper(this);\n\n native_wrapper->UpdateText();\n native_wrapper->UpdateBackgroundColor();\n native_wrapper->UpdateReadOnly();\n native_wrapper->UpdateFont();\n native_wrapper->UpdateEnabled();\n native_wrapper->UpdateBorder();\n\n return native_wrapper;\n}\n\nbase::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {\n#if defined(OS_WIN)\n return static_cast<base::KeyboardCode>(key_);\n#else\n return static_cast<base::KeyboardCode>(event_.keyval);\n#endif\n}\n\n#if defined(OS_WIN)\nbool Textfield::Keystroke::IsControlHeld() const {\n return win_util::IsCtrlPressed();\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return win_util::IsShiftPressed();\n}\n#else\nbool Textfield::Keystroke::IsControlHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_CONTROL_MASK;\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_SHIFT_MASK;\n}\n#endif\n\n} \/\/ namespace views\n<commit_msg>Backspace should not be processed as an accelerator in textfield, so it really removes the previous character.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/textfield\/textfield.h\"\n\n#if defined(OS_LINUX)\n#include <gdk\/gdkkeysyms.h>\n#endif\n\n#include \"app\/gfx\/insets.h\"\n#if defined(OS_WIN)\n#include \"app\/win_util.h\"\n#include \"base\/win_util.h\"\n#endif\n\n#include \"base\/keyboard_codes.h\"\n#include \"base\/string_util.h\"\n#include \"views\/controls\/textfield\/native_textfield_wrapper.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n\/\/ TODO(beng): this should be removed when the OS_WIN hack from\n\/\/ ViewHierarchyChanged is removed.\n#include \"views\/controls\/textfield\/native_textfield_win.h\"\n#endif\n\nnamespace views {\n\n\/\/ static\nconst char Textfield::kViewClassName[] = \"views\/Textfield\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield\n\nTextfield::Textfield()\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(STYLE_DEFAULT),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::Textfield(StyleFlags style)\n : native_wrapper_(NULL),\n controller_(NULL),\n style_(style),\n read_only_(false),\n default_width_in_chars_(0),\n draw_border_(true),\n text_color_(SK_ColorBLACK),\n use_default_text_color_(true),\n background_color_(SK_ColorWHITE),\n use_default_background_color_(true),\n num_lines_(1),\n initialized_(false) {\n SetFocusable(true);\n}\n\nTextfield::~Textfield() {\n}\n\nvoid Textfield::SetController(Controller* controller) {\n controller_ = controller;\n}\n\nTextfield::Controller* Textfield::GetController() const {\n return controller_;\n}\n\nvoid Textfield::SetReadOnly(bool read_only) {\n read_only_ = read_only;\n if (native_wrapper_) {\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n }\n}\n\nbool Textfield::IsPassword() const {\n return style_ & STYLE_PASSWORD;\n}\n\nbool Textfield::IsMultiLine() const {\n return !!(style_ & STYLE_MULTILINE);\n}\n\nvoid Textfield::SetText(const string16& text) {\n text_ = text;\n if (native_wrapper_)\n native_wrapper_->UpdateText();\n}\n\nvoid Textfield::AppendText(const string16& text) {\n text_ += text;\n if (native_wrapper_)\n native_wrapper_->AppendText(text);\n}\n\nvoid Textfield::SelectAll() {\n if (native_wrapper_)\n native_wrapper_->SelectAll();\n}\n\nstring16 Textfield::GetSelectedText() const {\n if (native_wrapper_)\n return native_wrapper_->GetSelectedText();\n return string16();\n}\n\nvoid Textfield::ClearSelection() const {\n if (native_wrapper_)\n native_wrapper_->ClearSelection();\n}\n\nvoid Textfield::SetTextColor(SkColor color) {\n text_color_ = color;\n use_default_text_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::UseDefaultTextColor() {\n use_default_text_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateTextColor();\n}\n\nvoid Textfield::SetBackgroundColor(SkColor color) {\n background_color_ = color;\n use_default_background_color_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::UseDefaultBackgroundColor() {\n use_default_background_color_ = true;\n if (native_wrapper_)\n native_wrapper_->UpdateBackgroundColor();\n}\n\nvoid Textfield::SetFont(const gfx::Font& font) {\n font_ = font;\n if (native_wrapper_)\n native_wrapper_->UpdateFont();\n}\n\nvoid Textfield::SetHorizontalMargins(int left, int right) {\n if (native_wrapper_)\n native_wrapper_->SetHorizontalMargins(left, right);\n}\n\nvoid Textfield::SetHeightInLines(int num_lines) {\n DCHECK(IsMultiLine());\n num_lines_ = num_lines;\n}\n\nvoid Textfield::RemoveBorder() {\n if (!draw_border_)\n return;\n\n draw_border_ = false;\n if (native_wrapper_)\n native_wrapper_->UpdateBorder();\n}\n\n\nvoid Textfield::SyncText() {\n if (native_wrapper_)\n text_ = native_wrapper_->GetText();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Textfield, View overrides:\n\nvoid Textfield::Layout() {\n if (native_wrapper_) {\n native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));\n native_wrapper_->GetView()->Layout();\n }\n}\n\ngfx::Size Textfield::GetPreferredSize() {\n gfx::Insets insets;\n if (draw_border_ && native_wrapper_)\n insets = native_wrapper_->CalculateInsets();\n return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +\n insets.width(),\n num_lines_ * font_.height() + insets.height());\n}\n\nbool Textfield::IsFocusable() const {\n return IsEnabled() && !read_only_;\n}\n\nvoid Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {\n SelectAll();\n}\n\nbool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {\n \/\/ TODO(hamaji): Figure out which keyboard combinations we need to add here,\n \/\/ similar to LocationBarView::SkipDefaultKeyEventProcessing.\n base::KeyboardCode key = e.GetKeyCode();\n if (key == base::VKEY_BACK)\n return true; \/\/ We'll handle BackSpace ourselves.\n\n#if defined(OS_WIN)\n \/\/ We don't translate accelerators for ALT + NumPad digit on Windows, they are\n \/\/ used for entering special characters. We do translate alt-home.\n if (e.IsAltDown() && (key != base::VKEY_HOME) &&\n win_util::IsNumPadDigit(key, e.IsExtendedKey()))\n return true;\n#endif\n return false;\n}\n\nvoid Textfield::SetEnabled(bool enabled) {\n View::SetEnabled(enabled);\n if (native_wrapper_)\n native_wrapper_->UpdateEnabled();\n}\n\nvoid Textfield::Focus() {\n if (native_wrapper_) {\n \/\/ Forward the focus to the wrapper if it exists.\n native_wrapper_->SetFocus();\n } else {\n \/\/ If there is no wrapper, cause the RootView to be focused so that we still\n \/\/ get keyboard messages.\n View::Focus();\n }\n}\n\nvoid Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {\n initialized_ = true;\n\n \/\/ The native wrapper's lifetime will be managed by the view hierarchy after\n \/\/ we call AddChildView.\n native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);\n AddChildView(native_wrapper_->GetView());\n \/\/ TODO(beng): Move this initialization to NativeTextfieldWin once it\n \/\/ subclasses NativeControlWin.\n native_wrapper_->UpdateText();\n native_wrapper_->UpdateTextColor();\n native_wrapper_->UpdateBackgroundColor();\n native_wrapper_->UpdateReadOnly();\n native_wrapper_->UpdateFont();\n native_wrapper_->UpdateEnabled();\n native_wrapper_->UpdateBorder();\n\n#if defined(OS_WIN)\n \/\/ TODO(beng): remove this once NativeTextfieldWin subclasses\n \/\/ NativeControlWin. This is currently called to perform post-AddChildView\n \/\/ initialization for the wrapper. The GTK version subclasses things\n \/\/ correctly and doesn't need this.\n \/\/\n \/\/ Remove the include for native_textfield_win.h above when you fix this.\n static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();\n#endif\n }\n}\n\nstd::string Textfield::GetClassName() const {\n return kViewClassName;\n}\n\nNativeTextfieldWrapper* Textfield::CreateWrapper() {\n NativeTextfieldWrapper* native_wrapper =\n NativeTextfieldWrapper::CreateWrapper(this);\n\n native_wrapper->UpdateText();\n native_wrapper->UpdateBackgroundColor();\n native_wrapper->UpdateReadOnly();\n native_wrapper->UpdateFont();\n native_wrapper->UpdateEnabled();\n native_wrapper->UpdateBorder();\n\n return native_wrapper;\n}\n\nbase::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {\n#if defined(OS_WIN)\n return static_cast<base::KeyboardCode>(key_);\n#else\n return static_cast<base::KeyboardCode>(event_.keyval);\n#endif\n}\n\n#if defined(OS_WIN)\nbool Textfield::Keystroke::IsControlHeld() const {\n return win_util::IsCtrlPressed();\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return win_util::IsShiftPressed();\n}\n#else\nbool Textfield::Keystroke::IsControlHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_CONTROL_MASK;\n}\n\nbool Textfield::Keystroke::IsShiftHeld() const {\n return (event_.state & gtk_accelerator_get_default_mod_mask()) ==\n GDK_SHIFT_MASK;\n}\n#endif\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"RendererOGLLinux.h\"\n#include \"core\/linux\/WindowLinux.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RendererOGLLinux::~RendererOGLLinux()\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(window);\n Display* display = windowLinux->getDisplay();\n\n if (display && context)\n {\n if (!glXMakeCurrent(display, None, nullptr))\n {\n Log(Log::Level::ERR) << \"Failed to unset GLX context\";\n }\n\n glXDestroyContext(display, context);\n }\n }\n\n bool RendererOGLLinux::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n PixelFormat newBackBufferFormat,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(newWindow);\n Display* display = windowLinux->getDisplay();\n\n \/\/ make sure OpenGL's GLX extension supported\n int dummy;\n if (!glXQueryExtension(display, &dummy, &dummy))\n {\n Log(Log::Level::ERR) << \"X server has no OpenGL GLX extension\";\n return false;\n }\n\n Screen* screen = XDefaultScreenOfDisplay(display);\n int screenIndex = XScreenNumberOfScreen(screen);\n\n int fbcount = 0;\n\n static const int attributes[] = {\n GLX_X_RENDERABLE, GL_TRUE,\n GLX_RENDER_TYPE, GLX_RGBA_BIT,\n GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,\n GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,\n GLX_DOUBLEBUFFER, GL_TRUE,\n GLX_RED_SIZE, 8,\n GLX_GREEN_SIZE, 8,\n GLX_BLUE_SIZE, 8,\n GLX_DEPTH_SIZE, newDepth ? 24 : 0,\n GLX_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n GLX_SAMPLES, static_cast<int>(newSampleCount),\n 0\n };\n\n std::unique_ptr<GLXFBConfig, int(*)(void*)> framebufferConfig(glXChooseFBConfig(display, screenIndex, attributes, &fbcount), XFree);\n if (!framebufferConfig)\n {\n Log(Log::Level::ERR) << \"Failed to get frame buffer\";\n }\n else\n {\n \/\/ create an OpenGL rendering context\n std::vector<int> contextAttribs = {\n GLX_CONTEXT_PROFILE_MASK_ARB,\n GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n GLX_CONTEXT_MAJOR_VERSION_ARB, 3,\n GLX_CONTEXT_MINOR_VERSION_ARB, 2\n };\n\n if (newDebugRenderer)\n {\n contextAttribs.push_back(GL_CONTEXT_FLAGS);\n contextAttribs.push_back(GLX_DEBUG_CONTEXT_BIT);\n }\n\n contextAttribs.push_back(0);\n\n PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>(\"glXCreateContextAttribsARB\")));\n\n if (glXCreateContextAttribsARB)\n {\n context = glXCreateContextAttribsARB(display, *framebufferConfig, NULL, GL_TRUE, contextAttribs.data());\n\n if (context)\n {\n apiMajorVersion = 3;\n apiMinorVersion = 2;\n Log(Log::Level::INFO) << \"GLX OpenGL 3.2 context created\";\n }\n }\n }\n\n if (!context)\n {\n context = glXCreateContext(display, windowLinux->getVisualInfo(), None, GL_TRUE);\n\n if (context)\n {\n apiMajorVersion = 2;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"GLX OpenGL 2 context created\";\n }\n else\n {\n Log(Log::Level::ERR) << \"Failed to create GLX context\";\n return false;\n }\n }\n\n \/\/ bind the rendering context to the window\n if (!glXMakeCurrent(display, windowLinux->getNativeWindow(), context))\n {\n Log(Log::Level::ERR) << \"Failed to make GLX context current\";\n return false;\n }\n\n PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddress(reinterpret_cast<const GLubyte*>(\"glXSwapIntervalEXT\"));\n\n if (glXSwapIntervalEXT)\n {\n glXSwapIntervalEXT(display, windowLinux->getNativeWindow(), newVerticalSync ? 1 : 0);\n }\n\n return RendererOGL::init(newWindow,\n newSize,\n newSampleCount,\n newTextureFilter,\n newMaxAnisotropy,\n newBackBufferFormat,\n newVerticalSync,\n newDepth,\n newDebugRenderer);\n }\n\n bool RendererOGLLinux::swapBuffers()\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(window);\n\n glXSwapBuffers(windowLinux->getDisplay(), windowLinux->getNativeWindow());\n\n return true;\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<commit_msg>Pass GL_CONTEXT_FLAG_DEBUG_BIT to OpenGL renderer on Linux<commit_after>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"RendererOGLLinux.h\"\n#include \"core\/linux\/WindowLinux.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RendererOGLLinux::~RendererOGLLinux()\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(window);\n Display* display = windowLinux->getDisplay();\n\n if (display && context)\n {\n if (!glXMakeCurrent(display, None, nullptr))\n {\n Log(Log::Level::ERR) << \"Failed to unset GLX context\";\n }\n\n glXDestroyContext(display, context);\n }\n }\n\n bool RendererOGLLinux::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n PixelFormat newBackBufferFormat,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(newWindow);\n Display* display = windowLinux->getDisplay();\n\n \/\/ make sure OpenGL's GLX extension supported\n int dummy;\n if (!glXQueryExtension(display, &dummy, &dummy))\n {\n Log(Log::Level::ERR) << \"X server has no OpenGL GLX extension\";\n return false;\n }\n\n Screen* screen = XDefaultScreenOfDisplay(display);\n int screenIndex = XScreenNumberOfScreen(screen);\n\n int fbcount = 0;\n\n static const int attributes[] = {\n GLX_X_RENDERABLE, GL_TRUE,\n GLX_RENDER_TYPE, GLX_RGBA_BIT,\n GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,\n GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,\n GLX_DOUBLEBUFFER, GL_TRUE,\n GLX_RED_SIZE, 8,\n GLX_GREEN_SIZE, 8,\n GLX_BLUE_SIZE, 8,\n GLX_DEPTH_SIZE, newDepth ? 24 : 0,\n GLX_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n GLX_SAMPLES, static_cast<int>(newSampleCount),\n 0\n };\n\n std::unique_ptr<GLXFBConfig, int(*)(void*)> framebufferConfig(glXChooseFBConfig(display, screenIndex, attributes, &fbcount), XFree);\n if (!framebufferConfig)\n {\n Log(Log::Level::ERR) << \"Failed to get frame buffer\";\n }\n else\n {\n \/\/ create an OpenGL rendering context\n std::vector<int> contextAttribs = {\n GLX_CONTEXT_PROFILE_MASK_ARB,\n GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n GLX_CONTEXT_MAJOR_VERSION_ARB, 3,\n GLX_CONTEXT_MINOR_VERSION_ARB, 2\n };\n\n if (newDebugRenderer)\n {\n contextAttribs.push_back(GL_CONTEXT_FLAGS);\n contextAttribs.push_back(GL_CONTEXT_FLAG_DEBUG_BIT);\n }\n\n contextAttribs.push_back(0);\n\n PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>(\"glXCreateContextAttribsARB\")));\n\n if (glXCreateContextAttribsARB)\n {\n context = glXCreateContextAttribsARB(display, *framebufferConfig, NULL, GL_TRUE, contextAttribs.data());\n\n if (context)\n {\n apiMajorVersion = 3;\n apiMinorVersion = 2;\n Log(Log::Level::INFO) << \"GLX OpenGL 3.2 context created\";\n }\n }\n }\n\n if (!context)\n {\n context = glXCreateContext(display, windowLinux->getVisualInfo(), None, GL_TRUE);\n\n if (context)\n {\n apiMajorVersion = 2;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"GLX OpenGL 2 context created\";\n }\n else\n {\n Log(Log::Level::ERR) << \"Failed to create GLX context\";\n return false;\n }\n }\n\n \/\/ bind the rendering context to the window\n if (!glXMakeCurrent(display, windowLinux->getNativeWindow(), context))\n {\n Log(Log::Level::ERR) << \"Failed to make GLX context current\";\n return false;\n }\n\n PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = reinterpret_cast<PFNGLXSWAPINTERVALEXTPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>(\"glXSwapIntervalEXT\")));\n\n if (glXSwapIntervalEXT)\n {\n glXSwapIntervalEXT(display, windowLinux->getNativeWindow(), newVerticalSync ? 1 : 0);\n }\n\n return RendererOGL::init(newWindow,\n newSize,\n newSampleCount,\n newTextureFilter,\n newMaxAnisotropy,\n newBackBufferFormat,\n newVerticalSync,\n newDepth,\n newDebugRenderer);\n }\n\n bool RendererOGLLinux::swapBuffers()\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(window);\n\n glXSwapBuffers(windowLinux->getDisplay(), windowLinux->getNativeWindow());\n\n return true;\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/quic\/quic_crypto_client_stream.h\"\n\n#include \"net\/quic\/crypto\/crypto_protocol.h\"\n#include \"net\/quic\/crypto\/crypto_utils.h\"\n#include \"net\/quic\/crypto\/null_encrypter.h\"\n#include \"net\/quic\/crypto\/proof_verifier.h\"\n#include \"net\/quic\/quic_protocol.h\"\n#include \"net\/quic\/quic_session.h\"\n\nnamespace net {\n\nQuicCryptoClientStream::QuicCryptoClientStream(\n const string& server_hostname,\n const QuicConfig& config,\n QuicSession* session,\n QuicCryptoClientConfig* crypto_config)\n : QuicCryptoStream(session),\n next_state_(STATE_IDLE),\n num_client_hellos_(0),\n config_(config),\n crypto_config_(crypto_config),\n server_hostname_(server_hostname) {\n}\n\nQuicCryptoClientStream::~QuicCryptoClientStream() {\n}\n\nvoid QuicCryptoClientStream::OnHandshakeMessage(\n const CryptoHandshakeMessage& message) {\n DoHandshakeLoop(&message);\n}\n\nbool QuicCryptoClientStream::CryptoConnect() {\n next_state_ = STATE_SEND_CHLO;\n DoHandshakeLoop(NULL);\n return true;\n}\n\nint QuicCryptoClientStream::num_sent_client_hellos() const {\n return num_client_hellos_;\n}\n\n\/\/ kMaxClientHellos is the maximum number of times that we'll send a client\n\/\/ hello. The value 3 accounts for:\n\/\/ * One failure due to an incorrect or missing source-address token.\n\/\/ * One failure due the server's certificate chain being unavailible and the\n\/\/ server being unwilling to send it without a valid source-address token.\nstatic const int kMaxClientHellos = 3;\n\nvoid QuicCryptoClientStream::DoHandshakeLoop(\n const CryptoHandshakeMessage* in) {\n CryptoHandshakeMessage out;\n QuicErrorCode error;\n string error_details;\n QuicCryptoClientConfig::CachedState* cached =\n crypto_config_->LookupOrCreate(server_hostname_);\n\n if (in != NULL) {\n DLOG(INFO) << \"Client received: \" << in->DebugString();\n }\n\n for (;;) {\n const State state = next_state_;\n next_state_ = STATE_IDLE;\n switch (state) {\n case STATE_SEND_CHLO: {\n if (num_client_hellos_ > kMaxClientHellos) {\n CloseConnection(QUIC_CRYPTO_TOO_MANY_REJECTS);\n return;\n }\n num_client_hellos_++;\n\n if (!cached->is_complete()) {\n crypto_config_->FillInchoateClientHello(\n server_hostname_, cached, &crypto_negotiated_params_, &out);\n next_state_ = STATE_RECV_REJ;\n DLOG(INFO) << \"Client Sending: \" << out.DebugString();\n SendHandshakeMessage(out);\n return;\n }\n const CryptoHandshakeMessage* scfg = cached->GetServerConfig();\n config_.ToHandshakeMessage(&out);\n error = crypto_config_->FillClientHello(\n server_hostname_,\n session()->connection()->guid(),\n cached,\n session()->connection()->clock()->WallNow(),\n session()->connection()->random_generator(),\n &crypto_negotiated_params_,\n &out,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n error = config_.ProcessFinalPeerHandshake(\n *scfg, CryptoUtils::PEER_PRIORITY, &negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n next_state_ = STATE_RECV_SHLO;\n DLOG(INFO) << \"Client Sending: \" << out.DebugString();\n SendHandshakeMessage(out);\n \/\/ Be prepared to decrypt with the new server write key.\n session()->connection()->SetAlternativeDecrypter(\n crypto_negotiated_params_.initial_crypters.decrypter.release(),\n true \/* latch once used *\/);\n \/\/ Send subsequent packets under encryption on the assumption that the\n \/\/ server will accept the handshake.\n session()->connection()->SetEncrypter(\n ENCRYPTION_INITIAL,\n crypto_negotiated_params_.initial_crypters.encrypter.release());\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_INITIAL);\n if (!encryption_established_) {\n \/\/ TODO(agl): the following, commented code should live here and not\n \/\/ down when the handshake is confirmed. However, it causes\n \/\/ EndToEndTest.LargePost to be flaky (b\/8074678), seemingly because\n \/\/ the packets dropped when the client hello is dropped cause the\n \/\/ congestion control to be too conservative and the server times\n \/\/ out.\n \/\/ session()->OnCryptoHandshakeEvent(\n \/\/ QuicSession::ENCRYPTION_FIRST_ESTABLISHED);\n \/\/ encryption_established_ = true;\n } else {\n session()->OnCryptoHandshakeEvent(\n QuicSession::ENCRYPTION_REESTABLISHED);\n }\n return;\n }\n case STATE_RECV_REJ:\n \/\/ We sent a dummy CHLO because we didn't have enough information to\n \/\/ perform a handshake, or we sent a full hello that the server\n \/\/ rejected. Here we hope to have a REJ that contains the information\n \/\/ that we need.\n if (in->tag() != kREJ) {\n CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,\n \"Expected REJ\");\n return;\n }\n error = crypto_config_->ProcessRejection(cached, *in,\n &crypto_negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n if (!cached->proof_valid()) {\n const ProofVerifier* verifier = crypto_config_->proof_verifier();\n if (!verifier) {\n \/\/ If no verifier is set then we don't check the certificates.\n cached->SetProofValid();\n } else if (!cached->signature().empty()) {\n \/\/ TODO(rtenneti): In Chromium, we will need to make VerifyProof()\n \/\/ asynchronous.\n if (!verifier->VerifyProof(server_hostname_,\n cached->server_config(),\n cached->certs(),\n cached->signature(),\n &error_details)) {\n CloseConnectionWithDetails(QUIC_PROOF_INVALID,\n \"Proof invalid: \" + error_details);\n return;\n }\n cached->SetProofValid();\n }\n }\n \/\/ Send the subsequent client hello in plaintext.\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_NONE);\n next_state_ = STATE_SEND_CHLO;\n break;\n case STATE_RECV_SHLO: {\n \/\/ We sent a CHLO that we expected to be accepted and now we're hoping\n \/\/ for a SHLO from the server to confirm that.\n if (in->tag() == kREJ) {\n \/\/ alternative_decrypter will be NULL if the original alternative\n \/\/ decrypter latched and became the primary decrypter. That happens\n \/\/ if we received a message encrypted with the INITIAL key.\n if (session()->connection()->alternative_decrypter() == NULL) {\n \/\/ The rejection was sent encrypted!\n CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,\n \"encrypted REJ message\");\n return;\n }\n next_state_ = STATE_RECV_REJ;\n break;\n }\n if (in->tag() != kSHLO) {\n CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,\n \"Expected SHLO or REJ\");\n return;\n }\n \/\/ alternative_decrypter will be NULL if the original alternative\n \/\/ decrypter latched and became the primary decrypter. That happens\n \/\/ if we received a message encrypted with the INITIAL key.\n if (session()->connection()->alternative_decrypter() != NULL) {\n \/\/ The server hello was sent without encryption.\n CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,\n \"unencrypted SHLO message\");\n return;\n }\n error = crypto_config_->ProcessServerHello(\n *in, session()->connection()->guid(), &crypto_negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(\n error, \"Server hello invalid: \" + error_details);\n return;\n }\n CrypterPair* crypters =\n &crypto_negotiated_params_.forward_secure_crypters;\n \/\/ TODO(agl): we don't currently latch this decrypter because the idea\n \/\/ has been floated that the server shouldn't send packets encrypted\n \/\/ with the FORWARD_SECURE key until it receives a FORWARD_SECURE\n \/\/ packet from the client.\n session()->connection()->SetAlternativeDecrypter(\n crypters->decrypter.release(), false \/* don't latch *\/);\n session()->connection()->SetEncrypter(\n ENCRYPTION_FORWARD_SECURE, crypters->encrypter.release());\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_FORWARD_SECURE);\n\n \/\/ TODO(agl): this code shouldn't be here. See the TODO further up\n \/\/ about it.\n session()->OnCryptoHandshakeEvent(\n QuicSession::ENCRYPTION_FIRST_ESTABLISHED);\n encryption_established_ = true;\n\n handshake_confirmed_ = true;\n session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED);\n return;\n }\n case STATE_IDLE:\n \/\/ This means that the peer sent us a message that we weren't expecting.\n CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE);\n return;\n }\n }\n}\n\n} \/\/ namespace net\n<commit_msg>Set encryption_established_ to true in QuicCryptoClientStream before calling OnCryptoHandshakeEvent of the session.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/quic\/quic_crypto_client_stream.h\"\n\n#include \"net\/quic\/crypto\/crypto_protocol.h\"\n#include \"net\/quic\/crypto\/crypto_utils.h\"\n#include \"net\/quic\/crypto\/null_encrypter.h\"\n#include \"net\/quic\/crypto\/proof_verifier.h\"\n#include \"net\/quic\/quic_protocol.h\"\n#include \"net\/quic\/quic_session.h\"\n\nnamespace net {\n\nQuicCryptoClientStream::QuicCryptoClientStream(\n const string& server_hostname,\n const QuicConfig& config,\n QuicSession* session,\n QuicCryptoClientConfig* crypto_config)\n : QuicCryptoStream(session),\n next_state_(STATE_IDLE),\n num_client_hellos_(0),\n config_(config),\n crypto_config_(crypto_config),\n server_hostname_(server_hostname) {\n}\n\nQuicCryptoClientStream::~QuicCryptoClientStream() {\n}\n\nvoid QuicCryptoClientStream::OnHandshakeMessage(\n const CryptoHandshakeMessage& message) {\n DoHandshakeLoop(&message);\n}\n\nbool QuicCryptoClientStream::CryptoConnect() {\n next_state_ = STATE_SEND_CHLO;\n DoHandshakeLoop(NULL);\n return true;\n}\n\nint QuicCryptoClientStream::num_sent_client_hellos() const {\n return num_client_hellos_;\n}\n\n\/\/ kMaxClientHellos is the maximum number of times that we'll send a client\n\/\/ hello. The value 3 accounts for:\n\/\/ * One failure due to an incorrect or missing source-address token.\n\/\/ * One failure due the server's certificate chain being unavailible and the\n\/\/ server being unwilling to send it without a valid source-address token.\nstatic const int kMaxClientHellos = 3;\n\nvoid QuicCryptoClientStream::DoHandshakeLoop(\n const CryptoHandshakeMessage* in) {\n CryptoHandshakeMessage out;\n QuicErrorCode error;\n string error_details;\n QuicCryptoClientConfig::CachedState* cached =\n crypto_config_->LookupOrCreate(server_hostname_);\n\n if (in != NULL) {\n DLOG(INFO) << \"Client received: \" << in->DebugString();\n }\n\n for (;;) {\n const State state = next_state_;\n next_state_ = STATE_IDLE;\n switch (state) {\n case STATE_SEND_CHLO: {\n if (num_client_hellos_ > kMaxClientHellos) {\n CloseConnection(QUIC_CRYPTO_TOO_MANY_REJECTS);\n return;\n }\n num_client_hellos_++;\n\n if (!cached->is_complete()) {\n crypto_config_->FillInchoateClientHello(\n server_hostname_, cached, &crypto_negotiated_params_, &out);\n next_state_ = STATE_RECV_REJ;\n DLOG(INFO) << \"Client Sending: \" << out.DebugString();\n SendHandshakeMessage(out);\n return;\n }\n const CryptoHandshakeMessage* scfg = cached->GetServerConfig();\n config_.ToHandshakeMessage(&out);\n error = crypto_config_->FillClientHello(\n server_hostname_,\n session()->connection()->guid(),\n cached,\n session()->connection()->clock()->WallNow(),\n session()->connection()->random_generator(),\n &crypto_negotiated_params_,\n &out,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n error = config_.ProcessFinalPeerHandshake(\n *scfg, CryptoUtils::PEER_PRIORITY, &negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n next_state_ = STATE_RECV_SHLO;\n DLOG(INFO) << \"Client Sending: \" << out.DebugString();\n SendHandshakeMessage(out);\n \/\/ Be prepared to decrypt with the new server write key.\n session()->connection()->SetAlternativeDecrypter(\n crypto_negotiated_params_.initial_crypters.decrypter.release(),\n true \/* latch once used *\/);\n \/\/ Send subsequent packets under encryption on the assumption that the\n \/\/ server will accept the handshake.\n session()->connection()->SetEncrypter(\n ENCRYPTION_INITIAL,\n crypto_negotiated_params_.initial_crypters.encrypter.release());\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_INITIAL);\n if (!encryption_established_) {\n \/\/ TODO(agl): the following, commented code should live here and not\n \/\/ down when the handshake is confirmed. However, it causes\n \/\/ EndToEndTest.LargePost to be flaky (b\/8074678), seemingly because\n \/\/ the packets dropped when the client hello is dropped cause the\n \/\/ congestion control to be too conservative and the server times\n \/\/ out.\n \/\/ encryption_established_ = true;\n \/\/ session()->OnCryptoHandshakeEvent(\n \/\/ QuicSession::ENCRYPTION_FIRST_ESTABLISHED);\n } else {\n session()->OnCryptoHandshakeEvent(\n QuicSession::ENCRYPTION_REESTABLISHED);\n }\n return;\n }\n case STATE_RECV_REJ:\n \/\/ We sent a dummy CHLO because we didn't have enough information to\n \/\/ perform a handshake, or we sent a full hello that the server\n \/\/ rejected. Here we hope to have a REJ that contains the information\n \/\/ that we need.\n if (in->tag() != kREJ) {\n CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,\n \"Expected REJ\");\n return;\n }\n error = crypto_config_->ProcessRejection(cached, *in,\n &crypto_negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(error, error_details);\n return;\n }\n if (!cached->proof_valid()) {\n const ProofVerifier* verifier = crypto_config_->proof_verifier();\n if (!verifier) {\n \/\/ If no verifier is set then we don't check the certificates.\n cached->SetProofValid();\n } else if (!cached->signature().empty()) {\n \/\/ TODO(rtenneti): In Chromium, we will need to make VerifyProof()\n \/\/ asynchronous.\n if (!verifier->VerifyProof(server_hostname_,\n cached->server_config(),\n cached->certs(),\n cached->signature(),\n &error_details)) {\n CloseConnectionWithDetails(QUIC_PROOF_INVALID,\n \"Proof invalid: \" + error_details);\n return;\n }\n cached->SetProofValid();\n }\n }\n \/\/ Send the subsequent client hello in plaintext.\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_NONE);\n next_state_ = STATE_SEND_CHLO;\n break;\n case STATE_RECV_SHLO: {\n \/\/ We sent a CHLO that we expected to be accepted and now we're hoping\n \/\/ for a SHLO from the server to confirm that.\n if (in->tag() == kREJ) {\n \/\/ alternative_decrypter will be NULL if the original alternative\n \/\/ decrypter latched and became the primary decrypter. That happens\n \/\/ if we received a message encrypted with the INITIAL key.\n if (session()->connection()->alternative_decrypter() == NULL) {\n \/\/ The rejection was sent encrypted!\n CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,\n \"encrypted REJ message\");\n return;\n }\n next_state_ = STATE_RECV_REJ;\n break;\n }\n if (in->tag() != kSHLO) {\n CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,\n \"Expected SHLO or REJ\");\n return;\n }\n \/\/ alternative_decrypter will be NULL if the original alternative\n \/\/ decrypter latched and became the primary decrypter. That happens\n \/\/ if we received a message encrypted with the INITIAL key.\n if (session()->connection()->alternative_decrypter() != NULL) {\n \/\/ The server hello was sent without encryption.\n CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,\n \"unencrypted SHLO message\");\n return;\n }\n error = crypto_config_->ProcessServerHello(\n *in, session()->connection()->guid(), &crypto_negotiated_params_,\n &error_details);\n if (error != QUIC_NO_ERROR) {\n CloseConnectionWithDetails(\n error, \"Server hello invalid: \" + error_details);\n return;\n }\n CrypterPair* crypters =\n &crypto_negotiated_params_.forward_secure_crypters;\n \/\/ TODO(agl): we don't currently latch this decrypter because the idea\n \/\/ has been floated that the server shouldn't send packets encrypted\n \/\/ with the FORWARD_SECURE key until it receives a FORWARD_SECURE\n \/\/ packet from the client.\n session()->connection()->SetAlternativeDecrypter(\n crypters->decrypter.release(), false \/* don't latch *\/);\n session()->connection()->SetEncrypter(\n ENCRYPTION_FORWARD_SECURE, crypters->encrypter.release());\n session()->connection()->SetDefaultEncryptionLevel(\n ENCRYPTION_FORWARD_SECURE);\n\n \/\/ TODO(agl): this code shouldn't be here. See the TODO further up\n \/\/ about it.\n encryption_established_ = true;\n session()->OnCryptoHandshakeEvent(\n QuicSession::ENCRYPTION_FIRST_ESTABLISHED);\n\n handshake_confirmed_ = true;\n session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED);\n return;\n }\n case STATE_IDLE:\n \/\/ This means that the peer sent us a message that we weren't expecting.\n CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE);\n return;\n }\n }\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: BinomialBlurImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The \\doxygen{BinomialBlurImageFilter} computes a nearest neighbor average\n\/\/ along each dimension. The process is repeated a number of times, as\n\/\/ specified by the user. In principle, after a large number of iterations\n\/\/ the result will approach the convolution with a Gaussian.\n\/\/\n\/\/ \\index{itk::Binomial\\-Blur\\-Image\\-Filter}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ \\index{itk::BinomialBlurImageFilter!header}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBinomialBlurImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 4 ) \n { \n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile numberOfRepetitions\" << std::endl;\n return 1;\n }\n\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Types should be chosen for the pixels of the input and output images.\n \/\/ Image types can be instantiated using the pixel type and dimension.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type is now instantiated using both the input image and the\n \/\/ output image types. Then a filter object is created.\n \/\/\n \/\/ \\index{itk::BinomialBlurImageFilter!instantiation}\n \/\/ \\index{itk::BinomialBlurImageFilter!New()}\n \/\/ \\index{itk::BinomialBlurImageFilter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::BinomialBlurImageFilter<\n InputImageType, OutputImageType > FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n const unsigned int repetitions = atoi( argv[3] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input image can be obtained from the output of another filter. Here,\n \/\/ an image reader is used as the source. The number of repetitions is set with\n \/\/ the \\code{SetRepetitions()} method. Computation time will\n \/\/ increase linearly with the number of repetitions selected. Finally, the\n \/\/ filter can be executed by calling the \\code{Update()} method.\n \/\/\n \/\/ \\index{itk::BinomialBlurImageFilter!Update()}\n \/\/ \\index{itk::BinomialBlurImageFilter!SetInput()}\n \/\/ \\index{itk::BinomialBlurImageFilter!SetRepetitions()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput( reader->GetOutput() );\n filter->SetRepetitions( repetitions );\n filter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ This section connects the filter output to a writer \n \/\/\n typedef unsigned char WritePixelType;\n typedef itk::Image< WritePixelType, 2 > WriteImageType;\n typedef itk::RescaleIntensityImageFilter< \n OutputImageType, WriteImageType > RescaleFilterType;\n\n RescaleFilterType::Pointer rescaler = RescaleFilterType::New();\n rescaler->SetOutputMinimum( 0 );\n rescaler->SetOutputMaximum( 255 );\n\n typedef itk::ImageFileWriter< WriteImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n\n writer->SetFileName( argv[2] );\n rescaler->SetInput( filter->GetOutput() );\n writer->SetInput( rescaler->GetOutput() );\n writer->Update();\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{BrainProtonDensitySlice.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{BinomialBlurImageFilterOutput.eps}\n \/\/ \\itkcaption[BinomialBlurImageFilter output.]{Effect of the\n \/\/ BinomialBlurImageFilter on a slice from a MRI proton density image of the\n \/\/ brain.}\n \/\/ \\label{fig:BinomialBlurImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Figure \\ref{fig:BinomialBlurImageFilterInputOutput} illustrates the\n \/\/ effect of this filter on a MRI proton density image of the brain. \n \/\/ \n \/\/ Note that the standard deviation $\\sigma$ of the equivalent Gaussian is\n \/\/ fixed. In the spatial spectrum, the effect of every iteration of this\n \/\/ filter is like a multiplication with a sinus cardinal function.\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n return 0;\n}\n\n<commit_msg>ENH: Command line tags for automatic generation of figures in Software guide<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: BinomialBlurImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {BrainProtonDensitySlice.png}\n\/\/ OUTPUTS: {BinomialBlurImageFilterOutput.png}\n\/\/ 5\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The \\doxygen{BinomialBlurImageFilter} computes a nearest neighbor average\n\/\/ along each dimension. The process is repeated a number of times, as\n\/\/ specified by the user. In principle, after a large number of iterations\n\/\/ the result will approach the convolution with a Gaussian.\n\/\/\n\/\/ \\index{itk::Binomial\\-Blur\\-Image\\-Filter}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ \\index{itk::BinomialBlurImageFilter!header}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBinomialBlurImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 4 ) \n { \n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile numberOfRepetitions\" << std::endl;\n return 1;\n }\n\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Types should be chosen for the pixels of the input and output images.\n \/\/ Image types can be instantiated using the pixel type and dimension.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type is now instantiated using both the input image and the\n \/\/ output image types. Then a filter object is created.\n \/\/\n \/\/ \\index{itk::BinomialBlurImageFilter!instantiation}\n \/\/ \\index{itk::BinomialBlurImageFilter!New()}\n \/\/ \\index{itk::BinomialBlurImageFilter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::BinomialBlurImageFilter<\n InputImageType, OutputImageType > FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n const unsigned int repetitions = atoi( argv[3] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input image can be obtained from the output of another filter. Here,\n \/\/ an image reader is used as the source. The number of repetitions is set with\n \/\/ the \\code{SetRepetitions()} method. Computation time will\n \/\/ increase linearly with the number of repetitions selected. Finally, the\n \/\/ filter can be executed by calling the \\code{Update()} method.\n \/\/\n \/\/ \\index{itk::BinomialBlurImageFilter!Update()}\n \/\/ \\index{itk::BinomialBlurImageFilter!SetInput()}\n \/\/ \\index{itk::BinomialBlurImageFilter!SetRepetitions()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput( reader->GetOutput() );\n filter->SetRepetitions( repetitions );\n filter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ This section connects the filter output to a writer \n \/\/\n typedef unsigned char WritePixelType;\n typedef itk::Image< WritePixelType, 2 > WriteImageType;\n typedef itk::RescaleIntensityImageFilter< \n OutputImageType, WriteImageType > RescaleFilterType;\n\n RescaleFilterType::Pointer rescaler = RescaleFilterType::New();\n rescaler->SetOutputMinimum( 0 );\n rescaler->SetOutputMaximum( 255 );\n\n typedef itk::ImageFileWriter< WriteImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n\n writer->SetFileName( argv[2] );\n rescaler->SetInput( filter->GetOutput() );\n writer->SetInput( rescaler->GetOutput() );\n writer->Update();\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{BrainProtonDensitySlice.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{BinomialBlurImageFilterOutput.eps}\n \/\/ \\itkcaption[BinomialBlurImageFilter output.]{Effect of the\n \/\/ BinomialBlurImageFilter on a slice from a MRI proton density image of the\n \/\/ brain.}\n \/\/ \\label{fig:BinomialBlurImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Figure \\ref{fig:BinomialBlurImageFilterInputOutput} illustrates the\n \/\/ effect of this filter on a MRI proton density image of the brain. \n \/\/ \n \/\/ Note that the standard deviation $\\sigma$ of the equivalent Gaussian is\n \/\/ fixed. In the spatial spectrum, the effect of every iteration of this\n \/\/ filter is like a multiplication with a sinus cardinal function.\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n\n#include \"chrome\/browser\/nacl_host\/nacl_process_host.h\"\n\n#if defined(OS_POSIX)\n#include <fcntl.h>\n#endif\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/nacl_cmd_line.h\"\n#include \"chrome\/common\/nacl_messages.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/browser\/renderer_host\/chrome_render_message_filter.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"native_client\/src\/shared\/imc\/nacl_imc.h\"\n\n#if defined(OS_POSIX)\n#include \"ipc\/ipc_channel_posix.h\"\n#elif defined(OS_WIN)\n#include \"chrome\/browser\/nacl_host\/nacl_broker_service_win.h\"\n#endif\n\nnamespace {\n\n#if !defined(DISABLE_NACL)\nvoid SetCloseOnExec(nacl::Handle fd) {\n#if defined(OS_POSIX)\n int flags = fcntl(fd, F_GETFD);\n CHECK(flags != -1);\n int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);\n CHECK(rc == 0);\n#endif\n}\n#endif\n\n} \/\/ namespace\n\nstruct NaClProcessHost::NaClInternal {\n std::vector<nacl::Handle> sockets_for_renderer;\n std::vector<nacl::Handle> sockets_for_sel_ldr;\n};\n\nNaClProcessHost::NaClProcessHost(const std::wstring& url)\n : BrowserChildProcessHost(NACL_LOADER_PROCESS),\n reply_msg_(NULL),\n internal_(new NaClInternal()),\n running_on_wow64_(false),\n ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)) {\n set_name(WideToUTF16Hack(url));\n#if defined(OS_WIN)\n running_on_wow64_ = (base::win::OSInfo::GetInstance()->wow64_status() ==\n base::win::OSInfo::WOW64_ENABLED);\n#endif\n}\n\nNaClProcessHost::~NaClProcessHost() {\n \/\/ nacl::Close() is not available at link time if DISABLE_NACL is\n \/\/ defined, but we still compile a bunch of other code from this\n \/\/ file anyway. TODO(mseaborn): Make this less messy.\n#ifndef DISABLE_NACL\n for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {\n if (nacl::Close(internal_->sockets_for_renderer[i]) != 0) {\n LOG(ERROR) << \"nacl::Close() failed\";\n }\n }\n for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {\n if (nacl::Close(internal_->sockets_for_sel_ldr[i]) != 0) {\n LOG(ERROR) << \"nacl::Close() failed\";\n }\n }\n#endif\n\n if (reply_msg_) {\n \/\/ The process failed to launch for some reason.\n \/\/ Don't keep the renderer hanging.\n reply_msg_->set_reply_error();\n chrome_render_message_filter_->Send(reply_msg_);\n }\n}\n\nbool NaClProcessHost::Launch(\n ChromeRenderMessageFilter* chrome_render_message_filter,\n int socket_count,\n IPC::Message* reply_msg) {\n#ifdef DISABLE_NACL\n NOTIMPLEMENTED() << \"Native Client disabled at build time\";\n return false;\n#else\n \/\/ Place an arbitrary limit on the number of sockets to limit\n \/\/ exposure in case the renderer is compromised. We can increase\n \/\/ this if necessary.\n if (socket_count > 8) {\n return false;\n }\n\n \/\/ Rather than creating a socket pair in the renderer, and passing\n \/\/ one side through the browser to sel_ldr, socket pairs are created\n \/\/ in the browser and then passed to the renderer and sel_ldr.\n \/\/\n \/\/ This is mainly for the benefit of Windows, where sockets cannot\n \/\/ be passed in messages, but are copied via DuplicateHandle().\n \/\/ This means the sandboxed renderer cannot send handles to the\n \/\/ browser process.\n\n for (int i = 0; i < socket_count; i++) {\n nacl::Handle pair[2];\n \/\/ Create a connected socket\n if (nacl::SocketPair(pair) == -1)\n return false;\n internal_->sockets_for_renderer.push_back(pair[0]);\n internal_->sockets_for_sel_ldr.push_back(pair[1]);\n SetCloseOnExec(pair[0]);\n SetCloseOnExec(pair[1]);\n }\n\n \/\/ Launch the process\n if (!LaunchSelLdr()) {\n return false;\n }\n chrome_render_message_filter_ = chrome_render_message_filter;\n reply_msg_ = reply_msg;\n\n return true;\n#endif \/\/ DISABLE_NACL\n}\n\nbool NaClProcessHost::LaunchSelLdr() {\n if (!CreateChannel())\n return false;\n\n CommandLine::StringType nacl_loader_prefix;\n#if defined(OS_POSIX)\n nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(\n switches::kNaClLoaderCmdPrefix);\n#endif \/\/ defined(OS_POSIX)\n\n \/\/ Build command line for nacl.\n\n#if defined(OS_MACOSX)\n \/\/ The Native Client process needs to be able to allocate a 1GB contiguous\n \/\/ region to use as the client environment's virtual address space. ASLR\n \/\/ (PIE) interferes with this by making it possible that no gap large enough\n \/\/ to accomodate this request will exist in the child process' address\n \/\/ space. Disable PIE for NaCl processes. See http:\/\/crbug.com\/90221 and\n \/\/ http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=2043.\n int flags = CHILD_NO_PIE;\n#elif defined(OS_LINUX)\n int flags = nacl_loader_prefix.empty() ? CHILD_ALLOW_SELF : CHILD_NORMAL;\n#else\n int flags = CHILD_NORMAL;\n#endif\n\n FilePath exe_path = GetChildPath(flags);\n if (exe_path.empty())\n return false;\n\n CommandLine* cmd_line = new CommandLine(exe_path);\n nacl::CopyNaClCommandLineArguments(cmd_line);\n\n cmd_line->AppendSwitchASCII(switches::kProcessType,\n switches::kNaClLoaderProcess);\n cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id());\n if (logging::DialogsAreSuppressed())\n cmd_line->AppendSwitch(switches::kNoErrorDialogs);\n\n if (!nacl_loader_prefix.empty())\n cmd_line->PrependWrapper(nacl_loader_prefix);\n\n \/\/ On Windows we might need to start the broker process to launch a new loader\n#if defined(OS_WIN)\n if (running_on_wow64_) {\n return NaClBrokerService::GetInstance()->LaunchLoader(\n this, ASCIIToWide(channel_id()));\n } else {\n BrowserChildProcessHost::Launch(FilePath(), cmd_line);\n }\n#elif defined(OS_POSIX)\n BrowserChildProcessHost::Launch(nacl_loader_prefix.empty(), \/\/ use_zygote\n base::environment_vector(),\n cmd_line);\n#endif\n\n return true;\n}\n\nvoid NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {\n set_handle(handle);\n OnProcessLaunched();\n}\n\nbase::TerminationStatus NaClProcessHost::GetChildTerminationStatus(\n int* exit_code) {\n if (running_on_wow64_)\n return base::GetTerminationStatus(handle(), exit_code);\n return BrowserChildProcessHost::GetChildTerminationStatus(exit_code);\n}\n\nvoid NaClProcessHost::OnChildDied() {\n#if defined(OS_WIN)\n NaClBrokerService::GetInstance()->OnLoaderDied();\n#endif\n BrowserChildProcessHost::OnChildDied();\n}\n\nFilePath::StringType NaClProcessHost::GetIrtLibraryFilename() {\n bool on_x86_64 = running_on_wow64_;\n#if defined(__x86_64__)\n on_x86_64 = true;\n#endif\n if (on_x86_64) {\n return FILE_PATH_LITERAL(\"nacl_irt_x86_64.nexe\");\n } else {\n return FILE_PATH_LITERAL(\"nacl_irt_x86_32.nexe\");\n }\n}\n\nvoid NaClProcessHost::OnProcessLaunched() {\n \/\/ TODO(mseaborn): Opening the IRT file every time a NaCl process is\n \/\/ launched probably does not work with auto-update on Linux. We\n \/\/ might need to open the file on startup. If so, we would need to\n \/\/ ensure that NaCl's ELF loader does not use lseek() on the shared\n \/\/ IRT file descriptor, otherwise there would be a race condition.\n FilePath irt_path;\n \/\/ Allow the IRT library to be overridden via an environment\n \/\/ variable. This allows the NaCl\/Chromium integration bot to\n \/\/ specify a newly-built IRT rather than using a prebuilt one\n \/\/ downloaded via Chromium's DEPS file. We use the same environment\n \/\/ variable that the standalone NaCl PPAPI plugin accepts.\n const char* irt_path_var = getenv(\"NACL_IRT_LIBRARY\");\n if (irt_path_var != NULL) {\n FilePath::StringType string(irt_path_var,\n irt_path_var + strlen(irt_path_var));\n irt_path = FilePath(string);\n } else {\n FilePath plugin_dir;\n if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {\n LOG(ERROR) << \"Failed to locate the plugins directory\";\n delete this;\n return;\n }\n irt_path = plugin_dir.Append(GetIrtLibraryFilename());\n }\n\n base::FileUtilProxy::CreateOrOpenCallback* callback =\n callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone);\n if (!base::FileUtilProxy::CreateOrOpen(\n BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),\n irt_path,\n base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,\n callback)) {\n delete this;\n }\n}\n\nvoid NaClProcessHost::OpenIrtFileDone(base::PlatformFileError error_code,\n base::PassPlatformFile file,\n bool created) {\n std::vector<nacl::FileDescriptor> handles_for_renderer;\n base::ProcessHandle nacl_process_handle;\n bool have_irt_file = false;\n if (base::PLATFORM_FILE_OK == error_code) {\n internal_->sockets_for_sel_ldr.push_back(file.ReleaseValue());\n have_irt_file = true;\n } else {\n LOG(ERROR) << \"Failed to open the NaCl IRT library file\";\n }\n\n for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {\n#if defined(OS_WIN)\n \/\/ Copy the handle into the renderer process.\n HANDLE handle_in_renderer;\n if (!DuplicateHandle(base::GetCurrentProcessHandle(),\n reinterpret_cast<HANDLE>(\n internal_->sockets_for_renderer[i]),\n chrome_render_message_filter_->peer_handle(),\n &handle_in_renderer,\n 0, \/\/ Unused given DUPLICATE_SAME_ACCESS.\n FALSE,\n DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n handles_for_renderer.push_back(\n reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));\n#else\n \/\/ No need to dup the imc_handle - we don't pass it anywhere else so\n \/\/ it cannot be closed.\n nacl::FileDescriptor imc_handle;\n imc_handle.fd = internal_->sockets_for_renderer[i];\n imc_handle.auto_close = true;\n handles_for_renderer.push_back(imc_handle);\n#endif\n }\n\n#if defined(OS_WIN)\n \/\/ Copy the process handle into the renderer process.\n if (!DuplicateHandle(base::GetCurrentProcessHandle(),\n handle(),\n chrome_render_message_filter_->peer_handle(),\n &nacl_process_handle,\n PROCESS_DUP_HANDLE,\n FALSE,\n 0)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n#else\n \/\/ We use pid as process handle on Posix\n nacl_process_handle = handle();\n#endif\n\n \/\/ Get the pid of the NaCl process\n base::ProcessId nacl_process_id = base::GetProcId(handle());\n\n ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(\n reply_msg_, handles_for_renderer, nacl_process_handle, nacl_process_id);\n chrome_render_message_filter_->Send(reply_msg_);\n chrome_render_message_filter_ = NULL;\n reply_msg_ = NULL;\n internal_->sockets_for_renderer.clear();\n\n std::vector<nacl::FileDescriptor> handles_for_sel_ldr;\n for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {\n#if defined(OS_WIN)\n HANDLE channel;\n if (!DuplicateHandle(GetCurrentProcess(),\n reinterpret_cast<HANDLE>(\n internal_->sockets_for_sel_ldr[i]),\n handle(),\n &channel,\n 0, \/\/ Unused given DUPLICATE_SAME_ACCESS.\n FALSE,\n DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n handles_for_sel_ldr.push_back(\n reinterpret_cast<nacl::FileDescriptor>(channel));\n#else\n nacl::FileDescriptor channel;\n channel.fd = internal_->sockets_for_sel_ldr[i];\n channel.auto_close = true;\n handles_for_sel_ldr.push_back(channel);\n#endif\n }\n\n#if defined(OS_MACOSX)\n \/\/ For dynamic loading support, NaCl requires a file descriptor that\n \/\/ was created in \/tmp, since those created with shm_open() are not\n \/\/ mappable with PROT_EXEC. Rather than requiring an extra IPC\n \/\/ round trip out of the sandbox, we create an FD here.\n base::SharedMemory memory_buffer;\n if (!memory_buffer.CreateAnonymous(\/* size= *\/ 1)) {\n LOG(ERROR) << \"Failed to allocate memory buffer\";\n delete this;\n return;\n }\n nacl::FileDescriptor memory_fd;\n memory_fd.fd = dup(memory_buffer.handle().fd);\n if (memory_fd.fd < 0) {\n LOG(ERROR) << \"Failed to dup() a file descriptor\";\n delete this;\n return;\n }\n memory_fd.auto_close = true;\n handles_for_sel_ldr.push_back(memory_fd);\n#endif\n\n Send(new NaClProcessMsg_Start(handles_for_sel_ldr, have_irt_file));\n internal_->sockets_for_sel_ldr.clear();\n}\n\nbool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {\n NOTREACHED() << \"Invalid message with type = \" << msg.type();\n return false;\n}\n\nbool NaClProcessHost::CanShutdown() {\n return true;\n}\n<commit_msg>NaCl: Print a log message if the NaCl process exits<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n\n#include \"chrome\/browser\/nacl_host\/nacl_process_host.h\"\n\n#if defined(OS_POSIX)\n#include <fcntl.h>\n#endif\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/nacl_cmd_line.h\"\n#include \"chrome\/common\/nacl_messages.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/browser\/renderer_host\/chrome_render_message_filter.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"native_client\/src\/shared\/imc\/nacl_imc.h\"\n\n#if defined(OS_POSIX)\n#include \"ipc\/ipc_channel_posix.h\"\n#elif defined(OS_WIN)\n#include \"chrome\/browser\/nacl_host\/nacl_broker_service_win.h\"\n#endif\n\nnamespace {\n\n#if !defined(DISABLE_NACL)\nvoid SetCloseOnExec(nacl::Handle fd) {\n#if defined(OS_POSIX)\n int flags = fcntl(fd, F_GETFD);\n CHECK(flags != -1);\n int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);\n CHECK(rc == 0);\n#endif\n}\n#endif\n\n} \/\/ namespace\n\nstruct NaClProcessHost::NaClInternal {\n std::vector<nacl::Handle> sockets_for_renderer;\n std::vector<nacl::Handle> sockets_for_sel_ldr;\n};\n\nNaClProcessHost::NaClProcessHost(const std::wstring& url)\n : BrowserChildProcessHost(NACL_LOADER_PROCESS),\n reply_msg_(NULL),\n internal_(new NaClInternal()),\n running_on_wow64_(false),\n ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)) {\n set_name(WideToUTF16Hack(url));\n#if defined(OS_WIN)\n running_on_wow64_ = (base::win::OSInfo::GetInstance()->wow64_status() ==\n base::win::OSInfo::WOW64_ENABLED);\n#endif\n}\n\nNaClProcessHost::~NaClProcessHost() {\n \/\/ nacl::Close() is not available at link time if DISABLE_NACL is\n \/\/ defined, but we still compile a bunch of other code from this\n \/\/ file anyway. TODO(mseaborn): Make this less messy.\n#ifndef DISABLE_NACL\n for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {\n if (nacl::Close(internal_->sockets_for_renderer[i]) != 0) {\n LOG(ERROR) << \"nacl::Close() failed\";\n }\n }\n for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {\n if (nacl::Close(internal_->sockets_for_sel_ldr[i]) != 0) {\n LOG(ERROR) << \"nacl::Close() failed\";\n }\n }\n#endif\n\n if (reply_msg_) {\n \/\/ The process failed to launch for some reason.\n \/\/ Don't keep the renderer hanging.\n reply_msg_->set_reply_error();\n chrome_render_message_filter_->Send(reply_msg_);\n }\n}\n\nbool NaClProcessHost::Launch(\n ChromeRenderMessageFilter* chrome_render_message_filter,\n int socket_count,\n IPC::Message* reply_msg) {\n#ifdef DISABLE_NACL\n NOTIMPLEMENTED() << \"Native Client disabled at build time\";\n return false;\n#else\n \/\/ Place an arbitrary limit on the number of sockets to limit\n \/\/ exposure in case the renderer is compromised. We can increase\n \/\/ this if necessary.\n if (socket_count > 8) {\n return false;\n }\n\n \/\/ Rather than creating a socket pair in the renderer, and passing\n \/\/ one side through the browser to sel_ldr, socket pairs are created\n \/\/ in the browser and then passed to the renderer and sel_ldr.\n \/\/\n \/\/ This is mainly for the benefit of Windows, where sockets cannot\n \/\/ be passed in messages, but are copied via DuplicateHandle().\n \/\/ This means the sandboxed renderer cannot send handles to the\n \/\/ browser process.\n\n for (int i = 0; i < socket_count; i++) {\n nacl::Handle pair[2];\n \/\/ Create a connected socket\n if (nacl::SocketPair(pair) == -1)\n return false;\n internal_->sockets_for_renderer.push_back(pair[0]);\n internal_->sockets_for_sel_ldr.push_back(pair[1]);\n SetCloseOnExec(pair[0]);\n SetCloseOnExec(pair[1]);\n }\n\n \/\/ Launch the process\n if (!LaunchSelLdr()) {\n return false;\n }\n chrome_render_message_filter_ = chrome_render_message_filter;\n reply_msg_ = reply_msg;\n\n return true;\n#endif \/\/ DISABLE_NACL\n}\n\nbool NaClProcessHost::LaunchSelLdr() {\n if (!CreateChannel())\n return false;\n\n CommandLine::StringType nacl_loader_prefix;\n#if defined(OS_POSIX)\n nacl_loader_prefix = CommandLine::ForCurrentProcess()->GetSwitchValueNative(\n switches::kNaClLoaderCmdPrefix);\n#endif \/\/ defined(OS_POSIX)\n\n \/\/ Build command line for nacl.\n\n#if defined(OS_MACOSX)\n \/\/ The Native Client process needs to be able to allocate a 1GB contiguous\n \/\/ region to use as the client environment's virtual address space. ASLR\n \/\/ (PIE) interferes with this by making it possible that no gap large enough\n \/\/ to accomodate this request will exist in the child process' address\n \/\/ space. Disable PIE for NaCl processes. See http:\/\/crbug.com\/90221 and\n \/\/ http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=2043.\n int flags = CHILD_NO_PIE;\n#elif defined(OS_LINUX)\n int flags = nacl_loader_prefix.empty() ? CHILD_ALLOW_SELF : CHILD_NORMAL;\n#else\n int flags = CHILD_NORMAL;\n#endif\n\n FilePath exe_path = GetChildPath(flags);\n if (exe_path.empty())\n return false;\n\n CommandLine* cmd_line = new CommandLine(exe_path);\n nacl::CopyNaClCommandLineArguments(cmd_line);\n\n cmd_line->AppendSwitchASCII(switches::kProcessType,\n switches::kNaClLoaderProcess);\n cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id());\n if (logging::DialogsAreSuppressed())\n cmd_line->AppendSwitch(switches::kNoErrorDialogs);\n\n if (!nacl_loader_prefix.empty())\n cmd_line->PrependWrapper(nacl_loader_prefix);\n\n \/\/ On Windows we might need to start the broker process to launch a new loader\n#if defined(OS_WIN)\n if (running_on_wow64_) {\n return NaClBrokerService::GetInstance()->LaunchLoader(\n this, ASCIIToWide(channel_id()));\n } else {\n BrowserChildProcessHost::Launch(FilePath(), cmd_line);\n }\n#elif defined(OS_POSIX)\n BrowserChildProcessHost::Launch(nacl_loader_prefix.empty(), \/\/ use_zygote\n base::environment_vector(),\n cmd_line);\n#endif\n\n return true;\n}\n\nvoid NaClProcessHost::OnProcessLaunchedByBroker(base::ProcessHandle handle) {\n set_handle(handle);\n OnProcessLaunched();\n}\n\nbase::TerminationStatus NaClProcessHost::GetChildTerminationStatus(\n int* exit_code) {\n if (running_on_wow64_)\n return base::GetTerminationStatus(handle(), exit_code);\n return BrowserChildProcessHost::GetChildTerminationStatus(exit_code);\n}\n\nvoid NaClProcessHost::OnChildDied() {\n int exit_code;\n GetChildTerminationStatus(&exit_code);\n std::string message =\n base::StringPrintf(\"NaCl process exited with status %i (0x%x)\",\n exit_code, exit_code);\n if (exit_code == 0) {\n LOG(INFO) << message;\n } else {\n LOG(ERROR) << message;\n }\n\n#if defined(OS_WIN)\n NaClBrokerService::GetInstance()->OnLoaderDied();\n#endif\n BrowserChildProcessHost::OnChildDied();\n}\n\nFilePath::StringType NaClProcessHost::GetIrtLibraryFilename() {\n bool on_x86_64 = running_on_wow64_;\n#if defined(__x86_64__)\n on_x86_64 = true;\n#endif\n if (on_x86_64) {\n return FILE_PATH_LITERAL(\"nacl_irt_x86_64.nexe\");\n } else {\n return FILE_PATH_LITERAL(\"nacl_irt_x86_32.nexe\");\n }\n}\n\nvoid NaClProcessHost::OnProcessLaunched() {\n \/\/ TODO(mseaborn): Opening the IRT file every time a NaCl process is\n \/\/ launched probably does not work with auto-update on Linux. We\n \/\/ might need to open the file on startup. If so, we would need to\n \/\/ ensure that NaCl's ELF loader does not use lseek() on the shared\n \/\/ IRT file descriptor, otherwise there would be a race condition.\n FilePath irt_path;\n \/\/ Allow the IRT library to be overridden via an environment\n \/\/ variable. This allows the NaCl\/Chromium integration bot to\n \/\/ specify a newly-built IRT rather than using a prebuilt one\n \/\/ downloaded via Chromium's DEPS file. We use the same environment\n \/\/ variable that the standalone NaCl PPAPI plugin accepts.\n const char* irt_path_var = getenv(\"NACL_IRT_LIBRARY\");\n if (irt_path_var != NULL) {\n FilePath::StringType string(irt_path_var,\n irt_path_var + strlen(irt_path_var));\n irt_path = FilePath(string);\n } else {\n FilePath plugin_dir;\n if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {\n LOG(ERROR) << \"Failed to locate the plugins directory\";\n delete this;\n return;\n }\n irt_path = plugin_dir.Append(GetIrtLibraryFilename());\n }\n\n base::FileUtilProxy::CreateOrOpenCallback* callback =\n callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone);\n if (!base::FileUtilProxy::CreateOrOpen(\n BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),\n irt_path,\n base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,\n callback)) {\n delete this;\n }\n}\n\nvoid NaClProcessHost::OpenIrtFileDone(base::PlatformFileError error_code,\n base::PassPlatformFile file,\n bool created) {\n std::vector<nacl::FileDescriptor> handles_for_renderer;\n base::ProcessHandle nacl_process_handle;\n bool have_irt_file = false;\n if (base::PLATFORM_FILE_OK == error_code) {\n internal_->sockets_for_sel_ldr.push_back(file.ReleaseValue());\n have_irt_file = true;\n } else {\n LOG(ERROR) << \"Failed to open the NaCl IRT library file\";\n }\n\n for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) {\n#if defined(OS_WIN)\n \/\/ Copy the handle into the renderer process.\n HANDLE handle_in_renderer;\n if (!DuplicateHandle(base::GetCurrentProcessHandle(),\n reinterpret_cast<HANDLE>(\n internal_->sockets_for_renderer[i]),\n chrome_render_message_filter_->peer_handle(),\n &handle_in_renderer,\n 0, \/\/ Unused given DUPLICATE_SAME_ACCESS.\n FALSE,\n DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n handles_for_renderer.push_back(\n reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer));\n#else\n \/\/ No need to dup the imc_handle - we don't pass it anywhere else so\n \/\/ it cannot be closed.\n nacl::FileDescriptor imc_handle;\n imc_handle.fd = internal_->sockets_for_renderer[i];\n imc_handle.auto_close = true;\n handles_for_renderer.push_back(imc_handle);\n#endif\n }\n\n#if defined(OS_WIN)\n \/\/ Copy the process handle into the renderer process.\n if (!DuplicateHandle(base::GetCurrentProcessHandle(),\n handle(),\n chrome_render_message_filter_->peer_handle(),\n &nacl_process_handle,\n PROCESS_DUP_HANDLE,\n FALSE,\n 0)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n#else\n \/\/ We use pid as process handle on Posix\n nacl_process_handle = handle();\n#endif\n\n \/\/ Get the pid of the NaCl process\n base::ProcessId nacl_process_id = base::GetProcId(handle());\n\n ChromeViewHostMsg_LaunchNaCl::WriteReplyParams(\n reply_msg_, handles_for_renderer, nacl_process_handle, nacl_process_id);\n chrome_render_message_filter_->Send(reply_msg_);\n chrome_render_message_filter_ = NULL;\n reply_msg_ = NULL;\n internal_->sockets_for_renderer.clear();\n\n std::vector<nacl::FileDescriptor> handles_for_sel_ldr;\n for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {\n#if defined(OS_WIN)\n HANDLE channel;\n if (!DuplicateHandle(GetCurrentProcess(),\n reinterpret_cast<HANDLE>(\n internal_->sockets_for_sel_ldr[i]),\n handle(),\n &channel,\n 0, \/\/ Unused given DUPLICATE_SAME_ACCESS.\n FALSE,\n DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {\n LOG(ERROR) << \"DuplicateHandle() failed\";\n delete this;\n return;\n }\n handles_for_sel_ldr.push_back(\n reinterpret_cast<nacl::FileDescriptor>(channel));\n#else\n nacl::FileDescriptor channel;\n channel.fd = internal_->sockets_for_sel_ldr[i];\n channel.auto_close = true;\n handles_for_sel_ldr.push_back(channel);\n#endif\n }\n\n#if defined(OS_MACOSX)\n \/\/ For dynamic loading support, NaCl requires a file descriptor that\n \/\/ was created in \/tmp, since those created with shm_open() are not\n \/\/ mappable with PROT_EXEC. Rather than requiring an extra IPC\n \/\/ round trip out of the sandbox, we create an FD here.\n base::SharedMemory memory_buffer;\n if (!memory_buffer.CreateAnonymous(\/* size= *\/ 1)) {\n LOG(ERROR) << \"Failed to allocate memory buffer\";\n delete this;\n return;\n }\n nacl::FileDescriptor memory_fd;\n memory_fd.fd = dup(memory_buffer.handle().fd);\n if (memory_fd.fd < 0) {\n LOG(ERROR) << \"Failed to dup() a file descriptor\";\n delete this;\n return;\n }\n memory_fd.auto_close = true;\n handles_for_sel_ldr.push_back(memory_fd);\n#endif\n\n Send(new NaClProcessMsg_Start(handles_for_sel_ldr, have_irt_file));\n internal_->sockets_for_sel_ldr.clear();\n}\n\nbool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {\n NOTREACHED() << \"Invalid message with type = \" << msg.type();\n return false;\n}\n\nbool NaClProcessHost::CanShutdown() {\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/string16.h\"\n#include \"chrome\/browser\/printing\/print_job.h\"\n#include \"chrome\/browser\/printing\/print_job_worker.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"printing\/printed_pages_source.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nclass TestSource : public printing::PrintedPagesSource {\n public:\n virtual string16 RenderSourceName() OVERRIDE {\n return string16();\n }\n};\n\nclass TestPrintJobWorker : public printing::PrintJobWorker {\n public:\n explicit TestPrintJobWorker(printing::PrintJobWorkerOwner* owner)\n : printing::PrintJobWorker(owner) {\n }\n friend class TestOwner;\n};\n\nclass TestOwner : public printing::PrintJobWorkerOwner {\n public:\n virtual void GetSettingsDone(const printing::PrintSettings& new_settings,\n printing::PrintingContext::Result result) {\n EXPECT_FALSE(true);\n }\n virtual printing::PrintJobWorker* DetachWorker(\n printing::PrintJobWorkerOwner* new_owner) {\n \/\/ We're screwing up here since we're calling worker from the main thread.\n \/\/ That's fine for testing. It is actually simulating PrinterQuery behavior.\n TestPrintJobWorker* worker(new TestPrintJobWorker(new_owner));\n EXPECT_TRUE(worker->Start());\n worker->printing_context()->UseDefaultSettings();\n settings_ = worker->printing_context()->settings();\n return worker;\n }\n virtual MessageLoop* message_loop() {\n EXPECT_FALSE(true);\n return NULL;\n }\n virtual const printing::PrintSettings& settings() const {\n return settings_;\n }\n virtual int cookie() const {\n return 42;\n }\n\n private:\n printing::PrintSettings settings_;\n};\n\nclass TestPrintJob : public printing::PrintJob {\n public:\n explicit TestPrintJob(volatile bool* check) : check_(check) {\n }\n private:\n ~TestPrintJob() {\n *check_ = true;\n }\n volatile bool* check_;\n};\n\nclass TestPrintNotifObserv : public content::NotificationObserver {\n public:\n \/\/ content::NotificationObserver\n virtual void Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n ADD_FAILURE();\n }\n};\n\n} \/\/ namespace\n\ntypedef testing::Test PrintJobTest;\n\n\/\/ Crashes under Linux Aura, see http:\/\/crbug.com\/100340\n#if defined(USE_AURA) && !defined(OS_WIN)\n#define MAYBE_SimplePrint DISABLED_SimplePrint\n#else\n#define MAYBE_SimplePrint SimplePrint\n#endif\nTEST_F(PrintJobTest, MAYBE_SimplePrint) {\n \/\/ Test the multi-threaded nature of PrintJob to make sure we can use it with\n \/\/ known lifetime.\n\n \/\/ This message loop is actually never run.\n MessageLoop current;\n\n content::NotificationRegistrar registrar_;\n TestPrintNotifObserv observ;\n registrar_.Add(&observ, content::NOTIFICATION_ALL,\n content::NotificationService::AllSources());\n volatile bool check = false;\n scoped_refptr<printing::PrintJob> job(new TestPrintJob(&check));\n EXPECT_EQ(MessageLoop::current(), job->message_loop());\n scoped_refptr<TestOwner> owner(new TestOwner);\n TestSource source;\n job->Initialize(owner, &source, 1);\n job->Stop();\n job = NULL;\n EXPECT_TRUE(check);\n}\n\nTEST_F(PrintJobTest, SimplePrintLateInit) {\n volatile bool check = false;\n MessageLoop current;\n scoped_refptr<printing::PrintJob> job(new TestPrintJob(&check));\n job = NULL;\n EXPECT_TRUE(check);\n \/* TODO(maruel): Test these.\n job->Initialize()\n job->Observe();\n job->GetSettingsDone();\n job->DetachWorker();\n job->message_loop();\n job->settings();\n job->cookie();\n job->GetSettings(printing::DEFAULTS, printing::ASK_USER, NULL);\n job->StartPrinting();\n job->Stop();\n job->Cancel();\n job->RequestMissingPages();\n job->FlushJob(timeout_ms);\n job->DisconnectSource();\n job->is_job_pending();\n job->document();\n \/\/ Private\n job->UpdatePrintedDocument(NULL);\n scoped_refptr<printing::JobEventDetails> event_details;\n job->OnNotifyPrintJobEvent(event_details);\n job->OnDocumentDone();\n job->ControlledWorkerShutdown();\n *\/\n}\n<commit_msg>Remove SimplePrint unit test issue from aura build.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/string16.h\"\n#include \"chrome\/browser\/printing\/print_job.h\"\n#include \"chrome\/browser\/printing\/print_job_worker.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"printing\/printed_pages_source.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nclass TestSource : public printing::PrintedPagesSource {\n public:\n virtual string16 RenderSourceName() OVERRIDE {\n return string16();\n }\n};\n\nclass TestPrintJobWorker : public printing::PrintJobWorker {\n public:\n explicit TestPrintJobWorker(printing::PrintJobWorkerOwner* owner)\n : printing::PrintJobWorker(owner) {\n }\n friend class TestOwner;\n};\n\nclass TestOwner : public printing::PrintJobWorkerOwner {\n public:\n virtual void GetSettingsDone(const printing::PrintSettings& new_settings,\n printing::PrintingContext::Result result) {\n EXPECT_FALSE(true);\n }\n virtual printing::PrintJobWorker* DetachWorker(\n printing::PrintJobWorkerOwner* new_owner) {\n \/\/ We're screwing up here since we're calling worker from the main thread.\n \/\/ That's fine for testing. It is actually simulating PrinterQuery behavior.\n TestPrintJobWorker* worker(new TestPrintJobWorker(new_owner));\n EXPECT_TRUE(worker->Start());\n worker->printing_context()->UseDefaultSettings();\n settings_ = worker->printing_context()->settings();\n return worker;\n }\n virtual MessageLoop* message_loop() {\n EXPECT_FALSE(true);\n return NULL;\n }\n virtual const printing::PrintSettings& settings() const {\n return settings_;\n }\n virtual int cookie() const {\n return 42;\n }\n\n private:\n printing::PrintSettings settings_;\n};\n\nclass TestPrintJob : public printing::PrintJob {\n public:\n explicit TestPrintJob(volatile bool* check) : check_(check) {\n }\n private:\n ~TestPrintJob() {\n *check_ = true;\n }\n volatile bool* check_;\n};\n\nclass TestPrintNotifObserv : public content::NotificationObserver {\n public:\n \/\/ content::NotificationObserver\n virtual void Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n ADD_FAILURE();\n }\n};\n\n} \/\/ namespace\n\ntypedef testing::Test PrintJobTest;\n\n#if !defined(USE_AURA)\nTEST_F(PrintJobTest, SimplePrint) {\n \/\/ Test the multi-threaded nature of PrintJob to make sure we can use it with\n \/\/ known lifetime.\n\n \/\/ This message loop is actually never run.\n MessageLoop current;\n\n content::NotificationRegistrar registrar_;\n TestPrintNotifObserv observ;\n registrar_.Add(&observ, content::NOTIFICATION_ALL,\n content::NotificationService::AllSources());\n volatile bool check = false;\n scoped_refptr<printing::PrintJob> job(new TestPrintJob(&check));\n EXPECT_EQ(MessageLoop::current(), job->message_loop());\n scoped_refptr<TestOwner> owner(new TestOwner);\n TestSource source;\n job->Initialize(owner, &source, 1);\n job->Stop();\n job = NULL;\n EXPECT_TRUE(check);\n}\n#endif\n\nTEST_F(PrintJobTest, SimplePrintLateInit) {\n volatile bool check = false;\n MessageLoop current;\n scoped_refptr<printing::PrintJob> job(new TestPrintJob(&check));\n job = NULL;\n EXPECT_TRUE(check);\n \/* TODO(maruel): Test these.\n job->Initialize()\n job->Observe();\n job->GetSettingsDone();\n job->DetachWorker();\n job->message_loop();\n job->settings();\n job->cookie();\n job->GetSettings(printing::DEFAULTS, printing::ASK_USER, NULL);\n job->StartPrinting();\n job->Stop();\n job->Cancel();\n job->RequestMissingPages();\n job->FlushJob(timeout_ms);\n job->DisconnectSource();\n job->is_job_pending();\n job->document();\n \/\/ Private\n job->UpdatePrintedDocument(NULL);\n scoped_refptr<printing::JobEventDetails> event_details;\n job->OnNotifyPrintJobEvent(event_details);\n job->OnDocumentDone();\n job->ControlledWorkerShutdown();\n *\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"nodes\/composite\/CompositeNode.h\"\n#include \"..\/..\/commands\/CompositeNodeChangeChild.h\"\n\nnamespace Model {\n\nDEFINE_TYPE_ID_DERIVED(CompositeNode, \"CompositeNode\", )\n\nREGISTER_ATTRIBUTE(CompositeNode, comment, Node, false, true, true)\n\nint CompositeNode::nextExtensionId_ = 0;\n\nvoid CompositeNode::initType()\n{\n\tNode::registerNodeType(\"CompositeNode\",\n\t\t\t[](Node* parent) -> Node* { return CompositeNode::createDefaultInstance(parent);},\n\t\t\t[](Node *parent, PersistentStore &store, bool partialLoadHint) -> Node*\n\t\t\t{ return new CompositeNode(parent, store, partialLoadHint);});\n\n\tfor (int i = 0; i<attributesToRegisterAtInitialization_().size(); ++i)\n\t\tattributesToRegisterAtInitialization_().at(i).first =\n\t\t\t\tregisterNewAttribute(attributesToRegisterAtInitialization_().at(i).second);\n}\n\nCompositeNode* CompositeNode::createDefaultInstance( Node* parent)\n{\n\treturn new CompositeNode(parent);\n}\n\nAttributeChain& CompositeNode::topLevelMeta()\n{\n\treturn meta_;\n}\n\nCompositeNode::CompositeNode(Node *parent) :\n\tSuper(parent), meta_(CompositeNode::getMetaData())\n{\n\tthrow ModelException(\"Constructing an CompositeNode class directly, without specifying meta data\");\n}\n\nCompositeNode::CompositeNode(Node *parent, PersistentStore &, bool) :\n\tSuper(parent), meta_(CompositeNode::getMetaData())\n{\n\tthrow ModelException(\"Constructing an CompositeNode class directly, without specifying meta data\");\n}\n\nCompositeNode::CompositeNode(const CompositeNode& other)\n\t: Super{other}, meta_{other.meta_}, subnodes_(meta_.numLevels())\n{\n\tQ_ASSERT(subnodes_.size() == other.subnodes_.size());\n\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tsubnodes_[level] = QVector<Node*> (currentLevel->size(), nullptr);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( auto node = other.subnodes_[level][i] )\n\t\t\t{\n\t\t\t\tsubnodes_[level][i] = node->clone();\n\t\t\t\tnode->setParent(this);\n\t\t\t}\n\t}\n}\n\nCompositeNode* CompositeNode::clone() const { return new CompositeNode(*this); }\n\nCompositeNode::CompositeNode(Node *parent, AttributeChain& metaData) :\n\tSuper(parent), meta_(metaData), subnodes_(meta_.numLevels())\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tsubnodes_[level] = QVector<Node*> (currentLevel->size(), nullptr);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( !(*currentLevel)[i].optional() )\n\t\t\t\tsubnodes_[level][i] = Node::createNewNode((*currentLevel)[i].type(), this);\n\t}\n}\n\nCompositeNode::CompositeNode(Node *parent, PersistentStore &store, bool, AttributeChain& metaData) :\n\tSuper(parent), meta_(metaData), subnodes_(meta_.numLevels())\n{\n\tQSet<QString> partial;\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tsubnodes_[level] = QVector<Node*> (meta_.level(level)->size(), nullptr);\n\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( (*currentLevel)[i].partial() ) partial.insert( (*currentLevel)[i].name() );\n\t}\n\n\tQList<LoadedNode> children = store.loadAllSubNodes(this, partial);\n\n\tfor (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)\n\t{\n\t\tCompositeIndex index = meta_.indexForAttribute(ln->name);\n\t\tif ( !index.isValid() ) throw ModelException(\"Node has attribute \"\n\t\t\t\t+ ln->name + \" in persistent store, but this attribute is not registered\");\n\n\t\tauto attribute = meta_.attribute(index);\n\t\tQ_ASSERT(ln->node->isSubtypeOf(attribute.type()));\n\n\t\t\/\/ Skip loading partial optional children.\n\t\tif (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())\n\t\t{\n\t\t\tsubnodes_[index.level()][index.index()] = ln->node;\n\t\t\tln->node->setParent(this);\n\t\t}\n\t}\n\n\tverifyHasAllMandatoryAttributes();\n}\n\nCompositeNode::~CompositeNode()\n{\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif ( subnodes_[level][i] ) SAFE_DELETE( subnodes_[level][i] );\n}\n\nAttributeChain& CompositeNode::getMetaData()\n{\n\tstatic AttributeChain descriptions{\"CompositeNode\"};\n\treturn descriptions;\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const QString &attributeName,\n\t\tconst QString &attributeType, bool canBePartiallyLoaded, bool isOptional, bool isPersistent)\n{\n\treturn registerNewAttribute(metaData, Attribute(attributeName, attributeType,\n\t\t\t\t\t\t\t\t\t\t\t\tisOptional, canBePartiallyLoaded, isPersistent));\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const Attribute& attribute)\n{\n\tif ( metaData.hasAttribute(attribute.name()) )\n\t\tthrow ModelException(\"Trying to register new attribute \" + attribute.name() + \" but this name already exists\");\n\n\tmetaData.append(attribute);\n\n\treturn CompositeIndex(metaData.numLevels() - 1, metaData.size() - 1);\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(const Attribute& attribute)\n{\n\treturn registerNewAttribute(getMetaData(), attribute);\n}\n\nCompositeIndex CompositeNode::addAttributeToInitialRegistrationList_ (CompositeIndex& index,\n\tconst QString &attributeName, const QString &attributeType, bool canBePartiallyLoaded, bool isOptional,\n\t\t\t bool isPersistent)\n{\n\tattributesToRegisterAtInitialization_().append(QPair< CompositeIndex&, Attribute>(index,\n\t\t\tAttribute(attributeName, attributeType, isOptional, canBePartiallyLoaded, isPersistent)));\n\treturn CompositeIndex();\n}\n\nQList<QPair< CompositeIndex&, Attribute> >& CompositeNode::attributesToRegisterAtInitialization_()\n{\n\tstatic QList<QPair< CompositeIndex&, Attribute> > a;\n\treturn a;\n}\n\nvoid CompositeNode::set(const CompositeIndex &attributeIndex, Node* node)\n{\n\tQ_ASSERT( attributeIndex.isValid() );\n\tQ_ASSERT( attributeIndex.level() < subnodes_.size());\n\tQ_ASSERT( attributeIndex.index() < subnodes_[attributeIndex.level()].size());\n\tauto attribute = meta_.attribute(attributeIndex);\n\tQ_ASSERT( node || attribute.optional());\n\tQ_ASSERT( !node || node->isSubtypeOf(attribute.type()));\n\texecute(new CompositeNodeChangeChild(this, node, attributeIndex, &subnodes_));\n}\n\nNode* CompositeNode::get(const QString &attributeName) const\n{\n\tCompositeIndex index = meta_.indexForAttribute(attributeName);\n\tif ( index.isValid() ) return subnodes_[index.level()][index.index()];\n\treturn nullptr;\n}\n\nCompositeIndex CompositeNode::indexOf(Node* node) const\n{\n\tif (node)\n\t{\n\t\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\t\tif (subnodes_[level][i] == node)\n\t\t\t\t\treturn CompositeIndex(level, i);\n\t}\n\n\treturn CompositeIndex();\n}\n\n\nCompositeIndex CompositeNode::indexOf(const QString& nodeName) const\n{\n\treturn meta_.indexForAttribute(nodeName);\n}\n\nQList<Node*> CompositeNode::children() const\n{\n\tQList<Node*> result;\n\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif (subnodes_[level][i]) result << subnodes_[level][i];\n\n\treturn result;\n}\n\nbool CompositeNode::replaceChild(Node* child, Node* replacement)\n{\n\tif (!child || !replacement) return false;\n\n\tCompositeIndex index = indexOf(child);\n\tQ_ASSERT(index.isValid());\n\tQ_ASSERT( !replacement || replacement->isSubtypeOf(meta_.attribute(index).type()));\n\texecute(new CompositeNodeChangeChild(this, replacement, index, &subnodes_));\n\treturn true;\n}\n\nbool CompositeNode::hasAttribute(const QString& attributeName)\n{\n\treturn meta_.hasAttribute(attributeName);\n}\n\nQList< QPair<QString, Node*> > CompositeNode::getAllAttributes(bool includeNullValues)\n{\n\tQList< QPair<QString, Node*> > result;\n\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] || includeNullValues )\n\t\t\t\tresult.append(QPair<QString, Node*>((*currentLevel)[i].name(), subnodes_[level][i]));\n\t}\n\n\treturn result;\n}\n\nvoid CompositeNode::save(PersistentStore &store) const\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] != nullptr && currentLevel->at(i).persistent() )\n\t\t\t\tstore.saveNode(subnodes_[level][i], currentLevel->at(i).name());\n\t}\n}\n\nvoid CompositeNode::load(PersistentStore &store)\n{\n\tif (store.currentNodeType() != typeName())\n\t\tthrow ModelException(\"Trying to load a CompositeNode from an incompatible node type \"\n\t\t\t\t+ store.currentNodeType());\n\n\tremoveAllNodes();\n\n\tQSet<QString> partial;\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( currentLevel->at(i).partial() )\n\t\t\t\tpartial.insert(currentLevel->at(i).name());\n\t}\n\n\tQList<LoadedNode> children = store.loadAllSubNodes(this, partial);\n\n\tfor (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)\n\t{\n\t\tCompositeIndex index = meta_.indexForAttribute(ln->name);\n\t\tif ( !index.isValid() )\n\t\t\tthrow ModelException(\"Node has attribute \"\n\t\t\t\t\t+ ln->name + \" in persistent store, but this attribute is not registered\");\n\n\t\tauto attribute = meta_.attribute(index);\n\t\tQ_ASSERT(ln->node->isSubtypeOf(attribute.type()));\n\n\t\t\/\/ Skip loading partial optional children.\n\t\tif (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())\n\t\t\texecute(new CompositeNodeChangeChild(this, ln->node, CompositeIndex(index.level(), index.index()), &subnodes_));\n\t}\n\n\tverifyHasAllMandatoryAttributes();\n}\n\nvoid CompositeNode::removeAllNodes()\n{\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif ( subnodes_[level][i] )\n\t\t\t\texecute(new CompositeNodeChangeChild(this, nullptr, CompositeIndex(level, i), &subnodes_));\n}\n\nvoid CompositeNode::verifyHasAllMandatoryAttributes()\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] == nullptr && (*currentLevel)[i].optional() == false )\n\t\t\t\tthrow ModelException(\"An CompositeNode of type '\" + meta_.typeName()\n\t\t\t\t\t\t+ \"' has an uninitialized mandatory attribute '\"\n\t\t\t\t\t\t+ (*currentLevel)[i].name() +\"'\");\n\t}\n}\n\nvoid CompositeNode::remove(const CompositeIndex &attributeIndex)\n{\n\tQ_ASSERT(attributeIndex.isValid());\n\n\tif ( meta_.attribute(attributeIndex).optional() )\n\t\texecute(new CompositeNodeChangeChild(\tthis, nullptr, attributeIndex, &subnodes_));\n\telse\n\t\texecute(new CompositeNodeChangeChild(\tthis, Node::createNewNode(meta_.attribute(attributeIndex).type(), nullptr),\n\t\t\t\tattributeIndex, &subnodes_));\n}\n\nvoid CompositeNode::remove(Node* childNode)\n{\n\tQ_ASSERT(childNode);\n\tremove(indexOf(childNode));\n}\n\nvoid CompositeNode::remove(QString childNodeName)\n{\n\tremove(indexOf(childNodeName));\n}\n\nNode* CompositeNode::setDefault(QString nodeName)\n{\n\tauto attributeIndex = indexOf(nodeName);\n\n\tauto newNode = Node::createNewNode(meta_.attribute(attributeIndex).type());\n\tset(attributeIndex, newNode);\n\n\treturn newNode;\n}\n\n}\n<commit_msg>Fix clone to correctly set the cloned node's parent<commit_after>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"nodes\/composite\/CompositeNode.h\"\n#include \"..\/..\/commands\/CompositeNodeChangeChild.h\"\n\nnamespace Model {\n\nDEFINE_TYPE_ID_DERIVED(CompositeNode, \"CompositeNode\", )\n\nREGISTER_ATTRIBUTE(CompositeNode, comment, Node, false, true, true)\n\nint CompositeNode::nextExtensionId_ = 0;\n\nvoid CompositeNode::initType()\n{\n\tNode::registerNodeType(\"CompositeNode\",\n\t\t\t[](Node* parent) -> Node* { return CompositeNode::createDefaultInstance(parent);},\n\t\t\t[](Node *parent, PersistentStore &store, bool partialLoadHint) -> Node*\n\t\t\t{ return new CompositeNode(parent, store, partialLoadHint);});\n\n\tfor (int i = 0; i<attributesToRegisterAtInitialization_().size(); ++i)\n\t\tattributesToRegisterAtInitialization_().at(i).first =\n\t\t\t\tregisterNewAttribute(attributesToRegisterAtInitialization_().at(i).second);\n}\n\nCompositeNode* CompositeNode::createDefaultInstance( Node* parent)\n{\n\treturn new CompositeNode(parent);\n}\n\nAttributeChain& CompositeNode::topLevelMeta()\n{\n\treturn meta_;\n}\n\nCompositeNode::CompositeNode(Node *parent) :\n\tSuper(parent), meta_(CompositeNode::getMetaData())\n{\n\tthrow ModelException(\"Constructing an CompositeNode class directly, without specifying meta data\");\n}\n\nCompositeNode::CompositeNode(Node *parent, PersistentStore &, bool) :\n\tSuper(parent), meta_(CompositeNode::getMetaData())\n{\n\tthrow ModelException(\"Constructing an CompositeNode class directly, without specifying meta data\");\n}\n\nCompositeNode::CompositeNode(const CompositeNode& other)\n\t: Super{other}, meta_{other.meta_}, subnodes_(meta_.numLevels())\n{\n\tQ_ASSERT(subnodes_.size() == other.subnodes_.size());\n\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tsubnodes_[level] = QVector<Node*> (currentLevel->size(), nullptr);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( auto node = other.subnodes_[level][i] )\n\t\t\t{\n\t\t\t\tauto cloned = node->clone();\n\t\t\t\tsubnodes_[level][i] = cloned;\n\t\t\t\tcloned->setParent(this);\n\t\t\t}\n\t}\n}\n\nCompositeNode* CompositeNode::clone() const { return new CompositeNode(*this); }\n\nCompositeNode::CompositeNode(Node *parent, AttributeChain& metaData) :\n\tSuper(parent), meta_(metaData), subnodes_(meta_.numLevels())\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tsubnodes_[level] = QVector<Node*> (currentLevel->size(), nullptr);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( !(*currentLevel)[i].optional() )\n\t\t\t\tsubnodes_[level][i] = Node::createNewNode((*currentLevel)[i].type(), this);\n\t}\n}\n\nCompositeNode::CompositeNode(Node *parent, PersistentStore &store, bool, AttributeChain& metaData) :\n\tSuper(parent), meta_(metaData), subnodes_(meta_.numLevels())\n{\n\tQSet<QString> partial;\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tsubnodes_[level] = QVector<Node*> (meta_.level(level)->size(), nullptr);\n\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( (*currentLevel)[i].partial() ) partial.insert( (*currentLevel)[i].name() );\n\t}\n\n\tQList<LoadedNode> children = store.loadAllSubNodes(this, partial);\n\n\tfor (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)\n\t{\n\t\tCompositeIndex index = meta_.indexForAttribute(ln->name);\n\t\tif ( !index.isValid() ) throw ModelException(\"Node has attribute \"\n\t\t\t\t+ ln->name + \" in persistent store, but this attribute is not registered\");\n\n\t\tauto attribute = meta_.attribute(index);\n\t\tQ_ASSERT(ln->node->isSubtypeOf(attribute.type()));\n\n\t\t\/\/ Skip loading partial optional children.\n\t\tif (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())\n\t\t{\n\t\t\tsubnodes_[index.level()][index.index()] = ln->node;\n\t\t\tln->node->setParent(this);\n\t\t}\n\t}\n\n\tverifyHasAllMandatoryAttributes();\n}\n\nCompositeNode::~CompositeNode()\n{\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif ( subnodes_[level][i] ) SAFE_DELETE( subnodes_[level][i] );\n}\n\nAttributeChain& CompositeNode::getMetaData()\n{\n\tstatic AttributeChain descriptions{\"CompositeNode\"};\n\treturn descriptions;\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const QString &attributeName,\n\t\tconst QString &attributeType, bool canBePartiallyLoaded, bool isOptional, bool isPersistent)\n{\n\treturn registerNewAttribute(metaData, Attribute(attributeName, attributeType,\n\t\t\t\t\t\t\t\t\t\t\t\tisOptional, canBePartiallyLoaded, isPersistent));\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(AttributeChain& metaData, const Attribute& attribute)\n{\n\tif ( metaData.hasAttribute(attribute.name()) )\n\t\tthrow ModelException(\"Trying to register new attribute \" + attribute.name() + \" but this name already exists\");\n\n\tmetaData.append(attribute);\n\n\treturn CompositeIndex(metaData.numLevels() - 1, metaData.size() - 1);\n}\n\nCompositeIndex CompositeNode::registerNewAttribute(const Attribute& attribute)\n{\n\treturn registerNewAttribute(getMetaData(), attribute);\n}\n\nCompositeIndex CompositeNode::addAttributeToInitialRegistrationList_ (CompositeIndex& index,\n\tconst QString &attributeName, const QString &attributeType, bool canBePartiallyLoaded, bool isOptional,\n\t\t\t bool isPersistent)\n{\n\tattributesToRegisterAtInitialization_().append(QPair< CompositeIndex&, Attribute>(index,\n\t\t\tAttribute(attributeName, attributeType, isOptional, canBePartiallyLoaded, isPersistent)));\n\treturn CompositeIndex();\n}\n\nQList<QPair< CompositeIndex&, Attribute> >& CompositeNode::attributesToRegisterAtInitialization_()\n{\n\tstatic QList<QPair< CompositeIndex&, Attribute> > a;\n\treturn a;\n}\n\nvoid CompositeNode::set(const CompositeIndex &attributeIndex, Node* node)\n{\n\tQ_ASSERT( attributeIndex.isValid() );\n\tQ_ASSERT( attributeIndex.level() < subnodes_.size());\n\tQ_ASSERT( attributeIndex.index() < subnodes_[attributeIndex.level()].size());\n\tauto attribute = meta_.attribute(attributeIndex);\n\tQ_ASSERT( node || attribute.optional());\n\tQ_ASSERT( !node || node->isSubtypeOf(attribute.type()));\n\texecute(new CompositeNodeChangeChild(this, node, attributeIndex, &subnodes_));\n}\n\nNode* CompositeNode::get(const QString &attributeName) const\n{\n\tCompositeIndex index = meta_.indexForAttribute(attributeName);\n\tif ( index.isValid() ) return subnodes_[index.level()][index.index()];\n\treturn nullptr;\n}\n\nCompositeIndex CompositeNode::indexOf(Node* node) const\n{\n\tif (node)\n\t{\n\t\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\t\tif (subnodes_[level][i] == node)\n\t\t\t\t\treturn CompositeIndex(level, i);\n\t}\n\n\treturn CompositeIndex();\n}\n\n\nCompositeIndex CompositeNode::indexOf(const QString& nodeName) const\n{\n\treturn meta_.indexForAttribute(nodeName);\n}\n\nQList<Node*> CompositeNode::children() const\n{\n\tQList<Node*> result;\n\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif (subnodes_[level][i]) result << subnodes_[level][i];\n\n\treturn result;\n}\n\nbool CompositeNode::replaceChild(Node* child, Node* replacement)\n{\n\tif (!child || !replacement) return false;\n\n\tCompositeIndex index = indexOf(child);\n\tQ_ASSERT(index.isValid());\n\tQ_ASSERT( !replacement || replacement->isSubtypeOf(meta_.attribute(index).type()));\n\texecute(new CompositeNodeChangeChild(this, replacement, index, &subnodes_));\n\treturn true;\n}\n\nbool CompositeNode::hasAttribute(const QString& attributeName)\n{\n\treturn meta_.hasAttribute(attributeName);\n}\n\nQList< QPair<QString, Node*> > CompositeNode::getAllAttributes(bool includeNullValues)\n{\n\tQList< QPair<QString, Node*> > result;\n\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] || includeNullValues )\n\t\t\t\tresult.append(QPair<QString, Node*>((*currentLevel)[i].name(), subnodes_[level][i]));\n\t}\n\n\treturn result;\n}\n\nvoid CompositeNode::save(PersistentStore &store) const\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] != nullptr && currentLevel->at(i).persistent() )\n\t\t\t\tstore.saveNode(subnodes_[level][i], currentLevel->at(i).name());\n\t}\n}\n\nvoid CompositeNode::load(PersistentStore &store)\n{\n\tif (store.currentNodeType() != typeName())\n\t\tthrow ModelException(\"Trying to load a CompositeNode from an incompatible node type \"\n\t\t\t\t+ store.currentNodeType());\n\n\tremoveAllNodes();\n\n\tQSet<QString> partial;\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( currentLevel->at(i).partial() )\n\t\t\t\tpartial.insert(currentLevel->at(i).name());\n\t}\n\n\tQList<LoadedNode> children = store.loadAllSubNodes(this, partial);\n\n\tfor (QList<LoadedNode>::iterator ln = children.begin(); ln != children.end(); ln++)\n\t{\n\t\tCompositeIndex index = meta_.indexForAttribute(ln->name);\n\t\tif ( !index.isValid() )\n\t\t\tthrow ModelException(\"Node has attribute \"\n\t\t\t\t\t+ ln->name + \" in persistent store, but this attribute is not registered\");\n\n\t\tauto attribute = meta_.attribute(index);\n\t\tQ_ASSERT(ln->node->isSubtypeOf(attribute.type()));\n\n\t\t\/\/ Skip loading partial optional children.\n\t\tif (!store.isLoadingPartially() || !attribute.optional() || !attribute.partial())\n\t\t\texecute(new CompositeNodeChangeChild(this, ln->node, CompositeIndex(index.level(), index.index()), &subnodes_));\n\t}\n\n\tverifyHasAllMandatoryAttributes();\n}\n\nvoid CompositeNode::removeAllNodes()\n{\n\tfor (int level = 0; level < subnodes_.size(); ++level)\n\t\tfor (int i = 0; i < subnodes_[level].size(); ++i)\n\t\t\tif ( subnodes_[level][i] )\n\t\t\t\texecute(new CompositeNodeChangeChild(this, nullptr, CompositeIndex(level, i), &subnodes_));\n}\n\nvoid CompositeNode::verifyHasAllMandatoryAttributes()\n{\n\tfor (int level = 0; level < meta_.numLevels(); ++level)\n\t{\n\t\tAttributeChain* currentLevel = meta_.level(level);\n\n\t\tfor (int i = 0; i < currentLevel->size(); ++i)\n\t\t\tif ( subnodes_[level][i] == nullptr && (*currentLevel)[i].optional() == false )\n\t\t\t\tthrow ModelException(\"An CompositeNode of type '\" + meta_.typeName()\n\t\t\t\t\t\t+ \"' has an uninitialized mandatory attribute '\"\n\t\t\t\t\t\t+ (*currentLevel)[i].name() +\"'\");\n\t}\n}\n\nvoid CompositeNode::remove(const CompositeIndex &attributeIndex)\n{\n\tQ_ASSERT(attributeIndex.isValid());\n\n\tif ( meta_.attribute(attributeIndex).optional() )\n\t\texecute(new CompositeNodeChangeChild(\tthis, nullptr, attributeIndex, &subnodes_));\n\telse\n\t\texecute(new CompositeNodeChangeChild(\tthis, Node::createNewNode(meta_.attribute(attributeIndex).type(), nullptr),\n\t\t\t\tattributeIndex, &subnodes_));\n}\n\nvoid CompositeNode::remove(Node* childNode)\n{\n\tQ_ASSERT(childNode);\n\tremove(indexOf(childNode));\n}\n\nvoid CompositeNode::remove(QString childNodeName)\n{\n\tremove(indexOf(childNodeName));\n}\n\nNode* CompositeNode::setDefault(QString nodeName)\n{\n\tauto attributeIndex = indexOf(nodeName);\n\n\tauto newNode = Node::createNewNode(meta_.attribute(attributeIndex).type());\n\tset(attributeIndex, newNode);\n\n\treturn newNode;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkTBBMultiThreader.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkProcessObject.h\"\n#include <iostream>\n#include <atomic>\n#include <thread>\n#include \"tbb\/parallel_for.h\"\n\nnamespace itk\n{\n\nTBBMultiThreader::TBBMultiThreader()\n{\n m_SingleMethod = nullptr;\n m_SingleData = nullptr;\n\n m_NumberOfThreads = std::max(1u, GetGlobalDefaultNumberOfThreads());\n}\n\nTBBMultiThreader::~TBBMultiThreader()\n{\n}\n\nvoid TBBMultiThreader::SetSingleMethod(ThreadFunctionType f, void *data)\n{\n m_SingleMethod = f;\n m_SingleData = data;\n}\n\nvoid TBBMultiThreader::SingleMethodExecute()\n{\n if( !m_SingleMethod )\n {\n itkExceptionMacro(<< \"No single method set!\");\n }\n\n \/\/we request grain size of 1 and simple_partitioner to ensure there is no chunking\n tbb::parallel_for(tbb::blocked_range<int>(0, m_NumberOfThreads, 1), [&](tbb::blocked_range<int>r)\n {\n \/\/ Make sure that TBB did not call us with a block of \"threads\"\n \/\/ but rather with only one \"thread\" to handle\n itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());\n\n ThreadInfoStruct ti;\n ti.ThreadID = r.begin();\n ti.UserData = m_SingleData;\n ti.NumberOfThreads = m_NumberOfThreads;\n m_SingleMethod(&ti); \/\/TBB takes care of properly propagating exceptions\n },\n tbb::simple_partitioner());\n}\n\nvoid TBBMultiThreader::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\nvoid\nTBBMultiThreader\n::ParallelizeArray(\n SizeValueType firstIndex,\n SizeValueType lastIndexPlus1,\n ArrayThreadingFunctorType aFunc,\n ProcessObject* filter )\n{\n if (filter)\n {\n filter->UpdateProgress(0.0f);\n }\n\n if ( firstIndex + 1 < lastIndexPlus1 )\n {\n unsigned count = lastIndexPlus1 - firstIndex;\n std::atomic< SizeValueType > progress = 0;\n std::thread::id callingThread = std::this_thread::get_id();\n \/\/we request grain size of 1 and simple_partitioner to ensure there is no chunking\n tbb::parallel_for(\n tbb::blocked_range<SizeValueType>(firstIndex, lastIndexPlus1, 1),\n [&](tbb::blocked_range<SizeValueType>r)\n {\n \/\/ Make sure that TBB did not call us with a block of \"threads\"\n \/\/ but rather with only one \"thread\" to handle\n itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());\n if ( filter && filter->GetAbortGenerateData() )\n {\n std::string msg;\n ProcessAborted e( __FILE__, __LINE__ );\n msg += \"AbortGenerateData was called in \" + std::string( filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n\n aFunc( r.begin() ); \/\/invoke the function\n\n if ( filter )\n {\n ++progress;\n \/\/make sure we are updating progress only from the thead which invoked us\n if ( callingThread == std::this_thread::get_id() )\n {\n filter->UpdateProgress( float( progress ) \/ count );\n }\n }\n },\n tbb::simple_partitioner());\n }\n else if ( firstIndex + 1 == lastIndexPlus1 )\n {\n aFunc( firstIndex );\n }\n \/\/ else nothing needs to be executed\n\n if (filter)\n {\n filter->UpdateProgress(1.0f);\n if (filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n }\n}\n\n}\n\nnamespace\n{\nstruct TBBImageRegionSplitter : public itk::ImageIORegion\n{\n static const bool is_splittable_in_proportion = true;\n TBBImageRegionSplitter(const TBBImageRegionSplitter&) = default;\n TBBImageRegionSplitter(const itk::ImageIORegion& region)\n :itk::ImageIORegion(region) \/\/use itk::ImageIORegion's copy constructor\n {}\n TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::split)\n :TBBImageRegionSplitter(region, tbb::proportional_split(1, 1)) \/\/delegate to proportional split\n {}\n\n TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::proportional_split p)\n {\n *this = region; \/\/most things will be the same\n for (int d = int(this->GetImageDimension()) - 1; d >= 0; d--) \/\/prefer to split along highest dimension\n {\n if (this->GetSize(d) > 1) \/\/split along this dimension\n {\n size_t myP = (this->GetSize(d) * p.right()) \/ (p.left() + p.right());\n if (myP == 0)\n {\n ++myP;\n }\n else if (myP == this->GetSize(d))\n {\n --myP;\n }\n this->SetSize(d, myP);\n region.SetSize(d, region.GetSize(d) - myP);\n region.SetIndex(d, myP + region.GetIndex(d));\n return;\n }\n }\n itkGenericExceptionMacro(\"An ImageIORegion could not be split. Region: \" << region);\n }\n\n bool empty() const\n {\n for (unsigned d = 0; d < this->GetImageDimension(); d++)\n {\n if (this->GetSize(d) == 0)\n {\n return true;\n }\n }\n return false;\n }\n\n bool is_divisible() const\n {\n for (unsigned d = 0; d < this->GetImageDimension(); d++)\n {\n if (this->GetSize(d) > 1)\n {\n return true;\n }\n }\n return false;\n }\n\n};\/\/TBBImageRegionSplitter struct definition\n}\/\/anonymous namespace\n\nnamespace itk\n{\nvoid TBBMultiThreader\n::ParallelizeImageRegion(\n unsigned int dimension,\n const IndexValueType index[],\n const SizeValueType size[],\n ThreadingFunctorType funcP,\n ProcessObject* filter)\n{\n if (filter)\n {\n filter->UpdateProgress(0.0f);\n }\n\n if (m_NumberOfThreads == 1) \/\/no multi-threading wanted\n {\n funcP(index, size);\n }\n else \/\/normal multi-threading\n {\n ImageIORegion region(dimension);\n for (unsigned d = 0; d < dimension; d++)\n {\n region.SetIndex(d, index[d]);\n region.SetSize(d, size[d]);\n }\n TBBImageRegionSplitter regionSplitter = region; \/\/use copy constructor\n\n std::atomic<SizeValueType> pixelProgress = { 0 };\n SizeValueType totalCount = region.GetNumberOfPixels();\n std::thread::id callingThread = std::this_thread::get_id();\n\n tbb::parallel_for(regionSplitter, [&](TBBImageRegionSplitter regionToProcess)\n {\n if (filter && filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n funcP(®ionToProcess.GetIndex()[0], ®ionToProcess.GetSize()[0]);\n if (filter) \/\/filter is provided, update progress\n {\n SizeValueType pixelCount = regionToProcess.GetNumberOfPixels();\n pixelProgress += pixelCount;\n \/\/make sure we are updating progress only from the thead which invoked filter->Update();\n if (callingThread == std::this_thread::get_id())\n {\n filter->UpdateProgress(float(pixelProgress) \/ totalCount);\n }\n }\n }); \/\/we implicitly use auto_partitioner for load balancing\n }\n\n if (filter)\n {\n filter->UpdateProgress(1.0f);\n if (filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n }\n}\n}\n<commit_msg>COMP: Address usage of deleted assignment operator<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkTBBMultiThreader.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkProcessObject.h\"\n#include <iostream>\n#include <atomic>\n#include <thread>\n#include \"tbb\/parallel_for.h\"\n\nnamespace itk\n{\n\nTBBMultiThreader::TBBMultiThreader()\n{\n m_SingleMethod = nullptr;\n m_SingleData = nullptr;\n\n m_NumberOfThreads = std::max(1u, GetGlobalDefaultNumberOfThreads());\n}\n\nTBBMultiThreader::~TBBMultiThreader()\n{\n}\n\nvoid TBBMultiThreader::SetSingleMethod(ThreadFunctionType f, void *data)\n{\n m_SingleMethod = f;\n m_SingleData = data;\n}\n\nvoid TBBMultiThreader::SingleMethodExecute()\n{\n if( !m_SingleMethod )\n {\n itkExceptionMacro(<< \"No single method set!\");\n }\n\n \/\/we request grain size of 1 and simple_partitioner to ensure there is no chunking\n tbb::parallel_for(tbb::blocked_range<int>(0, m_NumberOfThreads, 1), [&](tbb::blocked_range<int>r)\n {\n \/\/ Make sure that TBB did not call us with a block of \"threads\"\n \/\/ but rather with only one \"thread\" to handle\n itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());\n\n ThreadInfoStruct ti;\n ti.ThreadID = r.begin();\n ti.UserData = m_SingleData;\n ti.NumberOfThreads = m_NumberOfThreads;\n m_SingleMethod(&ti); \/\/TBB takes care of properly propagating exceptions\n },\n tbb::simple_partitioner());\n}\n\nvoid TBBMultiThreader::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\nvoid\nTBBMultiThreader\n::ParallelizeArray(\n SizeValueType firstIndex,\n SizeValueType lastIndexPlus1,\n ArrayThreadingFunctorType aFunc,\n ProcessObject* filter )\n{\n if (filter)\n {\n filter->UpdateProgress(0.0f);\n }\n\n if ( firstIndex + 1 < lastIndexPlus1 )\n {\n unsigned count = lastIndexPlus1 - firstIndex;\n std::atomic< SizeValueType > progress( 0 );\n std::thread::id callingThread = std::this_thread::get_id();\n \/\/we request grain size of 1 and simple_partitioner to ensure there is no chunking\n tbb::parallel_for(\n tbb::blocked_range<SizeValueType>(firstIndex, lastIndexPlus1, 1),\n [&](tbb::blocked_range<SizeValueType>r)\n {\n \/\/ Make sure that TBB did not call us with a block of \"threads\"\n \/\/ but rather with only one \"thread\" to handle\n itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());\n if ( filter && filter->GetAbortGenerateData() )\n {\n std::string msg;\n ProcessAborted e( __FILE__, __LINE__ );\n msg += \"AbortGenerateData was called in \" + std::string( filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n\n aFunc( r.begin() ); \/\/invoke the function\n\n if ( filter )\n {\n ++progress;\n \/\/make sure we are updating progress only from the thead which invoked us\n if ( callingThread == std::this_thread::get_id() )\n {\n filter->UpdateProgress( float( progress ) \/ count );\n }\n }\n },\n tbb::simple_partitioner());\n }\n else if ( firstIndex + 1 == lastIndexPlus1 )\n {\n aFunc( firstIndex );\n }\n \/\/ else nothing needs to be executed\n\n if (filter)\n {\n filter->UpdateProgress(1.0f);\n if (filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n }\n}\n\n}\n\nnamespace\n{\nstruct TBBImageRegionSplitter : public itk::ImageIORegion\n{\n static const bool is_splittable_in_proportion = true;\n TBBImageRegionSplitter(const TBBImageRegionSplitter&) = default;\n TBBImageRegionSplitter(const itk::ImageIORegion& region)\n :itk::ImageIORegion(region) \/\/use itk::ImageIORegion's copy constructor\n {}\n TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::split)\n :TBBImageRegionSplitter(region, tbb::proportional_split(1, 1)) \/\/delegate to proportional split\n {}\n\n TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::proportional_split p)\n {\n *this = region; \/\/most things will be the same\n for (int d = int(this->GetImageDimension()) - 1; d >= 0; d--) \/\/prefer to split along highest dimension\n {\n if (this->GetSize(d) > 1) \/\/split along this dimension\n {\n size_t myP = (this->GetSize(d) * p.right()) \/ (p.left() + p.right());\n if (myP == 0)\n {\n ++myP;\n }\n else if (myP == this->GetSize(d))\n {\n --myP;\n }\n this->SetSize(d, myP);\n region.SetSize(d, region.GetSize(d) - myP);\n region.SetIndex(d, myP + region.GetIndex(d));\n return;\n }\n }\n itkGenericExceptionMacro(\"An ImageIORegion could not be split. Region: \" << region);\n }\n\n bool empty() const\n {\n for (unsigned d = 0; d < this->GetImageDimension(); d++)\n {\n if (this->GetSize(d) == 0)\n {\n return true;\n }\n }\n return false;\n }\n\n bool is_divisible() const\n {\n for (unsigned d = 0; d < this->GetImageDimension(); d++)\n {\n if (this->GetSize(d) > 1)\n {\n return true;\n }\n }\n return false;\n }\n\n};\/\/TBBImageRegionSplitter struct definition\n}\/\/anonymous namespace\n\nnamespace itk\n{\nvoid TBBMultiThreader\n::ParallelizeImageRegion(\n unsigned int dimension,\n const IndexValueType index[],\n const SizeValueType size[],\n ThreadingFunctorType funcP,\n ProcessObject* filter)\n{\n if (filter)\n {\n filter->UpdateProgress(0.0f);\n }\n\n if (m_NumberOfThreads == 1) \/\/no multi-threading wanted\n {\n funcP(index, size);\n }\n else \/\/normal multi-threading\n {\n ImageIORegion region(dimension);\n for (unsigned d = 0; d < dimension; d++)\n {\n region.SetIndex(d, index[d]);\n region.SetSize(d, size[d]);\n }\n TBBImageRegionSplitter regionSplitter = region; \/\/use copy constructor\n\n std::atomic<SizeValueType> pixelProgress = { 0 };\n SizeValueType totalCount = region.GetNumberOfPixels();\n std::thread::id callingThread = std::this_thread::get_id();\n\n tbb::parallel_for(regionSplitter, [&](TBBImageRegionSplitter regionToProcess)\n {\n if (filter && filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n funcP(®ionToProcess.GetIndex()[0], ®ionToProcess.GetSize()[0]);\n if (filter) \/\/filter is provided, update progress\n {\n SizeValueType pixelCount = regionToProcess.GetNumberOfPixels();\n pixelProgress += pixelCount;\n \/\/make sure we are updating progress only from the thead which invoked filter->Update();\n if (callingThread == std::this_thread::get_id())\n {\n filter->UpdateProgress(float(pixelProgress) \/ totalCount);\n }\n }\n }); \/\/we implicitly use auto_partitioner for load balancing\n }\n\n if (filter)\n {\n filter->UpdateProgress(1.0f);\n if (filter->GetAbortGenerateData())\n {\n std::string msg;\n ProcessAborted e(__FILE__, __LINE__);\n msg += \"AbortGenerateData was called in \" + std::string(filter->GetNameOfClass() )\n + \" during multi-threaded part of filter execution\";\n e.SetDescription(msg);\n throw e;\n }\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Remove unused function<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/---------------------------- non_primitive_1.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2002 by the deal.II authors and Anna Schneebeli\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- non_primitive_1.cc ---------------------------\n\n\n\/\/ check some things about Nedelec elements, basically also that the\n\/\/ DoFRenumbering::component_wise function also works for\n\/\/ non_primitive elements, for which it did not work previously since\n\/\/ there is no component to associate a non-primitive shape function\n\/\/ with\n\/\/\n\/\/ this program is similar to anna_1, except that it tests the\n\/\/ component_wise function with a different order of components than\n\/\/ the default is.\n\/\/\n\/\/ this program is a modified version of one by Anna Schneebeli,\n\/\/ University of Basel\n\n#include <base\/logstream.h>\n#include <grid\/tria.h>\n#include <dofs\/dof_handler.h>\n#include <grid\/grid_generator.h>\n#include <grid\/tria_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <dofs\/dof_accessor.h>\n#include <dofs\/dof_tools.h>\n#include <fe\/fe_system.h>\t\t\n#include <fe\/fe_q.h>\n#include <fe\/fe_nedelec.h>\n#include <fe\/fe_base.h>\n#include <numerics\/dof_renumbering.h>\n#include <iostream>\n#include <fstream>\n\n\ntemplate <int dim>\nclass SystemTest \n{\n public:\n SystemTest ();\n void run (); \n\t\t\t\t \n private:\n void make_grid_and_dofs ();\n void shape_to_components ();\n void check_numbering ();\n\n\t\t\t\t \n Triangulation<dim> triangulation;\n FESystem<dim> fe;\n DoFHandler<dim> dof_handler;\n\n\t\t\t\t \n};\n\ntemplate <int dim>\nSystemTest<dim>::SystemTest () :\n fe (FE_Nedelec<dim>(1), 2,\n FE_Q<dim>(1), 1),\n\t\tdof_handler (triangulation)\n{};\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::make_grid_and_dofs ()\n{\n\t\t\t\t \n GridGenerator::hyper_cube (triangulation, -1, 1);\n triangulation.refine_global (0);\n deallog << \"Number of active cells: \" << triangulation.n_active_cells()\n << std::endl;\n deallog << \"Total number of cells: \" << triangulation.n_cells()\n << std::endl;\n\t\t\t\t \n dof_handler.distribute_dofs (fe);\n deallog << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n << std::endl;\n\t\t\t\t \n};\n\ntemplate <int dim>\nvoid SystemTest<dim>::shape_to_components () \n{\n \/\/ testing, if the shape function\n \/\/ with index i is of type Nedelec:\n \/\/ (i.e. the first component of the FESystem)\n \/\/ 1 for yes, 0 for no.\n \n for(unsigned int i = 0; i<fe.dofs_per_cell; i++)\n deallog <<\" shapefunction \"<< i << \" is Nedelec: \"\n << (fe.is_primitive(i) ? \"false\" : \"true\") << std::endl;\n};\n\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::check_numbering () \n{\n DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n std::vector<unsigned int>\tlocal_dof_indices(fe.dofs_per_cell);\n\t\n for (; cell!=endc; ++cell)\n {\n cell->get_dof_indices (local_dof_indices);\n for (unsigned int i=0; i<fe.dofs_per_cell; i++)\n deallog <<\" DoF \"<< local_dof_indices[i] << \" belongs to base element \" \n << fe.system_to_base_index(i).first.first\n << \", instance \" << fe.system_to_base_index(i).first.second\n << std::endl;\n deallog<< std::endl;\n };\n\t \n\t \n \/\/Now: Componentwise reodering of the dofs\n\t\n deallog << \" Now we renumber the DoFs anti-component-wise:\" << std::endl;\n deallog << \" *********************************************\" << std::endl;\n std::vector<unsigned int> comp(fe.n_components());\n for (unsigned int i=0; i<comp.size(); ++i)\n comp[i] = comp.size()-i-1;\n DoFRenumbering::component_wise (dof_handler, comp);\n\t\n cell = dof_handler.begin_active();\n endc = dof_handler.end();\n\t\n for (; cell!=endc; ++cell)\n {\n cell->get_dof_indices (local_dof_indices);\n for(unsigned int i=0; i<fe.dofs_per_cell; i++)\n deallog <<\" DoF \"<< local_dof_indices[i] << \" belongs to base \" \n << fe.system_to_base_index(i).first.first\n << \", instance \" << fe.system_to_base_index(i).first.second\n << std::endl;\n deallog << std::endl;\n };\n\t\n};\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::run () \n{\n make_grid_and_dofs ();\n shape_to_components ();\n check_numbering();\n};\n\n \n\nint main () \n{\n std::ofstream logfile(\"anna_2.output\");\n deallog.attach(logfile);\n deallog.depth_console(0);\n\n SystemTest<2>().run();\n SystemTest<3>().run(); \n return 0;\n};\n<commit_msg>Fix name of program.<commit_after>\/\/---------------------------- anna_2.cc ---------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2002 by the deal.II authors and Anna Schneebeli\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------- anna_2.cc ---------------------------\n\n\n\/\/ check some things about Nedelec elements, basically also that the\n\/\/ DoFRenumbering::component_wise function also works for\n\/\/ non_primitive elements, for which it did not work previously since\n\/\/ there is no component to associate a non-primitive shape function\n\/\/ with\n\/\/\n\/\/ this program is similar to anna_1, except that it tests the\n\/\/ component_wise function with a different order of components than\n\/\/ the default is.\n\/\/\n\/\/ this program is a modified version of one by Anna Schneebeli,\n\/\/ University of Basel\n\n#include <base\/logstream.h>\n#include <grid\/tria.h>\n#include <dofs\/dof_handler.h>\n#include <grid\/grid_generator.h>\n#include <grid\/tria_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <dofs\/dof_accessor.h>\n#include <dofs\/dof_tools.h>\n#include <fe\/fe_system.h>\t\t\n#include <fe\/fe_q.h>\n#include <fe\/fe_nedelec.h>\n#include <fe\/fe_base.h>\n#include <numerics\/dof_renumbering.h>\n#include <iostream>\n#include <fstream>\n\n\ntemplate <int dim>\nclass SystemTest \n{\n public:\n SystemTest ();\n void run (); \n\t\t\t\t \n private:\n void make_grid_and_dofs ();\n void shape_to_components ();\n void check_numbering ();\n\n\t\t\t\t \n Triangulation<dim> triangulation;\n FESystem<dim> fe;\n DoFHandler<dim> dof_handler;\n\n\t\t\t\t \n};\n\ntemplate <int dim>\nSystemTest<dim>::SystemTest () :\n fe (FE_Nedelec<dim>(1), 2,\n FE_Q<dim>(1), 1),\n\t\tdof_handler (triangulation)\n{};\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::make_grid_and_dofs ()\n{\n\t\t\t\t \n GridGenerator::hyper_cube (triangulation, -1, 1);\n triangulation.refine_global (0);\n deallog << \"Number of active cells: \" << triangulation.n_active_cells()\n << std::endl;\n deallog << \"Total number of cells: \" << triangulation.n_cells()\n << std::endl;\n\t\t\t\t \n dof_handler.distribute_dofs (fe);\n deallog << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n << std::endl;\n\t\t\t\t \n};\n\ntemplate <int dim>\nvoid SystemTest<dim>::shape_to_components () \n{\n \/\/ testing, if the shape function\n \/\/ with index i is of type Nedelec:\n \/\/ (i.e. the first component of the FESystem)\n \/\/ 1 for yes, 0 for no.\n \n for(unsigned int i = 0; i<fe.dofs_per_cell; i++)\n deallog <<\" shapefunction \"<< i << \" is Nedelec: \"\n << (fe.is_primitive(i) ? \"false\" : \"true\") << std::endl;\n};\n\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::check_numbering () \n{\n DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),\n endc = dof_handler.end();\n std::vector<unsigned int>\tlocal_dof_indices(fe.dofs_per_cell);\n\t\n for (; cell!=endc; ++cell)\n {\n cell->get_dof_indices (local_dof_indices);\n for (unsigned int i=0; i<fe.dofs_per_cell; i++)\n deallog <<\" DoF \"<< local_dof_indices[i] << \" belongs to base element \" \n << fe.system_to_base_index(i).first.first\n << \", instance \" << fe.system_to_base_index(i).first.second\n << std::endl;\n deallog<< std::endl;\n };\n\t \n\t \n \/\/Now: Componentwise reodering of the dofs\n\t\n deallog << \" Now we renumber the DoFs anti-component-wise:\" << std::endl;\n deallog << \" *********************************************\" << std::endl;\n std::vector<unsigned int> comp(fe.n_components());\n for (unsigned int i=0; i<comp.size(); ++i)\n comp[i] = comp.size()-i-1;\n DoFRenumbering::component_wise (dof_handler, comp);\n\t\n cell = dof_handler.begin_active();\n endc = dof_handler.end();\n\t\n for (; cell!=endc; ++cell)\n {\n cell->get_dof_indices (local_dof_indices);\n for(unsigned int i=0; i<fe.dofs_per_cell; i++)\n deallog <<\" DoF \"<< local_dof_indices[i] << \" belongs to base \" \n << fe.system_to_base_index(i).first.first\n << \", instance \" << fe.system_to_base_index(i).first.second\n << std::endl;\n deallog << std::endl;\n };\n\t\n};\n\n\ntemplate <int dim>\nvoid SystemTest<dim>::run () \n{\n make_grid_and_dofs ();\n shape_to_components ();\n check_numbering();\n};\n\n \n\nint main () \n{\n std::ofstream logfile(\"anna_2.output\");\n deallog.attach(logfile);\n deallog.depth_console(0);\n\n SystemTest<2>().run();\n SystemTest<3>().run(); \n return 0;\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/Carlos\/architecture\/DllExports.h\"\n#include \"class.MyServerSocket.hpp\"\n#include \"split.h\"\n#include \"..\/Carlos\/architecture\/modules\/fake\/class.FakeModulAndroid.hpp\"\n#include <windows.h>\n#include <iostream>\n#include <process.h> \n#include <iostream>\n\nusing namespace Architecture;\nusing namespace std;\n\n\/**\n* Modul ktory riadi TCP server a napoji tento server.\n* Tento modul je potom napojeny na halvnu apliakciu cez DLL subor.\n*\/\nclass TCPServer : public FakeModulAndroid, MessageHandler {\nprivate:\n\tServerSocket* server;\n\npublic:\n\t\/\/ Nas modul ma zatial nacitavat fake GPS suranice zo suboru \n\tTCPServer() : FakeModulAndroid(\"data\/video\/2013-10-20-12-25-52.txt\") {\n\t\tserver = NULL;\n\t}\n\n\t\/\/ Nas modul sa spusta\n\tvirtual void init() {\n\t\tFakeModulAndroid::init();\n\t\tcout << \"Native TCP server starting\\n\";\n\t\tserver = new MyServerSocket(this, \"10.0.0.107\", \"1234\");\n\t\tserver->start();\n\t}\n\n\t\/\/ Zachytavam spravy od clienta\n\tvoid HandleMessage(char* input) {\n\t\tstring inputText = input;\n\t\tcout << \"Reading\\n\" + inputText + \"\\n\";\n\t\tsize_t pos = inputText.find(\":\");\n\t\tif(pos == -1) {\n\t\t\tcout << \"Sprava nieje spravne formatovana.\\n\";\n\t\t\treturn;\n\t\t}\n\t\tstring key = inputText.substr(pos);\n\t\tstring value = inputText.substr(pos, inputText.length()); \n\n\t\t\/\/ Citaj prikaz\n\t\tif (key.compare(\"Command\") != 0) {\n\t\t\t\/\/sendRandomNumberResponse();\n\t\t\tupdateCommand(value); \/\/ TODO: tu ostava :\n\t\t\treturn;\n\t\t} \n\n\t\t\/\/ Citaj GPS\n\t\tif (key.compare(\"gps\") != 0) {\n\t\t\tvector<string> v;\n\t\t\tsplit(value, v);\n\t\t\tGPS gps;\t\t\n\t\t\tgps.latitude = stod(v.at(0));\n\t\t\tgps.longitude = stod(v.at(1));\n\t\t\tsetGPS(gps);\n\t\t\treturn;\n\t\t} \n\n\t\tcout << \"Unkown command from tcp!\\n\";\n\t}\n\n\t\/\/ Posielam clientovy odpoved\n\t\/*void sendRandomNumberResponse() {\n\tchar buffer[512];\n\tbuffer[0] = 0;\n\tsprintf_s(buffer, \"Command:5\\n\");\n\tgetListener()->sendTEXT2Client(buffer);\n\t}*\/\n\n\t\/\/ Nas modul ma byt vypusteny zo systemu\n\t~TCPServer() {\n\t\tif(server != NULL) {\n\t\t\tdelete server;\n\t\t}\n\t}\n\n\t\/\/ Ma byt moodu lspusteny v samostatnom vlakne ?\n\tvirtual bool isThreaded() { return true; }\n};\n\n\/\/ Ked nas modul ma byt vytvoreny cez riadiaci modul\nIMPEXP void* callFactory() {\n\treturn static_cast< void* > (new TCPServer());\n}\n\n\/\/ Ked chceme modul spustit ako normalnu aplikaciu\nint main() { \n\tTCPServer* a = new TCPServer();\n\ta->init();\n\tdelete a;\n}\n\n\/\/ Ked nas modul je nacitany cez riadiaci modul\nint WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*) {\n\tprintf(\"Dll nacitane\\n\");\n\treturn 1;\n}<commit_msg>upravena ip<commit_after>#include \"..\/Carlos\/architecture\/DllExports.h\"\n#include \"class.MyServerSocket.hpp\"\n#include \"split.h\"\n#include \"..\/Carlos\/architecture\/modules\/fake\/class.FakeModulAndroid.hpp\"\n#include <windows.h>\n#include <iostream>\n#include <process.h> \n#include <iostream>\n\nusing namespace Architecture;\nusing namespace std;\n\n\/**\n* Modul ktory riadi TCP server a napoji tento server.\n* Tento modul je potom napojeny na halvnu apliakciu cez DLL subor.\n*\/\nclass TCPServer : public FakeModulAndroid, MessageHandler {\nprivate:\n\tServerSocket* server;\n\npublic:\n\t\/\/ Nas modul ma zatial nacitavat fake GPS suranice zo suboru \n\tTCPServer() : FakeModulAndroid(\"data\/video\/2013-10-20-12-25-52.txt\") {\n\t\tserver = NULL;\n\t}\n\n\t\/\/ Nas modul sa spusta\n\tvirtual void init() {\n\t\tFakeModulAndroid::init();\n\t\tcout << \"Native TCP server starting\\n\";\n\t\tserver = new MyServerSocket(this, \"192.168.247.1\", \"1234\");\n\t\tserver->start();\n\t}\n\n\t\/\/ Zachytavam spravy od clienta\n\tvoid HandleMessage(char* input) {\n\t\tstring inputText = input;\n\t\tcout << \"Reading\\n\" + inputText + \"\\n\";\n\t\tsize_t pos = inputText.find(\":\");\n\t\tif(pos == -1) {\n\t\t\tcout << \"Sprava nieje spravne formatovana.\\n\";\n\t\t\treturn;\n\t\t}\n\t\tstring key = inputText.substr(0, pos);\n\t\tstring value = inputText.substr(pos+1, inputText.length()); \n\n\t\t\/\/ Citaj prikaz\n\t\tif (key.compare(\"Command\") != 0) {\n\t\t\t\/\/sendRandomNumberResponse();\n\t\t\tupdateCommand(value); \/\/ TODO: tu ostava :\n\t\t\treturn;\n\t\t} \n\n\t\t\/\/ Citaj GPS\n\t\t\n\t\tif (key.compare(\"gps\") != 0) {\n\t\t\tvector<string> v;\n\t\t\tsplit(value, v);\n\t\t\tGPS gps;\t\t\n\t\t\tgps.latitude = stod(v.at(0));\n\t\t\tgps.longitude = stod(v.at(1));\n\t\t\tsetGPS(gps);\n\t\t\treturn;\n\t\t} \n\n\t\tcout << \"Unkown command from tcp!\\n\";\n\t}\n\n\t\/\/ Posielam clientovy odpoved\n\t\/*void sendRandomNumberResponse() {\n\tchar buffer[512];\n\tbuffer[0] = 0;\n\tsprintf_s(buffer, \"Command:5\\n\");\n\tgetListener()->sendTEXT2Client(buffer);\n\t}*\/\n\n\t\/\/ Nas modul ma byt vypusteny zo systemu\n\t~TCPServer() {\n\t\tif(server != NULL) {\n\t\t\tdelete server;\n\t\t}\n\t}\n\n\t\/\/ Ma byt moodu lspusteny v samostatnom vlakne ?\n\tvirtual bool isThreaded() { return true; }\n};\n\n\/\/ Ked nas modul ma byt vytvoreny cez riadiaci modul\nIMPEXP void* callFactory() {\n\treturn static_cast< void* > (new TCPServer());\n}\n\n\/\/ Ked chceme modul spustit ako normalnu aplikaciu\nint main() { \n\tTCPServer* a = new TCPServer();\n\ta->init();\n\tdelete a;\n}\n\n\/\/ Ked nas modul je nacitany cez riadiaci modul\nint WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*) {\n\tprintf(\"Dll nacitane\\n\");\n\treturn 1;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ This is the llc code generator.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include <memory>\n#include <fstream>\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/ \nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bytecode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<bool> Force(\"f\", cl::desc(\"Overwrite output files\"));\n\nenum ArchName { noarch, x86, Sparc };\n\nstatic cl::opt<ArchName>\nArch(\"march\", cl::desc(\"Architecture to generate assembly for:\"), cl::Prefix,\n cl::values(clEnumVal(x86, \" IA-32 (Pentium and above)\"),\n clEnumValN(Sparc, \"sparc\", \" SPARC V9\"),\n\t\t0),\n cl::init(noarch));\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename...\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename)\n{\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n \n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": bytecode didn't read correctly.\\n\";\n return 1;\n }\n Module &mod = *M.get();\n\n \/\/ Allocate target machine. First, check whether the user has\n \/\/ explicitly specified an architecture to compile for.\n TargetMachine* (*TargetMachineAllocator)(const Module&) = 0;\n switch (Arch) {\n case x86:\n TargetMachineAllocator = allocateX86TargetMachine;\n break;\n case Sparc:\n TargetMachineAllocator = allocateSparcTargetMachine;\n break;\n default:\n \/\/ Decide what the default target machine should be, by looking at\n \/\/ the module. This heuristic (ILP32, LE -> IA32; LP64, BE ->\n \/\/ SPARCV9) is kind of gross, but it will work until we have more\n \/\/ sophisticated target information to work from.\n if (mod.getEndianness() == Module::LittleEndian &&\n mod.getPointerSize() == Module::Pointer32) { \n TargetMachineAllocator = allocateX86TargetMachine;\n } else if (mod.getEndianness() == Module::BigEndian &&\n mod.getPointerSize() == Module::Pointer64) { \n TargetMachineAllocator = allocateSparcTargetMachine;\n } else {\n \/\/ If the module is target independent, favor a target which matches the\n \/\/ current build system.\n#if defined(i386) || defined(__i386__) || defined(__x86__)\n TargetMachineAllocator = allocateX86TargetMachine;\n#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)\n TargetMachineAllocator = allocateSparcTargetMachine;\n#else\n std::cerr << argv[0] << \": module does not specify a target to use. \"\n << \"You must use the -march option.\\n\";\n return 1;\n#endif\n } \n break;\n }\n std::auto_ptr<TargetMachine> target(TargetMachineAllocator(mod));\n assert(target.get() && \"Could not allocate target machine!\");\n TargetMachine &Target = *target.get();\n const TargetData &TD = Target.getTargetData();\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n\n Passes.add(new TargetData(\"llc\", TD.isLittleEndian(), TD.getPointerSize(),\n TD.getPointerAlignment(), TD.getDoubleAlignment()));\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") {\n if (OutputFilename != \"-\") {\n \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n\t\/\/ If force is not specified, make sure not to overwrite a file!\n\tstd::cerr << argv[0] << \": error opening '\" << OutputFilename\n\t\t << \"': file exists!\\n\"\n\t\t << \"Use -f command line argument to force output\\n\";\n\treturn 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n } else {\n Out = &std::cout;\n }\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n OutputFilename = GetFileNameRoot(InputFilename); \n OutputFilename += \".s\";\n \n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n \n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n \n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n\n \/\/ Ask the target to add backend passes as necessary\n if (Target.addPassesToEmitAssembly(Passes, *Out)) {\n std::cerr << argv[0] << \": target '\" << Target.getName()\n << \"' does not support static compilation!\\n\";\n if (Out != &std::cout) delete Out;\n \/\/ And the Out file is empty and useless, so remove it now.\n std::remove(OutputFilename.c_str());\n return 1;\n } else {\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n }\n\n \/\/ Delete the ostream if it's not a stdout stream\n if (Out != &std::cout) delete Out;\n\n return 0;\n}\n<commit_msg>Added code to avoid checking for .bc when the filename is too short.<commit_after>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ This is the llc code generator.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include <memory>\n#include <fstream>\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/ \nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bytecode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<bool> Force(\"f\", cl::desc(\"Overwrite output files\"));\n\nenum ArchName { noarch, x86, Sparc };\n\nstatic cl::opt<ArchName>\nArch(\"march\", cl::desc(\"Architecture to generate assembly for:\"), cl::Prefix,\n cl::values(clEnumVal(x86, \" IA-32 (Pentium and above)\"),\n clEnumValN(Sparc, \"sparc\", \" SPARC V9\"),\n\t\t0),\n cl::init(noarch));\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename...\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename)\n{\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if ((Len > 2) &&\n IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n \n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": bytecode didn't read correctly.\\n\";\n return 1;\n }\n Module &mod = *M.get();\n\n \/\/ Allocate target machine. First, check whether the user has\n \/\/ explicitly specified an architecture to compile for.\n TargetMachine* (*TargetMachineAllocator)(const Module&) = 0;\n switch (Arch) {\n case x86:\n TargetMachineAllocator = allocateX86TargetMachine;\n break;\n case Sparc:\n TargetMachineAllocator = allocateSparcTargetMachine;\n break;\n default:\n \/\/ Decide what the default target machine should be, by looking at\n \/\/ the module. This heuristic (ILP32, LE -> IA32; LP64, BE ->\n \/\/ SPARCV9) is kind of gross, but it will work until we have more\n \/\/ sophisticated target information to work from.\n if (mod.getEndianness() == Module::LittleEndian &&\n mod.getPointerSize() == Module::Pointer32) { \n TargetMachineAllocator = allocateX86TargetMachine;\n } else if (mod.getEndianness() == Module::BigEndian &&\n mod.getPointerSize() == Module::Pointer64) { \n TargetMachineAllocator = allocateSparcTargetMachine;\n } else {\n \/\/ If the module is target independent, favor a target which matches the\n \/\/ current build system.\n#if defined(i386) || defined(__i386__) || defined(__x86__)\n TargetMachineAllocator = allocateX86TargetMachine;\n#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)\n TargetMachineAllocator = allocateSparcTargetMachine;\n#else\n std::cerr << argv[0] << \": module does not specify a target to use. \"\n << \"You must use the -march option.\\n\";\n return 1;\n#endif\n } \n break;\n }\n std::auto_ptr<TargetMachine> target(TargetMachineAllocator(mod));\n assert(target.get() && \"Could not allocate target machine!\");\n TargetMachine &Target = *target.get();\n const TargetData &TD = Target.getTargetData();\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n\n Passes.add(new TargetData(\"llc\", TD.isLittleEndian(), TD.getPointerSize(),\n TD.getPointerAlignment(), TD.getDoubleAlignment()));\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") {\n if (OutputFilename != \"-\") {\n \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n\t\/\/ If force is not specified, make sure not to overwrite a file!\n\tstd::cerr << argv[0] << \": error opening '\" << OutputFilename\n\t\t << \"': file exists!\\n\"\n\t\t << \"Use -f command line argument to force output\\n\";\n\treturn 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n } else {\n Out = &std::cout;\n }\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n OutputFilename = GetFileNameRoot(InputFilename); \n OutputFilename += \".s\";\n \n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n \n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n \n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n\n \/\/ Ask the target to add backend passes as necessary\n if (Target.addPassesToEmitAssembly(Passes, *Out)) {\n std::cerr << argv[0] << \": target '\" << Target.getName()\n << \"' does not support static compilation!\\n\";\n if (Out != &std::cout) delete Out;\n \/\/ And the Out file is empty and useless, so remove it now.\n std::remove(OutputFilename.c_str());\n return 1;\n } else {\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n }\n\n \/\/ Delete the ostream if it's not a stdout stream\n if (Out != &std::cout) delete Out;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llc.cpp - Implement the LLVM Compiler -----------------------------===\/\/\n\/\/\n\/\/ This is the llc compiler driver.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/Sparc.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/Instrumentation\/TraceValues.h\"\n#include \"llvm\/Transforms\/ChangeAllocations.h\"\n#include \"llvm\/Transforms\/HoistPHIConstants.h\"\n#include \"llvm\/Transforms\/Scalar\/DecomposeMultiDimRefs.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Transforms\/ConstantMerge.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/PassManager.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include <memory>\n#include <fstream>\nusing std::string;\n\nstatic cl::String InputFilename (\"\", \"Input filename\", cl::NoFlags, \"-\");\nstatic cl::String OutputFilename(\"o\", \"Output filename\", cl::NoFlags, \"\");\nstatic cl::Flag Force (\"f\", \"Overwrite output files\");\nstatic cl::Flag DumpAsm (\"d\", \"Print bytecode before native code generation\", cl::Hidden);\n\nenum TraceLevel {\n TraceOff, TraceFunctions, TraceBasicBlocks\n};\n\nstatic cl::Enum<enum TraceLevel> TraceValues(\"trace\", cl::NoFlags,\n \"Trace values through functions or basic blocks\",\n clEnumValN(TraceOff , \"off\", \"Disable trace code\"),\n clEnumValN(TraceFunctions , \"function\", \"Trace each function\"),\n clEnumValN(TraceBasicBlocks, \"basicblock\", \"Trace each basic block\"), 0);\n\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename...\nstatic inline string GetFileNameRoot(const string &InputFilename) {\n string IFN = InputFilename;\n string outputFilename;\n int Len = IFN.length();\n if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ Function main()\n\/\/ \n\/\/ Entry point for the llc compiler.\n\/\/===---------------------------------------------------------------------===\/\/\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n \n \/\/ Allocate a target... in the future this will be controllable on the\n \/\/ command line.\n std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());\n assert(target.get() && \"Could not allocate target machine!\");\n\n TargetMachine &Target = *target.get();\n \n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n cerr << \"bytecode didn't read correctly.\\n\";\n return 1;\n }\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n\n \/\/ Hoist constants out of PHI nodes into predecessor BB's\n Passes.add(createHoistPHIConstantsPass());\n\n if (TraceValues != TraceOff) { \/\/ If tracing enabled...\n \/\/ Insert trace code in all functions in the module\n if (TraceValues == TraceBasicBlocks)\n Passes.add(createTraceValuesPassForBasicBlocks());\n else if (TraceValues == TraceFunctions)\n Passes.add(createTraceValuesPassForFunction());\n else\n assert(0 && \"Bad value for TraceValues!\");\n\n \/\/ Eliminate duplication in constant pool\n Passes.add(createDynamicConstantMergePass());\n }\n \n \/\/ Decompose multi-dimensional refs into a sequence of 1D refs\n Passes.add(createDecomposeMultiDimRefsPass());\n \n \/\/ Write out the module with tracing code just before code generation\n if (TraceValues != TraceOff) { \/\/ If tracing enabled...\n assert(InputFilename != \"-\" &&\n \"files on stdin not supported with tracing\");\n string traceFileName = GetFileNameRoot(InputFilename) + \".trace.bc\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n \n std::ostream *os = new std::ofstream(traceFileName.c_str());\n if (!os->good()) {\n cerr << \"Error opening \" << traceFileName\n << \"! SKIPPING OUTPUT OF TRACE CODE\\n\";\n delete os;\n return 1;\n }\n \n Passes.add(new WriteBytecodePass(os, true));\n }\n \n \/\/ Replace malloc and free instructions with library calls.\n \/\/ Do this after tracing until lli implements these lib calls.\n \/\/ For now, it will emulate malloc and free internally.\n Passes.add(createLowerAllocationsPass(Target.DataLayout));\n \n \/\/ If LLVM dumping after transformations is requested, add it to the pipeline\n if (DumpAsm)\n Passes.add(new PrintFunctionPass(\"Code after xformations: \\n\", &cerr));\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") { \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n string OutputFilename = GetFileNameRoot(InputFilename); \n OutputFilename += \".s\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n cerr << \"Error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n \n Target.addPassesToEmitAssembly(Passes, *Out);\n \n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(M.get());\n\n if (Out != &std::cout) delete Out;\n\n return 0;\n}\n<commit_msg>Remove unneccesary pass.<commit_after>\/\/===-- llc.cpp - Implement the LLVM Compiler -----------------------------===\/\/\n\/\/\n\/\/ This is the llc compiler driver.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/Sparc.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/Instrumentation\/TraceValues.h\"\n#include \"llvm\/Transforms\/ChangeAllocations.h\"\n#include \"llvm\/Transforms\/Scalar\/DecomposeMultiDimRefs.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Transforms\/ConstantMerge.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/PassManager.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include <memory>\n#include <fstream>\nusing std::string;\n\nstatic cl::String InputFilename (\"\", \"Input filename\", cl::NoFlags, \"-\");\nstatic cl::String OutputFilename(\"o\", \"Output filename\", cl::NoFlags, \"\");\nstatic cl::Flag Force (\"f\", \"Overwrite output files\");\nstatic cl::Flag DumpAsm (\"d\", \"Print bytecode before native code generation\", cl::Hidden);\n\nenum TraceLevel {\n TraceOff, TraceFunctions, TraceBasicBlocks\n};\n\nstatic cl::Enum<enum TraceLevel> TraceValues(\"trace\", cl::NoFlags,\n \"Trace values through functions or basic blocks\",\n clEnumValN(TraceOff , \"off\", \"Disable trace code\"),\n clEnumValN(TraceFunctions , \"function\", \"Trace each function\"),\n clEnumValN(TraceBasicBlocks, \"basicblock\", \"Trace each basic block\"), 0);\n\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename...\nstatic inline string GetFileNameRoot(const string &InputFilename) {\n string IFN = InputFilename;\n string outputFilename;\n int Len = IFN.length();\n if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ Function main()\n\/\/ \n\/\/ Entry point for the llc compiler.\n\/\/===---------------------------------------------------------------------===\/\/\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n \n \/\/ Allocate a target... in the future this will be controllable on the\n \/\/ command line.\n std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());\n assert(target.get() && \"Could not allocate target machine!\");\n\n TargetMachine &Target = *target.get();\n \n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n cerr << \"bytecode didn't read correctly.\\n\";\n return 1;\n }\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n\n if (TraceValues != TraceOff) { \/\/ If tracing enabled...\n \/\/ Insert trace code in all functions in the module\n if (TraceValues == TraceBasicBlocks)\n Passes.add(createTraceValuesPassForBasicBlocks());\n else if (TraceValues == TraceFunctions)\n Passes.add(createTraceValuesPassForFunction());\n else\n assert(0 && \"Bad value for TraceValues!\");\n\n \/\/ Eliminate duplication in constant pool\n Passes.add(createDynamicConstantMergePass());\n }\n \n \/\/ Decompose multi-dimensional refs into a sequence of 1D refs\n Passes.add(createDecomposeMultiDimRefsPass());\n \n \/\/ Write out the module with tracing code just before code generation\n if (TraceValues != TraceOff) { \/\/ If tracing enabled...\n assert(InputFilename != \"-\" &&\n \"files on stdin not supported with tracing\");\n string traceFileName = GetFileNameRoot(InputFilename) + \".trace.bc\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n \n std::ostream *os = new std::ofstream(traceFileName.c_str());\n if (!os->good()) {\n cerr << \"Error opening \" << traceFileName\n << \"! SKIPPING OUTPUT OF TRACE CODE\\n\";\n delete os;\n return 1;\n }\n \n Passes.add(new WriteBytecodePass(os, true));\n }\n \n \/\/ Replace malloc and free instructions with library calls.\n \/\/ Do this after tracing until lli implements these lib calls.\n \/\/ For now, it will emulate malloc and free internally.\n Passes.add(createLowerAllocationsPass(Target.DataLayout));\n \n \/\/ If LLVM dumping after transformations is requested, add it to the pipeline\n if (DumpAsm)\n Passes.add(new PrintFunctionPass(\"Code after xformations: \\n\", &cerr));\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") { \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n string OutputFilename = GetFileNameRoot(InputFilename); \n OutputFilename += \".s\";\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n cerr << \"Error opening '\" << OutputFilename << \"': File exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n cerr << \"Error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ SIGINT\n RemoveFileOnSignal(OutputFilename);\n }\n }\n \n Target.addPassesToEmitAssembly(Passes, *Out);\n \n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(M.get());\n\n if (Out != &std::cout) delete Out;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and\/or associated documentation files (the\n\/\/ \"Materials\"), to deal in the Materials without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Materials, and to\n\/\/ permit persons to whom the Materials are furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Materials.\n\/\/\n\/\/ MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS\n\/\/ KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS\n\/\/ SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT\n\/\/ https:\/\/www.khronos.org\/registry\/\n\/\/\n\/\/ THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <vector>\n\n#include \"spirv-tools\/libspirv.h\"\n\nvoid print_usage(char* argv0) {\n printf(\n R\"(%s - Validate a SPIR-V binary file.\n\nUSAGE: %s [options] [<filename>]\n\nThe SPIR-V binary is read from <filename>. If no file is specified,\nor if the filename is \"-\", then the binary is read from standard input.\n\nOptions:\n -all Perform all validation (default OFF)\n -basic Perform basic validation (default OFF)\n -id Perform id validation (default OFF)\n -layout Perform layout validation (default OFF)\n -rules Perform rules validation (default OFF)\n)\",\n argv0, argv0);\n}\n\nint main(int argc, char** argv) {\n const char* inFile = nullptr;\n uint32_t options = 0;\n\n for (int argi = 1; argi < argc; ++argi) {\n const char* cur_arg = argv[argi];\n if ('-' == cur_arg[0]) {\n if (!strcmp(\"all\", cur_arg + 1)) {\n options |= SPV_VALIDATE_ALL;\n } else if (!strcmp(\"basic\", cur_arg + 1)) {\n options |= SPV_VALIDATE_BASIC_BIT;\n } else if (!strcmp(\"id\", cur_arg + 1)) {\n options |= SPV_VALIDATE_ID_BIT;\n } else if (!strcmp(\"layout\", cur_arg + 1)) {\n options |= SPV_VALIDATE_LAYOUT_BIT;\n } else if (!strcmp(\"rules\", cur_arg + 1)) {\n options |= SPV_VALIDATE_RULES_BIT;\n } else if (0 == cur_arg[1]) {\n \/\/ Setting a filename of \"-\" to indicate stdin.\n if (!inFile) {\n inFile = cur_arg;\n } else {\n fprintf(stderr, \"error: More than one input file specified\\n\");\n return 1;\n }\n\n } else {\n print_usage(argv[0]);\n return 1;\n }\n } else {\n if (!inFile) {\n inFile = cur_arg;\n } else {\n fprintf(stderr, \"error: More than one input file specified\\n\");\n return 1;\n }\n }\n }\n\n std::vector<uint32_t> contents;\n const bool use_file = inFile && strcmp(\"-\", inFile);\n if (FILE* fp = (use_file ? fopen(inFile, \"rb\") : stdin)) {\n uint32_t buf[1024];\n while (size_t len = fread(buf, sizeof(uint32_t),\n sizeof(buf) \/ sizeof(uint32_t), fp)) {\n contents.insert(contents.end(), buf, buf + len);\n }\n if (use_file) fclose(fp);\n } else {\n fprintf(stderr, \"error: file does not exist '%s'\\n\", inFile);\n return 1;\n }\n\n spv_const_binary_t binary = {contents.data(), contents.size()};\n\n spv_diagnostic diagnostic = nullptr;\n spv_context context = spvContextCreate();\n spv_result_t error = spvValidate(context, &binary, options, &diagnostic);\n spvContextDestroy(context);\n if (error) {\n spvDiagnosticPrint(diagnostic);\n spvDiagnosticDestroy(diagnostic);\n return error;\n }\n\n return 0;\n}\n<commit_msg>spirv-val help says it's a work in progress.<commit_after>\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and\/or associated documentation files (the\n\/\/ \"Materials\"), to deal in the Materials without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Materials, and to\n\/\/ permit persons to whom the Materials are furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Materials.\n\/\/\n\/\/ MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS\n\/\/ KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS\n\/\/ SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT\n\/\/ https:\/\/www.khronos.org\/registry\/\n\/\/\n\/\/ THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <vector>\n\n#include \"spirv-tools\/libspirv.h\"\n\nvoid print_usage(char* argv0) {\n printf(\n R\"(%s - Validate a SPIR-V binary file.\n\nUSAGE: %s [options] [<filename>]\n\nThe SPIR-V binary is read from <filename>. If no file is specified,\nor if the filename is \"-\", then the binary is read from standard input.\n\nNOTE: The validator is a work in progress.\n\nOptions:\n -all Perform all validation (default OFF)\n -basic Perform basic validation (default OFF)\n -id Perform id validation (default OFF)\n -layout Perform layout validation (default OFF)\n -rules Perform rules validation (default OFF)\n)\",\n argv0, argv0);\n}\n\nint main(int argc, char** argv) {\n const char* inFile = nullptr;\n uint32_t options = 0;\n\n for (int argi = 1; argi < argc; ++argi) {\n const char* cur_arg = argv[argi];\n if ('-' == cur_arg[0]) {\n if (!strcmp(\"all\", cur_arg + 1)) {\n options |= SPV_VALIDATE_ALL;\n } else if (!strcmp(\"basic\", cur_arg + 1)) {\n options |= SPV_VALIDATE_BASIC_BIT;\n } else if (!strcmp(\"id\", cur_arg + 1)) {\n options |= SPV_VALIDATE_ID_BIT;\n } else if (!strcmp(\"layout\", cur_arg + 1)) {\n options |= SPV_VALIDATE_LAYOUT_BIT;\n } else if (!strcmp(\"rules\", cur_arg + 1)) {\n options |= SPV_VALIDATE_RULES_BIT;\n } else if (0 == cur_arg[1]) {\n \/\/ Setting a filename of \"-\" to indicate stdin.\n if (!inFile) {\n inFile = cur_arg;\n } else {\n fprintf(stderr, \"error: More than one input file specified\\n\");\n return 1;\n }\n\n } else {\n print_usage(argv[0]);\n return 1;\n }\n } else {\n if (!inFile) {\n inFile = cur_arg;\n } else {\n fprintf(stderr, \"error: More than one input file specified\\n\");\n return 1;\n }\n }\n }\n\n std::vector<uint32_t> contents;\n const bool use_file = inFile && strcmp(\"-\", inFile);\n if (FILE* fp = (use_file ? fopen(inFile, \"rb\") : stdin)) {\n uint32_t buf[1024];\n while (size_t len = fread(buf, sizeof(uint32_t),\n sizeof(buf) \/ sizeof(uint32_t), fp)) {\n contents.insert(contents.end(), buf, buf + len);\n }\n if (use_file) fclose(fp);\n } else {\n fprintf(stderr, \"error: file does not exist '%s'\\n\", inFile);\n return 1;\n }\n\n spv_const_binary_t binary = {contents.data(), contents.size()};\n\n spv_diagnostic diagnostic = nullptr;\n spv_context context = spvContextCreate();\n spv_result_t error = spvValidate(context, &binary, options, &diagnostic);\n spvContextDestroy(context);\n if (error) {\n spvDiagnosticPrint(diagnostic);\n spvDiagnosticDestroy(diagnostic);\n return error;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017-2020 The Verible Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <unistd.h>\n\n#include <functional>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include \"absl\/flags\/usage.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"common\/strings\/compare.h\"\n#include \"common\/strings\/patch.h\"\n#include \"common\/util\/container_iterator_range.h\"\n#include \"common\/util\/file_util.h\"\n#include \"common\/util\/init_command_line.h\"\n\n\/\/ TODO(b\/160323522): refactor into common\/utils\/ for other subcommand-using\n\/\/ tools\nusing SubcommandArgs = std::vector<char*>;\nusing SubcommandArgsIterator = SubcommandArgs::const_iterator;\nusing SubcommandArgsRange =\n verible::container_iterator_range<SubcommandArgsIterator>;\n\nusing SubcommandFunction =\n std::function<absl::Status(const SubcommandArgsRange&, std::istream& ins,\n std::ostream& outs, std::ostream& errs)>;\n\n\/\/ Represents a function selected by the user.\nstruct SubcommandEntry {\n \/\/ sub-main function\n const SubcommandFunction main;\n\n \/\/ maybe a const std::string 'brief' for a half-line description\n\n \/\/ full description of command\n const std::string usage;\n};\n\nusing SubcommandMap =\n std::map<std::string, SubcommandEntry, verible::StringViewCompare>;\n\n\/\/ forward declarations of subcommand functions\nstatic absl::Status ChangedLines(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status ApplyPick(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status StdinTest(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status CatTest(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status Help(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\n\nstatic absl::Status Error(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n const auto unused_status = Help(args, ins, outs, errs);\n return absl::InvalidArgumentError(\"Unknown subcommand.\");\n}\n\nstatic const SubcommandMap& GetSubcommandMap() {\n static const auto* kCommands = new SubcommandMap{\n {\"help\",\n {&Help,\n \"help [command]\\n\"\n \"Prints command help. \"\n \"With no command or unknown command, this lists available \"\n \"commands.\\n\"}},\n\n \/\/ TODO(fangism): this should be a hidden command\n {\"error\",\n {&Error, \"same as 'help', but exits non-zero to signal a user-error\\n\"}},\n\n {\"changed-lines\", \/\/\n {&ChangedLines, \/\/\n R\"(changed-lines patchfile\n\nInput:\n 'patchfile' is a unified-diff file from 'diff -u' or other version-controlled\n equivalents like {p4,git,hg,cvs,svn} diff. Use '-' to read from stdin.\n\nOutput: (stdout)\n This prints output in the following format per line:\n\n filename [line-ranges]\n\n where line-ranges (optional) is suitable for tools that accept a set of lines\n to operate on, e.g. \"1-4,8,21-42\".\n line-ranges is omitted for files that are considered new in the patchfile.\n)\"}},\n\n \/\/ TODO(b\/156530527): add options like -p for path pruning\n \/\/ TODO(fangism): Support '-' as patchfile.\n {\"apply-pick\",\n {&ApplyPick,\n R\"(apply-pick patchfile\nInput:\n 'patchfile' is a unified-diff file from 'diff -u' or other version-controlled\n equivalents like {p4,git,hg,cvs,svn} diff.\n\nEffect:\n Modifies patched files in-place, following user selections on which patch\n hunks to apply.\n)\"}},\n\n \/\/ These are diagnostic tools and should be hidden from most users.\n {\"stdin-test\", \/\/\n {&StdinTest, \/\/\n R\"(Test for re-opening stdin.\n\nThis interactivel prompts the user to enter text, separating files with an EOF\n(Ctrl-D), and echoes the input text back to stdout.\n)\"}},\n {\"cat-test\", \/\/\n {&CatTest, \/\/\n R\"(Test for (UNIX) cat-like functionality.\n\nUsage: cat-test ARGS...\n\nwhere each ARG could point to a file on the filesystem or be '-' to read from stdin.\nEach '-' will prompt the user to enter text until EOF (Ctrl-D).\nEach 'file' echoed back to stdout will be enclosed in banner lines with\n<<<< and >>>>.\n)\"}},\n };\n return *kCommands;\n}\n\nabsl::Status ChangedLines(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n if (args.empty()) {\n return absl::InvalidArgumentError(\n \"Missing patchfile argument. Use '-' for stdin.\");\n }\n const auto patchfile = args[0];\n std::string patch_contents;\n {\n const auto status = verible::file::GetContents(patchfile, &patch_contents);\n if (!status.ok()) return status;\n }\n verible::PatchSet patch_set;\n {\n const auto status = patch_set.Parse(patch_contents);\n if (!status.ok()) return status;\n }\n const verible::FileLineNumbersMap changed_lines(\n patch_set.AddedLinesMap(false));\n for (const auto& file_lines : changed_lines) {\n outs << file_lines.first;\n if (!file_lines.second.empty()) {\n file_lines.second.FormatInclusive(outs << ' ', true);\n }\n outs << std::endl;\n }\n return absl::OkStatus();\n}\n\nabsl::Status ApplyPick(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n if (args.empty()) {\n return absl::InvalidArgumentError(\"Missing patchfile argument.\");\n }\n const auto patchfile = args[0];\n std::string patch_contents;\n {\n const auto status = verible::file::GetContents(patchfile, &patch_contents);\n if (!status.ok()) return status;\n }\n verible::PatchSet patch_set;\n {\n const auto status = patch_set.Parse(patch_contents);\n if (!status.ok()) return status;\n }\n return patch_set.PickApplyInPlace(ins, outs);\n}\n\nabsl::Status StdinTest(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n constexpr size_t kOpenLimit = 10;\n outs << \"This is a demo of re-opening std::cin, up to \" << kOpenLimit\n << \" times.\\n\"\n \"Enter text when prompted.\\n\"\n \"Ctrl-D sends an EOF to start the next file.\\n\"\n \"Ctrl-C terminates the loop and exits the program.\"\n << std::endl;\n size_t file_count = 0;\n std::string line;\n for (; file_count < kOpenLimit; ++file_count) {\n outs << \"==== file \" << file_count << \" ====\" << std::endl;\n while (ins) {\n if (isatty(0)) outs << \"enter text: \";\n std::getline(ins, line);\n outs << \"echo: \" << line << std::endl;\n }\n if (ins.eof()) {\n outs << \"EOF reached. Re-opening for next file\" << std::endl;\n ins.clear(); \/\/ allows std::cin to read the next file\n }\n }\n return absl::OkStatus();\n}\n\nabsl::Status CatTest(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n size_t file_count = 0;\n for (const auto& arg : args) {\n std::string contents;\n const auto status = verible::file::GetContents(arg, &contents);\n if (!status.ok()) return status;\n outs << \"<<<< contents of file[\" << file_count << \"] (\" << arg << \") <<<<\"\n << std::endl;\n outs << contents;\n outs << \">>>> end of file[\" << file_count << \"] (\" << arg << \") >>>>\"\n << std::endl;\n ++file_count;\n }\n return absl::OkStatus();\n}\n\nstatic std::string ListCommands() {\n static const SubcommandMap& commands(GetSubcommandMap());\n return absl::StrCat(\" \",\n absl::StrJoin(commands, \"\\n \",\n [](std::string* out,\n const SubcommandMap::value_type& entry) {\n *out += entry.first; \/\/ command name\n }),\n \"\\n\");\n}\n\nstatic const SubcommandEntry& GetSubcommandEntry(absl::string_view command) {\n static const SubcommandMap& commands(GetSubcommandMap());\n#if __cplusplus >= 201402L\n const auto iter = commands.find(command); \/\/ heterogenous lookup\n#else\n \/\/ without hetergenous lookup\n const auto iter = commands.find(std::string(command));\n#endif\n if (iter == commands.end()) {\n \/\/ Command not found, print help and exit non-zero.\n return commands.find(\"error\")->second;\n }\n return iter->second;\n}\n\nabsl::Status Help(const SubcommandArgsRange& args, std::istream&, std::ostream&,\n std::ostream& errs) {\n if (args.empty()) {\n errs << \"available commands:\\n\" << ListCommands() << std::endl;\n return absl::OkStatus();\n }\n\n const SubcommandEntry& entry = GetSubcommandEntry(args.front());\n errs << entry.usage << std::endl;\n return absl::OkStatus();\n}\n\nint main(int argc, char* argv[]) {\n const std::string usage = absl::StrCat(\"usage: \", argv[0],\n \" command args...\\n\"\n \"available commands:\\n\",\n ListCommands());\n\n const auto args = verible::InitCommandLine(usage, &argc, &argv);\n if (args.size() == 1) {\n std::cerr << absl::ProgramUsageMessage() << std::endl;\n return 1;\n }\n \/\/ args[0] is the program name\n \/\/ args[1] is the subcommand\n \/\/ subcommand args start at [2]\n const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend());\n\n const auto& sub = GetSubcommandEntry(args[1]);\n \/\/ Run the subcommand.\n const auto status = sub.main(command_args, std::cin, std::cout, std::cerr);\n if (!status.ok()) {\n std::cerr << status.message() << std::endl;\n return 1;\n }\n return 0;\n}\n<commit_msg>patch_tool: Suppress hidden commands from help.<commit_after>\/\/ Copyright 2017-2020 The Verible Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <unistd.h>\n\n#include <functional>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include \"absl\/flags\/usage.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_join.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"common\/strings\/compare.h\"\n#include \"common\/strings\/patch.h\"\n#include \"common\/util\/container_iterator_range.h\"\n#include \"common\/util\/file_util.h\"\n#include \"common\/util\/init_command_line.h\"\n\n\/\/ TODO(b\/160323522): refactor into common\/utils\/ for other subcommand-using\n\/\/ tools\nusing SubcommandArgs = std::vector<char*>;\nusing SubcommandArgsIterator = SubcommandArgs::const_iterator;\nusing SubcommandArgsRange =\n verible::container_iterator_range<SubcommandArgsIterator>;\n\nusing SubcommandFunction =\n std::function<absl::Status(const SubcommandArgsRange&, std::istream& ins,\n std::ostream& outs, std::ostream& errs)>;\n\n\/\/ Represents a function selected by the user.\nstruct SubcommandEntry {\n \/\/ sub-main function\n const SubcommandFunction main;\n\n \/\/ maybe a const std::string 'brief' for a half-line description\n\n \/\/ full description of command\n const std::string usage;\n\n \/\/ If true, display this subcommand in 'help'.\n const bool show_in_help = true;\n};\n\nusing SubcommandMap =\n std::map<std::string, SubcommandEntry, verible::StringViewCompare>;\n\n\/\/ forward declarations of subcommand functions\nstatic absl::Status ChangedLines(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status ApplyPick(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status StdinTest(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status CatTest(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\nstatic absl::Status Help(const SubcommandArgsRange&, std::istream&,\n std::ostream&, std::ostream&);\n\nstatic absl::Status Error(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n const auto unused_status = Help(args, ins, outs, errs);\n return absl::InvalidArgumentError(\"Unknown subcommand.\");\n}\n\nstatic const SubcommandMap& GetSubcommandMap() {\n static const auto* kCommands = new SubcommandMap{\n {\"help\",\n {&Help,\n \"help [command]\\n\"\n \"Prints command help. \"\n \"With no command or unknown command, this lists available \"\n \"commands.\\n\"}},\n\n {\"error\",\n {&Error, \"same as 'help', but exits non-zero to signal a user-error\\n\",\n false}},\n\n {\"changed-lines\", \/\/\n {&ChangedLines, \/\/\n R\"(changed-lines patchfile\n\nInput:\n 'patchfile' is a unified-diff file from 'diff -u' or other version-controlled\n equivalents like {p4,git,hg,cvs,svn} diff. Use '-' to read from stdin.\n\nOutput: (stdout)\n This prints output in the following format per line:\n\n filename [line-ranges]\n\n where line-ranges (optional) is suitable for tools that accept a set of lines\n to operate on, e.g. \"1-4,8,21-42\".\n line-ranges is omitted for files that are considered new in the patchfile.\n)\"}},\n\n \/\/ TODO(b\/156530527): add options like -p for path pruning\n \/\/ TODO(fangism): Support '-' as patchfile.\n {\"apply-pick\",\n {&ApplyPick,\n R\"(apply-pick patchfile\nInput:\n 'patchfile' is a unified-diff file from 'diff -u' or other version-controlled\n equivalents like {p4,git,hg,cvs,svn} diff.\n\nEffect:\n Modifies patched files in-place, following user selections on which patch\n hunks to apply.\n)\"}},\n\n {\"stdin-test\", \/\/\n {&StdinTest, \/\/\n R\"(Test for re-opening stdin.\n\nThis interactivel prompts the user to enter text, separating files with an EOF\n(Ctrl-D), and echoes the input text back to stdout.\n)\",\n false}},\n {\"cat-test\", \/\/\n {&CatTest, \/\/\n R\"(Test for (UNIX) cat-like functionality.\n\nUsage: cat-test ARGS...\n\nwhere each ARG could point to a file on the filesystem or be '-' to read from stdin.\nEach '-' will prompt the user to enter text until EOF (Ctrl-D).\nEach 'file' echoed back to stdout will be enclosed in banner lines with\n<<<< and >>>>.\n)\",\n false}},\n };\n return *kCommands;\n}\n\nabsl::Status ChangedLines(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n if (args.empty()) {\n return absl::InvalidArgumentError(\n \"Missing patchfile argument. Use '-' for stdin.\");\n }\n const auto patchfile = args[0];\n std::string patch_contents;\n {\n const auto status = verible::file::GetContents(patchfile, &patch_contents);\n if (!status.ok()) return status;\n }\n verible::PatchSet patch_set;\n {\n const auto status = patch_set.Parse(patch_contents);\n if (!status.ok()) return status;\n }\n const verible::FileLineNumbersMap changed_lines(\n patch_set.AddedLinesMap(false));\n for (const auto& file_lines : changed_lines) {\n outs << file_lines.first;\n if (!file_lines.second.empty()) {\n file_lines.second.FormatInclusive(outs << ' ', true);\n }\n outs << std::endl;\n }\n return absl::OkStatus();\n}\n\nabsl::Status ApplyPick(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n if (args.empty()) {\n return absl::InvalidArgumentError(\"Missing patchfile argument.\");\n }\n const auto patchfile = args[0];\n std::string patch_contents;\n {\n const auto status = verible::file::GetContents(patchfile, &patch_contents);\n if (!status.ok()) return status;\n }\n verible::PatchSet patch_set;\n {\n const auto status = patch_set.Parse(patch_contents);\n if (!status.ok()) return status;\n }\n return patch_set.PickApplyInPlace(ins, outs);\n}\n\nabsl::Status StdinTest(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n constexpr size_t kOpenLimit = 10;\n outs << \"This is a demo of re-opening std::cin, up to \" << kOpenLimit\n << \" times.\\n\"\n \"Enter text when prompted.\\n\"\n \"Ctrl-D sends an EOF to start the next file.\\n\"\n \"Ctrl-C terminates the loop and exits the program.\"\n << std::endl;\n size_t file_count = 0;\n std::string line;\n for (; file_count < kOpenLimit; ++file_count) {\n outs << \"==== file \" << file_count << \" ====\" << std::endl;\n while (ins) {\n if (isatty(0)) outs << \"enter text: \";\n std::getline(ins, line);\n outs << \"echo: \" << line << std::endl;\n }\n if (ins.eof()) {\n outs << \"EOF reached. Re-opening for next file\" << std::endl;\n ins.clear(); \/\/ allows std::cin to read the next file\n }\n }\n return absl::OkStatus();\n}\n\nabsl::Status CatTest(const SubcommandArgsRange& args, std::istream& ins,\n std::ostream& outs, std::ostream& errs) {\n size_t file_count = 0;\n for (const auto& arg : args) {\n std::string contents;\n const auto status = verible::file::GetContents(arg, &contents);\n if (!status.ok()) return status;\n outs << \"<<<< contents of file[\" << file_count << \"] (\" << arg << \") <<<<\"\n << std::endl;\n outs << contents;\n outs << \">>>> end of file[\" << file_count << \"] (\" << arg << \") >>>>\"\n << std::endl;\n ++file_count;\n }\n return absl::OkStatus();\n}\n\nstatic std::string ListCommands() {\n static const SubcommandMap& commands(GetSubcommandMap());\n std::vector<absl::string_view> public_commands;\n for (const auto& command : commands) {\n \/\/ List only public commands.\n if (command.second.show_in_help) {\n public_commands.emplace_back(command.first);\n }\n }\n return absl::StrCat(\" \", absl::StrJoin(public_commands, \"\\n \"), \"\\n\");\n}\n\nstatic const SubcommandEntry& GetSubcommandEntry(absl::string_view command) {\n static const SubcommandMap& commands(GetSubcommandMap());\n#if __cplusplus >= 201402L\n const auto iter = commands.find(command); \/\/ heterogenous lookup\n#else\n \/\/ without hetergenous lookup\n const auto iter = commands.find(std::string(command));\n#endif\n if (iter == commands.end()) {\n \/\/ Command not found, print help and exit non-zero.\n return commands.find(\"error\")->second;\n }\n return iter->second;\n}\n\nabsl::Status Help(const SubcommandArgsRange& args, std::istream&, std::ostream&,\n std::ostream& errs) {\n if (args.empty()) {\n errs << \"available commands:\\n\" << ListCommands() << std::endl;\n return absl::OkStatus();\n }\n\n const SubcommandEntry& entry = GetSubcommandEntry(args.front());\n errs << entry.usage << std::endl;\n return absl::OkStatus();\n}\n\nint main(int argc, char* argv[]) {\n const std::string usage = absl::StrCat(\"usage: \", argv[0],\n \" command args...\\n\"\n \"available commands:\\n\",\n ListCommands());\n\n const auto args = verible::InitCommandLine(usage, &argc, &argv);\n if (args.size() == 1) {\n std::cerr << absl::ProgramUsageMessage() << std::endl;\n return 1;\n }\n \/\/ args[0] is the program name\n \/\/ args[1] is the subcommand\n \/\/ subcommand args start at [2]\n const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend());\n\n const auto& sub = GetSubcommandEntry(args[1]);\n \/\/ Run the subcommand.\n const auto status = sub.main(command_args, std::cin, std::cout, std::cerr);\n if (!status.ok()) {\n std::cerr << status.message() << std::endl;\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <pthread.h>\n#include \"simulator.h\"\n#include \"thread_manager.h\"\n#include \"tile_manager.h\"\n#include \"tile.h\"\n#include \"core_model.h\"\n#include \"clock_converter.h\"\n#include \"config_file.hpp\"\n#include \"handle_args.h\"\n#include \"fxsupport.h\"\n#include \"carbon_user.h\"\n#include \"thread_support_private.h\"\n\nstatic config::ConfigFile cfg;\n\ntile_id_t CarbonGetTileId()\n{\n return Sim()->getTileManager()->getCurrentTileID();\n}\n\nint CarbonStartSim(int argc, char **argv)\n{\n string_vec args;\n\n \/\/ Set the default config path if it isn't \n \/\/ overwritten on the command line.\n std::string config_path = \"carbon_sim.cfg\";\n\n \/\/ Parse the arguments that are relative\n \/\/ to the config file changes as well\n \/\/ as extracting the config_path\n parse_args(args, config_path, argc, argv);\n\n cfg.load(config_path);\n handle_args(args, cfg);\n\n Simulator::setConfig(&cfg);\n\n Simulator::allocate();\n Sim()->start();\n\n if (Config::getSingleton()->getCurrentProcessNum() == 0)\n {\n \/\/ Main process\n Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));\n \n CarbonSpawnThreadSpawner();\n\n LOG_PRINT(\"Returning to main()...\");\n return 0;\n }\n else\n {\n LOG_PRINT(\"Replacing main()...\");\n\n CarbonThreadSpawner (NULL);\n\n \/\/ Not main process\n while (!Sim()->finished())\n usleep(100);\n\n CarbonStopSim();\n\n \/\/ Otherwise we will run main ...\n exit(0);\n }\n}\n\nvoid CarbonStopSim()\n{\n Simulator::release();\n}\n\nUInt64 CarbonGetTime()\n{\n \/\/ Floating Point Save\/Restore\n FloatingPointHandler floating_point_handler;\n\n Core* core = Sim()->getTileManager()->getCurrentCore();\n UInt64 time = convertCycleCount(core->getModel()->getCycleCount(), core->getTile()->getFrequency(), 1.0);\n\n return time;\n}\n<commit_msg>[absolute time] - changed CargonGetTime() to absolute time.<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <pthread.h>\n#include \"simulator.h\"\n#include \"thread_manager.h\"\n#include \"tile_manager.h\"\n#include \"tile.h\"\n#include \"core_model.h\"\n#include \"clock_converter.h\"\n#include \"config_file.hpp\"\n#include \"handle_args.h\"\n#include \"fxsupport.h\"\n#include \"carbon_user.h\"\n#include \"thread_support_private.h\"\n\nstatic config::ConfigFile cfg;\n\ntile_id_t CarbonGetTileId()\n{\n return Sim()->getTileManager()->getCurrentTileID();\n}\n\nint CarbonStartSim(int argc, char **argv)\n{\n string_vec args;\n\n \/\/ Set the default config path if it isn't \n \/\/ overwritten on the command line.\n std::string config_path = \"carbon_sim.cfg\";\n\n \/\/ Parse the arguments that are relative\n \/\/ to the config file changes as well\n \/\/ as extracting the config_path\n parse_args(args, config_path, argc, argv);\n\n cfg.load(config_path);\n handle_args(args, cfg);\n\n Simulator::setConfig(&cfg);\n\n Simulator::allocate();\n Sim()->start();\n\n if (Config::getSingleton()->getCurrentProcessNum() == 0)\n {\n \/\/ Main process\n Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));\n \n CarbonSpawnThreadSpawner();\n\n LOG_PRINT(\"Returning to main()...\");\n return 0;\n }\n else\n {\n LOG_PRINT(\"Replacing main()...\");\n\n CarbonThreadSpawner (NULL);\n\n \/\/ Not main process\n while (!Sim()->finished())\n usleep(100);\n\n CarbonStopSim();\n\n \/\/ Otherwise we will run main ...\n exit(0);\n }\n}\n\nvoid CarbonStopSim()\n{\n Simulator::release();\n}\n\nUInt64 CarbonGetTime()\n{\n \/\/ Floating Point Save\/Restore\n FloatingPointHandler floating_point_handler;\n\n Core* core = Sim()->getTileManager()->getCurrentCore();\n UInt64 time = core->getModel()->getCurrTime().toNanosec();\n\n return time;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"hal.h\"\n#include \"markAncestors.h\"\n\nusing namespace std;\nusing namespace hal;\n\nstatic void initParser(CLParser &optionsParser) {\n optionsParser.addArgument(\"inFile\", \"existing tree\");\n optionsParser.addArgument(\"botAlignmentFile\", \"tree containing insert, its \"\n \"proper bottom segments, and the new leaf genome\");\n optionsParser.addArgument(\"topAlignmentFile\", \"tree containing insert, its \"\n \"parent, and its proper top segments\");\n optionsParser.addArgument(\"parentName\", \"insert's future parent\");\n optionsParser.addArgument(\"insertName\", \"insert name\");\n optionsParser.addArgument(\"childName\", \"insert's future child\");\n optionsParser.addArgument(\"leafName\", \"name of new leaf genome\");\n optionsParser.addArgument(\"upperBranchLength\", \"length of branch from parent\"\n \" to insert\");\n optionsParser.addArgument(\"leafBranchLength\", \"leaf branch length\");\n optionsParser.addOptionFlag(\"noMarkAncestors\", \"don't mark ancestors for\"\n \" update\",\n false);\n}\n\nint main(int argc, char *argv[]) {\n CLParser optionsParser(WRITE_ACCESS);\n initParser(optionsParser);\n string inPath, botAlignmentPath, topAlignmentPath, parentName, insertName, childName, leafName;\n double upperBranchLength, leafBranchLength;\n bool noMarkAncestors;\n try {\n optionsParser.parseOptions(argc, argv);\n inPath = optionsParser.getArgument<string>(\"inFile\");\n botAlignmentPath = optionsParser.getArgument<string>(\"botAlignmentFile\");\n topAlignmentPath = optionsParser.getArgument<string>(\"topAlignmentFile\");\n parentName = optionsParser.getArgument<string>(\"parentName\");\n insertName = optionsParser.getArgument<string>(\"insertName\");\n childName = optionsParser.getArgument<string>(\"childName\");\n leafName = optionsParser.getArgument<string>(\"leafName\");\n upperBranchLength = optionsParser.getArgument<double>(\"upperBranchLength\");\n leafBranchLength = optionsParser.getArgument<double>(\"leafBranchLength\");\n noMarkAncestors = optionsParser.getFlag(\"noMarkAncestors\");\n } catch (exception &e) {\n optionsParser.printUsage(cerr);\n return 1;\n }\n AlignmentPtr mainAlignment(openHalAlignment(inPath, &optionsParser, READ_ACCESS | WRITE_ACCESS));\n AlignmentConstPtr botAlignment(openHalAlignment(botAlignmentPath, &optionsParser));\n AlignmentConstPtr topAlignment(openHalAlignment(topAlignmentPath, &optionsParser));\n mainAlignment->insertGenome(insertName, parentName, childName, upperBranchLength);\n mainAlignment->addLeafGenome(leafName, insertName, leafBranchLength);\n \/\/ Insert the new intermediate node.\n Genome *insertGenome = mainAlignment->openGenome(insertName);\n const Genome *topInsertGenome = topAlignment->openGenome(insertName);\n const Genome *botInsertGenome = botAlignment->openGenome(insertName);\n topInsertGenome->copyDimensions(insertGenome);\n topInsertGenome->copyTopDimensions(insertGenome);\n botInsertGenome->copyBottomDimensions(insertGenome);\n topInsertGenome->copySequence(insertGenome);\n topInsertGenome->copyTopSegments(insertGenome);\n topInsertGenome->copyMetadata(insertGenome);\n botInsertGenome->copyBottomSegments(insertGenome);\n insertGenome->fixParseInfo();\n\n \/\/ Copy the bottom segments for the parent genome from the top alignment.\n Genome *parentGenome = mainAlignment->openGenome(parentName);\n const Genome *botParentGenome = topAlignment->openGenome(parentName);\n botParentGenome->copyBottomDimensions(parentGenome);\n botParentGenome->copyBottomSegments(parentGenome);\n parentGenome->fixParseInfo();\n\n \/\/ Fix the parent's other children as well.\n vector<string> allChildren = mainAlignment->getChildNames(parentName);\n for (size_t i = 0; i < allChildren.size(); i++) {\n if (allChildren[i] != insertName) {\n Genome *outGenome = mainAlignment->openGenome(allChildren[i]);\n const Genome *topSegmentsGenome = topAlignment->openGenome(allChildren[i]);\n topSegmentsGenome->copyTopDimensions(outGenome);\n topSegmentsGenome->copyTopSegments(outGenome);\n outGenome->fixParseInfo();\n }\n }\n\n \/\/ Copy the top segments for the child genome from the bottom alignment.\n Genome *childGenome = mainAlignment->openGenome(childName);\n const Genome *topChildGenome = botAlignment->openGenome(childName);\n topChildGenome->copyTopDimensions(childGenome);\n topChildGenome->copyTopSegments(childGenome);\n childGenome->fixParseInfo();\n\n \/\/ Copy the entire genome for the leaf from the bottom alignment.\n Genome *outLeafGenome = mainAlignment->openGenome(leafName);\n const Genome *inLeafGenome = botAlignment->openGenome(leafName);\n inLeafGenome->copy(outLeafGenome);\n if (!noMarkAncestors) {\n markAncestorsForUpdate(mainAlignment.get(), insertName);\n }\n}\n<commit_msg>Copy sequence dimensions in halAddToBranch<commit_after>#include \"hal.h\"\n#include \"markAncestors.h\"\n\nusing namespace std;\nusing namespace hal;\n\nstatic void initParser(CLParser &optionsParser) {\n optionsParser.addArgument(\"inFile\", \"existing tree\");\n optionsParser.addArgument(\"botAlignmentFile\", \"tree containing insert, its \"\n \"proper bottom segments, and the new leaf genome\");\n optionsParser.addArgument(\"topAlignmentFile\", \"tree containing insert, its \"\n \"parent, and its proper top segments\");\n optionsParser.addArgument(\"parentName\", \"insert's future parent\");\n optionsParser.addArgument(\"insertName\", \"insert name\");\n optionsParser.addArgument(\"childName\", \"insert's future child\");\n optionsParser.addArgument(\"leafName\", \"name of new leaf genome\");\n optionsParser.addArgument(\"upperBranchLength\", \"length of branch from parent\"\n \" to insert\");\n optionsParser.addArgument(\"leafBranchLength\", \"leaf branch length\");\n optionsParser.addOptionFlag(\"noMarkAncestors\", \"don't mark ancestors for\"\n \" update\",\n false);\n}\n\nint main(int argc, char *argv[]) {\n CLParser optionsParser(WRITE_ACCESS);\n initParser(optionsParser);\n string inPath, botAlignmentPath, topAlignmentPath, parentName, insertName, childName, leafName;\n double upperBranchLength, leafBranchLength;\n bool noMarkAncestors;\n try {\n optionsParser.parseOptions(argc, argv);\n inPath = optionsParser.getArgument<string>(\"inFile\");\n botAlignmentPath = optionsParser.getArgument<string>(\"botAlignmentFile\");\n topAlignmentPath = optionsParser.getArgument<string>(\"topAlignmentFile\");\n parentName = optionsParser.getArgument<string>(\"parentName\");\n insertName = optionsParser.getArgument<string>(\"insertName\");\n childName = optionsParser.getArgument<string>(\"childName\");\n leafName = optionsParser.getArgument<string>(\"leafName\");\n upperBranchLength = optionsParser.getArgument<double>(\"upperBranchLength\");\n leafBranchLength = optionsParser.getArgument<double>(\"leafBranchLength\");\n noMarkAncestors = optionsParser.getFlag(\"noMarkAncestors\");\n } catch (exception &e) {\n optionsParser.printUsage(cerr);\n return 1;\n }\n AlignmentPtr mainAlignment(openHalAlignment(inPath, &optionsParser, READ_ACCESS | WRITE_ACCESS));\n AlignmentConstPtr botAlignment(openHalAlignment(botAlignmentPath, &optionsParser));\n AlignmentConstPtr topAlignment(openHalAlignment(topAlignmentPath, &optionsParser));\n\n \/\/ Add in the insert genome.\n mainAlignment->insertGenome(insertName, parentName, childName, upperBranchLength);\n\n \/\/ Add in the new leaf genome and its dimensions (so that it has the proper number of sequences).\n mainAlignment->addLeafGenome(leafName, insertName, leafBranchLength);\n Genome *outLeafGenome = mainAlignment->openGenome(leafName);\n const Genome *inLeafGenome = botAlignment->openGenome(leafName);\n inLeafGenome->copyDimensions(outLeafGenome);\n\n \/\/ Insert the new intermediate node.\n Genome *insertGenome = mainAlignment->openGenome(insertName);\n const Genome *topInsertGenome = topAlignment->openGenome(insertName);\n const Genome *botInsertGenome = botAlignment->openGenome(insertName);\n topInsertGenome->copyDimensions(insertGenome);\n topInsertGenome->copyTopDimensions(insertGenome);\n botInsertGenome->copyBottomDimensions(insertGenome);\n topInsertGenome->copySequence(insertGenome);\n topInsertGenome->copyTopSegments(insertGenome);\n topInsertGenome->copyMetadata(insertGenome);\n botInsertGenome->copyBottomSegments(insertGenome);\n insertGenome->fixParseInfo();\n\n \/\/ Copy the bottom segments for the parent genome from the top alignment.\n Genome *parentGenome = mainAlignment->openGenome(parentName);\n const Genome *botParentGenome = topAlignment->openGenome(parentName);\n botParentGenome->copyBottomDimensions(parentGenome);\n botParentGenome->copyBottomSegments(parentGenome);\n parentGenome->fixParseInfo();\n\n \/\/ Fix the parent's other children as well.\n vector<string> allChildren = mainAlignment->getChildNames(parentName);\n for (size_t i = 0; i < allChildren.size(); i++) {\n if (allChildren[i] != insertName) {\n Genome *outGenome = mainAlignment->openGenome(allChildren[i]);\n const Genome *topSegmentsGenome = topAlignment->openGenome(allChildren[i]);\n topSegmentsGenome->copyTopDimensions(outGenome);\n topSegmentsGenome->copyTopSegments(outGenome);\n outGenome->fixParseInfo();\n }\n }\n\n \/\/ Copy the top segments for the child genome from the bottom alignment.\n Genome *childGenome = mainAlignment->openGenome(childName);\n const Genome *topChildGenome = botAlignment->openGenome(childName);\n topChildGenome->copyTopDimensions(childGenome);\n topChildGenome->copyTopSegments(childGenome);\n childGenome->fixParseInfo();\n\n \/\/ Copy the entire genome for the leaf from the bottom alignment.\n inLeafGenome->copy(outLeafGenome);\n if (!noMarkAncestors) {\n markAncestorsForUpdate(mainAlignment.get(), insertName);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n Copyright (C) 2010 Red Hat, Inc.\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef WIN32\n#include \"config.h\"\n#endif\n\n#include \"common.h\"\n#include \"debug.h\"\n#include \"utils.h\"\n#include \"mjpeg_decoder.h\"\n\nenum {\n STATE_READ_HEADER,\n STATE_START_DECOMPRESS,\n STATE_READ_SCANLINES,\n STATE_FINISH_DECOMPRESS\n};\n\nextern \"C\" {\n\n static void init_source(j_decompress_ptr cinfo)\n {\n }\n\n static boolean fill_input_buffer(j_decompress_ptr cinfo)\n {\n return FALSE;\n }\n\n void mjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)\n {\n MJpegDecoder *decoder = (MJpegDecoder *)cinfo;\n if (num_bytes > 0) {\n if (cinfo->src->bytes_in_buffer >= (size_t)num_bytes) {\n cinfo->src->next_input_byte += (size_t) num_bytes;\n cinfo->src->bytes_in_buffer -= (size_t) num_bytes;\n } else {\n decoder->_extra_skip = num_bytes - cinfo->src->bytes_in_buffer;\n cinfo->src->bytes_in_buffer = 0;\n }\n }\n }\n\n static void term_source (j_decompress_ptr cinfo)\n {\n return;\n }\n}\n\nMJpegDecoder::MJpegDecoder(int width, int height,\n int stride,\n uint8_t *frame) :\n _data(NULL)\n , _data_size(0)\n , _data_start(0)\n , _data_end(0)\n , _extra_skip(0)\n , _width(width)\n , _height(height)\n , _stride(stride)\n , _frame(frame)\n , _y(0)\n , _state(0)\n{\n memset(&_cinfo, 0, sizeof(_cinfo));\n _cinfo.err = jpeg_std_error (&_jerr);\n jpeg_create_decompress (&_cinfo);\n\n _cinfo.src = &_jsrc;\n _cinfo.src->init_source = init_source;\n _cinfo.src->fill_input_buffer = fill_input_buffer;\n _cinfo.src->skip_input_data = mjpeg_skip_input_data;\n _cinfo.src->resync_to_restart = jpeg_resync_to_restart;\n _cinfo.src->term_source = term_source;\n\n _scanline = new uint8_t[width * 3];\n}\n\nMJpegDecoder::~MJpegDecoder()\n{\n delete [] _scanline;\n if (_data) {\n delete [] _data;\n }\n}\n\nvoid MJpegDecoder::convert_scanline(void)\n{\n uint32_t *row;\n uint32_t c;\n uint8_t *s;\n int x;\n\n ASSERT(_width % 2 == 0);\n ASSERT(_height % 2 == 0);\n\n row = (uint32_t *)(_frame + _y * _stride);\n s = _scanline;\n for (x = 0; x < _width; x++) {\n \/* This switches the order of red and blue.\n This is not accidental, but for backwards\n compatibility, since a bug in the old\n ffmpeg-using mjpeg code got these switched\n due to endianness issues. *\/\n c = s[0] | s[1] << 8 | s[2] << 16;\n s += 3;\n *row++ = c;\n }\n}\n\nbool MJpegDecoder::decode_data(uint8_t *data, size_t length)\n{\n uint8_t *new_data;\n size_t data_len;\n int res;\n bool got_picture;\n\n got_picture = false;\n\n if (_extra_skip > 0) {\n if (_extra_skip >= length) {\n _extra_skip -= length;\n return false;\n } else {\n data += _extra_skip;\n length -= _extra_skip;\n _extra_skip = 0;\n }\n }\n\n if (_data_size - _data_end < length) {\n \/* Can't fit in tail *\/\n\n data_len = _data_end - _data_start;\n if (_data_size - data_len < length) {\n \/* Can't fit at all, grow a bit *\/\n _data_size = _data_size + length * 2;\n new_data = new uint8_t[_data_size];\n memcpy (new_data, _data + _data_start, data_len);\n delete [] _data;\n _data = new_data;\n } else {\n \/* Just needs to compact *\/\n memmove (_data, _data + _data_start, data_len);\n }\n _data_start = 0;\n _data_end = data_len;\n }\n\n memcpy (_data + _data_end, data, length);\n _data_end += length;\n\n _jsrc.next_input_byte = _data + _data_start;\n _jsrc.bytes_in_buffer = _data_end - _data_start;\n\n switch (_state) {\n case STATE_READ_HEADER:\n res = jpeg_read_header(&_cinfo, TRUE);\n if (res == JPEG_SUSPENDED) {\n break;\n }\n\n _cinfo.do_fancy_upsampling = FALSE;\n _cinfo.do_block_smoothing = FALSE;\n _cinfo.out_color_space = JCS_RGB;\n\n PANIC_ON(_cinfo.image_width != _width);\n PANIC_ON(_cinfo.image_height != _height);\n\n _state = STATE_START_DECOMPRESS;\n\n \/* fall through *\/\n case STATE_START_DECOMPRESS:\n res = jpeg_start_decompress (&_cinfo);\n\n if (!res) {\n break;\n }\n\n _state = STATE_READ_SCANLINES;\n\n \/* fall through *\/\n case STATE_READ_SCANLINES:\n res = 0;\n while (_y < _height) {\n res = jpeg_read_scanlines(&_cinfo, &_scanline, 1);\n\n if (res == 0) {\n break;\n }\n\n convert_scanline();\n _y++;\n }\n if (res == 0) {\n break;\n }\n\n _state = STATE_FINISH_DECOMPRESS;\n\n \/* fall through *\/\n case STATE_FINISH_DECOMPRESS:\n res = jpeg_finish_decompress (&_cinfo);\n\n if (!res) {\n break;\n }\n\n _y = 0;\n _state = STATE_READ_HEADER;\n got_picture = true;\n\n break;\n }\n\n _data_start = _jsrc.next_input_byte - _data;\n _data_end = _data_start + _jsrc.bytes_in_buffer;\n\n return got_picture;\n}\n<commit_msg>Free the jpeg decoder with the stream<commit_after>\/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n Copyright (C) 2010 Red Hat, Inc.\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#ifndef WIN32\n#include \"config.h\"\n#endif\n\n#include \"common.h\"\n#include \"debug.h\"\n#include \"utils.h\"\n#include \"mjpeg_decoder.h\"\n\nenum {\n STATE_READ_HEADER,\n STATE_START_DECOMPRESS,\n STATE_READ_SCANLINES,\n STATE_FINISH_DECOMPRESS\n};\n\nextern \"C\" {\n\n static void init_source(j_decompress_ptr cinfo)\n {\n }\n\n static boolean fill_input_buffer(j_decompress_ptr cinfo)\n {\n return FALSE;\n }\n\n void mjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)\n {\n MJpegDecoder *decoder = (MJpegDecoder *)cinfo;\n if (num_bytes > 0) {\n if (cinfo->src->bytes_in_buffer >= (size_t)num_bytes) {\n cinfo->src->next_input_byte += (size_t) num_bytes;\n cinfo->src->bytes_in_buffer -= (size_t) num_bytes;\n } else {\n decoder->_extra_skip = num_bytes - cinfo->src->bytes_in_buffer;\n cinfo->src->bytes_in_buffer = 0;\n }\n }\n }\n\n static void term_source (j_decompress_ptr cinfo)\n {\n return;\n }\n}\n\nMJpegDecoder::MJpegDecoder(int width, int height,\n int stride,\n uint8_t *frame) :\n _data(NULL)\n , _data_size(0)\n , _data_start(0)\n , _data_end(0)\n , _extra_skip(0)\n , _width(width)\n , _height(height)\n , _stride(stride)\n , _frame(frame)\n , _y(0)\n , _state(0)\n{\n memset(&_cinfo, 0, sizeof(_cinfo));\n _cinfo.err = jpeg_std_error (&_jerr);\n jpeg_create_decompress (&_cinfo);\n\n _cinfo.src = &_jsrc;\n _cinfo.src->init_source = init_source;\n _cinfo.src->fill_input_buffer = fill_input_buffer;\n _cinfo.src->skip_input_data = mjpeg_skip_input_data;\n _cinfo.src->resync_to_restart = jpeg_resync_to_restart;\n _cinfo.src->term_source = term_source;\n\n _scanline = new uint8_t[width * 3];\n}\n\nMJpegDecoder::~MJpegDecoder()\n{\n jpeg_destroy_decompress(&_cinfo);\n delete [] _scanline;\n if (_data) {\n delete [] _data;\n }\n}\n\nvoid MJpegDecoder::convert_scanline(void)\n{\n uint32_t *row;\n uint32_t c;\n uint8_t *s;\n int x;\n\n ASSERT(_width % 2 == 0);\n ASSERT(_height % 2 == 0);\n\n row = (uint32_t *)(_frame + _y * _stride);\n s = _scanline;\n for (x = 0; x < _width; x++) {\n \/* This switches the order of red and blue.\n This is not accidental, but for backwards\n compatibility, since a bug in the old\n ffmpeg-using mjpeg code got these switched\n due to endianness issues. *\/\n c = s[0] | s[1] << 8 | s[2] << 16;\n s += 3;\n *row++ = c;\n }\n}\n\nbool MJpegDecoder::decode_data(uint8_t *data, size_t length)\n{\n uint8_t *new_data;\n size_t data_len;\n int res;\n bool got_picture;\n\n got_picture = false;\n\n if (_extra_skip > 0) {\n if (_extra_skip >= length) {\n _extra_skip -= length;\n return false;\n } else {\n data += _extra_skip;\n length -= _extra_skip;\n _extra_skip = 0;\n }\n }\n\n if (_data_size - _data_end < length) {\n \/* Can't fit in tail *\/\n\n data_len = _data_end - _data_start;\n if (_data_size - data_len < length) {\n \/* Can't fit at all, grow a bit *\/\n _data_size = _data_size + length * 2;\n new_data = new uint8_t[_data_size];\n memcpy (new_data, _data + _data_start, data_len);\n delete [] _data;\n _data = new_data;\n } else {\n \/* Just needs to compact *\/\n memmove (_data, _data + _data_start, data_len);\n }\n _data_start = 0;\n _data_end = data_len;\n }\n\n memcpy (_data + _data_end, data, length);\n _data_end += length;\n\n _jsrc.next_input_byte = _data + _data_start;\n _jsrc.bytes_in_buffer = _data_end - _data_start;\n\n switch (_state) {\n case STATE_READ_HEADER:\n res = jpeg_read_header(&_cinfo, TRUE);\n if (res == JPEG_SUSPENDED) {\n break;\n }\n\n _cinfo.do_fancy_upsampling = FALSE;\n _cinfo.do_block_smoothing = FALSE;\n _cinfo.out_color_space = JCS_RGB;\n\n PANIC_ON(_cinfo.image_width != _width);\n PANIC_ON(_cinfo.image_height != _height);\n\n _state = STATE_START_DECOMPRESS;\n\n \/* fall through *\/\n case STATE_START_DECOMPRESS:\n res = jpeg_start_decompress (&_cinfo);\n\n if (!res) {\n break;\n }\n\n _state = STATE_READ_SCANLINES;\n\n \/* fall through *\/\n case STATE_READ_SCANLINES:\n res = 0;\n while (_y < _height) {\n res = jpeg_read_scanlines(&_cinfo, &_scanline, 1);\n\n if (res == 0) {\n break;\n }\n\n convert_scanline();\n _y++;\n }\n if (res == 0) {\n break;\n }\n\n _state = STATE_FINISH_DECOMPRESS;\n\n \/* fall through *\/\n case STATE_FINISH_DECOMPRESS:\n res = jpeg_finish_decompress (&_cinfo);\n\n if (!res) {\n break;\n }\n\n _y = 0;\n _state = STATE_READ_HEADER;\n got_picture = true;\n\n break;\n }\n\n _data_start = _jsrc.next_input_byte - _data;\n _data_end = _data_start + _jsrc.bytes_in_buffer;\n\n return got_picture;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"vtrc-rpc-channel.h\"\n\n#include <google\/protobuf\/service.h>\n#include <google\/protobuf\/descriptor.h>\n\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-protocol-layer.h\"\n#include \"vtrc-common\/vtrc-exception.h\"\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n\nnamespace vtrc { namespace client {\n\n namespace gpb = google::protobuf;\n\n struct rpc_channel::impl {\n\n vtrc::weak_ptr<common::connection_iface> connection_;\n\n rpc_channel *parent_;\n\n impl(vtrc::shared_ptr<common::connection_iface> c)\n :connection_(c)\n {}\n\n void CallMethod(const gpb::MethodDescriptor* method,\n gpb::RpcController* controller,\n const gpb::Message* request,\n gpb::Message* response,\n gpb::Closure* done)\n {\n common::closure_holder hold(done);\n\n common::connection_iface_sptr cl(connection_.lock( ));\n\n if( cl.get( ) == NULL ) {\n throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,\n \"Connection is lost\");\n }\n\n vtrc_rpc_lowlevel::options call_opt\n ( cl->get_protocol( ).get_method_options(method) );\n\n std::string service_name(method->service( )->full_name( ));\n std::string method_name(method->name( ));\n\n vtrc::shared_ptr<\n vtrc_rpc_lowlevel::lowlevel_unit\n > llu(new vtrc_rpc_lowlevel::lowlevel_unit);\n\n llu->mutable_call( )->set_service( service_name );\n llu->mutable_call( )->set_method( method_name );\n\n llu->set_request( request->SerializeAsString( ) );\n llu->set_response( response->SerializeAsString( ) );\n\n llu->mutable_info( )->set_message_type(\n vtrc_rpc_lowlevel::message_info::MESSAGE_CALL );\n\n uint64_t call_id = cl->get_protocol( ).next_index( );\n\n llu->set_id( call_id );\n\n if( call_opt.wait( ) ) { \/\/ WAITABLE CALL\n\n cl->get_protocol( ).call_rpc_method( call_id, *llu );\n\n std::deque< vtrc::shared_ptr <\n vtrc_rpc_lowlevel::lowlevel_unit\n >\n > data_list;\n\n cl->get_protocol( ).wait_call_slot( call_id, data_list,\n call_opt.call_timeout( ) );\n\n vtrc::shared_ptr<vtrc_rpc_lowlevel::lowlevel_unit> top\n ( data_list.front( ) );\n\n if( top->error( ).code( ) != vtrc_errors::ERR_NO_ERROR )\n throw vtrc::common::exception( top->error( ).code( ),\n top->error( ).category( ),\n top->error( ).additional( ) );\n\n response->ParseFromString( top->response( ) );\n\n cl->get_protocol( ).close_slot( call_id );\n\n } else { \/\/ NOT WAITABLE CALL\n cl->get_protocol( ).call_rpc_method( *llu );\n }\n }\n };\n\n rpc_channel::rpc_channel( common::connection_iface_sptr c )\n :impl_(new impl(c))\n {\n impl_->parent_ = this;\n }\n\n rpc_channel::~rpc_channel( )\n {\n delete impl_;\n }\n\n void rpc_channel::CallMethod(const gpb::MethodDescriptor* method,\n gpb::RpcController* controller,\n const gpb::Message* request,\n gpb::Message* response,\n gpb::Closure* done)\n {\n impl_->CallMethod( method, controller, request, response, done );\n }\n\n}}\n<commit_msg>protocol<commit_after>#include \"vtrc-rpc-channel.h\"\n\n#include <google\/protobuf\/service.h>\n#include <google\/protobuf\/descriptor.h>\n\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-protocol-layer.h\"\n#include \"vtrc-common\/vtrc-exception.h\"\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n\nnamespace vtrc { namespace client {\n\n namespace gpb = google::protobuf;\n\n struct rpc_channel::impl {\n\n vtrc::weak_ptr<common::connection_iface> connection_;\n\n rpc_channel *parent_;\n\n impl(vtrc::shared_ptr<common::connection_iface> c)\n :connection_(c)\n {}\n\n void CallMethod(const gpb::MethodDescriptor* method,\n gpb::RpcController* controller,\n const gpb::Message* request,\n gpb::Message* response,\n gpb::Closure* done)\n {\n common::closure_holder hold(done);\n\n common::connection_iface_sptr cl(connection_.lock( ));\n\n if( cl.get( ) == NULL ) {\n throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,\n \"Connection lost\");\n }\n\n vtrc_rpc_lowlevel::options call_opt\n ( cl->get_protocol( ).get_method_options(method) );\n\n std::string service_name(method->service( )->full_name( ));\n std::string method_name(method->name( ));\n\n vtrc::shared_ptr<\n vtrc_rpc_lowlevel::lowlevel_unit\n > llu(new vtrc_rpc_lowlevel::lowlevel_unit);\n\n llu->mutable_call( )->set_service( service_name );\n llu->mutable_call( )->set_method( method_name );\n\n llu->set_request( request->SerializeAsString( ) );\n llu->set_response( response->SerializeAsString( ) );\n\n llu->mutable_info( )->set_message_type(\n vtrc_rpc_lowlevel::message_info::MESSAGE_CALL );\n\n uint64_t call_id = cl->get_protocol( ).next_index( );\n\n llu->set_id( call_id );\n\n if( call_opt.wait( ) ) { \/\/ WAITABLE CALL\n\n cl->get_protocol( ).call_rpc_method( call_id, *llu );\n\n std::deque< vtrc::shared_ptr <\n vtrc_rpc_lowlevel::lowlevel_unit\n >\n > data_list;\n\n cl->get_protocol( ).wait_call_slot( call_id, data_list,\n call_opt.call_timeout( ) );\n\n vtrc::shared_ptr<vtrc_rpc_lowlevel::lowlevel_unit> top\n ( data_list.front( ) );\n\n if( top->error( ).code( ) != vtrc_errors::ERR_NO_ERROR )\n throw vtrc::common::exception( top->error( ).code( ),\n top->error( ).category( ),\n top->error( ).additional( ) );\n\n response->ParseFromString( top->response( ) );\n\n cl->get_protocol( ).close_slot( call_id );\n\n } else { \/\/ NOT WAITABLE CALL\n cl->get_protocol( ).call_rpc_method( *llu );\n }\n }\n };\n\n rpc_channel::rpc_channel( common::connection_iface_sptr c )\n :impl_(new impl(c))\n {\n impl_->parent_ = this;\n }\n\n rpc_channel::~rpc_channel( )\n {\n delete impl_;\n }\n\n void rpc_channel::CallMethod(const gpb::MethodDescriptor* method,\n gpb::RpcController* controller,\n const gpb::Message* request,\n gpb::Message* response,\n gpb::Closure* done)\n {\n impl_->CallMethod( method, controller, request, response, done );\n }\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/translate\/translate_manager.h\"\n\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/translation_service.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_controller.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_entry.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/translate\/translate_infobars_delegates.h\"\n#include \"chrome\/browser\/translate\/translate_prefs.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/pref_service.h\"\n\nTranslateManager::~TranslateManager() {\n}\n\nvoid TranslateManager::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::NAV_ENTRY_COMMITTED: {\n \/\/ We have navigated to a new page.\n NavigationController* controller =\n Source<NavigationController>(source).ptr();\n NavigationEntry* entry = controller->GetActiveEntry();\n if (!entry->language().empty()) {\n \/\/ The language for that page is known (it must be a back\/forward\n \/\/ navigation to a page we already visited).\n InitiateTranslation(controller->tab_contents(), entry->language());\n }\n break;\n }\n case NotificationType::TAB_LANGUAGE_DETERMINED: {\n TabContents* tab = Source<TabContents>(source).ptr();\n std::string language = *(Details<std::string>(details).ptr());\n InitiateTranslation(tab, language);\n break;\n }\n case NotificationType::PAGE_TRANSLATED: {\n TabContents* tab = Source<TabContents>(source).ptr();\n std::pair<std::string, std::string>* language_pair =\n (Details<std::pair<std::string, std::string> >(details).ptr());\n PrefService* prefs = GetPrefService(tab);\n tab->AddInfoBar(new AfterTranslateInfoBarDelegate(tab, prefs,\n language_pair->first,\n language_pair->second));\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\nTranslateManager::TranslateManager() {\n if (!TranslationService::IsTranslationEnabled())\n return;\n\n notification_registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n NotificationService::AllSources());\n notification_registrar_.Add(this, NotificationType::TAB_LANGUAGE_DETERMINED,\n NotificationService::AllSources());\n notification_registrar_.Add(this, NotificationType::PAGE_TRANSLATED,\n NotificationService::AllSources());\n}\n\nvoid TranslateManager::InitiateTranslation(TabContents* tab,\n const std::string& page_lang) {\n PrefService* prefs = GetPrefService(tab);\n NavigationEntry* entry = tab->controller().GetActiveEntry();\n if (!entry) {\n NOTREACHED();\n return;\n }\n\n std::string chrome_lang = g_browser_process->GetApplicationLocale();\n\n \/\/ We don't want to translate:\n \/\/ - any Chrome specific page (New Tab Page, Download, History... pages).\n \/\/ - similar languages (ex: en-US to en).\n \/\/ - any user black-listed URLs or user selected language combination.\n if (entry->url().SchemeIs(\"chrome\") || page_lang == chrome_lang ||\n !TranslationService::ShouldTranslatePage(page_lang, chrome_lang) ||\n !TranslatePrefs::CanTranslate(prefs, page_lang, entry->url())) {\n return;\n }\n if (TranslatePrefs::ShouldAutoTranslate(prefs, page_lang, chrome_lang)) {\n \/\/ The user has previously select \"always translate\" for this language.\n tab->TranslatePage(page_lang, chrome_lang);\n return;\n }\n\n \/\/ Prompts the user if he\/she wants the page translated.\n tab->AddInfoBar(new BeforeTranslateInfoBarDelegate(tab, prefs,\n entry->url(),\n page_lang, chrome_lang));\n}\n\nPrefService* TranslateManager::GetPrefService(TabContents* tab) {\n PrefService* prefs = NULL;\n if (tab->profile())\n prefs = tab->profile()->GetPrefs();\n if (prefs)\n return prefs;\n\n return g_browser_process->local_state();\n}\n<commit_msg>The \"after infobar\" could be sticky in some cases. Make sure we always remove it before showing a new \"before translate\" infobar.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/translate\/translate_manager.h\"\n\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/translation_service.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_controller.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_entry.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/translate\/translate_infobars_delegates.h\"\n#include \"chrome\/browser\/translate\/translate_prefs.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_source.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/pref_service.h\"\n\nTranslateManager::~TranslateManager() {\n}\n\nvoid TranslateManager::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::NAV_ENTRY_COMMITTED: {\n \/\/ We have navigated to a new page.\n NavigationController* controller =\n Source<NavigationController>(source).ptr();\n NavigationEntry* entry = controller->GetActiveEntry();\n if (!entry->language().empty()) {\n \/\/ The language for that page is known (it must be a back\/forward\n \/\/ navigation to a page we already visited).\n InitiateTranslation(controller->tab_contents(), entry->language());\n }\n break;\n }\n case NotificationType::TAB_LANGUAGE_DETERMINED: {\n TabContents* tab = Source<TabContents>(source).ptr();\n std::string language = *(Details<std::string>(details).ptr());\n InitiateTranslation(tab, language);\n break;\n }\n case NotificationType::PAGE_TRANSLATED: {\n TabContents* tab = Source<TabContents>(source).ptr();\n std::pair<std::string, std::string>* language_pair =\n (Details<std::pair<std::string, std::string> >(details).ptr());\n PrefService* prefs = GetPrefService(tab);\n tab->AddInfoBar(new AfterTranslateInfoBarDelegate(tab, prefs,\n language_pair->first,\n language_pair->second));\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\nTranslateManager::TranslateManager() {\n if (!TranslationService::IsTranslationEnabled())\n return;\n\n notification_registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n NotificationService::AllSources());\n notification_registrar_.Add(this, NotificationType::TAB_LANGUAGE_DETERMINED,\n NotificationService::AllSources());\n notification_registrar_.Add(this, NotificationType::PAGE_TRANSLATED,\n NotificationService::AllSources());\n}\n\nvoid TranslateManager::InitiateTranslation(TabContents* tab,\n const std::string& page_lang) {\n PrefService* prefs = GetPrefService(tab);\n NavigationEntry* entry = tab->controller().GetActiveEntry();\n if (!entry) {\n NOTREACHED();\n return;\n }\n\n std::string chrome_lang = g_browser_process->GetApplicationLocale();\n\n \/\/ We don't want to translate:\n \/\/ - any Chrome specific page (New Tab Page, Download, History... pages).\n \/\/ - similar languages (ex: en-US to en).\n \/\/ - any user black-listed URLs or user selected language combination.\n if (entry->url().SchemeIs(\"chrome\") || page_lang == chrome_lang ||\n !TranslationService::ShouldTranslatePage(page_lang, chrome_lang) ||\n !TranslatePrefs::CanTranslate(prefs, page_lang, entry->url())) {\n return;\n }\n if (TranslatePrefs::ShouldAutoTranslate(prefs, page_lang, chrome_lang)) {\n \/\/ The user has previously select \"always translate\" for this language.\n tab->TranslatePage(page_lang, chrome_lang);\n return;\n }\n\n \/\/ If we already have an \"after translate\" infobar, it sometimes might be\n \/\/ sticky when running in frames. So we need to proactively remove any\n \/\/ translate related infobars as they would prevent any new infobar from\n \/\/ showing. (As TabContents will not add an infobar if there is already one\n \/\/ showing equal to the one being added.)\n for (int i = 0; i < tab->infobar_delegate_count(); ++i) {\n InfoBarDelegate* info_bar = tab->GetInfoBarDelegateAt(i);\n if (info_bar->AsTranslateInfoBarDelegate())\n tab->RemoveInfoBar(info_bar);\n }\n\n \/\/ Prompts the user if he\/she wants the page translated.\n tab->AddInfoBar(new BeforeTranslateInfoBarDelegate(tab, prefs,\n entry->url(),\n page_lang, chrome_lang));\n}\n\nPrefService* TranslateManager::GetPrefService(TabContents* tab) {\n PrefService* prefs = NULL;\n if (tab->profile())\n prefs = tab->profile()->GetPrefs();\n if (prefs)\n return prefs;\n\n return g_browser_process->local_state();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/====================================================================\n#include \"AliCentraldNdetaTask.h\"\n#include <TMath.h>\n#include <TH2D.h>\n#include <TH1D.h>\n#include <THStack.h>\n#include <TList.h>\n#include <AliAnalysisManager.h>\n#include <AliAODEvent.h>\n#include <AliAODHandler.h>\n#include <AliAODInputHandler.h>\n#include \"AliForwardUtil.h\"\n#include \"AliAODForwardMult.h\"\n#include \"AliAODCentralMult.h\"\n\nClassDef(AliCentraldNdetaTask)\n#ifdef DOXY_INPUT\n;\n#endif\n\n\/\/____________________________________________________________________\nAliCentraldNdetaTask::AliCentraldNdetaTask(const char*)\n : AliBasedNdetaTask(\"Central\") \n{ \n fSymmetrice = false; \n fCorrEmpty = false;\n}\n\n\/\/____________________________________________________________________\nTH2D*\nAliCentraldNdetaTask::GetHistogram(const AliAODEvent* aod, Bool_t mc) \n{\n \/\/ Get objects from the event structure \n TObject* obj = 0;\n if (mc) obj = aod->FindListObject(\"CentralClustersMC\");\n else obj = aod->FindListObject(\"CentralClusters\");\n\n \/\/ We should have a central object at least \n if (!obj) { \n if (!mc) AliWarning(\"No Central object found AOD\");\n return 0;\n }\n\n \/\/ Cast to good types \n AliAODCentralMult* central = static_cast<AliAODCentralMult*>(obj);\n\n return &(central->GetHistogram());\n}\n\n\/\/\n\/\/ EOF\n\/\/\n<commit_msg>Fixed problem<commit_after>\/\/====================================================================\n#include \"AliCentraldNdetaTask.h\"\n#include <TMath.h>\n#include <TH2D.h>\n#include <TH1D.h>\n#include <THStack.h>\n#include <TList.h>\n#include <AliAnalysisManager.h>\n#include <AliAODEvent.h>\n#include <AliAODHandler.h>\n#include <AliAODInputHandler.h>\n#include \"AliForwardUtil.h\"\n#include \"AliAODForwardMult.h\"\n#include \"AliAODCentralMult.h\"\n\nClassImp(AliCentraldNdetaTask)\n#ifdef DOXY_INPUT\n;\n#endif\n\n\/\/____________________________________________________________________\nAliCentraldNdetaTask::AliCentraldNdetaTask(const char*)\n : AliBasedNdetaTask(\"Central\") \n{ \n fSymmetrice = false; \n fCorrEmpty = false;\n}\n\n\/\/____________________________________________________________________\nTH2D*\nAliCentraldNdetaTask::GetHistogram(const AliAODEvent* aod, Bool_t mc) \n{\n \/\/ Get objects from the event structure \n TObject* obj = 0;\n if (mc) obj = aod->FindListObject(\"CentralClustersMC\");\n else obj = aod->FindListObject(\"CentralClusters\");\n\n \/\/ We should have a central object at least \n if (!obj) { \n if (!mc) AliWarning(\"No Central object found AOD\");\n return 0;\n }\n\n \/\/ Cast to good types \n AliAODCentralMult* central = static_cast<AliAODCentralMult*>(obj);\n\n return &(central->GetHistogram());\n}\n\n\/\/\n\/\/ EOF\n\/\/\n<|endoftext|>"} {"text":"<commit_before>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode)\n{\n \/\/ Check if user has a valid token, otherwise make one. This has limitations.\n \/\/ One can always follow the standard procedure of calling alien-token-init then\n \/\/ source \/tmp\/gclient_env_$UID in the current shell.\n if (!AliAnalysisGrid::CreateToken()) return NULL;\n AliAnalysisAlien *plugin = new AliAnalysisAlien();\n\n \/\/ Overwrite all generated files, datasets and output results from a previous session\n plugin->SetOverwriteMode();\n \/\/ Set the run mode (can be \"full\", \"test\", \"offline\", \"submit\" or \"terminate\")\n \/\/ plugin->SetRunMode(\"full\"); \/\/ VERY IMPORTANT - DECRIBED BELOW\n \/\/ plugin->SetRunMode(\"test\"); \/\/ VERY IMPORTANT - DECRIBED BELOW\n plugin->SetRunMode(pluginRunMode); \/\/ VERY IMPORTANT - DECRIBED BELOW\n\n \/\/ Set versions of used packages\n plugin->SetAPIVersion(\"V1.1x\");\n plugin->SetROOTVersion(\"v5-27-05\");\n plugin->SetAliROOTVersion(\"v4-20-08-AN\");\n \/\/ Declare input data to be processed.\n\n \/\/ Method 1: Create automatically XML collections using alien 'find' command.\n \/\/ Define production directory LFN\n \/\/ plugin->SetGridDataDir(\"\/alice\/sim\/LHC10a18\");\n \/\/ Set data search pattern\n \/\/ plugin->SetDataPattern(\"*ESDs.root\"); \/\/ simulated, tags not used\n \/\/ plugin->SetDataPattern(\"*ESDs\/pass4\/*ESDs.root\"); \/\/ real data check reco pass and data base directory\n \/\/ plugin->SetRunPrefix(\"000\"); \/\/ real data\n \/\/ plugin->SetDataPattern(\"*tag.root\"); \/\/ Use ESD tags (same applies for AOD's)\n \/\/ ...then add run numbers to be considered\n \/\/ plugin->AddRunNumber(125020); \/\/ simulated\n \/\/ plugin->AddRunNumber(104065); \/\/ real data\n\n \/\/ Method 2: Declare existing data files (raw collections, xml collections, root file)\n \/\/ If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())\n \/\/ XML collections added via this method can be combined with the first method if\n \/\/ the content is compatible (using or not tags)\n plugin->AddDataFile(\"tag.xml\");\n \/\/ file generated with: find -x tag \/alice\/sim\/LHC10d1\/117222\/* AliESDs.root > tag.xml\n\n \/\/ Define alien work directory where all files will be copied. Relative to alien $HOME.\n plugin->SetGridWorkingDir(outputDir.Data());\n \/\/ Declare alien output directory. Relative to working directory.\n plugin->SetGridOutputDir(\"output\"); \/\/ In this case will be $HOME\/work\/output\n \/\/ Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED\n \/\/ using ACLiC on the worker nodes.\n plugin->SetAnalysisSource(\"AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx\");\n \/\/ Declare all libraries (other than the default ones for the framework. These will be\n \/\/ loaded by the generated analysis macro. Add all extra files (task .cxx\/.h) here.\n plugin->SetAdditionalLibs(\"AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx\");\n\n \/\/ No need for output file names. Procedure is automatic. <-- not true\n plugin->SetDefaultOutputs(kFALSE);\n plugin->SetOutputFiles(outputName.Data());\n \/\/ No need define the files to be archived. Note that this is handled automatically by the plugin.\n \/\/ plugin->SetOutputArchive(\"log_archive.zip:stdout,stderr\");\n \/\/ Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique !\n plugin->SetAnalysisMacro(\"DavidEtAnalysis.C\");\n \/\/ Optionally set maximum number of input files\/subjob (default 100, put 0 to ignore). The optimum for an analysis\n \/\/ is correlated with the run time - count few hours TTL per job, not minutes !\n plugin->SetSplitMaxInputFileNumber(100);\n \/\/ Optionally set number of failed jobs that will trigger killing waiting sub-jobs.\n plugin->SetMaxInitFailed(5);\n \/\/ Optionally resubmit threshold.\n plugin->SetMasterResubmitThreshold(90);\n \/\/ Optionally set time to live (default 30000 sec)\n plugin->SetTTL(20000);\n \/\/ Optionally set input format (default xml-single)\n plugin->SetInputFormat(\"xml-single\");\n \/\/ Optionally modify the name of the generated JDL (default analysis.jdl)\n plugin->SetJDLName(\"TaskEt.jdl\");\n \/\/ Optionally modify job price (default 1)\n plugin->SetPrice(1); \n \/\/ Optionally modify split mode (default 'se') \n plugin->SetSplitMode(\"se\");\n return plugin;\n} \n<commit_msg>add missing source file for running with plugin<commit_after>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode)\n{\n \/\/ Check if user has a valid token, otherwise make one. This has limitations.\n \/\/ One can always follow the standard procedure of calling alien-token-init then\n \/\/ source \/tmp\/gclient_env_$UID in the current shell.\n if (!AliAnalysisGrid::CreateToken()) return NULL;\n AliAnalysisAlien *plugin = new AliAnalysisAlien();\n\n \/\/ Overwrite all generated files, datasets and output results from a previous session\n plugin->SetOverwriteMode();\n \/\/ Set the run mode (can be \"full\", \"test\", \"offline\", \"submit\" or \"terminate\")\n \/\/ plugin->SetRunMode(\"full\"); \/\/ VERY IMPORTANT - DECRIBED BELOW\n \/\/ plugin->SetRunMode(\"test\"); \/\/ VERY IMPORTANT - DECRIBED BELOW\n plugin->SetRunMode(pluginRunMode); \/\/ VERY IMPORTANT - DECRIBED BELOW\n\n \/\/ Set versions of used packages\n plugin->SetAPIVersion(\"V1.1x\");\n plugin->SetROOTVersion(\"v5-27-05\");\n plugin->SetAliROOTVersion(\"v4-20-08-AN\");\n \/\/ Declare input data to be processed.\n\n \/\/ Method 1: Create automatically XML collections using alien 'find' command.\n \/\/ Define production directory LFN\n \/\/ plugin->SetGridDataDir(\"\/alice\/sim\/LHC10a18\");\n \/\/ Set data search pattern\n \/\/ plugin->SetDataPattern(\"*ESDs.root\"); \/\/ simulated, tags not used\n \/\/ plugin->SetDataPattern(\"*ESDs\/pass4\/*ESDs.root\"); \/\/ real data check reco pass and data base directory\n \/\/ plugin->SetRunPrefix(\"000\"); \/\/ real data\n \/\/ plugin->SetDataPattern(\"*tag.root\"); \/\/ Use ESD tags (same applies for AOD's)\n \/\/ ...then add run numbers to be considered\n \/\/ plugin->AddRunNumber(125020); \/\/ simulated\n \/\/ plugin->AddRunNumber(104065); \/\/ real data\n\n \/\/ Method 2: Declare existing data files (raw collections, xml collections, root file)\n \/\/ If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())\n \/\/ XML collections added via this method can be combined with the first method if\n \/\/ the content is compatible (using or not tags)\n plugin->AddDataFile(\"tag.xml\");\n \/\/ plugin->AddDataFile(\"wn.xml\"); \/\/ test\n \/\/ file generated with: find -x tag \/alice\/sim\/LHC10d1\/117222\/* AliESDs.root > tag.xml\n\n \/\/ Define alien work directory where all files will be copied. Relative to alien $HOME.\n plugin->SetGridWorkingDir(outputDir.Data());\n \/\/ Declare alien output directory. Relative to working directory.\n plugin->SetGridOutputDir(\"output\"); \/\/ In this case will be $HOME\/work\/output\n \/\/ Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED\n \/\/ using ACLiC on the worker nodes.\n plugin->SetAnalysisSource(\"AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx\");\n \/\/ Declare all libraries (other than the default ones for the framework. These will be\n \/\/ loaded by the generated analysis macro. Add all extra files (task .cxx\/.h) here.\n plugin->SetAdditionalLibs(\"AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx\");\n\n \/\/ No need for output file names. Procedure is automatic. <-- not true\n plugin->SetDefaultOutputs(kFALSE);\n plugin->SetOutputFiles(outputName.Data());\n \/\/ No need define the files to be archived. Note that this is handled automatically by the plugin.\n \/\/ plugin->SetOutputArchive(\"log_archive.zip:stdout,stderr\");\n \/\/ Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique !\n plugin->SetAnalysisMacro(\"DavidEtAnalysis.C\");\n \/\/ Optionally set maximum number of input files\/subjob (default 100, put 0 to ignore). The optimum for an analysis\n \/\/ is correlated with the run time - count few hours TTL per job, not minutes !\n plugin->SetSplitMaxInputFileNumber(100);\n \/\/ Optionally set number of failed jobs that will trigger killing waiting sub-jobs.\n plugin->SetMaxInitFailed(5);\n \/\/ Optionally resubmit threshold.\n plugin->SetMasterResubmitThreshold(90);\n \/\/ Optionally set time to live (default 30000 sec)\n plugin->SetTTL(20000);\n \/\/ Optionally set input format (default xml-single)\n plugin->SetInputFormat(\"xml-single\");\n \/\/ Optionally modify the name of the generated JDL (default analysis.jdl)\n plugin->SetJDLName(\"TaskEt.jdl\");\n \/\/ Optionally modify job price (default 1)\n plugin->SetPrice(1); \n \/\/ Optionally modify split mode (default 'se') \n plugin->SetSplitMode(\"se\");\n return plugin;\n} \n<|endoftext|>"} {"text":"<commit_before>#include <deal.II\/base\/polynomials_bernstein.h>\n\n#include <boost\/math\/special_functions\/binomial.hpp>\n\n#include <vector>\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace Binomial\n{\n template <typename number>\n std::vector<number>\n get_bernstein_coefficients (\n const unsigned int k, const unsigned int n)\n {\n Assert(n>0, ExcMessage(\"Bernstein polynomial needs to be of degree > 0.\"));\n AssertIndexRange(k, n+1);\n std::vector<number> coeff(n + 1, number(0.0));\n for (unsigned int i = k; i < n + 1; ++i)\n {\n coeff[i] = pow(number(-1), number(i - k))\n * boost::math::binomial_coefficient<number>(n, i)\n * boost::math::binomial_coefficient<number>(i, k);\n }\n return coeff;\n }\n}\n\ntemplate <typename number>\nPolynomialsBernstein<number>:: PolynomialsBernstein (\n const unsigned int index, const unsigned int degree)\n :\n Polynomials::Polynomial<number>(\n Binomial::get_bernstein_coefficients<number>(index, degree))\n{\n}\n\n\n#include \"polynomials_bernstein.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Compute powers of -1 by checking exponent parity.<commit_after>#include <deal.II\/base\/polynomials_bernstein.h>\n\n#include <boost\/math\/special_functions\/binomial.hpp>\n\n#include <vector>\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace Binomial\n{\n template <typename number>\n std::vector<number>\n get_bernstein_coefficients (\n const unsigned int k, const unsigned int n)\n {\n Assert(n>0, ExcMessage(\"Bernstein polynomial needs to be of degree > 0.\"));\n AssertIndexRange(k, n+1);\n std::vector<number> coeff(n + 1, number(0.0));\n for (unsigned int i = k; i < n + 1; ++i)\n {\n coeff[i] = ((i - k) % 2 == 0 ? 1 : -1)\n * boost::math::binomial_coefficient<number>(n, i)\n * boost::math::binomial_coefficient<number>(i, k);\n }\n return coeff;\n }\n}\n\ntemplate <typename number>\nPolynomialsBernstein<number>:: PolynomialsBernstein (\n const unsigned int index, const unsigned int degree)\n :\n Polynomials::Polynomial<number>(\n Binomial::get_bernstein_coefficients<number>(index, degree))\n{\n}\n\n\n#include \"polynomials_bernstein.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"QueueWorkingModule.h\"\n\n\/\/--- project modules used -----------------------------------------------------\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"Server.h\"\n#include \"AppLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- QueueWorkingModule ---------------------------------------------------------------\nQueueWorkingModule::QueueWorkingModule(const char *name)\n\t: WDModule(name)\n\t, fpQueue(NULL)\n\t, fpContext(NULL)\n\t, fContextLock(\"QueueWorkingModuleContextLock\")\n\t, fFailedPutbackMessages(Storage::Global())\n\t, fAlive(0UL)\n{\n\tStartTrace(QueueWorkingModule.QueueWorkingModule);\n}\n\nQueueWorkingModule::~QueueWorkingModule()\n{\n}\n\nvoid QueueWorkingModule::LogError(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogError);\n\tSYSERROR(strMessage);\n\tLog(strMessage, fErrorLogName);\n}\n\nvoid QueueWorkingModule::LogWarning(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogWarning);\n\tSYSWARNING(strMessage);\n\tLog(strMessage, fWarningLogName);\n}\n\nvoid QueueWorkingModule::LogInfo(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogInfo);\n\tLog(strMessage, fInfoLogName);\n}\n\nvoid QueueWorkingModule::Log(String strMessage, const char *channel)\n{\n\tStartTrace(QueueWorkingModule.Log);\n\tTrace(strMessage);\n\tif ( IsAlive() && fpContext ) {\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tif ( IsAlive() && fpContext ) {\n\t\t\tfpContext->GetTmpStore()[\"LogMessage\"] = strMessage;\n\t\t\tAppLogModule::Log(*fpContext, channel);\n\t\t}\n\t}\n}\n\nvoid QueueWorkingModule::Log(Anything &anyStatus, const char *channel)\n{\n\tStartTrace(QueueWorkingModule.Log);\n\tTraceAny(anyStatus, \"content to log\");\n\tif ( IsAlive() && fpContext ) {\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tif ( IsAlive() && fpContext ) {\n\t\t\tfpContext->GetTmpStore()[\"QueueWorkingStatus\"] = anyStatus;\n\t\t\tAppLogModule::Log(*fpContext, channel);\n\t\t}\n\t}\n}\n\nbool QueueWorkingModule::Init(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.Init);\n\tSubTraceAny(FullConfig, config, \"Config: \");\n\tROAnything roaConfig;\n\tif ( config.LookupPath(roaConfig, fName) ) {\n\t\tfConfig = roaConfig.DeepClone();\n\t\tTraceAny(fConfig, \"Module config\");\n\t\tfErrorLogName = GetNamedConfig(\"Logging\")[\"ErrorChannel\"].AsCharPtr(\"ErrorLog\");\n\t\tfWarningLogName = GetNamedConfig(\"Logging\")[\"WarningChannel\"].AsCharPtr(\"WarningLog\");\n\t\tfInfoLogName = GetNamedConfig(\"Logging\")[\"InfoChannel\"].AsCharPtr(\"AccessLog\");\n\t\tconst char *pServerName = GetNamedConfig(\"Logging\")[\"Servername\"].AsCharPtr(\"Server\");\n\t\tServer *pServer = Server::FindServer(pServerName);\n\t\tAnything dummy;\n\t\tfpContext = new Context(fConfig, dummy, pServer, 0, 0);\n\t\tIntInitQueue(GetConfig());\n\t\tfAlive = 0xf007f007;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool QueueWorkingModule::Finis()\n{\n\tStartTrace(QueueWorkingModule.Finis);\n\n\tSetDead();\n\n\tAnything anyStat;\n\tif ( GetQueueStatistics(anyStat) ) {\n\t\tStringStream aStream;\n\t\taStream << \"Statistics for [\" << GetName() << \"]\\n\";\n\t\tanyStat.PrintOn(aStream, true) << flush;\n\t\tSysLog::WriteToStderr(aStream.str());\n\t}\n\n\t\/\/ delete Queue, also wakes up blocked threads, threads MUST be in termination sequence!!\n\tIntCleanupQueue();\n\n\t{\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tdelete fpContext;\n\t\tfpContext = NULL;\n\t}\n\n\treturn true;\n}\n\nbool QueueWorkingModule::ResetInit(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.ResetInit);\n\t\/\/ calls Init\n\treturn WDModule::ResetInit(config);\n}\n\nbool QueueWorkingModule::ResetFinis(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.ResetFinis);\n\t\/\/ calls Finis\n\treturn WDModule::ResetFinis(config);\n}\n\nvoid QueueWorkingModule::IntInitQueue(const ROAnything roaConfig)\n{\n\tStartTrace(QueueWorkingModule.IntInitQueue);\n\tlong lQueueSize = roaConfig[\"QueueSize\"].AsLong(100L);\n\tfpQueue = new Queue(GetName(), lQueueSize);\n\tfFailedPutbackMessages = Anything();\n}\n\nvoid QueueWorkingModule::IntCleanupQueue()\n{\n\tStartTrace(QueueWorkingModule.IntCleanupQueue);\n\t\/\/ we could do something here to persist the content of the queue and the putback message buffer\n\tdelete fpQueue;\n\tfpQueue = NULL;\n\tfFailedPutbackMessages = Anything();\n}\n\nQueue::StatusCode QueueWorkingModule::PutElement(Anything &anyELement, bool bTryLock)\n{\n\tStartTrace(QueueWorkingModule.PutElement);\n\tQueue::StatusCode eRet = Queue::eDead;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\teRet = fpQueue->Put(anyELement, bTryLock);\n\t\tif ( eRet != Queue::eSuccess ) {\n\t\t\tSYSWARNING(\"Queue->Put failed, Queue::StatusCode:\" << eRet << \" !\");\n\t\t}\n\t}\n\treturn eRet;\n}\n\nROAnything QueueWorkingModule::GetConfig()\n{\n\tStartTrace(QueueWorkingModule.GetConfig);\n\treturn ((ROAnything)fConfig);\n}\n\nROAnything QueueWorkingModule::GetNamedConfig(const char *name)\n{\n\tStartTrace(QueueWorkingModule.GetNamedConfig);\n\treturn ((ROAnything)fConfig)[name];\n}\n\nQueue::StatusCode QueueWorkingModule::GetElement(Anything &anyValues, bool bTryLock)\n{\n\tStartTrace(QueueWorkingModule.GetElement);\n\tQueue::StatusCode eRet = Queue::eDead;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\tTrace(\"Queue still alive\");\n\t\t\/\/ try to get a failed message first\n\t\tif ( fFailedPutbackMessages.GetSize() > 0 ) {\n\t\t\tTrace(\"getting failed message 1 of \" << fFailedPutbackMessages.GetSize() );\n\t\t\tanyValues = fFailedPutbackMessages[0L];\n\t\t\tfFailedPutbackMessages.Remove(0L);\n\t\t\teRet = Queue::eSuccess;\n\t\t} else {\n\t\t\t\/\/ Default is blocking get to save cpu time\n\t\t\teRet = fpQueue->Get(anyValues, bTryLock);\n\t\t\tif ( ( eRet != Queue::eSuccess ) && ( eRet != Queue::eEmpty ) ) {\n\t\t\t\tSYSWARNING(\"Queue->Get failed, Queue::StatusCode:\" << eRet << \" !\");\n\t\t\t}\n\t\t}\n\t}\n\treturn eRet;\n}\n\nvoid QueueWorkingModule::PutBackElement(Anything &anyValues)\n{\n\tStartTrace(QueueWorkingModule.PutBackElement);\n\t\/\/ put message back to the queue (Appends!) if possible\n\t\/\/ take care not to lock ourselves up here, thus we MUST use a trylock here!\n\tQueue::StatusCode eRet = PutElement(anyValues, true);\n\tif ( eRet != Queue::eSuccess && ( eRet & Queue::eFull ) ) {\n\t\t\/\/ no more room in Queue, need to store this message internally for later put back\n\t\tfFailedPutbackMessages.Append(anyValues);\n\t}\n}\n\nlong QueueWorkingModule::FlushQueue(Anything &anyElements)\n{\n\tStartTrace(QueueWorkingModule.FlushQueue);\n\tlong lElements = 0L;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\tfpQueue->EmptyQueue(anyElements);\n\t\tlElements = anyElements.GetSize();\n\t\tLogInfo(String(GetName()) << \": flushed \" << lElements << \" elements\");\n\t}\n\treturn lElements;\n}\n\nbool QueueWorkingModule::GetQueueStatistics(Anything &anyStat)\n{\n\tStartTrace(QueueWorkingModule.GetQueueStatistics);\n\tif ( fpQueue ) {\n\t\tfpQueue->GetStatistics(anyStat);\n\t\treturn true;\n\t}\n\treturn false;\n}\n<commit_msg>added newling<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"QueueWorkingModule.h\"\n\n\/\/--- project modules used -----------------------------------------------------\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"Server.h\"\n#include \"AppLog.h\"\n#include \"StringStream.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- QueueWorkingModule ---------------------------------------------------------------\nQueueWorkingModule::QueueWorkingModule(const char *name)\n\t: WDModule(name)\n\t, fpQueue(NULL)\n\t, fpContext(NULL)\n\t, fContextLock(\"QueueWorkingModuleContextLock\")\n\t, fFailedPutbackMessages(Storage::Global())\n\t, fAlive(0UL)\n{\n\tStartTrace(QueueWorkingModule.QueueWorkingModule);\n}\n\nQueueWorkingModule::~QueueWorkingModule()\n{\n}\n\nvoid QueueWorkingModule::LogError(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogError);\n\tSYSERROR(strMessage);\n\tLog(strMessage, fErrorLogName);\n}\n\nvoid QueueWorkingModule::LogWarning(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogWarning);\n\tSYSWARNING(strMessage);\n\tLog(strMessage, fWarningLogName);\n}\n\nvoid QueueWorkingModule::LogInfo(String strMessage)\n{\n\tStartTrace(QueueWorkingModule.LogInfo);\n\tLog(strMessage, fInfoLogName);\n}\n\nvoid QueueWorkingModule::Log(String strMessage, const char *channel)\n{\n\tStartTrace(QueueWorkingModule.Log);\n\tTrace(strMessage);\n\tif ( IsAlive() && fpContext ) {\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tif ( IsAlive() && fpContext ) {\n\t\t\tfpContext->GetTmpStore()[\"LogMessage\"] = strMessage;\n\t\t\tAppLogModule::Log(*fpContext, channel);\n\t\t}\n\t}\n}\n\nvoid QueueWorkingModule::Log(Anything &anyStatus, const char *channel)\n{\n\tStartTrace(QueueWorkingModule.Log);\n\tTraceAny(anyStatus, \"content to log\");\n\tif ( IsAlive() && fpContext ) {\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tif ( IsAlive() && fpContext ) {\n\t\t\tfpContext->GetTmpStore()[\"QueueWorkingStatus\"] = anyStatus;\n\t\t\tAppLogModule::Log(*fpContext, channel);\n\t\t}\n\t}\n}\n\nbool QueueWorkingModule::Init(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.Init);\n\tSubTraceAny(FullConfig, config, \"Config: \");\n\tROAnything roaConfig;\n\tif ( config.LookupPath(roaConfig, fName) ) {\n\t\tfConfig = roaConfig.DeepClone();\n\t\tTraceAny(fConfig, \"Module config\");\n\t\tfErrorLogName = GetNamedConfig(\"Logging\")[\"ErrorChannel\"].AsCharPtr(\"ErrorLog\");\n\t\tfWarningLogName = GetNamedConfig(\"Logging\")[\"WarningChannel\"].AsCharPtr(\"WarningLog\");\n\t\tfInfoLogName = GetNamedConfig(\"Logging\")[\"InfoChannel\"].AsCharPtr(\"AccessLog\");\n\t\tconst char *pServerName = GetNamedConfig(\"Logging\")[\"Servername\"].AsCharPtr(\"Server\");\n\t\tServer *pServer = Server::FindServer(pServerName);\n\t\tAnything dummy;\n\t\tfpContext = new Context(fConfig, dummy, pServer, 0, 0);\n\t\tIntInitQueue(GetConfig());\n\t\tfAlive = 0xf007f007;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool QueueWorkingModule::Finis()\n{\n\tStartTrace(QueueWorkingModule.Finis);\n\n\tSetDead();\n\n\tAnything anyStat;\n\tif ( GetQueueStatistics(anyStat) ) {\n\t\tStringStream aStream;\n\t\taStream << \"Statistics for [\" << GetName() << \"]\\n\";\n\t\tanyStat.PrintOn(aStream, true) << \"\\n\" << flush;\n\t\tSysLog::WriteToStderr(aStream.str());\n\t}\n\n\t\/\/ delete Queue, also wakes up blocked threads, threads MUST be in termination sequence!!\n\tIntCleanupQueue();\n\n\t{\n\t\tMutexEntry me(fContextLock);\n\t\tme.Use();\n\t\tdelete fpContext;\n\t\tfpContext = NULL;\n\t}\n\n\treturn true;\n}\n\nbool QueueWorkingModule::ResetInit(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.ResetInit);\n\t\/\/ calls Init\n\treturn WDModule::ResetInit(config);\n}\n\nbool QueueWorkingModule::ResetFinis(const ROAnything config)\n{\n\tStartTrace(QueueWorkingModule.ResetFinis);\n\t\/\/ calls Finis\n\treturn WDModule::ResetFinis(config);\n}\n\nvoid QueueWorkingModule::IntInitQueue(const ROAnything roaConfig)\n{\n\tStartTrace(QueueWorkingModule.IntInitQueue);\n\tlong lQueueSize = roaConfig[\"QueueSize\"].AsLong(100L);\n\tfpQueue = new Queue(GetName(), lQueueSize);\n\tfFailedPutbackMessages = Anything();\n}\n\nvoid QueueWorkingModule::IntCleanupQueue()\n{\n\tStartTrace(QueueWorkingModule.IntCleanupQueue);\n\t\/\/ we could do something here to persist the content of the queue and the putback message buffer\n\tdelete fpQueue;\n\tfpQueue = NULL;\n\tfFailedPutbackMessages = Anything();\n}\n\nQueue::StatusCode QueueWorkingModule::PutElement(Anything &anyELement, bool bTryLock)\n{\n\tStartTrace(QueueWorkingModule.PutElement);\n\tQueue::StatusCode eRet = Queue::eDead;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\teRet = fpQueue->Put(anyELement, bTryLock);\n\t\tif ( eRet != Queue::eSuccess ) {\n\t\t\tSYSWARNING(\"Queue->Put failed, Queue::StatusCode:\" << eRet << \" !\");\n\t\t}\n\t}\n\treturn eRet;\n}\n\nROAnything QueueWorkingModule::GetConfig()\n{\n\tStartTrace(QueueWorkingModule.GetConfig);\n\treturn ((ROAnything)fConfig);\n}\n\nROAnything QueueWorkingModule::GetNamedConfig(const char *name)\n{\n\tStartTrace(QueueWorkingModule.GetNamedConfig);\n\treturn ((ROAnything)fConfig)[name];\n}\n\nQueue::StatusCode QueueWorkingModule::GetElement(Anything &anyValues, bool bTryLock)\n{\n\tStartTrace(QueueWorkingModule.GetElement);\n\tQueue::StatusCode eRet = Queue::eDead;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\tTrace(\"Queue still alive\");\n\t\t\/\/ try to get a failed message first\n\t\tif ( fFailedPutbackMessages.GetSize() > 0 ) {\n\t\t\tTrace(\"getting failed message 1 of \" << fFailedPutbackMessages.GetSize() );\n\t\t\tanyValues = fFailedPutbackMessages[0L];\n\t\t\tfFailedPutbackMessages.Remove(0L);\n\t\t\teRet = Queue::eSuccess;\n\t\t} else {\n\t\t\t\/\/ Default is blocking get to save cpu time\n\t\t\teRet = fpQueue->Get(anyValues, bTryLock);\n\t\t\tif ( ( eRet != Queue::eSuccess ) && ( eRet != Queue::eEmpty ) ) {\n\t\t\t\tSYSWARNING(\"Queue->Get failed, Queue::StatusCode:\" << eRet << \" !\");\n\t\t\t}\n\t\t}\n\t}\n\treturn eRet;\n}\n\nvoid QueueWorkingModule::PutBackElement(Anything &anyValues)\n{\n\tStartTrace(QueueWorkingModule.PutBackElement);\n\t\/\/ put message back to the queue (Appends!) if possible\n\t\/\/ take care not to lock ourselves up here, thus we MUST use a trylock here!\n\tQueue::StatusCode eRet = PutElement(anyValues, true);\n\tif ( eRet != Queue::eSuccess && ( eRet & Queue::eFull ) ) {\n\t\t\/\/ no more room in Queue, need to store this message internally for later put back\n\t\tfFailedPutbackMessages.Append(anyValues);\n\t}\n}\n\nlong QueueWorkingModule::FlushQueue(Anything &anyElements)\n{\n\tStartTrace(QueueWorkingModule.FlushQueue);\n\tlong lElements = 0L;\n\tif ( fpQueue && fpQueue->IsAlive() && IsAlive() ) {\n\t\tfpQueue->EmptyQueue(anyElements);\n\t\tlElements = anyElements.GetSize();\n\t\tLogInfo(String(GetName()) << \": flushed \" << lElements << \" elements\");\n\t}\n\treturn lElements;\n}\n\nbool QueueWorkingModule::GetQueueStatistics(Anything &anyStat)\n{\n\tStartTrace(QueueWorkingModule.GetQueueStatistics);\n\tif ( fpQueue ) {\n\t\tfpQueue->GetStatistics(anyStat);\n\t\treturn true;\n\t}\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n\nclass Point\n{\n public:\n\n Point();\n\n \n\n\n};\n\n\n<commit_msg>Created accessor name to match declaration.closes #79<commit_after>#include <iostream>\n\n\nclass Point\n{\n public:\n\n Point();\n Point(double , double);\n double x();\n void set_x(double);\n double y();\n void set_y(double);\n\n private:\n double m_x;\n double m_y;\n\n};\n\nvoid Point::set_x(double x)\n{\n return m_x;\n}\nvoid Point::set_y(double y)\n{\n return m_y;\n\n}\nPoint::Point()\n{\n set_x(0);\n set_y(0);\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cctype> \/* std::tolower(int) *\/\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 13);\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t numbers[2] = {0, 0}; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = ParallelPrimeSieve::USE_IDEAL_NUM_THREADS;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.1, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2)\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n numbers[i-1] = parser.getResult();\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(10) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(10) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n if (!quietMode)\n std::cout << std::setw(10) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n \/\/ init primeSieve\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(numbers[0]);\n primeSieve.setStopNumber(numbers[1]);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n primeSieve.setNumThreads(threads);\n\n if (!quietMode)\n std::cout << std::setw(10) << \"Threads\" << \" = \" << primeSieve.getNumThreads() << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve();\n\n \/\/ print new line\n if ((flags & PRINT_STATUS) || (\n (flags & PRINT_FLAGS) &&\n (flags & COUNT_FLAGS) ))\n std::cout << std::endl;\n\n \/\/ get max output width\n std::size_t width = (quietMode) ?0 :12;\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if ((flags & (COUNT_PRIMES << i)) && width < primes[i].length())\n width = primes[i].length();\n\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(static_cast<int> (width)) << primes[i] << \" : \"\n << primeSieve.getCounts(i) << std::endl;\n\n \/\/ print time elapsed\n if (!quietMode)\n std::cout << std::setw(static_cast<int> (width)) << \"Time elapsed\" << \" : \"\n << primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<commit_msg>updated version number<commit_after>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cctype> \/* std::tolower(int) *\/\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 13);\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t numbers[2] = {0, 0}; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = ParallelPrimeSieve::USE_IDEAL_NUM_THREADS;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.2, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2)\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n numbers[i-1] = parser.getResult();\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(10) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(10) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n if (!quietMode)\n std::cout << std::setw(10) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n \/\/ init primeSieve\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(numbers[0]);\n primeSieve.setStopNumber(numbers[1]);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n primeSieve.setNumThreads(threads);\n\n if (!quietMode)\n std::cout << std::setw(10) << \"Threads\" << \" = \" << primeSieve.getNumThreads() << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve();\n\n \/\/ print new line\n if ((flags & PRINT_STATUS) || (\n (flags & PRINT_FLAGS) &&\n (flags & COUNT_FLAGS) ))\n std::cout << std::endl;\n\n \/\/ get max output width\n std::size_t width = (quietMode) ?0 :12;\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if ((flags & (COUNT_PRIMES << i)) && width < primes[i].length())\n width = primes[i].length();\n\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(static_cast<int> (width)) << primes[i] << \" : \"\n << primeSieve.getCounts(i) << std::endl;\n\n \/\/ print time elapsed\n if (!quietMode)\n std::cout << std::setw(static_cast<int> (width)) << \"Time elapsed\" << \" : \"\n << primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>mpImplWin only exists for dropdown ListBoxes<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Pack My Sprites.\n\n Pack My Sprites is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License.\n\n Pack My Sprites is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n \n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <boost\/spirit\/include\/classic_ast.hpp>\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::error_report_parser()\n{\n\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::error_report_parser( const std::string msg )\n : m_msg(msg)\n{\n\n}\n\ntemplate <typename ScannerT>\ntemplate <typename LocalScanner>\nint\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::operator()\n (const LocalScanner& scan, result_t& \/*result*\/) const\n{\n boost::spirit::classic::file_position fpos = scan.first.get_position();\n\n std::cerr << fpos.file << \": \" << fpos.line << \": \"\n << fpos.column << \": \" << m_msg << std::endl;\n\n return -1;\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nchar_error_report_parser::char_error_report_parser()\n{\n\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nchar_error_report_parser::char_error_report_parser( char c )\n : error_report_parser( std::string(\"Missing character '\") + c + \"'.\" )\n{\n\n}\n\n\n\n\n\ntemplate<typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::definition\n( const grammar& self )\n{\n initialize_error_parsers();\n\n m_file = m_atlas;\n\n m_atlas =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"atlas\") ]\n >> ( m_string | m_error_atlas )\n >> ( ( boost::spirit::classic::uint_p\n >> boost::spirit::classic::no_node_d\n [ boost::spirit::classic::ch_p('x') ]\n >> boost::spirit::classic::uint_p )\n | m_error_size )\n >> !m_margin\n >> !m_order\n >> *m_image_declaration >> *m_sprite_atlas_page;\n\n m_margin =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"margin\") ]\n >> boost::spirit::classic::uint_p\n ;\n\n m_order =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"order\") ]\n >> (m_string | m_error_string)\n ;\n\n m_image_declaration =\n m_identifier >> (m_string | m_error_string);\n\n m_sprite_atlas_page = m_sprite_declaration;\n\n m_sprite_declaration =\n !m_properties\n >> m_string\n >> ( m_sprite_size | m_error_autosize )\n >> boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"with\") ]\n >> m_identifier\n >> m_layer_list\n >> !m_mask\n >> ( boost::spirit::classic::no_node_d\n [ boost::spirit::classic::ch_p(';') ] | m_error_semicolon )\n ;\n\n m_mask =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"mask\") ]\n >> m_layer_list;\n ;\n\n m_layer_list =\n *m_layer_reference;\n\n m_layer_reference =\n ( !m_properties >> (m_string | m_glob) )\n | m_exclude;\n\n m_properties =\n boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('[') ]\n >> *m_identifier\n >> boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p(']') ]\n ;\n\n m_glob =\n boost::spirit::classic::strlit<>(\"glob\")\n >> m_string;\n ;\n\n m_exclude = \n boost::spirit::classic::strlit<>(\"exclude\")\n >> (m_string | m_glob);\n\n m_sprite_size =\n ( m_identifier | m_string )\n >> !( boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('*') ]\n >> boost::spirit::classic::real_p );\n\n m_identifier =\n boost::spirit::classic::no_node_d[ *boost::spirit::classic::blank_p ]\n >> boost::spirit::classic::token_node_d\n [ boost::spirit::classic::lexeme_d[ (boost::spirit::classic::alpha_p | '_')\n >> *(boost::spirit::classic::alnum_p | '_') ]\n ];\n\n m_string =\n boost::spirit::classic::lexeme_d\n [ boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('\"') ]\n >> boost::spirit::classic::token_node_d\n [ *(boost::spirit::classic::strlit<>(\"\\\\\\\"\")\n | (boost::spirit::classic::anychar_p - '\"') ) ]\n >> boost::spirit::classic::no_node_d\n [ ( '\"' | m_error_not_terminated_string ) ]\n ];\n}\n\ntemplate<typename ScannerT>\nvoid pms::serialization::spritedesc::grammar::definition<ScannerT>::\ninitialize_error_parsers()\n{\n m_error_autosize =\n error_report_parser( \"Size expected, like: autosize * 0.5.\" );\n m_error_identifier = error_report_parser( \"Identifier expected.\" );\n m_error_string = error_report_parser( \"String expected.\" );\n m_error_not_terminated_string =\n error_report_parser( \"Not terminated string.\" );\n\n m_error_atlas = error_report_parser( \"atlas expected\" );\n m_error_size = error_report_parser( \"Size expected (width x height).\" );\n\n m_error_semicolon = char_error_report_parser( ';' );\n}\n<commit_msg>Fix string replacement error in the grammar.<commit_after>\/*\n This file is part of Pack My Sprites.\n\n Pack My Sprites is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License.\n\n Pack My Sprites is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n \n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <boost\/spirit\/include\/classic_ast.hpp>\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::error_report_parser()\n{\n\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::error_report_parser( const std::string msg )\n : m_msg(msg)\n{\n\n}\n\ntemplate <typename ScannerT>\ntemplate <typename LocalScanner>\nint\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nerror_report_parser::operator()\n (const LocalScanner& scan, result_t& \/*result*\/) const\n{\n boost::spirit::classic::file_position fpos = scan.first.get_position();\n\n std::cerr << fpos.file << \": \" << fpos.line << \": \"\n << fpos.column << \": \" << m_msg << std::endl;\n\n return -1;\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nchar_error_report_parser::char_error_report_parser()\n{\n\n}\n\ntemplate <typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::\nchar_error_report_parser::char_error_report_parser( char c )\n : error_report_parser( std::string(\"Missing character '\") + c + \"'.\" )\n{\n\n}\n\n\n\n\n\ntemplate<typename ScannerT>\npms::serialization::spritedesc::grammar::definition<ScannerT>::definition\n( const grammar& self )\n{\n initialize_error_parsers();\n\n m_file = m_atlas;\n\n m_atlas =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"sprite_sheet\") ]\n >> ( m_string | m_error_atlas )\n >> ( ( boost::spirit::classic::uint_p\n >> boost::spirit::classic::no_node_d\n [ boost::spirit::classic::ch_p('x') ]\n >> boost::spirit::classic::uint_p )\n | m_error_size )\n >> !m_margin\n >> !m_order\n >> *m_image_declaration >> *m_sprite_atlas_page;\n\n m_margin =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"margin\") ]\n >> boost::spirit::classic::uint_p\n ;\n\n m_order =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"order\") ]\n >> (m_string | m_error_string)\n ;\n\n m_image_declaration =\n m_identifier >> (m_string | m_error_string);\n\n m_sprite_atlas_page = m_sprite_declaration;\n\n m_sprite_declaration =\n !m_properties\n >> m_string\n >> ( m_sprite_size | m_error_autosize )\n >> boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"with\") ]\n >> m_identifier\n >> m_layer_list\n >> !m_mask\n >> ( boost::spirit::classic::no_node_d\n [ boost::spirit::classic::ch_p(';') ] | m_error_semicolon )\n ;\n\n m_mask =\n boost::spirit::classic::no_node_d\n [ boost::spirit::classic::strlit<>(\"mask\") ]\n >> m_layer_list;\n ;\n\n m_layer_list =\n *m_layer_reference;\n\n m_layer_reference =\n ( !m_properties >> (m_string | m_glob) )\n | m_exclude;\n\n m_properties =\n boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('[') ]\n >> *m_identifier\n >> boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p(']') ]\n ;\n\n m_glob =\n boost::spirit::classic::strlit<>(\"glob\")\n >> m_string;\n ;\n\n m_exclude = \n boost::spirit::classic::strlit<>(\"exclude\")\n >> (m_string | m_glob);\n\n m_sprite_size =\n ( m_identifier | m_string )\n >> !( boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('*') ]\n >> boost::spirit::classic::real_p );\n\n m_identifier =\n boost::spirit::classic::no_node_d[ *boost::spirit::classic::blank_p ]\n >> boost::spirit::classic::token_node_d\n [ boost::spirit::classic::lexeme_d[ (boost::spirit::classic::alpha_p | '_')\n >> *(boost::spirit::classic::alnum_p | '_') ]\n ];\n\n m_string =\n boost::spirit::classic::lexeme_d\n [ boost::spirit::classic::no_node_d[ boost::spirit::classic::ch_p('\"') ]\n >> boost::spirit::classic::token_node_d\n [ *(boost::spirit::classic::strlit<>(\"\\\\\\\"\")\n | (boost::spirit::classic::anychar_p - '\"') ) ]\n >> boost::spirit::classic::no_node_d\n [ ( '\"' | m_error_not_terminated_string ) ]\n ];\n}\n\ntemplate<typename ScannerT>\nvoid pms::serialization::spritedesc::grammar::definition<ScannerT>::\ninitialize_error_parsers()\n{\n m_error_autosize =\n error_report_parser( \"Size expected, like: autosize * 0.5.\" );\n m_error_identifier = error_report_parser( \"Identifier expected.\" );\n m_error_string = error_report_parser( \"String expected.\" );\n m_error_not_terminated_string =\n error_report_parser( \"Not terminated string.\" );\n\n m_error_atlas = error_report_parser( \"atlas expected\" );\n m_error_size = error_report_parser( \"Size expected (width x height).\" );\n\n m_error_semicolon = char_error_report_parser( ';' );\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Main\n#include <boost\/test\/unit_test.hpp>\n#include <net\/client.h>\n#include <net\/server.h>\n\nconst dariadb::net::Server::Param server_param(2001);\nconst dariadb::net::Client::Param client_param(\"127.0.0.1\", 2001);\n\nBOOST_AUTO_TEST_CASE(Instance) {\n dariadb::net::Server s(server_param);\n BOOST_CHECK_EQUAL(s.connections_accepted(),size_t(0));\n\n dariadb::net::Client c(client_param);\n c.connect();\n\n while(s.connections_accepted()!=size_t(1)){\n\n }\n}\n<commit_msg>lock on test<commit_after>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Main\n#include <boost\/test\/unit_test.hpp>\n#include <net\/client.h>\n#include <net\/server.h>\n#include <utils\/locker.h>\n\nconst dariadb::net::Server::Param server_param(2001);\nconst dariadb::net::Client::Param client_param(\"127.0.0.1\", 2001);\n\nBOOST_AUTO_TEST_CASE(Instance) {\n dariadb::utils::Locker lock;\n std::lock_guard<dariadb::utils::Locker> lg(lock);\n dariadb::net::Server s(server_param);\n BOOST_CHECK_EQUAL(s.connections_accepted(),size_t(0));\n\n dariadb::net::Client c(client_param);\n c.connect();\n\n while(s.connections_accepted()!=size_t(1)){\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_file_io.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_util_proxy.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/platform_file.h\"\n#include \"base\/logging.h\"\n#include \"base\/time.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_file_io_dev.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_file_io_trusted_dev.h\"\n#include \"third_party\/ppapi\/c\/pp_completion_callback.h\"\n#include \"third_party\/ppapi\/c\/pp_errors.h\"\n#include \"webkit\/glue\/plugins\/pepper_file_ref.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_instance.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/plugins\/pepper_resource_tracker.h\"\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Module module_id) {\n PluginModule* module = PluginModule::FromPPModule(module_id);\n if (!module)\n return 0;\n\n FileIO* file_io = new FileIO(module);\n return file_io->GetReference();\n}\n\nbool IsFileIO(PP_Resource resource) {\n return !!Resource::GetAs<FileIO>(resource);\n}\n\nint32_t Open(PP_Resource file_io_id,\n PP_Resource file_ref_id,\n int32_t open_flags,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n\n scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id));\n if (!file_ref)\n return PP_ERROR_BADRESOURCE;\n\n return file_io->Open(file_ref, open_flags, callback);\n}\n\nint32_t Query(PP_Resource file_io_id,\n PP_FileInfo_Dev* info,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Query(info, callback);\n}\n\nint32_t Touch(PP_Resource file_io_id,\n PP_Time last_access_time,\n PP_Time last_modified_time,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Touch(last_access_time, last_modified_time, callback);\n}\n\nint32_t Read(PP_Resource file_io_id,\n int64_t offset,\n char* buffer,\n int32_t bytes_to_read,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Read(offset, buffer, bytes_to_read, callback);\n}\n\nint32_t Write(PP_Resource file_io_id,\n int64_t offset,\n const char* buffer,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Write(offset, buffer, bytes_to_write, callback);\n}\n\nint32_t SetLength(PP_Resource file_io_id,\n int64_t length,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->SetLength(length, callback);\n}\n\nint32_t Flush(PP_Resource file_io_id,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Flush(callback);\n}\n\nvoid Close(PP_Resource file_io_id) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return;\n file_io->Close();\n}\n\nconst PPB_FileIO_Dev ppb_fileio = {\n &Create,\n &IsFileIO,\n &Open,\n &Query,\n &Touch,\n &Read,\n &Write,\n &SetLength,\n &Flush,\n &Close\n};\n\nint32_t GetOSFileDescriptor(PP_Resource file_io_id) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->GetOSFileDescriptor();\n}\n\nint32_t WillWrite(PP_Resource file_io_id,\n int64_t offset,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->WillWrite(offset, bytes_to_write, callback);\n}\n\nint32_t WillSetLength(PP_Resource file_io_id,\n int64_t length,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->WillSetLength(length, callback);\n}\n\nconst PPB_FileIOTrusted_Dev ppb_fileiotrusted = {\n &GetOSFileDescriptor,\n &WillWrite,\n &WillSetLength\n};\n\nint PlatformFileErrorToPepperError(base::PlatformFileError error_code) {\n switch (error_code) {\n case base::PLATFORM_FILE_OK:\n return PP_OK;\n case base::PLATFORM_FILE_ERROR_EXISTS:\n return PP_ERROR_FILEEXISTS;\n case base::PLATFORM_FILE_ERROR_NOT_FOUND:\n return PP_ERROR_FILENOTFOUND;\n case base::PLATFORM_FILE_ERROR_ACCESS_DENIED:\n return PP_ERROR_NOACCESS;\n case base::PLATFORM_FILE_ERROR_NO_MEMORY:\n return PP_ERROR_NOMEMORY;\n case base::PLATFORM_FILE_ERROR_NO_SPACE:\n return PP_ERROR_NOSPACE;\n case base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY:\n NOTREACHED();\n return PP_ERROR_FAILED;\n default:\n return PP_ERROR_FAILED;\n }\n}\n\n} \/\/ namespace\n\nFileIO::FileIO(PluginModule* module)\n : Resource(module),\n delegate_(module->GetSomeInstance()->delegate()),\n ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)),\n file_(base::kInvalidPlatformFileValue),\n callback_(),\n info_(NULL) {\n}\n\nFileIO::~FileIO() {\n Close();\n}\n\n\/\/ static\nconst PPB_FileIO_Dev* FileIO::GetInterface() {\n return &ppb_fileio;\n}\n\n\/\/ static\nconst PPB_FileIOTrusted_Dev* FileIO::GetTrustedInterface() {\n return &ppb_fileiotrusted;\n}\n\nint32_t FileIO::Open(FileRef* file_ref,\n int32_t open_flags,\n PP_CompletionCallback callback) {\n if (file_ != base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n int flags = 0;\n if (open_flags & PP_FILEOPENFLAG_READ)\n flags |= base::PLATFORM_FILE_READ;\n if (open_flags & PP_FILEOPENFLAG_WRITE) {\n flags |= base::PLATFORM_FILE_WRITE;\n flags |= base::PLATFORM_FILE_WRITE_ATTRIBUTES;\n }\n if (open_flags & PP_FILEOPENFLAG_TRUNCATE) {\n DCHECK(flags & PP_FILEOPENFLAG_WRITE);\n flags |= base::PLATFORM_FILE_TRUNCATE;\n }\n\n if (open_flags & PP_FILEOPENFLAG_CREATE) {\n if (open_flags & PP_FILEOPENFLAG_EXCLUSIVE)\n flags |= base::PLATFORM_FILE_CREATE;\n else\n flags |= base::PLATFORM_FILE_OPEN_ALWAYS;\n } else\n flags |= base::PLATFORM_FILE_OPEN;\n\n file_system_type_ = file_ref->file_system_type();\n if (!delegate_->AsyncOpenFile(\n file_ref->system_path(), flags,\n callback_factory_.NewCallback(&FileIO::AsyncOpenFileCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Query(PP_FileInfo_Dev* info,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n DCHECK(!info_);\n DCHECK(info);\n info_ = info;\n\n if (!base::FileUtilProxy::GetFileInfoFromPlatformFile(\n delegate_->GetFileThreadMessageLoopProxy(), file_,\n callback_factory_.NewCallback(&FileIO::QueryInfoCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Touch(PP_Time last_access_time,\n PP_Time last_modified_time,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Touch(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, base::Time::FromDoubleT(last_access_time),\n base::Time::FromDoubleT(last_modified_time),\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Read(int64_t offset,\n char* buffer,\n int32_t bytes_to_read,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Read(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, offset, buffer, bytes_to_read,\n callback_factory_.NewCallback(&FileIO::ReadWriteCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Write(int64_t offset,\n const char* buffer,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Write(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, offset, buffer, bytes_to_write,\n callback_factory_.NewCallback(&FileIO::ReadWriteCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::SetLength(int64_t length,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Truncate(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, length,\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Flush(PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Flush(\n delegate_->GetFileThreadMessageLoopProxy(), file_,\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nvoid FileIO::Close() {\n if (file_ != base::kInvalidPlatformFileValue)\n base::FileUtilProxy::Close(\n delegate_->GetFileThreadMessageLoopProxy(), file_, NULL);\n}\n\nint32_t FileIO::GetOSFileDescriptor() {\n return reinterpret_cast<uintptr_t>(base::kInvalidPlatformFileValue);\n}\n\nint32_t FileIO::WillWrite(int64_t offset,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n \/\/ TODO(dumi): implement me\n return PP_OK;\n}\n\nint32_t FileIO::WillSetLength(int64_t length,\n PP_CompletionCallback callback) {\n \/\/ TODO(dumi): implement me\n return PP_OK;\n}\n\nvoid FileIO::RunPendingCallback(int result) {\n if (!callback_.func)\n return;\n\n PP_CompletionCallback callback = {0};\n std::swap(callback, callback_);\n PP_RunCompletionCallback(&callback, result);\n}\n\nvoid FileIO::StatusCallback(base::PlatformFileError error_code) {\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::AsyncOpenFileCallback(base::PlatformFileError error_code,\n base::PlatformFile file) {\n DCHECK(file_ == base::kInvalidPlatformFileValue);\n file_ = file;\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::QueryInfoCallback(base::PlatformFileError error_code,\n const base::PlatformFileInfo& file_info) {\n DCHECK(info_);\n if (error_code == base::PLATFORM_FILE_OK) {\n info_->size = file_info.size;\n info_->creation_time = file_info.creation_time.ToDoubleT();\n info_->last_access_time = file_info.last_accessed.ToDoubleT();\n info_->last_modified_time = file_info.last_modified.ToDoubleT();\n info_->system_type = file_system_type_;\n if (file_info.is_directory)\n info_->type = PP_FILETYPE_DIRECTORY;\n else\n info_->type = PP_FILETYPE_REGULAR;\n }\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::ReadWriteCallback(base::PlatformFileError error_code,\n int bytes_read_or_written) {\n if (error_code != base::PLATFORM_FILE_OK)\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n else\n RunPendingCallback(bytes_read_or_written);\n}\n\n} \/\/ namespace pepper\n<commit_msg>Fixing pepper::FileIO::GetOSFileDescriptor(): 1. Return the actual file descriptor. 2. int cannot be converted to uintptr_t on Linux and Mac (and we don't need to do this).<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_file_io.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_util_proxy.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/platform_file.h\"\n#include \"base\/logging.h\"\n#include \"base\/time.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_file_io_dev.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_file_io_trusted_dev.h\"\n#include \"third_party\/ppapi\/c\/pp_completion_callback.h\"\n#include \"third_party\/ppapi\/c\/pp_errors.h\"\n#include \"webkit\/glue\/plugins\/pepper_file_ref.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_instance.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/plugins\/pepper_resource_tracker.h\"\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Module module_id) {\n PluginModule* module = PluginModule::FromPPModule(module_id);\n if (!module)\n return 0;\n\n FileIO* file_io = new FileIO(module);\n return file_io->GetReference();\n}\n\nbool IsFileIO(PP_Resource resource) {\n return !!Resource::GetAs<FileIO>(resource);\n}\n\nint32_t Open(PP_Resource file_io_id,\n PP_Resource file_ref_id,\n int32_t open_flags,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n\n scoped_refptr<FileRef> file_ref(Resource::GetAs<FileRef>(file_ref_id));\n if (!file_ref)\n return PP_ERROR_BADRESOURCE;\n\n return file_io->Open(file_ref, open_flags, callback);\n}\n\nint32_t Query(PP_Resource file_io_id,\n PP_FileInfo_Dev* info,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Query(info, callback);\n}\n\nint32_t Touch(PP_Resource file_io_id,\n PP_Time last_access_time,\n PP_Time last_modified_time,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Touch(last_access_time, last_modified_time, callback);\n}\n\nint32_t Read(PP_Resource file_io_id,\n int64_t offset,\n char* buffer,\n int32_t bytes_to_read,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Read(offset, buffer, bytes_to_read, callback);\n}\n\nint32_t Write(PP_Resource file_io_id,\n int64_t offset,\n const char* buffer,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Write(offset, buffer, bytes_to_write, callback);\n}\n\nint32_t SetLength(PP_Resource file_io_id,\n int64_t length,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->SetLength(length, callback);\n}\n\nint32_t Flush(PP_Resource file_io_id,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->Flush(callback);\n}\n\nvoid Close(PP_Resource file_io_id) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return;\n file_io->Close();\n}\n\nconst PPB_FileIO_Dev ppb_fileio = {\n &Create,\n &IsFileIO,\n &Open,\n &Query,\n &Touch,\n &Read,\n &Write,\n &SetLength,\n &Flush,\n &Close\n};\n\nint32_t GetOSFileDescriptor(PP_Resource file_io_id) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->GetOSFileDescriptor();\n}\n\nint32_t WillWrite(PP_Resource file_io_id,\n int64_t offset,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->WillWrite(offset, bytes_to_write, callback);\n}\n\nint32_t WillSetLength(PP_Resource file_io_id,\n int64_t length,\n PP_CompletionCallback callback) {\n scoped_refptr<FileIO> file_io(Resource::GetAs<FileIO>(file_io_id));\n if (!file_io)\n return PP_ERROR_BADRESOURCE;\n return file_io->WillSetLength(length, callback);\n}\n\nconst PPB_FileIOTrusted_Dev ppb_fileiotrusted = {\n &GetOSFileDescriptor,\n &WillWrite,\n &WillSetLength\n};\n\nint PlatformFileErrorToPepperError(base::PlatformFileError error_code) {\n switch (error_code) {\n case base::PLATFORM_FILE_OK:\n return PP_OK;\n case base::PLATFORM_FILE_ERROR_EXISTS:\n return PP_ERROR_FILEEXISTS;\n case base::PLATFORM_FILE_ERROR_NOT_FOUND:\n return PP_ERROR_FILENOTFOUND;\n case base::PLATFORM_FILE_ERROR_ACCESS_DENIED:\n return PP_ERROR_NOACCESS;\n case base::PLATFORM_FILE_ERROR_NO_MEMORY:\n return PP_ERROR_NOMEMORY;\n case base::PLATFORM_FILE_ERROR_NO_SPACE:\n return PP_ERROR_NOSPACE;\n case base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY:\n NOTREACHED();\n return PP_ERROR_FAILED;\n default:\n return PP_ERROR_FAILED;\n }\n}\n\n} \/\/ namespace\n\nFileIO::FileIO(PluginModule* module)\n : Resource(module),\n delegate_(module->GetSomeInstance()->delegate()),\n ALLOW_THIS_IN_INITIALIZER_LIST(callback_factory_(this)),\n file_(base::kInvalidPlatformFileValue),\n callback_(),\n info_(NULL) {\n}\n\nFileIO::~FileIO() {\n Close();\n}\n\n\/\/ static\nconst PPB_FileIO_Dev* FileIO::GetInterface() {\n return &ppb_fileio;\n}\n\n\/\/ static\nconst PPB_FileIOTrusted_Dev* FileIO::GetTrustedInterface() {\n return &ppb_fileiotrusted;\n}\n\nint32_t FileIO::Open(FileRef* file_ref,\n int32_t open_flags,\n PP_CompletionCallback callback) {\n if (file_ != base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n int flags = 0;\n if (open_flags & PP_FILEOPENFLAG_READ)\n flags |= base::PLATFORM_FILE_READ;\n if (open_flags & PP_FILEOPENFLAG_WRITE) {\n flags |= base::PLATFORM_FILE_WRITE;\n flags |= base::PLATFORM_FILE_WRITE_ATTRIBUTES;\n }\n if (open_flags & PP_FILEOPENFLAG_TRUNCATE) {\n DCHECK(flags & PP_FILEOPENFLAG_WRITE);\n flags |= base::PLATFORM_FILE_TRUNCATE;\n }\n\n if (open_flags & PP_FILEOPENFLAG_CREATE) {\n if (open_flags & PP_FILEOPENFLAG_EXCLUSIVE)\n flags |= base::PLATFORM_FILE_CREATE;\n else\n flags |= base::PLATFORM_FILE_OPEN_ALWAYS;\n } else\n flags |= base::PLATFORM_FILE_OPEN;\n\n file_system_type_ = file_ref->file_system_type();\n if (!delegate_->AsyncOpenFile(\n file_ref->system_path(), flags,\n callback_factory_.NewCallback(&FileIO::AsyncOpenFileCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Query(PP_FileInfo_Dev* info,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n DCHECK(!info_);\n DCHECK(info);\n info_ = info;\n\n if (!base::FileUtilProxy::GetFileInfoFromPlatformFile(\n delegate_->GetFileThreadMessageLoopProxy(), file_,\n callback_factory_.NewCallback(&FileIO::QueryInfoCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Touch(PP_Time last_access_time,\n PP_Time last_modified_time,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Touch(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, base::Time::FromDoubleT(last_access_time),\n base::Time::FromDoubleT(last_modified_time),\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Read(int64_t offset,\n char* buffer,\n int32_t bytes_to_read,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Read(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, offset, buffer, bytes_to_read,\n callback_factory_.NewCallback(&FileIO::ReadWriteCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Write(int64_t offset,\n const char* buffer,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Write(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, offset, buffer, bytes_to_write,\n callback_factory_.NewCallback(&FileIO::ReadWriteCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::SetLength(int64_t length,\n PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Truncate(\n delegate_->GetFileThreadMessageLoopProxy(),\n file_, length,\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nint32_t FileIO::Flush(PP_CompletionCallback callback) {\n if (file_ == base::kInvalidPlatformFileValue)\n return PP_ERROR_FAILED;\n\n DCHECK(!callback_.func);\n callback_ = callback;\n\n if (!base::FileUtilProxy::Flush(\n delegate_->GetFileThreadMessageLoopProxy(), file_,\n callback_factory_.NewCallback(&FileIO::StatusCallback)))\n return PP_ERROR_FAILED;\n\n return PP_ERROR_WOULDBLOCK;\n}\n\nvoid FileIO::Close() {\n if (file_ != base::kInvalidPlatformFileValue)\n base::FileUtilProxy::Close(\n delegate_->GetFileThreadMessageLoopProxy(), file_, NULL);\n}\n\nint32_t FileIO::GetOSFileDescriptor() {\n#if defined(OS_POSIX)\n return file_;\n#else\n return reinterpret_cast<uintptr_t>(file_);\n#endif\n}\n\nint32_t FileIO::WillWrite(int64_t offset,\n int32_t bytes_to_write,\n PP_CompletionCallback callback) {\n \/\/ TODO(dumi): implement me\n return PP_OK;\n}\n\nint32_t FileIO::WillSetLength(int64_t length,\n PP_CompletionCallback callback) {\n \/\/ TODO(dumi): implement me\n return PP_OK;\n}\n\nvoid FileIO::RunPendingCallback(int result) {\n if (!callback_.func)\n return;\n\n PP_CompletionCallback callback = {0};\n std::swap(callback, callback_);\n PP_RunCompletionCallback(&callback, result);\n}\n\nvoid FileIO::StatusCallback(base::PlatformFileError error_code) {\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::AsyncOpenFileCallback(base::PlatformFileError error_code,\n base::PlatformFile file) {\n DCHECK(file_ == base::kInvalidPlatformFileValue);\n file_ = file;\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::QueryInfoCallback(base::PlatformFileError error_code,\n const base::PlatformFileInfo& file_info) {\n DCHECK(info_);\n if (error_code == base::PLATFORM_FILE_OK) {\n info_->size = file_info.size;\n info_->creation_time = file_info.creation_time.ToDoubleT();\n info_->last_access_time = file_info.last_accessed.ToDoubleT();\n info_->last_modified_time = file_info.last_modified.ToDoubleT();\n info_->system_type = file_system_type_;\n if (file_info.is_directory)\n info_->type = PP_FILETYPE_DIRECTORY;\n else\n info_->type = PP_FILETYPE_REGULAR;\n }\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n}\n\nvoid FileIO::ReadWriteCallback(base::PlatformFileError error_code,\n int bytes_read_or_written) {\n if (error_code != base::PLATFORM_FILE_OK)\n RunPendingCallback(PlatformFileErrorToPepperError(error_code));\n else\n RunPendingCallback(bytes_read_or_written);\n}\n\n} \/\/ namespace pepper\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Kuzma Shapran <kuzma.shapran@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"lxqtsysstatconfiguration.h\"\n#include \"ui_lxqtsysstatconfiguration.h\"\n#include \"lxqtsysstatutils.h\"\n#include \"lxqtsysstatcolours.h\"\n\n#include <SysStat\/CpuStat>\n#include <SysStat\/MemStat>\n#include <SysStat\/NetStat>\n\n\/\/Note: strings can't actually be translated here (in static initialization time)\n\/\/ the QT_TR_NOOP here is just for qt translate tools to get the strings for translation\nconst QStringList LxQtSysStatConfiguration::msStatTypes = {\n QStringLiteral(QT_TR_NOOP(\"CPU\"))\n , QStringLiteral(QT_TR_NOOP(\"Memory\"))\n , QStringLiteral(QT_TR_NOOP(\"Network\"))\n};\n\nnamespace\n{\n \/\/Note: workaround for making source strings translatable\n \/\/ (no need to ever call this function)\n void localizationWorkaround();\n auto t = localizationWorkaround;\/\/avoid unused function warning\n void localizationWorkaround()\n {\n const char * loc;\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu1\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu2\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu3\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu4\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu5\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu6\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu7\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu8\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu9\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu11\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu12\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu13\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu14\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu15\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu16\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu17\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu18\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu19\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu20\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu21\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu22\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu23\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu24\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"memory\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"swap\");\n static_cast<void>(t);\/\/avoid unused variable warning\n }\n}\n\nLxQtSysStatConfiguration::LxQtSysStatConfiguration(QSettings *settings, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::LxQtSysStatConfiguration),\n mSettings(settings),\n oldSettings(settings),\n mStat(NULL),\n mColoursDialog(NULL)\n{\n setAttribute(Qt::WA_DeleteOnClose);\n setObjectName(\"SysStatConfigurationWindow\");\n ui->setupUi(this);\n\n \/\/Note: translation is needed here in runtime (translator is attached already)\n for (auto const & type : msStatTypes)\n ui->typeCOB->addItem(tr(type.toStdString().c_str()), type);\n\n loadSettings();\n\n connect(ui->typeCOB, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->intervalSB, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->sizeSB, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->linesSB, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->titleLE, &QLineEdit::editingFinished, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->useFrequencyCB, &QCheckBox::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->logarithmicCB, &QCheckBox::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->sourceCOB, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->useThemeColoursRB, &QRadioButton::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n}\n\nLxQtSysStatConfiguration::~LxQtSysStatConfiguration()\n{\n delete ui;\n}\n\nvoid LxQtSysStatConfiguration::loadSettings()\n{\n ui->intervalSB->setValue(mSettings->value(\"graph\/updateInterval\", 1.0).toDouble());\n ui->sizeSB->setValue(mSettings->value(\"graph\/minimalSize\", 30).toInt());\n\n ui->linesSB->setValue(mSettings->value(\"grid\/lines\", 1).toInt());\n\n ui->titleLE->setText(mSettings->value(\"title\/label\", QString()).toString());\n\n int typeIndex = ui->typeCOB->findData(mSettings->value(\"data\/type\", msStatTypes[0]));\n ui->typeCOB->setCurrentIndex((typeIndex >= 0) ? typeIndex : 0);\n on_typeCOB_currentIndexChanged(ui->typeCOB->currentIndex());\n\n int sourceIndex = ui->sourceCOB->findText(mSettings->value(\"data\/source\", QString()).toString());\n ui->sourceCOB->setCurrentIndex((sourceIndex >= 0) ? sourceIndex : 0);\n\n ui->useFrequencyCB->setChecked(mSettings->value(\"cpu\/useFrequency\", true).toBool());\n ui->maximumHS->setValue(PluginSysStat::netSpeedFromString(mSettings->value(\"net\/maximumSpeed\", \"1 MB\/s\").toString()));\n on_maximumHS_valueChanged(ui->maximumHS->value());\n ui->logarithmicCB->setChecked(mSettings->value(\"net\/logarithmicScale\", true).toBool());\n ui->logScaleSB->setValue(mSettings->value(\"net\/logarithmicScaleSteps\", 4).toInt());\n\n bool useThemeColours = mSettings->value(\"graph\/useThemeColours\", true).toBool();\n ui->useThemeColoursRB->setChecked(useThemeColours);\n ui->useCustomColoursRB->setChecked(!useThemeColours);\n ui->customColoursB->setEnabled(!useThemeColours);\n}\n\nvoid LxQtSysStatConfiguration::saveSettings()\n{\n mSettings->setValue(\"graph\/useThemeColours\", ui->useThemeColoursRB->isChecked());\n mSettings->setValue(\"graph\/updateInterval\", ui->intervalSB->value());\n mSettings->setValue(\"graph\/minimalSize\", ui->sizeSB->value());\n\n mSettings->setValue(\"grid\/lines\", ui->linesSB->value());\n\n mSettings->setValue(\"title\/label\", ui->titleLE->text());\n\n \/\/Note:\n \/\/ need to make a realy deep copy of the msStatTypes[x] because of SEGFAULTs\n \/\/ occuring in static finalization time (don't know the real reason...maybe ordering of static finalizers\/destructors)\n QString type = ui->typeCOB->itemData(ui->typeCOB->currentIndex(), Qt::UserRole).toString().toStdString().c_str();\n mSettings->setValue(\"data\/type\", type);\n mSettings->setValue(\"data\/source\", ui->sourceCOB->currentText());\n\n mSettings->setValue(\"cpu\/useFrequency\", ui->useFrequencyCB->isChecked());\n\n mSettings->setValue(\"net\/maximumSpeed\", PluginSysStat::netSpeedToString(ui->maximumHS->value()));\n mSettings->setValue(\"net\/logarithmicScale\", ui->logarithmicCB->isChecked());\n mSettings->setValue(\"net\/logarithmicScaleSteps\", ui->logScaleSB->value());\n}\n\nvoid LxQtSysStatConfiguration::on_buttons_clicked(QAbstractButton *btn)\n{\n if (ui->buttons->buttonRole(btn) == QDialogButtonBox::ResetRole)\n {\n oldSettings.loadToSettings();\n loadSettings();\n }\n else\n close();\n}\n\nvoid LxQtSysStatConfiguration::on_typeCOB_currentIndexChanged(int index)\n{\n if (mStat)\n mStat->deleteLater();\n switch (index)\n {\n case 0:\n mStat = new SysStat::CpuStat(this);\n break;\n\n case 1:\n mStat = new SysStat::MemStat(this);\n break;\n\n case 2:\n mStat = new SysStat::NetStat(this);\n break;\n }\n\n ui->sourceCOB->blockSignals(true);\n ui->sourceCOB->clear();\n for (auto const & s : mStat->sources())\n ui->sourceCOB->addItem(tr(s.toStdString().c_str()));\n ui->sourceCOB->blockSignals(false);\n ui->sourceCOB->setCurrentIndex(0);\n}\n\nvoid LxQtSysStatConfiguration::on_maximumHS_valueChanged(int value)\n{\n ui->maximumValueL->setText(PluginSysStat::netSpeedToString(value));\n}\n\nvoid LxQtSysStatConfiguration::coloursChanged()\n{\n const LxQtSysStatColours::Colours &colours = mColoursDialog->colours();\n\n mSettings->setValue(\"grid\/colour\", colours[\"grid\"].name());\n mSettings->setValue(\"title\/colour\", colours[\"title\"].name());\n\n mSettings->setValue(\"cpu\/systemColour\", colours[\"cpuSystem\"].name());\n mSettings->setValue(\"cpu\/userColour\", colours[\"cpuUser\"].name());\n mSettings->setValue(\"cpu\/niceColour\", colours[\"cpuNice\"].name());\n mSettings->setValue(\"cpu\/otherColour\", colours[\"cpuOther\"].name());\n mSettings->setValue(\"cpu\/frequencyColour\", colours[\"cpuFrequency\"].name());\n\n mSettings->setValue(\"mem\/appsColour\", colours[\"memApps\"].name());\n mSettings->setValue(\"mem\/buffersColour\", colours[\"memBuffers\"].name());\n mSettings->setValue(\"mem\/cachedColour\", colours[\"memCached\"].name());\n mSettings->setValue(\"mem\/swapColour\", colours[\"memSwap\"].name());\n\n mSettings->setValue(\"net\/receivedColour\", colours[\"netReceived\"].name());\n mSettings->setValue(\"net\/transmittedColour\", colours[\"netTransmitted\"].name());\n}\n\nvoid LxQtSysStatConfiguration::on_customColoursB_clicked()\n{\n if (!mColoursDialog)\n {\n mColoursDialog = new LxQtSysStatColours(this);\n connect(mColoursDialog, SIGNAL(coloursChanged()), SLOT(coloursChanged()));\n }\n\n LxQtSysStatColours::Colours colours;\n\n const LxQtSysStatColours::Colours &defaultColours = mColoursDialog->defaultColours();\n\n colours[\"grid\"] = QColor(mSettings->value(\"grid\/colour\", defaultColours[\"grid\"] .name()).toString());\n colours[\"title\"] = QColor(mSettings->value(\"title\/colour\", defaultColours[\"title\"].name()).toString());\n\n colours[\"cpuSystem\"] = QColor(mSettings->value(\"cpu\/systemColour\", defaultColours[\"cpuSystem\"] .name()).toString());\n colours[\"cpuUser\"] = QColor(mSettings->value(\"cpu\/userColour\", defaultColours[\"cpuUser\"] .name()).toString());\n colours[\"cpuNice\"] = QColor(mSettings->value(\"cpu\/niceColour\", defaultColours[\"cpuNice\"] .name()).toString());\n colours[\"cpuOther\"] = QColor(mSettings->value(\"cpu\/otherColour\", defaultColours[\"cpuOther\"] .name()).toString());\n colours[\"cpuFrequency\"] = QColor(mSettings->value(\"cpu\/frequencyColour\", defaultColours[\"cpuFrequency\"].name()).toString());\n\n colours[\"memApps\"] = QColor(mSettings->value(\"mem\/appsColour\", defaultColours[\"memApps\"] .name()).toString());\n colours[\"memBuffers\"] = QColor(mSettings->value(\"mem\/buffersColour\", defaultColours[\"memBuffers\"].name()).toString());\n colours[\"memCached\"] = QColor(mSettings->value(\"mem\/cachedColour\", defaultColours[\"memCached\"] .name()).toString());\n colours[\"memSwap\"] = QColor(mSettings->value(\"mem\/swapColour\", defaultColours[\"memSwap\"] .name()).toString());\n\n colours[\"netReceived\"] = QColor(mSettings->value(\"net\/receivedColour\", defaultColours[\"netReceived\"] .name()).toString());\n colours[\"netTransmitted\"] = QColor(mSettings->value(\"net\/transmittedColour\", defaultColours[\"netTransmitted\"].name()).toString());\n\n mColoursDialog->setColours(colours);\n\n mColoursDialog->exec();\n}\n<commit_msg>plugin-sysstat: fix for source strings translation<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Kuzma Shapran <kuzma.shapran@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"lxqtsysstatconfiguration.h\"\n#include \"ui_lxqtsysstatconfiguration.h\"\n#include \"lxqtsysstatutils.h\"\n#include \"lxqtsysstatcolours.h\"\n\n#include <SysStat\/CpuStat>\n#include <SysStat\/MemStat>\n#include <SysStat\/NetStat>\n\n\/\/Note: strings can't actually be translated here (in static initialization time)\n\/\/ the QT_TR_NOOP here is just for qt translate tools to get the strings for translation\nconst QStringList LxQtSysStatConfiguration::msStatTypes = {\n QStringLiteral(QT_TR_NOOP(\"CPU\"))\n , QStringLiteral(QT_TR_NOOP(\"Memory\"))\n , QStringLiteral(QT_TR_NOOP(\"Network\"))\n};\n\nnamespace\n{\n \/\/Note: workaround for making source strings translatable\n \/\/ (no need to ever call this function)\n void localizationWorkaround();\n auto t = localizationWorkaround;\/\/avoid unused function warning\n void localizationWorkaround()\n {\n const char * loc;\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu1\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu2\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu3\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu4\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu5\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu6\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu7\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu8\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu9\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu11\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu12\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu13\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu14\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu15\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu16\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu17\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu18\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu19\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu20\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu21\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu22\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu23\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"cpu24\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"memory\");\n loc = QT_TRANSLATE_NOOP(\"LxQtSysStatConfiguration\", \"swap\");\n static_cast<void>(t);\/\/avoid unused variable warning\n }\n}\n\nLxQtSysStatConfiguration::LxQtSysStatConfiguration(QSettings *settings, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::LxQtSysStatConfiguration),\n mSettings(settings),\n oldSettings(settings),\n mStat(NULL),\n mColoursDialog(NULL)\n{\n setAttribute(Qt::WA_DeleteOnClose);\n setObjectName(\"SysStatConfigurationWindow\");\n ui->setupUi(this);\n\n \/\/Note: translation is needed here in runtime (translator is attached already)\n for (auto const & type : msStatTypes)\n ui->typeCOB->addItem(tr(type.toStdString().c_str()), type);\n\n loadSettings();\n\n connect(ui->typeCOB, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->intervalSB, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->sizeSB, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->linesSB, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->titleLE, &QLineEdit::editingFinished, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->useFrequencyCB, &QCheckBox::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->logarithmicCB, &QCheckBox::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->sourceCOB, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &LxQtSysStatConfiguration::saveSettings);\n connect(ui->useThemeColoursRB, &QRadioButton::toggled, this, &LxQtSysStatConfiguration::saveSettings);\n}\n\nLxQtSysStatConfiguration::~LxQtSysStatConfiguration()\n{\n delete ui;\n}\n\nvoid LxQtSysStatConfiguration::loadSettings()\n{\n ui->intervalSB->setValue(mSettings->value(\"graph\/updateInterval\", 1.0).toDouble());\n ui->sizeSB->setValue(mSettings->value(\"graph\/minimalSize\", 30).toInt());\n\n ui->linesSB->setValue(mSettings->value(\"grid\/lines\", 1).toInt());\n\n ui->titleLE->setText(mSettings->value(\"title\/label\", QString()).toString());\n\n int typeIndex = ui->typeCOB->findData(mSettings->value(\"data\/type\", msStatTypes[0]));\n ui->typeCOB->setCurrentIndex((typeIndex >= 0) ? typeIndex : 0);\n on_typeCOB_currentIndexChanged(ui->typeCOB->currentIndex());\n\n int sourceIndex = ui->sourceCOB->findData(mSettings->value(\"data\/source\", QString()));\n ui->sourceCOB->setCurrentIndex((sourceIndex >= 0) ? sourceIndex : 0);\n\n ui->useFrequencyCB->setChecked(mSettings->value(\"cpu\/useFrequency\", true).toBool());\n ui->maximumHS->setValue(PluginSysStat::netSpeedFromString(mSettings->value(\"net\/maximumSpeed\", \"1 MB\/s\").toString()));\n on_maximumHS_valueChanged(ui->maximumHS->value());\n ui->logarithmicCB->setChecked(mSettings->value(\"net\/logarithmicScale\", true).toBool());\n ui->logScaleSB->setValue(mSettings->value(\"net\/logarithmicScaleSteps\", 4).toInt());\n\n bool useThemeColours = mSettings->value(\"graph\/useThemeColours\", true).toBool();\n ui->useThemeColoursRB->setChecked(useThemeColours);\n ui->useCustomColoursRB->setChecked(!useThemeColours);\n ui->customColoursB->setEnabled(!useThemeColours);\n}\n\nvoid LxQtSysStatConfiguration::saveSettings()\n{\n mSettings->setValue(\"graph\/useThemeColours\", ui->useThemeColoursRB->isChecked());\n mSettings->setValue(\"graph\/updateInterval\", ui->intervalSB->value());\n mSettings->setValue(\"graph\/minimalSize\", ui->sizeSB->value());\n\n mSettings->setValue(\"grid\/lines\", ui->linesSB->value());\n\n mSettings->setValue(\"title\/label\", ui->titleLE->text());\n\n \/\/Note:\n \/\/ need to make a realy deep copy of the msStatTypes[x] because of SEGFAULTs\n \/\/ occuring in static finalization time (don't know the real reason...maybe ordering of static finalizers\/destructors)\n QString type = ui->typeCOB->itemData(ui->typeCOB->currentIndex(), Qt::UserRole).toString().toStdString().c_str();\n mSettings->setValue(\"data\/type\", type);\n mSettings->setValue(\"data\/source\", ui->sourceCOB->itemData(ui->sourceCOB->currentIndex(), Qt::UserRole));\n\n mSettings->setValue(\"cpu\/useFrequency\", ui->useFrequencyCB->isChecked());\n\n mSettings->setValue(\"net\/maximumSpeed\", PluginSysStat::netSpeedToString(ui->maximumHS->value()));\n mSettings->setValue(\"net\/logarithmicScale\", ui->logarithmicCB->isChecked());\n mSettings->setValue(\"net\/logarithmicScaleSteps\", ui->logScaleSB->value());\n}\n\nvoid LxQtSysStatConfiguration::on_buttons_clicked(QAbstractButton *btn)\n{\n if (ui->buttons->buttonRole(btn) == QDialogButtonBox::ResetRole)\n {\n oldSettings.loadToSettings();\n loadSettings();\n }\n else\n close();\n}\n\nvoid LxQtSysStatConfiguration::on_typeCOB_currentIndexChanged(int index)\n{\n if (mStat)\n mStat->deleteLater();\n switch (index)\n {\n case 0:\n mStat = new SysStat::CpuStat(this);\n break;\n\n case 1:\n mStat = new SysStat::MemStat(this);\n break;\n\n case 2:\n mStat = new SysStat::NetStat(this);\n break;\n }\n\n ui->sourceCOB->blockSignals(true);\n ui->sourceCOB->clear();\n for (auto const & s : mStat->sources())\n ui->sourceCOB->addItem(tr(s.toStdString().c_str()), s);\n ui->sourceCOB->blockSignals(false);\n ui->sourceCOB->setCurrentIndex(0);\n}\n\nvoid LxQtSysStatConfiguration::on_maximumHS_valueChanged(int value)\n{\n ui->maximumValueL->setText(PluginSysStat::netSpeedToString(value));\n}\n\nvoid LxQtSysStatConfiguration::coloursChanged()\n{\n const LxQtSysStatColours::Colours &colours = mColoursDialog->colours();\n\n mSettings->setValue(\"grid\/colour\", colours[\"grid\"].name());\n mSettings->setValue(\"title\/colour\", colours[\"title\"].name());\n\n mSettings->setValue(\"cpu\/systemColour\", colours[\"cpuSystem\"].name());\n mSettings->setValue(\"cpu\/userColour\", colours[\"cpuUser\"].name());\n mSettings->setValue(\"cpu\/niceColour\", colours[\"cpuNice\"].name());\n mSettings->setValue(\"cpu\/otherColour\", colours[\"cpuOther\"].name());\n mSettings->setValue(\"cpu\/frequencyColour\", colours[\"cpuFrequency\"].name());\n\n mSettings->setValue(\"mem\/appsColour\", colours[\"memApps\"].name());\n mSettings->setValue(\"mem\/buffersColour\", colours[\"memBuffers\"].name());\n mSettings->setValue(\"mem\/cachedColour\", colours[\"memCached\"].name());\n mSettings->setValue(\"mem\/swapColour\", colours[\"memSwap\"].name());\n\n mSettings->setValue(\"net\/receivedColour\", colours[\"netReceived\"].name());\n mSettings->setValue(\"net\/transmittedColour\", colours[\"netTransmitted\"].name());\n}\n\nvoid LxQtSysStatConfiguration::on_customColoursB_clicked()\n{\n if (!mColoursDialog)\n {\n mColoursDialog = new LxQtSysStatColours(this);\n connect(mColoursDialog, SIGNAL(coloursChanged()), SLOT(coloursChanged()));\n }\n\n LxQtSysStatColours::Colours colours;\n\n const LxQtSysStatColours::Colours &defaultColours = mColoursDialog->defaultColours();\n\n colours[\"grid\"] = QColor(mSettings->value(\"grid\/colour\", defaultColours[\"grid\"] .name()).toString());\n colours[\"title\"] = QColor(mSettings->value(\"title\/colour\", defaultColours[\"title\"].name()).toString());\n\n colours[\"cpuSystem\"] = QColor(mSettings->value(\"cpu\/systemColour\", defaultColours[\"cpuSystem\"] .name()).toString());\n colours[\"cpuUser\"] = QColor(mSettings->value(\"cpu\/userColour\", defaultColours[\"cpuUser\"] .name()).toString());\n colours[\"cpuNice\"] = QColor(mSettings->value(\"cpu\/niceColour\", defaultColours[\"cpuNice\"] .name()).toString());\n colours[\"cpuOther\"] = QColor(mSettings->value(\"cpu\/otherColour\", defaultColours[\"cpuOther\"] .name()).toString());\n colours[\"cpuFrequency\"] = QColor(mSettings->value(\"cpu\/frequencyColour\", defaultColours[\"cpuFrequency\"].name()).toString());\n\n colours[\"memApps\"] = QColor(mSettings->value(\"mem\/appsColour\", defaultColours[\"memApps\"] .name()).toString());\n colours[\"memBuffers\"] = QColor(mSettings->value(\"mem\/buffersColour\", defaultColours[\"memBuffers\"].name()).toString());\n colours[\"memCached\"] = QColor(mSettings->value(\"mem\/cachedColour\", defaultColours[\"memCached\"] .name()).toString());\n colours[\"memSwap\"] = QColor(mSettings->value(\"mem\/swapColour\", defaultColours[\"memSwap\"] .name()).toString());\n\n colours[\"netReceived\"] = QColor(mSettings->value(\"net\/receivedColour\", defaultColours[\"netReceived\"] .name()).toString());\n colours[\"netTransmitted\"] = QColor(mSettings->value(\"net\/transmittedColour\", defaultColours[\"netTransmitted\"].name()).toString());\n\n mColoursDialog->setColours(colours);\n\n mColoursDialog->exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"VkFramebuffer.hpp\"\n\n#include \"VkImageView.hpp\"\n#include \"VkRenderPass.hpp\"\n#include \"VkStringify.hpp\"\n\n#include <memory.h>\n#include <algorithm>\n\nnamespace vk {\n\nFramebuffer::Framebuffer(const VkFramebufferCreateInfo *pCreateInfo, void *mem)\n : attachments(reinterpret_cast<ImageView **>(mem))\n , extent{ pCreateInfo->width, pCreateInfo->height, pCreateInfo->layers }\n{\n\tconst VkBaseInStructure *curInfo = reinterpret_cast<const VkBaseInStructure *>(pCreateInfo->pNext);\n\tconst VkFramebufferAttachmentsCreateInfo *attachmentsCreateInfo = nullptr;\n\twhile(curInfo)\n\t{\n\t\tswitch(curInfo->sType)\n\t\t{\n\t\tcase VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO:\n\t\t\tattachmentsCreateInfo = reinterpret_cast<const VkFramebufferAttachmentsCreateInfo *>(curInfo);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLOG_TRAP(\"pFramebufferCreateInfo->pNext->sType = %s\", vk::Stringify(curInfo->sType).c_str());\n\t\t\tbreak;\n\t\t}\n\t\tcurInfo = curInfo->pNext;\n\t}\n\n\tif(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)\n\t{\n\t\t\/\/ If flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT, the pNext chain **must**\n\t\t\/\/ include a VkFramebufferAttachmentsCreateInfo.\n\t\tASSERT(attachmentsCreateInfo != nullptr);\n\t\tattachmentCount = attachmentsCreateInfo->attachmentImageInfoCount;\n\t\tfor(uint32_t i = 0; i < attachmentCount; i++)\n\t\t{\n\t\t\tattachments[i] = nullptr;\n\t\t}\n\t}\n\telse\n\t{\n\t\tattachmentCount = pCreateInfo->attachmentCount;\n\t\tfor(uint32_t i = 0; i < attachmentCount; i++)\n\t\t{\n\t\t\tattachments[i] = vk::Cast(pCreateInfo->pAttachments[i]);\n\t\t}\n\t}\n}\n\nvoid Framebuffer::destroy(const VkAllocationCallbacks *pAllocator)\n{\n\tvk::deallocate(attachments, pAllocator);\n}\n\nvoid Framebuffer::executeLoadOp(const RenderPass *renderPass, uint32_t clearValueCount, const VkClearValue *pClearValues, const VkRect2D &renderArea)\n{\n\t\/\/ This gets called at the start of a renderpass. Logically the `loadOp` gets executed at the\n\t\/\/ subpass where an attachment is first used, but since we don't discard contents between subpasses,\n\t\/\/ we can execute it sooner. Only clear operations have an effect.\n\n\tASSERT(attachmentCount == renderPass->getAttachmentCount());\n\n\tconst uint32_t count = std::min(clearValueCount, attachmentCount);\n\tfor(uint32_t i = 0; i < count; i++)\n\t{\n\t\tconst VkAttachmentDescription attachment = renderPass->getAttachment(i);\n\t\tVkImageAspectFlags aspectMask = Format(attachment.format).getAspects();\n\n\t\tswitch(attachment.loadOp)\n\t\t{\n\t\tcase VK_ATTACHMENT_LOAD_OP_CLEAR:\n\t\t\t\/\/ Keep the color aspect for clearing.\n\t\t\tbreak;\n\t\tcase VK_ATTACHMENT_LOAD_OP_LOAD:\n\t\tcase VK_ATTACHMENT_LOAD_OP_DONT_CARE:\n\t\t\t\/\/ Don't clear the attachment's color aspect.\n\t\t\taspectMask &= VK_IMAGE_ASPECT_STENCIL_BIT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tUNSUPPORTED(\"attachment.loadOp %d\", attachment.loadOp);\n\t\t}\n\n\t\tswitch(attachment.stencilLoadOp)\n\t\t{\n\t\tcase VK_ATTACHMENT_LOAD_OP_CLEAR:\n\t\t\t\/\/ Keep the stencil aspect for clearing.\n\t\t\tbreak;\n\t\tcase VK_ATTACHMENT_LOAD_OP_LOAD:\n\t\tcase VK_ATTACHMENT_LOAD_OP_DONT_CARE:\n\t\t\t\/\/ Don't clear the attachment's stencil aspect.\n\t\t\taspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tUNSUPPORTED(\"attachment.stencilLoadOp %d\", attachment.stencilLoadOp);\n\t\t}\n\n\t\tif(!aspectMask || !renderPass->isAttachmentUsed(i))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(renderPass->isMultiView())\n\t\t{\n\t\t\tattachments[i]->clearWithLayerMask(pClearValues[i], aspectMask, renderArea,\n\t\t\t renderPass->getAttachmentViewMask(i));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tattachments[i]->clear(pClearValues[i], aspectMask, renderArea);\n\t\t}\n\t}\n}\n\nvoid Framebuffer::clearAttachment(const RenderPass *renderPass, uint32_t subpassIndex, const VkClearAttachment &attachment, const VkClearRect &rect)\n{\n\tVkSubpassDescription subpass = renderPass->getSubpass(subpassIndex);\n\n\tif(attachment.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT)\n\t{\n\t\tASSERT(attachment.colorAttachment < subpass.colorAttachmentCount);\n\t\tuint32_t attachmentIndex = subpass.pColorAttachments[attachment.colorAttachment].attachment;\n\n\t\tif(attachmentIndex != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tASSERT(attachmentIndex < attachmentCount);\n\t\t\tImageView *imageView = attachments[attachmentIndex];\n\n\t\t\tif(renderPass->isMultiView())\n\t\t\t{\n\t\t\t\timageView->clearWithLayerMask(attachment.clearValue, attachment.aspectMask, rect.rect,\n\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\timageView->clear(attachment.clearValue, attachment.aspectMask, rect);\n\t\t\t}\n\t\t}\n\t}\n\telse if(attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))\n\t{\n\t\tuint32_t attachmentIndex = subpass.pDepthStencilAttachment->attachment;\n\n\t\tif(attachmentIndex != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tASSERT(attachmentIndex < attachmentCount);\n\t\t\tImageView *imageView = attachments[attachmentIndex];\n\n\t\t\tif(renderPass->isMultiView())\n\t\t\t{\n\t\t\t\timageView->clearWithLayerMask(attachment.clearValue, attachment.aspectMask, rect.rect,\n\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\timageView->clear(attachment.clearValue, attachment.aspectMask, rect);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Framebuffer::setAttachment(ImageView *imageView, uint32_t index)\n{\n\tASSERT(index < attachmentCount);\n\tASSERT(attachments[index] == nullptr);\n\tattachments[index] = imageView;\n}\n\nImageView *Framebuffer::getAttachment(uint32_t index) const\n{\n\treturn attachments[index];\n}\n\nvoid Framebuffer::resolve(const RenderPass *renderPass, uint32_t subpassIndex)\n{\n\tauto const &subpass = renderPass->getSubpass(subpassIndex);\n\tif(subpass.pResolveAttachments)\n\t{\n\t\tfor(uint32_t i = 0; i < subpass.colorAttachmentCount; i++)\n\t\t{\n\t\t\tuint32_t resolveAttachment = subpass.pResolveAttachments[i].attachment;\n\t\t\tif(resolveAttachment != VK_ATTACHMENT_UNUSED)\n\t\t\t{\n\t\t\t\tImageView *imageView = attachments[subpass.pColorAttachments[i].attachment];\n\t\t\t\tif(renderPass->isMultiView())\n\t\t\t\t{\n\t\t\t\t\timageView->resolveWithLayerMask(attachments[resolveAttachment],\n\t\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\timageView->resolve(attachments[resolveAttachment]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(renderPass->hasDepthStencilResolve() && subpass.pDepthStencilAttachment != nullptr)\n\t{\n\t\tVkSubpassDescriptionDepthStencilResolve dsResolve = renderPass->getSubpassDepthStencilResolve(subpassIndex);\n\t\tuint32_t depthStencilAttachment = subpass.pDepthStencilAttachment->attachment;\n\t\tif(depthStencilAttachment != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tImageView *imageView = attachments[depthStencilAttachment];\n\t\t\timageView->resolveDepthStencil(attachments[dsResolve.pDepthStencilResolveAttachment->attachment], dsResolve);\n\t\t}\n\t}\n}\n\nsize_t Framebuffer::ComputeRequiredAllocationSize(const VkFramebufferCreateInfo *pCreateInfo)\n{\n\tconst VkBaseInStructure *curInfo = reinterpret_cast<const VkBaseInStructure *>(pCreateInfo->pNext);\n\tconst VkFramebufferAttachmentsCreateInfo *attachmentsInfo = nullptr;\n\twhile(curInfo)\n\t{\n\t\tswitch(curInfo->sType)\n\t\t{\n\t\tcase VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO:\n\t\t\tattachmentsInfo = reinterpret_cast<const VkFramebufferAttachmentsCreateInfo *>(curInfo);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLOG_TRAP(\"pFramebufferCreateInfo->pNext->sType = %s\", vk::Stringify(curInfo->sType).c_str());\n\t\t\tbreak;\n\t\t}\n\n\t\tcurInfo = curInfo->pNext;\n\t}\n\n\tif(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)\n\t{\n\t\tASSERT(attachmentsInfo != nullptr);\n\t\treturn attachmentsInfo->attachmentImageInfoCount * sizeof(void *);\n\t}\n\telse\n\t{\n\t\treturn pCreateInfo->attachmentCount * sizeof(void *);\n\t}\n}\n\n} \/\/ namespace vk\n<commit_msg>Refactor determining the aspects to clear<commit_after>\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"VkFramebuffer.hpp\"\n\n#include \"VkImageView.hpp\"\n#include \"VkRenderPass.hpp\"\n#include \"VkStringify.hpp\"\n\n#include <memory.h>\n#include <algorithm>\n\nnamespace vk {\n\nFramebuffer::Framebuffer(const VkFramebufferCreateInfo *pCreateInfo, void *mem)\n : attachments(reinterpret_cast<ImageView **>(mem))\n , extent{ pCreateInfo->width, pCreateInfo->height, pCreateInfo->layers }\n{\n\tconst VkBaseInStructure *curInfo = reinterpret_cast<const VkBaseInStructure *>(pCreateInfo->pNext);\n\tconst VkFramebufferAttachmentsCreateInfo *attachmentsCreateInfo = nullptr;\n\twhile(curInfo)\n\t{\n\t\tswitch(curInfo->sType)\n\t\t{\n\t\tcase VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO:\n\t\t\tattachmentsCreateInfo = reinterpret_cast<const VkFramebufferAttachmentsCreateInfo *>(curInfo);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLOG_TRAP(\"pFramebufferCreateInfo->pNext->sType = %s\", vk::Stringify(curInfo->sType).c_str());\n\t\t\tbreak;\n\t\t}\n\t\tcurInfo = curInfo->pNext;\n\t}\n\n\tif(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)\n\t{\n\t\t\/\/ If flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT, the pNext chain **must**\n\t\t\/\/ include a VkFramebufferAttachmentsCreateInfo.\n\t\tASSERT(attachmentsCreateInfo != nullptr);\n\t\tattachmentCount = attachmentsCreateInfo->attachmentImageInfoCount;\n\t\tfor(uint32_t i = 0; i < attachmentCount; i++)\n\t\t{\n\t\t\tattachments[i] = nullptr;\n\t\t}\n\t}\n\telse\n\t{\n\t\tattachmentCount = pCreateInfo->attachmentCount;\n\t\tfor(uint32_t i = 0; i < attachmentCount; i++)\n\t\t{\n\t\t\tattachments[i] = vk::Cast(pCreateInfo->pAttachments[i]);\n\t\t}\n\t}\n}\n\nvoid Framebuffer::destroy(const VkAllocationCallbacks *pAllocator)\n{\n\tvk::deallocate(attachments, pAllocator);\n}\n\nvoid Framebuffer::executeLoadOp(const RenderPass *renderPass, uint32_t clearValueCount, const VkClearValue *pClearValues, const VkRect2D &renderArea)\n{\n\t\/\/ This gets called at the start of a renderpass. Logically the `loadOp` gets executed at the\n\t\/\/ subpass where an attachment is first used, but since we don't discard contents between subpasses,\n\t\/\/ we can execute it sooner. Only clear operations have an effect.\n\n\tASSERT(attachmentCount == renderPass->getAttachmentCount());\n\n\tconst uint32_t count = std::min(clearValueCount, attachmentCount);\n\tfor(uint32_t i = 0; i < count; i++)\n\t{\n\t\tconst VkAttachmentDescription attachment = renderPass->getAttachment(i);\n\t\tVkImageAspectFlags clearMask = 0;\n\n\t\tswitch(attachment.loadOp)\n\t\t{\n\t\tcase VK_ATTACHMENT_LOAD_OP_CLEAR:\n\t\t\tclearMask |= VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT;\n\t\t\tbreak;\n\t\tcase VK_ATTACHMENT_LOAD_OP_LOAD:\n\t\tcase VK_ATTACHMENT_LOAD_OP_DONT_CARE:\n\t\t\t\/\/ Don't clear the attachment's color or depth aspect.\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tUNSUPPORTED(\"attachment.loadOp %d\", attachment.loadOp);\n\t\t}\n\n\t\tswitch(attachment.stencilLoadOp)\n\t\t{\n\t\tcase VK_ATTACHMENT_LOAD_OP_CLEAR:\n\t\t\tclearMask |= VK_IMAGE_ASPECT_STENCIL_BIT;\n\t\t\tbreak;\n\t\tcase VK_ATTACHMENT_LOAD_OP_LOAD:\n\t\tcase VK_ATTACHMENT_LOAD_OP_DONT_CARE:\n\t\t\t\/\/ Don't clear the attachment's stencil aspect.\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tUNSUPPORTED(\"attachment.stencilLoadOp %d\", attachment.stencilLoadOp);\n\t\t}\n\n\t\t\/\/ Image::clear() demands that we only specify existing aspects.\n\t\tclearMask &= Format(attachment.format).getAspects();\n\n\t\tif(!clearMask || !renderPass->isAttachmentUsed(i))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(renderPass->isMultiView())\n\t\t{\n\t\t\tattachments[i]->clearWithLayerMask(pClearValues[i], clearMask, renderArea,\n\t\t\t renderPass->getAttachmentViewMask(i));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tattachments[i]->clear(pClearValues[i], clearMask, renderArea);\n\t\t}\n\t}\n}\n\nvoid Framebuffer::clearAttachment(const RenderPass *renderPass, uint32_t subpassIndex, const VkClearAttachment &attachment, const VkClearRect &rect)\n{\n\tVkSubpassDescription subpass = renderPass->getSubpass(subpassIndex);\n\n\tif(attachment.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT)\n\t{\n\t\tASSERT(attachment.colorAttachment < subpass.colorAttachmentCount);\n\t\tuint32_t attachmentIndex = subpass.pColorAttachments[attachment.colorAttachment].attachment;\n\n\t\tif(attachmentIndex != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tASSERT(attachmentIndex < attachmentCount);\n\t\t\tImageView *imageView = attachments[attachmentIndex];\n\n\t\t\tif(renderPass->isMultiView())\n\t\t\t{\n\t\t\t\timageView->clearWithLayerMask(attachment.clearValue, attachment.aspectMask, rect.rect,\n\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\timageView->clear(attachment.clearValue, attachment.aspectMask, rect);\n\t\t\t}\n\t\t}\n\t}\n\telse if(attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))\n\t{\n\t\tuint32_t attachmentIndex = subpass.pDepthStencilAttachment->attachment;\n\n\t\tif(attachmentIndex != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tASSERT(attachmentIndex < attachmentCount);\n\t\t\tImageView *imageView = attachments[attachmentIndex];\n\n\t\t\tif(renderPass->isMultiView())\n\t\t\t{\n\t\t\t\timageView->clearWithLayerMask(attachment.clearValue, attachment.aspectMask, rect.rect,\n\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\timageView->clear(attachment.clearValue, attachment.aspectMask, rect);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tUNSUPPORTED(\"attachment.aspectMask %X\", attachment.aspectMask);\n}\n\nvoid Framebuffer::setAttachment(ImageView *imageView, uint32_t index)\n{\n\tASSERT(index < attachmentCount);\n\tASSERT(attachments[index] == nullptr);\n\tattachments[index] = imageView;\n}\n\nImageView *Framebuffer::getAttachment(uint32_t index) const\n{\n\treturn attachments[index];\n}\n\nvoid Framebuffer::resolve(const RenderPass *renderPass, uint32_t subpassIndex)\n{\n\tauto const &subpass = renderPass->getSubpass(subpassIndex);\n\tif(subpass.pResolveAttachments)\n\t{\n\t\tfor(uint32_t i = 0; i < subpass.colorAttachmentCount; i++)\n\t\t{\n\t\t\tuint32_t resolveAttachment = subpass.pResolveAttachments[i].attachment;\n\t\t\tif(resolveAttachment != VK_ATTACHMENT_UNUSED)\n\t\t\t{\n\t\t\t\tImageView *imageView = attachments[subpass.pColorAttachments[i].attachment];\n\t\t\t\tif(renderPass->isMultiView())\n\t\t\t\t{\n\t\t\t\t\timageView->resolveWithLayerMask(attachments[resolveAttachment],\n\t\t\t\t\t renderPass->getViewMask(subpassIndex));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\timageView->resolve(attachments[resolveAttachment]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif(renderPass->hasDepthStencilResolve() && subpass.pDepthStencilAttachment != nullptr)\n\t{\n\t\tVkSubpassDescriptionDepthStencilResolve dsResolve = renderPass->getSubpassDepthStencilResolve(subpassIndex);\n\t\tuint32_t depthStencilAttachment = subpass.pDepthStencilAttachment->attachment;\n\t\tif(depthStencilAttachment != VK_ATTACHMENT_UNUSED)\n\t\t{\n\t\t\tImageView *imageView = attachments[depthStencilAttachment];\n\t\t\timageView->resolveDepthStencil(attachments[dsResolve.pDepthStencilResolveAttachment->attachment], dsResolve);\n\t\t}\n\t}\n}\n\nsize_t Framebuffer::ComputeRequiredAllocationSize(const VkFramebufferCreateInfo *pCreateInfo)\n{\n\tconst VkBaseInStructure *curInfo = reinterpret_cast<const VkBaseInStructure *>(pCreateInfo->pNext);\n\tconst VkFramebufferAttachmentsCreateInfo *attachmentsInfo = nullptr;\n\twhile(curInfo)\n\t{\n\t\tswitch(curInfo->sType)\n\t\t{\n\t\tcase VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO:\n\t\t\tattachmentsInfo = reinterpret_cast<const VkFramebufferAttachmentsCreateInfo *>(curInfo);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLOG_TRAP(\"pFramebufferCreateInfo->pNext->sType = %s\", vk::Stringify(curInfo->sType).c_str());\n\t\t\tbreak;\n\t\t}\n\n\t\tcurInfo = curInfo->pNext;\n\t}\n\n\tif(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)\n\t{\n\t\tASSERT(attachmentsInfo != nullptr);\n\t\treturn attachmentsInfo->attachmentImageInfoCount * sizeof(void *);\n\t}\n\telse\n\t{\n\t\treturn pCreateInfo->attachmentCount * sizeof(void *);\n\t}\n}\n\n} \/\/ namespace vk\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkValuePainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkValuePainter.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"vtkAbstractMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkImageData.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationDoubleVectorKey.h\"\n#include \"vtkInformationIntegerKey.h\"\n#include \"vtkInformationStringKey.h\"\n#include \"vtkNew.h\"\n#include \"vtkOpenGLTexture.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTimerLog.h\"\n\n#include \"vtkOpenGL.h\"\n#include \"vtkOpenGLError.h\"\n#include \"vtkOpenGLExtensionManager.h\"\n\n#include \"vtkgl.h\" \/\/ vtkgl namespace\n\nvtkInformationKeyMacro(vtkValuePainter, SCALAR_MODE, Integer);\nvtkInformationKeyMacro(vtkValuePainter, SCALAR_RANGE, DoubleVector);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_ID, Integer);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_NAME, String);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_COMPONENT, Integer);\n\n\/\/TODO: template MapScalars to eliminate casting\/conversion\n\/\/TODO: make MapScalars extensible if user has a different function in mind\n\/\/TODO: make MapScalars output within a band so that you can multipass on >24 bit quantities (like selection does)\n\nclass vtkValuePainter::vtkInternals\n{\npublic:\n int FieldAssociation;\n int FieldAttributeType;\n std::string FieldName;\n bool FieldNameSet;\n int Component;\n double ScalarRange[2];\n bool ScalarRangeSet;\n\n vtkNew<vtkImageData> Texture;\n\n \/\/ Description:\n \/\/ Constructor\n vtkInternals()\n {\n this->FieldNameSet = false;\n this->FieldAssociation = 0;\n this->FieldAttributeType = 0;\n this->Component = 0;\n this->ScalarRangeSet = false;\n this->ScalarRange[0] = 0.0;\n this->ScalarRange[1] = -1.0;\n\n #define MML 0x1000\n this->Texture->SetExtent(0,MML,0,0, 0,0);\n vtkSmartPointer<vtkUnsignedCharArray> chars = vtkSmartPointer<vtkUnsignedCharArray>::New();\n chars->SetNumberOfComponents(3);\n chars->SetNumberOfTuples(MML);\n unsigned char color[3];\n unsigned int i;\n for (i = 0; i < MML; i++)\n {\n vtkValuePainter::ValueToColor(i, 0, MML, color);\n chars->SetTuple3(i, color[0],color[1],color[2]);\n }\n this->Texture->GetPointData()->SetScalars(chars);\n }\n\n \/\/ Description:\n \/\/ Destructor\n ~vtkInternals()\n {\n }\n};\n\n\/\/----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkValuePainter);\n\n\/\/----------------------------------------------------------------------------\nvtkValuePainter::vtkValuePainter()\n{\n this->Internals = new vtkInternals;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkValuePainter::~vtkValuePainter()\n{\n delete this->Internals;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputArrayToProcess(\n int fieldAssociation,\n const char* name)\n{\n if ( !this->Internals->FieldNameSet\n || (this->Internals->FieldAssociation != fieldAssociation)\n || (this->Internals->FieldName != name) )\n {\n this->Internals->FieldAssociation = fieldAssociation;\n this->Internals->FieldName = name;\n this->Internals->FieldNameSet = true;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputArrayToProcess(\n int fieldAssociation,\n int fieldAttributeType)\n{\n if ( (this->Internals->FieldAssociation != fieldAssociation)\n || (this->Internals->FieldAttributeType != fieldAttributeType)\n || this->Internals->FieldNameSet )\n {\n this->Internals->FieldAssociation = fieldAssociation;\n this->Internals->FieldAttributeType = fieldAttributeType;\n this->Internals->FieldNameSet = false;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputComponentToProcess(int comp)\n{\n if ( this->Internals->Component != comp)\n {\n this->Internals->Component = comp;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetScalarRange(double min, double max)\n{\n if (this->Internals->ScalarRange[0] != min ||\n this->Internals->ScalarRange[1] != max)\n {\n this->Internals->ScalarRange[0] = min;\n this->Internals->ScalarRange[1] = max;\n this->Internals->ScalarRangeSet = (max > min);\n this->Modified();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ProcessInformation(vtkInformation* info)\n{\n bool modify = false;\n bool byname = false;\n\n int fa = this->Internals->FieldAssociation;\n int aidx = this->Internals->FieldAttributeType;\n std::string aname = this->Internals->FieldName;\n\n if (info->Has(vtkValuePainter::SCALAR_MODE()))\n {\n if (this->Internals->FieldAssociation != info->Get(vtkValuePainter::SCALAR_MODE()))\n {\n fa = info->Get(vtkValuePainter::SCALAR_MODE());\n modify = true;\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_ID()))\n {\n if (this->Internals->FieldAttributeType != info->Get(vtkValuePainter::ARRAY_ID()))\n {\n aidx = info->Get(vtkValuePainter::ARRAY_ID());\n modify = true;\n byname = false;\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_NAME()))\n {\n if (this->Internals->FieldName != info->Get(vtkValuePainter::ARRAY_NAME()))\n {\n aname = info->Get(vtkValuePainter::ARRAY_NAME());\n modify = true;\n byname = true;\n }\n }\n\n if (modify)\n {\n if (byname)\n {\n this->SetInputArrayToProcess(fa, aname.c_str());\n }\n else\n {\n this->SetInputArrayToProcess(fa, aidx);\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_COMPONENT()))\n {\n if (this->Internals->Component != info->Get(vtkValuePainter::ARRAY_COMPONENT()))\n {\n this->SetInputComponentToProcess(info->Get(vtkValuePainter::ARRAY_COMPONENT()));\n }\n }\n\n if (info->Has(vtkValuePainter::SCALAR_RANGE()))\n {\n double *nr = info->Get(vtkValuePainter::SCALAR_RANGE());\n if (this->Internals->ScalarRange[0] != nr[0] || this->Internals->ScalarRange[1] != nr[1])\n {\n this->SetScalarRange(nr[0], nr[1]);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ValueToColor(double value, double min, double scale,\n unsigned char *color)\n{\n \/\/TODO: make this configurable\n double valueS = (value - min)\/scale;\n valueS = (valueS<0.0?0.0:valueS); \/\/prevent underflow\n valueS = (valueS>1.0?1.0:valueS); \/\/prevent overflow\n int valueI = valueS * 0xffffff;\n\n color[0] = (unsigned char)((valueI & 0xff0000)>>16);\n color[1] = (unsigned char)((valueI & 0x00ff00)>>8);\n color[2] = (unsigned char)((valueI & 0x0000ff));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ColorToValue(unsigned char *color, double min, double scale,\n double &value)\n{\n \/\/TODO: make this configurable\n int valueI = ((int)(*(color+0)))<<16 | ((int)(*(color+1)))<<8 | ((int)(*(color+2)));\n double valueS = valueI\/(double)0xffffff;\n value = valueS*scale + min;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::RenderInternal(\n vtkRenderer* renderer,\n vtkActor* vtkNotUsed(actor),\n unsigned long typeflags,\n bool vtkNotUsed(forceCompileOnly))\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n this->Timer->StartTimer();\n\n vtkOpenGLClearErrorMacro();\n\n \/\/set render state so that colors we draw are not altered at all\n int oldSampling = glIsEnabled(vtkgl::MULTISAMPLE);\n int oldLight = glIsEnabled(GL_LIGHTING);\n int oldBlend = glIsEnabled(GL_BLEND);\n glDisable(vtkgl::MULTISAMPLE);\n glDisable(GL_LIGHTING);\n glDisable(GL_BLEND);\n\n vtkPolyData* pd = this->GetInputAsPolyData();\n\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, pd->GetVerts(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfVerts();\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, pd->GetLines(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfLines();\n if (typeflags & vtkPainter::POLYS)\n {\n this->DrawCells(VTK_POLYGON, pd->GetPolys(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfPolys();\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, pd->GetStrips(), startCell, renderer);\n }\n\n \/\/restore render state to whatever it was before\n if (oldSampling)\n {\n glEnable(vtkgl::MULTISAMPLE);\n }\n if (oldLight)\n {\n glEnable(GL_LIGHTING);\n }\n if (oldBlend)\n {\n glEnable(GL_BLEND);\n }\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::DrawCells(\n int mode, vtkCellArray *connectivity, vtkIdType startCellId,\n vtkRenderer *renderer)\n{\n vtkPolyData* pd = this->GetInputAsPolyData();\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = pd->GetPoints();\n if (!p)\n {\n return;\n }\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n int doingCells;\n vtkDataArray *values;\n\n if (this->Internals->FieldNameSet)\n {\n values = vtkAbstractMapper::GetScalars\n (pd, this->Internals->FieldAssociation, VTK_GET_ARRAY_BY_NAME, 1, this->Internals->FieldName.c_str(), doingCells);\n }\n else\n {\n values = vtkAbstractMapper::GetScalars\n (pd, this->Internals->FieldAssociation, VTK_GET_ARRAY_BY_ID, this->Internals->FieldAttributeType, NULL, doingCells);\n }\n if (!values)\n {\n vtkWarningMacro(\"Could not find array to draw.\")\n return;\n }\n\n int comp = this->Internals->Component;\n if (comp < 0 || comp >= values->GetNumberOfComponents())\n {\n comp = 0;\n }\n double *minmax;\n if (this->Internals->ScalarRangeSet)\n {\n minmax = this->Internals->ScalarRange;\n }\n else\n {\n minmax = values->GetRange(comp);\n }\n double scale = minmax[1]-minmax[0];\n if (scale <= 0)\n {\n scale = values->GetDataTypeMax()-values->GetDataTypeMin();\n }\n\n vtkSmartPointer<vtkOpenGLTexture> internalColorTexture;\n if (!doingCells)\n {\n internalColorTexture = vtkSmartPointer<vtkOpenGLTexture>::New();\n \/\/texture ensures that GL interpolates point values across polygons\n internalColorTexture->RepeatOff();\n internalColorTexture->SetInputData(this->Internals->Texture.GetPointer());\n internalColorTexture->Load(renderer);\n }\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n\n if (doingCells)\n {\n double value = values->GetComponent(count, comp);\n this->ValueToColor(value, minmax[0], scale, color);\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(vtkDataSetAttributes::SCALARS, 3, GL_UNSIGNED_BYTE, color);\n }\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n\n if (!doingCells)\n {\n double value = (values->GetComponent(pointId, comp) - minmax[0])\/scale;\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(vtkDataSetAttributes::TCOORDS,1,VTK_DOUBLE,&value, 0);\n }\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,\n pointtype, voidpoints, 3*pointId);\n }\n\n\n device->EndPrimitive();\n cellId++;\n if (count == 10000)\n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast<double>(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<commit_msg>Revert \"Fix test failure\"<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkValuePainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkValuePainter.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"vtkAbstractMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkImageData.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationDoubleVectorKey.h\"\n#include \"vtkInformationIntegerKey.h\"\n#include \"vtkInformationStringKey.h\"\n#include \"vtkNew.h\"\n#include \"vtkOpenGLTexture.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTimerLog.h\"\n\n#include \"vtkOpenGL.h\"\n#include \"vtkOpenGLError.h\"\n#include \"vtkOpenGLExtensionManager.h\"\n\n#include \"vtkgl.h\" \/\/ vtkgl namespace\n\nvtkInformationKeyMacro(vtkValuePainter, SCALAR_MODE, Integer);\nvtkInformationKeyMacro(vtkValuePainter, SCALAR_RANGE, DoubleVector);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_ID, Integer);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_NAME, String);\nvtkInformationKeyMacro(vtkValuePainter, ARRAY_COMPONENT, Integer);\n\n\/\/TODO: template MapScalars to eliminate casting\/conversion\n\/\/TODO: make MapScalars extensible if user has a different function in mind\n\/\/TODO: make MapScalars output within a band so that you can multipass on >24 bit quantities (like selection does)\n\nclass vtkValuePainter::vtkInternals\n{\npublic:\n int FieldAssociation;\n int FieldAttributeType;\n std::string FieldName;\n bool FieldNameSet;\n int Component;\n double ScalarRange[2];\n bool ScalarRangeSet;\n\n vtkNew<vtkImageData> Texture;\n\n \/\/ Description:\n \/\/ Constructor\n vtkInternals()\n {\n this->FieldNameSet = false;\n this->FieldAssociation = 0;\n this->FieldAttributeType = 0;\n this->Component = 0;\n this->ScalarRangeSet = false;\n this->ScalarRange[0] = 0.0;\n this->ScalarRange[1] = -1.0;\n\n #define MML 0x1000\n this->Texture->SetExtent(0,MML,0,0, 0,0);\n vtkSmartPointer<vtkUnsignedCharArray> chars = vtkSmartPointer<vtkUnsignedCharArray>::New();\n chars->SetNumberOfComponents(3);\n chars->SetNumberOfTuples(MML);\n unsigned char color[3];\n unsigned int i;\n for (i = 0; i < MML; i++)\n {\n vtkValuePainter::ValueToColor(i, 0, MML, color);\n chars->SetTuple3(i, color[0],color[1],color[2]);\n }\n this->Texture->GetPointData()->SetScalars(chars);\n }\n\n \/\/ Description:\n \/\/ Destructor\n ~vtkInternals()\n {\n }\n};\n\n\/\/----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkValuePainter);\n\n\/\/----------------------------------------------------------------------------\nvtkValuePainter::vtkValuePainter()\n{\n this->Internals = new vtkInternals;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkValuePainter::~vtkValuePainter()\n{\n delete this->Internals;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputArrayToProcess(\n int fieldAssociation,\n const char* name)\n{\n if ( !this->Internals->FieldNameSet\n || (this->Internals->FieldAssociation != fieldAssociation)\n || (this->Internals->FieldName != name) )\n {\n this->Internals->FieldAssociation = fieldAssociation;\n this->Internals->FieldName = name;\n this->Internals->FieldNameSet = true;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputArrayToProcess(\n int fieldAssociation,\n int fieldAttributeType)\n{\n if ( (this->Internals->FieldAssociation != fieldAssociation)\n || (this->Internals->FieldAttributeType != fieldAttributeType)\n || this->Internals->FieldNameSet )\n {\n this->Internals->FieldAssociation = fieldAssociation;\n this->Internals->FieldAttributeType = fieldAttributeType;\n this->Internals->FieldNameSet = false;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetInputComponentToProcess(int comp)\n{\n if ( this->Internals->Component != comp)\n {\n this->Internals->Component = comp;\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::SetScalarRange(double min, double max)\n{\n if (this->Internals->ScalarRange[0] != min ||\n this->Internals->ScalarRange[1] != max)\n {\n this->Internals->ScalarRange[0] = min;\n this->Internals->ScalarRange[1] = max;\n this->Internals->ScalarRangeSet = (max > min);\n this->Modified();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ProcessInformation(vtkInformation* info)\n{\n bool modify = false;\n bool byname = false;\n\n int fa = this->Internals->FieldAssociation;\n int aidx = this->Internals->FieldAttributeType;\n std::string aname = this->Internals->FieldName;\n\n if (info->Has(vtkValuePainter::SCALAR_MODE()))\n {\n if (this->Internals->FieldAssociation != info->Get(vtkValuePainter::SCALAR_MODE()))\n {\n fa = info->Get(vtkValuePainter::SCALAR_MODE());\n modify = true;\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_ID()))\n {\n if (this->Internals->FieldAttributeType != info->Get(vtkValuePainter::ARRAY_ID()))\n {\n aidx = info->Get(vtkValuePainter::ARRAY_ID());\n modify = true;\n byname = false;\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_NAME()))\n {\n if (this->Internals->FieldName != info->Get(vtkValuePainter::ARRAY_NAME()))\n {\n aname = info->Get(vtkValuePainter::ARRAY_NAME());\n modify = true;\n byname = true;\n }\n }\n\n if (modify)\n {\n if (byname)\n {\n this->SetInputArrayToProcess(fa, aname.c_str());\n }\n else\n {\n this->SetInputArrayToProcess(fa, aidx);\n }\n }\n\n if (info->Has(vtkValuePainter::ARRAY_COMPONENT()))\n {\n if (this->Internals->Component != info->Get(vtkValuePainter::ARRAY_COMPONENT()))\n {\n this->SetInputComponentToProcess(info->Get(vtkValuePainter::ARRAY_COMPONENT()));\n }\n }\n\n if (info->Has(vtkValuePainter::SCALAR_RANGE()))\n {\n double *nr = info->Get(vtkValuePainter::SCALAR_RANGE());\n if (this->Internals->ScalarRange[0] != nr[0] || this->Internals->ScalarRange[1] != nr[1])\n {\n this->SetScalarRange(nr[0], nr[1]);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ValueToColor(double value, double min, double scale,\n unsigned char *color)\n{\n \/\/TODO: make this configurable\n double valueS = (value - min)\/scale;\n valueS = (valueS<0.0?0.0:valueS); \/\/prevent underflow\n valueS = (valueS>1.0?1.0:valueS); \/\/prevent overflow\n int valueI = valueS * 0xffffff;\n\n color[0] = (unsigned char)((valueI & 0xff0000)>>16);\n color[1] = (unsigned char)((valueI & 0x00ff00)>>8);\n color[2] = (unsigned char)((valueI & 0x0000ff));\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::ColorToValue(unsigned char *color, double min, double scale,\n double &value)\n{\n \/\/TODO: make this configurable\n int valueI = ((int)(*(color+0)))<<16 | ((int)(*(color+1)))<<8 | ((int)(*(color+2)));\n double valueS = valueI\/(double)0xffffff;\n value = valueS*scale + min;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::RenderInternal(\n vtkRenderer* renderer,\n vtkActor* vtkNotUsed(actor),\n unsigned long typeflags,\n bool vtkNotUsed(forceCompileOnly))\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n this->Timer->StartTimer();\n\n vtkOpenGLClearErrorMacro();\n\n \/\/set render state so that colors we draw are not altered at all\n int oldSampling = glIsEnabled(vtkgl::MULTISAMPLE);\n int oldLight = glIsEnabled(GL_LIGHTING);\n int oldBlend = glIsEnabled(GL_BLEND);\n glDisable(vtkgl::MULTISAMPLE);\n glDisable(GL_LIGHTING);\n glDisable(GL_BLEND);\n\n vtkPolyData* pd = this->GetInputAsPolyData();\n\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, pd->GetVerts(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfVerts();\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, pd->GetLines(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfLines();\n if (typeflags & vtkPainter::POLYS)\n {\n this->DrawCells(VTK_POLYGON, pd->GetPolys(), startCell, renderer);\n }\n\n startCell += pd->GetNumberOfPolys();\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, pd->GetStrips(), startCell, renderer);\n }\n\n \/\/restore render state to whatever it was before\n if (oldSampling)\n {\n glEnable(vtkgl::MULTISAMPLE);\n }\n if (oldLight)\n {\n glEnable(GL_LIGHTING);\n }\n if (oldBlend)\n {\n glEnable(GL_BLEND);\n }\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkValuePainter::DrawCells(\n int mode, vtkCellArray *connectivity, vtkIdType startCellId,\n vtkRenderer *renderer)\n{\n vtkPolyData* pd = this->GetInputAsPolyData();\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = pd->GetPoints();\n if (!p)\n {\n return;\n }\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n int doingCells;\n vtkDataArray *values;\n\n if (this->Internals->FieldNameSet)\n {\n values = vtkAbstractMapper::GetScalars\n (pd, this->Internals->FieldAssociation, VTK_GET_ARRAY_BY_NAME, 1, this->Internals->FieldName.c_str(), doingCells);\n }\n else\n {\n values = vtkAbstractMapper::GetScalars\n (pd, this->Internals->FieldAssociation, VTK_GET_ARRAY_BY_ID, this->Internals->FieldAttributeType, NULL, doingCells);\n }\n if (!values)\n {\n vtkWarningMacro(\"Could not find array to draw.\")\n return;\n }\n\n int comp = this->Internals->Component;\n if (comp < 0 || comp >= values->GetNumberOfComponents())\n {\n comp = 0;\n }\n double *minmax;\n if (this->Internals->ScalarRangeSet)\n {\n minmax = this->Internals->ScalarRange;\n }\n else\n {\n minmax = values->GetRange(comp);\n }\n double scale = minmax[1]-minmax[0];\n if (scale <= 0)\n {\n scale = values->GetDataTypeMax()-values->GetDataTypeMin();\n }\n\n vtkSmartPointer<vtkOpenGLTexture> internalColorTexture;\n if (!doingCells)\n {\n internalColorTexture = vtkSmartPointer<vtkOpenGLTexture>::New();\n \/\/texture ensures that GL interpolates point values across polygons\n internalColorTexture->RepeatOff();\n internalColorTexture->SetInputData(this->Internals->Texture.GetPointer());\n internalColorTexture->Load(renderer);\n }\n\n#if VTK_SIZEOF_CHAR == 1\n GLenum vtkChar2GLenum = GL_UNSIGNED_BYTE;\n#elif VTK_SIZE_OF_CHAR == 2\n GLenum vtkChar2GLenum = GL_UNSIGNED_SHORT;\n#endif\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n\n if (doingCells)\n {\n double value = values->GetComponent(count, comp);\n this->ValueToColor(value, minmax[0], scale, color);\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(\n vtkDataSetAttributes::SCALARS, 3, vtkChar2GLenum, color);\n }\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n\n if (!doingCells)\n {\n double value = (values->GetComponent(pointId, comp) - minmax[0])\/scale;\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(vtkDataSetAttributes::TCOORDS,1,VTK_DOUBLE,&value, 0);\n }\n\n renderer->GetRenderWindow()->GetPainterDeviceAdapter()\n ->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,\n pointtype, voidpoints, 3*pointId);\n }\n\n\n device->EndPrimitive();\n cellId++;\n if (count == 10000)\n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast<double>(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkValuePainter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ https:\/\/github.com\/pillarjs\/path-to-regexp\/blob\/master\/index.js\n\n#ifndef PATH_TO_REGEX_HPP\n#define PATH_TO_REGEX_HPP\n\n#include <map>\n#include <regex>\n#include <string>\n#include <vector>\n\nnamespace route {\n\nstruct Token {\n\tstd::string name {};\t\/\/ can be a string or an int (index)\n\tstd::string prefix {};\n\tstd::string delimiter {};\n\tstd::string pattern {};\n bool optional {false};\n bool repeat {false};\n bool partial {false};\n bool asterisk {false};\n\tbool is_string {false};\t\/\/ If it is a string we only put\/have a string in the name-attribute (path in parse-method)\n\t \t\/\/ So if this is true, we can ignore all attributes except name\n\n void set_string_token(const std::string& name_) {\n name = name_;\n is_string = true;\n }\n}; \/\/< struct Token\n\nclass PathToRegex {\nprivate:\n \/\/----------------------------------------\n \/\/ Internal class type aliases\n using Keys = std::vector<Token>;\n using Tokens = std::vector<Token>;\n using Options = std::map<std::string, bool>;\n \/\/----------------------------------------\npublic:\n \/**\n * Creates a path-regex from string input (path)\n * Updates keys-vector (empty input parameter)\n *\n * Calls parse-method and then tokens_to_regex-method based on the tokens returned from parse-method\n * Puts the tokens that are keys (not string-tokens) into keys-vector\n *\n * std::vector<Token> keys (empty)\n * Is created outside the class and sent in as parameter\n * One Token-object in the keys-vector per parameter found in the path\n *\n * std::map<std::string, bool> options (optional)\n * Can contain bool-values for the keys \"sensitive\", \"strict\" and\/or \"end\"\n * Default:\n * strict = false\n * sensitive = false\n * end = true\n *\/\n\tstatic std::regex path_to_regex(const std::string& path, Keys& keys, const Options& options = Options{});\n\n \/**\n * Creates a path-regex from string input (path)\n *\n * Calls parse-method and then tokens_to_regex-method based on the tokens returned from parse-method\n *\n * std::map<std::string, bool> options (optional)\n * Can contain bool-values for the keys \"sensitive\", \"strict\" and\/or \"end\"\n * Default:\n * strict = false\n * sensitive = false\n * end = true\n *\/\n static std::regex path_to_regex(const std::string& path, const Options& options = Options{});\n\n \/**\n * Creates vector of tokens based on the given string (this vector of tokens can be sent as\n * input to tokens_to_regex-method and includes tokens that are strings, not only tokens\n * that are parameters in str)\n *\/\n static Tokens parse(const std::string& str);\n\n \/**\n * Creates a regex based on the tokens and options (optional) given\n *\/\n static std::regex tokens_to_regex(const Tokens& tokens, const Options& options = Options{});\n\n \/**\n * Goes through the tokens-vector and push all tokens that are not string-tokens\n * onto keys-vector\n *\/\n static void tokens_to_keys(const Tokens& tokens, Keys& keys);\n\nprivate:\n\tstatic const std::regex PATH_REGEXP;\n}; \/\/< class PathToRegex\n\n}; \/\/< namespace route\n\n#endif \/\/< PATH_TO_REGEX_HPP\n<commit_msg>Renamed include guard<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ https:\/\/github.com\/pillarjs\/path-to-regexp\/blob\/master\/index.js\n\n#ifndef ROUTE_PATH_TO_REGEX_HPP\n#define ROUTE_PATH_TO_REGEX_HPP\n\n#include <map>\n#include <regex>\n#include <string>\n#include <vector>\n\nnamespace route {\n\nstruct Token {\n\tstd::string name {};\t\/\/ can be a string or an int (index)\n\tstd::string prefix {};\n\tstd::string delimiter {};\n\tstd::string pattern {};\n bool optional {false};\n bool repeat {false};\n bool partial {false};\n bool asterisk {false};\n\tbool is_string {false};\t\/\/ If it is a string we only put\/have a string in the name-attribute (path in parse-method)\n\t \t\/\/ So if this is true, we can ignore all attributes except name\n\n void set_string_token(const std::string& name_) {\n name = name_;\n is_string = true;\n }\n}; \/\/< struct Token\n\nclass PathToRegex {\nprivate:\n \/\/----------------------------------------\n \/\/ Internal class type aliases\n using Keys = std::vector<Token>;\n using Tokens = std::vector<Token>;\n using Options = std::map<std::string, bool>;\n \/\/----------------------------------------\npublic:\n \/**\n * Creates a path-regex from string input (path)\n * Updates keys-vector (empty input parameter)\n *\n * Calls parse-method and then tokens_to_regex-method based on the tokens returned from parse-method\n * Puts the tokens that are keys (not string-tokens) into keys-vector\n *\n * std::vector<Token> keys (empty)\n * Is created outside the class and sent in as parameter\n * One Token-object in the keys-vector per parameter found in the path\n *\n * std::map<std::string, bool> options (optional)\n * Can contain bool-values for the keys \"sensitive\", \"strict\" and\/or \"end\"\n * Default:\n * strict = false\n * sensitive = false\n * end = true\n *\/\n\tstatic std::regex path_to_regex(const std::string& path, Keys& keys, const Options& options = Options{});\n\n \/**\n * Creates a path-regex from string input (path)\n *\n * Calls parse-method and then tokens_to_regex-method based on the tokens returned from parse-method\n *\n * std::map<std::string, bool> options (optional)\n * Can contain bool-values for the keys \"sensitive\", \"strict\" and\/or \"end\"\n * Default:\n * strict = false\n * sensitive = false\n * end = true\n *\/\n static std::regex path_to_regex(const std::string& path, const Options& options = Options{});\n\n \/**\n * Creates vector of tokens based on the given string (this vector of tokens can be sent as\n * input to tokens_to_regex-method and includes tokens that are strings, not only tokens\n * that are parameters in str)\n *\/\n static Tokens parse(const std::string& str);\n\n \/**\n * Creates a regex based on the tokens and options (optional) given\n *\/\n static std::regex tokens_to_regex(const Tokens& tokens, const Options& options = Options{});\n\n \/**\n * Goes through the tokens-vector and push all tokens that are not string-tokens\n * onto keys-vector\n *\/\n static void tokens_to_keys(const Tokens& tokens, Keys& keys);\n\nprivate:\n\tstatic const std::regex PATH_REGEXP;\n}; \/\/< class PathToRegex\n\n} \/\/< namespace route\n\n#endif \/\/< ROUTE_PATH_TO_REGEX_HPP\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\/\/~ #include <fstream>\n\/\/~ #include <cmath>\n#include <ctime>\n\n#include \"TH1.h\"\n\/\/~ #include \"TH2.h\"\n\/\/~ #include \"TH3.h\"\n\/\/~ #include \"TCanvas.h\"\n#include \"TRandom3.h\"\n\/\/~ #include \"TVector2.h\"\n\/\/~ #include \"TVector3.h\"\n\/\/~ #include \"TLorentzVector.h\"\n#include \"TString.h\"\n\n#include \"Math\/Minimizer.h\"\n#include \"Math\/Factory.h\"\n#include \"Math\/Functor.h\"\n\n\/* Algorithms list\n * minName algoName\n * ---------------------------------\n * Minuit\/Minuit2 Migrad, Simplex, Seek, Combined (default is Migrad)\n * Minuit\/Minuit2 Scan (good for scans, not minimizations)\n * Minuit2 Fumili (*** needs different function type ***), Fumili2\n * Fumili *** needs different function type ***\n * GSLMultiMin ConjugateFR, ConjugatePR, BFGS, BFGS2, SteepestDescent\n * GSLMultiFit *** needs different function type ***\n * GSLSimAn\n * Linear *** needs linear function ***\n * Genetic *** sloooow and inaccurate ***\n * \n * \n * https:\/\/root.cern.ch\/fitting\n * https:\/\/root.cern.ch\/numerical-minimization\n *\/\n\nconst int Ndim = 8;\n\nusing namespace ROOT::Math;\nusing namespace std;\n\ndouble parabola1(const double* xx)\n{\n double x = xx[0];\n double y = xx[1];\n return (x-3)*(x-3)+(y-2)*(y-2);\n}\n\ndouble parabolaN(const double* xx)\n{\n double accumulator=0;\n for (int i=0; i< Ndim; ++i) {\n double c = i+1;\n accumulator += (xx[i]-1\/c)*(xx[i]-1\/c);\n }\n return accumulator;\n}\n\ndouble rosenbrockN(const double* xx)\n{\n double accumulator=0;\n for (int i=0; i< Ndim-1; ++i) {\n accumulator += 100*pow(xx[i+1]-xx[i]*xx[i], 2) + pow(xx[i]-1, 2);\n }\n return accumulator;\n}\n\nclass MCMinimizer\n{\nprotected:\n TRandom3 rng;\n \n int Ndim = 0;\n double (*function)(const double*); \/\/ = &rosenbrockN;\n \n vector<double> params;\n vector<double> params_min;\n vector<double> params_max;\n vector<string> names;\n double minValue;\n \n int max_function_calls = 0;\n int printLevel;\n \npublic:\n MCMinimizer()\n {\n this->rng = TRandom3(12345);\n }\n \n inline void SetMCFunction(double (*function)(const double*), int Ndim)\n {\n this->function = function;\n this->Ndim = Ndim;\n }\n \n inline void SetMCVariable(string name, double val, double min, double max)\n {\n this->params.push_back(val);\n this->params_min.push_back(min);\n this->params_max.push_back(max);\n this->names.push_back(name);\n }\n \n inline void SetMaxFunctionCalls(int calls)\n {\n this->max_function_calls = calls;\n }\n \n bool Minimize()\n {\n if (printLevel) cout << \"Minimize using MCMinimizer\" << endl;\n this->minValue = this->function(¶ms[0]); \/\/ evaluate in given initial point\n \n for (int i=0; i<this->max_function_calls; ++i) {\n double pars_array[Ndim];\n for (int par=0; par < Ndim; ++par) { \/\/ get random params vector\n pars_array[par] = rng.Uniform(params_min[par], params_max[par]);\n }\n double nmin = (*function)(pars_array);\n if (nmin < this->minValue) {\n this->minValue = nmin;\n params = vector<double>(pars_array, pars_array + Ndim);\n }\n }\n if (printLevel) {\n cout << \"FVAL = \" << this->minValue << endl;\n for (int i=0; i<Ndim; ++i) {\n cout << names[i] << \"\\t = \" << params[i] << endl;\n }\n }\n return true;\n }\n \n inline void SetPrintLevel(int printLevel)\n {\n this->printLevel = printLevel;\n }\n \n inline double MinValue()\n {\n return this->minValue;\n }\n \n inline double* X()\n {\n return &(this->params[0]);\n }\n};\n\nclass MCZoomMinimizer\n{\nprotected:\n TRandom3 rng;\n \n int Ndim = 0;\n double (*function)(const double*); \/\/ = &rosenbrockN;\n \n vector<double> params;\n vector<double> params_min;\n vector<double> params_max;\n vector<string> names;\n double minValue;\n \n int max_function_calls = 0;\n int splits = 0;\n int printLevel;\n \npublic:\n MCZoomMinimizer()\n {\n this->rng = TRandom3(12345);\n }\n \n inline void SetMCFunction(double (*function)(const double*), int Ndim)\n {\n this->function = function;\n this->Ndim = Ndim;\n }\n \n inline void SetMCVariable(string name, double val, double min, double max)\n {\n this->params.push_back(val);\n this->params_min.push_back(min);\n this->params_max.push_back(max);\n this->names.push_back(name);\n }\n \n inline void SetMaxFunctionCalls(int calls)\n {\n this->max_function_calls = calls;\n }\n \n inline void SetSplitNumber(int splits)\n {\n this->splits = splits;\n }\n \n bool Minimize()\n {\n if (printLevel) cout << \"Minimize using MCZoomMinimizer\" << endl;\n this->minValue = this->function(¶ms[0]); \/\/ evaluate in given initial point\n \n for (int ns=0; ns < splits; ++ns) {\n double average[2][Ndim];\n int calls[2][Ndim];\n int call_block = this->max_function_calls\/this->splits;\n for (int i=0; i<call_block; ++i) {\n int call_over[Ndim];\n double pars_array[Ndim];\n for (int par=0; par < Ndim; ++par) { \/\/ get random params vector\n pars_array[par] = rng.Uniform(params_min[par], params_max[par]);\n int ifup = pars_array[par] > ((params_min[par] + params_max[par])\/2);\n calls[ifup][par]++;\n call_over[par] = ifup;\n }\n double nmin = (*function)(pars_array);\n for (int par=0; par < Ndim; ++par) {\n average[call_over[par]][par] += nmin;\n }\n if (nmin < this->minValue) {\n this->minValue = nmin;\n params = vector<double>(pars_array, pars_array + Ndim);\n }\n }\n \n for (int par=0; par < Ndim; ++par) {\n if (average[0][par]\/calls[0][par] > average[1][par]\/calls[1][par]) {\n params_max[par] = (params_min[par] + params_max[par])\/2;\n }\n else {\n params_min[par] = (params_min[par] + params_max[par])\/2;\n }\n }\n }\n \n if (printLevel) {\n cout << \"FVAL = \" << this->minValue << endl;\n for (int i=0; i<Ndim; ++i) {\n cout << names[i] << \"\\t = \" << params[i] << endl;\n }\n }\n return true;\n }\n \n inline void SetPrintLevel(int printLevel)\n {\n this->printLevel = printLevel;\n }\n \n inline double MinValue()\n {\n return this->minValue;\n }\n \n inline double* X()\n {\n return &(this->params[0]);\n }\n};\n\nint minimizer()\n{\n \/\/ List of valid minimizers\n vector<pair<string,string>> minVector;\n \/\/ name algorithm\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Migrad\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Simplex\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Combined\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Seek\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Scan\"));\n \n minVector.push_back(pair<string,string>(\"Minuit2\", \"Migrad\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Simplex\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Combined\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Seek\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Scan\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Fumili\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Fumili2\"));\n \n \/\/ minVector.push_back(pair<string,string>(\"Fumili\", \"Fumili\"));\n \n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"ConjugateFR\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"ConjugatePR\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"BFGS\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"BFGS2\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"SteepestDescent\"));\n \n \/\/ minVector.push_back(pair<string,string>(\"GSLMultiFit\", \"\"));\n \n minVector.push_back(pair<string,string>(\"GSLSimAn\", \"\"));\n\n \/\/ minVector.push_back(pair<string,string>(\"Linear\", \"\");\n \n \/\/ minVector.push_back(pair<string,string>(\"Genetic\", \"\"));\n\n for (unsigned int i=0; i < minVector.size(); ++i) {\n \n Minimizer* min = Factory::CreateMinimizer(minVector[i].first, minVector[i].second);\n if (min==nullptr) {\n cout << \"Invalid algorithm: \" << minVector[i].first << \" - \" << minVector[i].second << endl;\n continue;\n }\n else cout << \"Using algorithm: \" << minVector[i].first << \" - \" << minVector[i].second << endl;\n \n \/\/ The minimizer needs an IMultiGenFunction, which is easily provided\n \/\/ by a Functor, which is a generic wrapper class\n Functor fun = Functor(&rosenbrockN, Ndim);\n \n \/\/ Give the function to the minimizer\n min->SetFunction(fun);\n \n \/\/ Give the function variables\n if (minVector[i].first==\"Genetic\") {\n \/\/ Limited domain (genetic algorithm only)\n for (int i=0; i<Ndim; ++i) {\n min->SetLimitedVariable(i, Form(\"x%d\", i), 0, 0.05, -0.5, +0.5);\n }\n }\n else {\n for (int i=0; i<Ndim; ++i) {\n min->SetVariable(i, Form(\"x%d\", i), 0, 0.05);\n }\n }\n \n \/\/ Verbosity\n min->SetPrintLevel(1);\n \n \/\/ Algorithm strategy (higher=slower & more accurate)\n \/\/ min->SetStrategy(1);\n \n \/\/ Algorithms parameters\n min->SetMaxFunctionCalls(100000);\n min->SetMaxIterations(10000);\n min->SetTolerance(0.001);\n \n \/\/ Minimize!\n clock_t time = clock();\n bool success = min->Minimize();\n time = clock() - time;\n cout << \"Success: \" << success << endl;\n cout << \"Time: \" << 1000*(double)time\/CLOCKS_PER_SEC << \" ms \" << endl;\n \n \/\/ Get out the values\n const double minValue = min->MinValue();\n \/\/ const double* minPoint = min->X();\n \/\/ const double* minErrors= min->Errors();\n \n cout << \"Value: \" << minValue << endl;\n \/\/~ for (int i=0; i<Ndim; ++i) {\n \/\/~ cout << \"x\" << i+1 << \": \" << minPoint[i];\n \/\/~ if (minErrors!=nullptr) cout << \" ± \" << minErrors[i];\n \/\/~ cout << endl;\n \/\/~ }\n cout << endl;\n }\n \n \/\/ Now my minimizer\n {\n MCMinimizer* min = new MCMinimizer();\n cout << \"Using algorithm: MCMinimizer\" << endl;\n \n \/\/ Give the function to the minimizer\n min->SetMCFunction(rosenbrockN, Ndim);\n \n \/\/ Give the function variables\n for (int i=0; i<Ndim; ++i) {\n min->SetMCVariable(Form(\"x%d\", i), 0, 0.9, 1.1);\n }\n \n \/\/ Verbosity\n min->SetPrintLevel(1);\n \n \/\/ Algorithms parameters\n min->SetMaxFunctionCalls(100000);\n \n \/\/ Minimize!\n clock_t time = clock();\n bool success = min->Minimize();\n time = clock() - time;\n cout << \"Success: \" << success << endl;\n cout << \"Time: \" << 1000*(double)time\/CLOCKS_PER_SEC << \" ms \" << endl;\n \n \/\/ Get out the values\n const double minValue = min->MinValue();\n \/\/ const double* minPoint = min->X();\n \/\/ const double* minErrors= min->Errors();\n \n cout << \"Value: \" << minValue << endl;\n \/\/~ for (int i=0; i<Ndim; ++i) {\n \/\/~ cout << \"x\" << i+1 << \": \" << minPoint[i];\n \/\/~ if (minErrors!=nullptr) cout << \" ± \" << minErrors[i];\n \/\/~ cout << endl;\n \/\/~ }\n cout << endl;\n }\n \n \/\/ Now my minimizer\n {\n MCZoomMinimizer* min = new MCZoomMinimizer();\n cout << \"Using algorithm: MCMinimizer\" << endl;\n \n \/\/ Give the function to the minimizer\n min->SetMCFunction(rosenbrockN, Ndim);\n \n \/\/ Give the function variables\n for (int i=0; i<Ndim; ++i) {\n min->SetMCVariable(Form(\"x%d\", i), 0, 0.9, 1.1);\n }\n \n \/\/ Verbosity\n min->SetPrintLevel(1);\n \n \/\/ Algorithms parameters\n min->SetMaxFunctionCalls(100000);\n min->SetSplitNumber(10);\n \n \/\/ Minimize!\n clock_t time = clock();\n bool success = min->Minimize();\n time = clock() - time;\n cout << \"Success: \" << success << endl;\n cout << \"Time: \" << 1000*(double)time\/CLOCKS_PER_SEC << \" ms \" << endl;\n \n \/\/ Get out the values\n const double minValue = min->MinValue();\n \/\/ const double* minPoint = min->X();\n \/\/ const double* minErrors= min->Errors();\n \n cout << \"Value: \" << minValue << endl;\n \/\/~ for (int i=0; i<Ndim; ++i) {\n \/\/~ cout << \"x\" << i+1 << \": \" << minPoint[i];\n \/\/~ if (minErrors!=nullptr) cout << \" ± \" << minErrors[i];\n \/\/~ cout << endl;\n \/\/~ }\n cout << endl;\n }\n \n return 0;\n}\n\nint main(int, char**)\n{\n return minimizer();\n}\n<commit_msg>Removed<commit_after>#include <iostream>\n\/\/~ #include <fstream>\n\/\/~ #include <cmath>\n#include <ctime>\n\n#include \"TH1.h\"\n\/\/~ #include \"TH2.h\"\n\/\/~ #include \"TH3.h\"\n\/\/~ #include \"TCanvas.h\"\n#include \"TRandom3.h\"\n\/\/~ #include \"TVector2.h\"\n\/\/~ #include \"TVector3.h\"\n\/\/~ #include \"TLorentzVector.h\"\n#include \"TString.h\"\n\n#include \"Math\/Minimizer.h\"\n#include \"Math\/Factory.h\"\n#include \"Math\/Functor.h\"\n\n\/* Algorithms list\n * minName algoName\n * ---------------------------------\n * Minuit\/Minuit2 Migrad, Simplex, Seek, Combined (default is Migrad)\n * Minuit\/Minuit2 Scan (good for scans, not minimizations)\n * Minuit2 Fumili (*** needs different function type ***), Fumili2\n * Fumili *** needs different function type ***\n * GSLMultiMin ConjugateFR, ConjugatePR, BFGS, BFGS2, SteepestDescent\n * GSLMultiFit *** needs different function type ***\n * GSLSimAn\n * Linear *** needs linear function ***\n * Genetic *** sloooow and inaccurate ***\n * \n * \n * https:\/\/root.cern.ch\/fitting\n * https:\/\/root.cern.ch\/numerical-minimization\n *\/\n\nconst int Ndim = 8;\n\nusing namespace ROOT::Math;\nusing namespace std;\n\ndouble parabola1(const double* xx)\n{\n double x = xx[0];\n double y = xx[1];\n return (x-3)*(x-3)+(y-2)*(y-2);\n}\n\ndouble parabolaN(const double* xx)\n{\n double accumulator=0;\n for (int i=0; i< Ndim; ++i) {\n double c = i+1;\n accumulator += (xx[i]-1\/c)*(xx[i]-1\/c);\n }\n return accumulator;\n}\n\ndouble rosenbrockN(const double* xx)\n{\n double accumulator=0;\n for (int i=0; i< Ndim-1; ++i) {\n accumulator += 100*pow(xx[i+1]-xx[i]*xx[i], 2) + pow(xx[i]-1, 2);\n }\n return accumulator;\n}\n\nclass MCMinimizer\n{\nprotected:\n TRandom3 rng;\n \n int Ndim = 0;\n double (*function)(const double*); \/\/ = &rosenbrockN;\n \n vector<double> params;\n vector<double> params_min;\n vector<double> params_max;\n vector<string> names;\n double minValue;\n \n int max_function_calls = 0;\n int printLevel;\n \npublic:\n MCMinimizer()\n {\n this->rng = TRandom3(12345);\n }\n \n inline void SetMCFunction(double (*function)(const double*), int Ndim)\n {\n this->function = function;\n this->Ndim = Ndim;\n }\n \n inline void SetMCVariable(string name, double val, double min, double max)\n {\n this->params.push_back(val);\n this->params_min.push_back(min);\n this->params_max.push_back(max);\n this->names.push_back(name);\n }\n \n inline void SetMaxFunctionCalls(int calls)\n {\n this->max_function_calls = calls;\n }\n \n bool Minimize()\n {\n if (printLevel) cout << \"Minimize using MCMinimizer\" << endl;\n this->minValue = this->function(¶ms[0]); \/\/ evaluate in given initial point\n \n for (int i=0; i<this->max_function_calls; ++i) {\n double pars_array[Ndim];\n for (int par=0; par < Ndim; ++par) { \/\/ get random params vector\n pars_array[par] = rng.Uniform(params_min[par], params_max[par]);\n }\n double nmin = (*function)(pars_array);\n if (nmin < this->minValue) {\n this->minValue = nmin;\n params = vector<double>(pars_array, pars_array + Ndim);\n }\n }\n if (printLevel) {\n cout << \"FVAL = \" << this->minValue << endl;\n for (int i=0; i<Ndim; ++i) {\n cout << names[i] << \"\\t = \" << params[i] << endl;\n }\n }\n return true;\n }\n \n inline void SetPrintLevel(int printLevel)\n {\n this->printLevel = printLevel;\n }\n \n inline double MinValue()\n {\n return this->minValue;\n }\n \n inline double* X()\n {\n return &(this->params[0]);\n }\n};\n\nint minimizer()\n{\n \/\/ List of valid minimizers\n vector<pair<string,string>> minVector;\n \/\/ name algorithm\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Migrad\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Simplex\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Combined\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Seek\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit\", \"Scan\"));\n \n minVector.push_back(pair<string,string>(\"Minuit2\", \"Migrad\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Simplex\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Combined\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Seek\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Scan\"));\n \/\/ minVector.push_back(pair<string,string>(\"Minuit2\", \"Fumili\"));\n minVector.push_back(pair<string,string>(\"Minuit2\", \"Fumili2\"));\n \n \/\/ minVector.push_back(pair<string,string>(\"Fumili\", \"Fumili\"));\n \n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"ConjugateFR\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"ConjugatePR\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"BFGS\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"BFGS2\"));\n minVector.push_back(pair<string,string>(\"GSLMultiMin\", \"SteepestDescent\"));\n \n \/\/ minVector.push_back(pair<string,string>(\"GSLMultiFit\", \"\"));\n \n minVector.push_back(pair<string,string>(\"GSLSimAn\", \"\"));\n\n \/\/ minVector.push_back(pair<string,string>(\"Linear\", \"\");\n \n \/\/ minVector.push_back(pair<string,string>(\"Genetic\", \"\"));\n\n for (unsigned int i=0; i < minVector.size(); ++i) {\n \n Minimizer* min = Factory::CreateMinimizer(minVector[i].first, minVector[i].second);\n if (min==nullptr) {\n cout << \"Invalid algorithm: \" << minVector[i].first << \" - \" << minVector[i].second << endl;\n continue;\n }\n else cout << \"Using algorithm: \" << minVector[i].first << \" - \" << minVector[i].second << endl;\n \n \/\/ The minimizer needs an IMultiGenFunction, which is easily provided\n \/\/ by a Functor, which is a generic wrapper class\n Functor fun = Functor(&rosenbrockN, Ndim);\n \n \/\/ Give the function to the minimizer\n min->SetFunction(fun);\n \n \/\/ Give the function variables\n if (minVector[i].first==\"Genetic\") {\n \/\/ Limited domain (genetic algorithm only)\n for (int i=0; i<Ndim; ++i) {\n min->SetLimitedVariable(i, Form(\"x%d\", i), 0, 0.05, -0.5, +0.5);\n }\n }\n else {\n for (int i=0; i<Ndim; ++i) {\n min->SetVariable(i, Form(\"x%d\", i), 0, 0.05);\n }\n }\n \n \/\/ Verbosity\n min->SetPrintLevel(1);\n \n \/\/ Algorithm strategy (higher=slower & more accurate)\n \/\/ min->SetStrategy(1);\n \n \/\/ Algorithms parameters\n min->SetMaxFunctionCalls(100000);\n min->SetMaxIterations(10000);\n min->SetTolerance(0.001);\n \n \/\/ Minimize!\n clock_t time = clock();\n bool success = min->Minimize();\n time = clock() - time;\n cout << \"Success: \" << success << endl;\n cout << \"Time: \" << 1000*(double)time\/CLOCKS_PER_SEC << \" ms \" << endl;\n \n \/\/ Get out the values\n const double minValue = min->MinValue();\n \/\/ const double* minPoint = min->X();\n \/\/ const double* minErrors= min->Errors();\n \n cout << \"Value: \" << minValue << endl;\n \/\/~ for (int i=0; i<Ndim; ++i) {\n \/\/~ cout << \"x\" << i+1 << \": \" << minPoint[i];\n \/\/~ if (minErrors!=nullptr) cout << \" ± \" << minErrors[i];\n \/\/~ cout << endl;\n \/\/~ }\n cout << endl;\n }\n \n \/\/ Now my minimizer\n {\n MCMinimizer* min = new MCMinimizer();\n cout << \"Using algorithm: MCMinimizer\" << endl;\n \n \/\/ Give the function to the minimizer\n min->SetMCFunction(rosenbrockN, Ndim);\n \n \/\/ Give the function variables\n for (int i=0; i<Ndim; ++i) {\n min->SetMCVariable(Form(\"x%d\", i), 0, 0.9, 1.1);\n }\n \n \/\/ Verbosity\n min->SetPrintLevel(1);\n \n \/\/ Algorithms parameters\n min->SetMaxFunctionCalls(100000);\n \n \/\/ Minimize!\n clock_t time = clock();\n bool success = min->Minimize();\n time = clock() - time;\n cout << \"Success: \" << success << endl;\n cout << \"Time: \" << 1000*(double)time\/CLOCKS_PER_SEC << \" ms \" << endl;\n \n \/\/ Get out the values\n const double minValue = min->MinValue();\n \/\/ const double* minPoint = min->X();\n \/\/ const double* minErrors= min->Errors();\n \n cout << \"Value: \" << minValue << endl;\n \/\/~ for (int i=0; i<Ndim; ++i) {\n \/\/~ cout << \"x\" << i+1 << \": \" << minPoint[i];\n \/\/~ if (minErrors!=nullptr) cout << \" ± \" << minErrors[i];\n \/\/~ cout << endl;\n \/\/~ }\n cout << endl;\n }\n \n return 0;\n}\n\nint main(int, char**)\n{\n return minimizer();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SDD_DD_DEFINITION_HH_\n#define _SDD_DD_DEFINITION_HH_\n\n#include <initializer_list>\n#include <type_traits> \/\/ is_integral\n\n#include \"sdd\/dd\/alpha.hh\"\n#include \"sdd\/dd\/definition_fwd.hh\"\n#include \"sdd\/dd\/node.hh\"\n#include \"sdd\/dd\/terminal.hh\"\n#include \"sdd\/mem\/ptr.hh\"\n#include \"sdd\/mem\/ref_counted.hh\"\n#include \"sdd\/mem\/variant.hh\"\n#include \"sdd\/order\/order.hh\"\n#include \"sdd\/util\/print_sizes_fwd.hh\"\n\nnamespace sdd {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief SDD at the deepest level.\ntemplate <typename C>\nusing flat_node = node<C, typename C::Values>;\n\n\/\/\/ @brief All but SDD at the deepest level.\ntemplate <typename C>\nusing hierarchical_node = node<C, SDD<C>>;\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Tag to describe the type of a node.\nenum class node_tag {flat, hierarchical};\n\n\/\/\/ @internal\n\/\/\/ @brief Signature of the meta-function that returns the node's type corresponding to the\n\/\/\/ given tag.\ntemplate <typename C, enum node_tag>\nstruct node_for_tag;\n\n\/\/\/ @internal\n\/\/\/ @brief Specialization for flat node.\ntemplate <typename C>\nstruct node_for_tag<C, node_tag::flat>\n{\n typedef flat_node<C> type;\n};\n\n\/\/\/ @internal\n\/\/\/ @brief Specialization for hierarchical node.\ntemplate <typename C>\nstruct node_for_tag<C, node_tag::hierarchical>\n{\n typedef hierarchical_node<C> type;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hierarchical Set Decision Diagram.\ntemplate <typename C>\nclass SDD final\n{\n\n static_assert( std::is_integral<typename C::Variable>::value\n , \"A variable must be an integral type.\");\n\nprivate:\n\n \/\/\/ @brief A canonized SDD.\n \/\/\/\n \/\/\/ This is the real recursive definition of an SDD: it can be a |0| or |1| terminal, or it\n \/\/\/ can be a flat or an hierachical node.\n typedef mem::variant< const zero_terminal<C>, const one_terminal<C>\n , const flat_node<C>, const hierarchical_node<C>>\n data_type;\n\n \/\/\/ @brief A unified and canonized SDD, meant to be stored in a unique table.\n \/\/\/\n \/\/\/ It is automatically erased when there is no more reference to it.\n typedef mem::ref_counted<const data_type> unique_type;\n\n \/\/\/ @brief Define the smart pointer around a unified SDD.\n \/\/\/\n \/\/\/ It handles the reference counting as well as the deletion of the SDD when it is no longer\n \/\/\/ referenced.\n typedef mem::ptr<const unique_type> ptr_type;\n\npublic:\n\n \/\/\/ @brief The type of variables.\n typedef typename C::Variable variable_type;\n\n \/\/\/ @brief The type of a set of values.\n typedef typename C::Values values_type;\n\n \/\/\/ @brief The type of a value in a set of values.\n typedef typename C::Values::value_type value_type;\n\nprivate:\n\n \/\/\/ @brief The real smart pointer around a unified SDD.\n ptr_type ptr_;\n\npublic:\n\n \/\/\/ @brief Move constructor.\n \/\/\/\n \/\/\/ O(1).\n SDD(SDD&&) noexcept = default;\n\n \/\/\/ @brief Move operator.\n \/\/\/\n \/\/\/ O(1).\n SDD&\n operator=(SDD&&) noexcept = default;\n\n \/\/\/ @brief Copy constructor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const SDD&) noexcept = default;\n\n \/\/\/ @brief Copy operator.\n \/\/\/\n \/\/\/ O(1).\n SDD&\n operator=(const SDD&) noexcept = default;\n\n \/\/\/ @internal\n \/\/\/ @brief Construct a terminal.\n \/\/\/ @param terminal If true, create the |1| terminal; the |0| terminal otherwise.\n \/\/\/ @return The terminal |0| or |1|.\n \/\/\/\n \/\/\/ O(1).\n SDD(bool terminal)\n : ptr_(terminal ? one_ptr() : zero_ptr())\n {\n }\n\n \/\/\/ @brief Construct a hierarchical SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values constructed from an initialization list.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1), for the creation of the SDD itself, but the complexity of the construction of the\n \/\/\/ set of values depends on values_type.\n SDD(const variable_type& var, std::initializer_list<value_type> values, const SDD& succ)\n : ptr_(create_node(var, values_type(values), SDD(succ)))\n {\n }\n\n \/\/\/ @brief Construct a flat SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, values_type&& val, const SDD& succ)\n : ptr_(create_node(var, std::move(val), succ))\n {\n }\n\n \/\/\/ @brief Construct a flat SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, const values_type& val, const SDD& succ)\n : ptr_(create_node(var, val, succ))\n {\n }\n\n \/\/\/ @brief Construct a hierarchical SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, an SDD in this case.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, const SDD& val, const SDD& succ)\n : ptr_(create_node(var, val, succ))\n {\n }\n\n \/\/\/ @brief Construct an SDD with an order.\n template <typename Initializer>\n SDD(const order<C>& o, const Initializer& init)\n : ptr_(one_ptr())\n {\n if (o.empty())\n {\n return;\n }\n \/\/ flat\n else if (o.nested().empty())\n {\n ptr_ = create_node(o.variable(), init(o.identifier()), SDD(o.next(), init));\n }\n \/\/ hierarchical\n else\n {\n ptr_ = create_node(o.variable(), SDD(o.nested(), init), SDD(o.next(), init));\n }\n }\n\n \/\/\/ @brief Indicate if the SDD is |0|.\n \/\/\/ @return true if the SDD is |0|, false otherwise.\n \/\/\/\n \/\/\/ O(1).\n bool\n empty()\n const noexcept\n {\n return ptr_ == zero_ptr();\n }\n\n \/\/\/ @brief Swap two SDD.\n \/\/\/\n \/\/\/ O(1).\n friend void\n swap(SDD& lhs, SDD& rhs)\n noexcept\n {\n using std::swap;\n swap(lhs.ptr_, rhs.ptr_);\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD from a ptr.\n \/\/\/\n \/\/\/ O(1).\n SDD(const ptr_type& ptr)\n noexcept\n : ptr_(ptr)\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD from a moved ptr.\n \/\/\/\n \/\/\/ O(1).\n SDD(ptr_type&& ptr)\n noexcept\n : ptr_(std::move(ptr))\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD, flat or hierarchical, with an alpha.\n \/\/\/ \\tparam Valuation If an SDD, constructs a hierarchical SDD; if a set of values,\n \/\/\/ constructs a flat SDD.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n SDD(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n : ptr_(create_node(var, std::move(builder)))\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the content of the SDD (an mem::ref_counted).\n \/\/\/\n \/\/\/ O(1).\n const unique_type&\n operator*()\n const noexcept\n {\n return *ptr_;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get a pointer to the content of the SDD (an mem::ref_counted).\n \/\/\/\n \/\/\/ O(1).\n const unique_type*\n operator->()\n const noexcept\n {\n return ptr_.operator->();\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the real smart pointer of the unified data.\n \/\/\/\n \/\/\/ O(1).\n ptr_type\n ptr()\n const noexcept\n {\n return ptr_;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Create the |0| terminal.\n \/\/\/\n \/\/\/ O(1). The |0| is cached in a static variable.\n static\n ptr_type\n zero_ptr()\n {\n static char* addr = mem::allocate<unique_type>();\n static unique_type* z = new (addr) unique_type(mem::construct<zero_terminal<C>>());\n static const ptr_type zero(mem::unify(z));\n return zero;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Create the |1| terminal.\n \/\/\/\n \/\/\/ O(1). The |1| is cached in a static variable.\n static\n ptr_type\n one_ptr()\n {\n static char* addr = mem::allocate<unique_type>();\n static unique_type* o = new (addr) unique_type(mem::construct<one_terminal<C>>());\n static const ptr_type one(mem::unify(o));\n return one;\n }\n\nprivate:\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, with only one arc.\n \/\/\/\n \/\/\/ O(1).\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, Valuation&& val, const SDD& succ)\n {\n if (succ.empty() or val.empty())\n {\n return zero_ptr();\n }\n else\n {\n dd::alpha_builder<C, Valuation> builder;\n builder.add(std::move(val), succ);\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, with only one arc.\n \/\/\/\n \/\/\/ O(1).\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, const Valuation& val, const SDD& succ)\n {\n if (succ.empty() or val.empty())\n {\n return zero_ptr();\n }\n else\n {\n dd::alpha_builder<C, Valuation> builder;\n builder.add(val, succ);\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, from an alpha.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n {\n if (builder.empty())\n {\n return zero_ptr();\n }\n else\n {\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to unify a node, flat or hierarchical, from an alpha.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n static\n const unique_type&\n unify_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n {\n \/\/ Will be erased by the unicity table, either it's an already existing node or a deletion\n \/\/ is requested by ptr.\n \/\/ Note that the alpha function is allocated right behind the node, thus extra care must be\n \/\/ taken. This is also why we use Boost.Intrusive in order to be able to manage memory\n \/\/ exactly the way we want.\n char* addr = mem::allocate<unique_type>(builder.size_to_allocate());\n unique_type* u =\n new (addr) unique_type(mem::construct<node<C, Valuation>>(), var, builder);\n return mem::unify(u);\n }\n\n friend void util::print_sizes<C>(std::ostream&);\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Equality of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nbool\noperator==(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return lhs.ptr() == rhs.ptr();\n}\n\n\/\/\/ @brief Inequality of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nbool\noperator!=(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return not (lhs.ptr() == rhs.ptr());\n}\n\n\/\/\/ @brief Comparison of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1). The order of SDD is arbitrary and can change at each run.\ntemplate <typename C>\ninline\nbool\noperator<(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return lhs.ptr() < rhs.ptr();\n}\n\n\/\/\/ @brief Export the textual representation of an SDD to a stream.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ Use only with small SDD, output can be huge.\ntemplate <typename C>\nstd::ostream&\noperator<<(std::ostream& os, const SDD<C>& x)\n{\n return os << x->data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Return the |0| terminal.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nSDD<C>\nzero()\nnoexcept\n{\n return {false};\n}\n\n\/\/\/ @brief Return the |1| terminal.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nSDD<C>\none()\nnoexcept\n{\n return {true};\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hash specialization for sdd::dd::SDD.\ntemplate <typename C>\nstruct hash<sdd::SDD<C>>\n{\n std::size_t\n operator()(const sdd::SDD<C>& x)\n const noexcept\n {\n return std::hash<decltype(x.ptr())>()(x.ptr());\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_DD_DEFINITION_HH_\n<commit_msg>SDD: zero_ptr() and one_ptr() are private.<commit_after>#ifndef _SDD_DD_DEFINITION_HH_\n#define _SDD_DD_DEFINITION_HH_\n\n#include <initializer_list>\n#include <type_traits> \/\/ is_integral\n\n#include \"sdd\/dd\/alpha.hh\"\n#include \"sdd\/dd\/definition_fwd.hh\"\n#include \"sdd\/dd\/node.hh\"\n#include \"sdd\/dd\/terminal.hh\"\n#include \"sdd\/mem\/ptr.hh\"\n#include \"sdd\/mem\/ref_counted.hh\"\n#include \"sdd\/mem\/variant.hh\"\n#include \"sdd\/order\/order.hh\"\n#include \"sdd\/util\/print_sizes_fwd.hh\"\n\nnamespace sdd {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief SDD at the deepest level.\ntemplate <typename C>\nusing flat_node = node<C, typename C::Values>;\n\n\/\/\/ @brief All but SDD at the deepest level.\ntemplate <typename C>\nusing hierarchical_node = node<C, SDD<C>>;\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Tag to describe the type of a node.\nenum class node_tag {flat, hierarchical};\n\n\/\/\/ @internal\n\/\/\/ @brief Signature of the meta-function that returns the node's type corresponding to the\n\/\/\/ given tag.\ntemplate <typename C, enum node_tag>\nstruct node_for_tag;\n\n\/\/\/ @internal\n\/\/\/ @brief Specialization for flat node.\ntemplate <typename C>\nstruct node_for_tag<C, node_tag::flat>\n{\n typedef flat_node<C> type;\n};\n\n\/\/\/ @internal\n\/\/\/ @brief Specialization for hierarchical node.\ntemplate <typename C>\nstruct node_for_tag<C, node_tag::hierarchical>\n{\n typedef hierarchical_node<C> type;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hierarchical Set Decision Diagram.\ntemplate <typename C>\nclass SDD final\n{\n\n static_assert( std::is_integral<typename C::Variable>::value\n , \"A variable must be an integral type.\");\n\nprivate:\n\n \/\/\/ @brief A canonized SDD.\n \/\/\/\n \/\/\/ This is the real recursive definition of an SDD: it can be a |0| or |1| terminal, or it\n \/\/\/ can be a flat or an hierachical node.\n typedef mem::variant< const zero_terminal<C>, const one_terminal<C>\n , const flat_node<C>, const hierarchical_node<C>>\n data_type;\n\n \/\/\/ @brief A unified and canonized SDD, meant to be stored in a unique table.\n \/\/\/\n \/\/\/ It is automatically erased when there is no more reference to it.\n typedef mem::ref_counted<const data_type> unique_type;\n\n \/\/\/ @brief Define the smart pointer around a unified SDD.\n \/\/\/\n \/\/\/ It handles the reference counting as well as the deletion of the SDD when it is no longer\n \/\/\/ referenced.\n typedef mem::ptr<const unique_type> ptr_type;\n\npublic:\n\n \/\/\/ @brief The type of variables.\n typedef typename C::Variable variable_type;\n\n \/\/\/ @brief The type of a set of values.\n typedef typename C::Values values_type;\n\n \/\/\/ @brief The type of a value in a set of values.\n typedef typename C::Values::value_type value_type;\n\nprivate:\n\n \/\/\/ @brief The real smart pointer around a unified SDD.\n ptr_type ptr_;\n\npublic:\n\n \/\/\/ @brief Move constructor.\n \/\/\/\n \/\/\/ O(1).\n SDD(SDD&&) noexcept = default;\n\n \/\/\/ @brief Move operator.\n \/\/\/\n \/\/\/ O(1).\n SDD&\n operator=(SDD&&) noexcept = default;\n\n \/\/\/ @brief Copy constructor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const SDD&) noexcept = default;\n\n \/\/\/ @brief Copy operator.\n \/\/\/\n \/\/\/ O(1).\n SDD&\n operator=(const SDD&) noexcept = default;\n\n \/\/\/ @internal\n \/\/\/ @brief Construct a terminal.\n \/\/\/ @param terminal If true, create the |1| terminal; the |0| terminal otherwise.\n \/\/\/ @return The terminal |0| or |1|.\n \/\/\/\n \/\/\/ O(1).\n SDD(bool terminal)\n : ptr_(terminal ? one_ptr() : zero_ptr())\n {\n }\n\n \/\/\/ @brief Construct a hierarchical SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values constructed from an initialization list.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1), for the creation of the SDD itself, but the complexity of the construction of the\n \/\/\/ set of values depends on values_type.\n SDD(const variable_type& var, std::initializer_list<value_type> values, const SDD& succ)\n : ptr_(create_node(var, values_type(values), SDD(succ)))\n {\n }\n\n \/\/\/ @brief Construct a flat SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, values_type&& val, const SDD& succ)\n : ptr_(create_node(var, std::move(val), succ))\n {\n }\n\n \/\/\/ @brief Construct a flat SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, a set of values.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, const values_type& val, const SDD& succ)\n : ptr_(create_node(var, val, succ))\n {\n }\n\n \/\/\/ @brief Construct a hierarchical SDD.\n \/\/\/ @param var The SDD's variable.\n \/\/\/ @param val The SDD's valuation, an SDD in this case.\n \/\/\/ @param succ The SDD's successor.\n \/\/\/\n \/\/\/ O(1).\n SDD(const variable_type& var, const SDD& val, const SDD& succ)\n : ptr_(create_node(var, val, succ))\n {\n }\n\n \/\/\/ @brief Construct an SDD with an order.\n template <typename Initializer>\n SDD(const order<C>& o, const Initializer& init)\n : ptr_(one_ptr())\n {\n if (o.empty())\n {\n return;\n }\n \/\/ flat\n else if (o.nested().empty())\n {\n ptr_ = create_node(o.variable(), init(o.identifier()), SDD(o.next(), init));\n }\n \/\/ hierarchical\n else\n {\n ptr_ = create_node(o.variable(), SDD(o.nested(), init), SDD(o.next(), init));\n }\n }\n\n \/\/\/ @brief Indicate if the SDD is |0|.\n \/\/\/ @return true if the SDD is |0|, false otherwise.\n \/\/\/\n \/\/\/ O(1).\n bool\n empty()\n const noexcept\n {\n return ptr_ == zero_ptr();\n }\n\n \/\/\/ @brief Swap two SDD.\n \/\/\/\n \/\/\/ O(1).\n friend void\n swap(SDD& lhs, SDD& rhs)\n noexcept\n {\n using std::swap;\n swap(lhs.ptr_, rhs.ptr_);\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD from a ptr.\n \/\/\/\n \/\/\/ O(1).\n SDD(const ptr_type& ptr)\n noexcept\n : ptr_(ptr)\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD from a moved ptr.\n \/\/\/\n \/\/\/ O(1).\n SDD(ptr_type&& ptr)\n noexcept\n : ptr_(std::move(ptr))\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Construct an SDD, flat or hierarchical, with an alpha.\n \/\/\/ \\tparam Valuation If an SDD, constructs a hierarchical SDD; if a set of values,\n \/\/\/ constructs a flat SDD.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n SDD(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n : ptr_(create_node(var, std::move(builder)))\n {\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the content of the SDD (an mem::ref_counted).\n \/\/\/\n \/\/\/ O(1).\n const unique_type&\n operator*()\n const noexcept\n {\n return *ptr_;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get a pointer to the content of the SDD (an mem::ref_counted).\n \/\/\/\n \/\/\/ O(1).\n const unique_type*\n operator->()\n const noexcept\n {\n return ptr_.operator->();\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Get the real smart pointer of the unified data.\n \/\/\/\n \/\/\/ O(1).\n ptr_type\n ptr()\n const noexcept\n {\n return ptr_;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Create the |0| terminal.\nprivate:\n\n \/\/\/\n \/\/\/ O(1). The |0| is cached in a static variable.\n static\n ptr_type\n zero_ptr()\n {\n static char* addr = mem::allocate<unique_type>();\n static unique_type* z = new (addr) unique_type(mem::construct<zero_terminal<C>>());\n static const ptr_type zero(mem::unify(z));\n return zero;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Create the |1| terminal.\n \/\/\/\n \/\/\/ O(1). The |1| is cached in a static variable.\n static\n ptr_type\n one_ptr()\n {\n static char* addr = mem::allocate<unique_type>();\n static unique_type* o = new (addr) unique_type(mem::construct<one_terminal<C>>());\n static const ptr_type one(mem::unify(o));\n return one;\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, with only one arc.\n \/\/\/\n \/\/\/ O(1).\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, Valuation&& val, const SDD& succ)\n {\n if (succ.empty() or val.empty())\n {\n return zero_ptr();\n }\n else\n {\n dd::alpha_builder<C, Valuation> builder;\n builder.add(std::move(val), succ);\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, with only one arc.\n \/\/\/\n \/\/\/ O(1).\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, const Valuation& val, const SDD& succ)\n {\n if (succ.empty() or val.empty())\n {\n return zero_ptr();\n }\n else\n {\n dd::alpha_builder<C, Valuation> builder;\n builder.add(val, succ);\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to create a node, flat or hierarchical, from an alpha.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n static\n ptr_type\n create_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n {\n if (builder.empty())\n {\n return zero_ptr();\n }\n else\n {\n return unify_node<Valuation>(var, std::move(builder));\n }\n }\n\n \/\/\/ @internal\n \/\/\/ @brief Helper function to unify a node, flat or hierarchical, from an alpha.\n \/\/\/\n \/\/\/ O(n) where n is the number of arcs in the builder.\n template <typename Valuation>\n static\n const unique_type&\n unify_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)\n {\n \/\/ Will be erased by the unicity table, either it's an already existing node or a deletion\n \/\/ is requested by ptr.\n \/\/ Note that the alpha function is allocated right behind the node, thus extra care must be\n \/\/ taken. This is also why we use Boost.Intrusive in order to be able to manage memory\n \/\/ exactly the way we want.\n char* addr = mem::allocate<unique_type>(builder.size_to_allocate());\n unique_type* u =\n new (addr) unique_type(mem::construct<node<C, Valuation>>(), var, builder);\n return mem::unify(u);\n }\n\n friend void util::print_sizes<C>(std::ostream&);\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Equality of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nbool\noperator==(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return lhs.ptr() == rhs.ptr();\n}\n\n\/\/\/ @brief Inequality of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nbool\noperator!=(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return not (lhs.ptr() == rhs.ptr());\n}\n\n\/\/\/ @brief Comparison of two SDD.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1). The order of SDD is arbitrary and can change at each run.\ntemplate <typename C>\ninline\nbool\noperator<(const SDD<C>& lhs, const SDD<C>& rhs)\nnoexcept\n{\n return lhs.ptr() < rhs.ptr();\n}\n\n\/\/\/ @brief Export the textual representation of an SDD to a stream.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ Use only with small SDD, output can be huge.\ntemplate <typename C>\nstd::ostream&\noperator<<(std::ostream& os, const SDD<C>& x)\n{\n return os << x->data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Return the |0| terminal.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nSDD<C>\nzero()\nnoexcept\n{\n return {false};\n}\n\n\/\/\/ @brief Return the |1| terminal.\n\/\/\/ @related SDD\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename C>\ninline\nSDD<C>\none()\nnoexcept\n{\n return {true};\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hash specialization for sdd::dd::SDD.\ntemplate <typename C>\nstruct hash<sdd::SDD<C>>\n{\n std::size_t\n operator()(const sdd::SDD<C>& x)\n const noexcept\n {\n return std::hash<decltype(x.ptr())>()(x.ptr());\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_DD_DEFINITION_HH_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2005-2008 SIPez LLC.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2004-2008 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ SYSTEM INCLUDES\n#include <stdlib.h>\n\n\/\/ APPLICATION INCLUDES\n#include <os\/OsConfigDb.h>\n#include \"sipXmediaFactoryImpl.h\"\n#include \"CpPhoneMediaInterface.h\"\n#include <sdp\/SdpCodec.h>\n#include <mp\/MpMediaTask.h>\n#include <mp\/MpMisc.h>\n#include <mp\/MpCodec.h>\n#include <mp\/MpCallFlowGraph.h>\n#include <mp\/dmaTask.h>\n#include <mp\/MpCodecFactory.h>\n#include <sdp\/SdpCodecList.h>\n#include \"mi\/CpMediaInterfaceFactoryFactory.h\"\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n#include <rtcp\/RTCManager.h>\n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n#include <mp\/NetInTask.h>\n#endif\n\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ GLOBAL FUNCTION\n\n#define MAX_MANAGED_FLOW_GRAPHS 16\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\nint sipXmediaFactoryImpl::miInstanceCount=0;\n\nCpMediaInterfaceFactory* spFactory = NULL;\nint siInstanceCount=0;\n\n#ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY\nextern \"C\" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb,\n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n \/\/ TODO: Add locking\n\n if (spFactory == NULL)\n {\n spFactory = new CpMediaInterfaceFactory();\n spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb,\n maxSamplesPerFrame, \n maxSamplesPerSec));\n } \n siInstanceCount++;\n\n \/\/ Assert some sane value\n assert(siInstanceCount < 11);\n return spFactory;\n}\n\nextern \"C\" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb,\n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n return(cpDefaultMediaFactoryFactory(pConfigDb, maxSamplesPerFrame, maxSamplesPerSec));\n}\n#endif\n\nextern \"C\" void sipxDestroyMediaFactoryFactory()\n{\n \/\/ TODO: Add locking\n\n if (siInstanceCount > 0)\n {\n siInstanceCount--;\n if (siInstanceCount == 0)\n {\n if (spFactory)\n {\n delete spFactory;\n spFactory = NULL;\n }\n }\n }\n}\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nsipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb, \n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n \/\/ See doxyegen comments for this constructor for information on the impact \n \/\/ of the values of maxSamplesPerFrame and maxSamplesPerSec.\n mMaxSamplesPerFrame = (maxSamplesPerFrame == 0) ? 16000 : maxSamplesPerFrame;\n mMaxSamplesPerSec = (maxSamplesPerSec == 0) ? 160 : maxSamplesPerSec;\n\n int maxFlowGraph = -1; \n UtlString strInBandDTMF;\n if (pConfigDb)\n {\n pConfigDb->get(\"PHONESET_MAX_ACTIVE_CALLS_ALLOWED\", maxFlowGraph);\n pConfigDb->get(\"PHONESET_SEND_INBAND_DTMF\", strInBandDTMF);\n strInBandDTMF.toUpper();\n\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::sipXmediaFactoryImpl\"\n \" maxFlowGraph = %d\",\n maxFlowGraph);\n }\n\n \/\/ Max Flow graphs\n if (maxFlowGraph <=0 ) \n {\n maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS;\n }\n\n \/\/ Start audio subsystem if still not started.\n if (miInstanceCount == 0)\n {\n mpStartUp(mMaxSamplesPerSec, mMaxSamplesPerFrame, 16*maxFlowGraph, pConfigDb, \n mnCodecPaths, mpCodecPaths);\n }\n\n \/\/ Should we send inband DTMF by default? \n if (strInBandDTMF.compareTo(\"DISABLE\") == 0)\n {\n MpCallFlowGraph::setInbandDTMF(false);\n }\n else\n {\n MpCallFlowGraph::setInbandDTMF(true);\n }\n\n \/\/ init the media processing task\n mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); \n\n#ifdef INCLUDE_RTCP \/* [ *\/\n mpiRTCPControl = CRTCManager::getRTCPControl();\n#endif \/* INCLUDE_RTCP ] *\/\n\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStartTasks(); \n#else\n if (OS_SUCCESS != startNetInTask()) \n {\n OsSysLog::add(FAC_MP, PRI_ERR, \"Could not start NetInTask!!\");\n }\n#endif\n }\n\n miGain = 7;\n ++miInstanceCount;\n\n \/\/ We are missing synchronization -- give the tasks time to start\n OsTask::delay(100);\n}\n\n\n\/\/ Destructor\nsipXmediaFactoryImpl::~sipXmediaFactoryImpl()\n{\n \/\/ TODO: Shutdown\n --miInstanceCount;\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStopTasks();\n#else\n shutdownNetInTask();\n#endif\n mpShutdown();\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nCpMediaInterface* sipXmediaFactoryImpl::createMediaInterface(const char* publicAddress,\n const char* localAddress,\n int numCodecs,\n SdpCodec* sdpCodecArray[],\n const char* locale,\n int expeditedIpTos,\n const char* szStunServer,\n int iStunPort,\n int iStunKeepAliveSecs,\n const char* szTurnServer,\n int iTurnPort,\n const char* szTurnUsername,\n const char* szTurnPassword,\n int iTurnKeepAlivePeriodSecs,\n UtlBoolean bEnableICE,\n uint32_t samplesPerFrame,\n uint32_t samplesPerSec) \n{\n return new CpPhoneMediaInterface(this, publicAddress, localAddress, \n numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer,\n iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, \n szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, \n bEnableICE, samplesPerFrame, samplesPerSec);\n}\n\n\nOsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) \n{\n OsStatus rc = OS_SUCCESS;\n MpCodec_setVolume(iVolume);\n\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setCallDevice(device.data());\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) \n{\n OsStatus rc;\n\n miGain = iGain;\n rc = MpCodec_setGain(miGain);\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setInputDevice(device.data());\n#ifdef WIN32\n dmaSignalMicDeviceChange();\n#endif\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) \n{\n if (bMute)\n {\n MpCodec_setGain(0);\n }\n else\n {\n MpCodec_setGain(miGain);\n }\n return OS_SUCCESS;\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode)\n{\n if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode))\n {\n return OS_SUCCESS;\n }\n else\n {\n return OS_NOT_SUPPORTED;\n }\n}\n\nOsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) \n{\n if (MpCallFlowGraph::setAGC(bEnable)) \n {\n return OS_SUCCESS;\n }\n else \n {\n return OS_NOT_SUPPORTED; \n }\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) \n{\n if (mode == MEDIA_NOISE_REDUCTION_DISABLED)\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(FALSE))\n {\n return OS_SUCCESS;\n }\n }\n else\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(TRUE))\n {\n return OS_SUCCESS;\n }\n }\n return OS_NOT_SUPPORTED;\n}\n\nOsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, \n const UtlString& sAudioPreferences,\n const UtlString& sVideoPreferences,\n int videoFormat,\n int* iRejected)\n{\n OsStatus rc = OS_FAILED;\n\n *iRejected = 0;\n\n if (pFactory)\n {\n pFactory->clearCodecs();\n\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sAudioPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sAudioPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sAudioPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory();\n pCodecFactory->addCodecsToList(*pFactory);\n\n *iRejected = 0;\n rc = OS_SUCCESS;\n }\n\n#ifdef VIDEO \/\/ [\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sVideoPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sVideoPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sVideoPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n SdpCodec::SdpCodecTypes videoCodecs[] = {};\n const int numVideoCodecs = sizeof(videoCodecs)\/sizeof(SdpCodec::SdpCodecTypes);\n\n *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs);\n rc = OS_SUCCESS;\n }\n#endif \/\/ VIDEO ]\n }\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) \n{\n return OS_NOT_SUPPORTED;\n}\n\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const\n{\n OsStatus rc = OS_SUCCESS;\n\n iVolume = MpCodec_getVolume();\n if (iVolume==-1)\n {\n rc = OS_FAILED;\n iVolume = 0;\n }\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getCallDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const\n{\n OsStatus rc = OS_SUCCESS;\n iGain = MpCodec_getGain();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getMicDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoQuality(int quality)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const \n{\n connectionId = -1;\n return OS_NOT_SUPPORTED;\n\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<commit_msg>Fix bug in sipXmediaFactoryImpl constructor - number of samples per second and per frame were messed. Also change default to 80\/8000. Let users to explicitely request WB support.<commit_after>\/\/\n\/\/ Copyright (C) 2005-2008 SIPez LLC.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2004-2008 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ SYSTEM INCLUDES\n#include <stdlib.h>\n\n\/\/ APPLICATION INCLUDES\n#include <os\/OsConfigDb.h>\n#include \"sipXmediaFactoryImpl.h\"\n#include \"CpPhoneMediaInterface.h\"\n#include <sdp\/SdpCodec.h>\n#include <mp\/MpMediaTask.h>\n#include <mp\/MpMisc.h>\n#include <mp\/MpCodec.h>\n#include <mp\/MpCallFlowGraph.h>\n#include <mp\/dmaTask.h>\n#include <mp\/MpCodecFactory.h>\n#include <sdp\/SdpCodecList.h>\n#include \"mi\/CpMediaInterfaceFactoryFactory.h\"\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n#include <rtcp\/RTCManager.h>\n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n#include <mp\/NetInTask.h>\n#endif\n\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ GLOBAL FUNCTION\n\n#define MAX_MANAGED_FLOW_GRAPHS 16\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\nint sipXmediaFactoryImpl::miInstanceCount=0;\n\nCpMediaInterfaceFactory* spFactory = NULL;\nint siInstanceCount=0;\n\n#ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY\nextern \"C\" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb,\n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n \/\/ TODO: Add locking\n\n if (spFactory == NULL)\n {\n spFactory = new CpMediaInterfaceFactory();\n spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb,\n maxSamplesPerFrame, \n maxSamplesPerSec));\n } \n siInstanceCount++;\n\n \/\/ Assert some sane value\n assert(siInstanceCount < 11);\n return spFactory;\n}\n\nextern \"C\" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb,\n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n return(cpDefaultMediaFactoryFactory(pConfigDb, maxSamplesPerFrame, maxSamplesPerSec));\n}\n#endif\n\nextern \"C\" void sipxDestroyMediaFactoryFactory()\n{\n \/\/ TODO: Add locking\n\n if (siInstanceCount > 0)\n {\n siInstanceCount--;\n if (siInstanceCount == 0)\n {\n if (spFactory)\n {\n delete spFactory;\n spFactory = NULL;\n }\n }\n }\n}\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nsipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb, \n uint32_t maxSamplesPerFrame, \n uint32_t maxSamplesPerSec)\n{\n \/\/ See Doxygen comments for this constructor for information on the impact \n \/\/ of the values of maxSamplesPerFrame and maxSamplesPerSec.\n mMaxSamplesPerFrame = (maxSamplesPerFrame == 0) ? 80 : maxSamplesPerFrame;\n mMaxSamplesPerSec = (maxSamplesPerSec == 0) ? 8000 : maxSamplesPerSec;\n\n int maxFlowGraph = -1; \n UtlString strInBandDTMF;\n if (pConfigDb)\n {\n pConfigDb->get(\"PHONESET_MAX_ACTIVE_CALLS_ALLOWED\", maxFlowGraph);\n pConfigDb->get(\"PHONESET_SEND_INBAND_DTMF\", strInBandDTMF);\n strInBandDTMF.toUpper();\n\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::sipXmediaFactoryImpl\"\n \" maxFlowGraph = %d\",\n maxFlowGraph);\n }\n\n \/\/ Max Flow graphs\n if (maxFlowGraph <=0 ) \n {\n maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS;\n }\n\n \/\/ Start audio subsystem if still not started.\n if (miInstanceCount == 0)\n {\n mpStartUp(mMaxSamplesPerSec, mMaxSamplesPerFrame, 16*maxFlowGraph, pConfigDb, \n mnCodecPaths, mpCodecPaths);\n }\n\n \/\/ Should we send inband DTMF by default? \n if (strInBandDTMF.compareTo(\"DISABLE\") == 0)\n {\n MpCallFlowGraph::setInbandDTMF(false);\n }\n else\n {\n MpCallFlowGraph::setInbandDTMF(true);\n }\n\n \/\/ init the media processing task\n mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); \n\n#ifdef INCLUDE_RTCP \/* [ *\/\n mpiRTCPControl = CRTCManager::getRTCPControl();\n#endif \/* INCLUDE_RTCP ] *\/\n\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStartTasks(); \n#else\n if (OS_SUCCESS != startNetInTask()) \n {\n OsSysLog::add(FAC_MP, PRI_ERR, \"Could not start NetInTask!!\");\n }\n#endif\n }\n\n miGain = 7;\n ++miInstanceCount;\n\n \/\/ We are missing synchronization -- give the tasks time to start\n OsTask::delay(100);\n}\n\n\n\/\/ Destructor\nsipXmediaFactoryImpl::~sipXmediaFactoryImpl()\n{\n \/\/ TODO: Shutdown\n --miInstanceCount;\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStopTasks();\n#else\n shutdownNetInTask();\n#endif\n mpShutdown();\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nCpMediaInterface* sipXmediaFactoryImpl::createMediaInterface(const char* publicAddress,\n const char* localAddress,\n int numCodecs,\n SdpCodec* sdpCodecArray[],\n const char* locale,\n int expeditedIpTos,\n const char* szStunServer,\n int iStunPort,\n int iStunKeepAliveSecs,\n const char* szTurnServer,\n int iTurnPort,\n const char* szTurnUsername,\n const char* szTurnPassword,\n int iTurnKeepAlivePeriodSecs,\n UtlBoolean bEnableICE,\n uint32_t samplesPerFrame,\n uint32_t samplesPerSec) \n{\n return new CpPhoneMediaInterface(this, publicAddress, localAddress, \n numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer,\n iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, \n szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, \n bEnableICE, samplesPerFrame, samplesPerSec);\n}\n\n\nOsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) \n{\n OsStatus rc = OS_SUCCESS;\n MpCodec_setVolume(iVolume);\n\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setCallDevice(device.data());\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) \n{\n OsStatus rc;\n\n miGain = iGain;\n rc = MpCodec_setGain(miGain);\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setInputDevice(device.data());\n#ifdef WIN32\n dmaSignalMicDeviceChange();\n#endif\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) \n{\n if (bMute)\n {\n MpCodec_setGain(0);\n }\n else\n {\n MpCodec_setGain(miGain);\n }\n return OS_SUCCESS;\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode)\n{\n if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode))\n {\n return OS_SUCCESS;\n }\n else\n {\n return OS_NOT_SUPPORTED;\n }\n}\n\nOsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) \n{\n if (MpCallFlowGraph::setAGC(bEnable)) \n {\n return OS_SUCCESS;\n }\n else \n {\n return OS_NOT_SUPPORTED; \n }\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) \n{\n if (mode == MEDIA_NOISE_REDUCTION_DISABLED)\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(FALSE))\n {\n return OS_SUCCESS;\n }\n }\n else\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(TRUE))\n {\n return OS_SUCCESS;\n }\n }\n return OS_NOT_SUPPORTED;\n}\n\nOsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, \n const UtlString& sAudioPreferences,\n const UtlString& sVideoPreferences,\n int videoFormat,\n int* iRejected)\n{\n OsStatus rc = OS_FAILED;\n\n *iRejected = 0;\n\n if (pFactory)\n {\n pFactory->clearCodecs();\n\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sAudioPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sAudioPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sAudioPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory();\n pCodecFactory->addCodecsToList(*pFactory);\n\n *iRejected = 0;\n rc = OS_SUCCESS;\n }\n\n#ifdef VIDEO \/\/ [\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sVideoPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sVideoPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sVideoPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n SdpCodec::SdpCodecTypes videoCodecs[] = {};\n const int numVideoCodecs = sizeof(videoCodecs)\/sizeof(SdpCodec::SdpCodecTypes);\n\n *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs);\n rc = OS_SUCCESS;\n }\n#endif \/\/ VIDEO ]\n }\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) \n{\n return OS_NOT_SUPPORTED;\n}\n\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const\n{\n OsStatus rc = OS_SUCCESS;\n\n iVolume = MpCodec_getVolume();\n if (iVolume==-1)\n {\n rc = OS_FAILED;\n iVolume = 0;\n }\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getCallDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const\n{\n OsStatus rc = OS_SUCCESS;\n iGain = MpCodec_getGain();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getMicDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoQuality(int quality)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const \n{\n connectionId = -1;\n return OS_NOT_SUPPORTED;\n\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cstring> \/* std::strlen(const char*) *\/\n#include <cctype> \/* std::tolower(int) *\/\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 11) * 5;\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t numbers[2] = {0, 0}; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = -1;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.0, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2)\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n numbers[i-1] = parser.getResult();\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n int width = static_cast<int> (std::strlen(\"Sieve size\"));\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(width) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(width) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n\n if (!quietMode)\n std::cout << std::setw(width) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(numbers[0]);\n primeSieve.setStopNumber(numbers[1]);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n\n if (threads == -1)\n threads = primeSieve.getIdealThreadCount();\n if (!quietMode)\n std::cout << std::setw(width) << \"Threads\" << \" = \" << threads << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve(threads);\n if ((flags & PRINT_STATUS) || (flags & PRINT_FLAGS))\n std::cout << std::endl;\n\n \/\/ get max output string length\n width = static_cast<int> (std::strlen(\"Time elapsed\"));\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i)) {\n int length = static_cast<int> (primes[i].length());\n if (width < length)\n width = length;\n }\n }\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(width) << primes[i] << \" : \" <<\n primeSieve.getCounts(i) << std::endl;\n }\n std::cout << std::setw(width) << \"Time elapsed\" << \" : \" <<\n primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<commit_msg>updated for primesieve 2.0 release<commit_after>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cctype> \/* std::tolower(int) *\/\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 11) * 5;\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t numbers[2] = {0, 0}; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = -1;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.0, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2)\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n numbers[i-1] = parser.getResult();\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(10) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(10) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n\n if (!quietMode)\n std::cout << std::setw(10) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n \/\/ init primeSieve\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(numbers[0]);\n primeSieve.setStopNumber(numbers[1]);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n\n if (threads == -1)\n threads = primeSieve.getIdealThreadCount();\n if (!quietMode)\n std::cout << std::setw(10) << \"Threads\" << \" = \" << threads << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve(threads);\n\n \/\/ print new line\n if ((flags & PRINT_STATUS) || (\n (flags & PRINT_FLAGS) &&\n (flags & COUNT_FLAGS) ))\n std::cout << std::endl;\n\n \/\/ get max output width\n std::size_t width = (quietMode) ?0 :12;\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if ((flags & (COUNT_PRIMES << i)) && width < primes[i].length())\n width = primes[i].length();\n\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++)\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(static_cast<int> (width)) << primes[i] << \" : \"\n << primeSieve.getCounts(i) << std::endl;\n\n \/\/ print time elapsed\n if (!quietMode)\n std::cout << std::setw(static_cast<int> (width)) << \"Time elapsed\" << \" : \"\n << primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1213369 Untrusted value as argument<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2012 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/detail\/temporary_array.h>\n#include <thrust\/merge.h>\n#include <thrust\/system\/detail\/sequential\/insertion_sort.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace detail\n{\nnamespace sequential\n{\nnamespace stable_merge_sort_detail\n{\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid inplace_merge(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator middle,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;\n\n thrust::detail::temporary_array<value_type, DerivedPolicy> a(exec, first, middle);\n thrust::detail::temporary_array<value_type, DerivedPolicy> b(exec, middle, last);\n\n thrust::merge(exec, a.begin(), a.end(), b.begin(), b.end(), first, comp);\n}\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid inplace_merge_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 middle1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;\n\n RandomAccessIterator2 middle2 = first2 + (middle1 - first1);\n RandomAccessIterator2 last2 = first2 + (last1 - first1);\n\n thrust::detail::temporary_array<value_type1, DerivedPolicy> lhs1(exec, first1, middle1);\n thrust::detail::temporary_array<value_type1, DerivedPolicy> rhs1(exec, middle1, last1);\n thrust::detail::temporary_array<value_type2, DerivedPolicy> lhs2(exec, first2, middle2);\n thrust::detail::temporary_array<value_type2, DerivedPolicy> rhs2(exec, middle2, last2);\n\n thrust::merge_by_key(exec,\n lhs1.begin(), lhs1.end(),\n rhs1.begin(), rhs1.end(),\n lhs2.begin(), rhs2.begin(),\n first1, first2,\n comp);\n}\n\n\n} \/\/ end namespace stable_merge_sort_detail\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n if(last - first < 32)\n {\n thrust::system::detail::sequential::insertion_sort(first, last, comp);\n }\n else\n {\n RandomAccessIterator middle = first + (last - first) \/ 2;\n\n thrust::system::detail::sequential::stable_merge_sort(exec, first, middle, comp);\n thrust::system::detail::sequential::stable_merge_sort(exec, middle, last, comp);\n stable_merge_sort_detail::inplace_merge(exec, first, middle, last, comp);\n }\n}\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n StrictWeakOrdering comp)\n{\n if(last1 - first1 <= 32)\n {\n thrust::system::detail::sequential::insertion_sort_by_key(first1, last1, first2, comp);\n }\n else\n {\n RandomAccessIterator1 middle1 = first1 + (last1 - first1) \/ 2;\n RandomAccessIterator2 middle2 = first2 + (last1 - first1) \/ 2;\n\n thrust::system::detail::sequential::stable_merge_sort_by_key(exec, first1, middle1, first2, comp);\n thrust::system::detail::sequential::stable_merge_sort_by_key(exec, middle1, last1, middle2, comp);\n stable_merge_sort_detail::inplace_merge_by_key(exec, first1, middle1, last1, first2, comp);\n }\n}\n\n\n} \/\/ end namespace sequential\n} \/\/ end namespace detail\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<commit_msg>Avoid recursion in sequential merge sort in CUDA threads.<commit_after>\/*\n * Copyright 2008-2012 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/detail\/temporary_array.h>\n#include <thrust\/merge.h>\n#include <thrust\/system\/detail\/sequential\/insertion_sort.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace detail\n{\nnamespace sequential\n{\nnamespace stable_merge_sort_detail\n{\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid inplace_merge(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator middle,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;\n\n thrust::detail::temporary_array<value_type, DerivedPolicy> a(exec, first, middle);\n thrust::detail::temporary_array<value_type, DerivedPolicy> b(exec, middle, last);\n\n thrust::merge(exec, a.begin(), a.end(), b.begin(), b.end(), first, comp);\n}\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid inplace_merge_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 middle1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;\n\n RandomAccessIterator2 middle2 = first2 + (middle1 - first1);\n RandomAccessIterator2 last2 = first2 + (last1 - first1);\n\n thrust::detail::temporary_array<value_type1, DerivedPolicy> lhs1(exec, first1, middle1);\n thrust::detail::temporary_array<value_type1, DerivedPolicy> rhs1(exec, middle1, last1);\n thrust::detail::temporary_array<value_type2, DerivedPolicy> lhs2(exec, first2, middle2);\n thrust::detail::temporary_array<value_type2, DerivedPolicy> rhs2(exec, middle2, last2);\n\n thrust::merge_by_key(exec,\n lhs1.begin(), lhs1.end(),\n rhs1.begin(), rhs1.end(),\n lhs2.begin(), rhs2.begin(),\n first1, first2,\n comp);\n}\n\n\ntemplate<typename RandomAccessIterator,\n typename Size,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid insertion_sort_each(RandomAccessIterator first,\n RandomAccessIterator last,\n Size partition_size,\n StrictWeakOrdering comp)\n{\n if(partition_size > 1)\n {\n for(; first < last; first += partition_size)\n {\n RandomAccessIterator partition_last = thrust::min(last, first + partition_size);\n\n thrust::system::detail::sequential::insertion_sort(first, partition_last, comp);\n } \/\/ end for\n } \/\/ end if\n} \/\/ end insertion_sort_each()\n\n\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename Size,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid insertion_sort_each_by_key(RandomAccessIterator1 keys_first,\n RandomAccessIterator1 keys_last,\n RandomAccessIterator2 values_first,\n Size partition_size,\n StrictWeakOrdering comp)\n{\n if(partition_size > 1)\n {\n for(; keys_first < keys_last; keys_first += partition_size, values_first += partition_size)\n {\n RandomAccessIterator1 keys_partition_last = thrust::min(keys_last, keys_first + partition_size);\n\n thrust::system::detail::sequential::insertion_sort_by_key(keys_first, keys_partition_last, values_first, comp);\n } \/\/ end for\n } \/\/ end if\n} \/\/ end insertion_sort_each()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename Size,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid merge_adjacent_partitions(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first,\n RandomAccessIterator1 last,\n Size partition_size,\n RandomAccessIterator2 result,\n StrictWeakOrdering comp)\n{\n for(; first < last; first += 2 * partition_size, result += 2 * partition_size)\n {\n RandomAccessIterator1 interval_middle = thrust::min(last, first + partition_size);\n RandomAccessIterator1 interval_last = thrust::min(last, interval_middle + partition_size);\n\n thrust::merge(exec,\n first, interval_middle,\n interval_middle, interval_last,\n result,\n comp);\n } \/\/ end for\n} \/\/ end merge_adjacent_partitions()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename Size,\n typename RandomAccessIterator3,\n typename RandomAccessIterator4,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid merge_adjacent_partitions_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 keys_first,\n RandomAccessIterator1 keys_last,\n RandomAccessIterator2 values_first,\n Size partition_size,\n RandomAccessIterator3 keys_result,\n RandomAccessIterator4 values_result,\n StrictWeakOrdering comp)\n{\n for(;\n keys_first < keys_last;\n keys_first += 2 * partition_size, values_first += 2 * partition_size, keys_result += 2 * partition_size, values_result += 2 * partition_size)\n {\n RandomAccessIterator1 keys_interval_middle = thrust::min(keys_last, keys_first + partition_size);\n RandomAccessIterator1 keys_interval_last = thrust::min(keys_last, keys_interval_middle + partition_size);\n\n RandomAccessIterator2 values_first2 = values_first + (keys_interval_last - keys_interval_middle);\n\n thrust::merge_by_key(exec,\n keys_first, keys_interval_middle,\n keys_interval_middle, keys_interval_last,\n values_first,\n values_first2,\n keys_result,\n values_result,\n comp);\n } \/\/ end for\n} \/\/ end merge_adjacent_partitions()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid iterative_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator>::type value_type;\n typedef typename thrust::iterator_difference<RandomAccessIterator>::type difference_type;\n\n difference_type n = last - first;\n\n thrust::detail::temporary_array<value_type, DerivedPolicy> temp(exec, n);\n\n \/\/ insertion sort each 32 element partition\n difference_type partition_size = 32;\n insertion_sort_each(first, last, partition_size, comp);\n\n \/\/ ping indicates whether or not the latest data is in the source range [first, last)\n bool ping = true;\n\n \/\/ merge adjacent partitions until the partition size covers the entire range\n for(;\n partition_size < n;\n partition_size *= 2, ping = !ping)\n {\n if(ping)\n {\n merge_adjacent_partitions(exec, first, last, partition_size, temp.begin(), comp);\n } \/\/ end if\n else\n {\n merge_adjacent_partitions(exec, temp.begin(), temp.end(), partition_size, first, comp);\n } \/\/ end else\n } \/\/ end for m\n\n if(!ping)\n {\n thrust::copy(exec, temp.begin(), temp.end(), first);\n } \/\/ end if\n} \/\/ end iterative_stable_merge_sort()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid iterative_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 keys_first,\n RandomAccessIterator1 keys_last,\n RandomAccessIterator2 values_first,\n StrictWeakOrdering comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type1;\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type value_type2;\n typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;\n\n difference_type n = keys_last - keys_first;\n\n thrust::detail::temporary_array<value_type1, DerivedPolicy> keys_temp(exec, n);\n thrust::detail::temporary_array<value_type2, DerivedPolicy> values_temp(exec, n);\n\n \/\/ insertion sort each 32 element partition\n difference_type partition_size = 32;\n insertion_sort_each_by_key(keys_first, keys_last, values_first, partition_size, comp);\n\n \/\/ ping indicates whether or not the latest data is in the source range [first, last)\n bool ping = true;\n\n \/\/ merge adjacent partitions until the partition size covers the entire range\n for(;\n partition_size < n;\n partition_size *= 2, ping = !ping)\n {\n if(ping)\n {\n merge_adjacent_partitions_by_key(exec, keys_first, keys_last, values_first, partition_size, keys_temp.begin(), values_temp.begin(), comp);\n } \/\/ end if\n else\n {\n merge_adjacent_partitions_by_key(exec, keys_temp.begin(), keys_temp.end(), values_temp.begin(), partition_size, keys_first, values_first, comp);\n } \/\/ end else\n } \/\/ end for m\n\n if(!ping)\n {\n thrust::copy(exec, keys_temp.begin(), keys_temp.end(), keys_first);\n thrust::copy(exec, values_temp.begin(), values_temp.end(), values_first);\n } \/\/ end if\n} \/\/ end iterative_stable_merge_sort()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid recursive_stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n if(last - first < 32)\n {\n thrust::system::detail::sequential::insertion_sort(first, last, comp);\n } \/\/ end if\n else\n {\n RandomAccessIterator middle = first + (last - first) \/ 2;\n\n stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, middle, comp);\n stable_merge_sort_detail::recursive_stable_merge_sort(exec, middle, last, comp);\n stable_merge_sort_detail::inplace_merge(exec, first, middle, last, comp);\n } \/\/ end else\n} \/\/ end recursive_stable_merge_sort()\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid recursive_stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n StrictWeakOrdering comp)\n{\n if(last1 - first1 <= 32)\n {\n thrust::system::detail::sequential::insertion_sort_by_key(first1, last1, first2, comp);\n } \/\/ end if\n else\n {\n RandomAccessIterator1 middle1 = first1 + (last1 - first1) \/ 2;\n RandomAccessIterator2 middle2 = first2 + (last1 - first1) \/ 2;\n\n stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, middle1, first2, comp);\n stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, middle1, last1, middle2, comp);\n stable_merge_sort_detail::inplace_merge_by_key(exec, first1, middle1, last1, first2, comp);\n } \/\/ end else\n} \/\/ end recursive_stable_merge_sort_by_key()\n\n\n} \/\/ end namespace stable_merge_sort_detail\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid stable_merge_sort(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator first,\n RandomAccessIterator last,\n StrictWeakOrdering comp)\n{\n \/\/ avoid recursion in CUDA threads\n#ifdef __CUDA_ARCH__\n stable_merge_sort_detail::iterative_stable_merge_sort(exec, first, last, comp);\n#else\n stable_merge_sort_detail::recursive_stable_merge_sort(exec, first, last, comp);\n#endif\n}\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2,\n typename StrictWeakOrdering>\n__host__ __device__\nvoid stable_merge_sort_by_key(sequential::execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n StrictWeakOrdering comp)\n{\n \/\/ avoid recursion in CUDA threads\n#ifdef __CUDA_ARCH__\n stable_merge_sort_detail::iterative_stable_merge_sort_by_key(exec, first1, last1, first2, comp);\n#else\n stable_merge_sort_detail::recursive_stable_merge_sort_by_key(exec, first1, last1, first2, comp);\n#endif\n}\n\n\n} \/\/ end namespace sequential\n} \/\/ end namespace detail\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdentColoredPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkIdentColoredPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkConfigure.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolygon.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkTriangle.h\"\n#include \"vtkIdTypeArray.h\"\n\n#ifndef VTK_IMPLEMENT_MESA_CXX\n# include \"vtkOpenGL.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkIdentColoredPainter, \"1.15\");\nvtkStandardNewMacro(vtkIdentColoredPainter);\n\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)? \n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)? \n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)? \n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)? \n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::vtkIdentColoredPainter()\n{\n this->ColorMode = COLORBYIDENT;\n this->ResetCurrentId();\n\n this->ActorIds = NULL;\n this->PropAddrs = NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::~vtkIdentColoredPainter()\n{\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByConstant(unsigned int constant)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n this->CurrentIdPlane0 = constant;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)\n{\n \/\/free whatever we were given before this\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n \n \/\/sanity checking\n if (props == NULL || \n ids == NULL || \n (ids->GetNumberOfComponents() != 1) ||\n (ids->GetNumberOfTuples() == 0))\n {\n vtkWarningMacro(\"Invalid actor-id lookup table supplied.\");\n return;\n }\n\n \/\/copy over the new lookup table\n this->ActorIds = ids;\n this->ActorIds->Register(this);\n this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];\n for (int i = 0; i < ids->GetNumberOfTuples(); i++)\n {\n this->PropAddrs[i] = props[i];\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n\n vtkIdType maxId = 0;\n int numIds = 0;\n if (this->ActorIds != NULL)\n {\n numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i< numIds; i++)\n {\n vtkIdType nextId = this->ActorIds->GetValue(i);\n if (actorAddr == this->PropAddrs[i])\n {\n this->CurrentIdPlane0 = nextId + 1; \n return;\n }\n if (nextId > maxId)\n {\n maxId = nextId;\n }\n }\n }\n\n \/\/we didn't find the actor in the table, make up an ID and add it\n \/\/cerr << \"ID not found for actor \" << actorAddr \n \/\/ << \" using \" << maxId+1 << endl;\n vtkIdTypeArray *arr = vtkIdTypeArray::New();\n arr->SetNumberOfComponents(1);\n arr->SetNumberOfTuples(numIds+1);\n vtkProp **SaveProps = new vtkProp*[numIds+1];\n if (this->ActorIds != NULL)\n {\n for (int i = 0; i< numIds; i++)\n {\n arr->SetValue(i, this->ActorIds->GetValue(i));\n SaveProps[i] = this->PropAddrs[i];\n }\n }\n arr->SetValue(numIds, maxId+1);\n SaveProps[numIds] = actorAddr;\n this->MakeActorLookupTable(SaveProps, arr);\n arr->Delete();\n\n this->CurrentIdPlane0 = maxId+1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)\n{\n this->ColorMode = COLORBYIDENT;\n this->Plane = (plane < 3)?plane:2;\n this->ResetCurrentId();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ResetCurrentId() \n{\n \/\/do not use 0, it is reserved for miss\n this->CurrentIdPlane0 = 1;\n this->CurrentIdPlane1 = 1;\n this->CurrentIdPlane2 = 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::IncrementCurrentId()\n{\n if (this->ColorMode == COLORBYCONST)\n {\n return;\n }\n\n \/\/the limits are set up assuming 24 bits total for each for RGB pixel\n \/\/do not use A because the parallel compositing code does not support Alpha\n this->CurrentIdPlane0++;\n if (this->CurrentIdPlane0 >= 0x01000000)\n {\n this->CurrentIdPlane0 = 0x00000001;\n this->CurrentIdPlane1++;\n if (this->CurrentIdPlane1 >= 0x01000000)\n {\n this->CurrentIdPlane1 = 0x00000001;\n this->CurrentIdPlane2++;\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)\n{\n unsigned int val = this->CurrentIdPlane0;\n if (this->ColorMode == COLORBYIDENT)\n {\n if (this->Plane == 1)\n {\n val = this->CurrentIdPlane1;\n }\n else if (this->Plane == 2)\n {\n val = this->CurrentIdPlane2;\n }\n }\n\n \/\/cerr << \"Curr Color is \" \n \/\/ << this->ColorMode << \" \"\n \/\/ << this->CurrentIdPlane2 << \":\"\n \/\/ << this->CurrentIdPlane1 << \":\"\n \/\/ << this->CurrentIdPlane0 << endl;\n\n RGB[0] = (val & 0x00FF0000)>>16;\n RGB[1] = (val & 0x0000FF00)>>8;\n RGB[2] = (val & 0x000000FF);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer, \n vtkActor* actor, \n unsigned long typeflags)\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n if (!device)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n this->TotalCells = \n vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);\n\n this->Timer->StartTimer();\n\n \/\/turn off antialising and lighting so that the colors we draw will be the\n \/\/colors we read back\n int origMultisample = device->QueryMultisampling();\n int origLighting = device->QueryLighting();\n int origBlending = device->QueryBlending();\n\n device->MakeMultisampling(0);\n device->MakeLighting(0);\n device->MakeBlending(0);\n\n vtkIdType startCell = 0;\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfVerts();\n\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfLines();\n\n if (typeflags & vtkPainter::POLYS)\n {\n#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))\n if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)\n {\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n else\n#endif\n {\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n }\n \n startCell += this->PolyData->GetNumberOfPolys();\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n }\n\n \/\/reset lighting back to the default\n device->MakeBlending(origBlending);\n device->MakeLighting(origLighting);\n device->MakeMultisampling(origMultisample);\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n\n \/\/ let the superclass pass on the request to delegate painter.\n \/\/ Ofcouse, more than likely, this call will never have a delegate,\n \/\/ but anyways.\n this->Superclass::RenderInternal(renderer, actor, typeflags);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,\n vtkIdType startCellId, \n vtkRenderer *renderer)\n{\n if (!this->PolyData)\n {\n vtkWarningMacro(\"No polydata to render!\");\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = this->PolyData->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n \n \/\/ fieldColors are same as cell colors except when rendering \n \/\/ VTK_TRIANGLE_STRIP, when they represent triangle colors.\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n\n this->IncrementCurrentId();\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n \/\/ If using field colors, then we must send triangle colors, \n \/\/ if rendering triangle strips.\n if (mode == VTK_TRIANGLE_STRIP && cellpointi > 2)\n {\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n\n this->IncrementCurrentId();\n }\n \n \/\/ Send the point position as the last attribute.\n \/\/ TODO: how to mark that point position is being sent? since,\n \/\/ vtkDataSetAttributes doesn't define point positions and hence has\n \/\/ no enum for that. For now, vtkPointData::NUM_ATTRIBUTES marks\n \/\/ point positions.\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, \n pointtype, voidpoints, 3*pointId);\n }\n device->EndPrimitive();\n\n cellId++;\n\n if (count == 10000) \n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast<double>(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n \n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<commit_msg>BUG: Fix selection on polydata with triangle strips. Took out my partial attempt to give each tri within the strip its own id. Now selection of any tri in the strip will simply return the id for the whole strip.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdentColoredPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkIdentColoredPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkConfigure.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolygon.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkTriangle.h\"\n#include \"vtkIdTypeArray.h\"\n\n#ifndef VTK_IMPLEMENT_MESA_CXX\n# include \"vtkOpenGL.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkIdentColoredPainter, \"1.16\");\nvtkStandardNewMacro(vtkIdentColoredPainter);\n\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)? \n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)? \n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)? \n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)? \n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::vtkIdentColoredPainter()\n{\n this->ColorMode = COLORBYIDENT;\n this->ResetCurrentId();\n\n this->ActorIds = NULL;\n this->PropAddrs = NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::~vtkIdentColoredPainter()\n{\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByConstant(unsigned int constant)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n this->CurrentIdPlane0 = constant;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)\n{\n \/\/free whatever we were given before this\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n \n \/\/sanity checking\n if (props == NULL || \n ids == NULL || \n (ids->GetNumberOfComponents() != 1) ||\n (ids->GetNumberOfTuples() == 0))\n {\n vtkWarningMacro(\"Invalid actor-id lookup table supplied.\");\n return;\n }\n\n \/\/copy over the new lookup table\n this->ActorIds = ids;\n this->ActorIds->Register(this);\n this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];\n for (int i = 0; i < ids->GetNumberOfTuples(); i++)\n {\n this->PropAddrs[i] = props[i];\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n\n vtkIdType maxId = 0;\n int numIds = 0;\n if (this->ActorIds != NULL)\n {\n numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i< numIds; i++)\n {\n vtkIdType nextId = this->ActorIds->GetValue(i);\n if (actorAddr == this->PropAddrs[i])\n {\n this->CurrentIdPlane0 = nextId + 1; \n return;\n }\n if (nextId > maxId)\n {\n maxId = nextId;\n }\n }\n }\n\n \/\/we didn't find the actor in the table, make up an ID and add it\n \/\/cerr << \"ID not found for actor \" << actorAddr \n \/\/ << \" using \" << maxId+1 << endl;\n vtkIdTypeArray *arr = vtkIdTypeArray::New();\n arr->SetNumberOfComponents(1);\n arr->SetNumberOfTuples(numIds+1);\n vtkProp **SaveProps = new vtkProp*[numIds+1];\n if (this->ActorIds != NULL)\n {\n for (int i = 0; i< numIds; i++)\n {\n arr->SetValue(i, this->ActorIds->GetValue(i));\n SaveProps[i] = this->PropAddrs[i];\n }\n }\n arr->SetValue(numIds, maxId+1);\n SaveProps[numIds] = actorAddr;\n this->MakeActorLookupTable(SaveProps, arr);\n arr->Delete();\n\n this->CurrentIdPlane0 = maxId+1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)\n{\n this->ColorMode = COLORBYIDENT;\n this->Plane = (plane < 3)?plane:2;\n this->ResetCurrentId();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ResetCurrentId() \n{\n \/\/do not use 0, it is reserved for miss\n this->CurrentIdPlane0 = 1;\n this->CurrentIdPlane1 = 1;\n this->CurrentIdPlane2 = 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::IncrementCurrentId()\n{\n if (this->ColorMode == COLORBYCONST)\n {\n return;\n }\n\n \/\/the limits are set up assuming 24 bits total for each for RGB pixel\n \/\/do not use A because the parallel compositing code does not support Alpha\n this->CurrentIdPlane0++;\n if (this->CurrentIdPlane0 >= 0x01000000)\n {\n this->CurrentIdPlane0 = 0x00000001;\n this->CurrentIdPlane1++;\n if (this->CurrentIdPlane1 >= 0x01000000)\n {\n this->CurrentIdPlane1 = 0x00000001;\n this->CurrentIdPlane2++;\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)\n{\n unsigned int val = this->CurrentIdPlane0;\n if (this->ColorMode == COLORBYIDENT)\n {\n if (this->Plane == 1)\n {\n val = this->CurrentIdPlane1;\n }\n else if (this->Plane == 2)\n {\n val = this->CurrentIdPlane2;\n }\n }\n\n \/\/cerr << \"Curr Color is \" \n \/\/ << this->ColorMode << \" \"\n \/\/ << this->CurrentIdPlane2 << \":\"\n \/\/ << this->CurrentIdPlane1 << \":\"\n \/\/ << this->CurrentIdPlane0 << endl;\n\n RGB[0] = (val & 0x00FF0000)>>16;\n RGB[1] = (val & 0x0000FF00)>>8;\n RGB[2] = (val & 0x000000FF);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer, \n vtkActor* actor, \n unsigned long typeflags)\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n if (!device)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n this->TotalCells = \n vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);\n\n this->Timer->StartTimer();\n\n \/\/turn off antialising and lighting so that the colors we draw will be the\n \/\/colors we read back\n int origMultisample = device->QueryMultisampling();\n int origLighting = device->QueryLighting();\n int origBlending = device->QueryBlending();\n\n device->MakeMultisampling(0);\n device->MakeLighting(0);\n device->MakeBlending(0);\n\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfVerts();\n\n if (typeflags & vtkPainter::LINES)\n {\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfLines();\n\n if (typeflags & vtkPainter::POLYS)\n {\n#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))\n if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)\n {\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n else\n#endif\n {\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n } \n startCell += this->PolyData->GetNumberOfPolys();\n\n if (typeflags & vtkPainter::STRIPS)\n {\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfStrips();\n\n \/\/reset lighting back to the default\n device->MakeBlending(origBlending);\n device->MakeLighting(origLighting);\n device->MakeMultisampling(origMultisample);\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n\n \/\/ let the superclass pass on the request to delegate painter.\n \/\/ Ofcouse, more than likely, this call will never have a delegate,\n \/\/ but anyways.\n this->Superclass::RenderInternal(renderer, actor, typeflags);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,\n vtkIdType startCellId, \n vtkRenderer *renderer)\n{\n if (!this->PolyData)\n {\n vtkWarningMacro(\"No polydata to render!\");\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = this->PolyData->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n \n \/\/ fieldColors are same as cell colors except when rendering \n \/\/ VTK_TRIANGLE_STRIP, when they represent triangle colors.\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n if (mode == VTK_TRIANGLE_STRIP && cellpointi > 2)\n {\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n }\n \n \/\/ Send the point position as the last attribute.\n \/\/ TODO: how to mark that point position is being sent? since,\n \/\/ vtkDataSetAttributes doesn't define point positions and hence has\n \/\/ no enum for that. For now, vtkPointData::NUM_ATTRIBUTES marks\n \/\/ point positions.\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, \n pointtype, voidpoints, 3*pointId);\n }\n\n this->IncrementCurrentId();\n\n device->EndPrimitive();\n\n cellId++;\n\n if (count == 10000) \n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast<double>(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n return;\n }\n }\n }\n}\n \n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _mex_traits_hpp__\n#define _mex_traits_hpp__\n\n\/\/ Copyright(c) Andre Caron, 2009-2010\n\/\/\n\/\/ This document is covered by the Artistic License 2.0 (Open Source Initiative\n\/\/ approved license). A copy of the license should have been provided alongside\n\/\/ this software package (see \"license.rtf\"). If not, the license is available\n\/\/ online at \"http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\".\n\n#include \"__configure__.hpp\"\n#include \"types.hpp\"\n#include <exception>\n\nnamespace mex {\n\n template<typename T, type_t U>\n struct common_traits\n {\n typedef T value_type;\n typedef T * pointer;\n typedef const T * const_pointer;\n static const type_t type_code = U;\n\n static ::mxArray * check ( ::mxArray * array )\n {\n if ( array == 0 ) {\n throw (std::invalid_argument(\"MATLAB: invalid class\"));\n }\n if ( ::mxGetClassID(array) != type_code ) {\n throw (std::bad_cast());\n }\n return (array);\n }\n\n static const ::mxArray * check ( const ::mxArray * array )\n {\n if ( array == 0 ) {\n throw (std::invalid_argument(\"MATLAB: invalid class\"));\n }\n if ( ::mxGetClassID(array) != type_code ) {\n throw (std::bad_cast());\n }\n return (array);\n }\n };\n\n template<typename T, type_t U>\n struct numeric_traits :\n public common_traits< T, U >\n {\n static ::mxArray * matrix ( size_t m, size_t n, const real_t& )\n {\n ::mxArray *const result = ::mxCreateNumericMatrix\n (m, n, type_code, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * matrix ( size_t m, size_t n, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateNumericMatrix\n (m, n, type_code, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * array ( int ndim, const int * dims, const real_t& )\n {\n ::mxArray *const result = ::mxCreateNumericArray\n (ndim, dims, type_code, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * array\n ( int ndim, const int * dims, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateNumericArray\n (ndim, dims, type_code, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<typename T> struct traits;\n\n template<> struct traits< char_t > :\n public common_traits< char_t, mxCHAR_CLASS >\n {\n static ::mxArray * matrix ( size_t m, size_t n )\n {\n const size_t dims[] = { m, n };\n ::mxArray *const result = ::mxCreateCharArray(2, dims);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< double > :\n public common_traits< double, mxDOUBLE_CLASS >\n {\n static ::mxArray * matrix ( size_t m, size_t n, const real_t& )\n {\n ::mxArray *const result = ::mxCreateDoubleMatrix(m, n, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * matrix ( size_t m, size_t n, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateDoubleMatrix(m, n, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< logical > :\n public common_traits< double, mxLOGICAL_CLASS >\n {\n static ::mxArray * create ( size_t m, size_t n )\n {\n ::mxArray *const result = ::mxCreateLogicalMatrix(m, n);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< function > :\n public common_traits< function, mxFUNCTION_CLASS >\n {\n };\n\n template<> struct traits< unknown > :\n public common_traits< unknown, mxUNKNOWN_CLASS >\n {\n };\n\n template<> struct traits< object > :\n public common_traits< object, mxOBJECT_CLASS >\n {\n };\n\n template<> struct traits< int8 > :\n public numeric_traits< int8, mxINT8_CLASS >\n {\n };\n\n template<> struct traits< uint8 > :\n public numeric_traits< uint8, mxUINT8_CLASS >\n {\n };\n\n template<> struct traits< int16 > :\n public numeric_traits< int16, mxINT16_CLASS >\n {\n };\n\n template<> struct traits< uint16 > :\n public numeric_traits< uint16, mxUINT16_CLASS >\n {\n };\n\n template<> struct traits< int32 > :\n public numeric_traits< int32, mxINT32_CLASS >\n {\n };\n\n template<> struct traits< uint32 > :\n public numeric_traits< uint32, mxUINT32_CLASS >\n {\n };\n\n template<> struct traits< int64 > :\n public numeric_traits< int64, mxINT64_CLASS >\n {\n };\n\n template<> struct traits< uint64 > :\n public numeric_traits< uint64, mxUINT64_CLASS >\n {\n };\n\n}\n\n#endif \/* _mex_traits_hpp__ *\/\n<commit_msg>Added support for floats.<commit_after>#ifndef _mex_traits_hpp__\n#define _mex_traits_hpp__\n\n\/\/ Copyright(c) Andre Caron, 2009-2010\n\/\/\n\/\/ This document is covered by the Artistic License 2.0 (Open Source Initiative\n\/\/ approved license). A copy of the license should have been provided alongside\n\/\/ this software package (see \"license.rtf\"). If not, the license is available\n\/\/ online at \"http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\".\n\n#include \"__configure__.hpp\"\n#include \"types.hpp\"\n#include <exception>\n\nnamespace mex {\n\n template<typename T, type_t U>\n struct common_traits\n {\n typedef T value_type;\n typedef T * pointer;\n typedef const T * const_pointer;\n static const type_t type_code = U;\n\n static ::mxArray * check ( ::mxArray * array )\n {\n if ( array == 0 ) {\n throw (std::invalid_argument(\"MATLAB: invalid class\"));\n }\n if ( ::mxGetClassID(array) != type_code ) {\n throw (std::bad_cast());\n }\n return (array);\n }\n\n static const ::mxArray * check ( const ::mxArray * array )\n {\n if ( array == 0 ) {\n throw (std::invalid_argument(\"MATLAB: invalid class\"));\n }\n if ( ::mxGetClassID(array) != type_code ) {\n throw (std::bad_cast());\n }\n return (array);\n }\n };\n\n template<typename T, type_t U>\n struct numeric_traits :\n public common_traits< T, U >\n {\n static ::mxArray * matrix ( size_t m, size_t n, const real_t& )\n {\n ::mxArray *const result = ::mxCreateNumericMatrix\n (m, n, type_code, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * matrix ( size_t m, size_t n, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateNumericMatrix\n (m, n, type_code, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * array ( int ndim, const int * dims, const real_t& )\n {\n ::mxArray *const result = ::mxCreateNumericArray\n (ndim, dims, type_code, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * array\n ( int ndim, const int * dims, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateNumericArray\n (ndim, dims, type_code, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<typename T> struct traits;\n\n template<> struct traits< char_t > :\n public common_traits< char_t, mxCHAR_CLASS >\n {\n static ::mxArray * matrix ( size_t m, size_t n )\n {\n const size_t dims[] = { m, n };\n ::mxArray *const result = ::mxCreateCharArray(2, dims);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< double > :\n public common_traits< double, mxDOUBLE_CLASS >\n {\n static ::mxArray * matrix ( size_t m, size_t n, const real_t& )\n {\n ::mxArray *const result = ::mxCreateDoubleMatrix(m, n, mxREAL);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n\n static ::mxArray * matrix ( size_t m, size_t n, const complex_t& )\n {\n ::mxArray *const result = ::mxCreateDoubleMatrix(m, n, mxCOMPLEX);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< logical > :\n public common_traits< bool, mxLOGICAL_CLASS >\n {\n static ::mxArray * create ( size_t m, size_t n )\n {\n ::mxArray *const result = ::mxCreateLogicalMatrix(m, n);\n if ( result == 0 ) {\n throw (std::bad_alloc());\n }\n return (result);\n }\n };\n\n template<> struct traits< float > :\n public numeric_traits< float, mxSINGLE_CLASS >\n {\n };\n\n template<> struct traits< function > :\n public common_traits< function, mxFUNCTION_CLASS >\n {\n };\n\n template<> struct traits< unknown > :\n public common_traits< unknown, mxUNKNOWN_CLASS >\n {\n };\n\n template<> struct traits< object > :\n public common_traits< object, mxOBJECT_CLASS >\n {\n };\n\n template<> struct traits< int8 > :\n public numeric_traits< int8, mxINT8_CLASS >\n {\n };\n\n template<> struct traits< uint8 > :\n public numeric_traits< uint8, mxUINT8_CLASS >\n {\n };\n\n template<> struct traits< int16 > :\n public numeric_traits< int16, mxINT16_CLASS >\n {\n };\n\n template<> struct traits< uint16 > :\n public numeric_traits< uint16, mxUINT16_CLASS >\n {\n };\n\n template<> struct traits< int32 > :\n public numeric_traits< int32, mxINT32_CLASS >\n {\n };\n\n template<> struct traits< uint32 > :\n public numeric_traits< uint32, mxUINT32_CLASS >\n {\n };\n\n template<> struct traits< int64 > :\n public numeric_traits< int64, mxINT64_CLASS >\n {\n };\n\n template<> struct traits< uint64 > :\n public numeric_traits< uint64, mxUINT64_CLASS >\n {\n };\n\n}\n\n#endif \/* _mex_traits_hpp__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. The name of the author may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\/\/ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\/\/ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"third_party\/pcsc-lite\/naclport\/server\/src\/public\/pcsc_lite_server_web_port_service.h\"\n\n#include <stdint.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <thread>\n#include <utility>\n\n#include <google_smart_card_common\/ipc_emulation.h>\n#include <google_smart_card_common\/logging\/logging.h>\n#include <google_smart_card_common\/messaging\/typed_message.h>\n#include <google_smart_card_common\/optional.h>\n#include <google_smart_card_common\/value.h>\n#include <google_smart_card_common\/value_conversion.h>\n\n#include \"server_sockets_manager.h\"\n\n\/\/ Include the C headers after all other includes, because the preprocessor\n\/\/ definitions from them interfere with the symbols from the standard C++\n\/\/ library.\nextern \"C\" {\n#include \"winscard.h\"\n#include \"debuglog.h\"\n#include \"eventhandler.h\"\n#include \"hotplug.h\"\n#include \"readerfactory.h\"\n#include \"sys_generic.h\"\n#include \"winscard_svc.h\"\n}\n\n\/\/ Old versions of Emscripten have buggy multi-threading - so bail out if the\n\/\/ developer still hasn't updated their local Emscripten version.\n#ifdef __EMSCRIPTEN__\n#if __EMSCRIPTEN_major__ < 2 || \\\n (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \\\n __EMSCRIPTEN_tiny__ < 31)\n#error \"Emscripten >=2.0.31 must be used\"\n#endif\n#endif \/\/ __EMSCRIPTEN__\n\nnamespace google_smart_card {\n\nnamespace {\n\nPcscLiteServerWebPortService* g_pcsc_lite_server = nullptr;\n\nconstexpr char kLoggingPrefix[] = \"[PC\/SC-Lite NaCl port] \";\n\n\/\/ Constants for message types that are sent to the JavaScript side. These\n\/\/ strings must match the ones in reader-tracker.js.\nconstexpr char kReaderInitAddMessageType[] = \"reader_init_add\";\nconstexpr char kReaderFinishAddMessageType[] = \"reader_finish_add\";\nconstexpr char kReaderRemoveMessageType[] = \"reader_remove\";\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is being added by the PC\/SC-Lite daemon.\nstruct ReaderInitAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is completely added by the PC\/SC-Lite daemon.\nstruct ReaderFinishAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n long return_code;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is removed by the PC\/SC-Lite daemon.\nstruct ReaderRemoveMessageData {\n std::string reader_name;\n int port;\n};\n\nvoid PcscLiteServerDaemonThreadMain() {\n while (true) {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"[daemon thread] \"\n << \"Waiting for the new connected clients...\";\n optional<int> server_socket_file_descriptor =\n PcscLiteServerSocketsManager::GetInstance()->WaitAndPop();\n if (!server_socket_file_descriptor) {\n \/\/ A shutdown signal received.\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"[daemon thread] Shutting down...\";\n break;\n }\n\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"[daemon thread] A new \"\n << \"client was connected, starting a handler thread...\";\n \/\/ Note: even though the CreateContextThread function accepts its\n \/\/ server_socket_file_descriptor argument by pointer, it doesn't store the\n \/\/ pointer itself anywhere - so it's safe to use a local variable here.\n uint32_t server_socket_file_descriptor_unsigned =\n static_cast<uint32_t>(server_socket_file_descriptor.value());\n \/\/ FIXME(emaxx): Deal with cases when CreateContextThread returns errors.\n \/\/ Looks like it may happen legitimately when the abusive client(s) request\n \/\/ to establish too many requests. Probably, some limitation should be\n \/\/ applied to all clients.\n GOOGLE_SMART_CARD_CHECK(\n ::CreateContextThread(&server_socket_file_descriptor_unsigned) ==\n SCARD_S_SUCCESS);\n }\n\n \/\/ Clean up the structures and threads owned by the third-party PC\/SC-Lite\n \/\/ code. This follows the code in the \"if (AraKiri)\" block in the\n \/\/ `SVCServiceRunLoop()` function in pcsc-lite\/src\/src\/pcscdaemon.c.\n HPStopHotPluggables();\n SYS_Sleep(1);\n RFCleanupReaders();\n EHDeinitializeEventStructures();\n ContextsDeinitialize();\n}\n\n} \/\/ namespace\n\ntemplate <>\nStructValueDescriptor<ReaderInitAddMessageData>::Description\nStructValueDescriptor<ReaderInitAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderInitAddMessageData\")\n .WithField(&ReaderInitAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderInitAddMessageData::port, \"port\")\n .WithField(&ReaderInitAddMessageData::device, \"device\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderFinishAddMessageData>::Description\nStructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderFinishAddMessageData\")\n .WithField(&ReaderFinishAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderFinishAddMessageData::port, \"port\")\n .WithField(&ReaderFinishAddMessageData::device, \"device\")\n .WithField(&ReaderFinishAddMessageData::return_code, \"returnCode\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderRemoveMessageData>::Description\nStructValueDescriptor<ReaderRemoveMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderRemoveMessageData\")\n .WithField(&ReaderRemoveMessageData::reader_name, \"readerName\")\n .WithField(&ReaderRemoveMessageData::port, \"port\");\n}\n\nPcscLiteServerWebPortService::PcscLiteServerWebPortService(\n GlobalContext* global_context)\n : global_context_(global_context) {\n GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server);\n g_pcsc_lite_server = this;\n}\n\nPcscLiteServerWebPortService::~PcscLiteServerWebPortService() {\n \/\/ If the daemon thread is joinable, it means `ShutDownAndWait()` wasn't\n \/\/ called, which is a violation of the contract.\n GOOGLE_SMART_CARD_CHECK(!daemon_thread_.joinable());\n\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this);\n g_pcsc_lite_server = nullptr;\n}\n\n\/\/ static\nconst PcscLiteServerWebPortService*\nPcscLiteServerWebPortService::GetInstance() {\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server);\n return g_pcsc_lite_server;\n}\n\nvoid PcscLiteServerWebPortService::InitializeAndRunDaemonThread() {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization...\";\n\n IpcEmulation::CreateGlobalInstance();\n PcscLiteServerSocketsManager::CreateGlobalInstance();\n\n ::SYS_InitRandom();\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Setting up PC\/SC-Lite \"\n << \"logging...\";\n ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG);\n#ifdef NDEBUG\n ::DebugLogSetLevel(PCSC_LOG_ERROR);\n#else\n ::DebugLogSetLevel(PCSC_LOG_DEBUG);\n ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW);\n#endif\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite logging was \"\n << \"set up.\";\n\n LONG return_code;\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating reader \"\n << \"structures...\";\n return_code = ::RFAllocateReaderSpace(0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Reader structures \"\n << \"allocation finished with the following result: \\\"\"\n << ::pcsc_stringify_error(return_code) << \"\\\".\";\n GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Performing initial hot \"\n << \"plug drivers search...\";\n return_code = ::HPSearchHotPluggables();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Initial hot plug \"\n << \"drivers search finished with the following result code: \"\n << return_code << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Registering for hot \"\n << \"plug events...\";\n \/\/ FIXME(emaxx): Currently this ends up on polling the libusb each second, as\n \/\/ it doesn't provide any way to subscribe for the device list change. But\n \/\/ it's possible to optimize this onto publisher-pattern-style implementation,\n \/\/ by handling the chrome.usb API events (see\n \/\/ <https:\/\/developer.chrome.com\/apps\/usb#Events>) and using them in a\n \/\/ replacement implementation of the currently used original hotplug_libusb.c\n \/\/ source file.\n return_code = ::HPRegisterForHotplugEvents();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Registering for hot \"\n << \"plug events finished with the following result code: \" << return_code\n << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating client \"\n << \"structures...\";\n return_code = ::ContextsInitialize(0, 0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Client structures \"\n << \"allocation finished with the following result code: \" << return_code\n << \"...\";\n GOOGLE_SMART_CARD_CHECK(return_code == 1);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization...\";\n ::RFWaitForReaderInit();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization finished.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Starting PC\/SC-Lite \"\n << \"daemon thread...\";\n daemon_thread_ = std::thread(PcscLiteServerDaemonThreadMain);\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite daemon \"\n << \"thread has started.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization \"\n << \"successfully finished.\";\n}\n\nvoid PcscLiteServerWebPortService::ShutDownAndWait() {\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Shutting down the PC\/SC-Lite daemon thread...\";\n \/\/ This notifies the daemon thread to shut down.\n PcscLiteServerSocketsManager::GetInstance()->ShutDown();\n daemon_thread_.join();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"The PC\/SC-Lite daemon thread shut down.\";\n\n \/\/ Shut down the global state created in `InitializeAndRunDaemonThread()`.\n PcscLiteServerSocketsManager::DestroyGlobalInstance();\n IpcEmulation::DestroyGlobalInstance();\n}\n\nvoid PcscLiteServerWebPortService::PostReaderInitAddMessage(\n const char* reader_name,\n int port,\n const char* device) const {\n ReaderInitAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n PostMessage(kReaderInitAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderFinishAddMessage(\n const char* reader_name,\n int port,\n const char* device,\n long return_code) const {\n ReaderFinishAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n message_data.return_code = return_code;\n PostMessage(kReaderFinishAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderRemoveMessage(\n const char* reader_name,\n int port) const {\n ReaderRemoveMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n PostMessage(kReaderRemoveMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostMessage(const char* type,\n Value message_data) const {\n TypedMessage typed_message;\n typed_message.type = type;\n typed_message.data = std::move(message_data);\n global_context_->PostMessageToJs(\n ConvertToValueOrDie(std::move(typed_message)));\n}\n\n} \/\/ namespace google_smart_card\n<commit_msg>Workaround PC\/SC-Lite shutdown timing issues (#639)<commit_after>\/\/ Copyright 2016 Google Inc.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. The name of the author may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\/\/ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\/\/ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\/\/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"third_party\/pcsc-lite\/naclport\/server\/src\/public\/pcsc_lite_server_web_port_service.h\"\n\n#include <stdint.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <thread>\n#include <utility>\n\n#include <google_smart_card_common\/ipc_emulation.h>\n#include <google_smart_card_common\/logging\/logging.h>\n#include <google_smart_card_common\/messaging\/typed_message.h>\n#include <google_smart_card_common\/optional.h>\n#include <google_smart_card_common\/value.h>\n#include <google_smart_card_common\/value_conversion.h>\n\n#include \"server_sockets_manager.h\"\n\n\/\/ Include the C headers after all other includes, because the preprocessor\n\/\/ definitions from them interfere with the symbols from the standard C++\n\/\/ library.\nextern \"C\" {\n#include \"winscard.h\"\n#include \"debuglog.h\"\n#include \"eventhandler.h\"\n#include \"hotplug.h\"\n#include \"readerfactory.h\"\n#include \"sys_generic.h\"\n#include \"winscard_svc.h\"\n}\n\n\/\/ Old versions of Emscripten have buggy multi-threading - so bail out if the\n\/\/ developer still hasn't updated their local Emscripten version.\n#ifdef __EMSCRIPTEN__\n#if __EMSCRIPTEN_major__ < 2 || \\\n (__EMSCRIPTEN_major__ == 2 && __EMSCRIPTEN_minor__ == 0 && \\\n __EMSCRIPTEN_tiny__ < 31)\n#error \"Emscripten >=2.0.31 must be used\"\n#endif\n#endif \/\/ __EMSCRIPTEN__\n\nnamespace google_smart_card {\n\nnamespace {\n\nPcscLiteServerWebPortService* g_pcsc_lite_server = nullptr;\n\nconstexpr char kLoggingPrefix[] = \"[PC\/SC-Lite NaCl port] \";\n\n\/\/ Constants for message types that are sent to the JavaScript side. These\n\/\/ strings must match the ones in reader-tracker.js.\nconstexpr char kReaderInitAddMessageType[] = \"reader_init_add\";\nconstexpr char kReaderFinishAddMessageType[] = \"reader_finish_add\";\nconstexpr char kReaderRemoveMessageType[] = \"reader_remove\";\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is being added by the PC\/SC-Lite daemon.\nstruct ReaderInitAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is completely added by the PC\/SC-Lite daemon.\nstruct ReaderFinishAddMessageData {\n std::string reader_name;\n int port;\n std::string device;\n long return_code;\n};\n\n\/\/ Message data for the message that notifies the JavaScript side that a reader\n\/\/ is removed by the PC\/SC-Lite daemon.\nstruct ReaderRemoveMessageData {\n std::string reader_name;\n int port;\n};\n\nvoid PcscLiteServerDaemonThreadMain() {\n while (true) {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"[daemon thread] \"\n << \"Waiting for the new connected clients...\";\n optional<int> server_socket_file_descriptor =\n PcscLiteServerSocketsManager::GetInstance()->WaitAndPop();\n if (!server_socket_file_descriptor) {\n \/\/ A shutdown signal received.\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"[daemon thread] Shutting down...\";\n break;\n }\n\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"[daemon thread] A new \"\n << \"client was connected, starting a handler thread...\";\n \/\/ Note: even though the CreateContextThread function accepts its\n \/\/ server_socket_file_descriptor argument by pointer, it doesn't store the\n \/\/ pointer itself anywhere - so it's safe to use a local variable here.\n uint32_t server_socket_file_descriptor_unsigned =\n static_cast<uint32_t>(server_socket_file_descriptor.value());\n \/\/ FIXME(emaxx): Deal with cases when CreateContextThread returns errors.\n \/\/ Looks like it may happen legitimately when the abusive client(s) request\n \/\/ to establish too many requests. Probably, some limitation should be\n \/\/ applied to all clients.\n GOOGLE_SMART_CARD_CHECK(\n ::CreateContextThread(&server_socket_file_descriptor_unsigned) ==\n SCARD_S_SUCCESS);\n }\n\n \/\/ Clean up the structures and threads owned by the third-party PC\/SC-Lite\n \/\/ code. This follows the code in the \"if (AraKiri)\" block in the\n \/\/ `SVCServiceRunLoop()` function in pcsc-lite\/src\/src\/pcscdaemon.c.\n HPStopHotPluggables();\n \/\/ TODO: Upstream's approach with a magic sleep is flaky: the background\n \/\/ thread might be still running after this point, causing crashes. Replace\n \/\/ this with a proper waiting mechanism.\n SYS_Sleep(5);\n RFCleanupReaders();\n EHDeinitializeEventStructures();\n ContextsDeinitialize();\n}\n\n} \/\/ namespace\n\ntemplate <>\nStructValueDescriptor<ReaderInitAddMessageData>::Description\nStructValueDescriptor<ReaderInitAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderInitAddMessageData\")\n .WithField(&ReaderInitAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderInitAddMessageData::port, \"port\")\n .WithField(&ReaderInitAddMessageData::device, \"device\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderFinishAddMessageData>::Description\nStructValueDescriptor<ReaderFinishAddMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderFinishAddMessageData\")\n .WithField(&ReaderFinishAddMessageData::reader_name, \"readerName\")\n .WithField(&ReaderFinishAddMessageData::port, \"port\")\n .WithField(&ReaderFinishAddMessageData::device, \"device\")\n .WithField(&ReaderFinishAddMessageData::return_code, \"returnCode\");\n}\n\ntemplate <>\nStructValueDescriptor<ReaderRemoveMessageData>::Description\nStructValueDescriptor<ReaderRemoveMessageData>::GetDescription() {\n \/\/ Note: Strings passed to WithField() below must match the property names in\n \/\/ reader-tracker.js.\n return Describe(\"ReaderRemoveMessageData\")\n .WithField(&ReaderRemoveMessageData::reader_name, \"readerName\")\n .WithField(&ReaderRemoveMessageData::port, \"port\");\n}\n\nPcscLiteServerWebPortService::PcscLiteServerWebPortService(\n GlobalContext* global_context)\n : global_context_(global_context) {\n GOOGLE_SMART_CARD_CHECK(!g_pcsc_lite_server);\n g_pcsc_lite_server = this;\n}\n\nPcscLiteServerWebPortService::~PcscLiteServerWebPortService() {\n \/\/ If the daemon thread is joinable, it means `ShutDownAndWait()` wasn't\n \/\/ called, which is a violation of the contract.\n GOOGLE_SMART_CARD_CHECK(!daemon_thread_.joinable());\n\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server == this);\n g_pcsc_lite_server = nullptr;\n}\n\n\/\/ static\nconst PcscLiteServerWebPortService*\nPcscLiteServerWebPortService::GetInstance() {\n GOOGLE_SMART_CARD_CHECK(g_pcsc_lite_server);\n return g_pcsc_lite_server;\n}\n\nvoid PcscLiteServerWebPortService::InitializeAndRunDaemonThread() {\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization...\";\n\n IpcEmulation::CreateGlobalInstance();\n PcscLiteServerSocketsManager::CreateGlobalInstance();\n\n ::SYS_InitRandom();\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Setting up PC\/SC-Lite \"\n << \"logging...\";\n ::DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG);\n#ifdef NDEBUG\n ::DebugLogSetLevel(PCSC_LOG_ERROR);\n#else\n ::DebugLogSetLevel(PCSC_LOG_DEBUG);\n ::DebugLogSetCategory(DEBUG_CATEGORY_APDU | DEBUG_CATEGORY_SW);\n#endif\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite logging was \"\n << \"set up.\";\n\n LONG return_code;\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating reader \"\n << \"structures...\";\n return_code = ::RFAllocateReaderSpace(0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Reader structures \"\n << \"allocation finished with the following result: \\\"\"\n << ::pcsc_stringify_error(return_code) << \"\\\".\";\n GOOGLE_SMART_CARD_CHECK(return_code == SCARD_S_SUCCESS);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Performing initial hot \"\n << \"plug drivers search...\";\n return_code = ::HPSearchHotPluggables();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Initial hot plug \"\n << \"drivers search finished with the following result code: \"\n << return_code << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Registering for hot \"\n << \"plug events...\";\n \/\/ FIXME(emaxx): Currently this ends up on polling the libusb each second, as\n \/\/ it doesn't provide any way to subscribe for the device list change. But\n \/\/ it's possible to optimize this onto publisher-pattern-style implementation,\n \/\/ by handling the chrome.usb API events (see\n \/\/ <https:\/\/developer.chrome.com\/apps\/usb#Events>) and using them in a\n \/\/ replacement implementation of the currently used original hotplug_libusb.c\n \/\/ source file.\n return_code = ::HPRegisterForHotplugEvents();\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Registering for hot \"\n << \"plug events finished with the following result code: \" << return_code\n << \".\";\n GOOGLE_SMART_CARD_CHECK(return_code == 0);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Allocating client \"\n << \"structures...\";\n return_code = ::ContextsInitialize(0, 0);\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Client structures \"\n << \"allocation finished with the following result code: \" << return_code\n << \"...\";\n GOOGLE_SMART_CARD_CHECK(return_code == 1);\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization...\";\n ::RFWaitForReaderInit();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Waiting for the readers \"\n << \"initialization finished.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Starting PC\/SC-Lite \"\n << \"daemon thread...\";\n daemon_thread_ = std::thread(PcscLiteServerDaemonThreadMain);\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"PC\/SC-Lite daemon \"\n << \"thread has started.\";\n\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix << \"Initialization \"\n << \"successfully finished.\";\n}\n\nvoid PcscLiteServerWebPortService::ShutDownAndWait() {\n GOOGLE_SMART_CARD_LOG_DEBUG\n << kLoggingPrefix << \"Shutting down the PC\/SC-Lite daemon thread...\";\n \/\/ This notifies the daemon thread to shut down.\n PcscLiteServerSocketsManager::GetInstance()->ShutDown();\n daemon_thread_.join();\n GOOGLE_SMART_CARD_LOG_DEBUG << kLoggingPrefix\n << \"The PC\/SC-Lite daemon thread shut down.\";\n\n \/\/ Shut down the global state created in `InitializeAndRunDaemonThread()`.\n PcscLiteServerSocketsManager::DestroyGlobalInstance();\n IpcEmulation::DestroyGlobalInstance();\n}\n\nvoid PcscLiteServerWebPortService::PostReaderInitAddMessage(\n const char* reader_name,\n int port,\n const char* device) const {\n ReaderInitAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n PostMessage(kReaderInitAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderFinishAddMessage(\n const char* reader_name,\n int port,\n const char* device,\n long return_code) const {\n ReaderFinishAddMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n message_data.device = device;\n message_data.return_code = return_code;\n PostMessage(kReaderFinishAddMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostReaderRemoveMessage(\n const char* reader_name,\n int port) const {\n ReaderRemoveMessageData message_data;\n message_data.reader_name = reader_name;\n message_data.port = port;\n PostMessage(kReaderRemoveMessageType,\n ConvertToValueOrDie(std::move(message_data)));\n}\n\nvoid PcscLiteServerWebPortService::PostMessage(const char* type,\n Value message_data) const {\n TypedMessage typed_message;\n typed_message.type = type;\n typed_message.data = std::move(message_data);\n global_context_->PostMessageToJs(\n ConvertToValueOrDie(std::move(typed_message)));\n}\n\n} \/\/ namespace google_smart_card\n<|endoftext|>"} {"text":"<commit_before>#include \"Dealer.h\"\n\n\/*\nnamespace Blackjack\n{\n\tclass Dealer: public Player\n\t{\/\/A Blackjack dealer.\n\t\tprivate:\n\t\t\tstd::vector<Player*> players;\/\/A vector of the players. I have them stored as pointers so that it can store subclasses of Player.\n\n\t\tpublic:\n\t\t\t\/\/Dealer();\/\/Default Constructor.\n\t\t\t~Dealer();\/\/Default Destructor. Frees all the player pointers.\n\t\t\t\/\/void deal();\/\/Deal cards to players.\n\t\t\tvoid startGame();\/\/Starts the players playing.\n\t\t\tvoid addUserPlayer( std::string newName );\/\/Registers a new user's player for the game. newName is the name of the new player.\n\t\t\tvoid addAutoPlayer( std::string newName );\/\/Registers a new automatic player for the game. newName is the name of the new player.\n\t\t\tCard getRandomCard();\/\/Returns a randomly valued card.\n\t\t\tvoid play();\/\/Play a hand as the dealer.\n\t};\n}\n*\/\nnamespace Blackjack\n{\n\tDealer::Dealer()\n\t{\/\/Default Constructor.\n\t\t\/\/Create a new hand.\n\t\tHand newHand;\/\/Create the hand object itself.\n\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the first random card of the hand.\n\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the second random card of the hand.\n\t\tcollHands.addHand( newHand );\/\/Add the new hand to the collection of hands.\n\t}\n\n\tDealer::~Dealer()\n\t{\/\/Default Destructor. Frees all the player pointers.\n\t\tfor( std::vector<Player*>::iterator i = players.begin(); i != players.end(); i++ )\n\t\t{\/\/Iterate through each element in the players vector and delete each one.\n\t\t\tdelete *i;\n\t\t}\n\n\t\tplayers.clear();\/\/Remove all the deleted pointers from the players vector.\n\t}\n\n\tvoid Dealer::startGame()\n\t{\/\/Starts the players playing.\n\t\twhile( players.size() > 0 )\n\t\t{\n\t\t\tstd::vector<Player*>::iterator pit\n\n\t\t\tfor( pit = players.begin(); pit != players.end(); pit++ )\n\t\t\t{\/\/Go through the players and have each them play a hand.\n\t\t\t\t(*pit)->play();\n\t\t\t}\n\n\t\t\t\/\/Play a hand as the dealer.\n\t\t\tplay();\n\n\t\t\tpit = players.begin();\n\t\t\twhile( pit != players.end() )\n\t\t\t{\/\/Go through the players and count up the winnings\/losses and ask each if they want to quit.\n\t\t\t\t\n\t\t\t\tstd::cout << \"Winnings and losses to be programmed later...\" << std::endl;\n\t\t\t\t\/\/TODO: finish the calculations of winnings and losses.\n\t\t\t\t\n\t\t\t\tif( (*pit)->askQuit() == playReturnValues.quitPlaying )\n\t\t\t\t{\/\/Ask if the player wants to quit.\n\t\t\t\t\tpit = players.erase( pit );\/\/Erase the plaer and get the new iterator.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\/\/The player didn't want to quit, so just move on.\n\t\t\t\t\tpit++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Dealer::addUserPlayer( std::string newName )\n\t{\/\/Registers a new user's player for the game. newName is the name of the new player.\n\t\tplayers.push_back( new UserPlayer(newName) );\n\t}\n\n\tvoid Dealer::addAutoPlayer( std::string newName )\n\t{\/\/Registers a new automatic player for the game. newName is the name of the new player.\n\t\tplayers.push_back( new AutoPlayer(newName) );\n\t}\n\n\tCard Dealer::getRandomCard()\n\t{\/\/Returns a randomly valued card.\n\t\tCard randomCard( static_cast<Rank>(0,12), static_cast<Suit>(0,3) );\n\t\treturn randomCard;\n\t}\n\n\tCard Dealer::getDealerCard()\n\t{\/\/Returns one of the dealer's card for the player to see.\n\t\treturn (*collHands.begin()).getCard(1);\/\/Return the first card of the first hand.\n\t}\n\n\tvoid Dealer::play()\n\t{\/\/Play a hand as the dealer.\n\t\tstd::cout << \"The dealer doesn't know how to play yet.\" << std::endl;\n\t\t\/\/TODO: finish this method.\n\t}\n\n\tint Dealer::askQuit()\n\t{\/\/Just returns keep playing every time.\n\t\treturn playReturnValues.keepPlaying;\n\t}\n}\n<commit_msg>Added some code for the play method of the Dealer class.<commit_after>#include \"Dealer.h\"\n\n\/*\nnamespace Blackjack\n{\n\tclass Dealer: public Player\n\t{\/\/A Blackjack dealer.\n\t\tprivate:\n\t\t\tstd::vector<Player*> players;\/\/A vector of the players. I have them stored as pointers so that it can store subclasses of Player.\n\n\t\tpublic:\n\t\t\t\/\/Dealer();\/\/Default Constructor.\n\t\t\t~Dealer();\/\/Default Destructor. Frees all the player pointers.\n\t\t\t\/\/void deal();\/\/Deal cards to players.\n\t\t\tvoid startGame();\/\/Starts the players playing.\n\t\t\tvoid addUserPlayer( std::string newName );\/\/Registers a new user's player for the game. newName is the name of the new player.\n\t\t\tvoid addAutoPlayer( std::string newName );\/\/Registers a new automatic player for the game. newName is the name of the new player.\n\t\t\tCard getRandomCard();\/\/Returns a randomly valued card.\n\t\t\tvoid play();\/\/Play a hand as the dealer.\n\t};\n}\n*\/\nnamespace Blackjack\n{\n\tDealer::Dealer()\n\t{\/\/Default Constructor.\n\t\t\/\/Create a new hand.\n\t\tHand newHand;\/\/Create the hand object itself.\n\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the first random card of the hand.\n\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the second random card of the hand.\n\t\tcollHands.addHand( newHand );\/\/Add the new hand to the collection of hands.\n\t}\n\n\tDealer::~Dealer()\n\t{\/\/Default Destructor. Frees all the player pointers.\n\t\tfor( std::vector<Player*>::iterator i = players.begin(); i != players.end(); i++ )\n\t\t{\/\/Iterate through each element in the players vector and delete each one.\n\t\t\tdelete *i;\n\t\t}\n\n\t\tplayers.clear();\/\/Remove all the deleted pointers from the players vector.\n\t}\n\n\tvoid Dealer::startGame()\n\t{\/\/Starts the players playing.\n\t\twhile( players.size() > 0 )\n\t\t{\n\t\t\tstd::vector<Player*>::iterator pit\n\n\t\t\tfor( pit = players.begin(); pit != players.end(); pit++ )\n\t\t\t{\/\/Go through the players and have each them play a hand.\n\t\t\t\t(*pit)->play();\n\t\t\t}\n\n\t\t\t\/\/Play a hand as the dealer.\n\t\t\tplay();\n\n\t\t\tpit = players.begin();\n\t\t\twhile( pit != players.end() )\n\t\t\t{\/\/Go through the players and count up the winnings\/losses and ask each if they want to quit.\n\t\t\t\t\n\t\t\t\tstd::cout << \"Winnings and losses to be programmed later...\" << std::endl;\n\t\t\t\t\/\/TODO: finish the calculations of winnings and losses.\n\t\t\t\t\n\t\t\t\tif( (*pit)->askQuit() == playReturnValues.quitPlaying )\n\t\t\t\t{\/\/Ask if the player wants to quit.\n\t\t\t\t\tpit = players.erase( pit );\/\/Erase the plaer and get the new iterator.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\/\/The player didn't want to quit, so just move on.\n\t\t\t\t\tpit++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Dealer::addUserPlayer( std::string newName )\n\t{\/\/Registers a new user's player for the game. newName is the name of the new player.\n\t\tplayers.push_back( new UserPlayer(newName) );\n\t}\n\n\tvoid Dealer::addAutoPlayer( std::string newName )\n\t{\/\/Registers a new automatic player for the game. newName is the name of the new player.\n\t\tplayers.push_back( new AutoPlayer(newName) );\n\t}\n\n\tCard Dealer::getRandomCard()\n\t{\/\/Returns a randomly valued card.\n\t\tCard randomCard( static_cast<Rank>(0,12), static_cast<Suit>(0,3) );\n\t\treturn randomCard;\n\t}\n\n\tCard Dealer::getDealerCard()\n\t{\/\/Returns one of the dealer's card for the player to see.\n\t\treturn (*collHands.begin()).getCard(1);\/\/Return the first card of the first hand.\n\t}\n\n\tvoid Dealer::play()\n\t{\/\/Play a hand as the dealer.\n\t\tif( collHands.numHands() == 0 )\n\t\t{\/\/If there aren't any hands yet, create the first one so that play can start.\n\t\t\tHand newHand;\/\/Create the hand object itself.\n\t\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the first random card of the hand.\n\t\t\tnewHand.addCard( myDealer->getRandomCard() );\/\/Get the second random card of the hand.\n\t\t\tcollHands.addHand( newHand );\/\/Add the new hand to the collection of hands.\n\t\t}\n\t\t\t\n\t\tfor( HandList::iterator itr = collHands.begin(); itr != collHands.end(); itr++ )\n\t\t{\/\/Play each hand by iteration through them.\n\t\t\tbool doneWithThisHand = false;\/\/Used to keep track of wether the dealer has decided to stop playing this hand.\n\t\t\t\t\n\t\t\twhile( (doneWithThisHand != true) && (*itr.getMaxPointsAtOrBelow21() < 21) )\n\t\t\t{\/\/While the dealer hasn't decided to stop playing this hand and the hand is below 21 points, keep playing this hand.\n\t\t\t\tstd::cout << \"Dealer's hand: \" << *itr << std::endl;\/\/Print out the hand.\n\t\t\t\tstd::cout << \"Dealer's points: \" << *itr.getMaxPointsAtOrBelow21() << std::endl;\/\/Print out the number of points.\n\n\t\t\t\tif( *itr.getMaxPointsAtOrBelow21() < 17 )\n\t\t\t\t{\/\/If the points for this hand are below 17, hit.\n\t\t\t\t\t(*itr).addCard( myDealer->getRandomCard() );\/\/Put in a random card.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\/\/The dealer wants to stand, so done with this hand.\n\t\t\t\t\tdoneWithThisHand = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\n\t\t\t\/\/Print out the hand at the end of the play\n\t\t\tstd::cout << \"Dealer's hand: \" << std::endl;\n\t\t\tstd::cout << *itr << std::endl;\/\/Print out the hand.\n\t\t\tstd::cout << \"Dealer's points: \" << (*itr).getMaxPointsAtOrBelow21() << std::endl;\/\/Print out the number of points.\n\t\t}\n\t}\n\n\tint Dealer::askQuit()\n\t{\/\/Just returns keep playing every time.\n\t\treturn playReturnValues.keepPlaying;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2012 The QXmpp developers\n *\n * Authors:\n * Olivier Goffart\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppPresence.h\"\n\n#include \"presence.h\"\n#include \"tests.h\"\n\nvoid tst_QXmppPresence::testPresence_data()\n{\n QXmppPresence foo;\n\n QTest::addColumn<QByteArray>(\"xml\");\n QTest::addColumn<int>(\"type\");\n QTest::addColumn<int>(\"priority\");\n QTest::addColumn<int>(\"statusType\");\n QTest::addColumn<QString>(\"statusText\");\n QTest::addColumn<int>(\"vcardUpdate\");\n QTest::addColumn<QByteArray>(\"photoHash\");\n\n QTest::newRow(\"empty\") << QByteArray(\"<presence\/>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"unavailable\") << QByteArray(\"<presence type=\\\"unavailable\\\"\/>\") << int(QXmppPresence::Unavailable) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"error\") << QByteArray(\"<presence type=\\\"error\\\"\/>\") << int(QXmppPresence::Error) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n \n QTest::newRow(\"full\") << QByteArray(\"<presence><show>away<\/show><status>In a meeting<\/status><priority>5<\/priority><\/presence>\") << int(QXmppPresence::Available) << 5 << int(QXmppPresence::Away) << \"In a meeting\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n\n \/\/ status type\n QTest::newRow(\"away\") << QByteArray(\"<presence><show>away<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Away) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"dnd\") << QByteArray(\"<presence><show>dnd<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::DND) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"chat\") << QByteArray(\"<presence><show>chat<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Chat) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"xa\") << QByteArray(\"<presence><show>xa<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::XA) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"invisible\") << QByteArray(\"<presence><show>invisible<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Invisible) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n\n QTest::newRow(\"vcard-photo\") << QByteArray(\n \"<presence>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\">\"\n \"<photo>73b908bc<\/photo>\"\n \"<\/x>\"\n \"<\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateValidPhoto) << QByteArray::fromHex(\"73b908bc\");\n\n QTest::newRow(\"vard-not-ready\") << QByteArray(\n \"<presence>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\"\/>\"\n \"<\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNotReady) << QByteArray();\n}\n\nvoid tst_QXmppPresence::testPresence()\n{\n QFETCH(QByteArray, xml);\n QFETCH(int, type);\n QFETCH(int, priority);\n QFETCH(int, statusType);\n QFETCH(QString, statusText);\n QFETCH(int, vcardUpdate);\n QFETCH(QByteArray, photoHash);\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(int(presence.type()), type);\n QCOMPARE(presence.priority(), priority);\n QCOMPARE(int(presence.availableStatusType()), statusType);\n QCOMPARE(presence.statusText(), statusText);\n QCOMPARE(int(presence.vCardUpdateType()), vcardUpdate);\n QCOMPARE(presence.photoHash(), photoHash);\n\n \/\/ legacy\n QCOMPARE(presence.status().priority(), priority);\n QCOMPARE(int(presence.status().type()), statusType);\n QCOMPARE(presence.status().statusText(), statusText);\n\n serializePacket(presence, xml);\n}\n\nvoid tst_QXmppPresence::testPresenceWithCapability()\n{\n const QByteArray xml(\n \"<presence to=\\\"foo@example.com\/QXmpp\\\" from=\\\"bar@example.com\/QXmpp\\\">\"\n \"<show>away<\/show>\"\n \"<status>In a meeting<\/status>\"\n \"<priority>5<\/priority>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\">\"\n \"<photo>73b908bc<\/photo>\"\n \"<\/x>\"\n \"<c xmlns=\\\"http:\/\/jabber.org\/protocol\/caps\\\" hash=\\\"sha-1\\\" node=\\\"http:\/\/code.google.com\/p\/qxmpp\\\" ver=\\\"QgayPKawpkPSDYmwT\/WM94uAlu0=\\\"\/>\"\n \"<\/presence>\");\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(presence.to(), QString(\"foo@example.com\/QXmpp\"));\n QCOMPARE(presence.from(), QString(\"bar@example.com\/QXmpp\"));\n QCOMPARE(presence.availableStatusType(), QXmppPresence::Away);\n QCOMPARE(presence.statusText(), QString(\"In a meeting\"));\n QCOMPARE(presence.priority(), 5);\n QCOMPARE(presence.photoHash(), QByteArray::fromHex(\"73b908bc\"));\n QCOMPARE(presence.vCardUpdateType(), QXmppPresence::VCardUpdateValidPhoto);\n QCOMPARE(presence.capabilityHash(), QString(\"sha-1\"));\n QCOMPARE(presence.capabilityNode(), QString(\"http:\/\/code.google.com\/p\/qxmpp\"));\n QCOMPARE(presence.capabilityVer(), QByteArray::fromBase64(\"QgayPKawpkPSDYmwT\/WM94uAlu0=\"));\n\n serializePacket(presence, xml);\n}\n\nvoid tst_QXmppPresence::testPresenceWithMuc()\n{\n const QByteArray xml(\n \"<presence \"\n \"to=\\\"pistol@shakespeare.lit\/harfleur\\\" \"\n \"from=\\\"harfleur@henryv.shakespeare.lit\/pistol\\\" \"\n \"type=\\\"unavailable\\\">\"\n \"<x xmlns=\\\"http:\/\/jabber.org\/protocol\/muc#user\\\">\"\n \"<item affiliation=\\\"none\\\" role=\\\"none\\\">\"\n \"<actor jid=\\\"fluellen@shakespeare.lit\\\"\/>\"\n \"<reason>Avaunt, you cullion!<\/reason>\"\n \"<\/item>\"\n \"<status code=\\\"307\\\"\/>\"\n \"<\/x>\"\n \"<\/presence>\");\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(presence.to(), QLatin1String(\"pistol@shakespeare.lit\/harfleur\"));\n QCOMPARE(presence.from(), QLatin1String(\"harfleur@henryv.shakespeare.lit\/pistol\"));\n QCOMPARE(presence.type(), QXmppPresence::Unavailable);\n QCOMPARE(presence.mucItem().actor(), QLatin1String(\"fluellen@shakespeare.lit\"));\n QCOMPARE(presence.mucItem().affiliation(), QXmppMucItem::NoAffiliation);\n QCOMPARE(presence.mucItem().jid(), QString());\n QCOMPARE(presence.mucItem().reason(), QLatin1String(\"Avaunt, you cullion!\"));\n QCOMPARE(presence.mucItem().role(), QXmppMucItem::NoRole);\n QCOMPARE(presence.mucStatusCodes(), QList<int>() << 307);\n serializePacket(presence, xml);\n}\n\n<commit_msg>improve presence test coverage<commit_after>\/*\n * Copyright (C) 2008-2012 The QXmpp developers\n *\n * Authors:\n * Olivier Goffart\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppPresence.h\"\n\n#include \"presence.h\"\n#include \"tests.h\"\n\nvoid tst_QXmppPresence::testPresence_data()\n{\n QXmppPresence foo;\n\n QTest::addColumn<QByteArray>(\"xml\");\n QTest::addColumn<int>(\"type\");\n QTest::addColumn<int>(\"priority\");\n QTest::addColumn<int>(\"statusType\");\n QTest::addColumn<QString>(\"statusText\");\n QTest::addColumn<int>(\"vcardUpdate\");\n QTest::addColumn<QByteArray>(\"photoHash\");\n\n \/\/ presence type\n QTest::newRow(\"available\") << QByteArray(\"<presence\/>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"unavailable\") << QByteArray(\"<presence type=\\\"unavailable\\\"\/>\") << int(QXmppPresence::Unavailable) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"error\") << QByteArray(\"<presence type=\\\"error\\\"\/>\") << int(QXmppPresence::Error) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"subscribe\") << QByteArray(\"<presence type=\\\"subscribe\\\"\/>\") << int(QXmppPresence::Subscribe) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"unsubscribe\") << QByteArray(\"<presence type=\\\"unsubscribe\\\"\/>\") << int(QXmppPresence::Unsubscribe) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"subscribed\") << QByteArray(\"<presence type=\\\"subscribed\\\"\/>\") << int(QXmppPresence::Subscribed) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"unsubscribed\") << QByteArray(\"<presence type=\\\"unsubscribed\\\"\/>\") << int(QXmppPresence::Unsubscribed) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"probe\") << QByteArray(\"<presence type=\\\"probe\\\"\/>\") << int(QXmppPresence::Probe) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n\n \/\/ status text + priority \n QTest::newRow(\"full\") << QByteArray(\"<presence><show>away<\/show><status>In a meeting<\/status><priority>5<\/priority><\/presence>\") << int(QXmppPresence::Available) << 5 << int(QXmppPresence::Away) << \"In a meeting\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n\n \/\/ status type\n QTest::newRow(\"away\") << QByteArray(\"<presence><show>away<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Away) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"dnd\") << QByteArray(\"<presence><show>dnd<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::DND) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"chat\") << QByteArray(\"<presence><show>chat<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Chat) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"xa\") << QByteArray(\"<presence><show>xa<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::XA) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n QTest::newRow(\"invisible\") << QByteArray(\"<presence><show>invisible<\/show><\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Invisible) << \"\" << int(QXmppPresence::VCardUpdateNone) << QByteArray();\n\n \/\/ photo\n QTest::newRow(\"vcard-photo\") << QByteArray(\n \"<presence>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\">\"\n \"<photo>73b908bc<\/photo>\"\n \"<\/x>\"\n \"<\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateValidPhoto) << QByteArray::fromHex(\"73b908bc\");\n\n QTest::newRow(\"vard-not-ready\") << QByteArray(\n \"<presence>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\"\/>\"\n \"<\/presence>\") << int(QXmppPresence::Available) << 0 << int(QXmppPresence::Online) << \"\" << int(QXmppPresence::VCardUpdateNotReady) << QByteArray();\n}\n\nvoid tst_QXmppPresence::testPresence()\n{\n QFETCH(QByteArray, xml);\n QFETCH(int, type);\n QFETCH(int, priority);\n QFETCH(int, statusType);\n QFETCH(QString, statusText);\n QFETCH(int, vcardUpdate);\n QFETCH(QByteArray, photoHash);\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(int(presence.type()), type);\n QCOMPARE(presence.priority(), priority);\n QCOMPARE(int(presence.availableStatusType()), statusType);\n QCOMPARE(presence.statusText(), statusText);\n QCOMPARE(int(presence.vCardUpdateType()), vcardUpdate);\n QCOMPARE(presence.photoHash(), photoHash);\n\n \/\/ legacy\n QCOMPARE(presence.status().priority(), priority);\n QCOMPARE(int(presence.status().type()), statusType);\n QCOMPARE(presence.status().statusText(), statusText);\n\n serializePacket(presence, xml);\n}\n\nvoid tst_QXmppPresence::testPresenceWithCapability()\n{\n const QByteArray xml(\n \"<presence to=\\\"foo@example.com\/QXmpp\\\" from=\\\"bar@example.com\/QXmpp\\\">\"\n \"<show>away<\/show>\"\n \"<status>In a meeting<\/status>\"\n \"<priority>5<\/priority>\"\n \"<x xmlns=\\\"vcard-temp:x:update\\\">\"\n \"<photo>73b908bc<\/photo>\"\n \"<\/x>\"\n \"<c xmlns=\\\"http:\/\/jabber.org\/protocol\/caps\\\" hash=\\\"sha-1\\\" node=\\\"http:\/\/code.google.com\/p\/qxmpp\\\" ver=\\\"QgayPKawpkPSDYmwT\/WM94uAlu0=\\\"\/>\"\n \"<\/presence>\");\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(presence.to(), QString(\"foo@example.com\/QXmpp\"));\n QCOMPARE(presence.from(), QString(\"bar@example.com\/QXmpp\"));\n QCOMPARE(presence.availableStatusType(), QXmppPresence::Away);\n QCOMPARE(presence.statusText(), QString(\"In a meeting\"));\n QCOMPARE(presence.priority(), 5);\n QCOMPARE(presence.photoHash(), QByteArray::fromHex(\"73b908bc\"));\n QCOMPARE(presence.vCardUpdateType(), QXmppPresence::VCardUpdateValidPhoto);\n QCOMPARE(presence.capabilityHash(), QString(\"sha-1\"));\n QCOMPARE(presence.capabilityNode(), QString(\"http:\/\/code.google.com\/p\/qxmpp\"));\n QCOMPARE(presence.capabilityVer(), QByteArray::fromBase64(\"QgayPKawpkPSDYmwT\/WM94uAlu0=\"));\n\n serializePacket(presence, xml);\n}\n\nvoid tst_QXmppPresence::testPresenceWithMuc()\n{\n const QByteArray xml(\n \"<presence \"\n \"to=\\\"pistol@shakespeare.lit\/harfleur\\\" \"\n \"from=\\\"harfleur@henryv.shakespeare.lit\/pistol\\\" \"\n \"type=\\\"unavailable\\\">\"\n \"<x xmlns=\\\"http:\/\/jabber.org\/protocol\/muc#user\\\">\"\n \"<item affiliation=\\\"none\\\" role=\\\"none\\\">\"\n \"<actor jid=\\\"fluellen@shakespeare.lit\\\"\/>\"\n \"<reason>Avaunt, you cullion!<\/reason>\"\n \"<\/item>\"\n \"<status code=\\\"307\\\"\/>\"\n \"<\/x>\"\n \"<\/presence>\");\n\n QXmppPresence presence;\n parsePacket(presence, xml);\n QCOMPARE(presence.to(), QLatin1String(\"pistol@shakespeare.lit\/harfleur\"));\n QCOMPARE(presence.from(), QLatin1String(\"harfleur@henryv.shakespeare.lit\/pistol\"));\n QCOMPARE(presence.type(), QXmppPresence::Unavailable);\n QCOMPARE(presence.mucItem().actor(), QLatin1String(\"fluellen@shakespeare.lit\"));\n QCOMPARE(presence.mucItem().affiliation(), QXmppMucItem::NoAffiliation);\n QCOMPARE(presence.mucItem().jid(), QString());\n QCOMPARE(presence.mucItem().reason(), QLatin1String(\"Avaunt, you cullion!\"));\n QCOMPARE(presence.mucItem().role(), QXmppMucItem::NoRole);\n QCOMPARE(presence.mucStatusCodes(), QList<int>() << 307);\n serializePacket(presence, xml);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP).\n * @see http:\/\/primesieve.googlecode.com\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/expr\/ExpressionParser.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype> \/* std::tolower(int) *\/\n#include <iomanip> \/* std::setw(int) *\/\n\nnamespace {\n enum {\n OPTION_ERROR,\n OPTION_HELP,\n OPTION_SIEVE,\n OPTION_TEST,\n OPTION_VERSION\n };\n\n std::vector<uint64_t> numbers; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n bool quietMode = false;\n bool showParserResults = false;\n int threads = ParallelPrimeSieve::USE_IDEAL_NUM_THREADS;\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = static_cast<uint64_t> (1E13);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n}\n\nvoid version() {\n std::cout << \"primesieve 2.2, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n}\n\nbool isDigits(const std::string &str) {\n const std::string digits(\"0123456789\");\n if (str.size() == 0)\n return false;\n return str.find_first_not_of(digits) == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nint processOptions(int argc, char* argv[]) {\n std::string testOption(\"test\");\n std::string arg;\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n if (argc < 2 || argc > 20)\n return OPTION_HELP;\n if (argc > 2) {\n \/\/ get the START and STOP number\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n return OPTION_ERROR;\n }\n numbers.push_back(parser.getResult());\n if (!isDigits(argv[i]))\n showParserResults = true;\n }\n }\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n return OPTION_HELP;\n c++;\n switch (std::tolower(*c++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n return OPTION_HELP;\n flags |= ParallelPrimeSieve::COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n return OPTION_HELP;\n flags |= ParallelPrimeSieve::PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n return OPTION_HELP;\n sieveSize = static_cast<uint32_t> (parser.getResult());\n break;\n case 't': arg = &argv[i][1];\n if (arg.compare(testOption) == 0)\n return OPTION_TEST;\n if (++i >= argc || !parser.eval(argv[i]))\n return OPTION_HELP;\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': return OPTION_VERSION;\n default : return OPTION_HELP;\n }\n }\n if (numbers.size() == 2)\n return OPTION_SIEVE;\n return OPTION_HELP;\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n switch(processOptions(argc, argv)) {\n case OPTION_ERROR: return 1;\n case OPTION_HELP: help(); return 0;\n case OPTION_VERSION: version(); return 0;\n case OPTION_TEST: test(); return 0;\n default: break;\n }\n \/\/ print parser results\n std::cout.setf(std::ios::left);\n if (!quietMode && showParserResults)\n std::cout << std::setw(10) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(10) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n try {\n ParallelPrimeSieve pps;\n\n \/\/ set default settings\n if ((flags & pps.COUNT_FLAGS) == 0 && (flags & pps.PRINT_FLAGS) == 0)\n flags |= pps.COUNT_PRIMES;\n if (!quietMode && (flags & pps.PRINT_FLAGS) == 0)\n flags |= pps.PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ? L1_CACHE_SIZE : L2_CACHE_SIZE;\n\n pps.setStartNumber(numbers[0]);\n pps.setStopNumber(numbers[1]);\n pps.setSieveSize(sieveSize);\n pps.setFlags(flags);\n pps.setNumThreads(threads);\n\n if (!quietMode)\n std::cout << std::setw(10) << \"Sieve size\" << \" = \" << pps.getSieveSize() << \" KiloBytes\" << std::endl\n << std::setw(10) << \"Threads\" << \" = \" << pps.getNumThreads() << std::endl;\n\n \/\/ start sieving primes\n pps.sieve();\n if ((flags & pps.PRINT_STATUS) || (\n (flags & pps.PRINT_FLAGS) &&\n (flags & pps.COUNT_FLAGS)))\n std::cout << std::endl;\n\n const std::string primes[7] = {\n \"Prime numbers\",\n \"Twin primes\",\n \"Prime triplets\",\n \"Prime quadruplets\",\n \"Prime quintuplets\", \n \"Prime sextuplets\",\n \"Prime septuplets\"};\n\n \/\/ get max string size\n std::size_t size = (quietMode) ? 0 : 12;\n for (int i = 0; i < 7; i++)\n if ((flags & (pps.COUNT_PRIMES << i)) && size < primes[i].size())\n size = primes[i].size();\n \/\/ print prime count results and time elapsed\n int width = static_cast<int> (size);\n for (int i = 0; i < 7; i++)\n if (flags & (pps.COUNT_PRIMES << i))\n std::cout << std::setw(width) << primes[i] << \" : \" << pps.getCounts(i) << std::endl;\n if (!quietMode)\n std::cout << std::setw(width) << \"Time elapsed\" << \" : \" << pps.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n return 1;\n }\n return 0;\n}\n<commit_msg>improved code readability<commit_after>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP).\n * @see http:\/\/primesieve.googlecode.com\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that generates prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/expr\/ExpressionParser.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype> \/* std::tolower(int) *\/\n#include <iomanip> \/* std::setw(int) *\/\n\nnamespace {\n enum {\n OPTION_ERROR,\n OPTION_HELP,\n OPTION_SIEVE,\n OPTION_TEST,\n OPTION_VERSION\n };\n\n std::vector<uint64_t> numbers; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n bool quietMode = false;\n bool showParserResults = false;\n int threads = ParallelPrimeSieve::USE_IDEAL_NUM_THREADS;\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = static_cast<uint64_t> (1E13);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n}\n\nvoid version() {\n std::cout << \"primesieve 2.2, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n}\n\nbool isDigits(const std::string &str) {\n const std::string digits(\"0123456789\");\n if (str.size() == 0)\n return false;\n return str.find_first_not_of(digits) == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nint processOptions(int argc, char* argv[]) {\n std::string testOption(\"test\");\n std::string arg;\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n if (argc < 2 || argc > 20)\n return OPTION_HELP;\n if (argc > 2) {\n \/\/ get the START and STOP number\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n return OPTION_ERROR;\n }\n numbers.push_back(parser.getResult());\n if (!isDigits(argv[i]))\n showParserResults = true;\n }\n }\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n return OPTION_HELP;\n c++;\n switch (std::tolower(*c++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n return OPTION_HELP;\n flags |= ParallelPrimeSieve::COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n return OPTION_HELP;\n flags |= ParallelPrimeSieve::PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n return OPTION_HELP;\n sieveSize = static_cast<uint32_t> (parser.getResult());\n break;\n case 't': arg = &argv[i][1];\n if (arg.compare(testOption) == 0)\n return OPTION_TEST;\n if (++i >= argc || !parser.eval(argv[i]))\n return OPTION_HELP;\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': return OPTION_VERSION;\n default : return OPTION_HELP;\n }\n }\n if (numbers.size() == 2)\n return OPTION_SIEVE;\n return OPTION_HELP;\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n switch(processOptions(argc, argv)) {\n case OPTION_ERROR: return 1;\n case OPTION_HELP: help(); return 0;\n case OPTION_VERSION: version(); return 0;\n case OPTION_TEST: test(); return 0;\n default: break;\n }\n \/\/ print parser results\n std::cout.setf(std::ios::left);\n if (!quietMode && showParserResults)\n std::cout << std::setw(10) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(10) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n try {\n ParallelPrimeSieve pps;\n\n \/\/ set default settings\n if ((flags & pps.COUNT_FLAGS) == 0 && (flags & pps.PRINT_FLAGS) == 0)\n flags |= pps.COUNT_PRIMES;\n if (!quietMode && (flags & pps.PRINT_FLAGS) == 0)\n flags |= pps.PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ? L1_CACHE_SIZE : L2_CACHE_SIZE;\n\n pps.setStartNumber(numbers[0]);\n pps.setStopNumber(numbers[1]);\n pps.setSieveSize(sieveSize);\n pps.setFlags(flags);\n pps.setNumThreads(threads);\n\n if (!quietMode)\n std::cout << std::setw(10) << \"Sieve size\" << \" = \" << pps.getSieveSize() << \" KiloBytes\" << std::endl\n << std::setw(10) << \"Threads\" << \" = \" << pps.getNumThreads() << std::endl;\n\n \/\/ start sieving primes\n pps.sieve();\n if ((flags & pps.PRINT_STATUS) || (\n (flags & pps.PRINT_FLAGS) &&\n (flags & pps.COUNT_FLAGS)))\n std::cout << std::endl;\n\n const std::string primes[7] = {\n \"Prime numbers\",\n \"Twin primes\",\n \"Prime triplets\",\n \"Prime quadruplets\",\n \"Prime quintuplets\", \n \"Prime sextuplets\",\n \"Prime septuplets\"};\n\n \/\/ get max string size\n std::size_t size = (quietMode) ? 0 : 12;\n for (int i = 0; i < 7; i++)\n if ((flags & (pps.COUNT_PRIMES << i)) && size < primes[i].size())\n size = primes[i].size();\n \/\/ print prime count results and time elapsed\n int width = static_cast<int> (size);\n for (int i = 0; i < 7; i++)\n if (flags & (pps.COUNT_PRIMES << i))\n std::cout << std::setw(width) << primes[i] << \" : \" << pps.getCounts(i) << std::endl;\n if (!quietMode)\n std::cout << std::setw(width) << \"Time elapsed\" << \" : \" << pps.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>VclPtr: no dialog loaded from a .ui ever actually destructed<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkWindowToImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkWindowToImageFilter.h\"\n\n#include \"vtkCamera.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRendererCollection.h\"\n\nvtkCxxRevisionMacro(vtkWindowToImageFilter, \"1.16\");\nvtkStandardNewMacro(vtkWindowToImageFilter);\n\n\/\/----------------------------------------------------------------------------\nvtkWindowToImageFilter::vtkWindowToImageFilter()\n{\n this->Input = NULL;\n this->Magnification = 1;\n this->ReadFrontBuffer = 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWindowToImageFilter::~vtkWindowToImageFilter()\n{\n if (this->Input)\n {\n this->Input->UnRegister(this);\n this->Input = NULL;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWindowToImageFilter::SetInput(vtkWindow *input)\n{\n if (input != this->Input)\n {\n if (this->Input) {this->Input->UnRegister(this);}\n this->Input = input;\n if (this->Input) {this->Input->Register(this);}\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWindowToImageFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageSource::PrintSelf(os,indent);\n \n if ( this->Input )\n {\n os << indent << \"Input:\\n\";\n this->Input->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n os << indent << \"ReadFrontBuffer: \" << this->ReadFrontBuffer << \"\\n\";\n os << indent << \"Magnification: \" << this->Magnification << \"\\n\";\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This method returns the largest region that can be generated.\nvoid vtkWindowToImageFilter::ExecuteInformation()\n{\n if (this->Input == NULL )\n {\n vtkErrorMacro(<<\"Please specify a renderer as input!\");\n return;\n }\n vtkImageData *out = this->GetOutput();\n \n \/\/ set the extent\n out->SetWholeExtent(0, \n this->Input->GetSize()[0]*this->Magnification - 1,\n 0, \n this->Input->GetSize()[1]*this->Magnification - 1,\n 0, 0);\n \n \/\/ set the spacing\n out->SetSpacing(1.0, 1.0, 1.0);\n \n \/\/ set the origin.\n out->SetOrigin(0.0, 0.0, 0.0);\n \n \/\/ set the scalar components\n out->SetNumberOfScalarComponents(3);\n out->SetScalarType(VTK_UNSIGNED_CHAR);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads a region from a file. The regions extent\/axes\n\/\/ are assumed to be the same as the file extent\/order.\nvoid vtkWindowToImageFilter::ExecuteData(vtkDataObject *vtkNotUsed(data))\n{\n vtkImageData *out = this->GetOutput();\n out->SetExtent(out->GetWholeExtent());\n out->AllocateScalars();\n \n int outIncrY;\n int size[2];\n unsigned char *pixels, *outPtr;\n int idxY, rowSize;\n int i;\n \n if (out->GetScalarType() != VTK_UNSIGNED_CHAR)\n {\n vtkErrorMacro(\"mismatch in scalar types!\");\n return;\n }\n \n \/\/ get the size of the render window\n size[0] = this->Input->GetSize()[0];\n size[1] = this->Input->GetSize()[1];\n rowSize = size[0]*3;\n outIncrY = size[0]*this->Magnification*3;\n \n float *viewAngles;\n double *windowCenters;\n vtkRenderWindow *renWin = vtkRenderWindow::SafeDownCast(this->Input);\n if (!renWin)\n {\n vtkWarningMacro(\"The window passed to window to image should be a RenderWIndow or one of its subclasses\");\n return;\n }\n \n vtkRendererCollection *rc = renWin->GetRenderers();\n vtkRenderer *aren;\n vtkCamera *cam;\n int numRenderers = rc->GetNumberOfItems();\n\n \/\/ for each renderer\n vtkCamera **cams = new vtkCamera *[numRenderers];\n viewAngles = new float [numRenderers];\n windowCenters = new double [numRenderers*2];\n double *parallelScale = new double [numRenderers];\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n cams[i] = aren->GetActiveCamera();\n cams[i]->Register(this);\n cams[i]->GetWindowCenter(windowCenters+i*2);\n viewAngles[i] = cams[i]->GetViewAngle();\n parallelScale[i] = cams[i]->GetParallelScale();\n cam = cams[i]->NewInstance();\n cam->SetPosition(cams[i]->GetPosition());\n cam->SetFocalPoint(cams[i]->GetFocalPoint()); \n cam->SetViewUp(cams[i]->GetViewUp());\n cam->SetClippingRange(cams[i]->GetClippingRange());\n cam->SetParallelProjection(cams[i]->GetParallelProjection());\n cam->SetFocalDisk(cams[i]->GetFocalDisk());\n aren->SetActiveCamera(cam);\n }\n \n \/\/ render each of the tiles required to fill this request\n this->Input->SetTileScale(this->Magnification);\n this->Input->GetSize();\n \n int x, y;\n for (y = 0; y < this->Magnification; y++)\n {\n for (x = 0; x < this->Magnification; x++)\n {\n \/\/ setup the Window ivars\n this->Input->SetTileViewport((float)x\/this->Magnification,\n (float)y\/this->Magnification,\n (x+1.0)\/this->Magnification,\n (y+1.0)\/this->Magnification);\n float *tvp = this->Input->GetTileViewport();\n \n \/\/ for each renderer, setup camera\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n cam = aren->GetActiveCamera();\n float *vp = aren->GetViewport();\n float visVP[4];\n visVP[0] = (vp[0] >= tvp[0]) ? vp[0] : tvp[0];\n visVP[1] = (vp[1] >= tvp[1]) ? vp[1] : tvp[1];\n visVP[2] = (vp[2] <= tvp[2]) ? vp[2] : tvp[2];\n visVP[3] = (vp[3] <= tvp[3]) ? vp[3] : tvp[3];\n \/\/ compute magnification\n float mag = (visVP[3] - visVP[1])\/(vp[3] - vp[1]);\n \/\/ compute the delta\n float deltax = (visVP[2] + visVP[0])\/2.0 - (vp[2] + vp[0])\/2.0;\n float deltay = (visVP[3] + visVP[1])\/2.0 - (vp[3] + vp[1])\/2.0;\n \/\/ scale by original window size\n if (visVP[2] - visVP[0] > 0)\n {\n deltax = 2.0*deltax\/(visVP[2] - visVP[0]);\n }\n if (visVP[3] - visVP[1] > 0)\n {\n deltay = 2.0*deltay\/(visVP[3] - visVP[1]);\n }\n cam->SetWindowCenter(deltax,deltay); \n cam->SetViewAngle(asin(sin(viewAngles[i]*3.1415926\/360.0)*mag) \n * 360.0 \/ 3.1415926);\n cam->SetParallelScale(parallelScale[i]*mag);\n }\n \n \/\/ now render the tile and get the data\n this->Input->Render();\n int buffer = this->ReadFrontBuffer;\n if(!this->Input->GetDoubleBuffer())\n {\n buffer = 1;\n } \n\n pixels = this->Input->GetPixelData(0,0,size[0] - 1,\n size[1] - 1, buffer);\n unsigned char *pixels1 = pixels;\n \n \/\/ now write the data to the output image\n outPtr = \n (unsigned char *)out->GetScalarPointer(x*size[0],y*size[1], 0);\n \n \/\/ Loop through ouput pixels\n for (idxY = 0; idxY < size[1]; idxY++)\n {\n memcpy(outPtr,pixels1,rowSize);\n outPtr += outIncrY;\n pixels1 += rowSize;\n }\n \n \/\/ free the memory\n delete [] pixels;\n }\n }\n \n \/\/ restore settings\n \/\/ for each renderer\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n \/\/ store the old view angle & set the new\n cam = aren->GetActiveCamera();\n aren->SetActiveCamera(cams[i]);\n cams[i]->UnRegister(this);\n cam->Delete();\n }\n delete [] viewAngles;\n delete [] windowCenters;\n delete [] parallelScale;\n delete [] cams;\n \n \/\/ render each of the tiles required to fill this request\n this->Input->SetTileScale(1);\n this->Input->SetTileViewport(0.0,0.0,1.0,1.0);\n this->Input->GetSize();\n}\n\n\n\n<commit_msg>bug fix for some cases from volview branch<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkWindowToImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkWindowToImageFilter.h\"\n\n#include \"vtkCamera.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRendererCollection.h\"\n\nvtkCxxRevisionMacro(vtkWindowToImageFilter, \"1.17\");\nvtkStandardNewMacro(vtkWindowToImageFilter);\n\n\/\/----------------------------------------------------------------------------\nvtkWindowToImageFilter::vtkWindowToImageFilter()\n{\n this->Input = NULL;\n this->Magnification = 1;\n this->ReadFrontBuffer = 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWindowToImageFilter::~vtkWindowToImageFilter()\n{\n if (this->Input)\n {\n this->Input->UnRegister(this);\n this->Input = NULL;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWindowToImageFilter::SetInput(vtkWindow *input)\n{\n if (input != this->Input)\n {\n if (this->Input) {this->Input->UnRegister(this);}\n this->Input = input;\n if (this->Input) {this->Input->Register(this);}\n this->Modified();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWindowToImageFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageSource::PrintSelf(os,indent);\n \n if ( this->Input )\n {\n os << indent << \"Input:\\n\";\n this->Input->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n os << indent << \"ReadFrontBuffer: \" << this->ReadFrontBuffer << \"\\n\";\n os << indent << \"Magnification: \" << this->Magnification << \"\\n\";\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This method returns the largest region that can be generated.\nvoid vtkWindowToImageFilter::ExecuteInformation()\n{\n if (this->Input == NULL )\n {\n vtkErrorMacro(<<\"Please specify a renderer as input!\");\n return;\n }\n vtkImageData *out = this->GetOutput();\n \n \/\/ set the extent\n out->SetWholeExtent(0, \n this->Input->GetSize()[0]*this->Magnification - 1,\n 0, \n this->Input->GetSize()[1]*this->Magnification - 1,\n 0, 0);\n \n \/\/ set the spacing\n out->SetSpacing(1.0, 1.0, 1.0);\n \n \/\/ set the origin.\n out->SetOrigin(0.0, 0.0, 0.0);\n \n \/\/ set the scalar components\n out->SetNumberOfScalarComponents(3);\n out->SetScalarType(VTK_UNSIGNED_CHAR);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This function reads a region from a file. The regions extent\/axes\n\/\/ are assumed to be the same as the file extent\/order.\nvoid vtkWindowToImageFilter::ExecuteData(vtkDataObject *vtkNotUsed(data))\n{\n vtkImageData *out = this->GetOutput();\n out->SetExtent(out->GetWholeExtent());\n out->AllocateScalars();\n \n int outIncrY;\n int size[2];\n unsigned char *pixels, *outPtr;\n int idxY, rowSize;\n int i;\n \n if (out->GetScalarType() != VTK_UNSIGNED_CHAR)\n {\n vtkErrorMacro(\"mismatch in scalar types!\");\n return;\n }\n \n \/\/ get the size of the render window\n size[0] = this->Input->GetSize()[0];\n size[1] = this->Input->GetSize()[1];\n rowSize = size[0]*3;\n outIncrY = size[0]*this->Magnification*3;\n \n float *viewAngles;\n double *windowCenters;\n vtkRenderWindow *renWin = vtkRenderWindow::SafeDownCast(this->Input);\n if (!renWin)\n {\n vtkWarningMacro(\"The window passed to window to image should be a RenderWIndow or one of its subclasses\");\n return;\n }\n \n vtkRendererCollection *rc = renWin->GetRenderers();\n vtkRenderer *aren;\n vtkCamera *cam;\n int numRenderers = rc->GetNumberOfItems();\n\n \/\/ for each renderer\n vtkCamera **cams = new vtkCamera *[numRenderers];\n viewAngles = new float [numRenderers];\n windowCenters = new double [numRenderers*2];\n double *parallelScale = new double [numRenderers];\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n cams[i] = aren->GetActiveCamera();\n cams[i]->Register(this);\n cams[i]->GetWindowCenter(windowCenters+i*2);\n viewAngles[i] = cams[i]->GetViewAngle();\n parallelScale[i] = cams[i]->GetParallelScale();\n cam = cams[i]->NewInstance();\n cam->SetPosition(cams[i]->GetPosition());\n cam->SetFocalPoint(cams[i]->GetFocalPoint()); \n cam->SetViewUp(cams[i]->GetViewUp());\n cam->SetClippingRange(cams[i]->GetClippingRange());\n cam->SetParallelProjection(cams[i]->GetParallelProjection());\n cam->SetFocalDisk(cams[i]->GetFocalDisk());\n aren->SetActiveCamera(cam);\n }\n \n \/\/ render each of the tiles required to fill this request\n this->Input->SetTileScale(this->Magnification);\n this->Input->GetSize();\n \n int x, y;\n for (y = 0; y < this->Magnification; y++)\n {\n for (x = 0; x < this->Magnification; x++)\n {\n \/\/ setup the Window ivars\n this->Input->SetTileViewport((float)x\/this->Magnification,\n (float)y\/this->Magnification,\n (x+1.0)\/this->Magnification,\n (y+1.0)\/this->Magnification);\n float *tvp = this->Input->GetTileViewport();\n \n \/\/ for each renderer, setup camera\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n cam = aren->GetActiveCamera();\n float *vp = aren->GetViewport();\n float visVP[4];\n visVP[0] = (vp[0] < tvp[0]) ? tvp[0] : vp[0];\n visVP[0] = (visVP[0] > tvp[2]) ? tvp[2] : visVP[0];\n visVP[1] = (vp[1] < tvp[1]) ? tvp[1] : vp[1];\n visVP[1] = (visVP[1] > tvp[3]) ? tvp[3] : visVP[1];\n visVP[2] = (vp[2] > tvp[2]) ? tvp[2] : vp[2];\n visVP[2] = (visVP[2] < tvp[0]) ? tvp[0] : visVP[2];\n visVP[3] = (vp[3] > tvp[3]) ? tvp[3] : vp[3];\n visVP[3] = (visVP[3] < tvp[1]) ? tvp[1] : visVP[3];\n\n \/\/ compute magnification\n float mag = (visVP[3] - visVP[1])\/(vp[3] - vp[1]);\n \/\/ compute the delta\n float deltax = (visVP[2] + visVP[0])\/2.0 - (vp[2] + vp[0])\/2.0;\n float deltay = (visVP[3] + visVP[1])\/2.0 - (vp[3] + vp[1])\/2.0;\n \/\/ scale by original window size\n if (visVP[2] - visVP[0] > 0)\n {\n deltax = 2.0*deltax\/(visVP[2] - visVP[0]);\n }\n if (visVP[3] - visVP[1] > 0)\n {\n deltay = 2.0*deltay\/(visVP[3] - visVP[1]);\n }\n cam->SetWindowCenter(deltax,deltay); \n cam->SetViewAngle(asin(sin(viewAngles[i]*3.1415926\/360.0)*mag) \n * 360.0 \/ 3.1415926);\n cam->SetParallelScale(parallelScale[i]*mag);\n }\n \n \/\/ now render the tile and get the data\n this->Input->Render();\n int buffer = this->ReadFrontBuffer;\n if(!this->Input->GetDoubleBuffer())\n {\n buffer = 1;\n } \n\n pixels = this->Input->GetPixelData(0,0,size[0] - 1,\n size[1] - 1, buffer);\n unsigned char *pixels1 = pixels;\n \n \/\/ now write the data to the output image\n outPtr = \n (unsigned char *)out->GetScalarPointer(x*size[0],y*size[1], 0);\n \n \/\/ Loop through ouput pixels\n for (idxY = 0; idxY < size[1]; idxY++)\n {\n memcpy(outPtr,pixels1,rowSize);\n outPtr += outIncrY;\n pixels1 += rowSize;\n }\n \n \/\/ free the memory\n delete [] pixels;\n }\n }\n \n \/\/ restore settings\n \/\/ for each renderer\n rc->InitTraversal();\n for (i = 0; i < numRenderers; ++i)\n {\n aren = rc->GetNextItem();\n \/\/ store the old view angle & set the new\n cam = aren->GetActiveCamera();\n aren->SetActiveCamera(cams[i]);\n cams[i]->UnRegister(this);\n cam->Delete();\n }\n delete [] viewAngles;\n delete [] windowCenters;\n delete [] parallelScale;\n delete [] cams;\n \n \/\/ render each of the tiles required to fill this request\n this->Input->SetTileScale(1);\n this->Input->SetTileViewport(0.0,0.0,1.0,1.0);\n this->Input->GetSize();\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <utility> \/\/ std::move\n#include <string> \/\/ std::string\n#include <iostream> \/\/ std::ostream\n#include <memory> \/\/ std::unique_ptr\n#include <shark.hpp>\n\nusing namespace std;\nusing namespace shark;\n\nclass tester {\n\tostream& out;\n\tstring current;\n\tlong fails;\n\tlong tests;\n\tlong curfails;\n\tlong curchecks;\n\npublic:\n\ttester(ostream& out): out(out), fails(0), tests(0) { }\n\t~tester() { }\n\tvoid begin_test(const std::string& name);\n\tvoid end_test();\n\tvoid add_result(test_result r);\n};\n\nvoid tester::begin_test(const std::string& name) {\n\tcurrent = name;\n\tcurfails = 0;\n\tcurchecks = 0;\n\tif(world().procid == 0)\n\t\tout << \"Begin test \" << current << endl;\n\tworld().sync();\n}\n\nvoid tester::end_test() {\n\tworld().sync();\n\tbool fail = curfails > 0;\n\ttests++;\n\tif(fail) fails++;\n\tif(world().procid == 0) {\n\t\tout << \"End test \" << current << \": \";\n\t\tif(!fail)\n\t\t\tout << \"Success (\" << curchecks << \" checks)\" << endl;\n\t\telse\n\t\t\tout << \"FAILED (\" << curfails << \" of \" << curchecks << \" checks failed)\" << endl;\n\t}\n}\n\nvoid tester::add_result(test_result r) {\n\tcurchecks += r.checks;\n\tcurfails += r.fails;\n}\n\nusing namespace shark::ndim;\n\ntemplate<int ndim, typename S>\nclass suite1 {\n\tstatic_assert(S::number_of_dimensions == ndim, \"Source dimensionality\");\n\n\tconst Domain<ndim>& dom;\n\tconst S src;\n\ttypedef typename source<S>::element_type T;\n\n\tcoords_range<ndim> subrange();\n\tunique_ptr<T[]> src_buf(coords_range<ndim> r);\n\npublic:\n\tsuite1(const Domain<ndim>& dom, const S& src): dom(dom), src(src) { }\n\t~suite1() { }\n\tvoid test_basic(tester& t);\n\tvoid test_move(tester& t);\n\tvoid test_ghost(tester& t);\n\tvoid test_ghost_corner(tester& t);\n\tvoid test_ghost_periodic(tester& t);\n\tvoid test_get(tester& t);\n\tvoid test_put(tester& t);\n\tvoid test_accumulate(tester& t);\n\tvoid test_reshape(tester& t);\n\tvoid run(tester& t) {\n\t\ttest_basic(t);\n\t\ttest_move(t);\n\t\ttest_ghost(t);\n\t\ttest_ghost_corner(t);\n\t\ttest_ghost_periodic(t);\n\t\ttest_get(t);\n\t\ttest_put(t);\n\t\ttest_accumulate(t);\n\t\ttest_reshape(t);\n\t}\n};\n\ntemplate<int ndim, typename S>\nsuite1<ndim,S> make_suite1(const Domain<ndim>& dom, const S& src) {\n\treturn suite1<ndim,S>(dom, src);\n}\n\ntemplate<int ndim, typename S>\ncoords_range<ndim> suite1<ndim,S>::subrange() {\n\tcoords_range<ndim> total = dom.total();\n\tcoords_range<ndim> r;\n\tfor(int d = 0; d < ndim; d++) {\n\t\tcoord q = (total.upper[d] - total.lower[d])\/4;\n\t\tr.lower[d] = total.lower[d] + q;\n\t\tr.upper[d] = total.lower[d] + q * 3;\n\t}\n\treturn r;\n}\n\ntemplate<int ndim, typename S>\nunique_ptr<typename suite1<ndim,S>::T[]> suite1<ndim,S>::src_buf(coords_range<ndim> r) {\n\tconst typename S::accessor s(src);\n\tcoords<ndim+1> ld = r.stride();\n\tunique_ptr<T[]> ptr(new T[ld[0]]);\n\tr.for_each([&s,r,ld,&ptr](coords<ndim> ii) {\n\t\tptr[(ii - r.lower).offset(ld)] = s(ii);\n\t});\n\treturn ptr;\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_basic(tester& t) {\n\tt.begin_test(\"test_basic\");\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = src;\n\t\tt.add_result(check(ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_move(tester& t) {\n\tt.begin_test(\"test_move\");\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t{\n\t\t\tGlobalArray<ndim,T> tmp(dom);\n\t\t\ttmp = src;\n\t\t\tga = std::move(tmp);\n\t\t}\n\t\tt.add_result(check(ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost(tester& t) {\n\tt.begin_test(\"test_ghost\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\tcoords_range<ndim> inner = dom.total();\n\tfor(int d = 0; d < ndim; d++) {\n\t\tinner.lower[d] += gw[d];\n\t\tinner.upper[d] -= gw[d];\n\t}\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(inner, ga == src));\n\t\tfor(int d = 0; d < ndim; d++) {\n\t\t\tcoords<ndim> sd = {{}}, su = {{}};\n\t\t\tsd[d] = -1;\n\t\t\tsu[d] = 1;\n\t\t\tt.add_result(check(inner,\n\t\t\t\tshift(ga,sd) == shift(src,sd) &&\n\t\t\t\tshift(ga,su) == shift(src,su) &&\n\t\t\t\tshift(ga,sd+sd) == shift(src,sd+sd) &&\n\t\t\t\tshift(ga,su+su) == shift(src,su+su)));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost_corner(tester& t) {\n\tt.begin_test(\"test_ghost_corner\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\tcoords_range<ndim> inner = dom.total();\n\tfor(int d = 0; d < ndim; d++) {\n\t\tinner.lower[d] += gw[d];\n\t\tinner.upper[d] -= gw[d];\n\t}\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw, true);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(inner, ga == src));\n\t\tt.add_result(check(inner, shift(ga,gw) == shift(src,gw) && shift(ga,-gw) == shift(src,-gw)));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost_periodic(tester& t) {\n\tt.begin_test(\"test_ghost_periodic\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\ttypename GlobalArray<ndim,T>::bounds bd;\n\tfor(int d = 0; d < ndim; d++)\n\t\tbd[d] = Boundary<ndim,T>::periodic();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw, false, bd);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(ga == src));\n\t\tfor(int d = 0; d < ndim; d++) {\n\t\t\tcoords<ndim> sd = {{}}, su = {{}};\n\t\t\tsd[d] = -1;\n\t\t\tsu[d] = 1;\n\t\t\tt.add_result(check(\n\t\t\t\tshift(ga,sd) == shift(src,sd,dom.total()) &&\n\t\t\t\tshift(ga,su) == shift(src,su,dom.total()) && \n\t\t\t\tshift(ga,sd+sd) == shift(src,sd+sd,dom.total()) &&\n\t\t\t\tshift(ga,su+su) == shift(src,su+su,dom.total())));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_get(tester& t) {\n\tt.begin_test(\"test_get\");\n\tcoords_range<ndim> r = subrange();\n\tcoords<ndim+1> ld = r.stride();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = src;\n\t\t\/\/ Everyone does a \"get\" and checks the result\n\t\tunique_ptr<T[]> ptr(new T[ld[0]]);\n\t\tga.get(r, ptr.get());\n\t\t{\n\t\t\ttest_result tr = test_result();\n\t\t\tconst typename S::accessor s(src);\n\t\t\tr.for_each([&tr,&s,r,ld,&ptr](coords<ndim> ii) {\n\t\t\t\tif(s(ii) != ptr[(ii - r.lower).offset(ld)])\n\t\t\t\t\ttr.fails++;\n\t\t\t\ttr.checks++;\n\t\t\t});\n\t\t\t\/\/ Add everything together\n\t\t\tt.add_result(dom.group.external_sum(move(tr)));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_put(tester& t) {\n\tt.begin_test(\"test_put\");\n\tcoords_range<ndim> r = subrange();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t\/\/ First one does a put\n\t\tdom.group.sync();\n\t\tif (dom.group.procid == 0)\n\t\t\tga.put(r, src_buf(r).get());\n\t\tdom.group.sync();\n\t\t\/\/ Everyone helps check\n\t\tt.add_result(check(r, ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_accumulate(tester& t) {\n\tt.begin_test(\"test_accumulate\");\n\tcoords_range<ndim> r = subrange();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t\/\/ First and last one contribute\n\t\tdom.group.sync();\n\t\tif (dom.group.procid == 0)\n\t\t\tga.accumulate(r, src_buf(r).get());\n\t\tif (dom.group.procid == dom.group.nprocs-1)\n\t\t\tga.accumulate(r, src_buf(r).get());\n\t\tdom.group.sync();\n\t\t\/\/ Everyone helps check\n\t\tt.add_result(check(r, ga == src+src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_reshape(tester& t) {\n\tt.begin_test(\"test_reshape\");\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = src;\n\t\t\/\/ Construct distribution where everything is assigned to first one\n\t\ttypename Domain<ndim>::dists alt_nd(dom.nd);\n\t\tfor(int d = 0; d < ndim; d++) {\n\t\t\talt_nd[d][0] = 0;\n\t\t\tfor(int p = 1; p <= dom.np[d]; p++)\n\t\t\t\talt_nd[d][p] = dom.n[d];\n\t\t}\n\t\tDomain<ndim> alt_dom(dom.group, dom.n, dom.np, alt_nd);\n\t\tga.reshape(alt_dom);\n\t\tconst typename GlobalArray<ndim,T>::accessor a(ga);\n\t\tconst typename S::accessor s(src);\n\t\tt.add_result(alt_dom.sum(test_result(), [&a,&s](test_result& tr, coords<ndim> ii) {\n\t\t\tif(s(ii) != a(ii))\n\t\t\t\ttr.fails++;\n\t\t\ttr.checks++;\n\t\t}));\n\t}\n\tt.end_test();\n}\n\nint main(int argc, char* argv[]) {\n\tInit(&argc, &argv);\n\tSetupThreads();\n\ttester t(cerr);\n\tif(world().procid == 0)\n\t\tcerr << \"Testing <1,int>\" << endl;\n\t{\n\t\tcoords<1> n = {{1000}};\n\t\tDomain<1> dom(world(), n);\n\t\tauto f = coord_val<0>(dom, 1000);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tif(world().procid == 0)\n\t\tcerr << endl << \"Testing <3,double>\" << endl;\n\t{\n\t\tcoords<3> n = {{100,100,100}};\n\t\tDomain<3> dom(world(), n);\n\t\tauto f = sin(coord_val<0>(dom, 2*M_PI, false)) * cos(coord_val<1>(dom, 2*M_PI, false)) * coord_val<2>(dom, 1.0, false);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tif(world().procid == 0)\n\t\tcerr << endl << \"Testing <3,vec<3,double>>\" << endl;\n\t{\n\t\tcoords<3> n = {{100,100,100}};\n\t\tDomain<3> dom(world(), n);\n\t\tconst vec<3,double> one = {{1.0, 1.0, 1.0}};\n\t\tconst vec<3,double> mid = {{0.5, 0.5, 0.5}};\n\t\tauto f = abs(coord_vec(dom, one) - mid);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tFinalize();\n}\n<commit_msg>Reshape test<commit_after>\n#include <utility> \/\/ std::move\n#include <string> \/\/ std::string\n#include <iostream> \/\/ std::ostream\n#include <memory> \/\/ std::unique_ptr\n#include <shark.hpp>\n\nusing namespace std;\nusing namespace shark;\n\nclass tester {\n\tostream& out;\n\tstring current;\n\tlong fails;\n\tlong tests;\n\tlong curfails;\n\tlong curchecks;\n\npublic:\n\ttester(ostream& out): out(out), fails(0), tests(0) { }\n\t~tester() { }\n\tvoid begin_test(const std::string& name);\n\tvoid end_test();\n\tvoid add_result(test_result r);\n};\n\nvoid tester::begin_test(const std::string& name) {\n\tcurrent = name;\n\tcurfails = 0;\n\tcurchecks = 0;\n\tif(world().procid == 0)\n\t\tout << \"Begin test \" << current << endl;\n\tworld().sync();\n}\n\nvoid tester::end_test() {\n\tworld().sync();\n\tbool fail = curfails > 0;\n\ttests++;\n\tif(fail) fails++;\n\tif(world().procid == 0) {\n\t\tout << \"End test \" << current << \": \";\n\t\tif(!fail)\n\t\t\tout << \"Success (\" << curchecks << \" checks)\" << endl;\n\t\telse\n\t\t\tout << \"FAILED (\" << curfails << \" of \" << curchecks << \" checks failed)\" << endl;\n\t}\n}\n\nvoid tester::add_result(test_result r) {\n\tcurchecks += r.checks;\n\tcurfails += r.fails;\n}\n\nusing namespace shark::ndim;\n\ntemplate<int ndim, typename S>\nclass suite1 {\n\tstatic_assert(S::number_of_dimensions == ndim, \"Source dimensionality\");\n\n\tconst Domain<ndim>& dom;\n\tconst S src;\n\ttypedef typename source<S>::element_type T;\n\n\tcoords_range<ndim> subrange();\n\tunique_ptr<T[]> src_buf(coords_range<ndim> r);\n\n\tvoid test_reshape_domain(tester& t, const Domain<ndim>& alt_dom);\n\npublic:\n\tsuite1(const Domain<ndim>& dom, const S& src): dom(dom), src(src) { }\n\t~suite1() { }\n\tvoid test_basic(tester& t);\n\tvoid test_move(tester& t);\n\tvoid test_ghost(tester& t);\n\tvoid test_ghost_corner(tester& t);\n\tvoid test_ghost_periodic(tester& t);\n\tvoid test_get(tester& t);\n\tvoid test_put(tester& t);\n\tvoid test_accumulate(tester& t);\n\tvoid test_reshape(tester& t);\n\tvoid run(tester& t) {\n\t\ttest_basic(t);\n\t\ttest_move(t);\n\t\ttest_ghost(t);\n\t\ttest_ghost_corner(t);\n\t\ttest_ghost_periodic(t);\n\t\ttest_get(t);\n\t\ttest_put(t);\n\t\ttest_accumulate(t);\n\t\ttest_reshape(t);\n\t}\n};\n\ntemplate<int ndim, typename S>\nsuite1<ndim,S> make_suite1(const Domain<ndim>& dom, const S& src) {\n\treturn suite1<ndim,S>(dom, src);\n}\n\ntemplate<int ndim, typename S>\ncoords_range<ndim> suite1<ndim,S>::subrange() {\n\tcoords_range<ndim> total = dom.total();\n\tcoords_range<ndim> r;\n\tfor(int d = 0; d < ndim; d++) {\n\t\tcoord q = (total.upper[d] - total.lower[d])\/4;\n\t\tr.lower[d] = total.lower[d] + q;\n\t\tr.upper[d] = total.lower[d] + q * 3;\n\t}\n\treturn r;\n}\n\ntemplate<int ndim, typename S>\nunique_ptr<typename suite1<ndim,S>::T[]> suite1<ndim,S>::src_buf(coords_range<ndim> r) {\n\tconst typename S::accessor s(src);\n\tcoords<ndim+1> ld = r.stride();\n\tunique_ptr<T[]> ptr(new T[ld[0]]);\n\tr.for_each([&s,r,ld,&ptr](coords<ndim> ii) {\n\t\tptr[(ii - r.lower).offset(ld)] = s(ii);\n\t});\n\treturn ptr;\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_basic(tester& t) {\n\tt.begin_test(\"test_basic\");\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = src;\n\t\tt.add_result(check(ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_move(tester& t) {\n\tt.begin_test(\"test_move\");\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t{\n\t\t\tGlobalArray<ndim,T> tmp(dom);\n\t\t\ttmp = src;\n\t\t\tga = std::move(tmp);\n\t\t}\n\t\tt.add_result(check(ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost(tester& t) {\n\tt.begin_test(\"test_ghost\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\tcoords_range<ndim> inner = dom.total();\n\tfor(int d = 0; d < ndim; d++) {\n\t\tinner.lower[d] += gw[d];\n\t\tinner.upper[d] -= gw[d];\n\t}\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(inner, ga == src));\n\t\tfor(int d = 0; d < ndim; d++) {\n\t\t\tcoords<ndim> sd = {{}}, su = {{}};\n\t\t\tsd[d] = -1;\n\t\t\tsu[d] = 1;\n\t\t\tt.add_result(check(inner,\n\t\t\t\tshift(ga,sd) == shift(src,sd) &&\n\t\t\t\tshift(ga,su) == shift(src,su) &&\n\t\t\t\tshift(ga,sd+sd) == shift(src,sd+sd) &&\n\t\t\t\tshift(ga,su+su) == shift(src,su+su)));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost_corner(tester& t) {\n\tt.begin_test(\"test_ghost_corner\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\tcoords_range<ndim> inner = dom.total();\n\tfor(int d = 0; d < ndim; d++) {\n\t\tinner.lower[d] += gw[d];\n\t\tinner.upper[d] -= gw[d];\n\t}\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw, true);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(inner, ga == src));\n\t\tt.add_result(check(inner, shift(ga,gw) == shift(src,gw) && shift(ga,-gw) == shift(src,-gw)));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_ghost_periodic(tester& t) {\n\tt.begin_test(\"test_ghost_periodic\");\n\tcoords<ndim> gw;\n\tfor(int d = 0; d < ndim; d++)\n\t\tgw[d] = 2;\n\ttypename GlobalArray<ndim,T>::bounds bd;\n\tfor(int d = 0; d < ndim; d++)\n\t\tbd[d] = Boundary<ndim,T>::periodic();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom, gw, false, bd);\n\t\tga = src;\n\t\tga.update();\n\t\tt.add_result(check(ga == src));\n\t\tfor(int d = 0; d < ndim; d++) {\n\t\t\tcoords<ndim> sd = {{}}, su = {{}};\n\t\t\tsd[d] = -1;\n\t\t\tsu[d] = 1;\n\t\t\tt.add_result(check(\n\t\t\t\tshift(ga,sd) == shift(src,sd,dom.total()) &&\n\t\t\t\tshift(ga,su) == shift(src,su,dom.total()) && \n\t\t\t\tshift(ga,sd+sd) == shift(src,sd+sd,dom.total()) &&\n\t\t\t\tshift(ga,su+su) == shift(src,su+su,dom.total())));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_get(tester& t) {\n\tt.begin_test(\"test_get\");\n\tcoords_range<ndim> r = subrange();\n\tcoords<ndim+1> ld = r.stride();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = src;\n\t\t\/\/ Everyone does a \"get\" and checks the result\n\t\tunique_ptr<T[]> ptr(new T[ld[0]]);\n\t\tga.get(r, ptr.get());\n\t\t{\n\t\t\ttest_result tr = test_result();\n\t\t\tconst typename S::accessor s(src);\n\t\t\tr.for_each([&tr,&s,r,ld,&ptr](coords<ndim> ii) {\n\t\t\t\tif(s(ii) != ptr[(ii - r.lower).offset(ld)])\n\t\t\t\t\ttr.fails++;\n\t\t\t\ttr.checks++;\n\t\t\t});\n\t\t\t\/\/ Add everything together\n\t\t\tt.add_result(dom.group.external_sum(move(tr)));\n\t\t}\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_put(tester& t) {\n\tt.begin_test(\"test_put\");\n\tcoords_range<ndim> r = subrange();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t\/\/ First one does a put\n\t\tdom.group.sync();\n\t\tif (dom.group.procid == 0)\n\t\t\tga.put(r, src_buf(r).get());\n\t\tdom.group.sync();\n\t\t\/\/ Everyone helps check\n\t\tt.add_result(check(r, ga == src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_accumulate(tester& t) {\n\tt.begin_test(\"test_accumulate\");\n\tcoords_range<ndim> r = subrange();\n\t{\n\t\tGlobalArray<ndim,T> ga(dom);\n\t\tga = constant(dom, T());\n\t\t\/\/ First and last one contribute\n\t\tdom.group.sync();\n\t\tif (dom.group.procid == 0)\n\t\t\tga.accumulate(r, src_buf(r).get());\n\t\tif (dom.group.procid == dom.group.nprocs-1)\n\t\t\tga.accumulate(r, src_buf(r).get());\n\t\tdom.group.sync();\n\t\t\/\/ Everyone helps check\n\t\tt.add_result(check(r, ga == src+src));\n\t}\n\tt.end_test();\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_reshape_domain(tester& t, const Domain<ndim>& alt_dom) {\n\tGlobalArray<ndim,T> ga(dom);\n\tga = src;\n\tga.reshape(alt_dom);\n\tconst typename GlobalArray<ndim,T>::accessor a(ga);\n\tconst typename S::accessor s(src);\n\tt.add_result(alt_dom.sum(test_result(), [&a,&s](test_result& tr, coords<ndim> ii) {\n\t\tif(s(ii) != a(ii))\n\t\t\ttr.fails++;\n\t\ttr.checks++;\n\t}));\n}\n\ntemplate<int ndim, typename S>\nvoid suite1<ndim,S>::test_reshape(tester& t) {\n\tt.begin_test(\"test_reshape\");\n\t{\n\t\ttypename Domain<ndim>::pcoords row_np;\n\t\trow_np[0] = dom.group.nprocs;\n\t\tfor(int d = 1; d < ndim; d++)\n\t\t\trow_np[d] = 1;\n\t\ttest_reshape_domain(t, Domain<ndim>(dom.group, dom.n, row_np));\n\t\ttypename Domain<ndim>::pcoords col_np;\n\t\tfor(int d = 0; d < ndim-1; d++)\n\t\t\tcol_np[d] = 1;\n\t\tcol_np[ndim-1] = dom.group.nprocs;\n\t\ttest_reshape_domain(t, Domain<ndim>(dom.group, dom.n, col_np));\n\t}\n\tt.end_test();\n}\n\nint main(int argc, char* argv[]) {\n\tInit(&argc, &argv);\n\tSetupThreads();\n\ttester t(cerr);\n\tif(world().procid == 0)\n\t\tcerr << \"Testing <1,int>\" << endl;\n\t{\n\t\tcoords<1> n = {{1000}};\n\t\tDomain<1> dom(world(), n);\n\t\tauto f = coord_val<0>(dom, 1000);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tif(world().procid == 0)\n\t\tcerr << endl << \"Testing <3,double>\" << endl;\n\t{\n\t\tcoords<3> n = {{100,100,100}};\n\t\tDomain<3> dom(world(), n);\n\t\tauto f = sin(coord_val<0>(dom, 2*M_PI, false)) * cos(coord_val<1>(dom, 2*M_PI, false)) * coord_val<2>(dom, 1.0, false);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tif(world().procid == 0)\n\t\tcerr << endl << \"Testing <3,vec<3,double>>\" << endl;\n\t{\n\t\tcoords<3> n = {{100,100,100}};\n\t\tDomain<3> dom(world(), n);\n\t\tconst vec<3,double> one = {{1.0, 1.0, 1.0}};\n\t\tconst vec<3,double> mid = {{0.5, 0.5, 0.5}};\n\t\tauto f = abs(coord_vec(dom, one) - mid);\n\t\tmake_suite1(dom, f).run(t);\n\t}\n\tFinalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Shifts.hpp>\n#include <Dedispersion.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\ntypedef float dataType;\nstd::string typeName(\"float\");\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);\n\nint main(int argc, char * argv[]) {\n bool localMem = false;\n bool reInit = false;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tunsigned int minThreads = 0;\n unsigned int maxThreads = 0;\n\tunsigned int maxRows = 0;\n\tunsigned int maxColumns = 0;\n unsigned int threadUnit = 0;\n unsigned int threadIncrement = 0;\n unsigned int maxItems = 0;\n unsigned int maxUnroll = 0;\n unsigned int maxLoopBodySize = 0;\n AstroData::Observation observation;\n cl::Event event;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n localMem = args.getSwitch(\"-local\");\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n threadUnit = args.getSwitchArgument< unsigned int >(\"-thread_unit\");\n\t\tminThreads = args.getSwitchArgument< unsigned int >(\"-min_threads\");\n\t\tmaxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n\t\tmaxRows = args.getSwitchArgument< unsigned int >(\"-max_rows\");\n\t\tmaxColumns = args.getSwitchArgument< unsigned int >(\"-max_columns\");\n threadIncrement = args.getSwitchArgument< unsigned int >(\"-thread_increment\");\n\t\tmaxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxUnroll = args.getSwitchArgument< unsigned int >(\"-max_unroll\");\n maxLoopBodySize = args.getSwitchArgument< unsigned int >(\"-max_loopsize\");\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), args.getSwitchArgument< float >(\"-dm_first\"), args.getSwitchArgument< float >(\"-dm_step\"));\n\t} catch ( isa::utils::EmptyCommandLine & err ) {\n\t\tstd::cerr << argv[0] << \" -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ...\" << std::endl;\n\t\treturn 1;\n\t} catch ( std::exception & err ) {\n\t\tstd::cerr << err.what() << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Allocate host memory\n std::vector< float > * shifts = PulsarSearch::getShifts(observation);\n observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n\n\t\/\/ Initialize OpenCL\n\tcl::Context clContext;\n\tstd::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n\tstd::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n\tstd::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n\n\t\/\/ Allocate device memory\n cl::Buffer shifts_d;\n cl::Buffer dispersedData_d;\n cl::Buffer dedispersedData_d;\n\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n\n\t\/\/ Find the parameters\n\tstd::vector< unsigned int > samplesPerBlock;\n\tfor ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {\n\t\tif ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {\n\t\t\tsamplesPerBlock.push_back(samples);\n\t\t}\n\t}\n\tstd::vector< unsigned int > DMsPerBlock;\n\tfor ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {\n\t\tif ( (observation.getNrDMs() % DMs) == 0 ) {\n\t\t\tDMsPerBlock.push_back(DMs);\n\t\t}\n\t}\n\n\tstd::cout << std::fixed << std::endl;\n\tstd::cout << \"# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP\/s GB\/s time stdDeviation COV\" << std::endl << std::endl;\n\n\tfor ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {\n\t\tfor ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {\n\t\t\tif ( ((*samples) * (*DMs)) > maxThreads ) {\n\t\t\t\tbreak;\n\t\t\t} else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) {\n continue;\n }\n\n\t\t\tfor ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {\n\t\t\t\tif ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {\n\t\t\t\t\tif ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {\n if ( (observation.getNrChannels() - 1) % unroll != 0 ) {\n continue;\n } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) {\n break;\n }\n \/\/ Generate kernel\n double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());\n double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int)));\n isa::utils::Timer timer;\n cl::Kernel * kernel;\n std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"dedispersion\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n cl::NDRange global(observation.getNrSamplesPerSecond() \/ samplesPerThread, observation.getNrDMs() \/ DMsPerThread);\n cl::NDRange local(*samples, *DMs);\n\n kernel->setArg(0, dispersedData_d);\n kernel->setArg(1, dedispersedData_d);\n kernel->setArg(2, shifts_d);\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n timer.stop();\n }\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error kernel execution (\";\n std::cerr << localMem << \", \" << *samples << \", \" << *DMs << \", \" << samplesPerThread << \", \" << DMsPerThread << \", \" << unroll << \"): \";\n std::cerr << isa::utils::toString(err.err()) << \".\" << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n std::cout << observation.getNrDMs() << \" \" << observation.getNrChannels() << \" \" << observation.getNrSamplesPerSecond() << \" \" << localMem << \" \" << *samples << \" \" << *DMs << \" \" << samplesPerThread << \" \" << DMsPerThread << \" \" << unroll << \" \";\n std::cout << std::setprecision(3);\n std::cout << gflops \/ timer.getAverageTime() << \" \";\n std::cout << gbs \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \";\n std::cout << timer.getCoefficientOfVariation() << std::endl;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {\n try {\n *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0);\n *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);\n *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);\n clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data()));\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error: \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\n<commit_msg>Sync the device during memory transfers.<commit_after>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Shifts.hpp>\n#include <Dedispersion.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\ntypedef float dataType;\nstd::string typeName(\"float\");\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);\n\nint main(int argc, char * argv[]) {\n bool localMem = false;\n bool reInit = false;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tunsigned int minThreads = 0;\n unsigned int maxThreads = 0;\n\tunsigned int maxRows = 0;\n\tunsigned int maxColumns = 0;\n unsigned int threadUnit = 0;\n unsigned int threadIncrement = 0;\n unsigned int maxItems = 0;\n unsigned int maxUnroll = 0;\n unsigned int maxLoopBodySize = 0;\n AstroData::Observation observation;\n cl::Event event;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n localMem = args.getSwitch(\"-local\");\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n threadUnit = args.getSwitchArgument< unsigned int >(\"-thread_unit\");\n\t\tminThreads = args.getSwitchArgument< unsigned int >(\"-min_threads\");\n\t\tmaxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n\t\tmaxRows = args.getSwitchArgument< unsigned int >(\"-max_rows\");\n\t\tmaxColumns = args.getSwitchArgument< unsigned int >(\"-max_columns\");\n threadIncrement = args.getSwitchArgument< unsigned int >(\"-thread_increment\");\n\t\tmaxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxUnroll = args.getSwitchArgument< unsigned int >(\"-max_unroll\");\n maxLoopBodySize = args.getSwitchArgument< unsigned int >(\"-max_loopsize\");\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), args.getSwitchArgument< float >(\"-dm_first\"), args.getSwitchArgument< float >(\"-dm_step\"));\n\t} catch ( isa::utils::EmptyCommandLine & err ) {\n\t\tstd::cerr << argv[0] << \" -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ...\" << std::endl;\n\t\treturn 1;\n\t} catch ( std::exception & err ) {\n\t\tstd::cerr << err.what() << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Allocate host memory\n std::vector< float > * shifts = PulsarSearch::getShifts(observation);\n observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n\n\t\/\/ Initialize OpenCL\n\tcl::Context clContext;\n\tstd::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n\tstd::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n\tstd::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n\n\t\/\/ Allocate device memory\n cl::Buffer shifts_d;\n cl::Buffer dispersedData_d;\n cl::Buffer dedispersedData_d;\n\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n\n\t\/\/ Find the parameters\n\tstd::vector< unsigned int > samplesPerBlock;\n\tfor ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {\n\t\tif ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {\n\t\t\tsamplesPerBlock.push_back(samples);\n\t\t}\n\t}\n\tstd::vector< unsigned int > DMsPerBlock;\n\tfor ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {\n\t\tif ( (observation.getNrDMs() % DMs) == 0 ) {\n\t\t\tDMsPerBlock.push_back(DMs);\n\t\t}\n\t}\n\n\tstd::cout << std::fixed << std::endl;\n\tstd::cout << \"# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP\/s GB\/s time stdDeviation COV\" << std::endl << std::endl;\n\n\tfor ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {\n\t\tfor ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {\n\t\t\tif ( ((*samples) * (*DMs)) > maxThreads ) {\n\t\t\t\tbreak;\n\t\t\t} else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) {\n continue;\n }\n\n\t\t\tfor ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {\n\t\t\t\tif ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {\n\t\t\t\t\tif ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {\n if ( (observation.getNrChannels() - 1) % unroll != 0 ) {\n continue;\n } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) {\n break;\n }\n \/\/ Generate kernel\n double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());\n double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int)));\n isa::utils::Timer timer;\n cl::Kernel * kernel;\n std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"dedispersion\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n cl::NDRange global(observation.getNrSamplesPerSecond() \/ samplesPerThread, observation.getNrDMs() \/ DMsPerThread);\n cl::NDRange local(*samples, *DMs);\n\n kernel->setArg(0, dispersedData_d);\n kernel->setArg(1, dedispersedData_d);\n kernel->setArg(2, shifts_d);\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n timer.stop();\n }\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error kernel execution (\";\n std::cerr << localMem << \", \" << *samples << \", \" << *DMs << \", \" << samplesPerThread << \", \" << DMsPerThread << \", \" << unroll << \"): \";\n std::cerr << isa::utils::toString(err.err()) << \".\" << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n std::cout << observation.getNrDMs() << \" \" << observation.getNrChannels() << \" \" << observation.getNrSamplesPerSecond() << \" \" << localMem << \" \" << *samples << \" \" << *DMs << \" \" << samplesPerThread << \" \" << DMsPerThread << \" \" << unroll << \" \";\n std::cout << std::setprecision(3);\n std::cout << gflops \/ timer.getAverageTime() << \" \";\n std::cout << gbs \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \";\n std::cout << timer.getCoefficientOfVariation() << std::endl;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {\n try {\n *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0);\n *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);\n *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);\n clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data()));\n clQueue->finish();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error: \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"openqpritz.h\"\n\n\/\/ コンストラクタ(sentenceの場合) \/ Constructor\nOpenQpritz::OpenQpritz(const QString sentence, const int spritzWpmNumber)\n{\n m_wordList = makeWordList(sentence);\n m_spritzWpmNumber = spritzWpmNumber;\n\n spritzLoopNumber = 0;\n m_timer = new QTimer();\n}\n\n\n\/\/ コンストラクタ(wordListの場合) \/ Constructor\nOpenQpritz::OpenQpritz(const QStringList wordList, const int spritzWpmNumber)\n{\n m_wordList = wordList;\n m_spritzWpmNumber = spritzWpmNumber;\n\n spritzLoopNumber = 0;\n m_timer = new QTimer();\n}\n\n\n\/\/ 文章を単語リストに加工 \/ make wordList from sentence\nQStringList OpenQpritz::makeWordList(QString sentence)\n{\n QStringList wordListTemp;\n\n \/\/ 無選択の場合はreturn \/ if nothing selected, return\n if (sentence == \"\" | sentence == \" \") {\n wordListTemp.clear();\n return wordListTemp;\n }\n\n \/\/ webViewの選択範囲の先頭・後尾の空白文字の要素消去、分割\n wordListTemp = sentence.trimmed().split(QRegExp(\"(\\\\s|\\n)+\"));\n\n \/\/ wordListを返す \/ return the wordListTemp\n return wordListTemp;\n}\n\n\n\/\/ spritzの開始 \/ start spritz\nvoid OpenQpritz::start(int intervalNumber)\n{\n if (intervalNumber > 0) {\n qDebug(\"start(%d)\", intervalNumber);\n\n startupLoopNumber = intervalNumber + 1;\n connect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n\n m_timer->start(60 * 1000 \/ m_spritzWpmNumber);\n } else {\n qDebug(\"spritz\");\n\n if (m_spritzWpmNumber) {\n connect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n\n m_timer->start(60 * 1000 \/ m_spritzWpmNumber);\n }\n }\n}\n\n\n\/\/ 始動動作 \/ startup action\nvoid OpenQpritz::startup()\n{\n QString startupWordToShow = \"\";\n QString startupWord = \".\";\n\n if (startupLoopNumber > 0) {\n qDebug(\"startup(%d)\", startupLoopNumber);\n\n startupWordToShow += \"<font color = black>\" + startupWord.repeated(startupLoopNumber - 1) + \"<\/font>\";\n startupWordToShow += \"<font color = red>\" + startupWord + \"<\/font>\";\n startupWordToShow += \"<font color = black>\" + startupWord.repeated(startupLoopNumber - 1) + \"<\/font>\";\n startupWordToShow += \"<font color = transparent>.<\/font>\";\n\n emit outputSpritzWord(startupWordToShow);\n startupLoopNumber --;\n qDebug(\"loop\");\n } else {\n qDebug(\"%d startup\", startupLoopNumber);\n\n emit outputSpritzWord(startupWordToShow);\n startupLoopNumber --;\n qDebug(\"loop end\");\n\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n start(0);\n }\n}\n\n\n\/\/ spritzの一時停止 \/ pause spritz\nvoid OpenQpritz::pause()\n{\n m_timer->stop();\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n}\n\n\n\/\/ spritzの停止 \/ stop spritz\nvoid OpenQpritz::stop()\n{\n m_timer->stop();\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n spritzLoopNumber = 0;\n}\n\n\n\/\/ spritzCore関数 \/ spritz core function\nvoid OpenQpritz::spritz()\n{\n if (spritzLoopNumber < m_wordList.count()) {\n m_wordTemp = m_wordList[spritzLoopNumber];\n wordToShow = processWordForSpritz(m_wordList[spritzLoopNumber]);\n emit outputSpritzWord(wordToShow);\n\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n spritzLoopNumber += 1;\n } else {\n m_wordTemp = \"\";\n wordToShow = m_wordTemp;\n emit outputSpritzWord(m_wordTemp);\n\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n m_timer->stop();\n spritzLoopNumber = 0;\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n\n emit finishSpritz();\n }\n}\n\n\n\/\/ 単語をspritz用に加工 \/ process word for spritz\nQString OpenQpritz::processWordForSpritz(QString word)\n{\n int length = word.length();\n\n int bestLetter = 1;\n\n switch (length) {\n case 1:\n bestLetter = 1; \/\/ first\n break;\n case 2:\n case 3:\n case 4:\n case 5:\n bestLetter = 2; \/\/ second\n break;\n case 6:\n case 7:\n case 8:\n case 9:\n bestLetter = 3; \/\/ third\n break;\n case 10:\n case 11:\n case 12:\n case 13:\n bestLetter = 4; \/\/ fourth\n break;\n default:\n bestLetter = 5;\n }\n\n QString frontSpacer = QString(\".\").repeated(11 - bestLetter);\n QString frontWordPeace = word.mid(0, bestLetter - 1);\n QString coreWordPeace = word.mid(bestLetter - 1, 1);\n QString backWordPeace = word.mid(bestLetter, length - bestLetter);\n QString backSpacer = QString(\".\").repeated((11-(word.length() - bestLetter)));\n\n QString result = \"<font color = Transparent>\" + frontSpacer + \"<\/font>\";\n result += \"<font color = black>\" + frontWordPeace + \"<\/font>\";\n result += \"<font color = red>\" + coreWordPeace + \"<\/font>\";\n result += \"<font clor = black>\" + backWordPeace + \"<\/font>\";\n result += \"<font color = Transparent>\" + backSpacer + \"<\/font>\";\n\n return result;\n}\n\n\n\/\/ spritzWpmNumの更新 \/ update spritzWpmNum\nvoid OpenQpritz::setSpritzWpmNumber(const int newSpritzWpmNumber)\n{\n m_spritzWpmNumber = newSpritzWpmNumber;\n}\n<commit_msg>improvement speed a little, little bit<commit_after>#include \"openqpritz.h\"\n\n\/\/ コンストラクタ(sentenceの場合) \/ Constructor\nOpenQpritz::OpenQpritz(const QString sentence, const int spritzWpmNumber)\n{\n m_wordList = makeWordList(sentence);\n m_spritzWpmNumber = spritzWpmNumber;\n\n spritzLoopNumber = 0;\n m_timer = new QTimer();\n}\n\n\n\/\/ コンストラクタ(wordListの場合) \/ Constructor\nOpenQpritz::OpenQpritz(const QStringList wordList, const int spritzWpmNumber)\n{\n m_wordList = wordList;\n m_spritzWpmNumber = spritzWpmNumber;\n\n spritzLoopNumber = 0;\n m_timer = new QTimer();\n}\n\n\n\/\/ 文章を単語リストに加工 \/ make wordList from sentence\nQStringList OpenQpritz::makeWordList(QString sentence)\n{\n QStringList wordListTemp;\n\n \/\/ 無選択の場合はreturn \/ if nothing selected, return\n if (sentence == \"\" | sentence == \" \") {\n wordListTemp.clear();\n return wordListTemp;\n }\n\n \/\/ webViewの選択範囲の先頭・後尾の空白文字の要素消去、分割\n wordListTemp = sentence.trimmed().split(QRegExp(\"(\\\\s|\\n)+\"));\n\n \/\/ wordListを返す \/ return the wordListTemp\n return wordListTemp;\n}\n\n\n\/\/ spritzの開始 \/ start spritz\nvoid OpenQpritz::start(int intervalNumber)\n{\n if (intervalNumber > 0) {\n qDebug(\"start(%d)\", intervalNumber);\n\n startupLoopNumber = intervalNumber + 1;\n connect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n\n m_timer->start(60 * 1000 \/ m_spritzWpmNumber);\n } else {\n qDebug(\"spritz\");\n\n if (m_spritzWpmNumber) {\n connect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n\n m_timer->start(60 * 1000 \/ m_spritzWpmNumber);\n }\n }\n}\n\n\n\/\/ 始動動作 \/ startup action\nvoid OpenQpritz::startup()\n{\n QString startupWordToShow = \"\";\n QString startupWord = \".\";\n\n if (startupLoopNumber > 0) {\n qDebug(\"startup(%d)\", startupLoopNumber);\n\n startupWordToShow += \"<font color = black>\" + startupWord.repeated(startupLoopNumber - 1) + \"<\/font>\";\n startupWordToShow += \"<font color = red>\" + startupWord + \"<\/font>\";\n startupWordToShow += \"<font color = black>\" + startupWord.repeated(startupLoopNumber - 1) + \"<\/font>\";\n startupWordToShow += \"<font color = transparent>.<\/font>\";\n\n emit outputSpritzWord(startupWordToShow);\n startupLoopNumber --;\n qDebug(\"loop\");\n } else {\n qDebug(\"%d startup\", startupLoopNumber);\n\n emit outputSpritzWord(startupWordToShow);\n startupLoopNumber --;\n qDebug(\"loop end\");\n\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n start(0);\n }\n}\n\n\n\/\/ spritzの一時停止 \/ pause spritz\nvoid OpenQpritz::pause()\n{\n m_timer->stop();\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n}\n\n\n\/\/ spritzの停止 \/ stop spritz\nvoid OpenQpritz::stop()\n{\n m_timer->stop();\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(startup()));\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n spritzLoopNumber = 0;\n}\n\n\n\/\/ spritzCore関数 \/ spritz core function\nvoid OpenQpritz::spritz()\n{\n if (spritzLoopNumber < m_wordList.count()) {\n m_wordTemp = m_wordList[spritzLoopNumber];\n wordToShow = processWordForSpritz(m_wordList[spritzLoopNumber]);\n emit outputSpritzWord(wordToShow);\n\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n spritzLoopNumber += 1;\n } else {\n m_wordTemp = \"\";\n wordToShow = m_wordTemp;\n emit outputSpritzWord(m_wordTemp);\n\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n m_timer->stop();\n spritzLoopNumber = 0;\n qDebug(\"%d\\t\" + m_wordTemp.toLatin1(), spritzLoopNumber);\n\n disconnect(m_timer, SIGNAL(timeout()),\n this, SLOT(spritz()));\n\n emit finishSpritz();\n }\n}\n\n\n\/\/ 単語をspritz用に加工 \/ process word for spritz\nQString OpenQpritz::processWordForSpritz(QString word)\n{\n int length = word.length();\n\n int bestLetter = 1;\n\n if (length < 14) {\n bestLetter = (length + 2) \/ 4 + 1;\n\n \/\/ length = 1 -> bestLetter = 1\n \/\/ length = 2~5 -> bestLetter = 2\n \/\/ length = 6~9 -> bestLetter = 3\n \/\/ length = 10~13 -> bestLetter = 4\n } else {\n bestLetter = 5;\n\n \/\/ length = 14~ -> bestLetter = (length + 2) \/ 4 + 1;\n }\n\n QString frontSpacer = QString(\".\").repeated(11 - bestLetter);\n QString frontWordPeace = word.mid(0, bestLetter - 1);\n QString coreWordPeace = word.mid(bestLetter - 1, 1);\n QString backWordPeace = word.mid(bestLetter, length - bestLetter);\n QString backSpacer = QString(\".\").repeated((11-(word.length() - bestLetter)));\n\n QString result = \"<font color = Transparent>\" + frontSpacer + \"<\/font>\";\n result += \"<font color = black>\" + frontWordPeace + \"<\/font>\";\n result += \"<font color = red>\" + coreWordPeace + \"<\/font>\";\n result += \"<font clor = black>\" + backWordPeace + \"<\/font>\";\n result += \"<font color = Transparent>\" + backSpacer + \"<\/font>\";\n\n return result;\n}\n\n\n\/\/ spritzWpmNumの更新 \/ update spritzWpmNum\nvoid OpenQpritz::setSpritzWpmNumber(const int newSpritzWpmNumber)\n{\n m_spritzWpmNumber = newSpritzWpmNumber;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: InlineContainer.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 20:18:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n#define INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include <vector>\n#include <map>\n#include <set>\n\nnamespace comphelper\n{\n\n\/** Creates a UNO-Sequence which contains an arbitrary number of elements.\n Notice, that every call of the operator() issues a realloc, so this is not\n suitable to create very large sequences.\n\n usage:\n\n uno::Sequence< t >( MakeSequence< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeSequence : public ::com::sun::star::uno::Sequence< T >\n{\npublic:\n explicit MakeSequence(const T &a)\n : ::com::sun::star::uno::Sequence< T >( 1 )\n {\n this->operator[](0) = a;\n }\n MakeSequence& operator()(const T &a)\n {\n this->realloc( this->getLength() + 1 );\n this->operator[]( this->getLength() - 1 ) = a;\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** Creates a vector which contains an arbitrary number of elements.\n\n usage:\n\n vector< t > aVec( MakeVector< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeVector : public ::std::vector< T >\n{\npublic:\n explicit MakeVector(const T &a)\n : ::std::vector< T >(1, a)\n {\n }\n MakeVector &operator()(const T &a)\n {\n this->push_back(a);\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** Creates a set which contains an arbitrary number of elements.\n\n usage:\n\n set< t > aSet( MakeSet< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeSet : public ::std::set< T >\n{\npublic:\n explicit MakeSet(const T &a)\n : ::std::set< T >()\n {\n insert(this->end(), a);\n }\n MakeSet &operator()(const T &a)\n {\n this->insert(this->end(), a);\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** usage:\n\n map< k, v > aMap( MakeMap< k, v >\n ( key_1, value_1 )\n ( key_2, value_2 )\n ( key_3, value_3 )\n ...\n ( key_n, value_n )\n );\n *\/\ntemplate < typename Key, typename Value >\nclass MakeMap : public ::std::map< Key, Value >\n{\nprivate:\n typedef typename ::std::map< Key, Value >::value_type value_type;\npublic:\n explicit MakeMap( const Key &k, const Value &v )\n {\n this->insert( value_type( k, v ) );\n }\n MakeMap &operator()( const Key &k, const Value &v )\n {\n this->insert( value_type( k, v ) );\n return *this;\n }\n\n MakeMap &operator()( const MakeMap& rSource )\n {\n this->insert(rSource.begin(),rSource.end());\n return *this;\n }\n};\n\n} \/\/ namespace comphelper\n\n#endif\n\/\/ INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.110); FILE MERGED 2008\/03\/31 12:19:26 rt 1.3.110.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: InlineContainer.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n#define INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include <vector>\n#include <map>\n#include <set>\n\nnamespace comphelper\n{\n\n\/** Creates a UNO-Sequence which contains an arbitrary number of elements.\n Notice, that every call of the operator() issues a realloc, so this is not\n suitable to create very large sequences.\n\n usage:\n\n uno::Sequence< t >( MakeSequence< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeSequence : public ::com::sun::star::uno::Sequence< T >\n{\npublic:\n explicit MakeSequence(const T &a)\n : ::com::sun::star::uno::Sequence< T >( 1 )\n {\n this->operator[](0) = a;\n }\n MakeSequence& operator()(const T &a)\n {\n this->realloc( this->getLength() + 1 );\n this->operator[]( this->getLength() - 1 ) = a;\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** Creates a vector which contains an arbitrary number of elements.\n\n usage:\n\n vector< t > aVec( MakeVector< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeVector : public ::std::vector< T >\n{\npublic:\n explicit MakeVector(const T &a)\n : ::std::vector< T >(1, a)\n {\n }\n MakeVector &operator()(const T &a)\n {\n this->push_back(a);\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** Creates a set which contains an arbitrary number of elements.\n\n usage:\n\n set< t > aSet( MakeSet< t >( t_1 )( t_2 )...( t_n ) );\n *\/\ntemplate < typename T >\nclass MakeSet : public ::std::set< T >\n{\npublic:\n explicit MakeSet(const T &a)\n : ::std::set< T >()\n {\n insert(this->end(), a);\n }\n MakeSet &operator()(const T &a)\n {\n this->insert(this->end(), a);\n return *this;\n }\n};\n\n\/\/ ----------------------------------------\n\n\/** usage:\n\n map< k, v > aMap( MakeMap< k, v >\n ( key_1, value_1 )\n ( key_2, value_2 )\n ( key_3, value_3 )\n ...\n ( key_n, value_n )\n );\n *\/\ntemplate < typename Key, typename Value >\nclass MakeMap : public ::std::map< Key, Value >\n{\nprivate:\n typedef typename ::std::map< Key, Value >::value_type value_type;\npublic:\n explicit MakeMap( const Key &k, const Value &v )\n {\n this->insert( value_type( k, v ) );\n }\n MakeMap &operator()( const Key &k, const Value &v )\n {\n this->insert( value_type( k, v ) );\n return *this;\n }\n\n MakeMap &operator()( const MakeMap& rSource )\n {\n this->insert(rSource.begin(),rSource.end());\n return *this;\n }\n};\n\n} \/\/ namespace comphelper\n\n#endif\n\/\/ INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX\n<|endoftext|>"} {"text":"<commit_before>\r\n\/*\r\n\tcalculator08buggy.cpp\r\n\r\n\tHelpful comments removed.\r\n\r\n\tWe have inserted 3 bugs that the compiler will catch and 3 that it won't.\r\n*\/\r\n\r\n#include \"std_lib_facilities.h\"\r\n\r\nstruct Token {\r\n\tchar kind;\r\n\tdouble value;\r\n\tstring name;\r\n\tToken(char ch) :kind(ch), value(0) { }\r\n\tToken(char ch, double val) :kind(ch), value(val) { }\r\n};\r\n\r\nclass Token_stream {\r\n\tbool full;\r\n\tToken buffer;\r\npublic:\r\n\tToken_stream() :full(0), buffer(0) { }\r\n\r\n\tToken get();\r\n\tvoid unget(Token t) { buffer=t; full=true; }\r\n\r\n\tvoid ignore(char);\r\n};\r\n\r\nconst char let = 'L';\r\nconst char quit = 'Q';\r\nconst char print = ';';\r\nconst char number = '8';\r\nconst char name = 'a';\r\n\r\nToken Token_stream::get()\r\n{\r\n\tif (full) { full=false; return buffer; }\r\n\tchar ch;\r\n\tcin >> ch;\r\n\tswitch (ch) {\r\n\tcase '(':\r\n\tcase ')':\r\n\tcase '+':\r\n\tcase '-':\r\n\tcase '*':\r\n\tcase '\/':\r\n\tcase '%':\r\n\tcase ';':\r\n\tcase '=':\r\n\t\treturn Token(ch);\r\n\tcase '.':\r\n\tcase '0':\r\n\tcase '1':\r\n\tcase '2':\r\n\tcase '3':\r\n\tcase '4':\r\n\tcase '5':\r\n\tcase '6':\r\n\tcase '7':\r\n\tcase '8':\r\n\tcase '9':\r\n\t{\tcin.unget();\r\n\t\tdouble val;\r\n\t\tcin >> val;\r\n\t\treturn Token(number,val);\r\n\t}\r\n\tdefault:\r\n\t\tif (isalpha(ch)) {\r\n\t\t\tstring s;\r\n\t\t\ts += ch;\r\n\t\t\twhile(cin.get(ch) && (isalpha(ch) || isdigit(ch))) s=ch;\r\n\t\t\tcin.unget();\r\n\t\t\tif (s == \"let\") return Token(let);\t\r\n\t\t\tif (s == \"quit\") return Token(name);\r\n\t\t\treturn Token(name,s);\r\n\t\t}\r\n\t\terror(\"Bad token\");\r\n\t}\r\n}\r\n\r\nvoid Token_stream::ignore(char c)\r\n{\r\n\tif (full && c==buffer.kind) {\r\n\t\tfull = false;\r\n\t\treturn;\r\n\t}\r\n\tfull = false;\r\n\r\n\tchar ch;\r\n\twhile (cin>>ch)\r\n\t\tif (ch==c) return;\r\n}\r\n\r\nstruct Variable {\r\n\tstring name;\r\n\tdouble value;\r\n\tVariable(string n, double v) :name(n), value(v) { }\r\n};\r\n\r\nvector<Variable> names;\t\r\n\r\ndouble get_value(string s)\r\n{\r\n\tfor (int i = 0; i<names.size(); ++i)\r\n\t\tif (names[i].name == s) return names[i].value;\r\n\terror(\"get: undefined name \",s);\r\n}\r\n\r\nvoid set_value(string s, double d)\r\n{\r\n\tfor (int i = 0; i<=names.size(); ++i)\r\n\t\tif (names[i].name == s) {\r\n\t\t\tnames[i].value = d;\r\n\t\t\treturn;\r\n\t\t}\r\n\terror(\"set: undefined name \",s);\r\n}\r\n\r\nbool is_declared(string s)\r\n{\r\n\tfor (int i = 0; i<names.size(); ++i)\r\n\t\tif (names[i].name == s) return true;\r\n\treturn false;\r\n}\r\n\r\nToken_stream ts;\r\n\r\ndouble expression();\r\n\r\ndouble primary()\r\n{\r\n\tToken t = ts.get();\r\n\tswitch (t.kind) {\r\n\tcase '(':\r\n\t{\tdouble d = expression();\r\n\t\tt = ts.get();\r\n\t\tif (t.kind != ')') error(\"'(' expected\");\r\n\t}\r\n\tcase '-':\r\n\t\treturn - primary();\r\n\tcase number:\r\n\t\treturn t.value;\r\n\tcase name:\r\n\t\treturn get_value(t.name);\r\n\tdefault:\r\n\t\terror(\"primary expected\");\r\n\t}\r\n}\r\n\r\ndouble term()\r\n{\r\n\tdouble left = primary();\r\n\twhile(true) {\r\n\t\tToken t = ts.get();\r\n\t\tswitch(t.kind) {\r\n\t\tcase '*':\r\n\t\t\tleft *= primary();\r\n\t\t\tbreak;\r\n\t\tcase '\/':\r\n\t\t{\tdouble d = primary();\r\n\t\t\tif (d == 0) error(\"divide by zero\");\r\n\t\t\tleft \/= d;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tts.unget(t);\r\n\t\t\treturn left;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ndouble expression()\r\n{\r\n\tdouble left = term();\r\n\twhile(true) {\r\n\t\tToken t = ts.get();\r\n\t\tswitch(t.kind) {\r\n\t\tcase '+':\r\n\t\t\tleft += term();\r\n\t\t\tbreak;\r\n\t\tcase '-':\r\n\t\t\tleft -= term();\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tts.unget(t);\r\n\t\t\treturn left;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ndouble declaration()\r\n{\r\n\tToken t = ts.get();\r\n\tif (t.kind != 'a') error (\"name expected in declaration\");\r\n\tstring name = t.name;\r\n\tif (is_declared(name)) error(name, \" declared twice\");\r\n\tToken t2 = ts.get();\r\n\tif (t2.kind != '=') error(\"= missing in declaration of \" ,name);\r\n\tdouble d = expression();\r\n\tnames.push_back(Variable(name,d));\r\n\treturn d;\r\n}\r\n\r\ndouble statement()\r\n{\r\n\tToken t = ts.get();\r\n\tswitch(t.kind) {\r\n\tcase let:\r\n\t\treturn declaration();\r\n\tdefault:\r\n\t\tts.unget(t);\r\n\t\treturn expression();\r\n\t}\r\n}\r\n\r\nvoid clean_up_mess()\r\n{\r\n\tts.ignore(print);\r\n}\r\n\r\nconst string prompt = \"> \";\r\nconst string result = \"= \";\r\n\r\nvoid calculate()\r\n{\r\n\twhile(true) try {\r\n\t\tcout << prompt;\r\n\t\tToken t = ts.get();\r\n\t\twhile (t.kind == print) t=ts.get();\r\n\t\tif (t.kind == quit) return;\r\n\t\tts.unget(t);\r\n\t\tcout << result << statement() << endl;\r\n\t}\r\n\tcatch(runtime_error& e) {\r\n\t\tcerr << e.what() << endl;\r\n\t\tclean_up_mess();\r\n\t}\r\n}\r\n\r\nint main()\r\n\r\n\ttry {\r\n\t\tcalculate();\r\n\t\treturn 0;\r\n\t}\r\n\tcatch (exception& e) {\r\n\t\tcerr << \"exception: \" << e.what() << endl;\r\n\t\tchar c;\r\n\t\twhile (cin >>c&& c!=';') ;\r\n\t\treturn 1;\r\n\t}\r\n\tcatch (...) {\r\n\t\tcerr << \"exception\\n\";\r\n\t\tchar c;\r\n\t\twhile (cin>>c && c!=';');\r\n\t\treturn 2;\r\n\t}\r\n<commit_msg>Fix bug on calculator08.cpp - drill 1<commit_after>\r\n\/*\r\n\tcalculator08buggy.cpp\r\n\r\n\tHelpful comments removed.\r\n\r\n\tWe have inserted 3 bugs that the compiler will catch and 3 that it won't.\r\n*\/\r\n\r\n#include \"..\/std_lib_facilities.h\"\r\n\r\nstruct Token {\r\n\tchar kind;\r\n\tdouble value;\r\n\tstring name;\r\n\tToken(char ch) :kind(ch), value(0) { }\r\n\tToken(char ch, double val) :kind(ch), value(val) { }\r\n\tToken(char ch, string n): kind(ch), name(n) {}\r\n};\r\n\r\nclass Token_stream {\r\n\tbool full;\r\n\tToken buffer;\r\npublic:\r\n\tToken_stream() :full(0), buffer(0) { }\r\n\r\n\tToken get();\r\n\tvoid unget(Token t) { buffer=t; full=true; }\r\n\r\n\tvoid ignore(char);\r\n};\r\n\r\nconst char let = 'L';\r\nconst char quit = 'Q';\r\nconst char print = ';';\r\nconst char number = '8';\r\nconst char name = 'a';\r\n\r\nToken Token_stream::get()\r\n{\r\n\tif (full) { full=false; return buffer; }\r\n\tchar ch;\r\n\tcin >> ch;\r\n\tswitch (ch) {\r\n\tcase '(':\r\n\tcase ')':\r\n\tcase '+':\r\n\tcase '-':\r\n\tcase '*':\r\n\tcase '\/':\r\n\tcase '%':\r\n\tcase ';':\r\n\tcase '=':\r\n\t\treturn Token(ch);\r\n\tcase '.':\r\n\tcase '0':\r\n\tcase '1':\r\n\tcase '2':\r\n\tcase '3':\r\n\tcase '4':\r\n\tcase '5':\r\n\tcase '6':\r\n\tcase '7':\r\n\tcase '8':\r\n\tcase '9':\r\n\t{\r\n\t\tcin.unget();\r\n\t\tdouble val;\r\n\t\tcin >> val;\r\n\t\treturn Token(number,val);\r\n\t}\r\n\tdefault:\r\n\t\tif (isalpha(ch)) {\r\n\t\t\tstring s;\r\n\t\t\ts += ch;\r\n\t\t\twhile(cin.get(ch) && (isalpha(ch) || isdigit(ch))) s+=ch;\r\n\t\t\tcin.unget();\r\n\t\t\tif (s == \"let\") return Token(let);\r\n\t\t\tif (s == \"quit\") return Token(name);\r\n\t\t\treturn Token(name,s);\r\n\t\t}\r\n\t\terror(\"Bad token\");\r\n\t}\r\n}\r\n\r\nvoid Token_stream::ignore(char c)\r\n{\r\n\tif (full && c==buffer.kind) {\r\n\t\tfull = false;\r\n\t\treturn;\r\n\t}\r\n\tfull = false;\r\n\r\n\tchar ch;\r\n\twhile (cin>>ch)\r\n\t\tif (ch==c) return;\r\n}\r\n\r\nstruct Variable {\r\n\tstring name;\r\n\tdouble value;\r\n\tVariable(string n, double v) :name(n), value(v) { }\r\n};\r\n\r\nvector<Variable> names;\r\n\r\ndouble get_value(string s)\r\n{\r\n\tfor (int i = 0; i<names.size(); ++i)\r\n\t\tif (names[i].name == s) return names[i].value;\r\n\terror(\"get: undefined name \",s);\r\n}\r\n\r\nvoid set_value(string s, double d)\r\n{\r\n\tfor (int i = 0; i<=names.size(); ++i)\r\n\t\tif (names[i].name == s) {\r\n\t\t\tnames[i].value = d;\r\n\t\t\treturn;\r\n\t\t}\r\n\terror(\"set: undefined name \",s);\r\n}\r\n\r\nbool is_declared(string s)\r\n{\r\n\tfor (int i = 0; i<names.size(); ++i)\r\n\t\tif (names[i].name == s) return true;\r\n\treturn false;\r\n}\r\n\r\nToken_stream ts;\r\n\r\ndouble expression();\r\n\r\ndouble primary()\r\n{\r\n\tToken t = ts.get();\r\n\tswitch (t.kind) {\r\n\tcase '(':\r\n\t{\tdouble d = expression();\r\n\t\tt = ts.get();\r\n\t\tif (t.kind != ')') error(\"'(' expected\");\r\n\t}\r\n\tcase '-':\r\n\t\treturn - primary();\r\n\tcase number:\r\n\t\treturn t.value;\r\n\tcase name:\r\n\t\treturn get_value(t.name);\r\n\tdefault:\r\n\t\terror(\"primary expected\");\r\n\t}\r\n}\r\n\r\ndouble term()\r\n{\r\n\tdouble left = primary();\r\n\twhile(true) {\r\n\t\tToken t = ts.get();\r\n\t\tswitch(t.kind) {\r\n\t\tcase '*':\r\n\t\t\tleft *= primary();\r\n\t\t\tbreak;\r\n\t\tcase '\/':\r\n\t\t{\tdouble d = primary();\r\n\t\t\tif (d == 0) error(\"divide by zero\");\r\n\t\t\tleft \/= d;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tts.unget(t);\r\n\t\t\treturn left;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ndouble expression()\r\n{\r\n\tdouble left = term();\r\n\twhile(true) {\r\n\t\tToken t = ts.get();\r\n\t\tswitch(t.kind) {\r\n\t\tcase '+':\r\n\t\t\tleft += term();\r\n\t\t\tbreak;\r\n\t\tcase '-':\r\n\t\t\tleft -= term();\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tts.unget(t);\r\n\t\t\treturn left;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ndouble declaration()\r\n{\r\n\tToken t = ts.get();\r\n\tif (t.kind != 'a') error (\"name expected in declaration\");\r\n\tstring name = t.name;\r\n\tif (is_declared(name)) error(name, \" declared twice\");\r\n\tToken t2 = ts.get();\r\n\tif (t2.kind != '=') error(\"= missing in declaration of \" ,name);\r\n\tdouble d = expression();\r\n\tnames.push_back(Variable(name,d));\r\n\treturn d;\r\n}\r\n\r\ndouble statement()\r\n{\r\n\tToken t = ts.get();\r\n\tswitch(t.kind) {\r\n\tcase let:\r\n\t\treturn declaration();\r\n\tdefault:\r\n\t\tts.unget(t);\r\n\t\treturn expression();\r\n\t}\r\n}\r\n\r\nvoid clean_up_mess()\r\n{\r\n\tts.ignore(print);\r\n}\r\n\r\nconst string prompt = \"> \";\r\nconst string result = \"= \";\r\n\r\nvoid calculate()\r\n{\r\n\twhile(true) try {\r\n\t\tcout << prompt;\r\n\t\tToken t = ts.get();\r\n\t\twhile (t.kind == print) t=ts.get();\r\n\t\tif (t.kind == quit) return;\r\n\t\tts.unget(t);\r\n\t\tcout << result << statement() << endl;\r\n\t}\r\n\tcatch(runtime_error& e) {\r\n\t\tcerr << e.what() << endl;\r\n\t\tclean_up_mess();\r\n\t}\r\n}\r\n\r\nint main()\r\n\r\n\ttry {\r\n\t\tcalculate();\r\n\t\treturn 0;\r\n\t}\r\n\tcatch (exception& e) {\r\n\t\tcerr << \"exception: \" << e.what() << endl;\r\n\t\tchar c;\r\n\t\twhile (cin >>c&& c!=';') ;\r\n\t\treturn 1;\r\n\t}\r\n\tcatch (...) {\r\n\t\tcerr << \"exception\\n\";\r\n\t\tchar c;\r\n\t\twhile (cin>>c && c!=';');\r\n\t\treturn 2;\r\n\t}\r\n<|endoftext|>"} {"text":"<commit_before>void LDAPExample()\n{\n gSystem->Load(\"libRLDAP.so\");\n\n TLDAPServer *server = new TLDAPServer(\"ldap.cern.ch\");\n\n TLDAPResult *result = server.Search();\n\n if (result == 0) exit(1 );\n result->Print();\n delete result;\n\n const char *namingcontexts = server.GetNamingContexts();\n result = server.Search(namingcontexts, LDAP_SCOPE_ONELEVEL, 0, 0, 1);\n TLDAPEntry *entry = result.GetNext();\n entry->Print();\n\n TString dn = entry->GetDn();\n\n delete result;\n delete entry;\n\n cout << \"The DN of the entry is \" << dn << endl;\n\n result = server.Search(dn, LDAP_SCOPE_SUBTREE, 0, 0, 0);\n\n result->Print();\n Int_t counter = result.GetCount();\n cout << \"The result contains \" << counter << \" entries !!!\" << endl;\n\n entry = result.GetNext();\n\n TLDAPAttribute *attribute = entry.GetAttribute(\"member\");\n\n Int_t counter2 = attribute.GetCount();\n cout << \"The attribute \" << attribute.GetName() << \" contains \"\n << counter2 << \" values !!!\" << endl;\n const char *value = attribute.GetValue();\n cout << \"The first value of the attribute is \" << endl;\n cout << value << endl;\n\n delete result;\n delete entry;\n}\n<commit_msg>added some error handling code.<commit_after>void LDAPExample()\n{\n gSystem->Load(\"libRLDAP.so\");\n\n TLDAPServer *server = new TLDAPServer(\"ldap.cern.ch\");\n\n TLDAPResult *result = server.Search();\n\n if (result == 0) {\n printf(\"Search failed\\n\");\n exit(1);\n }\n result->Print();\n delete result;\n\n const char *namingcontexts = server.GetNamingContexts();\n result = server.Search(namingcontexts, LDAP_SCOPE_ONELEVEL, 0, 0, 1);\n TLDAPEntry *entry = result.GetNext();\n entry->Print();\n\n TString dn = entry->GetDn();\n\n delete result;\n delete entry;\n\n cout << \"The DN of the entry is \" << dn << endl;\n\n result = server.Search(dn, LDAP_SCOPE_SUBTREE, 0, 0, 0);\n\n if (result == 0) {\n printf(\"Search failed\\n\");\n exit(1);\n }\n\n result->Print();\n Int_t counter = result.GetCount();\n cout << \"The result contains \" << counter << \" entries !!!\" << endl;\n\n entry = result.GetNext();\n\n TLDAPAttribute *attribute = entry.GetAttribute(\"member\");\n\n Int_t counter2 = attribute.GetCount();\n cout << \"The attribute \" << attribute.GetName() << \" contains \"\n << counter2 << \" values !!!\" << endl;\n const char *value = attribute.GetValue();\n cout << \"The first value of the attribute is \" << endl;\n cout << value << endl;\n\n delete result;\n delete entry;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief Reset_Handler() for ARMv6-M and ARMv7-M\n *\n * \\author Copyright (C) 2014-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\nextern \"C\"\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/ weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()\n__attribute__ ((weak)) void lowLevelInitialization0()\n{\n\n}\n\n\/**\n * \\brief Reset_Handler() for ARMv6-M and ARMv7-M\n *\/\n\n__attribute__ ((naked)) void Reset_Handler()\n{\n\tasm volatile\n\t(\n\t\t\t\"\tldr\t\tr0, =%[lowLevelInitialization0]\t\t\\n\"\t\t\/\/ call lowLevelInitialization0() (PSP not set,\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ CONTROL not modified, memory not initialized)\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr0, =__process_stack_end\t\t\t\\n\"\t\t\/\/ initialize PSP\n\t\t\t\"\tmsr\t\tpsp, r0\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tmovs\tr0, %[controlSpselMsk]\t\t\t\t\\n\"\t\t\/\/ thread mode uses PSP and is privileged\n\t\t\t\"\tmsr\t\tcontrol, r0\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tisb\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr4, =__data_array_start\t\t\t\t\\n\"\t\t\/\/ initialize data_array (including .data)\n\t\t\t\"\tldr\t\tr5, =__data_array_end\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#ifdef __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr4, r5\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from data_array\n\t\t\t\"\tbhs\t\t4f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmia\tr4!, {r1-r3}\t\t\t\t\t\t\\n\"\t\t\/\/ r1 - start of source, r2 - start of destination,\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ r3 - end of destination\n\t\t\t\"\tb\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tldmia\tr1!, {r0}\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\tstmia\tr2!, {r0}\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\tcmp\t\tr2, r3\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tbne\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"4:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#else\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr4, r5\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from data_array\n\t\t\t\"\tite\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmialo\tr4!, {r1-r3}\t\t\t\t\t\t\\n\"\t\t\/\/ r1 - start of source, r2 - start of destination,\n\t\t\t\"\tbhs\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ r3 - end of destination\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tcmp\t\tr2, r3\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\tittt\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldrlo\tr0, [r1], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tstrlo\tr0, [r2], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tblo\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#endif\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"\tldr\t\tr3, =__bss_array_start\t\t\t\t\\n\"\t\t\/\/ initialize bss_array (including .bss)\n\t\t\t\"\tldr\t\tr4, =__bss_array_end\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#ifdef __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr3, r4\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from bss_array\n\t\t\t\"\tbhs\t\t4f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmia\tr3!, {r0-r2}\t\t\t\t\t\t\\n\"\t\t\/\/ r0 - value, r1 - start of destination, r2 - end\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ of destination\n\t\t\t\"\tb\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tstmia\tr1!, {r0}\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"3:\tcmp\t\tr1, r2\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tbne\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"4:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#else\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr3, r4\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from bss_array\n\t\t\t\"\tite\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmialo\tr3!, {r0-r2}\t\t\t\t\t\t\\n\"\t\t\/\/ r0 - value, r1 - start of destination, r2 - end\n\t\t\t\"\tbhs\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ of destination\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tcmp\t\tr1, r2\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\titt\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tstrlo\tr0, [r1], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tblo\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#endif\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"\tldr\t\tr0, =__libc_init_array\t\t\t\t\\n\"\t\t\/\/ call constructors for global and static objects\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr0, =main\t\t\t\t\t\t\t\\n\"\t\t\/\/ call main()\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr0, =__libc_fini_array\t\t\t\t\\n\"\t\t\/\/ call destructors for global and static objects\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t.\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ on return - loop till the end of the world\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\".ltorg\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ force dumping of literal pool\n\n\t\t\t::\t[controlSpselMsk] \"i\" (CONTROL_SPSEL_Msk),\n\t\t\t\t[lowLevelInitialization0] \"i\" (lowLevelInitialization0)\n\t);\n\n\t__builtin_unreachable();\n}\n\n}\t\/\/ extern \"C\"\n<commit_msg>Don't call __libc_fini_array in Reset_Handler() if destructors are off<commit_after>\/**\n * \\file\n * \\brief Reset_Handler() for ARMv6-M and ARMv7-M\n *\n * \\author Copyright (C) 2014-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\nextern \"C\"\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/ weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()\n__attribute__ ((weak)) void lowLevelInitialization0()\n{\n\n}\n\n\/**\n * \\brief Reset_Handler() for ARMv6-M and ARMv7-M\n *\/\n\n__attribute__ ((naked)) void Reset_Handler()\n{\n\tasm volatile\n\t(\n\t\t\t\"\tldr\t\tr0, =%[lowLevelInitialization0]\t\t\\n\"\t\t\/\/ call lowLevelInitialization0() (PSP not set,\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ CONTROL not modified, memory not initialized)\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr0, =__process_stack_end\t\t\t\\n\"\t\t\/\/ initialize PSP\n\t\t\t\"\tmsr\t\tpsp, r0\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tmovs\tr0, %[controlSpselMsk]\t\t\t\t\\n\"\t\t\/\/ thread mode uses PSP and is privileged\n\t\t\t\"\tmsr\t\tcontrol, r0\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tisb\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr4, =__data_array_start\t\t\t\t\\n\"\t\t\/\/ initialize data_array (including .data)\n\t\t\t\"\tldr\t\tr5, =__data_array_end\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#ifdef __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr4, r5\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from data_array\n\t\t\t\"\tbhs\t\t4f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmia\tr4!, {r1-r3}\t\t\t\t\t\t\\n\"\t\t\/\/ r1 - start of source, r2 - start of destination,\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ r3 - end of destination\n\t\t\t\"\tb\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tldmia\tr1!, {r0}\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\tstmia\tr2!, {r0}\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\tcmp\t\tr2, r3\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tbne\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"4:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#else\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr4, r5\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from data_array\n\t\t\t\"\tite\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmialo\tr4!, {r1-r3}\t\t\t\t\t\t\\n\"\t\t\/\/ r1 - start of source, r2 - start of destination,\n\t\t\t\"\tbhs\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ r3 - end of destination\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tcmp\t\tr2, r3\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\tittt\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldrlo\tr0, [r1], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tstrlo\tr0, [r2], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tblo\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#endif\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"\tldr\t\tr3, =__bss_array_start\t\t\t\t\\n\"\t\t\/\/ initialize bss_array (including .bss)\n\t\t\t\"\tldr\t\tr4, =__bss_array_end\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#ifdef __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr3, r4\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from bss_array\n\t\t\t\"\tbhs\t\t4f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmia\tr3!, {r0-r2}\t\t\t\t\t\t\\n\"\t\t\/\/ r0 - value, r1 - start of destination, r2 - end\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ of destination\n\t\t\t\"\tb\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tstmia\tr1!, {r0}\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"3:\tcmp\t\tr1, r2\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tbne\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"4:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#else\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"1:\tcmp\t\tr3, r4\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ outer loop - addresses from bss_array\n\t\t\t\"\tite\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldmialo\tr3!, {r0-r2}\t\t\t\t\t\t\\n\"\t\t\/\/ r0 - value, r1 - start of destination, r2 - end\n\t\t\t\"\tbhs\t\t3f\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ of destination\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"2:\tcmp\t\tr1, r2\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ inner loop - section initialization\n\t\t\t\"\titt\t\tlo\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tstrlo\tr0, [r1], #4\t\t\t\t\t\t\\n\"\n\t\t\t\"\tblo\t\t2b\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t1b\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ go back to start\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"3:\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#endif\t\/\/ !def __ARM_ARCH_6M__\n\t\t\t\"\tldr\t\tr0, =__libc_init_array\t\t\t\t\\n\"\t\t\/\/ call constructors for global and static objects\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tldr\t\tr0, =main\t\t\t\t\t\t\t\\n\"\t\t\/\/ call main()\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n#if CONFIG_STATIC_DESTRUCTORS_ENABLE == 1\n\t\t\t\"\tldr\t\tr0, =__libc_fini_array\t\t\t\t\\n\"\t\t\/\/ call destructors for global and static objects\n\t\t\t\"\tblx\t\tr0\t\t\t\t\t\t\t\t\t\\n\"\n#endif\t\/\/ CONFIG_STATIC_DESTRUCTORS_ENABLE == 1\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\"\tb\t\t.\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ on return - loop till the end of the world\n\t\t\t\"\t\t\t\t\t\t\t\t\t\t\t\t\\n\"\n\t\t\t\".ltorg\t\t\t\t\t\t\t\t\t\t\t\\n\"\t\t\/\/ force dumping of literal pool\n\n\t\t\t::\t[controlSpselMsk] \"i\" (CONTROL_SPSEL_Msk),\n\t\t\t\t[lowLevelInitialization0] \"i\" (lowLevelInitialization0)\n\t);\n\n\t__builtin_unreachable();\n}\n\n}\t\/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabpage.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:31:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <tools\/ref.hxx>\n\n#ifndef _SV_RC_H\n#include <tools\/rc.h>\n#endif\n#ifndef _SV_SVDATA_HXX\n#include <svdata.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <svapp.hxx>\n#endif\n#ifndef _SV_EVENT_HXX\n#include <event.hxx>\n#endif\n#ifndef _SV_TABPAGE_HXX\n#include <tabpage.hxx>\n#endif\n#ifndef _SV_TABCTRL_HXX\n#include <tabctrl.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n\n\n\n\n\/\/ =======================================================================\n\nvoid TabPage::ImplInit( Window* pParent, WinBits nStyle )\n{\n if ( !(nStyle & WB_NODIALOGCONTROL) )\n nStyle |= WB_DIALOGCONTROL;\n\n Window::ImplInit( pParent, nStyle, NULL );\n\n ImplInitSettings();\n\n \/\/ if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background\n \/\/ otherwise they will paint with a wrong background\n if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )\n EnableChildTransparentMode( TRUE );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::ImplInitSettings()\n{\n Window* pParent = GetParent();\n if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )\n {\n EnableChildTransparentMode( TRUE );\n SetParentClipMode( PARENTCLIPMODE_NOCLIP );\n SetPaintTransparent( TRUE );\n SetBackground();\n }\n else\n {\n EnableChildTransparentMode( FALSE );\n SetParentClipMode( 0 );\n SetPaintTransparent( FALSE );\n\n if ( IsControlBackground() )\n SetBackground( GetControlBackground() );\n else\n SetBackground( pParent->GetBackground() );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTabPage::TabPage( Window* pParent, WinBits nStyle ) :\n Window( WINDOW_TABPAGE )\n{\n ImplInit( pParent, nStyle );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTabPage::TabPage( Window* pParent, const ResId& rResId ) :\n Window( WINDOW_TABPAGE )\n{\n rResId.SetRT( RSC_TABPAGE );\n WinBits nStyle = ImplInitRes( rResId );\n ImplInit( pParent, nStyle );\n ImplLoadRes( rResId );\n\n if ( !(nStyle & WB_HIDE) )\n Show();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::StateChanged( StateChangedType nType )\n{\n Window::StateChanged( nType );\n\n if ( nType == STATE_CHANGE_INITSHOW )\n {\n if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )\n ImplWindowAutoMnemonic( this );\n }\n else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )\n {\n ImplInitSettings();\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Window::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&\n (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n ImplInitSettings();\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::Paint( const Rectangle& rRect )\n{\n \/\/ draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)\n if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )\n {\n const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 );\n\n ControlState nState = CTRL_STATE_ENABLED;\n int part = PART_ENTIRE_CONTROL;\n if ( !IsEnabled() )\n nState &= ~CTRL_STATE_ENABLED;\n if ( HasFocus() )\n nState |= CTRL_STATE_FOCUSED;\n Point aPoint;\n \/\/ pass the whole window region to NWF as the tab body might be a gradient or bitmap\n \/\/ that has to be scaled properly, clipping makes sure that we do not paint too much\n Region aCtrlRegion( Rectangle( aPoint, GetOutputSizePixel() ) );\n DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,\n aControlValue, rtl::OUString() );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::ActivatePage()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::DeactivatePage()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\n::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()\n{\n \/\/ TODO: remove this method (incompatible)\n\n return Window::CreateAccessible();\n}\n<commit_msg>INTEGRATION: CWS warnings01 (1.11.70); FILE MERGED 2005\/11\/10 20:06:35 pl 1.11.70.1: #i55991# removed warnings<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabpage.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 19:41:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <tools\/ref.hxx>\n\n#ifndef _SV_RC_H\n#include <tools\/rc.h>\n#endif\n#ifndef _SV_SVDATA_HXX\n#include <svdata.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <svapp.hxx>\n#endif\n#ifndef _SV_EVENT_HXX\n#include <event.hxx>\n#endif\n#ifndef _SV_TABPAGE_HXX\n#include <tabpage.hxx>\n#endif\n#ifndef _SV_TABCTRL_HXX\n#include <tabctrl.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessible.hpp>\n#endif\n\n\n\n\n\/\/ =======================================================================\n\nvoid TabPage::ImplInit( Window* pParent, WinBits nStyle )\n{\n if ( !(nStyle & WB_NODIALOGCONTROL) )\n nStyle |= WB_DIALOGCONTROL;\n\n Window::ImplInit( pParent, nStyle, NULL );\n\n ImplInitSettings();\n\n \/\/ if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background\n \/\/ otherwise they will paint with a wrong background\n if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )\n EnableChildTransparentMode( TRUE );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::ImplInitSettings()\n{\n Window* pParent = GetParent();\n if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )\n {\n EnableChildTransparentMode( TRUE );\n SetParentClipMode( PARENTCLIPMODE_NOCLIP );\n SetPaintTransparent( TRUE );\n SetBackground();\n }\n else\n {\n EnableChildTransparentMode( FALSE );\n SetParentClipMode( 0 );\n SetPaintTransparent( FALSE );\n\n if ( IsControlBackground() )\n SetBackground( GetControlBackground() );\n else\n SetBackground( pParent->GetBackground() );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTabPage::TabPage( Window* pParent, WinBits nStyle ) :\n Window( WINDOW_TABPAGE )\n{\n ImplInit( pParent, nStyle );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTabPage::TabPage( Window* pParent, const ResId& rResId ) :\n Window( WINDOW_TABPAGE )\n{\n rResId.SetRT( RSC_TABPAGE );\n WinBits nStyle = ImplInitRes( rResId );\n ImplInit( pParent, nStyle );\n ImplLoadRes( rResId );\n\n if ( !(nStyle & WB_HIDE) )\n Show();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::StateChanged( StateChangedType nType )\n{\n Window::StateChanged( nType );\n\n if ( nType == STATE_CHANGE_INITSHOW )\n {\n if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )\n ImplWindowAutoMnemonic( this );\n }\n else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )\n {\n ImplInitSettings();\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Window::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&\n (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n ImplInitSettings();\n Invalidate();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::Paint( const Rectangle& )\n{\n \/\/ draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)\n if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )\n {\n const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 );\n\n ControlState nState = CTRL_STATE_ENABLED;\n int part = PART_ENTIRE_CONTROL;\n if ( !IsEnabled() )\n nState &= ~CTRL_STATE_ENABLED;\n if ( HasFocus() )\n nState |= CTRL_STATE_FOCUSED;\n Point aPoint;\n \/\/ pass the whole window region to NWF as the tab body might be a gradient or bitmap\n \/\/ that has to be scaled properly, clipping makes sure that we do not paint too much\n Region aCtrlRegion( Rectangle( aPoint, GetOutputSizePixel() ) );\n DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,\n aControlValue, rtl::OUString() );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::ActivatePage()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TabPage::DeactivatePage()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\n::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > TabPage::CreateAccessible()\n{\n \/\/ TODO: remove this method (incompatible)\n\n return Window::CreateAccessible();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"balancer.hpp\"\n\n#define LB_VERBOSE 0\n#if LB_VERBOSE\n#define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__)\n#else\n#define LBOUT(fmt, ...) \/** **\/\n#endif\n\nusing namespace std::chrono;\n\nBalancer::Balancer(\n netstack_t& incoming, uint16_t in_port,\n netstack_t& outgoing, std::vector<net::Socket> nodelist)\n : netin(incoming), nodes()\n{\n for (auto& addr : nodelist) {\n nodes.add_node(outgoing, addr, pool_signal_t{this, &Balancer::handle_queue});\n }\n\n netin.tcp().listen(in_port,\n [this] (auto conn) {\n if (conn != nullptr) this->incoming(conn);\n });\n}\n\nint Balancer::wait_queue() const {\n return queue.size();\n}\nvoid Balancer::incoming(tcp_ptr conn)\n{\n queue.emplace_back(conn);\n LBOUT(\"Queueing connection (q=%lu)\\n\", queue.size());\n \/\/ see if LB needs more connections out\n this->handle_connections();\n}\nvoid Balancer::handle_queue()\n{\n \/\/ check waitq\n while (nodes.pool_size() > 0 && queue.empty() == false)\n {\n auto& client = queue.front();\n if (client.conn->is_connected()) {\n \/\/ NOTE: explicitly want to copy buffers\n if (nodes.assign(client.conn, client.readq)) {\n queue.pop_front();\n }\n }\n } \/\/ waitq check\n \/\/ check if we need to create more connections\n this->handle_connections();\n}\nvoid Balancer::handle_connections()\n{\n int np_connecting = nodes.pool_connecting();\n int estimate = queue.size() - (np_connecting + nodes.pool_size());\n estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS);\n estimate = std::max(0, estimate - np_connecting);\n if (estimate > 0)\n {\n try {\n \/\/ create more outgoing connections\n nodes.create_connections(estimate);\n }\n catch (std::exception& e)\n {\n if (this->rethrow_timer != Timers::UNUSED_ID)\n Timers::stop(this->rethrow_timer);\n \/\/ assuming the failure is due to not enough eph. ports\n this->rethrow_timer = Timers::oneshot(CONNECT_THROW_PERIOD,\n [this] (int) {\n this->rethrow_timer = Timers::UNUSED_ID;\n this->handle_connections();\n });\n }\n } \/\/ estimate\n} \/\/ handle_connections()\n\nWaiting::Waiting(tcp_ptr incoming)\n : conn(incoming), total(0)\n{\n \/\/ queue incoming data from clients not yet\n \/\/ assigned to a node\n conn->on_read(READQ_PER_CLIENT,\n [this] (auto buf, size_t len) {\n \/\/ prevent buffer bloat attack\n total += len;\n if (total > MAX_READQ_PER_NODE) {\n conn->abort();\n }\n else {\n LBOUT(\"*** Queued %lu bytes\\n\", len);\n readq.emplace_back(buf, len);\n }\n });\n}\n\ntemplate <typename... Args>\ninline void Nodes::add_node(Args&&... args) {\n nodes.emplace_back(std::forward<Args> (args)...);\n}\nvoid Nodes::create_connections(int total)\n{\n \/\/ temporary iterator\n for (int i = 0; i < total; i++)\n {\n \/\/ look for next active node up to *size* times\n for (size_t i = 0; i < nodes.size(); i++)\n {\n conn_iterator = (conn_iterator + 1) % nodes.size();\n if (nodes[conn_iterator].is_active()) break;\n }\n \/\/ only connect if node is determined active, to prevent\n \/\/ building up connect attempts on just one node\n if (nodes[conn_iterator].is_active()) {\n nodes[conn_iterator].connect();\n }\n }\n}\nbool Nodes::assign(tcp_ptr conn, queue_vector_t& readq)\n{\n for (size_t i = 0; i < nodes.size(); i++)\n {\n auto outgoing = nodes[algo_iterator].get_connection();\n \/\/ algorithm here \/\/\n algo_iterator = (algo_iterator + 1) % nodes.size();\n \/\/ check if connection was retrieved\n if (outgoing != nullptr)\n {\n assert(outgoing->is_connected());\n LBOUT(\"Assigning client to node %d (%s)\\n\",\n iterator, outgoing->to_string().c_str());\n this->create_session(conn, outgoing);\n \/\/ flush readq\n for (auto& buffer : readq) {\n LBOUT(\"*** Flushing %lu bytes\\n\", buffer.second);\n outgoing->write(std::move(buffer.first), buffer.second);\n }\n return true;\n }\n }\n return false;\n}\nsize_t Nodes::size() const noexcept {\n return nodes.size();\n}\nNodes::const_iterator Nodes::begin() const {\n return nodes.cbegin();\n}\nNodes::const_iterator Nodes::end() const {\n return nodes.cend();\n}\nint Nodes::pool_connecting() const {\n int count = 0;\n for (auto& node : nodes) count += node.connection_attempts();\n return count;\n}\nint Nodes::pool_size() const {\n int count = 0;\n for (auto& node : nodes) count += node.pool_size();\n return count;\n}\nint32_t Nodes::open_sessions() const {\n return session_cnt;\n}\nint64_t Nodes::total_sessions() const {\n return session_total;\n}\nvoid Nodes::create_session(tcp_ptr client, tcp_ptr outgoing)\n{\n int idx = -1;\n if (free_sessions.empty()) {\n idx = sessions.size();\n sessions.emplace_back(*this, idx, client, outgoing);\n } else {\n idx = free_sessions.back();\n new (&sessions[idx]) Session(*this, idx, client, outgoing);\n free_sessions.pop_back();\n }\n session_total++;\n session_cnt++;\n LBOUT(\"New session %d (current = %d, total = %ld)\\n\",\n idx, session_cnt, session_total);\n}\nSession& Nodes::get_session(int idx)\n{\n return sessions.at(idx);\n}\nvoid Nodes::close_session(int idx)\n{\n auto& session = get_session(idx);\n \/\/ disable timeout timer\n Timers::stop(session.timeout_timer);\n session.timeout_timer = Timers::UNUSED_ID;\n \/\/ close connections\n if (session.incoming != nullptr) {\n auto conn = std::move(session.incoming);\n conn->reset_callbacks();\n if (conn->is_connected()) conn->close();\n }\n if (session.outgoing != nullptr) {\n auto conn = std::move(session.outgoing);\n conn->reset_callbacks();\n if (conn->is_connected()) conn->close();\n }\n \/\/ free session\n free_sessions.push_back(session.self);\n session_cnt--;\n LBOUT(\"Session %d closed (total = %d)\\n\", session.self, session_cnt);\n}\n\nNode::Node(netstack_t& stk, net::Socket a, pool_signal_t sig)\n : stack(stk), addr(a), pool_signal(sig)\n{\n \/\/ periodically connect to node and determine if active\n \/\/ however, perform first check immediately\n this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD,\n [this] (int) {\n this->perform_active_check();\n });\n}\nvoid Node::restart_active_check()\n{\n if (this->active_timer == Timers::UNUSED_ID)\n {\n this->active_timer = Timers::periodic(\n ACTIVE_RETRY_PERIOD, ACTIVE_CHECK_PERIOD,\n [this] (int) {\n this->perform_active_check();\n });\n }\n}\nvoid Node::perform_active_check()\n{\n try {\n this->stack.tcp().connect(this->addr,\n [this] (auto conn) {\n this->active = (conn != nullptr);\n \/\/ if we are connected, its alive\n if (conn != nullptr)\n {\n \/\/ hopefully put this to good use\n pool.push_back(conn);\n \/\/ stop any active check\n this->stop_active_check();\n \/\/ signal change in pool\n this->pool_signal();\n }\n });\n } catch (std::exception& e) {\n \/\/ do nothing, because might just be eph.ports used up\n }\n}\nvoid Node::stop_active_check()\n{\n if (this->active_timer != Timers::UNUSED_ID) {\n Timers::stop(this->active_timer);\n this->active_timer = Timers::UNUSED_ID;\n }\n}\nvoid Node::connect()\n{\n auto outgoing = this->stack.tcp().connect(this->addr);\n \/\/ connecting to node atm.\n this->connecting++;\n \/\/ retry timer when connect takes too long\n int fail_timer = Timers::oneshot(CONNECT_WAIT_PERIOD,\n [this, outgoing] (int)\n {\n \/\/ close connection\n outgoing->abort();\n \/\/ no longer connecting\n assert(this->connecting > 0);\n this->connecting --;\n \/\/ set as inactive\n this->active = false;\n \/\/ restart active check\n this->restart_active_check();\n \/\/ signal change in pool\n this->pool_signal();\n });\n \/\/ add connection to pool on success, otherwise.. retry\n outgoing->on_connect(\n [this, fail_timer] (auto conn)\n {\n \/\/ stop retry timer\n Timers::stop(fail_timer);\n \/\/ no longer connecting\n assert(this->connecting > 0);\n this->connecting --;\n \/\/ connection may be null, apparently\n if (conn != nullptr && conn->is_connected())\n {\n LBOUT(\"Connected to %s (%ld total)\\n\",\n addr.to_string().c_str(), pool.size());\n this->pool.push_back(conn);\n \/\/ stop any active check\n this->stop_active_check();\n }\n else {\n this->perform_active_check();\n }\n \/\/ signal change in pool\n this->pool_signal();\n });\n}\ntcp_ptr Node::get_connection()\n{\n while (pool.empty() == false) {\n auto conn = pool.back();\n assert(conn != nullptr);\n pool.pop_back();\n if (conn->is_connected()) return conn;\n else conn->close();\n }\n return nullptr;\n}\n\n\/\/ use indexing to access Session because std::vector\nSession::Session(Nodes& n, int idx, tcp_ptr inc, tcp_ptr out)\n : parent(n), self(idx), incoming(inc), outgoing(out)\n{\n this->timeout_timer = Timers::oneshot(INITIAL_SESSION_TIMEOUT,\n [&nodes = n, idx] (int) {\n nodes.close_session(idx);\n });\n incoming->on_read(READQ_PER_CLIENT,\n [&nodes = n, idx] (auto buf, size_t len) mutable {\n auto& session = nodes.get_session(idx);\n session.handle_timeout();\n session.outgoing->write(std::move(buf), len);\n });\n incoming->on_close(\n [&nodes = n, idx] () mutable {\n nodes.close_session(idx);\n });\n outgoing->on_read(READQ_FOR_NODES,\n [&nodes = n, idx] (auto buf, size_t len) mutable {\n auto& session = nodes.get_session(idx);\n session.handle_timeout();\n session.incoming->write(std::move(buf), len);\n });\n outgoing->on_close(\n [&nodes = n, idx] () mutable {\n nodes.close_session(idx);\n });\n}\nvoid Session::handle_timeout()\n{\n \/\/ stop old timer\n Timers::stop(this->timeout_timer);\n \/\/ create new timeout\n this->timeout_timer = Timers::oneshot(ROLLING_SESSION_TIMEOUT,\n [&nodes = parent, idx = self] (int) {\n nodes.close_session(idx);\n });\n}\n<commit_msg>Fix issue with nodes slowly perma offline over time<commit_after>#include \"balancer.hpp\"\n\n#define LB_VERBOSE 0\n#if LB_VERBOSE\n#define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__)\n#else\n#define LBOUT(fmt, ...) \/** **\/\n#endif\n\nusing namespace std::chrono;\n\nBalancer::Balancer(\n netstack_t& incoming, uint16_t in_port,\n netstack_t& outgoing, std::vector<net::Socket> nodelist)\n : netin(incoming), nodes()\n{\n for (auto& addr : nodelist) {\n nodes.add_node(outgoing, addr, pool_signal_t{this, &Balancer::handle_queue});\n }\n\n netin.tcp().listen(in_port,\n [this] (auto conn) {\n if (conn != nullptr) this->incoming(conn);\n });\n}\n\nint Balancer::wait_queue() const {\n return queue.size();\n}\nvoid Balancer::incoming(tcp_ptr conn)\n{\n queue.emplace_back(conn);\n LBOUT(\"Queueing connection (q=%lu)\\n\", queue.size());\n \/\/ see if LB needs more connections out\n this->handle_connections();\n}\nvoid Balancer::handle_queue()\n{\n \/\/ check waitq\n while (nodes.pool_size() > 0 && queue.empty() == false)\n {\n auto& client = queue.front();\n if (client.conn->is_connected()) {\n \/\/ NOTE: explicitly want to copy buffers\n if (nodes.assign(client.conn, client.readq)) {\n queue.pop_front();\n }\n }\n } \/\/ waitq check\n \/\/ check if we need to create more connections\n this->handle_connections();\n}\nvoid Balancer::handle_connections()\n{\n int np_connecting = nodes.pool_connecting();\n int estimate = queue.size() - (np_connecting + nodes.pool_size());\n estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS);\n estimate = std::max(0, estimate - np_connecting);\n if (estimate > 0)\n {\n try {\n \/\/ create more outgoing connections\n nodes.create_connections(estimate);\n }\n catch (std::exception& e)\n {\n if (this->rethrow_timer != Timers::UNUSED_ID)\n Timers::stop(this->rethrow_timer);\n \/\/ assuming the failure is due to not enough eph. ports\n this->rethrow_timer = Timers::oneshot(CONNECT_THROW_PERIOD,\n [this] (int) {\n this->rethrow_timer = Timers::UNUSED_ID;\n this->handle_connections();\n });\n }\n } \/\/ estimate\n} \/\/ handle_connections()\n\nWaiting::Waiting(tcp_ptr incoming)\n : conn(incoming), total(0)\n{\n \/\/ queue incoming data from clients not yet\n \/\/ assigned to a node\n conn->on_read(READQ_PER_CLIENT,\n [this] (auto buf, size_t len) {\n \/\/ prevent buffer bloat attack\n total += len;\n if (total > MAX_READQ_PER_NODE) {\n conn->abort();\n }\n else {\n LBOUT(\"*** Queued %lu bytes\\n\", len);\n readq.emplace_back(buf, len);\n }\n });\n}\n\ntemplate <typename... Args>\ninline void Nodes::add_node(Args&&... args) {\n nodes.emplace_back(std::forward<Args> (args)...);\n}\nvoid Nodes::create_connections(int total)\n{\n \/\/ temporary iterator\n for (int i = 0; i < total; i++)\n {\n \/\/ look for next active node up to *size* times\n for (size_t i = 0; i < nodes.size(); i++)\n {\n conn_iterator = (conn_iterator + 1) % nodes.size();\n if (nodes[conn_iterator].is_active()) break;\n }\n \/\/ only connect if node is determined active, to prevent\n \/\/ building up connect attempts on just one node\n if (nodes[conn_iterator].is_active()) {\n nodes[conn_iterator].connect();\n }\n }\n}\nbool Nodes::assign(tcp_ptr conn, queue_vector_t& readq)\n{\n for (size_t i = 0; i < nodes.size(); i++)\n {\n auto outgoing = nodes[algo_iterator].get_connection();\n \/\/ algorithm here \/\/\n algo_iterator = (algo_iterator + 1) % nodes.size();\n \/\/ check if connection was retrieved\n if (outgoing != nullptr)\n {\n assert(outgoing->is_connected());\n LBOUT(\"Assigning client to node %d (%s)\\n\",\n iterator, outgoing->to_string().c_str());\n this->create_session(conn, outgoing);\n \/\/ flush readq\n for (auto& buffer : readq) {\n LBOUT(\"*** Flushing %lu bytes\\n\", buffer.second);\n outgoing->write(std::move(buffer.first), buffer.second);\n }\n return true;\n }\n }\n return false;\n}\nsize_t Nodes::size() const noexcept {\n return nodes.size();\n}\nNodes::const_iterator Nodes::begin() const {\n return nodes.cbegin();\n}\nNodes::const_iterator Nodes::end() const {\n return nodes.cend();\n}\nint Nodes::pool_connecting() const {\n int count = 0;\n for (auto& node : nodes) count += node.connection_attempts();\n return count;\n}\nint Nodes::pool_size() const {\n int count = 0;\n for (auto& node : nodes) count += node.pool_size();\n return count;\n}\nint32_t Nodes::open_sessions() const {\n return session_cnt;\n}\nint64_t Nodes::total_sessions() const {\n return session_total;\n}\nvoid Nodes::create_session(tcp_ptr client, tcp_ptr outgoing)\n{\n int idx = -1;\n if (free_sessions.empty()) {\n idx = sessions.size();\n sessions.emplace_back(*this, idx, client, outgoing);\n } else {\n idx = free_sessions.back();\n new (&sessions[idx]) Session(*this, idx, client, outgoing);\n free_sessions.pop_back();\n }\n session_total++;\n session_cnt++;\n LBOUT(\"New session %d (current = %d, total = %ld)\\n\",\n idx, session_cnt, session_total);\n}\nSession& Nodes::get_session(int idx)\n{\n return sessions.at(idx);\n}\nvoid Nodes::close_session(int idx)\n{\n auto& session = get_session(idx);\n \/\/ disable timeout timer\n Timers::stop(session.timeout_timer);\n session.timeout_timer = Timers::UNUSED_ID;\n \/\/ close connections\n if (session.incoming != nullptr) {\n auto conn = std::move(session.incoming);\n conn->reset_callbacks();\n if (conn->is_connected()) conn->close();\n }\n if (session.outgoing != nullptr) {\n auto conn = std::move(session.outgoing);\n conn->reset_callbacks();\n if (conn->is_connected()) conn->close();\n }\n \/\/ free session\n free_sessions.push_back(session.self);\n session_cnt--;\n LBOUT(\"Session %d closed (total = %d)\\n\", session.self, session_cnt);\n}\n\nNode::Node(netstack_t& stk, net::Socket a, pool_signal_t sig)\n : stack(stk), addr(a), pool_signal(sig)\n{\n \/\/ periodically connect to node and determine if active\n \/\/ however, perform first check immediately\n this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD,\n [this] (int) {\n this->perform_active_check();\n });\n}\nvoid Node::restart_active_check()\n{\n if (this->active_timer == Timers::UNUSED_ID)\n {\n this->active_timer = Timers::periodic(\n ACTIVE_RETRY_PERIOD, ACTIVE_CHECK_PERIOD,\n [this] (int) {\n this->perform_active_check();\n });\n }\n}\nvoid Node::perform_active_check()\n{\n try {\n this->stack.tcp().connect(this->addr,\n [this] (auto conn) {\n this->active = (conn != nullptr);\n \/\/ if we are connected, its alive\n if (conn != nullptr)\n {\n \/\/ hopefully put this to good use\n pool.push_back(conn);\n \/\/ stop any active check\n this->stop_active_check();\n \/\/ signal change in pool\n this->pool_signal();\n }\n else {\n \/\/ if no periodic check is being done right now,\n \/\/ start doing it (after initial delay)\n this->restart_active_check();\n }\n });\n } catch (std::exception& e) {\n \/\/ do nothing, because might just be eph.ports used up\n }\n}\nvoid Node::stop_active_check()\n{\n if (this->active_timer != Timers::UNUSED_ID) {\n Timers::stop(this->active_timer);\n this->active_timer = Timers::UNUSED_ID;\n }\n}\nvoid Node::connect()\n{\n auto outgoing = this->stack.tcp().connect(this->addr);\n \/\/ connecting to node atm.\n this->connecting++;\n \/\/ retry timer when connect takes too long\n int fail_timer = Timers::oneshot(CONNECT_WAIT_PERIOD,\n [this, outgoing] (int)\n {\n \/\/ close connection\n outgoing->abort();\n \/\/ no longer connecting\n assert(this->connecting > 0);\n this->connecting --;\n \/\/ set as inactive\n this->active = false;\n \/\/ restart active check\n this->restart_active_check();\n \/\/ signal change in pool\n this->pool_signal();\n });\n \/\/ add connection to pool on success, otherwise.. retry\n outgoing->on_connect(\n [this, fail_timer] (auto conn)\n {\n \/\/ stop retry timer\n Timers::stop(fail_timer);\n \/\/ no longer connecting\n assert(this->connecting > 0);\n this->connecting --;\n \/\/ connection may be null, apparently\n if (conn != nullptr && conn->is_connected())\n {\n LBOUT(\"Connected to %s (%ld total)\\n\",\n addr.to_string().c_str(), pool.size());\n this->pool.push_back(conn);\n \/\/ stop any active check\n this->stop_active_check();\n \/\/ signal change in pool\n this->pool_signal();\n }\n else {\n this->restart_active_check();\n }\n });\n}\ntcp_ptr Node::get_connection()\n{\n while (pool.empty() == false) {\n auto conn = pool.back();\n assert(conn != nullptr);\n pool.pop_back();\n if (conn->is_connected()) return conn;\n else conn->close();\n }\n return nullptr;\n}\n\n\/\/ use indexing to access Session because std::vector\nSession::Session(Nodes& n, int idx, tcp_ptr inc, tcp_ptr out)\n : parent(n), self(idx), incoming(inc), outgoing(out)\n{\n this->timeout_timer = Timers::oneshot(INITIAL_SESSION_TIMEOUT,\n [&nodes = n, idx] (int) {\n nodes.close_session(idx);\n });\n incoming->on_read(READQ_PER_CLIENT,\n [&nodes = n, idx] (auto buf, size_t len) mutable {\n auto& session = nodes.get_session(idx);\n session.handle_timeout();\n session.outgoing->write(std::move(buf), len);\n });\n incoming->on_close(\n [&nodes = n, idx] () mutable {\n nodes.close_session(idx);\n });\n outgoing->on_read(READQ_FOR_NODES,\n [&nodes = n, idx] (auto buf, size_t len) mutable {\n auto& session = nodes.get_session(idx);\n session.handle_timeout();\n session.incoming->write(std::move(buf), len);\n });\n outgoing->on_close(\n [&nodes = n, idx] () mutable {\n nodes.close_session(idx);\n });\n}\nvoid Session::handle_timeout()\n{\n \/\/ stop old timer\n Timers::stop(this->timeout_timer);\n \/\/ create new timeout\n this->timeout_timer = Timers::oneshot(ROLLING_SESSION_TIMEOUT,\n [&nodes = parent, idx = self] (int) {\n nodes.close_session(idx);\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Map.h\"\n\n#include \"..\/..\/..\/..\/texture\/ImageDecompression.h\"\n\n#include \"Arrow.h\"\n\nMap::Map(GLuint program, const GraphicsObjectManager& graphicsObjectManager) : HUDobject_Animated(program, graphicsObjectManager)\n{\n\tEventHandler::addCursorPosHook(this);\n\tEventHandler::addScrollHook(this);\n\n\tGLenum format;\n\tunsigned char* imageData = extractImageFrom7zFile(\"..\/..\/Source\/map.7z\", &m_originalWidth, &m_originalHeight, &format);\n\n\tglGenTextures(1, &m_textureObject);\n\tglBindTexture(GL_TEXTURE_2D, m_textureObject);\n\n\tglTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, m_originalWidth, m_originalHeight);\n\tglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_originalWidth, m_originalHeight, format, GL_UNSIGNED_BYTE, imageData);\n\tfreeImageData(imageData);\n\n\t\/\/glGenerateMipmap(GL_TEXTURE_2D);\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tm_zoomLevel = ZoomLevel();\n\n\tthis->setCoords({ 0.0f, 0.0f }, (GLfloat)m_originalWidth, (GLfloat)m_originalHeight, 0);\n\n\n\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.03f, 0.06f }, { 0.03f, 0.2f }));\n\tfloat mapAspectRatio = 3712.0f \/ 3333;\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.06f, 0.06f * mapAspectRatio }, { 0.15f, 0.15f * mapAspectRatio }));\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.06f, 0.03f }, { 0.27f, 0.03f }));\n}\n\nMap::~Map()\n{\n\tEventHandler::removeCursorPosHook(this);\n\tEventHandler::removeScrollHook(this);\n\n\tfor (auto arrow : m_arrows) delete arrow;\n}\n\nvoid Map::cursorPosCallback(const InputManager& input)\n{\n\tif (input.getMouse().m_isLeftMouseButtonDown)\n\t{\n\t\tCursorPos cursorPos = input.getMouse().getCursorPos();\n\t\tmove({ cursorPos.deltaX, cursorPos.deltaY }, 0);\n\t}\n}\n\nvoid Map::scrollCallback(float xOffset, float yOffset, const InputManager& input)\n{\n\tCursorPos cursorPos = input.getMouse().getCursorPos();\n\n\tZoomLevel oldZoomLevel = m_zoomLevel;\n\tif (oldZoomLevel == m_zoomLevel.offsetLevel((int)yOffset))\n\t\treturn;\n\n\tGLfloat currentWidth = getWidth();\n\tGLfloat newWidth = m_originalWidth * m_zoomLevel.getPercentage();\n\n\tzoom(newWidth \/ currentWidth, 1.0f \/ 4.0f, cursorPos);\n}\n\nvoid Map::graphicsUpdate(GLuint program, const GraphicsObjectManager& graphicsObjectManager)\n{\n\tglBindTexture(GL_TEXTURE_2D, m_textureObject);\n\n\tHUDobject_Animated::graphicsUpdate(program, graphicsObjectManager);\n\tHUDobject_Dynamic::graphicsUpdate(program, graphicsObjectManager);\n\n\tfor (Arrow* arrow : m_arrows)\n\t\tarrow->graphicsUpdate(graphicsObjectManager);\n}\n<commit_msg>Implemented Arrow::updatePosition()<commit_after>#include \"Map.h\"\n\n#include \"..\/..\/..\/..\/texture\/ImageDecompression.h\"\n\n#include \"Arrow.h\"\n\nMap::Map(GLuint program, const GraphicsObjectManager& graphicsObjectManager) : HUDobject_Animated(program, graphicsObjectManager)\n{\n\tEventHandler::addCursorPosHook(this);\n\tEventHandler::addScrollHook(this);\n\n\tGLenum format;\n\tunsigned char* imageData = extractImageFrom7zFile(\"..\/..\/Source\/map.7z\", &m_originalWidth, &m_originalHeight, &format);\n\n\tglGenTextures(1, &m_textureObject);\n\tglBindTexture(GL_TEXTURE_2D, m_textureObject);\n\n\tglTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, m_originalWidth, m_originalHeight);\n\tglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_originalWidth, m_originalHeight, format, GL_UNSIGNED_BYTE, imageData);\n\tfreeImageData(imageData);\n\n\t\/\/glGenerateMipmap(GL_TEXTURE_2D);\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n\tm_zoomLevel = ZoomLevel();\n\n\tthis->setCoords({ 0.0f, 0.0f }, (GLfloat)m_originalWidth, (GLfloat)m_originalHeight, 0);\n\n\n\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.03f, 0.06f }, { 0.03f, 0.2f }));\n\tfloat mapAspectRatio = 3712.0f \/ 3333;\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.06f, 0.06f * mapAspectRatio }, { 0.15f, 0.15f * mapAspectRatio }));\n\tm_arrows.push_back(new Arrow(graphicsObjectManager, *this, { 0.06f, 0.03f }, { 0.27f, 0.03f }));\n}\n\nMap::~Map()\n{\n\tEventHandler::removeCursorPosHook(this);\n\tEventHandler::removeScrollHook(this);\n\n\tfor (auto arrow : m_arrows) delete arrow;\n}\n\nvoid Map::cursorPosCallback(const InputManager& input)\n{\n\tif (input.getMouse().m_isLeftMouseButtonDown)\n\t{\n\t\tCursorPos cursorPos = input.getMouse().getCursorPos();\n\t\tmove({ cursorPos.deltaX, cursorPos.deltaY }, 0);\n\t}\n}\n\nvoid Map::scrollCallback(float xOffset, float yOffset, const InputManager& input)\n{\n\tCursorPos cursorPos = input.getMouse().getCursorPos();\n\n\tZoomLevel oldZoomLevel = m_zoomLevel;\n\tif (oldZoomLevel == m_zoomLevel.offsetLevel((int)yOffset))\n\t\treturn;\n\n\tGLfloat currentWidth = getWidth();\n\tGLfloat newWidth = m_originalWidth * m_zoomLevel.getPercentage();\n\n\tzoom(newWidth \/ currentWidth, 1.0f \/ 4.0f, cursorPos);\n}\n\nvoid Map::graphicsUpdate(GLuint program, const GraphicsObjectManager& graphicsObjectManager)\n{\n\tglBindTexture(GL_TEXTURE_2D, m_textureObject);\n\n\tHUDobject_Animated::graphicsUpdate(program, graphicsObjectManager);\n\n\tif (m_dirtyFlag)\n\t{\n\t\tfor (Arrow* arrow : m_arrows)\n\t\t\tarrow->updatePosition(*this);\n\t}\n\n\tHUDobject_Dynamic::graphicsUpdate(program, graphicsObjectManager);\n\n\tfor (Arrow* arrow : m_arrows)\n\t\tarrow->graphicsUpdate(graphicsObjectManager);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tCopyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin\n\tCopyright (C) 1998, 1999 by Jorrit Tyberghein\n\tWritten by Nathaniel 'NooTe' Saint Martin\n\n\tThis library is free software; you can redistribute it and\/or\n\tmodify it under the terms of the GNU Library General Public\n\tLicense as published by the Free Software Foundation; either\n\tversion 2 of the License, or (at your option) any later version.\n\n\tThis library is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\tLibrary General Public License for more details.\n\n\tYou should have received a copy of the GNU Library General Public\n\tLicense along with this library; if not, write to the Free\n\tSoftware Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"cssysdef.h\"\n#include \"csutil\/sysfunc.h\"\n#include \"iutil\/plugin.h\"\n#include \"iutil\/cfgfile.h\"\n#include \"iutil\/event.h\"\n#include \"iutil\/eventq.h\"\n#include \"iutil\/objreg.h\"\n#include \"isound\/driver.h\"\n#include \"isound\/data.h\"\n#include \"iutil\/eventh.h\"\n#include \"iutil\/comp.h\"\n#include \"iutil\/virtclk.h\"\n#include \"iutil\/cmdline.h\"\n#include \"ivaria\/reporter.h\"\n\n#include \"srdrcom.h\"\n#include \"..\/common\/slstn.h\"\n#include \"srdrsrc.h\"\n#include \"sndhdl.h\"\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_FACTORY (csSoundRenderSoftware)\n\n\nSCF_IMPLEMENT_IBASE(csSoundRenderSoftware)\n\tSCF_IMPLEMENTS_INTERFACE(iSoundRender)\n\tSCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)\nSCF_IMPLEMENT_IBASE_END;\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csSoundRenderSoftware::eiComponent)\n SCF_IMPLEMENTS_INTERFACE (iComponent)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_IBASE (csSoundRenderSoftware::EventHandler)\n SCF_IMPLEMENTS_INTERFACE (iEventHandler)\nSCF_IMPLEMENT_IBASE_END\n\ncsSoundRenderSoftware::csSoundRenderSoftware(iBase* piBase) : Listener(0)\n{\n SCF_CONSTRUCT_IBASE(piBase);\n SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);\n scfiEventHandler = 0;\n object_reg = 0;\n Listener = 0;\n memory = 0;\n memorysize = 0;\n ActivateMixing = false;\n owning = downing = false;\n data = csCondition::Create ();\n mixing = csMutex::Create (true);\n}\n\nvoid csSoundRenderSoftware::Report (int severity, const char* msg, ...)\n{\n va_list arg;\n va_start (arg, msg);\n csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter));\n if (rep)\n rep->ReportV (severity, \"crystalspace.sound.software\", msg, arg);\n else\n {\n csPrintfV (msg, arg);\n csPrintf (\"\\n\");\n }\n va_end (arg);\n}\n\nbool csSoundRenderSoftware::Initialize (iObjectRegistry *r)\n{\n \/\/ copy the system pointer\n object_reg = r;\n\n \/\/ read the config file\n Config.AddConfig(object_reg, \"\/config\/sound.cfg\");\n\n \/\/ check for optional sound driver fro the commandline\n csRef<iCommandLineParser> cmdline (CS_QUERY_REGISTRY (r, iCommandLineParser));\n const char *drv = cmdline->GetOption (\"sounddriver\");\n if (!drv)\n {\n \/\/ load the sound driver plug-in\n#ifdef CS_SOUND_DRIVER\n drv = CS_SOUND_DRIVER; \/\/ \"crystalspace.sound.driver.xxx\"\n#else\n drv = \"crystalspace.sound.driver.null\";\n#endif\n drv = Config->GetStr (\"Sound.Driver\", drv);\n }\n\n csRef<iPluginManager> plugin_mgr (\n \tCS_QUERY_REGISTRY (object_reg, iPluginManager));\n SoundDriver = CS_LOAD_PLUGIN (plugin_mgr, drv, iSoundDriver);\n if (!SoundDriver)\n {\n Report (CS_REPORTER_SEVERITY_ERROR,\n \"csSoundRenderSoftware: Failed to load sound driver: %s\", drv);\n return false;\n }\n\n \/\/ set event callback\n if (!scfiEventHandler)\n scfiEventHandler = new EventHandler (this);\n csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue));\n if (q != 0)\n q->RegisterListener(scfiEventHandler,\n CSMASK_Command | CSMASK_Broadcast | CSMASK_Nothing);\n\n return true;\n}\n\ncsSoundRenderSoftware::~csSoundRenderSoftware()\n{\n if (scfiEventHandler)\n {\n csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue));\n if (q != 0)\n q->RemoveListener (scfiEventHandler);\n scfiEventHandler->DecRef ();\n }\n Close();\n SCF_DESTRUCT_EMBEDDED_IBASE(scfiComponent);\n SCF_DESTRUCT_IBASE();\n}\n\nbool csSoundRenderSoftware::Open()\n{\n Report (CS_REPORTER_SEVERITY_NOTIFY, \"Software Sound Renderer selected\");\n CS_ASSERT (Config != 0);\n\n if (!SoundDriver) return false;\n\n SoundDriver->Open (this,\n Config->GetInt(\"Sound.Software.Frequency\", 22050),\n Config->GetBool(\"Sound.Software.16Bits\", true),\n Config->GetBool(\"Sound.Software.Stereo\", true));\n\n Volume = Config->GetFloat(\"Sound.Volume\", 1.0);\n if (Volume>1) Volume = 1;\n if (Volume<0) Volume = 0;\n\n Listener = new csSoundListener ();\n ActivateMixing = true;\n LoadFormat.Freq = getFrequency();\n LoadFormat.Bits = is16Bits() ? 16 : 8;\n LoadFormat.Channels = -1;\n\n Report (CS_REPORTER_SEVERITY_NOTIFY, \" Playing %d Hz, %d bits, %s\",\n getFrequency(), (is16Bits())?16:8, (isStereo())?\"Stereo\":\"Mono\");\n Report (CS_REPORTER_SEVERITY_NOTIFY, \" Volume: %g\", Volume);\n\n csTicks et, ct;\n csRef<iVirtualClock> vc (CS_QUERY_REGISTRY (object_reg, iVirtualClock));\n\n et = vc->GetElapsedTicks ();\n ct = vc->GetCurrentTicks ();\n LastTime = ct;\n\n if (SoundDriver->ThreadAware ())\n {\n mixing->LockWait ();\n bRunning = true;\n mixer = csThread::Create (new MixerRunnable (this));\n mixer->Start ();\n mixing->Release ();\n }\n return true;\n}\n\nvoid csSoundRenderSoftware::Close()\n{\n bRunning = false;\n data->Signal (true);\n mixing->LockWait ();\n owning = true;\n downing = true;\n ActivateMixing = false;\n if (SoundDriver)\n {\n SoundDriver->Close ();\n SoundDriver = 0;\n }\n\n if (Listener)\n {\n Listener->DecRef();\n Listener = 0;\n }\n\n while (Sources.Length()>0)\n Sources.Get(0)->Stop();\n\n while (SoundHandles.Length()>0)\n {\n csSoundHandleSoftware *hdl = SoundHandles.Pop();\n hdl->Unregister();\n hdl->DecRef();\n }\n owning = false;\n downing = false;\n mixing->Release ();\n}\n\ncsPtr<iSoundHandle> csSoundRenderSoftware::RegisterSound(iSoundData *snd)\n{\n \/\/ convert the sound\n if (!snd->Initialize(&LoadFormat)) return 0;\n\n \/\/ create the sound handle\n csSoundHandleSoftware *hdl = new csSoundHandleSoftware(this, snd);\n SoundHandles.Push(hdl);\n hdl->IncRef ();\t\/\/ Prevent smart pointer release.\n return csPtr<iSoundHandle> (hdl);\n}\n\nvoid csSoundRenderSoftware::UnregisterSound(iSoundHandle *snd)\n{\n int n = SoundHandles.Find((csSoundHandleSoftware*)snd);\n if (n != -1)\n {\n if (owning || mixing->LockWait ()) \/\/ dont remove while we mix\n {\n csSoundHandleSoftware *hdl = (csSoundHandleSoftware *)snd;\n SoundHandles.DeleteIndex (n);\n hdl->Unregister();\n hdl->DecRef();\n \n if (!owning) mixing->Release ();\n }\n }\n}\n\niSoundListener *csSoundRenderSoftware::GetListener()\n{\n return Listener;\n}\n\nbool csSoundRenderSoftware::is16Bits()\n{\n return SoundDriver->Is16Bits();\n}\n\nbool csSoundRenderSoftware::isStereo()\n{\n return SoundDriver->IsStereo();\n}\n\nint csSoundRenderSoftware::getFrequency()\n{\n return SoundDriver->GetFrequency();\n}\n\nvoid csSoundRenderSoftware::SetVolume(float vol)\n{\n Volume = vol;\n}\n\nfloat csSoundRenderSoftware::GetVolume()\n{\n return Volume;\n}\n\nvoid csSoundRenderSoftware::AddSource(csSoundSourceSoftware *src)\n{\n Sources.Push(src);\n src->IncRef();\n data->Signal (true);\n}\n\nvoid csSoundRenderSoftware::RemoveSource(csSoundSourceSoftware *src)\n{\n if (downing || mixing->LockWait ()) \/\/ dont remove while we mix\n {\n if (!downing) owning = true;\n int n=Sources.Find(src);\n if (n!=-1)\n {\n Sources.DeleteIndex (n);\n src->DecRef();\n }\n if (!downing) \n {\n owning = false;\n mixing->Release ();\n }\n }\n}\n\nvoid csSoundRenderSoftware::MixingFunction()\n{\n size_t i;\n\n \/\/ look if this function is activated\n if (!ActivateMixing) return;\n\n \/\/ test if we have a sound driver\n if(!SoundDriver) return;\n\n \/\/ Get a mixing lock. Mutex is recursive.\n mixing->LockWait ();\n\n \/\/ if no sources exist, there may be an optimized way to handle this\n if (Sources.Length()==0 && SoundDriver->IsHandleVoidSound())\n {\n mixing->Release();\n return;\n }\n\n \/\/ lock sound memory\n SoundDriver->LockMemory(&memory, &memorysize);\n if(!memory || memorysize<1) \n {\n mixing->Release();\n return;\n }\n\n \/\/ clear the buffer\n if (is16Bits()) memset(memory,0,memorysize);\n else memset(memory,128,memorysize);\n\n \/\/ prepare and play all sources\n for (i=0;i<Sources.Length();i++)\n {\n csSoundSourceSoftware *src=Sources.Get(i);\n src->Prepare(Volume);\n src->AddToBufferStatic(memory, memorysize);\n if (!src->IsActive())\n {\n Sources.DeleteIndex (i);\n src->DecRef ();\n i--;\n }\n }\n\n \/* Do not update the sound handles. Right now the source advances\n * the sound data stream. The default handle UpdateCount() function\n * will also advance the stream causing the sound to skip and play\n * twice as fast if the stream is started.\n *\/\n\/*\n \/\/ update sound handles\n long NumSamples = memorysize \/ (is16Bits()?2:1) \/ (isStereo()?2:1);\n for (i=0;i<SoundHandles.Length();i++) {\n csSoundHandleSoftware *hdl = SoundHandles.Get(i);\n hdl->UpdateCount(NumSamples);\n }\n*\/\n SoundDriver->UnlockMemory();\n mixing->Release();\n}\n\nbool csSoundRenderSoftware::HandleEvent (iEvent &e)\n{\n if (e.Type == csevCommand || e.Type == csevBroadcast) {\n switch (e.Command.Code) {\n case cscmdPreProcess:\n Update();\n break;\n case cscmdSystemOpen:\n Open();\n break;\n case cscmdSystemClose:\n Close();\n break;\n }\n }\n return false;\n}\n\nvoid csSoundRenderSoftware::Update()\n{\n \/\/ update sound if the sound driver doesn't do it\n if(!SoundDriver->IsBackground()) MixingFunction();\n}\n\nvoid csSoundRenderSoftware::ThreadedMix ()\n{\n while (bRunning)\n {\n mixing->LockWait ();\n data->Wait (mixing);\n bool bRelock = false;\n while (bRunning && Sources.Length() != 0)\n {\n if (bRelock) mixing->LockWait ();\n MixingFunction ();\n mixing->Release ();\n bRelock = true;\n }\n if (!bRelock) mixing->Release ();\n }\n}\n<commit_msg>Release the renderer mutex while closing the driver to avoid a potential deadlock.<commit_after>\/*\n\tCopyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin\n\tCopyright (C) 1998, 1999 by Jorrit Tyberghein\n\tWritten by Nathaniel 'NooTe' Saint Martin\n\n\tThis library is free software; you can redistribute it and\/or\n\tmodify it under the terms of the GNU Library General Public\n\tLicense as published by the Free Software Foundation; either\n\tversion 2 of the License, or (at your option) any later version.\n\n\tThis library is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\tLibrary General Public License for more details.\n\n\tYou should have received a copy of the GNU Library General Public\n\tLicense along with this library; if not, write to the Free\n\tSoftware Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"cssysdef.h\"\n#include \"csutil\/sysfunc.h\"\n#include \"iutil\/plugin.h\"\n#include \"iutil\/cfgfile.h\"\n#include \"iutil\/event.h\"\n#include \"iutil\/eventq.h\"\n#include \"iutil\/objreg.h\"\n#include \"isound\/driver.h\"\n#include \"isound\/data.h\"\n#include \"iutil\/eventh.h\"\n#include \"iutil\/comp.h\"\n#include \"iutil\/virtclk.h\"\n#include \"iutil\/cmdline.h\"\n#include \"ivaria\/reporter.h\"\n\n#include \"srdrcom.h\"\n#include \"..\/common\/slstn.h\"\n#include \"srdrsrc.h\"\n#include \"sndhdl.h\"\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_FACTORY (csSoundRenderSoftware)\n\n\nSCF_IMPLEMENT_IBASE(csSoundRenderSoftware)\n\tSCF_IMPLEMENTS_INTERFACE(iSoundRender)\n\tSCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)\nSCF_IMPLEMENT_IBASE_END;\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csSoundRenderSoftware::eiComponent)\n SCF_IMPLEMENTS_INTERFACE (iComponent)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_IBASE (csSoundRenderSoftware::EventHandler)\n SCF_IMPLEMENTS_INTERFACE (iEventHandler)\nSCF_IMPLEMENT_IBASE_END\n\ncsSoundRenderSoftware::csSoundRenderSoftware(iBase* piBase) : Listener(0)\n{\n SCF_CONSTRUCT_IBASE(piBase);\n SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);\n scfiEventHandler = 0;\n object_reg = 0;\n Listener = 0;\n memory = 0;\n memorysize = 0;\n ActivateMixing = false;\n owning = downing = false;\n data = csCondition::Create ();\n mixing = csMutex::Create (true);\n}\n\nvoid csSoundRenderSoftware::Report (int severity, const char* msg, ...)\n{\n va_list arg;\n va_start (arg, msg);\n csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter));\n if (rep)\n rep->ReportV (severity, \"crystalspace.sound.software\", msg, arg);\n else\n {\n csPrintfV (msg, arg);\n csPrintf (\"\\n\");\n }\n va_end (arg);\n}\n\nbool csSoundRenderSoftware::Initialize (iObjectRegistry *r)\n{\n \/\/ copy the system pointer\n object_reg = r;\n\n \/\/ read the config file\n Config.AddConfig(object_reg, \"\/config\/sound.cfg\");\n\n \/\/ check for optional sound driver fro the commandline\n csRef<iCommandLineParser> cmdline (CS_QUERY_REGISTRY (r, iCommandLineParser));\n const char *drv = cmdline->GetOption (\"sounddriver\");\n if (!drv)\n {\n \/\/ load the sound driver plug-in\n#ifdef CS_SOUND_DRIVER\n drv = CS_SOUND_DRIVER; \/\/ \"crystalspace.sound.driver.xxx\"\n#else\n drv = \"crystalspace.sound.driver.null\";\n#endif\n drv = Config->GetStr (\"Sound.Driver\", drv);\n }\n\n csRef<iPluginManager> plugin_mgr (\n \tCS_QUERY_REGISTRY (object_reg, iPluginManager));\n SoundDriver = CS_LOAD_PLUGIN (plugin_mgr, drv, iSoundDriver);\n if (!SoundDriver)\n {\n Report (CS_REPORTER_SEVERITY_ERROR,\n \"csSoundRenderSoftware: Failed to load sound driver: %s\", drv);\n return false;\n }\n\n \/\/ set event callback\n if (!scfiEventHandler)\n scfiEventHandler = new EventHandler (this);\n csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue));\n if (q != 0)\n q->RegisterListener(scfiEventHandler,\n CSMASK_Command | CSMASK_Broadcast | CSMASK_Nothing);\n\n return true;\n}\n\ncsSoundRenderSoftware::~csSoundRenderSoftware()\n{\n if (scfiEventHandler)\n {\n csRef<iEventQueue> q (CS_QUERY_REGISTRY(object_reg, iEventQueue));\n if (q != 0)\n q->RemoveListener (scfiEventHandler);\n scfiEventHandler->DecRef ();\n }\n Close();\n SCF_DESTRUCT_EMBEDDED_IBASE(scfiComponent);\n SCF_DESTRUCT_IBASE();\n}\n\nbool csSoundRenderSoftware::Open()\n{\n Report (CS_REPORTER_SEVERITY_NOTIFY, \"Software Sound Renderer selected\");\n CS_ASSERT (Config != 0);\n\n if (!SoundDriver) return false;\n\n SoundDriver->Open (this,\n Config->GetInt(\"Sound.Software.Frequency\", 22050),\n Config->GetBool(\"Sound.Software.16Bits\", true),\n Config->GetBool(\"Sound.Software.Stereo\", true));\n\n Volume = Config->GetFloat(\"Sound.Volume\", 1.0);\n if (Volume>1) Volume = 1;\n if (Volume<0) Volume = 0;\n\n Listener = new csSoundListener ();\n ActivateMixing = true;\n LoadFormat.Freq = getFrequency();\n LoadFormat.Bits = is16Bits() ? 16 : 8;\n LoadFormat.Channels = -1;\n\n Report (CS_REPORTER_SEVERITY_NOTIFY, \" Playing %d Hz, %d bits, %s\",\n getFrequency(), (is16Bits())?16:8, (isStereo())?\"Stereo\":\"Mono\");\n Report (CS_REPORTER_SEVERITY_NOTIFY, \" Volume: %g\", Volume);\n\n csTicks et, ct;\n csRef<iVirtualClock> vc (CS_QUERY_REGISTRY (object_reg, iVirtualClock));\n\n et = vc->GetElapsedTicks ();\n ct = vc->GetCurrentTicks ();\n LastTime = ct;\n\n if (SoundDriver->ThreadAware ())\n {\n mixing->LockWait ();\n bRunning = true;\n mixer = csThread::Create (new MixerRunnable (this));\n mixer->Start ();\n mixing->Release ();\n }\n return true;\n}\n\nvoid csSoundRenderSoftware::Close()\n{\n bRunning = false;\n data->Signal (true);\n mixing->LockWait ();\n owning = true;\n downing = true;\n ActivateMixing = false;\n\n \/\/ Must release the lock while we close the driver\n mixing->Release ();\n\n if (SoundDriver)\n {\n SoundDriver->Close ();\n SoundDriver = 0;\n }\n\n mixing->LockWait ();\n if (Listener)\n {\n Listener->DecRef();\n Listener = 0;\n }\n\n while (Sources.Length()>0)\n Sources.Get(0)->Stop();\n\n while (SoundHandles.Length()>0)\n {\n csSoundHandleSoftware *hdl = SoundHandles.Pop();\n hdl->Unregister();\n hdl->DecRef();\n }\n owning = false;\n downing = false;\n mixing->Release ();\n}\n\ncsPtr<iSoundHandle> csSoundRenderSoftware::RegisterSound(iSoundData *snd)\n{\n \/\/ convert the sound\n if (!snd->Initialize(&LoadFormat)) return 0;\n\n \/\/ create the sound handle\n csSoundHandleSoftware *hdl = new csSoundHandleSoftware(this, snd);\n SoundHandles.Push(hdl);\n hdl->IncRef ();\t\/\/ Prevent smart pointer release.\n return csPtr<iSoundHandle> (hdl);\n}\n\nvoid csSoundRenderSoftware::UnregisterSound(iSoundHandle *snd)\n{\n int n = SoundHandles.Find((csSoundHandleSoftware*)snd);\n if (n != -1)\n {\n if (owning || mixing->LockWait ()) \/\/ dont remove while we mix\n {\n csSoundHandleSoftware *hdl = (csSoundHandleSoftware *)snd;\n SoundHandles.DeleteIndex (n);\n hdl->Unregister();\n hdl->DecRef();\n \n if (!owning) mixing->Release ();\n }\n }\n}\n\niSoundListener *csSoundRenderSoftware::GetListener()\n{\n return Listener;\n}\n\nbool csSoundRenderSoftware::is16Bits()\n{\n return SoundDriver->Is16Bits();\n}\n\nbool csSoundRenderSoftware::isStereo()\n{\n return SoundDriver->IsStereo();\n}\n\nint csSoundRenderSoftware::getFrequency()\n{\n return SoundDriver->GetFrequency();\n}\n\nvoid csSoundRenderSoftware::SetVolume(float vol)\n{\n Volume = vol;\n}\n\nfloat csSoundRenderSoftware::GetVolume()\n{\n return Volume;\n}\n\nvoid csSoundRenderSoftware::AddSource(csSoundSourceSoftware *src)\n{\n Sources.Push(src);\n src->IncRef();\n data->Signal (true);\n}\n\nvoid csSoundRenderSoftware::RemoveSource(csSoundSourceSoftware *src)\n{\n if (downing || mixing->LockWait ()) \/\/ dont remove while we mix\n {\n if (!downing) owning = true;\n int n=Sources.Find(src);\n if (n!=-1)\n {\n Sources.DeleteIndex (n);\n src->DecRef();\n }\n if (!downing) \n {\n owning = false;\n mixing->Release ();\n }\n }\n}\n\nvoid csSoundRenderSoftware::MixingFunction()\n{\n size_t i;\n\n \/\/ look if this function is activated\n if (!ActivateMixing) return;\n\n \/\/ test if we have a sound driver\n if(!SoundDriver) return;\n\n \/\/ Get a mixing lock. Mutex is recursive.\n mixing->LockWait ();\n\n \/\/ if no sources exist, there may be an optimized way to handle this\n if (Sources.Length()==0 && SoundDriver->IsHandleVoidSound())\n {\n mixing->Release();\n return;\n }\n\n \/\/ lock sound memory\n SoundDriver->LockMemory(&memory, &memorysize);\n if(!memory || memorysize<1) \n {\n mixing->Release();\n return;\n }\n\n \/\/ clear the buffer\n if (is16Bits()) memset(memory,0,memorysize);\n else memset(memory,128,memorysize);\n\n \/\/ prepare and play all sources\n for (i=0;i<Sources.Length();i++)\n {\n csSoundSourceSoftware *src=Sources.Get(i);\n src->Prepare(Volume);\n src->AddToBufferStatic(memory, memorysize);\n if (!src->IsActive())\n {\n Sources.DeleteIndex (i);\n src->DecRef ();\n i--;\n }\n }\n\n \/* Do not update the sound handles. Right now the source advances\n * the sound data stream. The default handle UpdateCount() function\n * will also advance the stream causing the sound to skip and play\n * twice as fast if the stream is started.\n *\/\n\/*\n \/\/ update sound handles\n long NumSamples = memorysize \/ (is16Bits()?2:1) \/ (isStereo()?2:1);\n for (i=0;i<SoundHandles.Length();i++) {\n csSoundHandleSoftware *hdl = SoundHandles.Get(i);\n hdl->UpdateCount(NumSamples);\n }\n*\/\n SoundDriver->UnlockMemory();\n mixing->Release();\n}\n\nbool csSoundRenderSoftware::HandleEvent (iEvent &e)\n{\n if (e.Type == csevCommand || e.Type == csevBroadcast) {\n switch (e.Command.Code) {\n case cscmdPreProcess:\n Update();\n break;\n case cscmdSystemOpen:\n Open();\n break;\n case cscmdSystemClose:\n Close();\n break;\n }\n }\n return false;\n}\n\nvoid csSoundRenderSoftware::Update()\n{\n \/\/ update sound if the sound driver doesn't do it\n if(!SoundDriver->IsBackground()) MixingFunction();\n}\n\nvoid csSoundRenderSoftware::ThreadedMix ()\n{\n while (bRunning)\n {\n mixing->LockWait ();\n data->Wait (mixing);\n bool bRelock = false;\n while (bRunning && Sources.Length() != 0)\n {\n if (bRelock) mixing->LockWait ();\n MixingFunction ();\n mixing->Release ();\n bRelock = true;\n }\n if (!bRelock) mixing->Release ();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: window3.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-01-13 18:06:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define _SV_WINDOW_CXX\n\n#ifndef _SV_SVSYS_HXX\n#include <svsys.h>\n#endif\n\n#ifndef _SV_WINDOW_H\n#include <window.h>\n#endif\n#ifndef _SV_WINDOW_HXX\n#include <window.hxx>\n#endif\n#ifndef _SV_WAITOBJ_HXX\n#include <waitobj.hxx>\n#endif\n\n#ifndef _SV_SALGDI_HXX\n#include <salgdi.hxx>\n#endif\n#ifndef _SV_NATIVEWIDGETS_HXX\n#include <salnativewidgets.hxx>\n#endif\n#ifndef _SV_SALCTRLHANDLE_HXX\n#include <salctrlhandle.hxx>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\nusing namespace rtl;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ These functions are mainly passthrough functions that allow access to\n\/\/ the SalFrame behind a Window object for native widget rendering purposes.\n\/\/ -----------------------------------------------------------------------\n\nvoid Window::ImplInitSalControlHandle()\n{\n \/\/ create SalControlHandle on demand\n \/\/ not needed for ordinary windows\n \/\/ TODO: move creation to SalGraphics\n \/\/if( !ImplGetWinData()->mpSalControlHandle )\n \/\/ ImplGetWinData()->mpSalControlHandle = new SalControlHandle;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n return( mpGraphics->IsNativeControlSupported(nType, nPart) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::HitTestNativeControl( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n const Point& aPos,\n BOOL& rIsInside )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n ImplInitSalControlHandle();\n return( mpGraphics->HitTestNativeControl(nType, nPart, rControlRegion, aPos, *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::DrawNativeControl( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n \/*\n if( !IsInPaint() && IsPaintTransparent() )\n {\n \/\/ only required if called directly (ie, we're not in Paint() ):\n \/\/ force redraw (Paint()) for transparent controls\n \/\/ to trigger a repaint of the background\n Region aClipRgn( GetClipRegion() );\n if( !rControlRegion.IsEmpty() )\n aClipRgn.Intersect( rControlRegion );\n Invalidate( aClipRgn, INVALIDATE_UPDATE );\n return TRUE;\n }\n *\/\n\n ImplInitSalControlHandle();\n\n \/\/ make sure the current clip region is initialized correctly\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n if ( mbInitClipRegion )\n ImplInitClipRegion();\n if ( mbOutputClipped )\n return TRUE;\n\n if ( mbInitLineColor )\n ImplInitLineColor();\n if ( mbInitFillColor )\n ImplInitFillColor();\n\n \/\/ Convert the coordinates from relative to Window-absolute, so we draw\n \/\/ in the correct place in platform code\n Point aWinOffs;\n aWinOffs = OutputToScreenPixel( aWinOffs );\n Region screenRegion( rControlRegion );\n screenRegion.Move( aWinOffs.X(), aWinOffs.Y());\n\n Region aTestRegion( GetActiveClipRegion() );\n aTestRegion.Intersect( rControlRegion );\n if( aTestRegion == rControlRegion )\n nState |= CTRL_CACHING_ALLOWED; \/\/ control is not clipped, caching allowed\n\n return( mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::DrawNativeControlText(ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n ImplInitSalControlHandle();\n\n \/\/ make sure the current clip region is initialized correctly\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return false;\n\n if ( mbInitClipRegion )\n ImplInitClipRegion();\n if ( mbOutputClipped )\n return true;\n\n if ( mbInitLineColor )\n ImplInitLineColor();\n if ( mbInitFillColor )\n ImplInitFillColor();\n\n \/\/ Convert the coordinates from relative to Window-absolute, so we draw\n \/\/ in the correct place in platform code\n Point aWinOffs;\n aWinOffs = OutputToScreenPixel( aWinOffs );\n Region screenRegion( rControlRegion );\n screenRegion.Move( aWinOffs.X(), aWinOffs.Y());\n\n return( mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::GetNativeControlRegion( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption,\n Region &rNativeBoundingRegion,\n Region &rNativeContentRegion )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n ImplInitSalControlHandle();\n return( mpGraphics->GetNativeControlRegion(nType, nPart, rControlRegion, nState, aValue,\n *ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,\n rNativeContentRegion, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nWaitObject::~WaitObject()\n{\n if ( mpWindow )\n mpWindow->LeaveWait();\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.258); FILE MERGED 2005\/09\/05 14:45:19 rt 1.4.258.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: window3.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:33:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#define _SV_WINDOW_CXX\n\n#ifndef _SV_SVSYS_HXX\n#include <svsys.h>\n#endif\n\n#ifndef _SV_WINDOW_H\n#include <window.h>\n#endif\n#ifndef _SV_WINDOW_HXX\n#include <window.hxx>\n#endif\n#ifndef _SV_WAITOBJ_HXX\n#include <waitobj.hxx>\n#endif\n\n#ifndef _SV_SALGDI_HXX\n#include <salgdi.hxx>\n#endif\n#ifndef _SV_NATIVEWIDGETS_HXX\n#include <salnativewidgets.hxx>\n#endif\n#ifndef _SV_SALCTRLHANDLE_HXX\n#include <salctrlhandle.hxx>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\nusing namespace rtl;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ These functions are mainly passthrough functions that allow access to\n\/\/ the SalFrame behind a Window object for native widget rendering purposes.\n\/\/ -----------------------------------------------------------------------\n\nvoid Window::ImplInitSalControlHandle()\n{\n \/\/ create SalControlHandle on demand\n \/\/ not needed for ordinary windows\n \/\/ TODO: move creation to SalGraphics\n \/\/if( !ImplGetWinData()->mpSalControlHandle )\n \/\/ ImplGetWinData()->mpSalControlHandle = new SalControlHandle;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n return( mpGraphics->IsNativeControlSupported(nType, nPart) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::HitTestNativeControl( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n const Point& aPos,\n BOOL& rIsInside )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n ImplInitSalControlHandle();\n return( mpGraphics->HitTestNativeControl(nType, nPart, rControlRegion, aPos, *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::DrawNativeControl( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n \/*\n if( !IsInPaint() && IsPaintTransparent() )\n {\n \/\/ only required if called directly (ie, we're not in Paint() ):\n \/\/ force redraw (Paint()) for transparent controls\n \/\/ to trigger a repaint of the background\n Region aClipRgn( GetClipRegion() );\n if( !rControlRegion.IsEmpty() )\n aClipRgn.Intersect( rControlRegion );\n Invalidate( aClipRgn, INVALIDATE_UPDATE );\n return TRUE;\n }\n *\/\n\n ImplInitSalControlHandle();\n\n \/\/ make sure the current clip region is initialized correctly\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n if ( mbInitClipRegion )\n ImplInitClipRegion();\n if ( mbOutputClipped )\n return TRUE;\n\n if ( mbInitLineColor )\n ImplInitLineColor();\n if ( mbInitFillColor )\n ImplInitFillColor();\n\n \/\/ Convert the coordinates from relative to Window-absolute, so we draw\n \/\/ in the correct place in platform code\n Point aWinOffs;\n aWinOffs = OutputToScreenPixel( aWinOffs );\n Region screenRegion( rControlRegion );\n screenRegion.Move( aWinOffs.X(), aWinOffs.Y());\n\n Region aTestRegion( GetActiveClipRegion() );\n aTestRegion.Intersect( rControlRegion );\n if( aTestRegion == rControlRegion )\n nState |= CTRL_CACHING_ALLOWED; \/\/ control is not clipped, caching allowed\n\n return( mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::DrawNativeControlText(ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n ImplInitSalControlHandle();\n\n \/\/ make sure the current clip region is initialized correctly\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return false;\n\n if ( mbInitClipRegion )\n ImplInitClipRegion();\n if ( mbOutputClipped )\n return true;\n\n if ( mbInitLineColor )\n ImplInitLineColor();\n if ( mbInitFillColor )\n ImplInitFillColor();\n\n \/\/ Convert the coordinates from relative to Window-absolute, so we draw\n \/\/ in the correct place in platform code\n Point aWinOffs;\n aWinOffs = OutputToScreenPixel( aWinOffs );\n Region screenRegion( rControlRegion );\n screenRegion.Move( aWinOffs.X(), aWinOffs.Y());\n\n return( mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL Window::GetNativeControlRegion( ControlType nType,\n ControlPart nPart,\n const Region& rControlRegion,\n ControlState nState,\n const ImplControlValue& aValue,\n OUString aCaption,\n Region &rNativeBoundingRegion,\n Region &rNativeContentRegion )\n{\n if( !IsNativeWidgetEnabled() )\n return FALSE;\n\n if ( !mpGraphics )\n if ( !ImplGetGraphics() )\n return FALSE;\n\n ImplInitSalControlHandle();\n return( mpGraphics->GetNativeControlRegion(nType, nPart, rControlRegion, nState, aValue,\n *ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,\n rNativeContentRegion, this ) );\n}\n\n\n\/\/ -----------------------------------------------------------------------\n\nWaitObject::~WaitObject()\n{\n if ( mpWindow )\n mpWindow->LeaveWait();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/bootstrap.h\"\n\n#include \"include\/dart_api.h\"\n\n#include \"vm\/bootstrap_natives.h\"\n#include \"vm\/class_finalizer.h\"\n#include \"vm\/compiler.h\"\n#include \"vm\/dart_api_impl.h\"\n#include \"vm\/object.h\"\n#include \"vm\/object_store.h\"\n#include \"vm\/symbols.h\"\n\nnamespace dart {\n\n#define INIT_LIBRARY(index, name, source, patch) \\\n { index, \\\n \"dart:\"#name, source, \\\n \"dart:\"#name\"-patch\", patch } \\\n\ntypedef struct {\n ObjectStore::BootstrapLibraryId index_;\n const char* uri_;\n const char** source_paths_;\n const char* patch_uri_;\n const char** patch_paths_;\n} bootstrap_lib_props;\n\n\nenum {\n kPathsUriOffset = 0,\n kPathsFileOffset = 1,\n kPathsSourceOffset = 2,\n kPathsEntryLength = 3\n};\n\n\nstatic bootstrap_lib_props bootstrap_libraries[] = {\n INIT_LIBRARY(ObjectStore::kCore,\n core,\n Bootstrap::core_source_paths_,\n Bootstrap::core_patch_paths_),\n INIT_LIBRARY(ObjectStore::kAsync,\n async,\n Bootstrap::async_source_paths_,\n Bootstrap::async_patch_paths_),\n INIT_LIBRARY(ObjectStore::kConvert,\n convert,\n Bootstrap::convert_source_paths_,\n Bootstrap::convert_patch_paths_),\n INIT_LIBRARY(ObjectStore::kCollection,\n collection,\n Bootstrap::collection_source_paths_,\n Bootstrap::collection_patch_paths_),\n INIT_LIBRARY(ObjectStore::kDeveloper,\n developer,\n Bootstrap::developer_source_paths_,\n Bootstrap::developer_patch_paths_),\n INIT_LIBRARY(ObjectStore::kInternal,\n _internal,\n Bootstrap::_internal_source_paths_,\n Bootstrap::_internal_patch_paths_),\n INIT_LIBRARY(ObjectStore::kIsolate,\n isolate,\n Bootstrap::isolate_source_paths_,\n Bootstrap::isolate_patch_paths_),\n INIT_LIBRARY(ObjectStore::kMath,\n math,\n Bootstrap::math_source_paths_,\n Bootstrap::math_patch_paths_),\n INIT_LIBRARY(ObjectStore::kMirrors,\n mirrors,\n Bootstrap::mirrors_source_paths_,\n Bootstrap::mirrors_patch_paths_),\n INIT_LIBRARY(ObjectStore::kProfiler,\n profiler,\n Bootstrap::profiler_source_paths_,\n NULL),\n INIT_LIBRARY(ObjectStore::kTypedData,\n typed_data,\n Bootstrap::typed_data_source_paths_,\n Bootstrap::typed_data_patch_paths_),\n INIT_LIBRARY(ObjectStore::kVMService,\n _vmservice,\n Bootstrap::_vmservice_source_paths_,\n Bootstrap::_vmservice_patch_paths_),\n { ObjectStore::kNone, NULL, NULL, NULL, NULL }\n};\n\n\nstatic RawString* GetLibrarySource(const Library& lib,\n const String& uri,\n bool patch) {\n \/\/ First check if this is a valid bootstrap library and find it's index\n \/\/ in the 'bootstrap_libraries' table above.\n intptr_t index;\n const String& lib_uri = String::Handle(lib.url());\n for (index = 0;\n bootstrap_libraries[index].index_ != ObjectStore::kNone;\n ++index) {\n if (lib_uri.Equals(bootstrap_libraries[index].uri_)) {\n break;\n }\n }\n if (bootstrap_libraries[index].index_ == ObjectStore::kNone) {\n return String::null(); \/\/ Library is not a bootstrap library.\n }\n\n \/\/ Try to read the source using the path specified for the uri.\n const char** source_paths = patch ?\n bootstrap_libraries[index].patch_paths_ :\n bootstrap_libraries[index].source_paths_;\n if (source_paths == NULL) {\n return String::null(); \/\/ No path mapping information exists for library.\n }\n const char* source_path = NULL;\n const char* source_data = NULL;\n for (intptr_t i = 0; source_paths[i] != NULL; i += kPathsEntryLength) {\n if (uri.Equals(source_paths[i + kPathsUriOffset])) {\n source_path = source_paths[i + kPathsFileOffset];\n source_data = source_paths[i + kPathsSourceOffset];\n break;\n }\n }\n if ((source_path == NULL) && (source_data == NULL)) {\n return String::null(); \/\/ Uri does not exist in path mapping information.\n }\n\n const uint8_t* utf8_array = NULL;\n intptr_t file_length = -1;\n\n Dart_FileOpenCallback file_open = Isolate::file_open_callback();\n Dart_FileReadCallback file_read = Isolate::file_read_callback();\n Dart_FileCloseCallback file_close = Isolate::file_close_callback();\n if ((file_open != NULL) && (file_read != NULL) && (file_close != NULL)) {\n \/\/ Try to open and read the file.\n void* stream = (*file_open)(source_path, false);\n if (stream != NULL) {\n (*file_read)(&utf8_array, &file_length, stream);\n (*file_close)(stream);\n }\n }\n if (file_length == -1) {\n if (source_data != NULL) {\n file_length = strlen(source_data);\n utf8_array = reinterpret_cast<const uint8_t*>(source_data);\n } else {\n return String::null();\n }\n }\n ASSERT(utf8_array != NULL);\n ASSERT(file_length >= 0);\n return String::FromUTF8(utf8_array, file_length);\n}\n\n\nstatic RawError* Compile(const Library& library, const Script& script) {\n bool update_lib_status = (script.kind() == RawScript::kScriptTag ||\n script.kind() == RawScript::kLibraryTag);\n if (update_lib_status) {\n library.SetLoadInProgress();\n }\n const Error& error = Error::Handle(Compiler::Compile(library, script));\n if (update_lib_status) {\n if (error.IsNull()) {\n library.SetLoaded();\n } else {\n \/\/ Compilation errors are not Dart instances, so just mark the library\n \/\/ as having failed to load without providing an error instance.\n library.SetLoadError(Object::null_instance());\n }\n }\n return error.raw();\n}\n\n\nstatic Dart_Handle LoadPartSource(Thread* thread,\n const Library& lib,\n const String& uri) {\n Zone* zone = thread->zone();\n const String& part_source = String::Handle(\n zone, GetLibrarySource(lib, uri, false));\n const String& lib_uri = String::Handle(zone, lib.url());\n if (part_source.IsNull()) {\n return Api::NewError(\"Unable to read part file '%s' of library '%s'\",\n uri.ToCString(), lib_uri.ToCString());\n }\n\n \/\/ Prepend the library URI to form a unique script URI for the part.\n const Array& strings = Array::Handle(zone, Array::New(3));\n strings.SetAt(0, lib_uri);\n strings.SetAt(1, Symbols::Slash());\n strings.SetAt(2, uri);\n const String& part_uri = String::Handle(zone, String::ConcatAll(strings));\n\n \/\/ Create a script object and compile the part.\n const Script& part_script = Script::Handle(\n zone, Script::New(part_uri, part_source, RawScript::kSourceTag));\n const Error& error = Error::Handle(zone, Compile(lib, part_script));\n return Api::NewHandle(thread, error.raw());\n}\n\n\nstatic Dart_Handle BootstrapLibraryTagHandler(Dart_LibraryTag tag,\n Dart_Handle library,\n Dart_Handle uri) {\n Thread* thread = Thread::Current();\n Zone* zone = thread->zone();\n \/\/ This handler calls into the VM directly and does not use the Dart\n \/\/ API so we transition back to VM.\n TransitionNativeToVM transition(thread);\n if (!Dart_IsLibrary(library)) {\n return Api::NewError(\"not a library\");\n }\n if (!Dart_IsString(uri)) {\n return Api::NewError(\"uri is not a string\");\n }\n if (tag == Dart_kCanonicalizeUrl) {\n \/\/ In the bootstrap loader we do not try and do any canonicalization.\n return uri;\n }\n const String& uri_str = Api::UnwrapStringHandle(zone, uri);\n ASSERT(!uri_str.IsNull());\n if (tag == Dart_kImportTag) {\n \/\/ We expect the core bootstrap libraries to only import other\n \/\/ core bootstrap libraries.\n \/\/ We have precreated all the bootstrap library objects hence\n \/\/ we do not expect to be called back with the tag set to kImportTag.\n \/\/ The bootstrap process explicitly loads all the libraries one by one.\n return Api::NewError(\"Invalid import of '%s' in a bootstrap library\",\n uri_str.ToCString());\n }\n ASSERT(tag == Dart_kSourceTag);\n const Library& lib = Api::UnwrapLibraryHandle(zone, library);\n ASSERT(!lib.IsNull());\n return LoadPartSource(thread, lib, uri_str);\n}\n\n\nstatic RawError* LoadPatchFiles(Zone* zone,\n const Library& lib,\n const String& patch_uri,\n const char** patch_files) {\n String& patch_file_uri = String::Handle(zone);\n String& source = String::Handle(zone);\n Script& script = Script::Handle(zone);\n Error& error = Error::Handle(zone);\n const Array& strings = Array::Handle(zone, Array::New(3));\n strings.SetAt(0, patch_uri);\n strings.SetAt(1, Symbols::Slash());\n for (intptr_t j = 0; patch_files[j] != NULL; j += kPathsEntryLength) {\n patch_file_uri = String::New(patch_files[j + kPathsUriOffset]);\n source = GetLibrarySource(lib, patch_file_uri, true);\n if (source.IsNull()) {\n const String& message = String::Handle(\n String::NewFormatted(\"Unable to find dart patch source for %s\",\n patch_file_uri.ToCString()));\n return ApiError::New(message);\n }\n \/\/ Prepend the patch library URI to form a unique script URI for the patch.\n strings.SetAt(2, patch_file_uri);\n patch_file_uri = String::ConcatAll(strings);\n script = Script::New(patch_file_uri, source, RawScript::kPatchTag);\n error = lib.Patch(script);\n if (!error.IsNull()) {\n return error.raw();\n }\n }\n return Error::null();\n}\n\n\nRawError* Bootstrap::LoadandCompileScripts() {\n Thread* thread = Thread::Current();\n Isolate* isolate = thread->isolate();\n Zone* zone = thread->zone();\n String& uri = String::Handle(zone);\n String& patch_uri = String::Handle(zone);\n String& source = String::Handle(zone);\n Script& script = Script::Handle(zone);\n Library& lib = Library::Handle(zone);\n Error& error = Error::Handle(zone);\n Dart_LibraryTagHandler saved_tag_handler = isolate->library_tag_handler();\n\n \/\/ Set the library tag handler for the isolate to the bootstrap\n \/\/ library tag handler so that we can load all the bootstrap libraries.\n isolate->set_library_tag_handler(BootstrapLibraryTagHandler);\n\n HANDLESCOPE(thread);\n\n \/\/ Create library objects for all the bootstrap libraries.\n for (intptr_t i = 0;\n bootstrap_libraries[i].index_ != ObjectStore::kNone;\n ++i) {\n#ifdef PRODUCT\n if (bootstrap_libraries[i].index_ == ObjectStore::kMirrors) {\n continue;\n }\n#endif \/\/ !PRODUCT\n uri = Symbols::New(bootstrap_libraries[i].uri_);\n lib = Library::LookupLibrary(uri);\n if (lib.IsNull()) {\n lib = Library::NewLibraryHelper(uri, false);\n lib.SetLoadRequested();\n lib.Register();\n }\n isolate->object_store()->set_bootstrap_library(\n bootstrap_libraries[i].index_, lib);\n }\n\n \/\/ Load, compile and patch bootstrap libraries.\n for (intptr_t i = 0;\n bootstrap_libraries[i].index_ != ObjectStore::kNone;\n ++i) {\n#ifdef PRODUCT\n if (bootstrap_libraries[i].index_ == ObjectStore::kMirrors) {\n continue;\n }\n#endif \/\/ PRODUCT\n uri = Symbols::New(bootstrap_libraries[i].uri_);\n lib = Library::LookupLibrary(uri);\n ASSERT(!lib.IsNull());\n source = GetLibrarySource(lib, uri, false);\n if (source.IsNull()) {\n const String& message = String::Handle(\n String::NewFormatted(\"Unable to find dart source for %s\",\n uri.ToCString()));\n error ^= ApiError::New(message);\n break;\n }\n script = Script::New(uri, source, RawScript::kLibraryTag);\n error = Compile(lib, script);\n if (!error.IsNull()) {\n break;\n }\n \/\/ If a patch exists, load and patch the script.\n if (bootstrap_libraries[i].patch_paths_ != NULL) {\n patch_uri = Symbols::New(bootstrap_libraries[i].patch_uri_);\n error = LoadPatchFiles(zone,\n lib,\n patch_uri,\n bootstrap_libraries[i].patch_paths_);\n if (!error.IsNull()) {\n break;\n }\n }\n }\n if (error.IsNull()) {\n SetupNativeResolver();\n ClassFinalizer::ProcessPendingClasses();\n\n \/\/ Eagerly compile the _Closure class as it is the class of all closure\n \/\/ instances. This allows us to just finalize function types\n \/\/ without going through the hoops of trying to compile their scope class.\n const Class& cls =\n Class::Handle(zone, isolate->object_store()->closure_class());\n Compiler::CompileClass(cls);\n }\n\n \/\/ Restore the library tag handler for the isolate.\n isolate->set_library_tag_handler(saved_tag_handler);\n\n return error.raw();\n}\n\n} \/\/ namespace dart\n<commit_msg>Eagerly finalize bool class, before bool constants are used in the compiler.<commit_after>\/\/ Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/bootstrap.h\"\n\n#include \"include\/dart_api.h\"\n\n#include \"vm\/bootstrap_natives.h\"\n#include \"vm\/class_finalizer.h\"\n#include \"vm\/compiler.h\"\n#include \"vm\/dart_api_impl.h\"\n#include \"vm\/object.h\"\n#include \"vm\/object_store.h\"\n#include \"vm\/symbols.h\"\n\nnamespace dart {\n\n#define INIT_LIBRARY(index, name, source, patch) \\\n { index, \\\n \"dart:\"#name, source, \\\n \"dart:\"#name\"-patch\", patch } \\\n\ntypedef struct {\n ObjectStore::BootstrapLibraryId index_;\n const char* uri_;\n const char** source_paths_;\n const char* patch_uri_;\n const char** patch_paths_;\n} bootstrap_lib_props;\n\n\nenum {\n kPathsUriOffset = 0,\n kPathsFileOffset = 1,\n kPathsSourceOffset = 2,\n kPathsEntryLength = 3\n};\n\n\nstatic bootstrap_lib_props bootstrap_libraries[] = {\n INIT_LIBRARY(ObjectStore::kCore,\n core,\n Bootstrap::core_source_paths_,\n Bootstrap::core_patch_paths_),\n INIT_LIBRARY(ObjectStore::kAsync,\n async,\n Bootstrap::async_source_paths_,\n Bootstrap::async_patch_paths_),\n INIT_LIBRARY(ObjectStore::kConvert,\n convert,\n Bootstrap::convert_source_paths_,\n Bootstrap::convert_patch_paths_),\n INIT_LIBRARY(ObjectStore::kCollection,\n collection,\n Bootstrap::collection_source_paths_,\n Bootstrap::collection_patch_paths_),\n INIT_LIBRARY(ObjectStore::kDeveloper,\n developer,\n Bootstrap::developer_source_paths_,\n Bootstrap::developer_patch_paths_),\n INIT_LIBRARY(ObjectStore::kInternal,\n _internal,\n Bootstrap::_internal_source_paths_,\n Bootstrap::_internal_patch_paths_),\n INIT_LIBRARY(ObjectStore::kIsolate,\n isolate,\n Bootstrap::isolate_source_paths_,\n Bootstrap::isolate_patch_paths_),\n INIT_LIBRARY(ObjectStore::kMath,\n math,\n Bootstrap::math_source_paths_,\n Bootstrap::math_patch_paths_),\n INIT_LIBRARY(ObjectStore::kMirrors,\n mirrors,\n Bootstrap::mirrors_source_paths_,\n Bootstrap::mirrors_patch_paths_),\n INIT_LIBRARY(ObjectStore::kProfiler,\n profiler,\n Bootstrap::profiler_source_paths_,\n NULL),\n INIT_LIBRARY(ObjectStore::kTypedData,\n typed_data,\n Bootstrap::typed_data_source_paths_,\n Bootstrap::typed_data_patch_paths_),\n INIT_LIBRARY(ObjectStore::kVMService,\n _vmservice,\n Bootstrap::_vmservice_source_paths_,\n Bootstrap::_vmservice_patch_paths_),\n { ObjectStore::kNone, NULL, NULL, NULL, NULL }\n};\n\n\nstatic RawString* GetLibrarySource(const Library& lib,\n const String& uri,\n bool patch) {\n \/\/ First check if this is a valid bootstrap library and find it's index\n \/\/ in the 'bootstrap_libraries' table above.\n intptr_t index;\n const String& lib_uri = String::Handle(lib.url());\n for (index = 0;\n bootstrap_libraries[index].index_ != ObjectStore::kNone;\n ++index) {\n if (lib_uri.Equals(bootstrap_libraries[index].uri_)) {\n break;\n }\n }\n if (bootstrap_libraries[index].index_ == ObjectStore::kNone) {\n return String::null(); \/\/ Library is not a bootstrap library.\n }\n\n \/\/ Try to read the source using the path specified for the uri.\n const char** source_paths = patch ?\n bootstrap_libraries[index].patch_paths_ :\n bootstrap_libraries[index].source_paths_;\n if (source_paths == NULL) {\n return String::null(); \/\/ No path mapping information exists for library.\n }\n const char* source_path = NULL;\n const char* source_data = NULL;\n for (intptr_t i = 0; source_paths[i] != NULL; i += kPathsEntryLength) {\n if (uri.Equals(source_paths[i + kPathsUriOffset])) {\n source_path = source_paths[i + kPathsFileOffset];\n source_data = source_paths[i + kPathsSourceOffset];\n break;\n }\n }\n if ((source_path == NULL) && (source_data == NULL)) {\n return String::null(); \/\/ Uri does not exist in path mapping information.\n }\n\n const uint8_t* utf8_array = NULL;\n intptr_t file_length = -1;\n\n Dart_FileOpenCallback file_open = Isolate::file_open_callback();\n Dart_FileReadCallback file_read = Isolate::file_read_callback();\n Dart_FileCloseCallback file_close = Isolate::file_close_callback();\n if ((file_open != NULL) && (file_read != NULL) && (file_close != NULL)) {\n \/\/ Try to open and read the file.\n void* stream = (*file_open)(source_path, false);\n if (stream != NULL) {\n (*file_read)(&utf8_array, &file_length, stream);\n (*file_close)(stream);\n }\n }\n if (file_length == -1) {\n if (source_data != NULL) {\n file_length = strlen(source_data);\n utf8_array = reinterpret_cast<const uint8_t*>(source_data);\n } else {\n return String::null();\n }\n }\n ASSERT(utf8_array != NULL);\n ASSERT(file_length >= 0);\n return String::FromUTF8(utf8_array, file_length);\n}\n\n\nstatic RawError* Compile(const Library& library, const Script& script) {\n bool update_lib_status = (script.kind() == RawScript::kScriptTag ||\n script.kind() == RawScript::kLibraryTag);\n if (update_lib_status) {\n library.SetLoadInProgress();\n }\n const Error& error = Error::Handle(Compiler::Compile(library, script));\n if (update_lib_status) {\n if (error.IsNull()) {\n library.SetLoaded();\n } else {\n \/\/ Compilation errors are not Dart instances, so just mark the library\n \/\/ as having failed to load without providing an error instance.\n library.SetLoadError(Object::null_instance());\n }\n }\n return error.raw();\n}\n\n\nstatic Dart_Handle LoadPartSource(Thread* thread,\n const Library& lib,\n const String& uri) {\n Zone* zone = thread->zone();\n const String& part_source = String::Handle(\n zone, GetLibrarySource(lib, uri, false));\n const String& lib_uri = String::Handle(zone, lib.url());\n if (part_source.IsNull()) {\n return Api::NewError(\"Unable to read part file '%s' of library '%s'\",\n uri.ToCString(), lib_uri.ToCString());\n }\n\n \/\/ Prepend the library URI to form a unique script URI for the part.\n const Array& strings = Array::Handle(zone, Array::New(3));\n strings.SetAt(0, lib_uri);\n strings.SetAt(1, Symbols::Slash());\n strings.SetAt(2, uri);\n const String& part_uri = String::Handle(zone, String::ConcatAll(strings));\n\n \/\/ Create a script object and compile the part.\n const Script& part_script = Script::Handle(\n zone, Script::New(part_uri, part_source, RawScript::kSourceTag));\n const Error& error = Error::Handle(zone, Compile(lib, part_script));\n return Api::NewHandle(thread, error.raw());\n}\n\n\nstatic Dart_Handle BootstrapLibraryTagHandler(Dart_LibraryTag tag,\n Dart_Handle library,\n Dart_Handle uri) {\n Thread* thread = Thread::Current();\n Zone* zone = thread->zone();\n \/\/ This handler calls into the VM directly and does not use the Dart\n \/\/ API so we transition back to VM.\n TransitionNativeToVM transition(thread);\n if (!Dart_IsLibrary(library)) {\n return Api::NewError(\"not a library\");\n }\n if (!Dart_IsString(uri)) {\n return Api::NewError(\"uri is not a string\");\n }\n if (tag == Dart_kCanonicalizeUrl) {\n \/\/ In the bootstrap loader we do not try and do any canonicalization.\n return uri;\n }\n const String& uri_str = Api::UnwrapStringHandle(zone, uri);\n ASSERT(!uri_str.IsNull());\n if (tag == Dart_kImportTag) {\n \/\/ We expect the core bootstrap libraries to only import other\n \/\/ core bootstrap libraries.\n \/\/ We have precreated all the bootstrap library objects hence\n \/\/ we do not expect to be called back with the tag set to kImportTag.\n \/\/ The bootstrap process explicitly loads all the libraries one by one.\n return Api::NewError(\"Invalid import of '%s' in a bootstrap library\",\n uri_str.ToCString());\n }\n ASSERT(tag == Dart_kSourceTag);\n const Library& lib = Api::UnwrapLibraryHandle(zone, library);\n ASSERT(!lib.IsNull());\n return LoadPartSource(thread, lib, uri_str);\n}\n\n\nstatic RawError* LoadPatchFiles(Zone* zone,\n const Library& lib,\n const String& patch_uri,\n const char** patch_files) {\n String& patch_file_uri = String::Handle(zone);\n String& source = String::Handle(zone);\n Script& script = Script::Handle(zone);\n Error& error = Error::Handle(zone);\n const Array& strings = Array::Handle(zone, Array::New(3));\n strings.SetAt(0, patch_uri);\n strings.SetAt(1, Symbols::Slash());\n for (intptr_t j = 0; patch_files[j] != NULL; j += kPathsEntryLength) {\n patch_file_uri = String::New(patch_files[j + kPathsUriOffset]);\n source = GetLibrarySource(lib, patch_file_uri, true);\n if (source.IsNull()) {\n const String& message = String::Handle(\n String::NewFormatted(\"Unable to find dart patch source for %s\",\n patch_file_uri.ToCString()));\n return ApiError::New(message);\n }\n \/\/ Prepend the patch library URI to form a unique script URI for the patch.\n strings.SetAt(2, patch_file_uri);\n patch_file_uri = String::ConcatAll(strings);\n script = Script::New(patch_file_uri, source, RawScript::kPatchTag);\n error = lib.Patch(script);\n if (!error.IsNull()) {\n return error.raw();\n }\n }\n return Error::null();\n}\n\n\nRawError* Bootstrap::LoadandCompileScripts() {\n Thread* thread = Thread::Current();\n Isolate* isolate = thread->isolate();\n Zone* zone = thread->zone();\n String& uri = String::Handle(zone);\n String& patch_uri = String::Handle(zone);\n String& source = String::Handle(zone);\n Script& script = Script::Handle(zone);\n Library& lib = Library::Handle(zone);\n Error& error = Error::Handle(zone);\n Dart_LibraryTagHandler saved_tag_handler = isolate->library_tag_handler();\n\n \/\/ Set the library tag handler for the isolate to the bootstrap\n \/\/ library tag handler so that we can load all the bootstrap libraries.\n isolate->set_library_tag_handler(BootstrapLibraryTagHandler);\n\n HANDLESCOPE(thread);\n\n \/\/ Create library objects for all the bootstrap libraries.\n for (intptr_t i = 0;\n bootstrap_libraries[i].index_ != ObjectStore::kNone;\n ++i) {\n#ifdef PRODUCT\n if (bootstrap_libraries[i].index_ == ObjectStore::kMirrors) {\n continue;\n }\n#endif \/\/ !PRODUCT\n uri = Symbols::New(bootstrap_libraries[i].uri_);\n lib = Library::LookupLibrary(uri);\n if (lib.IsNull()) {\n lib = Library::NewLibraryHelper(uri, false);\n lib.SetLoadRequested();\n lib.Register();\n }\n isolate->object_store()->set_bootstrap_library(\n bootstrap_libraries[i].index_, lib);\n }\n\n \/\/ Load, compile and patch bootstrap libraries.\n for (intptr_t i = 0;\n bootstrap_libraries[i].index_ != ObjectStore::kNone;\n ++i) {\n#ifdef PRODUCT\n if (bootstrap_libraries[i].index_ == ObjectStore::kMirrors) {\n continue;\n }\n#endif \/\/ PRODUCT\n uri = Symbols::New(bootstrap_libraries[i].uri_);\n lib = Library::LookupLibrary(uri);\n ASSERT(!lib.IsNull());\n source = GetLibrarySource(lib, uri, false);\n if (source.IsNull()) {\n const String& message = String::Handle(\n String::NewFormatted(\"Unable to find dart source for %s\",\n uri.ToCString()));\n error ^= ApiError::New(message);\n break;\n }\n script = Script::New(uri, source, RawScript::kLibraryTag);\n error = Compile(lib, script);\n if (!error.IsNull()) {\n break;\n }\n \/\/ If a patch exists, load and patch the script.\n if (bootstrap_libraries[i].patch_paths_ != NULL) {\n patch_uri = Symbols::New(bootstrap_libraries[i].patch_uri_);\n error = LoadPatchFiles(zone,\n lib,\n patch_uri,\n bootstrap_libraries[i].patch_paths_);\n if (!error.IsNull()) {\n break;\n }\n }\n }\n if (error.IsNull()) {\n SetupNativeResolver();\n ClassFinalizer::ProcessPendingClasses();\n\n \/\/ Eagerly compile the _Closure class as it is the class of all closure\n \/\/ instances. This allows us to just finalize function types\n \/\/ without going through the hoops of trying to compile their scope class.\n Class& cls =\n Class::Handle(zone, isolate->object_store()->closure_class());\n Compiler::CompileClass(cls);\n \/\/ Eagerly compile Bool class, bool constants are used from within compiler.\n cls = isolate->object_store()->bool_class();\n Compiler::CompileClass(cls);\n }\n\n \/\/ Restore the library tag handler for the isolate.\n isolate->set_library_tag_handler(saved_tag_handler);\n\n return error.raw();\n}\n\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: KServices.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-01-19 15:31:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"KDriver.hxx\"\n\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nusing namespace connectivity::kab;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pTemp\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ The following C Api must be provided!\n\/\/ It consists in three functions that must be exported by the module\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString::createFromAscii(\"\/\");\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString::createFromAscii(\"\/UNO\/SERVICES\");\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"KAB::component_writeInfo : could not create a registry key !\");\n\n for (sal_uInt32 i=0; i<Services.getLength(); ++i)\n xNewKey->createKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment **ppEnv\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void* pServiceManager,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n REGISTER_PROVIDER(\n KabDriver::getImplementationName_Static(),\n KabDriver::getSupportedServiceNames_Static(), xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"KAB::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void* pRegistryKey)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n ProviderRequest aReq(pServiceManager,pImplementationName);\n\n aReq.CREATE_PROVIDER(\n KabDriver::getImplementationName_Static(),\n KabDriver::getSupportedServiceNames_Static(),\n &KabDriver::Create,\n ::cppu::createSingleFactory)\n ;\n\n if (aReq.xRet.is())\n aReq.xRet->acquire();\n\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.3.4); FILE MERGED 2006\/01\/30 14:18:54 sb 1.3.4.1: #i53898# Made code warning-free.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: KServices.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 01:39:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"KDriver.hxx\"\n\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nusing namespace connectivity::kab;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pTemp\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ The following C Api must be provided!\n\/\/ It consists in three functions that must be exported by the module\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString::createFromAscii(\"\/\");\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString::createFromAscii(\"\/UNO\/SERVICES\");\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"KAB::component_writeInfo : could not create a registry key !\");\n\n for (sal_Int32 i=0; i<Services.getLength(); ++i)\n xNewKey->createKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment **\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void*,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n REGISTER_PROVIDER(\n KabDriver::getImplementationName_Static(),\n KabDriver::getSupportedServiceNames_Static(), xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"KAB::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void*)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n ProviderRequest aReq(pServiceManager,pImplementationName);\n\n aReq.CREATE_PROVIDER(\n KabDriver::getImplementationName_Static(),\n KabDriver::getSupportedServiceNames_Static(),\n &KabDriver::Create,\n ::cppu::createSingleFactory)\n ;\n\n if (aReq.xRet.is())\n aReq.xRet->acquire();\n\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>refactor indescribable wall of code into reusable hunks<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>wrap vcl::Window* in VclPtr<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>probable intent is the other way around<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_capturer.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n LOG(LS_WARNING) << \"ViEBase released too many times.\";\n return -1;\n }\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {}\n\nViEBaseImpl::~ViEBaseImpl() {}\n\nint ViEBaseImpl::Init() {\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n LOG_F(LS_INFO) << \"SetVoiceEngine\";\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,\n CpuOveruseObserver* observer) {\n LOG_F(LS_INFO) << \"RegisterCpuOveruseObserver on channel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n assert(capturer);\n capturer->RegisterCpuOveruseObserver(observer);\n }\n\n shared_data_.overuse_observers()->insert(\n std::pair<int, CpuOveruseObserver*>(video_channel, observer));\n return 0;\n}\n\nint ViEBaseImpl::SetCpuOveruseOptions(int video_channel,\n const CpuOveruseOptions& options) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->SetCpuOveruseOptions(options);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::CpuOveruseMeasures(int video_channel,\n int* capture_jitter_ms,\n int* avg_encode_time_ms,\n int* encode_usage_percent,\n int* capture_queue_delay_ms_per_s) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->CpuOveruseMeasures(capture_jitter_ms,\n avg_encode_time_ms,\n encode_usage_percent,\n capture_queue_delay_ms_per_s);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n return CreateChannel(video_channel, static_cast<const Config*>(NULL));\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n const Config* config) {\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n config) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG(LS_INFO) << \"Video channel created: \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n LOG(LS_INFO) << \"Channel deleted \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n LOG_F(LS_INFO) << \"ConnectAudioChannel, video channel \" << video_channel\n << \", audio channel \" << audio_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n LOG_F(LS_INFO) << \"DisconnectAudioChannel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StartSend: \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n LOG_F(LS_ERROR) << \"Can't start send on a receive only channel.\";\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n LOG_F(LS_ERROR) << \"Could not start sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StopSend \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n LOG_F(LS_ERROR) << \"Could not stop sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StartReceive \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StopReceive \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n assert(kViEVersionMaxMessageSize == 1024);\n if (!version) {\n shared_data_.SetLastError(kViEBaseInvalidArgument);\n return -1;\n }\n\n \/\/ Add WebRTC Version.\n std::stringstream version_stream;\n version_stream << \"VideoEngine 3.51.0\" << std::endl;\n\n \/\/ Add build info.\n version_stream << \"Build: \" << BUILDINFO << std::endl;\n\n int version_length = version_stream.tellp();\n assert(version_length < 1024);\n memcpy(version, version_stream.str().c_str(), version_length);\n version[version_length] = '\\0';\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel, bool sender) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n original_channel,\n sender) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG_F(LS_INFO) << \"VideoChannel created: \" << video_channel\n << \", base channel \" << original_channel\n << \", is send channel : \" << sender;\n return 0;\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Updated WebRTC version to 3.52 TBR=wu@webrtc.org<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_capturer.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n LOG(LS_WARNING) << \"ViEBase released too many times.\";\n return -1;\n }\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {}\n\nViEBaseImpl::~ViEBaseImpl() {}\n\nint ViEBaseImpl::Init() {\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n LOG_F(LS_INFO) << \"SetVoiceEngine\";\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::RegisterCpuOveruseObserver(int video_channel,\n CpuOveruseObserver* observer) {\n LOG_F(LS_INFO) << \"RegisterCpuOveruseObserver on channel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n assert(capturer);\n capturer->RegisterCpuOveruseObserver(observer);\n }\n\n shared_data_.overuse_observers()->insert(\n std::pair<int, CpuOveruseObserver*>(video_channel, observer));\n return 0;\n}\n\nint ViEBaseImpl::SetCpuOveruseOptions(int video_channel,\n const CpuOveruseOptions& options) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->SetCpuOveruseOptions(options);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::CpuOveruseMeasures(int video_channel,\n int* capture_jitter_ms,\n int* avg_encode_time_ms,\n int* encode_usage_percent,\n int* capture_queue_delay_ms_per_s) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder);\n\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n ViECapturer* capturer = is.Capture(provider->Id());\n if (capturer) {\n capturer->CpuOveruseMeasures(capture_jitter_ms,\n avg_encode_time_ms,\n encode_usage_percent,\n capture_queue_delay_ms_per_s);\n return 0;\n }\n }\n return -1;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n return CreateChannel(video_channel, static_cast<const Config*>(NULL));\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n const Config* config) {\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n config) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG(LS_INFO) << \"Video channel created: \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n LOG(LS_INFO) << \"Channel deleted \" << video_channel;\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n LOG_F(LS_INFO) << \"ConnectAudioChannel, video channel \" << video_channel\n << \", audio channel \" << audio_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n LOG_F(LS_INFO) << \"DisconnectAudioChannel \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StartSend: \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n LOG_F(LS_ERROR) << \"Can't start send on a receive only channel.\";\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n LOG_F(LS_ERROR) << \"Could not start sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n LOG_F(LS_INFO) << \"StopSend \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n LOG_F(LS_ERROR) << \"Could not stop sending \" << video_channel;\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StartReceive \" << video_channel;\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n LOG_F(LS_INFO) << \"StopReceive \" << video_channel;\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n assert(kViEVersionMaxMessageSize == 1024);\n if (!version) {\n shared_data_.SetLastError(kViEBaseInvalidArgument);\n return -1;\n }\n\n \/\/ Add WebRTC Version.\n std::stringstream version_stream;\n version_stream << \"VideoEngine 3.52.0\" << std::endl;\n\n \/\/ Add build info.\n version_stream << \"Build: \" << BUILDINFO << std::endl;\n\n int version_length = version_stream.tellp();\n assert(version_length < 1024);\n memcpy(version, version_stream.str().c_str(), version_length);\n version[version_length] = '\\0';\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel, bool sender) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n original_channel,\n sender) == -1) {\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n LOG_F(LS_INFO) << \"VideoChannel created: \" << video_channel\n << \", base channel \" << original_channel\n << \", is send channel : \" << sender;\n return 0;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(XPATHALLOCATOR_INCLUDE_GUARD_135792455)\n#define XPATHALLOCATOR_INCLUDE_GUARD_135792455\n\n\n\n\/\/ Base include file. Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <PlatformSupport\/ArenaAllocator.hpp>\n\n\n\n#include <XPath\/XPath.hpp>\n\n\n\nclass XALAN_XPATH_EXPORT XPathAllocator\n{\npublic:\n\n\ttypedef XPath\t\t\t\t\t\t\tobject_type;\n\n\ttypedef ArenaAllocator<object_type>\t\tArenaAllocatorType;\n\ttypedef ArenaAllocatorType::size_type\tsize_type;\n\n\t\/**\n\t * Construct an instance that will allocate blocks of the specified size.\n\t *\n\t * @param theBlockSize The block size.\n\t *\/\n\tXPathAllocator(size_type\ttheBlockCount);\n\n\t~XPathAllocator();\n\n\t\/**\n\t * Create an XPath object using the allocator.\n\t * \n\t * @return a pointer to an XPath\n\t *\/\n\tobject_type*\n\tcreate();\n\n\t\/**\n\t * Determine if an object is owned by the allocator...\n\t *\/\n\tbool\n\townsObject(const object_type*\ttheObject)\n\t{\n\t\treturn m_allocator.ownsObject(theObject);\n\t}\n\n\t\/**\n\t * Delete all XPath objects allocated.\t \n\t *\/\t\n\tvoid\n\treset();\n\n\t\/**\n\t * Get the number of objects in each block.\n\t *\n\t * @return The size of the block\n\t *\/\n\tsize_type\n\tgetBlockCount() const\n\t{\n\t\treturn m_allocator.getBlockCount();\n\t}\n\n\t\/**\n\t * Get the number of blocks currently allocated.\n\t *\n\t * @return The number of blocks.\n\t *\/\n\tsize_type\n\tgetBlockSize() const\n\t{\n\t\treturn m_allocator.getBlockSize();\n\t}\n\nprivate:\n\n\t\/\/ Not implemented...\n\tXPathAllocator(const XPathAllocator&);\n\n\tXPathAllocator&\n\toperator=(const XPathAllocator&);\n\n\t\/\/ Data members...\n\tArenaAllocatorType\tm_allocator;\n};\n\n\n\n#endif\t\/\/ XNUMBERALLOCATOR_INCLUDE_GUARD_135792455\n<commit_msg>Added #ifdef.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(XPATHALLOCATOR_INCLUDE_GUARD_135792455)\n#define XPATHALLOCATOR_INCLUDE_GUARD_135792455\n\n\n\n\/\/ Base include file. Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <PlatformSupport\/ArenaAllocator.hpp>\n\n\n\n#include <XPath\/XPath.hpp>\n\n\n\nclass XALAN_XPATH_EXPORT XPathAllocator\n{\npublic:\n\n\ttypedef XPath\t\t\t\t\t\t\tobject_type;\n\n#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)\n\ttypedef ArenaBlock<object_type>\t\t\tArenaBlockType;\n\n\ttypedef ArenaAllocator<object_type,\n\t\t\t\t\t\t ArenaBlockType>\tArenaAllocatorType;\n#else\n\ttypedef ArenaAllocator<object_type>\t\tArenaAllocatorType;\n#endif\n\n\ttypedef ArenaAllocatorType::size_type\tsize_type;\n\n\t\/**\n\t * Construct an instance that will allocate blocks of the specified size.\n\t *\n\t * @param theBlockSize The block size.\n\t *\/\n\tXPathAllocator(size_type\ttheBlockCount);\n\n\t~XPathAllocator();\n\n\t\/**\n\t * Create an XPath object using the allocator.\n\t * \n\t * @return a pointer to an XPath\n\t *\/\n\tobject_type*\n\tcreate();\n\n\t\/**\n\t * Determine if an object is owned by the allocator...\n\t *\/\n\tbool\n\townsObject(const object_type*\ttheObject)\n\t{\n\t\treturn m_allocator.ownsObject(theObject);\n\t}\n\n\t\/**\n\t * Delete all XPath objects allocated.\t \n\t *\/\t\n\tvoid\n\treset();\n\n\t\/**\n\t * Get the number of objects in each block.\n\t *\n\t * @return The size of the block\n\t *\/\n\tsize_type\n\tgetBlockCount() const\n\t{\n\t\treturn m_allocator.getBlockCount();\n\t}\n\n\t\/**\n\t * Get the number of blocks currently allocated.\n\t *\n\t * @return The number of blocks.\n\t *\/\n\tsize_type\n\tgetBlockSize() const\n\t{\n\t\treturn m_allocator.getBlockSize();\n\t}\n\nprivate:\n\n\t\/\/ Not implemented...\n\tXPathAllocator(const XPathAllocator&);\n\n\tXPathAllocator&\n\toperator=(const XPathAllocator&);\n\n\t\/\/ Data members...\n\tArenaAllocatorType\tm_allocator;\n};\n\n\n\n#endif\t\/\/ XNUMBERALLOCATOR_INCLUDE_GUARD_135792455\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant \n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n\n#include <osquery\/core.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n#include <osquery\/sql.h>\n\nnamespace pt = boost::property_tree;\n\nnamespace osquery {\nnamespace tables {\n\nconst std::map<std::string, std::string> kAppsInfoPlistTopLevelStringKeys = {\n {\"CFBundleExecutable\", \"bundle_executable\"},\n {\"CFBundleIdentifier\", \"bundle_identifier\"},\n {\"CFBundleName\", \"bundle_name\"},\n {\"CFBundleShortVersionString\", \"bundle_short_version\"},\n {\"CFBundleVersion\", \"bundle_version\"},\n {\"CFBundlePackageType\", \"bundle_package_type\"},\n {\"CFBundleDevelopmentRegion\", \"development_region\"},\n {\"CFBundleDisplayName\", \"display_name\"},\n {\"CFBundleGetInfoString\", \"info_string\"},\n {\"DTCompiler\", \"compiler\"},\n {\"LSMinimumSystemVersion\", \"minimum_system_version\"},\n {\"LSApplicationCategoryType\", \"category\"},\n {\"NSAppleScriptEnabled\", \"applescript_enabled\"},\n {\"NSHumanReadableCopyright\", \"copyright\"},\n};\n\nconst std::vector<std::string> kHomeDirSearchPaths = {\n \"Applications\", \"Desktop\", \"Downloads\",\n};\n\nstd::vector<std::string> getSystemApplications() {\n std::vector<std::string> results;\n std::vector<std::string> sys_apps;\n auto status = osquery::listFilesInDirectory(\"\/Applications\", sys_apps);\n if (status.ok()) {\n for (const auto& app_path : sys_apps) {\n std::string plist_path = app_path + \"\/Contents\/Info.plist\";\n if (boost::filesystem::exists(plist_path)) {\n results.push_back(plist_path);\n }\n }\n } else {\n VLOG(1) << \"Error listing \/Applications: \" << status.toString();\n }\n return results;\n}\n\nstd::vector<std::string> getUserApplications(const std::string& home_dir) {\n std::vector<std::string> results;\n for (const auto& dir_to_check : kHomeDirSearchPaths) {\n boost::filesystem::path apps_path = home_dir;\n apps_path \/= dir_to_check;\n\n std::vector<std::string> user_apps;\n auto status = osquery::listFilesInDirectory(apps_path, user_apps);\n if (status.ok()) {\n for (const auto& user_app : user_apps) {\n std::string plist_path = user_app + \"\/Contents\/Info.plist\";\n if (boost::filesystem::exists(plist_path)) {\n results.push_back(plist_path);\n }\n }\n } else {\n VLOG(1) << \"Error listing \" << apps_path << \": \" << status.toString();\n }\n }\n return results;\n}\n\nstd::string getNameFromInfoPlistPath(const std::string& path) {\n boost::filesystem::path full = path;\n return full.parent_path().parent_path().filename().string();\n}\n\nstd::string getPathFromInfoPlistPath(const std::string& path) {\n boost::filesystem::path full = path;\n return full.parent_path().parent_path().string();\n}\n\nRow parseInfoPlist(const std::string& path, const pt::ptree& tree) {\n Row r;\n\n boost::filesystem::path full = path;\n r[\"name\"] = getNameFromInfoPlistPath(path);\n r[\"path\"] = getPathFromInfoPlistPath(path);\n for (const auto& it : kAppsInfoPlistTopLevelStringKeys) {\n try {\n r[it.second] = tree.get<std::string>(it.first);\n } catch (const pt::ptree_error& e) {\n VLOG(1) << \"Error retrieving \" << it.first << \" from \" << path << \": \"\n << e.what();\n r[it.second] = \"\";\n }\n }\n return r;\n}\n\nQueryData genApps(QueryContext& context) {\n QueryData results;\n pt::ptree tree;\n\n \/\/ Enumerate and parse applications in \/ (system applications).\n for (const auto& path : getSystemApplications()) {\n if (osquery::parsePlist(path, tree).ok()) {\n results.push_back(parseInfoPlist(path, tree));\n } else {\n VLOG(1) << \"Error parsing system applications: \" << path;\n }\n }\n\n auto users = SQL::selectAllFrom(\"users\");\n\n \/\/ Enumerate apps for each user (several paths).\n for (const auto& user : users) {\n for (const auto& path : getUserApplications(user.at(\"directory\"))) {\n if (osquery::parsePlist(path, tree).ok()) {\n Row r = parseInfoPlist(path, tree);\n results.push_back(r);\n } else {\n VLOG(1) << \"Error parsing user applications: \" << path;\n }\n }\n }\n\n return results;\n}\n}\n}\n<commit_msg>[Fix #733] Use directories instead of files in apps<commit_after>\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant \n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n\n#include <osquery\/core.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n#include <osquery\/sql.h>\n\nnamespace pt = boost::property_tree;\n\nnamespace osquery {\nnamespace tables {\n\nconst std::map<std::string, std::string> kAppsInfoPlistTopLevelStringKeys = {\n {\"CFBundleExecutable\", \"bundle_executable\"},\n {\"CFBundleIdentifier\", \"bundle_identifier\"},\n {\"CFBundleName\", \"bundle_name\"},\n {\"CFBundleShortVersionString\", \"bundle_short_version\"},\n {\"CFBundleVersion\", \"bundle_version\"},\n {\"CFBundlePackageType\", \"bundle_package_type\"},\n {\"CFBundleDevelopmentRegion\", \"development_region\"},\n {\"CFBundleDisplayName\", \"display_name\"},\n {\"CFBundleGetInfoString\", \"info_string\"},\n {\"DTCompiler\", \"compiler\"},\n {\"LSMinimumSystemVersion\", \"minimum_system_version\"},\n {\"LSApplicationCategoryType\", \"category\"},\n {\"NSAppleScriptEnabled\", \"applescript_enabled\"},\n {\"NSHumanReadableCopyright\", \"copyright\"},\n};\n\nconst std::vector<std::string> kHomeDirSearchPaths = {\n \"Applications\", \"Desktop\", \"Downloads\",\n};\n\nstd::vector<std::string> getSystemApplications() {\n std::vector<std::string> results;\n std::vector<std::string> sys_apps;\n auto status = osquery::listDirectoriesInDirectory(\"\/Applications\", sys_apps);\n\n if (status.ok()) {\n for (const auto& app_path : sys_apps) {\n std::string plist_path = app_path + \"\/Contents\/Info.plist\";\n if (boost::filesystem::exists(plist_path)) {\n results.push_back(plist_path);\n }\n }\n } else {\n VLOG(1) << \"Error listing \/Applications: \" << status.toString();\n }\n return results;\n}\n\nstd::vector<std::string> getUserApplications(const std::string& home_dir) {\n std::vector<std::string> results;\n for (const auto& dir_to_check : kHomeDirSearchPaths) {\n boost::filesystem::path apps_path = home_dir;\n apps_path \/= dir_to_check;\n\n std::vector<std::string> user_apps;\n auto status = osquery::listDirectoriesInDirectory(apps_path, user_apps);\n if (status.ok()) {\n for (const auto& user_app : user_apps) {\n std::string plist_path = user_app + \"\/Contents\/Info.plist\";\n if (boost::filesystem::exists(plist_path)) {\n results.push_back(plist_path);\n }\n }\n } else {\n VLOG(1) << \"Error listing \" << apps_path << \": \" << status.toString();\n }\n }\n return results;\n}\n\nstd::string getNameFromInfoPlistPath(const std::string& path) {\n boost::filesystem::path full = path;\n return full.parent_path().parent_path().filename().string();\n}\n\nstd::string getPathFromInfoPlistPath(const std::string& path) {\n boost::filesystem::path full = path;\n return full.parent_path().parent_path().string();\n}\n\nRow parseInfoPlist(const std::string& path, const pt::ptree& tree) {\n Row r;\n\n boost::filesystem::path full = path;\n r[\"name\"] = getNameFromInfoPlistPath(path);\n r[\"path\"] = getPathFromInfoPlistPath(path);\n for (const auto& it : kAppsInfoPlistTopLevelStringKeys) {\n try {\n r[it.second] = tree.get<std::string>(it.first);\n } catch (const pt::ptree_error& e) {\n VLOG(1) << \"Error retrieving \" << it.first << \" from \" << path << \": \"\n << e.what();\n r[it.second] = \"\";\n }\n }\n return r;\n}\n\nQueryData genApps(QueryContext& context) {\n QueryData results;\n pt::ptree tree;\n\n \/\/ Enumerate and parse applications in \/ (system applications).\n for (const auto& path : getSystemApplications()) {\n if (osquery::parsePlist(path, tree).ok()) {\n results.push_back(parseInfoPlist(path, tree));\n } else {\n VLOG(1) << \"Error parsing system applications: \" << path;\n }\n }\n\n auto users = SQL::selectAllFrom(\"users\");\n\n \/\/ Enumerate apps for each user (several paths).\n for (const auto& user : users) {\n for (const auto& path : getUserApplications(user.at(\"directory\"))) {\n if (osquery::parsePlist(path, tree).ok()) {\n Row r = parseInfoPlist(path, tree);\n results.push_back(r);\n } else {\n VLOG(1) << \"Error parsing user applications: \" << path;\n }\n }\n }\n\n return results;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.\n* See file LICENSE for terms.\n*\/\n\n#include \"ucp_test.h\"\n\n#include <ucs\/gtest\/test_helpers.h>\nextern \"C\" {\n#include <ucs\/arch\/atomic.h>\n}\n\n\nconst ucs::ptr_vector<ucp_test::entity>& ucp_test::entities() const {\n return m_entities;\n}\n\nvoid ucp_test::cleanup() {\n m_entities.clear();\n}\n\nucp_test::entity* ucp_test::create_entity() {\n entity *e = new entity(*this);\n m_entities.push_back(e);\n return e;\n}\n\nvoid ucp_test::get_params(ucp_params_t& params) const {\n params.features = 0;\n params.request_size = 0;\n params.request_init = NULL;\n params.request_cleanup = NULL;\n}\n\nvoid ucp_test::progress() const {\n for (ucs::ptr_vector<entity>::const_iterator iter = entities().begin();\n iter != entities().end(); ++iter)\n {\n (*iter)->progress();\n }\n}\n\nvoid ucp_test::short_progress_loop() const {\n for (unsigned i = 0; i < 100; ++i) {\n progress();\n usleep(100);\n }\n}\n\nucp_test::entity::entity(const ucp_test& test) : m_test(test), m_inprogress(0) {\n ucs::handle<ucp_config_t*> config;\n\n UCS_TEST_CREATE_HANDLE(ucp_config_t*, config, ucp_config_release,\n ucp_config_read, NULL, NULL);\n\n ucp_params_t params;\n test.get_params(params);\n\n UCS_TEST_CREATE_HANDLE(ucp_context_h, m_ucph, ucp_cleanup, ucp_init,\n ¶ms, config);\n\n UCS_TEST_CREATE_HANDLE(ucp_worker_h, m_worker, ucp_worker_destroy,\n ucp_worker_create, m_ucph, UCS_THREAD_MODE_MULTI);\n\n ucp_worker_progress_register(m_worker, progress_cb, this);\n}\n\nucp_test::entity::~entity() {\n ucp_worker_progress_unregister(m_worker, progress_cb, this);\n}\n\nvoid ucp_test::entity::connect(const ucp_test::entity* other) {\n ucs_status_t status;\n ucp_address_t *address;\n size_t address_length;\n\n status = ucp_worker_get_address(other->worker(), &address, &address_length);\n ASSERT_UCS_OK(status);\n\n ucp_ep_h ep;\n status = ucp_ep_create(m_worker, address, &ep);\n if (status == UCS_ERR_UNREACHABLE) {\n UCS_TEST_SKIP_R(\"could not find a valid transport\");\n }\n\n ASSERT_UCS_OK(status);\n m_ep.reset(ep, ucp_ep_destroy);\n\n ucp_worker_release_address(other->worker(), address);\n}\n\nvoid ucp_test::entity::flush() const {\n ucs_status_t status = ucp_worker_flush(worker());\n ASSERT_UCS_OK(status);\n}\n\nvoid ucp_test::entity::disconnect() {\n m_ep.reset();\n}\n\nucp_ep_h ucp_test::entity::ep() const {\n return m_ep;\n}\n\nucp_worker_h ucp_test::entity::worker() const {\n return m_worker;\n}\n\nucp_context_h ucp_test::entity::ucph() const {\n return m_ucph;\n}\n\nvoid ucp_test::entity::progress()\n{\n if (ucs_atomic_cswap32(&m_inprogress, 0, 1) != 0) {\n return;\n }\n\n ucp_worker_progress(m_worker);\n m_inprogress = 0;\n}\n\nvoid ucp_test::entity::progress_cb(void *arg)\n{\n entity *e = reinterpret_cast<entity*>(arg);\n e->progress_test();\n}\n\nvoid ucp_test::entity::progress_test()\n{\n if (ucs_atomic_cswap32(&m_inprogress, 0, 1) != 0) {\n return;\n }\n m_test.progress();\n m_inprogress = 0;\n}\n<commit_msg>TEST: Disconnect entities before destroying them, to ensure flush.<commit_after>\/**\n* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.\n* See file LICENSE for terms.\n*\/\n\n#include \"ucp_test.h\"\n\n#include <ucs\/gtest\/test_helpers.h>\nextern \"C\" {\n#include <ucs\/arch\/atomic.h>\n}\n\n\nconst ucs::ptr_vector<ucp_test::entity>& ucp_test::entities() const {\n return m_entities;\n}\n\nvoid ucp_test::cleanup() {\n \/* disconnect before destroying the entities *\/\n for (ucs::ptr_vector<entity>::const_iterator iter = entities().begin();\n iter != entities().end(); ++iter)\n {\n (*iter)->disconnect();\n }\n m_entities.clear();\n}\n\nucp_test::entity* ucp_test::create_entity() {\n entity *e = new entity(*this);\n m_entities.push_back(e);\n return e;\n}\n\nvoid ucp_test::get_params(ucp_params_t& params) const {\n params.features = 0;\n params.request_size = 0;\n params.request_init = NULL;\n params.request_cleanup = NULL;\n}\n\nvoid ucp_test::progress() const {\n for (ucs::ptr_vector<entity>::const_iterator iter = entities().begin();\n iter != entities().end(); ++iter)\n {\n (*iter)->progress();\n }\n}\n\nvoid ucp_test::short_progress_loop() const {\n for (unsigned i = 0; i < 100; ++i) {\n progress();\n usleep(100);\n }\n}\n\nucp_test::entity::entity(const ucp_test& test) : m_test(test), m_inprogress(0) {\n ucs::handle<ucp_config_t*> config;\n\n UCS_TEST_CREATE_HANDLE(ucp_config_t*, config, ucp_config_release,\n ucp_config_read, NULL, NULL);\n\n ucp_params_t params;\n test.get_params(params);\n\n UCS_TEST_CREATE_HANDLE(ucp_context_h, m_ucph, ucp_cleanup, ucp_init,\n ¶ms, config);\n\n UCS_TEST_CREATE_HANDLE(ucp_worker_h, m_worker, ucp_worker_destroy,\n ucp_worker_create, m_ucph, UCS_THREAD_MODE_MULTI);\n\n ucp_worker_progress_register(m_worker, progress_cb, this);\n}\n\nucp_test::entity::~entity() {\n ucp_worker_progress_unregister(m_worker, progress_cb, this);\n}\n\nvoid ucp_test::entity::connect(const ucp_test::entity* other) {\n ucs_status_t status;\n ucp_address_t *address;\n size_t address_length;\n\n status = ucp_worker_get_address(other->worker(), &address, &address_length);\n ASSERT_UCS_OK(status);\n\n ucp_ep_h ep;\n status = ucp_ep_create(m_worker, address, &ep);\n if (status == UCS_ERR_UNREACHABLE) {\n UCS_TEST_SKIP_R(\"could not find a valid transport\");\n }\n\n ASSERT_UCS_OK(status);\n m_ep.reset(ep, ucp_ep_destroy);\n\n ucp_worker_release_address(other->worker(), address);\n}\n\nvoid ucp_test::entity::flush() const {\n ucs_status_t status = ucp_worker_flush(worker());\n ASSERT_UCS_OK(status);\n}\n\nvoid ucp_test::entity::disconnect() {\n m_ep.reset();\n}\n\nucp_ep_h ucp_test::entity::ep() const {\n return m_ep;\n}\n\nucp_worker_h ucp_test::entity::worker() const {\n return m_worker;\n}\n\nucp_context_h ucp_test::entity::ucph() const {\n return m_ucph;\n}\n\nvoid ucp_test::entity::progress()\n{\n if (ucs_atomic_cswap32(&m_inprogress, 0, 1) != 0) {\n return;\n }\n\n ucp_worker_progress(m_worker);\n m_inprogress = 0;\n}\n\nvoid ucp_test::entity::progress_cb(void *arg)\n{\n entity *e = reinterpret_cast<entity*>(arg);\n e->progress_test();\n}\n\nvoid ucp_test::entity::progress_test()\n{\n if (ucs_atomic_cswap32(&m_inprogress, 0, 1) != 0) {\n return;\n }\n m_test.progress();\n m_inprogress = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ByteGrabber.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: mtg $ $Date: 2001-05-28 12:52:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _BYTE_GRABBER_HXX_\n#include \"ByteGrabber.hxx\"\n#endif\n\nusing namespace ::com::sun::star;\n\n\/** ByteGrabber implements the >> operators on an XOutputStream. This is\n * potentially quite slow and may need to be optimised\n *\/\n\nByteGrabber::ByteGrabber(uno::Reference < io::XInputStream > xIstream)\n: xStream(xIstream)\n, xSeek (xIstream, uno::UNO_QUERY )\n{\n}\nByteGrabber::~ByteGrabber()\n{\n}\nvoid ByteGrabber::setInputStream (uno::Reference < io::XInputStream > xNewStream)\n{\n xStream = xNewStream;\n xSeek = uno::Reference < io::XSeekable > (xNewStream, uno::UNO_QUERY);\n}\n\n\/\/ XInputStream chained\nsal_Int32 SAL_CALL ByteGrabber::readBytes( uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nBytesToRead )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n return xStream->readBytes(aData, nBytesToRead );\n}\nsal_Int32 SAL_CALL ByteGrabber::readSomeBytes( uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nMaxBytesToRead )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n return xStream->readSomeBytes( aData, nMaxBytesToRead );\n}\nvoid SAL_CALL ByteGrabber::skipBytes( sal_Int32 nBytesToSkip )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n xStream->skipBytes( nBytesToSkip );\n}\nsal_Int32 SAL_CALL ByteGrabber::available( )\n throw(io::NotConnectedException, io::IOException, uno::RuntimeException)\n{\n return xStream->available();\n}\nvoid SAL_CALL ByteGrabber::closeInput( )\n throw(io::NotConnectedException, io::IOException, uno::RuntimeException)\n{\n xStream->closeInput();\n}\n\n\/\/ XSeekable chained...\nsal_Int64 SAL_CALL ByteGrabber::seek( sal_Int64 location )\n throw(lang::IllegalArgumentException, io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n {\n sal_Int64 nLen = xSeek->getLength();\n if (location > nLen )\n location = nLen;\n xSeek->seek( location );\n return location;\n }\n else\n throw io::IOException();\n}\nsal_Int64 SAL_CALL ByteGrabber::getPosition( )\n throw(io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n return xSeek->getPosition();\n else\n throw io::IOException();\n}\nsal_Int64 SAL_CALL ByteGrabber::getLength( )\n throw(io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n return xSeek->getLength();\n else\n throw io::IOException();\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int8& rInt8)\n{\n uno::Sequence< sal_Int8 > aSequence (1);\n\n if (xStream->readBytes(aSequence,1) != 1)\n {\n rInt8 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n rInt8 = *(pArray) & 0xFF;\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int16& rInt16)\n{\n uno::Sequence< sal_Int8 > aSequence (2);\n\n if (xStream->readBytes(aSequence, 2) != 2)\n {\n rInt16 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n rInt16 = static_cast <sal_Int16>\n ((* pArray & 0xFF)\n | (*(pArray+1)& 0xFF) << 8);\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int32& rInt32)\n{\n uno::Sequence< sal_Int8 > aSequence (4);\n\n if (xStream->readBytes(aSequence, 4) != 4)\n {\n rInt32 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n rInt32 = static_cast < sal_Int32 >\n ((* (pArray ) & 0xFF)\n | (* (pArray+1) & 0xFF) << 8\n | (* (pArray+2) & 0xFF) << 16\n | (* (pArray+3) & 0xFF) << 24 );\n return *this;\n}\n\nByteGrabber& ByteGrabber::operator >> (sal_uInt8& ruInt8)\n{\n uno::Sequence< sal_Int8 > aSequence (1);\n\n if (xStream->readBytes(aSequence,1) != 1)\n {\n ruInt8 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n ruInt8 = static_cast <sal_uInt8> (* (pArray ) & 0xFF);\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_uInt16& ruInt16)\n{\n uno::Sequence< sal_Int8 > aSequence (2);\n\n if (xStream->readBytes(aSequence, 2) != 2)\n {\n ruInt16 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n ruInt16 = static_cast <sal_uInt16>\n ((* pArray & 0xFF)\n | (*(pArray+1)& 0xFF) << 8);\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_uInt32& ruInt32)\n{\n uno::Sequence< sal_Int8 > aSequence (4);\n\n if (xStream->readBytes(aSequence, 4) != 4)\n {\n ruInt32 = 0;\n return *this;\n }\n const sal_Int8 *pArray = aSequence.getArray();\n ruInt32 = static_cast < sal_uInt32 >\n ((* (pArray ) & 0xFF)\n | (* (pArray+1) & 0xFF) << 8\n | (* (pArray+2) & 0xFF) << 16\n | (* (pArray+3) & 0xFF) << 24 );\n return *this;\n}\n<commit_msg>#87099# OPtimise the stream operators<commit_after>\/*************************************************************************\n *\n * $RCSfile: ByteGrabber.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: mtg $ $Date: 2001-05-31 09:46:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _BYTE_GRABBER_HXX_\n#include \"ByteGrabber.hxx\"\n#endif\n\nusing namespace ::com::sun::star;\n\n\/** ByteGrabber implements the >> operators on an XOutputStream. This is\n * potentially quite slow and may need to be optimised\n *\/\n\nByteGrabber::ByteGrabber(uno::Reference < io::XInputStream > xIstream)\n: xStream(xIstream)\n, xSeek (xIstream, uno::UNO_QUERY )\n, aSequence ( 4 )\n{\n pSequence = aSequence.getArray();\n}\n\nByteGrabber::~ByteGrabber()\n{\n}\nvoid ByteGrabber::setInputStream (uno::Reference < io::XInputStream > xNewStream)\n{\n xStream = xNewStream;\n xSeek = uno::Reference < io::XSeekable > (xNewStream, uno::UNO_QUERY);\n}\n\n\/\/ XInputStream chained\nsal_Int32 SAL_CALL ByteGrabber::readBytes( uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nBytesToRead )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n return xStream->readBytes(aData, nBytesToRead );\n}\nsal_Int32 SAL_CALL ByteGrabber::readSomeBytes( uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nMaxBytesToRead )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n return xStream->readSomeBytes( aData, nMaxBytesToRead );\n}\nvoid SAL_CALL ByteGrabber::skipBytes( sal_Int32 nBytesToSkip )\n throw(io::NotConnectedException, io::BufferSizeExceededException, io::IOException, uno::RuntimeException)\n{\n xStream->skipBytes( nBytesToSkip );\n}\nsal_Int32 SAL_CALL ByteGrabber::available( )\n throw(io::NotConnectedException, io::IOException, uno::RuntimeException)\n{\n return xStream->available();\n}\nvoid SAL_CALL ByteGrabber::closeInput( )\n throw(io::NotConnectedException, io::IOException, uno::RuntimeException)\n{\n xStream->closeInput();\n}\n\n\/\/ XSeekable chained...\nsal_Int64 SAL_CALL ByteGrabber::seek( sal_Int64 location )\n throw(lang::IllegalArgumentException, io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n {\n sal_Int64 nLen = xSeek->getLength();\n if (location > nLen )\n location = nLen;\n xSeek->seek( location );\n return location;\n }\n else\n throw io::IOException();\n}\nsal_Int64 SAL_CALL ByteGrabber::getPosition( )\n throw(io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n return xSeek->getPosition();\n else\n throw io::IOException();\n}\nsal_Int64 SAL_CALL ByteGrabber::getLength( )\n throw(io::IOException, uno::RuntimeException)\n{\n if (xSeek.is() )\n return xSeek->getLength();\n else\n throw io::IOException();\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int8& rInt8)\n{\n if (xStream->readBytes(aSequence,1) != 1)\n rInt8 = 0;\n else\n rInt8 = pSequence[0] & 0xFF;\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int16& rInt16)\n{\n if (xStream->readBytes ( aSequence, 2) != 2)\n rInt16 = 0;\n else\n rInt16 = static_cast <sal_Int16>\n ( pSequence[0] & 0xFF\n | (pSequence[1] & 0xFF) << 8);\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_Int32& rInt32)\n{\n if (xStream->readBytes(aSequence, 4) != 4)\n rInt32 = 0;\n else\n rInt32 = static_cast < sal_Int32 >\n ( pSequence[0] & 0xFF\n | ( pSequence[1] & 0xFF ) << 8\n | ( pSequence[2] & 0xFF ) << 16\n | ( pSequence[3] & 0xFF ) << 24 );\n return *this;\n}\n\nByteGrabber& ByteGrabber::operator >> (sal_uInt8& rInt8)\n{\n if (xStream->readBytes(aSequence,1) != 1)\n rInt8 = 0;\n else\n rInt8 = static_cast < sal_uInt8 > (pSequence[0] & 0xFF );\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_uInt16& rInt16)\n{\n if (xStream->readBytes(aSequence, 2) != 2)\n rInt16 = 0;\n else\n rInt16 = static_cast <sal_uInt16>\n ( pSequence[0] & 0xFF\n | (pSequence[1] & 0xFF) << 8);\n return *this;\n}\nByteGrabber& ByteGrabber::operator >> (sal_uInt32& ruInt32)\n{\n if (xStream->readBytes(aSequence, 4) != 4)\n ruInt32 = 0;\n else\n ruInt32 = static_cast < sal_uInt32 >\n ( pSequence[0] & 0xFF\n | ( pSequence[1] & 0xFF ) << 8\n | ( pSequence[2] & 0xFF ) << 16\n | ( pSequence[3] & 0xFF ) << 24 );\n return *this;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <ctime>\n#include <typeinfo>\n#include <cstdlib>\n#include <fstream>\n\n\/\/#include <boost\/random.hpp>\n\/\/#include <boost\/generator_iterator.hpp>\n\/\/#include <boost\/date_time\/gregorian\/gregorian.hpp>\n\/\/#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\/\/#include <boost\/algorithm\/string.hpp>\n\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/serialization\/vector.hpp>\n#include <boost\/serialization\/list.hpp>\n\n#include \"mongoose.h\"\n#include \"json.hpp\"\n\n#include \"topology\/persistence.h\"\n#include \"geometry\/covertree.h\"\n#include \"topology\/sparse_rips_filtration.h\"\n#include \"topology\/rips_filtration.h\"\n\nusing json = nlohmann::json;\n\n\nstatic const char *s_http_port = \"8800\";\nstatic struct mg_serve_http_opts s_http_server_opts;\n\nvoid read_points_from_json(json& data, Points& points)\n{\n for(auto it = data.begin(); it != data.end(); it ++) {\n json t = *it;\n vector<double> p;\n p.push_back(t[\"px\"]);\n p.push_back(t[\"py\"]);\n points.push_back(Vector(p));\n }\n}\n\njson persistence_homology_split(json data)\n{\n\tPoints points;\n\tread_points_from_json(data, points);\n\n\tint max_d = 2;\n\n \/\/Filtration* full_filtration = new RipsFiltration(points, max_d);\n \/\/PersistentHomology sparse_rips_homology(full_filtration);\n Filtration* sparse_filtration = new SparseRipsFiltration(points, max_d, 1.0\/3);\n PersistentHomology ph(sparse_filtration);\n\n std::vector<PHCycle> reduction;\n Filtration* filtration;\n int loaded_max_d;\n \/\/ TODO load these from saved data\n\n ph.compute_matrix(reduction);\n\n \/\/ serialize vector\n {\n std::ofstream ofs(\"reduction.dat\");\n boost::archive::text_oarchive oa(ofs);\n oa & reduction;\n }\n\n std::vector<PHCycle> new_reduction;\n\n \/\/ load serialized vector\n {\n std::ifstream ifs(\"reduction.dat\");\n boost::archive::text_iarchive ia(ifs);\n ia & new_reduction;\n }\n\n\tPersistenceDiagram *sparse_rips_pd = ph.compute_persistence(new_reduction, filtration, loaded_max_d);\n\n\tsparse_rips_pd->sort_pairs_by_persistence();\n\n std::stringstream result;\n\tfor(unsigned i = 0; i < sparse_rips_pd->num_pairs(); i++) {\n\t\tPersistentPair pairing = sparse_rips_pd->get_pair(i);\n\t\t\/\/printf(\"%u %.7f %.7f\\n\", pairing.dim(), pairing.birth_time(), pairing.death_time());\n result << pairing.dim() << \" \"\n << pairing.birth_time() << \" \"\n << pairing.death_time() << \"\\n\";\n\t}\n\n delete sparse_rips_pd;\n return result.str();\n}\n\nstatic void handle_query_call(struct mg_connection *c, struct http_message *hm) {\n\n json q = json::parse(string(hm->body.p, hm->body.len));\n json result = persistence_homology_split(q);\n\n \/* Send result *\/\n std::string msg_content = result.dump();\n const std::string sep = \"\\r\\n\";\n\n std::stringstream ss;\n ss << \"HTTP\/1.1 200 OK\" << sep\n << \"Content-Type: application\/json\" << sep\n << \"Access-Control-Allow-Origin: *\" << sep\n << \"Content-Length: %d\" << sep << sep\n << \"%s\";\n\n mg_printf(c, ss.str().c_str(), (int) msg_content.size(), msg_content.c_str());\n}\n\nstatic void ev_handler(struct mg_connection *c, int ev, void *ev_data) {\n struct http_message *hm = (struct http_message *) ev_data;\n\n switch (ev) {\n case MG_EV_HTTP_REQUEST:\n if (mg_vcmp(&hm->uri, \"\/query\") == 0) {\n handle_query_call(c, hm); \/* Handle RESTful call *\/\n }\n else {\n mg_serve_http(c, hm, s_http_server_opts); \/* Serve static content *\/\n }\n break;\n default:\n break;\n }\n}\n\nint main(int argc, char *argv[]) {\n\n struct mg_mgr mgr;\n struct mg_connection *c;\n\n mg_mgr_init(&mgr, NULL);\n c = mg_bind(&mgr, s_http_port, ev_handler);\n mg_set_protocol_http_websocket(c);\n\n s_http_server_opts.document_root = \"..\/..\/webui\";\n s_http_server_opts.enable_directory_listing = \"yes\";\n\n\n printf(\"Starting server on port %s\\n\", s_http_port);\n\n for (;;) {\n mg_mgr_poll(&mgr, 1000);\n }\n\n\n mg_mgr_free(&mgr);\n\n return 0;\n}\n<commit_msg>use full rips filtration<commit_after>#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <ctime>\n#include <typeinfo>\n#include <cstdlib>\n#include <fstream>\n\n\/\/#include <boost\/random.hpp>\n\/\/#include <boost\/generator_iterator.hpp>\n\/\/#include <boost\/date_time\/gregorian\/gregorian.hpp>\n\/\/#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\/\/#include <boost\/algorithm\/string.hpp>\n\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/serialization\/vector.hpp>\n#include <boost\/serialization\/list.hpp>\n\n#include \"mongoose.h\"\n#include \"json.hpp\"\n\n#include \"topology\/persistence.h\"\n#include \"geometry\/covertree.h\"\n#include \"topology\/sparse_rips_filtration.h\"\n#include \"topology\/rips_filtration.h\"\n\nusing json = nlohmann::json;\n\n\nstatic const char *s_http_port = \"8800\";\nstatic struct mg_serve_http_opts s_http_server_opts;\n\nvoid read_points_from_json(json& data, Points& points)\n{\n for(auto it = data.begin(); it != data.end(); it ++) {\n json t = *it;\n vector<double> p;\n p.push_back(t[\"px\"]);\n p.push_back(t[\"py\"]);\n points.push_back(Vector(p));\n }\n}\n\njson persistence_homology_split(json data)\n{\n\tPoints points;\n\tread_points_from_json(data, points);\n\n\tint max_d = 2;\n\n Filtration* full_filtration = new RipsFiltration(points, max_d);\n PersistentHomology ph(full_filtration);\n \/\/Filtration* sparse_filtration = new SparseRipsFiltration(points, max_d, 1.0\/3);\n \/\/PersistentHomology ph(sparse_filtration);\n\n std::vector<PHCycle> reduction;\n Filtration* filtration;\n int loaded_max_d;\n \/\/ TODO load these from saved data\n\n ph.compute_matrix(reduction);\n\n \/\/ serialize vector\n {\n std::ofstream ofs(\"reduction.dat\");\n boost::archive::text_oarchive oa(ofs);\n oa & reduction;\n }\n\n std::vector<PHCycle> new_reduction;\n\n \/\/ load serialized vector\n {\n std::ifstream ifs(\"reduction.dat\");\n boost::archive::text_iarchive ia(ifs);\n ia & new_reduction;\n }\n\n\tPersistenceDiagram *sparse_rips_pd = ph.compute_persistence(new_reduction, filtration, loaded_max_d);\n\n\tsparse_rips_pd->sort_pairs_by_persistence();\n\n std::stringstream result;\n\tfor(unsigned i = 0; i < sparse_rips_pd->num_pairs(); i++) {\n\t\tPersistentPair pairing = sparse_rips_pd->get_pair(i);\n\t\t\/\/printf(\"%u %.7f %.7f\\n\", pairing.dim(), pairing.birth_time(), pairing.death_time());\n result << pairing.dim() << \" \"\n << pairing.birth_time() << \" \"\n << pairing.death_time() << \"\\n\";\n\t}\n\n delete sparse_rips_pd;\n return result.str();\n}\n\nstatic void handle_query_call(struct mg_connection *c, struct http_message *hm) {\n\n json q = json::parse(string(hm->body.p, hm->body.len));\n json result = persistence_homology_split(q);\n\n \/* Send result *\/\n std::string msg_content = result.dump();\n const std::string sep = \"\\r\\n\";\n\n std::stringstream ss;\n ss << \"HTTP\/1.1 200 OK\" << sep\n << \"Content-Type: application\/json\" << sep\n << \"Access-Control-Allow-Origin: *\" << sep\n << \"Content-Length: %d\" << sep << sep\n << \"%s\";\n\n mg_printf(c, ss.str().c_str(), (int) msg_content.size(), msg_content.c_str());\n}\n\nstatic void ev_handler(struct mg_connection *c, int ev, void *ev_data) {\n struct http_message *hm = (struct http_message *) ev_data;\n\n switch (ev) {\n case MG_EV_HTTP_REQUEST:\n if (mg_vcmp(&hm->uri, \"\/query\") == 0) {\n handle_query_call(c, hm); \/* Handle RESTful call *\/\n }\n else {\n mg_serve_http(c, hm, s_http_server_opts); \/* Serve static content *\/\n }\n break;\n default:\n break;\n }\n}\n\nint main(int argc, char *argv[]) {\n\n struct mg_mgr mgr;\n struct mg_connection *c;\n\n mg_mgr_init(&mgr, NULL);\n c = mg_bind(&mgr, s_http_port, ev_handler);\n mg_set_protocol_http_websocket(c);\n\n s_http_server_opts.document_root = \"..\/..\/webui\";\n s_http_server_opts.enable_directory_listing = \"yes\";\n\n\n printf(\"Starting server on port %s\\n\", s_http_port);\n\n for (;;) {\n mg_mgr_poll(&mgr, 1000);\n }\n\n\n mg_mgr_free(&mgr);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"bindings\/core\/v8\/V8DOMActivityLogger.h\"\n\n#include \"bindings\/core\/v8\/V8Binding.h\"\n#include \"platform\/weborigin\/KURL.h\"\n#include \"wtf\/HashMap.h\"\n#include \"wtf\/MainThread.h\"\n#include \"wtf\/text\/StringHash.h\"\n\nnamespace blink {\n\ntypedef HashMap<String, OwnPtr<V8DOMActivityLogger> > DOMActivityLoggerMapForMainWorld;\ntypedef HashMap<int, OwnPtr<V8DOMActivityLogger>, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int> > DOMActivityLoggerMapForIsolatedWorld;\n\nstatic DOMActivityLoggerMapForMainWorld& domActivityLoggersForMainWorld()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForMainWorld, map, ());\n return map;\n}\n\nstatic DOMActivityLoggerMapForIsolatedWorld& domActivityLoggersForIsolatedWorld()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForIsolatedWorld, map, ());\n return map;\n}\n\nvoid V8DOMActivityLogger::setActivityLogger(int worldId, const String& extensionId, PassOwnPtr<V8DOMActivityLogger> logger)\n{\n if (worldId)\n domActivityLoggersForIsolatedWorld().set(worldId, logger);\n else\n domActivityLoggersForMainWorld().set(extensionId, logger);\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const String& extensionId)\n{\n if (worldId) {\n DOMActivityLoggerMapForIsolatedWorld& loggers = domActivityLoggersForIsolatedWorld();\n DOMActivityLoggerMapForIsolatedWorld::iterator it = loggers.find(worldId);\n return it == loggers.end() ? 0 : it->value.get();\n }\n\n if (extensionId.isEmpty())\n return 0;\n\n DOMActivityLoggerMapForMainWorld& loggers = domActivityLoggersForMainWorld();\n DOMActivityLoggerMapForMainWorld::iterator it = loggers.find(extensionId);\n return it == loggers.end() ? 0 : it->value.get();\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const KURL& url)\n{\n \/\/ extension ID is ignored for worldId != 0.\n if (worldId)\n return activityLogger(worldId, String());\n\n \/\/ To find an activity logger that corresponds to the main world of an\n \/\/ extension, we need to obtain the extension ID. Extension ID is a hostname\n \/\/ of a background page's URL.\n if (!url.protocolIs(\"chrome-extension\"))\n return 0;\n\n return activityLogger(worldId, url.host());\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::currentActivityLogger()\n{\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n if (!isolate->InContext())\n return 0;\n\n v8::Handle<v8::Context> context = isolate->GetCurrentContext();\n if (context.IsEmpty() || !toDOMWindow(context))\n return 0;\n\n V8PerContextData* contextData = ScriptState::from(context)->perContextData();\n if (!contextData)\n return 0;\n\n return contextData->activityLogger();\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld()\n{\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n if (!isolate->InContext())\n return 0;\n\n v8::Handle<v8::Context> context = isolate->GetCurrentContext();\n if (context.IsEmpty() || !toDOMWindow(context))\n return 0;\n\n ScriptState* scriptState = ScriptState::from(context);\n if (!scriptState->world().isIsolatedWorld())\n return 0;\n\n V8PerContextData* contextData = scriptState->perContextData();\n if (!contextData)\n return 0;\n\n return contextData->activityLogger();\n}\n\n} \/\/ namespace blink\n<commit_msg>Add HandleScopes to V8DOMActivityLogger's methods<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"bindings\/core\/v8\/V8DOMActivityLogger.h\"\n\n#include \"bindings\/core\/v8\/V8Binding.h\"\n#include \"platform\/weborigin\/KURL.h\"\n#include \"wtf\/HashMap.h\"\n#include \"wtf\/MainThread.h\"\n#include \"wtf\/text\/StringHash.h\"\n\nnamespace blink {\n\ntypedef HashMap<String, OwnPtr<V8DOMActivityLogger> > DOMActivityLoggerMapForMainWorld;\ntypedef HashMap<int, OwnPtr<V8DOMActivityLogger>, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int> > DOMActivityLoggerMapForIsolatedWorld;\n\nstatic DOMActivityLoggerMapForMainWorld& domActivityLoggersForMainWorld()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForMainWorld, map, ());\n return map;\n}\n\nstatic DOMActivityLoggerMapForIsolatedWorld& domActivityLoggersForIsolatedWorld()\n{\n ASSERT(isMainThread());\n DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForIsolatedWorld, map, ());\n return map;\n}\n\nvoid V8DOMActivityLogger::setActivityLogger(int worldId, const String& extensionId, PassOwnPtr<V8DOMActivityLogger> logger)\n{\n if (worldId)\n domActivityLoggersForIsolatedWorld().set(worldId, logger);\n else\n domActivityLoggersForMainWorld().set(extensionId, logger);\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const String& extensionId)\n{\n if (worldId) {\n DOMActivityLoggerMapForIsolatedWorld& loggers = domActivityLoggersForIsolatedWorld();\n DOMActivityLoggerMapForIsolatedWorld::iterator it = loggers.find(worldId);\n return it == loggers.end() ? 0 : it->value.get();\n }\n\n if (extensionId.isEmpty())\n return 0;\n\n DOMActivityLoggerMapForMainWorld& loggers = domActivityLoggersForMainWorld();\n DOMActivityLoggerMapForMainWorld::iterator it = loggers.find(extensionId);\n return it == loggers.end() ? 0 : it->value.get();\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const KURL& url)\n{\n \/\/ extension ID is ignored for worldId != 0.\n if (worldId)\n return activityLogger(worldId, String());\n\n \/\/ To find an activity logger that corresponds to the main world of an\n \/\/ extension, we need to obtain the extension ID. Extension ID is a hostname\n \/\/ of a background page's URL.\n if (!url.protocolIs(\"chrome-extension\"))\n return 0;\n\n return activityLogger(worldId, url.host());\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::currentActivityLogger()\n{\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n if (!isolate->InContext())\n return 0;\n\n v8::HandleScope handleScope(isolate);\n v8::Handle<v8::Context> context = isolate->GetCurrentContext();\n if (context.IsEmpty() || !toDOMWindow(context))\n return 0;\n\n V8PerContextData* contextData = ScriptState::from(context)->perContextData();\n if (!contextData)\n return 0;\n\n return contextData->activityLogger();\n}\n\nV8DOMActivityLogger* V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld()\n{\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n if (!isolate->InContext())\n return 0;\n\n v8::HandleScope handleScope(isolate);\n v8::Handle<v8::Context> context = isolate->GetCurrentContext();\n if (context.IsEmpty() || !toDOMWindow(context))\n return 0;\n\n ScriptState* scriptState = ScriptState::from(context);\n if (!scriptState->world().isIsolatedWorld())\n return 0;\n\n V8PerContextData* contextData = scriptState->perContextData();\n if (!contextData)\n return 0;\n\n return contextData->activityLogger();\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InspectorFrontendHost.h\"\n\n#include \"bindings\/core\/v8\/ScriptFunctionCall.h\"\n#include \"bindings\/core\/v8\/ScriptState.h\"\n#include \"core\/clipboard\/Pasteboard.h\"\n#include \"core\/dom\/ExecutionContext.h\"\n#include \"core\/events\/Event.h\"\n#include \"core\/events\/EventTarget.h\"\n#include \"core\/fetch\/ResourceFetcher.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/html\/parser\/TextResourceDecoder.h\"\n#include \"core\/inspector\/InspectorController.h\"\n#include \"core\/inspector\/InspectorFrontendClient.h\"\n#include \"core\/loader\/FrameLoader.h\"\n#include \"core\/page\/ContextMenuController.h\"\n#include \"core\/page\/ContextMenuProvider.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/rendering\/RenderTheme.h\"\n#include \"platform\/ContextMenu.h\"\n#include \"platform\/ContextMenuItem.h\"\n#include \"platform\/SharedBuffer.h\"\n#include \"platform\/UserGestureIndicator.h\"\n#include \"platform\/network\/ResourceError.h\"\n#include \"platform\/network\/ResourceRequest.h\"\n#include \"platform\/network\/ResourceResponse.h\"\n\nnamespace blink {\n\nclass FrontendMenuProvider FINAL : public ContextMenuProvider {\npublic:\n static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)\n {\n return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items));\n }\n\n void disconnect()\n {\n m_frontendApiObject = ScriptValue();\n m_frontendHost = 0;\n }\n\nprivate:\n FrontendMenuProvider(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)\n : m_frontendHost(frontendHost)\n , m_frontendApiObject(frontendApiObject)\n , m_items(items)\n {\n }\n\n virtual ~FrontendMenuProvider()\n {\n contextMenuCleared();\n }\n\n virtual void populateContextMenu(ContextMenu* menu) OVERRIDE\n {\n for (size_t i = 0; i < m_items.size(); ++i)\n menu->appendItem(m_items[i]);\n }\n\n virtual void contextMenuItemSelected(const ContextMenuItem* item) OVERRIDE\n {\n if (m_frontendHost) {\n UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);\n int itemNumber = item->action() - ContextMenuItemBaseCustomTag;\n\n ScriptFunctionCall function(m_frontendApiObject, \"contextMenuItemSelected\");\n function.appendArgument(itemNumber);\n function.call();\n }\n }\n\n virtual void contextMenuCleared() OVERRIDE\n {\n if (m_frontendHost) {\n ScriptFunctionCall function(m_frontendApiObject, \"contextMenuCleared\");\n function.call();\n\n m_frontendHost->m_menuProvider = 0;\n }\n m_items.clear();\n m_frontendHost = 0;\n }\n\n InspectorFrontendHost* m_frontendHost;\n ScriptValue m_frontendApiObject;\n Vector<ContextMenuItem> m_items;\n};\n\nInspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage)\n : m_client(client)\n , m_frontendPage(frontendPage)\n , m_menuProvider(0)\n{\n ScriptWrappable::init(this);\n}\n\nInspectorFrontendHost::~InspectorFrontendHost()\n{\n ASSERT(!m_client);\n}\n\nvoid InspectorFrontendHost::trace(Visitor* visitor)\n{\n visitor->trace(m_frontendPage);\n}\n\nvoid InspectorFrontendHost::disconnectClient()\n{\n m_client = 0;\n if (m_menuProvider)\n m_menuProvider->disconnect();\n m_frontendPage = nullptr;\n}\n\nvoid InspectorFrontendHost::setZoomFactor(float zoom)\n{\n m_frontendPage->deprecatedLocalMainFrame()->setPageAndTextZoomFactors(zoom, 1);\n}\n\nfloat InspectorFrontendHost::zoomFactor()\n{\n return m_frontendPage->deprecatedLocalMainFrame()->pageZoomFactor();\n}\n\nvoid InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)\n{\n m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);\n}\n\nvoid InspectorFrontendHost::copyText(const String& text)\n{\n Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);\n}\n\nstatic String escapeUnicodeNonCharacters(const String& str)\n{\n const UChar nonChar = 0xD800;\n\n unsigned i = 0;\n while (i < str.length() && str[i] < nonChar)\n ++i;\n if (i == str.length())\n return str;\n\n StringBuilder dst;\n dst.append(str, 0, i);\n for (; i < str.length(); ++i) {\n UChar c = str[i];\n if (c >= nonChar) {\n unsigned symbol = static_cast<unsigned>(c);\n String symbolCode = String::format(\"\\\\u%04X\", symbol);\n dst.append(symbolCode);\n } else {\n dst.append(c);\n }\n }\n return dst.toString();\n}\n\nvoid InspectorFrontendHost::sendMessageToBackend(const String& message)\n{\n if (m_client)\n m_client->sendMessageToBackend(escapeUnicodeNonCharacters(message));\n}\n\nvoid InspectorFrontendHost::sendMessageToEmbedder(const String& message)\n{\n if (m_client)\n m_client->sendMessageToEmbedder(escapeUnicodeNonCharacters(message));\n}\n\nvoid InspectorFrontendHost::showContextMenu(Page* page, float x, float y, const Vector<ContextMenuItem>& items)\n{\n ASSERT(m_frontendPage);\n ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());\n ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject(\"InspectorFrontendAPI\");\n ASSERT(frontendApiObject.isObject());\n\n RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);\n m_menuProvider = menuProvider.get();\n float zoom = page->deprecatedLocalMainFrame()->pageZoomFactor();\n page->inspectorController().showContextMenu(x * zoom, y * zoom, menuProvider);\n}\n\nvoid InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)\n{\n if (!event)\n return;\n\n ASSERT(m_frontendPage);\n ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());\n ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject(\"InspectorFrontendAPI\");\n ASSERT(frontendApiObject.isObject());\n\n Page* targetPage = m_frontendPage;\n if (event->target() && event->target()->executionContext() && event->target()->executionContext()->executingWindow()) {\n LocalDOMWindow* window = event->target()->executionContext()->executingWindow();\n if (window->document() && window->document()->page())\n targetPage = window->document()->page();\n }\n\n RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);\n targetPage->contextMenuController().showContextMenu(event, menuProvider);\n m_menuProvider = menuProvider.get();\n}\n\nString InspectorFrontendHost::getSelectionBackgroundColor()\n{\n return RenderTheme::theme().activeSelectionBackgroundColor().serialized();\n}\n\nString InspectorFrontendHost::getSelectionForegroundColor()\n{\n return RenderTheme::theme().activeSelectionForegroundColor().serialized();\n}\n\nbool InspectorFrontendHost::isUnderTest()\n{\n return m_client && m_client->isUnderTest();\n}\n\nbool InspectorFrontendHost::isHostedMode()\n{\n return false;\n}\n\n} \/\/ namespace blink\n<commit_msg>[DevTools] Speculative fix for crash in InspectorFrontendHost::zoomFactor.<commit_after>\/*\n * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InspectorFrontendHost.h\"\n\n#include \"bindings\/core\/v8\/ScriptFunctionCall.h\"\n#include \"bindings\/core\/v8\/ScriptState.h\"\n#include \"core\/clipboard\/Pasteboard.h\"\n#include \"core\/dom\/ExecutionContext.h\"\n#include \"core\/events\/Event.h\"\n#include \"core\/events\/EventTarget.h\"\n#include \"core\/fetch\/ResourceFetcher.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/html\/parser\/TextResourceDecoder.h\"\n#include \"core\/inspector\/InspectorController.h\"\n#include \"core\/inspector\/InspectorFrontendClient.h\"\n#include \"core\/loader\/FrameLoader.h\"\n#include \"core\/page\/ContextMenuController.h\"\n#include \"core\/page\/ContextMenuProvider.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/rendering\/RenderTheme.h\"\n#include \"platform\/ContextMenu.h\"\n#include \"platform\/ContextMenuItem.h\"\n#include \"platform\/SharedBuffer.h\"\n#include \"platform\/UserGestureIndicator.h\"\n#include \"platform\/network\/ResourceError.h\"\n#include \"platform\/network\/ResourceRequest.h\"\n#include \"platform\/network\/ResourceResponse.h\"\n\nnamespace blink {\n\nclass FrontendMenuProvider FINAL : public ContextMenuProvider {\npublic:\n static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)\n {\n return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items));\n }\n\n void disconnect()\n {\n m_frontendApiObject = ScriptValue();\n m_frontendHost = 0;\n }\n\nprivate:\n FrontendMenuProvider(InspectorFrontendHost* frontendHost, ScriptValue frontendApiObject, const Vector<ContextMenuItem>& items)\n : m_frontendHost(frontendHost)\n , m_frontendApiObject(frontendApiObject)\n , m_items(items)\n {\n }\n\n virtual ~FrontendMenuProvider()\n {\n contextMenuCleared();\n }\n\n virtual void populateContextMenu(ContextMenu* menu) OVERRIDE\n {\n for (size_t i = 0; i < m_items.size(); ++i)\n menu->appendItem(m_items[i]);\n }\n\n virtual void contextMenuItemSelected(const ContextMenuItem* item) OVERRIDE\n {\n if (m_frontendHost) {\n UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);\n int itemNumber = item->action() - ContextMenuItemBaseCustomTag;\n\n ScriptFunctionCall function(m_frontendApiObject, \"contextMenuItemSelected\");\n function.appendArgument(itemNumber);\n function.call();\n }\n }\n\n virtual void contextMenuCleared() OVERRIDE\n {\n if (m_frontendHost) {\n ScriptFunctionCall function(m_frontendApiObject, \"contextMenuCleared\");\n function.call();\n\n m_frontendHost->m_menuProvider = 0;\n }\n m_items.clear();\n m_frontendHost = 0;\n }\n\n InspectorFrontendHost* m_frontendHost;\n ScriptValue m_frontendApiObject;\n Vector<ContextMenuItem> m_items;\n};\n\nInspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage)\n : m_client(client)\n , m_frontendPage(frontendPage)\n , m_menuProvider(0)\n{\n ScriptWrappable::init(this);\n}\n\nInspectorFrontendHost::~InspectorFrontendHost()\n{\n ASSERT(!m_client);\n}\n\nvoid InspectorFrontendHost::trace(Visitor* visitor)\n{\n visitor->trace(m_frontendPage);\n}\n\nvoid InspectorFrontendHost::disconnectClient()\n{\n m_client = 0;\n if (m_menuProvider)\n m_menuProvider->disconnect();\n m_frontendPage = nullptr;\n}\n\nvoid InspectorFrontendHost::setZoomFactor(float zoom)\n{\n if (LocalFrame* frame = m_frontendPage->deprecatedLocalMainFrame())\n frame->setPageAndTextZoomFactors(zoom, 1);\n}\n\nfloat InspectorFrontendHost::zoomFactor()\n{\n if (LocalFrame* frame = m_frontendPage->deprecatedLocalMainFrame())\n return frame->pageZoomFactor();\n return 1;\n}\n\nvoid InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)\n{\n m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);\n}\n\nvoid InspectorFrontendHost::copyText(const String& text)\n{\n Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);\n}\n\nstatic String escapeUnicodeNonCharacters(const String& str)\n{\n const UChar nonChar = 0xD800;\n\n unsigned i = 0;\n while (i < str.length() && str[i] < nonChar)\n ++i;\n if (i == str.length())\n return str;\n\n StringBuilder dst;\n dst.append(str, 0, i);\n for (; i < str.length(); ++i) {\n UChar c = str[i];\n if (c >= nonChar) {\n unsigned symbol = static_cast<unsigned>(c);\n String symbolCode = String::format(\"\\\\u%04X\", symbol);\n dst.append(symbolCode);\n } else {\n dst.append(c);\n }\n }\n return dst.toString();\n}\n\nvoid InspectorFrontendHost::sendMessageToBackend(const String& message)\n{\n if (m_client)\n m_client->sendMessageToBackend(escapeUnicodeNonCharacters(message));\n}\n\nvoid InspectorFrontendHost::sendMessageToEmbedder(const String& message)\n{\n if (m_client)\n m_client->sendMessageToEmbedder(escapeUnicodeNonCharacters(message));\n}\n\nvoid InspectorFrontendHost::showContextMenu(Page* page, float x, float y, const Vector<ContextMenuItem>& items)\n{\n ASSERT(m_frontendPage);\n ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());\n ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject(\"InspectorFrontendAPI\");\n ASSERT(frontendApiObject.isObject());\n\n RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);\n m_menuProvider = menuProvider.get();\n float zoom = page->deprecatedLocalMainFrame()->pageZoomFactor();\n page->inspectorController().showContextMenu(x * zoom, y * zoom, menuProvider);\n}\n\nvoid InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)\n{\n if (!event)\n return;\n\n ASSERT(m_frontendPage);\n ScriptState* frontendScriptState = ScriptState::forMainWorld(m_frontendPage->deprecatedLocalMainFrame());\n ScriptValue frontendApiObject = frontendScriptState->getFromGlobalObject(\"InspectorFrontendAPI\");\n ASSERT(frontendApiObject.isObject());\n\n Page* targetPage = m_frontendPage;\n if (event->target() && event->target()->executionContext() && event->target()->executionContext()->executingWindow()) {\n LocalDOMWindow* window = event->target()->executionContext()->executingWindow();\n if (window->document() && window->document()->page())\n targetPage = window->document()->page();\n }\n\n RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);\n targetPage->contextMenuController().showContextMenu(event, menuProvider);\n m_menuProvider = menuProvider.get();\n}\n\nString InspectorFrontendHost::getSelectionBackgroundColor()\n{\n return RenderTheme::theme().activeSelectionBackgroundColor().serialized();\n}\n\nString InspectorFrontendHost::getSelectionForegroundColor()\n{\n return RenderTheme::theme().activeSelectionForegroundColor().serialized();\n}\n\nbool InspectorFrontendHost::isUnderTest()\n{\n return m_client && m_client->isUnderTest();\n}\n\nbool InspectorFrontendHost::isHostedMode()\n{\n return false;\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n * Copyright (C) 2011 Ericsson AB. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"MediaStreamTrack.h\"\n\n#if ENABLE(MEDIA_STREAM)\n\n#include \"Event.h\"\n#include \"MediaStreamCenter.h\"\n#include \"MediaStreamComponent.h\"\n\nnamespace WebCore {\n\nPassRefPtr<MediaStreamTrack> MediaStreamTrack::create(ScriptExecutionContext* context, MediaStreamComponent* component)\n{\n RefPtr<MediaStreamTrack> track = adoptRef(new MediaStreamTrack(context, component));\n track->suspendIfNeeded();\n return track.release();\n}\n\nMediaStreamTrack::MediaStreamTrack(ScriptExecutionContext* context, MediaStreamComponent* component)\n : ActiveDOMObject(context)\n , m_stopped(false)\n , m_component(component)\n{\n m_component->source()->addObserver(this);\n}\n\nMediaStreamTrack::~MediaStreamTrack()\n{\n m_component->source()->removeObserver(this);\n}\n\nString MediaStreamTrack::kind() const\n{\n DEFINE_STATIC_LOCAL(String, audioKind, (ASCIILiteral(\"audio\")));\n DEFINE_STATIC_LOCAL(String, videoKind, (ASCIILiteral(\"video\")));\n\n switch (m_component->source()->type()) {\n case MediaStreamSource::TypeAudio:\n return audioKind;\n case MediaStreamSource::TypeVideo:\n return videoKind;\n }\n\n ASSERT_NOT_REACHED();\n return audioKind;\n}\n\nString MediaStreamTrack::id() const\n{\n return m_component->id();\n}\n\nString MediaStreamTrack::label() const\n{\n return m_component->source()->name();\n}\n\nbool MediaStreamTrack::enabled() const\n{\n return m_component->enabled();\n}\n\nvoid MediaStreamTrack::setEnabled(bool enabled)\n{\n if (m_stopped || enabled == m_component->enabled())\n return;\n\n m_component->setEnabled(enabled);\n\n if (m_component->stream()->ended())\n return;\n\n MediaStreamCenter::instance().didSetMediaStreamTrackEnabled(m_component->stream(), m_component.get());\n}\n\nString MediaStreamTrack::readyState() const\n{\n if (m_stopped)\n return ASCIILiteral(\"ended\");\n\n switch (m_component->source()->readyState()) {\n case MediaStreamSource::ReadyStateLive:\n return ASCIILiteral(\"live\");\n case MediaStreamSource::ReadyStateMuted:\n return ASCIILiteral(\"muted\");\n case MediaStreamSource::ReadyStateEnded:\n return ASCIILiteral(\"ended\");\n }\n\n ASSERT_NOT_REACHED();\n return String();\n}\n\nbool MediaStreamTrack::ended() const\n{\n return m_stopped || (m_component->source()->readyState() == MediaStreamSource::ReadyStateEnded);\n}\n\nvoid MediaStreamTrack::sourceChangedState()\n{\n if (m_stopped)\n return;\n\n switch (m_component->source()->readyState()) {\n case MediaStreamSource::ReadyStateLive:\n dispatchEvent(Event::create(eventNames().unmuteEvent, false, false));\n break;\n case MediaStreamSource::ReadyStateMuted:\n dispatchEvent(Event::create(eventNames().muteEvent, false, false));\n break;\n case MediaStreamSource::ReadyStateEnded:\n dispatchEvent(Event::create(eventNames().endedEvent, false, false));\n didEndTrack();\n break;\n }\n}\n\nvoid MediaStreamTrack::didEndTrack()\n{\n MediaStreamDescriptorClient* client = m_component->stream()->client();\n if (!client)\n return;\n\n client->trackEnded();\n}\n\nMediaStreamComponent* MediaStreamTrack::component()\n{\n return m_component.get();\n}\n\nvoid MediaStreamTrack::stop()\n{\n m_stopped = true;\n didEndTrack();\n}\n\nconst AtomicString& MediaStreamTrack::interfaceName() const\n{\n return eventNames().interfaceForMediaStreamTrack;\n}\n\nScriptExecutionContext* MediaStreamTrack::scriptExecutionContext() const\n{\n return ActiveDOMObject::scriptExecutionContext();\n}\n\nEventTargetData* MediaStreamTrack::eventTargetData()\n{\n return &m_eventTargetData;\n}\n\nEventTargetData* MediaStreamTrack::ensureEventTargetData()\n{\n return &m_eventTargetData;\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(MEDIA_STREAM)\n<commit_msg>MediaStream API: Stop means stop Removing notification functionality from MediaStreamTrack::stop because the world is being torn down.<commit_after>\/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n * Copyright (C) 2011 Ericsson AB. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"MediaStreamTrack.h\"\n\n#if ENABLE(MEDIA_STREAM)\n\n#include \"Event.h\"\n#include \"MediaStreamCenter.h\"\n#include \"MediaStreamComponent.h\"\n\nnamespace WebCore {\n\nPassRefPtr<MediaStreamTrack> MediaStreamTrack::create(ScriptExecutionContext* context, MediaStreamComponent* component)\n{\n RefPtr<MediaStreamTrack> track = adoptRef(new MediaStreamTrack(context, component));\n track->suspendIfNeeded();\n return track.release();\n}\n\nMediaStreamTrack::MediaStreamTrack(ScriptExecutionContext* context, MediaStreamComponent* component)\n : ActiveDOMObject(context)\n , m_stopped(false)\n , m_component(component)\n{\n m_component->source()->addObserver(this);\n}\n\nMediaStreamTrack::~MediaStreamTrack()\n{\n m_component->source()->removeObserver(this);\n}\n\nString MediaStreamTrack::kind() const\n{\n DEFINE_STATIC_LOCAL(String, audioKind, (ASCIILiteral(\"audio\")));\n DEFINE_STATIC_LOCAL(String, videoKind, (ASCIILiteral(\"video\")));\n\n switch (m_component->source()->type()) {\n case MediaStreamSource::TypeAudio:\n return audioKind;\n case MediaStreamSource::TypeVideo:\n return videoKind;\n }\n\n ASSERT_NOT_REACHED();\n return audioKind;\n}\n\nString MediaStreamTrack::id() const\n{\n return m_component->id();\n}\n\nString MediaStreamTrack::label() const\n{\n return m_component->source()->name();\n}\n\nbool MediaStreamTrack::enabled() const\n{\n return m_component->enabled();\n}\n\nvoid MediaStreamTrack::setEnabled(bool enabled)\n{\n if (m_stopped || enabled == m_component->enabled())\n return;\n\n m_component->setEnabled(enabled);\n\n if (m_component->stream()->ended())\n return;\n\n MediaStreamCenter::instance().didSetMediaStreamTrackEnabled(m_component->stream(), m_component.get());\n}\n\nString MediaStreamTrack::readyState() const\n{\n if (m_stopped)\n return ASCIILiteral(\"ended\");\n\n switch (m_component->source()->readyState()) {\n case MediaStreamSource::ReadyStateLive:\n return ASCIILiteral(\"live\");\n case MediaStreamSource::ReadyStateMuted:\n return ASCIILiteral(\"muted\");\n case MediaStreamSource::ReadyStateEnded:\n return ASCIILiteral(\"ended\");\n }\n\n ASSERT_NOT_REACHED();\n return String();\n}\n\nbool MediaStreamTrack::ended() const\n{\n return m_stopped || (m_component->source()->readyState() == MediaStreamSource::ReadyStateEnded);\n}\n\nvoid MediaStreamTrack::sourceChangedState()\n{\n if (m_stopped)\n return;\n\n switch (m_component->source()->readyState()) {\n case MediaStreamSource::ReadyStateLive:\n dispatchEvent(Event::create(eventNames().unmuteEvent, false, false));\n break;\n case MediaStreamSource::ReadyStateMuted:\n dispatchEvent(Event::create(eventNames().muteEvent, false, false));\n break;\n case MediaStreamSource::ReadyStateEnded:\n dispatchEvent(Event::create(eventNames().endedEvent, false, false));\n didEndTrack();\n break;\n }\n}\n\nvoid MediaStreamTrack::didEndTrack()\n{\n MediaStreamDescriptorClient* client = m_component->stream()->client();\n if (!client)\n return;\n\n client->trackEnded();\n}\n\nMediaStreamComponent* MediaStreamTrack::component()\n{\n return m_component.get();\n}\n\nvoid MediaStreamTrack::stop()\n{\n m_stopped = true;\n}\n\nconst AtomicString& MediaStreamTrack::interfaceName() const\n{\n return eventNames().interfaceForMediaStreamTrack;\n}\n\nScriptExecutionContext* MediaStreamTrack::scriptExecutionContext() const\n{\n return ActiveDOMObject::scriptExecutionContext();\n}\n\nEventTargetData* MediaStreamTrack::eventTargetData()\n{\n return &m_eventTargetData;\n}\n\nEventTargetData* MediaStreamTrack::ensureEventTargetData()\n{\n return &m_eventTargetData;\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(MEDIA_STREAM)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/RequestableChannelClassSpec>\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT RequestableChannelClassSpec::Private : public QSharedData\n{\n Private(const RequestableChannelClass &rcc)\n : rcc(rcc) {}\n\n RequestableChannelClass rcc;\n};\n\nRequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClass &rcc)\n : mPriv(new Private(rcc))\n{\n}\n\nRequestableChannelClassSpec::RequestableChannelClassSpec()\n{\n}\n\nRequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClassSpec &other)\n : mPriv(other.mPriv)\n{\n}\n\nRequestableChannelClassSpec::~RequestableChannelClassSpec()\n{\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::textChat()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::textChatroom()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaAudioCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialAudio\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialVideo\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCallWithAudio()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialAudio\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialVideo\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::fileTransfer()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_FILE_TRANSFER);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChat()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroom()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroomWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCallWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearch()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServer()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Server\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithLimit()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Limit\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServerAndLimit()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Server\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Limit\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec &RequestableChannelClassSpec::operator=(const RequestableChannelClassSpec &other)\n{\n this->mPriv = other.mPriv;\n return *this;\n}\n\nbool RequestableChannelClassSpec::operator==(const RequestableChannelClassSpec &other) const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->rcc == other.mPriv->rcc;\n}\n\nbool RequestableChannelClassSpec::supports(const RequestableChannelClassSpec &other) const\n{\n if (!isValid()) {\n return false;\n }\n\n if (mPriv->rcc.fixedProperties == other.fixedProperties()) {\n foreach (const QString &prop, other.allowedProperties()) {\n if (!mPriv->rcc.allowedProperties.contains(prop)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\nQString RequestableChannelClassSpec::channelType() const\n{\n if (!isValid()) {\n return QString();\n }\n return qdbus_cast<QString>(mPriv->rcc.fixedProperties.value(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".ChannelType\")));\n}\n\nbool RequestableChannelClassSpec::hasTargetHandleType() const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.fixedProperties.contains(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".TargetHandleType\"));\n}\n\nHandleType RequestableChannelClassSpec::targetHandleType() const\n{\n if (!hasTargetHandleType()) {\n return (HandleType) -1;\n }\n return (HandleType) qdbus_cast<uint>(mPriv->rcc.fixedProperties.value(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".TargetHandleType\")));\n}\n\nbool RequestableChannelClassSpec::hasFixedProperty(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.fixedProperties.contains(name);\n}\n\nQVariant RequestableChannelClassSpec::fixedProperty(const QString &name) const\n{\n if (!isValid()) {\n return QVariant();\n }\n return mPriv->rcc.fixedProperties.value(name);\n}\n\nQVariantMap RequestableChannelClassSpec::fixedProperties() const\n{\n if (!isValid()) {\n return QVariantMap();\n }\n return mPriv->rcc.fixedProperties;\n}\n\nbool RequestableChannelClassSpec::allowsProperty(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.allowedProperties.contains(name);\n}\n\nQStringList RequestableChannelClassSpec::allowedProperties() const\n{\n if (!isValid()) {\n return QStringList();\n }\n return mPriv->rcc.allowedProperties;\n}\n\nRequestableChannelClass RequestableChannelClassSpec::bareClass() const\n{\n return isValid() ? mPriv->rcc : RequestableChannelClass();\n}\n\n} \/\/ Tp\n<commit_msg>RequestableChannelClassSpec: Return true in operator== if both instances are invalid and false if only one of them is.<commit_after>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/RequestableChannelClassSpec>\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT RequestableChannelClassSpec::Private : public QSharedData\n{\n Private(const RequestableChannelClass &rcc)\n : rcc(rcc) {}\n\n RequestableChannelClass rcc;\n};\n\nRequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClass &rcc)\n : mPriv(new Private(rcc))\n{\n}\n\nRequestableChannelClassSpec::RequestableChannelClassSpec()\n{\n}\n\nRequestableChannelClassSpec::RequestableChannelClassSpec(const RequestableChannelClassSpec &other)\n : mPriv(other.mPriv)\n{\n}\n\nRequestableChannelClassSpec::~RequestableChannelClassSpec()\n{\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::textChat()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::textChatroom()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaAudioCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialAudio\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialVideo\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::streamedMediaVideoCallWithAudio()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialAudio\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA + QLatin1String(\".InitialVideo\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::fileTransfer()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_FILE_TRANSFER);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeContact);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChat()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroom()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceTextChatroomWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_TEXT);\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".TargetHandleType\"),\n (uint) HandleTypeRoom);\n\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCall()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::conferenceStreamedMediaCallWithInvitees()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_STREAMED_MEDIA);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialChannels\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(\".InitialInviteeHandles\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearch()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServer()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Server\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithLimit()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Limit\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec RequestableChannelClassSpec::contactSearchWithSpecificServerAndLimit()\n{\n static RequestableChannelClassSpec spec;\n\n if (!spec.isValid()) {\n RequestableChannelClass rcc;\n rcc.fixedProperties.insert(TP_QT4_IFACE_CHANNEL + QLatin1String(\".ChannelType\"),\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH);\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Server\"));\n rcc.allowedProperties.append(\n TP_QT4_IFACE_CHANNEL_TYPE_CONTACT_SEARCH + QLatin1String(\".Limit\"));\n spec = RequestableChannelClassSpec(rcc);\n }\n\n return spec;\n}\n\nRequestableChannelClassSpec &RequestableChannelClassSpec::operator=(const RequestableChannelClassSpec &other)\n{\n this->mPriv = other.mPriv;\n return *this;\n}\n\nbool RequestableChannelClassSpec::operator==(const RequestableChannelClassSpec &other) const\n{\n if (!isValid() || !other.isValid()) {\n if (!isValid() && !other.isValid()) {\n return true;\n }\n return false;\n }\n\n return mPriv->rcc == other.mPriv->rcc;\n}\n\nbool RequestableChannelClassSpec::supports(const RequestableChannelClassSpec &other) const\n{\n if (!isValid()) {\n return false;\n }\n\n if (mPriv->rcc.fixedProperties == other.fixedProperties()) {\n foreach (const QString &prop, other.allowedProperties()) {\n if (!mPriv->rcc.allowedProperties.contains(prop)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\nQString RequestableChannelClassSpec::channelType() const\n{\n if (!isValid()) {\n return QString();\n }\n return qdbus_cast<QString>(mPriv->rcc.fixedProperties.value(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".ChannelType\")));\n}\n\nbool RequestableChannelClassSpec::hasTargetHandleType() const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.fixedProperties.contains(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".TargetHandleType\"));\n}\n\nHandleType RequestableChannelClassSpec::targetHandleType() const\n{\n if (!hasTargetHandleType()) {\n return (HandleType) -1;\n }\n return (HandleType) qdbus_cast<uint>(mPriv->rcc.fixedProperties.value(\n QLatin1String(TELEPATHY_INTERFACE_CHANNEL \".TargetHandleType\")));\n}\n\nbool RequestableChannelClassSpec::hasFixedProperty(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.fixedProperties.contains(name);\n}\n\nQVariant RequestableChannelClassSpec::fixedProperty(const QString &name) const\n{\n if (!isValid()) {\n return QVariant();\n }\n return mPriv->rcc.fixedProperties.value(name);\n}\n\nQVariantMap RequestableChannelClassSpec::fixedProperties() const\n{\n if (!isValid()) {\n return QVariantMap();\n }\n return mPriv->rcc.fixedProperties;\n}\n\nbool RequestableChannelClassSpec::allowsProperty(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n return mPriv->rcc.allowedProperties.contains(name);\n}\n\nQStringList RequestableChannelClassSpec::allowedProperties() const\n{\n if (!isValid()) {\n return QStringList();\n }\n return mPriv->rcc.allowedProperties;\n}\n\nRequestableChannelClass RequestableChannelClassSpec::bareClass() const\n{\n return isValid() ? mPriv->rcc : RequestableChannelClass();\n}\n\n} \/\/ Tp\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkLBFGSOptimizerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) 2000 National Library of Medicine\n All rights reserved.\n\n See COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n\n#include <itkLBFGSOptimizer.h>\n#include <itkPoint.h>\n\n\n\/** \n * The objectif function is the quadratic form:\n *\n * 1\/2 x^T A x - b^T x\n *\n * Where A is represented as an itkMatrix and \n * b is represented as a itkVector\n *\n * The system in this example is:\n *\n * | 3 2 ||x| | 2| |0|\n * | 2 6 ||y| + |-8| = |0|\n *\n *\n * the solution is the vector | 2 -2 |\n *\n *\/ \nclass CostFunction : public itk::LightObject \n{\npublic:\n\n typedef CostFunction Self;\n typedef itk::LightObject Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkNewMacro( Self );\n\n enum { SpaceDimension=2 };\n typedef itk::Point<double,SpaceDimension> ParametersType;\n typedef itk::Point<double,SpaceDimension> DerivativeType;\n typedef double MeasureType ;\n\n\n CostFunction() \n {\n }\n\n const ParametersType & GetParameters(void) const \n { \n return m_Parameters;\n }\n\n double GetValue( const ParametersType & position ) const\n { \n\n m_Parameters = position;\n\n double x = position[0];\n double y = position[1];\n\n std::cout << \"GetValue ( \" ;\n std::cout << x << \" , \" << y;\n std::cout << \") = \";\n\n double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;\n\n std::cout << val << std::endl; \n\n return val;\n }\n\n DerivativeType GetDerivative( const ParametersType & position ) const\n {\n\n double x = position[0];\n double y = position[1];\n\n std::cout << \"GetDerivative ( \" ;\n std::cout << x << \" , \" << y;\n std::cout << \") = \";\n\n DerivativeType grad;\n grad[0] = 3*x + 2*y -2;\n grad[1] = 2*x + 6*y +8;\n std::cout << \"(\" ; \n std::cout << grad[0] <<\" , \";\n std::cout << grad[1] << \")\" << std::endl;\n return grad;\n }\n\nprivate:\n\n mutable ParametersType m_Parameters;\n\n};\n\n\n\nint main() \n{\n std::cout << \"Conjugate Gradient Optimizer Test \\n \\n\";\n\n typedef itk::LBFGSOptimizer< \n CostFunction > OptimizerType;\n\n typedef OptimizerType::InternalOptimizerType vnlOptimizerType;\n\n \n \n \/\/ Declaration of a itkOptimizer\n OptimizerType::Pointer itkOptimizer = OptimizerType::New();\n\n\n \/\/ Declaration of the CostFunction adaptor\n CostFunction costFunction;\n\n\n itkOptimizer->SetCostFunction( &costFunction );\n\n \n const double F_Tolerance = 1e-3; \/\/ Function value tolerance\n const double G_Tolerance = 1e-4; \/\/ Gradient magnitude tolerance \n const double X_Tolerance = 1e-8; \/\/ Search space tolerance\n const double Epsilon_Function = 1e-10; \/\/ Step\n const int Max_Iterations = 100; \/\/ Maximum number of iterations\n\n\n vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();\n\n vnlOptimizer.set_f_tolerance( F_Tolerance );\n vnlOptimizer.set_g_tolerance( G_Tolerance );\n vnlOptimizer.set_x_tolerance( X_Tolerance ); \n vnlOptimizer.set_epsilon_function( Epsilon_Function );\n vnlOptimizer.set_max_function_evals( Max_Iterations );\n\n vnlOptimizer.set_check_derivatives( 3 );\n \n const unsigned int SpaceDimension = 2;\n typedef itk::Point<double,SpaceDimension> ParametersType;\n ParametersType initialValue;\n\n \/\/ We start not so far from | 2 -2 |\n initialValue[0] = 100;\n initialValue[1] = -100;\n\n itkOptimizer->SetInitialPosition( initialValue );\n itkOptimizer->StartOptimization();\n\n std::cout << \"End condition = \" << vnlOptimizer.get_failure_code() << std::endl;\n std::cout << \"Number of iters = \" << vnlOptimizer.get_num_iterations() << std::endl;\n std::cout << \"Number of evals = \" << vnlOptimizer.get_num_evaluations() << std::endl; \n std::cout << std::endl;\n\n ParametersType finalValue = costFunction.GetParameters();\n\n std::cout << \"Solution = (\";\n std::cout << finalValue[0] << \",\" ;\n std::cout << finalValue[1] << \")\" << std::endl; \n\n return 0;\n\n}\n\n\n\n<commit_msg>ENH: Added test for numerical precision<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkLBFGSOptimizerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) 2000 National Library of Medicine\n All rights reserved.\n\n See COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n\n#include <itkLBFGSOptimizer.h>\n#include <itkPoint.h>\n\n\n\/** \n * The objectif function is the quadratic form:\n *\n * 1\/2 x^T A x - b^T x\n *\n * Where A is represented as an itkMatrix and \n * b is represented as a itkVector\n *\n * The system in this example is:\n *\n * | 3 2 ||x| | 2| |0|\n * | 2 6 ||y| + |-8| = |0|\n *\n *\n * the solution is the vector | 2 -2 |\n *\n *\/ \nclass CostFunction : public itk::LightObject \n{\npublic:\n\n typedef CostFunction Self;\n typedef itk::LightObject Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkNewMacro( Self );\n\n enum { SpaceDimension=2 };\n typedef itk::Point<double,SpaceDimension> ParametersType;\n typedef itk::Point<double,SpaceDimension> DerivativeType;\n typedef double MeasureType ;\n\n\n CostFunction() \n {\n }\n\n const ParametersType & GetParameters(void) const \n { \n return m_Parameters;\n }\n\n double GetValue( const ParametersType & position ) const\n { \n\n m_Parameters = position;\n\n double x = position[0];\n double y = position[1];\n\n std::cout << \"GetValue ( \" ;\n std::cout << x << \" , \" << y;\n std::cout << \") = \";\n\n double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;\n\n std::cout << val << std::endl; \n\n return val;\n }\n\n DerivativeType GetDerivative( const ParametersType & position ) const\n {\n\n double x = position[0];\n double y = position[1];\n\n std::cout << \"GetDerivative ( \" ;\n std::cout << x << \" , \" << y;\n std::cout << \") = \";\n\n DerivativeType grad;\n grad[0] = 3*x + 2*y -2;\n grad[1] = 2*x + 6*y +8;\n std::cout << \"(\" ; \n std::cout << grad[0] <<\" , \";\n std::cout << grad[1] << \")\" << std::endl;\n return grad;\n }\n\nprivate:\n\n mutable ParametersType m_Parameters;\n\n};\n\n\n\nint main() \n{\n std::cout << \"Conjugate Gradient Optimizer Test \\n \\n\";\n\n typedef itk::LBFGSOptimizer< \n CostFunction > OptimizerType;\n\n typedef OptimizerType::InternalOptimizerType vnlOptimizerType;\n\n \n \n \/\/ Declaration of a itkOptimizer\n OptimizerType::Pointer itkOptimizer = OptimizerType::New();\n\n\n \/\/ Declaration of the CostFunction adaptor\n CostFunction costFunction;\n\n\n itkOptimizer->SetCostFunction( &costFunction );\n\n \n const double F_Tolerance = 1e-3; \/\/ Function value tolerance\n const double G_Tolerance = 1e-4; \/\/ Gradient magnitude tolerance \n const double X_Tolerance = 1e-8; \/\/ Search space tolerance\n const double Epsilon_Function = 1e-10; \/\/ Step\n const int Max_Iterations = 100; \/\/ Maximum number of iterations\n\n\n vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();\n\n vnlOptimizer.set_f_tolerance( F_Tolerance );\n vnlOptimizer.set_g_tolerance( G_Tolerance );\n vnlOptimizer.set_x_tolerance( X_Tolerance ); \n vnlOptimizer.set_epsilon_function( Epsilon_Function );\n vnlOptimizer.set_max_function_evals( Max_Iterations );\n\n vnlOptimizer.set_check_derivatives( 3 );\n \n const unsigned int SpaceDimension = 2;\n typedef itk::Point<double,SpaceDimension> ParametersType;\n ParametersType initialValue;\n\n \/\/ We start not so far from | 2 -2 |\n initialValue[0] = 100;\n initialValue[1] = -100;\n\n itkOptimizer->SetInitialPosition( initialValue );\n itkOptimizer->StartOptimization();\n\n std::cout << \"End condition = \" << vnlOptimizer.get_failure_code() << std::endl;\n std::cout << \"Number of iters = \" << vnlOptimizer.get_num_iterations() << std::endl;\n std::cout << \"Number of evals = \" << vnlOptimizer.get_num_evaluations() << std::endl; \n std::cout << std::endl;\n\n ParametersType finalPosition;\n finalPosition = costFunction.GetParameters();\n std::cout << \"Solution = (\";\n std::cout << finalPosition[0] << \",\" ;\n std::cout << finalPosition[1] << \")\" << std::endl; \n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[2] = { 2, -2 };\n for( unsigned int j = 0; j < 2; j++ )\n {\n if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )\n pass = false;\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n\n\n\n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"game.h\"\n#include \"player.h\"\n#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(int argc, char **argv)\n{\n\tsrand(time(0)); \/\/Random numbers.\n\tGame game;\n\tPlayer player;\n\tPlayer player2; \/\/Unused if we dont have isTwoHumanPlayer set.\n\n\tchar piece = '-';\t\/\/current players player piece.\n\t\n\tif (argc < 2) {\n\t\tstd::cout << \"Please enter how many players you would like. 1 or 2.\\n\";\n\t\tstd::cout << \"Also enter which piece player one is. NO spaces\\n\";\n\t\tstd::cout << \"Example: .\/tictactoe 20 for two player game, random piece.\\n\";\n\t\tstd::cout << \"Additional help will come when I'm closer to releasing game fully...\\n\";\n\t\treturn 0;\n\t}\n\t\n\t\/\/Welcome message\/banner\n\tstd::cout << \"\\n\\nW E L C O M E T O T I C T A C T O E\\n\\n\";\t\n\t\n\tif (strtol(argv[1], NULL, 10) == 20) {\n\t\tstd::cout << \"Starting 2 player game, random pieces.\\n\";\n\t\tstd::cout << \"Chosing random piece...\\n\";\n\t\tif (game.get_random_num(100) % 2 == 0) {\n\t\t\tplayer.playerPiece = 'X';\n\t\t\tplayer2.playerPiece = 'O';\n\t\t\tstd::cout << \"Player one, your piece is \" << player.playerPiece << \"\\n\";\n\t\t\tstd::cout << \"Player two, your piece is \" << player2.playerPiece << \"\\n\";\n\t\t\tplayer.isTwoHumanPlayer = true;\n\t\t} else {\n\t\t\tstd::cout << \"Player one, your piece is O\\n\";\n\t\t\tstd::cout << \"Player two, your piece is X\\n\";\n\t\t\tplayer.playerPiece = 'O';\n\t\t\tplayer2.playerPiece = 'X';\n\t\t\tplayer.isTwoHumanPlayer = true;\n\t\t}\n\t}\n\t\n\tif (strtol(argv[1], NULL, 10) == 21) {\n\t\tstd::cout << \"Starting 2 player game, player on is X.\\n\";\n\t\tplayer.playerPiece = 'X';\n\t\tplayer2.playerPiece = 'O';\n\t\tplayer.isTwoHumanPlayer = true;\n\t}\n\t\n\tif (strtol(argv[1], NULL, 10) == 22) {\n\t\tstd::cout << \"Starting 2 player game, player one is O.\\n\";\n\t\tplayer.playerPiece = 'O';\n\t\tplayer2.playerPiece = 'X';\n\t\tplayer.isTwoHumanPlayer = true;\n\t}\n\n\twhile (game.isRunning) {\n\t\t\/\/Time to play the game!\n\t\tint userInput = 0;\n\n\t\tif (player.isTwoHumanPlayer) {\n\t\t\tif (player.isPlayerTurn) {\n\t\t\t\tpiece = player.playerPiece;\n\t\t\t\tstd::cout << \"Player one, enter the number of the square you want.\\n\";\n\t\t\t\tuserInput = player.get_input();\t\n\t\t\t\tif (userInput == -1) {\n\t\t\t\t\tstd::cout << \"\\n\\nExiting the game on grounds of user error or request.\\n\\n\";;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (game.make_move(userInput, player.playerPiece) == 1) {\n\t\t\t\t\tstd::cout << \"Overlap detected... \\n\";\n\t\t\t\t\tstd::cout << \"Player 1, try again.\\n\";\n\t\t\t\t\tplayer.isPlayerTurn = true;\n\t\t\t\t}\n\t\t\t\tplayer.isPlayerTurn = false;\n\t\t\t} else {\n\t\t\t\tpiece = player2.playerPiece;\n\t\t\t\tstd::cout << \"Player two, enter the number of the square you want.\\n\";\n\t\t\t\tuserInput = player.get_input();\n\t\t\t\tif (userInput == -1) {\n\t\t\t\t\tstd::cout << \"\\n\\nExiting the game on grounds of user error or request.\\n\\n\";;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (game.make_move(userInput, player.playerPiece) == 1) {\n\t\t\t\t\tstd::cout << \"Overlap detected... \\n\";\n\t\t\t\t\tstd::cout << \"Player 2, try again.\\n\";\n\t\t\t\t\tplayer.isPlayerTurn = false;\n\t\t\t\t}\n\t\t\t\tplayer.isPlayerTurn = true;\n\t\t\t}\n\t\t}\n\t\tgame.print_board();\n\t\t\n\t\t\/\/Whoever wins first wins first, there is no other option.\n\t\t\/\/You cannot tie for win in tic tac toe, but you can draw\n\t\t\/\/and\/or stalemate the game. <--- happens regularly... stalemates :Z\n\t\t\/*\n\t\tif (game.is_victory(player.playerPiece)) {\n\t\t\tstd::cout << \"\\n\\nPlayer one wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of happy victory ;)\\n\\n\";\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (game.is_victory(player2.playerPiece)) {\n\t\t\tstd::cout << \"\\n\\nPlayer two wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of happy victory ;)\\n\\n\";\n\t\t\treturn 0;\n\t\t}\n\t\t*\/\n\t\tif (game.isStalemate) {\n\t\t\tstd::cout << \"\\n\\nNobody wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of an angry stalemate. ARgh!\\n\\n\";\n\t\t}\n\t}\n}\n\n\n<commit_msg>Picking up where I left off. Fixing bugs, stalemate detection, etc.<commit_after>#include \"game.h\"\n#include \"player.h\"\n#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main(int argc, char **argv)\n{\n\tsrand(time(0)); \/\/Random numbers.\n\tGame game;\n\tPlayer player;\n\tPlayer player2; \/\/Unused if we dont have isTwoHumanPlayer set.\n\n\tchar piece = '-';\t\/\/current players player piece.\n\t\n\tif (argc < 2) {\n\t\tstd::cout << \"Please enter how many players you would like. 1 or 2.\\n\";\n\t\tstd::cout << \"Also enter which piece player one is. NO spaces\\n\";\n\t\tstd::cout << \"Example: .\/tictactoe 20 for two player game, random piece.\\n\";\n\t\tstd::cout << \"Additional help will come when I'm closer to releasing game fully...\\n\";\n\t\treturn 0;\n\t}\n\t\n\t\/\/Welcome message\/banner\n\tstd::cout << \"\\n\\nW E L C O M E T O T I C T A C T O E\\n\\n\";\t\n\t\n\tif (strtol(argv[1], NULL, 10) == 20) {\n\t\tstd::cout << \"Starting 2 player game, random pieces.\\n\";\n\t\tstd::cout << \"Chosing random piece...\\n\";\n\t\tif (game.get_random_num(100) % 2 == 0) {\n\t\t\tplayer.playerPiece = 'X';\n\t\t\tplayer2.playerPiece = 'O';\n\t\t\tstd::cout << \"Player one, your piece is \" << player.playerPiece << \"\\n\";\n\t\t\tstd::cout << \"Player two, your piece is \" << player2.playerPiece << \"\\n\";\n\t\t\tplayer.isTwoHumanPlayer = true;\n\t\t} else {\n\t\t\tstd::cout << \"Player one, your piece is O\\n\";\n\t\t\tstd::cout << \"Player two, your piece is X\\n\";\n\t\t\tplayer.playerPiece = 'O';\n\t\t\tplayer2.playerPiece = 'X';\n\t\t\tplayer.isTwoHumanPlayer = true;\n\t\t}\n\t}\n\t\n\tif (strtol(argv[1], NULL, 10) == 21) {\n\t\tstd::cout << \"Starting 2 player game, player on is X.\\n\";\n\t\tplayer.playerPiece = 'X';\n\t\tplayer2.playerPiece = 'O';\n\t\tplayer.isTwoHumanPlayer = true;\n\t}\n\t\n\tif (strtol(argv[1], NULL, 10) == 22) {\n\t\tstd::cout << \"Starting 2 player game, player one is O.\\n\";\n\t\tplayer.playerPiece = 'O';\n\t\tplayer2.playerPiece = 'X';\n\t\tplayer.isTwoHumanPlayer = true;\n\t}\n\n\twhile (game.isRunning) {\n\t\t\/\/Time to play the game!\n\t\tint userInput = 0;\n\n\t\tif (player.isTwoHumanPlayer) {\n\t\t\tif (player.isPlayerTurn) {\n\t\t\t\tpiece = player.playerPiece;\n\t\t\t\tstd::cout << \"Player one, enter the number of the square you want.\\n\";\n\t\t\t\tuserInput = player.get_input();\t\n\t\t\t\tif (game.make_move(userInput, player.playerPiece) == 1) {\n\t\t\t\t\tstd::cout << \"Overlap detected... \\n\";\n\t\t\t\t\tstd::cout << \"Player 1, try again.\\n\";\n\t\t\t\t\tplayer.isPlayerTurn = true;\n\t\t\t\t} else {\n\t\t\t\t\tplayer.isPlayerTurn = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpiece = player2.playerPiece;\n\t\t\t\tstd::cout << \"Player two, enter the number of the square you want.\\n\";\n\t\t\t\tuserInput = player.get_input();\n\t\t\t\tif (game.make_move(userInput, player2.playerPiece) == 1) {\n\t\t\t\t\tstd::cout << \"Overlap detected... \\n\";\n\t\t\t\t\tstd::cout << \"Player 2, try again.\\n\";\n\t\t\t\t\tplayer.isPlayerTurn = false;\n\t\t\t\t} else {\n\t\t\t\t\tplayer.isPlayerTurn = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgame.print_board();\n\t\t\n\t\t\/\/Whoever wins first wins first, there is no other option.\n\t\t\/\/You cannot tie for win in tic tac toe, but you can draw\n\t\t\/\/and\/or stalemate the game. <--- happens regularly... stalemates :Z\n\t\t\/*\n\t\tif (game.is_victory(player.playerPiece)) {\n\t\t\tstd::cout << \"\\n\\nPlayer one wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of happy victory ;)\\n\\n\";\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (game.is_victory(player2.playerPiece)) {\n\t\t\tstd::cout << \"\\n\\nPlayer two wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of happy victory ;)\\n\\n\";\n\t\t\treturn 0;\n\t\t}\n\t\t*\/\n\t\tif (game.isStalemate) {\n\t\t\tstd::cout << \"\\n\\nNobody wins!\\n\\n\";\n\t\t\tstd::cout << \"Now exiting on grounds of an angry stalemate. ARgh!\\n\\n\";\n\t\t}\n\t}\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of `et engine`\n * Copyright 2009-2013 by Sergey Reznik\n * Please, do not modify content without approval.\n *\n *\/\n\n#include <et\/core\/tools.h>\n#include <et\/app\/backgroundthread.h>\n\nusing namespace et;\n\nBackgroundRunLoop::BackgroundRunLoop() :\n\t_owner(nullptr) { }\n\nvoid BackgroundRunLoop::setOwner(BackgroundThread* owner)\n\t{ _owner = owner; }\n\nvoid BackgroundRunLoop::addTask(Task* t, float delay)\n{\n\tRunLoop::addTask(t, delay);\n\t_owner->resume();\n}\n\nBackgroundThread::BackgroundThread()\n{\n\t_runLoop.setOwner(this);\n}\n\nThreadResult BackgroundThread::main()\n{\n\twhile (running())\n\t{\n\t\tif (_runLoop.hasTasks())\n\t\t\t_runLoop.update(queryContiniousTimeInMilliSeconds());\n\t\telse\n\t\t\tsuspend();\n\t}\n\t\n\treturn 0;\n}\n<commit_msg>background thread fix<commit_after>\/*\n * This file is part of `et engine`\n * Copyright 2009-2013 by Sergey Reznik\n * Please, do not modify content without approval.\n *\n *\/\n\n#include <et\/core\/tools.h>\n#include <et\/app\/backgroundthread.h>\n\nusing namespace et;\n\nBackgroundRunLoop::BackgroundRunLoop() :\n\t_owner(nullptr) { }\n\nvoid BackgroundRunLoop::setOwner(BackgroundThread* owner)\n\t{ _owner = owner; }\n\nvoid BackgroundRunLoop::addTask(Task* t, float delay)\n{\n\tRunLoop::update(queryContiniousTimeInMilliSeconds());\n\tRunLoop::addTask(t, delay);\n\t\n\t_owner->resume();\n}\n\nBackgroundThread::BackgroundThread()\n{\n\t_runLoop.setOwner(this);\n}\n\nThreadResult BackgroundThread::main()\n{\n\twhile (running())\n\t{\n\t\tif (_runLoop.hasTasks())\n\t\t\t_runLoop.update(queryContiniousTimeInMilliSeconds());\n\t\telse\n\t\t\tsuspend();\n\t}\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Return kTRUE since kFALSE indicates to Root v6-18-04 real problems<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n\tMIDIDriver.cpp\n\t\n=============================================================================*\/\n\/*\n\tCopyright: \t Copyright 2000 Apple Computer, Inc. All rights reserved.\n\n\tDisclaimer:\tIMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.\n\t\t\t(\"Apple\") in consideration of your agreement to the following terms, and your\n\t\t\tuse, installation, modification or redistribution of this Apple software\n\t\t\tconstitutes acceptance of these terms. If you do not agree with these terms,\n\t\t\tplease do not use, install, modify or redistribute this Apple software.\n\n\t\t\tIn consideration of your agreement to abide by the following terms, and subject\n\t\t\tto these terms, Apple grants you a personal, non-exclusive license, under Apples\n\t\t\tcopyrights in this original Apple software (the \"Apple Software\"), to use,\n\t\t\treproduce, modify and redistribute the Apple Software, with or without\n\t\t\tmodifications, in source and\/or binary forms; provided that if you redistribute\n\t\t\tthe Apple Software in its entirety and without modifications, you must retain\n\t\t\tthis notice and the following text and disclaimers in all such redistributions of\n\t\t\tthe Apple Software. Neither the name, trademarks, service marks or logos of\n\t\t\tApple Computer, Inc. may be used to endorse or promote products derived from the\n\t\t\tApple Software without specific prior written permission from Apple. Except as\n\t\t\texpressly stated in this notice, no other rights or licenses, express or implied,\n\t\t\tare granted by Apple herein, including but not limited to any patent rights that\n\t\t\tmay be infringed by your derivative works or by other works in which the Apple\n\t\t\tSoftware may be incorporated.\n\n\t\t\tThe Apple Software is provided by Apple on an \"AS IS\" basis. APPLE MAKES NO\n\t\t\tWARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED\n\t\t\tWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\t\t\tPURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN\n\t\t\tCOMBINATION WITH YOUR PRODUCTS.\n\n\t\t\tIN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR\n\t\t\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n\t\t\tGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\t\t\tARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND\/OR DISTRIBUTION\n\t\t\tOF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT\n\t\t\t(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN\n\t\t\tADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ A CFPlugin MIDIDriver using a C interface to CFPlugin, but calling a C++ class to do the work.\n\n#include \"MIDIDriverClass.h\"\n\n\/\/ Implementation of the IUnknown QueryInterface function.\nstatic HRESULT MIDIDriverQueryInterface(MIDIDriverRef ref, REFIID iid, LPVOID *ppv) \n{\n\t\/\/ Create a CoreFoundation UUIDRef for the requested interface.\n\tCFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes( NULL, iid );\n\n#if V2_MIDI_DRIVER_SUPPORT\n\tif (CFEqual(interfaceID, kMIDIDriverInterface2ID)) {\n\t\t\/\/ If the MIDIDriverInterface was requested, bump the ref count,\n\t\t\/\/ set the ppv parameter equal to the instance, and\n\t\t\/\/ return good status.\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\tself->mVersion = 2;\n#if MIDI_WEAK_LINK_TO_V2_CALLS\n\t\tInitMIDIWeakLinks();\n#endif\n\t\treturn S_OK;\n\t}\n#endif\n\n#if V1_MIDI_DRIVER_SUPPORT\n\t\/\/ Test the requested ID against the valid interfaces.\n\tif (CFEqual(interfaceID, kMIDIDriverInterfaceID)) {\n\t\t\/\/ If the MIDIDriverInterface was requested, bump the ref count,\n\t\t\/\/ set the ppv parameter equal to the instance, and\n\t\t\/\/ return good status.\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\tself->mVersion = 1;\n\t\treturn S_OK;\n\t}\n#endif\n\n\tif (CFEqual(interfaceID, IUnknownUUID)) {\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\treturn S_OK;\n\t}\n\t\n\t\/\/ Requested interface unknown, bail with error.\n\t*ppv = NULL;\n\tCFRelease(interfaceID);\n\treturn E_NOINTERFACE;\n}\n\/\/ return value ppv is a pointer to a pointer to the interface\n\n\n\/\/ Implementation of reference counting for this type.\n\/\/ Whenever an interface is requested, bump the refCount for\n\/\/ the instance. NOTE: returning the refcount is a convention\n\/\/ but is not required so don't rely on it.\nstatic ULONG MIDIDriverAddRef(MIDIDriverRef ref) \n{\n\tMIDIDriver *self = GetMIDIDriver(ref);\n\n\treturn ++self->mRefCount;\n}\n\n\/\/ When an interface is released, decrement the refCount.\n\/\/ If the refCount goes to zero, deallocate the instance.\nstatic ULONG MIDIDriverRelease(MIDIDriverRef ref) \n{\n\tMIDIDriver *self = GetMIDIDriver(ref);\n\n\tif (--self->mRefCount == 0) {\n\t\tdelete self;\n\t\treturn 0;\n\t} else\n\t\treturn self->mRefCount;\n}\n\nOSStatus\tMIDIDriverFindDevices(MIDIDriverRef self, MIDIDeviceListRef devList)\n{\n\treturn GetMIDIDriver(self)->FindDevices(devList);\n}\n\nOSStatus\tMIDIDriverStart(MIDIDriverRef self, MIDIDeviceListRef devList)\n{\n\treturn GetMIDIDriver(self)->Start(devList);\n}\n\nOSStatus\tMIDIDriverStop(MIDIDriverRef self)\n{\n\treturn GetMIDIDriver(self)->Stop();\n}\n\nOSStatus\tMIDIDriverConfigure(MIDIDriverRef self, MIDIDeviceRef device)\n{\n\treturn GetMIDIDriver(self)->Configure(device);\n}\n\nOSStatus\tMIDIDriverSend(MIDIDriverRef self, const MIDIPacketList *pktlist, \n\t\t\t\tvoid *destRefCon1, void *destRefCon2)\n{\n\treturn GetMIDIDriver(self)->Send(pktlist, destRefCon1, destRefCon2);\n}\n\nOSStatus\tMIDIDriverEnableSource(MIDIDriverRef self, MIDIEndpointRef src, Boolean enabled)\n{\n\treturn GetMIDIDriver(self)->EnableSource(src, enabled);\n}\n\nOSStatus\tMIDIDriverFlush(MIDIDriverRef self, MIDIEndpointRef dest, void *destRefCon1, void *destRefCon2)\n{\n\treturn GetMIDIDriver(self)->Flush(dest, destRefCon1, destRefCon2);\n}\n\nOSStatus\tMIDIDriverMonitor(MIDIDriverRef self, MIDIEndpointRef dest, const MIDIPacketList *pktlist)\n{\n\treturn GetMIDIDriver(self)->Monitor(dest, pktlist);\n}\n\n\/\/ The MIDIDriverInterface function table.\nstatic MIDIDriverInterface MIDIDriverInterfaceFtbl = {\n\tNULL, \/\/ Required padding for COM\n\t\/\/\n\t\/\/ These are the required COM functions\n\t\/\/ NOTE: Warnings here about conversion from MIDIDriverInterface** to void* are nothing to worry about\n\t\/\/ (although yucky)\n\tMIDIDriverQueryInterface,\n\tMIDIDriverAddRef,\n\tMIDIDriverRelease,\n\t\/\/\n\t\/\/ These are the MIDIDriver methods\n\tMIDIDriverFindDevices,\n\tMIDIDriverStart,\n\tMIDIDriverStop,\n\tMIDIDriverConfigure,\n\tMIDIDriverSend,\n\tMIDIDriverEnableSource,\n\tMIDIDriverFlush,\n\tMIDIDriverMonitor\n};\n\nMIDIDriver::MIDIDriver(CFUUIDRef factoryID)\n{\n\t\/\/ Point to the function table\n\tmInterface = &MIDIDriverInterfaceFtbl;\n\n\t\/\/ Retain and keep an open instance refcount for each factory.\n\tmFactoryID = factoryID;\n\tCFPlugInAddInstanceForFactory(factoryID);\n\n\tmRefCount = 1;\n\tmVersion = 0;\n}\n\nMIDIDriver::~MIDIDriver()\n{\n\tif (mFactoryID) {\n\t\tCFPlugInRemoveInstanceForFactory(mFactoryID);\n\t\t\/\/ CFRelease(mFactoryID); this came from CFUUIDGetConstantUUIDWithBytes which\n\t\t\/\/ says that it is immortal and should never be released\n\t}\n}\n<commit_msg>A little bit of casting to avoid compiler warnings.<commit_after>\/*=============================================================================\n\tMIDIDriver.cpp\n\t\n=============================================================================*\/\n\/*\n\tCopyright: \t Copyright 2000 Apple Computer, Inc. All rights reserved.\n\n\tDisclaimer:\tIMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.\n\t\t\t(\"Apple\") in consideration of your agreement to the following terms, and your\n\t\t\tuse, installation, modification or redistribution of this Apple software\n\t\t\tconstitutes acceptance of these terms. If you do not agree with these terms,\n\t\t\tplease do not use, install, modify or redistribute this Apple software.\n\n\t\t\tIn consideration of your agreement to abide by the following terms, and subject\n\t\t\tto these terms, Apple grants you a personal, non-exclusive license, under Apples\n\t\t\tcopyrights in this original Apple software (the \"Apple Software\"), to use,\n\t\t\treproduce, modify and redistribute the Apple Software, with or without\n\t\t\tmodifications, in source and\/or binary forms; provided that if you redistribute\n\t\t\tthe Apple Software in its entirety and without modifications, you must retain\n\t\t\tthis notice and the following text and disclaimers in all such redistributions of\n\t\t\tthe Apple Software. Neither the name, trademarks, service marks or logos of\n\t\t\tApple Computer, Inc. may be used to endorse or promote products derived from the\n\t\t\tApple Software without specific prior written permission from Apple. Except as\n\t\t\texpressly stated in this notice, no other rights or licenses, express or implied,\n\t\t\tare granted by Apple herein, including but not limited to any patent rights that\n\t\t\tmay be infringed by your derivative works or by other works in which the Apple\n\t\t\tSoftware may be incorporated.\n\n\t\t\tThe Apple Software is provided by Apple on an \"AS IS\" basis. APPLE MAKES NO\n\t\t\tWARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED\n\t\t\tWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\t\t\tPURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN\n\t\t\tCOMBINATION WITH YOUR PRODUCTS.\n\n\t\t\tIN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR\n\t\t\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n\t\t\tGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\t\t\tARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND\/OR DISTRIBUTION\n\t\t\tOF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT\n\t\t\t(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN\n\t\t\tADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ A CFPlugin MIDIDriver using a C interface to CFPlugin, but calling a C++ class to do the work.\n\n#include \"MIDIDriverClass.h\"\n\n\/\/ Implementation of the IUnknown QueryInterface function.\nstatic HRESULT MIDIDriverQueryInterface(void *thisPointer, REFIID iid, LPVOID *ppv) \n{\n\tMIDIDriverRef ref = (MIDIDriverRef)thisPointer;\n\n\t\/\/ Create a CoreFoundation UUIDRef for the requested interface.\n\tCFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes( NULL, iid );\n\n#if V2_MIDI_DRIVER_SUPPORT\n\tif (CFEqual(interfaceID, kMIDIDriverInterface2ID)) {\n\t\t\/\/ If the MIDIDriverInterface was requested, bump the ref count,\n\t\t\/\/ set the ppv parameter equal to the instance, and\n\t\t\/\/ return good status.\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\tself->mVersion = 2;\n#if MIDI_WEAK_LINK_TO_V2_CALLS\n\t\tInitMIDIWeakLinks();\n#endif\n\t\treturn S_OK;\n\t}\n#endif\n\n#if V1_MIDI_DRIVER_SUPPORT\n\t\/\/ Test the requested ID against the valid interfaces.\n\tif (CFEqual(interfaceID, kMIDIDriverInterfaceID)) {\n\t\t\/\/ If the MIDIDriverInterface was requested, bump the ref count,\n\t\t\/\/ set the ppv parameter equal to the instance, and\n\t\t\/\/ return good status.\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\tself->mVersion = 1;\n\t\treturn S_OK;\n\t}\n#endif\n\n\tif (CFEqual(interfaceID, IUnknownUUID)) {\n\t\tMIDIDriver *self = GetMIDIDriver(ref);\n\t\tself->mInterface->AddRef(ref);\n\t\t*ppv = &self->mInterface;\n\t\tCFRelease(interfaceID);\n\t\treturn S_OK;\n\t}\n\t\n\t\/\/ Requested interface unknown, bail with error.\n\t*ppv = NULL;\n\tCFRelease(interfaceID);\n\treturn E_NOINTERFACE;\n}\n\/\/ return value ppv is a pointer to a pointer to the interface\n\n\n\/\/ Implementation of reference counting for this type.\n\/\/ Whenever an interface is requested, bump the refCount for\n\/\/ the instance. NOTE: returning the refcount is a convention\n\/\/ but is not required so don't rely on it.\nstatic ULONG MIDIDriverAddRef(void *thisPointer) \n{\n\tMIDIDriver *self = GetMIDIDriver((MIDIDriverRef)thisPointer);\n\n\treturn ++self->mRefCount;\n}\n\n\/\/ When an interface is released, decrement the refCount.\n\/\/ If the refCount goes to zero, deallocate the instance.\nstatic ULONG MIDIDriverRelease(void *thisPointer) \n{\n\tMIDIDriver *self = GetMIDIDriver((MIDIDriverRef)thisPointer);\n\n\tif (--self->mRefCount == 0) {\n\t\tdelete self;\n\t\treturn 0;\n\t} else\n\t\treturn self->mRefCount;\n}\n\nOSStatus\tMIDIDriverFindDevices(MIDIDriverRef self, MIDIDeviceListRef devList)\n{\n\treturn GetMIDIDriver(self)->FindDevices(devList);\n}\n\nOSStatus\tMIDIDriverStart(MIDIDriverRef self, MIDIDeviceListRef devList)\n{\n\treturn GetMIDIDriver(self)->Start(devList);\n}\n\nOSStatus\tMIDIDriverStop(MIDIDriverRef self)\n{\n\treturn GetMIDIDriver(self)->Stop();\n}\n\nOSStatus\tMIDIDriverConfigure(MIDIDriverRef self, MIDIDeviceRef device)\n{\n\treturn GetMIDIDriver(self)->Configure(device);\n}\n\nOSStatus\tMIDIDriverSend(MIDIDriverRef self, const MIDIPacketList *pktlist, \n\t\t\t\tvoid *destRefCon1, void *destRefCon2)\n{\n\treturn GetMIDIDriver(self)->Send(pktlist, destRefCon1, destRefCon2);\n}\n\nOSStatus\tMIDIDriverEnableSource(MIDIDriverRef self, MIDIEndpointRef src, Boolean enabled)\n{\n\treturn GetMIDIDriver(self)->EnableSource(src, enabled);\n}\n\nOSStatus\tMIDIDriverFlush(MIDIDriverRef self, MIDIEndpointRef dest, void *destRefCon1, void *destRefCon2)\n{\n\treturn GetMIDIDriver(self)->Flush(dest, destRefCon1, destRefCon2);\n}\n\nOSStatus\tMIDIDriverMonitor(MIDIDriverRef self, MIDIEndpointRef dest, const MIDIPacketList *pktlist)\n{\n\treturn GetMIDIDriver(self)->Monitor(dest, pktlist);\n}\n\n\/\/ The MIDIDriverInterface function table.\nstatic MIDIDriverInterface MIDIDriverInterfaceFtbl = {\n\tNULL, \/\/ Required padding for COM\n\t\/\/\n\t\/\/ These are the required COM functions\n\tMIDIDriverQueryInterface,\n\tMIDIDriverAddRef,\n\tMIDIDriverRelease,\n\t\/\/\n\t\/\/ These are the MIDIDriver methods\n\tMIDIDriverFindDevices,\n\tMIDIDriverStart,\n\tMIDIDriverStop,\n\tMIDIDriverConfigure,\n\tMIDIDriverSend,\n\tMIDIDriverEnableSource,\n\tMIDIDriverFlush,\n\tMIDIDriverMonitor\n};\n\nMIDIDriver::MIDIDriver(CFUUIDRef factoryID)\n{\n\t\/\/ Point to the function table\n\tmInterface = &MIDIDriverInterfaceFtbl;\n\n\t\/\/ Retain and keep an open instance refcount for each factory.\n\tmFactoryID = factoryID;\n\tCFPlugInAddInstanceForFactory(factoryID);\n\n\tmRefCount = 1;\n\tmVersion = 0;\n}\n\nMIDIDriver::~MIDIDriver()\n{\n\tif (mFactoryID) {\n\t\tCFPlugInRemoveInstanceForFactory(mFactoryID);\n\t\t\/\/ CFRelease(mFactoryID); this came from CFUUIDGetConstantUUIDWithBytes which\n\t\t\/\/ says that it is immortal and should never be released\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n#include \"VendingMachine.h\"\n#include \"GameManager.h\"\n#include \"SoundManager.h\"\n#include \"SpriteComponent.h\"\n#include \"AnimationComponent.h\"\n#include \"InputManager.h\"\n#include \"ComponentManager.h\"\n#include \"StageManager.h\"\n#include \"HPKit.h\"\n#include \"SpriteComponent.h\"\n\n#define KITNUM 2\n#define VENDING_WIDTH 50\n#define VENDING_HEIGHT 90\n\nbool VendingMachine::init()\n{\n\tif (!NPC::init())\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/Ÿ vendingMachine ٲ Ѵ. \n\tm_Type = OT_VENDING_MACHINE;\n\tm_Info.m_Size = cocos2d::Size(VENDING_WIDTH, VENDING_HEIGHT);\n\n\t\/\/kitnum ʱȭ\n\tm_KitNum = KITNUM;\n\n\t\/\/ڽ\n\tauto meterial = cocos2d::PhysicsMaterial(0, 0, 0);\n\tm_Body = cocos2d::PhysicsBody::createBox(m_Info.m_Size, meterial, cocos2d::Point(0, 0));\n\tm_Body->setContactTestBitmask(PHYC_PLAYER);\n\tm_Body->setCategoryBitmask(PHYC_NPC);\n\tm_Body->setCollisionBitmask(PHYC_PLAYER | PHYC_BLOCK);\n\tm_Body->setMass(10);\n\tm_Body->setRotationEnable(false);\n\tm_Body->setVelocityLimit(1000);\n\tsetPhysicsBody(m_Body);\n\tm_Body->retain();\n\n\t\/\/Ʈ ʱȭ\n\tm_FirstSprite = GET_COMPONENT_MANAGER()->createComponent<SpriteComponent>();\n\tm_FirstSprite->initSprite(ST_VENDING_MACHINE, this);\n\tm_FirstSprite->retain();\n\tm_FirstSprite->enter();\n\t\n\n\t\/\/ִϸ̼ ʱȭ\n\tm_ContactAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();\n\tm_ContactAni->setAnimation(AT_VENDING_MACHINE_CONTACT, this, 1, false);\n\tm_ContactAni->retain();\n\tm_SeperateAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();\n\tm_SeperateAni->setAnimation(AT_VENDING_MACHINE_SEPERATE, this, 1, false);\n\tm_SeperateAni->retain();\n\n\treturn true;\n}\n\nvoid VendingMachine::update(float dTime)\n{\n\tCreature::update(dTime);\n\tif (m_OnContact)\n\t{\n\n\t\tif (GET_INPUT_MANAGER()->getKeyState(KC_INTERACT) == KS_PRESS)\n\t\t{\n\t\t\tif (m_KitNum > 0)\n\t\t\t{\n\t\t\t\t--m_KitNum;\n\t\t\t\t\/\/⼭ ÷̾ ٿ Ǵµ \n\n\n\t\t\t\t\/\/⼭ ŰƮ \n\t\t\t\tint roomNum = GET_STAGE_MANAGER()->getRoomNum();\n\t\t\t\tauto hpKit = HPKit::create();\n\t\t\t\tGET_STAGE_MANAGER()->addObject(hpKit, roomNum, getPosition(), GAME_OBJECT);\n\n\t\t\t\tif (m_KitNum <= 0)\n\t\t\t\t{\n\t\t\t\t\tm_IsDead = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid VendingMachine::enter()\n{\n\tresume();\n\tm_FirstSprite->enter();\n}\n\nvoid VendingMachine::exit()\n{\n\tremoveFromParent();\n}\n\n\nvoid VendingMachine::dead()\n{\n\texit();\n}\n\nbool VendingMachine::onContactBegin(cocos2d::PhysicsContact& contact)\n{\n\tauto bodyA = contact.getShapeA()->getBody();\n\tauto bodyB = contact.getShapeB()->getBody();\n\tauto componentA = (BaseComponent*)bodyA->getNode();\n\tauto componentB = (BaseComponent*)bodyB->getNode();\n\tBaseComponent* enemyComponent;\n\tBaseComponent* myComponent;\n\n\tbool isComponentA = true;\n\n\tif (componentA->getType() == getType())\n\t{\n\t\tenemyComponent = componentB;\n\t\tmyComponent = componentA;\n\t\tisComponentA = true;\n\t}\n\telse\n\t{\n\t\tenemyComponent = componentA;\n\t\tmyComponent = componentB;\n\t\tisComponentA = false;\n\t}\n\n\tif ((m_LockOwner == nullptr || m_LockOwner == myComponent)\n\t\t&& enemyComponent->getPhysicsBody()->getCategoryBitmask() == PHYC_PLAYER)\n\t{\n\t\tm_LockOwner = myComponent;\n\t\tm_OnContact = true;\n\t\tm_MessageBox->enter();\n\t}\n\n\n\tm_SeperateAni->exit();\n\tm_FirstSprite->exit();\n\tm_ContactAni->enter();\n\n\treturn true;\n}\n\nvoid VendingMachine::onContactSeparate(cocos2d::PhysicsContact& contact)\n{\n\tm_ContactAni->exit();\n\tm_FirstSprite->exit();\n\tm_SeperateAni->enter();\n\tm_OnContact = false;\n\tm_MessageBox->exit();\n}\n\n\n<commit_msg>벤딩머신 속도 빠르게<commit_after>#include \"pch.h\"\n#include \"VendingMachine.h\"\n#include \"GameManager.h\"\n#include \"SoundManager.h\"\n#include \"SpriteComponent.h\"\n#include \"AnimationComponent.h\"\n#include \"InputManager.h\"\n#include \"ComponentManager.h\"\n#include \"StageManager.h\"\n#include \"HPKit.h\"\n#include \"SpriteComponent.h\"\n\n#define KITNUM 2\n#define VENDING_WIDTH 50\n#define VENDING_HEIGHT 90\n\nbool VendingMachine::init()\n{\n\tif (!NPC::init())\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/Ÿ vendingMachine ٲ Ѵ. \n\tm_Type = OT_VENDING_MACHINE;\n\tm_Info.m_Size = cocos2d::Size(VENDING_WIDTH, VENDING_HEIGHT);\n\n\t\/\/kitnum ʱȭ\n\tm_KitNum = KITNUM;\n\n\t\/\/ڽ\n\tauto meterial = cocos2d::PhysicsMaterial(0, 0, 0);\n\tm_Body = cocos2d::PhysicsBody::createBox(m_Info.m_Size, meterial, cocos2d::Point(0, 0));\n\tm_Body->setContactTestBitmask(PHYC_PLAYER);\n\tm_Body->setCategoryBitmask(PHYC_NPC);\n\tm_Body->setCollisionBitmask(PHYC_PLAYER | PHYC_BLOCK);\n\tm_Body->setMass(10);\n\tm_Body->setRotationEnable(false);\n\tm_Body->setVelocityLimit(1000);\n\tsetPhysicsBody(m_Body);\n\tm_Body->retain();\n\n\t\/\/Ʈ ʱȭ\n\tm_FirstSprite = GET_COMPONENT_MANAGER()->createComponent<SpriteComponent>();\n\tm_FirstSprite->initSprite(ST_VENDING_MACHINE, this);\n\tm_FirstSprite->retain();\n\tm_FirstSprite->enter();\n\t\n\n\t\/\/ִϸ̼ ʱȭ\n\tm_ContactAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();\n\tm_ContactAni->setAnimation(AT_VENDING_MACHINE_CONTACT, this, 1, false);\n\tm_ContactAni->retain();\n\tm_ContactAni->exit();\n\tm_SeperateAni = GET_COMPONENT_MANAGER()->createComponent<AnimationComponent>();\n\tm_SeperateAni->setAnimation(AT_VENDING_MACHINE_SEPERATE, this, 1, false);\n\tm_SeperateAni->retain();\n\tm_SeperateAni->exit();\n\n\treturn true;\n}\n\nvoid VendingMachine::update(float dTime)\n{\n\tCreature::update(dTime);\n\tif (m_OnContact)\n\t{\n\n\t\tif (GET_INPUT_MANAGER()->getKeyState(KC_INTERACT) == KS_PRESS)\n\t\t{\n\t\t\tif (m_KitNum > 0)\n\t\t\t{\n\t\t\t\t--m_KitNum;\n\t\t\t\t\/\/⼭ ÷̾ ٿ Ǵµ \n\n\n\t\t\t\t\/\/⼭ ŰƮ \n\t\t\t\tint roomNum = GET_STAGE_MANAGER()->getRoomNum();\n\t\t\t\tauto hpKit = HPKit::create();\n\t\t\t\tGET_STAGE_MANAGER()->addObject(hpKit, roomNum, getPosition(), GAME_OBJECT);\n\n\t\t\t\tif (m_KitNum <= 0)\n\t\t\t\t{\n\t\t\t\t\tm_IsDead = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid VendingMachine::enter()\n{\n\tresume();\n\tm_FirstSprite->enter();\n}\n\nvoid VendingMachine::exit()\n{\n\tremoveFromParent();\n}\n\n\nvoid VendingMachine::dead()\n{\n\texit();\n}\n\nbool VendingMachine::onContactBegin(cocos2d::PhysicsContact& contact)\n{\n\tauto bodyA = contact.getShapeA()->getBody();\n\tauto bodyB = contact.getShapeB()->getBody();\n\tauto componentA = (BaseComponent*)bodyA->getNode();\n\tauto componentB = (BaseComponent*)bodyB->getNode();\n\tBaseComponent* enemyComponent;\n\tBaseComponent* myComponent;\n\n\tbool isComponentA = true;\n\n\tif (componentA->getType() == getType())\n\t{\n\t\tenemyComponent = componentB;\n\t\tmyComponent = componentA;\n\t\tisComponentA = true;\n\t}\n\telse\n\t{\n\t\tenemyComponent = componentA;\n\t\tmyComponent = componentB;\n\t\tisComponentA = false;\n\t}\n\n\tif ((m_LockOwner == nullptr || m_LockOwner == myComponent)\n\t\t&& enemyComponent->getPhysicsBody()->getCategoryBitmask() == PHYC_PLAYER)\n\t{\n\t\tm_LockOwner = myComponent;\n\t\tm_OnContact = true;\n\t\tm_MessageBox->enter();\n\t\tm_SeperateAni->exit();\n\t\tm_FirstSprite->exit();\n\t\tm_ContactAni->enter();\n\n\t}\n\n\n\treturn true;\n}\n\nvoid VendingMachine::onContactSeparate(cocos2d::PhysicsContact& contact)\n{\n\tm_ContactAni->exit();\n\tm_FirstSprite->exit();\n\tm_SeperateAni->enter();\n\tm_OnContact = false;\n\tm_MessageBox->exit();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"elf_file.h\"\n\n#include \"common_compiler_test.h\"\n#include \"oat.h\"\n\nnamespace art {\n\nclass ElfWriterTest : public CommonCompilerTest {\n protected:\n virtual void SetUp() {\n ReserveImageSpace();\n CommonCompilerTest::SetUp();\n }\n};\n\n#define EXPECT_ELF_FILE_ADDRESS(ef, expected_value, symbol_name, build_map) \\\n do { \\\n void* addr = reinterpret_cast<void*>(ef->FindSymbolAddress(SHT_DYNSYM, \\\n symbol_name, \\\n build_map)); \\\n EXPECT_NE(nullptr, addr); \\\n EXPECT_LT(static_cast<uintptr_t>(ART_BASE_ADDRESS), reinterpret_cast<uintptr_t>(addr)); \\\n if (expected_value == nullptr) { \\\n expected_value = addr; \\\n } \\\n EXPECT_EQ(expected_value, addr); \\\n EXPECT_EQ(expected_value, ef->FindDynamicSymbolAddress(symbol_name)); \\\n } while (false)\n\nTEST_F(ElfWriterTest, dlsym) {\n std::string elf_filename;\n if (IsHost()) {\n const char* host_dir = getenv(\"ANDROID_HOST_OUT\");\n CHECK(host_dir != NULL);\n elf_filename = StringPrintf(\"%s\/framework\/core.oat\", host_dir);\n } else {\n elf_filename = \"\/data\/art-test\/core.oat\";\n }\n LOG(INFO) << \"elf_filename=\" << elf_filename;\n\n UnreserveImageSpace();\n void* dl_oatdata = NULL;\n void* dl_oatexec = NULL;\n void* dl_oatlastword = NULL;\n\n#if defined(ART_USE_PORTABLE_COMPILER)\n {\n \/\/ We only use dlopen for loading with portable. See OatFile::Open.\n void* dl_oat_so = dlopen(elf_filename.c_str(), RTLD_NOW);\n ASSERT_TRUE(dl_oat_so != NULL) << dlerror();\n dl_oatdata = dlsym(dl_oat_so, \"oatdata\");\n ASSERT_TRUE(dl_oatdata != NULL);\n\n OatHeader* dl_oat_header = reinterpret_cast<OatHeader*>(dl_oatdata);\n ASSERT_TRUE(dl_oat_header->IsValid());\n dl_oatexec = dlsym(dl_oat_so, \"oatexec\");\n ASSERT_TRUE(dl_oatexec != NULL);\n ASSERT_LT(dl_oatdata, dl_oatexec);\n\n dl_oatlastword = dlsym(dl_oat_so, \"oatlastword\");\n ASSERT_TRUE(dl_oatlastword != NULL);\n ASSERT_LT(dl_oatexec, dl_oatlastword);\n\n ASSERT_EQ(0, dlclose(dl_oat_so));\n }\n#endif\n\n UniquePtr<File> file(OS::OpenFileForReading(elf_filename.c_str()));\n ASSERT_TRUE(file.get() != NULL);\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, false, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatdata, \"oatdata\", false);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatexec, \"oatexec\", false);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatlastword, \"oatlastword\", false);\n }\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, false, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatdata, \"oatdata\", true);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatexec, \"oatexec\", true);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatlastword, \"oatlastword\", true);\n }\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, true, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n CHECK(ef->Load(false, &error_msg)) << error_msg;\n EXPECT_EQ(dl_oatdata, ef->FindDynamicSymbolAddress(\"oatdata\"));\n EXPECT_EQ(dl_oatexec, ef->FindDynamicSymbolAddress(\"oatexec\"));\n EXPECT_EQ(dl_oatlastword, ef->FindDynamicSymbolAddress(\"oatlastword\"));\n }\n}\n\n} \/\/ namespace art\n<commit_msg>Fix elf_writer_test for 64b target<commit_after>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"elf_file.h\"\n\n#include \"common_compiler_test.h\"\n#include \"oat.h\"\n\nnamespace art {\n\nclass ElfWriterTest : public CommonCompilerTest {\n protected:\n virtual void SetUp() {\n ReserveImageSpace();\n CommonCompilerTest::SetUp();\n }\n};\n\n#define EXPECT_ELF_FILE_ADDRESS(ef, expected_value, symbol_name, build_map) \\\n do { \\\n void* addr = reinterpret_cast<void*>(ef->FindSymbolAddress(SHT_DYNSYM, \\\n symbol_name, \\\n build_map)); \\\n EXPECT_NE(nullptr, addr); \\\n EXPECT_LT(static_cast<uintptr_t>(ART_BASE_ADDRESS), reinterpret_cast<uintptr_t>(addr)); \\\n if (expected_value == nullptr) { \\\n expected_value = addr; \\\n } \\\n EXPECT_EQ(expected_value, addr); \\\n EXPECT_EQ(expected_value, ef->FindDynamicSymbolAddress(symbol_name)); \\\n } while (false)\n\nTEST_F(ElfWriterTest, dlsym) {\n std::string elf_filename;\n if (IsHost()) {\n const char* host_dir = getenv(\"ANDROID_HOST_OUT\");\n CHECK(host_dir != NULL);\n elf_filename = StringPrintf(\"%s\/framework\/core.oat\", host_dir);\n } else {\n#ifdef __LP64__\n elf_filename = \"\/data\/art-test64\/core.oat\";\n#else\n elf_filename = \"\/data\/art-test\/core.oat\";\n#endif\n }\n LOG(INFO) << \"elf_filename=\" << elf_filename;\n\n UnreserveImageSpace();\n void* dl_oatdata = NULL;\n void* dl_oatexec = NULL;\n void* dl_oatlastword = NULL;\n\n#if defined(ART_USE_PORTABLE_COMPILER)\n {\n \/\/ We only use dlopen for loading with portable. See OatFile::Open.\n void* dl_oat_so = dlopen(elf_filename.c_str(), RTLD_NOW);\n ASSERT_TRUE(dl_oat_so != NULL) << dlerror();\n dl_oatdata = dlsym(dl_oat_so, \"oatdata\");\n ASSERT_TRUE(dl_oatdata != NULL);\n\n OatHeader* dl_oat_header = reinterpret_cast<OatHeader*>(dl_oatdata);\n ASSERT_TRUE(dl_oat_header->IsValid());\n dl_oatexec = dlsym(dl_oat_so, \"oatexec\");\n ASSERT_TRUE(dl_oatexec != NULL);\n ASSERT_LT(dl_oatdata, dl_oatexec);\n\n dl_oatlastword = dlsym(dl_oat_so, \"oatlastword\");\n ASSERT_TRUE(dl_oatlastword != NULL);\n ASSERT_LT(dl_oatexec, dl_oatlastword);\n\n ASSERT_EQ(0, dlclose(dl_oat_so));\n }\n#endif\n\n UniquePtr<File> file(OS::OpenFileForReading(elf_filename.c_str()));\n ASSERT_TRUE(file.get() != NULL);\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, false, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatdata, \"oatdata\", false);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatexec, \"oatexec\", false);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatlastword, \"oatlastword\", false);\n }\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, false, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatdata, \"oatdata\", true);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatexec, \"oatexec\", true);\n EXPECT_ELF_FILE_ADDRESS(ef, dl_oatlastword, \"oatlastword\", true);\n }\n {\n std::string error_msg;\n UniquePtr<ElfFile> ef(ElfFile::Open(file.get(), false, true, &error_msg));\n CHECK(ef.get() != nullptr) << error_msg;\n CHECK(ef->Load(false, &error_msg)) << error_msg;\n EXPECT_EQ(dl_oatdata, ef->FindDynamicSymbolAddress(\"oatdata\"));\n EXPECT_EQ(dl_oatexec, ef->FindDynamicSymbolAddress(\"oatexec\"));\n EXPECT_EQ(dl_oatlastword, ef->FindDynamicSymbolAddress(\"oatlastword\"));\n }\n}\n\n} \/\/ namespace art\n<|endoftext|>"} {"text":"<commit_before>#include <ROOT\/TDataFrame.hxx>\n#include <ROOT\/TTrivialDS.hxx>\n#include <ROOT\/TSeq.hxx>\n\n#include \"gtest\/gtest.h\"\n\nusing namespace ROOT::Experimental;\nusing namespace ROOT::Experimental::TDF;\n\nTEST(TTrivialDS, ColTypeNames)\n{\n TTrivialDS tds(32);\n tds.SetNSlots(1);\n\n auto colName = tds.GetColumnNames()[0]; \/\/ We know it's one.\n EXPECT_STREQ(\"col0\", colName.c_str());\n EXPECT_STREQ(\"ULong64_t\", tds.GetTypeName(\"col0\").c_str());\n\n EXPECT_TRUE(tds.HasColumn(\"col0\"));\n EXPECT_FALSE(tds.HasColumn(\"col1\"));\n}\n\nTEST(TTrivialDS, EntryRanges)\n{\n TTrivialDS tds(32);\n const auto nSlots = 4U;\n tds.SetNSlots(nSlots);\n\n auto ranges = tds.GetEntryRanges();\n\n EXPECT_EQ(4U, ranges.size());\n EXPECT_EQ(0U, ranges[0].first);\n EXPECT_EQ(8U, ranges[0].second);\n EXPECT_EQ(8U, ranges[1].first);\n EXPECT_EQ(16U, ranges[1].second);\n EXPECT_EQ(16U, ranges[2].first);\n EXPECT_EQ(24U, ranges[2].second);\n EXPECT_EQ(24U, ranges[3].first);\n EXPECT_EQ(32U, ranges[3].second);\n}\n\nTEST(TTrivialDS, ColumnReaders)\n{\n TTrivialDS tds(32);\n const auto nSlots = 4U;\n tds.SetNSlots(nSlots);\n auto vals = tds.GetColumnReaders<ULong64_t>(\"col0\");\n auto ranges = tds.GetEntryRanges();\n auto slot = 0U;\n for (auto &&range : ranges) {\n for (auto i : ROOT::TSeq<ULong64_t>(range.first, range.second)) {\n tds.SetEntry(slot, i);\n auto val = **vals[slot];\n EXPECT_EQ(i, val);\n }\n slot++;\n }\n}\n\n#ifndef NDEBUG\nTEST(TTrivialDS, SetNSlotsTwice)\n{\n auto theTest = []() {\n TTrivialDS tds(1);\n tds.SetNSlots(1);\n tds.SetNSlots(1);\n };\n ASSERT_DEATH(theTest(), \"Setting the number of slots even if the number of slots is different from zero.\");\n}\n#endif\n\nTEST(TTrivialDS, FromATDF)\n{\n std::unique_ptr<TDataSource> tds(new TTrivialDS(32));\n TDataFrame tdf(std::move(tds));\n auto max = tdf.Max<ULong64_t>(\"col0\");\n auto min = tdf.Min<ULong64_t>(\"col0\");\n auto c = tdf.Count();\n\n EXPECT_EQ(32U, *c);\n EXPECT_DOUBLE_EQ(31., *max);\n EXPECT_DOUBLE_EQ(0., *min);\n}\n\nTEST(TTrivialDS, FromATDFWithJitting)\n{\n std::unique_ptr<TDataSource> tds(new TTrivialDS(32));\n TDataFrame tdf(std::move(tds));\n auto max = tdf.Filter(\"col0 < 10\").Max(\"col0\");\n auto min = tdf.Filter(\"col0 > 10\").Define(\"j\", \"col0*2\").Min(\"j\");\n\n EXPECT_DOUBLE_EQ(9., *max);\n EXPECT_DOUBLE_EQ(22., *min);\n}\n<commit_msg>[TDF] Also test Filter\/Define for the trivial data-source<commit_after>#include <ROOT\/TDataFrame.hxx>\n#include <ROOT\/TTrivialDS.hxx>\n#include <ROOT\/TSeq.hxx>\n\n#include \"gtest\/gtest.h\"\n\nusing namespace ROOT::Experimental;\nusing namespace ROOT::Experimental::TDF;\n\nTEST(TTrivialDS, ColTypeNames)\n{\n TTrivialDS tds(32);\n tds.SetNSlots(1);\n\n auto colName = tds.GetColumnNames()[0]; \/\/ We know it's one.\n EXPECT_STREQ(\"col0\", colName.c_str());\n EXPECT_STREQ(\"ULong64_t\", tds.GetTypeName(\"col0\").c_str());\n\n EXPECT_TRUE(tds.HasColumn(\"col0\"));\n EXPECT_FALSE(tds.HasColumn(\"col1\"));\n}\n\nTEST(TTrivialDS, EntryRanges)\n{\n TTrivialDS tds(32);\n const auto nSlots = 4U;\n tds.SetNSlots(nSlots);\n\n auto ranges = tds.GetEntryRanges();\n\n EXPECT_EQ(4U, ranges.size());\n EXPECT_EQ(0U, ranges[0].first);\n EXPECT_EQ(8U, ranges[0].second);\n EXPECT_EQ(8U, ranges[1].first);\n EXPECT_EQ(16U, ranges[1].second);\n EXPECT_EQ(16U, ranges[2].first);\n EXPECT_EQ(24U, ranges[2].second);\n EXPECT_EQ(24U, ranges[3].first);\n EXPECT_EQ(32U, ranges[3].second);\n}\n\nTEST(TTrivialDS, ColumnReaders)\n{\n TTrivialDS tds(32);\n const auto nSlots = 4U;\n tds.SetNSlots(nSlots);\n auto vals = tds.GetColumnReaders<ULong64_t>(\"col0\");\n auto ranges = tds.GetEntryRanges();\n auto slot = 0U;\n for (auto &&range : ranges) {\n for (auto i : ROOT::TSeq<ULong64_t>(range.first, range.second)) {\n tds.SetEntry(slot, i);\n auto val = **vals[slot];\n EXPECT_EQ(i, val);\n }\n slot++;\n }\n}\n\n#ifndef NDEBUG\nTEST(TTrivialDS, SetNSlotsTwice)\n{\n auto theTest = []() {\n TTrivialDS tds(1);\n tds.SetNSlots(1);\n tds.SetNSlots(1);\n };\n ASSERT_DEATH(theTest(), \"Setting the number of slots even if the number of slots is different from zero.\");\n}\n#endif\n\nTEST(TTrivialDS, FromATDF)\n{\n std::unique_ptr<TDataSource> tds(new TTrivialDS(32));\n TDataFrame tdf(std::move(tds));\n auto max = tdf.Max<ULong64_t>(\"col0\");\n auto min = tdf.Min<ULong64_t>(\"col0\");\n auto c = tdf.Count();\n auto max2 = tdf.Filter([](ULong64_t col0) { return col0 < 10; }, {\"col0\"}).Max<ULong64_t>(\"col0\");\n auto min2 = tdf.Filter([](ULong64_t col0) { return col0 > 10; }, {\"col0\"})\n .Define(\"j\", [](ULong64_t col0) { return col0 * 2; }, {\"col0\"})\n .Min<ULong64_t>(\"j\");\n\n EXPECT_EQ(32U, *c);\n EXPECT_DOUBLE_EQ(31., *max);\n EXPECT_DOUBLE_EQ(0., *min);\n EXPECT_DOUBLE_EQ(9., *max2);\n EXPECT_DOUBLE_EQ(22., *min2);\n}\n\nTEST(TTrivialDS, FromATDFWithJitting)\n{\n std::unique_ptr<TDataSource> tds(new TTrivialDS(32));\n TDataFrame tdf(std::move(tds));\n auto max = tdf.Filter(\"col0 < 10\").Max(\"col0\");\n auto min = tdf.Filter(\"col0 > 10\").Define(\"j\", \"col0*2\").Min(\"j\");\n\n EXPECT_DOUBLE_EQ(9., *max);\n EXPECT_DOUBLE_EQ(22., *min);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <string>\n\n#include <QApplication>\n#include <QWidget>\n#include <QPushButton>\n#include <reflectionzeug\/Property.h>\n#include <reflectionzeug\/PropertyGroup.h>\n#include <reflectionzeug\/PropertySerializer.h>\n#include <reflectionzeug\/PropertyDeserializer.h>\n#include <propertyguizeug\/PropertyBrowser.h>\n\n#include \"libzeug-version.h\"\n\n#include \"Switch.h\"\n\n#ifdef WIN32\n#define SETTINGS_PATH \".\\\\data\\\\propertygui.ini\"\n#else\n#define SETTINGS_PATH \".\/data\/propertygui.ini\"\n#endif\n\n\nusing namespace reflectionzeug;\nusing namespace propertyguizeug;\n\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n QApplication::setApplicationName(\"propertygui-example\");\n QApplication::setOrganizationName(META_AUTHOR_ORGANIZATION);\n\n auto * widget = new QWidget();\n widget->setMinimumWidth(200);\n widget->setMaximumWidth(640);\n widget->setMinimumHeight(200);\n widget->setMaximumHeight(460);\n widget->setWindowTitle(\"Property Example\");\n widget->setAutoFillBackground(true);\n\n auto * settings = new PropertyGroup(\"Settings\");\n\n auto * visible = settings->addProperty<bool>(\"Visible\",\n [widget]() {\n return widget->isVisible();\n },\n [widget](const bool & b) {\n widget->setVisible(b);\n });\n \n visible->setOption(\"tooltip\", \"Opens and closes the example window.\");\n\n PropertyGroup * size = settings->addGroup(\"Size\");\n\n auto * width = size->addProperty<int>(\"Width\",\n [widget] () -> int {\n return widget->width();\n },\n [widget] (const int & width) {\n widget->resize(width, widget->height());\n });\n \n width->setOption(\"minimum\", widget->minimumWidth());\n width->setOption(\"maximum\", widget->maximumWidth());\n width->setOption(\"suffix\", \" pixel\");\n\n auto * height = size->addProperty<int>(\"Height\",\n [widget] () -> int {\n return widget->height();\n },\n [widget] (const int & height) {\n widget->resize(widget->width(), height);\n });\n\n height->setOption(\"minimum\", widget->minimumHeight());\n height->setOption(\"maximum\", widget->maximumHeight());\n height->setOption(\"suffix\", \" pixel\");\n\n auto * aspect = size->addProperty<float>(\"Aspect\",\n [widget] () -> float {\n return static_cast<float>(widget->width()) \/ widget->height();\n },\n [widget] (const float & aspect) {\n int width = static_cast<int>(aspect * widget->height());\n widget->resize(width, widget->height());\n });\n aspect->setOption(\"step\", 0.1f);\n aspect->setOption(\"suffix\", \" w\/h\");\n aspect->setOption(\"precision\", 4);\n\n auto * minimumSize = size->addProperty<std::array<int, 2>>(\"minimumSize\",\n [widget] (size_t i) -> int {\n switch (i)\n {\n case 0:\n return widget->minimumWidth();\n case 1:\n return widget->minimumHeight();\n default:\n return -1;\n }\n },\n [widget, width, height] (size_t i, const int & size) {\n switch (i)\n {\n case 0:\n widget->setMinimumWidth(size);\n width->setOption(\"minimum\", size);\n break;\n case 1:\n widget->setMinimumHeight(size);\n height->setOption(\"minimum\", size);\n \n }\n });\n\n minimumSize->setOption(\"title\", \"Minimum Size\");\n\n auto * maximumSize = size->addProperty<std::array<int, 2>>(\"maximumSize\",\n [widget](size_t i) -> int {\n switch (i)\n {\n case 0:\n return widget->maximumWidth();\n case 1:\n return widget->maximumHeight();\n default:\n return -1;\n \n }\n },\n [widget, width, height] (size_t i, const int & size) {\n switch (i)\n {\n case 0:\n widget->setMaximumWidth(size);\n width->setOption(\"maximum\", size);\n break;\n case 1:\n widget->setMaximumHeight(size);\n height->setOption(\"maximum\", size);\n }\n });\n\n maximumSize->setOption(\"title\", \"Maximum Size\");\n\n auto * windowTitle = settings->addProperty<std::string>(\"windowTitle\",\n [widget]() {\n return widget->windowTitle().toStdString();\n },\n [widget](const std::string & title) {\n widget->setWindowTitle(QString::fromStdString(title));\n });\n\n windowTitle->setOption(\"title\", \"Window Title\");\n\n auto * backgroundColor = settings->addProperty<Color>(\"backgroundColor\",\n [widget]() {\n QColor qcolor = widget->palette().color(QPalette::Window);\n return Color(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha());\n },\n [widget](const Color & color) {\n QColor qcolor(color.red(), color.green(), color.blue(), color.alpha());\n QPalette palette;\n palette.setColor(QPalette::Window, qcolor);\n widget->setPalette(palette);\n });\n\n backgroundColor->setOption(\"title\", \"Background Color\");\n backgroundColor->setOption(\"tooltip\", \"Sets the background color of the example window.\");\n\n auto * cursorProperty = settings->addProperty<Qt::CursorShape>(\"Cursor\",\n [widget] () \n {\n return widget->cursor().shape();\n },\n [widget] (const Qt::CursorShape & shape) \n {\n widget->setCursor(QCursor(shape));\n });\n\n cursorProperty->setStrings({\n { Qt::PointingHandCursor, \"Pointing Hand Cursor\" },\n { Qt::BusyCursor, \"Busy Cursor\" },\n { Qt::ArrowCursor, \"Arrow Cursor\" },\n { Qt::WaitCursor, \"Wait Cursor\" }\n });\n \n Property<FilePath> * filePath = settings->addProperty<FilePath>(\"filePath\", \"\");\n filePath->setOption(\"uniqueidentifier\", \"settings\/filePath\");\n filePath->setOption(\"tooltip\", \"A file path with no meaning.\");\n\n QPushButton button(\"Add\");\n\n QObject::connect(&button, &QAbstractButton::pressed, [settings] ()\n {\n static int i = 0;\n settings->addProperty<int>(\"_\" + std::to_string(i++), 12);\n });\n \n button.show();\n\n PropertyDeserializer deserializer;\n deserializer.deserialize(*settings, SETTINGS_PATH);\n\n auto * browser = new PropertyBrowser(settings);\n browser->show();\n\n int result = a.exec();\n\n PropertySerializer serializer;\n serializer.serialize(*settings, SETTINGS_PATH);\n\n delete settings;\n delete browser;\n delete widget;\n \n return result;\n}\n<commit_msg>Update propertyguiexample<commit_after>\n#include <string>\n\n#include <QApplication>\n#include <QWidget>\n#include <QPushButton>\n#include <reflectionzeug\/Property.h>\n#include <reflectionzeug\/PropertyGroup.h>\n#include <reflectionzeug\/PropertySerializer.h>\n#include <reflectionzeug\/PropertyDeserializer.h>\n#include <propertyguizeug\/PropertyBrowser.h>\n\n#include \"libzeug-version.h\"\n\n#include \"Switch.h\"\n\n#ifdef WIN32\n#define SETTINGS_PATH \".\\\\data\\\\propertygui.ini\"\n#else\n#define SETTINGS_PATH \".\/data\/propertygui.ini\"\n#endif\n\n\nusing namespace reflectionzeug;\nusing namespace propertyguizeug;\n\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n QApplication::setApplicationName(\"propertygui-example\");\n QApplication::setOrganizationName(META_AUTHOR_ORGANIZATION);\n\n auto * widget = new QWidget();\n widget->setMinimumWidth(200);\n widget->setMaximumWidth(640);\n widget->setMinimumHeight(200);\n widget->setMaximumHeight(460);\n widget->setWindowTitle(\"Property Example\");\n widget->setAutoFillBackground(true);\n\n auto * settings = new PropertyGroup(\"Settings\");\n\n auto * visible = settings->addProperty<bool>(\"Visible\",\n [widget]() {\n return widget->isVisible();\n },\n [widget](const bool & b) {\n widget->setVisible(b);\n });\n \n visible->setOption(\"tooltip\", \"Opens and closes the example window.\");\n\n PropertyGroup * size = settings->addGroup(\"Size\");\n\n auto * width = size->addProperty<int>(\"Width\",\n [widget] () -> int {\n return widget->width();\n },\n [widget] (const int & width) {\n widget->resize(width, widget->height());\n });\n \n width->setOption(\"minimum\", widget->minimumWidth());\n width->setOption(\"maximum\", widget->maximumWidth());\n width->setOption(\"suffix\", \" pixel\");\n\n auto * height = size->addProperty<int>(\"Height\",\n [widget] () -> int {\n return widget->height();\n },\n [widget] (const int & height) {\n widget->resize(widget->width(), height);\n });\n\n height->setOption(\"minimum\", widget->minimumHeight());\n height->setOption(\"maximum\", widget->maximumHeight());\n height->setOption(\"suffix\", \" pixel\");\n\n auto * aspect = size->addProperty<float>(\"Aspect\",\n [widget] () -> float {\n return static_cast<float>(widget->width()) \/ widget->height();\n },\n [widget] (const float & aspect) {\n int width = static_cast<int>(aspect * widget->height());\n widget->resize(width, widget->height());\n });\n aspect->setOption(\"step\", 0.1f);\n aspect->setOption(\"suffix\", \" w\/h\");\n aspect->setOption(\"precision\", 4);\n \n const char * sizeTitles[] = { \"Width\", \"Height\" };\n \n auto * minimumSize = size->addProperty<std::array<int, 2>>(\"minimumSize\",\n [widget] (size_t i) -> int {\n switch (i)\n {\n case 0:\n return widget->minimumWidth();\n case 1:\n return widget->minimumHeight();\n default:\n return -1;\n }\n },\n [widget, width, height] (size_t i, const int & size) {\n switch (i)\n {\n case 0:\n widget->setMinimumWidth(size);\n width->setOption(\"minimum\", size);\n break;\n case 1:\n widget->setMinimumHeight(size);\n height->setOption(\"minimum\", size);\n \n }\n });\n \n minimumSize->setOption(\"title\", \"Minimum Size\");\n for (size_t i = 0; i < minimumSize->count(); ++i)\n minimumSize->at(i)->setOption(\"title\", sizeTitles[i]);\n\n auto * maximumSize = size->addProperty<std::array<int, 2>>(\"maximumSize\",\n [widget](size_t i) -> int {\n switch (i)\n {\n case 0:\n return widget->maximumWidth();\n case 1:\n return widget->maximumHeight();\n default:\n return -1;\n \n }\n },\n [widget, width, height] (size_t i, const int & size) {\n switch (i)\n {\n case 0:\n widget->setMaximumWidth(size);\n width->setOption(\"maximum\", size);\n break;\n case 1:\n widget->setMaximumHeight(size);\n height->setOption(\"maximum\", size);\n }\n });\n \n maximumSize->setOption(\"title\", \"Maximum Size\");\n for (size_t i = 0; i < maximumSize->count(); ++i)\n maximumSize->at(i)->setOption(\"title\", sizeTitles[i]);\n\n \n\n auto * windowTitle = settings->addProperty<std::string>(\"windowTitle\",\n [widget]() {\n return widget->windowTitle().toStdString();\n },\n [widget](const std::string & title) {\n widget->setWindowTitle(QString::fromStdString(title));\n });\n\n windowTitle->setOption(\"title\", \"Window Title\");\n\n auto * backgroundColor = settings->addProperty<Color>(\"backgroundColor\",\n [widget]() {\n QColor qcolor = widget->palette().color(QPalette::Window);\n return Color(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha());\n },\n [widget](const Color & color) {\n QColor qcolor(color.red(), color.green(), color.blue(), color.alpha());\n QPalette palette;\n palette.setColor(QPalette::Window, qcolor);\n widget->setPalette(palette);\n });\n\n backgroundColor->setOption(\"title\", \"Background Color\");\n backgroundColor->setOption(\"tooltip\", \"Sets the background color of the example window.\");\n\n auto * cursorProperty = settings->addProperty<Qt::CursorShape>(\"Cursor\",\n [widget] () \n {\n return widget->cursor().shape();\n },\n [widget] (const Qt::CursorShape & shape) \n {\n widget->setCursor(QCursor(shape));\n });\n\n cursorProperty->setStrings({\n { Qt::PointingHandCursor, \"Pointing Hand Cursor\" },\n { Qt::BusyCursor, \"Busy Cursor\" },\n { Qt::ArrowCursor, \"Arrow Cursor\" },\n { Qt::WaitCursor, \"Wait Cursor\" }\n });\n \n Property<FilePath> * filePath = settings->addProperty<FilePath>(\"filePath\", \"\");\n filePath->setOption(\"uniqueidentifier\", \"settings\/filePath\");\n filePath->setOption(\"tooltip\", \"A file path with no meaning.\");\n\n PropertyDeserializer deserializer;\n deserializer.deserialize(*settings, SETTINGS_PATH);\n\n auto * browser = new PropertyBrowser(settings);\n browser->show();\n\n int result = a.exec();\n\n PropertySerializer serializer;\n serializer.serialize(*settings, SETTINGS_PATH);\n\n delete settings;\n delete browser;\n delete widget;\n \n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\nusing namespace std;\nclass Math{\n template <typename t> add(a, b){\n return a + b;\n }\n \n template <typename t> subract(a, b){\n return a - b;\n }\n \n template <typename t> divide(a, b){\n return a \/ b;\n }\n \n template <typename t> multiply(a, b){\n return a * b;\n }\n \n template <typename t> exponent(a, n){\n t value = 0;\n for(int i = 0; i < n; i++){\n value *= a;\n }\n }\n \n \/*\n Takes in a vector of numbers and finds the mean.\n \n Input: A vector of numbers\n \n Returns: The mean of the numbers (no decimals if not floating point)\n *\/\n template<typename t>\n double getMean(vector <t>numbers){\n\tt sum = 0;\n\tvector<t>::iterator numberIterator\n\tfor(vector<t>::iterator numberIterator = numbers.begin(); numberIterator < numbers.end(); numberIterator++){\n\t sum += *numberIterator\n\t}\n\treturn sum\/numbers.size();\n }\n}\n<commit_msg>added variable types (Forgot)<commit_after>#include <vector>\nusing namespace std;\nclass Math{\n template <typename t> add(t a, t b){\n return a + b;\n }\n \n template <typename t> subract(t a, t b){\n return a - b;\n }\n \n template <typename t> divide(t a, t b){\n return a \/ b;\n }\n \n template <typename t> multiply(t a, t b){\n return a * b;\n }\n \n template <typename t> exponent(t a, t n){\n t value = 0;\n for(int i = 0; i < n; i++){\n value *= a;\n }\n }\n \n \/*\n Takes in a vector of numbers and finds the mean.\n \n Input: A vector of numbers\n \n Returns: The mean of the numbers (no decimals if not floating point)\n *\/\n template<typename t>\n double getMean(vector <t>numbers){\n\tt sum = 0;\n\tvector<t>::iterator numberIterator\n\tfor(vector<t>::iterator numberIterator = numbers.begin(); numberIterator < numbers.end(); numberIterator++){\n\t sum += *numberIterator\n\t}\n\treturn sum\/numbers.size();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <lua.hpp>\n#include <LuaBridge.h>\n#include <RefCountedPtr.h>\n#include <LuaState.h>\n#include <iostream>\n\nnamespace {\nvoid luabridge_bind(lua_State* L) {\n\tclass Test {\n\tpublic:\n\t\tTest() {\n\t\t\tstd::cout<<__FUNCTION__<<std::endl;\n\t\t}\n\n\t\t~Test() {\n\t\t\tstd::cout<<__FUNCTION__<<std::endl;\n\t\t}\n\t};\n\n\tluabridge::getGlobalNamespace(L)\n\t\t.beginClass<Test>(\"Test\")\n\t\t\t.addConstructor<void(*)(),RefCountedPtr<Test>>()\n\t\t.endClass()\n\t;\n}\n}\n\nint main() {\n\tlua::State state;\n luabridge_bind(state.getState());\n try {\n \tstate.doString(\"Test()\");\n \tstate.doString(\"blabla()\");\n } catch (std::exception& e) {\n \tstd::cerr<<e.what()<<std::endl;\n }\n}\n<commit_msg>[ci skip]<commit_after>#include <lua.hpp>\n#include <LuaBridge.h>\n#include <RefCountedPtr.h>\n#include <LuaState.h>\n#include <iostream>\n\nnamespace {\nvoid luabridge_bind(lua_State* L) {\n\tclass Test {\n\tpublic:\n\t\tTest() {\n\t\t\tstd::cout<<__FUNCTION__<<std::endl;\n\t\t}\n\n\t\t~Test() {\n\t\t\tstd::cout<<__FUNCTION__<<std::endl;\n\t\t}\n\t};\n\n\tluabridge::getGlobalNamespace(L)\n\t\t.beginClass<Test>(\"Test\")\n\t\t\t.addConstructor<void(*)(),RefCountedPtr<Test>>()\n\t\t.endClass()\n\t;\n}\n}\n\nint main() {\n lua::State state;\n luabridge_bind(state.getState());\n try {\n \tstate.doString(\"Test()\");\n \tstate.doString(\"blabla()\");\n } catch (std::exception& e) {\n \tstd::cerr<<e.what()<<std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include \"utest_helper.hpp\"\n\nvoid test_get_arg_info(void)\n{\n int ret;\n uint32_t ret_val;\n cl_kernel_arg_type_qualifier type_qual;\n size_t ret_sz;\n char name[64];\n\n \/\/ Setup kernel and buffers\n OCL_CREATE_KERNEL(\"test_get_arg_info\");\n\n \/\/Arg 0\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_ADDRESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_address_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ADDRESS_GLOBAL);\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_ACCESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_access_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ACCESS_NONE);\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"float*\") + 1);\n OCL_ASSERT(!strcmp(name, \"float*\"));\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"src\") + 1);\n OCL_ASSERT(!strcmp(name, \"src\"));\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_TYPE_QUALIFIER,\n sizeof(type_qual), &type_qual, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_type_qualifier));\n OCL_ASSERT(type_qual == (CL_KERNEL_ARG_TYPE_CONST|CL_KERNEL_ARG_TYPE_VOLATILE));\n\n \/\/Arg 1\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_ADDRESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_address_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ADDRESS_LOCAL);\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_ACCESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_access_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ACCESS_NONE);\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"int*\") + 1);\n OCL_ASSERT(!strcmp(name, \"int*\"));\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"dst\") + 1);\n OCL_ASSERT(!strcmp(name, \"dst\"));\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_TYPE_QUALIFIER,\n sizeof(type_qual), &type_qual, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_type_qualifier));\n OCL_ASSERT(type_qual == CL_KERNEL_ARG_TYPE_NONE);\n\n \/\/Arg 2\n ret = clGetKernelArgInfo(kernel, 2, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"test_arg_struct\") + 1);\n OCL_ASSERT(!strcmp(name, \"test_arg_struct\"));\n}\n\nMAKE_UTEST_FROM_FUNCTION(test_get_arg_info);\n<commit_msg>Utest: Add -cl-kernel-arg-info to the utest test_get_arg_info<commit_after>#include <string.h>\n#include \"utest_helper.hpp\"\n\nvoid test_get_arg_info(void)\n{\n int ret;\n uint32_t ret_val;\n cl_kernel_arg_type_qualifier type_qual;\n size_t ret_sz;\n char name[64];\n\n \/\/ Setup kernel and buffers\n OCL_CALL (cl_kernel_init, \"test_get_arg_info.cl\", \"test_get_arg_info\", SOURCE, \"-cl-kernel-arg-info\");\n\n \/\/Arg 0\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_ADDRESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_address_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ADDRESS_GLOBAL);\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_ACCESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_access_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ACCESS_NONE);\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"float*\") + 1);\n OCL_ASSERT(!strcmp(name, \"float*\"));\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"src\") + 1);\n OCL_ASSERT(!strcmp(name, \"src\"));\n\n ret = clGetKernelArgInfo(kernel, 0, CL_KERNEL_ARG_TYPE_QUALIFIER,\n sizeof(type_qual), &type_qual, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_type_qualifier));\n OCL_ASSERT(type_qual == (CL_KERNEL_ARG_TYPE_CONST|CL_KERNEL_ARG_TYPE_VOLATILE));\n\n \/\/Arg 1\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_ADDRESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_address_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ADDRESS_LOCAL);\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_ACCESS_QUALIFIER,\n sizeof(ret_val), &ret_val, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_access_qualifier));\n OCL_ASSERT(ret_val == CL_KERNEL_ARG_ACCESS_NONE);\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"int*\") + 1);\n OCL_ASSERT(!strcmp(name, \"int*\"));\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"dst\") + 1);\n OCL_ASSERT(!strcmp(name, \"dst\"));\n\n ret = clGetKernelArgInfo(kernel, 1, CL_KERNEL_ARG_TYPE_QUALIFIER,\n sizeof(type_qual), &type_qual, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == sizeof(cl_kernel_arg_type_qualifier));\n OCL_ASSERT(type_qual == CL_KERNEL_ARG_TYPE_NONE);\n\n \/\/Arg 2\n ret = clGetKernelArgInfo(kernel, 2, CL_KERNEL_ARG_TYPE_NAME,\n sizeof(name), name, &ret_sz);\n OCL_ASSERT(ret == CL_SUCCESS);\n OCL_ASSERT(ret_sz == strlen(\"test_arg_struct\") + 1);\n OCL_ASSERT(!strcmp(name, \"test_arg_struct\"));\n}\n\nMAKE_UTEST_FROM_FUNCTION(test_get_arg_info);\n<|endoftext|>"} {"text":"<commit_before>#ifndef MAIN_FRAME_H\n#define MAIN_FRAME_H\n\n\/\/(*Headers(MainFrame)\n#include <wx\/listctrl.h>\n#include <wx\/menu.h>\n#include <wx\/panel.h>\n#include <wx\/button.h>\n#include <wx\/frame.h>\n#include <wx\/statusbr.h>\n\/\/*)\n\n#include \"..\/Partmod\/disk.h\"\n#include \"..\/Partmod\/disk_exception.h\"\n\n#define S_PARTITION 1\n#define S_FREE_SPACE 2\n\n\n\n\nstruct sel_type\n{\n int type;\n uint32_t flags;\n};\n\nstruct lvlist\n{\nstd::string partition,\n type,\n fs_type,\n size,\n free,\n begin_sect,\n last_sect,\n mountpoint;\n\nint num;\n\nint selection_type;\nuint32_t flags;\n\n\n};\n\nclass MainFrame: public wxFrame\n{\n\tpublic:\n\n\t\tMainFrame(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);\n\t\tvirtual ~MainFrame();\n\n\t\t\/\/(*Declarations(MainFrame)\n\t\twxMenuItem* MenuOpenDiskImage;\n\t\twxMenuItem* MenuAbout;\n\t\twxListView* partitionList;\n\t\twxListView* diskList;\n\t\twxMenu* menuPartition;\n\t\twxMenuItem* MenuRestoreBackup;\n\t\twxMenuItem* MenuSaveChanges;\n\t\twxMenu* menuActions;\n\t\twxMenuItem* MenuSetInactive;\n\t\twxButton* Button1;\n\t\twxMenuItem* MenuListGuid;\n\t\twxMenuItem* MenuDeletePartition;\n\t\twxPanel* Panel1;\n\t\twxMenuItem* MenuCloseDisk;\n\t\twxMenuItem* MenuPartitionProperties;\n\t\twxButton* Button2;\n\t\twxMenuItem* MenuSetActive;\n\t\twxMenu* menuHelp;\n\t\twxMenuItem* MenuCreateBackup;\n\t\twxStatusBar* StatusBar1;\n\t\twxMenu* menuTools;\n\t\twxMenu* menuDisk;\n\t\twxMenuItem* MenuWipePartition;\n\t\twxMenuItem* MenuCreatePartition;\n\t\twxMenuItem* MenuQuit;\n\t\twxMenuBar* menuBar;\n\t\t\/\/*)\n\n\tprotected:\n\n\t\t\/\/(*Identifiers(MainFrame)\n\t\tstatic const long ID_LISTVIEW1;\n\t\tstatic const long ID_LISTVIEW2;\n\t\tstatic const long ID_BUTTON1;\n\t\tstatic const long ID_BUTTON2;\n\t\tstatic const long ID_PANEL1;\n\t\tstatic const long ID_SAVE_CHANGES;\n\t\tstatic const long ID_QUIT;\n\t\tstatic const long ID_CLOSE_DISK;\n\t\tstatic const long ID_OPEN_DISK_IMAGE;\n\t\tstatic const long ID_CREATE_BACKUP;\n\t\tstatic const long ID_RESTORE_BACKUP;\n\t\tstatic const long ID_CREATE_PARTITION;\n\t\tstatic const long ID_DELETE_PARTITION;\n\t\tstatic const long ID_SET_ACTIVE;\n\t\tstatic const long ID_SET_INACTIVE;\n\t\tstatic const long ID_PARTITION_PROPERTIES;\n\t\tstatic const long ID_WIPE_PARTITION;\n\t\tstatic const long ID_LIST_GUID;\n\t\tstatic const long ID_ABOUT;\n\t\tstatic const long ID_STATUSBAR1;\n\t\t\/\/*)\n\n\tprivate:\n\t Disk *disk;\n std::vector<lvlist> disk_structure; \/\/ list of partition and free space slices\n int selected_partition,selected_frs;\n\n\t\t\/\/(*Handlers(MainFrame)\n\t\tvoid OndiskListItemActivated(wxListEvent& event);\n\t\tvoid OnMenuCloseDiskSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSaveChangesSelected(wxCommandEvent& event);\n\t\tvoid OnMenuQuitSelected(wxCommandEvent& event);\n\t\tvoid OnMenuOpenDiskImageSelected(wxCommandEvent& event);\n\t\tvoid OnMenuCreateBackupSelected(wxCommandEvent& event);\n\t\tvoid OnMenuRestoreBackupSelected(wxCommandEvent& event);\n\t\tvoid OnMenuCreatePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuDeletePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSetActiveSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSetInactiveSelected(wxCommandEvent& event);\n\t\tvoid OnMenuWipePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuListGuidSelected(wxCommandEvent& event);\n\t\tvoid OnMenuAboutSelected(wxCommandEvent& event);\n\t\tvoid OnPartitionListItemActivated(wxListEvent& event);\n\t\tvoid OnPartitionListItemRClick(wxListEvent& event);\n\t\tvoid OnMenuPartitionPropertiesSelected(wxCommandEvent& event);\n\t\tvoid OnPartitionListItemDeselect(wxListEvent& event);\n\t\t\/\/*)\n void OnPartitionListPopupClick(wxListEvent& event);\n\n\n void refresh_disk_list();\n void refresh_partition_list();\n\n\t\tDECLARE_EVENT_TABLE()\n};\n\n#endif\n<commit_msg>git-svn-id: svn:\/\/svn.code.sf.net\/p\/partmodproject\/code\/trunk@23 3d63fe75-a90b-4577-b595-b0b07fb0d485<commit_after>#ifndef MAIN_FRAME_H\n#define MAIN_FRAME_H\n\n\/\/(*Headers(MainFrame)\n#include <wx\/listctrl.h>\n#include <wx\/menu.h>\n#include <wx\/panel.h>\n#include <wx\/button.h>\n#include <wx\/frame.h>\n#include <wx\/statusbr.h>\n\/\/*)\n\n#include \"..\/Partmod\/disk.h\"\n#include \"..\/Partmod\/disk_exception.h\"\n\n#define S_PARTITION 1\n#define S_FREE_SPACE 2\n\n\nstruct lvlist\n{\nstd::string partition,\n type,\n fs_type,\n size,\n free,\n begin_sect,\n last_sect,\n mountpoint;\n\nint num;\n\nint selection_type;\nuint32_t flags;\n\n\n};\n\nclass MainFrame: public wxFrame\n{\n\tpublic:\n\n\t\tMainFrame(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);\n\t\tvirtual ~MainFrame();\n\n\t\t\/\/(*Declarations(MainFrame)\n\t\twxMenuItem* MenuOpenDiskImage;\n\t\twxMenuItem* MenuAbout;\n\t\twxListView* partitionList;\n\t\twxListView* diskList;\n\t\twxMenu* menuPartition;\n\t\twxMenuItem* MenuRestoreBackup;\n\t\twxMenuItem* MenuSaveChanges;\n\t\twxMenu* menuActions;\n\t\twxMenuItem* MenuSetInactive;\n\t\twxMenuItem* MenuListGuid;\n\t\twxMenuItem* MenuDeletePartition;\n\t\twxPanel* Panel1;\n\t\twxMenuItem* MenuCloseDisk;\n\t\twxMenuItem* MenuPartitionProperties;\n\t\twxMenuItem* MenuSetActive;\n\t\twxButton* ButtonSaveChanges;\n\t\twxMenu* menuHelp;\n\t\twxMenuItem* MenuCreateBackup;\n\t\twxStatusBar* StatusBar1;\n\t\twxMenu* menuTools;\n\t\twxButton* ButtonQuit;\n\t\twxMenu* menuDisk;\n\t\twxMenuItem* MenuWipePartition;\n\t\twxMenuItem* MenuCreatePartition;\n\t\twxMenuItem* MenuQuit;\n\t\twxMenuBar* menuBar;\n\t\t\/\/*)\n\n\tprotected:\n\n\t\t\/\/(*Identifiers(MainFrame)\n\t\tstatic const long ID_LISTVIEW1;\n\t\tstatic const long ID_LISTVIEW2;\n\t\tstatic const long ID_BUTTON1;\n\t\tstatic const long ID_BUTTON2;\n\t\tstatic const long ID_PANEL1;\n\t\tstatic const long ID_SAVE_CHANGES;\n\t\tstatic const long ID_QUIT;\n\t\tstatic const long ID_CLOSE_DISK;\n\t\tstatic const long ID_OPEN_DISK_IMAGE;\n\t\tstatic const long ID_CREATE_BACKUP;\n\t\tstatic const long ID_RESTORE_BACKUP;\n\t\tstatic const long ID_CREATE_PARTITION;\n\t\tstatic const long ID_DELETE_PARTITION;\n\t\tstatic const long ID_SET_ACTIVE;\n\t\tstatic const long ID_SET_INACTIVE;\n\t\tstatic const long ID_PARTITION_PROPERTIES;\n\t\tstatic const long ID_WIPE_PARTITION;\n\t\tstatic const long ID_LIST_GUID;\n\t\tstatic const long ID_ABOUT;\n\t\tstatic const long ID_STATUSBAR1;\n\t\t\/\/*)\n\n\tprivate:\n\t Disk *disk;\n std::vector<lvlist> disk_structure; \/\/ list of partition and free space slices\n int selected_partition,selected_frs;\n\n\t\t\/\/(*Handlers(MainFrame)\n\t\tvoid OndiskListItemActivated(wxListEvent& event);\n\t\tvoid OnMenuCloseDiskSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSaveChangesSelected(wxCommandEvent& event);\n\t\tvoid OnMenuQuitSelected(wxCommandEvent& event);\n\t\tvoid OnMenuOpenDiskImageSelected(wxCommandEvent& event);\n\t\tvoid OnMenuCreateBackupSelected(wxCommandEvent& event);\n\t\tvoid OnMenuRestoreBackupSelected(wxCommandEvent& event);\n\t\tvoid OnMenuCreatePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuDeletePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSetActiveSelected(wxCommandEvent& event);\n\t\tvoid OnMenuSetInactiveSelected(wxCommandEvent& event);\n\t\tvoid OnMenuWipePartitionSelected(wxCommandEvent& event);\n\t\tvoid OnMenuListGuidSelected(wxCommandEvent& event);\n\t\tvoid OnMenuAboutSelected(wxCommandEvent& event);\n\t\tvoid OnPartitionListItemActivated(wxListEvent& event);\n\t\tvoid OnPartitionListItemRClick(wxListEvent& event);\n\t\tvoid OnMenuPartitionPropertiesSelected(wxCommandEvent& event);\n\t\tvoid OnPartitionListItemDeselect(wxListEvent& event);\n\t\t\/\/*)\n void OnPartitionListPopupClick(wxListEvent& event);\n\n\n void refresh_disk_list();\n void refresh_partition_list();\n\n\t\tDECLARE_EVENT_TABLE()\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix build errors with latest ibus<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * ZoteroCollections.cpp\n *\n * Copyright (C) 2009-20 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"ZoteroCollections.hpp\"\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/json\/Json.hpp>\n\n#include <core\/Hash.hpp>\n\n#include <core\/FileSerializer.hpp>\n\n#include <session\/prefs\/UserState.hpp>\n#include <session\/prefs\/UserPrefs.hpp>\n#include <session\/SessionModuleContext.hpp>\n#include <session\/projects\/SessionProjects.hpp>\n#include <session\/SessionAsyncDownloadFile.hpp>\n\n#include \"ZoteroCollectionsLocal.hpp\"\n#include \"ZoteroCollectionsWeb.hpp\"\n#include \"ZoteroUtil.hpp\"\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace zotero {\nnamespace collections {\n\nnamespace {\n\nconst char * const kIndexFile = \"INDEX\";\nconst char * const kFile = \"file\";\n\nFilePath collectionsCacheDir(const std::string& type, const std::string& context)\n{\n \/\/ cache dir name (depends on whether bbt is enabled as when that changes it should invalidate all cache entries)\n std::string dirName = \"libraries\";\n if (session::prefs::userState().zoteroUseBetterBibtex())\n dirName += \"-bbt\";\n\n \/\/ ~\/.local\/share\/rstudio\/zotero\/libraries\n FilePath cachePath = module_context::userScratchPath()\n .completeChildPath(\"zotero\")\n .completeChildPath(dirName)\n .completeChildPath(type)\n .completeChildPath(context);\n Error error = cachePath.ensureDirectory();\n if (error)\n LOG_ERROR(error);\n return cachePath;\n}\n\nstruct IndexedCollection\n{\n bool empty() const { return file.empty(); }\n int version;\n std::string file;\n std::string key;\n std::string parentKey;\n};\n\nstd::map<std::string,IndexedCollection> collectionsCacheIndex(const FilePath& cacheDir)\n{\n std::map<std::string,IndexedCollection> index;\n\n FilePath indexFile = cacheDir.completeChildPath(kIndexFile);\n if (indexFile.exists())\n {\n std::string indexContents;\n Error error = core::readStringFromFile(indexFile, &indexContents);\n if (!error)\n {\n json::Object indexJson;\n error = indexJson.parse(indexContents);\n if (!error)\n {\n std::for_each(indexJson.begin(), indexJson.end(), [&index](json::Object::Member member) {\n\n json::Object entryJson = member.getValue().getObject();\n IndexedCollection coll;\n coll.version = entryJson[kVersion].getInt();\n coll.file = entryJson[kFile].getString();\n coll.key = entryJson[kKey].getString();\n coll.parentKey = entryJson[kParentKey].getString();\n index.insert(std::make_pair(member.getName(),coll));\n });\n }\n }\n\n if (error)\n LOG_ERROR(error);\n }\n\n return index;\n}\n\nvoid updateCollectionsCacheIndex(const FilePath& cacheDir, const std::map<std::string,IndexedCollection>& index)\n{\n \/\/ create json for index\n json::Object indexJson;\n for (auto item : index)\n {\n json::Object collJson;\n collJson[kVersion] = item.second.version;\n collJson[kFile] = item.second.file;\n collJson[kKey] = item.second.key;\n collJson[kParentKey] = item.second.parentKey;\n indexJson[item.first] = collJson;\n }\n\n \/\/ write index\n FilePath indexFile = cacheDir.completeChildPath(kIndexFile);\n Error error = core::writeStringToFile(indexFile, indexJson.writeFormatted());\n if (error)\n LOG_ERROR(error);\n}\n\nError readCollection(const FilePath& filePath, ZoteroCollection* pCollection)\n{\n std::string cacheContents;\n Error error = core::readStringFromFile(filePath, &cacheContents);\n if (error)\n return error;\n\n json::Object collectionJson;\n error = collectionJson.parse(cacheContents);\n if (error)\n return error;\n\n pCollection->name = collectionJson[kName].getString();\n pCollection->version = collectionJson[kVersion].getInt();\n pCollection->key = collectionJson[kKey].getString();\n pCollection->parentKey = collectionJson[kParentKey].getString();\n pCollection->items = collectionJson[kItems].getArray();\n\n return Success();\n}\n\n\nZoteroCollection cachedCollection(const std::string& type, const std::string& context, const std::string& name)\n{\n ZoteroCollection collection;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (!coll.empty())\n {\n FilePath cachePath = cacheDir.completeChildPath(coll.file);\n Error error = readCollection(cachePath, &collection);\n if (error)\n LOG_ERROR(error);\n }\n return collection;\n}\n\nZoteroCollectionSpec cachedCollectionSpec(const std::string& type, const std::string& context, const std::string& name)\n{\n ZoteroCollectionSpec spec;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (!coll.empty())\n {\n spec.name = name;\n spec.version = coll.version;\n }\n return spec;\n}\n\nZoteroCollectionSpecs cachedCollectionsSpecs(const std::string& type, const std::string& context)\n{\n ZoteroCollectionSpecs specs;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n for (auto entry : index)\n {\n ZoteroCollectionSpec spec(entry.first, entry.second.key, entry.second.parentKey, entry.second.version);\n specs.push_back(spec);\n }\n return specs;\n}\n\nvoid updateCachedCollection(const std::string& type, const std::string& context, const std::string& name, const ZoteroCollection& collection)\n{\n \/\/ update index\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (coll.empty())\n coll.file = core::system::generateShortenedUuid();\n coll.version = collection.version;\n index[name] = coll;\n updateCollectionsCacheIndex(cacheDir, index);\n\n \/\/ write the collection\n json::Object collectionJson;\n collectionJson[kName] = collection.name;\n collectionJson[kVersion] = collection.version;\n collectionJson[kKey] = collection.key;\n collectionJson[kParentKey] = collection.parentKey;\n collectionJson[kItems] = collection.items;\n Error error = core::writeStringToFile(cacheDir.completeChildPath(coll.file), collectionJson.writeFormatted());\n if (error)\n LOG_ERROR(error);\n}\n\n\n\/\/ repsond with either a collection from the server cache or just name\/version if the client\n\/\/ already has the same version\nZoteroCollection responseFromServerCache(const std::string& type,\n const std::string& apiKey,\n const std::string& collection,\n const ZoteroCollectionSpecs& clientCacheSpecs)\n{\n ZoteroCollection cached = cachedCollection(type, apiKey, collection);\n if (!cached.empty() )\n {\n \/\/ see if the client specs already indicate an up to date version\n ZoteroCollectionSpecs::const_iterator clientIt = std::find_if(clientCacheSpecs.begin(), clientCacheSpecs.end(), [cached](ZoteroCollectionSpec spec) {\n return spec.name == cached.name && spec.version == cached.version;\n });\n if (clientIt == clientCacheSpecs.end())\n {\n \/\/ client spec didn't match, return cached collection\n TRACE(\"Returning server cache for \" + collection, cached.items.getSize());\n return cached;\n }\n else\n {\n \/\/ client had up to date version, just return the spec w\/ no items\n TRACE(\"Using client cache for \" + collection);\n return ZoteroCollection(*clientIt);\n }\n }\n else\n {\n return ZoteroCollection();\n }\n\n}\n\nstruct Connection\n{\n bool empty() const { return type.length() == 0; }\n std::string type;\n std::string context;\n std::string cacheContext;\n ZoteroCollectionSource source;\n};\n\nConnection zoteroConnection()\n{\n \/\/ use local connection if available for 'auto'\n std::string type = prefs::userState().zoteroConnectionType();\n if ((type.empty() || type == kZoteroConnectionTypeAuto) && localZoteroAvailable())\n type = kZoteroConnectionTypeLocal;\n\n \/\/ return empty connection if it's none or auto (as auto would have already been resolved)\n if (type == kZoteroConnectionTypeAuto || type == kZoteroConnectionTypeNone)\n {\n return Connection();\n }\n\n \/\/ initialize context\n std::string context;\n if (type == kZoteroConnectionTypeLocal)\n {\n FilePath localDataDir = zoteroDataDirectory();\n if (!localDataDir.isEmpty())\n {\n if (localDataDir.exists())\n context = localDataDir.getAbsolutePath();\n else\n LOG_ERROR(core::fileNotFoundError(localDataDir, ERROR_LOCATION));\n }\n }\n else\n {\n context = prefs::userState().zoteroApiKey();\n }\n\n \/\/ if we have a context then proceed to fill out the connection, otherwise\n \/\/ just return an empty connection. we wouldn't have a context if we were\n \/\/ configured for a local connection (the default) but there was no zotero\n \/\/ data directory. we also woudln't have a context if we were configured\n \/\/ for a web connection and there was no zotero API key\n if (!context.empty())\n {\n Connection connection;\n connection.type = type;\n connection.context = context;\n \/\/ use a hash of the context for the cacheContext (as it might not be a valid directory name)\n connection.cacheContext = core::hash::crc32HexHash(context);\n connection.source = type == kZoteroConnectionTypeLocal ? collections::localCollections() : collections::webCollections();\n return connection;\n }\n else\n {\n return Connection();\n }\n}\n\n\n} \/\/ end anonymous namespace\n\nconst char * const kName = \"name\";\nconst char * const kVersion = \"version\";\nconst char * const kKey = \"key\";\nconst char * const kParentKey = \"parentKey\";\nconst char * const kItems = \"items\";\n\nconst int kNoVersion = -1;\n\nZoteroCollectionSpec findParentSpec(const ZoteroCollectionSpec& spec, const ZoteroCollectionSpecs& specs)\n{\n \/\/ search for parentKey if we have one\n if (!spec.parentKey.empty())\n {\n auto it = std::find_if(specs.begin(), specs.end(), [spec](const ZoteroCollectionSpec& s) { return s.key == spec.parentKey; });\n if (it != specs.end())\n return *it;\n }\n\n \/\/ not found\n return ZoteroCollectionSpec();\n}\n\n\nvoid getCollectionSpecs(std::vector<std::string> collections, ZoteroCollectionSpecsHandler handler)\n{\n \/\/ get connection if we have one\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n conn.source.getCollectionSpecs(conn.context, collections, handler);\n }\n else\n {\n handler(Success(), std::vector<ZoteroCollectionSpec>());\n }\n}\n\nvoid getLibraryNames(ZoteroLibrariesHandler handler)\n{\n \/\/ get connection if we have one\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n conn.source.getLibraryNames(conn.context, handler);\n }\n else\n {\n handler(Success(), std::vector<std::string>());\n }\n}\n\nvoid getCollections(std::vector<std::string> collections,\n ZoteroCollectionSpecs cacheSpecs,\n bool useCache,\n ZoteroCollectionsHandler handler)\n{ \n \/\/ clear out client cache specs if the cache is disabled\n if (!useCache)\n cacheSpecs.clear();\n\n \/\/ get connection if we have o ne\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n \/\/ create a set of specs based on what we have in our server cache (as we always want to keep our cache up to date)\n ZoteroCollectionSpecs serverCacheSpecs;\n if (useCache)\n {\n \/\/ request for explicit list of collections, provide specs for matching collections from the server cache\n if (!collections.empty())\n {\n std::transform(collections.begin(), collections.end(), std::back_inserter(serverCacheSpecs), [conn](std::string name) {\n ZoteroCollectionSpec cacheSpec(name);\n ZoteroCollectionSpec cached = cachedCollectionSpec(conn.type, conn.cacheContext, name);\n if (!cached.empty())\n cacheSpec.version = cached.version;\n return cacheSpec;\n });\n }\n\n \/\/ request for all collections, provide specs for all collections in the server cache\n else\n {\n serverCacheSpecs = cachedCollectionsSpecs(conn.type, conn.cacheContext);\n }\n }\n\n \/\/ get collections\n conn.source.getCollections(conn.context, collections, serverCacheSpecs,\n [conn, collections, cacheSpecs, serverCacheSpecs, handler](Error error, ZoteroCollections webCollections, std::string warning) {\n\n \/\/ process response -- for any collection returned w\/ a version higher than that in the\n \/\/ cache, update the cache. for any collection available (from cache or web) with a version\n \/\/ higher than that of the client request, return the updated items (else return no items) \n if (!error)\n {\n ZoteroCollections responseCollections;\n for (auto webCollection : webCollections)\n {\n \/\/ see if the server side cache needs updating\n ZoteroCollectionSpecs::const_iterator it = std::find_if(serverCacheSpecs.begin(), serverCacheSpecs.end(), [webCollection](ZoteroCollectionSpec cacheSpec) {\n return cacheSpec.name == webCollection.name && cacheSpec.version == webCollection.version;\n });\n \/\/ need to update the cache -- do so and then return the just cached copy to the client\n if (it == serverCacheSpecs.end())\n {\n TRACE(\"Updating server cache for \" + webCollection.name);\n updateCachedCollection(conn.type, conn.cacheContext, webCollection.name, webCollection);\n TRACE(\"Returning server cache for \" + webCollection.name);\n responseCollections.push_back(webCollection);\n }\n\n \/\/ we have a cache for this collection, check to see if it is recent enough (and in that\n \/\/ case don't return the items to the client)\n else\n {\n \/\/ see we can satisfy the request from our cache\n ZoteroCollection cached = responseFromServerCache(conn.type, conn.cacheContext, webCollection.name, cacheSpecs);\n if (!cached.empty())\n {\n responseCollections.push_back(cached);\n }\n else\n { \n \/\/ shouldn't be possible to get here (as the initial condition tested in the loop ensures\n \/\/ that we have a cached collection)\n TRACE(\"Unexpected failure to find cache for \" + webCollection.name);\n }\n }\n }\n\n handler(Success(), responseCollections, warning);\n\n \/\/ for host errors try to serve from the cache\n } else if (isHostError(core::errorDescription(error))) {\n\n ZoteroCollections responseCollections;\n for (auto collection : collections)\n {\n ZoteroCollection cached = responseFromServerCache(conn.type, conn.cacheContext, collection, cacheSpecs);\n if (!cached.empty())\n responseCollections.push_back(cached);\n }\n handler(Success(),responseCollections, warning);\n\n \/\/ report error\n } else {\n handler(error, std::vector<ZoteroCollection>(), warning);\n }\n\n\n });\n }\n else\n {\n handler(Success(), std::vector<ZoteroCollection>(), \"\");\n }\n\n}\n\n} \/\/ end namespace collections\n} \/\/ end namespace zotero\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n<commit_msg>rename zotero cache dir<commit_after>\/*\n * ZoteroCollections.cpp\n *\n * Copyright (C) 2009-20 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"ZoteroCollections.hpp\"\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/json\/Json.hpp>\n\n#include <core\/Hash.hpp>\n\n#include <core\/FileSerializer.hpp>\n\n#include <session\/prefs\/UserState.hpp>\n#include <session\/prefs\/UserPrefs.hpp>\n#include <session\/SessionModuleContext.hpp>\n#include <session\/projects\/SessionProjects.hpp>\n#include <session\/SessionAsyncDownloadFile.hpp>\n\n#include \"ZoteroCollectionsLocal.hpp\"\n#include \"ZoteroCollectionsWeb.hpp\"\n#include \"ZoteroUtil.hpp\"\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace zotero {\nnamespace collections {\n\nnamespace {\n\nconst char * const kIndexFile = \"INDEX\";\nconst char * const kFile = \"file\";\n\nFilePath collectionsCacheDir(const std::string& type, const std::string& context)\n{\n \/\/ cache dir name (depends on whether bbt is enabled as when that changes it should invalidate all cache entries)\n std::string dirName = \"libraries-cache\";\n if (session::prefs::userState().zoteroUseBetterBibtex())\n dirName += \"-bbt\";\n\n \/\/ ~\/.local\/share\/rstudio\/zotero\/libraries\n FilePath cachePath = module_context::userScratchPath()\n .completeChildPath(\"zotero\")\n .completeChildPath(dirName)\n .completeChildPath(type)\n .completeChildPath(context);\n Error error = cachePath.ensureDirectory();\n if (error)\n LOG_ERROR(error);\n return cachePath;\n}\n\nstruct IndexedCollection\n{\n bool empty() const { return file.empty(); }\n int version;\n std::string file;\n std::string key;\n std::string parentKey;\n};\n\nstd::map<std::string,IndexedCollection> collectionsCacheIndex(const FilePath& cacheDir)\n{\n std::map<std::string,IndexedCollection> index;\n\n FilePath indexFile = cacheDir.completeChildPath(kIndexFile);\n if (indexFile.exists())\n {\n std::string indexContents;\n Error error = core::readStringFromFile(indexFile, &indexContents);\n if (!error)\n {\n json::Object indexJson;\n error = indexJson.parse(indexContents);\n if (!error)\n {\n std::for_each(indexJson.begin(), indexJson.end(), [&index](json::Object::Member member) {\n\n json::Object entryJson = member.getValue().getObject();\n IndexedCollection coll;\n coll.version = entryJson[kVersion].getInt();\n coll.file = entryJson[kFile].getString();\n coll.key = entryJson[kKey].getString();\n coll.parentKey = entryJson[kParentKey].getString();\n index.insert(std::make_pair(member.getName(),coll));\n });\n }\n }\n\n if (error)\n LOG_ERROR(error);\n }\n\n return index;\n}\n\nvoid updateCollectionsCacheIndex(const FilePath& cacheDir, const std::map<std::string,IndexedCollection>& index)\n{\n \/\/ create json for index\n json::Object indexJson;\n for (auto item : index)\n {\n json::Object collJson;\n collJson[kVersion] = item.second.version;\n collJson[kFile] = item.second.file;\n collJson[kKey] = item.second.key;\n collJson[kParentKey] = item.second.parentKey;\n indexJson[item.first] = collJson;\n }\n\n \/\/ write index\n FilePath indexFile = cacheDir.completeChildPath(kIndexFile);\n Error error = core::writeStringToFile(indexFile, indexJson.writeFormatted());\n if (error)\n LOG_ERROR(error);\n}\n\nError readCollection(const FilePath& filePath, ZoteroCollection* pCollection)\n{\n std::string cacheContents;\n Error error = core::readStringFromFile(filePath, &cacheContents);\n if (error)\n return error;\n\n json::Object collectionJson;\n error = collectionJson.parse(cacheContents);\n if (error)\n return error;\n\n pCollection->name = collectionJson[kName].getString();\n pCollection->version = collectionJson[kVersion].getInt();\n pCollection->key = collectionJson[kKey].getString();\n pCollection->parentKey = collectionJson[kParentKey].getString();\n pCollection->items = collectionJson[kItems].getArray();\n\n return Success();\n}\n\n\nZoteroCollection cachedCollection(const std::string& type, const std::string& context, const std::string& name)\n{\n ZoteroCollection collection;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (!coll.empty())\n {\n FilePath cachePath = cacheDir.completeChildPath(coll.file);\n Error error = readCollection(cachePath, &collection);\n if (error)\n LOG_ERROR(error);\n }\n return collection;\n}\n\nZoteroCollectionSpec cachedCollectionSpec(const std::string& type, const std::string& context, const std::string& name)\n{\n ZoteroCollectionSpec spec;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (!coll.empty())\n {\n spec.name = name;\n spec.version = coll.version;\n }\n return spec;\n}\n\nZoteroCollectionSpecs cachedCollectionsSpecs(const std::string& type, const std::string& context)\n{\n ZoteroCollectionSpecs specs;\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n for (auto entry : index)\n {\n ZoteroCollectionSpec spec(entry.first, entry.second.key, entry.second.parentKey, entry.second.version);\n specs.push_back(spec);\n }\n return specs;\n}\n\nvoid updateCachedCollection(const std::string& type, const std::string& context, const std::string& name, const ZoteroCollection& collection)\n{\n \/\/ update index\n FilePath cacheDir = collectionsCacheDir(type, context);\n auto index = collectionsCacheIndex(cacheDir);\n auto coll = index[name];\n if (coll.empty())\n coll.file = core::system::generateShortenedUuid();\n coll.version = collection.version;\n index[name] = coll;\n updateCollectionsCacheIndex(cacheDir, index);\n\n \/\/ write the collection\n json::Object collectionJson;\n collectionJson[kName] = collection.name;\n collectionJson[kVersion] = collection.version;\n collectionJson[kKey] = collection.key;\n collectionJson[kParentKey] = collection.parentKey;\n collectionJson[kItems] = collection.items;\n Error error = core::writeStringToFile(cacheDir.completeChildPath(coll.file), collectionJson.writeFormatted());\n if (error)\n LOG_ERROR(error);\n}\n\n\n\/\/ repsond with either a collection from the server cache or just name\/version if the client\n\/\/ already has the same version\nZoteroCollection responseFromServerCache(const std::string& type,\n const std::string& apiKey,\n const std::string& collection,\n const ZoteroCollectionSpecs& clientCacheSpecs)\n{\n ZoteroCollection cached = cachedCollection(type, apiKey, collection);\n if (!cached.empty() )\n {\n \/\/ see if the client specs already indicate an up to date version\n ZoteroCollectionSpecs::const_iterator clientIt = std::find_if(clientCacheSpecs.begin(), clientCacheSpecs.end(), [cached](ZoteroCollectionSpec spec) {\n return spec.name == cached.name && spec.version == cached.version;\n });\n if (clientIt == clientCacheSpecs.end())\n {\n \/\/ client spec didn't match, return cached collection\n TRACE(\"Returning server cache for \" + collection, cached.items.getSize());\n return cached;\n }\n else\n {\n \/\/ client had up to date version, just return the spec w\/ no items\n TRACE(\"Using client cache for \" + collection);\n return ZoteroCollection(*clientIt);\n }\n }\n else\n {\n return ZoteroCollection();\n }\n\n}\n\nstruct Connection\n{\n bool empty() const { return type.length() == 0; }\n std::string type;\n std::string context;\n std::string cacheContext;\n ZoteroCollectionSource source;\n};\n\nConnection zoteroConnection()\n{\n \/\/ use local connection if available for 'auto'\n std::string type = prefs::userState().zoteroConnectionType();\n if ((type.empty() || type == kZoteroConnectionTypeAuto) && localZoteroAvailable())\n type = kZoteroConnectionTypeLocal;\n\n \/\/ return empty connection if it's none or auto (as auto would have already been resolved)\n if (type == kZoteroConnectionTypeAuto || type == kZoteroConnectionTypeNone)\n {\n return Connection();\n }\n\n \/\/ initialize context\n std::string context;\n if (type == kZoteroConnectionTypeLocal)\n {\n FilePath localDataDir = zoteroDataDirectory();\n if (!localDataDir.isEmpty())\n {\n if (localDataDir.exists())\n context = localDataDir.getAbsolutePath();\n else\n LOG_ERROR(core::fileNotFoundError(localDataDir, ERROR_LOCATION));\n }\n }\n else\n {\n context = prefs::userState().zoteroApiKey();\n }\n\n \/\/ if we have a context then proceed to fill out the connection, otherwise\n \/\/ just return an empty connection. we wouldn't have a context if we were\n \/\/ configured for a local connection (the default) but there was no zotero\n \/\/ data directory. we also woudln't have a context if we were configured\n \/\/ for a web connection and there was no zotero API key\n if (!context.empty())\n {\n Connection connection;\n connection.type = type;\n connection.context = context;\n \/\/ use a hash of the context for the cacheContext (as it might not be a valid directory name)\n connection.cacheContext = core::hash::crc32HexHash(context);\n connection.source = type == kZoteroConnectionTypeLocal ? collections::localCollections() : collections::webCollections();\n return connection;\n }\n else\n {\n return Connection();\n }\n}\n\n\n} \/\/ end anonymous namespace\n\nconst char * const kName = \"name\";\nconst char * const kVersion = \"version\";\nconst char * const kKey = \"key\";\nconst char * const kParentKey = \"parentKey\";\nconst char * const kItems = \"items\";\n\nconst int kNoVersion = -1;\n\nZoteroCollectionSpec findParentSpec(const ZoteroCollectionSpec& spec, const ZoteroCollectionSpecs& specs)\n{\n \/\/ search for parentKey if we have one\n if (!spec.parentKey.empty())\n {\n auto it = std::find_if(specs.begin(), specs.end(), [spec](const ZoteroCollectionSpec& s) { return s.key == spec.parentKey; });\n if (it != specs.end())\n return *it;\n }\n\n \/\/ not found\n return ZoteroCollectionSpec();\n}\n\n\nvoid getCollectionSpecs(std::vector<std::string> collections, ZoteroCollectionSpecsHandler handler)\n{\n \/\/ get connection if we have one\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n conn.source.getCollectionSpecs(conn.context, collections, handler);\n }\n else\n {\n handler(Success(), std::vector<ZoteroCollectionSpec>());\n }\n}\n\nvoid getLibraryNames(ZoteroLibrariesHandler handler)\n{\n \/\/ get connection if we have one\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n conn.source.getLibraryNames(conn.context, handler);\n }\n else\n {\n handler(Success(), std::vector<std::string>());\n }\n}\n\nvoid getCollections(std::vector<std::string> collections,\n ZoteroCollectionSpecs cacheSpecs,\n bool useCache,\n ZoteroCollectionsHandler handler)\n{ \n \/\/ clear out client cache specs if the cache is disabled\n if (!useCache)\n cacheSpecs.clear();\n\n \/\/ get connection if we have o ne\n Connection conn = zoteroConnection();\n if (!conn.empty())\n {\n \/\/ create a set of specs based on what we have in our server cache (as we always want to keep our cache up to date)\n ZoteroCollectionSpecs serverCacheSpecs;\n if (useCache)\n {\n \/\/ request for explicit list of collections, provide specs for matching collections from the server cache\n if (!collections.empty())\n {\n std::transform(collections.begin(), collections.end(), std::back_inserter(serverCacheSpecs), [conn](std::string name) {\n ZoteroCollectionSpec cacheSpec(name);\n ZoteroCollectionSpec cached = cachedCollectionSpec(conn.type, conn.cacheContext, name);\n if (!cached.empty())\n cacheSpec.version = cached.version;\n return cacheSpec;\n });\n }\n\n \/\/ request for all collections, provide specs for all collections in the server cache\n else\n {\n serverCacheSpecs = cachedCollectionsSpecs(conn.type, conn.cacheContext);\n }\n }\n\n \/\/ get collections\n conn.source.getCollections(conn.context, collections, serverCacheSpecs,\n [conn, collections, cacheSpecs, serverCacheSpecs, handler](Error error, ZoteroCollections webCollections, std::string warning) {\n\n \/\/ process response -- for any collection returned w\/ a version higher than that in the\n \/\/ cache, update the cache. for any collection available (from cache or web) with a version\n \/\/ higher than that of the client request, return the updated items (else return no items) \n if (!error)\n {\n ZoteroCollections responseCollections;\n for (auto webCollection : webCollections)\n {\n \/\/ see if the server side cache needs updating\n ZoteroCollectionSpecs::const_iterator it = std::find_if(serverCacheSpecs.begin(), serverCacheSpecs.end(), [webCollection](ZoteroCollectionSpec cacheSpec) {\n return cacheSpec.name == webCollection.name && cacheSpec.version == webCollection.version;\n });\n \/\/ need to update the cache -- do so and then return the just cached copy to the client\n if (it == serverCacheSpecs.end())\n {\n TRACE(\"Updating server cache for \" + webCollection.name);\n updateCachedCollection(conn.type, conn.cacheContext, webCollection.name, webCollection);\n TRACE(\"Returning server cache for \" + webCollection.name);\n responseCollections.push_back(webCollection);\n }\n\n \/\/ we have a cache for this collection, check to see if it is recent enough (and in that\n \/\/ case don't return the items to the client)\n else\n {\n \/\/ see we can satisfy the request from our cache\n ZoteroCollection cached = responseFromServerCache(conn.type, conn.cacheContext, webCollection.name, cacheSpecs);\n if (!cached.empty())\n {\n responseCollections.push_back(cached);\n }\n else\n { \n \/\/ shouldn't be possible to get here (as the initial condition tested in the loop ensures\n \/\/ that we have a cached collection)\n TRACE(\"Unexpected failure to find cache for \" + webCollection.name);\n }\n }\n }\n\n handler(Success(), responseCollections, warning);\n\n \/\/ for host errors try to serve from the cache\n } else if (isHostError(core::errorDescription(error))) {\n\n ZoteroCollections responseCollections;\n for (auto collection : collections)\n {\n ZoteroCollection cached = responseFromServerCache(conn.type, conn.cacheContext, collection, cacheSpecs);\n if (!cached.empty())\n responseCollections.push_back(cached);\n }\n handler(Success(),responseCollections, warning);\n\n \/\/ report error\n } else {\n handler(error, std::vector<ZoteroCollection>(), warning);\n }\n\n\n });\n }\n else\n {\n handler(Success(), std::vector<ZoteroCollection>(), \"\");\n }\n\n}\n\n} \/\/ end namespace collections\n} \/\/ end namespace zotero\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_ALPHA_PREDECODER_HH__\n#define __ARCH_ALPHA_PREDECODER_HH__\n\n#include \"arch\/alpha\/types.hh\"\n#include \"base\/misc.hh\"\n#include \"config\/full_system.hh\"\n#include \"sim\/host.hh\"\n\nclass ThreadContext;\n\nnamespace AlphaISA\n{\n class Predecoder\n {\n protected:\n ThreadContext * tc;\n \/\/The extended machine instruction being generated\n ExtMachInst ext_inst;\n\n public:\n Predecoder(ThreadContext * _tc) : tc(_tc)\n {}\n\n ThreadContext * getTC()\n {\n return tc;\n }\n\n void setTC(ThreadContext * _tc)\n {\n tc = _tc;\n }\n\n void process()\n {\n }\n\n void reset()\n {}\n\n \/\/Use this to give data to the predecoder. This should be used\n \/\/when there is control flow.\n void moreBytes(Addr pc, Addr fetchPC, MachInst inst)\n {\n ext_inst = inst;\n#if FULL_SYSTEM\n if (pc && 0x1)\n ext_inst|=(static_cast<ExtMachInst>(pc & 0x1) << 32);\n#endif\n }\n\n bool needMoreBytes()\n {\n return true;\n }\n\n bool extMachInstReady()\n {\n return true;\n }\n\n \/\/This returns a constant reference to the ExtMachInst to avoid a copy\n const ExtMachInst & getExtMachInst()\n {\n return ext_inst;\n }\n };\n};\n\n#endif \/\/ __ARCH_ALPHA_PREDECODER_HH__\n<commit_msg>Alpha: Fix a long standing bug where all code ran as PAL code in FS.<commit_after>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_ALPHA_PREDECODER_HH__\n#define __ARCH_ALPHA_PREDECODER_HH__\n\n#include \"arch\/alpha\/types.hh\"\n#include \"base\/misc.hh\"\n#include \"config\/full_system.hh\"\n#include \"sim\/host.hh\"\n\nclass ThreadContext;\n\nnamespace AlphaISA\n{\n class Predecoder\n {\n protected:\n ThreadContext * tc;\n \/\/The extended machine instruction being generated\n ExtMachInst ext_inst;\n\n public:\n Predecoder(ThreadContext * _tc) : tc(_tc)\n {}\n\n ThreadContext * getTC()\n {\n return tc;\n }\n\n void setTC(ThreadContext * _tc)\n {\n tc = _tc;\n }\n\n void process()\n {\n }\n\n void reset()\n {}\n\n \/\/Use this to give data to the predecoder. This should be used\n \/\/when there is control flow.\n void moreBytes(Addr pc, Addr fetchPC, MachInst inst)\n {\n ext_inst = inst;\n#if FULL_SYSTEM\n ext_inst|=(static_cast<ExtMachInst>(pc & 0x1) << 32);\n#endif\n }\n\n bool needMoreBytes()\n {\n return true;\n }\n\n bool extMachInstReady()\n {\n return true;\n }\n\n \/\/This returns a constant reference to the ExtMachInst to avoid a copy\n const ExtMachInst & getExtMachInst()\n {\n return ext_inst;\n }\n };\n};\n\n#endif \/\/ __ARCH_ALPHA_PREDECODER_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2017 Joy Machine, LLC. All rights reserved.\n\n#include \"steelhunters.h\"\n\n#include \"ObjectPool.h\"\n\n#include \"DateTime.h\"\n\n#include \"IPooledObject.h\"\n\n\/\/ Console variable definition.\nstatic TAutoConsoleVariable< int > CVarDebugObjectPooling( TEXT( \"joy.DebugObjectPooling\" ), \n\t0,\n\tTEXT( \"Verbose output from the object pooling system for debugging.\" ),\n\tECVF_Default );\n\n\/\/ Static class definitions.\nconst int64 UObjectPool::kDefaultPruneStaleSeconds = 60;\n\nuint32 UObjectPool::IDCounter = 0;\nuint32 UObjectPool::PoolCount = 0;\n\n\/\/----------------------------------------------------------------------------------------------------\nUObjectPool::UObjectPool( const class FObjectInitializer& ObjectInitializer )\n: Name( *FString::Printf( TEXT( \"Pool-%d\" ), PoolCount ) )\n, PoolID( PoolCount )\n, PoolSizeOptimal( 256 )\n, PoolSizeMaximum( 2048 )\n, PruneStale( false )\n, PruneLastTimestamp( FDateTime::Now( ).ToUnixTimestamp( ) )\n, PruneStale_Seconds( kDefaultPruneStaleSeconds )\n{\n\tPool.Empty( );\n\n\t\/\/ Set this pool ID.\n\tPoolID = ++PoolCount;\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Just toss out some debug information.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Creating new pool (Pool Count: %d).\" ), PoolCount );\n\t\t}\n\t}\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::OnObjectReturn( IPooledObject* pObject )\n{\n\tcheck( pObject != nullptr );\n\n\t\/\/ Reset the object (pure virtual method, so the logic is reliant on the child class).\n\tpObject->IsActive = false;\n\tpObject->Reset( );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::Prune( )\n{\n\tconst int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );\n\tint32 prunedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tif( !pObject.IsStale( ) && pObject.IsValid( ) )\n\t\t{\n\t\t\t\/\/ The object pointer is either stale or no longer valid.\n\t\t\treturn false;\n\t\t}\n\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !pPooledObject->GetIsActive( ) && !pPooledObject->Check( ) || ( PruneStale && ( ( currentTime - pPooledObject->LastActiveTimestamp ) > PruneStale_Seconds ) ) )\n\t\t{\n\t\t\t\/\/ This object is invalid or stale. Remove it.\n\t\t\tif( pPooledObject != nullptr )\n\t\t\t{\n\t\t\t\t\/\/ Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.\n\t\t\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\t\t\tpPooledObject->DestroyInstance( );\n\t\t\t\tpPooledObject = nullptr;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Log the number of pruned objects.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool pruning logic completed (Pool: %s, Object Count: %d, Pruned Count: %d.\" ), *Name.ToString( ), Pool.Num( ), prunedObjectCount );\n\t\t}\n\t}\n\n\tPruneLastTimestamp = currentTime;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetName( const FName& PoolName )\n{\n\t\/\/ Just set the pool name; doesn't have to be unique.\n\tName = GenerateName( PoolName );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nFName UObjectPool::GenerateName( const FName& BaseName )\n{\n\treturn( *FString::Printf( TEXT( \"%s-%d\" ), *BaseName.ToString( ), PoolCount ) );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::Empty( bool SeparateActiveInstances )\n{\n\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\n\t\/\/ Remove all objects from the pool and destroy them (unless SeparateActiveInstances is true, in which case leave them alone for now).\n\tint32 destroyedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !( SeparateActiveInstances && ( pPooledObject != nullptr ) && pPooledObject->GetIsActive( ) ) )\n\t\t{\n\t\t\t\/\/ Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.\n\t\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\t\tpPooledObject->DestroyInstance( );\n\t\t\tpPooledObject = nullptr;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\tif( !SeparateActiveInstances )\n\t{\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Log the object destroyed count and the destruction of the pool.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool destroy completed (Pool: %s, Destroyed Object Count: %d).\" ), *Name.ToString( ), destroyedObjectCount );\n\t\t}\n\n\t\treturn;\n\t}\n\n\t\/\/ Now handle the separation of objects.\n\tint32 separatedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\tpPooledObject->OnPoolRemovalWhileActive( );\n\t\treturn true;\n\t} );\n\n\tif( debug )\n\t{\n\t\t\/\/ Log the object destroyed count and the destruction of the pool.\n\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool destroy completed with object separation (Pool: %s, Separated Object Count: %d, Destroyed Object Count: %d).\" ), *Name.ToString( ), separatedObjectCount, destroyedObjectCount );\n\t}\n\n#if !UE_BUILD_SHIPPING\n\tensure( Pool.Num( ) == 0 );\n#endif\t\/\/ !UE_BUILD_SHIPPING.\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nbool UObjectPool::Add( IPooledObject* ObjectIn, bool Active )\n{\n\tcheck( ObjectIn != nullptr );\n\n\t\/\/ Check to ensure that IPooledObject is a derivative of UObject.\n\tUObject* pUObject = dynamic_cast< UObject* >( ObjectIn );\n\n#if !UE_BUILD_SHIPPING\n\tensure( IsValid( pUObject ) );\n#endif\t\/\/ !UE_BUILD_SHIPPING.\n\n\t\/\/ Predicate to check if this object is already in the pool.\n\tconst uint32 objectID = ObjectIn->ID;\n\tif( Pool.ContainsByPredicate( [objectID]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\treturn( objectID == pPooledObject->ID );\n\t} ) )\n\t{\n\t\t\/\/ Object is already in the pool.\n\t\treturn false;\n\t}\n\n\t\/\/ Add this object to the pool.\n\tPool.Add( pUObject );\n\n\t\/\/ Set whether or not the object is active (if being added, it usually is), and give it an ID.\n\tObjectIn->IsActive = Active;\n\tObjectIn->ID = IDCounter++;\n\n\t\/\/ Setup the object's pool return delegate (executed when the object is deactivated).\n\tObjectIn->ReturnToPool.BindUObject( this, &UObjectPool::OnObjectReturn );\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Debug logging.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Adding object to pool (Pool: %s, Object Count: %d).\" ), *Name.ToString( ), Pool.Num( ) );\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\ntemplate< typename T >\nT* UObjectPool::GetPooledObject( )\n{\n\tIPooledObject* pPooledObject = GetPooledObject( );\n\tif( pPooledObject == nullptr )\n\t{\n\t\t\/\/ No valid pooled objects.\n\t\treturn nullptr;\n\t}\n\n\tT* pTemplateObject = Cast< T >( pPooledObject );\n\tcheck( IsValid( pTemplateObject ) );\n\n\treturn pTemplateObject;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nIPooledObject* UObjectPool::GetPooledObject( )\n{\n\tconst int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );\n\tbool executePrune = PruneStale && ( ( currentTime - PruneLastTimestamp ) > PruneStale_Seconds );\t\t\/\/ If this isn't true, then it may be time to prune anyway if the search finds an invalid object.\n\n\t\/\/ Find the first inactive and valid object.\n\tint32 idx = Pool.IndexOfByPredicate( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !pPooledObject->GetIsActive( ) )\n\t\t{\n\t\t\tif( !pPooledObject->Check( ) )\n\t\t\t{\n\t\t\t\t\/\/ This object is invalid. Prune the pool after this search.\n\t\t\t\texecutePrune = true;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\tif( idx == INDEX_NONE )\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Debug logging.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Unable to get a free object from the pool using ::GetPooledObject (Pool: %s, Object Count: %d).\" ), *Name.ToString( ), Pool.Num( ) );\n\t\t}\n\t}\n\n\t\/\/ Get the found valid object, remove its place in the array, and add it to the back for a more efficient check later.\n\t\/\/\tNOTE (trent, 12\/10\/17): Ensure that this is actually an optimization.\n\tUObject* pUObject = Pool[idx].Get( );\n\tIPooledObject* pValidObject = dynamic_cast< IPooledObject* >( pUObject );\n\tPool.RemoveAtSwap( idx, 1, false );\n\tPool.Add( pUObject );\n\n\t\/\/ Activate the object.\n\tpValidObject->IsActive = true;\n\tpValidObject->LastActiveTimestamp = FDateTime::Now( ).ToUnixTimestamp( );\n\n\tif( executePrune )\n\t{\n\t\t\/\/ Prune the pool if need be (or if it's just time).\n\t\t\/\/\tNOTE: Since the object that was just found has already been reactivated and given an updated timestamp, it won't be pruned.\n\t\tPrune( );\n\t}\n\n\treturn pValidObject;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetPruneStale( bool PruneStaleIn )\n{\n\tPruneStale = PruneStaleIn;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetPruneInactiveTime( int64 PruneInactivitySeconds )\n{\n\tPruneStale_Seconds = PruneInactivitySeconds;\n}<commit_msg>Fixed an occasional first-run crash with the pooling system.<commit_after>\/\/ Copyright 2015-2017 Joy Machine, LLC. All rights reserved.\n\n#include \"steelhunters.h\"\n\n#include \"ObjectPool.h\"\n\n#include \"DateTime.h\"\n\n#include \"IPooledObject.h\"\n\n\/\/ Console variable definition.\nstatic TAutoConsoleVariable< int > CVarDebugObjectPooling( TEXT( \"joy.DebugObjectPooling\" ), \n\t0,\n\tTEXT( \"Verbose output from the object pooling system for debugging.\" ),\n\tECVF_Default );\n\n\/\/ Static class definitions.\nconst int64 UObjectPool::kDefaultPruneStaleSeconds = 60;\n\nuint32 UObjectPool::IDCounter = 0;\nuint32 UObjectPool::PoolCount = 0;\n\n\/\/----------------------------------------------------------------------------------------------------\nUObjectPool::UObjectPool( const class FObjectInitializer& ObjectInitializer )\n: Name( *FString::Printf( TEXT( \"Pool-%d\" ), PoolCount ) )\n, PoolID( PoolCount )\n, PoolSizeOptimal( 256 )\n, PoolSizeMaximum( 2048 )\n, PruneStale( false )\n, PruneLastTimestamp( FDateTime::Now( ).ToUnixTimestamp( ) )\n, PruneStale_Seconds( kDefaultPruneStaleSeconds )\n{\n\tPool.Empty( );\n\n\t\/\/ Set this pool ID.\n\tPoolID = ++PoolCount;\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Just toss out some debug information.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Creating new pool (Pool Count: %d).\" ), PoolCount );\n\t\t}\n\t}\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::OnObjectReturn( IPooledObject* pObject )\n{\n\tcheck( pObject != nullptr );\n\n\t\/\/ Reset the object (pure virtual method, so the logic is reliant on the child class).\n\tpObject->IsActive = false;\n\tpObject->Reset( );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::Prune( )\n{\n\tconst int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );\n\tint32 prunedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tif( !pObject.IsStale( ) && pObject.IsValid( ) )\n\t\t{\n\t\t\t\/\/ The object pointer is either stale or no longer valid.\n\t\t\treturn false;\n\t\t}\n\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !pPooledObject->GetIsActive( ) && !pPooledObject->Check( ) || ( PruneStale && ( ( currentTime - pPooledObject->LastActiveTimestamp ) > PruneStale_Seconds ) ) )\n\t\t{\n\t\t\t\/\/ This object is invalid or stale. Remove it.\n\t\t\tif( pPooledObject != nullptr )\n\t\t\t{\n\t\t\t\t\/\/ Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.\n\t\t\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\t\t\tpPooledObject->DestroyInstance( );\n\t\t\t\tpPooledObject = nullptr;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Log the number of pruned objects.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool pruning logic completed (Pool: %s, Object Count: %d, Pruned Count: %d.\" ), *Name.ToString( ), Pool.Num( ), prunedObjectCount );\n\t\t}\n\t}\n\n\tPruneLastTimestamp = currentTime;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetName( const FName& PoolName )\n{\n\t\/\/ Just set the pool name; doesn't have to be unique.\n\tName = GenerateName( PoolName );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nFName UObjectPool::GenerateName( const FName& BaseName )\n{\n\treturn( *FString::Printf( TEXT( \"%s-%d\" ), *BaseName.ToString( ), PoolCount ) );\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::Empty( bool SeparateActiveInstances )\n{\n\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\n\t\/\/ Remove all objects from the pool and destroy them (unless SeparateActiveInstances is true, in which case leave them alone for now).\n\tint32 destroyedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !( SeparateActiveInstances && ( pPooledObject != nullptr ) && pPooledObject->GetIsActive( ) ) )\n\t\t{\n\t\t\t\/\/ Just in case any logic in ::Deactivate is necessary, execute that, and then the ::Destroy method.\n\t\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\t\tpPooledObject->DestroyInstance( );\n\t\t\tpPooledObject = nullptr;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\tif( !SeparateActiveInstances )\n\t{\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Log the object destroyed count and the destruction of the pool.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool destroy completed (Pool: %s, Destroyed Object Count: %d).\" ), *Name.ToString( ), destroyedObjectCount );\n\t\t}\n\n\t\treturn;\n\t}\n\n\t\/\/ Now handle the separation of objects.\n\tint32 separatedObjectCount = Pool.RemoveAll( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tpPooledObject->ReturnToPool.Unbind( );\n\n\t\tpPooledObject->OnPoolRemovalWhileActive( );\n\t\treturn true;\n\t} );\n\n\tif( debug )\n\t{\n\t\t\/\/ Log the object destroyed count and the destruction of the pool.\n\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool destroy completed with object separation (Pool: %s, Separated Object Count: %d, Destroyed Object Count: %d).\" ), *Name.ToString( ), separatedObjectCount, destroyedObjectCount );\n\t}\n\n#if !UE_BUILD_SHIPPING\n\tensure( Pool.Num( ) == 0 );\n#endif\t\/\/ !UE_BUILD_SHIPPING.\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nbool UObjectPool::Add( IPooledObject* ObjectIn, bool Active )\n{\n\tcheck( ObjectIn != nullptr );\n\n\t\/\/ Check to ensure that IPooledObject is a derivative of UObject.\n\tUObject* pUObject = dynamic_cast< UObject* >( ObjectIn );\n\n#if !UE_BUILD_SHIPPING\n\tensure( IsValid( pUObject ) );\n#endif\t\/\/ !UE_BUILD_SHIPPING.\n\n\t\/\/ Predicate to check if this object is already in the pool.\n\tconst uint32 objectID = ObjectIn->ID;\n\tif( Pool.ContainsByPredicate( [objectID]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\treturn( objectID == pPooledObject->ID );\n\t} ) )\n\t{\n\t\t\/\/ Object is already in the pool.\n\t\treturn false;\n\t}\n\n\t\/\/ Add this object to the pool.\n\tPool.Add( pUObject );\n\n\t\/\/ Set whether or not the object is active (if being added, it usually is), and give it an ID.\n\tObjectIn->IsActive = Active;\n\tObjectIn->ID = IDCounter++;\n\n\t\/\/ Setup the object's pool return delegate (executed when the object is deactivated).\n\tObjectIn->ReturnToPool.BindUObject( this, &UObjectPool::OnObjectReturn );\n\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Debug logging.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Adding object to pool (Pool: %s, Object Count: %d).\" ), *Name.ToString( ), Pool.Num( ) );\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\ntemplate< typename T >\nT* UObjectPool::GetPooledObject( )\n{\n\tIPooledObject* pPooledObject = GetPooledObject( );\n\tif( pPooledObject == nullptr )\n\t{\n\t\t\/\/ No valid pooled objects.\n\t\treturn nullptr;\n\t}\n\n\tT* pTemplateObject = Cast< T >( pPooledObject );\n\tcheck( IsValid( pTemplateObject ) );\n\n\treturn pTemplateObject;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nIPooledObject* UObjectPool::GetPooledObject( )\n{\n\tif( Pool.Num( ) <= 0 )\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Debug logging.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Pool size of 0 in ::GetPooledObject (Pool: %s, Object Count: %d).\" ), *Name.ToString( ), Pool.Num( ) );\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tconst int64 currentTime = FDateTime::Now( ).ToUnixTimestamp( );\n\tbool executePrune = PruneStale && ( ( currentTime - PruneLastTimestamp ) > PruneStale_Seconds );\t\t\/\/ If this isn't true, then it may be time to prune anyway if the search finds an invalid object.\n\n\t\/\/ Find the first inactive and valid object.\n\tint32 idx = Pool.IndexOfByPredicate( [&]( TWeakObjectPtr< UObject > pObject ) {\n\t\tIPooledObject* pPooledObject = dynamic_cast< IPooledObject* >( pObject.Get( ) );\n\t\tif( !pPooledObject->GetIsActive( ) )\n\t\t{\n\t\t\tif( !pPooledObject->Check( ) )\n\t\t\t{\n\t\t\t\t\/\/ This object is invalid. Prune the pool after this search.\n\t\t\t\texecutePrune = true;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t} );\n\n\tif( idx == INDEX_NONE )\n\t{\n\t\tconst bool debug = CVarDebugObjectPooling.GetValueOnGameThread( );\n\t\tif( debug )\n\t\t{\n\t\t\t\/\/ Debug logging.\n\t\t\tUE_LOG( SteelHuntersLog, Log, TEXT( \"[UObjectPool] Unable to get a free object from the pool using ::GetPooledObject (Pool: %s, Object Count: %d).\" ), *Name.ToString( ), Pool.Num( ) );\n\t\t}\n\t}\n\n\t\/\/ Get the found valid object, remove its place in the array, and add it to the back for a more efficient check later.\n\t\/\/\tNOTE (trent, 12\/10\/17): Ensure that this is actually an optimization.\n\tUObject* pUObject = Pool[idx].Get( );\n\tIPooledObject* pValidObject = dynamic_cast< IPooledObject* >( pUObject );\n\tPool.RemoveAtSwap( idx, 1, false );\n\tPool.Add( pUObject );\n\n\t\/\/ Activate the object.\n\tpValidObject->IsActive = true;\n\tpValidObject->LastActiveTimestamp = FDateTime::Now( ).ToUnixTimestamp( );\n\n\tif( executePrune )\n\t{\n\t\t\/\/ Prune the pool if need be (or if it's just time).\n\t\t\/\/\tNOTE: Since the object that was just found has already been reactivated and given an updated timestamp, it won't be pruned.\n\t\tPrune( );\n\t}\n\n\treturn pValidObject;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetPruneStale( bool PruneStaleIn )\n{\n\tPruneStale = PruneStaleIn;\n}\n\n\/\/----------------------------------------------------------------------------------------------------\nvoid UObjectPool::SetPruneInactiveTime( int64 PruneInactivitySeconds )\n{\n\tPruneStale_Seconds = PruneInactivitySeconds;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Korey Sewell\n *\/\n\n#ifndef __ARCH_MIPS_LINUX_LINUX_HH__\n#define __ARCH_MIPS_LINUX_LINUX_HH__\n\n#include \"kern\/linux\/linux.hh\"\n\nclass MipsLinux : public Linux\n{\n public:\n\n \/\/\/ This table maps the target open() flags to the corresponding\n \/\/\/ host open() flags.\n static OpenFlagTransTable openFlagTable[];\n\n \/\/\/ Number of entries in openFlagTable[].\n static const int NUM_OPEN_FLAGS;\n\n \/\/@{\n \/\/\/ open(2) flag values.\n static const int TGT_O_RDONLY = 0x00000000; \/\/!< O_RDONLY\n static const int TGT_O_WRONLY = 0x00000001; \/\/!< O_WRONLY\n static const int TGT_O_RDWR = 0x00000002; \/\/!< O_RDWR\n static const int TGT_O_NONBLOCK = 0x00000080; \/\/!< O_NONBLOCK\n static const int TGT_O_APPEND = 0x00000008; \/\/!< O_APPEND\n static const int TGT_O_CREAT = 0x00000100; \/\/!< O_CREAT\n static const int TGT_O_TRUNC = 0x00000200; \/\/!< O_TRUNC\n static const int TGT_O_EXCL = 0x00000400; \/\/!< O_EXCL\n static const int TGT_O_NOCTTY = 0x00000800; \/\/!< O_NOCTTY\n static const int TGT_O_SYNC = 0x00000010; \/\/!< O_SYNC\n static const int TGT_O_DRD = 0x00010000; \/\/!< O_DRD\n static const int TGT_O_DIRECTIO = 0x00020000; \/\/!< O_DIRECTIO\n static const int TGT_O_CACHE = 0x00002000; \/\/!< O_CACHE\n static const int TGT_O_DSYNC = 0x00008000; \/\/!< O_DSYNC\n static const int TGT_O_RSYNC = 0x00040000; \/\/!< O_RSYNC\n \/\/@}\n\n \/\/\/ For mmap().\n static const unsigned TGT_MAP_ANONYMOUS = 0x800;\n static const unsigned TGT_MAP_FIXED = 0x10;\n\n \/\/@{\n \/\/\/ For getsysinfo().\n static const unsigned GSI_PLATFORM_NAME = 103; \/\/!< platform name as string\n static const unsigned GSI_CPU_INFO = 59; \/\/!< CPU information\n static const unsigned GSI_PROC_TYPE = 60; \/\/!< get proc_type\n static const unsigned GSI_MAX_CPU = 30; \/\/!< max # cpu's on this machine\n static const unsigned GSI_CPUS_IN_BOX = 55; \/\/!< number of CPUs in system\n static const unsigned GSI_PHYSMEM = 19; \/\/!< Physical memory in KB\n static const unsigned GSI_CLK_TCK = 42; \/\/!< clock freq in Hz\n \/\/@}\n\n \/\/@{\n \/\/\/ For setsysinfo().\n static const unsigned SSI_IEEE_FP_CONTROL = 14; \/\/!< ieee_set_fp_control()\n \/\/@}\n\n \/\/@{\n \/\/\/ ioctl() command codes.\n static const unsigned TGT_TCGETA = 0x5401;\n static const unsigned TGT_TCSETAW = 0x5403;\n static const unsigned TGT_TCGETS = 0x540d;\n static const unsigned TGT_FIONREAD = 0x467f;\n static const unsigned TGT_TIOCGETP = 0x7408;\n static const unsigned TGT_TIOCSETP = 0x7409;\n static const unsigned TGT_TIOCSETN = 0x740a;\n \/\/@}\n\n static bool\n isTtyReq(unsigned req)\n {\n switch (req) {\n case TGT_TIOCGETP:\n case TGT_TIOCSETP:\n case TGT_TIOCSETN:\n case TGT_FIONREAD:\n case TGT_TCGETS:\n case TGT_TCGETA:\n case TGT_TCSETAW:\n return true;\n default:\n return false;\n }\n }\n\n \/\/\/ For table().\n static const int TBL_SYSINFO = 12;\n\n \/\/\/ Resource constants for getrlimit() (overide some generics).\n static const unsigned TGT_RLIMIT_NPROC = 8;\n static const unsigned TGT_RLIMIT_AS = 6;\n static const unsigned RLIMIT_RSS = 7;\n static const unsigned TGT_RLIMIT_NOFILE = 5;\n static const unsigned TGT_RLIMIT_MEMLOCK = 9;\n\n \/\/\/ Offset used to make sure that processes don't\n \/\/\/ assign themselves to process IDs reserved for\n \/\/\/ the root users.\n static const int NUM_ROOT_PROCS = 2;\n \n typedef struct {\n int32_t uptime; \/* Seconds since boot *\/\n uint32_t loads[3]; \/* 1, 5, and 15 minute load averages *\/\n uint32_t totalram; \/* Total usable main memory size *\/\n uint32_t freeram; \/* Available memory size *\/\n uint32_t sharedram; \/* Amount of shared memory *\/\n uint32_t bufferram; \/* Memory used by buffers *\/\n uint32_t totalswap; \/* Total swap space size *\/\n uint32_t freeswap; \/* swap space still available *\/\n uint16_t procs; \/* Number of current processes *\/\n uint32_t totalhigh; \/* Total high memory size *\/\n uint32_t freehigh; \/* Available high memory size *\/\n uint32_t mem_unit; \/* Memory unit size in bytes *\/\n } tgt_sysinfo;\n \n};\n\n#endif\n<commit_msg>mips: Fix RLIMIT_RSS naming<commit_after>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Korey Sewell\n *\/\n\n#ifndef __ARCH_MIPS_LINUX_LINUX_HH__\n#define __ARCH_MIPS_LINUX_LINUX_HH__\n\n#include \"kern\/linux\/linux.hh\"\n\nclass MipsLinux : public Linux\n{\n public:\n\n \/\/\/ This table maps the target open() flags to the corresponding\n \/\/\/ host open() flags.\n static OpenFlagTransTable openFlagTable[];\n\n \/\/\/ Number of entries in openFlagTable[].\n static const int NUM_OPEN_FLAGS;\n\n \/\/@{\n \/\/\/ open(2) flag values.\n static const int TGT_O_RDONLY = 0x00000000; \/\/!< O_RDONLY\n static const int TGT_O_WRONLY = 0x00000001; \/\/!< O_WRONLY\n static const int TGT_O_RDWR = 0x00000002; \/\/!< O_RDWR\n static const int TGT_O_NONBLOCK = 0x00000080; \/\/!< O_NONBLOCK\n static const int TGT_O_APPEND = 0x00000008; \/\/!< O_APPEND\n static const int TGT_O_CREAT = 0x00000100; \/\/!< O_CREAT\n static const int TGT_O_TRUNC = 0x00000200; \/\/!< O_TRUNC\n static const int TGT_O_EXCL = 0x00000400; \/\/!< O_EXCL\n static const int TGT_O_NOCTTY = 0x00000800; \/\/!< O_NOCTTY\n static const int TGT_O_SYNC = 0x00000010; \/\/!< O_SYNC\n static const int TGT_O_DRD = 0x00010000; \/\/!< O_DRD\n static const int TGT_O_DIRECTIO = 0x00020000; \/\/!< O_DIRECTIO\n static const int TGT_O_CACHE = 0x00002000; \/\/!< O_CACHE\n static const int TGT_O_DSYNC = 0x00008000; \/\/!< O_DSYNC\n static const int TGT_O_RSYNC = 0x00040000; \/\/!< O_RSYNC\n \/\/@}\n\n \/\/\/ For mmap().\n static const unsigned TGT_MAP_ANONYMOUS = 0x800;\n static const unsigned TGT_MAP_FIXED = 0x10;\n\n \/\/@{\n \/\/\/ For getsysinfo().\n static const unsigned GSI_PLATFORM_NAME = 103; \/\/!< platform name as string\n static const unsigned GSI_CPU_INFO = 59; \/\/!< CPU information\n static const unsigned GSI_PROC_TYPE = 60; \/\/!< get proc_type\n static const unsigned GSI_MAX_CPU = 30; \/\/!< max # cpu's on this machine\n static const unsigned GSI_CPUS_IN_BOX = 55; \/\/!< number of CPUs in system\n static const unsigned GSI_PHYSMEM = 19; \/\/!< Physical memory in KB\n static const unsigned GSI_CLK_TCK = 42; \/\/!< clock freq in Hz\n \/\/@}\n\n \/\/@{\n \/\/\/ For setsysinfo().\n static const unsigned SSI_IEEE_FP_CONTROL = 14; \/\/!< ieee_set_fp_control()\n \/\/@}\n\n \/\/@{\n \/\/\/ ioctl() command codes.\n static const unsigned TGT_TCGETA = 0x5401;\n static const unsigned TGT_TCSETAW = 0x5403;\n static const unsigned TGT_TCGETS = 0x540d;\n static const unsigned TGT_FIONREAD = 0x467f;\n static const unsigned TGT_TIOCGETP = 0x7408;\n static const unsigned TGT_TIOCSETP = 0x7409;\n static const unsigned TGT_TIOCSETN = 0x740a;\n \/\/@}\n\n static bool\n isTtyReq(unsigned req)\n {\n switch (req) {\n case TGT_TIOCGETP:\n case TGT_TIOCSETP:\n case TGT_TIOCSETN:\n case TGT_FIONREAD:\n case TGT_TCGETS:\n case TGT_TCGETA:\n case TGT_TCSETAW:\n return true;\n default:\n return false;\n }\n }\n\n \/\/\/ For table().\n static const int TBL_SYSINFO = 12;\n\n \/\/\/ Resource constants for getrlimit() (overide some generics).\n static const unsigned TGT_RLIMIT_NPROC = 8;\n static const unsigned TGT_RLIMIT_AS = 6;\n static const unsigned TGT_RLIMIT_RSS = 7;\n static const unsigned TGT_RLIMIT_NOFILE = 5;\n static const unsigned TGT_RLIMIT_MEMLOCK = 9;\n\n \/\/\/ Offset used to make sure that processes don't\n \/\/\/ assign themselves to process IDs reserved for\n \/\/\/ the root users.\n static const int NUM_ROOT_PROCS = 2;\n \n typedef struct {\n int32_t uptime; \/* Seconds since boot *\/\n uint32_t loads[3]; \/* 1, 5, and 15 minute load averages *\/\n uint32_t totalram; \/* Total usable main memory size *\/\n uint32_t freeram; \/* Available memory size *\/\n uint32_t sharedram; \/* Amount of shared memory *\/\n uint32_t bufferram; \/* Memory used by buffers *\/\n uint32_t totalswap; \/* Total swap space size *\/\n uint32_t freeswap; \/* swap space still available *\/\n uint16_t procs; \/* Number of current processes *\/\n uint32_t totalhigh; \/* Total high memory size *\/\n uint32_t freehigh; \/* Available high memory size *\/\n uint32_t mem_unit; \/* Memory unit size in bytes *\/\n } tgt_sysinfo;\n \n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/%LICENSE\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Licensed to The Open Group (TOG) under one or more contributor license\n\/\/ agreements. Refer to the OpenPegasusNOTICE.txt file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ Each contributor licenses this file to you under the OpenPegasus Open\n\/\/ Source License; you may not use this file except in compliance with the\n\/\/ License.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/%\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <sys\/stat.h>\n\nUNIX_LogEntry::UNIX_LogEntry(void)\n{\n}\n\nUNIX_LogEntry::~UNIX_LogEntry(void)\n{\n}\n\n\nBoolean UNIX_LogEntry::getInstanceID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getInstanceID() const\n{\n\tString s;\n\ts.append(getLogName());\n\ts.append(\"_\");\n\ts.append(\"A\");\n\treturn s;\n}\n\nBoolean UNIX_LogEntry::getCaption(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_CAPTION, getCaption());\n\treturn true;\n}\n\nString UNIX_LogEntry::getCaption() const\n{\n\treturn msg;\n}\n\nBoolean UNIX_LogEntry::getDescription(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_DESCRIPTION, getDescription());\n\treturn true;\n}\n\nString UNIX_LogEntry::getDescription() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getElementName(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());\n\treturn true;\n}\n\nString UNIX_LogEntry::getElementName() const\n{\n\treturn String(\"LogEntry\");\n}\n\nBoolean UNIX_LogEntry::getRecordFormat(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_FORMAT, getRecordFormat());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordFormat() const\n{\n\treturn String (\"[DATE] [MESSAGE]\");\n}\n\nBoolean UNIX_LogEntry::getRecordData(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_DATA, getRecordData());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordData() const\n{\n\treturn data;\n}\n\nBoolean UNIX_LogEntry::getLocale(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOCALE, getLocale());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLocale() const\n{\n\treturn String (\"en-US\");\n}\n\nBoolean UNIX_LogEntry::getPerceivedSeverity(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_PERCEIVED_SEVERITY, getPerceivedSeverity());\n\treturn true;\n}\n\nUint16 UNIX_LogEntry::getPerceivedSeverity() const\n{\n\treturn Uint16(0);\n}\n\nBoolean UNIX_LogEntry::getLogInstanceID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOG_INSTANCE_ID, getLogInstanceID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLogInstanceID() const\n{\n\treturn logs.getInstanceID();\n}\n\nBoolean UNIX_LogEntry::getLogName(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOG_NAME, getLogName());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLogName() const\n{\n\treturn logs.getName();\n}\n\nBoolean UNIX_LogEntry::getRecordID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_ID, getRecordID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordID() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getCreationTimeStamp(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_CREATION_TIME_STAMP, getCreationTimeStamp());\n\treturn true;\n}\n\nCIMDateTime UNIX_LogEntry::getCreationTimeStamp() const\n{\n\treturn logDate;\n}\n\nBoolean UNIX_LogEntry::getMessageID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE_ID, getMessageID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getMessageID() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getMessage(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE, getMessage());\n\treturn true;\n}\n\nString UNIX_LogEntry::getMessage() const\n{\n\treturn msg;\n}\n\nBoolean UNIX_LogEntry::getMessageArguments(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE_ARGUMENTS, getMessageArguments());\n\treturn true;\n}\n\nArray<String> UNIX_LogEntry::getMessageArguments() const\n{\n\tArray<String> as;\n\t\n\n\treturn as;\n\n}\n\nBoolean UNIX_LogEntry::getOwningEntity(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_OWNING_ENTITY, getOwningEntity());\n\treturn true;\n}\n\nString UNIX_LogEntry::getOwningEntity() const\n{\n\treturn String (\"\");\n}\n\n\n\nBoolean UNIX_LogEntry::initialize()\n{\n\tfp = NULL;\n\tlogs.initialize();\n\tlogIndex = 0;\n\treturn false;\n}\n\nBoolean UNIX_LogEntry::load(int &pIndex)\n{\n\tif (fp == NULL)\n\t{\n\t\tif (logs.load(logIndex))\n\t\t{\n\t\t\tlogIndex++;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (fp == NULL)\n\t{\n\t\tif (logs.getFileName(fileName))\n\t\t{\n\t\t\tif ((fp = fopen(fileName.getCString(), \"r\")) == NULL)\n\t\t\t{\n\t\t\t\tfileName.assign(\"\");\n\t\t\t\tfp = NULL;\n\t\t\t\treturn load(++pIndex);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Since syslog doesn't store year in logs will use the year of the file *\/\n\t\t\t\t\/* Hopfully syslog change the file when it changes year *\/\n\t\t\t\tstruct tm* clock;\t\t\t\/\/ create a time structure\n\t\t\t\tstruct stat attrib;\t\t\t\/\/ create a file attribute structure\n\t\t\t\tstat(fileName.getCString(), &attrib);\t\t\/\/ get the attributes mnt\n\t\t\t\tclock = gmtime(&(attrib.st_mtime));\t\/\/ Get the last modified time and put it into the time structure\n\t\t\t\tcurrentYear = clock->tm_year + 1900;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfp == NULL;\n\t\t\treturn load(++pIndex);\n\t\t}\n\t}\n\tchar val[512];\n\tif (fgets(val, sizeof(val), fp) != NULL)\n\t{\n\t\t\/\/Parse Date from syslog\n\t\tstruct tm clock;\n\t\tchar *retc = strptime(val, \"%b %d %H:%M:%S\", &clock);\n\t\tlogDate = CIMDateTime(\n\t\tcurrentYear,\n\t\tclock.tm_mon + 1,\n\t\tclock.tm_mday,\n\t\tclock.tm_hour,\n\t\tclock.tm_min,\n\t\tclock.tm_sec,\n\t\t0,0,\n\t\t0);\n\t\tdata = String(val);\n\t\tmsg.assign(CIMHelper::trim(retc));\n\t\treturn true;\n\t}\n\telse \n\t{\n\t\tfclose(fp);\n\t\tfp = NULL;\n\t\treturn load(++pIndex);\n\t}\n}\n\nBoolean UNIX_LogEntry::finalize()\n{\n\tlogIndex = 0;\n\tlogs.finalize();\n\treturn false;\n}\n\nBoolean UNIX_LogEntry::find(Array<CIMKeyBinding> &kbArray)\n{\n\tCIMKeyBinding kb;\n\tString instanceIDKey;\n\n\n\tfor(Uint32 i = 0; i < kbArray.size(); i++)\n\t{\n\t\tkb = kbArray[i];\n\t\tCIMName keyName = kb.getName();\n\t\tif (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();\n\t}\n\n\n\n\/* EXecute find with extracted keys *\/\n\n\treturn false;\n}\n<commit_msg>Fixing CIM_LogEntry Implementation<commit_after>\/\/%LICENSE\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Licensed to The Open Group (TOG) under one or more contributor license\n\/\/ agreements. Refer to the OpenPegasusNOTICE.txt file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ Each contributor licenses this file to you under the OpenPegasus Open\n\/\/ Source License; you may not use this file except in compliance with the\n\/\/ License.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/%\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <sys\/stat.h>\n\nUNIX_LogEntry::UNIX_LogEntry(void)\n{\n}\n\nUNIX_LogEntry::~UNIX_LogEntry(void)\n{\n}\n\n\nBoolean UNIX_LogEntry::getInstanceID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getInstanceID() const\n{\n\tString s;\n\ts.append(getLogName());\n\ts.append(\"_\");\n\ts.append(\"A\");\n\treturn s;\n}\n\nBoolean UNIX_LogEntry::getCaption(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_CAPTION, getCaption());\n\treturn true;\n}\n\nString UNIX_LogEntry::getCaption() const\n{\n\treturn msg;\n}\n\nBoolean UNIX_LogEntry::getDescription(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_DESCRIPTION, getDescription());\n\treturn true;\n}\n\nString UNIX_LogEntry::getDescription() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getElementName(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());\n\treturn true;\n}\n\nString UNIX_LogEntry::getElementName() const\n{\n\treturn String(\"LogEntry\");\n}\n\nBoolean UNIX_LogEntry::getRecordFormat(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_FORMAT, getRecordFormat());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordFormat() const\n{\n\treturn String (\"[DATE] [MESSAGE]\");\n}\n\nBoolean UNIX_LogEntry::getRecordData(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_DATA, getRecordData());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordData() const\n{\n\treturn data;\n}\n\nBoolean UNIX_LogEntry::getLocale(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOCALE, getLocale());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLocale() const\n{\n\treturn String (\"en-US\");\n}\n\nBoolean UNIX_LogEntry::getPerceivedSeverity(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_PERCEIVED_SEVERITY, getPerceivedSeverity());\n\treturn true;\n}\n\nUint16 UNIX_LogEntry::getPerceivedSeverity() const\n{\n\treturn Uint16(0);\n}\n\nBoolean UNIX_LogEntry::getLogInstanceID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOG_INSTANCE_ID, getLogInstanceID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLogInstanceID() const\n{\n\treturn logs.getInstanceID();\n}\n\nBoolean UNIX_LogEntry::getLogName(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_LOG_NAME, getLogName());\n\treturn true;\n}\n\nString UNIX_LogEntry::getLogName() const\n{\n\treturn logs.getName();\n}\n\nBoolean UNIX_LogEntry::getRecordID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_RECORD_ID, getRecordID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getRecordID() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getCreationTimeStamp(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_CREATION_TIME_STAMP, getCreationTimeStamp());\n\treturn true;\n}\n\nCIMDateTime UNIX_LogEntry::getCreationTimeStamp() const\n{\n\treturn logDate;\n}\n\nBoolean UNIX_LogEntry::getMessageID(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE_ID, getMessageID());\n\treturn true;\n}\n\nString UNIX_LogEntry::getMessageID() const\n{\n\treturn String (\"\");\n}\n\nBoolean UNIX_LogEntry::getMessage(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE, getMessage());\n\treturn true;\n}\n\nString UNIX_LogEntry::getMessage() const\n{\n\treturn msg;\n}\n\nBoolean UNIX_LogEntry::getMessageArguments(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_MESSAGE_ARGUMENTS, getMessageArguments());\n\treturn true;\n}\n\nArray<String> UNIX_LogEntry::getMessageArguments() const\n{\n\tArray<String> as;\n\t\n\n\treturn as;\n\n}\n\nBoolean UNIX_LogEntry::getOwningEntity(CIMProperty &p) const\n{\n\tp = CIMProperty(PROPERTY_OWNING_ENTITY, getOwningEntity());\n\treturn true;\n}\n\nString UNIX_LogEntry::getOwningEntity() const\n{\n\treturn String (\"\");\n}\n\n\n\nBoolean UNIX_LogEntry::initialize()\n{\n\tfp = NULL;\n\tlogs.initialize();\n\tlogIndex = 0;\n\treturn true;\n}\n\nBoolean UNIX_LogEntry::load(int &pIndex)\n{\n\tif (fp == NULL)\n\t{\n\t\tif (logs.load(logIndex))\n\t\t{\n\t\t\tlogIndex++;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (fp == NULL)\n\t{\n\t\tif (logs.getFileName(fileName))\n\t\t{\n\t\t\tif ((fp = fopen(fileName.getCString(), \"r\")) == NULL)\n\t\t\t{\n\t\t\t\tfileName.assign(\"\");\n\t\t\t\tfp = NULL;\n\t\t\t\treturn load(++pIndex);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/* Since syslog doesn't store year in logs will use the year of the file *\/\n\t\t\t\t\/* Hopfully syslog change the file when it changes year *\/\n\t\t\t\tstruct tm* clock;\t\t\t\/\/ create a time structure\n\t\t\t\tstruct stat attrib;\t\t\t\/\/ create a file attribute structure\n\t\t\t\tstat(fileName.getCString(), &attrib);\t\t\/\/ get the attributes mnt\n\t\t\t\tclock = gmtime(&(attrib.st_mtime));\t\/\/ Get the last modified time and put it into the time structure\n\t\t\t\tcurrentYear = clock->tm_year + 1900;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfp == NULL;\n\t\t\treturn load(++pIndex);\n\t\t}\n\t}\n\tchar val[512];\n\tif (fgets(val, sizeof(val), fp) != NULL)\n\t{\n\t\t\/\/Parse Date from syslog\n\t\tstruct tm clock;\n\t\tchar *retc = strptime(val, \"%b %d %H:%M:%S\", &clock);\n\t\tlogDate = CIMDateTime(\n\t\tcurrentYear,\n\t\tclock.tm_mon + 1,\n\t\tclock.tm_mday,\n\t\tclock.tm_hour,\n\t\tclock.tm_min,\n\t\tclock.tm_sec,\n\t\t0,0,\n\t\t0);\n\t\tdata = String(val);\n\t\tmsg.assign(CIMHelper::trim(retc));\n\t\treturn true;\n\t}\n\telse \n\t{\n\t\tfclose(fp);\n\t\tfp = NULL;\n\t\treturn load(++pIndex);\n\t}\n}\n\nBoolean UNIX_LogEntry::finalize()\n{\n\tlogIndex = 0;\n\tlogs.finalize();\n\treturn true;\n}\n\nBoolean UNIX_LogEntry::find(Array<CIMKeyBinding> &kbArray)\n{\n\tCIMKeyBinding kb;\n\tString instanceIDKey;\n\n\n\tfor(Uint32 i = 0; i < kbArray.size(); i++)\n\t{\n\t\tkb = kbArray[i];\n\t\tCIMName keyName = kb.getName();\n\t\tif (keyName.equal(PROPERTY_INSTANCE_ID)) instanceIDKey = kb.getValue();\n\t}\n\n\n\n\/* EXecute find with extracted keys *\/\n\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of k-par-means\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __KPM_DIST_MATRIX_HPP__\n#define __KPM_DIST_MATRIX_HPP__\n\n#include <memory>\n#include <limits>\n#include <vector>\n\n#include <El.hpp>\n#include \"util.hpp\"\n\n#if 0\nnamespace kpmeans { namespace prune {\n class prune_clusters;\n} } \/\/ End namespace kpmeans, prune\n#endif\n\nnamespace kpmeans { namespace prune {\n\/\/ NOTE: Creates a matrix like this e.g for K = 5\n\/* - Don't store full matrix, don't store dist to myself -> space: (k*k-1)\/2\n 0 ==> 1 2 3 4\n 1 ==> 2 3 4\n 2 ==> 3 4\n 3 ==> 4\n (4 ==> not needed)\n *\/\nclass dist_matrix {\nprivate:\n std::vector<std::vector<double>> mat;\n unsigned rows;\n\n dist_matrix(const unsigned rows);\n void translate(unsigned& row, unsigned& col);\n\npublic:\n typedef typename std::shared_ptr<dist_matrix> ptr;\n\n static ptr create(const unsigned rows) {\n return ptr(new dist_matrix(rows));\n }\n\n const unsigned get_num_rows() { return rows; }\n\n \/* Do a translation from raw id's to indexes in the distance matrix *\/\n double get(unsigned row, unsigned col);\n \/\/ Testing purposes only\n double get_min_dist(const unsigned row);\n void set(unsigned row, unsigned col, double val);\n\n void print();\n#if 0\n void compute_dist(kpmeans::base::prune_clusters::ptr cl,\n const unsigned ncol);\n#endif\n \/\/ Note cls is col-wise unlike dist_matrix\n template<typename T>\n void compute_dist(El::Matrix<T>& cls,\n std::vector<T>& s_val_v) {\n if (cls.Width() <= 1) return (T)0;\n\n assert(get_num_rows() == cls.Width());\n std::fill(s_val_v.begin(), s_val_v.end(),\n std::numeric_limits<double>::max());\n\n for (unsigned i = 0; i < cls.Width(); i++) {\n for (unsigned j = i+1; j < cls.Width(); j++) {\n \/\/ FIXME\n double dist = kpmeans::base::eucl_dist(cls.LockedBuffer(0,i),\n cls.LockedBuffer(0,j), cls.Height()) \/ 2.0;\n\n set(i,j, dist);\n\n \/\/ Set s(x) for each cluster\n if (dist < s_val_v[i])\n s_val_v[i] = dist;\n\n if (dist < s_val_v[j])\n s_val_v[j] = dist;\n }\n }\n#if VERBOSE\n for (unsigned cl = 0; cl < cls.Width(); cl++) {\n assert(s_val_v[cl] == get_min_dist(cl));\n if (El::mpi::Rank(El::mpi::COMM_WORLD) == 0)\n El::Output(\"cl: \", cl,\" get_s_val: \", s_val_v[cl]);\n }\n#endif\n}\n};\n} } \/\/ End namespace kpmeans, prune\n#endif\n<commit_msg>bug: return should be void<commit_after>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of k-par-means\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __KPM_DIST_MATRIX_HPP__\n#define __KPM_DIST_MATRIX_HPP__\n\n#include <memory>\n#include <limits>\n#include <vector>\n\n#include <El.hpp>\n#include \"util.hpp\"\n\n#if 0\nnamespace kpmeans { namespace prune {\n class prune_clusters;\n} } \/\/ End namespace kpmeans, prune\n#endif\n\nnamespace kpmeans { namespace prune {\n\/\/ NOTE: Creates a matrix like this e.g for K = 5\n\/* - Don't store full matrix, don't store dist to myself -> space: (k*k-1)\/2\n 0 ==> 1 2 3 4\n 1 ==> 2 3 4\n 2 ==> 3 4\n 3 ==> 4\n (4 ==> not needed)\n *\/\nclass dist_matrix {\nprivate:\n std::vector<std::vector<double>> mat;\n unsigned rows;\n\n dist_matrix(const unsigned rows);\n void translate(unsigned& row, unsigned& col);\n\npublic:\n typedef typename std::shared_ptr<dist_matrix> ptr;\n\n static ptr create(const unsigned rows) {\n return ptr(new dist_matrix(rows));\n }\n\n const unsigned get_num_rows() { return rows; }\n\n \/* Do a translation from raw id's to indexes in the distance matrix *\/\n double get(unsigned row, unsigned col);\n \/\/ Testing purposes only\n double get_min_dist(const unsigned row);\n void set(unsigned row, unsigned col, double val);\n\n void print();\n#if 0\n void compute_dist(kpmeans::base::prune_clusters::ptr cl,\n const unsigned ncol);\n#endif\n \/\/ Note cls is col-wise unlike dist_matrix\n template<typename T>\n void compute_dist(El::Matrix<T>& cls,\n std::vector<T>& s_val_v) {\n if (cls.Width() == 1) {\n s_val_v.push_back((T)0);\n return;\n }\n\n assert(get_num_rows() == cls.Width());\n std::fill(s_val_v.begin(), s_val_v.end(),\n std::numeric_limits<double>::max());\n\n for (unsigned i = 0; i < cls.Width(); i++) {\n for (unsigned j = i+1; j < cls.Width(); j++) {\n \/\/ FIXME\n double dist = kpmeans::base::eucl_dist(cls.LockedBuffer(0,i),\n cls.LockedBuffer(0,j), cls.Height()) \/ 2.0;\n\n set(i,j, dist);\n\n \/\/ Set s(x) for each cluster\n if (dist < s_val_v[i])\n s_val_v[i] = dist;\n\n if (dist < s_val_v[j])\n s_val_v[j] = dist;\n }\n }\n#if VERBOSE\n for (unsigned cl = 0; cl < cls.Width(); cl++) {\n assert(s_val_v[cl] == get_min_dist(cl));\n if (El::mpi::Rank(El::mpi::COMM_WORLD) == 0)\n El::Output(\"cl: \", cl,\" get_s_val: \", s_val_v[cl]);\n }\n#endif\n}\n};\n} } \/\/ End namespace kpmeans, prune\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"CGUITerrainControlWidget.h\"\r\n\r\n#include \"CProgramContext.h\"\r\n#include \"CMainState.h\"\r\n#include \"CTerrainNodeManager.h\"\r\n#include \"CGUIContext.h\"\r\n\r\n#include <Gwen\/Controls.h>\r\n#include <Gwen\/Controls\/ComboBox.h>\r\n\r\n\r\nCGUITerrainControlWidget::CGUITerrainControlWidget()\r\n\t: Terrain(CProgramContext::Get().Scene.Terrain), Water(CProgramContext::Get().Scene.Water), MainState(CMainState::Get())\r\n{\r\n\tWindow = new Gwen::Controls::WindowControl(GUIManager->GetCanvas());\r\n\tWindow->SetDeleteOnClose(false);\r\n\tWindow->SetBounds(1200, 500, 330, 235);\r\n\tWindow->SetTitle(\"Terrain Controls\");\r\n\tWindow->SetHidden(true);\r\n\r\n\tTerrainButton = new Gwen::Controls::Button(Window);\r\n\tTerrainButton->SetBounds(15, 10, 290, 25);\r\n\tTerrainButton->SetText(Terrain->GetNode()->IsVisible() ? \"Disable Terrain\" : \"Enable Terrain\");\r\n\tTerrainButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleTerrain);\r\n\r\n\tWaterButton = new Gwen::Controls::Button(Window);\r\n\tWaterButton->SetBounds(15, 10 + 35, 290, 25);\r\n\tWaterButton->SetText(\"Enable Water\");\r\n\t\/\/WaterButton->SetText(Water->isVisible() ? \"Disable Water\" : \"Enable Water\");\r\n\tWaterButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleWater);\r\n\r\n\t\/\/ Panel\r\n\t{\r\n\t\tGwen::Controls::Label * SliderLabel = new Gwen::Controls::Label(Window);\r\n\t\tSliderLabel->SetFont(GUIManager->GetRegularFont());\r\n\t\tSliderLabel->SetText(L\"Texture:\");\r\n\t\tSliderLabel->SetBounds(10, 10 + 30 + 45, 300, 40);\r\n\t\tSliderLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));\r\n\r\n\t\tGwen::Controls::Button * ElevationButton = new Gwen::Controls::Button(Window);\r\n\t\tElevationButton->SetBounds(15, 10 + 30 + 45 + 20, 140, 25);\r\n\t\tElevationButton->SetText(\"Elevation\");\r\n\t\tElevationButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectElevation);\r\n\r\n\t\tGwen::Controls::Button * ColorButton = new Gwen::Controls::Button(Window);\r\n\t\tColorButton->SetBounds(140 + 15 + 10, 10 + 30 + 45 + 20, 140, 25);\r\n\t\tColorButton->SetText(\"GoogleMaps\");\r\n\t\tColorButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectColor);\r\n\r\n\t\tGwen::Controls::Label * ModeLabel = new Gwen::Controls::Label(Window);\r\n\t\tModeLabel->SetFont(GUIManager->GetRegularFont());\r\n\t\tModeLabel->SetText(L\"Mode:\");\r\n\t\tModeLabel->SetBounds(10, 10 + 15 + 45 + 75, 300, 40);\r\n\t\tModeLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));\r\n\r\n\t\tGwen::Controls::ComboBox * ModeBox = new Gwen::Controls::ComboBox(Window);\r\n\t\tModeBox->SetBounds(15, 10 + 15 + 45 + 20 + 75, 200, 25);\r\n\t\tModeBox->AddItem(L\"Solid\");\r\n\t\tModeBox->AddItem(L\"Wireframe\");\r\n\t\tModeBox->AddItem(L\"AO1\");\r\n\t\tModeBox->AddItem(L\"AO2\");\r\n\t\tModeBox->AddItem(L\"AO3\");\r\n\t\tModeBox->AddItem(L\"AO4\");\r\n\t\tModeBox->AddItem(L\"AO5\");\r\n\t\tModeBox->AddItem(L\"AO6\");\r\n\t\tModeBox->AddItem(L\"AO7\");\r\n\t\tModeBox->AddItem(L\"AO8\");\r\n\t\tModeBox->AddItem(L\"AO9\");\r\n\t\tModeBox->onSelection.Add(this, & CGUITerrainControlWidget::OnModeSelect);\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnToggleTerrain(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\r\n\tif (Context->Scene.Terrain->GetNode()->IsVisible())\r\n\t{\r\n\t\tContext->Scene.Terrain->GetNode()->SetVisible(false);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Terrain View Disabled\");\r\n\t\tTerrainButton->SetText(\"Enable Terrain\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tContext->Scene.Terrain->GetNode()->SetVisible(true);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Terrain View Enabled\");\r\n\t\tTerrainButton->SetText(\"Disable Terrain\");\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnToggleWater(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\r\n\t\/\/if (Context->Scene.Water->isVisible())\r\n\t\/\/{\r\n\t\/\/\tContext->Scene.Water->setVisible(false);\r\n\t\/\/\tGUIContext->GetConsole()->AddMessage(\"Water View Disabled\");\r\n\t\/\/\tWaterButton->SetText(\"Enable Water\");\r\n\t\/\/}\r\n\t\/\/else\r\n\t\/\/{\r\n\t\/\/\tContext->Scene.Water->setVisible(true);\r\n\t\/\/\tGUIContext->GetConsole()->AddMessage(\"Water View Enabled\");\r\n\t\/\/\tWaterButton->SetText(\"Disable Water\");\r\n\t\/\/}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnSelectElevation(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tContext->Scene.Terrain->SetDebugHeightEnabled(true);\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnSelectColor(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tContext->Scene.Terrain->SetDebugHeightEnabled(false);\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnModeSelect(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tGwen::Controls::ComboBox * Box = (Gwen::Controls::ComboBox *) Control;\r\n\t\r\n\tif (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"Solid\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 0;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"Wireframe\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 0;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, true);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO1\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 1;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO2\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 2;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO3\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 3;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO4\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 4;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO5\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 5;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO6\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 6;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO7\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 7;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO8\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 8;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO9\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 9;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::toggle()\r\n{\r\n\tWindow->SetHidden(Window->Visible());\r\n}\r\n<commit_msg>Re-enable water controls in gui<commit_after>#include \"CGUITerrainControlWidget.h\"\r\n\r\n#include \"CProgramContext.h\"\r\n#include \"CMainState.h\"\r\n#include \"CTerrainNodeManager.h\"\r\n#include \"CGUIContext.h\"\r\n\r\n#include <Gwen\/Controls.h>\r\n#include <Gwen\/Controls\/ComboBox.h>\r\n\r\n\r\nCGUITerrainControlWidget::CGUITerrainControlWidget()\r\n\t: Terrain(CProgramContext::Get().Scene.Terrain), Water(CProgramContext::Get().Scene.Water), MainState(CMainState::Get())\r\n{\r\n\tWindow = new Gwen::Controls::WindowControl(GUIManager->GetCanvas());\r\n\tWindow->SetDeleteOnClose(false);\r\n\tWindow->SetBounds(1200, 500, 330, 235);\r\n\tWindow->SetTitle(\"Terrain Controls\");\r\n\tWindow->SetHidden(true);\r\n\r\n\tTerrainButton = new Gwen::Controls::Button(Window);\r\n\tTerrainButton->SetBounds(15, 10, 290, 25);\r\n\tTerrainButton->SetText(Terrain->GetNode()->IsVisible() ? \"Disable Terrain\" : \"Enable Terrain\");\r\n\tTerrainButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleTerrain);\r\n\r\n\tWaterButton = new Gwen::Controls::Button(Window);\r\n\tWaterButton->SetBounds(15, 10 + 35, 290, 25);\r\n\tWaterButton->SetText(\"Enable Water\");\r\n\tWaterButton->SetText(Water->IsVisible() ? \"Disable Water\" : \"Enable Water\");\r\n\tWaterButton->onPress.Add(this, & CGUITerrainControlWidget::OnToggleWater);\r\n\r\n\t\/\/ Panel\r\n\t{\r\n\t\tGwen::Controls::Label * SliderLabel = new Gwen::Controls::Label(Window);\r\n\t\tSliderLabel->SetFont(GUIManager->GetRegularFont());\r\n\t\tSliderLabel->SetText(L\"Texture:\");\r\n\t\tSliderLabel->SetBounds(10, 10 + 30 + 45, 300, 40);\r\n\t\tSliderLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));\r\n\r\n\t\tGwen::Controls::Button * ElevationButton = new Gwen::Controls::Button(Window);\r\n\t\tElevationButton->SetBounds(15, 10 + 30 + 45 + 20, 140, 25);\r\n\t\tElevationButton->SetText(\"Elevation\");\r\n\t\tElevationButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectElevation);\r\n\r\n\t\tGwen::Controls::Button * ColorButton = new Gwen::Controls::Button(Window);\r\n\t\tColorButton->SetBounds(140 + 15 + 10, 10 + 30 + 45 + 20, 140, 25);\r\n\t\tColorButton->SetText(\"GoogleMaps\");\r\n\t\tColorButton->onPress.Add(this, & CGUITerrainControlWidget::OnSelectColor);\r\n\r\n\t\tGwen::Controls::Label * ModeLabel = new Gwen::Controls::Label(Window);\r\n\t\tModeLabel->SetFont(GUIManager->GetRegularFont());\r\n\t\tModeLabel->SetText(L\"Mode:\");\r\n\t\tModeLabel->SetBounds(10, 10 + 15 + 45 + 75, 300, 40);\r\n\t\tModeLabel->SetTextColor(Gwen::Color(50, 20, 20, 215));\r\n\r\n\t\tGwen::Controls::ComboBox * ModeBox = new Gwen::Controls::ComboBox(Window);\r\n\t\tModeBox->SetBounds(15, 10 + 15 + 45 + 20 + 75, 200, 25);\r\n\t\tModeBox->AddItem(L\"Solid\");\r\n\t\tModeBox->AddItem(L\"Wireframe\");\r\n\t\tModeBox->AddItem(L\"AO1\");\r\n\t\tModeBox->AddItem(L\"AO2\");\r\n\t\tModeBox->AddItem(L\"AO3\");\r\n\t\tModeBox->AddItem(L\"AO4\");\r\n\t\tModeBox->AddItem(L\"AO5\");\r\n\t\tModeBox->AddItem(L\"AO6\");\r\n\t\tModeBox->AddItem(L\"AO7\");\r\n\t\tModeBox->AddItem(L\"AO8\");\r\n\t\tModeBox->AddItem(L\"AO9\");\r\n\t\tModeBox->onSelection.Add(this, & CGUITerrainControlWidget::OnModeSelect);\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnToggleTerrain(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\r\n\tif (Context->Scene.Terrain->GetNode()->IsVisible())\r\n\t{\r\n\t\tContext->Scene.Terrain->GetNode()->SetVisible(false);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Terrain View Disabled\");\r\n\t\tTerrainButton->SetText(\"Enable Terrain\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tContext->Scene.Terrain->GetNode()->SetVisible(true);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Terrain View Enabled\");\r\n\t\tTerrainButton->SetText(\"Disable Terrain\");\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnToggleWater(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\r\n\tif (Context->Scene.Water->IsVisible())\r\n\t{\r\n\t\tContext->Scene.Water->SetVisible(false);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Water View Disabled\");\r\n\t\tWaterButton->SetText(\"Enable Water\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tContext->Scene.Water->SetVisible(true);\r\n\t\tGUIContext->GetConsole()->AddMessage(\"Water View Enabled\");\r\n\t\tWaterButton->SetText(\"Disable Water\");\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnSelectElevation(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tContext->Scene.Terrain->SetDebugHeightEnabled(true);\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnSelectColor(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tContext->Scene.Terrain->SetDebugHeightEnabled(false);\r\n}\r\n\r\nvoid CGUITerrainControlWidget::OnModeSelect(Gwen::Controls::Base * Control)\r\n{\r\n\tCProgramContext * Context = & CProgramContext::Get();\r\n\tGwen::Controls::ComboBox * Box = (Gwen::Controls::ComboBox *) Control;\r\n\t\r\n\tif (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"Solid\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 0;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"Wireframe\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 0;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, true);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO1\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 1;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO2\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 2;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO3\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 3;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO4\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 4;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO5\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 5;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO6\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 6;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO7\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 7;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO8\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 8;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n\telse if (Box->GetSelectedItem()->GetText() == Gwen::UnicodeString(L\"AO9\"))\r\n\t{\r\n\t\tContext->Scene.Terrain->DebugMode = 9;\r\n\t\tContext->Scene.Terrain->GetNode()->SetFeatureEnabled(ion::GL::EDrawFeature::Wireframe, false);\r\n\t}\r\n}\r\n\r\nvoid CGUITerrainControlWidget::toggle()\r\n{\r\n\tWindow->SetHidden(Window->Visible());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * Simbody(tm): SimTKcommon *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2008-12 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"ParallelExecutorImpl.h\"\n#include \"SimTKcommon\/internal\/ParallelExecutor.h\"\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <mutex>\n\nusing namespace std;\n\nnamespace SimTK {\n\nstatic void threadBody(ThreadInfo& info);\n\nParallelExecutorImpl::ParallelExecutorImpl() : finished(false) {\n\n \/\/By default, we use the total number of processors available of the\n \/\/computer (including hyperthreads)\n numMaxThreads = ParallelExecutor::getNumProcessors();\n if(numMaxThreads <= 0)\n numMaxThreads = 1;\n}\nParallelExecutorImpl::ParallelExecutorImpl(int numThreads) : finished(false) {\n\n \/\/ Set the maximum number of threads that we can use\n SimTK_APIARGCHECK_ALWAYS(numThreads > 0, \"ParallelExecutorImpl\",\n \"ParallelExecutorImpl\", \"Number of threads must be positive.\");\n numMaxThreads = numThreads;\n}\nParallelExecutorImpl::~ParallelExecutorImpl() {\n \n \/\/ Notify the threads that they should exit.\n \n std::unique_lock<std::mutex> lock(runMutex);\n finished = true;\n for (int i = 0; i < (int) threads.size(); ++i)\n threadInfo[i].running = true;\n runCondition.notify_all();\n lock.unlock();\n \n \/\/ Wait until all the threads have finished.\n \n for (int i = 0; i < (int) threads.size(); ++i)\n threads[i].join();\n}\nParallelExecutorImpl* ParallelExecutorImpl::clone() const {\n return new ParallelExecutorImpl(numMaxThreads);\n}\nvoid ParallelExecutorImpl::execute(ParallelExecutor::Task& task, int times) {\n if (numMaxThreads < 2) {\n \/\/(1) NON-PARALLEL CASE:\n \/\/ Nothing is actually going to get done in parallel, so we might as well\n \/\/ just execute the task directly and save the threading overhead.\n task.initialize();\n for (int i = 0; i < times; ++i)\n task.execute(i);\n task.finish();\n return;\n }\n \n \/\/(2) PARALLEL CASE:\n \/\/ We launch the maximum number of threads and save them for later use\n if(threads.size() < (size_t)numMaxThreads)\n {\n \/\/ We do not support numMaxThreads changing for a given instance of\n \/\/ ParallelExecutor.\n assert(threads.size() == 0);\n threadInfo.reserve(numMaxThreads);\n threads.resize(numMaxThreads);\n for (int i = 0; i < numMaxThreads; ++i) {\n threadInfo.emplace_back(i, this);\n threads[i] = std::thread(threadBody, std::ref(threadInfo[i]));\n }\n }\n \n \/\/ Initialize fields to execute the new task.\n std::unique_lock<std::mutex> lock(runMutex);\n currentTask = &task;\n currentTaskCount = times;\n waitingThreadCount = 0;\n for (int i = 0; i < (int)threadInfo.size(); ++i) {\n threadInfo[i].running = true;\n }\n\n \/\/ Wake up the worker threads and wait until they finish.\n runCondition.notify_all();\n waitCondition.wait(lock,\n [&] { return waitingThreadCount == (int)threads.size(); });\n lock.unlock();\n}\nvoid ParallelExecutorImpl::incrementWaitingThreads() {\n std::lock_guard<std::mutex> lock(runMutex);\n getCurrentTask().finish();\n waitingThreadCount++;\n if (waitingThreadCount == (int)threads.size()) {\n waitCondition.notify_one();\n }\n}\n\nthread_local bool ParallelExecutorImpl::isWorker(false);\n\n\/**\n * This function contains the code executed by the worker threads.\n *\/\n\nvoid threadBody(ThreadInfo& info) {\n ParallelExecutorImpl::isWorker = true;\n ParallelExecutorImpl& executor = *info.executor;\n int threadCount = executor.getThreadCount();\n while (!executor.isFinished()) {\n \n \/\/ Wait for a Task to come in.\n \n std::unique_lock<std::mutex> lock(executor.getMutex());\n executor.getCondition().wait(lock, [&] { return info.running; });\n lock.unlock();\n if (!executor.isFinished()) {\n \n \/\/ Execute the task for all the indices belonging to this thread.\n \n int count = executor.getCurrentTaskCount();\n ParallelExecutor::Task& task = executor.getCurrentTask();\n task.initialize();\n int index = info.index;\n \n try {\n while (index < count) {\n task.execute(index);\n index += threadCount;\n }\n }\n catch (const std::exception& ex) {\n std::cerr <<\"The parallel task threw an unhandled exception:\"<< std::endl;\n std::cerr <<ex.what()<< std::endl;\n }\n catch (...) {\n std::cerr <<\"The parallel task threw an error.\"<< std::endl;\n }\n info.running = false;\n executor.incrementWaitingThreads();\n }\n }\n}\n\nParallelExecutor::ParallelExecutor() : HandleBase(new ParallelExecutorImpl()) {\n}\n\nParallelExecutor::ParallelExecutor(int numThreads) : HandleBase(new ParallelExecutorImpl(numThreads)) {\n}\n\nParallelExecutor* ParallelExecutor::clone() const{\n return new ParallelExecutor(getMaxThreads());\n}\n\nvoid ParallelExecutor::execute(Task& task, int times) {\n updImpl().execute(task, times);\n}\n\n#ifdef __APPLE__\n #include <sys\/sysctl.h>\n #include <dlfcn.h>\n#elif _WIN32\n #include <windows.h>\n#elif __linux__\n #include <dlfcn.h>\n #include <unistd.h>\n#else\n #error \"Architecture unsupported\"\n#endif\n\nint ParallelExecutor::getNumProcessors() {\n#ifdef __APPLE__\n int ncpu,retval;\n size_t len = 4;\n\n retval = sysctlbyname( \"hw.physicalcpu\", &ncpu, &len, NULL, 0 );\n if( retval == 0 ) {\n return (ncpu );\n } else {\n return(1);\n }\n#else\n#ifdef __linux__\n long nProcessorsOnline = sysconf(_SC_NPROCESSORS_ONLN);\n if( nProcessorsOnline == -1 ) {\n return(1);\n } else {\n return( (int)nProcessorsOnline );\n }\n#else\n \/\/ Windows\n\n SYSTEM_INFO siSysInfo;\n int ncpu;\n\n \/\/ Copy the hardware information to the SYSTEM_INFO structure.\n\n GetSystemInfo(&siSysInfo);\n\n \/\/ Display the contents of the SYSTEM_INFO structure.\n\n ncpu = siSysInfo.dwNumberOfProcessors;\n if( ncpu < 1 ) ncpu = 1;\n return(ncpu);\n#endif\n#endif\n}\n\nbool ParallelExecutor::isWorkerThread() {\n return ParallelExecutorImpl::isWorker;\n}\nint ParallelExecutor::getMaxThreads() const{\n return getImpl().getMaxThreads();\n}\n\n} \/\/ namespace SimTK\n<commit_msg>Fix build on FreeBSD (#726)<commit_after>\/* -------------------------------------------------------------------------- *\n * Simbody(tm): SimTKcommon *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2008-12 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"ParallelExecutorImpl.h\"\n#include \"SimTKcommon\/internal\/ParallelExecutor.h\"\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <mutex>\n\nusing namespace std;\n\nnamespace SimTK {\n\nstatic void threadBody(ThreadInfo& info);\n\nParallelExecutorImpl::ParallelExecutorImpl() : finished(false) {\n\n \/\/By default, we use the total number of processors available of the\n \/\/computer (including hyperthreads)\n numMaxThreads = ParallelExecutor::getNumProcessors();\n if(numMaxThreads <= 0)\n numMaxThreads = 1;\n}\nParallelExecutorImpl::ParallelExecutorImpl(int numThreads) : finished(false) {\n\n \/\/ Set the maximum number of threads that we can use\n SimTK_APIARGCHECK_ALWAYS(numThreads > 0, \"ParallelExecutorImpl\",\n \"ParallelExecutorImpl\", \"Number of threads must be positive.\");\n numMaxThreads = numThreads;\n}\nParallelExecutorImpl::~ParallelExecutorImpl() {\n \n \/\/ Notify the threads that they should exit.\n \n std::unique_lock<std::mutex> lock(runMutex);\n finished = true;\n for (int i = 0; i < (int) threads.size(); ++i)\n threadInfo[i].running = true;\n runCondition.notify_all();\n lock.unlock();\n \n \/\/ Wait until all the threads have finished.\n \n for (int i = 0; i < (int) threads.size(); ++i)\n threads[i].join();\n}\nParallelExecutorImpl* ParallelExecutorImpl::clone() const {\n return new ParallelExecutorImpl(numMaxThreads);\n}\nvoid ParallelExecutorImpl::execute(ParallelExecutor::Task& task, int times) {\n if (numMaxThreads < 2) {\n \/\/(1) NON-PARALLEL CASE:\n \/\/ Nothing is actually going to get done in parallel, so we might as well\n \/\/ just execute the task directly and save the threading overhead.\n task.initialize();\n for (int i = 0; i < times; ++i)\n task.execute(i);\n task.finish();\n return;\n }\n \n \/\/(2) PARALLEL CASE:\n \/\/ We launch the maximum number of threads and save them for later use\n if(threads.size() < (size_t)numMaxThreads)\n {\n \/\/ We do not support numMaxThreads changing for a given instance of\n \/\/ ParallelExecutor.\n assert(threads.size() == 0);\n threadInfo.reserve(numMaxThreads);\n threads.resize(numMaxThreads);\n for (int i = 0; i < numMaxThreads; ++i) {\n threadInfo.emplace_back(i, this);\n threads[i] = std::thread(threadBody, std::ref(threadInfo[i]));\n }\n }\n \n \/\/ Initialize fields to execute the new task.\n std::unique_lock<std::mutex> lock(runMutex);\n currentTask = &task;\n currentTaskCount = times;\n waitingThreadCount = 0;\n for (int i = 0; i < (int)threadInfo.size(); ++i) {\n threadInfo[i].running = true;\n }\n\n \/\/ Wake up the worker threads and wait until they finish.\n runCondition.notify_all();\n waitCondition.wait(lock,\n [&] { return waitingThreadCount == (int)threads.size(); });\n lock.unlock();\n}\nvoid ParallelExecutorImpl::incrementWaitingThreads() {\n std::lock_guard<std::mutex> lock(runMutex);\n getCurrentTask().finish();\n waitingThreadCount++;\n if (waitingThreadCount == (int)threads.size()) {\n waitCondition.notify_one();\n }\n}\n\nthread_local bool ParallelExecutorImpl::isWorker(false);\n\n\/**\n * This function contains the code executed by the worker threads.\n *\/\n\nvoid threadBody(ThreadInfo& info) {\n ParallelExecutorImpl::isWorker = true;\n ParallelExecutorImpl& executor = *info.executor;\n int threadCount = executor.getThreadCount();\n while (!executor.isFinished()) {\n \n \/\/ Wait for a Task to come in.\n \n std::unique_lock<std::mutex> lock(executor.getMutex());\n executor.getCondition().wait(lock, [&] { return info.running; });\n lock.unlock();\n if (!executor.isFinished()) {\n \n \/\/ Execute the task for all the indices belonging to this thread.\n \n int count = executor.getCurrentTaskCount();\n ParallelExecutor::Task& task = executor.getCurrentTask();\n task.initialize();\n int index = info.index;\n \n try {\n while (index < count) {\n task.execute(index);\n index += threadCount;\n }\n }\n catch (const std::exception& ex) {\n std::cerr <<\"The parallel task threw an unhandled exception:\"<< std::endl;\n std::cerr <<ex.what()<< std::endl;\n }\n catch (...) {\n std::cerr <<\"The parallel task threw an error.\"<< std::endl;\n }\n info.running = false;\n executor.incrementWaitingThreads();\n }\n }\n}\n\nParallelExecutor::ParallelExecutor() : HandleBase(new ParallelExecutorImpl()) {\n}\n\nParallelExecutor::ParallelExecutor(int numThreads) : HandleBase(new ParallelExecutorImpl(numThreads)) {\n}\n\nParallelExecutor* ParallelExecutor::clone() const{\n return new ParallelExecutor(getMaxThreads());\n}\n\nvoid ParallelExecutor::execute(Task& task, int times) {\n updImpl().execute(task, times);\n}\n\n#ifdef __APPLE__\n #include <sys\/sysctl.h>\n #include <dlfcn.h>\n#elif __FreeBSD__\n #include <sys\/types.h>\n #include <sys\/sysctl.h>\n#elif _WIN32\n #include <windows.h>\n#elif __linux__\n #include <dlfcn.h>\n #include <unistd.h>\n#else\n #error \"Architecture unsupported\"\n#endif\n\nint ParallelExecutor::getNumProcessors() {\n#ifdef __APPLE__\n int ncpu,retval;\n size_t len = 4;\n\n retval = sysctlbyname( \"hw.physicalcpu\", &ncpu, &len, NULL, 0 );\n if( retval == 0 ) {\n return (ncpu );\n } else {\n return(1);\n }\n#elif defined(__FreeBSD__)\n int mib[2];\n int ncpu;\n size_t szNcpu = sizeof(ncpu);\n\n mib[0] = CTL_HW;\n mib[1] = HW_NCPU;\n int ret = sysctl(mib, 2, &ncpu, &szNcpu, NULL, 0);\n return ret == 0 ? ncpu : 1;\n#elif defined(__linux__)\n long nProcessorsOnline = sysconf(_SC_NPROCESSORS_ONLN);\n if( nProcessorsOnline == -1 ) {\n return(1);\n } else {\n return( (int)nProcessorsOnline );\n }\n#elif defined(_WIN32)\n \/\/ Windows\n\n SYSTEM_INFO siSysInfo;\n int ncpu;\n\n \/\/ Copy the hardware information to the SYSTEM_INFO structure.\n\n GetSystemInfo(&siSysInfo);\n\n \/\/ Display the contents of the SYSTEM_INFO structure.\n\n ncpu = siSysInfo.dwNumberOfProcessors;\n if( ncpu < 1 ) ncpu = 1;\n return(ncpu);\n#else\n #error \"Architecture unsupported\"\n#endif\n}\n\nbool ParallelExecutor::isWorkerThread() {\n return ParallelExecutorImpl::isWorker;\n}\nint ParallelExecutor::getMaxThreads() const{\n return getImpl().getMaxThreads();\n}\n\n} \/\/ namespace SimTK\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#define MY_PARAM_TYPE(name, DType, MType) \\\n struct name { \\\n typedef DType DataType; \\\n typedef MType MassType; \\\n }; \\\n\n#include \"Sofa_test.h\"\n\n#include <SofaBaseMechanics\/DiagonalMass.h>\n\nnamespace sofa {\n\ntemplate <class T>\nclass SOFA_TestPlugin_API DiagonalMass_test : public ::testing::Test\n{\npublic :\n\n typedef typename T::DataType dt;\n typedef typename T::MassType mt;\n typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType;\n typename DiagonalMassType::SPtr m;\n\n \/**\n * Constructor call for each test\n *\/\n virtual void SetUp(){}\n};\n\nTYPED_TEST_CASE_P(DiagonalMass_test);\n\nTYPED_TEST_P(DiagonalMass_test, fakeTest1)\n{\n EXPECT_EQ(0,0);\n std::cout << this->m->templateName() << std::endl;\n}\n\nTYPED_TEST_P(DiagonalMass_test, fakeTest2)\n{\n EXPECT_EQ(0,1);\n std::cout << this->m->templateName() << std::endl;\n}\n\nREGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, fakeTest1, fakeTest2);\n\nMY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double)\nMY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double)\nMY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double)\n\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1, DiagonalMass_test, Vec3dd);\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2, DiagonalMass_test, Vec2dd);\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3, DiagonalMass_test, Vec1dd);\n\n} \/\/ namespace sofa\n<commit_msg>Fix test in DiagonalMass<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#define MY_PARAM_TYPE(name, DType, MType) \\\n struct name { \\\n typedef DType DataType; \\\n typedef MType MassType; \\\n }; \\\n\n#include \"Sofa_test.h\"\n\n#include <SofaBaseMechanics\/DiagonalMass.h>\n\n\/\/TODO : Perform smart tests :) Infrastructure for multi templated tests is ok.\n\nnamespace sofa {\n\ntemplate <class T>\nclass SOFA_TestPlugin_API DiagonalMass_test : public ::testing::Test\n{\npublic :\n\n typedef typename T::DataType dt;\n typedef typename T::MassType mt;\n typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType;\n typename DiagonalMassType::SPtr m;\n\n \/**\n * Constructor call for each test\n *\/\n virtual void SetUp(){}\n};\n\nTYPED_TEST_CASE_P(DiagonalMass_test);\n\nTYPED_TEST_P(DiagonalMass_test, fakeTest1)\n{\n EXPECT_EQ(0,0);\n}\n\nTYPED_TEST_P(DiagonalMass_test, fakeTest2)\n{\n EXPECT_EQ(1,1);\n}\n\nREGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, fakeTest1, fakeTest2);\n\nMY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double)\nMY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double)\nMY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double)\n\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1, DiagonalMass_test, Vec3dd);\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2, DiagonalMass_test, Vec2dd);\nINSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3, DiagonalMass_test, Vec1dd);\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/dreamview\/backend\/simulation_world\/simulation_world_updater.h\"\n\n#include \"google\/protobuf\/util\/json_util.h\"\n#include \"modules\/dreamview\/backend\/common\/dreamview_gflags.h\"\n#include \"modules\/map\/hdmap\/hdmap_util.h\"\n\nnamespace apollo {\nnamespace dreamview {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::monitor::MonitorMessageItem;\nusing apollo::common::util::GetProtoFromASCIIFile;\nusing apollo::hdmap::EndWayPointFile;\nusing apollo::routing::RoutingRequest;\nusing google::protobuf::util::MessageToJsonString;\nusing Json = nlohmann::json;\n\nSimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,\n const MapService *map_service,\n bool routing_from_file)\n : sim_world_service_(map_service, routing_from_file),\n map_service_(map_service),\n websocket_(websocket) {\n \/\/ Initialize default end point\n if (!GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {\n AWARN << \"Failed to load default end point from \" << EndWayPointFile();\n }\n\n websocket_->RegisterMessageHandler(\n \"RetrieveMapData\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n auto iter = json.find(\"elements\");\n if (iter != json.end()) {\n MapElementIds map_element_ids(*iter);\n auto retrieved = map_service_->RetrieveMapElements(map_element_ids);\n\n std::string retrieved_json_string;\n MessageToJsonString(retrieved, &retrieved_json_string);\n\n Json response;\n response[\"type\"] = \"MapData\";\n response[\"data\"] = Json::parse(retrieved_json_string);\n\n websocket_->SendData(conn, response.dump());\n }\n });\n\n websocket_->RegisterMessageHandler(\n \"RetrieveMapElementsByRadius\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n auto radius = json.find(\"radius\");\n if (radius == json.end()) {\n AERROR << \"Cannot retrieve map elements with unknown radius.\";\n return;\n }\n\n Json response = sim_world_service_.GetMapElements(*radius);\n response[\"type\"] = \"MapElements\";\n websocket_->SendData(conn, response.dump());\n });\n\n websocket_->RegisterMessageHandler(\n \"SendRoutingRequest\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n RoutingRequest routing_request;\n\n bool succeed = ConstructRoutingRequest(json, &routing_request);\n if (succeed) {\n AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,\n &routing_request);\n AdapterManager::PublishRoutingRequest(routing_request);\n }\n\n \/\/ Publish monitor message.\n if (succeed) {\n sim_world_service_.PublishMonitorMessage(\n MonitorMessageItem::INFO, \"Routing Request Sent\");\n } else {\n sim_world_service_.PublishMonitorMessage(\n MonitorMessageItem::ERROR, \"Failed to send routing request\");\n }\n });\n\n websocket_->RegisterMessageHandler(\n \"RequestSimulationWorld\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n if (!sim_world_service_.ReadyToPush()) {\n AWARN_EVERY(100)\n << \"Not sending simulation world as the data is not ready!\";\n return;\n }\n\n std::string to_send;\n {\n \/\/ Pay the price to copy the data instead of sending data over the\n \/\/ wire while holding the lock.\n boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);\n to_send = simulation_world_json_;\n }\n websocket_->SendData(conn, to_send, true);\n });\n}\n\nbool SimulationWorldUpdater::ConstructRoutingRequest(\n const Json &json, RoutingRequest *routing_request) {\n \/\/ Input validations\n if (json.find(\"start\") == json.end() ||\n json.find(\"sendDefaultRoute\") == json.end()) {\n AERROR << \"Cannot prepare a routing request: input validation failed.\";\n return false;\n }\n\n \/\/ Try to reload end point if it hasn't be loaded yet.\n if (!default_end_point_.has_id() &&\n !GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {\n AERROR << \"Failed to load default end point from \" << EndWayPointFile();\n return false;\n }\n\n \/\/ set start point\n auto start = json[\"start\"];\n if (start.find(\"x\") == start.end() || start.find(\"y\") == start.end()) {\n AERROR << \"Failed to prepare a routing request: start point not found\";\n return false;\n }\n map_service_->ConstructLaneWayPoint(start[\"x\"], start[\"y\"],\n routing_request->mutable_start());\n\n \/\/ set way point(s) if any\n auto iter = json.find(\"waypoint\");\n if (iter != json.end()) {\n auto *waypoint = routing_request->mutable_waypoint();\n for (size_t i = 0; i < iter->size(); ++i) {\n auto &point = (*iter)[i];\n if (!map_service_->ConstructLaneWayPoint(point[\"x\"], point[\"y\"],\n waypoint->Add())) {\n waypoint->RemoveLast();\n }\n }\n }\n\n \/\/ set end point\n RoutingRequest::LaneWaypoint *endLane = routing_request->mutable_end();\n if (json[\"sendDefaultRoute\"]) {\n endLane->set_id(default_end_point_.id());\n endLane->set_s(default_end_point_.s());\n auto *pose = endLane->mutable_pose();\n pose->set_x(default_end_point_.pose().x());\n pose->set_y(default_end_point_.pose().y());\n } else {\n if (json.find(\"end\") == json.end()) {\n AERROR << \"Failed to prepare a routing request: end point not found\";\n return false;\n }\n\n auto end = json[\"end\"];\n if (end.find(\"x\") == end.end() || end.find(\"y\") == end.end()) {\n AERROR << \"Failed to prepare a routing request: end point not found\";\n return false;\n }\n map_service_->ConstructLaneWayPoint(end[\"x\"], end[\"y\"], endLane);\n }\n\n return true;\n}\n\nvoid SimulationWorldUpdater::Start() {\n \/\/ start ROS timer, one-shot = false, auto-start = true\n timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),\n &SimulationWorldUpdater::OnTimer, this);\n}\n\nvoid SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {\n sim_world_service_.Update();\n\n {\n boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);\n\n simulation_world_json_ =\n sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();\n }\n}\n\n} \/\/ namespace dreamview\n} \/\/ namespace apollo\n<commit_msg>Dreamview: Load default end when needed (#449)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/dreamview\/backend\/simulation_world\/simulation_world_updater.h\"\n\n#include \"google\/protobuf\/util\/json_util.h\"\n#include \"modules\/dreamview\/backend\/common\/dreamview_gflags.h\"\n#include \"modules\/map\/hdmap\/hdmap_util.h\"\n\nnamespace apollo {\nnamespace dreamview {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::monitor::MonitorMessageItem;\nusing apollo::common::util::GetProtoFromASCIIFile;\nusing apollo::hdmap::EndWayPointFile;\nusing apollo::routing::RoutingRequest;\nusing google::protobuf::util::MessageToJsonString;\nusing Json = nlohmann::json;\n\nSimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,\n const MapService *map_service,\n bool routing_from_file)\n : sim_world_service_(map_service, routing_from_file),\n map_service_(map_service),\n websocket_(websocket) {\n \/\/ Initialize default end point\n if (!GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {\n AWARN << \"Failed to load default end point from \" << EndWayPointFile();\n }\n\n websocket_->RegisterMessageHandler(\n \"RetrieveMapData\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n auto iter = json.find(\"elements\");\n if (iter != json.end()) {\n MapElementIds map_element_ids(*iter);\n auto retrieved = map_service_->RetrieveMapElements(map_element_ids);\n\n std::string retrieved_json_string;\n MessageToJsonString(retrieved, &retrieved_json_string);\n\n Json response;\n response[\"type\"] = \"MapData\";\n response[\"data\"] = Json::parse(retrieved_json_string);\n\n websocket_->SendData(conn, response.dump());\n }\n });\n\n websocket_->RegisterMessageHandler(\n \"RetrieveMapElementsByRadius\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n auto radius = json.find(\"radius\");\n if (radius == json.end()) {\n AERROR << \"Cannot retrieve map elements with unknown radius.\";\n return;\n }\n\n Json response = sim_world_service_.GetMapElements(*radius);\n response[\"type\"] = \"MapElements\";\n websocket_->SendData(conn, response.dump());\n });\n\n websocket_->RegisterMessageHandler(\n \"SendRoutingRequest\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n RoutingRequest routing_request;\n\n bool succeed = ConstructRoutingRequest(json, &routing_request);\n if (succeed) {\n AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,\n &routing_request);\n AdapterManager::PublishRoutingRequest(routing_request);\n }\n\n \/\/ Publish monitor message.\n if (succeed) {\n sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,\n \"Routing Request Sent\");\n } else {\n sim_world_service_.PublishMonitorMessage(\n MonitorMessageItem::ERROR, \"Failed to send routing request\");\n }\n });\n\n websocket_->RegisterMessageHandler(\n \"RequestSimulationWorld\",\n [this](const Json &json, WebSocketHandler::Connection *conn) {\n if (!sim_world_service_.ReadyToPush()) {\n AWARN_EVERY(100)\n << \"Not sending simulation world as the data is not ready!\";\n return;\n }\n\n std::string to_send;\n {\n \/\/ Pay the price to copy the data instead of sending data over the\n \/\/ wire while holding the lock.\n boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);\n to_send = simulation_world_json_;\n }\n websocket_->SendData(conn, to_send, true);\n });\n}\n\nbool SimulationWorldUpdater::ConstructRoutingRequest(\n const Json &json, RoutingRequest *routing_request) {\n \/\/ Input validations\n if (json.find(\"start\") == json.end() ||\n json.find(\"sendDefaultRoute\") == json.end()) {\n AERROR << \"Cannot prepare a routing request: input validation failed.\";\n return false;\n }\n\n \/\/ set start point\n auto start = json[\"start\"];\n if (start.find(\"x\") == start.end() || start.find(\"y\") == start.end()) {\n AERROR << \"Failed to prepare a routing request: start point not found\";\n return false;\n }\n map_service_->ConstructLaneWayPoint(start[\"x\"], start[\"y\"],\n routing_request->mutable_start());\n\n \/\/ set way point(s) if any\n auto iter = json.find(\"waypoint\");\n if (iter != json.end()) {\n auto *waypoint = routing_request->mutable_waypoint();\n for (size_t i = 0; i < iter->size(); ++i) {\n auto &point = (*iter)[i];\n if (!map_service_->ConstructLaneWayPoint(point[\"x\"], point[\"y\"],\n waypoint->Add())) {\n waypoint->RemoveLast();\n }\n }\n }\n\n \/\/ set end point\n RoutingRequest::LaneWaypoint *endLane = routing_request->mutable_end();\n if (json[\"sendDefaultRoute\"]) {\n \/\/ Try to reload end point if it hasn't been loaded yet.\n if (!default_end_point_.has_id() &&\n !GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_)) {\n AERROR << \"Failed to load default end point from \" << EndWayPointFile();\n return false;\n }\n\n endLane->set_id(default_end_point_.id());\n endLane->set_s(default_end_point_.s());\n auto *pose = endLane->mutable_pose();\n pose->set_x(default_end_point_.pose().x());\n pose->set_y(default_end_point_.pose().y());\n } else {\n if (json.find(\"end\") == json.end()) {\n AERROR << \"Failed to prepare a routing request: end point not found\";\n return false;\n }\n\n auto end = json[\"end\"];\n if (end.find(\"x\") == end.end() || end.find(\"y\") == end.end()) {\n AERROR << \"Failed to prepare a routing request: end point not found\";\n return false;\n }\n map_service_->ConstructLaneWayPoint(end[\"x\"], end[\"y\"], endLane);\n }\n\n return true;\n}\n\nvoid SimulationWorldUpdater::Start() {\n \/\/ start ROS timer, one-shot = false, auto-start = true\n timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),\n &SimulationWorldUpdater::OnTimer, this);\n}\n\nvoid SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {\n sim_world_service_.Update();\n\n {\n boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);\n\n simulation_world_json_ =\n sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();\n }\n}\n\n} \/\/ namespace dreamview\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <windows.h>\n#include <TlHelp32.h>\n#include <vector>\n#include \"process.h\"\n#include \"memoryjs.h\"\n\nprocess::process() {}\n\nprocess::~process() {\n\tCloseHandle(hProcess);\n}\n\nusing v8::Exception;\nusing v8::Isolate;\nusing v8::String;\n\nPROCESSENTRY32 process::processEntry;\nHANDLE process::hProcess;\n\nPROCESSENTRY32 process::openProcess(const char* processName, char** errorMessage){\n\tPROCESSENTRY32 process;\n\n\t\/\/ A list of processes (PROCESSENTRY32)\n\tstd::vector<PROCESSENTRY32> processes = getProcesses(errorMessage);\n\n\tfor(std::vector<PROCESSENTRY32>::size_type i = 0; i != processes.size(); i++){\n\t\t\/\/ Check to see if this is the process we want.\n\t\tif (!strcmp(processes[i].szExeFile, processName)) {\n\t\t\t\/\/ Store the process handle and process ID internally\n\t\t\t\/\/ for reading\/writing to memory\n\t\t\tprocess::hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processes[i].th32ProcessID);\n\n\t\t\t\/\/ Store the handle (just for reference to close the handle later)\n\t\t\t\/\/ process is returned and processEntry is used internally for reading\/writing to memory\n\t\t\thandle = (int) process::hProcess;\n\t\t\tprocess = processEntry = processes[i];\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn process;\n}\n\nvoid process::closeProcess(){\n\tCloseHandle((HANDLE) handle);\n}\n\nstd::vector<PROCESSENTRY32> process::getProcesses(char** errorMessage) {\n\t\/\/ Take a snapshot of all processes.\n\tHANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);\n\tPROCESSENTRY32 pEntry;\n\n\tif (hProcessSnapshot == INVALID_HANDLE_VALUE) {\n\t\t*errorMessage = \"method failed to take snapshot of the process\";\n\t}\n\n\t\/\/ Before use, set the structure size.\n\tpEntry.dwSize = sizeof(pEntry);\n\n\t\/\/ Exit if unable to find the first process.\n\tif (!Process32First(hProcessSnapshot, &pEntry)) {\n\t\tCloseHandle(hProcessSnapshot);\n\t\t*errorMessage = \"method failed to retrieve the first process\";\n\t}\n\n\tstd::vector<PROCESSENTRY32> processes;\n\n\t\/\/ Loop through processes.\n\tdo {\n\t\t\/\/ Add the process to the vector\n\t\tprocesses.push_back(pEntry);\n\t} while (Process32Next(hProcessSnapshot, &pEntry));\n\n\tCloseHandle(hProcessSnapshot);\n\treturn processes;\n}\n<commit_msg>closed process handle correctly<commit_after>#include <node.h>\n#include <windows.h>\n#include <TlHelp32.h>\n#include <vector>\n#include \"process.h\"\n#include \"memoryjs.h\"\n\nprocess::process() {}\n\nprocess::~process() {\n\tCloseHandle(hProcess);\n}\n\nusing v8::Exception;\nusing v8::Isolate;\nusing v8::String;\n\nPROCESSENTRY32 process::processEntry;\nHANDLE process::hProcess;\n\nPROCESSENTRY32 process::openProcess(const char* processName, char** errorMessage){\n\tPROCESSENTRY32 process;\n\n\t\/\/ A list of processes (PROCESSENTRY32)\n\tstd::vector<PROCESSENTRY32> processes = getProcesses(errorMessage);\n\n\tfor(std::vector<PROCESSENTRY32>::size_type i = 0; i != processes.size(); i++){\n\t\t\/\/ Check to see if this is the process we want.\n\t\tif (!strcmp(processes[i].szExeFile, processName)) {\n\t\t\t\/\/ Store the process handle and process ID internally\n\t\t\t\/\/ for reading\/writing to memory\n\t\t\tprocess::hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processes[i].th32ProcessID);\n\n\t\t\t\/\/ Store the handle (just for reference to close the handle later)\n\t\t\t\/\/ process is returned and processEntry is used internally for reading\/writing to memory\n\t\t\thandle = (int) process::hProcess;\n\t\t\tprocess = processEntry = processes[i];\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn process;\n}\n\nvoid process::closeProcess(){\n\tCloseHandle(process::hProcess);\n}\n\nstd::vector<PROCESSENTRY32> process::getProcesses(char** errorMessage) {\n\t\/\/ Take a snapshot of all processes.\n\tHANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);\n\tPROCESSENTRY32 pEntry;\n\n\tif (hProcessSnapshot == INVALID_HANDLE_VALUE) {\n\t\t*errorMessage = \"method failed to take snapshot of the process\";\n\t}\n\n\t\/\/ Before use, set the structure size.\n\tpEntry.dwSize = sizeof(pEntry);\n\n\t\/\/ Exit if unable to find the first process.\n\tif (!Process32First(hProcessSnapshot, &pEntry)) {\n\t\tCloseHandle(hProcessSnapshot);\n\t\t*errorMessage = \"method failed to retrieve the first process\";\n\t}\n\n\tstd::vector<PROCESSENTRY32> processes;\n\n\t\/\/ Loop through processes.\n\tdo {\n\t\t\/\/ Add the process to the vector\n\t\tprocesses.push_back(pEntry);\n\t} while (Process32Next(hProcessSnapshot, &pEntry));\n\n\tCloseHandle(hProcessSnapshot);\n\treturn processes;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Be careful to use a platform-specific conditional include to only make the\n\/\/ code visible for the appropriate platform. Arduino will try to compile and\n\/\/ link all .cpp files regardless of platform.\n#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__)\n\n#include <avr\/interrupt.h>\n#include <avr\/power.h>\n#include <avr\/sleep.h>\n#include <avr\/wdt.h>\n\n#include \"WatchdogAVR.h\"\n\n\/\/ Define watchdog timer interrupt.\nISR(WDT_vect)\n{\n \/\/ Nothing needs to be done, however interrupt handler must be defined to\n \/\/ prevent a reset.\n}\n\nint WatchdogAVR::enable(int maxPeriodMS) {\n \/\/ Pick the closest appropriate watchdog timer value.\n int actualMS;\n _setPeriod(maxPeriodMS, _wdto, actualMS);\n \/\/ Enable the watchdog and return the actual countdown value.\n wdt_enable(_wdto);\n return actualMS;\n}\n\nvoid WatchdogAVR::reset() {\n \/\/ Reset the watchdog.\n wdt_reset();\n}\n\nvoid WatchdogAVR::disable() {\n \/\/ Disable the watchdog and clear any saved watchdog timer value.\n wdt_disable();\n _wdto = -1;\n}\n\nint WatchdogAVR::sleep(int maxPeriodMS) {\n \/\/ Pick the closest appropriate watchdog timer value.\n int sleepWDTO, actualMS;\n _setPeriod(maxPeriodMS, sleepWDTO, actualMS);\n\n \/\/ Build watchdog prescaler register value before timing critical code.\n uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) |\n ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) |\n ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) |\n ((sleepWDTO & 0x01 ? 1 : 0) << WDP0);\n\n \/\/ The next section is timing critical so interrupts are disabled.\n cli();\n \/\/ First clear any previous watchdog reset.\n MCUSR &= ~(1<<WDRF);\n \/\/ Now change the watchdog prescaler and interrupt enable bit so the watchdog\n \/\/ reset only triggers the interrupt (and wakes from deep sleep) and not a \n \/\/ full device reset. This is a timing critical section of code that must \n \/\/ happen in 4 cycles.\n WDTCSR |= (1<<WDCE) | (1<<WDE); \/\/ Set WDCE and WDE to enable changes.\n WDTCSR = wdps; \/\/ Set the prescaler bit values.\n WDTCSR |= (1<<WDIE); \/\/ Enable only watchdog interrupts.\n \/\/ Critical section finished, re-enable interrupts.\n sei();\n\n \/\/ Set full power-down sleep mode and go to sleep.\n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n sleep_mode();\n\n \/\/ Chip is now asleep!\n\n \/\/ Once awakened by the watchdog execution resumes here. Start by disabling\n \/\/ sleep.\n sleep_disable();\n\n \/\/ Check if the user had the watchdog enabled before sleep and re-enable it.\n if (_wdto != -1) {\n wdt_enable(_wdto);\n }\n\n \/\/ Return how many actual milliseconds were spent sleeping.\n return actualMS;\n}\n\nvoid WatchdogAVR::_setPeriod(int maxMS, int &wdto, int &actualMS) {\n \/\/ Note the order of these if statements from highest to lowest is \n \/\/ important so that control flow cascades down to the right value based\n \/\/ on its position in the range of discrete timeouts.\n if ((maxMS >= 8000) || (maxMS == 0)) {\n wdto = WDTO_8S;\n actualMS = 8000;\n }\n else if (maxMS >= 4000) {\n wdto = WDTO_4S;\n actualMS = 4000;\n }\n else if (maxMS >= 2000) {\n wdto = WDTO_2S;\n actualMS = 2000;\n }\n else if (maxMS >= 1000) {\n wdto = WDTO_1S;\n actualMS = 1000;\n }\n else if (maxMS >= 500) {\n wdto = WDTO_500MS;\n actualMS = 500;\n }\n else if (maxMS >= 250) {\n wdto = WDTO_250MS;\n actualMS = 250;\n }\n else if (maxMS >= 120) {\n wdto = WDTO_120MS;\n actualMS = 120;\n }\n else if (maxMS >= 60) {\n wdto = WDTO_60MS;\n actualMS = 60;\n }\n else if (maxMS >= 30) {\n wdto = WDTO_30MS;\n actualMS = 30;\n }\n else {\n wdto = WDTO_15MS;\n actualMS = 15;\n }\n}\n\n#endif<commit_msg>disable USB on '32u4 for ~200uA savings<commit_after>\/\/ Be careful to use a platform-specific conditional include to only make the\n\/\/ code visible for the appropriate platform. Arduino will try to compile and\n\/\/ link all .cpp files regardless of platform.\n#if defined(ARDUINO_ARCH_AVR) || defined(__AVR__)\n\n#include <avr\/interrupt.h>\n#include <avr\/power.h>\n#include <avr\/sleep.h>\n#include <avr\/wdt.h>\n\n#include \"WatchdogAVR.h\"\n\n\/\/ Define watchdog timer interrupt.\nISR(WDT_vect)\n{\n \/\/ Nothing needs to be done, however interrupt handler must be defined to\n \/\/ prevent a reset.\n}\n\nint WatchdogAVR::enable(int maxPeriodMS) {\n \/\/ Pick the closest appropriate watchdog timer value.\n int actualMS;\n _setPeriod(maxPeriodMS, _wdto, actualMS);\n \/\/ Enable the watchdog and return the actual countdown value.\n wdt_enable(_wdto);\n return actualMS;\n}\n\nvoid WatchdogAVR::reset() {\n \/\/ Reset the watchdog.\n wdt_reset();\n}\n\nvoid WatchdogAVR::disable() {\n \/\/ Disable the watchdog and clear any saved watchdog timer value.\n wdt_disable();\n _wdto = -1;\n}\n\nint WatchdogAVR::sleep(int maxPeriodMS) {\n \/\/ Pick the closest appropriate watchdog timer value.\n int sleepWDTO, actualMS;\n _setPeriod(maxPeriodMS, sleepWDTO, actualMS);\n\n \/\/ Build watchdog prescaler register value before timing critical code.\n uint8_t wdps = ((sleepWDTO & 0x08 ? 1 : 0) << WDP3) |\n ((sleepWDTO & 0x04 ? 1 : 0) << WDP2) |\n ((sleepWDTO & 0x02 ? 1 : 0) << WDP1) |\n ((sleepWDTO & 0x01 ? 1 : 0) << WDP0);\n\n \/\/ The next section is timing critical so interrupts are disabled.\n cli();\n \/\/ First clear any previous watchdog reset.\n MCUSR &= ~(1<<WDRF);\n \/\/ Now change the watchdog prescaler and interrupt enable bit so the watchdog\n \/\/ reset only triggers the interrupt (and wakes from deep sleep) and not a \n \/\/ full device reset. This is a timing critical section of code that must \n \/\/ happen in 4 cycles.\n WDTCSR |= (1<<WDCE) | (1<<WDE); \/\/ Set WDCE and WDE to enable changes.\n WDTCSR = wdps; \/\/ Set the prescaler bit values.\n WDTCSR |= (1<<WDIE); \/\/ Enable only watchdog interrupts.\n \/\/ Critical section finished, re-enable interrupts.\n sei();\n\n \/\/ Disable USB if it exists\n #ifdef USBCON\n USBCON |= _BV(FRZCLK); \/\/freeze USB clock\n PLLCSR &= ~_BV(PLLE); \/\/ turn off USB PLL\n USBCON &= ~_BV(USBE); \/\/ disable USB\n #endif\n\n \/\/ Set full power-down sleep mode and go to sleep.\n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n sleep_mode();\n\n \/\/ Chip is now asleep!\n\n \/\/ Once awakened by the watchdog execution resumes here. Start by disabling\n \/\/ sleep.\n sleep_disable();\n\n \/\/ Check if the user had the watchdog enabled before sleep and re-enable it.\n if (_wdto != -1) {\n wdt_enable(_wdto);\n }\n\n \/\/ Return how many actual milliseconds were spent sleeping.\n return actualMS;\n}\n\nvoid WatchdogAVR::_setPeriod(int maxMS, int &wdto, int &actualMS) {\n \/\/ Note the order of these if statements from highest to lowest is \n \/\/ important so that control flow cascades down to the right value based\n \/\/ on its position in the range of discrete timeouts.\n if ((maxMS >= 8000) || (maxMS == 0)) {\n wdto = WDTO_8S;\n actualMS = 8000;\n }\n else if (maxMS >= 4000) {\n wdto = WDTO_4S;\n actualMS = 4000;\n }\n else if (maxMS >= 2000) {\n wdto = WDTO_2S;\n actualMS = 2000;\n }\n else if (maxMS >= 1000) {\n wdto = WDTO_1S;\n actualMS = 1000;\n }\n else if (maxMS >= 500) {\n wdto = WDTO_500MS;\n actualMS = 500;\n }\n else if (maxMS >= 250) {\n wdto = WDTO_250MS;\n actualMS = 250;\n }\n else if (maxMS >= 120) {\n wdto = WDTO_120MS;\n actualMS = 120;\n }\n else if (maxMS >= 60) {\n wdto = WDTO_60MS;\n actualMS = 60;\n }\n else if (maxMS >= 30) {\n wdto = WDTO_30MS;\n actualMS = 30;\n }\n else {\n wdto = WDTO_15MS;\n actualMS = 15;\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Cosa\/Canvas\/Font\/FixedNums8x16.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2012-2014, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Canvas\/Font\/FixedNums8x16.hh\"\n#include \"Cosa\/Board.hh\"\n\nFixedNums8x16 fixednums8x16;\n\nconst uint8_t FixedNums8x16::width = 8;\nconst uint8_t FixedNums8x16::height = 16;\nconst uint8_t FixedNums8x16::first = '+';\nconst uint8_t FixedNums8x16::last = ':';\n\nconst uint8_t FixedNums8x16::bitmap[] __PROGMEM = {\n 8,16,'+',':',\n 0x80, 0x80, 0x80, 0xe0, 0xe0, 0x80, 0x80, 0x80, \n 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, \/\/ char '+'\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0xb0, 0x70, 0x00, 0x00, 0x00, \/\/ char ','\n 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \/\/ char '-'\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, \/\/ char '.'\n 0x00, 0x00, 0x00, 0xc0, 0xf0, 0x3c, 0x0f, 0x03, \n 0x30, 0x3c, 0x0f, 0x03, 0x00, 0x00, 0x00, 0x00, \/\/ char '\/'\n 0xfc, 0xfe, 0x03, 0x81, 0x61, 0x1b, 0xfe, 0xfc,\n 0x0f, 0x1f, 0x36, 0x21, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '0'\n 0x04, 0x04, 0x06, 0xff, 0xff, 0x00, 0x00, 0x00,\n 0x20, 0x20, 0x20, 0x3f, 0x3f, 0x20, 0x20, 0x20, \/\/ char '1'\n 0x0c, 0x0e, 0x03, 0x01, 0x81, 0xc3, 0x7e, 0x3c,\n 0x38, 0x3c, 0x26, 0x23, 0x21, 0x20, 0x20, 0x20, \/\/ char '2'\n 0x0c, 0x0e, 0x43, 0x41, 0x41, 0x43, 0xfe, 0xbc,\n 0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '3'\n 0x00, 0xe0, 0xfc, 0x1f, 0x83, 0x80, 0x00, 0x00,\n 0x0f, 0x0f, 0x08, 0x08, 0x3f, 0x3f, 0x08, 0x08, \/\/ char '4'\n#if defined(BOARD_ATMEGA2560)\n 0x3f, 0x3f, 0x21, 0x21, 0x41, 0x61, 0xc1, 0x81,\n#else\n 0x3f, 0x3f, 0x21, 0x21, 0x21, 0x61, 0xc1, 0x81,\n#endif\n 0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '5'\n 0xe0, 0xf8, 0x5c, 0x46, 0x43, 0xc1, 0x81, 0x01,\n 0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '6'\n 0x01, 0x01, 0x01, 0x01, 0x81, 0xf1, 0x7f, 0x0f,\n 0x00, 0x00, 0x00, 0x3c, 0x3f, 0x03, 0x00, 0x00, \/\/ char '7'\n 0x1c, 0xbe, 0xe3, 0x41, 0x41, 0xe3, 0xbe, 0x1c,\n 0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '8'\n 0x3c, 0x7e, 0xc3, 0x81, 0x81, 0x83, 0xfe, 0xfc,\n 0x20, 0x20, 0x20, 0x30, 0x18, 0x0e, 0x07, 0x01, \/\/ char '9'\n 0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00 \/\/ char ':\n};\n<commit_msg>Remove specs from FixedNums font bitmap<commit_after>\/**\n * @file Cosa\/Canvas\/Font\/FixedNums8x16.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2012-2014, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Canvas\/Font\/FixedNums8x16.hh\"\n#include \"Cosa\/Board.hh\"\n\nFixedNums8x16 fixednums8x16;\n\nconst uint8_t FixedNums8x16::width = 8;\nconst uint8_t FixedNums8x16::height = 16;\nconst uint8_t FixedNums8x16::first = '+';\nconst uint8_t FixedNums8x16::last = ':';\n\nconst uint8_t FixedNums8x16::bitmap[] __PROGMEM = {\n 0x80, 0x80, 0x80, 0xe0, 0xe0, 0x80, 0x80, 0x80, \n 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, \/\/ char '+'\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0xb0, 0x70, 0x00, 0x00, 0x00, \/\/ char ','\n 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, \n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \/\/ char '-'\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, \/\/ char '.'\n 0x00, 0x00, 0x00, 0xc0, 0xf0, 0x3c, 0x0f, 0x03, \n 0x30, 0x3c, 0x0f, 0x03, 0x00, 0x00, 0x00, 0x00, \/\/ char '\/'\n 0xfc, 0xfe, 0x03, 0x81, 0x61, 0x1b, 0xfe, 0xfc,\n 0x0f, 0x1f, 0x36, 0x21, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '0'\n 0x04, 0x04, 0x06, 0xff, 0xff, 0x00, 0x00, 0x00,\n 0x20, 0x20, 0x20, 0x3f, 0x3f, 0x20, 0x20, 0x20, \/\/ char '1'\n 0x0c, 0x0e, 0x03, 0x01, 0x81, 0xc3, 0x7e, 0x3c,\n 0x38, 0x3c, 0x26, 0x23, 0x21, 0x20, 0x20, 0x20, \/\/ char '2'\n 0x0c, 0x0e, 0x43, 0x41, 0x41, 0x43, 0xfe, 0xbc,\n 0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '3'\n 0x00, 0xe0, 0xfc, 0x1f, 0x83, 0x80, 0x00, 0x00,\n 0x0f, 0x0f, 0x08, 0x08, 0x3f, 0x3f, 0x08, 0x08, \/\/ char '4'\n#if defined(BOARD_ATMEGA2560)\n 0x3f, 0x3f, 0x21, 0x21, 0x41, 0x61, 0xc1, 0x81,\n#else\n 0x3f, 0x3f, 0x21, 0x21, 0x21, 0x61, 0xc1, 0x81,\n#endif\n 0x0c, 0x1c, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '5'\n 0xe0, 0xf8, 0x5c, 0x46, 0x43, 0xc1, 0x81, 0x01,\n 0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '6'\n 0x01, 0x01, 0x01, 0x01, 0x81, 0xf1, 0x7f, 0x0f,\n 0x00, 0x00, 0x00, 0x3c, 0x3f, 0x03, 0x00, 0x00, \/\/ char '7'\n 0x1c, 0xbe, 0xe3, 0x41, 0x41, 0xe3, 0xbe, 0x1c,\n 0x0f, 0x1f, 0x30, 0x20, 0x20, 0x30, 0x1f, 0x0f, \/\/ char '8'\n 0x3c, 0x7e, 0xc3, 0x81, 0x81, 0x83, 0xfe, 0xfc,\n 0x20, 0x20, 0x20, 0x30, 0x18, 0x0e, 0x07, 0x01, \/\/ char '9'\n 0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00 \/\/ char ':\n};\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iodlgimp.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:33:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _IODLGIMP_HXX\n#define _IODLGIMP_HXX\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_MENUBTN_HXX\n#include <vcl\/menubtn.hxx>\n#endif\n#ifndef _SV_TIMER_HXX\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _SV_GROUP_HXX\n#include <vcl\/group.hxx>\n#endif\n\n#include \"svtools\/svarray.hxx\"\n\n#include <vector>\n\n\/\/*****************************************************************************\n\nclass Accelerator;\nclass CheckBox;\nclass SvtFileDialog;\nclass SvStringsDtor;\nclass SvUShorts;\n\n\/\/*****************************************************************************\n\n#define FILEDIALOG_DEF_EXTSEP ';'\n#define FILEDIALOG_DEF_WILDCARD '*'\n#define FILEDIALOG_DEF_IMAGEBORDER 10\n#define FILEDIALOG_DEF_TIMEOUT 250\n\n\/\/*****************************************************************************\n\nString GetRegularExpression_Impl( const String& rFilter );\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogFilter_Impl\n\/\/*****************************************************************************\n\n\/* [Beschreibung]\n\n Instanzen dieser Klasse repr\"asentieren einen Filter\n*\/\n\nclass SvtFileDialogFilter_Impl\n{\nprivate:\n String m_aName; \/\/ name of the entry\n String m_aType; \/\/ filter wildcard - if empty, the entry marks a group\n\npublic:\n SvtFileDialogFilter_Impl( const String& rName, const String& rType );\n ~SvtFileDialogFilter_Impl();\n\n const String& GetName() const { return m_aName; }\n const String& GetType() const { return m_aType; }\n\n sal_Bool isGroupSeparator() const { return 0 == m_aType.Len(); }\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogFilterList_Impl\n\/\/*****************************************************************************\n\nSV_DECL_PTRARR_DEL( SvtFileDialogFilterList_Impl, SvtFileDialogFilter_Impl*, 3, 3 );\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgMode\n\/\/*****************************************************************************\n\nenum SvtFileDlgMode\n{\n FILEDLG_MODE_OPEN = 0,\n FILEDLG_MODE_SAVE = 1\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgType\n\/\/*****************************************************************************\n\nenum SvtFileDlgType\n{\n FILEDLG_TYPE_FILEDLG = 0,\n FILEDLG_TYPE_PATHDLG\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogURLSelector\n\/\/*****************************************************************************\nclass SvtFileDialogURLSelector : public MenuButton\n{\nprivate:\n SvtFileDialog* m_pParent;\n PopupMenu* m_pMenu;\n\nprotected:\n\/\/ inline const SvtFileDialog* GetParent() const { return _pParent; }\n inline SvtFileDialog* GetParent() { return m_pParent; }\n\nprotected:\n void OpenURL( const String& rURL );\n\n virtual void FillURLMenu( PopupMenu* _pMenu ) = 0;\n\nprotected:\n SvtFileDialogURLSelector( SvtFileDialog* _pParent, const ResId& _rResId, sal_uInt16 _nButtonId );\n ~SvtFileDialogURLSelector();\n\n virtual void Activate();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtUpButton_Impl\n\/\/*****************************************************************************\n\nclass SvtUpButton_Impl : public SvtFileDialogURLSelector\n{\nprivate:\n SvStringsDtor* _pURLs;\n\npublic:\n SvtUpButton_Impl( SvtFileDialog* pParent, const ResId& rResId );\n ~SvtUpButton_Impl();\n\nprotected:\n virtual void FillURLMenu( PopupMenu* _pMenu );\n virtual void Select();\n virtual void Click();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtTravelButton_Impl\n\/\/*****************************************************************************\n\nclass SvtTravelButton_Impl : public SvtFileDialogURLSelector\n{\nprivate:\n ::std::vector< String > m_aFavourites;\n\npublic:\n SvtTravelButton_Impl( SvtFileDialog* pParent, const ResId& rResId );\n ~SvtTravelButton_Impl();\n\n void SetFavouriteLocations( const ::std::vector< String >& _rLocations );\n\nprotected:\n virtual void FillURLMenu( PopupMenu* _pMenu );\n virtual void Select();\n virtual void Click();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgState\n\/\/*****************************************************************************\n\ntypedef sal_uInt8 SvtFileDlgState;\n\n#define FILEDLG_STATE_NONE ((SvtFileDlgState)0x00)\n#define FILEDLG_STATE_REMOTE ((SvtFileDlgState)0x01)\n\n\/\/*****************************************************************************\n\/\/ SvtExpFileDlg_Impl\n\/\/*****************************************************************************\nclass SvtURLBox;\nclass SvtExpFileDlg_Impl\n{\nprivate:\n DECL_STATIC_LINK( SvtExpFileDlg_Impl, UnClickHdl, Button* );\n\nprivate:\n ListBox* _pLbFilter;\n\n const SvtFileDialogFilter_Impl* _pCurFilter;\n String m_sCurrentFilterDisplayName; \/\/ may differ from _pCurFilter->GetName in case it is a cached entry\n\npublic:\n SvtFileDialogFilterList_Impl* _pFilter;\n SvtFileDialogFilter_Impl* _pUserFilter;\n\n FixedText* _pFtFileName;\n SvtURLBox* _pEdFileName;\n\n FixedText* _pFtFileVersion;\n ListBox* _pLbFileVersion;\n\n FixedText* _pFtTemplates;\n ListBox* _pLbTemplates;\n\n FixedText* _pFtImageTemplates;\n ListBox* _pLbImageTemplates;\n\n FixedText* _pFtFileType;\n PushButton* _pBtnFileOpen;\n PushButton* _pBtnCancel;\n HelpButton* _pBtnHelp;\n SvtUpButton_Impl* _pBtnUp;\n ImageButton* _pBtnNewFolder;\n SvtTravelButton_Impl* _pBtnStandard;\n CheckBox* _pCbPassword;\n FixedText* _pFtCurrentPath;\n CheckBox* _pCbAutoExtension;\n CheckBox* _pCbOptions;\n\n SvtFileDlgMode _eMode;\n SvtFileDlgType _eDlgType;\n SvtFileDlgState _nState;\n WinBits _nStyle;\n\n String _aStdDir;\n\n \/\/ beim traveln der Filterbox erst Zeitversetzt filtern\n Timer _aFilterTimer;\n\n \/\/ Zeigt der OpenHdl_Imp(), ob das Open durch einen Doppelclick ausgel\"ost wurde\n sal_Bool _bDoubleClick;\n sal_Bool m_bNeedDelayedFilterExecute;\n\n \/\/ Liste mit den 5 zuletzt genutzten Filtern\n \/\/ Defaultfilter fuer <Alle> oder <Alle ...>\n const SvtFileDialogFilter_Impl* _pDefaultFilter;\n\n \/\/ Multiselektion?\n sal_Bool _bMultiSelection;\n\n \/\/ Fixgr\"ossen f\"ur Resize merken\n long _nFixDeltaHeight;\n Size _a6Size;\n Size _aDlgSize;\n String _aIniKey;\n\n sal_Bool _bFolderHasOpened;\n\n SvtExpFileDlg_Impl( WinBits nBits );\n ~SvtExpFileDlg_Impl();\n\n void SetStandardDir( const String& _rDir );\n inline const String& GetStandardDir() const { return _aStdDir; }\n inline void DisableFilterBoxAutoWidth() { _pLbFilter->EnableDDAutoWidth( FALSE ); }\n\n \/\/ ------------------------------------------\n \/\/ access to the filter listbox only as Control* - we want to maintain the entries\/userdata ourself\n Control* GetFilterListControl() { return _pLbFilter; }\n const Control* GetFilterListControl() const { return _pLbFilter; }\n void CreateFilterListControl( Window* _pParent, const ResId& _rId );\n inline void SetFilterListSelectHdl( const Link& _rHandler );\n\n \/\/ inits the listbox for the filters from the filter list (_pFilter)\n void ClearFilterList( );\n void InitFilterList( );\n inline sal_Bool HasFilterListEntry( const String& _rFilterName );\n inline void SelectFilterListEntry( const String& _rFilterName );\n inline void SetNoFilterListSelection( );\n void InsertFilterListEntry( const SvtFileDialogFilter_Impl* _pFilterDesc );\n \/\/ _pFilterDesc must already have been added to _pFilter\n inline SvtFileDialogFilter_Impl* GetSelectedFilterEntry( String& \/* [out] *\/ _rDisplayName ) const;\n inline sal_Bool IsFilterListTravelSelect() const;\n\n SvtFileDialogFilter_Impl* FindFilter( const String& _rFilterName );\n\n \/\/ ------------------------------------------\n \/\/ access to the current filter via methods only - need to care for consistency between _pCurFilter and m_sCurrentFilterDisplayName\n inline const SvtFileDialogFilter_Impl* GetCurFilter( ) const;\n inline const String& GetCurFilterDisplayName() const;\n void SetCurFilter( SvtFileDialogFilter_Impl* _pFilter, const String& _rDisplayName );\n inline void SetCurFilter( SvtFileDialogFilter_Impl* _pFilter );\n};\n\ninline void SvtExpFileDlg_Impl::SetFilterListSelectHdl( const Link& _rHandler )\n{\n _pLbFilter->SetSelectHdl( _rHandler );\n}\n\ninline sal_Bool SvtExpFileDlg_Impl::HasFilterListEntry( const String& _rFilterName )\n{\n return ( LISTBOX_ENTRY_NOTFOUND != _pLbFilter->GetEntryPos( _rFilterName ) );\n}\n\ninline void SvtExpFileDlg_Impl::SelectFilterListEntry( const String& _rFilterName )\n{\n _pLbFilter->SelectEntry( _rFilterName );\n}\n\ninline void SvtExpFileDlg_Impl::SetNoFilterListSelection( )\n{\n _pLbFilter->SetNoSelection( );\n}\n\ninline SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetSelectedFilterEntry( String& _rDisplayName ) const\n{\n _rDisplayName = _pLbFilter->GetSelectEntry();\n return static_cast< SvtFileDialogFilter_Impl* >( _pLbFilter->GetEntryData ( _pLbFilter->GetSelectEntryPos() ) );\n}\n\ninline sal_Bool SvtExpFileDlg_Impl::IsFilterListTravelSelect() const\n{\n return _pLbFilter->IsTravelSelect();\n}\n\ninline const SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetCurFilter( ) const\n{\n return _pCurFilter;\n}\n\ninline const String& SvtExpFileDlg_Impl::GetCurFilterDisplayName() const\n{\n return m_sCurrentFilterDisplayName;\n}\n\ninline void SvtExpFileDlg_Impl::SetCurFilter( SvtFileDialogFilter_Impl* pFilter )\n{\n SetCurFilter( pFilter, pFilter->GetName() );\n}\n\n#endif \/\/ #ifndef _IODLGIMP_HXX\n\n\n<commit_msg>INTEGRATION: CWS dba202a (1.3.12); FILE MERGED 2005\/10\/24 08:30:20 fs 1.3.12.1: #i35830# only strip extensions which really are extensions - thanks to rvojta@openoffice.org for the patch<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: iodlgimp.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2005-12-21 13:10:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _IODLGIMP_HXX\n#define _IODLGIMP_HXX\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_MENUBTN_HXX\n#include <vcl\/menubtn.hxx>\n#endif\n#ifndef _SV_TIMER_HXX\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _SV_GROUP_HXX\n#include <vcl\/group.hxx>\n#endif\n\n#include \"svtools\/svarray.hxx\"\n\n#include <vector>\n\n\/\/*****************************************************************************\n\nclass Accelerator;\nclass CheckBox;\nclass SvtFileDialog;\nclass SvStringsDtor;\nclass SvUShorts;\n\n\/\/*****************************************************************************\n\n#define FILEDIALOG_DEF_EXTSEP ';'\n#define FILEDIALOG_DEF_WILDCARD '*'\n#define FILEDIALOG_DEF_IMAGEBORDER 10\n#define FILEDIALOG_DEF_TIMEOUT 250\n\n\/\/*****************************************************************************\n\nString GetRegularExpression_Impl( const String& rFilter );\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogFilter_Impl\n\/\/*****************************************************************************\n\n\/* [Beschreibung]\n\n Instanzen dieser Klasse repr\"asentieren einen Filter\n*\/\n\nclass SvtFileDialogFilter_Impl\n{\nprivate:\n String m_aName; \/\/ name of the entry\n String m_aType; \/\/ filter wildcard - if empty, the entry marks a group\n\npublic:\n SvtFileDialogFilter_Impl( const String& rName, const String& rType );\n ~SvtFileDialogFilter_Impl();\n\n const String& GetName() const { return m_aName; }\n const String& GetType() const { return m_aType; }\n const String GetExtension() const { return m_aType.Copy( 2 ); }\n\n sal_Bool isGroupSeparator() const { return 0 == m_aType.Len(); }\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogFilterList_Impl\n\/\/*****************************************************************************\n\nSV_DECL_PTRARR_DEL( SvtFileDialogFilterList_Impl, SvtFileDialogFilter_Impl*, 3, 3 );\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgMode\n\/\/*****************************************************************************\n\nenum SvtFileDlgMode\n{\n FILEDLG_MODE_OPEN = 0,\n FILEDLG_MODE_SAVE = 1\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgType\n\/\/*****************************************************************************\n\nenum SvtFileDlgType\n{\n FILEDLG_TYPE_FILEDLG = 0,\n FILEDLG_TYPE_PATHDLG\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDialogURLSelector\n\/\/*****************************************************************************\nclass SvtFileDialogURLSelector : public MenuButton\n{\nprivate:\n SvtFileDialog* m_pParent;\n PopupMenu* m_pMenu;\n\nprotected:\n\/\/ inline const SvtFileDialog* GetParent() const { return _pParent; }\n inline SvtFileDialog* GetParent() { return m_pParent; }\n\nprotected:\n void OpenURL( const String& rURL );\n\n virtual void FillURLMenu( PopupMenu* _pMenu ) = 0;\n\nprotected:\n SvtFileDialogURLSelector( SvtFileDialog* _pParent, const ResId& _rResId, sal_uInt16 _nButtonId );\n ~SvtFileDialogURLSelector();\n\n virtual void Activate();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtUpButton_Impl\n\/\/*****************************************************************************\n\nclass SvtUpButton_Impl : public SvtFileDialogURLSelector\n{\nprivate:\n SvStringsDtor* _pURLs;\n\npublic:\n SvtUpButton_Impl( SvtFileDialog* pParent, const ResId& rResId );\n ~SvtUpButton_Impl();\n\nprotected:\n virtual void FillURLMenu( PopupMenu* _pMenu );\n virtual void Select();\n virtual void Click();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtTravelButton_Impl\n\/\/*****************************************************************************\n\nclass SvtTravelButton_Impl : public SvtFileDialogURLSelector\n{\nprivate:\n ::std::vector< String > m_aFavourites;\n\npublic:\n SvtTravelButton_Impl( SvtFileDialog* pParent, const ResId& rResId );\n ~SvtTravelButton_Impl();\n\n void SetFavouriteLocations( const ::std::vector< String >& _rLocations );\n\nprotected:\n virtual void FillURLMenu( PopupMenu* _pMenu );\n virtual void Select();\n virtual void Click();\n};\n\n\/\/*****************************************************************************\n\/\/ SvtFileDlgState\n\/\/*****************************************************************************\n\ntypedef sal_uInt8 SvtFileDlgState;\n\n#define FILEDLG_STATE_NONE ((SvtFileDlgState)0x00)\n#define FILEDLG_STATE_REMOTE ((SvtFileDlgState)0x01)\n\n\/\/*****************************************************************************\n\/\/ SvtExpFileDlg_Impl\n\/\/*****************************************************************************\nclass SvtURLBox;\nclass SvtExpFileDlg_Impl\n{\nprivate:\n DECL_STATIC_LINK( SvtExpFileDlg_Impl, UnClickHdl, Button* );\n\nprivate:\n ListBox* _pLbFilter;\n\n const SvtFileDialogFilter_Impl* _pCurFilter;\n String m_sCurrentFilterDisplayName; \/\/ may differ from _pCurFilter->GetName in case it is a cached entry\n\npublic:\n SvtFileDialogFilterList_Impl* _pFilter;\n SvtFileDialogFilter_Impl* _pUserFilter;\n\n FixedText* _pFtFileName;\n SvtURLBox* _pEdFileName;\n\n FixedText* _pFtFileVersion;\n ListBox* _pLbFileVersion;\n\n FixedText* _pFtTemplates;\n ListBox* _pLbTemplates;\n\n FixedText* _pFtImageTemplates;\n ListBox* _pLbImageTemplates;\n\n FixedText* _pFtFileType;\n PushButton* _pBtnFileOpen;\n PushButton* _pBtnCancel;\n HelpButton* _pBtnHelp;\n SvtUpButton_Impl* _pBtnUp;\n ImageButton* _pBtnNewFolder;\n SvtTravelButton_Impl* _pBtnStandard;\n CheckBox* _pCbPassword;\n FixedText* _pFtCurrentPath;\n CheckBox* _pCbAutoExtension;\n CheckBox* _pCbOptions;\n\n SvtFileDlgMode _eMode;\n SvtFileDlgType _eDlgType;\n SvtFileDlgState _nState;\n WinBits _nStyle;\n\n String _aStdDir;\n\n \/\/ beim traveln der Filterbox erst Zeitversetzt filtern\n Timer _aFilterTimer;\n\n \/\/ Zeigt der OpenHdl_Imp(), ob das Open durch einen Doppelclick ausgel\"ost wurde\n sal_Bool _bDoubleClick;\n sal_Bool m_bNeedDelayedFilterExecute;\n\n \/\/ Liste mit den 5 zuletzt genutzten Filtern\n \/\/ Defaultfilter fuer <Alle> oder <Alle ...>\n const SvtFileDialogFilter_Impl* _pDefaultFilter;\n\n \/\/ Multiselektion?\n sal_Bool _bMultiSelection;\n\n \/\/ Fixgr\"ossen f\"ur Resize merken\n long _nFixDeltaHeight;\n Size _a6Size;\n Size _aDlgSize;\n String _aIniKey;\n\n sal_Bool _bFolderHasOpened;\n\n SvtExpFileDlg_Impl( WinBits nBits );\n ~SvtExpFileDlg_Impl();\n\n void SetStandardDir( const String& _rDir );\n inline const String& GetStandardDir() const { return _aStdDir; }\n inline void DisableFilterBoxAutoWidth() { _pLbFilter->EnableDDAutoWidth( FALSE ); }\n\n \/\/ ------------------------------------------\n \/\/ access to the filter listbox only as Control* - we want to maintain the entries\/userdata ourself\n Control* GetFilterListControl() { return _pLbFilter; }\n const Control* GetFilterListControl() const { return _pLbFilter; }\n void CreateFilterListControl( Window* _pParent, const ResId& _rId );\n inline void SetFilterListSelectHdl( const Link& _rHandler );\n\n \/\/ inits the listbox for the filters from the filter list (_pFilter)\n void ClearFilterList( );\n void InitFilterList( );\n inline sal_Bool HasFilterListEntry( const String& _rFilterName );\n inline void SelectFilterListEntry( const String& _rFilterName );\n inline void SetNoFilterListSelection( );\n void InsertFilterListEntry( const SvtFileDialogFilter_Impl* _pFilterDesc );\n \/\/ _pFilterDesc must already have been added to _pFilter\n inline SvtFileDialogFilter_Impl* GetSelectedFilterEntry( String& \/* [out] *\/ _rDisplayName ) const;\n inline sal_Bool IsFilterListTravelSelect() const;\n\n SvtFileDialogFilter_Impl* FindFilter( const String& _rFilterName );\n\n \/\/ ------------------------------------------\n \/\/ access to the current filter via methods only - need to care for consistency between _pCurFilter and m_sCurrentFilterDisplayName\n inline const SvtFileDialogFilter_Impl* GetCurFilter( ) const;\n inline const String& GetCurFilterDisplayName() const;\n void SetCurFilter( SvtFileDialogFilter_Impl* _pFilter, const String& _rDisplayName );\n inline void SetCurFilter( SvtFileDialogFilter_Impl* _pFilter );\n};\n\ninline void SvtExpFileDlg_Impl::SetFilterListSelectHdl( const Link& _rHandler )\n{\n _pLbFilter->SetSelectHdl( _rHandler );\n}\n\ninline sal_Bool SvtExpFileDlg_Impl::HasFilterListEntry( const String& _rFilterName )\n{\n return ( LISTBOX_ENTRY_NOTFOUND != _pLbFilter->GetEntryPos( _rFilterName ) );\n}\n\ninline void SvtExpFileDlg_Impl::SelectFilterListEntry( const String& _rFilterName )\n{\n _pLbFilter->SelectEntry( _rFilterName );\n}\n\ninline void SvtExpFileDlg_Impl::SetNoFilterListSelection( )\n{\n _pLbFilter->SetNoSelection( );\n}\n\ninline SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetSelectedFilterEntry( String& _rDisplayName ) const\n{\n _rDisplayName = _pLbFilter->GetSelectEntry();\n return static_cast< SvtFileDialogFilter_Impl* >( _pLbFilter->GetEntryData ( _pLbFilter->GetSelectEntryPos() ) );\n}\n\ninline sal_Bool SvtExpFileDlg_Impl::IsFilterListTravelSelect() const\n{\n return _pLbFilter->IsTravelSelect();\n}\n\ninline const SvtFileDialogFilter_Impl* SvtExpFileDlg_Impl::GetCurFilter( ) const\n{\n return _pCurFilter;\n}\n\ninline const String& SvtExpFileDlg_Impl::GetCurFilterDisplayName() const\n{\n return m_sCurrentFilterDisplayName;\n}\n\ninline void SvtExpFileDlg_Impl::SetCurFilter( SvtFileDialogFilter_Impl* pFilter )\n{\n SetCurFilter( pFilter, pFilter->GetName() );\n}\n\n#endif \/\/ #ifndef _IODLGIMP_HXX\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2011, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n#include <iostream>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ these are declared before the session objects\n\t\/\/ so that they are destructed last. This enables\n\t\/\/ the sessions to destruct in parallel\n\tsession_proxy p1;\n\tsession_proxy p2;\n\tsession_proxy p3;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48010, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49010, 50000), \"0.0.0.0\", 0);\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50010, 51000), \"0.0.0.0\", 0);\n\n\tses1.set_alert_mask(alert::all_categories);\n\tses2.set_alert_mask(alert::all_categories);\n\tses3.set_alert_mask(alert::all_categories);\n\n\t\/\/ this is to avoid everything finish from a single peer\n\t\/\/ immediately. To make the swarm actually connect all\n\t\/\/ three peers before finishing.\n\tfloat rate_limit = 100000;\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tsettings.ignore_limits_on_local_network = false;\n\tsettings.choking_algorithm = session_settings::auto_expand_choker;\n\tsettings.upload_rate_limit = rate_limit;\n\tsettings.unchoke_slots_limit = 1;\n\tses1.set_settings(settings);\n\n\tsettings.upload_rate_limit = rate_limit \/ 10;\n\tsettings.download_rate_limit = rate_limit \/ 5;\n\tsettings.unchoke_slots_limit = 0;\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::forced;\n\tpes.in_enc_policy = pe_settings::forced;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n\tses3.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, \"_unchoke\");\t\n\n\tsession_status st = ses1.status();\n\tTEST_CHECK(st.allowed_upload_slots == 1);\n\tfor (int i = 0; i < 50; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\n\n\t\tst = ses1.status();\n\t\tstd::cerr << st.allowed_upload_slots << \" \";\n\t\tif (st.allowed_upload_slots >= 2) break;\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\t\ttorrent_status st3 = tor3.status();\n\n\t\tprint_ses_rate(i, &st1, &st2, &st3);\n\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(st.allowed_upload_slots >= 2);\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\t\/\/ this allows shutting down the sessions in parallel\n\tp1 = ses1.abort();\n\tp2 = ses2.abort();\n\tp3 = ses3.abort();\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was t r catch (std::exception&) {}erminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_unchoke\", ec);\n\tremove_all(\".\/tmp2_unchoke\", ec);\n\tremove_all(\".\/tmp3_unchoke\", ec);\n\n\ttest_swarm();\n\t\n\ttest_sleep(2000);\n\tTEST_CHECK(!exists(\".\/tmp1_unchoke\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp2_unchoke\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp3_unchoke\/temporary\"));\n\n\tremove_all(\".\/tmp1_unchoke\", ec);\n\tremove_all(\".\/tmp2_unchoke\", ec);\n\tremove_all(\".\/tmp3_unchoke\", ec);\n\n\treturn 0;\n}\n\n<commit_msg>minor test_auto_unchoke cleanup<commit_after>\/*\n\nCopyright (c) 2011, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n#include <iostream>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ these are declared before the session objects\n\t\/\/ so that they are destructed last. This enables\n\t\/\/ the sessions to destruct in parallel\n\tsession_proxy p1;\n\tsession_proxy p2;\n\tsession_proxy p3;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48010, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49010, 50000), \"0.0.0.0\", 0);\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50010, 51000), \"0.0.0.0\", 0);\n\n\tses1.set_alert_mask(alert::all_categories);\n\tses2.set_alert_mask(alert::all_categories);\n\tses3.set_alert_mask(alert::all_categories);\n\n\t\/\/ this is to avoid everything finish from a single peer\n\t\/\/ immediately. To make the swarm actually connect all\n\t\/\/ three peers before finishing.\n\tfloat rate_limit = 100000;\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tsettings.ignore_limits_on_local_network = false;\n\tsettings.choking_algorithm = session_settings::auto_expand_choker;\n\tsettings.upload_rate_limit = rate_limit;\n\tsettings.unchoke_slots_limit = 1;\n\tses1.set_settings(settings);\n\n\tsettings.upload_rate_limit = rate_limit \/ 10;\n\tsettings.download_rate_limit = rate_limit \/ 5;\n\tsettings.unchoke_slots_limit = 0;\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::forced;\n\tpes.in_enc_policy = pe_settings::forced;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n\tses3.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, \"_unchoke\");\t\n\n\tsession_status st = ses1.status();\n\tTEST_CHECK(st.allowed_upload_slots == 1);\n\tfor (int i = 0; i < 100; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\n\n\t\tst = ses1.status();\n\t\tfprintf(stderr, \"allowed unchoked: %d\\n\", st.allowed_upload_slots);\n\t\tif (st.allowed_upload_slots >= 2) break;\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\t\ttorrent_status st3 = tor3.status();\n\n\t\tprint_ses_rate(i, &st1, &st2, &st3);\n\n\t\ttest_sleep(100);\n\t}\n\n\tTEST_CHECK(st.allowed_upload_slots >= 2);\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\t\/\/ this allows shutting down the sessions in parallel\n\tp1 = ses1.abort();\n\tp2 = ses2.abort();\n\tp3 = ses3.abort();\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was t r catch (std::exception&) {}erminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_unchoke\", ec);\n\tremove_all(\".\/tmp2_unchoke\", ec);\n\tremove_all(\".\/tmp3_unchoke\", ec);\n\n\ttest_swarm();\n\t\n\ttest_sleep(2000);\n\tTEST_CHECK(!exists(\".\/tmp1_unchoke\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp2_unchoke\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp3_unchoke\/temporary\"));\n\n\tremove_all(\".\/tmp1_unchoke\", ec);\n\tremove_all(\".\/tmp2_unchoke\", ec);\n\tremove_all(\".\/tmp3_unchoke\", ec);\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2011 The PHP Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.php.net\/license\/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $Id: header 310447 2011-04-23 21:14:10Z bjori $ *\/\nextern \"C\"\n{\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"php.h\"\n#include \"php_ini.h\"\n#include \"ext\/standard\/info.h\"\n}\n\n#include <vector>\n#include <string>\n#include \"php_zeppelin.h\"\n#include \"libzp\/include\/zp_client.h\"\n#include \"slash\/include\/slash_status.h\"\n#include \"zend.h\"\n\n\/* If you declare any globals in php_zeppelin.h uncomment this:\nZEND_DECLARE_MODULE_GLOBALS(zeppelin)\n*\/\nstatic int le_zeppelin;\n\n\/* True global resources - no need for thread safety here *\/\nzend_class_entry *zeppelin_client_ext;\n\n\/* {{{ zeppelin_functions[]\n *\n * Every user visible function must have an entry in zeppelin_functions[].\n *\/\n\n\/\/zend_function_entry zeppelin_functions[] = {\n\/\/ PHP_FE(confirm_zeppelin_compiled, NULL) \/* For testing, remove later. *\/\n\/\/ PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)\n\/\/ {NULL, NULL, NULL}\n\/\/ \/\/PHP_FE_END \/* Must be the last line in zeppelin_functions[] *\/\n\/\/};\nzend_function_entry zeppelin_functions[] = {\n\t{NULL, NULL, NULL}\n};\n\nzend_function_entry phppan_functions[] = {\n PHP_FE(confirm_zeppelin_compiled, NULL) \/* For testing, remove later. *\/\n PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, mget, NULL, ZEND_ACC_PUBLIC)\n {NULL, NULL, NULL}\n};\n\/* }}} *\/\n\n\/* {{{ zeppelin_module_entry\n *\/\nzend_module_entry zeppelin_module_entry = {\n#if ZEND_MODULE_API_NO >= 20010901\n STANDARD_MODULE_HEADER,\n#endif\n \"zeppelin\",\n zeppelin_functions,\n PHP_MINIT(zeppelin),\n PHP_MSHUTDOWN(zeppelin),\n PHP_RINIT(zeppelin), \/* Replace with NULL if there's nothing to do at request start *\/\n PHP_RSHUTDOWN(zeppelin), \/* Replace with NULL if there's nothing to do at request end *\/\n PHP_MINFO(zeppelin),\n#if ZEND_MODULE_API_NO >= 20010901\n \"0.1\", \/* Replace with version number for your extension *\/\n#endif\n STANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\nextern \"C\"\n{\n#ifdef COMPILE_DL_ZEPPELIN\nZEND_GET_MODULE(zeppelin)\n#endif\n}\n\nstatic void zeppelin_destructor_zeppelin_client(zend_rsrc_list_entry * rsrc TSRMLS_DC)\n{\n\tlibzp::Client *zp = (libzp::Client *) rsrc->ptr;\n delete zp;\n}\n\nint zeppelin_client_get(zval *id, libzp::Client **zeppelin_sock TSRMLS_DC, int no_throw)\n{\n zval **socket;\n int resource_type;\n\n if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), \"Zeppelin\",\n sizeof(\"Zeppelin\"), (void **) &socket) == FAILURE) {\n return -1;\n }\n\n *zeppelin_sock = (libzp::Client *) zend_list_find(Z_LVAL_PP(socket), &resource_type);\n\n if (!*zeppelin_sock || resource_type != le_zeppelin) {\n return -1;\n }\n\n return Z_LVAL_PP(socket);\n}\n\nPHP_MINIT_FUNCTION(zeppelin)\n{\n \/* If you have INI entries, uncomment these lines\n REGISTER_INI_ENTRIES();\n *\/\n zend_class_entry zeppelin_class_entry;\n\/\/ INIT_CLASS_ENTRY(zeppelin_class_entry, \"Zeppelin\", zeppelin_functions);\n INIT_CLASS_ENTRY(zeppelin_class_entry, \"Zeppelin\", phppan_functions);\n zeppelin_client_ext = zend_register_internal_class(&zeppelin_class_entry TSRMLS_CC);\n\n le_zeppelin = zend_register_list_destructors_ex(\n zeppelin_destructor_zeppelin_client,\n NULL,\n \"zeppelin-client\", module_number\n );\n\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION\n *\/\nPHP_MSHUTDOWN_FUNCTION(zeppelin)\n{\n \/* uncomment this line if you have INI entries\n UNREGISTER_INI_ENTRIES();\n *\/\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* Remove if there's nothing to do at request start *\/\n\/* {{{ PHP_RINIT_FUNCTION\n *\/\nPHP_RINIT_FUNCTION(zeppelin)\n{\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* Remove if there's nothing to do at request end *\/\n\/* {{{ PHP_RSHUTDOWN_FUNCTION\n *\/\nPHP_RSHUTDOWN_FUNCTION(zeppelin)\n{\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP _MINFO_FUNCTION\n *\/\nPHP_MINFO_FUNCTION(zeppelin)\n{\n php_info_print_table_start();\n php_info_print_table_header(2, \"zeppelin support\", \"enabled\");\n php_info_print_table_end();\n\n \/* Remove comments if you have entries in php.ini\n DISPLAY_INI_ENTRIES();\n *\/\n}\n\/* }}} *\/\n\n\nPHP_METHOD(Zeppelin, __construct)\n{\n char *ip = NULL;\n int ip_len = 0;\n int port = 0;\n char *table = NULL;\n int table_len = 0;\n zval *self;\n zval *object;\n int id;\n int timeout = -1;\n libzp::Options options;\n libzp::Client *zp = NULL;\n char * addrs = NULL;\n int addrs_len = 0;\n\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oss|l\",\n\t&object, zeppelin_client_ext, &addrs, &addrs_len, &table, &table_len, &timeout) == SUCCESS) {\n\tstd::vector<std::string> addr_v;\n\tchar *addr = strtok(addrs, \";\");\n\twhile(addr != NULL) {\n\t addr_v.push_back(std::string(addr));\n\t addr = strtok(NULL,\";\");\n\t}\n\n\tstd::string ip;\n\tint port = 0;\n\t\/\/ Split address into ip and port\n\tfor (size_t i = 0; i < addr_v.size(); i++) {\n\t if(!slash::ParseIpPortString(addr_v[i], ip, port)) {\n\t\tRETURN_FALSE;\n\t }\n\t libzp::Node node(ip, port);\n\t options.meta_addr.push_back(node);\n\t}\n\t\/\/ Timeout\n\tif (timeout != -1) {\n\t options.op_timeout = timeout;\n\t}\n\t\/\/ Connect\n\tzp = new libzp::Client(options, std::string(table, table_len));\n } else {\n\tRETURN_FALSE;\n }\n\n#if PHP_VERSION_ID >= 50400\n\tid = zend_list_insert(zp, le_zeppelin TSRMLS_CC);\n#else\n\tid = zend_list_insert(zp, le_zeppelin);\n#endif\n\tadd_property_resource(object, \"Zeppelin\", id);\n}\n\n\nPHP_METHOD(Zeppelin, __destruct)\n{\n \/\/ todo\n}\n\nPHP_FUNCTION(confirm_zeppelin_compiled)\n{\n char *arg = NULL;\n int arg_len, len;\n char *strg;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &arg, &arg_len) == FAILURE) {\n return;\n }\n\n len = spprintf(&strg, 0, \"Congratulations! You have successfully modified ext\/%.78s\/config.m4. Module %.78s is now compiled into PHP.\", \"zeppelin\", arg);\n RETURN_STRINGL(strg, len, 0);\n}\n\nPHP_METHOD(Zeppelin, set)\n{\n char *key = NULL;\n char *value = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n int value_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oss\",\n &object, zeppelin_client_ext, &key, &key_len, &value, &value_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n\tlibzp::Status s = zp->Set(std::string(key, key_len), std::string(value, value_len));\n if (s.ok()) {\n RETVAL_TRUE;\n } else {\n RETVAL_FALSE;\n }\n}\n\nPHP_METHOD(Zeppelin, get)\n{\n struct timeval tv;\n char *key = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Os\",\n &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n std::string val;\n\tlibzp::Status s = zp->Get(std::string(key, key_len), &val);\n\tif (s.ok()) {\n RETVAL_STRINGL((char *)val.data(), val.size(), 1);\n\t} else {\n RETVAL_FALSE;\n\t}\n}\n\nPHP_METHOD(Zeppelin, mget)\n{\n zval *keys = NULL;\n int argc = ZEND_NUM_ARGS();\n zval *object;\n\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oa\",\n &object, zeppelin_client_ext, &keys) == FAILURE) {\n RETURN_FALSE;\n }\n\n libzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n std::vector<std::string> vkeys;\n if (Z_TYPE_P(keys) == IS_ARRAY) {\n zval **arrval;\n HashPosition pos;\n zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos);\n while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&arrval, &pos) == SUCCESS) {\n if (Z_TYPE_PP(arrval) == IS_STRING) {\n vkeys.push_back(std::string(Z_STRVAL_PP(arrval), Z_STRLEN_PP(arrval)));\n }\n zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos);\n }\n }\n\n std::map<std::string, std::string> result;\n libzp::Status s = zp->Mget(vkeys, &result);\n if (s.ok()) {\n if (return_value_used) {\n array_init(return_value);\n std::map<std::string, std::string>::iterator r_it = result.begin();\n for (; r_it != result.end(); ++r_it) {\n add_assoc_string(return_value, (char *) r_it->first.data(),\n (char *) r_it->second.data(), 1);\n }\n }\n } else {\n RETVAL_FALSE;\n }\n}\n\nPHP_METHOD(Zeppelin, delete)\n{\n char *key = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Os\",\n &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n\tlibzp::Status s = zp->Delete(std::string(key, key_len));\n if (s.ok()) {\n RETVAL_TRUE;\n } else {\n RETVAL_FALSE;\n }\n}\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\n\/*\n * Local variables:\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<commit_msg>bugfix phpzeppelin mget<commit_after>\/*\n +----------------------------------------------------------------------+\n | PHP Version 5 |\n +----------------------------------------------------------------------+\n | Copyright (c) 1997-2011 The PHP Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 3.01 of the PHP license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.php.net\/license\/3_01.txt |\n | If you did not receive a copy of the PHP license and are unable to |\n | obtain it through the world-wide-web, please send a note to |\n | license@php.net so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: |\n +----------------------------------------------------------------------+\n*\/\n\n\/* $Id: header 310447 2011-04-23 21:14:10Z bjori $ *\/\nextern \"C\"\n{\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"php.h\"\n#include \"php_ini.h\"\n#include \"ext\/standard\/info.h\"\n}\n\n#include <vector>\n#include <string>\n#include \"php_zeppelin.h\"\n#include \"libzp\/include\/zp_client.h\"\n#include \"slash\/include\/slash_status.h\"\n#include \"zend.h\"\n\n\/* If you declare any globals in php_zeppelin.h uncomment this:\nZEND_DECLARE_MODULE_GLOBALS(zeppelin)\n*\/\nstatic int le_zeppelin;\n\n\/* True global resources - no need for thread safety here *\/\nzend_class_entry *zeppelin_client_ext;\n\n\/* {{{ zeppelin_functions[]\n *\n * Every user visible function must have an entry in zeppelin_functions[].\n *\/\n\n\/\/zend_function_entry zeppelin_functions[] = {\n\/\/ PHP_FE(confirm_zeppelin_compiled, NULL) \/* For testing, remove later. *\/\n\/\/ PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)\n\/\/ PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)\n\/\/ {NULL, NULL, NULL}\n\/\/ \/\/PHP_FE_END \/* Must be the last line in zeppelin_functions[] *\/\n\/\/};\nzend_function_entry zeppelin_functions[] = {\n\t{NULL, NULL, NULL}\n};\n\nzend_function_entry phppan_functions[] = {\n PHP_FE(confirm_zeppelin_compiled, NULL) \/* For testing, remove later. *\/\n PHP_ME(Zeppelin, __construct, NULL, ZEND_ACC_CTOR | ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, __destruct, NULL, ZEND_ACC_DTOR | ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, set, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, get, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, delete, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(Zeppelin, mget, NULL, ZEND_ACC_PUBLIC)\n {NULL, NULL, NULL}\n};\n\/* }}} *\/\n\n\/* {{{ zeppelin_module_entry\n *\/\nzend_module_entry zeppelin_module_entry = {\n#if ZEND_MODULE_API_NO >= 20010901\n STANDARD_MODULE_HEADER,\n#endif\n \"zeppelin\",\n zeppelin_functions,\n PHP_MINIT(zeppelin),\n PHP_MSHUTDOWN(zeppelin),\n PHP_RINIT(zeppelin), \/* Replace with NULL if there's nothing to do at request start *\/\n PHP_RSHUTDOWN(zeppelin), \/* Replace with NULL if there's nothing to do at request end *\/\n PHP_MINFO(zeppelin),\n#if ZEND_MODULE_API_NO >= 20010901\n \"0.1\", \/* Replace with version number for your extension *\/\n#endif\n STANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\nextern \"C\"\n{\n#ifdef COMPILE_DL_ZEPPELIN\nZEND_GET_MODULE(zeppelin)\n#endif\n}\n\nstatic void zeppelin_destructor_zeppelin_client(zend_rsrc_list_entry * rsrc TSRMLS_DC)\n{\n\tlibzp::Client *zp = (libzp::Client *) rsrc->ptr;\n delete zp;\n}\n\nint zeppelin_client_get(zval *id, libzp::Client **zeppelin_sock TSRMLS_DC, int no_throw)\n{\n zval **socket;\n int resource_type;\n\n if (Z_TYPE_P(id) != IS_OBJECT || zend_hash_find(Z_OBJPROP_P(id), \"Zeppelin\",\n sizeof(\"Zeppelin\"), (void **) &socket) == FAILURE) {\n return -1;\n }\n\n *zeppelin_sock = (libzp::Client *) zend_list_find(Z_LVAL_PP(socket), &resource_type);\n\n if (!*zeppelin_sock || resource_type != le_zeppelin) {\n return -1;\n }\n\n return Z_LVAL_PP(socket);\n}\n\nPHP_MINIT_FUNCTION(zeppelin)\n{\n \/* If you have INI entries, uncomment these lines\n REGISTER_INI_ENTRIES();\n *\/\n zend_class_entry zeppelin_class_entry;\n\/\/ INIT_CLASS_ENTRY(zeppelin_class_entry, \"Zeppelin\", zeppelin_functions);\n INIT_CLASS_ENTRY(zeppelin_class_entry, \"Zeppelin\", phppan_functions);\n zeppelin_client_ext = zend_register_internal_class(&zeppelin_class_entry TSRMLS_CC);\n\n le_zeppelin = zend_register_list_destructors_ex(\n zeppelin_destructor_zeppelin_client,\n NULL,\n \"zeppelin-client\", module_number\n );\n\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION\n *\/\nPHP_MSHUTDOWN_FUNCTION(zeppelin)\n{\n \/* uncomment this line if you have INI entries\n UNREGISTER_INI_ENTRIES();\n *\/\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* Remove if there's nothing to do at request start *\/\n\/* {{{ PHP_RINIT_FUNCTION\n *\/\nPHP_RINIT_FUNCTION(zeppelin)\n{\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* Remove if there's nothing to do at request end *\/\n\/* {{{ PHP_RSHUTDOWN_FUNCTION\n *\/\nPHP_RSHUTDOWN_FUNCTION(zeppelin)\n{\n return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP _MINFO_FUNCTION\n *\/\nPHP_MINFO_FUNCTION(zeppelin)\n{\n php_info_print_table_start();\n php_info_print_table_header(2, \"zeppelin support\", \"enabled\");\n php_info_print_table_end();\n\n \/* Remove comments if you have entries in php.ini\n DISPLAY_INI_ENTRIES();\n *\/\n}\n\/* }}} *\/\n\n\nPHP_METHOD(Zeppelin, __construct)\n{\n char *ip = NULL;\n int ip_len = 0;\n int port = 0;\n char *table = NULL;\n int table_len = 0;\n zval *self;\n zval *object;\n int id;\n int timeout = -1;\n libzp::Options options;\n libzp::Client *zp = NULL;\n char * addrs = NULL;\n int addrs_len = 0;\n\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oss|l\",\n\t&object, zeppelin_client_ext, &addrs, &addrs_len, &table, &table_len, &timeout) == SUCCESS) {\n\tstd::vector<std::string> addr_v;\n\tchar *addr = strtok(addrs, \";\");\n\twhile(addr != NULL) {\n\t addr_v.push_back(std::string(addr));\n\t addr = strtok(NULL,\";\");\n\t}\n\n\tstd::string ip;\n\tint port = 0;\n\t\/\/ Split address into ip and port\n\tfor (size_t i = 0; i < addr_v.size(); i++) {\n\t if(!slash::ParseIpPortString(addr_v[i], ip, port)) {\n\t\tRETURN_FALSE;\n\t }\n\t libzp::Node node(ip, port);\n\t options.meta_addr.push_back(node);\n\t}\n\t\/\/ Timeout\n\tif (timeout != -1) {\n\t options.op_timeout = timeout;\n\t}\n\t\/\/ Connect\n\tzp = new libzp::Client(options, std::string(table, table_len));\n } else {\n\tRETURN_FALSE;\n }\n\n#if PHP_VERSION_ID >= 50400\n\tid = zend_list_insert(zp, le_zeppelin TSRMLS_CC);\n#else\n\tid = zend_list_insert(zp, le_zeppelin);\n#endif\n\tadd_property_resource(object, \"Zeppelin\", id);\n}\n\n\nPHP_METHOD(Zeppelin, __destruct)\n{\n \/\/ todo\n}\n\nPHP_FUNCTION(confirm_zeppelin_compiled)\n{\n char *arg = NULL;\n int arg_len, len;\n char *strg;\n\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &arg, &arg_len) == FAILURE) {\n return;\n }\n\n len = spprintf(&strg, 0, \"Congratulations! You have successfully modified ext\/%.78s\/config.m4. Module %.78s is now compiled into PHP.\", \"zeppelin\", arg);\n RETURN_STRINGL(strg, len, 0);\n}\n\nPHP_METHOD(Zeppelin, set)\n{\n char *key = NULL;\n char *value = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n int value_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oss\",\n &object, zeppelin_client_ext, &key, &key_len, &value, &value_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n\tlibzp::Status s = zp->Set(std::string(key, key_len), std::string(value, value_len));\n if (s.ok()) {\n RETVAL_TRUE;\n } else {\n RETVAL_FALSE;\n }\n}\n\nPHP_METHOD(Zeppelin, get)\n{\n struct timeval tv;\n char *key = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Os\",\n &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n std::string val;\n\tlibzp::Status s = zp->Get(std::string(key, key_len), &val);\n\tif (s.ok()) {\n RETVAL_STRINGL((char *)val.data(), val.size(), 1);\n\t} else {\n RETVAL_FALSE;\n\t}\n}\n\nPHP_METHOD(Zeppelin, mget)\n{\n zval *keys = NULL;\n int argc = ZEND_NUM_ARGS();\n zval *object;\n\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oa\",\n &object, zeppelin_client_ext, &keys) == FAILURE) {\n RETURN_FALSE;\n }\n\n libzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n std::vector<std::string> vkeys;\n if (Z_TYPE_P(keys) == IS_ARRAY) {\n zval **arrval;\n HashPosition pos;\n zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos);\n while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&arrval, &pos) == SUCCESS) {\n if (Z_TYPE_PP(arrval) == IS_STRING) {\n vkeys.push_back(std::string(Z_STRVAL_PP(arrval), Z_STRLEN_PP(arrval)));\n }\n zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos);\n }\n }\n\n std::map<std::string, std::string> result;\n libzp::Status s = zp->Mget(vkeys, &result);\n if (s.ok()) {\n if (return_value_used) {\n array_init(return_value);\n std::map<std::string, std::string>::iterator r_it = result.begin();\n for (; r_it != result.end(); ++r_it) {\n\t\t\t\tadd_assoc_stringl_ex(return_value, (char *) r_it->first.data(), r_it->first.size() + 1,\n\t\t\t\t\t(char *) r_it->second.data(), r_it->second.size(), 1);\n }\n }\n } else {\n RETVAL_FALSE;\n }\n}\n\nPHP_METHOD(Zeppelin, delete)\n{\n char *key = NULL;\n int argc = ZEND_NUM_ARGS();\n int key_len = 0;\n zval *object;\n if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Os\",\n &object, zeppelin_client_ext, &key, &key_len) == FAILURE) {\n return;\n }\n\n\tlibzp::Client *zp;\n if(zeppelin_client_get(object, &zp TSRMLS_CC, 0) < 0) {\n RETURN_FALSE;\n }\n\n\tlibzp::Status s = zp->Delete(std::string(key, key_len));\n if (s.ok()) {\n RETVAL_TRUE;\n } else {\n RETVAL_FALSE;\n }\n}\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\n\/*\n * Local variables:\n\n\/* The previous line is meant for vim and emacs, so it can correctly fold and\n unfold functions in source code. See the corresponding marks just before\n function definition, where the functions purpose is also documented. Please\n follow this convention for the convenience of others editing your code.\n*\/\n\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include <unordered_map>\n#include <mutex>\n#include <thread>\n\n#include <brynet\/net\/Platform.h>\n#include <brynet\/net\/Noexcept.h>\n\n#include <brynet\/net\/SSLHelper.h>\n \nnamespace brynet { namespace net {\n\n SSLHelper::Ptr SSLHelper::Create()\n {\n class make_shared_enabler : public SSLHelper {};\n return std::make_shared<make_shared_enabler>();\n }\n\n SSLHelper::SSLHelper() BRYNET_NOEXCEPT\n {\n#ifdef USE_OPENSSL\n mOpenSSLCTX = nullptr;\n#endif\n }\n\n SSLHelper::~SSLHelper() BRYNET_NOEXCEPT\n {\n#ifdef USE_OPENSSL\n destroySSL();\n#endif\n }\n\n#ifdef USE_OPENSSL\n SSL_CTX* SSLHelper::getOpenSSLCTX()\n {\n return mOpenSSLCTX;\n }\n\n static void cryptoSetThreadIDCallback(CRYPTO_THREADID* id)\n {\n#ifdef PLATFORM_WINDOWS\n CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(GetCurrentThreadId()));\n#else\n CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(pthread_self()));\n#endif\n }\n\n static std::unordered_map<int, std::shared_ptr<std::mutex>> cryptoLocks;\n static void cryptoLockingCallback(int mode,\n int type,\n const char *file, int line)\n {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK)\n {\n cryptoLocks[type]->lock();\n }\n else if (mode & CRYPTO_UNLOCK)\n {\n cryptoLocks[type]->unlock();\n }\n }\n\n static std::once_flag initCryptoThreadSafeSupportOnceFlag;\n static void InitCryptoThreadSafeSupport()\n {\n for (int i = 0; i < CRYPTO_num_locks(); i++)\n {\n cryptoLocks[i] = std::make_shared<std::mutex>();\n }\n\n CRYPTO_THREADID_set_callback(cryptoSetThreadIDCallback);\n CRYPTO_set_locking_callback(cryptoLockingCallback);\n }\n\n bool SSLHelper::initSSL(const std::string& certificate, const std::string& privatekey)\n {\n std::call_once(initCryptoThreadSafeSupportOnceFlag, InitCryptoThreadSafeSupport);\n\n if (mOpenSSLCTX != nullptr)\n {\n return false;\n }\n if (certificate.empty() || privatekey.empty())\n {\n return false;\n }\n\n mOpenSSLCTX = SSL_CTX_new(SSLv23_method());\n SSL_CTX_set_client_CA_list(mOpenSSLCTX, SSL_load_client_CA_file(certificate.c_str()));\n SSL_CTX_set_verify_depth(mOpenSSLCTX, 10);\n\n if (SSL_CTX_use_certificate_chain_file(mOpenSSLCTX, certificate.c_str()) <= 0)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n if (SSL_CTX_use_PrivateKey_file(mOpenSSLCTX, privatekey.c_str(), SSL_FILETYPE_PEM) <= 0)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n if (!SSL_CTX_check_private_key(mOpenSSLCTX))\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n return true;\n }\n\n void SSLHelper::destroySSL()\n {\n if (mOpenSSLCTX != nullptr)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n }\n }\n#endif\n\n} }<commit_msg>fix warning of unused ssl crypto function<commit_after>#include <unordered_map>\n#include <mutex>\n#include <thread>\n\n#include <brynet\/net\/Platform.h>\n#include <brynet\/net\/Noexcept.h>\n\n#include <brynet\/net\/SSLHelper.h>\n \nnamespace brynet { namespace net {\n\n SSLHelper::Ptr SSLHelper::Create()\n {\n class make_shared_enabler : public SSLHelper {};\n return std::make_shared<make_shared_enabler>();\n }\n\n SSLHelper::SSLHelper() BRYNET_NOEXCEPT\n {\n #ifdef USE_OPENSSL\n mOpenSSLCTX = nullptr;\n #endif\n }\n\n SSLHelper::~SSLHelper() BRYNET_NOEXCEPT\n {\n #ifdef USE_OPENSSL\n destroySSL();\n #endif\n }\n\n #ifdef USE_OPENSSL\n SSL_CTX* SSLHelper::getOpenSSLCTX()\n {\n return mOpenSSLCTX;\n }\n\n #ifndef CRYPTO_THREADID_set_callback\n static void cryptoSetThreadIDCallback(CRYPTO_THREADID* id)\n {\n #ifdef PLATFORM_WINDOWS\n CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(GetCurrentThreadId()));\n #else\n CRYPTO_THREADID_set_numeric(id, static_cast<unsigned long>(pthread_self()));\n #endif\n }\n #endif\n\n #ifndef CRYPTO_set_locking_callback\n static std::unordered_map<int, std::shared_ptr<std::mutex>> cryptoLocks;\n static void cryptoLockingCallback(int mode,\n int type,\n const char *file, int line)\n {\n (void)file;\n (void)line;\n if (mode & CRYPTO_LOCK)\n {\n cryptoLocks[type]->lock();\n }\n else if (mode & CRYPTO_UNLOCK)\n {\n cryptoLocks[type]->unlock();\n }\n }\n #endif\n\n static std::once_flag initCryptoThreadSafeSupportOnceFlag;\n static void InitCryptoThreadSafeSupport()\n {\n #ifndef CRYPTO_THREADID_set_callback\n CRYPTO_THREADID_set_callback(cryptoSetThreadIDCallback);\n #endif\n\n #ifndef CRYPTO_set_locking_callback\n for (int i = 0; i < CRYPTO_num_locks(); i++)\n {\n cryptoLocks[i] = std::make_shared<std::mutex>();\n }\n CRYPTO_set_locking_callback(cryptoLockingCallback);\n #endif\n }\n\n bool SSLHelper::initSSL(const std::string& certificate, const std::string& privatekey)\n {\n std::call_once(initCryptoThreadSafeSupportOnceFlag, InitCryptoThreadSafeSupport);\n\n if (mOpenSSLCTX != nullptr)\n {\n return false;\n }\n if (certificate.empty() || privatekey.empty())\n {\n return false;\n }\n\n mOpenSSLCTX = SSL_CTX_new(SSLv23_method());\n SSL_CTX_set_client_CA_list(mOpenSSLCTX, SSL_load_client_CA_file(certificate.c_str()));\n SSL_CTX_set_verify_depth(mOpenSSLCTX, 10);\n\n if (SSL_CTX_use_certificate_chain_file(mOpenSSLCTX, certificate.c_str()) <= 0)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n if (SSL_CTX_use_PrivateKey_file(mOpenSSLCTX, privatekey.c_str(), SSL_FILETYPE_PEM) <= 0)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n if (!SSL_CTX_check_private_key(mOpenSSLCTX))\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n return false;\n }\n\n return true;\n }\n\n void SSLHelper::destroySSL()\n {\n if (mOpenSSLCTX != nullptr)\n {\n SSL_CTX_free(mOpenSSLCTX);\n mOpenSSLCTX = nullptr;\n }\n }\n #endif\n\n} }<|endoftext|>"} {"text":"<commit_before>#ifndef BUFFER_CACHE_ALT_ALT_HPP_\n#define BUFFER_CACHE_ALT_ALT_HPP_\n\n#include <vector>\n#include <utility>\n\n#include \"buffer_cache\/alt\/page.hpp\"\n#include \"buffer_cache\/general_types.hpp\"\n#include \"concurrency\/auto_drainer.hpp\"\n#include \"concurrency\/semaphore.hpp\"\n#include \"containers\/two_level_array.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"utils.hpp\"\n\nclass serializer_t;\n\nnamespace alt {\n\nclass alt_buf_lock_t;\nclass alt_cache_config_t;\nclass alt_cache_stats_t;\nclass alt_snapshot_node_t;\n\nclass alt_memory_tracker_t : public memory_tracker_t {\npublic:\n alt_memory_tracker_t();\n ~alt_memory_tracker_t();\n void inform_memory_change(uint64_t in_memory_size,\n uint64_t memory_limit);\n void begin_txn_or_throttle(int64_t expected_change_count);\n void end_txn(int64_t saved_expected_change_count);\nprivate:\n adjustable_semaphore_t semaphore_;\n DISABLE_COPYING(alt_memory_tracker_t);\n};\n\nclass alt_cache_t : public home_thread_mixin_t {\npublic:\n explicit alt_cache_t(serializer_t *serializer,\n const alt_cache_config_t &dynamic_config,\n perfmon_collection_t *perfmon_collection);\n ~alt_cache_t();\n\n block_size_t max_block_size() const;\n \/\/ RSI: Remove this.\n block_size_t get_block_size() const { return max_block_size(); }\n\n \/\/ These todos come from the mirrored cache. The real problem is that whole\n \/\/ cache account \/ priority thing is just one ghetto hack amidst a dozen other\n \/\/ throttling systems. TODO: Come up with a consistent priority scheme,\n \/\/ i.e. define a \"default\" priority etc. TODO: As soon as we can support it, we\n \/\/ might consider supporting a mem_cap paremeter.\n void create_cache_account(int priority, scoped_ptr_t<alt_cache_account_t> *out);\n\nprivate:\n friend class alt_txn_t; \/\/ for drainer_->lock()\n friend class alt_inner_txn_t; \/\/ for &page_cache_\n friend class alt_buf_read_t; \/\/ for &page_cache_\n friend class alt_buf_write_t; \/\/ for &page_cache_\n\n friend class alt_buf_lock_t; \/\/ for latest_snapshot_node and\n \/\/ push_latest_snapshot_node\n\n alt_snapshot_node_t *matching_snapshot_node_or_null(block_id_t block_id,\n block_version_t block_version);\n void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);\n void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);\n\n scoped_ptr_t<alt_cache_stats_t> stats_;\n\n \/\/ tracker_ is used for throttling (which can cause the alt_txn_t constructor to\n \/\/ block). RSI: The throttling interface is bad (maybe) because it's worried\n \/\/ about transaction_t's passing one another(?) or maybe the callers are bad with\n \/\/ their use of chained mutexes. Make sure that timestamps don't get mixed up in\n \/\/ their ordering, once they begin to play a role.\n alt_memory_tracker_t tracker_;\n page_cache_t page_cache_;\n\n two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;\n\n scoped_ptr_t<auto_drainer_t> drainer_;\n\n DISABLE_COPYING(alt_cache_t);\n};\n\nclass alt_inner_txn_t {\npublic:\n \/\/ This is public because scoped_ptr_t needs to call it.\n ~alt_inner_txn_t();\n\nprivate:\n friend class alt_txn_t;\n alt_inner_txn_t(alt_cache_t *cache,\n \/\/ Unused for read transactions, pass repli_timestamp_t::invalid.\n repli_timestamp_t txn_recency,\n alt_inner_txn_t *preceding_txn_or_null);\n\n alt_cache_t *cache() { return cache_; }\n\n page_txn_t *page_txn() { return &page_txn_; }\n\n alt_cache_t *cache_;\n page_txn_t page_txn_;\n\n DISABLE_COPYING(alt_inner_txn_t);\n};\n\nclass alt_txn_t {\npublic:\n \/\/ Constructor for read-only transactions.\n \/\/ RSI: Generally speaking I don't think we use preceding_txn -- and should read\n \/\/ transactions use preceding_txn at all?\n explicit alt_txn_t(alt_cache_t *cache,\n alt_read_access_t read_access,\n alt_txn_t *preceding_txn = NULL);\n\n\n \/\/ RSI: Remove default parameter for expected_change_count.\n \/\/ RSI: Generally speaking I don't think we use preceding_txn and we should.\n alt_txn_t(alt_cache_t *cache,\n write_durability_t durability,\n repli_timestamp_t txn_timestamp,\n int64_t expected_change_count = 2,\n alt_txn_t *preceding_txn = NULL);\n\n ~alt_txn_t();\n\n alt_cache_t *cache() { return inner_->cache(); }\n page_txn_t *page_txn() { return inner_->page_txn(); }\n alt_access_t access() const { return access_; }\n\n void set_account(alt_cache_account_t *cache_account);\n\nprivate:\n static void destroy_inner_txn(alt_inner_txn_t *inner,\n alt_cache_t *cache,\n int64_t saved_expected_change_count,\n auto_drainer_t::lock_t);\n\n const alt_access_t access_;\n\n \/\/ Only applicable if access_ == write.\n const write_durability_t durability_;\n const int64_t saved_expected_change_count_; \/\/ RSI: A fugly relationship with\n \/\/ the tracker.\n\n scoped_ptr_t<alt_inner_txn_t> inner_;\n DISABLE_COPYING(alt_txn_t);\n};\n\n\/\/ The intrusive list of alt_snapshot_node_t contains all the snapshot nodes for a\n\/\/ given block id, in order by version. (See\n\/\/ alt_cache_t::snapshot_nodes_by_block_id_.)\nclass alt_snapshot_node_t : public intrusive_list_node_t<alt_snapshot_node_t> {\npublic:\n alt_snapshot_node_t(scoped_ptr_t<current_page_acq_t> &&acq);\n ~alt_snapshot_node_t();\n\nprivate:\n \/\/ RSI: Should this really use friends? Does this type need to be visible in the\n \/\/ header?\n friend class alt_buf_lock_t;\n friend class alt_cache_t;\n\n \/\/ This is never null (and is always a current_page_acq_t that has had\n \/\/ declare_snapshotted() called).\n scoped_ptr_t<current_page_acq_t> current_page_acq_;\n\n \/\/ RSP: std::map memory usage.\n \/\/ A NULL pointer associated with a block id indicates that the block is deleted.\n std::map<block_id_t, alt_snapshot_node_t *> children_;\n\n \/\/ The number of alt_buf_lock_t's referring to this node, plus the number of\n \/\/ alt_snapshot_node_t's referring to this node (via its children_ vector).\n int64_t ref_count_;\n\n\n DISABLE_COPYING(alt_snapshot_node_t);\n};\n\nclass alt_buf_parent_t;\n\nclass alt_buf_lock_t {\npublic:\n alt_buf_lock_t();\n\n \/\/ RSI: These constructors definitely duplicate one another. Too bad one\n \/\/ constructor can't call another (in GCC 4.4). Maybe we could still dedup\n \/\/ these, though, or get rid of some. (Make alt_access_t include create, and\n \/\/ separate it from page_access_t?)\n\n \/\/ Nonblocking constructor.\n alt_buf_lock_t(alt_buf_parent_t parent,\n block_id_t block_id,\n alt_access_t access);\n\n \/\/ Nonblocking constructor, creates a new block with a specified block id.\n alt_buf_lock_t(alt_txn_t *txn,\n block_id_t block_id,\n alt_create_t create);\n\n \/\/ Nonblocking constructor, IF parent->{access}_acq_signal() has already been\n \/\/ pulsed. In either case, returns before the block is acquired, but after we're\n \/\/ _in line_ for the block.\n alt_buf_lock_t(alt_buf_lock_t *parent,\n block_id_t block_id,\n alt_access_t access);\n\n \/\/ Nonblocking constructor that acquires a block with a new block id. `access`\n \/\/ must be `write`.\n alt_buf_lock_t(alt_buf_parent_t parent,\n alt_create_t create);\n\n \/\/ Nonblocking constructor, IF parent->{access}_acq_signal() has already been\n \/\/ pulsed. Allocates a block with a new block id. `access` must be `write`.\n alt_buf_lock_t(alt_buf_lock_t *parent,\n alt_create_t create);\n\n ~alt_buf_lock_t();\n\n alt_buf_lock_t(alt_buf_lock_t &&movee);\n alt_buf_lock_t &operator=(alt_buf_lock_t &&movee);\n\n void swap(alt_buf_lock_t &other);\n void reset_buf_lock();\n bool empty() const {\n return txn_ == NULL;\n }\n\n void snapshot_subtree();\n\n void detach_child(block_id_t child_id);\n\n block_id_t block_id() const {\n guarantee(txn_ != NULL);\n return current_page_acq()->block_id();\n }\n \/\/ RSI: Remove get_block_id().\n block_id_t get_block_id() const { return block_id(); }\n\n \/\/ RSI: Rename.\n repli_timestamp_t get_recency() const;\n\n alt_access_t access() const {\n guarantee(!empty());\n return current_page_acq()->access();\n }\n\n signal_t *read_acq_signal() {\n guarantee(!empty());\n return current_page_acq()->read_acq_signal();\n }\n signal_t *write_acq_signal() {\n guarantee(!empty());\n return current_page_acq()->write_acq_signal();\n }\n\n void mark_deleted();\n\n alt_txn_t *txn() const { return txn_; }\n alt_cache_t *cache() const { return txn_->cache(); }\n\nprivate:\n static void wait_for_parent(alt_buf_parent_t parent, alt_access_t access);\n static alt_snapshot_node_t *\n get_or_create_child_snapshot_node(alt_cache_t *cache,\n alt_snapshot_node_t *parent,\n block_id_t child_id);\n static void create_empty_child_snapshot_nodes(alt_cache_t *cache,\n block_version_t parent_version,\n block_id_t parent_id,\n block_id_t child_id);\n static void create_child_snapshot_nodes(alt_cache_t *cache,\n block_version_t parent_version,\n block_id_t parent_id,\n block_id_t child_id);\n current_page_acq_t *current_page_acq() const;\n\n friend class alt_buf_read_t; \/\/ for get_held_page_for_read, access_ref_count_.\n friend class alt_buf_write_t; \/\/ for get_held_page_for_write, access_ref_count_.\n\n page_t *get_held_page_for_read();\n page_t *get_held_page_for_write();\n\n alt_txn_t *txn_;\n\n scoped_ptr_t<current_page_acq_t> current_page_acq_;\n\n alt_snapshot_node_t *snapshot_node_;\n\n \/\/ Keeps track of how many alt_buf_{read|write}_t have been created for\n \/\/ this lock, for assertion\/guarantee purposes.\n intptr_t access_ref_count_;\n\n \/\/ RSI: We should get rid of this variable.\n bool was_destroyed_;\n\n DISABLE_COPYING(alt_buf_lock_t);\n};\n\n\nclass alt_buf_parent_t {\npublic:\n alt_buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }\n\n explicit alt_buf_parent_t(alt_buf_lock_t *lock)\n : txn_(lock->txn()), lock_or_null_(lock) {\n guarantee(lock != NULL);\n guarantee(!lock->empty());\n }\n \/\/ RSI: Replace this constructor with a create_dangerously static method.\n explicit alt_buf_parent_t(alt_txn_t *txn)\n : txn_(txn), lock_or_null_(NULL) { }\n\n alt_txn_t *txn() const {\n guarantee(txn_ != NULL);\n return txn_;\n }\n alt_cache_t *cache() const {\n guarantee(txn_ != NULL);\n return txn_->cache();\n }\n\nprivate:\n friend class alt_buf_lock_t;\n alt_txn_t *txn_;\n alt_buf_lock_t *lock_or_null_;\n};\n\nclass alt_buf_read_t {\npublic:\n explicit alt_buf_read_t(alt_buf_lock_t *lock);\n ~alt_buf_read_t();\n\n const void *get_data_read(uint32_t *block_size_out);\n \/\/ RSI: Remove.\n const void *get_data_read() {\n uint32_t unused_block_size;\n return get_data_read(&unused_block_size);\n }\n\nprivate:\n alt_buf_lock_t *lock_;\n page_acq_t page_acq_;\n\n DISABLE_COPYING(alt_buf_read_t);\n};\n\nclass alt_buf_write_t {\npublic:\n explicit alt_buf_write_t(alt_buf_lock_t *lock);\n ~alt_buf_write_t();\n\n void *get_data_write(uint32_t block_size);\n \/\/ Equivalent to passing the max_block_size.\n void *get_data_write();\n\nprivate:\n alt_buf_lock_t *lock_;\n page_acq_t page_acq_;\n\n DISABLE_COPYING(alt_buf_write_t);\n};\n\n\n} \/\/ namespace alt\n\n#endif \/\/ BUFFER_CACHE_ALT_ALT_HPP_\n<commit_msg>Fixed some trivial style problems.<commit_after>#ifndef BUFFER_CACHE_ALT_ALT_HPP_\n#define BUFFER_CACHE_ALT_ALT_HPP_\n\n#include <map>\n#include <vector>\n#include <utility>\n\n#include \"buffer_cache\/alt\/page.hpp\"\n#include \"buffer_cache\/general_types.hpp\"\n#include \"concurrency\/auto_drainer.hpp\"\n#include \"concurrency\/semaphore.hpp\"\n#include \"containers\/two_level_array.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"utils.hpp\"\n\nclass serializer_t;\n\nnamespace alt {\n\nclass alt_buf_lock_t;\nclass alt_cache_config_t;\nclass alt_cache_stats_t;\nclass alt_snapshot_node_t;\n\nclass alt_memory_tracker_t : public memory_tracker_t {\npublic:\n alt_memory_tracker_t();\n ~alt_memory_tracker_t();\n void inform_memory_change(uint64_t in_memory_size,\n uint64_t memory_limit);\n void begin_txn_or_throttle(int64_t expected_change_count);\n void end_txn(int64_t saved_expected_change_count);\nprivate:\n adjustable_semaphore_t semaphore_;\n DISABLE_COPYING(alt_memory_tracker_t);\n};\n\nclass alt_cache_t : public home_thread_mixin_t {\npublic:\n explicit alt_cache_t(serializer_t *serializer,\n const alt_cache_config_t &dynamic_config,\n perfmon_collection_t *perfmon_collection);\n ~alt_cache_t();\n\n block_size_t max_block_size() const;\n \/\/ RSI: Remove this.\n block_size_t get_block_size() const { return max_block_size(); }\n\n \/\/ These todos come from the mirrored cache. The real problem is that whole\n \/\/ cache account \/ priority thing is just one ghetto hack amidst a dozen other\n \/\/ throttling systems. TODO: Come up with a consistent priority scheme,\n \/\/ i.e. define a \"default\" priority etc. TODO: As soon as we can support it, we\n \/\/ might consider supporting a mem_cap paremeter.\n void create_cache_account(int priority, scoped_ptr_t<alt_cache_account_t> *out);\n\nprivate:\n friend class alt_txn_t; \/\/ for drainer_->lock()\n friend class alt_inner_txn_t; \/\/ for &page_cache_\n friend class alt_buf_read_t; \/\/ for &page_cache_\n friend class alt_buf_write_t; \/\/ for &page_cache_\n\n friend class alt_buf_lock_t; \/\/ for latest_snapshot_node and\n \/\/ push_latest_snapshot_node\n\n alt_snapshot_node_t *matching_snapshot_node_or_null(block_id_t block_id,\n block_version_t block_version);\n void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);\n void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);\n\n scoped_ptr_t<alt_cache_stats_t> stats_;\n\n \/\/ tracker_ is used for throttling (which can cause the alt_txn_t constructor to\n \/\/ block). RSI: The throttling interface is bad (maybe) because it's worried\n \/\/ about transaction_t's passing one another(?) or maybe the callers are bad with\n \/\/ their use of chained mutexes. Make sure that timestamps don't get mixed up in\n \/\/ their ordering, once they begin to play a role.\n alt_memory_tracker_t tracker_;\n page_cache_t page_cache_;\n\n two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;\n\n scoped_ptr_t<auto_drainer_t> drainer_;\n\n DISABLE_COPYING(alt_cache_t);\n};\n\nclass alt_inner_txn_t {\npublic:\n \/\/ This is public because scoped_ptr_t needs to call it.\n ~alt_inner_txn_t();\n\nprivate:\n friend class alt_txn_t;\n alt_inner_txn_t(alt_cache_t *cache,\n \/\/ Unused for read transactions, pass repli_timestamp_t::invalid.\n repli_timestamp_t txn_recency,\n alt_inner_txn_t *preceding_txn_or_null);\n\n alt_cache_t *cache() { return cache_; }\n\n page_txn_t *page_txn() { return &page_txn_; }\n\n alt_cache_t *cache_;\n page_txn_t page_txn_;\n\n DISABLE_COPYING(alt_inner_txn_t);\n};\n\nclass alt_txn_t {\npublic:\n \/\/ Constructor for read-only transactions.\n \/\/ RSI: Generally speaking I don't think we use preceding_txn -- and should read\n \/\/ transactions use preceding_txn at all?\n explicit alt_txn_t(alt_cache_t *cache,\n alt_read_access_t read_access,\n alt_txn_t *preceding_txn = NULL);\n\n\n \/\/ RSI: Remove default parameter for expected_change_count.\n \/\/ RSI: Generally speaking I don't think we use preceding_txn and we should.\n alt_txn_t(alt_cache_t *cache,\n write_durability_t durability,\n repli_timestamp_t txn_timestamp,\n int64_t expected_change_count = 2,\n alt_txn_t *preceding_txn = NULL);\n\n ~alt_txn_t();\n\n alt_cache_t *cache() { return inner_->cache(); }\n page_txn_t *page_txn() { return inner_->page_txn(); }\n alt_access_t access() const { return access_; }\n\n void set_account(alt_cache_account_t *cache_account);\n\nprivate:\n static void destroy_inner_txn(alt_inner_txn_t *inner,\n alt_cache_t *cache,\n int64_t saved_expected_change_count,\n auto_drainer_t::lock_t);\n\n const alt_access_t access_;\n\n \/\/ Only applicable if access_ == write.\n const write_durability_t durability_;\n const int64_t saved_expected_change_count_; \/\/ RSI: A fugly relationship with\n \/\/ the tracker.\n\n scoped_ptr_t<alt_inner_txn_t> inner_;\n DISABLE_COPYING(alt_txn_t);\n};\n\n\/\/ The intrusive list of alt_snapshot_node_t contains all the snapshot nodes for a\n\/\/ given block id, in order by version. (See\n\/\/ alt_cache_t::snapshot_nodes_by_block_id_.)\nclass alt_snapshot_node_t : public intrusive_list_node_t<alt_snapshot_node_t> {\npublic:\n explicit alt_snapshot_node_t(scoped_ptr_t<current_page_acq_t> &&acq);\n ~alt_snapshot_node_t();\n\nprivate:\n \/\/ RSI: Should this really use friends? Does this type need to be visible in the\n \/\/ header?\n friend class alt_buf_lock_t;\n friend class alt_cache_t;\n\n \/\/ This is never null (and is always a current_page_acq_t that has had\n \/\/ declare_snapshotted() called).\n scoped_ptr_t<current_page_acq_t> current_page_acq_;\n\n \/\/ RSP: std::map memory usage.\n \/\/ A NULL pointer associated with a block id indicates that the block is deleted.\n std::map<block_id_t, alt_snapshot_node_t *> children_;\n\n \/\/ The number of alt_buf_lock_t's referring to this node, plus the number of\n \/\/ alt_snapshot_node_t's referring to this node (via its children_ vector).\n int64_t ref_count_;\n\n\n DISABLE_COPYING(alt_snapshot_node_t);\n};\n\nclass alt_buf_parent_t;\n\nclass alt_buf_lock_t {\npublic:\n alt_buf_lock_t();\n\n \/\/ RSI: These constructors definitely duplicate one another. Too bad one\n \/\/ constructor can't call another (in GCC 4.4). Maybe we could still dedup\n \/\/ these, though, or get rid of some. (Make alt_access_t include create, and\n \/\/ separate it from page_access_t?)\n\n \/\/ Nonblocking constructor.\n alt_buf_lock_t(alt_buf_parent_t parent,\n block_id_t block_id,\n alt_access_t access);\n\n \/\/ Nonblocking constructor, creates a new block with a specified block id.\n alt_buf_lock_t(alt_txn_t *txn,\n block_id_t block_id,\n alt_create_t create);\n\n \/\/ Nonblocking constructor, IF parent->{access}_acq_signal() has already been\n \/\/ pulsed. In either case, returns before the block is acquired, but after we're\n \/\/ _in line_ for the block.\n alt_buf_lock_t(alt_buf_lock_t *parent,\n block_id_t block_id,\n alt_access_t access);\n\n \/\/ Nonblocking constructor that acquires a block with a new block id. `access`\n \/\/ must be `write`.\n alt_buf_lock_t(alt_buf_parent_t parent,\n alt_create_t create);\n\n \/\/ Nonblocking constructor, IF parent->{access}_acq_signal() has already been\n \/\/ pulsed. Allocates a block with a new block id. `access` must be `write`.\n alt_buf_lock_t(alt_buf_lock_t *parent,\n alt_create_t create);\n\n ~alt_buf_lock_t();\n\n alt_buf_lock_t(alt_buf_lock_t &&movee);\n alt_buf_lock_t &operator=(alt_buf_lock_t &&movee);\n\n void swap(alt_buf_lock_t &other);\n void reset_buf_lock();\n bool empty() const {\n return txn_ == NULL;\n }\n\n void snapshot_subtree();\n\n void detach_child(block_id_t child_id);\n\n block_id_t block_id() const {\n guarantee(txn_ != NULL);\n return current_page_acq()->block_id();\n }\n \/\/ RSI: Remove get_block_id().\n block_id_t get_block_id() const { return block_id(); }\n\n \/\/ RSI: Rename.\n repli_timestamp_t get_recency() const;\n\n alt_access_t access() const {\n guarantee(!empty());\n return current_page_acq()->access();\n }\n\n signal_t *read_acq_signal() {\n guarantee(!empty());\n return current_page_acq()->read_acq_signal();\n }\n signal_t *write_acq_signal() {\n guarantee(!empty());\n return current_page_acq()->write_acq_signal();\n }\n\n void mark_deleted();\n\n alt_txn_t *txn() const { return txn_; }\n alt_cache_t *cache() const { return txn_->cache(); }\n\nprivate:\n static void wait_for_parent(alt_buf_parent_t parent, alt_access_t access);\n static alt_snapshot_node_t *\n get_or_create_child_snapshot_node(alt_cache_t *cache,\n alt_snapshot_node_t *parent,\n block_id_t child_id);\n static void create_empty_child_snapshot_nodes(alt_cache_t *cache,\n block_version_t parent_version,\n block_id_t parent_id,\n block_id_t child_id);\n static void create_child_snapshot_nodes(alt_cache_t *cache,\n block_version_t parent_version,\n block_id_t parent_id,\n block_id_t child_id);\n current_page_acq_t *current_page_acq() const;\n\n friend class alt_buf_read_t; \/\/ for get_held_page_for_read, access_ref_count_.\n friend class alt_buf_write_t; \/\/ for get_held_page_for_write, access_ref_count_.\n\n page_t *get_held_page_for_read();\n page_t *get_held_page_for_write();\n\n alt_txn_t *txn_;\n\n scoped_ptr_t<current_page_acq_t> current_page_acq_;\n\n alt_snapshot_node_t *snapshot_node_;\n\n \/\/ Keeps track of how many alt_buf_{read|write}_t have been created for\n \/\/ this lock, for assertion\/guarantee purposes.\n intptr_t access_ref_count_;\n\n \/\/ RSI: We should get rid of this variable.\n bool was_destroyed_;\n\n DISABLE_COPYING(alt_buf_lock_t);\n};\n\n\nclass alt_buf_parent_t {\npublic:\n alt_buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }\n\n explicit alt_buf_parent_t(alt_buf_lock_t *lock)\n : txn_(lock->txn()), lock_or_null_(lock) {\n guarantee(lock != NULL);\n guarantee(!lock->empty());\n }\n \/\/ RSI: Replace this constructor with a create_dangerously static method.\n explicit alt_buf_parent_t(alt_txn_t *txn)\n : txn_(txn), lock_or_null_(NULL) { }\n\n alt_txn_t *txn() const {\n guarantee(txn_ != NULL);\n return txn_;\n }\n alt_cache_t *cache() const {\n guarantee(txn_ != NULL);\n return txn_->cache();\n }\n\nprivate:\n friend class alt_buf_lock_t;\n alt_txn_t *txn_;\n alt_buf_lock_t *lock_or_null_;\n};\n\nclass alt_buf_read_t {\npublic:\n explicit alt_buf_read_t(alt_buf_lock_t *lock);\n ~alt_buf_read_t();\n\n const void *get_data_read(uint32_t *block_size_out);\n \/\/ RSI: Remove.\n const void *get_data_read() {\n uint32_t unused_block_size;\n return get_data_read(&unused_block_size);\n }\n\nprivate:\n alt_buf_lock_t *lock_;\n page_acq_t page_acq_;\n\n DISABLE_COPYING(alt_buf_read_t);\n};\n\nclass alt_buf_write_t {\npublic:\n explicit alt_buf_write_t(alt_buf_lock_t *lock);\n ~alt_buf_write_t();\n\n void *get_data_write(uint32_t block_size);\n \/\/ Equivalent to passing the max_block_size.\n void *get_data_write();\n\nprivate:\n alt_buf_lock_t *lock_;\n page_acq_t page_acq_;\n\n DISABLE_COPYING(alt_buf_write_t);\n};\n\n\n} \/\/ namespace alt\n\n#endif \/\/ BUFFER_CACHE_ALT_ALT_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbIceViewer.h\"\n#include \"otbDEMHandler.h\"\n\n\nvoid error_callback(int, const char* description)\n{\n std::cerr << description << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" img1 ... imgN\" << std::endl << std::endl;\n\n return EXIT_FAILURE;\n }\n\n char* demdir = getenv(\"OTB_DEM_DIR\");\n char* geoidfile = getenv(\"OTB_GEOID_FILE\");\n\n otb::DEMHandler::Pointer demHandler = otb::DEMHandler::Instance();\n\n if (demdir != nullptr)\n {\n std::cout << \"Configuring DEM directory: \" << demdir << std::endl;\n demHandler->OpenDEMDirectory(demdir);\n }\n\n if (geoidfile != nullptr)\n {\n std::cout << \"Configuring geoid file: \" << geoidfile << std::endl;\n demHandler->OpenGeoidFile(geoidfile);\n }\n\n otb::IceViewer::Pointer viewer = otb::IceViewer::New();\n\n \/\/ Initialize viewer\n try\n {\n viewer->Initialize(800, 600);\n }\n catch (itk::ExceptionObject& err)\n {\n std::cerr << \"Failed to initialized viewer: \" << err << std::endl;\n return EXIT_FAILURE;\n }\n\n for (int i = 1; i < argc; ++i)\n {\n try\n {\n viewer->AddImage(argv[i], argv[i]);\n }\n catch (itk::ExceptionObject& err)\n {\n std::cerr << \"Failed to open object as image: \" << err << std::endl;\n try\n {\n viewer->AddVector(argv[i], argv[i]);\n }\n catch (itk::ExceptionObject& err2)\n {\n std::cerr << \"Failed to open object as vector: \" << err2 << std::endl;\n std::cerr << \"Could not open file \" << argv[i] << \" as an image or a vector, skipping.\" << std::endl;\n }\n }\n catch (std::runtime_error& err)\n {\n std::cerr << \"Runtime error: \" << err.what() << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"Press F1 for help\" << std::endl;\n\n viewer->Start();\n\n\n return EXIT_SUCCESS;\n}\n<commit_msg>BUG: use the new DEMHandler API in Ice<commit_after>\/*\n * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbIceViewer.h\"\n#include \"otbDEMHandler.h\"\n\n\nvoid error_callback(int, const char* description)\n{\n std::cerr << description << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" img1 ... imgN\" << std::endl << std::endl;\n\n return EXIT_FAILURE;\n }\n\n char* demdir = getenv(\"OTB_DEM_DIR\");\n char* geoidfile = getenv(\"OTB_GEOID_FILE\");\n\n auto& demHandler = otb::DEMHandler::GetInstance();\n\n if (demdir != nullptr)\n {\n std::cout << \"Configuring DEM directory: \" << demdir << std::endl;\n demHandler.OpenDEMDirectory(demdir);\n }\n\n if (geoidfile != nullptr)\n {\n std::cout << \"Configuring geoid file: \" << geoidfile << std::endl;\n demHandler.OpenGeoidFile(geoidfile);\n }\n\n otb::IceViewer::Pointer viewer = otb::IceViewer::New();\n\n \/\/ Initialize viewer\n try\n {\n viewer->Initialize(800, 600);\n }\n catch (itk::ExceptionObject& err)\n {\n std::cerr << \"Failed to initialized viewer: \" << err << std::endl;\n return EXIT_FAILURE;\n }\n\n for (int i = 1; i < argc; ++i)\n {\n try\n {\n viewer->AddImage(argv[i], argv[i]);\n }\n catch (itk::ExceptionObject& err)\n {\n std::cerr << \"Failed to open object as image: \" << err << std::endl;\n try\n {\n viewer->AddVector(argv[i], argv[i]);\n }\n catch (itk::ExceptionObject& err2)\n {\n std::cerr << \"Failed to open object as vector: \" << err2 << std::endl;\n std::cerr << \"Could not open file \" << argv[i] << \" as an image or a vector, skipping.\" << std::endl;\n }\n }\n catch (std::runtime_error& err)\n {\n std::cerr << \"Runtime error: \" << err.what() << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"Press F1 for help\" << std::endl;\n\n viewer->Start();\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: salgeom.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-04-11 18:06:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SV_SALGEOM_HXX\n#define _SV_SALGEOM_HXX\n\ntypedef struct _SalFrameGeometry {\n \/\/ screen position of upper left corner of drawable area in pixel\n int nX, nY;\n \/\/ dimensions of the drawable area in pixel\n unsigned int nWidth, nHeight;\n \/\/ thickness of the decoration in pixel\n unsigned int nLeftDecoration,\n nTopDecoration,\n nRightDecoration,\n nBottomDecoration;\n} SalFrameGeometry;\n\n#endif \/\/ _SV_SALGEOM_HXX\n<commit_msg>INTEGRATION: CWS presenterview (1.2.24); FILE MERGED 2007\/10\/12 13:25:56 pl 1.2.24.1: #i82554# add WB_SYSTEMCHILDWINDOW<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: salgeom.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-04-03 15:47:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SV_SALGEOM_HXX\n#define _SV_SALGEOM_HXX\n\ntypedef struct _SalFrameGeometry {\n \/\/ screen position of upper left corner of drawable area in pixel\n int nX, nY;\n \/\/ dimensions of the drawable area in pixel\n unsigned int nWidth, nHeight;\n \/\/ thickness of the decoration in pixel\n unsigned int nLeftDecoration,\n nTopDecoration,\n nRightDecoration,\n nBottomDecoration;\n unsigned int nScreenNumber;\n\n _SalFrameGeometry() :\n nX( 0 ), nY( 0 ), nWidth( 1 ), nHeight( 1 ),\n nLeftDecoration( 0 ), nTopDecoration( 0 ),\n nRightDecoration( 0 ), nBottomDecoration( 0 ),\n nScreenNumber( 0 )\n {}\n} SalFrameGeometry;\n\n#endif \/\/ _SV_SALGEOM_HXX\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com>\n Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"audiooutput.h\"\n#include <QVector>\n#include <QtCore\/QCoreApplication>\n\n#include <sys\/ioctl.h>\n#include <iostream>\n#include <QSet>\n#include \"mediaobject.h\"\n#include \"backend.h\"\n#include \"events.h\"\n#include \"wirecall.h\"\n#include \"xineengine.h\"\n#include \"xinethread.h\"\n#include \"keepreference.h\"\n#include \"audiodataoutput.h\"\n\n#include <xine\/audio_out.h>\n\n\/\/ the gcc 4.0 STL includes assert.h\n#undef assert\n\nnamespace Phonon\n{\nnamespace Xine\n{\n\nAudioOutput::AudioOutput(QObject *parent)\n : AbstractAudioOutput(new AudioOutputXT, parent)\n{\n}\n\nAudioOutput::~AudioOutput()\n{\n \/\/debug() << Q_FUNC_INFO ;\n}\n\nAudioOutputXT::~AudioOutputXT()\n{\n if (m_audioPort) {\n xine_close_audio_driver(m_xine, m_audioPort);\n m_audioPort = 0;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port destroyed\";\n }\n}\n\nqreal AudioOutput::volume() const\n{\n return m_volume;\n}\n\nint AudioOutput::outputDevice() const\n{\n return m_device.index();\n}\n\nvoid AudioOutput::setVolume(qreal newVolume)\n{\n m_volume = newVolume;\n\n int xinevolume = static_cast<int>(m_volume * 100);\n if (xinevolume > 200) {\n xinevolume = 200;\n } else if (xinevolume < 0) {\n xinevolume = 0;\n }\n\n upstreamEvent(new UpdateVolumeEvent(xinevolume));\n emit volumeChanged(m_volume);\n}\n\nxine_audio_port_t *AudioOutputXT::audioPort() const\n{\n return m_audioPort;\n}\n\nstatic QByteArray audioDriverFor(const QByteArray &driver)\n{\n if (driver == \"alsa\" || driver == \"oss\" || driver == \"pulseaudio\" || driver == \"esd\" ||\n driver == \"arts\" || driver == \"jack\") {\n return driver;\n }\n return QByteArray();\n}\n\nstatic bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver)\n{\n if(!xine_config_lookup_entry(xine, key, entry)) {\n \/\/ the config key is not registered yet - it is registered when the output\n \/\/ plugin is opened. So we open the plugin and close it again, then we can set the\n \/\/ setting. :(\n xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0);\n if (port) {\n xine_close_audio_driver(xine, port);\n \/\/ port == 0 does not have to be fatal, since it might be only the default device\n \/\/ that cannot be opened\n }\n \/\/ now the config key should be registered\n if(!xine_config_lookup_entry(xine, key, entry)) {\n qWarning() << \"cannot configure the device on Xine's\" << driver << \"output plugin\";\n return false;\n }\n }\n return true;\n}\n\nxine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc)\n{\n K_XT(AudioOutput);\n xine_audio_port_t *port = 0;\n if (!deviceDesc.isValid()) {\n \/\/ use null output for invalid devices\n port = xine_open_audio_driver(xt->m_xine, \"none\", 0);\n debug() << Q_FUNC_INFO << \"----------------------------------------------- null audio_port created\";\n return port;\n }\n\n typedef QPair<QByteArray, QString> PhononDeviceAccess;\n QList<PhononDeviceAccess> deviceAccessList = deviceAccessListFor(deviceDesc);\n if (deviceAccessList.isEmpty()) {\n const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index());\n if (outputPlugin == \"alsa\") {\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=0\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=1\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=2\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=3\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=4\"));\n } else if (outputPlugin == \"oss\") {\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp1\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp2\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp3\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp4\"));\n } else {\n debug() << Q_FUNC_INFO << \"use output plugin:\" << outputPlugin;\n port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0);\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n }\n const QList<PhononDeviceAccess> &_deviceAccessList = deviceAccessList;\n foreach (const PhononDeviceAccess &access, _deviceAccessList) {\n const QByteArray &outputPlugin = audioDriverFor(access.first);\n if (outputPlugin.isEmpty()) {\n continue;\n }\n const QString &handle = access.second;\n if (outputPlugin == \"alsa\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.device.alsa_default_device\",\n &deviceConfig, \"alsa\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n QByteArray deviceStr = handle.toUtf8();\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n const int err = xine_config_lookup_entry(xt->m_xine, \"audio.device.alsa_front_device\",\n &deviceConfig);\n Q_ASSERT(err); Q_UNUSED(err);\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"alsa\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use ALSA device: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n } else if (outputPlugin == \"pulseaudio\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.pulseaudio_device\", &deviceConfig,\n \"pulseaudio\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n QByteArray deviceStr = handle.toUtf8();\n deviceStr.replace('\\n', ':');\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"pulseaudio\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use PulseAudio: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n } else if (outputPlugin == \"oss\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.device.oss_device_name\", &deviceConfig,\n \"oss\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM);\n deviceConfig.num_value = 0;\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n if(!xine_config_lookup_entry(xt->m_xine, \"audio.device.oss_device_number\",\n &deviceConfig)) {\n qWarning() << \"cannot set the OSS device on Xine's OSS output plugin\";\n return 0;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM);\n const QByteArray &deviceStr = handle.toUtf8();\n char lastChar = deviceStr[deviceStr.length() - 1];\n int deviceNumber = -1;\n if (lastChar >= '0' || lastChar <= '9') {\n deviceNumber = lastChar - '0';\n char lastChar = deviceStr[deviceStr.length() - 2];\n if (lastChar >= '0' || lastChar <= '9') {\n deviceNumber += 10 * (lastChar - '0');\n }\n }\n deviceConfig.num_value = deviceNumber;\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"oss\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use OSS device: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n }\n }\n return port;\n}\n\nbool AudioOutput::setOutputDevice(int newDevice)\n{\n return setOutputDevice(AudioOutputDevice::fromIndex(newDevice));\n}\n\nbool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice)\n{\n K_XT(AudioOutput);\n if (!xt->m_xine) {\n \/\/ remeber the choice until we have a xine_t\n m_device = newDevice;\n return true;\n }\n\n xine_audio_port_t *port = createPort(newDevice);\n if (!port) {\n debug() << Q_FUNC_INFO << \"new audio port is invalid\";\n return false;\n }\n\n KeepReference<> *keep = new KeepReference<>;\n keep->addObject(xt);\n keep->ready();\n\n AudioOutputXT *newXt = new AudioOutputXT;\n newXt->m_audioPort = port;\n newXt->m_xine = xt->m_xine;\n m_threadSafeObject = newXt;\n\n m_device = newDevice;\n SourceNode *src = source();\n if (src) {\n QList<WireCall> wireCall;\n QList<WireCall> unwireCall;\n wireCall << WireCall(src, this);\n unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt));\n QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall));\n graphChanged();\n }\n\n AudioDataOutputXT *dataOutput = dynamic_cast<AudioDataOutputXT*>(m_source->threadSafeObject().data());\n if (dataOutput)\n dataOutput->intercept(xt->m_audioPort);\n\n return true;\n}\n\nvoid AudioOutput::xineEngineChanged()\n{\n K_XT(AudioOutput);\n if (xt->m_xine) {\n xine_audio_port_t *port = createPort(m_device);\n if (!port) {\n debug() << Q_FUNC_INFO << \"stored audio port is invalid\";\n QMetaObject::invokeMethod(this, \"audioDeviceFailed\", Qt::QueuedConnection);\n return;\n }\n\n \/\/ our XT object is in a wirecall, better not delete it\n\n Q_ASSERT(xt->m_audioPort == 0);\n xt->m_audioPort = port;\n\n\n AudioDataOutputXT *dataOutput = dynamic_cast<AudioDataOutputXT*>(m_source->threadSafeObject().data());\n if (dataOutput)\n dataOutput->intercept(xt->m_audioPort);\n }\n}\n\nvoid AudioOutput::aboutToChangeXineEngine()\n{\n K_XT(AudioOutput);\n if (xt->m_audioPort) {\n AudioOutputXT *xt2 = new AudioOutputXT;\n xt2->m_xine = xt->m_xine;\n xt2->m_audioPort = xt->m_audioPort;\n xt->m_audioPort = 0;\n KeepReference<> *keep = new KeepReference<>;\n keep->addObject(xt2);\n keep->ready();\n }\n}\n\nvoid AudioOutput::downstreamEvent(Event *e)\n{\n Q_ASSERT(e);\n QCoreApplication::sendEvent(this, e);\n SinkNode::downstreamEvent(e);\n}\n\nvoid AudioOutputXT::rewireTo(SourceNodeXT *source)\n{\n if (!source->audioOutputPort()) {\n return;\n }\n source->assert();\n xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort);\n source->assert();\n SinkNodeXT::assert();\n}\n\nbool AudioOutput::event(QEvent *ev)\n{\n switch (ev->type()) {\n case Event::AudioDeviceFailed:\n {\n ev->accept();\n \/\/ we don't know for sure which AudioPort failed. We also can't know from the\n \/\/ information libxine makes available. So we have to just try the old device again\n if (setOutputDevice(m_device)) {\n return true;\n }\n \/\/ we really need a different output device\n QMetaObject::invokeMethod(this, \"audioDeviceFailed\", Qt::QueuedConnection);\n }\n return true;\n default:\n return AbstractAudioOutput::event(ev);\n }\n}\n\nvoid AudioOutput::graphChanged()\n{\n debug() << Q_FUNC_INFO;\n \/\/ we got connected to a new XineStream, it needs to know our m_volume\n int xinevolume = static_cast<int>(m_volume * 100);\n if (xinevolume > 200) {\n xinevolume = 200;\n } else if (xinevolume < 0) {\n xinevolume = 0;\n }\n upstreamEvent(new UpdateVolumeEvent(xinevolume));\n}\n\n}} \/\/namespace Phonon::Xine\n\n#include \"audiooutput.moc\"\n\/\/ vim: sw=4 ts=4\n<commit_msg>xine: Fix output when using PulseAudio after latest changes.<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com>\n Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"audiooutput.h\"\n#include <QVector>\n#include <QtCore\/QCoreApplication>\n\n#include <sys\/ioctl.h>\n#include <iostream>\n#include <QSet>\n#include \"mediaobject.h\"\n#include \"backend.h\"\n#include \"events.h\"\n#include \"wirecall.h\"\n#include \"xineengine.h\"\n#include \"xinethread.h\"\n#include \"keepreference.h\"\n#include \"audiodataoutput.h\"\n\n#include <xine\/audio_out.h>\n\n\/\/ the gcc 4.0 STL includes assert.h\n#undef assert\n\nnamespace Phonon\n{\nnamespace Xine\n{\n\nAudioOutput::AudioOutput(QObject *parent)\n : AbstractAudioOutput(new AudioOutputXT, parent)\n{\n \/\/ Always initialise the \"device\" in use.\n \/\/ This is needed for PulseAudio support as subsequent calls to setOutputDevice()\n \/\/ are suppressed\n setOutputDevice(0);\n}\n\nAudioOutput::~AudioOutput()\n{\n \/\/debug() << Q_FUNC_INFO ;\n}\n\nAudioOutputXT::~AudioOutputXT()\n{\n if (m_audioPort) {\n xine_close_audio_driver(m_xine, m_audioPort);\n m_audioPort = 0;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port destroyed\";\n }\n}\n\nqreal AudioOutput::volume() const\n{\n return m_volume;\n}\n\nint AudioOutput::outputDevice() const\n{\n return m_device.index();\n}\n\nvoid AudioOutput::setVolume(qreal newVolume)\n{\n m_volume = newVolume;\n\n int xinevolume = static_cast<int>(m_volume * 100);\n if (xinevolume > 200) {\n xinevolume = 200;\n } else if (xinevolume < 0) {\n xinevolume = 0;\n }\n\n upstreamEvent(new UpdateVolumeEvent(xinevolume));\n emit volumeChanged(m_volume);\n}\n\nxine_audio_port_t *AudioOutputXT::audioPort() const\n{\n return m_audioPort;\n}\n\nstatic QByteArray audioDriverFor(const QByteArray &driver)\n{\n if (driver == \"alsa\" || driver == \"oss\" || driver == \"pulseaudio\" || driver == \"esd\" ||\n driver == \"arts\" || driver == \"jack\") {\n return driver;\n }\n return QByteArray();\n}\n\nstatic bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver)\n{\n if(!xine_config_lookup_entry(xine, key, entry)) {\n \/\/ the config key is not registered yet - it is registered when the output\n \/\/ plugin is opened. So we open the plugin and close it again, then we can set the\n \/\/ setting. :(\n xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0);\n if (port) {\n xine_close_audio_driver(xine, port);\n \/\/ port == 0 does not have to be fatal, since it might be only the default device\n \/\/ that cannot be opened\n }\n \/\/ now the config key should be registered\n if(!xine_config_lookup_entry(xine, key, entry)) {\n qWarning() << \"cannot configure the device on Xine's\" << driver << \"output plugin\";\n return false;\n }\n }\n return true;\n}\n\nxine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc)\n{\n K_XT(AudioOutput);\n xine_audio_port_t *port = 0;\n if (!deviceDesc.isValid()) {\n \/\/ use null output for invalid devices\n port = xine_open_audio_driver(xt->m_xine, \"none\", 0);\n debug() << Q_FUNC_INFO << \"----------------------------------------------- null audio_port created\";\n return port;\n }\n\n typedef QPair<QByteArray, QString> PhononDeviceAccess;\n QList<PhononDeviceAccess> deviceAccessList = deviceAccessListFor(deviceDesc);\n if (deviceAccessList.isEmpty()) {\n const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index());\n if (outputPlugin == \"alsa\") {\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=0\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=1\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=2\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=3\"));\n deviceAccessList << PhononDeviceAccess(\"alsa\", QLatin1String(\"default:CARD=4\"));\n } else if (outputPlugin == \"oss\") {\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp1\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp2\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp3\"));\n deviceAccessList << PhononDeviceAccess(\"oss\", QLatin1String(\"\/dev\/dsp4\"));\n } else {\n debug() << Q_FUNC_INFO << \"use output plugin:\" << outputPlugin;\n port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0);\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n }\n const QList<PhononDeviceAccess> &_deviceAccessList = deviceAccessList;\n foreach (const PhononDeviceAccess &access, _deviceAccessList) {\n const QByteArray &outputPlugin = audioDriverFor(access.first);\n if (outputPlugin.isEmpty()) {\n continue;\n }\n const QString &handle = access.second;\n if (outputPlugin == \"alsa\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.device.alsa_default_device\",\n &deviceConfig, \"alsa\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n QByteArray deviceStr = handle.toUtf8();\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n const int err = xine_config_lookup_entry(xt->m_xine, \"audio.device.alsa_front_device\",\n &deviceConfig);\n Q_ASSERT(err); Q_UNUSED(err);\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"alsa\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use ALSA device: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n } else if (outputPlugin == \"pulseaudio\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.pulseaudio_device\", &deviceConfig,\n \"pulseaudio\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING);\n QByteArray deviceStr = handle.toUtf8();\n deviceStr.replace('\\n', ':');\n deviceConfig.str_value = deviceStr.data();\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"pulseaudio\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use PulseAudio: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n } else if (outputPlugin == \"oss\") {\n xine_cfg_entry_t deviceConfig;\n if (!lookupConfigEntry(xt->m_xine, \"audio.device.oss_device_name\", &deviceConfig,\n \"oss\")) {\n continue;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM);\n deviceConfig.num_value = 0;\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n if(!xine_config_lookup_entry(xt->m_xine, \"audio.device.oss_device_number\",\n &deviceConfig)) {\n qWarning() << \"cannot set the OSS device on Xine's OSS output plugin\";\n return 0;\n }\n Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM);\n const QByteArray &deviceStr = handle.toUtf8();\n char lastChar = deviceStr[deviceStr.length() - 1];\n int deviceNumber = -1;\n if (lastChar >= '0' || lastChar <= '9') {\n deviceNumber = lastChar - '0';\n char lastChar = deviceStr[deviceStr.length() - 2];\n if (lastChar >= '0' || lastChar <= '9') {\n deviceNumber += 10 * (lastChar - '0');\n }\n }\n deviceConfig.num_value = deviceNumber;\n xine_config_update_entry(xt->m_xine, &deviceConfig);\n\n port = xine_open_audio_driver(xt->m_xine, \"oss\", 0);\n if (port) {\n debug() << Q_FUNC_INFO << \"use OSS device: \" << handle;\n debug() << Q_FUNC_INFO << \"----------------------------------------------- audio_port created\";\n return port;\n }\n }\n }\n return port;\n}\n\nbool AudioOutput::setOutputDevice(int newDevice)\n{\n return setOutputDevice(AudioOutputDevice::fromIndex(newDevice));\n}\n\nbool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice)\n{\n K_XT(AudioOutput);\n if (!xt->m_xine) {\n \/\/ remeber the choice until we have a xine_t\n m_device = newDevice;\n return true;\n }\n\n xine_audio_port_t *port = createPort(newDevice);\n if (!port) {\n debug() << Q_FUNC_INFO << \"new audio port is invalid\";\n return false;\n }\n\n KeepReference<> *keep = new KeepReference<>;\n keep->addObject(xt);\n keep->ready();\n\n AudioOutputXT *newXt = new AudioOutputXT;\n newXt->m_audioPort = port;\n newXt->m_xine = xt->m_xine;\n m_threadSafeObject = newXt;\n\n m_device = newDevice;\n SourceNode *src = source();\n if (src) {\n QList<WireCall> wireCall;\n QList<WireCall> unwireCall;\n wireCall << WireCall(src, this);\n unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt));\n QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall));\n graphChanged();\n }\n\n AudioDataOutputXT *dataOutput = dynamic_cast<AudioDataOutputXT*>(m_source->threadSafeObject().data());\n if (dataOutput)\n dataOutput->intercept(xt->m_audioPort);\n\n return true;\n}\n\nvoid AudioOutput::xineEngineChanged()\n{\n K_XT(AudioOutput);\n if (xt->m_xine) {\n xine_audio_port_t *port = createPort(m_device);\n if (!port) {\n debug() << Q_FUNC_INFO << \"stored audio port is invalid\";\n QMetaObject::invokeMethod(this, \"audioDeviceFailed\", Qt::QueuedConnection);\n return;\n }\n\n \/\/ our XT object is in a wirecall, better not delete it\n\n Q_ASSERT(xt->m_audioPort == 0);\n xt->m_audioPort = port;\n\n\n AudioDataOutputXT *dataOutput = dynamic_cast<AudioDataOutputXT*>(m_source->threadSafeObject().data());\n if (dataOutput)\n dataOutput->intercept(xt->m_audioPort);\n }\n}\n\nvoid AudioOutput::aboutToChangeXineEngine()\n{\n K_XT(AudioOutput);\n if (xt->m_audioPort) {\n AudioOutputXT *xt2 = new AudioOutputXT;\n xt2->m_xine = xt->m_xine;\n xt2->m_audioPort = xt->m_audioPort;\n xt->m_audioPort = 0;\n KeepReference<> *keep = new KeepReference<>;\n keep->addObject(xt2);\n keep->ready();\n }\n}\n\nvoid AudioOutput::downstreamEvent(Event *e)\n{\n Q_ASSERT(e);\n QCoreApplication::sendEvent(this, e);\n SinkNode::downstreamEvent(e);\n}\n\nvoid AudioOutputXT::rewireTo(SourceNodeXT *source)\n{\n if (!source->audioOutputPort()) {\n return;\n }\n source->assert();\n xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort);\n source->assert();\n SinkNodeXT::assert();\n}\n\nbool AudioOutput::event(QEvent *ev)\n{\n switch (ev->type()) {\n case Event::AudioDeviceFailed:\n {\n ev->accept();\n \/\/ we don't know for sure which AudioPort failed. We also can't know from the\n \/\/ information libxine makes available. So we have to just try the old device again\n if (setOutputDevice(m_device)) {\n return true;\n }\n \/\/ we really need a different output device\n QMetaObject::invokeMethod(this, \"audioDeviceFailed\", Qt::QueuedConnection);\n }\n return true;\n default:\n return AbstractAudioOutput::event(ev);\n }\n}\n\nvoid AudioOutput::graphChanged()\n{\n debug() << Q_FUNC_INFO;\n \/\/ we got connected to a new XineStream, it needs to know our m_volume\n int xinevolume = static_cast<int>(m_volume * 100);\n if (xinevolume > 200) {\n xinevolume = 200;\n } else if (xinevolume < 0) {\n xinevolume = 0;\n }\n upstreamEvent(new UpdateVolumeEvent(xinevolume));\n}\n\n}} \/\/namespace Phonon::Xine\n\n#include \"audiooutput.moc\"\n\/\/ vim: sw=4 ts=4\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <rtl\/bootstrap.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/registry\/XSimpleRegistry.hpp>\n#include <com\/sun\/star\/ucb\/UniversalContentBroker.hpp>\n\n#include <vcl\/vclmain.hxx>\n\n#include <tools\/urlobj.hxx>\n#include <tools\/stream.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/pngread.hxx>\n#include <vcl\/wrkwin.hxx>\n#include <vcl\/virdev.hxx>\n#include <vcl\/graphicfilter.hxx>\n\n# define FIXME_ALPHA_WORKING\n# define FIXME_ROUNDED_RECT_WORKING\n# define FIXME_DRAW_TRANSPARENT_WORKING\n#if 0\n#endif\n\nusing namespace css;\n\nclass DemoBase :\n public WorkWindow \/\/ hide OutputDevice if necessary\n{\npublic:\n DemoBase() : WorkWindow( NULL, WB_APP | WB_STDWORK)\n {\n }\n OutputDevice &getOutDev() { return *this; }\n};\n\nclass DemoWin : public DemoBase\n{\n Bitmap maIntroBW;\n BitmapEx maIntro;\n\npublic:\n DemoWin() : DemoBase()\n {\n \/\/ Needed to find images\n OUString aPath;\n rtl::Bootstrap::get(\"SYSBINDIR\", aPath);\n#ifdef FIXME_THIS_FAILS\n rtl::Bootstrap::set(\"BRAND_BASE_DIR\", aPath + \"\/..\");\n if (Application::LoadBrandBitmap(\"intro\", maIntro))\n Application::Abort(\"Failed to load intro image\");\n#else\n aPath = aPath + \"\/intro.png\";\n SvFileStream aFileStream( aPath, STREAM_READ );\n GraphicFilter aGraphicFilter(false);\n Graphic aGraphic;\n if (aGraphicFilter.ImportGraphic(aGraphic, aPath, aFileStream) != 0)\n Application::Abort(\"Failed to load intro image: \" + aPath);\n maIntro = aGraphic.GetBitmapEx();\n#endif\n maIntroBW = maIntro.GetBitmap();\n maIntroBW.Filter( BMP_FILTER_EMBOSS_GREY );\n }\n\n void drawToDevice(OutputDevice &r, bool bVdev);\n\n virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE\n {\n fprintf(stderr, \"DemoWin::Paint(%ld,%ld,%ld,%ld)\\n\", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());\n drawToDevice(getOutDev(), false);\n }\n\n std::vector<Rectangle> partitionAndClear(OutputDevice &rDev,\n int nX, int nY);\n\n void drawBackground(OutputDevice &rDev)\n {\n Rectangle r(Point(0,0), rDev.GetOutputSizePixel());\n Gradient aGradient;\n aGradient.SetStartColor(COL_BLUE);\n aGradient.SetEndColor(COL_GREEN);\n aGradient.SetStyle(GradientStyle_LINEAR);\n\/\/ aGradient.SetBorder(r.GetSize().Width()\/20);\n rDev.DrawGradient(r, aGradient);\n }\n\n void drawRadialLines(OutputDevice &rDev, Rectangle r)\n {\n rDev.SetFillColor(Color(COL_LIGHTRED));\n rDev.SetLineColor(Color(COL_BLACK));\n rDev.DrawRect( r );\n\n \/\/ FIXME: notice these appear reflected at the bottom not the top.\n for(int i=0; i<r.GetHeight(); i+=15)\n rDev.DrawLine( Point(r.Left(), r.Top()+i), Point(r.Right(), r.Bottom()-i) );\n for(int i=0; i<r.GetWidth(); i+=15)\n rDev.DrawLine( Point(r.Left()+i, r.Bottom()), Point(r.Right()-i, r.Top()) );\n\n \/\/ Should draw a white-line across the middle\n Color aLastPixel( COL_WHITE );\n Point aCenter((r.Left() + r.Right())\/2 - 4,\n (r.Top() + r.Bottom())\/2 - 4);\n for(int i=0; i<8; i++)\n {\n rDev.DrawPixel(aCenter, aLastPixel);\n aLastPixel = rDev.GetPixel(aCenter);\n aCenter.Move(1,1);\n }\n }\n\n void drawText(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.SetTextColor( Color( COL_BLACK ) );\n vcl::Font aFont( OUString( \"Times\" ), Size( 0, 25 ) );\n rDev.SetFont( aFont );\n rDev.DrawText( r, OUString( \"Just a simple text\" ) );\n }\n\n void drawPoly(OutputDevice &rDev, Rectangle r)\n \/\/ pretty\n {\n drawCheckered(rDev, r);\n\n long nDx = r.GetWidth()\/20;\n long nDy = r.GetHeight()\/20;\n Rectangle aShrunk(r);\n aShrunk.Move(nDx, nDy);\n aShrunk.SetSize(Size(r.GetWidth()-nDx*2,\n r.GetHeight()-nDy*2));\n Polygon aPoly(aShrunk);\n tools::PolyPolygon aPPoly(aPoly);\n rDev.SetLineColor(Color(COL_RED));\n rDev.SetFillColor(Color(COL_RED));\n \/\/ This hits the optional 'drawPolyPolygon' code-path\n rDev.DrawTransparent(aPPoly, 64);\n }\n void drawEllipse(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.SetLineColor(Color(COL_RED));\n rDev.SetFillColor(Color(COL_GREEN));\n rDev.DrawEllipse(r);\n }\n void drawCheckered(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.DrawCheckered(r.TopLeft(), r.GetSize());\n }\n void drawGradient(OutputDevice &rDev, Rectangle r)\n\n {\n Gradient aGradient;\n aGradient.SetStartColor(COL_YELLOW);\n aGradient.SetEndColor(COL_RED);\n\/\/ aGradient.SetAngle(45);\n aGradient.SetStyle(GradientStyle_RECT);\n aGradient.SetBorder(r.GetSize().Width()\/20);\n rDev.DrawGradient(r, aGradient);\n }\n void drawBitmap(OutputDevice &rDev, Rectangle r)\n\n {\n Bitmap aBitmap(maIntroBW);\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n void drawBitmapEx(OutputDevice &rDev, Rectangle r)\n\n {\n drawCheckered(rDev, r);\n\n BitmapEx aBitmap(maIntro);\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n#ifdef FIXME_ALPHA_WORKING\n AlphaMask aSemiTransp(aBitmap.GetSizePixel());\n aSemiTransp.Erase(64);\n rDev.DrawBitmapEx(r.TopLeft(), BitmapEx(aBitmap.GetBitmap(),\n aSemiTransp));\n#else\n rDev.DrawBitmapEx(r.TopLeft(), aBitmap);\n#endif\n }\n void drawPolyPolgons(OutputDevice &rDev, Rectangle r)\n\n {\n struct {\n double nX, nY;\n } aPoints[] = { { 0.1, 0.1 }, { 0.9, 0.9 },\n { 0.9, 0.1 }, { 0.1, 0.9 },\n { 0.1, 0.1 } };\n\n tools::PolyPolygon aPolyPoly;\n \/\/ Render 4x polygons & aggregate into another PolyPolygon\n for (int x = 0; x < 2; x++)\n {\n for (int y = 0; y < 2; y++)\n {\n Rectangle aSubRect(r);\n aSubRect.Move(x * r.GetWidth()\/3, y * r.GetHeight()\/3);\n aSubRect.SetSize(Size(r.GetWidth()\/2, r.GetHeight()\/4));\n Polygon aPoly(SAL_N_ELEMENTS(aPoints));\n for (size_t v = 0; v < SAL_N_ELEMENTS(aPoints); v++)\n {\n aPoly.SetPoint(Point(aSubRect.Left() +\n aSubRect.GetWidth() * aPoints[v].nX,\n aSubRect.Top() +\n aSubRect.GetHeight() * aPoints[v].nY),\n v);\n }\n rDev.SetLineColor(Color(COL_YELLOW));\n rDev.SetFillColor(Color(COL_BLACK));\n rDev.DrawPolygon(aPoly);\n\n \/\/ now move and add to the polypolygon\n aPoly.Move(0, r.GetHeight()\/2);\n aPolyPoly.Insert(aPoly);\n }\n }\n rDev.SetLineColor(Color(COL_LIGHTRED));\n rDev.SetFillColor(Color(COL_GREEN));\n#ifdef FIXME_DRAW_TRANSPARENT_WORKING\n rDev.DrawTransparent(aPolyPoly, 50);\n#else\n rDev.DrawPolyPolygon(aPolyPoly);\n#endif\n }\n void drawToVirtualDevice(OutputDevice &rDev, Rectangle r)\n {\n VirtualDevice aNested;\n aNested.SetOutputSize(r.GetSize());\n Rectangle aWhole(Point(0,0), r.GetSize());\n \/\/ mini me\n drawToDevice(aNested, true);\n\n Bitmap aBitmap(aNested.GetBitmap(Point(0,0),aWhole.GetSize()));\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n\n void fetchDrawBitmap(OutputDevice &rDev, Rectangle r)\n {\n \/\/ FIXME: should work ...\n Bitmap aBitmap(GetBitmap(Point(0,0),rDev.GetOutputSizePixel()));\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n};\n\nstd::vector<Rectangle> DemoWin::partitionAndClear(OutputDevice &rDev, int nX, int nY)\n{\n Rectangle r;\n std::vector<Rectangle> aRegions;\n\n \/\/ Make small cleared area for these guys\n Size aSize(rDev.GetOutputSizePixel());\n long nBorderSize = aSize.Width() \/ 32;\n long nBoxWidth = (aSize.Width() - nBorderSize*(nX+1)) \/ nX;\n long nBoxHeight = (aSize.Height() - nBorderSize*(nY+1)) \/ nY;\n for (int y = 0; y < nY; y++ )\n {\n for (int x = 0; x < nX; x++ )\n {\n r.SetPos(Point(nBorderSize + (nBorderSize + nBoxWidth) * x,\n nBorderSize + (nBorderSize + nBoxHeight) * y));\n r.SetSize(Size(nBoxWidth, nBoxHeight));\n\n \/\/ knock up a nice little border\n rDev.SetLineColor(COL_GRAY);\n rDev.SetFillColor(COL_LIGHTGRAY);\n if ((x + y) % 2)\n rDev.DrawRect(r);\n else\n {\n#ifdef FIXME_ROUNDED_RECT_WORKING\n rDev.DrawRect(r, nBorderSize, nBorderSize);\n#else\n rDev.DrawRect(r);\n#endif\n }\n\n aRegions.push_back(r);\n }\n }\n\n return aRegions;\n}\n\nvoid DemoWin::drawToDevice(OutputDevice &rDev, bool bVdev)\n{\n drawBackground(rDev);\n\n std::vector<Rectangle> aRegions(partitionAndClear(rDev, 4, 3));\n\n drawRadialLines(rDev, aRegions[0]);\n drawText(rDev, aRegions[1]);\n drawPoly(rDev, aRegions[2]);\n drawEllipse(rDev, aRegions[3]);\n drawCheckered(rDev, aRegions[4]);\n drawBitmapEx(rDev, aRegions[5]);\n drawBitmap(rDev, aRegions[6]);\n drawGradient(rDev, aRegions[7]);\n drawPolyPolgons(rDev, aRegions[8]);\n if (!bVdev)\n drawToVirtualDevice(rDev, aRegions[9]);\n \/\/ last - thumbnail all the above\n fetchDrawBitmap(rDev, aRegions[10]);\n}\n\nclass DemoApp : public Application\n{\npublic:\n DemoApp() {}\n\n virtual int Main() SAL_OVERRIDE\n {\n DemoWin aMainWin;\n aMainWin.SetText( \"Interactive VCL demo\" );\n aMainWin.Show();\n Application::Execute();\n return 0;\n }\n\nprotected:\n uno::Reference<lang::XMultiServiceFactory> xMSF;\n void Init() SAL_OVERRIDE\n {\n try\n {\n uno::Reference<uno::XComponentContext> xComponentContext\n = ::cppu::defaultBootstrap_InitialComponentContext();\n xMSF = uno::Reference<lang::XMultiServiceFactory>\n ( xComponentContext->getServiceManager(), uno::UNO_QUERY );\n if( !xMSF.is() )\n Application::Abort(\"Bootstrap failure - no service manager\");\n\n ::comphelper::setProcessServiceFactory( xMSF );\n }\n catch (const uno::Exception &e)\n {\n Application::Abort(\"Bootstrap exception \" + e.Message);\n }\n }\n void DeInit() SAL_OVERRIDE\n {\n uno::Reference< lang::XComponent >(\n comphelper::getProcessComponentContext(),\n uno::UNO_QUERY_THROW )-> dispose();\n ::comphelper::setProcessServiceFactory( NULL );\n }\n};\n\nvoid vclmain::createApplication()\n{\n static DemoApp aApp;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>vcldemo: load and render some icons<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <rtl\/bootstrap.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/registry\/XSimpleRegistry.hpp>\n#include <com\/sun\/star\/ucb\/UniversalContentBroker.hpp>\n\n#include <vcl\/vclmain.hxx>\n\n#include <tools\/urlobj.hxx>\n#include <tools\/stream.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/pngread.hxx>\n#include <vcl\/wrkwin.hxx>\n#include <vcl\/virdev.hxx>\n#include <vcl\/graphicfilter.hxx>\n\n#if 0\n# define FIXME_SELF_INTERSECTING_WORKING\n# define FIXME_DRAW_BITMAPEX\n#endif\n\nusing namespace css;\n\nclass DemoBase :\n public WorkWindow \/\/ hide OutputDevice if necessary\n{\npublic:\n DemoBase() : WorkWindow( NULL, WB_APP | WB_STDWORK)\n {\n }\n OutputDevice &getOutDev() { return *this; }\n};\n\nclass DemoWin : public DemoBase\n{\n Bitmap maIntroBW;\n BitmapEx maIntro;\n\npublic:\n DemoWin() : DemoBase()\n {\n \/\/ Needed to find images\n OUString aPath;\n rtl::Bootstrap::get(\"SYSBINDIR\", aPath);\n#ifdef FIXME_THIS_FAILS\n rtl::Bootstrap::set(\"BRAND_BASE_DIR\", aPath + \"\/..\");\n if (Application::LoadBrandBitmap(\"intro\", maIntro))\n Application::Abort(\"Failed to load intro image\");\n#else\n aPath = aPath + \"\/intro.png\";\n SvFileStream aFileStream( aPath, STREAM_READ );\n GraphicFilter aGraphicFilter(false);\n Graphic aGraphic;\n if (aGraphicFilter.ImportGraphic(aGraphic, aPath, aFileStream) != 0)\n Application::Abort(\"Failed to load intro image: \" + aPath);\n maIntro = aGraphic.GetBitmapEx();\n#endif\n maIntroBW = maIntro.GetBitmap();\n maIntroBW.Filter( BMP_FILTER_EMBOSS_GREY );\n }\n\n void drawToDevice(OutputDevice &r, bool bVdev);\n\n virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE\n {\n fprintf(stderr, \"DemoWin::Paint(%ld,%ld,%ld,%ld)\\n\", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());\n drawToDevice(getOutDev(), false);\n }\n\n std::vector<Rectangle> partitionAndClear(OutputDevice &rDev,\n int nX, int nY);\n\n void drawBackground(OutputDevice &rDev)\n {\n Rectangle r(Point(0,0), rDev.GetOutputSizePixel());\n Gradient aGradient;\n aGradient.SetStartColor(COL_BLUE);\n aGradient.SetEndColor(COL_GREEN);\n aGradient.SetStyle(GradientStyle_LINEAR);\n\/\/ aGradient.SetBorder(r.GetSize().Width()\/20);\n rDev.DrawGradient(r, aGradient);\n }\n\n void drawRadialLines(OutputDevice &rDev, Rectangle r)\n {\n rDev.SetFillColor(Color(COL_LIGHTRED));\n rDev.SetLineColor(Color(COL_BLACK));\n rDev.DrawRect( r );\n\n for(int i=0; i<r.GetHeight(); i+=15)\n rDev.DrawLine( Point(r.Left(), r.Top()+i), Point(r.Right(), r.Bottom()-i) );\n for(int i=0; i<r.GetWidth(); i+=15)\n rDev.DrawLine( Point(r.Left()+i, r.Bottom()), Point(r.Right()-i, r.Top()) );\n\n \/\/ Should draw a white-line across the middle\n Color aLastPixel( COL_WHITE );\n Point aCenter((r.Left() + r.Right())\/2 - 4,\n (r.Top() + r.Bottom())\/2 - 4);\n for(int i=0; i<8; i++)\n {\n rDev.DrawPixel(aCenter, aLastPixel);\n aLastPixel = rDev.GetPixel(aCenter);\n aCenter.Move(1,1);\n }\n }\n\n void drawText(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.SetTextColor( Color( COL_BLACK ) );\n vcl::Font aFont( OUString( \"Times\" ), Size( 0, 25 ) );\n rDev.SetFont( aFont );\n rDev.DrawText( r, OUString( \"Just a simple text\" ) );\n }\n\n void drawPoly(OutputDevice &rDev, Rectangle r) \/\/ pretty\n {\n drawCheckered(rDev, r);\n\n long nDx = r.GetWidth()\/20;\n long nDy = r.GetHeight()\/20;\n Rectangle aShrunk(r);\n aShrunk.Move(nDx, nDy);\n aShrunk.SetSize(Size(r.GetWidth()-nDx*2,\n r.GetHeight()-nDy*2));\n Polygon aPoly(aShrunk);\n tools::PolyPolygon aPPoly(aPoly);\n rDev.SetLineColor(Color(COL_RED));\n rDev.SetFillColor(Color(COL_RED));\n \/\/ This hits the optional 'drawPolyPolygon' code-path\n rDev.DrawTransparent(aPPoly, 64);\n }\n void drawEllipse(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.SetLineColor(Color(COL_RED));\n rDev.SetFillColor(Color(COL_GREEN));\n rDev.DrawEllipse(r);\n }\n void drawCheckered(OutputDevice &rDev, Rectangle r)\n\n {\n rDev.DrawCheckered(r.TopLeft(), r.GetSize());\n }\n void drawGradient(OutputDevice &rDev, Rectangle r)\n\n {\n Gradient aGradient;\n aGradient.SetStartColor(COL_YELLOW);\n aGradient.SetEndColor(COL_RED);\n\/\/ aGradient.SetAngle(45);\n aGradient.SetStyle(GradientStyle_RECT);\n aGradient.SetBorder(r.GetSize().Width()\/20);\n rDev.DrawGradient(r, aGradient);\n }\n void drawBitmap(OutputDevice &rDev, Rectangle r)\n\n {\n Bitmap aBitmap(maIntroBW);\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n void drawBitmapEx(OutputDevice &rDev, Rectangle r)\n\n {\n drawCheckered(rDev, r);\n\n BitmapEx aBitmap(maIntro);\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n AlphaMask aSemiTransp(aBitmap.GetSizePixel());\n aSemiTransp.Erase(64);\n rDev.DrawBitmapEx(r.TopLeft(), BitmapEx(aBitmap.GetBitmap(),\n aSemiTransp));\n }\n void drawPolyPolgons(OutputDevice &rDev, Rectangle r)\n\n {\n struct {\n double nX, nY;\n } aPoints[] = { { 0.1, 0.1 }, { 0.9, 0.9 },\n#ifdef FIXME_SELF_INTERSECTING_WORKING\n { 0.9, 0.1 }, { 0.1, 0.9 },\n { 0.1, 0.1 } };\n#else\n { 0.1, 0.9 }, { 0.5, 0.5 },\n { 0.9, 0.1 }, { 0.1, 0.1 } };\n#endif\n\n tools::PolyPolygon aPolyPoly;\n \/\/ Render 4x polygons & aggregate into another PolyPolygon\n for (int x = 0; x < 2; x++)\n {\n for (int y = 0; y < 2; y++)\n {\n Rectangle aSubRect(r);\n aSubRect.Move(x * r.GetWidth()\/3, y * r.GetHeight()\/3);\n aSubRect.SetSize(Size(r.GetWidth()\/2, r.GetHeight()\/4));\n Polygon aPoly(SAL_N_ELEMENTS(aPoints));\n for (size_t v = 0; v < SAL_N_ELEMENTS(aPoints); v++)\n {\n aPoly.SetPoint(Point(aSubRect.Left() +\n aSubRect.GetWidth() * aPoints[v].nX,\n aSubRect.Top() +\n aSubRect.GetHeight() * aPoints[v].nY),\n v);\n }\n rDev.SetLineColor(Color(COL_YELLOW));\n rDev.SetFillColor(Color(COL_BLACK));\n rDev.DrawPolygon(aPoly);\n\n \/\/ now move and add to the polypolygon\n aPoly.Move(0, r.GetHeight()\/2);\n aPolyPoly.Insert(aPoly);\n }\n }\n rDev.SetLineColor(Color(COL_LIGHTRED));\n rDev.SetFillColor(Color(COL_GREEN));\n rDev.DrawTransparent(aPolyPoly, 50);\n }\n void drawToVirtualDevice(OutputDevice &rDev, Rectangle r)\n {\n VirtualDevice aNested(rDev);\n aNested.SetOutputSizePixel(r.GetSize());\n Rectangle aWhole(Point(0,0), r.GetSize());\n \/\/ mini me\n drawToDevice(aNested, true);\n\n Bitmap aBitmap(aNested.GetBitmap(Point(0,0),aWhole.GetSize()));\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n\n std::vector<BitmapEx> maIcons;\n void initIcons()\n {\n if (maIcons.size())\n return;\n\n const char *pNames[] = {\n \"cmd\/lc_openurl.png\",\n \"cmd\/lc_newdoc.png\",\n \"cmd\/lc_save.png\",\n \"cmd\/lc_saveas.png\",\n \"cmd\/lc_sendmail.png\",\n \"cmd\/lc_editdoc.png\",\n \"cmd\/lc_print.png\",\n \"cmd\/lc_printpreview.png\",\n \"cmd\/lc_cut.png\",\n \"cmd\/lc_copy.png\",\n \"cmd\/lc_paste.png\",\n \"cmd\/lc_formatpaintbrush.png\",\n \"cmd\/lc_undo.png\",\n \"cmd\/lc_redo.png\",\n };\n for (size_t i = 0; i < SAL_N_ELEMENTS(pNames); i++)\n maIcons.push_back(BitmapEx(OUString::createFromAscii(pNames[i])));\n }\n void drawIcons(OutputDevice &rDev, Rectangle r)\n {\n initIcons();\n\n Rectangle p(r);\n for (size_t i = 0; i < maIcons.size(); i++)\n {\n Size aSize(maIcons[i].GetSizePixel());\n#ifdef FIXME_DRAW_BITMAPEX\n rDev.DrawBitmapEx(p.TopLeft(), maIcons[i]);\n#else\n rDev.DrawBitmap(p.TopLeft(), maIcons[i].GetBitmap());\n#endif\n p.Move(aSize.Width(), 0);\n if (p.Left() >= r.Right())\n break;\n }\n }\n\n void fetchDrawBitmap(OutputDevice &rDev, Rectangle r)\n {\n Bitmap aBitmap(GetBitmap(Point(0,0),rDev.GetOutputSizePixel()));\n aBitmap.Scale(r.GetSize(), BMP_SCALE_BESTQUALITY);\n rDev.DrawBitmap(r.TopLeft(), aBitmap);\n }\n};\n\nstd::vector<Rectangle> DemoWin::partitionAndClear(OutputDevice &rDev, int nX, int nY)\n{\n Rectangle r;\n std::vector<Rectangle> aRegions;\n\n \/\/ Make small cleared area for these guys\n Size aSize(rDev.GetOutputSizePixel());\n long nBorderSize = aSize.Width() \/ 32;\n long nBoxWidth = (aSize.Width() - nBorderSize*(nX+1)) \/ nX;\n long nBoxHeight = (aSize.Height() - nBorderSize*(nY+1)) \/ nY;\n for (int y = 0; y < nY; y++ )\n {\n for (int x = 0; x < nX; x++ )\n {\n r.SetPos(Point(nBorderSize + (nBorderSize + nBoxWidth) * x,\n nBorderSize + (nBorderSize + nBoxHeight) * y));\n r.SetSize(Size(nBoxWidth, nBoxHeight));\n\n \/\/ knock up a nice little border\n rDev.SetLineColor(COL_GRAY);\n rDev.SetFillColor(COL_LIGHTGRAY);\n if ((x + y) % 2)\n rDev.DrawRect(r, nBorderSize, nBorderSize);\n else\n rDev.DrawRect(r);\n\n aRegions.push_back(r);\n }\n }\n\n return aRegions;\n}\n\nvoid DemoWin::drawToDevice(OutputDevice &rDev, bool bVdev)\n{\n drawBackground(rDev);\n\n std::vector<Rectangle> aRegions(partitionAndClear(rDev, 4, 3));\n\n drawRadialLines(rDev, aRegions[0]);\n drawText(rDev, aRegions[1]);\n drawPoly(rDev, aRegions[2]);\n drawEllipse(rDev, aRegions[3]);\n drawCheckered(rDev, aRegions[4]);\n drawBitmapEx(rDev, aRegions[5]);\n drawBitmap(rDev, aRegions[6]);\n drawGradient(rDev, aRegions[7]);\n drawPolyPolgons(rDev, aRegions[8]);\n if (!bVdev)\n drawToVirtualDevice(rDev, aRegions[9]);\n drawIcons(rDev, aRegions[10]);\n \/\/ last - thumbnail all the above\n fetchDrawBitmap(rDev, aRegions[11]);\n}\n\nclass DemoApp : public Application\n{\npublic:\n DemoApp() {}\n\n virtual int Main() SAL_OVERRIDE\n {\n DemoWin aMainWin;\n aMainWin.SetText( \"Interactive VCL demo\" );\n aMainWin.Show();\n Application::Execute();\n return 0;\n }\n\nprotected:\n uno::Reference<lang::XMultiServiceFactory> xMSF;\n void Init() SAL_OVERRIDE\n {\n try\n {\n uno::Reference<uno::XComponentContext> xComponentContext\n = ::cppu::defaultBootstrap_InitialComponentContext();\n xMSF = uno::Reference<lang::XMultiServiceFactory>\n ( xComponentContext->getServiceManager(), uno::UNO_QUERY );\n if( !xMSF.is() )\n Application::Abort(\"Bootstrap failure - no service manager\");\n\n ::comphelper::setProcessServiceFactory( xMSF );\n }\n catch (const uno::Exception &e)\n {\n Application::Abort(\"Bootstrap exception \" + e.Message);\n }\n }\n void DeInit() SAL_OVERRIDE\n {\n uno::Reference< lang::XComponent >(\n comphelper::getProcessComponentContext(),\n uno::UNO_QUERY_THROW )-> dispose();\n ::comphelper::setProcessServiceFactory( NULL );\n }\n};\n\nvoid vclmain::createApplication()\n{\n static DemoApp aApp;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharserver.h\"\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"epackettype.h\"\n#include \"platform_defines.h\"\n#include \"connection.h\"\n#include <unordered_set>\n#include \"isc_client_status.h\"\n#include \"logconsole.h\"\n\n#include <algorithm>\n\nusing namespace RoseCommon;\n\nvoid update_status(const Packet::IscClientStatus& packet, CCharServer& server, User& user) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->debug(\"Char {} now has status {}\", user.get_name(), packet.get_status());\n const bool isSwitching = user.get_status() == User::Status::SWITCHING ? true : false;\n user.set_status(packet.get_status());\n \/\/ we update the id every client on the map refers to when talking about this character. (this is different from the charId)\n user.set_entityId(packet.get_entityMapId());\n if (user.get_status() == User::Status::CONNECTED && isSwitching) {\n \/\/ reload the map\n Core::CharacterTable characterTable{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto charRes = conn(sqlpp::select(characterTable.map)\n .from(characterTable).where(characterTable.id == user.get_charId()));\n if (charRes.empty()) {\n logger->error(\"Error while trying to access the updated map of {}\", user.get_name());\n return;\n }\n user.set_mapId(charRes.front().map);\n }\n}\n\nCCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) {\n register_dispatcher(std::function{update_status});\n register_dispatcher(std::function{party_request});\n\n reactor_thread = std::thread([this]() {\n for (auto [res, task] = work_queue.pop_front(); res;) {\n {\n std::lock_guard<std::recursive_mutex> lock(access);\n std::invoke(std::move(task), *this);\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n });\n}\n\nCCharServer::~CCharServer() {\n socket_[SocketType::Client]->shutdown();\n work_queue.kill();\n reactor_thread.join();\n}\n\nvoid CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) {\n \/\/if (_sock->is_active()) {\n \/\/ Do Something?\n std::string _address = _sock->get_address();\n if (IsISCServer() == false) {\n std::lock_guard<std::mutex> lock(client_list_mutex_);\n std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock));\n nClient->set_id(client_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"[{}] Client connected from: {}\", nClient->get_id(),\n _address.c_str());\n client_list_.push_front(std::move(nClient));\n } else {\n std::lock_guard<std::mutex> lock(isc_list_mutex_);\n std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock));\n nClient->set_id(server_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"Server connected from: {}\", _address.c_str() );\n isc_list_.push_front(std::move(nClient));\n }\n \/\/}\n}\n\nvoid CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) {\n std::shared_ptr<RoseCommon::CRoseClient> ptr;\n for (const auto& p : isc_list_) {\n if (p.get() == isc) {\n ptr = p;\n break;\n }\n }\n if (!ptr) {\n logger_->error(\"ISC server not found when registering maps!\");\n return;\n }\n for (const auto& m : maps) {\n this->maps[m] = ptr;\n }\n}\n\nvoid CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) {\n const auto& m = P.get_maps();\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n if (m.empty()) {\n for (const auto& [m, p] : maps) {\n if (auto ptr = p.lock()) {\n set.insert(ptr);\n }\n }\n } else if (m.size() == 1 && m[0] == 0) {\n dispatch_packet(P.get_originatorId(),\n RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data())));\n return;\n } else {\n for (const auto& mm : m) {\n if (auto ptr = maps[mm].lock()) {\n set.insert(ptr);\n }\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) {\n std::vector<uint16_t> maps;\n for (auto name : P.get_names()) {\n if (const auto user = get_user(name); user) {\n maps.push_back(user.value()->get_mapId());\n }\n }\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n for (auto map : maps) {\n if (auto ptr = this->maps[map].lock()) {\n set.insert(ptr);\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) {\n auto packet = RoseCommon::Packet::IscTransfer::create(0, {map});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n if (auto ptr = maps[map].lock()) {\n ptr->send(packet);\n }\n}\n\nvoid CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& p) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n auto packet = RoseCommon::Packet::IscTransferChar::create({user.value()->get_name()});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n\n if (auto ptr = maps[user.value()->get_mapId()].lock()) {\n ptr->send(packet);\n }\n}\n\nvoid CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n auto packet = RoseCommon::Packet::IscTransferChar::create({character});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n\n if (auto ptr = maps[user.value()->get_mapId()].lock()) {\n ptr->send(packet);\n }\n}\n\nbool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {\n if (!packet) {\n logger_->error(\"Empty packet\");\n return false;\n }\n if (!dispatcher.is_supported(*packet.get())) {\n logger_->error(\"Packet not supported!\");\n return false;\n }\n auto user = get_user(charId);\n if (!user) {\n logger_->error(\"User {} not loaded!\", charId);\n return false;\n }\n work_queue.push_back([&user = *user.value(), packet = std::move(packet)](CCharServer& server) mutable {\n server.dispatcher.dispatch(std::move(packet), server, std::forward<User&>(user));\n });\n return true;\n}\n\nstd::optional<const User*const> CCharServer::get_user(const std::string& name) const {\n if (const auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint32_t id) const {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) const {\n if (const auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(const std::string& name) {\n if (auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(uint32_t id) {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n \nstd::optional<User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) {\n if (auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nvoid CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) {\n Core::CharacterTable characterTable{};\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n\n auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map)\n .from(characterTable).where(characterTable.id == id));\n\n if (charRes.empty()) {\n return;\n }\n User user(client, charRes.front().name, id, charRes.front().map);\n user.set_party(partys.get_party(id)); \/\/ we load the party if there is one for that character\n}\n\nvoid CCharServer::unload_user(uint32_t id) {\n users.erase(id);\n}\n<commit_msg>Update ccharserver.cpp<commit_after>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharserver.h\"\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"epackettype.h\"\n#include \"platform_defines.h\"\n#include \"connection.h\"\n#include <unordered_set>\n#include \"isc_client_status.h\"\n#include \"logconsole.h\"\n\n#include <algorithm>\n\nusing namespace RoseCommon;\n\nvoid update_status(const Packet::IscClientStatus& packet, CCharServer& server, User& user) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->debug(\"Char {} now has status {}\", user.get_name(), packet.get_status());\n const bool isSwitching = user.get_status() == User::Status::SWITCHING ? true : false;\n user.set_status(packet.get_status());\n \/\/ we update the id every client on the map refers to when talking about this character. (this is different from the charId)\n user.set_entityId(packet.get_entityMapId());\n if (user.get_status() == User::Status::CONNECTED && isSwitching) {\n \/\/ reload the map\n Core::CharacterTable characterTable{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto charRes = conn(sqlpp::select(characterTable.map)\n .from(characterTable).where(characterTable.id == user.get_charId()));\n if (charRes.empty()) {\n logger->error(\"Error while trying to access the updated map of {}\", user.get_name());\n return;\n }\n user.set_mapId(charRes.front().map);\n }\n}\n\nCCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) {\n register_dispatcher(std::function{update_status});\n register_dispatcher(std::function{party_request});\n\n reactor_thread = std::thread([this]() {\n for (auto [res, task] = work_queue.pop_front(); res;) {\n {\n std::lock_guard<std::recursive_mutex> lock(access);\n std::invoke(std::move(task), *this);\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n });\n}\n\nCCharServer::~CCharServer() {\n socket_[SocketType::Client]->shutdown();\n work_queue.kill();\n reactor_thread.join();\n}\n\nvoid CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) {\n \/\/if (_sock->is_active()) {\n \/\/ Do Something?\n std::string _address = _sock->get_address();\n if (IsISCServer() == false) {\n std::lock_guard<std::mutex> lock(client_list_mutex_);\n std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock));\n nClient->set_id(client_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"[{}] Client connected from: {}\", nClient->get_id(),\n _address.c_str());\n client_list_.push_front(std::move(nClient));\n } else {\n std::lock_guard<std::mutex> lock(isc_list_mutex_);\n std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock));\n nClient->set_id(server_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"Server connected from: {}\", _address.c_str() );\n isc_list_.push_front(std::move(nClient));\n }\n \/\/}\n}\n\nvoid CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) {\n std::shared_ptr<RoseCommon::CRoseClient> ptr;\n for (const auto& p : isc_list_) {\n if (p.get() == isc) {\n ptr = p;\n break;\n }\n }\n if (!ptr) {\n logger_->error(\"ISC server not found when registering maps!\");\n return;\n }\n for (const auto& m : maps) {\n this->maps[m] = ptr;\n }\n}\n\nvoid CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) {\n const auto& m = P.get_maps();\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n if (m.empty()) {\n for (const auto& [m, p] : maps) {\n if (auto ptr = p.lock()) {\n set.insert(ptr);\n }\n }\n } else if (m.size() == 1 && m[0] == 0) {\n dispatch_packet(P.get_originatorId(),\n RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data())));\n return;\n } else {\n for (const auto& mm : m) {\n if (auto ptr = maps[mm].lock()) {\n set.insert(ptr);\n }\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) {\n std::vector<uint16_t> maps;\n for (auto name : P.get_names()) {\n if (const auto user = get_user(name); user) {\n maps.push_back(user.value()->get_mapId());\n }\n }\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n for (auto map : maps) {\n if (auto ptr = this->maps[map].lock()) {\n set.insert(ptr);\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) {\n auto packet = RoseCommon::Packet::IscTransfer::create(0, {map});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n if (auto ptr = maps[map].lock()) {\n ptr->send(packet);\n }\n}\n\nvoid CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& packet) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nvoid CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nbool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {\n if (!packet) {\n logger_->error(\"Empty packet\");\n return false;\n }\n if (!dispatcher.is_supported(*packet.get())) {\n logger_->error(\"Packet not supported!\");\n return false;\n }\n auto user = get_user(charId);\n if (!user) {\n logger_->error(\"User {} not loaded!\", charId);\n return false;\n }\n work_queue.push_back([&user = *user.value(), packet = std::move(packet)](CCharServer& server) mutable {\n server.dispatcher.dispatch(std::move(packet), server, std::forward<User&>(user));\n });\n return true;\n}\n\nstd::optional<const User*const> CCharServer::get_user(const std::string& name) const {\n if (const auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint32_t id) const {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) const {\n if (const auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(const std::string& name) {\n if (auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(uint32_t id) {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n \nstd::optional<User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) {\n if (auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nvoid CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) {\n Core::CharacterTable characterTable{};\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n\n auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map)\n .from(characterTable).where(characterTable.id == id));\n\n if (charRes.empty()) {\n return;\n }\n User user(client, charRes.front().name, id, charRes.front().map);\n user.set_party(partys.get_party(id)); \/\/ we load the party if there is one for that character\n}\n\nvoid CCharServer::unload_user(uint32_t id) {\n users.erase(id);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharserver.h\"\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"epackettype.h\"\n#include \"platform_defines.h\"\n#include \"connection.h\"\n#include <unordered_set>\n#include \"isc_client_status.h\"\n#include \"logconsole.h\"\n\n#include <algorithm>\n\nusing namespace RoseCommon;\n\nvoid update_status(const Packet::IscClientStatus& packet, CCharServer& server, User& user) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->debug(\"Char {} now has status {}\", user.get_name(), packet.get_status());\n const bool isSwitching = user.get_status() == User::Status::SWITCHING ? true : false;\n user.set_status(packet.get_status());\n \/\/ we update the id every client on the map refers to when talking about this character. (this is different from the charId)\n user.set_entityId(packet.get_entityMapId());\n if (user.get_status() == User::Status::CONNECTED && isSwitching) {\n \/\/ reload the map\n Core::CharacterTable characterTable{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto charRes = conn(sqlpp::select(characterTable.map)\n .from(characterTable).where(characterTable.id == user.get_charId()));\n if (charRes.empty()) {\n logger->error(\"Error while trying to access the updated map of {}\", user.get_name());\n return;\n }\n user.set_mapId(charRes.front().map);\n }\n}\n\nCCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) {\n register_dispatcher(std::function{update_status});\n register_dispatcher(std::function{party_request});\n\n reactor_thread = std::thread([this]() {\n for (auto [res, task] = work_queue.pop_front(); res;) {\n {\n std::lock_guard<std::recursive_mutex> lock(access);\n std::invoke(std::move(task), *this);\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n });\n}\n\nCCharServer::~CCharServer() {\n socket_[SocketType::Client]->shutdown();\n work_queue.kill();\n reactor_thread.join();\n}\n\nvoid CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) {\n \/\/if (_sock->is_active()) {\n \/\/ Do Something?\n std::string _address = _sock->get_address();\n if (IsISCServer() == false) {\n std::lock_guard<std::mutex> lock(client_list_mutex_);\n std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock));\n nClient->set_id(client_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"[{}] Client connected from: {}\", nClient->get_id(),\n _address.c_str());\n client_list_.push_front(std::move(nClient));\n } else {\n std::lock_guard<std::mutex> lock(isc_list_mutex_);\n std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock));\n nClient->set_id(server_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"Server connected from: {}\", _address.c_str() );\n isc_list_.push_front(std::move(nClient));\n }\n \/\/}\n}\n\nvoid CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) {\n std::shared_ptr<RoseCommon::CRoseClient> ptr;\n for (const auto& p : isc_list_) {\n if (p.get() == isc) {\n ptr = p;\n break;\n }\n }\n if (!ptr) {\n logger_->error(\"ISC server not found when registering maps!\");\n return;\n }\n for (const auto& m : maps) {\n this->maps[m] = ptr;\n }\n}\n\nvoid CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) {\n const auto& m = P.get_maps();\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n if (m.empty()) {\n for (const auto& [m, p] : maps) {\n if (auto ptr = p.lock()) {\n set.insert(ptr);\n }\n }\n } else if (m.size() == 1 && m[0] == 0) {\n dispatch_packet(P.get_originatorId(),\n RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data())));\n return;\n } else {\n for (const auto& mm : m) {\n if (auto ptr = maps[mm].lock()) {\n set.insert(ptr);\n }\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) {\n std::vector<uint16_t> maps;\n for (auto name : P.get_names()) {\n if (const auto user = get_user(name); user) {\n maps.push_back(user.value()->get_mapId());\n }\n }\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n for (auto map : maps) {\n if (auto ptr = this->maps[map].lock()) {\n set.insert(ptr);\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) {\n auto packet = RoseCommon::Packet::IscTransfer::create(0, {map});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n if (auto ptr = maps[map].lock()) {\n ptr->send(packet);\n }\n}\n\nvoid CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& packet) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nvoid CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nbool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {\n if (!packet) {\n logger_->error(\"Empty packet\");\n return false;\n }\n if (!dispatcher.is_supported(*packet.get())) {\n logger_->error(\"Packet not supported!\");\n return false;\n }\n auto user = get_user(charId);\n if (!user) {\n logger_->error(\"User {} not loaded!\", charId);\n return false;\n }\n work_queue.push_back([&user = *user.value(), packet = std::move(packet)](CCharServer& server) mutable {\n server.dispatcher.dispatch(std::move(packet), server, std::forward<User&>(user));\n });\n return true;\n}\n\nstd::optional<const User*const> CCharServer::get_user(const std::string& name) const {\n if (const auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint32_t id) const {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) const {\n if (const auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(const std::string& name) {\n if (auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(uint32_t id) {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n \nstd::optional<User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) {\n if (auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nvoid CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) {\n Core::CharacterTable characterTable{};\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n\n auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map)\n .from(characterTable).where(characterTable.id == id));\n\n if (charRes.empty()) {\n return;\n }\n User user(client, charRes.front().name, id, charRes.front().map);\n user.set_party(partys.get_party(id)); \/\/ we load the party if there is one for that character\n}\n\nvoid CCharServer::unload_user(uint32_t id) {\n users.erase(id);\n}\n<commit_msg>Update ccharserver.cpp<commit_after>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharserver.h\"\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"epackettype.h\"\n#include \"platform_defines.h\"\n#include \"connection.h\"\n#include <unordered_set>\n#include \"isc_client_status.h\"\n#include \"logconsole.h\"\n\n#include <algorithm>\n\nusing namespace RoseCommon;\n\nvoid update_status(const Packet::IscClientStatus& packet, CCharServer& server, User& user) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->debug(\"Char {} now has status {}\", user.get_name(), packet.get_status());\n const bool isSwitching = user.get_status() == User::Status::SWITCHING ? true : false;\n user.set_status(packet.get_status());\n \/\/ we update the id every client on the map refers to when talking about this character. (this is different from the charId)\n user.set_entityId(packet.get_entityMapId());\n if (user.get_status() == User::Status::CONNECTED && isSwitching) {\n \/\/ reload the map\n Core::CharacterTable characterTable{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto charRes = conn(sqlpp::select(characterTable.map)\n .from(characterTable).where(characterTable.id == user.get_charId()));\n if (charRes.empty()) {\n logger->error(\"Error while trying to access the updated map of {}\", user.get_name());\n return;\n }\n user.set_mapId(charRes.front().map);\n }\n}\n\nCCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) {\n register_dispatcher(std::function{update_status});\n register_dispatcher(std::function{party_request});\n\n reactor_thread = std::thread([this]() {\n for (auto [res, task] = work_queue.pop_front(); res;) {\n {\n std::lock_guard<std::recursive_mutex> lock(access);\n std::invoke(std::move(task), *this);\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n });\n}\n\nCCharServer::~CCharServer() {\n socket_[SocketType::Client]->shutdown();\n work_queue.kill();\n reactor_thread.join();\n}\n\nvoid CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) {\n \/\/if (_sock->is_active()) {\n \/\/ Do Something?\n std::string _address = _sock->get_address();\n if (IsISCServer() == false) {\n std::lock_guard<std::mutex> lock(client_list_mutex_);\n std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock));\n nClient->set_id(client_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"[{}] Client connected from: {}\", nClient->get_id(),\n _address.c_str());\n client_list_.push_front(std::move(nClient));\n } else {\n std::lock_guard<std::mutex> lock(isc_list_mutex_);\n std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock));\n nClient->set_id(server_count_++);\n nClient->set_update_time( Core::Time::GetTickCount() );\n nClient->set_active(true);\n nClient->start_recv();\n logger_->info( \"Server connected from: {}\", _address.c_str() );\n isc_list_.push_front(std::move(nClient));\n }\n \/\/}\n}\n\nvoid CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) {\n std::shared_ptr<RoseCommon::CRoseClient> ptr;\n for (const auto& p : isc_list_) {\n if (p.get() == isc) {\n ptr = p;\n break;\n }\n }\n if (!ptr) {\n logger_->error(\"ISC server not found when registering maps!\");\n return;\n }\n for (const auto& m : maps) {\n this->maps[m] = ptr;\n }\n}\n\nvoid CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) {\n const auto& m = P.get_maps();\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n if (m.empty()) {\n for (const auto& [m, p] : maps) {\n if (auto ptr = p.lock()) {\n set.insert(ptr);\n }\n }\n } else if (m.size() == 1 && m[0] == 0) {\n dispatch_packet(P.get_originatorId(),\n RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data())));\n return;\n } else {\n for (const auto& mm : m) {\n if (auto ptr = maps[mm].lock()) {\n set.insert(ptr);\n }\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) {\n std::vector<uint16_t> maps;\n for (auto name : P.get_names()) {\n if (const auto user = get_user(name); user) {\n maps.push_back(user.value()->get_mapId());\n }\n }\n std::unordered_set<std::shared_ptr<CRoseClient>> set;\n for (auto map : maps) {\n if (auto ptr = this->maps[map].lock()) {\n set.insert(ptr);\n }\n }\n for (auto ptr : set) {\n ptr->send(P);\n }\n}\n\nvoid CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) {\n auto packet = RoseCommon::Packet::IscTransfer::create(0, {map});\n std::vector<uint8_t> blob;\n p.write_to_vector(blob);\n packet.set_blob(blob);\n if (auto ptr = maps[map].lock()) {\n ptr->send(packet);\n }\n}\n\nvoid CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& packet) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nvoid CCharServer::send_char(const User& user, const RoseCommon::CRosePacket& packet) {\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nvoid CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) {\n const auto user = get_user(character);\n if (!user) {\n return;\n }\n if (auto client = user.value()->get_client().lock(); client) {\n client->send_packet(packet);\n }\n}\n\nbool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) {\n if (!packet) {\n logger_->error(\"Empty packet\");\n return false;\n }\n if (!dispatcher.is_supported(*packet.get())) {\n logger_->error(\"Packet not supported!\");\n return false;\n }\n auto user = get_user(charId);\n if (!user) {\n logger_->error(\"User {} not loaded!\", charId);\n return false;\n }\n work_queue.push_back([&user = *user.value(), packet = std::move(packet)](CCharServer& server) mutable {\n server.dispatcher.dispatch(std::move(packet), server, std::forward<User&>(user));\n });\n return true;\n}\n\nstd::optional<const User*const> CCharServer::get_user(const std::string& name) const {\n if (const auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint32_t id) const {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n\nstd::optional<const User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) const {\n if (const auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(const std::string& name) {\n if (auto result = std::find_if(users.begin(), users.end(), \n [&name](const auto& user) { return user.second.get_name() == name; });\n result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nstd::optional<User*const> CCharServer::get_user(uint32_t id) {\n if (auto it = users.find(id); it != users.end()) {\n return {&it->second};\n }\n return {};\n}\n \nstd::optional<User*const> CCharServer::get_user(uint16_t id, uint16_t mapId) {\n if (auto result = std::find_if(users.begin(), users.end(), [id, mapId](const auto& user) {\n return user.second.get_mapId() == mapId && user.second.get_entityId() == id;\n }); result != users.end()) {\n return {&result->second};\n }\n return {};\n}\n\nvoid CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) {\n Core::CharacterTable characterTable{};\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n\n auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map)\n .from(characterTable).where(characterTable.id == id));\n\n if (charRes.empty()) {\n return;\n }\n User user(client, charRes.front().name, id, charRes.front().map);\n user.set_party(partys.get_party(id)); \/\/ we load the party if there is one for that character\n}\n\nvoid CCharServer::unload_user(uint32_t id) {\n users.erase(id);\n}\n\nstd::shared_ptr<Party> CCharServer::create_party(User& user) {\n auto party = partys.create_party(user.get_id());\n user.set_party(party);\n return party;\n}\n\nvoid CCharServer::add_user_to_party(User& user, std::shared_ptr<Party> party) {\n partys.add_member_to_party(party, user.get_id());\n user.set_party(party);\n \/\/ TODO: send packet\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include <cstdint>\n#include <cassert>\n\n#include <gtest\/gtest.h>\n\n#include \"joynr\/DelayedScheduler.h\"\n#include \"joynr\/Logger.h\"\n#include \"joynr\/Semaphore.h\"\n#include \"joynr\/SingleThreadedIOService.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/utils\/TimeUtils.h\"\n#include \"tests\/mock\/MockRunnable.h\"\n\nusing namespace joynr;\n\nusing namespace ::testing;\nusing ::testing::StrictMock;\n\n\/\/ Expected accuracy of the timer in milliseconds\nstatic const std::uint64_t timerAccuracy_ms = 15U;\n\nclass SimpleDelayedScheduler :\n public DelayedScheduler\n{\n\npublic:\n\n SimpleDelayedScheduler(std::shared_ptr<SingleThreadedIOService> singleThreadedIOService)\n : DelayedScheduler(std::bind(&SimpleDelayedScheduler::workAvailable, this, std::placeholders::_1), singleThreadedIOService->getIOService()),\n est_ms(0)\n {\n }\n\n ~SimpleDelayedScheduler() = default;\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n MOCK_CONST_METHOD1(workAvailableCalled, void (std::shared_ptr<Runnable>));\n MOCK_CONST_METHOD0(workAvailableInTime, void ());\n#pragma GCC diagnostic pop\n\n DelayedScheduler::RunnableHandle schedule(std::shared_ptr<Runnable> runnable,\n std::chrono::milliseconds delay)\n {\n RunnableHandle currentHandle = DelayedScheduler::schedule(runnable, delay);\n est_ms = TimeUtils::getCurrentMillisSinceEpoch() + delay.count();\n return currentHandle;\n }\n\n void workAvailable(std::shared_ptr<Runnable> runnable)\n {\n const std::uint64_t now_ms = TimeUtils::getCurrentMillisSinceEpoch();\n workAvailableCalled(runnable);\n\n if(est_ms > 0)\n {\n const std::uint64_t diff_ms = (now_ms > est_ms) ? now_ms - est_ms : est_ms - now_ms;\n\n JOYNR_LOG_TRACE(logger(), \"Runnable is available\");\n JOYNR_LOG_TRACE(logger(), \" ETA : {}\",est_ms);\n JOYNR_LOG_TRACE(logger(), \" current : {}\",now_ms);\n JOYNR_LOG_TRACE(logger(), \" difference : {}\",diff_ms);\n\n if (diff_ms <= timerAccuracy_ms)\n {\n workAvailableInTime();\n }\n }\n else\n {\n JOYNR_LOG_TRACE(logger(), \"No delay given but work available called.\");\n }\n \/\/if (runnable->isDeleteOnExit()) {\n \/\/ delete runnable;\n \/\/}\n }\n\nprivate:\n std::uint64_t est_ms;\n};\n\nTEST(DelayedSchedulerTest, startAndShutdownWithoutWork)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n\n scheduler->shutdown();\n}\n\nTEST(DelayedSchedulerTest, startAndShutdownWithPendingWork_callDtorOfRunnablesCorrect)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n\n \/\/ Dtor should be called\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(100));\n\n \/\/ Dtor called after scheduler was cleaned\n auto runnable2 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable2, std::chrono::milliseconds(100));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n scheduler->shutdown();\n\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n EXPECT_CALL(*runnable2, dtorCalled()).Times(1);\n}\n\nTEST(DelayedSchedulerTest, testAccuracyOfDelayedScheduler)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(5));\n\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(1);\n EXPECT_CALL(*scheduler, workAvailableInTime()).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(1000)));\n\n scheduler->shutdown();\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n}\n\nTEST(DelayedSchedulerTest, avoidCallingDtorOfRunnablesAfterSchedulerHasExpired)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(5));\n\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));\n\n scheduler->shutdown();\n}\n\nTEST(DelayedSchedulerTest, scheduleAndUnscheduleRunnable_NoCallToRunnable)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n DelayedScheduler::RunnableHandle handle = scheduler->schedule(runnable1, std::chrono::milliseconds(50));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(0);\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n scheduler->unschedule(handle);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n scheduler->shutdown();\n}\n\nTEST(DelayedSchedulerTest, scheduleAndUnscheduleRunnable_CallDtorOnUnschedule)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n DelayedScheduler::RunnableHandle handle = scheduler->schedule(runnable1, std::chrono::milliseconds(50));\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n scheduler->unschedule(handle);\n runnable1.reset();\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));\n\n scheduler->shutdown();\n}\n<commit_msg>[C++] Stop SingleThreadedIOService in DelayedSchedulerTest<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include <cstdint>\n#include <cassert>\n\n#include <gtest\/gtest.h>\n\n#include \"joynr\/DelayedScheduler.h\"\n#include \"joynr\/Logger.h\"\n#include \"joynr\/Semaphore.h\"\n#include \"joynr\/SingleThreadedIOService.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/utils\/TimeUtils.h\"\n#include \"tests\/mock\/MockRunnable.h\"\n\nusing namespace joynr;\n\nusing namespace ::testing;\nusing ::testing::StrictMock;\n\n\/\/ Expected accuracy of the timer in milliseconds\nstatic const std::uint64_t timerAccuracy_ms = 15U;\n\nclass SimpleDelayedScheduler :\n public DelayedScheduler\n{\n\npublic:\n\n SimpleDelayedScheduler(std::shared_ptr<SingleThreadedIOService> singleThreadedIOService)\n : DelayedScheduler(std::bind(&SimpleDelayedScheduler::workAvailable, this, std::placeholders::_1), singleThreadedIOService->getIOService()),\n est_ms(0)\n {\n }\n\n ~SimpleDelayedScheduler() = default;\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n MOCK_CONST_METHOD1(workAvailableCalled, void (std::shared_ptr<Runnable>));\n MOCK_CONST_METHOD0(workAvailableInTime, void ());\n#pragma GCC diagnostic pop\n\n DelayedScheduler::RunnableHandle schedule(std::shared_ptr<Runnable> runnable,\n std::chrono::milliseconds delay)\n {\n RunnableHandle currentHandle = DelayedScheduler::schedule(runnable, delay);\n est_ms = TimeUtils::getCurrentMillisSinceEpoch() + delay.count();\n return currentHandle;\n }\n\n void workAvailable(std::shared_ptr<Runnable> runnable)\n {\n const std::uint64_t now_ms = TimeUtils::getCurrentMillisSinceEpoch();\n workAvailableCalled(runnable);\n\n if(est_ms > 0)\n {\n const std::uint64_t diff_ms = (now_ms > est_ms) ? now_ms - est_ms : est_ms - now_ms;\n\n JOYNR_LOG_TRACE(logger(), \"Runnable is available\");\n JOYNR_LOG_TRACE(logger(), \" ETA : {}\",est_ms);\n JOYNR_LOG_TRACE(logger(), \" current : {}\",now_ms);\n JOYNR_LOG_TRACE(logger(), \" difference : {}\",diff_ms);\n\n if (diff_ms <= timerAccuracy_ms)\n {\n workAvailableInTime();\n }\n }\n else\n {\n JOYNR_LOG_TRACE(logger(), \"No delay given but work available called.\");\n }\n \/\/if (runnable->isDeleteOnExit()) {\n \/\/ delete runnable;\n \/\/}\n }\n\nprivate:\n std::uint64_t est_ms;\n};\n\nTEST(DelayedSchedulerTest, startAndShutdownWithoutWork)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n\n scheduler->shutdown();\n singleThreadedIOService->stop();\n}\n\nTEST(DelayedSchedulerTest, startAndShutdownWithPendingWork_callDtorOfRunnablesCorrect)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n\n \/\/ Dtor should be called\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(100));\n\n \/\/ Dtor called after scheduler was cleaned\n auto runnable2 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable2, std::chrono::milliseconds(100));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n scheduler->shutdown();\n\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n EXPECT_CALL(*runnable2, dtorCalled()).Times(1);\n singleThreadedIOService->stop();\n}\n\nTEST(DelayedSchedulerTest, testAccuracyOfDelayedScheduler)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(5));\n\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(1);\n EXPECT_CALL(*scheduler, workAvailableInTime()).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(1000)));\n\n scheduler->shutdown();\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n singleThreadedIOService->stop();\n}\n\nTEST(DelayedSchedulerTest, avoidCallingDtorOfRunnablesAfterSchedulerHasExpired)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n scheduler->schedule(runnable1, std::chrono::milliseconds(5));\n\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));\n\n scheduler->shutdown();\n singleThreadedIOService->stop();\n}\n\nTEST(DelayedSchedulerTest, scheduleAndUnscheduleRunnable_NoCallToRunnable)\n{\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n DelayedScheduler::RunnableHandle handle = scheduler->schedule(runnable1, std::chrono::milliseconds(50));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1);\n EXPECT_CALL(*scheduler, workAvailableCalled(std::dynamic_pointer_cast<Runnable>(runnable1))).Times(0);\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n scheduler->unschedule(handle);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n scheduler->shutdown();\n singleThreadedIOService->stop();\n}\n\nTEST(DelayedSchedulerTest, scheduleAndUnscheduleRunnable_CallDtorOnUnschedule)\n{\n joynr::Semaphore semaphore;\n auto singleThreadedIOService = std::make_shared<SingleThreadedIOService>();\n singleThreadedIOService->start();\n auto scheduler = std::make_shared<SimpleDelayedScheduler>(singleThreadedIOService);\n auto runnable1 = std::make_shared<StrictMock<MockRunnable>>();\n DelayedScheduler::RunnableHandle handle = scheduler->schedule(runnable1, std::chrono::milliseconds(50));\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n\n EXPECT_CALL(*runnable1, dtorCalled()).Times(1).WillOnce(ReleaseSemaphore(&semaphore));\n\n scheduler->unschedule(handle);\n runnable1.reset();\n\n EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));\n\n scheduler->shutdown();\n singleThreadedIOService->stop();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 500){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n \/\/for(int i=0; i < obstacles_lc.size(); i++){\n \/\/ Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);\n \/\/}\n\n dmath::Vector3D g = goal_lc_;\n Fs += get_potential_force(g, 2, 0, 1.5, 1);\n \n dmath::Vector3D vel = Fs * force;\n cmd.linear.x = vel.y;\n cmd.linear.y = vel.x;\n cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n geometry_msgs::PointStamped g_lc;\n try{\n tf_listener_.transformPoint(base_link_, goal_msg, g_lc);\n goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n goal_lc_ = dmath::Vector3D();\n }\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n dmath::Vector3D goal_lc_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<commit_msg>Fix a parameter of attraction force from goal<commit_after>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 500){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n \/\/for(int i=0; i < obstacles_lc.size(); i++){\n \/\/ Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);\n \/\/}\n\n dmath::Vector3D g = goal_lc_;\n Fs += get_potential_force(g, 200, 0, 1.5, 1);\n \n dmath::Vector3D vel = Fs * force;\n cmd.linear.x = vel.y;\n cmd.linear.y = vel.x;\n cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n geometry_msgs::PointStamped g_lc;\n try{\n tf_listener_.transformPoint(base_link_, goal_msg, g_lc);\n goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n goal_lc_ = dmath::Vector3D();\n }\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n dmath::Vector3D goal_lc_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Basic tests.\n\n#include \"utils\/if_test_helper.hxx\"\n\n#include \"nmranet\/NMRAnetEventRegistry.hxx\"\n#include \"if\/nmranet_if.h\"\n\nTEST_F(IfTest, Setup) {}\n\nTEST_F(IfTest, WriteMessageSync) {\n \/\/ We write a message using the WriteFlow class directly into the interface.\n ExpectPacket(\":X195B412DN0102030405060708;\");\n event_write_helper1.WriteAsync(node_, MTI_EVENT_REPORT, WriteHelper::Global(),\n EventIdToBuffer(0x0102030405060708ULL),\n nullptr);\n}\n\nTEST_F(IfTest, WriteMessageASync) {\n \/\/ We write a message using the WriteFlow class asynchronously.\n ExpectPacket(\":X195B412DN0102030405060708;\");\n SyncNotifiable n;\n event_write_helper1.WriteAsync(node_, MTI_EVENT_REPORT, WriteHelper::Global(),\n EventIdToBuffer(0x0102030405060708ULL),\n &n);\n n.WaitForNotification();\n}\n\nTEST_F(IfTest, ReadMessageAndReply) {\n \/\/ We send an alias mapping enquiry frame and expect the node ID back.\n ExpectPacket(\":X1070112DN02010d000003;\");\n SendPacket( \":X10702000N;\");\n}\n<commit_msg>Fixes if_test_test for the c++ api.<commit_after>\/\/ Basic tests.\n\n#include \"utils\/if_test_helper.hxx\"\n\n#include \"nmranet\/NMRAnetEventRegistry.hxx\"\n#include \"nmranet\/NMRAnetIf.hxx\"\n\nnamespace NMRAnet {\n\nTEST_F(IfTest, Setup) {}\n\nTEST_F(IfTest, WriteMessageSync) {\n \/\/ We write a message using the WriteFlow class directly into the interface.\n ExpectPacket(\":X195B412DN0102030405060708;\");\n event_write_helper1.WriteAsync(node_, If::MTI_EVENT_REPORT, WriteHelper::global(),\n EventIdToBuffer(0x0102030405060708ULL),\n nullptr);\n}\n\nTEST_F(IfTest, WriteMessageASync) {\n \/\/ We write a message using the WriteFlow class asynchronously.\n ExpectPacket(\":X195B412DN0102030405060708;\");\n SyncNotifiable n;\n event_write_helper1.WriteAsync(node_, If::MTI_EVENT_REPORT, WriteHelper::global(),\n EventIdToBuffer(0x0102030405060708ULL),\n &n);\n n.WaitForNotification();\n}\n\nTEST_F(IfTest, ReadMessageAndReply) {\n \/\/ We send an alias mapping enquiry frame and expect the node ID back.\n ExpectPacket(\":X1070112DN02010d000003;\");\n SendPacket( \":X10702001N;\");\n}\n\n} \/\/ namespace NMRAnet\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) by respective owners including Yahoo!, Microsoft, and\n individual contributors. All rights reserved. Released under a BSD (revised)\n license as described in the file LICENSE.\n *\/\n#include \"gd.h\"\n\nusing namespace std;\nusing namespace LEARNER;\n\n#define W_XT 0 \/\/ current parameter w(XT)\n#define W_ZT 1 \/\/ accumulated z(t) = z(t-1) + g(t) + sigma*w(t)\n#define W_G2 2 \/\/ accumulated gradient squre n(t) = n(t-1) + g(t)*g(t)\n\n\/********************************************************************\/\n\/* mem & w definition ***********************************************\/\n\/********************************************************************\/ \n\/\/ w[0] = current weight\n\/\/ w[1] = accumulated zt\n\/\/ w[2] = accumulated g2\n\n\/\/nonrentrant\nstruct ftrl {\n vw* all; \/\/features, finalize, l1, l2, \n float ftrl_alpha;\n float ftrl_beta;\n};\n \nvoid predict(ftrl& b, base_learner& base, example& ec)\n{\n ec.partial_prediction = GD::inline_predict(*b.all, ec);\n ec.pred.scalar = GD::finalize_prediction(b.all->sd, ec.partial_prediction);\n}\n \ninline float sign(float w){ if (w < 0.) return -1.; else return 1.;}\n\nstruct update_data {\n float update;\n float ftrl_alpha;\n float ftrl_beta;\n float l1_lambda;\n float l2_lambda;\n};\n\nvoid inner_update(update_data& d, float x, float& wref) {\n float* w = &wref;\n float gradient = d.update * x;\n float ng2 = w[W_G2] + gradient * gradient;\n float sigma = (sqrtf(ng2) - sqrtf(w[W_G2]))\/ d.ftrl_alpha;\n w[W_ZT] += gradient - sigma * w[W_XT];\n w[W_G2] = ng2;\n float flag = sign(w[W_ZT]);\n float fabs_zt = w[W_ZT] * flag;\n if (fabs_zt <= d.l1_lambda) \n w[W_XT] = 0.;\n else {\n float step = 1\/(d.l2_lambda + (d.ftrl_beta + sqrtf(w[W_G2]))\/d.ftrl_alpha);\n w[W_XT] = step * flag * (d.l1_lambda - fabs_zt);\n }\n}\n\nvoid update(ftrl& b, example& ec)\n{\n struct update_data data; \n data.update = b.all->loss->first_derivative(b.all->sd, ec.pred.scalar, ec.l.simple.label)\n *ec.l.simple.weight;\n data.ftrl_alpha = b.ftrl_alpha;\n data.ftrl_beta = b.ftrl_beta;\n data.l1_lambda = b.all->l1_lambda;\n data.l2_lambda = b.all->l2_lambda;\n \n GD::foreach_feature<update_data, inner_update>(*b.all, ec, data);\n}\n\nvoid learn(ftrl& a, base_learner& base, example& ec) {\n assert(ec.in_use);\n \/\/ predict w*x\n predict(a, base, ec);\n \/\/updat state\n update(a,ec);\n}\n\nvoid save_load(ftrl& b, io_buf& model_file, bool read, bool text) \n{\n vw* all = b.all;\n if (read)\n initialize_regressor(*all);\n \n if (model_file.files.size() > 0) {\n bool resume = all->save_resume;\n char buff[512];\n uint32_t text_len = sprintf(buff, \":%d\\n\", resume);\n bin_text_read_write_fixed(model_file,(char *)&resume, sizeof (resume), \"\", read, buff, text_len, text);\n \n if (resume) \n GD::save_load_online_state(*all, model_file, read, text);\n else\n GD::save_load_regressor(*all, model_file, read, text);\n }\n}\n\nbase_learner* ftrl_setup(vw& all) \n{\n if (missing_option(all, false, \"ftrl\", \"Follow the Regularized Leader\")) \n return NULL;\n new_options(all, \"FTRL options\")\n (\"ftrl_alpha\", po::value<float>()->default_value(1.0), \"Learning rate for FTRL-proximal optimization\")\n (\"ftrl_beta\", po::value<float>()->default_value(0.1f), \"FTRL beta\");\n add_options(all);\n \n ftrl& b = calloc_or_die<ftrl>();\n b.all = &all;\n b.ftrl_beta = all.vm[\"ftrl_beta\"].as<float>();\n b.ftrl_alpha = all.vm[\"ftrl_alpha\"].as<float>();\n \n all.reg.stride_shift = 2; \/\/ NOTE: for more parameter storage\n \n if (!all.quiet) {\n cerr << \"Enabling FTRL-Proximal based optimization\" << endl;\n cerr << \"ftrl_alpha = \" << b.ftrl_alpha << endl;\n cerr << \"ftrl_beta = \" << b.ftrl_beta << endl;\n }\n \n learner<ftrl>& l = init_learner(&b, learn, 1 << all.reg.stride_shift);\n l.set_predict(predict);\n l.set_save_load(save_load);\n return make_base(l);\n}\n<commit_msg>better ftrl_alpha default<commit_after>\/*\n Copyright (c) by respective owners including Yahoo!, Microsoft, and\n individual contributors. All rights reserved. Released under a BSD (revised)\n license as described in the file LICENSE.\n *\/\n#include \"gd.h\"\n\nusing namespace std;\nusing namespace LEARNER;\n\n#define W_XT 0 \/\/ current parameter w(XT)\n#define W_ZT 1 \/\/ accumulated z(t) = z(t-1) + g(t) + sigma*w(t)\n#define W_G2 2 \/\/ accumulated gradient squre n(t) = n(t-1) + g(t)*g(t)\n\n\/********************************************************************\/\n\/* mem & w definition ***********************************************\/\n\/********************************************************************\/ \n\/\/ w[0] = current weight\n\/\/ w[1] = accumulated zt\n\/\/ w[2] = accumulated g2\n\n\/\/nonrentrant\nstruct ftrl {\n vw* all; \/\/features, finalize, l1, l2, \n float ftrl_alpha;\n float ftrl_beta;\n};\n \nvoid predict(ftrl& b, base_learner& base, example& ec)\n{\n ec.partial_prediction = GD::inline_predict(*b.all, ec);\n ec.pred.scalar = GD::finalize_prediction(b.all->sd, ec.partial_prediction);\n}\n \ninline float sign(float w){ if (w < 0.) return -1.; else return 1.;}\n\nstruct update_data {\n float update;\n float ftrl_alpha;\n float ftrl_beta;\n float l1_lambda;\n float l2_lambda;\n};\n\nvoid inner_update(update_data& d, float x, float& wref) {\n float* w = &wref;\n float gradient = d.update * x;\n float ng2 = w[W_G2] + gradient * gradient;\n float sigma = (sqrtf(ng2) - sqrtf(w[W_G2]))\/ d.ftrl_alpha;\n w[W_ZT] += gradient - sigma * w[W_XT];\n w[W_G2] = ng2;\n float flag = sign(w[W_ZT]);\n float fabs_zt = w[W_ZT] * flag;\n if (fabs_zt <= d.l1_lambda) \n w[W_XT] = 0.;\n else {\n float step = 1\/(d.l2_lambda + (d.ftrl_beta + sqrtf(w[W_G2]))\/d.ftrl_alpha);\n w[W_XT] = step * flag * (d.l1_lambda - fabs_zt);\n }\n}\n\nvoid update(ftrl& b, example& ec)\n{\n struct update_data data; \n data.update = b.all->loss->first_derivative(b.all->sd, ec.pred.scalar, ec.l.simple.label)\n *ec.l.simple.weight;\n data.ftrl_alpha = b.ftrl_alpha;\n data.ftrl_beta = b.ftrl_beta;\n data.l1_lambda = b.all->l1_lambda;\n data.l2_lambda = b.all->l2_lambda;\n \n GD::foreach_feature<update_data, inner_update>(*b.all, ec, data);\n}\n\nvoid learn(ftrl& a, base_learner& base, example& ec) {\n assert(ec.in_use);\n \/\/ predict w*x\n predict(a, base, ec);\n \/\/updat state\n update(a,ec);\n}\n\nvoid save_load(ftrl& b, io_buf& model_file, bool read, bool text) \n{\n vw* all = b.all;\n if (read)\n initialize_regressor(*all);\n \n if (model_file.files.size() > 0) {\n bool resume = all->save_resume;\n char buff[512];\n uint32_t text_len = sprintf(buff, \":%d\\n\", resume);\n bin_text_read_write_fixed(model_file,(char *)&resume, sizeof (resume), \"\", read, buff, text_len, text);\n \n if (resume) \n GD::save_load_online_state(*all, model_file, read, text);\n else\n GD::save_load_regressor(*all, model_file, read, text);\n }\n}\n\nbase_learner* ftrl_setup(vw& all) \n{\n if (missing_option(all, false, \"ftrl\", \"Follow the Regularized Leader\")) \n return NULL;\n new_options(all, \"FTRL options\")\n (\"ftrl_alpha\", po::value<float>()->default_value(0.005f), \"Learning rate for FTRL-proximal optimization\")\n (\"ftrl_beta\", po::value<float>()->default_value(0.1f), \"FTRL beta\");\n add_options(all);\n \n ftrl& b = calloc_or_die<ftrl>();\n b.all = &all;\n b.ftrl_beta = all.vm[\"ftrl_beta\"].as<float>();\n b.ftrl_alpha = all.vm[\"ftrl_alpha\"].as<float>();\n \n all.reg.stride_shift = 2; \/\/ NOTE: for more parameter storage\n \n if (!all.quiet) {\n cerr << \"Enabling FTRL-Proximal based optimization\" << endl;\n cerr << \"ftrl_alpha = \" << b.ftrl_alpha << endl;\n cerr << \"ftrl_beta = \" << b.ftrl_beta << endl;\n }\n \n learner<ftrl>& l = init_learner(&b, learn, 1 << all.reg.stride_shift);\n l.set_predict(predict);\n l.set_save_load(save_load);\n return make_base(l);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <QApplication>\n#include <QTextEdit>\n#include <QtGui>\n#include <QTextCodec>\n#include \"mainwindow.h\"\n#include \"login.h\"\n#include \"desktopimage.h\"\n#include \"mdi_background.h\"\n\n#include <kernel\/sched\/waitq.h>\n#include <fcntl.h>\n#include <framework\/mod\/options.h>\n#include <module\/platform\/zrv\/cmd\/texteditor.h>\n\n#define DEFAULT_WIDTH \\\n\t\tOPTION_MODULE_GET(platform__zrv__cmd__texteditor, NUMBER, root_window_width)\n\n#define DEFAULT_HEIGHT \\\n\t\tOPTION_MODULE_GET(platform__zrv__cmd__texteditor, NUMBER, root_window_height)\n\n#define FSIZE 64\n#define SEP ':'\n\nstatic QString defaultImagePath = \":\/images\/default.png\";\n\nQMdiAreaWBackground *emarea;\nstatic DesktopImageDialog *wallpaperDialog;\nstatic QStringList desktopImagesList;\nstatic QApplication *__qt_app;\nstatic QMenu *__qt_menu;\n\nstatic struct waitq texteditor_inited_wq;\nstatic char texteditor_inited;\nstatic int curuid;\n\nstatic void emboxQtShowLoginForm();\n\nclass EmboxRootWindow : public QMainWindow\n{\n Q_OBJECT\n\n public:\n\n\tQAction *closeAllEditorsAction;\n\tEmboxRootWindow() {\n\tfileMenu = new QMenu(QString(\"&Пуск\"), this);\n\tmenuBar()->addMenu(fileMenu);\n\n\t__qt_menu = fileMenu;\n\n\ttextEditorAction = new QAction(QString(\"&Текстовый редактор\"), this);\n\tfileMenu->addAction(textEditorAction);\n\tconnect(textEditorAction, SIGNAL(triggered()), this, SLOT(textEditorRun()));\n\n\tcloseAllEditorsAction = new QAction(QString(\"&Закрыть все окна\"), this);\n\tfileMenu->addAction(closeAllEditorsAction);\n\tconnect(closeAllEditorsAction, SIGNAL(triggered()), this, SLOT(closeAllEditors()));\n\n\tlogoutAction = new QAction(QString(\"&Завершение сеанса\"), this);\n\tfileMenu->addAction(logoutAction);\n\tconnect(logoutAction, SIGNAL(triggered()), this, SLOT(logout()));\n\n\tsaveAction = new QAction(QString(\"&Сохранить конфигурацию\"), this);\n\tfileMenu->addAction(saveAction);\n\tconnect(saveAction, SIGNAL(triggered()), this, SLOT(savedefault()));\n\n\twallpaperAction = new QAction(QString(\"&Графические настройки\"), this);\n\tfileMenu->addAction(wallpaperAction);\n\tconnect(wallpaperAction, SIGNAL(triggered()), this, SLOT(wallpaper()));\n }\n\n private slots:\n\tvoid textEditorRun() {\n\t\tTextEditor *textEditor = new TextEditor(emarea);\n\t\ttextEditor->show();\n\t}\n\n\tvoid closeAllEditors() {\n\t\tTextEditor::closeAllEditors();\n\t}\n\n\tvoid logout() {\n\t\temboxQtHideDesktop();\n\t\temboxQtShowLoginForm();\n\t}\n\n\tvoid wallpaper() {\n\t\twallpaperDialog = new DesktopImageDialog(desktopImagesList);\n\t\twallpaperDialog->show();\n\t}\n\n\tvoid savedefault() {\n\n\t}\n\n private:\n\tQAction *logoutAction;\n\tQAction *textEditorAction;\n\tQAction *wallpaperAction;\n\tQAction *saveAction;\n\tQMenu *fileMenu;\n};\n\nstatic EmboxRootWindow *emroot;\n\nstatic char *parse(char **buf) {\n\tchar *ret = *buf;\n\tchar *ch;\n\n\tif ((ch = strchr(*buf, SEP))) {\n\t\t*ch++ = '\\0';\n\t}\n\n\t*buf = ch;\n\n\treturn ret;\n}\n\nvoid emboxQtSetfont(const QString &fontFamily, int fontPt) {\n\tQFont serifFont(fontFamily, fontPt);\n\t__qt_app->setFont(serifFont);\n\t__qt_menu->setFont(serifFont);\n}\n\nstatic void load_pref(void) {\n\tint fd, ret;\n\tchar cbuf[FSIZE];\n\tconst char *wall = \"default.png\";\n\tconst char *font = \"Times\";\n\tint font_pt = 10;\n\n\tsnprintf(cbuf, FSIZE, \"\/mnt\/pref_%d\", curuid);\n\tfd = open(cbuf, O_RDONLY, 0755);\n\n\tif (fd == -1)\n\t\tgoto set_default;\n\n\tlseek(fd, 0, 0);\n\tif (0 < (ret = read(fd, cbuf, FSIZE))) {\n\t\tchar *buf = cbuf;\n\n\t\tbuf[ret] = '\\0';\n\n\t\twall = parse(&buf);\n\t\tfont = parse(&buf);\n\t\tfont_pt = atoi(parse(&buf));\n\t}\n\tclose(fd);\n\nset_default:\n\tQString imagePath = QString(\":\/images\/\").append(QString(wall));\n\temarea->setBackgroundPath(imagePath);\n\n\temboxQtSetfont(font, font_pt);\n\n}\n\nvoid emboxQtSavePref(char *wall, char *font, int font_pt) {\n\tint fd, len;\n\tchar cbuf[FSIZE];\n\n\tsnprintf(cbuf, FSIZE, \"\/mnt\/pref_%d\", curuid);\n\n\tfd = creat(cbuf, 0755);\n\n\tlen = snprintf(cbuf, FSIZE, \"%s:%s:%d\", wall, font, font_pt);\n\n\twrite(fd, cbuf, len);\n\n\tftruncate(fd, len);\n\n\tclose(fd);\n}\n\nvoid emboxQtShowDesktop(uid_t uid) {\n\tint fd = -1;\n\tbool enabled = uid ? false : true;\n\n\tcuruid = uid;\n\temroot->menuBar()->show();\n\temroot->closeAllEditorsAction->setEnabled(enabled);\n\n\tload_pref();\n}\n\nvoid emboxQtHideDesktop() {\n\temarea->closeAllSubWindows();\n\temroot->menuBar()->hide();\n}\n\nvoid emboxRootWindowShow(int width, int height) {\n\temroot->setGeometry(QRect(0,0, width, height));\n\ttexteditor_inited = 1;\n\twaitq_wakeup_all(&texteditor_inited_wq);\n}\n\nstatic void emboxQtShowLoginForm() {\n\tLoginDialog *loginDialog = new LoginDialog(0, emarea);\n\tloginDialog->show();\n\n\temarea->setBackgroundPath(defaultImagePath);\n}\n\nint main(int argv, char **args)\n{\n\t\/\/Q_INIT_RESOURCE(texteditor);\n\n\twaitq_init(&texteditor_inited_wq);\n\n\tQApplication app(argv, args);\n\n\t__qt_app = &app;\n\n\tQFont serifFont(\"Times\", 10);\n\tapp.setFont(serifFont);\n\tqDebug() << \"Supported formats:\" << QImageReader::supportedImageFormats();\n\tdesktopImagesList << \"cats.jpg\" << \"default.png\";\n\n\tQTextCodec::setCodecForCStrings(QTextCodec::codecForName(\"UTF-8\"));\n\tQTextCodec::setCodecForLocale(QTextCodec::codecForName(\"UTF-8\"));\n\tQTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n\n\temroot = new EmboxRootWindow();\n\temarea = new QMdiAreaWBackground(defaultImagePath);\n\n\temroot->setCentralWidget(emarea);\n\n\tif (DEFAULT_WIDTH == 0 || DEFAULT_HEIGHT == 0) {\n\t\tWAITQ_WAIT(&texteditor_inited_wq, texteditor_inited); \/* EMBOXVC plugin*\/\n\t} else {\n\t\temroot->setGeometry(QRect(0,0, DEFAULT_WIDTH, DEFAULT_HEIGHT)); \/* VNC plugin *\/\n\t}\n\n\temroot->show();\n\n\temboxQtHideDesktop();\n\n\temboxQtShowLoginForm();\n\n\treturn app.exec();\n}\n\n#include \"main.moc\"\n<commit_msg>qt-pro: Fix texteditor options references<commit_after>\n#include <QApplication>\n#include <QTextEdit>\n#include <QtGui>\n#include <QTextCodec>\n#include \"mainwindow.h\"\n#include \"login.h\"\n#include \"desktopimage.h\"\n#include \"mdi_background.h\"\n\n#include <kernel\/sched\/waitq.h>\n#include <fcntl.h>\n#include <framework\/mod\/options.h>\n#include <module\/zrv\/cmd\/texteditor.h>\n\n#define DEFAULT_WIDTH \\\n\t\tOPTION_MODULE_GET(zrv__cmd__texteditor, NUMBER, root_window_width)\n\n#define DEFAULT_HEIGHT \\\n\t\tOPTION_MODULE_GET(zrv__cmd__texteditor, NUMBER, root_window_height)\n\n#define FSIZE 64\n#define SEP ':'\n\nstatic QString defaultImagePath = \":\/images\/default.png\";\n\nQMdiAreaWBackground *emarea;\nstatic DesktopImageDialog *wallpaperDialog;\nstatic QStringList desktopImagesList;\nstatic QApplication *__qt_app;\nstatic QMenu *__qt_menu;\n\nstatic struct waitq texteditor_inited_wq;\nstatic char texteditor_inited;\nstatic int curuid;\n\nstatic void emboxQtShowLoginForm();\n\nclass EmboxRootWindow : public QMainWindow\n{\n Q_OBJECT\n\n public:\n\n\tQAction *closeAllEditorsAction;\n\tEmboxRootWindow() {\n\tfileMenu = new QMenu(QString(\"&Пуск\"), this);\n\tmenuBar()->addMenu(fileMenu);\n\n\t__qt_menu = fileMenu;\n\n\ttextEditorAction = new QAction(QString(\"&Текстовый редактор\"), this);\n\tfileMenu->addAction(textEditorAction);\n\tconnect(textEditorAction, SIGNAL(triggered()), this, SLOT(textEditorRun()));\n\n\tcloseAllEditorsAction = new QAction(QString(\"&Закрыть все окна\"), this);\n\tfileMenu->addAction(closeAllEditorsAction);\n\tconnect(closeAllEditorsAction, SIGNAL(triggered()), this, SLOT(closeAllEditors()));\n\n\tlogoutAction = new QAction(QString(\"&Завершение сеанса\"), this);\n\tfileMenu->addAction(logoutAction);\n\tconnect(logoutAction, SIGNAL(triggered()), this, SLOT(logout()));\n\n\tsaveAction = new QAction(QString(\"&Сохранить конфигурацию\"), this);\n\tfileMenu->addAction(saveAction);\n\tconnect(saveAction, SIGNAL(triggered()), this, SLOT(savedefault()));\n\n\twallpaperAction = new QAction(QString(\"&Графические настройки\"), this);\n\tfileMenu->addAction(wallpaperAction);\n\tconnect(wallpaperAction, SIGNAL(triggered()), this, SLOT(wallpaper()));\n }\n\n private slots:\n\tvoid textEditorRun() {\n\t\tTextEditor *textEditor = new TextEditor(emarea);\n\t\ttextEditor->show();\n\t}\n\n\tvoid closeAllEditors() {\n\t\tTextEditor::closeAllEditors();\n\t}\n\n\tvoid logout() {\n\t\temboxQtHideDesktop();\n\t\temboxQtShowLoginForm();\n\t}\n\n\tvoid wallpaper() {\n\t\twallpaperDialog = new DesktopImageDialog(desktopImagesList);\n\t\twallpaperDialog->show();\n\t}\n\n\tvoid savedefault() {\n\n\t}\n\n private:\n\tQAction *logoutAction;\n\tQAction *textEditorAction;\n\tQAction *wallpaperAction;\n\tQAction *saveAction;\n\tQMenu *fileMenu;\n};\n\nstatic EmboxRootWindow *emroot;\n\nstatic char *parse(char **buf) {\n\tchar *ret = *buf;\n\tchar *ch;\n\n\tif ((ch = strchr(*buf, SEP))) {\n\t\t*ch++ = '\\0';\n\t}\n\n\t*buf = ch;\n\n\treturn ret;\n}\n\nvoid emboxQtSetfont(const QString &fontFamily, int fontPt) {\n\tQFont serifFont(fontFamily, fontPt);\n\t__qt_app->setFont(serifFont);\n\t__qt_menu->setFont(serifFont);\n}\n\nstatic void load_pref(void) {\n\tint fd, ret;\n\tchar cbuf[FSIZE];\n\tconst char *wall = \"default.png\";\n\tconst char *font = \"Times\";\n\tint font_pt = 10;\n\n\tsnprintf(cbuf, FSIZE, \"\/mnt\/pref_%d\", curuid);\n\tfd = open(cbuf, O_RDONLY, 0755);\n\n\tif (fd == -1)\n\t\tgoto set_default;\n\n\tlseek(fd, 0, 0);\n\tif (0 < (ret = read(fd, cbuf, FSIZE))) {\n\t\tchar *buf = cbuf;\n\n\t\tbuf[ret] = '\\0';\n\n\t\twall = parse(&buf);\n\t\tfont = parse(&buf);\n\t\tfont_pt = atoi(parse(&buf));\n\t}\n\tclose(fd);\n\nset_default:\n\tQString imagePath = QString(\":\/images\/\").append(QString(wall));\n\temarea->setBackgroundPath(imagePath);\n\n\temboxQtSetfont(font, font_pt);\n\n}\n\nvoid emboxQtSavePref(char *wall, char *font, int font_pt) {\n\tint fd, len;\n\tchar cbuf[FSIZE];\n\n\tsnprintf(cbuf, FSIZE, \"\/mnt\/pref_%d\", curuid);\n\n\tfd = creat(cbuf, 0755);\n\n\tlen = snprintf(cbuf, FSIZE, \"%s:%s:%d\", wall, font, font_pt);\n\n\twrite(fd, cbuf, len);\n\n\tftruncate(fd, len);\n\n\tclose(fd);\n}\n\nvoid emboxQtShowDesktop(uid_t uid) {\n\tint fd = -1;\n\tbool enabled = uid ? false : true;\n\n\tcuruid = uid;\n\temroot->menuBar()->show();\n\temroot->closeAllEditorsAction->setEnabled(enabled);\n\n\tload_pref();\n}\n\nvoid emboxQtHideDesktop() {\n\temarea->closeAllSubWindows();\n\temroot->menuBar()->hide();\n}\n\nvoid emboxRootWindowShow(int width, int height) {\n\temroot->setGeometry(QRect(0,0, width, height));\n\ttexteditor_inited = 1;\n\twaitq_wakeup_all(&texteditor_inited_wq);\n}\n\nstatic void emboxQtShowLoginForm() {\n\tLoginDialog *loginDialog = new LoginDialog(0, emarea);\n\tloginDialog->show();\n\n\temarea->setBackgroundPath(defaultImagePath);\n}\n\nint main(int argv, char **args)\n{\n\t\/\/Q_INIT_RESOURCE(texteditor);\n\n\twaitq_init(&texteditor_inited_wq);\n\n\tQApplication app(argv, args);\n\n\t__qt_app = &app;\n\n\tQFont serifFont(\"Times\", 10);\n\tapp.setFont(serifFont);\n\tqDebug() << \"Supported formats:\" << QImageReader::supportedImageFormats();\n\tdesktopImagesList << \"cats.jpg\" << \"default.png\";\n\n\tQTextCodec::setCodecForCStrings(QTextCodec::codecForName(\"UTF-8\"));\n\tQTextCodec::setCodecForLocale(QTextCodec::codecForName(\"UTF-8\"));\n\tQTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n\n\temroot = new EmboxRootWindow();\n\temarea = new QMdiAreaWBackground(defaultImagePath);\n\n\temroot->setCentralWidget(emarea);\n\n\tif (DEFAULT_WIDTH == 0 || DEFAULT_HEIGHT == 0) {\n\t\tWAITQ_WAIT(&texteditor_inited_wq, texteditor_inited); \/* EMBOXVC plugin*\/\n\t} else {\n\t\temroot->setGeometry(QRect(0,0, DEFAULT_WIDTH, DEFAULT_HEIGHT)); \/* VNC plugin *\/\n\t}\n\n\temroot->show();\n\n\temboxQtHideDesktop();\n\n\temboxQtShowLoginForm();\n\n\treturn app.exec();\n}\n\n#include \"main.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"mutation_partition.hh\"\n#include \"streamed_mutation.hh\"\n#include \"utils\/anchorless_list.hh\"\n#include \"utils\/logalloc.hh\"\n\n\/\/ This is MVCC implementation for mutation_partitions.\n\/\/\n\/\/ It is assumed that mutation_partitions are stored in some sort of LSA-managed\n\/\/ container (memtable or row cache).\n\/\/\n\/\/ partition_entry - the main handle to the mutation_partition, allows writes\n\/\/ and reads.\n\/\/ partition_version - mutation_partition inside a list of partition versions.\n\/\/ mutation_partition represents just a difference against\n\/\/ the next one in the list. To get a single\n\/\/ mutation_partition fully representing this version one\n\/\/ needs to merge this one and all its successors in the\n\/\/ list.\n\/\/ partition_snapshot - a handle to some particular partition_version. It allows\n\/\/ only reads and itself is immutable the partition version\n\/\/ it represents won't be modified as long as the snapshot\n\/\/ is alive.\n\/\/\n\/\/ pe - partition_entry\n\/\/ pv - partition_version\n\/\/ ps - partition_snapshot\n\/\/ ps(u) - partition_snapshot marked as unique owner\n\n\/\/ Scene I. Write-only loads\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ pe\n\/\/ In case of write-only loads all incoming mutations are directly applied\n\/\/ to the partition_version that partition_entry is pointing to. The list\n\/\/ of partition_versions contains only a single element.\n\/\/\n\/\/ Scene II. Read-only loads\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ pe <- ps\n\/\/ In case of read-only scenarios there is only a single partition_snapshot\n\/\/ object that points to the partition_entry. There is only a single\n\/\/ partition_version.\n\/\/\n\/\/ Scene III. Writes and reads\n\/\/ pv -- pv -- pv\n\/\/ ^ ^ ^\n\/\/ | | |\n\/\/ pe ps ps\n\/\/ If the partition_entry that needs to be modified is currently read from (i.e.\n\/\/ there exist a partition_snapshot pointing to it) instead of applying new\n\/\/ mutation directly a new partition version is created and added at the front\n\/\/ of the list. partition_entry points to the new version (so that it has the\n\/\/ most recent view of stored data) while the partition_snapshot points to the\n\/\/ same partition_version it pointed to before (so that the data it sees doesn't\n\/\/ change).\n\/\/ As a result the list may contain multiple partition versions used by\n\/\/ different partition snapshots.\n\/\/ When the partition_snapshot is destroyed partition_versions are squashed\n\/\/ together to minimize the amount of elements on the list.\n\/\/\n\/\/ Scene IV. Schema upgrade\n\/\/ pv pv --- pv\n\/\/ ^ ^ ^\n\/\/ | | |\n\/\/ pe ps(u) ps\n\/\/ When there is a schema upgrade the list of partition versions pointed to\n\/\/ by partition_entry is replaced by a new single partition_version that is a\n\/\/ result of squashing and upgrading the old versions.\n\/\/ Old versions not used by any partition snapshot are removed. The first\n\/\/ partition snapshot on the list is marked as unique which means that upon\n\/\/ its destruction it won't attempt to squash versions but instead remove\n\/\/ the unused ones and pass the \"unique owner\" mark the next snapshot on the\n\/\/ list (if there is any).\n\/\/\n\/\/ Scene V. partition_entry eviction\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ ps(u)\n\/\/ When partition_entry is removed (e.g. because it was evicted from cache)\n\/\/ the partition versions are removed in a similar manner than in the schema\n\/\/ upgrade scenario. The unused ones are destroyed right away and the first\n\/\/ snapshot on the list is marked as unique owner so that on its destruction\n\/\/ it continues removal of the partition versions.\n\nclass partition_version_ref;\n\nclass partition_version : public anchorless_list_base_hook<partition_version> {\n partition_version_ref* _backref = nullptr;\n mutation_partition _partition;\n\n friend class partition_version_ref;\npublic:\n explicit partition_version(schema_ptr s) noexcept\n : _partition(std::move(s)) { }\n explicit partition_version(mutation_partition mp) noexcept\n : _partition(std::move(mp)) { }\n partition_version(partition_version&& pv) noexcept;\n partition_version& operator=(partition_version&& pv) noexcept;\n ~partition_version();\n\n mutation_partition& partition() { return _partition; }\n const mutation_partition& partition() const { return _partition; }\n\n bool is_referenced() const { return _backref; }\n partition_version_ref& back_reference() { return *_backref; }\n};\n\nclass partition_version_ref {\n partition_version* _version = nullptr;\n bool _unique_owner = false;\n\n friend class partition_version;\npublic:\n partition_version_ref() = default;\n explicit partition_version_ref(partition_version& pv) noexcept : _version(&pv) {\n assert(!_version->_backref);\n _version->_backref = this;\n }\n ~partition_version_ref() {\n if (_version) {\n _version->_backref = nullptr;\n }\n }\n partition_version_ref(partition_version_ref&& other) noexcept : _version(other._version) {\n if (_version) {\n _version->_backref = this;\n }\n other._version = nullptr;\n }\n partition_version_ref& operator=(partition_version_ref&& other) noexcept {\n if (this != &other) {\n this->~partition_version_ref();\n new (this) partition_version_ref(std::move(other));\n }\n return *this;\n }\n\n explicit operator bool() const { return _version; }\n\n partition_version& operator*() {\n assert(_version);\n return *_version;\n }\n partition_version* operator->() {\n assert(_version);\n return _version;\n }\n const partition_version* operator->() const {\n assert(_version);\n return _version;\n }\n\n bool is_unique_owner() const { return _unique_owner; }\n void mark_as_unique_owner() { _unique_owner = true; }\n};\n\nclass partition_entry;\n\nclass partition_snapshot : public enable_lw_shared_from_this<partition_snapshot> {\npublic:\n \/\/ Only snapshots created with the same value of phase can point to the same version.\n using phase_type = uint64_t;\n static constexpr phase_type default_phase = 0;\n static constexpr phase_type max_phase = std::numeric_limits<phase_type>::max();\nprivate:\n schema_ptr _schema;\n \/\/ Either _version or _entry is non-null.\n partition_version_ref _version;\n partition_entry* _entry;\n phase_type _phase;\n\n friend class partition_entry;\npublic:\n explicit partition_snapshot(schema_ptr s,\n partition_entry* entry,\n phase_type phase = default_phase)\n : _schema(std::move(s)), _entry(entry), _phase(phase) { }\n partition_snapshot(const partition_snapshot&) = delete;\n partition_snapshot(partition_snapshot&&) = delete;\n partition_snapshot& operator=(const partition_snapshot&) = delete;\n partition_snapshot& operator=(partition_snapshot&&) = delete;\n\n \/\/ If possible merges the version pointed to by this snapshot with\n \/\/ adjacent partition versions. Leaves the snapshot in an unspecified state.\n \/\/ Can be retried if previous merge attempt has failed.\n void merge_partition_versions();\n\n ~partition_snapshot();\n\n partition_version_ref& version();\n\n const partition_version_ref& version() const;\n\n auto versions() {\n return version()->elements_from_this();\n }\n\n unsigned version_count();\n tombstone partition_tombstone() const;\n row static_row() const;\n mutation_partition squashed() const;\n \/\/ Returns range tombstones overlapping with [start, end)\n std::vector<range_tombstone> range_tombstones(const schema& s, position_in_partition_view start, position_in_partition_view end);\n};\n\nclass partition_entry {\n partition_snapshot* _snapshot = nullptr;\n partition_version_ref _version;\n\n friend class partition_snapshot;\n friend class cache_entry;\nprivate:\n void set_version(partition_version*);\n\n void apply(const schema& s, partition_version* pv, const schema& pv_schema);\npublic:\n partition_entry() = default;\n explicit partition_entry(mutation_partition mp);\n ~partition_entry();\n\n partition_entry(partition_entry&& pe) noexcept\n : _snapshot(pe._snapshot), _version(std::move(pe._version))\n {\n if (_snapshot) {\n _snapshot->_entry = this;\n }\n pe._snapshot = nullptr;\n }\n partition_entry& operator=(partition_entry&& other) noexcept {\n if (this != &other) {\n this->~partition_entry();\n new (this) partition_entry(std::move(other));\n }\n return *this;\n }\n\n partition_version_ref& version() {\n return _version;\n }\n\n \/\/ Strong exception guarantees.\n \/\/ Assumes this instance and mp are fully continuous.\n void apply(const schema& s, const mutation_partition& mp, const schema& mp_schema);\n\n \/\/ Same exception guarantees as:\n \/\/ mutation_partition::apply(const schema&, mutation_partition&&, const schema&)\n void apply(const schema& s, mutation_partition&& mp, const schema& mp_schema);\n\n \/\/ Strong exception guarantees.\n \/\/ Assumes this instance and mpv are fully continuous.\n void apply(const schema& s, mutation_partition_view mpv, const schema& mp_schema);\n\n \/\/ Weak exception guarantees.\n \/\/ If an exception is thrown this and pe will be left in some valid states\n \/\/ such that if the operation is retried (possibly many times) and eventually\n \/\/ succeeds the result will be as if the first attempt didn't fail.\n void apply(const schema& s, partition_entry&& pe, const schema& pe_schema);\n\n \/\/ Ensures that the latest version can be populated with data from given phase\n \/\/ by inserting a new version if necessary.\n \/\/ Doesn't affect value or continuity of the partition.\n \/\/ Returns a reference to the new latest version.\n partition_version& open_version(const schema& s, partition_snapshot::phase_type phase = partition_snapshot::max_phase) {\n if (_snapshot && _snapshot->_phase != phase) {\n auto new_version = current_allocator().construct<partition_version>(mutation_partition(s.shared_from_this()));\n new_version->partition().set_static_row_continuous(_version->partition().static_row_continuous());\n new_version->insert_before(*_version);\n set_version(new_version);\n return *new_version;\n }\n return *_version;\n }\n\n mutation_partition squashed(schema_ptr from, schema_ptr to);\n mutation_partition squashed(const schema&);\n\n \/\/ needs to be called with reclaiming disabled\n void upgrade(schema_ptr from, schema_ptr to);\n\n \/\/ Snapshots with different values of phase will point to different partition_version objects.\n lw_shared_ptr<partition_snapshot> read(schema_ptr entry_schema,\n partition_snapshot::phase_type phase = partition_snapshot::default_phase);\n};\n\ninline partition_version_ref& partition_snapshot::version()\n{\n if (_version) {\n return _version;\n } else {\n return _entry->_version;\n }\n}\n\ninline const partition_version_ref& partition_snapshot::version() const\n{\n if (_version) {\n return _version;\n } else {\n return _entry->_version;\n }\n}\n<commit_msg>partition_version: Make return type of versions() explicit<commit_after>\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"mutation_partition.hh\"\n#include \"streamed_mutation.hh\"\n#include \"utils\/anchorless_list.hh\"\n#include \"utils\/logalloc.hh\"\n\n\/\/ This is MVCC implementation for mutation_partitions.\n\/\/\n\/\/ It is assumed that mutation_partitions are stored in some sort of LSA-managed\n\/\/ container (memtable or row cache).\n\/\/\n\/\/ partition_entry - the main handle to the mutation_partition, allows writes\n\/\/ and reads.\n\/\/ partition_version - mutation_partition inside a list of partition versions.\n\/\/ mutation_partition represents just a difference against\n\/\/ the next one in the list. To get a single\n\/\/ mutation_partition fully representing this version one\n\/\/ needs to merge this one and all its successors in the\n\/\/ list.\n\/\/ partition_snapshot - a handle to some particular partition_version. It allows\n\/\/ only reads and itself is immutable the partition version\n\/\/ it represents won't be modified as long as the snapshot\n\/\/ is alive.\n\/\/\n\/\/ pe - partition_entry\n\/\/ pv - partition_version\n\/\/ ps - partition_snapshot\n\/\/ ps(u) - partition_snapshot marked as unique owner\n\n\/\/ Scene I. Write-only loads\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ pe\n\/\/ In case of write-only loads all incoming mutations are directly applied\n\/\/ to the partition_version that partition_entry is pointing to. The list\n\/\/ of partition_versions contains only a single element.\n\/\/\n\/\/ Scene II. Read-only loads\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ pe <- ps\n\/\/ In case of read-only scenarios there is only a single partition_snapshot\n\/\/ object that points to the partition_entry. There is only a single\n\/\/ partition_version.\n\/\/\n\/\/ Scene III. Writes and reads\n\/\/ pv -- pv -- pv\n\/\/ ^ ^ ^\n\/\/ | | |\n\/\/ pe ps ps\n\/\/ If the partition_entry that needs to be modified is currently read from (i.e.\n\/\/ there exist a partition_snapshot pointing to it) instead of applying new\n\/\/ mutation directly a new partition version is created and added at the front\n\/\/ of the list. partition_entry points to the new version (so that it has the\n\/\/ most recent view of stored data) while the partition_snapshot points to the\n\/\/ same partition_version it pointed to before (so that the data it sees doesn't\n\/\/ change).\n\/\/ As a result the list may contain multiple partition versions used by\n\/\/ different partition snapshots.\n\/\/ When the partition_snapshot is destroyed partition_versions are squashed\n\/\/ together to minimize the amount of elements on the list.\n\/\/\n\/\/ Scene IV. Schema upgrade\n\/\/ pv pv --- pv\n\/\/ ^ ^ ^\n\/\/ | | |\n\/\/ pe ps(u) ps\n\/\/ When there is a schema upgrade the list of partition versions pointed to\n\/\/ by partition_entry is replaced by a new single partition_version that is a\n\/\/ result of squashing and upgrading the old versions.\n\/\/ Old versions not used by any partition snapshot are removed. The first\n\/\/ partition snapshot on the list is marked as unique which means that upon\n\/\/ its destruction it won't attempt to squash versions but instead remove\n\/\/ the unused ones and pass the \"unique owner\" mark the next snapshot on the\n\/\/ list (if there is any).\n\/\/\n\/\/ Scene V. partition_entry eviction\n\/\/ pv\n\/\/ ^\n\/\/ |\n\/\/ ps(u)\n\/\/ When partition_entry is removed (e.g. because it was evicted from cache)\n\/\/ the partition versions are removed in a similar manner than in the schema\n\/\/ upgrade scenario. The unused ones are destroyed right away and the first\n\/\/ snapshot on the list is marked as unique owner so that on its destruction\n\/\/ it continues removal of the partition versions.\n\nclass partition_version_ref;\n\nclass partition_version : public anchorless_list_base_hook<partition_version> {\n partition_version_ref* _backref = nullptr;\n mutation_partition _partition;\n\n friend class partition_version_ref;\npublic:\n explicit partition_version(schema_ptr s) noexcept\n : _partition(std::move(s)) { }\n explicit partition_version(mutation_partition mp) noexcept\n : _partition(std::move(mp)) { }\n partition_version(partition_version&& pv) noexcept;\n partition_version& operator=(partition_version&& pv) noexcept;\n ~partition_version();\n\n mutation_partition& partition() { return _partition; }\n const mutation_partition& partition() const { return _partition; }\n\n bool is_referenced() const { return _backref; }\n partition_version_ref& back_reference() { return *_backref; }\n};\n\nusing partition_version_range = anchorless_list_base_hook<partition_version>::range;\n\nclass partition_version_ref {\n partition_version* _version = nullptr;\n bool _unique_owner = false;\n\n friend class partition_version;\npublic:\n partition_version_ref() = default;\n explicit partition_version_ref(partition_version& pv) noexcept : _version(&pv) {\n assert(!_version->_backref);\n _version->_backref = this;\n }\n ~partition_version_ref() {\n if (_version) {\n _version->_backref = nullptr;\n }\n }\n partition_version_ref(partition_version_ref&& other) noexcept : _version(other._version) {\n if (_version) {\n _version->_backref = this;\n }\n other._version = nullptr;\n }\n partition_version_ref& operator=(partition_version_ref&& other) noexcept {\n if (this != &other) {\n this->~partition_version_ref();\n new (this) partition_version_ref(std::move(other));\n }\n return *this;\n }\n\n explicit operator bool() const { return _version; }\n\n partition_version& operator*() {\n assert(_version);\n return *_version;\n }\n partition_version* operator->() {\n assert(_version);\n return _version;\n }\n const partition_version* operator->() const {\n assert(_version);\n return _version;\n }\n\n bool is_unique_owner() const { return _unique_owner; }\n void mark_as_unique_owner() { _unique_owner = true; }\n};\n\nclass partition_entry;\n\nclass partition_snapshot : public enable_lw_shared_from_this<partition_snapshot> {\npublic:\n \/\/ Only snapshots created with the same value of phase can point to the same version.\n using phase_type = uint64_t;\n static constexpr phase_type default_phase = 0;\n static constexpr phase_type max_phase = std::numeric_limits<phase_type>::max();\nprivate:\n schema_ptr _schema;\n \/\/ Either _version or _entry is non-null.\n partition_version_ref _version;\n partition_entry* _entry;\n phase_type _phase;\n\n friend class partition_entry;\npublic:\n explicit partition_snapshot(schema_ptr s,\n partition_entry* entry,\n phase_type phase = default_phase)\n : _schema(std::move(s)), _entry(entry), _phase(phase) { }\n partition_snapshot(const partition_snapshot&) = delete;\n partition_snapshot(partition_snapshot&&) = delete;\n partition_snapshot& operator=(const partition_snapshot&) = delete;\n partition_snapshot& operator=(partition_snapshot&&) = delete;\n\n \/\/ If possible merges the version pointed to by this snapshot with\n \/\/ adjacent partition versions. Leaves the snapshot in an unspecified state.\n \/\/ Can be retried if previous merge attempt has failed.\n void merge_partition_versions();\n\n ~partition_snapshot();\n\n partition_version_ref& version();\n\n const partition_version_ref& version() const;\n\n partition_version_range versions() {\n return version()->elements_from_this();\n }\n\n unsigned version_count();\n tombstone partition_tombstone() const;\n row static_row() const;\n mutation_partition squashed() const;\n \/\/ Returns range tombstones overlapping with [start, end)\n std::vector<range_tombstone> range_tombstones(const schema& s, position_in_partition_view start, position_in_partition_view end);\n};\n\nclass partition_entry {\n partition_snapshot* _snapshot = nullptr;\n partition_version_ref _version;\n\n friend class partition_snapshot;\n friend class cache_entry;\nprivate:\n void set_version(partition_version*);\n\n void apply(const schema& s, partition_version* pv, const schema& pv_schema);\npublic:\n partition_entry() = default;\n explicit partition_entry(mutation_partition mp);\n ~partition_entry();\n\n partition_entry(partition_entry&& pe) noexcept\n : _snapshot(pe._snapshot), _version(std::move(pe._version))\n {\n if (_snapshot) {\n _snapshot->_entry = this;\n }\n pe._snapshot = nullptr;\n }\n partition_entry& operator=(partition_entry&& other) noexcept {\n if (this != &other) {\n this->~partition_entry();\n new (this) partition_entry(std::move(other));\n }\n return *this;\n }\n\n partition_version_ref& version() {\n return _version;\n }\n\n \/\/ Strong exception guarantees.\n \/\/ Assumes this instance and mp are fully continuous.\n void apply(const schema& s, const mutation_partition& mp, const schema& mp_schema);\n\n \/\/ Same exception guarantees as:\n \/\/ mutation_partition::apply(const schema&, mutation_partition&&, const schema&)\n void apply(const schema& s, mutation_partition&& mp, const schema& mp_schema);\n\n \/\/ Strong exception guarantees.\n \/\/ Assumes this instance and mpv are fully continuous.\n void apply(const schema& s, mutation_partition_view mpv, const schema& mp_schema);\n\n \/\/ Weak exception guarantees.\n \/\/ If an exception is thrown this and pe will be left in some valid states\n \/\/ such that if the operation is retried (possibly many times) and eventually\n \/\/ succeeds the result will be as if the first attempt didn't fail.\n void apply(const schema& s, partition_entry&& pe, const schema& pe_schema);\n\n \/\/ Ensures that the latest version can be populated with data from given phase\n \/\/ by inserting a new version if necessary.\n \/\/ Doesn't affect value or continuity of the partition.\n \/\/ Returns a reference to the new latest version.\n partition_version& open_version(const schema& s, partition_snapshot::phase_type phase = partition_snapshot::max_phase) {\n if (_snapshot && _snapshot->_phase != phase) {\n auto new_version = current_allocator().construct<partition_version>(mutation_partition(s.shared_from_this()));\n new_version->partition().set_static_row_continuous(_version->partition().static_row_continuous());\n new_version->insert_before(*_version);\n set_version(new_version);\n return *new_version;\n }\n return *_version;\n }\n\n mutation_partition squashed(schema_ptr from, schema_ptr to);\n mutation_partition squashed(const schema&);\n\n \/\/ needs to be called with reclaiming disabled\n void upgrade(schema_ptr from, schema_ptr to);\n\n \/\/ Snapshots with different values of phase will point to different partition_version objects.\n lw_shared_ptr<partition_snapshot> read(schema_ptr entry_schema,\n partition_snapshot::phase_type phase = partition_snapshot::default_phase);\n};\n\ninline partition_version_ref& partition_snapshot::version()\n{\n if (_version) {\n return _version;\n } else {\n return _entry->_version;\n }\n}\n\ninline const partition_version_ref& partition_snapshot::version() const\n{\n if (_version) {\n return _version;\n } else {\n return _entry->_version;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"periodic.h\"\n#include \"Element.h\"\n#include <sifteo.h>\n\n\/\/ Default constructor will not create a valid element, it must be initialized before use using GetRawElement\nElement::Element()\n{\n}\n\nElement::Element(const char* name, const char* symbol, const char* group, short atomicNumber, double elementWeight, int numOuterElectrons, double electroNegativity)\n{\n this->baseElement = NULL;\n this->name = name;\n this->symbol = symbol;\n\tthis->group = group;\n this->atomicNumber = atomicNumber;\n this->elementWeight = elementWeight;\n this->numOuterElectrons = numOuterElectrons;\n\tthis->electroNegativity = electroNegativity;\n}\n\nElement::Element(Element* baseElement)\n{\n Assert(baseElement != NULL);\n this->baseElement = baseElement;\n ResetToBasicState();\n}\n\nvoid Element::ResetToBasicState()\n{\n this->name = baseElement->name;\n this->symbol = baseElement->symbol;\n this->atomicNumber = baseElement->atomicNumber;\n this->elementWeight = baseElement->elementWeight;\n this->numOuterElectrons = baseElement->numOuterElectrons;\n}\n\nconst char* Element::GetName() { return name; }\nconst char* Element::GetSymbol() { return symbol; }\nconst char* Element::GetGroup() { return group; }\nshort Element::GetAtomicNumber() { return atomicNumber; }\ndouble Element::GetElementWeight() { return elementWeight; }\nint Element::GetNumOuterElectrons() { return numOuterElectrons; }\ndouble Element::GetElectroNegativity() { return electroNegativity; }\n\nbool Element::IsRawElement()\n{\n return baseElement == NULL;\n}\n\nint Element::GetCharge()\n{\n if (IsRawElement())\n { return 0; }\n\n return baseElement->numOuterElectrons - this->numOuterElectrons;\n}\n\nbool Element::ReactWith(Element* other)\n{\n \/\/TODO: This method needs to become more complicated to where it stores state about what elements it is interacting with.\n \/\/LOG(\"My electrons: %d, Other electrons: %d\\n\", this->numOuterElectrons, other->numOuterElectrons);\n\n\t\/\/if any element is a noble gas, a bond won't occur.\n\tif (strcmp(this->group, \"noble\") != 0 ||\n\t\tstrcmp(other->group, \"noble\") != 0)\n\t\treturn false;\n\t\/\/if both elements are alkali metals, no bonding will occur\n\telse if (strcmp(this->group, \"alkali\") == 0 &&\n\t\tstrcmp(other->group, \"alkali\") == 0)\n\t\treturn false;\n\t\/\/if both elements are halogens, covalent bonding will occur\n\telse if (strcmp(this->group, \"halogen\") == 0 &&\n\t\tstrcmp(other->group, \"halogen\") == 0)\n\t\treturn true;\n\t\/\/hydrogen will bond with any halogen and form a covalent bond\n\telse if (strcmp(this->name, \"Hydrogen\") == 0 &&\n\t\tstrcmp(other->group, \"halogen\") == 0)\n\t\treturn true;\n\t\/\/The difference in electronegativity is 1.68, which is very near to 1.7\n\t\/\/This is an Ionic bond but a special case in which the difference isn't >= 1.7\n\t\/\/which is why we have a hard coded case (possible to clean up in the future?)\n\telse if (strcmp(this->name, \"Lithium\") == 0 &&\n\t\tstrcmp(other->name, \"Iodine\") == 0)\n\t\treturn true;\n\n\t\/\/find the greater negativity\n\tdouble maxNegativity = this->electroNegativity > other->electroNegativity ? this->electroNegativity : other->electroNegativity;\n\tdouble minNegativity = this->electroNegativity < other->electroNegativity ? this->electroNegativity : other->electroNegativity;\n\n\t\/\/Ionic\n\tif (maxNegativity - minNegativity > 1.7 &&\n\t\tthis->numOuterElectrons + other->numOuterElectrons == 8)\n\t{\n\t\tif (this->numOuterElectrons < other->numOuterElectrons)\n\t\t{\n\t\t\tint electronsDonated = 8 - other->numOuterElectrons;\n\t\t\tthis->numOuterElectrons -= electronsDonated;\n\t\t\tother->numOuterElectrons += electronsDonated;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint electronsDonated = 8 - this->numOuterElectrons;\n\t\t\tother->numOuterElectrons -= electronsDonated;\n\t\t\tthis->numOuterElectrons += electronsDonated;\n\t\t}\n\t\treturn true;\n\t}\n\t\t\n\t\/\/covalent\n\telse if (maxNegativity - minNegativity <= 1.7)\n\t\treturn true;\n\n\treturn false;\n}\n\nstatic Element rawElements[] =\n{\n \/\/Alkali Metals\n\tElement(\"Hydrogen\", \"H\", \"nonmetal\", 1, 1.008, 1, 2.20),\n Element(\"Lithium\", \"Li\", \"alkali\", 3, 6.94, 1, 0.98),\n\tElement(\"Sodium\", \"Na\", \"alkali\", 11, 22.9898, 1, 0.93),\n\tElement(\"Potassium\", \"K\", \"alkali\", 19, 39.0938, 1, 0.82),\n\tElement(\"Rubidium\", \"Rb\", \"alkali\", 37, 85.4678, 1, 0.82),\n\tElement(\"Cesium\", \"Cs\", \"alkali\", 55, 132.90545196, 1, 0.79), \/\/don't remember if we need this one or not\n \n \/\/Halogens\n Element(\"Flourine\", \"F\", \"halogen\", 9, 18.998403163, 7, 3.98),\n\tElement(\"Chlorine\", \"Cl\", \"halogen\", 17, 35.45, 7, 3.16),\n\tElement(\"Bromine\", \"Br\", \"halogen\", 35, 79.094, 7, 2.96),\n\tElement(\"Iodine\", \"I\", \"halogen\", 53, 126.90447, 7, 2.66),\n \n \/\/Noble Gases\n Element(\"Helium\", \"He\", \"noble\", 2, 4.002602, 2, 0),\n\tElement(\"Neon\", \"Ne\", \"noble\", 10, 20.1797, 8, 0),\n\tElement(\"Argon\", \"Ar\", \"noble\", 18, 39.948, 8, 0),\n\tElement(\"Krypton\", \"Kr\", \"noble\", 36, 83.798, 8, 0),\n};\n\nvoid Element::GetRawElement(int num, Element* elementOut)\n{\n Assert(num >= 0 && num < GetRawElementCount());\n *elementOut = Element(&rawElements[num]);\n}\n\nbool Element::GetRawElement(const char* name, Element* elementOut)\n{\n int num = GetRawElementNum(name);\n\n if (num < 0)\n {\n *elementOut = Element(\"INVALID\", \"INV\", \"INV\", 0, 0.0, 0, 0.0);\n return false;\n }\n else\n {\n *elementOut = Element(&rawElements[num]);\n return true;\n }\n}\n\nint Element::GetRawElementNum(const char* name)\n{\n for (int i = 0; i < GetRawElementCount(); i++)\n {\n if (strcmp(name, rawElements[i].GetSymbol()) == 0)\n {\n return i;\n }\n }\n\n return -1;\n}\n\nint Element::GetRawElementCount()\n{\n return CountOfArray(rawElements);\n}\n<commit_msg>Added alkali earth metals<commit_after>#include \"periodic.h\"\n#include \"Element.h\"\n#include <sifteo.h>\n\n\/\/ Default constructor will not create a valid element, it must be initialized before use using GetRawElement\nElement::Element()\n{\n}\n\nElement::Element(const char* name, const char* symbol, const char* group, short atomicNumber, double elementWeight, int numOuterElectrons, double electroNegativity)\n{\n this->baseElement = NULL;\n this->name = name;\n this->symbol = symbol;\n\tthis->group = group;\n this->atomicNumber = atomicNumber;\n this->elementWeight = elementWeight;\n this->numOuterElectrons = numOuterElectrons;\n\tthis->electroNegativity = electroNegativity;\n}\n\nElement::Element(Element* baseElement)\n{\n Assert(baseElement != NULL);\n this->baseElement = baseElement;\n ResetToBasicState();\n}\n\nvoid Element::ResetToBasicState()\n{\n this->name = baseElement->name;\n this->symbol = baseElement->symbol;\n this->atomicNumber = baseElement->atomicNumber;\n this->elementWeight = baseElement->elementWeight;\n this->numOuterElectrons = baseElement->numOuterElectrons;\n}\n\nconst char* Element::GetName() { return name; }\nconst char* Element::GetSymbol() { return symbol; }\nconst char* Element::GetGroup() { return group; }\nshort Element::GetAtomicNumber() { return atomicNumber; }\ndouble Element::GetElementWeight() { return elementWeight; }\nint Element::GetNumOuterElectrons() { return numOuterElectrons; }\ndouble Element::GetElectroNegativity() { return electroNegativity; }\n\nbool Element::IsRawElement()\n{\n return baseElement == NULL;\n}\n\nint Element::GetCharge()\n{\n if (IsRawElement())\n { return 0; }\n\n return baseElement->numOuterElectrons - this->numOuterElectrons;\n}\n\nbool Element::ReactWith(Element* other)\n{\n \/\/TODO: This method needs to become more complicated to where it stores state about what elements it is interacting with.\n \/\/LOG(\"My electrons: %d, Other electrons: %d\\n\", this->numOuterElectrons, other->numOuterElectrons);\n\n\t\/\/if any element is a noble gas, a bond won't occur.\n\tif (strcmp(this->group, \"noble\") != 0 ||\n\t\tstrcmp(other->group, \"noble\") != 0)\n\t\treturn false;\n\t\/\/if both elements are alkali metals, no bonding will occur\n\telse if (strcmp(this->group, \"alkali\") == 0 &&\n\t\tstrcmp(other->group, \"alkali\") == 0)\n\t\treturn false;\n\t\/\/if both elements are halogens, covalent bonding will occur\n\telse if (strcmp(this->group, \"halogen\") == 0 &&\n\t\tstrcmp(other->group, \"halogen\") == 0)\n\t\treturn true;\n\t\/\/hydrogen will bond with any halogen and form a covalent bond\n\telse if (strcmp(this->name, \"Hydrogen\") == 0 &&\n\t\tstrcmp(other->group, \"halogen\") == 0)\n\t\treturn true;\n\t\/\/The difference in electronegativity is 1.68, which is very near to 1.7\n\t\/\/This is an Ionic bond but a special case in which the difference isn't >= 1.7\n\t\/\/which is why we have a hard coded case (possible to clean up in the future?)\n\telse if (strcmp(this->name, \"Lithium\") == 0 &&\n\t\tstrcmp(other->name, \"Iodine\") == 0)\n\t\treturn true;\n\n\t\/\/find the greater negativity\n\tdouble maxNegativity = this->electroNegativity > other->electroNegativity ? this->electroNegativity : other->electroNegativity;\n\tdouble minNegativity = this->electroNegativity < other->electroNegativity ? this->electroNegativity : other->electroNegativity;\n\n\t\/\/Ionic\n\tif (maxNegativity - minNegativity > 1.7 &&\n\t\tthis->numOuterElectrons + other->numOuterElectrons == 8)\n\t{\n\t\tif (this->numOuterElectrons < other->numOuterElectrons)\n\t\t{\n\t\t\tint electronsDonated = 8 - other->numOuterElectrons;\n\t\t\tthis->numOuterElectrons -= electronsDonated;\n\t\t\tother->numOuterElectrons += electronsDonated;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint electronsDonated = 8 - this->numOuterElectrons;\n\t\t\tother->numOuterElectrons -= electronsDonated;\n\t\t\tthis->numOuterElectrons += electronsDonated;\n\t\t}\n\t\treturn true;\n\t}\n\t\t\n\t\/\/covalent\n\telse if (maxNegativity - minNegativity <= 1.7)\n\t\treturn true;\n\n\treturn false;\n}\n\nstatic Element rawElements[] =\n{\n \/\/Alkali Metals\n\tElement(\"Hydrogen\", \"H\", \"nonmetal\", 1, 1.008, 1, 2.20),\n Element(\"Lithium\", \"Li\", \"alkali\", 3, 6.94, 1, 0.98),\n\tElement(\"Sodium\", \"Na\", \"alkali\", 11, 22.9898, 1, 0.93),\n\tElement(\"Potassium\", \"K\", \"alkali\", 19, 39.0938, 1, 0.82),\n\tElement(\"Rubidium\", \"Rb\", \"alkali\", 37, 85.4678, 1, 0.82),\n\tElement(\"Cesium\", \"Cs\", \"alkali\", 55, 132.90545196, 1, 0.79), \/\/don't remember if we need this one or not\n \n \/\/Halogens\n Element(\"Flourine\", \"F\", \"halogen\", 9, 18.998403163, 7, 3.98),\n\tElement(\"Chlorine\", \"Cl\", \"halogen\", 17, 35.45, 7, 3.16),\n\tElement(\"Bromine\", \"Br\", \"halogen\", 35, 79.094, 7, 2.96),\n\tElement(\"Iodine\", \"I\", \"halogen\", 53, 126.90447, 7, 2.66),\n \n \/\/Noble Gases\n Element(\"Helium\", \"He\", \"noble\", 2, 4.002602, 2, 0),\n\tElement(\"Neon\", \"Ne\", \"noble\", 10, 20.1797, 8, 0),\n\tElement(\"Argon\", \"Ar\", \"noble\", 18, 39.948, 8, 0),\n\tElement(\"Krypton\", \"Kr\", \"noble\", 36, 83.798, 8, 0),\n\t\n\t\/\/alkali earth metals\n\tElement(\"Beryllium\", \"Be\", \"alkaliEarth\", 4, 9.0121831, 2, 1.27),\n\tElement(\"Magnesium\", \"Mg\", \"alkaliEarth\", 12, 24.305, 2, 1.31),\n\tElement(\"Calcium\", \"Ca\", \"alkaliEarth\", 20, 40.078, 2, 1.0),\n\tElement(\"Strontium\", \"Sr\", \"alkaliEarth\", 38, 87.62, 2, 0.95),\n\tElement(\"Barium\", \"Ba\", \"alkaliEarth\", 56, 137.327, 2, 0.89),\n\tElement(\"Radium\", \"Ra\", \"alkaliEarth\", 88, 226, 2, 0.9), \/\/not sure if needed\n\t\n};\n\nvoid Element::GetRawElement(int num, Element* elementOut)\n{\n Assert(num >= 0 && num < GetRawElementCount());\n *elementOut = Element(&rawElements[num]);\n}\n\nbool Element::GetRawElement(const char* name, Element* elementOut)\n{\n int num = GetRawElementNum(name);\n\n if (num < 0)\n {\n *elementOut = Element(\"INVALID\", \"INV\", \"INV\", 0, 0.0, 0, 0.0);\n return false;\n }\n else\n {\n *elementOut = Element(&rawElements[num]);\n return true;\n }\n}\n\nint Element::GetRawElementNum(const char* name)\n{\n for (int i = 0; i < GetRawElementCount(); i++)\n {\n if (strcmp(name, rawElements[i].GetSymbol()) == 0)\n {\n return i;\n }\n }\n\n return -1;\n}\n\nint Element::GetRawElementCount()\n{\n return CountOfArray(rawElements);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com>\n * Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"directoryprovider.h\"\n\n#include <QtGui\/QDesktopServices>\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QtCore\/QSettings>\n\nusing namespace GluonCore;\n\nGLUON_DEFINE_SINGLETON( DirectoryProvider )\n\nDirectoryProvider::DirectoryProvider( QObject* parent )\n{\n m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );\n m_userDataPath.remove( QCoreApplication::applicationName() );\n m_userDataPath.remove( QCoreApplication::organizationName() );\n m_userDataPath.append( \"\/gluon\/\" );\n\n \/\/Define standard dirs Gluon recommends\n m_userDirs[\"data\"] = QDir::fromNativeSeparators( m_userDataPath + \"\/data\" );\n m_userDirs[\"games\"] = QDir::fromNativeSeparators( m_userDataPath + \"\/games\" );\n\n \/\/Create standard dirs Gluon recommends\n QDir dir;\n foreach( const QString& dirPath, m_userDirs )\n {\n dir.mkpath( dirPath );\n }\n}\n\nQString DirectoryProvider::installPrefix() const\n{\n#ifdef Q_OS_WIN\n QSettings *settings;\n if (GLUON_ARCHITECTURE == \"32\")\n settings = new QSettings(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Wow6432Node\\\\Gluon\\\\Gluon-\" + GLUON_VERSION_STRING + \"\\\\\", QSettings::NativeFormat);\n else if (GLUON_ARCHITECTURE == \"64\")\n settings = new QSettings(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Gluon\\\\Gluon-\" + GLUON_VERSION_STRING + \"\\\\\", QSettings::NativeFormat);\n\n QString installPath = settings->value(\"Default\").toString();\n delete settings;\n return installPath.isEmpty() ? GLUON_INSTALL_PREFIX : installPath;\n#else\n return GLUON_INSTALL_PREFIX;\n#endif\n}\n\nQString DirectoryProvider::dataDirectory() const\n{\n return installPrefix() + \"\/\" + GLUON_SHARE_INSTALL_DIR;\n}\n\nQString DirectoryProvider::libDirectory() const\n{\n return installPrefix() + \"\/\" + GLUON_LIB_INSTALL_DIR;\n}\n\nQString DirectoryProvider::userDirectory( const QString& name )\n{\n if( !m_userDirs.contains( name ) )\n {\n QString path = QDir::fromNativeSeparators( m_userDataPath + name );\n m_userDirs[name] = path;\n QDir dir;\n dir.mkpath( path );\n }\n\n return m_userDirs[name];\n}\n\n#include \"directoryprovider.moc\"\n<commit_msg>Sanity removal of the many unneccesary slash characters<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com>\n * Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"directoryprovider.h\"\n\n#include <QtGui\/QDesktopServices>\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QtCore\/QSettings>\n\nusing namespace GluonCore;\n\nGLUON_DEFINE_SINGLETON( DirectoryProvider )\n\nDirectoryProvider::DirectoryProvider( QObject* parent )\n{\n m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );\n m_userDataPath.remove( QCoreApplication::organizationName() + \"\/\" + QCoreApplication::applicationName() );\n m_userDataPath.append( \"gluon\/\" );\n\n \/\/Define standard dirs Gluon recommends\n m_userDirs[\"data\"] = QDir::fromNativeSeparators( m_userDataPath + \"data\" );\n m_userDirs[\"games\"] = QDir::fromNativeSeparators( m_userDataPath + \"games\" );\n\n \/\/Create standard dirs Gluon recommends\n QDir dir;\n foreach( const QString& dirPath, m_userDirs )\n {\n dir.mkpath( dirPath );\n }\n}\n\nQString DirectoryProvider::installPrefix() const\n{\n#ifdef Q_OS_WIN\n QSettings *settings;\n if (GLUON_ARCHITECTURE == \"32\")\n settings = new QSettings(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Wow6432Node\\\\Gluon\\\\Gluon-\" + GLUON_VERSION_STRING + \"\\\\\", QSettings::NativeFormat);\n else if (GLUON_ARCHITECTURE == \"64\")\n settings = new QSettings(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Gluon\\\\Gluon-\" + GLUON_VERSION_STRING + \"\\\\\", QSettings::NativeFormat);\n\n QString installPath = settings->value(\"Default\").toString();\n delete settings;\n return installPath.isEmpty() ? GLUON_INSTALL_PREFIX : installPath;\n#else\n return GLUON_INSTALL_PREFIX;\n#endif\n}\n\nQString DirectoryProvider::dataDirectory() const\n{\n return installPrefix() + \"\/\" + GLUON_SHARE_INSTALL_DIR;\n}\n\nQString DirectoryProvider::libDirectory() const\n{\n return installPrefix() + \"\/\" + GLUON_LIB_INSTALL_DIR;\n}\n\nQString DirectoryProvider::userDirectory( const QString& name )\n{\n if( !m_userDirs.contains( name ) )\n {\n QString path = QDir::fromNativeSeparators( m_userDataPath + name );\n m_userDirs[name] = path;\n QDir dir;\n dir.mkpath( path );\n }\n\n return m_userDirs[name];\n}\n\n#include \"directoryprovider.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"catch.hpp\"\n#include <mapnik\/text\/icu_shaper.hpp>\n#include <mapnik\/text\/harfbuzz_shaper.hpp>\n#include <mapnik\/text\/font_library.hpp>\n#include <mapnik\/unicode.hpp>\n\nTEST_CASE(\"shaping\")\n{\n mapnik::freetype_engine::register_font(\"test\/data\/fonts\/NotoSans-Regular.ttc\");\n mapnik::freetype_engine::register_fonts(\"test\/data\/fonts\/Noto\");\n mapnik::font_set fontset(\"fontset\");\n for (auto const& name : mapnik::freetype_engine::face_names())\n {\n fontset.add_face_name(name);\n }\n mapnik::transcoder tr(\"utf8\");\n std::map<unsigned,double> width_map;\n double scale_factor = 1;\n mapnik::font_library fl;\n mapnik::freetype_engine::font_file_mapping_type font_file_mapping;\n mapnik::freetype_engine::font_memory_cache_type font_memory_cache;\n mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache);\n\n mapnik::text_itemizer itemizer;\n auto props = std::make_unique<mapnik::detail::evaluated_format_properties>();\n props->fontset = fontset;\n props->text_size = 64;\n\n std::vector<std::tuple<unsigned, unsigned>> expected =\n {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}};\n \/\/ with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^\n\n \/\/std::vector<std::tuple<unsigned, unsigned>> expected =\n \/\/ {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}};\n \/\/ expected results if \"NotoSansTibetan-Regular.ttf is registered^^\n auto ustr = tr.transcode(\"སྤུ་ཧྲེང (abc)\");\n auto length = ustr.length();\n itemizer.add_text(ustr, props);\n\n {\n mapnik::text_line line(0, length);\n mapnik::harfbuzz_shaper::shape_text(line, itemizer,\n width_map,\n fm,\n scale_factor);\n\n std::size_t index = 0;\n for (auto const& g : line)\n {\n unsigned glyph_index, char_index;\n std::tie(glyph_index, char_index) = expected[index++];\n REQUIRE(glyph_index == g.glyph_index);\n REQUIRE(char_index == g.char_index);\n }\n }\n#if 0\n {\n mapnik::text_line line(0, length);\n mapnik::icu_shaper::shape_text(line,itemizer,\n width_map,\n fm,\n scale_factor);\n\n }\n#endif\n}\n<commit_msg>refactor to make it easier to run multiple tests<commit_after>#include \"catch.hpp\"\n#include <mapnik\/text\/icu_shaper.hpp>\n#include <mapnik\/text\/harfbuzz_shaper.hpp>\n#include <mapnik\/text\/font_library.hpp>\n#include <mapnik\/unicode.hpp>\n\nnamespace {\n\nvoid test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm,\n std::vector<std::tuple<unsigned, unsigned>> const& expected, char const* str)\n{\n mapnik::transcoder tr(\"utf8\");\n std::map<unsigned,double> width_map;\n mapnik::text_itemizer itemizer;\n auto props = std::make_unique<mapnik::detail::evaluated_format_properties>();\n props->fontset = fontset;\n props->text_size = 32;\n\n double scale_factor = 1;\n auto ustr = tr.transcode(str);\n auto length = ustr.length();\n itemizer.add_text(ustr, props);\n\n mapnik::text_line line(0, length);\n mapnik::harfbuzz_shaper::shape_text(line, itemizer,\n width_map,\n fm,\n scale_factor);\n\n std::size_t index = 0;\n for (auto const& g : line)\n {\n unsigned glyph_index, char_index;\n CHECK(index < expected.size());\n std::tie(glyph_index, char_index) = expected[index++];\n REQUIRE(glyph_index == g.glyph_index);\n REQUIRE(char_index == g.char_index);\n }\n}\n}\n\nTEST_CASE(\"shaping\")\n{\n mapnik::freetype_engine::register_font(\"test\/data\/fonts\/NotoSans-Regular.ttc\");\n mapnik::freetype_engine::register_fonts(\"test\/data\/fonts\/Noto\");\n mapnik::font_set fontset(\"fontset\");\n for (auto const& name : mapnik::freetype_engine::face_names())\n {\n fontset.add_face_name(name);\n }\n\n mapnik::font_library fl;\n mapnik::freetype_engine::font_file_mapping_type font_file_mapping;\n mapnik::freetype_engine::font_memory_cache_type font_memory_cache;\n mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache);\n\n {\n std::vector<std::tuple<unsigned, unsigned>> expected =\n {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}};\n \/\/ with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^\n \/\/std::vector<std::tuple<unsigned, unsigned>> expected =\n \/\/ {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}};\n \/\/ expected results if \"NotoSansTibetan-Regular.ttf is registered^^\n test_shaping(fontset, fm, expected, \"སྤུ་ཧྲེང (abc)\");\n }\n\n {\n std::vector<std::tuple<unsigned, unsigned>> expected =\n {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}};\n test_shaping(fontset, fm, expected, \"སྤུ་ཧྲེང (普兰镇)\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkCodec.h\"\n#include \"SkCodecPriv.h\"\n#include \"SkMath.h\"\n#include \"SkMathPriv.h\"\n#include \"SkSampledCodec.h\"\n#include \"SkSampler.h\"\n#include \"SkTemplates.h\"\n\nSkSampledCodec::SkSampledCodec(SkCodec* codec, ExifOrientationBehavior behavior)\n : INHERITED(codec, behavior)\n{}\n\nSkISize SkSampledCodec::accountForNativeScaling(int* sampleSizePtr, int* nativeSampleSize) const {\n SkISize preSampledSize = this->codec()->dimensions();\n int sampleSize = *sampleSizePtr;\n SkASSERT(sampleSize > 1);\n\n if (nativeSampleSize) {\n *nativeSampleSize = 1;\n }\n\n \/\/ Only JPEG supports native downsampling.\n if (this->codec()->getEncodedFormat() == SkEncodedImageFormat::kJPEG) {\n \/\/ See if libjpeg supports this scale directly\n switch (sampleSize) {\n case 2:\n case 4:\n case 8:\n \/\/ This class does not need to do any sampling.\n *sampleSizePtr = 1;\n return this->codec()->getScaledDimensions(get_scale_from_sample_size(sampleSize));\n default:\n break;\n }\n\n \/\/ Check if sampleSize is a multiple of something libjpeg can support.\n int remainder;\n const int sampleSizes[] = { 8, 4, 2 };\n for (int supportedSampleSize : sampleSizes) {\n int actualSampleSize;\n SkTDivMod(sampleSize, supportedSampleSize, &actualSampleSize, &remainder);\n if (0 == remainder) {\n float scale = get_scale_from_sample_size(supportedSampleSize);\n\n \/\/ this->codec() will scale to this size.\n preSampledSize = this->codec()->getScaledDimensions(scale);\n\n \/\/ And then this class will sample it.\n *sampleSizePtr = actualSampleSize;\n if (nativeSampleSize) {\n *nativeSampleSize = supportedSampleSize;\n }\n break;\n }\n }\n }\n\n return preSampledSize;\n}\n\nSkISize SkSampledCodec::onGetSampledDimensions(int sampleSize) const {\n const SkISize size = this->accountForNativeScaling(&sampleSize);\n return SkISize::Make(get_scaled_dimension(size.width(), sampleSize),\n get_scaled_dimension(size.height(), sampleSize));\n}\n\nSkCodec::Result SkSampledCodec::onGetAndroidPixels(const SkImageInfo& info, void* pixels,\n size_t rowBytes, const AndroidOptions& options) {\n \/\/ Create an Options struct for the codec.\n SkCodec::Options codecOptions;\n codecOptions.fZeroInitialized = options.fZeroInitialized;\n\n SkIRect* subset = options.fSubset;\n if (!subset || subset->size() == this->codec()->dimensions()) {\n if (this->codec()->dimensionsSupported(info.dimensions())) {\n return this->codec()->getPixels(info, pixels, rowBytes, &codecOptions);\n }\n\n \/\/ If the native codec does not support the requested scale, scale by sampling.\n return this->sampledDecode(info, pixels, rowBytes, options);\n }\n\n \/\/ We are performing a subset decode.\n int sampleSize = options.fSampleSize;\n SkISize scaledSize = this->getSampledDimensions(sampleSize);\n if (!this->codec()->dimensionsSupported(scaledSize)) {\n \/\/ If the native codec does not support the requested scale, scale by sampling.\n return this->sampledDecode(info, pixels, rowBytes, options);\n }\n\n \/\/ Calculate the scaled subset bounds.\n int scaledSubsetX = subset->x() \/ sampleSize;\n int scaledSubsetY = subset->y() \/ sampleSize;\n int scaledSubsetWidth = info.width();\n int scaledSubsetHeight = info.height();\n\n const SkImageInfo scaledInfo = info.makeWH(scaledSize.width(), scaledSize.height());\n\n {\n \/\/ Although startScanlineDecode expects the bottom and top to match the\n \/\/ SkImageInfo, startIncrementalDecode uses them to determine which rows to\n \/\/ decode.\n SkIRect incrementalSubset = SkIRect::MakeXYWH(scaledSubsetX, scaledSubsetY,\n scaledSubsetWidth, scaledSubsetHeight);\n codecOptions.fSubset = &incrementalSubset;\n const SkCodec::Result startResult = this->codec()->startIncrementalDecode(\n scaledInfo, pixels, rowBytes, &codecOptions);\n if (SkCodec::kSuccess == startResult) {\n int rowsDecoded = 0;\n const SkCodec::Result incResult = this->codec()->incrementalDecode(&rowsDecoded);\n if (incResult == SkCodec::kSuccess) {\n return SkCodec::kSuccess;\n }\n SkASSERT(incResult == SkCodec::kIncompleteInput || incResult == SkCodec::kErrorInInput);\n\n \/\/ FIXME: Can zero initialized be read from SkCodec::fOptions?\n this->codec()->fillIncompleteImage(scaledInfo, pixels, rowBytes,\n options.fZeroInitialized, scaledSubsetHeight, rowsDecoded);\n return incResult;\n } else if (startResult != SkCodec::kUnimplemented) {\n return startResult;\n }\n \/\/ Otherwise fall down to use the old scanline decoder.\n \/\/ codecOptions.fSubset will be reset below, so it will not continue to\n \/\/ point to the object that is no longer on the stack.\n }\n\n \/\/ Start the scanline decode.\n SkIRect scanlineSubset = SkIRect::MakeXYWH(scaledSubsetX, 0, scaledSubsetWidth,\n scaledSize.height());\n codecOptions.fSubset = &scanlineSubset;\n\n SkCodec::Result result = this->codec()->startScanlineDecode(scaledInfo,\n &codecOptions);\n if (SkCodec::kSuccess != result) {\n return result;\n }\n\n \/\/ At this point, we are only concerned with subsetting. Either no scale was\n \/\/ requested, or the this->codec() is handling the scale.\n \/\/ Note that subsetting is only supported for kTopDown, so this code will not be\n \/\/ reached for other orders.\n SkASSERT(this->codec()->getScanlineOrder() == SkCodec::kTopDown_SkScanlineOrder);\n if (!this->codec()->skipScanlines(scaledSubsetY)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n scaledSubsetHeight, 0);\n return SkCodec::kIncompleteInput;\n }\n\n int decodedLines = this->codec()->getScanlines(pixels, scaledSubsetHeight, rowBytes);\n if (decodedLines != scaledSubsetHeight) {\n return SkCodec::kIncompleteInput;\n }\n return SkCodec::kSuccess;\n}\n\n\nSkCodec::Result SkSampledCodec::sampledDecode(const SkImageInfo& info, void* pixels,\n size_t rowBytes, const AndroidOptions& options) {\n \/\/ We should only call this function when sampling.\n SkASSERT(options.fSampleSize > 1);\n\n \/\/ Create options struct for the codec.\n SkCodec::Options sampledOptions;\n sampledOptions.fZeroInitialized = options.fZeroInitialized;\n\n \/\/ FIXME: This was already called by onGetAndroidPixels. Can we reduce that?\n int sampleSize = options.fSampleSize;\n int nativeSampleSize;\n SkISize nativeSize = this->accountForNativeScaling(&sampleSize, &nativeSampleSize);\n\n \/\/ Check if there is a subset.\n SkIRect subset;\n int subsetY = 0;\n int subsetWidth = nativeSize.width();\n int subsetHeight = nativeSize.height();\n if (options.fSubset) {\n \/\/ We will need to know about subsetting in the y-dimension in order to use the\n \/\/ scanline decoder.\n \/\/ Update the subset to account for scaling done by this->codec().\n const SkIRect* subsetPtr = options.fSubset;\n\n \/\/ Do the divide ourselves, instead of calling get_scaled_dimension. If\n \/\/ X and Y are 0, they should remain 0, rather than being upgraded to 1\n \/\/ due to being smaller than the sampleSize.\n const int subsetX = subsetPtr->x() \/ nativeSampleSize;\n subsetY = subsetPtr->y() \/ nativeSampleSize;\n\n subsetWidth = get_scaled_dimension(subsetPtr->width(), nativeSampleSize);\n subsetHeight = get_scaled_dimension(subsetPtr->height(), nativeSampleSize);\n\n \/\/ The scanline decoder only needs to be aware of subsetting in the x-dimension.\n subset.setXYWH(subsetX, 0, subsetWidth, nativeSize.height());\n sampledOptions.fSubset = ⊂\n }\n\n \/\/ Since we guarantee that output dimensions are always at least one (even if the sampleSize\n \/\/ is greater than a given dimension), the input sampleSize is not always the sampleSize that\n \/\/ we use in practice.\n const int sampleX = subsetWidth \/ info.width();\n const int sampleY = subsetHeight \/ info.height();\n\n const int samplingOffsetY = get_start_coord(sampleY);\n const int startY = samplingOffsetY + subsetY;\n const int dstHeight = info.height();\n\n const SkImageInfo nativeInfo = info.makeWH(nativeSize.width(), nativeSize.height());\n\n {\n \/\/ Although startScanlineDecode expects the bottom and top to match the\n \/\/ SkImageInfo, startIncrementalDecode uses them to determine which rows to\n \/\/ decode.\n SkCodec::Options incrementalOptions = sampledOptions;\n SkIRect incrementalSubset;\n if (sampledOptions.fSubset) {\n incrementalSubset.fTop = subsetY;\n incrementalSubset.fBottom = subsetY + subsetHeight;\n incrementalSubset.fLeft = sampledOptions.fSubset->fLeft;\n incrementalSubset.fRight = sampledOptions.fSubset->fRight;\n incrementalOptions.fSubset = &incrementalSubset;\n }\n const SkCodec::Result startResult = this->codec()->startIncrementalDecode(nativeInfo,\n pixels, rowBytes, &incrementalOptions);\n if (SkCodec::kSuccess == startResult) {\n SkSampler* sampler = this->codec()->getSampler(true);\n if (!sampler) {\n return SkCodec::kUnimplemented;\n }\n\n if (sampler->setSampleX(sampleX) != info.width()) {\n return SkCodec::kInvalidScale;\n }\n if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {\n return SkCodec::kInvalidScale;\n }\n\n sampler->setSampleY(sampleY);\n\n int rowsDecoded = 0;\n const SkCodec::Result incResult = this->codec()->incrementalDecode(&rowsDecoded);\n if (incResult == SkCodec::kSuccess) {\n return SkCodec::kSuccess;\n }\n SkASSERT(incResult == SkCodec::kIncompleteInput || incResult == SkCodec::kErrorInInput);\n\n SkASSERT(rowsDecoded <= info.height());\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n info.height(), rowsDecoded);\n return incResult;\n } else if (startResult != SkCodec::kUnimplemented) {\n return startResult;\n } \/\/ kUnimplemented means use the old method.\n }\n\n \/\/ Start the scanline decode.\n SkCodec::Result result = this->codec()->startScanlineDecode(nativeInfo,\n &sampledOptions);\n if (SkCodec::kSuccess != result) {\n return result;\n }\n\n SkSampler* sampler = this->codec()->getSampler(true);\n if (!sampler) {\n return SkCodec::kUnimplemented;\n }\n\n if (sampler->setSampleX(sampleX) != info.width()) {\n return SkCodec::kInvalidScale;\n }\n if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {\n return SkCodec::kInvalidScale;\n }\n\n switch(this->codec()->getScanlineOrder()) {\n case SkCodec::kTopDown_SkScanlineOrder: {\n if (!this->codec()->skipScanlines(startY)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n dstHeight, 0);\n return SkCodec::kIncompleteInput;\n }\n void* pixelPtr = pixels;\n for (int y = 0; y < dstHeight; y++) {\n if (1 != this->codec()->getScanlines(pixelPtr, 1, rowBytes)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes,\n options.fZeroInitialized, dstHeight, y + 1);\n return SkCodec::kIncompleteInput;\n }\n if (y < dstHeight - 1) {\n if (!this->codec()->skipScanlines(sampleY - 1)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes,\n options.fZeroInitialized, dstHeight, y + 1);\n return SkCodec::kIncompleteInput;\n }\n }\n pixelPtr = SkTAddOffset<void>(pixelPtr, rowBytes);\n }\n return SkCodec::kSuccess;\n }\n case SkCodec::kBottomUp_SkScanlineOrder: {\n \/\/ Note that these modes do not support subsetting.\n SkASSERT(0 == subsetY && nativeSize.height() == subsetHeight);\n int y;\n for (y = 0; y < nativeSize.height(); y++) {\n int srcY = this->codec()->nextScanline();\n if (is_coord_necessary(srcY, sampleY, dstHeight)) {\n void* pixelPtr = SkTAddOffset<void>(pixels,\n rowBytes * get_dst_coord(srcY, sampleY));\n if (1 != this->codec()->getScanlines(pixelPtr, 1, rowBytes)) {\n break;\n }\n } else {\n if (!this->codec()->skipScanlines(1)) {\n break;\n }\n }\n }\n\n if (nativeSize.height() == y) {\n return SkCodec::kSuccess;\n }\n\n \/\/ We handle filling uninitialized memory here instead of using this->codec().\n \/\/ this->codec() does not know that we are sampling.\n const SkImageInfo fillInfo = info.makeWH(info.width(), 1);\n for (; y < nativeSize.height(); y++) {\n int srcY = this->codec()->outputScanline(y);\n if (!is_coord_necessary(srcY, sampleY, dstHeight)) {\n continue;\n }\n\n void* rowPtr = SkTAddOffset<void>(pixels, rowBytes * get_dst_coord(srcY, sampleY));\n SkSampler::Fill(fillInfo, rowPtr, rowBytes, options.fZeroInitialized);\n }\n return SkCodec::kIncompleteInput;\n }\n default:\n SkASSERT(false);\n return SkCodec::kUnimplemented;\n }\n}\n<commit_msg>Treat start(Incremental\/Scanline)Decode errors as failures<commit_after>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkCodec.h\"\n#include \"SkCodecPriv.h\"\n#include \"SkMath.h\"\n#include \"SkMathPriv.h\"\n#include \"SkSampledCodec.h\"\n#include \"SkSampler.h\"\n#include \"SkTemplates.h\"\n\nSkSampledCodec::SkSampledCodec(SkCodec* codec, ExifOrientationBehavior behavior)\n : INHERITED(codec, behavior)\n{}\n\nSkISize SkSampledCodec::accountForNativeScaling(int* sampleSizePtr, int* nativeSampleSize) const {\n SkISize preSampledSize = this->codec()->dimensions();\n int sampleSize = *sampleSizePtr;\n SkASSERT(sampleSize > 1);\n\n if (nativeSampleSize) {\n *nativeSampleSize = 1;\n }\n\n \/\/ Only JPEG supports native downsampling.\n if (this->codec()->getEncodedFormat() == SkEncodedImageFormat::kJPEG) {\n \/\/ See if libjpeg supports this scale directly\n switch (sampleSize) {\n case 2:\n case 4:\n case 8:\n \/\/ This class does not need to do any sampling.\n *sampleSizePtr = 1;\n return this->codec()->getScaledDimensions(get_scale_from_sample_size(sampleSize));\n default:\n break;\n }\n\n \/\/ Check if sampleSize is a multiple of something libjpeg can support.\n int remainder;\n const int sampleSizes[] = { 8, 4, 2 };\n for (int supportedSampleSize : sampleSizes) {\n int actualSampleSize;\n SkTDivMod(sampleSize, supportedSampleSize, &actualSampleSize, &remainder);\n if (0 == remainder) {\n float scale = get_scale_from_sample_size(supportedSampleSize);\n\n \/\/ this->codec() will scale to this size.\n preSampledSize = this->codec()->getScaledDimensions(scale);\n\n \/\/ And then this class will sample it.\n *sampleSizePtr = actualSampleSize;\n if (nativeSampleSize) {\n *nativeSampleSize = supportedSampleSize;\n }\n break;\n }\n }\n }\n\n return preSampledSize;\n}\n\nSkISize SkSampledCodec::onGetSampledDimensions(int sampleSize) const {\n const SkISize size = this->accountForNativeScaling(&sampleSize);\n return SkISize::Make(get_scaled_dimension(size.width(), sampleSize),\n get_scaled_dimension(size.height(), sampleSize));\n}\n\nSkCodec::Result SkSampledCodec::onGetAndroidPixels(const SkImageInfo& info, void* pixels,\n size_t rowBytes, const AndroidOptions& options) {\n \/\/ Create an Options struct for the codec.\n SkCodec::Options codecOptions;\n codecOptions.fZeroInitialized = options.fZeroInitialized;\n\n SkIRect* subset = options.fSubset;\n if (!subset || subset->size() == this->codec()->dimensions()) {\n if (this->codec()->dimensionsSupported(info.dimensions())) {\n return this->codec()->getPixels(info, pixels, rowBytes, &codecOptions);\n }\n\n \/\/ If the native codec does not support the requested scale, scale by sampling.\n return this->sampledDecode(info, pixels, rowBytes, options);\n }\n\n \/\/ We are performing a subset decode.\n int sampleSize = options.fSampleSize;\n SkISize scaledSize = this->getSampledDimensions(sampleSize);\n if (!this->codec()->dimensionsSupported(scaledSize)) {\n \/\/ If the native codec does not support the requested scale, scale by sampling.\n return this->sampledDecode(info, pixels, rowBytes, options);\n }\n\n \/\/ Calculate the scaled subset bounds.\n int scaledSubsetX = subset->x() \/ sampleSize;\n int scaledSubsetY = subset->y() \/ sampleSize;\n int scaledSubsetWidth = info.width();\n int scaledSubsetHeight = info.height();\n\n const SkImageInfo scaledInfo = info.makeWH(scaledSize.width(), scaledSize.height());\n\n {\n \/\/ Although startScanlineDecode expects the bottom and top to match the\n \/\/ SkImageInfo, startIncrementalDecode uses them to determine which rows to\n \/\/ decode.\n SkIRect incrementalSubset = SkIRect::MakeXYWH(scaledSubsetX, scaledSubsetY,\n scaledSubsetWidth, scaledSubsetHeight);\n codecOptions.fSubset = &incrementalSubset;\n const SkCodec::Result startResult = this->codec()->startIncrementalDecode(\n scaledInfo, pixels, rowBytes, &codecOptions);\n if (SkCodec::kSuccess == startResult) {\n int rowsDecoded = 0;\n const SkCodec::Result incResult = this->codec()->incrementalDecode(&rowsDecoded);\n if (incResult == SkCodec::kSuccess) {\n return SkCodec::kSuccess;\n }\n SkASSERT(incResult == SkCodec::kIncompleteInput || incResult == SkCodec::kErrorInInput);\n\n \/\/ FIXME: Can zero initialized be read from SkCodec::fOptions?\n this->codec()->fillIncompleteImage(scaledInfo, pixels, rowBytes,\n options.fZeroInitialized, scaledSubsetHeight, rowsDecoded);\n return incResult;\n } else if (startResult != SkCodec::kUnimplemented) {\n return startResult;\n }\n \/\/ Otherwise fall down to use the old scanline decoder.\n \/\/ codecOptions.fSubset will be reset below, so it will not continue to\n \/\/ point to the object that is no longer on the stack.\n }\n\n \/\/ Start the scanline decode.\n SkIRect scanlineSubset = SkIRect::MakeXYWH(scaledSubsetX, 0, scaledSubsetWidth,\n scaledSize.height());\n codecOptions.fSubset = &scanlineSubset;\n\n SkCodec::Result result = this->codec()->startScanlineDecode(scaledInfo,\n &codecOptions);\n if (SkCodec::kSuccess != result) {\n return result;\n }\n\n \/\/ At this point, we are only concerned with subsetting. Either no scale was\n \/\/ requested, or the this->codec() is handling the scale.\n \/\/ Note that subsetting is only supported for kTopDown, so this code will not be\n \/\/ reached for other orders.\n SkASSERT(this->codec()->getScanlineOrder() == SkCodec::kTopDown_SkScanlineOrder);\n if (!this->codec()->skipScanlines(scaledSubsetY)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n scaledSubsetHeight, 0);\n return SkCodec::kIncompleteInput;\n }\n\n int decodedLines = this->codec()->getScanlines(pixels, scaledSubsetHeight, rowBytes);\n if (decodedLines != scaledSubsetHeight) {\n return SkCodec::kIncompleteInput;\n }\n return SkCodec::kSuccess;\n}\n\n\nSkCodec::Result SkSampledCodec::sampledDecode(const SkImageInfo& info, void* pixels,\n size_t rowBytes, const AndroidOptions& options) {\n \/\/ We should only call this function when sampling.\n SkASSERT(options.fSampleSize > 1);\n\n \/\/ Create options struct for the codec.\n SkCodec::Options sampledOptions;\n sampledOptions.fZeroInitialized = options.fZeroInitialized;\n\n \/\/ FIXME: This was already called by onGetAndroidPixels. Can we reduce that?\n int sampleSize = options.fSampleSize;\n int nativeSampleSize;\n SkISize nativeSize = this->accountForNativeScaling(&sampleSize, &nativeSampleSize);\n\n \/\/ Check if there is a subset.\n SkIRect subset;\n int subsetY = 0;\n int subsetWidth = nativeSize.width();\n int subsetHeight = nativeSize.height();\n if (options.fSubset) {\n \/\/ We will need to know about subsetting in the y-dimension in order to use the\n \/\/ scanline decoder.\n \/\/ Update the subset to account for scaling done by this->codec().\n const SkIRect* subsetPtr = options.fSubset;\n\n \/\/ Do the divide ourselves, instead of calling get_scaled_dimension. If\n \/\/ X and Y are 0, they should remain 0, rather than being upgraded to 1\n \/\/ due to being smaller than the sampleSize.\n const int subsetX = subsetPtr->x() \/ nativeSampleSize;\n subsetY = subsetPtr->y() \/ nativeSampleSize;\n\n subsetWidth = get_scaled_dimension(subsetPtr->width(), nativeSampleSize);\n subsetHeight = get_scaled_dimension(subsetPtr->height(), nativeSampleSize);\n\n \/\/ The scanline decoder only needs to be aware of subsetting in the x-dimension.\n subset.setXYWH(subsetX, 0, subsetWidth, nativeSize.height());\n sampledOptions.fSubset = ⊂\n }\n\n \/\/ Since we guarantee that output dimensions are always at least one (even if the sampleSize\n \/\/ is greater than a given dimension), the input sampleSize is not always the sampleSize that\n \/\/ we use in practice.\n const int sampleX = subsetWidth \/ info.width();\n const int sampleY = subsetHeight \/ info.height();\n\n const int samplingOffsetY = get_start_coord(sampleY);\n const int startY = samplingOffsetY + subsetY;\n const int dstHeight = info.height();\n\n const SkImageInfo nativeInfo = info.makeWH(nativeSize.width(), nativeSize.height());\n\n {\n \/\/ Although startScanlineDecode expects the bottom and top to match the\n \/\/ SkImageInfo, startIncrementalDecode uses them to determine which rows to\n \/\/ decode.\n SkCodec::Options incrementalOptions = sampledOptions;\n SkIRect incrementalSubset;\n if (sampledOptions.fSubset) {\n incrementalSubset.fTop = subsetY;\n incrementalSubset.fBottom = subsetY + subsetHeight;\n incrementalSubset.fLeft = sampledOptions.fSubset->fLeft;\n incrementalSubset.fRight = sampledOptions.fSubset->fRight;\n incrementalOptions.fSubset = &incrementalSubset;\n }\n const SkCodec::Result startResult = this->codec()->startIncrementalDecode(nativeInfo,\n pixels, rowBytes, &incrementalOptions);\n if (SkCodec::kSuccess == startResult) {\n SkSampler* sampler = this->codec()->getSampler(true);\n if (!sampler) {\n return SkCodec::kUnimplemented;\n }\n\n if (sampler->setSampleX(sampleX) != info.width()) {\n return SkCodec::kInvalidScale;\n }\n if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {\n return SkCodec::kInvalidScale;\n }\n\n sampler->setSampleY(sampleY);\n\n int rowsDecoded = 0;\n const SkCodec::Result incResult = this->codec()->incrementalDecode(&rowsDecoded);\n if (incResult == SkCodec::kSuccess) {\n return SkCodec::kSuccess;\n }\n SkASSERT(incResult == SkCodec::kIncompleteInput || incResult == SkCodec::kErrorInInput);\n\n SkASSERT(rowsDecoded <= info.height());\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n info.height(), rowsDecoded);\n return incResult;\n } else if (startResult == SkCodec::kIncompleteInput\n || startResult == SkCodec::kErrorInInput) {\n return SkCodec::kInvalidInput;\n } else if (startResult != SkCodec::kUnimplemented) {\n return startResult;\n } \/\/ kUnimplemented means use the old method.\n }\n\n \/\/ Start the scanline decode.\n SkCodec::Result result = this->codec()->startScanlineDecode(nativeInfo,\n &sampledOptions);\n if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {\n return SkCodec::kInvalidInput;\n } else if (SkCodec::kSuccess != result) {\n return result;\n }\n\n SkSampler* sampler = this->codec()->getSampler(true);\n if (!sampler) {\n return SkCodec::kUnimplemented;\n }\n\n if (sampler->setSampleX(sampleX) != info.width()) {\n return SkCodec::kInvalidScale;\n }\n if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {\n return SkCodec::kInvalidScale;\n }\n\n switch(this->codec()->getScanlineOrder()) {\n case SkCodec::kTopDown_SkScanlineOrder: {\n if (!this->codec()->skipScanlines(startY)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,\n dstHeight, 0);\n return SkCodec::kIncompleteInput;\n }\n void* pixelPtr = pixels;\n for (int y = 0; y < dstHeight; y++) {\n if (1 != this->codec()->getScanlines(pixelPtr, 1, rowBytes)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes,\n options.fZeroInitialized, dstHeight, y + 1);\n return SkCodec::kIncompleteInput;\n }\n if (y < dstHeight - 1) {\n if (!this->codec()->skipScanlines(sampleY - 1)) {\n this->codec()->fillIncompleteImage(info, pixels, rowBytes,\n options.fZeroInitialized, dstHeight, y + 1);\n return SkCodec::kIncompleteInput;\n }\n }\n pixelPtr = SkTAddOffset<void>(pixelPtr, rowBytes);\n }\n return SkCodec::kSuccess;\n }\n case SkCodec::kBottomUp_SkScanlineOrder: {\n \/\/ Note that these modes do not support subsetting.\n SkASSERT(0 == subsetY && nativeSize.height() == subsetHeight);\n int y;\n for (y = 0; y < nativeSize.height(); y++) {\n int srcY = this->codec()->nextScanline();\n if (is_coord_necessary(srcY, sampleY, dstHeight)) {\n void* pixelPtr = SkTAddOffset<void>(pixels,\n rowBytes * get_dst_coord(srcY, sampleY));\n if (1 != this->codec()->getScanlines(pixelPtr, 1, rowBytes)) {\n break;\n }\n } else {\n if (!this->codec()->skipScanlines(1)) {\n break;\n }\n }\n }\n\n if (nativeSize.height() == y) {\n return SkCodec::kSuccess;\n }\n\n \/\/ We handle filling uninitialized memory here instead of using this->codec().\n \/\/ this->codec() does not know that we are sampling.\n const SkImageInfo fillInfo = info.makeWH(info.width(), 1);\n for (; y < nativeSize.height(); y++) {\n int srcY = this->codec()->outputScanline(y);\n if (!is_coord_necessary(srcY, sampleY, dstHeight)) {\n continue;\n }\n\n void* rowPtr = SkTAddOffset<void>(pixels, rowBytes * get_dst_coord(srcY, sampleY));\n SkSampler::Fill(fillInfo, rowPtr, rowBytes, options.fZeroInitialized);\n }\n return SkCodec::kIncompleteInput;\n }\n default:\n SkASSERT(false);\n return SkCodec::kUnimplemented;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/label.h\"\n\n#include <math.h>\n#include <limits>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/text_elider.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/logging.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/color_utils.h\"\n#include \"gfx\/font.h\"\n#include \"gfx\/insets.h\"\n#include \"views\/background.h\"\n\nnamespace views {\n\n\/\/ static\nconst char Label::kViewClassName[] = \"views\/Label\";\nSkColor Label::kEnabledColor, Label::kDisabledColor;\n\nstatic const int kFocusBorderPadding = 1;\n\nLabel::Label() {\n Init(std::wstring(), GetDefaultFont());\n}\n\nLabel::Label(const std::wstring& text) {\n Init(text, GetDefaultFont());\n}\n\nLabel::Label(const std::wstring& text, const gfx::Font& font) {\n Init(text, font);\n}\n\nLabel::~Label() {\n}\n\ngfx::Size Label::GetPreferredSize() {\n \/\/ Return a size of (0, 0) if the label is not visible and if the\n \/\/ collapse_when_hidden_ flag is set.\n \/\/ TODO(munjal): This logic probably belongs to the View class. But for now,\n \/\/ put it here since putting it in View class means all inheriting classes\n \/\/ need ot respect the collapse_when_hidden_ flag.\n if (!IsVisible() && collapse_when_hidden_)\n return gfx::Size();\n\n gfx::Size prefsize(GetTextSize());\n gfx::Insets insets = GetInsets();\n prefsize.Enlarge(insets.width(), insets.height());\n return prefsize;\n}\n\nint Label::GetBaseline() {\n return GetInsets().top() + font_.baseline();\n}\n\nint Label::GetHeightForWidth(int w) {\n return is_multi_line_ ?\n (GetTextSize().height() + GetInsets().height()) :\n View::GetHeightForWidth(w);\n}\n\nvoid Label::DidChangeBounds(const gfx::Rect& previous,\n const gfx::Rect& current) {\n text_size_valid_ &= !is_multi_line_;\n}\n\nvoid Label::Paint(gfx::Canvas* canvas) {\n PaintBackground(canvas);\n std::wstring paint_text;\n gfx::Rect text_bounds;\n int flags = 0;\n CalculateDrawStringParams(&paint_text, &text_bounds, &flags);\n canvas->DrawStringInt(paint_text, font_, color_,\n text_bounds.x(), text_bounds.y(),\n text_bounds.width(), text_bounds.height(), flags);\n\n if (HasFocus() || paint_as_focused_) {\n text_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding);\n \/\/ If the label is a single line of text, then the computed text bound\n \/\/ corresponds directly to the text being drawn and no mirroring is needed\n \/\/ for the RTL case. For multiline text, the text bound is an estimation\n \/\/ and is recomputed in gfx::Canvas::SizeStringInt(). For multiline text\n \/\/ in RTL, we need to take mirroring into account when computing the focus\n \/\/ rectangle.\n if (flags & gfx::Canvas::MULTI_LINE)\n text_bounds.set_x(MirroredLeftPointForRect(text_bounds));\n canvas->DrawFocusRect(text_bounds.x(), text_bounds.y(),\n text_bounds.width(), text_bounds.height());\n }\n}\n\nvoid Label::PaintBackground(gfx::Canvas* canvas) {\n const Background* bg = contains_mouse_ ? GetMouseOverBackground() : NULL;\n if (!bg)\n bg = background();\n if (bg)\n bg->Paint(canvas, this);\n}\n\nvoid Label::SetFont(const gfx::Font& font) {\n font_ = font;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nvoid Label::SetText(const std::wstring& text) {\n text_ = text;\n url_set_ = false;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nconst std::wstring Label::GetText() const {\n return url_set_ ? UTF8ToWide(url_.spec()) : text_;\n}\n\nvoid Label::SetURL(const GURL& url) {\n url_ = url;\n text_ = UTF8ToWide(url_.spec());\n url_set_ = true;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nconst GURL Label::GetURL() const {\n return url_set_ ? url_ : GURL(WideToUTF8(text_));\n}\n\nvoid Label::SetHorizontalAlignment(Alignment a) {\n \/\/ If the View's UI layout is right-to-left and rtl_alignment_mode_ is\n \/\/ USE_UI_ALIGNMENT, we need to flip the alignment so that the alignment\n \/\/ settings take into account the text directionality.\n if (UILayoutIsRightToLeft() && (rtl_alignment_mode_ == USE_UI_ALIGNMENT) &&\n (a != ALIGN_CENTER))\n a = (a == ALIGN_LEFT) ? ALIGN_RIGHT : ALIGN_LEFT;\n if (horiz_alignment_ != a) {\n horiz_alignment_ = a;\n SchedulePaint();\n }\n}\n\nvoid Label::SetMultiLine(bool f) {\n if (f != is_multi_line_) {\n is_multi_line_ = f;\n text_size_valid_ = false;\n SchedulePaint();\n }\n}\n\nvoid Label::SetAllowCharacterBreak(bool f) {\n if (f != allow_character_break_) {\n allow_character_break_ = f;\n text_size_valid_ = false;\n SchedulePaint();\n }\n}\n\nvoid Label::SetTooltipText(const std::wstring& tooltip_text) {\n tooltip_text_ = tooltip_text;\n}\n\nbool Label::GetTooltipText(const gfx::Point& p, std::wstring* tooltip) {\n DCHECK(tooltip);\n\n \/\/ If a tooltip has been explicitly set, use it.\n if (!tooltip_text_.empty()) {\n tooltip->assign(tooltip_text_);\n return true;\n }\n\n \/\/ Show the full text if the text does not fit.\n if (!is_multi_line_ && font_.GetStringWidth(text_) > width()) {\n *tooltip = text_;\n return true;\n }\n return false;\n}\n\nvoid Label::OnMouseMoved(const MouseEvent& e) {\n UpdateContainsMouse(e);\n}\n\nvoid Label::OnMouseEntered(const MouseEvent& event) {\n UpdateContainsMouse(event);\n}\n\nvoid Label::OnMouseExited(const MouseEvent& event) {\n SetContainsMouse(false);\n}\n\nvoid Label::SetMouseOverBackground(Background* background) {\n mouse_over_background_.reset(background);\n}\n\nconst Background* Label::GetMouseOverBackground() const {\n return mouse_over_background_.get();\n}\n\nvoid Label::SetEnabled(bool enabled) {\n if (enabled == enabled_)\n return;\n View::SetEnabled(enabled);\n SetColor(enabled ? kEnabledColor : kDisabledColor);\n}\n\ngfx::Insets Label::GetInsets() const {\n gfx::Insets insets = View::GetInsets();\n if (IsFocusable() || has_focus_border_) {\n insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,\n kFocusBorderPadding, kFocusBorderPadding);\n }\n return insets;\n}\n\nvoid Label::SizeToFit(int max_width) {\n DCHECK(is_multi_line_);\n\n std::vector<std::wstring> lines;\n SplitString(text_, L'\\n', &lines);\n\n int label_width = 0;\n for (std::vector<std::wstring>::const_iterator iter = lines.begin();\n iter != lines.end(); ++iter)\n label_width = std::max(label_width, font_.GetStringWidth(*iter));\n\n label_width += GetInsets().width();\n\n if (max_width > 0)\n label_width = std::min(label_width, max_width);\n\n SetBounds(x(), y(), label_width, 0);\n SizeToPreferredSize();\n}\n\nbool Label::GetAccessibleRole(AccessibilityTypes::Role* role) {\n DCHECK(role);\n\n *role = AccessibilityTypes::ROLE_TEXT;\n return true;\n}\n\nbool Label::GetAccessibleName(std::wstring* name) {\n DCHECK(name);\n *name = GetText();\n return !name->empty();\n}\n\nbool Label::GetAccessibleState(AccessibilityTypes::State* state) {\n DCHECK(state);\n\n *state = AccessibilityTypes::STATE_READONLY;\n return true;\n}\n\nvoid Label::SetHasFocusBorder(bool has_focus_border) {\n has_focus_border_ = has_focus_border;\n text_size_valid_ &= !is_multi_line_;\n}\n\n\/\/ static\ngfx::Font Label::GetDefaultFont() {\n return ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);\n}\n\nvoid Label::Init(const std::wstring& text, const gfx::Font& font) {\n static bool initialized = false;\n if (!initialized) {\n#if defined(OS_WIN)\n kEnabledColor = color_utils::GetSysSkColor(COLOR_WINDOWTEXT);\n kDisabledColor = color_utils::GetSysSkColor(COLOR_GRAYTEXT);\n#else\n \/\/ TODO(beng): source from theme provider.\n kEnabledColor = SK_ColorBLACK;\n kDisabledColor = SK_ColorGRAY;\n#endif\n\n initialized = true;\n }\n\n contains_mouse_ = false;\n font_ = font;\n text_size_valid_ = false;\n SetText(text);\n url_set_ = false;\n color_ = kEnabledColor;\n horiz_alignment_ = ALIGN_CENTER;\n is_multi_line_ = false;\n allow_character_break_ = false;\n collapse_when_hidden_ = false;\n rtl_alignment_mode_ = USE_UI_ALIGNMENT;\n paint_as_focused_ = false;\n has_focus_border_ = false;\n}\n\nvoid Label::CalculateDrawStringParams(std::wstring* paint_text,\n gfx::Rect* text_bounds,\n int* flags) const {\n DCHECK(paint_text && text_bounds && flags);\n\n if (url_set_) {\n \/\/ TODO(jungshik) : Figure out how to get 'intl.accept_languages'\n \/\/ preference and use it when calling ElideUrl.\n *paint_text = gfx::ElideUrl(url_, font_, width(), std::wstring());\n\n \/\/ An URLs is always treated as an LTR text and therefore we should\n \/\/ explicitly mark it as such if the locale is RTL so that URLs containing\n \/\/ Hebrew or Arabic characters are displayed correctly.\n \/\/\n \/\/ Note that we don't check the View's UI layout setting in order to\n \/\/ determine whether or not to insert the special Unicode formatting\n \/\/ characters. We use the locale settings because an URL is always treated\n \/\/ as an LTR string, even if its containing view does not use an RTL UI\n \/\/ layout.\n if (base::i18n::IsRTL())\n base::i18n::WrapStringWithLTRFormatting(paint_text);\n } else {\n *paint_text = text_;\n }\n\n *text_bounds = GetTextBounds();\n *flags = ComputeMultiLineFlags();\n}\n\nvoid Label::UpdateContainsMouse(const MouseEvent& event) {\n SetContainsMouse(GetTextBounds().Contains(event.x(), event.y()));\n}\n\nvoid Label::SetContainsMouse(bool contains_mouse) {\n if (contains_mouse_ == contains_mouse)\n return;\n contains_mouse_ = contains_mouse;\n if (GetMouseOverBackground())\n SchedulePaint();\n}\n\ngfx::Rect Label::GetTextBounds() const {\n gfx::Rect available_rect(GetAvailableRect());\n gfx::Size text_size(GetTextSize());\n text_size.set_width(std::min(available_rect.width(), text_size.width()));\n\n gfx::Insets insets = GetInsets();\n gfx::Point text_origin(insets.left(), insets.top());\n switch (horiz_alignment_) {\n case ALIGN_LEFT:\n break;\n case ALIGN_CENTER:\n \/\/ We put any extra margin pixel on the left rather than the right, since\n \/\/ GetTextExtentPoint32() can report a value one too large on the right.\n text_origin.Offset((available_rect.width() + 1 - text_size.width()) \/ 2,\n 0);\n break;\n case ALIGN_RIGHT:\n text_origin.set_x(available_rect.right() - text_size.width());\n break;\n default:\n NOTREACHED();\n break;\n }\n text_origin.Offset(0,\n std::max(0, (available_rect.height() - text_size.height())) \/ 2);\n return gfx::Rect(text_origin, text_size);\n}\n\ngfx::Size Label::GetTextSize() const {\n if (!text_size_valid_) {\n int w = is_multi_line_ ?\n GetAvailableRect().width() : std::numeric_limits<int>::max();\n int h = font_.height();\n gfx::Canvas::SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());\n text_size_.SetSize(w, h);\n text_size_valid_ = true;\n }\n\n return text_size_;\n}\n\nint Label::ComputeMultiLineFlags() const {\n if (!is_multi_line_)\n return 0;\n\n int flags = gfx::Canvas::MULTI_LINE;\n#if !defined(OS_WIN)\n \/\/ Don't ellide multiline labels on Linux.\n \/\/ Todo(davemoore): Do we depend on elliding multiline text?\n \/\/ Pango insists on limiting the number of lines to one if text is\n \/\/ ellided. You can get around this if you can pass a maximum height\n \/\/ but we don't currently have that data when we call the pango code.\n flags |= gfx::Canvas::NO_ELLIPSIS;\n#endif\n if (allow_character_break_)\n flags |= gfx::Canvas::CHARACTER_BREAK;\n switch (horiz_alignment_) {\n case ALIGN_LEFT:\n flags |= gfx::Canvas::TEXT_ALIGN_LEFT;\n break;\n case ALIGN_CENTER:\n flags |= gfx::Canvas::TEXT_ALIGN_CENTER;\n break;\n case ALIGN_RIGHT:\n flags |= gfx::Canvas::TEXT_ALIGN_RIGHT;\n break;\n }\n return flags;\n}\n\ngfx::Rect Label::GetAvailableRect() const {\n gfx::Rect bounds(gfx::Point(), size());\n gfx::Insets insets(GetInsets());\n bounds.Inset(insets.left(), insets.top(), insets.right(), insets.bottom());\n return bounds;\n}\n\n} \/\/ namespace views\n<commit_msg>Fix regression from Label fixes -- I forgot to make GetHeightForWidth() actually care about the provided width for multi-line text. Oops.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/label.h\"\n\n#include <cmath>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/text_elider.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/logging.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"gfx\/canvas.h\"\n#include \"gfx\/color_utils.h\"\n#include \"gfx\/font.h\"\n#include \"gfx\/insets.h\"\n#include \"views\/background.h\"\n\nnamespace views {\n\n\/\/ static\nconst char Label::kViewClassName[] = \"views\/Label\";\nSkColor Label::kEnabledColor, Label::kDisabledColor;\n\nstatic const int kFocusBorderPadding = 1;\n\nLabel::Label() {\n Init(std::wstring(), GetDefaultFont());\n}\n\nLabel::Label(const std::wstring& text) {\n Init(text, GetDefaultFont());\n}\n\nLabel::Label(const std::wstring& text, const gfx::Font& font) {\n Init(text, font);\n}\n\nLabel::~Label() {\n}\n\ngfx::Size Label::GetPreferredSize() {\n \/\/ Return a size of (0, 0) if the label is not visible and if the\n \/\/ collapse_when_hidden_ flag is set.\n \/\/ TODO(munjal): This logic probably belongs to the View class. But for now,\n \/\/ put it here since putting it in View class means all inheriting classes\n \/\/ need ot respect the collapse_when_hidden_ flag.\n if (!IsVisible() && collapse_when_hidden_)\n return gfx::Size();\n\n gfx::Size prefsize(GetTextSize());\n gfx::Insets insets = GetInsets();\n prefsize.Enlarge(insets.width(), insets.height());\n return prefsize;\n}\n\nint Label::GetBaseline() {\n return GetInsets().top() + font_.baseline();\n}\n\nint Label::GetHeightForWidth(int w) {\n if (!is_multi_line_)\n return View::GetHeightForWidth(w);\n\n w = std::max(0, w - GetInsets().width());\n int h = font_.height();\n gfx::Canvas::SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());\n return h + GetInsets().height();\n}\n\nvoid Label::DidChangeBounds(const gfx::Rect& previous,\n const gfx::Rect& current) {\n text_size_valid_ &= !is_multi_line_;\n}\n\nvoid Label::Paint(gfx::Canvas* canvas) {\n PaintBackground(canvas);\n std::wstring paint_text;\n gfx::Rect text_bounds;\n int flags = 0;\n CalculateDrawStringParams(&paint_text, &text_bounds, &flags);\n canvas->DrawStringInt(paint_text, font_, color_,\n text_bounds.x(), text_bounds.y(),\n text_bounds.width(), text_bounds.height(), flags);\n\n if (HasFocus() || paint_as_focused_) {\n text_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding);\n \/\/ If the label is a single line of text, then the computed text bound\n \/\/ corresponds directly to the text being drawn and no mirroring is needed\n \/\/ for the RTL case. For multiline text, the text bound is an estimation\n \/\/ and is recomputed in gfx::Canvas::SizeStringInt(). For multiline text\n \/\/ in RTL, we need to take mirroring into account when computing the focus\n \/\/ rectangle.\n if (flags & gfx::Canvas::MULTI_LINE)\n text_bounds.set_x(MirroredLeftPointForRect(text_bounds));\n canvas->DrawFocusRect(text_bounds.x(), text_bounds.y(),\n text_bounds.width(), text_bounds.height());\n }\n}\n\nvoid Label::PaintBackground(gfx::Canvas* canvas) {\n const Background* bg = contains_mouse_ ? GetMouseOverBackground() : NULL;\n if (!bg)\n bg = background();\n if (bg)\n bg->Paint(canvas, this);\n}\n\nvoid Label::SetFont(const gfx::Font& font) {\n font_ = font;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nvoid Label::SetText(const std::wstring& text) {\n text_ = text;\n url_set_ = false;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nconst std::wstring Label::GetText() const {\n return url_set_ ? UTF8ToWide(url_.spec()) : text_;\n}\n\nvoid Label::SetURL(const GURL& url) {\n url_ = url;\n text_ = UTF8ToWide(url_.spec());\n url_set_ = true;\n text_size_valid_ = false;\n SchedulePaint();\n}\n\nconst GURL Label::GetURL() const {\n return url_set_ ? url_ : GURL(WideToUTF8(text_));\n}\n\nvoid Label::SetHorizontalAlignment(Alignment a) {\n \/\/ If the View's UI layout is right-to-left and rtl_alignment_mode_ is\n \/\/ USE_UI_ALIGNMENT, we need to flip the alignment so that the alignment\n \/\/ settings take into account the text directionality.\n if (UILayoutIsRightToLeft() && (rtl_alignment_mode_ == USE_UI_ALIGNMENT) &&\n (a != ALIGN_CENTER))\n a = (a == ALIGN_LEFT) ? ALIGN_RIGHT : ALIGN_LEFT;\n if (horiz_alignment_ != a) {\n horiz_alignment_ = a;\n SchedulePaint();\n }\n}\n\nvoid Label::SetMultiLine(bool f) {\n if (f != is_multi_line_) {\n is_multi_line_ = f;\n text_size_valid_ = false;\n SchedulePaint();\n }\n}\n\nvoid Label::SetAllowCharacterBreak(bool f) {\n if (f != allow_character_break_) {\n allow_character_break_ = f;\n text_size_valid_ = false;\n SchedulePaint();\n }\n}\n\nvoid Label::SetTooltipText(const std::wstring& tooltip_text) {\n tooltip_text_ = tooltip_text;\n}\n\nbool Label::GetTooltipText(const gfx::Point& p, std::wstring* tooltip) {\n DCHECK(tooltip);\n\n \/\/ If a tooltip has been explicitly set, use it.\n if (!tooltip_text_.empty()) {\n tooltip->assign(tooltip_text_);\n return true;\n }\n\n \/\/ Show the full text if the text does not fit.\n if (!is_multi_line_ && font_.GetStringWidth(text_) > width()) {\n *tooltip = text_;\n return true;\n }\n return false;\n}\n\nvoid Label::OnMouseMoved(const MouseEvent& e) {\n UpdateContainsMouse(e);\n}\n\nvoid Label::OnMouseEntered(const MouseEvent& event) {\n UpdateContainsMouse(event);\n}\n\nvoid Label::OnMouseExited(const MouseEvent& event) {\n SetContainsMouse(false);\n}\n\nvoid Label::SetMouseOverBackground(Background* background) {\n mouse_over_background_.reset(background);\n}\n\nconst Background* Label::GetMouseOverBackground() const {\n return mouse_over_background_.get();\n}\n\nvoid Label::SetEnabled(bool enabled) {\n if (enabled == enabled_)\n return;\n View::SetEnabled(enabled);\n SetColor(enabled ? kEnabledColor : kDisabledColor);\n}\n\ngfx::Insets Label::GetInsets() const {\n gfx::Insets insets = View::GetInsets();\n if (IsFocusable() || has_focus_border_) {\n insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,\n kFocusBorderPadding, kFocusBorderPadding);\n }\n return insets;\n}\n\nvoid Label::SizeToFit(int max_width) {\n DCHECK(is_multi_line_);\n\n std::vector<std::wstring> lines;\n SplitString(text_, L'\\n', &lines);\n\n int label_width = 0;\n for (std::vector<std::wstring>::const_iterator iter = lines.begin();\n iter != lines.end(); ++iter)\n label_width = std::max(label_width, font_.GetStringWidth(*iter));\n\n label_width += GetInsets().width();\n\n if (max_width > 0)\n label_width = std::min(label_width, max_width);\n\n SetBounds(x(), y(), label_width, 0);\n SizeToPreferredSize();\n}\n\nbool Label::GetAccessibleRole(AccessibilityTypes::Role* role) {\n DCHECK(role);\n\n *role = AccessibilityTypes::ROLE_TEXT;\n return true;\n}\n\nbool Label::GetAccessibleName(std::wstring* name) {\n DCHECK(name);\n *name = GetText();\n return !name->empty();\n}\n\nbool Label::GetAccessibleState(AccessibilityTypes::State* state) {\n DCHECK(state);\n\n *state = AccessibilityTypes::STATE_READONLY;\n return true;\n}\n\nvoid Label::SetHasFocusBorder(bool has_focus_border) {\n has_focus_border_ = has_focus_border;\n text_size_valid_ &= !is_multi_line_;\n}\n\n\/\/ static\ngfx::Font Label::GetDefaultFont() {\n return ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);\n}\n\nvoid Label::Init(const std::wstring& text, const gfx::Font& font) {\n static bool initialized = false;\n if (!initialized) {\n#if defined(OS_WIN)\n kEnabledColor = color_utils::GetSysSkColor(COLOR_WINDOWTEXT);\n kDisabledColor = color_utils::GetSysSkColor(COLOR_GRAYTEXT);\n#else\n \/\/ TODO(beng): source from theme provider.\n kEnabledColor = SK_ColorBLACK;\n kDisabledColor = SK_ColorGRAY;\n#endif\n\n initialized = true;\n }\n\n contains_mouse_ = false;\n font_ = font;\n text_size_valid_ = false;\n SetText(text);\n url_set_ = false;\n color_ = kEnabledColor;\n horiz_alignment_ = ALIGN_CENTER;\n is_multi_line_ = false;\n allow_character_break_ = false;\n collapse_when_hidden_ = false;\n rtl_alignment_mode_ = USE_UI_ALIGNMENT;\n paint_as_focused_ = false;\n has_focus_border_ = false;\n}\n\nvoid Label::CalculateDrawStringParams(std::wstring* paint_text,\n gfx::Rect* text_bounds,\n int* flags) const {\n DCHECK(paint_text && text_bounds && flags);\n\n if (url_set_) {\n \/\/ TODO(jungshik) : Figure out how to get 'intl.accept_languages'\n \/\/ preference and use it when calling ElideUrl.\n *paint_text = gfx::ElideUrl(url_, font_, width(), std::wstring());\n\n \/\/ An URLs is always treated as an LTR text and therefore we should\n \/\/ explicitly mark it as such if the locale is RTL so that URLs containing\n \/\/ Hebrew or Arabic characters are displayed correctly.\n \/\/\n \/\/ Note that we don't check the View's UI layout setting in order to\n \/\/ determine whether or not to insert the special Unicode formatting\n \/\/ characters. We use the locale settings because an URL is always treated\n \/\/ as an LTR string, even if its containing view does not use an RTL UI\n \/\/ layout.\n if (base::i18n::IsRTL())\n base::i18n::WrapStringWithLTRFormatting(paint_text);\n } else {\n *paint_text = text_;\n }\n\n *text_bounds = GetTextBounds();\n *flags = ComputeMultiLineFlags();\n}\n\nvoid Label::UpdateContainsMouse(const MouseEvent& event) {\n SetContainsMouse(GetTextBounds().Contains(event.x(), event.y()));\n}\n\nvoid Label::SetContainsMouse(bool contains_mouse) {\n if (contains_mouse_ == contains_mouse)\n return;\n contains_mouse_ = contains_mouse;\n if (GetMouseOverBackground())\n SchedulePaint();\n}\n\ngfx::Rect Label::GetTextBounds() const {\n gfx::Rect available_rect(GetAvailableRect());\n gfx::Size text_size(GetTextSize());\n text_size.set_width(std::min(available_rect.width(), text_size.width()));\n\n gfx::Insets insets = GetInsets();\n gfx::Point text_origin(insets.left(), insets.top());\n switch (horiz_alignment_) {\n case ALIGN_LEFT:\n break;\n case ALIGN_CENTER:\n \/\/ We put any extra margin pixel on the left rather than the right, since\n \/\/ GetTextExtentPoint32() can report a value one too large on the right.\n text_origin.Offset((available_rect.width() + 1 - text_size.width()) \/ 2,\n 0);\n break;\n case ALIGN_RIGHT:\n text_origin.set_x(available_rect.right() - text_size.width());\n break;\n default:\n NOTREACHED();\n break;\n }\n text_origin.Offset(0,\n std::max(0, (available_rect.height() - text_size.height())) \/ 2);\n return gfx::Rect(text_origin, text_size);\n}\n\ngfx::Size Label::GetTextSize() const {\n if (!text_size_valid_) {\n int w = GetAvailableRect().width();\n int h = font_.height();\n \/\/ For single-line strings, ignore the available width and calculate how\n \/\/ wide the text wants to be.\n int flags = ComputeMultiLineFlags();\n if (!is_multi_line_)\n flags |= gfx::Canvas::NO_ELLIPSIS;\n gfx::Canvas::SizeStringInt(text_, font_, &w, &h, flags);\n text_size_.SetSize(w, h);\n text_size_valid_ = true;\n }\n\n return text_size_;\n}\n\nint Label::ComputeMultiLineFlags() const {\n if (!is_multi_line_)\n return 0;\n\n int flags = gfx::Canvas::MULTI_LINE;\n#if !defined(OS_WIN)\n \/\/ Don't elide multiline labels on Linux.\n \/\/ Todo(davemoore): Do we depend on eliding multiline text?\n \/\/ Pango insists on limiting the number of lines to one if text is\n \/\/ elided. You can get around this if you can pass a maximum height\n \/\/ but we don't currently have that data when we call the pango code.\n flags |= gfx::Canvas::NO_ELLIPSIS;\n#endif\n if (allow_character_break_)\n flags |= gfx::Canvas::CHARACTER_BREAK;\n switch (horiz_alignment_) {\n case ALIGN_LEFT:\n flags |= gfx::Canvas::TEXT_ALIGN_LEFT;\n break;\n case ALIGN_CENTER:\n flags |= gfx::Canvas::TEXT_ALIGN_CENTER;\n break;\n case ALIGN_RIGHT:\n flags |= gfx::Canvas::TEXT_ALIGN_RIGHT;\n break;\n }\n return flags;\n}\n\ngfx::Rect Label::GetAvailableRect() const {\n gfx::Rect bounds(gfx::Point(), size());\n gfx::Insets insets(GetInsets());\n bounds.Inset(insets.left(), insets.top(), insets.right(), insets.bottom());\n return bounds;\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLESPixelFormat.h\"\n\n#include \"OgreRoot.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreBitwise.h\"\n\n\nnamespace Ogre {\n GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n return GL_ALPHA;\n\n case PF_L8:\n case PF_L16:\n case PF_FLOAT16_R:\n case PF_FLOAT32_R:\n return GL_LUMINANCE;\n\n case PF_BYTE_LA:\n case PF_SHORT_GR:\n case PF_FLOAT16_GR:\n case PF_FLOAT32_GR:\n return GL_LUMINANCE_ALPHA;\n\n \/\/ PVR compressed formats\n case PF_PVR_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVR_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVR_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVR_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n \n case PF_R3G3B2:\n case PF_R5G6B5:\n case PF_FLOAT16_RGB:\n case PF_FLOAT32_RGB:\n case PF_SHORT_RGB:\n return GL_RGB;\n\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n case PF_A2R10G10B10:\n\/\/ This case in incorrect, swaps R & B channels\n\/\/ return GL_BGRA;\n\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_A2B10G10R10:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n return GL_RGBA;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n \/\/ Formats are in native endian, so R8G8B8 on little endian is\n \/\/ BGR, on big endian it is RGB.\n case PF_R8G8B8:\n return GL_RGB;\n case PF_B8G8R8:\n return 0;\n#else\n case PF_R8G8B8:\n return 0;\n case PF_B8G8R8:\n return GL_RGB;\n#endif\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n case PF_B5G6R5:\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n case PF_L8:\n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_BYTE_LA:\n case PF_PVR_RGB2:\n case PF_PVR_RGB4:\n case PF_PVR_RGBA2:\n case PF_PVR_RGBA4:\n return GL_UNSIGNED_BYTE;\n case PF_R5G6B5:\n case PF_B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n case PF_L16:\n return GL_UNSIGNED_SHORT;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_B8G8R8A8:\n return GL_UNSIGNED_BYTE;\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#else\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_BYTE;\n case PF_B8G8R8A8:\n case PF_R8G8B8A8:\n return 0;\n#endif\n\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n return GL_FLOAT;\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n return GL_UNSIGNED_SHORT;\n\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_RGBA:\n case PF_R3G3B2:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n \/\/ TODO not supported\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)\n {\n switch (fmt)\n {\n case PF_L8:\n return GL_LUMINANCE;\n\n case PF_A8:\n return GL_ALPHA;\n\n case PF_BYTE_LA:\n return GL_LUMINANCE_ALPHA;\n\n case PF_PVR_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVR_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVR_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVR_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n \n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_X8B8G8R8:\n case PF_X8R8G8B8:\n \/\/ DJR - Commenting this out resolves texture problems on iPhone\n\/\/ if (!hwGamma)\n\/\/ {\n\/\/ return GL_RGB;\n\/\/ }\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n if (!hwGamma)\n {\n return GL_RGBA;\n }\n case PF_A4L4:\n case PF_L16:\n case PF_A4R4G4B4:\n case PF_R3G3B2:\n case PF_A1R5G5B5:\n case PF_R5G6B5:\n case PF_B5G6R5:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,\n bool hwGamma)\n {\n GLenum format = getGLInternalFormat(mFormat, hwGamma);\n if (format==0)\n {\n if (hwGamma)\n {\n \/\/ TODO not supported\n return 0;\n }\n else\n {\n return GL_RGBA;\n }\n }\n else\n {\n return format;\n }\n }\n\n PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt)\n {\n switch (fmt)\n {\n case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:\n return PF_PVR_RGB2;\n case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:\n return PF_PVR_RGBA2;\n case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:\n return PF_PVR_RGB4;\n case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:\n return PF_PVR_RGBA4;\n case GL_LUMINANCE:\n return PF_L8;\n case GL_ALPHA:\n return PF_A8;\n case GL_LUMINANCE_ALPHA:\n return PF_BYTE_LA;\n case GL_RGB:\n return PF_X8R8G8B8;\n case GL_RGBA:\n return PF_A8R8G8B8;\n#ifdef GL_BGRA\n case GL_BGRA:\n#endif\n\/\/ return PF_X8B8G8R8;\n default:\n \/\/TODO: not supported\n return PF_A8R8G8B8;\n };\n }\n\n size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,\n PixelFormat format)\n {\n size_t count = 0;\n\n do {\n if (width > 1)\n {\n width = width \/ 2;\n }\n if (height > 1)\n {\n height = height \/ 2;\n }\n if (depth > 1)\n {\n depth = depth \/ 2;\n }\n \/*\n NOT needed, compressed formats will have mipmaps up to 1x1\n if(PixelUtil::isValidExtent(width, height, depth, format))\n count ++;\n else\n break;\n *\/\n count++;\n } while (!(width == 1 && height == 1 && depth == 1));\n\n return count;\n }\n\n size_t GLESPixelUtil::optionalPO2(size_t value)\n {\n const RenderSystemCapabilities *caps =\n Root::getSingleton().getRenderSystem()->getCapabilities();\n\n if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))\n {\n return value;\n }\n else\n {\n return Bitwise::firstPO2From((uint32)value);\n }\n }\n\n PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data,\n GLenum *outputFormat)\n {\n GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format);\n if (glFormat != 0)\n {\n \/\/ format already supported\n return OGRE_NEW PixelBox(data);\n }\n\n PixelBox *converted = 0;\n\n if (data.format == PF_R8G8B8)\n {\n \/\/ Convert BGR -> RGB\n converted->format = PF_B8G8R8;\n *outputFormat = GL_RGB;\n\n converted = OGRE_NEW PixelBox(data);\n uint32 *data = (uint32 *) converted->data;\n for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)\n {\n uint32 *color = data;\n *color = (*color & 0x000000ff) << 16 |\n (*color & 0x0000FF00) |\n (*color & 0x00FF0000) >> 16;\n data += 1;\n }\n }\n\n return converted;\n }\n}\n<commit_msg>Didn't mean to check this in, PVR texture support isn't finished yet. Commenting it out for now<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLESPixelFormat.h\"\n\n#include \"OgreRoot.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreBitwise.h\"\n\n\nnamespace Ogre {\n GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n return GL_ALPHA;\n\n case PF_L8:\n case PF_L16:\n case PF_FLOAT16_R:\n case PF_FLOAT32_R:\n return GL_LUMINANCE;\n\n case PF_BYTE_LA:\n case PF_SHORT_GR:\n case PF_FLOAT16_GR:\n case PF_FLOAT32_GR:\n return GL_LUMINANCE_ALPHA;\n\n \/\/ PVR compressed formats\n\/\/ case PF_PVR_RGB2:\n\/\/ return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n\/\/ case PF_PVR_RGB4:\n\/\/ return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n\/\/ case PF_PVR_RGBA2:\n\/\/ return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n\/\/ case PF_PVR_RGBA4:\n\/\/ return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n \n case PF_R3G3B2:\n case PF_R5G6B5:\n case PF_FLOAT16_RGB:\n case PF_FLOAT32_RGB:\n case PF_SHORT_RGB:\n return GL_RGB;\n\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n case PF_A2R10G10B10:\n\/\/ This case in incorrect, swaps R & B channels\n\/\/ return GL_BGRA;\n\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_A2B10G10R10:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n return GL_RGBA;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n \/\/ Formats are in native endian, so R8G8B8 on little endian is\n \/\/ BGR, on big endian it is RGB.\n case PF_R8G8B8:\n return GL_RGB;\n case PF_B8G8R8:\n return 0;\n#else\n case PF_R8G8B8:\n return 0;\n case PF_B8G8R8:\n return GL_RGB;\n#endif\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n case PF_B5G6R5:\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n case PF_L8:\n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_BYTE_LA:\n\/\/ case PF_PVR_RGB2:\n\/\/ case PF_PVR_RGB4:\n\/\/ case PF_PVR_RGBA2:\n\/\/ case PF_PVR_RGBA4:\n return GL_UNSIGNED_BYTE;\n case PF_R5G6B5:\n case PF_B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n case PF_L16:\n return GL_UNSIGNED_SHORT;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_B8G8R8A8:\n return GL_UNSIGNED_BYTE;\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#else\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_BYTE;\n case PF_B8G8R8A8:\n case PF_R8G8B8A8:\n return 0;\n#endif\n\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n return GL_FLOAT;\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n return GL_UNSIGNED_SHORT;\n\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_RGBA:\n case PF_R3G3B2:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n \/\/ TODO not supported\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)\n {\n switch (fmt)\n {\n case PF_L8:\n return GL_LUMINANCE;\n\n case PF_A8:\n return GL_ALPHA;\n\n case PF_BYTE_LA:\n return GL_LUMINANCE_ALPHA;\n\n\/\/ case PF_PVR_RGB2:\n\/\/ return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n\/\/ case PF_PVR_RGB4:\n\/\/ return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n\/\/ case PF_PVR_RGBA2:\n\/\/ return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n\/\/ case PF_PVR_RGBA4:\n\/\/ return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n \n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_X8B8G8R8:\n case PF_X8R8G8B8:\n \/\/ DJR - Commenting this out resolves texture problems on iPhone\n\/\/ if (!hwGamma)\n\/\/ {\n\/\/ return GL_RGB;\n\/\/ }\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n if (!hwGamma)\n {\n return GL_RGBA;\n }\n case PF_A4L4:\n case PF_L16:\n case PF_A4R4G4B4:\n case PF_R3G3B2:\n case PF_A1R5G5B5:\n case PF_R5G6B5:\n case PF_B5G6R5:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n default:\n return 0;\n }\n }\n\n GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,\n bool hwGamma)\n {\n GLenum format = getGLInternalFormat(mFormat, hwGamma);\n if (format==0)\n {\n if (hwGamma)\n {\n \/\/ TODO not supported\n return 0;\n }\n else\n {\n return GL_RGBA;\n }\n }\n else\n {\n return format;\n }\n }\n\n PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt)\n {\n switch (fmt)\n {\n\/\/ case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:\n\/\/ return PF_PVR_RGB2;\n\/\/ case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:\n\/\/ return PF_PVR_RGBA2;\n\/\/ case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:\n\/\/ return PF_PVR_RGB4;\n\/\/ case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:\n\/\/ return PF_PVR_RGBA4;\n case GL_LUMINANCE:\n return PF_L8;\n case GL_ALPHA:\n return PF_A8;\n case GL_LUMINANCE_ALPHA:\n return PF_BYTE_LA;\n case GL_RGB:\n return PF_X8R8G8B8;\n case GL_RGBA:\n return PF_A8R8G8B8;\n#ifdef GL_BGRA\n case GL_BGRA:\n#endif\n\/\/ return PF_X8B8G8R8;\n default:\n \/\/TODO: not supported\n return PF_A8R8G8B8;\n };\n }\n\n size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,\n PixelFormat format)\n {\n size_t count = 0;\n\n do {\n if (width > 1)\n {\n width = width \/ 2;\n }\n if (height > 1)\n {\n height = height \/ 2;\n }\n if (depth > 1)\n {\n depth = depth \/ 2;\n }\n \/*\n NOT needed, compressed formats will have mipmaps up to 1x1\n if(PixelUtil::isValidExtent(width, height, depth, format))\n count ++;\n else\n break;\n *\/\n count++;\n } while (!(width == 1 && height == 1 && depth == 1));\n\n return count;\n }\n\n size_t GLESPixelUtil::optionalPO2(size_t value)\n {\n const RenderSystemCapabilities *caps =\n Root::getSingleton().getRenderSystem()->getCapabilities();\n\n if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))\n {\n return value;\n }\n else\n {\n return Bitwise::firstPO2From((uint32)value);\n }\n }\n\n PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data,\n GLenum *outputFormat)\n {\n GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format);\n if (glFormat != 0)\n {\n \/\/ format already supported\n return OGRE_NEW PixelBox(data);\n }\n\n PixelBox *converted = 0;\n\n if (data.format == PF_R8G8B8)\n {\n \/\/ Convert BGR -> RGB\n converted->format = PF_B8G8R8;\n *outputFormat = GL_RGB;\n\n converted = OGRE_NEW PixelBox(data);\n uint32 *data = (uint32 *) converted->data;\n for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)\n {\n uint32 *color = data;\n *color = (*color & 0x000000ff) << 16 |\n (*color & 0x0000FF00) |\n (*color & 0x00FF0000) >> 16;\n data += 1;\n }\n }\n\n return converted;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/Author: John Xu. 6\/23\/2019\n\/\/Initial code drafted on 6\/21\/2019 on a flight back from Plantation, FL\n\/\/\n\/\/The initial problem was an Amazon phone screen problem: print out the top K number from a given array of integers\n\/\/\n\/\/Initally the answer should be simple: take each integer from the array and insert into a priority queue and then\n\/\/do a loop to pop from this prioroty queue to print out each of the integer\n\/\/\n\/\/Then later on, it is asked, what if the array is so big, such as comming from a stream, and does not fit into the memory ?\n\/\/My immediate response was: once we reached size K for the priority queue, we remove the last element before insert the\n\/\/new element into the priority queue, if the new element is larger than the last element of the priority queue.\n\/\/\n\/\/ Above immediate response has following defects: \n\/\/ \n\/\/ 1) priority queue does not have a method to access or remove the last element\n\/\/ regular queue has push, pop, front, back, size, empty. \n\/\/ dequeue has push_back, push_front, pop_back, pop_front, size, empty\n\/\/ priority_queue has push, pop, top, size, empty\n\/\/\n\/\/ 2) over use of priority queue may be too slow. Priority queue better used for cases where the data is really used as\n\/\/ a queue structure, where processed elements are gone from the storage, where no need to keep the historical top K\n\/\/ element. \n\/\/\n\/\/ 3) If we want to keep the historical top K element from a unlimited stream inout, it is more efficient to maintain a \n\/\/ dynamic array of size K. Maintain the array sorted from large to small. When new element comes in, if it is smaller\n\/\/ than the last one, ignore it. Otherwise, remove the last one, and shift every element one position to next one if that\n\/\/ element is smaller than the new one, then insert the new one at the end of the shift. \n\/\/\n\n\/\/example of keep top 3 element from a unlimited stream of integers: top3\n\/\/ generic cases: topk\n\/\/\n\/\/ compiling instruction: g++ --std=c++17 topk.cpp -o topk\n\n\n#include <fstream>\n#include <iostream>\n#include <filesystem>\n\n#define MIN_INT -65535\n\nvoid top3(char* filename)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n while (! fstrm.eof()) {\n fstrm >> number;\n if (number > top1) {\n top2 = top1; \n top1 = number;\n }\n else if (number > top2){\n top3 = top2; \n top2 = number;\n }\n else if (number > top3)\n top3 = number;\n\n }\n cout << top1 << endl << top2 << endl << top3 << endl;\n}\n\nvoid topk(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n arr[i] = MIN_INT;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n for (i = K-1; i >= 0; i--) {\n cout << \" number = \" << number << \" i = \" << i << endl; \/\/debug\n if (number < arr[i] ) \/\/ arr[i] > number > arr[i+1]\n break;\n }\n\n if (i < 0)\n i = 0;\n \n int j = K-1;\n for (j=K-1; j>i; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[i] = number;\n\n cout << \" i = \" << i << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\nvoid topk2(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n arr[i] = MIN_INT;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n int l =0;\n for (i = 0; i < K; i++) {\n if ( number > arr[i]) {\n l = i; \/\/this will fix the uncertainty of value i\n break;\n }\n }\n\n int j = K-1;\n for (j=K-1; j>l; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[l] = number;\n\n cout << \" l = \" << l << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\nvoid topk3(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n arr[i] = MIN_INT;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n if (!fstrm)\n break;\n\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n int l =0;\n for (i = 0; i < K; i++) {\n if ( number > arr[i]) {\n l = i; \/\/this will fix the uncertainty of value i\n break;\n }\n }\n\n int j = K-1;\n for (j=K-1; j>l; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[l] = number;\n\n cout << \" l = \" << l << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\nint main(int argc, char* argv[])\n{\n int K = atoi(argv[2]);\n topk3(argv[1], K);\n return 0;\n}\n\n\n\/\/above version still have some bugs. an input of 1, 2, 3, 4, 5, 6 with command top example.txt 9\n\/\/ will output 6, 6, 5, 4, 3, 2, 1, -65535, -65535. When we expect 6, 5, 4, 3, 2, 1, -65535, -65535\n\/\/ an input of 5,4,3,2,1,0 with top example2.txt 9 will output 4,3,2,1,0,0,5, -65535, -65535\n\n\n\/\/ Future modified versions will need to be worked on and put in topk2, topk3, ..., etc\n\/\/\n\/\/ topk2 has less bug than topk, but testing data still shows 6,6,5,4,3,2 for example.txt and 0,5,4,3,2,1 for\n\/\/ example2.txt. This is due to the last number get read twice in the stream. \n\/* \n l = 0 number = 1\n l = 0 number = 2\n l = 0 number = 3\n l = 0 number = 4\n l = 0 number = 5\n l = 0 number = 6\n l = 1 number = 6\n\n l = 0 number = 5\n l = 1 number = 4\n l = 2 number = 3\n l = 3 number = 2\n l = 4 number = 1\n l = 5 number = 0\n l = 0 number = 0\n\n*\/\n\n\/\/\n\/\/ topk3 fixed above bug. We check if last read is successful or not before using the data we thought we got from the read.\n\/\/ if it failed, the fstrm >> number will be invalid but the data in number is still good at its last value;<commit_msg>used INT_MIN and #include <climits to make use of INT_MIN<commit_after>\/\/Author: John Xu. 6\/23\/2019\n\/\/Initial code drafted on 6\/21\/2019 on a flight back from Plantation, FL\n\/\/\n\/\/The initial problem was an Amazon phone screen problem: print out the top K number from a given array of integers\n\/\/\n\/\/Initally the answer should be simple: take each integer from the array and insert into a priority queue and then\n\/\/do a loop to pop from this prioroty queue to print out each of the integer\n\/\/\n\/\/Then later on, it is asked, what if the array is so big, such as comming from a stream, and does not fit into the memory ?\n\/\/My immediate response was: once we reached size K for the priority queue, we remove the last element before insert the\n\/\/new element into the priority queue, if the new element is larger than the last element of the priority queue.\n\/\/\n\/\/ Above immediate response has following defects: \n\/\/ \n\/\/ 1) priority queue does not have a method to access or remove the last element\n\/\/ regular queue has push, pop, front, back, size, empty. \n\/\/ dequeue has push_back, push_front, pop_back, pop_front, size, empty\n\/\/ priority_queue has push, pop, top, size, empty\n\/\/\n\/\/ 2) over use of priority queue may be too slow. Priority queue better used for cases where the data is really used as\n\/\/ a queue structure, where processed elements are gone from the storage, where no need to keep the historical top K\n\/\/ element. \n\/\/\n\/\/ 3) If we want to keep the historical top K element from a unlimited stream inout, it is more efficient to maintain a \n\/\/ dynamic array of size K. Maintain the array sorted from large to small. When new element comes in, if it is smaller\n\/\/ than the last one, ignore it. Otherwise, remove the last one, and shift every element one position to next one if that\n\/\/ element is smaller than the new one, then insert the new one at the end of the shift. \n\/\/\n\n\/\/example of keep top 3 element from a unlimited stream of integers: top3\n\/\/ generic cases: topk\n\/\/\n\/\/ compiling instruction: g++ --std=c++17 topk.cpp -o topk\n\n\n#include <fstream>\n#include <iostream>\n#include <filesystem>\n\n#define MIN_INT -65535\n\nvoid top3(char* filename)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n while (! fstrm.eof()) {\n fstrm >> number;\n if (number > top1) {\n top2 = top1; \n top1 = number;\n }\n else if (number > top2){\n top3 = top2; \n top2 = number;\n }\n else if (number > top3)\n top3 = number;\n\n }\n cout << top1 << endl << top2 << endl << top3 << endl;\n}\n\nvoid topk(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n arr[i] = MIN_INT;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n for (i = K-1; i >= 0; i--) {\n cout << \" number = \" << number << \" i = \" << i << endl; \/\/debug\n if (number < arr[i] ) \/\/ arr[i] > number > arr[i+1]\n break;\n }\n\n if (i < 0)\n i = 0;\n \n int j = K-1;\n for (j=K-1; j>i; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[i] = number;\n\n cout << \" i = \" << i << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\nvoid topk2(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n arr[i] = MIN_INT;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n int l =0;\n for (i = 0; i < K; i++) {\n if ( number > arr[i]) {\n l = i; \/\/this will fix the uncertainty of value i\n break;\n }\n }\n\n int j = K-1;\n for (j=K-1; j>l; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[l] = number;\n\n cout << \" l = \" << l << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\n#include <climits>\nvoid topk3(char* filename, int K)\n{\n using namespace std;\n namespace fs = std::filesystem;\n fs::path fp {filename};\n if (!fs::exists(fp)) {\n cout << \"file \" << filename << \" not exist\" << endl;\n return;\n }\n\n ifstream fstrm(filename);\n\n\/\/ int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;\n int number;\n int arr[K];\n\n for (int i=0; i<K; i++)\n\/\/ arr[i] = MIN_INT;\n arr[i] = INT_MIN;\n\n while (! fstrm.eof()) {\n\n fstrm >> number;\n if (!fstrm)\n break;\n\n int i = K-1;\n\n if (number < arr[K-1])\n break;\n\n int l =0;\n for (i = 0; i < K; i++) {\n if ( number > arr[i]) {\n l = i; \/\/this will fix the uncertainty of value i\n break;\n }\n }\n\n int j = K-1;\n for (j=K-1; j>l; j--) {\n arr[j] = arr[j-1];\n }\n\n arr[l] = number;\n\n cout << \" l = \" << l << \" number = \" << number << endl;\n }\n\n fstrm.close();\n\n for (int i=0; i<K; i++)\n cout << arr[i] << endl;\n\n}\n\nint main(int argc, char* argv[])\n{\n int K = atoi(argv[2]);\n topk3(argv[1], K);\n return 0;\n}\n\n\n\/\/above version still have some bugs. an input of 1, 2, 3, 4, 5, 6 with command top example.txt 9\n\/\/ will output 6, 6, 5, 4, 3, 2, 1, -65535, -65535. When we expect 6, 5, 4, 3, 2, 1, -65535, -65535\n\/\/ an input of 5,4,3,2,1,0 with top example2.txt 9 will output 4,3,2,1,0,0,5, -65535, -65535\n\n\n\/\/ Future modified versions will need to be worked on and put in topk2, topk3, ..., etc\n\/\/\n\/\/ topk2 has less bug than topk, but testing data still shows 6,6,5,4,3,2 for example.txt and 0,5,4,3,2,1 for\n\/\/ example2.txt. This is due to the last number get read twice in the stream. \n\/* \n l = 0 number = 1\n l = 0 number = 2\n l = 0 number = 3\n l = 0 number = 4\n l = 0 number = 5\n l = 0 number = 6\n l = 1 number = 6\n\n l = 0 number = 5\n l = 1 number = 4\n l = 2 number = 3\n l = 3 number = 2\n l = 4 number = 1\n l = 5 number = 0\n l = 0 number = 0\n\n*\/\n\n\/\/\n\/\/ topk3 fixed above bug. We check if last read is successful or not before using the data we thought we got from the read.\n\/\/ if it failed, the fstrm >> number will be invalid but the data in number is still good at its last value;<|endoftext|>"} {"text":"<commit_before>#include \"computing_data.h\"\n#include \"bart_builder.h\"\n\n#include <deal.II\/fe\/fe_update_flags.h>\n\n\/\/ XSections::XSections (Materials& material)\n\/\/ :\n\/\/ sigt(material.GetSigT()),\n\/\/ inv_sigt(material.GetInvSigT()),\n\/\/ q(material.GetQ()),\n\/\/ q_per_ster(material.GetQPerSter()),\n\/\/ is_material_fissile(material.GetFissileIDMap()),\n\/\/ nu_sigf(material.GetNuSigf()),\n\/\/ sigs(material.GetSigS()),\n\/\/ sigs_per_ster(material.GetSigSPerSter()),\n\/\/ fiss_transfer(material.GetFissTransfer()),\n\/\/ fiss_transfer_per_ster(material.GetFissTransferPerSter()) {}\n\nXSections::XSections (MaterialBase& material)\n :\n sigt(material.GetSigT()),\n inv_sigt(material.GetInvSigT()),\n q(material.GetQ()),\n q_per_ster(material.GetQPerSter()),\n is_material_fissile(material.GetFissileIDMap()),\n nu_sigf(material.GetNuSigF()),\n sigs(material.GetSigS()),\n sigs_per_ster(material.GetSigSPerSter()),\n fiss_transfer(material.GetChiNuSigF()),\n fiss_transfer_per_ster(material.GetChiNuSigFPerSter())\n{}\n\ntemplate <int dim>\nFundamentalData<dim>::FundamentalData (dealii::ParameterHandler &prm,\n dealii::Triangulation<dim> &tria)\n :\n pcout(std::cout,\n (dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)==0)),\n \/\/material(prm),\n mesh(prm),\n mat_vec(std::shared_ptr<MatrixVector> (new MatrixVector())),\n \/\/xsec(std::shared_ptr<XSections> (new XSections(material))),\n fe_data(prm),\n dof_handler(tria) {\n MaterialProtobuf material{prm};\n xsec = std::make_shared<XSections>(material);\n bbuilders::BuildAQ<dim>(prm, aq);\n aq->MakeAQ();\n}\n\ntemplate <int dim>\nFundamentalData<dim>::~FundamentalData () {}\n\ntemplate <int dim>\nFEData<dim>::FEData (const dealii::ParameterHandler &prm) {\n bbuilders::BuildFESpaces(prm, fe);\n const dealii::UpdateFlags update_flags =\n dealii::update_values | dealii::update_gradients |\n dealii::update_quadrature_points |\n dealii::update_JxW_values;\n const dealii::UpdateFlags update_face_flags = dealii::update_normal_vectors |\n dealii::update_values | dealii::update_gradients |\n dealii::update_quadrature_points |\n dealii::update_JxW_values;\n\n for (auto &f : fe) {\n \/\/ f.first is the equation name, f.second is the correspoding FiniteElement\n \/\/ object\n \/\/ TODO: all fe use the same finite element for now.\n if (f.first!=\"nda\" && f.first!=\"tg_nda\")\n discretization[f.first] = prm.get(\"ho spatial discretization\");\n else\n discretization[f.first] = prm.get(\"nda spatial discretization\");\n p_order[f.first] = prm.get_integer(\"finite element polynomial degree\");\n q_rule[f.first] = std::shared_ptr<dealii::QGauss<dim>>(\n new dealii::QGauss<dim>(p_order[f.first]+1));\n qf_rule[f.first] = std::shared_ptr<dealii::QGauss<dim-1>>(\n new dealii::QGauss<dim-1>(p_order[f.first]+1));\n\n fv[f.first] = std::shared_ptr<dealii::FEValues<dim>> (\n new dealii::FEValues<dim> (*f.second, *q_rule[f.first], update_flags));\n\n fvf[f.first] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[f.first], update_face_flags));\n\n fvf_nei[f.first] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[f.first], update_face_flags));\n\n dofs_per_cell[f.first] = fe[f.first]->dofs_per_cell;\n n_q[f.first] = q_rule[f.first]->size();\n n_qf[f.first] = qf_rule[f.first]->size();\n\n local_dof_indices[f.first].resize (dofs_per_cell[f.first]);\n neigh_dof_indices[f.first].resize (dofs_per_cell[f.first]);\n\n if (f.first==\"nda\") {\n \/\/ corrections related objects\n q_rule[\"corr\"] = std::shared_ptr<dealii::QGauss<dim>>(\n new dealii::QGauss<dim>(p_order[f.first]+3));\n qf_rule[\"corr\"] = std::shared_ptr<dealii::QGauss<dim-1>>(\n new dealii::QGauss<dim-1>(p_order[f.first]+3));\n\n fv[\"corr\"] = std::shared_ptr<dealii::FEValues<dim>> (\n new dealii::FEValues<dim> (*f.second, *q_rule[\"corr\"], update_face_flags));\n\n fvf[\"corr\"] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[\"corr\"], update_face_flags));\n\n fvf_nei[\"corr\"] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[\"corr\"], update_face_flags));\n\n n_q[\"corr\"] = q_rule[\"corr\"]->size();\n n_qf[\"corr\"] = qf_rule[\"corr\"]->size();\n }\n }\n}\n\ntemplate <int dim>\nFEData<dim>::~FEData() {}\n\ntemplate struct FundamentalData<1>;\ntemplate struct FundamentalData<2>;\ntemplate struct FundamentalData<3>;\n\ntemplate struct FEData<1>;\ntemplate struct FEData<2>;\ntemplate struct FEData<3>;\n<commit_msg>replace BuildAQ call with new CreateAQ factory in FundamentalData class<commit_after>#include \"computing_data.h\"\n#include \"bart_builder.h\"\n\n#include <deal.II\/fe\/fe_update_flags.h>\n\nXSections::XSections (MaterialBase& material)\n :\n sigt(material.GetSigT()),\n inv_sigt(material.GetInvSigT()),\n q(material.GetQ()),\n q_per_ster(material.GetQPerSter()),\n is_material_fissile(material.GetFissileIDMap()),\n nu_sigf(material.GetNuSigF()),\n sigs(material.GetSigS()),\n sigs_per_ster(material.GetSigSPerSter()),\n fiss_transfer(material.GetChiNuSigF()),\n fiss_transfer_per_ster(material.GetChiNuSigFPerSter())\n{}\n\ntemplate <int dim>\nFundamentalData<dim>::FundamentalData (dealii::ParameterHandler &prm,\n dealii::Triangulation<dim> &tria)\n :\n pcout(std::cout,\n (dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)==0)),\n aq(AQBase<dim>::CreateAQ(prm)),\n \/\/material(prm),\n mesh(prm),\n mat_vec(std::shared_ptr<MatrixVector> (new MatrixVector())),\n \/\/xsec(std::shared_ptr<XSections> (new XSections(material))),\n fe_data(prm),\n dof_handler(tria) {\n MaterialProtobuf material{prm};\n xsec = std::make_shared<XSections>(material);\n aq->MakeAQ();\n}\n\ntemplate <int dim>\nFundamentalData<dim>::~FundamentalData () {}\n\ntemplate <int dim>\nFEData<dim>::FEData (const dealii::ParameterHandler &prm) {\n bbuilders::BuildFESpaces(prm, fe);\n const dealii::UpdateFlags update_flags =\n dealii::update_values | dealii::update_gradients |\n dealii::update_quadrature_points |\n dealii::update_JxW_values;\n const dealii::UpdateFlags update_face_flags = dealii::update_normal_vectors |\n dealii::update_values | dealii::update_gradients |\n dealii::update_quadrature_points |\n dealii::update_JxW_values;\n\n for (auto &f : fe) {\n \/\/ f.first is the equation name, f.second is the correspoding FiniteElement\n \/\/ object\n \/\/ TODO: all fe use the same finite element for now.\n if (f.first!=\"nda\" && f.first!=\"tg_nda\")\n discretization[f.first] = prm.get(\"ho spatial discretization\");\n else\n discretization[f.first] = prm.get(\"nda spatial discretization\");\n p_order[f.first] = prm.get_integer(\"finite element polynomial degree\");\n q_rule[f.first] = std::shared_ptr<dealii::QGauss<dim>>(\n new dealii::QGauss<dim>(p_order[f.first]+1));\n qf_rule[f.first] = std::shared_ptr<dealii::QGauss<dim-1>>(\n new dealii::QGauss<dim-1>(p_order[f.first]+1));\n\n fv[f.first] = std::shared_ptr<dealii::FEValues<dim>> (\n new dealii::FEValues<dim> (*f.second, *q_rule[f.first], update_flags));\n\n fvf[f.first] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[f.first], update_face_flags));\n\n fvf_nei[f.first] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[f.first], update_face_flags));\n\n dofs_per_cell[f.first] = fe[f.first]->dofs_per_cell;\n n_q[f.first] = q_rule[f.first]->size();\n n_qf[f.first] = qf_rule[f.first]->size();\n\n local_dof_indices[f.first].resize (dofs_per_cell[f.first]);\n neigh_dof_indices[f.first].resize (dofs_per_cell[f.first]);\n\n if (f.first==\"nda\") {\n \/\/ corrections related objects\n q_rule[\"corr\"] = std::shared_ptr<dealii::QGauss<dim>>(\n new dealii::QGauss<dim>(p_order[f.first]+3));\n qf_rule[\"corr\"] = std::shared_ptr<dealii::QGauss<dim-1>>(\n new dealii::QGauss<dim-1>(p_order[f.first]+3));\n\n fv[\"corr\"] = std::shared_ptr<dealii::FEValues<dim>> (\n new dealii::FEValues<dim> (*f.second, *q_rule[\"corr\"], update_face_flags));\n\n fvf[\"corr\"] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[\"corr\"], update_face_flags));\n\n fvf_nei[\"corr\"] = std::shared_ptr<dealii::FEFaceValues<dim>> (\n new dealii::FEFaceValues<dim>(\n *f.second, *qf_rule[\"corr\"], update_face_flags));\n\n n_q[\"corr\"] = q_rule[\"corr\"]->size();\n n_qf[\"corr\"] = qf_rule[\"corr\"]->size();\n }\n }\n}\n\ntemplate <int dim>\nFEData<dim>::~FEData() {}\n\ntemplate struct FundamentalData<1>;\ntemplate struct FundamentalData<2>;\ntemplate struct FundamentalData<3>;\n\ntemplate struct FEData<1>;\ntemplate struct FEData<2>;\ntemplate struct FEData<3>;\n<|endoftext|>"} {"text":"<commit_before>\/** \\file SystemdUtil.cc\n * \\brief Helper functions to use with systemd\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"SystemdUtil.h\"\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nconst std::string SYSTEMCTL_EXECUTABLE(\"systemctl\");\nconst std::string SYSTEMD_SERVICE_DIRECTORY(\"\/etc\/systemd\/system\/\");\n\n\nbool SystemdUtil::IsAvailable() {\n static const bool is_available(ExecUtil::GetOriginalCommandNameFromPID(1) == \"systemd\");\n return is_available;\n}\n\n\nvoid SystemdUtil::Reload() {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"daemon-reload\"});\n}\n\n\nvoid SystemdUtil::DisableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"disable\", unit });\n}\n\n\nvoid SystemdUtil::EnableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"enable\", unit });\n}\n\n\nvoid SystemdUtil::InstallUnit(const std::string &service_file_path) {\n std::string service_file_dirname, service_file_basename;\n FileUtil::DirnameAndBasename(service_file_path, &service_file_dirname, &service_file_basename);\n\n ExecUtil::ExecOrDie(ExecUtil::Which(\"mkdir\"), { \"-p\", SYSTEMD_SERVICE_DIRECTORY });\n FileUtil::CopyOrDie(service_file_path, SYSTEMD_SERVICE_DIRECTORY + service_file_basename);\n SystemdUtil::Reload();\n}\n\n\nbool SystemdUtil::IsUnitAvailable(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"--all\", \"list-unit-files\" }, &out, &err);\n return RegexMatcher::Matched(\"^\" + unit + \"\\\\.service\", out, RegexMatcher::MULTILINE);\n}\n\n\nbool SystemdUtil::IsUnitEnabled(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"is-enabled\", unit }, &out, &err);\n return StringUtil::StartsWith(out, \"enabled\", \/* ignore_case *\/ true);\n}\n\n\nbool SystemdUtil::IsUnitRunning(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"status\", unit }, &out, &err);\n return RegexMatcher::Matched(\"(running)\", out);\n}\n\n\nvoid SystemdUtil::RestartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"restart\", unit });\n}\n\n\nvoid SystemdUtil::StartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"start\", unit });\n}\n<commit_msg>improved SystemdUtil::IsAvailable<commit_after>\/** \\file SystemdUtil.cc\n * \\brief Helper functions to use with systemd\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"SystemdUtil.h\"\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nconst std::string SYSTEMCTL_EXECUTABLE(\"systemctl\");\nconst std::string SYSTEMD_SERVICE_DIRECTORY(\"\/etc\/systemd\/system\/\");\n\n\nbool SystemdUtil::IsAvailable() {\n \/\/ Docker: systemd not running at all (+ not installed)\n \/\/ CentOS: systemd running with pid 1\n \/\/ Ubuntu: systemd running with random pid\n static const std::unordered_set<unsigned> systemd_pids(ExecUtil::FindActivePrograms(\"systemd\"));\n return systemd_pids.size() > 0;\n}\n\n\nvoid SystemdUtil::Reload() {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"daemon-reload\"});\n}\n\n\nvoid SystemdUtil::DisableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"disable\", unit });\n}\n\n\nvoid SystemdUtil::EnableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"enable\", unit });\n}\n\n\nvoid SystemdUtil::InstallUnit(const std::string &service_file_path) {\n std::string service_file_dirname, service_file_basename;\n FileUtil::DirnameAndBasename(service_file_path, &service_file_dirname, &service_file_basename);\n\n ExecUtil::ExecOrDie(ExecUtil::Which(\"mkdir\"), { \"-p\", SYSTEMD_SERVICE_DIRECTORY });\n FileUtil::CopyOrDie(service_file_path, SYSTEMD_SERVICE_DIRECTORY + service_file_basename);\n SystemdUtil::Reload();\n}\n\n\nbool SystemdUtil::IsUnitAvailable(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"--all\", \"list-unit-files\" }, &out, &err);\n return RegexMatcher::Matched(\"^\" + unit + \"\\\\.service\", out, RegexMatcher::MULTILINE);\n}\n\n\nbool SystemdUtil::IsUnitEnabled(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"is-enabled\", unit }, &out, &err);\n return StringUtil::StartsWith(out, \"enabled\", \/* ignore_case *\/ true);\n}\n\n\nbool SystemdUtil::IsUnitRunning(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"status\", unit }, &out, &err);\n return RegexMatcher::Matched(\"(running)\", out);\n}\n\n\nvoid SystemdUtil::RestartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"restart\", unit });\n}\n\n\nvoid SystemdUtil::StartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"start\", unit });\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file SystemdUtil.cc\n * \\brief Helper functions to use with systemd\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"SystemdUtil.h\"\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nconst std::string SYSTEMCTL_EXECUTABLE(\"systemctl\");\nconst std::string SYSTEMD_SERVICE_DIRECTORY(\"\/etc\/systemd\/system\/\");\n\n\nbool SystemdUtil::IsAvailable() {\n return ExecUtil::GetOriginalCommandNameFromPID(1) == \"systemd\";\n}\n\n\nvoid SystemdUtil::Reload() {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"daemon-reload\"});\n}\n\n\nvoid SystemdUtil::DisableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"disable\", unit });\n}\n\n\nvoid SystemdUtil::EnableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"enable\", unit });\n}\n\n\nvoid SystemdUtil::InstallUnit(const std::string &service_file_path) {\n std::string service_file_dirname, service_file_basename;\n FileUtil::DirnameAndBasename(service_file_path, &service_file_dirname, &service_file_basename);\n\n ExecUtil::ExecOrDie(ExecUtil::Which(\"mkdir\"), { \"-p\", SYSTEMD_SERVICE_DIRECTORY });\n FileUtil::CopyOrDie(service_file_path, SYSTEMD_SERVICE_DIRECTORY + service_file_basename);\n SystemdUtil::Reload();\n}\n\n\nbool SystemdUtil::IsUnitAvailable(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"--all\", \"list-unit-files\" }, &out, &err);\n return RegexMatcher::Matched(\"^\" + unit + \"\\\\.service\", out, RegexMatcher::MULTILINE);\n}\n\n\nbool SystemdUtil::IsUnitEnabled(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"is-enabled\", unit }, &out, &err);\n return StringUtil::StartsWith(out, \"enabled\", \/* ignore_case *\/ true);\n}\n\n\nbool SystemdUtil::IsUnitRunning(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"status\", unit }, &out, &err);\n return RegexMatcher::Matched(\"(running)\", out);\n}\n\n\nvoid SystemdUtil::RestartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"restart\", unit });\n}\n\n\nvoid SystemdUtil::StartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"start\", unit });\n}\n<commit_msg>Cache the sucker!<commit_after>\/** \\file SystemdUtil.cc\n * \\brief Helper functions to use with systemd\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"SystemdUtil.h\"\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nconst std::string SYSTEMCTL_EXECUTABLE(\"systemctl\");\nconst std::string SYSTEMD_SERVICE_DIRECTORY(\"\/etc\/systemd\/system\/\");\n\n\nbool SystemdUtil::IsAvailable() {\n static const bool is_available(ExecUtil::GetOriginalCommandNameFromPID(1) == \"systemd\");\n return is_available;\n}\n\n\nvoid SystemdUtil::Reload() {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"daemon-reload\"});\n}\n\n\nvoid SystemdUtil::DisableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"disable\", unit });\n}\n\n\nvoid SystemdUtil::EnableUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"enable\", unit });\n}\n\n\nvoid SystemdUtil::InstallUnit(const std::string &service_file_path) {\n std::string service_file_dirname, service_file_basename;\n FileUtil::DirnameAndBasename(service_file_path, &service_file_dirname, &service_file_basename);\n\n ExecUtil::ExecOrDie(ExecUtil::Which(\"mkdir\"), { \"-p\", SYSTEMD_SERVICE_DIRECTORY });\n FileUtil::CopyOrDie(service_file_path, SYSTEMD_SERVICE_DIRECTORY + service_file_basename);\n SystemdUtil::Reload();\n}\n\n\nbool SystemdUtil::IsUnitAvailable(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"--all\", \"list-unit-files\" }, &out, &err);\n return RegexMatcher::Matched(\"^\" + unit + \"\\\\.service\", out, RegexMatcher::MULTILINE);\n}\n\n\nbool SystemdUtil::IsUnitEnabled(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"is-enabled\", unit }, &out, &err);\n return StringUtil::StartsWith(out, \"enabled\", \/* ignore_case *\/ true);\n}\n\n\nbool SystemdUtil::IsUnitRunning(const std::string &unit) {\n std::string out, err;\n ExecUtil::ExecSubcommandAndCaptureStdoutAndStderr(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"status\", unit }, &out, &err);\n return RegexMatcher::Matched(\"(running)\", out);\n}\n\n\nvoid SystemdUtil::RestartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"restart\", unit });\n}\n\n\nvoid SystemdUtil::StartUnit(const std::string &unit) {\n ExecUtil::ExecOrDie(ExecUtil::Which(SYSTEMCTL_EXECUTABLE), { \"start\", unit });\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <unistd.h>\n#include <netinet\/tcp.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <pthread.h>\n#include <errno.h>\n\n#include <json\/writer.h>\n#include <json\/reader.h>\n#include <json\/value.h>\n\n#include <grids\/define.h>\n#include <grids\/protocol.h>\n\nnamespace Grids {\n void *runEventLoopThreadEntryPoint(void *arg) {\n Protocol *gp = (Protocol *)arg;\n gp->runEventLoop();\n }\n \/*\n void *dispatchEventEntryPoint(void *arg) {\n Protocol *gp = (Protocol *)arg;\n gp->dispatchEvent();\n }\n *\/\n Protocol::Protocol() {\n sock = 0;\n finished = 0;\n pthread_mutex_init(&finishedMutex, NULL);\n eventLoopThread = (pthread_t)NULL;\n }\n\n bool Protocol::connectToNode(const char *address) {\n \/\/ look up host\n struct hostent *hp;\n struct sockaddr_in addr;\n struct timeval timeout;\n int on = 1;\n\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n\n if ((hp = gethostbyname(address)) == NULL) {\n herror(\"gethostbyname\");\n return 0;\n }\n\n bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);\n addr.sin_port = htons(GRIDS_PORT);\n addr.sin_family = AF_INET;\n\n sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);\n\n if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)) != 0) {\n std::cerr << \"Could not setsockopt TCP_NODELAY: \" << strerror(errno) << \"\\n\";\n return -1;\n }\n if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) != 0) {\n std::cerr << \"Could not setsockopt SO_RCVTIMEO: \" << strerror(errno) << \"\\n\";\n return -1;\n }\n\n if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1) {\n return 0;\n }\n\n \/\/ hooray we are connnected! initialize protocol\n sendProtocolInitiationString();\n\n return 1;\n }\n\n void Protocol::sendProtocolInitiationString() {\n protocolWrite(\"==Grids\/1.0\/JSON\");\n }\n\n int Protocol::protocolWrite(const char *str) {\n uint32_t len = strlen(str);\n uint32_t len_net = htonl(len);\n\n unsigned int outstr_len = len + 4;\n char *outstr = (char *)malloc(outstr_len);\n\n memcpy(outstr, &len_net, 4);\n memcpy((outstr + 4), str, len);\n\n int ret = write(sock, outstr, outstr_len);\n free(outstr);\n\n return ret;\n }\n\n void Protocol::closeConnection() {\n ::shutdown(sock, SHUT_RDWR); \n ::close(sock); \n }\n\n std::string Protocol::stringifyMap(gridsmap_t *m) {\n Json::FastWriter *writer = new Json::FastWriter();\n Json::Value root = mapToJsonValue(m);\n return writer->write(root);\n }\n\n void Protocol::sendRequest(std::string evt) {\n sendRequest(evt, NULL);\n }\n \n void Protocol::sendRequest(std::string evt, gridsmap_t *args) {\n if (evt.empty())\n return;\n\n if (args == NULL) {\n args = new gridsmap_t();\n }\n\n const static std::string methodkey = \"_method\";\n (*args)[methodkey] = evt;\n std::string msg = stringifyMap(args);\n\n protocolWrite(msg.c_str());\n }\n\n Json::Value Protocol::mapToJsonValue(gridsmap_t *m) {\n giterator mapIterator;\n\n Json::Value jsonVal;\n\n for(mapIterator = m->begin(); \n mapIterator != m->end();\n mapIterator++) {\n\n gridskey_t key = mapIterator->first;\n gridsval_t val = mapIterator->second;\n\n jsonVal[key] = val;\n }\n\n return jsonVal;\n }\n\n void Protocol::setEventCallback(gevent_callback_t cb, void *userData) { eventCallback = cb; eventCallbackUserData = userData; }\n\n void Protocol::runEventLoop() {\n int bytesRead;\n uint32_t incomingLength;\n char *buf;\n char *bufIncoming;\n\n while (! isFinished() && sock) {\n \/\/ read in 4 byte length of message\n bytesRead = read(sock, &incomingLength, 4);\n incomingLength = ntohl(incomingLength);\n\n \/\/std::cout << \"bytesRead: \" << bytesRead << \" incoming: \" << incomingLength << \"\\n\";\n \n if (bytesRead == -1) {\n if (errno == EAGAIN) {\n \/\/ nothing to read, do it again\n continue;\n }\n\n \/\/ uh oh, socket read error\n std::cerr << \"Socket read error: \" << strerror(errno) << \"\\n\";\n break;\n }\n\n if (bytesRead != 4) {\n std::cerr << \"read zero bytes\\n\";\n \/\/ wtf? try reading again\n continue;\n }\n\n if (incomingLength > 1024 * 1024 * 1024) {\n \/\/ not going to read in more than a gig, f that\n std::cerr << \"Got incoming message size: \" << incomingLength << \". Skipping\\n\";\n continue;\n }\n\n \/\/ TODO: run in seperate thread\n\n \/\/ allocate space for incoming message + null byte\n buf = (char *)malloc(incomingLength + 1);\n\n \/\/std::cout << \"incoming: \" << incomingLength << \"\\n\";\n uint32_t bytesRemaining = incomingLength;\n bufIncoming = buf;\n\n do {\n bytesRead = read(sock, bufIncoming, bytesRemaining);\n\n if (bytesRead > 0) {\n bytesRemaining -= bytesRead;\n bufIncoming += bytesRead;\n }\n\n \/\/std::cout << \"read: \" << bytesRead << \" remaining: \" << bytesRemaining << \"\\n\";\n \n } while ((bytesRead > 0 || errno != EAGAIN) && bytesRemaining && ! isFinished());\n buf[incomingLength] = '\\0';\n\n if (bytesRead == -1) {\n \/\/ o snap read error\n std::cerr << \"Socket read error: \" << bytesRead << \"\\n\";\n free(buf);\n break;\n }\n\n if (bytesRead == 0) {\n \/\/ not chill\n std::cerr << \"Didn't read any data when expecting message of \" << incomingLength << \" bytes\\n\";\n free(buf);\n continue;\n }\n\n if (bytesRead != incomingLength) {\n std::cerr << \"Only read \" << bytesRead << \" bytes when expecting message of \"\n << incomingLength << \" bytes\\n\";\n free(buf);\n continue;\n }\n\n \/\/ TODO: run in seperate thread\n std::string msg = buf;\n handleMessage(msg);\n \n free(buf);\n }\n\n std::cout << \"ended read thread\\n\";\n }\n\n void Protocol::handleMessage(std::string &msg) {\n std::cout << \"Got message \\\"\" << msg << \"\\\"\\n\";\n if (msg.size() < 2) return; \/\/ obv. bogus\n\n if (msg.find(\"==\", 0, 2) == 0) {\n \/\/ protocol initiation message\n } else if (msg.find(\"--\", 0, 2) == 0) {\n \/\/ encrypted protocol message\n } else {\n \/\/ assume this is json for now\n Json::Value root = parseJson(msg);\n\n \/\/ FIXME: this is slow and lame\n gridsmap_t rootMap = jsonToMap(root);\n\n Event *evt = new Event(rootMap[\"_method\"], rootMap);\n eventCallback(this, evt, eventCallbackUserData);\n delete evt;\n }\n }\n\n gridsmap_t Protocol::jsonToMap(Json::Value &root) {\n \/\/ ghetto, should fix in the future\n Json::Value::Members memberList = root.getMemberNames();\n gridsmap_t outMap;\n\n for( memberList = memberList.begin(); memberList != memberList.end(); memberList++ ) {\n outMap[*memberList] = root[*memberList];\n }\n\n return outMap;\n }\n\n\n Json::Value Protocol::parseJson(std::string &msg) {\n Json::Value root;\n Json::Reader reader;\n\n if (reader.parse(msg, root))\n return root;\n\n std::cerr << \"Could not parse JSON: \" << msg << \"\\n\";\n return Json::Value(0);\n }\n\n int Protocol::runEventLoopThreaded() {\n return pthread_create(&eventLoopThread, NULL, runEventLoopThreadEntryPoint, this);\n }\n\n void Protocol::stopEventLoopThread() {\n pthread_mutex_lock(&finishedMutex);\n finished = 1;\n pthread_mutex_unlock(&finishedMutex);\n\n if (eventLoopThread)\n pthread_join(eventLoopThread, NULL);\n }\n\n\n short Protocol::isFinished() {\n int isFinished;\n pthread_mutex_lock(&finishedMutex);\n isFinished = finished;\n pthread_mutex_unlock(&finishedMutex);\n \n return isFinished;\n } \n}\n<commit_msg>convert json value to map of strings for now. slow and ghetto but will work<commit_after>#include <iostream>\n#include <sstream>\n#include <unistd.h>\n#include <netinet\/tcp.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <pthread.h>\n#include <errno.h>\n\n#include <json\/writer.h>\n#include <json\/reader.h>\n#include <json\/value.h>\n\n#include <grids\/define.h>\n#include <grids\/protocol.h>\n\nnamespace Grids {\n void *runEventLoopThreadEntryPoint(void *arg) {\n Protocol *gp = (Protocol *)arg;\n gp->runEventLoop();\n }\n \/*\n void *dispatchEventEntryPoint(void *arg) {\n Protocol *gp = (Protocol *)arg;\n gp->dispatchEvent();\n }\n *\/\n Protocol::Protocol() {\n sock = 0;\n finished = 0;\n pthread_mutex_init(&finishedMutex, NULL);\n eventLoopThread = (pthread_t)NULL;\n }\n\n bool Protocol::connectToNode(const char *address) {\n \/\/ look up host\n struct hostent *hp;\n struct sockaddr_in addr;\n struct timeval timeout;\n int on = 1;\n\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n\n if ((hp = gethostbyname(address)) == NULL) {\n herror(\"gethostbyname\");\n return 0;\n }\n\n bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);\n addr.sin_port = htons(GRIDS_PORT);\n addr.sin_family = AF_INET;\n\n sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);\n\n if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)) != 0) {\n std::cerr << \"Could not setsockopt TCP_NODELAY: \" << strerror(errno) << \"\\n\";\n return -1;\n }\n if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) != 0) {\n std::cerr << \"Could not setsockopt SO_RCVTIMEO: \" << strerror(errno) << \"\\n\";\n return -1;\n }\n\n if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1) {\n return 0;\n }\n\n \/\/ hooray we are connnected! initialize protocol\n sendProtocolInitiationString();\n\n return 1;\n }\n\n void Protocol::sendProtocolInitiationString() {\n protocolWrite(\"==Grids\/1.0\/JSON\");\n }\n\n int Protocol::protocolWrite(const char *str) {\n uint32_t len = strlen(str);\n uint32_t len_net = htonl(len);\n\n unsigned int outstr_len = len + 4;\n char *outstr = (char *)malloc(outstr_len);\n\n memcpy(outstr, &len_net, 4);\n memcpy((outstr + 4), str, len);\n\n int ret = write(sock, outstr, outstr_len);\n free(outstr);\n\n return ret;\n }\n\n void Protocol::closeConnection() {\n ::shutdown(sock, SHUT_RDWR); \n ::close(sock); \n }\n\n std::string Protocol::stringifyMap(gridsmap_t *m) {\n Json::FastWriter *writer = new Json::FastWriter();\n Json::Value root = mapToJsonValue(m);\n return writer->write(root);\n }\n\n void Protocol::sendRequest(std::string evt) {\n sendRequest(evt, NULL);\n }\n \n void Protocol::sendRequest(std::string evt, gridsmap_t *args) {\n if (evt.empty())\n return;\n\n if (args == NULL) {\n args = new gridsmap_t();\n }\n\n const static std::string methodkey = \"_method\";\n (*args)[methodkey] = evt;\n std::string msg = stringifyMap(args);\n\n protocolWrite(msg.c_str());\n }\n\n Json::Value Protocol::mapToJsonValue(gridsmap_t *m) {\n giterator mapIterator;\n\n Json::Value jsonVal;\n\n for(mapIterator = m->begin(); \n mapIterator != m->end();\n mapIterator++) {\n\n gridskey_t key = mapIterator->first;\n gridsval_t val = mapIterator->second;\n\n jsonVal[key] = val;\n }\n\n return jsonVal;\n }\n\n void Protocol::setEventCallback(gevent_callback_t cb, void *userData) { eventCallback = cb; eventCallbackUserData = userData; }\n\n void Protocol::runEventLoop() {\n int bytesRead;\n uint32_t incomingLength;\n char *buf;\n char *bufIncoming;\n\n while (! isFinished() && sock) {\n \/\/ read in 4 byte length of message\n bytesRead = read(sock, &incomingLength, 4);\n incomingLength = ntohl(incomingLength);\n\n \/\/std::cout << \"bytesRead: \" << bytesRead << \" incoming: \" << incomingLength << \"\\n\";\n \n if (bytesRead == -1) {\n if (errno == EAGAIN) {\n \/\/ nothing to read, do it again\n continue;\n }\n\n \/\/ uh oh, socket read error\n std::cerr << \"Socket read error: \" << strerror(errno) << \"\\n\";\n break;\n }\n\n if (bytesRead != 4) {\n std::cerr << \"read zero bytes\\n\";\n \/\/ wtf? try reading again\n continue;\n }\n\n if (incomingLength > 1024 * 1024 * 1024) {\n \/\/ not going to read in more than a gig, f that\n std::cerr << \"Got incoming message size: \" << incomingLength << \". Skipping\\n\";\n continue;\n }\n\n \/\/ TODO: run in seperate thread\n\n \/\/ allocate space for incoming message + null byte\n buf = (char *)malloc(incomingLength + 1);\n\n \/\/std::cout << \"incoming: \" << incomingLength << \"\\n\";\n uint32_t bytesRemaining = incomingLength;\n bufIncoming = buf;\n\n do {\n bytesRead = read(sock, bufIncoming, bytesRemaining);\n\n if (bytesRead > 0) {\n bytesRemaining -= bytesRead;\n bufIncoming += bytesRead;\n }\n\n \/\/std::cout << \"read: \" << bytesRead << \" remaining: \" << bytesRemaining << \"\\n\";\n \n } while ((bytesRead > 0 || errno != EAGAIN) && bytesRemaining && ! isFinished());\n buf[incomingLength] = '\\0';\n\n if (bytesRead == -1) {\n \/\/ o snap read error\n std::cerr << \"Socket read error: \" << bytesRead << \"\\n\";\n free(buf);\n break;\n }\n\n if (bytesRead == 0) {\n \/\/ not chill\n std::cerr << \"Didn't read any data when expecting message of \" << incomingLength << \" bytes\\n\";\n free(buf);\n continue;\n }\n\n if (bytesRead != incomingLength) {\n std::cerr << \"Only read \" << bytesRead << \" bytes when expecting message of \"\n << incomingLength << \" bytes\\n\";\n free(buf);\n continue;\n }\n\n \/\/ TODO: run in seperate thread\n std::string msg = buf;\n handleMessage(msg);\n \n free(buf);\n }\n\n std::cout << \"ended read thread\\n\";\n }\n\n void Protocol::handleMessage(std::string &msg) {\n std::cout << \"Got message \\\"\" << msg << \"\\\"\\n\";\n if (msg.size() < 2) return; \/\/ obv. bogus\n\n if (msg.find(\"==\", 0, 2) == 0) {\n \/\/ protocol initiation message\n } else if (msg.find(\"--\", 0, 2) == 0) {\n \/\/ encrypted protocol message\n } else {\n \/\/ assume this is json for now\n Json::Value root = parseJson(msg);\n\n \/\/ FIXME: this is slow and lame\n gridsmap_t rootMap = jsonToMap(root);\n\n Event *evt = new Event(rootMap[\"_method\"], rootMap);\n eventCallback(this, evt, eventCallbackUserData);\n delete evt;\n }\n }\n\n gridsmap_t Protocol::jsonToMap(Json::Value &root) {\n \/\/ ghetto, should fix in the future\n Json::Value::Members memberList = root.getMemberNames();\n std::vector<std::string>::iterator iter;\n\n gridsmap_t outMap;\n\n for (iter = memberList.begin(); iter != memberList.end(); iter++) {\n Json::Value val = root[*iter];\n\n std::stringstream outVal;\n outVal << val;\n\n outMap[*iter] = outVal.str();\n }\n\n return outMap;\n }\n\n\n Json::Value Protocol::parseJson(std::string &msg) {\n Json::Value root;\n Json::Reader reader;\n\n if (reader.parse(msg, root))\n return root;\n\n std::cerr << \"Could not parse JSON: \" << msg << \"\\n\";\n return Json::Value(0);\n }\n\n int Protocol::runEventLoopThreaded() {\n return pthread_create(&eventLoopThread, NULL, runEventLoopThreadEntryPoint, this);\n }\n\n void Protocol::stopEventLoopThread() {\n pthread_mutex_lock(&finishedMutex);\n finished = 1;\n pthread_mutex_unlock(&finishedMutex);\n\n if (eventLoopThread)\n pthread_join(eventLoopThread, NULL);\n }\n\n\n short Protocol::isFinished() {\n int isFinished;\n pthread_mutex_lock(&finishedMutex);\n isFinished = finished;\n pthread_mutex_unlock(&finishedMutex);\n \n return isFinished;\n } \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>\n Copyright (C) 2011 Dario Freddi <dario.freddi@collabora.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"contact-request-handler.h\"\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingOperation>\n#include <TelepathyQt4\/Account>\n\n#include <KTelepathy\/error-dictionary.h>\n\n#include <QtCore\/QFutureWatcher>\n\n#include <KDebug>\n#include <KGlobal>\n#include <KAboutData>\n#include <KMenu>\n#include <KAction>\n#include <KStatusNotifierItem>\n\nQ_DECLARE_METATYPE(Tp::ContactPtr)\n\nbool kde_tp_filter_contacts_by_publication_status(const Tp::ContactPtr &contact)\n{\n return contact->publishState() == Tp::Contact::PresenceStateAsk;\n}\n\nContactRequestHandler::ContactRequestHandler(const Tp::AccountManagerPtr& am, QObject *parent)\n : QObject(parent)\n{\n m_accountManager = am;\n connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)),\n this, SLOT(onNewAccountAdded(Tp::AccountPtr)));\n\n QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();\n\n Q_FOREACH(const Tp::AccountPtr &account, accounts) {\n onNewAccountAdded(account);\n }\n\n m_noContactsAction = new KAction(i18n(\"No pending contact requests at the moment\"), this);\n m_noContactsAction->setEnabled(false);\n}\n\nContactRequestHandler::~ContactRequestHandler()\n{\n\n}\n\nvoid ContactRequestHandler::onNewAccountAdded(const Tp::AccountPtr& account)\n{\n kWarning();\n Q_ASSERT(account->isReady(Tp::Account::FeatureCore));\n\n if (account->connection()) {\n monitorPresence(account->connection());\n }\n\n connect(account.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n this, SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n}\n\nvoid ContactRequestHandler::onConnectionChanged(const Tp::ConnectionPtr& connection)\n{\n if (!connection.isNull()) {\n monitorPresence(connection);\n }\n}\n\nvoid ContactRequestHandler::monitorPresence(const Tp::ConnectionPtr &connection)\n{\n kDebug();\n connect(connection->contactManager().data(), SIGNAL(presencePublicationRequested(Tp::Contacts)),\n this, SLOT(onPresencePublicationRequested(Tp::Contacts)));\n\n connect(connection->contactManager().data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n this, SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n\n onContactManagerStateChanged(connection->contactManager(),\n connection->contactManager()->state());\n}\n\nvoid ContactRequestHandler::onContactManagerStateChanged(Tp::ContactListState state)\n{\n onContactManagerStateChanged(Tp::ContactManagerPtr(qobject_cast< Tp::ContactManager* >(sender())), state);\n}\n\nvoid ContactRequestHandler::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager,\n Tp::ContactListState state)\n{\n if (state == Tp::ContactListStateSuccess) {\n QFutureWatcher< Tp::ContactPtr > *watcher = new QFutureWatcher< Tp::ContactPtr >(this);\n connect(watcher, SIGNAL(finished()), this, SLOT(onAccountsPresenceStatusFiltered()));\n watcher->setFuture(QtConcurrent::filtered(contactManager->allKnownContacts(),\n kde_tp_filter_contacts_by_publication_status));\n\n kDebug() << \"Watcher is on\";\n } else {\n kDebug() << \"Watcher still off, state is\" << state << \"contactManager is\" << contactManager.isNull();\n }\n}\n\nvoid ContactRequestHandler::onAccountsPresenceStatusFiltered()\n{\n kDebug() << \"Watcher is here\";\n QFutureWatcher< Tp::ContactPtr > *watcher = dynamic_cast< QFutureWatcher< Tp::ContactPtr > * >(sender());\n kDebug() << \"Watcher is casted\";\n Tp::Contacts contacts = watcher->future().results().toSet();\n kDebug() << \"Watcher is used\";\n if (!contacts.isEmpty()) {\n onPresencePublicationRequested(contacts);\n }\n watcher->deleteLater();\n}\n\nvoid ContactRequestHandler::onPresencePublicationRequested(const Tp::Contacts& contacts)\n{\n kDebug() << \"New contact requested\";\n\n Q_FOREACH (const Tp::ContactPtr &contact, contacts) {\n Tp::ContactManagerPtr manager = contact->manager();\n\n if (contact->subscriptionState() == Tp::Contact::PresenceStateYes) {\n Tp::PendingOperation *op = manager->authorizePresencePublication(QList< Tp::ContactPtr >() << contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*)));\n } else {\n m_pendingContacts.insert(contact->id(), contact);\n\n updateMenus();\n\n m_notifierItem.data()->showMessage(i18n(\"New contact request\"),\n i18n(\"The contact %1 added you to its contact list\",\n contact->id()),\n QLatin1String(\"list-add-user\"));\n }\n }\n}\n\nvoid ContactRequestHandler::onFinalizeSubscriptionFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error adding contact\"),\n i18n(\"%1 has been added successfully to your contact list, \"\n \"but might be unable to see your presence. Error details: %2\",\n contact->alias(), KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n } else {\n \/\/ Yeah. All fine, so don't notify\n }\n}\n\nvoid ContactRequestHandler::updateNotifierItemTooltip()\n{\n if (!m_menuItems.size()) {\n \/\/ Set passive\n m_notifierItem.data()->setStatus(KStatusNotifierItem::Passive);\n \/\/ Add the usual \"nothing\" action, if needed\n if (!m_notifierMenu->actions().contains(m_noContactsAction)) {\n m_notifierMenu->addAction(m_noContactsAction);\n }\n\n m_notifierItem.data()->setToolTip(QLatin1String(\"list-add-user\"),\n i18n(\"No incoming contact requests\"),\n QString());\n } else {\n \/\/ Set active\n m_notifierItem.data()->setStatus(KStatusNotifierItem::Active);\n \/\/ Remove the \"nothing\" action, if needed\n if (m_notifierMenu->actions().contains(m_noContactsAction)) {\n m_notifierMenu->removeAction(m_noContactsAction);\n }\n\n m_notifierItem.data()->setToolTip(QLatin1String(\"list-add-user\"),\n i18np(\"You have 1 incoming contact request\",\n \"You have %1 incoming contact requests\",\n m_menuItems.size()),\n QString());\n }\n}\n\nvoid ContactRequestHandler::onContactRequestApproved()\n{\n QString contactId = qobject_cast<KAction*>(sender())->data().toString();\n\n if (!contactId.isEmpty()) {\n Tp::ContactPtr contact = m_pendingContacts.value(contactId);\n if (!contact.isNull()) {\n Tp::PendingOperation *op = contact->manager()->authorizePresencePublication(QList< Tp::ContactPtr >() << contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect (op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onAuthorizePresencePublicationFinished(Tp::PendingOperation*)));\n }\n }\n}\n\nvoid ContactRequestHandler::onAuthorizePresencePublicationFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error accepting contact request\"),\n i18n(\"There was an error while accepting the request: %1\",\n KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n\n \/\/ Re-enable the action\n m_menuItems.value(contact->id())->setEnabled(true);\n } else {\n \/\/ Yeah\n m_notifierItem.data()->showMessage(i18n(\"Contact request accepted\"),\n i18n(\"%1 will now be able to see your presence\",\n contact->alias()), QLatin1String(\"dialog-ok-apply\"));\n\n \/\/ If needed, reiterate the request on the other end\n if (contact->manager()->canRequestPresenceSubscription() &&\n contact->subscriptionState() == Tp::Contact::PresenceStateNo) {\n connect(contact->manager()->requestPresenceSubscription(QList< Tp::ContactPtr >() << contact),\n SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*)));\n }\n\n \/\/ Update the menu\n m_pendingContacts.remove(contact->id());\n updateMenus();\n }\n}\n\nvoid ContactRequestHandler::onContactRequestDenied()\n{\n QString contactId = qobject_cast<KAction*>(sender())->data().toString();\n\n \/\/ Disable the action in the meanwhile\n m_menuItems.value(contactId)->setEnabled(false);\n\n if (!contactId.isEmpty()) {\n Tp::ContactPtr contact = m_pendingContacts.value(contactId);\n if (!contact.isNull()) {\n Tp::PendingOperation *op = contact->manager()->removePresencePublication(QList< Tp::ContactPtr >() << contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onRemovePresencePublicationFinished(Tp::PendingOperation*)));\n }\n }\n}\n\nvoid ContactRequestHandler::onRemovePresencePublicationFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error denying contact request\"),\n i18n(\"There was an error while denying the request: %1\",\n KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n\n \/\/ Re-enable the action\n m_menuItems.value(contact->id())->setEnabled(true);\n } else {\n \/\/ Yeah\n m_notifierItem.data()->showMessage(i18n(\"Contact request denied\"),\n i18n(\"%1 will not be able to see your presence\",\n contact->alias()), QLatin1String(\"dialog-ok-apply\"));\n\n \/\/ Update the menu\n m_pendingContacts.remove(contact->id());\n updateMenus();\n }\n}\n\nvoid ContactRequestHandler::updateMenus()\n{\n if (m_notifierItem.isNull()) {\n m_notifierItem = new KStatusNotifierItem(QLatin1String(\"telepathy_kde_contact_requests\"), this);\n m_notifierItem.data()->setCategory(KStatusNotifierItem::Communications);\n m_notifierItem.data()->setStatus(KStatusNotifierItem::NeedsAttention);\n m_notifierItem.data()->setIconByName(QLatin1String(\"user-identity\"));\n m_notifierItem.data()->setAttentionIconByName(QLatin1String(\"list-add-user\"));\n m_notifierItem.data()->setStandardActionsEnabled(false);\n m_notifierItem.data()->setTitle(i18nc(\"Menu title\", \"Pending contact requests\"));\n\n m_notifierMenu = new KMenu(0);\n m_notifierMenu->addTitle(i18nc(\"Context menu title\", \"Received contact requests\"));\n\n m_notifierItem.data()->setContextMenu(m_notifierMenu);\n }\n\n kDebug() << m_pendingContacts.keys();\n\n QHash<QString, Tp::ContactPtr>::const_iterator i;\n for (i = m_pendingContacts.constBegin(); i != m_pendingContacts.constEnd(); ++i) {\n if (m_menuItems.contains(i.key())) {\n \/\/ Skip\n continue;\n }\n\n kDebug();\n Tp::ContactPtr contact = i.value();\n\n KMenu *contactMenu = new KMenu(m_notifierMenu);\n contactMenu->setTitle(i18n(\"Request from %1\", contact->alias()));\n contactMenu->setObjectName(contact->id());\n\n KAction *menuAction;\n if (!contact->publishStateMessage().isEmpty()) {\n contactMenu->addTitle(contact->publishStateMessage());\n } else {\n contactMenu->addTitle(contact->alias());\n }\n menuAction = new KAction(KIcon(QLatin1String(\"dialog-ok-apply\")), i18n(\"Approve\"), contactMenu);\n menuAction->setData(i.key());\n connect(menuAction, SIGNAL(triggered()),\n this, SLOT(onContactRequestApproved()));\n contactMenu->addAction(menuAction);\n\n menuAction = new KAction(KIcon(QLatin1String(\"dialog-close\")), i18n(\"Deny\"), contactMenu);\n menuAction->setData(i.key());\n connect(menuAction, SIGNAL(triggered()),\n this, SLOT(onContactRequestDenied()));\n contactMenu->addAction(menuAction);\n\n m_notifierMenu->addMenu(contactMenu);\n m_menuItems.insert(i.key(), contactMenu);\n }\n\n QHash<QString, KMenu*>::iterator j = m_menuItems.begin();\n while (j != m_menuItems.end()) {\n if (m_pendingContacts.contains(j.key())) {\n \/\/ Skip\n ++j;\n continue;\n }\n\n \/\/ Remove\n m_notifierMenu->removeAction(j.value()->menuAction());\n j = m_menuItems.erase(j);\n }\n\n updateNotifierItemTooltip();\n}\n\n#include \"contact-request-handler.moc\"\n<commit_msg>Handle multi-account requests with the same contact Id as if they were one, and authorize them altogether<commit_after>\/*\n Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>\n Copyright (C) 2011 Dario Freddi <dario.freddi@collabora.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"contact-request-handler.h\"\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingOperation>\n#include <TelepathyQt4\/PendingComposite>\n#include <TelepathyQt4\/Account>\n\n#include <KTelepathy\/error-dictionary.h>\n\n#include <QtCore\/QFutureWatcher>\n\n#include <KDebug>\n#include <KGlobal>\n#include <KAboutData>\n#include <KMenu>\n#include <KAction>\n#include <KStatusNotifierItem>\n\nQ_DECLARE_METATYPE(Tp::ContactPtr)\n\nbool kde_tp_filter_contacts_by_publication_status(const Tp::ContactPtr &contact)\n{\n return contact->publishState() == Tp::Contact::PresenceStateAsk;\n}\n\nContactRequestHandler::ContactRequestHandler(const Tp::AccountManagerPtr& am, QObject *parent)\n : QObject(parent)\n{\n m_accountManager = am;\n connect(m_accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)),\n this, SLOT(onNewAccountAdded(Tp::AccountPtr)));\n\n QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();\n\n Q_FOREACH(const Tp::AccountPtr &account, accounts) {\n onNewAccountAdded(account);\n }\n\n m_noContactsAction = new KAction(i18n(\"No pending contact requests at the moment\"), this);\n m_noContactsAction->setEnabled(false);\n}\n\nContactRequestHandler::~ContactRequestHandler()\n{\n\n}\n\nvoid ContactRequestHandler::onNewAccountAdded(const Tp::AccountPtr& account)\n{\n kWarning();\n Q_ASSERT(account->isReady(Tp::Account::FeatureCore));\n\n if (account->connection()) {\n monitorPresence(account->connection());\n }\n\n connect(account.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n this, SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n}\n\nvoid ContactRequestHandler::onConnectionChanged(const Tp::ConnectionPtr& connection)\n{\n if (!connection.isNull()) {\n monitorPresence(connection);\n }\n}\n\nvoid ContactRequestHandler::monitorPresence(const Tp::ConnectionPtr &connection)\n{\n kDebug();\n connect(connection->contactManager().data(), SIGNAL(presencePublicationRequested(Tp::Contacts)),\n this, SLOT(onPresencePublicationRequested(Tp::Contacts)));\n\n connect(connection->contactManager().data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n this, SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n\n onContactManagerStateChanged(connection->contactManager(),\n connection->contactManager()->state());\n}\n\nvoid ContactRequestHandler::onContactManagerStateChanged(Tp::ContactListState state)\n{\n onContactManagerStateChanged(Tp::ContactManagerPtr(qobject_cast< Tp::ContactManager* >(sender())), state);\n}\n\nvoid ContactRequestHandler::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager,\n Tp::ContactListState state)\n{\n if (state == Tp::ContactListStateSuccess) {\n QFutureWatcher< Tp::ContactPtr > *watcher = new QFutureWatcher< Tp::ContactPtr >(this);\n connect(watcher, SIGNAL(finished()), this, SLOT(onAccountsPresenceStatusFiltered()));\n watcher->setFuture(QtConcurrent::filtered(contactManager->allKnownContacts(),\n kde_tp_filter_contacts_by_publication_status));\n\n kDebug() << \"Watcher is on\";\n } else {\n kDebug() << \"Watcher still off, state is\" << state << \"contactManager is\" << contactManager.isNull();\n }\n}\n\nvoid ContactRequestHandler::onAccountsPresenceStatusFiltered()\n{\n kDebug() << \"Watcher is here\";\n QFutureWatcher< Tp::ContactPtr > *watcher = dynamic_cast< QFutureWatcher< Tp::ContactPtr > * >(sender());\n kDebug() << \"Watcher is casted\";\n Tp::Contacts contacts = watcher->future().results().toSet();\n kDebug() << \"Watcher is used\";\n if (!contacts.isEmpty()) {\n onPresencePublicationRequested(contacts);\n }\n watcher->deleteLater();\n}\n\nvoid ContactRequestHandler::onPresencePublicationRequested(const Tp::Contacts& contacts)\n{\n kDebug() << \"New contact requested\";\n\n Q_FOREACH (const Tp::ContactPtr &contact, contacts) {\n Tp::ContactManagerPtr manager = contact->manager();\n\n if (contact->subscriptionState() == Tp::Contact::PresenceStateYes) {\n Tp::PendingOperation *op = manager->authorizePresencePublication(QList< Tp::ContactPtr >() << contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*)));\n } else {\n \/\/ Handle multiaccount requests properly\n if (m_pendingContacts.contains(contact->id())) {\n \/\/ It's likely we have a simultaneous request\n bool newReq = true;\n QHash<QString, Tp::ContactPtr>::const_iterator i = m_pendingContacts.find(contact->id());\n while (i != m_pendingContacts.constEnd() && i.key() == contact->id()) {\n if (i.value().data() == contact.data()) {\n newReq = false;\n break;\n }\n ++i;\n }\n\n if (newReq) {\n \/\/ Insert multi\n m_pendingContacts.insertMulti(contact->id(), contact);\n }\n } else {\n \/\/ Simple insertion\n m_pendingContacts.insert(contact->id(), contact);\n }\n\n updateMenus();\n\n m_notifierItem.data()->showMessage(i18n(\"New contact request\"),\n i18n(\"The contact %1 added you to its contact list\",\n contact->id()),\n QLatin1String(\"list-add-user\"));\n }\n }\n}\n\nvoid ContactRequestHandler::onFinalizeSubscriptionFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error adding contact\"),\n i18n(\"%1 has been added successfully to your contact list, \"\n \"but might be unable to see your presence. Error details: %2\",\n contact->alias(), KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n } else {\n \/\/ Yeah. All fine, so don't notify\n }\n}\n\nvoid ContactRequestHandler::updateNotifierItemTooltip()\n{\n if (!m_menuItems.size()) {\n \/\/ Set passive\n m_notifierItem.data()->setStatus(KStatusNotifierItem::Passive);\n \/\/ Add the usual \"nothing\" action, if needed\n if (!m_notifierMenu->actions().contains(m_noContactsAction)) {\n m_notifierMenu->addAction(m_noContactsAction);\n }\n\n m_notifierItem.data()->setToolTip(QLatin1String(\"list-add-user\"),\n i18n(\"No incoming contact requests\"),\n QString());\n } else {\n \/\/ Set active\n m_notifierItem.data()->setStatus(KStatusNotifierItem::Active);\n \/\/ Remove the \"nothing\" action, if needed\n if (m_notifierMenu->actions().contains(m_noContactsAction)) {\n m_notifierMenu->removeAction(m_noContactsAction);\n }\n\n m_notifierItem.data()->setToolTip(QLatin1String(\"list-add-user\"),\n i18np(\"You have 1 incoming contact request\",\n \"You have %1 incoming contact requests\",\n m_menuItems.size()),\n QString());\n }\n}\n\nvoid ContactRequestHandler::onContactRequestApproved()\n{\n QString contactId = qobject_cast<KAction*>(sender())->data().toString();\n\n \/\/ Disable the action in the meanwhile\n m_menuItems.value(contactId)->setEnabled(false);\n\n if (!contactId.isEmpty()) {\n QList<Tp::PendingOperation*> operations;\n QHash<QString, Tp::ContactPtr>::const_iterator i = m_pendingContacts.find(contactId);\n while (i != m_pendingContacts.constEnd() && i.key() == contactId) {\n Tp::PendingOperation *op = i.value()->manager()->authorizePresencePublication(QList< Tp::ContactPtr >() << i.value());\n op->setProperty(\"__contact\", QVariant::fromValue(i.value()));\n operations.append(op);\n ++i;\n }\n\n \/\/ Take the first value, if any\n if (!operations.isEmpty()) {\n Tp::ContactPtr contact = m_pendingContacts.find(contactId).value();\n\n Tp::PendingComposite *op = new Tp::PendingComposite(operations, true, contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onAuthorizePresencePublicationFinished(Tp::PendingOperation*)));\n }\n }\n\n}\n\nvoid ContactRequestHandler::onAuthorizePresencePublicationFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error accepting contact request\"),\n i18n(\"There was an error while accepting the request: %1\",\n KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n\n \/\/ Re-enable the action\n m_menuItems.value(contact->id())->setEnabled(true);\n } else {\n \/\/ Yeah\n m_notifierItem.data()->showMessage(i18n(\"Contact request accepted\"),\n i18n(\"%1 will now be able to see your presence\",\n contact->alias()), QLatin1String(\"dialog-ok-apply\"));\n\n \/\/ If needed, reiterate the request on the other end\n if (contact->manager()->canRequestPresenceSubscription() &&\n contact->subscriptionState() == Tp::Contact::PresenceStateNo) {\n connect(contact->manager()->requestPresenceSubscription(QList< Tp::ContactPtr >() << contact),\n SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onFinalizeSubscriptionFinished(Tp::PendingOperation*)));\n }\n\n \/\/ Update the menu\n m_pendingContacts.remove(contact->id());\n updateMenus();\n }\n}\n\nvoid ContactRequestHandler::onContactRequestDenied()\n{\n QString contactId = qobject_cast<KAction*>(sender())->data().toString();\n\n \/\/ Disable the action in the meanwhile\n m_menuItems.value(contactId)->setEnabled(false);\n\n if (!contactId.isEmpty()) {\n QList<Tp::PendingOperation*> operations;\n QHash<QString, Tp::ContactPtr>::const_iterator i = m_pendingContacts.find(contactId);\n while (i != m_pendingContacts.constEnd() && i.key() == contactId) {\n Tp::PendingOperation *op = i.value()->manager()->removePresencePublication(QList< Tp::ContactPtr >() << i.value());\n op->setProperty(\"__contact\", QVariant::fromValue(i.value()));\n operations.append(op);\n ++i;\n }\n\n \/\/ Take the first value, if any\n if (!operations.isEmpty()) {\n Tp::ContactPtr contact = m_pendingContacts.find(contactId).value();\n\n Tp::PendingComposite *op = new Tp::PendingComposite(operations, true, contact);\n op->setProperty(\"__contact\", QVariant::fromValue(contact));\n\n connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(onRemovePresencePublicationFinished(Tp::PendingOperation*)));\n }\n }\n}\n\nvoid ContactRequestHandler::onRemovePresencePublicationFinished(Tp::PendingOperation *op)\n{\n Tp::ContactPtr contact = op->property(\"__contact\").value< Tp::ContactPtr >();\n\n if (op->isError()) {\n \/\/ ARGH\n m_notifierItem.data()->showMessage(i18n(\"Error denying contact request\"),\n i18n(\"There was an error while denying the request: %1\",\n KTp::ErrorDictionary::displayVerboseErrorMessage(op->errorName())),\n QLatin1String(\"dialog-error\"));\n\n \/\/ Re-enable the action\n m_menuItems.value(contact->id())->setEnabled(true);\n } else {\n \/\/ Yeah\n m_notifierItem.data()->showMessage(i18n(\"Contact request denied\"),\n i18n(\"%1 will not be able to see your presence\",\n contact->alias()), QLatin1String(\"dialog-ok-apply\"));\n\n \/\/ Update the menu\n m_pendingContacts.remove(contact->id());\n updateMenus();\n }\n}\n\nvoid ContactRequestHandler::updateMenus()\n{\n if (m_notifierItem.isNull()) {\n m_notifierItem = new KStatusNotifierItem(QLatin1String(\"telepathy_kde_contact_requests\"), this);\n m_notifierItem.data()->setCategory(KStatusNotifierItem::Communications);\n m_notifierItem.data()->setStatus(KStatusNotifierItem::NeedsAttention);\n m_notifierItem.data()->setIconByName(QLatin1String(\"user-identity\"));\n m_notifierItem.data()->setAttentionIconByName(QLatin1String(\"list-add-user\"));\n m_notifierItem.data()->setStandardActionsEnabled(false);\n m_notifierItem.data()->setTitle(i18nc(\"Menu title\", \"Pending contact requests\"));\n\n m_notifierMenu = new KMenu(0);\n m_notifierMenu->addTitle(i18nc(\"Context menu title\", \"Received contact requests\"));\n\n m_notifierItem.data()->setContextMenu(m_notifierMenu);\n }\n\n kDebug() << m_pendingContacts.keys();\n\n QHash<QString, Tp::ContactPtr>::const_iterator i;\n for (i = m_pendingContacts.constBegin(); i != m_pendingContacts.constEnd(); ++i) {\n if (m_menuItems.contains(i.key())) {\n \/\/ Skip\n continue;\n }\n\n kDebug();\n Tp::ContactPtr contact = i.value();\n\n KMenu *contactMenu = new KMenu(m_notifierMenu);\n contactMenu->setTitle(i18n(\"Request from %1\", contact->alias()));\n contactMenu->setObjectName(contact->id());\n\n KAction *menuAction;\n if (!contact->publishStateMessage().isEmpty()) {\n contactMenu->addTitle(contact->publishStateMessage());\n } else {\n contactMenu->addTitle(contact->alias());\n }\n menuAction = new KAction(KIcon(QLatin1String(\"dialog-ok-apply\")), i18n(\"Approve\"), contactMenu);\n menuAction->setData(i.key());\n connect(menuAction, SIGNAL(triggered()),\n this, SLOT(onContactRequestApproved()));\n contactMenu->addAction(menuAction);\n\n menuAction = new KAction(KIcon(QLatin1String(\"dialog-close\")), i18n(\"Deny\"), contactMenu);\n menuAction->setData(i.key());\n connect(menuAction, SIGNAL(triggered()),\n this, SLOT(onContactRequestDenied()));\n contactMenu->addAction(menuAction);\n\n m_notifierMenu->addMenu(contactMenu);\n m_menuItems.insert(i.key(), contactMenu);\n }\n\n QHash<QString, KMenu*>::iterator j = m_menuItems.begin();\n while (j != m_menuItems.end()) {\n if (m_pendingContacts.contains(j.key())) {\n \/\/ Skip\n ++j;\n continue;\n }\n\n \/\/ Remove\n m_notifierMenu->removeAction(j.value()->menuAction());\n j = m_menuItems.erase(j);\n }\n\n updateNotifierItemTooltip();\n}\n\n#include \"contact-request-handler.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <algorithm>\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <map>\n\n#include <malloc.h> \/\/ _alloca\n#include <stdlib.h>\n\n#include \"amxprofiler.h\"\n#include \"logprintf.h\"\n#include \"plugin.h\"\n#include \"version.h\"\n\nextern void *pAMXFunctions;\n\nstatic std::map<AMX*, AMX_DBG> amxDebugInfo;\nstatic std::map<AMX*, AMXProfiler*> amxProfilers;\n\nstatic bool ByExecutionTime(const AMXProfilerStat &op1, const AMXProfilerStat &op2) {\n return op1.executionTime > op2.executionTime;\n}\n\nstatic bool ByNumberOfCalls(const AMXProfilerStat &op1, const AMXProfilerStat &op2) {\n return op1.numberOfCalls > op2.numberOfCalls;\n}\n\nstatic const char *FindNativeByIndex(AMX *amx, cell index) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n\n AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\n int numNatives = (hdr->libraries - hdr->natives) \/ hdr->defsize;\n\n for (int i = 0; i < numNatives; i++) {\n if (i == index) {\n return reinterpret_cast<char*>(amx->base + natives[i].nameofs);\n }\n }\n\n return 0;\n}\n\nnamespace natives {\n \n \/\/ native Profiler_Start(const path_to_amx[]);\n cell AMX_NATIVE_CALL Profiler_Start(AMX *amx, cell *params) {\n char *path_to_amx;\n amx_StrParam(amx, params[1], path_to_amx);\n\n FILE *fp = fopen(path_to_amx, \"rb\");\n if (fp == 0) {\n return 0;\n }\n\n AMX_DBG amxdbg;\n if (dbg_LoadInfo(&amxdbg, fp) != AMX_ERR_NONE) {\n fclose(fp);\n return 0;\n }\n\n amxDebugInfo[amx] = amxdbg;\n fclose(fp);\n\n amxProfilers[amx]->Run();\n\n return 1;\n }\n\n \/\/ native Profiler_Stop();\n cell AMX_NATIVE_CALL Profiler_Stop(AMX *amx, cell *params) {\n AMXProfiler *prof = amxProfilers[amx];\n\n if (!prof->IsRunning()) {\n return 0;\n }\n\n prof->Terminate();\n return 1;\n }\n\n \/\/ native Profiler_PrintStats(const filename[]);\n cell AMX_NATIVE_CALL Profiler_PrintStats(AMX *amx, cell *params) {\n AMXProfiler *prof = amxProfilers[amx];\n\n if (prof->IsRunning()) { \n return 0;\n }\n\n char *filename;\n amx_StrParam(amx, params[1], filename);\n\n std::ofstream stream(filename);\n if (!stream.is_open()) {\n return 0;\n }\n\n AMX_DBG amxdbg = ::amxDebugInfo[amx];\n\n std::vector<AMXProfilerStat> v = prof->GetStats();\n std::sort(v.begin(), v.end(), ByExecutionTime);\n\n \/\/ Table header\n stream << \"<table>\\n\"\n << \"\\t<tr>\\n\"\n << \"\\t\\t<td>Function<\/td>\\n\"\n << \"\\t\\t<td>No. calls<\/td>\\n\"\n << \"\\t\\t<td>Time per call<\/td>\\n\"\n << \"\\t\\t<td>Overall time, %<\/td>\\n\"\n << \"\\t<\/tr>\\n\";\n\n \/\/ Calculate overall execution time\n uint64_t totalTime = 0;\n for (std::vector<AMXProfilerStat>::iterator it = v.begin(); it != v.end(); ++it) {\n totalTime += it->executionTime;\n }\n\n for (std::vector<AMXProfilerStat>::iterator it = v.begin(); it != v.end(); ++it)\n {\n if (it->numberOfCalls <= 0) {\n continue;\n }\n\n stream << \"\\t<tr>\\n\";\n\n if (it->native) {\n stream << \"\\t\\t<td>\" << FindNativeByIndex(amx, it->address) << \"<\/td>\\n\";\n } else {\n const char *name;\n if (dbg_LookupFunction(&amxdbg, it->address, &name) == AMX_ERR_NONE) {\n stream << \"\\t\\t<td>\" << name << \"<\/td>\\n\";\n } else {\n stream << \"\\t\\t<td>\" << std::hex << it->address << std::dec << \"<\/td>\\n\";\n }\n }\n stream << \"\\t\\t<td>\" << it->numberOfCalls << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::fixed << std::setprecision(0)\n << it->executionTime * 1.0 \/ it->numberOfCalls << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::setprecision(4)\n << it->executionTime * 100.0 \/ totalTime << \"<\/td>\\n\";\n stream << \"\\t<\/tr>\\n\";\n }\n stream << \"<\/table>\\n\";\n\n return 1;\n }\n\n const AMX_NATIVE_INFO all[] = { \n {\"Profiler_Start\", Profiler_Start},\n {\"Profiler_Stop\", Profiler_Stop},\n {\"Profiler_Print\", Profiler_PrintStats},\n {0, 0}\n };\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) {\n pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS];\n logprintf = (logprintf_t)pluginData[PLUGIN_DATA_LOGPRINTF];\n\n logprintf(\" Profiler plugin \" VERSION \" (built on \" __DATE__ \")\"); \n\n return true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n return;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n amxProfilers[amx] = new AMXProfiler(amx);\n return amx_Register(amx, natives::all, -1);\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n delete amxProfilers[amx];\n return AMX_ERR_NONE;\n}\n<commit_msg>git is crazy<commit_after>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <algorithm>\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <map>\n\n#include <malloc.h> \/\/ _alloca\n#include <stdlib.h>\n\n#include \"amxprofiler.h\"\n#include \"logprintf.h\"\n#include \"plugin.h\"\n#include \"version.h\"\n\nextern void *pAMXFunctions;\n\nstatic std::map<AMX*, AMX_DBG> amxDebugInfo;\nstatic std::map<AMX*, AMXProfiler*> amxProfilers;\n\nstatic bool ByExecutionTime(const AMXProfilerStat &op1, const AMXProfilerStat &op2) {\n return op1.executionTime > op2.executionTime;\n}\n\nstatic bool ByNumberOfCalls(const AMXProfilerStat &op1, const AMXProfilerStat &op2) {\n return op1.numberOfCalls > op2.numberOfCalls;\n}\n\nstatic const char *FindNativeByIndex(AMX *amx, cell index) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n\n AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\n int numNatives = (hdr->libraries - hdr->natives) \/ hdr->defsize;\n\n for (int i = 0; i < numNatives; i++) {\n if (i == index) {\n return reinterpret_cast<char*>(amx->base + natives[i].nameofs);\n }\n }\n\n return 0;\n}\n\nnamespace natives {\n \n \/\/ native Profiler_Start(const path_to_amx[]);\n cell AMX_NATIVE_CALL Profiler_Start(AMX *amx, cell *params) {\n char *path_to_amx;\n amx_StrParam(amx, params[1], path_to_amx);\n\n FILE *fp = fopen(path_to_amx, \"rb\");\n if (fp == 0) {\n return 0;\n }\n\n AMX_DBG amxdbg;\n if (dbg_LoadInfo(&amxdbg, fp) != AMX_ERR_NONE) {\n fclose(fp);\n return 0;\n }\n\n amxDebugInfo[amx] = amxdbg;\n fclose(fp);\n\n amxProfilers[amx]->Run();\n\n return 1;\n }\n\n \/\/ native Profiler_Stop();\n cell AMX_NATIVE_CALL Profiler_Stop(AMX *amx, cell *params) {\n AMXProfiler *prof = amxProfilers[amx];\n\n if (!prof->IsRunning()) {\n return 0;\n }\n\n prof->Terminate();\n return 1;\n }\n\n \/\/ native Profiler_PrintStats(const filename[]);\n cell AMX_NATIVE_CALL Profiler_PrintStats(AMX *amx, cell *params) {\n AMXProfiler *prof = amxProfilers[amx];\n\n if (prof->IsRunning()) { \n return 0;\n }\n\n char *filename;\n amx_StrParam(amx, params[1], filename);\n\n std::ofstream stream(filename);\n if (!stream.is_open()) {\n return 0;\n }\n\n std::vector<AMXProfilerStat> v = prof->GetStats();\n std::sort(v.begin(), v.end(), ByExecutionTime);\n\n \/\/ Table header\n stream << \"<table>\\n\"\n << \"\\t<tr>\\n\"\n << \"\\t\\t<td>Function<\/td>\\n\"\n << \"\\t\\t<td>No. calls<\/td>\\n\"\n << \"\\t\\t<td>Time per call<\/td>\\n\"\n << \"\\t\\t<td>Overall time, %<\/td>\\n\"\n << \"\\t<\/tr>\\n\";\n\n \/\/ Calculate overall execution time\n uint64_t totalTime = 0;\n for (std::vector<AMXProfilerStat>::iterator it = v.begin(); it != v.end(); ++it) {\n totalTime += it->executionTime;\n }\n\n for (std::vector<AMXProfilerStat>::iterator it = v.begin(); it != v.end(); ++it)\n {\n if (it->numberOfCalls <= 0) {\n continue;\n }\n\n stream << \"\\t<tr>\\n\";\n\n if (it->native) {\n stream << \"\\t\\t<td>\" << FindNativeByIndex(amx, it->address) << \"<\/td>\\n\";\n } else {\n AMX_DBG amxdbg = ::amxDebugInfo[amx];\n const char *name;\n if (dbg_LookupFunction(&amxdbg, it->address, &name) == AMX_ERR_NONE) {\n stream << \"\\t\\t<td>\" << name << \"<\/td>\\n\";\n } else {\n stream << \"\\t\\t<td>\" << std::hex << it->address << std::dec << \"<\/td>\\n\";\n }\n }\n stream << \"\\t\\t<td>\" << it->numberOfCalls << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::fixed << std::setprecision(0)\n << it->executionTime * 1.0 \/ it->numberOfCalls << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::setprecision(4)\n << it->executionTime * 100.0 \/ totalTime << \"<\/td>\\n\";\n stream << \"\\t<\/tr>\\n\";\n }\n stream << \"<\/table>\\n\";\n\n return 1;\n }\n\n const AMX_NATIVE_INFO all[] = { \n {\"Profiler_Start\", Profiler_Start},\n {\"Profiler_Stop\", Profiler_Stop},\n {\"Profiler_Print\", Profiler_PrintStats},\n {0, 0}\n };\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) {\n pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS];\n logprintf = (logprintf_t)pluginData[PLUGIN_DATA_LOGPRINTF];\n\n logprintf(\" Profiler plugin \" VERSION \" (built on \" __DATE__ \")\"); \n\n return true;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n return;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n amxProfilers[amx] = new AMXProfiler(amx);\n return amx_Register(amx, natives::all, -1);\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n delete amxProfilers[amx];\n return AMX_ERR_NONE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================\n\/\/ Skeleton Project for CS-150: 3D Computer Graphics\n\/\/===================================================*\/\n\n#include <glad\/glad.h> \/\/ must be included first\n#include <GLFW\/glfw3.h>\n#include <iostream>\n#include <array>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace std;\n\nstruct Vertex {\n glm::vec3 position;\n glm::vec3 color;\n};\n\nconst int NUM_TRIANGLES = 1;\n\nconst array<Vertex, 3*NUM_TRIANGLES> triangles =\n{{\n { glm::vec3(-0.5f, -0.289, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f) },\n { glm::vec3(0.5f, -0.289f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) },\n { glm::vec3(0.0f, 0.577f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f) }\n}};\n\nconst GLchar* vertexShaderSource = R\"glsl(\n#version 330\nuniform mat4 MVP;\nin vec3 vCol;\nin vec3 vPos;\nout vec3 color;\n\nvoid main()\n{\n gl_Position = MVP * vec4(vPos, 1.0);\n color = vCol;\n}\n)glsl\";\n\nconst GLchar* fragmentShaderSource = R\"glsl(\n#version 330\nin vec3 color;\nout vec4 fragColor;\n\nvoid main()\n{\n fragColor = vec4(color, 1.0);\n}\n)glsl\";\n\nvoid errorCallback(int error, const char* description)\n{\n cerr << \"GLFW Error: \" << description << endl;\n}\n\nvoid keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GLFW_TRUE);\n}\n\nvoid compileShader(GLuint shader, const char *shaderText)\n{\n glShaderSource(shader, 1, &shaderText, NULL);\n glCompileShader(shader);\n GLchar infoLog[8192];\n GLint success = 0;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &success);\n if (!success)\n {\n glGetShaderInfoLog(shader, 8192, NULL, infoLog);\n cerr << \"Shader failed to complile.\" << endl\n << \"Error log: \" << infoLog << endl;\n }\n}\n\nint main(void)\n{\n GLFWwindow* window;\n\n glfwSetErrorCallback(errorCallback);\n\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\n \/\/ Request OpenGL version 3.3.\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); \/\/ Don't use old OpenGL\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); \/\/ OSX needs this\n\n window = glfwCreateWindow(640, 480, \"CS 150 Template Project\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n\n glfwSetKeyCallback(window, keyCallback);\n\n glfwMakeContextCurrent(window);\n gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);\n cout << \"GL version: \" << glGetString(GL_VERSION) << endl\n << \"GL vendor: \" << glGetString(GL_VENDOR) << endl\n << \"GL renderer: \" << glGetString(GL_RENDERER) << endl\n << \"GL shading language version: \"\n << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;\n\n glfwSwapInterval(1); \/\/ Framerate matches monitor refresh rate\n\n \/\/ Compile shaders and check for errors\n GLuint vertexShader, fragmentShader, program;\n vertexShader = glCreateShader(GL_VERTEX_SHADER);\n fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);\n compileShader(vertexShader, vertexShaderSource);\n compileShader(fragmentShader, fragmentShaderSource);\n program = glCreateProgram();\n glAttachShader(program, vertexShader);\n glAttachShader(program, fragmentShader);\n glLinkProgram(program);\n GLint success = 0;\n glGetProgramiv(program, GL_LINK_STATUS, &success);\n if (!success)\n {\n cerr << \"ERROR: Shader linking failed.\" << endl;\n glDeleteProgram(program);\n program = 0u;\n }\n glDeleteShader(vertexShader);\n glDeleteShader(fragmentShader);\n\n GLint l_MVP = glGetUniformLocation(program, \"MVP\");\n GLint l_vPos = glGetAttribLocation(program, \"vPos\");\n GLint l_vCol = glGetAttribLocation(program, \"vCol\");\n\n \/\/ Send data to OpenGL context\n GLuint VAO, VBO; \/\/ vertex array object, vertex buffer object\n glGenVertexArrays(1, &VAO);\n glBindVertexArray(VAO);\n glGenBuffers(1, &VBO);\n glBindBuffer(GL_ARRAY_BUFFER, VBO);\n glBufferData(GL_ARRAY_BUFFER, triangles.size() * sizeof(Vertex),\n triangles.data(), GL_STATIC_DRAW);\n glEnableVertexAttribArray(l_vPos);\n glVertexAttribPointer(l_vPos, 3, GL_FLOAT, GL_FALSE,\n sizeof(Vertex), (GLvoid*) 0);\n glEnableVertexAttribArray(l_vCol);\n glVertexAttribPointer(l_vCol, 3, GL_FLOAT, GL_FALSE,\n sizeof(Vertex), (GLvoid*) (sizeof(glm::vec3)));\n\n glUseProgram(program);\n glEnable(GL_DEPTH_TEST);\n glm::mat4 M, V, P, MVP;\n glm::vec3 eye = glm::vec3(0.0, 0.0, 5.0);\n glm::vec3 center = glm::vec3(0.0, 0.0, 0.0);\n glm::vec3 up = glm::vec3(0.0, 1.0, 0.0);\n V = glm::lookAt(eye, center, up);\n\n while (!glfwWindowShouldClose(window))\n {\n float ratio;\n int width, height;\n\n glfwGetFramebufferSize(window, &width, &height);\n glViewport(0, 0, width, height);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n ratio = width \/ (float) height;\n P = glm::perspective(0.50f, ratio, 1.0f, 100.0f);\n M = glm::rotate(glm::mat4(1.0f),\n (float) glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f));\n MVP = P * V * M;\n\n glUniformMatrix4fv(l_MVP, 1, GL_FALSE, glm::value_ptr(MVP));\n glDrawArrays(GL_TRIANGLES, 0, 3*NUM_TRIANGLES);\n\n \/\/ check for OpenGL errors\n GLenum error_code;\n while ((error_code = glGetError()) != GL_NO_ERROR)\n cerr << \"OpenGL error HEX: \" << hex << error_code << endl;\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<commit_msg>moved glUseProgram call<commit_after>\/*===================================================\n\/\/ Skeleton Project for CS-150: 3D Computer Graphics\n\/\/===================================================*\/\n\n#include <glad\/glad.h> \/\/ must be included first\n#include <GLFW\/glfw3.h>\n#include <iostream>\n#include <array>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\nusing namespace std;\n\nstruct Vertex {\n glm::vec3 position;\n glm::vec3 color;\n};\n\nconst int NUM_TRIANGLES = 1;\n\nconst array<Vertex, 3*NUM_TRIANGLES> triangles =\n{{\n { glm::vec3(-0.5f, -0.289, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f) },\n { glm::vec3(0.5f, -0.289f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) },\n { glm::vec3(0.0f, 0.577f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f) }\n}};\n\nconst GLchar* vertexShaderSource = R\"glsl(\n#version 330\nuniform mat4 MVP;\nin vec3 vCol;\nin vec3 vPos;\nout vec3 color;\n\nvoid main()\n{\n gl_Position = MVP * vec4(vPos, 1.0);\n color = vCol;\n}\n)glsl\";\n\nconst GLchar* fragmentShaderSource = R\"glsl(\n#version 330\nin vec3 color;\nout vec4 fragColor;\n\nvoid main()\n{\n fragColor = vec4(color, 1.0);\n}\n)glsl\";\n\nvoid errorCallback(int error, const char* description)\n{\n cerr << \"GLFW Error: \" << description << endl;\n}\n\nvoid keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GLFW_TRUE);\n}\n\nvoid compileShader(GLuint shader, const char *shaderText)\n{\n glShaderSource(shader, 1, &shaderText, NULL);\n glCompileShader(shader);\n GLchar infoLog[8192];\n GLint success = 0;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &success);\n if (!success)\n {\n glGetShaderInfoLog(shader, 8192, NULL, infoLog);\n cerr << \"Shader failed to complile.\" << endl\n << \"Error log: \" << infoLog << endl;\n }\n}\n\nint main(void)\n{\n GLFWwindow* window;\n\n glfwSetErrorCallback(errorCallback);\n\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\n \/\/ Request OpenGL version 3.3.\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); \/\/ Don't use old OpenGL\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); \/\/ OSX needs this\n\n window = glfwCreateWindow(640, 480, \"CS 150 Template Project\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n\n glfwSetKeyCallback(window, keyCallback);\n\n glfwMakeContextCurrent(window);\n gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);\n cout << \"GL version: \" << glGetString(GL_VERSION) << endl\n << \"GL vendor: \" << glGetString(GL_VENDOR) << endl\n << \"GL renderer: \" << glGetString(GL_RENDERER) << endl\n << \"GL shading language version: \"\n << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;\n\n glfwSwapInterval(1); \/\/ Framerate matches monitor refresh rate\n\n \/\/ Compile shaders and check for errors\n GLuint vertexShader, fragmentShader, program;\n vertexShader = glCreateShader(GL_VERTEX_SHADER);\n fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);\n compileShader(vertexShader, vertexShaderSource);\n compileShader(fragmentShader, fragmentShaderSource);\n program = glCreateProgram();\n glAttachShader(program, vertexShader);\n glAttachShader(program, fragmentShader);\n glLinkProgram(program);\n GLint success = 0;\n glGetProgramiv(program, GL_LINK_STATUS, &success);\n if (!success)\n {\n cerr << \"ERROR: Shader linking failed.\" << endl;\n glDeleteProgram(program);\n program = 0u;\n }\n glDeleteShader(vertexShader);\n glDeleteShader(fragmentShader);\n glUseProgram(program);\n\n GLint l_MVP = glGetUniformLocation(program, \"MVP\");\n GLint l_vPos = glGetAttribLocation(program, \"vPos\");\n GLint l_vCol = glGetAttribLocation(program, \"vCol\");\n\n \/\/ Send data to OpenGL context\n GLuint VAO, VBO; \/\/ vertex array object, vertex buffer object\n glGenVertexArrays(1, &VAO);\n glBindVertexArray(VAO);\n glGenBuffers(1, &VBO);\n glBindBuffer(GL_ARRAY_BUFFER, VBO);\n glBufferData(GL_ARRAY_BUFFER, triangles.size() * sizeof(Vertex),\n triangles.data(), GL_STATIC_DRAW);\n glEnableVertexAttribArray(l_vPos);\n glVertexAttribPointer(l_vPos, 3, GL_FLOAT, GL_FALSE,\n sizeof(Vertex), (GLvoid*) 0);\n glEnableVertexAttribArray(l_vCol);\n glVertexAttribPointer(l_vCol, 3, GL_FLOAT, GL_FALSE,\n sizeof(Vertex), (GLvoid*) (sizeof(glm::vec3)));\n\n glEnable(GL_DEPTH_TEST);\n glm::mat4 M, V, P, MVP;\n glm::vec3 eye = glm::vec3(0.0, 0.0, 5.0);\n glm::vec3 center = glm::vec3(0.0, 0.0, 0.0);\n glm::vec3 up = glm::vec3(0.0, 1.0, 0.0);\n V = glm::lookAt(eye, center, up);\n\n while (!glfwWindowShouldClose(window))\n {\n float ratio;\n int width, height;\n\n glfwGetFramebufferSize(window, &width, &height);\n glViewport(0, 0, width, height);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n ratio = width \/ (float) height;\n P = glm::perspective(0.50f, ratio, 1.0f, 100.0f);\n M = glm::rotate(glm::mat4(1.0f),\n (float) glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f));\n MVP = P * V * M;\n\n glUniformMatrix4fv(l_MVP, 1, GL_FALSE, glm::value_ptr(MVP));\n glDrawArrays(GL_TRIANGLES, 0, 3*NUM_TRIANGLES);\n\n \/\/ check for OpenGL errors\n GLenum error_code;\n while ((error_code = glGetError()) != GL_NO_ERROR)\n cerr << \"OpenGL error HEX: \" << hex << error_code << endl;\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Reference: http:\/\/plms.oxfordjournals.org\/content\/s2-42\/1\/230.full.pdf+html\n *\n * Instruction set\n * ===============\n * m-config symbol operations final m-config\n * string char op1,op2,... string\n *\n * op:\n * L - move left one step\n * R - move right one step\n * P<symbol> - print symbol on tap\n * E - erase symbol from tap\n * symbol:\n * ~ - matches blank cell\n * * - matches any symbol\n * other char matches themselves\n *\n * Lines starting with # are ignored by the interpreter\n *\/\n\n#include <iostream>\n#include <string>\n#include <regex>\n#include <map>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nstruct Configuration {\n string state;\n char symbol;\n bool operator<(const Configuration &o) const {\n return state < o.state || (state == o.state && symbol < o.symbol);\n }\n};\n\nstruct Action {\n string ops;\n string state;\n};\n\nstruct Machine {\n int tp = 0;\n string curr;\n map< Configuration, Action > program;\n map< int, char > tape;\n\n void load_program() {\n cin.sync_with_stdio(false);\n string line;\n while (getline(cin, line)) {\n \/\/ skip empty lines\n if (line.length() == 0) {\n continue;\n }\n\n \/\/ lines begining with # are comments\n if (line.at(0) == '#') {\n continue;\n }\n\n istringstream iss(line);\n string state, symbol, ops, fstate;\n iss >> state >> symbol >> ops >> fstate;\n\n if (curr.length() == 0) {\n curr = state;\n }\n\n Configuration c = {state, symbol.at(0)};\n Action a = {ops, fstate};\n program[c] = a;\n }\n }\n\n void print_program() {\n for (auto it = program.begin(); it != program.end(); it++) {\n cout << it->first.state << \" \";\n cout << it->first.symbol << \" \";\n cout << it->second.ops << \" \";\n cout << it->second.state << endl;\n }\n }\n\n void print_tape() {\n cout << \"tape: \";\n for (auto it = tape.begin(); it != tape.end(); it++) {\n cout << it->second;\n }\n cout << endl;\n }\n\n char read_tape() {\n if (tape.count(tp)) {\n return tape[tp];\n } else {\n return '~';\n }\n }\n\n int perform_ops(string ops) {\n for (int i = 0; i < ops.length(); i++) {\n char op = ops.at(i);\n switch (op) {\n case 'R':\n tp++;\n break;\n case 'L':\n tp--;\n break;\n case 'E':\n tape[tp] = '~';\n break;\n case 'P':\n i++;\n tape[tp] = ops.at(i);\n case ',':\n break;\n default:\n cout << \"unknown op: \" << op << endl;\n exit(1);\n }\n }\n return tp;\n }\n\n void eval(int max) {\n int cnt = 0;\n while (cnt < max) {\n Configuration c = {curr, read_tape()};\n if (program.count(c) == 0) {\n c = {curr, '*'};\n }\n if (program.count(c) == 0) {\n break;\n }\n Action a = program[c];\n tp = perform_ops(a.ops);\n curr = a.state;\n\n cnt++;\n print_config(c);\n print_tape();\n }\n }\n\n void print_config(Configuration c) {\n cout << \"conf: \" << c.state << \" \" << c.symbol << endl;\n }\n};\n\nint main(int argc, char *argv[]) {\n Machine m;\n m.load_program();\n m.print_program();\n m.eval(1000);\n return 0;\n}\n<commit_msg>rename eval to run<commit_after>\/*\n * Reference: http:\/\/plms.oxfordjournals.org\/content\/s2-42\/1\/230.full.pdf+html\n *\n * Instruction set\n * ===============\n * m-config symbol operations final m-config\n * string char op1,op2,... string\n *\n * op:\n * L - move left one step\n * R - move right one step\n * P<symbol> - print symbol on tap\n * E - erase symbol from tap\n * symbol:\n * ~ - matches blank cell\n * * - matches any symbol\n * other char matches themselves\n *\n * Lines starting with # are ignored by the interpreter\n *\/\n\n#include <iostream>\n#include <string>\n#include <regex>\n#include <map>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nstruct Configuration {\n string state;\n char symbol;\n bool operator<(const Configuration &o) const {\n return state < o.state || (state == o.state && symbol < o.symbol);\n }\n};\n\nstruct Action {\n string ops;\n string state;\n};\n\nstruct Machine {\n int tp = 0;\n string curr;\n map< Configuration, Action > program;\n map< int, char > tape;\n\n void load_program() {\n cin.sync_with_stdio(false);\n string line;\n while (getline(cin, line)) {\n \/\/ skip empty lines\n if (line.length() == 0) {\n continue;\n }\n\n \/\/ lines begining with # are comments\n if (line.at(0) == '#') {\n continue;\n }\n\n istringstream iss(line);\n string state, symbol, ops, fstate;\n iss >> state >> symbol >> ops >> fstate;\n\n if (curr.length() == 0) {\n curr = state;\n }\n\n Configuration c = {state, symbol.at(0)};\n Action a = {ops, fstate};\n program[c] = a;\n }\n }\n\n void print_program() {\n for (auto it = program.begin(); it != program.end(); it++) {\n cout << it->first.state << \" \";\n cout << it->first.symbol << \" \";\n cout << it->second.ops << \" \";\n cout << it->second.state << endl;\n }\n }\n\n void print_tape() {\n cout << \"tape: \";\n for (auto it = tape.begin(); it != tape.end(); it++) {\n cout << it->second;\n }\n cout << endl;\n }\n\n char read_tape() {\n if (tape.count(tp)) {\n return tape[tp];\n } else {\n return '~';\n }\n }\n\n int perform_ops(string ops) {\n for (int i = 0; i < ops.length(); i++) {\n char op = ops.at(i);\n switch (op) {\n case 'R':\n tp++;\n break;\n case 'L':\n tp--;\n break;\n case 'E':\n tape[tp] = '~';\n break;\n case 'P':\n i++;\n tape[tp] = ops.at(i);\n case ',':\n break;\n default:\n cout << \"unknown op: \" << op << endl;\n exit(1);\n }\n }\n return tp;\n }\n\n void run(int max) {\n int cnt = 0;\n while (cnt < max) {\n Configuration c = {curr, read_tape()};\n if (program.count(c) == 0) {\n c = {curr, '*'};\n }\n if (program.count(c) == 0) {\n break;\n }\n Action a = program[c];\n tp = perform_ops(a.ops);\n curr = a.state;\n\n cnt++;\n print_config(c);\n print_tape();\n }\n }\n\n void print_config(Configuration c) {\n cout << \"conf: \" << c.state << \" \" << c.symbol << endl;\n }\n};\n\nint main(int argc, char *argv[]) {\n Machine m;\n m.load_program();\n m.print_program();\n m.run(1000);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"netdrawer.h\"\n\nusing namespace NEAT;\nusing namespace std;\n\n\/*\n\/\/void setPosition(double &x, double &y, double Min, double Max){\nvoid setPosition(double &x, double &y){\n\t\/\/randomly generate position for a node;\n\tdouble Min = 0.0, Max = 1000.0;\n\tdouble p = (double)rand() \/ RAND_MAX;\n\tx = Min + p * (Max - Min);\n\tx = (floor(x * 10))\/10; \/\/only keep one digit after the decimal point\n\t\n\tdouble q = (double)rand() \/ RAND_MAX;\n\ty = Min + q * (Max - Min);\n\ty = (floor(y * 10))\/10;\n\t\n\treturn;\n}\n*\/\n\nvoid setPositionX(double &x, int side){\n\t\/\/side can only be 0, 1, 2 (representing left, right, middle)\n\tswitch(side){\n\t\tcase 0:\n\t\tx = 100.0;\n\t\tbreak;\n\t\t\n\t\tcase 1:\n\t\tx = 500.0;\n\t\tbreak;\n\t\t\n\t\tcase 2: \/\/middle\n\t\tx = 300.0;\n\t}\n\t\n\treturn;\n}\n\n\nvoid printNode(NNode* node, double x, double y, std::ofstream &myfile){\n\n\tint type = node->type;\n\t\/\/nodetype is 1, which is transition\n\tif(type){\n\t\tmyfile << \"<transition id=\\\"\" << node->node_id << \"\\\">\\n\";\n\t\tmyfile << \"<graphics>\\n\";\n\t\tmyfile << \"<position x=\\\"\" << x << \"\\\" y=\\\"\" << y << \"\\\"\/>\\n\";\n\t\tmyfile << \"<\/graphics>\\n\";\n\t\tmyfile << \"<name>\\n\";\n\t\tmyfile << \"<value>\" << node->node_id << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/name>\\n\";\n\t\tmyfile << \"<orientation>\\n\";\n\t\tmyfile << \"<value>0<\/value>\\n\";\n\t\tmyfile << \"<\/orientation>\\n\";\n\t\tmyfile << \"<rate>\\n\";\n\t\tmyfile << \"<value>1.0<\/value>\\n\";\n\t\tmyfile << \"<\/rate>\\n\";\n\t\tmyfile << \"<timed>\\n\";\n\t\tmyfile << \"<value>false<\/value>\\n\";\n\t\tmyfile << \"<\/timed>\\n\";\n\t\tmyfile << \"<\/transition>\\n\";\t\t\t\t\n\t}\n\telse{ \/\/\/\/nodetype is 0, which is place\n\t\tmyfile << \"<place id=\\\"\" << node->node_id << \"\\\">\\n\";\n\t\tmyfile << \"<graphics>\\n\";\n\t\tmyfile << \"<position x=\\\"\" << x << \"\\\" y=\\\"\" << y << \"\\\"\/>\\n\";\n\t\tmyfile << \"<\/graphics>\\n\";\n\t\tmyfile << \"<name>\\n\";\n\t\tmyfile << \"<value>\" << node->node_id << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/name>\\n\";\n\t\tmyfile << \"<initialMarking>\\n\";\n\t\tmyfile << \"<value>\" << node->tok_count << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/initialMarking>\\n\";\n\t\tmyfile << \"<\/place>\\n\";\n\t}\n\t\t \n}\n\nvoid printLink(Link* nlink, std::map<NNode*, int> npos, std::vector<double> xpos, std::vector<double> ypos, std::ofstream &myfile){\n\tNNode* in = nlink->in_node;\n\tNNode* out = nlink->out_node;\n\tint in_ptr = npos[in];\n\tint out_ptr = npos[out];\n\t\n\tmyfile << \"<arc id=\\\"\" << in->node_id << \" to \" << out->node_id << \"\\\" \";\n\tmyfile << \"source=\\\"\" << in->node_id << \"\\\" target=\\\"\" << out->node_id <<\"\\\">\\n\";\n\tmyfile << \"<graphics\/>\\n\";\n\tmyfile << \"<inscription>\\n\";\n\tmyfile << \"<value>\" << (int)nlink->weight << \"<\/value>\\n\";\n\tmyfile << \"<graphics\/>\\n\";\n\tmyfile << \"<\/inscription>\\n\";\n\tmyfile << \"<arcpath id=\\\"000\\\" x=\\\"\" << ((int)xpos[in_ptr]) + 11;\n\tmyfile << \"\\\" y=\\\"\" << ((int)ypos[in_ptr]) + 5 << \"\\\" curvePoint=\\\"false\\\"\/>\\n\";\n\tmyfile << \"<arcpath id=\\\"001\\\" x=\\\"\" << ((int)xpos[out_ptr]) + 11;\n\tmyfile << \"\\\" y=\\\"\" << ((int)ypos[out_ptr]) + 5 << \"\\\" curvePoint=\\\"false\\\"\/>\\n\";\n\tmyfile << \"<\/arc>\\n\";\n}\n\nint netdrawer(const Network* network){\n\t\n\t\/\/build an xml file for the network\n\t\/\/initialize the xml file\n\tstd::ofstream myfile;\n\tchar buff[100];\n \tsprintf(buff, \"PetriNet_%d.xml\", network->net_id);\n\tmyfile.open(buff, std::ofstream::out);\n\tmyfile <<\"<?xml version=\\\"1.0\\\" encoding=\\\"iso-8859-1\\\"?>\\n<pnml>\\n<net id=\\\"Net-One\\\" type=\\\"P\/T net\\\">\";\n\t\n\t\/\/a hashmap to record posiitons of nodes using node pointer (NNode*) and position number(int)\n\tstd::map<NNode*, int> nodepos; \n\t\/\/two vectors to record positions of the nodes\n\tstd::vector<double> xpos; \n\tstd::vector<double> ypos;\n\n\t\/\/Write all the places\n\tstd::vector<NNode*>::const_iterator curnode;\n\tint count = 0;\n\tdouble x, y = 50.0;\n\tsetPositionX(x, 2); \/\/setting positions for transitions\n\n\t\/\/Write all the transitions\n\tfor(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){\n\t\t\/\/generate an position\n\t\tnodepos[*curnode] = count;\n\t\txpos.push_back(x);\n\t\typos.push_back(y);\n\t\tprintNode(*curnode, x, y, myfile);\n\n\t\ty += 50;\n\t\tcount++;\n\t}\n\n\ty = 50.0;\n\t\/\/Write all the places\n\tfor(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {\n\t\t\/\/generate an random position for curnode;\n\t\tint side = randint(0, 1);\n\t\tsetPositionX(x, side);\n\t\tnodepos[*curnode] = count;\n\t\txpos.push_back(x);\n\t\typos.push_back(y);\n\t\ty += 50;\n\t\t\n\t\tprintNode(*curnode, x, y, myfile);\n\t\t\n\t\tcount++;\n\t}\n\t\n\t\/\/Write all the links\n\tstd::vector<Link*>::const_iterator curlink;\n\tfor(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {\n\t\tfor(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){\n\t\t\tprintLink(*curlink, nodepos, xpos, ypos, myfile);\n\t\t}\n\t}\n\t\t\n\tfor(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){\n\t\tfor(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){\n\t\t\tprintLink(*curlink, nodepos, xpos, ypos, myfile);\n\t\t}\n\t}\n\t\n\t\/\/closing xml file\n\tmyfile <<\"<\/net>\\n<\/pnml>\";\n\tmyfile.close();\n\treturn 0;\n}\n\t\n<commit_msg>add action_type in name of transition<commit_after>#include \"netdrawer.h\"\n\nusing namespace NEAT;\nusing namespace std;\n\n\/*\n\/\/void setPosition(double &x, double &y, double Min, double Max){\nvoid setPosition(double &x, double &y){\n\t\/\/randomly generate position for a node;\n\tdouble Min = 0.0, Max = 1000.0;\n\tdouble p = (double)rand() \/ RAND_MAX;\n\tx = Min + p * (Max - Min);\n\tx = (floor(x * 10))\/10; \/\/only keep one digit after the decimal point\n\t\n\tdouble q = (double)rand() \/ RAND_MAX;\n\ty = Min + q * (Max - Min);\n\ty = (floor(y * 10))\/10;\n\t\n\treturn;\n}\n*\/\n\nvoid setPositionX(double &x, int side){\n\t\/\/side can only be 0, 1, 2 (representing left, right, middle)\n\tswitch(side){\n\t\tcase 0:\n\t\tx = 100.0;\n\t\tbreak;\n\t\t\n\t\tcase 1:\n\t\tx = 500.0;\n\t\tbreak;\n\t\t\n\t\tcase 2: \/\/middle\n\t\tx = 300.0;\n\t}\n\t\n\treturn;\n}\n\n\nvoid printNode(NNode* node, double x, double y, std::ofstream &myfile){\n\n\tint type = node->type;\n\t\/\/nodetype is 1, which is transition\n\tif(type){\n\t\tmyfile << \"<transition id=\\\"\" << node->node_id << \"\\\">\\n\";\n\t\tmyfile << \"<graphics>\\n\";\n\t\tmyfile << \"<position x=\\\"\" << x << \"\\\" y=\\\"\" << y << \"\\\"\/>\\n\";\n\t\tmyfile << \"<\/graphics>\\n\";\n\t\tmyfile << \"<name>\\n\";\n\t\tmyfile << \"<value>\" << node->node_id << \"_\";\n\t\t\n\t\tswitch(node->action_ID){\n\t\t\tcase 0: \n\t\t\tmyfile << \"move right\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase 1: \n\t\t\tmyfile << \"move up\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2:\n\t\t\tmyfile << \"move left\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase 3:\n\t\t\tmyfile << \"move down\";\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tmyfile << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/name>\\n\";\n\t\tmyfile << \"<orientation>\\n\";\n\t\tmyfile << \"<value>0<\/value>\\n\";\n\t\tmyfile << \"<\/orientation>\\n\";\n\t\tmyfile << \"<rate>\\n\";\n\t\tmyfile << \"<value>1.0<\/value>\\n\";\n\t\tmyfile << \"<\/rate>\\n\";\n\t\tmyfile << \"<timed>\\n\";\n\t\tmyfile << \"<value>false<\/value>\\n\";\n\t\tmyfile << \"<\/timed>\\n\";\n\t\tmyfile << \"<\/transition>\\n\";\t\t\t\t\n\t}\n\telse{ \/\/\/\/nodetype is 0, which is place\n\t\tmyfile << \"<place id=\\\"\" << node->node_id << \"\\\">\\n\";\n\t\tmyfile << \"<graphics>\\n\";\n\t\tmyfile << \"<position x=\\\"\" << x << \"\\\" y=\\\"\" << y << \"\\\"\/>\\n\";\n\t\tmyfile << \"<\/graphics>\\n\";\n\t\tmyfile << \"<name>\\n\";\n\t\tmyfile << \"<value>\" << node->node_id << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/name>\\n\";\n\t\tmyfile << \"<initialMarking>\\n\";\n\t\tmyfile << \"<value>\" << node->tok_count << \"<\/value>\\n\";\n\t\tmyfile << \"<graphics\/>\\n\";\n\t\tmyfile << \"<\/initialMarking>\\n\";\n\t\tmyfile << \"<\/place>\\n\";\n\t}\n\t\t \n}\n\nvoid printLink(Link* nlink, std::map<NNode*, int> npos, std::vector<double> xpos, std::vector<double> ypos, std::ofstream &myfile){\n\tNNode* in = nlink->in_node;\n\tNNode* out = nlink->out_node;\n\tint in_ptr = npos[in];\n\tint out_ptr = npos[out];\n\t\n\tmyfile << \"<arc id=\\\"\" << in->node_id << \" to \" << out->node_id << \"\\\" \";\n\tmyfile << \"source=\\\"\" << in->node_id << \"\\\" target=\\\"\" << out->node_id <<\"\\\">\\n\";\n\tmyfile << \"<graphics\/>\\n\";\n\tmyfile << \"<inscription>\\n\";\n\tmyfile << \"<value>\" << (int)nlink->weight << \"<\/value>\\n\";\n\tmyfile << \"<graphics\/>\\n\";\n\tmyfile << \"<\/inscription>\\n\";\n\tmyfile << \"<arcpath id=\\\"000\\\" x=\\\"\" << ((int)xpos[in_ptr]) + 11;\n\tmyfile << \"\\\" y=\\\"\" << ((int)ypos[in_ptr]) + 5 << \"\\\" curvePoint=\\\"false\\\"\/>\\n\";\n\tmyfile << \"<arcpath id=\\\"001\\\" x=\\\"\" << ((int)xpos[out_ptr]) + 11;\n\tmyfile << \"\\\" y=\\\"\" << ((int)ypos[out_ptr]) + 5 << \"\\\" curvePoint=\\\"false\\\"\/>\\n\";\n\tmyfile << \"<\/arc>\\n\";\n}\n\nint netdrawer(const Network* network){\n\t\n\t\/\/build an xml file for the network\n\t\/\/initialize the xml file\n\tstd::ofstream myfile;\n\tchar buff[100];\n \tsprintf(buff, \"PetriNet_%d.xml\", network->net_id);\n\tmyfile.open(buff, std::ofstream::out);\n\tmyfile <<\"<?xml version=\\\"1.0\\\" encoding=\\\"iso-8859-1\\\"?>\\n<pnml>\\n<net id=\\\"Net-One\\\" type=\\\"P\/T net\\\">\";\n\t\n\t\/\/a hashmap to record posiitons of nodes using node pointer (NNode*) and position number(int)\n\tstd::map<NNode*, int> nodepos; \n\t\/\/two vectors to record positions of the nodes\n\tstd::vector<double> xpos; \n\tstd::vector<double> ypos;\n\n\t\/\/Write all the places\n\tstd::vector<NNode*>::const_iterator curnode;\n\tint count = 0;\n\tdouble x, y = 50.0;\n\tsetPositionX(x, 2); \/\/setting positions for transitions\n\n\t\/\/Write all the transitions\n\tfor(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){\n\t\t\/\/generate an position\n\t\tnodepos[*curnode] = count;\n\t\txpos.push_back(x);\n\t\typos.push_back(y);\n\t\tprintNode(*curnode, x, y, myfile);\n\n\t\ty += 50;\n\t\tcount++;\n\t}\n\n\ty = 50.0;\n\t\/\/Write all the places\n\tfor(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {\n\t\t\/\/generate an random position for curnode;\n\t\tint side = randint(0, 1);\n\t\tsetPositionX(x, side);\n\t\tnodepos[*curnode] = count;\n\t\txpos.push_back(x);\n\t\typos.push_back(y);\n\t\ty += 50;\n\t\t\n\t\tprintNode(*curnode, x, y, myfile);\n\t\t\n\t\tcount++;\n\t}\n\t\n\t\/\/Write all the links\n\tstd::vector<Link*>::const_iterator curlink;\n\tfor(curnode = network->places.begin(); curnode != network->places.end(); ++curnode) {\n\t\tfor(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){\n\t\t\tprintLink(*curlink, nodepos, xpos, ypos, myfile);\n\t\t}\n\t}\n\t\t\n\tfor(curnode = network->transitions.begin(); curnode != network->transitions.end(); ++curnode){\n\t\tfor(curlink = (*curnode)->incoming.begin(); curlink != (*curnode)->incoming.end(); ++curlink){\n\t\t\tprintLink(*curlink, nodepos, xpos, ypos, myfile);\n\t\t}\n\t}\n\t\n\t\/\/closing xml file\n\tmyfile <<\"<\/net>\\n<\/pnml>\";\n\tmyfile.close();\n\treturn 0;\n}\n\t\n<|endoftext|>"} {"text":"<commit_before>#include \"platform_node.h\"\n\nPlatformNode::PlatformNode(void) {\n for (uint8_t i = 0; i < PLATFORM_TOTAL_CHANNEL_COUNT; i++) {\n _channels[i] = PLATFORM_DEFAULT_CHANNEL_VALUE;\n }\n}\n\n\/**\n * Return true if new bind key was generated\n *\/\nvoid PlatformNode::seed(void) {\n uint8_t val;\n\n val = EEPROM.read(EEPROM_ADDRESS_BIND_KEY_SEEDED);\n\n if (val != 0xf1) {\n EEPROM.write(EEPROM_ADDRESS_BIND_0, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_1, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_2, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_3, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_KEY_SEEDED, 0xf1);\n } \n}\n\nvoid PlatformNode::loadBindKey(uint8_t key[]) {\n key[0] = EEPROM.read(EEPROM_ADDRESS_BIND_0);\n key[1] = EEPROM.read(EEPROM_ADDRESS_BIND_1);\n key[2] = EEPROM.read(EEPROM_ADDRESS_BIND_2);\n key[3] = EEPROM.read(EEPROM_ADDRESS_BIND_3);\n}\n\nvoid PlatformNode::saveBindKey(uint8_t key[]) {\n EEPROM.write(EEPROM_ADDRESS_BIND_0, key[0]);\n EEPROM.write(EEPROM_ADDRESS_BIND_1, key[1]);\n EEPROM.write(EEPROM_ADDRESS_BIND_2, key[2]);\n EEPROM.write(EEPROM_ADDRESS_BIND_3, key[3]);\n EEPROM.write(EEPROM_ADDRESS_BIND_KEY_SEEDED, 0xf1);\n}\n\nint PlatformNode::getRcChannel(uint8_t channel) {\n if (channel < PLATFORM_TOTAL_CHANNEL_COUNT) {\n return _channels[channel];\n } else {\n return PLATFORM_DEFAULT_CHANNEL_VALUE;\n }\n}\n\nvoid PlatformNode::setRcChannel(uint8_t channel, int value, int offset) {\n if (channel < PLATFORM_TOTAL_CHANNEL_COUNT) {\n _channels[channel] = value + offset;\n }\n}\n\nvoid PlatformNode::enterBindMode(void) {\n isBindMode = true;\n\n \/\/ Set temporary bind mode\n bindKey[0] = 0xf1;\n bindKey[1] = 0x1e;\n bindKey[2] = 0x07;\n bindKey[3] = 0x42;\n\n radioNode.set(\n 0, \/\/ Minimum power\n 125000, \/\/ 125kHz bandwidth\n 6, \/\/ low spreading factor, we do not need high RX sensitivity\n 5, \/\/ same for coding rate\n 868000000 \/\/Fixed frequency while binding\n );\n bindModeExitMillis = millis() + 1000; \/\/This happens only on RX\n}\n\nvoid PlatformNode::leaveBindMode(void) {\n isBindMode = false;\n loadBindKey(bindKey);\n radioNode.reset();\n}<commit_msg>Update platform_node.cpp<commit_after>#include \"platform_node.h\"\n\nPlatformNode::PlatformNode(void) {\n for (uint8_t i = 0; i < PLATFORM_TOTAL_CHANNEL_COUNT; i++) {\n _channels[i] = PLATFORM_DEFAULT_CHANNEL_VALUE;\n }\n}\n\n\/**\n * Return true if new bind key was generated\n *\/\nvoid PlatformNode::seed(void) {\n uint8_t val;\n\n val = EEPROM.read(EEPROM_ADDRESS_BIND_KEY_SEEDED);\n\n if (val != 0xf1) {\n EEPROM.write(EEPROM_ADDRESS_BIND_0, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_1, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_2, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_3, random(1, 255)); \/\/Yes, from 1 to 254\n EEPROM.write(EEPROM_ADDRESS_BIND_KEY_SEEDED, 0xf1);\n #ifdef ARDUINO_SAMD_FEATHER_M0\n EEPROM.commit();\n #endif\n } \n}\n\nvoid PlatformNode::loadBindKey(uint8_t key[]) {\n key[0] = EEPROM.read(EEPROM_ADDRESS_BIND_0);\n key[1] = EEPROM.read(EEPROM_ADDRESS_BIND_1);\n key[2] = EEPROM.read(EEPROM_ADDRESS_BIND_2);\n key[3] = EEPROM.read(EEPROM_ADDRESS_BIND_3);\n}\n\nvoid PlatformNode::saveBindKey(uint8_t key[]) {\n EEPROM.write(EEPROM_ADDRESS_BIND_0, key[0]);\n EEPROM.write(EEPROM_ADDRESS_BIND_1, key[1]);\n EEPROM.write(EEPROM_ADDRESS_BIND_2, key[2]);\n EEPROM.write(EEPROM_ADDRESS_BIND_3, key[3]);\n EEPROM.write(EEPROM_ADDRESS_BIND_KEY_SEEDED, 0xf1);\n #ifdef ARDUINO_SAMD_FEATHER_M0\n EEPROM.commit();\n #endif\n}\n\nint PlatformNode::getRcChannel(uint8_t channel) {\n if (channel < PLATFORM_TOTAL_CHANNEL_COUNT) {\n return _channels[channel];\n } else {\n return PLATFORM_DEFAULT_CHANNEL_VALUE;\n }\n}\n\nvoid PlatformNode::setRcChannel(uint8_t channel, int value, int offset) {\n if (channel < PLATFORM_TOTAL_CHANNEL_COUNT) {\n _channels[channel] = value + offset;\n }\n}\n\nvoid PlatformNode::enterBindMode(void) {\n isBindMode = true;\n\n \/\/ Set temporary bind mode\n bindKey[0] = 0xf1;\n bindKey[1] = 0x1e;\n bindKey[2] = 0x07;\n bindKey[3] = 0x42;\n\n radioNode.set(\n 0, \/\/ Minimum power\n 125000, \/\/ 125kHz bandwidth\n 6, \/\/ low spreading factor, we do not need high RX sensitivity\n 5, \/\/ same for coding rate\n 868000000 \/\/Fixed frequency while binding\n );\n bindModeExitMillis = millis() + 1000; \/\/This happens only on RX\n}\n\nvoid PlatformNode::leaveBindMode(void) {\n isBindMode = false;\n loadBindKey(bindKey);\n radioNode.reset();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (Apache License)\n *\n * Copyright (c) 2014, Dan Solomon\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <console_bridge\/console.h>\n\n#include \"descartes_moveit\/moveit_state_adapter.h\"\n#include \"descartes_core\/pretty_print.hpp\"\n#include \"descartes_moveit\/seed_search.h\"\n\n#include <eigen_conversions\/eigen_msg.h>\n#include <random_numbers\/random_numbers.h>\n#include <ros\/assert.h>\n#include <sstream>\n\nconst static int SAMPLE_ITERATIONS = 10;\n\nnamespace\n{\nbool getJointVelocityLimits(const moveit::core::RobotState& state, const std::string& group_name,\n std::vector<double>& output)\n{\n std::vector<double> result;\n\n auto models = state.getJointModelGroup(group_name)->getActiveJointModels();\n for (const moveit::core::JointModel* model : models)\n {\n const auto& bounds = model->getVariableBounds();\n \/\/ Check to see if there is a single bounds constraint (more might indicate\n \/\/ not revolute joint)\n if (model->getType() != moveit::core::JointModel::REVOLUTE &&\n model->getType() != moveit::core::JointModel::PRISMATIC)\n {\n ROS_ERROR_STREAM(__FUNCTION__ << \" Unexpected joint type. Currently works only\"\n \" with single axis prismatic or revolute joints.\");\n return false;\n }\n else\n {\n result.push_back(bounds[0].max_velocity_);\n }\n }\n\n output = result;\n return true;\n}\n\n} \/\/ end anon namespace\n\nnamespace descartes_moveit\n{\nMoveitStateAdapter::MoveitStateAdapter() : world_to_root_(Eigen::Affine3d::Identity())\n{\n}\n\nbool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,\n const std::string& world_frame, const std::string& tcp_frame)\n{\n \/\/ Initialize MoveIt state objects\n robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));\n auto model = robot_model_loader_->getModel();\n if (!model)\n {\n logError(\"Failed to load robot model from robot description parameter: %s\", robot_description.c_str());\n return false;\n }\n\n return initialize(model, group_name, world_frame, tcp_frame);\n}\n\nbool MoveitStateAdapter::initialize(robot_model::RobotModelConstPtr robot_model, const std::string &group_name,\n const std::string &world_frame, const std::string &tcp_frame)\n{\n robot_model_ptr_ = robot_model;\n robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));\n robot_state_->setToDefaultValues();\n planning_scene_.reset(new planning_scene::PlanningScene(robot_model));\n joint_group_ = robot_model_ptr_->getJointModelGroup(group_name);\n\n \/\/ Assign robot frames\n group_name_ = group_name;\n tool_frame_ = tcp_frame;\n world_frame_ = world_frame;\n\n \/\/ Validate our model inputs w\/ URDF\n if (!joint_group_)\n {\n logError(\"%s: Joint group '%s' does not exist in robot model\", __FUNCTION__, group_name_.c_str());\n std::stringstream msg;\n msg << \"Possible group names: \" << robot_state_->getRobotModel()->getJointModelGroupNames();\n logError(msg.str().c_str());\n return false;\n }\n\n const auto& link_names = joint_group_->getLinkModelNames();\n if (tool_frame_ != link_names.back())\n {\n logError(\"%s: Tool frame '%s' does not match group tool frame '%s', functionality\"\n \"will be implemented in the future\",\n __FUNCTION__, tool_frame_.c_str(), link_names.back().c_str());\n return false;\n }\n\n if (!::getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))\n {\n logWarn(\"%s: Could not determine velocity limits of RobotModel from MoveIt\", __FUNCTION__);\n }\n\n if (seed_states_.empty())\n {\n seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);\n logDebug(\"Generated %lu random seeds\", static_cast<unsigned long>(seed_states_.size()));\n }\n\n auto model_frame = robot_state_->getRobotModel()->getModelFrame();\n if (world_frame_ != model_frame)\n {\n logInform(\"%s: World frame '%s' does not match model root frame '%s', all poses will be\"\n \" transformed to world frame '%s'\",\n __FUNCTION__, world_frame_.c_str(), model_frame.c_str(), world_frame_.c_str());\n\n Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);\n world_to_root_ = descartes_core::Frame(root_to_world.inverse());\n }\n\n return true;\n}\n\nbool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, const std::vector<double>& seed_state,\n std::vector<double>& joint_pose) const\n{\n robot_state_->setJointGroupPositions(group_name_, seed_state);\n return getIK(pose, joint_pose);\n}\n\nbool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, std::vector<double>& joint_pose) const\n{\n bool rtn = false;\n\n \/\/ transform to group base\n Eigen::Affine3d tool_pose = world_to_root_.frame * pose;\n\n if (robot_state_->setFromIK(joint_group_, tool_pose, tool_frame_))\n {\n robot_state_->copyJointGroupPositions(group_name_, joint_pose);\n if (!isValid(joint_pose))\n {\n ROS_DEBUG_STREAM(\"Robot joint pose is invalid\");\n }\n else\n {\n rtn = true;\n }\n }\n else\n {\n rtn = false;\n }\n\n return rtn;\n}\n\nbool MoveitStateAdapter::getAllIK(const Eigen::Affine3d& pose, std::vector<std::vector<double> >& joint_poses) const\n{\n \/\/ The minimum difference between solutions should be greater than the search discretization\n \/\/ used by the IK solver. This value is multiplied by 4 to remove any chance that a solution\n \/\/ in the middle of a discretization step could be double counted. In reality, we'd like solutions\n \/\/ to be further apart than this.\n double epsilon = 4 * joint_group_->getSolverInstance()->getSearchDiscretization();\n logDebug(\"Utilizing an min. difference of %f between IK solutions\", epsilon);\n joint_poses.clear();\n for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)\n {\n robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);\n std::vector<double> joint_pose;\n if (getIK(pose, joint_pose))\n {\n if (joint_poses.empty())\n {\n std::stringstream msg;\n msg << \"Found *first* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n joint_poses.push_back(joint_pose);\n }\n else\n {\n std::stringstream msg;\n msg << \"Found *potential* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n\n std::vector<std::vector<double> >::iterator joint_pose_it;\n bool match_found = false;\n for (joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)\n {\n if (descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon))\n {\n logDebug(\"Found matching, potential solution is not new\");\n match_found = true;\n break;\n }\n }\n if (!match_found)\n {\n std::stringstream msg;\n msg << \"Found *new* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n joint_poses.push_back(joint_pose);\n }\n }\n }\n }\n\n logDebug(\"Found %lu joint solutions out of %lu iterations\", static_cast<unsigned long>(joint_poses.size()),\n static_cast<unsigned long>(seed_states_.size()));\n\n if (joint_poses.empty())\n {\n logError(\"Found 0 joint solutions out of %lu iterations\", static_cast<unsigned long>(seed_states_.size()));\n return false;\n }\n else\n {\n logInform(\"Found %lu joint solutions out of %lu iterations\", static_cast<unsigned long>(joint_poses.size()),\n static_cast<unsigned long>(seed_states_.size()));\n return true;\n }\n}\n\nbool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const\n{\n bool in_collision = false;\n if (check_collisions_)\n {\n moveit::core::RobotState state (robot_model_ptr_);\n state.setToDefaultValues();\n robot_state_->setJointGroupPositions(joint_group_, joint_pose);\n in_collision = planning_scene_->isStateColliding(state, group_name_);\n }\n return in_collision;\n}\n\nbool MoveitStateAdapter::isInLimits(const std::vector<double> &joint_pose) const\n{\n return joint_group_->satisfiesPositionBounds(joint_pose.data());\n}\n\nbool MoveitStateAdapter::getFK(const std::vector<double>& joint_pose, Eigen::Affine3d& pose) const\n{\n bool rtn = false;\n robot_state_->setJointGroupPositions(group_name_, joint_pose);\n if (isValid(joint_pose))\n {\n if (robot_state_->knowsFrameTransform(tool_frame_))\n {\n pose = world_to_root_.frame * robot_state_->getFrameTransform(tool_frame_);\n rtn = true;\n }\n else\n {\n logError(\"Robot state does not recognize tool frame: %s\", tool_frame_.c_str());\n rtn = false;\n }\n }\n else\n {\n logError(\"Invalid joint pose passed to get forward kinematics\");\n rtn = false;\n }\n\n return rtn;\n}\n\nbool MoveitStateAdapter::isValid(const std::vector<double>& joint_pose) const\n{\n \/\/ Logical check on input sizes\n if (joint_group_->getActiveJointModels().size() != joint_pose.size())\n {\n logError(\"Size of joint pose: %lu doesn't match robot state variable size: %lu\",\n static_cast<unsigned long>(joint_pose.size()),\n static_cast<unsigned long>(joint_group_->getActiveJointModels().size()));\n return false;\n }\n\n return isInLimits(joint_pose) && !isInCollision(joint_pose);\n}\n\nbool MoveitStateAdapter::isValid(const Eigen::Affine3d& pose) const\n{\n \/\/ TODO: Could check robot extents first as a quick check\n std::vector<double> dummy;\n return getIK(pose, dummy);\n}\n\nint MoveitStateAdapter::getDOF() const\n{\n return joint_group_->getVariableCount();\n}\n\nbool MoveitStateAdapter::isValidMove(const double* from_joint_pose,\n const double* to_joint_pose, double dt) const\n{\n\n for (std::size_t i = 0; i < getDOF(); ++i)\n {\n double dtheta = std::abs(from_joint_pose[i] - to_joint_pose[i]);\n double max_dtheta = dt * velocity_limits_[i];\n if (dtheta > max_dtheta)\n return false;\n }\n\n return true;\n}\n\nstd::vector<double> MoveitStateAdapter::getJointVelocityLimits() const\n{\n return velocity_limits_;\n}\n\nvoid MoveitStateAdapter::setState(const moveit::core::RobotState& state)\n{\n ROS_ASSERT_MSG(static_cast<bool>(robot_state_), \"'robot_state_' member pointer is null. Have you called \"\n \"initialize()?\");\n *robot_state_ = state;\n planning_scene_->setCurrentState(state);\n}\n\n} \/\/ descartes_moveit\n<commit_msg>Fixed a screw up where the global robot state was being used for setting a groups position instead of the locally created one. The change was originally made for thread safety but this meant collision checking was just all kinds of wrong<commit_after>\/*\n * Software License Agreement (Apache License)\n *\n * Copyright (c) 2014, Dan Solomon\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <console_bridge\/console.h>\n\n#include \"descartes_moveit\/moveit_state_adapter.h\"\n#include \"descartes_core\/pretty_print.hpp\"\n#include \"descartes_moveit\/seed_search.h\"\n\n#include <eigen_conversions\/eigen_msg.h>\n#include <random_numbers\/random_numbers.h>\n#include <ros\/assert.h>\n#include <sstream>\n\nconst static int SAMPLE_ITERATIONS = 10;\n\nnamespace\n{\nbool getJointVelocityLimits(const moveit::core::RobotState& state, const std::string& group_name,\n std::vector<double>& output)\n{\n std::vector<double> result;\n\n auto models = state.getJointModelGroup(group_name)->getActiveJointModels();\n for (const moveit::core::JointModel* model : models)\n {\n const auto& bounds = model->getVariableBounds();\n \/\/ Check to see if there is a single bounds constraint (more might indicate\n \/\/ not revolute joint)\n if (model->getType() != moveit::core::JointModel::REVOLUTE &&\n model->getType() != moveit::core::JointModel::PRISMATIC)\n {\n ROS_ERROR_STREAM(__FUNCTION__ << \" Unexpected joint type. Currently works only\"\n \" with single axis prismatic or revolute joints.\");\n return false;\n }\n else\n {\n result.push_back(bounds[0].max_velocity_);\n }\n }\n\n output = result;\n return true;\n}\n\n} \/\/ end anon namespace\n\nnamespace descartes_moveit\n{\nMoveitStateAdapter::MoveitStateAdapter() : world_to_root_(Eigen::Affine3d::Identity())\n{\n}\n\nbool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,\n const std::string& world_frame, const std::string& tcp_frame)\n{\n \/\/ Initialize MoveIt state objects\n robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));\n auto model = robot_model_loader_->getModel();\n if (!model)\n {\n logError(\"Failed to load robot model from robot description parameter: %s\", robot_description.c_str());\n return false;\n }\n\n return initialize(model, group_name, world_frame, tcp_frame);\n}\n\nbool MoveitStateAdapter::initialize(robot_model::RobotModelConstPtr robot_model, const std::string &group_name,\n const std::string &world_frame, const std::string &tcp_frame)\n{\n robot_model_ptr_ = robot_model;\n robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));\n robot_state_->setToDefaultValues();\n planning_scene_.reset(new planning_scene::PlanningScene(robot_model));\n joint_group_ = robot_model_ptr_->getJointModelGroup(group_name);\n\n \/\/ Assign robot frames\n group_name_ = group_name;\n tool_frame_ = tcp_frame;\n world_frame_ = world_frame;\n\n \/\/ Validate our model inputs w\/ URDF\n if (!joint_group_)\n {\n logError(\"%s: Joint group '%s' does not exist in robot model\", __FUNCTION__, group_name_.c_str());\n std::stringstream msg;\n msg << \"Possible group names: \" << robot_state_->getRobotModel()->getJointModelGroupNames();\n logError(msg.str().c_str());\n return false;\n }\n\n const auto& link_names = joint_group_->getLinkModelNames();\n if (tool_frame_ != link_names.back())\n {\n logError(\"%s: Tool frame '%s' does not match group tool frame '%s', functionality\"\n \"will be implemented in the future\",\n __FUNCTION__, tool_frame_.c_str(), link_names.back().c_str());\n return false;\n }\n\n if (!::getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))\n {\n logWarn(\"%s: Could not determine velocity limits of RobotModel from MoveIt\", __FUNCTION__);\n }\n\n if (seed_states_.empty())\n {\n seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);\n logDebug(\"Generated %lu random seeds\", static_cast<unsigned long>(seed_states_.size()));\n }\n\n auto model_frame = robot_state_->getRobotModel()->getModelFrame();\n if (world_frame_ != model_frame)\n {\n logInform(\"%s: World frame '%s' does not match model root frame '%s', all poses will be\"\n \" transformed to world frame '%s'\",\n __FUNCTION__, world_frame_.c_str(), model_frame.c_str(), world_frame_.c_str());\n\n Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);\n world_to_root_ = descartes_core::Frame(root_to_world.inverse());\n }\n\n return true;\n}\n\nbool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, const std::vector<double>& seed_state,\n std::vector<double>& joint_pose) const\n{\n robot_state_->setJointGroupPositions(group_name_, seed_state);\n return getIK(pose, joint_pose);\n}\n\nbool MoveitStateAdapter::getIK(const Eigen::Affine3d& pose, std::vector<double>& joint_pose) const\n{\n bool rtn = false;\n\n \/\/ transform to group base\n Eigen::Affine3d tool_pose = world_to_root_.frame * pose;\n\n if (robot_state_->setFromIK(joint_group_, tool_pose, tool_frame_))\n {\n robot_state_->copyJointGroupPositions(group_name_, joint_pose);\n if (!isValid(joint_pose))\n {\n ROS_DEBUG_STREAM(\"Robot joint pose is invalid\");\n }\n else\n {\n rtn = true;\n }\n }\n else\n {\n rtn = false;\n }\n\n return rtn;\n}\n\nbool MoveitStateAdapter::getAllIK(const Eigen::Affine3d& pose, std::vector<std::vector<double> >& joint_poses) const\n{\n \/\/ The minimum difference between solutions should be greater than the search discretization\n \/\/ used by the IK solver. This value is multiplied by 4 to remove any chance that a solution\n \/\/ in the middle of a discretization step could be double counted. In reality, we'd like solutions\n \/\/ to be further apart than this.\n double epsilon = 4 * joint_group_->getSolverInstance()->getSearchDiscretization();\n logDebug(\"Utilizing an min. difference of %f between IK solutions\", epsilon);\n joint_poses.clear();\n for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)\n {\n robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);\n std::vector<double> joint_pose;\n if (getIK(pose, joint_pose))\n {\n if (joint_poses.empty())\n {\n std::stringstream msg;\n msg << \"Found *first* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n joint_poses.push_back(joint_pose);\n }\n else\n {\n std::stringstream msg;\n msg << \"Found *potential* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n\n std::vector<std::vector<double> >::iterator joint_pose_it;\n bool match_found = false;\n for (joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)\n {\n if (descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon))\n {\n logDebug(\"Found matching, potential solution is not new\");\n match_found = true;\n break;\n }\n }\n if (!match_found)\n {\n std::stringstream msg;\n msg << \"Found *new* solution on \" << sample_iter << \" iteration, joint: \" << joint_pose;\n logDebug(msg.str().c_str());\n joint_poses.push_back(joint_pose);\n }\n }\n }\n }\n\n logDebug(\"Found %lu joint solutions out of %lu iterations\", static_cast<unsigned long>(joint_poses.size()),\n static_cast<unsigned long>(seed_states_.size()));\n\n if (joint_poses.empty())\n {\n logError(\"Found 0 joint solutions out of %lu iterations\", static_cast<unsigned long>(seed_states_.size()));\n return false;\n }\n else\n {\n logInform(\"Found %lu joint solutions out of %lu iterations\", static_cast<unsigned long>(joint_poses.size()),\n static_cast<unsigned long>(seed_states_.size()));\n return true;\n }\n}\n\nbool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const\n{\n bool in_collision = false;\n if (check_collisions_)\n {\n moveit::core::RobotState state (robot_model_ptr_);\n state.setToDefaultValues();\n state.setJointGroupPositions(joint_group_, joint_pose);\n in_collision = planning_scene_->isStateColliding(state, group_name_);\n }\n return in_collision;\n}\n\nbool MoveitStateAdapter::isInLimits(const std::vector<double> &joint_pose) const\n{\n return joint_group_->satisfiesPositionBounds(joint_pose.data());\n}\n\nbool MoveitStateAdapter::getFK(const std::vector<double>& joint_pose, Eigen::Affine3d& pose) const\n{\n bool rtn = false;\n robot_state_->setJointGroupPositions(group_name_, joint_pose);\n if (isValid(joint_pose))\n {\n if (robot_state_->knowsFrameTransform(tool_frame_))\n {\n pose = world_to_root_.frame * robot_state_->getFrameTransform(tool_frame_);\n rtn = true;\n }\n else\n {\n logError(\"Robot state does not recognize tool frame: %s\", tool_frame_.c_str());\n rtn = false;\n }\n }\n else\n {\n logError(\"Invalid joint pose passed to get forward kinematics\");\n rtn = false;\n }\n\n return rtn;\n}\n\nbool MoveitStateAdapter::isValid(const std::vector<double>& joint_pose) const\n{\n \/\/ Logical check on input sizes\n if (joint_group_->getActiveJointModels().size() != joint_pose.size())\n {\n logError(\"Size of joint pose: %lu doesn't match robot state variable size: %lu\",\n static_cast<unsigned long>(joint_pose.size()),\n static_cast<unsigned long>(joint_group_->getActiveJointModels().size()));\n return false;\n }\n\n return isInLimits(joint_pose) && !isInCollision(joint_pose);\n}\n\nbool MoveitStateAdapter::isValid(const Eigen::Affine3d& pose) const\n{\n \/\/ TODO: Could check robot extents first as a quick check\n std::vector<double> dummy;\n return getIK(pose, dummy);\n}\n\nint MoveitStateAdapter::getDOF() const\n{\n return joint_group_->getVariableCount();\n}\n\nbool MoveitStateAdapter::isValidMove(const double* from_joint_pose,\n const double* to_joint_pose, double dt) const\n{\n\n for (std::size_t i = 0; i < getDOF(); ++i)\n {\n double dtheta = std::abs(from_joint_pose[i] - to_joint_pose[i]);\n double max_dtheta = dt * velocity_limits_[i];\n if (dtheta > max_dtheta)\n return false;\n }\n\n return true;\n}\n\nstd::vector<double> MoveitStateAdapter::getJointVelocityLimits() const\n{\n return velocity_limits_;\n}\n\nvoid MoveitStateAdapter::setState(const moveit::core::RobotState& state)\n{\n ROS_ASSERT_MSG(static_cast<bool>(robot_state_), \"'robot_state_' member pointer is null. Have you called \"\n \"initialize()?\");\n *robot_state_ = state;\n planning_scene_->setCurrentState(state);\n}\n\n} \/\/ descartes_moveit\n<|endoftext|>"} {"text":"<commit_before>\/\/ Virvo - Virtual Reality Volume Rendering\n\/\/ Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University\n\/\/ Contact: Jurgen P. Schulze, jschulze@ucsd.edu\n\/\/\n\/\/ This file is part of Virvo.\n\/\/\n\/\/ Virvo is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library (see license.txt); if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"util.h\"\n\n#include <GL\/glew.h>\n\n#ifdef _WIN32\n#include <Windows.h>\n#endif\n\n#include <stdio.h>\n#include <stdarg.h>\n\n\nnamespace gl = virvo::gl;\n\n\n#ifndef APIENTRY\n#define APIENTRY\n#endif\n\n\n#ifndef NDEBUG\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#if defined(GL_KHR_debug)\nstatic char const* GetDebugTypeString(GLenum type)\n{\n switch (type)\n {\n case GL_DEBUG_TYPE_ERROR:\n return \"error\";\n case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n return \"deprecated behavior detected\";\n case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:\n return \"undefined behavior detected\";\n case GL_DEBUG_TYPE_PORTABILITY:\n return \"portablility warning\";\n case GL_DEBUG_TYPE_PERFORMANCE:\n return \"performance warning\";\n case GL_DEBUG_TYPE_OTHER:\n return \"other\";\n case GL_DEBUG_TYPE_MARKER:\n return \"marker\";\n }\n\n return \"{unknown type}\";\n}\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#ifdef _WIN32\nstatic void OutputDebugStringAF(char const* format, ...)\n{\n char text[1024] = {0};\n\n va_list args;\n va_start(args, format);\n\n vsnprintf_s(text, _TRUNCATE, format, args);\n\n va_end(args);\n\n OutputDebugStringA(text);\n}\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#if defined(GL_KHR_debug)\nstatic void APIENTRY DebugCallback( GLenum \/*source*\/,\n GLenum type,\n GLuint \/*id*\/,\n GLenum \/*severity*\/,\n GLsizei \/*length*\/,\n const GLchar* message,\n GLvoid* \/*userParam*\/\n )\n{\n if (type != GL_DEBUG_TYPE_ERROR)\n return;\n\n#ifdef _WIN32\n if (IsDebuggerPresent())\n {\n OutputDebugStringAF(\"GL %s: %s\\n\", GetDebugTypeString(type), message);\n DebugBreak();\n }\n#endif\n\n fprintf(stderr, \"GL %s: %s\\n\", GetDebugTypeString(type), message);\n}\n#endif\n\n#endif \/\/ !NDEBUG\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::enableDebugCallback()\n{\n#if !defined(NDEBUG) && defined(GL_KHR_debug)\n if (GLEW_KHR_debug)\n {\n glEnable(GL_DEBUG_OUTPUT);\n glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);\n\n glDebugMessageCallback(DebugCallback, 0);\n }\n#endif \/\/ !NDEBUG\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nGLenum gl::getError(char const* file, int line)\n{\n GLenum err = glGetError();\n\n if (err != GL_NO_ERROR)\n fprintf(stderr, \"%s(%d) : GL error: %s\\n\", file, line, gluErrorString(err));\n\n return err;\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nstatic char const* GetFramebufferStatusString(GLenum status)\n{\n switch (status)\n {\n case GL_FRAMEBUFFER_COMPLETE:\n return \"framebuffer complete\";\n case GL_FRAMEBUFFER_UNDEFINED:\n return \"framebuffer undefined\";\n case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return \"framebuffer incomplete attachment\";\n case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return \"framebuffer incomplete missing attachment\";\n case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:\n return \"framebuffer incomplete draw buffer\";\n case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:\n return \"framebuffer incomplete read buffer\";\n case GL_FRAMEBUFFER_UNSUPPORTED:\n return \"framebuffer unsupported\";\n case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n return \"framebuffer incomplete multisample\";\n case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:\n return \"framebuffer incomplete layer targets\";\n default:\n return \"{unknown status}\";\n }\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nGLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)\n{\n GLenum status = glCheckFramebufferStatus(target);\n\n if (status != GL_FRAMEBUFFER_COMPLETE)\n fprintf(stderr, \"%s(%d) : GL framebuffer error: %s\\n\", file, line, GetFramebufferStatusString(status));\n\n return status;\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nstatic void DrawFullScreenQuad()\n{\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);\n glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);\n glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);\n glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);\n glEnd();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glActiveTexture(GL_TEXTURE0);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texture);\n\n glDepthMask(GL_FALSE);\n\n DrawFullScreenQuad();\n\n glPopAttrib();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendTexture(GLuint texture)\n{\n blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_COLOR_BUFFER_BIT);\n\n GLint viewport[4];\n\n glGetIntegerv(GL_VIEWPORT, &viewport[0]);\n\n glWindowPos2i(viewport[0], viewport[1]);\n\n GLfloat scaleX = static_cast<GLfloat>(viewport[2]) \/ srcW;\n GLfloat scaleY = static_cast<GLfloat>(viewport[3]) \/ srcH;\n\n glPixelZoom(scaleX, scaleY);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glDrawPixels(srcW, srcH, format, type, pixels);\n\n glPopAttrib();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)\n{\n blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::renderInterlacedStereoStencilBuffer(bool lines)\n{\n static const GLubyte kPatternLines[32*(32\/8)] = {\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n };\n\n static const GLubyte kPatternCheckerBoard[32*(32\/8)] = {\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n };\n\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);\n\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_SCISSOR_TEST);\n glDisable(GL_LIGHTING);\n\n glColorMask(0, 0, 0, 0);\n glDepthMask(0);\n\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n glEnable(GL_POLYGON_STIPPLE);\n if (lines)\n glPolygonStipple(kPatternLines);\n else\n glPolygonStipple(kPatternCheckerBoard);\n\n glEnable(GL_STENCIL_TEST);\n glStencilMask(0xFFFFFFFF);\n glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);\n glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);\n\n DrawFullScreenQuad();\n\n glPopAttrib();\n glPopClientAttrib();\n}\n<commit_msg>check for GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS before use<commit_after>\/\/ Virvo - Virtual Reality Volume Rendering\n\/\/ Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University\n\/\/ Contact: Jurgen P. Schulze, jschulze@ucsd.edu\n\/\/\n\/\/ This file is part of Virvo.\n\/\/\n\/\/ Virvo is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library (see license.txt); if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"util.h\"\n\n#include <GL\/glew.h>\n\n#ifdef _WIN32\n#include <Windows.h>\n#endif\n\n#include <stdio.h>\n#include <stdarg.h>\n\n\nnamespace gl = virvo::gl;\n\n\n#ifndef APIENTRY\n#define APIENTRY\n#endif\n\n\n#ifndef NDEBUG\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#if defined(GL_KHR_debug)\nstatic char const* GetDebugTypeString(GLenum type)\n{\n switch (type)\n {\n case GL_DEBUG_TYPE_ERROR:\n return \"error\";\n case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n return \"deprecated behavior detected\";\n case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:\n return \"undefined behavior detected\";\n case GL_DEBUG_TYPE_PORTABILITY:\n return \"portablility warning\";\n case GL_DEBUG_TYPE_PERFORMANCE:\n return \"performance warning\";\n case GL_DEBUG_TYPE_OTHER:\n return \"other\";\n case GL_DEBUG_TYPE_MARKER:\n return \"marker\";\n }\n\n return \"{unknown type}\";\n}\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#ifdef _WIN32\nstatic void OutputDebugStringAF(char const* format, ...)\n{\n char text[1024] = {0};\n\n va_list args;\n va_start(args, format);\n\n vsnprintf_s(text, _TRUNCATE, format, args);\n\n va_end(args);\n\n OutputDebugStringA(text);\n}\n#endif\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\n#if defined(GL_KHR_debug)\nstatic void APIENTRY DebugCallback( GLenum \/*source*\/,\n GLenum type,\n GLuint \/*id*\/,\n GLenum \/*severity*\/,\n GLsizei \/*length*\/,\n const GLchar* message,\n GLvoid* \/*userParam*\/\n )\n{\n if (type != GL_DEBUG_TYPE_ERROR)\n return;\n\n#ifdef _WIN32\n if (IsDebuggerPresent())\n {\n OutputDebugStringAF(\"GL %s: %s\\n\", GetDebugTypeString(type), message);\n DebugBreak();\n }\n#endif\n\n fprintf(stderr, \"GL %s: %s\\n\", GetDebugTypeString(type), message);\n}\n#endif\n\n#endif \/\/ !NDEBUG\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::enableDebugCallback()\n{\n#if !defined(NDEBUG) && defined(GL_KHR_debug)\n if (GLEW_KHR_debug)\n {\n glEnable(GL_DEBUG_OUTPUT);\n glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);\n\n glDebugMessageCallback(DebugCallback, 0);\n }\n#endif \/\/ !NDEBUG\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nGLenum gl::getError(char const* file, int line)\n{\n GLenum err = glGetError();\n\n if (err != GL_NO_ERROR)\n fprintf(stderr, \"%s(%d) : GL error: %s\\n\", file, line, gluErrorString(err));\n\n return err;\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nstatic char const* GetFramebufferStatusString(GLenum status)\n{\n switch (status)\n {\n case GL_FRAMEBUFFER_COMPLETE:\n return \"framebuffer complete\";\n case GL_FRAMEBUFFER_UNDEFINED:\n return \"framebuffer undefined\";\n case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return \"framebuffer incomplete attachment\";\n case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return \"framebuffer incomplete missing attachment\";\n case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:\n return \"framebuffer incomplete draw buffer\";\n case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:\n return \"framebuffer incomplete read buffer\";\n case GL_FRAMEBUFFER_UNSUPPORTED:\n return \"framebuffer unsupported\";\n case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n return \"framebuffer incomplete multisample\";\n#ifdef GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\n case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:\n return \"framebuffer incomplete layer targets\";\n#endif\n default:\n return \"{unknown status}\";\n }\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nGLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)\n{\n GLenum status = glCheckFramebufferStatus(target);\n\n if (status != GL_FRAMEBUFFER_COMPLETE)\n fprintf(stderr, \"%s(%d) : GL framebuffer error: %s\\n\", file, line, GetFramebufferStatusString(status));\n\n return status;\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nstatic void DrawFullScreenQuad()\n{\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);\n glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);\n glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);\n glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);\n glEnd();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glActiveTexture(GL_TEXTURE0);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texture);\n\n glDepthMask(GL_FALSE);\n\n DrawFullScreenQuad();\n\n glPopAttrib();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendTexture(GLuint texture)\n{\n blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_COLOR_BUFFER_BIT);\n\n GLint viewport[4];\n\n glGetIntegerv(GL_VIEWPORT, &viewport[0]);\n\n glWindowPos2i(viewport[0], viewport[1]);\n\n GLfloat scaleX = static_cast<GLfloat>(viewport[2]) \/ srcW;\n GLfloat scaleY = static_cast<GLfloat>(viewport[3]) \/ srcH;\n\n glPixelZoom(scaleX, scaleY);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glDrawPixels(srcW, srcH, format, type, pixels);\n\n glPopAttrib();\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)\n{\n blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n}\n\n\n\/\/--------------------------------------------------------------------------------------------------\n\/\/\n\/\/--------------------------------------------------------------------------------------------------\nvoid gl::renderInterlacedStereoStencilBuffer(bool lines)\n{\n static const GLubyte kPatternLines[32*(32\/8)] = {\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0xFF, 0xFF, 0xFF, 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n };\n\n static const GLubyte kPatternCheckerBoard[32*(32\/8)] = {\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n 0xAA, 0xAA, 0xAA, 0xAA,\n 0x55, 0x55, 0x55, 0x55,\n };\n\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);\n\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_SCISSOR_TEST);\n glDisable(GL_LIGHTING);\n\n glColorMask(0, 0, 0, 0);\n glDepthMask(0);\n\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n glEnable(GL_POLYGON_STIPPLE);\n if (lines)\n glPolygonStipple(kPatternLines);\n else\n glPolygonStipple(kPatternCheckerBoard);\n\n glEnable(GL_STENCIL_TEST);\n glStencilMask(0xFFFFFFFF);\n glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);\n glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);\n\n DrawFullScreenQuad();\n\n glPopAttrib();\n glPopClientAttrib();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Virvo - Virtual Reality Volume Rendering\n\/\/ Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University\n\/\/ Contact: Jurgen P. Schulze, jschulze@ucsd.edu\n\/\/\n\/\/ This file is part of Virvo.\n\/\/\n\/\/ Virvo is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library (see license.txt); if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"vvvirvo.h\"\n\n#include <algorithm>\n#include <locale>\n#include <string>\n\n#ifdef HAVE_CONFIG_H\n#include \"vvconfig.h\"\n#endif\n\n#define VV_STRINGIFY(X) VV_STRINGIFY2(X)\n#define VV_STRINGIFY2(X) #X\n\nconst char* virvo::version()\n{\n return VV_STRINGIFY(VV_VERSION_MAJOR) \".\" VV_STRINGIFY(VV_VERSION_MINOR);\n}\n\nbool virvo::hasFeature(const char* name)\n{\n#ifndef HAVE_CONFIG_H\n return false;\n#endif\n\n std::string str = name;\n std::transform(str.begin(), str.end(), str.begin(), ::tolower);\n\n if (str == \"bonjour\")\n {\n#ifdef HAVE_BONJOUR\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"cg\")\n {\n#ifdef HAVE_CG\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"cuda\")\n {\n#ifdef HAVE_CUDA\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"ffmpeg\")\n {\n#ifdef HAVE_FFMEPG\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"gl\" || str == \"opengl\")\n {\n#ifdef HAVE_GL\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"glu\")\n {\n#ifdef HAVE_GLU\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"nifty\")\n {\n#if VV_HAVE_NIFTI\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"snappy\")\n {\n#ifdef HAVE_SNAPPY\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"volpack\")\n {\n#ifdef HAVE_VOLPACK\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"x11\")\n {\n#ifdef HAVE_X11\n return true;\n#else\n return false;\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\/\/ vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\\:0g0t0\n<commit_msg>Fix a typo<commit_after>\/\/ Virvo - Virtual Reality Volume Rendering\n\/\/ Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University\n\/\/ Contact: Jurgen P. Schulze, jschulze@ucsd.edu\n\/\/\n\/\/ This file is part of Virvo.\n\/\/\n\/\/ Virvo is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library (see license.txt); if not, write to the\n\/\/ Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n#include \"vvvirvo.h\"\n\n#include <algorithm>\n#include <locale>\n#include <string>\n\n#ifdef HAVE_CONFIG_H\n#include \"vvconfig.h\"\n#endif\n\n#define VV_STRINGIFY(X) VV_STRINGIFY2(X)\n#define VV_STRINGIFY2(X) #X\n\nconst char* virvo::version()\n{\n return VV_STRINGIFY(VV_VERSION_MAJOR) \".\" VV_STRINGIFY(VV_VERSION_MINOR);\n}\n\nbool virvo::hasFeature(const char* name)\n{\n#ifndef HAVE_CONFIG_H\n return false;\n#endif\n\n std::string str = name;\n std::transform(str.begin(), str.end(), str.begin(), ::tolower);\n\n if (str == \"bonjour\")\n {\n#ifdef HAVE_BONJOUR\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"cg\")\n {\n#ifdef HAVE_CG\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"cuda\")\n {\n#ifdef HAVE_CUDA\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"ffmpeg\")\n {\n#ifdef HAVE_FFMEPG\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"gl\" || str == \"opengl\")\n {\n#ifdef HAVE_GL\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"glu\")\n {\n#ifdef HAVE_GLU\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"nifti\")\n {\n#if VV_HAVE_NIFTI\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"snappy\")\n {\n#ifdef HAVE_SNAPPY\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"volpack\")\n {\n#ifdef HAVE_VOLPACK\n return true;\n#else\n return false;\n#endif\n }\n else if (str == \"x11\")\n {\n#ifdef HAVE_X11\n return true;\n#else\n return false;\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\/\/ vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\\:0g0t0\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n\n#include \"btree_str_kv.h\"\n#include \"test.h\"\n#include \"common.h\"\n#include \"list.h\"\n#include \"memleak.h\"\n\ntypedef uint16_t key_len_t;\n\nvoid kv_set_key_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n char str[] = \"teststring\";\n uint8_t *key = alca(uint8_t, sizeof(void *));\n size_t str_len = sizeof(str);\n\n \/\/ set key ptr\n btree_str_kv_set_key(key, str, str_len);\n void *kv_addr;\n memcpy(&kv_addr, key, sizeof(void *));\n\n \/\/ check key len\n key_len_t kv_len;\n memcpy(&kv_len, (key_len_t *)kv_addr, sizeof(key_len_t));\n key_len_t kv_len_dec = _endian_decode(kv_len);\n TEST_CHK(kv_len_dec == str_len);\n\n \/\/ check key size\n char kv_str[str_len];\n memcpy(kv_str, ((char *)kv_addr) + sizeof(key_len_t), str_len);\n int cmp = strcmp(kv_str, str);\n TEST_CHK(cmp == 0);\n free(kv_addr);\n\n memleak_end();\n TEST_RESULT(\"kv set key test\");\n}\n\n\nvoid construct_key_ptr(const char *str, const key_len_t len, void *key_ptr){\n void *key;\n key_len_t _str_len;\n key = (void *)malloc(sizeof(key_len_t) + len);\n _str_len = _endian_encode(len);\n memcpy(key, &_str_len, sizeof(key_len_t));\n memcpy((uint8_t*)key + sizeof(key_len_t), str, len);\n memcpy(key_ptr, &key, sizeof(void *));\n}\n\nvoid kv_get_key_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n \/\/ create kv ptr\n void *key;\n char str[] = \"teststring\";\n key_len_t str_len = sizeof(str);\n construct_key_ptr(str, str_len, &key);\n\n \/\/ get_key unpacks kv formated key\n char *strbuf = alca(char, str_len);\n size_t len;\n btree_str_kv_get_key(&key, strbuf, &len);\n\n \/\/ check results\n int cmp = strcmp(strbuf, str);\n TEST_CHK(cmp == 0);\n TEST_CHK(len ==str_len);\n free(key);\n\n memleak_end();\n TEST_RESULT(\"kv get key test\");\n}\n\nvoid kv_free_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n void *key;\n char str[] = \"teststring\";\n key_len_t str_len = sizeof(str);\n construct_key_ptr(str, str_len, &key);\n\n TEST_CHK(key != NULL);\n btree_str_kv_free_key(&key);\n TEST_CHK(key == NULL);\n\n memleak_end();\n TEST_RESULT(\"kv free test\");\n}\n\nint main()\n{\n\n #ifdef _MEMPOOL\n mempool_init();\n #endif\n\n kv_set_key_test();\n kv_get_key_test();\n kv_free_test();\n return 0;\n}\n<commit_msg>additional str_kv_tests with kv ops<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n\n#include \"btree.h\"\n#include \"btree_kv.h\"\n#include \"btree_str_kv.h\"\n#include \"btreeblock.h\"\n#include \"filemgr_ops.h\"\n#include \"test.h\"\n#include \"common.h\"\n#include \"list.h\"\n#include \"memleak.h\"\n\ntypedef uint16_t key_len_t;\n\n\nvoid freevars(void **vv, size_t n)\n{\n for(int i = 0; i < n; i++){\n free(vv[i]);\n }\n}\n\nvoid kv_set_key_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n char str[] = \"teststring\";\n uint8_t *key = alca(uint8_t, sizeof(void *));\n size_t str_len = sizeof(str);\n\n \/\/ set key ptr\n btree_str_kv_set_key(key, str, str_len);\n void *kv_addr;\n memcpy(&kv_addr, key, sizeof(void *));\n\n \/\/ check key len\n key_len_t kv_len;\n memcpy(&kv_len, (key_len_t *)kv_addr, sizeof(key_len_t));\n key_len_t kv_len_dec = _endian_decode(kv_len);\n TEST_CHK(kv_len_dec == str_len);\n\n \/\/ check key size\n char kv_str[str_len];\n memcpy(kv_str, ((char *)kv_addr) + sizeof(key_len_t), str_len);\n int cmp = strcmp(kv_str, str);\n TEST_CHK(cmp == 0);\n free(kv_addr);\n\n memleak_end();\n TEST_RESULT(\"kv set key test\");\n}\n\n\nvoid construct_key_ptr(const char *str, const key_len_t len, void *key_ptr){\n void *key;\n key_len_t _str_len;\n key = (void *)malloc(sizeof(key_len_t) + len);\n _str_len = _endian_encode(len);\n memcpy(key, &_str_len, sizeof(key_len_t));\n memcpy((uint8_t*)key + sizeof(key_len_t), str, len);\n memcpy(key_ptr, &key, sizeof(void *));\n}\n\nvoid kv_get_key_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n \/\/ create kv ptr\n void *key;\n char str[] = \"teststring\";\n key_len_t str_len = sizeof(str);\n construct_key_ptr(str, str_len, &key);\n\n \/\/ get_key unpacks kv formated key\n char *strbuf = alca(char, str_len);\n size_t len;\n btree_str_kv_get_key(&key, strbuf, &len);\n\n \/\/ check results\n int cmp = strcmp(strbuf, str);\n TEST_CHK(cmp == 0);\n TEST_CHK(len ==str_len);\n free(key);\n\n memleak_end();\n TEST_RESULT(\"kv get key test\");\n}\n\nvoid kv_get_key_isnull_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n void *key = NULL;\n char *strbuf;\n size_t len;\n btree_str_kv_get_key(&key, strbuf, &len);\n\n \/\/ check results\n TEST_CHK(len == 0);\n free(key);\n\n memleak_end();\n TEST_RESULT(\"kv get key is null test\");\n}\n\nvoid kv_free_test()\n{\n\n TEST_INIT();\n memleak_start();\n\n void *key;\n char str[] = \"teststring\";\n key_len_t str_len = sizeof(str);\n construct_key_ptr(str, str_len, &key);\n\n TEST_CHK(key != NULL);\n btree_str_kv_free_key(&key);\n TEST_CHK(key == NULL);\n\n memleak_end();\n TEST_RESULT(\"kv free test\");\n}\n\nstruct bnode* dummy_node(uint8_t ksize, uint8_t vsize, uint16_t level)\n{\n struct bnode *node;\n node = (struct bnode*)malloc(sizeof(bnode));\n memset(node, 0, sizeof(bnode));\n\n node->kvsize = ksize<<4 | vsize;\n node->level = level;\n node->data = (void *)malloc(node->kvsize);\n return node;\n}\n\n\nvoid kv_init_ops_test()\n{\n TEST_INIT();\n memleak_start();\n\n \/\/ init with null\n btree_kv_ops *kv_ops = btree_str_kv_get_kb64_vb64(NULL);\n TEST_CHK(kv_ops != NULL);\n\n \/\/ re-init with existing ops\n btree_kv_ops *kv_ops_copy = btree_str_kv_get_kb64_vb64(kv_ops);\n TEST_CHK(memcmp(kv_ops, kv_ops_copy, sizeof(btree_kv_ops)) == 0);\n\n free(kv_ops);\n memleak_end();\n TEST_RESULT(\"kv init ops test\");\n}\n\n\nvoid kv_init_var_test()\n{\n TEST_INIT();\n memleak_start();\n\n void *key, *value;\n btree_kv_ops *kv_ops = btree_str_kv_get_kb64_vb64(NULL);\n btree *tree = alca(struct btree, 1);\n uint8_t ksize = sizeof(void *);\n uint8_t vsize = 8;\n\n \/\/ unintialized key\/value\n key = NULL;\n value = NULL;\n kv_ops->init_kv_var(tree, key, value);\n TEST_CHK(key == NULL);\n TEST_CHK(value == NULL);\n\n \/\/ initialized\n key = (void *)alca(uint8_t, ksize);\n value = (void *)alca(uint8_t, vsize);\n tree->vsize = vsize;\n kv_ops->init_kv_var(tree, key, value);\n TEST_CHK( *(uint8_t *)key == 0 );\n TEST_CHK( *(uint8_t *)value == 0 );\n\n free(kv_ops);\n memleak_end();\n TEST_RESULT(\"kv init var test\");\n}\n\n\nvoid kv_set_var_test()\n{\n TEST_INIT();\n memleak_start();\n\n bnoderef node;\n btree_kv_ops *kv_ops;\n void *key, *value;\n uint8_t ksize, vsize;\n int level;\n uint64_t v;\n int cmp;\n idx_t idx;\n char str[] = \"teststring\";\n char str2[] = \"test\";\n key_len_t str_len = sizeof(str);\n\n vsize = sizeof(v);\n v = 10;\n\n construct_key_ptr(str, str_len, &key);\n value = alca(uint8_t, vsize);\n memset(value, 0, vsize);\n memcpy(value, &v, vsize);\n\n \/\/ init ops\n kv_ops = alca(btree_kv_ops, 1);\n btree_str_kv_get_kb64_vb64(kv_ops);\n\n \/\/ set key\/value in node\n idx = 0;\n level = 1;\n ksize = str_len + sizeof(key_len_t);\n node = dummy_node(ksize, vsize, level);\n kv_ops->set_kv(node, idx, &key, value);\n\n \/\/ verify node->data\n cmp = strcmp((char *)((uint8_t *)node->data + sizeof(key_len_t)), str);\n TEST_CHK(cmp == 0);\n cmp = memcmp((uint8_t *)node->data + ksize, value, vsize);\n TEST_CHK(cmp == 0);\n\n void *vars[] = {node->data, node, key};\n freevars(vars, sizeof(vars)\/sizeof(void *));\n\n memleak_end();\n TEST_RESULT(\"kv set var test\");\n}\n\nint main()\n{\n\n #ifdef _MEMPOOL\n mempool_init();\n #endif\n\n kv_set_key_test();\n kv_get_key_test();\n kv_get_key_isnull_test();\n kv_free_test();\n kv_init_ops_test();\n kv_init_var_test();\n kv_set_var_test();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017 Politecnico di Torino\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"BPF.h\"\n#include \"catch.hpp\"\n\nTEST_CASE(\"test bpf table\", \"[bpf_table]\") {\n const std::string BPF_PROGRAM = R\"(\n BPF_TABLE(\"hash\", int, int, myhash, 128);\n )\";\n\n ebpf::BPF *bpf(new ebpf::BPF);\n ebpf::StatusTuple res(0);\n res = bpf->init(BPF_PROGRAM);\n REQUIRE(res.code() == 0);\n\n ebpf::BPFTable t = bpf->get_table(\"myhash\");\n\n \/\/ update element\n std::string value;\n res = t.update_value(\"0x07\", \"0x42\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x07\", value);\n REQUIRE(res.code() == 0);\n REQUIRE(value == \"0x42\");\n\n \/\/ update another element\n res = t.update_value(\"0x11\", \"0x777\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x11\", value);\n REQUIRE(res.code() == 0);\n REQUIRE(value == \"0x777\");\n\n \/\/ remove value\n res = t.remove_value(\"0x11\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x11\", value);\n REQUIRE(res.code() != 0);\n\n \/\/ delete bpf_module, call to key\/leaf printf\/scanf must fail\n delete bpf;\n\n res = t.update_value(\"0x07\", \"0x42\");\n REQUIRE(res.code() != 0);\n\n res = t.get_value(\"0x07\", value);\n REQUIRE(res.code() != 0);\n\n res = t.remove_value(\"0x07\");\n REQUIRE(res.code() != 0);\n}\n<commit_msg>Add tests for C++ API Hash table and Stack table<commit_after>\/*\n * Copyright (c) 2017 Politecnico di Torino\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <linux\/version.h>\n#include <unistd.h>\n#include <string>\n\n#include \"BPF.h\"\n#include \"catch.hpp\"\n\nTEST_CASE(\"test bpf table\", \"[bpf_table]\") {\n const std::string BPF_PROGRAM = R\"(\n BPF_TABLE(\"hash\", int, int, myhash, 128);\n )\";\n\n ebpf::BPF *bpf(new ebpf::BPF);\n ebpf::StatusTuple res(0);\n res = bpf->init(BPF_PROGRAM);\n REQUIRE(res.code() == 0);\n\n ebpf::BPFTable t = bpf->get_table(\"myhash\");\n\n \/\/ update element\n std::string value;\n res = t.update_value(\"0x07\", \"0x42\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x07\", value);\n REQUIRE(res.code() == 0);\n REQUIRE(value == \"0x42\");\n\n \/\/ update another element\n res = t.update_value(\"0x11\", \"0x777\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x11\", value);\n REQUIRE(res.code() == 0);\n REQUIRE(value == \"0x777\");\n\n \/\/ remove value\n res = t.remove_value(\"0x11\");\n REQUIRE(res.code() == 0);\n res = t.get_value(\"0x11\", value);\n REQUIRE(res.code() != 0);\n\n \/\/ delete bpf_module, call to key\/leaf printf\/scanf must fail\n delete bpf;\n\n res = t.update_value(\"0x07\", \"0x42\");\n REQUIRE(res.code() != 0);\n\n res = t.get_value(\"0x07\", value);\n REQUIRE(res.code() != 0);\n\n res = t.remove_value(\"0x07\");\n REQUIRE(res.code() != 0);\n}\n\nTEST_CASE(\"test bpf hash table\", \"[bpf_hash_table]\") {\n const std::string BPF_PROGRAM = R\"(\n BPF_HASH(myhash, int, int, 128);\n )\";\n\n ebpf::BPF bpf;\n ebpf::StatusTuple res(0);\n res = bpf.init(BPF_PROGRAM);\n REQUIRE(res.code() == 0);\n\n auto t = bpf.get_hash_table<int, int>(\"myhash\");\n\n int key, value;\n\n \/\/ updaate element\n key = 0x08;\n value = 0x43;\n res = t.update_value(key, value);\n REQUIRE(res.code() == 0);\n REQUIRE(t[key] == value);\n\n \/\/ update another element\n key = 0x12;\n value = 0x778;\n res = t.update_value(key, value);\n REQUIRE(res.code() == 0);\n key = 0x31;\n value = 0x123;\n res = t.update_value(key, value);\n REQUIRE(res.code() == 0);\n key = 0x12;\n value = 0;\n res = t.get_value(key, value);\n REQUIRE(res.code() == 0);\n REQUIRE(value == 0x778);\n\n \/\/ remove value and dump table\n key = 0x12;\n res = t.remove_value(key);\n REQUIRE(res.code() == 0);\n auto values = t.get_table_offline();\n REQUIRE(values.size() == 2);\n\n \/\/ clear table\n res = t.clear_table_non_atomic();\n REQUIRE(res.code() == 0);\n values = t.get_table_offline();\n REQUIRE(values.size() == 0);\n}\n\nTEST_CASE(\"test bpf stack table\", \"[bpf_stack_table]\") {\n#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 6, 0)\n const std::string BPF_PROGRAM = R\"(\n BPF_HASH(id, int, int, 1);\n BPF_STACK_TRACE(stack_traces, 8);\n\n int on_sys_getuid(void *ctx) {\n int stack_id = stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID);\n int zero = 0, *val;\n val = id.lookup_or_init(&zero, &stack_id);\n (*val) = stack_id;\n }\n )\";\n\n ebpf::BPF bpf;\n ebpf::StatusTuple res(0);\n res = bpf.init(BPF_PROGRAM);\n REQUIRE(res.code() == 0);\n res = bpf.attach_kprobe(\"sys_getuid\", \"on_sys_getuid\");\n REQUIRE(res.code() == 0);\n REQUIRE(getuid() >= 0);\n res = bpf.detach_kprobe(\"sys_getuid\");\n REQUIRE(res.code() == 0);\n\n auto id = bpf.get_hash_table<int, int>(\"id\");\n auto stack_traces = bpf.get_stack_table(\"stack_traces\");\n\n int stack_id = id[0];\n REQUIRE(stack_id >= 0);\n\n auto addrs = stack_traces.get_stack_addr(stack_id);\n auto symbols = stack_traces.get_stack_symbol(stack_id, -1);\n REQUIRE(addrs.size() > 0);\n REQUIRE(addrs.size() == symbols.size());\n bool found = false;\n for (const auto &symbol : symbols)\n if (symbol.find(\"sys_getuid\") != std::string::npos) {\n found = true;\n break;\n }\n REQUIRE(found);\n\n stack_traces.clear_table_non_atomic();\n addrs = stack_traces.get_stack_addr(stack_id);\n REQUIRE(addrs.size() == 0);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 - 2018 Code 4 Game, Org. All Rights Reserved.\n\n#include \"glTFForUE4PrivatePCH.h\"\n#include \"glTFForUE4Module.h\"\n\n#include \"ModuleManager.h\"\n\n#define LOCTEXT_NAMESPACE \"FglTFForUE4Module\"\n\nclass FglTFForUE4Module : public IglTFForUE4Module\n{\npublic:\n \/** IModuleInterface implementation *\/\n virtual void StartupModule()\n {\n \/\/\n }\n\n virtual void ShutdownModule()\n {\n \/\/\n }\n};\n\n#undef LOCTEXT_NAMESPACE\n\nIMPLEMENT_MODULE(FglTFForUE4Module, glTFForUE4)\n<commit_msg>fix some errors for ue4.20 again<commit_after>\/\/ Copyright 2017 - 2018 Code 4 Game, Org. All Rights Reserved.\n\n#include \"glTFForUE4PrivatePCH.h\"\n#include \"glTFForUE4Module.h\"\n\n#include \"Modules\/ModuleManager.h\"\n\n#define LOCTEXT_NAMESPACE \"FglTFForUE4Module\"\n\nclass FglTFForUE4Module : public IglTFForUE4Module\n{\npublic:\n \/** IModuleInterface implementation *\/\n virtual void StartupModule()\n {\n \/\/\n }\n\n virtual void ShutdownModule()\n {\n \/\/\n }\n};\n\n#undef LOCTEXT_NAMESPACE\n\nIMPLEMENT_MODULE(FglTFForUE4Module, glTFForUE4)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Holger Hans Peter Freyther\n * Copyright (C) 2014 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"config.h\"\n#include \"platform\/fonts\/shaping\/SimpleShaper.h\"\n\n#include \"platform\/fonts\/Character.h\"\n#include \"platform\/fonts\/Font.h\"\n#include \"platform\/fonts\/GlyphBuffer.h\"\n#include \"platform\/fonts\/Latin1TextIterator.h\"\n#include \"platform\/fonts\/SimpleFontData.h\"\n#include \"platform\/text\/SurrogatePairAwareTextIterator.h\"\n#include \"wtf\/MathExtras.h\"\n\nusing namespace WTF;\nusing namespace Unicode;\n\nnamespace blink {\n\nSimpleShaper::SimpleShaper(const Font* font, const TextRun& run,\n HashSet<const SimpleFontData*>* fallbackFonts, GlyphBounds* bounds,\n bool forTextEmphasis)\n : m_font(font)\n , m_run(run)\n , m_currentCharacter(0)\n , m_runWidthSoFar(0)\n , m_isAfterExpansion(!run.allowsLeadingExpansion())\n , m_fallbackFonts(fallbackFonts)\n , m_bounds(bounds)\n , m_forTextEmphasis(forTextEmphasis)\n{\n \/\/ If the padding is non-zero, count the number of spaces in the run\n \/\/ and divide that by the padding for per space addition.\n m_expansion = m_run.expansion();\n if (!m_expansion) {\n m_expansionPerOpportunity = 0;\n } else {\n bool isAfterExpansion = m_isAfterExpansion;\n unsigned expansionOpportunityCount = m_run.is8Bit() ? Character::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify()) : Character::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify());\n if (isAfterExpansion && !m_run.allowsTrailingExpansion())\n expansionOpportunityCount--;\n\n if (!expansionOpportunityCount)\n m_expansionPerOpportunity = 0;\n else\n m_expansionPerOpportunity = m_expansion \/ expansionOpportunityCount;\n }\n}\n\nGlyphData SimpleShaper::glyphDataForCharacter(CharacterData& charData, bool normalizeSpace)\n{\n ASSERT(m_font);\n return m_font->glyphDataForCharacter(charData.character, m_run.rtl(), normalizeSpace);\n}\n\nfloat SimpleShaper::characterWidth(UChar32 character, const GlyphData& glyphData) const\n{\n const SimpleFontData* fontData = glyphData.fontData;\n ASSERT(fontData);\n\n if (UNLIKELY(character == '\\t' && m_run.allowTabs()))\n return m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar);\n\n float width = fontData->widthForGlyph(glyphData.glyph);\n\n \/\/ SVG uses horizontalGlyphStretch(), when textLength is used to stretch\/squeeze text.\n if (UNLIKELY(m_run.horizontalGlyphStretch() != 1))\n width *= m_run.horizontalGlyphStretch();\n\n return width;\n}\n\nvoid SimpleShaper::cacheFallbackFont(const SimpleFontData* fontData,\n const SimpleFontData* primaryFont)\n{\n if (fontData == primaryFont)\n return;\n\n m_fallbackFonts->add(fontData);\n}\n\nfloat SimpleShaper::adjustSpacing(float width, const CharacterData& charData)\n{\n \/\/ Account for letter-spacing.\n if (width)\n width += m_font->fontDescription().letterSpacing();\n\n bool isExpansionOpportunity = Character::treatAsSpace(charData.character) || (m_run.textJustify() == TextJustifyDistribute);\n if (isExpansionOpportunity || (m_run.textJustify() == TextJustifyAuto && Character::isCJKIdeographOrSymbol(charData.character))) {\n \/\/ Distribute the run's total expansion evenly over all expansion opportunities in the run.\n if (m_expansion) {\n if (!isExpansionOpportunity && !m_isAfterExpansion) {\n \/\/ Take the expansion opportunity before this ideograph.\n m_expansion -= m_expansionPerOpportunity;\n m_runWidthSoFar += m_expansionPerOpportunity;\n }\n if (m_run.allowsTrailingExpansion()\n || (m_run.ltr() && charData.characterOffset + charData.clusterLength < static_cast<size_t>(m_run.length()))\n || (m_run.rtl() && charData.characterOffset)) {\n m_expansion -= m_expansionPerOpportunity;\n width += m_expansionPerOpportunity;\n m_isAfterExpansion = true;\n }\n } else {\n m_isAfterExpansion = false;\n }\n\n \/\/ Account for word spacing.\n \/\/ We apply additional space between \"words\" by adding width to the space character.\n if (isExpansionOpportunity && (charData.character != '\\t' || !m_run.allowTabs())\n && (charData.characterOffset || charData.character == noBreakSpace)\n && m_font->fontDescription().wordSpacing()) {\n width += m_font->fontDescription().wordSpacing();\n }\n } else {\n m_isAfterExpansion = false;\n }\n\n return width;\n}\n\nvoid SimpleShaper::updateGlyphBounds(const GlyphData& glyphData, float width, bool firstCharacter)\n{\n ASSERT(glyphData.fontData);\n FloatRect bounds = glyphData.fontData->boundsForGlyph(glyphData.glyph);\n\n ASSERT(m_bounds);\n if (firstCharacter)\n m_bounds->firstGlyphOverflow = std::max<float>(0, -bounds.x());\n m_bounds->lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);\n m_bounds->maxGlyphBoundingBoxY = std::max(m_bounds->maxGlyphBoundingBoxY, bounds.maxY());\n m_bounds->minGlyphBoundingBoxY = std::min(m_bounds->minGlyphBoundingBoxY, bounds.y());\n}\n\ntemplate <typename TextIterator>\nunsigned SimpleShaper::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)\n{\n bool hasExtraSpacing = (m_font->fontDescription().letterSpacing() || m_font->fontDescription().wordSpacing() || m_expansion)\n && !m_run.spacingDisabled();\n\n const SimpleFontData* primaryFont = m_font->primaryFont();\n const SimpleFontData* lastFontData = primaryFont;\n bool normalizeSpace = m_run.normalizeSpace();\n\n CharacterData charData;\n while (textIterator.consume(charData.character, charData.clusterLength)) {\n charData.characterOffset = textIterator.currentCharacter();\n\n GlyphData glyphData = glyphDataForCharacter(charData, normalizeSpace);\n\n \/\/ Some fonts do not have a glyph for zero-width-space,\n \/\/ in that case use the space character and override the width.\n float width;\n bool spaceUsedAsZeroWidthSpace = false;\n if (!glyphData.glyph && Character::treatAsZeroWidthSpaceInComplexScript(charData.character)) {\n charData.character = space;\n glyphData = glyphDataForCharacter(charData);\n width = 0;\n spaceUsedAsZeroWidthSpace = true;\n } else {\n width = characterWidth(charData.character, glyphData);\n }\n\n Glyph glyph = glyphData.glyph;\n const SimpleFontData* fontData = glyphData.fontData;\n ASSERT(fontData);\n\n if (m_fallbackFonts && lastFontData != fontData && width) {\n lastFontData = fontData;\n cacheFallbackFont(fontData, primaryFont);\n }\n\n if (hasExtraSpacing && !spaceUsedAsZeroWidthSpace)\n width = adjustSpacing(width, charData);\n\n if (m_bounds)\n updateGlyphBounds(glyphData, width, !charData.characterOffset);\n\n if (m_forTextEmphasis) {\n if (!Character::canReceiveTextEmphasis(charData.character))\n glyph = 0;\n\n \/\/ The emphasis code expects mid-glyph offsets.\n width \/= 2;\n m_runWidthSoFar += width;\n }\n\n if (glyphBuffer)\n glyphBuffer->add(glyph, fontData, m_runWidthSoFar);\n\n \/\/ Advance past the character we just dealt with.\n textIterator.advance(charData.clusterLength);\n m_runWidthSoFar += width;\n }\n\n unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;\n m_currentCharacter = textIterator.currentCharacter();\n\n return consumedCharacters;\n}\n\nunsigned SimpleShaper::advance(unsigned offset, GlyphBuffer* glyphBuffer)\n{\n unsigned length = m_run.length();\n\n if (offset > length)\n offset = length;\n\n if (m_currentCharacter >= offset)\n return 0;\n\n if (m_run.is8Bit()) {\n Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);\n return advanceInternal(textIterator, glyphBuffer);\n }\n\n SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);\n return advanceInternal(textIterator, glyphBuffer);\n}\n\nbool SimpleShaper::advanceOneCharacter(float& width)\n{\n float initialWidth = m_runWidthSoFar;\n\n if (!advance(m_currentCharacter + 1))\n return false;\n\n width = m_runWidthSoFar - initialWidth;\n return true;\n}\n\n} \/\/ namespace blink\n<commit_msg>At some places Blink is using old style character string notation for Unicode. Replacing those with defined Character Names\/Unicodes. Also using local variable for multiple similar calls.<commit_after>\/*\n * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Holger Hans Peter Freyther\n * Copyright (C) 2014 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"config.h\"\n#include \"platform\/fonts\/shaping\/SimpleShaper.h\"\n\n#include \"platform\/fonts\/Character.h\"\n#include \"platform\/fonts\/Font.h\"\n#include \"platform\/fonts\/GlyphBuffer.h\"\n#include \"platform\/fonts\/Latin1TextIterator.h\"\n#include \"platform\/fonts\/SimpleFontData.h\"\n#include \"platform\/text\/SurrogatePairAwareTextIterator.h\"\n#include \"wtf\/MathExtras.h\"\n#include \"wtf\/unicode\/CharacterNames.h\"\n\nusing namespace WTF;\nusing namespace Unicode;\n\nnamespace blink {\n\nSimpleShaper::SimpleShaper(const Font* font, const TextRun& run,\n HashSet<const SimpleFontData*>* fallbackFonts, GlyphBounds* bounds,\n bool forTextEmphasis)\n : m_font(font)\n , m_run(run)\n , m_currentCharacter(0)\n , m_runWidthSoFar(0)\n , m_isAfterExpansion(!run.allowsLeadingExpansion())\n , m_fallbackFonts(fallbackFonts)\n , m_bounds(bounds)\n , m_forTextEmphasis(forTextEmphasis)\n{\n \/\/ If the padding is non-zero, count the number of spaces in the run\n \/\/ and divide that by the padding for per space addition.\n m_expansion = m_run.expansion();\n if (!m_expansion) {\n m_expansionPerOpportunity = 0;\n } else {\n bool isAfterExpansion = m_isAfterExpansion;\n unsigned expansionOpportunityCount = m_run.is8Bit() ? Character::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify()) : Character::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify());\n if (isAfterExpansion && !m_run.allowsTrailingExpansion())\n expansionOpportunityCount--;\n\n if (!expansionOpportunityCount)\n m_expansionPerOpportunity = 0;\n else\n m_expansionPerOpportunity = m_expansion \/ expansionOpportunityCount;\n }\n}\n\nGlyphData SimpleShaper::glyphDataForCharacter(CharacterData& charData, bool normalizeSpace)\n{\n ASSERT(m_font);\n return m_font->glyphDataForCharacter(charData.character, m_run.rtl(), normalizeSpace);\n}\n\nfloat SimpleShaper::characterWidth(UChar32 character, const GlyphData& glyphData) const\n{\n const SimpleFontData* fontData = glyphData.fontData;\n ASSERT(fontData);\n\n if (UNLIKELY(character == characterTabulation && m_run.allowTabs()))\n return m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar);\n\n float width = fontData->widthForGlyph(glyphData.glyph);\n\n \/\/ SVG uses horizontalGlyphStretch(), when textLength is used to stretch\/squeeze text.\n if (UNLIKELY(m_run.horizontalGlyphStretch() != 1))\n width *= m_run.horizontalGlyphStretch();\n\n return width;\n}\n\nvoid SimpleShaper::cacheFallbackFont(const SimpleFontData* fontData,\n const SimpleFontData* primaryFont)\n{\n if (fontData == primaryFont)\n return;\n\n m_fallbackFonts->add(fontData);\n}\n\nfloat SimpleShaper::adjustSpacing(float width, const CharacterData& charData)\n{\n \/\/ Account for letter-spacing.\n if (width)\n width += m_font->fontDescription().letterSpacing();\n\n bool isExpansionOpportunity = Character::treatAsSpace(charData.character) || (m_run.textJustify() == TextJustifyDistribute);\n if (isExpansionOpportunity || (m_run.textJustify() == TextJustifyAuto && Character::isCJKIdeographOrSymbol(charData.character))) {\n \/\/ Distribute the run's total expansion evenly over all expansion opportunities in the run.\n if (m_expansion) {\n if (!isExpansionOpportunity && !m_isAfterExpansion) {\n \/\/ Take the expansion opportunity before this ideograph.\n m_expansion -= m_expansionPerOpportunity;\n m_runWidthSoFar += m_expansionPerOpportunity;\n }\n if (m_run.allowsTrailingExpansion()\n || (m_run.ltr() && charData.characterOffset + charData.clusterLength < static_cast<size_t>(m_run.length()))\n || (m_run.rtl() && charData.characterOffset)) {\n m_expansion -= m_expansionPerOpportunity;\n width += m_expansionPerOpportunity;\n m_isAfterExpansion = true;\n }\n } else {\n m_isAfterExpansion = false;\n }\n\n \/\/ Account for word spacing.\n \/\/ We apply additional space between \"words\" by adding width to the space character.\n if (isExpansionOpportunity && (charData.character != characterTabulation || !m_run.allowTabs())\n && (charData.characterOffset || charData.character == noBreakSpace)\n && m_font->fontDescription().wordSpacing()) {\n width += m_font->fontDescription().wordSpacing();\n }\n } else {\n m_isAfterExpansion = false;\n }\n\n return width;\n}\n\nvoid SimpleShaper::updateGlyphBounds(const GlyphData& glyphData, float width, bool firstCharacter)\n{\n ASSERT(glyphData.fontData);\n FloatRect bounds = glyphData.fontData->boundsForGlyph(glyphData.glyph);\n\n ASSERT(m_bounds);\n if (firstCharacter)\n m_bounds->firstGlyphOverflow = std::max<float>(0, -bounds.x());\n m_bounds->lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);\n m_bounds->maxGlyphBoundingBoxY = std::max(m_bounds->maxGlyphBoundingBoxY, bounds.maxY());\n m_bounds->minGlyphBoundingBoxY = std::min(m_bounds->minGlyphBoundingBoxY, bounds.y());\n}\n\ntemplate <typename TextIterator>\nunsigned SimpleShaper::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)\n{\n bool hasExtraSpacing = (m_font->fontDescription().letterSpacing() || m_font->fontDescription().wordSpacing() || m_expansion)\n && !m_run.spacingDisabled();\n\n const SimpleFontData* primaryFont = m_font->primaryFont();\n const SimpleFontData* lastFontData = primaryFont;\n bool normalizeSpace = m_run.normalizeSpace();\n\n CharacterData charData;\n while (textIterator.consume(charData.character, charData.clusterLength)) {\n charData.characterOffset = textIterator.currentCharacter();\n\n GlyphData glyphData = glyphDataForCharacter(charData, normalizeSpace);\n\n \/\/ Some fonts do not have a glyph for zero-width-space,\n \/\/ in that case use the space character and override the width.\n float width;\n bool spaceUsedAsZeroWidthSpace = false;\n if (!glyphData.glyph && Character::treatAsZeroWidthSpaceInComplexScript(charData.character)) {\n charData.character = space;\n glyphData = glyphDataForCharacter(charData);\n width = 0;\n spaceUsedAsZeroWidthSpace = true;\n } else {\n width = characterWidth(charData.character, glyphData);\n }\n\n Glyph glyph = glyphData.glyph;\n const SimpleFontData* fontData = glyphData.fontData;\n ASSERT(fontData);\n\n if (m_fallbackFonts && lastFontData != fontData && width) {\n lastFontData = fontData;\n cacheFallbackFont(fontData, primaryFont);\n }\n\n if (hasExtraSpacing && !spaceUsedAsZeroWidthSpace)\n width = adjustSpacing(width, charData);\n\n if (m_bounds)\n updateGlyphBounds(glyphData, width, !charData.characterOffset);\n\n if (m_forTextEmphasis) {\n if (!Character::canReceiveTextEmphasis(charData.character))\n glyph = 0;\n\n \/\/ The emphasis code expects mid-glyph offsets.\n width \/= 2;\n m_runWidthSoFar += width;\n }\n\n if (glyphBuffer)\n glyphBuffer->add(glyph, fontData, m_runWidthSoFar);\n\n \/\/ Advance past the character we just dealt with.\n textIterator.advance(charData.clusterLength);\n m_runWidthSoFar += width;\n }\n\n unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;\n m_currentCharacter = textIterator.currentCharacter();\n\n return consumedCharacters;\n}\n\nunsigned SimpleShaper::advance(unsigned offset, GlyphBuffer* glyphBuffer)\n{\n unsigned length = m_run.length();\n\n if (offset > length)\n offset = length;\n\n if (m_currentCharacter >= offset)\n return 0;\n\n if (m_run.is8Bit()) {\n Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);\n return advanceInternal(textIterator, glyphBuffer);\n }\n\n SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);\n return advanceInternal(textIterator, glyphBuffer);\n}\n\nbool SimpleShaper::advanceOneCharacter(float& width)\n{\n float initialWidth = m_runWidthSoFar;\n\n if (!advance(m_currentCharacter + 1))\n return false;\n\n width = m_runWidthSoFar - initialWidth;\n return true;\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>\/*\n * server_test.cpp\n *\n * Created on: Jan 16, 2013\n * Author: mfleder\n *\/\n\n#include <stdio.h>\n#include <lcm\/lcm-cpp.hpp>\n#include <boost\/shared_ptr.hpp>\n#include \"affordance\/AffordanceServer.h\"\n#include \"affordance\/AffordanceUpWrapper.h\"\n#include \"affordance\/AffordanceState.h\"\n#include <path_util\/path_util.h>\n#include <iostream>\n\nusing namespace boost;\nusing namespace std;\nusing namespace affordance;\n\n\/**populates the server w\/ a bunch of affordances*\/\nvoid runPopulate(const shared_ptr<lcm::LCM> lcm)\n{\n AffordanceUpWrapper wrapper(lcm);\n\n const int mapId = 0;\n int uniqueObjId = 0;\n\n \/\/sphere\n AffordanceState sphere(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),\n Eigen::Vector3f(1.0, 0.0, 1.0)); \/\/color\n sphere._params[AffordanceState::RADIUS_NAME] = 0.125;\n sphere.setType(AffordanceState::SPHERE);\n wrapper.addNewlyFittedAffordance(sphere);\n\n \/\/box\n float box_height = 0.01;\n AffordanceState box(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(0.0, 0.0, -box_height \/ 2.0)),\n Eigen::Vector3f(0.75, 0.75, 0.0)); \/\/color\n box._params[AffordanceState::LENGTH_NAME] = 100;\n box._params[AffordanceState::WIDTH_NAME] = 100;\n box._params[AffordanceState::HEIGHT_NAME] = box_height;\n box.setType(AffordanceState::BOX);\n wrapper.addNewlyFittedAffordance(box);\n\n \/\/cylinder\n AffordanceState cylinder(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),\n Eigen::Vector3f(0.0, 1.0, 1.0)); \/\/color\n cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;\n cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;\n cylinder.setType(AffordanceState::CYLINDER);\n wrapper.addNewlyFittedAffordance(cylinder);\n\n \/\/==car\n string carUrdfFName = getModelsPath() + string(\"\/mit_gazebo_objects\/mit_simple_vehicle\/model.urdf\");\n cout << \"using card urdf = \" << carUrdfFName << endl;\n\n vector<AffPtr> carAffs;\n AffordanceState::getBoxesCylindersSpheres(carUrdfFName, carAffs);\n for(uint i = 0; i < carAffs.size(); i++)\n wrapper.addNewlyFittedAffordance(*carAffs[i]);\n\n cout << \"\\n added \" << carAffs.size() << \" car affordances\" << endl;\n\n \/\/wait a few second so we get an update from the server\n boost::this_thread::sleep(boost::posix_time::seconds(3));\n\n \/\/===now loop and printout periodically\n boost::posix_time::seconds sleepTime(60); \/\/update (printout) every 60 seconds\n\n while (true)\n {\n \/\/cout << \"\\n\\n===\" << j << endl;\n cout << wrapper << endl;\n boost::this_thread::sleep(sleepTime); \/\/======sleep\n\n \/\/======modify server\n \/\/ user code\n \/\/===finished modifications \n }\n}\n\nint main(int argc, char **argv)\n{\n shared_ptr<lcm::LCM> theLcm(new lcm::LCM());\n\n if (!theLcm->good())\n {\n cerr << \"Cannot create lcm object\" << endl;\n return -1;\n }\n\n \/\/create the server\n AffordanceServer s(theLcm);\n\n \/\/thread will add to the affordance server\n \/\/and possibly make changes over time\n boost::thread populateThread = boost::thread(runPopulate, theLcm);\n\n \/\/lcm loop\n cout << \"\\nstarting lcm loop\" << endl;\n\n while (0 == theLcm->handle())\n {\n ;\n }\n\n return 0;\n}\n<commit_msg>Switches demo_populate_affordance_server to use mit_vehicle rather than mit_simple_vehicle.<commit_after>\/*\n * server_test.cpp\n *\n * Created on: Jan 16, 2013\n * Author: mfleder\n *\/\n\n#include <stdio.h>\n#include <lcm\/lcm-cpp.hpp>\n#include <boost\/shared_ptr.hpp>\n#include \"affordance\/AffordanceServer.h\"\n#include \"affordance\/AffordanceUpWrapper.h\"\n#include \"affordance\/AffordanceState.h\"\n#include <path_util\/path_util.h>\n#include <iostream>\n\nusing namespace boost;\nusing namespace std;\nusing namespace affordance;\n\n\/**populates the server w\/ a bunch of affordances*\/\nvoid runPopulate(const shared_ptr<lcm::LCM> lcm)\n{\n AffordanceUpWrapper wrapper(lcm);\n\n const int mapId = 0;\n int uniqueObjId = 0;\n\n \/\/sphere\n AffordanceState sphere(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),\n Eigen::Vector3f(1.0, 0.0, 1.0)); \/\/color\n sphere._params[AffordanceState::RADIUS_NAME] = 0.125;\n sphere.setType(AffordanceState::SPHERE);\n wrapper.addNewlyFittedAffordance(sphere);\n\n \/\/box\n float box_height = 0.01;\n AffordanceState box(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(0.0, 0.0, -box_height \/ 2.0)),\n Eigen::Vector3f(0.75, 0.75, 0.0)); \/\/color\n box._params[AffordanceState::LENGTH_NAME] = 100;\n box._params[AffordanceState::WIDTH_NAME] = 100;\n box._params[AffordanceState::HEIGHT_NAME] = box_height;\n box.setType(AffordanceState::BOX);\n wrapper.addNewlyFittedAffordance(box);\n\n \/\/cylinder\n AffordanceState cylinder(uniqueObjId++, mapId,\n KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),\n Eigen::Vector3f(0.0, 1.0, 1.0)); \/\/color\n cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;\n cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;\n cylinder.setType(AffordanceState::CYLINDER);\n wrapper.addNewlyFittedAffordance(cylinder);\n\n \/\/==car\n string carUrdfFName = getModelsPath() + string(\"\/mit_gazebo_objects\/mit_vehicle\/model_drake.urdf\");\n cout << \"using card urdf = \" << carUrdfFName << endl;\n\n vector<AffPtr> carAffs;\n AffordanceState::getBoxesCylindersSpheres(carUrdfFName, carAffs);\n for(uint i = 0; i < carAffs.size(); i++)\n wrapper.addNewlyFittedAffordance(*carAffs[i]);\n\n cout << \"\\n added \" << carAffs.size() << \" car affordances\" << endl;\n\n \/\/wait a few second so we get an update from the server\n boost::this_thread::sleep(boost::posix_time::seconds(3));\n\n \/\/===now loop and printout periodically\n boost::posix_time::seconds sleepTime(60); \/\/update (printout) every 60 seconds\n\n while (true)\n {\n \/\/cout << \"\\n\\n===\" << j << endl;\n cout << wrapper << endl;\n boost::this_thread::sleep(sleepTime); \/\/======sleep\n\n \/\/======modify server\n \/\/ user code\n \/\/===finished modifications \n }\n}\n\nint main(int argc, char **argv)\n{\n shared_ptr<lcm::LCM> theLcm(new lcm::LCM());\n\n if (!theLcm->good())\n {\n cerr << \"Cannot create lcm object\" << endl;\n return -1;\n }\n\n \/\/create the server\n AffordanceServer s(theLcm);\n\n \/\/thread will add to the affordance server\n \/\/and possibly make changes over time\n boost::thread populateThread = boost::thread(runPopulate, theLcm);\n\n \/\/lcm loop\n cout << \"\\nstarting lcm loop\" << endl;\n\n while (0 == theLcm->handle())\n {\n ;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"statusbar.h\"\n\n#include <QPainter>\n#include <QX11Info>\n#include <QTouchEvent>\n#include <QDBusInterface>\n#include <QDBusConnection>\n#include <QGraphicsScene>\n#include <QGraphicsView>\n#include <QTimer>\n\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n#include <X11\/Xatom.h>\n#include <X11\/extensions\/Xcomposite.h>\n#include <X11\/extensions\/Xdamage.h>\n\n\/\/ Fetches the shared status bar pixmap\nstatic QPixmap fetchSharedPixmap()\n{\n static Atom propertyWindowAtom = 0;\n static Atom pixmapHandleAtom = 0;\n\n \/\/ This contains the statusbar window\n if (propertyWindowAtom == 0)\n propertyWindowAtom = XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_STATUSBAR_PROPERTY_WINDOW\", False);\n\n \/\/ This contains the shared pixmap\n if (pixmapHandleAtom == 0)\n pixmapHandleAtom = XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_STATUSBAR_PIXMAP\", False);\n\n \/\/ Some common variables\n Atom actualType = 0;\n int actualFormat = 0;\n unsigned long nitems = 0;\n unsigned long bytesAfter = 0;\n unsigned char *data = 0;\n int status = 0;\n\n \/\/ Getting the status bar window\n status = XGetWindowProperty(QX11Info::display(),\n QX11Info::appRootWindow(),\n propertyWindowAtom,\n 0,\n 1,\n False,\n XA_WINDOW,\n &actualType,\n &actualFormat,\n &nitems,\n &bytesAfter,\n &data);\n\n Window window(0);\n if (status == Success && data != None)\n {\n window = *(Window *)data;\n XFree(data);\n }\n\n \/\/ Getting the shared pixmap from the status bar window\n status = XGetWindowProperty(QX11Info::display(),\n window,\n pixmapHandleAtom,\n 0,\n 1,\n False,\n XA_PIXMAP,\n &actualType,\n &actualFormat,\n &nitems,\n &bytesAfter,\n &data);\n\n QPixmap result;\n\n if (status == Success)\n {\n quint32 handle = *((unsigned long*)data);\n\n if (actualType == XA_PIXMAP && actualFormat == 32 && handle != 0)\n {\n result = QPixmap::fromX11Pixmap(handle, QPixmap::ExplicitlyShared);\n \/\/ TODO: we should register for damage events for this pixmap and repaint when they arrive\n \/\/ (perhaps create an XEventListener fromt his class too?)\n }\n\n XFree(data);\n }\n\n return result;\n}\n\nStatusBar::StatusBar(QDeclarativeItem *parent) :\n QDeclarativeItem(parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n setAcceptTouchEvents(true);\n setImplicitHeight(36);\n QTimer::singleShot(3000, this, SLOT(initializeStatusBar()));\n}\n\nvoid StatusBar::initializeStatusBar()\n{\n _sharedPixmap = fetchSharedPixmap();\n setImplicitHeight(_sharedPixmap.height() \/ 2);\n updateXThings();\n}\n\nvoid StatusBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n Q_UNUSED(option)\n Q_UNUSED(widget)\n\n if (_sharedPixmap.isNull())\n {\n qDebug() << \"StatusBar: the shared pixmap is null, can't draw it!\";\n return;\n }\n\n \/\/ Info: The shared pixmap contains both the portrait and the landscape mode status bars below each other.\n \/\/ Landscape is on top, portrait on bottom. They have the same height.\n \/\/ All we need is check the orientation here and set the source rect accordingly.\n\n painter->drawPixmap(QRectF(0, 0, width(), height()), _sharedPixmap, QRectF(0, _isPortrait ? height() : 0, width(), height()));\n}\n\nbool StatusBar::isPortrait() const\n{\n return _isPortrait;\n}\n\nvoid StatusBar::updateXThings()\n{\n \/\/ If the pixmap is null, don't bother\n if (_sharedPixmap.isNull())\n return;\n\n \/\/ Statusbar rect\n QPointF p = mapToScene(0, 0);\n unsigned long data[4] = { (int)p.x(), (int)p.y(), width(), height() };\n qDebug() << \"statusbar geo:\" << (int)p.x() << (int)p.y() << width() << height();\n\n \/\/ Orientation angle\n int angle = isPortrait() ? 270 : 0;\n qDebug() << \"orientation angle:\" << angle;\n\n \/\/ Stuff for X\n QWidget *activeWindow = this->scene()->views().at(0);\n Display *dpy = QX11Info::display();\n\n \/\/ Setting the status bar geometry atom (probably not necessary here)\n Atom statusBarGeometryAtom = XInternAtom(dpy, \"_MEEGOTOUCH_MSTATUSBAR_GEOMETRY\", False);\n XChangeProperty(dpy, activeWindow->effectiveWinId(), statusBarGeometryAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)data, 4);\n\n \/\/ Setting the orientation angle atom (sysuid uses this to determine what orientation it should draw itself)\n Atom orientationAngleAtom = XInternAtom(dpy, \"_MEEGOTOUCH_ORIENTATION_ANGLE\", False);\n XChangeProperty(dpy, activeWindow->effectiveWinId(), orientationAngleAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&angle, 1);\n}\n\nvoid StatusBar::setIsPortrait(bool value)\n{\n \/\/ If there is no change, don't bother\n if (_isPortrait == value)\n return;\n\n _isPortrait = value;\n updateXThings();\n\n emit isPortraitChanged();\n}\n\nbool StatusBar::sceneEvent(QEvent *event)\n{\n if (event->type() == QEvent::TouchBegin)\n {\n return true;\n }\n if (event->type() == QEvent::TouchEnd)\n {\n qDebug() << \"opening status menu\";\n\n QDBusInterface interface(\"com.meego.core.MStatusIndicatorMenu\",\n \"\/statusindicatormenu\",\n \"com.meego.core.MStatusIndicatorMenu\",\n QDBusConnection::sessionBus());\n\n interface.call(QDBus::NoBlock, \"open\");\n\n return true;\n }\n\n return false;\n}\n<commit_msg>Status bar: calling update() after getting the shared pixmap<commit_after>\n#include \"statusbar.h\"\n\n#include <QPainter>\n#include <QX11Info>\n#include <QTouchEvent>\n#include <QDBusInterface>\n#include <QDBusConnection>\n#include <QGraphicsScene>\n#include <QGraphicsView>\n#include <QTimer>\n\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n#include <X11\/Xatom.h>\n#include <X11\/extensions\/Xcomposite.h>\n#include <X11\/extensions\/Xdamage.h>\n\n\/\/ Fetches the shared status bar pixmap\nstatic QPixmap fetchSharedPixmap()\n{\n static Atom propertyWindowAtom = 0;\n static Atom pixmapHandleAtom = 0;\n\n \/\/ This contains the statusbar window\n if (propertyWindowAtom == 0)\n propertyWindowAtom = XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_STATUSBAR_PROPERTY_WINDOW\", False);\n\n \/\/ This contains the shared pixmap\n if (pixmapHandleAtom == 0)\n pixmapHandleAtom = XInternAtom(QX11Info::display(), \"_MEEGOTOUCH_STATUSBAR_PIXMAP\", False);\n\n \/\/ Some common variables\n Atom actualType = 0;\n int actualFormat = 0;\n unsigned long nitems = 0;\n unsigned long bytesAfter = 0;\n unsigned char *data = 0;\n int status = 0;\n\n \/\/ Getting the status bar window\n status = XGetWindowProperty(QX11Info::display(),\n QX11Info::appRootWindow(),\n propertyWindowAtom,\n 0,\n 1,\n False,\n XA_WINDOW,\n &actualType,\n &actualFormat,\n &nitems,\n &bytesAfter,\n &data);\n\n Window window(0);\n if (status == Success && data != None)\n {\n window = *(Window *)data;\n XFree(data);\n }\n\n \/\/ Getting the shared pixmap from the status bar window\n status = XGetWindowProperty(QX11Info::display(),\n window,\n pixmapHandleAtom,\n 0,\n 1,\n False,\n XA_PIXMAP,\n &actualType,\n &actualFormat,\n &nitems,\n &bytesAfter,\n &data);\n\n QPixmap result;\n\n if (status == Success)\n {\n quint32 handle = *((unsigned long*)data);\n\n if (actualType == XA_PIXMAP && actualFormat == 32 && handle != 0)\n {\n result = QPixmap::fromX11Pixmap(handle, QPixmap::ExplicitlyShared);\n \/\/ TODO: we should register for damage events for this pixmap and repaint when they arrive\n \/\/ (perhaps create an XEventListener fromt his class too?)\n }\n\n XFree(data);\n }\n\n return result;\n}\n\nStatusBar::StatusBar(QDeclarativeItem *parent) :\n QDeclarativeItem(parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n setAcceptTouchEvents(true);\n setImplicitHeight(36);\n QTimer::singleShot(3000, this, SLOT(initializeStatusBar()));\n}\n\nvoid StatusBar::initializeStatusBar()\n{\n _sharedPixmap = fetchSharedPixmap();\n setImplicitHeight(_sharedPixmap.height() \/ 2);\n updateXThings();\n}\n\nvoid StatusBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n Q_UNUSED(option)\n Q_UNUSED(widget)\n\n if (_sharedPixmap.isNull())\n {\n qDebug() << \"StatusBar: the shared pixmap is null, can't draw it!\";\n painter->setPen(QColor(Qt::black));\n painter->drawRect(0, 0, width(), height());\n return;\n }\n\n \/\/ Info: The shared pixmap contains both the portrait and the landscape mode status bars below each other.\n \/\/ Landscape is on top, portrait on bottom. They have the same height.\n \/\/ All we need is check the orientation here and set the source rect accordingly.\n\n painter->drawPixmap(QRectF(0, 0, width(), height()), _sharedPixmap, QRectF(0, _isPortrait ? height() : 0, width(), height()));\n}\n\nbool StatusBar::isPortrait() const\n{\n return _isPortrait;\n}\n\nvoid StatusBar::updateXThings()\n{\n \/\/ If the pixmap is null, don't bother\n if (_sharedPixmap.isNull())\n return;\n\n \/\/ Statusbar rect\n QPointF p = mapToScene(0, 0);\n unsigned long data[4] = { (int)p.x(), (int)p.y(), width(), height() };\n qDebug() << \"statusbar geo:\" << (int)p.x() << (int)p.y() << width() << height();\n\n \/\/ Orientation angle\n int angle = isPortrait() ? 270 : 0;\n qDebug() << \"orientation angle:\" << angle;\n\n \/\/ Stuff for X\n QWidget *activeWindow = this->scene()->views().at(0);\n Display *dpy = QX11Info::display();\n\n \/\/ Setting the status bar geometry atom (probably not necessary here)\n Atom statusBarGeometryAtom = XInternAtom(dpy, \"_MEEGOTOUCH_MSTATUSBAR_GEOMETRY\", False);\n XChangeProperty(dpy, activeWindow->effectiveWinId(), statusBarGeometryAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)data, 4);\n\n \/\/ Setting the orientation angle atom (sysuid uses this to determine what orientation it should draw itself)\n Atom orientationAngleAtom = XInternAtom(dpy, \"_MEEGOTOUCH_ORIENTATION_ANGLE\", False);\n XChangeProperty(dpy, activeWindow->effectiveWinId(), orientationAngleAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&angle, 1);\n\n update();\n}\n\nvoid StatusBar::setIsPortrait(bool value)\n{\n \/\/ If there is no change, don't bother\n if (_isPortrait == value)\n return;\n\n _isPortrait = value;\n updateXThings();\n\n emit isPortraitChanged();\n}\n\nbool StatusBar::sceneEvent(QEvent *event)\n{\n if (event->type() == QEvent::TouchBegin)\n {\n return true;\n }\n if (event->type() == QEvent::TouchEnd)\n {\n qDebug() << \"opening status menu\";\n\n QDBusInterface interface(\"com.meego.core.MStatusIndicatorMenu\",\n \"\/statusindicatormenu\",\n \"com.meego.core.MStatusIndicatorMenu\",\n QDBusConnection::sessionBus());\n\n interface.call(QDBus::NoBlock, \"open\");\n\n return true;\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file Action.hpp\n*\/\n\n#ifndef __ACTION_HPP__\n#define __ACTION_HPP__\n\n#include \"ESRoot\/Types.hpp\"\n#include \"PortUtils.hpp\"\n\nnamespace ES\n{\nclass ModelObject;\n}\nnamespace Action \n{\n\t\n\nvoid send(ES::ModelObject* target, ES::EventRef signal);\n\/**<\nSends a message to a model object.\n@param target The target object where the signal has to be sent. \n@param signal The signal to be sent.\n*\/\n\t\ntemplate <typename T, typename S>\nvoid send(T target, S signal);\n\/**<\nSends a message to a port.\n@param port The port object where the signal has to be sent. \n@param signal The signal to be sent.\n*\/\n\nvoid start(ES::ModelObject* sm);\n\/**<\nStarts the state machine of a model object.\n@param sm The state machine to be started. \n*\/\n\nvoid deleteObject(ES::ModelObject* modelObject);\n\/**<\nDispose a model object reference.\n@param modelObject The object to be deleted.\n*\/\n\t\nvoid log(ES::String message);\n\/**<\nLogs a message.\n@param message The message to be logged. \n*\/\n\t\ntemplate<typename LeftEnd, typename RightEnd>\nvoid link(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2);\n\/**<\nLinks two model objects through the specified association.\nIt has no effect if the objects are already linked through the specified association.\n@param LeftEnd The type representing the left end of the association.\n@param RightEnd The type representing the rigth end of the association.\n@param e1 The object at the left end of the association.\n@param e2 The object at the right end of the association.\n*\/\n\n\t\ntemplate<typename LeftEnd, typename RightEnd>\nvoid unlink(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2);\n\/**<\nUnlinks two model objects through the specified association.\nIt has no effect if the objects are not linked through the specified association.\n@param LeftEnd The type representing the left end of the association.\n@param RightEnd The type representing the rigth end of the association.\n@param e1 The object at the left end of the association.\n@param e2 The object at the right end of the association.\n*\/\n\n\n\ntemplate<typename LeftEnd, typename RightEnd>\nvoid link(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2)\n{\n\te1->template link<RightEnd>(e2);\n\te2->template link<LeftEnd>(e1);\n}\n\ntemplate<typename LeftEnd, typename RightEnd>\nvoid unlink(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2)\n{\n\te1->template unlink<RightEnd>(e2);\n\te2->template unlink<LeftEnd>(e1);\n}\n\t\ntemplate <typename T, typename S>\nvoid send(T target, S signal)\n{\n\ttarget->send(signal);\n}\n\n}\n\n#endif\n<commit_msg>Modifies link\/unlink functions<commit_after>\/** @file Action.hpp\n*\/\n\n#ifndef __ACTION_HPP__\n#define __ACTION_HPP__\n\n#include \"ESRoot\/Types.hpp\"\n#include \"PortUtils.hpp\"\n\nnamespace ES\n{\nclass ModelObject;\n}\nnamespace Action \n{\n\t\n\nvoid send(ES::ModelObject* target, ES::EventRef signal);\n\/**<\nSends a message to a model object.\n@param target The target object where the signal has to be sent. \n@param signal The signal to be sent.\n*\/\n\t\ntemplate <typename T, typename S>\nvoid send(T target, S signal);\n\/**<\nSends a message to a port.\n@param port The port object where the signal has to be sent. \n@param signal The signal to be sent.\n*\/\n\nvoid start(ES::ModelObject* sm);\n\/**<\nStarts the state machine of a model object.\n@param sm The state machine to be started. \n*\/\n\nvoid deleteObject(ES::ModelObject* modelObject);\n\/**<\nDispose a model object reference.\n@param modelObject The object to be deleted.\n*\/\n\t\nvoid log(ES::String message);\n\/**<\nLogs a message.\n@param message The message to be logged. \n*\/\n\t\ntemplate<typename L, typename LE, typename R, typename RE>\nvoid link (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);\n\/**<\nLinks two model objects through the specified association.\nIt has no effect if the objects are already linked through the specified association.\n@param leftEnd The type representing the left end of the association.\n@param rightEnd The type representing the right end of the association.\n@param leftObject The object at the left end of the association.\n@param rightObject The object at the right end of the association.\n*\/\n\n\t\ntemplate<typename LeftEnd, typename RightEnd>\nvoid unlink (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);\n\/**<\nUnlinks two model objects through the specified association.\nIt has no effect if the objects are not linked through the specified association.\n@param leftEnd The type representing the left end of the association.\n@param rightEnd The type representing the right end of the association.\n@param leftObject The object at the left end of the association.\n@param rightObject The object at the right end of the association.\n*\/\n\n\n\ntemplate<typename L, typename LE, typename R, typename RE>\nvoid link (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd)\n{\n\tleftEnd->association->link (leftObject, leftEnd, rightObject, rightEnd);\n}\n\ntemplate<typename L, typename LE, typename R, typename RE>\nvoid unlink (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);\n{\n\tleftEnd->association->unlink (leftObject, leftEnd, rightObject, rightEnd);\n\n}\n\t\ntemplate <typename T, typename S>\nvoid send(T target, S signal)\n{\n\ttarget->send(signal);\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PointsPrimitive.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/MessageHandler.h\"\n\n#include \"IECoreGL\/ToGLPointsConverter.h\"\n#include \"IECoreGL\/PointsPrimitive.h\"\n\nusing namespace IECoreGL;\n\nToGLPointsConverter::ToGLPointsConverter( IECore::ConstPointsPrimitivePtr toConvert )\n\t:\tToGLConverter( \"Converts IECore::PointsPrimitive objects to IECoreGL::PointsPrimitive objects.\", IECore::PointsPrimitiveTypeId )\n{\n\tsrcParameter()->setValue( IECore::constPointerCast<IECore::PointsPrimitive>( toConvert ) );\n}\n\nToGLPointsConverter::~ToGLPointsConverter()\n{\n}\n\nIECore::RunTimeTypedPtr ToGLPointsConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const\n{\n\tIECore::PointsPrimitive::ConstPtr pointsPrim = IECore::staticPointerCast<const IECore::PointsPrimitive>( src ); \/\/ safe because the parameter validated it for us\n\n\tIECore::V3fVectorData::ConstPtr points = pointsPrim->variableData<IECore::V3fVectorData>( \"P\", IECore::PrimitiveVariable::Vertex );\n\tif( !points )\n\t{\n\t\tthrow IECore::Exception( \"Must specify primitive variable \\\"P\\\", of type V3fVectorData and interpolation type Vertex.\" );\n\t}\n\n\t\/\/ get type\n\tPointsPrimitive::Type type = PointsPrimitive::Disk;\n\tif( IECore::ConstStringDataPtr t = pointsPrim->variableData<IECore::StringData>( \"type\", IECore::PrimitiveVariable::Uniform ) )\n\t{\n\t\tif( t->readable()==\"particle\" || t->readable()==\"disk\" || t->readable()==\"blobby\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Disk;\n\t\t}\n\t\telse if( t->readable()==\"sphere\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Sphere;\n\t\t}\n\t\telse if( t->readable()==\"patch\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Quad;\n\t\t}\n\t\telse if( t->readable()==\"gl:point\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Point;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIECore::msg( IECore::Msg::Warning, \"ToGLPointsConverter::doConversion\", boost::format( \"Unknown type \\\"%s\\\" - reverting to particle type.\" ) % t->readable() );\n\t\t}\n\t}\n\n\tPointsPrimitive::Ptr result = new PointsPrimitive( type );\n\n\tfor ( IECore::PrimitiveVariableMap::const_iterator pIt = pointsPrim->variables.begin(); pIt != pointsPrim->variables.end(); ++pIt )\n\t{\n\t\tif ( pIt->first == \"type\" )\n\t\t\tcontinue;\n\n\t\tif ( pIt->second.data )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( pIt->first, pIt->second );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIECore::msg( IECore::Msg::Warning, \"ToGLPointsConverter\", boost::format( \"No data given for primvar \\\"%s\\\"\" ) % pIt->first );\n\t\t}\n\t}\n\n\tIECore::ConstFloatVectorDataPtr widths = pointsPrim->variableData<IECore::FloatVectorData>( \"width\" );\n\tIECore::ConstFloatDataPtr width = pointsPrim->variableData<IECore::FloatData>( \"width\", IECore::PrimitiveVariable::Constant );\n\n\t\/\/ use \"constantwidth\" as \"width\"\n\tif ( pointsPrim->variables.find( \"width\" ) == pointsPrim->variables.end() )\n\t{\n\t\tIECore::PrimitiveVariableMap::const_iterator pIt = pointsPrim->variables.find( \"constantwidth\" );\n\t\tif ( pIt != pointsPrim->variables.end() )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( \"width\", pIt->second );\n\t\t\twidth = IECore::runTimeCast< const IECore::FloatData >(pIt->second.data);\n\t\t}\n\t}\n\n\t\/\/ compute heights\n\tIECore::ConstFloatDataPtr constantAspectData = pointsPrim->variableData<IECore::FloatData>( \"patchaspectratio\", IECore::PrimitiveVariable::Constant );\n\tIECore::ConstFloatVectorDataPtr aspectData = pointsPrim->variableData<IECore::FloatVectorData>( \"patchaspectratio\" );\n\n\tif( !constantAspectData && !aspectData )\n\t{\n\t\t\/\/ heights = width\n\t\tif ( widths )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( \"height\", pointsPrim->variables.find( \"width\" )->second );\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\t\/\/ constant width...\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Constant, new IECore::FloatData(width->readable() ) ) );\n\t\t}\n\t}\n\telse if( constantAspectData )\n\t{\n\t\tfloat aspect = constantAspectData->readable();\n\t\tif ( widths )\n\t\t{\n\t\t\tIECore::FloatVectorDataPtr h = widths->copy();\n\t\t\tstd::vector<float> &hV = h->writable();\n\t\t\tfor( unsigned int i=0; i<hV.size(); i++ )\n\t\t\t{\n\t\t\t\thV[i] \/= aspect;\n\t\t\t}\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( pointsPrim->variables.find(\"width\")->second.interpolation, h ) );\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\t\/\/ constant width...\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Constant, new IECore::FloatData(width->readable() \/ aspect) ) );\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ we have varying aspect data\n\t\tIECore::FloatVectorDataPtr h = aspectData->copy();\n\t\tstd::vector<float> &hV = h->writable();\n\t\tfloat defaultWidth = 1;\n\t\tconst float *widthsP = &defaultWidth;\n\t\tunsigned int widthStride = 0;\n\t\tif( widths )\n\t\t{\n\t\t\twidthsP = &widths->readable()[0];\n\t\t\tif ( widths->readable().size() == aspectData->readable().size() )\n\t\t\t\twidthStride = 1;\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\twidthsP = &width->readable();\n\t\t\twidthStride = 0;\n\t\t}\n\t\tfor( unsigned int i=0; i<hV.size(); i++ )\n\t\t{\n\t\t\thV[i] = *widthsP \/ hV[i];\n\t\t\twidthsP += widthStride;\n\t\t}\n\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( pointsPrim->variables.find(\"patchaspectratio\")->second.interpolation, h ) );\n\t}\n\treturn result;\n}\n<commit_msg>Testing \"type\" primvar as Constant, and if it's not there, then test as Uniform. Should be Constant because if it's Uniform than arePrimitiveVariablesValid() returns False.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/PointsPrimitive.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/MessageHandler.h\"\n\n#include \"IECoreGL\/ToGLPointsConverter.h\"\n#include \"IECoreGL\/PointsPrimitive.h\"\n\nusing namespace IECoreGL;\n\nToGLPointsConverter::ToGLPointsConverter( IECore::ConstPointsPrimitivePtr toConvert )\n\t:\tToGLConverter( \"Converts IECore::PointsPrimitive objects to IECoreGL::PointsPrimitive objects.\", IECore::PointsPrimitiveTypeId )\n{\n\tsrcParameter()->setValue( IECore::constPointerCast<IECore::PointsPrimitive>( toConvert ) );\n}\n\nToGLPointsConverter::~ToGLPointsConverter()\n{\n}\n\nIECore::RunTimeTypedPtr ToGLPointsConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const\n{\n\tIECore::PointsPrimitive::ConstPtr pointsPrim = IECore::staticPointerCast<const IECore::PointsPrimitive>( src ); \/\/ safe because the parameter validated it for us\n\n\tIECore::V3fVectorData::ConstPtr points = pointsPrim->variableData<IECore::V3fVectorData>( \"P\", IECore::PrimitiveVariable::Vertex );\n\tif( !points )\n\t{\n\t\tthrow IECore::Exception( \"Must specify primitive variable \\\"P\\\", of type V3fVectorData and interpolation type Vertex.\" );\n\t}\n\n\t\/\/ get type\n\tPointsPrimitive::Type type = PointsPrimitive::Disk;\n\tIECore::ConstStringDataPtr t = pointsPrim->variableData<IECore::StringData>( \"type\", IECore::PrimitiveVariable::Constant );\n\tif ( !t )\n\t{\n\t\tt = pointsPrim->variableData<IECore::StringData>( \"type\", IECore::PrimitiveVariable::Uniform );\n\t}\n\tif( t )\n\t{\n\t\tif( t->readable()==\"particle\" || t->readable()==\"disk\" || t->readable()==\"blobby\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Disk;\n\t\t}\n\t\telse if( t->readable()==\"sphere\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Sphere;\n\t\t}\n\t\telse if( t->readable()==\"patch\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Quad;\n\t\t}\n\t\telse if( t->readable()==\"gl:point\" )\n\t\t{\n\t\t\ttype = PointsPrimitive::Point;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIECore::msg( IECore::Msg::Warning, \"ToGLPointsConverter::doConversion\", boost::format( \"Unknown type \\\"%s\\\" - reverting to particle type.\" ) % t->readable() );\n\t\t}\n\t}\n\n\tPointsPrimitive::Ptr result = new PointsPrimitive( type );\n\n\tfor ( IECore::PrimitiveVariableMap::const_iterator pIt = pointsPrim->variables.begin(); pIt != pointsPrim->variables.end(); ++pIt )\n\t{\n\t\tif ( pIt->first == \"type\" )\n\t\t\tcontinue;\n\n\t\tif ( pIt->second.data )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( pIt->first, pIt->second );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIECore::msg( IECore::Msg::Warning, \"ToGLPointsConverter\", boost::format( \"No data given for primvar \\\"%s\\\"\" ) % pIt->first );\n\t\t}\n\t}\n\n\tIECore::ConstFloatVectorDataPtr widths = pointsPrim->variableData<IECore::FloatVectorData>( \"width\" );\n\tIECore::ConstFloatDataPtr width = pointsPrim->variableData<IECore::FloatData>( \"width\", IECore::PrimitiveVariable::Constant );\n\n\t\/\/ use \"constantwidth\" as \"width\"\n\tif ( pointsPrim->variables.find( \"width\" ) == pointsPrim->variables.end() )\n\t{\n\t\tIECore::PrimitiveVariableMap::const_iterator pIt = pointsPrim->variables.find( \"constantwidth\" );\n\t\tif ( pIt != pointsPrim->variables.end() )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( \"width\", pIt->second );\n\t\t\twidth = IECore::runTimeCast< const IECore::FloatData >(pIt->second.data);\n\t\t}\n\t}\n\n\t\/\/ compute heights\n\tIECore::ConstFloatDataPtr constantAspectData = pointsPrim->variableData<IECore::FloatData>( \"patchaspectratio\", IECore::PrimitiveVariable::Constant );\n\tIECore::ConstFloatVectorDataPtr aspectData = pointsPrim->variableData<IECore::FloatVectorData>( \"patchaspectratio\" );\n\n\tif( !constantAspectData && !aspectData )\n\t{\n\t\t\/\/ heights = width\n\t\tif ( widths )\n\t\t{\n\t\t\tresult->addPrimitiveVariable( \"height\", pointsPrim->variables.find( \"width\" )->second );\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\t\/\/ constant width...\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Constant, new IECore::FloatData(width->readable() ) ) );\n\t\t}\n\t}\n\telse if( constantAspectData )\n\t{\n\t\tfloat aspect = constantAspectData->readable();\n\t\tif ( widths )\n\t\t{\n\t\t\tIECore::FloatVectorDataPtr h = widths->copy();\n\t\t\tstd::vector<float> &hV = h->writable();\n\t\t\tfor( unsigned int i=0; i<hV.size(); i++ )\n\t\t\t{\n\t\t\t\thV[i] \/= aspect;\n\t\t\t}\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( pointsPrim->variables.find(\"width\")->second.interpolation, h ) );\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\t\/\/ constant width...\n\t\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( IECore::PrimitiveVariable::Constant, new IECore::FloatData(width->readable() \/ aspect) ) );\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ we have varying aspect data\n\t\tIECore::FloatVectorDataPtr h = aspectData->copy();\n\t\tstd::vector<float> &hV = h->writable();\n\t\tfloat defaultWidth = 1;\n\t\tconst float *widthsP = &defaultWidth;\n\t\tunsigned int widthStride = 0;\n\t\tif( widths )\n\t\t{\n\t\t\twidthsP = &widths->readable()[0];\n\t\t\tif ( widths->readable().size() == aspectData->readable().size() )\n\t\t\t\twidthStride = 1;\n\t\t}\n\t\telse if ( width )\n\t\t{\n\t\t\twidthsP = &width->readable();\n\t\t\twidthStride = 0;\n\t\t}\n\t\tfor( unsigned int i=0; i<hV.size(); i++ )\n\t\t{\n\t\t\thV[i] = *widthsP \/ hV[i];\n\t\t\twidthsP += widthStride;\n\t\t}\n\t\tresult->addPrimitiveVariable( \"height\", IECore::PrimitiveVariable( pointsPrim->variables.find(\"patchaspectratio\")->second.interpolation, h ) );\n\t}\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DELEGATE_HPP\n#define DELEGATE_HPP\n\n#include <type_traits>\n#include \"variadic.hpp\"\n\nnamespace ctl {\n template<typename T>\n struct delegate;\n\n namespace impl {\n template<typename R, typename T>\n struct is_valid_function_signature;\n\n template<typename R>\n struct is_valid_function_signature<R, std::nullptr_t> : std::false_type {};\n\n template<typename R, typename ... Args, typename T>\n struct is_valid_function_signature<R(Args...), T> : std::integral_constant<bool,\n std::is_convertible<ctl::return_type<T>, R>::value &&\n ctl::argument_count<T>::value == sizeof...(Args) &&\n ctl::are_convertible<ctl::function_arguments<T>, type_list<Args...>>::value> {};\n\n template<typename R, typename T>\n using is_valid_function_signature_t = typename is_valid_function_signature<\n R, typename std::decay<T>::type>::type;\n }\n\n \/\/\/ Wrapper to store lambda functions.\n \/** This structure is a simple wrapper that, much like std::bind(), stores the \"this\" pointer of\n member functions in order to use member functions like normal functions.\n The bound member function does not need to have the same signature as that of the delegate.\n The delegate parameters just need to be implicitly convertible to that of the member\n function, and the converse is true for the return value.\n\n Use case:\n\n \\code{.cpp}\n std::vector<delegate<int(int)>> v;\n v.push_back([](int i) { return 1*i; });\n v.push_back([](int i) { return 2*i; });\n v.push_back([](int i) { return 3*i; });\n for (auto& d : v) {\n std::cout << d(12) << std::endl;\n }\n \\endcode\n\n It shares similar features with std::function, except that it does not support free\n functions and custom allocators (not needed). On the other hand, it is tailored for use with\n lambda functions (or any other functor), and provides substantial performance improvements\n over std::function (about a factor 2 faster with clang & gcc in -O3).\n\n Based on \"Impossibly fast C++ delegates\".\n http:\/\/www.codeproject.com\/Articles\/11015\/The-Impossibly-Fast-C-Delegates\n **\/\n template<typename R, typename ... Args>\n struct delegate<R(Args...)> {\n \/\/\/ Default constructor.\n \/** When default constructed, a delegate is in \"empty\" state. See empty().\n **\/\n delegate() = default;\n delegate(std::nullptr_t) : delegate() {}\n\n \/\/\/ Construct a new delegate from a member function.\n \/** \\param obj The object on which the delegate acts. When the object is given as a\n reference or a pointer, then only a pointer to this object is kept inside\n the delegate, and the object is expected to outlive the delegate. On the\n other hand, if the object is given as an r-value (either a temporary or an\n r-value reference), a new instance is move constructed inside the delegate,\n and its lifetime is bound to that of the delegate.\n \\param fun The member function. It can be given either as a function pointer, or as an\n std::integral_constant. The latter is usually faster because the function\n pointer is a template argument, and can be more easily inlined by the\n compiler, but it is also more tedious to write.\n **\/\n template<typename T, typename M, typename enable = typename std::enable_if<\n impl::is_valid_function_signature_t<R(Args...), M>::value>::type>\n delegate(T&& obj, M&& fun) {\n init_obj_(std::forward<T>(obj));\n init_fun_<T>(std::forward<M>(fun));\n }\n\n \/\/\/ Construct a new delegate from a functor or lambda.\n \/** \\param obj The functor or lambda. If the functor is given as a reference or a pointer,\n then only a pointer to this object is kept inside the delegate, and the\n object is expected to outlive the delegate. On the other hand, if the\n object is given as an r-value (either a temporary or an r-value reference),\n a new instance is move constructed inside the delegate, and its lifetime is\n bound to that of the delegate.\n **\/\n template<typename T, typename enable = typename std::enable_if<\n impl::is_valid_function_signature_t<R(Args...), T>::value>::type>\n delegate(T&& obj) {\n init_obj_(std::forward<T>(obj));\n using RT = typename std::remove_reference<T>::type;\n init_fun_<T>(std::integral_constant<decltype(&RT::operator()),&RT::operator()>());\n }\n\n delegate(const delegate&) = delete;\n delegate& operator= (const delegate&) = delete;\n\n \/\/\/ Move constructor.\n \/** The delegate object that is moved into this one is left in empty state.\n **\/\n delegate(delegate&& d) :\n fun_(d.fun_), wfun_(d.wfun_), del_(d.del_), mov_(d.mov_) {\n if (mov_) {\n (*mov_)(std::move(d), *this);\n d.mov_ = nullptr;\n } else {\n obj_ = d.obj_;\n }\n\n d.obj_ = nullptr;\n d.del_ = nullptr;\n d.fun_ = nullptr;\n d.wfun_ = nullptr;\n }\n\n \/\/\/ Destructor\n ~delegate() {\n if (del_) {\n (*del_)(obj_);\n }\n }\n\n \/\/\/ Move assignment.\n \/** The delegate object that is moved into this one is left in empty state.\n **\/\n delegate& operator= (delegate&& d) {\n if (del_) {\n (*del_)(obj_);\n }\n\n del_ = d.del_;\n mov_ = d.mov_;\n fun_ = d.fun_;\n wfun_ = d.wfun_;\n\n if (mov_) {\n (*mov_)(std::move(d), *this);\n d.mov_ = nullptr;\n } else {\n obj_ = d.obj_;\n }\n\n d.obj_ = nullptr;\n d.del_ = nullptr;\n d.fun_ = nullptr;\n d.wfun_ = nullptr;\n\n return *this;\n }\n\n \/\/\/ Assign a new functor or lambda to this delegate.\n \/** \\param obj The functor or lambda. If the functor is given as a reference or a pointer,\n then only a pointer to this object is kept inside the delegate, and the\n object is expected to outlive the delegate. On the other hand, if the\n object is given as an r-value (either a temporary or an r-value reference),\n a new instance is move constructed inside the delegate, and its lifetime is\n bound to that of the delegate.\n **\/\n \/\/ template<typename T, typename enable = typename std::enable_if<std::is_convertible<\n \/\/ return_type<T>, R>::value>::type>\n \/\/ delegate& operator= (T&& obj) {\n \/\/ clear();\n\n \/\/ init_obj_(std::forward<T>(obj));\n \/\/ using RT = typename std::remove_reference<T>::type;\n \/\/ init_fun_<T>(std::integral_constant<decltype(&RT::operator()),&RT::operator()>());\n \/\/ return *this;\n \/\/ }\n\n \/\/\/ Put the delegate in \"empty\" state. See empty().\n delegate& operator= (const std::nullptr_t&) {\n clear();\n return *this;\n }\n\n \/\/\/ Put the delegate in \"empty\" state. See empty().\n void clear() {\n if (del_) {\n (*del_)(obj_);\n }\n\n obj_ = nullptr;\n del_ = nullptr;\n mov_ = nullptr;\n fun_ = nullptr;\n wfun_ = nullptr;\n }\n\n \/\/\/ Return 'true' if in \"empty\" state.\n \/** When in \"empty\" state, a delegate has minimal memory usage.\n Trying to call an empty delegate will crash the program.\n **\/\n bool empty() const {\n return obj_ == nullptr;\n }\n\n \/\/\/ Check if the delegate is not in \"empty\" state.\n explicit operator bool () const {\n return !empty();\n }\n\n bool operator == (std::nullptr_t) const {\n return empty();\n }\n\n bool operator != (std::nullptr_t) const {\n return !empty();\n }\n\n \/\/\/ Call the delegate.\n R operator() (Args ... args) const {\n return (*wfun_)(obj_, fun_, std::forward<Args>(args)...);\n }\n\n private :\n using wfun_t = R (*)(void*, void*, Args...);\n using dfun_t = void (*)(void*);\n using mfun_t = void (*)(delegate&&, delegate&);\n\n static const std::size_t max_small_object_size = 2*sizeof(std::size_t);\n\n void* obj_ = nullptr;\n char inplace_[max_small_object_size];\n\n void* fun_ = nullptr;\n wfun_t wfun_ = nullptr;\n\n dfun_t del_ = nullptr;\n mfun_t mov_ = nullptr;\n\n template<typename T>\n static void deleter_(void* obj) {\n delete static_cast<T*>(obj);\n }\n\n template<typename T>\n static void inplace_deleter_(void* obj) {\n static_cast<T*>(obj)->~T();\n }\n\n template<typename T>\n static void inplace_mover_(delegate&& from, delegate& to) {\n to.obj_ = new (static_cast<void*>(to.inplace_)) T(std::move(*static_cast<T*>(from.obj_)));\n inplace_deleter_<T>(from.obj_);\n }\n\n template<typename T, typename M>\n static R wrapper_(void* obj, void* fun, Args... args) {\n M cfun = nullptr;\n *reinterpret_cast<void**>(&cfun) = fun;\n return (static_cast<T*>(obj)->*cfun)(std::forward<Args>(args)...);\n }\n\n template<typename T, typename M, M m>\n static R template_wrapper_(void* obj, void*, Args... args) {\n return (static_cast<T*>(obj)->*m)(std::forward<Args>(args)...);\n }\n\n template<typename T>\n void init_obj_(T& obj) {\n obj_ = &obj;\n }\n\n template<typename T>\n void init_obj_(T* obj) {\n obj_ = obj;\n }\n\n template<typename T>\n void init_obj_(T&& obj, std::false_type) {\n obj_ = new T(std::forward<T>(obj));\n del_ = &deleter_<T>;\n }\n\n template<typename T>\n void init_obj_(T&& obj, std::true_type) {\n \/\/ Small object optimization\n obj_ = new (static_cast<void*>(inplace_)) T(std::forward<T>(obj));\n del_ = &inplace_deleter_<T>;\n mov_ = &inplace_mover_<T>;\n }\n\n template<typename T>\n void init_obj_(T&& obj) {\n init_obj_(std::forward<T>(obj),\n std::integral_constant<bool, sizeof(T) <= max_small_object_size>{});\n }\n\n template<typename T, typename FT, FT F>\n void init_fun_(std::integral_constant<FT,F>) {\n using RT = typename std::remove_reference<T>::type;\n wfun_ = &template_wrapper_<RT, FT, F>;\n }\n\n template<typename T, typename M>\n void init_fun_(M fun) {\n fun_ = *reinterpret_cast<void**>(&fun);\n using RT = typename std::remove_reference<T>::type;\n wfun_ = &wrapper_<RT, M>;\n }\n };\n}\n\n#define make_delegate(obj,func) ctl::delegate<ctl::get_signature<decltype(func)>>( \\\n obj, std::integral_constant<decltype(func),func>{})\n\n#endif\n<commit_msg>Fixed ambiguous template instantiation found by gcc 7.4<commit_after>#ifndef DELEGATE_HPP\n#define DELEGATE_HPP\n\n#include <type_traits>\n#include \"variadic.hpp\"\n\nnamespace ctl {\n template<typename T>\n struct delegate;\n\n namespace impl {\n template<typename R, typename T>\n struct is_valid_function_signature;\n\n template<typename R, typename ... Args>\n struct is_valid_function_signature<R(Args...), std::nullptr_t> : std::false_type {};\n\n template<typename R, typename ... Args, typename T>\n struct is_valid_function_signature<R(Args...), T> : std::integral_constant<bool,\n std::is_convertible<ctl::return_type<T>, R>::value &&\n ctl::argument_count<T>::value == sizeof...(Args) &&\n ctl::are_convertible<ctl::function_arguments<T>, type_list<Args...>>::value> {};\n\n template<typename R, typename T>\n using is_valid_function_signature_t = typename is_valid_function_signature<\n R, typename std::decay<T>::type>::type;\n }\n\n \/\/\/ Wrapper to store lambda functions.\n \/** This structure is a simple wrapper that, much like std::bind(), stores the \"this\" pointer of\n member functions in order to use member functions like normal functions.\n The bound member function does not need to have the same signature as that of the delegate.\n The delegate parameters just need to be implicitly convertible to that of the member\n function, and the converse is true for the return value.\n\n Use case:\n\n \\code{.cpp}\n std::vector<delegate<int(int)>> v;\n v.push_back([](int i) { return 1*i; });\n v.push_back([](int i) { return 2*i; });\n v.push_back([](int i) { return 3*i; });\n for (auto& d : v) {\n std::cout << d(12) << std::endl;\n }\n \\endcode\n\n It shares similar features with std::function, except that it does not support free\n functions and custom allocators (not needed). On the other hand, it is tailored for use with\n lambda functions (or any other functor), and provides substantial performance improvements\n over std::function (about a factor 2 faster with clang & gcc in -O3).\n\n Based on \"Impossibly fast C++ delegates\".\n http:\/\/www.codeproject.com\/Articles\/11015\/The-Impossibly-Fast-C-Delegates\n **\/\n template<typename R, typename ... Args>\n struct delegate<R(Args...)> {\n \/\/\/ Default constructor.\n \/** When default constructed, a delegate is in \"empty\" state. See empty().\n **\/\n delegate() = default;\n delegate(std::nullptr_t) : delegate() {}\n\n \/\/\/ Construct a new delegate from a member function.\n \/** \\param obj The object on which the delegate acts. When the object is given as a\n reference or a pointer, then only a pointer to this object is kept inside\n the delegate, and the object is expected to outlive the delegate. On the\n other hand, if the object is given as an r-value (either a temporary or an\n r-value reference), a new instance is move constructed inside the delegate,\n and its lifetime is bound to that of the delegate.\n \\param fun The member function. It can be given either as a function pointer, or as an\n std::integral_constant. The latter is usually faster because the function\n pointer is a template argument, and can be more easily inlined by the\n compiler, but it is also more tedious to write.\n **\/\n template<typename T, typename M, typename enable = typename std::enable_if<\n impl::is_valid_function_signature_t<R(Args...), M>::value>::type>\n delegate(T&& obj, M&& fun) {\n init_obj_(std::forward<T>(obj));\n init_fun_<T>(std::forward<M>(fun));\n }\n\n \/\/\/ Construct a new delegate from a functor or lambda.\n \/** \\param obj The functor or lambda. If the functor is given as a reference or a pointer,\n then only a pointer to this object is kept inside the delegate, and the\n object is expected to outlive the delegate. On the other hand, if the\n object is given as an r-value (either a temporary or an r-value reference),\n a new instance is move constructed inside the delegate, and its lifetime is\n bound to that of the delegate.\n **\/\n template<typename T, typename enable = typename std::enable_if<\n impl::is_valid_function_signature_t<R(Args...), T>::value>::type>\n delegate(T&& obj) {\n init_obj_(std::forward<T>(obj));\n using RT = typename std::remove_reference<T>::type;\n init_fun_<T>(std::integral_constant<decltype(&RT::operator()),&RT::operator()>());\n }\n\n delegate(const delegate&) = delete;\n delegate& operator= (const delegate&) = delete;\n\n \/\/\/ Move constructor.\n \/** The delegate object that is moved into this one is left in empty state.\n **\/\n delegate(delegate&& d) :\n fun_(d.fun_), wfun_(d.wfun_), del_(d.del_), mov_(d.mov_) {\n if (mov_) {\n (*mov_)(std::move(d), *this);\n d.mov_ = nullptr;\n } else {\n obj_ = d.obj_;\n }\n\n d.obj_ = nullptr;\n d.del_ = nullptr;\n d.fun_ = nullptr;\n d.wfun_ = nullptr;\n }\n\n \/\/\/ Destructor\n ~delegate() {\n if (del_) {\n (*del_)(obj_);\n }\n }\n\n \/\/\/ Move assignment.\n \/** The delegate object that is moved into this one is left in empty state.\n **\/\n delegate& operator= (delegate&& d) {\n if (del_) {\n (*del_)(obj_);\n }\n\n del_ = d.del_;\n mov_ = d.mov_;\n fun_ = d.fun_;\n wfun_ = d.wfun_;\n\n if (mov_) {\n (*mov_)(std::move(d), *this);\n d.mov_ = nullptr;\n } else {\n obj_ = d.obj_;\n }\n\n d.obj_ = nullptr;\n d.del_ = nullptr;\n d.fun_ = nullptr;\n d.wfun_ = nullptr;\n\n return *this;\n }\n\n \/\/\/ Assign a new functor or lambda to this delegate.\n \/** \\param obj The functor or lambda. If the functor is given as a reference or a pointer,\n then only a pointer to this object is kept inside the delegate, and the\n object is expected to outlive the delegate. On the other hand, if the\n object is given as an r-value (either a temporary or an r-value reference),\n a new instance is move constructed inside the delegate, and its lifetime is\n bound to that of the delegate.\n **\/\n \/\/ template<typename T, typename enable = typename std::enable_if<std::is_convertible<\n \/\/ return_type<T>, R>::value>::type>\n \/\/ delegate& operator= (T&& obj) {\n \/\/ clear();\n\n \/\/ init_obj_(std::forward<T>(obj));\n \/\/ using RT = typename std::remove_reference<T>::type;\n \/\/ init_fun_<T>(std::integral_constant<decltype(&RT::operator()),&RT::operator()>());\n \/\/ return *this;\n \/\/ }\n\n \/\/\/ Put the delegate in \"empty\" state. See empty().\n delegate& operator= (std::nullptr_t) {\n clear();\n return *this;\n }\n\n \/\/\/ Put the delegate in \"empty\" state. See empty().\n void clear() {\n if (del_) {\n (*del_)(obj_);\n }\n\n obj_ = nullptr;\n del_ = nullptr;\n mov_ = nullptr;\n fun_ = nullptr;\n wfun_ = nullptr;\n }\n\n \/\/\/ Return 'true' if in \"empty\" state.\n \/** When in \"empty\" state, a delegate has minimal memory usage.\n Trying to call an empty delegate will crash the program.\n **\/\n bool empty() const {\n return obj_ == nullptr;\n }\n\n \/\/\/ Check if the delegate is not in \"empty\" state.\n explicit operator bool () const {\n return !empty();\n }\n\n bool operator == (std::nullptr_t) const {\n return empty();\n }\n\n bool operator != (std::nullptr_t) const {\n return !empty();\n }\n\n \/\/\/ Call the delegate.\n R operator() (Args ... args) const {\n return (*wfun_)(obj_, fun_, std::forward<Args>(args)...);\n }\n\n private :\n using wfun_t = R (*)(void*, void*, Args...);\n using dfun_t = void (*)(void*);\n using mfun_t = void (*)(delegate&&, delegate&);\n\n static const std::size_t max_small_object_size = 2*sizeof(std::size_t);\n\n void* obj_ = nullptr;\n char inplace_[max_small_object_size];\n\n void* fun_ = nullptr;\n wfun_t wfun_ = nullptr;\n\n dfun_t del_ = nullptr;\n mfun_t mov_ = nullptr;\n\n template<typename T>\n static void deleter_(void* obj) {\n delete static_cast<T*>(obj);\n }\n\n template<typename T>\n static void inplace_deleter_(void* obj) {\n static_cast<T*>(obj)->~T();\n }\n\n template<typename T>\n static void inplace_mover_(delegate&& from, delegate& to) {\n to.obj_ = new (static_cast<void*>(to.inplace_)) T(std::move(*static_cast<T*>(from.obj_)));\n inplace_deleter_<T>(from.obj_);\n }\n\n template<typename T, typename M>\n static R wrapper_(void* obj, void* fun, Args... args) {\n M cfun = nullptr;\n *reinterpret_cast<void**>(&cfun) = fun;\n return (static_cast<T*>(obj)->*cfun)(std::forward<Args>(args)...);\n }\n\n template<typename T, typename M, M m>\n static R template_wrapper_(void* obj, void*, Args... args) {\n return (static_cast<T*>(obj)->*m)(std::forward<Args>(args)...);\n }\n\n template<typename T>\n void init_obj_(T& obj) {\n obj_ = &obj;\n }\n\n template<typename T>\n void init_obj_(T* obj) {\n obj_ = obj;\n }\n\n template<typename T>\n void init_obj_(T&& obj, std::false_type) {\n obj_ = new T(std::forward<T>(obj));\n del_ = &deleter_<T>;\n }\n\n template<typename T>\n void init_obj_(T&& obj, std::true_type) {\n \/\/ Small object optimization\n obj_ = new (static_cast<void*>(inplace_)) T(std::forward<T>(obj));\n del_ = &inplace_deleter_<T>;\n mov_ = &inplace_mover_<T>;\n }\n\n template<typename T>\n void init_obj_(T&& obj) {\n init_obj_(std::forward<T>(obj),\n std::integral_constant<bool, sizeof(T) <= max_small_object_size>{});\n }\n\n template<typename T, typename FT, FT F>\n void init_fun_(std::integral_constant<FT,F>) {\n using RT = typename std::remove_reference<T>::type;\n wfun_ = &template_wrapper_<RT, FT, F>;\n }\n\n template<typename T, typename M>\n void init_fun_(M fun) {\n fun_ = *reinterpret_cast<void**>(&fun);\n using RT = typename std::remove_reference<T>::type;\n wfun_ = &wrapper_<RT, M>;\n }\n };\n}\n\n#define make_delegate(obj,func) ctl::delegate<ctl::get_signature<decltype(func)>>( \\\n obj, std::integral_constant<decltype(func),func>{})\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n* Copyright 2022 Axel Waggershauser\n*\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"HRI.h\"\n\n#include \"ZXAlgorithms.h\"\n\n#include <sstream>\n\nnamespace ZXing {\n\nstruct AiInfo\n{\n\tstd::string_view aiPrefix;\n\tint _fieldSize;\t\/\/ if negative, the length is variable and abs(length) give the max size\n\n\tbool isVariableLength() const noexcept { return _fieldSize < 0; }\n\tint fieldSize() const noexcept { return std::abs(_fieldSize); }\n\tint aiSize() const\n\t{\n\t\tif ((aiPrefix[0] == '3' && Contains(\"1234569\", aiPrefix[1])) || aiPrefix == \"703\" || aiPrefix == \"723\")\n\t\t\treturn 4;\n\t\telse\n\t\t\treturn Size(aiPrefix);\n\t}\n};\n\n\/\/ GS1 General Specifications Release 22.0 (Jan 22, 2022)\nstatic const AiInfo aiInfos[] = {\n\/\/ TWO_DIGIT_DATA_LENGTH\n\t{ \"00\", 18 },\n\t{ \"01\", 14 },\n\t{ \"02\", 14 },\n\n\t{ \"10\", -20 },\n\t{ \"11\", 6 },\n\t{ \"12\", 6 },\n\t{ \"13\", 6 },\n\t{ \"15\", 6 },\n\t{ \"16\", 6 },\n\t{ \"17\", 6 },\n\n\t{ \"20\", 2 },\n\t{ \"21\", -20 },\n\t{ \"22\", -20 },\n\n\t{ \"30\", -8 },\n\t{ \"37\", -8 },\n\n\t\/\/internal company codes\n\t{ \"90\", -30 },\n\t{ \"91\", -90 },\n\t{ \"92\", -90 },\n\t{ \"93\", -90 },\n\t{ \"94\", -90 },\n\t{ \"95\", -90 },\n\t{ \"96\", -90 },\n\t{ \"97\", -90 },\n\t{ \"98\", -90 },\n\t{ \"99\", -90 },\n\n\/\/THREE_DIGIT_DATA_LENGTH\n\t{ \"235\", -28 },\n\t{ \"240\", -30 },\n\t{ \"241\", -30 },\n\t{ \"242\", -6 },\n\t{ \"243\", -20 },\n\t{ \"250\", -30 },\n\t{ \"251\", -30 },\n\t{ \"253\", -30 },\n\t{ \"254\", -20 },\n\t{ \"255\", -25 },\n\n\t{ \"400\", -30 },\n\t{ \"401\", -30 },\n\t{ \"402\", 17 },\n\t{ \"403\", -30 },\n\t{ \"410\", 13 },\n\t{ \"411\", 13 },\n\t{ \"412\", 13 },\n\t{ \"413\", 13 },\n\t{ \"414\", 13 },\n\t{ \"415\", 13 },\n\t{ \"416\", 13 },\n\t{ \"417\", 13 },\n\t{ \"420\", -20 },\n\t{ \"421\", -12 },\n\t{ \"422\", 3 },\n\t{ \"423\", -15 },\n\t{ \"424\", 3 },\n\t{ \"425\", -15 },\n\t{ \"426\", 3 },\n\t{ \"427\", -3 },\n\n\t{ \"710\", -20 },\n\t{ \"711\", -20 },\n\t{ \"712\", -20 },\n\t{ \"713\", -20 },\n\t{ \"714\", -20 },\n\t{ \"715\", -20 },\n\n\/\/THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH\n\t{ \"310\", 6 },\n\t{ \"311\", 6 },\n\t{ \"312\", 6 },\n\t{ \"313\", 6 },\n\t{ \"314\", 6 },\n\t{ \"315\", 6 },\n\t{ \"316\", 6 },\n\t{ \"320\", 6 },\n\t{ \"321\", 6 },\n\t{ \"322\", 6 },\n\t{ \"323\", 6 },\n\t{ \"324\", 6 },\n\t{ \"325\", 6 },\n\t{ \"326\", 6 },\n\t{ \"327\", 6 },\n\t{ \"328\", 6 },\n\t{ \"329\", 6 },\n\t{ \"330\", 6 },\n\t{ \"331\", 6 },\n\t{ \"332\", 6 },\n\t{ \"333\", 6 },\n\t{ \"334\", 6 },\n\t{ \"335\", 6 },\n\t{ \"336\", 6 },\n\t{ \"337\", 6 },\n\t{ \"340\", 6 },\n\t{ \"341\", 6 },\n\t{ \"342\", 6 },\n\t{ \"343\", 6 },\n\t{ \"344\", 6 },\n\t{ \"345\", 6 },\n\t{ \"346\", 6 },\n\t{ \"347\", 6 },\n\t{ \"348\", 6 },\n\t{ \"349\", 6 },\n\t{ \"350\", 6 },\n\t{ \"351\", 6 },\n\t{ \"352\", 6 },\n\t{ \"353\", 6 },\n\t{ \"354\", 6 },\n\t{ \"355\", 6 },\n\t{ \"356\", 6 },\n\t{ \"357\", 6 },\n\t{ \"360\", 6 },\n\t{ \"361\", 6 },\n\t{ \"362\", 6 },\n\t{ \"363\", 6 },\n\t{ \"364\", 6 },\n\t{ \"365\", 6 },\n\t{ \"366\", 6 },\n\t{ \"367\", 6 },\n\t{ \"368\", 6 },\n\t{ \"369\", 6 },\n\t{ \"390\", -15 },\n\t{ \"391\", -18 },\n\t{ \"392\", -15 },\n\t{ \"393\", -18 },\n\t{ \"394\", 4 },\n\t{ \"395\", 6 },\n\t{ \"703\", -30 },\n\t{ \"723\", -30 },\n\n\/\/FOUR_DIGIT_DATA_LENGTH\n\t{ \"4300\", -35 },\n\t{ \"4301\", -35 },\n\t{ \"4302\", -70 },\n\t{ \"4303\", -70 },\n\t{ \"4304\", -70 },\n\t{ \"4305\", -70 },\n\t{ \"4306\", -70 },\n\t{ \"4307\", 2 },\n\t{ \"4308\", -30 },\n\t{ \"4310\", -35 },\n\t{ \"4311\", -35 },\n\t{ \"4312\", -70 },\n\t{ \"4313\", -70 },\n\t{ \"4314\", -70 },\n\t{ \"4315\", -70 },\n\t{ \"4316\", -70 },\n\t{ \"4317\", 2 },\n\t{ \"4318\", -20 },\n\t{ \"4319\", -30 },\n\t{ \"4320\", -35 },\n\t{ \"4321\", 1 },\n\t{ \"4322\", 1 },\n\t{ \"4323\", 1 },\n\t{ \"4324\", 10 },\n\t{ \"4325\", 10 },\n\t{ \"4326\", 6 },\n\n\t{ \"7001\", 13 },\n\t{ \"7002\", -30 },\n\t{ \"7003\", 10 },\n\t{ \"7004\", -4 },\n\t{ \"7005\", -12 },\n\t{ \"7006\", 6 },\n\t{ \"7007\", -12 },\n\t{ \"7008\", -3 },\n\t{ \"7009\", -10 },\n\t{ \"7010\", -2 },\n\t{ \"7020\", -20 },\n\t{ \"7021\", -20 },\n\t{ \"7022\", -20 },\n\t{ \"7023\", -30 },\n\t{ \"7040\", 4 },\n\t{ \"7240\", -20 },\n\n\t{ \"8001\", 14 },\n\t{ \"8002\", -20 },\n\t{ \"8003\", -30 },\n\t{ \"8004\", -30 },\n\t{ \"8005\", 6 },\n\t{ \"8006\", 18 },\n\t{ \"8007\", -34 },\n\t{ \"8008\", -12 },\n\t{ \"8009\", -50 },\n\t{ \"8010\", -30 },\n\t{ \"8011\", -12 },\n\t{ \"8012\", -20 },\n\t{ \"8013\", -25 },\n\t{ \"8017\", 18 },\n\t{ \"8018\", 18 },\n\t{ \"8019\", -10 },\n\t{ \"8020\", -25 },\n\t{ \"8026\", 18 },\n\t{ \"8110\", -70 },\n\t{ \"8111\", 4 },\n\t{ \"8112\", -70 },\n\t{ \"8200\", -70 },\n};\n\nstd::string HRIFromGS1(std::string_view gs1)\n{\n\t\/\/TODO: c++20\n\tauto starts_with = [](std::string_view str, std::string_view pre) { return str.substr(0, pre.size()) == pre; };\n\tconstexpr char GS = 29; \/\/ GS character (29 \/ 0x1D)\n\n\tstd::string_view rem = gs1;\n\tstd::string res;\n\n\twhile (rem.size()) {\n\t\tconst AiInfo* i = FindIf(aiInfos, [&](const AiInfo& i) { return starts_with(rem, i.aiPrefix); });\n\t\tif (i == std::end(aiInfos))\n\t\t\treturn {};\n\n\t\tint aiSize = i->aiSize();\n\t\tif (Size(rem) < aiSize)\n\t\t\treturn {};\n\n\t\tres += '(';\n\t\tres += rem.substr(0, aiSize);\n\t\tres += ')';\n\t\trem.remove_prefix(aiSize);\n\n\t\tint fieldSize = i->fieldSize();\n\t\tif (i->isVariableLength()) {\n\t\t\tauto gsPos = rem.find(GS);\n#if 1\n\t\t\tfieldSize = std::min(gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos), fieldSize);\n#else\n\t\t\t\/\/ TODO: ignore the 'max field size' part for now as it breaks rssexpanded-3\/13.png?\n\t\t\tfieldSize = gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos);\n#endif\n\t\t}\n\t\tif (fieldSize == 0 || Size(rem) < fieldSize)\n\t\t\treturn {};\n\n\t\tres += rem.substr(0, fieldSize);\n\t\trem.remove_prefix(fieldSize);\n\n\t\t\/\/ See General Specification v22.0 Section 7.8.6.3: \"...the processing routine SHALL tolerate a single separator character\n\t\t\/\/ immediately following any element string, whether necessary or not...\"\n\t\tif (Size(rem) && rem.front() == GS)\n\t\t\trem.remove_prefix(1);\n\t}\n\n\treturn res;\n}\n\n#if __cplusplus > 201703L\nstd::ostream& operator<<(std::ostream& os, const char8_t* str)\n{\n\treturn os << reinterpret_cast<const char*>(str);\n}\n#endif\n\nstd::string HRIFromISO15434(std::string_view str)\n{\n\t\/\/ Use available unicode symbols to simulate sub- and superscript letters as specified in\n\t\/\/ ISO\/IEC 15434:2019(E) 6. Human readable representation\n\n\tstd::ostringstream oss;\n\n\tfor (char c : str) {\n\t\tswitch (c) {\n\t\tcase 4: oss << u8\"\\u1d31\\u1d52\\u209c\"; break; \/\/ EOT\n\t\tcase 28: oss << u8\"\\ua7f3\\u209b\"; break; \/\/ FS\n\t\tcase 29: oss << u8\"\\u1d33\\u209b\"; break; \/\/ GS\n\t\tcase 30: oss << u8\"\\u1d3f\\u209b\"; break; \/\/ RS\n\t\tcase 31: oss << u8\"\\u1d41\\u209b\"; break; \/\/ US\n\t\tdefault: oss << c;\n\t\t}\n\t}\n\n\treturn oss.str();\n}\n\n} \/\/ namespace ZXing\n<commit_msg>HRI: use unicode \"Control Pictures\" for ASCII control characters<commit_after>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n* Copyright 2022 Axel Waggershauser\n*\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"HRI.h\"\n\n#include \"ZXAlgorithms.h\"\n\n#include <sstream>\n\nnamespace ZXing {\n\nstruct AiInfo\n{\n\tstd::string_view aiPrefix;\n\tint _fieldSize;\t\/\/ if negative, the length is variable and abs(length) give the max size\n\n\tbool isVariableLength() const noexcept { return _fieldSize < 0; }\n\tint fieldSize() const noexcept { return std::abs(_fieldSize); }\n\tint aiSize() const\n\t{\n\t\tif ((aiPrefix[0] == '3' && Contains(\"1234569\", aiPrefix[1])) || aiPrefix == \"703\" || aiPrefix == \"723\")\n\t\t\treturn 4;\n\t\telse\n\t\t\treturn Size(aiPrefix);\n\t}\n};\n\n\/\/ GS1 General Specifications Release 22.0 (Jan 22, 2022)\nstatic const AiInfo aiInfos[] = {\n\/\/ TWO_DIGIT_DATA_LENGTH\n\t{ \"00\", 18 },\n\t{ \"01\", 14 },\n\t{ \"02\", 14 },\n\n\t{ \"10\", -20 },\n\t{ \"11\", 6 },\n\t{ \"12\", 6 },\n\t{ \"13\", 6 },\n\t{ \"15\", 6 },\n\t{ \"16\", 6 },\n\t{ \"17\", 6 },\n\n\t{ \"20\", 2 },\n\t{ \"21\", -20 },\n\t{ \"22\", -20 },\n\n\t{ \"30\", -8 },\n\t{ \"37\", -8 },\n\n\t\/\/internal company codes\n\t{ \"90\", -30 },\n\t{ \"91\", -90 },\n\t{ \"92\", -90 },\n\t{ \"93\", -90 },\n\t{ \"94\", -90 },\n\t{ \"95\", -90 },\n\t{ \"96\", -90 },\n\t{ \"97\", -90 },\n\t{ \"98\", -90 },\n\t{ \"99\", -90 },\n\n\/\/THREE_DIGIT_DATA_LENGTH\n\t{ \"235\", -28 },\n\t{ \"240\", -30 },\n\t{ \"241\", -30 },\n\t{ \"242\", -6 },\n\t{ \"243\", -20 },\n\t{ \"250\", -30 },\n\t{ \"251\", -30 },\n\t{ \"253\", -30 },\n\t{ \"254\", -20 },\n\t{ \"255\", -25 },\n\n\t{ \"400\", -30 },\n\t{ \"401\", -30 },\n\t{ \"402\", 17 },\n\t{ \"403\", -30 },\n\t{ \"410\", 13 },\n\t{ \"411\", 13 },\n\t{ \"412\", 13 },\n\t{ \"413\", 13 },\n\t{ \"414\", 13 },\n\t{ \"415\", 13 },\n\t{ \"416\", 13 },\n\t{ \"417\", 13 },\n\t{ \"420\", -20 },\n\t{ \"421\", -12 },\n\t{ \"422\", 3 },\n\t{ \"423\", -15 },\n\t{ \"424\", 3 },\n\t{ \"425\", -15 },\n\t{ \"426\", 3 },\n\t{ \"427\", -3 },\n\n\t{ \"710\", -20 },\n\t{ \"711\", -20 },\n\t{ \"712\", -20 },\n\t{ \"713\", -20 },\n\t{ \"714\", -20 },\n\t{ \"715\", -20 },\n\n\/\/THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH\n\t{ \"310\", 6 },\n\t{ \"311\", 6 },\n\t{ \"312\", 6 },\n\t{ \"313\", 6 },\n\t{ \"314\", 6 },\n\t{ \"315\", 6 },\n\t{ \"316\", 6 },\n\t{ \"320\", 6 },\n\t{ \"321\", 6 },\n\t{ \"322\", 6 },\n\t{ \"323\", 6 },\n\t{ \"324\", 6 },\n\t{ \"325\", 6 },\n\t{ \"326\", 6 },\n\t{ \"327\", 6 },\n\t{ \"328\", 6 },\n\t{ \"329\", 6 },\n\t{ \"330\", 6 },\n\t{ \"331\", 6 },\n\t{ \"332\", 6 },\n\t{ \"333\", 6 },\n\t{ \"334\", 6 },\n\t{ \"335\", 6 },\n\t{ \"336\", 6 },\n\t{ \"337\", 6 },\n\t{ \"340\", 6 },\n\t{ \"341\", 6 },\n\t{ \"342\", 6 },\n\t{ \"343\", 6 },\n\t{ \"344\", 6 },\n\t{ \"345\", 6 },\n\t{ \"346\", 6 },\n\t{ \"347\", 6 },\n\t{ \"348\", 6 },\n\t{ \"349\", 6 },\n\t{ \"350\", 6 },\n\t{ \"351\", 6 },\n\t{ \"352\", 6 },\n\t{ \"353\", 6 },\n\t{ \"354\", 6 },\n\t{ \"355\", 6 },\n\t{ \"356\", 6 },\n\t{ \"357\", 6 },\n\t{ \"360\", 6 },\n\t{ \"361\", 6 },\n\t{ \"362\", 6 },\n\t{ \"363\", 6 },\n\t{ \"364\", 6 },\n\t{ \"365\", 6 },\n\t{ \"366\", 6 },\n\t{ \"367\", 6 },\n\t{ \"368\", 6 },\n\t{ \"369\", 6 },\n\t{ \"390\", -15 },\n\t{ \"391\", -18 },\n\t{ \"392\", -15 },\n\t{ \"393\", -18 },\n\t{ \"394\", 4 },\n\t{ \"395\", 6 },\n\t{ \"703\", -30 },\n\t{ \"723\", -30 },\n\n\/\/FOUR_DIGIT_DATA_LENGTH\n\t{ \"4300\", -35 },\n\t{ \"4301\", -35 },\n\t{ \"4302\", -70 },\n\t{ \"4303\", -70 },\n\t{ \"4304\", -70 },\n\t{ \"4305\", -70 },\n\t{ \"4306\", -70 },\n\t{ \"4307\", 2 },\n\t{ \"4308\", -30 },\n\t{ \"4310\", -35 },\n\t{ \"4311\", -35 },\n\t{ \"4312\", -70 },\n\t{ \"4313\", -70 },\n\t{ \"4314\", -70 },\n\t{ \"4315\", -70 },\n\t{ \"4316\", -70 },\n\t{ \"4317\", 2 },\n\t{ \"4318\", -20 },\n\t{ \"4319\", -30 },\n\t{ \"4320\", -35 },\n\t{ \"4321\", 1 },\n\t{ \"4322\", 1 },\n\t{ \"4323\", 1 },\n\t{ \"4324\", 10 },\n\t{ \"4325\", 10 },\n\t{ \"4326\", 6 },\n\n\t{ \"7001\", 13 },\n\t{ \"7002\", -30 },\n\t{ \"7003\", 10 },\n\t{ \"7004\", -4 },\n\t{ \"7005\", -12 },\n\t{ \"7006\", 6 },\n\t{ \"7007\", -12 },\n\t{ \"7008\", -3 },\n\t{ \"7009\", -10 },\n\t{ \"7010\", -2 },\n\t{ \"7020\", -20 },\n\t{ \"7021\", -20 },\n\t{ \"7022\", -20 },\n\t{ \"7023\", -30 },\n\t{ \"7040\", 4 },\n\t{ \"7240\", -20 },\n\n\t{ \"8001\", 14 },\n\t{ \"8002\", -20 },\n\t{ \"8003\", -30 },\n\t{ \"8004\", -30 },\n\t{ \"8005\", 6 },\n\t{ \"8006\", 18 },\n\t{ \"8007\", -34 },\n\t{ \"8008\", -12 },\n\t{ \"8009\", -50 },\n\t{ \"8010\", -30 },\n\t{ \"8011\", -12 },\n\t{ \"8012\", -20 },\n\t{ \"8013\", -25 },\n\t{ \"8017\", 18 },\n\t{ \"8018\", 18 },\n\t{ \"8019\", -10 },\n\t{ \"8020\", -25 },\n\t{ \"8026\", 18 },\n\t{ \"8110\", -70 },\n\t{ \"8111\", 4 },\n\t{ \"8112\", -70 },\n\t{ \"8200\", -70 },\n};\n\nstd::string HRIFromGS1(std::string_view gs1)\n{\n\t\/\/TODO: c++20\n\tauto starts_with = [](std::string_view str, std::string_view pre) { return str.substr(0, pre.size()) == pre; };\n\tconstexpr char GS = 29; \/\/ GS character (29 \/ 0x1D)\n\n\tstd::string_view rem = gs1;\n\tstd::string res;\n\n\twhile (rem.size()) {\n\t\tconst AiInfo* i = FindIf(aiInfos, [&](const AiInfo& i) { return starts_with(rem, i.aiPrefix); });\n\t\tif (i == std::end(aiInfos))\n\t\t\treturn {};\n\n\t\tint aiSize = i->aiSize();\n\t\tif (Size(rem) < aiSize)\n\t\t\treturn {};\n\n\t\tres += '(';\n\t\tres += rem.substr(0, aiSize);\n\t\tres += ')';\n\t\trem.remove_prefix(aiSize);\n\n\t\tint fieldSize = i->fieldSize();\n\t\tif (i->isVariableLength()) {\n\t\t\tauto gsPos = rem.find(GS);\n#if 1\n\t\t\tfieldSize = std::min(gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos), fieldSize);\n#else\n\t\t\t\/\/ TODO: ignore the 'max field size' part for now as it breaks rssexpanded-3\/13.png?\n\t\t\tfieldSize = gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos);\n#endif\n\t\t}\n\t\tif (fieldSize == 0 || Size(rem) < fieldSize)\n\t\t\treturn {};\n\n\t\tres += rem.substr(0, fieldSize);\n\t\trem.remove_prefix(fieldSize);\n\n\t\t\/\/ See General Specification v22.0 Section 7.8.6.3: \"...the processing routine SHALL tolerate a single separator character\n\t\t\/\/ immediately following any element string, whether necessary or not...\"\n\t\tif (Size(rem) && rem.front() == GS)\n\t\t\trem.remove_prefix(1);\n\t}\n\n\treturn res;\n}\n\n#if __cplusplus > 201703L\nstd::ostream& operator<<(std::ostream& os, const char8_t* str)\n{\n\treturn os << reinterpret_cast<const char*>(str);\n}\n#endif\n\nstd::string HRIFromISO15434(std::string_view str)\n{\n\t\/\/ Use available unicode symbols to simulate sub- and superscript letters as specified in\n\t\/\/ ISO\/IEC 15434:2019(E) 6. Human readable representation\n\n\tstd::ostringstream oss;\n\n\tfor (char c : str) {\n#if 1\n\t\tif (0 <= c && c <= 0x20)\n\t\t\toss << \"\\xe2\\x90\" << char(0x80 + c); \/\/ Unicode Block “Control Pictures”: 0x2400\n\t\telse\n\t\t\toss << c;\n#else\n\t\tswitch (c) {\n\t\tcase 4: oss << u8\"\\u1d31\\u1d52\\u209c\"; break; \/\/ EOT\n\t\tcase 28: oss << u8\"\\ua7f3\\u209b\"; break; \/\/ FS\n\t\tcase 29: oss << u8\"\\u1d33\\u209b\"; break; \/\/ GS\n\t\tcase 30: oss << u8\"\\u1d3f\\u209b\"; break; \/\/ RS\n\t\tcase 31: oss << u8\"\\u1d41\\u209b\"; break; \/\/ US\n\t\tdefault: oss << c;\n\t\t}\n#endif\n\t}\n\n\treturn oss.str();\n}\n\n} \/\/ namespace ZXing\n<|endoftext|>"} {"text":"<commit_before>#include <system\/System.h>\n\n#ifdef HX_MACOS\n#include <CoreFoundation\/CoreFoundation.h>\n#endif\n\n#include <SDL_rwops.h>\n#include <SDL_timer.h>\n\n\nnamespace lime {\n\t\n\t\n\tdouble System::GetTimer () {\n\t\t\n\t\treturn SDL_GetTicks ();\n\t\t\n\t}\n\t\n\t\n\tFILE* FILE_HANDLE::getFile () {\n\t\t\n\t\tif (((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE) {\n\t\t\t\n\t\t\treturn ((SDL_RWops*)handle)->hidden.stdio.fp;\n\t\t\t\n\t\t} else if (((SDL_RWops*)handle)->type == SDL_RWOPS_JNIFILE) {\n\t\t\t\n\t\t\t#ifdef ANDROID\n\t\t\tFILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, \"rb\");\n\t\t\t::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0);\n\t\t\treturn file;\n\t\t\t#endif\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t}\n\t\n\t\n\tint FILE_HANDLE::getLength () {\n\t\t\n\t\treturn SDL_RWsize (((SDL_RWops*)handle));\n\t\t\n\t}\n\t\n\t\n\tbool FILE_HANDLE::isFile () {\n\t\t\n\t\treturn ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE;\n\t\t\n\t}\n\t\n\t\n\tint fclose (FILE_HANDLE *stream) {\n\t\t\n\t\tif (stream) {\n\t\t\t\n\t\t\treturn SDL_RWclose ((SDL_RWops*)stream->handle);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn 0;\n\t\t\n\t}\n\t\n\t\n\tFILE_HANDLE *fdopen (int fd, const char *mode) {\n\t\t\n\t\tFILE* fp = ::fdopen (fd, mode);\n\t\tSDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE);\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t}\n\t\n\t\n\tFILE_HANDLE *fopen (const char *filename, const char *mode) {\n\t\t\n\t\tSDL_RWops *result;\n\t\t\n\t\t#ifdef HX_MACOS\n\t\t\n\t\tresult = SDL_RWFromFile (filename, \"rb\");\n\t\t\n\t\tif (!result) {\n\t\t\t\n\t\t\tCFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);\n\t\t\tCFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);\n\t\t\tCFRelease (str);\n\t\t\t\n\t\t\tif (path) {\n\t\t\t\t\n\t\t\t\tstr = CFURLCopyPath (path);\n\t\t\t\tCFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);\n\t\t\t\tchar *buffer = (char *)malloc (maxSize);\n\t\t\t\t\n\t\t\t\tif (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {\n\t\t\t\t\t\n\t\t\t\t\tresult = SDL_RWFromFP (::fopen (buffer, \"rb\"), SDL_TRUE);\n\t\t\t\t\tfree (buffer);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tCFRelease (str);\n\t\t\t\tCFRelease (path);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t#else\n\t\tresult = SDL_RWFromFile (filename, mode);\n\t\t#endif\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t}\n\t\n\t\n\tsize_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {\n\t\t\n\t\treturn SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);\n\t\t\n\t}\n\t\n\t\n\tint fseek (FILE_HANDLE *stream, long int offset, int origin) {\n\t\t\n\t\treturn SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin);\n\t\t\n\t}\n\t\n\t\n\tlong int ftell (FILE_HANDLE *stream) {\n\t\t\n\t\treturn SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL);\n\t\t\n\t}\n\t\n\t\n\tsize_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {\n\t\t\n\t\treturn SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);\n\t\t\n\t}\n\t\n\t\n}<commit_msg>Fix Windows file I\/O<commit_after>#include <system\/System.h>\n\n#ifdef HX_MACOS\n#include <CoreFoundation\/CoreFoundation.h>\n#endif\n\n#ifdef HX_WINDOWS\n#include <stdio.h>\n\/\/#include <io.h>\n\/\/#include <fcntl.h>\n#endif\n\n#include <SDL_rwops.h>\n#include <SDL_timer.h>\n\n\nnamespace lime {\n\t\n\t\n\tdouble System::GetTimer () {\n\t\t\n\t\treturn SDL_GetTicks ();\n\t\t\n\t}\n\t\n\t\n\tFILE* FILE_HANDLE::getFile () {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\tswitch (((SDL_RWops*)handle)->type) {\n\t\t\t\n\t\t\tcase SDL_RWOPS_STDFILE:\n\t\t\t\t\n\t\t\t\treturn ((SDL_RWops*)handle)->hidden.stdio.fp;\n\t\t\t\n\t\t\tcase SDL_RWOPS_JNIFILE:\n\t\t\t{\n\t\t\t\t#ifdef ANDROID\n\t\t\t\tFILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, \"rb\");\n\t\t\t\t::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0);\n\t\t\t\treturn file;\n\t\t\t\t#endif\n\t\t\t}\n\t\t\t\t\n\t\t\tcase SDL_RWOPS_WINFILE:\n\t\t\t{\n\t\t\t\t\/*#ifdef HX_WINDOWS\n\t\t\t\tprintf(\"SDKFLJDSLFKJ\\n\");\n\t\t\t\tint fd = _open_osfhandle ((intptr_t)((SDL_RWops*)handle)->hidden.windowsio.h, _O_RDONLY);\n\t\t\t\t\n\t\t\t\tif (fd != -1) {\n\t\t\t\t\tprintf(\"SDKFLJDSLFKJ\\n\");\n\t\t\t\t\treturn ::fdopen (fd, \"rb\");\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t#endif*\/\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t\t#else\n\t\t\n\t\treturn (FILE*)handle;\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tint FILE_HANDLE::getLength () {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn SDL_RWsize (((SDL_RWops*)handle));\n\t\t\n\t\t#else\n\t\t\n\t\treturn 0;\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tbool FILE_HANDLE::isFile () {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE;\n\t\t\n\t\t#else\n\t\t\n\t\treturn true;\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tint fclose (FILE_HANDLE *stream) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\tif (stream) {\n\t\t\t\n\t\t\treturn SDL_RWclose ((SDL_RWops*)stream->handle);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn 0;\n\t\t\n\t\t#else\n\t\t\n\t\treturn ::fclose ((FILE*)stream->handle);\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tFILE_HANDLE *fdopen (int fd, const char *mode) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\tFILE* fp = ::fdopen (fd, mode);\n\t\tSDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE);\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t\t#else\n\t\t\n\t\tFILE* result = ::fdopen (fd, mode);\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tFILE_HANDLE *fopen (const char *filename, const char *mode) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\tSDL_RWops *result;\n\t\t\n\t\t#ifdef HX_MACOS\n\t\t\n\t\tresult = SDL_RWFromFile (filename, \"rb\");\n\t\t\n\t\tif (!result) {\n\t\t\t\n\t\t\tCFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);\n\t\t\tCFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);\n\t\t\tCFRelease (str);\n\t\t\t\n\t\t\tif (path) {\n\t\t\t\t\n\t\t\t\tstr = CFURLCopyPath (path);\n\t\t\t\tCFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);\n\t\t\t\tchar *buffer = (char *)malloc (maxSize);\n\t\t\t\t\n\t\t\t\tif (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {\n\t\t\t\t\t\n\t\t\t\t\tresult = SDL_RWFromFP (::fopen (buffer, \"rb\"), SDL_TRUE);\n\t\t\t\t\tfree (buffer);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tCFRelease (str);\n\t\t\t\tCFRelease (path);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t#else\n\t\tresult = SDL_RWFromFile (filename, mode);\n\t\t#endif\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t\t#else\n\t\t\n\t\tFILE* result = ::fopen (filename, mode);\n\t\t\n\t\tif (result) {\n\t\t\t\n\t\t\treturn new FILE_HANDLE (result);\n\t\t\t\n\t\t}\n\t\t\n\t\treturn NULL;\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tsize_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);\n\t\t\n\t\t#else\n\t\t\n\t\treturn ::fread (ptr, size, count, (FILE*)stream->handle);\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tint fseek (FILE_HANDLE *stream, long int offset, int origin) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin);\n\t\t\n\t\t#else\n\t\t\n\t\treturn ::fseek ((FILE*)stream->handle, offset, origin);\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tlong int ftell (FILE_HANDLE *stream) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL);\n\t\t\n\t\t#else\n\t\t\n\t\treturn ::ftell ((FILE*)stream->handle);\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n\tsize_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {\n\t\t\n\t\t#ifndef HX_WINDOWS\n\t\t\n\t\treturn SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);\n\t\t\n\t\t#else\n\t\t\n\t\treturn ::fwrite (ptr, size, count, (FILE*)stream->handle);\n\t\t\n\t\t#endif\n\t\t\n\t}\n\t\n\t\n}<|endoftext|>"} {"text":"<commit_before>#include \"c-enum.src.hpp\"\n#include \"c-enum.gen.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include \"tests\/catch.hpp\"\n\nusing namespace reflang;\nusing namespace std;\n\nTEST_CASE(\"iterate\")\n{\n\tfor (const auto& it : Enum<CEnum>::Iterate())\n\t{\n\t\tREQUIRE(false);\n\t}\n}\n\nTEST_CASE(\"to string\")\n{\n\tREQUIRE(Enum<CEnum>::Translate(CEnum()) == \"\");\n}\n\nTEST_CASE(\"from string\")\n{\n\tCEnum e1;\n\tREQUIRE(!Enum<CEnum>::TryTranslate(\"\", e1));\n\tREQUIRE(!Enum<CEnum>::TryTranslate(\"Hi\", e1));\n}\n<commit_msg>Fix tests for C-style enums<commit_after>#include \"c-enum.src.hpp\"\n#include \"c-enum.gen.hpp\"\n\n#define CATCH_CONFIG_MAIN\n#include \"tests\/catch.hpp\"\n\nusing namespace reflang;\nusing namespace std;\n\nTEST_CASE(\"iterate\")\n{\n\tint i = 0;\n\tfor (const auto& it : Enum<CEnum>::Iterate())\n\t{\n\t\tswitch (i)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tREQUIRE(it == CEnum::Value0);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tREQUIRE(it == CEnum::Value1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tREQUIRE(false);\n\t\t\t\tbreak;\n\t\t}\n\t\t++i;\n\t}\n}\n\nTEST_CASE(\"to string\")\n{\n\tREQUIRE(Enum<CEnum>::Translate(CEnum::Value0) == \"Value0\");\n\tREQUIRE(Enum<CEnum>::Translate(CEnum::Value1) == \"Value1\");\n}\n\nTEST_CASE(\"from string\")\n{\n\tauto FromString = [](const string& s)\n\t{\n\t\tCEnum e;\n\t\tREQUIRE(Enum<CEnum>::TryTranslate(s, e));\n\t\treturn e;\n\t};\n\tREQUIRE(FromString(\"Value0\") == CEnum::Value0);\n\tREQUIRE(FromString(\"Value1\") == CEnum::Value1);\n\n\tCEnum e;\n\tREQUIRE(!Enum<CEnum>::TryTranslate(\"UnknownString\", e));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <unistd.h>\n#include <sstream>\n#include <string>\nusing namespace std;\n\nint auto_commit() {\n vector<string> cmds;\n cmds.push_back(\"echo `date \\\"+%Y-%m-%d %H:%M:%S\\\"` >> exe_history\");\n cmds.push_back(\"git add .\");\n cmds.push_back(\"git commit -m \\\"impl ApnsPooledConnection.java\\\"\");\n cmds.push_back(\"git push\");\n\n vector<string>::iterator iter=cmds.begin();\n for(; iter!=cmds.end(); iter++) {\n string s=*iter;\n system(s.c_str());\n }\n}\n\nint main() {\n while(true) {\n auto_commit();\n\n \/* gap 6 hours *\/\n for(int i=1; i<4320; ++i) {\n \/* print keep-alive log *\/\n std::ostringstream ss;\n ss << i;\n string cmd=\"echo \";\n cmd+=ss.str();\n cmd+=\" >> keep_thread_alive.log\";\n system(cmd.c_str());\n sleep(5);\n }\n }\n return 0;\n}\n\n\n<commit_msg>Create github.cpp<commit_after>#include <iostream>\n#include <cstdlib>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <unistd.h>\n#include <sstream>\n#include <string>\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nusing namespace std;\n\nint auto_commit() {\n vector<string> cmds;\n cmds.push_back(\"echo `date \\\"+%Y-%m-%d %H:%M:%S\\\"` >> exe_history\");\n cmds.push_back(\"git add .\");\n cmds.push_back(\"git commit -m \\\"impl ApnsPooledConnection.java\\\"\");\n cmds.push_back(\"git push\");\n\n vector<string>::iterator iter=cmds.begin();\n for(; iter!=cmds.end(); iter++) {\n string s=*iter;\n system(s.c_str());\n }\n}\n\nint main() {\n while(true) {\n srand((unsigned)time(NULL));\n int num=rand()%4;\n\n for(int i=0; i<num; ++i) {\n auto_commit();\n }\n\n \/* gap 24 hours *\/\n for(int i=1; i<17280; ++i) {\n \/* print keep-alive log *\/\n std::ostringstream ss;\n ss << i;\n string cmd=\"echo \";\n cmd+=ss.str();\n cmd+=\" >> keep_thread_alive.log\";\n system(cmd.c_str());\n sleep(5);\n }\n }\n return 0;\n}\n\n\/\/ #include <iostream>\n\/\/ #include <cstdlib>\n\/\/ #include <vector>\n\/\/ #include <iostream>\n\/\/ #include <algorithm>\n\/\/ #include <unistd.h>\n\/\/ #include <sstream>\n\/\/ #include <string>\n\/\/ using namespace std;\n\n\/\/ int auto_commit() {\n\/\/ vector<string> cmds;\n\/\/ cmds.push_back(\"echo `date \\\"+%Y-%m-%d %H:%M:%S\\\"` >> exe_history\");\n\/\/ cmds.push_back(\"git add .\");\n\/\/ cmds.push_back(\"git commit -m \\\"impl ApnsPooledConnection.java\\\"\");\n\/\/ cmds.push_back(\"git push\");\n\n\/\/ vector<string>::iterator iter=cmds.begin();\n\/\/ for(; iter!=cmds.end(); iter++) {\n\/\/ string s=*iter;\n\/\/ system(s.c_str());\n\/\/ }\n\/\/ }\n\n\/\/ int main() {\n\/\/ while(true) {\n\/\/ auto_commit();\n\n\/\/ \/* gap 6 hours *\/\n\/\/ for(int i=1; i<4320; ++i) {\n\/\/ \/* print keep-alive log *\/\n\/\/ std::ostringstream ss;\n\/\/ ss << i;\n\/\/ string cmd=\"echo \";\n\/\/ cmd+=ss.str();\n\/\/ cmd+=\" >> keep_thread_alive.log\";\n\/\/ system(cmd.c_str());\n\/\/ sleep(5);\n\/\/ }\n\/\/ }\n\/\/ return 0;\n\/\/ }\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/memory_size.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file memory_size.C\n\/\/\/ @brief Return the effective memory size behind a target\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#include <fapi2.H>\n#include <lib\/mss_attribute_accessors.H>\n\n#include <lib\/shared\/mss_const.H>\n#include <lib\/eff_config\/memory_size.H>\n\n#include <lib\/utils\/find.H>\n\nnamespace mss\n{\n\n\/\/\/\n\/\/\/ @brief Return the total memory size behind an MCA\n\/\/\/ @param[in] i_target the MCA target\n\/\/\/ @param[out] o_size the size of memory in GB behind the target\n\/\/\/ @return FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )\n{\n uint32_t l_sizes[MAX_DIMM_PER_PORT];\n o_size = 0;\n\n FAPI_TRY( mss::eff_dimm_size(i_target, &(l_sizes[0])) );\n\n for (size_t i = 0; i < MAX_DIMM_PER_PORT; ++i)\n {\n o_size += l_sizes[i];\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Return the total memory size behind an MBIST\n\/\/\/ @param[in] i_target the MCBIST target\n\/\/\/ @param[out] o_size the size of memory in GB behind the target\n\/\/\/ @return FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )\n{\n o_size = 0;\n\n for (const auto& mcs : mss::find_targets<fapi2::TARGET_TYPE_MCS>(i_target))\n {\n uint32_t l_sizes[PORTS_PER_MCS][MAX_DIMM_PER_PORT];\n FAPI_TRY( mss::eff_dimm_size(mcs, &(l_sizes[0][0])) );\n\n for (size_t i = 0; i < PORTS_PER_MCS; ++i)\n {\n for (size_t j = 0; j < MAX_DIMM_PER_PORT; ++j)\n {\n o_size += l_sizes[i][j];\n }\n }\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n}\n\n<commit_msg>Change eff_memory_size to account for non-initialized attrs<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/memory_size.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file memory_size.C\n\/\/\/ @brief Return the effective memory size behind a target\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#include <fapi2.H>\n#include <lib\/mss_attribute_accessors.H>\n\n#include <lib\/shared\/mss_const.H>\n#include <lib\/eff_config\/memory_size.H>\n\n#include <lib\/utils\/find.H>\n\nnamespace mss\n{\n\n\/\/\/\n\/\/\/ @brief Return the total memory size behind an MCA\n\/\/\/ @param[in] i_target the MCA target\n\/\/\/ @param[out] o_size the size of memory in GB behind the target\n\/\/\/ @return FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )\n{\n \/\/ Don't try to get cute and read the attributes once and loop over the array.\n \/\/ Cronus honors initToZero which would work, but HB might not and so we might get\n \/\/ crap in some of the attributes (which we shouldn't access as there's no DIMM there)\n uint32_t l_sizes = 0;\n o_size = 0;\n\n for (const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target))\n {\n FAPI_TRY( mss::eff_dimm_size(d, l_sizes) );\n o_size += l_sizes;\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Return the total memory size behind an MBIST\n\/\/\/ @param[in] i_target the MCBIST target\n\/\/\/ @param[out] o_size the size of memory in GB behind the target\n\/\/\/ @return FAPI2_RC_SUCCESS if ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )\n{\n o_size = 0;\n\n for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target))\n {\n uint64_t l_size = 0;\n FAPI_TRY( eff_memory_size(p, l_size) );\n o_size += l_size;\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/fs\/turing\/cvs\/copasi_dev\/cvs_admin\/addHeader,v $\n\/\/ $Revision: 1.18 $\n\/\/ $Name: HEAD $\n\/\/ $Author: shoops $\n\/\/ $Date: 2012\/03\/07 20:49:51 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \"CPlotColors.h\"\n\n\/\/static\nstd::string CPlotColors::getCopasiColorStr(size_t index)\n{\n index = index % 6;\n\n switch (index)\n {\n case 0: return \"#FF0000\";\n case 1: return \"#0000FF\";\n case 2: return \"#00E600\";\n case 3: return \"#00BEF0\";\n case 4: return \"#F000FF\";\n case 5: return \"#F0C800\";\n\n }\n\n return \"auto\";\n}\n\n\/\/static\nsize_t CPlotColors::getNumCopasiColors()\n{\n return 6;\n}\n\n\n\n\/\/QColor curveColours[6] = {QColor(255, 0, 0), QColor(0, 0, 255), QColor(0, 230, 0), QColor(0, 190, 240), QColor(240, 0, 255), QColor(240, 200, 0)} ; \/\/TODO\n<commit_msg>- issue 2877: new colors added<commit_after>\/\/ Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the\n\/\/ University of Virginia, University of Heidelberg, and University\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2012 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \"CPlotColors.h\"\n\n\/\/static\nstd::string CPlotColors::getCopasiColorStr(size_t index)\n{\n index = index % getNumCopasiColors();\n\n switch (index)\n {\n case 0:\n return \"#FF0000\"; \/\/red\n\n case 1:\n return \"#0000FF\"; \/\/blue\n\n case 2:\n return \"#00E600\"; \/\/green\n\n case 3:\n return \"#00BEF0\"; \/\/deep sky blue\n\n case 4:\n return \"#F000FF\"; \/\/magenta\n\n case 5:\n return \"#F0C800\"; \/\/supernova\n\n case 6:\n return \"#000000\"; \/\/ black\n\n case 7:\n return \"#7051A7\"; \/\/purple\n\n case 8:\n return \"#FD8D3C\"; \/\/orange\n\n case 9:\n return \"#1B9E77\"; \/\/dark teal\n\n }\n\n return \"auto\";\n}\n\n\/\/static\nsize_t CPlotColors::getNumCopasiColors()\n{\n return 10;\n}\n\n\n\n\/\/QColor curveColours[6] = {QColor(255, 0, 0), QColor(0, 0, 255), QColor(0, 230, 0), QColor(0, 190, 240), QColor(240, 0, 255), QColor(240, 200, 0)} ; \/\/TODO\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * cam_SSAG.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Craig Stark.\r\n * Copyright (c) 2006, 2007, 2008, 2009, 2010 Craig Stark.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n#include \"phd.h\"\r\n\r\n#if defined (SSAG)\r\n\r\n#include \"camera.h\"\r\n#include \"time.h\"\r\n#include \"image_math.h\"\r\n\r\n#include <wx\/stdpaths.h>\r\n#include <wx\/textfile.h>\r\n\/\/wxTextFile *qglogfile;\r\n\r\n#include \"cam_SSAG.h\"\r\n\/\/ QHY CMOS guide camera version\r\n\/\/ Tom's driver\r\n\r\n#include <Setupapi.h>\r\n\r\n#define INITGUID\r\n#include <devpkey.h>\r\n\r\nextern int ushort_compare(const void * a, const void * b);\r\n\r\nstatic bool GetDiPropStr(HDEVINFO h, SP_DEVINFO_DATA *data, const DEVPROPKEY& key, WCHAR *buf, DWORD size)\r\n{\r\n DEVPROPTYPE proptype;\r\n return SetupDiGetDeviceProperty(h, data, &key, &proptype, (PBYTE)buf, size, &size, 0) &&\r\n proptype == DEVPROP_TYPE_STRING;\r\n}\r\n\r\nstatic unsigned int GetSSAGDriverVersion()\r\n{\r\n \/\/ check to see if the SSAG driver is v2 (\"1.2.0.0\") or v4 (\"3.0.0.0\")\r\n\r\n unsigned int driverVersion = 2; \/\/ assume v2\r\n\r\n HDEVINFO h = SetupDiGetClassDevs(NULL, L\"USB\", NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);\r\n if (h != INVALID_HANDLE_VALUE)\r\n {\r\n DWORD idx = 0;\r\n SP_DEVINFO_DATA data;\r\n memset(&data, 0, sizeof(data));\r\n data.cbSize = sizeof(data);\r\n\r\n while (SetupDiEnumDeviceInfo(h, idx, &data))\r\n {\r\n WCHAR buf[4096];\r\n\r\n if (GetDiPropStr(h, &data, DEVPKEY_Device_InstanceId, buf, sizeof(buf)) &&\r\n wcsncmp(buf, L\"USB\\\\VID_1856&PID_0012\\\\\", 22) == 0)\r\n {\r\n if (GetDiPropStr(h, &data, DEVPKEY_Device_DriverVersion, buf, sizeof(buf)))\r\n {\r\n Debug.AddLine(wxString::Format(\"SSAG driver version is %s\", wxString(buf)));\r\n int v;\r\n if (swscanf(buf, L\"%d\", &v) == 1 && v >= 3)\r\n {\r\n driverVersion = 4;\r\n }\r\n }\r\n break;\r\n }\r\n\r\n ++idx;\r\n }\r\n\r\n SetupDiDestroyDeviceInfoList(h);\r\n }\r\n\r\n return driverVersion;\r\n}\r\n\r\n\/\/ declare function pointers for imported functions\r\n\r\n#define F1(r,f,a1) typedef r (_stdcall *f##_t)(a1); static f##_t f;\r\n#define F2(r,f,a1,a2) typedef r (_stdcall *f##_t)(a1,a2); static f##_t f;\r\n#define F5(r,f,a1,a2,a3,a4,a5) typedef r (_stdcall *f##_t)(a1,a2,a3,a4,a5); static f##_t f;\r\n#include \"cameras\/_SSAGIF.h\"\r\n#undef F1\r\n#undef F2\r\n#undef F5\r\n\r\n\/\/ initialize the function pointers\r\n\r\nstatic bool InitProcs(HINSTANCE hinst)\r\n{\r\n bool ok = false;\r\n\r\n try\r\n {\r\n\r\n#define F(f,n) \\\r\n if ((f = (f##_t) GetProcAddress(hinst, n)) == NULL) \\\r\n throw ERROR_INFO(\"SSAGIF DLL missing \" n);\r\n#define F1(r,f,a1) F(f,#f)\r\n#define F2(r,f,a1,a2) F(f,#f)\r\n#define F5(r,f,a1,a2,a3,a4,a5) F(f,#f)\r\n#include \"cameras\/_SSAGIF.h\"\r\n#undef F1\r\n#undef F2\r\n#undef F5\r\n#undef F\r\n\r\n ok = true;\r\n }\r\n catch (const wxString& msg)\r\n {\r\n POSSIBLY_UNUSED(msg);\r\n }\r\n\r\n return ok;\r\n}\r\n\r\nstatic HINSTANCE s_dllinst;\r\n\r\n\/\/\r\n\/\/ load the SSAGv2 or SSAGv4 DLL based on the SSAG driver version and load the addresses of the imported functions\r\n\/\/\r\nstatic bool LoadSSAGIFDll()\r\n{\r\n bool ok = false;\r\n\r\n try\r\n {\r\n unsigned int driverVersion = GetSSAGDriverVersion();\r\n\r\n LPCWSTR libname;\r\n if (driverVersion == 2)\r\n libname = _T(\"SSAGIFv2.dll\");\r\n else if (driverVersion == 4)\r\n libname = _T(\"SSAGIFv4.dll\");\r\n else\r\n throw ERROR_INFO(\"unexpected SSAG driver version!\");\r\n\r\n wxASSERT(s_dllinst == NULL);\r\n s_dllinst = LoadLibrary(libname);\r\n if (s_dllinst == NULL)\r\n throw ERROR_INFO(\"SSAG LoadLibrary failed\");\r\n\r\n if (!InitProcs(s_dllinst))\r\n throw ERROR_INFO(\"SSAG failed to load required symbols\");\r\n\r\n ok = true;\r\n }\r\n catch (const wxString& msg)\r\n {\r\n POSSIBLY_UNUSED(msg);\r\n if (s_dllinst != NULL)\r\n {\r\n FreeLibrary(s_dllinst);\r\n s_dllinst = NULL;\r\n }\r\n }\r\n\r\n return ok;\r\n}\r\n\r\nstatic void UnloadSSAGIFDll()\r\n{\r\n if (s_dllinst != NULL)\r\n {\r\n FreeLibrary(s_dllinst);\r\n s_dllinst = NULL;\r\n }\r\n}\r\n\r\nCamera_SSAGClass::Camera_SSAGClass()\r\n{\r\n Connected = false;\r\n Name = _T(\"StarShoot Autoguider\");\r\n FullSize = wxSize(1280, 1024);\r\n m_hasGuideOutput = true;\r\n HasGainControl = true;\r\n PixelSize = 5.2;\r\n}\r\n\r\nbool Camera_SSAGClass::Connect()\r\n{\r\n \/\/ returns true on error\r\n\r\n if (!LoadSSAGIFDll())\r\n return true;\r\n\r\n if (!_SSAG_openUSB())\r\n {\r\n UnloadSSAGIFDll();\r\n return true;\r\n }\r\n\r\n _SSAG_SETBUFFERMODE(0);\r\n Connected = true;\r\n\r\n \/\/qglogfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + _T(\"PHD_QGuide_log.txt\"));\r\n \/\/qglogfile->AddLine(wxNow() + \": QGuide connected\"); \/\/qglogfile->Write();\r\n\r\n return false;\r\n}\r\n\r\nbool Camera_SSAGClass::ST4PulseGuideScope(int direction, int duration)\r\n{\r\n int reg = 0;\r\n int dur = duration \/ 10;\r\n\r\n \/\/qglogfile->AddLine(wxString::Format(\"Sending guide dur %d\",dur)); \/\/qglogfile->Write();\r\n\r\n if (dur >= 255) dur = 254; \/\/ Max guide pulse is 2.54s -- 255 keeps it on always\r\n\r\n \/\/ Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http:\/\/www.starlight-xpress.co.uk\/faq.htm\r\n switch (direction) {\r\n case WEST: reg = 0x80; break; \/\/ 0111 0000\r\n case NORTH: reg = 0x40; break; \/\/ 1011 0000\r\n case SOUTH: reg = 0x20; break; \/\/ 1101 0000\r\n case EAST: reg = 0x10; break; \/\/ 1110 0000\r\n default: return true; \/\/ bad direction passed in\r\n }\r\n _SSAG_GuideCommand(reg, dur);\r\n\r\n wxMilliSleep(duration + 10);\r\n\r\n \/\/qglogfile->AddLine(\"Done\"); \/\/qglogfile->Write();\r\n\r\n return false;\r\n}\r\n\r\nvoid Camera_SSAGClass::ClearGuidePort()\r\n{\r\n}\r\n\r\nvoid Camera_SSAGClass::InitCapture()\r\n{\r\n _SSAG_ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 \/ 100));\r\n _SSAG_SetNoiseReduction(0);\r\n}\r\n\r\nbool Camera_SSAGClass::Disconnect()\r\n{\r\n _SSAG_closeUSB();\r\n UnloadSSAGIFDll();\r\n Connected = false;\r\n \/\/qglogfile->AddLine(wxNow() + \": Disconnecting\"); \/\/qglogfile->Write(); \/\/qglogfile->Close();\r\n return false;\r\n}\r\n\r\nbool Camera_SSAGClass::Capture(int duration, usImage& img, wxRect subframe, bool recon)\r\n{\r\n \/\/ Only does full frames\r\n\r\n unsigned short *dptr;\r\n int xsize = FullSize.GetWidth();\r\n int ysize = FullSize.GetHeight();\r\n bool firstimg = true;\r\n\r\n \/\/qglogfile->AddLine(wxString::Format(\"Capturing dur %d\",duration)); \/\/qglogfile->Write();\r\n\r\n _SSAG_ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 \/ 100));\r\n\r\n if (img.NPixels != (xsize*ysize))\r\n {\r\n if (img.Init(xsize,ysize))\r\n {\r\n pFrame->Alert(_T(\"Memory allocation error during capture\"));\r\n Disconnect();\r\n return true;\r\n }\r\n }\r\n\r\n _SSAG_ThreadedExposure(duration, NULL);\r\n\r\n \/\/qglogfile->AddLine(\"Exposure programmed\"); \/\/qglogfile->Write();\r\n\r\n if (duration > 100) {\r\n wxMilliSleep(duration - 100);\r\n wxGetApp().Yield();\r\n }\r\n\r\n while (_SSAG_isExposing())\r\n wxMilliSleep(50);\r\n\r\n \/\/qglogfile->AddLine(\"Exposure done\"); \/\/qglogfile->Write();\r\n\r\n dptr = img.ImageData;\r\n _SSAG_GETBUFFER(dptr, img.NPixels * 2);\r\n\r\n if (recon) SubtractDark(img);\r\n\r\n \/\/qglogfile->AddLine(\"Image loaded\"); \/\/qglogfile->Write();\r\n\r\n \/\/ Do quick L recon to remove bayer array\r\n\/\/ QuickLRecon(img);\r\n\/\/ RemoveLines(img);\r\n\r\n return false;\r\n}\r\n\r\nvoid Camera_SSAGClass::RemoveLines(usImage& img)\r\n{\r\n int i, j, val;\r\n unsigned short data[21];\r\n unsigned short *ptr1, *ptr2;\r\n unsigned short med[1024];\r\n int offset;\r\n double mean;\r\n int h = img.Size.GetHeight();\r\n int w = img.Size.GetWidth();\r\n size_t sz = sizeof(unsigned short);\r\n mean = 0.0;\r\n\r\n for (i=0; i<h; i++) {\r\n ptr1 = data;\r\n ptr2 = img.ImageData + i*w;\r\n for (j=0; j<21; j++, ptr1++, ptr2++)\r\n *ptr1 = *ptr2;\r\n qsort(data,21,sz,ushort_compare);\r\n med[i] = data[10];\r\n mean = mean + (double) (med[i]);\r\n }\r\n mean = mean \/ (double) h;\r\n for (i=0; i<h; i++) {\r\n offset = (int) mean - (int) med[i];\r\n ptr2 = img.ImageData + i*w;\r\n for (j=0; j<w; j++, ptr2++) {\r\n val = (int) *ptr2 + offset;\r\n if (val < 0) val = 0;\r\n else if (val > 65535) val = 65535;\r\n *ptr2 = (unsigned short) val;\r\n }\r\n\r\n }\r\n}\r\n\r\n#endif\r\n<commit_msg>fix case in new SSAG driver detection code where some SSAG cameras were not being detected<commit_after>\/*\r\n * cam_SSAG.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Craig Stark.\r\n * Copyright (c) 2006, 2007, 2008, 2009, 2010 Craig Stark.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n#include \"phd.h\"\r\n\r\n#if defined (SSAG)\r\n\r\n#include \"camera.h\"\r\n#include \"time.h\"\r\n#include \"image_math.h\"\r\n\r\n#include <wx\/stdpaths.h>\r\n#include <wx\/textfile.h>\r\n\/\/wxTextFile *qglogfile;\r\n\r\n#include \"cam_SSAG.h\"\r\n\/\/ QHY CMOS guide camera version\r\n\/\/ Tom's driver\r\n\r\n#include <Setupapi.h>\r\n\r\n#define INITGUID\r\n#include <devpkey.h>\r\n\r\nextern int ushort_compare(const void * a, const void * b);\r\n\r\nstatic bool GetDiPropStr(HDEVINFO h, SP_DEVINFO_DATA *data, const DEVPROPKEY& key, WCHAR *buf, DWORD size)\r\n{\r\n DEVPROPTYPE proptype;\r\n return SetupDiGetDeviceProperty(h, data, &key, &proptype, (PBYTE)buf, size, &size, 0) &&\r\n proptype == DEVPROP_TYPE_STRING;\r\n}\r\n\r\nstatic unsigned int GetSSAGDriverVersion()\r\n{\r\n \/\/ check to see if the SSAG driver is v2 (\"1.2.0.0\") or v4 (\"3.0.0.0\")\r\n\r\n Debug.AddLine(\"Checking SSAG driver version\");\r\n\r\n bool found = false;\r\n unsigned int driverVersion = 2; \/\/ assume v2\r\n\r\n HDEVINFO h = SetupDiGetClassDevs(NULL, L\"USB\", NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);\r\n if (h != INVALID_HANDLE_VALUE)\r\n {\r\n DWORD idx = 0;\r\n SP_DEVINFO_DATA data;\r\n memset(&data, 0, sizeof(data));\r\n data.cbSize = sizeof(data);\r\n\r\n while (SetupDiEnumDeviceInfo(h, idx, &data))\r\n {\r\n WCHAR buf[4096];\r\n\r\n if (GetDiPropStr(h, &data, DEVPKEY_Device_InstanceId, buf, sizeof(buf)) &&\r\n (wcsncmp(buf, L\"USB\\\\VID_1856&PID_0012\\\\\", 22) == 0) ||\r\n (wcsncmp(buf, L\"USB\\\\VID_1856&PID_0011\\\\\", 22) == 0))\r\n {\r\n Debug.AddLine(wxString::Format(\"Found SSAG device %s\", buf));\r\n if (GetDiPropStr(h, &data, DEVPKEY_Device_DriverVersion, buf, sizeof(buf)))\r\n {\r\n Debug.AddLine(wxString::Format(\"SSAG driver version is %s\", wxString(buf)));\r\n int v;\r\n if (swscanf(buf, L\"%d\", &v) == 1 && v >= 3)\r\n {\r\n driverVersion = 4;\r\n }\r\n }\r\n found = true;\r\n break;\r\n }\r\n\r\n ++idx;\r\n }\r\n\r\n SetupDiDestroyDeviceInfoList(h);\r\n }\r\n\r\n if (!found)\r\n Debug.AddLine(\"No SSAG device was found\");\r\n\r\n return driverVersion;\r\n}\r\n\r\n\/\/ declare function pointers for imported functions\r\n\r\n#define F1(r,f,a1) typedef r (_stdcall *f##_t)(a1); static f##_t f;\r\n#define F2(r,f,a1,a2) typedef r (_stdcall *f##_t)(a1,a2); static f##_t f;\r\n#define F5(r,f,a1,a2,a3,a4,a5) typedef r (_stdcall *f##_t)(a1,a2,a3,a4,a5); static f##_t f;\r\n#include \"cameras\/_SSAGIF.h\"\r\n#undef F1\r\n#undef F2\r\n#undef F5\r\n\r\n\/\/ initialize the function pointers\r\n\r\nstatic bool InitProcs(HINSTANCE hinst)\r\n{\r\n bool ok = false;\r\n\r\n try\r\n {\r\n\r\n#define F(f,n) \\\r\n if ((f = (f##_t) GetProcAddress(hinst, n)) == NULL) \\\r\n throw ERROR_INFO(\"SSAGIF DLL missing \" n);\r\n#define F1(r,f,a1) F(f,#f)\r\n#define F2(r,f,a1,a2) F(f,#f)\r\n#define F5(r,f,a1,a2,a3,a4,a5) F(f,#f)\r\n#include \"cameras\/_SSAGIF.h\"\r\n#undef F1\r\n#undef F2\r\n#undef F5\r\n#undef F\r\n\r\n ok = true;\r\n }\r\n catch (const wxString& msg)\r\n {\r\n POSSIBLY_UNUSED(msg);\r\n }\r\n\r\n return ok;\r\n}\r\n\r\nstatic HINSTANCE s_dllinst;\r\n\r\n\/\/\r\n\/\/ load the SSAGv2 or SSAGv4 DLL based on the SSAG driver version and load the addresses of the imported functions\r\n\/\/\r\nstatic bool LoadSSAGIFDll()\r\n{\r\n bool ok = false;\r\n\r\n try\r\n {\r\n unsigned int driverVersion = GetSSAGDriverVersion();\r\n\r\n LPCWSTR libname;\r\n if (driverVersion == 2)\r\n libname = _T(\"SSAGIFv2.dll\");\r\n else if (driverVersion == 4)\r\n libname = _T(\"SSAGIFv4.dll\");\r\n else\r\n throw ERROR_INFO(\"unexpected SSAG driver version!\");\r\n\r\n wxASSERT(s_dllinst == NULL);\r\n Debug.AddLine(wxString::Format(\"Loading SSAG dll %s\", libname));\r\n s_dllinst = LoadLibrary(libname);\r\n if (s_dllinst == NULL)\r\n throw ERROR_INFO(\"SSAG LoadLibrary failed\");\r\n\r\n if (!InitProcs(s_dllinst))\r\n throw ERROR_INFO(\"SSAG failed to load required symbols\");\r\n\r\n ok = true;\r\n }\r\n catch (const wxString& msg)\r\n {\r\n POSSIBLY_UNUSED(msg);\r\n if (s_dllinst != NULL)\r\n {\r\n FreeLibrary(s_dllinst);\r\n s_dllinst = NULL;\r\n }\r\n }\r\n\r\n return ok;\r\n}\r\n\r\nstatic void UnloadSSAGIFDll()\r\n{\r\n if (s_dllinst != NULL)\r\n {\r\n Debug.AddLine(\"Unloading SSAG DLL\");\r\n FreeLibrary(s_dllinst);\r\n s_dllinst = NULL;\r\n }\r\n}\r\n\r\nCamera_SSAGClass::Camera_SSAGClass()\r\n{\r\n Connected = false;\r\n Name = _T(\"StarShoot Autoguider\");\r\n FullSize = wxSize(1280, 1024);\r\n m_hasGuideOutput = true;\r\n HasGainControl = true;\r\n PixelSize = 5.2;\r\n}\r\n\r\nbool Camera_SSAGClass::Connect()\r\n{\r\n \/\/ returns true on error\r\n\r\n if (!LoadSSAGIFDll())\r\n return true;\r\n\r\n if (!_SSAG_openUSB())\r\n {\r\n UnloadSSAGIFDll();\r\n return true;\r\n }\r\n\r\n _SSAG_SETBUFFERMODE(0);\r\n Connected = true;\r\n\r\n \/\/qglogfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + _T(\"PHD_QGuide_log.txt\"));\r\n \/\/qglogfile->AddLine(wxNow() + \": QGuide connected\"); \/\/qglogfile->Write();\r\n\r\n return false;\r\n}\r\n\r\nbool Camera_SSAGClass::ST4PulseGuideScope(int direction, int duration)\r\n{\r\n int reg = 0;\r\n int dur = duration \/ 10;\r\n\r\n \/\/qglogfile->AddLine(wxString::Format(\"Sending guide dur %d\",dur)); \/\/qglogfile->Write();\r\n\r\n if (dur >= 255) dur = 254; \/\/ Max guide pulse is 2.54s -- 255 keeps it on always\r\n\r\n \/\/ Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http:\/\/www.starlight-xpress.co.uk\/faq.htm\r\n switch (direction) {\r\n case WEST: reg = 0x80; break; \/\/ 0111 0000\r\n case NORTH: reg = 0x40; break; \/\/ 1011 0000\r\n case SOUTH: reg = 0x20; break; \/\/ 1101 0000\r\n case EAST: reg = 0x10; break; \/\/ 1110 0000\r\n default: return true; \/\/ bad direction passed in\r\n }\r\n _SSAG_GuideCommand(reg, dur);\r\n\r\n wxMilliSleep(duration + 10);\r\n\r\n \/\/qglogfile->AddLine(\"Done\"); \/\/qglogfile->Write();\r\n\r\n return false;\r\n}\r\n\r\nvoid Camera_SSAGClass::ClearGuidePort()\r\n{\r\n}\r\n\r\nvoid Camera_SSAGClass::InitCapture()\r\n{\r\n _SSAG_ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 \/ 100));\r\n _SSAG_SetNoiseReduction(0);\r\n}\r\n\r\nbool Camera_SSAGClass::Disconnect()\r\n{\r\n _SSAG_closeUSB();\r\n UnloadSSAGIFDll();\r\n Connected = false;\r\n \/\/qglogfile->AddLine(wxNow() + \": Disconnecting\"); \/\/qglogfile->Write(); \/\/qglogfile->Close();\r\n return false;\r\n}\r\n\r\nbool Camera_SSAGClass::Capture(int duration, usImage& img, wxRect subframe, bool recon)\r\n{\r\n \/\/ Only does full frames\r\n\r\n unsigned short *dptr;\r\n int xsize = FullSize.GetWidth();\r\n int ysize = FullSize.GetHeight();\r\n bool firstimg = true;\r\n\r\n \/\/qglogfile->AddLine(wxString::Format(\"Capturing dur %d\",duration)); \/\/qglogfile->Write();\r\n\r\n _SSAG_ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 \/ 100));\r\n\r\n if (img.NPixels != (xsize*ysize))\r\n {\r\n if (img.Init(xsize,ysize))\r\n {\r\n pFrame->Alert(_T(\"Memory allocation error during capture\"));\r\n Disconnect();\r\n return true;\r\n }\r\n }\r\n\r\n _SSAG_ThreadedExposure(duration, NULL);\r\n\r\n \/\/qglogfile->AddLine(\"Exposure programmed\"); \/\/qglogfile->Write();\r\n\r\n if (duration > 100) {\r\n wxMilliSleep(duration - 100);\r\n wxGetApp().Yield();\r\n }\r\n\r\n while (_SSAG_isExposing())\r\n wxMilliSleep(50);\r\n\r\n \/\/qglogfile->AddLine(\"Exposure done\"); \/\/qglogfile->Write();\r\n\r\n dptr = img.ImageData;\r\n _SSAG_GETBUFFER(dptr, img.NPixels * 2);\r\n\r\n if (recon) SubtractDark(img);\r\n\r\n \/\/qglogfile->AddLine(\"Image loaded\"); \/\/qglogfile->Write();\r\n\r\n \/\/ Do quick L recon to remove bayer array\r\n\/\/ QuickLRecon(img);\r\n\/\/ RemoveLines(img);\r\n\r\n return false;\r\n}\r\n\r\nvoid Camera_SSAGClass::RemoveLines(usImage& img)\r\n{\r\n int i, j, val;\r\n unsigned short data[21];\r\n unsigned short *ptr1, *ptr2;\r\n unsigned short med[1024];\r\n int offset;\r\n double mean;\r\n int h = img.Size.GetHeight();\r\n int w = img.Size.GetWidth();\r\n size_t sz = sizeof(unsigned short);\r\n mean = 0.0;\r\n\r\n for (i=0; i<h; i++) {\r\n ptr1 = data;\r\n ptr2 = img.ImageData + i*w;\r\n for (j=0; j<21; j++, ptr1++, ptr2++)\r\n *ptr1 = *ptr2;\r\n qsort(data,21,sz,ushort_compare);\r\n med[i] = data[10];\r\n mean = mean + (double) (med[i]);\r\n }\r\n mean = mean \/ (double) h;\r\n for (i=0; i<h; i++) {\r\n offset = (int) mean - (int) med[i];\r\n ptr2 = img.ImageData + i*w;\r\n for (j=0; j<w; j++, ptr2++) {\r\n val = (int) *ptr2 + offset;\r\n if (val < 0) val = 0;\r\n else if (val > 65535) val = 65535;\r\n *ptr2 = (unsigned short) val;\r\n }\r\n\r\n }\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include <sstream>\n#include <TestSuite\/Tester.h>\n\n#include \"Math\/Constants.h\"\n#include \"Math\/Matrix4.h\"\n#include \"Math\/Quaternion.h\"\n\nnamespace Magnum { namespace Math { namespace Test {\n\nclass QuaternionTest: public Corrade::TestSuite::Tester {\n public:\n explicit QuaternionTest();\n\n void construct();\n void addSubtract();\n void negated();\n void multiplyDivideScalar();\n void multiply();\n void dot();\n void length();\n void normalized();\n void conjugated();\n void inverted();\n void invertedNormalized();\n void rotation();\n void matrix();\n void lerp();\n\n void debug();\n};\n\ntypedef Math::Quaternion<float> Quaternion;\ntypedef Math::Vector3<float> Vector3;\n\nQuaternionTest::QuaternionTest() {\n addTests(&QuaternionTest::construct,\n &QuaternionTest::addSubtract,\n &QuaternionTest::negated,\n &QuaternionTest::multiplyDivideScalar,\n &QuaternionTest::multiply,\n &QuaternionTest::dot,\n &QuaternionTest::length,\n &QuaternionTest::normalized,\n &QuaternionTest::conjugated,\n &QuaternionTest::inverted,\n &QuaternionTest::invertedNormalized,\n &QuaternionTest::rotation,\n &QuaternionTest::matrix,\n &QuaternionTest::lerp,\n &QuaternionTest::debug);\n}\n\nvoid QuaternionTest::construct() {\n Quaternion q({1.0f, 2.0f, 3.0f}, -4.0f);\n CORRADE_COMPARE(q.vector(), Vector3(1.0f, 2.0f, 3.0f));\n CORRADE_COMPARE(q.scalar(), -4.0f);\n\n CORRADE_COMPARE(Quaternion(), Quaternion({0.0f, 0.0f, 0.0f}, {1.0f}));\n}\n\nvoid QuaternionTest::addSubtract() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-0.5f, 1.4f, 3.0f}, 12.0f);\n Quaternion c({0.5f, 4.4f, 1.0f}, 8.0f);\n\n CORRADE_COMPARE(a+b, c);\n CORRADE_COMPARE(c-b, a);\n}\n\nvoid QuaternionTest::negated() {\n CORRADE_COMPARE(-Quaternion({1.0f, 2.0f, -3.0f}, -4.0f), Quaternion({-1.0f, -2.0f, 3.0f}, 4.0f));\n}\n\nvoid QuaternionTest::multiplyDivideScalar() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-1.5f, -4.5f, 3.0f}, 6.0f);\n\n CORRADE_COMPARE(a*-1.5f, b);\n CORRADE_COMPARE(-1.5f*a, b);\n CORRADE_COMPARE(b\/-1.5f, a);\n\n CORRADE_COMPARE(2.0f\/a, Quaternion({2.0f, 0.666666f, -1.0f}, -0.5f));\n}\n\nvoid QuaternionTest::multiply() {\n CORRADE_COMPARE(Quaternion({-6.0f, -9.0f, 15.0f}, 0.5f)*Quaternion({2.0f, 3.0f, -5.0f}, 2.0f),\n Quaternion({-11.0f, -16.5f, 27.5f}, 115.0f));\n}\n\nvoid QuaternionTest::dot() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-0.5f, 1.5f, 3.0f}, 12.0f);\n\n CORRADE_COMPARE(Quaternion::dot(a, b), -50.0f);\n}\n\nvoid QuaternionTest::length() {\n CORRADE_COMPARE(Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).length(), std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::normalized() {\n Quaternion normalized = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).normalized();\n CORRADE_COMPARE(normalized.length(), 1.0f);\n CORRADE_COMPARE(normalized, Quaternion({1.0f, 3.0f, -2.0f}, -4.0f)\/std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::conjugated() {\n CORRADE_COMPARE(Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).conjugated(),\n Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f));\n}\n\nvoid QuaternionTest::inverted() {\n Quaternion a = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion inverted = a.inverted();\n\n CORRADE_COMPARE(a*inverted, Quaternion());\n CORRADE_COMPARE(inverted*a, Quaternion());\n CORRADE_COMPARE(inverted, Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f)\/30.0f);\n}\n\nvoid QuaternionTest::invertedNormalized() {\n Quaternion a = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f);\n\n std::ostringstream o;\n Corrade::Utility::Error::setOutput(&o);\n Quaternion notInverted = a.invertedNormalized();\n CORRADE_COMPARE(notInverted.vector(), Vector3());\n CORRADE_COMPARE(notInverted.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::invertedNormalized(): quaternion must be normalized\\n\");\n\n Quaternion aNormalized = a.normalized();\n Quaternion inverted = aNormalized.invertedNormalized();\n CORRADE_COMPARE(aNormalized*inverted, Quaternion());\n CORRADE_COMPARE(inverted*aNormalized.normalized(), Quaternion());\n CORRADE_COMPARE(inverted, Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f)\/std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::rotation() {\n float angle = deg(120.0f);\n Vector3 axis(1.0f\/Constants<float>::sqrt3());\n Quaternion q = Quaternion::fromRotation(angle, axis);\n CORRADE_COMPARE(q, Quaternion(Vector3(0.5f, 0.5f, 0.5f), 0.5f));\n CORRADE_COMPARE(q.rotationAngle(), angle);\n CORRADE_COMPARE(q.rotationAxis(), axis);\n CORRADE_COMPARE(q.rotationAxis().length(), 1.0f);\n\n \/* Verify negative angle *\/\n Quaternion q2 = Quaternion::fromRotation(deg(-120.0f), axis);\n CORRADE_COMPARE(q2, Quaternion(Vector3(-0.5f, -0.5f, -0.5f), 0.5f));\n CORRADE_COMPARE(q2.rotationAngle(), deg(120.0f));\n CORRADE_COMPARE(q2.rotationAxis(), -axis);\n}\n\nvoid QuaternionTest::matrix() {\n float angle = deg(37.0f);\n Vector3 axis(1.0f\/Constants<float>::sqrt3());\n Quaternion q = Quaternion::fromRotation(angle, axis);\n Matrix<3, float> expected = Matrix4<float>::rotation(angle, axis).rotationScaling();\n CORRADE_COMPARE(q.matrix(), expected);\n\n \/* Verify that negated quaternion gives the same rotation *\/\n CORRADE_COMPARE((-q).matrix(), expected);\n}\n\nvoid QuaternionTest::lerp() {\n Quaternion a = Quaternion::fromRotation(deg(15.0f), Vector3(1.0f\/Constants<float>::sqrt3()));\n Quaternion b = Quaternion::fromRotation(deg(23.0f), Vector3::xAxis());\n\n std::ostringstream o;\n Corrade::Utility::Error::setOutput(&o);\n\n Quaternion notLerpA = Quaternion::lerp(a*3.0f, b, 0.35f);\n CORRADE_COMPARE(notLerpA.vector(), Vector3());\n CORRADE_COMPARE(notLerpA.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::lerp(): quaternions must be normalized\\n\");\n\n o.str(\"\");\n Quaternion notLerpB = Quaternion::lerp(a, b*-3.0f, 0.35f);\n CORRADE_COMPARE(notLerpB.vector(), Vector3());\n CORRADE_COMPARE(notLerpB.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::lerp(): quaternions must be normalized\\n\");\n\n Quaternion lerp = Quaternion::lerp(a, b, 0.35f);\n CORRADE_COMPARE(lerp, Quaternion({0.119127f, 0.049134f, 0.049134f}, 0.990445f));\n}\n\nvoid QuaternionTest::debug() {\n std::ostringstream o;\n\n Corrade::Utility::Debug(&o) << Quaternion({1.0f, 2.0f, 3.0f}, -4.0f);\n CORRADE_COMPARE(o.str(), \"Quaternion({1, 2, 3}, -4)\\n\");\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Math::Test::QuaternionTest)\n<commit_msg>Math: test also parameterless Quaternion::dot().<commit_after>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include <sstream>\n#include <TestSuite\/Tester.h>\n\n#include \"Math\/Constants.h\"\n#include \"Math\/Matrix4.h\"\n#include \"Math\/Quaternion.h\"\n\nnamespace Magnum { namespace Math { namespace Test {\n\nclass QuaternionTest: public Corrade::TestSuite::Tester {\n public:\n explicit QuaternionTest();\n\n void construct();\n void addSubtract();\n void negated();\n void multiplyDivideScalar();\n void multiply();\n void dot();\n void dotSelf();\n void length();\n void normalized();\n void conjugated();\n void inverted();\n void invertedNormalized();\n void rotation();\n void matrix();\n void lerp();\n\n void debug();\n};\n\ntypedef Math::Quaternion<float> Quaternion;\ntypedef Math::Vector3<float> Vector3;\n\nQuaternionTest::QuaternionTest() {\n addTests(&QuaternionTest::construct,\n &QuaternionTest::addSubtract,\n &QuaternionTest::negated,\n &QuaternionTest::multiplyDivideScalar,\n &QuaternionTest::multiply,\n &QuaternionTest::dot,\n &QuaternionTest::dotSelf,\n &QuaternionTest::length,\n &QuaternionTest::normalized,\n &QuaternionTest::conjugated,\n &QuaternionTest::inverted,\n &QuaternionTest::invertedNormalized,\n &QuaternionTest::rotation,\n &QuaternionTest::matrix,\n &QuaternionTest::lerp,\n &QuaternionTest::debug);\n}\n\nvoid QuaternionTest::construct() {\n Quaternion q({1.0f, 2.0f, 3.0f}, -4.0f);\n CORRADE_COMPARE(q.vector(), Vector3(1.0f, 2.0f, 3.0f));\n CORRADE_COMPARE(q.scalar(), -4.0f);\n\n CORRADE_COMPARE(Quaternion(), Quaternion({0.0f, 0.0f, 0.0f}, {1.0f}));\n}\n\nvoid QuaternionTest::addSubtract() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-0.5f, 1.4f, 3.0f}, 12.0f);\n Quaternion c({0.5f, 4.4f, 1.0f}, 8.0f);\n\n CORRADE_COMPARE(a+b, c);\n CORRADE_COMPARE(c-b, a);\n}\n\nvoid QuaternionTest::negated() {\n CORRADE_COMPARE(-Quaternion({1.0f, 2.0f, -3.0f}, -4.0f), Quaternion({-1.0f, -2.0f, 3.0f}, 4.0f));\n}\n\nvoid QuaternionTest::multiplyDivideScalar() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-1.5f, -4.5f, 3.0f}, 6.0f);\n\n CORRADE_COMPARE(a*-1.5f, b);\n CORRADE_COMPARE(-1.5f*a, b);\n CORRADE_COMPARE(b\/-1.5f, a);\n\n CORRADE_COMPARE(2.0f\/a, Quaternion({2.0f, 0.666666f, -1.0f}, -0.5f));\n}\n\nvoid QuaternionTest::multiply() {\n CORRADE_COMPARE(Quaternion({-6.0f, -9.0f, 15.0f}, 0.5f)*Quaternion({2.0f, 3.0f, -5.0f}, 2.0f),\n Quaternion({-11.0f, -16.5f, 27.5f}, 115.0f));\n}\n\nvoid QuaternionTest::dot() {\n Quaternion a({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion b({-0.5f, 1.5f, 3.0f}, 12.0f);\n\n CORRADE_COMPARE(Quaternion::dot(a, b), -50.0f);\n}\n\nvoid QuaternionTest::dotSelf() {\n CORRADE_COMPARE(Quaternion({1.0f, 2.0f, -3.0f}, -4.0f).dot(), 30.0f);\n}\n\nvoid QuaternionTest::length() {\n CORRADE_COMPARE(Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).length(), std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::normalized() {\n Quaternion normalized = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).normalized();\n CORRADE_COMPARE(normalized.length(), 1.0f);\n CORRADE_COMPARE(normalized, Quaternion({1.0f, 3.0f, -2.0f}, -4.0f)\/std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::conjugated() {\n CORRADE_COMPARE(Quaternion({1.0f, 3.0f, -2.0f}, -4.0f).conjugated(),\n Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f));\n}\n\nvoid QuaternionTest::inverted() {\n Quaternion a = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f);\n Quaternion inverted = a.inverted();\n\n CORRADE_COMPARE(a*inverted, Quaternion());\n CORRADE_COMPARE(inverted*a, Quaternion());\n CORRADE_COMPARE(inverted, Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f)\/30.0f);\n}\n\nvoid QuaternionTest::invertedNormalized() {\n Quaternion a = Quaternion({1.0f, 3.0f, -2.0f}, -4.0f);\n\n std::ostringstream o;\n Corrade::Utility::Error::setOutput(&o);\n Quaternion notInverted = a.invertedNormalized();\n CORRADE_COMPARE(notInverted.vector(), Vector3());\n CORRADE_COMPARE(notInverted.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::invertedNormalized(): quaternion must be normalized\\n\");\n\n Quaternion aNormalized = a.normalized();\n Quaternion inverted = aNormalized.invertedNormalized();\n CORRADE_COMPARE(aNormalized*inverted, Quaternion());\n CORRADE_COMPARE(inverted*aNormalized.normalized(), Quaternion());\n CORRADE_COMPARE(inverted, Quaternion({-1.0f, -3.0f, 2.0f}, -4.0f)\/std::sqrt(30.0f));\n}\n\nvoid QuaternionTest::rotation() {\n float angle = deg(120.0f);\n Vector3 axis(1.0f\/Constants<float>::sqrt3());\n Quaternion q = Quaternion::fromRotation(angle, axis);\n CORRADE_COMPARE(q, Quaternion(Vector3(0.5f, 0.5f, 0.5f), 0.5f));\n CORRADE_COMPARE(q.rotationAngle(), angle);\n CORRADE_COMPARE(q.rotationAxis(), axis);\n CORRADE_COMPARE(q.rotationAxis().length(), 1.0f);\n\n \/* Verify negative angle *\/\n Quaternion q2 = Quaternion::fromRotation(deg(-120.0f), axis);\n CORRADE_COMPARE(q2, Quaternion(Vector3(-0.5f, -0.5f, -0.5f), 0.5f));\n CORRADE_COMPARE(q2.rotationAngle(), deg(120.0f));\n CORRADE_COMPARE(q2.rotationAxis(), -axis);\n}\n\nvoid QuaternionTest::matrix() {\n float angle = deg(37.0f);\n Vector3 axis(1.0f\/Constants<float>::sqrt3());\n Quaternion q = Quaternion::fromRotation(angle, axis);\n Matrix<3, float> expected = Matrix4<float>::rotation(angle, axis).rotationScaling();\n CORRADE_COMPARE(q.matrix(), expected);\n\n \/* Verify that negated quaternion gives the same rotation *\/\n CORRADE_COMPARE((-q).matrix(), expected);\n}\n\nvoid QuaternionTest::lerp() {\n Quaternion a = Quaternion::fromRotation(deg(15.0f), Vector3(1.0f\/Constants<float>::sqrt3()));\n Quaternion b = Quaternion::fromRotation(deg(23.0f), Vector3::xAxis());\n\n std::ostringstream o;\n Corrade::Utility::Error::setOutput(&o);\n\n Quaternion notLerpA = Quaternion::lerp(a*3.0f, b, 0.35f);\n CORRADE_COMPARE(notLerpA.vector(), Vector3());\n CORRADE_COMPARE(notLerpA.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::lerp(): quaternions must be normalized\\n\");\n\n o.str(\"\");\n Quaternion notLerpB = Quaternion::lerp(a, b*-3.0f, 0.35f);\n CORRADE_COMPARE(notLerpB.vector(), Vector3());\n CORRADE_COMPARE(notLerpB.scalar(), std::numeric_limits<float>::quiet_NaN());\n CORRADE_COMPARE(o.str(), \"Math::Quaternion::lerp(): quaternions must be normalized\\n\");\n\n Quaternion lerp = Quaternion::lerp(a, b, 0.35f);\n CORRADE_COMPARE(lerp, Quaternion({0.119127f, 0.049134f, 0.049134f}, 0.990445f));\n}\n\nvoid QuaternionTest::debug() {\n std::ostringstream o;\n\n Corrade::Utility::Debug(&o) << Quaternion({1.0f, 2.0f, 3.0f}, -4.0f);\n CORRADE_COMPARE(o.str(), \"Quaternion({1, 2, 3}, -4)\\n\");\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Math::Test::QuaternionTest)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Renderer\/RenderWindow.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/Thread.hpp>\n#include <Nazara\/Renderer\/Context.hpp>\n#include <Nazara\/Renderer\/OpenGL.hpp>\n#include <Nazara\/Renderer\/Renderer.hpp>\n#include <Nazara\/Renderer\/Texture.hpp>\n#include <stdexcept>\n#include <Nazara\/Renderer\/Debug.hpp>\n\nNzRenderWindow::NzRenderWindow(NzVideoMode mode, const NzString& title, nzUInt32 style, const NzContextParameters& parameters)\n{\n\tCreate(mode, title, style, parameters);\n\n\t#ifdef NAZARA_DEBUG\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Failed to create render window\");\n\t\tthrow std::runtime_error(\"Constructor failed\");\n\t}\n\t#endif\n}\n\nNzRenderWindow::NzRenderWindow(NzWindowHandle handle, const NzContextParameters& parameters)\n{\n\tCreate(handle, parameters);\n\n\t#ifdef NAZARA_DEBUG\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Failed to create render window\");\n\t\tthrow std::runtime_error(\"Constructor failed\");\n\t}\n\t#endif\n}\n\nNzRenderWindow::~NzRenderWindow()\n{\n\t\/\/ Nécessaire si NzWindow::Destroy est appelé par son destructeur\n\tOnWindowDestroy();\n}\n\nbool NzRenderWindow::CopyToImage(NzImage* image) const\n{\n\t#if NAZARA_RENDERER_SAFE\n\tif (!m_context)\n\t{\n\t\tNazaraError(\"Window has not been created\");\n\t\treturn false;\n\t}\n\n\tif (!image)\n\t{\n\t\tNazaraError(\"Image must be valid\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tconst NzContext* currentContext = NzContext::GetCurrent();\n\tif (m_context != currentContext)\n\t{\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tNzVector2ui size = GetSize();\n\n\tif (!image->Create(nzImageType_2D, nzPixelFormat_RGBA8, size.x, size.y, 1, 1))\n\t{\n\t\tNazaraError(\"Failed to create image\");\n\t\treturn false;\n\t}\n\n\tnzUInt8* pixels = image->GetPixels();\n\tglReadPixels(0, 0, size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, pixels);\n\n\timage->FlipVertically();\n\n\tif (m_context != currentContext)\n\t{\n\t\tif (currentContext)\n\t\t{\n\t\t\tif (!currentContext->SetActive(true))\n\t\t\t\tNazaraWarning(\"Failed to reset current context\");\n\t\t}\n\t\telse\n\t\t\tm_context->SetActive(false);\n\t}\n\n\treturn true;\n}\n\nbool NzRenderWindow::CopyToTexture(NzTexture* texture) const\n{\n\t#if NAZARA_RENDERER_SAFE\n\tif (!m_context)\n\t{\n\t\tNazaraError(\"Window has not been created\");\n\t\treturn false;\n\t}\n\n\tif (!texture)\n\t{\n\t\tNazaraError(\"Texture must be valid\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tconst NzContext* currentContext = NzContext::GetCurrent();\n\tif (m_context != currentContext)\n\t{\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tNzVector2ui size = GetSize();\n\n\tif (!texture->Create(nzImageType_2D, nzPixelFormat_RGBA8, size.x, size.y, 1, 1))\n\t{\n\t\tNazaraError(\"Failed to create texture\");\n\t\treturn false;\n\t}\n\n\tglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, size.x, size.y);\n\n\tif (m_context != currentContext)\n\t{\n\t\tif (currentContext)\n\t\t{\n\t\t\tif (!currentContext->SetActive(true))\n\t\t\t\tNazaraWarning(\"Failed to reset current context\");\n\t\t}\n\t\telse\n\t\t\tm_context->SetActive(false);\n\t}\n\n\treturn true;\n}\n\nbool NzRenderWindow::Create(NzVideoMode mode, const NzString& title, nzUInt32 style, const NzContextParameters& parameters)\n{\n m_parameters = parameters;\n return NzWindow::Create(mode, title, style);\n}\n\nbool NzRenderWindow::Create(NzWindowHandle handle, const NzContextParameters& parameters)\n{\n m_parameters = parameters;\n return NzWindow::Create(handle);\n}\n\nvoid NzRenderWindow::Display()\n{\n\tif (m_framerateLimit > 0)\n\t{\n\t\tint remainingTime = 1000\/static_cast<int>(m_framerateLimit) - static_cast<int>(m_clock.GetMilliseconds());\n\t\tif (remainingTime > 0)\n\t\t\tNzThread::Sleep(remainingTime);\n\n\t\tm_clock.Restart();\n\t}\n\n\tif (m_context && m_parameters.doubleBuffered)\n\t\tm_context->SwapBuffers();\n}\n\nvoid NzRenderWindow::EnableVerticalSync(bool enabled)\n{\n if (m_context)\n {\n\t\t#if defined(NAZARA_PLATFORM_WINDOWS)\n if (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn;\n\t\t}\n\n if (wglSwapInterval)\n wglSwapInterval(enabled ? 1 : 0);\n else\n\t\t#elif defined(NAZARA_PLATFORM_LINUX)\n if (!m_context->SetActive(true))\n {\n NazaraError(\"Failed to activate context\");\n return;\n }\n\n if (glXSwapInterval)\n glXSwapInterval(enabled ? 1 : 0);\n else\n\t\t#else\n\t\t\t#error Vertical Sync is not supported on this platform\n\t\t#endif\n NazaraError(\"Vertical Sync is not supported on this platform\");\n }\n else\n NazaraError(\"No context\");\n}\n\nunsigned int NzRenderWindow::GetHeight() const\n{\n\treturn NzWindow::GetHeight();\n}\n\nNzRenderTargetParameters NzRenderWindow::GetParameters() const\n{\n\tif (m_context)\n\t{\n\t\tconst NzContextParameters& parameters = m_context->GetParameters();\n\t\treturn NzRenderTargetParameters(parameters.antialiasingLevel, parameters.depthBits, parameters.stencilBits);\n\t}\n\telse\n\t{\n\t\tNazaraError(\"Window not created\/context not initialized\");\n\t\treturn NzRenderTargetParameters();\n\t}\n}\n\nunsigned int NzRenderWindow::GetWidth() const\n{\n\treturn NzWindow::GetWidth();\n}\n\nbool NzRenderWindow::IsRenderable() const\n{\n\treturn m_impl != nullptr; \/\/ Si m_impl est valide, alors m_context l'est aussi\n}\n\nbool NzRenderWindow::IsValid() const\n{\n\treturn m_impl != nullptr;\n}\n\nvoid NzRenderWindow::SetFramerateLimit(unsigned int limit)\n{\n\tm_framerateLimit = limit;\n}\n\nNzContextParameters NzRenderWindow::GetContextParameters() const\n{\n\tif (m_context)\n\t\treturn m_context->GetParameters();\n\telse\n\t{\n\t\tNazaraError(\"Window not created\/context not initialized\");\n\t\treturn NzContextParameters();\n\t}\n}\n\nbool NzRenderWindow::HasContext() const\n{\n\treturn true;\n}\n\nbool NzRenderWindow::Activate() const\n{\n\tif (m_context->SetActive(true))\n\t{\n\t\tglDrawBuffer((m_parameters.doubleBuffered) ? GL_BACK : GL_FRONT);\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tNazaraError(\"Failed to activate window's context\");\n\t\treturn false;\n\t}\n}\n\nvoid NzRenderWindow::EnsureTargetUpdated() const\n{\n\t\/\/ Rien à faire\n}\n\nbool NzRenderWindow::OnWindowCreated()\n{\n\tm_parameters.doubleBuffered = true;\n m_parameters.window = GetHandle();\n\n m_context = new NzContext;\n if (!m_context->Create(m_parameters))\n {\n NazaraError(\"Failed not create context\");\n delete m_context;\n\n return false;\n }\n\n\tif (!SetActive(true)) \/\/ Les fenêtres s'activent à la création\n\t\tNazaraWarning(\"Failed to activate window\");\n\n EnableVerticalSync(false);\n\n\tNzVector2ui size = GetSize();\n\n\t\/\/ Le scissorBox\/viewport (à la création) est de la taille de la fenêtre\n\t\/\/ https:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glGet.xml\n\tNzOpenGL::SetScissorBox(NzRecti(0, 0, size.x, size.y));\n\tNzOpenGL::SetViewport(NzRecti(0, 0, size.x, size.y));\n\n\tNotifyParametersChange();\n\tNotifySizeChange();\n\n\tm_clock.Restart();\n\n return true;\n}\n\nvoid NzRenderWindow::OnWindowDestroy()\n{\n\tif (m_context)\n\t{\n\t\tif (IsActive())\n\t\t\tNzRenderer::SetTarget(nullptr);\n\n\t\tdelete m_context;\n\t\tm_context = nullptr;\n\t}\n}\n\nvoid NzRenderWindow::OnWindowResized()\n{\n\tNotifySizeChange();\n}\n\n<commit_msg>Fixed whitespaces<commit_after>\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Renderer\/RenderWindow.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/Thread.hpp>\n#include <Nazara\/Renderer\/Context.hpp>\n#include <Nazara\/Renderer\/OpenGL.hpp>\n#include <Nazara\/Renderer\/Renderer.hpp>\n#include <Nazara\/Renderer\/Texture.hpp>\n#include <stdexcept>\n#include <Nazara\/Renderer\/Debug.hpp>\n\nNzRenderWindow::NzRenderWindow(NzVideoMode mode, const NzString& title, nzUInt32 style, const NzContextParameters& parameters)\n{\n\tCreate(mode, title, style, parameters);\n\n\t#ifdef NAZARA_DEBUG\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Failed to create render window\");\n\t\tthrow std::runtime_error(\"Constructor failed\");\n\t}\n\t#endif\n}\n\nNzRenderWindow::NzRenderWindow(NzWindowHandle handle, const NzContextParameters& parameters)\n{\n\tCreate(handle, parameters);\n\n\t#ifdef NAZARA_DEBUG\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Failed to create render window\");\n\t\tthrow std::runtime_error(\"Constructor failed\");\n\t}\n\t#endif\n}\n\nNzRenderWindow::~NzRenderWindow()\n{\n\t\/\/ Nécessaire si NzWindow::Destroy est appelé par son destructeur\n\tOnWindowDestroy();\n}\n\nbool NzRenderWindow::CopyToImage(NzImage* image) const\n{\n\t#if NAZARA_RENDERER_SAFE\n\tif (!m_context)\n\t{\n\t\tNazaraError(\"Window has not been created\");\n\t\treturn false;\n\t}\n\n\tif (!image)\n\t{\n\t\tNazaraError(\"Image must be valid\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tconst NzContext* currentContext = NzContext::GetCurrent();\n\tif (m_context != currentContext)\n\t{\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tNzVector2ui size = GetSize();\n\n\tif (!image->Create(nzImageType_2D, nzPixelFormat_RGBA8, size.x, size.y, 1, 1))\n\t{\n\t\tNazaraError(\"Failed to create image\");\n\t\treturn false;\n\t}\n\n\tnzUInt8* pixels = image->GetPixels();\n\tglReadPixels(0, 0, size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, pixels);\n\n\timage->FlipVertically();\n\n\tif (m_context != currentContext)\n\t{\n\t\tif (currentContext)\n\t\t{\n\t\t\tif (!currentContext->SetActive(true))\n\t\t\t\tNazaraWarning(\"Failed to reset current context\");\n\t\t}\n\t\telse\n\t\t\tm_context->SetActive(false);\n\t}\n\n\treturn true;\n}\n\nbool NzRenderWindow::CopyToTexture(NzTexture* texture) const\n{\n\t#if NAZARA_RENDERER_SAFE\n\tif (!m_context)\n\t{\n\t\tNazaraError(\"Window has not been created\");\n\t\treturn false;\n\t}\n\n\tif (!texture)\n\t{\n\t\tNazaraError(\"Texture must be valid\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tconst NzContext* currentContext = NzContext::GetCurrent();\n\tif (m_context != currentContext)\n\t{\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tNzVector2ui size = GetSize();\n\n\tif (!texture->Create(nzImageType_2D, nzPixelFormat_RGBA8, size.x, size.y, 1, 1))\n\t{\n\t\tNazaraError(\"Failed to create texture\");\n\t\treturn false;\n\t}\n\n\tglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, size.x, size.y);\n\n\tif (m_context != currentContext)\n\t{\n\t\tif (currentContext)\n\t\t{\n\t\t\tif (!currentContext->SetActive(true))\n\t\t\t\tNazaraWarning(\"Failed to reset current context\");\n\t\t}\n\t\telse\n\t\t\tm_context->SetActive(false);\n\t}\n\n\treturn true;\n}\n\nbool NzRenderWindow::Create(NzVideoMode mode, const NzString& title, nzUInt32 style, const NzContextParameters& parameters)\n{\n m_parameters = parameters;\n return NzWindow::Create(mode, title, style);\n}\n\nbool NzRenderWindow::Create(NzWindowHandle handle, const NzContextParameters& parameters)\n{\n m_parameters = parameters;\n return NzWindow::Create(handle);\n}\n\nvoid NzRenderWindow::Display()\n{\n\tif (m_framerateLimit > 0)\n\t{\n\t\tint remainingTime = 1000\/static_cast<int>(m_framerateLimit) - static_cast<int>(m_clock.GetMilliseconds());\n\t\tif (remainingTime > 0)\n\t\t\tNzThread::Sleep(remainingTime);\n\n\t\tm_clock.Restart();\n\t}\n\n\tif (m_context && m_parameters.doubleBuffered)\n\t\tm_context->SwapBuffers();\n}\n\nvoid NzRenderWindow::EnableVerticalSync(bool enabled)\n{\n\tif (m_context)\n\t{\n\t\t#if defined(NAZARA_PLATFORM_WINDOWS)\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (wglSwapInterval)\n\t\t\twglSwapInterval(enabled ? 1 : 0);\n\t\telse\n\t\t#elif defined(NAZARA_PLATFORM_LINUX)\n\t\tif (!m_context->SetActive(true))\n\t\t{\n\t\t\tNazaraError(\"Failed to activate context\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (glXSwapInterval)\n\t\t\tglXSwapInterval(enabled ? 1 : 0);\n\t\telse\n\t\t#else\n\t\t\t#error Vertical Sync is not supported on this platform\n\t\t#endif\n\t\t\tNazaraError(\"Vertical Sync is not supported on this platform\");\n\t}\n\telse\n\t\tNazaraError(\"No context\");\n}\n\nunsigned int NzRenderWindow::GetHeight() const\n{\n\treturn NzWindow::GetHeight();\n}\n\nNzRenderTargetParameters NzRenderWindow::GetParameters() const\n{\n\tif (m_context)\n\t{\n\t\tconst NzContextParameters& parameters = m_context->GetParameters();\n\t\treturn NzRenderTargetParameters(parameters.antialiasingLevel, parameters.depthBits, parameters.stencilBits);\n\t}\n\telse\n\t{\n\t\tNazaraError(\"Window not created\/context not initialized\");\n\t\treturn NzRenderTargetParameters();\n\t}\n}\n\nunsigned int NzRenderWindow::GetWidth() const\n{\n\treturn NzWindow::GetWidth();\n}\n\nbool NzRenderWindow::IsRenderable() const\n{\n\treturn m_impl != nullptr; \/\/ Si m_impl est valide, alors m_context l'est aussi\n}\n\nbool NzRenderWindow::IsValid() const\n{\n\treturn m_impl != nullptr;\n}\n\nvoid NzRenderWindow::SetFramerateLimit(unsigned int limit)\n{\n\tm_framerateLimit = limit;\n}\n\nNzContextParameters NzRenderWindow::GetContextParameters() const\n{\n\tif (m_context)\n\t\treturn m_context->GetParameters();\n\telse\n\t{\n\t\tNazaraError(\"Window not created\/context not initialized\");\n\t\treturn NzContextParameters();\n\t}\n}\n\nbool NzRenderWindow::HasContext() const\n{\n\treturn true;\n}\n\nbool NzRenderWindow::Activate() const\n{\n\tif (m_context->SetActive(true))\n\t{\n\t\tglDrawBuffer((m_parameters.doubleBuffered) ? GL_BACK : GL_FRONT);\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tNazaraError(\"Failed to activate window's context\");\n\t\treturn false;\n\t}\n}\n\nvoid NzRenderWindow::EnsureTargetUpdated() const\n{\n\t\/\/ Rien à faire\n}\n\nbool NzRenderWindow::OnWindowCreated()\n{\n\tm_parameters.doubleBuffered = true;\n m_parameters.window = GetHandle();\n\n m_context = new NzContext;\n if (!m_context->Create(m_parameters))\n {\n NazaraError(\"Failed not create context\");\n delete m_context;\n\n return false;\n }\n\n\tif (!SetActive(true)) \/\/ Les fenêtres s'activent à la création\n\t\tNazaraWarning(\"Failed to activate window\");\n\n EnableVerticalSync(false);\n\n\tNzVector2ui size = GetSize();\n\n\t\/\/ Le scissorBox\/viewport (à la création) est de la taille de la fenêtre\n\t\/\/ https:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glGet.xml\n\tNzOpenGL::SetScissorBox(NzRecti(0, 0, size.x, size.y));\n\tNzOpenGL::SetViewport(NzRecti(0, 0, size.x, size.y));\n\n\tNotifyParametersChange();\n\tNotifySizeChange();\n\n\tm_clock.Restart();\n\n return true;\n}\n\nvoid NzRenderWindow::OnWindowDestroy()\n{\n\tif (m_context)\n\t{\n\t\tif (IsActive())\n\t\t\tNzRenderer::SetTarget(nullptr);\n\n\t\tdelete m_context;\n\t\tm_context = nullptr;\n\t}\n}\n\nvoid NzRenderWindow::OnWindowResized()\n{\n\tNotifySizeChange();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ This file contains the WebRTC suppressions for ThreadSanitizer.\n\/\/ Please refer to\n\/\/ http:\/\/dev.chromium.org\/developers\/testing\/threadsanitizer-tsan-v2\n\/\/ for more info.\n\n#if defined(THREAD_SANITIZER)\n\n\/\/ Please make sure the code below declares a single string variable\n\/\/ kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.\n\/\/ See http:\/\/dev.chromium.org\/developers\/testing\/threadsanitizer-tsan-v2\n\/\/ for the instructions on writing suppressions.\nchar kTSanDefaultSuppressions[] =\n\n\/\/ WebRTC specific suppressions.\n\n\/\/ False positive in system wrappers.\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=300\n\"race:webrtc\/system_wrappers\/source\/thread_posix.cc\\n\"\n\n\/\/ Audio processing\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2521 for details.\n\"race:webrtc\/modules\/audio_processing\/aec\/aec_core.c\\n\"\n\"race:webrtc\/modules\/audio_processing\/aec\/aec_rdft.c\\n\"\n\n\/\/ libjingle_p2p_unittest\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2079\n\"race:webrtc\/base\/messagequeue.cc\\n\"\n\"race:webrtc\/base\/testclient.cc\\n\"\n\"race:webrtc\/base\/virtualsocketserver.cc\\n\"\n\"race:talk\/base\/messagequeue.cc\\n\"\n\"race:talk\/base\/testclient.cc\\n\"\n\"race:talk\/base\/virtualsocketserver.cc\\n\"\n\"race:talk\/p2p\/base\/stunserver_unittest.cc\\n\"\n\n\/\/ libjingle_unittest\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2080\n\"race:webrtc\/base\/logging.cc\\n\"\n\"race:webrtc\/base\/sharedexclusivelock_unittest.cc\\n\"\n\"race:webrtc\/base\/signalthread_unittest.cc\\n\"\n\"race:webrtc\/base\/thread.cc\\n\"\n\"race:talk\/base\/logging.cc\\n\"\n\"race:talk\/base\/sharedexclusivelock_unittest.cc\\n\"\n\"race:talk\/base\/signalthread_unittest.cc\\n\"\n\"race:talk\/base\/thread.cc\\n\"\n\n\/\/ third_party\/usrsctp\n\/\/ TODO(jiayl): https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3492\n\"race:third_party\/usrsctp\/usrsctplib\/user_sctp_timer_iterate.c\\n\"\n\n\/\/ Potential deadlocks detected after roll in r6516.\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3509\n\"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\\n\"\n\"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\\n\"\n\"deadlock:talk_base::AsyncResolver::~AsyncResolver\\n\"\n\"deadlock:webrtc::ProcessThreadImpl::RegisterModule\\n\"\n\"deadlock:webrtc::RTCPReceiver::SetSsrcs\\n\"\n\"deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\\n\"\n\"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\\n\"\n\"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\\n\"\n\"deadlock:webrtc::VideoSendStreamTest_SuspendBelowMinBitrate_Test::TestBody\\n\"\n\"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\\n\"\n\"deadlock:webrtc::ViEChannel::StartSend\\n\"\n\"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\\n\"\n\"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\\n\"\n\"deadlock:webrtc::ViESender::RegisterSendTransport\\n\"\n\n\/\/ From Chromium's tsan_suppressions.cc file.\n\n\/\/ False positives in libglib.so. Since we don't instrument them, we cannot\n\/\/ reason about the synchronization in them.\n\"race:libglib*.so\\n\"\n\n\/\/ Races in libevent, http:\/\/crbug.com\/23244.\n\"race:libevent\/event.c\\n\"\n\n\/\/ http:\/\/crbug.com\/84094.\n\"race:sqlite3StatusSet\\n\"\n\"race:pcache1EnforceMaxPage\\n\"\n\"race:pcache1AllocPage\\n\"\n\n\/\/ http:\/\/crbug.com\/157586\n\"race:third_party\/libvpx\/source\/libvpx\/vp8\/decoder\/threading.c\\n\"\n\n\/\/ http:\/\/crbug.com\/158922\n\"race:third_party\/libvpx\/source\/libvpx\/vp8\/encoder\/*\\n\"\n\n\/\/ http:\/\/crbug.com\/223352\n\"race:uprv_malloc_46\\n\"\n\"race:uprv_realloc_46\\n\"\n\n\/\/ http:\/\/crbug.com\/244385\n\"race:unixTempFileDir\\n\"\n\n\/\/ http:\/\/crbug.com\/244774\n\"race:webrtc::RTPReceiver::ProcessBitrate\\n\"\n\"race:webrtc::RTPSender::ProcessBitrate\\n\"\n\"race:webrtc::VideoCodingModuleImpl::Decode\\n\"\n\"race:webrtc::RTPSender::SendOutgoingData\\n\"\n\"race:webrtc::VP8EncoderImpl::GetEncodedPartitions\\n\"\n\"race:webrtc::VP8EncoderImpl::Encode\\n\"\n\"race:webrtc::ViEEncoder::DeliverFrame\\n\"\n\"race:webrtc::vcm::VideoReceiver::Decode\\n\"\n\"race:webrtc::VCMReceiver::FrameForDecoding\\n\"\n\"race:*trace_event_unique_catstatic*\\n\"\n\n\/\/ http:\/\/crbug.com\/244856\n\"race:AutoPulseLock\\n\"\n\n\/\/ http:\/\/crbug.com\/246968\n\"race:webrtc::VideoCodingModuleImpl::RegisterPacketRequestCallback\\n\"\n\n\/\/ http:\/\/crbug.com\/246970\n\"race:webrtc::EventPosix::StartTimer\\n\"\n\n\/\/ http:\/\/crbug.com\/258479\n\"race:SamplingStateScope\\n\"\n\"race:g_trace_state\\n\"\n\n\/\/ http:\/\/crbug.com\/270037\n\"race:gLibCleanupFunctions\\n\"\n\n\/\/ http:\/\/crbug.com\/272987\n\"race:webrtc::MediaStreamTrack<webrtc::AudioTrackInterface>::set_enabled\\n\"\n\n\/\/ http:\/\/crbug.com\/345245\n\"race:jingle_glue::JingleThreadWrapper::~JingleThreadWrapper\\n\"\n\"race:webrtc::voe::Channel::UpdatePacketDelay\\n\"\n\"race:webrtc::voe::Channel::GetDelayEstimate\\n\"\n\"race:webrtc::VCMCodecDataBase::DeregisterReceiveCodec\\n\"\n\"race:webrtc::GainControlImpl::set_stream_analog_level\\n\"\n\n\/\/ http:\/\/crbug.com\/347538\n\"race:sctp_timer_start\\n\"\n\n\/\/ http:\/\/crbug.com\/347548\n\"race:cricket::WebRtcVideoMediaChannel::MaybeResetVieSendCodec\\n\"\n\"race:cricket::WebRtcVideoMediaChannel::SetSendCodec\\n\"\n\n\/\/ http:\/\/crbug.com\/348511\n\"race:webrtc::acm1::AudioCodingModuleImpl::PlayoutData10Ms\\n\"\n\n\/\/ http:\/\/crbug.com\/348982\n\"race:cricket::P2PTransportChannel::OnConnectionDestroyed\\n\"\n\"race:cricket::P2PTransportChannel::AddConnection\\n\"\n\n\/\/ http:\/\/crbug.com\/348984\n\"race:sctp_express_handle_sack\\n\"\n\n\/\/ http:\/\/crbug.com\/350982\n\"race:libvpx\/vp9\/decoder\/vp9_thread.c\\n\"\n\n\/\/ http:\/\/crbug.com\/372807\n\"deadlock:net::X509Certificate::CreateCertificateListFromBytes\\n\"\n\"deadlock:net::X509Certificate::CreateFromBytes\\n\"\n\"deadlock:net::SSLClientSocketNSS::Core::DoHandshakeLoop\\n\"\n\n\/\/ False positive in libc's tzset_internal, http:\/\/crbug.com\/379738.\n\"race:tzset_internal\\n\"\n\n\/\/ http:\/\/crbug.com\/380554\n\"deadlock:g_type_add_interface_static\\n\"\n\n\/\/ End of suppressions.\n; \/\/ Please keep this semicolon.\n\n#endif \/\/ THREAD_SANITIZER\n<commit_msg>Tight data race suppressions around thread_posix.<commit_after>\/*\n * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/ This file contains the WebRTC suppressions for ThreadSanitizer.\n\/\/ Please refer to\n\/\/ http:\/\/dev.chromium.org\/developers\/testing\/threadsanitizer-tsan-v2\n\/\/ for more info.\n\n#if defined(THREAD_SANITIZER)\n\n\/\/ Please make sure the code below declares a single string variable\n\/\/ kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.\n\/\/ See http:\/\/dev.chromium.org\/developers\/testing\/threadsanitizer-tsan-v2\n\/\/ for the instructions on writing suppressions.\nchar kTSanDefaultSuppressions[] =\n\n\/\/ WebRTC specific suppressions.\n\n\/\/ Usage of trace callback and trace level is racy in libjingle_media_unittests.\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3372\n\"race:webrtc::TraceImpl::WriteToFile\\n\"\n\"race:webrtc::VideoEngine::SetTraceFilter\\n\"\n\"race:webrtc::VoiceEngine::SetTraceFilter\\n\"\n\n\/\/ Audio processing\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2521 for details.\n\"race:webrtc\/modules\/audio_processing\/aec\/aec_core.c\\n\"\n\"race:webrtc\/modules\/audio_processing\/aec\/aec_rdft.c\\n\"\n\n\/\/ libjingle_p2p_unittest\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2079\n\"race:webrtc\/base\/messagequeue.cc\\n\"\n\"race:webrtc\/base\/testclient.cc\\n\"\n\"race:webrtc\/base\/virtualsocketserver.cc\\n\"\n\"race:talk\/base\/messagequeue.cc\\n\"\n\"race:talk\/base\/testclient.cc\\n\"\n\"race:talk\/base\/virtualsocketserver.cc\\n\"\n\"race:talk\/p2p\/base\/stunserver_unittest.cc\\n\"\n\n\/\/ libjingle_unittest\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2080\n\"race:webrtc\/base\/logging.cc\\n\"\n\"race:webrtc\/base\/sharedexclusivelock_unittest.cc\\n\"\n\"race:webrtc\/base\/signalthread_unittest.cc\\n\"\n\"race:webrtc\/base\/thread.cc\\n\"\n\"race:talk\/base\/logging.cc\\n\"\n\"race:talk\/base\/sharedexclusivelock_unittest.cc\\n\"\n\"race:talk\/base\/signalthread_unittest.cc\\n\"\n\"race:talk\/base\/thread.cc\\n\"\n\n\/\/ third_party\/usrsctp\n\/\/ TODO(jiayl): https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3492\n\"race:third_party\/usrsctp\/usrsctplib\/user_sctp_timer_iterate.c\\n\"\n\n\/\/ Potential deadlocks detected after roll in r6516.\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3509\n\"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\\n\"\n\"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\\n\"\n\"deadlock:talk_base::AsyncResolver::~AsyncResolver\\n\"\n\"deadlock:webrtc::ProcessThreadImpl::RegisterModule\\n\"\n\"deadlock:webrtc::RTCPReceiver::SetSsrcs\\n\"\n\"deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\\n\"\n\"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\\n\"\n\"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\\n\"\n\"deadlock:webrtc::VideoSendStreamTest_SuspendBelowMinBitrate_Test::TestBody\\n\"\n\"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\\n\"\n\"deadlock:webrtc::ViEChannel::StartSend\\n\"\n\"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\\n\"\n\"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\\n\"\n\"deadlock:webrtc::ViESender::RegisterSendTransport\\n\"\n\n\/\/ From Chromium's tsan_suppressions.cc file.\n\n\/\/ False positives in libglib.so. Since we don't instrument them, we cannot\n\/\/ reason about the synchronization in them.\n\"race:libglib*.so\\n\"\n\n\/\/ Races in libevent, http:\/\/crbug.com\/23244.\n\"race:libevent\/event.c\\n\"\n\n\/\/ http:\/\/crbug.com\/84094.\n\"race:sqlite3StatusSet\\n\"\n\"race:pcache1EnforceMaxPage\\n\"\n\"race:pcache1AllocPage\\n\"\n\n\/\/ http:\/\/crbug.com\/157586\n\"race:third_party\/libvpx\/source\/libvpx\/vp8\/decoder\/threading.c\\n\"\n\n\/\/ http:\/\/crbug.com\/158922\n\"race:third_party\/libvpx\/source\/libvpx\/vp8\/encoder\/*\\n\"\n\n\/\/ http:\/\/crbug.com\/223352\n\"race:uprv_malloc_46\\n\"\n\"race:uprv_realloc_46\\n\"\n\n\/\/ http:\/\/crbug.com\/244385\n\"race:unixTempFileDir\\n\"\n\n\/\/ http:\/\/crbug.com\/244774\n\"race:webrtc::RTPReceiver::ProcessBitrate\\n\"\n\"race:webrtc::RTPSender::ProcessBitrate\\n\"\n\"race:webrtc::VideoCodingModuleImpl::Decode\\n\"\n\"race:webrtc::RTPSender::SendOutgoingData\\n\"\n\"race:webrtc::VP8EncoderImpl::GetEncodedPartitions\\n\"\n\"race:webrtc::VP8EncoderImpl::Encode\\n\"\n\"race:webrtc::ViEEncoder::DeliverFrame\\n\"\n\"race:webrtc::vcm::VideoReceiver::Decode\\n\"\n\"race:webrtc::VCMReceiver::FrameForDecoding\\n\"\n\"race:*trace_event_unique_catstatic*\\n\"\n\n\/\/ http:\/\/crbug.com\/244856\n\"race:AutoPulseLock\\n\"\n\n\/\/ http:\/\/crbug.com\/246968\n\"race:webrtc::VideoCodingModuleImpl::RegisterPacketRequestCallback\\n\"\n\n\/\/ http:\/\/crbug.com\/246970\n\"race:webrtc::EventPosix::StartTimer\\n\"\n\n\/\/ http:\/\/crbug.com\/258479\n\"race:SamplingStateScope\\n\"\n\"race:g_trace_state\\n\"\n\n\/\/ http:\/\/crbug.com\/270037\n\"race:gLibCleanupFunctions\\n\"\n\n\/\/ http:\/\/crbug.com\/272987\n\"race:webrtc::MediaStreamTrack<webrtc::AudioTrackInterface>::set_enabled\\n\"\n\n\/\/ http:\/\/crbug.com\/345245\n\"race:jingle_glue::JingleThreadWrapper::~JingleThreadWrapper\\n\"\n\"race:webrtc::voe::Channel::UpdatePacketDelay\\n\"\n\"race:webrtc::voe::Channel::GetDelayEstimate\\n\"\n\"race:webrtc::VCMCodecDataBase::DeregisterReceiveCodec\\n\"\n\"race:webrtc::GainControlImpl::set_stream_analog_level\\n\"\n\n\/\/ http:\/\/crbug.com\/347538\n\"race:sctp_timer_start\\n\"\n\n\/\/ http:\/\/crbug.com\/347548\n\"race:cricket::WebRtcVideoMediaChannel::MaybeResetVieSendCodec\\n\"\n\"race:cricket::WebRtcVideoMediaChannel::SetSendCodec\\n\"\n\n\/\/ http:\/\/crbug.com\/348511\n\"race:webrtc::acm1::AudioCodingModuleImpl::PlayoutData10Ms\\n\"\n\n\/\/ http:\/\/crbug.com\/348982\n\"race:cricket::P2PTransportChannel::OnConnectionDestroyed\\n\"\n\"race:cricket::P2PTransportChannel::AddConnection\\n\"\n\n\/\/ http:\/\/crbug.com\/348984\n\"race:sctp_express_handle_sack\\n\"\n\n\/\/ http:\/\/crbug.com\/350982\n\"race:libvpx\/vp9\/decoder\/vp9_thread.c\\n\"\n\n\/\/ http:\/\/crbug.com\/372807\n\"deadlock:net::X509Certificate::CreateCertificateListFromBytes\\n\"\n\"deadlock:net::X509Certificate::CreateFromBytes\\n\"\n\"deadlock:net::SSLClientSocketNSS::Core::DoHandshakeLoop\\n\"\n\n\/\/ False positive in libc's tzset_internal, http:\/\/crbug.com\/379738.\n\"race:tzset_internal\\n\"\n\n\/\/ http:\/\/crbug.com\/380554\n\"deadlock:g_type_add_interface_static\\n\"\n\n\/\/ End of suppressions.\n; \/\/ Please keep this semicolon.\n\n#endif \/\/ THREAD_SANITIZER\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/proof:$Id$\n\/\/ Author: Sangsu Ryu 28\/06\/2011\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TSelVerifyDataSet \/\/\n\/\/ \/\/\n\/\/ Selector to verify dataset in parallel on workers \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define TSelVerifyDataSet_cxx\n\n#include \"TSelVerifyDataSet.h\"\n#include \"TDataSetManager.h\"\n#include \"TDSet.h\"\n#include \"TParameter.h\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n#include \"TNamed.h\"\n#include <unistd.h>\n#include \"TSystem.h\"\n#include \"TROOT.h\"\n#include \"TEnv.h\"\n#include \"TFileStager.h\"\n#include \"TProofDebug.h\"\n#include \"TProofServ.h\"\n#include \"TFileCollection.h\"\n#include \"TFileInfo.h\"\n\nClassImp(TSelVerifyDataSet)\n\n\/\/______________________________________________________________________________\nTSelVerifyDataSet::TSelVerifyDataSet(TTree *)\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nTSelVerifyDataSet::TSelVerifyDataSet()\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::Begin(TTree *)\n{\n Init(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::SlaveBegin(TTree *)\n{\n\n Init(0);\n\n TString dsname, opts;\n\n TNamed* par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_VerifyDataSet\"));\n if (par) {\n dsname = par->GetTitle();\n } else {\n Abort(\"cannot find dataset name: cannot continue\", kAbortProcess);\n return;\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_VerifyDataSetOption\"));\n if (par) {\n opts = par->GetTitle();\n } else {\n Abort(\"cannot find verify options: cannot continue\", kAbortProcess);\n return;\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_MSS\"));\n if (par) {\n fMss = par->GetTitle();\n PDB(kSelector, 2) Info(\"SlaveBegin\", \"dataset MSS: '%s'\", fMss.Data());\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_StageOption\"));\n if (par) {\n fStageopts = par->GetTitle();\n PDB(kSelector, 2) Info(\"SlaveBegin\", \"dataset stage options: '%s'\", fStageopts.Data());\n }\n\n \/\/ Extract the directives\n UInt_t o = 0;\n if (!opts.IsNull()) {\n \/\/ Selection options\n if (strstr(opts, \"allfiles:\") || strchr(opts, 'A'))\n o |= TDataSetManager::kAllFiles;\n else if (strstr(opts, \"staged:\") || strchr(opts, 'D'))\n o |= TDataSetManager::kStagedFiles;\n \/\/ Pre-action options\n if (strstr(opts, \"open:\") || strchr(opts, 'O'))\n o |= TDataSetManager::kReopen;\n if (strstr(opts, \"touch:\") || strchr(opts, 'T'))\n o |= TDataSetManager::kTouch;\n if (strstr(opts, \"nostagedcheck:\") || strchr(opts, 'I'))\n o |= TDataSetManager::kNoStagedCheck;\n \/\/ Process options\n if (strstr(opts, \"noaction:\") || strchr(opts, 'N'))\n o |= TDataSetManager::kNoAction;\n if (strstr(opts, \"locateonly:\") || strchr(opts, 'L'))\n o |= TDataSetManager::kLocateOnly;\n if (strstr(opts, \"stageonly:\") || strchr(opts, 'S'))\n o |= TDataSetManager::kStageOnly;\n \/\/ Auxilliary options\n if (strstr(opts, \"verbose:\") || strchr(opts, 'V'))\n o |= TDataSetManager::kDebug;\n } else {\n \/\/ Default\n o = TDataSetManager::kReopen | TDataSetManager::kDebug;\n }\n\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"o=%d\", o);\n \/\/ File selection\n fFopt = ((o & TDataSetManager::kAllFiles)) ? -1 : 0;\n if (fFopt >= 0) {\n if ((o & TDataSetManager::kStagedFiles)) {\n fFopt = 10;\n } else {\n if ((o & TDataSetManager::kReopen)) fFopt++;\n if ((o & TDataSetManager::kTouch)) fFopt++;\n }\n if ((o & TDataSetManager::kNoStagedCheck)) fFopt += 100;\n } else {\n if ((o & TDataSetManager::kStagedFiles) || (o & TDataSetManager::kReopen) || (o & TDataSetManager::kTouch)) {\n Warning(\"SlaveBegin\", \"kAllFiles mode: ignoring kStagedFiles or kReopen\"\n \" or kTouch requests\");\n }\n if ((o & TDataSetManager::kNoStagedCheck)) fFopt -= 100;\n }\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"fFopt=%d\", fFopt);\n\n \/\/ Type of action\n fSopt = ((o & TDataSetManager::kNoAction)) ? -1 : 0;\n if (fSopt >= 0) {\n if ((o & TDataSetManager::kLocateOnly) && (o & TDataSetManager::kStageOnly)) {\n Error(\"SlaveBegin\", \"kLocateOnly and kStageOnly cannot be processed concurrently\");\n return;\n }\n if ((o & TDataSetManager::kLocateOnly)) fSopt = 1;\n if ((o & TDataSetManager::kStageOnly)) fSopt = 2;\n } else if ((o & TDataSetManager::kLocateOnly) || (o & TDataSetManager::kStageOnly)) {\n Warning(\"SlaveBegin\", \"kNoAction mode: ignoring kLocateOnly or kStageOnly requests\");\n }\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"fSopt=%d\", fSopt);\n\n fDbg = ((o & TDataSetManager::kDebug)) ? kTRUE : kFALSE;\n\n \/\/ File selection, Reopen and Touch options\n fAllf = (fFopt == -1) ? kTRUE : kFALSE;\n fCheckstg = (fFopt >= 100 || fFopt < -1) ? kFALSE : kTRUE;\n if (fFopt >= 0) fFopt %= 100;\n fNonStgf = (fFopt >= 0 && fFopt < 10) ? kTRUE : kFALSE;\n fReopen = (fFopt >= 1 && fFopt < 10) ? kTRUE : kFALSE;\n fTouch = (fFopt >= 2 && fFopt < 10) ? kTRUE : kFALSE;\n fStgf = (fFopt == 10) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fAllf=%d fCheckstg=%d fNonStgf=%d fReopen=%d fTouch=%d fStgf=%d\",\n fAllf, fCheckstg, fNonStgf, fReopen, fTouch, fStgf);\n\n \/\/ File processing options\n fNoaction = (fSopt == -1) ? kTRUE : kFALSE;\n fFullproc = (fSopt == 0) ? kTRUE : kFALSE;\n fLocateonly = (fSopt == 1) ? kTRUE : kFALSE;\n fStageonly = (fSopt == 2) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fNoaction=%d fFullproc=%d fLocateonly=%d fStageonly=%d\",\n fNoaction, fFullproc, fLocateonly, fStageonly);\n\n \/\/ Run options\n fDoall = (fRopt == 0) ? kTRUE : kFALSE;\n fGetlistonly = (fRopt == 1) ? kTRUE : kFALSE;\n fScanlist = (fRopt == 2) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fDoall=%d fGetlistonly=%d fScanlist=%d\",\n fDoall, fGetlistonly, fScanlist);\n\n TString hostname(TUrl(gSystem->HostName()).GetHostFQDN());\n TString thisordinal = gProofServ ? gProofServ->GetOrdinal() : \"n.d\";\n TString title =\n TString::Format(\"TSelVerifyDataSet_%s_%s\", hostname.Data(), thisordinal.Data());\n fSubDataSet= new TFileCollection(dsname, title);\n}\n\n\/\/______________________________________________________________________________\nBool_t TSelVerifyDataSet::Process(Long64_t entry)\n{\n \/\/ Process a single entry\n \n TDSetElement *fCurrent = 0;\n TPair *elemPair = 0;\n if (fInput && (elemPair = dynamic_cast<TPair *>\n (fInput->FindObject(\"PROOF_CurrentElement\")))) {\n if ((fCurrent = dynamic_cast<TDSetElement *>(elemPair->Value()))) {\n Info(\"Process\", \"entry %lld: file: '%s'\", entry, fCurrent->GetName());\n } else { \n Error(\"Process\", \"entry %lld: no file specified!\", entry);\n return kFALSE;\n }\n }\n \n TFileInfo *fileInfo = dynamic_cast<TFileInfo*>(fCurrent->GetAssocObj(0));\n if (!fileInfo) {\n Error(\"Process\", \"can not get TFileInfo; returning\");\n return kFALSE;\n }\n\n PDB(kSelector, 1) {\n Info(\"Process\", \"input fileinfo: \");\n fileInfo->Print(\"L\");\n }\n\n TFileStager *stager = 0;\n Bool_t createStager = kFALSE;\n\n TFileInfo* newfileinfo = new TFileInfo(*fileInfo);\n newfileinfo->SetIndex(fileInfo->GetIndex());\n\n if (fDoall || fGetlistonly) {\n\n stager = (fMss && strlen(fMss) > 0) ? TFileStager::Open(fMss) : 0;\n createStager = (stager) ? kFALSE : kTRUE;\n\n \/\/ Check which files have been staged, this can be replaced by a bulk command,\n \/\/ once it exists in the xrdclient\n\n \/\/ For real time monitoring\n gSystem->DispatchOneEvent(kTRUE);\n\n Bool_t changed = kFALSE;\n Bool_t touched = kFALSE;\n Bool_t disappeared = kFALSE;\n\n TDataSetManager::CheckStagedStatus(newfileinfo, fFopt, -1, 0, stager, createStager,\n fDbg, changed, touched, disappeared);\n\n if (changed) fChangedDs = kTRUE;\n if (touched) fTouched++;\n if (disappeared) fDisappeared++;\n \n SafeDelete(stager);\n\n PDB(kSelector, 1) Info(\"Process\",\n \"fChangedDs = %d, fTouched = %d disappeared = %d\",\n fChangedDs, fTouched, fDisappeared);\n\n \/\/ If required to only get the list we are done\n if (fGetlistonly) {\n Info(\"Process\", \"updated fileinfo: \");\n newfileinfo->Print(\"F\");\n fSubDataSet->Add(newfileinfo);\n return kTRUE;\n }\n }\n\n if (!fNoaction && (fDoall || fScanlist)) {\n\n \/\/ Point to the fileinfo\n \/\/newStagedFiles = (!fDoall && fScanlist && flist) ? flist : newStagedFiles;\n if (!fDoall && fScanlist) {\n SafeDelete(newfileinfo);\n newfileinfo = new TFileInfo(*fileInfo);\n newfileinfo->SetIndex(fileInfo->GetIndex());\n }\n\n \/\/ Loop over now staged files\n PDB(kSelector, 1) Info(\"Process\",\n \"file appear to be newly staged; %s\",\n newfileinfo->GetFirstUrl()->GetUrl());\n\n \/\/ If staging files, prepare the stager\n if (fLocateonly || fStageonly) {\n stager = (fMss && strlen(fMss) > 0) ? TFileStager::Open(fMss) : 0;\n createStager = (stager) ? kFALSE : kTRUE;\n }\n\n \/\/ Process the file\n Bool_t changed = kFALSE;\n Bool_t opened = kFALSE;\n TDataSetManager::ProcessFile(newfileinfo, fSopt, fCheckstg, fDoall, stager, createStager, fStageopts,\n fDbg, changed, opened);\n\n if (changed) fChangedDs = kTRUE;\n if (opened) fOpened++;\n }\n \n PDB(kSelector, 1) {\n Info(\"Process\", \"updated fileinfo: \");\n newfileinfo->Print(\"L\");\n }\n fSubDataSet->Add(newfileinfo);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::SlaveTerminate()\n{\n if (fSubDataSet) {\n fSubDataSet->Update();\n if (fSubDataSet->GetNFiles() > 0) {\n fOutput->Add(fSubDataSet);\n Info(\"SlaveTerminate\",\n \"sub-dataset '%s' added to the output list (%lld files)\",\n fSubDataSet->GetTitle(), fSubDataSet->GetNFiles());\n }\n \/\/ Add information for registration\n fOutput->Add(new TNamed(TString::Format(\"DATASET_%s\", fSubDataSet->GetName()).Data(),\"OT:sortidx:\"));\n fOutput->Add(new TNamed(\"PROOFSERV_RegisterDataSet\", \"\"));\n }\n\n \/\/ Send the number of files disppeared, opened and mark 'changed'if any fileinfo in the dataset has changed\n TString hostname(TUrl(gSystem->HostName()).GetHostFQDN());\n TString thisordinal = gProofServ ? gProofServ->GetOrdinal() : \"n.d\";\n TString sfdisppeared= TString::Format(\"PROOF_NoFilesDisppeared_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfdisppeared.Data(), fDisappeared));\n TString sfOpened= TString::Format(\"PROOF_NoFilesOpened_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfOpened.Data(), fOpened));\n TString sfTouched = TString::Format(\"PROOF_NoFilesTouched_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfTouched.Data(), fTouched));\n TString schanged= TString::Format(\"PROOF_DataSetChanged_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Bool_t>(schanged.Data(), fChangedDs));\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::Terminate()\n{}\n<commit_msg>Remove unused include<commit_after>\/\/ @(#)root\/proof:$Id$\n\/\/ Author: Sangsu Ryu 28\/06\/2011\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TSelVerifyDataSet \/\/\n\/\/ \/\/\n\/\/ Selector to verify dataset in parallel on workers \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define TSelVerifyDataSet_cxx\n\n#include \"TSelVerifyDataSet.h\"\n#include \"TDataSetManager.h\"\n#include \"TDSet.h\"\n#include \"TParameter.h\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n#include \"TNamed.h\"\n#include \"TSystem.h\"\n#include \"TROOT.h\"\n#include \"TEnv.h\"\n#include \"TFileStager.h\"\n#include \"TProofDebug.h\"\n#include \"TProofServ.h\"\n#include \"TFileCollection.h\"\n#include \"TFileInfo.h\"\n\nClassImp(TSelVerifyDataSet)\n\n\/\/______________________________________________________________________________\nTSelVerifyDataSet::TSelVerifyDataSet(TTree *)\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nTSelVerifyDataSet::TSelVerifyDataSet()\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::Begin(TTree *)\n{\n Init(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::SlaveBegin(TTree *)\n{\n\n Init(0);\n\n TString dsname, opts;\n\n TNamed* par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_VerifyDataSet\"));\n if (par) {\n dsname = par->GetTitle();\n } else {\n Abort(\"cannot find dataset name: cannot continue\", kAbortProcess);\n return;\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_VerifyDataSetOption\"));\n if (par) {\n opts = par->GetTitle();\n } else {\n Abort(\"cannot find verify options: cannot continue\", kAbortProcess);\n return;\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_MSS\"));\n if (par) {\n fMss = par->GetTitle();\n PDB(kSelector, 2) Info(\"SlaveBegin\", \"dataset MSS: '%s'\", fMss.Data());\n }\n\n par = dynamic_cast<TNamed*>(fInput->FindObject(\"PROOF_StageOption\"));\n if (par) {\n fStageopts = par->GetTitle();\n PDB(kSelector, 2) Info(\"SlaveBegin\", \"dataset stage options: '%s'\", fStageopts.Data());\n }\n\n \/\/ Extract the directives\n UInt_t o = 0;\n if (!opts.IsNull()) {\n \/\/ Selection options\n if (strstr(opts, \"allfiles:\") || strchr(opts, 'A'))\n o |= TDataSetManager::kAllFiles;\n else if (strstr(opts, \"staged:\") || strchr(opts, 'D'))\n o |= TDataSetManager::kStagedFiles;\n \/\/ Pre-action options\n if (strstr(opts, \"open:\") || strchr(opts, 'O'))\n o |= TDataSetManager::kReopen;\n if (strstr(opts, \"touch:\") || strchr(opts, 'T'))\n o |= TDataSetManager::kTouch;\n if (strstr(opts, \"nostagedcheck:\") || strchr(opts, 'I'))\n o |= TDataSetManager::kNoStagedCheck;\n \/\/ Process options\n if (strstr(opts, \"noaction:\") || strchr(opts, 'N'))\n o |= TDataSetManager::kNoAction;\n if (strstr(opts, \"locateonly:\") || strchr(opts, 'L'))\n o |= TDataSetManager::kLocateOnly;\n if (strstr(opts, \"stageonly:\") || strchr(opts, 'S'))\n o |= TDataSetManager::kStageOnly;\n \/\/ Auxilliary options\n if (strstr(opts, \"verbose:\") || strchr(opts, 'V'))\n o |= TDataSetManager::kDebug;\n } else {\n \/\/ Default\n o = TDataSetManager::kReopen | TDataSetManager::kDebug;\n }\n\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"o=%d\", o);\n \/\/ File selection\n fFopt = ((o & TDataSetManager::kAllFiles)) ? -1 : 0;\n if (fFopt >= 0) {\n if ((o & TDataSetManager::kStagedFiles)) {\n fFopt = 10;\n } else {\n if ((o & TDataSetManager::kReopen)) fFopt++;\n if ((o & TDataSetManager::kTouch)) fFopt++;\n }\n if ((o & TDataSetManager::kNoStagedCheck)) fFopt += 100;\n } else {\n if ((o & TDataSetManager::kStagedFiles) || (o & TDataSetManager::kReopen) || (o & TDataSetManager::kTouch)) {\n Warning(\"SlaveBegin\", \"kAllFiles mode: ignoring kStagedFiles or kReopen\"\n \" or kTouch requests\");\n }\n if ((o & TDataSetManager::kNoStagedCheck)) fFopt -= 100;\n }\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"fFopt=%d\", fFopt);\n\n \/\/ Type of action\n fSopt = ((o & TDataSetManager::kNoAction)) ? -1 : 0;\n if (fSopt >= 0) {\n if ((o & TDataSetManager::kLocateOnly) && (o & TDataSetManager::kStageOnly)) {\n Error(\"SlaveBegin\", \"kLocateOnly and kStageOnly cannot be processed concurrently\");\n return;\n }\n if ((o & TDataSetManager::kLocateOnly)) fSopt = 1;\n if ((o & TDataSetManager::kStageOnly)) fSopt = 2;\n } else if ((o & TDataSetManager::kLocateOnly) || (o & TDataSetManager::kStageOnly)) {\n Warning(\"SlaveBegin\", \"kNoAction mode: ignoring kLocateOnly or kStageOnly requests\");\n }\n PDB(kSelector, 1) Info(\"SlaveBegin\", \"fSopt=%d\", fSopt);\n\n fDbg = ((o & TDataSetManager::kDebug)) ? kTRUE : kFALSE;\n\n \/\/ File selection, Reopen and Touch options\n fAllf = (fFopt == -1) ? kTRUE : kFALSE;\n fCheckstg = (fFopt >= 100 || fFopt < -1) ? kFALSE : kTRUE;\n if (fFopt >= 0) fFopt %= 100;\n fNonStgf = (fFopt >= 0 && fFopt < 10) ? kTRUE : kFALSE;\n fReopen = (fFopt >= 1 && fFopt < 10) ? kTRUE : kFALSE;\n fTouch = (fFopt >= 2 && fFopt < 10) ? kTRUE : kFALSE;\n fStgf = (fFopt == 10) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fAllf=%d fCheckstg=%d fNonStgf=%d fReopen=%d fTouch=%d fStgf=%d\",\n fAllf, fCheckstg, fNonStgf, fReopen, fTouch, fStgf);\n\n \/\/ File processing options\n fNoaction = (fSopt == -1) ? kTRUE : kFALSE;\n fFullproc = (fSopt == 0) ? kTRUE : kFALSE;\n fLocateonly = (fSopt == 1) ? kTRUE : kFALSE;\n fStageonly = (fSopt == 2) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fNoaction=%d fFullproc=%d fLocateonly=%d fStageonly=%d\",\n fNoaction, fFullproc, fLocateonly, fStageonly);\n\n \/\/ Run options\n fDoall = (fRopt == 0) ? kTRUE : kFALSE;\n fGetlistonly = (fRopt == 1) ? kTRUE : kFALSE;\n fScanlist = (fRopt == 2) ? kTRUE : kFALSE;\n\n PDB(kSelector, 1) Info(\"SlaveBegin\",\n \"fDoall=%d fGetlistonly=%d fScanlist=%d\",\n fDoall, fGetlistonly, fScanlist);\n\n TString hostname(TUrl(gSystem->HostName()).GetHostFQDN());\n TString thisordinal = gProofServ ? gProofServ->GetOrdinal() : \"n.d\";\n TString title =\n TString::Format(\"TSelVerifyDataSet_%s_%s\", hostname.Data(), thisordinal.Data());\n fSubDataSet= new TFileCollection(dsname, title);\n}\n\n\/\/______________________________________________________________________________\nBool_t TSelVerifyDataSet::Process(Long64_t entry)\n{\n \/\/ Process a single entry\n \n TDSetElement *fCurrent = 0;\n TPair *elemPair = 0;\n if (fInput && (elemPair = dynamic_cast<TPair *>\n (fInput->FindObject(\"PROOF_CurrentElement\")))) {\n if ((fCurrent = dynamic_cast<TDSetElement *>(elemPair->Value()))) {\n Info(\"Process\", \"entry %lld: file: '%s'\", entry, fCurrent->GetName());\n } else { \n Error(\"Process\", \"entry %lld: no file specified!\", entry);\n return kFALSE;\n }\n }\n \n TFileInfo *fileInfo = dynamic_cast<TFileInfo*>(fCurrent->GetAssocObj(0));\n if (!fileInfo) {\n Error(\"Process\", \"can not get TFileInfo; returning\");\n return kFALSE;\n }\n\n PDB(kSelector, 1) {\n Info(\"Process\", \"input fileinfo: \");\n fileInfo->Print(\"L\");\n }\n\n TFileStager *stager = 0;\n Bool_t createStager = kFALSE;\n\n TFileInfo* newfileinfo = new TFileInfo(*fileInfo);\n newfileinfo->SetIndex(fileInfo->GetIndex());\n\n if (fDoall || fGetlistonly) {\n\n stager = (fMss && strlen(fMss) > 0) ? TFileStager::Open(fMss) : 0;\n createStager = (stager) ? kFALSE : kTRUE;\n\n \/\/ Check which files have been staged, this can be replaced by a bulk command,\n \/\/ once it exists in the xrdclient\n\n \/\/ For real time monitoring\n gSystem->DispatchOneEvent(kTRUE);\n\n Bool_t changed = kFALSE;\n Bool_t touched = kFALSE;\n Bool_t disappeared = kFALSE;\n\n TDataSetManager::CheckStagedStatus(newfileinfo, fFopt, -1, 0, stager, createStager,\n fDbg, changed, touched, disappeared);\n\n if (changed) fChangedDs = kTRUE;\n if (touched) fTouched++;\n if (disappeared) fDisappeared++;\n \n SafeDelete(stager);\n\n PDB(kSelector, 1) Info(\"Process\",\n \"fChangedDs = %d, fTouched = %d disappeared = %d\",\n fChangedDs, fTouched, fDisappeared);\n\n \/\/ If required to only get the list we are done\n if (fGetlistonly) {\n Info(\"Process\", \"updated fileinfo: \");\n newfileinfo->Print(\"F\");\n fSubDataSet->Add(newfileinfo);\n return kTRUE;\n }\n }\n\n if (!fNoaction && (fDoall || fScanlist)) {\n\n \/\/ Point to the fileinfo\n \/\/newStagedFiles = (!fDoall && fScanlist && flist) ? flist : newStagedFiles;\n if (!fDoall && fScanlist) {\n SafeDelete(newfileinfo);\n newfileinfo = new TFileInfo(*fileInfo);\n newfileinfo->SetIndex(fileInfo->GetIndex());\n }\n\n \/\/ Loop over now staged files\n PDB(kSelector, 1) Info(\"Process\",\n \"file appear to be newly staged; %s\",\n newfileinfo->GetFirstUrl()->GetUrl());\n\n \/\/ If staging files, prepare the stager\n if (fLocateonly || fStageonly) {\n stager = (fMss && strlen(fMss) > 0) ? TFileStager::Open(fMss) : 0;\n createStager = (stager) ? kFALSE : kTRUE;\n }\n\n \/\/ Process the file\n Bool_t changed = kFALSE;\n Bool_t opened = kFALSE;\n TDataSetManager::ProcessFile(newfileinfo, fSopt, fCheckstg, fDoall, stager, createStager, fStageopts,\n fDbg, changed, opened);\n\n if (changed) fChangedDs = kTRUE;\n if (opened) fOpened++;\n }\n \n PDB(kSelector, 1) {\n Info(\"Process\", \"updated fileinfo: \");\n newfileinfo->Print(\"L\");\n }\n fSubDataSet->Add(newfileinfo);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::SlaveTerminate()\n{\n if (fSubDataSet) {\n fSubDataSet->Update();\n if (fSubDataSet->GetNFiles() > 0) {\n fOutput->Add(fSubDataSet);\n Info(\"SlaveTerminate\",\n \"sub-dataset '%s' added to the output list (%lld files)\",\n fSubDataSet->GetTitle(), fSubDataSet->GetNFiles());\n }\n \/\/ Add information for registration\n fOutput->Add(new TNamed(TString::Format(\"DATASET_%s\", fSubDataSet->GetName()).Data(),\"OT:sortidx:\"));\n fOutput->Add(new TNamed(\"PROOFSERV_RegisterDataSet\", \"\"));\n }\n\n \/\/ Send the number of files disppeared, opened and mark 'changed'if any fileinfo in the dataset has changed\n TString hostname(TUrl(gSystem->HostName()).GetHostFQDN());\n TString thisordinal = gProofServ ? gProofServ->GetOrdinal() : \"n.d\";\n TString sfdisppeared= TString::Format(\"PROOF_NoFilesDisppeared_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfdisppeared.Data(), fDisappeared));\n TString sfOpened= TString::Format(\"PROOF_NoFilesOpened_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfOpened.Data(), fOpened));\n TString sfTouched = TString::Format(\"PROOF_NoFilesTouched_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Int_t>(sfTouched.Data(), fTouched));\n TString schanged= TString::Format(\"PROOF_DataSetChanged_%s_%s\", hostname.Data(), thisordinal.Data());\n fOutput->Add(new TParameter<Bool_t>(schanged.Data(), fChangedDs));\n}\n\n\/\/______________________________________________________________________________\nvoid TSelVerifyDataSet::Terminate()\n{}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ximpgrp.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 13:58:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XIMPGROUP_HXX\n#define _XIMPGROUP_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _SDXMLIMP_IMPL_HXX\n#include \"sdxmlimp_impl.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include \"nmspmap.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_\n#include <com\/sun\/star\/drawing\/XShapes.hpp>\n#endif\n\n#ifndef _RTTI_HXX\n#include <tools\/rtti.hxx>\n#endif\n\n#ifndef _XIMPSHAPE_HXX\n#include \"ximpshap.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ draw:g context (RECURSIVE)\n\nclass SdXMLGroupShapeContext : public SdXMLShapeContext\n{\n \/\/ the shape group this group is working on\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;\n\nprotected:\n void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)\n { mxShapes = rNew; }\n\npublic:\n TYPEINFO();\n\n SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,\n sal_Bool bTemporaryShape);\n virtual ~SdXMLGroupShapeContext();\n\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);\n virtual void EndElement();\n\n const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const\n { return mxShapes; }\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()\n { return mxShapes; }\n};\n\n\n#endif \/\/ _XIMPGROUP_HXX\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.6.274); FILE MERGED 2007\/06\/04 13:23:25 vg 1.6.274.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ximpgrp.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 15:10:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XIMPGROUP_HXX\n#define _XIMPGROUP_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include <xmloff\/xmlictxt.hxx>\n#endif\n\n#ifndef _SDXMLIMP_IMPL_HXX\n#include \"sdxmlimp_impl.hxx\"\n#endif\n\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_\n#include <com\/sun\/star\/drawing\/XShapes.hpp>\n#endif\n\n#ifndef _RTTI_HXX\n#include <tools\/rtti.hxx>\n#endif\n\n#ifndef _XIMPSHAPE_HXX\n#include \"ximpshap.hxx\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ draw:g context (RECURSIVE)\n\nclass SdXMLGroupShapeContext : public SdXMLShapeContext\n{\n \/\/ the shape group this group is working on\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxChilds;\n\nprotected:\n void SetLocalShapesContext(com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rNew)\n { mxShapes = rNew; }\n\npublic:\n TYPEINFO();\n\n SdXMLGroupShapeContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,\n sal_Bool bTemporaryShape);\n virtual ~SdXMLGroupShapeContext();\n\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix, const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);\n virtual void EndElement();\n\n const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext() const\n { return mxShapes; }\n com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& GetLocalShapesContext()\n { return mxShapes; }\n};\n\n\n#endif \/\/ _XIMPGROUP_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"TcpConn.hpp\"\n#include <geode\/DistributedSystem.hpp>\n#include <geode\/SystemProperties.hpp>\n#include <geode\/Log.hpp>\n\n#include <memory.h>\n\n#include <ace\/INET_Addr.h>\n#include <ace\/SOCK_IO.h>\n#include <ace\/SOCK_Connector.h>\n#include <ace\/SOCK_Acceptor.h>\n#include <ace\/OS.h>\n\nusing namespace apache::geode::client;\n\nint TcpConn::m_chunkSize = TcpConn::setChunkSize();\n\nvoid TcpConn::clearNagle(ACE_SOCKET sock) {\n int32_t val = 1;\n#ifdef WIN32\n const char *param = (const char *)&val;\n#else\n const void *param = (const void *)&val;\n#endif\n int32_t plen = sizeof(val);\n\n if (0 != setsockopt(sock, IPPROTO_TCP, 1, param, plen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to set TCP_NODELAY on socket. Errno: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n }\n}\n\nint32_t TcpConn::maxSize(ACE_SOCKET sock, int32_t flag, int32_t size) {\n int32_t val = 0;\n#ifdef _WIN32\n const char *cparam = (const char *)&val;\n char *param = (char *)&val;\n#else\n const void *cparam = (const void *)&val;\n void *param = (void *)&val;\n#endif\n socklen_t plen = sizeof(val);\n socklen_t clen = sizeof(val);\n\n static int32_t max = 32000;\n if (m_maxBuffSizePool <= 0) {\n SystemProperties *props = DistributedSystem::getSystemProperties();\n if (props != nullptr) {\n max = props->maxSocketBufferSize();\n }\n } else {\n max = m_maxBuffSizePool;\n }\n int32_t inc = 32120;\n val = size - (3 * inc);\n if (val < 0) val = 0;\n if (size == 0) size = max;\n int32_t red = 0;\n int32_t lastRed = -1;\n while (lastRed != red) {\n lastRed = red;\n val += inc;\n if (0 != setsockopt(sock, SOL_SOCKET, flag, cparam, clen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to set socket options. Errno: %d : %s \", lastError,\n ACE_OS::strerror(lastError));\n }\n if (0 != getsockopt(sock, SOL_SOCKET, flag, param, &plen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\n \"Failed to get buffer size for flag %d on socket. Errno: %d : %s\",\n flag, lastError, ACE_OS::strerror(lastError));\n }\n#ifdef _LINUX\n val \/= 2;\n#endif\n if ((val >= max) || (val >= size)) continue;\n red = val;\n }\n return val;\n}\n\nvoid TcpConn::createSocket(ACE_SOCKET sock) {\n LOGDEBUG(\"Creating plain socket stream\");\n m_io = new ACE_SOCK_Stream((ACE_HANDLE)sock);\n \/\/ m_io->enable(ACE_NONBLOCK);\n}\n\nvoid TcpConn::init() {\n \/* adongre\n * CID 28736: Improper use of negative value (NEGATIVE_RETURNS)\n * Function \"socket(2, 1, 0)\" returns a negative number.\n * Assigning: unsigned variable \"sock\" = \"socket\".\n *\n * CID 28737: Unsigned compared against 0 (NO_EFFECT)\n * This less-than-zero comparison of an unsigned value is never true. \"sock <\n * 0U\".\n *\/\n ACE_SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);\n \/\/ if ( sock < 0 ) {\n if (sock == -1) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to create socket. Errno: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n char msg[256];\n ACE_OS::snprintf(msg, 256, \"TcpConn::connect failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n throw GeodeIOException(msg);\n }\n\n clearNagle(sock);\n\n static int32_t readSize = 0;\n static int32_t writeSize = 0;\n int32_t originalReadSize = readSize;\n readSize = maxSize(sock, SO_SNDBUF, readSize);\n if (originalReadSize != readSize) {\n \/\/ This should get logged once at startup and again only if it changes\n LOGINFO(\"Using socket send buffer size of %d.\", readSize);\n }\n int32_t originalWriteSize = writeSize;\n writeSize = maxSize(sock, SO_RCVBUF, writeSize);\n if (originalWriteSize != writeSize) {\n \/\/ This should get logged once at startup and again only if it changes\n LOGINFO(\"Using socket receive buffer size of %d.\", writeSize);\n }\n\n createSocket(sock);\n\n connect();\n}\n\nTcpConn::TcpConn() : m_io(nullptr), m_waitSeconds(0), m_maxBuffSizePool(0) {}\n\nTcpConn::TcpConn(const char *ipaddr, uint32_t waitSeconds,\n int32_t maxBuffSizePool)\n : m_io(nullptr),\n m_addr(ipaddr),\n m_waitSeconds(waitSeconds),\n m_maxBuffSizePool(maxBuffSizePool) {}\n\nTcpConn::TcpConn(const char *hostname, int32_t port, uint32_t waitSeconds,\n int32_t maxBuffSizePool)\n : m_io(nullptr),\n m_addr(port, hostname),\n m_waitSeconds(waitSeconds),\n m_maxBuffSizePool(maxBuffSizePool) {}\n\nvoid TcpConn::listen(const char *hostname, int32_t port, uint32_t waitSeconds) {\n ACE_INET_Addr addr(port, hostname);\n listen(addr, waitSeconds);\n}\n\nvoid TcpConn::listen(const char *ipaddr, uint32_t waitSeconds) {\n ACE_INET_Addr addr(ipaddr);\n listen(addr, waitSeconds);\n}\n\nvoid TcpConn::listen(ACE_INET_Addr addr, uint32_t waitSeconds) {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_SOCK_Acceptor listener(addr, 1);\n int32_t retVal = 0;\n if (waitSeconds > 0) {\n ACE_Time_Value wtime(waitSeconds);\n retVal = listener.accept(*m_io, 0, &wtime);\n } else {\n retVal = listener.accept(*m_io, 0);\n }\n if (retVal == -1) {\n char msg[256];\n int32_t lastError = ACE_OS::last_error();\n if (lastError == ETIME || lastError == ETIMEDOUT) {\n \/* adongre\n * Coverity - II\n * CID 29270: Calling risky function (SECURE_CODING)[VERY RISKY]. Using\n * \"sprintf\" can cause a\n * buffer overflow when done incorrectly. Because sprintf() assumes an\n * arbitrarily long string,\n * callers must be careful not to overflow the actual space of the\n * destination.\n * Use snprintf() instead, or correct precision specifiers.\n * Fix : using ACE_OS::snprintf\n *\/\n ACE_OS::snprintf(\n msg, 256,\n \"TcpConn::listen Attempt to listen timed out after %d seconds.\",\n waitSeconds);\n throw TimeoutException(msg);\n }\n ACE_OS::snprintf(msg, 256, \"TcpConn::listen failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n throw GeodeIOException(msg);\n }\n}\n\nvoid TcpConn::connect(const char *hostname, int32_t port,\n uint32_t waitSeconds) {\n ACE_INET_Addr addr(port, hostname);\n m_addr = addr;\n m_waitSeconds = waitSeconds;\n connect();\n}\n\nvoid TcpConn::connect(const char *ipaddr, uint32_t waitSeconds) {\n ACE_INET_Addr addr(ipaddr);\n m_addr = addr;\n m_waitSeconds = waitSeconds;\n connect();\n}\n\nvoid TcpConn::connect() {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_INET_Addr ipaddr = m_addr;\n uint32_t waitSeconds = m_waitSeconds;\n\n ACE_OS::signal(SIGPIPE, SIG_IGN); \/\/ Ignore broken pipe\n\n \/\/ passing waittime as microseconds\n if (DistributedSystem::getSystemProperties()->readTimeoutUnitInMillis()) {\n waitSeconds = waitSeconds * 1000;\n } else {\n waitSeconds = waitSeconds * (1000 * 1000);\n }\n\n LOGFINER(\"Connecting plain socket stream to %s:%d waiting %d micro sec\",\n ipaddr.get_host_name(), ipaddr.get_port_number(), waitSeconds);\n\n ACE_SOCK_Connector conn;\n int32_t retVal = 0;\n if (waitSeconds > 0) {\n \/\/ passing waittime as microseconds\n ACE_Time_Value wtime(0, waitSeconds);\n retVal = conn.connect(*m_io, ipaddr, &wtime);\n } else {\n retVal = conn.connect(*m_io, ipaddr);\n }\n if (retVal == -1) {\n char msg[256];\n int32_t lastError = ACE_OS::last_error();\n if (lastError == ETIME || lastError == ETIMEDOUT) {\n ACE_OS::snprintf(\n msg, 256,\n \"TcpConn::connect Attempt to connect timed out after %d seconds.\",\n waitSeconds);\n \/\/ this is only called by constructor, so we must delete m_io\n GF_SAFE_DELETE(m_io);\n throw TimeoutException(msg);\n }\n ACE_OS::snprintf(msg, 256, \"TcpConn::connect failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n \/\/ this is only called by constructor, so we must delete m_io\n GF_SAFE_DELETE(m_io);\n throw GeodeIOException(msg);\n }\n int rc = this->m_io->enable(ACE_NONBLOCK);\n if (-1 == rc) {\n char msg[250];\n int32_t lastError = ACE_OS::last_error();\n ACE_OS::snprintf(msg, 256, \"TcpConn::NONBLOCK: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n\n LOGINFO(msg);\n }\n}\n\nvoid TcpConn::close() {\n if (m_io != nullptr) {\n m_io->close();\n GF_SAFE_DELETE(m_io);\n }\n}\n\nint32_t TcpConn::receive(char *buff, int32_t len, uint32_t waitSeconds,\n uint32_t waitMicroSeconds) {\n return socketOp(SOCK_READ, buff, len, waitSeconds);\n}\n\nint32_t TcpConn::send(const char *buff, int32_t len, uint32_t waitSeconds,\n uint32_t waitMicroSeconds) {\n return socketOp(SOCK_WRITE, const_cast<char *>(buff), len, waitSeconds);\n}\n\nint32_t TcpConn::socketOp(TcpConn::SockOp op, char *buff, int32_t len,\n uint32_t waitSeconds) {\n {\n \/*{\n ACE_HANDLE handle = m_io->get_handle();\n int val = ACE::get_flags (handle);\n\n if (ACE_BIT_DISABLED (val, ACE_NONBLOCK))\n {\n \/\/ACE::set_flags (handle, ACE_NONBLOCK);\n LOGINFO(\"Flag is not set\");\n }else\n {\n LOGINFO(\"Flag is set\");\n }\n }*\/\n\n GF_DEV_ASSERT(m_io != nullptr);\n GF_DEV_ASSERT(buff != nullptr);\n\n#if GF_DEVEL_ASSERTS == 1\n if (len <= 0) {\n LOGERROR(\n \"TcpConn::socketOp called with a length of %d specified. \"\n \"No operation performed.\",\n len);\n GF_DEV_ASSERT(false);\n }\n#endif\n\n ACE_Time_Value waitTime(0, waitSeconds \/*now its in microSeconds*\/);\n ACE_Time_Value endTime(ACE_OS::gettimeofday() + waitTime);\n ACE_Time_Value sleepTime(0, 100);\n size_t readLen = 0;\n ssize_t retVal;\n bool errnoSet = false;\n\n int32_t sendlen = len;\n int32_t totalsend = 0;\n\n while (len > 0 && waitTime > ACE_Time_Value::zero) {\n if (len > m_chunkSize) {\n sendlen = m_chunkSize;\n len -= m_chunkSize;\n } else {\n sendlen = len;\n len = 0;\n }\n do {\n if (op == SOCK_READ) {\n retVal = m_io->recv_n(buff, sendlen, &waitTime, &readLen);\n } else {\n retVal = m_io->send_n(buff, sendlen, &waitTime, &readLen);\n }\n sendlen -= static_cast<int32_t>(readLen);\n totalsend += static_cast<int32_t>(readLen);\n if (retVal < 0) {\n int32_t lastError = ACE_OS::last_error();\n if (lastError == EAGAIN) {\n ACE_OS::sleep(sleepTime);\n } else {\n errnoSet = true;\n break;\n }\n } else if (retVal == 0 && readLen == 0) {\n ACE_OS::last_error(EPIPE);\n errnoSet = true;\n break;\n }\n\n buff += readLen;\n if (sendlen == 0) break;\n waitTime = endTime - ACE_OS::gettimeofday();\n if (waitTime <= ACE_Time_Value::zero) break;\n } while (sendlen > 0);\n if (errnoSet) break;\n }\n\n if (len > 0 && !errnoSet) {\n ACE_OS::last_error(ETIME);\n }\n\n GF_DEV_ASSERT(len >= 0);\n return totalsend;\n }\n}\n\n\/\/ Return the local port for this TCP connection.\nuint16_t TcpConn::getPort() {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_INET_Addr localAddr;\n m_io->get_local_addr(*(ACE_Addr *)&localAddr);\n return localAddr.get_port_number();\n}\n<commit_msg>GEODE-3143: Close socket before deleting it.<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"TcpConn.hpp\"\n#include <geode\/DistributedSystem.hpp>\n#include <geode\/SystemProperties.hpp>\n#include <geode\/Log.hpp>\n\n#include <memory.h>\n\n#include <ace\/INET_Addr.h>\n#include <ace\/SOCK_IO.h>\n#include <ace\/SOCK_Connector.h>\n#include <ace\/SOCK_Acceptor.h>\n#include <ace\/OS.h>\n\nusing namespace apache::geode::client;\n\nint TcpConn::m_chunkSize = TcpConn::setChunkSize();\n\nvoid TcpConn::clearNagle(ACE_SOCKET sock) {\n int32_t val = 1;\n#ifdef WIN32\n const char *param = (const char *)&val;\n#else\n const void *param = (const void *)&val;\n#endif\n int32_t plen = sizeof(val);\n\n if (0 != setsockopt(sock, IPPROTO_TCP, 1, param, plen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to set TCP_NODELAY on socket. Errno: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n }\n}\n\nint32_t TcpConn::maxSize(ACE_SOCKET sock, int32_t flag, int32_t size) {\n int32_t val = 0;\n#ifdef _WIN32\n const char *cparam = (const char *)&val;\n char *param = (char *)&val;\n#else\n const void *cparam = (const void *)&val;\n void *param = (void *)&val;\n#endif\n socklen_t plen = sizeof(val);\n socklen_t clen = sizeof(val);\n\n static int32_t max = 32000;\n if (m_maxBuffSizePool <= 0) {\n SystemProperties *props = DistributedSystem::getSystemProperties();\n if (props != nullptr) {\n max = props->maxSocketBufferSize();\n }\n } else {\n max = m_maxBuffSizePool;\n }\n int32_t inc = 32120;\n val = size - (3 * inc);\n if (val < 0) val = 0;\n if (size == 0) size = max;\n int32_t red = 0;\n int32_t lastRed = -1;\n while (lastRed != red) {\n lastRed = red;\n val += inc;\n if (0 != setsockopt(sock, SOL_SOCKET, flag, cparam, clen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to set socket options. Errno: %d : %s \", lastError,\n ACE_OS::strerror(lastError));\n }\n if (0 != getsockopt(sock, SOL_SOCKET, flag, param, &plen)) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\n \"Failed to get buffer size for flag %d on socket. Errno: %d : %s\",\n flag, lastError, ACE_OS::strerror(lastError));\n }\n#ifdef _LINUX\n val \/= 2;\n#endif\n if ((val >= max) || (val >= size)) continue;\n red = val;\n }\n return val;\n}\n\nvoid TcpConn::createSocket(ACE_SOCKET sock) {\n LOGDEBUG(\"Creating plain socket stream\");\n m_io = new ACE_SOCK_Stream((ACE_HANDLE)sock);\n \/\/ m_io->enable(ACE_NONBLOCK);\n}\n\nvoid TcpConn::init() {\n \/* adongre\n * CID 28736: Improper use of negative value (NEGATIVE_RETURNS)\n * Function \"socket(2, 1, 0)\" returns a negative number.\n * Assigning: unsigned variable \"sock\" = \"socket\".\n *\n * CID 28737: Unsigned compared against 0 (NO_EFFECT)\n * This less-than-zero comparison of an unsigned value is never true. \"sock <\n * 0U\".\n *\/\n ACE_SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);\n \/\/ if ( sock < 0 ) {\n if (sock == -1) {\n int32_t lastError = ACE_OS::last_error();\n LOGERROR(\"Failed to create socket. Errno: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n char msg[256];\n ACE_OS::snprintf(msg, 256, \"TcpConn::connect failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n throw GeodeIOException(msg);\n }\n\n clearNagle(sock);\n\n static int32_t readSize = 0;\n static int32_t writeSize = 0;\n int32_t originalReadSize = readSize;\n readSize = maxSize(sock, SO_SNDBUF, readSize);\n if (originalReadSize != readSize) {\n \/\/ This should get logged once at startup and again only if it changes\n LOGINFO(\"Using socket send buffer size of %d.\", readSize);\n }\n int32_t originalWriteSize = writeSize;\n writeSize = maxSize(sock, SO_RCVBUF, writeSize);\n if (originalWriteSize != writeSize) {\n \/\/ This should get logged once at startup and again only if it changes\n LOGINFO(\"Using socket receive buffer size of %d.\", writeSize);\n }\n\n createSocket(sock);\n\n connect();\n}\n\nTcpConn::TcpConn() : m_io(nullptr), m_waitSeconds(0), m_maxBuffSizePool(0) {}\n\nTcpConn::TcpConn(const char *ipaddr, uint32_t waitSeconds,\n int32_t maxBuffSizePool)\n : m_io(nullptr),\n m_addr(ipaddr),\n m_waitSeconds(waitSeconds),\n m_maxBuffSizePool(maxBuffSizePool) {}\n\nTcpConn::TcpConn(const char *hostname, int32_t port, uint32_t waitSeconds,\n int32_t maxBuffSizePool)\n : m_io(nullptr),\n m_addr(port, hostname),\n m_waitSeconds(waitSeconds),\n m_maxBuffSizePool(maxBuffSizePool) {}\n\nvoid TcpConn::listen(const char *hostname, int32_t port, uint32_t waitSeconds) {\n ACE_INET_Addr addr(port, hostname);\n listen(addr, waitSeconds);\n}\n\nvoid TcpConn::listen(const char *ipaddr, uint32_t waitSeconds) {\n ACE_INET_Addr addr(ipaddr);\n listen(addr, waitSeconds);\n}\n\nvoid TcpConn::listen(ACE_INET_Addr addr, uint32_t waitSeconds) {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_SOCK_Acceptor listener(addr, 1);\n int32_t retVal = 0;\n if (waitSeconds > 0) {\n ACE_Time_Value wtime(waitSeconds);\n retVal = listener.accept(*m_io, 0, &wtime);\n } else {\n retVal = listener.accept(*m_io, 0);\n }\n if (retVal == -1) {\n char msg[256];\n int32_t lastError = ACE_OS::last_error();\n if (lastError == ETIME || lastError == ETIMEDOUT) {\n \/* adongre\n * Coverity - II\n * CID 29270: Calling risky function (SECURE_CODING)[VERY RISKY]. Using\n * \"sprintf\" can cause a\n * buffer overflow when done incorrectly. Because sprintf() assumes an\n * arbitrarily long string,\n * callers must be careful not to overflow the actual space of the\n * destination.\n * Use snprintf() instead, or correct precision specifiers.\n * Fix : using ACE_OS::snprintf\n *\/\n ACE_OS::snprintf(\n msg, 256,\n \"TcpConn::listen Attempt to listen timed out after %d seconds.\",\n waitSeconds);\n throw TimeoutException(msg);\n }\n ACE_OS::snprintf(msg, 256, \"TcpConn::listen failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n throw GeodeIOException(msg);\n }\n}\n\nvoid TcpConn::connect(const char *hostname, int32_t port,\n uint32_t waitSeconds) {\n ACE_INET_Addr addr(port, hostname);\n m_addr = addr;\n m_waitSeconds = waitSeconds;\n connect();\n}\n\nvoid TcpConn::connect(const char *ipaddr, uint32_t waitSeconds) {\n ACE_INET_Addr addr(ipaddr);\n m_addr = addr;\n m_waitSeconds = waitSeconds;\n connect();\n}\n\nvoid TcpConn::connect() {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_INET_Addr ipaddr = m_addr;\n uint32_t waitSeconds = m_waitSeconds;\n\n ACE_OS::signal(SIGPIPE, SIG_IGN); \/\/ Ignore broken pipe\n\n \/\/ passing waittime as microseconds\n if (DistributedSystem::getSystemProperties()->readTimeoutUnitInMillis()) {\n waitSeconds = waitSeconds * 1000;\n } else {\n waitSeconds = waitSeconds * (1000 * 1000);\n }\n\n LOGFINER(\"Connecting plain socket stream to %s:%d waiting %d micro sec\",\n ipaddr.get_host_name(), ipaddr.get_port_number(), waitSeconds);\n\n ACE_SOCK_Connector conn;\n int32_t retVal = 0;\n if (waitSeconds > 0) {\n \/\/ passing waittime as microseconds\n ACE_Time_Value wtime(0, waitSeconds);\n retVal = conn.connect(*m_io, ipaddr, &wtime);\n } else {\n retVal = conn.connect(*m_io, ipaddr);\n }\n if (retVal == -1) {\n char msg[256];\n int32_t lastError = ACE_OS::last_error();\n if (lastError == ETIME || lastError == ETIMEDOUT) {\n ACE_OS::snprintf(\n msg, 256,\n \"TcpConn::connect Attempt to connect timed out after %d seconds.\",\n waitSeconds);\n \/\/ this is only called by constructor, so we must delete m_io\n GF_SAFE_DELETE(m_io);\n throw TimeoutException(msg);\n }\n ACE_OS::snprintf(msg, 256, \"TcpConn::connect failed with errno: %d: %s\",\n lastError, ACE_OS::strerror(lastError));\n \/\/ this is only called by constructor, so we must delete m_io\n\tclose();\n throw GeodeIOException(msg);\n }\n int rc = this->m_io->enable(ACE_NONBLOCK);\n if (-1 == rc) {\n char msg[250];\n int32_t lastError = ACE_OS::last_error();\n ACE_OS::snprintf(msg, 256, \"TcpConn::NONBLOCK: %d: %s\", lastError,\n ACE_OS::strerror(lastError));\n\n LOGINFO(msg);\n }\n}\n\nvoid TcpConn::close() {\n if (m_io != nullptr) {\n m_io->close();\n GF_SAFE_DELETE(m_io);\n }\n}\n\nint32_t TcpConn::receive(char *buff, int32_t len, uint32_t waitSeconds,\n uint32_t waitMicroSeconds) {\n return socketOp(SOCK_READ, buff, len, waitSeconds);\n}\n\nint32_t TcpConn::send(const char *buff, int32_t len, uint32_t waitSeconds,\n uint32_t waitMicroSeconds) {\n return socketOp(SOCK_WRITE, const_cast<char *>(buff), len, waitSeconds);\n}\n\nint32_t TcpConn::socketOp(TcpConn::SockOp op, char *buff, int32_t len,\n uint32_t waitSeconds) {\n {\n \/*{\n ACE_HANDLE handle = m_io->get_handle();\n int val = ACE::get_flags (handle);\n\n if (ACE_BIT_DISABLED (val, ACE_NONBLOCK))\n {\n \/\/ACE::set_flags (handle, ACE_NONBLOCK);\n LOGINFO(\"Flag is not set\");\n }else\n {\n LOGINFO(\"Flag is set\");\n }\n }*\/\n\n GF_DEV_ASSERT(m_io != nullptr);\n GF_DEV_ASSERT(buff != nullptr);\n\n#if GF_DEVEL_ASSERTS == 1\n if (len <= 0) {\n LOGERROR(\n \"TcpConn::socketOp called with a length of %d specified. \"\n \"No operation performed.\",\n len);\n GF_DEV_ASSERT(false);\n }\n#endif\n\n ACE_Time_Value waitTime(0, waitSeconds \/*now its in microSeconds*\/);\n ACE_Time_Value endTime(ACE_OS::gettimeofday() + waitTime);\n ACE_Time_Value sleepTime(0, 100);\n size_t readLen = 0;\n ssize_t retVal;\n bool errnoSet = false;\n\n int32_t sendlen = len;\n int32_t totalsend = 0;\n\n while (len > 0 && waitTime > ACE_Time_Value::zero) {\n if (len > m_chunkSize) {\n sendlen = m_chunkSize;\n len -= m_chunkSize;\n } else {\n sendlen = len;\n len = 0;\n }\n do {\n if (op == SOCK_READ) {\n retVal = m_io->recv_n(buff, sendlen, &waitTime, &readLen);\n } else {\n retVal = m_io->send_n(buff, sendlen, &waitTime, &readLen);\n }\n sendlen -= static_cast<int32_t>(readLen);\n totalsend += static_cast<int32_t>(readLen);\n if (retVal < 0) {\n int32_t lastError = ACE_OS::last_error();\n if (lastError == EAGAIN) {\n ACE_OS::sleep(sleepTime);\n } else {\n errnoSet = true;\n break;\n }\n } else if (retVal == 0 && readLen == 0) {\n ACE_OS::last_error(EPIPE);\n errnoSet = true;\n break;\n }\n\n buff += readLen;\n if (sendlen == 0) break;\n waitTime = endTime - ACE_OS::gettimeofday();\n if (waitTime <= ACE_Time_Value::zero) break;\n } while (sendlen > 0);\n if (errnoSet) break;\n }\n\n if (len > 0 && !errnoSet) {\n ACE_OS::last_error(ETIME);\n }\n\n GF_DEV_ASSERT(len >= 0);\n return totalsend;\n }\n}\n\n\/\/ Return the local port for this TCP connection.\nuint16_t TcpConn::getPort() {\n GF_DEV_ASSERT(m_io != nullptr);\n\n ACE_INET_Addr localAddr;\n m_io->get_local_addr(*(ACE_Addr *)&localAddr);\n return localAddr.get_port_number();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Use the boundary_pos parameter passed to the MultiPartResponseClient::didReceiveData function as the length of the data. At times HTTP byte range requests return responses which specify invalid content ranges as per the spec, i.e. the last byte position is smaller than the first byte position, etc. I looked into Firefox's byte range parsing code and it always calculates the length based on the boundary position.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2011 Collabora Ltd. <info@collabora.co.uk>\n @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"applicationsource.h\"\n#include \"..\/elementfactory.h\"\n#include <gst\/app\/gstappsrc.h>\n\nnamespace QGst {\nnamespace Utils {\n\n#ifndef DOXYGEN_RUN\n\nstruct QTGSTREAMERUTILS_NO_EXPORT ApplicationSource::Priv\n{\npublic:\n ElementPtr m_appsrc;\n\n void lazyConstruct(ApplicationSource *self);\n void setCallbacks(ApplicationSource *self);\n\n inline GstAppSrc *appSrc()\n {\n return reinterpret_cast<GstAppSrc*>(static_cast<GstElement*>(m_appsrc));\n }\n\nprivate:\n static void need_data(GstAppSrc *src, guint length, gpointer user_data);\n static void enough_data(GstAppSrc *src, gpointer user_data);\n static gboolean seek_data(GstAppSrc *src, guint64 offset, gpointer user_data);\n\n static void need_data_noop(GstAppSrc*, guint, gpointer) {}\n static void enough_data_noop(GstAppSrc*, gpointer) {}\n static gboolean seek_data_noop(GstAppSrc*, guint64, gpointer) { return FALSE; }\n};\n\nvoid ApplicationSource::Priv::lazyConstruct(ApplicationSource *self)\n{\n if (!m_appsrc) {\n m_appsrc = QGst::ElementFactory::make(\"appsrc\");\n if (!m_appsrc) {\n qWarning() << \"Failed to construct appsrc\";\n }\n setCallbacks(self);\n }\n}\n\nvoid ApplicationSource::Priv::setCallbacks(ApplicationSource *self)\n{\n if (m_appsrc) {\n if (self) {\n static GstAppSrcCallbacks callbacks = { &need_data, &enough_data, &seek_data };\n gst_app_src_set_callbacks(appSrc(), &callbacks, self, NULL);\n } else {\n static GstAppSrcCallbacks callbacks = { &need_data_noop, &enough_data_noop, &seek_data_noop };\n gst_app_src_set_callbacks(appSrc(), &callbacks, NULL, NULL);\n }\n }\n}\n\nvoid ApplicationSource::Priv::need_data(GstAppSrc *src, guint length, gpointer user_data)\n{\n Q_UNUSED(src);\n static_cast<ApplicationSource*>(user_data)->needData(length);\n}\n\nvoid ApplicationSource::Priv::enough_data(GstAppSrc *src, gpointer user_data)\n{\n Q_UNUSED(src);\n static_cast<ApplicationSource*>(user_data)->enoughData();\n}\n\ngboolean ApplicationSource::Priv::seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)\n{\n Q_UNUSED(src);\n return static_cast<ApplicationSource*>(user_data)->seekData(offset) ? TRUE : FALSE;\n}\n\n#endif \/\/DOXYGEN_RUN\n\nApplicationSource::ApplicationSource()\n : d(new Priv)\n{\n}\n\nApplicationSource::~ApplicationSource()\n{\n d->setCallbacks(NULL); \/\/remove the callbacks from the source\n delete d;\n}\n\nElementPtr ApplicationSource::element() const\n{\n d->lazyConstruct(const_cast<ApplicationSource*>(this));\n return d->m_appsrc;\n}\n\nvoid ApplicationSource::setElement(const ElementPtr & appsrc)\n{\n Q_ASSERT(QGlib::Type::fromInstance(appsrc).isA(GST_TYPE_APP_SRC));\n d->setCallbacks(NULL); \/\/remove the callbacks from the previous source\n d->m_appsrc = appsrc;\n d->setCallbacks(this);\n}\n\nCapsPtr ApplicationSource::caps() const\n{\n CapsPtr c;\n if (d->appSrc()) {\n c = CapsPtr::wrap(gst_app_src_get_caps(d->appSrc()), false);\n }\n return c;\n}\n\nvoid ApplicationSource::setCaps(const CapsPtr & caps)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_caps(d->appSrc(), caps);\n }\n}\n\nquint64 ApplicationSource::minLatency() const\n{\n guint64 ret = -1;\n if (d->appSrc()) {\n gst_app_src_get_latency(d->appSrc(), &ret, NULL);\n }\n return ret;\n}\n\nquint64 ApplicationSource::maxLatency() const\n{\n guint64 ret = -1;\n if (d->appSrc()) {\n gst_app_src_get_latency(d->appSrc(), NULL, &ret);\n }\n return ret;\n}\n\nvoid ApplicationSource::setLatency(quint64 min, quint64 max)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_latency(d->appSrc(), min, max);\n }\n}\n\nqint64 ApplicationSource::size() const\n{\n return d->appSrc() ? gst_app_src_get_size(d->appSrc()) : -1;\n}\n\nvoid ApplicationSource::setSize(qint64 size)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_size(d->appSrc(), size);\n }\n}\n\nAppStreamType ApplicationSource::streamType() const\n{\n return d->appSrc() ? static_cast<AppStreamType>(gst_app_src_get_stream_type(d->appSrc()))\n : AppStreamTypeStream;\n}\n\nvoid ApplicationSource::setStreamType(AppStreamType type)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_stream_type(d->appSrc(), static_cast<GstAppStreamType>(type));\n }\n}\n\nquint64 ApplicationSource::maxBytes() const\n{\n return d->appSrc() ? gst_app_src_get_max_bytes(d->appSrc()) : 0;\n}\n\nvoid ApplicationSource::setMaxBytes(quint64 max)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_max_bytes(d->appSrc(), max);\n }\n}\n\nbool ApplicationSource::blockEnabled() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"block\").toBool() : false;\n}\n\nvoid ApplicationSource::enableBlock(bool enable)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"block\", enable);\n }\n}\n\nbool ApplicationSource::isLive() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"is-live\").toBool() : false;\n}\n\nvoid ApplicationSource::setLive(bool islive)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"is-live\", islive);\n }\n}\n\nuint ApplicationSource::minPercent() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"min-percent\").toUInt() : 0;\n}\n\nvoid ApplicationSource::setMinPercent(uint min)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"min-percent\", min);\n }\n}\n\nFormat ApplicationSource::format() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"format\").get<Format>() : FormatBytes;\n}\n\nvoid ApplicationSource::setFormat(Format f)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"format\", f);\n }\n}\n\nFlowReturn ApplicationSource::pushBuffer(const BufferPtr & buffer)\n{\n if (d->appSrc()) {\n return static_cast<FlowReturn>(gst_app_src_push_buffer(d->appSrc(), gst_buffer_ref(buffer)));\n } else {\n return FlowWrongState;\n }\n}\n\nFlowReturn ApplicationSource::endOfStream()\n{\n if (d->appSrc()) {\n return static_cast<FlowReturn>(gst_app_src_end_of_stream(d->appSrc()));\n } else {\n return FlowWrongState;\n }\n}\n\nvoid ApplicationSource::needData(uint length)\n{\n Q_UNUSED(length);\n}\n\nvoid ApplicationSource::enoughData()\n{\n}\n\nbool ApplicationSource::seekData(quint64 offset)\n{\n Q_UNUSED(offset);\n return false;\n}\n\n} \/\/namespace Utils\n} \/\/namespace QGst\n<commit_msg>src\/QGst\/Utils\/applicationsource.cpp an additional callback was added to GstAppSrcCallbacks<commit_after>\/*\n Copyright (C) 2011 Collabora Ltd. <info@collabora.co.uk>\n @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"applicationsource.h\"\n#include \"..\/elementfactory.h\"\n#include <gst\/app\/gstappsrc.h>\n\nnamespace QGst {\nnamespace Utils {\n\n#ifndef DOXYGEN_RUN\n\nstruct QTGSTREAMERUTILS_NO_EXPORT ApplicationSource::Priv\n{\npublic:\n ElementPtr m_appsrc;\n\n void lazyConstruct(ApplicationSource *self);\n void setCallbacks(ApplicationSource *self);\n\n inline GstAppSrc *appSrc()\n {\n return reinterpret_cast<GstAppSrc*>(static_cast<GstElement*>(m_appsrc));\n }\n\nprivate:\n static void need_data(GstAppSrc *src, guint length, gpointer user_data);\n static void enough_data(GstAppSrc *src, gpointer user_data);\n static gboolean seek_data(GstAppSrc *src, guint64 offset, gpointer user_data);\n\n static void need_data_noop(GstAppSrc*, guint, gpointer) {}\n static void enough_data_noop(GstAppSrc*, gpointer) {}\n static gboolean seek_data_noop(GstAppSrc*, guint64, gpointer) { return FALSE; }\n};\n\nvoid ApplicationSource::Priv::lazyConstruct(ApplicationSource *self)\n{\n if (!m_appsrc) {\n m_appsrc = QGst::ElementFactory::make(\"appsrc\");\n if (!m_appsrc) {\n qWarning() << \"Failed to construct appsrc\";\n }\n setCallbacks(self);\n }\n}\n\nvoid ApplicationSource::Priv::setCallbacks(ApplicationSource *self)\n{\n if (m_appsrc) {\n if (self) {\n static GstAppSrcCallbacks callbacks = { &need_data, &enough_data, &seek_data, NULL };\n gst_app_src_set_callbacks(appSrc(), &callbacks, self, NULL);\n } else {\n static GstAppSrcCallbacks callbacks = { &need_data_noop, &enough_data_noop, &seek_data_noop, NULL };\n gst_app_src_set_callbacks(appSrc(), &callbacks, NULL, NULL);\n }\n }\n}\n\nvoid ApplicationSource::Priv::need_data(GstAppSrc *src, guint length, gpointer user_data)\n{\n Q_UNUSED(src);\n static_cast<ApplicationSource*>(user_data)->needData(length);\n}\n\nvoid ApplicationSource::Priv::enough_data(GstAppSrc *src, gpointer user_data)\n{\n Q_UNUSED(src);\n static_cast<ApplicationSource*>(user_data)->enoughData();\n}\n\ngboolean ApplicationSource::Priv::seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)\n{\n Q_UNUSED(src);\n return static_cast<ApplicationSource*>(user_data)->seekData(offset) ? TRUE : FALSE;\n}\n\n#endif \/\/DOXYGEN_RUN\n\nApplicationSource::ApplicationSource()\n : d(new Priv)\n{\n}\n\nApplicationSource::~ApplicationSource()\n{\n d->setCallbacks(NULL); \/\/remove the callbacks from the source\n delete d;\n}\n\nElementPtr ApplicationSource::element() const\n{\n d->lazyConstruct(const_cast<ApplicationSource*>(this));\n return d->m_appsrc;\n}\n\nvoid ApplicationSource::setElement(const ElementPtr & appsrc)\n{\n Q_ASSERT(QGlib::Type::fromInstance(appsrc).isA(GST_TYPE_APP_SRC));\n d->setCallbacks(NULL); \/\/remove the callbacks from the previous source\n d->m_appsrc = appsrc;\n d->setCallbacks(this);\n}\n\nCapsPtr ApplicationSource::caps() const\n{\n CapsPtr c;\n if (d->appSrc()) {\n c = CapsPtr::wrap(gst_app_src_get_caps(d->appSrc()), false);\n }\n return c;\n}\n\nvoid ApplicationSource::setCaps(const CapsPtr & caps)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_caps(d->appSrc(), caps);\n }\n}\n\nquint64 ApplicationSource::minLatency() const\n{\n guint64 ret = -1;\n if (d->appSrc()) {\n gst_app_src_get_latency(d->appSrc(), &ret, NULL);\n }\n return ret;\n}\n\nquint64 ApplicationSource::maxLatency() const\n{\n guint64 ret = -1;\n if (d->appSrc()) {\n gst_app_src_get_latency(d->appSrc(), NULL, &ret);\n }\n return ret;\n}\n\nvoid ApplicationSource::setLatency(quint64 min, quint64 max)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_latency(d->appSrc(), min, max);\n }\n}\n\nqint64 ApplicationSource::size() const\n{\n return d->appSrc() ? gst_app_src_get_size(d->appSrc()) : -1;\n}\n\nvoid ApplicationSource::setSize(qint64 size)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_size(d->appSrc(), size);\n }\n}\n\nAppStreamType ApplicationSource::streamType() const\n{\n return d->appSrc() ? static_cast<AppStreamType>(gst_app_src_get_stream_type(d->appSrc()))\n : AppStreamTypeStream;\n}\n\nvoid ApplicationSource::setStreamType(AppStreamType type)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_stream_type(d->appSrc(), static_cast<GstAppStreamType>(type));\n }\n}\n\nquint64 ApplicationSource::maxBytes() const\n{\n return d->appSrc() ? gst_app_src_get_max_bytes(d->appSrc()) : 0;\n}\n\nvoid ApplicationSource::setMaxBytes(quint64 max)\n{\n d->lazyConstruct(this);\n if (d->appSrc()) {\n gst_app_src_set_max_bytes(d->appSrc(), max);\n }\n}\n\nbool ApplicationSource::blockEnabled() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"block\").toBool() : false;\n}\n\nvoid ApplicationSource::enableBlock(bool enable)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"block\", enable);\n }\n}\n\nbool ApplicationSource::isLive() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"is-live\").toBool() : false;\n}\n\nvoid ApplicationSource::setLive(bool islive)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"is-live\", islive);\n }\n}\n\nuint ApplicationSource::minPercent() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"min-percent\").toUInt() : 0;\n}\n\nvoid ApplicationSource::setMinPercent(uint min)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"min-percent\", min);\n }\n}\n\nFormat ApplicationSource::format() const\n{\n return d->m_appsrc ? d->m_appsrc->property(\"format\").get<Format>() : FormatBytes;\n}\n\nvoid ApplicationSource::setFormat(Format f)\n{\n d->lazyConstruct(this);\n if (d->m_appsrc) {\n d->m_appsrc->setProperty(\"format\", f);\n }\n}\n\nFlowReturn ApplicationSource::pushBuffer(const BufferPtr & buffer)\n{\n if (d->appSrc()) {\n return static_cast<FlowReturn>(gst_app_src_push_buffer(d->appSrc(), gst_buffer_ref(buffer)));\n } else {\n return FlowWrongState;\n }\n}\n\nFlowReturn ApplicationSource::endOfStream()\n{\n if (d->appSrc()) {\n return static_cast<FlowReturn>(gst_app_src_end_of_stream(d->appSrc()));\n } else {\n return FlowWrongState;\n }\n}\n\nvoid ApplicationSource::needData(uint length)\n{\n Q_UNUSED(length);\n}\n\nvoid ApplicationSource::enoughData()\n{\n}\n\nbool ApplicationSource::seekData(quint64 offset)\n{\n Q_UNUSED(offset);\n return false;\n}\n\n} \/\/namespace Utils\n} \/\/namespace QGst\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <limits>\n#include <cassert>\n#include <cmath>\n\n#include \"acmacs-base\/vector.hh\"\n#include \"acmacs-base\/transformation.hh\"\n#include \"acmacs-base\/size.hh\"\n#include \"acmacs-base\/stream.hh\"\n#include \"acmacs-base\/indexes.hh\"\n#include \"acmacs-base\/range.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n class Coordinates : public Vector\n {\n public:\n using Vector::Vector;\n\n Coordinates(Location2D loc) : Vector{loc.x(), loc.y()} {}\n Coordinates(Location3D loc) : Vector{loc.x(), loc.y(), loc.z()} {}\n\n Coordinates transform(const Transformation& aTransformation) const\n {\n return aTransformation.transform(static_cast<Location2D>(*this));\n }\n\n bool not_nan() const\n {\n return !empty() && std::all_of(begin(), end(), [](double value) -> bool { return !std::isnan(value); });\n }\n\n operator Location2D() const\n {\n assert(size() == 2);\n return {operator[](0), operator[](1)};\n }\n\n operator Location3D() const\n {\n assert(size() == 3);\n return {operator[](0), operator[](1), operator[](2)};\n }\n\n }; \/\/ class Coordinates\n\n inline std::ostream& operator<<(std::ostream& s, const Coordinates& c)\n {\n stream_internal::write_to_stream(s, c, \"[\", \"]\", \", \");\n return s;\n }\n\n \/\/ ----------------------------------------------------------------------\n\n struct Area\n {\n Coordinates min, max;\n\n Area(const Coordinates& a_min, const Coordinates& a_max) : min(a_min), max(a_max) {}\n Area(const Coordinates& a_min) : min(a_min), max(a_min) {}\n\n size_t num_dim() const { return min.size(); }\n\n void extend(const Coordinates& point)\n {\n for (size_t dim = 0; dim < num_dim(); ++dim) {\n if (point[dim] < min[dim])\n min[dim] = point[dim];\n if (point[dim] > max[dim])\n max[dim] = point[dim];\n }\n }\n\n double area() const\n {\n double result = max[0] - min[0];\n for (size_t dim = 1; dim < num_dim(); ++dim)\n result *= max[dim] - min[dim];\n return result;\n }\n\n class Iterator\n {\n private:\n double step_;\n Coordinates min_, max_, current_;\n\n friend struct Area;\n Iterator(double step, const Coordinates& a_min, const Coordinates& a_max) : step_(step), min_(a_min), max_(a_min), current_(a_min) { set_max(a_max); }\n Iterator() : step_(std::numeric_limits<double>::quiet_NaN()) {}\n\n void set_max(const Coordinates& a_max)\n {\n for (auto dim : acmacs::range(max_.size()))\n max_[dim] = min_[dim] + std::ceil((a_max[dim] - min_[dim]) \/ step_) * step_;\n }\n\n public:\n bool operator==(const Iterator& rhs) const\n {\n if (std::isnan(rhs.step_))\n return current_[0] > max_[0];\n else if (std::isnan(step_))\n return rhs.current_[0] > rhs.max_[0];\n else\n throw std::runtime_error(\"cannot compare Area::Iterators\");\n }\n\n bool operator!=(const Iterator& rhs) const { return !operator==(rhs); }\n const Coordinates& operator*() const { return current_; }\n const Coordinates* operator->() const { return ¤t_; }\n\n const Iterator& operator++()\n {\n if (current_[0] <= max_[0]) {\n for (auto dim : acmacs::range(current_.size())) {\n current_[dim] += step_;\n if (current_[dim] <= max_[dim]) {\n std::copy(min_.begin(), min_.begin() + static_cast<Coordinates::difference_type>(dim), current_.begin());\n break;\n }\n }\n }\n return *this;\n }\n };\n\n Iterator begin(double step) const { return Iterator(step, min, max); }\n Iterator end() const { return Iterator{}; }\n\n }; \/\/ struct Area\n\n inline std::string to_string(const Area& area, size_t precision = 32) { return to_string(area.min, precision) + ' ' + to_string(area.max, precision); }\n\n inline std::ostream& operator<<(std::ostream& s, const Area& area) { return s << to_string(area, 4); }\n\n \/\/ ----------------------------------------------------------------------\n\n class LayoutInterface;\n\n class LayoutConstIterator\n {\n public:\n Coordinates operator*() const;\n auto& operator++()\n {\n ++point_no_;\n \/\/ do not skip disconnected points to avoid jumping over end iterator\n return *this;\n }\n bool operator==(const LayoutConstIterator& rhs) const\n {\n if (&parent_ != &rhs.parent_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for different layouts\");\n return point_no_ == rhs.point_no_;\n }\n bool operator!=(const LayoutConstIterator& rhs) const { return !operator==(rhs); }\n\n private:\n const LayoutInterface& parent_;\n mutable size_t point_no_;\n\n LayoutConstIterator(const LayoutInterface& parent, size_t point_no) : parent_{parent}, point_no_{point_no} {}\n\n friend class LayoutInterface;\n\n }; \/\/ class LayoutConstIterator\n\n class LayoutDimensionConstIterator\n {\n public:\n double operator*() const;\n auto& operator++()\n {\n ++point_no_;\n \/\/ do not skip disconnected points to avoid jumping over end iterator\n return *this;\n }\n bool operator==(const LayoutDimensionConstIterator& rhs) const\n {\n if (&parent_ != &rhs.parent_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for different layouts\");\n if (dimension_no_ != rhs.dimension_no_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for dimensions\");\n return point_no_ == rhs.point_no_;\n }\n bool operator!=(const LayoutDimensionConstIterator& rhs) const { return !operator==(rhs); }\n\n private:\n const LayoutInterface& parent_;\n mutable size_t point_no_;\n const size_t dimension_no_;\n\n LayoutDimensionConstIterator(const LayoutInterface& parent, size_t point_no, size_t dimension_no) : parent_{parent}, point_no_{point_no}, dimension_no_{dimension_no} {}\n\n friend class LayoutInterface;\n\n }; \/\/ class LayoutDimensionConstIterator\n\n \/\/ ----------------------------------------------------------------------\n\n class LayoutInterface\n {\n public:\n LayoutInterface() = default;\n LayoutInterface(const LayoutInterface&) = default;\n virtual ~LayoutInterface() = default;\n LayoutInterface& operator=(const LayoutInterface&) = default;\n\n virtual size_t number_of_points() const noexcept = 0;\n virtual size_t number_of_dimensions() const noexcept = 0;\n virtual const Coordinates operator[](size_t aPointNo) const = 0;\n const Coordinates get(size_t aPointNo) const { return operator[](aPointNo); }\n Coordinates& operator[](size_t) = delete; \/\/ use set()!\n virtual double coordinate(size_t aPointNo, size_t aDimensionNo) const = 0;\n double operator()(size_t aPointNo, size_t aDimensionNo) const { return coordinate(aPointNo, aDimensionNo); }\n virtual bool point_has_coordinates(size_t point_no) const = 0;\n virtual std::vector<double> as_flat_vector_double() const = 0;\n virtual std::vector<float> as_flat_vector_float() const = 0;\n\n double distance(size_t p1, size_t p2, double no_distance = std::numeric_limits<double>::quiet_NaN()) const\n {\n const auto c1 = operator[](p1);\n const auto c2 = operator[](p2);\n return (c1.not_nan() && c2.not_nan()) ? c1.distance(c2) : no_distance;\n }\n\n \/\/ returns indexes for min points for each dimension and max points for each dimension\n virtual std::pair<std::vector<size_t>, std::vector<size_t>> min_max_point_indexes() const;\n \/\/ returns boundary coordinates (min and max)\n virtual Area area() const; \/\/ for all points\n virtual Area area(const std::vector<size_t>& points) const; \/\/ just for the specified point indexes\n virtual LayoutInterface* transform(const Transformation& aTransformation) const;\n virtual Coordinates centroid() const;\n\n virtual void set(size_t aPointNo, const acmacs::Vector& aCoordinates) = 0;\n virtual void set(size_t point_no, size_t dimension_no, double value) = 0;\n\n LayoutConstIterator begin() const { return {*this, 0}; }\n LayoutConstIterator end() const { return {*this, number_of_points()}; }\n LayoutConstIterator begin_antigens(size_t \/*number_of_antigens*\/) const { return {*this, 0}; }\n LayoutConstIterator end_antigens(size_t number_of_antigens) const { return {*this, number_of_antigens}; }\n LayoutConstIterator begin_sera(size_t number_of_antigens) const { return {*this, number_of_antigens}; }\n LayoutConstIterator end_sera(size_t \/*number_of_antigens*\/) const { return {*this, number_of_points()}; }\n\n LayoutDimensionConstIterator begin_dimension(size_t dimension_no) const { return {*this, 0, dimension_no}; }\n LayoutDimensionConstIterator end_dimension(size_t dimension_no) const { return {*this, number_of_points(), dimension_no}; }\n LayoutDimensionConstIterator begin_antigens_dimension(size_t \/*number_of_antigens*\/, size_t dimension_no) const { return {*this, 0, dimension_no}; }\n LayoutDimensionConstIterator end_antigens_dimension(size_t number_of_antigens, size_t dimension_no) const { return {*this, number_of_antigens, dimension_no}; }\n LayoutDimensionConstIterator begin_sera_dimension(size_t number_of_antigens, size_t dimension_no) const { return {*this, number_of_antigens, dimension_no}; }\n LayoutDimensionConstIterator end_sera_dimension(size_t \/*number_of_antigens*\/, size_t dimension_no) const { return {*this, number_of_points(), dimension_no}; }\n\n }; \/\/ class LayoutInterface\n\n inline std::ostream& operator<<(std::ostream& s, const LayoutInterface& aLayout)\n {\n s << \"Layout [\";\n for (size_t no = 0; no < aLayout.number_of_points(); ++no)\n s << aLayout[no] << ' ';\n s << ']';\n return s;\n }\n\n inline Coordinates LayoutConstIterator::operator*() const\n {\n while (point_no_ < parent_.number_of_points() && !parent_.point_has_coordinates(point_no_))\n ++point_no_; \/\/ skip disconnected points\n return parent_.get(point_no_);\n }\n\n inline double LayoutDimensionConstIterator::operator*() const\n {\n while (point_no_ < parent_.number_of_points() && !parent_.point_has_coordinates(point_no_))\n ++point_no_; \/\/ skip disconnected points\n return parent_.coordinate(point_no_, dimension_no_);\n }\n\n \/\/ ----------------------------------------------------------------------\n\n class Layout : public virtual LayoutInterface, public std::vector<double>\n {\n public:\n using Vec = std::vector<double>;\n\n Layout() = default;\n Layout(const Layout&) = default;\n Layout(size_t aNumberOfPoints, size_t aNumberOfDimensions) : Vec(aNumberOfPoints * aNumberOfDimensions, std::numeric_limits<double>::quiet_NaN()), number_of_dimensions_{aNumberOfDimensions} {}\n Layout(size_t aNumberOfDimensions, const double* first, const double* last) : Vec(first, last), number_of_dimensions_{aNumberOfDimensions} {}\n Layout(const LayoutInterface& aSource) : Vec(aSource.as_flat_vector_double()), number_of_dimensions_{aSource.number_of_dimensions()} {}\n Layout(const LayoutInterface& aSource, const std::vector<size_t>& aIndexes); \/\/ make layout by subsetting source\n Layout& operator=(const Layout&) = default;\n\n size_t number_of_points() const noexcept override { return size() \/ number_of_dimensions_; }\n size_t number_of_dimensions() const noexcept override { return number_of_dimensions_; }\n\n void change_number_of_dimensions(size_t num_dim, bool allow_dimensions_increase = false)\n {\n if (!allow_dimensions_increase && num_dim >= number_of_dimensions_) {\n throw std::runtime_error(\"Layout::change_number_of_dimensions: dimensions increase: \" + std::to_string(number_of_dimensions_) + \" --> \" + std::to_string(num_dim));\n \/\/ std::cerr << \"WARNING: Layout::change_number_of_dimensions: \" << number_of_dimensions_ << \" --> \" << num_dim << '\\n';\n }\n resize(number_of_points() * num_dim);\n number_of_dimensions_ = num_dim;\n }\n\n const Coordinates operator[](size_t aPointNo) const override\n {\n return {Vec::begin() + static_cast<difference_type>(aPointNo * number_of_dimensions_), Vec::begin() + static_cast<difference_type>((aPointNo + 1) * number_of_dimensions_)};\n }\n\n double coordinate(size_t aPointNo, size_t aDimensionNo) const override { return at(aPointNo * number_of_dimensions_ + aDimensionNo); }\n bool point_has_coordinates(size_t point_no) const override { return !std::isnan(coordinate(point_no, 0)); }\n std::vector<double> as_flat_vector_double() const override { return *this; }\n std::vector<float> as_flat_vector_float() const override { return {Vec::begin(), Vec::end()}; }\n\n void set(size_t aPointNo, const acmacs::Vector& aCoordinates) override\n {\n std::copy(aCoordinates.begin(), aCoordinates.end(), Vec::begin() + static_cast<decltype(Vec::begin())::difference_type>(aPointNo * number_of_dimensions()));\n }\n\n void set_nan(size_t aPointNo)\n {\n const auto first{Vec::begin() + static_cast<difference_type>(aPointNo * number_of_dimensions())}, last{first + static_cast<difference_type>(number_of_dimensions())};\n std::for_each(first, last, [](auto& target) { target = std::numeric_limits<std::decay_t<decltype(target)>>::quiet_NaN(); });\n }\n\n virtual void set(size_t point_no, size_t dimension_no, double value) override { Vec::operator[](point_no* number_of_dimensions() + dimension_no) = value; }\n\n void remove_points(const ReverseSortedIndexes& indexes, size_t base)\n {\n for (const auto index : indexes) {\n const auto first = Vec::begin() + static_cast<difference_type>((index + base) * number_of_dimensions_);\n erase(first, first + static_cast<difference_type>(number_of_dimensions_));\n }\n }\n\n void insert_point(size_t before, size_t base)\n {\n insert(Vec::begin() + static_cast<difference_type>((before + base) * number_of_dimensions_), number_of_dimensions_, std::numeric_limits<double>::quiet_NaN());\n }\n\n std::vector<std::pair<double, double>> minmax() const;\n\n private:\n size_t number_of_dimensions_;\n\n }; \/\/ class Layout\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>Coordinates::mean_with()<commit_after>#pragma once\n\n#include <limits>\n#include <cassert>\n#include <cmath>\n\n#include \"acmacs-base\/vector.hh\"\n#include \"acmacs-base\/transformation.hh\"\n#include \"acmacs-base\/size.hh\"\n#include \"acmacs-base\/stream.hh\"\n#include \"acmacs-base\/indexes.hh\"\n#include \"acmacs-base\/range.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n class Coordinates : public Vector\n {\n public:\n using Vector::Vector;\n\n Coordinates(Location2D loc) : Vector{loc.x(), loc.y()} {}\n Coordinates(Location3D loc) : Vector{loc.x(), loc.y(), loc.z()} {}\n\n Coordinates transform(const Transformation& aTransformation) const\n {\n return aTransformation.transform(static_cast<Location2D>(*this));\n }\n\n bool not_nan() const\n {\n return !empty() && std::all_of(begin(), end(), [](double value) -> bool { return !std::isnan(value); });\n }\n\n operator Location2D() const\n {\n assert(size() == 2);\n return {operator[](0), operator[](1)};\n }\n\n operator Location3D() const\n {\n assert(size() == 3);\n return {operator[](0), operator[](1), operator[](2)};\n }\n\n Coordinates& mean_with(const Coordinates& another)\n {\n for (size_t dim = 0; dim < size(); ++dim)\n (*this)[dim] = ((*this)[dim] + another[dim]) \/ 2.0;\n return *this;\n }\n\n }; \/\/ class Coordinates\n\n inline std::ostream& operator<<(std::ostream& s, const Coordinates& c)\n {\n stream_internal::write_to_stream(s, c, \"[\", \"]\", \", \");\n return s;\n }\n\n \/\/ ----------------------------------------------------------------------\n\n struct Area\n {\n Coordinates min, max;\n\n Area(const Coordinates& a_min, const Coordinates& a_max) : min(a_min), max(a_max) {}\n Area(const Coordinates& a_min) : min(a_min), max(a_min) {}\n\n size_t num_dim() const { return min.size(); }\n\n void extend(const Coordinates& point)\n {\n for (size_t dim = 0; dim < num_dim(); ++dim) {\n if (point[dim] < min[dim])\n min[dim] = point[dim];\n if (point[dim] > max[dim])\n max[dim] = point[dim];\n }\n }\n\n double area() const\n {\n double result = max[0] - min[0];\n for (size_t dim = 1; dim < num_dim(); ++dim)\n result *= max[dim] - min[dim];\n return result;\n }\n\n class Iterator\n {\n private:\n double step_;\n Coordinates min_, max_, current_;\n\n friend struct Area;\n Iterator(double step, const Coordinates& a_min, const Coordinates& a_max) : step_(step), min_(a_min), max_(a_min), current_(a_min) { set_max(a_max); }\n Iterator() : step_(std::numeric_limits<double>::quiet_NaN()) {}\n\n void set_max(const Coordinates& a_max)\n {\n for (auto dim : acmacs::range(max_.size()))\n max_[dim] = min_[dim] + std::ceil((a_max[dim] - min_[dim]) \/ step_) * step_;\n }\n\n public:\n bool operator==(const Iterator& rhs) const\n {\n if (std::isnan(rhs.step_))\n return current_[0] > max_[0];\n else if (std::isnan(step_))\n return rhs.current_[0] > rhs.max_[0];\n else\n throw std::runtime_error(\"cannot compare Area::Iterators\");\n }\n\n bool operator!=(const Iterator& rhs) const { return !operator==(rhs); }\n const Coordinates& operator*() const { return current_; }\n const Coordinates* operator->() const { return ¤t_; }\n\n const Iterator& operator++()\n {\n if (current_[0] <= max_[0]) {\n for (auto dim : acmacs::range(current_.size())) {\n current_[dim] += step_;\n if (current_[dim] <= max_[dim]) {\n std::copy(min_.begin(), min_.begin() + static_cast<Coordinates::difference_type>(dim), current_.begin());\n break;\n }\n }\n }\n return *this;\n }\n };\n\n Iterator begin(double step) const { return Iterator(step, min, max); }\n Iterator end() const { return Iterator{}; }\n\n }; \/\/ struct Area\n\n inline std::string to_string(const Area& area, size_t precision = 32) { return to_string(area.min, precision) + ' ' + to_string(area.max, precision); }\n\n inline std::ostream& operator<<(std::ostream& s, const Area& area) { return s << to_string(area, 4); }\n\n \/\/ ----------------------------------------------------------------------\n\n class LayoutInterface;\n\n class LayoutConstIterator\n {\n public:\n Coordinates operator*() const;\n auto& operator++()\n {\n ++point_no_;\n \/\/ do not skip disconnected points to avoid jumping over end iterator\n return *this;\n }\n bool operator==(const LayoutConstIterator& rhs) const\n {\n if (&parent_ != &rhs.parent_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for different layouts\");\n return point_no_ == rhs.point_no_;\n }\n bool operator!=(const LayoutConstIterator& rhs) const { return !operator==(rhs); }\n\n private:\n const LayoutInterface& parent_;\n mutable size_t point_no_;\n\n LayoutConstIterator(const LayoutInterface& parent, size_t point_no) : parent_{parent}, point_no_{point_no} {}\n\n friend class LayoutInterface;\n\n }; \/\/ class LayoutConstIterator\n\n class LayoutDimensionConstIterator\n {\n public:\n double operator*() const;\n auto& operator++()\n {\n ++point_no_;\n \/\/ do not skip disconnected points to avoid jumping over end iterator\n return *this;\n }\n bool operator==(const LayoutDimensionConstIterator& rhs) const\n {\n if (&parent_ != &rhs.parent_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for different layouts\");\n if (dimension_no_ != rhs.dimension_no_)\n throw std::runtime_error(\"LayoutDimensionConstIterator: cannot compare iterators for dimensions\");\n return point_no_ == rhs.point_no_;\n }\n bool operator!=(const LayoutDimensionConstIterator& rhs) const { return !operator==(rhs); }\n\n private:\n const LayoutInterface& parent_;\n mutable size_t point_no_;\n const size_t dimension_no_;\n\n LayoutDimensionConstIterator(const LayoutInterface& parent, size_t point_no, size_t dimension_no) : parent_{parent}, point_no_{point_no}, dimension_no_{dimension_no} {}\n\n friend class LayoutInterface;\n\n }; \/\/ class LayoutDimensionConstIterator\n\n \/\/ ----------------------------------------------------------------------\n\n class LayoutInterface\n {\n public:\n LayoutInterface() = default;\n LayoutInterface(const LayoutInterface&) = default;\n virtual ~LayoutInterface() = default;\n LayoutInterface& operator=(const LayoutInterface&) = default;\n\n virtual size_t number_of_points() const noexcept = 0;\n virtual size_t number_of_dimensions() const noexcept = 0;\n virtual const Coordinates operator[](size_t aPointNo) const = 0;\n const Coordinates get(size_t aPointNo) const { return operator[](aPointNo); }\n Coordinates& operator[](size_t) = delete; \/\/ use set()!\n virtual double coordinate(size_t aPointNo, size_t aDimensionNo) const = 0;\n double operator()(size_t aPointNo, size_t aDimensionNo) const { return coordinate(aPointNo, aDimensionNo); }\n virtual bool point_has_coordinates(size_t point_no) const = 0;\n virtual std::vector<double> as_flat_vector_double() const = 0;\n virtual std::vector<float> as_flat_vector_float() const = 0;\n\n double distance(size_t p1, size_t p2, double no_distance = std::numeric_limits<double>::quiet_NaN()) const\n {\n const auto c1 = operator[](p1);\n const auto c2 = operator[](p2);\n return (c1.not_nan() && c2.not_nan()) ? c1.distance(c2) : no_distance;\n }\n\n \/\/ returns indexes for min points for each dimension and max points for each dimension\n virtual std::pair<std::vector<size_t>, std::vector<size_t>> min_max_point_indexes() const;\n \/\/ returns boundary coordinates (min and max)\n virtual Area area() const; \/\/ for all points\n virtual Area area(const std::vector<size_t>& points) const; \/\/ just for the specified point indexes\n virtual LayoutInterface* transform(const Transformation& aTransformation) const;\n virtual Coordinates centroid() const;\n\n virtual void set(size_t aPointNo, const acmacs::Vector& aCoordinates) = 0;\n virtual void set(size_t point_no, size_t dimension_no, double value) = 0;\n\n LayoutConstIterator begin() const { return {*this, 0}; }\n LayoutConstIterator end() const { return {*this, number_of_points()}; }\n LayoutConstIterator begin_antigens(size_t \/*number_of_antigens*\/) const { return {*this, 0}; }\n LayoutConstIterator end_antigens(size_t number_of_antigens) const { return {*this, number_of_antigens}; }\n LayoutConstIterator begin_sera(size_t number_of_antigens) const { return {*this, number_of_antigens}; }\n LayoutConstIterator end_sera(size_t \/*number_of_antigens*\/) const { return {*this, number_of_points()}; }\n\n LayoutDimensionConstIterator begin_dimension(size_t dimension_no) const { return {*this, 0, dimension_no}; }\n LayoutDimensionConstIterator end_dimension(size_t dimension_no) const { return {*this, number_of_points(), dimension_no}; }\n LayoutDimensionConstIterator begin_antigens_dimension(size_t \/*number_of_antigens*\/, size_t dimension_no) const { return {*this, 0, dimension_no}; }\n LayoutDimensionConstIterator end_antigens_dimension(size_t number_of_antigens, size_t dimension_no) const { return {*this, number_of_antigens, dimension_no}; }\n LayoutDimensionConstIterator begin_sera_dimension(size_t number_of_antigens, size_t dimension_no) const { return {*this, number_of_antigens, dimension_no}; }\n LayoutDimensionConstIterator end_sera_dimension(size_t \/*number_of_antigens*\/, size_t dimension_no) const { return {*this, number_of_points(), dimension_no}; }\n\n }; \/\/ class LayoutInterface\n\n inline std::ostream& operator<<(std::ostream& s, const LayoutInterface& aLayout)\n {\n s << \"Layout [\";\n for (size_t no = 0; no < aLayout.number_of_points(); ++no)\n s << aLayout[no] << ' ';\n s << ']';\n return s;\n }\n\n inline Coordinates LayoutConstIterator::operator*() const\n {\n while (point_no_ < parent_.number_of_points() && !parent_.point_has_coordinates(point_no_))\n ++point_no_; \/\/ skip disconnected points\n return parent_.get(point_no_);\n }\n\n inline double LayoutDimensionConstIterator::operator*() const\n {\n while (point_no_ < parent_.number_of_points() && !parent_.point_has_coordinates(point_no_))\n ++point_no_; \/\/ skip disconnected points\n return parent_.coordinate(point_no_, dimension_no_);\n }\n\n \/\/ ----------------------------------------------------------------------\n\n class Layout : public virtual LayoutInterface, public std::vector<double>\n {\n public:\n using Vec = std::vector<double>;\n\n Layout() = default;\n Layout(const Layout&) = default;\n Layout(size_t aNumberOfPoints, size_t aNumberOfDimensions) : Vec(aNumberOfPoints * aNumberOfDimensions, std::numeric_limits<double>::quiet_NaN()), number_of_dimensions_{aNumberOfDimensions} {}\n Layout(size_t aNumberOfDimensions, const double* first, const double* last) : Vec(first, last), number_of_dimensions_{aNumberOfDimensions} {}\n Layout(const LayoutInterface& aSource) : Vec(aSource.as_flat_vector_double()), number_of_dimensions_{aSource.number_of_dimensions()} {}\n Layout(const LayoutInterface& aSource, const std::vector<size_t>& aIndexes); \/\/ make layout by subsetting source\n Layout& operator=(const Layout&) = default;\n\n size_t number_of_points() const noexcept override { return size() \/ number_of_dimensions_; }\n size_t number_of_dimensions() const noexcept override { return number_of_dimensions_; }\n\n void change_number_of_dimensions(size_t num_dim, bool allow_dimensions_increase = false)\n {\n if (!allow_dimensions_increase && num_dim >= number_of_dimensions_) {\n throw std::runtime_error(\"Layout::change_number_of_dimensions: dimensions increase: \" + std::to_string(number_of_dimensions_) + \" --> \" + std::to_string(num_dim));\n \/\/ std::cerr << \"WARNING: Layout::change_number_of_dimensions: \" << number_of_dimensions_ << \" --> \" << num_dim << '\\n';\n }\n resize(number_of_points() * num_dim);\n number_of_dimensions_ = num_dim;\n }\n\n const Coordinates operator[](size_t aPointNo) const override\n {\n return {Vec::begin() + static_cast<difference_type>(aPointNo * number_of_dimensions_), Vec::begin() + static_cast<difference_type>((aPointNo + 1) * number_of_dimensions_)};\n }\n\n double coordinate(size_t aPointNo, size_t aDimensionNo) const override { return at(aPointNo * number_of_dimensions_ + aDimensionNo); }\n bool point_has_coordinates(size_t point_no) const override { return !std::isnan(coordinate(point_no, 0)); }\n std::vector<double> as_flat_vector_double() const override { return *this; }\n std::vector<float> as_flat_vector_float() const override { return {Vec::begin(), Vec::end()}; }\n\n void set(size_t aPointNo, const acmacs::Vector& aCoordinates) override\n {\n std::copy(aCoordinates.begin(), aCoordinates.end(), Vec::begin() + static_cast<decltype(Vec::begin())::difference_type>(aPointNo * number_of_dimensions()));\n }\n\n void set_nan(size_t aPointNo)\n {\n const auto first{Vec::begin() + static_cast<difference_type>(aPointNo * number_of_dimensions())}, last{first + static_cast<difference_type>(number_of_dimensions())};\n std::for_each(first, last, [](auto& target) { target = std::numeric_limits<std::decay_t<decltype(target)>>::quiet_NaN(); });\n }\n\n virtual void set(size_t point_no, size_t dimension_no, double value) override { Vec::operator[](point_no* number_of_dimensions() + dimension_no) = value; }\n\n void remove_points(const ReverseSortedIndexes& indexes, size_t base)\n {\n for (const auto index : indexes) {\n const auto first = Vec::begin() + static_cast<difference_type>((index + base) * number_of_dimensions_);\n erase(first, first + static_cast<difference_type>(number_of_dimensions_));\n }\n }\n\n void insert_point(size_t before, size_t base)\n {\n insert(Vec::begin() + static_cast<difference_type>((before + base) * number_of_dimensions_), number_of_dimensions_, std::numeric_limits<double>::quiet_NaN());\n }\n\n std::vector<std::pair<double, double>> minmax() const;\n\n private:\n size_t number_of_dimensions_;\n\n }; \/\/ class Layout\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include \"astutil.h\"\n#include \"beautify.h\"\n#include \"driver.h\"\n#include \"expr.h\"\n#include \"files.h\"\n#include \"mysystem.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"symscope.h\"\n\nstatic int max(int a, int b) {\n return (a >= b) ? a : b;\n}\n\nstatic void setOrder(Map<ClassType*,int>& order, int& maxOrder, ClassType* ct);\n\nstatic int\ngetOrder(Map<ClassType*,int>& order, int& maxOrder,\n ClassType* ct, Vec<ClassType*>& visit) {\n if (visit.set_in(ct))\n return 0;\n visit.set_add(ct);\n if (order.get(ct))\n return order.get(ct);\n int i = 0;\n for_fields(field, ct) {\n if (ClassType* fct = dynamic_cast<ClassType*>(field->type)) {\n if (!visit.set_in(fct) && fct->classTag != CLASS_CLASS)\n setOrder(order, maxOrder, fct);\n i = max(i, getOrder(order, maxOrder, fct, visit));\n }\n }\n return i + (ct->classTag != CLASS_CLASS);\n}\n\n\nstatic void\nsetOrder(Map<ClassType*,int>& order, int& maxOrder,\n ClassType* ct) {\n if (ct->classTag == CLASS_CLASS || order.get(ct))\n return;\n int i;\n Vec<ClassType*> visit;\n i = getOrder(order, maxOrder, ct, visit);\n order.put(ct, i);\n if (i > maxOrder)\n maxOrder = i;\n}\n\n\n#define STRSUB(x) \\\n *ch = '\\0'; \\\n sym->cname = stringcat(sym->cname, x, ch+1); \\\n ch = sym->cname\n\nstatic void legalizeCName(Symbol* sym) {\n for (char* ch = sym->cname; *ch != '\\0'; ch++) {\n switch (*ch) {\n case '>': STRSUB(\"_GREATER_\"); break;\n case '<': STRSUB(\"_LESS_\"); break;\n case '=': STRSUB(\"_EQUAL_\"); break;\n case '*': STRSUB(\"_ASTERISK_\"); break;\n case '\/': STRSUB(\"_SLASH_\"); break;\n case '%': STRSUB(\"_PERCENT_\"); break;\n case '+': STRSUB(\"_PLUS_\"); break;\n case '-': STRSUB(\"_HYPHEN_\"); break;\n case '^': STRSUB(\"_CARET_\"); break;\n case '&': STRSUB(\"_AMPERSAND_\"); break;\n case '|': STRSUB(\"_BAR_\"); break;\n case '!': STRSUB(\"_EXCLAMATION_\"); break;\n case '#': STRSUB(\"_POUND_\"); break;\n case '?': STRSUB(\"_QUESTION_\"); break;\n case '~': STRSUB(\"_TILDA_\"); break;\n default: break;\n }\n }\n}\n\nstatic void codegen_header(void) {\n ChainHashMap<char*, StringHashFns, int> cnames;\n Vec<TypeSymbol*> typeSymbols;\n Vec<FnSymbol*> fnSymbols;\n Vec<VarSymbol*> varSymbols;\n\n chpl_main->addPragma(\"rename _chpl_main\");\n\n cnames.put(\"abs\", 1);\n cnames.put(\"exit\", 1);\n cnames.put(\"_init\", 1);\n cnames.put(\"stdin\", 1);\n cnames.put(\"close\", 1);\n cnames.put(\"fwrite\", 1);\n cnames.put(\"fread\", 1);\n cnames.put(\"main\", 1);\n cnames.put(\"open\", 1);\n cnames.put(\"printf\", 1);\n cnames.put(\"quad\", 1);\n cnames.put(\"read\", 1);\n cnames.put(\"sleep\", 1);\n cnames.put(\"stderr\", 1);\n cnames.put(\"stdout\", 1);\n cnames.put(\"write\", 1);\n cnames.put(\"y1\", 1); \/\/ this is ridiculous...\n cnames.put(\"log2\", 1);\n cnames.put(\"remove\", 1);\n cnames.put(\"fprintf\", 1);\n cnames.put(\"clone\", 1);\n cnames.put(\"new\", 1);\n\n forv_Vec(BaseAST, ast, gAsts) {\n if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {\n Symbol* sym = def->sym;\n\n if (sym->name == sym->cname)\n sym->cname = stringcpy(sym->name);\n\n if (char* pragma = sym->hasPragmaPrefix(\"rename\"))\n sym->cname = stringcpy(pragma+7);\n\n if (VarSymbol* vs = dynamic_cast<VarSymbol*>(ast))\n if (vs->immediate)\n continue;\n\n legalizeCName(sym);\n\n \/\/ mangle symbol that is neither field nor formal if the symbol's\n \/\/ name has already been encountered\n if (!dynamic_cast<ArgSymbol*>(sym) &&\n !dynamic_cast<UnresolvedSymbol*>(sym) &&\n !dynamic_cast<ClassType*>(sym->parentScope->astParent) &&\n cnames.get(sym->cname))\n sym->cname = stringcat(\"_\", intstring(sym->id), \"_\", sym->cname);\n\n cnames.put(sym->cname, 1);\n \n if (TypeSymbol* typeSymbol = dynamic_cast<TypeSymbol*>(sym)) {\n typeSymbols.add(typeSymbol);\n } else if (FnSymbol* fnSymbol = dynamic_cast<FnSymbol*>(sym)) {\n fnSymbols.add(fnSymbol);\n } else if (VarSymbol* varSymbol = dynamic_cast<VarSymbol*>(sym)) {\n if (varSymbol->parentScope->parent == rootScope)\n varSymbols.add(varSymbol);\n }\n }\n }\n\n qsort(varSymbols.v, varSymbols.n, sizeof(varSymbols.v[0]), compareSymbol);\n qsort(typeSymbols.v, typeSymbols.n, sizeof(typeSymbols.v[0]), compareSymbol);\n qsort(fnSymbols.v, fnSymbols.n, sizeof(fnSymbols.v[0]), compareSymbol);\n\n fileinfo header;\n openCFile(&header, \"_chpl_header\", \"h\");\n FILE* outfile = header.fptr;\n\n fprintf(outfile, \"#include \\\"stdchpl.h\\\"\\n\");\n fprintf(outfile, \"\\n\/*** Class Reference Types ***\/\\n\\n\");\n\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n typeSymbol->codegenPrototype(outfile);\n }\n\n \/\/ codegen enumerated types\n fprintf(outfile, \"\\n\/*** Enumerated Types ***\/\\n\\n\");\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n if (dynamic_cast<EnumType*>(typeSymbol->type))\n typeSymbol->codegenDef(outfile);\n }\n\n \/\/ order records\/unions topologically\n \/\/ (int, int) before (int, (int, int))\n Map<ClassType*,int> order;\n int maxOrder = 0;\n forv_Vec(TypeSymbol, ts, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))\n setOrder(order, maxOrder, ct);\n }\n\n \/\/ debug\n\/\/ for (int i = 0; i < order.n; i++) {\n\/\/ if (order.v[i].key && order.v[i].value) {\n\/\/ printf(\"%d: %s\\n\", order.v[i].value, order.v[i].key->symbol->name);\n\/\/ }\n\/\/ }\n\/\/ printf(\"%d\\n\", maxOrder);\n\n \/\/ codegen records\/unions in topological order\n fprintf(outfile, \"\\n\/*** Records and Unions (Hierarchically) ***\/\\n\\n\");\n for (int i = 1; i <= maxOrder; i++) {\n forv_Vec(TypeSymbol, ts, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))\n if (order.get(ct) == i)\n ts->codegenDef(outfile);\n }\n }\n\n \/\/ codegen remaining types\n fprintf(outfile, \"\/*** Classes ***\/\\n\\n\");\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(typeSymbol->type))\n if (ct->classTag != CLASS_CLASS)\n continue;\n if (dynamic_cast<EnumType*>(typeSymbol->type))\n continue;\n typeSymbol->codegenDef(outfile);\n }\n\n fprintf(outfile, \"\/*** Function Prototypes ***\/\\n\\n\");\n forv_Vec(FnSymbol, fnSymbol, fnSymbols) {\n fnSymbol->codegenPrototype(outfile);\n }\n\n fprintf(outfile, \"\\n\/*** Global Variables ***\/\\n\\n\");\n forv_Vec(VarSymbol, varSymbol, varSymbols) {\n varSymbol->codegenDef(outfile);\n }\n closeCFile(&header);\n beautify(&header);\n}\n\n\nstatic void\ncodegen_config(FILE* outfile) {\n fprintf(outfile, \"void CreateConfigVarTable(void) {\\n\");\n fprintf(outfile, \"initConfigVarTable();\\n\");\n\n forv_Vec(BaseAST, ast, gAsts) {\n if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {\n VarSymbol* var = dynamic_cast<VarSymbol*>(def->sym);\n if (var && var->varClass == VAR_CONFIG) {\n fprintf(outfile, \"installConfigVar(\\\"%s\\\", \\\"\", var->name);\n fprintf(outfile, var->type->symbol->name);\n fprintf(outfile, \"\\\", \\\"%s\\\");\\n\", var->getModule()->name);\n }\n }\n }\n\n fprintf(outfile, \"if (askedToParseArgs()) {\\n\");\n fprintf(outfile, \" parseConfigArgs();\\n\");\n fprintf(outfile, \"}\\n\");\n\n fprintf(outfile, \"if (askedToPrintHelpMessage()) {\\n\");\n fprintf(outfile, \" printHelpTable();\\n\");\n fprintf(outfile, \" printConfigVarTable();\\n\");\n fprintf(outfile, \"}\\n\");\n \n fprintf(outfile, \"}\\n\");\n}\n\n\nvoid codegen(void) {\n if (no_codegen)\n return;\n\n fileinfo mainfile;\n openCFile(&mainfile, \"_main\", \"c\");\n fprintf(mainfile.fptr, \"#include \\\"_chpl_header.h\\\"\\n\");\n\n codegen_makefile(&mainfile);\n\n codegen_header();\n\n codegen_config(mainfile.fptr);\n\n forv_Vec(ModuleSymbol, currentModule, allModules) {\n mysystem(stringcat(\"# codegen-ing module\", currentModule->name),\n \"generating comment for --print-commands option\");\n\n fileinfo modulefile;\n openCFile(&modulefile, currentModule->name, \"c\");\n currentModule->codegenDef(modulefile.fptr);\n closeCFile(&modulefile);\n fprintf(mainfile.fptr, \"#include \\\"%s%s\\\"\\n\", currentModule->name, \".c\");\n beautify(&modulefile);\n }\n\n closeCFile(&mainfile);\n beautify(&mainfile);\n makeBinary();\n}\n<commit_msg><commit_after>#include <stdio.h>\n#include \"astutil.h\"\n#include \"beautify.h\"\n#include \"driver.h\"\n#include \"expr.h\"\n#include \"files.h\"\n#include \"mysystem.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"symscope.h\"\n\nstatic int max(int a, int b) {\n return (a >= b) ? a : b;\n}\n\nstatic void setOrder(Map<ClassType*,int>& order, int& maxOrder, ClassType* ct);\n\nstatic int\ngetOrder(Map<ClassType*,int>& order, int& maxOrder,\n ClassType* ct, Vec<ClassType*>& visit) {\n if (visit.set_in(ct))\n return 0;\n visit.set_add(ct);\n if (order.get(ct))\n return order.get(ct);\n int i = 0;\n for_fields(field, ct) {\n if (ClassType* fct = dynamic_cast<ClassType*>(field->type)) {\n if (!visit.set_in(fct) && fct->classTag != CLASS_CLASS)\n setOrder(order, maxOrder, fct);\n i = max(i, getOrder(order, maxOrder, fct, visit));\n }\n }\n return i + (ct->classTag != CLASS_CLASS);\n}\n\n\nstatic void\nsetOrder(Map<ClassType*,int>& order, int& maxOrder,\n ClassType* ct) {\n if (ct->classTag == CLASS_CLASS || order.get(ct))\n return;\n int i;\n Vec<ClassType*> visit;\n i = getOrder(order, maxOrder, ct, visit);\n order.put(ct, i);\n if (i > maxOrder)\n maxOrder = i;\n}\n\n\n#define STRSUB(x) \\\n *ch = '\\0'; \\\n sym->cname = stringcat(sym->cname, x, ch+1); \\\n ch = sym->cname\n\nstatic void legalizeCName(Symbol* sym) {\n for (char* ch = sym->cname; *ch != '\\0'; ch++) {\n switch (*ch) {\n case '>': STRSUB(\"_GREATER_\"); break;\n case '<': STRSUB(\"_LESS_\"); break;\n case '=': STRSUB(\"_EQUAL_\"); break;\n case '*': STRSUB(\"_ASTERISK_\"); break;\n case '\/': STRSUB(\"_SLASH_\"); break;\n case '%': STRSUB(\"_PERCENT_\"); break;\n case '+': STRSUB(\"_PLUS_\"); break;\n case '-': STRSUB(\"_HYPHEN_\"); break;\n case '^': STRSUB(\"_CARET_\"); break;\n case '&': STRSUB(\"_AMPERSAND_\"); break;\n case '|': STRSUB(\"_BAR_\"); break;\n case '!': STRSUB(\"_EXCLAMATION_\"); break;\n case '#': STRSUB(\"_POUND_\"); break;\n case '?': STRSUB(\"_QUESTION_\"); break;\n case '~': STRSUB(\"_TILDA_\"); break;\n default: break;\n }\n }\n}\n\nstatic void codegen_header(void) {\n ChainHashMap<char*, StringHashFns, int> cnames;\n Vec<TypeSymbol*> typeSymbols;\n Vec<FnSymbol*> fnSymbols;\n Vec<VarSymbol*> varSymbols;\n\n chpl_main->addPragma(\"rename _chpl_main\");\n\n cnames.put(\"abs\", 1);\n cnames.put(\"exit\", 1);\n cnames.put(\"_init\", 1);\n cnames.put(\"stdin\", 1);\n cnames.put(\"close\", 1);\n cnames.put(\"fwrite\", 1);\n cnames.put(\"fread\", 1);\n cnames.put(\"main\", 1);\n cnames.put(\"open\", 1);\n cnames.put(\"printf\", 1);\n cnames.put(\"quad\", 1);\n cnames.put(\"read\", 1);\n cnames.put(\"sleep\", 1);\n cnames.put(\"stderr\", 1);\n cnames.put(\"stdout\", 1);\n cnames.put(\"write\", 1);\n cnames.put(\"y1\", 1); \/\/ this is ridiculous...\n cnames.put(\"log2\", 1);\n cnames.put(\"remove\", 1);\n cnames.put(\"fprintf\", 1);\n cnames.put(\"clone\", 1);\n cnames.put(\"new\", 1);\n\n forv_Vec(BaseAST, ast, gAsts) {\n if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {\n Symbol* sym = def->sym;\n\n if (sym->name == sym->cname)\n sym->cname = stringcpy(sym->name);\n\n if (char* pragma = sym->hasPragmaPrefix(\"rename\"))\n sym->cname = stringcpy(pragma+7);\n\n if (VarSymbol* vs = dynamic_cast<VarSymbol*>(ast))\n if (vs->immediate)\n continue;\n\n legalizeCName(sym);\n\n \/\/ mangle symbol that is neither field nor formal if the symbol's\n \/\/ name has already been encountered\n if (!dynamic_cast<ArgSymbol*>(sym) &&\n !dynamic_cast<UnresolvedSymbol*>(sym) &&\n !dynamic_cast<ClassType*>(sym->parentScope->astParent) &&\n cnames.get(sym->cname))\n sym->cname = stringcat(\"_\", sym->cname, \"_\", intstring(sym->id));\n\n cnames.put(sym->cname, 1);\n \n if (TypeSymbol* typeSymbol = dynamic_cast<TypeSymbol*>(sym)) {\n typeSymbols.add(typeSymbol);\n } else if (FnSymbol* fnSymbol = dynamic_cast<FnSymbol*>(sym)) {\n fnSymbols.add(fnSymbol);\n } else if (VarSymbol* varSymbol = dynamic_cast<VarSymbol*>(sym)) {\n if (varSymbol->parentScope->parent == rootScope)\n varSymbols.add(varSymbol);\n }\n }\n }\n\n qsort(varSymbols.v, varSymbols.n, sizeof(varSymbols.v[0]), compareSymbol);\n qsort(typeSymbols.v, typeSymbols.n, sizeof(typeSymbols.v[0]), compareSymbol);\n qsort(fnSymbols.v, fnSymbols.n, sizeof(fnSymbols.v[0]), compareSymbol);\n\n fileinfo header;\n openCFile(&header, \"_chpl_header\", \"h\");\n FILE* outfile = header.fptr;\n\n fprintf(outfile, \"#include \\\"stdchpl.h\\\"\\n\");\n fprintf(outfile, \"\\n\/*** Class Reference Types ***\/\\n\\n\");\n\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n typeSymbol->codegenPrototype(outfile);\n }\n\n \/\/ codegen enumerated types\n fprintf(outfile, \"\\n\/*** Enumerated Types ***\/\\n\\n\");\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n if (dynamic_cast<EnumType*>(typeSymbol->type))\n typeSymbol->codegenDef(outfile);\n }\n\n \/\/ order records\/unions topologically\n \/\/ (int, int) before (int, (int, int))\n Map<ClassType*,int> order;\n int maxOrder = 0;\n forv_Vec(TypeSymbol, ts, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))\n setOrder(order, maxOrder, ct);\n }\n\n \/\/ debug\n\/\/ for (int i = 0; i < order.n; i++) {\n\/\/ if (order.v[i].key && order.v[i].value) {\n\/\/ printf(\"%d: %s\\n\", order.v[i].value, order.v[i].key->symbol->name);\n\/\/ }\n\/\/ }\n\/\/ printf(\"%d\\n\", maxOrder);\n\n \/\/ codegen records\/unions in topological order\n fprintf(outfile, \"\\n\/*** Records and Unions (Hierarchically) ***\/\\n\\n\");\n for (int i = 1; i <= maxOrder; i++) {\n forv_Vec(TypeSymbol, ts, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))\n if (order.get(ct) == i)\n ts->codegenDef(outfile);\n }\n }\n\n \/\/ codegen remaining types\n fprintf(outfile, \"\/*** Classes ***\/\\n\\n\");\n forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {\n if (ClassType* ct = dynamic_cast<ClassType*>(typeSymbol->type))\n if (ct->classTag != CLASS_CLASS)\n continue;\n if (dynamic_cast<EnumType*>(typeSymbol->type))\n continue;\n typeSymbol->codegenDef(outfile);\n }\n\n fprintf(outfile, \"\/*** Function Prototypes ***\/\\n\\n\");\n forv_Vec(FnSymbol, fnSymbol, fnSymbols) {\n fnSymbol->codegenPrototype(outfile);\n }\n\n fprintf(outfile, \"\\n\/*** Global Variables ***\/\\n\\n\");\n forv_Vec(VarSymbol, varSymbol, varSymbols) {\n varSymbol->codegenDef(outfile);\n }\n closeCFile(&header);\n beautify(&header);\n}\n\n\nstatic void\ncodegen_config(FILE* outfile) {\n fprintf(outfile, \"void CreateConfigVarTable(void) {\\n\");\n fprintf(outfile, \"initConfigVarTable();\\n\");\n\n forv_Vec(BaseAST, ast, gAsts) {\n if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {\n VarSymbol* var = dynamic_cast<VarSymbol*>(def->sym);\n if (var && var->varClass == VAR_CONFIG) {\n fprintf(outfile, \"installConfigVar(\\\"%s\\\", \\\"\", var->name);\n fprintf(outfile, var->type->symbol->name);\n fprintf(outfile, \"\\\", \\\"%s\\\");\\n\", var->getModule()->name);\n }\n }\n }\n\n fprintf(outfile, \"if (askedToParseArgs()) {\\n\");\n fprintf(outfile, \" parseConfigArgs();\\n\");\n fprintf(outfile, \"}\\n\");\n\n fprintf(outfile, \"if (askedToPrintHelpMessage()) {\\n\");\n fprintf(outfile, \" printHelpTable();\\n\");\n fprintf(outfile, \" printConfigVarTable();\\n\");\n fprintf(outfile, \"}\\n\");\n \n fprintf(outfile, \"}\\n\");\n}\n\n\nvoid codegen(void) {\n if (no_codegen)\n return;\n\n fileinfo mainfile;\n openCFile(&mainfile, \"_main\", \"c\");\n fprintf(mainfile.fptr, \"#include \\\"_chpl_header.h\\\"\\n\");\n\n codegen_makefile(&mainfile);\n\n codegen_header();\n\n codegen_config(mainfile.fptr);\n\n forv_Vec(ModuleSymbol, currentModule, allModules) {\n mysystem(stringcat(\"# codegen-ing module\", currentModule->name),\n \"generating comment for --print-commands option\");\n\n fileinfo modulefile;\n openCFile(&modulefile, currentModule->name, \"c\");\n currentModule->codegenDef(modulefile.fptr);\n closeCFile(&modulefile);\n fprintf(mainfile.fptr, \"#include \\\"%s%s\\\"\\n\", currentModule->name, \".c\");\n beautify(&modulefile);\n }\n\n closeCFile(&mainfile);\n beautify(&mainfile);\n makeBinary();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"command_pool.hpp\"\n#include \"device.hpp\"\n\nnamespace Vulkan\n{\nCommandPool::CommandPool(Device *device_, uint32_t queue_family_index)\n : device(device_), table(&device_->get_device_table())\n{\n\tVkCommandPoolCreateInfo info = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };\n\tinfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;\n\tinfo.queueFamilyIndex = queue_family_index;\n\ttable->vkCreateCommandPool(device->get_device(), &info, nullptr, &pool);\n}\n\nCommandPool::CommandPool(CommandPool &&other) noexcept\n{\n\t*this = std::move(other);\n}\n\nCommandPool &CommandPool::operator=(CommandPool &&other) noexcept\n{\n\tif (this != &other)\n\t{\n\t\tdevice = other.device;\n\t\ttable = other.table;\n\t\tif (!buffers.empty())\n\t\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\t\tif (pool != VK_NULL_HANDLE)\n\t\t\ttable->vkDestroyCommandPool(device->get_device(), pool, nullptr);\n\n\t\tpool = VK_NULL_HANDLE;\n\t\tbuffers.clear();\n\t\tstd::swap(pool, other.pool);\n\t\tstd::swap(buffers, other.buffers);\n\t\tindex = other.index;\n\t\tother.index = 0;\n#ifdef VULKAN_DEBUG\n\t\tin_flight.clear();\n\t\tstd::swap(in_flight, other.in_flight);\n#endif\n\t}\n\treturn *this;\n}\n\nCommandPool::~CommandPool()\n{\n\tif (!buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\tif (!secondary_buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, secondary_buffers.size(), secondary_buffers.data());\n\tif (pool != VK_NULL_HANDLE)\n\t\ttable->vkDestroyCommandPool(device->get_device(), pool, nullptr);\n}\n\nvoid CommandPool::signal_submitted(VkCommandBuffer cmd)\n{\n#ifdef VULKAN_DEBUG\n\tVK_ASSERT(in_flight.find(cmd) != end(in_flight));\n\tin_flight.erase(cmd);\n#else\n\t(void)cmd;\n#endif\n}\n\nVkCommandBuffer CommandPool::request_secondary_command_buffer()\n{\n\tif (secondary_index < secondary_buffers.size())\n\t{\n\t\tauto ret = secondary_buffers[secondary_index++];\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(ret) == end(in_flight));\n\t\tin_flight.insert(ret);\n#endif\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tVkCommandBuffer cmd;\n\t\tVkCommandBufferAllocateInfo info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };\n\t\tinfo.commandPool = pool;\n\t\tinfo.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;\n\t\tinfo.commandBufferCount = 1;\n\n\t\ttable->vkAllocateCommandBuffers(device->get_device(), &info, &cmd);\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(cmd) == end(in_flight));\n\t\tin_flight.insert(cmd);\n#endif\n\t\tsecondary_buffers.push_back(cmd);\n\t\tsecondary_index++;\n\t\treturn cmd;\n\t}\n}\n\nVkCommandBuffer CommandPool::request_command_buffer()\n{\n\tif (index < buffers.size())\n\t{\n\t\tauto ret = buffers[index++];\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(ret) == end(in_flight));\n\t\tin_flight.insert(ret);\n#endif\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tVkCommandBuffer cmd;\n\t\tVkCommandBufferAllocateInfo info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };\n\t\tinfo.commandPool = pool;\n\t\tinfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;\n\t\tinfo.commandBufferCount = 1;\n\n\t\ttable->vkAllocateCommandBuffers(device->get_device(), &info, &cmd);\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(cmd) == end(in_flight));\n\t\tin_flight.insert(cmd);\n#endif\n\t\tbuffers.push_back(cmd);\n\t\tindex++;\n\t\treturn cmd;\n\t}\n}\n\nvoid CommandPool::begin()\n{\n#ifdef VULKAN_DEBUG\n\tVK_ASSERT(in_flight.empty());\n#endif\n\tif (index > 0 || secondary_index > 0)\n\t\ttable->vkResetCommandPool(device->get_device(), pool, 0);\n\tindex = 0;\n\tsecondary_index = 0;\n}\n\nvoid CommandPool::trim()\n{\n\ttable->vkResetCommandPool(device->get_device(), pool, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT);\n\tif (!buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\tif (!secondary_buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, secondary_buffers.size(), secondary_buffers.data());\n\tbuffers.clear();\n\tsecondary_buffers.clear();\n\tif (device->get_device_features().supports_maintenance_1)\n\t\ttable->vkTrimCommandPoolKHR(device->get_device(), pool, 0);\n}\n}\n<commit_msg>Don't create command pool with ignored family index.<commit_after>\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"command_pool.hpp\"\n#include \"device.hpp\"\n\nnamespace Vulkan\n{\nCommandPool::CommandPool(Device *device_, uint32_t queue_family_index)\n : device(device_), table(&device_->get_device_table())\n{\n\tVkCommandPoolCreateInfo info = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };\n\tinfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;\n\tinfo.queueFamilyIndex = queue_family_index;\n\tif (queue_family_index != VK_QUEUE_FAMILY_IGNORED)\n\t\ttable->vkCreateCommandPool(device->get_device(), &info, nullptr, &pool);\n}\n\nCommandPool::CommandPool(CommandPool &&other) noexcept\n{\n\t*this = std::move(other);\n}\n\nCommandPool &CommandPool::operator=(CommandPool &&other) noexcept\n{\n\tif (this != &other)\n\t{\n\t\tdevice = other.device;\n\t\ttable = other.table;\n\t\tif (!buffers.empty())\n\t\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\t\tif (pool != VK_NULL_HANDLE)\n\t\t\ttable->vkDestroyCommandPool(device->get_device(), pool, nullptr);\n\n\t\tpool = VK_NULL_HANDLE;\n\t\tbuffers.clear();\n\t\tstd::swap(pool, other.pool);\n\t\tstd::swap(buffers, other.buffers);\n\t\tindex = other.index;\n\t\tother.index = 0;\n#ifdef VULKAN_DEBUG\n\t\tin_flight.clear();\n\t\tstd::swap(in_flight, other.in_flight);\n#endif\n\t}\n\treturn *this;\n}\n\nCommandPool::~CommandPool()\n{\n\tif (!buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\tif (!secondary_buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, secondary_buffers.size(), secondary_buffers.data());\n\tif (pool != VK_NULL_HANDLE)\n\t\ttable->vkDestroyCommandPool(device->get_device(), pool, nullptr);\n}\n\nvoid CommandPool::signal_submitted(VkCommandBuffer cmd)\n{\n#ifdef VULKAN_DEBUG\n\tVK_ASSERT(in_flight.find(cmd) != end(in_flight));\n\tin_flight.erase(cmd);\n#else\n\t(void)cmd;\n#endif\n}\n\nVkCommandBuffer CommandPool::request_secondary_command_buffer()\n{\n\tVK_ASSERT(pool != VK_NULL_HANDLE);\n\n\tif (secondary_index < secondary_buffers.size())\n\t{\n\t\tauto ret = secondary_buffers[secondary_index++];\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(ret) == end(in_flight));\n\t\tin_flight.insert(ret);\n#endif\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tVkCommandBuffer cmd;\n\t\tVkCommandBufferAllocateInfo info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };\n\t\tinfo.commandPool = pool;\n\t\tinfo.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;\n\t\tinfo.commandBufferCount = 1;\n\n\t\ttable->vkAllocateCommandBuffers(device->get_device(), &info, &cmd);\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(cmd) == end(in_flight));\n\t\tin_flight.insert(cmd);\n#endif\n\t\tsecondary_buffers.push_back(cmd);\n\t\tsecondary_index++;\n\t\treturn cmd;\n\t}\n}\n\nVkCommandBuffer CommandPool::request_command_buffer()\n{\n\tVK_ASSERT(pool != VK_NULL_HANDLE);\n\n\tif (index < buffers.size())\n\t{\n\t\tauto ret = buffers[index++];\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(ret) == end(in_flight));\n\t\tin_flight.insert(ret);\n#endif\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tVkCommandBuffer cmd;\n\t\tVkCommandBufferAllocateInfo info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };\n\t\tinfo.commandPool = pool;\n\t\tinfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;\n\t\tinfo.commandBufferCount = 1;\n\n\t\ttable->vkAllocateCommandBuffers(device->get_device(), &info, &cmd);\n#ifdef VULKAN_DEBUG\n\t\tVK_ASSERT(in_flight.find(cmd) == end(in_flight));\n\t\tin_flight.insert(cmd);\n#endif\n\t\tbuffers.push_back(cmd);\n\t\tindex++;\n\t\treturn cmd;\n\t}\n}\n\nvoid CommandPool::begin()\n{\n\tif (pool == VK_NULL_HANDLE)\n\t\treturn;\n\n#ifdef VULKAN_DEBUG\n\tVK_ASSERT(in_flight.empty());\n#endif\n\tif (index > 0 || secondary_index > 0)\n\t\ttable->vkResetCommandPool(device->get_device(), pool, 0);\n\tindex = 0;\n\tsecondary_index = 0;\n}\n\nvoid CommandPool::trim()\n{\n\tif (pool == VK_NULL_HANDLE)\n\t\treturn;\n\n\ttable->vkResetCommandPool(device->get_device(), pool, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT);\n\tif (!buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, buffers.size(), buffers.data());\n\tif (!secondary_buffers.empty())\n\t\ttable->vkFreeCommandBuffers(device->get_device(), pool, secondary_buffers.size(), secondary_buffers.data());\n\tbuffers.clear();\n\tsecondary_buffers.clear();\n\tif (device->get_device_features().supports_maintenance_1)\n\t\ttable->vkTrimCommandPoolKHR(device->get_device(), pool, 0);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"cmakehighlighter.h\"\n\n#include <QRegExp>\n#include <QTextDocument>\n\nusing namespace CMakeProjectManager::Internal;\n\n\nstatic bool isVariable(const QByteArray &word)\n{\n if (word.length() < 4) \/\/ must be at least \"${.}\"\n return false;\n return word.startsWith(\"${\") && word.endsWith('}');\n}\n\n\nCMakeHighlighter::CMakeHighlighter(QTextDocument *document) :\n TextEditor::SyntaxHighlighter(document)\n{\n static QVector<TextEditor::TextStyle> categories;\n if (categories.isEmpty()) {\n categories << TextEditor::C_LABEL \/\/ variables\n << TextEditor::C_KEYWORD \/\/ functions\n << TextEditor::C_COMMENT\n << TextEditor::C_STRING\n << TextEditor::C_VISUAL_WHITESPACE;\n }\n setTextFormatCategories(categories);\n}\n\n\nvoid CMakeHighlighter::highlightBlock(const QString &text)\n{\n QByteArray buf;\n bool inCommentMode = false;\n bool inStringMode = (previousBlockState() == 1);\n\n QTextCharFormat emptyFormat;\n int i=0;\n for (i=0; i < text.length(); i++) {\n char c = text.at(i).toLatin1();\n if (inCommentMode) {\n setFormat(i, 1, formatForCategory(CMakeCommentFormat));\n } else {\n if (c == '#') {\n if (!inStringMode) {\n inCommentMode = true;\n setFormat(i, 1, formatForCategory(CMakeCommentFormat));\n buf.clear();\n } else {\n buf += c;\n }\n } else if (c == '(') {\n if (!inStringMode) {\n if (!buf.isEmpty())\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeFunctionFormat));\n buf.clear();\n } else {\n buf += c;\n }\n } else if (text.at(i).isSpace()) {\n if (!inStringMode)\n buf.clear();\n else\n buf += c;\n } else if (c == '\\\"') {\n buf += c;\n if (inStringMode) {\n setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n buf.clear();\n } else {\n setFormat(i, 1, formatForCategory(CMakeStringFormat));\n }\n inStringMode = !inStringMode;\n } else if (c == '\\\\') {\n setFormat(i, 1, emptyFormat);\n buf += c;\n i++;\n if (i < text.length()) {\n text.at(i);\n setFormat(i, 1, emptyFormat);\n buf += c;\n }\n } else if (c == '$') {\n if (inStringMode)\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n buf.clear();\n buf += c;\n setFormat(i, 1, emptyFormat);\n } else if (c == '}') {\n buf += c;\n if (isVariable(buf)) {\n setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeVariableFormat));\n buf.clear();\n }\n } else {\n buf += c;\n setFormat(i, 1, emptyFormat);\n }\n }\n }\n\n if (inStringMode) {\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n setCurrentBlockState(1);\n } else {\n setCurrentBlockState(0);\n }\n\n applyFormatToSpaces(text, formatForCategory(CMakeVisualWhiteSpaceFormat));\n}\n\n<commit_msg>CMake: Remove statement that has no effect<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"cmakehighlighter.h\"\n\n#include <QRegExp>\n#include <QTextDocument>\n\nusing namespace CMakeProjectManager::Internal;\n\n\nstatic bool isVariable(const QByteArray &word)\n{\n if (word.length() < 4) \/\/ must be at least \"${.}\"\n return false;\n return word.startsWith(\"${\") && word.endsWith('}');\n}\n\n\nCMakeHighlighter::CMakeHighlighter(QTextDocument *document) :\n TextEditor::SyntaxHighlighter(document)\n{\n static QVector<TextEditor::TextStyle> categories;\n if (categories.isEmpty()) {\n categories << TextEditor::C_LABEL \/\/ variables\n << TextEditor::C_KEYWORD \/\/ functions\n << TextEditor::C_COMMENT\n << TextEditor::C_STRING\n << TextEditor::C_VISUAL_WHITESPACE;\n }\n setTextFormatCategories(categories);\n}\n\n\nvoid CMakeHighlighter::highlightBlock(const QString &text)\n{\n QByteArray buf;\n bool inCommentMode = false;\n bool inStringMode = (previousBlockState() == 1);\n\n QTextCharFormat emptyFormat;\n int i=0;\n for (i=0; i < text.length(); i++) {\n char c = text.at(i).toLatin1();\n if (inCommentMode) {\n setFormat(i, 1, formatForCategory(CMakeCommentFormat));\n } else {\n if (c == '#') {\n if (!inStringMode) {\n inCommentMode = true;\n setFormat(i, 1, formatForCategory(CMakeCommentFormat));\n buf.clear();\n } else {\n buf += c;\n }\n } else if (c == '(') {\n if (!inStringMode) {\n if (!buf.isEmpty())\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeFunctionFormat));\n buf.clear();\n } else {\n buf += c;\n }\n } else if (text.at(i).isSpace()) {\n if (!inStringMode)\n buf.clear();\n else\n buf += c;\n } else if (c == '\\\"') {\n buf += c;\n if (inStringMode) {\n setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n buf.clear();\n } else {\n setFormat(i, 1, formatForCategory(CMakeStringFormat));\n }\n inStringMode = !inStringMode;\n } else if (c == '\\\\') {\n setFormat(i, 1, emptyFormat);\n buf += c;\n i++;\n if (i < text.length()) {\n setFormat(i, 1, emptyFormat);\n buf += c;\n }\n } else if (c == '$') {\n if (inStringMode)\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n buf.clear();\n buf += c;\n setFormat(i, 1, emptyFormat);\n } else if (c == '}') {\n buf += c;\n if (isVariable(buf)) {\n setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeVariableFormat));\n buf.clear();\n }\n } else {\n buf += c;\n setFormat(i, 1, emptyFormat);\n }\n }\n }\n\n if (inStringMode) {\n setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));\n setCurrentBlockState(1);\n } else {\n setCurrentBlockState(0);\n }\n\n applyFormatToSpaces(text, formatForCategory(CMakeVisualWhiteSpaceFormat));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#include <stdio.h>\n#include \"sl_test_header.h\"\n\ntest_framework_t::test_framework_t(void)\n{\n}\n\ntest_framework_t::~test_framework_t(void)\n{\n}\n\ntest_framework_t& \ntest_framework_t::singleton(void)\n{\n static test_framework_t _s_test;\n\n return _s_test;\n}\n\nvoid \ntest_framework_t::run(void)\n{\n fprintf(stdout, \"begin testing for slib++ ...\\n\");\n\n size_t size = case_list_.size();\n for (size_t i = 0; i < size; ++i) {\n fprintf(stdout, \"\\ttest %s module : \", case_list_[i].name_);\n case_list_[i].test_();\n fprintf(stdout, \"passed !!!\\n\");\n }\n \n fprintf(stdout, \"end testing for slib++ ...\\n\");\n}\n\nbool \ntest_framework_t::register_test(const char* name, void (*test)(void))\n{\n if (NULL == name || NULL == test)\n return false;\n\n case_list_.push_back(test_case_t(name, test));\n return true;\n}\n\n\n\nint \nmain(int argc, char* argv[])\n{\n test_framework_t::singleton().run();\n\n return 0;\n}\n<commit_msg>updated display information for test framework of slib++<commit_after>\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#include <stdio.h>\n#include \"sl_test_header.h\"\n\ntest_framework_t::test_framework_t(void)\n{\n}\n\ntest_framework_t::~test_framework_t(void)\n{\n}\n\ntest_framework_t& \ntest_framework_t::singleton(void)\n{\n static test_framework_t _s_test;\n\n return _s_test;\n}\n\nvoid \ntest_framework_t::run(void)\n{\n fprintf(stdout, \"begin testing for slib++ ...\\n\");\n\n size_t size = case_list_.size();\n for (size_t i = 0; i < size; ++i) {\n fprintf(stdout, \"\\ttesting for %s module : \\n\", case_list_[i].name_);\n case_list_[i].test_();\n fprintf(stdout, \"\\ttesting passed !!!\\n\\n\");\n }\n \n fprintf(stdout, \"end testing for slib++ ...\\n\");\n}\n\nbool \ntest_framework_t::register_test(const char* name, void (*test)(void))\n{\n if (NULL == name || NULL == test)\n return false;\n\n case_list_.push_back(test_case_t(name, test));\n return true;\n}\n\n\n\nint \nmain(int argc, char* argv[])\n{\n test_framework_t::singleton().run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Element.h\"\n#include \"Feeder.h\"\n#include \"IfBlock.h\"\n#include \"Import.h\"\n#include \"Pipeline.h\"\n#include \"CommandLine.h\"\n#include \"Comment.h\"\nusing namespace std;\n\nIfBlock::IfBlock(Feeder *f, Environment *env) : Element(f,env)\n{\n}\n\nIfBlock::~IfBlock()\n{\n}\n\n\/* IfBlock means an if-then-else chunk in usual programing languages.\n * ex)\n\n| commandline1\t <- if\n\tcommandline2\n| commandline2\t <- else if\n\tcommandline3\n| otherwise\t <- else\n\tcommandline4\n\t\t\t \ncommandline5\t <- out of if block\n\nThe other purpose to use IfBlock is the cancel of exit statuses\n\n| seq '1' '1000000000' >>= head\n\nThough the head command invokes SIGPIPE error of the seq command,\n\"|\" cancels this failure in this case.\nHowever, this technique should be carefully used.\n *\/\nbool IfBlock::parse(void)\n{\n\tm_feeder->getPos(&m_start_line, &m_start_char);\n\n\tint indent = m_feeder->countIndent();\n\t\n\tm_feeder->blank(NULL);\n\t\/\/ detect the first condition\n\tif(! m_feeder->str(\"?\")){\n\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\treturn false;\n\t}\n\n\twhile(1){\n\t\t\/\/ condition -> many (pipeline or commandline) -> condition ->...\n\t\tm_feeder->blank(NULL);\n\t\t\n\t\tif(m_feeder->str(\"otherwise\")){\n\t\t\tm_nodes.push_back(NULL); \/\/ dummy\n\t\t}else if(add(new Pipeline(m_feeder,m_env))){\n\t\t\t((Pipeline *)m_nodes.back())->setIfFlag();\n\t\t}\n\t\telse if(add(new CommandLine(m_feeder,m_env))){\n\t\t\t((CommandLine *)m_nodes.back())->setIfFlag();\n\t\t}else{\n\t\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\t\treturn false;\n\t\t}\n\n\t\tm_is_cond_node.push_back(true);\n\n\/*\n\t\tif(m_feeder->atEnd()){\n\t\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\treturn true;\n\t\t}\n*\/\n\n\t\t\/\/while(add(new Comment(m_feeder,m_env))){ }\n\n\t\tint sub_indent = m_feeder->countIndent();\n\n\t\t\/\/ end of the if block\n\t\tif(sub_indent < indent){\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ found another condition\n\t\tif( indent == sub_indent){\n\t\t\tm_feeder->blank(NULL);\n\t\t\tif(m_feeder->str(\"?\")){\n\t\t\t\t\/\/ another condition\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tbreak; \/\/ end of the if block\n\t\t\t}\n\t\t}\n\n\t\t\/\/ attempt to search procedures related to the condition\n\t\twhile(sub_indent > indent){\n\t\t\tm_feeder->blank(NULL);\n\n\t\t\tif(\tadd(new IfBlock(m_feeder,m_env))\n\t\t\t\t|| add(new Pipeline(m_feeder,m_env))\n\t\t\t \t|| add(new CommandLine(m_feeder,m_env))){\n\n\n\t\t\t\tm_is_cond_node.push_back(false);\n\/*\n\t\t\t\tif(m_feeder->atEnd()){\n\t\t\t\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n*\/\n\t\t\t\tsub_indent = m_feeder->countIndent();\n\t\t\t}else{\n\t\t\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ after procedures related to the condition\n\t\tif(sub_indent < indent){\n\t\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\tbreak;\n\t\t}\n\n\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\/\/ next condition\n\t\tm_feeder->blank(NULL);\n\t\t\/\/ detect the first condition\n\t\tif(! m_feeder->str(\"|\")){\n\t\t\tm_feeder->setPos(m_end_line, m_end_char);\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_feeder->getPos(&m_end_line, &m_end_char);\n\n\treturn true;\n}\n\nint IfBlock::exec(void)\n{\n\tif(m_nodes.size() != m_is_cond_node.size()){\n\t\tm_error_msg = \"BUG: IfBlock internal error\";\n\t\tthrow this;\n\t}\n\n\tint exit_status = 0;\n\tbool skip = false;\n\tbool match = false;\n\tfor(int i=0;i<m_nodes.size();i++){\n\t\tif(m_is_cond_node[i]){ \/\/ cond node\n\t\t\tif(match) \/\/ already matched\n\t\t\t\tbreak;\t\n\t\t\t\n\t\t\tif(m_nodes[i] == NULL || m_nodes[i]->exec() == 0){\n\t\t\t\tmatch = true;\n\t\t\t\tskip = false;\n\t\t\t}else\n\t\t\t\tskip = true;\n\n\t\t}else{ \/\/ other node\n\t\t\tif(!skip)\n\t\t\t\tm_nodes[i]->exec();\n\t\t}\n\t}\n\/*\n\tfor(auto &c : m_nodes){\n\t}\n*\/\n\treturn exit_status;\n}\n<commit_msg>Modify old comment<commit_after>#include \"Element.h\"\n#include \"Feeder.h\"\n#include \"IfBlock.h\"\n#include \"Import.h\"\n#include \"Pipeline.h\"\n#include \"CommandLine.h\"\n#include \"Comment.h\"\nusing namespace std;\n\nIfBlock::IfBlock(Feeder *f, Environment *env) : Element(f,env)\n{\n}\n\nIfBlock::~IfBlock()\n{\n}\n\n\/* IfBlock means an if-then-else chunk in usual programing languages.\n * ex)\n\n? commandline1\t <- if\n\tcommandline2\n| commandline2\t <- else if\n\tcommandline3\n| otherwise\t <- else\n\tcommandline4\n\t\t\t \ncommandline5\t <- out of if block\n\nThe other purpose to use IfBlock is the cancel of exit statuses\n\n? seq '1' '1000000000' >>= head\n\nThough the head command invokes SIGPIPE error of the seq command,\n\"|\" cancels this failure in this case.\nHowever, this technique should be carefully used.\n *\/\nbool IfBlock::parse(void)\n{\n\tm_feeder->getPos(&m_start_line, &m_start_char);\n\n\tint indent = m_feeder->countIndent();\n\t\n\tm_feeder->blank(NULL);\n\t\/\/ detect the first condition\n\tif(! m_feeder->str(\"?\")){\n\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\treturn false;\n\t}\n\n\twhile(1){\n\t\t\/\/ condition -> many (pipeline or commandline) -> condition ->...\n\t\tm_feeder->blank(NULL);\n\t\t\n\t\tif(m_feeder->str(\"otherwise\")){\n\t\t\tm_nodes.push_back(NULL); \/\/ dummy\n\t\t}else if(add(new Pipeline(m_feeder,m_env))){\n\t\t\t((Pipeline *)m_nodes.back())->setIfFlag();\n\t\t}\n\t\telse if(add(new CommandLine(m_feeder,m_env))){\n\t\t\t((CommandLine *)m_nodes.back())->setIfFlag();\n\t\t}else{\n\t\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\t\treturn false;\n\t\t}\n\n\t\tm_is_cond_node.push_back(true);\n\n\t\t\/\/while(add(new Comment(m_feeder,m_env))){ }\n\n\t\tint sub_indent = m_feeder->countIndent();\n\n\t\t\/\/ end of the if block\n\t\tif(sub_indent < indent){\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ found another condition\n\t\tif( indent == sub_indent){\n\t\t\tm_feeder->blank(NULL);\n\t\t\tif(m_feeder->str(\"?\")){\n\t\t\t\t\/\/ another condition\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tbreak; \/\/ end of the if block\n\t\t\t}\n\t\t}\n\n\t\t\/\/ attempt to search procedures related to the condition\n\t\twhile(sub_indent > indent){\n\t\t\tm_feeder->blank(NULL);\n\n\t\t\tif(\tadd(new IfBlock(m_feeder,m_env))\n\t\t\t\t|| add(new Pipeline(m_feeder,m_env))\n\t\t\t \t|| add(new CommandLine(m_feeder,m_env))){\n\n\n\t\t\t\tm_is_cond_node.push_back(false);\n\t\t\t\tsub_indent = m_feeder->countIndent();\n\t\t\t}else{\n\t\t\t\tm_feeder->setPos(m_start_line, m_start_char);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ after procedures related to the condition\n\t\tif(sub_indent < indent){\n\t\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\tbreak;\n\t\t}\n\n\t\tm_feeder->getPos(&m_end_line, &m_end_char);\n\t\t\/\/ next condition\n\t\tm_feeder->blank(NULL);\n\t\t\/\/ detect the first condition\n\t\tif(! m_feeder->str(\"|\")){\n\t\t\tm_feeder->setPos(m_end_line, m_end_char);\n\t\t\tbreak;\n\t\t}\n\t}\n\tm_feeder->getPos(&m_end_line, &m_end_char);\n\n\treturn true;\n}\n\nint IfBlock::exec(void)\n{\n\tif(m_nodes.size() != m_is_cond_node.size()){\n\t\tm_error_msg = \"BUG: IfBlock internal error\";\n\t\tthrow this;\n\t}\n\n\tint exit_status = 0;\n\tbool skip = false;\n\tbool match = false;\n\tfor(int i=0;i<m_nodes.size();i++){\n\t\tif(m_is_cond_node[i]){ \/\/ cond node\n\t\t\tif(match) \/\/ already matched\n\t\t\t\tbreak;\t\n\t\t\t\n\t\t\tif(m_nodes[i] == NULL || m_nodes[i]->exec() == 0){\n\t\t\t\tmatch = true;\n\t\t\t\tskip = false;\n\t\t\t}else\n\t\t\t\tskip = true;\n\n\t\t}else{ \/\/ other node\n\t\t\tif(!skip)\n\t\t\t\tm_nodes[i]->exec();\n\t\t}\n\t}\n\/*\n\tfor(auto &c : m_nodes){\n\t}\n*\/\n\treturn exit_status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\n\tfilename: \tCEGUISlider.cpp\n\tcreated:\t13\/4\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of Slider widget base class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"elements\/CEGUISlider.h\"\n#include \"elements\/CEGUIThumb.h\"\n#include <boost\/bind.hpp>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\n\/*************************************************************************\n\tEvent name constants\n*************************************************************************\/\nconst utf8\tSlider::ValueChanged[]\t\t= \"ValueChanged\";\n\n\n\/*************************************************************************\n\tSlider base class constructor\n*************************************************************************\/\nSlider::Slider(const String& type, const String& name) :\n\tWindow(type, name),\n\td_value(0.0f),\n\td_maxValue(1.0f),\n\td_step(0.01f),\n\td_thumb(NULL)\n{\n\taddSliderEvents();\n}\n\n\n\/*************************************************************************\n\tSlider base class destructor\n*************************************************************************\/\nSlider::~Slider(void)\n{\n}\n\n\n\/*************************************************************************\n\tInitialises the Window based object ready for use.\t\n*************************************************************************\/\nvoid Slider::initialise(void)\n{\n\t\/\/ create and attach thumb\n\td_thumb = createThumb();\n\taddChildWindow(d_thumb);\n\n\t\/\/ bind handler to thumb event triggered when thumb moves\n\td_thumb->subscribeEvent(Thumb::ThumbPositionChanged, boost::bind(&CEGUI::Slider::handleThumbMoved, this, _1));\n\n\tlayoutComponentWidgets();\n}\n\n\n\/*************************************************************************\n\tset the maximum value for the slider.\n\tNote that the minimum value is fixed at 0.\t\n*************************************************************************\/\nvoid Slider::setMaxValue(float maxVal)\n{\n\td_maxValue = maxVal;\n\n\tfloat oldval = d_value;\n\n\t\/\/ limit current value to be within new max\n\tif (d_value > d_maxValue) {\n\t\td_value = d_maxValue;\n\t}\n\n\tupdateThumb();\n\n\t\/\/ send notification if slider value changed.\n\tif (d_value != oldval)\n\t{\n\t\tonValueChanged(WindowEventArgs(this));\n\t}\n\n}\n\n\n\/*************************************************************************\n\tset the current slider value.\n*************************************************************************\/\nvoid Slider::setCurrentValue(float value)\n{\n\tfloat oldval = d_value;\n\n\t\/\/ range for value: 0 <= value <= maxValue\n\td_value = (value <= d_maxValue) ? value : d_maxValue;\n\n\tupdateThumb();\n\n\t\/\/ send notification if slider value changed.\n\tif (d_value != oldval)\n\t{\n\t\tonValueChanged(WindowEventArgs(this));\n\t}\n\n}\n\n\n\/*************************************************************************\n\tAdd slider specific events\t\n*************************************************************************\/\nvoid Slider::addSliderEvents(void)\n{\n\taddEvent(ValueChanged);\n}\n\n\n\/*************************************************************************\n\tHandler triggered when the slider value changes\n*************************************************************************\/\nvoid Slider::onValueChanged(WindowEventArgs& e)\n{\n\tfireEvent(ValueChanged, e);\n}\n\n\n\/*************************************************************************\n\tHandler for when a mouse button is pressed\n*************************************************************************\/\nvoid Slider::onMouseButtonDown(MouseEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onMouseButtonDown(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tfloat adj = getAdjustDirectionFromPoint(e.position);\n\n\t\t\/\/ adjust slider position in whichever direction as required.\n\t\tif (adj != 0)\n\t\t{\n\t\t\tsetCurrentValue(d_value + (adj * d_step));\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when the size of the slider widget changes.\n*************************************************************************\/\nvoid Slider::onSized(EventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onSized(e);\n\n\tlayoutComponentWidgets();\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\thandler function for when thumb moves.\t\n*************************************************************************\/\nvoid Slider::handleThumbMoved(const EventArgs& e)\n{\n\tsetCurrentValue(getValueFromThumb());\n}\n\n\n} \/\/ End of CEGUI namespace section\n<commit_msg>Bug fix to range checking in CEGUI::Slider::setCurrentValue.<commit_after>\/************************************************************************\n\tfilename: \tCEGUISlider.cpp\n\tcreated:\t13\/4\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of Slider widget base class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"elements\/CEGUISlider.h\"\n#include \"elements\/CEGUIThumb.h\"\n#include <boost\/bind.hpp>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\n\/*************************************************************************\n\tEvent name constants\n*************************************************************************\/\nconst utf8\tSlider::ValueChanged[]\t\t= \"ValueChanged\";\n\n\n\/*************************************************************************\n\tSlider base class constructor\n*************************************************************************\/\nSlider::Slider(const String& type, const String& name) :\n\tWindow(type, name),\n\td_value(0.0f),\n\td_maxValue(1.0f),\n\td_step(0.01f),\n\td_thumb(NULL)\n{\n\taddSliderEvents();\n}\n\n\n\/*************************************************************************\n\tSlider base class destructor\n*************************************************************************\/\nSlider::~Slider(void)\n{\n}\n\n\n\/*************************************************************************\n\tInitialises the Window based object ready for use.\t\n*************************************************************************\/\nvoid Slider::initialise(void)\n{\n\t\/\/ create and attach thumb\n\td_thumb = createThumb();\n\taddChildWindow(d_thumb);\n\n\t\/\/ bind handler to thumb event triggered when thumb moves\n\td_thumb->subscribeEvent(Thumb::ThumbPositionChanged, boost::bind(&CEGUI::Slider::handleThumbMoved, this, _1));\n\n\tlayoutComponentWidgets();\n}\n\n\n\/*************************************************************************\n\tset the maximum value for the slider.\n\tNote that the minimum value is fixed at 0.\t\n*************************************************************************\/\nvoid Slider::setMaxValue(float maxVal)\n{\n\td_maxValue = maxVal;\n\n\tfloat oldval = d_value;\n\n\t\/\/ limit current value to be within new max\n\tif (d_value > d_maxValue) {\n\t\td_value = d_maxValue;\n\t}\n\n\tupdateThumb();\n\n\t\/\/ send notification if slider value changed.\n\tif (d_value != oldval)\n\t{\n\t\tonValueChanged(WindowEventArgs(this));\n\t}\n\n}\n\n\n\/*************************************************************************\n\tset the current slider value.\n*************************************************************************\/\nvoid Slider::setCurrentValue(float value)\n{\n\tfloat oldval = d_value;\n\n\t\/\/ range for value: 0 <= value <= maxValue\n\td_value = (value >= 0.0f) ? ((value <= d_maxValue) ? value : d_maxValue) : 0.0f;\n\n\tupdateThumb();\n\n\t\/\/ send notification if slider value changed.\n\tif (d_value != oldval)\n\t{\n\t\tonValueChanged(WindowEventArgs(this));\n\t}\n\n}\n\n\n\/*************************************************************************\n\tAdd slider specific events\t\n*************************************************************************\/\nvoid Slider::addSliderEvents(void)\n{\n\taddEvent(ValueChanged);\n}\n\n\n\/*************************************************************************\n\tHandler triggered when the slider value changes\n*************************************************************************\/\nvoid Slider::onValueChanged(WindowEventArgs& e)\n{\n\tfireEvent(ValueChanged, e);\n}\n\n\n\/*************************************************************************\n\tHandler for when a mouse button is pressed\n*************************************************************************\/\nvoid Slider::onMouseButtonDown(MouseEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onMouseButtonDown(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tfloat adj = getAdjustDirectionFromPoint(e.position);\n\n\t\t\/\/ adjust slider position in whichever direction as required.\n\t\tif (adj != 0)\n\t\t{\n\t\t\tsetCurrentValue(d_value + (adj * d_step));\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when the size of the slider widget changes.\n*************************************************************************\/\nvoid Slider::onSized(EventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onSized(e);\n\n\tlayoutComponentWidgets();\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\thandler function for when thumb moves.\t\n*************************************************************************\/\nvoid Slider::handleThumbMoved(const EventArgs& e)\n{\n\tsetCurrentValue(getValueFromThumb());\n}\n\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\n\tfilename: \tCEGUIStatic.cpp\n\tcreated:\t13\/4\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of Static widget base class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"elements\/CEGUIStatic.h\"\n#include \"CEGUIImagesetManager.h\"\n#include \"CEGUIImageset.h\"\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tDefinitions of Properties for this class\n*************************************************************************\/\nStaticProperties::FrameEnabled\t\t\t\tStatic::d_frameEnabledProperty;\nStaticProperties::BackgroundEnabled\t\t\tStatic::d_backgroundEnabledProperty;\nStaticProperties::FrameColours\t\t\t\tStatic::d_frameColoursProperty;\nStaticProperties::BackgroundColours\t\t\tStatic::d_backgroundColoursProperty;\nStaticProperties::BackgroundImage\t\t\tStatic::d_backgroundImageProperty;\nStaticProperties::TopLeftFrameImage\t\t\tStatic::d_topLeftFrameProperty;\nStaticProperties::TopRightFrameImage\t\tStatic::d_topRightFrameProperty;\nStaticProperties::BottomLeftFrameImage\t\tStatic::d_bottomLeftFrameProperty;\nStaticProperties::BottomRightFrameImage\t\tStatic::d_bottomRightFrameProperty;\nStaticProperties::LeftFrameImage\t\t\tStatic::d_leftFrameProperty;\nStaticProperties::RightFrameImage\t\t\tStatic::d_rightFrameProperty;\nStaticProperties::TopFrameImage\t\t\t\tStatic::d_topFrameProperty;\nStaticProperties::BottomFrameImage\t\t\tStatic::d_bottomFrameProperty;\n\n\n\/*************************************************************************\n\tConstructor for static widget base class\n*************************************************************************\/\nStatic::Static(const String& type, const String& name) :\n\tWindow(type, name),\n\td_frameEnabled(false),\n\td_frameCols(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF),\n\td_backgroundCols(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)\n{\n\taddStaticProperties();\n}\n\n\n\/*************************************************************************\n\tDestructor for static widget base class.\n*************************************************************************\/\nStatic::~Static(void)\n{\n}\n\n\n\/*************************************************************************\n\toverridden so derived classes are auto-clipped to within the inner\n\tarea of the frame when it's active.\n*************************************************************************\/\nRect Static::getUnclippedInnerRect(void) const\n{\n\t\/\/ if frame is enabled, return rect for area inside frame\n\tif (d_frameEnabled)\n\t{\n\t\tRect tmp(Window::getUnclippedInnerRect());\n\t\ttmp.d_left\t\t+= d_left_width;\n\t\ttmp.d_right\t\t-= d_right_width;\n\t\ttmp.d_top\t\t+= d_top_height;\n\t\ttmp.d_bottom\t-= d_bottom_height;\n\t\treturn tmp;\n\t}\n\t\/\/ no frame, so return default inner rect.\n\telse\n\t{\n\t\treturn Window::getUnclippedInnerRect();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tEnable or disable rendering of the frame for this static widget.\n*************************************************************************\/\nvoid Static::setFrameEnabled(bool setting)\n{\n\tif (d_frameEnabled != setting)\n\t{\n\t\td_frameEnabled = setting;\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n}\n\n\n\/*************************************************************************\n\tspecify the Image objects to use for each part of the frame.\n\tA NULL may be used to omit any part.\t\n*************************************************************************\/\nvoid Static::setFrameImages(const Image* topleft, const Image* topright, const Image* bottomleft, const Image* bottomright, const Image* left, const Image* top, const Image* right, const Image* bottom)\n{\n\t\/\/ install the new images into the RenderableFrame\n\td_frame.setImages(topleft, topright, bottomleft, bottomright, left, top, right, bottom);\n\n\t\/\/ get sizes of frame edges\n\td_left_width\t= (left != NULL) ? left->getWidth() : 0.0f;\n\td_right_width\t= (right != NULL) ? right->getWidth() : 0.0f;\n\td_top_height\t= (top != NULL) ? top->getHeight() : 0.0f;\n\td_bottom_height\t= (bottom != NULL) ? bottom->getHeight() : 0.0f;\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the frame\t\n*************************************************************************\/\nvoid Static::setFrameColours(const ColourRect& colours)\n{\n\td_frameCols = colours;\n\tupdateRenderableFrameColours();\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the frame\t\n*************************************************************************\/\nvoid Static::setFrameColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour)\n{\n\td_frameCols.d_top_left\t\t= top_left_colour;\n\td_frameCols.d_top_right\t\t= top_right_colour;\n\td_frameCols.d_bottom_left\t= bottom_left_colour;\n\td_frameCols.d_bottom_right\t= bottom_right_colour;\n\tupdateRenderableFrameColours();\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tEnable or disable rendering of the background for this static widget.\t\n*************************************************************************\/\nvoid Static::setBackgroundEnabled(bool setting)\n{\n\tif (d_backgroundEnabled != setting)\n\t{\n\t\td_backgroundEnabled = setting;\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSet the image to use as the background for the static widget.\n*************************************************************************\/\nvoid Static::setBackgroundImage(const Image* image)\n{\n\td_background = image;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSet the image to use as the background for the static widget.\t\n*************************************************************************\/\nvoid Static::setBackgroundImage(const String& imageset, const String& image)\n{\n\tsetBackgroundImage(&ImagesetManager::getSingleton().getImageset(imageset)->getImage(image));\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the background.\t\n*************************************************************************\/\nvoid Static::setBackgroundColours(const ColourRect& colours)\n{\n\td_backgroundCols = colours;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the background.\t\n*************************************************************************\/\nvoid Static::setBackgroundColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour)\n{\n\td_backgroundCols.d_top_left\t\t= top_left_colour;\n\td_backgroundCols.d_top_right\t= top_right_colour;\n\td_backgroundCols.d_bottom_left\t= bottom_left_colour;\n\td_backgroundCols.d_bottom_right\t= bottom_right_colour;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tupdate the internal RenderableFrame with currently set colours and\n\talpha settings.\n*************************************************************************\/\nvoid Static::updateRenderableFrameColours(void)\n{\n\tfloat alpha = getEffectiveAlpha();\n\n\td_frame.setColours(\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_top_left, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_top_right, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_bottom_left, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_bottom_right, alpha)\n\t);\n\n}\n\n\n\/*************************************************************************\n\tgiven an ARGB colour value and a alpha float value return the colour\n\tvalue with the alpha component modulated by the given alpha float.\n*************************************************************************\/\ncolour Static::calculateModulatedAlphaColour(colour col, float alpha) const\n{\n\treturn ((col & 0x00FFFFFF) | (((colour)(((float)(col >> 24)) * alpha)) << 24));\n}\n\n\n\/*************************************************************************\n\tPerform the actual rendering for this Window.\t\n*************************************************************************\/\nvoid Static::drawSelf(float z)\n{\n\tRect clipper(getPixelRect());\n\n\t\/\/ do nothing if the widget is totally clipped.\n\tif (clipper.getWidth() == 0)\n\t{\n\t\treturn;\n\t}\n\n\tRect absrect(getUnclippedPixelRect());\n\n\t\/\/ draw frame\n\tif (d_frameEnabled)\n\t{\n\t\td_frame.draw(Vector3(absrect.d_left, absrect.d_top, z), clipper);\n\n\t\t\/\/ adjust absrect and clipper so that later stages of render to not overwite frame\n\t\tabsrect.d_left\t\t+= d_left_width;\n\t\tabsrect.d_right\t\t-= d_right_width;\n\t\tabsrect.d_top\t\t+= d_top_height;\n\t\tabsrect.d_bottom\t-= d_bottom_height;\n\n\t\tclipper = clipper.getIntersection(absrect);\n\t}\n\n\t\/\/ draw backdrop\n\tif (d_backgroundEnabled && (d_background != NULL))\n\t{\n\t\t\/\/ factor window alpha into colours to use when rendering background\n\t\tfloat alpha = getEffectiveAlpha();\n\t\tColourRect colours;\n\t\tcolours.d_top_left\t\t= calculateModulatedAlphaColour(d_backgroundCols.d_top_left, alpha);\n\t\tcolours.d_top_right\t\t= calculateModulatedAlphaColour(d_backgroundCols.d_top_right, alpha);\n\t\tcolours.d_bottom_left\t= calculateModulatedAlphaColour(d_backgroundCols.d_bottom_left, alpha);\n\t\tcolours.d_bottom_right\t= calculateModulatedAlphaColour(d_backgroundCols.d_bottom_right, alpha);\n\n\t\td_background->draw(absrect, z, clipper, colours);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when window is sized\n*************************************************************************\/\nvoid Static::onSized(WindowEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onSized(e);\n\n\t\/\/ update frame size.\n\td_frame.setSize(getAbsoluteSize());\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tHandler for when alpha value changes\n*************************************************************************\/\nvoid Static::onAlphaChanged(WindowEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onAlphaChanged(e);\n\n\t\/\/ update frame colours to use new alpha value\n\tupdateRenderableFrameColours();\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tReturn the Image being used for the specified location of the frame.\t\n*************************************************************************\/\nconst Image* Static::getImageForFrameLocation(FrameLocation location) const\n{\n\treturn d_frame.getImageForLocation(location);\n}\n\n\n\/*************************************************************************\n\tReturn the Image currently set as the background image for the widget.\n*************************************************************************\/\nconst Image* Static::getBackgroundImage(void) const\n{\n\treturn d_background;\n}\n\n\n\/*************************************************************************\n\tSet the Image to use for the specified location of the frame.\t\n*************************************************************************\/\nvoid Static::setImageForFrameLocation(FrameLocation location, const Image* image)\n{\n\td_frame.setImageForLocation(location, image);\n}\n\n\/*************************************************************************\n\tAdds properties for the static widget base class\n*************************************************************************\/\nvoid Static::addStaticProperties(void)\n{\n\taddProperty(&d_frameEnabledProperty);\n\taddProperty(&d_backgroundEnabledProperty);\n\taddProperty(&d_frameColoursProperty);\n\taddProperty(&d_backgroundColoursProperty);\n\taddProperty(&d_backgroundImageProperty);\n\taddProperty(&d_topLeftFrameProperty);\n\taddProperty(&d_topRightFrameProperty);\n\taddProperty(&d_bottomLeftFrameProperty);\n\taddProperty(&d_bottomRightFrameProperty);\n\taddProperty(&d_leftFrameProperty);\n\taddProperty(&d_topFrameProperty);\n\taddProperty(&d_rightFrameProperty);\n\taddProperty(&d_bottomFrameProperty);\n}\n\n} \/\/ End of CEGUI namespace section\n<commit_msg>Fixed Static::setImageForFrameLocation to update state properly so backgound image is set to correct size.<commit_after>\/************************************************************************\n\tfilename: \tCEGUIStatic.cpp\n\tcreated:\t13\/4\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplementation of Static widget base class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"elements\/CEGUIStatic.h\"\n#include \"CEGUIImagesetManager.h\"\n#include \"CEGUIImageset.h\"\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tDefinitions of Properties for this class\n*************************************************************************\/\nStaticProperties::FrameEnabled\t\t\t\tStatic::d_frameEnabledProperty;\nStaticProperties::BackgroundEnabled\t\t\tStatic::d_backgroundEnabledProperty;\nStaticProperties::FrameColours\t\t\t\tStatic::d_frameColoursProperty;\nStaticProperties::BackgroundColours\t\t\tStatic::d_backgroundColoursProperty;\nStaticProperties::BackgroundImage\t\t\tStatic::d_backgroundImageProperty;\nStaticProperties::TopLeftFrameImage\t\t\tStatic::d_topLeftFrameProperty;\nStaticProperties::TopRightFrameImage\t\tStatic::d_topRightFrameProperty;\nStaticProperties::BottomLeftFrameImage\t\tStatic::d_bottomLeftFrameProperty;\nStaticProperties::BottomRightFrameImage\t\tStatic::d_bottomRightFrameProperty;\nStaticProperties::LeftFrameImage\t\t\tStatic::d_leftFrameProperty;\nStaticProperties::RightFrameImage\t\t\tStatic::d_rightFrameProperty;\nStaticProperties::TopFrameImage\t\t\t\tStatic::d_topFrameProperty;\nStaticProperties::BottomFrameImage\t\t\tStatic::d_bottomFrameProperty;\n\n\n\/*************************************************************************\n\tConstructor for static widget base class\n*************************************************************************\/\nStatic::Static(const String& type, const String& name) :\n\tWindow(type, name),\n\td_frameEnabled(false),\n\td_frameCols(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF),\n\td_backgroundCols(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)\n{\n\taddStaticProperties();\n}\n\n\n\/*************************************************************************\n\tDestructor for static widget base class.\n*************************************************************************\/\nStatic::~Static(void)\n{\n}\n\n\n\/*************************************************************************\n\toverridden so derived classes are auto-clipped to within the inner\n\tarea of the frame when it's active.\n*************************************************************************\/\nRect Static::getUnclippedInnerRect(void) const\n{\n\t\/\/ if frame is enabled, return rect for area inside frame\n\tif (d_frameEnabled)\n\t{\n\t\tRect tmp(Window::getUnclippedInnerRect());\n\t\ttmp.d_left\t\t+= d_left_width;\n\t\ttmp.d_right\t\t-= d_right_width;\n\t\ttmp.d_top\t\t+= d_top_height;\n\t\ttmp.d_bottom\t-= d_bottom_height;\n\t\treturn tmp;\n\t}\n\t\/\/ no frame, so return default inner rect.\n\telse\n\t{\n\t\treturn Window::getUnclippedInnerRect();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tEnable or disable rendering of the frame for this static widget.\n*************************************************************************\/\nvoid Static::setFrameEnabled(bool setting)\n{\n\tif (d_frameEnabled != setting)\n\t{\n\t\td_frameEnabled = setting;\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n}\n\n\n\/*************************************************************************\n\tspecify the Image objects to use for each part of the frame.\n\tA NULL may be used to omit any part.\t\n*************************************************************************\/\nvoid Static::setFrameImages(const Image* topleft, const Image* topright, const Image* bottomleft, const Image* bottomright, const Image* left, const Image* top, const Image* right, const Image* bottom)\n{\n\t\/\/ install the new images into the RenderableFrame\n\td_frame.setImages(topleft, topright, bottomleft, bottomright, left, top, right, bottom);\n\n\t\/\/ get sizes of frame edges\n\td_left_width\t= (left != NULL) ? left->getWidth() : 0.0f;\n\td_right_width\t= (right != NULL) ? right->getWidth() : 0.0f;\n\td_top_height\t= (top != NULL) ? top->getHeight() : 0.0f;\n\td_bottom_height\t= (bottom != NULL) ? bottom->getHeight() : 0.0f;\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the frame\t\n*************************************************************************\/\nvoid Static::setFrameColours(const ColourRect& colours)\n{\n\td_frameCols = colours;\n\tupdateRenderableFrameColours();\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the frame\t\n*************************************************************************\/\nvoid Static::setFrameColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour)\n{\n\td_frameCols.d_top_left\t\t= top_left_colour;\n\td_frameCols.d_top_right\t\t= top_right_colour;\n\td_frameCols.d_bottom_left\t= bottom_left_colour;\n\td_frameCols.d_bottom_right\t= bottom_right_colour;\n\tupdateRenderableFrameColours();\n\n\t\/\/ redraw only if change would be seen.\n\tif (d_frameEnabled)\n\t{\n\t\tWindowEventArgs args(this);\n\t\tonStaticFrameChanged(args);\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tEnable or disable rendering of the background for this static widget.\t\n*************************************************************************\/\nvoid Static::setBackgroundEnabled(bool setting)\n{\n\tif (d_backgroundEnabled != setting)\n\t{\n\t\td_backgroundEnabled = setting;\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSet the image to use as the background for the static widget.\n*************************************************************************\/\nvoid Static::setBackgroundImage(const Image* image)\n{\n\td_background = image;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSet the image to use as the background for the static widget.\t\n*************************************************************************\/\nvoid Static::setBackgroundImage(const String& imageset, const String& image)\n{\n\tsetBackgroundImage(&ImagesetManager::getSingleton().getImageset(imageset)->getImage(image));\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the background.\t\n*************************************************************************\/\nvoid Static::setBackgroundColours(const ColourRect& colours)\n{\n\td_backgroundCols = colours;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tSets the colours to be applied when rendering the background.\t\n*************************************************************************\/\nvoid Static::setBackgroundColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour)\n{\n\td_backgroundCols.d_top_left\t\t= top_left_colour;\n\td_backgroundCols.d_top_right\t= top_right_colour;\n\td_backgroundCols.d_bottom_left\t= bottom_left_colour;\n\td_backgroundCols.d_bottom_right\t= bottom_right_colour;\n\n\tif (d_backgroundEnabled)\n\t{\n\t\trequestRedraw();\n\t}\n\n}\n\n\n\/*************************************************************************\n\tupdate the internal RenderableFrame with currently set colours and\n\talpha settings.\n*************************************************************************\/\nvoid Static::updateRenderableFrameColours(void)\n{\n\tfloat alpha = getEffectiveAlpha();\n\n\td_frame.setColours(\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_top_left, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_top_right, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_bottom_left, alpha),\n\t\tcalculateModulatedAlphaColour(d_frameCols.d_bottom_right, alpha)\n\t);\n\n}\n\n\n\/*************************************************************************\n\tgiven an ARGB colour value and a alpha float value return the colour\n\tvalue with the alpha component modulated by the given alpha float.\n*************************************************************************\/\ncolour Static::calculateModulatedAlphaColour(colour col, float alpha) const\n{\n\treturn ((col & 0x00FFFFFF) | (((colour)(((float)(col >> 24)) * alpha)) << 24));\n}\n\n\n\/*************************************************************************\n\tPerform the actual rendering for this Window.\t\n*************************************************************************\/\nvoid Static::drawSelf(float z)\n{\n\tRect clipper(getPixelRect());\n\n\t\/\/ do nothing if the widget is totally clipped.\n\tif (clipper.getWidth() == 0)\n\t{\n\t\treturn;\n\t}\n\n\tRect absrect(getUnclippedPixelRect());\n\n\t\/\/ draw frame\n\tif (d_frameEnabled)\n\t{\n\t\td_frame.draw(Vector3(absrect.d_left, absrect.d_top, z), clipper);\n\n\t\t\/\/ adjust absrect and clipper so that later stages of render to not overwite frame\n\t\tabsrect.d_left\t\t+= d_left_width;\n\t\tabsrect.d_right\t\t-= d_right_width;\n\t\tabsrect.d_top\t\t+= d_top_height;\n\t\tabsrect.d_bottom\t-= d_bottom_height;\n\n\t\tclipper = clipper.getIntersection(absrect);\n\t}\n\n\t\/\/ draw backdrop\n\tif (d_backgroundEnabled && (d_background != NULL))\n\t{\n\t\t\/\/ factor window alpha into colours to use when rendering background\n\t\tfloat alpha = getEffectiveAlpha();\n\t\tColourRect colours;\n\t\tcolours.d_top_left\t\t= calculateModulatedAlphaColour(d_backgroundCols.d_top_left, alpha);\n\t\tcolours.d_top_right\t\t= calculateModulatedAlphaColour(d_backgroundCols.d_top_right, alpha);\n\t\tcolours.d_bottom_left\t= calculateModulatedAlphaColour(d_backgroundCols.d_bottom_left, alpha);\n\t\tcolours.d_bottom_right\t= calculateModulatedAlphaColour(d_backgroundCols.d_bottom_right, alpha);\n\n\t\td_background->draw(absrect, z, clipper, colours);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when window is sized\n*************************************************************************\/\nvoid Static::onSized(WindowEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onSized(e);\n\n\t\/\/ update frame size.\n\td_frame.setSize(getAbsoluteSize());\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tHandler for when alpha value changes\n*************************************************************************\/\nvoid Static::onAlphaChanged(WindowEventArgs& e)\n{\n\t\/\/ base class processing\n\tWindow::onAlphaChanged(e);\n\n\t\/\/ update frame colours to use new alpha value\n\tupdateRenderableFrameColours();\n\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tReturn the Image being used for the specified location of the frame.\t\n*************************************************************************\/\nconst Image* Static::getImageForFrameLocation(FrameLocation location) const\n{\n\treturn d_frame.getImageForLocation(location);\n}\n\n\n\/*************************************************************************\n\tReturn the Image currently set as the background image for the widget.\n*************************************************************************\/\nconst Image* Static::getBackgroundImage(void) const\n{\n\treturn d_background;\n}\n\n\n\/*************************************************************************\n\tSet the Image to use for the specified location of the frame.\t\n*************************************************************************\/\nvoid Static::setImageForFrameLocation(FrameLocation location, const Image* image)\n{\n\td_frame.setImageForLocation(location, image);\n\n\t\/\/ update our record of image size\n\tswitch (location)\n\t{\n\tcase LeftEdge:\n\t\td_left_width = (image != NULL) ? image->getWidth() : 0;\n\t\tbreak;\n\n\tcase RightEdge:\n\t\td_right_width = (image != NULL) ? image->getWidth() : 0;\n\t\tbreak;\n\n\tcase TopEdge:\n\t\td_top_height = (image != NULL) ? image->getHeight() : 0;\n\t\tbreak;\n\n\tcase BottomEdge:\n\t\td_bottom_height = (image != NULL) ? image->getHeight() : 0;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n}\n\n\/*************************************************************************\n\tAdds properties for the static widget base class\n*************************************************************************\/\nvoid Static::addStaticProperties(void)\n{\n\taddProperty(&d_frameEnabledProperty);\n\taddProperty(&d_backgroundEnabledProperty);\n\taddProperty(&d_frameColoursProperty);\n\taddProperty(&d_backgroundColoursProperty);\n\taddProperty(&d_backgroundImageProperty);\n\taddProperty(&d_topLeftFrameProperty);\n\taddProperty(&d_topRightFrameProperty);\n\taddProperty(&d_bottomLeftFrameProperty);\n\taddProperty(&d_bottomRightFrameProperty);\n\taddProperty(&d_leftFrameProperty);\n\taddProperty(&d_topFrameProperty);\n\taddProperty(&d_rightFrameProperty);\n\taddProperty(&d_bottomFrameProperty);\n}\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>#include \"App.h\"\n\n#include \"error.h\"\n#include \"OsPath.h\"\n\n\nint App::run() {\n \/\/ TODO:\n \/\/ put merged repositories to the project from config, options; and more\n \/\/ (repositories from options have more priority - put in the beginning)\n \/\/ create\/init project\n \/\/ create\/init build\n \/\/ compile\n\n \/\/ TODO:\n \/\/ make watch mode from command line options,\n \/\/ incremental build.\n\n return ERROR_OK;\n}\n\n\nint App::initOptions(int argc, const char *argv[]) {\n return argParser.parse(options, argc, argv);\n}\n\n\nint App::initConfig() {\n std::string content;\n int error = loadConfig(content);\n if (error < ERROR_OK) return error;\n\n return iniParser(config, content);\n}\n\n\nint App::loadConfig(std::string& content) {\n \/\/ take DEFAULT_CONFIG_PATH or overriden from options\n auto search = options.flags.find(CONFIG_FLAG);\n std::string path = search != options.flags.end() ?\n search->second : DEFAULT_CONFIG_PATH;\n\n if (!OsPath::exists(path) || !OsPath::isFile(path))\n return APP_CONFIG_NOT_EXISTS;\n\n content = OsPath::load(path);\n return ERROR_OK;\n}\n<commit_msg>fix iniParser.parse<commit_after>#include \"App.h\"\n\n#include \"error.h\"\n#include \"OsPath.h\"\n\n\nint App::run() {\n \/\/ TODO:\n \/\/ put merged repositories to the project from config, options; and more\n \/\/ (repositories from options have more priority - put in the beginning)\n \/\/ create\/init project\n \/\/ create\/init build\n \/\/ compile\n\n \/\/ TODO:\n \/\/ make watch mode from command line options,\n \/\/ incremental build.\n\n return ERROR_OK;\n}\n\n\nint App::initOptions(int argc, const char *argv[]) {\n return argParser.parse(options, argc, argv);\n}\n\n\nint App::initConfig() {\n std::string content;\n int error = loadConfig(content);\n if (error < ERROR_OK) return error;\n\n return iniParser.parse(config, content);\n}\n\n\nint App::loadConfig(std::string& content) {\n \/\/ take DEFAULT_CONFIG_PATH or overriden from options\n auto search = options.flags.find(CONFIG_FLAG);\n std::string path = search != options.flags.end() ?\n search->second : DEFAULT_CONFIG_PATH;\n\n if (!OsPath::exists(path) || !OsPath::isFile(path))\n return APP_CONFIG_NOT_EXISTS;\n\n content = OsPath::load(path);\n return ERROR_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"system\/Logger.hpp\"\n#include <ctime>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <glm\/gtx\/io.hpp>\n\n#ifdef _WIN32\n#\tinclude <io.h>\n#\tinclude <cstdio>\n#else\n#\tinclude <unistd.h>\n#endif\n\n\/\/ We statically initialize the default logger.\n\/\/ We don't really care about its exact construction\/destruction moments,\n\/\/ but we want it to always be created.\nLog * Log::_defaultLogger = new Log();\n\nvoid Log::set(Level l) {\n\t_level\t\t = l;\n\t_appendPrefix = true;\n\tif(_level == Level::VERBOSE && !_verbose) {\n\t\t\/\/ In this case, we want to ignore until the next flush.\n\t\t_ignoreUntilFlush = true;\n\t\t_appendPrefix\t = false;\n\t}\n}\n\nLog::Log() {\n\n\t\/\/ Setup glm objects delimiters.\n\t_stream << glm::io::delimeter<char>('(', ')', ',');\n\n#ifdef _WIN32\n\t\/\/ Enable color output.\n\tHANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );\n\tif( h != INVALID_HANDLE_VALUE ) {\n\t\tDWORD dwMode = 0;\n\t\tif( GetConsoleMode( h, &dwMode ) ) {\n\t\t\tdwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;\n\t\t\tif( SetConsoleMode( h, dwMode ) ) {\n\t\t\t\t_useColors = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n#else\n\t\/\/ Check if the output is indeed a terminal, and not piped.\n\tconst bool isTerminal = isatty(fileno(stdout));\n\tchar * env_p\t\t = std::getenv(\"TERM\");\n\tif(isTerminal && env_p) {\n\t\t\/\/ Check if the output support colors.\n\t\tconst std::vector<std::string> terms = {\"xterm\", \"xterm-256\", \"xterm-256color\", \"vt100\", \"color\", \"ansi\", \"cygwin\", \"linux\"};\n\t\tconst std::string term(env_p);\n\t\tfor(const auto & possibleTerm : terms) {\n\t\t\tif(term == possibleTerm) {\n\t\t\t\t_useColors = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n}\n\nLog::Log(const std::string & filePath, bool logToStdin, bool verbose) :\n\t_logToStdOut(logToStdin), _verbose(verbose) {\n\n\t\/\/ Setup glm objects delimiters.\n\t_stream << glm::io::delimeter<char>('(', ')', ',');\n\t\/\/ Create file if it doesnt exist.\n\tsetFile(filePath, false);\n}\n\nvoid Log::setFile(const std::string & filePath, bool flushExisting) {\n\tif(flushExisting) {\n\t\t_stream << std::endl;\n\t\tflush();\n\t}\n\tif(_file.is_open()) {\n\t\t_file.close();\n\t}\n\t_file.open(filePath, std::ofstream::app);\n\tif(_file.is_open()) {\n\t\t_file << \"-- New session - \" << time(nullptr) << \" -------------------------------\" << std::endl;\n\t\t_useColors = false;\n\t} else {\n\t\tstd::cerr << \"[Logger] Unable to create log file at path \" << filePath << \".\" << std::endl;\n\t}\n}\n\nvoid Log::setVerbose(bool verbose) {\n\t_verbose = verbose;\n}\n\nvoid Log::setDefaultFile(const std::string & filePath) {\n\t_defaultLogger->setFile(filePath);\n}\n\nvoid Log::setDefaultVerbose(bool verbose) {\n\t_defaultLogger->setVerbose(verbose);\n}\n\nLog & Log::Info() {\n\t_defaultLogger->set(Level::INFO);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Warning() {\n\t_defaultLogger->set(Level::WARNING);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Error() {\n\t_defaultLogger->set(Level::ERROR);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Verbose() {\n\t_defaultLogger->set(Level::VERBOSE);\n\treturn *_defaultLogger;\n}\n\nvoid Log::flush() {\n\tif(!_ignoreUntilFlush) {\n\t\tconst std::string finalStr = _stream.str();\n\n\t\tif(_logToStdOut) {\n\t\t\tif(_level == Level::INFO || _level == Level::VERBOSE) {\n\t\t\t\tstd::cout << finalStr << std::flush;\n\t\t\t} else {\n\t\t\t\tstd::cerr << finalStr << std::flush;\n\t\t\t}\n\t\t}\n\t\tif(_file.is_open()) {\n\t\t\t_file << finalStr << std::flush;\n\t\t}\n\t}\n\t_ignoreUntilFlush = false;\n\t_appendPrefix\t = false;\n\t_stream.str(std::string());\n\t_stream.clear();\n\t_level = Level::INFO;\n}\n\nvoid Log::appendIfNeeded() {\n\tif(_appendPrefix) {\n\t\t_appendPrefix = false;\n\t\tif(_useColors) {\n\t\t\t_stream << _colorStrings[int(_level)];\n\t\t}\n\t\t_stream << _levelStrings[int(_level)];\n\t}\n}\n\nLog & Log::operator<<(const Domain & domain) {\n\n\tif(_appendPrefix && _useColors) {\n\t\t_stream << _colorStrings[int(_level)];\n\t}\n\t_stream << \"[\" << _domainStrings[domain] << \"] \";\n\n\tif(_appendPrefix) {\n\t\t_stream << _levelStrings[int(_level)];\n\t\t_appendPrefix = false;\n\t}\n\treturn *this;\n}\n\nLog & Log::operator<<(std::ostream & (*modif)(std::ostream &)) {\n\tappendIfNeeded();\n\n\tmodif(_stream);\n\n\tflush();\n\treturn *this;\n}\n\nLog & Log::operator<<(std::ios_base & (*modif)(std::ios_base &)) {\n\tmodif(_stream);\n\treturn *this;\n}\n<commit_msg>Logger: fix Windows compilation.<commit_after>#include \"system\/Logger.hpp\"\n#include <ctime>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <glm\/gtx\/io.hpp>\n\n#ifdef _WIN32\n#\tinclude <io.h>\n#\tinclude <cstdio>\n#\tinclude <windows.h>\n#\tifdef ERROR\n#\t\tundef ERROR\n#\tendif\n#else\n#\tinclude <unistd.h>\n#endif\n\n\/\/ We statically initialize the default logger.\n\/\/ We don't really care about its exact construction\/destruction moments,\n\/\/ but we want it to always be created.\nLog * Log::_defaultLogger = new Log();\n\nvoid Log::set(Level l) {\n\t_level\t\t = l;\n\t_appendPrefix = true;\n\tif(_level == Level::VERBOSE && !_verbose) {\n\t\t\/\/ In this case, we want to ignore until the next flush.\n\t\t_ignoreUntilFlush = true;\n\t\t_appendPrefix\t = false;\n\t}\n}\n\nLog::Log() {\n\n\t\/\/ Setup glm objects delimiters.\n\t_stream << glm::io::delimeter<char>('(', ')', ',');\n\n#ifdef _WIN32\n\t\/\/ Enable color output.\n\tHANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );\n\tif( h != INVALID_HANDLE_VALUE ) {\n\t\tDWORD dwMode = 0;\n\t\tif( GetConsoleMode( h, &dwMode ) ) {\n\t\t\tdwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;\n\t\t\tif( SetConsoleMode( h, dwMode ) ) {\n\t\t\t\t_useColors = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n#else\n\t\/\/ Check if the output is indeed a terminal, and not piped.\n\tconst bool isTerminal = isatty(fileno(stdout));\n\tchar * env_p\t\t = std::getenv(\"TERM\");\n\tif(isTerminal && env_p) {\n\t\t\/\/ Check if the output support colors.\n\t\tconst std::vector<std::string> terms = {\"xterm\", \"xterm-256\", \"xterm-256color\", \"vt100\", \"color\", \"ansi\", \"cygwin\", \"linux\"};\n\t\tconst std::string term(env_p);\n\t\tfor(const auto & possibleTerm : terms) {\n\t\t\tif(term == possibleTerm) {\n\t\t\t\t_useColors = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n}\n\nLog::Log(const std::string & filePath, bool logToStdin, bool verbose) :\n\t_logToStdOut(logToStdin), _verbose(verbose) {\n\n\t\/\/ Setup glm objects delimiters.\n\t_stream << glm::io::delimeter<char>('(', ')', ',');\n\t\/\/ Create file if it doesnt exist.\n\tsetFile(filePath, false);\n}\n\nvoid Log::setFile(const std::string & filePath, bool flushExisting) {\n\tif(flushExisting) {\n\t\t_stream << std::endl;\n\t\tflush();\n\t}\n\tif(_file.is_open()) {\n\t\t_file.close();\n\t}\n\t_file.open(filePath, std::ofstream::app);\n\tif(_file.is_open()) {\n\t\t_file << \"-- New session - \" << time(nullptr) << \" -------------------------------\" << std::endl;\n\t\t_useColors = false;\n\t} else {\n\t\tstd::cerr << \"[Logger] Unable to create log file at path \" << filePath << \".\" << std::endl;\n\t}\n}\n\nvoid Log::setVerbose(bool verbose) {\n\t_verbose = verbose;\n}\n\nvoid Log::setDefaultFile(const std::string & filePath) {\n\t_defaultLogger->setFile(filePath);\n}\n\nvoid Log::setDefaultVerbose(bool verbose) {\n\t_defaultLogger->setVerbose(verbose);\n}\n\nLog & Log::Info() {\n\t_defaultLogger->set(Level::INFO);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Warning() {\n\t_defaultLogger->set(Level::WARNING);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Error() {\n\t_defaultLogger->set(Level::ERROR);\n\treturn *_defaultLogger;\n}\n\nLog & Log::Verbose() {\n\t_defaultLogger->set(Level::VERBOSE);\n\treturn *_defaultLogger;\n}\n\nvoid Log::flush() {\n\tif(!_ignoreUntilFlush) {\n\t\tconst std::string finalStr = _stream.str();\n\n\t\tif(_logToStdOut) {\n\t\t\tif(_level == Level::INFO || _level == Level::VERBOSE) {\n\t\t\t\tstd::cout << finalStr << std::flush;\n\t\t\t} else {\n\t\t\t\tstd::cerr << finalStr << std::flush;\n\t\t\t}\n\t\t}\n\t\tif(_file.is_open()) {\n\t\t\t_file << finalStr << std::flush;\n\t\t}\n\t}\n\t_ignoreUntilFlush = false;\n\t_appendPrefix\t = false;\n\t_stream.str(std::string());\n\t_stream.clear();\n\t_level = Level::INFO;\n}\n\nvoid Log::appendIfNeeded() {\n\tif(_appendPrefix) {\n\t\t_appendPrefix = false;\n\t\tif(_useColors) {\n\t\t\t_stream << _colorStrings[int(_level)];\n\t\t}\n\t\t_stream << _levelStrings[int(_level)];\n\t}\n}\n\nLog & Log::operator<<(const Domain & domain) {\n\n\tif(_appendPrefix && _useColors) {\n\t\t_stream << _colorStrings[int(_level)];\n\t}\n\t_stream << \"[\" << _domainStrings[domain] << \"] \";\n\n\tif(_appendPrefix) {\n\t\t_stream << _levelStrings[int(_level)];\n\t\t_appendPrefix = false;\n\t}\n\treturn *this;\n}\n\nLog & Log::operator<<(std::ostream & (*modif)(std::ostream &)) {\n\tappendIfNeeded();\n\n\tmodif(_stream);\n\n\tflush();\n\treturn *this;\n}\n\nLog & Log::operator<<(std::ios_base & (*modif)(std::ios_base &)) {\n\tmodif(_stream);\n\treturn *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3112\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3112 to 3113<commit_after>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3113\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3242\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3242 to 3243<commit_after>\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3243\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cassert>\n#include <iostream>\n#include <string>\n\n#include <Python.h>\n\n\/\/------------------------------------------------------------------------------\n\nnamespace py {\n\nclass Object;\nclass Unicode;\n\nconstexpr PyMethodDef METHODDEF_END{nullptr, nullptr, 0, nullptr};\n\n\/\/------------------------------------------------------------------------------\n\nclass Exception\n{\npublic:\n\n Exception() {}\n\n};\n\n\ninline void check_return(int value)\n{\n assert(value == 0 || value == -1);\n if (value != 0)\n throw Exception();\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\ninline T* cast(PyObject* obj)\n{\n assert(T::Check(obj)); \/\/ FIXME: TypeError?\n return static_cast<T*>(obj);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nclass ref\n{\npublic:\n\n \/\/ FIXME: Do we need this?\n static ref<T> take(T* obj)\n { return ref(obj); }\n\n static ref<T> take(PyObject* obj)\n { return ref(cast<T>(obj)); }\n\n static ref<T> of(T* obj)\n { incref(obj); return ref{obj}; }\n\n static ref<T> of(PyObject* obj)\n { return of(cast<T>(obj)); }\n\n ref()\n : obj_(nullptr) {}\n ref(ref<T>&& ref)\n : obj_(ref.release()) {}\n ~ref()\n { if (obj_ != nullptr) decref(obj_); }\n\n operator T*() const\n { return obj_; }\n\n T* operator->() const\n { return obj_; }\n\n T* release()\n { auto obj = obj_; obj_ = nullptr; return obj; }\n\n\nprivate:\n\n ref(T* obj)\n : obj_(obj) {}\n\n T* obj_;\n\n};\n\n\ninline PyObject* incref(PyObject* obj)\n{\n Py_INCREF(obj);\n return obj;\n}\n\n\ninline PyObject* decref(PyObject* obj)\n{\n Py_DECREF(obj);\n return obj;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Object\n : public PyObject\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return true; }\n\n Object() = delete;\n ~Object() = delete;\n\n auto length()\n { return PyObject_Length(this); }\n auto repr()\n { return ref<Unicode>::take(PyObject_Repr(this)); }\n auto str()\n { return ref<Unicode>::take(PyObject_Str(this)); }\n\n};\n\n\ntemplate<typename T>\ninline std::ostream& operator<<(std::ostream& os, ref<T>& ref)\n{\n os << ref->str()->as_utf8();\n return os;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Unicode\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyUnicode_Check(obj); }\n\n static auto FromString(char* utf8)\n { return ref<Unicode>::take(PyUnicode_FromString(utf8)); }\n \/\/ FIXME: Cast on const here?\n static auto FromStringAndSize(char* utf8, size_t length)\n { return ref<Unicode>::take(PyUnicode_FromStringAndSize(utf8, length)); }\n\n static auto from(std::string const& str)\n { return FromStringAndSize(const_cast<char*>(str.c_str()), str.length()); }\n\n char* as_utf8() { return PyUnicode_AsUTF8(this); }\n\n std::string as_utf8_string()\n {\n Py_ssize_t length;\n char* const utf8 = PyUnicode_AsUTF8AndSize(this, &length);\n if (utf8 == nullptr)\n throw Exception();\n else\n return std::string(utf8, length);\n }\n\n};\n\n\ntemplate<>\ninline std::ostream& operator<<(std::ostream& os, ref<Unicode>& ref)\n{\n os << ref->as_utf8();\n return os;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Long\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyLong_Check(obj); }\n static auto create(long val)\n { return ref<Long>::take(PyLong_FromLong(val)); }\n\n operator long()\n { return PyLong_AsLong(this); }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Module\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyModule_Check(obj); }\n static auto Create(PyModuleDef* def)\n { return ref<Module>::take(PyModule_Create(def)); }\n\n void AddObject(char const* name, PyObject* val)\n { check_return(PyModule_AddObject(this, name, incref(val))); }\n\n void add(PyTypeObject* type)\n {\n \/\/ Make sure the qualified name of the type includes this module's name.\n std::string const qualname = type->tp_name;\n std::string const mod_name = PyModule_GetName(this);\n auto dot = qualname.find_last_of('.');\n assert(dot != std::string::npos);\n assert(qualname.compare(0, dot, mod_name) == 1);\n \/\/ Add it, under its unqualified name.\n AddObject(qualname.substr(dot + 1).c_str(), (PyObject*) type);\n }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass ExtensionType\n : public Object\n{\npublic:\n\n PyObject_HEAD\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Type\n : public PyTypeObject\n{\npublic:\n\n Type(PyTypeObject o) : PyTypeObject(o) {}\n\n void Ready()\n { check_return(PyType_Ready(this)); }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\n} \/\/ namespace py\n\n\n<commit_msg>Method wrapper.<commit_after>#pragma once\n\n#include <cassert>\n#include <iostream>\n#include <string>\n\n#include <Python.h>\n\n\/\/------------------------------------------------------------------------------\n\nnamespace py {\n\nclass Object;\nclass Unicode;\n\nconstexpr PyMethodDef METHODDEF_END{nullptr, nullptr, 0, nullptr};\n\n\/\/------------------------------------------------------------------------------\n\nclass Exception\n{\npublic:\n\n Exception() {}\n\n};\n\n\ninline void check_return(int value)\n{\n assert(value == 0 || value == -1);\n if (value != 0)\n throw Exception();\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\ninline T* cast(PyObject* obj)\n{\n assert(T::Check(obj)); \/\/ FIXME: TypeError?\n return static_cast<T*>(obj);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nclass ref\n{\npublic:\n\n \/\/ FIXME: Do we need this?\n static ref<T> take(T* obj)\n { return ref(obj); }\n\n static ref<T> take(PyObject* obj)\n { return ref(cast<T>(obj)); }\n\n static ref<T> of(T* obj)\n { incref(obj); return ref{obj}; }\n\n static ref<T> of(PyObject* obj)\n { return of(cast<T>(obj)); }\n\n ref()\n : obj_(nullptr) {}\n ref(ref<T>&& ref)\n : obj_(ref.release()) {}\n ~ref()\n { if (obj_ != nullptr) decref(obj_); }\n\n operator T*() const\n { return obj_; }\n\n T* operator->() const\n { return obj_; }\n\n T* release()\n { auto obj = obj_; obj_ = nullptr; return obj; }\n\n\nprivate:\n\n ref(T* obj)\n : obj_(obj) {}\n\n T* obj_;\n\n};\n\n\ninline PyObject* incref(PyObject* obj)\n{\n Py_INCREF(obj);\n return obj;\n}\n\n\ninline PyObject* decref(PyObject* obj)\n{\n Py_DECREF(obj);\n return obj;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Object\n : public PyObject\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return true; }\n\n Object() = delete;\n ~Object() = delete;\n\n auto length()\n { return PyObject_Length(this); }\n auto repr()\n { return ref<Unicode>::take(PyObject_Repr(this)); }\n auto str()\n { return ref<Unicode>::take(PyObject_Str(this)); }\n\n};\n\n\ntemplate<typename T>\ninline std::ostream& operator<<(std::ostream& os, ref<T>& ref)\n{\n os << ref->str()->as_utf8();\n return os;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Unicode\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyUnicode_Check(obj); }\n\n static auto FromString(char* utf8)\n { return ref<Unicode>::take(PyUnicode_FromString(utf8)); }\n \/\/ FIXME: Cast on const here?\n static auto FromStringAndSize(char* utf8, size_t length)\n { return ref<Unicode>::take(PyUnicode_FromStringAndSize(utf8, length)); }\n\n static auto from(std::string const& str)\n { return FromStringAndSize(const_cast<char*>(str.c_str()), str.length()); }\n\n char* as_utf8() { return PyUnicode_AsUTF8(this); }\n\n std::string as_utf8_string()\n {\n Py_ssize_t length;\n char* const utf8 = PyUnicode_AsUTF8AndSize(this, &length);\n if (utf8 == nullptr)\n throw Exception();\n else\n return std::string(utf8, length);\n }\n\n};\n\n\ntemplate<>\ninline std::ostream& operator<<(std::ostream& os, ref<Unicode>& ref)\n{\n os << ref->as_utf8();\n return os;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Long\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyLong_Check(obj); }\n static auto create(long val)\n { return ref<Long>::take(PyLong_FromLong(val)); }\n\n operator long()\n { return PyLong_AsLong(this); }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Module\n : public Object\n{\npublic:\n\n static bool Check(PyObject* obj)\n { return PyModule_Check(obj); }\n static auto Create(PyModuleDef* def)\n { return ref<Module>::take(PyModule_Create(def)); }\n\n void AddObject(char const* name, PyObject* val)\n { check_return(PyModule_AddObject(this, name, incref(val))); }\n\n void add(PyTypeObject* type)\n {\n \/\/ Make sure the qualified name of the type includes this module's name.\n std::string const qualname = type->tp_name;\n std::string const mod_name = PyModule_GetName(this);\n auto dot = qualname.find_last_of('.');\n assert(dot != std::string::npos);\n assert(qualname.compare(0, dot, mod_name) == 1);\n \/\/ Add it, under its unqualified name.\n AddObject(qualname.substr(dot + 1).c_str(), (PyObject*) type);\n }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass ExtensionType\n : public Object\n{\npublic:\n\n PyObject_HEAD\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\nclass Type\n : public PyTypeObject\n{\npublic:\n\n Type(PyTypeObject o) : PyTypeObject(o) {}\n\n void Ready()\n { check_return(PyType_Ready(this)); }\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nusing Method = ref<Object> (*)(T*, Object*, Object*);\n\ntemplate<typename T, Method<T> M>\nPyObject* wrap_method(PyObject* self, PyObject* args, PyObject* kw_args)\n{\n try {\n return M((T*) self, (Object*) args, (Object*) kw_args).release();\n }\n catch (Exception) {\n return nullptr;\n }\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n} \/\/ namespace py\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries\n * Copyright (C) 2016 Kåre Särs <kare.sars@iki.fi>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include <QCoreApplication>\n#include <QFile>\n#include <QFileInfo>\n#include <QString>\n#include <QRegularExpression>\n#include <QDebug>\n#include <QCommandLineParser>\n\nQString link(const QString &path, const QString &fileName)\n{\n QFile in(path + QLatin1Char('\/') + fileName);\n if (!in.open(QIODevice::ReadOnly)) {\n qDebug() << \"failed to read\" << path << fileName << in.fileName();\n return QString();\n }\n\n QString firstLine = QString::fromLocal8Bit(in.readLine());\n if (firstLine.isEmpty()) {\n qDebug() << in.fileName() << \"line could not be read...\";\n return QString();\n }\n QRegularExpression fNameReg(QStringLiteral(\"(.*\\\\.(?:svg|png|gif|ico))\"));\n QRegularExpressionMatch match = fNameReg.match(firstLine);\n if (!match.hasMatch()) {\n return QString();\n }\n\n QFileInfo linkInfo(path + QLatin1Char('\/') + match.captured(1));\n QString aliasLink = link(linkInfo.path(), linkInfo.fileName());\n if (!aliasLink.isEmpty()) {\n \/\/qDebug() << fileName << \"=\" << match.captured(1) << \"=\" << aliasLink;\n return aliasLink;\n }\n\n return path + QLatin1Char('\/') + match.captured(1);\n}\n\nint parseFile(const QString &infile, const QString &outfile)\n{\n QFile in(infile);\n QFile out(outfile);\n QRegularExpression imageReg(QStringLiteral(\"<file>(.*\\\\.(?:svg|png|gif|ico))<\/file>\"));\n\n if (!in.open(QIODevice::ReadOnly)) {\n qDebug() << \"Failed to open\" << infile;\n return -1;\n }\n if (!out.open(QIODevice::WriteOnly)) {\n qDebug() << \"Failed to create\" << outfile;\n return -2;\n }\n\n while (in.bytesAvailable()) {\n QString line = QString::fromLocal8Bit(in.readLine());\n QRegularExpressionMatch match = imageReg.match(line);\n if (!match.hasMatch()) {\n \/\/qDebug() << \"No Match: \" << line;\n out.write(qPrintable(line));\n continue;\n }\n\n QFileInfo info(match.captured(1));\n\n QString aliasLink = link(info.path(), info.fileName());\n if (aliasLink.isEmpty()) {\n \/\/qDebug() << \"No alias: \" << line;\n out.write(qPrintable(line));\n continue;\n }\n\n QString newLine = QStringLiteral(\"<file alias=\\\"%1\\\">%2<\/file>\\n\").arg(match.captured(1), aliasLink);\n \/\/qDebug() << newLine;\n out.write(qPrintable(newLine));\n }\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n QCommandLineParser parser;\n\n QCommandLineOption inOption(QStringList() << QLatin1String(\"i\") << QLatin1String(\"infile\"), QStringLiteral(\"Input qrc file\"), QStringLiteral(\"infile\"));\n QCommandLineOption outOption(QStringList() << QLatin1String(\"o\") << QLatin1String(\"outfile\"), QStringLiteral(\"Output qrc file\"), QStringLiteral(\"outfile\"));\n parser.setApplicationDescription(\n QLatin1String(\"On Windows git handles symbolic links by converting them \"\n \"to text files containing the links to the actual file. This application \"\n \"takes a .qrc file as input and outputs a .qrc file with the symbolic \"\n \"links converted to qrc-aliases.\"));\n parser.addHelpOption();\n parser.addVersionOption();\n parser.addOption(inOption);\n parser.addOption(outOption);\n parser.process(app);\n\n const QString inName = parser.value(inOption);\n const QString outName = parser.value(outOption);\n\n return parseFile(inName, outName);\n}\n<commit_msg>Fix fNameReg regex<commit_after>\/* This file is part of the KDE libraries\n * Copyright (C) 2016 Kåre Särs <kare.sars@iki.fi>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include <QCoreApplication>\n#include <QFile>\n#include <QFileInfo>\n#include <QString>\n#include <QRegularExpression>\n#include <QDebug>\n#include <QCommandLineParser>\n\nQString link(const QString &path, const QString &fileName)\n{\n QFile in(path + QLatin1Char('\/') + fileName);\n if (!in.open(QIODevice::ReadOnly)) {\n qDebug() << \"failed to read\" << path << fileName << in.fileName();\n return QString();\n }\n\n QString firstLine = QString::fromLocal8Bit(in.readLine());\n if (firstLine.isEmpty()) {\n qDebug() << in.fileName() << \"line could not be read...\";\n return QString();\n }\n QRegularExpression fNameReg(QStringLiteral(\"(.*\\\\.(?:svg|png|gif|ico))$\"));\n QRegularExpressionMatch match = fNameReg.match(firstLine);\n if (!match.hasMatch()) {\n return QString();\n }\n\n QFileInfo linkInfo(path + QLatin1Char('\/') + match.captured(1));\n QString aliasLink = link(linkInfo.path(), linkInfo.fileName());\n if (!aliasLink.isEmpty()) {\n \/\/qDebug() << fileName << \"=\" << match.captured(1) << \"=\" << aliasLink;\n return aliasLink;\n }\n\n return path + QLatin1Char('\/') + match.captured(1);\n}\n\nint parseFile(const QString &infile, const QString &outfile)\n{\n QFile in(infile);\n QFile out(outfile);\n QRegularExpression imageReg(QStringLiteral(\"<file>(.*\\\\.(?:svg|png|gif|ico))<\/file>\"));\n\n if (!in.open(QIODevice::ReadOnly)) {\n qDebug() << \"Failed to open\" << infile;\n return -1;\n }\n if (!out.open(QIODevice::WriteOnly)) {\n qDebug() << \"Failed to create\" << outfile;\n return -2;\n }\n\n while (in.bytesAvailable()) {\n QString line = QString::fromLocal8Bit(in.readLine());\n QRegularExpressionMatch match = imageReg.match(line);\n if (!match.hasMatch()) {\n \/\/qDebug() << \"No Match: \" << line;\n out.write(qPrintable(line));\n continue;\n }\n\n QFileInfo info(match.captured(1));\n\n QString aliasLink = link(info.path(), info.fileName());\n if (aliasLink.isEmpty()) {\n \/\/qDebug() << \"No alias: \" << line;\n out.write(qPrintable(line));\n continue;\n }\n\n QString newLine = QStringLiteral(\"<file alias=\\\"%1\\\">%2<\/file>\\n\").arg(match.captured(1), aliasLink);\n \/\/qDebug() << newLine;\n out.write(qPrintable(newLine));\n }\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n QCommandLineParser parser;\n\n QCommandLineOption inOption(QStringList() << QLatin1String(\"i\") << QLatin1String(\"infile\"), QStringLiteral(\"Input qrc file\"), QStringLiteral(\"infile\"));\n QCommandLineOption outOption(QStringList() << QLatin1String(\"o\") << QLatin1String(\"outfile\"), QStringLiteral(\"Output qrc file\"), QStringLiteral(\"outfile\"));\n parser.setApplicationDescription(\n QLatin1String(\"On Windows git handles symbolic links by converting them \"\n \"to text files containing the links to the actual file. This application \"\n \"takes a .qrc file as input and outputs a .qrc file with the symbolic \"\n \"links converted to qrc-aliases.\"));\n parser.addHelpOption();\n parser.addVersionOption();\n parser.addOption(inOption);\n parser.addOption(outOption);\n parser.process(app);\n\n const QString inName = parser.value(inOption);\n const QString outName = parser.value(outOption);\n\n return parseFile(inName, outName);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"lesh.hpp\"\t\n\nnamespace Primitive {\nValue apply_plus(const Vlist& arguments);\nValue apply_minus(const Vlist& arguments);\nValue apply_multiply(const Vlist& arguments);\nValue apply_equal(const Vlist& arguments);\nValue apply_null(const Vlist& arguments);\nValue apply_list(const Vlist& arguments);\nValue apply_car(const Vlist& arguments);\nValue apply_cdr(const Vlist& arguments);\n\nconst Symbol END_OF_FUNC_LIST = \"__END_OF_FUNC_LIST__\";\n\ntypedef Value (*PrimitiveFuncp)(const Vlist&);\n\n\/**\n * symbol and function table\n *\/\nconst pair<Symbol, PrimitiveFuncp> func_table[] = {\n\tmake_pair(SYMBOL_PLUS, &apply_plus),\n\tmake_pair(SYMBOL_MINUS, &apply_minus),\n\tmake_pair(SYMBOL_MULTIPLY, &apply_multiply),\n\tmake_pair(SYMBOL_EQUAL, &apply_equal),\n\tmake_pair(SYMBOL_NULL, &apply_null),\n\tmake_pair(SYMBOL_LIST, &apply_list),\n\tmake_pair(SYMBOL_CAR, &apply_car),\n\tmake_pair(SYMBOL_CDR, &apply_cdr),\n\tmake_pair(END_OF_FUNC_LIST, &apply_plus),\n};\n\n\nvoid define_variables(Env &env) {\n\tenv.define_variable( SYMBOL_TRUE, Value(SYMBOL_TRUE));\n\tenv.define_variable( SYMBOL_FALSE, Value(SYMBOL_FALSE));\n\tfor ( auto i=0; func_table[i].first!=END_OF_FUNC_LIST; i++ ) {\n\t\tenv.define_variable( func_table[i].first, Value(func_table[i].first, PRIMITIVE));\n\t}\n}\n\nValue apply_procedure(const Symbol& sym, const Vlist& arguments) {\n\tfor ( auto i=0; func_table[i].first!=END_OF_FUNC_LIST; i++ ) {\n\t\tif ( func_table[i].first == sym ) {\n\t\t\treturn func_table[i].second(arguments);\n\t\t}\n\t}\n\treturn Value(SYMBOL_ERROR);\n}\n\nValue apply_plus(const Vlist& arguments) {\n\t\tauto ret=0;\n\t\tfor( auto itr=arguments.begin(); itr!=arguments.end(); itr++ ){\n\t\t\tret += itr->num;\n\t\t}\n\t\treturn Value(ret);\n}\n\nValue apply_minus(const Vlist& arguments) {\n\t\tauto itr=arguments.begin();\n\t\tauto ret = itr->num;\n\t\tfor( itr++; itr!=arguments.end(); itr++ ){\n\t\t\tret -= itr->num;\n\t\t}\n\t\treturn Value(ret);\n} \n\nValue apply_multiply(const Vlist& arguments) {\n\t\tauto ret=1;\n\t\tfor( auto itr=arguments.begin(); itr!=arguments.end(); itr++ ){\n\t\t\tret *= itr->num;\n\t\t}\n\t\treturn Value(ret);\n} \n\nValue apply_equal(const Vlist& arguments) {\n\t\tauto itr=arguments.cbegin();\n\t\tauto j = itr;\n\t\t++itr;\n\t\t\/\/assert( j->type == NUM );\n\t\tif ( itr->num == j->num ) \n\t\t\treturn Value(SYMBOL_TRUE);\n\t\telse\n\t\t\treturn Value(SYMBOL_FALSE);\n}\n\nValue apply_null(const Vlist& arguments) {\n\t\tauto first=arguments.cbegin();\n\t\tif ( first->type == LIST && first->vlist.size()==0 )\n\t\t\treturn Value(SYMBOL_TRUE);\n\t\telse\n\t\t\treturn Value(SYMBOL_FALSE);\n}\n\nValue apply_list(const Vlist& arguments) {\n\t\treturn Vlist(arguments.begin(),arguments.end());\n}\n\nValue apply_car(const Vlist& arguments) {\n\t\tif ( arguments.size() != 1 ) cerr << \"err-argument\" << endl;\n\t\tauto first=arguments.cbegin();\n\t\treturn *(first->vlist.begin());\n}\n\nValue apply_cdr(const Vlist& arguments) {\n\t\tif ( arguments.size() != 1 ) cerr << \"err-argument\" << endl;\n\t\tauto first=arguments.begin();\n\t\treturn Vlist(first->vlist.begin()+1,first->vlist.end());\n}\n\n\n}\n\n<commit_msg>macosx clang not support cbegin<commit_after>#include \"lesh.hpp\"\t\n\nnamespace Primitive {\nValue apply_plus(const Vlist& arguments);\nValue apply_minus(const Vlist& arguments);\nValue apply_multiply(const Vlist& arguments);\nValue apply_equal(const Vlist& arguments);\nValue apply_null(const Vlist& arguments);\nValue apply_list(const Vlist& arguments);\nValue apply_car(const Vlist& arguments);\nValue apply_cdr(const Vlist& arguments);\n\nconst Symbol END_OF_FUNC_LIST = \"__END_OF_FUNC_LIST__\";\n\ntypedef Value (*PrimitiveFuncp)(const Vlist&);\n\n\/**\n * symbol and function table\n *\/\nconst pair<Symbol, PrimitiveFuncp> func_table[] = {\n\tmake_pair(SYMBOL_PLUS, &apply_plus),\n\tmake_pair(SYMBOL_MINUS, &apply_minus),\n\tmake_pair(SYMBOL_MULTIPLY, &apply_multiply),\n\tmake_pair(SYMBOL_EQUAL, &apply_equal),\n\tmake_pair(SYMBOL_NULL, &apply_null),\n\tmake_pair(SYMBOL_LIST, &apply_list),\n\tmake_pair(SYMBOL_CAR, &apply_car),\n\tmake_pair(SYMBOL_CDR, &apply_cdr),\n\tmake_pair(END_OF_FUNC_LIST, &apply_plus),\n};\n\n\nvoid define_variables(Env &env) {\n\tenv.define_variable( SYMBOL_TRUE, Value(SYMBOL_TRUE));\n\tenv.define_variable( SYMBOL_FALSE, Value(SYMBOL_FALSE));\n\tfor ( auto i=0; func_table[i].first!=END_OF_FUNC_LIST; i++ ) {\n\t\tenv.define_variable( func_table[i].first, Value(func_table[i].first, PRIMITIVE));\n\t}\n}\n\nValue apply_procedure(const Symbol& sym, const Vlist& arguments) {\n\tfor ( auto i=0; func_table[i].first!=END_OF_FUNC_LIST; i++ ) {\n\t\tif ( func_table[i].first == sym ) {\n\t\t\treturn func_table[i].second(arguments);\n\t\t}\n\t}\n\treturn Value(SYMBOL_ERROR);\n}\n\nValue apply_plus(const Vlist& arguments) {\n\t\tauto ret=0;\n\t\tfor( auto itr=arguments.begin(); itr!=arguments.end(); itr++ ){\n\t\t\tret += itr->num;\n\t\t}\n\t\treturn Value(ret);\n}\n\nValue apply_minus(const Vlist& arguments) {\n\t\tauto itr=arguments.begin();\n\t\tauto ret = itr->num;\n\t\tfor( itr++; itr!=arguments.end(); itr++ ){\n\t\t\tret -= itr->num;\n\t\t}\n\t\treturn Value(ret);\n} \n\nValue apply_multiply(const Vlist& arguments) {\n\t\tauto ret=1;\n\t\tfor( auto itr=arguments.begin(); itr!=arguments.end(); itr++ ){\n\t\t\tret *= itr->num;\n\t\t}\n\t\treturn Value(ret);\n} \n\nValue apply_equal(const Vlist& arguments) {\n\t\tauto itr=arguments.begin();\n\t\tauto j = itr;\n\t\t++itr;\n\t\t\/\/assert( j->type == NUM );\n\t\tif ( itr->num == j->num ) \n\t\t\treturn Value(SYMBOL_TRUE);\n\t\telse\n\t\t\treturn Value(SYMBOL_FALSE);\n}\n\nValue apply_null(const Vlist& arguments) {\n\t\tauto first=arguments.begin();\n\t\tif ( first->type == LIST && first->vlist.size()==0 )\n\t\t\treturn Value(SYMBOL_TRUE);\n\t\telse\n\t\t\treturn Value(SYMBOL_FALSE);\n}\n\nValue apply_list(const Vlist& arguments) {\n\t\treturn Vlist(arguments.begin(),arguments.end());\n}\n\nValue apply_car(const Vlist& arguments) {\n\t\tif ( arguments.size() != 1 ) cerr << \"err-argument\" << endl;\n\t\tauto first=arguments.begin();\n\t\treturn *(first->vlist.begin());\n}\n\nValue apply_cdr(const Vlist& arguments) {\n\t\tif ( arguments.size() != 1 ) cerr << \"err-argument\" << endl;\n\t\tauto first=arguments.begin();\n\t\treturn Vlist(first->vlist.begin()+1,first->vlist.end());\n}\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"r_texture.h\"\n#include \"u_sha512.h\"\n#include \"u_file.h\"\n#include \"engine.h\"\n\n#ifdef GL_UNSIGNED_INT_8_8_8_8_REV\n# define R_TEX_DATA_RGBA GL_UNSIGNED_INT_8_8_8_8_REV\n#else\n# define R_TEX_DATA_RGBA GL_UNSINGED_BYTE\n#endif\n#ifdef GL_UNSIGNED_INT_8_8_8_8\n# define R_TEX_DATA_BGRA GL_UNSIGNED_INT_8_8_8_8\n#else\n# define R_TEX_DATA_BGRA GL_UNSIGNED_BYTE\n#endif\n\nstruct textureDXTCacheHeader {\n size_t width;\n size_t height;\n \/\/ Original format (RGB or RGBA) == (DXT1 or DXT5)\n textureFormat format;\n};\n\nstatic bool readDXTCache(texture &tex) {\n \/\/ Do we even have it in cache?\n const u::string path = neoPath() + \"cache\/\";\n u::sha512 hash(tex.data(), tex.size());\n const u::string file = path + hash.hex();\n if (!u::exists(file))\n return false;\n\n \/\/ Found it in cache, unload the current texture and load the cache from disk.\n auto load = u::read(file, \"rb\");\n if (!load)\n return false;\n\n \/\/ Parse header\n auto vec = *load;\n textureDXTCacheHeader head;\n memcpy(&head, &vec[0], sizeof(head));\n\n const unsigned char *data = &vec[0] + sizeof(head);\n const size_t length = vec.size() - sizeof(head);\n\n \/\/ Now swap!\n tex.unload();\n tex.from(data, length, head.width, head.height, head.format);\n\n printf(\"R DXT: %s\\n\", file.c_str());\n return true;\n}\n\nstatic bool writeDXTCache(const texture &tex, GLuint handle) {\n \/\/ Don't bother caching if we already have it\n const u::string path = neoPath() + \"cache\/\";\n u::sha512 hash(tex.data(), tex.size());\n const u::string file = path + hash.hex();\n if (u::exists(file))\n return false;\n\n \/\/ Build the header\n textureDXTCacheHeader head;\n head.width = tex.width();\n head.height = tex.height();\n head.format = tex.format();\n\n \/\/ Query the compressed texture size\n gl::BindTexture(GL_TEXTURE_2D, handle);\n GLint compressedSize;\n gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0,\n GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &compressedSize);\n\n \/\/ Prepare the data\n u::vector<unsigned char> data;\n data.resize(sizeof(head) + compressedSize);\n memcpy(&data[0], &head, sizeof(head));\n\n \/\/ Read the compressed image\n gl::GetCompressedTexImage(GL_TEXTURE_2D, 0, &data[0] + sizeof(head));\n\n \/\/ Write it to disk!\n printf(\"W DXT: %s\\n\", file.c_str());\n return u::write(data, file);\n}\n\nstruct queryFormat {\n GLenum format;\n GLenum data;\n GLenum internal;\n};\n\n\/\/ Given a source texture the following function finds the best way to present\n\/\/ that texture to the hardware. This function will also favor texture compression\n\/\/ if the hardware supports it by converting the texture if it needs to.\nstatic queryFormat getBestFormat(texture &tex) {\n queryFormat fmt;\n memset(&fmt, 0, sizeof(fmt));\n textureFormat format = tex.format();\n\n \/\/ Convert the textures to a format S3TC texture compression supports if\n \/\/ the hardware supports S3TC compression\n if (gl::has(\"GL_EXT_texture_compression_s3tc\")) {\n if (format == TEX_BGRA)\n tex.convert<TEX_RGBA>();\n else if (format == TEX_BGR)\n tex.convert<TEX_RGB>();\n }\n\n switch (format) {\n case TEX_RGBA:\n fmt.format = GL_RGBA;\n fmt.data = R_TEX_DATA_RGBA;\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n fmt.internal = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n else\n fmt.internal = GL_RGBA;\n break;\n case TEX_RGB:\n fmt.format = GL_RGB;\n fmt.data = GL_UNSIGNED_BYTE;\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n fmt.internal = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;\n else\n fmt.internal = GL_RGBA;\n break;\n\n case TEX_BGRA:\n fmt.format = GL_BGRA;\n fmt.data = R_TEX_DATA_BGRA;\n fmt.internal = GL_RGBA;\n break;\n case TEX_BGR:\n fmt.format = GL_BGR;\n fmt.data = GL_UNSIGNED_BYTE;\n fmt.internal = GL_RGBA;\n break;\n case TEX_LUMINANCE:\n fmt.format = GL_RED;\n fmt.data = GL_UNSIGNED_BYTE;\n fmt.internal = GL_RED;\n break;\n }\n return fmt;\n}\n\ntexture2D::texture2D(void) :\n m_uploaded(false),\n m_textureHandle(0)\n{\n \/\/\n}\n\ntexture2D::~texture2D(void) {\n if (m_uploaded)\n gl::DeleteTextures(1, &m_textureHandle);\n}\n\nbool texture2D::useDXTCache(void) {\n if (!gl::has(\"GL_EXT_texture_compression_s3tc\"))\n return false;\n if (!readDXTCache(m_texture))\n return false;\n switch (m_texture.format()) {\n case TEX_RGB:\n gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT,\n m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());\n break;\n case TEX_RGBA:\n gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,\n m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());\n break;\n default:\n neoFatal(\"malformatted DXT cache\");\n }\n return true;\n}\n\nbool texture2D::cacheDXT(void) {\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n return writeDXTCache(m_texture, m_textureHandle);\n return false;\n}\n\nbool texture2D::load(const u::string &file) {\n return m_texture.load(file);\n}\n\nbool texture2D::upload(void) {\n if (m_uploaded)\n return true;\n\n gl::GenTextures(1, &m_textureHandle);\n gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);\n\n bool useCache = useDXTCache();\n if (!useCache) {\n queryFormat format = getBestFormat(m_texture);\n gl::TexImage2D(GL_TEXTURE_2D, 0, format.internal, m_texture.width(),\n m_texture.height(), 0, format.format, format.data, m_texture.data());\n }\n\n gl::GenerateMipmap(GL_TEXTURE_2D);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n\n if (!useCache)\n cacheDXT();\n\n return m_uploaded = true;\n}\n\nvoid texture2D::bind(GLenum unit) {\n gl::ActiveTexture(unit);\n gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);\n}\n\nvoid texture2D::resize(size_t width, size_t height) {\n m_texture.resize(width, height);\n}\n\n\/\/\/! texture3D\ntexture3D::texture3D() :\n m_uploaded(false),\n m_textureHandle(0)\n{\n}\n\ntexture3D::~texture3D(void) {\n if (m_uploaded)\n gl::DeleteTextures(1, &m_textureHandle);\n}\n\nbool texture3D::load(const u::string &ft, const u::string &bk, const u::string &up,\n const u::string &dn, const u::string &rt, const u::string &lf)\n{\n if (!m_textures[0].load(ft)) return false;\n if (!m_textures[1].load(bk)) return false;\n if (!m_textures[2].load(up)) return false;\n if (!m_textures[3].load(dn)) return false;\n if (!m_textures[4].load(rt)) return false;\n if (!m_textures[5].load(lf)) return false;\n return true;\n}\n\nbool texture3D::upload(void) {\n if (m_uploaded)\n return true;\n\n gl::GenTextures(1, &m_textureHandle);\n gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);\n\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n\n \/\/ find the largest texture in the cubemap and scale all others to it\n size_t mw = 0;\n size_t mh = 0;\n size_t mi = 0;\n for (size_t i = 0; i < 6; i++) {\n if (m_textures[i].width() > mw && m_textures[i].height() > mh)\n mi = i;\n }\n\n const size_t fw = m_textures[mi].width();\n const size_t fh = m_textures[mi].height();\n for (size_t i = 0; i < 6; i++) {\n if (m_textures[i].width() != fw || m_textures[i].height() != fh)\n m_textures[i].resize(fw, fh);\n queryFormat format = getBestFormat(m_textures[i]);\n gl::TexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,\n format.internal, fw, fh, 0, format.format, format.data, m_textures[i].data());\n }\n\n return m_uploaded = true;\n}\n\nvoid texture3D::bind(GLenum unit) {\n gl::ActiveTexture(unit);\n gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);\n}\n\nvoid texture3D::resize(size_t width, size_t height) {\n for (size_t i = 0; i < 6; i++)\n m_textures[i].resize(width, height);\n}\n<commit_msg>Remove prints<commit_after>#include \"r_texture.h\"\n#include \"u_sha512.h\"\n#include \"u_file.h\"\n#include \"engine.h\"\n\n#ifdef GL_UNSIGNED_INT_8_8_8_8_REV\n# define R_TEX_DATA_RGBA GL_UNSIGNED_INT_8_8_8_8_REV\n#else\n# define R_TEX_DATA_RGBA GL_UNSINGED_BYTE\n#endif\n#ifdef GL_UNSIGNED_INT_8_8_8_8\n# define R_TEX_DATA_BGRA GL_UNSIGNED_INT_8_8_8_8\n#else\n# define R_TEX_DATA_BGRA GL_UNSIGNED_BYTE\n#endif\n\nstruct textureDXTCacheHeader {\n size_t width;\n size_t height;\n \/\/ Original format (RGB or RGBA) == (DXT1 or DXT5)\n textureFormat format;\n};\n\nstatic bool readDXTCache(texture &tex) {\n \/\/ Do we even have it in cache?\n const u::string path = neoPath() + \"cache\/\";\n u::sha512 hash(tex.data(), tex.size());\n const u::string file = path + hash.hex();\n if (!u::exists(file))\n return false;\n\n \/\/ Found it in cache, unload the current texture and load the cache from disk.\n auto load = u::read(file, \"rb\");\n if (!load)\n return false;\n\n \/\/ Parse header\n auto vec = *load;\n textureDXTCacheHeader head;\n memcpy(&head, &vec[0], sizeof(head));\n\n const unsigned char *data = &vec[0] + sizeof(head);\n const size_t length = vec.size() - sizeof(head);\n\n \/\/ Now swap!\n tex.unload();\n tex.from(data, length, head.width, head.height, head.format);\n return true;\n}\n\nstatic bool writeDXTCache(const texture &tex, GLuint handle) {\n \/\/ Don't bother caching if we already have it\n const u::string path = neoPath() + \"cache\/\";\n u::sha512 hash(tex.data(), tex.size());\n const u::string file = path + hash.hex();\n if (u::exists(file))\n return false;\n\n \/\/ Build the header\n textureDXTCacheHeader head;\n head.width = tex.width();\n head.height = tex.height();\n head.format = tex.format();\n\n \/\/ Query the compressed texture size\n gl::BindTexture(GL_TEXTURE_2D, handle);\n GLint compressedSize;\n gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0,\n GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &compressedSize);\n\n \/\/ Prepare the data\n u::vector<unsigned char> data;\n data.resize(sizeof(head) + compressedSize);\n memcpy(&data[0], &head, sizeof(head));\n\n \/\/ Read the compressed image\n gl::GetCompressedTexImage(GL_TEXTURE_2D, 0, &data[0] + sizeof(head));\n\n \/\/ Write it to disk!\n return u::write(data, file);\n}\n\nstruct queryFormat {\n GLenum format;\n GLenum data;\n GLenum internal;\n};\n\n\/\/ Given a source texture the following function finds the best way to present\n\/\/ that texture to the hardware. This function will also favor texture compression\n\/\/ if the hardware supports it by converting the texture if it needs to.\nstatic queryFormat getBestFormat(texture &tex) {\n queryFormat fmt;\n memset(&fmt, 0, sizeof(fmt));\n textureFormat format = tex.format();\n\n \/\/ Convert the textures to a format S3TC texture compression supports if\n \/\/ the hardware supports S3TC compression\n if (gl::has(\"GL_EXT_texture_compression_s3tc\")) {\n if (format == TEX_BGRA)\n tex.convert<TEX_RGBA>();\n else if (format == TEX_BGR)\n tex.convert<TEX_RGB>();\n }\n\n switch (format) {\n case TEX_RGBA:\n fmt.format = GL_RGBA;\n fmt.data = R_TEX_DATA_RGBA;\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n fmt.internal = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n else\n fmt.internal = GL_RGBA;\n break;\n case TEX_RGB:\n fmt.format = GL_RGB;\n fmt.data = GL_UNSIGNED_BYTE;\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n fmt.internal = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;\n else\n fmt.internal = GL_RGBA;\n break;\n\n case TEX_BGRA:\n fmt.format = GL_BGRA;\n fmt.data = R_TEX_DATA_BGRA;\n fmt.internal = GL_RGBA;\n break;\n case TEX_BGR:\n fmt.format = GL_BGR;\n fmt.data = GL_UNSIGNED_BYTE;\n fmt.internal = GL_RGBA;\n break;\n case TEX_LUMINANCE:\n fmt.format = GL_RED;\n fmt.data = GL_UNSIGNED_BYTE;\n fmt.internal = GL_RED;\n break;\n }\n return fmt;\n}\n\ntexture2D::texture2D(void) :\n m_uploaded(false),\n m_textureHandle(0)\n{\n \/\/\n}\n\ntexture2D::~texture2D(void) {\n if (m_uploaded)\n gl::DeleteTextures(1, &m_textureHandle);\n}\n\nbool texture2D::useDXTCache(void) {\n if (!gl::has(\"GL_EXT_texture_compression_s3tc\"))\n return false;\n if (!readDXTCache(m_texture))\n return false;\n switch (m_texture.format()) {\n case TEX_RGB:\n gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT,\n m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());\n break;\n case TEX_RGBA:\n gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,\n m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());\n break;\n default:\n neoFatal(\"malformatted DXT cache\");\n }\n return true;\n}\n\nbool texture2D::cacheDXT(void) {\n if (gl::has(\"GL_EXT_texture_compression_s3tc\"))\n return writeDXTCache(m_texture, m_textureHandle);\n return false;\n}\n\nbool texture2D::load(const u::string &file) {\n return m_texture.load(file);\n}\n\nbool texture2D::upload(void) {\n if (m_uploaded)\n return true;\n\n gl::GenTextures(1, &m_textureHandle);\n gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);\n\n bool useCache = useDXTCache();\n if (!useCache) {\n queryFormat format = getBestFormat(m_texture);\n gl::TexImage2D(GL_TEXTURE_2D, 0, format.internal, m_texture.width(),\n m_texture.height(), 0, format.format, format.data, m_texture.data());\n }\n\n gl::GenerateMipmap(GL_TEXTURE_2D);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n\n if (!useCache)\n cacheDXT();\n\n return m_uploaded = true;\n}\n\nvoid texture2D::bind(GLenum unit) {\n gl::ActiveTexture(unit);\n gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);\n}\n\nvoid texture2D::resize(size_t width, size_t height) {\n m_texture.resize(width, height);\n}\n\n\/\/\/! texture3D\ntexture3D::texture3D() :\n m_uploaded(false),\n m_textureHandle(0)\n{\n}\n\ntexture3D::~texture3D(void) {\n if (m_uploaded)\n gl::DeleteTextures(1, &m_textureHandle);\n}\n\nbool texture3D::load(const u::string &ft, const u::string &bk, const u::string &up,\n const u::string &dn, const u::string &rt, const u::string &lf)\n{\n if (!m_textures[0].load(ft)) return false;\n if (!m_textures[1].load(bk)) return false;\n if (!m_textures[2].load(up)) return false;\n if (!m_textures[3].load(dn)) return false;\n if (!m_textures[4].load(rt)) return false;\n if (!m_textures[5].load(lf)) return false;\n return true;\n}\n\nbool texture3D::upload(void) {\n if (m_uploaded)\n return true;\n\n gl::GenTextures(1, &m_textureHandle);\n gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);\n\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n\n \/\/ find the largest texture in the cubemap and scale all others to it\n size_t mw = 0;\n size_t mh = 0;\n size_t mi = 0;\n for (size_t i = 0; i < 6; i++) {\n if (m_textures[i].width() > mw && m_textures[i].height() > mh)\n mi = i;\n }\n\n const size_t fw = m_textures[mi].width();\n const size_t fh = m_textures[mi].height();\n for (size_t i = 0; i < 6; i++) {\n if (m_textures[i].width() != fw || m_textures[i].height() != fh)\n m_textures[i].resize(fw, fh);\n queryFormat format = getBestFormat(m_textures[i]);\n gl::TexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,\n format.internal, fw, fh, 0, format.format, format.data, m_textures[i].data());\n }\n\n return m_uploaded = true;\n}\n\nvoid texture3D::bind(GLenum unit) {\n gl::ActiveTexture(unit);\n gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);\n}\n\nvoid texture3D::resize(size_t width, size_t height) {\n for (size_t i = 0; i < 6; i++)\n m_textures[i].resize(width, height);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __Rectangle__\n#define __Rectangle__\n\n#ifdef __APPLE__\n#include <GLUT\/glut.h>\n#else\n#include <GL\/glut.h>\n#endif\n#include \"color.hpp\"\n\nusing namespace std;\n\nclass Rectangle {\npublic:\n\tdouble x1, y1, x2, y2;\n\tdouble width, height;\n\tColor color;\n\n\tvoid init(double x, double y, double w, double h, Color c);\n\n\tRectangle();\n\tRectangle(double x, double y, double w, double h);\n\tRectangle(double x, double y, double w, double h, Color c);\n\tRectangle(const Rectangle &c);\n\tRectangle &operator= (const Rectangle &c);\n\t\n\tvoid setX(double x);\n\tvoid setY(double y);\n\tvoid setWidth(double w);\n\tvoid setHeight(double h);\n\tvoid setColor(Color c);\n\n\tdouble getX();\n\tdouble getY();\n\tdouble getWidth();\n\tdouble getHeight();\n\t\n\tbool hover(double x, double y);\n\tvoid draw();\n};\n\n#endif<commit_msg>Switch rectangle to use ui.hpp<commit_after>#ifndef __Rectangle__\n#define __Rectangle__\n\n#include \"ui.hpp\"\n\nusing namespace std;\n\nclass Rectangle {\npublic:\n\tdouble x1, y1, x2, y2;\n\tdouble width, height;\n\tColor color;\n\n\tvoid init(double x, double y, double w, double h, Color c);\n\n\tRectangle();\n\tRectangle(double x, double y, double w, double h);\n\tRectangle(double x, double y, double w, double h, Color c);\n\tRectangle(const Rectangle &c);\n\tRectangle &operator= (const Rectangle &c);\n\t\n\tvoid setX(double x);\n\tvoid setY(double y);\n\tvoid setWidth(double w);\n\tvoid setHeight(double h);\n\tvoid setColor(Color c);\n\n\tdouble getX();\n\tdouble getY();\n\tdouble getWidth();\n\tdouble getHeight();\n\t\n\tbool hover(double x, double y);\n\tvoid draw();\n};\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImportContainerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n#include \"itkImportImageContainer.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkOutputWindow.h\"\n#include \"itkTextOutput.h\"\n\nint itkImportContainerTest(int , char * [] )\n{\n typedef float PixelType;\n typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;\n\n itk::OutputWindow::SetInstance(itk::TextOutput::New());\n\n\/\/ First test with ContainerManagesMemory false\n PixelType *ptr1;\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 2: Reserve memory\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Take control of the pointer\n container1->ContainerManageMemoryOff();\n ptr1 = container1->GetImportPointer();\n\n \/\/ Test 3: Reserve a smaller amount of memory\n container1->Reserve(100);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n\/\/ now repeat the tests with a user provided pointer\n PixelType *myPtr = new float[2000];\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n container1->SetImportPointer(myPtr, 2000);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n *(myPtr + 500) = 500.0;\n\n \/\/ Test 2: Reserve less memory than capacity\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Reserve(1000), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Test 3: Reserve more memory than capacity\n container1->Reserve(10000);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Reserve(10000), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Squeeze(), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n \/\/ Now repeat tests with ContainerManagesMemory true\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 2: Reserve memory\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 3: Reserve a smaller amount of memory\n container1->Reserve(100);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n \/\/ SGI's always say they can get you the memory you want.\n#if !defined(__sgi)\n \/\/ Check the exception on the memory allocation\n bool caughtException = false;\n try\n {\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Reserve( itk::NumericTraits<unsigned long>::max()\/sizeof(PixelType));\n }\n catch (itk::ExceptionObject& err)\n {\n std::cout << \"Caught expected exception: \" << err << std::endl;\n caughtException = true;\n }\n#else\n caughtException = true;\n#endif\n\n \/\/ We must delete the memory we said we would manage\n delete [] ptr1;\n delete [] myPtr;\n\n if (!caughtException)\n {\n std::cout << \"Failed to catch expected exception\" << std::endl;\n return EXIT_FAILURE; \n }\n return EXIT_SUCCESS; \n}\n<commit_msg>COMP: SGIs always say they can get the memory you ask for. The expected exception will not be thrown. The oversized memory request is skipped for SGIs.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImportContainerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n#include \"itkImportImageContainer.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkOutputWindow.h\"\n#include \"itkTextOutput.h\"\n\nint itkImportContainerTest(int , char * [] )\n{\n typedef float PixelType;\n typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;\n\n itk::OutputWindow::SetInstance(itk::TextOutput::New());\n\n\/\/ First test with ContainerManagesMemory false\n PixelType *ptr1;\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 2: Reserve memory\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Take control of the pointer\n container1->ContainerManageMemoryOff();\n ptr1 = container1->GetImportPointer();\n\n \/\/ Test 3: Reserve a smaller amount of memory\n container1->Reserve(100);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n\/\/ now repeat the tests with a user provided pointer\n PixelType *myPtr = new float[2000];\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n container1->SetImportPointer(myPtr, 2000);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n *(myPtr + 500) = 500.0;\n\n \/\/ Test 2: Reserve less memory than capacity\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Reserve(1000), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Test 3: Reserve more memory than capacity\n container1->Reserve(10000);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Reserve(10000), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n if (*(myPtr + 500) != 500.0)\n {\n std::cout << \"Test failed: After container1->Squeeze(), container1[500] does != 500.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n \/\/ Now repeat tests with ContainerManagesMemory true\n {\n \/\/ Test 1: Create an empty container and print it\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Print(std::cout);\n std::cout << \"After New(), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n\n \/\/ Test 2: Reserve memory\n container1->Reserve(1000);\n std::cout << \"After container1->Reserve(1000), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 3: Reserve a smaller amount of memory\n container1->Reserve(100);\n std::cout << \"After container1->Reserve(100), size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 4: Squeeze the container\n container1->Squeeze();\n std::cout << \"After container1->Squeeze() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n\n \/\/ Test 5: Initialize the container\n container1->Initialize();\n std::cout << \"After container1->Initialize() size is \"\n << container1->Size()\n << \", capacity is \"\n << container1->Capacity()\n << \" and import pointer is \"\n << container1->GetImportPointer()\n << std::endl;\n }\n\n \/\/ SGI's always say they can get you the memory you want.\n#if !defined(__sgi)\n \/\/ Check the exception on the memory allocation\n bool caughtException = false;\n try\n {\n ContainerType::Pointer container1 = ContainerType::New();\n container1->Reserve( itk::NumericTraits<unsigned long>::max()\/sizeof(PixelType));\n }\n catch (itk::ExceptionObject& err)\n {\n std::cout << \"Caught expected exception: \" << err << std::endl;\n caughtException = true;\n }\n#endif\n\n \/\/ We must delete the memory we said we would manage\n delete [] ptr1;\n delete [] myPtr;\n\n \/\/ SGI's always say they can get you the memory you want.\n#if !defined(__sgi)\n if (!caughtException)\n {\n std::cout << \"Failed to catch expected exception\" << std::endl;\n return EXIT_FAILURE;\n }\n#endif\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n\/\/#include \"jsoncpp\/json\/json.h\"\n#include <map>\n#include <errno.h>\n#include <fcntl.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n\n#include \"nvme.h\"\n#include \"mp.h\"\n\nclass StringSearchResponse : public StringSearchResponseWrapper {\npublic:\n virtual void strstrLoc ( const uint32_t pos ) {\n\tif (pos != -1)\n\t fprintf(stderr, \"string search at character pos=%d\\n\", pos);\n }\n StringSearchResponse(int id, PortalPoller *poller = 0) : StringSearchResponseWrapper(id, poller) {\n }\n};\n\nint main(int argc, char * const *argv)\n{\n Nvme nvme;\n StringSearchRequestProxy search(IfcNames_StringSearchRequestS2H);\n StringSearchResponse searchResponse(IfcNames_StringSearchResponseH2S);\n\n int flags, opt;\n const char *filename;\n const char *needle = \"needle\";\n int source_fd = -1;\n\n int doidentify;\n int dosearch = 0;\n int dotrace = 0;\n int dowrite = 0;\n while ((opt = getopt(argc, argv, \"iw:s:t\")) != -1) {\n\tswitch (opt) {\n\tcase 'i':\n\t doidentify = 1;\n\t break;\n\tcase 's':\n\t needle = optarg;\n\t dosearch = 1;\n\t break;\n\tcase 't':\n\t dotrace = 1;\n\t break;\n\tcase 'w':\n\t filename = optarg;\n\t dowrite = 1;\n\t break;\n\t}\n }\n\n if (dowrite) {\n\tstruct stat statbuf;\n\tint rc = stat(filename, &statbuf);\n\tif (rc < 0) {\n\t fprintf(stderr, \"%s:%d File %s does not exist %d:%s\\n\", __FILE__, __LINE__, filename, errno, strerror(errno));\n\t char pwd[128];\n\t getcwd(pwd, sizeof(pwd));\n\t fprintf(stderr, \"cwd = %s\\n\", pwd);\n\t return rc;\n\t}\n }\n\n sleep(1);\n\n nvme.setup();\n\n if (dosearch) {\n\tint needle_len = strlen(needle);\n\tint border[needle_len+1];\n\n\tcompute_borders(nvme.needleBuffer.buffer(), border, needle_len);\n\tcompute_MP_next(nvme.needleBuffer.buffer(), (struct MP *)nvme.mpNextBuffer.buffer(), needle_len);\n\tnvme.needleBuffer.cacheInvalidate(0, 1); \/\/ flush the whole thing\n\tnvme.mpNextBuffer.cacheInvalidate(0, 1); \/\/ flush the whole thing\n\n\t\/\/FIXME: read the text from NVME storage\n\t\/\/MP(needle, haystack, mpNext, needle_len, haystack_len, &sw_match_cnt);\n\n\t\/\/ the MPEngine will read in the needle and mpNext\n\tsearch.setSearchString(nvme.needleRef, nvme.mpNextRef, needle_len);\n }\n\n if (doidentify)\n\tnvme.identify();\n nvme.getFeatures();\n nvme.allocIOQueues(0);\n\n fprintf(stderr, \"CSTS %08x\\n\", nvme.read32( 0x1c));\n int startBlock = 100000; \/\/ base and extent of test file in SSD\n int blocksPerRequest = 8; \/\/12*BlocksPerRequest;\n int numBlocks = 1*blocksPerRequest; \/\/ 55; \/\/8177;\n if (dosearch) {\n\tsearch.startSearch(numBlocks*512);\n } else {\n \/\/ if search is not running, then data read below will be discarded\n }\n if (dowrite) {\n\tstruct stat statbuf;\n\tint rc = stat(filename, &statbuf);\n\tif (rc < 0) {\n\t fprintf(stderr, \"%s:%d File %s does not exist %d:%s\\n\", __FILE__, __LINE__, filename, errno, strerror(errno));\n\t char pwd[128];\n\t getcwd(pwd, sizeof(pwd));\n\t fprintf(stderr, \"cwd = %s\\n\", pwd);\n\t return rc;\n\t}\n\tnumBlocks = statbuf.st_blocks;\n\tnumBlocks -= (numBlocks % blocksPerRequest);\n\tfprintf(stderr, \"Writing %d blocks from file %s to flash at block %d\\n\", numBlocks, filename, startBlock);\n\tsource_fd = open(filename, O_RDONLY);\n }\n\n for (int block = 0; block < numBlocks; block += blocksPerRequest) {\n\tnvme_io_opcode opcode = (dowrite) ? nvme_write : nvme_read;\n\tfprintf(stderr, \"starting transfer dowrite=%d opcode=%d\\n\", dowrite, opcode);\n\tif (opcode == nvme_write) {\n\t if (filename) {\n\t\tread(source_fd, (char *)nvme.transferBuffer.buffer(), 512*blocksPerRequest);\n\t } else {\n\t\t int *buffer = (int *)nvme.transferBuffer.buffer();\n\t\tfor (int i = 0; i < numBlocks*512\/4; i ++)\n\t\t buffer[i] = i;\n\t }\n\t}\n\tint sc = nvme.doIO(opcode, startBlock, blocksPerRequest, (opcode == nvme_read ? 2 : 1), dotrace);\n\tnvme.status();\n\tif (sc != 0)\n\t break;\n\tstartBlock += blocksPerRequest;\n }\n\n nvme.dumpTrace();\n \/\/nvme.transferStats();\n fprintf(stderr, \"CSTS %08x\\n\", nvme.read32( 0x1c));\n\n return 0;\n}\n<commit_msg>include ConnectalProjectConfig.h<commit_after>#include <stdio.h>\n\/\/#include \"jsoncpp\/json\/json.h\"\n#include <map>\n#include <errno.h>\n#include <fcntl.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n\n#include \"ConnectalProjectConfig.h\"\n\n#include \"nvme.h\"\n#include \"mp.h\"\n\nclass StringSearchResponse : public StringSearchResponseWrapper {\npublic:\n virtual void strstrLoc ( const uint32_t pos ) {\n\tif (pos != -1)\n\t fprintf(stderr, \"string search at character pos=%d\\n\", pos);\n }\n StringSearchResponse(int id, PortalPoller *poller = 0) : StringSearchResponseWrapper(id, poller) {\n }\n};\n\nint main(int argc, char * const *argv)\n{\n Nvme nvme;\n StringSearchRequestProxy search(IfcNames_StringSearchRequestS2H);\n StringSearchResponse searchResponse(IfcNames_StringSearchResponseH2S);\n\n int flags, opt;\n const char *filename;\n const char *needle = \"needle\";\n int source_fd = -1;\n\n int doidentify;\n int dosearch = 0;\n int dotrace = 0;\n int dowrite = 0;\n while ((opt = getopt(argc, argv, \"iw:s:t\")) != -1) {\n\tswitch (opt) {\n\tcase 'i':\n\t doidentify = 1;\n\t break;\n\tcase 's':\n\t needle = optarg;\n\t dosearch = 1;\n\t break;\n\tcase 't':\n\t dotrace = 1;\n\t break;\n\tcase 'w':\n\t filename = optarg;\n\t dowrite = 1;\n\t break;\n\t}\n }\n\n if (dowrite) {\n\tstruct stat statbuf;\n\tint rc = stat(filename, &statbuf);\n\tif (rc < 0) {\n\t fprintf(stderr, \"%s:%d File %s does not exist %d:%s\\n\", __FILE__, __LINE__, filename, errno, strerror(errno));\n\t char pwd[128];\n\t getcwd(pwd, sizeof(pwd));\n\t fprintf(stderr, \"cwd = %s\\n\", pwd);\n\t return rc;\n\t}\n }\n\n sleep(1);\n\n nvme.setup();\n\n if (dosearch) {\n\tint needle_len = strlen(needle);\n\tint border[needle_len+1];\n\n\tcompute_borders(nvme.needleBuffer.buffer(), border, needle_len);\n\tcompute_MP_next(nvme.needleBuffer.buffer(), (struct MP *)nvme.mpNextBuffer.buffer(), needle_len);\n\tnvme.needleBuffer.cacheInvalidate(0, 1); \/\/ flush the whole thing\n\tnvme.mpNextBuffer.cacheInvalidate(0, 1); \/\/ flush the whole thing\n\n\t\/\/FIXME: read the text from NVME storage\n\t\/\/MP(needle, haystack, mpNext, needle_len, haystack_len, &sw_match_cnt);\n\n\t\/\/ the MPEngine will read in the needle and mpNext\n\tsearch.setSearchString(nvme.needleRef, nvme.mpNextRef, needle_len);\n }\n\n if (doidentify)\n\tnvme.identify();\n nvme.getFeatures();\n nvme.allocIOQueues(0);\n\n fprintf(stderr, \"CSTS %08x\\n\", nvme.read32( 0x1c));\n int startBlock = 100000; \/\/ base and extent of test file in SSD\n int blocksPerRequest = 8; \/\/12*BlocksPerRequest;\n int numBlocks = 1*blocksPerRequest; \/\/ 55; \/\/8177;\n if (dosearch) {\n\tsearch.startSearch(numBlocks*512);\n } else {\n \/\/ if search is not running, then data read below will be discarded\n }\n if (dowrite) {\n\tstruct stat statbuf;\n\tint rc = stat(filename, &statbuf);\n\tif (rc < 0) {\n\t fprintf(stderr, \"%s:%d File %s does not exist %d:%s\\n\", __FILE__, __LINE__, filename, errno, strerror(errno));\n\t char pwd[128];\n\t getcwd(pwd, sizeof(pwd));\n\t fprintf(stderr, \"cwd = %s\\n\", pwd);\n\t return rc;\n\t}\n\tnumBlocks = statbuf.st_blocks;\n\tnumBlocks -= (numBlocks % blocksPerRequest);\n\tfprintf(stderr, \"Writing %d blocks from file %s to flash at block %d\\n\", numBlocks, filename, startBlock);\n\tsource_fd = open(filename, O_RDONLY);\n }\n\n for (int block = 0; block < numBlocks; block += blocksPerRequest) {\n\tnvme_io_opcode opcode = (dowrite) ? nvme_write : nvme_read;\n\tfprintf(stderr, \"starting transfer dowrite=%d opcode=%d\\n\", dowrite, opcode);\n\tif (opcode == nvme_write) {\n\t if (filename) {\n\t\tread(source_fd, (char *)nvme.transferBuffer.buffer(), 512*blocksPerRequest);\n\t } else {\n\t\t int *buffer = (int *)nvme.transferBuffer.buffer();\n\t\tfor (int i = 0; i < numBlocks*512\/4; i ++)\n\t\t buffer[i] = i;\n\t }\n\t}\n\tint sc = nvme.doIO(opcode, startBlock, blocksPerRequest, (opcode == nvme_read ? 2 : 1), dotrace);\n\tnvme.status();\n\tif (sc != 0)\n\t break;\n\tstartBlock += blocksPerRequest;\n }\n\n nvme.dumpTrace();\n \/\/nvme.transferStats();\n fprintf(stderr, \"CSTS %08x\\n\", nvme.read32( 0x1c));\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ros_video_components\/ros_signal_strength.hpp\"\n\/*#include <QLabel>\n#include <QMainWindow>\n#include <QApplication>*\/\n\n#define RECT_X 5\n#define RECT_Y 100\n#define RECT_WIDTH RECT_X*40\n#define RECT_HEIGHT 150\n#define MAXDATA 100\n#define MAXNUM 10\n#define NUMCOLOR 3\n#define GREEN 8\n#define YELLOW 4\n#define RED 1\n#define HASH MAXDATA\/MAXNUM\n#define TOO_WEAK MAXDATA\/20\n\nROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :\n QQuickPaintedItem(parent),\n current_image(NULL),\n current_buffer(NULL),\n topic_value(\"\/cam0\"),\n ros_ready(false),\n img_trans(NULL) {\n}\n\nvoid ROS_Signal_Strength::setup(ros::NodeHandle * nh) {\n\n img_trans = new image_transport::ImageTransport(*nh);\n \/\/TODO: make these parameters of the component\n image_sub = img_trans->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Signal_Strength::receive_image,\n this,\n image_transport::TransportHints(\"compressed\")\n );\n\n ros_ready = true;\n ROS_INFO(\"Setup of video component complete\");\n}\n\nvoid ROS_Signal_Strength::receive_image(const sensor_msgs::Image::ConstPtr &msg) {\n \/\/ check to see if we already have an image frame, if we do then we need to\n \/\/ delete it to avoid memory leaks\n if( current_image ) {\n delete current_image;\n }\n\n \/\/ allocate a buffer of sufficient size to contain our video frame\n uchar * temp_buffer = (uchar *) malloc(sizeof(uchar) * msg->data.size());\n\n \/\/ and copy the message into the buffer\n \/\/ we need to do this because QImage api requires the buffer we pass in to\n \/\/ continue to exist whilst the image is in use, but the msg and it's data will\n \/\/ be lost once we leave this context\n current_image = new QImage(\n temp_buffer,\n msg->width,\n msg->height,\n QImage::Format_RGB888 \/\/ TODO: detect the type from the message\n );\n\n ROS_INFO(\"Recieved Message\");\n\n \/\/ We then swap out of bufer to avoid memory leaks\n if(current_buffer) {\n delete current_buffer;\n current_buffer = temp_buffer;\n }\n\n \/\/ finally we need to re-render the component to display the new image\n update();\n}\n\nvoid ROS_Signal_Strength::paint(QPainter * painter) {\n\t\n\tint data = 2; \/\/int data = getSignalStrength\n \/\/painter->drawImage(QPoint(5,0), *(this->current_image));\n \/\/painter->drawArc(0, 0, 100, 10, 3, 10);\n\tint x = RECT_X;\n\tint y = RECT_Y;\n\tint width = RECT_WIDTH;\n\tint height = RECT_HEIGHT;\n\n\t\/\/QPainter::drawRect(x, y, width, height);\n\t\/*draw 4 more rectangles. the base of each would be\n\tx+y. **MORE EXPERIMENTATION NEEDED ON THIS ONE**\n\tnum\/25 rectangles*\/\n\tQLinearGradient linearGradient(0, 0, 100, 100);\n\tint num = 0;\n\tfloat hash = HASH;\n\tif(data >= MAXDATA){\n\t\tnum = MAXNUM;\n\t}else if(data <= TOO_WEAK){\n\t\tnum = 0;\n\t\tlinearGradient.setColorAt(0.0, Qt::white);\n\t\tpainter->setBrush(linearGradient);\t\n\t}else{\n\t\tnum = (data\/hash) +1;\n\t}\n\tpainter->drawRect(x, y, width, height); \/\/draw the main rectangle\n\t\/\/int i = 0;\n\t\/\/y -= x;\n\t\/\/int barWidth = width\/numBars;\n\tint barWidth = width\/MAXNUM;\n\tint barHeight = height\/MAXNUM;\n\ty += ((MAXNUM-1) * height) \/MAXNUM;\n\tconst int increment = height\/MAXNUM;\n\t\/\/ROS_INFO(\"y is %d, barHeight is %d\\n\",y, barHeight);\n\tif(num == 0){\n\t\t\/\/print flashing \"NO SIGNAL\" on the screen\n\t\t\/*QLabel * label = new QLabel(&mainWindow);\n\t\tlabel->setText(\"NO SIGNAL\\n\");\n\t\tmainWindow.show();*\/\n\t\tROS_INFO(\"NO SIGNAL\\n\");\n\t}else{\n\t\tfor(int i = 1; i <= num; i++){\n\t\t \n\t\t if(num >= GREEN\/*(MAXNUM - (MAXNUM\/NUMCOLOR))*\/){\n\t\t\t linearGradient.setColorAt(0.2, Qt::green);\n\t\t }else if(num >= YELLOW\/*(MAXNUM\/NUMCOLOR)*\/){\n\t\t\t linearGradient.setColorAt(0.2, Qt::yellow); \t\n\t\t }else{\n\t\t \tlinearGradient.setColorAt(0.2, Qt::red);\n\t\t }\n\t\t \/\/linearGradient.setColorAt(1.0, Qt::black);\n\t\t painter->setBrush(linearGradient);\n\t\t\tpainter->drawRect(x, y, barWidth, barHeight);\n\t\t\tx += barWidth; \/\/move x along\n\t\t\tbarHeight += increment; \/\/increase height\n\t\t\ty -= increment; \/\/decrease height\n\t\t}\n\t}\n\t\n \/\/if(current_image) {\n \/\/ painter->drawImage(QPoint(0,0), *(this->current_image));\n \/\/}\n}\n\nvoid ROS_Signal_Strength::set_topic(const QString & new_value) {\n if(topic_value != new_value) {\n topic_value = new_value;\n if(ros_ready) {\n image_sub.shutdown();\n image_sub = img_trans->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Signal_Strength::receive_image,\n this,\n image_transport::TransportHints(\"compressed\")\n );\n }\n emit topic_changed();\n }\n}\n\nQString ROS_Signal_Strength::get_topic() const {\n return topic_value;\n}\n<commit_msg>Tested with different MAXDATA<commit_after>#include \"ros_video_components\/ros_signal_strength.hpp\"\n\/*#include <QLabel>\n#include <QMainWindow>\n#include <QApplication>*\/\n\n#define RECT_X 5\n#define RECT_Y 100\n#define RECT_WIDTH RECT_X*40\n#define RECT_HEIGHT 150\n#define MAXDATA 100\n#define MAXNUM 5\n#define NUMCOLOR 3\n#define GREEN 4\n#define YELLOW 2\n#define RED 1\n#define HASH MAXDATA\/MAXNUM\n#define TOO_WEAK MAXDATA\/20\n\nROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :\n QQuickPaintedItem(parent),\n current_image(NULL),\n current_buffer(NULL),\n topic_value(\"\/cam0\"),\n ros_ready(false),\n img_trans(NULL) {\n}\n\nvoid ROS_Signal_Strength::setup(ros::NodeHandle * nh) {\n\n img_trans = new image_transport::ImageTransport(*nh);\n \/\/TODO: make these parameters of the component\n image_sub = img_trans->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Signal_Strength::receive_image,\n this,\n image_transport::TransportHints(\"compressed\")\n );\n\n ros_ready = true;\n ROS_INFO(\"Setup of video component complete\");\n}\n\nvoid ROS_Signal_Strength::receive_image(const sensor_msgs::Image::ConstPtr &msg) {\n \/\/ check to see if we already have an image frame, if we do then we need to\n \/\/ delete it to avoid memory leaks\n if( current_image ) {\n delete current_image;\n }\n\n \/\/ allocate a buffer of sufficient size to contain our video frame\n uchar * temp_buffer = (uchar *) malloc(sizeof(uchar) * msg->data.size());\n\n \/\/ and copy the message into the buffer\n \/\/ we need to do this because QImage api requires the buffer we pass in to\n \/\/ continue to exist whilst the image is in use, but the msg and it's data will\n \/\/ be lost once we leave this context\n current_image = new QImage(\n temp_buffer,\n msg->width,\n msg->height,\n QImage::Format_RGB888 \/\/ TODO: detect the type from the message\n );\n\n ROS_INFO(\"Recieved Message\");\n\n \/\/ We then swap out of bufer to avoid memory leaks\n if(current_buffer) {\n delete current_buffer;\n current_buffer = temp_buffer;\n }\n\n \/\/ finally we need to re-render the component to display the new image\n update();\n}\n\nvoid ROS_Signal_Strength::paint(QPainter * painter) {\n\t\n\tint data = 3; \/\/int data = getSignalStrength();\n \/\/painter->drawImage(QPoint(5,0), *(this->current_image));\n \/\/painter->drawArc(0, 0, 100, 10, 3, 10);\n\tint x = RECT_X;\n\tint y = RECT_Y;\n\tint width = RECT_WIDTH;\n\tint height = RECT_HEIGHT;\n\n\t\/\/QPainter::drawRect(x, y, width, height);\n\t\/*draw 4 more rectangles. the base of each would be\n\tx+y. **MORE EXPERIMENTATION NEEDED ON THIS ONE**\n\tnum\/25 rectangles*\/\n\tQLinearGradient linearGradient(0, 0, 100, 100);\n\tint num = 0;\n\tfloat hash = HASH;\n\tif(data >= MAXDATA){\n\t\tnum = MAXNUM;\n\t}else if(data <= TOO_WEAK){\n\t\tnum = 0;\n\t\tlinearGradient.setColorAt(0.0, Qt::white);\n\t\tpainter->setBrush(linearGradient);\t\n\t}else{\n\t\tnum = (data\/hash) +1;\n\t}\n\tpainter->drawRect(x, y, width, height); \/\/draw the main rectangle\n\t\/\/int i = 0;\n\t\/\/y -= x;\n\t\/\/int barWidth = width\/numBars;\n\tint barWidth = width\/MAXNUM;\n\tint barHeight = height\/MAXNUM;\n\ty += ((MAXNUM-1) * height) \/MAXNUM;\n\tconst int increment = height\/MAXNUM;\n\t\/\/ROS_INFO(\"y is %d, barHeight is %d\\n\",y, barHeight);\n\tif(num == 0){\n\t\t\/\/print flashing \"NO SIGNAL\" on the screen\n\t\t\/*QLabel * label = new QLabel(&mainWindow);\n\t\tlabel->setText(\"NO SIGNAL\\n\");\n\t\tmainWindow.show();*\/\n\t\tROS_INFO(\"NO SIGNAL\\n\");\n\t}else{\n\t\tfor(int i = 1; i <= num; i++){\n\t\t \n\t\t if(num >= GREEN\/*(MAXNUM - (MAXNUM\/NUMCOLOR))*\/){\n\t\t\t linearGradient.setColorAt(0.2, Qt::green);\n\t\t }else if(num >= YELLOW\/*(MAXNUM\/NUMCOLOR)*\/){\n\t\t\t linearGradient.setColorAt(0.2, Qt::yellow); \t\n\t\t }else{\n\t\t \tlinearGradient.setColorAt(0.2, Qt::red);\n\t\t }\n\t\t \/\/linearGradient.setColorAt(1.0, Qt::black);\n\t\t painter->setBrush(linearGradient);\n\t\t\tpainter->drawRect(x, y, barWidth, barHeight);\n\t\t\tx += barWidth; \/\/move x along\n\t\t\tbarHeight += increment; \/\/increase height\n\t\t\ty -= increment; \/\/decrease height\n\t\t}\n\t}\n\t\n \/\/if(current_image) {\n \/\/ painter->drawImage(QPoint(0,0), *(this->current_image));\n \/\/}\n}\n\nvoid ROS_Signal_Strength::set_topic(const QString & new_value) {\n if(topic_value != new_value) {\n topic_value = new_value;\n if(ros_ready) {\n image_sub.shutdown();\n image_sub = img_trans->subscribe(\n topic_value.toStdString(),\n 1,\n &ROS_Signal_Strength::receive_image,\n this,\n image_transport::TransportHints(\"compressed\")\n );\n }\n emit topic_changed();\n }\n}\n\nQString ROS_Signal_Strength::get_topic() const {\n return topic_value;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************\n* Wrappers for X.509 types *\n* (C) 2005-2006 Jack Lloyd <lloyd@randombit.net> *\n*************************************************\/\n\n#include <botan\/oids.h>\n#include <botan\/pipe.h>\n#include <botan\/filters.h>\n#include <botan\/x509cert.h>\n#include <botan\/x509stor.h>\nusing namespace Botan;\n\n#include <boost\/python.hpp>\nnamespace python = boost::python;\n\ntemplate<typename T>\nclass vector_to_list\n {\n public:\n static PyObject* convert(const std::vector<T>& in)\n {\n python::list out;\n typename std::vector<T>::const_iterator i = in.begin();\n while(i != in.end())\n {\n out.append(*i);\n ++i;\n }\n return python::incref(out.ptr());\n }\n\n vector_to_list()\n {\n python::to_python_converter<std::vector<T>, vector_to_list<T> >();\n }\n };\n\ntemplate<typename T>\nclass memvec_to_hexstr\n {\n public:\n static PyObject* convert(const T& in)\n {\n Pipe pipe(new Hex_Encoder);\n pipe.process_msg(in);\n std::string result = pipe.read_all_as_string();\n return python::incref(python::str(result).ptr());\n }\n\n memvec_to_hexstr()\n {\n python::to_python_converter<T, memvec_to_hexstr<T> >();\n }\n };\n\nclass X509_Store_Search_Wrap : public X509_Store::Search_Func,\n public python::wrapper<X509_Store::Search_Func>\n {\n public:\n bool match(const X509_Certificate& cert) const\n {\n return this->get_override(\"match\")(cert);\n }\n };\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_cert_ols, add_cert, 1, 2)\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(validate_cert_ols, validate_cert, 1, 2)\n\nvoid export_x509()\n {\n vector_to_list<std::string>();\n vector_to_list<X509_Certificate>();\n memvec_to_hexstr<MemoryVector<byte> >();\n\n python::class_<X509_Certificate>\n (\"X509_Certificate\", python::init<std::string>())\n .def(python::self == python::self)\n .def(python::self != python::self)\n .add_property(\"version\", &X509_Certificate::x509_version)\n .add_property(\"is_CA\", &X509_Certificate::is_CA_cert)\n .add_property(\"self_signed\", &X509_Certificate::is_self_signed)\n .add_property(\"pathlimit\", &X509_Certificate::path_limit)\n .add_property(\"as_pem\", &X509_Object::PEM_encode)\n .def(\"start_time\", &X509_Certificate::start_time)\n .def(\"end_time\", &X509_Certificate::end_time)\n .def(\"subject_info\", &X509_Certificate::subject_info)\n .def(\"issuer_info\", &X509_Certificate::issuer_info)\n .def(\"ex_constraints\", &X509_Certificate::ex_constraints)\n .def(\"policies\", &X509_Certificate::policies)\n .def(\"subject_key_id\", &X509_Certificate::subject_key_id)\n .def(\"authority_key_id\", &X509_Certificate::authority_key_id);\n\n python::enum_<X509_Code>(\"verify_result\")\n .value(\"verified\", VERIFIED)\n .value(\"unknown_x509_error\", UNKNOWN_X509_ERROR)\n .value(\"cannot_establish_trust\", CANNOT_ESTABLISH_TRUST)\n .value(\"cert_chain_too_long\", CERT_CHAIN_TOO_LONG)\n .value(\"signature_error\", SIGNATURE_ERROR)\n .value(\"policy_error\", POLICY_ERROR)\n .value(\"invalid_usage\", INVALID_USAGE)\n .value(\"cert_format_error\", CERT_FORMAT_ERROR)\n .value(\"cert_issuer_not_found\", CERT_ISSUER_NOT_FOUND)\n .value(\"cert_not_yet_valid\", CERT_NOT_YET_VALID)\n .value(\"cert_has_expired\", CERT_HAS_EXPIRED)\n .value(\"cert_is_revoked\", CERT_IS_REVOKED)\n .value(\"crl_format_error\", CRL_FORMAT_ERROR)\n .value(\"crl_issuer_not_found\", CRL_ISSUER_NOT_FOUND)\n .value(\"crl_not_yet_valid\", CRL_NOT_YET_VALID)\n .value(\"crl_has_expired\", CRL_HAS_EXPIRED)\n .value(\"ca_cert_cannot_sign\", CA_CERT_CANNOT_SIGN)\n .value(\"ca_cert_not_for_cert_issuer\", CA_CERT_NOT_FOR_CERT_ISSUER)\n .value(\"ca_cert_not_for_crl_issuer\", CA_CERT_NOT_FOR_CRL_ISSUER);\n\n python::enum_<X509_Store::Cert_Usage>(\"cert_usage\")\n .value(\"any\", X509_Store::ANY)\n .value(\"tls_server\", X509_Store::TLS_SERVER)\n .value(\"tls_client\", X509_Store::TLS_CLIENT)\n .value(\"code_signing\", X509_Store::CODE_SIGNING)\n .value(\"email_protection\", X509_Store::EMAIL_PROTECTION)\n .value(\"time_stamping\", X509_Store::TIME_STAMPING)\n .value(\"crl_signing\", X509_Store::CRL_SIGNING);\n\n {\n python::scope in_class = \n python::class_<X509_Store>(\"X509_Store\")\n .def(\"add_cert\", &X509_Store::add_cert, add_cert_ols())\n .def(\"validate\", &X509_Store::validate_cert, validate_cert_ols())\n .def(\"get_certs\", &X509_Store::get_certs); \n\n python::class_<X509_Store_Search_Wrap, boost::noncopyable>\n (\"Search_Func\")\n .def(\"match\", python::pure_virtual(&X509_Store::Search_Func::match));\n }\n }\n<commit_msg>Add basic wrapping for X509_CRL, no member functions are exposed as they would require additional type conversions.<commit_after>\/*************************************************\n* Wrappers for X.509 types *\n* (C) 2005-2006 Jack Lloyd <lloyd@randombit.net> *\n*************************************************\/\n\n#include <botan\/oids.h>\n#include <botan\/pipe.h>\n#include <botan\/filters.h>\n#include <botan\/x509cert.h>\n#include <botan\/x509_crl.h>\n#include <botan\/x509stor.h>\nusing namespace Botan;\n\n#include <boost\/python.hpp>\nnamespace python = boost::python;\n\ntemplate<typename T>\nclass vector_to_list\n {\n public:\n static PyObject* convert(const std::vector<T>& in)\n {\n python::list out;\n typename std::vector<T>::const_iterator i = in.begin();\n while(i != in.end())\n {\n out.append(*i);\n ++i;\n }\n return python::incref(out.ptr());\n }\n\n vector_to_list()\n {\n python::to_python_converter<std::vector<T>, vector_to_list<T> >();\n }\n };\n\ntemplate<typename T>\nclass memvec_to_hexstr\n {\n public:\n static PyObject* convert(const T& in)\n {\n Pipe pipe(new Hex_Encoder);\n pipe.process_msg(in);\n std::string result = pipe.read_all_as_string();\n return python::incref(python::str(result).ptr());\n }\n\n memvec_to_hexstr()\n {\n python::to_python_converter<T, memvec_to_hexstr<T> >();\n }\n };\n\nclass X509_Store_Search_Wrap : public X509_Store::Search_Func,\n public python::wrapper<X509_Store::Search_Func>\n {\n public:\n bool match(const X509_Certificate& cert) const\n {\n return this->get_override(\"match\")(cert);\n }\n };\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_cert_ols, add_cert, 1, 2)\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(validate_cert_ols, validate_cert, 1, 2)\n\nvoid export_x509()\n {\n vector_to_list<std::string>();\n vector_to_list<X509_Certificate>();\n memvec_to_hexstr<MemoryVector<byte> >();\n\n python::class_<X509_Certificate>\n (\"X509_Certificate\", python::init<std::string>())\n .def(python::self == python::self)\n .def(python::self != python::self)\n .add_property(\"version\", &X509_Certificate::x509_version)\n .add_property(\"is_CA\", &X509_Certificate::is_CA_cert)\n .add_property(\"self_signed\", &X509_Certificate::is_self_signed)\n .add_property(\"pathlimit\", &X509_Certificate::path_limit)\n .add_property(\"as_pem\", &X509_Object::PEM_encode)\n .def(\"start_time\", &X509_Certificate::start_time)\n .def(\"end_time\", &X509_Certificate::end_time)\n .def(\"subject_info\", &X509_Certificate::subject_info)\n .def(\"issuer_info\", &X509_Certificate::issuer_info)\n .def(\"ex_constraints\", &X509_Certificate::ex_constraints)\n .def(\"policies\", &X509_Certificate::policies)\n .def(\"subject_key_id\", &X509_Certificate::subject_key_id)\n .def(\"authority_key_id\", &X509_Certificate::authority_key_id);\n\n python::class_<X509_CRL>\n (\"X509_CRL\", python::init<std::string>())\n .add_property(\"as_pem\", &X509_Object::PEM_encode);\n\n python::enum_<X509_Code>(\"verify_result\")\n .value(\"verified\", VERIFIED)\n .value(\"unknown_x509_error\", UNKNOWN_X509_ERROR)\n .value(\"cannot_establish_trust\", CANNOT_ESTABLISH_TRUST)\n .value(\"cert_chain_too_long\", CERT_CHAIN_TOO_LONG)\n .value(\"signature_error\", SIGNATURE_ERROR)\n .value(\"policy_error\", POLICY_ERROR)\n .value(\"invalid_usage\", INVALID_USAGE)\n .value(\"cert_format_error\", CERT_FORMAT_ERROR)\n .value(\"cert_issuer_not_found\", CERT_ISSUER_NOT_FOUND)\n .value(\"cert_not_yet_valid\", CERT_NOT_YET_VALID)\n .value(\"cert_has_expired\", CERT_HAS_EXPIRED)\n .value(\"cert_is_revoked\", CERT_IS_REVOKED)\n .value(\"crl_format_error\", CRL_FORMAT_ERROR)\n .value(\"crl_issuer_not_found\", CRL_ISSUER_NOT_FOUND)\n .value(\"crl_not_yet_valid\", CRL_NOT_YET_VALID)\n .value(\"crl_has_expired\", CRL_HAS_EXPIRED)\n .value(\"ca_cert_cannot_sign\", CA_CERT_CANNOT_SIGN)\n .value(\"ca_cert_not_for_cert_issuer\", CA_CERT_NOT_FOR_CERT_ISSUER)\n .value(\"ca_cert_not_for_crl_issuer\", CA_CERT_NOT_FOR_CRL_ISSUER);\n\n python::enum_<X509_Store::Cert_Usage>(\"cert_usage\")\n .value(\"any\", X509_Store::ANY)\n .value(\"tls_server\", X509_Store::TLS_SERVER)\n .value(\"tls_client\", X509_Store::TLS_CLIENT)\n .value(\"code_signing\", X509_Store::CODE_SIGNING)\n .value(\"email_protection\", X509_Store::EMAIL_PROTECTION)\n .value(\"time_stamping\", X509_Store::TIME_STAMPING)\n .value(\"crl_signing\", X509_Store::CRL_SIGNING);\n\n {\n python::scope in_class = \n python::class_<X509_Store>(\"X509_Store\")\n .def(\"add_cert\", &X509_Store::add_cert, add_cert_ols())\n .def(\"validate\", &X509_Store::validate_cert, validate_cert_ols())\n .def(\"get_certs\", &X509_Store::get_certs)\n .def(\"add_crl\", &X509_Store::add_crl);\n\n python::class_<X509_Store_Search_Wrap, boost::noncopyable>\n (\"Search_Func\")\n .def(\"match\", python::pure_virtual(&X509_Store::Search_Func::match));\n }\n }\n<|endoftext|>"} {"text":"<commit_before>#ifndef _USE_MATH_DEFINES\n#define _USE_MATH_DEFINES\n#endif\n\n#include <cmath>\n#include <limits>\n#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <Tools\/Noise\/Noise.hpp>\n\n#include \"Frozenbits_generator_BEC.hpp\"\n\nusing namespace aff3ct::tools;\n\nFrozenbits_generator_BEC\n::Frozenbits_generator_BEC(const int K, const int N)\n: Frozenbits_generator(K, N), m((int)std::log2(N)), z((int)std::exp2(m), 0)\n{\n}\n\nFrozenbits_generator_BEC\n::~Frozenbits_generator_BEC()\n{\n}\n\nvoid Frozenbits_generator_BEC\n::evaluate()\n{\n\tfor (unsigned i = 0; i != this->best_channels.size(); i++) \n\t\tthis->best_channels[i] = i;\n\n\tfor (auto i = 0; i < std::exp2(m); i++)\n\t\tz[i] = 2.0 \/ std::pow((double)this->n->get_noise(), 2.0);\n\n\tfor (auto l = 1; l <= m; l++)\n\t{\n\t\tauto o1 = (int)std::exp2(m - l +1);\n\t\tauto o2 = (int)std::exp2(m - l );\n\n\/\/\t\tfor (auto t = 0; t < (int)std::exp2(l -1); t++)\n\/\/\t\t{\n\/\/\t\t\tdouble T = z[t * o1];\n\/\/\n\/\/\t\t\tz[t * o1] = phi_inv(1.0 - std::pow(1.0 - phi(T), 2.0));\n\/\/\t\t\tif (z[t * o1] == HUGE_VAL)\n\/\/\t\t\t\tz[t * o1] = T + M_LN2 \/ (alpha * gamma);\n\/\/\n\/\/\t\t\tz[t * o1 + o2] = 2.0 * T;\n\/\/\t\t}\n\t}\n\n\tstd::sort(this->best_channels.begin(), this->best_channels.end(), [this](int i1, int i2) { return z[i1] > z[i2]; });\n}\n\nvoid Frozenbits_generator_BEC\n::check_noise()\n{\n\tFrozenbits_generator::check_noise();\n\n\tthis->n->is_of_type_throw(tools::Noise_type::EP);\n}<commit_msg>Implement BEC frozen bits generator.<commit_after>#ifndef _USE_MATH_DEFINES\n#define _USE_MATH_DEFINES\n#endif\n\n#include <cmath>\n#include <limits>\n#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <Tools\/Noise\/Noise.hpp>\n\n#include \"Frozenbits_generator_BEC.hpp\"\n\nusing namespace aff3ct::tools;\n\nFrozenbits_generator_BEC\n::Frozenbits_generator_BEC(const int K, const int N)\n: Frozenbits_generator(K, N), m((int)std::log2(N)), z((int)std::exp2(m), 0)\n{\n}\n\nFrozenbits_generator_BEC\n::~Frozenbits_generator_BEC()\n{\n}\n\nvoid Frozenbits_generator_BEC\n::evaluate()\n{\n\tfor (unsigned i = 0; i != this->best_channels.size(); i++) \n\t\tthis->best_channels[i] = i;\n\n\tfor (auto i = 0; i < std::exp2(m); i++)\n\t\tz[i] = static_cast<double>(this->n->get_noise());\n\n\tfor (auto l = 1; l <= m; l++)\n\t{\n\t\tauto o1 = (int)std::exp2(m - l +1);\n\t\tauto o2 = (int)std::exp2(m - l );\n\n\t\tfor (auto t = 0; t < (int)std::exp2(l -1); t++)\n\t\t{\n\t\t\tdouble T = z[t * o1];\n\n\t\t\tz[t * o1] = T * T;\n\n\t\t\tz[t * o1 + o2] = 2 * T - T * T ;\n\t\t}\n\t}\n\n\/\/\tstd::sort(this->best_channels.begin(), this->best_channels.end(), [this](int i1, int i2) { return z[i1] > z[i2]; });\n\/\/\tfor (auto chan : this->best_channels)\n\/\/\t\tstd::cout << chan << \" \";\n\/\/\tstd::cout << std::endl;\n}\n\nvoid Frozenbits_generator_BEC\n::check_noise()\n{\n\tFrozenbits_generator::check_noise();\n\n\tthis->n->is_of_type_throw(tools::Noise_type::EP);\n}<|endoftext|>"} {"text":"<commit_before>#include \"mob.hpp\"\n\nplayer::player(std::string name, std::string area, std::string skill, int level = 1, int EXP = 0)\n{\n setName(name);\n setArea(area);\n setSkill(skill);\n setLevel(level);\n setEXP(EXP);\n setMaxHealth();\n setHealth(mobMaxHealth);\n setDamage();\n}\n\n\/\/Member function definitions\nvoid mob::setName(std::string name)\n{\n mobName = name;\n}\nvoid mob::setArea(std::string area)\n{\n mobName = name;\n}\nvoid mob::setSkill(std::string skill)\n{\n mobSkill = skill;\n}\nvoid mob::setLevel(int level)\n{\n mobLevel = level;\n}\nvoid mob::setEXP(int EXP)\n{\n mobEXP = (35 * getLevel());\n}\nvoid mob::setHealth(int health)\n{\n mobHealth = health;\n}\nvoid mob::setMaxHealth()\n{\n mobMaxHealth = (63 * getLevel());\n}\nvoid mob::setDamage()\n{\n mobDamage = (10 * getLevel());\n}\n\n\/\/Member function constructors\nvoid mob::getName()\n{\n return mobName;\n}\nvoid mob::getArea()\n{\n return mobArea;\n}\nvoid mob::getSkill()\n{\n return mobSkill;\n}\nvoid mob::getLevel()\n{\n return mobLevel;\n}\nvoid mob::getHealth()\n{\n return mobHealth;\n}\nvoid mob::getMaxHealth()\n{\n return mobMaxhealth;\n}\nvoid mob::getDamage()\n{\n return mobDamage;\n}\nvoid mob::getEXP()\n{\n return mobEXP;\n}\n\n<commit_msg>Update mob.cpp<commit_after>#include \"mob.hpp\"\n\nplayer::player(std::string name, std::string area, std::string skill, int level = 1, int EXP = 0)\n{\n setName(name);\n setArea(area);\n setSkill(skill);\n setLevel(level);\n setEXP(EXP);\n setMaxHealth();\n setHealth(mobMaxHealth);\n setDamage();\n}\n\n\/\/Member function definitions\nvoid mob::setName(std::string name)\n{\n mobName = name;\n}\nvoid mob::setArea(std::string area)\n{\n mobArea = area;\n}\nvoid mob::setSkill(std::string skill)\n{\n mobSkill = skill;\n}\nvoid mob::setLevel(int level)\n{\n mobLevel = level;\n}\nvoid mob::setEXP(int EXP)\n{\n mobEXP = (35 * getLevel());\n}\nvoid mob::setHealth(int health)\n{\n mobHealth = health;\n}\nvoid mob::setMaxHealth()\n{\n mobMaxHealth = (63 * getLevel());\n}\nvoid mob::setDamage()\n{\n mobDamage = (10 * getLevel());\n}\n\n\/\/Member function constructors\nvoid mob::getName()\n{\n return mobName;\n}\nvoid mob::getArea()\n{\n return mobArea;\n}\nvoid mob::getSkill()\n{\n return mobSkill;\n}\nvoid mob::getLevel()\n{\n return mobLevel;\n}\nvoid mob::getHealth()\n{\n return mobHealth;\n}\nvoid mob::getMaxHealth()\n{\n return mobMaxhealth;\n}\nvoid mob::getDamage()\n{\n return mobDamage;\n}\nvoid mob::getEXP()\n{\n return mobEXP;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ActiveMSPList.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-05-19 08:27:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_\n#define _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_\n\n#include <hash_map>\n#include <map>\n\n#include <osl\/mutex.hxx>\n#include <rtl\/ustring>\n#include <cppuhelper\/implbase1.hxx>\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n\n#include <drafts\/com\/sun\/star\/script\/provider\/XScriptProvider.hpp>\n#include <drafts\/com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n\n\nnamespace func_provider\n{\n\/\/ for simplification\n#define css ::com::sun::star\n#define dcsss ::drafts::com::sun::star::script\n\n\/\/Typedefs\n\/\/=============================================================================\n\n\nstruct MspInst\n{\n css::uno::Reference< dcsss::provider::XScriptProvider > provider;\n css::uno::Reference< dcsss::browse::XBrowseNode > node;\n};\n\ntypedef ::std::map < css::uno::Reference< css::frame::XModel >,\n MspInst > Model_map;\n\ntypedef ::std::hash_map< ::rtl::OUString,\n MspInst,\n ::rtl::OUStringHash,\n ::std::equal_to< ::rtl::OUString > > Msp_hash;\n\nclass ActiveMSPList : public ::cppu::WeakImplHelper1< css::lang::XEventListener >\n{\n\npublic:\n static ActiveMSPList& instance( const css::uno::Reference<\n css::uno::XComponentContext >& xContext );\n ~ActiveMSPList();\n void addActiveMSP( const css::uno::Reference< css::frame::XModel >& xModel,\n const css::uno::Reference< dcsss::provider::XScriptProvider >& msp );\n\n \/\/XEventListener\n \/\/======================================================================\n\n virtual void SAL_CALL disposing( const css::lang::EventObject& Source )\n throw ( css::uno::RuntimeException );\n\n \/\/ Factory method for create MasterScriptProviders\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createMSP( const css::uno::Any& context )\n throw ( css::uno::RuntimeException );\nprivate:\n ActiveMSPList( const css::uno::Reference<\n css::uno::XComponentContext > & xContext );\n ::rtl::OUString\n getDocNameOrURLFromModel( const css::uno::Reference< css::frame::XModel >& xModel );\n\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createMSP( const ::rtl::OUString& context )\n throw ( css::uno::RuntimeException );\n\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createMSP( const css::uno::Reference< css::frame::XModel >& xModel )\n throw ( css::uno::RuntimeException );\n\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createNewMSP( const css::uno::Any& )\n throw ( css::uno::RuntimeException );\n\n void createNonDocMSPs();\n Msp_hash m_hMsps;\n Model_map m_mModels;\n osl::Mutex m_mutex;\n ::rtl::OUString userDirString;\n ::rtl::OUString shareDirString;\n css::uno::Reference< css::uno::XComponentContext > m_xContext;\n};\n} \/\/ func_provider\n#endif\n<commit_msg>INTEGRATION: CWS scriptingf7 (1.4.4); FILE MERGED 2004\/06\/12 08:42:34 npower 1.4.4.1: #i25269# Add support for pkgchk.<commit_after>\/*************************************************************************\n *\n * $RCSfile: ActiveMSPList.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2004-07-23 14:09:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_\n#define _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_\n\n#include <hash_map>\n#include <map>\n\n#include <osl\/mutex.hxx>\n#include <rtl\/ustring>\n#include <cppuhelper\/implbase1.hxx>\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n\n#include <drafts\/com\/sun\/star\/script\/provider\/XScriptProvider.hpp>\n#include <drafts\/com\/sun\/star\/script\/browse\/XBrowseNode.hpp>\n\n\nnamespace func_provider\n{\n\/\/ for simplification\n#define css ::com::sun::star\n#define dcsss ::drafts::com::sun::star::script\n\n\/\/Typedefs\n\/\/=============================================================================\n\n\ntypedef ::std::map < css::uno::Reference< css::frame::XModel >,\n css::uno::Reference< dcsss::provider::XScriptProvider > > Model_map;\n\ntypedef ::std::hash_map< ::rtl::OUString,\n css::uno::Reference< dcsss::provider::XScriptProvider >,\n ::rtl::OUStringHash,\n ::std::equal_to< ::rtl::OUString > > Msp_hash;\n\nclass ActiveMSPList : public ::cppu::WeakImplHelper1< css::lang::XEventListener >\n{\n\npublic:\n static ActiveMSPList& instance( const css::uno::Reference<\n css::uno::XComponentContext >& xContext );\n\n ActiveMSPList( const css::uno::Reference<\n css::uno::XComponentContext > & xContext );\n ~ActiveMSPList();\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createMSP( const ::rtl::OUString& context )\n throw ( css::uno::RuntimeException );\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createMSP( const css::uno::Any& context )\n throw ( css::uno::RuntimeException );\n css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > >\n getActiveProviders();\n \/\/XEventListener\n \/\/======================================================================\n\n virtual void SAL_CALL disposing( const css::lang::EventObject& Source )\n throw ( css::uno::RuntimeException );\n\nprivate:\n void addActiveMSP( const css::uno::Reference< css::frame::XModel >& xModel,\n const css::uno::Reference< dcsss::provider::XScriptProvider >& msp );\n css::uno::Reference< dcsss::provider::XScriptProvider >\n createNewMSP( const ::rtl::OUString& )\n throw ( css::uno::RuntimeException );\n void createNonDocMSPs();\n Msp_hash m_hMsps;\n Model_map m_mModels;\n osl::Mutex m_mutex;\n ::rtl::OUString userDirString;\n ::rtl::OUString shareDirString;\n css::uno::Reference< css::uno::XComponentContext > m_xContext;\n};\n} \/\/ func_provider\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <com\/sun\/star\/ucb\/Command.hpp>\n#include <com\/sun\/star\/ucb\/XCommandEnvironment.hpp>\n#include <com\/sun\/star\/i18n\/XExtendedTransliteration.hpp>\n#include <com\/sun\/star\/ucb\/XCommandProcessor.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/script\/XInvocation.hpp>\n\n#include <l10ntools\/HelpSearch.hxx>\n\n#ifndef INCLUDED_STL_ALGORITHM\n#include <algorithm>\n#define INCLUDED_STL_ALGORITHM\n#endif\n#ifndef INCLUDED_STL_SET\n#include <set>\n#define INCLUDED_STL_SET\n#endif\n\n#include <qe\/Query.hxx>\n#include <qe\/DocGenerator.hxx>\n#include \"resultsetforquery.hxx\"\n#include \"databases.hxx\"\n\nusing namespace std;\nusing namespace chelp;\nusing namespace xmlsearch::excep;\nusing namespace xmlsearch::qe;\nusing namespace com::sun::star;\nusing namespace com::sun::star::ucb;\nusing namespace com::sun::star::i18n;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\nstruct HitItem\n{\n rtl::OUString m_aURL;\n float m_fScore;\n\n HitItem( void ) {}\n HitItem( const rtl::OUString& aURL, float fScore )\n : m_aURL( aURL )\n , m_fScore( fScore )\n {}\n bool operator < ( const HitItem& rHitItem ) const\n {\n return rHitItem.m_fScore < m_fScore;\n }\n};\n\nResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >& xMSF,\n const uno::Reference< XContentProvider >& xProvider,\n sal_Int32 nOpenMode,\n const uno::Sequence< beans::Property >& seq,\n const uno::Sequence< NumberedSortingInfo >& seqSort,\n URLParameter& aURLParameter,\n Databases* pDatabases )\n : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),\n m_pDatabases( pDatabases ),\n m_aURLParameter( aURLParameter )\n{\n fprintf(stderr, \"ResultSetForQuery::ResultSetForQuery\\n\");\n\n Reference< XTransliteration > xTrans(\n xMSF->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.i18n.Transliteration\" )) ),\n UNO_QUERY );\n Locale aLocale( aURLParameter.get_language(),\n rtl::OUString(),\n rtl::OUString() );\n if(xTrans.is())\n xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,\n aLocale );\n\n \/\/ EDIT FROM HERE\n\n vector< vector< rtl::OUString > > queryList;\n {\n sal_Int32 idx;\n rtl::OUString query = m_aURLParameter.get_query();\n while( !query.isEmpty() )\n {\n idx = query.indexOf( sal_Unicode( ' ' ) );\n if( idx == -1 )\n idx = query.getLength();\n\n vector< rtl::OUString > currentQuery;\n rtl::OUString tmp(query.copy( 0,idx ));\n rtl:: OUString toliterate = tmp;\n if(xTrans.is()) {\n Sequence<sal_Int32> aSeq;\n toliterate = xTrans->transliterate(\n tmp,0,tmp.getLength(),aSeq);\n }\n\n currentQuery.push_back( toliterate );\n queryList.push_back( currentQuery );\n\n int nCpy = 1 + idx;\n if( nCpy >= query.getLength() )\n query = rtl::OUString();\n else\n query = query.copy( 1 + idx );\n }\n }\n\n vector< rtl::OUString > aCompleteResultVector;\n rtl::OUString scope = m_aURLParameter.get_scope();\n bool bCaptionsOnly = ( scope.compareToAscii( \"Heading\" ) == 0 );\n sal_Int32 hitCount = m_aURLParameter.get_hitCount();\n\n IndexFolderIterator aIndexFolderIt( *pDatabases, m_aURLParameter.get_module(), m_aURLParameter.get_language() );\n rtl::OUString idxDir;\n bool bExtension = false;\n int iDir = 0;\n vector< vector<HitItem>* > aIndexFolderResultVectorVector;\n\n bool bTemporary;\n while( !(idxDir = aIndexFolderIt.nextIndexFolder( bExtension, bTemporary )).isEmpty() )\n {\n vector<HitItem> aIndexFolderResultVector;\n\n try\n {\n vector< vector<HitItem>* > aQueryListResultVectorVector;\n set< rtl::OUString > aSet,aCurrent,aResultSet;\n\n int nQueryListSize = queryList.size();\n if( nQueryListSize > 1 )\n hitCount = 2000;\n\n for( int i = 0; i < nQueryListSize; ++i )\n {\n vector<HitItem>* pQueryResultVector;\n if( nQueryListSize > 1 )\n {\n pQueryResultVector = new vector<HitItem>();\n aQueryListResultVectorVector.push_back( pQueryResultVector );\n }\n else\n {\n pQueryResultVector = &aIndexFolderResultVector;\n }\n pQueryResultVector->reserve( hitCount );\n\n\/\/ INVOCATION HERE\n rtl::OUString aLang = m_aURLParameter.get_language();\n rtl::OUString aSystemPath;\n osl::FileBase::getSystemPathFromFileURL( idxDir, aSystemPath );\n const std::vector< rtl::OUString >& aListItem = queryList[i];\n ::rtl::OUString aNewQueryStr = aListItem[0];\n\n vector<float> aScoreVector;\n vector<rtl::OUString> aPathVector;\n\n HelpSearch searcher(aLang, aSystemPath);\n searcher.query(aNewQueryStr, bCaptionsOnly, aPathVector, aScoreVector);\n\n if( nQueryListSize > 1 )\n aSet.clear();\n\n for (unsigned j = 0; j < aPathVector.size(); ++i) {\n pQueryResultVector->push_back(HitItem(aPathVector[j], aScoreVector[j]));\n if (nQueryListSize > 1)\n aSet.insert(aPathVector[j]);\n }\n\/\/ INVOCATION END\n \/\/ intersect\n if( nQueryListSize > 1 )\n {\n if( i == 0 )\n {\n aResultSet = aSet;\n }\n else\n {\n aCurrent = aResultSet;\n aResultSet.clear();\n set_intersection( aSet.begin(),aSet.end(),\n aCurrent.begin(),aCurrent.end(),\n inserter(aResultSet,aResultSet.begin()));\n }\n }\n }\n\n \/\/ Combine results in aIndexFolderResultVector\n if( nQueryListSize > 1 )\n {\n for( int n = 0 ; n < nQueryListSize ; ++n )\n {\n vector<HitItem>* pQueryResultVector = aQueryListResultVectorVector[n];\n vector<HitItem>& rQueryResultVector = *pQueryResultVector;\n\n int nItemCount = rQueryResultVector.size();\n for( int i = 0 ; i < nItemCount ; ++i )\n {\n const HitItem& rItem = rQueryResultVector[ i ];\n set< rtl::OUString >::iterator it;\n if( (it = aResultSet.find( rItem.m_aURL )) != aResultSet.end() )\n {\n HitItem aItemCopy( rItem );\n aItemCopy.m_fScore \/= nQueryListSize; \/\/ To get average score\n if( n == 0 )\n {\n \/\/ Use first pass to create entry\n aIndexFolderResultVector.push_back( aItemCopy );\n }\n else\n {\n \/\/ Find entry in vector\n int nCount = aIndexFolderResultVector.size();\n for( int j = 0 ; j < nCount ; ++j )\n {\n HitItem& rFindItem = aIndexFolderResultVector[ j ];\n if( rFindItem.m_aURL.equals( aItemCopy.m_aURL ) )\n {\n rFindItem.m_fScore += aItemCopy.m_fScore;\n break;\n }\n }\n }\n }\n }\n\n delete pQueryResultVector;\n }\n\n sort( aIndexFolderResultVector.begin(), aIndexFolderResultVector.end() );\n }\n\n vector<HitItem>* pIndexFolderHitItemVector = new vector<HitItem>( aIndexFolderResultVector );\n aIndexFolderResultVectorVector.push_back( pIndexFolderHitItemVector );\n aIndexFolderResultVector.clear();\n }\n catch( const Exception& )\n {\n }\n\n ++iDir;\n\n if( bTemporary )\n aIndexFolderIt.deleteTempIndexFolder( idxDir );\n\n } \/\/ Iterator\n\n\n int nVectorCount = aIndexFolderResultVectorVector.size();\n vector<HitItem>::size_type* pCurrentVectorIndex = new vector<HitItem>::size_type[nVectorCount];\n for( int j = 0 ; j < nVectorCount ; ++j )\n pCurrentVectorIndex[j] = 0;\n\n sal_Int32 nTotalHitCount = m_aURLParameter.get_hitCount();\n sal_Int32 nHitCount = 0;\n while( nHitCount < nTotalHitCount )\n {\n int iVectorWithBestScore = -1;\n float fBestScore = 0.0;\n for( int k = 0 ; k < nVectorCount ; ++k )\n {\n vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[k];\n if( pCurrentVectorIndex[k] < rIndexFolderVector.size() )\n {\n const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[k] ];\n\n if( fBestScore < rItem.m_fScore )\n {\n fBestScore = rItem.m_fScore;\n iVectorWithBestScore = k;\n }\n }\n }\n\n if( iVectorWithBestScore == -1 ) \/\/ No item left at all\n break;\n\n vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[iVectorWithBestScore];\n const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[iVectorWithBestScore] ];\n\n pCurrentVectorIndex[iVectorWithBestScore]++;\n\n aCompleteResultVector.push_back( rItem.m_aURL );\n ++nHitCount;\n }\n\n delete[] pCurrentVectorIndex;\n for( int n = 0 ; n < nVectorCount ; ++n )\n {\n vector<HitItem>* pIndexFolderVector = aIndexFolderResultVectorVector[n];\n delete pIndexFolderVector;\n }\n\n sal_Int32 replIdx = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"#HLP#\" )).getLength();\n rtl::OUString replWith = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"vnd.sun.star.help:\/\/\" ));\n\n int nResultCount = aCompleteResultVector.size();\n for( int r = 0 ; r < nResultCount ; ++r )\n {\n rtl::OUString aURL = aCompleteResultVector[r];\n rtl::OUString aResultStr = replWith + aURL.copy(replIdx);\n m_aPath.push_back( aResultStr );\n }\n\n m_aItems.resize( m_aPath.size() );\n m_aIdents.resize( m_aPath.size() );\n\n Command aCommand;\n aCommand.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"getPropertyValues\" ));\n aCommand.Argument <<= m_sProperty;\n\n for( m_nRow = 0; sal::static_int_cast<sal_uInt32>( m_nRow ) < m_aPath.size(); ++m_nRow )\n {\n m_aPath[m_nRow] =\n m_aPath[m_nRow] +\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"?Language=\" )) +\n m_aURLParameter.get_language() +\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"&System=\" )) +\n m_aURLParameter.get_system();\n\n uno::Reference< XContent > content = queryContent();\n if( content.is() )\n {\n uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );\n cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow]; \/\/TODO: check return value of operator >>=\n }\n }\n m_nRow = 0xffffffff;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Bugfix resultsetforquery<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <com\/sun\/star\/ucb\/Command.hpp>\n#include <com\/sun\/star\/ucb\/XCommandEnvironment.hpp>\n#include <com\/sun\/star\/i18n\/XExtendedTransliteration.hpp>\n#include <com\/sun\/star\/ucb\/XCommandProcessor.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/script\/XInvocation.hpp>\n\n#include <l10ntools\/HelpSearch.hxx>\n\n#ifndef INCLUDED_STL_ALGORITHM\n#include <algorithm>\n#define INCLUDED_STL_ALGORITHM\n#endif\n#ifndef INCLUDED_STL_SET\n#include <set>\n#define INCLUDED_STL_SET\n#endif\n\n#include <qe\/Query.hxx>\n#include <qe\/DocGenerator.hxx>\n#include \"resultsetforquery.hxx\"\n#include \"databases.hxx\"\n\nusing namespace std;\nusing namespace chelp;\nusing namespace xmlsearch::excep;\nusing namespace xmlsearch::qe;\nusing namespace com::sun::star;\nusing namespace com::sun::star::ucb;\nusing namespace com::sun::star::i18n;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\nstruct HitItem\n{\n rtl::OUString m_aURL;\n float m_fScore;\n\n HitItem( void ) {}\n HitItem( const rtl::OUString& aURL, float fScore )\n : m_aURL( aURL )\n , m_fScore( fScore )\n {}\n bool operator < ( const HitItem& rHitItem ) const\n {\n return rHitItem.m_fScore < m_fScore;\n }\n};\n\nResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >& xMSF,\n const uno::Reference< XContentProvider >& xProvider,\n sal_Int32 nOpenMode,\n const uno::Sequence< beans::Property >& seq,\n const uno::Sequence< NumberedSortingInfo >& seqSort,\n URLParameter& aURLParameter,\n Databases* pDatabases )\n : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),\n m_pDatabases( pDatabases ),\n m_aURLParameter( aURLParameter )\n{\n fprintf(stderr, \"ResultSetForQuery::ResultSetForQuery\\n\");\n\n Reference< XTransliteration > xTrans(\n xMSF->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.i18n.Transliteration\" )) ),\n UNO_QUERY );\n Locale aLocale( aURLParameter.get_language(),\n rtl::OUString(),\n rtl::OUString() );\n if(xTrans.is())\n xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,\n aLocale );\n\n vector< vector< rtl::OUString > > queryList;\n {\n sal_Int32 idx;\n rtl::OUString query = m_aURLParameter.get_query();\n while( !query.isEmpty() )\n {\n idx = query.indexOf( sal_Unicode( ' ' ) );\n if( idx == -1 )\n idx = query.getLength();\n\n vector< rtl::OUString > currentQuery;\n rtl::OUString tmp(query.copy( 0,idx ));\n rtl:: OUString toliterate = tmp;\n if(xTrans.is()) {\n Sequence<sal_Int32> aSeq;\n toliterate = xTrans->transliterate(\n tmp,0,tmp.getLength(),aSeq);\n }\n\n currentQuery.push_back( toliterate );\n queryList.push_back( currentQuery );\n\n int nCpy = 1 + idx;\n if( nCpy >= query.getLength() )\n query = rtl::OUString();\n else\n query = query.copy( 1 + idx );\n }\n }\n\n vector< rtl::OUString > aCompleteResultVector;\n rtl::OUString scope = m_aURLParameter.get_scope();\n bool bCaptionsOnly = ( scope.compareToAscii( \"Heading\" ) == 0 );\n sal_Int32 hitCount = m_aURLParameter.get_hitCount();\n\n IndexFolderIterator aIndexFolderIt( *pDatabases, m_aURLParameter.get_module(), m_aURLParameter.get_language() );\n rtl::OUString idxDir;\n bool bExtension = false;\n int iDir = 0;\n vector< vector<HitItem>* > aIndexFolderResultVectorVector;\n\n bool bTemporary;\n while( !(idxDir = aIndexFolderIt.nextIndexFolder( bExtension, bTemporary )).isEmpty() )\n {\n vector<HitItem> aIndexFolderResultVector;\n\n try\n {\n vector< vector<HitItem>* > aQueryListResultVectorVector;\n set< rtl::OUString > aSet,aCurrent,aResultSet;\n\n int nQueryListSize = queryList.size();\n if( nQueryListSize > 1 )\n hitCount = 2000;\n\n for( int i = 0; i < nQueryListSize; ++i )\n {\n vector<HitItem>* pQueryResultVector;\n if( nQueryListSize > 1 )\n {\n pQueryResultVector = new vector<HitItem>();\n aQueryListResultVectorVector.push_back( pQueryResultVector );\n }\n else\n {\n pQueryResultVector = &aIndexFolderResultVector;\n }\n pQueryResultVector->reserve( hitCount );\n\n \/\/ START Invoke CLucene HelpSearch\n rtl::OUString aLang = m_aURLParameter.get_language();\n rtl::OUString aSystemPath;\n osl::FileBase::getSystemPathFromFileURL( idxDir, aSystemPath );\n const std::vector< rtl::OUString >& aListItem = queryList[i];\n ::rtl::OUString aNewQueryStr = aListItem[0];\n\n vector<float> aScoreVector;\n vector<rtl::OUString> aPathVector;\n\n HelpSearch searcher(aLang, aSystemPath);\n searcher.query(aNewQueryStr, bCaptionsOnly, aPathVector, aScoreVector);\n\n if( nQueryListSize > 1 )\n aSet.clear();\n\n for (unsigned j = 0; j < aPathVector.size(); ++j) {\n pQueryResultVector->push_back(HitItem(aPathVector[j], aScoreVector[j]));\n if (nQueryListSize > 1)\n aSet.insert(aPathVector[j]);\n }\n \/\/ END Invoke CLucene HelpSearch\n\n \/\/ intersect\n if( nQueryListSize > 1 )\n {\n if( i == 0 )\n {\n aResultSet = aSet;\n }\n else\n {\n aCurrent = aResultSet;\n aResultSet.clear();\n set_intersection( aSet.begin(),aSet.end(),\n aCurrent.begin(),aCurrent.end(),\n inserter(aResultSet,aResultSet.begin()));\n }\n }\n }\n\n \/\/ Combine results in aIndexFolderResultVector\n if( nQueryListSize > 1 )\n {\n for( int n = 0 ; n < nQueryListSize ; ++n )\n {\n vector<HitItem>* pQueryResultVector = aQueryListResultVectorVector[n];\n vector<HitItem>& rQueryResultVector = *pQueryResultVector;\n\n int nItemCount = rQueryResultVector.size();\n for( int i = 0 ; i < nItemCount ; ++i )\n {\n const HitItem& rItem = rQueryResultVector[ i ];\n set< rtl::OUString >::iterator it;\n if( (it = aResultSet.find( rItem.m_aURL )) != aResultSet.end() )\n {\n HitItem aItemCopy( rItem );\n aItemCopy.m_fScore \/= nQueryListSize; \/\/ To get average score\n if( n == 0 )\n {\n \/\/ Use first pass to create entry\n aIndexFolderResultVector.push_back( aItemCopy );\n }\n else\n {\n \/\/ Find entry in vector\n int nCount = aIndexFolderResultVector.size();\n for( int j = 0 ; j < nCount ; ++j )\n {\n HitItem& rFindItem = aIndexFolderResultVector[ j ];\n if( rFindItem.m_aURL.equals( aItemCopy.m_aURL ) )\n {\n rFindItem.m_fScore += aItemCopy.m_fScore;\n break;\n }\n }\n }\n }\n }\n\n delete pQueryResultVector;\n }\n\n sort( aIndexFolderResultVector.begin(), aIndexFolderResultVector.end() );\n }\n\n vector<HitItem>* pIndexFolderHitItemVector = new vector<HitItem>( aIndexFolderResultVector );\n aIndexFolderResultVectorVector.push_back( pIndexFolderHitItemVector );\n aIndexFolderResultVector.clear();\n }\n catch( const Exception& )\n {\n }\n\n ++iDir;\n\n if( bTemporary )\n aIndexFolderIt.deleteTempIndexFolder( idxDir );\n\n } \/\/ Iterator\n\n\n int nVectorCount = aIndexFolderResultVectorVector.size();\n vector<HitItem>::size_type* pCurrentVectorIndex = new vector<HitItem>::size_type[nVectorCount];\n for( int j = 0 ; j < nVectorCount ; ++j )\n pCurrentVectorIndex[j] = 0;\n\n sal_Int32 nTotalHitCount = m_aURLParameter.get_hitCount();\n sal_Int32 nHitCount = 0;\n while( nHitCount < nTotalHitCount )\n {\n int iVectorWithBestScore = -1;\n float fBestScore = 0.0;\n for( int k = 0 ; k < nVectorCount ; ++k )\n {\n vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[k];\n if( pCurrentVectorIndex[k] < rIndexFolderVector.size() )\n {\n const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[k] ];\n\n if( fBestScore < rItem.m_fScore )\n {\n fBestScore = rItem.m_fScore;\n iVectorWithBestScore = k;\n }\n }\n }\n\n if( iVectorWithBestScore == -1 ) \/\/ No item left at all\n break;\n\n vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[iVectorWithBestScore];\n const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[iVectorWithBestScore] ];\n\n pCurrentVectorIndex[iVectorWithBestScore]++;\n\n aCompleteResultVector.push_back( rItem.m_aURL );\n ++nHitCount;\n }\n\n delete[] pCurrentVectorIndex;\n for( int n = 0 ; n < nVectorCount ; ++n )\n {\n vector<HitItem>* pIndexFolderVector = aIndexFolderResultVectorVector[n];\n delete pIndexFolderVector;\n }\n\n sal_Int32 replIdx = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"#HLP#\" )).getLength();\n rtl::OUString replWith = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"vnd.sun.star.help:\/\/\" ));\n\n int nResultCount = aCompleteResultVector.size();\n for( int r = 0 ; r < nResultCount ; ++r )\n {\n rtl::OUString aURL = aCompleteResultVector[r];\n rtl::OUString aResultStr = replWith + aURL.copy(replIdx);\n m_aPath.push_back( aResultStr );\n }\n\n m_aItems.resize( m_aPath.size() );\n m_aIdents.resize( m_aPath.size() );\n\n Command aCommand;\n aCommand.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"getPropertyValues\" ));\n aCommand.Argument <<= m_sProperty;\n\n for( m_nRow = 0; sal::static_int_cast<sal_uInt32>( m_nRow ) < m_aPath.size(); ++m_nRow )\n {\n m_aPath[m_nRow] =\n m_aPath[m_nRow] +\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"?Language=\" )) +\n m_aURLParameter.get_language() +\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"&System=\" )) +\n m_aURLParameter.get_system();\n\n uno::Reference< XContent > content = queryContent();\n if( content.is() )\n {\n uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );\n cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow]; \/\/TODO: check return value of operator >>=\n }\n }\n m_nRow = 0xffffffff;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/memory\/lib\/plug_rules\/exp_spd_keys_supported_map.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _EXP_SPD_KEYS_SUPPORTED_MAP_H_\n#define _EXP_SPD_KEYS_SUPPORTED_MAP_H_\n\n#include <lib\/plug_rules\/p10_plug_rules.H>\n\nnamespace mss\n{\nnamespace plug_rule\n{\n\/\/\/ @note These are the latest and minimum allowed DDIMM SPD combined revisions\n\/\/\/ combined revision is the SPD revision and the SPD content revision\n\/\/\/ any DIMMs with older SPD will generate an error\n\/\/\/ The first byte is the major revision\n\/\/\/ any updates to this are usually new bytes and will require code updates\n\/\/\/ The second byte is the content revision\n\/\/\/ updates to this byte are most likely values and it's less likely that code will need to be updated\n\/\/\/ The vectors go from a lookup key to a combined revisions\n\/\/\/ The first vector is the minimum allowed combined revision\n\/\/\/ The second vector is the latest version of the combined revision\n\/\/\/ @note When adding new vendors\/heights\/sizes, THIS NEEDS TO BE IN SORTED ORDER BY VENDOR ID ENCODING\nstatic const std::vector<std::pair<spd_lookup_key, uint16_t>> MINIMUM_SPD_KEY_COMBINED_REV =\n{\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_128GB}, 0x0309},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n};\n\nstatic const std::vector<std::pair<spd_lookup_key, uint16_t>> LATEST_SPD_KEY_COMBINED_REV =\n{\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_128GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n};\n\n} \/\/ ns plug_rules\n} \/\/ ns mss\n#endif\n<commit_msg>Micron 32G 4U 0_4_0<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/memory\/lib\/plug_rules\/exp_spd_keys_supported_map.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _EXP_SPD_KEYS_SUPPORTED_MAP_H_\n#define _EXP_SPD_KEYS_SUPPORTED_MAP_H_\n\n#include <lib\/plug_rules\/p10_plug_rules.H>\n\nnamespace mss\n{\nnamespace plug_rule\n{\n\/\/\/ @note These are the latest and minimum allowed DDIMM SPD combined revisions\n\/\/\/ combined revision is the SPD revision and the SPD content revision\n\/\/\/ any DIMMs with older SPD will generate an error\n\/\/\/ The first byte is the major revision\n\/\/\/ any updates to this are usually new bytes and will require code updates\n\/\/\/ The second byte is the content revision\n\/\/\/ updates to this byte are most likely values and it's less likely that code will need to be updated\n\/\/\/ The vectors go from a lookup key to a combined revisions\n\/\/\/ The first vector is the minimum allowed combined revision\n\/\/\/ The second vector is the latest version of the combined revision\n\/\/\/ @note When adding new vendors\/heights\/sizes, THIS NEEDS TO BE IN SORTED ORDER BY VENDOR ID ENCODING\nstatic const std::vector<std::pair<spd_lookup_key, uint16_t>> MINIMUM_SPD_KEY_COMBINED_REV =\n{\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_128GB}, 0x0309},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n};\n\nstatic const std::vector<std::pair<spd_lookup_key, uint16_t>> LATEST_SPD_KEY_COMBINED_REV =\n{\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SMART, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_MICRON, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_1U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_16GB}, 0x0308},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_2U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_128GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_32GB}, 0x0400},\n {{fapi2::ENUM_ATTR_MEM_EFF_MODULE_MFG_ID_SAMSUNG, fapi2::ENUM_ATTR_MEM_EFF_DRAM_MODULE_HEIGHT_4U, fapi2::ENUM_ATTR_MEM_EFF_DIMM_SIZE_64GB}, 0x0400},\n};\n\n} \/\/ ns plug_rules\n} \/\/ ns mss\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n * Copyright (c) 2015, Peter Andreas Entschev\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of fft_benchmark nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************************\/\n\n#include \"common.hpp\"\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include <clFFT.h>\n\n#ifdef __APPLE__\n#include <OpenCL\/opencl.h>\n#else\n#include <CL\/cl.h>\n#endif\n\n#define CLFFT_CHECK(err) { \\\n if (err != CLFFT_SUCCESS) { \\\n printf(\"Error %d in %s:%d.\\n\", \\\n err, __FILE__, __LINE__); \\\n return -1; \\\n } \\\n}\n\nstatic const int NSamplesMin = 128;\nstatic const int NSamplesMax = 4096;\nstatic const int Batches = 10;\nstatic const int Rank = 2;\nstatic const int Iterations = 10;\n\nint main(int argc, char* argv[])\n{\n#if __cplusplus > 199711L\n std::chrono::high_resolution_clock::time_point tStart, tEnd;\n#else\n std::clock_t tStart, tEnd;\n#endif\n\n \/\/ Query platforms and devices\n cl_platform_id platform;\n cl_device_id device;\n cl_uint num_devices, num_platforms;\n cl_int err;\n CLFFT_CHECK(clGetPlatformIDs(1, &platform, &num_platforms));\n CLFFT_CHECK(clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1,\n &device, &num_devices));\n\n \/\/ Create OpenCL context\n cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);\n CLFFT_CHECK(err);\n\n \/\/ Create OpenCL command queue\n cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);\n CLFFT_CHECK(err);\n\n for (int n = NSamplesMin; n <= NSamplesMax; n <<= 1) {\n clfftPlanHandle inPlan, outPlan;\n clfftDim rank = (clfftDim)Rank;\n size_t fft_strides[3], fft_dims[3];\n for (int i = 0; i < Rank; i++) {\n fft_dims[i] = n;\n fft_strides[i] = (i == 0) ? 1 : fft_strides[i-1] * fft_dims[i];\n }\n\n \/\/ Setup clFFT\n clfftSetupData fftSetup;\n err = clfftInitSetupData(&fftSetup);\n err = clfftSetup(&fftSetup);\n\n \/\/ Create a complex clFFT plan\n err = clfftCreateDefaultPlan(&inPlan, context, rank, fft_dims);\n\n \/\/ Configure clFFT inPlan\n CLFFT_CHECK(clfftSetLayout(inPlan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n CLFFT_CHECK(clfftSetPlanBatchSize(inPlan, Batches));\n CLFFT_CHECK(clfftSetPlanDistance(inPlan, fft_strides[Rank], fft_strides[Rank]));\n CLFFT_CHECK(clfftSetPlanInStride(inPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanOutStride(inPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanPrecision(inPlan, CLFFT_SINGLE));\n CLFFT_CHECK(clfftSetResultLocation(inPlan, CLFFT_INPLACE));\n\n \/\/ Bake inPlan\n CLFFT_CHECK(clfftBakePlan(inPlan, 1, &queue, NULL, NULL));\n\n cl_mem complexIn = 0, complexOut = 0;\n size_t bufferSize = sizeof(float) * 2 * Batches;\n for (int i = 0; i < Rank; i++)\n bufferSize *= n;\n\n \/\/ No data is copied to buffers as FFT performance is not data\n \/\/ dependent, but only size dependent\n\t\tcomplexIn = clCreateBuffer(context, CL_MEM_READ_WRITE, bufferSize, 0, &err);\n\t\tcomplexOut = clCreateBuffer(context, CL_MEM_READ_WRITE, bufferSize, 0, &err);\n\n std::cout << \"Number of dimensions: \" << Rank << std::endl;\n std::cout << \"Matrix dimensions: \" << n << \"x\" << n << std::endl;\n std::cout << \"Batch size: \" << Batches << std::endl;\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(inPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexOut, &complexOut, NULL));\n }\n clFinish(queue);\n tEnd = getTime();\n std::cout << \"In-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl;\n\n \/\/ Destroy in-place FFT plan\n clfftDestroyPlan(&inPlan);\n\n \/\/ Create a complex clFFT plan\n err = clfftCreateDefaultPlan(&outPlan, context, rank, fft_dims);\n\n \/\/ Configure clFFT outPlan\n CLFFT_CHECK(clfftSetLayout(outPlan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n CLFFT_CHECK(clfftSetPlanBatchSize(outPlan, Batches));\n CLFFT_CHECK(clfftSetPlanDistance(outPlan, fft_strides[Rank], fft_strides[Rank]));\n CLFFT_CHECK(clfftSetPlanInStride(outPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanOutStride(outPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanPrecision(outPlan, CLFFT_SINGLE));\n CLFFT_CHECK(clfftSetResultLocation(outPlan, CLFFT_INPLACE));\n\n \/\/ Bake outPlan\n CLFFT_CHECK(clfftBakePlan(outPlan, 1, &queue, NULL, NULL));\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(outPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexIn, &complexOut, NULL));\n }\n clFinish(queue);\n tEnd = getTime();\n std::cout << \"Out-of-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl;\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n CLFFT_CHECK(clEnqueueCopyBuffer(queue, complexOut, complexIn, 0, 0, bufferSize, 0, NULL, NULL));\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(outPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexIn, &complexOut, NULL));\n }\n clFinish(queue);\n tEnd = getTime();\n std::cout << \"Buffer Copy + Out-of-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl << std::endl;\n\n\t clReleaseMemObject(complexIn);\n\t clReleaseMemObject(complexOut);\n\n \/\/ Destroy out-of-place FFT plan\n clfftDestroyPlan(&outPlan);\n\n \/\/ Force release of clFFT temporary buffers\n clfftTeardown();\n }\n\n \/\/ Flush\/Release OpenCL resources\n clFlush(queue);\n clFinish(queue);\n clReleaseCommandQueue(queue);\n clReleaseContext(context);\n\n return 0;\n}\n<commit_msg>Added missing checks to OpenCL\/clFFT calls<commit_after>\/*********************************************************************************\n * Copyright (c) 2015, Peter Andreas Entschev\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of fft_benchmark nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************************\/\n\n#include \"common.hpp\"\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include <clFFT.h>\n\n#ifdef __APPLE__\n#include <OpenCL\/opencl.h>\n#else\n#include <CL\/cl.h>\n#endif\n\n#define CLFFT_CHECK(err) { \\\n if (err != CLFFT_SUCCESS) { \\\n printf(\"Error %d in %s:%d.\\n\", \\\n err, __FILE__, __LINE__); \\\n return -1; \\\n } \\\n}\n\nstatic const int NSamplesMin = 128;\nstatic const int NSamplesMax = 4096;\nstatic const int Batches = 10;\nstatic const int Rank = 2;\nstatic const int Iterations = 10;\n\nint main(int argc, char* argv[])\n{\n#if __cplusplus > 199711L\n std::chrono::high_resolution_clock::time_point tStart, tEnd;\n#else\n std::clock_t tStart, tEnd;\n#endif\n\n \/\/ Query platforms and devices\n cl_platform_id platform;\n cl_device_id device;\n cl_uint num_devices, num_platforms;\n cl_int err;\n CLFFT_CHECK(clGetPlatformIDs(1, &platform, &num_platforms));\n CLFFT_CHECK(clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1,\n &device, &num_devices));\n\n \/\/ Create OpenCL context\n cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);\n CLFFT_CHECK(err);\n\n \/\/ Create OpenCL command queue\n cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);\n CLFFT_CHECK(err);\n\n for (int n = NSamplesMin; n <= NSamplesMax; n <<= 1) {\n clfftPlanHandle inPlan, outPlan;\n clfftDim rank = (clfftDim)Rank;\n size_t fft_strides[3], fft_dims[3];\n for (int i = 0; i < Rank; i++) {\n fft_dims[i] = n;\n fft_strides[i] = (i == 0) ? 1 : fft_strides[i-1] * fft_dims[i];\n }\n\n \/\/ Setup clFFT\n clfftSetupData fftSetup;\n CLFFT_CHECK(clfftInitSetupData(&fftSetup));\n CLFFT_CHECK(clfftSetup(&fftSetup));\n\n \/\/ Create a complex clFFT plan\n CLFFT_CHECK(clfftCreateDefaultPlan(&inPlan, context, rank, fft_dims));\n\n \/\/ Configure clFFT inPlan\n CLFFT_CHECK(clfftSetLayout(inPlan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n CLFFT_CHECK(clfftSetPlanBatchSize(inPlan, Batches));\n CLFFT_CHECK(clfftSetPlanDistance(inPlan, fft_strides[Rank], fft_strides[Rank]));\n CLFFT_CHECK(clfftSetPlanInStride(inPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanOutStride(inPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanPrecision(inPlan, CLFFT_SINGLE));\n CLFFT_CHECK(clfftSetResultLocation(inPlan, CLFFT_INPLACE));\n\n \/\/ Bake inPlan\n CLFFT_CHECK(clfftBakePlan(inPlan, 1, &queue, NULL, NULL));\n\n cl_mem complexIn = 0, complexOut = 0;\n size_t bufferSize = sizeof(float) * 2 * Batches;\n for (int i = 0; i < Rank; i++)\n bufferSize *= n;\n\n \/\/ No data is copied to buffers as FFT performance is not data\n \/\/ dependent, but only size dependent\n complexIn = clCreateBuffer(context, CL_MEM_READ_WRITE, bufferSize, 0, &err);\n CLFFT_CHECK(err);\n complexOut = clCreateBuffer(context, CL_MEM_READ_WRITE, bufferSize, 0, &err);\n CLFFT_CHECK(err);\n\n std::cout << \"Matrix dimensions: \" << n << \"x\" << n << std::endl;\n std::cout << \"Batch size: \" << Batches << std::endl;\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(inPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexOut, &complexOut, NULL));\n }\n CLFFT_CHECK(clFinish(queue));\n tEnd = getTime();\n std::cout << \"In-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl;\n\n \/\/ Destroy in-place FFT plan\n CLFFT_CHECK(clfftDestroyPlan(&inPlan));\n\n \/\/ Create a complex clFFT plan\n CLFFT_CHECK(clfftCreateDefaultPlan(&outPlan, context, rank, fft_dims));\n\n \/\/ Configure clFFT outPlan\n CLFFT_CHECK(clfftSetLayout(outPlan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n CLFFT_CHECK(clfftSetPlanBatchSize(outPlan, Batches));\n CLFFT_CHECK(clfftSetPlanDistance(outPlan, fft_strides[Rank], fft_strides[Rank]));\n CLFFT_CHECK(clfftSetPlanInStride(outPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanOutStride(outPlan, rank, fft_strides));\n CLFFT_CHECK(clfftSetPlanPrecision(outPlan, CLFFT_SINGLE));\n CLFFT_CHECK(clfftSetResultLocation(outPlan, CLFFT_INPLACE));\n\n \/\/ Bake outPlan\n CLFFT_CHECK(clfftBakePlan(outPlan, 1, &queue, NULL, NULL));\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(outPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexIn, &complexOut, NULL));\n }\n CLFFT_CHECK(clFinish(queue));\n tEnd = getTime();\n std::cout << \"Out-of-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl;\n\n tStart = getTime();\n for (int i = 0; i < Iterations; i++) {\n CLFFT_CHECK(clEnqueueCopyBuffer(queue, complexOut, complexIn, 0, 0, bufferSize, 0, NULL, NULL));\n \/\/ Compute forward FFT\n CLFFT_CHECK(clfftEnqueueTransform(outPlan, CLFFT_FORWARD, 1, &queue,\n 0, NULL, NULL,\n &complexIn, &complexOut, NULL));\n }\n CLFFT_CHECK(clFinish(queue));\n tEnd = getTime();\n std::cout << \"Buffer Copy + Out-of-place C2C FFT time for \" << Iterations << \" runs: \" << getTimeCount(tEnd, tStart) << \" ms\" << std::endl << std::endl;\n\n CLFFT_CHECK(clReleaseMemObject(complexIn));\n CLFFT_CHECK(clReleaseMemObject(complexOut));\n\n \/\/ Destroy out-of-place FFT plan\n CLFFT_CHECK(clfftDestroyPlan(&outPlan));\n\n \/\/ Force release of clFFT temporary buffers\n CLFFT_CHECK(clfftTeardown());\n }\n\n \/\/ Flush\/Release OpenCL resources\n CLFFT_CHECK(clFlush(queue));\n CLFFT_CHECK(clFinish(queue));\n CLFFT_CHECK(clReleaseCommandQueue(queue));\n CLFFT_CHECK(clReleaseContext(context));\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file RegexMatcher.cc\n * \\brief Implementation of the RegexMatcher class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015,2017,2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"RegexMatcher.h\"\n#include \"Compiler.h\"\n#include \"util.h\"\n\n\nbool RegexMatcher::utf8_configured_;\n\n\nbool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg,\n ::pcre_extra **pcre_extra_arg, std::string * const err_msg)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const char *errptr;\n int erroffset;\n\n int pcre_options(0);\n if (options & RegexMatcher::ENABLE_UTF8)\n pcre_options |= PCRE_UTF8;\n if (options & RegexMatcher::CASE_INSENSITIVE)\n pcre_options |= PCRE_CASELESS;\n if (options & RegexMatcher::MULTILINE)\n pcre_options |= PCRE_MULTILINE;\n\n *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr);\n if (*pcre_arg == nullptr) {\n *pcre_extra_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to compile invalid regular expression: \\\"\" + pattern + \"\\\"! (\"\n + std::string(errptr) + \")\";\n return false;\n }\n\n \/\/ Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe.\n *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr);\n if (*pcre_extra_arg == nullptr and errptr != nullptr) {\n ::pcre_free(*pcre_arg);\n *pcre_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to \\\"study\\\" the compiled pattern \\\"\" + pattern + \"\\\"! (\" + std::string(errptr) + \")\";\n return false;\n }\n\n return true;\n}\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg,\n const unsigned options)\n{\n \/\/ Make sure the PCRE library supports UTF8:\n if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) {\n int utf8_available;\n if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) {\n if (err_msg != nullptr)\n *err_msg = \"PCRE library does not know PCRE_CONFIG_UTF8!\";\n return nullptr;\n }\n\n if (utf8_available != 1) {\n if (err_msg != nullptr)\n *err_msg = \"This version of the PCRE library does not support UTF8!\";\n return nullptr;\n }\n\n RegexMatcher::utf8_configured_ = true;\n }\n\n ::pcre *pcre_ptr;\n ::pcre_extra *pcre_extra_ptr;\n if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg))\n return nullptr;\n\n return new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr);\n}\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactoryOrDie(const std::string ®ex, const unsigned options) {\n std::string error_message;\n RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options));\n if (not error_message.empty())\n LOG_ERROR(\"failed to compile regex \\\"\" + regex + \"\\\": \" + error_message);\n\n return regex_matcher;\n}\n\n\nRegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) {\n if (this == &that)\n return;\n\n if (that.pcre_ == nullptr) {\n pcre_ = nullptr;\n pcre_extra_ = nullptr;\n } else {\n std::string err_msg;\n if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg))\n logger->error(\"In RegexMatcher copy constructor: unexpected error: \" + err_msg);\n substr_vector_ = that.substr_vector_;\n last_match_count_ = that.last_match_count_;\n }\n}\n\n\nRegexMatcher::RegexMatcher(RegexMatcher &&that)\n : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_),\n pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)),\n substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_)\n{\n that.pcre_ = nullptr;\n that.pcre_extra_ = nullptr;\n}\n\n\nbool RegexMatcher::matched(const std::string &subject, std::string * const err_msg,\n size_t * const start_pos, size_t * const end_pos)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const int retcode = ::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), 0, 0,\n &substr_vector_[0], substr_vector_.size());\n\n if (retcode == 0) {\n if (err_msg != nullptr)\n *err_msg = \"Too many captured substrings! (We only support \"\n + std::to_string(substr_vector_.size() \/ 3 - 1) + \" substrings.)\";\n return false;\n }\n\n if (retcode > 0) {\n last_match_count_ = retcode;\n last_subject_ = subject;\n if (start_pos != nullptr)\n *start_pos = substr_vector_[0];\n if (end_pos != nullptr)\n *end_pos = substr_vector_[1];\n return true;\n }\n\n if (retcode != PCRE_ERROR_NOMATCH) {\n if (retcode == PCRE_ERROR_BADUTF8) {\n if (err_msg != nullptr)\n *err_msg = \"A \\\"subject\\\" with invalid UTF-8 was passed into RegexMatcher::matched()!\";\n } else if (err_msg != nullptr)\n *err_msg = \"Unknown error!\";\n }\n\n return false;\n}\n\n\nbool RegexMatcher::Matched(const std::string ®ex, const std::string &subject, const unsigned options,\n std::string * const err_msg, size_t * const start_pos, size_t * const end_pos)\n{\n RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex, err_msg, options));\n if (matcher == nullptr)\n LOG_ERROR(\"Failed to compile pattern \\\"\" + regex + \"\\\": \" + *err_msg);\n\n return matcher->matched(subject, err_msg, start_pos, end_pos);\n}\n\n\nstd::string RegexMatcher::operator[](const unsigned group) const {\n if (unlikely(group >= last_match_count_))\n throw std::out_of_range(\"in RegexMatcher::operator[]: group(\" + std::to_string(group) + \") >= \"\n + std::to_string(last_match_count_) + \"!\");\n\n const unsigned first_index(group * 2);\n const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]);\n return (substring_length == 0) ? \"\" : last_subject_.substr(substr_vector_[first_index], substring_length);\n}\n<commit_msg>cache for RegexMatcher factory (especially for better performance of RegexMatcher::Match)<commit_after>\/** \\file RegexMatcher.cc\n * \\brief Implementation of the RegexMatcher class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015,2017,2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"RegexMatcher.h\"\n#include <unordered_map>\n#include \"Compiler.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nbool RegexMatcher::utf8_configured_;\n\n\nbool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg,\n ::pcre_extra **pcre_extra_arg, std::string * const err_msg)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const char *errptr;\n int erroffset;\n\n int pcre_options(0);\n if (options & RegexMatcher::ENABLE_UTF8)\n pcre_options |= PCRE_UTF8;\n if (options & RegexMatcher::CASE_INSENSITIVE)\n pcre_options |= PCRE_CASELESS;\n if (options & RegexMatcher::MULTILINE)\n pcre_options |= PCRE_MULTILINE;\n\n *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr);\n if (*pcre_arg == nullptr) {\n *pcre_extra_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to compile invalid regular expression: \\\"\" + pattern + \"\\\"! (\"\n + std::string(errptr) + \")\";\n return false;\n }\n\n \/\/ Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe.\n *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr);\n if (*pcre_extra_arg == nullptr and errptr != nullptr) {\n ::pcre_free(*pcre_arg);\n *pcre_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to \\\"study\\\" the compiled pattern \\\"\" + pattern + \"\\\"! (\" + std::string(errptr) + \")\";\n return false;\n }\n\n return true;\n}\n\n\nstd::unordered_map<std::string, RegexMatcher*> matcher_cache;\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg,\n const unsigned options)\n{\n const std::string cache_key(pattern + \"###\" + StringUtil::ToString(options));\n auto cache_iter(matcher_cache.find(cache_key));\n if (cache_iter != matcher_cache.end())\n return cache_iter->second;\n\n \/\/ Make sure the PCRE library supports UTF8:\n if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) {\n int utf8_available;\n if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) {\n if (err_msg != nullptr)\n *err_msg = \"PCRE library does not know PCRE_CONFIG_UTF8!\";\n return nullptr;\n }\n\n if (utf8_available != 1) {\n if (err_msg != nullptr)\n *err_msg = \"This version of the PCRE library does not support UTF8!\";\n return nullptr;\n }\n\n RegexMatcher::utf8_configured_ = true;\n }\n\n ::pcre *pcre_ptr;\n ::pcre_extra *pcre_extra_ptr;\n if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg))\n return nullptr;\n\n RegexMatcher * const matcher = new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr);\n matcher_cache.emplace(cache_key, matcher);\n return matcher;\n}\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactoryOrDie(const std::string ®ex, const unsigned options) {\n std::string error_message;\n RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options));\n if (not error_message.empty())\n LOG_ERROR(\"failed to compile regex \\\"\" + regex + \"\\\": \" + error_message);\n\n return regex_matcher;\n}\n\n\nRegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) {\n if (this == &that)\n return;\n\n if (that.pcre_ == nullptr) {\n pcre_ = nullptr;\n pcre_extra_ = nullptr;\n } else {\n std::string err_msg;\n if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg))\n logger->error(\"In RegexMatcher copy constructor: unexpected error: \" + err_msg);\n substr_vector_ = that.substr_vector_;\n last_match_count_ = that.last_match_count_;\n }\n}\n\n\nRegexMatcher::RegexMatcher(RegexMatcher &&that)\n : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_),\n pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)),\n substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_)\n{\n that.pcre_ = nullptr;\n that.pcre_extra_ = nullptr;\n}\n\n\nbool RegexMatcher::matched(const std::string &subject, std::string * const err_msg,\n size_t * const start_pos, size_t * const end_pos)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const int retcode = ::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), 0, 0,\n &substr_vector_[0], substr_vector_.size());\n\n if (retcode == 0) {\n if (err_msg != nullptr)\n *err_msg = \"Too many captured substrings! (We only support \"\n + std::to_string(substr_vector_.size() \/ 3 - 1) + \" substrings.)\";\n return false;\n }\n\n if (retcode > 0) {\n last_match_count_ = retcode;\n last_subject_ = subject;\n if (start_pos != nullptr)\n *start_pos = substr_vector_[0];\n if (end_pos != nullptr)\n *end_pos = substr_vector_[1];\n return true;\n }\n\n if (retcode != PCRE_ERROR_NOMATCH) {\n if (retcode == PCRE_ERROR_BADUTF8) {\n if (err_msg != nullptr)\n *err_msg = \"A \\\"subject\\\" with invalid UTF-8 was passed into RegexMatcher::matched()!\";\n } else if (err_msg != nullptr)\n *err_msg = \"Unknown error!\";\n }\n\n return false;\n}\n\n\nbool RegexMatcher::Matched(const std::string ®ex, const std::string &subject, const unsigned options,\n std::string * const err_msg, size_t * const start_pos, size_t * const end_pos)\n{\n RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex, err_msg, options));\n if (matcher == nullptr)\n LOG_ERROR(\"Failed to compile pattern \\\"\" + regex + \"\\\": \" + *err_msg);\n\n return matcher->matched(subject, err_msg, start_pos, end_pos);\n}\n\n\nstd::string RegexMatcher::operator[](const unsigned group) const {\n if (unlikely(group >= last_match_count_))\n throw std::out_of_range(\"in RegexMatcher::operator[]: group(\" + std::to_string(group) + \") >= \"\n + std::to_string(last_match_count_) + \"!\");\n\n const unsigned first_index(group * 2);\n const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]);\n return (substring_length == 0) ? \"\" : last_subject_.substr(substr_vector_[first_index], substring_length);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************************************\/\/**\n\t\t* File: stack.cpp\n\t\t* Description: includes realized primitives from stack.h\n*****************************************************************************************************\/\n#include \"stack.h\"\n#include <sys\/mman.h>\n#include <assert.h>\n\n\/\/StackMap * StackMap::getInstance() {\n\/\/\tstatic thread_local StackMap instance;\n\/\/\treturn &instance;\n\/\/}\n\nconstexpr int PAGE_SIZE = 4096;\nconstexpr int ELEM_PER_PAGE = PAGE_SIZE \/ sizeof(StackElement);\n\nvoid StackMap::register_stack_root(void * newAddr) {\n\/\/ precisegc::details::lock_guard<mutex_type> lock(m_mutex);\n\tif (free_list == nullptr) {\n\t\tStackElement * data = (StackElement *) mmap(nullptr, PAGE_SIZE, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n\t\tassert(data != MAP_FAILED);\n\t\tfor (int i = 0; i < ELEM_PER_PAGE; ++i) {\n\t\t\tdata->next = free_list;\n\t\t\tfree_list = data;\n\t\t\tdata++;\n\t\t}\n\t}\n\tStackElement *result = free_list;\n\tfree_list = free_list->next;\n\tresult->next = top;\n\tresult->addr = newAddr;\n\ttop = result;\n}\n\nvoid StackMap::delete_stack_root(void * address) {\n\/\/ precisegc::details::lock_guard<mutex_type> lock(m_mutex);\n\tif (top->addr != address) {\n\t\t\/\/ if it is so, then automatic objects dectructs\n\t\t\/\/ not in the reverse order with their constructors\n\t\t\/\/ so we need to find and replace object that might be deleted\n\t\t\/\/ by object that is on the top\n\t\tStackElement *temp = top;\n\t\twhile (temp != nullptr) {\n\t\t\tif (temp->addr == address) {\n\t\t\t\ttemp->addr = top->addr;\n\t\t\t\tgoto end_a;\n\t\t\t}\n\t\t\ttemp = temp->next;\n\t\t}\n\t\tassert(false);\n\t}\n\tend_a:\n\tStackElement *deleted = top;\n\ttop = top->next;\n\tdeleted->next = free_list;\n\tfree_list = deleted;\n}\n\nStackElement* StackMap::begin() {\n\treturn top;\n}\n\nStackMap::lock_type StackMap::lock()\n{\n return lock_type(m_mutex);\n}\n\nStackMap::StackMap()\n\t: free_list(nullptr)\n\t, top(nullptr)\n{}\n<commit_msg>unsafe scope in stack root<commit_after>\/*************************************************************************************************\/\/**\n\t\t* File: stack.cpp\n\t\t* Description: includes realized primitives from stack.h\n*****************************************************************************************************\/\n#include \"stack.h\"\n#include <sys\/mman.h>\n#include <assert.h>\n\n#include \"details\/gc_unsafe_scope.h\"\n\n\/\/StackMap * StackMap::getInstance() {\n\/\/\tstatic thread_local StackMap instance;\n\/\/\treturn &instance;\n\/\/}\n\nconstexpr int PAGE_SIZE = 4096;\nconstexpr int ELEM_PER_PAGE = PAGE_SIZE \/ sizeof(StackElement);\n\nvoid StackMap::register_stack_root(void * newAddr) {\n\tprecisegc::details::gc_unsafe_scope unsafe_scope;\n\tif (free_list == nullptr) {\n\t\tStackElement * data = (StackElement *) mmap(nullptr, PAGE_SIZE, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n\t\tassert(data != MAP_FAILED);\n\t\tfor (int i = 0; i < ELEM_PER_PAGE; ++i) {\n\t\t\tdata->next = free_list;\n\t\t\tfree_list = data;\n\t\t\tdata++;\n\t\t}\n\t}\n\tStackElement *result = free_list;\n\tfree_list = free_list->next;\n\tresult->next = top;\n\tresult->addr = newAddr;\n\ttop = result;\n}\n\nvoid StackMap::delete_stack_root(void * address) {\n precisegc::details::gc_unsafe_scope unsafe_scope;\n\tif (top->addr != address) {\n\t\t\/\/ if it is so, then automatic objects dectructs\n\t\t\/\/ not in the reverse order with their constructors\n\t\t\/\/ so we need to find and replace object that might be deleted\n\t\t\/\/ by object that is on the top\n\t\tStackElement *temp = top;\n\t\twhile (temp != nullptr) {\n\t\t\tif (temp->addr == address) {\n\t\t\t\ttemp->addr = top->addr;\n\t\t\t\tgoto end_a;\n\t\t\t}\n\t\t\ttemp = temp->next;\n\t\t}\n\t\tassert(false);\n\t}\n\tend_a:\n\tStackElement *deleted = top;\n\ttop = top->next;\n\tdeleted->next = free_list;\n\tfree_list = deleted;\n}\n\nStackElement* StackMap::begin() {\n\treturn top;\n}\n\nStackMap::lock_type StackMap::lock()\n{\n return lock_type(m_mutex);\n}\n\nStackMap::StackMap()\n\t: free_list(nullptr)\n\t, top(nullptr)\n{}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013 Rajendra Kumar Uppal\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\n#include <iostream>\n#include \"MailMessage.h\"\n\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\n\n#define print(s) cout<<endl<<(s)<<endl;\n\n\nvoid send(const MailMessage& msg)\n{\n \/\/\/ Just a skeleton.\n \/\/\/ Assuming that there is a third party send\n \/\/\/ API which is responsible for sending email.\n print( \"Sender: \" + msg.getSender() );\n\n print(\"Recipients:\");\n MailMessage::Recipients recipients = msg.getRecipients();\n for ( auto start = recipients.begin(); start != recipients.end(); ++start )\n print( (*start).getAddress() );\n\n print(\"Subject: \" + msg.getSubject() );\n print(\"Content: \" + msg.getContent() );\n}\n\n\nvoid Test_MailMessage()\n{\n std::string sender(\"rajen.iitd@gmail.com\");\n std::string recipient(\"uppal@adobe.com\");\n std::string subject(\"Generated email\");\n std::string content = \"Hi \";\n content += recipient;\n content += \",\\n\\n\";\n content += \"Have a good day!\\n\\n\";\n content += \"Regards,\\n\";\n content += \"A-Team\";\n std::string attachment(\"C:\\\\DSC.jpg\");\n\n MailMessage message;\n message.setSender( sender );\n message.addRecipient( MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient) );\n message.setSubject( subject );\n message.setContent( content );\n message.addAttachment( attachment );\n\n send(message);\n}\n\n\nint main(int argc, char ** argv)\n{\n Test_MailMessage();\n\n print(\"Press any key to continue...\");\n cin.get();\n return 0;\n}\n\n\/\/ ~EOF\n<commit_msg>Update Client.cpp<commit_after>\n#include <iostream>\n#include \"MailMessage.h\"\n\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\n\n#define print(s) cout<<endl<<(s)<<endl;\n\n\nvoid send(const MailMessage& msg)\n{\n \/\/\/ Just a skeleton.\n \/\/\/ Assuming that there is a third party send\n \/\/\/ API which is responsible for sending email.\n print( \"Sender: \" + msg.getSender() );\n\n print(\"Recipients:\");\n MailMessage::Recipients recipients = msg.getRecipients();\n for ( auto start = recipients.begin(); start != recipients.end(); ++start )\n print( (*start).getAddress() );\n\n print(\"Subject: \" + msg.getSubject() );\n print(\"Content: \" + msg.getContent() );\n}\n\n\nvoid Test_MailMessage()\n{\n std::string sender(\"rajen.iitd@gmail.com\");\n std::string recipient(\"uppal@adobe.com\");\n std::string subject(\"Generated email\");\n std::string content = \"Hi \";\n content += recipient;\n content += \",\\n\\n\";\n content += \"Have a good day!\\n\\n\";\n content += \"Regards,\\n\";\n content += \"A-Team\";\n std::string attachment(\"C:\\\\DSC.jpg\");\n\n MailMessage message;\n message.setSender( sender );\n message.addRecipient( MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient) );\n message.setSubject( subject );\n message.setContent( content );\n message.addAttachment( attachment );\n\n send(message);\n}\n\n\nint main(int argc, char ** argv)\n{\n Test_MailMessage();\n\n print(\"Press any key to continue...\");\n cin.get();\n return 0;\n}\n\n\/\/ ~EOF\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbOGRExtendedFilenameToOptions.h\"\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n\nusing namespace otb;\n\n\ntypedef OGRExtendedFilenameToOptions FilenameHelperType;\n\nint otbOGRExtendedFileName(int , char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const char * inputExtendedFilename = argv[1];\n const char * outputFilename = argv[2];\n\n std::cout<< argv[1] <<\" \"<<argv[2]<<std::endl;\n FilenameHelperType::Pointer helper = FilenameHelperType::New();\n\n helper->SetExtendedFileName(inputExtendedFilename);\n\n std::ofstream file;\n file.open(outputFilename);\n\n file << helper->SimpleFileNameIsSet() << std::endl;\n file << helper->GetSimpleFileName() << std::endl;\n\n file << \"Open option :\"<<std::endl;\n FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();\n for ( auto option : open )\n {\n file<< option << std::endl;\n }\n\n file << \"Create option :\"<<std::endl;\n FilenameHelperType::GDALOptionType create = helper->GetGDALOptions(\"creation\");\n for ( auto option : create )\n {\n file<< option << std::endl;\n }\n\n file << \"Layer option :\"<<std::endl;\n FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions(\"layer\");\n for ( auto option : layer )\n {\n file<< option << std::endl;\n }\n\n file<< \"End of classic helper.\"<<std::endl;\n\n layer.push_back(\"TOTO=first\");\n FilenameHelperType::Pointer layerHelper = \n FilenameHelperType::GetGDALLayerOptionsHelper ( layer );\n std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;\n FilenameHelperType::GDALOptionType newOptions;\n \/\/ std::vector< std::string> newOptions;\n newOptions.push_back(\"TOTO=second\");\n newOptions.push_back(\"TiTi=option\");\n layerHelper->AddGDALLayerOptions( newOptions );\n\n file << layerHelper->SimpleFileNameIsSet() << std::endl;\n file << layerHelper->HasGDALLayerOption() << std::endl;\n file << \"Layer option from layer helper:\"<<std::endl;\n FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions(\"layer\");\n \/\/ need to sort for dummy windows\n std::sort( latestOptions.begin() , latestOptions.end() );\n for ( auto option : latestOptions ) \n {\n file<< option << std::endl;\n }\n\n file.close();\n return EXIT_SUCCESS;\n}\n\n<commit_msg>TEST: fix TvOGRExtendedFilename<commit_after>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbOGRExtendedFilenameToOptions.h\"\n#include \"itksys\/SystemTools.hxx\"\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n\nusing namespace otb;\n\n\ntypedef OGRExtendedFilenameToOptions FilenameHelperType;\n\nint otbOGRExtendedFileName(int , char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const char * inputExtendedFilename = argv[1];\n const char * outputFilename = argv[2];\n\n std::cout<< argv[1] <<\" \"<<argv[2]<<std::endl;\n FilenameHelperType::Pointer helper = FilenameHelperType::New();\n\n helper->SetExtendedFileName(inputExtendedFilename);\n\n std::ofstream file;\n file.open(outputFilename);\n\n file << helper->SimpleFileNameIsSet() << std::endl;\n file << itksys::SystemTools::GetFilenameName(helper->GetSimpleFileName()) << std::endl;\n\n file << \"Open option :\"<<std::endl;\n FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();\n for ( auto option : open )\n {\n file<< option << std::endl;\n }\n\n file << \"Create option :\"<<std::endl;\n FilenameHelperType::GDALOptionType create = helper->GetGDALOptions(\"creation\");\n for ( auto option : create )\n {\n file<< option << std::endl;\n }\n\n file << \"Layer option :\"<<std::endl;\n FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions(\"layer\");\n for ( auto option : layer )\n {\n file<< option << std::endl;\n }\n\n file<< \"End of classic helper.\"<<std::endl;\n\n layer.push_back(\"TOTO=first\");\n FilenameHelperType::Pointer layerHelper = \n FilenameHelperType::GetGDALLayerOptionsHelper ( layer );\n std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;\n FilenameHelperType::GDALOptionType newOptions;\n \/\/ std::vector< std::string> newOptions;\n newOptions.push_back(\"TOTO=second\");\n newOptions.push_back(\"TiTi=option\");\n layerHelper->AddGDALLayerOptions( newOptions );\n\n file << layerHelper->SimpleFileNameIsSet() << std::endl;\n file << layerHelper->HasGDALLayerOption() << std::endl;\n file << \"Layer option from layer helper:\"<<std::endl;\n FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions(\"layer\");\n \/\/ need to sort for dummy windows\n std::sort( latestOptions.begin() , latestOptions.end() );\n for ( auto option : latestOptions ) \n {\n file<< option << std::endl;\n }\n\n file.close();\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/* ScriptData\nSDName: Westfall\nSD%Complete: 90\nSDComment: Quest support: 155\nSDCategory: Westfall\nEndScriptData *\/\n\n\/* ContentData\nnpc_daphne_stilwell\nEndContentData *\/\n\n#include \"Player.h\"\n#include \"ScriptMgr.h\"\n#include \"ScriptedCreature.h\"\n#include \"ScriptedEscortAI.h\"\n\n\/*######\n## npc_daphne_stilwell\n######*\/\n\nenum DaphneStilwell\n{\n \/\/ Yells\n SAY_DS_START = 0,\n SAY_DS_DOWN_1 = 1,\n SAY_DS_DOWN_2 = 2,\n SAY_DS_DOWN_3 = 3,\n SAY_DS_PROLOGUE = 4,\n\n \/\/ Spells\n SPELL_SHOOT = 6660,\n\n \/\/ Quests\n QUEST_TOME_VALOR = 1651,\n\n \/\/ Creatures\n NPC_DEFIAS_RAIDER = 6180,\n\n \/\/ Equips\n EQUIP_ID_RIFLE = 2511\n};\n\nclass npc_daphne_stilwell : public CreatureScript\n{\npublic:\n npc_daphne_stilwell() : CreatureScript(\"npc_daphne_stilwell\") { }\n\n bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) override\n {\n if (quest->GetQuestId() == QUEST_TOME_VALOR)\n {\n creature->AI()->Talk(SAY_DS_START);\n\n if (npc_escortAI* pEscortAI = CAST_AI(npc_daphne_stilwell::npc_daphne_stilwellAI, creature->AI()))\n pEscortAI->Start(true, true, player->GetGUID());\n }\n\n return true;\n }\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return new npc_daphne_stilwellAI(creature);\n }\n\n struct npc_daphne_stilwellAI : public npc_escortAI\n {\n npc_daphne_stilwellAI(Creature* creature) : npc_escortAI(creature), summons(me) { }\n\n SummonList summons;\n uint8 textCounter;\n\n void Reset() override\n {\n summons.DespawnAll();\n textCounter = SAY_DS_DOWN_1;\n }\n\n void WaypointReached(uint32 waypointId) override\n {\n Player* player = GetPlayerForEscort();\n\n if (!player)\n return;\n\n switch (waypointId)\n {\n case 4:\n SetEquipmentSlots(false, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE, EQUIP_ID_RIFLE);\n me->SetSheath(SHEATH_STATE_RANGED);\n me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);\n break;\n case 7:\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 8:\n me->SetSheath(SHEATH_STATE_RANGED);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 9:\n me->SetSheath(SHEATH_STATE_RANGED);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11438.14f, 1607.6f, 70.94f, 4.38f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 10:\n SetRun(false);\n break;\n case 11:\n Talk(SAY_DS_PROLOGUE);\n break;\n case 13:\n SetEquipmentSlots(true);\n me->SetSheath(SHEATH_STATE_UNARMED);\n me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);\n break;\n case 17:\n SetEscortPaused(true);\n player->GroupEventHappens(QUEST_TOME_VALOR, me);\n me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER);\n me->DespawnOrUnsummon(60000);\n break;\n }\n }\n\n void AttackStart(Unit* who) override\n {\n if (me->Attack(who, false))\n {\n me->SetInCombatWith(who);\n who->SetInCombatWith(me);\n }\n }\n\n void JustSummoned(Creature* creature) override\n {\n creature->SetHomePosition(me->GetHomePosition());\n creature->GetMotionMaster()->MoveChase(me);\n creature->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());\n creature->AI()->AttackStart(me);\n creature->AddThreat(me, 0.0f);\n summons.Summon(creature);\n }\n\n void SummonedCreatureDies(Creature* creature, Unit*) override\n {\n summons.Despawn(creature);\n if (summons.empty())\n Talk(textCounter++, GetPlayerForEscort());\n }\n\n void Update(const uint32 diff)\n {\n npc_escortAI::UpdateAI(diff);\n\n if (!UpdateVictim())\n return;\n\n if (me->isAttackReady(BASE_ATTACK))\n {\n if (!me->IsWithinDist(me->GetVictim(), ATTACK_DISTANCE))\n DoCastVictim(SPELL_SHOOT, true);\n else\n {\n me->SetSheath(SHEATH_STATE_MELEE);\n me->AttackerStateUpdate(me->GetVictim());\n }\n\n me->resetAttackTimer();\n }\n }\n };\n};\n\nvoid AddSC_westfall()\n{\n new npc_daphne_stilwell();\n}\n<commit_msg>fix(Core\/Quest): Daphne Stillwater respawn for quest Tome of Valor (#9469)<commit_after>\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/* ScriptData\nSDName: Westfall\nSD%Complete: 90\nSDComment: Quest support: 155\nSDCategory: Westfall\nEndScriptData *\/\n\n\/* ContentData\nnpc_daphne_stilwell\nEndContentData *\/\n\n#include \"Player.h\"\n#include \"ScriptMgr.h\"\n#include \"ScriptedCreature.h\"\n#include \"ScriptedEscortAI.h\"\n\n\/*######\n## npc_daphne_stilwell\n######*\/\n\nenum DaphneStilwell\n{\n \/\/ Yells\n SAY_DS_START = 0,\n SAY_DS_DOWN_1 = 1,\n SAY_DS_DOWN_2 = 2,\n SAY_DS_DOWN_3 = 3,\n SAY_DS_PROLOGUE = 4,\n\n \/\/ Spells\n SPELL_SHOOT = 6660,\n\n \/\/ Quests\n QUEST_TOME_VALOR = 1651,\n\n \/\/ Creatures\n NPC_DEFIAS_RAIDER = 6180,\n\n \/\/ Equips\n EQUIP_ID_RIFLE = 2511\n};\n\nclass npc_daphne_stilwell : public CreatureScript\n{\npublic:\n npc_daphne_stilwell() : CreatureScript(\"npc_daphne_stilwell\") { }\n\n bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) override\n {\n if (quest->GetQuestId() == QUEST_TOME_VALOR)\n {\n creature->AI()->Talk(SAY_DS_START);\n\n if (npc_escortAI* pEscortAI = CAST_AI(npc_daphne_stilwell::npc_daphne_stilwellAI, creature->AI()))\n pEscortAI->Start(true, true, player->GetGUID());\n }\n\n return true;\n }\n\n CreatureAI* GetAI(Creature* creature) const override\n {\n return new npc_daphne_stilwellAI(creature);\n }\n\n struct npc_daphne_stilwellAI : public npc_escortAI\n {\n npc_daphne_stilwellAI(Creature* creature) : npc_escortAI(creature), summons(me) { }\n\n SummonList summons;\n uint8 textCounter;\n\n void Reset() override\n {\n summons.DespawnAll();\n textCounter = SAY_DS_DOWN_1;\n }\n\n void WaypointReached(uint32 waypointId) override\n {\n Player* player = GetPlayerForEscort();\n\n if (!player)\n return;\n\n switch (waypointId)\n {\n case 4:\n SetEquipmentSlots(false, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE, EQUIP_ID_RIFLE);\n me->SetSheath(SHEATH_STATE_RANGED);\n me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);\n break;\n case 7:\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 8:\n me->SetSheath(SHEATH_STATE_RANGED);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 9:\n me->SetSheath(SHEATH_STATE_RANGED);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n me->SummonCreature(NPC_DEFIAS_RAIDER, -11438.14f, 1607.6f, 70.94f, 4.38f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);\n break;\n case 10:\n SetRun(false);\n break;\n case 11:\n Talk(SAY_DS_PROLOGUE);\n break;\n case 13:\n SetEquipmentSlots(true);\n me->SetSheath(SHEATH_STATE_UNARMED);\n me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);\n break;\n case 17:\n SetEscortPaused(true);\n player->GroupEventHappens(QUEST_TOME_VALOR, me);\n me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER);\n me->DespawnOrUnsummon(1s, 1s);\n break;\n }\n }\n\n void AttackStart(Unit* who) override\n {\n if (me->Attack(who, false))\n {\n me->SetInCombatWith(who);\n who->SetInCombatWith(me);\n }\n }\n\n void JustSummoned(Creature* creature) override\n {\n creature->SetHomePosition(me->GetHomePosition());\n creature->GetMotionMaster()->MoveChase(me);\n creature->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());\n creature->AI()->AttackStart(me);\n creature->AddThreat(me, 0.0f);\n summons.Summon(creature);\n }\n\n void SummonedCreatureDies(Creature* creature, Unit*) override\n {\n summons.Despawn(creature);\n if (summons.empty())\n Talk(textCounter++, GetPlayerForEscort());\n }\n\n void Update(const uint32 diff)\n {\n npc_escortAI::UpdateAI(diff);\n\n if (!UpdateVictim())\n return;\n\n if (me->isAttackReady(BASE_ATTACK))\n {\n if (!me->IsWithinDist(me->GetVictim(), ATTACK_DISTANCE))\n DoCastVictim(SPELL_SHOOT, true);\n else\n {\n me->SetSheath(SHEATH_STATE_MELEE);\n me->AttackerStateUpdate(me->GetVictim());\n }\n\n me->resetAttackTimer();\n }\n }\n };\n};\n\nvoid AddSC_westfall()\n{\n new npc_daphne_stilwell();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbOGRExtendedFilenameToOptions.h\"\n#include <iostream>\n#include <fstream>\n\nusing namespace otb;\n\n\ntypedef OGRExtendedFilenameToOptions FilenameHelperType;\n\nint otbOGRExtendedFileName(int , char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const char * inputExtendedFilename = argv[1];\n const char * outputFilename = argv[2];\n\n std::cout<< argv[1] <<\" \"<<argv[2]<<std::endl;\n FilenameHelperType::Pointer helper = FilenameHelperType::New();\n\n helper->SetExtendedFileName(inputExtendedFilename);\n\n std::ofstream file;\n file.open(outputFilename);\n\n file << helper->SimpleFileNameIsSet() << std::endl;\n file << helper->GetSimpleFileName() << std::endl;\n\n file << \"Open option :\"<<std::endl;\n FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();\n for ( auto option : open )\n {\n file<< option << std::endl;\n }\n\n file << \"Create option :\"<<std::endl;\n FilenameHelperType::GDALOptionType create = helper->GetGDALOptions(\"creation\");\n for ( auto option : create )\n {\n file<< option << std::endl;\n }\n\n file << \"Layer option :\"<<std::endl;\n FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions(\"layer\");\n for ( auto option : layer )\n {\n file<< option << std::endl;\n }\n\n file<< \"End of classic helper.\"<<std::endl;\n\n layer.push_back(\"TOTO=first\");\n FilenameHelperType::Pointer layerHelper = \n FilenameHelperType::GetGDALLayerOptionsHelper ( layer );\n std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;\n FilenameHelperType::GDALOptionType newOptions;\n \/\/ std::vector< std::string> newOptions;\n newOptions.push_back(\"TOTO=second\");\n newOptions.push_back(\"TiTi=option\");\n layerHelper->AddGDALLayerOptions( newOptions );\n\n file << layerHelper->SimpleFileNameIsSet() << std::endl;\n file << layerHelper->HasGDALLayerOption() << std::endl;\n file << \"Layer option from layer helper:\"<<std::endl;\n FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions(\"layer\");\n for ( auto option : latestOptions )\n {\n file<< option << std::endl;\n }\n \/\/ test\n\n file.close();\n return EXIT_SUCCESS;\n}\n\n<commit_msg>TEST: ordered vector of string to get the same output on every OS<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbOGRExtendedFilenameToOptions.h\"\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n\nusing namespace otb;\n\n\ntypedef OGRExtendedFilenameToOptions FilenameHelperType;\n\nint otbOGRExtendedFileName(int , char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const char * inputExtendedFilename = argv[1];\n const char * outputFilename = argv[2];\n\n std::cout<< argv[1] <<\" \"<<argv[2]<<std::endl;\n FilenameHelperType::Pointer helper = FilenameHelperType::New();\n\n helper->SetExtendedFileName(inputExtendedFilename);\n\n std::ofstream file;\n file.open(outputFilename);\n\n file << helper->SimpleFileNameIsSet() << std::endl;\n file << helper->GetSimpleFileName() << std::endl;\n\n file << \"Open option :\"<<std::endl;\n FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();\n for ( auto option : open )\n {\n file<< option << std::endl;\n }\n\n file << \"Create option :\"<<std::endl;\n FilenameHelperType::GDALOptionType create = helper->GetGDALOptions(\"creation\");\n for ( auto option : create )\n {\n file<< option << std::endl;\n }\n\n file << \"Layer option :\"<<std::endl;\n FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions(\"layer\");\n for ( auto option : layer )\n {\n file<< option << std::endl;\n }\n\n file<< \"End of classic helper.\"<<std::endl;\n\n layer.push_back(\"TOTO=first\");\n FilenameHelperType::Pointer layerHelper = \n FilenameHelperType::GetGDALLayerOptionsHelper ( layer );\n std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;\n FilenameHelperType::GDALOptionType newOptions;\n \/\/ std::vector< std::string> newOptions;\n newOptions.push_back(\"TOTO=second\");\n newOptions.push_back(\"TiTi=option\");\n layerHelper->AddGDALLayerOptions( newOptions );\n\n file << layerHelper->SimpleFileNameIsSet() << std::endl;\n file << layerHelper->HasGDALLayerOption() << std::endl;\n file << \"Layer option from layer helper:\"<<std::endl;\n FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions(\"layer\");\n \/\/ need to sort for dummy windows\n std::sort( latestOptions.begin() , latestOptions.end() );\n for ( auto option : latestOptions ) \n {\n file<< option << std::endl;\n }\n\n file.close();\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>class PowerSpectrum:public SplineFunction {\npublic:\n PowerSpectrum(int n): SplineFunction(n) {};\n int fixed_power;\n double normalization;\n double Pk_smooth2; \/\/ param.Pk_smooth squared\n double Rnorm; \n double sigmaR_integrand(double k) {\n double x=k*Rnorm;\n double w;\n if (x<=1e-3) w = 1-x*x\/10.0;\n else w = 3.0*(sin(x)-x*cos(x))\/x\/x\/x;\n return 0.5\/M_PI\/M_PI*k*k*w*w*this->power(k);\n }\n double sigmaR(double R) {\n double target_prec = 1e-11; \/\/ 1e-12 was causing divergence in certain cases\n double precision = 1.0;\n Rnorm = R;\n double retval = sqrt(Romberg(&PowerSpectrum::sigmaR_integrand,0,10.0,target_prec,&precision));\n if(precision > target_prec){\n printf(\"Error: actual Romberg integration precision (%g) is greater than the target precision (%g); halting.\\n\", precision, target_prec);\n exit(1);\n }\n return retval;\n }\n \/\/ Do Romberg integration with up to 25 bisections.\n \/\/ Give a precision 'prec'. Also return the estimated precision in 'obtprec'.\n\n #define MAXITER 25\n double Romberg(double (PowerSpectrum::*func)(double), double a, double b,\n double prec, double *obtprec) {\n int jj;\n double h, s, fourtokm1, TT[MAXITER+1][MAXITER+1];\n\n h = 0.5*(b-a);\n TT[0][1] = h * ( (this->*func)(a) + (this->*func)(b) );\n jj = 0;\n do {\n jj++;\n s = 0; for(int k=1; k<=(1<<(jj-1)); k++) s += (this->*func)(a + (2*k-1)*h);\n TT[jj][1] = 0.5*TT[jj-1][1] + h * s;\n fourtokm1 = 1;\n for(int k=2; k<=jj; k++) {\n fourtokm1 *=4;\n TT[jj][k] = TT[jj][k-1] + ( TT[jj][k-1] - TT[jj-1][k-1])\/(fourtokm1 -1);\n }\n h *= 0.5;\n \/\/printf(\"TT[%d] = %g\\n\", jj, TT[jj][jj]);\n if(jj>1 && fabs(TT[jj][jj]-TT[jj-1][jj-1])<prec*fabs(TT[jj][jj])) break;\n } while(jj<MAXITER);\n\n *obtprec = (TT[jj][jj]-TT[jj-1][jj-1])\/TT[jj][jj];\n return TT[jj][jj];\n }\n \n int LoadPower(char filename[], Parameters& param) {\n \/\/ Read the file and load\/compile the spline function\n \/\/ Return 0 if ok\n \/\/ Read the file\n \/\/ Rescale the given wavenumbers to match to simulation units\n \/\/ Renormalize the power spectrum\n \/\/ Divide the power spectrum by the box volume, so that the \n \/\/ inverse FFT is normalized properly.\n char line[200];\n FILE *fp;\n double k,P;\n int nn;\n Pk_smooth2 = 0.0;\n normalization = 1.0;\n fp = fopen(filename,\"r\");\n if(fp == NULL){\n printf(\"Power spectrum file \\\"%s\\\" not found; exiting.\\n\", filename);\n exit(1);\n }\n nn=0;\n\n int jj = 0;\n while (fgets(line,200,fp)!=NULL) {\n jj++;\n if (line[0]=='#') continue;\n sscanf(line,\"%lf %lf\",&k,&P);\n if (k<0.0) continue;\n if (P<0.0) continue;\n k*=param.Pk_scale;\n if (k>0.0) {\n this->load(log(k),log(P));\n } else {\n this->load(-1e3,log(P));\n }\n nn++;\n }\n this->spline();\n \n \/\/ Might still have to normalize things!\n if (param.Pk_norm>0.0) { \/\/ Do a normalization \n printf(\"Input sigma(%f) = %f\\n\", param.Pk_norm, sigmaR(param.Pk_norm));\n normalization = param.Pk_sigma\/sigmaR(param.Pk_norm);\n normalization *= normalization;\n printf(\"Final sigma(%f) = %f\\n\", param.Pk_norm, sigmaR(param.Pk_norm));\n }\n \/\/ Might need to normalize to the box volume. This is appropriate\n \/\/ if the iFFT is like FFTW, i.e., not dividing by N.\n \/\/ This is because integrals over k bring in a phase space volume\n \/\/ per cell of (2*pi\/L)^3\n normalization \/= param.boxsize*param.boxsize*param.boxsize;\n Pk_smooth2 = param.Pk_smooth*param.Pk_smooth;\n \n fixed_power = param.qPk_fix_to_mean;\n if (fixed_power)\n printf(\"Fixing density mode amplitudes to sqrt(P(k))\\n\");\n return 0;\n }\n\n double power(double wavenumber) {\n \/\/ Evaluate the power spectrum and apply a smoothing.\n \/\/ Probably we should force P(k=0) to be 0.\n \/\/ The smoothing should be exp(-k^2 sig^2\/2) for the density,\n \/\/ which is exp(-k^2 sig^2) for the power\n if (wavenumber<=0.0) return 0.0;\n return exp(this->val(log(wavenumber))-wavenumber*wavenumber*this->Pk_smooth2)*normalization;\n }\n\n double one_rand(int i) {\n return gsl_rng_uniform(rng[i]);\n }\n Complx cgauss(double wavenumber, int rng) {\n \/\/ Return a gaussian complex deviate scaled to the sqrt of the power\n \/\/ Box-Muller, adapted from Numerical Recipes\n \/\/ If fixed_power is set, the complex deviate always has amplitude sqrt(P(k))\n double Pk = this->power(wavenumber);\n double phase1, phase2, r2;\n \/\/ printf(\"P(%f) = %g\\n\",wavenumber,Pk);\n do { \n phase1 = one_rand(rng)*2.0-1.0;\n phase2 = one_rand(rng)*2.0-1.0;\n r2 = phase1*phase1+phase2*phase2;\n } while (!(r2<1.0&&r2>0.0));\n if (fixed_power){\n r2 = sqrt(Pk\/r2);\n } else {\n r2 = sqrt(-Pk*log(r2)\/r2); \/\/ Drop the factor of 2, so these Gaussians\n \/\/ have variance of 1\/2.\n }\n \/\/ printf(\"cgauss: %f %f\\n\", phase1*r2, phase2*r2);\n return Complx(phase1*r2,phase2*r2);\n }\n};\n<commit_msg>Add extrapolation warning<commit_after>class PowerSpectrum:public SplineFunction {\npublic:\n PowerSpectrum(int n): SplineFunction(n) {};\n int fixed_power;\n double normalization;\n double Pk_smooth2; \/\/ param.Pk_smooth squared\n double Rnorm;\n double kmax; \/\/ max k in the input PS\n double sigmaR_integrand(double k) {\n double x=k*Rnorm;\n double w;\n if (x<=1e-3) w = 1-x*x\/10.0;\n else w = 3.0*(sin(x)-x*cos(x))\/x\/x\/x;\n return 0.5\/M_PI\/M_PI*k*k*w*w*this->power(k);\n }\n double sigmaR(double R) {\n double target_prec = 1e-11; \/\/ 1e-12 was causing divergence in certain cases\n double precision = 1.0;\n Rnorm = R;\n double retval = sqrt(Romberg(&PowerSpectrum::sigmaR_integrand,0,10.0,target_prec,&precision));\n if(precision > target_prec){\n printf(\"Error: actual Romberg integration precision (%g) is greater than the target precision (%g); halting.\\n\", precision, target_prec);\n exit(1);\n }\n return retval;\n }\n \/\/ Do Romberg integration with up to 25 bisections.\n \/\/ Give a precision 'prec'. Also return the estimated precision in 'obtprec'.\n\n #define MAXITER 25\n double Romberg(double (PowerSpectrum::*func)(double), double a, double b,\n double prec, double *obtprec) {\n int jj;\n double h, s, fourtokm1, TT[MAXITER+1][MAXITER+1];\n\n h = 0.5*(b-a);\n TT[0][1] = h * ( (this->*func)(a) + (this->*func)(b) );\n jj = 0;\n do {\n jj++;\n s = 0; for(int k=1; k<=(1<<(jj-1)); k++) s += (this->*func)(a + (2*k-1)*h);\n TT[jj][1] = 0.5*TT[jj-1][1] + h * s;\n fourtokm1 = 1;\n for(int k=2; k<=jj; k++) {\n fourtokm1 *=4;\n TT[jj][k] = TT[jj][k-1] + ( TT[jj][k-1] - TT[jj-1][k-1])\/(fourtokm1 -1);\n }\n h *= 0.5;\n \/\/printf(\"TT[%d] = %g\\n\", jj, TT[jj][jj]);\n if(jj>1 && fabs(TT[jj][jj]-TT[jj-1][jj-1])<prec*fabs(TT[jj][jj])) break;\n } while(jj<MAXITER);\n\n *obtprec = (TT[jj][jj]-TT[jj-1][jj-1])\/TT[jj][jj];\n return TT[jj][jj];\n }\n \n int LoadPower(char filename[], Parameters& param) {\n \/\/ Read the file and load\/compile the spline function\n \/\/ Return 0 if ok\n \/\/ Read the file\n \/\/ Rescale the given wavenumbers to match to simulation units\n \/\/ Renormalize the power spectrum\n \/\/ Divide the power spectrum by the box volume, so that the \n \/\/ inverse FFT is normalized properly.\n char line[200];\n FILE *fp;\n double k,P;\n int nn;\n Pk_smooth2 = 0.0;\n normalization = 1.0;\n fp = fopen(filename,\"r\");\n if(fp == NULL){\n printf(\"Power spectrum file \\\"%s\\\" not found; exiting.\\n\", filename);\n exit(1);\n }\n nn=0;\n\n int jj = 0;\n while (fgets(line,200,fp)!=NULL) {\n jj++;\n if (line[0]=='#') continue;\n sscanf(line,\"%lf %lf\",&k,&P);\n if (k<0.0) continue;\n if (P<0.0) continue;\n k*=param.Pk_scale;\n if (k>0.0) {\n this->load(log(k),log(P));\n } else {\n this->load(-1e3,log(P));\n }\n kmax = std::max(k,kmax);\n nn++;\n }\n this->spline();\n \n \/\/ Might still have to normalize things!\n if (param.Pk_norm>0.0) { \/\/ Do a normalization \n printf(\"Input sigma(%f) = %f\\n\", param.Pk_norm, sigmaR(param.Pk_norm));\n normalization = param.Pk_sigma\/sigmaR(param.Pk_norm);\n normalization *= normalization;\n printf(\"Final sigma(%f) = %f\\n\", param.Pk_norm, sigmaR(param.Pk_norm));\n }\n \/\/ Might need to normalize to the box volume. This is appropriate\n \/\/ if the iFFT is like FFTW, i.e., not dividing by N.\n \/\/ This is because integrals over k bring in a phase space volume\n \/\/ per cell of (2*pi\/L)^3\n normalization \/= param.boxsize*param.boxsize*param.boxsize;\n Pk_smooth2 = param.Pk_smooth*param.Pk_smooth;\n \n fixed_power = param.qPk_fix_to_mean;\n if (fixed_power)\n printf(\"Fixing density mode amplitudes to sqrt(P(k))\\n\");\n return 0;\n }\n\n double power(double wavenumber) {\n \/\/ Evaluate the power spectrum and apply a smoothing.\n \/\/ Probably we should force P(k=0) to be 0.\n \/\/ The smoothing should be exp(-k^2 sig^2\/2) for the density,\n \/\/ which is exp(-k^2 sig^2) for the power\n static bool already_warned = false;\n if (wavenumber > kmax && !already_warned) {\n fprintf(stderr, \"\\n*** WARNING: power spectrum spline interpolation was requested\\n\"\n \" past the maximum k (%f) that was provided in the input power\\n\"\n \" spectrum file. The extrapolation should be well-behaved, but\\n\"\n \" make sure that this was expected. Provide a power spectrum\\n\"\n \" that goes to k=10 to get rid of this warning.\\n\", wavenumber, kmax);\n already_warned = true;\n }\n if (wavenumber<=0.0) return 0.0;\n return exp(this->val(log(wavenumber))-wavenumber*wavenumber*this->Pk_smooth2)*normalization;\n }\n\n double one_rand(int i) {\n return gsl_rng_uniform(rng[i]);\n }\n Complx cgauss(double wavenumber, int rng) {\n \/\/ Return a gaussian complex deviate scaled to the sqrt of the power\n \/\/ Box-Muller, adapted from Numerical Recipes\n \/\/ If fixed_power is set, the complex deviate always has amplitude sqrt(P(k))\n double Pk = this->power(wavenumber);\n double phase1, phase2, r2;\n \/\/ printf(\"P(%f) = %g\\n\",wavenumber,Pk);\n do { \n phase1 = one_rand(rng)*2.0-1.0;\n phase2 = one_rand(rng)*2.0-1.0;\n r2 = phase1*phase1+phase2*phase2;\n } while (!(r2<1.0&&r2>0.0));\n if (fixed_power){\n r2 = sqrt(Pk\/r2);\n } else {\n r2 = sqrt(-Pk*log(r2)\/r2); \/\/ Drop the factor of 2, so these Gaussians\n \/\/ have variance of 1\/2.\n }\n \/\/ printf(\"cgauss: %f %f\\n\", phase1*r2, phase2*r2);\n return Complx(phase1*r2,phase2*r2);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2013 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/*\n * SEDMLUtils.cpp\n *\n * Created on: 15 Jul 2013\n * Author: dada\n *\/\n\n\/\/#include <zip.h>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include \"SEDMLUtils.h\"\n\n#include <sedml\/SedTypes.h>\n#include <sbml\/SBMLTypes.h>\n\n#include <copasi\/model\/CModel.h>\n#include <copasi\/report\/CCopasiObject.h>\n#include <copasi\/CopasiDataModel\/CCopasiDataModel.h>\n\nstd::string SEDMLUtils::findIdByNameAndType(\n const std::map<const CCopasiObject*, SBase*>& map,\n int typeCode,\n const std::string& name)\n{\n std::map<const CCopasiObject*, SBase*>::const_iterator it = map.begin();\n\n std::string::size_type compartmentStart = name.find(\"{\");\n\n std::string compId = \"\";\n\n if (compartmentStart != std::string::npos)\n {\n std::string compName = name.substr(compartmentStart + 1, name.size() - compartmentStart - 2);\n SEDMLUtils::removeCharactersFromString(compName, \"\\\"\");\n\n compId = findIdByNameAndType(map, SBML_COMPARTMENT, compName);\n }\n\n while (it != map.end())\n {\n SBase* current = it->second;\n const CCopasiObject* object = it->first;\n std::string displayName = object->getObjectDisplayName();\n\n if (((current->getTypeCode() & typeCode) != typeCode))\n {\n ++it;\n continue;\n }\n\n if (current->getName() == name)\n return current->getId();\n\n if (typeCode == SBML_SPECIES && compartmentStart != std::string::npos)\n {\n if (displayName == name)\n {\n Species* species = (Species*)current;\n\n if (species->getCompartment() == compId)\n return species->getId();\n }\n }\n\n ++it;\n }\n\n return \"\";\n}\n\nstd::string\nSEDMLUtils::getXPathAndName(std::string& sbmlId,\n const std::string &type,\n const CModel *pModel,\n const CCopasiDataModel& dataModel)\n{\n std::vector<std::string> stringsContainer;\n std::string targetXPathString;\n const std::map<const CCopasiObject*, SBase*>& copasi2sbmlmap =\n const_cast<CCopasiDataModel&>(dataModel).getCopasi2SBMLMap();\n std::string displayName = sbmlId;\n\n if (copasi2sbmlmap.size() == 0)\n {\n \/\/ this should not be happening, as this is used to verify the element.\n return \"\";\n }\n\n std::map<CCopasiObject*, SBase*>::const_iterator pos;\n\n if (type == \"Concentration\" || type == \"InitialConcentration\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfSpecies\/sbml:species[@id=\\'\";\n \/\/remove unwanted characters from the plot item object name\n removeCharactersFromString(displayName, \"[]\");\n\n if (type == \"InitialConcentration\")\n {\n displayName = displayName.substr(0, displayName.length() - 2);\n }\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_SPECIES, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n\n else if (type == \"Flux\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id=\\'\";\n splitStrings(displayName, ')', stringsContainer);\n displayName = stringsContainer[0];\n\n removeCharactersFromString(displayName, \"(\");\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Value\" || type == \"InitialValue\")\n {\n if (type == \"InitialValue\")\n {\n displayName = displayName.substr(0, displayName.find(\".InitialValue\"));\n }\n\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfParameters\/sbml:parameter[@id=\\'\";\n splitStrings(displayName, '[', stringsContainer);\n\n if (stringsContainer.size() == 1)\n {\n \/\/ not found ... might be a local parameter\n removeCharactersFromString(displayName, \"()\");\n splitStrings(displayName, '.', stringsContainer);\n\n if (stringsContainer.size() == 2)\n {\n sbmlId = stringsContainer[0] + \"_\" + stringsContainer[1];\n std::stringstream xpath;\n xpath << \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id=\\'\";\n xpath << stringsContainer[0];\n xpath << \"\\']\/sbml:kineticLaw\/sbml:listOfParameters\/sbml:parameter[@id=\\'\";\n xpath << stringsContainer[1];\n xpath << \"\\']\";\n return xpath.str();\n }\n }\n\n displayName = stringsContainer[1];\n\n removeCharactersFromString(displayName, \"]\");\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_PARAMETER , displayName);\n\n if (sbmlId.empty())\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_LOCAL_PARAMETER , displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Volume\" || type == \"InitialVolume\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfCompartments\/sbml:compartment[@id=\\'\";\n splitStrings(displayName, '[', stringsContainer);\n displayName = stringsContainer[1];\n\n if (type == \"InitialVolume\")\n {\n displayName = displayName.substr(0, displayName.find(\".InitialVolume\"));\n }\n\n if (type == \"Volume\")\n {\n displayName = displayName.substr(0, displayName.find(\".Volume\"));\n }\n\n removeCharactersFromString(displayName, \"]\");\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_COMPARTMENT, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Time\" || type == \"Initial Time\")\n return SEDML_TIME_URN;\n\n sbmlId = \"\";\n return targetXPathString;\n}\n\nconst CCopasiObject*\nSEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference)\n{\n \/\/ for now one variable only\n if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL;\n\n const SedVariable* var = dataReference->getVariable(0);\n\n if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN)\n {\n return static_cast<const CCopasiObject *>(model->getObject(CCopasiObjectName(\"Reference=Time\")));\n }\n\n return resolveXPath(model, var->getTarget());\n}\n\nstd::string\nSEDMLUtils::translateTargetXpathInSBMLId(const std::string &xpath, std::string& SBMLType)\n{\n std::vector<std::string> xpathStrings;\n std::string id, nextString;\n\n splitStrings(xpath, ':', xpathStrings);\n nextString = xpathStrings[xpathStrings.size() - 1];\n\n splitStrings(nextString, '[', xpathStrings);\n SBMLType = xpathStrings[0];\n nextString = xpathStrings[xpathStrings.size() - 1];\n\n splitStrings(nextString, '=', xpathStrings);\n nextString = xpathStrings[xpathStrings.size() - 1];\n splitStrings(nextString, ']', xpathStrings);\n id = xpathStrings[0];\n\n \/\/remove the remaining unwanted characters\n removeCharactersFromString(id, \"\\\"']\");\n return id;\n}\n\nconst CCopasiObject*\nSEDMLUtils::resolveXPath(const CModel *model, const std::string& xpath,\n bool initial \/* = false*\/)\n{\n std::string SBMLType;\n std::string id = translateTargetXpathInSBMLId(xpath, SBMLType);\n const CCopasiObject* result = getObjectForSbmlId(model, id, SBMLType, initial);\n\n if (result == NULL)\n {\n \/\/ old method fails here, possibly a local parameter\n size_t pos = xpath.find(\"\/sbml:kineticLaw\/sbml:listOfParameters\/\");\n\n if (pos != std::string::npos)\n {\n std::string reactionType;\n std::string reactionId = translateTargetXpathInSBMLId(xpath.substr(0, pos), reactionType);\n const CCopasiObject* flux = getObjectForSbmlId(model, reactionId, reactionType);\n\n if (flux != NULL)\n {\n const CCopasiObject* reactionObj = flux->getObjectParent();\n std::string cn = \"ParameterGroup=Parameters,Parameter=\" + id + \",Reference=Value\";\n return dynamic_cast<const CCopasiObject*>(reactionObj->getObject(cn));\n }\n }\n }\n\n return result;\n}\n\nstd::string&\nSEDMLUtils::removeCharactersFromString(std::string& str, const std::string& characters)\n{\n for (unsigned int ii = 0; ii < characters.length(); ++ii)\n {\n str.erase(std::remove(str.begin(), str.end(), characters[ii]), str.end());\n }\n\n return str;\n}\n\nstd::string\nSEDMLUtils::getXPathForObject(const CCopasiObject& object)\n{\n const std::string& type = object.getObjectName();\n const CCopasiDataModel* dm = object.getObjectDataModel();\n std::string yAxis = object.getObjectDisplayName();\n std::string targetXPathString = getXPathAndName(yAxis, type,\n dm->getModel(), *dm);\n return targetXPathString;\n}\n\nstd::string SEDMLUtils::getNextId(const std::string& base, int count)\n{\n std::stringstream str; str << base << count;\n return str.str();\n}\n\nint SEDMLUtils::processArchive(const std::string & archiveFile,\n std::string &fileName, std::string &fileContent)\n{\n\n int err = 0;\n \/*\n const char * cArchive = archiveFile.c_str();\n\n \/\/Open the ZIP archive\n zip *zip = zip_open(cArchive, 0, &err);\n\n \/\/Search for file using its given name\n const char *nameOfFile = fileName.c_str();\n struct zip_stat st;\n zip_stat_init(&st);\n zip_stat(zip, nameOfFile, 0, &st);\n\n \/\/Alloc memory for its uncompressed contents\n char *fileCont = new char[st.size];\n\n \/\/Read the compressed file\n zip_file *file = zip_fopen(zip, nameOfFile, 0);\n zip_fread(file, fileCont, st.size);\n\n std::ostringstream fileContentStream;\n size_t i, iMax = st.size;\n for(i = 0; i<iMax; ++i){\n fileContentStream << fileCont[i];\n }\n fileContent = fileContentStream.str();\n\n \/\/close the file and archive\n zip_fclose(file);\n zip_close(zip);\n *\/\n\n return err;\n}\n\n\/\/split: receives a char delimiter and string and a vector of strings that will contain the splited strings\n\/\/this is presently a hack to parse the XPath based target attribute in SEDML. A better solution may be\n\/\/necessary in the future.\n\nvoid\nSEDMLUtils::splitStrings(const std::string &xpath, char delim,\n std::vector<std::string> &xpathStrings)\n{\n std::string myPath = xpath;\n xpathStrings.clear();\n std::string next;\n\n \/\/ For each character in the string\n for (std::string::const_iterator it = xpath.begin(); it != xpath.end(); it++)\n {\n \/\/ check delimeter character\n if (*it == delim)\n {\n if (!next.empty())\n {\n \/\/ Add them to the xpathStrings vector\n xpathStrings.push_back(next);\n next.clear();\n }\n }\n else\n {\n next += *it;\n }\n }\n\n if (!next.empty())\n xpathStrings.push_back(next);\n}\n\nconst CCopasiObject *\nSEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial\/* = false*\/)\n{\n if (SBMLType == \"Time\")\n return static_cast<const CCopasiObject *>(pModel->getObject(CCopasiObjectName(\"Reference=Time\")));\n\n if (SBMLType == \"species\")\n {\n size_t iMet, imax = pModel->getMetabolites().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n \/\/ the importer should not need to change the initial concentration\n \/\/ pModel->getMetabolites()[iMet].setInitialConcentration(0.896901);\n\n if (pModel->getMetabolites()[iMet].getSBMLId() == id)\n {\n if (initial)\n return pModel->getMetabolites()[iMet].getInitialConcentrationReference();\n\n return pModel->getMetabolites()[iMet].getConcentrationReference();\n }\n }\n }\n else if (SBMLType == \"reaction\")\n {\n size_t iMet, imax = pModel->getReactions().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n if (pModel->getReactions()[iMet].getSBMLId() == id)\n {\n if (initial)\n return NULL;\n\n return pModel->getReactions()[iMet].getFluxReference();\n }\n }\n }\n else if (SBMLType == \"parameter\")\n {\n size_t iMet, imax = pModel->getModelValues().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n if (pModel->getModelValues()[iMet].getSBMLId() == id)\n {\n if (initial)\n return pModel->getModelValues()[iMet].getInitialValueReference();\n\n return pModel->getModelValues()[iMet].getValueReference();\n }\n }\n }\n\n else if (SBMLType == \"compartment\")\n {\n size_t iComp, imax = pModel->getCompartments().size();\n\n for (iComp = 0; iComp < imax; ++iComp)\n {\n if (pModel->getCompartments()[iComp].getSBMLId() == id)\n {\n if (initial)\n return pModel->getCompartments()[iComp].getInitialValueReference();\n\n return pModel->getCompartments()[iComp].getValueReference();\n }\n }\n }\n\n return NULL;\n}\n\n\/*void SEDMLUtils::resmoveUnwantedChars(std::string & str, char chars[]) {\n for (unsigned int i = 0; i < strlen(chars); ++i) {\n\n str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());\n }\n}\n *\/\nSEDMLUtils::SEDMLUtils()\n{\n \/\/ TODO Auto-generated constructor stub\n}\n\nSEDMLUtils::~SEDMLUtils()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n<commit_msg>- issue 2360: fix xpath generation for reactions<commit_after>\/\/ Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2013 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/*\n * SEDMLUtils.cpp\n *\n * Created on: 15 Jul 2013\n * Author: dada\n *\/\n\n\/\/#include <zip.h>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include \"SEDMLUtils.h\"\n\n#include <sedml\/SedTypes.h>\n#include <sbml\/SBMLTypes.h>\n\n#include <copasi\/model\/CModel.h>\n#include <copasi\/report\/CCopasiObject.h>\n#include <copasi\/CopasiDataModel\/CCopasiDataModel.h>\n\nstd::string SEDMLUtils::findIdByNameAndType(\n const std::map<const CCopasiObject*, SBase*>& map,\n int typeCode,\n const std::string& name)\n{\n std::map<const CCopasiObject*, SBase*>::const_iterator it = map.begin();\n\n std::string::size_type compartmentStart = name.find(\"{\");\n\n std::string compId = \"\";\n\n if (compartmentStart != std::string::npos)\n {\n std::string compName = name.substr(compartmentStart + 1, name.size() - compartmentStart - 2);\n SEDMLUtils::removeCharactersFromString(compName, \"\\\"\");\n\n compId = findIdByNameAndType(map, SBML_COMPARTMENT, compName);\n }\n\n while (it != map.end())\n {\n SBase* current = it->second;\n const CCopasiObject* object = it->first;\n std::string displayName = object->getObjectDisplayName();\n\n if (((current->getTypeCode() & typeCode) != typeCode))\n {\n ++it;\n continue;\n }\n\n if (current->getName() == name)\n return current->getId();\n\n if (typeCode == SBML_SPECIES && compartmentStart != std::string::npos)\n {\n if (displayName == name)\n {\n Species* species = (Species*)current;\n\n if (species->getCompartment() == compId)\n return species->getId();\n }\n }\n\n ++it;\n }\n\n return \"\";\n}\n\nstd::string\nSEDMLUtils::getXPathAndName(std::string& sbmlId,\n const std::string &type,\n const CModel *pModel,\n const CCopasiDataModel& dataModel)\n{\n std::vector<std::string> stringsContainer;\n std::string targetXPathString;\n const std::map<const CCopasiObject*, SBase*>& copasi2sbmlmap =\n const_cast<CCopasiDataModel&>(dataModel).getCopasi2SBMLMap();\n std::string displayName = sbmlId;\n\n if (copasi2sbmlmap.size() == 0)\n {\n \/\/ this should not be happening, as this is used to verify the element.\n return \"\";\n }\n\n std::map<CCopasiObject*, SBase*>::const_iterator pos;\n\n if (type == \"Concentration\" || type == \"InitialConcentration\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfSpecies\/sbml:species[@id=\\'\";\n \/\/remove unwanted characters from the plot item object name\n removeCharactersFromString(displayName, \"[]\");\n\n if (type == \"InitialConcentration\")\n {\n displayName = displayName.substr(0, displayName.length() - 2);\n }\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_SPECIES, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n\n else if (type == \"Flux\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id=\\'\";\n\n std::string::size_type pos = displayName.rfind(\".Flux\");\n displayName = displayName.substr(1, pos - 2);\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Value\" || type == \"InitialValue\")\n {\n if (type == \"InitialValue\")\n {\n displayName = displayName.substr(0, displayName.find(\".InitialValue\"));\n }\n\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfParameters\/sbml:parameter[@id=\\'\";\n splitStrings(displayName, '[', stringsContainer);\n\n if (stringsContainer.size() == 1)\n {\n \/\/ not found ... might be a local parameter\n removeCharactersFromString(displayName, \"()\");\n splitStrings(displayName, '.', stringsContainer);\n\n if (stringsContainer.size() == 2)\n {\n sbmlId = stringsContainer[0] + \"_\" + stringsContainer[1];\n std::stringstream xpath;\n xpath << \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id=\\'\";\n xpath << stringsContainer[0];\n xpath << \"\\']\/sbml:kineticLaw\/sbml:listOfParameters\/sbml:parameter[@id=\\'\";\n xpath << stringsContainer[1];\n xpath << \"\\']\";\n return xpath.str();\n }\n }\n\n displayName = stringsContainer[1];\n\n removeCharactersFromString(displayName, \"]\");\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_PARAMETER , displayName);\n\n if (sbmlId.empty())\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_LOCAL_PARAMETER , displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Volume\" || type == \"InitialVolume\")\n {\n targetXPathString = \"\/sbml:sbml\/sbml:model\/sbml:listOfCompartments\/sbml:compartment[@id=\\'\";\n splitStrings(displayName, '[', stringsContainer);\n displayName = stringsContainer[1];\n\n if (type == \"InitialVolume\")\n {\n displayName = displayName.substr(0, displayName.find(\".InitialVolume\"));\n }\n\n if (type == \"Volume\")\n {\n displayName = displayName.substr(0, displayName.find(\".Volume\"));\n }\n\n removeCharactersFromString(displayName, \"]\");\n\n sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_COMPARTMENT, displayName);\n\n if (!sbmlId.empty())\n {\n return targetXPathString + sbmlId + \"\\']\";\n }\n else\n return \"\";\n }\n else if (type == \"Time\" || type == \"Initial Time\")\n return SEDML_TIME_URN;\n\n sbmlId = \"\";\n return targetXPathString;\n}\n\nconst CCopasiObject*\nSEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference)\n{\n \/\/ for now one variable only\n if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL;\n\n const SedVariable* var = dataReference->getVariable(0);\n\n if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN)\n {\n return static_cast<const CCopasiObject *>(model->getObject(CCopasiObjectName(\"Reference=Time\")));\n }\n\n return resolveXPath(model, var->getTarget());\n}\n\nstd::string\nSEDMLUtils::translateTargetXpathInSBMLId(const std::string &xpath, std::string& SBMLType)\n{\n std::vector<std::string> xpathStrings;\n std::string id, nextString;\n\n splitStrings(xpath, ':', xpathStrings);\n nextString = xpathStrings[xpathStrings.size() - 1];\n\n splitStrings(nextString, '[', xpathStrings);\n SBMLType = xpathStrings[0];\n nextString = xpathStrings[xpathStrings.size() - 1];\n\n splitStrings(nextString, '=', xpathStrings);\n nextString = xpathStrings[xpathStrings.size() - 1];\n splitStrings(nextString, ']', xpathStrings);\n id = xpathStrings[0];\n\n \/\/remove the remaining unwanted characters\n removeCharactersFromString(id, \"\\\"']\");\n return id;\n}\n\nconst CCopasiObject*\nSEDMLUtils::resolveXPath(const CModel *model, const std::string& xpath,\n bool initial \/* = false*\/)\n{\n std::string SBMLType;\n std::string id = translateTargetXpathInSBMLId(xpath, SBMLType);\n const CCopasiObject* result = getObjectForSbmlId(model, id, SBMLType, initial);\n\n if (result == NULL)\n {\n \/\/ old method fails here, possibly a local parameter\n size_t pos = xpath.find(\"\/sbml:kineticLaw\/sbml:listOfParameters\/\");\n\n if (pos != std::string::npos)\n {\n std::string reactionType;\n std::string reactionId = translateTargetXpathInSBMLId(xpath.substr(0, pos), reactionType);\n const CCopasiObject* flux = getObjectForSbmlId(model, reactionId, reactionType);\n\n if (flux != NULL)\n {\n const CCopasiObject* reactionObj = flux->getObjectParent();\n std::string cn = \"ParameterGroup=Parameters,Parameter=\" + id + \",Reference=Value\";\n return dynamic_cast<const CCopasiObject*>(reactionObj->getObject(cn));\n }\n }\n }\n\n return result;\n}\n\nstd::string&\nSEDMLUtils::removeCharactersFromString(std::string& str, const std::string& characters)\n{\n for (unsigned int ii = 0; ii < characters.length(); ++ii)\n {\n str.erase(std::remove(str.begin(), str.end(), characters[ii]), str.end());\n }\n\n return str;\n}\n\nstd::string\nSEDMLUtils::getXPathForObject(const CCopasiObject& object)\n{\n const std::string& type = object.getObjectName();\n const CCopasiDataModel* dm = object.getObjectDataModel();\n std::string yAxis = object.getObjectDisplayName();\n std::string targetXPathString = getXPathAndName(yAxis, type,\n dm->getModel(), *dm);\n return targetXPathString;\n}\n\nstd::string SEDMLUtils::getNextId(const std::string& base, int count)\n{\n std::stringstream str; str << base << count;\n return str.str();\n}\n\nint SEDMLUtils::processArchive(const std::string & archiveFile,\n std::string &fileName, std::string &fileContent)\n{\n\n int err = 0;\n \/*\n const char * cArchive = archiveFile.c_str();\n\n \/\/Open the ZIP archive\n zip *zip = zip_open(cArchive, 0, &err);\n\n \/\/Search for file using its given name\n const char *nameOfFile = fileName.c_str();\n struct zip_stat st;\n zip_stat_init(&st);\n zip_stat(zip, nameOfFile, 0, &st);\n\n \/\/Alloc memory for its uncompressed contents\n char *fileCont = new char[st.size];\n\n \/\/Read the compressed file\n zip_file *file = zip_fopen(zip, nameOfFile, 0);\n zip_fread(file, fileCont, st.size);\n\n std::ostringstream fileContentStream;\n size_t i, iMax = st.size;\n for(i = 0; i<iMax; ++i){\n fileContentStream << fileCont[i];\n }\n fileContent = fileContentStream.str();\n\n \/\/close the file and archive\n zip_fclose(file);\n zip_close(zip);\n *\/\n\n return err;\n}\n\n\/\/split: receives a char delimiter and string and a vector of strings that will contain the splited strings\n\/\/this is presently a hack to parse the XPath based target attribute in SEDML. A better solution may be\n\/\/necessary in the future.\n\nvoid\nSEDMLUtils::splitStrings(const std::string &xpath, char delim,\n std::vector<std::string> &xpathStrings)\n{\n std::string myPath = xpath;\n xpathStrings.clear();\n std::string next;\n\n \/\/ For each character in the string\n for (std::string::const_iterator it = xpath.begin(); it != xpath.end(); it++)\n {\n \/\/ check delimeter character\n if (*it == delim)\n {\n if (!next.empty())\n {\n \/\/ Add them to the xpathStrings vector\n xpathStrings.push_back(next);\n next.clear();\n }\n }\n else\n {\n next += *it;\n }\n }\n\n if (!next.empty())\n xpathStrings.push_back(next);\n}\n\nconst CCopasiObject *\nSEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial\/* = false*\/)\n{\n if (SBMLType == \"Time\")\n return static_cast<const CCopasiObject *>(pModel->getObject(CCopasiObjectName(\"Reference=Time\")));\n\n if (SBMLType == \"species\")\n {\n size_t iMet, imax = pModel->getMetabolites().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n \/\/ the importer should not need to change the initial concentration\n \/\/ pModel->getMetabolites()[iMet].setInitialConcentration(0.896901);\n\n if (pModel->getMetabolites()[iMet].getSBMLId() == id)\n {\n if (initial)\n return pModel->getMetabolites()[iMet].getInitialConcentrationReference();\n\n return pModel->getMetabolites()[iMet].getConcentrationReference();\n }\n }\n }\n else if (SBMLType == \"reaction\")\n {\n size_t iMet, imax = pModel->getReactions().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n if (pModel->getReactions()[iMet].getSBMLId() == id)\n {\n if (initial)\n return NULL;\n\n return pModel->getReactions()[iMet].getFluxReference();\n }\n }\n }\n else if (SBMLType == \"parameter\")\n {\n size_t iMet, imax = pModel->getModelValues().size();\n\n for (iMet = 0; iMet < imax; ++iMet)\n {\n if (pModel->getModelValues()[iMet].getSBMLId() == id)\n {\n if (initial)\n return pModel->getModelValues()[iMet].getInitialValueReference();\n\n return pModel->getModelValues()[iMet].getValueReference();\n }\n }\n }\n\n else if (SBMLType == \"compartment\")\n {\n size_t iComp, imax = pModel->getCompartments().size();\n\n for (iComp = 0; iComp < imax; ++iComp)\n {\n if (pModel->getCompartments()[iComp].getSBMLId() == id)\n {\n if (initial)\n return pModel->getCompartments()[iComp].getInitialValueReference();\n\n return pModel->getCompartments()[iComp].getValueReference();\n }\n }\n }\n\n return NULL;\n}\n\n\/*void SEDMLUtils::resmoveUnwantedChars(std::string & str, char chars[]) {\n for (unsigned int i = 0; i < strlen(chars); ++i) {\n\n str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());\n }\n}\n *\/\nSEDMLUtils::SEDMLUtils()\n{\n \/\/ TODO Auto-generated constructor stub\n}\n\nSEDMLUtils::~SEDMLUtils()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * \n * Last modified: July 20 2015\n * By: Edgar Perez Lezama <eperezle@cern.ch>, GSI-Darmstadt\n * \n * \n *\/\n\n\n\n\nvoid AddTask_eperezl_dNdPtpp_TPCITS()\n{\n\/*\nCheckLoadLibrary(\"libPWG0base\");\nCheckLoadLibrary(\"libPWG0dep\");\nCheckLoadLibrary(\"libPWG0selectors\");\n*\/\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n if (!mgr) {\n Error(\"AddTask_dNdPtAnalysis_TPCITS\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/ Switch off all AliInfo (too much output!!!)\n AliLog::SetGlobalLogLevel(AliLog::kError);\n mgr->SetDebugLevel(0);\n\n \/\/\n \/\/ Create physics trigger selection class\n \/\/\n \/\/AliPhysicsSelection *physTrigSel = new AliPhysicsSelection();\n \/\/physTrigSel->AddBackgroundIdentification(new AliBackgroundSelection());\n\n \/\/\n \/\/ Create event cuts\n \/\/\n Float_t zvWindow =10. ;\n\n AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts(\"AlidNdPtEventCuts\",\"Event cuts\");\n evtCuts->SetZvRange(-zvWindow,zvWindow);\n evtCuts->SetMeanXYZv(0.0,0.0,0.0);\n evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);\n evtCuts->SetTriggerRequired(kTRUE);\n\n \/\/\n \/\/ Create geom. acceptance cuts\n \/\/\n Float_t etaWindow = 1.0 ;\n Float_t ptMin = 0.10;\n\n AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts(\"AlidNdPtAcceptanceCuts\",\"Geom. acceptance cuts\");\n accCuts->SetEtaRange(-etaWindow,etaWindow);\n accCuts->SetPtRange(ptMin,1.e10);\n\n \/\/\n \/\/ Create standard esd track cuts\n \/\/\n Int_t cutMode = 222;\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/SPECTRA\/ChargedHadrons\/dNdPt\/macros\/CreatedNdPtTrackCuts.C\");\n AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);\n if (!esdTrackCuts) {\n printf(\"ERROR: esdTrackCuts could not be created\\n\");\n return;\n } else {\n \/\/esdTrackCuts->SetHistogramsOn(kTRUE);\n esdTrackCuts->SetHistogramsOn(kTRUE);\n }\n\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);\n\n \/\/\n \/\/ Create task\n \/\/\n AlidNdPtTask *task = new AlidNdPtTask(\"AlidNdPtTask_TPCITS\"); \n task->SetUseMCInfo(hasMC);\n\n \/\/ trigger \n task->SelectCollisionCandidates(AliVEvent::kMB); \n\n\n \/\/\n \/\/ set analysis options from the Helper here !!!\n \/\/\n\n \/\/AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;\n AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;\n AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;\n\n \/\/\n \/\/ Create analysis object\n \/\/\n\n AlidNdPtAnalysis *fdNdPtAnalysis = new AlidNdPtAnalysis(\"dNdPtAnalysis\",\"dN\/dPt Analysis with TPC-ITS tracking\");\n fdNdPtAnalysis->SetEventCuts(evtCuts);\n fdNdPtAnalysis->SetAcceptanceCuts(accCuts);\n fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);\n \/\/fdNdPtAnalysis->SetBackgroundCuts(backCuts);\n fdNdPtAnalysis->SetAnalysisMode(analysisMode); \n fdNdPtAnalysis->SetParticleMode(particleMode); \n \/\/fdNdPtAnalysis->SetTrigger(trigger);\n fdNdPtAnalysis->SetTriggerMask(AliVEvent::kMB);\n \/\/fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1); \n if(hasMC) \n {\n \/\/physTrigSel->SetAnalyzeMC();\n \/\/fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel); \n fdNdPtAnalysis->SetUseMCInfo(kTRUE);\n fdNdPtAnalysis->SetHistogramsOn(kTRUE);\n \/\/fdNdPtAnalysis->SetHistogramsOn(kFALSE);\n }\n else { \/\/ online trigger\n\/\/ physTrigSel->SetUseBXNumbers();\n\/\/ physTrigSel->SetComputeBG();\n\/\/ fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel); \n }\n \n \/\/ change binning\n Int_t multNbins = 252; \n Double_t binsMult[253];\n for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }\n binsMult[252] = 1000.;\n \/\/ change binning\n const Int_t ptNbins = 81;\n Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};\n Double_t* binsPt = new Double_t[82];\n for (int i=0; i<82; i++) {binsPt[i] = bins[i];}\n fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);\n fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt); \n fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);\n \n \/\/ for mean pt use tpc tracks as mult. estimator\n AlidNdPtAcceptanceCuts *multAccCuts = new AlidNdPtAcceptanceCuts(\"MultaccCuts\",\"Geom. acceptance cuts\");\n multAccCuts->SetEtaRange(-0.3,0.3);\n multAccCuts->SetPtRange(0.0,1.e10); \n AliESDtrackCuts* multTrackCuts = CreatedNdPtTrackCuts(222);\n fdNdPtAnalysis->SetMultAcceptanceCuts(multAccCuts);\n fdNdPtAnalysis->SetMultTrackCuts(multTrackCuts); \n \n\n \/\/ Add analysis object\n task->AddAnalysisObject( fdNdPtAnalysis );\n\t\n \/\/ Add task\n mgr->AddTask(task);\n\n \/\/ Create containers for input\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n mgr->ConnectInput(task, 0, cinput);\n\n AliAnalysisDataContainer *coutput = mgr->CreateContainer(\"eperezl_dNdPtpp_TPCITS\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n Form(\"%s:dNdPtHistos\", mgr->GetCommonFileName())); \n\n\n mgr->ConnectOutput(task, 1, coutput);\n\n}\n\n<commit_msg>update of AddTask for Edgar<commit_after>\/*\n * \n * Last modified: July 20 2015\n * By: Edgar Perez Lezama <eperezle@cern.ch>, GSI-Darmstadt\n * \n * \n *\/\n\n\n\n\nvoid AddTask_eperezl_dNdPtpp_TPCITS()\n{\n\/*\nCheckLoadLibrary(\"libPWG0base\");\nCheckLoadLibrary(\"libPWG0dep\");\nCheckLoadLibrary(\"libPWG0selectors\");\n*\/\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n if (!mgr) {\n Error(\"AddTask_dNdPtAnalysis_TPCITS\", \"No analysis manager found.\");\n return 0;\n }\n\n \/\/ Switch off all AliInfo (too much output!!!)\n AliLog::SetGlobalLogLevel(AliLog::kError);\n mgr->SetDebugLevel(0);\n\n \/\/\n \/\/ Create physics trigger selection class\n \/\/\n \/\/AliPhysicsSelection *physTrigSel = new AliPhysicsSelection();\n \/\/physTrigSel->AddBackgroundIdentification(new AliBackgroundSelection());\n\n \/\/\n \/\/ Create event cuts\n \/\/\n Float_t zvWindow =30. ;\n\n AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts(\"AlidNdPtEventCuts\",\"Event cuts\");\n evtCuts->SetZvRange(-zvWindow,zvWindow);\n evtCuts->SetMeanXYZv(0.0,0.0,0.0);\n evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);\n evtCuts->SetTriggerRequired(kTRUE);\n\n \/\/\n \/\/ Create geom. acceptance cuts\n \/\/\n Float_t etaWindow = 1.0 ;\n Float_t ptMin = 0.10;\n\n AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts(\"AlidNdPtAcceptanceCuts\",\"Geom. acceptance cuts\");\n accCuts->SetEtaRange(-etaWindow,etaWindow);\n accCuts->SetPtRange(ptMin,1.e10);\n\n \/\/\n \/\/ Create standard esd track cuts\n \/\/\n Int_t cutMode = 222;\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/SPECTRA\/ChargedHadrons\/dNdPt\/macros\/CreatedNdPtTrackCuts.C\");\n AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);\n if (!esdTrackCuts) {\n printf(\"ERROR: esdTrackCuts could not be created\\n\");\n return;\n } else {\n \/\/esdTrackCuts->SetHistogramsOn(kTRUE);\n esdTrackCuts->SetHistogramsOn(kTRUE);\n }\n\n Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);\n\n \/\/\n \/\/ Create task\n \/\/\n AlidNdPtTask *task = new AlidNdPtTask(\"AlidNdPtTask_TPCITS\"); \n task->SetUseMCInfo(hasMC);\n\n \/\/ trigger \n task->SelectCollisionCandidates(AliVEvent::kMB); \n\n\n \/\/\n \/\/ set analysis options from the Helper here !!!\n \/\/\n\n \/\/AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;\n AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;\n AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;\n\n \/\/\n \/\/ Create analysis object\n \/\/\n\n AlidNdPtAnalysis *fdNdPtAnalysis = new AlidNdPtAnalysis(\"dNdPtAnalysis\",\"dN\/dPt Analysis with TPC-ITS tracking\");\n fdNdPtAnalysis->SetEventCuts(evtCuts);\n fdNdPtAnalysis->SetAcceptanceCuts(accCuts);\n fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);\n \/\/fdNdPtAnalysis->SetBackgroundCuts(backCuts);\n fdNdPtAnalysis->SetAnalysisMode(analysisMode); \n fdNdPtAnalysis->SetParticleMode(particleMode); \n \/\/fdNdPtAnalysis->SetTrigger(trigger);\n fdNdPtAnalysis->SetTriggerMask(AliVEvent::kMB);\n \/\/fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1); \n if(hasMC) \n {\n \/\/physTrigSel->SetAnalyzeMC();\n \/\/fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel); \n fdNdPtAnalysis->SetUseMCInfo(kTRUE);\n fdNdPtAnalysis->SetHistogramsOn(kTRUE);\n \/\/fdNdPtAnalysis->SetHistogramsOn(kFALSE);\n }\n else { \/\/ online trigger\n\/\/ physTrigSel->SetUseBXNumbers();\n\/\/ physTrigSel->SetComputeBG();\n\/\/ fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel); \n }\n \n \/\/ change binning\n Int_t multNbins = 252; \n Double_t binsMult[253];\n for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }\n binsMult[252] = 1000.;\n \/\/ change binning\n const Int_t ptNbins = 81;\n Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};\n Double_t* binsPt = new Double_t[82];\n for (int i=0; i<82; i++) {binsPt[i] = bins[i];}\n fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);\n fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt); \n fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);\n \n \/\/ for mean pt use tpc tracks as mult. estimator\n AlidNdPtAcceptanceCuts *multAccCuts = new AlidNdPtAcceptanceCuts(\"MultaccCuts\",\"Geom. acceptance cuts\");\n multAccCuts->SetEtaRange(-0.3,0.3);\n multAccCuts->SetPtRange(0.0,1.e10); \n AliESDtrackCuts* multTrackCuts = CreatedNdPtTrackCuts(222);\n fdNdPtAnalysis->SetMultAcceptanceCuts(multAccCuts);\n fdNdPtAnalysis->SetMultTrackCuts(multTrackCuts); \n \n\n \/\/ Add analysis object\n task->AddAnalysisObject( fdNdPtAnalysis );\n\t\n \/\/ Add task\n mgr->AddTask(task);\n\n \/\/ Create containers for input\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n mgr->ConnectInput(task, 0, cinput);\n\n AliAnalysisDataContainer *coutput = mgr->CreateContainer(\"eperezl_dNdPtpp_TPCITS\",\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n Form(\"%s:dNdPtHistos\", mgr->GetCommonFileName())); \n\n\n mgr->ConnectOutput(task, 1, coutput);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Library names have changed thanks to the \"layer\" changes<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#ifndef PEGTL_PARSE_HH\n#define PEGTL_PARSE_HH\n\n#include <string>\n#include <cstring>\n#include <sstream>\n\n#include \"normal.hh\"\n#include \"nothing.hh\"\n#include \"apply_mode.hh\"\n#include \"memory_input.hh\"\n#include \"buffer_input.hh\"\n\n#include \"internal\/cstream_reader.hh\"\n#include \"internal\/cstring_reader.hh\"\n#include \"internal\/istream_reader.hh\"\n\nnamespace pegtl\n{\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Input, typename ... States >\n bool parse_input( Input & in, States && ... st )\n {\n return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_arg( const int argn, char ** argv, States && ... st )\n {\n std::ostringstream os;\n os << \"argv[\" << argn << ']';\n const std::string source = os.str();\n memory_input in( 1, 0, argv[ argn ], argv[ argn ] + ::strlen( argv[ argn ] ), source.c_str() );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_memory( const char * data, const char * dend, const char * source, States && ... st )\n {\n memory_input in( 1, 0, data, dend, source );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_memory( const char * data, const std::size_t size, const char * source, States && ... st )\n {\n return parse_memory< Rule, Action, Control >( data, data + size, source, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_string( const std::string & data, const std::string & source, States && ... st )\n {\n return parse_memory< Rule, Action, Control >( data.data(), data.data() + data.size(), source.c_str(), st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_cstream( std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstream_reader > in( source, maximum, stream );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_stdin( const std::size_t maximum, States && ... st )\n {\n return parse_cstream< Rule, Action, Control >( stdin, \"stdin\", maximum, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_cstring( const char * string, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstring_reader > in( source, maximum, string );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_istream( std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename Input, typename ... States >\n bool parse_input_nested( const Outer & oi, Input & in, States && ... st )\n {\n try {\n return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );\n }\n catch ( parse_error & e ) {\n e.positions.push_back( position_info( oi ) );\n throw;\n }\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_memory_nested( const Outer & oi, const char * data, const char * dend, const char * source, States && ... st )\n {\n memory_input in( 1, 0, data, dend, source );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_memory_nested( const Outer & oi, const char * data, const std::size_t size, const char * source, States && ... st )\n {\n return parse_memory_nested< Rule, Action, Control >( oi, data, data + size, source, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_string_nested( const Outer & oi, const std::string & data, const std::string & source, States && ... st )\n {\n return parse_memory_nested< Rule, Action, Control >( oi, data.data(), data.data() + data.size(), source.c_str(), st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_cstream_nested( const Outer & oi, std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstream_reader > in( source, maximum, stream );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_cstring_nested( const Outer & oi, const char * string, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstring_reader > in( source, maximum, string );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_istream( const Outer & oi, std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n} \/\/ pegtl\n\n#endif\n<commit_msg>Add assert() to assist clang-tidy<commit_after>\/\/ Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#ifndef PEGTL_PARSE_HH\n#define PEGTL_PARSE_HH\n\n#include <string>\n#include <cstring>\n#include <sstream>\n\n#include \"normal.hh\"\n#include \"nothing.hh\"\n#include \"apply_mode.hh\"\n#include \"memory_input.hh\"\n#include \"buffer_input.hh\"\n\n#include \"internal\/cstream_reader.hh\"\n#include \"internal\/cstring_reader.hh\"\n#include \"internal\/istream_reader.hh\"\n\nnamespace pegtl\n{\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Input, typename ... States >\n bool parse_input( Input & in, States && ... st )\n {\n return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_arg( const int argn, char ** argv, States && ... st )\n {\n std::ostringstream os;\n os << \"argv[\" << argn << ']';\n const std::string source = os.str();\n assert( argv[ argn ] );\n memory_input in( 1, 0, argv[ argn ], argv[ argn ] + std::strlen( argv[ argn ] ), source.c_str() );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_memory( const char * data, const char * dend, const char * source, States && ... st )\n {\n memory_input in( 1, 0, data, dend, source );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_memory( const char * data, const std::size_t size, const char * source, States && ... st )\n {\n return parse_memory< Rule, Action, Control >( data, data + size, source, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_string( const std::string & data, const std::string & source, States && ... st )\n {\n return parse_memory< Rule, Action, Control >( data.data(), data.data() + data.size(), source.c_str(), st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_cstream( std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstream_reader > in( source, maximum, stream );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_stdin( const std::size_t maximum, States && ... st )\n {\n return parse_cstream< Rule, Action, Control >( stdin, \"stdin\", maximum, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_cstring( const char * string, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstring_reader > in( source, maximum, string );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >\n bool parse_istream( std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );\n return parse_input< Rule, Action, Control >( in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename Input, typename ... States >\n bool parse_input_nested( const Outer & oi, Input & in, States && ... st )\n {\n try {\n return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );\n }\n catch ( parse_error & e ) {\n e.positions.push_back( position_info( oi ) );\n throw;\n }\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_memory_nested( const Outer & oi, const char * data, const char * dend, const char * source, States && ... st )\n {\n memory_input in( 1, 0, data, dend, source );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_memory_nested( const Outer & oi, const char * data, const std::size_t size, const char * source, States && ... st )\n {\n return parse_memory_nested< Rule, Action, Control >( oi, data, data + size, source, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_string_nested( const Outer & oi, const std::string & data, const std::string & source, States && ... st )\n {\n return parse_memory_nested< Rule, Action, Control >( oi, data.data(), data.data() + data.size(), source.c_str(), st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_cstream_nested( const Outer & oi, std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstream_reader > in( source, maximum, stream );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_cstring_nested( const Outer & oi, const char * string, const char * source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::cstring_reader > in( source, maximum, string );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >\n bool parse_istream( const Outer & oi, std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )\n {\n buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );\n return parse_input_nested< Rule, Action, Control >( oi, in, st ... );\n }\n\n} \/\/ pegtl\n\n#endif\n<|endoftext|>"} {"text":"<commit_before> \/**\n * \\file main.cc\n * \\brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted\n * \\author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars\n * \\copyright Copyright (c) 2017, The R2D2 Team\n * \\license See LICENSE\n *\/\n\n\n#include \"mysql.hh\"\n#include \"mfrc522.hh\"\n#include \"led-controller.hh\"\n#include \"matrix-keypad.hh\"\n#include \"config-file-parser.hh\"\n#include \"databasemanager.hh\"\n\n#include <wiringPi.h>\n#include <wiringPiSPI.h>\n\n#include <iostream>\n\nstruct MFAuthentData {\n uint8_t command_code;\n uint8_t blockAddress;\n uint8_t sectorKey[5];\n uint8_t serialNumber[4];\n};\n\nint main(int argc, char **argv) {\n#define USING_PIN \/\/ Comment out this rule if not using a pincode on your application\n try {\n\n std::string ip;\n std::string username;\n std::string password;\n\n \/\/int encryptionKey;\n\n ConfigFileParser factory(\"database-config.txt\");\n factory.loadDatabaseSettings(ip, username, password);\n\n MySql connection;\n\n connection.connectTo(ip, username, password);\n connection.selectDatabase(\"R2D2\");\n\n std::cout << \"Made connection to the database\\n\";\n wiringPiSetup();\n wiringPiSPISetup(0, 10000000);\/\/max speed for mfrc522 is 10Mhz\n MFRC522 rfid;\n rfid.PCD_Init();\n\n \/\/Keypad pinSetup\n const int keypadRow[] = {15, 16, 1, 4};\n const int keypadColumn[] = {8, 9, 7, 2};\n\n \/\/Keypad objects\n MatrixKeypad keypad(keypadRow, keypadColumn, 4);\n\n LedController led(0);\nstd::cerr<<\"lukkie\" ;\n while (true) {\n delay(1000);\n std::cout << \"\\n\\nWaiting for rfid tag: \\n\";\n\n if(!rfid.PICC_IsNewCardPresent())\n continue;\n \n if(!rfid.PICC_ReadCardSerial())\n continue;\n std::cerr<<\"rickaerdotje\" ;\n \n \/\/ Hier moet het database gedeelte komen om te checken of je ID al in de database staat\n\n\n#ifdef USING_PIN\n MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\n if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))\n continue;\n \/\/read pincode\n std::string id;\n for(byte i = 0; i < rfid.uid.size; ++i){\n std::cerr <<\"0\";\n if(rfid.uid.uidByte[i] < 0x10){\n id +=(char)rfid.uid.uidByte[i];\n std::cerr<<\"1\" ;\n }\n else{\n id += (char)rfid.uid.uidByte[i];\n std::cerr<<\"2\" ;\n }\n }\n std::cerr<<\"philips \" ;\n DatabaseManager information;\n information.connectTo(ip,username,password);\n information.selectDatabase(\"R2D2\");\n if ( information.isCardInDatabase(id)){\n std::cout << \" id in database\";\n }\n \n\n\n byte bufferSize = (byte)18;\n byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);\n std::cout << \"Readarray contains: \\n\";\n for (int i = 0; i < 18; i++){\n std::cout <<(int)readArray[i] << '\\n';\n } \n\n \/\/pincode invoeren\n std::cout << \"Input PIN and finish with #\\n\";\n std::string value = keypad.getString();\n\n \/\/ write pincode\n\t \tbyte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n\t\t int index = 0;\n for(auto c :value){\n if (c >47 && c < 58 ){\n int number = c - 48;\n writeArray[index++] = (byte)number;\n\t\t }\n\t }\n rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);\n for (int i = 0; i < 16; i++){\n std::cout <<(int)writeArray[i] << '\\n';\n } \n \n#endif\n\n rfid.PCD_StopCrypto1();\n\n for(byte i = 0; i < rfid.uid.size; ++i){\n if(rfid.uid.uidByte[i] < 0x10){\n printf(\" 0\");\n printf(\"%X\",rfid.uid.uidByte[i]);\n }\n else{\n printf(\" \");\n printf(\"%X\", rfid.uid.uidByte[i]);\n }\n }\n\n connection.executeQuery(\"SELECT * FROM RFID\");\n\n\/\/ std::cout << \"Database information: \"\n\/\/ << database.getAllCardIdFromDatabase()\n\/\/ << '\\n';\n\n led.blinkLed(1000);\n }\n } catch (const std::string &error) {\n std::cerr << error << '\\n';\n exit(EXIT_FAILURE);\n } catch (...) {\n std::cerr << \"Something went wrong\\n\";\n exit(EXIT_FAILURE);\n }\n return 0;\n}\n\n<commit_msg> [RFID-03] debuging database<commit_after> \/**\n * \\file main.cc\n * \\brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted\n * \\author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars\n * \\copyright Copyright (c) 2017, The R2D2 Team\n * \\license See LICENSE\n *\/\n\n\n#include \"mysql.hh\"\n#include \"mfrc522.hh\"\n#include \"led-controller.hh\"\n#include \"matrix-keypad.hh\"\n#include \"config-file-parser.hh\"\n#include \"databasemanager.hh\"\n\n#include <wiringPi.h>\n#include <wiringPiSPI.h>\n\n#include <iostream>\n\nstruct MFAuthentData {\n uint8_t command_code;\n uint8_t blockAddress;\n uint8_t sectorKey[5];\n uint8_t serialNumber[4];\n};\n\nint main(int argc, char **argv) {\n#define USING_PIN \/\/ Comment out this rule if not using a pincode on your application\n try {\n\n std::string ip;\n std::string username;\n std::string password;\n\n \/\/int encryptionKey;\n\n ConfigFileParser factory(\"database-config.txt\");\n factory.loadDatabaseSettings(ip, username, password);\n\n MySql connection;\n\n connection.connectTo(ip, username, password);\n connection.selectDatabase(\"R2D2\");\n\n std::cout << \"Made connection to the database\\n\";\n wiringPiSetup();\n wiringPiSPISetup(0, 10000000);\/\/max speed for mfrc522 is 10Mhz\n MFRC522 rfid;\n rfid.PCD_Init();\n\n \/\/Keypad pinSetup\n const int keypadRow[] = {15, 16, 1, 4};\n const int keypadColumn[] = {8, 9, 7, 2};\n\n \/\/Keypad objects\n MatrixKeypad keypad(keypadRow, keypadColumn, 4);\n\n LedController led(0);\n DatabaseManager information;\n information.connectTo(ip,username,password);\n information.selectDatabase(\"R2D2\");\n while (true) {\n delay(1000);\n std::cout << \"\\n\\nWaiting for rfid tag: \\n\";\n\n if(!rfid.PICC_IsNewCardPresent())\n continue;\n \n if(!rfid.PICC_ReadCardSerial())\n continue;\n\n \n \/\/ Hier moet het database gedeelte komen om te checken of je ID al in de database staat\n std::string id;\n for(byte i = 0; i < rfid.uid.size; ++i){\n\n if(rfid.uid.uidByte[i] < 0x10){\n id +=(char)rfid.uid.uidByte[i];\n\n }\n else{\n id += (char)rfid.uid.uidByte[i];\n\n }\n }\n if ( information.isCardInDatabase(id)){\n std::cout << \" id in database\";\n }\n\n#ifdef USING_PIN\n MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\n if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))\n continue;\n \/\/read pincode\n\n \n\n\n byte bufferSize = (byte)18;\n byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);\n std::cout << \"Readarray contains: \\n\";\n for (int i = 0; i < 18; i++){\n std::cout <<(int)readArray[i] << '\\n';\n } \n\n \/\/pincode invoeren\n std::cout << \"Input PIN and finish with #\\n\";\n std::string value = keypad.getString();\n\n \/\/ write pincode\n\t \tbyte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n\t\t int index = 0;\n for(auto c :value){\n if (c >47 && c < 58 ){\n int number = c - 48;\n writeArray[index++] = (byte)number;\n\t\t }\n\t }\n rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);\n for (int i = 0; i < 16; i++){\n std::cout <<(int)writeArray[i] << '\\n';\n } \n \n#endif\n\n rfid.PCD_StopCrypto1();\n\n for(byte i = 0; i < rfid.uid.size; ++i){\n if(rfid.uid.uidByte[i] < 0x10){\n printf(\" 0\");\n printf(\"%X\",rfid.uid.uidByte[i]);\n }\n else{\n printf(\" \");\n printf(\"%X\", rfid.uid.uidByte[i]);\n }\n }\n\n connection.executeQuery(\"SELECT * FROM RFID\");\n\n\/\/ std::cout << \"Database information: \"\n\/\/ << database.getAllCardIdFromDatabase()\n\/\/ << '\\n';\n\n led.blinkLed(1000);\n }\n } catch (const std::string &error) {\n std::cerr << error << '\\n';\n exit(EXIT_FAILURE);\n } catch (...) {\n std::cerr << \"Something went wrong\\n\";\n exit(EXIT_FAILURE);\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ RefCount.hh for FbTk - Fluxbox Toolkit\n\/\/ Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n#ifndef FBTK_REFCOUNT_HH\n#define FBTK_REFCOUNT_HH\n\nnamespace FbTk {\n\n\/\/\/ holds a pointer with reference counting, similar to std:auto_ptr\ntemplate <typename Pointer>\nclass RefCount {\npublic:\n RefCount();\n explicit RefCount(Pointer *p);\n explicit RefCount(RefCount<Pointer> ©);\n explicit RefCount(const RefCount<Pointer> ©);\n ~RefCount();\n RefCount<Pointer> &operator = (const RefCount<Pointer> ©);\n RefCount<Pointer> &operator = (Pointer *p);\n Pointer *operator * () const { return get(); } \n Pointer *operator -> () const { return get(); }\n Pointer *get() const { return m_data; }\n \/\/\/ @return number of referenses\n unsigned int usedBy() const { return (m_refcount != 0 ? *m_refcount : 0); }\nprivate:\n \/\/\/ increase referense count\n void incRefCount();\n \/\/\/ decrease referense count\n void decRefCount();\n Pointer *m_data; \/\/\/< data holder\n mutable unsigned int *m_refcount; \/\/\/< holds reference counting\n};\n\n\/\/ implementation\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount():m_data(0), m_refcount(new unsigned int(0)) {\n\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(RefCount<Pointer> ©):\n m_data(copy.m_data),\n m_refcount(copy.m_refcount) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(Pointer *p):m_data(p), m_refcount(new unsigned int(0)) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(const RefCount<Pointer> ©):\n m_data(copy.m_data),\n m_refcount(copy.m_refcount) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::~RefCount() {\n decRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer> &RefCount<Pointer>::operator = (const RefCount<Pointer> ©) {\n decRefCount(); \/\/ dec current ref count\n m_refcount = copy.m_refcount; \/\/ set new ref count\n m_data = copy.m_data; \/\/ set new data pointer\n incRefCount(); \/\/ inc new ref count \n return *this;\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer> &RefCount<Pointer>::operator = (Pointer *p) {\n decRefCount();\n m_data = p; \/\/ set data pointer\n m_refcount = new unsigned int(0); \/\/ create new counter\n incRefCount();\n}\n\ntemplate <typename Pointer>\nvoid RefCount<Pointer>::decRefCount() {\n if (m_refcount == 0)\n return;\n if (*m_refcount == 0) { \/\/ already zero, then delete refcount\n delete m_refcount;\n m_refcount = 0;\n return;\n }\n (*m_refcount)--;\n if (*m_refcount == 0) { \/\/ destroy m_data and m_refcount if nobody else is using this\n if (m_data != 0)\n delete m_data;\n m_data = 0;\n delete m_refcount;\n m_refcount = 0;\n }\n}\n\ntemplate <typename Pointer>\nvoid RefCount<Pointer>::incRefCount() {\n if (m_refcount == 0)\n return;\n (*m_refcount)++;\n}\n\n}; \/\/ end namespace FbTk\n\n#endif \/\/ FBTK_REFCOUNT_HH\n<commit_msg>removed explicit from copy constructor<commit_after>\/\/ RefCount.hh for FbTk - Fluxbox Toolkit\n\/\/ Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n#ifndef FBTK_REFCOUNT_HH\n#define FBTK_REFCOUNT_HH\n\nnamespace FbTk {\n\n\/\/\/ holds a pointer with reference counting, similar to std:auto_ptr\ntemplate <typename Pointer>\nclass RefCount {\npublic:\n RefCount();\n explicit RefCount(Pointer *p);\n explicit RefCount(RefCount<Pointer> ©);\n RefCount(const RefCount<Pointer> ©);\n ~RefCount();\n RefCount<Pointer> &operator = (const RefCount<Pointer> ©);\n RefCount<Pointer> &operator = (Pointer *p);\n Pointer *operator * () const { return get(); } \n Pointer *operator -> () const { return get(); }\n Pointer *get() const { return m_data; }\n \/\/\/ @return number of referenses\n unsigned int usedBy() const { return (m_refcount != 0 ? *m_refcount : 0); }\nprivate:\n \/\/\/ increase referense count\n void incRefCount();\n \/\/\/ decrease referense count\n void decRefCount();\n Pointer *m_data; \/\/\/< data holder\n mutable unsigned int *m_refcount; \/\/\/< holds reference counting\n};\n\n\/\/ implementation\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount():m_data(0), m_refcount(new unsigned int(0)) {\n\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(RefCount<Pointer> ©):\n m_data(copy.m_data),\n m_refcount(copy.m_refcount) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(Pointer *p):m_data(p), m_refcount(new unsigned int(0)) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::RefCount(const RefCount<Pointer> ©):\n m_data(copy.m_data),\n m_refcount(copy.m_refcount) {\n incRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer>::~RefCount() {\n decRefCount();\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer> &RefCount<Pointer>::operator = (const RefCount<Pointer> ©) {\n decRefCount(); \/\/ dec current ref count\n m_refcount = copy.m_refcount; \/\/ set new ref count\n m_data = copy.m_data; \/\/ set new data pointer\n incRefCount(); \/\/ inc new ref count \n return *this;\n}\n\ntemplate <typename Pointer>\nRefCount<Pointer> &RefCount<Pointer>::operator = (Pointer *p) {\n decRefCount();\n m_data = p; \/\/ set data pointer\n m_refcount = new unsigned int(0); \/\/ create new counter\n incRefCount();\n}\n\ntemplate <typename Pointer>\nvoid RefCount<Pointer>::decRefCount() {\n if (m_refcount == 0)\n return;\n if (*m_refcount == 0) { \/\/ already zero, then delete refcount\n delete m_refcount;\n m_refcount = 0;\n return;\n }\n (*m_refcount)--;\n if (*m_refcount == 0) { \/\/ destroy m_data and m_refcount if nobody else is using this\n if (m_data != 0)\n delete m_data;\n m_data = 0;\n delete m_refcount;\n m_refcount = 0;\n }\n}\n\ntemplate <typename Pointer>\nvoid RefCount<Pointer>::incRefCount() {\n if (m_refcount == 0)\n return;\n (*m_refcount)++;\n}\n\n}; \/\/ end namespace FbTk\n\n#endif \/\/ FBTK_REFCOUNT_HH\n<|endoftext|>"} {"text":"<commit_before>\/**\n* \\file main.cc\n* \\brief Program for giving an indication when a RFID card has been\n* detected, a database connection has been made and a string has been encrypted\n* \\author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de\n* Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens,\n* Jeremy Ruijzenaars\n* \\copyright Copyright (c) 2017, The R2D2 Team\n* \\license See LICENSE\n*\/\n\n#include \"config-file-parser.hh\"\n#include \"database-manager.hh\"\n#include \"led-controller.hh\"\n#include \"matrix-keypad.hh\"\n#include \"mfrc522.hh\"\n\n#include <wiringPiSPI.h>\n\n#include <iomanip>\n\nint main(int argc, char **argv) {\n#define USING_PIN \/\/ Comment out this rule if not using a pin code on your\n \/\/ application\n std::string ip;\n std::string username;\n std::string password;\n\n ConfigFileParser factory(\"database-config.txt\");\n factory.loadDatabaseSettings(ip, username, password);\n\n MySql connection;\n\n std::cout << \"Made connection to the database\\n\";\n wiringPiSetup();\n wiringPiSPISetup(0, 10000000); \/\/ max speed for mfrc522 is 10Mhz\n MFRC522 rfid;\n rfid.PCD_Init();\n\n \/\/ Keypad pinSetup\n const int keypadRow[] = {15, 16, 1, 4};\n const int keypadColumn[] = {8, 9, 7, 2};\n\n \/\/ Keypad objects\n MatrixKeypad keypad(keypadRow, keypadColumn, 4);\n\n LedController redLed(0);\n LedController greenLed(11);\n DatabaseManager information;\n information.connectTo(ip, username, password);\n information.selectDatabase(\"R2D2\");\n while (true) {\n delay(1000);\n std::cout << \"\\n\\nWaiting for RFID tag: \\n\";\n\n if (!rfid.PICC_IsNewCardPresent())\n continue;\n\n if (!rfid.PICC_ReadCardSerial())\n continue;\n\n std::string id;\n for (byte i = 0; i < rfid.uid.size; ++i) {\n std::stringstream ss;\n ss << std::hex << (int) rfid.uid.uidByte[i];\n std::string res(ss.str());\n id += res;\n if (i != rfid.uid.size - 1) {\n id += ' ';\n }\n }\n\n bool inDatabase;\n std::cout << id << \" is the presented ID\\n\";\n if (!information.isCardInDatabase(id)) {\n std::cout << \"This ID is in the database\\n\";\n inDatabase = 1;\n } else {\n std::cout << \"This ID is NOT in the database\\n\";\n inDatabase = 0;\n }\n\n#ifdef USING_PIN\n MFRC522::MIFARE_Key key = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};\n if (1 !=\n rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A,\n (byte) 0x05, &key, &rfid.uid))\n continue;\n\n \/\/ read pin code\n byte bufferSize = (byte) 18;\n byte readArray[18] = {0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0};\n rfid.MIFARE_Read((byte) 0x05, readArray, &bufferSize);\n std::cout << \"Read array contains: \\n\";\n for (int i = 0; i < 18; i++) {\n std::cout << (int) readArray[i] << ' ';\n }\n\n \/\/ enter pin code\n std::cout << \"\\nInput PIN and finish with #\\n\";\n std::string value = keypad.getString();\n\n \/\/ write pin code\n byte writeArray[16] = {0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0};\n int index = 0;\n for (auto c : value) {\n if (c > 47 && c < 58) {\n int number = c - 48;\n writeArray[index++] = (byte) number;\n }\n }\n rfid.MIFARE_Write((byte) 0x05, writeArray, (byte) 16);\n std::cout << \"Write array contains: \\n\";\n for (int i = 0; i < 16; i++) {\n std::cout << (int) writeArray[i] << ' ';\n }\n\n#endif\n rfid.PCD_StopCrypto1();\n if (inDatabase) {\n greenLed.blinkLed(3000);\n } else {\n redLed.blinkLed(3000);\n }\n }\n}\n<commit_msg>[RFID-03] Changed all the stuff according to the review on pr 31<commit_after>\/**\n* \\file main.cc\n* \\brief Program for giving an indication when a RFID card has been\n* detected, a database connection has been made and a string has been encrypted\n* \\author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de\n* Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens,\n* Jeremy Ruijzenaars\n* \\copyright Copyright (c) 2017, The R2D2 Team\n* \\license See LICENSE\n*\/\n\n#include \"config-file-parser.hh\"\n#include \"database-manager.hh\"\n#include \"led-controller.hh\"\n#include \"matrix-keypad.hh\"\n#include \"mfrc522.hh\"\n\n#include <wiringPiSPI.h>\n\n#include <iomanip>\n#include <string>\n\n\/\/ Keypad pinSetup\nconst int keypadRow[] = {15, 16, 1, 4};\nconst int keypadColumn[] = {8, 9, 7, 2};\n\n\/\/ Magic number declarations\nconst int redLedPin = 0;\nconst int greenLedPin = 11;\nconst int maxSpeedWiringSPI = 10000000; \/\/ max speed for mfrc522 is 10Mhz\nconst int keypadColumnSize = 4;\nconst int blockSizeWithCrc = 18;\nconst int blockSize = 16;\nconst int zeroAscii = 47;\nconst int nineAscii = 58;\nconst int blinkTime = 3000;\n\nint main(int argc, char **argv) {\n\n if(argc != 2 || std::string(argv[1]) != \"pin\" && std::string(argv[1]) != \"no-pin\") {\n std::cerr << \"Please only put in 'pin' or 'no-pin' as parameter, nothing else.\" << std::endl\n << \"Your function will then either look like '.\/rfid pin' or '.\/rfid no-pin'\" << std::endl;\n }\n\n \/\/ Keypad objects\n MatrixKeypad keypad(keypadRow, keypadColumn, keypadColumnSize);\n\n LedController redLed(redLedPin);\n LedController greenLed(greenLedPin);\n\n std::string ip;\n std::string username;\n std::string password;\n\n ConfigFileParser factory(\"database-config.txt\");\n factory.loadDatabaseSettings(ip, username, password);\n DatabaseManager information;\n information.connectTo(ip, username, password);\n information.selectDatabase(\"R2D2\");\n\n std::cout << \"Made connection to the database\\n\";\n wiringPiSetup();\n wiringPiSPISetup(0, maxSpeedWiringSPI);\n\n MFRC522 rfid;\n rfid.PCD_Init();\n\n while (true) {\n delay(1000);\n std::cout << \"\\n\\nWaiting for RFID tag: \\n\";\n\n if (!rfid.PICC_IsNewCardPresent())\n continue;\n\n if (!rfid.PICC_ReadCardSerial())\n continue;\n\n std::string id;\n for (byte i = 0; i < rfid.uid.size; ++i) {\n std::stringstream ss;\n ss << std::hex << (int) rfid.uid.uidByte[i];\n id += ss.str();\n if (i != rfid.uid.size - 1) {\n id += ' ';\n }\n }\n\n bool inDatabase;\n std::cout << id << \" is the presented ID\\n\";\n if (!information.isCardInDatabase(id)) {\n std::cout << \"This ID is in the database\\n\";\n inDatabase = 1;\n } else {\n std::cout << \"This ID is NOT in the database\\n\";\n inDatabase = 0;\n }\n\n if(std::string(argv[1]) == \"pin\") {\n MFRC522::MIFARE_Key key = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};\n if (rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A,\n (byte) 0x05, &key, &rfid.uid) != 1)\n continue;\n\n \/\/ read pin code\n byte bufferSize = (byte) blockSizeWithCrc;\n byte readArray[blockSizeWithCrc] = {};\n rfid.MIFARE_Read((byte) 0x05, readArray, &bufferSize);\n std::cout << \"Read array contains: \\n\";\n for (int i = 0; i < blockSizeWithCrc; i++) {\n std::cout << (int) readArray[i] << ' ';\n }\n\n \/\/ enter pin code\n std::cout << \"\\nInput PIN and finish with #\\n\";\n std::string value = keypad.getString();\n\n \/\/ write pin code\n byte writeArray[blockSize] = {};\n int index = 0;\n for (const auto c : value) {\n if (c > zeroAscii && c < nineAscii) {\n int number = c - (zeroAscii+1);\n writeArray[index++] = (byte) number;\n }\n }\n rfid.MIFARE_Write((byte) 0x05, writeArray, (byte) blockSize);\n std::cout << \"Write array contains: \\n\";\n for (int i = 0; i < blockSize; i++) {\n std::cout << (int) writeArray[i] << ' ';\n }\n }\n\n rfid.PCD_StopCrypto1();\n if (inDatabase) {\n greenLed.blinkLed(blinkTime);\n } else {\n redLed.blinkLed(blinkTime);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_erepairGetFailedLanesHwp.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_erepairGetFailedLanesHwp.H\n\/\/\/ @brief FW Team HWP that accesses the fail lanes of Fabric and Memory buses.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>\n\/\/ *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>\n\/\/ *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>\n\/\/ *HWP Team : IO\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : FSP:HB\n\/\/----------------------------------------------------------------------------\n\n#ifndef P9_IO_EREPAIRGETFAILEDLANESHWP_H_\n#define P9_IO_EREPAIRGETFAILEDLANESHWP_H_\n\n#include <fapi2.H>\n#include <p9_io_erepairConsts.H>\n\n\ntypedef fapi2::ReturnCode (*p9_io_erepairGetFailedLanesHwp_FP_t)(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS |\n fapi2::TARGET_TYPE_OBUS |\n fapi2::TARGET_TYPE_MEMBUF_CHIP |\n fapi2::TARGET_TYPE_MCS_CHIPLET |\n fapi2::TARGET_TYPE_MCS > &i_target,\n EREPAIR::erepairVpdType i_vpdType,\n const uint8_t i_clkGroup,\n std::vector<uint8_t>& o_txFailLanes,\n std::vector<uint8_t>& o_rxFailLanes);\n\nextern \"C\"\n{\n\n \/**\n * @brief FW Team HWP that retrieves the eRepair fail lanes.\n * It retrieves the eRepair data from the P9 MVPD and the Centaur FRU\n * VPD sections depending on the passed target type. It then parses the\n * eRepair data to determine the fail lane numbers on the sub-interfaces\n * (Tx and Rx) of the passed bus target.\n *\n * @param[in] i_tgtHandle Reference to X-Bus or A-Bus or MCS or memBuf Target\n * @param[in] i_vpdType Specifies which VPD (MNFG or Field) to access.\n * @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]\n * @param[o] o_txFailLanes Reference to a vector that will hold eRepair fail\n * lane numbers of the Tx sub-interface.\n * @param[o] o_rxFailLanes Reference to a vector that will hold eRepair fail\n * lane numbers of the Rx sub-interface.\n *\n * @return ReturnCode\n *\n *\/\n fapi2::ReturnCode p9_io_erepairGetFailedLanesHwp(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS |\n fapi2::TARGET_TYPE_OBUS |\n fapi2::TARGET_TYPE_MEMBUF_CHIP |\n fapi2::TARGET_TYPE_MCS_CHIPLET |\n fapi2::TARGET_TYPE_MCS > &i_target,\n EREPAIR::erepairVpdType i_vpdType,\n const uint8_t i_clkGroup,\n std::vector<uint8_t>& o_txFailLanes,\n std::vector<uint8_t>& o_rxFailLanes);\n\n}\/\/ end of extern C\n\n#endif\n<commit_msg>erepair VPD access bug fixes<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_erepairGetFailedLanesHwp.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_erepairGetFailedLanesHwp.H\n\/\/\/ @brief FW Team HWP that accesses the fail lanes of Fabric and Memory buses.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>\n\/\/ *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>\n\/\/ *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>\n\/\/ *HWP Team : IO\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : FSP:HB\n\/\/----------------------------------------------------------------------------\n\n#ifndef P9_IO_EREPAIRGETFAILEDLANESHWP_H_\n#define P9_IO_EREPAIRGETFAILEDLANESHWP_H_\n\n#include <fapi2.H>\n#include <p9_io_erepairConsts.H>\n\n\ntemplate<fapi2::TargetType K>\nusing p9_io_erepairGetFailedLanesHwp_FP_t = fapi2::ReturnCode (*)(\n const fapi2::Target < K >& i_target,\n EREPAIR::erepairVpdType i_vpdType,\n const uint8_t i_clkGroup,\n std::vector<uint8_t>& o_txFailLanes,\n std::vector<uint8_t>& o_rxFailLanes);\n\n\n\/**\n * @brief FW Team HWP that retrieves the eRepair fail lanes.\n * It retrieves the eRepair data from the P9 MVPD and the Centaur FRU\n * VPD sections depending on the passed target type. It then parses the\n * eRepair data to determine the fail lane numbers on the sub-interfaces\n * (Tx and Rx) of the passed bus target.\n *\n * @param[in] i_tgtHandle Reference to X-Bus or A-Bus or MCS or memBuf Target\n * @param[in] i_vpdType Specifies which VPD (MNFG or Field) to access.\n * @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]\n * @param[o] o_txFailLanes Reference to a vector that will hold eRepair fail\n * lane numbers of the Tx sub-interface.\n * @param[o] o_rxFailLanes Reference to a vector that will hold eRepair fail\n * lane numbers of the Rx sub-interface.\n *\n * @return ReturnCode\n *\n *\/\ntemplate<fapi2::TargetType K>\nfapi2::ReturnCode p9_io_erepairGetFailedLanesHwp(\n const fapi2::Target < K >& i_target,\n EREPAIR::erepairVpdType i_vpdType,\n const uint8_t i_clkGroup,\n std::vector<uint8_t>& o_txFailLanes,\n std::vector<uint8_t>& o_rxFailLanes);\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/cont:$Id$\n\/\/ Author: Fons Rademakers 10\/08\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ THashList \/\/\n\/\/ \/\/\n\/\/ THashList implements a hybrid collection class consisting of a \/\/\n\/\/ hash table and a list to store TObject's. The hash table is used for \/\/\n\/\/ quick access and lookup of objects while the list allows the objects \/\/\n\/\/ to be ordered. The hash value is calculated using the value returned \/\/\n\/\/ by the TObject's Hash() function. Each class inheriting from TObject \/\/\n\/\/ can override Hash() as it sees fit. \/\/\n\/\/Begin_Html\n\/*\n<img src=gif\/thashlist.gif>\n*\/\n\/\/End_Html\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"THashList.h\"\n#include \"THashTable.h\"\n\n\nClassImp(THashList)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a THashList object. Capacity is the initial hashtable capacity\n\/\/\/ (i.e. number of slots), by default kInitHashTableCapacity = 17, and\n\/\/\/ rehash is the value at which a rehash will be triggered. I.e. when the\n\/\/\/ average size of the linked lists at a slot becomes longer than rehash\n\/\/\/ then the hashtable will be resized and refilled to reduce the collision\n\/\/\/ rate to about 1. The higher the collision rate, i.e. the longer the\n\/\/\/ linked lists, the longer lookup will take. If rehash=0 the table will\n\/\/\/ NOT automatically be rehashed. Use Rehash() for manual rehashing.\n\/\/\/ WARNING !!!\n\/\/\/ If the name of an object in the HashList is modified, The hashlist\n\/\/\/ must be Rehashed\n\nTHashList::THashList(Int_t capacity, Int_t rehash)\n{\n fTable = new THashTable(capacity, rehash);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ For backward compatibility only. Use other ctor.\n\nTHashList::THashList(TObject *, Int_t capacity, Int_t rehash)\n{\n fTable = new THashTable(capacity, rehash);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Delete a hashlist. Objects are not deleted unless the THashList is the\n\/\/\/ owner (set via SetOwner()).\n\nTHashList::~THashList()\n{\n Clear();\n SafeDelete(fTable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the beginning of the list.\n\nvoid THashList::AddFirst(TObject *obj)\n{\n TList::AddFirst(obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the beginning of the list and also store option.\n\/\/\/ Storing an option is useful when one wants to change the behaviour\n\/\/\/ of an object a little without having to create a complete new\n\/\/\/ copy of the object. This feature is used, for example, by the Draw()\n\/\/\/ method. It allows the same object to be drawn in different ways.\n\nvoid THashList::AddFirst(TObject *obj, Option_t *opt)\n{\n TList::AddFirst(obj, opt);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the end of the list.\n\nvoid THashList::AddLast(TObject *obj)\n{\n TList::AddLast(obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the end of the list and also store option.\n\/\/\/ Storing an option is useful when one wants to change the behaviour\n\/\/\/ of an object a little without having to create a complete new\n\/\/\/ copy of the object. This feature is used, for example, by the Draw()\n\/\/\/ method. It allows the same object to be drawn in different ways.\n\nvoid THashList::AddLast(TObject *obj, Option_t *opt)\n{\n TList::AddLast(obj, opt);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object before object before in the list.\n\nvoid THashList::AddBefore(const TObject *before, TObject *obj)\n{\n TList::AddBefore(before, obj);\n fTable->AddBefore(before, obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object before object before in the list.\n\nvoid THashList::AddBefore(TObjLink *before, TObject *obj)\n{\n TList::AddBefore(before, obj);\n fTable->AddBefore(before->GetObject(), obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object after object after in the list.\n\nvoid THashList::AddAfter(const TObject *after, TObject *obj)\n{\n TList::AddAfter(after, obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object after object after in the list.\n\nvoid THashList::AddAfter(TObjLink *after, TObject *obj)\n{\n TList::AddAfter(after, obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object at location idx in the list.\n\nvoid THashList::AddAt(TObject *obj, Int_t idx)\n{\n TList::AddAt(obj, idx);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the average collision rate. The higher the number the longer\n\/\/\/ the linked lists in the hashtable, the slower the lookup. If the number\n\/\/\/ is high, or lookup noticeably too slow, perfrom a Rehash().\n\nFloat_t THashList::AverageCollisions() const\n{\n return fTable->AverageCollisions();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove all objects from the list. Does not delete the objects unless\n\/\/\/ the THashList is the owner (set via SetOwner()).\n\nvoid THashList::Clear(Option_t *option)\n{\n fTable->Clear(\"nodelete\"); \/\/ clear table so not more lookups\n if (IsOwner())\n TList::Delete(option);\n else\n TList::Clear(option);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove all objects from the list AND delete all heap based objects.\n\/\/\/ If option=\"slow\" then keep list consistent during delete. This allows\n\/\/\/ recursive list operations during the delete (e.g. during the dtor\n\/\/\/ of an object in this list one can still access the list to search for\n\/\/\/ other not yet deleted objects).\n\nvoid THashList::Delete(Option_t *option)\n{\n Bool_t slow = option ? (!strcmp(option, \"slow\") ? kTRUE : kFALSE) : kFALSE;\n\n if (!slow) {\n fTable->Clear(\"nodelete\"); \/\/ clear table so no more lookups\n TList::Delete(option); \/\/ this deletes the objects\n } else {\n while (fFirst) {\n TObjLink *tlk = fFirst;\n fFirst = fFirst->Next();\n fSize--;\n \/\/ remove object from table\n fTable->Remove(tlk->GetObject());\n \/\/ delete only heap objects\n if (tlk->GetObject() && tlk->GetObject()->IsOnHeap())\n TCollection::GarbageCollect(tlk->GetObject());\n\n delete tlk;\n }\n fFirst = fLast = fCache = 0;\n fSize = 0;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Find object using its name. Uses the hash value returned by the\n\/\/\/ TString::Hash() after converting name to a TString.\n\nTObject *THashList::FindObject(const char *name) const\n{\n return fTable->FindObject(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Find object using its hash value (returned by its Hash() member).\n\nTObject *THashList::FindObject(const TObject *obj) const\n{\n return fTable->FindObject(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the THashTable's list (bucket) in which obj can be found based on\n\/\/\/ its hash; see THashTable::GetListForObject().\n\nconst TList *THashList::GetListForObject(const char *name) const\n{\n return fTable->GetListForObject(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the THashTable's list (bucket) in which obj can be found based on\n\/\/\/ its hash; see THashTable::GetListForObject().\n\nconst TList *THashList::GetListForObject(const TObject *obj) const\n{\n return fTable->GetListForObject(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object from this collection and recursively remove the object\n\/\/\/ from all other objects (and collections).\n\/\/\/ This function overrides TCollection::RecursiveRemove that calls\n\/\/\/ the Remove function. THashList::Remove cannot be called because\n\/\/\/ it uses the hash value of the hash table. This hash value\n\/\/\/ is not available anymore when RecursiveRemove is called from\n\/\/\/ the TObject destructor.\n\nvoid THashList::RecursiveRemove(TObject *obj)\n{\n if (!obj) return;\n\n \/\/ Remove obj in the list itself\n TObject *object = TList::Remove(obj);\n if (object) fTable->RemoveSlow(object);\n\n \/\/ Scan again the list and invoke RecursiveRemove for all objects\n TIter next(this);\n\n while ((object = next())) {\n if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Rehash the hashlist. If the collision rate becomes too high (i.e.\n\/\/\/ the average size of the linked lists become too long) then lookup\n\/\/\/ efficiency decreases since relatively long lists have to be searched\n\/\/\/ every time. To improve performance rehash the hashtable. This resizes\n\/\/\/ the table to newCapacity slots and refills the table. Use\n\/\/\/ AverageCollisions() to check if you need to rehash.\n\nvoid THashList::Rehash(Int_t newCapacity)\n{\n fTable->Rehash(newCapacity);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object from the list.\n\nTObject *THashList::Remove(TObject *obj)\n{\n if (!obj || !fTable->FindObject(obj)) return 0;\n\n TList::Remove(obj);\n return fTable->Remove(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object via its objlink from the list.\n\nTObject *THashList::Remove(TObjLink *lnk)\n{\n if (!lnk) return 0;\n\n TObject *obj = lnk->GetObject();\n\n TList::Remove(lnk);\n return fTable->Remove(obj);\n}\n<commit_msg>Doxygen & spell check<commit_after>\/\/ @(#)root\/cont:$Id$\n\/\/ Author: Fons Rademakers 10\/08\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class THashList\nTHashList implements a hybrid collection class consisting of a\nhash table and a list to store TObject's. The hash table is used for\nquick access and lookup of objects while the list allows the objects\nto be ordered. The hash value is calculated using the value returned\nby the TObject's Hash() function. Each class inheriting from TObject\ncan override Hash() as it sees fit.\n*\/\n\n#include \"THashList.h\"\n#include \"THashTable.h\"\n\n\nClassImp(THashList)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a THashList object. Capacity is the initial hashtable capacity\n\/\/\/ (i.e. number of slots), by default kInitHashTableCapacity = 17, and\n\/\/\/ rehash is the value at which a rehash will be triggered. I.e. when the\n\/\/\/ average size of the linked lists at a slot becomes longer than rehash\n\/\/\/ then the hashtable will be resized and refilled to reduce the collision\n\/\/\/ rate to about 1. The higher the collision rate, i.e. the longer the\n\/\/\/ linked lists, the longer lookup will take. If rehash=0 the table will\n\/\/\/ NOT automatically be rehashed. Use Rehash() for manual rehashing.\n\/\/\/\n\/\/\/ WARNING !!!\n\/\/\/ If the name of an object in the HashList is modified, The hashlist\n\/\/\/ must be Rehashed\n\nTHashList::THashList(Int_t capacity, Int_t rehash)\n{\n fTable = new THashTable(capacity, rehash);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ For backward compatibility only. Use other ctor.\n\nTHashList::THashList(TObject *, Int_t capacity, Int_t rehash)\n{\n fTable = new THashTable(capacity, rehash);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Delete a hashlist. Objects are not deleted unless the THashList is the\n\/\/\/ owner (set via SetOwner()).\n\nTHashList::~THashList()\n{\n Clear();\n SafeDelete(fTable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the beginning of the list.\n\nvoid THashList::AddFirst(TObject *obj)\n{\n TList::AddFirst(obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the beginning of the list and also store option.\n\/\/\/ Storing an option is useful when one wants to change the behaviour\n\/\/\/ of an object a little without having to create a complete new\n\/\/\/ copy of the object. This feature is used, for example, by the Draw()\n\/\/\/ method. It allows the same object to be drawn in different ways.\n\nvoid THashList::AddFirst(TObject *obj, Option_t *opt)\n{\n TList::AddFirst(obj, opt);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the end of the list.\n\nvoid THashList::AddLast(TObject *obj)\n{\n TList::AddLast(obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add object at the end of the list and also store option.\n\/\/\/ Storing an option is useful when one wants to change the behaviour\n\/\/\/ of an object a little without having to create a complete new\n\/\/\/ copy of the object. This feature is used, for example, by the Draw()\n\/\/\/ method. It allows the same object to be drawn in different ways.\n\nvoid THashList::AddLast(TObject *obj, Option_t *opt)\n{\n TList::AddLast(obj, opt);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object before object before in the list.\n\nvoid THashList::AddBefore(const TObject *before, TObject *obj)\n{\n TList::AddBefore(before, obj);\n fTable->AddBefore(before, obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object before object before in the list.\n\nvoid THashList::AddBefore(TObjLink *before, TObject *obj)\n{\n TList::AddBefore(before, obj);\n fTable->AddBefore(before->GetObject(), obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object after object after in the list.\n\nvoid THashList::AddAfter(const TObject *after, TObject *obj)\n{\n TList::AddAfter(after, obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object after object after in the list.\n\nvoid THashList::AddAfter(TObjLink *after, TObject *obj)\n{\n TList::AddAfter(after, obj);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Insert object at location idx in the list.\n\nvoid THashList::AddAt(TObject *obj, Int_t idx)\n{\n TList::AddAt(obj, idx);\n fTable->Add(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the average collision rate. The higher the number the longer\n\/\/\/ the linked lists in the hashtable, the slower the lookup. If the number\n\/\/\/ is high, or lookup noticeably too slow, perform a Rehash().\n\nFloat_t THashList::AverageCollisions() const\n{\n return fTable->AverageCollisions();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove all objects from the list. Does not delete the objects unless\n\/\/\/ the THashList is the owner (set via SetOwner()).\n\nvoid THashList::Clear(Option_t *option)\n{\n fTable->Clear(\"nodelete\"); \/\/ clear table so not more lookups\n if (IsOwner())\n TList::Delete(option);\n else\n TList::Clear(option);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove all objects from the list AND delete all heap based objects.\n\/\/\/ If option=\"slow\" then keep list consistent during delete. This allows\n\/\/\/ recursive list operations during the delete (e.g. during the dtor\n\/\/\/ of an object in this list one can still access the list to search for\n\/\/\/ other not yet deleted objects).\n\nvoid THashList::Delete(Option_t *option)\n{\n Bool_t slow = option ? (!strcmp(option, \"slow\") ? kTRUE : kFALSE) : kFALSE;\n\n if (!slow) {\n fTable->Clear(\"nodelete\"); \/\/ clear table so no more lookups\n TList::Delete(option); \/\/ this deletes the objects\n } else {\n while (fFirst) {\n TObjLink *tlk = fFirst;\n fFirst = fFirst->Next();\n fSize--;\n \/\/ remove object from table\n fTable->Remove(tlk->GetObject());\n \/\/ delete only heap objects\n if (tlk->GetObject() && tlk->GetObject()->IsOnHeap())\n TCollection::GarbageCollect(tlk->GetObject());\n\n delete tlk;\n }\n fFirst = fLast = fCache = 0;\n fSize = 0;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Find object using its name. Uses the hash value returned by the\n\/\/\/ TString::Hash() after converting name to a TString.\n\nTObject *THashList::FindObject(const char *name) const\n{\n return fTable->FindObject(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Find object using its hash value (returned by its Hash() member).\n\nTObject *THashList::FindObject(const TObject *obj) const\n{\n return fTable->FindObject(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the THashTable's list (bucket) in which obj can be found based on\n\/\/\/ its hash; see THashTable::GetListForObject().\n\nconst TList *THashList::GetListForObject(const char *name) const\n{\n return fTable->GetListForObject(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return the THashTable's list (bucket) in which obj can be found based on\n\/\/\/ its hash; see THashTable::GetListForObject().\n\nconst TList *THashList::GetListForObject(const TObject *obj) const\n{\n return fTable->GetListForObject(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object from this collection and recursively remove the object\n\/\/\/ from all other objects (and collections).\n\/\/\/ This function overrides TCollection::RecursiveRemove that calls\n\/\/\/ the Remove function. THashList::Remove cannot be called because\n\/\/\/ it uses the hash value of the hash table. This hash value\n\/\/\/ is not available anymore when RecursiveRemove is called from\n\/\/\/ the TObject destructor.\n\nvoid THashList::RecursiveRemove(TObject *obj)\n{\n if (!obj) return;\n\n \/\/ Remove obj in the list itself\n TObject *object = TList::Remove(obj);\n if (object) fTable->RemoveSlow(object);\n\n \/\/ Scan again the list and invoke RecursiveRemove for all objects\n TIter next(this);\n\n while ((object = next())) {\n if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Rehash the hashlist. If the collision rate becomes too high (i.e.\n\/\/\/ the average size of the linked lists become too long) then lookup\n\/\/\/ efficiency decreases since relatively long lists have to be searched\n\/\/\/ every time. To improve performance rehash the hashtable. This resizes\n\/\/\/ the table to newCapacity slots and refills the table. Use\n\/\/\/ AverageCollisions() to check if you need to rehash.\n\nvoid THashList::Rehash(Int_t newCapacity)\n{\n fTable->Rehash(newCapacity);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object from the list.\n\nTObject *THashList::Remove(TObject *obj)\n{\n if (!obj || !fTable->FindObject(obj)) return 0;\n\n TList::Remove(obj);\n return fTable->Remove(obj);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Remove object via its objlink from the list.\n\nTObject *THashList::Remove(TObjLink *lnk)\n{\n if (!lnk) return 0;\n\n TObject *obj = lnk->GetObject();\n\n TList::Remove(lnk);\n return fTable->Remove(obj);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file matriz_bit3.cpp\n * @brief Implementación de funciones para MatrizBit de tipo 3\n *\n *\/\n\nconst int MAX_POS = 16;\n\nbool Inicializar (MatrizBit& m, int fils, int cols)\n{\n bool exito = fils * cols <= m.MAX_ESPACIO && fils >= 0 && cols >= 0;\n\n if (exito)\n {\n m.espacio = (fils << MAX_POS) | cols;\n\n for (int i = 0; i < fils * cols; i++)\n m.v[i] = '0';\n }\n\n return exito;\n}\n\n\/\/________________________________________________________________\n\nint GetFilas (const MatrizBit& m)\n{\n return m.espacio >> MAX_POS;\n}\n\n\/\/________________________________________________________________\n\nint GetColumnas (const MatrizBit& m)\n{\n return m.espacio & 0xFFFF;\n}\n\/\/________________________________________________________________\n\nbool GetElemento (const MatrizBit& m, int f, int c)\n{\n return m.v[GetColumnas(m)*f + c] == '1';\n}\n\n\/\/________________________________________________________________\n\nvoid SetElemento (MatrizBit& m, int f, int c, bool v)\n{\n const int COLS = GetColumnas(m);\n const int FILS = GetFilas(m);\n\n if (f < FILS && c < COLS && f >= 0 && c >= 0)\n m.v[COLS*f + c] = v ? '1' : '0';\n}\n\n\/* Fin fichero: matriz_bit3.cpp *\/\n<commit_msg>minnor fixes<commit_after>\/**\n * @file matriz_bit3.cpp\n * @brief Implementación de funciones para MatrizBit de tipo 3\n *\n *\/\n\nconst int MAX_POS = 16;\n\nbool Inicializar (MatrizBit& m, int fils, int cols)\n{\n bool exito = fils * cols <= m.MAX_ESPACIO && fils >= 0 && cols >= 0;\n\n if (exito)\n {\n m.espacio = (fils << MAX_POS) | cols;\n\n for (int i = 0; i < fils * cols; i++)\n m.v[i] = '0';\n }\n\n return exito;\n}\n\n\/\/________________________________________________________________\n\nint GetFilas (const MatrizBit& m)\n{\n return m.espacio >> MAX_POS;\n}\n\n\/\/________________________________________________________________\n\nint GetColumnas (const MatrizBit& m)\n{\n return m.espacio & 0xFFFF;\n}\n\/\/________________________________________________________________\n\nbool GetElemento (const MatrizBit& m, int f, int c)\n{\n return m.v[GetColumnas(m) * f + c];\n}\n\n\/\/________________________________________________________________\n\nvoid SetElemento (MatrizBit& m, int f, int c, bool v)\n{\n const int COLS = GetColumnas(m);\n const int FILS = GetFilas(m);\n\n if (f < FILS && c < COLS && f >= 0 && c >= 0)\n m.v[COLS * f + c] = v ? '1' : '\\0';\n}\n\n\/* Fin fichero: matriz_bit3.cpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tA vector implementation by Charles Bailey\n\tBecause sundays are boring.\n\n\t12\/4\/16\n*\/\n#include <stdexcept>\n\nnamespace Charlie {\n\n\ttypedef unsigned int size_t;\n\n\ttemplate <typename T>\n\tclass Vector {\n\t\tT *stuff;\n\t\tsize_t actual_size, num_elements;\n\n\t public:\n\t\tVector();\n\t\tVector(size_t _size, T def = T());\n\t\tVector(const Vector<T>& other);\n\t\tVector(Vector<T>&& other);\n\n\t\tvoid operator=(const Vector<T>& other);\n\t\tvoid operator=(Vector<T>&& other);\n\n\t\t~Vector();\n\n\t\tT& operator[](size_t index);\n\t\tconst T& operator[](size_t index) const;\n\n\t\tT& at(size_t index);\n\t\tconst T& at(size_t index) const;\n\n\t\tT& front();\n\t\tconst T& front() const;\n\n\t\tT& back();\n\t\tconst T& back() const;\n\n\t\tT* data();\n\t\tconst T* data() const;\n\n\t\tbool empty() const;\n\n\t\tvoid push_back(const T& item);\n\t\tT pop_back();\n\n\t\tvoid insert(const int& index , const T& item);\n\n\t\tsize_t size() const;\n\t\tsize_t capacity() const;\n\t\tsize_t max_size() const;\n\n\t\tvoid shrink_to_fit();\n\t\tvoid reserve(size_t new_size);\n\n\t\tvoid resize(size_t count);\n\t\tvoid resize(size_t count , const T& value);\n\t\tvoid assign(size_t count , const T& value);\n\n\t\tvoid clear();\n\t\tvoid swap(Vector<T>& other);\n\n\t private:\n\n\t\tvoid _grow();\n\t\tvoid _resize(const size_t& new_size);\n\t};\n\n\ttemplate <typename T>\n\tVector<T>::Vector() : actual_size(10), num_elements(0) {\n\t\tstuff = new T[actual_size];\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(size_t _size, T def) {\n\t\tactual_size = _size;\n\t\tstuff = new T[actual_size];\n\n\t\tnum_elements = 0;\n\t\twhile (num_elements < actual_size)\n\t\t\tstuff[num_elements++] = def;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(const Vector<T>& other) {\n\t\t*this = other;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(Vector<T>&& other) {\n\t\t*this = other;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::operator=(const Vector<T>& other) {\n\t\tif (this == &other)\n\t\t\treturn;\n\n\t\tactual_size = other.actual_size;\n\t\tstuff = new T[actual_size];\n\n\t\tnum_elements = 0;\n\t\twhile(num_elements < other.num_elements) {\n\t\t\tstuff[num_elements] = other.stuff[num_elements];\n\t\t\tnum_elements++;\n\t\t}\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::operator=(Vector<T>&& other) {\n\t\tif (this == &other)\n\t\t\treturn;\n\n\t\tactual_size = other.actual_size;\n\t\tnum_elements = other.num_elements;\n\n\t\tstuff = other.stuff;\n\t\tother.stuff = nullptr;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::~Vector() {\n\t\tdelete [] stuff;\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::operator[](size_t index) {\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::operator[](size_t index) const {\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::at(size_t index) {\n\t\tif (index >= num_elements)\n\t\t\tthrow std::out_of_range(\"That index is out of range.\");\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::at(size_t index) const {\n\t\tif (index >= num_elements)\n\t\t\tthrow std::out_of_range(\"That index is out of range.\");\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::front() {\n\t\treturn at(0);\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::front() const {\n\t\treturn at(0);\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::back() {\n\t\treturn at(num_elements - 1);\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::back() const {\n\t\treturn at(num_elements - 1);\n\t}\n\n\ttemplate <typename T>\n\tT* Vector<T>::data() {\n\t\treturn stuff;\n\t}\n\n\ttemplate <typename T>\n\tconst T* Vector<T>::data() const {\n\t\treturn (const T*)stuff;\n\t}\n\n\ttemplate <typename T>\n\tbool Vector<T>::empty() const {\n\t\treturn num_elements == 0;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::push_back(const T& item) {\n\t\tinsert(num_elements, item);\n\t}\n\n\ttemplate <typename T>\n\tT Vector<T>::pop_back() {\n\t\treturn stuff[--num_elements];\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::insert(const int& index , const T& item) {\n\t\tif (num_elements >= actual_size) {\n\t\t\t_grow();\n\t\t}\n\n\n\t\tint curr = num_elements++; \/* pay attention to this. I'm too lazy to make it its own line. :) *\/\n\t\twhile (--curr >= index) {\n\t\t\tstuff[curr+1] = stuff[curr];\n\t\t}\n\t\tstuff[ index ] = item;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::size() const {\n\t\treturn actual_size;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::capacity() const {\n\t\treturn actual_size;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::max_size() const {\n\t\tsize_t sz = 0;\n\t\treturn (sz-1);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::shrink_to_fit() {\n\t\t_resize(num_elements);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::reserve(size_t new_size) {\n\t\tif (new_size > actual_size)\n\t\t\t_resize(actual_size);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::resize(size_t count) {\n\t\t_resize(count);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::resize(size_t count , const T& value) {\n\t\tbool writein = count > actual_size;\n\t\t_resize(count);\n\n\t\tif (writein)\n\t\t\twhile (num_elements < actual_size)\n\t\t\t\tstuff[num_elements++] = value;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::assign(size_t count , const T& value) {\n\t\tnum_elements = 0;\n\t\tresize(count, value);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::clear() {\n\t\tfor (size_t i = 0; i < num_elements; i++) {\n\t\t\tstuff[i] = T();\n\t\t}\n\t\tnum_elements = 0;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::swap(Vector<T>& other) {\n\t\tstd::swap(this->num_elements , other.num_elements);\n\t\tstd::swap(this->actual_size , other.actual_size);\n\t\tstd::swap(this->stuff, other.stuff);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::_grow() {\n\t\t_resize(2 * actual_size + 1);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::_resize(const size_t& new_size) {\n\t\tif (actual_size == new_size)\n\t\t\treturn;\n\n\t\tactual_size = new_size;\n\t\tT *tmp = new T[actual_size];\n\n\t\tsize_t n = actual_size < num_elements ? actual_size : num_elements;\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t\ttmp[i] = stuff[i];\n\n\t\tdelete [] stuff;\n\t\tstuff = tmp;\n\t}\n\n};\n<commit_msg>pushing comparison vector work<commit_after>\/*\n\tA vector implementation by Charles Bailey\n\tBecause sundays are boring.\n\n\t12\/4\/16\n*\/\n#include <stdexcept>\n\nnamespace Charlie {\n\n\ttypedef unsigned int size_t;\n\n\ttemplate <typename T>\n\tclass Vector {\n\t\tT *stuff;\n\t\tsize_t actual_size, num_elements;\n\n\t public:\n\t\tVector();\n\t\tVector(size_t _size, T def = T());\n\t\tVector(const Vector<T>& other);\n\t\tVector(Vector<T>&& other);\n\n\t\tvoid operator=(const Vector<T>& other);\n\t\tvoid operator=(Vector<T>&& other);\n\n\t\t~Vector();\n\n\t\tT& operator[](size_t index);\n\t\tconst T& operator[](size_t index) const;\n\n\t\tT& at(size_t index);\n\t\tconst T& at(size_t index) const;\n\n\t\tT& front();\n\t\tconst T& front() const;\n\n\t\tT& back();\n\t\tconst T& back() const;\n\n\t\tT* data();\n\t\tconst T* data() const;\n\n\t\tbool empty() const;\n\n\t\tvoid push_back(const T& item);\n\t\tT pop_back();\n\n\t\tvoid insert(const int& index , const T& item);\n\n\t\tsize_t size() const;\n\t\tsize_t capacity() const;\n\t\tsize_t max_size() const;\n\n\t\tvoid shrink_to_fit();\n\t\tvoid reserve(size_t new_size);\n\n\t\tvoid resize(size_t count);\n\t\tvoid resize(size_t count , const T& value);\n\t\tvoid assign(size_t count , const T& value);\n\n\t\tvoid clear();\n\t\tvoid swap(Vector<T>& other);\n\n\t\tbool operator==(const Vector<T>& other) const;\n\t\tbool operator!=(const Vector<T>& other) const;\n\t\tbool operator<=(const Vector<T>& other) const;\n\t\tbool operator>=(const Vector<T>& other) const;\n\t\tbool operator<(const Vector<T>& other) const;\n\t\tbool operator>(const Vector<T>& other) const;\n\n\t private:\n\n\t\tvoid _grow();\n\t\tvoid _resize(const size_t& new_size);\n\t};\n\n\ttemplate <typename T>\n\tVector<T>::Vector() : actual_size(10), num_elements(0) {\n\t\tstuff = new T[actual_size];\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(size_t _size, T def) {\n\t\tactual_size = _size;\n\t\tstuff = new T[actual_size];\n\n\t\tnum_elements = 0;\n\t\twhile (num_elements < actual_size)\n\t\t\tstuff[num_elements++] = def;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(const Vector<T>& other) {\n\t\t*this = other;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::Vector(Vector<T>&& other) {\n\t\t*this = other;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::operator=(const Vector<T>& other) {\n\t\tif (this == &other)\n\t\t\treturn;\n\n\t\tactual_size = other.actual_size;\n\t\tstuff = new T[actual_size];\n\n\t\tnum_elements = 0;\n\t\twhile(num_elements < other.num_elements) {\n\t\t\tstuff[num_elements] = other.stuff[num_elements];\n\t\t\tnum_elements++;\n\t\t}\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::operator=(Vector<T>&& other) {\n\t\tif (this == &other)\n\t\t\treturn;\n\n\t\tactual_size = other.actual_size;\n\t\tnum_elements = other.num_elements;\n\n\t\tstuff = other.stuff;\n\t\tother.stuff = nullptr;\n\t}\n\n\ttemplate <typename T>\n\tVector<T>::~Vector() {\n\t\tdelete [] stuff;\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::operator[](size_t index) {\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::operator[](size_t index) const {\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::at(size_t index) {\n\t\tif (index >= num_elements)\n\t\t\tthrow std::out_of_range(\"That index is out of range.\");\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::at(size_t index) const {\n\t\tif (index >= num_elements)\n\t\t\tthrow std::out_of_range(\"That index is out of range.\");\n\t\treturn stuff[index];\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::front() {\n\t\treturn at(0);\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::front() const {\n\t\treturn at(0);\n\t}\n\n\ttemplate <typename T>\n\tT& Vector<T>::back() {\n\t\treturn at(num_elements - 1);\n\t}\n\n\ttemplate <typename T>\n\tconst T& Vector<T>::back() const {\n\t\treturn at(num_elements - 1);\n\t}\n\n\ttemplate <typename T>\n\tT* Vector<T>::data() {\n\t\treturn stuff;\n\t}\n\n\ttemplate <typename T>\n\tconst T* Vector<T>::data() const {\n\t\treturn (const T*)stuff;\n\t}\n\n\ttemplate <typename T>\n\tbool Vector<T>::empty() const {\n\t\treturn num_elements == 0;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::push_back(const T& item) {\n\t\tinsert(num_elements, item);\n\t}\n\n\ttemplate <typename T>\n\tT Vector<T>::pop_back() {\n\t\treturn stuff[--num_elements];\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::insert(const int& index , const T& item) {\n\t\tif (num_elements >= actual_size) {\n\t\t\t_grow();\n\t\t}\n\n\n\t\tint curr = num_elements++; \/* pay attention to this. I'm too lazy to make it its own line. :) *\/\n\t\twhile (--curr >= index) {\n\t\t\tstuff[curr+1] = stuff[curr];\n\t\t}\n\t\tstuff[ index ] = item;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::size() const {\n\t\treturn actual_size;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::capacity() const {\n\t\treturn actual_size;\n\t}\n\n\ttemplate <typename T>\n\tsize_t Vector<T>::max_size() const {\n\t\tsize_t sz = 0;\n\t\treturn (sz-1);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::shrink_to_fit() {\n\t\t_resize(num_elements);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::reserve(size_t new_size) {\n\t\tif (new_size > actual_size)\n\t\t\t_resize(actual_size);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::resize(size_t count) {\n\t\t_resize(count);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::resize(size_t count , const T& value) {\n\t\tbool writein = count > actual_size;\n\t\t_resize(count);\n\n\t\tif (writein)\n\t\t\twhile (num_elements < actual_size)\n\t\t\t\tstuff[num_elements++] = value;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::assign(size_t count , const T& value) {\n\t\tnum_elements = 0;\n\t\tresize(count, value);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::clear() {\n\t\tfor (size_t i = 0; i < num_elements; i++) {\n\t\t\tstuff[i] = T();\n\t\t}\n\t\tnum_elements = 0;\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::swap(Vector<T>& other) {\n\t\tstd::swap(this->num_elements , other.num_elements);\n\t\tstd::swap(this->actual_size , other.actual_size);\n\t\tstd::swap(this->stuff, other.stuff);\n\t}\n\n\ttemplate <typename T>\t\n\tbool Vector<T>::operator==(const Vector<T>& other) const {\n\t\tif (other.actual_size != this->actual_size) return false;\n\t\tfor (size_t i = 0; i < this->actual_size; i++) {\n\t\t\tif (other.stuff[i] !+ this->stuff[i])\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\ttemplate <typename T>\n\tbool Vector<T>::operator!=(const Vector<T>& other) const {\n\t\treturn !(*this == other);\n\t}\n\t\n\ttemplate <typename T>\n\tbool Vector<T>::operator<=(const Vector<T>& other) const;\n\t\n\ttemplate <typename T>\n\tbool Vector<T>::operator>=(const Vector<T>& other) const;\n\t\n\ttemplate <typename T>\n\tbool Vector<T>::operator<(const Vector<T>& other) const;\n\t\n\ttemplate <typename T>\n\tbool Vector<T>::operator>(const Vector<T>& other) const;\n\n\ttemplate <typename T>\n\tvoid Vector<T>::_grow() {\n\t\t_resize(2 * actual_size + 1);\n\t}\n\n\ttemplate <typename T>\n\tvoid Vector<T>::_resize(const size_t& new_size) {\n\t\tif (actual_size == new_size)\n\t\t\treturn;\n\n\t\tactual_size = new_size;\n\t\tT *tmp = new T[actual_size];\n\n\t\tsize_t n = actual_size < num_elements ? actual_size : num_elements;\n\t\tfor (size_t i = 0; i < n; i++)\n\t\t\ttmp[i] = stuff[i];\n\n\t\tdelete [] stuff;\n\t\tstuff = tmp;\n\t}\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n\nusing namespace std;\n\n#define SAFE_GETLINE(_IS, _LINE, _SIZE, _DELIM) {_IS.getline(_LINE, _SIZE, _DELIM); if(_IS.fail() && !_IS.bad() && !_IS.eof()) _IS.clear();}\n#define LINE_MAX_LENGTH 10000\n\nclass SentenceAlignment {\n public:\n vector<string> english;\n vector<string> foreign;\n vector<int> alignedCountF;\n vector< vector<int> > alignedToE;\n\n int create( char[], char[], char[], int );\n \/\/ void clear() { delete(alignment); };\n};\n\nvoid extract( SentenceAlignment & );\nvoid addPhrase( SentenceAlignment &, int, int, int, int );\nvector<string> tokenize( char [] );\nbool isAligned ( SentenceAlignment &, int, int );\n\nofstream extractFile;\nofstream extractFileInv;\nofstream extractFileOrientation;\nint maxPhraseLength;\nint phraseCount = 0;\nchar* fileNameExtract;\nbool orientationFlag;\n\nint main(int argc, char* argv[]) \n{\n cerr << \"PhraseExtract v1.3.0, written by Philipp Koehn\\n\"\n << \"phrase extraction from an aligned parallel corpus\\n\";\n time_t starttime = time(NULL);\n\n if (argc != 6 && argc != 7) {\n cerr << \"syntax: phrase-extract en de align extract max-length [orientation]\\n\";\n exit(1);\n }\n char* &fileNameE = argv[1];\n char* &fileNameF = argv[2];\n char* &fileNameA = argv[3];\n fileNameExtract = argv[4];\n maxPhraseLength = atoi(argv[5]);\n orientationFlag = (argc == 7);\n if (orientationFlag) cerr << \"(also extracting orientation)\\n\";\n\n \/\/ string fileNameE = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.en\";\n \/\/ string fileNameF = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.de\";\n \/\/ string fileNameA = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.grow-diag-final\";\n\n ifstream eFile;\n ifstream fFile;\n ifstream aFile;\n eFile.open(fileNameE);\n fFile.open(fileNameF);\n aFile.open(fileNameA);\n istream *eFileP = &eFile;\n istream *fFileP = &fFile;\n istream *aFileP = &aFile;\n \n \/\/ string fileNameExtract = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/new-extract\";\n\n int i=0;\n while(true) {\n i++;\n if (i%10000 == 0) cerr << \".\" << flush;\n char englishString[LINE_MAX_LENGTH];\n char foreignString[LINE_MAX_LENGTH];\n char alignmentString[LINE_MAX_LENGTH];\n SAFE_GETLINE((*eFileP), englishString, LINE_MAX_LENGTH, '\\n');\n if (eFileP->eof()) break;\n SAFE_GETLINE((*fFileP), foreignString, LINE_MAX_LENGTH, '\\n');\n SAFE_GETLINE((*aFileP), alignmentString, LINE_MAX_LENGTH, '\\n');\n SentenceAlignment sentence;\n \/\/ cout << \"read in: \" << englishString << \" & \" << foreignString << \" & \" << alignmentString << endl;\n if (sentence.create( englishString, foreignString, alignmentString, i ))\n extract(sentence);\n }\n\n eFile.close();\n fFile.close();\n aFile.close();\n extractFile.close();\n extractFileInv.close();\n}\n \nvoid extract( SentenceAlignment &sentence ) {\n int countE = sentence.english.size();\n int countF = sentence.foreign.size();\n\n \/\/ check alignments for english phrase startE...endE\n for(int startE=0;startE<countE;startE++) {\n for(int endE=startE;\n\t(endE<countE && endE<startE+maxPhraseLength);\n\tendE++) {\n \n int minF = 9999;\n int maxF = -1;\n vector< int > usedF = sentence.alignedCountF;\n for(int ei=startE;ei<=endE;ei++) {\n\tfor(int i=0;i<sentence.alignedToE[ei].size();i++) {\n\t int fi = sentence.alignedToE[ei][i];\n\t \/\/ cout << \"point (\" << fi << \", \" << ei << \")\\n\";\n\t if (fi<minF) { minF = fi; }\n\t if (fi>maxF) { maxF = fi; }\n\t usedF[ fi ]--;\n\t}\n }\n \n \/\/ cout << \"f projected ( \" << minF << \"-\" << maxF << \", \" << startE << \",\" << endE << \")\\n\"; \n\n if (maxF >= 0 && \/\/ aligned to any foreign words at all\n\t maxF-minF < maxPhraseLength) { \/\/ foreign phrase within limits\n\t\n\t\/\/ check if foreign words are aligned to out of bound english words\n\tbool out_of_bounds = false;\n\tfor(int fi=minF;fi<=maxF && !out_of_bounds;fi++)\n\t if (usedF[fi]>0) {\n\t \/\/ cout << \"ouf of bounds: \" << fi << \"\\n\";\n\t out_of_bounds = true;\n\t }\n\t\n\t\/\/ cout << \"doing if for ( \" << minF << \"-\" << maxF << \", \" << startE << \",\" << endE << \")\\n\"; \n\tif (!out_of_bounds)\n\t \/\/ start point of foreign phrase may retreat over unaligned\n\t for(int startF=minF;\n\t (startF>=0 &&\n\t startF>maxF-maxPhraseLength && \/\/ within length limit\n\t (startF==minF || sentence.alignedCountF[startF]==0)); \/\/ unaligned\n\t startF--)\n\t \/\/ end point of foreign phrase may advance over unaligned\n\t for(int endF=maxF;\n\t\t(endF<countF && \n\t\t endF<startF+maxPhraseLength && \/\/ within length limit\n\t\t (endF==maxF || sentence.alignedCountF[endF]==0)); \/\/ unaligned\n\t\tendF++) \n\t addPhrase(sentence,startE,endE,startF,endF);\n }\n }\n }\n}\n\nvoid addPhrase( SentenceAlignment &sentence, int startE, int endE, int startF, int endF ) {\n \/\/ foreign\n \/\/ cout << \"adding ( \" << startF << \"-\" << endF << \", \" << startE << \"-\" << endE << \")\\n\"; \n if (phraseCount % 10000000 == 0) {\n if (phraseCount>0) {\n extractFile.close();\n extractFileInv.close();\n if (orientationFlag) extractFileOrientation.close();\n }\n char part[10];\n sprintf(part,\".part%04d\",phraseCount\/10000000);\n string fileNameExtractPart = string(fileNameExtract) + part;\n string fileNameExtractInvPart = string(fileNameExtract) + \".inv\" + part;\n string fileNameExtractOrientationPart = string(fileNameExtract) + \".o\" + part;\n extractFile.open(fileNameExtractPart.c_str());\n extractFileInv.open(fileNameExtractInvPart.c_str());\n if (orientationFlag) extractFileOrientation.open(fileNameExtractOrientationPart.c_str());\n }\n phraseCount++;\n\n for(int fi=startF;fi<=endF;fi++) {\n extractFile << sentence.foreign[fi] << \" \";\n if (orientationFlag) extractFileOrientation << sentence.foreign[fi] << \" \";\n }\n extractFile << \"||| \";\n if (orientationFlag) extractFileOrientation << \"||| \";\n\n \/\/ english\n for(int ei=startE;ei<=endE;ei++) {\n extractFile << sentence.english[ei] << \" \";\n extractFileInv << sentence.english[ei] << \" \";\n if (orientationFlag) extractFileOrientation << sentence.english[ei] << \" \";\n }\n extractFile << \"|||\";\n extractFileInv << \"||| \";\n if (orientationFlag) extractFileOrientation << \"||| \";\n\n \/\/ foreign (for inverse)\n for(int fi=startF;fi<=endF;fi++)\n extractFileInv << sentence.foreign[fi] << \" \";\n extractFileInv << \"|||\";\n\n \/\/ alignment\n for(int ei=startE;ei<=endE;ei++) \n for(int i=0;i<sentence.alignedToE[ei].size();i++) {\n int fi = sentence.alignedToE[ei][i];\n extractFile << \" \" << fi-startF << \"-\" << ei-startE;\n extractFileInv << \" \" << ei-startE << \"-\" << fi-startF;\n }\n\n if (orientationFlag) {\n\n \/\/ orientation to previous E\n bool connectedLeftTop = isAligned( sentence, startF-1, startE-1 );\n bool connectedRightTop = isAligned( sentence, endF+1, startE-1 );\n if ( connectedLeftTop && !connectedRightTop) \n extractFileOrientation << \"mono\";\n else if (!connectedLeftTop && connectedRightTop) \n extractFileOrientation << \"swap\";\n else \n extractFileOrientation << \"other\";\n \n \/\/ orientation to following E\n bool connectedLeftBottom = isAligned( sentence, startF-1, endE+1 );\n bool connectedRightBottom = isAligned( sentence, endF+1, endE+1 );\n if ( connectedLeftBottom && !connectedRightBottom) \n extractFileOrientation << \" swap\";\n else if (!connectedLeftBottom && connectedRightBottom) \n extractFileOrientation << \" mono\";\n else \n extractFileOrientation << \" other\";\n }\n\n extractFile << \"\\n\";\n extractFileInv << \"\\n\";\n if (orientationFlag) extractFileOrientation << \"\\n\";\n}\n \nbool isAligned ( SentenceAlignment &sentence, int fi, int ei ) {\n if (ei == -1 && fi == -1) return true;\n if (ei <= -1 || fi <= -1) return false;\n if (ei == sentence.english.size() && fi == sentence.foreign.size()) return true;\n if (ei >= sentence.english.size() || fi >= sentence.foreign.size()) return false;\n for(int i=0;i<sentence.alignedToE[ei].size();i++) \n if (sentence.alignedToE[ei][i] == fi) return true;\n return false;\n}\n\n\nint SentenceAlignment::create( char englishString[], char foreignString[], char alignmentString[], int sentenceID ) {\n english = tokenize( englishString );\n foreign = tokenize( foreignString );\n \/\/ alignment = new bool[foreign.size()*english.size()];\n \/\/ alignment = (bool**) calloc(english.size()*foreign.size(),sizeof(bool)); \/\/ is this right?\n \n if (english.size() == 0 || foreign.size() == 0) {\n cerr << \"no english (\" << english.size() << \") or foreign (\" << foreign.size() << \") words << end insentence \" << sentenceID << endl;\n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n \/\/ cout << \"english.size = \" << english.size() << endl;\n \/\/ cout << \"foreign.size = \" << foreign.size() << endl;\n\n \/\/ cout << \"xxx\\n\";\n for(int i=0; i<foreign.size(); i++) {\n \/\/ cout << \"i\" << i << endl;\n alignedCountF.push_back( 0 );\n }\n for(int i=0; i<english.size(); i++) {\n vector< int > dummy;\n alignedToE.push_back( dummy );\n }\n \/\/ cout << \"\\nscanning...\\n\";\n\n vector<string> alignmentSequence = tokenize( alignmentString );\n for(int i=0; i<alignmentSequence.size(); i++) {\n int e,f;\n \/\/ cout << \"scaning \" << alignmentSequence[i].c_str() << endl;\n if (! sscanf(alignmentSequence[i].c_str(), \"%d-%d\", &f, &e)) {\n cerr << \"WARNING: \" << alignmentSequence[i] << \" is a bad alignment point in sentnce \" << sentenceID << endl; \n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n \/\/ cout << \"alignmentSequence[i] \" << alignmentSequence[i] << \" is \" << f << \", \" << e << endl;\n if (e >= english.size() || f >= foreign.size()) { \n cerr << \"WARNING: sentence \" << sentenceID << \" has alignment point (\" << f << \", \" << e << \") out of bounds (\" << foreign.size() << \", \" << english.size() << \")\\n\";\n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n alignedToE[e].push_back( f );\n alignedCountF[f]++;\n }\n return 1;\n}\n\n<commit_msg>andreas zollman's changes to write span information<commit_after>\/\/ $Id$\n\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n\nusing namespace std;\n\n#define SAFE_GETLINE(_IS, _LINE, _SIZE, _DELIM) {_IS.getline(_LINE, _SIZE, _DELIM); if(_IS.fail() && !_IS.bad() && !_IS.eof()) _IS.clear();}\n#define LINE_MAX_LENGTH 10000\n\nclass SentenceAlignment {\n public:\n vector<string> english;\n vector<string> foreign;\n vector<int> alignedCountF;\n vector< vector<int> > alignedToE;\n\n int create( char[], char[], char[], int );\n \/\/ void clear() { delete(alignment); };\n};\n\nvoid extract( SentenceAlignment & );\nvoid addPhrase( SentenceAlignment &, int, int, int, int );\nvector<string> tokenize( char [] );\nbool isAligned ( SentenceAlignment &, int, int );\n\nofstream extractFile;\nofstream extractFileInv;\nofstream extractFileOrientation;\nint maxPhraseLength;\nint phraseCount = 0;\nchar* fileNameExtract;\nbool orientationFlag;\nbool onlyOutputSpanInfo;\n\nint main(int argc, char* argv[]) \n{\n cerr << \"PhraseExtract v1.3.0, written by Philipp Koehn\\n\"\n << \"phrase extraction from an aligned parallel corpus\\n\";\n time_t starttime = time(NULL);\n\n if (argc != 6 && argc != 7) {\n cerr << \"syntax: phrase-extract en de align extract max-length [orientation | --OnlyOutputSpanInfo]\\n\";\n exit(1);\n }\n char* &fileNameE = argv[1];\n char* &fileNameF = argv[2];\n char* &fileNameA = argv[3];\n fileNameExtract = argv[4];\n maxPhraseLength = atoi(argv[5]);\n onlyOutputSpanInfo = argc == 7 && strcmp(argv[6],\"--OnlyOutputSpanInfo\") == 0; \/\/az\n if (onlyOutputSpanInfo) cerr << \"Only outputting span info in format (starting from 0): SrcBegin SrcEnd TgtBegin TgtEnd\\n\"; \/\/az\n orientationFlag = (argc == 7 && !onlyOutputSpanInfo);\n if (orientationFlag) cerr << \"(also extracting orientation)\\n\";\n\n \/\/ string fileNameE = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.en\";\n \/\/ string fileNameF = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.de\";\n \/\/ string fileNameA = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/aligned.grow-diag-final\";\n\n ifstream eFile;\n ifstream fFile;\n ifstream aFile;\n eFile.open(fileNameE);\n fFile.open(fileNameF);\n aFile.open(fileNameA);\n istream *eFileP = &eFile;\n istream *fFileP = &fFile;\n istream *aFileP = &aFile;\n \n \/\/ string fileNameExtract = \"\/data\/nlp\/koehn\/europarl-v2\/models\/de-en\/model\/new-extract\";\n\n int i=0;\n while(true) {\n i++;\n if (i%10000 == 0) cerr << \".\" << flush;\n char englishString[LINE_MAX_LENGTH];\n char foreignString[LINE_MAX_LENGTH];\n char alignmentString[LINE_MAX_LENGTH];\n SAFE_GETLINE((*eFileP), englishString, LINE_MAX_LENGTH, '\\n');\n if (eFileP->eof()) break;\n SAFE_GETLINE((*fFileP), foreignString, LINE_MAX_LENGTH, '\\n');\n SAFE_GETLINE((*aFileP), alignmentString, LINE_MAX_LENGTH, '\\n');\n SentenceAlignment sentence;\n \/\/ cout << \"read in: \" << englishString << \" & \" << foreignString << \" & \" << alignmentString << endl;\n \/\/az: output src, tgt, and alingment line\n if (onlyOutputSpanInfo) {\n cout << \"LOG: SRC: \" << foreignString << endl;\n cout << \"LOG: TGT: \" << englishString << endl;\n cout << \"LOG: ALT: \" << alignmentString << endl;\n cout << \"LOG: PHRASES_BEGIN:\" << endl;\n }\n \n if (sentence.create( englishString, foreignString, alignmentString, i ))\n extract(sentence);\n if (onlyOutputSpanInfo) cout << \"LOG: PHRASES_END:\" << endl; \/\/az: mark end of phrases\n }\n\n eFile.close();\n fFile.close();\n aFile.close();\n \/\/az: only close if we actually opened it\n if (!onlyOutputSpanInfo) {\n extractFile.close();\n extractFileInv.close();\n if (orientationFlag) extractFileOrientation.close();\n }\n}\n \nvoid extract( SentenceAlignment &sentence ) {\n int countE = sentence.english.size();\n int countF = sentence.foreign.size();\n\n \/\/ check alignments for english phrase startE...endE\n for(int startE=0;startE<countE;startE++) {\n for(int endE=startE;\n\t(endE<countE && endE<startE+maxPhraseLength);\n\tendE++) {\n \n int minF = 9999;\n int maxF = -1;\n vector< int > usedF = sentence.alignedCountF;\n for(int ei=startE;ei<=endE;ei++) {\n\tfor(int i=0;i<sentence.alignedToE[ei].size();i++) {\n\t int fi = sentence.alignedToE[ei][i];\n\t \/\/ cout << \"point (\" << fi << \", \" << ei << \")\\n\";\n\t if (fi<minF) { minF = fi; }\n\t if (fi>maxF) { maxF = fi; }\n\t usedF[ fi ]--;\n\t}\n }\n \n \/\/ cout << \"f projected ( \" << minF << \"-\" << maxF << \", \" << startE << \",\" << endE << \")\\n\"; \n\n if (maxF >= 0 && \/\/ aligned to any foreign words at all\n\t maxF-minF < maxPhraseLength) { \/\/ foreign phrase within limits\n\t\n\t\/\/ check if foreign words are aligned to out of bound english words\n\tbool out_of_bounds = false;\n\tfor(int fi=minF;fi<=maxF && !out_of_bounds;fi++)\n\t if (usedF[fi]>0) {\n\t \/\/ cout << \"ouf of bounds: \" << fi << \"\\n\";\n\t out_of_bounds = true;\n\t }\n\t\n\t\/\/ cout << \"doing if for ( \" << minF << \"-\" << maxF << \", \" << startE << \",\" << endE << \")\\n\"; \n\tif (!out_of_bounds)\n\t \/\/ start point of foreign phrase may retreat over unaligned\n\t for(int startF=minF;\n\t (startF>=0 &&\n\t startF>maxF-maxPhraseLength && \/\/ within length limit\n\t (startF==minF || sentence.alignedCountF[startF]==0)); \/\/ unaligned\n\t startF--)\n\t \/\/ end point of foreign phrase may advance over unaligned\n\t for(int endF=maxF;\n\t\t(endF<countF && \n\t\t endF<startF+maxPhraseLength && \/\/ within length limit\n\t\t (endF==maxF || sentence.alignedCountF[endF]==0)); \/\/ unaligned\n\t\tendF++) \n\t addPhrase(sentence,startE,endE,startF,endF);\n }\n }\n }\n}\n\nvoid addPhrase( SentenceAlignment &sentence, int startE, int endE, int startF, int endF ) {\n \/\/ foreign\n \/\/ cout << \"adding ( \" << startF << \"-\" << endF << \", \" << startE << \"-\" << endE << \")\\n\"; \n\n if (onlyOutputSpanInfo) {\n cout << startF << \" \" << endF << \" \" << startE << \" \" << endE << endl;\n } else {\n\n if (phraseCount % 10000000 == 0) {\n if (phraseCount>0) {\n extractFile.close();\n extractFileInv.close();\n if (orientationFlag) extractFileOrientation.close();\n }\n char part[10];\n sprintf(part,\".part%04d\",phraseCount\/10000000);\n string fileNameExtractPart = string(fileNameExtract) + part;\n string fileNameExtractInvPart = string(fileNameExtract) + \".inv\" + part;\n string fileNameExtractOrientationPart = string(fileNameExtract) + \".o\" + part;\n extractFile.open(fileNameExtractPart.c_str());\n extractFileInv.open(fileNameExtractInvPart.c_str());\n if (orientationFlag) extractFileOrientation.open(fileNameExtractOrientationPart.c_str());\n }\n phraseCount++;\n\n for(int fi=startF;fi<=endF;fi++) {\n extractFile << sentence.foreign[fi] << \" \";\n if (orientationFlag) extractFileOrientation << sentence.foreign[fi] << \" \";\n }\n extractFile << \"||| \";\n if (orientationFlag) extractFileOrientation << \"||| \";\n\n \/\/ english\n for(int ei=startE;ei<=endE;ei++) {\n extractFile << sentence.english[ei] << \" \";\n extractFileInv << sentence.english[ei] << \" \";\n if (orientationFlag) extractFileOrientation << sentence.english[ei] << \" \";\n }\n extractFile << \"|||\";\n extractFileInv << \"||| \";\n if (orientationFlag) extractFileOrientation << \"||| \";\n\n \/\/ foreign (for inverse)\n for(int fi=startF;fi<=endF;fi++)\n extractFileInv << sentence.foreign[fi] << \" \";\n extractFileInv << \"|||\";\n\n \/\/ alignment\n for(int ei=startE;ei<=endE;ei++) \n for(int i=0;i<sentence.alignedToE[ei].size();i++) {\n int fi = sentence.alignedToE[ei][i];\n extractFile << \" \" << fi-startF << \"-\" << ei-startE;\n extractFileInv << \" \" << ei-startE << \"-\" << fi-startF;\n }\n\n if (orientationFlag) {\n\n \/\/ orientation to previous E\n bool connectedLeftTop = isAligned( sentence, startF-1, startE-1 );\n bool connectedRightTop = isAligned( sentence, endF+1, startE-1 );\n if ( connectedLeftTop && !connectedRightTop) \n extractFileOrientation << \"mono\";\n else if (!connectedLeftTop && connectedRightTop) \n extractFileOrientation << \"swap\";\n else \n extractFileOrientation << \"other\";\n \n \/\/ orientation to following E\n bool connectedLeftBottom = isAligned( sentence, startF-1, endE+1 );\n bool connectedRightBottom = isAligned( sentence, endF+1, endE+1 );\n if ( connectedLeftBottom && !connectedRightBottom) \n extractFileOrientation << \" swap\";\n else if (!connectedLeftBottom && connectedRightBottom) \n extractFileOrientation << \" mono\";\n else \n extractFileOrientation << \" other\";\n }\n\n extractFile << \"\\n\";\n extractFileInv << \"\\n\";\n if (orientationFlag) extractFileOrientation << \"\\n\";\n } \/\/ end: if (onlyOutputSpanInfo)\n}\n \nbool isAligned ( SentenceAlignment &sentence, int fi, int ei ) {\n if (ei == -1 && fi == -1) return true;\n if (ei <= -1 || fi <= -1) return false;\n if (ei == sentence.english.size() && fi == sentence.foreign.size()) return true;\n if (ei >= sentence.english.size() || fi >= sentence.foreign.size()) return false;\n for(int i=0;i<sentence.alignedToE[ei].size();i++) \n if (sentence.alignedToE[ei][i] == fi) return true;\n return false;\n}\n\n\nint SentenceAlignment::create( char englishString[], char foreignString[], char alignmentString[], int sentenceID ) {\n english = tokenize( englishString );\n foreign = tokenize( foreignString );\n \/\/ alignment = new bool[foreign.size()*english.size()];\n \/\/ alignment = (bool**) calloc(english.size()*foreign.size(),sizeof(bool)); \/\/ is this right?\n \n if (english.size() == 0 || foreign.size() == 0) {\n cerr << \"no english (\" << english.size() << \") or foreign (\" << foreign.size() << \") words << end insentence \" << sentenceID << endl;\n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n \/\/ cout << \"english.size = \" << english.size() << endl;\n \/\/ cout << \"foreign.size = \" << foreign.size() << endl;\n\n \/\/ cout << \"xxx\\n\";\n for(int i=0; i<foreign.size(); i++) {\n \/\/ cout << \"i\" << i << endl;\n alignedCountF.push_back( 0 );\n }\n for(int i=0; i<english.size(); i++) {\n vector< int > dummy;\n alignedToE.push_back( dummy );\n }\n \/\/ cout << \"\\nscanning...\\n\";\n\n vector<string> alignmentSequence = tokenize( alignmentString );\n for(int i=0; i<alignmentSequence.size(); i++) {\n int e,f;\n \/\/ cout << \"scaning \" << alignmentSequence[i].c_str() << endl;\n if (! sscanf(alignmentSequence[i].c_str(), \"%d-%d\", &f, &e)) {\n cerr << \"WARNING: \" << alignmentSequence[i] << \" is a bad alignment point in sentnce \" << sentenceID << endl; \n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n \/\/ cout << \"alignmentSequence[i] \" << alignmentSequence[i] << \" is \" << f << \", \" << e << endl;\n if (e >= english.size() || f >= foreign.size()) { \n cerr << \"WARNING: sentence \" << sentenceID << \" has alignment point (\" << f << \", \" << e << \") out of bounds (\" << foreign.size() << \", \" << english.size() << \")\\n\";\n cerr << \"E: \" << englishString << endl << \"F: \" << foreignString << endl;\n return 0;\n }\n alignedToE[e].push_back( f );\n alignedCountF[f]++;\n }\n return 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix other tile sizes<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"ROOT\/RTaskArena.hxx\"\n#include \"TError.h\"\n#include \"TROOT.h\"\n#include \"TThread.h\"\n#include <fstream>\n#include <sys\/stat.h>\n#include <thread>\n#include \"tbb\/task_arena.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ \\class ROOT::Internal::RTaskArenaWrapper\n\/\/\/ \\ingroup Parallelism\n\/\/\/ \\brief Wrapper over tbb::task_arena\n\/\/\/\n\/\/\/ This class is a wrapper over tbb::task_arena, in order to keep\n\/\/\/ TBB away from ROOT's headers. We keep a single global instance,\n\/\/\/ obtained with `ROOT::Internal::GetGlobalTaskArena()`, to be used by any\n\/\/\/ parallel ROOT class with TBB as a backend. This has several advantages:\n\/\/\/\n\/\/\/ - Provides a unique interface to the TBB scheduler: TThreadExecutor,\n\/\/\/ IMT and any class relying on TBB will get a pointer to the scheduler\n\/\/\/ through `ROOT::Internal::GetGlobalTaskArena()`, which will return a\n\/\/\/ reference to the only pointer to the TBB scheduler that will be\n\/\/\/ active in any ROOT Process\n\/\/\/ - Solves multiple undefined behaviors. Guaranteeing that all classes\n\/\/\/ use the same task arena avoids interferences and undefined behavior\n\/\/\/ by providing a single instance of the tbb::task_arena and automated\n\/\/\/ bookkeeping, instantiation and destruction.\n\/\/\/\n\/\/\/ #### Examples:\n\/\/\/ ~~~{.cpp}\n\/\/\/ root[] auto gTA = ROOT::Internal::GetGlobalTaskArena() \/\/get a shared_ptr to the global arena\n\/\/\/ root[] gTA->InitGlobalTaskArena(nWorkers) \/\/ Initialize the global arena and enable Thread Safety in ROOT\n\/\/\/ root[] gTA->TaskArenaSize() \/\/ Get the current size of the arena (number of worker threads)\n\/\/\/ root[] gTA->Access() \/\/std::unique_ptr to the internal tbb::task_arena for interacting directly with it (needed to call operations such as execute)\n\/\/\/ root[] root[] gTA->Access()->max_concurrency() \/\/ call to tbb::task_arena::max_concurrency()\n\/\/\/ ~~~\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns the available number of logical cores.\n\/\/\/\n\/\/\/ - Checks if there is CFS bandwidth control in place (linux, via cgroups,\n\/\/\/ assuming standard paths)\n\/\/\/ - Otherwise, returns the number of logical cores provided by\n\/\/\/ std::thread::hardware_concurrency()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic Int_t LogicalCPUBandwithControl()\n{\n#ifdef R__LINUX\n \/\/ Check for CFS bandwith control\n std::ifstream f;\n std::string quotaFile(\"\/sys\/fs\/cgroup\/cpuacct\/cpu.cfs_quota_us\");\n struct stat buffer;\n \/\/ Does the file exist?\n if(stat(quotaFile.c_str(), &buffer) == 0) {\n f.open(quotaFile);\n float cfs_quota;\n f>>cfs_quota;\n f.close();\n if(cfs_quota > 0) {\n std::string periodFile(\"\/sys\/fs\/cgroup\/cpuacct\/cpu.cfs_period_us\");\n f.open(periodFile);\n float cfs_period;\n f>>cfs_period;\n f.close();\n return static_cast<int>(std::ceil(cfs_quota\/cfs_period));\n }\n }\n#endif\n return std::thread::hardware_concurrency();\n}\n\nnamespace ROOT{\nnamespace Internal {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Initializes the tbb::task_arena within RTaskArenaWrapper\n\/\/\/\n\/\/\/ * Can't be reinitialized\n\/\/\/ * Checks for CPU bandwidth control and avoids oversubscribing\n\/\/\/ * If no BC in place and maxConcurrency<1, defaults to the default tbb number of threads,\n\/\/\/ which is CPU affinity aware\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRTaskArenaWrapper::RTaskArenaWrapper(unsigned maxConcurrency): fTBBArena(new tbb::task_arena{})\n{\n if (!fTBBArena->is_active()) {\n unsigned tbbDefaultNumberThreads = fTBBArena->max_concurrency(); \/\/ not initialized, automatic state\n maxConcurrency = maxConcurrency > 0 ? std::min(maxConcurrency, tbbDefaultNumberThreads) : tbbDefaultNumberThreads;\n unsigned bcCpus = LogicalCPUBandwithControl();\n if (maxConcurrency>bcCpus) {\n Warning(\"RTaskArenaWrapper\", \"CPU Bandwith Control Active. Proceeding with %d threads accordingly\",\n bcCpus);\n maxConcurrency = bcCpus;\n }\n fTBBArena->initialize(maxConcurrency);\n fNWorkers = maxConcurrency;\n ROOT::EnableThreadSafety();\n } else {\n unsigned current = fTBBArena->max_concurrency();\n if (maxConcurrency && (current != maxConcurrency)) {\n Warning(\"RTaskArenaWrapper\", \"There's already an active task arena. Proceeding with the current %d threads\",\n current);\n }\n }\n}\n\nRTaskArenaWrapper::~RTaskArenaWrapper()\n{\n fNWorkers = 0u;\n}\n\nunsigned RTaskArenaWrapper::fNWorkers = 0u;\n\nunsigned RTaskArenaWrapper::TaskArenaSize()\n{\n return fNWorkers;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Provides access to the wrapped tbb::task_arena\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::unique_ptr<tbb::task_arena> &RTaskArenaWrapper::Access()\n{\n return fTBBArena;\n}\n\n\nstd::shared_ptr<ROOT::Internal::RTaskArenaWrapper> GetGlobalTaskArena(unsigned maxConcurrency)\n{\n static std::weak_ptr<ROOT::Internal::RTaskArenaWrapper> weak_GTAWrapper;\n if (weak_GTAWrapper.expired()) {\n std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> shared_GTAWrapper(new ROOT::Internal::RTaskArenaWrapper(maxConcurrency));\n weak_GTAWrapper = shared_GTAWrapper;\n return weak_GTAWrapper.lock();\n }\n\n return weak_GTAWrapper.lock();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n<commit_msg>make variables const<commit_after>#include \"ROOT\/RTaskArena.hxx\"\n#include \"TError.h\"\n#include \"TROOT.h\"\n#include \"TThread.h\"\n#include <fstream>\n#include <sys\/stat.h>\n#include <thread>\n#include \"tbb\/task_arena.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ \\class ROOT::Internal::RTaskArenaWrapper\n\/\/\/ \\ingroup Parallelism\n\/\/\/ \\brief Wrapper over tbb::task_arena\n\/\/\/\n\/\/\/ This class is a wrapper over tbb::task_arena, in order to keep\n\/\/\/ TBB away from ROOT's headers. We keep a single global instance,\n\/\/\/ obtained with `ROOT::Internal::GetGlobalTaskArena()`, to be used by any\n\/\/\/ parallel ROOT class with TBB as a backend. This has several advantages:\n\/\/\/\n\/\/\/ - Provides a unique interface to the TBB scheduler: TThreadExecutor,\n\/\/\/ IMT and any class relying on TBB will get a pointer to the scheduler\n\/\/\/ through `ROOT::Internal::GetGlobalTaskArena()`, which will return a\n\/\/\/ reference to the only pointer to the TBB scheduler that will be\n\/\/\/ active in any ROOT Process\n\/\/\/ - Solves multiple undefined behaviors. Guaranteeing that all classes\n\/\/\/ use the same task arena avoids interferences and undefined behavior\n\/\/\/ by providing a single instance of the tbb::task_arena and automated\n\/\/\/ bookkeeping, instantiation and destruction.\n\/\/\/\n\/\/\/ #### Examples:\n\/\/\/ ~~~{.cpp}\n\/\/\/ root[] auto gTA = ROOT::Internal::GetGlobalTaskArena() \/\/get a shared_ptr to the global arena\n\/\/\/ root[] gTA->InitGlobalTaskArena(nWorkers) \/\/ Initialize the global arena and enable Thread Safety in ROOT\n\/\/\/ root[] gTA->TaskArenaSize() \/\/ Get the current size of the arena (number of worker threads)\n\/\/\/ root[] gTA->Access() \/\/std::unique_ptr to the internal tbb::task_arena for interacting directly with it (needed to call operations such as execute)\n\/\/\/ root[] root[] gTA->Access()->max_concurrency() \/\/ call to tbb::task_arena::max_concurrency()\n\/\/\/ ~~~\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns the available number of logical cores.\n\/\/\/\n\/\/\/ - Checks if there is CFS bandwidth control in place (linux, via cgroups,\n\/\/\/ assuming standard paths)\n\/\/\/ - Otherwise, returns the number of logical cores provided by\n\/\/\/ std::thread::hardware_concurrency()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic Int_t LogicalCPUBandwithControl()\n{\n#ifdef R__LINUX\n \/\/ Check for CFS bandwith control\n std::ifstream f;\n std::string quotaFile(\"\/sys\/fs\/cgroup\/cpuacct\/cpu.cfs_quota_us\");\n struct stat buffer;\n \/\/ Does the file exist?\n if(stat(quotaFile.c_str(), &buffer) == 0) {\n f.open(quotaFile);\n float cfs_quota;\n f>>cfs_quota;\n f.close();\n if(cfs_quota > 0) {\n std::string periodFile(\"\/sys\/fs\/cgroup\/cpuacct\/cpu.cfs_period_us\");\n f.open(periodFile);\n float cfs_period;\n f>>cfs_period;\n f.close();\n return static_cast<int>(std::ceil(cfs_quota\/cfs_period));\n }\n }\n#endif\n return std::thread::hardware_concurrency();\n}\n\nnamespace ROOT{\nnamespace Internal {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Initializes the tbb::task_arena within RTaskArenaWrapper\n\/\/\/\n\/\/\/ * Can't be reinitialized\n\/\/\/ * Checks for CPU bandwidth control and avoids oversubscribing\n\/\/\/ * If no BC in place and maxConcurrency<1, defaults to the default tbb number of threads,\n\/\/\/ which is CPU affinity aware\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRTaskArenaWrapper::RTaskArenaWrapper(unsigned maxConcurrency): fTBBArena(new tbb::task_arena{})\n{\n if (!fTBBArena->is_active()) {\n const unsigned tbbDefaultNumberThreads = fTBBArena->max_concurrency(); \/\/ not initialized, automatic state\n maxConcurrency = maxConcurrency > 0 ? std::min(maxConcurrency, tbbDefaultNumberThreads) : tbbDefaultNumberThreads;\n const unsigned bcCpus = LogicalCPUBandwithControl();\n if (maxConcurrency>bcCpus) {\n Warning(\"RTaskArenaWrapper\", \"CPU Bandwith Control Active. Proceeding with %d threads accordingly\",\n bcCpus);\n maxConcurrency = bcCpus;\n }\n fTBBArena->initialize(maxConcurrency);\n fNWorkers = maxConcurrency;\n ROOT::EnableThreadSafety();\n } else {\n const unsigned current = fTBBArena->max_concurrency();\n if (maxConcurrency && (current != maxConcurrency)) {\n Warning(\"RTaskArenaWrapper\", \"There's already an active task arena. Proceeding with the current %d threads\",\n current);\n }\n }\n}\n\nRTaskArenaWrapper::~RTaskArenaWrapper()\n{\n fNWorkers = 0u;\n}\n\nunsigned RTaskArenaWrapper::fNWorkers = 0u;\n\nunsigned RTaskArenaWrapper::TaskArenaSize()\n{\n return fNWorkers;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Provides access to the wrapped tbb::task_arena\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::unique_ptr<tbb::task_arena> &RTaskArenaWrapper::Access()\n{\n return fTBBArena;\n}\n\n\nstd::shared_ptr<ROOT::Internal::RTaskArenaWrapper> GetGlobalTaskArena(unsigned maxConcurrency)\n{\n static std::weak_ptr<ROOT::Internal::RTaskArenaWrapper> weak_GTAWrapper;\n if (weak_GTAWrapper.expired()) {\n std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> shared_GTAWrapper(new ROOT::Internal::RTaskArenaWrapper(maxConcurrency));\n weak_GTAWrapper = shared_GTAWrapper;\n return weak_GTAWrapper.lock();\n }\n\n return weak_GTAWrapper.lock();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <unistd.h>\nusing namespace std;\n\n#include \"tinyxml2\/tinyxml2.h\"\nusing namespace tinyxml2;\n\n#include \"pretty_printer.h\"\n\n\/*\n * Usage:\n * \t$ pp \"xml string\"\n * \t$ xml_output_program | pp\n *\/\n\nint main(int argc, char* argv[]) {\n\n\t\/*\n\t * No args.\n\t * Read XML input from STDIN (used for piping)\n\t *\/\n\tif(argc == 1) { \n FILE* fp = stdin;\n if(!isatty(fileno(fp))){ \/\/Check STDIN for input\n\t\t\tstring str;\n\t\t\tchar temp;\n\t\t\twhile(!cin.eof()) { \/\/Iterate file pointer until EOF\n\t\t\t\tcin.get(temp); \/\/Get char\n\t\t\t\tstr += temp; \/\/append char to data string\n\t\t\t}\n\t\t\tprint_xml(str.c_str()); \/\/convert str to const char*, format, & print\n } else { \/\/pp called with no args & no data on STDIN\n \targ_error();\n\t\t}\n\t}\n\n\t\/*\n\t * Single argument should be XML data\n\t *\/\n\telse if(argc == 2) {\n\t\tprint_xml(argv[1]); \/\/format & print argument\n\t} else { \/\/Something else\n\t\targ_error();\n\t}\n}\n\n\/*\n * Outputs \"usage\" message\n *\/\nvoid arg_error(void) {\n\tcout << \"Argument error, check the README.\\nUsage:\\n\";\n\tcout << \"\\tpp \\\"<Hello>World<\/Hello>\\\"\\n\\tprogram_outputs_xml args | pp\\n\";\n}\n\n\/*\n * Formats and prints document\n * Yay tinyxml2!\n *\/\nvoid print_xml(const char* cstr) {\n\tXMLDocument doc;\n\tXMLPrinter printer;\n\n\tif (doc.Parse(cstr) == XML_SUCCESS) {\n\t\tXMLPrinter printer;\n\t\tdoc.Print(&printer);\n\t\tcout << printer.CStr();\n\t} else {\n\t\tcout << \"Error parsing XML document.\\n\";\n\t}\n}\n<commit_msg>Fix'd formatting?<commit_after>#include <iostream>\n#include <string>\n#include <unistd.h>\nusing namespace std;\n\n#include \"tinyxml2\/tinyxml2.h\"\nusing namespace tinyxml2;\n\n#include \"pretty_printer.h\"\n\n\/*\n * Usage:\n * \t$ pp \"xml string\"\n * \t$ xml_output_program | pp\n *\/\n\nint main(int argc, char* argv[]) {\n\n\t\/*\n\t * No args.\n\t * Read XML input from STDIN (used for piping)\n\t *\/\n\tif(argc == 1) { \n\t\tFILE* fp = stdin;\n\t\tif(!isatty(fileno(fp))){ \/\/Check STDIN for input\n\t\t\tstring str;\n\t\t\tchar temp;\n\t\t\twhile(!cin.eof()) { \/\/Iterate file pointer until EOF\n\t\t\t\tcin.get(temp); \/\/Get char\n\t\t\t\tstr += temp; \/\/append char to data string\n\t\t\t}\n\t\t\tprint_xml(str.c_str()); \/\/convert str to const char*, format, & print\n\t\t} else { \/\/pp called with no args & no data on STDIN\n\t\t\targ_error();\n\t\t}\n\t}\n\n\t\/*\n\t * Single argument should be XML data\n\t *\/\n\telse if(argc == 2) {\n\t\tprint_xml(argv[1]); \/\/format & print argument\n\t} else { \/\/Something else\n\t\targ_error();\n\t}\n}\n\n\/*\n * Outputs \"usage\" message\n *\/\nvoid arg_error(void) {\n\tcout << \"Argument error, check the README.\\nUsage:\\n\";\n\tcout << \"\\tpp \\\"<Hello>World<\/Hello>\\\"\\n\\tprogram_outputs_xml args | pp\\n\";\n}\n\n\/*\n * Formats and prints document\n * Yay tinyxml2!\n *\/\nvoid print_xml(const char* cstr) {\n\tXMLDocument doc;\n\tXMLPrinter printer;\n\n\tif (doc.Parse(cstr) == XML_SUCCESS) {\n\t\tXMLPrinter printer;\n\t\tdoc.Print(&printer);\n\t\tcout << printer.CStr();\n\t} else {\n\t\tcout << \"Error parsing XML document.\\n\";\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/Copyright (c) 2019 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <gtest\/gtest.h>\n#include <clipper.hpp>\n#include <..\/src\/utils\/AABB.h>\n#include <..\/src\/utils\/AABB3D.h>\n#include <..\/src\/utils\/polygon.h>\n\nnamespace cura\n{\n inline AABB3D toBox(const coord_t& x, const coord_t& y, const coord_t& z)\n {\n const Point3 pt(x, y, z);\n return AABB3D(pt, pt);\n }\n\n TEST(AABB3DTest, TestConstructEmpty)\n {\n AABB3D empty_box;\n\n EXPECT_FALSE(empty_box.hit(toBox(0, 0, 0))) << \"Empty box shouldn't contain anything.\";\n EXPECT_FALSE(empty_box.hit(empty_box)) << \"Empty boxes shouldn't intersect.\";\n\n empty_box.include(Point3(-10, -5, -2));\n empty_box.include(Point3(5, 10, 2));\n\n EXPECT_TRUE(empty_box.hit(toBox(0, 0, 0))) << \"The previously empty box should now contain this point.\";\n EXPECT_FALSE(empty_box.hit(toBox(11, 5, 0))) << \"The previously empty box should now still not contain this point.\";\n }\n\n TEST(AABB3DTest, TestConstructPoint)\n {\n AABB3D point_box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n EXPECT_TRUE(point_box.hit(toBox(0, 0, 0))) << \"Box constructed from points around the origin should contain it.\";\n EXPECT_FALSE(point_box.hit(toBox(11, 5, 0))) << \"The box shouldn't contain a point outside of it.\";\n }\n\n TEST(AABB3DTest, TestConstructInverse)\n {\n AABB3D inverse_box(Point3(5, 10, 2), Point3(-10, -5, -2));\n\n EXPECT_FALSE(inverse_box.hit(toBox(0, 0, 0))) << \"'Inverse' box shouldn't contain anything.\";\n EXPECT_FALSE(inverse_box.hit(inverse_box)) << \"'Inverse' boxes shouldn't intersect.\";\n\n inverse_box.include(Point3(-5, -2, -1));\n inverse_box.include(Point3(2, 5, 1));\n\n EXPECT_TRUE(inverse_box.hit(toBox(0, 0, 0))) << \"The previously 'inverse' box should now contain this point.\";\n EXPECT_FALSE(inverse_box.hit(toBox(4, 8, -1))) << \"The previously 'inverse' box should now still not contain this point.\";\n }\n\n TEST(AABB3DTest, TestHit)\n {\n AABB3D box_a(Point3(-10, -5, -2), Point3(5, 10, 2));\n AABB3D box_b(Point3(4, 9, 0), Point3(12, 12, 12));\n AABB3D box_c(Point3(11, 11, 11), Point3(14, 14, 14));\n\n EXPECT_TRUE(box_a.hit(box_a)) << \"Box should overlap itself.\";\n\n EXPECT_TRUE(box_a.hit(box_b)) << \"These boxes should overlap (case AB).\";\n EXPECT_TRUE(box_b.hit(box_a)) << \"These boxes should overlap (case BA).\";\n EXPECT_TRUE(box_b.hit(box_c)) << \"These boxes should overlap (case BC).\";\n EXPECT_TRUE(box_c.hit(box_b)) << \"These boxes should overlap (case CB).\";\n\n EXPECT_FALSE(box_a.hit(box_c)) << \"These boxes should not overlap (case AC).\";\n EXPECT_FALSE(box_c.hit(box_a)) << \"These boxes should not overlap (case CA).\";\n\n AABB3D box_d(Point3(3, 10, 2), Point3(12, 12, 12));\n AABB3D box_e(Point3(5, 10, 2), Point3(12, 12, 12));\n\n EXPECT_TRUE(box_a.hit(box_d)) << \"Overlap-check is inclusive (case AD).\";\n EXPECT_TRUE(box_d.hit(box_a)) << \"Overlap-check is inclusive (case DA).\";\n EXPECT_TRUE(box_a.hit(box_e)) << \"Overlap-check is inclusive (case AE).\";\n EXPECT_TRUE(box_e.hit(box_a)) << \"Overlap-check is inclusive (case EA).\";\n }\n\n TEST(AABB3DTest, TestGetMiddle)\n {\n AABB3D box_a(Point3(-10, -6, -5), Point3(6, 10, 3));\n AABB3D box_b(Point3(4, 10, 2), Point3(12, 12, 12));\n\n EXPECT_EQ(box_a.getMiddle(), Point3(-2, 2, -1)) << \"The middle of the AABB should be this point (case A).\";\n EXPECT_EQ(box_b.getMiddle(), Point3(8, 11, 7)) << \"The middle of the AABB should be this point (case B).\";\n }\n\n TEST(AABB3DTest, TestInclude)\n {\n AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));\n\n EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << \"The unexpanded (via include\/point) box should not contain a point in the (future) expanded area.\";\n\n box.include(Point3(0, 0, 0));\n\n EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << \"The expanded (via include\/point) box should contain a point in the expanded area.\";\n EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << \"The unexpanded (via include\/other) box should not contain a point in the (future) expanded area.\";\n\n box.include(AABB3D(Point3(7, 9, -2), Point3(8, 10, 0)));\n\n EXPECT_TRUE(box.hit(toBox(6, 9, -1))) << \"The expanded (via include\/other) box should contain a point in the expanded area.\";\n\n box.includeZ(-6);\n\n EXPECT_TRUE(box.hit(toBox(6, 9, -3))) << \"The expanded (via includeZ\/scalar) box should contain a point in the expanded area.\";\n }\n\n TEST(AABB3DTest, TestOffset)\n {\n AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));\n\n EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << \"The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.\";\n\n box.offset(Point3(-2, -2, -2));\n\n EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << \"The expanded (via offset-3D) box should contain a point in the expanded area.\";\n EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << \"The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.\";\n\n box.offset(Point(-2, -2));\n\n EXPECT_TRUE(box.hit(toBox(-1, -1, 0))) << \"The expanded (via offset-2D) box should contain a point in the expanded area.\";\n }\n\n TEST(AABB3DTest, TestExpand)\n {\n AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n EXPECT_FALSE(box.hit(toBox(6, 11, 3))) << \"Before expanding, the box shouldn't contain this point.\";\n\n box.expandXY(2);\n\n EXPECT_TRUE(box.hit(toBox(6, 11, 1))) << \"After expanding, the box should contain this point.\";\n\n box.expandXY(-2);\n\n EXPECT_FALSE(box.hit(toBox(6, 11, 1))) << \"After shrinking, the box shouldn't contain this point anymore.\";\n }\n\n TEST(AABB3DTest, TestFlatten)\n {\n AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n AABB flat = box.flatten();\n\n EXPECT_TRUE(flat.contains(Point(1, 1))) << \"The flattened box should contain this point.\";\n EXPECT_FALSE(flat.contains(Point(-11, 3))) << \"The flattened box shouldn't contain this point.\";\n }\n}\n<commit_msg>Use include double quotes for local header files<commit_after>\/\/Copyright (c) 2019 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <gtest\/gtest.h>\n#include <clipper.hpp>\n\n#include \"..\/src\/utils\/AABB.h\"\n#include \"..\/src\/utils\/AABB3D.h\"\n#include \"..\/src\/utils\/polygon.h\"\n\nnamespace cura\n{\n inline AABB3D toBox(const coord_t& x, const coord_t& y, const coord_t& z)\n {\n const Point3 pt(x, y, z);\n return AABB3D(pt, pt);\n }\n\n TEST(AABB3DTest, TestConstructEmpty)\n {\n AABB3D empty_box;\n\n EXPECT_FALSE(empty_box.hit(toBox(0, 0, 0))) << \"Empty box shouldn't contain anything.\";\n EXPECT_FALSE(empty_box.hit(empty_box)) << \"Empty boxes shouldn't intersect.\";\n\n empty_box.include(Point3(-10, -5, -2));\n empty_box.include(Point3(5, 10, 2));\n\n EXPECT_TRUE(empty_box.hit(toBox(0, 0, 0))) << \"The previously empty box should now contain this point.\";\n EXPECT_FALSE(empty_box.hit(toBox(11, 5, 0))) << \"The previously empty box should now still not contain this point.\";\n }\n\n TEST(AABB3DTest, TestConstructPoint)\n {\n AABB3D point_box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n EXPECT_TRUE(point_box.hit(toBox(0, 0, 0))) << \"Box constructed from points around the origin should contain it.\";\n EXPECT_FALSE(point_box.hit(toBox(11, 5, 0))) << \"The box shouldn't contain a point outside of it.\";\n }\n\n TEST(AABB3DTest, TestConstructInverse)\n {\n AABB3D inverse_box(Point3(5, 10, 2), Point3(-10, -5, -2));\n\n EXPECT_FALSE(inverse_box.hit(toBox(0, 0, 0))) << \"'Inverse' box shouldn't contain anything.\";\n EXPECT_FALSE(inverse_box.hit(inverse_box)) << \"'Inverse' boxes shouldn't intersect.\";\n\n inverse_box.include(Point3(-5, -2, -1));\n inverse_box.include(Point3(2, 5, 1));\n\n EXPECT_TRUE(inverse_box.hit(toBox(0, 0, 0))) << \"The previously 'inverse' box should now contain this point.\";\n EXPECT_FALSE(inverse_box.hit(toBox(4, 8, -1))) << \"The previously 'inverse' box should now still not contain this point.\";\n }\n\n TEST(AABB3DTest, TestHit)\n {\n AABB3D box_a(Point3(-10, -5, -2), Point3(5, 10, 2));\n AABB3D box_b(Point3(4, 9, 0), Point3(12, 12, 12));\n AABB3D box_c(Point3(11, 11, 11), Point3(14, 14, 14));\n\n EXPECT_TRUE(box_a.hit(box_a)) << \"Box should overlap itself.\";\n\n EXPECT_TRUE(box_a.hit(box_b)) << \"These boxes should overlap (case AB).\";\n EXPECT_TRUE(box_b.hit(box_a)) << \"These boxes should overlap (case BA).\";\n EXPECT_TRUE(box_b.hit(box_c)) << \"These boxes should overlap (case BC).\";\n EXPECT_TRUE(box_c.hit(box_b)) << \"These boxes should overlap (case CB).\";\n\n EXPECT_FALSE(box_a.hit(box_c)) << \"These boxes should not overlap (case AC).\";\n EXPECT_FALSE(box_c.hit(box_a)) << \"These boxes should not overlap (case CA).\";\n\n AABB3D box_d(Point3(3, 10, 2), Point3(12, 12, 12));\n AABB3D box_e(Point3(5, 10, 2), Point3(12, 12, 12));\n\n EXPECT_TRUE(box_a.hit(box_d)) << \"Overlap-check is inclusive (case AD).\";\n EXPECT_TRUE(box_d.hit(box_a)) << \"Overlap-check is inclusive (case DA).\";\n EXPECT_TRUE(box_a.hit(box_e)) << \"Overlap-check is inclusive (case AE).\";\n EXPECT_TRUE(box_e.hit(box_a)) << \"Overlap-check is inclusive (case EA).\";\n }\n\n TEST(AABB3DTest, TestGetMiddle)\n {\n AABB3D box_a(Point3(-10, -6, -5), Point3(6, 10, 3));\n AABB3D box_b(Point3(4, 10, 2), Point3(12, 12, 12));\n\n EXPECT_EQ(box_a.getMiddle(), Point3(-2, 2, -1)) << \"The middle of the AABB should be this point (case A).\";\n EXPECT_EQ(box_b.getMiddle(), Point3(8, 11, 7)) << \"The middle of the AABB should be this point (case B).\";\n }\n\n TEST(AABB3DTest, TestInclude)\n {\n AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));\n\n EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << \"The unexpanded (via include\/point) box should not contain a point in the (future) expanded area.\";\n\n box.include(Point3(0, 0, 0));\n\n EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << \"The expanded (via include\/point) box should contain a point in the expanded area.\";\n EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << \"The unexpanded (via include\/other) box should not contain a point in the (future) expanded area.\";\n\n box.include(AABB3D(Point3(7, 9, -2), Point3(8, 10, 0)));\n\n EXPECT_TRUE(box.hit(toBox(6, 9, -1))) << \"The expanded (via include\/other) box should contain a point in the expanded area.\";\n\n box.includeZ(-6);\n\n EXPECT_TRUE(box.hit(toBox(6, 9, -3))) << \"The expanded (via includeZ\/scalar) box should contain a point in the expanded area.\";\n }\n\n TEST(AABB3DTest, TestOffset)\n {\n AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));\n\n EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << \"The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.\";\n\n box.offset(Point3(-2, -2, -2));\n\n EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << \"The expanded (via offset-3D) box should contain a point in the expanded area.\";\n EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << \"The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.\";\n\n box.offset(Point(-2, -2));\n\n EXPECT_TRUE(box.hit(toBox(-1, -1, 0))) << \"The expanded (via offset-2D) box should contain a point in the expanded area.\";\n }\n\n TEST(AABB3DTest, TestExpand)\n {\n AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n EXPECT_FALSE(box.hit(toBox(6, 11, 3))) << \"Before expanding, the box shouldn't contain this point.\";\n\n box.expandXY(2);\n\n EXPECT_TRUE(box.hit(toBox(6, 11, 1))) << \"After expanding, the box should contain this point.\";\n\n box.expandXY(-2);\n\n EXPECT_FALSE(box.hit(toBox(6, 11, 1))) << \"After shrinking, the box shouldn't contain this point anymore.\";\n }\n\n TEST(AABB3DTest, TestFlatten)\n {\n AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));\n\n AABB flat = box.flatten();\n\n EXPECT_TRUE(flat.contains(Point(1, 1))) << \"The flattened box should contain this point.\";\n EXPECT_FALSE(flat.contains(Point(-11, 3))) << \"The flattened box shouldn't contain this point.\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Code for basic data manipulation\n\/\/\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\n#define ERROR \"Error: \"\n#define MAX_WORD_LEN 100\n\nstruct node{\t\t\t\t\/\/ node data structure for DLL\n\tchar word[MAX_WORD_LEN];\n\tnode * next;\n\tnode * prev;\n};\n\n\/*node**\/int getWords(char * infile)\n{\n\tifstream file (infile);\t\t\t\t\t\t\t\t\/\/ open file into an input file stream\n\tif(file.is_open()){\n\t\tstring word;\n\t\twhile(file >> word){\t\t\t\t\t\t\t\/\/ stream operator parses on white space (seperating words)\n\t\t\ttransform(word.begin(), word.end(), word.begin(), ::tolower);\t\/\/ make sure all words are lower case\n\t\t\tcout << word << endl;\n\t\t\t\/\/TODO sort the words (as chars), in order, into a dll\n\t\t}\n\t\tfile.close();\n\t}else{\n\t\tcout << ERROR << \"cannot open file\" << endl;\n\t\treturn 0;\n\t}\n\treturn -1;\n}\n\nvoid printDLL_forward(node * head)\n{\n\tnode * current = head;\n\twhile(current != NULL ){\t\t\/\/ rotate threw list untill end\n\t\tcout << current->word << \", \"; \/\/ print out the current word\n\t\tcurrent = current->next;\t\/\/ set the next node to be the current\n\t}\n\tcout << endl;\n}\n\nvoid printDLL_backward(node * head)\n{\n\tnode * current = head;\n\twhile(current->next != NULL){\t\t\/\/ find the tail\n\t\tcurrent = current->next;\n\t}\n\n\twhile(current != NULL){\n\t\tcout << current->word << \", \";\n\t\tcurrent = current->prev;\n\t}\n\tcout << endl;\n}\n\nint main(int argc, char * argv[])\n{\n\t\/\/ get file input\n\tif(argc != 2){\n\t\tcout << ERROR << \"Please include file to open\" << endl;\n\t\treturn -1;\n\t}\n\t\n\tgetWords(argv[1]);\n\t\/\/ get doubly linked list of words\n\/\/\tnode* head;\n\/\/\n\/\/\tcout << \"Test 1: Words in order\" << endl;\n\/\/\n\/\/\tcout << \"Test 2: Words in reverse order\" << endl;\n\/\/\n\/\/\tcout << \"Test 3: Remove the 2nd item\" << endl;\n\/\/\n\/\/\tcout << \"Test 4: Words in order\" << endl;\n\n\treturn 0;\n}\n\n<commit_msg>implemented DLL to store words: works!<commit_after>\/\/ Code for basic data manipulation\n\/\/\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstring>\n#include <algorithm>\nusing namespace std;\n\n#define ERROR \"Error: \"\n#define MAX_WORD_LEN 100\n\nstruct node{\t\t\t\t\/\/ node data structure for DLL\n\tchar word[MAX_WORD_LEN];\n\tnode * next;\n\tnode * prev;\n};\n\nnode * getWords(char * infile)\n{\n\tnode * head = NULL; \n\tnode * prev = NULL;\n\n\tifstream file (infile);\t\t\t\t\t\t\t\t\/\/ open file into an input file stream\n\tif(file.is_open()){\n\t\tstring word;\n\t\twhile(file >> word){\t\t\t\t\t\t\t\/\/ stream operator parses on white space (seperating words)\n\t\t\ttransform(word.begin(), word.end(), word.begin(), ::tolower);\t\/\/ make sure all words are lower case\n\n\t\t\tnode * current;\t\t\t\t\/\/ create a new node pointer\n\t\t\tcurrent = new node;\t\t\t\/\/ allocate memory for the node\n\n\t\t\tstrcpy(current->word, word.c_str());\t\/\/ copy the lower case word into the node\n\t\t\tif(prev != NULL){\n\t\t\t \tprev->next = current;\t\t\/\/ set next, prev pointers\n\t\t\t\tcurrent->prev = prev;\n\t\t\t}\n\n\t\t\tif(head == NULL) head = current;\t\/\/ set head node pointer\n\t\t\tprev = current;\t\t\t\t\/\/ remember the last node\n\t\t}\n\t\tfile.close();\n\t}else{\n\t\tcout << ERROR << \"cannot open file\" << endl;\n\t\treturn NULL;\n\t}\n\treturn head;\n}\n\nvoid printDLL_forward(node * head)\n{\n\tnode * current = head;\n\twhile(current->next != NULL ){\t\t\/\/ rotate threw list untill end\n\t\tcout << current->word << \", \"; \/\/ print out the current word\n\t\tcurrent = current->next;\t\/\/ set the next node to be the current\n\t}\n\tcout << current->word << endl;\n}\n\nvoid printDLL_backward(node * head)\n{\n\tnode * current = head;\n\twhile(current->next != NULL){\t\t\/\/ find the tail\n\t\tcurrent = current->next;\n\t}\n\n\twhile(current != NULL){\n\t\tcout << current->word << \", \";\n\t\tcurrent = current->prev;\n\t}\n\tcout << endl;\n}\n\nint main(int argc, char * argv[])\n{\n\t\/\/ get file input\n\tif(argc != 2){\n\t\tcout << ERROR << \"Please include file to open\" << endl;\n\t\treturn -1;\n\t}\n\tnode * head = getWords(argv[1]);\n\t\n\tcout << \"Test 1: Words in order\" << endl;\n\tprintDLL_forward(head);\n\n\/\/\tcout << \"Test 2: Words in reverse order\" << endl;\n\/\/\n\/\/\tcout << \"Test 3: Remove the 2nd item\" << endl;\n\/\/\n\/\/\tcout << \"Test 4: Words in order\" << endl;\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <avr\/io.h>\n#include <avr\/sleep.h>\n#include <avr\/interrupt.h>\n#include <interrupt\/PCINT0.hpp>\n#include <common.hpp>\n#include <port.hpp>\n#include <sensor.hpp>\n\ntypedef Pin<Port<A>, 3> GDO0;\n\nstatic void write_eeprom(int addr, unsigned char value)\n{\n\tEECR = 0;\n\n\tEEAR = addr;\n\tEEDR = value;\n\n\tEECR |= _BV(EEMPE);\n\tEECR |= _BV(EEPE);\n\n\tloop_until_bit_is_clear(EECR, EEPE);\n}\n\nstatic unsigned int eeprom_addr = 0;\n\nstatic void mark_eeprom_eof()\n{\n\twrite_eeprom(eeprom_addr, 0xff);\n}\n\nstatic void receive()\n{\n\twhile (GDO0::is_set()) {\n\t\tradio::select();\n\t\tunsigned char rxbytes = radio::status<radio::RXBYTES>();\n\t\tunsigned char d[rxbytes];\n\t\tradio::read_rxfifo(d, rxbytes);\n\t\tif (rxbytes >= 2 && rxbytes <= 32 && rxbytes == d[0] + 3) {\n\t\t\tSensorValue<RSSI>::encode(static_cast<int>(d[rxbytes - 2]) - 148, d + rxbytes - 2);\n\t\t\td[0] += 2;\n\t\t\tfor (int i = 0; i < rxbytes; ++i) {\n\t\t\t\twrite_eeprom(eeprom_addr++, d[i]);\n\t\t\t}\n\t\t}\n\t}\n\tmark_eeprom_eof();\n}\n\nstatic void receive_loop()\n{\n\tradio::select();\n\tradio::wcmd<radio::SRX>();\n\tradio::release();\n\tPCINT0Interrupt::set(receive);\n\n\twhile(1) {\n\t\tset_sleep_mode(SLEEP_MODE_PWR_DOWN);\n\t\tsleep_mode();\n\t\tPCINT0Interrupt::pending();\n\t}\n}\n\nint main()\n{\n\tmark_eeprom_eof();\n\n\tGDO0::mode(INPUT);\n\n\tradio::setup();\n\tradio_reset();\n\tradio::select();\n\tradio::set<radio::IOCFG2>(0x7);\n\tradio::set<radio::IOCFG0>(0x7);\n\tradio::release();\n\n\tGIMSK |= _BV(PCIE0);\n\tPCMSK0 |= _BV(PCINT3);\n\n\tsei();\n\n\treceive_loop();\n}\n<commit_msg>Extra check for packet<commit_after>#include <avr\/io.h>\n#include <avr\/sleep.h>\n#include <avr\/interrupt.h>\n#include <interrupt\/PCINT0.hpp>\n#include <common.hpp>\n#include <port.hpp>\n#include <sensor.hpp>\n\ntypedef Pin<Port<A>, 3> GDO0;\n\nstatic void write_eeprom(int addr, unsigned char value)\n{\n\tEECR = 0;\n\n\tEEAR = addr;\n\tEEDR = value;\n\n\tEECR |= _BV(EEMPE);\n\tEECR |= _BV(EEPE);\n\n\tloop_until_bit_is_clear(EECR, EEPE);\n}\n\nstatic unsigned int eeprom_addr = 0;\n\nstatic void mark_eeprom_eof()\n{\n\twrite_eeprom(eeprom_addr, 0xff);\n}\n\nstatic void receive()\n{\n\twhile (GDO0::is_set()) {\n\t\tradio::select();\n\t\tunsigned char rxbytes = radio::status<radio::RXBYTES>();\n\t\tunsigned char d[rxbytes];\n\t\tradio::read_rxfifo(d, rxbytes);\n\t\tif (rxbytes >= 3 && rxbytes <= 32 && rxbytes == d[0] + 3) {\n\t\t\tSensorValue<RSSI>::encode(static_cast<int>(d[rxbytes - 2]) - 148, d + rxbytes - 2);\n\t\t\td[0] += 2;\n\t\t\tfor (int i = 0; i < rxbytes; ++i) {\n\t\t\t\twrite_eeprom(eeprom_addr++, d[i]);\n\t\t\t}\n\t\t}\n\t}\n\tmark_eeprom_eof();\n}\n\nstatic void receive_loop()\n{\n\tradio::select();\n\tradio::wcmd<radio::SRX>();\n\tradio::release();\n\tPCINT0Interrupt::set(receive);\n\n\twhile(1) {\n\t\tset_sleep_mode(SLEEP_MODE_PWR_DOWN);\n\t\tsleep_mode();\n\t\tPCINT0Interrupt::pending();\n\t}\n}\n\nint main()\n{\n\tmark_eeprom_eof();\n\n\tGDO0::mode(INPUT);\n\n\tradio::setup();\n\tradio_reset();\n\tradio::select();\n\tradio::set<radio::IOCFG2>(0x7);\n\tradio::set<radio::IOCFG0>(0x7);\n\tradio::release();\n\n\tGIMSK |= _BV(PCIE0);\n\tPCMSK0 |= _BV(PCINT3);\n\n\tsei();\n\n\treceive_loop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AsynchronousCall.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2006-01-19 12:51:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_ASYNCHRONOUS_CALL_HXX\n#define SD_ASYNCHRONOUS_CALL_HXX\n\n#include <vcl\/timer.hxx>\n#include <memory>\n#include <boost\/function.hpp>\n\nnamespace sd { namespace tools {\n\n\n\/** Store a function object and execute it asynchronous.\n\n This features of this class are:\n a) It provides a wrapper around a VCL Timer so that generic function\n objects can be used.\n b) When more than one function objects are posted to be executed later\n then the pending ones are erased and only the last will actually be\n executed.\n\n Use this class like this:\n aInstanceOfAsynchronousCall.Post(\n ::boost::bind(\n ::std::mem_fun(&DrawViewShell::SwitchPage),\n pDrawViewShell,\n 11));\n*\/\nclass AsynchronousCall\n{\npublic:\n \/** Create a new asynchronous call. Each object of this class processes\n one (semantical) type of call.\n *\/\n AsynchronousCall (void);\n\n ~AsynchronousCall (void);\n\n \/** Post a function object that is to executed asynchronously. When\n this method is called while the current function object has not bee\n executed then the later is destroyed and only the given function\n object will be executed.\n @param rFunction\n The function object that may be called asynchronously in the\n near future.\n @param nTimeoutInMilliseconds\n The timeout in milliseconds until the function object is\n executed.\n *\/\n typedef ::boost::function0<void> AsynchronousFunction;\n void Post (\n const AsynchronousFunction& rFunction,\n sal_uInt32 nTimeoutInMilliseconds=10);\n\nprivate:\n Timer maTimer;\n \/** The function object that will be executed when the TimerCallback\n function is called the next time. This pointer may be NULL.\n *\/\n ::std::auto_ptr<AsynchronousFunction> mpFunction;\n DECL_LINK(TimerCallback,Timer*);\n};\n\n\n} } \/\/ end of namespace ::sd::tools\n\n#endif\n<commit_msg>INTEGRATION: CWS components1 (1.2.150); FILE MERGED 2007\/02\/16 14:05:31 af 1.2.150.2: #i68075# Fixed comments. 2006\/12\/07 09:24:19 af 1.2.150.1: #i71253# Fixed a typo.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AsynchronousCall.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 16:14:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_ASYNCHRONOUS_CALL_HXX\n#define SD_ASYNCHRONOUS_CALL_HXX\n\n#include <vcl\/timer.hxx>\n#include <memory>\n#include <boost\/function.hpp>\n\nnamespace sd { namespace tools {\n\n\n\/** Store a function object and execute it asynchronous.\n\n The features of this class are:\n a) It provides a wrapper around a VCL Timer so that generic function\n objects can be used.\n b) When more than one function objects are posted to be executed later\n then the pending ones are erased and only the last one will actually be\n executed.\n\n Use this class like this:\n aInstanceOfAsynchronousCall.Post(\n ::boost::bind(\n ::std::mem_fun(&DrawViewShell::SwitchPage),\n pDrawViewShell,\n 11));\n*\/\nclass AsynchronousCall\n{\npublic:\n \/** Create a new asynchronous call. Each object of this class processes\n one (semantical) type of call.\n *\/\n AsynchronousCall (void);\n\n ~AsynchronousCall (void);\n\n \/** Post a function object that is to be executed asynchronously. When\n this method is called while the current function object has not bee\n executed then the later is destroyed and only the given function\n object will be executed.\n @param rFunction\n The function object that may be called asynchronously in the\n near future.\n @param nTimeoutInMilliseconds\n The timeout in milliseconds until the function object is\n executed.\n *\/\n typedef ::boost::function0<void> AsynchronousFunction;\n void Post (\n const AsynchronousFunction& rFunction,\n sal_uInt32 nTimeoutInMilliseconds=10);\n\nprivate:\n Timer maTimer;\n \/** The function object that will be executed when the TimerCallback\n function is called the next time. This pointer may be NULL.\n *\/\n ::std::auto_ptr<AsynchronousFunction> mpFunction;\n DECL_LINK(TimerCallback,Timer*);\n};\n\n\n} } \/\/ end of namespace ::sd::tools\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_knowledge_base\/VALVisitorProblem.h\"\n#include <iostream>\n\n\/* implementation of rosplan_knowledge_base::VALVisitorPredicate *\/\nnamespace KCL_rosplan {\n\n\t\/*----------------*\/\n\t\/* return methods *\/\n\t\/*----------------*\/\n\n\tstd::map <std::string, std::vector<std::string> > VALVisitorProblem::returnInstances() {\n\t\tVAL::const_symbol_list *c = problem->objects;\n\t\tfor (VAL::const_symbol_list::const_iterator symbolListIterator = c->begin();\n\t\t\tsymbolListIterator != c->end(); symbolListIterator++) {\n\t\t\tconst VAL::const_symbol *object = *symbolListIterator;\n\t\t\tinstances[object->type->getName()].push_back(object->pddl_typed_symbol::getName());\n\t\t}\n\t\treturn instances;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFacts(){\n\t\tif(!effects_read) {\n\t\t\tvisit_effect_lists(problem->initial_state);\n\t\t\teffects_read = true;\n\t\t}\n\t\treturn facts;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFunctions(){\n\t\tif(!effects_read) {\n\t\t\tvisit_effect_lists(problem->initial_state);\n\t\t\teffects_read = true;\n\t\t}\n\t\treturn functions;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnGoals() {\n\t\tproblem->the_goal->visit(this);\n\t\treturn goals;\n\t}\n\n\trosplan_knowledge_msgs::KnowledgeItem VALVisitorProblem::returnMetric() {\n\t\tproblem->metric->visit(this);\n\t\treturn metric;\n\t}\n\n\n\t\/*--------------*\/\n\t\/* propositions *\/\n\t\/*--------------*\/\n\n\t\/**\n\t * Visit a proposition to pack into ROS message\n\t *\/\n\tvoid VALVisitorProblem::visit_proposition(VAL::proposition *p) {\n\n\t\tlast_prop.typed_parameters.clear();\n\t\tlast_prop.name = p->head->getName();\n\n\t\tstd::vector<std::string> predicateLabels;\n\n\t\t\/\/ parse domain for predicates\n\t\tVAL::pred_decl_list *predicates = domain->predicates;\n\t\tfor (VAL::pred_decl_list::const_iterator predicateIterator = predicates->begin(); predicateIterator != predicates->end(); predicateIterator++) {\n\n\t\t\tVAL::pred_decl *tempPredicate = *predicateIterator;\n\n\t\t\t\/\/ compare pedicate name with last proposition name\n\t\t\tif (tempPredicate->getPred()->symbol::getName() == last_prop.name) {\n\n\t\t\t\t\/\/ iterate the predicate symbols\n\t\t\t\tfor (VAL::var_symbol_list::const_iterator varSymbolIterator = tempPredicate->getArgs()->begin();\n\t\t\t\t\t\t varSymbolIterator != tempPredicate->getArgs()->end(); varSymbolIterator++) {\n\n\t\t\t\t\t\/\/ add labels to predicateLabels\n\t\t\t\t\tconst VAL::var_symbol *tempVarSymbol = *varSymbolIterator;\n\t\t\t\t\tpredicateLabels.push_back(tempVarSymbol->pddl_typed_symbol::getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ pack parameters\n\t\tint index = 0;\n\t\tfor (VAL::parameter_symbol_list::const_iterator vi = p->args->begin(); vi != p->args->end(); vi++) {\n\n\t\t\tconst VAL::parameter_symbol* var = *vi;\n\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = predicateLabels[index];\n\t\t\tparam.value = var->pddl_typed_symbol::getName();\n\t\t\tlast_prop.typed_parameters.push_back(param);\n\n\t\t\t++index;\n\t\t}\n\t}\n\n\n\t\/*---------*\/\n\t\/* Effects *\/\n\t\/*---------*\/\n\n\tvoid VALVisitorProblem::visit_effect_lists(VAL::effect_lists * e) {\n\n\t\tproblem_eff_neg = false;\n\t\te->add_effects.pc_list<VAL::simple_effect*>::visit(this);\n\n\t\tproblem_eff_neg = true;\n\t\te->del_effects.pc_list<VAL::simple_effect*>::visit(this);\n\t\tproblem_eff_neg = false;\n\n\t\te->forall_effects.pc_list<VAL::forall_effect*>::visit(this);\n\t\te->cond_effects.pc_list<VAL::cond_effect*>::visit(this);\n\t\te->cond_assign_effects.pc_list<VAL::cond_effect*>::visit(this);\n\t\te->assign_effects.pc_list<VAL::assignment*>::visit(this);\n\t\te->timed_effects.pc_list<VAL::timed_effect*>::visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_timed_effect(VAL::timed_effect * e) {\n\t\tproblem_eff_time = e->ts;\n\t\te->effs->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_simple_effect(VAL::simple_effect * e) {\n\n\t\te->prop->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_prop.name;\n\t\titem.is_negative = problem_eff_neg;\n\n\t\tfor(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_prop.typed_parameters[a].key;\n\t\t\tparam.value = last_prop.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\tfacts.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_assignment(VAL::assignment *e) {\n\n\t\te->getFTerm()->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_func_term.name;\n\t\titem.is_negative = false;\n\n\t\tfor(unsigned int a = 0; a < last_func_term.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_func_term.typed_parameters[a].key;\n\t\t\tparam.value = last_func_term.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\texpression.str(\"\");\n\t\te->getExpr()->visit(this);\n\t\titem.function_value = std::atof(expression.str().c_str());\n\n\t\tfunctions.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_forall_effect(VAL::forall_effect * e) {\n\t\tROS_ERROR(\"Not yet implemented forall effects in intial state parser.\");\n\t}\n\n\tvoid VALVisitorProblem::visit_cond_effect(VAL::cond_effect * e) {\n\t\tROS_ERROR(\"Not yet implemented conditional effects in intial state parser.\");\t\n\t}\n\n\t\/*-------*\/\n\t\/* Goals *\/\n\t\/*-------*\/\n\n\tvoid VALVisitorProblem::visit_conj_goal(VAL::conj_goal * g){\n\t\tg->getGoals()->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_timed_goal(VAL::timed_goal *c){\n\t\tproblem_cond_time = c->getTime();\n\t\tc->getGoal()->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_neg_goal(VAL::neg_goal *c) {\n\t\tproblem_cond_neg = !problem_cond_neg;\n\t\tc->getGoal()->visit(this);\n\t\tproblem_cond_neg = !problem_cond_neg;\n\t}\n\n\tvoid VALVisitorProblem::visit_simple_goal(VAL::simple_goal* g) {\n\n\t\tg->getProp()->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_prop.name;\n\t\titem.is_negative = problem_cond_neg;\n\n\t\tfor(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_prop.typed_parameters[a].key;\n\t\t\tparam.value = last_prop.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\tgoals.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_qfied_goal(VAL::qfied_goal *) {}\n\tvoid VALVisitorProblem::visit_disj_goal(VAL::disj_goal *) {}\n\tvoid VALVisitorProblem::visit_imply_goal(VAL::imply_goal *) {}\n\tvoid VALVisitorProblem::visit_comparison(VAL::comparison *c) {}\n\n\n\t\/*---------*\/\n\t\/* metrics *\/\n\t\/*---------*\/\n\n\tvoid VALVisitorProblem::visit_metric_spec(VAL::metric_spec * s){\n\n\t\texpression.str(\"\");\n cout << \"metric start\\n\";\n\t\ts->expr->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 2;\n\t\tdiagnostic_msgs::KeyValue param;\n\n\t\tif (s->opt == 0){\n\t\t\tparam.key = \"minimize\";\n\t\t}\n\t\telse {\n\t\t\tparam.key = \"maximize\";\n\t\t}\n\n\t\tparam.value = expression.str();\n\t\titem.values.push_back(param);\n\t\tmetric = item;\n cout << \"metric end\\n\";\n\t}\n\n\n\t\/*-------------*\/\n\t\/* expressions *\/\n\t\/*-------------*\/\n\n\tvoid VALVisitorProblem::visit_plus_expression(VAL::plus_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_minus_expression(VAL::minus_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_mul_expression(VAL::mul_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_div_expression(VAL::div_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_uminus_expression(VAL::uminus_expression * s){\n\t\ts->getExpr()->visit(this);\n\n\t}\n\tvoid VALVisitorProblem::visit_int_expression(VAL::int_expression * s){\n\t\texpression << s->double_value();\n cout << \"expression value int: \"+ expression.str()+\"\\n\";\n\t}\n\tvoid VALVisitorProblem::visit_float_expression(VAL::float_expression * s){\n\t\texpression << s->double_value();\n cout << \"expression value float: \"+ expression.str()+\"\\n\";\n\t}\n\tvoid VALVisitorProblem::visit_special_val_expr(VAL::special_val_expr * s){\n string tempExpression;\n switch(s->getKind()) {\n case 0:\n tempExpression = \"hasht\";\n break;\n case 1:\n tempExpression = \"duration-var\";\n break;\n case 2:\n tempExpression = \"total-time\";\n }\n\t\texpression << tempExpression;\n cout << \"expression value special val: \"+ expression.str()+\"\\n\";\n\t}\n\tvoid VALVisitorProblem::visit_violation_term(VAL::violation_term * v){\n\t\texpression << v->getName();\n cout << \"expression value violation: \"+ expression.str()+\"\\n\";\n\t}\n\tvoid VALVisitorProblem::visit_func_term(VAL::func_term * s) {\n\n\t\tlast_func_term.typed_parameters.clear();\n\n\t\t\/\/ func_term name\n\t\tlast_func_term.name = s->getFunction()->getName();\n cout << \"expression value: \"+s->getFunction()->getName()+\"\\n\";\n\t\texpression << last_func_term.name;\n\n\t\tstd::vector<std::string> parameterLabels;\n\n\t\t\/\/ parse domain for parameter labels\n\t\tfor (VAL::func_decl_list::const_iterator fit = domain->functions->begin(); fit != domain->functions->end(); fit++) {\n\t\t\tif ((*fit)->getFunction()->symbol::getName() == last_func_term.name) {\n\t\t\t\tVAL::var_symbol_list::const_iterator vit = (*fit)->getArgs()->begin();\n\t\t\t\tfor(; vit != (*fit)->getArgs()->end(); vit++) {\n\t\t\t\t\tparameterLabels.push_back((*vit)->pddl_typed_symbol::getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ func_term variables\n\t\tint index = 0;\n\t\tfor (VAL::parameter_symbol_list::const_iterator vi = s->getArgs()->begin(); vi != s->getArgs()->end(); vi++) {\n\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = parameterLabels[index];\n\t\t\tparam.value = (*vi)->getName();\n\t\t\tlast_func_term.typed_parameters.push_back(param);\n\t\t\tindex++;\n\n\t\t\texpression << \" \" << (*vi)->getName();\n\t\t}\n\t}\n\n\n\t\/*----------------------*\/\n\t\/* unused visit methods *\/\n\t\/*----------------------*\/\n\n\tvoid VALVisitorProblem::visit_operator_(VAL::operator_ *) {}\n\tvoid VALVisitorProblem::visit_derivation_rule(VAL::derivation_rule *o) {}\n\n} \/\/ close namespace\n<commit_msg>code refactoring<commit_after>#include \"rosplan_knowledge_base\/VALVisitorProblem.h\"\n#include <iostream>\n\n\/* implementation of rosplan_knowledge_base::VALVisitorPredicate *\/\nnamespace KCL_rosplan {\n\n\t\/*----------------*\/\n\t\/* return methods *\/\n\t\/*----------------*\/\n\n\tstd::map <std::string, std::vector<std::string> > VALVisitorProblem::returnInstances() {\n\t\tVAL::const_symbol_list *c = problem->objects;\n\t\tfor (VAL::const_symbol_list::const_iterator symbolListIterator = c->begin();\n\t\t\tsymbolListIterator != c->end(); symbolListIterator++) {\n\t\t\tconst VAL::const_symbol *object = *symbolListIterator;\n\t\t\tinstances[object->type->getName()].push_back(object->pddl_typed_symbol::getName());\n\t\t}\n\t\treturn instances;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFacts(){\n\t\tif(!effects_read) {\n\t\t\tvisit_effect_lists(problem->initial_state);\n\t\t\teffects_read = true;\n\t\t}\n\t\treturn facts;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFunctions(){\n\t\tif(!effects_read) {\n\t\t\tvisit_effect_lists(problem->initial_state);\n\t\t\teffects_read = true;\n\t\t}\n\t\treturn functions;\n\t}\n\n\tstd::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnGoals() {\n\t\tproblem->the_goal->visit(this);\n\t\treturn goals;\n\t}\n\n\trosplan_knowledge_msgs::KnowledgeItem VALVisitorProblem::returnMetric() {\n\t\tproblem->metric->visit(this);\n\t\treturn metric;\n\t}\n\n\n\t\/*--------------*\/\n\t\/* propositions *\/\n\t\/*--------------*\/\n\n\t\/**\n\t * Visit a proposition to pack into ROS message\n\t *\/\n\tvoid VALVisitorProblem::visit_proposition(VAL::proposition *p) {\n\n\t\tlast_prop.typed_parameters.clear();\n\t\tlast_prop.name = p->head->getName();\n\n\t\tstd::vector<std::string> predicateLabels;\n\n\t\t\/\/ parse domain for predicates\n\t\tVAL::pred_decl_list *predicates = domain->predicates;\n\t\tfor (VAL::pred_decl_list::const_iterator predicateIterator = predicates->begin(); predicateIterator != predicates->end(); predicateIterator++) {\n\n\t\t\tVAL::pred_decl *tempPredicate = *predicateIterator;\n\n\t\t\t\/\/ compare pedicate name with last proposition name\n\t\t\tif (tempPredicate->getPred()->symbol::getName() == last_prop.name) {\n\n\t\t\t\t\/\/ iterate the predicate symbols\n\t\t\t\tfor (VAL::var_symbol_list::const_iterator varSymbolIterator = tempPredicate->getArgs()->begin();\n\t\t\t\t\t\t varSymbolIterator != tempPredicate->getArgs()->end(); varSymbolIterator++) {\n\n\t\t\t\t\t\/\/ add labels to predicateLabels\n\t\t\t\t\tconst VAL::var_symbol *tempVarSymbol = *varSymbolIterator;\n\t\t\t\t\tpredicateLabels.push_back(tempVarSymbol->pddl_typed_symbol::getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ pack parameters\n\t\tint index = 0;\n\t\tfor (VAL::parameter_symbol_list::const_iterator vi = p->args->begin(); vi != p->args->end(); vi++) {\n\n\t\t\tconst VAL::parameter_symbol* var = *vi;\n\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = predicateLabels[index];\n\t\t\tparam.value = var->pddl_typed_symbol::getName();\n\t\t\tlast_prop.typed_parameters.push_back(param);\n\n\t\t\t++index;\n\t\t}\n\t}\n\n\n\t\/*---------*\/\n\t\/* Effects *\/\n\t\/*---------*\/\n\n\tvoid VALVisitorProblem::visit_effect_lists(VAL::effect_lists * e) {\n\n\t\tproblem_eff_neg = false;\n\t\te->add_effects.pc_list<VAL::simple_effect*>::visit(this);\n\n\t\tproblem_eff_neg = true;\n\t\te->del_effects.pc_list<VAL::simple_effect*>::visit(this);\n\t\tproblem_eff_neg = false;\n\n\t\te->forall_effects.pc_list<VAL::forall_effect*>::visit(this);\n\t\te->cond_effects.pc_list<VAL::cond_effect*>::visit(this);\n\t\te->cond_assign_effects.pc_list<VAL::cond_effect*>::visit(this);\n\t\te->assign_effects.pc_list<VAL::assignment*>::visit(this);\n\t\te->timed_effects.pc_list<VAL::timed_effect*>::visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_timed_effect(VAL::timed_effect * e) {\n\t\tproblem_eff_time = e->ts;\n\t\te->effs->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_simple_effect(VAL::simple_effect * e) {\n\n\t\te->prop->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_prop.name;\n\t\titem.is_negative = problem_eff_neg;\n\n\t\tfor(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_prop.typed_parameters[a].key;\n\t\t\tparam.value = last_prop.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\tfacts.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_assignment(VAL::assignment *e) {\n\n\t\te->getFTerm()->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_func_term.name;\n\t\titem.is_negative = false;\n\n\t\tfor(unsigned int a = 0; a < last_func_term.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_func_term.typed_parameters[a].key;\n\t\t\tparam.value = last_func_term.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\texpression.str(\"\");\n\t\te->getExpr()->visit(this);\n\t\titem.function_value = std::atof(expression.str().c_str());\n\n\t\tfunctions.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_forall_effect(VAL::forall_effect * e) {\n\t\tROS_ERROR(\"Not yet implemented forall effects in intial state parser.\");\n\t}\n\n\tvoid VALVisitorProblem::visit_cond_effect(VAL::cond_effect * e) {\n\t\tROS_ERROR(\"Not yet implemented conditional effects in intial state parser.\");\t\n\t}\n\n\t\/*-------*\/\n\t\/* Goals *\/\n\t\/*-------*\/\n\n\tvoid VALVisitorProblem::visit_conj_goal(VAL::conj_goal * g){\n\t\tg->getGoals()->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_timed_goal(VAL::timed_goal *c){\n\t\tproblem_cond_time = c->getTime();\n\t\tc->getGoal()->visit(this);\n\t}\n\n\tvoid VALVisitorProblem::visit_neg_goal(VAL::neg_goal *c) {\n\t\tproblem_cond_neg = !problem_cond_neg;\n\t\tc->getGoal()->visit(this);\n\t\tproblem_cond_neg = !problem_cond_neg;\n\t}\n\n\tvoid VALVisitorProblem::visit_simple_goal(VAL::simple_goal* g) {\n\n\t\tg->getProp()->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 1;\n\t\titem.attribute_name = last_prop.name;\n\t\titem.is_negative = problem_cond_neg;\n\n\t\tfor(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = last_prop.typed_parameters[a].key;\n\t\t\tparam.value = last_prop.typed_parameters[a].value;\n\t\t\titem.values.push_back(param);\n\t\t}\n\n\t\tgoals.push_back(item);\n\t}\n\n\tvoid VALVisitorProblem::visit_qfied_goal(VAL::qfied_goal *) {}\n\tvoid VALVisitorProblem::visit_disj_goal(VAL::disj_goal *) {}\n\tvoid VALVisitorProblem::visit_imply_goal(VAL::imply_goal *) {}\n\tvoid VALVisitorProblem::visit_comparison(VAL::comparison *c) {}\n\n\n\t\/*---------*\/\n\t\/* metrics *\/\n\t\/*---------*\/\n\n\tvoid VALVisitorProblem::visit_metric_spec(VAL::metric_spec * s){\n\n\t\texpression.str(\"\");\n\t\ts->expr->visit(this);\n\n\t\trosplan_knowledge_msgs::KnowledgeItem item;\n\t\titem.knowledge_type = 2;\n\t\tdiagnostic_msgs::KeyValue param;\n\n\t\tif (s->opt == 0){\n\t\t\tparam.key = \"minimize\";\n\t\t}\n\t\telse {\n\t\t\tparam.key = \"maximize\";\n\t\t}\n\n\t\tparam.value = expression.str();\n\t\titem.values.push_back(param);\n\t\tmetric = item;\n\t}\n\n\n\t\/*-------------*\/\n\t\/* expressions *\/\n\t\/*-------------*\/\n\n\tvoid VALVisitorProblem::visit_plus_expression(VAL::plus_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_minus_expression(VAL::minus_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_mul_expression(VAL::mul_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_div_expression(VAL::div_expression * s){\n\t\ts->getLHS()->visit(this);\n\t\ts->getRHS()->visit(this);\n\t}\n\tvoid VALVisitorProblem::visit_uminus_expression(VAL::uminus_expression * s){\n\t\ts->getExpr()->visit(this);\n\n\t}\n\tvoid VALVisitorProblem::visit_int_expression(VAL::int_expression * s){\n\t\texpression << s->double_value();\n\t}\n\tvoid VALVisitorProblem::visit_float_expression(VAL::float_expression * s){\n\t\texpression << s->double_value();\n\t}\n\tvoid VALVisitorProblem::visit_special_val_expr(VAL::special_val_expr * s){\n string tempExpression;\n switch(s->getKind()) {\n case 0:\n tempExpression = \"hasht\";\n break;\n case 1:\n tempExpression = \"duration-var\";\n break;\n case 2:\n tempExpression = \"total-time\";\n }\n\t\texpression << tempExpression;\n\t}\n\tvoid VALVisitorProblem::visit_violation_term(VAL::violation_term * v){\n\t\texpression << v->getName();\n\t}\n\tvoid VALVisitorProblem::visit_func_term(VAL::func_term * s) {\n\n\t\tlast_func_term.typed_parameters.clear();\n\n\t\t\/\/ func_term name\n\t\tlast_func_term.name = s->getFunction()->getName();\n\t\texpression << last_func_term.name;\n\n\t\tstd::vector<std::string> parameterLabels;\n\n\t\t\/\/ parse domain for parameter labels\n\t\tfor (VAL::func_decl_list::const_iterator fit = domain->functions->begin(); fit != domain->functions->end(); fit++) {\n\t\t\tif ((*fit)->getFunction()->symbol::getName() == last_func_term.name) {\n\t\t\t\tVAL::var_symbol_list::const_iterator vit = (*fit)->getArgs()->begin();\n\t\t\t\tfor(; vit != (*fit)->getArgs()->end(); vit++) {\n\t\t\t\t\tparameterLabels.push_back((*vit)->pddl_typed_symbol::getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ func_term variables\n\t\tint index = 0;\n\t\tfor (VAL::parameter_symbol_list::const_iterator vi = s->getArgs()->begin(); vi != s->getArgs()->end(); vi++) {\n\n\t\t\tdiagnostic_msgs::KeyValue param;\n\t\t\tparam.key = parameterLabels[index];\n\t\t\tparam.value = (*vi)->getName();\n\t\t\tlast_func_term.typed_parameters.push_back(param);\n\t\t\tindex++;\n\n\t\t\texpression << \" \" << (*vi)->getName();\n\t\t}\n\t}\n\n\n\t\/*----------------------*\/\n\t\/* unused visit methods *\/\n\t\/*----------------------*\/\n\n\tvoid VALVisitorProblem::visit_operator_(VAL::operator_ *) {}\n\tvoid VALVisitorProblem::visit_derivation_rule(VAL::derivation_rule *o) {}\n\n} \/\/ close namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n\n#include <errno.h>\n\n#include \"CephxClientHandler.h\"\n#include \"CephxProtocol.h\"\n\n#include \"..\/KeyRing.h\"\n\n#include \"common\/config.h\"\n\n#define DOUT_SUBSYS auth\n#undef dout_prefix\n#define dout_prefix *_dout << \"cephx client: \"\n\n\nint CephxClientHandler::build_request(bufferlist& bl)\n{\n ldout(cct, 10) << \"build_request\" << dendl;\n\n ldout(cct, 10) << \"validate_tickets: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n validate_tickets();\n\n ldout(cct, 10) << \"want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);\n\n if (need & CEPH_ENTITY_TYPE_AUTH) {\n \/* authenticate *\/\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_AUTH_SESSION_KEY;\n ::encode(header, bl);\n\n CryptoKey secret;\n keyring->get_secret(cct->_conf->name, secret);\n\n CephXAuthenticate req;\n get_random_bytes((char *)&req.client_challenge, sizeof(req.client_challenge));\n std::string error;\n cephx_calc_client_server_challenge(secret, server_challenge,\n\t\t\t\t req.client_challenge, &req.key, error);\n if (!error.empty()) {\n ldout(cct, 20) << \"cephx_calc_client_server_challenge error: \" << error << dendl;\n return -EIO;\n }\n\n req.old_ticket = ticket_handler.ticket;\n\n if (req.old_ticket.blob.length()) {\n ldout(cct, 20) << \"old ticket len=\" << req.old_ticket.blob.length() << dendl;\n }\n\n ::encode(req, bl);\n\n ldout(cct, 10) << \"get auth session key: client_challenge \" << req.client_challenge << dendl;\n return 0;\n }\n\n if (need) {\n \/* get service tickets *\/\n ldout(cct, 10) << \"get service keys: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_PRINCIPAL_SESSION_KEY;\n ::encode(header, bl);\n\n authorizer = ticket_handler.build_authorizer(global_id);\n if (!authorizer)\n return -EINVAL;\n bl.claim_append(authorizer->bl);\n\n CephXServiceTicketRequest req;\n req.keys = need;\n ::encode(req, bl);\n }\n\n return 0;\n}\n\nint CephxClientHandler::handle_response(int ret, bufferlist::iterator& indata)\n{\n ldout(cct, 10) << \"handle_response ret = \" << ret << dendl;\n \n if (ret < 0)\n return ret; \/\/ hrm!\n\n if (starting) {\n CephXServerChallenge ch;\n ::decode(ch, indata);\n server_challenge = ch.server_challenge;\n ldout(cct, 10) << \" got initial server challenge \" << server_challenge << dendl;\n starting = false;\n\n tickets.invalidate_ticket(CEPH_ENTITY_TYPE_AUTH);\n return -EAGAIN;\n }\n\n struct CephXResponseHeader header;\n ::decode(header, indata);\n\n switch (header.request_type) {\n case CEPHX_GET_AUTH_SESSION_KEY:\n {\n ldout(cct, 10) << \" get_auth_session_key\" << dendl;\n CryptoKey secret;\n keyring->get_secret(cct->_conf->name, secret);\n\t\n if (!tickets.verify_service_ticket_reply(secret, indata)) {\n\tldout(cct, 0) << \"could not verify service_ticket reply\" << dendl;\n\treturn -EPERM;\n }\n ldout(cct, 10) << \" want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n validate_tickets();\n if (need)\n\tret = -EAGAIN;\n else\n\tret = 0;\n }\n break;\n\n case CEPHX_GET_PRINCIPAL_SESSION_KEY:\n {\n CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);\n ldout(cct, 10) << \" get_principal_session_key session_key \" << ticket_handler.session_key << dendl;\n \n if (!tickets.verify_service_ticket_reply(ticket_handler.session_key, indata)) {\n ldout(cct, 0) << \"could not verify service_ticket reply\" << dendl;\n return -EPERM;\n }\n validate_tickets();\n if (!need) {\n\tret = 0;\n }\n }\n break;\n\n case CEPHX_GET_ROTATING_KEY:\n {\n ldout(cct, 10) << \" get_rotating_key\" << dendl;\n if (rotating_secrets) {\n\tRotatingSecrets secrets;\n\tCryptoKey secret_key;\n\tkeyring->get_secret(cct->_conf->name, secret_key);\n\tstd::string error;\n\tdecode_decrypt(secrets, secret_key, indata, error);\n\tif (error.empty()) {\n\t rotating_secrets->set_secrets(secrets);\n\t} else {\n\t ldout(cct, 0) << \"could not set rotating key: decode_decrypt failed. error:\"\n\t << error << dendl;\n\t error.clear();\n\t}\n }\n }\n break;\n\n default:\n ldout(cct, 0) << \" unknown request_type \" << header.request_type << dendl;\n assert(0);\n }\n return ret;\n}\n\n\n\nAuthAuthorizer *CephxClientHandler::build_authorizer(uint32_t service_id)\n{\n ldout(cct, 10) << \"build_authorizer for service \" << ceph_entity_type_name(service_id) << dendl;\n return tickets.build_authorizer(service_id);\n}\n\n\nbool CephxClientHandler::build_rotating_request(bufferlist& bl)\n{\n ldout(cct, 10) << \"build_rotating_request\" << dendl;\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_ROTATING_KEY;\n ::encode(header, bl);\n return true;\n}\n\nvoid CephxClientHandler::validate_tickets()\n{\n tickets.validate_tickets(want, have, need);\n}\n\nbool CephxClientHandler::need_tickets()\n{\n validate_tickets();\n\n ldout(cct, 20) << \"need_tickets: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n return (need != 0);\n}\n\n<commit_msg>cephx: don't leak Authorizers on each request<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n\n#include <errno.h>\n\n#include \"CephxClientHandler.h\"\n#include \"CephxProtocol.h\"\n\n#include \"..\/KeyRing.h\"\n\n#include \"common\/config.h\"\n\n#define DOUT_SUBSYS auth\n#undef dout_prefix\n#define dout_prefix *_dout << \"cephx client: \"\n\n\nint CephxClientHandler::build_request(bufferlist& bl)\n{\n ldout(cct, 10) << \"build_request\" << dendl;\n\n ldout(cct, 10) << \"validate_tickets: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n validate_tickets();\n\n ldout(cct, 10) << \"want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);\n\n if (need & CEPH_ENTITY_TYPE_AUTH) {\n \/* authenticate *\/\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_AUTH_SESSION_KEY;\n ::encode(header, bl);\n\n CryptoKey secret;\n keyring->get_secret(cct->_conf->name, secret);\n\n CephXAuthenticate req;\n get_random_bytes((char *)&req.client_challenge, sizeof(req.client_challenge));\n std::string error;\n cephx_calc_client_server_challenge(secret, server_challenge,\n\t\t\t\t req.client_challenge, &req.key, error);\n if (!error.empty()) {\n ldout(cct, 20) << \"cephx_calc_client_server_challenge error: \" << error << dendl;\n return -EIO;\n }\n\n req.old_ticket = ticket_handler.ticket;\n\n if (req.old_ticket.blob.length()) {\n ldout(cct, 20) << \"old ticket len=\" << req.old_ticket.blob.length() << dendl;\n }\n\n ::encode(req, bl);\n\n ldout(cct, 10) << \"get auth session key: client_challenge \" << req.client_challenge << dendl;\n return 0;\n }\n\n if (need) {\n \/* get service tickets *\/\n ldout(cct, 10) << \"get service keys: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_PRINCIPAL_SESSION_KEY;\n ::encode(header, bl);\n\n authorizer = ticket_handler.build_authorizer(global_id);\n if (!authorizer)\n return -EINVAL;\n bl.claim_append(authorizer->bl);\n delete authorizer;\n\n CephXServiceTicketRequest req;\n req.keys = need;\n ::encode(req, bl);\n }\n\n return 0;\n}\n\nint CephxClientHandler::handle_response(int ret, bufferlist::iterator& indata)\n{\n ldout(cct, 10) << \"handle_response ret = \" << ret << dendl;\n \n if (ret < 0)\n return ret; \/\/ hrm!\n\n if (starting) {\n CephXServerChallenge ch;\n ::decode(ch, indata);\n server_challenge = ch.server_challenge;\n ldout(cct, 10) << \" got initial server challenge \" << server_challenge << dendl;\n starting = false;\n\n tickets.invalidate_ticket(CEPH_ENTITY_TYPE_AUTH);\n return -EAGAIN;\n }\n\n struct CephXResponseHeader header;\n ::decode(header, indata);\n\n switch (header.request_type) {\n case CEPHX_GET_AUTH_SESSION_KEY:\n {\n ldout(cct, 10) << \" get_auth_session_key\" << dendl;\n CryptoKey secret;\n keyring->get_secret(cct->_conf->name, secret);\n\t\n if (!tickets.verify_service_ticket_reply(secret, indata)) {\n\tldout(cct, 0) << \"could not verify service_ticket reply\" << dendl;\n\treturn -EPERM;\n }\n ldout(cct, 10) << \" want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n validate_tickets();\n if (need)\n\tret = -EAGAIN;\n else\n\tret = 0;\n }\n break;\n\n case CEPHX_GET_PRINCIPAL_SESSION_KEY:\n {\n CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);\n ldout(cct, 10) << \" get_principal_session_key session_key \" << ticket_handler.session_key << dendl;\n \n if (!tickets.verify_service_ticket_reply(ticket_handler.session_key, indata)) {\n ldout(cct, 0) << \"could not verify service_ticket reply\" << dendl;\n return -EPERM;\n }\n validate_tickets();\n if (!need) {\n\tret = 0;\n }\n }\n break;\n\n case CEPHX_GET_ROTATING_KEY:\n {\n ldout(cct, 10) << \" get_rotating_key\" << dendl;\n if (rotating_secrets) {\n\tRotatingSecrets secrets;\n\tCryptoKey secret_key;\n\tkeyring->get_secret(cct->_conf->name, secret_key);\n\tstd::string error;\n\tdecode_decrypt(secrets, secret_key, indata, error);\n\tif (error.empty()) {\n\t rotating_secrets->set_secrets(secrets);\n\t} else {\n\t ldout(cct, 0) << \"could not set rotating key: decode_decrypt failed. error:\"\n\t << error << dendl;\n\t error.clear();\n\t}\n }\n }\n break;\n\n default:\n ldout(cct, 0) << \" unknown request_type \" << header.request_type << dendl;\n assert(0);\n }\n return ret;\n}\n\n\n\nAuthAuthorizer *CephxClientHandler::build_authorizer(uint32_t service_id)\n{\n ldout(cct, 10) << \"build_authorizer for service \" << ceph_entity_type_name(service_id) << dendl;\n return tickets.build_authorizer(service_id);\n}\n\n\nbool CephxClientHandler::build_rotating_request(bufferlist& bl)\n{\n ldout(cct, 10) << \"build_rotating_request\" << dendl;\n CephXRequestHeader header;\n header.request_type = CEPHX_GET_ROTATING_KEY;\n ::encode(header, bl);\n return true;\n}\n\nvoid CephxClientHandler::validate_tickets()\n{\n tickets.validate_tickets(want, have, need);\n}\n\nbool CephxClientHandler::need_tickets()\n{\n validate_tickets();\n\n ldout(cct, 20) << \"need_tickets: want=\" << want << \" need=\" << need << \" have=\" << have << dendl;\n\n return (need != 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#pragma once\n\n#include \"math\/Vector3.hpp\"\n\nnamespace ouzel\n{\n class Quaternion\n {\n public:\n float x = 0.0F;\n float y = 0.0F;\n float z = 0.0F;\n float w = 0.0F;\n\n Quaternion()\n {\n }\n\n Quaternion(float initX, float initY, float initZ, float initW):\n x(initX), y(initY), z(initZ), w(initW)\n {\n }\n\n Quaternion(const Quaternion& copy):\n x(copy.x), y(copy.y), z(copy.z), w(copy.w)\n {\n }\n\n static Quaternion identity()\n {\n return Quaternion(0.0F, 0.0F, 0.0F, 1.0F);\n }\n\n Quaternion operator*(const Quaternion& q) const\n {\n return Quaternion( x * q.w + y * q.z - z * q.y + w * q.x,\n -x * q.z + y * q.w + z * q.x + w * q.y,\n x * q.y - y * q.x + z * q.w + w * q.z,\n -x * q.x - y * q.y - z * q.z + w * q.w);\n }\n\n const Quaternion& operator*=(const Quaternion& q)\n {\n float tempX = x * q.w + y * q.z - z * q.y + w * q.x;\n float tempY = -x * q.z + y * q.w + z * q.x + w * q.y;\n float tempZ = x * q.y - y * q.x + z * q.w + w * q.z;\n float tempW = -x * q.x - y * q.y - z * q.z + w * q.w;\n\n x = tempX;\n y = tempY;\n z = tempZ;\n w = tempW;\n\n return *this;\n }\n\n Quaternion operator*(float scalar) const\n {\n return Quaternion(x * scalar,\n y * scalar,\n z * scalar,\n w * scalar);\n }\n\n const Quaternion& operator*=(float scalar)\n {\n x *= scalar;\n y *= scalar;\n z *= scalar;\n w *= scalar;\n\n return *this;\n }\n\n Quaternion operator\/(float scalar) const\n {\n return Quaternion(x \/ scalar,\n y \/ scalar,\n z \/ scalar,\n w \/ scalar);\n }\n\n const Quaternion& operator\/=(float scalar)\n {\n x \/= scalar;\n y \/= scalar;\n z \/= scalar;\n w \/= scalar;\n\n return *this;\n }\n\n inline Quaternion operator-() const\n {\n return Quaternion(-x, -y, -z, -w);\n }\n\n inline Quaternion operator+(const Quaternion& q) const\n {\n Quaternion result(*this);\n result.x += q.x;\n result.y += q.y;\n result.z += q.z;\n result.w += q.w;\n\n return result;\n }\n\n inline Quaternion& operator+=(const Quaternion& q)\n {\n x += q.x;\n y += q.y;\n z += q.z;\n w += q.w;\n\n return *this;\n }\n\n inline Quaternion operator-(const Quaternion& q) const\n {\n Quaternion result(*this);\n result.x -= q.x;\n result.y -= q.y;\n result.z -= q.z;\n result.w -= q.w;\n\n return result;\n }\n\n inline Quaternion& operator-=(const Quaternion& q)\n {\n x -= q.x;\n y -= q.y;\n z -= q.z;\n w -= q.w;\n\n return *this;\n }\n\n inline bool operator==(const Quaternion& q) const\n {\n return x == q.x && y == q.y && z == q.z && w == q.w;\n }\n\n inline bool operator!=(const Quaternion& q) const\n {\n return x != q.x || y != q.y || z != q.z || w != q.w;\n }\n\n inline void negate()\n {\n x = -x;\n y = -y;\n z = -z;\n w = -w;\n }\n\n inline void conjugate()\n {\n x = -x;\n y = -y;\n z = -z;\n }\n\n inline void invert()\n {\n float n2 = x * x + y * y + z * z + w * w; \/\/ norm squared\n\n if (n2 == 0.0F) return;\n\n \/\/ conjugate divided by norm squared\n x = -x \/ n2;\n y = -y \/ n2;\n z = -z \/ n2;\n w = w \/ n2;\n }\n\n float getNorm();\n void normalize();\n void rotate(float angle, Vector3 axis);\n void getRotation(float& angle, Vector3& axis);\n\n void setEulerAngles(const Vector3& angles);\n Vector3 getEulerAngles() const;\n float getEulerAngleX() const;\n float getEulerAngleY() const;\n float getEulerAngleZ() const;\n\n inline Vector3 operator*(const Vector3& vector) const\n {\n return rotateVector(vector);\n }\n\n inline Vector3 rotateVector(const Vector3& vector) const\n {\n Vector3 q(x, y, z);\n Vector3 t = 2.0F * Vector3::cross(q, vector);\n Vector3 result = vector + (w * t) + Vector3::cross(q, t);\n return result;\n }\n\n inline Vector3 getRightVector() const\n {\n return rotateVector(Vector3(1.0F, 0.0F, 0.0F));\n }\n\n inline Vector3 getUpVector() const\n {\n return rotateVector(Vector3(0.0F, 1.0F, 0.0F));\n }\n\n inline Vector3 getForwardVector() const\n {\n return rotateVector(Vector3(0.0F, 0.0F, 1.0F));\n }\n\n Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, float t)\n {\n const float scale = 1.0F - t;\n return (*this = (q1 * scale) + (q2 * t));\n }\n };\n}\n<commit_msg>Simplify rotateVector<commit_after>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#pragma once\n\n#include \"math\/Vector3.hpp\"\n\nnamespace ouzel\n{\n class Quaternion\n {\n public:\n float x = 0.0F;\n float y = 0.0F;\n float z = 0.0F;\n float w = 0.0F;\n\n Quaternion()\n {\n }\n\n Quaternion(float initX, float initY, float initZ, float initW):\n x(initX), y(initY), z(initZ), w(initW)\n {\n }\n\n Quaternion(const Quaternion& copy):\n x(copy.x), y(copy.y), z(copy.z), w(copy.w)\n {\n }\n\n static Quaternion identity()\n {\n return Quaternion(0.0F, 0.0F, 0.0F, 1.0F);\n }\n\n Quaternion operator*(const Quaternion& q) const\n {\n return Quaternion( x * q.w + y * q.z - z * q.y + w * q.x,\n -x * q.z + y * q.w + z * q.x + w * q.y,\n x * q.y - y * q.x + z * q.w + w * q.z,\n -x * q.x - y * q.y - z * q.z + w * q.w);\n }\n\n const Quaternion& operator*=(const Quaternion& q)\n {\n float tempX = x * q.w + y * q.z - z * q.y + w * q.x;\n float tempY = -x * q.z + y * q.w + z * q.x + w * q.y;\n float tempZ = x * q.y - y * q.x + z * q.w + w * q.z;\n float tempW = -x * q.x - y * q.y - z * q.z + w * q.w;\n\n x = tempX;\n y = tempY;\n z = tempZ;\n w = tempW;\n\n return *this;\n }\n\n Quaternion operator*(float scalar) const\n {\n return Quaternion(x * scalar,\n y * scalar,\n z * scalar,\n w * scalar);\n }\n\n const Quaternion& operator*=(float scalar)\n {\n x *= scalar;\n y *= scalar;\n z *= scalar;\n w *= scalar;\n\n return *this;\n }\n\n Quaternion operator\/(float scalar) const\n {\n return Quaternion(x \/ scalar,\n y \/ scalar,\n z \/ scalar,\n w \/ scalar);\n }\n\n const Quaternion& operator\/=(float scalar)\n {\n x \/= scalar;\n y \/= scalar;\n z \/= scalar;\n w \/= scalar;\n\n return *this;\n }\n\n inline Quaternion operator-() const\n {\n return Quaternion(-x, -y, -z, -w);\n }\n\n inline Quaternion operator+(const Quaternion& q) const\n {\n Quaternion result(*this);\n result.x += q.x;\n result.y += q.y;\n result.z += q.z;\n result.w += q.w;\n\n return result;\n }\n\n inline Quaternion& operator+=(const Quaternion& q)\n {\n x += q.x;\n y += q.y;\n z += q.z;\n w += q.w;\n\n return *this;\n }\n\n inline Quaternion operator-(const Quaternion& q) const\n {\n Quaternion result(*this);\n result.x -= q.x;\n result.y -= q.y;\n result.z -= q.z;\n result.w -= q.w;\n\n return result;\n }\n\n inline Quaternion& operator-=(const Quaternion& q)\n {\n x -= q.x;\n y -= q.y;\n z -= q.z;\n w -= q.w;\n\n return *this;\n }\n\n inline bool operator==(const Quaternion& q) const\n {\n return x == q.x && y == q.y && z == q.z && w == q.w;\n }\n\n inline bool operator!=(const Quaternion& q) const\n {\n return x != q.x || y != q.y || z != q.z || w != q.w;\n }\n\n inline void negate()\n {\n x = -x;\n y = -y;\n z = -z;\n w = -w;\n }\n\n inline void conjugate()\n {\n x = -x;\n y = -y;\n z = -z;\n }\n\n inline void invert()\n {\n float n2 = x * x + y * y + z * z + w * w; \/\/ norm squared\n\n if (n2 == 0.0F) return;\n\n \/\/ conjugate divided by norm squared\n x = -x \/ n2;\n y = -y \/ n2;\n z = -z \/ n2;\n w = w \/ n2;\n }\n\n float getNorm();\n void normalize();\n void rotate(float angle, Vector3 axis);\n void getRotation(float& angle, Vector3& axis);\n\n void setEulerAngles(const Vector3& angles);\n Vector3 getEulerAngles() const;\n float getEulerAngleX() const;\n float getEulerAngleY() const;\n float getEulerAngleZ() const;\n\n inline Vector3 operator*(const Vector3& vector) const\n {\n return rotateVector(vector);\n }\n\n inline Vector3 rotateVector(const Vector3& vector) const\n {\n Vector3 q(x, y, z);\n Vector3 t = 2.0F * Vector3::cross(q, vector);\n return vector + (w * t) + Vector3::cross(q, t);\n }\n\n inline Vector3 getRightVector() const\n {\n return rotateVector(Vector3(1.0F, 0.0F, 0.0F));\n }\n\n inline Vector3 getUpVector() const\n {\n return rotateVector(Vector3(0.0F, 1.0F, 0.0F));\n }\n\n inline Vector3 getForwardVector() const\n {\n return rotateVector(Vector3(0.0F, 0.0F, 1.0F));\n }\n\n Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, float t)\n {\n const float scale = 1.0F - t;\n return (*this = (q1 * scale) + (q2 * t));\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkGLWidget.h\"\n\n#if SK_SUPPORT_GPU\n\nSkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {\n fDebugger = debugger;\n}\n\nSkGLWidget::~SkGLWidget() {\n}\n\nvoid SkGLWidget::setSampleCount(int sampleCount) {\n QGLFormat currentFormat = format();\n currentFormat.setSampleBuffers(sampleCount > 0);\n currentFormat.setSamples(sampleCount);\n setFormat(currentFormat);\n}\n\nvoid SkGLWidget::initializeGL() {\n if (!fCurIntf) {\n fCurIntf.reset(GrGLCreateNativeInterface());\n }\n if (!fCurIntf) {\n return;\n }\n \/\/ The call may come multiple times, for example after setSampleCount(). The QGLContext will be\n \/\/ different, but we do not have a mechanism to catch the destroying of QGLContext, so that\n \/\/ proper resource cleanup could be made.\n if (fCurContext) {\n fCurContext->abandonContext();\n }\n fGpuDevice.reset(nullptr);\n fCanvas.reset(nullptr);\n\n fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));\n}\n\nvoid SkGLWidget::createRenderTarget() {\n if (!fCurContext) {\n return;\n }\n\n glDisable(GL_SCISSOR_TEST);\n glStencilMask(0xffffffff);\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n fCurContext->resetContext();\n\n fGpuDevice.reset(nullptr);\n fCanvas.reset(nullptr);\n\n GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());\n desc.fOrigin = kBottomLeft_GrSurfaceOrigin;\n SkAutoTUnref<GrRenderTarget> curRenderTarget(\n fCurContext->textureProvider()->wrapBackendRenderTarget(desc));\n SkSurfaceProps props(0, kUnknown_SkPixelGeometry);\n fGpuDevice.reset(SkGpuDevice::Create(curRenderTarget, &props,\n SkGpuDevice::kUninit_InitContents));\n fCanvas.reset(new SkCanvas(fGpuDevice));\n}\n\nvoid SkGLWidget::resizeGL(int w, int h) {\n SkASSERT(w == this->width() && h == this->height());\n this->createRenderTarget();\n}\n\nvoid SkGLWidget::paintGL() {\n if (!this->isHidden() && fCanvas) {\n fCurContext->resetContext();\n fDebugger->draw(fCanvas.get());\n \/\/ TODO(chudy): Implement an optional flush button in Gui.\n fCanvas->flush();\n Q_EMIT drawComplete();\n }\n}\n\nGrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {\n GrBackendRenderTargetDesc desc;\n desc.fWidth = SkScalarRoundToInt(this->width());\n desc.fHeight = SkScalarRoundToInt(this->height());\n desc.fConfig = kSkia8888_GrPixelConfig;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);\n GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);\n GrGLint buffer;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);\n desc.fRenderTargetHandle = buffer;\n\n return desc;\n}\n\n#endif\n<commit_msg>Fix old debugger GOLD_TRYBOT_URL= https:\/\/gold.skia.org\/search2?unt=true&query=source_type%3Dgm&master=false&issue=1935623002<commit_after>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkGLWidget.h\"\n\n#if SK_SUPPORT_GPU\n\nSkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {\n fDebugger = debugger;\n}\n\nSkGLWidget::~SkGLWidget() {\n}\n\nvoid SkGLWidget::setSampleCount(int sampleCount) {\n QGLFormat currentFormat = format();\n currentFormat.setSampleBuffers(sampleCount > 0);\n currentFormat.setSamples(sampleCount);\n setFormat(currentFormat);\n}\n\nvoid SkGLWidget::initializeGL() {\n if (!fCurIntf) {\n fCurIntf.reset(GrGLCreateNativeInterface());\n }\n if (!fCurIntf) {\n return;\n }\n \/\/ The call may come multiple times, for example after setSampleCount(). The QGLContext will be\n \/\/ different, but we do not have a mechanism to catch the destroying of QGLContext, so that\n \/\/ proper resource cleanup could be made.\n if (fCurContext) {\n fCurContext->abandonContext();\n }\n fGpuDevice.reset(nullptr);\n fCanvas.reset(nullptr);\n\n fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));\n}\n\nvoid SkGLWidget::createRenderTarget() {\n if (!fCurContext) {\n return;\n }\n\n glDisable(GL_SCISSOR_TEST);\n glStencilMask(0xffffffff);\n glClearStencil(0);\n glClear(GL_STENCIL_BUFFER_BIT);\n fCurContext->resetContext();\n\n fGpuDevice.reset(nullptr);\n fCanvas.reset(nullptr);\n\n GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());\n desc.fOrigin = kBottomLeft_GrSurfaceOrigin;\n sk_sp<GrRenderTarget> curRenderTarget(\n fCurContext->textureProvider()->wrapBackendRenderTarget(desc));\n SkSurfaceProps props(0, kUnknown_SkPixelGeometry);\n fGpuDevice.reset(SkGpuDevice::Make(std::move(curRenderTarget), &props,\n SkGpuDevice::kUninit_InitContents).release());\n fCanvas.reset(new SkCanvas(fGpuDevice));\n}\n\nvoid SkGLWidget::resizeGL(int w, int h) {\n SkASSERT(w == this->width() && h == this->height());\n this->createRenderTarget();\n}\n\nvoid SkGLWidget::paintGL() {\n if (!this->isHidden() && fCanvas) {\n fCurContext->resetContext();\n fDebugger->draw(fCanvas.get());\n \/\/ TODO(chudy): Implement an optional flush button in Gui.\n fCanvas->flush();\n Q_EMIT drawComplete();\n }\n}\n\nGrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {\n GrBackendRenderTargetDesc desc;\n desc.fWidth = SkScalarRoundToInt(this->width());\n desc.fHeight = SkScalarRoundToInt(this->height());\n desc.fConfig = kSkia8888_GrPixelConfig;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);\n GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);\n GrGLint buffer;\n GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);\n desc.fRenderTargetHandle = buffer;\n\n return desc;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#include \"Component.hpp\"\n#include \"Actor.hpp\"\n#include \"math\/MathUtils.hpp\"\n\nnamespace ouzel\n{\n namespace scene\n {\n Component::Component(uint32_t initClass):\n cls(initClass)\n {\n }\n\n Component::~Component()\n {\n if (actor) actor->removeComponent(this);\n }\n\n void Component::draw(const Matrix4F&,\n float,\n const Matrix4F&,\n bool)\n {\n }\n\n bool Component::pointOn(const Vector2F& position) const\n {\n return boundingBox.containsPoint(Vector3F(position));\n }\n\n inline void gatherPolygonProjectionExtents(const std::vector<Vector2F>& vertList,\n const Vector2F& v,\n float& outMin, float& outMax)\n {\n outMin = outMax = v.dot(vertList[0]);\n\n size_t vertListSize = vertList.size();\n for (size_t i = 1 ; i < vertListSize; ++i)\n {\n float d = v.dot(vertList[i]);\n if (d < outMin) outMin = d;\n else if (d > outMax) outMax = d;\n }\n }\n\n inline bool findSeparatingAxis(const std::vector<Vector2F>& aVertList,\n const std::vector<Vector2F>& bVertList)\n {\n Vector2F v;\n\n size_t aVertListSize = aVertList.size();\n size_t prev = aVertListSize - 1;\n for (size_t cur = 0; cur < aVertListSize; ++cur)\n {\n Vector2F edge = aVertList[cur] - aVertList[prev];\n\n v.v[0] = edge.v[1];\n v.v[1] = -edge.v[0];\n\n float aMin;\n float aMax;\n float bMin;\n float bMax;\n gatherPolygonProjectionExtents(aVertList, v, aMin, aMax);\n gatherPolygonProjectionExtents(bVertList, v, bMin, bMax);\n\n if (aMax < bMin) return true;\n if (bMax < aMin) return true;\n\n prev = cur;\n }\n\n return false;\n }\n\n bool Component::shapeOverlaps(const std::vector<Vector2F>& edges) const\n {\n std::vector<Vector2F> boundingBoxEdges = {\n Vector2F(boundingBox.min),\n Vector2F(boundingBox.max.v[0], boundingBox.min.v[1]),\n Vector2F(boundingBox.max),\n Vector2F(boundingBox.min.v[0], boundingBox.max.v[1])\n };\n\n if (findSeparatingAxis(boundingBoxEdges, edges))\n return false;\n\n if (findSeparatingAxis(edges, boundingBoxEdges))\n return false;\n\n return true;\n }\n\n void Component::removeFromActor()\n {\n if (actor) actor->removeComponent(this);\n }\n\n void Component::setActor(Actor* newActor)\n {\n actor = newActor;\n }\n\n void Component::setLayer(Layer* newLayer)\n {\n layer = newLayer;\n }\n\n void Component::updateTransform()\n {\n }\n } \/\/ namespace scene\n} \/\/ namespace ouzel\n<commit_msg>Use iterators to calculate polygon overlap<commit_after>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#include \"Component.hpp\"\n#include \"Actor.hpp\"\n#include \"math\/MathUtils.hpp\"\n\nnamespace ouzel\n{\n namespace scene\n {\n Component::Component(uint32_t initClass):\n cls(initClass)\n {\n }\n\n Component::~Component()\n {\n if (actor) actor->removeComponent(this);\n }\n\n void Component::draw(const Matrix4F&,\n float,\n const Matrix4F&,\n bool)\n {\n }\n\n bool Component::pointOn(const Vector2F& position) const\n {\n return boundingBox.containsPoint(Vector3F(position));\n }\n\n static inline void gatherPolygonProjectionExtents(const std::vector<Vector2F>& vertList,\n const Vector2F& v,\n float& outMin, float& outMax)\n {\n auto i = vertList.begin();\n if (i != vertList.end())\n {\n outMin = outMax = v.dot(*i);\n ++i;\n\n for (; i != vertList.end(); ++i)\n {\n float d = v.dot(*i);\n if (d < outMin) outMin = d;\n else if (d > outMax) outMax = d;\n }\n }\n }\n\n static inline bool findSeparatingAxis(const std::vector<Vector2F>& aVertList,\n const std::vector<Vector2F>& bVertList)\n {\n Vector2F v;\n auto prev = aVertList.end() - 1;\n for (auto cur = aVertList.begin(); cur != aVertList.end(); ++cur)\n {\n Vector2F edge = *cur - *prev;\n v.v[0] = edge.v[1];\n v.v[1] = -edge.v[0];\n\n float aMin;\n float aMax;\n float bMin;\n float bMax;\n gatherPolygonProjectionExtents(aVertList, v, aMin, aMax);\n gatherPolygonProjectionExtents(bVertList, v, bMin, bMax);\n\n if (aMax < bMin) return true;\n if (bMax < aMin) return true;\n\n prev = cur;\n }\n\n return false;\n }\n\n bool Component::shapeOverlaps(const std::vector<Vector2F>& edges) const\n {\n std::vector<Vector2F> boundingBoxEdges = {\n Vector2F(boundingBox.min),\n Vector2F(boundingBox.max.v[0], boundingBox.min.v[1]),\n Vector2F(boundingBox.max),\n Vector2F(boundingBox.min.v[0], boundingBox.max.v[1])\n };\n\n if (findSeparatingAxis(boundingBoxEdges, edges))\n return false;\n\n if (findSeparatingAxis(edges, boundingBoxEdges))\n return false;\n\n return true;\n }\n\n void Component::removeFromActor()\n {\n if (actor) actor->removeComponent(this);\n }\n\n void Component::setActor(Actor* newActor)\n {\n actor = newActor;\n }\n\n void Component::setLayer(Layer* newLayer)\n {\n layer = newLayer;\n }\n\n void Component::updateTransform()\n {\n }\n } \/\/ namespace scene\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>#include \"logger.h\"\n#include <iostream>\n#include <QTime>\n#include <QCoreApplication>\n#include <QDate>\n\nLogger::Logger(QObject *parent) : QObject(parent){\n \/\/setup the default log file\n QDate date;\n QString current_date = date.currentDate().toString(\"yyyy-MM-dd\");\n QString log_file_name = current_date + \".log\";\n setLogDir(\"log\");\n setLogFile(\"log\\\\\" + log_file_name);\n}\n\nvoid Logger::setLogDir(QString dir){\n \/\/create a dir for log save, default under applicationDirPath\/log\n QString app_dir_path = QCoreApplication::applicationDirPath();\n log_dir.mkdir(app_dir_path + \"\\\\\" + dir);\n}\n\nvoid Logger::setLogFile(QString file){\n \/\/setup log file location\n QString app_dir_path = QCoreApplication::applicationDirPath();\n log_file.setFileName(app_dir_path + \"\\\\\" + file);\n \/\/if log file not exists, new one\n if(!log_file.exists()){\n \/\/only new, not do anything\n log_file.open(QIODevice::WriteOnly | QIODevice::Text);\n log_file.close();\n }\n}\n\nvoid Logger::log(QString log_type, QString log_msg){\n \/\/set the file open as R\/W, text and append\n log_file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append);\n \/\/append use QTextStream\n QTextStream in(&log_file);\n \/\/log format is \"hh:mm:ss[<log_type>]: <log_msg>\", time is the currentTime\n QTime time;\n in<<time.currentTime().toString(\"hh:mm:ss\")<<\" [\"<<log_type<<\"]: \"<<log_msg<<\"\\n\";\n \/\/log finished and close IO\n log_file.close();\n}\n<commit_msg>add comments in logger<commit_after>#include \"logger.h\"\n#include <iostream>\n#include <QTime>\n#include <QCoreApplication>\n#include <QDate>\n\nLogger::Logger(QObject *parent) : QObject(parent){\n \/\/setup the default log file\n QDate date;\n QString current_date = date.currentDate().toString(\"yyyy-MM-dd\");\n QString log_file_name = current_date + \".log\";\n setLogDir(\"log\");\n setLogFile(\"log\\\\\" + log_file_name);\n}\n\n\/*\n * Logger: Set Log Dir\n * Input: QString dir path for file save\n * Return: NONE\n *\/\nvoid Logger::setLogDir(QString dir){\n \/\/create a dir for log save, default under applicationDirPath\/log\n QString app_dir_path = QCoreApplication::applicationDirPath();\n log_dir.mkdir(app_dir_path + \"\\\\\" + dir);\n}\n\n\/*\n * Logger: Set Log File\n * Input: QString file name for log\n * Return: NONE\n *\/\nvoid Logger::setLogFile(QString file){\n \/\/setup log file location\n QString app_dir_path = QCoreApplication::applicationDirPath();\n log_file.setFileName(app_dir_path + \"\\\\\" + file);\n \/\/if log file not exists, new one\n if(!log_file.exists()){\n \/\/only new, not do anything\n log_file.open(QIODevice::WriteOnly | QIODevice::Text);\n log_file.close();\n }\n}\n\n\/*\n * Logger: Log Information\n * Input: QString log type: [INFO],[ERROR],[DEBUG],etc. QString log message\n * Return: NONE\n *\/\nvoid Logger::log(QString log_type, QString log_msg){\n \/\/set the file open as R\/W, text and append\n log_file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append);\n \/\/append use QTextStream\n QTextStream in(&log_file);\n \/\/log format is \"hh:mm:ss[<log_type>]: <log_msg>\", time is the currentTime\n QTime time;\n in<<time.currentTime().toString(\"hh:mm:ss\")<<\" [\"<<log_type<<\"]: \"<<log_msg<<\"\\n\";\n \/\/log finished and close IO\n log_file.close();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VEXCL_DEVLIST_HPP\n#define VEXCL_DEVLIST_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file devlist.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief OpenCL device enumeration and context initialization.\n *\/\n\n#include <vector>\n#include <functional>\n#include <string>\n#include <cstdlib>\n\n#include <vexcl\/backend.hpp>\n#include <vexcl\/util.hpp>\n\n#ifdef __GNUC__\n# ifndef _GLIBCXX_USE_NANOSLEEP\n# define _GLIBCXX_USE_NANOSLEEP\n# endif\n#endif\n\nnamespace vex {\n\n\/\/\/ Device filters.\nnamespace Filter {\n \/\/\/ \\cond INTERNAL\n struct AnyFilter {\n bool operator()(const backend::device&) const {\n return true;\n }\n };\n \/\/\/ \\endcond\n\n \/\/\/ Selects any device. \\deprecated\n const AnyFilter All = {};\n\n \/\/\/ Selects any device.\n const AnyFilter Any = {};\n\n \/\/\/ Selects no more than given number of devices.\n \/**\n * \\note This filter should be the last in filter expression. In this case,\n * it will be applied only to devices which passed all other filters.\n * Otherwise, you could get less devices than planned (every time this\n * filter is applied, internal counter is decremented).\n *\/\n struct Count {\n explicit Count(int c) : count(c) {}\n\n bool operator()(const backend::device&) const {\n return --count >= 0;\n }\n\n private:\n mutable int count;\n };\n\n \/\/\/ Selects one device at the given position.\n \/**\n * Select one device at the given position in the list of devices\n * satisfying previously applied filters.\n *\/\n struct Position {\n explicit Position(int p) : pos(p) {}\n\n bool operator()(const backend::device&) const {\n return 0 == pos--;\n }\n\n private:\n mutable int pos;\n };\n\n \/\/\/ \\cond INTERNAL\n\n \/\/\/ Negation of a filter.\n struct NegateFilter {\n template <class Filter>\n NegateFilter(Filter&& filter)\n : filter(std::forward<Filter>(filter)) {}\n\n bool operator()(const backend::device &d) const {\n return !filter(d);\n }\n\n private:\n std::function<bool(const backend::device&)> filter;\n };\n\n \/\/\/ Filter join operators.\n enum FilterOp {\n FilterAnd, FilterOr\n };\n\n \/\/\/ Filter join expression template.\n template <FilterOp op>\n struct FilterBinaryOp {\n template <class LHS, class RHS>\n FilterBinaryOp(LHS&& lhs, RHS&& rhs)\n : lhs(std::forward<LHS>(lhs)), rhs(std::forward<RHS>(rhs)) {}\n\n bool operator()(const backend::device &d) const {\n \/\/ This could be hidden into FilterOp::apply() call (with FilterOp\n \/\/ being a struct instead of enum), but this form allows to rely on\n \/\/ short-circuit evaluation (important for mutable filters as Count\n \/\/ or Position).\n switch (op) {\n case FilterOr:\n return lhs(d) || rhs(d);\n case FilterAnd:\n default:\n return lhs(d) && rhs(d);\n }\n }\n\n private:\n std::function<bool(const backend::device&)> lhs;\n std::function<bool(const backend::device&)> rhs;\n };\n\n \/\/\/ \\endcond\n\n \/\/\/ Join two filters with AND operator.\n template <class LHS, class RHS>\n FilterBinaryOp<FilterAnd> operator&&(LHS&& lhs, RHS&& rhs)\n {\n return FilterBinaryOp<FilterAnd>(std::forward<LHS>(lhs), std::forward<RHS>(rhs));\n }\n\n \/\/\/ Join two filters with OR operator.\n template <class LHS, class RHS>\n FilterBinaryOp<FilterOr> operator||(LHS&& lhs, RHS&& rhs)\n {\n return FilterBinaryOp<FilterOr>(std::forward<LHS>(lhs), std::forward<RHS>(rhs));\n }\n\n \/\/\/ Negate a filter.\n template <class Filter>\n NegateFilter operator!(Filter&& filter) {\n return NegateFilter(std::forward<Filter>(filter));\n }\n\n \/\/\/ Runtime filter holder.\n \/**\n * The filter can be changed at runtime as in:\n \\code\n vex::Filter::General f = vex::Filter::Env;\n if (need_double) f = f && vex::Filter::DoublePrecision;\n \\endcode\n *\/\n struct General {\n template<class Filter>\n General(Filter filter) : filter(filter) { }\n\n bool operator()(const backend::device &d) const {\n return filter(d);\n }\n\n private:\n std::function<bool(const backend::device&)> filter;\n };\n\n \/\/\/ \\cond INTERNAL\n struct EnvFilter {\n EnvFilter()\n : filter( backend_env_filters() )\n {\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4996)\n#endif\n const char *maxdev = getenv(\"OCL_MAX_DEVICES\");\n const char *position = getenv(\"OCL_POSITION\");\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n if (maxdev) filter.push_back(Count(std::stoi(maxdev)));\n if (position) filter.push_back(Position(std::stoi(position)));\n }\n\n bool operator()(const backend::device &d) const {\n if (filter.empty()) return true;\n\n return std::all_of(\n filter.begin(), filter.end(),\n [d](const std::function<bool(const backend::device)> &f) {\n return f(d);\n });\n }\n\n private:\n std::vector< std::function<bool(const backend::device&)> > filter;\n };\n \/\/\/ \\endcond\n\n \/\/\/ Environment filter\n \/**\n * Selects devices with respect to environment variables. Recognized\n * variables are:\n *\n * \\li OCL_PLATFORM -- platform name;\n * \\li OCL_VENDOR -- device vendor;\n * \\li OCL_DEVICE -- device name;\n * \\li OCL_TYPE -- device type (CPU, GPU, ACCELERATOR);\n * \\li OCL_MAX_DEVICES -- maximum number of devices to use.\n * \\li OCL_POSITION -- devices position in the device list.\n *\n * \\note Since this filter possibly counts passed devices, it should be the\n * last in filter expression. Same reasoning applies as in case of\n * Filter::Count.\n *\/\n const EnvFilter Env;\n\n} \/\/ namespace Filter\n\nclass Context;\n\ntemplate <bool dummy = true>\nclass StaticContext {\n static_assert(dummy, \"dummy parameter should be true\");\n\n public:\n static void set(Context &ctx) {\n instance = &ctx;\n }\n\n static const Context& get() {\n precondition(instance, \"Uninitialized static context\");\n return *instance;\n }\n private:\n static Context *instance;\n};\n\ntemplate <bool dummy>\nContext* StaticContext<dummy>::instance = 0;\n\n\/\/\/ Returns reference to the latest instance of vex::Context.\ninline const Context& current_context() {\n return StaticContext<>::get();\n}\n\n\/\/\/ Check if type is a device filter.\ntemplate <class T, class Enable = void>\nstruct is_device_filter : std::false_type {};\n\ntemplate <class T>\nstruct is_device_filter<T,\n typename std::enable_if<\n std::is_same<\n bool, typename std::result_of<T(const backend::device&)>::type\n >::value\n >::type\n > : std::true_type\n{};\n\n\/\/\/ VexCL context holder.\n\/**\n * Holds vectors of backend::contexts and backend::command_queues returned by queue_list.\n *\/\nclass Context {\n public:\n \/\/\/ Initialize context from a device filter.\n template <class F>\n explicit Context(F&& filter,\n backend::command_queue_properties properties = 0,\n typename std::enable_if<is_device_filter<F>::value>::type* = 0)\n {\n std::tie(c, q) = backend::queue_list(std::forward<F>(filter), properties);\n\n#ifdef VEXCL_THROW_ON_EMPTY_CONTEXT\n precondition(!q.empty(), \"No compute devices found\");\n#endif\n\n StaticContext<>::set(*this);\n }\n\n \/\/\/ Initializes context from user-supplied list of backend::contexts and backend::command_queues.\n Context(const std::vector<std::pair<backend::context, backend::command_queue>> &user_ctx) {\n c.reserve(user_ctx.size());\n q.reserve(user_ctx.size());\n for(auto u = user_ctx.begin(); u != user_ctx.end(); u++) {\n c.push_back(u->first);\n q.push_back(u->second);\n }\n\n StaticContext<>::set(*this);\n }\n\n const std::vector<backend::context>& context() const {\n return c;\n }\n\n const backend::context& context(unsigned d) const {\n return c[d];\n }\n\n const std::vector<backend::command_queue>& queue() const {\n return q;\n }\n\n operator const std::vector<backend::command_queue>&() const {\n return q;\n }\n\n const backend::command_queue& queue(unsigned d) const {\n return q[d];\n }\n\n const backend::device device(unsigned d) const {\n return backend::device( backend::get_device_id(q[d]) );\n }\n\n size_t size() const {\n return q.size();\n }\n\n bool empty() const {\n return q.empty();\n }\n\n operator bool() const {\n return !empty();\n }\n\n void finish() const {\n for(auto queue = q.begin(); queue != q.end(); ++queue)\n queue->finish();\n }\n private:\n std::vector<backend::context> c;\n std::vector<backend::command_queue> q;\n};\n\n} \/\/ namespace vex\n\nnamespace std {\n\n\/\/\/ Output list of devices to stream.\ninline std::ostream& operator<<(std::ostream &os,\n const std::vector<vex::backend::command_queue> &queue)\n{\n unsigned p = 0;\n\n for(auto q = queue.begin(); q != queue.end(); q++)\n os << ++p << \". \" << *q << std::endl;\n\n return os;\n}\n\n\/\/\/ Output list of devices to stream.\ninline std::ostream& operator<<(std::ostream &os, const vex::Context &ctx) {\n return os << ctx.queue();\n}\n\n}\n\n#endif\n<commit_msg>Provide alternative Context constructor for user-supplied contexts\/queues<commit_after>#ifndef VEXCL_DEVLIST_HPP\n#define VEXCL_DEVLIST_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file devlist.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief OpenCL device enumeration and context initialization.\n *\/\n\n#include <vector>\n#include <functional>\n#include <string>\n#include <cstdlib>\n\n#include <vexcl\/backend.hpp>\n#include <vexcl\/util.hpp>\n\n#ifdef __GNUC__\n# ifndef _GLIBCXX_USE_NANOSLEEP\n# define _GLIBCXX_USE_NANOSLEEP\n# endif\n#endif\n\nnamespace vex {\n\n\/\/\/ Device filters.\nnamespace Filter {\n \/\/\/ \\cond INTERNAL\n struct AnyFilter {\n bool operator()(const backend::device&) const {\n return true;\n }\n };\n \/\/\/ \\endcond\n\n \/\/\/ Selects any device. \\deprecated\n const AnyFilter All = {};\n\n \/\/\/ Selects any device.\n const AnyFilter Any = {};\n\n \/\/\/ Selects no more than given number of devices.\n \/**\n * \\note This filter should be the last in filter expression. In this case,\n * it will be applied only to devices which passed all other filters.\n * Otherwise, you could get less devices than planned (every time this\n * filter is applied, internal counter is decremented).\n *\/\n struct Count {\n explicit Count(int c) : count(c) {}\n\n bool operator()(const backend::device&) const {\n return --count >= 0;\n }\n\n private:\n mutable int count;\n };\n\n \/\/\/ Selects one device at the given position.\n \/**\n * Select one device at the given position in the list of devices\n * satisfying previously applied filters.\n *\/\n struct Position {\n explicit Position(int p) : pos(p) {}\n\n bool operator()(const backend::device&) const {\n return 0 == pos--;\n }\n\n private:\n mutable int pos;\n };\n\n \/\/\/ \\cond INTERNAL\n\n \/\/\/ Negation of a filter.\n struct NegateFilter {\n template <class Filter>\n NegateFilter(Filter&& filter)\n : filter(std::forward<Filter>(filter)) {}\n\n bool operator()(const backend::device &d) const {\n return !filter(d);\n }\n\n private:\n std::function<bool(const backend::device&)> filter;\n };\n\n \/\/\/ Filter join operators.\n enum FilterOp {\n FilterAnd, FilterOr\n };\n\n \/\/\/ Filter join expression template.\n template <FilterOp op>\n struct FilterBinaryOp {\n template <class LHS, class RHS>\n FilterBinaryOp(LHS&& lhs, RHS&& rhs)\n : lhs(std::forward<LHS>(lhs)), rhs(std::forward<RHS>(rhs)) {}\n\n bool operator()(const backend::device &d) const {\n \/\/ This could be hidden into FilterOp::apply() call (with FilterOp\n \/\/ being a struct instead of enum), but this form allows to rely on\n \/\/ short-circuit evaluation (important for mutable filters as Count\n \/\/ or Position).\n switch (op) {\n case FilterOr:\n return lhs(d) || rhs(d);\n case FilterAnd:\n default:\n return lhs(d) && rhs(d);\n }\n }\n\n private:\n std::function<bool(const backend::device&)> lhs;\n std::function<bool(const backend::device&)> rhs;\n };\n\n \/\/\/ \\endcond\n\n \/\/\/ Join two filters with AND operator.\n template <class LHS, class RHS>\n FilterBinaryOp<FilterAnd> operator&&(LHS&& lhs, RHS&& rhs)\n {\n return FilterBinaryOp<FilterAnd>(std::forward<LHS>(lhs), std::forward<RHS>(rhs));\n }\n\n \/\/\/ Join two filters with OR operator.\n template <class LHS, class RHS>\n FilterBinaryOp<FilterOr> operator||(LHS&& lhs, RHS&& rhs)\n {\n return FilterBinaryOp<FilterOr>(std::forward<LHS>(lhs), std::forward<RHS>(rhs));\n }\n\n \/\/\/ Negate a filter.\n template <class Filter>\n NegateFilter operator!(Filter&& filter) {\n return NegateFilter(std::forward<Filter>(filter));\n }\n\n \/\/\/ Runtime filter holder.\n \/**\n * The filter can be changed at runtime as in:\n \\code\n vex::Filter::General f = vex::Filter::Env;\n if (need_double) f = f && vex::Filter::DoublePrecision;\n \\endcode\n *\/\n struct General {\n template<class Filter>\n General(Filter filter) : filter(filter) { }\n\n bool operator()(const backend::device &d) const {\n return filter(d);\n }\n\n private:\n std::function<bool(const backend::device&)> filter;\n };\n\n \/\/\/ \\cond INTERNAL\n struct EnvFilter {\n EnvFilter()\n : filter( backend_env_filters() )\n {\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4996)\n#endif\n const char *maxdev = getenv(\"OCL_MAX_DEVICES\");\n const char *position = getenv(\"OCL_POSITION\");\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n if (maxdev) filter.push_back(Count(std::stoi(maxdev)));\n if (position) filter.push_back(Position(std::stoi(position)));\n }\n\n bool operator()(const backend::device &d) const {\n if (filter.empty()) return true;\n\n return std::all_of(\n filter.begin(), filter.end(),\n [d](const std::function<bool(const backend::device)> &f) {\n return f(d);\n });\n }\n\n private:\n std::vector< std::function<bool(const backend::device&)> > filter;\n };\n \/\/\/ \\endcond\n\n \/\/\/ Environment filter\n \/**\n * Selects devices with respect to environment variables. Recognized\n * variables are:\n *\n * \\li OCL_PLATFORM -- platform name;\n * \\li OCL_VENDOR -- device vendor;\n * \\li OCL_DEVICE -- device name;\n * \\li OCL_TYPE -- device type (CPU, GPU, ACCELERATOR);\n * \\li OCL_MAX_DEVICES -- maximum number of devices to use.\n * \\li OCL_POSITION -- devices position in the device list.\n *\n * \\note Since this filter possibly counts passed devices, it should be the\n * last in filter expression. Same reasoning applies as in case of\n * Filter::Count.\n *\/\n const EnvFilter Env;\n\n} \/\/ namespace Filter\n\nclass Context;\n\ntemplate <bool dummy = true>\nclass StaticContext {\n static_assert(dummy, \"dummy parameter should be true\");\n\n public:\n static void set(Context &ctx) {\n instance = &ctx;\n }\n\n static const Context& get() {\n precondition(instance, \"Uninitialized static context\");\n return *instance;\n }\n private:\n static Context *instance;\n};\n\ntemplate <bool dummy>\nContext* StaticContext<dummy>::instance = 0;\n\n\/\/\/ Returns reference to the latest instance of vex::Context.\ninline const Context& current_context() {\n return StaticContext<>::get();\n}\n\n\/\/\/ Check if type is a device filter.\ntemplate <class T, class Enable = void>\nstruct is_device_filter : std::false_type {};\n\ntemplate <class T>\nstruct is_device_filter<T,\n typename std::enable_if<\n std::is_same<\n bool, typename std::result_of<T(const backend::device&)>::type\n >::value\n >::type\n > : std::true_type\n{};\n\n\/\/\/ VexCL context holder.\n\/**\n * Holds vectors of backend::contexts and backend::command_queues returned by queue_list.\n *\/\nclass Context {\n public:\n \/\/\/ Initialize context from a device filter.\n template <class F>\n explicit Context(F&& filter,\n backend::command_queue_properties properties = 0,\n typename std::enable_if<is_device_filter<F>::value>::type* = 0)\n {\n std::tie(c, q) = backend::queue_list(std::forward<F>(filter), properties);\n\n#ifdef VEXCL_THROW_ON_EMPTY_CONTEXT\n precondition(!q.empty(), \"No compute devices found\");\n#endif\n\n StaticContext<>::set(*this);\n }\n\n \/\/\/ Initializes context from user-supplied list of backend::contexts and backend::command_queues.\n Context(const std::vector<std::pair<backend::context, backend::command_queue>> &user_ctx) {\n c.reserve(user_ctx.size());\n q.reserve(user_ctx.size());\n for(auto u = user_ctx.begin(); u != user_ctx.end(); u++) {\n c.push_back(u->first);\n q.push_back(u->second);\n }\n\n StaticContext<>::set(*this);\n }\n\n \/\/\/ Initializes context from user-supplied list of backend::contexts and backend::command_queues.\n Context(std::vector<backend::context> c, std::vector<backend::command_queue> q)\n : c(std::move(c)), q(std::move(q))\n {\n StaticContext<>::set(*this);\n }\n\n const std::vector<backend::context>& context() const {\n return c;\n }\n\n const backend::context& context(unsigned d) const {\n return c[d];\n }\n\n const std::vector<backend::command_queue>& queue() const {\n return q;\n }\n\n operator const std::vector<backend::command_queue>&() const {\n return q;\n }\n\n const backend::command_queue& queue(unsigned d) const {\n return q[d];\n }\n\n const backend::device device(unsigned d) const {\n return backend::device( backend::get_device_id(q[d]) );\n }\n\n size_t size() const {\n return q.size();\n }\n\n bool empty() const {\n return q.empty();\n }\n\n operator bool() const {\n return !empty();\n }\n\n void finish() const {\n for(auto queue = q.begin(); queue != q.end(); ++queue)\n queue->finish();\n }\n private:\n std::vector<backend::context> c;\n std::vector<backend::command_queue> q;\n};\n\n} \/\/ namespace vex\n\nnamespace std {\n\n\/\/\/ Output list of devices to stream.\ninline std::ostream& operator<<(std::ostream &os,\n const std::vector<vex::backend::command_queue> &queue)\n{\n unsigned p = 0;\n\n for(auto q = queue.begin(); q != queue.end(); q++)\n os << ++p << \". \" << *q << std::endl;\n\n return os;\n}\n\n\/\/\/ Output list of devices to stream.\ninline std::ostream& operator<<(std::ostream &os, const vex::Context &ctx) {\n return os << ctx.queue();\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file LoadBalancer.cpp\n\/\/\/ @brief The LoadBalancer assigns work to the individual threads\n\/\/\/ in the computation of the special leaves in the\n\/\/\/ Lagarias-Miller-Odlyzko and Deleglise-Rivat prime\n\/\/\/ counting algorithms.\n\/\/\/\n\/\/\/ Simply parallelizing the computation of the special\n\/\/\/ leaves in the Lagarias-Miller-Odlyzko algorithm by\n\/\/\/ subdividing the sieve interval by the number of threads\n\/\/\/ into equally sized subintervals does not scale because\n\/\/\/ the distribution of the special leaves is highly skewed\n\/\/\/ and most special leaves are in the first few segments\n\/\/\/ whereas later on there are very few special leaves.\n\/\/\/\n\/\/\/ This LoadBalancer gradually increases the number of\n\/\/\/ segments to sieve as long the expected runtime of the\n\/\/\/ sieve distance is smaller than the expected finish time\n\/\/\/ of the algorithm. Near the end the LoadBalancer will\n\/\/\/ gradually decrease the number of segments to sieve in\n\/\/\/ order to prevent that 1 thread will run much longer\n\/\/\/ than all the other threads.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <LoadBalancer.hpp>\n#include <primecount-internal.hpp>\n#include <S2Status.hpp>\n#include <Sieve.hpp>\n#include <imath.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <calculator.hpp>\n#include <json.hpp>\n\n#include <stdint.h>\n#include <cmath>\n#include <string>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\n\nnamespace primecount {\n\ntemplate <typename T>\nvoid print_resume(double percent, T x)\n{\n print_log(\"Resume from \" + backup_file());\n print_status(percent, x);\n}\n\nint LoadBalancer::resume_threads() const\n{\n int threads = 0;\n\n if (is_resume(copy_, \"S2_hard\", x_, y_, z_))\n {\n int threads = copy_[\"S2_hard\"][\"threads\"];\n double percent = json_[\"S2_hard\"][\"percent\"];\n print_resume(percent, x_);\n }\n\n return threads;\n}\n\n\/\/\/ backup thread\nvoid LoadBalancer::backup(int threads,\n int thread_id,\n int64_t low,\n int64_t segments,\n int64_t segment_size)\n{\n double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);\n double seconds = get_wtime() - backup_time_;\n\n string tid = \"thread\" + to_string(thread_id);\n\n json_[\"S2_hard\"][\"threads\"] = threads;\n json_[\"S2_hard\"][\"low\"] = low_;\n json_[\"S2_hard\"][\"segments\"] = segments_;\n json_[\"S2_hard\"][\"segment_size\"] = segment_size_;\n json_[\"S2_hard\"][\"s2_hard\"] = to_string(s2_total_);\n json_[\"S2_hard\"][\"percent\"] = percent;\n json_[\"S2_hard\"][\"seconds\"] = get_wtime() - time_;\n json_[\"S2_hard\"][tid][\"low\"] = low;\n json_[\"S2_hard\"][tid][\"segments\"] = segments;\n json_[\"S2_hard\"][tid][\"segment_size\"] = segment_size;\n\n if (seconds > 60)\n {\n backup_time_ = get_wtime();\n store_backup(json_);\n }\n}\n\n\/\/\/ backup result\nvoid LoadBalancer::backup()\n{\n json_.erase(\"S2_hard\");\n\n json_[\"S2_hard\"][\"x\"] = to_string(x_);\n json_[\"S2_hard\"][\"y\"] = y_;\n json_[\"S2_hard\"][\"z\"] = z_;\n json_[\"S2_hard\"][\"s2_hard\"] = to_string(s2_total_);\n json_[\"S2_hard\"][\"percent\"] = 100;\n json_[\"S2_hard\"][\"seconds\"] = get_wtime() - time_;\n\n store_backup(json_);\n}\n\n\/\/\/ resume thread\nbool LoadBalancer::resume(int thread_id,\n int64_t& low,\n int64_t& segments,\n int64_t& segment_size)\n{\n bool resumed = false;\n\n #pragma omp critical (LoadBalancer)\n if (is_resume(copy_, \"S2_hard\", thread_id, x_, y_, z_))\n {\n string tid = \"thread\" + to_string(thread_id);\n low = copy_[\"S2_hard\"][tid][\"low\"];\n segments = copy_[\"S2_hard\"][tid][\"segments\"];\n segment_size = copy_[\"S2_hard\"][tid][\"segment_size\"];\n resumed = true;\n }\n\n return resumed;\n}\n\n\/\/ resume result\nbool LoadBalancer::resume(maxint_t& s2_hard, double& time) const\n{\n if (is_resume(copy_, \"S2_hard\", x_, y_, z_) &&\n copy_[\"S2_hard\"].count(\"low\") == 0)\n {\n double percent = copy_[\"S2_hard\"][\"percent\"];\n double seconds = copy_[\"S2_hard\"][\"seconds\"];\n\n s2_hard = calculator::eval<maxint_t>(copy_[\"S2_hard\"][\"s2_hard\"]);\n time = get_wtime() - seconds;\n print_resume(percent, x_);\n return true;\n }\n\n return false;\n}\n\nLoadBalancer::LoadBalancer(maxint_t x,\n int64_t y,\n int64_t z,\n maxint_t s2_approx) :\n low_(0),\n max_low_(0),\n x_(x),\n y_(y),\n z_(z),\n segments_(1),\n s2_total_(0),\n s2_approx_(s2_approx),\n time_(get_wtime()),\n backup_time_(get_wtime()),\n status_(x),\n json_(load_backup())\n{\n \/\/ Read only json copy that is accessed\n \/\/ in parallel by multiple threads\n copy_ = json_;\n\n if (is_resume(json_, \"S2_hard\", x_, y_, z_))\n {\n double seconds = copy_[\"S2_hard\"][\"seconds\"];\n s2_total_ = calculator::eval<maxint_t>(copy_[\"S2_hard\"][\"s2_hard\"]);\n time_ = get_wtime() - seconds;\n\n if (json_[\"S2_hard\"].count(\"low\"))\n {\n low_ = copy_[\"S2_hard\"][\"low\"];\n segments_ = copy_[\"S2_hard\"][\"segments\"];\n segment_size_ = copy_[\"S2_hard\"][\"segment_size\"];\n }\n }\n else\n {\n json_.erase(\"S2_hard\");\n json_[\"S2_hard\"][\"x\"] = to_string(x_);\n json_[\"S2_hard\"][\"y\"] = y_;\n json_[\"S2_hard\"][\"z\"] = z_;\n }\n\n init_size();\n maxint_t x16 = iroot<6>(x);\n double alpha = get_alpha(x, y);\n smallest_hard_leaf_ = (int64_t) (x \/ (y * sqrt(alpha) * x16));\n}\n\nvoid LoadBalancer::init_size()\n{\n \/\/ start with a tiny segment_size as most\n \/\/ special leaves are in the first few segments\n \/\/ and we need to ensure that all threads are\n \/\/ assigned an equal amount of work\n int64_t sqrtz = isqrt(z_);\n int64_t log = ilog(sqrtz);\n log = max(log, 1);\n segment_size_ = sqrtz \/ log;\n\n int64_t min_size = 1 << 9;\n segment_size_ = max(segment_size_, min_size);\n segment_size_ = Sieve::get_segment_size(segment_size_);\n\n \/\/ try to use a segment size that fits exactly\n \/\/ into the CPUs L1 data cache\n int64_t l1_dcache_size = 1 << 15;\n max_size_ = l1_dcache_size * 30;\n max_size_ = max(max_size_, sqrtz);\n max_size_ = Sieve::get_segment_size(max_size_);\n}\n\nmaxint_t LoadBalancer::get_result() const\n{\n return s2_total_;\n}\n\ndouble LoadBalancer::get_time() const\n{\n return time_;\n}\n\nbool LoadBalancer::get_work(int threads,\n int thread_id,\n int64_t* low,\n int64_t* segments,\n int64_t* segment_size,\n maxint_t s2,\n Runtime& runtime)\n{\n #pragma omp critical (LoadBalancer)\n {\n s2_total_ += s2;\n\n update(low, segments, runtime);\n\n *low = low_;\n *segments = segments_;\n *segment_size = segment_size_;\n\n low_ += segments_ * segment_size_;\n\n backup(threads, thread_id, *low, *segments, *segment_size);\n\n if (is_print())\n status_.print(s2_total_, s2_approx_);\n }\n\n return *low <= z_;\n}\n\nvoid LoadBalancer::update(int64_t* low,\n int64_t* segments,\n Runtime& runtime)\n{\n if (*low > max_low_)\n {\n max_low_ = *low;\n segments_ = *segments;\n\n if (segment_size_ < max_size_)\n segment_size_ = min(segment_size_ * 2, max_size_);\n else\n {\n double next = get_next(runtime);\n next = in_between(0.25, next, 2.0);\n next *= segments_;\n next = max(1.0, next);\n segments_ = (int64_t) next;\n }\n }\n\n auto high = low_ + segments_ * segment_size_;\n\n \/\/ Most hard special leaves are located just past\n \/\/ smallest_hard_leaf_. In order to prevent assigning\n \/\/ the bulk of work to a single thread we reduce\n \/\/ the number of segments to a minimum.\n \/\/\n if (smallest_hard_leaf_ >= low_ &&\n smallest_hard_leaf_ <= high)\n {\n segments_ = 1;\n }\n}\n\ndouble LoadBalancer::get_next(Runtime& runtime) const\n{\n double min_secs = runtime.init * 10;\n double run_secs = runtime.secs;\n\n min_secs = max(min_secs, 0.01);\n run_secs = max(run_secs, min_secs \/ 10);\n\n double rem = remaining_secs();\n double threshold = rem \/ 4;\n threshold = max(threshold, min_secs);\n\n return threshold \/ run_secs;\n}\n\n\/\/\/ Remaining seconds till finished\ndouble LoadBalancer::remaining_secs() const\n{\n double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);\n percent = in_between(20, percent, 100);\n\n double total_secs = get_wtime() - time_;\n double secs = total_secs * (100 \/ percent) - total_secs;\n return secs;\n}\n\n} \/\/ namespace\n<commit_msg>Remove critical section<commit_after>\/\/\/\n\/\/\/ @file LoadBalancer.cpp\n\/\/\/ @brief The LoadBalancer assigns work to the individual threads\n\/\/\/ in the computation of the special leaves in the\n\/\/\/ Lagarias-Miller-Odlyzko and Deleglise-Rivat prime\n\/\/\/ counting algorithms.\n\/\/\/\n\/\/\/ Simply parallelizing the computation of the special\n\/\/\/ leaves in the Lagarias-Miller-Odlyzko algorithm by\n\/\/\/ subdividing the sieve interval by the number of threads\n\/\/\/ into equally sized subintervals does not scale because\n\/\/\/ the distribution of the special leaves is highly skewed\n\/\/\/ and most special leaves are in the first few segments\n\/\/\/ whereas later on there are very few special leaves.\n\/\/\/\n\/\/\/ This LoadBalancer gradually increases the number of\n\/\/\/ segments to sieve as long the expected runtime of the\n\/\/\/ sieve distance is smaller than the expected finish time\n\/\/\/ of the algorithm. Near the end the LoadBalancer will\n\/\/\/ gradually decrease the number of segments to sieve in\n\/\/\/ order to prevent that 1 thread will run much longer\n\/\/\/ than all the other threads.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <LoadBalancer.hpp>\n#include <primecount-internal.hpp>\n#include <S2Status.hpp>\n#include <Sieve.hpp>\n#include <imath.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <calculator.hpp>\n#include <json.hpp>\n\n#include <stdint.h>\n#include <cmath>\n#include <string>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\n\nnamespace primecount {\n\ntemplate <typename T>\nvoid print_resume(double percent, T x)\n{\n print_log(\"Resume from \" + backup_file());\n print_status(percent, x);\n}\n\nint LoadBalancer::resume_threads() const\n{\n int threads = 0;\n\n if (is_resume(copy_, \"S2_hard\", x_, y_, z_))\n {\n int threads = copy_[\"S2_hard\"][\"threads\"];\n double percent = json_[\"S2_hard\"][\"percent\"];\n print_resume(percent, x_);\n }\n\n return threads;\n}\n\n\/\/\/ backup thread\nvoid LoadBalancer::backup(int threads,\n int thread_id,\n int64_t low,\n int64_t segments,\n int64_t segment_size)\n{\n double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);\n double seconds = get_wtime() - backup_time_;\n\n string tid = \"thread\" + to_string(thread_id);\n\n json_[\"S2_hard\"][\"threads\"] = threads;\n json_[\"S2_hard\"][\"low\"] = low_;\n json_[\"S2_hard\"][\"segments\"] = segments_;\n json_[\"S2_hard\"][\"segment_size\"] = segment_size_;\n json_[\"S2_hard\"][\"s2_hard\"] = to_string(s2_total_);\n json_[\"S2_hard\"][\"percent\"] = percent;\n json_[\"S2_hard\"][\"seconds\"] = get_wtime() - time_;\n json_[\"S2_hard\"][tid][\"low\"] = low;\n json_[\"S2_hard\"][tid][\"segments\"] = segments;\n json_[\"S2_hard\"][tid][\"segment_size\"] = segment_size;\n\n if (seconds > 60)\n {\n backup_time_ = get_wtime();\n store_backup(json_);\n }\n}\n\n\/\/\/ backup result\nvoid LoadBalancer::backup()\n{\n json_.erase(\"S2_hard\");\n\n json_[\"S2_hard\"][\"x\"] = to_string(x_);\n json_[\"S2_hard\"][\"y\"] = y_;\n json_[\"S2_hard\"][\"z\"] = z_;\n json_[\"S2_hard\"][\"s2_hard\"] = to_string(s2_total_);\n json_[\"S2_hard\"][\"percent\"] = 100;\n json_[\"S2_hard\"][\"seconds\"] = get_wtime() - time_;\n\n store_backup(json_);\n}\n\n\/\/\/ resume thread\nbool LoadBalancer::resume(int thread_id,\n int64_t& low,\n int64_t& segments,\n int64_t& segment_size)\n{\n if (is_resume(copy_, \"S2_hard\", thread_id, x_, y_, z_))\n {\n string tid = \"thread\" + to_string(thread_id);\n low = copy_[\"S2_hard\"][tid][\"low\"];\n segments = copy_[\"S2_hard\"][tid][\"segments\"];\n segment_size = copy_[\"S2_hard\"][tid][\"segment_size\"];\n return true;\n }\n\n return false;\n}\n\n\/\/ resume result\nbool LoadBalancer::resume(maxint_t& s2_hard, double& time) const\n{\n if (is_resume(copy_, \"S2_hard\", x_, y_, z_) &&\n copy_[\"S2_hard\"].count(\"low\") == 0)\n {\n double percent = copy_[\"S2_hard\"][\"percent\"];\n double seconds = copy_[\"S2_hard\"][\"seconds\"];\n\n s2_hard = calculator::eval<maxint_t>(copy_[\"S2_hard\"][\"s2_hard\"]);\n time = get_wtime() - seconds;\n print_resume(percent, x_);\n return true;\n }\n\n return false;\n}\n\nLoadBalancer::LoadBalancer(maxint_t x,\n int64_t y,\n int64_t z,\n maxint_t s2_approx) :\n low_(0),\n max_low_(0),\n x_(x),\n y_(y),\n z_(z),\n segments_(1),\n s2_total_(0),\n s2_approx_(s2_approx),\n time_(get_wtime()),\n backup_time_(get_wtime()),\n status_(x),\n json_(load_backup())\n{\n \/\/ Read only json copy that is accessed\n \/\/ in parallel by multiple threads\n copy_ = json_;\n\n if (is_resume(json_, \"S2_hard\", x_, y_, z_))\n {\n double seconds = copy_[\"S2_hard\"][\"seconds\"];\n s2_total_ = calculator::eval<maxint_t>(copy_[\"S2_hard\"][\"s2_hard\"]);\n time_ = get_wtime() - seconds;\n\n if (json_[\"S2_hard\"].count(\"low\"))\n {\n low_ = copy_[\"S2_hard\"][\"low\"];\n segments_ = copy_[\"S2_hard\"][\"segments\"];\n segment_size_ = copy_[\"S2_hard\"][\"segment_size\"];\n }\n }\n else\n {\n json_.erase(\"S2_hard\");\n json_[\"S2_hard\"][\"x\"] = to_string(x_);\n json_[\"S2_hard\"][\"y\"] = y_;\n json_[\"S2_hard\"][\"z\"] = z_;\n }\n\n init_size();\n maxint_t x16 = iroot<6>(x);\n double alpha = get_alpha(x, y);\n smallest_hard_leaf_ = (int64_t) (x \/ (y * sqrt(alpha) * x16));\n}\n\nvoid LoadBalancer::init_size()\n{\n \/\/ start with a tiny segment_size as most\n \/\/ special leaves are in the first few segments\n \/\/ and we need to ensure that all threads are\n \/\/ assigned an equal amount of work\n int64_t sqrtz = isqrt(z_);\n int64_t log = ilog(sqrtz);\n log = max(log, 1);\n segment_size_ = sqrtz \/ log;\n\n int64_t min_size = 1 << 9;\n segment_size_ = max(segment_size_, min_size);\n segment_size_ = Sieve::get_segment_size(segment_size_);\n\n \/\/ try to use a segment size that fits exactly\n \/\/ into the CPUs L1 data cache\n int64_t l1_dcache_size = 1 << 15;\n max_size_ = l1_dcache_size * 30;\n max_size_ = max(max_size_, sqrtz);\n max_size_ = Sieve::get_segment_size(max_size_);\n}\n\nmaxint_t LoadBalancer::get_result() const\n{\n return s2_total_;\n}\n\ndouble LoadBalancer::get_time() const\n{\n return time_;\n}\n\nbool LoadBalancer::get_work(int threads,\n int thread_id,\n int64_t* low,\n int64_t* segments,\n int64_t* segment_size,\n maxint_t s2,\n Runtime& runtime)\n{\n #pragma omp critical (LoadBalancer)\n {\n s2_total_ += s2;\n\n update(low, segments, runtime);\n\n *low = low_;\n *segments = segments_;\n *segment_size = segment_size_;\n\n low_ += segments_ * segment_size_;\n\n backup(threads, thread_id, *low, *segments, *segment_size);\n\n if (is_print())\n status_.print(s2_total_, s2_approx_);\n }\n\n return *low <= z_;\n}\n\nvoid LoadBalancer::update(int64_t* low,\n int64_t* segments,\n Runtime& runtime)\n{\n if (*low > max_low_)\n {\n max_low_ = *low;\n segments_ = *segments;\n\n if (segment_size_ < max_size_)\n segment_size_ = min(segment_size_ * 2, max_size_);\n else\n {\n double next = get_next(runtime);\n next = in_between(0.25, next, 2.0);\n next *= segments_;\n next = max(1.0, next);\n segments_ = (int64_t) next;\n }\n }\n\n auto high = low_ + segments_ * segment_size_;\n\n \/\/ Most hard special leaves are located just past\n \/\/ smallest_hard_leaf_. In order to prevent assigning\n \/\/ the bulk of work to a single thread we reduce\n \/\/ the number of segments to a minimum.\n \/\/\n if (smallest_hard_leaf_ >= low_ &&\n smallest_hard_leaf_ <= high)\n {\n segments_ = 1;\n }\n}\n\ndouble LoadBalancer::get_next(Runtime& runtime) const\n{\n double min_secs = runtime.init * 10;\n double run_secs = runtime.secs;\n\n min_secs = max(min_secs, 0.01);\n run_secs = max(run_secs, min_secs \/ 10);\n\n double rem = remaining_secs();\n double threshold = rem \/ 4;\n threshold = max(threshold, min_secs);\n\n return threshold \/ run_secs;\n}\n\n\/\/\/ Remaining seconds till finished\ndouble LoadBalancer::remaining_secs() const\n{\n double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);\n percent = in_between(20, percent, 100);\n\n double total_secs = get_wtime() - time_;\n double secs = total_secs * (100 \/ percent) - total_secs;\n return secs;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n\n MYPROJECT: A software package for whatever.\n\n Copyright (c) University College London (UCL). All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.\n\n See LICENSE.txt in the top level directory for details.\n\n=============================================================================*\/\n\n#include \"mpQQuickVTKView.h\"\n#include <vtkRendererCollection.h>\n#include <vtkEventQtSlotConnect.h>\n#include <QVTKInteractorAdapter.h>\n#include <QMutexLocker>\n\nnamespace mp {\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::~QQuickVTKView()\n{\n if (m_VTKRenderWindow)\n {\n m_VTKRenderWindowInteractor->Disable();\n m_VTKRenderWindow->SetInteractor(nullptr);\n#ifdef BUILD_VTK_OpenGL2\n m_VTKRenderWindow->SetReadyForRendering(false);\n#endif\n m_VTKRenderWindow->RemoveAllObservers();\n vtkRendererCollection *c = m_VTKRenderWindow->GetRenderers();\n vtkRenderer *v = nullptr;\n while(v = c->GetNextItem(), v != nullptr)\n {\n m_VTKRenderWindow->RemoveRenderer(v);\n }\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(QWindow * parent)\n: QQuickView(parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(QQmlEngine * engine, QWindow * parent)\n: QQuickView(engine, parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(const QUrl & source, QWindow * parent)\n: QQuickView(source, parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::Init()\n{\n m_VTKRenderWindow = vtkExternalOpenGLRenderWindow::New();\n\n m_VTKInteractorStyleMultiTouchCamera = vtkInteractorStyleMultiTouchCamera::New();\n\n m_VTKRenderWindowInteractor = vtkRenderWindowInteractor::New();\n m_VTKRenderWindowInteractor->SetRenderWindow(m_VTKRenderWindow);\n m_VTKRenderWindowInteractor->SetInteractorStyle(m_VTKInteractorStyleMultiTouchCamera);\n m_VTKRenderWindowInteractor->SetEnableRender(false); \/\/ this is to stop interactor triggering Render().\n\n m_VTKInteractorAdapter = new QVTKInteractorAdapter(this);\n m_VTKInteractorAdapter->SetDevicePixelRatio(this->devicePixelRatio());\n\n m_EventSlotConnector = vtkSmartPointer<vtkEventQtSlotConnect>::New();\n\n connect(this, SIGNAL(beforeRendering()), this, SLOT(Render()), Qt::DirectConnection);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::AddRenderer(vtkRenderer* r)\n{\n m_VTKRenderWindow->AddRenderer(r);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::RemoveRenderer(vtkRenderer *r)\n{\n m_VTKRenderWindow->RemoveRenderer(r);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::SetEraseBeforeVTKRendering(bool b)\n{\n m_EraseBeforeVTKRendering = b;\n m_VTKRenderWindow->SetErase(m_EraseBeforeVTKRendering);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::Render()\n{\n emit beforeVTKRendering();\n\n QMutexLocker lock(&m_Mutex);\n\n m_VTKRenderWindow->Render();\n emit afterVTKRendering();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::SetEnabled(bool isEnabled)\n{\n if (isEnabled)\n {\n m_VTKRenderWindowInteractor->Enable();\n }\n else\n {\n m_VTKRenderWindowInteractor->Disable();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool QQuickVTKView::event(QEvent *e)\n{\n if(e->type() == QEvent::TouchBegin ||\n e->type() == QEvent::TouchUpdate ||\n e->type() == QEvent::TouchEnd\n )\n {\n QMutexLocker lock(&m_Mutex);\n if(m_VTKRenderWindow \n#ifdef BUILD_VTK_OpenGL2\n && m_VTKRenderWindow->GetReadyForRendering()\n#endif\n )\n {\n m_VTKInteractorAdapter->ProcessEvent(e, m_VTKRenderWindow->GetInteractor());\n if (e->isAccepted())\n {\n return true;\n }\n }\n }\n return QQuickView::event(e);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool QQuickVTKView::ProcessEvent(QEvent* e)\n{\n QMutexLocker lock(&m_Mutex);\n if (m_VTKRenderWindow \n#ifdef BUILD_VTK_OpenGL2\n && m_VTKRenderWindow->GetReadyForRendering()\n#endif\n )\n {\n return m_VTKInteractorAdapter->ProcessEvent(e, m_VTKRenderWindowInteractor);\n }\n return false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mousePressEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseMoveEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseReleaseEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseDoubleClickEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::keyPressEvent(QKeyEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::keyReleaseEvent(QKeyEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::enterEvent(QEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::leaveEvent(QEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::wheelEvent(QWheelEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\/\/-----------------------------------------------------------------------------\n} \/\/ end namespace\n<commit_msg>Issue #39: Update comment, VTK interaction working on Windows, Mac.<commit_after>\/*=============================================================================\n\n MYPROJECT: A software package for whatever.\n\n Copyright (c) University College London (UCL). All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.\n\n See LICENSE.txt in the top level directory for details.\n\n=============================================================================*\/\n\n#include \"mpQQuickVTKView.h\"\n#include <vtkRendererCollection.h>\n#include <vtkEventQtSlotConnect.h>\n#include <QVTKInteractorAdapter.h>\n#include <QMutexLocker>\n\nnamespace mp {\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::~QQuickVTKView()\n{\n if (m_VTKRenderWindow)\n {\n m_VTKRenderWindowInteractor->Disable();\n m_VTKRenderWindow->SetInteractor(nullptr);\n#ifdef BUILD_VTK_OpenGL2\n m_VTKRenderWindow->SetReadyForRendering(false);\n#endif\n m_VTKRenderWindow->RemoveAllObservers();\n vtkRendererCollection *c = m_VTKRenderWindow->GetRenderers();\n vtkRenderer *v = nullptr;\n while(v = c->GetNextItem(), v != nullptr)\n {\n m_VTKRenderWindow->RemoveRenderer(v);\n }\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(QWindow * parent)\n: QQuickView(parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(QQmlEngine * engine, QWindow * parent)\n: QQuickView(engine, parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQQuickVTKView::QQuickVTKView(const QUrl & source, QWindow * parent)\n: QQuickView(source, parent)\n, m_Mutex(QMutex::NonRecursive)\n, m_VTKRenderWindow(nullptr)\n, m_VTKRenderWindowInteractor(nullptr)\n, m_VTKInteractorStyleMultiTouchCamera(nullptr)\n, m_EraseBeforeVTKRendering(true)\n{\n this->Init();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::Init()\n{\n m_VTKRenderWindow = vtkExternalOpenGLRenderWindow::New();\n\n m_VTKInteractorStyleMultiTouchCamera = vtkInteractorStyleMultiTouchCamera::New();\n\n m_VTKRenderWindowInteractor = vtkRenderWindowInteractor::New();\n m_VTKRenderWindowInteractor->SetRenderWindow(m_VTKRenderWindow);\n m_VTKRenderWindowInteractor->SetInteractorStyle(m_VTKInteractorStyleMultiTouchCamera);\n\n \/\/ This is to stop interactor triggering Render(),\n \/\/ as the rendering is done in the scene graph thread,\n \/\/ but the interaction is done in the gui thread.\n m_VTKRenderWindowInteractor->SetEnableRender(false);\n\n m_VTKInteractorAdapter = new QVTKInteractorAdapter(this);\n m_VTKInteractorAdapter->SetDevicePixelRatio(this->devicePixelRatio());\n\n m_EventSlotConnector = vtkSmartPointer<vtkEventQtSlotConnect>::New();\n\n connect(this, SIGNAL(beforeRendering()), this, SLOT(Render()), Qt::DirectConnection);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::AddRenderer(vtkRenderer* r)\n{\n m_VTKRenderWindow->AddRenderer(r);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::RemoveRenderer(vtkRenderer *r)\n{\n m_VTKRenderWindow->RemoveRenderer(r);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::SetEraseBeforeVTKRendering(bool b)\n{\n m_EraseBeforeVTKRendering = b;\n m_VTKRenderWindow->SetErase(m_EraseBeforeVTKRendering);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::Render()\n{\n emit beforeVTKRendering();\n\n QMutexLocker lock(&m_Mutex);\n\n m_VTKRenderWindow->Render();\n emit afterVTKRendering();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::SetEnabled(bool isEnabled)\n{\n if (isEnabled)\n {\n m_VTKRenderWindowInteractor->Enable();\n }\n else\n {\n m_VTKRenderWindowInteractor->Disable();\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool QQuickVTKView::event(QEvent *e)\n{\n if(e->type() == QEvent::TouchBegin ||\n e->type() == QEvent::TouchUpdate ||\n e->type() == QEvent::TouchEnd\n )\n {\n QMutexLocker lock(&m_Mutex);\n if(m_VTKRenderWindow \n#ifdef BUILD_VTK_OpenGL2\n && m_VTKRenderWindow->GetReadyForRendering()\n#endif\n )\n {\n m_VTKInteractorAdapter->ProcessEvent(e, m_VTKRenderWindow->GetInteractor());\n if (e->isAccepted())\n {\n return true;\n }\n }\n }\n return QQuickView::event(e);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool QQuickVTKView::ProcessEvent(QEvent* e)\n{\n QMutexLocker lock(&m_Mutex);\n if (m_VTKRenderWindow \n#ifdef BUILD_VTK_OpenGL2\n && m_VTKRenderWindow->GetReadyForRendering()\n#endif\n )\n {\n return m_VTKInteractorAdapter->ProcessEvent(e, m_VTKRenderWindowInteractor);\n }\n return false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mousePressEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseMoveEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseReleaseEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::mouseDoubleClickEvent(QMouseEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::keyPressEvent(QKeyEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::keyReleaseEvent(QKeyEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::enterEvent(QEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::leaveEvent(QEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid QQuickVTKView::wheelEvent(QWheelEvent* event)\n{\n this->ProcessEvent(event);\n}\n\n\/\/-----------------------------------------------------------------------------\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>#include <stdint.h>\n\n#include <QtEndian>\n\n#include \"viewer.h\"\n#include \"ui_viewer.h\"\n\nViewer::Viewer(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Viewer)\n{\n ui->setupUi(this);\n}\n\nViewer::~Viewer()\n{\n delete ui;\n}\n\nvoid Viewer::message(QString message)\n{\n ui->statusLabel->setText(message);\n ui->statusLabel->setStyleSheet(\"color: black; font-weight: normal;\");\n}\n\nvoid Viewer::error(const char *message, int error)\n{\n ui->statusLabel->setText(QString(\"%1 (%2)\").arg(message).arg(error));\n ui->statusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n}\n\nvoid Viewer::on_scanButton_clicked()\n{\n int timeout = ui->timeoutSlider->value();\n\n if (timeout == ui->timeoutSlider->maximum())\n timeout = -1;\n else\n timeout *= 1000;\n\n Fingerprint *fingerprint;\n try {\n fingerprint = scanner->getFingerprint(timeout);\n } catch (ScannerTimeout &e) {\n message(\"Timeout...\");\n return;\n } catch (ScannerException &e) {\n error(e.what(), e.code());\n return;\n }\n\n QString status;\n scene.clear();\n ui->templateText->clear();\n\n if (fingerprint->image) {\n QImage *image = fingerprint->image->getImage();\n pixmap = QPixmap::fromImage(*image);\n scene.addPixmap(pixmap);\n scene.setSceneRect(pixmap.rect());\n scene.addRect(pixmap.rect(), QPen(Qt::blue), QBrush());\n message(QString(\"Obtained %1x%2 pixels large image\").arg(image->width()).arg(image->height()));\n delete image;\n }\n\n if (fingerprint->minutiaeRecord) {\n ui->templateText->setPlainText(fingerprint->minutiaeRecord->getRecord());\n\n if (fingerprint->image) {\n for (std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin(); m != fingerprint->minutiaeRecord->minutiae.end(); m++) {\n scene.addRect(m->x - 1, m->y - 1, 3, 3, QPen(Qt::red), QBrush());\n scene.addRect(m->x - 2, m->y - 2, 5, 5, QPen(Qt::red), QBrush());\n }\n }\n }\n\n ui->imageView->setScene(&scene);\n\n delete fingerprint;\n}\n\nvoid Viewer::on_onOffButton_clicked()\n{\n if (!enabled) {\n try {\n scanner = new Scanner();\n message(QString(\"Turned on scanner '%1'\").arg(scanner->getName()));\n enabled = true;\n } catch (ScannerException &e) {\n error(e.what(), e.code());\n }\n } else {\n delete scanner;\n ui->templateText->clear();\n scene.clear();\n message(\"Turned off scanner\");\n enabled = false;\n }\n\n ui->scanButton->setEnabled(enabled);\n ui->timeoutSlider->setEnabled(enabled);\n ui->onOffButton->setText(enabled ? \"Turn off\" : \"Turn on\");\n}\n\nvoid Viewer::on_timeoutSlider_sliderMoved(int position)\n{\n QString timeout;\n\n if (position == ui->timeoutSlider->maximum())\n timeout = QString(\"infinite\");\n else if (position == 0)\n timeout = QString(\"none\");\n else if (position == 1)\n timeout = QString(\"1 second\");\n else\n timeout = QString(\"%1 seconds\").arg(position);\n\n ui->timeoutLabel->setText(QString(\"Timeout: %1\").arg(timeout));\n}\n<commit_msg>viewer: Initialise critical member<commit_after>#include <stdint.h>\n\n#include <QtEndian>\n\n#include \"viewer.h\"\n#include \"ui_viewer.h\"\n\nViewer::Viewer(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Viewer),\n enabled(false)\n{\n ui->setupUi(this);\n}\n\nViewer::~Viewer()\n{\n delete ui;\n}\n\nvoid Viewer::message(QString message)\n{\n ui->statusLabel->setText(message);\n ui->statusLabel->setStyleSheet(\"color: black; font-weight: normal;\");\n}\n\nvoid Viewer::error(const char *message, int error)\n{\n ui->statusLabel->setText(QString(\"%1 (%2)\").arg(message).arg(error));\n ui->statusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n}\n\nvoid Viewer::on_scanButton_clicked()\n{\n int timeout = ui->timeoutSlider->value();\n\n if (timeout == ui->timeoutSlider->maximum())\n timeout = -1;\n else\n timeout *= 1000;\n\n Fingerprint *fingerprint;\n try {\n fingerprint = scanner->getFingerprint(timeout);\n } catch (ScannerTimeout &e) {\n message(\"Timeout...\");\n return;\n } catch (ScannerException &e) {\n error(e.what(), e.code());\n return;\n }\n\n QString status;\n scene.clear();\n ui->templateText->clear();\n\n if (fingerprint->image) {\n QImage *image = fingerprint->image->getImage();\n pixmap = QPixmap::fromImage(*image);\n scene.addPixmap(pixmap);\n scene.setSceneRect(pixmap.rect());\n scene.addRect(pixmap.rect(), QPen(Qt::blue), QBrush());\n message(QString(\"Obtained %1x%2 pixels large image\").arg(image->width()).arg(image->height()));\n delete image;\n }\n\n if (fingerprint->minutiaeRecord) {\n ui->templateText->setPlainText(fingerprint->minutiaeRecord->getRecord());\n\n if (fingerprint->image) {\n for (std::list<FingerprintMinutia>::iterator m = fingerprint->minutiaeRecord->minutiae.begin(); m != fingerprint->minutiaeRecord->minutiae.end(); m++) {\n scene.addRect(m->x - 1, m->y - 1, 3, 3, QPen(Qt::red), QBrush());\n scene.addRect(m->x - 2, m->y - 2, 5, 5, QPen(Qt::red), QBrush());\n }\n }\n }\n\n ui->imageView->setScene(&scene);\n\n delete fingerprint;\n}\n\nvoid Viewer::on_onOffButton_clicked()\n{\n if (!enabled) {\n try {\n scanner = new Scanner();\n message(QString(\"Turned on scanner '%1'\").arg(scanner->getName()));\n enabled = true;\n } catch (ScannerException &e) {\n error(e.what(), e.code());\n }\n } else {\n delete scanner;\n ui->templateText->clear();\n scene.clear();\n message(\"Turned off scanner\");\n enabled = false;\n }\n\n ui->scanButton->setEnabled(enabled);\n ui->timeoutSlider->setEnabled(enabled);\n ui->onOffButton->setText(enabled ? \"Turn off\" : \"Turn on\");\n}\n\nvoid Viewer::on_timeoutSlider_sliderMoved(int position)\n{\n QString timeout;\n\n if (position == ui->timeoutSlider->maximum())\n timeout = QString(\"infinite\");\n else if (position == 0)\n timeout = QString(\"none\");\n else if (position == 1)\n timeout = QString(\"1 second\");\n else\n timeout = QString(\"%1 seconds\").arg(position);\n\n ui->timeoutLabel->setText(QString(\"Timeout: %1\").arg(timeout));\n}\n<|endoftext|>"} {"text":"<commit_before>#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include \"wowfoot.h\"\n#include <assert.h>\n#include <string.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include \"win32.h\"\n#include \"util\/exception.h\"\n\nusing namespace std;\n\nclass SourceHandler : public RequestHandler {\npublic:\n\tvirtual ResponseData* handleRequest(const char* urlPart, MHD_Connection*);\n\tvirtual void cleanup(ResponseData*) __attribute__((noreturn));\n\tvirtual void unload(const char*, size_t) {}\n\tvirtual void load() {}\n};\n\nstatic int sh(const char* cmd) {\n\tprintf(\"%s\\n\", cmd);\n\treturn system(cmd);\n}\n\nResponseData* SourceHandler::handleRequest(const char* urlPart, MHD_Connection* conn) {\n\tassert(*urlPart == 0);\n\tint res;\n\n\t\/\/ call TAR\n\tchar* cwd = getcwd(NULL, 0);\n\tERRNO(chdir(\"..\/..\"));\n\tERRNO(sh(\"tar -czf t.tgz -X wowfoot\/.gitignore --exclude=.git wowfoot\"));\n\tERRNO(chdir(cwd));\n\tfree(cwd);\n\n\t\/\/ send file\n\tint code;\n\tuint64_t size;\n\ttime_t fileDate;\n\tchar* text = readFileForHTTP(\"..\/..\/t.tgz\", size, 0, fileDate, code);\n\tEASSERT(text);\n\tMHD_Response* resp = MHD_create_response_from_data(size, text, 1, 0);\n\tassert(resp);\n\t{\n\t\t\/\/ todo: correct mime type?\n\t\tres = MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE, \"archive\/tgz\");\n\t\tassert(res == MHD_YES);\n\t\t\/\/ todo: rename file; have browser treat it as an attachment, so it gets saved to disk.\n\t\tres = MHD_add_response_header(resp, \"Content-Disposition\", \"attachment; filename=\\\"source.tgz\\\"\");\n\t\tassert(res == MHD_YES);\n\t}\n\tres = MHD_queue_response(conn, code, resp);\n\tassert(res == MHD_YES);\n\tMHD_destroy_response(resp);\n\treturn NULL;\n}\n\nvoid SourceHandler::cleanup(ResponseData*) {\n\t\/\/ this function should never be called.\n\tabort();\n}\n\nvoid mountSource() {\n\tinsertExactPattern(PatternPair(\"\/source\", new SourceHandler()));\n}\n<commit_msg>sourceHandler: .git\/info\/exclude<commit_after>#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include \"wowfoot.h\"\n#include <assert.h>\n#include <string.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include \"win32.h\"\n#include \"util\/exception.h\"\n\nusing namespace std;\n\nclass SourceHandler : public RequestHandler {\npublic:\n\tvirtual ResponseData* handleRequest(const char* urlPart, MHD_Connection*);\n\tvirtual void cleanup(ResponseData*) __attribute__((noreturn));\n\tvirtual void unload(const char*, size_t) {}\n\tvirtual void load() {}\n};\n\nstatic int sh(const char* cmd) {\n\tprintf(\"%s\\n\", cmd);\n\treturn system(cmd);\n}\n\nResponseData* SourceHandler::handleRequest(const char* urlPart, MHD_Connection* conn) {\n\tassert(*urlPart == 0);\n\tint res;\n\n\t\/\/ call TAR\n\tchar* cwd = getcwd(NULL, 0);\n\tERRNO(chdir(\"..\/..\"));\n\tERRNO(sh(\"tar -czf t.tgz -X wowfoot\/.gitignore -X wowfoot\/.git\/info\/exclude --exclude=.git wowfoot\"));\n\tERRNO(chdir(cwd));\n\tfree(cwd);\n\n\t\/\/ send file\n\tint code;\n\tuint64_t size;\n\ttime_t fileDate;\n\tchar* text = readFileForHTTP(\"..\/..\/t.tgz\", size, 0, fileDate, code);\n\tEASSERT(text);\n\tMHD_Response* resp = MHD_create_response_from_data(size, text, 1, 0);\n\tassert(resp);\n\t{\n\t\t\/\/ todo: correct mime type?\n\t\tres = MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE, \"archive\/tgz\");\n\t\tassert(res == MHD_YES);\n\t\t\/\/ todo: rename file; have browser treat it as an attachment, so it gets saved to disk.\n\t\tres = MHD_add_response_header(resp, \"Content-Disposition\", \"attachment; filename=\\\"source.tgz\\\"\");\n\t\tassert(res == MHD_YES);\n\t}\n\tres = MHD_queue_response(conn, code, resp);\n\tassert(res == MHD_YES);\n\tMHD_destroy_response(resp);\n\treturn NULL;\n}\n\nvoid SourceHandler::cleanup(ResponseData*) {\n\t\/\/ this function should never be called.\n\tabort();\n}\n\nvoid mountSource() {\n\tinsertExactPattern(PatternPair(\"\/source\", new SourceHandler()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include <cstdio>\n#include <sys\/stat.h>\n#include \"core\/clever.h\"\n#include \"core\/value.h\"\n#include \"core\/vm.h\"\n#include \"modules\/std\/file\/cfile.h\"\n#include \"modules\/std\/file\/file.h\"\n#include \"modules\/std\/core\/function.h\"\n#include \"types\/type.h\"\n\n\nnamespace clever { namespace modules { namespace std {\n\nnamespace file {\n\nstatic CLEVER_FUNCTION(rename)\n{\n\tif (!clever_static_check_args(\"ss\")) {\n\t\treturn;\n\t}\n\n\tconst char* from = args[0]->getStr()->c_str();\n\tconst char* to = args[1]->getStr()->c_str();\n\tstruct stat info;\n\n\t\/\/ Check if file from exists\n\tif (stat(from, &info) != 0) {\n\t\tclever_throw(\"File FROM does not exists.\");\n\t\treturn;\n\t}\n\n\tresult->setBool(::std::rename(from, to) == 0);\n}\n\nstatic CLEVER_FUNCTION(remove)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* file = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\t\/\/ Check if file from exists\n\tif (stat(file, &info) != 0) {\n\t\tclever_throw(\"File does not exists.\");\n\t\treturn;\n\t}\n\n\tresult->setBool(::std::remove(file) == 0);\n}\n\nstatic CLEVER_FUNCTION(file_exists)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* file = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\tresult->setBool(stat(file, &info) == 0);\n}\n\nstatic CLEVER_FUNCTION(is_dir)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* dir = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\tif (stat(dir, &info) != 0) {\n\t\tresult->setBool(false);\n return;\n\t}\n\n\tresult->setBool((info.st_mode & S_IFMT) == S_IFDIR);\n}\n\n} \/\/ clever::modules::std::file\n\n\/\/\/ Initializes Standard File module\nCLEVER_MODULE_INIT(FileModule)\n{\n\taddFunction(new Function(\"rename\", &CLEVER_NS_FNAME(file, rename)));\n\taddFunction(new Function(\"remove\", &CLEVER_NS_FNAME(file, remove)));\n\taddFunction(new Function(\"file_exists\", &CLEVER_NS_FNAME(file, file_exists)));\n\taddFunction(new Function(\"is_dir\", &CLEVER_NS_FNAME(file, is_dir)));\n\n\taddType(new CFile);\n}\n\n}}} \/\/ clever::modules::std\n<commit_msg>- Added glob() function to std.file module<commit_after>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include <cstdio>\n#include <sys\/stat.h>\n#ifndef _WIN32\n#include <glob.h>\n#else\n#include <windows.h>\n#endif\n#include \"core\/clever.h\"\n#include \"core\/value.h\"\n#include \"core\/vm.h\"\n#include \"modules\/std\/file\/cfile.h\"\n#include \"modules\/std\/file\/file.h\"\n#include \"modules\/std\/core\/function.h\"\n#include \"modules\/std\/core\/array.h\"\n#include \"types\/type.h\"\n\n\nnamespace clever { namespace modules { namespace std {\n\nnamespace file {\n\n\/\/ rename(String current_path, String new_path)\nstatic CLEVER_FUNCTION(rename)\n{\n\tif (!clever_static_check_args(\"ss\")) {\n\t\treturn;\n\t}\n\n\tconst char* from = args[0]->getStr()->c_str();\n\tconst char* to = args[1]->getStr()->c_str();\n\tstruct stat info;\n\n\t\/\/ Check if file from exists\n\tif (stat(from, &info) != 0) {\n\t\tclever_throw(\"File FROM does not exists.\");\n\t\treturn;\n\t}\n\n\tresult->setBool(::std::rename(from, to) == 0);\n}\n\n\/\/ remove(String path)\nstatic CLEVER_FUNCTION(remove)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* file = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\t\/\/ Check if file from exists\n\tif (stat(file, &info) != 0) {\n\t\tclever_throw(\"File does not exists.\");\n\t\treturn;\n\t}\n\n\tresult->setBool(::std::remove(file) == 0);\n}\n\n\/\/ file_exists(String path)\nstatic CLEVER_FUNCTION(file_exists)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* file = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\tresult->setBool(stat(file, &info) == 0);\n}\n\n\/\/ is_dir(String path)\nstatic CLEVER_FUNCTION(is_dir)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\n\tconst char* dir = args[0]->getStr()->c_str();\n\tstruct stat info;\n\n\tif (stat(dir, &info) != 0) {\n\t\tresult->setBool(false);\n return;\n\t}\n\n\tresult->setBool((info.st_mode & S_IFMT) == S_IFDIR);\n}\n\n\/\/ glob(String pattern)\nstatic CLEVER_FUNCTION(glob)\n{\n\tif (!clever_static_check_args(\"s\")) {\n\t\treturn;\n\t}\n\t::std::vector< ::std::string> paths;\n\n#ifndef _WIN32\n\tglob_t globbuf;\n\n\tglobbuf.gl_offs = 0;\n\n\tglob(args[0]->getStr()->c_str(), GLOB_DOOFFS, NULL, &globbuf);\n\n\tfor (size_t i = 0; i < globbuf.gl_pathc; ++i) {\n\t\tpaths.push_back(globbuf.gl_pathv[i]);\n\t}\n\n\tif (globbuf.gl_pathc) {\n\t\tglobfree(&globbuf);\n\t}\n#else\n\tWIN32_FIND_DATA ffd;\n\tHANDLE hf = FindFirstFile(args[0]->getStr()->c_str(), &ffd);\n\n\tif (hf) {\n\t\tdo {\n\t\t\tpaths.push_back(ffd.cFileName);\n\t\t} while (FindNextFile(hf, &ffd) != 0);\n\n\t\tFindClose(hf);\n\t}\n#endif\n\n\tif (paths.empty()) {\n\t\tresult->setBool(false);\n\t} else {\n\t\t::std::vector< ::std::string>::const_iterator it(paths.begin()),\n\t\t\tend(paths.end());\n\t\tArrayObject* array = new ArrayObject;\n\n\t\tfor (; it != end; ++it) {\n\t\t\tValue* value = new Value;\n\t\t\tvalue->setStr(new StrObject(*it));\n\n\t\t\tarray->getData().push_back(value);\n\t\t}\n\t\tresult->setObj(CLEVER_ARRAY_TYPE, array);\n\t}\n}\n\n} \/\/ clever::modules::std::file\n\n\/\/\/ Initializes Standard File module\nCLEVER_MODULE_INIT(FileModule)\n{\n\taddFunction(new Function(\"rename\", &CLEVER_NS_FNAME(file, rename)));\n\taddFunction(new Function(\"remove\", &CLEVER_NS_FNAME(file, remove)));\n\taddFunction(new Function(\"file_exists\", &CLEVER_NS_FNAME(file, file_exists)));\n\taddFunction(new Function(\"is_dir\", &CLEVER_NS_FNAME(file, is_dir)));\n\taddFunction(new Function(\"glob\", &CLEVER_NS_FNAME(file, glob)));\n\n\taddType(new CFile);\n}\n\n}}} \/\/ clever::modules::std\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"future.hh\"\n#include \"queue.hh\"\n\n#include <experimental\/optional>\n\n\/\/\/ \\defgroup fiber-module Fibers\n\/\/\/\n\/\/\/ \\brief Fibers of execution\n\/\/\/\n\/\/\/ Seastar continuations are normally short, but often chained to one\n\/\/\/ another, so that one continuation does a bit of work and then schedules\n\/\/\/ another continuation for later. Such chains can be long, and often even\n\/\/\/ involve loopings - see for example \\ref repeat. We call such chains\n\/\/\/ \"fibers\" of execution.\n\/\/\/\n\/\/\/ These fibers are not threads - each is just a string of continuations -\n\/\/\/ but they share some common requirements with traditional threads.\n\/\/\/ For example, we want to avoid one fiber getting starved while a second\n\/\/\/ fiber continuously runs its continuations one after another.\n\/\/\/ As another example, fibers may want to communicate - e.g., one fiber\n\/\/\/ produces data that a second fiber consumes, and we wish to ensure that\n\/\/\/ both fibers get a chance to run, and that if one stops prematurely,\n\/\/\/ the other doesn't hang forever.\n\/\/\/\n\/\/\/ Consult the following table to see which APIs are useful for fiber tasks:\n\/\/\/\n\/\/\/ Task | APIs\n\/\/\/ -----------------------------------------------|-------------------\n\/\/\/ Repeat a blocking task indefinitely | \\ref keep_doing()\n\/\/\/ Repeat a blocking task, then exit | \\ref repeat(), \\ref do_until()\n\/\/\/ Provide mutual exclusion between two tasks | \\ref semaphore, \\ref shared_mutex\n\/\/\/ Pass a stream of data between two fibers | \\ref seastar::pipe\n\/\/\/ Safely shut down a resource | \\ref seastar::gate, \\ref seastar::with_gate()\n\/\/\/ Hold on to an object while a fiber is running | \\ref do_with()\n\/\/\/\n\n\/\/\/ Seastar API namespace\nnamespace seastar {\n\n\/\/\/ \\addtogroup fiber-module\n\/\/\/ @{\n\nclass broken_pipe_exception : public std::exception {\npublic:\n virtual const char* what() const noexcept {\n return \"Broken pipe\";\n }\n};\n\nclass unread_overflow_exception : public std::exception {\npublic:\n virtual const char* what() const noexcept {\n return \"pipe_reader::unread() overflow\";\n }\n};\n\n\/\/\/ \\cond internal\nnamespace internal {\ntemplate <typename T>\nclass pipe_buffer {\nprivate:\n queue<std::experimental::optional<T>> _buf;\n bool _read_open = true;\n bool _write_open = true;\npublic:\n pipe_buffer(size_t size) : _buf(size) {}\n future<std::experimental::optional<T>> read() {\n return _buf.pop_eventually();\n }\n future<> write(T&& data) {\n return _buf.push_eventually(std::move(data));\n }\n bool readable() const {\n return _write_open || !_buf.empty();\n }\n bool writeable() const {\n return _read_open;\n }\n bool close_read() {\n \/\/ If a writer blocking (on a full queue), need to stop it.\n if (_buf.full()) {\n _buf.abort(std::make_exception_ptr(broken_pipe_exception()));\n }\n _read_open = false;\n return !_write_open;\n }\n bool close_write() {\n \/\/ If the queue is empty, write the EOF (disengaged optional) to the\n \/\/ queue to wake a blocked reader. If the queue is not empty, there is\n \/\/ no need to write the EOF to the queue - the reader will return an\n \/\/ EOF when it sees that _write_open == false.\n if (_buf.empty()) {\n _buf.push({});\n }\n _write_open = false;\n return !_read_open;\n }\n};\n} \/\/ namespace internal\n\/\/\/ \\endcond\n\ntemplate <typename T>\nclass pipe;\n\n\/\/\/ \\brief Read side of a \\ref seastar::pipe\n\/\/\/\n\/\/\/ The read side of a pipe, which allows only reading from the pipe.\n\/\/\/ A pipe_reader object cannot be created separately, but only as part of a\n\/\/\/ reader\/writer pair through \\ref seastar::pipe.\ntemplate <typename T>\nclass pipe_reader {\nprivate:\n internal::pipe_buffer<T> *_bufp;\n std::experimental::optional<T> _unread;\n pipe_reader(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { }\n friend class pipe<T>;\npublic:\n \/\/\/ \\brief Read next item from the pipe\n \/\/\/\n \/\/\/ Returns a future value, which is fulfilled when the pipe's buffer\n \/\/\/ becomes non-empty, or the write side is closed. The value returned\n \/\/\/ is an optional<T>, which is disengaged to mark and end of file\n \/\/\/ (i.e., the write side was closed, and we've read everything it sent).\n future<std::experimental::optional<T>> read() {\n if (_unread) {\n auto&& ret = std::move(*_unread);\n _unread = {};\n return make_ready_future<std::experimental::optional<T>>(ret);\n }\n if (_bufp->readable()) {\n return _bufp->read();\n } else {\n return make_ready_future<std::experimental::optional<T>>();\n }\n }\n \/\/\/ \\brief Return an item to the front of the pipe\n \/\/\/\n \/\/\/ Pushes the given item to the front of the pipe, so it will be\n \/\/\/ returned by the next read() call. The typical use case is to\n \/\/\/ unread() the last item returned by read().\n \/\/\/ More generally, it is legal to unread() any item, not just one\n \/\/\/ previously returned by read(), but note that the unread() is limited\n \/\/\/ to just one item - two calls to unread() without an intervening call\n \/\/\/ to read() will cause an exception.\n void unread(T&& item) {\n if (_unread) {\n throw unread_overflow_exception();\n }\n _unread = std::move(item);\n }\n ~pipe_reader() {\n if (_bufp && _bufp->close_read()) {\n delete _bufp;\n }\n }\n \/\/ Allow move, but not copy, of pipe_reader\n pipe_reader(pipe_reader&& other) : _bufp(other._bufp) {\n other._bufp = nullptr;\n }\n pipe_reader& operator=(pipe_reader&& other) {\n std::swap(_bufp, other._bufp);\n }\n};\n\n\/\/\/ \\brief Write side of a \\ref seastar::pipe\n\/\/\/\n\/\/\/ The write side of a pipe, which allows only writing to the pipe.\n\/\/\/ A pipe_writer object cannot be created separately, but only as part of a\n\/\/\/ reader\/writer pair through \\ref seastar::pipe.\ntemplate <typename T>\nclass pipe_writer {\nprivate:\n internal::pipe_buffer<T> *_bufp;\n pipe_writer(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { }\n friend class pipe<T>;\npublic:\n \/\/\/ \\brief Write an item to the pipe\n \/\/\/\n \/\/\/ Returns a future value, which is fulfilled when the data was written\n \/\/\/ to the buffer (when it become non-full). If the data could not be\n \/\/\/ written because the read side was closed, an exception\n \/\/\/ \\ref broken_pipe_exception is returned in the future.\n future<> write(T&& data) {\n if (_bufp->writeable()) {\n return _bufp->write(std::move(data));\n } else {\n return make_exception_future<>(broken_pipe_exception());\n }\n }\n ~pipe_writer() {\n if (_bufp && _bufp->close_write()) {\n delete _bufp;\n }\n }\n \/\/ Allow move, but not copy, of pipe_writer\n pipe_writer(pipe_writer&& other) : _bufp(other._bufp) {\n other._bufp = nullptr;\n }\n pipe_writer& operator=(pipe_writer&& other) {\n std::swap(_bufp, other._bufp);\n }\n};\n\n\/\/\/ \\brief A fixed-size pipe for communicating between two fibers.\n\/\/\/\n\/\/\/ A pipe<T> is a mechanism to transfer data between two fibers, one\n\/\/\/ producing data, and the other consuming it. The fixed-size buffer also\n\/\/\/ ensures a balanced execution of the two fibers, because the producer\n\/\/\/ fiber blocks when it writes to a full pipe, until the consumer fiber gets\n\/\/\/ to run and read from the pipe.\n\/\/\/\n\/\/\/ A pipe<T> resembles a Unix pipe, in that it has a read side, a write side,\n\/\/\/ and a fixed-sized buffer between them, and supports either end to be closed\n\/\/\/ independently (and EOF or broken pipe when using the other side).\n\/\/\/ A pipe<T> object holds the reader and write sides of the pipe as two\n\/\/\/ separate objects. These objects can be moved into two different fibers.\n\/\/\/ Importantly, if one of the pipe ends is destroyed (i.e., the continuations\n\/\/\/ capturing it end), the other end of the pipe will stop blocking, so the\n\/\/\/ other fiber will not hang.\n\/\/\/\n\/\/\/ The pipe's read and write interfaces are future-based blocking. I.e., the\n\/\/\/ write() and read() methods return a future which is fulfilled when the\n\/\/\/ operation is complete. The pipe is single-reader single-writer, meaning\n\/\/\/ that until the future returned by read() is fulfilled, read() must not be\n\/\/\/ called again (and same for write).\n\/\/\/\n\/\/\/ Note: The pipe reader and writer are movable, but *not* copyable. It is\n\/\/\/ often convenient to wrap each end in a shared pointer, so it can be\n\/\/\/ copied (e.g., used in an std::function which needs to be copyable) or\n\/\/\/ easily captured into multiple continuations.\ntemplate <typename T>\nclass pipe {\npublic:\n pipe_reader<T> reader;\n pipe_writer<T> writer;\n explicit pipe(size_t size) : pipe(new internal::pipe_buffer<T>(size)) { }\nprivate:\n pipe(internal::pipe_buffer<T> *bufp) : reader(bufp), writer(bufp) { }\n};\n\n\n\/\/\/ @}\n\n} \/\/ namespace seastar\n<commit_msg>core: fix pipe unread<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"future.hh\"\n#include \"queue.hh\"\n\n#include <experimental\/optional>\n\n\/\/\/ \\defgroup fiber-module Fibers\n\/\/\/\n\/\/\/ \\brief Fibers of execution\n\/\/\/\n\/\/\/ Seastar continuations are normally short, but often chained to one\n\/\/\/ another, so that one continuation does a bit of work and then schedules\n\/\/\/ another continuation for later. Such chains can be long, and often even\n\/\/\/ involve loopings - see for example \\ref repeat. We call such chains\n\/\/\/ \"fibers\" of execution.\n\/\/\/\n\/\/\/ These fibers are not threads - each is just a string of continuations -\n\/\/\/ but they share some common requirements with traditional threads.\n\/\/\/ For example, we want to avoid one fiber getting starved while a second\n\/\/\/ fiber continuously runs its continuations one after another.\n\/\/\/ As another example, fibers may want to communicate - e.g., one fiber\n\/\/\/ produces data that a second fiber consumes, and we wish to ensure that\n\/\/\/ both fibers get a chance to run, and that if one stops prematurely,\n\/\/\/ the other doesn't hang forever.\n\/\/\/\n\/\/\/ Consult the following table to see which APIs are useful for fiber tasks:\n\/\/\/\n\/\/\/ Task | APIs\n\/\/\/ -----------------------------------------------|-------------------\n\/\/\/ Repeat a blocking task indefinitely | \\ref keep_doing()\n\/\/\/ Repeat a blocking task, then exit | \\ref repeat(), \\ref do_until()\n\/\/\/ Provide mutual exclusion between two tasks | \\ref semaphore, \\ref shared_mutex\n\/\/\/ Pass a stream of data between two fibers | \\ref seastar::pipe\n\/\/\/ Safely shut down a resource | \\ref seastar::gate, \\ref seastar::with_gate()\n\/\/\/ Hold on to an object while a fiber is running | \\ref do_with()\n\/\/\/\n\n\/\/\/ Seastar API namespace\nnamespace seastar {\n\n\/\/\/ \\addtogroup fiber-module\n\/\/\/ @{\n\nclass broken_pipe_exception : public std::exception {\npublic:\n virtual const char* what() const noexcept {\n return \"Broken pipe\";\n }\n};\n\nclass unread_overflow_exception : public std::exception {\npublic:\n virtual const char* what() const noexcept {\n return \"pipe_reader::unread() overflow\";\n }\n};\n\n\/\/\/ \\cond internal\nnamespace internal {\ntemplate <typename T>\nclass pipe_buffer {\nprivate:\n queue<std::experimental::optional<T>> _buf;\n bool _read_open = true;\n bool _write_open = true;\npublic:\n pipe_buffer(size_t size) : _buf(size) {}\n future<std::experimental::optional<T>> read() {\n return _buf.pop_eventually();\n }\n future<> write(T&& data) {\n return _buf.push_eventually(std::move(data));\n }\n bool readable() const {\n return _write_open || !_buf.empty();\n }\n bool writeable() const {\n return _read_open;\n }\n bool close_read() {\n \/\/ If a writer blocking (on a full queue), need to stop it.\n if (_buf.full()) {\n _buf.abort(std::make_exception_ptr(broken_pipe_exception()));\n }\n _read_open = false;\n return !_write_open;\n }\n bool close_write() {\n \/\/ If the queue is empty, write the EOF (disengaged optional) to the\n \/\/ queue to wake a blocked reader. If the queue is not empty, there is\n \/\/ no need to write the EOF to the queue - the reader will return an\n \/\/ EOF when it sees that _write_open == false.\n if (_buf.empty()) {\n _buf.push({});\n }\n _write_open = false;\n return !_read_open;\n }\n};\n} \/\/ namespace internal\n\/\/\/ \\endcond\n\ntemplate <typename T>\nclass pipe;\n\n\/\/\/ \\brief Read side of a \\ref seastar::pipe\n\/\/\/\n\/\/\/ The read side of a pipe, which allows only reading from the pipe.\n\/\/\/ A pipe_reader object cannot be created separately, but only as part of a\n\/\/\/ reader\/writer pair through \\ref seastar::pipe.\ntemplate <typename T>\nclass pipe_reader {\nprivate:\n internal::pipe_buffer<T> *_bufp;\n std::experimental::optional<T> _unread;\n pipe_reader(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { }\n friend class pipe<T>;\npublic:\n \/\/\/ \\brief Read next item from the pipe\n \/\/\/\n \/\/\/ Returns a future value, which is fulfilled when the pipe's buffer\n \/\/\/ becomes non-empty, or the write side is closed. The value returned\n \/\/\/ is an optional<T>, which is disengaged to mark and end of file\n \/\/\/ (i.e., the write side was closed, and we've read everything it sent).\n future<std::experimental::optional<T>> read() {\n if (_unread) {\n auto ret = std::move(*_unread);\n _unread = {};\n return make_ready_future<std::experimental::optional<T>>(std::move(ret));\n }\n if (_bufp->readable()) {\n return _bufp->read();\n } else {\n return make_ready_future<std::experimental::optional<T>>();\n }\n }\n \/\/\/ \\brief Return an item to the front of the pipe\n \/\/\/\n \/\/\/ Pushes the given item to the front of the pipe, so it will be\n \/\/\/ returned by the next read() call. The typical use case is to\n \/\/\/ unread() the last item returned by read().\n \/\/\/ More generally, it is legal to unread() any item, not just one\n \/\/\/ previously returned by read(), but note that the unread() is limited\n \/\/\/ to just one item - two calls to unread() without an intervening call\n \/\/\/ to read() will cause an exception.\n void unread(T&& item) {\n if (_unread) {\n throw unread_overflow_exception();\n }\n _unread = std::move(item);\n }\n ~pipe_reader() {\n if (_bufp && _bufp->close_read()) {\n delete _bufp;\n }\n }\n \/\/ Allow move, but not copy, of pipe_reader\n pipe_reader(pipe_reader&& other) : _bufp(other._bufp) {\n other._bufp = nullptr;\n }\n pipe_reader& operator=(pipe_reader&& other) {\n std::swap(_bufp, other._bufp);\n }\n};\n\n\/\/\/ \\brief Write side of a \\ref seastar::pipe\n\/\/\/\n\/\/\/ The write side of a pipe, which allows only writing to the pipe.\n\/\/\/ A pipe_writer object cannot be created separately, but only as part of a\n\/\/\/ reader\/writer pair through \\ref seastar::pipe.\ntemplate <typename T>\nclass pipe_writer {\nprivate:\n internal::pipe_buffer<T> *_bufp;\n pipe_writer(internal::pipe_buffer<T> *bufp) : _bufp(bufp) { }\n friend class pipe<T>;\npublic:\n \/\/\/ \\brief Write an item to the pipe\n \/\/\/\n \/\/\/ Returns a future value, which is fulfilled when the data was written\n \/\/\/ to the buffer (when it become non-full). If the data could not be\n \/\/\/ written because the read side was closed, an exception\n \/\/\/ \\ref broken_pipe_exception is returned in the future.\n future<> write(T&& data) {\n if (_bufp->writeable()) {\n return _bufp->write(std::move(data));\n } else {\n return make_exception_future<>(broken_pipe_exception());\n }\n }\n ~pipe_writer() {\n if (_bufp && _bufp->close_write()) {\n delete _bufp;\n }\n }\n \/\/ Allow move, but not copy, of pipe_writer\n pipe_writer(pipe_writer&& other) : _bufp(other._bufp) {\n other._bufp = nullptr;\n }\n pipe_writer& operator=(pipe_writer&& other) {\n std::swap(_bufp, other._bufp);\n }\n};\n\n\/\/\/ \\brief A fixed-size pipe for communicating between two fibers.\n\/\/\/\n\/\/\/ A pipe<T> is a mechanism to transfer data between two fibers, one\n\/\/\/ producing data, and the other consuming it. The fixed-size buffer also\n\/\/\/ ensures a balanced execution of the two fibers, because the producer\n\/\/\/ fiber blocks when it writes to a full pipe, until the consumer fiber gets\n\/\/\/ to run and read from the pipe.\n\/\/\/\n\/\/\/ A pipe<T> resembles a Unix pipe, in that it has a read side, a write side,\n\/\/\/ and a fixed-sized buffer between them, and supports either end to be closed\n\/\/\/ independently (and EOF or broken pipe when using the other side).\n\/\/\/ A pipe<T> object holds the reader and write sides of the pipe as two\n\/\/\/ separate objects. These objects can be moved into two different fibers.\n\/\/\/ Importantly, if one of the pipe ends is destroyed (i.e., the continuations\n\/\/\/ capturing it end), the other end of the pipe will stop blocking, so the\n\/\/\/ other fiber will not hang.\n\/\/\/\n\/\/\/ The pipe's read and write interfaces are future-based blocking. I.e., the\n\/\/\/ write() and read() methods return a future which is fulfilled when the\n\/\/\/ operation is complete. The pipe is single-reader single-writer, meaning\n\/\/\/ that until the future returned by read() is fulfilled, read() must not be\n\/\/\/ called again (and same for write).\n\/\/\/\n\/\/\/ Note: The pipe reader and writer are movable, but *not* copyable. It is\n\/\/\/ often convenient to wrap each end in a shared pointer, so it can be\n\/\/\/ copied (e.g., used in an std::function which needs to be copyable) or\n\/\/\/ easily captured into multiple continuations.\ntemplate <typename T>\nclass pipe {\npublic:\n pipe_reader<T> reader;\n pipe_writer<T> writer;\n explicit pipe(size_t size) : pipe(new internal::pipe_buffer<T>(size)) { }\nprivate:\n pipe(internal::pipe_buffer<T> *bufp) : reader(bufp), writer(bufp) { }\n};\n\n\n\/\/\/ @}\n\n} \/\/ namespace seastar\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <vector>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate <typename Dtype>\nclass ArgMaxLayerTest : public ::testing::Test {\n protected:\n ArgMaxLayerTest()\n : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)),\n blob_top_(new Blob<Dtype>()) {\n Caffe::set_random_seed(1701);\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller<Dtype> filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }\n Blob<Dtype>* const blob_bottom_;\n Blob<Dtype>* const blob_top_;\n vector<Blob<Dtype>*> blob_bottom_vec_;\n vector<Blob<Dtype>*> blob_top_vec_;\n};\n\ntypedef ::testing::Types<float, double> Dtypes;\nTYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);\n\n\nTYPED_TEST(ArgMaxLayerTest, TestSetup) {\n LayerParameter layer_param;\n ThresholdLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num());\n EXPECT_EQ(this->blob_top_->channels(), 1);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {\n LayerParameter layer_param;\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ThresholdLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num());\n EXPECT_EQ(this->blob_top_->channels(), 2);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPU) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i];\n max_val = bottom_data[i * dim + max_ind];\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i * 2];\n max_val = top_data[i * 2 + 1];\n EXPECT_EQ(bottom_data[i * dim + max_ind],max_val);\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\n} \/\/ namespace caffe\n<commit_msg>Fixed name of ArgMaxLayerParameter<commit_after>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <vector>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate <typename Dtype>\nclass ArgMaxLayerTest : public ::testing::Test {\n protected:\n ArgMaxLayerTest()\n : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)),\n blob_top_(new Blob<Dtype>()) {\n Caffe::set_random_seed(1701);\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller<Dtype> filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }\n Blob<Dtype>* const blob_bottom_;\n Blob<Dtype>* const blob_top_;\n vector<Blob<Dtype>*> blob_bottom_vec_;\n vector<Blob<Dtype>*> blob_top_vec_;\n};\n\ntypedef ::testing::Types<float, double> Dtypes;\nTYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);\n\n\nTYPED_TEST(ArgMaxLayerTest, TestSetup) {\n LayerParameter layer_param;\n ThresholdLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num());\n EXPECT_EQ(this->blob_top_->channels(), 1);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {\n LayerParameter layer_param;\n ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ThresholdLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num());\n EXPECT_EQ(this->blob_top_->channels(), 2);\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPU) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i];\n max_val = bottom_data[i * dim + max_ind];\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\nTYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {\n LayerParameter layer_param;\n Caffe::set_mode(Caffe::CPU);\n ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param();\n argmax_param->set_out_max_val(true);\n ArgMaxLayer<TypeParam> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const TypeParam* bottom_data = this->blob_bottom_->cpu_data();\n const TypeParam* top_data = this->blob_top_->cpu_data();\n int max_ind;\n TypeParam max_val;\n int num = this->blob_bottom_->num();\n int dim = this->blob_bottom_->count() \/ num;\n for (int i = 0; i < num; ++i) {\n EXPECT_GE(top_data[i], 0);\n EXPECT_LE(top_data[i], dim);\n max_ind = top_data[i * 2];\n max_val = top_data[i * 2 + 1];\n EXPECT_EQ(bottom_data[i * dim + max_ind],max_val);\n for (int j = 0; j < dim; ++j) {\n EXPECT_LE(bottom_data[i * dim + j], max_val);\n }\n }\n}\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"<commit_before>\/\/ cvt.c - IEEE floating point formatting routines for FreeBSD\n\/\/ from GNU libc-4.6.27\n\/\/\n\/\/ Copyright (C) 2002 Michael Ringgaard. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ \n\/\/ 1. Redistributions of source code must retain the above copyright \n\/\/ notice, this list of conditions and the following disclaimer. \n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution. \n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF \n\/\/ SUCH DAMAGE.\n\n#include <cassert>\n#include <cstdlib>\n#include <cmath>\n\nnamespace fixfmt {\n\nconstexpr size_t CVTBUFSIZE = 512;\n\nchar* cvt(double arg, int ndigits, int* decpt, int* sign, char* buf, int eflag)\n{\n assert(ndigits >= 0);\n assert(ndigits < CVTBUFSIZE - 1);\n\n int r2;\n double fi;\n double fj;\n char* p;\n char* p1;\n\n r2 = 0;\n *sign = 0;\n p = &buf[0];\n if (arg < 0) {\n *sign = 1;\n arg = -arg;\n }\n\n \/\/ Split into integral and fractional parts.\n arg = modf(arg, &fi);\n p1 = &buf[CVTBUFSIZE];\n if (fi != 0) {\n \/\/ Have an integral part. Render it right-to-left at the end of the buffer.\n p1 = &buf[CVTBUFSIZE];\n while (fi != 0) {\n fj = modf(fi \/ 10, &fi);\n *--p1 = (int)((fj + .03) * 10) + '0';\n r2++;\n }\n \/\/ Copy it to the beginning of the buffer.\n while (p1 < &buf[CVTBUFSIZE]) \n *p++ = *p1++;\n } \n else if (arg > 0) \n \/\/ Fractional part only. Scale it up until the first fractional digit \n \/\/ is nonzero.\n while ((fj = arg * 10) < 1) {\n arg = fj;\n r2--;\n }\n\n p1 = &buf[ndigits];\n if (eflag == 0) \n p1 += r2;\n *decpt = r2;\n if (p1 < &buf[0]) {\n buf[0] = '\\0';\n return buf;\n }\n while (p <= p1 && p < &buf[CVTBUFSIZE]) {\n arg *= 10;\n arg = modf(arg, &fj);\n *p++ = (int) fj + '0';\n }\n if (p1 >= &buf[CVTBUFSIZE]) {\n buf[CVTBUFSIZE - 1] = '\\0';\n return buf;\n }\n p = p1;\n *p1 += 5;\n while (*p1 > '9') {\n *p1 = '0';\n if (p1 > buf)\n ++*--p1;\n else {\n *p1 = '1';\n (*decpt)++;\n if (eflag == 0) {\n if (p > buf) \n *p = '0';\n p++;\n }\n }\n }\n *p = '\\0';\n return buf;\n}\n\nchar* ecvtbuf(double arg, int ndigits, int* decpt, int* sign, char* buf) {\n return cvt(arg, ndigits, decpt, sign, buf, 1);\n}\n\nchar* fcvtbuf(double arg, int ndigits, int* decpt, int* sign, char* buf) {\n return cvt(arg, ndigits, decpt, sign, buf, 0);\n}\n\n\n} \/\/ namespace fixfmt\n<commit_msg>Remove cvt.cc.<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef group_1_instructions_hpp\n#define group_1_instructions_hpp\n\n\n\/\/ Group 1 Instructions\n\/\/ 01fo oooo aaaa bbbb iiii iiii iiii iiii\n\n\t\/\/ f: 1 if can affect flags (and instruction type supports it), 0 if\n\t\/\/ flags unchanged.\n\n\t\/\/ o: opcode\n\t\/\/ a: rA\n\t\/\/ b: rB\n\t\/\/ i: 16-bit immediate value\n\n#define LIST_OF_INSTR_G1_RA_RB_IMM__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\/* rA = rB + (zero-extended imm) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Addi) VALUE(\"addi\") \\\n\\\n\/* rA = rB + (zero-extended imm) + carry_flag *\/ \\\n\/* Add with carry *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Adci) VALUE(\"adci\") \\\n\\\n\/* rA = rB - (zero-extended imm) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Subi) VALUE(\"subi\") \\\n\\\n\/* rA = rB + (~(zero-extended imm)) + carry_flag *\/ \\\n\/* Subtract with borrow (6502 style) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Sbci) VALUE(\"sbci\") \\\n\\\n\\\n\\\n\/* rA = (zero-extended imm) - rB *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Rsbi) VALUE(\"rsbi\") \\\n\\\n\/* rA = rB * (zero-extended imm) *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Muli) VALUE(\"muli\") \\\n\\\n\/* rA = rB & (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Andi) VALUE(\"andi\") \\\n\\\n\/* rA = rB | (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Ori) VALUE(\"ori\") \\\n\\\n\\\n\\\n\/* rA = rB ^ (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Xori) VALUE(\"xori\") \\\n\\\n\/* Logical shift left *\/ \\\n\/* rA = rB << (zero-extended imm) *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Lsli) VALUE(\"lsli\") \\\n\\\n\/* Logical shift right *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Lsri) VALUE(\"lsri\") \\\n\\\n\/* Arithmetic shift right *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Asri) VALUE(\"asri\") \\\n\\\n\\\n\\\n\/* Rotate left by (zero-extended imm) bits, then store result in rA. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Roli) VALUE(\"roli\") \\\n\\\n\/* Rotate right by (zero-extended imm) bits, then store result in rA. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Rori) VALUE(\"rori\") \\\n\n\n#define LIST_OF_INSTR_G1_IMM__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\/* Branch always, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bra) VALUE(\"bra\") \\\n\\\n\/* Branch never (effectively a NOP), *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bnv) VALUE(\"bnv\") \\\n\\\n\\\n\\\n\/* Branch when Z == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bne) VALUE(\"bne\") \\\n\\\n\/* Branch when Z == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Beq) VALUE(\"beq\") \\\n\\\n\/* Branch when C == 0 [unsigned less than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bcc) VALUE(\"bcc\") \\\n\\\n\/* Branch when C == 1 [unsigned greater than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bcs) VALUE(\"bcs\") \\\n\\\n\\\n\\\n\/* Branch when (C == 0 or Z == 1) [unsigned less than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bls) VALUE(\"bls\") \\\n\\\n\/* Branch when (C == 1 and Z == 0) [unsigned greater than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bhi) VALUE(\"bhi\") \\\n\\\n\/* Branch when N == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bpl) VALUE(\"bpl\") \\\n\\\n\/* Branch when N == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bmi) VALUE(\"bmi\") \\\n\\\n\\\n\\\n\/* Branch when V == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bvc) VALUE(\"bvc\") \\\n\\\n\/* Branch when V == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bvs) VALUE(\"bvs\") \\\n\\\n\/* Branch when N == V [signed greater than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bge) VALUE(\"bge\") \\\n\\\n\/* Branch when N != V [signed less than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Blt) VALUE(\"blt\") \\\n\\\n\\\n\\\n\/* Branch when (N == V and Z == 0) [signed greater than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bgt) VALUE(\"bgt\") \\\n\\\n\/* Branch when (N != V or Z == 1) [signed less than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Ble) VALUE(\"ble\") \\\n\n\n#define LIST_OF_INSTR_G1_RA_RB_SIMM__COLLECTION_1(ARGS, VARNAME, VALUE) \\\n\/* rA = rB ^ (sign-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_simm16) VARNAME(Xorsi) VALUE(\"xorsi\")\n\n\/* Reserved for future expansion. *\/\n\n\n#endif\t\t\/\/ group_1_instructions_hpp\n<commit_msg>Stuffs<commit_after>#ifndef group_1_instructions_hpp\n#define group_1_instructions_hpp\n\n\n\/\/ Group 1 Instructions\n\/\/ 01fo oooo aaaa bbbb iiii iiii iiii iiii\n\n\t\/\/ f: 1 if can affect flags (and instruction type supports it), 0 if\n\t\/\/ flags unchanged.\n\n\t\/\/ o: opcode\n\t\/\/ a: rA\n\t\/\/ b: rB\n\t\/\/ i: 16-bit immediate value\n\n#define LIST_OF_INSTR_G1_RA_RB_UIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\/* rA = rB + (zero-extended imm) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Addi) VALUE(\"addi\") \\\n\\\n\/* rA = rB + (zero-extended imm) + carry_flag *\/ \\\n\/* Add with carry *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Adci) VALUE(\"adci\") \\\n\\\n\/* rA = rB - (zero-extended imm) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Subi) VALUE(\"subi\") \\\n\\\n\/* rA = rB + (~(zero-extended imm)) + carry_flag *\/ \\\n\/* Subtract with borrow (6502 style) *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Sbci) VALUE(\"sbci\") \\\n\\\n\\\n\\\n\/* rA = (zero-extended imm) - rB *\/ \\\n\/* This instruction can affect N, V, Z, and C flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Rsbi) VALUE(\"rsbi\") \\\n\\\n\/* rA = rB * (zero-extended imm) *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Muli) VALUE(\"muli\") \\\n\\\n\/* rA = rB & (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Andi) VALUE(\"andi\") \\\n\\\n\/* rA = rB | (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Ori) VALUE(\"ori\") \\\n\\\n\\\n\\\n\/* rA = rB ^ (zero-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Xori) VALUE(\"xori\") \\\n\\\n\/* Logical shift left *\/ \\\n\/* rA = rB << (zero-extended imm) *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Lsli) VALUE(\"lsli\") \\\n\\\n\/* Logical shift right *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Lsri) VALUE(\"lsri\") \\\n\\\n\/* Arithmetic shift right *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Asri) VALUE(\"asri\") \\\n\\\n\\\n\\\n\/* Rotate left by (zero-extended imm) bits, then store result in rA. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Roli) VALUE(\"roli\") \\\n\\\n\/* Rotate right by (zero-extended imm) bits, then store result in rA. *\/ \\\nARGS(ra_rb_uimm16) VARNAME(Rori) VALUE(\"rori\") \\\n\n\n#define LIST_OF_INSTR_G1_SIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\/* Branch always, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bra) VALUE(\"bra\") \\\n\\\n\/* Branch never (effectively a NOP), *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bnv) VALUE(\"bnv\") \\\n\\\n\\\n\\\n\/* Branch when Z == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bne) VALUE(\"bne\") \\\n\\\n\/* Branch when Z == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Beq) VALUE(\"beq\") \\\n\\\n\/* Branch when C == 0 [unsigned less than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bcc) VALUE(\"bcc\") \\\n\\\n\/* Branch when C == 1 [unsigned greater than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bcs) VALUE(\"bcs\") \\\n\\\n\\\n\\\n\/* Branch when (C == 0 or Z == 1) [unsigned less than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bls) VALUE(\"bls\") \\\n\\\n\/* Branch when (C == 1 and Z == 0) [unsigned greater than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bhi) VALUE(\"bhi\") \\\n\\\n\/* Branch when N == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bpl) VALUE(\"bpl\") \\\n\\\n\/* Branch when N == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bmi) VALUE(\"bmi\") \\\n\\\n\\\n\\\n\/* Branch when V == 0, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bvc) VALUE(\"bvc\") \\\n\\\n\/* Branch when V == 1, *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bvs) VALUE(\"bvs\") \\\n\\\n\/* Branch when N == V [signed greater than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bge) VALUE(\"bge\") \\\n\\\n\/* Branch when N != V [signed less than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Blt) VALUE(\"blt\") \\\n\\\n\\\n\\\n\/* Branch when (N == V and Z == 0) [signed greater than], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Bgt) VALUE(\"bgt\") \\\n\\\n\/* Branch when (N != V or Z == 1) [signed less than or equal], *\/ \\\n\/* to ((pc when instruction starts) *\/ \\\n\/* + (sign-extended 16-bit immediate value)) *\/ \\\nARGS(simm16) VARNAME(Ble) VALUE(\"ble\") \\\n\n\n#define LIST_OF_INSTR_G1_RA_RB_SIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\/* rA = rB ^ (sign-extended imm) *\/ \\\n\/* This instruction can affect the N and Z flags. *\/ \\\nARGS(ra_rb_simm16) VARNAME(Xorsi) VALUE(\"xorsi\")\n\n\/* Reserved for future expansion. *\/\n\n\n#define LIST_OF_GROUP_1_INSTRUCTIONS(ARGS, VARNAME, VALUE) \\\nLIST_OF_INSTR_G1_RA_RB_UIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\nLIST_OF_INSTR_G1_SIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\nLIST_OF_INSTR_G1_RA_RB_SIMM16__COLLECTION_0(ARGS, VARNAME, VALUE) \\\n\n\n#endif\t\t\/\/ group_1_instructions_hpp\n<|endoftext|>"} {"text":"<commit_before>\n#include <map>\n#include <utility>\n#include <string.h>\n\n#include <disir\/disir.h>\n#include <disir\/util.h>\n#include <disir\/plugin.h>\n\n#define MQ_ENQUEUE(q, x) \\\n { \\\n (x)->next = NULL; \\\n \\\n if ((q) == NULL) { \\\n (q) = (x)->prev = (x); \\\n } else { \\\n (q)->prev->next = (x); \\\n (x)->prev = (q)->prev; \\\n (q)->prev = (x); \\\n } \\\n }\n\n\n\n\ntypedef enum disir_status (*output_mold)(struct disir_mold **);\n\n#include \"basic_keyval.cc\"\n#include \"basic_section.cc\"\n#include \"json_test_mold.cc\"\n#include \"restriction_keyval_numeric_types.cc\"\n#include \"restriction_entries.cc\"\n#include \"restriction_config_parent_keyval_min_entry.cc\"\n#include \"restriction_config_parent_keyval_max_entry.cc\"\n#include \"restriction_config_parent_section_max_entry.cc\"\n#include \"restriction_section_parent_keyval_max_entry.cc\"\n#include \"basic_version_difference.cc\"\n#include \"complex_section.cc\"\n\n\/\/ Forward declaration\nenum disir_status dio_test_config_read (struct disir_instance *disir,\n void *storage, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config);\nenum disir_status dio_test_config_entries (struct disir_instance *disir,\n void *storage, struct disir_entry **entries);\nenum disir_status dio_test_config_version (struct disir_instance *disir, void *storage,\n const char *entry_id, struct semantic_version *semver);\nenum disir_status dio_test_mold_read (struct disir_instance *disir, void *storage,\n const char *entry_id, struct disir_mold **mold);\nenum disir_status dio_test_mold_entries (struct disir_instance *disir,\n void *storage, struct disir_entry **entries);\n\nstruct cmp_str\n{\n bool operator()(char const *a, char const *b)\n {\n return strcmp(a, b) < 0;\n }\n};\n\n\/\/! Internal static map to store test molds by id\nstatic std::map<const char *, output_mold, cmp_str> molds = {\n std::make_pair (\"basic_keyval\", basic_keyval),\n std::make_pair (\"basic_section\", basic_section),\n std::make_pair (\"json_test_mold\", json_test_mold),\n std::make_pair (\"restriction_keyval_numeric_types\", restriction_keyval_numeric_types),\n std::make_pair (\"restriction_entries\", restriction_entries),\n std::make_pair (\"restriction_config_parent_keyval_min_entry\",\n restriction_config_parent_keyval_min_entry),\n std::make_pair (\"restriction_config_parent_keyval_max_entry\",\n restriction_config_parent_keyval_max_entry),\n std::make_pair (\"restriction_config_parent_section_max_entry\",\n restriction_config_parent_section_max_entry),\n std::make_pair (\"restriction_section_parent_keyval_max_entry\",\n restriction_section_parent_keyval_max_entry),\n std::make_pair (\"basic_version_difference\", basic_version_difference),\n std::make_pair (\"complex_section\", complex_section),\n};\n\nenum disir_status\ndio_test_config_read (struct disir_instance *disir, void *storage, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config)\n{\n enum disir_status status;\n output_mold func_mold;\n\n fprintf (stderr, \"TEST_CONFIG_READ: stroage: %p\\n\", storage);\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n status = func_mold (&mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n status = disir_generate_config_from_mold (mold, NULL, config);\n \/\/ We are finished with our allocated mold\n disir_mold_finished (&mold);\n return status;\n}\n\nenum disir_status\ndio_test_config_entries (struct disir_instance *disir, void *storage, struct disir_entry **entries)\n{\n return dio_test_mold_entries (disir, storage, entries);\n}\n\nenum disir_status\ndio_test_config_query (struct disir_instance *disir, void *storage, const char *entry_id)\n{\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nenum disir_status\ndio_test_mold_read (struct disir_instance *disir, void *storage,\n const char *entry_id, struct disir_mold **mold)\n{\n enum disir_status status;\n output_mold func_mold;\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n status = func_mold (mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n return DISIR_STATUS_OK;;\n}\n\nenum disir_status\ndio_test_mold_entries (struct disir_instance *disir, void *storage, struct disir_entry **entries)\n{\n struct disir_entry *queue;\n struct disir_entry *entry;\n\n queue = NULL;\n\n for (auto i = molds.begin(); i != molds.end(); ++i)\n {\n entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (entry == NULL)\n continue;\n\n entry->de_entry_name = strdup (i->first);\n entry->DE_READABLE = 1;\n entry->DE_WRITABLE = 1;\n MQ_ENQUEUE (queue, entry);\n }\n\n *entries = queue;\n\n return DISIR_STATUS_OK;\n}\n\nenum disir_status\ndio_test_mold_query (struct disir_instance *disir, void *storage, const char *entry_id)\n{\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nextern \"C\" enum disir_status\ndio_register_plugin (struct disir_instance *disir, const char *name)\n{\n struct disir_plugin plugin;\n\n plugin.dp_name = (char *) \"test\";\n plugin.dp_description = (char *) \"A collection of various molds to enumerate functionality in libdisir\";\n plugin.dp_type = (char *) \"test\";\n \/\/ Storage space unused.\n plugin.dp_storage = NULL;\n plugin.dp_plugin_finished = NULL;\n\n plugin.dp_config_read = dio_test_config_read;\n plugin.dp_config_write = NULL;\n plugin.dp_config_entries = dio_test_config_entries;\n plugin.dp_config_query = dio_test_config_query;\n\n plugin.dp_mold_read = dio_test_mold_read;\n plugin.dp_mold_write = NULL;\n plugin.dp_mold_entries = dio_test_mold_entries;\n plugin.dp_mold_query = dio_test_mold_query;\n\n return disir_plugin_register (disir, &plugin);\n}\n\n<commit_msg>plugin test: remove old print<commit_after>\n#include <map>\n#include <utility>\n#include <string.h>\n\n#include <disir\/disir.h>\n#include <disir\/util.h>\n#include <disir\/plugin.h>\n\n#define MQ_ENQUEUE(q, x) \\\n { \\\n (x)->next = NULL; \\\n \\\n if ((q) == NULL) { \\\n (q) = (x)->prev = (x); \\\n } else { \\\n (q)->prev->next = (x); \\\n (x)->prev = (q)->prev; \\\n (q)->prev = (x); \\\n } \\\n }\n\n\n\n\ntypedef enum disir_status (*output_mold)(struct disir_mold **);\n\n#include \"basic_keyval.cc\"\n#include \"basic_section.cc\"\n#include \"json_test_mold.cc\"\n#include \"restriction_keyval_numeric_types.cc\"\n#include \"restriction_entries.cc\"\n#include \"restriction_config_parent_keyval_min_entry.cc\"\n#include \"restriction_config_parent_keyval_max_entry.cc\"\n#include \"restriction_config_parent_section_max_entry.cc\"\n#include \"restriction_section_parent_keyval_max_entry.cc\"\n#include \"basic_version_difference.cc\"\n#include \"complex_section.cc\"\n\n\/\/ Forward declaration\nenum disir_status dio_test_config_read (struct disir_instance *disir,\n void *storage, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config);\nenum disir_status dio_test_config_entries (struct disir_instance *disir,\n void *storage, struct disir_entry **entries);\nenum disir_status dio_test_config_version (struct disir_instance *disir, void *storage,\n const char *entry_id, struct semantic_version *semver);\nenum disir_status dio_test_mold_read (struct disir_instance *disir, void *storage,\n const char *entry_id, struct disir_mold **mold);\nenum disir_status dio_test_mold_entries (struct disir_instance *disir,\n void *storage, struct disir_entry **entries);\n\nstruct cmp_str\n{\n bool operator()(char const *a, char const *b)\n {\n return strcmp(a, b) < 0;\n }\n};\n\n\/\/! Internal static map to store test molds by id\nstatic std::map<const char *, output_mold, cmp_str> molds = {\n std::make_pair (\"basic_keyval\", basic_keyval),\n std::make_pair (\"basic_section\", basic_section),\n std::make_pair (\"json_test_mold\", json_test_mold),\n std::make_pair (\"restriction_keyval_numeric_types\", restriction_keyval_numeric_types),\n std::make_pair (\"restriction_entries\", restriction_entries),\n std::make_pair (\"restriction_config_parent_keyval_min_entry\",\n restriction_config_parent_keyval_min_entry),\n std::make_pair (\"restriction_config_parent_keyval_max_entry\",\n restriction_config_parent_keyval_max_entry),\n std::make_pair (\"restriction_config_parent_section_max_entry\",\n restriction_config_parent_section_max_entry),\n std::make_pair (\"restriction_section_parent_keyval_max_entry\",\n restriction_section_parent_keyval_max_entry),\n std::make_pair (\"basic_version_difference\", basic_version_difference),\n std::make_pair (\"complex_section\", complex_section),\n};\n\nenum disir_status\ndio_test_config_read (struct disir_instance *disir, void *storage, const char *entry_id,\n struct disir_mold *mold, struct disir_config **config)\n{\n enum disir_status status;\n output_mold func_mold;\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n status = func_mold (&mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n status = disir_generate_config_from_mold (mold, NULL, config);\n \/\/ We are finished with our allocated mold\n disir_mold_finished (&mold);\n return status;\n}\n\nenum disir_status\ndio_test_config_entries (struct disir_instance *disir, void *storage, struct disir_entry **entries)\n{\n return dio_test_mold_entries (disir, storage, entries);\n}\n\nenum disir_status\ndio_test_config_query (struct disir_instance *disir, void *storage, const char *entry_id)\n{\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nenum disir_status\ndio_test_mold_read (struct disir_instance *disir, void *storage,\n const char *entry_id, struct disir_mold **mold)\n{\n enum disir_status status;\n output_mold func_mold;\n\n func_mold = molds[entry_id];\n if (func_mold == NULL)\n return DISIR_STATUS_INVALID_ARGUMENT;\n\n status = func_mold (mold);\n if (status != DISIR_STATUS_OK)\n return status;\n\n return DISIR_STATUS_OK;;\n}\n\nenum disir_status\ndio_test_mold_entries (struct disir_instance *disir, void *storage, struct disir_entry **entries)\n{\n struct disir_entry *queue;\n struct disir_entry *entry;\n\n queue = NULL;\n\n for (auto i = molds.begin(); i != molds.end(); ++i)\n {\n entry = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));\n if (entry == NULL)\n continue;\n\n entry->de_entry_name = strdup (i->first);\n entry->DE_READABLE = 1;\n entry->DE_WRITABLE = 1;\n MQ_ENQUEUE (queue, entry);\n }\n\n *entries = queue;\n\n return DISIR_STATUS_OK;\n}\n\nenum disir_status\ndio_test_mold_query (struct disir_instance *disir, void *storage, const char *entry_id)\n{\n if (molds[entry_id] == NULL)\n return DISIR_STATUS_NOT_EXIST;\n else\n return DISIR_STATUS_EXISTS;\n}\n\nextern \"C\" enum disir_status\ndio_register_plugin (struct disir_instance *disir, const char *name)\n{\n struct disir_plugin plugin;\n\n plugin.dp_name = (char *) \"test\";\n plugin.dp_description = (char *) \"A collection of various molds to enumerate functionality in libdisir\";\n plugin.dp_type = (char *) \"test\";\n \/\/ Storage space unused.\n plugin.dp_storage = NULL;\n plugin.dp_plugin_finished = NULL;\n\n plugin.dp_config_read = dio_test_config_read;\n plugin.dp_config_write = NULL;\n plugin.dp_config_entries = dio_test_config_entries;\n plugin.dp_config_query = dio_test_config_query;\n\n plugin.dp_mold_read = dio_test_mold_read;\n plugin.dp_mold_write = NULL;\n plugin.dp_mold_entries = dio_test_mold_entries;\n plugin.dp_mold_query = dio_test_mold_query;\n\n return disir_plugin_register (disir, &plugin);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Time keeping for memcached.\n *\n * Orginally part of memcached.c this module encapsulates some time\n * keeping functions that are exposed via the engine API.\n *\n * This module implements a prviate and non-data path \"tick\" function\n * which maintains a view of time.\n *\n * - see mc_time_clock_tick\n *\n * This module provides public time methods that allow performant\n * data-path code access to:\n *\n * 1. A monotonic interval time (great for relative expiry and timed\n * locks). - mc_time_get_current_time()\n * 2. approximation of system-clock. - mc_time_convert_to_abs_time()\n * 2.1 The following returns system clock time -\n * mc_time_convert_to_abs_time(mc_time_get_current_time())\n * 3. A method for work with expiry timestamps as per the memcached\n * protocol - mc_time_convert_to_real_time()\n *\n *\/\n#include <signal.h>\n\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mc_time.h\"\n\n#include <atomic>\n\nextern std::atomic<bool> memcached_shutdown;\n\n\/*\n * This constant defines the seconds between libevent clock callbacks.\n * This roughly equates to how frequency of gethrtime calls made.\n *\/\nconst time_t memcached_clock_tick_seconds = 1;\n\n\/*\n * This constant defines the frequency of system clock checks.\n * This equates to an extra gettimeofday every 'n' seconds.\n *\/\nconst time_t memcached_check_system_time = 60;\n\n\/*\n * This constant defines the maximum relative time (30 days in seconds)\n * time values above this are interpretted as absolute.\n *\/\nconst time_t memcached_maximum_relative_time = 60*60*24*30;\n\nstatic std::atomic<rel_time_t> memcached_uptime(0);\nstatic volatile time_t memcached_epoch = 0;\nstatic volatile uint64_t memcached_monotonic_start = 0;\nstatic struct event_base* main_ev_base = NULL;\n\nstatic void mc_time_clock_event_handler(evutil_socket_t fd, short which, void *arg);\nstatic void mc_gather_timing_samples(void);\n\n\/*\n * Init internal state and start the timer event callback.\n *\/\nvoid mc_time_init(struct event_base* ev_base) {\n\n main_ev_base = ev_base;\n\n mc_time_init_epoch();\n\n \/* tick once to begin procedings *\/\n mc_time_clock_tick();\n\n \/* Begin the time keeping by registering for a time based callback *\/\n mc_time_clock_event_handler(0, 0, 0);\n}\n\n\/*\n * Initisalise our \"EPOCH\" variables\n * In order to provide a monotonic \"uptime\" and track system time, we record\n * some points in time.\n *\/\nvoid mc_time_init_epoch(void) {\n struct timeval t;\n memcached_uptime = 0;\n memcached_monotonic_start = cb_get_monotonic_seconds();\n cb_get_timeofday(&t);\n memcached_epoch = t.tv_sec;\n}\n\n\/*\n * Return a monotonically increasing value.\n * The value returned represents seconds since memcached started.\n *\/\nrel_time_t mc_time_get_current_time(void) {\n return memcached_uptime;\n}\n\n\/\/\/ @return true if a + b would overflow rel_time_t\nstatic bool would_overflow(rel_time_t a, std::chrono::seconds b) {\n return a > (std::numeric_limits<rel_time_t>::max() - b.count());\n}\n\n\/**\n * @return true if a + b would overflow int64_t\n *\/\nstatic bool would_overflow(int64_t a, int64_t b) {\n return a > (std::numeric_limits<int64_t>::max() - b);\n}\n\n\/\/ The above would_overflow(a. b) assumes rel_time_t is unsigned\nstatic_assert(std::is_unsigned<rel_time_t>::value,\n \"would_overflow assumes rel_time_t is unsigned\");\n\nrel_time_t mc_time_convert_to_real_time(rel_time_t t, cb::ExpiryLimit limit) {\n rel_time_t rv = 0;\n\n int64_t epoch{memcached_epoch};\n int64_t uptime{memcached_uptime.load()};\n\n if (t > memcached_maximum_relative_time) { \/\/ t is absolute\n\n \/\/ Ensure overflow is predictable (we stay at max rel_time_t)\n if (would_overflow(epoch, uptime)) {\n return std::numeric_limits<rel_time_t>::max();\n }\n if (limit &&\n would_overflow(gsl::narrow_cast<rel_time_t>(epoch + uptime),\n limit.get())) {\n return std::numeric_limits<rel_time_t>::max();\n }\n\n if (limit && t > (epoch + uptime + limit.get().count())) {\n if (would_overflow(gsl::narrow_cast<int64_t>(epoch + uptime),\n limit.get().count())) {\n t = std::numeric_limits<rel_time_t>::max();\n } else {\n t = gsl::narrow<rel_time_t>((epoch + uptime) +\n limit.get().count());\n }\n }\n\n \/* if item expiration is at\/before the server started, give it an\n expiration time of 1 second after the server started.\n (because 0 means don't expire). without this, we'd\n underflow and wrap around to some large value way in the\n future, effectively making items expiring in the past\n really expiring never *\/\n if (t <= epoch) {\n rv = (rel_time_t)1;\n } else {\n rv = (rel_time_t)(t - epoch);\n }\n } else if (t != 0) { \/\/ t is relative\n if (limit && t > limit.get().count()) {\n t = gsl::narrow<rel_time_t>(limit.get().count());\n }\n\n \/\/ Ensure overflow is predictable (we stay at max rel_time_t)\n if (would_overflow(t, uptime)) {\n rv = std::numeric_limits<rel_time_t>::max();\n } else {\n if (limit &&\n would_overflow(gsl::narrow_cast<rel_time_t>(t + uptime),\n limit.get())) {\n rv = std::numeric_limits<rel_time_t>::max();\n } else {\n rv = (rel_time_t)(t + uptime);\n }\n }\n }\n\n return rv;\n}\n\n\/*\n * Convert the relative time to an absolute time (relative to EPOCH ;) )\n *\/\ntime_t mc_time_convert_to_abs_time(const rel_time_t rel_time) {\n return memcached_epoch + rel_time;\n}\n\n\/*\n * clock_handler - libevent call back.\n * This method is called (ticks) every 'memcached_clock_tick_seconds' and\n * primarily keeps time flowing.\n *\/\nstatic void mc_time_clock_event_handler(evutil_socket_t fd, short which, void *arg) {\n static bool initialized = false;\n static struct event clockevent;\n struct timeval t;\n\n t.tv_sec = (long)memcached_clock_tick_seconds;\n t.tv_usec = 0;\n\n if (memcached_shutdown) {\n return ;\n }\n\n if (initialized) {\n \/* only delete the event if it's actually there. *\/\n evtimer_del(&clockevent);\n } else {\n initialized = true;\n }\n\n evtimer_set(&clockevent, mc_time_clock_event_handler, 0);\n event_base_set(main_ev_base, &clockevent);\n evtimer_add(&clockevent, &t);\n\n mc_time_clock_tick();\n}\n\n\/*\n * Update a number of time keeping variables and account for system\n * clock changes.\n *\/\nvoid mc_time_clock_tick(void) {\n static uint64_t check_system_time = 0;\n static bool previous_time_valid = false;\n static struct timeval previous_time = {0, 0};\n\n \/* calculate our monotonic uptime *\/\n memcached_uptime = (rel_time_t)(cb_get_monotonic_seconds() - memcached_monotonic_start + cb_get_uptime_offset());\n\n \/* Collect samples *\/\n mc_gather_timing_samples();\n\n \/*\n every 'memcached_check_system_time' seconds, keep an eye on the\n system clock.\n *\/\n if (memcached_uptime >= check_system_time) {\n struct timeval timeofday;\n cb_get_timeofday(&timeofday);\n time_t difference = labs(timeofday.tv_sec - previous_time.tv_sec);\n \/* perform a fuzzy check on time, this allows 2 seconds each way. *\/\n if (previous_time_valid\n && ((difference > memcached_check_system_time + 1)\n || (difference < memcached_check_system_time - 1))) {\n if (settings.extensions.logger) {\n \/* log all variables used in time calculations *\/\n LOG_WARNING(\n \"system clock changed? difference = {}, \"\n \"memcached_epoch = {}, \"\n \"memcached_uptime = {}, new memcached_epoch = {}, \"\n \"next check {}\",\n difference,\n memcached_epoch,\n memcached_uptime.load(),\n (timeofday.tv_sec - memcached_uptime),\n check_system_time + memcached_check_system_time);\n }\n \/* adjust memcached_epoch to ensure correct timeofday can\n be calculated by clients*\/\n memcached_epoch = timeofday.tv_sec - memcached_uptime;\n }\n\n \/* move our checksystem time marker to trigger the next check\n at the correct interval*\/\n check_system_time += memcached_check_system_time;\n\n previous_time_valid = true;\n previous_time = timeofday;\n }\n\n \/\/ check on tasks to be made runnable in the future\n executorPool->clockTick();\n}\n\nstatic void mc_gather_timing_samples(void) {\n bucketsForEach([](Bucket& bucket, void *) -> bool {\n bucket.timings.sample(std::chrono::seconds(1));\n return true;\n }, nullptr);\n}\n<commit_msg>MB-28635: Fix race in memcached_epoch access<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Time keeping for memcached.\n *\n * Orginally part of memcached.c this module encapsulates some time\n * keeping functions that are exposed via the engine API.\n *\n * This module implements a prviate and non-data path \"tick\" function\n * which maintains a view of time.\n *\n * - see mc_time_clock_tick\n *\n * This module provides public time methods that allow performant\n * data-path code access to:\n *\n * 1. A monotonic interval time (great for relative expiry and timed\n * locks). - mc_time_get_current_time()\n * 2. approximation of system-clock. - mc_time_convert_to_abs_time()\n * 2.1 The following returns system clock time -\n * mc_time_convert_to_abs_time(mc_time_get_current_time())\n * 3. A method for work with expiry timestamps as per the memcached\n * protocol - mc_time_convert_to_real_time()\n *\n *\/\n#include <signal.h>\n\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mc_time.h\"\n\n#include <atomic>\n\nextern std::atomic<bool> memcached_shutdown;\n\n\/*\n * This constant defines the seconds between libevent clock callbacks.\n * This roughly equates to how frequency of gethrtime calls made.\n *\/\nconst time_t memcached_clock_tick_seconds = 1;\n\n\/*\n * This constant defines the frequency of system clock checks.\n * This equates to an extra gettimeofday every 'n' seconds.\n *\/\nconst time_t memcached_check_system_time = 60;\n\n\/*\n * This constant defines the maximum relative time (30 days in seconds)\n * time values above this are interpretted as absolute.\n *\/\nconst time_t memcached_maximum_relative_time = 60*60*24*30;\n\nstatic std::atomic<rel_time_t> memcached_uptime(0);\nstatic std::atomic<time_t> memcached_epoch(0);\nstatic volatile uint64_t memcached_monotonic_start = 0;\nstatic struct event_base* main_ev_base = NULL;\n\nstatic void mc_time_clock_event_handler(evutil_socket_t fd, short which, void *arg);\nstatic void mc_gather_timing_samples(void);\n\n\/*\n * Init internal state and start the timer event callback.\n *\/\nvoid mc_time_init(struct event_base* ev_base) {\n\n main_ev_base = ev_base;\n\n mc_time_init_epoch();\n\n \/* tick once to begin procedings *\/\n mc_time_clock_tick();\n\n \/* Begin the time keeping by registering for a time based callback *\/\n mc_time_clock_event_handler(0, 0, 0);\n}\n\n\/*\n * Initisalise our \"EPOCH\" variables\n * In order to provide a monotonic \"uptime\" and track system time, we record\n * some points in time.\n *\/\nvoid mc_time_init_epoch(void) {\n struct timeval t;\n memcached_uptime = 0;\n memcached_monotonic_start = cb_get_monotonic_seconds();\n cb_get_timeofday(&t);\n memcached_epoch = t.tv_sec;\n}\n\n\/*\n * Return a monotonically increasing value.\n * The value returned represents seconds since memcached started.\n *\/\nrel_time_t mc_time_get_current_time(void) {\n return memcached_uptime;\n}\n\n\/\/\/ @return true if a + b would overflow rel_time_t\nstatic bool would_overflow(rel_time_t a, std::chrono::seconds b) {\n return a > (std::numeric_limits<rel_time_t>::max() - b.count());\n}\n\n\/**\n * @return true if a + b would overflow int64_t\n *\/\nstatic bool would_overflow(int64_t a, int64_t b) {\n return a > (std::numeric_limits<int64_t>::max() - b);\n}\n\n\/\/ The above would_overflow(a. b) assumes rel_time_t is unsigned\nstatic_assert(std::is_unsigned<rel_time_t>::value,\n \"would_overflow assumes rel_time_t is unsigned\");\n\nrel_time_t mc_time_convert_to_real_time(rel_time_t t, cb::ExpiryLimit limit) {\n rel_time_t rv = 0;\n\n int64_t epoch{memcached_epoch.load()};\n int64_t uptime{memcached_uptime.load()};\n\n if (t > memcached_maximum_relative_time) { \/\/ t is absolute\n\n \/\/ Ensure overflow is predictable (we stay at max rel_time_t)\n if (would_overflow(epoch, uptime)) {\n return std::numeric_limits<rel_time_t>::max();\n }\n if (limit &&\n would_overflow(gsl::narrow_cast<rel_time_t>(epoch + uptime),\n limit.get())) {\n return std::numeric_limits<rel_time_t>::max();\n }\n\n if (limit && t > (epoch + uptime + limit.get().count())) {\n if (would_overflow(gsl::narrow_cast<int64_t>(epoch + uptime),\n limit.get().count())) {\n t = std::numeric_limits<rel_time_t>::max();\n } else {\n t = gsl::narrow<rel_time_t>((epoch + uptime) +\n limit.get().count());\n }\n }\n\n \/* if item expiration is at\/before the server started, give it an\n expiration time of 1 second after the server started.\n (because 0 means don't expire). without this, we'd\n underflow and wrap around to some large value way in the\n future, effectively making items expiring in the past\n really expiring never *\/\n if (t <= epoch) {\n rv = (rel_time_t)1;\n } else {\n rv = (rel_time_t)(t - epoch);\n }\n } else if (t != 0) { \/\/ t is relative\n if (limit && t > limit.get().count()) {\n t = gsl::narrow<rel_time_t>(limit.get().count());\n }\n\n \/\/ Ensure overflow is predictable (we stay at max rel_time_t)\n if (would_overflow(t, uptime)) {\n rv = std::numeric_limits<rel_time_t>::max();\n } else {\n if (limit &&\n would_overflow(gsl::narrow_cast<rel_time_t>(t + uptime),\n limit.get())) {\n rv = std::numeric_limits<rel_time_t>::max();\n } else {\n rv = (rel_time_t)(t + uptime);\n }\n }\n }\n\n return rv;\n}\n\n\/*\n * Convert the relative time to an absolute time (relative to EPOCH ;) )\n *\/\ntime_t mc_time_convert_to_abs_time(const rel_time_t rel_time) {\n return memcached_epoch + rel_time;\n}\n\n\/*\n * clock_handler - libevent call back.\n * This method is called (ticks) every 'memcached_clock_tick_seconds' and\n * primarily keeps time flowing.\n *\/\nstatic void mc_time_clock_event_handler(evutil_socket_t fd, short which, void *arg) {\n static bool initialized = false;\n static struct event clockevent;\n struct timeval t;\n\n t.tv_sec = (long)memcached_clock_tick_seconds;\n t.tv_usec = 0;\n\n if (memcached_shutdown) {\n return ;\n }\n\n if (initialized) {\n \/* only delete the event if it's actually there. *\/\n evtimer_del(&clockevent);\n } else {\n initialized = true;\n }\n\n evtimer_set(&clockevent, mc_time_clock_event_handler, 0);\n event_base_set(main_ev_base, &clockevent);\n evtimer_add(&clockevent, &t);\n\n mc_time_clock_tick();\n}\n\n\/*\n * Update a number of time keeping variables and account for system\n * clock changes.\n *\/\nvoid mc_time_clock_tick(void) {\n static uint64_t check_system_time = 0;\n static bool previous_time_valid = false;\n static struct timeval previous_time = {0, 0};\n\n \/* calculate our monotonic uptime *\/\n memcached_uptime = (rel_time_t)(cb_get_monotonic_seconds() - memcached_monotonic_start + cb_get_uptime_offset());\n\n \/* Collect samples *\/\n mc_gather_timing_samples();\n\n \/*\n every 'memcached_check_system_time' seconds, keep an eye on the\n system clock.\n *\/\n if (memcached_uptime >= check_system_time) {\n struct timeval timeofday;\n cb_get_timeofday(&timeofday);\n time_t difference = labs(timeofday.tv_sec - previous_time.tv_sec);\n \/* perform a fuzzy check on time, this allows 2 seconds each way. *\/\n if (previous_time_valid\n && ((difference > memcached_check_system_time + 1)\n || (difference < memcached_check_system_time - 1))) {\n if (settings.extensions.logger) {\n \/* log all variables used in time calculations *\/\n LOG_WARNING(\n \"system clock changed? difference = {}, \"\n \"memcached_epoch = {}, \"\n \"memcached_uptime = {}, new memcached_epoch = {}, \"\n \"next check {}\",\n difference,\n memcached_epoch.load(),\n memcached_uptime.load(),\n (timeofday.tv_sec - memcached_uptime),\n check_system_time + memcached_check_system_time);\n }\n \/* adjust memcached_epoch to ensure correct timeofday can\n be calculated by clients*\/\n memcached_epoch.store(timeofday.tv_sec - memcached_uptime);\n }\n\n \/* move our checksystem time marker to trigger the next check\n at the correct interval*\/\n check_system_time += memcached_check_system_time;\n\n previous_time_valid = true;\n previous_time = timeofday;\n }\n\n \/\/ check on tasks to be made runnable in the future\n executorPool->clockTick();\n}\n\nstatic void mc_gather_timing_samples(void) {\n bucketsForEach([](Bucket& bucket, void *) -> bool {\n bucket.timings.sample(std::chrono::seconds(1));\n return true;\n }, nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mcaudit.h\"\n#include \"memcached_audit_events.h\"\n#include \"buckets.h\"\n#include \"debug_helpers.h\"\n#include \"runtime.h\"\n\n#include <memcached\/audit_interface.h>\n#include <cJSON.h>\n#include <memcached\/isotime.h>\n#include <relaxed_atomic.h>\n\nstatic Couchbase::RelaxedAtomic<bool> audit_enabled;\n\n\/**\n * Create the typical memcached audit object. It constists of a\n * timestamp, the socket endpoints and the creds. Then each audit event\n * may add event-specific content.\n *\n * @param c the connection object\n * @return the cJSON object containing the basic information\n *\/\nstatic unique_cJSON_ptr create_memcached_audit_object(const Connection *c) {\n cJSON *root = cJSON_CreateObject();\n\n std::string timestamp = ISOTime::generatetimestamp();\n cJSON_AddStringToObject(root, \"timestamp\", timestamp.c_str());\n\n cJSON_AddStringToObject(root, \"peername\", c->getPeername().c_str());\n cJSON_AddStringToObject(root, \"sockname\", c->getSockname().c_str());\n cJSON *source = cJSON_CreateObject();\n cJSON_AddStringToObject(source, \"source\", \"memcached\");\n cJSON_AddStringToObject(source, \"user\", c->getUsername());\n cJSON_AddItemToObject(root, \"real_userid\", source);\n\n return unique_cJSON_ptr(root);\n}\n\n\/**\n * Convert the JSON object to text and send it to the audit framework\n *\n * @param c the connection object requesting the call\n * @param id the audit identifier\n * @param event the payload of the audit description\n * @param warn what to log if we're failing to put the audit event\n *\/\nstatic void do_audit(const Connection* c,\n uint32_t id,\n unique_cJSON_ptr& event,\n const char* warn) {\n auto text = to_string(event, false);\n auto status = put_audit_event(get_audit_handle(), id, text.data(),\n text.length());\n\n if (status != AUDIT_SUCCESS) {\n LOG_WARNING(c, \"%s: %s\", warn, text.c_str());\n }\n}\n\nvoid audit_auth_failure(const Connection *c, const char *reason) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"reason\", reason);\n\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_FAILED, root,\n \"Failed to send AUTH FAILED audit event\");\n}\n\nvoid audit_auth_success(const Connection *c) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED, root,\n \"Failed to send AUTH SUCCESS audit event\");\n}\n\n\nvoid audit_bucket_flush(const Connection *c, const char *bucket) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket);\n\n do_audit(c, MEMCACHED_AUDIT_BUCKET_FLUSH, root,\n \"Failed to send BUCKET_FLUSH audit event\");\n}\n\n\nvoid audit_dcp_open(const Connection *c) {\n if (!audit_enabled) {\n return;\n }\n if (c->isInternal()) {\n LOG_INFO(c, \"Open DCP stream with admin credentials\");\n } else {\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", getBucketName(c));\n\n do_audit(c, MEMCACHED_AUDIT_OPENED_DCP_CONNECTION, root,\n \"Failed to send DCP open connection \"\n \"audit event to audit daemon\");\n }\n}\n\nvoid audit_set_privilege_debug_mode(const Connection* c, bool enable) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddBoolToObject(root.get(), \"enable\", enable);\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED, root,\n \"Failed to send modifications in privilege debug state \"\n \"audit event to audit daemon\");\n}\n\nvoid audit_privilege_debug(const Connection* c,\n const std::string& command,\n const std::string& bucket,\n const std::string& privilege,\n const std::string& context) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"command\", command.c_str());\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket.c_str());\n cJSON_AddStringToObject(root.get(), \"privilege\", privilege.c_str());\n cJSON_AddStringToObject(root.get(), \"context\", context.c_str());\n\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG, root,\n \"Failed to send privilege debug audit event to audit daemon\");\n}\n\nvoid audit_command_access_failed(const McbpConnection *c) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer, sizeof(buffer), c->getId(), true,\n \"Access to command is not allowed:\",\n reinterpret_cast<const char*>(&c->getBinaryHeader()),\n sizeof(protocol_binary_request_header));\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(c, MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE, root, buffer);\n}\n\nvoid audit_invalid_packet(const McbpConnection *c) {\n if (!audit_enabled) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer, sizeof(buffer), c->getId(), true,\n \"Invalid Packet:\",\n reinterpret_cast<const char*>(&c->getBinaryHeader()),\n sizeof(protocol_binary_request_header));\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(c, MEMCACHED_AUDIT_INVALID_PACKET, root, buffer);\n}\n\nbool mc_audit_event(uint32_t audit_eventid,\n const void* payload,\n size_t length) {\n if (!audit_enabled) {\n return true;\n }\n\n return put_audit_event(get_audit_handle(), audit_eventid,\n payload, length) == AUDIT_SUCCESS;\n}\n\nstatic void event_state_listener(uint32_t id, bool enabled) {\n \/\/ We only care about the global on \/ off switch\n if (id == 0) {\n LOG_NOTICE(nullptr, \"Audit changed from: %s to: %s\",\n audit_enabled ? \"enabled\" : \"disabled\",\n enabled ? \"enabled\" : \"disabled\");\n audit_enabled.store(enabled);\n }\n}\n\nvoid initialize_audit() {\n\/* Start the audit daemon *\/\n AUDIT_EXTENSION_DATA audit_extension_data;\n memset(&audit_extension_data, 0, sizeof(audit_extension_data));\n audit_extension_data.log_extension = settings.extensions.logger;\n audit_extension_data.notify_io_complete = notify_io_complete;\n audit_extension_data.configfile = settings.getAuditFile().c_str();\n Audit* handle = nullptr;\n if (start_auditdaemon(&audit_extension_data, &handle) != AUDIT_SUCCESS) {\n FATAL_ERROR(EXIT_FAILURE, \"FATAL: Failed to start audit daemon\");\n }\n set_audit_handle(handle);\n cb::audit::add_event_state_listener(handle, event_state_listener);\n cb::audit::notify_all_event_states(handle);\n}\n<commit_msg>Add per-event dropping of audit events<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"mcaudit.h\"\n#include \"memcached_audit_events.h\"\n#include \"buckets.h\"\n#include \"debug_helpers.h\"\n#include \"runtime.h\"\n\n#include <memcached\/audit_interface.h>\n#include <cJSON.h>\n#include <memcached\/isotime.h>\n#include <relaxed_atomic.h>\n\nstatic Couchbase::RelaxedAtomic<bool> audit_enabled;\n\nstatic const int First = MEMCACHED_AUDIT_OPENED_DCP_CONNECTION;\nstatic const int Last = MEMCACHED_AUDIT_PRIVILEGE_DEBUG;\n\nstatic std::array<Couchbase::RelaxedAtomic<bool>, Last - First + 1> events;\n\nstatic bool isEnabled(uint32_t id) {\n if (!audit_enabled) {\n \/\/ Global switch is off.. All events are disabled\n return false;\n }\n\n if (id >= First && id <= Last) {\n \/\/ This is one of ours\n return events[id - First];\n }\n\n \/\/ we don't have information about this id... let the underlying event\n \/\/ framework deal with it\n return true;\n}\n\nvoid setEnabled(uint32_t id, bool enable) {\n if (id == 0) {\n LOG_NOTICE(nullptr, \"Audit changed from: %s to: %s\",\n audit_enabled ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n audit_enabled.store(enable);\n }\n\n if (id >= First && id <= Last) {\n LOG_INFO(nullptr, \"Audit descriptor %u changed from: %s to: %s\",\n id, events[id - First] ? \"enabled\" : \"disabled\",\n enable ? \"enabled\" : \"disabled\");\n events[id - First] = enable;\n }\n}\n\n\/**\n * Create the typical memcached audit object. It constists of a\n * timestamp, the socket endpoints and the creds. Then each audit event\n * may add event-specific content.\n *\n * @param c the connection object\n * @return the cJSON object containing the basic information\n *\/\nstatic unique_cJSON_ptr create_memcached_audit_object(const Connection *c) {\n cJSON *root = cJSON_CreateObject();\n\n std::string timestamp = ISOTime::generatetimestamp();\n cJSON_AddStringToObject(root, \"timestamp\", timestamp.c_str());\n\n cJSON_AddStringToObject(root, \"peername\", c->getPeername().c_str());\n cJSON_AddStringToObject(root, \"sockname\", c->getSockname().c_str());\n cJSON *source = cJSON_CreateObject();\n cJSON_AddStringToObject(source, \"source\", \"memcached\");\n cJSON_AddStringToObject(source, \"user\", c->getUsername());\n cJSON_AddItemToObject(root, \"real_userid\", source);\n\n return unique_cJSON_ptr(root);\n}\n\n\/**\n * Convert the JSON object to text and send it to the audit framework\n *\n * @param c the connection object requesting the call\n * @param id the audit identifier\n * @param event the payload of the audit description\n * @param warn what to log if we're failing to put the audit event\n *\/\nstatic void do_audit(const Connection* c,\n uint32_t id,\n unique_cJSON_ptr& event,\n const char* warn) {\n auto text = to_string(event, false);\n auto status = put_audit_event(get_audit_handle(), id, text.data(),\n text.length());\n\n if (status != AUDIT_SUCCESS) {\n LOG_WARNING(c, \"%s: %s\", warn, text.c_str());\n }\n}\n\nvoid audit_auth_failure(const Connection *c, const char *reason) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_FAILED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"reason\", reason);\n\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_FAILED, root,\n \"Failed to send AUTH FAILED audit event\");\n}\n\nvoid audit_auth_success(const Connection *c) {\n if (!isEnabled(MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n do_audit(c, MEMCACHED_AUDIT_AUTHENTICATION_SUCCEEDED, root,\n \"Failed to send AUTH SUCCESS audit event\");\n}\n\n\nvoid audit_bucket_flush(const Connection *c, const char *bucket) {\n if (!isEnabled(MEMCACHED_AUDIT_BUCKET_FLUSH)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket);\n\n do_audit(c, MEMCACHED_AUDIT_BUCKET_FLUSH, root,\n \"Failed to send BUCKET_FLUSH audit event\");\n}\n\n\nvoid audit_dcp_open(const Connection *c) {\n if (!isEnabled(MEMCACHED_AUDIT_OPENED_DCP_CONNECTION)) {\n return;\n }\n if (c->isInternal()) {\n LOG_INFO(c, \"Open DCP stream with admin credentials\");\n } else {\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"bucket\", getBucketName(c));\n\n do_audit(c, MEMCACHED_AUDIT_OPENED_DCP_CONNECTION, root,\n \"Failed to send DCP open connection \"\n \"audit event to audit daemon\");\n }\n}\n\nvoid audit_set_privilege_debug_mode(const Connection* c, bool enable) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddBoolToObject(root.get(), \"enable\", enable);\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG_CONFIGURED, root,\n \"Failed to send modifications in privilege debug state \"\n \"audit event to audit daemon\");\n}\n\nvoid audit_privilege_debug(const Connection* c,\n const std::string& command,\n const std::string& bucket,\n const std::string& privilege,\n const std::string& context) {\n if (!isEnabled(MEMCACHED_AUDIT_PRIVILEGE_DEBUG)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n cJSON_AddStringToObject(root.get(), \"command\", command.c_str());\n cJSON_AddStringToObject(root.get(), \"bucket\", bucket.c_str());\n cJSON_AddStringToObject(root.get(), \"privilege\", privilege.c_str());\n cJSON_AddStringToObject(root.get(), \"context\", context.c_str());\n\n do_audit(c, MEMCACHED_AUDIT_PRIVILEGE_DEBUG, root,\n \"Failed to send privilege debug audit event to audit daemon\");\n}\n\nvoid audit_command_access_failed(const McbpConnection *c) {\n if (!isEnabled(MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer, sizeof(buffer), c->getId(), true,\n \"Access to command is not allowed:\",\n reinterpret_cast<const char*>(&c->getBinaryHeader()),\n sizeof(protocol_binary_request_header));\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(c, MEMCACHED_AUDIT_COMMAND_ACCESS_FAILURE, root, buffer);\n}\n\nvoid audit_invalid_packet(const McbpConnection *c) {\n if (!isEnabled(MEMCACHED_AUDIT_INVALID_PACKET)) {\n return;\n }\n auto root = create_memcached_audit_object(c);\n char buffer[256];\n memset(buffer, 0, sizeof(buffer));\n \/\/ Deliberately ignore failure of bytes_to_output_string\n \/\/ We'll either have a partial string or no string.\n bytes_to_output_string(buffer, sizeof(buffer), c->getId(), true,\n \"Invalid Packet:\",\n reinterpret_cast<const char*>(&c->getBinaryHeader()),\n sizeof(protocol_binary_request_header));\n cJSON_AddStringToObject(root.get(), \"packet\", buffer);\n do_audit(c, MEMCACHED_AUDIT_INVALID_PACKET, root, buffer);\n}\n\nbool mc_audit_event(uint32_t audit_eventid,\n const void* payload,\n size_t length) {\n if (!audit_enabled) {\n return true;\n }\n\n return put_audit_event(get_audit_handle(), audit_eventid,\n payload, length) == AUDIT_SUCCESS;\n}\n\nstatic void event_state_listener(uint32_t id, bool enabled) {\n setEnabled(id, enabled);\n}\n\nvoid initialize_audit() {\n\/* Start the audit daemon *\/\n AUDIT_EXTENSION_DATA audit_extension_data;\n memset(&audit_extension_data, 0, sizeof(audit_extension_data));\n audit_extension_data.log_extension = settings.extensions.logger;\n audit_extension_data.notify_io_complete = notify_io_complete;\n audit_extension_data.configfile = settings.getAuditFile().c_str();\n Audit* handle = nullptr;\n if (start_auditdaemon(&audit_extension_data, &handle) != AUDIT_SUCCESS) {\n FATAL_ERROR(EXIT_FAILURE, \"FATAL: Failed to start audit daemon\");\n }\n set_audit_handle(handle);\n cb::audit::add_event_state_listener(handle, event_state_listener);\n cb::audit::notify_all_event_states(handle);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2015 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"topkeys.h\"\n#include \"settings.h\"\n\n#include <platform\/sysinfo.h>\n\n#include <folly\/concurrency\/CacheLocality.h>\n#include <inttypes.h>\n#include <nlohmann\/json.hpp>\n\n#include <algorithm>\n#include <gsl\/gsl>\n#include <set>\n#include <stdexcept>\n\n\/*\n * Implementation Details\n *\n * === TopKeys ===\n *\n * The TopKeys class is split into shards for performance reasons. We create one\n * shard per (logical) core to:\n *\n * a) prevent any cache contention\n * b) allow as much concurrent access as possible (each shard is guarded by a\n * mutex)\n *\n * Topkeys passes on requests to the correct Shard (determined by the core id of\n * the calling thread), and when statistics are requested it aggregates\n * information from each shard. When aggregating information, the TopKeys class\n * has to remove duplicates from the possible pool of top keys because we shard\n * per core for performance. Previously, TopKeys would create 8 shards\n * (regardless of machine size), each with storage for a configurably amount of\n * keys and shard by key hash (which meant that we would not have duplicate keys\n * across shards). Now that we shard per core instead of by key hash, to keep\n * the size of the stat output the same we need a minimum of 8 X N keys per\n * shard (because each shard could be an exact duplicate of the others).\n *\n * === TopKeys::Shard ===\n *\n * This is where the action happens. Each Shard maintains an ordered\n * list of key names and related statistics, orded by when they were\n * last accessed. There is a fixed number of keys each Shard tracks.\n\n * Given we generally track only a small number of keys per shard (10\n * by default), it's highly likely that any one key access will 'miss'\n * - i.e. not find an existing topkey. Therefore this class is\n * optimized for that case, attempting to minimise memory allocation\n * in steady-state.\n *\n * Internally Shard consists of a vector of topkey_t, storing the\n * current max_keys top_keys, and a list of topkey_t pointers, used to\n * main the current most -> least recently used ordering:\n\n * max_keys elements. Each element is a tuple of\n * {hash(key), key, topkey_stats}:\n *\n *\n * vector<topkey_t>\n * +----------+-------------+---------------+\n * | size_t | std::string | topkey_item_t |\n * +----------+-------------+---------------+\n * | <hash 1> | <key 1> | stats 1 | <--- Node1\n * | <hash 2> | <key 2> | stats 2 | <--- Node2\n * | <hash 3> | <key 3> | stats 3 | <--- Node3\n * . .... .\n * | <hash N> | <key N> | stats N | <--- NodeN\n * +----------------------------------------+\n *\n * Node3 <---> Node1 <---> ... <---> Node2\n * ^^^ ^^^\n * MRU LRU\n *\n *\n * Upon a key 'hit', TopKeys::updateKey() is called. That hashes the\n * key, and finds the Shard responsible for that\n * key. TopKeys::Shard::updateKey() is then called.\n *\n * Shard::updateKey() iterates over the vector, searching for a hash\n * match with an existing element, using the actual key string to\n * validate (in case of a hash collision). If it is found, then the\n * stats are simply updated. If it is not found, then the\n * least-recently-used element is selected as a 'victim' and it's\n * contents is replaced by the incoming key. Finally the linked-list\n * is updated to move the updated element to the head of the list.\n *\/\nTopKeys::TopKeys(int mkeys)\n : keys_to_return(mkeys * legacy_multiplier), shards(cb::get_cpu_count()) {\n for (auto& shard : shards) {\n shard->setMaxKeys(keys_to_return);\n }\n}\n\nTopKeys::~TopKeys() {\n}\n\nvoid TopKeys::updateKey(const void* key,\n size_t nkey,\n rel_time_t operation_time) {\n if (Settings::instance().isTopkeysEnabled()) {\n doUpdateKey(key, nkey, operation_time);\n }\n}\n\nENGINE_ERROR_CODE TopKeys::stats(const void* cookie,\n rel_time_t current_time,\n const AddStatFn& add_stat) {\n if (Settings::instance().isTopkeysEnabled()) {\n return doStats(cookie, current_time, add_stat);\n }\n\n return ENGINE_SUCCESS;\n}\n\nENGINE_ERROR_CODE TopKeys::json_stats(nlohmann::json& object,\n rel_time_t current_time) {\n if (Settings::instance().isTopkeysEnabled()) {\n return do_json_stats(object, current_time);\n }\n\n return ENGINE_SUCCESS;\n}\n\nTopKeys::Shard& TopKeys::getShard() {\n auto stripe =\n folly::AccessSpreader<std::atomic>::cachedCurrent(shards.size());\n return *shards[stripe];\n}\n\nTopKeys::topkey_t* TopKeys::Shard::searchForKey(\n size_t key_hash, const cb::const_char_buffer& key) {\n for (auto& topkey : storage) {\n if (topkey.first.hash == key_hash) {\n \/\/ Double-check with full compare\n if (topkey.first.key.compare(\n 0, topkey.first.key.size(), key.buf, key.len) == 0) {\n \/\/ Match found.\n return &topkey;\n }\n }\n }\n return nullptr;\n}\n\nbool TopKeys::Shard::updateKey(const cb::const_char_buffer& key,\n size_t key_hash,\n const rel_time_t ct) {\n try {\n std::lock_guard<std::mutex> lock(mutex);\n\n topkey_t* found_key = searchForKey(key_hash, key);\n\n if (!found_key) {\n \/\/ Key not found.\n if (storage.size() == max_keys) {\n \/\/ Re-use the lowest keys' storage.\n found_key = list.back();\n found_key->first.hash = key_hash;\n found_key->first.key.assign(key.buf, key.len);\n found_key->second = topkey_item_t(ct);\n\n \/\/ Move back element to the front, shuffling down the\n \/\/ rest.\n list.splice(list.begin(), list, --list.end());\n\n } else {\n \/\/ add a new element to the storage array.\n\n storage.emplace_back(std::make_pair(\n KeyId{key_hash, std::string(key.buf, key.len)},\n topkey_item_t(ct)));\n found_key = &storage.back();\n\n \/\/ Insert the new item to the front of the list\n list.push_front(found_key);\n }\n } else {\n \/\/ Found - shuffle to the front.\n auto it = std::find(list.begin(), list.end(), found_key);\n list.splice(list.begin(), list, it);\n }\n\n \/\/ Increment access count.\n found_key->second.ti_access_count++;\n return true;\n\n } catch (const std::bad_alloc&) {\n \/\/ Failed to update.\n return false;\n }\n}\n\nvoid TopKeys::doUpdateKey(const void* key,\n size_t nkey,\n rel_time_t operation_time) {\n if (key == nullptr || nkey == 0) {\n throw std::invalid_argument(\n \"TopKeys::doUpdateKey: key must be specified\");\n }\n\n try {\n \/\/ We store a key hash to make lookup of topkeys faster and because the\n \/\/ memory footprint is relatively small.\n cb::const_char_buffer key_buf(static_cast<const char*>(key), nkey);\n std::hash<cb::const_char_buffer> hash_fn;\n const size_t key_hash = hash_fn(key_buf);\n\n getShard().updateKey(key_buf, key_hash, operation_time);\n } catch (const std::bad_alloc&) {\n \/\/ Failed to increment topkeys, continue...\n }\n}\n\nstruct tk_context {\n using CallbackFn = void (*)(const std::string&,\n const topkey_item_t&,\n void*);\n tk_context(const void* c,\n const AddStatFn& a,\n rel_time_t t,\n nlohmann::json* arr,\n CallbackFn callbackFn)\n : cookie(c),\n add_stat(a),\n current_time(t),\n array(arr),\n callbackFunction(callbackFn) {\n \/\/ empty\n }\n\n const void* cookie;\n AddStatFn add_stat;\n rel_time_t current_time;\n nlohmann::json* array;\n CallbackFn callbackFunction;\n};\n\nstatic void tk_iterfunc(const std::string& key,\n const topkey_item_t& it,\n void* arg) {\n auto* c = (struct tk_context*)arg;\n char val_str[500];\n \/* Note we use accessed time for both 'atime' and 'ctime' below. They have\n * had the same value since the topkeys code was added; but given that\n * clients may expect separate values we print both.\n *\/\n rel_time_t created_time = c->current_time - it.ti_ctime;\n int vlen = snprintf(val_str,\n sizeof(val_str) - 1,\n \"get_hits=%d,\"\n \"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,\"\n \"decr_hits=0,decr_misses=0,delete_hits=0,\"\n \"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,\"\n \"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,\"\n \"get_meta=0,set_meta=0,del_meta=0,ctime=%\" PRIu32\n \",atime=%\" PRIu32,\n it.ti_access_count,\n created_time,\n created_time);\n if (vlen > 0 && vlen < int(sizeof(val_str) - 1)) {\n c->add_stat(key, val_str, c->cookie);\n }\n}\n\n\/**\n * Passing in a list of keys, context, and json array will populate that\n * array with an object for each key in the following format:\n * {\n * \"key\": \"somekey\",\n * \"access_count\": nnn,\n * \"ctime\": ccc,\n * \"atime\": aaa\n * }\n *\/\nstatic void tk_jsonfunc(const std::string& key,\n const topkey_item_t& it,\n void* arg) {\n auto* c = (struct tk_context*)arg;\n if (c->array == nullptr) {\n throw std::invalid_argument(\"tk_jsonfunc: c->array can't be nullptr\");\n }\n\n nlohmann::json obj;\n obj[\"key\"] = key;\n obj[\"access_count\"] = it.ti_access_count;\n obj[\"ctime\"] = c->current_time - it.ti_ctime;\n\n c->array->push_back(obj);\n}\n\nstatic void tk_aggregate_func(const TopKeys::topkey_t& it, void* arg) {\n auto* map = (std::unordered_map<std::string, topkey_item_t>*)arg;\n\n auto res = map->insert(std::make_pair(it.first.key, it.second));\n\n \/\/ If insert failed, then we have a duplicate top key. Add the stats\n if (!res.second) {\n res.first->second.ti_access_count += it.second.ti_access_count;\n }\n}\n\nENGINE_ERROR_CODE TopKeys::doStats(const void* cookie,\n rel_time_t current_time,\n const AddStatFn& add_stat) {\n struct tk_context context(\n cookie, add_stat, current_time, nullptr, &tk_iterfunc);\n doStatsInner(context);\n\n return ENGINE_SUCCESS;\n}\n\n\/**\n * Passing a set of topkeys, and relevant context data will\n * return a json object containing an array of topkeys (with each key\n * appearing as in the example above for tk_jsonfunc):\n * {\n * \"topkeys\": [\n * { ... }, ..., { ... }\n * ]\n * }\n *\/\nENGINE_ERROR_CODE TopKeys::do_json_stats(nlohmann::json& object,\n rel_time_t current_time) {\n nlohmann::json topkeys = nlohmann::json::array();\n struct tk_context context(\n nullptr, nullptr, current_time, &topkeys, &tk_jsonfunc);\n doStatsInner(context);\n\n auto str = topkeys.dump();\n object[\"topkeys\"] = topkeys;\n\n return ENGINE_SUCCESS;\n}\n\nvoid TopKeys::Shard::accept_visitor(iterfunc_t visitor_func,\n void* visitor_ctx) {\n std::lock_guard<std::mutex> lock(mutex);\n for (const auto* key : list) {\n visitor_func(*key, visitor_ctx);\n }\n}\n\nvoid TopKeys::doStatsInner(const tk_context& stat_context) {\n \/\/ 1) Find the unique set of top keys by putting every top key in a map\n std::unordered_map<std::string, topkey_item_t> map =\n std::unordered_map<std::string, topkey_item_t>();\n\n for (auto& shard : shards) {\n shard->accept_visitor(tk_aggregate_func, &map);\n }\n\n \/\/ Easiest way to sort this by access_count is to drop the contents of the\n \/\/ map into a vector and sort that.\n auto items = std::vector<topkey_stat_t>(map.begin(), map.end());\n std::sort(items.begin(),\n items.end(),\n [](const TopKeys::topkey_stat_t& a,\n const TopKeys::topkey_stat_t& b) {\n \/\/ Sort by number of accesses\n return a.second.ti_access_count > b.second.ti_access_count;\n });\n\n \/\/ 2) Iterate on this set making the required callback for each key. We only\n \/\/ iterate from the start of the container (highest access count) to the\n \/\/ number of keys to return.\n std::for_each(items.begin(),\n std::min(items.begin() + keys_to_return, items.end()),\n [stat_context](const topkey_stat_t& t) {\n stat_context.callbackFunction(\n t.first, t.second, (void*)&stat_context);\n });\n}\n<commit_msg>Refactor c-style cast to C++ casting in top keys<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2020 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"topkeys.h\"\n#include \"settings.h\"\n\n#include <platform\/sysinfo.h>\n\n#include <folly\/concurrency\/CacheLocality.h>\n#include <inttypes.h>\n#include <nlohmann\/json.hpp>\n\n#include <algorithm>\n#include <gsl\/gsl>\n#include <set>\n#include <stdexcept>\n\n\/*\n * Implementation Details\n *\n * === TopKeys ===\n *\n * The TopKeys class is split into shards for performance reasons. We create one\n * shard per (logical) core to:\n *\n * a) prevent any cache contention\n * b) allow as much concurrent access as possible (each shard is guarded by a\n * mutex)\n *\n * Topkeys passes on requests to the correct Shard (determined by the core id of\n * the calling thread), and when statistics are requested it aggregates\n * information from each shard. When aggregating information, the TopKeys class\n * has to remove duplicates from the possible pool of top keys because we shard\n * per core for performance. Previously, TopKeys would create 8 shards\n * (regardless of machine size), each with storage for a configurably amount of\n * keys and shard by key hash (which meant that we would not have duplicate keys\n * across shards). Now that we shard per core instead of by key hash, to keep\n * the size of the stat output the same we need a minimum of 8 X N keys per\n * shard (because each shard could be an exact duplicate of the others).\n *\n * === TopKeys::Shard ===\n *\n * This is where the action happens. Each Shard maintains an ordered\n * list of key names and related statistics, orded by when they were\n * last accessed. There is a fixed number of keys each Shard tracks.\n\n * Given we generally track only a small number of keys per shard (10\n * by default), it's highly likely that any one key access will 'miss'\n * - i.e. not find an existing topkey. Therefore this class is\n * optimized for that case, attempting to minimise memory allocation\n * in steady-state.\n *\n * Internally Shard consists of a vector of topkey_t, storing the\n * current max_keys top_keys, and a list of topkey_t pointers, used to\n * main the current most -> least recently used ordering:\n\n * max_keys elements. Each element is a tuple of\n * {hash(key), key, topkey_stats}:\n *\n *\n * vector<topkey_t>\n * +----------+-------------+---------------+\n * | size_t | std::string | topkey_item_t |\n * +----------+-------------+---------------+\n * | <hash 1> | <key 1> | stats 1 | <--- Node1\n * | <hash 2> | <key 2> | stats 2 | <--- Node2\n * | <hash 3> | <key 3> | stats 3 | <--- Node3\n * . .... .\n * | <hash N> | <key N> | stats N | <--- NodeN\n * +----------------------------------------+\n *\n * Node3 <---> Node1 <---> ... <---> Node2\n * ^^^ ^^^\n * MRU LRU\n *\n *\n * Upon a key 'hit', TopKeys::updateKey() is called. That hashes the\n * key, and finds the Shard responsible for that\n * key. TopKeys::Shard::updateKey() is then called.\n *\n * Shard::updateKey() iterates over the vector, searching for a hash\n * match with an existing element, using the actual key string to\n * validate (in case of a hash collision). If it is found, then the\n * stats are simply updated. If it is not found, then the\n * least-recently-used element is selected as a 'victim' and it's\n * contents is replaced by the incoming key. Finally the linked-list\n * is updated to move the updated element to the head of the list.\n *\/\nTopKeys::TopKeys(int mkeys)\n : keys_to_return(mkeys * legacy_multiplier), shards(cb::get_cpu_count()) {\n for (auto& shard : shards) {\n shard->setMaxKeys(keys_to_return);\n }\n}\n\nTopKeys::~TopKeys() {\n}\n\nvoid TopKeys::updateKey(const void* key,\n size_t nkey,\n rel_time_t operation_time) {\n if (Settings::instance().isTopkeysEnabled()) {\n doUpdateKey(key, nkey, operation_time);\n }\n}\n\nENGINE_ERROR_CODE TopKeys::stats(const void* cookie,\n rel_time_t current_time,\n const AddStatFn& add_stat) {\n if (Settings::instance().isTopkeysEnabled()) {\n return doStats(cookie, current_time, add_stat);\n }\n\n return ENGINE_SUCCESS;\n}\n\nENGINE_ERROR_CODE TopKeys::json_stats(nlohmann::json& object,\n rel_time_t current_time) {\n if (Settings::instance().isTopkeysEnabled()) {\n return do_json_stats(object, current_time);\n }\n\n return ENGINE_SUCCESS;\n}\n\nTopKeys::Shard& TopKeys::getShard() {\n auto stripe =\n folly::AccessSpreader<std::atomic>::cachedCurrent(shards.size());\n return *shards[stripe];\n}\n\nTopKeys::topkey_t* TopKeys::Shard::searchForKey(\n size_t key_hash, const cb::const_char_buffer& key) {\n for (auto& topkey : storage) {\n if (topkey.first.hash == key_hash) {\n \/\/ Double-check with full compare\n if (topkey.first.key.compare(\n 0, topkey.first.key.size(), key.buf, key.len) == 0) {\n \/\/ Match found.\n return &topkey;\n }\n }\n }\n return nullptr;\n}\n\nbool TopKeys::Shard::updateKey(const cb::const_char_buffer& key,\n size_t key_hash,\n const rel_time_t ct) {\n try {\n std::lock_guard<std::mutex> lock(mutex);\n\n topkey_t* found_key = searchForKey(key_hash, key);\n\n if (!found_key) {\n \/\/ Key not found.\n if (storage.size() == max_keys) {\n \/\/ Re-use the lowest keys' storage.\n found_key = list.back();\n found_key->first.hash = key_hash;\n found_key->first.key.assign(key.buf, key.len);\n found_key->second = topkey_item_t(ct);\n\n \/\/ Move back element to the front, shuffling down the\n \/\/ rest.\n list.splice(list.begin(), list, --list.end());\n\n } else {\n \/\/ add a new element to the storage array.\n\n storage.emplace_back(std::make_pair(\n KeyId{key_hash, std::string(key.buf, key.len)},\n topkey_item_t(ct)));\n found_key = &storage.back();\n\n \/\/ Insert the new item to the front of the list\n list.push_front(found_key);\n }\n } else {\n \/\/ Found - shuffle to the front.\n auto it = std::find(list.begin(), list.end(), found_key);\n list.splice(list.begin(), list, it);\n }\n\n \/\/ Increment access count.\n found_key->second.ti_access_count++;\n return true;\n\n } catch (const std::bad_alloc&) {\n \/\/ Failed to update.\n return false;\n }\n}\n\nvoid TopKeys::doUpdateKey(const void* key,\n size_t nkey,\n rel_time_t operation_time) {\n if (key == nullptr || nkey == 0) {\n throw std::invalid_argument(\n \"TopKeys::doUpdateKey: key must be specified\");\n }\n\n try {\n \/\/ We store a key hash to make lookup of topkeys faster and because the\n \/\/ memory footprint is relatively small.\n cb::const_char_buffer key_buf(static_cast<const char*>(key), nkey);\n std::hash<cb::const_char_buffer> hash_fn;\n const size_t key_hash = hash_fn(key_buf);\n\n getShard().updateKey(key_buf, key_hash, operation_time);\n } catch (const std::bad_alloc&) {\n \/\/ Failed to increment topkeys, continue...\n }\n}\n\nstruct tk_context {\n using CallbackFn = void (*)(const std::string&,\n const topkey_item_t&,\n void*);\n tk_context(const void* c,\n const AddStatFn& a,\n rel_time_t t,\n nlohmann::json* arr,\n CallbackFn callbackFn)\n : cookie(c),\n add_stat(a),\n current_time(t),\n array(arr),\n callbackFunction(callbackFn) {\n \/\/ empty\n }\n\n const void* cookie;\n AddStatFn add_stat;\n rel_time_t current_time;\n nlohmann::json* array;\n CallbackFn callbackFunction;\n};\n\nstatic void tk_iterfunc(const std::string& key,\n const topkey_item_t& it,\n void* arg) {\n auto* c = static_cast<struct tk_context*>(arg);\n char val_str[500];\n \/* Note we use accessed time for both 'atime' and 'ctime' below. They have\n * had the same value since the topkeys code was added; but given that\n * clients may expect separate values we print both.\n *\/\n rel_time_t created_time = c->current_time - it.ti_ctime;\n int vlen = snprintf(val_str,\n sizeof(val_str) - 1,\n \"get_hits=%d,\"\n \"get_misses=0,cmd_set=0,incr_hits=0,incr_misses=0,\"\n \"decr_hits=0,decr_misses=0,delete_hits=0,\"\n \"delete_misses=0,evictions=0,cas_hits=0,cas_badval=0,\"\n \"cas_misses=0,get_replica=0,evict=0,getl=0,unlock=0,\"\n \"get_meta=0,set_meta=0,del_meta=0,ctime=%\" PRIu32\n \",atime=%\" PRIu32,\n it.ti_access_count,\n created_time,\n created_time);\n if (vlen > 0 && vlen < int(sizeof(val_str) - 1)) {\n c->add_stat(key, val_str, c->cookie);\n }\n}\n\n\/**\n * Passing in a list of keys, context, and json array will populate that\n * array with an object for each key in the following format:\n * {\n * \"key\": \"somekey\",\n * \"access_count\": nnn,\n * \"ctime\": ccc,\n * \"atime\": aaa\n * }\n *\/\nstatic void tk_jsonfunc(const std::string& key,\n const topkey_item_t& it,\n void* arg) {\n auto* c = static_cast<struct tk_context*>(arg);\n if (c->array == nullptr) {\n throw std::invalid_argument(\"tk_jsonfunc: c->array can't be nullptr\");\n }\n\n nlohmann::json obj;\n obj[\"key\"] = key;\n obj[\"access_count\"] = it.ti_access_count;\n obj[\"ctime\"] = c->current_time - it.ti_ctime;\n\n c->array->push_back(obj);\n}\n\nstatic void tk_aggregate_func(const TopKeys::topkey_t& it, void* arg) {\n auto* map =\n static_cast<std::unordered_map<std::string, topkey_item_t>*>(arg);\n\n auto res = map->insert(std::make_pair(it.first.key, it.second));\n\n \/\/ If insert failed, then we have a duplicate top key. Add the stats\n if (!res.second) {\n res.first->second.ti_access_count += it.second.ti_access_count;\n }\n}\n\nENGINE_ERROR_CODE TopKeys::doStats(const void* cookie,\n rel_time_t current_time,\n const AddStatFn& add_stat) {\n struct tk_context context(\n cookie, add_stat, current_time, nullptr, &tk_iterfunc);\n doStatsInner(context);\n\n return ENGINE_SUCCESS;\n}\n\n\/**\n * Passing a set of topkeys, and relevant context data will\n * return a json object containing an array of topkeys (with each key\n * appearing as in the example above for tk_jsonfunc):\n * {\n * \"topkeys\": [\n * { ... }, ..., { ... }\n * ]\n * }\n *\/\nENGINE_ERROR_CODE TopKeys::do_json_stats(nlohmann::json& object,\n rel_time_t current_time) {\n nlohmann::json topkeys = nlohmann::json::array();\n struct tk_context context(\n nullptr, nullptr, current_time, &topkeys, &tk_jsonfunc);\n doStatsInner(context);\n\n auto str = topkeys.dump();\n object[\"topkeys\"] = topkeys;\n\n return ENGINE_SUCCESS;\n}\n\nvoid TopKeys::Shard::accept_visitor(iterfunc_t visitor_func,\n void* visitor_ctx) {\n std::lock_guard<std::mutex> lock(mutex);\n for (const auto* key : list) {\n visitor_func(*key, visitor_ctx);\n }\n}\n\nvoid TopKeys::doStatsInner(const tk_context& stat_context) {\n \/\/ 1) Find the unique set of top keys by putting every top key in a map\n std::unordered_map<std::string, topkey_item_t> map =\n std::unordered_map<std::string, topkey_item_t>();\n\n for (auto& shard : shards) {\n shard->accept_visitor(tk_aggregate_func, &map);\n }\n\n \/\/ Easiest way to sort this by access_count is to drop the contents of the\n \/\/ map into a vector and sort that.\n auto items = std::vector<topkey_stat_t>(map.begin(), map.end());\n std::sort(items.begin(),\n items.end(),\n [](const TopKeys::topkey_stat_t& a,\n const TopKeys::topkey_stat_t& b) {\n \/\/ Sort by number of accesses\n return a.second.ti_access_count > b.second.ti_access_count;\n });\n\n \/\/ 2) Iterate on this set making the required callback for each key. We only\n \/\/ iterate from the start of the container (highest access count) to the\n \/\/ number of keys to return.\n std::for_each(items.begin(),\n std::min(items.begin() + keys_to_return, items.end()),\n [stat_context](const topkey_stat_t& t) {\n stat_context.callbackFunction(\n t.first, t.second, (void*)&stat_context);\n });\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Create 1133 - Rest of a Division.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * This program is under the GNU GPL.\n * Use at your own risk.\n *\n * written by David Bucciarelli (humanware@plus.it)\n * Humanware s.r.l.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <GL\/glut.h>\n#ifndef M_PI\n#define M_PI 3.14159265\n#endif\n\n#include \"particles.h\"\nextern \"C\" {\n#include \"readtex.h\"\n}\n\n#ifdef _WIN32\n#include <windows.h>\n#include <mmsystem.h>\n#endif\n\n#ifdef XMESA\n#include \"GL\/xmesa.h\"\nstatic int fullscreen=1;\n#endif\n\nstatic int WIDTH=640;\nstatic int HEIGHT=480;\nstatic int NUMPART=7500;\n\n#define FRAME 50\n\nstatic float fogcolor[4]={1.0,1.0,1.0,1.0};\n\n#define DIMP 40.0\n#define DIMTP 32.0\n\nstatic float q[4][3]={\n {-DIMP,0.0,-DIMP},\n {DIMP,0.0,-DIMP},\n {DIMP,0.0,DIMP},\n {-DIMP,0.0,DIMP}\n};\n\nstatic float qt[4][2]={\n {-DIMTP,-DIMTP},\n {DIMTP,-DIMTP},\n {DIMTP,DIMTP},\n {-DIMTP,DIMTP}\n};\n\nstatic int win=0;\n\nstatic int fog=1;\nstatic int help=1;\n\nstatic GLuint groundid;\n\nstatic float obs[3]={2.0,1.0,0.0};\nstatic float dir[3];\nstatic float v=0.0;\nstatic float alpha=-90.0;\nstatic float beta=90.0;\n\nstatic particleSystem *ps;\n\nstatic float gettime()\n{\n static clock_t told=0;\n clock_t tnew,ris;\n\n tnew=clock();\n\n ris=tnew-told;\n\n told=tnew;\n\n return(ris\/(float)CLOCKS_PER_SEC);\n}\n\nstatic float gettimerain()\n{\n static clock_t told=0;\n clock_t tnew,ris;\n\n tnew=clock();\n\n ris=tnew-told;\n\n told=tnew;\n\n return(ris\/(float)CLOCKS_PER_SEC);\n}\n\nstatic void calcposobs(void)\n{\n dir[0]=sin(alpha*M_PI\/180.0);\n dir[2]=cos(alpha*M_PI\/180.0)*sin(beta*M_PI\/180.0);\n dir[1]=cos(beta*M_PI\/180.0);\n\n obs[0]+=v*dir[0];\n obs[1]+=v*dir[1];\n obs[2]+=v*dir[2];\n\n rainParticle::setRainingArea(obs[0]-7.0f,-0.2f,obs[2]-7.0f,obs[0]+7.0f,8.0f,obs[2]+7.0f);\n}\n\nstatic void printstring(void *font, const char *string)\n{\n int len,i;\n\n len=(int)strlen(string);\n for(i=0;i<len;i++)\n glutBitmapCharacter(font,string[i]);\n}\n\nstatic void reshape(int width, int height)\n{\n WIDTH=width;\n HEIGHT=height;\n glViewport(0,0,(GLint)width,(GLint)height);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(70.0,width\/(float)height,0.1,30.0);\n\n glMatrixMode(GL_MODELVIEW);\n}\n\nstatic void printhelp(void)\n{\n glEnable(GL_BLEND);\n glColor4f(0.0,0.0,0.0,0.5);\n glRecti(40,40,600,440);\n glDisable(GL_BLEND);\n\n glColor3f(1.0,0.0,0.0);\n glRasterPos2i(300,420);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"Help\");\n\n glRasterPos2i(60,390);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"h - Toggle Help\");\n\n glRasterPos2i(60,360);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"f - Toggle Fog\");\n glRasterPos2i(60,330);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"Arrow Keys - Rotate\");\n glRasterPos2i(60,300);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"a - Increase velocity\");\n glRasterPos2i(60,270);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"z - Decrease velocity\");\n glRasterPos2i(60,240);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"l - Increase rain length\");\n glRasterPos2i(60,210);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"k - Increase rain length\");\n}\n\nstatic void drawrain(void)\n{\n static int count=0;\n static char frbuf[80];\n float fr;\n\n glEnable(GL_DEPTH_TEST);\n\n if(fog)\n glEnable(GL_FOG);\n else\n glDisable(GL_FOG);\n\n glDepthMask(GL_TRUE);\n glClearColor(1.0,1.0,1.0,1.0);\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n glPushMatrix();\n calcposobs();\n gluLookAt(obs[0],obs[1],obs[2],\n\t obs[0]+dir[0],obs[1]+dir[1],obs[2]+dir[2],\n\t 0.0,1.0,0.0);\n\n glColor4f(1.0,1.0,1.0,1.0);\n\n glEnable(GL_TEXTURE_2D);\n\n glBindTexture(GL_TEXTURE_2D,groundid);\n glBegin(GL_QUADS);\n glTexCoord2fv(qt[0]);\n glVertex3fv(q[0]);\n glTexCoord2fv(qt[1]);\n glVertex3fv(q[1]);\n glTexCoord2fv(qt[2]);\n glVertex3fv(q[2]);\n glTexCoord2fv(qt[3]);\n glVertex3fv(q[3]);\n glEnd();\n\n \/\/ Particle System\n\n glDisable(GL_TEXTURE_2D);\n glShadeModel(GL_SMOOTH);\n glEnable(GL_BLEND);\n\n ps->draw();\n ps->addTime(gettimerain());\n \n glShadeModel(GL_FLAT);\n \n\n if((count % FRAME)==0) {\n fr=gettime();\n sprintf(frbuf,\"Frame rate: %f\",FRAME\/fr);\n }\n\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_FOG);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-0.5,639.5,-0.5,479.5,-1.0,1.0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glColor3f(1.0,0.0,0.0);\n glRasterPos2i(10,10);\n printstring(GLUT_BITMAP_HELVETICA_18,frbuf);\n glRasterPos2i(350,470);\n printstring(GLUT_BITMAP_HELVETICA_10,\"Rain V1.0 Written by David Bucciarelli (humanware@plus.it)\");\n\n if(help)\n printhelp();\n\n reshape(WIDTH,HEIGHT);\n glPopMatrix();\n\n glutSwapBuffers();\n\n count++;\n}\n\n\nstatic void special(int key, int x, int y)\n{\n switch (key) {\n case GLUT_KEY_LEFT:\n alpha+=2.0;\n break;\n case GLUT_KEY_RIGHT:\n alpha-=2.0;\n break;\n case GLUT_KEY_DOWN:\n beta-=2.0;\n break;\n case GLUT_KEY_UP:\n beta+=2.0;\n break;\n }\n}\n\nstatic void key(unsigned char key, int x, int y)\n{\n switch (key) {\n case 27:\n exit(0);\n break;\n\n case 'a':\n v+=0.01;\n break;\n case 'z':\n v-=0.01;\n break;\n\n case 'l':\n rainParticle::setLength(rainParticle::getLength()+0.025f);\n break;\n case 'k':\n rainParticle::setLength(rainParticle::getLength()-0.025f);\n break;\n\n case 'h':\n help=(!help);\n break;\n case 'f':\n fog=(!fog);\n break;\n#ifdef XMESA\n case ' ':\n XMesaSetFXmode(fullscreen ? XMESA_FX_FULLSCREEN : XMESA_FX_WINDOW);\n fullscreen=(!fullscreen);\n break;\n#endif\n }\n}\n\nstatic void inittextures(void)\n{\n GLubyte *img;\n GLint width,height;\n GLenum format;\n GLenum gluerr;\n\n glGenTextures(1,&groundid);\n glBindTexture(GL_TEXTURE_2D,groundid);\n\n if(!(img=LoadRGBImage(\"..\/images\/s128.rgb\",&width,&height,&format))){\n \tfprintf(stderr,\"Error reading a texture.\\n\");\n \texit(-1);\n }\n glPixelStorei(GL_UNPACK_ALIGNMENT,4);\n if((gluerr=(GLenum)gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height,GL_RGB,\n\t\t\t GL_UNSIGNED_BYTE, (GLvoid *)(img)))) {\n fprintf(stderr,\"GLULib%s\\n\",gluErrorString(gluerr));\n exit(-1);\n }\n\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);\n\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);\n\n glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_DECAL);\n}\n\nstatic void initparticle(void)\n{\n ps=new particleSystem;\n\n rainParticle::setRainingArea(-7.0f,-0.2f,-7.0f,7.0f,8.0f,7.0f);\n\n for(int i=0;i<NUMPART;i++) {\n rainParticle *p=new rainParticle;\n p->randomHeight();\n\n ps->addParticle((particle *)p);\n }\n}\n\nint main(int ac,char **av)\n{\n fprintf(stderr,\"Rain V1.0\\nWritten by David Bucciarelli (humanware@plus.it)\\n\");\n\n \/* Default settings *\/\n\n WIDTH=640;\n HEIGHT=480;\n\n glutInitWindowPosition(0,0);\n glutInitWindowSize(WIDTH,HEIGHT);\n glutInit(&ac,av);\n\n glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_DOUBLE);\n\n if(!(win=glutCreateWindow(\"Rain\"))) {\n fprintf(stderr,\"Error opening a window.\\n\");\n exit(-1);\n }\n \n reshape(WIDTH,HEIGHT);\n\n inittextures();\n\n glShadeModel(GL_FLAT);\n glEnable(GL_DEPTH_TEST);\n\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n\n glEnable(GL_FOG);\n glFogi(GL_FOG_MODE,GL_EXP);\n glFogfv(GL_FOG_COLOR,fogcolor);\n glFogf(GL_FOG_DENSITY,0.1);\n#ifdef FX\n glHint(GL_FOG_HINT,GL_NICEST);\n#endif\n\n initparticle();\n\n glutKeyboardFunc(key);\n glutSpecialFunc(special);\n glutDisplayFunc(drawrain);\n glutIdleFunc(drawrain);\n glutReshapeFunc(reshape);\n glutMainLoop();\n\n return(0);\n}\n<commit_msg>progs\/demos: Fix the progs\/demos\/rain help text<commit_after>\/*\n * This program is under the GNU GPL.\n * Use at your own risk.\n *\n * written by David Bucciarelli (humanware@plus.it)\n * Humanware s.r.l.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <GL\/glut.h>\n#ifndef M_PI\n#define M_PI 3.14159265\n#endif\n\n#include \"particles.h\"\nextern \"C\" {\n#include \"readtex.h\"\n}\n\n#ifdef _WIN32\n#include <windows.h>\n#include <mmsystem.h>\n#endif\n\n#ifdef XMESA\n#include \"GL\/xmesa.h\"\nstatic int fullscreen=1;\n#endif\n\nstatic int WIDTH=640;\nstatic int HEIGHT=480;\nstatic int NUMPART=7500;\n\n#define FRAME 50\n\nstatic float fogcolor[4]={1.0,1.0,1.0,1.0};\n\n#define DIMP 40.0\n#define DIMTP 32.0\n\nstatic float q[4][3]={\n {-DIMP,0.0,-DIMP},\n {DIMP,0.0,-DIMP},\n {DIMP,0.0,DIMP},\n {-DIMP,0.0,DIMP}\n};\n\nstatic float qt[4][2]={\n {-DIMTP,-DIMTP},\n {DIMTP,-DIMTP},\n {DIMTP,DIMTP},\n {-DIMTP,DIMTP}\n};\n\nstatic int win=0;\n\nstatic int fog=1;\nstatic int help=1;\n\nstatic GLuint groundid;\n\nstatic float obs[3]={2.0,1.0,0.0};\nstatic float dir[3];\nstatic float v=0.0;\nstatic float alpha=-90.0;\nstatic float beta=90.0;\n\nstatic particleSystem *ps;\n\nstatic float gettime()\n{\n static clock_t told=0;\n clock_t tnew,ris;\n\n tnew=clock();\n\n ris=tnew-told;\n\n told=tnew;\n\n return(ris\/(float)CLOCKS_PER_SEC);\n}\n\nstatic float gettimerain()\n{\n static clock_t told=0;\n clock_t tnew,ris;\n\n tnew=clock();\n\n ris=tnew-told;\n\n told=tnew;\n\n return(ris\/(float)CLOCKS_PER_SEC);\n}\n\nstatic void calcposobs(void)\n{\n dir[0]=sin(alpha*M_PI\/180.0);\n dir[2]=cos(alpha*M_PI\/180.0)*sin(beta*M_PI\/180.0);\n dir[1]=cos(beta*M_PI\/180.0);\n\n obs[0]+=v*dir[0];\n obs[1]+=v*dir[1];\n obs[2]+=v*dir[2];\n\n rainParticle::setRainingArea(obs[0]-7.0f,-0.2f,obs[2]-7.0f,obs[0]+7.0f,8.0f,obs[2]+7.0f);\n}\n\nstatic void printstring(void *font, const char *string)\n{\n int len,i;\n\n len=(int)strlen(string);\n for(i=0;i<len;i++)\n glutBitmapCharacter(font,string[i]);\n}\n\nstatic void reshape(int width, int height)\n{\n WIDTH=width;\n HEIGHT=height;\n glViewport(0,0,(GLint)width,(GLint)height);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(70.0,width\/(float)height,0.1,30.0);\n\n glMatrixMode(GL_MODELVIEW);\n}\n\nstatic void printhelp(void)\n{\n glEnable(GL_BLEND);\n glColor4f(0.0,0.0,0.0,0.5);\n glRecti(40,40,600,440);\n glDisable(GL_BLEND);\n\n glColor3f(1.0,0.0,0.0);\n glRasterPos2i(300,420);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"Help\");\n\n glRasterPos2i(60,390);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"h - Toggle Help\");\n\n glRasterPos2i(60,360);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"f - Toggle Fog\");\n glRasterPos2i(60,330);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"Arrow Keys - Rotate\");\n glRasterPos2i(60,300);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"a - Increase velocity\");\n glRasterPos2i(60,270);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"z - Decrease velocity\");\n glRasterPos2i(60,240);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"l - Increase rain length\");\n glRasterPos2i(60,210);\n printstring(GLUT_BITMAP_TIMES_ROMAN_24,\"k - Decrease rain length\");\n}\n\nstatic void drawrain(void)\n{\n static int count=0;\n static char frbuf[80];\n float fr;\n\n glEnable(GL_DEPTH_TEST);\n\n if(fog)\n glEnable(GL_FOG);\n else\n glDisable(GL_FOG);\n\n glDepthMask(GL_TRUE);\n glClearColor(1.0,1.0,1.0,1.0);\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n glPushMatrix();\n calcposobs();\n gluLookAt(obs[0],obs[1],obs[2],\n\t obs[0]+dir[0],obs[1]+dir[1],obs[2]+dir[2],\n\t 0.0,1.0,0.0);\n\n glColor4f(1.0,1.0,1.0,1.0);\n\n glEnable(GL_TEXTURE_2D);\n\n glBindTexture(GL_TEXTURE_2D,groundid);\n glBegin(GL_QUADS);\n glTexCoord2fv(qt[0]);\n glVertex3fv(q[0]);\n glTexCoord2fv(qt[1]);\n glVertex3fv(q[1]);\n glTexCoord2fv(qt[2]);\n glVertex3fv(q[2]);\n glTexCoord2fv(qt[3]);\n glVertex3fv(q[3]);\n glEnd();\n\n \/\/ Particle System\n\n glDisable(GL_TEXTURE_2D);\n glShadeModel(GL_SMOOTH);\n glEnable(GL_BLEND);\n\n ps->draw();\n ps->addTime(gettimerain());\n \n glShadeModel(GL_FLAT);\n \n\n if((count % FRAME)==0) {\n fr=gettime();\n sprintf(frbuf,\"Frame rate: %f\",FRAME\/fr);\n }\n\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_FOG);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-0.5,639.5,-0.5,479.5,-1.0,1.0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glColor3f(1.0,0.0,0.0);\n glRasterPos2i(10,10);\n printstring(GLUT_BITMAP_HELVETICA_18,frbuf);\n glRasterPos2i(350,470);\n printstring(GLUT_BITMAP_HELVETICA_10,\"Rain V1.0 Written by David Bucciarelli (humanware@plus.it)\");\n\n if(help)\n printhelp();\n\n reshape(WIDTH,HEIGHT);\n glPopMatrix();\n\n glutSwapBuffers();\n\n count++;\n}\n\n\nstatic void special(int key, int x, int y)\n{\n switch (key) {\n case GLUT_KEY_LEFT:\n alpha+=2.0;\n break;\n case GLUT_KEY_RIGHT:\n alpha-=2.0;\n break;\n case GLUT_KEY_DOWN:\n beta-=2.0;\n break;\n case GLUT_KEY_UP:\n beta+=2.0;\n break;\n }\n}\n\nstatic void key(unsigned char key, int x, int y)\n{\n switch (key) {\n case 27:\n exit(0);\n break;\n\n case 'a':\n v+=0.01;\n break;\n case 'z':\n v-=0.01;\n break;\n\n case 'l':\n rainParticle::setLength(rainParticle::getLength()+0.025f);\n break;\n case 'k':\n rainParticle::setLength(rainParticle::getLength()-0.025f);\n break;\n\n case 'h':\n help=(!help);\n break;\n case 'f':\n fog=(!fog);\n break;\n#ifdef XMESA\n case ' ':\n XMesaSetFXmode(fullscreen ? XMESA_FX_FULLSCREEN : XMESA_FX_WINDOW);\n fullscreen=(!fullscreen);\n break;\n#endif\n }\n}\n\nstatic void inittextures(void)\n{\n GLubyte *img;\n GLint width,height;\n GLenum format;\n GLenum gluerr;\n\n glGenTextures(1,&groundid);\n glBindTexture(GL_TEXTURE_2D,groundid);\n\n if(!(img=LoadRGBImage(\"..\/images\/s128.rgb\",&width,&height,&format))){\n \tfprintf(stderr,\"Error reading a texture.\\n\");\n \texit(-1);\n }\n glPixelStorei(GL_UNPACK_ALIGNMENT,4);\n if((gluerr=(GLenum)gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height,GL_RGB,\n\t\t\t GL_UNSIGNED_BYTE, (GLvoid *)(img)))) {\n fprintf(stderr,\"GLULib%s\\n\",gluErrorString(gluerr));\n exit(-1);\n }\n\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);\n\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);\n\n glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_DECAL);\n}\n\nstatic void initparticle(void)\n{\n ps=new particleSystem;\n\n rainParticle::setRainingArea(-7.0f,-0.2f,-7.0f,7.0f,8.0f,7.0f);\n\n for(int i=0;i<NUMPART;i++) {\n rainParticle *p=new rainParticle;\n p->randomHeight();\n\n ps->addParticle((particle *)p);\n }\n}\n\nint main(int ac,char **av)\n{\n fprintf(stderr,\"Rain V1.0\\nWritten by David Bucciarelli (humanware@plus.it)\\n\");\n\n \/* Default settings *\/\n\n WIDTH=640;\n HEIGHT=480;\n\n glutInitWindowPosition(0,0);\n glutInitWindowSize(WIDTH,HEIGHT);\n glutInit(&ac,av);\n\n glutInitDisplayMode(GLUT_RGB|GLUT_DEPTH|GLUT_DOUBLE);\n\n if(!(win=glutCreateWindow(\"Rain\"))) {\n fprintf(stderr,\"Error opening a window.\\n\");\n exit(-1);\n }\n \n reshape(WIDTH,HEIGHT);\n\n inittextures();\n\n glShadeModel(GL_FLAT);\n glEnable(GL_DEPTH_TEST);\n\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n\n glEnable(GL_FOG);\n glFogi(GL_FOG_MODE,GL_EXP);\n glFogfv(GL_FOG_COLOR,fogcolor);\n glFogf(GL_FOG_DENSITY,0.1);\n#ifdef FX\n glHint(GL_FOG_HINT,GL_NICEST);\n#endif\n\n initparticle();\n\n glutKeyboardFunc(key);\n glutSpecialFunc(special);\n glutDisplayFunc(drawrain);\n glutIdleFunc(drawrain);\n glutReshapeFunc(reshape);\n glutMainLoop();\n\n return(0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: cupsmgr.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-09-08 15:51:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _PSPRINT_CUPSMGR_HXX_\n#define _PSPRINT_CUPSMGR_HXX_\n\n#include <psprint\/printerinfomanager.hxx>\n#include <osl\/module.h>\n#include <osl\/thread.h>\n#include <osl\/mutex.hxx>\n\nnamespace psp\n{\n\nclass CUPSWrapper;\nclass PPDParser;\n\nstruct FPtrHash\n{\n size_t operator()(const FILE* pPtr) const\n { return (size_t)pPtr; }\n};\n\nclass CUPSManager : public PrinterInfoManager\n{\n CUPSWrapper* m_pCUPSWrapper;\n std::hash_map< FILE*, rtl::OString, FPtrHash > m_aSpoolFiles;\n int m_nDests;\n void* m_pDests;\n bool m_bNewDests;\n std::hash_map< rtl::OUString, int, rtl::OUStringHash > m_aCUPSDestMap;\n\n std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts;\n\n rtl::OString m_aUser;\n \/\/ this is a security risk, but the CUPS API demands\n \/\/ to deliver a pointer to a static buffer containing\n \/\/ the password, so this cannot be helped\n rtl::OString m_aPassword;\n\n osl::Mutex m_aCUPSMutex;\n oslThread m_aDestThread;\n\n CUPSManager( CUPSWrapper* );\n virtual ~CUPSManager();\n\n virtual void initialize();\n\n void runDests();\n static void runDestThread(void* pMgr);\npublic:\n\n static CUPSManager* tryLoadCUPS();\n\n const PPDParser* createCUPSParser( const rtl::OUString& rPrinter );\n \/\/ wraps cupsGetPPD, so unlink after use !\n\n const char* authenticateUser( const char* );\n\n virtual FILE* startSpool( const rtl::OUString& rPrinterName );\n virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile );\n virtual void setupJobContextData( JobData& rData );\n\n \/\/ changes the info about a named printer\n virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo );\n\n \/\/ check if the printer configuration has changed\n virtual bool checkPrintersChanged();\n\n \/\/ members for administration (->padmin)\n \/\/ disable for CUPS\n virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName );\n virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false );\n virtual bool writePrinterConfig();\n virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName );\n};\n\n} \/\/ namespace psp\n\n#endif\n<commit_msg>INTEGRATION: CWS vcl28 (1.4.4); FILE MERGED 2004\/10\/07 16:31:25 pl 1.4.4.1: #i34799# make CUPSManager fall back to PrinterInfoManager as long as no dests are delivered<commit_after>\/*************************************************************************\n *\n * $RCSfile: cupsmgr.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2004-11-09 16:35:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _PSPRINT_CUPSMGR_HXX_\n#define _PSPRINT_CUPSMGR_HXX_\n\n#include <psprint\/printerinfomanager.hxx>\n#include <osl\/module.h>\n#include <osl\/thread.h>\n#include <osl\/mutex.hxx>\n\nnamespace psp\n{\n\nclass CUPSWrapper;\nclass PPDParser;\n\nstruct FPtrHash\n{\n size_t operator()(const FILE* pPtr) const\n { return (size_t)pPtr; }\n};\n\nclass CUPSManager : public PrinterInfoManager\n{\n CUPSWrapper* m_pCUPSWrapper;\n std::hash_map< FILE*, rtl::OString, FPtrHash > m_aSpoolFiles;\n int m_nDests;\n void* m_pDests;\n bool m_bNewDests;\n std::hash_map< rtl::OUString, int, rtl::OUStringHash > m_aCUPSDestMap;\n\n std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts;\n\n rtl::OString m_aUser;\n \/\/ this is a security risk, but the CUPS API demands\n \/\/ to deliver a pointer to a static buffer containing\n \/\/ the password, so this cannot be helped\n rtl::OString m_aPassword;\n\n osl::Mutex m_aCUPSMutex;\n oslThread m_aDestThread;\n\n CUPSManager( CUPSWrapper* );\n virtual ~CUPSManager();\n\n virtual void initialize();\n\n void runDests();\n static void runDestThread(void* pMgr);\npublic:\n\n static CUPSManager* tryLoadCUPS();\n\n const PPDParser* createCUPSParser( const rtl::OUString& rPrinter );\n \/\/ wraps cupsGetPPD, so unlink after use !\n\n const char* authenticateUser( const char* );\n\n virtual FILE* startSpool( const rtl::OUString& rPrinterName );\n virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile );\n virtual void setupJobContextData( JobData& rData );\n\n \/\/ changes the info about a named printer\n virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo );\n\n \/\/ check if the printer configuration has changed\n virtual bool checkPrintersChanged();\n\n \/\/ members for administration (->padmin)\n \/\/ disable for CUPS\n virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName );\n virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false );\n virtual bool writePrinterConfig();\n virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName );\n\n virtual bool addOrRemovePossible() const;\n};\n\n} \/\/ namespace psp\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <Internal\/FluidManagerImpl.hpp>\n#include <Internal\/PhysicsModuleImplementation.hpp>\nnamespace DoremiEngine\n{\n namespace Physics\n {\n FluidManagerImpl::FluidManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils) {}\n FluidManagerImpl::~FluidManagerImpl() {}\n\n void FluidManagerImpl::CreateFluid(int p_id)\n {\n float maxParticles = 100;\n bool perParticleRestOffset = false;\n\n \/\/ Create the particle systen\n PxParticleSystem* particleSystem = m_utils.m_physics->createParticleSystem(maxParticles, perParticleRestOffset);\n\n \/\/ Add particle system to the world\n if(particleSystem)\n {\n m_utils.m_worldScene->addActor(*particleSystem);\n }\n }\n void FluidManagerImpl::CreateFluidParticles(int p_id, vector<XMFLOAT3>& p_positions, vector<XMFLOAT3>& p_velocities, vector<int32_t>& p_indices)\n {\n \/\/ Cast XMFLOAT3s into something that PhysX likes. Possible since the data of the types are identical. Thanks, Bolt!\n PxVec3* positions = reinterpret_cast<PxVec3*>(&p_positions[0]);\n PxVec3* velocities = reinterpret_cast<PxVec3*>(&p_velocities[0]);\n PxU32* indices = reinterpret_cast<PxU32*>(&p_indices[0]);\n \/\/ Create the data for the particles\n PxParticleCreationData particleData;\n particleData.positionBuffer = PxStrideIterator<const PxVec3>(positions);\n particleData.velocityBuffer = PxStrideIterator<const PxVec3>(velocities);\n particleData.indexBuffer = PxStrideIterator<const PxU32>(indices);\n \/\/ Check that the data is valid\n if(particleData.isValid())\n {\n \/\/ Create the particles\n m_fluids[p_id]->createParticles(particleData);\n }\n else\n {\n \/\/ Shit went wrong! Handle somehow?\n }\n }\n\n vector<XMFLOAT3> FluidManagerImpl::GetParticlePositions(int p_id)\n {\n PxParticleFluidReadData* readData = m_fluids[p_id]->lockParticleFluidReadData();\n return vector<XMFLOAT3>();\n }\n }\n}<commit_msg>FluidManager: implementet method to get positions<commit_after>#include <Internal\/FluidManagerImpl.hpp>\n#include <Internal\/PhysicsModuleImplementation.hpp>\nnamespace DoremiEngine\n{\n namespace Physics\n {\n FluidManagerImpl::FluidManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils) {}\n FluidManagerImpl::~FluidManagerImpl() {}\n\n void FluidManagerImpl::CreateFluid(int p_id)\n {\n float maxParticles = 100;\n bool perParticleRestOffset = false;\n\n \/\/ Create the particle systen\n PxParticleSystem* particleSystem = m_utils.m_physics->createParticleSystem(maxParticles, perParticleRestOffset);\n\n \/\/ Add particle system to the world\n if(particleSystem)\n {\n m_utils.m_worldScene->addActor(*particleSystem);\n }\n }\n void FluidManagerImpl::CreateFluidParticles(int p_id, vector<XMFLOAT3>& p_positions, vector<XMFLOAT3>& p_velocities, vector<int32_t>& p_indices)\n {\n \/\/ Cast XMFLOAT3s into something that PhysX likes. Possible since the data of the types are identical. Thanks, Bolt!\n PxVec3* positions = reinterpret_cast<PxVec3*>(&p_positions[0]);\n PxVec3* velocities = reinterpret_cast<PxVec3*>(&p_velocities[0]);\n PxU32* indices = reinterpret_cast<PxU32*>(&p_indices[0]);\n \/\/ Create the data for the particles\n PxParticleCreationData particleData;\n particleData.positionBuffer = PxStrideIterator<const PxVec3>(positions);\n particleData.velocityBuffer = PxStrideIterator<const PxVec3>(velocities);\n particleData.indexBuffer = PxStrideIterator<const PxU32>(indices);\n \/\/ Check that the data is valid\n if(particleData.isValid())\n {\n \/\/ Create the particles\n m_fluids[p_id]->createParticles(particleData);\n }\n else\n {\n \/\/ Shit went wrong! Handle somehow?\n }\n }\n\n vector<XMFLOAT3> FluidManagerImpl::GetParticlePositions(int p_id)\n {\n PxParticleFluidReadData* readData = m_fluids[p_id]->lockParticleFluidReadData();\n PxStrideIterator<const PxVec3> positions = readData->positionBuffer;\n const XMFLOAT3* positionsXM = reinterpret_cast<const XMFLOAT3*>(positions.ptr());\n int numParticles = readData->nbValidParticles;\n vector<const XMFLOAT3> positionsXMVector;\n positionsXMVector.reserve(numParticles);\n positionsXMVector.data = positionsXMVector;\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/* \\brief Utility Functions for Transforming Data in accordance with BSZ Requirements\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <set>\n#include \"StlHelpers.h\"\n#include \"BSZTransform.h\"\n#include \"Downloader.h\"\n#include \"FileUtil.h\"\n#include \"MapUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"UrlUtil.h\"\n#include \"util.h\"\n\n\nnamespace BSZTransform {\n\n\nvoid LoadISSNToPPNMap(std::unordered_map<std::string, PPNandTitle> * const ISSN_to_superior_ppn_map) {\n enum ISSN_TO_PPN_OFFSET {ISSN_OFFSET = 0, PPN_OFFSET = 1, TITLE_OFFSET = 4};\n std::vector<std::vector<std::string>> parsed_issn_to_superior_content;\n TextUtil::ParseCSVFileOrDie(ISSN_TO_MISC_BITS_MAP_PATH_LOCAL, &parsed_issn_to_superior_content, ',', (char) 0x00);\n for (const auto parsed_line : parsed_issn_to_superior_content) {\n const std::string ISSN(parsed_line[ISSN_OFFSET]);\n const std::string PPN(parsed_line[PPN_OFFSET]);\n const std::string title(StringUtil::RightTrim(\" \\t\", parsed_line[TITLE_OFFSET]));\n ISSN_to_superior_ppn_map->emplace(ISSN, PPNandTitle(PPN, title));\n }\n}\n\n\nAugmentMaps::AugmentMaps(const std::string &map_directory_path) {\n MapUtil::DeserialiseMap(map_directory_path + \"language_to_language_code.map\", &language_to_language_code_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_language_code.map\", &ISSN_to_language_code_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_licence.map\", &ISSN_to_licence_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_keyword_field.map\", &ISSN_to_keyword_field_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_volume.map\", &ISSN_to_volume_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_SSG.map\", &ISSN_to_SSG_map_);\n LoadISSNToPPNMap(&ISSN_to_superior_ppn_and_title_map_);\n}\n\n\n\/\/ \"author\" must be in the lastname,firstname format. Returns the empty string if no PPN was found.\nstd::string DownloadAuthorPPN(const std::string &author, const std::string &author_lookup_base_url) {\n const std::string LOOKUP_URL(author_lookup_base_url + UrlUtil::UrlEncode(author));\n static std::unordered_map<std::string, std::string> url_to_lookup_result_cache;\n const auto url_and_lookup_result(url_to_lookup_result_cache.find(LOOKUP_URL));\n if (url_and_lookup_result == url_to_lookup_result_cache.end()) {\n static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(\"<SMALL>PPN<\/SMALL>.*<div><SMALL>([0-9X]+)\"));\n Downloader downloader(LOOKUP_URL);\n if (downloader.anErrorOccurred())\n LOG_WARNING(\"couldn't download author PPN! downloader error: \" + downloader.getLastErrorMessage());\n else if (matcher->matched(downloader.getMessageBody())) {\n url_to_lookup_result_cache.emplace(LOOKUP_URL, (*matcher)[1]);\n return (*matcher)[1];\n } else\n url_to_lookup_result_cache.emplace(LOOKUP_URL, \"\");\n } else\n return url_and_lookup_result->second;\n return \"\";\n}\n\n\nBSZTransform::BSZTransform(const std::string &map_directory_path): augment_maps_(AugmentMaps(map_directory_path)) {}\nBSZTransform::BSZTransform(const AugmentMaps &augment_maps): augment_maps_(augment_maps) {}\n\n\nvoid BSZTransform::DetermineKeywordOutputFieldFromISSN(const std::string &issn, std::string * const tag, char * const subfield) {\n if (not issn.empty()) {\n const auto issn_and_field_tag_and_subfield_code(augment_maps_.ISSN_to_keyword_field_map_.find(issn));\n if (issn_and_field_tag_and_subfield_code != augment_maps_.ISSN_to_keyword_field_map_.end()) {\n if (unlikely(issn_and_field_tag_and_subfield_code->second.length() != 3 + 1))\n LOG_ERROR(\"\\\"\" + issn_and_field_tag_and_subfield_code->second\n + \"\\\" is not a valid MARC tag + subfield code! (Error in \\\"ISSN_to_keyword_field.map\\\"!)\");\n *tag = issn_and_field_tag_and_subfield_code->second.substr(0, 3);\n *subfield = issn_and_field_tag_and_subfield_code->second[3];\n return;\n }\n }\n *tag = \"650\";\n *subfield = 'a';\n}\n\n\nvoid ParseAuthor(const std::string &author, std::string * const first_name, std::string * const last_name) {\n const auto normalised_author(TextUtil::CollapseAndTrimWhitespace(author));\n const auto name_separator(normalised_author.rfind(' '));\n if (name_separator != std::string::npos) {\n *first_name = normalised_author.substr(0, name_separator);\n *last_name = normalised_author.substr(name_separator + 1);\n } else {\n *first_name = normalised_author;\n last_name->clear();\n }\n}\n\n\nbool FilterEmptyAndCommentLines(std::string str) {\n StringUtil::TrimWhite(&str);\n return not str.empty() and str.front() != '#';\n}\n\n\nvoid StripBlacklistedTokensFromAuthorName(std::string * const first_name, std::string * const last_name) {\n static std::unique_ptr<RegexMatcher> matcher;\n if (matcher == nullptr) {\n std::unordered_set<std::string> blacklisted_tokens, filtered_blacklisted_tokens;\n auto string_data(FileUtil::ReadStringOrDie(AUTHOR_NAME_BLACKLIST));\n StringUtil::Split(string_data, '\\n', &blacklisted_tokens, \/* suppress_empty_components = *\/true);\n\n StlHelpers::Functional::Filter(blacklisted_tokens.begin(), blacklisted_tokens.end(), filtered_blacklisted_tokens,\n FilterEmptyAndCommentLines);\n\n std::string match_regex(\"\\\\b(\");\n for (auto blacklisted_token : filtered_blacklisted_tokens) {\n \/\/ escape backslashes first to keep from overwriting other escape sequences\n blacklisted_token = StringUtil::ReplaceString(\"\\\\\", \"\\\\\\\\\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\"(\", \"\\\\(\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\")\", \"\\\\)\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\".\", \"\\\\.\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\"\/\", \"\\\\\/\", blacklisted_token);\n\n match_regex += blacklisted_token + \"|\";\n }\n match_regex += \")\\\\b\";\n\n matcher.reset(RegexMatcher::RegexMatcherFactoryOrDie(match_regex, RegexMatcher::ENABLE_UTF8));\n }\n\n std::string first_name_buffer(matcher->replaceAll(*first_name, \"\")), last_name_buffer(matcher->replaceAll(*last_name, \"\"));\n StringUtil::TrimWhite(&first_name_buffer);\n StringUtil::TrimWhite(&last_name_buffer);\n\n *first_name = first_name_buffer;\n *last_name = last_name_buffer;\n}\n\n\nbool IsAuthorNameTokenTitle(std::string token) {\n static const std::unordered_set<std::string> VALID_TITLES {\n \"jr\", \"sr\", \"sj\", \"s.j\", \"fr\", \"hr\", \"dr\", \"prof\", \"em\"\n };\n\n bool final_period(token.back() == '.');\n if (final_period)\n token.erase(token.size() - 1);\n\n TextUtil::UTF8ToLower(&token);\n return VALID_TITLES.find(token) != VALID_TITLES.end();\n}\n\n\nbool IsAuthorNameTokenAffix(std::string token) {\n static const std::unordered_set<std::string> VALID_AFFIXES {\n \"i\", \"ii\", \"iii\", \"iv\", \"v\"\n };\n\n TextUtil::UTF8ToLower(&token);\n return VALID_AFFIXES.find(token) != VALID_AFFIXES.end();\n}\n\n\nvoid PostProcessAuthorName(std::string * const first_name, std::string * const last_name, std::string * const title,\n std::string * const affix)\n{\n std::string first_name_buffer, last_name_buffer, title_buffer, affix_buffer;\n std::vector<std::string> tokens;\n\n StringUtil::Split(*first_name, ' ', &tokens);\n for (const auto &token : tokens) {\n if (IsAuthorNameTokenTitle(token))\n title_buffer += token + \" \";\n else\n first_name_buffer += token + \" \";\n }\n\n StringUtil::Split(*last_name, ' ', &tokens);\n for (const auto &token : tokens) {\n if (IsAuthorNameTokenTitle(token))\n title_buffer += token + \" \";\n else if (IsAuthorNameTokenAffix(token))\n affix_buffer += token + \" \";\n else\n last_name_buffer += token + \" \";\n }\n\n TextUtil::CollapseAndTrimWhitespace(&first_name_buffer);\n TextUtil::CollapseAndTrimWhitespace(&last_name_buffer);\n TextUtil::CollapseAndTrimWhitespace(&title_buffer);\n TextUtil::CollapseAndTrimWhitespace(&affix_buffer);\n\n StripBlacklistedTokensFromAuthorName(&first_name_buffer, &last_name_buffer);\n\n *title = title_buffer;\n *affix = affix_buffer;\n \/\/ try to reparse the name if either part of the name is empty\n if (first_name_buffer.empty())\n ParseAuthor(last_name_buffer, first_name, last_name);\n else if (last_name_buffer.empty())\n ParseAuthor(first_name_buffer, first_name, last_name);\n else if (not first_name_buffer.empty() and not last_name_buffer.empty()) {\n *first_name = first_name_buffer;\n *last_name = last_name_buffer;\n }\n\n LOG_DEBUG(\"post-processed author first name = '\" + *first_name + \"', last name = '\" + *last_name +\n \"', title = '\" + *title + \"', affix = '\" + *affix + \"'\");\n}\n\n\n} \/\/ end namespace BSZTransform\n<commit_msg>Minor changes<commit_after>\/* \\brief Utility Functions for Transforming Data in accordance with BSZ Requirements\n * \\copyright 2018,2019 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <set>\n#include \"StlHelpers.h\"\n#include \"BSZTransform.h\"\n#include \"Downloader.h\"\n#include \"FileUtil.h\"\n#include \"MapUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"UrlUtil.h\"\n#include \"util.h\"\n\n\nnamespace BSZTransform {\n\n\nvoid LoadISSNToPPNMap(std::unordered_map<std::string, PPNandTitle> * const ISSN_to_superior_ppn_map) {\n enum ISSN_TO_PPN_OFFSET {ISSN_OFFSET = 0, PPN_OFFSET = 1, TITLE_OFFSET = 4};\n std::vector<std::vector<std::string>> parsed_issn_to_superior_content;\n TextUtil::ParseCSVFileOrDie(ISSN_TO_MISC_BITS_MAP_PATH_LOCAL, &parsed_issn_to_superior_content, ',', (char) 0x00);\n for (const auto parsed_line : parsed_issn_to_superior_content) {\n const std::string ISSN(parsed_line[ISSN_OFFSET]);\n const std::string PPN(parsed_line[PPN_OFFSET]);\n const std::string title(StringUtil::RightTrim(\" \\t\", parsed_line[TITLE_OFFSET]));\n ISSN_to_superior_ppn_map->emplace(ISSN, PPNandTitle(PPN, title));\n }\n}\n\n\nAugmentMaps::AugmentMaps(const std::string &map_directory_path) {\n MapUtil::DeserialiseMap(map_directory_path + \"language_to_language_code.map\", &language_to_language_code_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_language_code.map\", &ISSN_to_language_code_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_licence.map\", &ISSN_to_licence_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_keyword_field.map\", &ISSN_to_keyword_field_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_volume.map\", &ISSN_to_volume_map_);\n MapUtil::DeserialiseMap(map_directory_path + \"ISSN_to_SSG.map\", &ISSN_to_SSG_map_);\n LoadISSNToPPNMap(&ISSN_to_superior_ppn_and_title_map_);\n}\n\n\n\/\/ \"author\" must be in the lastname,firstname format. Returns the empty string if no PPN was found.\nstd::string DownloadAuthorPPN(const std::string &author, const std::string &author_lookup_base_url) {\n const std::string LOOKUP_URL(author_lookup_base_url + UrlUtil::UrlEncode(author));\n static std::unordered_map<std::string, std::string> url_to_lookup_result_cache;\n const auto url_and_lookup_result(url_to_lookup_result_cache.find(LOOKUP_URL));\n if (url_and_lookup_result == url_to_lookup_result_cache.end()) {\n static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(\"<SMALL>PPN<\/SMALL>.*<div><SMALL>([0-9X]+)\"));\n Downloader downloader(LOOKUP_URL);\n if (downloader.anErrorOccurred())\n LOG_WARNING(\"couldn't download author PPN! downloader error: \" + downloader.getLastErrorMessage());\n else if (matcher->matched(downloader.getMessageBody())) {\n url_to_lookup_result_cache.emplace(LOOKUP_URL, (*matcher)[1]);\n return (*matcher)[1];\n } else\n url_to_lookup_result_cache.emplace(LOOKUP_URL, \"\");\n } else\n return url_and_lookup_result->second;\n return \"\";\n}\n\n\nBSZTransform::BSZTransform(const std::string &map_directory_path): augment_maps_(AugmentMaps(map_directory_path)) {}\nBSZTransform::BSZTransform(const AugmentMaps &augment_maps): augment_maps_(augment_maps) {}\n\n\nvoid BSZTransform::DetermineKeywordOutputFieldFromISSN(const std::string &issn, std::string * const tag, char * const subfield) {\n if (not issn.empty()) {\n const auto issn_and_field_tag_and_subfield_code(augment_maps_.ISSN_to_keyword_field_map_.find(issn));\n if (issn_and_field_tag_and_subfield_code != augment_maps_.ISSN_to_keyword_field_map_.end()) {\n if (unlikely(issn_and_field_tag_and_subfield_code->second.length() != 3 + 1))\n LOG_ERROR(\"\\\"\" + issn_and_field_tag_and_subfield_code->second\n + \"\\\" is not a valid MARC tag + subfield code! (Error in \\\"ISSN_to_keyword_field.map\\\"!)\");\n *tag = issn_and_field_tag_and_subfield_code->second.substr(0, 3);\n *subfield = issn_and_field_tag_and_subfield_code->second[3];\n return;\n }\n }\n *tag = \"650\";\n *subfield = 'a';\n}\n\n\nvoid ParseAuthor(const std::string &author, std::string * const first_name, std::string * const last_name) {\n const auto normalised_author(TextUtil::CollapseAndTrimWhitespace(author));\n const auto name_separator(normalised_author.rfind(' '));\n if (name_separator != std::string::npos) {\n *first_name = normalised_author.substr(0, name_separator);\n *last_name = normalised_author.substr(name_separator + 1);\n } else {\n *first_name = normalised_author;\n last_name->clear();\n }\n}\n\n\nbool FilterEmptyAndCommentLines(std::string str) {\n StringUtil::TrimWhite(&str);\n return not str.empty() and str.front() != '#';\n}\n\n\nvoid StripBlacklistedTokensFromAuthorName(std::string * const first_name, std::string * const last_name) {\n static std::unique_ptr<RegexMatcher> matcher;\n if (matcher == nullptr) {\n std::unordered_set<std::string> blacklisted_tokens, filtered_blacklisted_tokens;\n auto string_data(FileUtil::ReadStringOrDie(AUTHOR_NAME_BLACKLIST));\n StringUtil::Split(string_data, '\\n', &blacklisted_tokens, \/* suppress_empty_components = *\/true);\n\n StlHelpers::Functional::Filter(blacklisted_tokens.begin(), blacklisted_tokens.end(), filtered_blacklisted_tokens,\n FilterEmptyAndCommentLines);\n\n std::string match_regex(\"\\\\b(\");\n for (auto blacklisted_token : filtered_blacklisted_tokens) {\n \/\/ escape backslashes first to keep from overwriting other escape sequences\n blacklisted_token = StringUtil::ReplaceString(\"\\\\\", \"\\\\\\\\\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\"(\", \"\\\\(\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\")\", \"\\\\)\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\".\", \"\\\\.\", blacklisted_token);\n blacklisted_token = StringUtil::ReplaceString(\"\/\", \"\\\\\/\", blacklisted_token);\n\n match_regex += blacklisted_token + \"|\";\n }\n match_regex += \")\\\\b\";\n\n matcher.reset(RegexMatcher::RegexMatcherFactoryOrDie(match_regex, RegexMatcher::ENABLE_UTF8));\n }\n\n std::string first_name_buffer(matcher->replaceAll(*first_name, \"\")), last_name_buffer(matcher->replaceAll(*last_name, \"\"));\n StringUtil::TrimWhite(&first_name_buffer);\n StringUtil::TrimWhite(&last_name_buffer);\n\n *first_name = first_name_buffer;\n *last_name = last_name_buffer;\n}\n\n\nbool IsAuthorNameTokenTitle(std::string token) {\n static const std::set<std::string> VALID_TITLES {\n \"jr\", \"sr\", \"sj\", \"s.j\", \"fr\", \"hr\", \"dr\", \"prof\", \"em\"\n };\n\n bool final_period(token.back() == '.');\n if (final_period)\n token.erase(token.size() - 1);\n\n TextUtil::UTF8ToLower(&token);\n return VALID_TITLES.find(token) != VALID_TITLES.end();\n}\n\n\nbool IsAuthorNameTokenAffix(std::string token) {\n static const std::set<std::string> VALID_AFFIXES {\n \"i\", \"ii\", \"iii\", \"iv\", \"v\"\n };\n\n TextUtil::UTF8ToLower(&token);\n return VALID_AFFIXES.find(token) != VALID_AFFIXES.end();\n}\n\n\nvoid PostProcessAuthorName(std::string * const first_name, std::string * const last_name, std::string * const title,\n std::string * const affix)\n{\n std::string first_name_buffer, last_name_buffer, title_buffer, affix_buffer;\n std::vector<std::string> tokens;\n\n StringUtil::Split(*first_name, ' ', &tokens);\n for (const auto &token : tokens) {\n if (IsAuthorNameTokenTitle(token))\n title_buffer += token + \" \";\n else\n first_name_buffer += token + \" \";\n }\n\n StringUtil::Split(*last_name, ' ', &tokens);\n for (const auto &token : tokens) {\n if (IsAuthorNameTokenTitle(token))\n title_buffer += token + \" \";\n else if (IsAuthorNameTokenAffix(token))\n affix_buffer += token + \" \";\n else\n last_name_buffer += token + \" \";\n }\n\n TextUtil::CollapseAndTrimWhitespace(&first_name_buffer);\n TextUtil::CollapseAndTrimWhitespace(&last_name_buffer);\n TextUtil::CollapseAndTrimWhitespace(&title_buffer);\n TextUtil::CollapseAndTrimWhitespace(&affix_buffer);\n\n StripBlacklistedTokensFromAuthorName(&first_name_buffer, &last_name_buffer);\n\n *title = title_buffer;\n *affix = affix_buffer;\n \/\/ try to reparse the name if either part of the name is empty\n if (first_name_buffer.empty())\n ParseAuthor(last_name_buffer, first_name, last_name);\n else if (last_name_buffer.empty())\n ParseAuthor(first_name_buffer, first_name, last_name);\n else if (not first_name_buffer.empty() and not last_name_buffer.empty()) {\n *first_name = first_name_buffer;\n *last_name = last_name_buffer;\n }\n\n LOG_DEBUG(\"post-processed author first name = '\" + *first_name + \"', last name = '\" + *last_name +\n \"', title = '\" + *title + \"', affix = '\" + *affix + \"'\");\n}\n\n\n} \/\/ end namespace BSZTransform\n<|endoftext|>"} {"text":"<commit_before>\/** \\file RegexMatcher.cc\n * \\brief Implementation of the RegexMatcher class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015,2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"RegexMatcher.h\"\n#include \"Compiler.h\"\n#include \"util.h\"\n\n\nbool RegexMatcher::utf8_configured_;\n\n\nbool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg,\n ::pcre_extra **pcre_extra_arg, std::string * const err_msg)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const char *errptr;\n int erroffset;\n\n int pcre_options(0);\n if (options & RegexMatcher::ENABLE_UTF8)\n pcre_options |= PCRE_UTF8;\n if (options & RegexMatcher::CASE_INSENSITIVE)\n pcre_options |= PCRE_CASELESS;\n\n *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr);\n if (*pcre_arg == nullptr) {\n *pcre_extra_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to compile invalid regular expression: \\\"\" + pattern + \"\\\"! (\"\n + std::string(errptr) + \")\";\n return false;\n }\n\n \/\/ Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe.\n *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr);\n if (*pcre_extra_arg == nullptr and errptr != nullptr) {\n ::pcre_free(*pcre_arg);\n *pcre_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to \\\"study\\\" the compiled pattern \\\"\" + pattern + \"\\\"! (\" + std::string(errptr) + \")\";\n return false;\n }\n\n return true;\n}\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg,\n const unsigned options)\n{\n \/\/ Make sure the PCRE library supports UTF8:\n if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) {\n int utf8_available;\n if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) {\n if (err_msg != nullptr)\n *err_msg = \"PCRE library does not know PCRE_CONFIG_UTF8!\";\n return nullptr;\n }\n\n if (utf8_available != 1) {\n if (err_msg != nullptr)\n *err_msg = \"This version of the PCRE library does not support UTF8!\";\n return nullptr;\n }\n\n RegexMatcher::utf8_configured_ = true;\n }\n\n ::pcre *pcre_ptr;\n ::pcre_extra *pcre_extra_ptr;\n if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg))\n return nullptr;\n\n return new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr);\n}\n\n\nRegexMatcher *RegexMatcher::FactoryOrDie(const std::string ®ex, const unsigned options) {\n std::string error_message;\n RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options));\n if (not error_message.empty())\n ERROR(\"failed to compile regex \\\"\" + regex + \"\\\": \" + error_message);\n\n return regex_matcher;\n}\n\n\nRegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) {\n if (this == &that)\n return;\n\n if (that.pcre_ == nullptr) {\n pcre_ = nullptr;\n pcre_extra_ = nullptr;\n } else {\n std::string err_msg;\n if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg))\n logger->error(\"In RegexMatcher copy constructor: unexpected error: \" + err_msg);\n substr_vector_ = that.substr_vector_;\n last_match_count_ = that.last_match_count_;\n }\n}\n\n\nRegexMatcher::RegexMatcher(RegexMatcher &&that)\n : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_),\n pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)),\n substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_)\n{\n that.pcre_ = nullptr;\n that.pcre_extra_ = nullptr;\n}\n\n\nbool RegexMatcher::matched(const std::string &subject, std::string * const err_msg,\n size_t * const start_pos, size_t * const end_pos)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const int retcode = ::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), 0, 0,\n &substr_vector_[0], substr_vector_.size());\n\n if (retcode == 0) {\n if (err_msg != nullptr)\n *err_msg = \"Too many captured substrings! (We only support \"\n + std::to_string(substr_vector_.size() \/ 3 - 1) + \" substrings.)\";\n return false;\n }\n\n if (retcode > 0) {\n last_match_count_ = retcode;\n last_subject_ = subject;\n if (start_pos != nullptr)\n *start_pos = substr_vector_[0];\n if (end_pos != nullptr)\n *end_pos = substr_vector_[1];\n return true;\n }\n\n if (retcode != PCRE_ERROR_NOMATCH) {\n if (retcode == PCRE_ERROR_BADUTF8) {\n if (err_msg != nullptr)\n *err_msg = \"A \\\"subject\\\" with invalid UTF-8 was passed into RegexMatcher::matched()!\";\n } else if (err_msg != nullptr)\n *err_msg = \"Unknown error!\";\n }\n\n return false;\n}\n\n\nstd::string RegexMatcher::operator[](const unsigned group) const {\n if (unlikely(group >= last_match_count_))\n throw std::out_of_range(\"in RegexMatcher::operator[]: group(\" + std::to_string(group) + \") >= \"\n + std::to_string(last_match_count_) + \"!\");\n\n const unsigned first_index(group * 2);\n const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]);\n return (substring_length == 0) ? \"\" : last_subject_.substr(substr_vector_[first_index], substring_length);\n}\n<commit_msg>Update RegexMatcher.cc<commit_after>\/** \\file RegexMatcher.cc\n * \\brief Implementation of the RegexMatcher class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015,2017,2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"RegexMatcher.h\"\n#include \"Compiler.h\"\n#include \"util.h\"\n\n\nbool RegexMatcher::utf8_configured_;\n\n\nbool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg,\n ::pcre_extra **pcre_extra_arg, std::string * const err_msg)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const char *errptr;\n int erroffset;\n\n int pcre_options(0);\n if (options & RegexMatcher::ENABLE_UTF8)\n pcre_options |= PCRE_UTF8;\n if (options & RegexMatcher::CASE_INSENSITIVE)\n pcre_options |= PCRE_CASELESS;\n\n *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr);\n if (*pcre_arg == nullptr) {\n *pcre_extra_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to compile invalid regular expression: \\\"\" + pattern + \"\\\"! (\"\n + std::string(errptr) + \")\";\n return false;\n }\n\n \/\/ Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe.\n *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr);\n if (*pcre_extra_arg == nullptr and errptr != nullptr) {\n ::pcre_free(*pcre_arg);\n *pcre_arg = nullptr;\n if (err_msg != nullptr)\n *err_msg = \"failed to \\\"study\\\" the compiled pattern \\\"\" + pattern + \"\\\"! (\" + std::string(errptr) + \")\";\n return false;\n }\n\n return true;\n}\n\n\nRegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg,\n const unsigned options)\n{\n \/\/ Make sure the PCRE library supports UTF8:\n if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) {\n int utf8_available;\n if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) {\n if (err_msg != nullptr)\n *err_msg = \"PCRE library does not know PCRE_CONFIG_UTF8!\";\n return nullptr;\n }\n\n if (utf8_available != 1) {\n if (err_msg != nullptr)\n *err_msg = \"This version of the PCRE library does not support UTF8!\";\n return nullptr;\n }\n\n RegexMatcher::utf8_configured_ = true;\n }\n\n ::pcre *pcre_ptr;\n ::pcre_extra *pcre_extra_ptr;\n if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg))\n return nullptr;\n\n return new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr);\n}\n\n\nRegexMatcher *RegexMatcher::FactoryOrDie(const std::string ®ex, const unsigned options) {\n std::string error_message;\n RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options));\n if (not error_message.empty())\n ERROR(\"failed to compile regex \\\"\" + regex + \"\\\": \" + error_message);\n\n return regex_matcher;\n}\n\n\nRegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) {\n if (this == &that)\n return;\n\n if (that.pcre_ == nullptr) {\n pcre_ = nullptr;\n pcre_extra_ = nullptr;\n } else {\n std::string err_msg;\n if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg))\n logger->error(\"In RegexMatcher copy constructor: unexpected error: \" + err_msg);\n substr_vector_ = that.substr_vector_;\n last_match_count_ = that.last_match_count_;\n }\n}\n\n\nRegexMatcher::RegexMatcher(RegexMatcher &&that)\n : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_),\n pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)),\n substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_)\n{\n that.pcre_ = nullptr;\n that.pcre_extra_ = nullptr;\n}\n\n\nbool RegexMatcher::matched(const std::string &subject, std::string * const err_msg,\n size_t * const start_pos, size_t * const end_pos)\n{\n if (err_msg != nullptr)\n err_msg->clear();\n\n const int retcode = ::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), 0, 0,\n &substr_vector_[0], substr_vector_.size());\n\n if (retcode == 0) {\n if (err_msg != nullptr)\n *err_msg = \"Too many captured substrings! (We only support \"\n + std::to_string(substr_vector_.size() \/ 3 - 1) + \" substrings.)\";\n return false;\n }\n\n if (retcode > 0) {\n last_match_count_ = retcode;\n last_subject_ = subject;\n if (start_pos != nullptr)\n *start_pos = substr_vector_[0];\n if (end_pos != nullptr)\n *end_pos = substr_vector_[1];\n return true;\n }\n\n if (retcode != PCRE_ERROR_NOMATCH) {\n if (retcode == PCRE_ERROR_BADUTF8) {\n if (err_msg != nullptr)\n *err_msg = \"A \\\"subject\\\" with invalid UTF-8 was passed into RegexMatcher::matched()!\";\n } else if (err_msg != nullptr)\n *err_msg = \"Unknown error!\";\n }\n\n return false;\n}\n\n\nstd::string RegexMatcher::operator[](const unsigned group) const {\n if (unlikely(group >= last_match_count_))\n throw std::out_of_range(\"in RegexMatcher::operator[]: group(\" + std::to_string(group) + \") >= \"\n + std::to_string(last_match_count_) + \"!\");\n\n const unsigned first_index(group * 2);\n const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]);\n return (substring_length == 0) ? \"\" : last_subject_.substr(substr_vector_[first_index], substring_length);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Modified by Cloudius Systems\n *\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"function.hh\"\n#include \"aggregate_fcts.hh\"\n#include \"time_uuid_fcts.hh\"\n#include \"uuid_fcts.hh\"\n#include \"bytes_conversion_fcts.hh\"\n#include \"aggregate_fcts.hh\"\n#include \"bytes_conversion_fcts.hh\"\n#include \"cql3\/assignment_testable.hh\"\n#include \"cql3\/cql3_type.hh\"\n#include \"cql3\/column_identifier.hh\"\n#include \"to_string.hh\"\n#include <unordered_map>\n#include <boost\/lexical_cast.hpp>\n\nnamespace cql3 {\n\nnamespace functions {\n\n#if 0\n \/\/ We special case the token function because that's the only function whose argument types actually\n \/\/ depend on the table on which the function is called. Because it's the sole exception, it's easier\n \/\/ to handle it as a special case.\n private static final FunctionName TOKEN_FUNCTION_NAME = FunctionName.nativeFunction(\"token\");\n#endif\n\nclass functions {\n static thread_local std::unordered_multimap<function_name, shared_ptr<function>> _declared;\nprivate:\n static std::unordered_multimap<function_name, shared_ptr<function>> init() {\n std::unordered_multimap<function_name, shared_ptr<function>> ret;\n auto declare = [&ret] (shared_ptr<function> f) { ret.emplace(f->name(), std::move(f)); };\n declare(aggregate_fcts::make_count_rows_function());\n declare(time_uuid_fcts::make_now_fct());\n declare(time_uuid_fcts::make_min_timeuuid_fct());\n declare(time_uuid_fcts::make_max_timeuuid_fct());\n declare(time_uuid_fcts::make_date_of_fct());\n declare(time_uuid_fcts::make_unix_timestamp_of_fcf());\n declare(make_uuid_fct());\n\n for (auto&& type : cql3_type::values()) {\n \/\/ Note: because text and varchar ends up being synonimous, our automatic makeToBlobFunction doesn't work\n \/\/ for varchar, so we special case it below. We also skip blob for obvious reasons.\n if (type == cql3_type::varchar || type == cql3_type::blob) {\n continue;\n }\n\n declare(make_to_blob_function(type->get_type()));\n declare(make_from_blob_function(type->get_type()));\n }\n declare(aggregate_fcts::make_count_function<int32_t>());\n declare(aggregate_fcts::make_max_function<int32_t>());\n declare(aggregate_fcts::make_min_function<int32_t>());\n\n declare(aggregate_fcts::make_count_function<int64_t>());\n declare(aggregate_fcts::make_max_function<int64_t>());\n declare(aggregate_fcts::make_min_function<int64_t>());\n\n \/\/FIXME:\n \/\/declare(aggregate_fcts::make_count_function<bytes>());\n \/\/declare(aggregate_fcts::make_max_function<bytes>());\n \/\/declare(aggregate_fcts::make_min_function<bytes>());\n\n \/\/ FIXME: more count\/min\/max\n\n declare(make_varchar_as_blob_fct());\n declare(make_blob_as_varchar_fct());\n declare(aggregate_fcts::make_sum_function<int32_t>());\n declare(aggregate_fcts::make_sum_function<int64_t>());\n declare(aggregate_fcts::make_avg_function<int32_t>());\n declare(aggregate_fcts::make_avg_function<int64_t>());\n#if 0\n declare(AggregateFcts.sumFunctionForFloat);\n declare(AggregateFcts.sumFunctionForDouble);\n declare(AggregateFcts.sumFunctionForDecimal);\n declare(AggregateFcts.sumFunctionForVarint);\n declare(AggregateFcts.avgFunctionForFloat);\n declare(AggregateFcts.avgFunctionForDouble);\n declare(AggregateFcts.avgFunctionForVarint);\n declare(AggregateFcts.avgFunctionForDecimal);\n#endif\n\n \/\/ also needed for smp:\n#if 0\n MigrationManager.instance.register(new FunctionsMigrationListener());\n#endif\n return ret;\n }\n\npublic:\n static shared_ptr<column_specification> make_arg_spec(const sstring& receiver_ks, const sstring& receiver_cf,\n const function& fun, size_t i) {\n auto&& name = boost::lexical_cast<std::string>(fun.name());\n std::transform(name.begin(), name.end(), name.begin(), ::tolower);\n return ::make_shared<column_specification>(receiver_ks,\n receiver_cf,\n ::make_shared<column_identifier>(sprint(\"arg%d(%s)\", i, name), true),\n fun.arg_types()[i]);\n }\n\n static int get_overload_count(const function_name& name) {\n return _declared.count(name);\n }\n\npublic:\n static shared_ptr<function> get(const sstring& keyspace,\n const function_name& name,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n \/\/ FIXME:\n#if 0\n \/\/ later\n if (name.has_keyspace()\n ? name.equals(TOKEN_FUNCTION_NAME)\n : name.name.equals(TOKEN_FUNCTION_NAME.name))\n return new TokenFct(Schema.instance.getCFMetaData(receiverKs, receiverCf));\n#endif\n std::vector<shared_ptr<function>> candidates;\n auto&& add_declared = [&] (function_name fn) {\n auto&& fns = _declared.equal_range(fn);\n for (auto i = fns.first; i != fns.second; ++i) {\n candidates.push_back(i->second);\n }\n };\n if (!name.has_keyspace()) {\n \/\/ add 'SYSTEM' (native) candidates\n add_declared(name.as_native_function());\n add_declared(function_name(keyspace, name.name));\n } else {\n \/\/ function name is fully qualified (keyspace + name)\n add_declared(name);\n }\n\n if (candidates.empty()) {\n return {};\n }\n\n \/\/ Fast path if there is only one choice\n if (candidates.size() == 1) {\n auto fun = std::move(candidates[0]);\n validate_types(keyspace, fun, provided_args, receiver_ks, receiver_cf);\n return fun;\n }\n\n std::vector<shared_ptr<function>> compatibles;\n for (auto&& to_test : candidates) {\n auto r = match_arguments(keyspace, to_test, provided_args, receiver_ks, receiver_cf);\n switch (r) {\n case assignment_testable::test_result::EXACT_MATCH:\n \/\/ We always favor exact matches\n return to_test;\n case assignment_testable::test_result::WEAKLY_ASSIGNABLE:\n compatibles.push_back(std::move(to_test));\n break;\n default:\n ;\n };\n }\n\n if (compatibles.empty()) {\n throw exceptions::invalid_request_exception(\n sprint(\"Invalid call to function %s, none of its type signatures match (known type signatures: %s)\",\n name, join(\", \", candidates)));\n }\n\n if (compatibles.size() > 1) {\n throw exceptions::invalid_request_exception(\n sprint(\"Ambiguous call to function %s (can be matched by following signatures: %s): use type casts to disambiguate\",\n name, join(\", \", compatibles)));\n }\n\n return std::move(compatibles[0]);\n }\n\n template <typename AssignmentTestablePtrRange>\n static shared_ptr<function> get(const sstring& keyspace,\n const function_name& name,\n AssignmentTestablePtrRange&& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n const std::vector<shared_ptr<assignment_testable>> args(std::begin(provided_args), std::end(provided_args));\n return get(keyspace, name, args, receiver_ks, receiver_cf);\n }\n\n static std::vector<shared_ptr<function>> find(const function_name& name) {\n auto range = _declared.equal_range(name);\n std::vector<shared_ptr<function>> ret;\n for (auto i = range.first; i != range.second; ++i) {\n ret.push_back(i->second);\n }\n return ret;\n }\n\n static shared_ptr<function> find(const function_name& name, const std::vector<data_type>& arg_types) {\n assert(name.has_keyspace()); \/\/ : \"function name not fully qualified\";\n for (auto&& f : find(name)) {\n if (type_equals(f->arg_types(), arg_types)) {\n return f;\n }\n }\n return {};\n }\n\nprivate:\n \/\/ This method and matchArguments are somewhat duplicate, but this method allows us to provide more precise errors in the common\n \/\/ case where there is no override for a given function. This is thus probably worth the minor code duplication.\n static void validate_types(const sstring& keyspace,\n shared_ptr<function> fun,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n if (provided_args.size() != fun->arg_types().size()) {\n throw exceptions::invalid_request_exception(\n sprint(\"Invalid number of arguments in call to function %s: %d required but %d provided\",\n fun->name(), fun->arg_types().size(), provided_args.size()));\n }\n\n for (size_t i = 0; i < provided_args.size(); ++i) {\n auto&& provided = provided_args[i];\n\n \/\/ If the concrete argument is a bind variables, it can have any type.\n \/\/ We'll validate the actually provided value at execution time.\n if (!provided) {\n continue;\n }\n\n auto&& expected = make_arg_spec(receiver_ks, receiver_cf, *fun, i);\n if (!is_assignable(provided->test_assignment(keyspace, expected))) {\n throw exceptions::invalid_request_exception(\n sprint(\"Type error: %s cannot be passed as argument %d of function %s of type %s\",\n provided, i, fun->name(), expected->type->as_cql3_type()));\n }\n }\n }\n\n static assignment_testable::test_result match_arguments(const sstring& keyspace,\n shared_ptr<function> fun,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n if (provided_args.size() != fun->arg_types().size()) {\n return assignment_testable::test_result::NOT_ASSIGNABLE;\n }\n\n \/\/ It's an exact match if all are exact match, but is not assignable as soon as any is non assignable.\n auto res = assignment_testable::test_result::EXACT_MATCH;\n for (size_t i = 0; i < provided_args.size(); ++i) {\n auto&& provided = provided_args[i];\n if (!provided) {\n res = assignment_testable::test_result::WEAKLY_ASSIGNABLE;\n continue;\n }\n auto&& expected = make_arg_spec(receiver_ks, receiver_cf, *fun, i);\n auto arg_res = provided->test_assignment(keyspace, expected);\n if (arg_res == assignment_testable::test_result::NOT_ASSIGNABLE) {\n return assignment_testable::test_result::NOT_ASSIGNABLE;\n }\n if (arg_res == assignment_testable::test_result::WEAKLY_ASSIGNABLE) {\n res = assignment_testable::test_result::WEAKLY_ASSIGNABLE;\n }\n }\n return res;\n }\n\n#if 0\n \/\/ This is *not* thread safe but is only called in SchemaTables that is synchronized.\n public static void addFunction(AbstractFunction fun)\n {\n \/\/ We shouldn't get there unless that function don't exist\n assert find(fun.name(), fun.argTypes()) == null;\n declare(fun);\n }\n\n \/\/ Same remarks than for addFunction\n public static void removeFunction(FunctionName name, List<AbstractType<?>> argsTypes)\n {\n Function old = find(name, argsTypes);\n assert old != null && !old.isNative();\n declared.remove(old.name(), old);\n }\n\n \/\/ Same remarks than for addFunction\n public static void replaceFunction(AbstractFunction fun)\n {\n removeFunction(fun.name(), fun.argTypes());\n addFunction(fun);\n }\n\n public static List<Function> getReferencesTo(Function old)\n {\n List<Function> references = new ArrayList<>();\n for (Function function : declared.values())\n if (function.hasReferenceTo(old))\n references.add(function);\n return references;\n }\n\n public static Collection<Function> all()\n {\n return declared.values();\n }\n\n public static boolean typeEquals(AbstractType<?> t1, AbstractType<?> t2)\n {\n return t1.asCQL3Type().toString().equals(t2.asCQL3Type().toString());\n }\n\n#endif\n\n static bool type_equals(const std::vector<data_type>& t1, const std::vector<data_type>& t2) {\n#if 0\n if (t1.size() != t2.size())\n return false;\n for (int i = 0; i < t1.size(); i ++)\n if (!typeEquals(t1.get(i), t2.get(i)))\n return false;\n return true;\n#endif\n abort();\n }\n\n#if 0\n private static class FunctionsMigrationListener implements IMigrationListener\n {\n public void onCreateKeyspace(String ksName) { }\n public void onCreateColumnFamily(String ksName, String cfName) { }\n public void onCreateUserType(String ksName, String typeName) { }\n public void onCreateFunction(String ksName, String functionName) { }\n public void onCreateAggregate(String ksName, String aggregateName) { }\n\n public void onUpdateKeyspace(String ksName) { }\n public void onUpdateColumnFamily(String ksName, String cfName) { }\n public void onUpdateUserType(String ksName, String typeName) {\n for (Function function : all())\n if (function instanceof UDFunction)\n ((UDFunction)function).userTypeUpdated(ksName, typeName);\n }\n public void onUpdateFunction(String ksName, String functionName) { }\n public void onUpdateAggregate(String ksName, String aggregateName) { }\n\n public void onDropKeyspace(String ksName) { }\n public void onDropColumnFamily(String ksName, String cfName) { }\n public void onDropUserType(String ksName, String typeName) { }\n public void onDropFunction(String ksName, String functionName) { }\n public void onDropAggregate(String ksName, String aggregateName) { }\n }\n#endif\n};\n\n}\n}\n<commit_msg>cql3: fix too eager move in functions.hh<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Modified by Cloudius Systems\n *\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"function.hh\"\n#include \"aggregate_fcts.hh\"\n#include \"time_uuid_fcts.hh\"\n#include \"uuid_fcts.hh\"\n#include \"bytes_conversion_fcts.hh\"\n#include \"aggregate_fcts.hh\"\n#include \"bytes_conversion_fcts.hh\"\n#include \"cql3\/assignment_testable.hh\"\n#include \"cql3\/cql3_type.hh\"\n#include \"cql3\/column_identifier.hh\"\n#include \"to_string.hh\"\n#include <unordered_map>\n#include <boost\/lexical_cast.hpp>\n\nnamespace cql3 {\n\nnamespace functions {\n\n#if 0\n \/\/ We special case the token function because that's the only function whose argument types actually\n \/\/ depend on the table on which the function is called. Because it's the sole exception, it's easier\n \/\/ to handle it as a special case.\n private static final FunctionName TOKEN_FUNCTION_NAME = FunctionName.nativeFunction(\"token\");\n#endif\n\nclass functions {\n static thread_local std::unordered_multimap<function_name, shared_ptr<function>> _declared;\nprivate:\n static std::unordered_multimap<function_name, shared_ptr<function>> init() {\n std::unordered_multimap<function_name, shared_ptr<function>> ret;\n auto declare = [&ret] (shared_ptr<function> f) { ret.emplace(f->name(), f); };\n declare(aggregate_fcts::make_count_rows_function());\n declare(time_uuid_fcts::make_now_fct());\n declare(time_uuid_fcts::make_min_timeuuid_fct());\n declare(time_uuid_fcts::make_max_timeuuid_fct());\n declare(time_uuid_fcts::make_date_of_fct());\n declare(time_uuid_fcts::make_unix_timestamp_of_fcf());\n declare(make_uuid_fct());\n\n for (auto&& type : cql3_type::values()) {\n \/\/ Note: because text and varchar ends up being synonimous, our automatic makeToBlobFunction doesn't work\n \/\/ for varchar, so we special case it below. We also skip blob for obvious reasons.\n if (type == cql3_type::varchar || type == cql3_type::blob) {\n continue;\n }\n\n declare(make_to_blob_function(type->get_type()));\n declare(make_from_blob_function(type->get_type()));\n }\n declare(aggregate_fcts::make_count_function<int32_t>());\n declare(aggregate_fcts::make_max_function<int32_t>());\n declare(aggregate_fcts::make_min_function<int32_t>());\n\n declare(aggregate_fcts::make_count_function<int64_t>());\n declare(aggregate_fcts::make_max_function<int64_t>());\n declare(aggregate_fcts::make_min_function<int64_t>());\n\n \/\/FIXME:\n \/\/declare(aggregate_fcts::make_count_function<bytes>());\n \/\/declare(aggregate_fcts::make_max_function<bytes>());\n \/\/declare(aggregate_fcts::make_min_function<bytes>());\n\n \/\/ FIXME: more count\/min\/max\n\n declare(make_varchar_as_blob_fct());\n declare(make_blob_as_varchar_fct());\n declare(aggregate_fcts::make_sum_function<int32_t>());\n declare(aggregate_fcts::make_sum_function<int64_t>());\n declare(aggregate_fcts::make_avg_function<int32_t>());\n declare(aggregate_fcts::make_avg_function<int64_t>());\n#if 0\n declare(AggregateFcts.sumFunctionForFloat);\n declare(AggregateFcts.sumFunctionForDouble);\n declare(AggregateFcts.sumFunctionForDecimal);\n declare(AggregateFcts.sumFunctionForVarint);\n declare(AggregateFcts.avgFunctionForFloat);\n declare(AggregateFcts.avgFunctionForDouble);\n declare(AggregateFcts.avgFunctionForVarint);\n declare(AggregateFcts.avgFunctionForDecimal);\n#endif\n\n \/\/ also needed for smp:\n#if 0\n MigrationManager.instance.register(new FunctionsMigrationListener());\n#endif\n return ret;\n }\n\npublic:\n static shared_ptr<column_specification> make_arg_spec(const sstring& receiver_ks, const sstring& receiver_cf,\n const function& fun, size_t i) {\n auto&& name = boost::lexical_cast<std::string>(fun.name());\n std::transform(name.begin(), name.end(), name.begin(), ::tolower);\n return ::make_shared<column_specification>(receiver_ks,\n receiver_cf,\n ::make_shared<column_identifier>(sprint(\"arg%d(%s)\", i, name), true),\n fun.arg_types()[i]);\n }\n\n static int get_overload_count(const function_name& name) {\n return _declared.count(name);\n }\n\npublic:\n static shared_ptr<function> get(const sstring& keyspace,\n const function_name& name,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n \/\/ FIXME:\n#if 0\n \/\/ later\n if (name.has_keyspace()\n ? name.equals(TOKEN_FUNCTION_NAME)\n : name.name.equals(TOKEN_FUNCTION_NAME.name))\n return new TokenFct(Schema.instance.getCFMetaData(receiverKs, receiverCf));\n#endif\n std::vector<shared_ptr<function>> candidates;\n auto&& add_declared = [&] (function_name fn) {\n auto&& fns = _declared.equal_range(fn);\n for (auto i = fns.first; i != fns.second; ++i) {\n candidates.push_back(i->second);\n }\n };\n if (!name.has_keyspace()) {\n \/\/ add 'SYSTEM' (native) candidates\n add_declared(name.as_native_function());\n add_declared(function_name(keyspace, name.name));\n } else {\n \/\/ function name is fully qualified (keyspace + name)\n add_declared(name);\n }\n\n if (candidates.empty()) {\n return {};\n }\n\n \/\/ Fast path if there is only one choice\n if (candidates.size() == 1) {\n auto fun = std::move(candidates[0]);\n validate_types(keyspace, fun, provided_args, receiver_ks, receiver_cf);\n return fun;\n }\n\n std::vector<shared_ptr<function>> compatibles;\n for (auto&& to_test : candidates) {\n auto r = match_arguments(keyspace, to_test, provided_args, receiver_ks, receiver_cf);\n switch (r) {\n case assignment_testable::test_result::EXACT_MATCH:\n \/\/ We always favor exact matches\n return to_test;\n case assignment_testable::test_result::WEAKLY_ASSIGNABLE:\n compatibles.push_back(std::move(to_test));\n break;\n default:\n ;\n };\n }\n\n if (compatibles.empty()) {\n throw exceptions::invalid_request_exception(\n sprint(\"Invalid call to function %s, none of its type signatures match (known type signatures: %s)\",\n name, join(\", \", candidates)));\n }\n\n if (compatibles.size() > 1) {\n throw exceptions::invalid_request_exception(\n sprint(\"Ambiguous call to function %s (can be matched by following signatures: %s): use type casts to disambiguate\",\n name, join(\", \", compatibles)));\n }\n\n return std::move(compatibles[0]);\n }\n\n template <typename AssignmentTestablePtrRange>\n static shared_ptr<function> get(const sstring& keyspace,\n const function_name& name,\n AssignmentTestablePtrRange&& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n const std::vector<shared_ptr<assignment_testable>> args(std::begin(provided_args), std::end(provided_args));\n return get(keyspace, name, args, receiver_ks, receiver_cf);\n }\n\n static std::vector<shared_ptr<function>> find(const function_name& name) {\n auto range = _declared.equal_range(name);\n std::vector<shared_ptr<function>> ret;\n for (auto i = range.first; i != range.second; ++i) {\n ret.push_back(i->second);\n }\n return ret;\n }\n\n static shared_ptr<function> find(const function_name& name, const std::vector<data_type>& arg_types) {\n assert(name.has_keyspace()); \/\/ : \"function name not fully qualified\";\n for (auto&& f : find(name)) {\n if (type_equals(f->arg_types(), arg_types)) {\n return f;\n }\n }\n return {};\n }\n\nprivate:\n \/\/ This method and matchArguments are somewhat duplicate, but this method allows us to provide more precise errors in the common\n \/\/ case where there is no override for a given function. This is thus probably worth the minor code duplication.\n static void validate_types(const sstring& keyspace,\n shared_ptr<function> fun,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n if (provided_args.size() != fun->arg_types().size()) {\n throw exceptions::invalid_request_exception(\n sprint(\"Invalid number of arguments in call to function %s: %d required but %d provided\",\n fun->name(), fun->arg_types().size(), provided_args.size()));\n }\n\n for (size_t i = 0; i < provided_args.size(); ++i) {\n auto&& provided = provided_args[i];\n\n \/\/ If the concrete argument is a bind variables, it can have any type.\n \/\/ We'll validate the actually provided value at execution time.\n if (!provided) {\n continue;\n }\n\n auto&& expected = make_arg_spec(receiver_ks, receiver_cf, *fun, i);\n if (!is_assignable(provided->test_assignment(keyspace, expected))) {\n throw exceptions::invalid_request_exception(\n sprint(\"Type error: %s cannot be passed as argument %d of function %s of type %s\",\n provided, i, fun->name(), expected->type->as_cql3_type()));\n }\n }\n }\n\n static assignment_testable::test_result match_arguments(const sstring& keyspace,\n shared_ptr<function> fun,\n const std::vector<shared_ptr<assignment_testable>>& provided_args,\n const sstring& receiver_ks,\n const sstring& receiver_cf) {\n if (provided_args.size() != fun->arg_types().size()) {\n return assignment_testable::test_result::NOT_ASSIGNABLE;\n }\n\n \/\/ It's an exact match if all are exact match, but is not assignable as soon as any is non assignable.\n auto res = assignment_testable::test_result::EXACT_MATCH;\n for (size_t i = 0; i < provided_args.size(); ++i) {\n auto&& provided = provided_args[i];\n if (!provided) {\n res = assignment_testable::test_result::WEAKLY_ASSIGNABLE;\n continue;\n }\n auto&& expected = make_arg_spec(receiver_ks, receiver_cf, *fun, i);\n auto arg_res = provided->test_assignment(keyspace, expected);\n if (arg_res == assignment_testable::test_result::NOT_ASSIGNABLE) {\n return assignment_testable::test_result::NOT_ASSIGNABLE;\n }\n if (arg_res == assignment_testable::test_result::WEAKLY_ASSIGNABLE) {\n res = assignment_testable::test_result::WEAKLY_ASSIGNABLE;\n }\n }\n return res;\n }\n\n#if 0\n \/\/ This is *not* thread safe but is only called in SchemaTables that is synchronized.\n public static void addFunction(AbstractFunction fun)\n {\n \/\/ We shouldn't get there unless that function don't exist\n assert find(fun.name(), fun.argTypes()) == null;\n declare(fun);\n }\n\n \/\/ Same remarks than for addFunction\n public static void removeFunction(FunctionName name, List<AbstractType<?>> argsTypes)\n {\n Function old = find(name, argsTypes);\n assert old != null && !old.isNative();\n declared.remove(old.name(), old);\n }\n\n \/\/ Same remarks than for addFunction\n public static void replaceFunction(AbstractFunction fun)\n {\n removeFunction(fun.name(), fun.argTypes());\n addFunction(fun);\n }\n\n public static List<Function> getReferencesTo(Function old)\n {\n List<Function> references = new ArrayList<>();\n for (Function function : declared.values())\n if (function.hasReferenceTo(old))\n references.add(function);\n return references;\n }\n\n public static Collection<Function> all()\n {\n return declared.values();\n }\n\n public static boolean typeEquals(AbstractType<?> t1, AbstractType<?> t2)\n {\n return t1.asCQL3Type().toString().equals(t2.asCQL3Type().toString());\n }\n\n#endif\n\n static bool type_equals(const std::vector<data_type>& t1, const std::vector<data_type>& t2) {\n#if 0\n if (t1.size() != t2.size())\n return false;\n for (int i = 0; i < t1.size(); i ++)\n if (!typeEquals(t1.get(i), t2.get(i)))\n return false;\n return true;\n#endif\n abort();\n }\n\n#if 0\n private static class FunctionsMigrationListener implements IMigrationListener\n {\n public void onCreateKeyspace(String ksName) { }\n public void onCreateColumnFamily(String ksName, String cfName) { }\n public void onCreateUserType(String ksName, String typeName) { }\n public void onCreateFunction(String ksName, String functionName) { }\n public void onCreateAggregate(String ksName, String aggregateName) { }\n\n public void onUpdateKeyspace(String ksName) { }\n public void onUpdateColumnFamily(String ksName, String cfName) { }\n public void onUpdateUserType(String ksName, String typeName) {\n for (Function function : all())\n if (function instanceof UDFunction)\n ((UDFunction)function).userTypeUpdated(ksName, typeName);\n }\n public void onUpdateFunction(String ksName, String functionName) { }\n public void onUpdateAggregate(String ksName, String aggregateName) { }\n\n public void onDropKeyspace(String ksName) { }\n public void onDropColumnFamily(String ksName, String cfName) { }\n public void onDropUserType(String ksName, String typeName) { }\n public void onDropFunction(String ksName, String functionName) { }\n public void onDropAggregate(String ksName, String aggregateName) { }\n }\n#endif\n};\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * This file is property of and copyright by the Experimental Nuclear *\n * Physics Group, Dep. of Physics *\n * University of Oslo, Norway, 2007 *\n * *\n * Author: Per Thomas Hille <perthi@fys.uio.no> for the ALICE HLT Project.*\n * Contributors are mentioned in the code where appropriate. *\n * Please report bugs to perthi@fys.uio.no *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliHLTEMCALRawAnalyzerLMSComponent.h\"\n#include \"AliCaloRawAnalyzerLMS.h\"\n\n\/\/Evaluation of Amplitude and Peak position using Least Mean Square (LMS) fit\n\/\/-----------\n\/\/-----------\n\/\/-----------\n\/\/-----------\n\n\nAliHLTEMCALRawAnalyzerLMSComponent gAliHLTEMCALRawAnalyzerLMSComponent;\n\nAliHLTEMCALRawAnalyzerLMSComponent::AliHLTEMCALRawAnalyzerLMSComponent() : AliHLTEMCALRawAnalyzerComponent(kLMS)\n{\n \/\/ fAnalyzerPtr\n \/\/ fAnalyzerPtr = new AliCaloRawAnalyzerLMS();\n}\n\n\nAliHLTEMCALRawAnalyzerLMSComponent::~AliHLTEMCALRawAnalyzerLMSComponent()\n{\n \/\/ delete fAnalyzerPtr;\n}\n\n\n\nconst char* \nAliHLTEMCALRawAnalyzerLMSComponent::GetComponentID()\n{\n return \"EmcalRawLms\";\n}\n\n\n\nAliHLTComponent* \nAliHLTEMCALRawAnalyzerLMSComponent::Spawn()\n{\n return new AliHLTEMCALRawAnalyzerLMSComponent();\n}\n\n\nint \nAliHLTEMCALRawAnalyzerLMSComponent::Deinit()\n{\n return 0;\n}\n<commit_msg>Removing obsolete class AliCaloRawAnalyzerLMS<commit_after>\/**************************************************************************\n * This file is property of and copyright by the Experimental Nuclear *\n * Physics Group, Dep. of Physics *\n * University of Oslo, Norway, 2007 *\n * *\n * Author: Per Thomas Hille <perthi@fys.uio.no> for the ALICE HLT Project.*\n * Contributors are mentioned in the code where appropriate. *\n * Please report bugs to perthi@fys.uio.no *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliHLTEMCALRawAnalyzerLMSComponent.h\"\n#include \"AliCaloRawAnalyzerKStandard.h\"\n\/\/#include \"AliCaloRawAnalyzerLMS.h\"\n\n\/\/Evaluation of Amplitude and Peak position using Least Mean Square (LMS) fit\n\/\/-----------\n\/\/-----------\n\/\/-----------\n\/\/-----------\n\n\nAliHLTEMCALRawAnalyzerLMSComponent gAliHLTEMCALRawAnalyzerLMSComponent;\n\n\/\/AliHLTEMCALRawAnalyzerLMSComponent::AliHLTEMCALRawAnalyzerLMSComponent() : AliHLTEMCALRawAnalyzerComponent(kLMS)\nAliHLTEMCALRawAnalyzerLMSComponent::AliHLTEMCALRawAnalyzerLMSComponent() : AliHLTEMCALRawAnalyzerComponent(kStandard)\n{\n \/\/ fAnalyzerPtr\n \/\/ fAnalyzerPtr = new AliCaloRawAnalyzerLMS();\n}\n\n\nAliHLTEMCALRawAnalyzerLMSComponent::~AliHLTEMCALRawAnalyzerLMSComponent()\n{\n \/\/ delete fAnalyzerPtr;\n}\n\n\n\nconst char* \nAliHLTEMCALRawAnalyzerLMSComponent::GetComponentID()\n{\n return \"EmcalRawLms\";\n}\n\n\n\nAliHLTComponent* \nAliHLTEMCALRawAnalyzerLMSComponent::Spawn()\n{\n return new AliHLTEMCALRawAnalyzerLMSComponent();\n}\n\n\nint \nAliHLTEMCALRawAnalyzerLMSComponent::Deinit()\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef UNION_SSE_HPP_\n#define UNION_SSE_HPP_\n\n#include <immintrin.h>\n\n#include <algorithm>\n\n#include \"branchless.hpp\"\n\n\nsize_t union_vector_sse(const uint32_t *list1, size_t size1, const uint32_t *list2, size_t size2, uint32_t *result){\n\tsize_t count = 0;\n#ifdef __SSE2__\n\tsize_t i_a = 0, i_b = 0;\n\t\/\/ trim lengths to be a multiple of 4\n\tsize_t st_a = ((size1-1) \/ 4) * 4;\n\tsize_t st_b = ((size2-1) \/ 4) * 4;\n\tuint32_t endofblock=~0, a_nextfirst, b_nextfirst;\n\tuint32_t maxtail[4];\n\n\tif(i_a < st_a && i_b < st_b){\n\t\t__m128i v_a = _mm_load_si128((__m128i*)&list1[i_a]);\n\t\t__m128i v_b = _mm_load_si128((__m128i*)&list2[i_b]);\n\n\t\tdo {\n\t\t\t__m128i step1min = _mm_min_epu32(v_a, v_b);\n\t\t\t__m128i step1max = _mm_max_epu32(v_a, v_b);\n\n\t\t\tconstexpr int32_t cyclic_shift = _MM_SHUFFLE(2,1,0,3);\n\t\t\t__m128i tmp = _mm_shuffle_epi32(step1max, cyclic_shift);\n\t\t\t__m128i step2min = _mm_min_epu32(step1min, tmp);\n\t\t\t__m128i step2max = _mm_max_epu32(step1min, tmp);\n\n\t\t\t__m128i tmp2 = _mm_shuffle_epi32(step2max, cyclic_shift);\n\t\t\t__m128i step3min = _mm_min_epu32(step2min, tmp2);\n\t\t\t__m128i step3max = _mm_max_epu32(step2min, tmp2);\n\n\t\t\t__m128i tmp3 = _mm_shuffle_epi32(step3max, cyclic_shift);\n\t\t\t__m128i step4min = _mm_min_epu32(step3min, tmp3);\n\t\t\t__m128i step4max = _mm_max_epu32(step3min, tmp3);\n\n\t\t\t__m128i tmp4 = _mm_shuffle_epi32(step4max, cyclic_shift);\n\n\t\t\t\/\/ deduplicate over block end, 1 2 3 4 | 4 5 6 7\n\t\t\tuint32_t first = _mm_extract_epi32(step4min, 0);\n\t\t\tcount -= (endofblock==first);\n\t\t\tendofblock = _mm_extract_epi32(step4min, 3);\n\t\t\t\/\/ in register deduplicate, only removes inside one vector\n\t\t\t__m128i dedup = _mm_shuffle_epi32(step4min, cyclic_shift);\n\t\t\t__m128i dedup_mask = _mm_cmpeq_epi32(step4min, dedup);\n\t\t\t\/\/ flip mask\n\t\t\tdedup_mask = _mm_andnot_si128(dedup_mask, _mm_cmpeq_epi32(tmp, tmp));\n\t\t\t\/\/ compress shuffle like in intersect\n\t\t\t\/\/ convert the 128-bit mask to the 4-bit mask\n\t\t\tint32_t mask = _mm_movemask_ps((__m128)dedup_mask);\n\t\t\t__m128i p = _mm_shuffle_epi8(step4min, shuffle_mask[mask]);\n\t\t\t_mm_storeu_si128((__m128i*)&result[count], p);\n\t\t\tcount += _mm_popcnt_u32(mask); \/\/ a number of elements is a weight of the mask\n\n\t\t\tv_a = tmp4;\n\t\t\t\/\/ compare first element of the next block in both lists\n\t\t\ta_nextfirst = list1[i_a+4];\n\t\t\tb_nextfirst = list2[i_b+4];\n\t\t\t\/\/ write minimum as above out to result\n\t\t\t\/\/ keep maximum and do the same steps as above with next block\n\t\t\t\/\/ next block from one list, which first element in new block is smaller\n\t\t\tasm(\".intel_syntax noprefix;\"\n\n\t\t\t\t\"xor rax, rax;\"\n\t\t\t\t\"xor rbx, rbx;\"\n\t\t\t\t\"cmp %5, %6;\"\n\t\t\t\t\"setbe al;\"\n\t\t\t\t\"seta bl;\"\n\t\t\t\t\"lea %q0, [%q0 + rax*4];\"\n\t\t\t\t\"lea %q1, [%q1 + rbx*4];\"\n\n\t\t\t\t\/\/ load next block from list with smaller first element\n\t\t\t\t\"mov r10, %q8;\"\n\t\t\t\t\"mov r11, %q1;\"\n\t\t\t\t\"cmovbe r10, %q7;\"\n\t\t\t\t\"cmovbe r11, %q0;\"\n\t\t\t\t\"vmovdqa %2, [r10 + r11*4];\" \/\/FIXME: this might read past the end of one array, not used afterwards as loop head fails\n\n\t\t\t\t\".att_syntax\"\n\t\t\t\t: \"=r\"(i_a), \"=r\"(i_b), \"=x\"(v_b)\n\t\t\t\t: \"0\"(i_a), \"1\"(i_b), \"r\"(a_nextfirst), \"r\"(b_nextfirst), \"r\"(list1), \"r\"(list2)\n\t\t\t\t: \"%eax\",\"%ebx\", \"%r10\",\"%r11\", \"cc\"\n\t\t\t);\n\t\t}while(i_a < st_a && i_b < st_b);\n\t\t\/\/ v_a contains max vector from last comparison, v_b contains new, might be out of bounds\n\t\t\/\/ indices i_a and i_b correct, still need to handle v_a\n\t\t_mm_storeu_si128((__m128i*)maxtail, v_a);\n\n\t\tsize_t mti=0;\n\t\tsize_t mtsize = std::unique(maxtail, maxtail+4) - maxtail; \/\/ deduplicate tail\n\t\tif(a_nextfirst <= b_nextfirst){\n\t\t\t\/\/ endofblock needs to be considered too, for deduplication\n\t\t\tif(endofblock == std::min(maxtail[0],list1[i_a])) --count;\n\t\t\t\/\/ compare maxtail with list1\n\t\/\/ \t\tcount += union_scalar_branchless(maxtail, 4, list1+i_a, size1-i_a, result+count);\n\t\t\twhile(mti < mtsize && i_a < size1){\n\t\t\t\tif(maxtail[mti] < list1[i_a]){\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++;\n\t\t\t\t}else if(maxtail[mti] > list1[i_a]){\n\t\t\t\t\tresult[count++] = list1[i_a];\n\t\t\t\t\ti_a++;\n\t\t\t\t}else{\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++; i_a++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti_b += 4;\n\t\t}else{\n\t\t\t\/\/ endofblock needs to be considered too, for deduplication\n\t\t\tif(endofblock == std::min(maxtail[0],list2[i_b])) --count;\n\t\t\t\/\/ compare maxtail with list2\n\t\/\/ \t\tcount += union_scalar_branchless(maxtail, 4, list2+i_b, size2-i_b, result+count);\n\t\t\twhile(mti < mtsize && i_b < size2){\n\t\t\t\tif(maxtail[mti] < list2[i_b]){\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++;\n\t\t\t\t}else if(maxtail[mti] > list2[i_b]){\n\t\t\t\t\tresult[count++] = list2[i_b];\n\t\t\t\t\ti_b++;\n\t\t\t\t}else{\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++; i_b++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti_a += 4;\n\t\t}\n\t\twhile(mti < mtsize){\n\t\t\tresult[count++] = maxtail[mti++];\n\t\t}\n\t}\n\n\t\/\/ scalar tail\n\tcount += union_scalar_branchless(list1+i_a, size1-i_a, list2+i_b, size2-i_b, result+count);\n#endif\n\n\treturn count;\n}\n\n#endif\n<commit_msg>added new deduplication variant to SSE set_union<commit_after>#ifndef UNION_SSE_HPP_\n#define UNION_SSE_HPP_\n\n#include <immintrin.h>\n\n#include <algorithm>\n\n#include \"branchless.hpp\"\n\n#define BLEND 1\n#if BLEND\nstatic constexpr constarray<uint8_t,16*16> prepare_shuffle(){\n\tconstarray<uint8_t,16*16> arr = {0xff};\n\tint size=0;\n\tfor(int i=0; i<16; ++i){\n\t\tint counter=0;\n\t\tfor(int j=0; j<4; ++j){\n\t\t\tif((i & (1 << j)) == 0){\n\t\t\t\tarr[size+counter*4 ] = 4*j;\n\t\t\t\tarr[size+counter*4+1] = 4*j + 1;\n\t\t\t\tarr[size+counter*4+2] = 4*j + 2;\n\t\t\t\tarr[size+counter*4+3] = 4*j + 3;\n\t\t\t\t++counter;\n\t\t\t}\n\t\t}\n\t\tsize += 16;\n\t}\n\treturn arr;\n}\nstatic const constexpr auto shuffle_arr = prepare_shuffle();\nstatic const constexpr __m128i *shuffle = (__m128i*)shuffle_arr.elems;\n#endif\n\n\nsize_t union_vector_sse(const uint32_t *list1, size_t size1, const uint32_t *list2, size_t size2, uint32_t *result){\n\tsize_t count = 0;\n#ifdef __SSE2__\n\tsize_t i_a = 0, i_b = 0;\n\t\/\/ trim lengths to be a multiple of 4\n\tsize_t st_a = ((size1-1) \/ 4) * 4;\n\tsize_t st_b = ((size2-1) \/ 4) * 4;\n\tuint32_t a_nextfirst, b_nextfirst;\n#if !BLEND\n\tuint32_t endofblock=~0;\n#else\n\t__m128i old = _mm_set1_epi32(-1); \/\/FIXME: hardcoded, use something related to the lists\n#endif\n\tuint32_t maxtail[4];\n\n\tif(i_a < st_a && i_b < st_b){\n\t\t__m128i v_a = _mm_load_si128((__m128i*)&list1[i_a]);\n\t\t__m128i v_b = _mm_load_si128((__m128i*)&list2[i_b]);\n\n\t\tdo {\n\t\t\t__m128i step1min = _mm_min_epu32(v_a, v_b);\n\t\t\t__m128i step1max = _mm_max_epu32(v_a, v_b);\n\n\t\t\tconstexpr int32_t cyclic_shift = _MM_SHUFFLE(2,1,0,3);\n\t\t\t__m128i tmp = _mm_shuffle_epi32(step1max, cyclic_shift);\n\t\t\t__m128i step2min = _mm_min_epu32(step1min, tmp);\n\t\t\t__m128i step2max = _mm_max_epu32(step1min, tmp);\n\n\t\t\t__m128i tmp2 = _mm_shuffle_epi32(step2max, cyclic_shift);\n\t\t\t__m128i step3min = _mm_min_epu32(step2min, tmp2);\n\t\t\t__m128i step3max = _mm_max_epu32(step2min, tmp2);\n\n\t\t\t__m128i tmp3 = _mm_shuffle_epi32(step3max, cyclic_shift);\n\t\t\t__m128i step4min = _mm_min_epu32(step3min, tmp3);\n\t\t\t__m128i step4max = _mm_max_epu32(step3min, tmp3);\n\n\t\t\t__m128i tmp4 = _mm_shuffle_epi32(step4max, cyclic_shift);\n\n#if !BLEND\n\t\t\t\/\/ deduplicate over block end, 1 2 3 4 | 4 5 6 7\n\t\t\tuint32_t first = _mm_extract_epi32(step4min, 0);\n\t\t\tcount -= (endofblock==first);\n\t\t\tendofblock = _mm_extract_epi32(step4min, 3);\n\t\t\t\/\/ in register deduplicate, only removes inside one vector\n\t\t\t__m128i dedup = _mm_shuffle_epi32(step4min, cyclic_shift);\n\t\t\t__m128i dedup_mask = _mm_cmpeq_epi32(step4min, dedup);\n\t\t\t\/\/ flip mask\n\t\t\tdedup_mask = _mm_andnot_si128(dedup_mask, _mm_cmpeq_epi32(tmp, tmp));\n\t\t\t\/\/ compress shuffle like in intersect\n\t\t\t\/\/ convert the 128-bit mask to the 4-bit mask\n\t\t\tint32_t mask = _mm_movemask_ps((__m128)dedup_mask);\n\t\t\t__m128i p = _mm_shuffle_epi8(step4min, shuffle_mask[mask]);\n\t\t\t_mm_storeu_si128((__m128i*)&result[count], p);\n\t\t\tcount += _mm_popcnt_u32(mask); \/\/ a number of elements is a weight of the mask\n#else\n\t\t\t\/\/ deduplicate over block end, 1 2 3 4 | 4 5 6 7\n\t\t\t\/\/ remember previous minimum vector, only use highest value\n\t\t\t__m128i recon = _mm_blend_epi32(old, step4min, 0b0111);\n\t\t\t\/\/ in register deduplicate, removes duplicates in one vector\n\t\t\t\/\/ and across as we moved in the highest previous value\n\t\t\t__m128i dedup = _mm_shuffle_epi32(recon, cyclic_shift);\n\t\t\t\/\/ compress shuffle like in intersect but flipped, use flipped lut\n\t\t\t\/\/ convert the 128-bit mask to the 4-bit mask\n\t\t\tint32_t mask = _mm_movemask_ps((__m128)_mm_cmpeq_epi32(dedup, step4min));\n\t\t\t__m128i p = _mm_shuffle_epi8(step4min, shuffle[mask]);\n\t\t\t_mm_storeu_si128((__m128i*)&result[count], p);\n\t\t\tcount += 4 - _mm_popcnt_u32(mask); \/\/ a number of elements is a weight of the mask\n\t\t\t\/\/ remember minimum for next iteration\n\t\t\told = step4min;\n#endif\n\n\t\t\tv_a = tmp4;\n\t\t\t\/\/ compare first element of the next block in both lists\n\t\t\ta_nextfirst = list1[i_a+4];\n\t\t\tb_nextfirst = list2[i_b+4];\n\t\t\t\/\/ write minimum as above out to result\n\t\t\t\/\/ keep maximum and do the same steps as above with next block\n\t\t\t\/\/ next block from one list, which first element in new block is smaller\n\t\t\tasm(\".intel_syntax noprefix;\"\n\n\t\t\t\t\"xor rax, rax;\"\n\t\t\t\t\"xor rbx, rbx;\"\n\t\t\t\t\"cmp %5, %6;\"\n\t\t\t\t\"setbe al;\"\n\t\t\t\t\"seta bl;\"\n\t\t\t\t\"lea %q0, [%q0 + rax*4];\"\n\t\t\t\t\"lea %q1, [%q1 + rbx*4];\"\n\n\t\t\t\t\/\/ load next block from list with smaller first element\n\t\t\t\t\"mov r10, %q8;\"\n\t\t\t\t\"mov r11, %q1;\"\n\t\t\t\t\"cmovbe r10, %q7;\"\n\t\t\t\t\"cmovbe r11, %q0;\"\n\t\t\t\t\"vmovdqa %2, [r10 + r11*4];\" \/\/FIXME: this might read past the end of one array, not used afterwards as loop head fails\n\n\t\t\t\t\".att_syntax\"\n\t\t\t\t: \"=r\"(i_a), \"=r\"(i_b), \"=x\"(v_b)\n\t\t\t\t: \"0\"(i_a), \"1\"(i_b), \"r\"(a_nextfirst), \"r\"(b_nextfirst), \"r\"(list1), \"r\"(list2)\n\t\t\t\t: \"%eax\",\"%ebx\", \"%r10\",\"%r11\", \"cc\"\n\t\t\t);\n\t\t}while(i_a < st_a && i_b < st_b);\n\t\t\/\/ v_a contains max vector from last comparison, v_b contains new, might be out of bounds\n\t\t\/\/ indices i_a and i_b correct, still need to handle v_a\n\t\t_mm_storeu_si128((__m128i*)maxtail, v_a);\n#if BLEND\n\t\tuint32_t endofblock = _mm_extract_epi32(old, 3);\n#endif\n\n\t\tsize_t mti=0;\n\t\tsize_t mtsize = std::unique(maxtail, maxtail+4) - maxtail; \/\/ deduplicate tail\n\t\tif(a_nextfirst <= b_nextfirst){\n\t\t\t\/\/ endofblock needs to be considered too, for deduplication\n\t\t\tif(endofblock == std::min(maxtail[0],list1[i_a])) --count;\n\t\t\t\/\/ compare maxtail with list1\n\t\/\/ \t\tcount += union_scalar_branchless(maxtail, 4, list1+i_a, size1-i_a, result+count);\n\t\t\twhile(mti < mtsize && i_a < size1){\n\t\t\t\tif(maxtail[mti] < list1[i_a]){\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++;\n\t\t\t\t}else if(maxtail[mti] > list1[i_a]){\n\t\t\t\t\tresult[count++] = list1[i_a];\n\t\t\t\t\ti_a++;\n\t\t\t\t}else{\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++; i_a++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti_b += 4;\n\t\t}else{\n\t\t\t\/\/ endofblock needs to be considered too, for deduplication\n\t\t\tif(endofblock == std::min(maxtail[0],list2[i_b])) --count;\n\t\t\t\/\/ compare maxtail with list2\n\t\/\/ \t\tcount += union_scalar_branchless(maxtail, 4, list2+i_b, size2-i_b, result+count);\n\t\t\twhile(mti < mtsize && i_b < size2){\n\t\t\t\tif(maxtail[mti] < list2[i_b]){\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++;\n\t\t\t\t}else if(maxtail[mti] > list2[i_b]){\n\t\t\t\t\tresult[count++] = list2[i_b];\n\t\t\t\t\ti_b++;\n\t\t\t\t}else{\n\t\t\t\t\tresult[count++] = maxtail[mti];\n\t\t\t\t\tmti++; i_b++;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti_a += 4;\n\t\t}\n\t\twhile(mti < mtsize){\n\t\t\tresult[count++] = maxtail[mti++];\n\t\t}\n\t}\n\n\t\/\/ scalar tail\n\tcount += union_scalar_branchless(list1+i_a, size1-i_a, list2+i_b, size2-i_b, result+count);\n#endif\n\n\treturn count;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#include<assert.h>\n#include<thread>\n#include<mutex>\n\n#include\"ParallelTest.h\"\n#include\"INode.h\"\n#include\"CDirectory.h\"\n\n\n#define MAXSIZE 0xFFFFF\n\n\/\/ ----------------------\n\nstatic SimpleFilesystem *fs;\n\n\/\/ ----------------------\n\ntypedef struct\n{\n INODEPTR node;\n char filename[256];\n int size;\n std::mutex mtx;\n char data[MAXSIZE+2];\n unsigned int g_seed;\n} FSTRUCT;\n\nstatic FSTRUCT *files;\n\nstatic unsigned int niter = 2000;\nstatic unsigned int nfiles = 10;\nstatic unsigned int nthreads = 10;\n\nstatic unsigned int g_seed = 0;\n\ninline int fastrand(unsigned int &g_seed)\n{\n g_seed = (214013*g_seed+2531011);\n return (g_seed>>16)&0x7FFF;\n}\n\n\/\/ ----------------------\n\nvoid Execute(int tid)\n{\n char *data = new char[MAXSIZE+2];\n CDirectory dir = fs->OpenDir(\"\/\");\n\n \/\/printf(\"thread %i:\\n\", tid);\n for(unsigned int iter=0; iter<niter; iter++)\n {\n int cmd = fastrand(g_seed)%6;\n int id = fastrand(g_seed)%nfiles;\n int ofs = 0;\n\n files[id].mtx.lock();\n \/\/printf(\"cmd=%i id=%i\\n\", cmd, id);\n switch(cmd)\n {\n\n case 0: \/\/ Truncate\n {\n int newsize = rand() & MAXSIZE;\n printf(\"tid %1i %5i: Truncate %i size=%i\\n\", tid, iter, id, newsize);\n if (newsize > files[id].size)\n {\n memset(&(files[id].data[ files[id].size ]), 0, newsize-files[id].size);\n }\n files[id].size = newsize;\n files[id].node->Truncate(newsize);\n }\n break;\n\n\n case 1: \/\/ write\n {\n if (files[id].size > 0) ofs = rand() % files[id].size;\n int newsize = rand() & MAXSIZE;\n if (ofs+newsize > MAXSIZE) newsize = MAXSIZE - ofs - 1;\n if (newsize < 0) newsize = 0;\n\n printf(\"tid %1i %5i: write %i ofs=%i size=%i\\n\", tid, iter, id, ofs, newsize);\n for(int i=0; i<newsize; i++)\n {\n files[id].data[ofs+i] = fastrand(files[id].g_seed);\n }\n\n files[id].node->Write((int8_t*)&(files[id].data[ofs]), ofs, newsize);\n if (ofs+newsize > files[id].size) files[id].size = ofs+newsize;\n }\n break;\n\n case 2: \/\/ read\n {\n if (files[id].size > 0) ofs = rand() % files[id].size;\n int newsize = rand() & MAXSIZE;\n if (ofs+newsize > MAXSIZE) newsize = MAXSIZE - ofs - 1;\n if (newsize < 0) newsize = 0;\n\n printf(\"tid %1i %5i: read %i ofs=%i size=%i\\n\", tid, iter, id, ofs, newsize);\n if (ofs+newsize > files[id].size) newsize = files[id].size - ofs - 1;\n if (newsize < 0) newsize = 0;\n files[id].node->Read((int8_t*)data, ofs, newsize);\n\n for(int i=0; i<newsize; i++)\n {\n if (data[i] != files[id].data[ofs+i])\n {\n printf(\"read data from file %i does not match at ofs=%i read=%i but should be %i\\n\", id, ofs+i, data[i], files[id].data[ofs+i]);\n exit(1);\n }\n }\n }\n break;\n\n case 3: \/\/ check filesize\n {\n printf(\"tid %1i %5i: filesize %i\\n\", tid, iter, id);\n if (files[id].node->size != (unsigned int)files[id].size)\n {\n printf(\"size of file %i does not match %i %lli\\n\", id, files[id].size, (long long int)files[id].node->size);\n exit(1);\n }\n }\n break;\n\n case 4: \/\/ rename\n {\n printf(\"tid %1i %5i: rename %i\\n\", tid, iter, id);\n char newfilename[256];\n sprintf(newfilename, \"tests%02i_%03i.dat\", id, rand()%999);\n fs->Rename(files[id].node, dir, newfilename);\n strncpy(files[id].filename, newfilename, 256);\n }\n break;\n\n\n case 5: \/\/ create&remove\n {\n printf(\"tid %1i %5i: create&remove %i\\n\", tid, iter, id);\n char newfilename[256];\n sprintf(newfilename, \"tests%02i_check.dat\", id);\n dir.CreateFile(newfilename);\n INODEPTR node = fs->OpenNode(newfilename);\n node->Remove();\n }\n break;\n\n } \/\/ switch\n files[id].mtx.unlock();\n\n }\n\n}\n\n\nvoid ParallelTest(unsigned int _nfiles, unsigned int _nthreads, unsigned int _niter, SimpleFilesystem &_fs)\n{\n printf(\"Number of files %i\\n\", nfiles);\n printf(\"Number of threads: %i\\n\", nthreads);\n printf(\"Number of iterations per thread: %i\\n\", niter);\n\n srand (time(NULL));\n g_seed = time(NULL);\n\n nfiles = _nfiles;\n nthreads = _nthreads;\n niter = _niter;\n fs = &_fs;\n CDirectory dir = fs->OpenDir(\"\/\");\n\n files = new FSTRUCT[nfiles];\n for(unsigned int i=0; i<nfiles; i++)\n {\n files[i].g_seed = 0xA0A0A0+i;\n sprintf(files[i].filename, \"tests%02i_%03i.dat\", i, 0);\n try\n {\n dir.CreateFile(files[i].filename);\n }\n catch(...)\n {\n \/\/ file already exists\n }\n files[i].node = fs->OpenNode(files[i].filename);\n files[i].node->Truncate(0);\n\n files[i].size = 0;\n memset(files[i].data, 0, MAXSIZE+1);\n }\n\n std::thread *t = new std::thread[nthreads];\n\n for(unsigned int i=0; i<nthreads; i++)\n {\n t[i] = std::thread(Execute, i);\n }\n\n for(unsigned int i=0; i<nthreads; i++)\n {\n t[i].join();\n }\n printf(\"Tests done\\n\");\n\n}\n<commit_msg>Remove memory leaks<commit_after>#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\n#include<assert.h>\n#include<thread>\n#include<mutex>\n\n#include\"ParallelTest.h\"\n#include\"INode.h\"\n#include\"CDirectory.h\"\n\n\n#define MAXSIZE 0xFFFFF\n\n\/\/ ----------------------\n\nstatic SimpleFilesystem *fs;\n\n\/\/ ----------------------\n\ntypedef struct\n{\n INODEPTR node;\n char filename[256];\n int size;\n std::mutex mtx;\n char data[MAXSIZE+2];\n unsigned int g_seed;\n} FSTRUCT;\n\nstatic FSTRUCT *files;\n\nstatic unsigned int niter = 2000;\nstatic unsigned int nfiles = 10;\nstatic unsigned int nthreads = 10;\n\nstatic unsigned int g_seed = 0;\n\ninline int fastrand(unsigned int &g_seed)\n{\n g_seed = (214013*g_seed+2531011);\n return (g_seed>>16)&0x7FFF;\n}\n\n\/\/ ----------------------\n\nvoid Execute(int tid)\n{\n char *data = new char[MAXSIZE+2];\n CDirectory dir = fs->OpenDir(\"\/\");\n\n \/\/printf(\"thread %i:\\n\", tid);\n for(unsigned int iter=0; iter<niter; iter++)\n {\n int cmd = fastrand(g_seed)%6;\n int id = fastrand(g_seed)%nfiles;\n int ofs = 0;\n\n files[id].mtx.lock();\n \/\/printf(\"cmd=%i id=%i\\n\", cmd, id);\n switch(cmd)\n {\n\n case 0: \/\/ Truncate\n {\n int newsize = rand() & MAXSIZE;\n printf(\"tid %1i %5i: Truncate %i size=%i\\n\", tid, iter, id, newsize);\n if (newsize > files[id].size)\n {\n memset(&(files[id].data[ files[id].size ]), 0, newsize-files[id].size);\n }\n files[id].size = newsize;\n files[id].node->Truncate(newsize);\n }\n break;\n\n\n case 1: \/\/ write\n {\n if (files[id].size > 0) ofs = rand() % files[id].size;\n int newsize = rand() & MAXSIZE;\n if (ofs+newsize > MAXSIZE) newsize = MAXSIZE - ofs - 1;\n if (newsize < 0) newsize = 0;\n\n printf(\"tid %1i %5i: write %i ofs=%i size=%i\\n\", tid, iter, id, ofs, newsize);\n for(int i=0; i<newsize; i++)\n {\n files[id].data[ofs+i] = fastrand(files[id].g_seed);\n }\n\n files[id].node->Write((int8_t*)&(files[id].data[ofs]), ofs, newsize);\n if (ofs+newsize > files[id].size) files[id].size = ofs+newsize;\n }\n break;\n\n case 2: \/\/ read\n {\n if (files[id].size > 0) ofs = rand() % files[id].size;\n int newsize = rand() & MAXSIZE;\n if (ofs+newsize > MAXSIZE) newsize = MAXSIZE - ofs - 1;\n if (newsize < 0) newsize = 0;\n\n printf(\"tid %1i %5i: read %i ofs=%i size=%i\\n\", tid, iter, id, ofs, newsize);\n if (ofs+newsize > files[id].size) newsize = files[id].size - ofs - 1;\n if (newsize < 0) newsize = 0;\n files[id].node->Read((int8_t*)data, ofs, newsize);\n\n for(int i=0; i<newsize; i++)\n {\n if (data[i] != files[id].data[ofs+i])\n {\n printf(\"read data from file %i does not match at ofs=%i read=%i but should be %i\\n\", id, ofs+i, data[i], files[id].data[ofs+i]);\n exit(1);\n }\n }\n }\n break;\n\n case 3: \/\/ check filesize\n {\n printf(\"tid %1i %5i: filesize %i\\n\", tid, iter, id);\n if (files[id].node->size != (unsigned int)files[id].size)\n {\n printf(\"size of file %i does not match %i %lli\\n\", id, files[id].size, (long long int)files[id].node->size);\n exit(1);\n }\n }\n break;\n\n case 4: \/\/ rename\n {\n printf(\"tid %1i %5i: rename %i\\n\", tid, iter, id);\n char newfilename[256];\n sprintf(newfilename, \"tests%02i_%03i.dat\", id, rand()%999);\n fs->Rename(files[id].node, dir, newfilename);\n strncpy(files[id].filename, newfilename, 256);\n }\n break;\n\n\n case 5: \/\/ create&remove\n {\n printf(\"tid %1i %5i: create&remove %i\\n\", tid, iter, id);\n char newfilename[256];\n sprintf(newfilename, \"tests%02i_check.dat\", id);\n dir.CreateFile(newfilename);\n INODEPTR node = fs->OpenNode(newfilename);\n node->Remove();\n }\n break;\n\n } \/\/ switch\n files[id].mtx.unlock();\n\n }\n delete[] data;\n}\n\n\nvoid ParallelTest(unsigned int _nfiles, unsigned int _nthreads, unsigned int _niter, SimpleFilesystem &_fs)\n{\n printf(\"Number of files %i\\n\", nfiles);\n printf(\"Number of threads: %i\\n\", nthreads);\n printf(\"Number of iterations per thread: %i\\n\", niter);\n\n srand (time(NULL));\n g_seed = time(NULL);\n\n nfiles = _nfiles;\n nthreads = _nthreads;\n niter = _niter;\n fs = &_fs;\n CDirectory dir = fs->OpenDir(\"\/\");\n\n files = new FSTRUCT[nfiles];\n for(unsigned int i=0; i<nfiles; i++)\n {\n files[i].g_seed = 0xA0A0A0+i;\n sprintf(files[i].filename, \"tests%02i_%03i.dat\", i, 0);\n try\n {\n dir.CreateFile(files[i].filename);\n }\n catch(...)\n {\n \/\/ file already exists\n }\n files[i].node = fs->OpenNode(files[i].filename);\n files[i].node->Truncate(0);\n\n files[i].size = 0;\n memset(files[i].data, 0, MAXSIZE+1);\n }\n\n std::thread *t = new std::thread[nthreads];\n\n for(unsigned int i=0; i<nthreads; i++)\n {\n t[i] = std::thread(Execute, i);\n }\n\n for(unsigned int i=0; i<nthreads; i++)\n {\n t[i].join();\n }\n delete[] t;\n delete[] files;\n\n printf(\"Tests done\\n\");\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __RUBBISH_ADD_QUALIFIER__\n#define __RUBBISH_ADD_QUALIFIER__\n\n#include \"basic_traits.hpp\"\n#include \"remove_qualifier.hpp\"\n\nnamespace rubbish{\n \n namespace helper{\n template <class T,bool function_type=false> struct add_pointer_h {typedef typename remove_reference<T>::type type;};\n template <class T> struct add_pointer_h<T,true> {typedef T type;};\n template < class T,class ...Args> struct add_pointer_h<T(Args...),true> {using type = T(*)(Args...);};\n template < class T,class ...Args> struct add_pointer_h<T(Args...,...),true> {using type = T(*)(Args...,...);};\n } \/\/ namespace helper\n \n template <class T> struct add_const {typedef const T type;};\n \n template <class T> struct add_volatile {typedef volatile T type;};\n \n template <class T> struct add_cv {typedef typename add_const<typename add_volatile<T>::type>::type type;};\n \n \/\/ Always set `type` as an lvalue reference\n template <class T> struct add_lvalue_reference {typedef T& type;};\n template <class T> struct add_lvalue_reference<T&> {typedef T& type;};\n template <class T> struct add_lvalue_reference<T&&> {typedef T& type;};\n \n \/\/ Always set `type` as an rvalue reference\n template <class T> struct add_rvalue_reference {typedef T&& type;};\n template <class T> struct add_rvalue_reference<T&> {typedef T&& type;};\n template <class T> struct add_rvalue_reference<T&&> {typedef T&& type;};\n \n template <class T> struct add_pointer:public helper::add_pointer_h<T,is_function<T>::value> {};\n \n template <class T> struct decay {\n private:\n typedef typename remove_reference<T>::type U;\n public:\n typedef typename condition<is_array<U>::value,\n typename remove_extent<U>::type*,\n typename condition<is_function<U>::value,\n typename add_pointer<U>::type,\n typename remove_cv<U>::type\n >::type\n >::type type;\n };\n}\n#endif \/\/ __RUBBISH_ADD_QUALIFIER__\n<commit_msg>Fixed a bug<commit_after>#ifndef __RUBBISH_ADD_QUALIFIER__\n#define __RUBBISH_ADD_QUALIFIER__\n\n#include \"basic_traits.hpp\"\n#include \"is_checkers.hpp\"\n#include \"remove_qualifier.hpp\"\n\nnamespace rubbish{\n \n namespace helper{\n template <class T,bool function_type=false> struct add_pointer_h {typedef typename remove_reference<T>::type type;};\n template <class T> struct add_pointer_h<T,true> {typedef T type;};\n template < class T,class ...Args> struct add_pointer_h<T(Args...),true> {using type = T(*)(Args...);};\n template < class T,class ...Args> struct add_pointer_h<T(Args...,...),true> {using type = T(*)(Args...,...);};\n } \/\/ namespace helper\n \n template <class T> struct add_const {typedef const T type;};\n \n template <class T> struct add_volatile {typedef volatile T type;};\n \n template <class T> struct add_cv {typedef typename add_const<typename add_volatile<T>::type>::type type;};\n \n \/\/ Always set `type` as an lvalue reference\n template <class T> struct add_lvalue_reference {typedef T& type;};\n template <class T> struct add_lvalue_reference<T&> {typedef T& type;};\n template <class T> struct add_lvalue_reference<T&&> {typedef T& type;};\n \n \/\/ Always set `type` as an rvalue reference\n template <class T> struct add_rvalue_reference {typedef T&& type;};\n template <class T> struct add_rvalue_reference<T&> {typedef T&& type;};\n template <class T> struct add_rvalue_reference<T&&> {typedef T&& type;};\n \n template <class T> struct add_pointer:public helper::add_pointer_h<T,is_function<T>::value> {};\n \n template <class T> struct decay {\n private:\n typedef typename remove_reference<T>::type U;\n public:\n typedef typename condition<is_array<U>::value,\n typename remove_extent<U>::type*,\n typename condition<is_function<U>::value,\n typename add_pointer<U>::type,\n typename remove_cv<U>::type\n >::type\n >::type type;\n };\n}\n#endif \/\/ __RUBBISH_ADD_QUALIFIER__\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center, \nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without \neven the implied warranty of MERCHANTABILITY or FITNESS FOR \nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#include \"mitkDisplayVectorInteractor.h\"\n#include \"mitkOperation.h\"\n#include \"mitkDisplayCoordinateOperation.h\"\n#include \"mitkDisplayPositionEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkStateEvent.h\"\n#include \"mitkInteractionConst.h\"\n#include \"mitkAction.h\"\n\nvoid mitk::DisplayVectorInteractor::ExecuteOperation(Operation* itkNotUsed( operation ) )\n{\n \/*DisplayCoordinateOperation* dcOperation = static_cast<DisplayCoordinateOperation*>(operation);\n if(dcOperation==NULL) return;\n \n switch(operation->GetOperationType())\n {\n case OpSELECTPOINT:\n m_Sender=dcOperation->GetRenderer();\n m_StartDisplayCoordinate=dcOperation->GetStartDisplayCoordinate();\n m_LastDisplayCoordinate=dcOperation->GetLastDisplayCoordinate();\n m_CurrentDisplayCoordinate=dcOperation->GetCurrentDisplayCoordinate();\n\/\/ MITK_INFO << m_CurrentDisplayCoordinate << std::endl;\n \n MITK_INFO<<\"Message from DisplayVectorInteractor.cpp::ExecuteOperation() : \"\n << \"StartDisplayCoordinate:\" << m_StartDisplayCoordinate \n << \"LastDisplayCoordinate:\" << m_LastDisplayCoordinate \n << \"CurrentDisplayCoordinate:\" << m_CurrentDisplayCoordinate \n << std::endl;\n \n break;\n }*\/\n \n}\n\nbool mitk::DisplayVectorInteractor::ExecuteAction(Action* action, mitk::StateEvent const* stateEvent)\n{\n bool ok=false;\n \n const DisplayPositionEvent* posEvent=dynamic_cast<const DisplayPositionEvent*>(stateEvent->GetEvent());\n if(posEvent==NULL) return false;\n\n int actionId = action->GetActionId();\n \/\/initzoom and initmove is the same!\n if (actionId == AcINITZOOM)\n actionId = AcINITMOVE;\n switch(actionId)\n {\n \/\/case 0:\n \/\/ {\n \/\/ DisplayCoordinateOperation* doOp = new mitk::DisplayCoordinateOperation(OpTEST, posEvent->GetSender(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition());\n \/\/ if (m_UndoEnabled) \/\/write to UndoMechanism\n \/\/ {\n \/\/ DisplayCoordinateOperation* undoOp = new DisplayCoordinateOperation(OpTEST, m_Sender, m_StartDisplayCoordinate, m_LastDisplayCoordinate, m_CurrentDisplayCoordinate);\n \/\/ \n \/\/ \n \/\/ OperationEvent *operationEvent = new OperationEvent(this, doOp, undoOp);\n \/\/ m_UndoController->SetOperationEvent(operationEvent);\n \/\/ }\n \/\/ \n \/\/ \/\/execute the Operation\n \/\/ m_Destination->ExecuteOperation(doOp);\n \/\/ ok = true;\n \/\/ break;\n \/\/ }\n case AcSENDCOORDINATES:\n {\n DisplayCoordinateOperation* doOp = new mitk::DisplayCoordinateOperation(OpSENDCOORDINATES, posEvent->GetSender(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition());\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n case AcINITMOVE:\n {\n m_Sender=posEvent->GetSender();\n\n mitk::Vector2D origin = m_Sender->GetDisplayGeometry()->GetOriginInMM();\n double scaleFactorMMPerDisplayUnit = m_Sender->GetDisplayGeometry()->GetScaleFactorMMPerDisplayUnit();\n\n m_StartDisplayCoordinate=posEvent->GetDisplayPosition();\n m_LastDisplayCoordinate=posEvent->GetDisplayPosition();\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n m_StartCoordinateInMM=mitk::Point2D( ( origin+m_StartDisplayCoordinate.GetVectorFromOrigin()*scaleFactorMMPerDisplayUnit ).GetDataPointer() );\n ok = true;\n break; if (m_UndoEnabled) \/\/write to UndoMechanism\n {\n \/\/ DisplayCoordinateOperation* doOp = new mitk::DisplayCoordinateOperation(OpMOVE, m_Sender, m_StartDisplayCoordinate, m_StartDisplayCoordinate, posEvent->GetDisplayPosition());\n \/\/DisplayCoordinateOperation* undoOp = new mitk::DisplayCoordinateOperation(OpMOVE, posEvent->GetSender(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition(), m_StartDisplayCoordinate);\n\n \/\/OperationEvent *operationEvent = new OperationEvent(m_Destination, doOp, undoOp, \"Move view\");\n \/\/ m_UndoController->SetOperationEvent(operationEvent);\n }\n }\n case AcMOVE:\n {\n DisplayCoordinateOperation* doOp = new DisplayCoordinateOperation(OpMOVE, m_Sender, m_StartDisplayCoordinate, m_CurrentDisplayCoordinate, posEvent->GetDisplayPosition());\n \/\/make Operation\n m_LastDisplayCoordinate=m_CurrentDisplayCoordinate;\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n \n \/\/execute the Operation\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n case AcFINISHMOVE:\n { \n ok = true;\n break;\n }\n case AcZOOM:\n {\n DisplayCoordinateOperation* doOp = new DisplayCoordinateOperation(OpZOOM, m_Sender, m_StartDisplayCoordinate, m_LastDisplayCoordinate, posEvent->GetDisplayPosition(),m_StartCoordinateInMM);\n \n \/\/make Operation\n m_LastDisplayCoordinate=m_CurrentDisplayCoordinate;\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n \/\/MITK_INFO << m_CurrentDisplayCoordinate << std::endl;\n \n \/\/execute the Operation\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n default:\n ok = false;\n break;\n }\n return ok;\n}\n\nmitk::DisplayVectorInteractor::DisplayVectorInteractor(const char * type, mitk::OperationActor* destination)\n : mitk::StateMachine(type), m_Sender(NULL), m_Destination(destination)\n{\n m_StartDisplayCoordinate.Fill(0);\n m_LastDisplayCoordinate.Fill(0);\n m_CurrentDisplayCoordinate.Fill(0);\n\n if(m_Destination==NULL)\n m_Destination=this;\n}\n\n\nmitk::DisplayVectorInteractor::~DisplayVectorInteractor()\n{\n}\n\n<commit_msg>clean up<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center, \nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without \neven the implied warranty of MERCHANTABILITY or FITNESS FOR \nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#include \"mitkDisplayVectorInteractor.h\"\n#include \"mitkOperation.h\"\n#include \"mitkDisplayCoordinateOperation.h\"\n#include \"mitkDisplayPositionEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkStateEvent.h\"\n#include \"mitkInteractionConst.h\"\n#include \"mitkAction.h\"\n\nvoid mitk::DisplayVectorInteractor::ExecuteOperation(Operation* itkNotUsed( operation ) )\n{\n \/*DisplayCoordinateOperation* dcOperation = static_cast<DisplayCoordinateOperation*>(operation);\n if(dcOperation==NULL) return;\n \n switch(operation->GetOperationType())\n {\n case OpSELECTPOINT:\n m_Sender=dcOperation->GetRenderer();\n m_StartDisplayCoordinate=dcOperation->GetStartDisplayCoordinate();\n m_LastDisplayCoordinate=dcOperation->GetLastDisplayCoordinate();\n m_CurrentDisplayCoordinate=dcOperation->GetCurrentDisplayCoordinate();\n\/\/ MITK_INFO << m_CurrentDisplayCoordinate << std::endl;\n \n MITK_INFO<<\"Message from DisplayVectorInteractor.cpp::ExecuteOperation() : \"\n << \"StartDisplayCoordinate:\" << m_StartDisplayCoordinate \n << \"LastDisplayCoordinate:\" << m_LastDisplayCoordinate \n << \"CurrentDisplayCoordinate:\" << m_CurrentDisplayCoordinate \n << std::endl;\n \n break;\n }*\/\n \n}\n\nbool mitk::DisplayVectorInteractor::ExecuteAction(Action* action, mitk::StateEvent const* stateEvent)\n{\n bool ok=false;\n \n const DisplayPositionEvent* posEvent=dynamic_cast<const DisplayPositionEvent*>(stateEvent->GetEvent());\n if(posEvent==NULL) return false;\n\n int actionId = action->GetActionId();\n \/\/initzoom and initmove is the same!\n if (actionId == AcINITZOOM)\n actionId = AcINITMOVE;\n switch(actionId)\n {\n \/\/case 0:\n \/\/ {\n \/\/ DisplayCoordinateOperation* doOp = new mitk::DisplayCoordinateOperation(OpTEST, posEvent->GetSender(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition());\n \/\/\n \/\/ \/\/execute the Operation\n \/\/ m_Destination->ExecuteOperation(doOp);\n \/\/ ok = true;\n \/\/ break;\n \/\/ }\n case AcSENDCOORDINATES:\n {\n DisplayCoordinateOperation* doOp = new mitk::DisplayCoordinateOperation(OpSENDCOORDINATES, posEvent->GetSender(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition(), posEvent->GetDisplayPosition());\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n case AcINITMOVE:\n {\n m_Sender=posEvent->GetSender();\n\n mitk::Vector2D origin = m_Sender->GetDisplayGeometry()->GetOriginInMM();\n double scaleFactorMMPerDisplayUnit = m_Sender->GetDisplayGeometry()->GetScaleFactorMMPerDisplayUnit();\n\n m_StartDisplayCoordinate=posEvent->GetDisplayPosition();\n m_LastDisplayCoordinate=posEvent->GetDisplayPosition();\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n m_StartCoordinateInMM=mitk::Point2D( ( origin+m_StartDisplayCoordinate.GetVectorFromOrigin()*scaleFactorMMPerDisplayUnit ).GetDataPointer() );\n ok = true;\n break;\n }\n case AcMOVE:\n {\n DisplayCoordinateOperation* doOp = new DisplayCoordinateOperation(OpMOVE, m_Sender, m_StartDisplayCoordinate, m_CurrentDisplayCoordinate, posEvent->GetDisplayPosition());\n \/\/make Operation\n m_LastDisplayCoordinate=m_CurrentDisplayCoordinate;\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n \n \/\/execute the Operation\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n case AcFINISHMOVE:\n { \n ok = true;\n break;\n }\n case AcZOOM:\n {\n DisplayCoordinateOperation* doOp = new DisplayCoordinateOperation(OpZOOM, m_Sender, m_StartDisplayCoordinate, m_LastDisplayCoordinate, posEvent->GetDisplayPosition(),m_StartCoordinateInMM);\n \n \/\/make Operation\n m_LastDisplayCoordinate=m_CurrentDisplayCoordinate;\n m_CurrentDisplayCoordinate=posEvent->GetDisplayPosition();\n \/\/MITK_INFO << m_CurrentDisplayCoordinate << std::endl;\n \n \/\/execute the Operation\n m_Destination->ExecuteOperation(doOp);\n ok = true;\n break;\n }\n default:\n ok = false;\n break;\n }\n return ok;\n}\n\nmitk::DisplayVectorInteractor::DisplayVectorInteractor(const char * type, mitk::OperationActor* destination)\n : mitk::StateMachine(type), m_Sender(NULL), m_Destination(destination)\n{\n m_StartDisplayCoordinate.Fill(0);\n m_LastDisplayCoordinate.Fill(0);\n m_CurrentDisplayCoordinate.Fill(0);\n\n if(m_Destination==NULL)\n m_Destination=this;\n}\n\n\nmitk::DisplayVectorInteractor::~DisplayVectorInteractor()\n{\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <pangolin\/pangolin.h>\n#include <pangolin\/video\/video_record_repeat.h>\n#include <pangolin\/gl\/gltexturecache.h>\n#include <pangolin\/gl\/glpixformat.h>\n\ntemplate<typename T>\nstd::pair<float,float> GetOffsetScale(const pangolin::Image<unsigned char>& img, float type_max, float format_max)\n{\n std::pair<float,float> mm(std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());\n for(size_t i=0; i < img.Area(); ++i) {\n const T val = ((T*)img.ptr)[i];\n if(val != 0) {\n if(val < mm.first) mm.first = val;\n if(val > mm.second) mm.second = val;\n }\n }\n\n const float type_scale = format_max \/ type_max;\n const float offset = -type_scale* mm.first;\n const float scale = type_max \/ (mm.second - mm.first);\n return std::pair<float,float>(offset, scale);\n}\n\nvoid VideoViewer(const std::string& input_uri, const std::string& output_uri)\n{\n \/\/ Open Video by URI\n pangolin::VideoRecordRepeat video(input_uri, output_uri);\n int total_frames = std::numeric_limits<int>::max();\n\n if(video.Streams().size() == 0) {\n pango_print_error(\"No video streams from device.\\n\");\n return;\n }\n\n \/\/ Check if video supports VideoPlaybackInterface\n pangolin::VideoPlaybackInterface* video_playback = video.Cast<pangolin::VideoPlaybackInterface>();\n if( video_playback ) {\n total_frames = video_playback->GetTotalFrames();\n std::cout << \"Video length: \" << total_frames << \" frames\" << std::endl;\n }\n\n std::vector<unsigned char> buffer;\n buffer.resize(video.SizeBytes()+1);\n\n \/\/ Create OpenGL window - guess sensible dimensions\n pangolin::CreateWindowAndBind( \"VideoViewer\",\n video.Width() * video.Streams().size(), video.Height()\n );\n\n \/\/ Setup resizable views for video streams\n std::vector<pangolin::GlPixFormat> glfmt;\n std::vector<std::pair<float,float> > gloffsetscale;\n\n pangolin::DisplayBase().SetLayout(pangolin::LayoutEqual);\n for(unsigned int d=0; d < video.Streams().size(); ++d) {\n pangolin::View& view = pangolin::CreateDisplay().SetAspect(video.Streams()[d].Aspect());\n pangolin::DisplayBase().AddDisplay(view);\n glfmt.push_back(pangolin::GlPixFormat(video.Streams()[d].PixFormat()));\n gloffsetscale.push_back(std::pair<float,float>(0.0f, 1.0f) );\n }\n\n int frame = 0;\n pangolin::Var<int> max_frame(\"max_frame\", total_frames );\n pangolin::Var<bool> linear_sampling(\"linear_sampling\", true );\n\n std::vector<pangolin::Image<unsigned char> > images;\n\n#ifdef CALLEE_HAS_CPP11\n const int FRAME_SKIP = 30;\n\n \/\/ Show\/hide streams\n for(size_t v=0; v < pangolin::DisplayBase().NumChildren() && v < 9; v++) {\n pangolin::RegisterKeyPressCallback('1'+v, [v](){\n pangolin::DisplayBase()[v].ToggleShow();\n } );\n }\n\n pangolin::RegisterKeyPressCallback('r', [&](){\n if(!video.IsRecording()) {\n video.Record();\n pango_print_info(\"Started Recording.\\n\");\n }else{\n video.Stop();\n pango_print_info(\"Finished recording.\\n\");\n }\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback('p', [&](){\n video.Play();\n max_frame = std::numeric_limits<int>::max();\n pango_print_info(\"Playing from file log.\\n\");\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback('s', [&](){\n video.Source();\n max_frame = std::numeric_limits<int>::max();\n pango_print_info(\"Playing from source input.\\n\");\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback(' ', [&](){\n max_frame = (frame < max_frame) ? frame : std::numeric_limits<int>::max();\n });\n pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_LEFT, [&](){\n if(video_playback) {\n const int frame = std::min(video_playback->GetCurrentFrameId()-FRAME_SKIP, video_playback->GetTotalFrames()-1);\n video_playback->Seek(frame);\n }else{\n \/\/ We can't go backwards\n }\n });\n pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_RIGHT, [&](){\n if(video_playback) {\n const int frame = std::max(video_playback->GetCurrentFrameId()+FRAME_SKIP, 0);\n video_playback->Seek(frame);\n }else{\n \/\/ Pause at this frame\n max_frame = frame+1;\n }\n });\n pangolin::RegisterKeyPressCallback('l', [&](){ linear_sampling = true; });\n pangolin::RegisterKeyPressCallback('n', [&](){ linear_sampling = false; });\n\n pangolin::RegisterKeyPressCallback('a', [&](){\n \/\/ Adapt scale\n for(unsigned int i=0; i<images.size(); ++i) {\n if(pangolin::DisplayBase()[i].HasFocus()) {\n std::pair<float,float> os(0.0f, 1.0f);\n if(glfmt[i].gltype == GL_UNSIGNED_BYTE) {\n os = GetOffsetScale<unsigned char>(images[i], 255.0f, 1.0f);\n }else if(glfmt[i].gltype == GL_UNSIGNED_SHORT) {\n os = GetOffsetScale<unsigned short>(images[i], 65535.0f, 1.0f);\n }else if(glfmt[i].gltype == GL_FLOAT) {\n os = GetOffsetScale<float>(images[i], 1.0f, 1.0f);\n }\n gloffsetscale[i] = os;\n }\n }\n });\n#endif\n\n\n \/\/ Stream and display video\n while(!pangolin::ShouldQuit())\n {\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n glColor3f(1.0f, 1.0f, 1.0f);\n\n if (frame == 0 || frame < max_frame) {\n if (video.Grab(&buffer[0], images) ){\n ++frame;\n }\n }\n\n for(unsigned int i=0; i<images.size(); ++i)\n {\n if(pangolin::DisplayBase()[i].IsShown()) {\n pangolin::DisplayBase()[i].Activate();\n const std::pair<float,float> os = gloffsetscale[i];\n pangolin::GlSlUtilities::OffsetAndScale(os.first, os.second);\n pangolin::RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);\n pangolin::GlSlUtilities::UseNone();\n }\n }\n\n pangolin::FinishFrame();\n }\n}\n\n\nint main( int argc, char* argv[] )\n{\n const std::string dflt_output_uri = \"pango:\/\/video.pango\";\n\n if( argc > 1 ) {\n const std::string input_uri = std::string(argv[1]);\n const std::string output_uri = (argc > 2) ? std::string(argv[2]) : dflt_output_uri;\n try{\n VideoViewer(input_uri, output_uri);\n } catch (pangolin::VideoException e) {\n std::cout << e.what() << std::endl;\n }\n }else{\n const std::string input_uris[] = {\n \"dc1394:[fps=30,dma=10,size=640x480,iso=400]\/\/0\",\n \"convert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video0\",\n \"convert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video1\",\n \"openni:[img1=rgb]\/\/\",\n \"test:[size=160x120,n=1,fmt=RGB24]\/\/\"\n \"\"\n };\n\n std::cout << \"Usage : VideoViewer [video-uri]\" << std::endl << std::endl;\n std::cout << \"Where video-uri describes a stream or file resource, e.g.\" << std::endl;\n std::cout << \"\\tfile:[realtime=1]\/\/\/home\/user\/video\/movie.pvn\" << std::endl;\n std::cout << \"\\tfile:\/\/\/home\/user\/video\/movie.avi\" << std::endl;\n std::cout << \"\\tfiles:\/\/\/home\/user\/seqiemce\/foo%03d.jpeg\" << std::endl;\n std::cout << \"\\tdc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]\/\/0\" << std::endl;\n std::cout << \"\\tdc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]\/\/0\" << std::endl;\n std::cout << \"\\tv4l:\/\/\/dev\/video0\" << std::endl;\n std::cout << \"\\tconvert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video0\" << std::endl;\n std::cout << \"\\tmjpeg:\/\/http:\/\/127.0.0.1\/?action=stream\" << std::endl;\n std::cout << \"\\topenni:[img1=rgb]\/\/\" << std::endl;\n std::cout << std::endl;\n\n \/\/ Try to open some video device\n for(int i=0; !input_uris[i].empty(); ++i )\n {\n try{\n pango_print_info(\"Trying: %s\\n\", input_uris[i].c_str());\n VideoViewer(input_uris[i], dflt_output_uri);\n return 0;\n }catch(pangolin::VideoException) { }\n }\n }\n\n return 0;\n}\n<commit_msg>VideoViewer: Assume packed video data unless otherwise specified.<commit_after>#include <pangolin\/pangolin.h>\n#include <pangolin\/video\/video_record_repeat.h>\n#include <pangolin\/gl\/gltexturecache.h>\n#include <pangolin\/gl\/glpixformat.h>\n\ntemplate<typename T>\nstd::pair<float,float> GetOffsetScale(const pangolin::Image<unsigned char>& img, float type_max, float format_max)\n{\n std::pair<float,float> mm(std::numeric_limits<float>::max(), -std::numeric_limits<float>::max());\n for(size_t i=0; i < img.Area(); ++i) {\n const T val = ((T*)img.ptr)[i];\n if(val != 0) {\n if(val < mm.first) mm.first = val;\n if(val > mm.second) mm.second = val;\n }\n }\n\n const float type_scale = format_max \/ type_max;\n const float offset = -type_scale* mm.first;\n const float scale = type_max \/ (mm.second - mm.first);\n return std::pair<float,float>(offset, scale);\n}\n\nvoid VideoViewer(const std::string& input_uri, const std::string& output_uri)\n{\n \/\/ Open Video by URI\n pangolin::VideoRecordRepeat video(input_uri, output_uri);\n int total_frames = std::numeric_limits<int>::max();\n\n if(video.Streams().size() == 0) {\n pango_print_error(\"No video streams from device.\\n\");\n return;\n }\n\n \/\/ Check if video supports VideoPlaybackInterface\n pangolin::VideoPlaybackInterface* video_playback = video.Cast<pangolin::VideoPlaybackInterface>();\n if( video_playback ) {\n total_frames = video_playback->GetTotalFrames();\n std::cout << \"Video length: \" << total_frames << \" frames\" << std::endl;\n }\n\n std::vector<unsigned char> buffer;\n buffer.resize(video.SizeBytes()+1);\n\n \/\/ Create OpenGL window - guess sensible dimensions\n pangolin::CreateWindowAndBind( \"VideoViewer\",\n video.Width() * video.Streams().size(), video.Height()\n );\n\n \/\/ Assume packed OpenGL data unless otherwise specified\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glPixelStorei(GL_PACK_ALIGNMENT, 1);\n\n \/\/ Setup resizable views for video streams\n std::vector<pangolin::GlPixFormat> glfmt;\n std::vector<std::pair<float,float> > gloffsetscale;\n\n pangolin::DisplayBase().SetLayout(pangolin::LayoutEqual);\n for(unsigned int d=0; d < video.Streams().size(); ++d) {\n pangolin::View& view = pangolin::CreateDisplay().SetAspect(video.Streams()[d].Aspect());\n pangolin::DisplayBase().AddDisplay(view);\n glfmt.push_back(pangolin::GlPixFormat(video.Streams()[d].PixFormat()));\n gloffsetscale.push_back(std::pair<float,float>(0.0f, 1.0f) );\n }\n\n int frame = 0;\n pangolin::Var<int> max_frame(\"max_frame\", total_frames );\n pangolin::Var<bool> linear_sampling(\"linear_sampling\", true );\n\n std::vector<pangolin::Image<unsigned char> > images;\n\n#ifdef CALLEE_HAS_CPP11\n const int FRAME_SKIP = 30;\n\n \/\/ Show\/hide streams\n for(size_t v=0; v < pangolin::DisplayBase().NumChildren() && v < 9; v++) {\n pangolin::RegisterKeyPressCallback('1'+v, [v](){\n pangolin::DisplayBase()[v].ToggleShow();\n } );\n }\n\n pangolin::RegisterKeyPressCallback('r', [&](){\n if(!video.IsRecording()) {\n video.Record();\n pango_print_info(\"Started Recording.\\n\");\n }else{\n video.Stop();\n pango_print_info(\"Finished recording.\\n\");\n }\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback('p', [&](){\n video.Play();\n max_frame = std::numeric_limits<int>::max();\n pango_print_info(\"Playing from file log.\\n\");\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback('s', [&](){\n video.Source();\n max_frame = std::numeric_limits<int>::max();\n pango_print_info(\"Playing from source input.\\n\");\n fflush(stdout);\n });\n pangolin::RegisterKeyPressCallback(' ', [&](){\n max_frame = (frame < max_frame) ? frame : std::numeric_limits<int>::max();\n });\n pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_LEFT, [&](){\n if(video_playback) {\n const int frame = std::min(video_playback->GetCurrentFrameId()-FRAME_SKIP, video_playback->GetTotalFrames()-1);\n video_playback->Seek(frame);\n }else{\n \/\/ We can't go backwards\n }\n });\n pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_RIGHT, [&](){\n if(video_playback) {\n const int frame = std::max(video_playback->GetCurrentFrameId()+FRAME_SKIP, 0);\n video_playback->Seek(frame);\n }else{\n \/\/ Pause at this frame\n max_frame = frame+1;\n }\n });\n pangolin::RegisterKeyPressCallback('l', [&](){ linear_sampling = true; });\n pangolin::RegisterKeyPressCallback('n', [&](){ linear_sampling = false; });\n\n pangolin::RegisterKeyPressCallback('a', [&](){\n \/\/ Adapt scale\n for(unsigned int i=0; i<images.size(); ++i) {\n if(pangolin::DisplayBase()[i].HasFocus()) {\n std::pair<float,float> os(0.0f, 1.0f);\n if(glfmt[i].gltype == GL_UNSIGNED_BYTE) {\n os = GetOffsetScale<unsigned char>(images[i], 255.0f, 1.0f);\n }else if(glfmt[i].gltype == GL_UNSIGNED_SHORT) {\n os = GetOffsetScale<unsigned short>(images[i], 65535.0f, 1.0f);\n }else if(glfmt[i].gltype == GL_FLOAT) {\n os = GetOffsetScale<float>(images[i], 1.0f, 1.0f);\n }\n gloffsetscale[i] = os;\n }\n }\n });\n#endif\n\n\n \/\/ Stream and display video\n while(!pangolin::ShouldQuit())\n {\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n glColor3f(1.0f, 1.0f, 1.0f);\n\n if (frame == 0 || frame < max_frame) {\n if (video.Grab(&buffer[0], images) ){\n ++frame;\n }\n }\n\n for(unsigned int i=0; i<images.size(); ++i)\n {\n if(pangolin::DisplayBase()[i].IsShown()) {\n pangolin::DisplayBase()[i].Activate();\n const std::pair<float,float> os = gloffsetscale[i];\n pangolin::GlSlUtilities::OffsetAndScale(os.first, os.second);\n pangolin::RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);\n pangolin::GlSlUtilities::UseNone();\n }\n }\n\n pangolin::FinishFrame();\n }\n}\n\n\nint main( int argc, char* argv[] )\n{\n const std::string dflt_output_uri = \"pango:\/\/video.pango\";\n\n if( argc > 1 ) {\n const std::string input_uri = std::string(argv[1]);\n const std::string output_uri = (argc > 2) ? std::string(argv[2]) : dflt_output_uri;\n try{\n VideoViewer(input_uri, output_uri);\n } catch (pangolin::VideoException e) {\n std::cout << e.what() << std::endl;\n }\n }else{\n const std::string input_uris[] = {\n \"dc1394:[fps=30,dma=10,size=640x480,iso=400]\/\/0\",\n \"convert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video0\",\n \"convert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video1\",\n \"openni:[img1=rgb]\/\/\",\n \"test:[size=160x120,n=1,fmt=RGB24]\/\/\"\n \"\"\n };\n\n std::cout << \"Usage : VideoViewer [video-uri]\" << std::endl << std::endl;\n std::cout << \"Where video-uri describes a stream or file resource, e.g.\" << std::endl;\n std::cout << \"\\tfile:[realtime=1]\/\/\/home\/user\/video\/movie.pvn\" << std::endl;\n std::cout << \"\\tfile:\/\/\/home\/user\/video\/movie.avi\" << std::endl;\n std::cout << \"\\tfiles:\/\/\/home\/user\/seqiemce\/foo%03d.jpeg\" << std::endl;\n std::cout << \"\\tdc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]\/\/0\" << std::endl;\n std::cout << \"\\tdc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]\/\/0\" << std::endl;\n std::cout << \"\\tv4l:\/\/\/dev\/video0\" << std::endl;\n std::cout << \"\\tconvert:[fmt=RGB24]\/\/v4l:\/\/\/dev\/video0\" << std::endl;\n std::cout << \"\\tmjpeg:\/\/http:\/\/127.0.0.1\/?action=stream\" << std::endl;\n std::cout << \"\\topenni:[img1=rgb]\/\/\" << std::endl;\n std::cout << std::endl;\n\n \/\/ Try to open some video device\n for(int i=0; !input_uris[i].empty(); ++i )\n {\n try{\n pango_print_info(\"Trying: %s\\n\", input_uris[i].c_str());\n VideoViewer(input_uris[i], dflt_output_uri);\n return 0;\n }catch(pangolin::VideoException) { }\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ex13_42_TextQuery.h\"\n#include <sstream>\n#include <algorithm>\n\nusing std::string;\n\nTextQuery::TextQuery(std::ifstream& ifs) : input(new StrVec)\n{\n size_t lineNo = 0;\n for (string line; std::getline(ifs, line); ++lineNo) {\n input->push_back(line);\n std::istringstream line_stream(line);\n for (string text, word; line_stream >> text; word.clear()) {\n \/\/ avoid read a word followed by punctuation(such as: word, )\n std::remove_copy_if(text.begin(), text.end(),\n std::back_inserter(word), ispunct);\n \/\/ use reference avoid count of shared_ptr add.\n auto& nos = result[word];\n if (!nos) nos.reset(new std::set<size_t>);\n nos->insert(lineNo);\n }\n }\n}\n\nQueryResult TextQuery::query(const string& str) const\n{\n \/\/ use static just allocate once.\n static std::shared_ptr<std::set<size_t>> nodate(new std::set<size_t>);\n auto found = result.find(str);\n if (found == result.end())\n return QueryResult(str, nodate, input);\n else\n return QueryResult(str, found->second, input);\n}\n\nstd::ostream& print(std::ostream& out, const QueryResult& qr)\n{\n out << qr.word << \" occurs \" << qr.nos->size()\n << (qr.nos->size() > 1 ? \" times\" : \" time\") << std::endl;\n for (auto i : *qr.nos)\n out << \"\\t(line \" << i + 1 << \") \" << qr.input->at(i) << std::endl;\n return out;\n}\n<commit_msg>Update ex13_42_TextQuery.cpp<commit_after>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cstddef>\n#include <algorithm>\n#include <iterator>\n#include <cctype>\n#include \"ex13_40.h\"\n#include \"ex12_27_30.h\"\n\nusing namespace std;\n\nTextQuery::TextQuery(ifstream &is):file(new StrVec)\n{\n string line;\n while(getline(is, line))\n {\n file->push_back(line);\n int n=file->size()-1;\n istringstream in(line);\n string text, word;\n while(in>>text)\n {\n \/\/avoid read a word followed by punctuation(such as: word,)\n remove_copy_if(text.begin(), text.end(), back_inserter(word), [](const char &ch) {return ispunct(ch);});\n auto &lines=wm[word];\n if(!lines)\n lines.reset(new set<size_t>);\n lines->insert(n);\n word.clear();\n }\n }\n}\n\nQueryResult TextQuery::query(const string &sought) const\n{\n \/\/use static just allocate once\n static shared_ptr<set<size_t>> nodata(new set<size_t>);\n\n auto loc=wm.find(sought);\n if(loc==wm.end())\n return QueryResult(sought, nodata, file);\n else\n return QueryResult(sought, loc->second, file);\n}\n\nostream &print(ostream &os, const QueryResult &qr)\n{\n os<<qr.sought<<\" occurs \"<<qr.lines->size()<<(qr.lines->size()>1 ? \" times\" : \" time\")<<endl;\n for(auto num : *qr.lines)\n os<<\"\\t(line \"<<num+1<<\") \"<<qr.file->at(num)<<endl;\n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppElement.h\"\n#include \"QXmppUtils.h\"\n\n#include <QDomElement>\n\nclass QXmppElementPrivate\n{\npublic:\n QXmppElementPrivate();\n QXmppElementPrivate(const QDomElement &element);\n ~QXmppElementPrivate();\n\n QAtomicInt counter;\n\n QXmppElementPrivate *parent;\n QMap<QString, QString> attributes;\n QList<QXmppElementPrivate*> children;\n QString name;\n QString value;\n};\n\nQXmppElementPrivate::QXmppElementPrivate()\n : counter(1), parent(NULL)\n{\n}\n\nQXmppElementPrivate::QXmppElementPrivate(const QDomElement &element)\n : counter(1), parent(NULL)\n{\n if (element.isNull())\n return;\n\n name = element.tagName();\n QString xmlns = element.namespaceURI();\n QString parentns = element.parentNode().namespaceURI();\n if (!xmlns.isEmpty() && xmlns != parentns)\n attributes.insert(\"xmlns\", xmlns);\n QDomNamedNodeMap attrs = element.attributes();\n for (int i = 0; i < attrs.size(); i++)\n {\n QDomAttr attr = attrs.item(i).toAttr();\n attributes.insert(attr.name(), attr.value());\n }\n\n QDomNode childNode = element.firstChild();\n while (!childNode.isNull())\n {\n if (childNode.isElement())\n {\n QXmppElementPrivate *child = new QXmppElementPrivate(childNode.toElement());\n child->parent = this;\n children.append(child);\n } else if (childNode.isText()) {\n value += childNode.toText().data();\n }\n childNode = childNode.nextSibling();\n }\n}\n\nQXmppElementPrivate::~QXmppElementPrivate()\n{\n foreach (QXmppElementPrivate *child, children)\n if (!child->counter.deref())\n delete child;\n}\n\nQXmppElement::QXmppElement()\n{\n d = new QXmppElementPrivate();\n}\n\nQXmppElement::QXmppElement(const QXmppElement &other)\n{\n other.d->counter.ref();\n d = other.d;\n}\n\nQXmppElement::QXmppElement(QXmppElementPrivate *other)\n{\n other->counter.ref();\n d = other;\n}\n\nQXmppElement::QXmppElement(const QDomElement &element)\n{\n d = new QXmppElementPrivate(element);\n}\n\nQXmppElement::~QXmppElement()\n{\n if (!d->counter.deref())\n delete d;\n}\n\nQXmppElement &QXmppElement::operator=(const QXmppElement &other)\n{\n other.d->counter.ref();\n if (!d->counter.deref())\n delete d;\n d = other.d;\n return *this;\n}\n\nQStringList QXmppElement::attributeNames() const\n{\n return d->attributes.keys();\n}\n\nQString QXmppElement::attribute(const QString &name) const\n{\n return d->attributes.value(name);\n}\n\nvoid QXmppElement::setAttribute(const QString &name, const QString &value)\n{\n d->attributes.insert(name, value);\n}\n\nvoid QXmppElement::appendChild(const QXmppElement &child)\n{\n if (child.d->parent == d)\n return;\n\n if (child.d->parent)\n child.d->parent->children.removeAll(child.d);\n else\n child.d->counter.ref();\n d->children.append(child.d);\n}\n\nQXmppElement QXmppElement::firstChildElement(const QString &name) const\n{\n foreach (QXmppElementPrivate *child_d, d->children)\n if (name.isEmpty() || child_d->name == name)\n return QXmppElement(child_d);\n return QXmppElement();\n}\n\nQXmppElement QXmppElement::nextSiblingElement(const QString &name) const\n{\n if (!d->parent)\n return QXmppElement();\n const QList<QXmppElementPrivate*> &siblings_d = d->parent->children;\n for (int i = siblings_d.indexOf(d) + 1; i < siblings_d.size(); i++)\n if (name.isEmpty() || siblings_d[i]->name == name)\n return QXmppElement(siblings_d[i]);\n return QXmppElement();\n}\n\nbool QXmppElement::isNull() const\n{\n return d->name.isEmpty();\n}\n\nvoid QXmppElement::removeChild(const QXmppElement &child)\n{\n if (child.d->parent != d)\n return;\n\n d->children.removeAll(child.d);\n child.d->counter.deref();\n child.d->parent = NULL;\n}\n\nQString QXmppElement::tagName() const\n{\n return d->name;\n}\n\nvoid QXmppElement::setTagName(const QString &tagName)\n{\n d->name = tagName;\n}\n\nQString QXmppElement::value() const\n{\n return d->value;\n}\n\nvoid QXmppElement::setValue(const QString &value)\n{\n d->value = value;\n}\n\nvoid QXmppElement::toXml(QXmlStreamWriter *writer) const\n{\n if (isNull())\n return;\n\n writer->writeStartElement(d->name);\n if (d->attributes.contains(\"xmlns\"))\n helperToXmlAddAttribute(writer, \"xmlns\", d->attributes.value(\"xmlns\"));\n foreach (const QString &attr, d->attributes.keys())\n if (attr != \"xmlns\")\n helperToXmlAddAttribute(writer, attr, d->attributes.value(attr));\n if (!d->value.isEmpty())\n writer->writeCharacters(d->value);\n foreach (const QXmppElement &child, d->children)\n child.toXml(writer);\n writer->writeEndElement();\n}\n\nQXmppElementList::QXmppElementList()\n{\n}\n\nQXmppElementList::QXmppElementList(const QXmppElement &element)\n{\n append(element);\n}\n\n\nQXmppElementList::QXmppElementList(const QList<QXmppElement> &other)\n : QList<QXmppElement>(other)\n{\n}\n\n<commit_msg>fix QXmppElement parenting so that nextSiblingElement() actually works<commit_after>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppElement.h\"\n#include \"QXmppUtils.h\"\n\n#include <QDomElement>\n\nclass QXmppElementPrivate\n{\npublic:\n QXmppElementPrivate();\n QXmppElementPrivate(const QDomElement &element);\n ~QXmppElementPrivate();\n\n QAtomicInt counter;\n\n QXmppElementPrivate *parent;\n QMap<QString, QString> attributes;\n QList<QXmppElementPrivate*> children;\n QString name;\n QString value;\n};\n\nQXmppElementPrivate::QXmppElementPrivate()\n : counter(1), parent(NULL)\n{\n}\n\nQXmppElementPrivate::QXmppElementPrivate(const QDomElement &element)\n : counter(1), parent(NULL)\n{\n if (element.isNull())\n return;\n\n name = element.tagName();\n QString xmlns = element.namespaceURI();\n QString parentns = element.parentNode().namespaceURI();\n if (!xmlns.isEmpty() && xmlns != parentns)\n attributes.insert(\"xmlns\", xmlns);\n QDomNamedNodeMap attrs = element.attributes();\n for (int i = 0; i < attrs.size(); i++)\n {\n QDomAttr attr = attrs.item(i).toAttr();\n attributes.insert(attr.name(), attr.value());\n }\n\n QDomNode childNode = element.firstChild();\n while (!childNode.isNull())\n {\n if (childNode.isElement())\n {\n QXmppElementPrivate *child = new QXmppElementPrivate(childNode.toElement());\n child->parent = this;\n children.append(child);\n } else if (childNode.isText()) {\n value += childNode.toText().data();\n }\n childNode = childNode.nextSibling();\n }\n}\n\nQXmppElementPrivate::~QXmppElementPrivate()\n{\n foreach (QXmppElementPrivate *child, children)\n if (!child->counter.deref())\n delete child;\n}\n\nQXmppElement::QXmppElement()\n{\n d = new QXmppElementPrivate();\n}\n\nQXmppElement::QXmppElement(const QXmppElement &other)\n{\n other.d->counter.ref();\n d = other.d;\n}\n\nQXmppElement::QXmppElement(QXmppElementPrivate *other)\n{\n other->counter.ref();\n d = other;\n}\n\nQXmppElement::QXmppElement(const QDomElement &element)\n{\n d = new QXmppElementPrivate(element);\n}\n\nQXmppElement::~QXmppElement()\n{\n if (!d->counter.deref())\n delete d;\n}\n\nQXmppElement &QXmppElement::operator=(const QXmppElement &other)\n{\n other.d->counter.ref();\n if (!d->counter.deref())\n delete d;\n d = other.d;\n return *this;\n}\n\nQStringList QXmppElement::attributeNames() const\n{\n return d->attributes.keys();\n}\n\nQString QXmppElement::attribute(const QString &name) const\n{\n return d->attributes.value(name);\n}\n\nvoid QXmppElement::setAttribute(const QString &name, const QString &value)\n{\n d->attributes.insert(name, value);\n}\n\nvoid QXmppElement::appendChild(const QXmppElement &child)\n{\n if (child.d->parent == d)\n return;\n\n if (child.d->parent)\n child.d->parent->children.removeAll(child.d);\n else\n child.d->counter.ref();\n child.d->parent = d;\n d->children.append(child.d);\n}\n\nQXmppElement QXmppElement::firstChildElement(const QString &name) const\n{\n foreach (QXmppElementPrivate *child_d, d->children)\n if (name.isEmpty() || child_d->name == name)\n return QXmppElement(child_d);\n return QXmppElement();\n}\n\nQXmppElement QXmppElement::nextSiblingElement(const QString &name) const\n{\n if (!d->parent)\n return QXmppElement();\n const QList<QXmppElementPrivate*> &siblings_d = d->parent->children;\n for (int i = siblings_d.indexOf(d) + 1; i < siblings_d.size(); i++)\n if (name.isEmpty() || siblings_d[i]->name == name)\n return QXmppElement(siblings_d[i]);\n return QXmppElement();\n}\n\nbool QXmppElement::isNull() const\n{\n return d->name.isEmpty();\n}\n\nvoid QXmppElement::removeChild(const QXmppElement &child)\n{\n if (child.d->parent != d)\n return;\n\n d->children.removeAll(child.d);\n child.d->counter.deref();\n child.d->parent = NULL;\n}\n\nQString QXmppElement::tagName() const\n{\n return d->name;\n}\n\nvoid QXmppElement::setTagName(const QString &tagName)\n{\n d->name = tagName;\n}\n\nQString QXmppElement::value() const\n{\n return d->value;\n}\n\nvoid QXmppElement::setValue(const QString &value)\n{\n d->value = value;\n}\n\nvoid QXmppElement::toXml(QXmlStreamWriter *writer) const\n{\n if (isNull())\n return;\n\n writer->writeStartElement(d->name);\n if (d->attributes.contains(\"xmlns\"))\n helperToXmlAddAttribute(writer, \"xmlns\", d->attributes.value(\"xmlns\"));\n foreach (const QString &attr, d->attributes.keys())\n if (attr != \"xmlns\")\n helperToXmlAddAttribute(writer, attr, d->attributes.value(attr));\n if (!d->value.isEmpty())\n writer->writeCharacters(d->value);\n foreach (const QXmppElement &child, d->children)\n child.toXml(writer);\n writer->writeEndElement();\n}\n\nQXmppElementList::QXmppElementList()\n{\n}\n\nQXmppElementList::QXmppElementList(const QXmppElement &element)\n{\n append(element);\n}\n\n\nQXmppElementList::QXmppElementList(const QList<QXmppElement> &other)\n : QList<QXmppElement>(other)\n{\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tCopyright (C) 2015-2016 Claude SIMON (http:\/\/q37.info\/contact\/).\n\n\tThis file is part of dmnzq.\n\n dmnzq is free software: you can redistribute it and\/or\n\tmodify it under the terms of the GNU Affero General Public License as\n\tpublished by the Free Software Foundation, either version 3 of the\n\tLicense, or (at your option) any later version.\n\n dmnzq is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\tAffero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with dmnzq. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n#include \"misc.h\"\n\n#include \"registry.h\"\n\n#include \"scltool.h\"\n#include \"sclerror.h\"\n\n#include \"csdlec.h\"\n\n#include \"err.h\"\n#include \"cio.h\"\n#include \"epsmsc.h\"\n#include \"xpp.h\"\n#include \"fnm.h\"\n#include \"flf.h\"\n#include \"plgn.h\"\n\nusing cio::CErr;\nusing cio::COut;\nusing cio::CIn;\n\n# define NAME_MC\t\t\t\"dmnzq\"\n# define NAME_LC\t\t\t\"dmnzq\"\n# define NAME_UC\t\t\t\"DMNZQ\"\n# define WEBSITE_URL\t\t\"http:\/\/q37.info\/\"\n# define AUTHOR_NAME\t\t\"Claude SIMON\"\n# define AUTHOR_CONTACT\t\t\"http:\/\/q37.info\/contact\/\"\n# define OWNER_NAME\t\t\t\"Claude SIMON\"\n# define OWNER_CONTACT\t\t\"http:\/\/q37.info\/contact\/\"\n# define COPYRIGHT\t\t\tCOPYRIGHT_YEARS \" \" OWNER_NAME \" (\" OWNER_CONTACT \")\"\t\n\nstatic void PrintHeader_( void )\n{\n\tCOut << NAME_MC \" V\" VERSION << \" (\" WEBSITE_URL \")\" << txf::nl;\n\tCOut << \"Copyright (C) \" COPYRIGHT << txf::nl;\n\tCOut << txf::pad << \"Build : \" __DATE__ \" \" __TIME__ << \" (\" << cpe::GetDescription() << ')' << txf::nl;\n}\n\nnamespace {\n\tusing misc::sModule;\n\n\tcsdlec::library_embedded_client_core__ *Core_ = NULL;\n\n\tvoid ExitFunction_( void )\n\t{\n\tqRH\n\t\tstr::string Message;\n\tqRB\n\t\tif ( Core_ != NULL ) {\n\t\t\tMessage.Init();\n\t\t\tCOut << sclmisc::GetBaseTranslation( \"TerminatingModule\", Message ) << txf::nl << txf::commit;\n\t\t\tdelete Core_;\n\t\t\tCOut << sclmisc::GetBaseTranslation( \"ModuleTerminated\", Message ) << txf::nl << txf::commit;\n\t\t}\n\n\t\tCore_ = NULL;\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid LoadModule_( const bso::char__ *ModuleFilename )\n\t{\n\tqRH\n\t\tlcl::locale SharedLocale;\n\t\trgstry::registry SharedRegistry;\n\t\tcsdlec::library_data__ LibraryData;\n\t\tlcl::meaning Meaning, MeaningBuffer;\n\t\tstr::string Translation;\n\t\terr::buffer__ ErrBuffer;\n\t\tsclmisc::sRack SCLRack;\n\tqRB\n\t\tSharedLocale.Init();\n\t\tSharedRegistry.Init();\n\n\t\tSCLRack.Init( *err::qRRor, *sclerror::SCLERRORError, cio::GetCurrentSet(), scllocale::GetRack() );\n\n\t\tLibraryData.Init( csdleo::cRegular, ModuleFilename, &SCLRack, csdleo::mRemote );\n\n\t\tif ( ( Core_ = new csdlec::library_embedded_client_core__ ) == NULL )\n\t\t\tqRAlc();\n\n\t\tif ( !Core_->Init( ModuleFilename, LibraryData, err::hUserDefined ) ) {\n\t\t\tMeaning.Init();\n\t\t\tMeaning.SetValue( \"UnableToLoadModule\" );\n\t\t\tMeaning.AddTag( ModuleFilename );\n\t\t\tsclerror::SetMeaning( Meaning );\n\t\t\tqRAbort();\n\t\t}\n\tqRR\n\t\tMeaning.Init();\n\t\tMeaning.SetValue( \"ModuleError\" );\n\t\tMeaning.AddTag( ModuleFilename );\n\n\t\tif ( ERRType >= err::t_amount ) {\n\t\t\tif ( sclerror::IsErrorPending() ) {\n\t\t\t\tMeaningBuffer.Init();\n\t\t\t\tMeaning.AddTag( sclerror::GetMeaning( MeaningBuffer ) );\n\t\t\t} else {\n\t\t\t\tTranslation.Init();\n\t\t\t\tMeaning.AddTag( sclmisc::GetBaseTranslation( \"UnkonwnError\", Translation ) );\n\t\t\t}\n\t\t} else {\n\t\t\tMeaning.AddTag( err::Message( ErrBuffer ) );\n\t\t}\n\n\t\tTranslation.Init();\n\t\tsclmisc::GetBaseTranslation( Meaning, Translation );\n\n\t\tcio::CErr << Translation << txf::nl << txf::commit;\n\tqRT\n\tqRE\n\t}\n\n\tusing misc::cHandler;\n\n\tvoid Process_(\n\t\tcHandler &Handler,\n\t\tsModule &Module )\n\t{\n\t\tHandler.Handle( Module );\n\t}\n\n\tvoid Process_( misc::sModule &Module )\n\t{\n\tqRH\n\t\tplgn::rRetriever<cHandler> Retriever;\n\t\tstr::wString PluginId, PluginArguments;\n\tqRB\n\t\tPluginId.Init();\n\t\tPluginArguments.Init();\n\t\tModule.Preferences( PluginId, PluginArguments );\n\n\t\tRetriever.Init();\n\n\t\tsclmisc::Plug( misc::SlotPluginTarget, PluginId, PluginArguments, NULL, Retriever );\n\n\t\tProcess_( Retriever.Plugin(), Module );\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid Process_( void )\n\t{\n\tqRH\n\t\tTOL_CBUFFER___ Buffer;\n\tqRB\n\t\tatexit( ExitFunction_ );\n\n\t\tcio::COut.Commit();\n\n\t\tLoadModule_( sclmisc::MGetValue( registry::Module, Buffer ) );\n\n\t\tProcess_( Core_->GetCallback() );\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid AboutPlugin_( void )\n\t{\n\tqRH\n\t\tplgn::rRetriever<cHandler> Retriever;\n\tqRB\n\t\tRetriever.Init();\n\n\t\tsclmisc::Plug( misc::SlotPluginTarget, NULL, Retriever );\n\n\t\tcio::COut << Retriever.About() << txf::nl << Retriever.Identifier() << txf::commit;\n\tqRR\n\tqRT\n\tqRE\n\t}\n}\n\n#define C( name )\\\n\telse if ( Command == #name )\\\n\t\tname##_()\n\nint scltool::SCLTOOLMain(\n\tconst str::string_ &Command,\n\tconst scltool::oddities__ &Oddities )\n{\n\tint ExitValue = EXIT_FAILURE;\nqRH\nqRB\n\tif ( Command == \"Version\" )\n\t\tPrintHeader_();\n\telse if ( Command == \"License\" )\n\t\tepsmsc::PrintLicense( NAME_MC );\n\tC( Process );\n\tC( AboutPlugin );\n\telse\n\t\tqRGnr();\n\n\tExitValue = EXIT_SUCCESS;\nqRR\nqRT\nqRE\n\treturn ExitValue;\n}\n\n#undef C\n\nconst char *sclmisc::SCLMISCTargetName = NAME_LC;\n\nQ37_GCTOR( dmnzq )\n{\n}<commit_msg>27\/03\/2016 11:40:43<commit_after>\/*\n\tCopyright (C) 2015-2016 Claude SIMON (http:\/\/q37.info\/contact\/).\n\n\tThis file is part of dmnzq.\n\n dmnzq is free software: you can redistribute it and\/or\n\tmodify it under the terms of the GNU Affero General Public License as\n\tpublished by the Free Software Foundation, either version 3 of the\n\tLicense, or (at your option) any later version.\n\n dmnzq is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\tAffero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with dmnzq. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n#include \"misc.h\"\n\n#include \"registry.h\"\n\n#include \"scltool.h\"\n#include \"sclerror.h\"\n\n#include \"csdlec.h\"\n\n#include \"err.h\"\n#include \"cio.h\"\n#include \"epsmsc.h\"\n#include \"xpp.h\"\n#include \"fnm.h\"\n#include \"flf.h\"\n#include \"plgn.h\"\n\nusing cio::CErr;\nusing cio::COut;\nusing cio::CIn;\n\n# define NAME_MC\t\t\t\"dmnzq\"\n# define NAME_LC\t\t\t\"dmnzq\"\n# define NAME_UC\t\t\t\"DMNZQ\"\n# define WEBSITE_URL\t\t\"http:\/\/q37.info\/\"\n# define AUTHOR_NAME\t\t\"Claude SIMON\"\n# define AUTHOR_CONTACT\t\t\"http:\/\/q37.info\/contact\/\"\n# define OWNER_NAME\t\t\t\"Claude SIMON\"\n# define OWNER_CONTACT\t\t\"http:\/\/q37.info\/contact\/\"\n# define COPYRIGHT\t\t\tCOPYRIGHT_YEARS \" \" OWNER_NAME \" (\" OWNER_CONTACT \")\"\t\n\nstatic void PrintHeader_( void )\n{\n\tCOut << NAME_MC \" V\" VERSION << \" (\" WEBSITE_URL \")\" << txf::nl;\n\tCOut << \"Copyright (C) \" COPYRIGHT << txf::nl;\n\tCOut << txf::pad << \"Build : \" __DATE__ \" \" __TIME__ << \" (\" << cpe::GetDescription() << ')' << txf::nl;\n}\n\nnamespace {\n\tusing misc::sModule;\n\n\tcsdlec::library_embedded_client_core__ *Core_ = NULL;\n\n\tvoid ExitFunction_( void )\n\t{\n\tqRH\n\t\tstr::string Message;\n\tqRB\n\t\tif ( Core_ != NULL ) {\n\t\t\tMessage.Init();\n\t\t\tCOut << sclmisc::GetBaseTranslation( \"TerminatingModule\", Message ) << txf::nl << txf::commit;\n\t\t\tdelete Core_;\n\t\t\tCOut << sclmisc::GetBaseTranslation( \"ModuleTerminated\", Message ) << txf::nl << txf::commit;\n\t\t}\n\n\t\tCore_ = NULL;\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid LoadModule_( const bso::char__ *ModuleFilename )\n\t{\n\tqRH\n\t\tlcl::locale SharedLocale;\n\t\trgstry::registry SharedRegistry;\n\t\tcsdlec::library_data__ LibraryData;\n\t\tlcl::meaning Meaning, MeaningBuffer;\n\t\tstr::string Translation;\n\t\terr::buffer__ ErrBuffer;\n\t\tsclmisc::sRack SCLRack;\n\tqRB\n\t\tSharedLocale.Init();\n\t\tSharedRegistry.Init();\n\n\t\tSCLRack.Init( *err::qRRor, *sclerror::SCLERRORError, cio::GetCurrentSet(), scllocale::GetRack() );\n\n\t\tLibraryData.Init( csdleo::cRegular, ModuleFilename, &SCLRack, csdleo::mRemote );\n\n\t\tif ( ( Core_ = new csdlec::library_embedded_client_core__ ) == NULL )\n\t\t\tqRAlc();\n\n\t\tif ( !Core_->Init( ModuleFilename, LibraryData, err::hUserDefined ) ) {\n\t\t\tMeaning.Init();\n\t\t\tMeaning.SetValue( \"UnableToLoadModule\" );\n\t\t\tMeaning.AddTag( ModuleFilename );\n\t\t\tsclerror::SetMeaning( Meaning );\n\t\t\tqRAbort();\n\t\t}\n\tqRR\n\t\tMeaning.Init();\n\t\tMeaning.SetValue( \"ModuleError\" );\n\t\tMeaning.AddTag( ModuleFilename );\n\n\t\tif ( ERRType >= err::t_amount ) {\n\t\t\tif ( sclerror::IsErrorPending() ) {\n\t\t\t\tMeaningBuffer.Init();\n\t\t\t\tMeaning.AddTag( sclerror::GetMeaning( MeaningBuffer ) );\n\t\t\t} else {\n\t\t\t\tTranslation.Init();\n\t\t\t\tMeaning.AddTag( sclmisc::GetBaseTranslation( \"UnkonwnError\", Translation ) );\n\t\t\t}\n\t\t} else {\n\t\t\tMeaning.AddTag( err::Message( ErrBuffer ) );\n\t\t}\n\n\t\tTranslation.Init();\n\t\tsclmisc::GetBaseTranslation( Meaning, Translation );\n\n\t\tcio::CErr << Translation << txf::nl << txf::commit;\n\tqRT\n\tqRE\n\t}\n\n\tusing misc::cHandler;\n\n\tvoid Process_(\n\t\tcHandler &Handler,\n\t\tsModule &Module )\n\t{\n\t\tHandler.Handle( Module );\n\t}\n\n\tvoid Process_( misc::sModule &Module )\n\t{\n\tqRH\n\t\tplgn::rRetriever<cHandler> Retriever;\n\t\tstr::wString PluginId, PluginArguments;\n\tqRB\n\t\tPluginId.Init();\n\t\tPluginArguments.Init();\n\t\tModule.Preferences( PluginId, PluginArguments );\n\n\t\tRetriever.Init();\n\n\t\tsclmisc::Plug( misc::SlotPluginTarget, PluginId, PluginArguments, NULL, Retriever );\n\n\t\tProcess_( Retriever.Plugin(), Module );\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid Process_( void )\n\t{\n\tqRH\n\t\tTOL_CBUFFER___ Buffer;\n\tqRB\n\t\tatexit( ExitFunction_ );\n\n\t\tcio::COut.Commit();\n\n\t\tLoadModule_( sclmisc::MGetValue( registry::Module, Buffer ) );\n\n\t\tProcess_( Core_->GetCallback() );\n\tqRR\n\tqRT\n\tqRE\n\t}\n\n\tvoid AboutPlugin_( void )\n\t{\n\tqRH\n\t\tplgn::rRetriever<cHandler> Retriever;\n\tqRB\n\t\tRetriever.Init();\n\n\t\tsclmisc::Plug( misc::SlotPluginTarget, NULL, Retriever );\n\n\t\tcio::COut << Retriever.Details() << txf::nl << Retriever.Identifier() << txf::commit;\n\tqRR\n\tqRT\n\tqRE\n\t}\n}\n\n#define C( name )\\\n\telse if ( Command == #name )\\\n\t\tname##_()\n\nint scltool::SCLTOOLMain(\n\tconst str::string_ &Command,\n\tconst scltool::oddities__ &Oddities )\n{\n\tint ExitValue = EXIT_FAILURE;\nqRH\nqRB\n\tif ( Command == \"Version\" )\n\t\tPrintHeader_();\n\telse if ( Command == \"License\" )\n\t\tepsmsc::PrintLicense( NAME_MC );\n\tC( Process );\n\tC( AboutPlugin );\n\telse\n\t\tqRGnr();\n\n\tExitValue = EXIT_SUCCESS;\nqRR\nqRT\nqRE\n\treturn ExitValue;\n}\n\n#undef C\n\nconst char *sclmisc::SCLMISCTargetName = NAME_LC;\n\nQ37_GCTOR( dmnzq )\n{\n}<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the \"x0\" project\n\/\/ (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <xzero\/RuntimeError.h>\n#include <xzero\/Tokenizer.h>\n#include <xzero\/Buffer.h>\n#include <xzero\/sysconfig.h>\n#include <typeinfo>\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n\n#if defined(HAVE_EXECINFO_H)\n#include <execinfo.h>\n#endif\n\n#if defined(HAVE_DLFCN_H)\n#include <dlfcn.h>\n#endif\n\nnamespace xzero {\n\n#define MAX_FRAMES 64\n#define SKIP_FRAMES 2\n\nclass Pipe { \/\/ {{{\n private:\n Pipe(const Pipe&) = delete;\n Pipe& operator=(Pipe&) = delete;\n\n public:\n Pipe();\n Pipe(Pipe&& other);\n Pipe& operator=(Pipe&& other);\n ~Pipe();\n\n int readFd() const noexcept { return pfd_[0]; }\n int writeFd() const noexcept { return pfd_[1]; }\n\n void close();\n void closeRead();\n void closeWrite();\n\n private:\n int pfd_[2];\n};\n\nPipe::Pipe() {\n#if defined(HAVE_PIPE2)\n int rv = pipe2(pfd_, O_CLOEXEC);\n#else\n int rv = pipe(pfd_);\n#endif\n if (rv < 0) {\n throw RUNTIME_ERROR(strerror(errno)); \/\/ FIXME: not thread safe\n }\n}\n\nPipe::Pipe(Pipe&& other) {\n pfd_[0] = other.pfd_[0];\n pfd_[1] = other.pfd_[1];\n\n other.pfd_[0] = -1;\n other.pfd_[1] = -1;\n}\n\nPipe& Pipe::operator=(Pipe&& other) {\n pfd_[0] = other.pfd_[0];\n pfd_[1] = other.pfd_[1];\n\n other.pfd_[0] = -1;\n other.pfd_[1] = -1;\n\n return *this;\n}\n\nPipe::~Pipe() {\n close();\n}\n\nvoid Pipe::close() {\n closeRead();\n closeWrite();\n}\n\nvoid Pipe::closeRead() {\n if (readFd() >= 0)\n ::close(readFd());\n}\n\nvoid Pipe::closeWrite() {\n if (writeFd() >= 0)\n ::close(writeFd());\n}\n\/\/ }}}\n\nstd::string demangleSymbol(const char* symbol) {\n return symbol; \/\/ TODO: __cxa_demangle()\n}\n\nvoid consoleLogger(const std::exception& e) {\n if (auto rt = dynamic_cast<const RuntimeError*>(&e)) {\n fprintf(stderr, \"Unhandled exception caught in executor [%s:%d] (%s): %s\\n\",\n rt->sourceFile(), rt->sourceLine(),\n demangleSymbol(typeid(e).name()).c_str(),\n rt->what());\n auto bt = rt->backtrace();\n for (size_t i = 0; i < bt.size(); ++i)\n fprintf(stderr, \" [%zu] %s\\n\", i, bt[i].c_str());\n return;\n }\n\n fprintf(stderr, \"Unhandled exception caught in executor (%s): %s\\n\",\n demangleSymbol(typeid(e).name()).c_str(), e.what());\n}\n\nRuntimeError::RuntimeError(const std::string& what,\n const char* sourceFile,\n int sourceLine)\n : std::runtime_error(what),\n sourceFile_(sourceFile),\n sourceLine_(sourceLine),\n#if defined(HAVE_BACKTRACE)\n frames_(MAX_FRAMES ? new void*[SKIP_FRAMES + MAX_FRAMES] : nullptr),\n frameCount_(MAX_FRAMES ? ::backtrace(frames_, SKIP_FRAMES + MAX_FRAMES) : 0)\n#else\n frames_(nullptr),\n frameCount_(0)\n#endif\n{\n}\n\nRuntimeError::~RuntimeError() {\n delete[] frames_;\n}\n\nstd::vector<std::string> RuntimeError::backtrace() const {\n#if defined(HAVE_DLFCN_H) && defined(HAVE_DUP2) && defined(HAVE_FORK)\n if (!frameCount_ || !frames_)\n return {};\n\n std::vector<std::string> output;\n\n Buffer rawFramesText;\n for (int i = SKIP_FRAMES; i <= frameCount_; ++i) {\n Dl_info info;\n if (dladdr(frames_[i], &info)) {\n char buf[512];\n int n = snprintf(buf, sizeof(buf), \"%s %p\", info.dli_fname, frames_[i]);\n rawFramesText.push_back(buf, n);\n rawFramesText.push_back('\\n');\n output.push_back(buf);\n }\n }\n\n Pipe fin;\n Pipe fout;\n\n std::string symbolizerPath = \"\/usr\/bin\/llvm-symbolizer\";\n if (const char* p = getenv(\"SYMBOLIZER\"))\n symbolizerPath = p;\n\n pid_t pid = fork();\n if (pid < 0) {\n \/\/ error\n return output;\n } else if (pid == 0) {\n \/\/ child\n dup2(fin.readFd(), STDIN_FILENO);\n dup2(fout.writeFd(), STDOUT_FILENO);\n dup2(fout.writeFd(), STDERR_FILENO);\n fin.close();\n fout.close();\n\n execl(symbolizerPath.c_str(), symbolizerPath.c_str(), nullptr);\n close(STDOUT_FILENO);\n close(STDERR_FILENO);\n abort();\n } else {\n \/\/ parent\n fin.closeRead();\n fout.closeWrite();\n\n write(fin.writeFd(), rawFramesText.data(), rawFramesText.size());\n fin.closeWrite();\n\n Buffer symbolizerOutput;\n char chunk[1024];\n for (;;) {\n int n = read(fout.readFd(), chunk, sizeof(chunk));\n if (n <= 0)\n break;\n symbolizerOutput.push_back(chunk, n);\n }\n\n int status = 0;\n waitpid(pid, &status, 0);\n\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)\n \/\/ symbolizer failed. return raw output.\n return output;\n\n if (symbolizerOutput.empty())\n \/\/ symbolizer returned nothing\n return output;\n\n output.clear();\n auto lines = Tokenizer<BufferRef>::tokenize(symbolizerOutput.ref(), \"\\n\");\n for (size_t i = 0; i + 1 < lines.size(); i += 2) {\n Buffer buf;\n buf.push_back(lines[i]);\n buf.push_back(\" in \");\n buf.push_back(lines[i + 1]);\n output.push_back(buf.str());\n }\n return output;\n }\n#else\n return {};\n#endif\n}\n\n} \/\/ namespace xzero\n<commit_msg>RuntimeError: make fallback backtrace output slightly more readable<commit_after>\/\/ This file is part of the \"x0\" project\n\/\/ (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <xzero\/RuntimeError.h>\n#include <xzero\/Tokenizer.h>\n#include <xzero\/Buffer.h>\n#include <xzero\/sysconfig.h>\n#include <typeinfo>\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n\n#if defined(HAVE_EXECINFO_H)\n#include <execinfo.h>\n#endif\n\n#if defined(HAVE_DLFCN_H)\n#include <dlfcn.h>\n#endif\n\nnamespace xzero {\n\n#define MAX_FRAMES 64\n#define SKIP_FRAMES 2\n\nclass Pipe { \/\/ {{{\n private:\n Pipe(const Pipe&) = delete;\n Pipe& operator=(Pipe&) = delete;\n\n public:\n Pipe();\n Pipe(Pipe&& other);\n Pipe& operator=(Pipe&& other);\n ~Pipe();\n\n int readFd() const noexcept { return pfd_[0]; }\n int writeFd() const noexcept { return pfd_[1]; }\n\n void close();\n void closeRead();\n void closeWrite();\n\n private:\n int pfd_[2];\n};\n\nPipe::Pipe() {\n#if defined(HAVE_PIPE2)\n int rv = pipe2(pfd_, O_CLOEXEC);\n#else\n int rv = pipe(pfd_);\n#endif\n if (rv < 0) {\n throw RUNTIME_ERROR(strerror(errno)); \/\/ FIXME: not thread safe\n }\n}\n\nPipe::Pipe(Pipe&& other) {\n pfd_[0] = other.pfd_[0];\n pfd_[1] = other.pfd_[1];\n\n other.pfd_[0] = -1;\n other.pfd_[1] = -1;\n}\n\nPipe& Pipe::operator=(Pipe&& other) {\n pfd_[0] = other.pfd_[0];\n pfd_[1] = other.pfd_[1];\n\n other.pfd_[0] = -1;\n other.pfd_[1] = -1;\n\n return *this;\n}\n\nPipe::~Pipe() {\n close();\n}\n\nvoid Pipe::close() {\n closeRead();\n closeWrite();\n}\n\nvoid Pipe::closeRead() {\n if (readFd() >= 0)\n ::close(readFd());\n}\n\nvoid Pipe::closeWrite() {\n if (writeFd() >= 0)\n ::close(writeFd());\n}\n\/\/ }}}\n\nstd::string demangleSymbol(const char* symbol) {\n return symbol; \/\/ TODO: __cxa_demangle()\n}\n\nvoid consoleLogger(const std::exception& e) {\n if (auto rt = dynamic_cast<const RuntimeError*>(&e)) {\n fprintf(stderr, \"Unhandled exception caught in executor [%s:%d] (%s): %s\\n\",\n rt->sourceFile(), rt->sourceLine(),\n demangleSymbol(typeid(e).name()).c_str(),\n rt->what());\n auto bt = rt->backtrace();\n for (size_t i = 0; i < bt.size(); ++i)\n fprintf(stderr, \" [%zu] %s\\n\", i, bt[i].c_str());\n return;\n }\n\n fprintf(stderr, \"Unhandled exception caught in executor (%s): %s\\n\",\n demangleSymbol(typeid(e).name()).c_str(), e.what());\n}\n\nRuntimeError::RuntimeError(const std::string& what,\n const char* sourceFile,\n int sourceLine)\n : std::runtime_error(what),\n sourceFile_(sourceFile),\n sourceLine_(sourceLine),\n#if defined(HAVE_BACKTRACE)\n frames_(MAX_FRAMES ? new void*[SKIP_FRAMES + MAX_FRAMES] : nullptr),\n frameCount_(MAX_FRAMES ? ::backtrace(frames_, SKIP_FRAMES + MAX_FRAMES) : 0)\n#else\n frames_(nullptr),\n frameCount_(0)\n#endif\n{\n}\n\nRuntimeError::~RuntimeError() {\n delete[] frames_;\n}\n\nstd::vector<std::string> RuntimeError::backtrace() const {\n#if defined(HAVE_DLFCN_H) && defined(HAVE_DUP2) && defined(HAVE_FORK)\n if (!frameCount_ || !frames_)\n return {};\n\n std::vector<std::string> output;\n\n Buffer rawFramesText;\n for (int i = SKIP_FRAMES; i <= frameCount_; ++i) {\n Dl_info info;\n if (dladdr(frames_[i], &info)) {\n char buf[512];\n int n = snprintf(buf, sizeof(buf), \"%s %p\", info.dli_fname, frames_[i]);\n rawFramesText.push_back(buf, n);\n rawFramesText.push_back('\\n');\n\n if (info.dli_sname)\n n = snprintf(buf, sizeof(buf), \"%s\", info.dli_sname);\n else\n n = snprintf(buf, sizeof(buf), \"%p %s\", frames_[i], info.dli_fname);\n\n output.push_back(std::string(buf, n));\n }\n }\n\n Pipe fin;\n Pipe fout;\n\n std::string symbolizerPath = \"\/usr\/bin\/llvm-symbolizer\";\n if (const char* p = getenv(\"SYMBOLIZER\"))\n symbolizerPath = p;\n\n pid_t pid = fork();\n if (pid < 0) {\n \/\/ error\n return output;\n } else if (pid == 0) {\n \/\/ child\n dup2(fin.readFd(), STDIN_FILENO);\n dup2(fout.writeFd(), STDOUT_FILENO);\n dup2(fout.writeFd(), STDERR_FILENO);\n fin.close();\n fout.close();\n\n execl(symbolizerPath.c_str(), symbolizerPath.c_str(), nullptr);\n close(STDOUT_FILENO);\n close(STDERR_FILENO);\n abort();\n } else {\n \/\/ parent\n fin.closeRead();\n fout.closeWrite();\n\n write(fin.writeFd(), rawFramesText.data(), rawFramesText.size());\n fin.closeWrite();\n\n Buffer symbolizerOutput;\n char chunk[1024];\n for (;;) {\n int n = read(fout.readFd(), chunk, sizeof(chunk));\n if (n <= 0)\n break;\n symbolizerOutput.push_back(chunk, n);\n }\n\n int status = 0;\n waitpid(pid, &status, 0);\n\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)\n \/\/ symbolizer failed. return raw output.\n return output;\n\n if (symbolizerOutput.empty())\n \/\/ symbolizer returned nothing\n return output;\n\n output.clear();\n auto lines = Tokenizer<BufferRef>::tokenize(symbolizerOutput.ref(), \"\\n\");\n for (size_t i = 0; i + 1 < lines.size(); i += 2) {\n Buffer buf;\n buf.push_back(lines[i]);\n buf.push_back(\" in \");\n buf.push_back(lines[i + 1]);\n output.push_back(buf.str());\n }\n return output;\n }\n#else\n return {};\n#endif\n}\n\n} \/\/ namespace xzero\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: dg $ $Date: 2001-02-12 16:23:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#include <offmgr\/app.hxx>\n#include <comphelper\/processfactory.hxx>\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n\n#include <setup2\/installer.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#include <vcl\/msgbox.hxx>\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nvoid PreloadConfigTrees()\n{\n \/\/ these tree are preloaded to get a faster startup for the office\n Sequence <rtl::OUString> aPreloadPathList(6);\n aPreloadPathList[0] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Common\");\n aPreloadPathList[1] = rtl::OUString::createFromAscii(\"org.openoffice.ucb.Configuration\/ContentProviders\/Office\/SecondaryKeys\/Local\/ProviderData\");\n aPreloadPathList[2] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Writer\");\n aPreloadPathList[3] = rtl::OUString::createFromAscii(\"org.openoffice.Office.WriterWeb\");\n aPreloadPathList[4] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Calc\");\n aPreloadPathList[5] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Impress\");\n\n Reference< XMultiServiceFactory > xProvider(\n ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\")), UNO_QUERY);\n\n Any aValue;\n aValue <<= aPreloadPathList;\n\n Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii(\"PrefetchNodes\"), aValue );\n}\n\n\nvoid ReplaceStringHookProc( UniString& rStr )\n{\n static String aBrandName;\n static String aVersion;\n static String aExtension;\n\n static int nAll = 0, nPro = 0;\n\n if ( !aBrandName.Len() )\n {\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n rtl::OUString aTmp;\n aRet >>= aTmp;\n aBrandName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n aVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );\n aRet >>= aTmp;\n aExtension = aTmp;\n }\n\n nAll++;\n if ( rStr.SearchAscii( \"%PRODUCT\" ) != STRING_NOTFOUND )\n {\n nPro++;\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", aBrandName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", aVersion );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTEXTENSION\", aExtension );\n }\n}\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n ResMgr::SetReadStringHook( ReplaceStringHookProc );\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\/\/ Read the common configuration items for optimization purpose\n PreloadConfigTrees();\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n<commit_msg>#83239# preloading of ucb configurationdata<commit_after>\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: kso $ $Date: 2001-02-12 16:50:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#include <offmgr\/app.hxx>\n#include <comphelper\/processfactory.hxx>\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n\n#include <setup2\/installer.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#include <vcl\/msgbox.hxx>\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nvoid PreloadConfigTrees()\n{\n \/\/ these tree are preloaded to get a faster startup for the office\n Sequence <rtl::OUString> aPreloadPathList(6);\n aPreloadPathList[0] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Common\");\n aPreloadPathList[1] = rtl::OUString::createFromAscii(\"org.openoffice.ucb.Configuration\");\n aPreloadPathList[2] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Writer\");\n aPreloadPathList[3] = rtl::OUString::createFromAscii(\"org.openoffice.Office.WriterWeb\");\n aPreloadPathList[4] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Calc\");\n aPreloadPathList[5] = rtl::OUString::createFromAscii(\"org.openoffice.Office.Impress\");\n\n Reference< XMultiServiceFactory > xProvider(\n ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\")), UNO_QUERY);\n\n Any aValue;\n aValue <<= aPreloadPathList;\n\n Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii(\"PrefetchNodes\"), aValue );\n}\n\n\nvoid ReplaceStringHookProc( UniString& rStr )\n{\n static String aBrandName;\n static String aVersion;\n static String aExtension;\n\n static int nAll = 0, nPro = 0;\n\n if ( !aBrandName.Len() )\n {\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n rtl::OUString aTmp;\n aRet >>= aTmp;\n aBrandName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n aVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );\n aRet >>= aTmp;\n aExtension = aTmp;\n }\n\n nAll++;\n if ( rStr.SearchAscii( \"%PRODUCT\" ) != STRING_NOTFOUND )\n {\n nPro++;\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", aBrandName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", aVersion );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTEXTENSION\", aExtension );\n }\n}\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n ResMgr::SetReadStringHook( ReplaceStringHookProc );\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\/\/ Read the common configuration items for optimization purpose\n PreloadConfigTrees();\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::_str_to_str_backend\n\n\nnamespace abc {\n\nvoid _str_to_str_backend::set_format(istr const & sFormat) {\n ABC_TRACE_FUNC(this, sFormat);\n\n auto it(sFormat.cbegin());\n\n \/\/ Add parsing of the format string here.\n\n \/\/ If we still have any characters, they are garbage.\n if (it != sFormat.cend()) {\n ABC_THROW(syntax_error, (\n SL(\"unexpected character\"), sFormat, static_cast<unsigned>(it - sFormat.cend())\n ));\n }\n}\n\n\nvoid _str_to_str_backend::write(\n void const * p, size_t cb, text::encoding enc, io::text::writer * ptwOut\n) {\n ABC_TRACE_FUNC(this, p, cb, enc, ptwOut);\n\n ptwOut->write_binary(p, cb, enc);\n}\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::str_base\n\n\nnamespace abc {\n\nchar_t const str_base::smc_chNul('\\0');\n\n\nchar_t const * str_base::_advance_char_ptr(char_t const * pch, ptrdiff_t i, bool bIndex) const {\n ABC_TRACE_FUNC(this, pch, i, bIndex);\n\n char_t const * pchBegin(chars_begin()), * pchEnd(chars_end());\n ptrdiff_t iOrig(i);\n\n \/\/ If i is positive, move forward.\n for (; i > 0 && pch < pchEnd; --i) {\n \/\/ Find the next code point start, skipping any trail characters.\n pch += text::host_char_traits::lead_char_to_codepoint_size(*pch);\n }\n \/\/ If i is negative, move backwards.\n for (; i < 0 && pch > pchBegin; ++i) {\n \/\/ Moving to the previous code point requires finding the previous non-trail character.\n while (text::host_char_traits::is_trail_char(*--pch)) {\n ;\n }\n }\n\n \/\/ Verify that the pointer is still within range: that’s not the case if we left either for loop\n \/\/ before i reached 0, or if the pointer was invalid on entry (e.g. accessing istr()[0]).\n if (i != 0 || pch < pchBegin || pch > pchEnd || (bIndex && pch == pchEnd)) {\n if (bIndex) {\n ABC_THROW(index_error, (iOrig));\n } else {\n ABC_THROW(pointer_iterator_error, (pchBegin, pchEnd, pch));\n }\n }\n\n \/\/ Return the resulting pointer.\n return pch;\n}\n\n\nstr_base::c_str_pointer str_base::c_str() const {\n ABC_TRACE_FUNC(this);\n\n if (m_bNulT) {\n \/\/ The string already includes a NUL terminator, so we can simply return the same array.\n return c_str_pointer(chars_begin(), c_str_pointer::deleter_type(false));\n } else if (size_t cch = size_in_chars()) {\n \/\/ The string is not empty but lacks a NUL terminator: create a temporary copy that includes a\n \/\/ NUL, and return it.\n c_str_pointer psz(\n memory::alloc<char_t const []>(cch + 1 \/*NUL*\/).release(),\n c_str_pointer::deleter_type(true)\n );\n char_t * pch(const_cast<char_t *>(psz.get()));\n memory::copy(pch, chars_begin(), cch);\n memory::clear(pch + cch);\n return std::move(psz);\n } else {\n \/\/ The string is empty, so a static NUL character will suffice.\n return c_str_pointer(&smc_chNul, c_str_pointer::deleter_type(false));\n }\n}\n\n\ndmvector<uint8_t> str_base::encode(text::encoding enc, bool bNulT) const {\n ABC_TRACE_FUNC(this, enc, bNulT);\n\n dmvector<uint8_t> vb;\n size_t cbChar, cbUsed, cbStr(size_in_bytes());\n if (enc == abc::text::encoding::host) {\n \/\/ Optimal case: no transcoding necessary.\n cbChar = sizeof(char_t);\n \/\/ Enlarge vb as necessary, then copy to it the contents of the string buffer.\n vb.set_capacity(cbStr + (bNulT ? sizeof(char_t) : 0), false);\n memory::copy(vb.begin().base(), _raw_trivial_vextr_impl::begin<uint8_t>(), cbStr);\n cbUsed = cbStr;\n } else {\n cbChar = text::get_encoding_size(enc);\n void const * pStr(chars_begin());\n \/\/ Calculate the size required, then resize vb accorgingly.\n cbUsed = abc::text::transcode(true, abc::text::encoding::host, &pStr, &cbStr, enc);\n vb.set_capacity(cbUsed + (bNulT ? cbChar : 0), false);\n \/\/ Transcode the string into vb.\n void * pBuf(vb.begin().base());\n \/\/ Re-assign to cbUsed because transcode() will set *(&cbUsed) to 0.\n cbUsed = abc::text::transcode(\n true, abc::text::encoding::host, &pStr, &cbStr, enc, &pBuf, &cbUsed\n );\n }\n if (bNulT) {\n memory::clear(vb.begin().base() + cbUsed, cbChar);\n cbUsed += cbChar;\n }\n \/\/ Assign the vector its size, and return it.\n vb.set_size(cbUsed);\n return std::move(vb);\n}\n\n\nbool str_base::ends_with(istr const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n char_t const * pchStart(chars_end() - s.size_in_chars());\n return pchStart >= chars_begin() && text::str_traits::compare(\n pchStart, chars_end(), s.chars_begin(), s.chars_end()\n ) == 0;\n}\n\n\nstr_base::const_iterator str_base::find(char_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);\n}\nstr_base::const_iterator str_base::find(char32_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);\n}\nstr_base::const_iterator str_base::find(istr const & sNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, sNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_substr(\n itWhence.base(), chars_end(), sNeedle.chars_begin(), sNeedle.chars_end()\n ), this);\n}\n\n\nstr_base::const_iterator str_base::find_last(char_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char_last(\n chars_begin(), itWhence.base(), chNeedle\n ), this);\n}\nstr_base::const_iterator str_base::find_last(char32_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char_last(\n chars_begin(), itWhence.base(), chNeedle\n ), this);\n}\nstr_base::const_iterator str_base::find_last(istr const & sNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, sNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_substr_last(\n chars_begin(), itWhence.base(), sNeedle.chars_begin(), sNeedle.chars_end()\n ), this);\n}\n\n\nbool str_base::starts_with(istr const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n char_t const * pchEnd(chars_begin() + s.size_in_chars());\n return pchEnd <= chars_end() && text::str_traits::compare(\n chars_begin(), pchEnd, s.chars_begin(), s.chars_end()\n ) == 0;\n}\n\n\nstr_base::const_iterator str_base::translate_index(intptr_t ich) const {\n ABC_TRACE_FUNC(this, ich);\n\n const_iterator it, itLoopEnd;\n int iDelta;\n if (ich >= 0) {\n \/\/ The character index is non-negative: assume it’s faster to reach the corresponding code\n \/\/ point index by starting from the beginning.\n it = begin();\n itLoopEnd = end();\n iDelta = 1;\n } else {\n \/\/ The character index is negative: assume it’s faster to reach the corresponding code point\n \/\/ index by starting from the end.\n it = end();\n itLoopEnd = begin();\n iDelta = -1;\n }\n while (ich && it != itLoopEnd) {\n ich -= iDelta;\n it += iDelta;\n }\n return std::move(it);\n}\n\n\nstd::pair<str_base::const_iterator, str_base::const_iterator> str_base::translate_range(\n intptr_t ichBegin, intptr_t ichEnd\n) const {\n ABC_TRACE_FUNC(this, ichBegin, ichEnd);\n\n auto itBegin(translate_index(ichBegin));\n auto itEnd(translate_index(ichEnd));\n \/\/ If the interval is empty, return [end(), end()) .\n if (itBegin >= itEnd) {\n return std::pair<const_iterator, const_iterator>(end(), end());\n }\n \/\/ Return the constructed interval.\n return std::pair<const_iterator, const_iterator>(itBegin, itEnd);\n}\n\n} \/\/namespace abc\n\n\nnamespace std {\n\n\/\/ Implementation based on the Fowler\/Noll\/Vo variant 1a (FNV-1a) algorithm. See\n\/\/ <http:\/\/www.isthe.com\/chongo\/tech\/comp\/fnv\/> for details.\n\/\/\n\/\/ The bases are calculated by src\/fnv_hash_basis.py.\nsize_t hash<abc::str_base>::operator()(abc::str_base const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n static_assert(\n sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,\n \"unexpected sizeof(size_t) will break FNV prime\/basis selection\"\n );\n#if ABC_HOST_WORD_SIZE == 16\n size_t const c_iFNVPrime(0x1135);\n size_t const c_iFNVBasis(16635u);\n#elif ABC_HOST_WORD_SIZE == 32\n size_t const c_iFNVPrime(0x01000193);\n size_t const c_iFNVBasis(2166136261u);\n#elif ABC_HOST_WORD_SIZE == 64\n size_t const c_iFNVPrime(0x00000100000001b3);\n size_t const c_iFNVBasis(14695981039346656037u);\n#endif\n size_t iHash(c_iFNVBasis);\n for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {\n iHash ^= static_cast<size_t>(*it);\n iHash *= c_iFNVPrime;\n }\n return iHash;\n}\n\n} \/\/namespace std\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::mstr\n\n\nnamespace abc {\n\nvoid mstr::_replace_codepoint(char_t * pch, char_t chNew) {\n ABC_TRACE_FUNC(pch, chNew);\n\n size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));\n uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));\n _raw_trivial_vextr_impl::insert_remove(ich, nullptr, sizeof(char_t), cbRemove);\n \/\/ insert_remove() may have switched string buffer, so recalculate pch now.\n pch = chars_begin() + ich;\n \/\/ At this point, insert_remove() validated pch.\n *pch = chNew;\n}\nvoid mstr::_replace_codepoint(char_t * pch, char32_t chNew) {\n ABC_TRACE_FUNC(pch, chNew);\n\n size_t cbInsert(sizeof(char_t) * text::host_char_traits::codepoint_size(chNew));\n size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));\n uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));\n _raw_trivial_vextr_impl::insert_remove(ich, nullptr, cbInsert, cbRemove);\n \/\/ insert_remove() may have switched string buffer, so recalculate pch now.\n pch = chars_begin() + ich;\n \/\/ At this point, insert_remove() validated pch and codepoint_size() validated chNew; this means\n \/\/ that there’s nothing that could go wrong here leaving us in an inconsistent state.\n text::host_char_traits::traits_base::codepoint_to_chars(chNew, pch);\n}\n\n\nvoid mstr::set_from(std::function<size_t (char_t * pch, size_t cchMax)> const & fnRead) {\n \/\/ The initial size avoids a few reallocations (* smc_iGrowthRate ** 2).\n \/\/ Multiplying by smc_iGrowthRate should guarantee that set_capacity() will allocate exactly the\n \/\/ requested number of characters, eliminating the need to query back with capacity().\n size_t cchRet, cchMax(smc_cbCapacityMin * smc_iGrowthRate);\n do {\n cchMax *= smc_iGrowthRate;\n set_capacity(cchMax, false);\n cchRet = fnRead(chars_begin(), cchMax);\n } while (cchRet >= cchMax);\n \/\/ Finalize the length.\n set_size_in_chars(cchRet);\n}\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Add missing ABC_TRACE_FUNC() statement<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::_str_to_str_backend\n\n\nnamespace abc {\n\nvoid _str_to_str_backend::set_format(istr const & sFormat) {\n ABC_TRACE_FUNC(this, sFormat);\n\n auto it(sFormat.cbegin());\n\n \/\/ Add parsing of the format string here.\n\n \/\/ If we still have any characters, they are garbage.\n if (it != sFormat.cend()) {\n ABC_THROW(syntax_error, (\n SL(\"unexpected character\"), sFormat, static_cast<unsigned>(it - sFormat.cend())\n ));\n }\n}\n\n\nvoid _str_to_str_backend::write(\n void const * p, size_t cb, text::encoding enc, io::text::writer * ptwOut\n) {\n ABC_TRACE_FUNC(this, p, cb, enc, ptwOut);\n\n ptwOut->write_binary(p, cb, enc);\n}\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::str_base\n\n\nnamespace abc {\n\nchar_t const str_base::smc_chNul('\\0');\n\n\nchar_t const * str_base::_advance_char_ptr(char_t const * pch, ptrdiff_t i, bool bIndex) const {\n ABC_TRACE_FUNC(this, pch, i, bIndex);\n\n char_t const * pchBegin(chars_begin()), * pchEnd(chars_end());\n ptrdiff_t iOrig(i);\n\n \/\/ If i is positive, move forward.\n for (; i > 0 && pch < pchEnd; --i) {\n \/\/ Find the next code point start, skipping any trail characters.\n pch += text::host_char_traits::lead_char_to_codepoint_size(*pch);\n }\n \/\/ If i is negative, move backwards.\n for (; i < 0 && pch > pchBegin; ++i) {\n \/\/ Moving to the previous code point requires finding the previous non-trail character.\n while (text::host_char_traits::is_trail_char(*--pch)) {\n ;\n }\n }\n\n \/\/ Verify that the pointer is still within range: that’s not the case if we left either for loop\n \/\/ before i reached 0, or if the pointer was invalid on entry (e.g. accessing istr()[0]).\n if (i != 0 || pch < pchBegin || pch > pchEnd || (bIndex && pch == pchEnd)) {\n if (bIndex) {\n ABC_THROW(index_error, (iOrig));\n } else {\n ABC_THROW(pointer_iterator_error, (pchBegin, pchEnd, pch));\n }\n }\n\n \/\/ Return the resulting pointer.\n return pch;\n}\n\n\nstr_base::c_str_pointer str_base::c_str() const {\n ABC_TRACE_FUNC(this);\n\n if (m_bNulT) {\n \/\/ The string already includes a NUL terminator, so we can simply return the same array.\n return c_str_pointer(chars_begin(), c_str_pointer::deleter_type(false));\n } else if (size_t cch = size_in_chars()) {\n \/\/ The string is not empty but lacks a NUL terminator: create a temporary copy that includes a\n \/\/ NUL, and return it.\n c_str_pointer psz(\n memory::alloc<char_t const []>(cch + 1 \/*NUL*\/).release(),\n c_str_pointer::deleter_type(true)\n );\n char_t * pch(const_cast<char_t *>(psz.get()));\n memory::copy(pch, chars_begin(), cch);\n memory::clear(pch + cch);\n return std::move(psz);\n } else {\n \/\/ The string is empty, so a static NUL character will suffice.\n return c_str_pointer(&smc_chNul, c_str_pointer::deleter_type(false));\n }\n}\n\n\ndmvector<uint8_t> str_base::encode(text::encoding enc, bool bNulT) const {\n ABC_TRACE_FUNC(this, enc, bNulT);\n\n dmvector<uint8_t> vb;\n size_t cbChar, cbUsed, cbStr(size_in_bytes());\n if (enc == abc::text::encoding::host) {\n \/\/ Optimal case: no transcoding necessary.\n cbChar = sizeof(char_t);\n \/\/ Enlarge vb as necessary, then copy to it the contents of the string buffer.\n vb.set_capacity(cbStr + (bNulT ? sizeof(char_t) : 0), false);\n memory::copy(vb.begin().base(), _raw_trivial_vextr_impl::begin<uint8_t>(), cbStr);\n cbUsed = cbStr;\n } else {\n cbChar = text::get_encoding_size(enc);\n void const * pStr(chars_begin());\n \/\/ Calculate the size required, then resize vb accorgingly.\n cbUsed = abc::text::transcode(true, abc::text::encoding::host, &pStr, &cbStr, enc);\n vb.set_capacity(cbUsed + (bNulT ? cbChar : 0), false);\n \/\/ Transcode the string into vb.\n void * pBuf(vb.begin().base());\n \/\/ Re-assign to cbUsed because transcode() will set *(&cbUsed) to 0.\n cbUsed = abc::text::transcode(\n true, abc::text::encoding::host, &pStr, &cbStr, enc, &pBuf, &cbUsed\n );\n }\n if (bNulT) {\n memory::clear(vb.begin().base() + cbUsed, cbChar);\n cbUsed += cbChar;\n }\n \/\/ Assign the vector its size, and return it.\n vb.set_size(cbUsed);\n return std::move(vb);\n}\n\n\nbool str_base::ends_with(istr const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n char_t const * pchStart(chars_end() - s.size_in_chars());\n return pchStart >= chars_begin() && text::str_traits::compare(\n pchStart, chars_end(), s.chars_begin(), s.chars_end()\n ) == 0;\n}\n\n\nstr_base::const_iterator str_base::find(char_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);\n}\nstr_base::const_iterator str_base::find(char32_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);\n}\nstr_base::const_iterator str_base::find(istr const & sNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, sNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_substr(\n itWhence.base(), chars_end(), sNeedle.chars_begin(), sNeedle.chars_end()\n ), this);\n}\n\n\nstr_base::const_iterator str_base::find_last(char_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char_last(\n chars_begin(), itWhence.base(), chNeedle\n ), this);\n}\nstr_base::const_iterator str_base::find_last(char32_t chNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, chNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_char_last(\n chars_begin(), itWhence.base(), chNeedle\n ), this);\n}\nstr_base::const_iterator str_base::find_last(istr const & sNeedle, const_iterator itWhence) const {\n ABC_TRACE_FUNC(this, sNeedle, itWhence);\n\n validate_pointer(itWhence.base());\n return const_iterator(text::str_traits::find_substr_last(\n chars_begin(), itWhence.base(), sNeedle.chars_begin(), sNeedle.chars_end()\n ), this);\n}\n\n\nbool str_base::starts_with(istr const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n char_t const * pchEnd(chars_begin() + s.size_in_chars());\n return pchEnd <= chars_end() && text::str_traits::compare(\n chars_begin(), pchEnd, s.chars_begin(), s.chars_end()\n ) == 0;\n}\n\n\nstr_base::const_iterator str_base::translate_index(intptr_t ich) const {\n ABC_TRACE_FUNC(this, ich);\n\n const_iterator it, itLoopEnd;\n int iDelta;\n if (ich >= 0) {\n \/\/ The character index is non-negative: assume it’s faster to reach the corresponding code\n \/\/ point index by starting from the beginning.\n it = begin();\n itLoopEnd = end();\n iDelta = 1;\n } else {\n \/\/ The character index is negative: assume it’s faster to reach the corresponding code point\n \/\/ index by starting from the end.\n it = end();\n itLoopEnd = begin();\n iDelta = -1;\n }\n while (ich && it != itLoopEnd) {\n ich -= iDelta;\n it += iDelta;\n }\n return std::move(it);\n}\n\n\nstd::pair<str_base::const_iterator, str_base::const_iterator> str_base::translate_range(\n intptr_t ichBegin, intptr_t ichEnd\n) const {\n ABC_TRACE_FUNC(this, ichBegin, ichEnd);\n\n auto itBegin(translate_index(ichBegin));\n auto itEnd(translate_index(ichEnd));\n \/\/ If the interval is empty, return [end(), end()) .\n if (itBegin >= itEnd) {\n return std::pair<const_iterator, const_iterator>(end(), end());\n }\n \/\/ Return the constructed interval.\n return std::pair<const_iterator, const_iterator>(itBegin, itEnd);\n}\n\n} \/\/namespace abc\n\n\nnamespace std {\n\n\/\/ Implementation based on the Fowler\/Noll\/Vo variant 1a (FNV-1a) algorithm. See\n\/\/ <http:\/\/www.isthe.com\/chongo\/tech\/comp\/fnv\/> for details.\n\/\/\n\/\/ The bases are calculated by src\/fnv_hash_basis.py.\nsize_t hash<abc::str_base>::operator()(abc::str_base const & s) const {\n ABC_TRACE_FUNC(this, s);\n\n static_assert(\n sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,\n \"unexpected sizeof(size_t) will break FNV prime\/basis selection\"\n );\n#if ABC_HOST_WORD_SIZE == 16\n size_t const c_iFNVPrime(0x1135);\n size_t const c_iFNVBasis(16635u);\n#elif ABC_HOST_WORD_SIZE == 32\n size_t const c_iFNVPrime(0x01000193);\n size_t const c_iFNVBasis(2166136261u);\n#elif ABC_HOST_WORD_SIZE == 64\n size_t const c_iFNVPrime(0x00000100000001b3);\n size_t const c_iFNVBasis(14695981039346656037u);\n#endif\n size_t iHash(c_iFNVBasis);\n for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {\n iHash ^= static_cast<size_t>(*it);\n iHash *= c_iFNVPrime;\n }\n return iHash;\n}\n\n} \/\/namespace std\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::mstr\n\n\nnamespace abc {\n\nvoid mstr::_replace_codepoint(char_t * pch, char_t chNew) {\n ABC_TRACE_FUNC(pch, chNew);\n\n size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));\n uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));\n _raw_trivial_vextr_impl::insert_remove(ich, nullptr, sizeof(char_t), cbRemove);\n \/\/ insert_remove() may have switched string buffer, so recalculate pch now.\n pch = chars_begin() + ich;\n \/\/ At this point, insert_remove() validated pch.\n *pch = chNew;\n}\nvoid mstr::_replace_codepoint(char_t * pch, char32_t chNew) {\n ABC_TRACE_FUNC(pch, chNew);\n\n size_t cbInsert(sizeof(char_t) * text::host_char_traits::codepoint_size(chNew));\n size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));\n uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));\n _raw_trivial_vextr_impl::insert_remove(ich, nullptr, cbInsert, cbRemove);\n \/\/ insert_remove() may have switched string buffer, so recalculate pch now.\n pch = chars_begin() + ich;\n \/\/ At this point, insert_remove() validated pch and codepoint_size() validated chNew; this means\n \/\/ that there’s nothing that could go wrong here leaving us in an inconsistent state.\n text::host_char_traits::traits_base::codepoint_to_chars(chNew, pch);\n}\n\n\nvoid mstr::set_from(std::function<size_t (char_t * pch, size_t cchMax)> const & fnRead) {\n ABC_TRACE_FUNC(this\/*, fnRead*\/);\n\n \/\/ The initial size avoids a few reallocations (* smc_iGrowthRate ** 2).\n \/\/ Multiplying by smc_iGrowthRate should guarantee that set_capacity() will allocate exactly the\n \/\/ requested number of characters, eliminating the need to query back with capacity().\n size_t cchRet, cchMax(smc_cbCapacityMin * smc_iGrowthRate);\n do {\n cchMax *= smc_iGrowthRate;\n set_capacity(cchMax, false);\n cchRet = fnRead(chars_begin(), cchMax);\n } while (cchRet >= cchMax);\n \/\/ Finalize the length.\n set_size_in_chars(cchRet);\n}\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2015 Cask Data, Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n* use this file except in compliance with the License. You may obtain a copy of\n* the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n* License for the specific language governing permissions and limitations under\n* the License.\n*\/\n\n#include \"stdafx.h\"\n#include \"NoSchemaColumnsDataReader.h\"\n\nCask::CdapOdbc::NoSchemaColumnsDataReader::NoSchemaColumnsDataReader(const std::wstring& tableName, const QueryResult& queryResult)\n : tableName(tableName)\n , queryResult(queryResult)\n , currentRowIndex(-1) {\n}\n\nbool Cask::CdapOdbc::NoSchemaColumnsDataReader::read() {\n ++this->currentRowIndex;\n return this->currentRowIndex < 3;\n}\n\nvoid Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnValue(const ColumnBinding& binding) {\n static std::array<const wchar_t*, 3> names = { L\"ts\", L\"headers\", L\"body\" };\n\n switch (binding.getColumnNumber()) {\n case 1: \/\/ TABLE_CAT \n case 2: \/\/ TABLE_SCHEM \n case 9: \/\/ DECIMAL_DIGITS \n case 12: \/\/ REMARKS \n case 13: \/\/ COLUMN_DEF \n case 15: \/\/ SQL_DATETIME_SUB \n case 16: \/\/ CHAR_OCTET_LENGTH \n this->fetchNull(binding);\n break;\n case 3: \/\/ TABLE_NAME \n this->fetchVarchar(this->tableName.c_str(), binding);\n break;\n case 4: \/\/ COLUMN_NAME \n\t\t\tif (binding.getTargetType() == SQL_WCHAR) {\n\t\t\t\tthis->fetchWVarchar(names[this->currentRowIndex], binding);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->fetchVarchar(names[this->currentRowIndex], binding);\n\t\t\t}\n break;\n case 5: \/\/ DATA_TYPE\n case 14: \/\/ SQL_DATA_TYPE \n this->fetchSmallint(SQL_CHAR, binding);\n break;\n case 6: \/\/ TYPE_NAME \n this->fetchVarchar(L\"string\", binding);\n break;\n case 7: \/\/ COLUMN_SIZE \n this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);\n break;\n case 8: \/\/ BUFFER_LENGTH \n this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);\n break;\n case 10: \/\/ NUM_PREC_RADIX \n this->fetchSmallint(0, binding);\n break;\n case 11: \/\/ NULLABLE\n this->fetchSmallint(SQL_NULLABLE, binding);\n break;\n case 17: \/\/ ORDINAL_POSITION \n this->fetchInt(this->currentRowIndex + 1, binding);\n break;\n case 18: \/\/ IS_NULLABLE \n this->fetchVarchar(L\"YES\", binding);\n break;\n }\n}\n\nshort Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnCount() const {\n return 18;\n}\n\nstd::unique_ptr<Cask::CdapOdbc::ColumnInfo> Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnInfo(short columnNumber) const {\n return std::unique_ptr<ColumnInfo>();\n}\n<commit_msg>Varchar\/WVarchar check in NoSchemaColumnsDataReader<commit_after>\/*\n* Copyright 2015 Cask Data, Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n* use this file except in compliance with the License. You may obtain a copy of\n* the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n* License for the specific language governing permissions and limitations under\n* the License.\n*\/\n\n#include \"stdafx.h\"\n#include \"NoSchemaColumnsDataReader.h\"\n\nCask::CdapOdbc::NoSchemaColumnsDataReader::NoSchemaColumnsDataReader(const std::wstring& tableName, const QueryResult& queryResult)\n : tableName(tableName)\n , queryResult(queryResult)\n , currentRowIndex(-1) {\n}\n\nbool Cask::CdapOdbc::NoSchemaColumnsDataReader::read() {\n ++this->currentRowIndex;\n return this->currentRowIndex < 3;\n}\n\nvoid Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnValue(const ColumnBinding& binding) {\n static std::array<const wchar_t*, 3> names = { L\"ts\", L\"headers\", L\"body\" };\n\n switch (binding.getColumnNumber()) {\n case 1: \/\/ TABLE_CAT \n case 2: \/\/ TABLE_SCHEM \n case 9: \/\/ DECIMAL_DIGITS \n case 12: \/\/ REMARKS \n case 13: \/\/ COLUMN_DEF \n case 15: \/\/ SQL_DATETIME_SUB \n case 16: \/\/ CHAR_OCTET_LENGTH \n this->fetchNull(binding);\n break;\n case 3: \/\/ TABLE_NAME\n if (binding.getTargetType() == SQL_WCHAR) {\n this->fetchWVarchar(this->tableName.c_str(), binding);\n }\n else {\n this->fetchVarchar(this->tableName.c_str(), binding);\n }\n break;\n case 4: \/\/ COLUMN_NAME \n\t\t\tif (binding.getTargetType() == SQL_WCHAR) {\n\t\t\t\tthis->fetchWVarchar(names[this->currentRowIndex], binding);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->fetchVarchar(names[this->currentRowIndex], binding);\n\t\t\t}\n break;\n case 5: \/\/ DATA_TYPE\n case 14: \/\/ SQL_DATA_TYPE \n this->fetchSmallint(SQL_CHAR, binding);\n break;\n case 6: \/\/ TYPE_NAME\n if (binding.getTargetType() == SQL_WCHAR) {\n this->fetchWVarchar(L\"string\", binding);\n }\n else {\n this->fetchVarchar(L\"string\", binding);\n }\n break;\n case 7: \/\/ COLUMN_SIZE \n this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);\n break;\n case 8: \/\/ BUFFER_LENGTH \n this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);\n break;\n case 10: \/\/ NUM_PREC_RADIX \n this->fetchSmallint(0, binding);\n break;\n case 11: \/\/ NULLABLE\n this->fetchSmallint(SQL_NULLABLE, binding);\n break;\n case 17: \/\/ ORDINAL_POSITION \n this->fetchInt(this->currentRowIndex + 1, binding);\n break;\n case 18: \/\/ IS_NULLABLE \n if (binding.getTargetType() == SQL_WCHAR) {\n this->fetchWVarchar(L\"YES\", binding);\n }\n else {\n this->fetchVarchar(L\"YES\", binding);\n }\n break;\n }\n}\n\nshort Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnCount() const {\n return 18;\n}\n\nstd::unique_ptr<Cask::CdapOdbc::ColumnInfo> Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnInfo(short columnNumber) const {\n return std::unique_ptr<ColumnInfo>();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b2dquadraticbezier.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:24:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_CURVE_B2DQUADRATICBEZIER_HXX\n#define _BGFX_CURVE_B2DQUADRATICBEZIER_HXX\n\n#ifndef _BGFX_POINT_B2DPOINT_HXX\n#include <basegfx\/point\/b2dpoint.hxx>\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n class B2DQuadraticBezier\n {\n ::basegfx::B2DPoint maStartPoint;\n ::basegfx::B2DPoint maEndPoint;\n ::basegfx::B2DPoint maControlPoint;\n\n public:\n B2DQuadraticBezier();\n B2DQuadraticBezier(const B2DQuadraticBezier& rBezier);\n B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart, const ::basegfx::B2DPoint& rEnd);\n B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart,\n const ::basegfx::B2DPoint& rControlPoint, const ::basegfx::B2DPoint& rEnd);\n ~B2DQuadraticBezier();\n\n \/\/ assignment operator\n B2DQuadraticBezier& operator=(const B2DQuadraticBezier& rBezier);\n\n \/\/ compare operators\n bool operator==(const B2DQuadraticBezier& rBezier) const;\n bool operator!=(const B2DQuadraticBezier& rBezier) const;\n\n \/\/ test if control point is placed on the edge\n bool isBezier() const;\n\n \/\/ data interface\n ::basegfx::B2DPoint getStartPoint() const { return maStartPoint; }\n void setStartPoint(const ::basegfx::B2DPoint& rValue) { maStartPoint = rValue; }\n\n ::basegfx::B2DPoint getEndPoint() const { return maEndPoint; }\n void setEndPoint(const ::basegfx::B2DPoint& rValue) { maEndPoint = rValue; }\n\n ::basegfx::B2DPoint getControlPoint() const { return maControlPoint; }\n void setControlPoint(const ::basegfx::B2DPoint& rValue) { maControlPoint = rValue; }\n };\n} \/\/ end of namespace basegfx\n\n#endif \/* _BGFX_CURVE_B2DQUADRATICBEZIER_HXX *\/\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.88); FILE MERGED 2008\/04\/01 10:48:07 thb 1.7.88.2: #i85898# Stripping all external header guards 2008\/03\/28 16:05:38 rt 1.7.88.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b2dquadraticbezier.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _BGFX_CURVE_B2DQUADRATICBEZIER_HXX\n#define _BGFX_CURVE_B2DQUADRATICBEZIER_HXX\n\n#include <basegfx\/point\/b2dpoint.hxx>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace basegfx\n{\n class B2DQuadraticBezier\n {\n ::basegfx::B2DPoint maStartPoint;\n ::basegfx::B2DPoint maEndPoint;\n ::basegfx::B2DPoint maControlPoint;\n\n public:\n B2DQuadraticBezier();\n B2DQuadraticBezier(const B2DQuadraticBezier& rBezier);\n B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart, const ::basegfx::B2DPoint& rEnd);\n B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart,\n const ::basegfx::B2DPoint& rControlPoint, const ::basegfx::B2DPoint& rEnd);\n ~B2DQuadraticBezier();\n\n \/\/ assignment operator\n B2DQuadraticBezier& operator=(const B2DQuadraticBezier& rBezier);\n\n \/\/ compare operators\n bool operator==(const B2DQuadraticBezier& rBezier) const;\n bool operator!=(const B2DQuadraticBezier& rBezier) const;\n\n \/\/ test if control point is placed on the edge\n bool isBezier() const;\n\n \/\/ data interface\n ::basegfx::B2DPoint getStartPoint() const { return maStartPoint; }\n void setStartPoint(const ::basegfx::B2DPoint& rValue) { maStartPoint = rValue; }\n\n ::basegfx::B2DPoint getEndPoint() const { return maEndPoint; }\n void setEndPoint(const ::basegfx::B2DPoint& rValue) { maEndPoint = rValue; }\n\n ::basegfx::B2DPoint getControlPoint() const { return maControlPoint; }\n void setControlPoint(const ::basegfx::B2DPoint& rValue) { maControlPoint = rValue; }\n };\n} \/\/ end of namespace basegfx\n\n#endif \/* _BGFX_CURVE_B2DQUADRATICBEZIER_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"GLContext.h\"\n#include \"ShaderCombinaison.h\"\n#include \"GL.h\"\n#include \"FrameBuffer.h\"\n#include \"Material.h\"\n#include \"VertexArrayObject.h\"\n#include <n\/concurrent\/Thread.h>\n#include <n\/core\/Timer.h>\n\n#include <iostream>\n\nnamespace n {\nnamespace graphics {\n\nGLAPIENTRY void debugOut(gl::GLenum, gl::GLenum type, gl::GLuint, gl::GLuint sev, gl::GLsizei len, const char *msg, const void *) {\n\tif(sev == GL_DEBUG_SEVERITY_NOTIFICATION) {\n\t\treturn;\n\t}\n\tcore::String t;\n\tswitch(type) {\n\t\tcase GL_DEBUG_TYPE_PERFORMANCE:\n\t\t\tt = \"[perf]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_PORTABILITY:\n\t\t\tt = \"[port]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n\t\t\tt = \"[depr]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_ERROR:\n\t\t\tt = \"[err]\";\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n\n\tstd::cerr<<std::endl<<\"[GL]\"<<(sev == GL_DEBUG_SEVERITY_HIGH ? \"[HIGH]\" : \"\")<<t<<\" \"<<core::String(msg, len)<<std::endl;\n}\n\nGLContext *GLContext::getContext() {\n\tstatic GLContext *ct = 0;\n\tif(!ct) {\n\t\tct = new GLContext();\n\t\tShaderProgram(ct->program).bind();\n\t}\n\treturn ct;\n}\n\nvoid GLContext::flush() {\n\tgl::glFlush();\n}\n\nvoid GLContext::addGLTask(const core::Functor<void()> &f) {\n\ttasks.queue(f);\n}\n\nbool GLContext::processTasks() {\n\tcore::Option<core::Functor<void()>> tsk = tasks.tryDequeue();\n\tif(tsk) {\n\t\ttsk.get()();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid GLContext::finishTasks() {\n\tcore::List<core::Functor<void()>> tsk = tasks.getAndClear();\n\tfor(const core::Functor<void()> &f : tsk) {\n\t\tf();\n\t}\n}\n\nGLContext::GLContext() : shader(0), program(ShaderProgram::getNullProgram()), frameBuffer(0), material(0), viewport(800, 600), screen(0) {\n\tif(concurrent::Thread::getCurrent()) {\n\t\tfatal(\"n::graphics::Context not created on main thread.\");\n\t}\n\tgl::glewExperimental = true;\n\tif(gl::glewInit() != GLEW_OK) {\n\t\tfatal(\"Unable to initialize glew.\");\n\t}\n\tstd::cout<<\"Running on \"<<gl::glGetString(GL_VENDOR)<<\" \"<<gl::glGetString(GL_RENDERER)<<\" using GL \"<<gl::glGetString(GL_VERSION);\n\t#ifdef N_32BITS\n\tstd::cout<<\" (32 bits)\";\n\t#endif\n\tstd::cout<<std::endl;\n\n\n\t\/\/gl::glEnable(GL_TEXTURE_2D);\n\t\/\/gl::glEnable(GL_CULL_FACE);\n\t\/\/gl::glEnable(GL_DEPTH_TEST);\n\n\tgl::glViewport(0, 0, viewport.x(), viewport.y());\n\n\tfor(uint i = 0; i != Max; i++) {\n\t\thwInts[i] = 0;\n\t}\n\n\tgl::glGetIntegerv(GL_MAX_DRAW_BUFFERS, &hwInts[MaxFboAttachements]);\n\tgl::glGetIntegerv(GL_MAX_TEXTURE_UNITS, &hwInts[MaxTextures]);\n\tgl::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &hwInts[MaxVertexAttribs]);\n\n\tif(hwInts[MaxVertexAttribs] <= 4) {\n\t\tfatal(\"No enought vertex attribs.\");\n\t}\n\n\n\t#define CHECK_TEX_FORMAT(frm) if(!Texture::isHWSupported(ImageFormat::frm)) { fatal((\"Texture format \" + core::String(#frm) + \" not supported\").toChar()); }\n\n\tCHECK_TEX_FORMAT(RGBA32F);\n\tCHECK_TEX_FORMAT(RGBA16);\n\tCHECK_TEX_FORMAT(RG16);\n\tCHECK_TEX_FORMAT(F32);\n\tCHECK_TEX_FORMAT(Depth32);\n\n\t#undef CHECK_TEX_FORMAT\n\n\tgl::glGetError();\n\n\tgl::glDebugMessageCallback(&debugOut, 0);\n\tgl::glEnable(GL_DEBUG_OUTPUT);\n}\n\nGLContext::~GLContext() {\n\tdelete screen;\n\tfinishTasks();\n}\n\nvoid GLContext::setDebugEnabled(bool deb) {\n\tif(deb) {\n\t\tgl::glEnable(GL_DEBUG_OUTPUT);\n\t} else {\n\t\tgl::glDisable(GL_DEBUG_OUTPUT);\n\t}\n}\n\nvoid GLContext::setViewport(const math::Vec2ui &v) {\n\tviewport = v;\n\tif(!frameBuffer) {\n\t\tgl::glViewport(0, 0, viewport.x(), viewport.y());\n\t}\n}\n\nmath::Vec2ui GLContext::getViewport() const {\n\treturn frameBuffer ? frameBuffer->getSize() : viewport;\n}\n\nbool GLContext::checkGLError() {\n\tint error = gl::glGetError();\n\tif(error) {\n\t\tfatal((\"Warning : error : \" + (error == GL_INVALID_OPERATION ? core::String(\"INVALID OPERATION\") :\n\t\t\t(error == GL_INVALID_ENUM ? core::String(\"INVALID ENUM\") :\n\t\t\t(error == GL_INVALID_VALUE ? core::String(\"INVALID VALUE\") :\n\t\t\t(error == GL_OUT_OF_MEMORY ? core::String(\"OUT OF MEMORY\") : core::String(error)))))).toChar());\n\t\treturn true; \/\/ just in case...\n\t}\n\treturn false;\n}\n\nvoid GLContext::setModelMatrix(const math::Matrix4<> &m) {\n\tmodel = m;\n\t#ifdef N_USE_MATRIX_BUFFER\n\tmatrixBuffer->set(model, 0);\n\tmatrixBuffer->bind(0);\n\t#else\n\tif(shader) {\n\t\tshader->setValue(\"n_ModelMatrix\", model);\n\t}\n\t#endif\n}\n\nvoid GLContext::setViewMatrix(const math::Matrix4<> &m) {\n\tif(view == m) {\n\t\treturn;\n\t}\n\tview = m;\n\tif(shader) {\n\t\tshader->setValue(\"n_ViewMatrix\", m);\n\t\tshader->setValue(\"n_ViewProjectionMatrix\", projection * m);\n\t}\n}\n\nvoid GLContext::setProjectionMatrix(const math::Matrix4<> &m) {\n\tif(projection == m) {\n\t\treturn;\n\t}\n\tprojection = m;\n\tif(shader) {\n\t\tshader->setValue(\"n_ProjectionMatrix\", m);\n\t\tshader->setValue(\"n_ViewProjectionMatrix\", m * view);\n\t}\n}\n\nconst math::Matrix4<> &GLContext::getProjectionMatrix() const {\n\treturn projection;\n}\n\nconst math::Matrix4<> &GLContext::getViewMatrix() const {\n\treturn view;\n}\n\nconst math::Matrix4<> &GLContext::getModelMatrix() const {\n\treturn model;\n}\n\nconst VertexArrayObject<float> &GLContext::getScreen() const {\n\tif(!screen) {\n\t\tscreen = new VertexArrayObject<float>(TriangleBuffer<>::getScreen());\n\t}\n\treturn *screen;\n}\n\n}\n}\n\n\n\n\n<commit_msg>Added OGL verion check (for 4.3)<commit_after>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"GLContext.h\"\n#include \"ShaderCombinaison.h\"\n#include \"GL.h\"\n#include \"FrameBuffer.h\"\n#include \"Material.h\"\n#include \"VertexArrayObject.h\"\n#include <n\/concurrent\/Thread.h>\n#include <n\/core\/Timer.h>\n\n#include <iostream>\n\nnamespace n {\nnamespace graphics {\n\nGLAPIENTRY void debugOut(gl::GLenum, gl::GLenum type, gl::GLuint, gl::GLuint sev, gl::GLsizei len, const char *msg, const void *) {\n\tif(sev == GL_DEBUG_SEVERITY_NOTIFICATION) {\n\t\treturn;\n\t}\n\tcore::String t;\n\tswitch(type) {\n\t\tcase GL_DEBUG_TYPE_PERFORMANCE:\n\t\t\tt = \"[perf]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_PORTABILITY:\n\t\t\tt = \"[port]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n\t\t\tt = \"[depr]\";\n\t\tbreak;\n\t\tcase GL_DEBUG_TYPE_ERROR:\n\t\t\tt = \"[err]\";\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n\n\tstd::cerr<<std::endl<<\"[GL]\"<<(sev == GL_DEBUG_SEVERITY_HIGH ? \"[HIGH]\" : \"\")<<t<<\" \"<<core::String(msg, len)<<std::endl;\n}\n\nGLContext *GLContext::getContext() {\n\tstatic GLContext *ct = 0;\n\tif(!ct) {\n\t\tct = new GLContext();\n\t\tShaderProgram(ct->program).bind();\n\t}\n\treturn ct;\n}\n\nvoid GLContext::flush() {\n\tgl::glFlush();\n}\n\nvoid GLContext::addGLTask(const core::Functor<void()> &f) {\n\ttasks.queue(f);\n}\n\nbool GLContext::processTasks() {\n\tcore::Option<core::Functor<void()>> tsk = tasks.tryDequeue();\n\tif(tsk) {\n\t\ttsk.get()();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid GLContext::finishTasks() {\n\tcore::List<core::Functor<void()>> tsk = tasks.getAndClear();\n\tfor(const core::Functor<void()> &f : tsk) {\n\t\tf();\n\t}\n}\n\nGLContext::GLContext() : shader(0), program(ShaderProgram::getNullProgram()), frameBuffer(0), material(0), viewport(800, 600), screen(0) {\n\tif(concurrent::Thread::getCurrent()) {\n\t\tfatal(\"n::graphics::Context not created on main thread.\");\n\t}\n\tgl::glewExperimental = true;\n\tif(gl::glewInit() != GLEW_OK) {\n\t\tfatal(\"Unable to initialize glew.\");\n\t}\n\tstd::cout<<\"Running on \"<<gl::glGetString(GL_VENDOR)<<\" \"<<gl::glGetString(GL_RENDERER)<<\" using GL \"<<gl::glGetString(GL_VERSION);\n\t#ifdef N_32BITS\n\tstd::cout<<\" (32 bits)\";\n\t#endif\n\tstd::cout<<std::endl;\n\t\n\tint major = 0;\n\tint minor = 0;\n\tgl::glGetIntegerv(GL_MAJOR_VERSION, &major);\n\tgl::glGetIntegerv(GL_MINOR_VERSION, &minor);\n\tif(major > 4 || (major == 4 && minor > 3)) {\n\t\tfatal(\"This needs OpenGL 4.3 or newer to run\");\n\t}\n\n\n\t\/\/gl::glEnable(GL_TEXTURE_2D);\n\t\/\/gl::glEnable(GL_CULL_FACE);\n\t\/\/gl::glEnable(GL_DEPTH_TEST);\n\n\tgl::glViewport(0, 0, viewport.x(), viewport.y());\n\n\tfor(uint i = 0; i != Max; i++) {\n\t\thwInts[i] = 0;\n\t}\n\n\tgl::glGetIntegerv(GL_MAX_DRAW_BUFFERS, &hwInts[MaxFboAttachements]);\n\tgl::glGetIntegerv(GL_MAX_TEXTURE_UNITS, &hwInts[MaxTextures]);\n\tgl::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &hwInts[MaxVertexAttribs]);\n\n\tif(hwInts[MaxVertexAttribs] <= 4) {\n\t\tfatal(\"No enought vertex attribs.\");\n\t}\n\n\n\t#define CHECK_TEX_FORMAT(frm) if(!Texture::isHWSupported(ImageFormat::frm)) { fatal((\"Texture format \" + core::String(#frm) + \" not supported\").toChar()); }\n\n\tCHECK_TEX_FORMAT(RGBA32F);\n\tCHECK_TEX_FORMAT(RGBA16);\n\tCHECK_TEX_FORMAT(RG16);\n\tCHECK_TEX_FORMAT(F32);\n\tCHECK_TEX_FORMAT(Depth32);\n\n\t#undef CHECK_TEX_FORMAT\n\n\tgl::glGetError();\n\n\tgl::glDebugMessageCallback(&debugOut, 0);\n\tgl::glEnable(GL_DEBUG_OUTPUT);\n}\n\nGLContext::~GLContext() {\n\tdelete screen;\n\tfinishTasks();\n}\n\nvoid GLContext::setDebugEnabled(bool deb) {\n\tif(deb) {\n\t\tgl::glEnable(GL_DEBUG_OUTPUT);\n\t} else {\n\t\tgl::glDisable(GL_DEBUG_OUTPUT);\n\t}\n}\n\nvoid GLContext::setViewport(const math::Vec2ui &v) {\n\tviewport = v;\n\tif(!frameBuffer) {\n\t\tgl::glViewport(0, 0, viewport.x(), viewport.y());\n\t}\n}\n\nmath::Vec2ui GLContext::getViewport() const {\n\treturn frameBuffer ? frameBuffer->getSize() : viewport;\n}\n\nbool GLContext::checkGLError() {\n\tint error = gl::glGetError();\n\tif(error) {\n\t\tfatal((\"Warning : error : \" + (error == GL_INVALID_OPERATION ? core::String(\"INVALID OPERATION\") :\n\t\t\t(error == GL_INVALID_ENUM ? core::String(\"INVALID ENUM\") :\n\t\t\t(error == GL_INVALID_VALUE ? core::String(\"INVALID VALUE\") :\n\t\t\t(error == GL_OUT_OF_MEMORY ? core::String(\"OUT OF MEMORY\") : core::String(error)))))).toChar());\n\t\treturn true; \/\/ just in case...\n\t}\n\treturn false;\n}\n\nvoid GLContext::setModelMatrix(const math::Matrix4<> &m) {\n\tmodel = m;\n\t#ifdef N_USE_MATRIX_BUFFER\n\tmatrixBuffer->set(model, 0);\n\tmatrixBuffer->bind(0);\n\t#else\n\tif(shader) {\n\t\tshader->setValue(\"n_ModelMatrix\", model);\n\t}\n\t#endif\n}\n\nvoid GLContext::setViewMatrix(const math::Matrix4<> &m) {\n\tif(view == m) {\n\t\treturn;\n\t}\n\tview = m;\n\tif(shader) {\n\t\tshader->setValue(\"n_ViewMatrix\", m);\n\t\tshader->setValue(\"n_ViewProjectionMatrix\", projection * m);\n\t}\n}\n\nvoid GLContext::setProjectionMatrix(const math::Matrix4<> &m) {\n\tif(projection == m) {\n\t\treturn;\n\t}\n\tprojection = m;\n\tif(shader) {\n\t\tshader->setValue(\"n_ProjectionMatrix\", m);\n\t\tshader->setValue(\"n_ViewProjectionMatrix\", m * view);\n\t}\n}\n\nconst math::Matrix4<> &GLContext::getProjectionMatrix() const {\n\treturn projection;\n}\n\nconst math::Matrix4<> &GLContext::getViewMatrix() const {\n\treturn view;\n}\n\nconst math::Matrix4<> &GLContext::getModelMatrix() const {\n\treturn model;\n}\n\nconst VertexArrayObject<float> &GLContext::getScreen() const {\n\tif(!screen) {\n\t\tscreen = new VertexArrayObject<float>(TriangleBuffer<>::getScreen());\n\t}\n\treturn *screen;\n}\n\n}\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * kPPP: A pppd front end for the KDE project\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n *\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n\n#include <qlayout.h>\n#include <qpainter.h>\n#include <kapp.h>\n#include <kwm.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include \"pppdata.h\"\n#include \"pppstatdlg.h\"\n#include \"kpppconfig.h\"\n#include \"iplined.h\"\n#include <klocale.h>\n#include \"pppstats.h\"\n\nextern PPPData gpppdata;\n\nPPPStats stats;\n\nPPPStatsDlg::PPPStatsDlg(QWidget *parent, const char *name, QWidget *)\n : QWidget(parent, name, 0 )\n{\n int i;\n max = 1024;\n\n setCaption(i18n(\"kppp Statistics\"));\n KWM::setMiniIcon(winId(), kapp->miniIcon());\n\n QVBoxLayout *tl = new QVBoxLayout(this, 10);\n QGridLayout *l1 = new QGridLayout(4, 4);\n tl->addLayout(l1, 1);\n box = new QGroupBox(i18n(\"Statistics\"), this);\n l1->addMultiCellWidget(box, 0, 3, 0, 3);\n l1->addRowSpacing(0, fontMetrics().lineSpacing() - 10);\n l1->setRowStretch(1, 1);\n l1->setColStretch(1, 1);\n\n \/\/ inner part of the grid\n QVBoxLayout *l11 = new QVBoxLayout;\n l1->addLayout(l11, 1, 1);\n\n \/\/ modem pixmap and IP labels\n QHBoxLayout *l111 = new QHBoxLayout;\n l11->addLayout(l111);\n\n big_modem_both_pixmap = BarIcon(\"modemboth\");\n big_modem_left_pixmap = BarIcon(\"modemleft\");\n big_modem_right_pixmap = BarIcon(\"modemright\");\n big_modem_none_pixmap = BarIcon(\"modemnone\");\n\n pixmap_l = new QLabel(this);\n pixmap_l->setMinimumSize(big_modem_both_pixmap.size());\n l111->addWidget(pixmap_l, 1);\n pixmap_l->setAlignment(AlignVCenter|AlignLeft);\n\n QGridLayout *l1112 = new QGridLayout(3, 2);\n l111->addLayout(l1112);\n\n ip_address_label1 = new QLabel(this);\n ip_address_label1->setText(i18n(\"Local Addr:\"));\n\n ip_address_label2 = new IPLineEdit(this);\n ip_address_label2->setFocusPolicy(QWidget::NoFocus);\n\n ip_address_label3 = new QLabel(this);\n ip_address_label3->setText(i18n(\"Remote Addr:\"));\n\n ip_address_label4 = new IPLineEdit(this);\n ip_address_label4->setFocusPolicy(QWidget::NoFocus);\n\n l1112->addWidget(ip_address_label1, 0, 0);\n l1112->addWidget(ip_address_label2, 0, 1);\n l1112->addWidget(ip_address_label3, 1, 0);\n l1112->addWidget(ip_address_label4, 1, 1);\n\n \/\/ consumes space on bottom\n l1112->setRowStretch(2, 1);\n\n QGridLayout *l112 = new QGridLayout(5, 4);\n l11->addLayout(l112);\n for(i =0 ; i < 5; i++) {\n labela1[i] = new QLabel(this);\n\n labela2[i] = new QLabel(this);\n labela2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);\n\n labelb1[i] = new QLabel(this);\n\n labelb2[i] = new QLabel(this);\n labelb2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);\n }\n\n labela1[0]->setText(i18n(\"bytes in\"));\n labelb1[0]->setText(i18n(\"bytes out\"));\n\n labela1[1]->setText(i18n(\"packets in\"));\n labelb1[1]->setText(i18n(\"packets out\"));\n\n labela1[2]->setText(i18n(\"vjcomp in\"));\n labelb1[2]->setText(i18n(\"vjcomp out\"));\n\n labela1[3]->setText(i18n(\"vjunc in\"));\n labelb1[3]->setText(i18n(\"vjunc out\"));\n\n labela1[4]->setText(i18n(\"vjerr\"));\n labelb1[4]->setText(i18n(\"non-vj\"));\n\n for(i = 0; i < 5; i++) {\n labela2[i]->setText(\"88888888\");\n labelb2[i]->setText(\"88888888\");\n labela2[i]->setFixedSize(labela2[i]->sizeHint());\n labelb2[i]->setFixedSize(labelb2[i]->sizeHint());\n labela2[i]->setText(\"\");\n labelb2[i]->setText(\"\");\n\n \/\/ add to layout\n l112->addWidget(labela1[i], i, 0);\n l112->addWidget(labela2[i], i, 1);\n l112->addWidget(labelb1[i], i, 2);\n l112->addWidget(labelb2[i], i, 3);\n }\n\n l112->setColStretch(1, 1);\n l112->setColStretch(3, 1);\n\n tl->addSpacing(5);\n QHBoxLayout *l12 = new QHBoxLayout;\n tl->addLayout(l12);\n l12->addStretch(1);\n\n if(gpppdata.graphingEnabled()) {\n bool dummy;\n\n gpppdata.graphingOptions(dummy, bg, text, in, out);\n\n graph = new QFrame(this);\n graph->setFrameStyle(QFrame::Box | QFrame::Sunken);\n l1->addMultiCellWidget(graph, 2, 2, 1, 2);\n graph->setMinimumWidth(300);\n graph->setFixedHeight(76+4);\n graph->setBackgroundColor(bg);\n }\n\n cancelbutton = new QPushButton(this, \"cancelbutton\");\n cancelbutton->setText(i18n(\"Close\"));\n cancelbutton->setFocus();\n connect(cancelbutton, SIGNAL(clicked()), this,SLOT(cancel()));\n cancelbutton->setFixedHeight(cancelbutton->sizeHint().height());\n cancelbutton->setMinimumWidth(QMAX(cancelbutton->sizeHint().width(), 70));\n l12->addWidget(cancelbutton);\n\n if(gpppdata.graphingEnabled()) {\n graphTimer = new QTimer(this);\n connect(graphTimer, SIGNAL(timeout()), SLOT(updateGraph()));\n }\n\n setFixedSize(sizeHint());\n\n connect(&stats, SIGNAL(statsChanged(int)), SLOT(paintIcon(int)));\n}\n\n\nPPPStatsDlg::~PPPStatsDlg() {\n}\n\n\nvoid PPPStatsDlg::cancel() {\n hide();\n}\n\n\nvoid PPPStatsDlg::take_stats() {\n stats.initStats();\n ips_set = false;\n bin_last = stats.ibytes;\n bout_last = stats.obytes; \n ringIdx = 0;\n for(int i = 0; i < MAX_GRAPH_WIDTH; i++) {\n bin[i] = -1;\n bout[i] = -1;\n }\n\n update_data();\n\n stats.start();\n if(gpppdata.graphingEnabled())\n graphTimer->start(GRAPH_UPDATE_TIME); \n}\n\n\nvoid PPPStatsDlg::stop_stats() {\n stats.stop();\n if(gpppdata.graphingEnabled())\n graphTimer->stop();\n}\n\nvoid PPPStatsDlg::paintGraph() {\n \/\/ why draw that stuff if not visible?\n if(!isVisible())\n return;\n\n QPixmap pm(graph->width() - 4, graph->height() - 4);\n QPainter p;\n pm.fill(graph->backgroundColor());\n p.begin(&pm);\n\n int x;\n int idx = ringIdx - pm.width() + 1;\n if(idx < 0)\n idx += MAX_GRAPH_WIDTH;\n \n \/\/ find good scaling factor \n int last_h_in = \n pm.height() - (int)((float)bin[idx]\/max * (pm.height() - 8))-1;\n int last_h_out = \n pm.height() - (int)((float)bout[idx]\/max * (pm.height() - 8))-1;\n \n \/\/ plot scale line\n p.setPen(text);\n p.setFont(QFont(\"fixed\", 8));\n\n \/\/ plot data\n int last_idx = 0;\n for(x = 1; x < pm.width(); x++) {\n int h_in, h_out;\n \n h_in = pm.height() - (int)((float)bin[idx]\/max * (pm.height() - 8))-1;\n h_out = pm.height() - (int)((float)bout[idx]\/max * (pm.height() - 8))-1;\n \n p.setPen(out); \n if(bout[idx]!=-1)\n p.drawLine(x-1, last_h_out, x, h_out);\n p.setPen(in);\n if(bin[idx]!=-1)\n p.drawLine(x-1, last_h_in, x, h_in);\n last_h_in = h_in;\n last_h_out = h_out;\n\n last_idx = idx;\n idx = (idx + 1) % MAX_GRAPH_WIDTH;\n }\n\n \/\/ take last value\n int last_max = bin[last_idx]>bout[last_idx] ? bin[last_idx] : bout[last_idx];\n\n QRect r;\n QString s;\n s.sprintf(i18n(\"%0.1f (max. %0.1f) kb\/sec\"), (float)last_max \/ 1024.0, (float)max \/ 1024.0);\n s = i18n(\"%1 (max. %2) kb\/sec\")\n\t\t.arg(QString().setNum((float)last_max \/ 1024.0, 'f', 1))\n\t\t.arg(QString().setNum((float)max \/ 1024.0, 'f', 1));\n p.drawText(0, 0, pm.width(), 2*8, AlignRight|AlignVCenter, s, -1, &r);\n p.drawLine(0, 8, r.left() - 8, 8);\n\n p.end();\n bitBlt(graph, 2, 2, &pm, 0, 0, pm.width(), pm.height(), CopyROP);\n}\n\nvoid PPPStatsDlg::updateGraph() {\n bin[ringIdx] = stats.ibytes - bin_last;\n bout[ringIdx] = stats.obytes - bout_last;\n if(bin[ringIdx] > max)\n max = ((bin[ringIdx] \/ 1024) + 1) * 1024;\n \n if(bout[ringIdx] > max)\n max = ((bout[ringIdx] \/ 1024) + 1) * 1024;\n \n bin_last = stats.ibytes;\n bout_last = stats.obytes;\n ringIdx = (ringIdx + 1) % MAX_GRAPH_WIDTH;\n paintGraph();\n}\n\n\nvoid PPPStatsDlg::paintEvent (QPaintEvent *) {\n paintIcon(PPPStats::BytesNone); \/\/ correct ?\n if(gpppdata.graphingEnabled())\n paintGraph();\n}\n\n\nvoid PPPStatsDlg::paintIcon(int status) {\n\n const QPixmap *pixmap;\n\n switch(status)\n {\n case PPPStats::BytesIn:\n pixmap = &big_modem_left_pixmap;\n break;\n case PPPStats::BytesOut:\n pixmap = &big_modem_right_pixmap;\n break;\n case PPPStats::BytesBoth:\n pixmap = &big_modem_both_pixmap;\n break;\n case PPPStats::BytesNone:\n default:\n pixmap = &big_modem_none_pixmap;\n break;\n }\n\n bitBlt(pixmap_l, 0, 0, pixmap);\n\n update_data();\n}\n\n\nvoid PPPStatsDlg::timeclick() {\n \/\/ volume accounting\n switch(gpppdata.VolAcctEnabled()) {\n case 0: \/\/ no accounting\n break;\n\n case 1: \/\/ bytes in\n stats.totalbytes = gpppdata.totalBytes() + stats.ibytes;\n break;\n\n case 2:\n stats.totalbytes = gpppdata.totalBytes() + stats.obytes;\n break;\n\n case 3:\n stats.totalbytes = gpppdata.totalBytes() + stats.ibytes + stats.obytes;\n break;\n }\n}\n\n\nvoid PPPStatsDlg::closeEvent( QCloseEvent *e ) {\n e->ignore();\n}\n\n\nvoid PPPStatsDlg::update_data() {\n timeclick();\n\n ibytes_string.sprintf(\"%d\", stats.ibytes);\n ipackets_string.sprintf(\"%d\", stats.ipackets);\n compressedin_string.sprintf(\"%d\", stats.compressedin);\n uncompressedin_string.sprintf(\"%d\", stats.uncompressedin);\n errorin_string.sprintf(\"%d\", stats.errorin);\n obytes_string.sprintf(\"%d\", stats.obytes);\n opackets_string.sprintf(\"%d\", stats.opackets);\n compressed_string.sprintf(\"%d\", stats.compressed);\n packetsunc_string.sprintf(\"%d\", stats.packetsunc);\n packetsoutunc_string.sprintf(\"%d\", stats.packetsoutunc);\n\n labela2[0]->setText(ibytes_string);\n labela2[1]->setText(ipackets_string);\n labela2[2]->setText(compressedin_string);\n labela2[3]->setText(uncompressedin_string);\n labela2[4]->setText(errorin_string);\n\n labelb2[0]->setText(obytes_string);\n labelb2[1]->setText(opackets_string);\n labelb2[2]->setText(compressed_string);\n labelb2[3]->setText(packetsunc_string);\n labelb2[4]->setText(packetsoutunc_string);\n\n if(!ips_set) {\n \/\/ if I don't resort to this trick it is imposible to\n \/\/ copy\/paste the ip out of the lineedits due to\n \/\/ reset of cursor position on setText()\n\n if( !stats.local_ip_address.isEmpty() )\n ip_address_label2->setText(stats.local_ip_address);\n else\n ip_address_label2->setText(i18n(\"unavailable\"));\n\n if( !stats.remote_ip_address.isEmpty() )\n ip_address_label4->setText(stats.remote_ip_address);\n else\n ip_address_label4->setText(i18n(\"unavailable\"));\n \n ips_set = true;\n }\n}\n\n#include \"pppstatdlg.moc\"\n\n<commit_msg>don't ignore close attempts (bug #2203)<commit_after>\/*\n * kPPP: A pppd front end for the KDE project\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n *\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n\n#include <qlayout.h>\n#include <qpainter.h>\n#include <kapp.h>\n#include <kwm.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include \"pppdata.h\"\n#include \"pppstatdlg.h\"\n#include \"kpppconfig.h\"\n#include \"iplined.h\"\n#include <klocale.h>\n#include \"pppstats.h\"\n\nextern PPPData gpppdata;\n\nPPPStats stats;\n\nPPPStatsDlg::PPPStatsDlg(QWidget *parent, const char *name, QWidget *)\n : QWidget(parent, name, 0 )\n{\n int i;\n max = 1024;\n\n setCaption(i18n(\"kppp Statistics\"));\n KWM::setMiniIcon(winId(), kapp->miniIcon());\n\n QVBoxLayout *tl = new QVBoxLayout(this, 10);\n QGridLayout *l1 = new QGridLayout(4, 4);\n tl->addLayout(l1, 1);\n box = new QGroupBox(i18n(\"Statistics\"), this);\n l1->addMultiCellWidget(box, 0, 3, 0, 3);\n l1->addRowSpacing(0, fontMetrics().lineSpacing() - 10);\n l1->setRowStretch(1, 1);\n l1->setColStretch(1, 1);\n\n \/\/ inner part of the grid\n QVBoxLayout *l11 = new QVBoxLayout;\n l1->addLayout(l11, 1, 1);\n\n \/\/ modem pixmap and IP labels\n QHBoxLayout *l111 = new QHBoxLayout;\n l11->addLayout(l111);\n\n big_modem_both_pixmap = BarIcon(\"modemboth\");\n big_modem_left_pixmap = BarIcon(\"modemleft\");\n big_modem_right_pixmap = BarIcon(\"modemright\");\n big_modem_none_pixmap = BarIcon(\"modemnone\");\n\n pixmap_l = new QLabel(this);\n pixmap_l->setMinimumSize(big_modem_both_pixmap.size());\n l111->addWidget(pixmap_l, 1);\n pixmap_l->setAlignment(AlignVCenter|AlignLeft);\n\n QGridLayout *l1112 = new QGridLayout(3, 2);\n l111->addLayout(l1112);\n\n ip_address_label1 = new QLabel(this);\n ip_address_label1->setText(i18n(\"Local Addr:\"));\n\n ip_address_label2 = new IPLineEdit(this);\n ip_address_label2->setFocusPolicy(QWidget::NoFocus);\n\n ip_address_label3 = new QLabel(this);\n ip_address_label3->setText(i18n(\"Remote Addr:\"));\n\n ip_address_label4 = new IPLineEdit(this);\n ip_address_label4->setFocusPolicy(QWidget::NoFocus);\n\n l1112->addWidget(ip_address_label1, 0, 0);\n l1112->addWidget(ip_address_label2, 0, 1);\n l1112->addWidget(ip_address_label3, 1, 0);\n l1112->addWidget(ip_address_label4, 1, 1);\n\n \/\/ consumes space on bottom\n l1112->setRowStretch(2, 1);\n\n QGridLayout *l112 = new QGridLayout(5, 4);\n l11->addLayout(l112);\n for(i =0 ; i < 5; i++) {\n labela1[i] = new QLabel(this);\n\n labela2[i] = new QLabel(this);\n labela2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);\n\n labelb1[i] = new QLabel(this);\n\n labelb2[i] = new QLabel(this);\n labelb2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);\n }\n\n labela1[0]->setText(i18n(\"bytes in\"));\n labelb1[0]->setText(i18n(\"bytes out\"));\n\n labela1[1]->setText(i18n(\"packets in\"));\n labelb1[1]->setText(i18n(\"packets out\"));\n\n labela1[2]->setText(i18n(\"vjcomp in\"));\n labelb1[2]->setText(i18n(\"vjcomp out\"));\n\n labela1[3]->setText(i18n(\"vjunc in\"));\n labelb1[3]->setText(i18n(\"vjunc out\"));\n\n labela1[4]->setText(i18n(\"vjerr\"));\n labelb1[4]->setText(i18n(\"non-vj\"));\n\n for(i = 0; i < 5; i++) {\n labela2[i]->setText(\"88888888\");\n labelb2[i]->setText(\"88888888\");\n labela2[i]->setFixedSize(labela2[i]->sizeHint());\n labelb2[i]->setFixedSize(labelb2[i]->sizeHint());\n labela2[i]->setText(\"\");\n labelb2[i]->setText(\"\");\n\n \/\/ add to layout\n l112->addWidget(labela1[i], i, 0);\n l112->addWidget(labela2[i], i, 1);\n l112->addWidget(labelb1[i], i, 2);\n l112->addWidget(labelb2[i], i, 3);\n }\n\n l112->setColStretch(1, 1);\n l112->setColStretch(3, 1);\n\n tl->addSpacing(5);\n QHBoxLayout *l12 = new QHBoxLayout;\n tl->addLayout(l12);\n l12->addStretch(1);\n\n if(gpppdata.graphingEnabled()) {\n bool dummy;\n\n gpppdata.graphingOptions(dummy, bg, text, in, out);\n\n graph = new QFrame(this);\n graph->setFrameStyle(QFrame::Box | QFrame::Sunken);\n l1->addMultiCellWidget(graph, 2, 2, 1, 2);\n graph->setMinimumWidth(300);\n graph->setFixedHeight(76+4);\n graph->setBackgroundColor(bg);\n }\n\n cancelbutton = new QPushButton(this, \"cancelbutton\");\n cancelbutton->setText(i18n(\"Close\"));\n cancelbutton->setFocus();\n connect(cancelbutton, SIGNAL(clicked()), this,SLOT(cancel()));\n cancelbutton->setFixedHeight(cancelbutton->sizeHint().height());\n cancelbutton->setMinimumWidth(QMAX(cancelbutton->sizeHint().width(), 70));\n l12->addWidget(cancelbutton);\n\n if(gpppdata.graphingEnabled()) {\n graphTimer = new QTimer(this);\n connect(graphTimer, SIGNAL(timeout()), SLOT(updateGraph()));\n }\n\n setFixedSize(sizeHint());\n\n connect(&stats, SIGNAL(statsChanged(int)), SLOT(paintIcon(int)));\n}\n\n\nPPPStatsDlg::~PPPStatsDlg() {\n}\n\n\nvoid PPPStatsDlg::cancel() {\n hide();\n}\n\n\nvoid PPPStatsDlg::take_stats() {\n stats.initStats();\n ips_set = false;\n bin_last = stats.ibytes;\n bout_last = stats.obytes; \n ringIdx = 0;\n for(int i = 0; i < MAX_GRAPH_WIDTH; i++) {\n bin[i] = -1;\n bout[i] = -1;\n }\n\n update_data();\n\n stats.start();\n if(gpppdata.graphingEnabled())\n graphTimer->start(GRAPH_UPDATE_TIME); \n}\n\n\nvoid PPPStatsDlg::stop_stats() {\n stats.stop();\n if(gpppdata.graphingEnabled())\n graphTimer->stop();\n}\n\nvoid PPPStatsDlg::paintGraph() {\n \/\/ why draw that stuff if not visible?\n if(!isVisible())\n return;\n\n QPixmap pm(graph->width() - 4, graph->height() - 4);\n QPainter p;\n pm.fill(graph->backgroundColor());\n p.begin(&pm);\n\n int x;\n int idx = ringIdx - pm.width() + 1;\n if(idx < 0)\n idx += MAX_GRAPH_WIDTH;\n \n \/\/ find good scaling factor \n int last_h_in = \n pm.height() - (int)((float)bin[idx]\/max * (pm.height() - 8))-1;\n int last_h_out = \n pm.height() - (int)((float)bout[idx]\/max * (pm.height() - 8))-1;\n \n \/\/ plot scale line\n p.setPen(text);\n p.setFont(QFont(\"fixed\", 8));\n\n \/\/ plot data\n int last_idx = 0;\n for(x = 1; x < pm.width(); x++) {\n int h_in, h_out;\n \n h_in = pm.height() - (int)((float)bin[idx]\/max * (pm.height() - 8))-1;\n h_out = pm.height() - (int)((float)bout[idx]\/max * (pm.height() - 8))-1;\n \n p.setPen(out); \n if(bout[idx]!=-1)\n p.drawLine(x-1, last_h_out, x, h_out);\n p.setPen(in);\n if(bin[idx]!=-1)\n p.drawLine(x-1, last_h_in, x, h_in);\n last_h_in = h_in;\n last_h_out = h_out;\n\n last_idx = idx;\n idx = (idx + 1) % MAX_GRAPH_WIDTH;\n }\n\n \/\/ take last value\n int last_max = bin[last_idx]>bout[last_idx] ? bin[last_idx] : bout[last_idx];\n\n QRect r;\n QString s;\n s.sprintf(i18n(\"%0.1f (max. %0.1f) kb\/sec\"), (float)last_max \/ 1024.0, (float)max \/ 1024.0);\n s = i18n(\"%1 (max. %2) kb\/sec\")\n\t\t.arg(QString().setNum((float)last_max \/ 1024.0, 'f', 1))\n\t\t.arg(QString().setNum((float)max \/ 1024.0, 'f', 1));\n p.drawText(0, 0, pm.width(), 2*8, AlignRight|AlignVCenter, s, -1, &r);\n p.drawLine(0, 8, r.left() - 8, 8);\n\n p.end();\n bitBlt(graph, 2, 2, &pm, 0, 0, pm.width(), pm.height(), CopyROP);\n}\n\nvoid PPPStatsDlg::updateGraph() {\n bin[ringIdx] = stats.ibytes - bin_last;\n bout[ringIdx] = stats.obytes - bout_last;\n if(bin[ringIdx] > max)\n max = ((bin[ringIdx] \/ 1024) + 1) * 1024;\n \n if(bout[ringIdx] > max)\n max = ((bout[ringIdx] \/ 1024) + 1) * 1024;\n \n bin_last = stats.ibytes;\n bout_last = stats.obytes;\n ringIdx = (ringIdx + 1) % MAX_GRAPH_WIDTH;\n paintGraph();\n}\n\n\nvoid PPPStatsDlg::paintEvent (QPaintEvent *) {\n paintIcon(PPPStats::BytesNone); \/\/ correct ?\n if(gpppdata.graphingEnabled())\n paintGraph();\n}\n\n\nvoid PPPStatsDlg::paintIcon(int status) {\n\n const QPixmap *pixmap;\n\n switch(status)\n {\n case PPPStats::BytesIn:\n pixmap = &big_modem_left_pixmap;\n break;\n case PPPStats::BytesOut:\n pixmap = &big_modem_right_pixmap;\n break;\n case PPPStats::BytesBoth:\n pixmap = &big_modem_both_pixmap;\n break;\n case PPPStats::BytesNone:\n default:\n pixmap = &big_modem_none_pixmap;\n break;\n }\n\n bitBlt(pixmap_l, 0, 0, pixmap);\n\n update_data();\n}\n\n\nvoid PPPStatsDlg::timeclick() {\n \/\/ volume accounting\n switch(gpppdata.VolAcctEnabled()) {\n case 0: \/\/ no accounting\n break;\n\n case 1: \/\/ bytes in\n stats.totalbytes = gpppdata.totalBytes() + stats.ibytes;\n break;\n\n case 2:\n stats.totalbytes = gpppdata.totalBytes() + stats.obytes;\n break;\n\n case 3:\n stats.totalbytes = gpppdata.totalBytes() + stats.ibytes + stats.obytes;\n break;\n }\n}\n\n\nvoid PPPStatsDlg::closeEvent( QCloseEvent *e ) {\n emit cancel();\n}\n\n\nvoid PPPStatsDlg::update_data() {\n timeclick();\n\n ibytes_string.sprintf(\"%d\", stats.ibytes);\n ipackets_string.sprintf(\"%d\", stats.ipackets);\n compressedin_string.sprintf(\"%d\", stats.compressedin);\n uncompressedin_string.sprintf(\"%d\", stats.uncompressedin);\n errorin_string.sprintf(\"%d\", stats.errorin);\n obytes_string.sprintf(\"%d\", stats.obytes);\n opackets_string.sprintf(\"%d\", stats.opackets);\n compressed_string.sprintf(\"%d\", stats.compressed);\n packetsunc_string.sprintf(\"%d\", stats.packetsunc);\n packetsoutunc_string.sprintf(\"%d\", stats.packetsoutunc);\n\n labela2[0]->setText(ibytes_string);\n labela2[1]->setText(ipackets_string);\n labela2[2]->setText(compressedin_string);\n labela2[3]->setText(uncompressedin_string);\n labela2[4]->setText(errorin_string);\n\n labelb2[0]->setText(obytes_string);\n labelb2[1]->setText(opackets_string);\n labelb2[2]->setText(compressed_string);\n labelb2[3]->setText(packetsunc_string);\n labelb2[4]->setText(packetsoutunc_string);\n\n if(!ips_set) {\n \/\/ if I don't resort to this trick it is imposible to\n \/\/ copy\/paste the ip out of the lineedits due to\n \/\/ reset of cursor position on setText()\n\n if( !stats.local_ip_address.isEmpty() )\n ip_address_label2->setText(stats.local_ip_address);\n else\n ip_address_label2->setText(i18n(\"unavailable\"));\n\n if( !stats.remote_ip_address.isEmpty() )\n ip_address_label4->setText(stats.remote_ip_address);\n else\n ip_address_label4->setText(i18n(\"unavailable\"));\n \n ips_set = true;\n }\n}\n\n#include \"pppstatdlg.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2011, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __ARRAYS_H\n#define __ARRAYS_H\n\n#include <cstdlib>\n#include <cassert>\n\nnamespace mozart {\n\n\/**\n * A simple wrapper for an array and its size (only in debug mode)\n * @param <T> Type of the elements in the array\n *\/\ntemplate <class T>\nclass StaticArray {\nprivate:\n \/\/ Apparently, std::nullptr_t is not defined in every standard library yet\n typedef decltype(nullptr) nullptr_t;\nprivate:\n T* _array;\n\n#ifndef NDEBUG\n int _size;\n#endif\n\npublic:\n \/** Create an array with s elements *\/\n StaticArray(T* array, int s) : _array(array) {\n#ifndef NDEBUG\n _size = s;\n#endif\n }\n\n \/** Create an array with no element *\/\n StaticArray() : _array(nullptr) {\n#ifndef NDEBUG\n _size = 0;\n#endif\n }\n\n \/** Convert from nullptr *\/\n StaticArray(nullptr_t nullp) : _array(nullptr) {\n#ifndef NDEBUG\n _size = 0;\n#endif\n }\n\n \/** Zero-based access to elements (read-write) *\/\n inline\n T& operator[](int i) {\n assert(0 <= i && i < _size);\n return _array[i];\n }\n\n \/** Convert to a raw array *\/\n inline\n operator T*() {\n return _array;\n }\n\n \/** Assign from nullptr *\/\n inline\n void operator=(nullptr_t nullp) {\n _array = nullptr;\n#ifndef NDEBUG\n _size = 0;\n#endif\n }\n};\n\n}\n\n#endif \/\/ __ARRAYS_H\n<commit_msg>Protect StaticArray._size under a dedicated define (not just NDEBUG).<commit_after>\/\/ Copyright © 2011, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __ARRAYS_H\n#define __ARRAYS_H\n\n#include <cstdlib>\n#include <cassert>\n\nnamespace mozart {\n\n\/**\n * A simple wrapper for an array and its size (only in debug mode)\n * @param <T> Type of the elements in the array\n *\/\ntemplate <class T>\nclass StaticArray {\nprivate:\n \/\/ Apparently, std::nullptr_t is not defined in every standard library yet\n typedef decltype(nullptr) nullptr_t;\nprivate:\n T* _array;\n\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n int _size;\n#endif\n\npublic:\n \/** Create an array with s elements *\/\n StaticArray(T* array, int s) : _array(array) {\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n _size = s;\n#endif\n }\n\n \/** Create an array with no element *\/\n StaticArray() : _array(nullptr) {\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n _size = 0;\n#endif\n }\n\n \/** Convert from nullptr *\/\n StaticArray(nullptr_t nullp) : _array(nullptr) {\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n _size = 0;\n#endif\n }\n\n \/** Zero-based access to elements (read-write) *\/\n inline\n T& operator[](int i) {\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n assert(0 <= i && i < _size);\n#endif\n return _array[i];\n }\n\n \/** Convert to a raw array *\/\n inline\n operator T*() {\n return _array;\n }\n\n \/** Assign from nullptr *\/\n inline\n void operator=(nullptr_t nullp) {\n _array = nullptr;\n#ifdef MOZART_STATICARRAY_WITH_SIZE\n _size = 0;\n#endif\n }\n};\n\n}\n\n#endif \/\/ __ARRAYS_H\n<|endoftext|>"} {"text":"<commit_before>#include \"ros\/ros.h\"\n#include \"boost\/asio.hpp\"\n#include \"jaws_msgs\/Thrusters.h\"\n\nclass Arbotix\n{\n private:\n ros::NodeHandle nh;\n ros::Subscriber sub;\n boost::asio::io_service i_o;\n boost::asio::serial_port s_p;\n std::string port_name;\n int br;\n char c;\n std::string feedback;\n public:\n Arbotix() : nh(), i_o(), s_p(i_o)\n {\n nh.getParam(\"\/arbotix_node\/port_name\",port_name);\n nh.getParam(\"\/arbotix_node\/baud_rate\",br);\n s_p.open(port_name);\n s_p.set_option(boost::asio::serial_port_base::baud_rate(br));\n\n sub = nh.subscribe<jaws_msgs::Thrusters>(\"thrusters\", 1, &Arbotix::callback, this);\n }\n void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)\n {\n const int SIZE = 11;\n unsigned char packet[SIZE];\n\n packet[0] = '-';\n\n packet[1] = (thrusters->port_angle >> 8) & 0xFF;\n packet[2] = thrusters->port_angle & 0xFF;\n\n packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;\n packet[4] = thrusters->stbd_angle & 0xFF;\n\n packet[5] = (thrusters->aft_power >> 8) & 0xFF;\n packet[6] = thrusters->aft_power & 0xFF;\n\n packet[7] = (thrusters->port_power >> 8) & 0xFF;\n packet[8] = thrusters->port_power & 0xFF;\n\n packet[9] = (thrusters->stbd_power >> 8) & 0xFF;\n packet[10] = thrusters->stbd_power & 0xFF;\n\n s_p.write_some(boost::asio::buffer(&packet, SIZE));\n \n while(c!=\"\\n\"){\n c=s_p.read_some(boost::asio::buffer(&c,1);\n if(c!=\"\\n\"){\n \t feedback+=c;\n\t }\n }\n ROS_INFO(\"%s\",feedback);\n\n }\n void loop()\n {\n ros::spin();\n }\n};\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"arbotix_node\");\n Arbotix arbotix;\n arbotix.loop();\n}\n<commit_msg>Code to close and reopen serial if it stops responding<commit_after>#include \"ros\/ros.h\"\n#include \"boost\/asio.hpp\"\n#include \"jaws_msgs\/Thrusters.h\"\n#include \"time.h\"\nclass Arbotix\n{\n private:\n ros::NodeHandle nh;\n ros::Subscriber sub;\n boost::asio::io_service i_o;\n boost::asio::serial_port s_p;\n std::string port_name;\n int br;\n char c;\n std::string feedback;\n public:\n Arbotix() : nh(), i_o(), s_p(i_o)\n {\n nh.getParam(\"\/arbotix_node\/port_name\",port_name);\n nh.getParam(\"\/arbotix_node\/baud_rate\",br);\n s_p.open(port_name);\n s_p.set_option(boost::asio::serial_port_base::baud_rate(br));\n\n sub = nh.subscribe<jaws_msgs::Thrusters>(\"thrusters\", 1, &Arbotix::callback, this);\n }\n void restartPort()\n {\n\tnh.getParam(\"\/arbotix_node\/port_name\",port_name);\n\tnh.getParam(\"\/arbotix_node\/baud_rate\",br);\n\ts_p.close();\n s_p.open(port_name);\n\ts_p.set_option(boost::asio::serial_port_base::baud_rate(br));\n }\n void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)\n {\n const int SIZE = 11;\n unsigned char packet[SIZE];\n\t\n unsigned int start=clock();\n packet[0] = '-';\n\n packet[1] = (thrusters->port_angle >> 8) & 0xFF;\n packet[2] = thrusters->port_angle & 0xFF;\n\n packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;\n packet[4] = thrusters->stbd_angle & 0xFF;\n\n packet[5] = (thrusters->aft_power >> 8) & 0xFF;\n packet[6] = thrusters->aft_power & 0xFF;\n\n packet[7] = (thrusters->port_power >> 8) & 0xFF;\n packet[8] = thrusters->port_power & 0xFF;\n packet[9] = (thrusters->stbd_power >> 8) & 0xFF;\n packet[10] = thrusters->stbd_power & 0xFF;\n\n s_p.write_some(boost::asio::buffer(&packet, SIZE));\n c='a';\n while(c!='\\n'){\n c=s_p.read_some(boost::asio::buffer(&c,1));\n if(c!='\\n'){\n \t feedback+=c;\n\t }\n\telse{\n\t\tbreak;\n\t}\n\tif((clock()-start\/CLOCKS_PER_SEC)>5000){\n\t restartPort();\n\t break;\n\t}\n }\n ROS_INFO(\"%s\",feedback.c_str());\n\n }\n void loop()\n {\n ros::spin();\n }\n};\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"arbotix_node\");\n Arbotix arbotix;\n arbotix.loop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Library: CTK\n \n Copyright (c) 2010 Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.commontk.org\/LICENSE\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n=========================================================================*\/\n\/*=========================================================================\n\n Program: ParaView\n Module: $RCSfile$\n\n Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.\n All rights reserved.\n\n ParaView is a free software; you can redistribute it and\/or modify it\n under the terms of the ParaView license version 1.2. \n\n See License_v1.2.txt for the full ParaView license.\n A copy of this license can be obtained by contacting\n Kitware Inc.\n 28 Corporate Drive\n Clifton Park, NY 12065\n USA\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n\/\/#include <vtkPython.h> \/\/ python first\n\n\/\/ Qt includes\n#include <QCoreApplication>\n#include <QResizeEvent>\n#include <QScrollBar>\n#include <QStringListModel>\n#include <QTextCharFormat>\n#include <QVBoxLayout>\n\n\/\/ PythonQt includes\n#include <PythonQt.h>\n#include <PythonQtObjectPtr.h>\n\n\/\/ CTK includes\n#include <ctkConsoleWidget.h>\n#include <ctkAbstractPythonManager.h>\n#include \"ctkPythonShell.h\"\n\n\/\/----------------------------------------------------------------------------\nclass ctkPythonShellCompleter : public ctkConsoleWidgetCompleter\n{\npublic:\n ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)\n {\n this->setParent(&p);\n }\n\n virtual void updateCompletionModel(const QString& completion)\n {\n \/\/ Start by clearing the model\n this->setModel(0);\n\n \/\/ Don't try to complete the empty string\n if (completion.isEmpty())\n {\n return;\n }\n\n \/\/ Search backward through the string for usable characters\n QString textToComplete;\n for (int i = completion.length()-1; i >= 0; --i)\n {\n QChar c = completion.at(i);\n if (c.isLetterOrNumber() || c == '.' || c == '_')\n {\n textToComplete.prepend(c);\n }\n else\n {\n break;\n }\n }\n\n \/\/ Split the string at the last dot, if one exists\n QString lookup;\n QString compareText = textToComplete;\n int dot = compareText.lastIndexOf('.');\n if (dot != -1)\n {\n lookup = compareText.mid(0, dot);\n compareText = compareText.mid(dot+1);\n }\n\n \/\/ Lookup python names\n QStringList attrs;\n if (!lookup.isEmpty() || !compareText.isEmpty())\n {\n attrs = Parent.getPythonAttributes(lookup);\n }\n\n \/\/ Initialize the completion model\n if (!attrs.isEmpty())\n {\n this->setCompletionMode(QCompleter::PopupCompletion);\n this->setModel(new QStringListModel(attrs, this));\n this->setCaseSensitivity(Qt::CaseInsensitive);\n this->setCompletionPrefix(compareText.toLower());\n this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));\n }\n }\n ctkPythonShell& Parent;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ctkPythonShell::pqImplementation\n\nstruct ctkPythonShell::pqImplementation\n{\n pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)\n : Console(_parent), PythonManager(pythonManager)\n {\n }\n\n\/\/----------------------------------------------------------------------------\n\/\/ void initialize(int argc, char* argv[])\n\/\/ {\n\/\/ \/\/ Setup Python's interactive prompts\n\/\/ PyObject* ps1 = PySys_GetObject(const_cast<char*>(\"ps1\"));\n\/\/ if(!ps1)\n\/\/ {\n\/\/ PySys_SetObject(const_cast<char*>(\"ps1\"), ps1 = PyString_FromString(\">>> \"));\n\/\/ Py_XDECREF(ps1);\n\/\/ }\n\/\/ \n\/\/ PyObject* ps2 = PySys_GetObject(const_cast<char*>(\"ps2\"));\n\/\/ if(!ps2)\n\/\/ {\n\/\/ PySys_SetObject(const_cast<char*>(\"ps2\"), ps2 = PyString_FromString(\"... \"));\n\/\/ Py_XDECREF(ps2);\n\/\/ }\n\/\/ this->MultilineStatement = false;\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\n ~pqImplementation()\n {\n\/\/ this->destroyInterpretor();\n }\n\n\/\/----------------------------------------------------------------------------\n\/\/ void destroyInterpretor()\n\/\/ {\n\/\/ if (this->Interpreter)\n\/\/ {\n\/\/ QTextCharFormat format = this->Console.getFormat();\n\/\/ format.setForeground(QColor(255, 0, 0));\n\/\/ this->Console.setFormat(format);\n\/\/ this->Console.printString(\"\\n... restarting ...\\n\");\n\/\/ format.setForeground(QColor(0, 0, 0));\n\/\/ this->Console.setFormat(format);\n\/\/ \n\/\/ this->Interpreter->MakeCurrent();\n\/\/ \n\/\/ \/\/ Restore Python's original stdout and stderr\n\/\/ PySys_SetObject(const_cast<char*>(\"stdout\"), PySys_GetObject(const_cast<char*>(\"__stdout__\")));\n\/\/ PySys_SetObject(const_cast<char*>(\"stderr\"), PySys_GetObject(const_cast<char*>(\"__stderr__\")));\n\/\/ this->Interpreter->ReleaseControl();\n\/\/ this->Interpreter->Delete();\n\/\/ }\n\/\/ this->Interpreter = 0;\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\n void executeCommand(const QString& command)\n {\n\/\/ this->MultilineStatement = \n\/\/ this->Interpreter->Push(Command.toAscii().data());\n if (command.length())\n {\n Q_ASSERT(this->PythonManager);\n this->PythonManager->executeString(command);\n }\n }\n \n\/\/----------------------------------------------------------------------------\n void promptForInput(const QString& indent=QString())\n {\n QTextCharFormat format = this->Console.getFormat();\n format.setForeground(QColor(0, 0, 0));\n this->Console.setFormat(format);\n\n\/\/ this->Interpreter->MakeCurrent();\n if(!this->MultilineStatement)\n {\n this->Console.prompt(\">>> \");\n \/\/this->Console.prompt(\n \/\/ PyString_AsString(PySys_GetObject(const_cast<char*>(\"ps1\"))));\n }\n else\n {\n this->Console.prompt(\"... \");\n \/\/this->Console.prompt(\n \/\/ PyString_AsString(PySys_GetObject(const_cast<char*>(\"ps2\"))));\n }\n this->Console.printCommand(indent);\n\/\/ this->Interpreter->ReleaseControl();\n }\n\n \/\/\/ Provides a console for gathering user input and displaying \n \/\/\/ Python output\n ctkConsoleWidget Console;\n\n ctkAbstractPythonManager* PythonManager;\n\n \/\/\/ Indicates if the last statement processes was incomplete.\n bool MultilineStatement;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ctkPythonShell\n\n\/\/----------------------------------------------------------------------------\nctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):\n Superclass(_parent),\n Implementation(new pqImplementation(this, pythonManager))\n{\n \/\/ Layout UI\n QVBoxLayout* const boxLayout = new QVBoxLayout(this);\n boxLayout->setMargin(0);\n boxLayout->addWidget(&this->Implementation->Console);\n\n this->setObjectName(\"pythonShell\");\n\n ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);\n this->Implementation->Console.setCompleter(completer);\n \n QObject::connect(\n &this->Implementation->Console, SIGNAL(executeCommand(const QString&)), \n this, SLOT(onExecuteCommand(const QString&)));\n\n \/\/ The call to mainContext() ensures that python has been initialized.\n Q_ASSERT(this->Implementation->PythonManager);\n this->Implementation->PythonManager->mainContext();\n\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 0, 255));\n this->Implementation->Console.setFormat(format);\n this->Implementation->Console.printString(\n QString(\"Python %1 on %2\\n\").arg(Py_GetVersion()).arg(Py_GetPlatform()));\n this->promptForInput();\n\n Q_ASSERT(PythonQt::self());\n\n this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),\n SLOT(printStdout(const QString&)));\n this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),\n SLOT(printStderr(const QString&)));\n}\n\n\/\/----------------------------------------------------------------------------\nctkPythonShell::~ctkPythonShell()\n{\n delete this->Implementation;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::clear()\n{\n this->Implementation->Console.clear();\n this->Implementation->promptForInput();\n}\n\n\/\/ \/\/----------------------------------------------------------------------------\n\/\/ void ctkPythonShell::makeCurrent()\n\/\/ {\n\/\/ this->Implementation->Interpreter->MakeCurrent();\n\/\/ }\n\/\/ \n\/\/ \/\/----------------------------------------------------------------------------\n\/\/ void ctkPythonShell::releaseControl()\n\/\/ {\n\/\/ this->Implementation->Interpreter->ReleaseControl();\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::executeScript(const QString& script)\n{\n Q_UNUSED(script);\n \n this->printStdout(\"\\n\");\n emit this->executing(true);\n\/\/ this->Implementation->Interpreter->RunSimpleString(\n\/\/ script.toAscii().data());\n emit this->executing(false);\n this->Implementation->promptForInput();\n}\n\n\/\/----------------------------------------------------------------------------\nQStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)\n{\n\/\/ this->makeCurrent();\n\n Q_ASSERT(PyThreadState_GET()->interp);\n PyObject* dict = PyImport_GetModuleDict();\n PyObject* object = PyDict_GetItemString(dict, \"__main__\");\n Py_INCREF(object);\n\n\n if (!pythonVariableName.isEmpty())\n {\n QStringList tmpNames = pythonVariableName.split('.');\n for (int i = 0; i < tmpNames.size() && object; ++i)\n {\n QByteArray tmpName = tmpNames.at(i).toLatin1();\n PyObject* prevObj = object;\n if (PyDict_Check(object))\n {\n object = PyDict_GetItemString(object, tmpName.data());\n Py_XINCREF(object);\n }\n else\n {\n object = PyObject_GetAttrString(object, tmpName.data());\n }\n Py_DECREF(prevObj);\n }\n PyErr_Clear();\n }\n\n QStringList results;\n if (object)\n {\n PyObject* keys = PyObject_Dir(object);\n if (keys)\n {\n PyObject* key;\n PyObject* value;\n QString keystr;\n int nKeys = PyList_Size(keys);\n for (int i = 0; i < nKeys; ++i)\n {\n key = PyList_GetItem(keys, i);\n value = PyObject_GetAttr(object, key);\n if (!value)\n {\n continue;\n }\n\n results << PyString_AsString(key);\n Py_DECREF(value);\n }\n Py_DECREF(keys);\n }\n Py_DECREF(object);\n }\n\n\/\/ this->releaseControl();\n return results;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printStdout(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 150, 0));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n \n QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printMessage(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 0, 150));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printStderr(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(255, 0, 0));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n \n QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::onExecuteCommand(const QString& Command)\n{\n QString command = Command;\n command.replace(QRegExp(\"\\\\s*$\"), \"\");\n this->internalExecuteCommand(command);\n\n \/\/ Find the indent for the command.\n QRegExp regExp(\"^(\\\\s+)\");\n QString indent;\n if (regExp.indexIn(command) != -1)\n {\n indent = regExp.cap(1);\n }\n this->Implementation->promptForInput(indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::promptForInput()\n{\n this->Implementation->promptForInput();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::internalExecuteCommand(const QString& command)\n{\n emit this->executing(true); \n this->Implementation->executeCommand(command);\n emit this->executing(false);\n}\n<commit_msg>COMP: Use \"pragma GCC diagnostic ignored\" trick to shut up python old-style-cast warnings<commit_after>\/*=========================================================================\n\n Library: CTK\n \n Copyright (c) 2010 Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.commontk.org\/LICENSE\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n=========================================================================*\/\n\/*=========================================================================\n\n Program: ParaView\n Module: $RCSfile$\n\n Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.\n All rights reserved.\n\n ParaView is a free software; you can redistribute it and\/or modify it\n under the terms of the ParaView license version 1.2. \n\n See License_v1.2.txt for the full ParaView license.\n A copy of this license can be obtained by contacting\n Kitware Inc.\n 28 Corporate Drive\n Clifton Park, NY 12065\n USA\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n\/\/#include <vtkPython.h> \/\/ python first\n\n\/\/ Qt includes\n#include <QCoreApplication>\n#include <QResizeEvent>\n#include <QScrollBar>\n#include <QStringListModel>\n#include <QTextCharFormat>\n#include <QVBoxLayout>\n\n\/\/ PythonQt includes\n#include <PythonQt.h>\n#include <PythonQtObjectPtr.h>\n\n\/\/ CTK includes\n#include <ctkConsoleWidget.h>\n#include <ctkAbstractPythonManager.h>\n#include \"ctkPythonShell.h\"\n\n\/\/ Disable warnings related to Python macros and functions\n\/\/ See http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Diagnostic-Pragmas.html\n\/\/ Note: Ideally the incriminated functions and macros should be fixed upstream ...\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n\n\/\/----------------------------------------------------------------------------\nclass ctkPythonShellCompleter : public ctkConsoleWidgetCompleter\n{\npublic:\n ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)\n {\n this->setParent(&p);\n }\n\n virtual void updateCompletionModel(const QString& completion)\n {\n \/\/ Start by clearing the model\n this->setModel(0);\n\n \/\/ Don't try to complete the empty string\n if (completion.isEmpty())\n {\n return;\n }\n\n \/\/ Search backward through the string for usable characters\n QString textToComplete;\n for (int i = completion.length()-1; i >= 0; --i)\n {\n QChar c = completion.at(i);\n if (c.isLetterOrNumber() || c == '.' || c == '_')\n {\n textToComplete.prepend(c);\n }\n else\n {\n break;\n }\n }\n\n \/\/ Split the string at the last dot, if one exists\n QString lookup;\n QString compareText = textToComplete;\n int dot = compareText.lastIndexOf('.');\n if (dot != -1)\n {\n lookup = compareText.mid(0, dot);\n compareText = compareText.mid(dot+1);\n }\n\n \/\/ Lookup python names\n QStringList attrs;\n if (!lookup.isEmpty() || !compareText.isEmpty())\n {\n attrs = Parent.getPythonAttributes(lookup);\n }\n\n \/\/ Initialize the completion model\n if (!attrs.isEmpty())\n {\n this->setCompletionMode(QCompleter::PopupCompletion);\n this->setModel(new QStringListModel(attrs, this));\n this->setCaseSensitivity(Qt::CaseInsensitive);\n this->setCompletionPrefix(compareText.toLower());\n this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));\n }\n }\n ctkPythonShell& Parent;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ctkPythonShell::pqImplementation\n\nstruct ctkPythonShell::pqImplementation\n{\n pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)\n : Console(_parent), PythonManager(pythonManager)\n {\n }\n\n\/\/----------------------------------------------------------------------------\n\/\/ void initialize(int argc, char* argv[])\n\/\/ {\n\/\/ \/\/ Setup Python's interactive prompts\n\/\/ PyObject* ps1 = PySys_GetObject(const_cast<char*>(\"ps1\"));\n\/\/ if(!ps1)\n\/\/ {\n\/\/ PySys_SetObject(const_cast<char*>(\"ps1\"), ps1 = PyString_FromString(\">>> \"));\n\/\/ Py_XDECREF(ps1);\n\/\/ }\n\/\/ \n\/\/ PyObject* ps2 = PySys_GetObject(const_cast<char*>(\"ps2\"));\n\/\/ if(!ps2)\n\/\/ {\n\/\/ PySys_SetObject(const_cast<char*>(\"ps2\"), ps2 = PyString_FromString(\"... \"));\n\/\/ Py_XDECREF(ps2);\n\/\/ }\n\/\/ this->MultilineStatement = false;\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\n ~pqImplementation()\n {\n\/\/ this->destroyInterpretor();\n }\n\n\/\/----------------------------------------------------------------------------\n\/\/ void destroyInterpretor()\n\/\/ {\n\/\/ if (this->Interpreter)\n\/\/ {\n\/\/ QTextCharFormat format = this->Console.getFormat();\n\/\/ format.setForeground(QColor(255, 0, 0));\n\/\/ this->Console.setFormat(format);\n\/\/ this->Console.printString(\"\\n... restarting ...\\n\");\n\/\/ format.setForeground(QColor(0, 0, 0));\n\/\/ this->Console.setFormat(format);\n\/\/ \n\/\/ this->Interpreter->MakeCurrent();\n\/\/ \n\/\/ \/\/ Restore Python's original stdout and stderr\n\/\/ PySys_SetObject(const_cast<char*>(\"stdout\"), PySys_GetObject(const_cast<char*>(\"__stdout__\")));\n\/\/ PySys_SetObject(const_cast<char*>(\"stderr\"), PySys_GetObject(const_cast<char*>(\"__stderr__\")));\n\/\/ this->Interpreter->ReleaseControl();\n\/\/ this->Interpreter->Delete();\n\/\/ }\n\/\/ this->Interpreter = 0;\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\n void executeCommand(const QString& command)\n {\n\/\/ this->MultilineStatement = \n\/\/ this->Interpreter->Push(Command.toAscii().data());\n if (command.length())\n {\n Q_ASSERT(this->PythonManager);\n this->PythonManager->executeString(command);\n }\n }\n \n\/\/----------------------------------------------------------------------------\n void promptForInput(const QString& indent=QString())\n {\n QTextCharFormat format = this->Console.getFormat();\n format.setForeground(QColor(0, 0, 0));\n this->Console.setFormat(format);\n\n\/\/ this->Interpreter->MakeCurrent();\n if(!this->MultilineStatement)\n {\n this->Console.prompt(\">>> \");\n \/\/this->Console.prompt(\n \/\/ PyString_AsString(PySys_GetObject(const_cast<char*>(\"ps1\"))));\n }\n else\n {\n this->Console.prompt(\"... \");\n \/\/this->Console.prompt(\n \/\/ PyString_AsString(PySys_GetObject(const_cast<char*>(\"ps2\"))));\n }\n this->Console.printCommand(indent);\n\/\/ this->Interpreter->ReleaseControl();\n }\n\n \/\/\/ Provides a console for gathering user input and displaying \n \/\/\/ Python output\n ctkConsoleWidget Console;\n\n ctkAbstractPythonManager* PythonManager;\n\n \/\/\/ Indicates if the last statement processes was incomplete.\n bool MultilineStatement;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ctkPythonShell\n\n\/\/----------------------------------------------------------------------------\nctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):\n Superclass(_parent),\n Implementation(new pqImplementation(this, pythonManager))\n{\n \/\/ Layout UI\n QVBoxLayout* const boxLayout = new QVBoxLayout(this);\n boxLayout->setMargin(0);\n boxLayout->addWidget(&this->Implementation->Console);\n\n this->setObjectName(\"pythonShell\");\n\n ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);\n this->Implementation->Console.setCompleter(completer);\n \n QObject::connect(\n &this->Implementation->Console, SIGNAL(executeCommand(const QString&)), \n this, SLOT(onExecuteCommand(const QString&)));\n\n \/\/ The call to mainContext() ensures that python has been initialized.\n Q_ASSERT(this->Implementation->PythonManager);\n this->Implementation->PythonManager->mainContext();\n\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 0, 255));\n this->Implementation->Console.setFormat(format);\n this->Implementation->Console.printString(\n QString(\"Python %1 on %2\\n\").arg(Py_GetVersion()).arg(Py_GetPlatform()));\n this->promptForInput();\n\n Q_ASSERT(PythonQt::self());\n\n this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),\n SLOT(printStdout(const QString&)));\n this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),\n SLOT(printStderr(const QString&)));\n}\n\n\/\/----------------------------------------------------------------------------\nctkPythonShell::~ctkPythonShell()\n{\n delete this->Implementation;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::clear()\n{\n this->Implementation->Console.clear();\n this->Implementation->promptForInput();\n}\n\n\/\/ \/\/----------------------------------------------------------------------------\n\/\/ void ctkPythonShell::makeCurrent()\n\/\/ {\n\/\/ this->Implementation->Interpreter->MakeCurrent();\n\/\/ }\n\/\/ \n\/\/ \/\/----------------------------------------------------------------------------\n\/\/ void ctkPythonShell::releaseControl()\n\/\/ {\n\/\/ this->Implementation->Interpreter->ReleaseControl();\n\/\/ }\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::executeScript(const QString& script)\n{\n Q_UNUSED(script);\n \n this->printStdout(\"\\n\");\n emit this->executing(true);\n\/\/ this->Implementation->Interpreter->RunSimpleString(\n\/\/ script.toAscii().data());\n emit this->executing(false);\n this->Implementation->promptForInput();\n}\n\n\/\/----------------------------------------------------------------------------\nQStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)\n{\n\/\/ this->makeCurrent();\n\n Q_ASSERT(PyThreadState_GET()->interp);\n PyObject* dict = PyImport_GetModuleDict();\n PyObject* object = PyDict_GetItemString(dict, \"__main__\");\n Py_INCREF(object);\n\n\n if (!pythonVariableName.isEmpty())\n {\n QStringList tmpNames = pythonVariableName.split('.');\n for (int i = 0; i < tmpNames.size() && object; ++i)\n {\n QByteArray tmpName = tmpNames.at(i).toLatin1();\n PyObject* prevObj = object;\n if (PyDict_Check(object))\n {\n object = PyDict_GetItemString(object, tmpName.data());\n Py_XINCREF(object);\n }\n else\n {\n object = PyObject_GetAttrString(object, tmpName.data());\n }\n Py_DECREF(prevObj);\n }\n PyErr_Clear();\n }\n\n QStringList results;\n if (object)\n {\n PyObject* keys = PyObject_Dir(object);\n if (keys)\n {\n PyObject* key;\n PyObject* value;\n QString keystr;\n int nKeys = PyList_Size(keys);\n for (int i = 0; i < nKeys; ++i)\n {\n key = PyList_GetItem(keys, i);\n value = PyObject_GetAttr(object, key);\n if (!value)\n {\n continue;\n }\n\n results << PyString_AsString(key);\n Py_DECREF(value);\n }\n Py_DECREF(keys);\n }\n Py_DECREF(object);\n }\n\n\/\/ this->releaseControl();\n return results;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printStdout(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 150, 0));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n \n QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printMessage(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(0, 0, 150));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::printStderr(const QString& text)\n{\n QTextCharFormat format = this->Implementation->Console.getFormat();\n format.setForeground(QColor(255, 0, 0));\n this->Implementation->Console.setFormat(format);\n \n this->Implementation->Console.printString(text);\n \n QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::onExecuteCommand(const QString& Command)\n{\n QString command = Command;\n command.replace(QRegExp(\"\\\\s*$\"), \"\");\n this->internalExecuteCommand(command);\n\n \/\/ Find the indent for the command.\n QRegExp regExp(\"^(\\\\s+)\");\n QString indent;\n if (regExp.indexIn(command) != -1)\n {\n indent = regExp.cap(1);\n }\n this->Implementation->promptForInput(indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::promptForInput()\n{\n this->Implementation->promptForInput();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkPythonShell::internalExecuteCommand(const QString& command)\n{\n emit this->executing(true); \n this->Implementation->executeCommand(command);\n emit this->executing(false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\/*=========================================================================\n *\n * Portions of this file are subject to the VTK Toolkit Version 3 copyright.\n *\n * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n *\n * For complete copyright, license and disclaimer of warranty information\n * please refer to the NOTICE file at the top of the ITK source tree.\n *\n *=========================================================================*\/\n#ifndef itkResourceProbe_hxx\n#define itkResourceProbe_hxx\n\n#include <numeric>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n#include <functional>\n\n#include \"itkResourceProbe.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkMultiThreader.h\"\n#include \"itksys\/SystemInformation.hxx\"\n\nnamespace itk\n{\n\ntemplate< typename ValueType, typename MeanType >\nResourceProbe< ValueType, MeanType >\n::ResourceProbe(const std::string & type, const std::string & unit):\n m_TypeString(type), m_UnitString(unit)\n{\n this->GetSystemInformation();\n this->Reset();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nResourceProbe< ValueType, MeanType >\n::~ResourceProbe()\n{}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Reset(void)\n{\n this->m_TotalValue = NumericTraits< ValueType >::ZeroValue();\n this->m_StartValue = NumericTraits< ValueType >::ZeroValue();\n this->m_MinimumValue = NumericTraits< ValueType >::max();\n this->m_MaximumValue = NumericTraits< ValueType >::min();\n this->m_MeanValue = NumericTraits< ValueType >::ZeroValue();\n this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();\n\n this->m_NumberOfStarts = NumericTraits< CountType >::ZeroValue();\n this->m_NumberOfStops = NumericTraits< CountType >::ZeroValue();\n this->m_NumberOfIteration = NumericTraits< CountType >::ZeroValue();\n\n this->m_ProbeValueList.clear();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetType(void) const\n{\n return this->m_TypeString;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetUnit(void) const\n{\n return this->m_UnitString;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Start(void)\n{\n this->m_NumberOfStarts++;\n this->m_StartValue = this->GetInstantValue();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Stop(void)\n{\n ValueType probevalue = this->GetInstantValue() - this->m_StartValue;\n if ( this->m_NumberOfStops == this->m_NumberOfStarts )\n {\n return;\n }\n\n this->UpdateMinimumMaximumMeasuredValue(probevalue);\n this->m_TotalValue += probevalue;\n this->m_ProbeValueList.push_back(probevalue);\n this->m_NumberOfStops++;\n this->m_NumberOfIteration = static_cast<CountType>(this->m_ProbeValueList.size());\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfStarts(void) const\n{\n return this->m_NumberOfStarts;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfStops(void) const\n{\n return this->m_NumberOfStops;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfIteration(void) const\n{\n return this->m_NumberOfIteration;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetTotal(void) const\n{\n return this->m_TotalValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nMeanType\nResourceProbe< ValueType, MeanType >\n::GetMean(void) const\n{\n MeanType meanValue = NumericTraits< MeanType >::ZeroValue();\n\n if ( this->m_NumberOfStops )\n {\n meanValue = static_cast< MeanType >( this->m_TotalValue ) \/ static_cast< MeanType >( this->m_NumberOfStops );\n }\n\n return meanValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetMinimum() const\n{\n return this->m_MinimumValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetMaximum() const\n{\n return this->m_MaximumValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetStandardDeviation()\n{\n this->m_MeanValue = this->GetMean();\n std::vector<ValueType> diff(this->m_ProbeValueList.size());\n std::transform(this->m_ProbeValueList.begin(),\n this->m_ProbeValueList.end(),\n diff.begin(),\n std::bind2nd(std::minus<ValueType>(),\n this->m_MeanValue ));\n ValueType sq_sum =\n std::inner_product(diff.begin(),diff.end(),\n diff.begin(),\n 0.0);\n\n int sz = this->m_ProbeValueList.size()-1;\n if (sz <=0)\n {\n this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();\n }\n else\n {\n this->m_StandardDeviation =\n std::sqrt(sq_sum \/\n (static_cast<ValueType>(sz)));\n }\n return this->m_StandardDeviation;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::SetNameOfProbe(const char* nameOfProbe)\n{\n this->m_NameOfProbe = nameOfProbe;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetNameOfProbe() const\n{\n return this->m_NameOfProbe;\n}\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintSystemInformation(std::ostream & os)\n{\n os << \"System: \" << m_SystemName << std::endl;\n os << \"Processor: \" << m_ProcessorName << std::endl;\n os << \" Cache: \" << m_ProcessorCacheSize << std::endl;\n os << \" Clock: \" << m_ProcessorClockFrequency << std::endl;\n os << \" Cores: \" << m_NumberOfPhysicalCPU\n << \" cpus x \" << m_NumberOfLogicalCPU\n << \" Cores = \"<< m_NumberOfAvailableCore << std::endl;\n \/\/ Retrieve memory information in megabyte.\n os << \" Virtual Memory: Total: \"\n << m_TotalVirtualMemory\n <<\" Available: \"<< m_AvailableVirtualMemory << std::endl;\n os << \" Physical Memory: Total:\"\n << m_TotalPhysicalMemory\n <<\" Available: \"<< m_AvailablePhysicalMemory << std::endl;\n\n os << \"OSName: \"<< m_OSName << std::endl;\n os << \" Release: \"<< m_OSRelease << std::endl;\n os << \" Version: \"<< m_OSVersion << std::endl;\n os << \" Platform: \"<< m_OSPlatform << std::endl;\n\n os << \" Operating System is \"\n << (m_Is64Bits?\"64 bit\":\"32 bit\") << std::endl;\n\n os << \"ITK Version: \"\n << m_ITKVersion << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Report(std::ostream & os, bool printSystemInfo, bool printReportHead )\n{\n if(printSystemInfo)\n {\n this->PrintSystemInformation(os);\n }\n\n if(printReportHead)\n {\n this->PrintReportHead(os);\n }\n\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe\n << std::left << std::setw( tabwidth ) << this->m_NumberOfIteration\n << std::left << std::setw( tabwidth ) << this->GetTotal()\n << std::left << std::setw( tabwidth ) << this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetMean()\n << std::left << std::setw( tabwidth ) << this->GetMaximum()\n << std::left << std::setw( tabwidth ) << this->GetStandardDeviation();\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::ExpandedReport(std::ostream & os, bool printSystemInfo, bool printReportHead )\n{\n if(printSystemInfo)\n {\n this->PrintSystemInformation(os);\n }\n\n if(printReportHead)\n {\n this->PrintExpandedReportHead(os);\n }\n\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe\n << std::left << std::setw( tabwidth ) << this->m_NumberOfIteration\n << std::left << std::setw( tabwidth ) << this->GetTotal()\n << std::left << std::setw( tabwidth ) << this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetMean() - this->GetMinimum()\n << std::left << std::setw( tabwidth ) << (this->GetMean()\/this->GetMinimum())*100\n << std::left << std::setw( tabwidth ) << this->GetMean()\n << std::left << std::setw( tabwidth ) << this->GetMaximum() - this->GetMean()\n << std::left << std::setw( tabwidth ) << (this->GetMaximum()\/this->GetMean())*100\n << std::left << std::setw( tabwidth ) << this->GetMaximum()\n << std::left << std::setw( tabwidth ) << this->GetMaximum() - this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetStandardDeviation();\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::UpdateMinimumMaximumMeasuredValue(ValueType value)\n{\n if(this->m_MinimumValue > value)\n {\n this->m_MinimumValue = value;\n }\n\n if(this->m_MaximumValue < value)\n {\n this->m_MaximumValue = value;\n }\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintReportHead(std::ostream & os)\n{\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << std::string(\"Name Of Probe(\")+this->m_TypeString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Iteration\"\n << std::left << std::setw( tabwidth ) << std::string(\"Total(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Min(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Mean(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Max(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Std(\") + this->m_UnitString + std::string(\")\");\n\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintExpandedReportHead(std::ostream & os)\n{\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << std::string(\"Name Of Probe(\") + this->m_TypeString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Iteration\"\n << std::left << std::setw( tabwidth ) << std::string(\"Total(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Min(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Mean-Min(diff)\"\n << std::left << std::setw( tabwidth ) << \"Mean\/Min(%)\"\n << std::left << std::setw( tabwidth ) << std::string(\"Mean(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Max-Mean(diff)\"\n << std::left << std::setw( tabwidth ) << \"Max\/Mean(%)\"\n << std::left << std::setw( tabwidth ) << std::string(\"Max(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Total Diff(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Std(\") + this->m_UnitString + std::string(\")\");\n\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::GetSystemInformation()\n{\n itksys::SystemInformation systeminfo;\n systeminfo.RunCPUCheck();\n systeminfo.RunMemoryCheck();\n systeminfo.RunOSCheck();\n\n m_SystemName = systeminfo.GetHostname();\n m_ProcessorName = systeminfo.GetExtendedProcessorName();\n m_ProcessorCacheSize = systeminfo.GetProcessorCacheSize();\n m_ProcessorClockFrequency = systeminfo.GetProcessorClockFrequency();\n m_NumberOfPhysicalCPU = systeminfo.GetNumberOfPhysicalCPU();\n m_NumberOfLogicalCPU = systeminfo.GetNumberOfLogicalCPU();\n m_NumberOfAvailableCore = m_NumberOfPhysicalCPU*m_NumberOfLogicalCPU;\n\n m_OSName = systeminfo.GetOSName();\n m_OSRelease = systeminfo.GetOSRelease();\n m_OSVersion = systeminfo.GetOSVersion();\n m_OSPlatform = systeminfo.GetOSPlatform();\n\n m_Is64Bits = systeminfo.Is64Bits();\n std::ostringstream itkversion;\n itkversion << ITK_VERSION_MAJOR << \".\" << ITK_VERSION_MINOR << \".\" << ITK_VERSION_PATCH;\n m_ITKVersion = itkversion.str();\n\n \/\/ Retrieve memory information in megabyte.\n m_TotalVirtualMemory = systeminfo.GetTotalVirtualMemory();\n m_AvailableVirtualMemory = systeminfo.GetAvailableVirtualMemory();\n m_TotalPhysicalMemory = systeminfo.GetTotalPhysicalMemory();\n m_AvailablePhysicalMemory = systeminfo.GetAvailablePhysicalMemory();\n}\n\n} \/\/ end namespace itk\n\n#endif\n<commit_msg>COMP: Fixed 'std::sqrt' : ambiguous call to overloaded function<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\/*=========================================================================\n *\n * Portions of this file are subject to the VTK Toolkit Version 3 copyright.\n *\n * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n *\n * For complete copyright, license and disclaimer of warranty information\n * please refer to the NOTICE file at the top of the ITK source tree.\n *\n *=========================================================================*\/\n#ifndef itkResourceProbe_hxx\n#define itkResourceProbe_hxx\n\n#include <numeric>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n#include <functional>\n\n#include \"itkResourceProbe.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkMultiThreader.h\"\n#include \"itksys\/SystemInformation.hxx\"\n\nnamespace itk\n{\n\ntemplate< typename ValueType, typename MeanType >\nResourceProbe< ValueType, MeanType >\n::ResourceProbe(const std::string & type, const std::string & unit):\n m_TypeString(type), m_UnitString(unit)\n{\n this->GetSystemInformation();\n this->Reset();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nResourceProbe< ValueType, MeanType >\n::~ResourceProbe()\n{}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Reset(void)\n{\n this->m_TotalValue = NumericTraits< ValueType >::ZeroValue();\n this->m_StartValue = NumericTraits< ValueType >::ZeroValue();\n this->m_MinimumValue = NumericTraits< ValueType >::max();\n this->m_MaximumValue = NumericTraits< ValueType >::min();\n this->m_MeanValue = NumericTraits< ValueType >::ZeroValue();\n this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();\n\n this->m_NumberOfStarts = NumericTraits< CountType >::ZeroValue();\n this->m_NumberOfStops = NumericTraits< CountType >::ZeroValue();\n this->m_NumberOfIteration = NumericTraits< CountType >::ZeroValue();\n\n this->m_ProbeValueList.clear();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetType(void) const\n{\n return this->m_TypeString;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetUnit(void) const\n{\n return this->m_UnitString;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Start(void)\n{\n this->m_NumberOfStarts++;\n this->m_StartValue = this->GetInstantValue();\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Stop(void)\n{\n ValueType probevalue = this->GetInstantValue() - this->m_StartValue;\n if ( this->m_NumberOfStops == this->m_NumberOfStarts )\n {\n return;\n }\n\n this->UpdateMinimumMaximumMeasuredValue(probevalue);\n this->m_TotalValue += probevalue;\n this->m_ProbeValueList.push_back(probevalue);\n this->m_NumberOfStops++;\n this->m_NumberOfIteration = static_cast<CountType>(this->m_ProbeValueList.size());\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfStarts(void) const\n{\n return this->m_NumberOfStarts;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfStops(void) const\n{\n return this->m_NumberOfStops;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\ntypename ResourceProbe< ValueType, MeanType >::CountType\nResourceProbe< ValueType, MeanType >\n::GetNumberOfIteration(void) const\n{\n return this->m_NumberOfIteration;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetTotal(void) const\n{\n return this->m_TotalValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nMeanType\nResourceProbe< ValueType, MeanType >\n::GetMean(void) const\n{\n MeanType meanValue = NumericTraits< MeanType >::ZeroValue();\n\n if ( this->m_NumberOfStops )\n {\n meanValue = static_cast< MeanType >( this->m_TotalValue ) \/ static_cast< MeanType >( this->m_NumberOfStops );\n }\n\n return meanValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetMinimum() const\n{\n return this->m_MinimumValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetMaximum() const\n{\n return this->m_MaximumValue;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nValueType\nResourceProbe< ValueType, MeanType >\n::GetStandardDeviation()\n{\n this->m_MeanValue = this->GetMean();\n std::vector<ValueType> diff(this->m_ProbeValueList.size());\n std::transform(this->m_ProbeValueList.begin(),\n this->m_ProbeValueList.end(),\n diff.begin(),\n std::bind2nd(std::minus<ValueType>(),\n this->m_MeanValue ));\n ValueType sqsum =\n std::inner_product(diff.begin(),diff.end(),\n diff.begin(),\n 0.0);\n\n int sz = this->m_ProbeValueList.size()-1;\n if (sz <=0)\n {\n this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();\n }\n else\n {\n this->m_StandardDeviation =\n static_cast<ValueType>(std::sqrt(static_cast<double>(sqsum \/(static_cast<ValueType>(sz)))));\n }\n return this->m_StandardDeviation;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::SetNameOfProbe(const char* nameOfProbe)\n{\n this->m_NameOfProbe = nameOfProbe;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nstd::string\nResourceProbe< ValueType, MeanType >\n::GetNameOfProbe() const\n{\n return this->m_NameOfProbe;\n}\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintSystemInformation(std::ostream & os)\n{\n os << \"System: \" << m_SystemName << std::endl;\n os << \"Processor: \" << m_ProcessorName << std::endl;\n os << \" Cache: \" << m_ProcessorCacheSize << std::endl;\n os << \" Clock: \" << m_ProcessorClockFrequency << std::endl;\n os << \" Cores: \" << m_NumberOfPhysicalCPU\n << \" cpus x \" << m_NumberOfLogicalCPU\n << \" Cores = \"<< m_NumberOfAvailableCore << std::endl;\n \/\/ Retrieve memory information in megabyte.\n os << \" Virtual Memory: Total: \"\n << m_TotalVirtualMemory\n <<\" Available: \"<< m_AvailableVirtualMemory << std::endl;\n os << \" Physical Memory: Total:\"\n << m_TotalPhysicalMemory\n <<\" Available: \"<< m_AvailablePhysicalMemory << std::endl;\n\n os << \"OSName: \"<< m_OSName << std::endl;\n os << \" Release: \"<< m_OSRelease << std::endl;\n os << \" Version: \"<< m_OSVersion << std::endl;\n os << \" Platform: \"<< m_OSPlatform << std::endl;\n\n os << \" Operating System is \"\n << (m_Is64Bits?\"64 bit\":\"32 bit\") << std::endl;\n\n os << \"ITK Version: \"\n << m_ITKVersion << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::Report(std::ostream & os, bool printSystemInfo, bool printReportHead )\n{\n if(printSystemInfo)\n {\n this->PrintSystemInformation(os);\n }\n\n if(printReportHead)\n {\n this->PrintReportHead(os);\n }\n\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe\n << std::left << std::setw( tabwidth ) << this->m_NumberOfIteration\n << std::left << std::setw( tabwidth ) << this->GetTotal()\n << std::left << std::setw( tabwidth ) << this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetMean()\n << std::left << std::setw( tabwidth ) << this->GetMaximum()\n << std::left << std::setw( tabwidth ) << this->GetStandardDeviation();\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::ExpandedReport(std::ostream & os, bool printSystemInfo, bool printReportHead )\n{\n if(printSystemInfo)\n {\n this->PrintSystemInformation(os);\n }\n\n if(printReportHead)\n {\n this->PrintExpandedReportHead(os);\n }\n\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe\n << std::left << std::setw( tabwidth ) << this->m_NumberOfIteration\n << std::left << std::setw( tabwidth ) << this->GetTotal()\n << std::left << std::setw( tabwidth ) << this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetMean() - this->GetMinimum()\n << std::left << std::setw( tabwidth ) << (this->GetMean()\/this->GetMinimum())*100\n << std::left << std::setw( tabwidth ) << this->GetMean()\n << std::left << std::setw( tabwidth ) << this->GetMaximum() - this->GetMean()\n << std::left << std::setw( tabwidth ) << (this->GetMaximum()\/this->GetMean())*100\n << std::left << std::setw( tabwidth ) << this->GetMaximum()\n << std::left << std::setw( tabwidth ) << this->GetMaximum() - this->GetMinimum()\n << std::left << std::setw( tabwidth ) << this->GetStandardDeviation();\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::UpdateMinimumMaximumMeasuredValue(ValueType value)\n{\n if(this->m_MinimumValue > value)\n {\n this->m_MinimumValue = value;\n }\n\n if(this->m_MaximumValue < value)\n {\n this->m_MaximumValue = value;\n }\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintReportHead(std::ostream & os)\n{\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << std::string(\"Name Of Probe(\")+this->m_TypeString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Iteration\"\n << std::left << std::setw( tabwidth ) << std::string(\"Total(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Min(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Mean(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Max(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Std(\") + this->m_UnitString + std::string(\")\");\n\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::PrintExpandedReportHead(std::ostream & os)\n{\n std::stringstream ss;\n ss << std::left << std::setw( tabwidth *2 ) << std::string(\"Name Of Probe(\") + this->m_TypeString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Iteration\"\n << std::left << std::setw( tabwidth ) << std::string(\"Total(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Min(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Mean-Min(diff)\"\n << std::left << std::setw( tabwidth ) << \"Mean\/Min(%)\"\n << std::left << std::setw( tabwidth ) << std::string(\"Mean(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << \"Max-Mean(diff)\"\n << std::left << std::setw( tabwidth ) << \"Max\/Mean(%)\"\n << std::left << std::setw( tabwidth ) << std::string(\"Max(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Total Diff(\") + this->m_UnitString + std::string(\")\")\n << std::left << std::setw( tabwidth ) << std::string(\"Std(\") + this->m_UnitString + std::string(\")\");\n\n os << ss.str() << std::endl;\n}\n\n\ntemplate< typename ValueType, typename MeanType >\nvoid\nResourceProbe< ValueType, MeanType >\n::GetSystemInformation()\n{\n itksys::SystemInformation systeminfo;\n systeminfo.RunCPUCheck();\n systeminfo.RunMemoryCheck();\n systeminfo.RunOSCheck();\n\n m_SystemName = systeminfo.GetHostname();\n m_ProcessorName = systeminfo.GetExtendedProcessorName();\n m_ProcessorCacheSize = systeminfo.GetProcessorCacheSize();\n m_ProcessorClockFrequency = systeminfo.GetProcessorClockFrequency();\n m_NumberOfPhysicalCPU = systeminfo.GetNumberOfPhysicalCPU();\n m_NumberOfLogicalCPU = systeminfo.GetNumberOfLogicalCPU();\n m_NumberOfAvailableCore = m_NumberOfPhysicalCPU*m_NumberOfLogicalCPU;\n\n m_OSName = systeminfo.GetOSName();\n m_OSRelease = systeminfo.GetOSRelease();\n m_OSVersion = systeminfo.GetOSVersion();\n m_OSPlatform = systeminfo.GetOSPlatform();\n\n m_Is64Bits = systeminfo.Is64Bits();\n std::ostringstream itkversion;\n itkversion << ITK_VERSION_MAJOR << \".\" << ITK_VERSION_MINOR << \".\" << ITK_VERSION_PATCH;\n m_ITKVersion = itkversion.str();\n\n \/\/ Retrieve memory information in megabyte.\n m_TotalVirtualMemory = systeminfo.GetTotalVirtualMemory();\n m_AvailableVirtualMemory = systeminfo.GetAvailableVirtualMemory();\n m_TotalPhysicalMemory = systeminfo.GetTotalPhysicalMemory();\n m_AvailablePhysicalMemory = systeminfo.GetAvailablePhysicalMemory();\n}\n\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"audio\/player.h\"\n\nnamespace loftili {\n\nnamespace audio {\n\nvoid Player::Stop() {\n m_state = PLAYER_STATE_STOPPED;\n}\n\nbool Player::Play(std::string url) {\n Startup();\n loftili::net::HttpClient client;\n loftili::net::HttpRequest req(loftili::net::Url(url.c_str()));\n\n mpg123_handle* m_handle;\n m_handle = mpg123_new(NULL, NULL);\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"attempting to download track...\");\n if(client.Send(req)) {\n std::shared_ptr<loftili::net::HttpResponse> res = client.Latest();\n if(res->Status() != 200) {\n spdlog::get(LOFTILI_SPDLOG_ID)->critical(\"download {0} failed\", url.c_str());\n return false;\n }\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"download complete, temporarily saving to file system\");\n remove(\"current.mp3\");\n std::ofstream download;\n download.open(\"current.mp3\", std::ios::binary | std::ios::out);\n download.write(res->Body(), res->ContentLength());\n download.close();\n int err = mpg123_open(m_handle, \"current.mp3\");\n\n if(err != MPG123_OK) {\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n return false;\n }\n\n off_t frame_offset;\n unsigned char* audio;\n size_t done;\n int channels, encoding;\n long rate;\n\n err = mpg123_getformat(m_handle, &rate, &channels, &encoding);\n if(err != MPG123_OK) {\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n }\n\n ao_sample_format format;\n format.bits = mpg123_encsize(encoding) * 8;\n format.rate = rate;\n format.channels = channels;\n format.byte_format = AO_FMT_NATIVE;\n format.matrix = 0;\n\n ao_device* dev = ao_open_live(ao_default_driver_id(), &format, NULL);\n m_state = PLAYER_STATE_PLAYING;\n\n do {\n err = mpg123_decode_frame(m_handle, &frame_offset, &audio, &done);\n switch(err) {\n case MPG123_OK:\n ao_play(dev, (char*)audio, done);\n break;\n default:\n break;\n }\n } while(done > 0 && m_state == PLAYER_STATE_PLAYING);\n\n ao_close(dev);\n }\n\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n return true;\n}\n\nPlayer::operator bool() {\n return m_state == PLAYER_STATE_PLAYING;\n}\n\nvoid Player::Startup() {\n ao_initialize();\n mpg123_init();\n}\n\nvoid Player::Shutdown() {\n ao_shutdown();\n mpg123_exit();\n}\n\n}\n\n}\n<commit_msg>[LFTCE-31] detecting libao inability to open audio device and exiting out of playback<commit_after>#include \"audio\/player.h\"\n\nnamespace loftili {\n\nnamespace audio {\n\nvoid Player::Stop() {\n m_state = PLAYER_STATE_STOPPED;\n}\n\nbool Player::Play(std::string url) {\n Startup();\n loftili::net::HttpClient client;\n loftili::net::HttpRequest req(loftili::net::Url(url.c_str()));\n\n mpg123_handle* m_handle;\n m_handle = mpg123_new(NULL, NULL);\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"attempting to download track...\");\n if(client.Send(req)) {\n std::shared_ptr<loftili::net::HttpResponse> res = client.Latest();\n if(res->Status() != 200) {\n spdlog::get(LOFTILI_SPDLOG_ID)->critical(\"download {0} failed\", url.c_str());\n return false;\n }\n\n spdlog::get(LOFTILI_SPDLOG_ID)->info(\"download complete, temporarily saving to file system\");\n remove(\"current.mp3\");\n std::ofstream download;\n download.open(\"current.mp3\", std::ios::binary | std::ios::out);\n download.write(res->Body(), res->ContentLength());\n download.close();\n int err = mpg123_open(m_handle, \"current.mp3\");\n\n if(err != MPG123_OK) {\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n return false;\n }\n\n off_t frame_offset;\n unsigned char* audio;\n size_t done;\n int channels, encoding;\n long rate;\n\n err = mpg123_getformat(m_handle, &rate, &channels, &encoding);\n if(err != MPG123_OK) {\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n }\n\n ao_sample_format format;\n format.bits = mpg123_encsize(encoding) * 8;\n format.rate = rate;\n format.channels = channels;\n format.byte_format = AO_FMT_NATIVE;\n format.matrix = 0;\n\n ao_device* dev = ao_open_live(ao_default_driver_id(), &format, NULL);\n if(dev == NULL) {\n spdlog::get(LOFTILI_SPDLOG_ID)->critical(\"failed opening libao device, unable to play audio\");\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n return false;\n }\n\n m_state = PLAYER_STATE_PLAYING;\n\n do {\n err = mpg123_decode_frame(m_handle, &frame_offset, &audio, &done);\n switch(err) {\n case MPG123_OK:\n ao_play(dev, (char*)audio, done);\n break;\n default:\n break;\n }\n } while(done > 0 && m_state == PLAYER_STATE_PLAYING);\n\n ao_close(dev);\n }\n\n mpg123_close(m_handle);\n mpg123_delete(m_handle);\n Shutdown();\n return true;\n}\n\nPlayer::operator bool() {\n return m_state == PLAYER_STATE_PLAYING;\n}\n\nvoid Player::Startup() {\n ao_initialize();\n mpg123_init();\n}\n\nvoid Player::Shutdown() {\n ao_shutdown();\n mpg123_exit();\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DanpheApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n#include \"ModulesApp.h\"\n\n\/\/Kernels\n#include \"ElectricPotential.h\"\n\/\/Auxkernels\n#include \"CurrentDensity.h\"\n\/\/Materials\n#include \"TinSheet.h\"\n\ntemplate<>\nInputParameters validParams<DanpheApp>()\n{\n InputParameters params = validParams<MooseApp>();\n return params;\n}\n\nDanpheApp::DanpheApp(const std::string & name, InputParameters parameters) :\n MooseApp(name, parameters)\n{\n srand(processor_id());\n\n Moose::registerObjects(_factory);\n ModulesApp::registerObjects(_factory);\n DanpheApp::registerObjects(_factory);\n\n Moose::associateSyntax(_syntax, _action_factory);\n ModulesApp::associateSyntax(_syntax, _action_factory);\n DanpheApp::associateSyntax(_syntax, _action_factory);\n}\n\nDanpheApp::~DanpheApp()\n{\n}\n\nvoid\nDanpheApp::registerApps()\n{\n registerApp(DanpheApp);\n}\n\nvoid\nDanpheApp::registerObjects(Factory & factory)\n{\n registerKernel(ElectricPotential);\n registerAux(CurrentDensity);\n registerMaterial(TinSheet);\n}\n\nvoid\nDanpheApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)\n{\n}\n<commit_msg>Update DanpheApp.C<commit_after>#include \"DanpheApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n#include \"ModulesApp.h\"\n\n\/\/Kernels\n#include \"ElectricPotential.h\"\n#include \"CoupledPotential.h\"\n\/\/Auxkernels\n#include \"CurrentDensity.h\"\n\/\/Materials\n#include \"TinSheet.h\"\n\ntemplate<>\nInputParameters validParams<DanpheApp>()\n{\n InputParameters params = validParams<MooseApp>();\n return params;\n}\n\nDanpheApp::DanpheApp(const std::string & name, InputParameters parameters) :\n MooseApp(name, parameters)\n{\n srand(processor_id());\n\n Moose::registerObjects(_factory);\n ModulesApp::registerObjects(_factory);\n DanpheApp::registerObjects(_factory);\n\n Moose::associateSyntax(_syntax, _action_factory);\n ModulesApp::associateSyntax(_syntax, _action_factory);\n DanpheApp::associateSyntax(_syntax, _action_factory);\n}\n\nDanpheApp::~DanpheApp()\n{\n}\n\nvoid\nDanpheApp::registerApps()\n{\n registerApp(DanpheApp);\n}\n\nvoid\nDanpheApp::registerObjects(Factory & factory)\n{\n registerKernel(ElectricPotential);\n registerKernel(CoupledPotential);\n registerAux(CurrentDensity);\n registerMaterial(TinSheet);\n}\n\nvoid\nDanpheApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file ct2ctml.cpp\n * Driver for the system call to the python executable that converts\n * cti files to ctml files (see \\ref inputfiles).\n *\/\n\/\/ Copyright 2001-2005 California Institute of Technology\n\n#include \"cantera\/base\/ctml.h\"\n#include \"cantera\/base\/stringUtils.h\"\n#include \"..\/..\/ext\/libexecstream\/exec-stream.h\"\n\n#include <fstream>\n#include <sstream>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\nusing namespace Cantera;\nusing namespace std;\n\nnamespace ctml\n{\n\n\/\/! return the full path to the Python interpreter.\n\/*!\n * Use the environment variable PYTHON_CMD if it is set. If not, return\n * the string 'python'.\n *\n * Note, there are hidden problems here that really direct us to use\n * a full pathname for the location of python. Basically the system\n * call will use the shell \/bin\/sh, in order to launch python.\n * This default shell may not be the shell that the user is employing.\n * Therefore, the default path to python may be different during\n * a system call than during the default user shell environment.\n * This is quite a headache. The answer is to always set the\n * PYTHON_CMD environmental variable in the user environment to\n * an absolute path to locate the python executable. Then this\n * issue goes away.\n *\/\nstatic string pypath()\n{\n string s = \"python\";\n const char* py = getenv(\"PYTHON_CMD\");\n\n if (py) {\n string sp = stripws(string(py));\n if (sp.size() > 0) {\n s = sp;\n }\n }\n return s;\n}\n\nvoid ct2ctml(const char* file, const int debug)\n{\n string xml = ct2ctml_string(file);\n string out_name = file;\n#ifdef _WIN32\n \/\/ For Windows, make the path POSIX compliant so code looking for directory\n \/\/ separators is simpler. Just look for '\/' not both '\/' and '\\\\'\n std::replace_if(out_name.begin(), out_name.end(),\n std::bind2nd(std::equal_to<char>(), '\\\\'), '\/') ;\n#endif\n size_t idir = out_name.rfind('\/');\n if (idir != npos) {\n out_name = out_name.substr(idir+1, out_name.size());\n }\n size_t idot = out_name.rfind('.');\n if (idot != npos) {\n out_name = out_name.substr(0, idot) + \".xml\";\n } else {\n out_name += \".xml\";\n }\n std::ofstream out(out_name.c_str());\n out << xml;\n}\n\nstatic std::string call_ctml_writer(const std::string& text, bool isfile)\n{\n std::string file, arg;\n if (isfile) {\n file = text;\n arg = \"r'\" + text + \"'\";\n } else {\n file = \"<string>\";\n arg = \"text=r'''\" + text + \"'''\";\n }\n\n#ifdef HAS_NO_PYTHON\n \/*\n * Section to bomb out if python is not\n * present in the computation environment.\n *\/\n throw CanteraError(\"ct2ctml\",\n \"python cti to ctml conversion requested for file, \" + file +\n \", but not available in this computational environment\");\n#endif\n\n string python_output, error_output;\n int python_exit_code;\n try {\n exec_stream_t python;\n python.set_wait_timeout(exec_stream_t::s_all, 1800000); \/\/ 30 minutes\n stringstream output_stream, error_stream;\n std::vector<string> args;\n args.push_back(\"-c\");\n\n args.push_back(\n \"from __future__ import print_function\\n\"\n \"import sys\\n\"\n \"try:\\n\"\n \" from cantera import ctml_writer\\n\"\n \"except ImportError:\\n\"\n \" print('sys.path: ' + repr(sys.path) + '\\\\n', file=sys.stderr)\\n\"\n \" raise\\n\"\n \"ctml_writer.convert(\" + arg + \", outName='STDOUT')\\n\"\n \"sys.exit(0)\\n\");\n\n python.start(pypath(), args.begin(), args.end());\n std::string line;\n\n while (python.out().good()) {\n std::getline(python.out(), line);\n output_stream << line << std::endl;\n }\n\n#ifdef _WIN32\n \/\/ Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while\n \/\/ reading from the stream.\n Sleep(1);\n#endif\n while (python.err().good()) {\n std::getline(python.err(), line);\n error_stream << line << std::endl;\n }\n python.close();\n python_exit_code = python.exit_code();\n error_output = stripws(error_stream.str());\n python_output = output_stream.str();\n } catch (std::exception& err) {\n \/\/ Report failure to execute Python\n stringstream message;\n message << \"Error executing python while converting input file:\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << err.what() << std::endl;\n throw CanteraError(\"ct2ctml_string\", message.str());\n }\n\n if (python_exit_code != 0) {\n \/\/ Report a failure in the conversion process\n stringstream message;\n message << \"Error converting input file \\\"\" << file << \"\\\" to CTML.\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << \"The exit code was: \" << python_exit_code << \"\\n\";\n if (error_output.size() > 0) {\n message << \"-------------- start of converter log --------------\\n\";\n message << error_output << std::endl;\n message << \"--------------- end of converter log ---------------\";\n } else {\n message << \"The command did not produce any output.\" << endl;\n }\n throw CanteraError(\"ct2ctml_string\", message.str());\n }\n\n if (error_output.size() > 0) {\n \/\/ Warn if there was any output from the conversion process\n stringstream message;\n message << \"Warning: Unexpected output from CTI converter\\n\";\n message << \"-------------- start of converter log --------------\\n\";\n message << error_output << std::endl;\n message << \"--------------- end of converter log ---------------\\n\";\n writelog(message.str());\n }\n return python_output;\n}\n\nstd::string ct2ctml_string(const std::string& file)\n{\n return call_ctml_writer(file, true);\n}\n\nstd::string ct_string2ctml_string(const std::string& cti)\n{\n return call_ctml_writer(cti, false);\n}\n\nvoid ck2cti(const std::string& in_file, const std::string& thermo_file,\n const std::string& transport_file, const std::string& id_tag)\n{\n#ifdef HAS_NO_PYTHON\n \/*\n * Section to bomb out if python is not\n * present in the computation environment.\n *\/\n string ppath = in_file;\n throw CanteraError(\"ct2ctml\",\n \"python ck to cti conversion requested for file, \" + ppath +\n \", but not available in this computational environment\");\n#endif\n\n string python_output;\n int python_exit_code;\n try {\n exec_stream_t python;\n python.set_wait_timeout(exec_stream_t::s_all, 1800000); \/\/ 30 minutes\n python.start(pypath(), \"-i\");\n stringstream output_stream;\n\n ostream& pyin = python.in();\n pyin << \"if True:\\n\" << \/\/ Use this so that the rest is a single block\n \" import sys\\n\" <<\n \" sys.stderr = sys.stdout\\n\" <<\n \" try:\\n\" <<\n \" from cantera import ck2cti\\n\" <<\n \" except ImportError:\\n\" <<\n \" print('sys.path: ' + repr(sys.path))\\n\" <<\n \" raise\\n\"\n \" ck2cti.Parser().convertMech(r'\" << in_file << \"',\";\n if (thermo_file != \"\" && thermo_file != \"-\") {\n pyin << \" thermoFile=r'\" << thermo_file << \"',\";\n }\n if (transport_file != \"\" && transport_file != \"-\") {\n pyin << \" transportFile=r'\" << transport_file << \"',\";\n }\n pyin << \" phaseName='\" << id_tag << \"',\";\n pyin << \" permissive=True,\";\n pyin << \" quiet=True)\\n\";\n pyin << \" sys.exit(0)\\n\\n\";\n pyin << \"sys.exit(7)\\n\";\n python.close_in();\n\n std::string line;\n while (python.out().good()) {\n std::getline(python.out(), line);\n output_stream << line << std::endl;;\n }\n python.close();\n python_exit_code = python.exit_code();\n python_output = stripws(output_stream.str());\n } catch (std::exception& err) {\n \/\/ Report failure to execute Python\n stringstream message;\n message << \"Error executing python while converting input file:\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << err.what() << std::endl;\n throw CanteraError(\"ct2ctml\", message.str());\n }\n\n if (python_exit_code != 0) {\n \/\/ Report a failure in the conversion process\n stringstream message;\n message << \"Error converting input file \\\"\" << in_file << \"\\\" to CTI.\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << \"The exit code was: \" << python_exit_code << \"\\n\";\n if (python_output.size() > 0) {\n message << \"-------------- start of converter log --------------\\n\";\n message << python_output << std::endl;\n message << \"--------------- end of converter log ---------------\";\n } else {\n message << \"The command did not produce any output.\" << endl;\n }\n throw CanteraError(\"ck2cti\", message.str());\n }\n\n if (python_output.size() > 0) {\n \/\/ Warn if there was any output from the conversion process\n stringstream message;\n message << \"Warning: Unexpected output from CTI converter\\n\";\n message << \"-------------- start of converter log --------------\\n\";\n message << python_output << std::endl;\n message << \"--------------- end of converter log ---------------\\n\";\n writelog(message.str());\n }\n}\n\nvoid get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)\n{\n warn_deprecated(\"get_CTML_Tree\", \"To be removed after Cantera 2.2. \"\n \"Use get_XML_File instead.\");\n XML_Node* src = get_XML_File(file);\n src->copy(rootPtr);\n}\n\nCantera::XML_Node getCtmlTree(const std::string& file)\n{\n warn_deprecated(\"getCtmlTree\", \"To be removed after Cantera 2.2. \"\n \"Use get_XML_File instead.\");\n XML_Node root;\n XML_Node* src = get_XML_File(file);\n src->copy(&root);\n return root;\n}\n\n}\n<commit_msg>Fix compilation with Visual Studio 2013<commit_after>\/**\n * @file ct2ctml.cpp\n * Driver for the system call to the python executable that converts\n * cti files to ctml files (see \\ref inputfiles).\n *\/\n\/\/ Copyright 2001-2005 California Institute of Technology\n\n#include \"cantera\/base\/ctml.h\"\n#include \"cantera\/base\/stringUtils.h\"\n#include \"..\/..\/ext\/libexecstream\/exec-stream.h\"\n\n#include <fstream>\n#include <sstream>\n#include <functional>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\nusing namespace Cantera;\nusing namespace std;\n\nnamespace ctml\n{\n\n\/\/! return the full path to the Python interpreter.\n\/*!\n * Use the environment variable PYTHON_CMD if it is set. If not, return\n * the string 'python'.\n *\n * Note, there are hidden problems here that really direct us to use\n * a full pathname for the location of python. Basically the system\n * call will use the shell \/bin\/sh, in order to launch python.\n * This default shell may not be the shell that the user is employing.\n * Therefore, the default path to python may be different during\n * a system call than during the default user shell environment.\n * This is quite a headache. The answer is to always set the\n * PYTHON_CMD environmental variable in the user environment to\n * an absolute path to locate the python executable. Then this\n * issue goes away.\n *\/\nstatic string pypath()\n{\n string s = \"python\";\n const char* py = getenv(\"PYTHON_CMD\");\n\n if (py) {\n string sp = stripws(string(py));\n if (sp.size() > 0) {\n s = sp;\n }\n }\n return s;\n}\n\nvoid ct2ctml(const char* file, const int debug)\n{\n string xml = ct2ctml_string(file);\n string out_name = file;\n#ifdef _WIN32\n \/\/ For Windows, make the path POSIX compliant so code looking for directory\n \/\/ separators is simpler. Just look for '\/' not both '\/' and '\\\\'\n std::replace_if(out_name.begin(), out_name.end(),\n std::bind2nd(std::equal_to<char>(), '\\\\'), '\/') ;\n#endif\n size_t idir = out_name.rfind('\/');\n if (idir != npos) {\n out_name = out_name.substr(idir+1, out_name.size());\n }\n size_t idot = out_name.rfind('.');\n if (idot != npos) {\n out_name = out_name.substr(0, idot) + \".xml\";\n } else {\n out_name += \".xml\";\n }\n std::ofstream out(out_name.c_str());\n out << xml;\n}\n\nstatic std::string call_ctml_writer(const std::string& text, bool isfile)\n{\n std::string file, arg;\n if (isfile) {\n file = text;\n arg = \"r'\" + text + \"'\";\n } else {\n file = \"<string>\";\n arg = \"text=r'''\" + text + \"'''\";\n }\n\n#ifdef HAS_NO_PYTHON\n \/*\n * Section to bomb out if python is not\n * present in the computation environment.\n *\/\n throw CanteraError(\"ct2ctml\",\n \"python cti to ctml conversion requested for file, \" + file +\n \", but not available in this computational environment\");\n#endif\n\n string python_output, error_output;\n int python_exit_code;\n try {\n exec_stream_t python;\n python.set_wait_timeout(exec_stream_t::s_all, 1800000); \/\/ 30 minutes\n stringstream output_stream, error_stream;\n std::vector<string> args;\n args.push_back(\"-c\");\n\n args.push_back(\n \"from __future__ import print_function\\n\"\n \"import sys\\n\"\n \"try:\\n\"\n \" from cantera import ctml_writer\\n\"\n \"except ImportError:\\n\"\n \" print('sys.path: ' + repr(sys.path) + '\\\\n', file=sys.stderr)\\n\"\n \" raise\\n\"\n \"ctml_writer.convert(\" + arg + \", outName='STDOUT')\\n\"\n \"sys.exit(0)\\n\");\n\n python.start(pypath(), args.begin(), args.end());\n std::string line;\n\n while (python.out().good()) {\n std::getline(python.out(), line);\n output_stream << line << std::endl;\n }\n\n#ifdef _WIN32\n \/\/ Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while\n \/\/ reading from the stream.\n Sleep(1);\n#endif\n while (python.err().good()) {\n std::getline(python.err(), line);\n error_stream << line << std::endl;\n }\n python.close();\n python_exit_code = python.exit_code();\n error_output = stripws(error_stream.str());\n python_output = output_stream.str();\n } catch (std::exception& err) {\n \/\/ Report failure to execute Python\n stringstream message;\n message << \"Error executing python while converting input file:\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << err.what() << std::endl;\n throw CanteraError(\"ct2ctml_string\", message.str());\n }\n\n if (python_exit_code != 0) {\n \/\/ Report a failure in the conversion process\n stringstream message;\n message << \"Error converting input file \\\"\" << file << \"\\\" to CTML.\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << \"The exit code was: \" << python_exit_code << \"\\n\";\n if (error_output.size() > 0) {\n message << \"-------------- start of converter log --------------\\n\";\n message << error_output << std::endl;\n message << \"--------------- end of converter log ---------------\";\n } else {\n message << \"The command did not produce any output.\" << endl;\n }\n throw CanteraError(\"ct2ctml_string\", message.str());\n }\n\n if (error_output.size() > 0) {\n \/\/ Warn if there was any output from the conversion process\n stringstream message;\n message << \"Warning: Unexpected output from CTI converter\\n\";\n message << \"-------------- start of converter log --------------\\n\";\n message << error_output << std::endl;\n message << \"--------------- end of converter log ---------------\\n\";\n writelog(message.str());\n }\n return python_output;\n}\n\nstd::string ct2ctml_string(const std::string& file)\n{\n return call_ctml_writer(file, true);\n}\n\nstd::string ct_string2ctml_string(const std::string& cti)\n{\n return call_ctml_writer(cti, false);\n}\n\nvoid ck2cti(const std::string& in_file, const std::string& thermo_file,\n const std::string& transport_file, const std::string& id_tag)\n{\n#ifdef HAS_NO_PYTHON\n \/*\n * Section to bomb out if python is not\n * present in the computation environment.\n *\/\n string ppath = in_file;\n throw CanteraError(\"ct2ctml\",\n \"python ck to cti conversion requested for file, \" + ppath +\n \", but not available in this computational environment\");\n#endif\n\n string python_output;\n int python_exit_code;\n try {\n exec_stream_t python;\n python.set_wait_timeout(exec_stream_t::s_all, 1800000); \/\/ 30 minutes\n python.start(pypath(), \"-i\");\n stringstream output_stream;\n\n ostream& pyin = python.in();\n pyin << \"if True:\\n\" << \/\/ Use this so that the rest is a single block\n \" import sys\\n\" <<\n \" sys.stderr = sys.stdout\\n\" <<\n \" try:\\n\" <<\n \" from cantera import ck2cti\\n\" <<\n \" except ImportError:\\n\" <<\n \" print('sys.path: ' + repr(sys.path))\\n\" <<\n \" raise\\n\"\n \" ck2cti.Parser().convertMech(r'\" << in_file << \"',\";\n if (thermo_file != \"\" && thermo_file != \"-\") {\n pyin << \" thermoFile=r'\" << thermo_file << \"',\";\n }\n if (transport_file != \"\" && transport_file != \"-\") {\n pyin << \" transportFile=r'\" << transport_file << \"',\";\n }\n pyin << \" phaseName='\" << id_tag << \"',\";\n pyin << \" permissive=True,\";\n pyin << \" quiet=True)\\n\";\n pyin << \" sys.exit(0)\\n\\n\";\n pyin << \"sys.exit(7)\\n\";\n python.close_in();\n\n std::string line;\n while (python.out().good()) {\n std::getline(python.out(), line);\n output_stream << line << std::endl;;\n }\n python.close();\n python_exit_code = python.exit_code();\n python_output = stripws(output_stream.str());\n } catch (std::exception& err) {\n \/\/ Report failure to execute Python\n stringstream message;\n message << \"Error executing python while converting input file:\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << err.what() << std::endl;\n throw CanteraError(\"ct2ctml\", message.str());\n }\n\n if (python_exit_code != 0) {\n \/\/ Report a failure in the conversion process\n stringstream message;\n message << \"Error converting input file \\\"\" << in_file << \"\\\" to CTI.\\n\";\n message << \"Python command was: '\" << pypath() << \"'\\n\";\n message << \"The exit code was: \" << python_exit_code << \"\\n\";\n if (python_output.size() > 0) {\n message << \"-------------- start of converter log --------------\\n\";\n message << python_output << std::endl;\n message << \"--------------- end of converter log ---------------\";\n } else {\n message << \"The command did not produce any output.\" << endl;\n }\n throw CanteraError(\"ck2cti\", message.str());\n }\n\n if (python_output.size() > 0) {\n \/\/ Warn if there was any output from the conversion process\n stringstream message;\n message << \"Warning: Unexpected output from CTI converter\\n\";\n message << \"-------------- start of converter log --------------\\n\";\n message << python_output << std::endl;\n message << \"--------------- end of converter log ---------------\\n\";\n writelog(message.str());\n }\n}\n\nvoid get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)\n{\n warn_deprecated(\"get_CTML_Tree\", \"To be removed after Cantera 2.2. \"\n \"Use get_XML_File instead.\");\n XML_Node* src = get_XML_File(file);\n src->copy(rootPtr);\n}\n\nCantera::XML_Node getCtmlTree(const std::string& file)\n{\n warn_deprecated(\"getCtmlTree\", \"To be removed after Cantera 2.2. \"\n \"Use get_XML_File instead.\");\n XML_Node root;\n XML_Node* src = get_XML_File(file);\n src->copy(&root);\n return root;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ MCMailProvider.cpp\n\/\/ mailcore2\n\/\/\n\/\/ Created by Robert Widmann on 4\/28\/13.\n\/\/ Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCMailProvider.h\"\n#include \"MCNetService.h\"\n#include \"MCIterator.h\"\n#include \"MCJSON.h\"\n\n#ifdef _MSC_VER\n#include <unicode\/uregex.h>\n#include <unicode\/utext.h>\n#include <unicode\/utypes.h>\n#include <unicode\/localpointer.h>\n#include <unicode\/parseerr.h>\n#else\n#include <regex.h>\n#endif\n\nusing namespace mailcore;\n\nvoid MailProvider::init()\n{\n mIdentifier = NULL;\n mImapServices = new Array();\n mSmtpServices = new Array();\n mPopServices = new Array();\n mDomainMatch = new Array();\n mDomainExclude = new Array();\n mMxMatch = new Array();\n mMailboxPaths = NULL;\n}\n\nMailProvider::MailProvider()\n{\n init();\n}\n\nMailProvider::MailProvider(MailProvider * other)\n{\n init();\n MC_SAFE_REPLACE_COPY(String, mIdentifier, other->mIdentifier);\n MC_SAFE_REPLACE_COPY(Array, mImapServices, other->mImapServices);\n MC_SAFE_REPLACE_COPY(Array, mSmtpServices, other->mSmtpServices);\n MC_SAFE_REPLACE_COPY(Array, mPopServices, other->mPopServices);\n MC_SAFE_REPLACE_COPY(Array, mDomainMatch, other->mDomainMatch);\n MC_SAFE_REPLACE_COPY(Array, mDomainExclude, other->mDomainExclude);\n MC_SAFE_REPLACE_COPY(Array, mMxMatch, other->mMxMatch);\n MC_SAFE_REPLACE_COPY(HashMap, mMailboxPaths, other->mMailboxPaths);\n}\n\nMailProvider::~MailProvider()\n{\n MC_SAFE_RELEASE(mImapServices);\n MC_SAFE_RELEASE(mSmtpServices);\n MC_SAFE_RELEASE(mPopServices);\n MC_SAFE_RELEASE(mMxMatch);\n MC_SAFE_RELEASE(mDomainMatch);\n MC_SAFE_RELEASE(mDomainExclude);\n MC_SAFE_RELEASE(mMailboxPaths);\n MC_SAFE_RELEASE(mIdentifier);\n}\n\nMailProvider * MailProvider::providerWithInfo(HashMap * info)\n{\n MailProvider * provider = new MailProvider();\n provider->fillWithInfo(info);\n provider->autorelease();\n return provider;\n}\n\nvoid MailProvider::fillWithInfo(HashMap * info)\n{\n Array * imapInfos;\n Array * smtpInfos;\n Array * popInfos;\n HashMap * serverInfo;\n \n MC_SAFE_RELEASE(mDomainMatch);\n if (info->objectForKey(MCSTR(\"domain-match\")) != NULL) {\n mDomainMatch = (Array *) info->objectForKey(MCSTR(\"domain-match\"))->retain();\n }\n MC_SAFE_RELEASE(mDomainExclude);\n if (info->objectForKey(MCSTR(\"domain-exclude\")) != NULL) {\n mDomainExclude = (Array *) info->objectForKey(MCSTR(\"domain-exclude\"))->retain();\n }\n MC_SAFE_RELEASE(mMailboxPaths);\n if (info->objectForKey(MCSTR(\"mailboxes\")) != NULL) {\n mMailboxPaths = (HashMap *) info->objectForKey(MCSTR(\"mailboxes\"))->retain();\n }\n MC_SAFE_RELEASE(mMxMatch);\n if (info->objectForKey(MCSTR(\"mx-match\")) != NULL) {\n mMxMatch = (Array *) info->objectForKey(MCSTR(\"mx-match\"))->retain();\n }\n \n serverInfo = (HashMap *) info->objectForKey(MCSTR(\"servers\"));\n if (serverInfo == NULL) {\n MCLog(\"servers key missing from provider %s\", MCUTF8DESC(info));\n }\n MCAssert(serverInfo != NULL);\n imapInfos = (Array *) serverInfo->objectForKey(MCSTR(\"imap\"));\n smtpInfos = (Array *) serverInfo->objectForKey(MCSTR(\"smtp\"));\n popInfos = (Array *) serverInfo->objectForKey(MCSTR(\"pop\"));\n \n mImapServices->removeAllObjects();\n mc_foreacharray(HashMap, imapInfo, imapInfos) {\n NetService * service = NetService::serviceWithInfo(imapInfo);\n mImapServices->addObject(service);\n }\n \n mSmtpServices->removeAllObjects();\n mc_foreacharray(HashMap, smtpInfo, smtpInfos) {\n NetService * service = NetService::serviceWithInfo(smtpInfo);\n mSmtpServices->addObject(service);\n }\n \n mPopServices->removeAllObjects();\n mc_foreacharray(HashMap, popInfo, popInfos) {\n NetService * service = NetService::serviceWithInfo(popInfo);\n mPopServices->addObject(service);\n }\n}\n\nvoid MailProvider::setIdentifier(String * identifier)\n{\n MC_SAFE_REPLACE_COPY(String, mIdentifier, identifier);\n}\n\nString * MailProvider::identifier()\n{\n return mIdentifier;\n}\n\nArray * MailProvider::imapServices()\n{\n return mImapServices;\n}\n\nArray * MailProvider::smtpServices()\n{\n return mSmtpServices;\n}\n\nArray * MailProvider::popServices()\n{\n return mPopServices;\n}\n\nbool MailProvider::matchEmail(String * email)\n{\n Array * components;\n String * domain;\n \n components = email->componentsSeparatedByString(MCSTR(\"@\"));\n if (components->count() < 2)\n return false;\n \n domain = (String *) components->lastObject();\n\n bool matchExcludeDomain = false;\n mc_foreacharray(String, exclude, mDomainExclude) {\n if (matchDomain(exclude, domain)){\n matchExcludeDomain = true;;\n break;\n }\n }\n if (matchExcludeDomain) {\n return false;\n }\n\n bool matchValidDomain = false;\n mc_foreacharray(String, match, mDomainMatch) {\n if (matchDomain(match, domain)){\n matchValidDomain = true;\n break;\n }\n }\n if (matchValidDomain) {\n return true;\n }\n\n return false;\n}\n\nbool MailProvider::matchMX(String * hostname)\n{\n bool result = false;\n mc_foreacharray(String, match, mMxMatch) {\n if (matchDomain(match, hostname)){\n result = true;\n break;\n }\n }\n\n return result;\n}\n\nbool MailProvider::matchDomain(String * match, String * domain)\n{\n#ifdef _MSC_VER\n UParseError error;\n UErrorCode code = U_ZERO_ERROR;\n URegularExpression * r = uregex_open(match->unicodeCharacters(), match->length(), UREGEX_CASE_INSENSITIVE, &error, &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n uregex_setText(r, domain->unicodeCharacters(), domain->length(), &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n\n\tbool matched = uregex_matches(r, 0, &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n\n uregex_close(r);\n\n return matched;\n#else\n const char * cDomain;\n regex_t r;\n bool matched; \n\n cDomain = domain->UTF8Characters();\n match = String::stringWithUTF8Format(\"^%s$\", match->UTF8Characters());\n matched = false;\n\n if (regcomp(&r, match->UTF8Characters(), REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0){\n return matched;\n }\n\n if (regexec(&r, cDomain, 0, NULL, 0) == 0) {\n matched = true;\n }\n\n regfree(&r);\n\n return matched;\n#endif\n}\n\nString * MailProvider::sentMailFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"sentmail\"));\n}\n\nString * MailProvider::starredFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"starred\"));\n}\n\nString * MailProvider::allMailFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"allmail\"));\n}\n\nString * MailProvider::trashFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"trash\"));\n}\n\nString * MailProvider::draftsFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"drafts\"));\n}\n\nString * MailProvider::spamFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"spam\"));\n}\n\nString * MailProvider::importantFolderPath()\n{\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"important\"));\n}\n\nbool MailProvider::isMainFolder(String * folderPath, String * prefix)\n{\n bool result = false;\n mc_foreachhashmapValue(String, path, mMailboxPaths) {\n String * fullPath;\n \n if (prefix != NULL) {\n fullPath = prefix->stringByAppendingString((String *) path);\n }\n else {\n fullPath = path;\n }\n \n if (fullPath->isEqual(folderPath)) {\n result = true;\n break;\n }\n }\n \n return result;\n}\n\nString * MailProvider::description()\n{\n return String::stringWithUTF8Format(\"<%s:%p, %s>\", className()->UTF8Characters(), this, MCUTF8(mIdentifier));\n}\n\nObject * MailProvider::copy()\n{\n return new MailProvider(this);\n}\n\n<commit_msg>Do not segfault on MailProvider::*FolderPath in case of absence information about folders in providers.json (#1410)<commit_after>\/\/\n\/\/ MCMailProvider.cpp\n\/\/ mailcore2\n\/\/\n\/\/ Created by Robert Widmann on 4\/28\/13.\n\/\/ Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCMailProvider.h\"\n#include \"MCNetService.h\"\n#include \"MCIterator.h\"\n#include \"MCJSON.h\"\n\n#ifdef _MSC_VER\n#include <unicode\/uregex.h>\n#include <unicode\/utext.h>\n#include <unicode\/utypes.h>\n#include <unicode\/localpointer.h>\n#include <unicode\/parseerr.h>\n#else\n#include <regex.h>\n#endif\n\nusing namespace mailcore;\n\nvoid MailProvider::init()\n{\n mIdentifier = NULL;\n mImapServices = new Array();\n mSmtpServices = new Array();\n mPopServices = new Array();\n mDomainMatch = new Array();\n mDomainExclude = new Array();\n mMxMatch = new Array();\n mMailboxPaths = NULL;\n}\n\nMailProvider::MailProvider()\n{\n init();\n}\n\nMailProvider::MailProvider(MailProvider * other)\n{\n init();\n MC_SAFE_REPLACE_COPY(String, mIdentifier, other->mIdentifier);\n MC_SAFE_REPLACE_COPY(Array, mImapServices, other->mImapServices);\n MC_SAFE_REPLACE_COPY(Array, mSmtpServices, other->mSmtpServices);\n MC_SAFE_REPLACE_COPY(Array, mPopServices, other->mPopServices);\n MC_SAFE_REPLACE_COPY(Array, mDomainMatch, other->mDomainMatch);\n MC_SAFE_REPLACE_COPY(Array, mDomainExclude, other->mDomainExclude);\n MC_SAFE_REPLACE_COPY(Array, mMxMatch, other->mMxMatch);\n MC_SAFE_REPLACE_COPY(HashMap, mMailboxPaths, other->mMailboxPaths);\n}\n\nMailProvider::~MailProvider()\n{\n MC_SAFE_RELEASE(mImapServices);\n MC_SAFE_RELEASE(mSmtpServices);\n MC_SAFE_RELEASE(mPopServices);\n MC_SAFE_RELEASE(mMxMatch);\n MC_SAFE_RELEASE(mDomainMatch);\n MC_SAFE_RELEASE(mDomainExclude);\n MC_SAFE_RELEASE(mMailboxPaths);\n MC_SAFE_RELEASE(mIdentifier);\n}\n\nMailProvider * MailProvider::providerWithInfo(HashMap * info)\n{\n MailProvider * provider = new MailProvider();\n provider->fillWithInfo(info);\n provider->autorelease();\n return provider;\n}\n\nvoid MailProvider::fillWithInfo(HashMap * info)\n{\n Array * imapInfos;\n Array * smtpInfos;\n Array * popInfos;\n HashMap * serverInfo;\n \n MC_SAFE_RELEASE(mDomainMatch);\n if (info->objectForKey(MCSTR(\"domain-match\")) != NULL) {\n mDomainMatch = (Array *) info->objectForKey(MCSTR(\"domain-match\"))->retain();\n }\n MC_SAFE_RELEASE(mDomainExclude);\n if (info->objectForKey(MCSTR(\"domain-exclude\")) != NULL) {\n mDomainExclude = (Array *) info->objectForKey(MCSTR(\"domain-exclude\"))->retain();\n }\n MC_SAFE_RELEASE(mMailboxPaths);\n if (info->objectForKey(MCSTR(\"mailboxes\")) != NULL) {\n mMailboxPaths = (HashMap *) info->objectForKey(MCSTR(\"mailboxes\"))->retain();\n }\n MC_SAFE_RELEASE(mMxMatch);\n if (info->objectForKey(MCSTR(\"mx-match\")) != NULL) {\n mMxMatch = (Array *) info->objectForKey(MCSTR(\"mx-match\"))->retain();\n }\n \n serverInfo = (HashMap *) info->objectForKey(MCSTR(\"servers\"));\n if (serverInfo == NULL) {\n MCLog(\"servers key missing from provider %s\", MCUTF8DESC(info));\n }\n MCAssert(serverInfo != NULL);\n imapInfos = (Array *) serverInfo->objectForKey(MCSTR(\"imap\"));\n smtpInfos = (Array *) serverInfo->objectForKey(MCSTR(\"smtp\"));\n popInfos = (Array *) serverInfo->objectForKey(MCSTR(\"pop\"));\n \n mImapServices->removeAllObjects();\n mc_foreacharray(HashMap, imapInfo, imapInfos) {\n NetService * service = NetService::serviceWithInfo(imapInfo);\n mImapServices->addObject(service);\n }\n \n mSmtpServices->removeAllObjects();\n mc_foreacharray(HashMap, smtpInfo, smtpInfos) {\n NetService * service = NetService::serviceWithInfo(smtpInfo);\n mSmtpServices->addObject(service);\n }\n \n mPopServices->removeAllObjects();\n mc_foreacharray(HashMap, popInfo, popInfos) {\n NetService * service = NetService::serviceWithInfo(popInfo);\n mPopServices->addObject(service);\n }\n}\n\nvoid MailProvider::setIdentifier(String * identifier)\n{\n MC_SAFE_REPLACE_COPY(String, mIdentifier, identifier);\n}\n\nString * MailProvider::identifier()\n{\n return mIdentifier;\n}\n\nArray * MailProvider::imapServices()\n{\n return mImapServices;\n}\n\nArray * MailProvider::smtpServices()\n{\n return mSmtpServices;\n}\n\nArray * MailProvider::popServices()\n{\n return mPopServices;\n}\n\nbool MailProvider::matchEmail(String * email)\n{\n Array * components;\n String * domain;\n \n components = email->componentsSeparatedByString(MCSTR(\"@\"));\n if (components->count() < 2)\n return false;\n \n domain = (String *) components->lastObject();\n\n bool matchExcludeDomain = false;\n mc_foreacharray(String, exclude, mDomainExclude) {\n if (matchDomain(exclude, domain)){\n matchExcludeDomain = true;;\n break;\n }\n }\n if (matchExcludeDomain) {\n return false;\n }\n\n bool matchValidDomain = false;\n mc_foreacharray(String, match, mDomainMatch) {\n if (matchDomain(match, domain)){\n matchValidDomain = true;\n break;\n }\n }\n if (matchValidDomain) {\n return true;\n }\n\n return false;\n}\n\nbool MailProvider::matchMX(String * hostname)\n{\n bool result = false;\n mc_foreacharray(String, match, mMxMatch) {\n if (matchDomain(match, hostname)){\n result = true;\n break;\n }\n }\n\n return result;\n}\n\nbool MailProvider::matchDomain(String * match, String * domain)\n{\n#ifdef _MSC_VER\n UParseError error;\n UErrorCode code = U_ZERO_ERROR;\n URegularExpression * r = uregex_open(match->unicodeCharacters(), match->length(), UREGEX_CASE_INSENSITIVE, &error, &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n uregex_setText(r, domain->unicodeCharacters(), domain->length(), &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n\n\tbool matched = uregex_matches(r, 0, &code);\n if (code != U_ZERO_ERROR) {\n uregex_close(r);\n return false;\n }\n\n uregex_close(r);\n\n return matched;\n#else\n const char * cDomain;\n regex_t r;\n bool matched; \n\n cDomain = domain->UTF8Characters();\n match = String::stringWithUTF8Format(\"^%s$\", match->UTF8Characters());\n matched = false;\n\n if (regcomp(&r, match->UTF8Characters(), REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0){\n return matched;\n }\n\n if (regexec(&r, cDomain, 0, NULL, 0) == 0) {\n matched = true;\n }\n\n regfree(&r);\n\n return matched;\n#endif\n}\n\nString * MailProvider::sentMailFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"sentmail\"));\n}\n\nString * MailProvider::starredFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"starred\"));\n}\n\nString * MailProvider::allMailFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"allmail\"));\n}\n\nString * MailProvider::trashFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"trash\"));\n}\n\nString * MailProvider::draftsFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"drafts\"));\n}\n\nString * MailProvider::spamFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"spam\"));\n}\n\nString * MailProvider::importantFolderPath()\n{\n if (mMailboxPaths == NULL)\n return NULL;\n return (String *) mMailboxPaths->objectForKey(MCSTR(\"important\"));\n}\n\nbool MailProvider::isMainFolder(String * folderPath, String * prefix)\n{\n bool result = false;\n mc_foreachhashmapValue(String, path, mMailboxPaths) {\n String * fullPath;\n \n if (prefix != NULL) {\n fullPath = prefix->stringByAppendingString((String *) path);\n }\n else {\n fullPath = path;\n }\n \n if (fullPath->isEqual(folderPath)) {\n result = true;\n break;\n }\n }\n \n return result;\n}\n\nString * MailProvider::description()\n{\n return String::stringWithUTF8Format(\"<%s:%p, %s>\", className()->UTF8Characters(), this, MCUTF8(mIdentifier));\n}\n\nObject * MailProvider::copy()\n{\n return new MailProvider(this);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n# if defined(__APPLE__) || defined(__FreeBSD__)\n\n# include \"io_looper.h\"\n\n# define IO_LOOPER_USER_NOTIFICATION_FD (-10)\n\nnamespace dsn\n{\n namespace tools\n {\n io_looper::io_looper()\n {\n _io_queue = -1;\n _local_notification_fd = IO_LOOPER_USER_NOTIFICATION_FD;\n _filters.insert(EVFILT_READ);\n _filters.insert(EVFILT_WRITE);\n \/\/_filters.insert(EVFILT_AIO);\n _filters.insert(EVFILT_READ_WRITE);\n _filters.insert(EVFILT_USER);\n }\n\n io_looper::~io_looper(void)\n {\n stop();\n }\n\n error_code io_looper::bind_io_handle(\n dsn_handle_t handle,\n io_loop_callback* cb,\n unsigned int events,\n ref_counter* ctx\n )\n {\n int fd;\n short filters[2];\n int nr_filters;\n struct kevent e; \n\n if (cb == nullptr)\n {\n derror(\"cb == nullptr\");\n return ERR_INVALID_PARAMETERS;\n }\n\n fd = (int)(intptr_t)(handle);\n if (fd < 0)\n {\n if (fd != IO_LOOPER_USER_NOTIFICATION_FD)\n {\n derror(\"The fd %d is less than 0.\", fd);\n return ERR_INVALID_PARAMETERS;\n }\n }\n\n if (_filters.find((short)events) == _filters.end())\n {\n derror(\"The filter %u is unsupported.\", events);\n return ERR_INVALID_PARAMETERS;\n }\n\n if (fd > 0)\n {\n int flags = fcntl(fd, F_GETFL, 0);\n dassert (flags != -1, \"fcntl failed, err = %s, fd = %d\", strerror(errno), fd);\n\n if (!(flags & O_NONBLOCK))\n {\n flags |= O_NONBLOCK;\n flags = fcntl(fd, F_SETFL, flags);\n dassert(flags != -1, \"fcntl failed, err = %s, fd = %d\", strerror(errno), fd);\n }\n }\n\n uintptr_t cb0 = (uintptr_t)cb;\n dassert((cb0 & 0x1) == 0, \"the least one bit must be zero for the callback address\");\n\n if (ctx)\n {\n cb0 |= 0x1; \/\/ has ref_counter\n\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto pr = _io_sessions.insert(io_sessions::value_type(cb, ctx));\n dassert(pr.second, \"the callback must not be registered before\");\n }\n \n if ((short)events == EVFILT_READ_WRITE)\n {\n filters[0] = EVFILT_READ;\n filters[1] = EVFILT_WRITE;\n nr_filters = 2;\n }\n else\n {\n filters[0] = (short)events;\n nr_filters = 1;\n }\n\n for (int i = 0; i < nr_filters; i++)\n {\n EV_SET(&e, fd, filters[i], (EV_ADD | EV_ENABLE | EV_CLEAR), 0, 0, (void*)cb0);\n\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n derror(\"bind io handler to kqueue failed, err = %s, fd = %d\", strerror(errno), fd);\n\n if (ctx)\n {\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto r = _io_sessions.erase(cb);\n dassert(r > 0, \"the callback must be present\");\n }\n\n for (int j = 0; j < i; j++)\n {\n EV_SET(&e, fd, filters[j], EV_DELETE, 0, 0, nullptr);\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n derror(\"Unregister kqueue failed, filter = %d, err = %s, fd = %d\", filters[j], strerror(errno), fd);\n }\n }\n\n return ERR_BIND_IOCP_FAILED;\n }\n }\n\n return ERR_OK;\n }\n \n error_code io_looper::unbind_io_handle(dsn_handle_t handle, io_loop_callback* cb)\n {\n int fd = (int)(intptr_t)handle;\n struct kevent e;\n \n if (cb)\n {\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto r = _io_sessions.erase(cb);\n dassert(r > 0, \"the callback must be present\");\n }\n\n for (auto filter : _filters)\n {\n EV_SET(&e, fd, filter, EV_DELETE, 0, 0, nullptr);\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n if (errno != ENOENT)\n {\n derror(\"unbind io handler to kqueue failed, err = %s, fd = %d\", strerror(errno), fd);\n return ERR_BIND_IOCP_FAILED;\n }\n }\n }\n\n return ERR_OK;\n }\n\n void io_looper::notify_local_execution()\n {\n struct kevent e;\n EV_SET(&e, _local_notification_fd, EVFILT_USER, 0, (NOTE_FFCOPY | NOTE_TRIGGER), 0, &_local_notification_callback);\n\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n dassert(false, \"post local notification via eventfd failed, err = %s\", strerror(errno));\n }\n dinfo(\"notify local\");\n }\n\n void io_looper::create_completion_queue()\n {\n _io_queue = ::kqueue();\n dassert(_io_queue != -1, \"Fail to create kqueue\");\n\n _local_notification_callback = [this](\n int native_error,\n uint32_t io_size,\n uintptr_t lolp_or_events\n )\n {\n this->handle_local_queues();\n };\n\n bind_io_handle((dsn_handle_t)(intptr_t)_local_notification_fd, &_local_notification_callback, \n EVFILT_USER);\n }\n\n void io_looper::close_completion_queue()\n {\n if (_io_queue != -1)\n {\n\t\tunbind_io_handle((dsn_handle_t)(intptr_t)_local_notification_fd, &_local_notification_callback);\n ::close(_io_queue);\n _io_queue = -1;\n }\n }\n\n void io_looper::start(service_node* node, int worker_count)\n {\n create_completion_queue();\n \n for (int i = 0; i < worker_count; i++)\n {\n std::thread* thr = new std::thread([this, node, i]()\n {\n task::set_tls_dsn_context(node, nullptr, nullptr);\n\n const char* name = node ? ::dsn::tools::get_service_node_name(node) : \"glb\";\n char buffer[128];\n sprintf(buffer, \"%s.io-loop.%d\", name, i);\n task_worker::set_name(buffer);\n \n this->loop_worker(); \n });\n _workers.push_back(thr);\n }\n }\n\n void io_looper::stop()\n {\n close_completion_queue();\n\n if (_workers.size() > 0)\n {\n for (auto thr : _workers)\n {\n thr->join();\n delete thr;\n }\n _workers.clear();\n }\n }\n\n void io_looper::loop_worker()\n {\n struct timespec ts = { 0, 1000000 };\n\n while (true)\n {\n int nfds = kevent(_io_queue, nullptr, 0, _events, IO_LOOPER_MAX_EVENT_COUNT, &ts); \/\/ 1ms for timers\n if (nfds == 0) \/\/ timeout\n {\n handle_local_queues();\n continue;\n }\n else if (-1 == nfds)\n {\n if (errno == EINTR)\n {\n continue;\n } \n else\n {\n derror(\"epoll_wait loop exits, err = %s\", strerror(errno));\n break;\n }\n }\n\n for (int i = 0; i < nfds; i++)\n {\n auto cb = (io_loop_callback*)_events[i].udata;\n dinfo(\"kevent get events %x, cb = %p\", _events[i].filter, cb);\n\n uintptr_t cb0 = (uintptr_t)cb;\n\n \/\/ for those with ref_counter register entries\n if (cb0 & 0x1)\n {\n cb = (io_loop_callback*)(cb0 - 1);\n\n ref_counter* robj;\n {\n\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto it = _io_sessions.find(cb);\n if (it != _io_sessions.end())\n {\n robj = it->second;\n \/\/ make sure callback is protected by ref counting\n robj->add_ref();\n }\n else\n {\n robj = nullptr;\n }\n }\n\n if (robj)\n {\n (*cb)(0, 0, (uintptr_t)&_events[i]);\n robj->release_ref();\n }\n else\n {\n \/\/ context is gone (unregistered), let's skip\n dwarn(\"kevent event %x skipped as session is gone, cb = %p\",\n _events[i].filter,\n cb\n );\n }\n }\n else\n {\n (*cb)(0, 0, (uintptr_t)&_events[i]);\n }\n }\n }\n }\n }\n}\n\n# endif\n<commit_msg>More error checks.<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n# if defined(__APPLE__) || defined(__FreeBSD__)\n\n# include \"io_looper.h\"\n\n# define IO_LOOPER_USER_NOTIFICATION_FD (-10)\n\nnamespace dsn\n{\n namespace tools\n {\n io_looper::io_looper()\n {\n _io_queue = -1;\n _local_notification_fd = IO_LOOPER_USER_NOTIFICATION_FD;\n _filters.insert(EVFILT_READ);\n _filters.insert(EVFILT_WRITE);\n \/\/_filters.insert(EVFILT_AIO);\n _filters.insert(EVFILT_READ_WRITE);\n _filters.insert(EVFILT_USER);\n }\n\n io_looper::~io_looper(void)\n {\n stop();\n }\n\n error_code io_looper::bind_io_handle(\n dsn_handle_t handle,\n io_loop_callback* cb,\n unsigned int events,\n ref_counter* ctx\n )\n {\n int fd;\n short filters[2];\n int nr_filters;\n struct kevent e; \n\n if (cb == nullptr)\n {\n derror(\"cb == nullptr\");\n return ERR_INVALID_PARAMETERS;\n }\n\n fd = (int)(intptr_t)(handle);\n if (fd < 0)\n {\n if (fd != IO_LOOPER_USER_NOTIFICATION_FD)\n {\n derror(\"The fd %d is less than 0.\", fd);\n return ERR_INVALID_PARAMETERS;\n }\n }\n\n if (_filters.find((short)events) == _filters.end())\n {\n derror(\"The filter %u is unsupported.\", events);\n return ERR_INVALID_PARAMETERS;\n }\n\n if (fd > 0)\n {\n int flags = fcntl(fd, F_GETFL, 0);\n dassert (flags != -1, \"fcntl failed, err = %s, fd = %d\", strerror(errno), fd);\n\n if (!(flags & O_NONBLOCK))\n {\n flags |= O_NONBLOCK;\n flags = fcntl(fd, F_SETFL, flags);\n dassert(flags != -1, \"fcntl failed, err = %s, fd = %d\", strerror(errno), fd);\n }\n }\n\n uintptr_t cb0 = (uintptr_t)cb;\n dassert((cb0 & 0x1) == 0, \"the least one bit must be zero for the callback address\");\n\n if (ctx)\n {\n cb0 |= 0x1; \/\/ has ref_counter\n\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto pr = _io_sessions.insert(io_sessions::value_type(cb, ctx));\n dassert(pr.second, \"the callback must not be registered before\");\n }\n \n if ((short)events == EVFILT_READ_WRITE)\n {\n filters[0] = EVFILT_READ;\n filters[1] = EVFILT_WRITE;\n nr_filters = 2;\n }\n else\n {\n filters[0] = (short)events;\n nr_filters = 1;\n }\n\n for (int i = 0; i < nr_filters; i++)\n {\n EV_SET(&e, fd, filters[i], (EV_ADD | EV_ENABLE | EV_CLEAR), 0, 0, (void*)cb0);\n\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n derror(\"bind io handler to kqueue failed, err = %s, fd = %d\", strerror(errno), fd);\n\n if (ctx)\n {\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto r = _io_sessions.erase(cb);\n dassert(r > 0, \"the callback must be present\");\n }\n\n for (int j = 0; j < i; j++)\n {\n EV_SET(&e, fd, filters[j], EV_DELETE, 0, 0, nullptr);\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n derror(\"Unregister kqueue failed, filter = %d, err = %s, fd = %d\", filters[j], strerror(errno), fd);\n }\n }\n\n return ERR_BIND_IOCP_FAILED;\n }\n }\n\n return ERR_OK;\n }\n \n error_code io_looper::unbind_io_handle(dsn_handle_t handle, io_loop_callback* cb)\n {\n int fd = (int)(intptr_t)handle;\n struct kevent e;\n int cnt = 0;\n\n for (auto filter : _filters)\n {\n EV_SET(&e, fd, filter, EV_DELETE, 0, 0, nullptr);\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n if (errno != ENOENT)\n {\n derror(\"unbind io handler to kqueue failed, err = %s, fd = %d\", strerror(errno), fd);\n return ERR_BIND_IOCP_FAILED;\n }\n }\n else\n {\n cnt++;\n }\n }\n\n if (cnt == 0)\n {\n derror(\"fd = %d has not been binded yet.\", fd);\n return ERR_BIND_IOCP_FAILED;\n }\n\n if (cb)\n {\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto r = _io_sessions.erase(cb);\n dassert(r > 0, \"the callback must be present\");\n }\n\n return ERR_OK;\n }\n\n void io_looper::notify_local_execution()\n {\n struct kevent e;\n EV_SET(&e, _local_notification_fd, EVFILT_USER, 0, (NOTE_FFCOPY | NOTE_TRIGGER), 0, &_local_notification_callback);\n\n if (kevent(_io_queue, &e, 1, nullptr, 0, nullptr) == -1)\n {\n dassert(false, \"post local notification via eventfd failed, err = %s\", strerror(errno));\n }\n dinfo(\"notify local\");\n }\n\n void io_looper::create_completion_queue()\n {\n _io_queue = ::kqueue();\n dassert(_io_queue != -1, \"Fail to create kqueue\");\n\n _local_notification_callback = [this](\n int native_error,\n uint32_t io_size,\n uintptr_t lolp_or_events\n )\n {\n this->handle_local_queues();\n };\n\n bind_io_handle((dsn_handle_t)(intptr_t)_local_notification_fd, &_local_notification_callback, \n EVFILT_USER);\n }\n\n void io_looper::close_completion_queue()\n {\n if (_io_queue != -1)\n {\n\t\tunbind_io_handle((dsn_handle_t)(intptr_t)_local_notification_fd, &_local_notification_callback);\n ::close(_io_queue);\n _io_queue = -1;\n }\n }\n\n void io_looper::start(service_node* node, int worker_count)\n {\n create_completion_queue();\n \n for (int i = 0; i < worker_count; i++)\n {\n std::thread* thr = new std::thread([this, node, i]()\n {\n task::set_tls_dsn_context(node, nullptr, nullptr);\n\n const char* name = node ? ::dsn::tools::get_service_node_name(node) : \"glb\";\n char buffer[128];\n sprintf(buffer, \"%s.io-loop.%d\", name, i);\n task_worker::set_name(buffer);\n \n this->loop_worker(); \n });\n _workers.push_back(thr);\n }\n }\n\n void io_looper::stop()\n {\n close_completion_queue();\n\n if (_workers.size() > 0)\n {\n for (auto thr : _workers)\n {\n thr->join();\n delete thr;\n }\n _workers.clear();\n }\n }\n\n void io_looper::loop_worker()\n {\n struct timespec ts = { 0, 1000000 };\n\n while (true)\n {\n int nfds = kevent(_io_queue, nullptr, 0, _events, IO_LOOPER_MAX_EVENT_COUNT, &ts); \/\/ 1ms for timers\n if (nfds == 0) \/\/ timeout\n {\n handle_local_queues();\n continue;\n }\n else if (-1 == nfds)\n {\n if (errno == EINTR)\n {\n continue;\n } \n else\n {\n derror(\"epoll_wait loop exits, err = %s\", strerror(errno));\n break;\n }\n }\n\n for (int i = 0; i < nfds; i++)\n {\n auto cb = (io_loop_callback*)_events[i].udata;\n dinfo(\"kevent get events %x, cb = %p\", _events[i].filter, cb);\n\n uintptr_t cb0 = (uintptr_t)cb;\n\n \/\/ for those with ref_counter register entries\n if (cb0 & 0x1)\n {\n cb = (io_loop_callback*)(cb0 - 1);\n\n ref_counter* robj;\n {\n\n utils::auto_lock<utils::ex_lock_nr_spin> l(_io_sessions_lock);\n auto it = _io_sessions.find(cb);\n if (it != _io_sessions.end())\n {\n robj = it->second;\n \/\/ make sure callback is protected by ref counting\n robj->add_ref();\n }\n else\n {\n robj = nullptr;\n }\n }\n\n if (robj)\n {\n (*cb)(0, 0, (uintptr_t)&_events[i]);\n robj->release_ref();\n }\n else\n {\n \/\/ context is gone (unregistered), let's skip\n dwarn(\"kevent event %x skipped as session is gone, cb = %p\",\n _events[i].filter,\n cb\n );\n }\n }\n else\n {\n (*cb)(0, 0, (uintptr_t)&_events[i]);\n }\n }\n }\n }\n }\n}\n\n# endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <vector>>\r\nusing namespace std;\r\n<commit_msg>Delete progr_main.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"MultiPoint.hpp\"\n#include \"BoundingBox.hpp\"\n\nnamespace Slic3r {\n\nMultiPoint::operator Points() const\n{\n return this->points;\n}\n\nvoid MultiPoint::scale(double factor)\n{\n for (Point &pt : points)\n pt *= factor;\n}\n\nvoid MultiPoint::scale(double factor_x, double factor_y)\n{\n for (Point &pt : points)\n {\n\t\tpt(0) = coord_t(pt(0) * factor_x);\n\t\tpt(1) = coord_t(pt(1) * factor_y);\n }\n}\n\nvoid MultiPoint::translate(double x, double y)\n{\n Vector v(x, y);\n for (Point &pt : points)\n pt += v;\n}\n\nvoid MultiPoint::translate(const Point &v)\n{\n for (Point &pt : points)\n pt += v;\n}\n\nvoid MultiPoint::rotate(double cos_angle, double sin_angle)\n{\n for (Point &pt : this->points) {\n double cur_x = double(pt(0));\n double cur_y = double(pt(1));\n pt(0) = coord_t(round(cos_angle * cur_x - sin_angle * cur_y));\n pt(1) = coord_t(round(cos_angle * cur_y + sin_angle * cur_x));\n }\n}\n\nvoid MultiPoint::rotate(double angle, const Point ¢er)\n{\n double s = sin(angle);\n double c = cos(angle);\n for (Point &pt : points) {\n Vec2crd v(pt - center);\n pt(0) = (coord_t)round(double(center(0)) + c * v[0] - s * v[1]);\n pt(1) = (coord_t)round(double(center(1)) + c * v[1] + s * v[0]);\n }\n}\n\nvoid MultiPoint::reverse()\n{\n std::reverse(this->points.begin(), this->points.end());\n}\n\nPoint MultiPoint::first_point() const\n{\n return this->points.front();\n}\n\ndouble\nMultiPoint::length() const\n{\n Lines lines = this->lines();\n double len = 0;\n for (Lines::iterator it = lines.begin(); it != lines.end(); ++it) {\n len += it->length();\n }\n return len;\n}\n\nint\nMultiPoint::find_point(const Point &point) const\n{\n for (const Point &pt : this->points)\n if (pt == point)\n return int(&pt - &this->points.front());\n return -1; \/\/ not found\n}\n\nbool\nMultiPoint::has_boundary_point(const Point &point) const\n{\n double dist = (point.projection_onto(*this) - point).cast<double>().norm();\n return dist < SCALED_EPSILON;\n}\n\nBoundingBox\nMultiPoint::bounding_box() const\n{\n return BoundingBox(this->points);\n}\n\nbool \nMultiPoint::has_duplicate_points() const\n{\n for (size_t i = 1; i < points.size(); ++i)\n if (points[i-1] == points[i])\n return true;\n return false;\n}\n\nbool\nMultiPoint::remove_duplicate_points()\n{\n size_t j = 0;\n for (size_t i = 1; i < points.size(); ++i) {\n if (points[j] == points[i]) {\n \/\/ Just increase index i.\n } else {\n ++ j;\n if (j < i)\n points[j] = points[i];\n }\n }\n if (++ j < points.size()) {\n points.erase(points.begin() + j, points.end());\n return true;\n }\n return false;\n}\n\nbool\nMultiPoint::intersection(const Line& line, Point* intersection) const\n{\n Lines lines = this->lines();\n for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it) {\n if (it->intersection(line, intersection)) return true;\n }\n return false;\n}\n\nbool MultiPoint::first_intersection(const Line& line, Point* intersection) const\n{\n bool found = false;\n double dmin = 0.;\n for (const Line &l : this->lines()) {\n Point ip;\n if (l.intersection(line, &ip)) {\n if (! found) {\n found = true;\n dmin = (line.a - ip).cast<double>().norm();\n *intersection = ip;\n } else {\n double d = (line.a - ip).cast<double>().norm();\n if (d < dmin) {\n dmin = d;\n *intersection = ip;\n }\n }\n }\n }\n return found;\n}\n\nstd::vector<Point> MultiPoint::_douglas_peucker(const std::vector<Point>& pts, const double tolerance)\n{\n std::vector<Point> result_pts;\n\tdouble tolerance_sq = tolerance * tolerance;\n if (! pts.empty()) {\n const Point *anchor = &pts.front();\n size_t anchor_idx = 0;\n const Point *floater = &pts.back();\n size_t floater_idx = pts.size() - 1;\n result_pts.reserve(pts.size());\n result_pts.emplace_back(*anchor);\n if (anchor_idx != floater_idx) {\n assert(pts.size() > 1);\n std::vector<size_t> dpStack;\n dpStack.reserve(pts.size());\n dpStack.emplace_back(floater_idx);\n for (;;) {\n double max_dist_sq = 0.0;\n size_t furthest_idx = anchor_idx;\n \/\/ find point furthest from line seg created by (anchor, floater) and note it\n for (size_t i = anchor_idx + 1; i < floater_idx; ++ i) {\n double dist_sq = Line::distance_to_squared(pts[i], *anchor, *floater);\n if (dist_sq > max_dist_sq) {\n max_dist_sq = dist_sq;\n furthest_idx = i;\n }\n }\n \/\/ remove point if less than tolerance\n if (max_dist_sq <= tolerance_sq) {\n result_pts.emplace_back(*floater);\n anchor_idx = floater_idx;\n anchor = floater;\n assert(dpStack.back() == floater_idx);\n dpStack.pop_back();\n if (dpStack.empty())\n break;\n floater_idx = dpStack.back();\n } else {\n floater_idx = furthest_idx;\n dpStack.emplace_back(floater_idx);\n }\n floater = &pts[floater_idx];\n }\n }\n }\n return result_pts;\n}\n\n\/\/ Visivalingam simplification algorithm https:\/\/github.com\/slic3r\/Slic3r\/pull\/3825\n\/\/ thanks to @fuchstraumer\n\/*\n struct - vis_node\n Used with the visivalignam simplification algorithm, which needs to be able to find a points\n successors and predecessors to operate succesfully. Since this struct is only used in one\n location, it could probably be dropped into a namespace to avoid polluting the slic3r namespace.\n Source: https:\/\/github.com\/shortsleeves\/visvalingam_simplify\n ^ Provided original algorithm implementation. I've only changed things a bit to \"clean\" them up\n (i.e be more like my personal style), and managed to do this without requiring a binheap implementation\n *\/\nstruct vis_node{\n vis_node(const size_t& idx, const size_t& _prev_idx, const size_t& _next_idx, const double& _area) : pt_idx(idx), prev_idx(_prev_idx), next_idx(_next_idx), area(_area) {}\n \/\/ Indices into a Points container, from which this object was constructed\n size_t pt_idx, prev_idx, next_idx;\n \/\/ Effective area of this \"node\"\n double area;\n \/\/ Overloaded operator used to sort the binheap\n \/\/ Greater area = \"more important\" node. So, this node is less than the \n \/\/ other node if it's area is less than the other node's area\n bool operator<(const vis_node& other) { return (this->area < other.area); }\n};\nPoints MultiPoint::visivalingam(const Points& pts, const double& tolerance)\n{\n \/\/ Make sure there's enough points in \"pts\" to bother with simplification.\n assert(pts.size() >= 2);\n \/\/ Result object\n Points results;\n \/\/ Lambda to calculate effective area spanned by a point and its immediate \n \/\/ successor + predecessor.\n auto effective_area = [pts](const size_t& curr_pt_idx, const size_t& prev_pt_idx, const size_t& next_pt_idx)->coordf_t {\n const Point& curr = pts[curr_pt_idx];\n const Point& prev = pts[prev_pt_idx];\n const Point& next = pts[next_pt_idx];\n \/\/ Use point objects as vector-distances\n\t\tconst Vec2d curr_to_next = (next - curr).cast<double>();\n\t\tconst Vec2d prev_to_next = (prev - curr).cast<double>();\n \/\/ Take cross product of these two vector distances\n\t\treturn 0.50 * abs(cross2(curr_to_next, prev_to_next));\n };\n \/\/ We store the effective areas for each node\n std::vector<coordf_t> areas;\n areas.reserve(pts.size());\n \/\/ Construct the initial set of nodes. We will make a heap out of the \"heap\" vector using \n \/\/ std::make_heap. node_list is used later.\n std::vector<vis_node*> node_list;\n node_list.resize(pts.size());\n std::vector<vis_node*> heap;\n heap.reserve(pts.size());\n for (size_t i = 1; i < pts.size() - 1; ++ i) {\n \/\/ Get effective area of current node.\n coordf_t area = effective_area(i, i - 1, i + 1);\n \/\/ If area is greater than some arbitrarily small value, use it.\n node_list[i] = new vis_node(i, i - 1, i + 1, area);\n heap.push_back(node_list[i]);\n }\n \/\/ Call std::make_heap, which uses the < operator by default to make \"heap\" into \n \/\/ a binheap, sorted by the < operator we defind in the vis_node struct\n std::make_heap(heap.begin(), heap.end());\n \/\/ Start comparing areas. Set min_area to an outrageous value initially.\n double min_area = -std::numeric_limits<double>::max();\n while (!heap.empty()) {\n \/\/ Get current node.\n vis_node* curr = heap.front();\n \/\/ Pop node we just retrieved off the heap. pop_heap moves front element in vector\n \/\/ to the back, so we can call pop_back()\n std::pop_heap(heap.begin(), heap.end());\n heap.pop_back();\n \/\/ Sanity assert check\n assert(curr == node_list[curr->pt_idx]);\n \/\/ If the current pt'ss area is less than that of the previous pt's area\n \/\/ use the last pt's area instead. This ensures we don't elimate the current\n \/\/ point without eliminating the previous \n min_area = std::max(min_area, curr->area);\n \/\/ Update prev\n vis_node* prev = node_list[curr->prev_idx];\n if(prev != nullptr){\n prev->next_idx = curr->next_idx;\n prev->area = effective_area(prev->pt_idx, prev->prev_idx, prev->next_idx);\n \/\/ For some reason, std::make_heap() is the fastest way to resort the heap. Probably needs testing.\n std::make_heap(heap.begin(), heap.end());\n }\n \/\/ Update next\n vis_node* next = node_list[curr->next_idx];\n if(next != nullptr){\n next->prev_idx = curr->prev_idx;\n next->area = effective_area(next->pt_idx, next->prev_idx, next->next_idx);\n std::make_heap(heap.begin(), heap.end());\n }\n areas[curr->pt_idx] = min_area;\n node_list[curr->pt_idx] = nullptr;\n delete curr;\n }\n \/\/ Clear node list and shrink_to_fit() (to free actual memory). Not necessary. Could be removed.\n node_list.clear();\n node_list.shrink_to_fit();\n \/\/ This lambda is how we test whether or not to keep a point.\n auto use_point = [areas, tolerance](const size_t& idx)->bool {\n assert(idx < areas.size());\n \/\/ Return true at front\/back of path\/areas\n if(idx == 0 || idx == areas.size() - 1){\n return true;\n }\n \/\/ Return true if area at idx is greater than minimum area to consider \"valid\"\n else{\n return areas[idx] > tolerance;\n }\n };\n \/\/ Use previously defined lambda to build results.\n for (size_t i = 0; i < pts.size(); ++i) {\n if (use_point(i)){\n results.push_back(pts[i]);\n }\n }\n \/\/ Check that results has at least two points\n assert(results.size() >= 2);\n \/\/ Return simplified vector of points\n return results;\n}\n\nvoid MultiPoint3::translate(double x, double y)\n{\n for (Vec3crd &p : points) {\n p(0) += coord_t(x);\n p(1) += coord_t(y);\n }\n}\n\nvoid MultiPoint3::translate(const Point& vector)\n{\n this->translate(vector(0), vector(1));\n}\n\ndouble MultiPoint3::length() const\n{\n double len = 0.0;\n for (const Line3& line : this->lines())\n len += line.length();\n return len;\n}\n\nBoundingBox3 MultiPoint3::bounding_box() const\n{\n return BoundingBox3(points);\n}\n\nbool MultiPoint3::remove_duplicate_points()\n{\n size_t j = 0;\n for (size_t i = 1; i < points.size(); ++i) {\n if (points[j] == points[i]) {\n \/\/ Just increase index i.\n } else {\n ++ j;\n if (j < i)\n points[j] = points[i];\n }\n }\n\n if (++j < points.size())\n {\n points.erase(points.begin() + j, points.end());\n return true;\n }\n\n return false;\n}\n\nBoundingBox get_extents(const MultiPoint &mp)\n{ \n return BoundingBox(mp.points);\n}\n\nBoundingBox get_extents_rotated(const Points &points, double angle)\n{ \n BoundingBox bbox;\n if (! points.empty()) {\n double s = sin(angle);\n double c = cos(angle);\n Points::const_iterator it = points.begin();\n double cur_x = (double)(*it)(0);\n double cur_y = (double)(*it)(1);\n bbox.min(0) = bbox.max(0) = (coord_t)round(c * cur_x - s * cur_y);\n bbox.min(1) = bbox.max(1) = (coord_t)round(c * cur_y + s * cur_x);\n for (++it; it != points.end(); ++it) {\n double cur_x = (double)(*it)(0);\n double cur_y = (double)(*it)(1);\n coord_t x = (coord_t)round(c * cur_x - s * cur_y);\n coord_t y = (coord_t)round(c * cur_y + s * cur_x);\n bbox.min(0) = std::min(x, bbox.min(0));\n bbox.min(1) = std::min(y, bbox.min(1));\n bbox.max(0) = std::max(x, bbox.max(0));\n bbox.max(1) = std::max(y, bbox.max(1));\n }\n bbox.defined = true;\n }\n return bbox;\n}\n\nBoundingBox get_extents_rotated(const MultiPoint &mp, double angle)\n{\n return get_extents_rotated(mp.points, angle);\n}\n\n}\n<commit_msg>Added debugging code for the Douglas-Peucker contour simplification code.<commit_after>#include \"MultiPoint.hpp\"\n#include \"BoundingBox.hpp\"\n\nnamespace Slic3r {\n\nMultiPoint::operator Points() const\n{\n return this->points;\n}\n\nvoid MultiPoint::scale(double factor)\n{\n for (Point &pt : points)\n pt *= factor;\n}\n\nvoid MultiPoint::scale(double factor_x, double factor_y)\n{\n for (Point &pt : points)\n {\n\t\tpt(0) = coord_t(pt(0) * factor_x);\n\t\tpt(1) = coord_t(pt(1) * factor_y);\n }\n}\n\nvoid MultiPoint::translate(double x, double y)\n{\n Vector v(x, y);\n for (Point &pt : points)\n pt += v;\n}\n\nvoid MultiPoint::translate(const Point &v)\n{\n for (Point &pt : points)\n pt += v;\n}\n\nvoid MultiPoint::rotate(double cos_angle, double sin_angle)\n{\n for (Point &pt : this->points) {\n double cur_x = double(pt(0));\n double cur_y = double(pt(1));\n pt(0) = coord_t(round(cos_angle * cur_x - sin_angle * cur_y));\n pt(1) = coord_t(round(cos_angle * cur_y + sin_angle * cur_x));\n }\n}\n\nvoid MultiPoint::rotate(double angle, const Point ¢er)\n{\n double s = sin(angle);\n double c = cos(angle);\n for (Point &pt : points) {\n Vec2crd v(pt - center);\n pt(0) = (coord_t)round(double(center(0)) + c * v[0] - s * v[1]);\n pt(1) = (coord_t)round(double(center(1)) + c * v[1] + s * v[0]);\n }\n}\n\nvoid MultiPoint::reverse()\n{\n std::reverse(this->points.begin(), this->points.end());\n}\n\nPoint MultiPoint::first_point() const\n{\n return this->points.front();\n}\n\ndouble\nMultiPoint::length() const\n{\n Lines lines = this->lines();\n double len = 0;\n for (Lines::iterator it = lines.begin(); it != lines.end(); ++it) {\n len += it->length();\n }\n return len;\n}\n\nint\nMultiPoint::find_point(const Point &point) const\n{\n for (const Point &pt : this->points)\n if (pt == point)\n return int(&pt - &this->points.front());\n return -1; \/\/ not found\n}\n\nbool\nMultiPoint::has_boundary_point(const Point &point) const\n{\n double dist = (point.projection_onto(*this) - point).cast<double>().norm();\n return dist < SCALED_EPSILON;\n}\n\nBoundingBox\nMultiPoint::bounding_box() const\n{\n return BoundingBox(this->points);\n}\n\nbool \nMultiPoint::has_duplicate_points() const\n{\n for (size_t i = 1; i < points.size(); ++i)\n if (points[i-1] == points[i])\n return true;\n return false;\n}\n\nbool\nMultiPoint::remove_duplicate_points()\n{\n size_t j = 0;\n for (size_t i = 1; i < points.size(); ++i) {\n if (points[j] == points[i]) {\n \/\/ Just increase index i.\n } else {\n ++ j;\n if (j < i)\n points[j] = points[i];\n }\n }\n if (++ j < points.size()) {\n points.erase(points.begin() + j, points.end());\n return true;\n }\n return false;\n}\n\nbool\nMultiPoint::intersection(const Line& line, Point* intersection) const\n{\n Lines lines = this->lines();\n for (Lines::const_iterator it = lines.begin(); it != lines.end(); ++it) {\n if (it->intersection(line, intersection)) return true;\n }\n return false;\n}\n\nbool MultiPoint::first_intersection(const Line& line, Point* intersection) const\n{\n bool found = false;\n double dmin = 0.;\n for (const Line &l : this->lines()) {\n Point ip;\n if (l.intersection(line, &ip)) {\n if (! found) {\n found = true;\n dmin = (line.a - ip).cast<double>().norm();\n *intersection = ip;\n } else {\n double d = (line.a - ip).cast<double>().norm();\n if (d < dmin) {\n dmin = d;\n *intersection = ip;\n }\n }\n }\n }\n return found;\n}\n\nstd::vector<Point> MultiPoint::_douglas_peucker(const std::vector<Point>& pts, const double tolerance)\n{\n std::vector<Point> result_pts;\n\tdouble tolerance_sq = tolerance * tolerance;\n if (! pts.empty()) {\n const Point *anchor = &pts.front();\n size_t anchor_idx = 0;\n const Point *floater = &pts.back();\n size_t floater_idx = pts.size() - 1;\n result_pts.reserve(pts.size());\n result_pts.emplace_back(*anchor);\n if (anchor_idx != floater_idx) {\n assert(pts.size() > 1);\n std::vector<size_t> dpStack;\n dpStack.reserve(pts.size());\n dpStack.emplace_back(floater_idx);\n for (;;) {\n double max_dist_sq = 0.0;\n size_t furthest_idx = anchor_idx;\n \/\/ find point furthest from line seg created by (anchor, floater) and note it\n for (size_t i = anchor_idx + 1; i < floater_idx; ++ i) {\n double dist_sq = Line::distance_to_squared(pts[i], *anchor, *floater);\n if (dist_sq > max_dist_sq) {\n max_dist_sq = dist_sq;\n furthest_idx = i;\n }\n }\n \/\/ remove point if less than tolerance\n if (max_dist_sq <= tolerance_sq) {\n result_pts.emplace_back(*floater);\n anchor_idx = floater_idx;\n anchor = floater;\n assert(dpStack.back() == floater_idx);\n dpStack.pop_back();\n if (dpStack.empty())\n break;\n floater_idx = dpStack.back();\n } else {\n floater_idx = furthest_idx;\n dpStack.emplace_back(floater_idx);\n }\n floater = &pts[floater_idx];\n }\n }\n assert(result_pts.front() == pts.front());\n assert(result_pts.back() == pts.back());\n\n#if 0\n {\n static int iRun = 0;\n\t\t\tBoundingBox bbox(pts);\n\t\t\tBoundingBox bbox2(result_pts);\n\t\t\tbbox.merge(bbox2);\n SVG svg(debug_out_path(\"douglas_peucker_%d.svg\", iRun ++).c_str(), bbox);\n if (pts.front() == pts.back())\n svg.draw(Polygon(pts), \"black\");\n else\n svg.draw(Polyline(pts), \"black\");\n if (result_pts.front() == result_pts.back())\n svg.draw(Polygon(result_pts), \"green\", scale_(0.1));\n else\n svg.draw(Polyline(result_pts), \"green\", scale_(0.1));\n }\n#endif\n }\n return result_pts;\n}\n\n\/\/ Visivalingam simplification algorithm https:\/\/github.com\/slic3r\/Slic3r\/pull\/3825\n\/\/ thanks to @fuchstraumer\n\/*\n struct - vis_node\n Used with the visivalignam simplification algorithm, which needs to be able to find a points\n successors and predecessors to operate succesfully. Since this struct is only used in one\n location, it could probably be dropped into a namespace to avoid polluting the slic3r namespace.\n Source: https:\/\/github.com\/shortsleeves\/visvalingam_simplify\n ^ Provided original algorithm implementation. I've only changed things a bit to \"clean\" them up\n (i.e be more like my personal style), and managed to do this without requiring a binheap implementation\n *\/\nstruct vis_node{\n vis_node(const size_t& idx, const size_t& _prev_idx, const size_t& _next_idx, const double& _area) : pt_idx(idx), prev_idx(_prev_idx), next_idx(_next_idx), area(_area) {}\n \/\/ Indices into a Points container, from which this object was constructed\n size_t pt_idx, prev_idx, next_idx;\n \/\/ Effective area of this \"node\"\n double area;\n \/\/ Overloaded operator used to sort the binheap\n \/\/ Greater area = \"more important\" node. So, this node is less than the \n \/\/ other node if it's area is less than the other node's area\n bool operator<(const vis_node& other) { return (this->area < other.area); }\n};\nPoints MultiPoint::visivalingam(const Points& pts, const double& tolerance)\n{\n \/\/ Make sure there's enough points in \"pts\" to bother with simplification.\n assert(pts.size() >= 2);\n \/\/ Result object\n Points results;\n \/\/ Lambda to calculate effective area spanned by a point and its immediate \n \/\/ successor + predecessor.\n auto effective_area = [pts](const size_t& curr_pt_idx, const size_t& prev_pt_idx, const size_t& next_pt_idx)->coordf_t {\n const Point& curr = pts[curr_pt_idx];\n const Point& prev = pts[prev_pt_idx];\n const Point& next = pts[next_pt_idx];\n \/\/ Use point objects as vector-distances\n\t\tconst Vec2d curr_to_next = (next - curr).cast<double>();\n\t\tconst Vec2d prev_to_next = (prev - curr).cast<double>();\n \/\/ Take cross product of these two vector distances\n\t\treturn 0.50 * abs(cross2(curr_to_next, prev_to_next));\n };\n \/\/ We store the effective areas for each node\n std::vector<coordf_t> areas;\n areas.reserve(pts.size());\n \/\/ Construct the initial set of nodes. We will make a heap out of the \"heap\" vector using \n \/\/ std::make_heap. node_list is used later.\n std::vector<vis_node*> node_list;\n node_list.resize(pts.size());\n std::vector<vis_node*> heap;\n heap.reserve(pts.size());\n for (size_t i = 1; i < pts.size() - 1; ++ i) {\n \/\/ Get effective area of current node.\n coordf_t area = effective_area(i, i - 1, i + 1);\n \/\/ If area is greater than some arbitrarily small value, use it.\n node_list[i] = new vis_node(i, i - 1, i + 1, area);\n heap.push_back(node_list[i]);\n }\n \/\/ Call std::make_heap, which uses the < operator by default to make \"heap\" into \n \/\/ a binheap, sorted by the < operator we defind in the vis_node struct\n std::make_heap(heap.begin(), heap.end());\n \/\/ Start comparing areas. Set min_area to an outrageous value initially.\n double min_area = -std::numeric_limits<double>::max();\n while (!heap.empty()) {\n \/\/ Get current node.\n vis_node* curr = heap.front();\n \/\/ Pop node we just retrieved off the heap. pop_heap moves front element in vector\n \/\/ to the back, so we can call pop_back()\n std::pop_heap(heap.begin(), heap.end());\n heap.pop_back();\n \/\/ Sanity assert check\n assert(curr == node_list[curr->pt_idx]);\n \/\/ If the current pt'ss area is less than that of the previous pt's area\n \/\/ use the last pt's area instead. This ensures we don't elimate the current\n \/\/ point without eliminating the previous \n min_area = std::max(min_area, curr->area);\n \/\/ Update prev\n vis_node* prev = node_list[curr->prev_idx];\n if(prev != nullptr){\n prev->next_idx = curr->next_idx;\n prev->area = effective_area(prev->pt_idx, prev->prev_idx, prev->next_idx);\n \/\/ For some reason, std::make_heap() is the fastest way to resort the heap. Probably needs testing.\n std::make_heap(heap.begin(), heap.end());\n }\n \/\/ Update next\n vis_node* next = node_list[curr->next_idx];\n if(next != nullptr){\n next->prev_idx = curr->prev_idx;\n next->area = effective_area(next->pt_idx, next->prev_idx, next->next_idx);\n std::make_heap(heap.begin(), heap.end());\n }\n areas[curr->pt_idx] = min_area;\n node_list[curr->pt_idx] = nullptr;\n delete curr;\n }\n \/\/ Clear node list and shrink_to_fit() (to free actual memory). Not necessary. Could be removed.\n node_list.clear();\n node_list.shrink_to_fit();\n \/\/ This lambda is how we test whether or not to keep a point.\n auto use_point = [areas, tolerance](const size_t& idx)->bool {\n assert(idx < areas.size());\n \/\/ Return true at front\/back of path\/areas\n if(idx == 0 || idx == areas.size() - 1){\n return true;\n }\n \/\/ Return true if area at idx is greater than minimum area to consider \"valid\"\n else{\n return areas[idx] > tolerance;\n }\n };\n \/\/ Use previously defined lambda to build results.\n for (size_t i = 0; i < pts.size(); ++i) {\n if (use_point(i)){\n results.push_back(pts[i]);\n }\n }\n \/\/ Check that results has at least two points\n assert(results.size() >= 2);\n \/\/ Return simplified vector of points\n return results;\n}\n\nvoid MultiPoint3::translate(double x, double y)\n{\n for (Vec3crd &p : points) {\n p(0) += coord_t(x);\n p(1) += coord_t(y);\n }\n}\n\nvoid MultiPoint3::translate(const Point& vector)\n{\n this->translate(vector(0), vector(1));\n}\n\ndouble MultiPoint3::length() const\n{\n double len = 0.0;\n for (const Line3& line : this->lines())\n len += line.length();\n return len;\n}\n\nBoundingBox3 MultiPoint3::bounding_box() const\n{\n return BoundingBox3(points);\n}\n\nbool MultiPoint3::remove_duplicate_points()\n{\n size_t j = 0;\n for (size_t i = 1; i < points.size(); ++i) {\n if (points[j] == points[i]) {\n \/\/ Just increase index i.\n } else {\n ++ j;\n if (j < i)\n points[j] = points[i];\n }\n }\n\n if (++j < points.size())\n {\n points.erase(points.begin() + j, points.end());\n return true;\n }\n\n return false;\n}\n\nBoundingBox get_extents(const MultiPoint &mp)\n{ \n return BoundingBox(mp.points);\n}\n\nBoundingBox get_extents_rotated(const Points &points, double angle)\n{ \n BoundingBox bbox;\n if (! points.empty()) {\n double s = sin(angle);\n double c = cos(angle);\n Points::const_iterator it = points.begin();\n double cur_x = (double)(*it)(0);\n double cur_y = (double)(*it)(1);\n bbox.min(0) = bbox.max(0) = (coord_t)round(c * cur_x - s * cur_y);\n bbox.min(1) = bbox.max(1) = (coord_t)round(c * cur_y + s * cur_x);\n for (++it; it != points.end(); ++it) {\n double cur_x = (double)(*it)(0);\n double cur_y = (double)(*it)(1);\n coord_t x = (coord_t)round(c * cur_x - s * cur_y);\n coord_t y = (coord_t)round(c * cur_y + s * cur_x);\n bbox.min(0) = std::min(x, bbox.min(0));\n bbox.min(1) = std::min(y, bbox.min(1));\n bbox.max(0) = std::max(x, bbox.max(0));\n bbox.max(1) = std::max(y, bbox.max(1));\n }\n bbox.defined = true;\n }\n return bbox;\n}\n\nBoundingBox get_extents_rotated(const MultiPoint &mp, double angle)\n{\n return get_extents_rotated(mp.points, angle);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n#include \"luanode.h\"\r\n#include \"luanode_net.h\"\r\n#include \"luanode_net_acceptor.h\"\r\n#include \"blogger.h\"\r\n\r\n#include <boost\/asio\/placeholders.hpp>\r\n#include <boost\/make_shared.hpp>\r\n\r\n#include <boost\/bind.hpp>\r\n\r\nusing namespace LuaNode::Net;\r\n\r\nstatic unsigned long s_nextAcceptorId = 0;\r\nstatic unsigned long s_acceptorCount = 0;\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nvoid LuaNode::Net::Acceptor::RegisterFunctions(lua_State* L) {}\r\n\r\n\r\nconst char* Acceptor::className = \"Acceptor\";\r\nconst Acceptor::RegType Acceptor::methods[] = {\r\n\t{\"open\", &Acceptor::Open},\r\n\t{\"close\", &Acceptor::Close},\r\n\t{\"setoption\", &Acceptor::SetOption},\r\n\t{\"getsockname\", &Acceptor::GetLocalAddress},\r\n\t{\"bind\", &Acceptor::Bind},\r\n\t{\"listen\", &Acceptor::Listen},\r\n\t{\"accept\", &Acceptor::Accept},\r\n\t{0}\r\n};\r\n\r\nconst Acceptor::RegType Acceptor::setters[] = {\r\n\t{0}\r\n};\r\n\r\nconst Acceptor::RegType Acceptor::getters[] = {\r\n\t{0}\r\n};\r\n\r\nAcceptor::Acceptor(lua_State* L) : \r\n\tm_L( LuaNode::GetLuaVM() ),\r\n\tm_acceptorId(++s_nextAcceptorId),\r\n\tm_acceptor( GetIoService() )\r\n{\r\n\ts_acceptorCount++;\r\n\tLogDebug(\"Constructing Acceptor (%p) (id:%u). Current acceptor count = %lu\", this, m_acceptorId, s_acceptorCount);\r\n}\r\n\r\nAcceptor::~Acceptor(void)\r\n{\r\n\ts_acceptorCount--;\r\n\tLogDebug(\"Destructing Acceptor (%p) (id:%u). Current acceptor count = %lu\", this, m_acceptorId, s_acceptorCount);\r\n\r\n\t\/\/ Close the acceptor if it was still open\r\n\tif(m_acceptor.is_open()) {\r\n\t\tboost::system::error_code ec;\r\n\t\tm_acceptor.close(ec);\r\n\t\tif(ec) {\r\n\t\t\tLogError(\"Error closing acceptor (%p) (id:%u) - %s\", this, m_acceptorId, ec.message().c_str());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\n\/*static*\/ int Acceptor::tostring_T(lua_State* L) {\r\n\tuserdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1));\r\n\tAcceptor* obj = ud->pT;\r\n\tlua_pushfstring(L, \"%s (%p) (id:%d)\", className, obj, obj->m_acceptorId);\r\n\treturn 1;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ Open the acceptor using the specified protocol\r\nint Acceptor::Open(lua_State* L) {\r\n\tconst char* kind = luaL_checkstring(L, 2);\r\n\tLogDebug(\"Acceptor::Open (%p) (id:%u) - %s\", this, m_acceptorId, kind);\r\n\r\n\tboost::system::error_code ec;\r\n\tif(strcmp(kind, \"tcp4\") == 0) {\r\n\t\tm_acceptor.open( boost::asio::ip::tcp::v4(), ec );\r\n\t}\r\n\telse if(strcmp(kind, \"tcp6\") == 0) {\r\n\t\tm_acceptor.open( boost::asio::ip::tcp::v6(), ec );\r\n\t}\r\n\telse {\r\n\t\tlua_pushnil(L);\r\n\t\tlua_pushfstring(L, \"unknown protocol %s\", kind);\r\n#if defined(WSAEPROTONOSUPPORT)\r\n\t\tlua_pushinteger(L, WSAEPROTONOSUPPORT);\r\n#else\r\n\t\tlua_pushinteger(L, EPROTONOSUPPORT);\r\n#endif\r\n\t\treturn 3;\r\n\t}\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Close(lua_State* L) {\r\n\tLogDebug(\"Acceptor::Close (%p) (id:%u)\", this, m_acceptorId);\r\n\tboost::system::error_code ec;\r\n\tm_acceptor.close(ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::SetOption(lua_State* L) {\r\n\tconst char* option = luaL_checkstring(L, 2);\r\n\tLogDebug(\"Acceptor::SetOption (%p) (id:%u) - %s\", this, m_acceptorId, option);\r\n\r\n\tboost::system::error_code ec;\r\n\r\n\tif(strcmp(option, \"reuseaddr\") == 0) {\r\n\t\tbool value = lua_toboolean(L, 3) != 0;\r\n\t\tm_acceptor.set_option( boost::asio::socket_base::reuse_address(value), ec );\r\n\t}\r\n\telse {\r\n\t\tec = boost::asio::error::invalid_argument;\r\n\t}\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::GetLocalAddress(lua_State* L) {\r\n\tboost::system::error_code ec;\r\n\tconst boost::asio::ip::tcp::endpoint& endpoint = m_acceptor.local_endpoint(ec);\r\n\r\n\tif(!ec) {\r\n\t\tlua_pushstring(L, endpoint.address().to_string().c_str());\r\n\t\tlua_pushinteger(L, endpoint.port());\r\n\t\treturn 2;\r\n\t}\r\n\treturn luaL_error(L, \"Acceptor::GetLocalAddress - %s:%d\", ec.message().c_str(), ec.value());\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Bind(lua_State* L) {\r\n\tconst char* ip = luaL_checkstring(L, 2);\r\n\tunsigned short port = luaL_checkinteger(L, 3);\r\n\r\n\tLogDebug(\"Acceptor::Bind (%p) (id:%u) - (%s,%hu)\", this, m_acceptorId, ip, port);\r\n\r\n\tboost::system::error_code ec;\r\n\tboost::asio::ip::address address = boost::asio::ip::address::from_string(ip, ec);\r\n\tif(ec) {\r\n\t\treturn BoostErrorCodeToLua(L, ec);\r\n\t}\r\n\r\n\tboost::asio::ip::tcp::endpoint endpoint( address, port );\r\n\tm_acceptor.bind(endpoint, ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Listen(lua_State* L) {\r\n\tint backlog = luaL_optinteger(L, 2, boost::asio::socket_base::max_connections);\r\n\tLogDebug(\"Acceptor::Listen (%p) (id:%u) - backlog = %d\", this, m_acceptorId, backlog);\r\n\r\n\tboost::system::error_code ec;\r\n\tm_acceptor.listen(backlog, ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Accept(lua_State* L) {\r\n\tLogDebug(\"Acceptor::Accept (%p) (id:%u)\", this, m_acceptorId);\r\n\r\n\tboost::shared_ptr<boost::asio::ip::tcp::socket> socket = boost::make_shared<boost::asio::ip::tcp::socket>( boost::ref(GetIoService()) );\r\n\r\n\t\/\/ store a reference in the registry\r\n\tlua_pushvalue(L, 1);\r\n\tint reference = luaL_ref(L, LUA_REGISTRYINDEX);\r\n\r\n\tm_acceptor.async_accept(\r\n\t\t*socket,\r\n\t\tboost::bind(&Acceptor::HandleAccept, this, reference, socket, boost::asio::placeholders::error)\r\n\t);\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nvoid Acceptor::HandleAccept(int reference, boost::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code& error) {\r\n\tLogDebug(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p)\", this, m_acceptorId, socket.get());\r\n\tlua_State* L = LuaNode::GetLuaVM();\r\n\tlua_rawgeti(L, LUA_REGISTRYINDEX, reference);\r\n\tluaL_unref(L, LUA_REGISTRYINDEX, reference);\r\n\r\n\tlua_getfield(L, 1, \"callback\");\r\n\tassert(lua_type(L, -1) == LUA_TFUNCTION); \/\/An acceptor must have a callback\"\r\n\r\n\tif(!error) {\r\n\t\tboost::asio::ip::address address = socket->remote_endpoint().address();\r\n\t\t\r\n\t\tlua_pushnil(L);\r\n\t\tlua_newtable(L);\r\n\t\tint peer = lua_gettop(L);\r\n\r\n\t\tlua_pushstring(L, \"socket\");\r\n\t\tSocket* luasocket = new Socket(L, socket);\r\n\t\tSocket::push(L, luasocket, true);\t\/\/ now Socket is the owner\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tconst std::string& sAddress = address.to_string();\r\n\t\tlua_pushstring(L, \"address\");\r\n\t\tlua_pushlstring(L, sAddress.c_str(), sAddress.length());\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tlua_pushstring(L, \"port\");\r\n\t\tlua_pushnumber(L, socket->remote_endpoint().port());\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tLuaNode::GetLuaVM().call(2, LUA_MULTRET);\r\n\t}\r\n\telse {\r\n\t\tif(error != boost::asio::error::operation_aborted) {\r\n\t\t\tLogError(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - %s\", this, m_acceptorId, socket.get(), error.message().c_str());\r\n\t\t}\r\n\r\n\t\tint ret = BoostErrorToCallback(L, error);\r\n\t\tLuaNode::GetLuaVM().call(ret, LUA_MULTRET);\r\n\t}\r\n\tlua_settop(L, 0);\r\n}\r\n<commit_msg>Deal with errors in socket.remote_endpoint<commit_after>#include \"stdafx.h\"\r\n#include \"luanode.h\"\r\n#include \"luanode_net.h\"\r\n#include \"luanode_net_acceptor.h\"\r\n#include \"blogger.h\"\r\n\r\n#include <boost\/asio\/placeholders.hpp>\r\n#include <boost\/make_shared.hpp>\r\n\r\n#include <boost\/bind.hpp>\r\n\r\nusing namespace LuaNode::Net;\r\n\r\nstatic unsigned long s_nextAcceptorId = 0;\r\nstatic unsigned long s_acceptorCount = 0;\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nvoid LuaNode::Net::Acceptor::RegisterFunctions(lua_State* L) {}\r\n\r\n\r\nconst char* Acceptor::className = \"Acceptor\";\r\nconst Acceptor::RegType Acceptor::methods[] = {\r\n\t{\"open\", &Acceptor::Open},\r\n\t{\"close\", &Acceptor::Close},\r\n\t{\"setoption\", &Acceptor::SetOption},\r\n\t{\"getsockname\", &Acceptor::GetLocalAddress},\r\n\t{\"bind\", &Acceptor::Bind},\r\n\t{\"listen\", &Acceptor::Listen},\r\n\t{\"accept\", &Acceptor::Accept},\r\n\t{0}\r\n};\r\n\r\nconst Acceptor::RegType Acceptor::setters[] = {\r\n\t{0}\r\n};\r\n\r\nconst Acceptor::RegType Acceptor::getters[] = {\r\n\t{0}\r\n};\r\n\r\nAcceptor::Acceptor(lua_State* L) : \r\n\tm_L( LuaNode::GetLuaVM() ),\r\n\tm_acceptorId(++s_nextAcceptorId),\r\n\tm_acceptor( GetIoService() )\r\n{\r\n\ts_acceptorCount++;\r\n\tLogDebug(\"Constructing Acceptor (%p) (id:%u). Current acceptor count = %lu\", this, m_acceptorId, s_acceptorCount);\r\n}\r\n\r\nAcceptor::~Acceptor(void)\r\n{\r\n\ts_acceptorCount--;\r\n\tLogDebug(\"Destructing Acceptor (%p) (id:%u). Current acceptor count = %lu\", this, m_acceptorId, s_acceptorCount);\r\n\r\n\t\/\/ Close the acceptor if it was still open\r\n\tif(m_acceptor.is_open()) {\r\n\t\tboost::system::error_code ec;\r\n\t\tm_acceptor.close(ec);\r\n\t\tif(ec) {\r\n\t\t\tLogError(\"Error closing acceptor (%p) (id:%u) - %s\", this, m_acceptorId, ec.message().c_str());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\n\/*static*\/ int Acceptor::tostring_T(lua_State* L) {\r\n\tuserdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1));\r\n\tAcceptor* obj = ud->pT;\r\n\tlua_pushfstring(L, \"%s (%p) (id:%d)\", className, obj, obj->m_acceptorId);\r\n\treturn 1;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ Open the acceptor using the specified protocol\r\nint Acceptor::Open(lua_State* L) {\r\n\tconst char* kind = luaL_checkstring(L, 2);\r\n\tLogDebug(\"Acceptor::Open (%p) (id:%u) - %s\", this, m_acceptorId, kind);\r\n\r\n\tboost::system::error_code ec;\r\n\tif(strcmp(kind, \"tcp4\") == 0) {\r\n\t\tm_acceptor.open( boost::asio::ip::tcp::v4(), ec );\r\n\t}\r\n\telse if(strcmp(kind, \"tcp6\") == 0) {\r\n\t\tm_acceptor.open( boost::asio::ip::tcp::v6(), ec );\r\n\t}\r\n\telse {\r\n\t\tlua_pushnil(L);\r\n\t\tlua_pushfstring(L, \"unknown protocol %s\", kind);\r\n#if defined(WSAEPROTONOSUPPORT)\r\n\t\tlua_pushinteger(L, WSAEPROTONOSUPPORT);\r\n#else\r\n\t\tlua_pushinteger(L, EPROTONOSUPPORT);\r\n#endif\r\n\t\treturn 3;\r\n\t}\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Close(lua_State* L) {\r\n\tLogDebug(\"Acceptor::Close (%p) (id:%u)\", this, m_acceptorId);\r\n\tboost::system::error_code ec;\r\n\tm_acceptor.close(ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::SetOption(lua_State* L) {\r\n\tconst char* option = luaL_checkstring(L, 2);\r\n\tLogDebug(\"Acceptor::SetOption (%p) (id:%u) - %s\", this, m_acceptorId, option);\r\n\r\n\tboost::system::error_code ec;\r\n\r\n\tif(strcmp(option, \"reuseaddr\") == 0) {\r\n\t\tbool value = lua_toboolean(L, 3) != 0;\r\n\t\tm_acceptor.set_option( boost::asio::socket_base::reuse_address(value), ec );\r\n\t}\r\n\telse {\r\n\t\tec = boost::asio::error::invalid_argument;\r\n\t}\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::GetLocalAddress(lua_State* L) {\r\n\tboost::system::error_code ec;\r\n\tconst boost::asio::ip::tcp::endpoint& endpoint = m_acceptor.local_endpoint(ec);\r\n\r\n\tif(!ec) {\r\n\t\tlua_pushstring(L, endpoint.address().to_string().c_str());\r\n\t\tlua_pushinteger(L, endpoint.port());\r\n\t\treturn 2;\r\n\t}\r\n\treturn luaL_error(L, \"Acceptor::GetLocalAddress - %s:%d\", ec.message().c_str(), ec.value());\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Bind(lua_State* L) {\r\n\tconst char* ip = luaL_checkstring(L, 2);\r\n\tunsigned short port = luaL_checkinteger(L, 3);\r\n\r\n\tLogDebug(\"Acceptor::Bind (%p) (id:%u) - (%s,%hu)\", this, m_acceptorId, ip, port);\r\n\r\n\tboost::system::error_code ec;\r\n\tboost::asio::ip::address address = boost::asio::ip::address::from_string(ip, ec);\r\n\tif(ec) {\r\n\t\treturn BoostErrorCodeToLua(L, ec);\r\n\t}\r\n\r\n\tboost::asio::ip::tcp::endpoint endpoint( address, port );\r\n\tm_acceptor.bind(endpoint, ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Listen(lua_State* L) {\r\n\tint backlog = luaL_optinteger(L, 2, boost::asio::socket_base::max_connections);\r\n\tLogDebug(\"Acceptor::Listen (%p) (id:%u) - backlog = %d\", this, m_acceptorId, backlog);\r\n\r\n\tboost::system::error_code ec;\r\n\tm_acceptor.listen(backlog, ec);\r\n\treturn BoostErrorCodeToLua(L, ec);\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nint Acceptor::Accept(lua_State* L) {\r\n\tLogDebug(\"Acceptor::Accept (%p) (id:%u)\", this, m_acceptorId);\r\n\r\n\tboost::shared_ptr<boost::asio::ip::tcp::socket> socket = boost::make_shared<boost::asio::ip::tcp::socket>( boost::ref(GetIoService()) );\r\n\r\n\t\/\/ store a reference in the registry\r\n\tlua_pushvalue(L, 1);\r\n\tint reference = luaL_ref(L, LUA_REGISTRYINDEX);\r\n\r\n\tm_acceptor.async_accept(\r\n\t\t*socket,\r\n\t\tboost::bind(&Acceptor::HandleAccept, this, reference, socket, boost::asio::placeholders::error)\r\n\t);\r\n\treturn 0;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ \r\nvoid Acceptor::HandleAccept(int reference, boost::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code& error) {\r\n\tLogDebug(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p)\", this, m_acceptorId, socket.get());\r\n\tlua_State* L = LuaNode::GetLuaVM();\r\n\tlua_rawgeti(L, LUA_REGISTRYINDEX, reference);\r\n\tluaL_unref(L, LUA_REGISTRYINDEX, reference);\r\n\r\n\tlua_getfield(L, 1, \"callback\");\r\n\tassert(lua_type(L, -1) == LUA_TFUNCTION); \/\/An acceptor must have a callback\"\r\n\r\n\tif(!error) {\r\n\t\t\/\/ Get the remote endpoint, dealing with the case the connection is already closed when we get here.\r\n\t\tboost::system::error_code ec;\r\n\t\tconst boost::asio::ip::tcp::endpoint& endpoint = socket->remote_endpoint(ec);\r\n\t\tif(ec) {\r\n\t\t\tif(ec == boost::asio::error::not_connected) {\r\n\t\t\t\tLogWarning(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - Socket was already closed when accepted. %s\", \r\n\t\t\t\t\tthis, m_acceptorId, socket.get(), ec.message().c_str());\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tLogWarning(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - Error retrieving remote endpoint. %s\", \r\n\t\t\t\t\tthis, m_acceptorId, socket.get(), ec.message().c_str());\r\n\t\t\t}\r\n\t\t\t\/\/ TODO: Should I call the callback, even when the connection is already closed and there's nothing to be done?\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tboost::asio::ip::address address = endpoint.address();\r\n\t\t\r\n\t\tlua_pushnil(L);\r\n\t\tlua_newtable(L);\r\n\t\tint peer = lua_gettop(L);\r\n\r\n\t\tlua_pushstring(L, \"socket\");\r\n\t\tSocket* luasocket = new Socket(L, socket);\r\n\t\tSocket::push(L, luasocket, true);\t\/\/ now Socket is the owner\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tconst std::string& sAddress = address.to_string();\r\n\t\tlua_pushstring(L, \"address\");\r\n\t\tlua_pushlstring(L, sAddress.c_str(), sAddress.length());\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tlua_pushstring(L, \"port\");\r\n\t\tlua_pushnumber(L, endpoint.port());\r\n\t\tlua_rawset(L, peer);\r\n\r\n\t\tLuaNode::GetLuaVM().call(2, LUA_MULTRET);\r\n\t}\r\n\telse {\r\n\t\tif(error != boost::asio::error::operation_aborted) {\r\n\t\t\tLogError(\"Acceptor::HandleAccept (%p) (id:%u) (new socket %p) - %s\", this, m_acceptorId, socket.get(), error.message().c_str());\r\n\t\t}\r\n\r\n\t\tint ret = BoostErrorToCallback(L, error);\r\n\t\tLuaNode::GetLuaVM().call(ret, LUA_MULTRET);\r\n\t}\r\n\tlua_settop(L, 0);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef LUNAR_SLAB_ALLOCATOR\n#define LUNAR_SLAB_ALLOCATOR\n\n#include <new>\n#include <limits>\n\n#include <stdlib.h>\n\n#include \"slab.hpp\"\n\nnamespace lunar {\n\ntemplate <typename T>\nclass slab_allocator {\npublic:\n typedef T value_type;\n typedef size_t size_type;\n typedef ptrdiff_t difference_type;\n typedef T* pointer;\n typedef const T* const_pointer;\n typedef T& reference;\n typedef const T& const_reference;\n\n template <class U> struct rebind { typedef slab_allocator<U> other; };\n slab_allocator() throw() { slab_init(&m_slab, sizeof(T)); }\n slab_allocator(const slab_allocator&) throw() { slab_init(&m_slab, sizeof(T)); }\n\n template <class U> slab_allocator(const slab_allocator<U>&) throw(){ slab_init(&m_slab, sizeof(T)); }\n\n ~slab_allocator() throw() { slab_destroy(&m_slab); }\n\n pointer address(reference x) const { return &x; }\n const_pointer address(const_reference x) const { return &x; }\n\n pointer allocate(size_type s, void const * = 0) {\n if (s == 1) {\n return (pointer)slab_alloc(&m_slab);\n } else if (s >= 1) {\n pointer temp = (pointer)malloc(sizeof(void*) + s * sizeof(T));\n if (temp == nullptr)\n return nullptr;\n\n void **vp = (void**)temp;\n *vp = (void*)~(uint64_t)0;\n\n return (pointer)((char*)temp + sizeof(void*));\n } else {\n return nullptr;\n }\n }\n\n void deallocate(pointer p, size_type) {\n void **vp = (void**)((char*)p - sizeof(void*));\n\n if (*vp == (void*)~(uint64_t)0)\n free(vp);\n else\n slab_free(&m_slab, p);\n }\n\n size_type max_size() const throw() {\n return std::numeric_limits<size_t>::max() \/ sizeof(T);\n }\n\n void construct(pointer p, const T& val) {\n new((void *)p) T(val);\n }\n\n void destroy(pointer p) {\n p->~T();\n }\n\nprivate:\n slab_chain m_slab;\n};\n\n}\n\n#endif \/\/ LUNAR_SLAB_ALLOCATOR<commit_msg>use thread local storage<commit_after>#ifndef LUNAR_SLAB_ALLOCATOR\n#define LUNAR_SLAB_ALLOCATOR\n\n#include <new>\n#include <limits>\n\n#include <stdlib.h>\n\n#include \"slab.hpp\"\n\nnamespace lunar {\n\ntemplate <typename T>\nclass slab_allocator {\npublic:\n typedef T value_type;\n typedef size_t size_type;\n typedef ptrdiff_t difference_type;\n typedef T* pointer;\n typedef const T* const_pointer;\n typedef T& reference;\n typedef const T& const_reference;\n\n template <class U> struct rebind { typedef slab_allocator<U> other; };\n slab_allocator() throw()\n {\n if (! slab_allocator<T>::m_is_init) {\n slab_init(&m_slab, sizeof(T));\n slab_allocator<T>::m_is_init = true;\n }\n }\n slab_allocator(const slab_allocator&) throw()\n {\n if (! slab_allocator<T>::m_is_init) {\n slab_init(&m_slab, sizeof(T));\n slab_allocator<T>::m_is_init = true;\n }\n }\n\n template <class U> slab_allocator(const slab_allocator<U>&) throw()\n {\n if (! slab_allocator<U>::m_is_init) {\n slab_init(&slab_allocator<U>::m_slab, sizeof(U));\n slab_allocator<U>::m_is_init = true;\n }\n }\n\n ~slab_allocator() throw() { slab_destroy(&m_slab); }\n\n pointer address(reference x) const { return &x; }\n const_pointer address(const_reference x) const { return &x; }\n\n pointer allocate(size_type s, void const * = 0) {\n if (s == 1) {\n return (pointer)slab_alloc(&m_slab);\n } else if (s >= 1) {\n pointer temp = (pointer)malloc(sizeof(void*) + s * sizeof(T));\n if (temp == nullptr)\n return nullptr;\n\n void **vp = (void**)temp;\n *vp = (void*)~(uint64_t)0;\n\n return (pointer)((char*)temp + sizeof(void*));\n } else {\n return nullptr;\n }\n }\n\n void deallocate(pointer p, size_type) {\n void **vp = (void**)((char*)p - sizeof(void*));\n\n if (*vp == (void*)~(uint64_t)0)\n free(vp);\n else\n slab_free(&m_slab, p);\n }\n\n size_type max_size() const throw() {\n return std::numeric_limits<size_t>::max() \/ sizeof(T);\n }\n\n void construct(pointer p, const T& val) {\n new((void *)p) T(val);\n }\n\n void destroy(pointer p) {\n p->~T();\n }\n\nprivate:\n __thread static bool m_is_init;\n __thread static slab_chain m_slab;\n};\n\ntemplate <typename T> __thread bool slab_allocator<T>::m_is_init = false;\ntemplate <typename T> __thread slab_chain slab_allocator<T>::m_slab;\n\n}\n\n#endif \/\/ LUNAR_SLAB_ALLOCATOR<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"BOSSAssert.h\"\n#include \"Common.h\"\n#include <algorithm>\n\nnamespace BOSS\n{\ntemplate <class T,size_t max_capacity>\nclass Vec\n{\n size_t\t_size;\n size_t _capacity;\n T\t\t_arr[max_capacity];\n\npublic:\n\n Vec<T,max_capacity>()\n : _size(0)\n ,_capacity(max_capacity)\n {\n }\n\n Vec<T,max_capacity>(const size_t & size)\n : _size(size)\n ,_capacity(max_capacity)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec initializing with size > capacity, Size = %d, Capacity = %d\",size,_capacity);\n }\n\n Vec<T,max_capacity>(const size_t & size,const T & val)\n : _size(size)\n ,_capacity(max_capacity)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec initializing with size > capacity, Size = %d, Capacity = %d\",size,_capacity);\n fill(val);\n }\n \n void resize(const size_t & size)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec resizing with size > capacity, Size = %d, Cpacity = %d\",size,_capacity);\n _size = size;\n }\n\n T & get(const size_t & index)\n {\n BOSS_ASSERT(index < size(),\"Vec out of bounds exception, Size = %d, Index = %d\",size(),index);\n return _arr[index];\n }\n\n const T & get(const size_t & index) const\n {\n BOSS_ASSERT(index < size(),\"Vec out of bounds exception, Size = %d, Index = %d\",size(),index);\n return _arr[index];\n }\n\n T & operator [] (const size_t & index)\n {\n return get(index);\n }\n\n const T & operator [] (const size_t & index) const\n {\n return get(index);\n }\n\n const bool contains(const T & e) const\n {\n for (size_t i(0); i<size(); ++i)\n {\n if (get(i) == e)\n {\n return true;\n }\n }\n\n return false;\n }\n\n void addSorted(const T & e)\n {\n size_t index(0);\n while (_arr[index] < e)\n {\n ++index;\n }\n \n addAtIndex(e, index);\n }\n\n void addAtIndex(const T & e, const size_t & index)\n {\n BOSS_ASSERT(index <= size(), \"Can't add at index: Index = %d, Size = %d\", index, size());\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Size = %d\",capacity());\n\n copyShiftRight(index);\n _arr[index] = e;\n }\n\n void copyShiftRight(const size_t & index)\n {\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Size = %d\",capacity());\n for (size_t i(_size + 1); i > index; --i)\n {\n _arr[i] = _arr[i-1];\n }\n\n _size++;\n }\n\n void copyShiftLeft(const size_t & index)\n {\n BOSS_ASSERT(size() > 0, \"Can't shift left when empty\");\n for (size_t i(index); i < size()-1; ++i)\n {\n _arr[i] = _arr[i+1];\n }\n\n _size--;\n }\n \n const size_t & capacity() const\n {\n return _capacity;\n }\n\n void push_back(const T & e)\n {\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Size = %d\",capacity());\n _arr[_size] = e;\n ++_size;\n }\n\n const T & back() const\n {\n BOSS_ASSERT(!empty(),\"Vector back() with empty array\");\n\n return get(_size);\n }\n\n void remove(const size_t & index)\n {\n remove_by_swap(index);\n }\n\n void removeByShift(const size_t & index)\n {\n copyShiftLeft(index);\n }\n\n void remove_by_swap(const size_t & index)\n {\n BOSS_ASSERT(index < size(),\"Vector out of bounds exception, Size = %d, Index = %d\",size(),index);\n\n std::swap(_arr[index],_arr[size()-1]);\n pop_back();\n }\n\n void pop_back()\n {\n BOSS_ASSERT(!empty(),\"Vector pop_back() with empty array\");\n\n _size--;\n }\n\n void sort()\n {\n std::sort(_arr, _arr + _size);\n }\n\n const bool empty() const\n {\n return size() == 0;\n }\n\n void clear()\n {\n _size = 0;\n }\n\n const size_t & size() const\n {\n return _size;\n }\n\n inline void fill(const T & val)\n {\n std::fill(_arr,_arr + _size,val);\n }\n\n class iterator\n {\n T * _ptr;\n public:\n iterator(T * ptr) : _ptr(ptr) { }\n iterator operator ++ () { iterator i = *this; _ptr++; return i; }\n iterator operator ++ (int junk) { _ptr++; return *this; }\n T & operator * () { return *_ptr; }\n T * operator -> () { return _ptr; }\n bool operator == (const iterator & rhs) { return _ptr == rhs._ptr; }\n bool operator != (const iterator & rhs) { return _ptr != rhs._ptr; }\n };\n \n class const_iterator\n {\n T * _ptr;\n public:\n const_iterator(T * ptr) : _ptr(ptr) { }\n const_iterator operator ++ () { const_iterator i = *this; _ptr++; return i; }\n const_iterator operator ++ (int junk) { _ptr++; return *this; }\n const T & operator * () { return *_ptr; }\n const T * operator -> () { return _ptr; }\n bool operator == (const const_iterator & rhs) { return _ptr == rhs._ptr; }\n bool operator != (const const_iterator & rhs) { return _ptr != rhs._ptr; }\n };\n \n iterator begin()\n {\n return iterator(_arr);\n }\n\n iterator end()\n {\n return iterator(_arr + size());\n }\n\n};\n\n}<commit_msg>Extra log to track down crash against XIMP<commit_after>#pragma once\n#include \"BOSSAssert.h\"\n#include \"Common.h\"\n#include <algorithm>\n\nnamespace BOSS\n{\ntemplate <class T,size_t max_capacity>\nclass Vec\n{\n size_t\t_size;\n size_t _capacity;\n T\t\t_arr[max_capacity];\n\npublic:\n\n Vec<T,max_capacity>()\n : _size(0)\n ,_capacity(max_capacity)\n {\n\t\tBOSS_ASSERT(max_capacity>0, \"Vec initializing with capacity = 0\");\n }\n\n Vec<T,max_capacity>(const size_t & size)\n : _size(size)\n ,_capacity(max_capacity)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec initializing with size > capacity, Size = %d, Capacity = %d\",size,_capacity);\n }\n\n Vec<T,max_capacity>(const size_t & size,const T & val)\n : _size(size)\n ,_capacity(max_capacity)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec initializing with size > capacity, Size = %d, Capacity = %d\",size,_capacity);\n fill(val);\n }\n \n void resize(const size_t & size)\n {\n BOSS_ASSERT(size <= max_capacity,\"Vec resizing with size > capacity, Size = %d, Cpacity = %d\",size,_capacity);\n _size = size;\n }\n\n T & get(const size_t & index)\n {\n BOSS_ASSERT(index < size(),\"Vec out of bounds exception, Size = %d, Index = %d\",size(),index);\n return _arr[index];\n }\n\n const T & get(const size_t & index) const\n {\n BOSS_ASSERT(index < size(),\"Vec out of bounds exception, Size = %d, Index = %d\",size(),index);\n return _arr[index];\n }\n\n T & operator [] (const size_t & index)\n {\n return get(index);\n }\n\n const T & operator [] (const size_t & index) const\n {\n return get(index);\n }\n\n const bool contains(const T & e) const\n {\n for (size_t i(0); i<size(); ++i)\n {\n if (get(i) == e)\n {\n return true;\n }\n }\n\n return false;\n }\n\n void addSorted(const T & e)\n {\n size_t index(0);\n while (_arr[index] < e)\n {\n ++index;\n }\n \n addAtIndex(e, index);\n }\n\n void addAtIndex(const T & e, const size_t & index)\n {\n BOSS_ASSERT(index <= size(), \"Can't add at index: Index = %d, Size = %d\", index, size());\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Size = %d\",capacity());\n\n copyShiftRight(index);\n _arr[index] = e;\n }\n\n void copyShiftRight(const size_t & index)\n {\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Size = %d\",capacity());\n for (size_t i(_size + 1); i > index; --i)\n {\n _arr[i] = _arr[i-1];\n }\n\n _size++;\n }\n\n void copyShiftLeft(const size_t & index)\n {\n BOSS_ASSERT(size() > 0, \"Can't shift left when empty\");\n for (size_t i(index); i < size()-1; ++i)\n {\n _arr[i] = _arr[i+1];\n }\n\n _size--;\n }\n \n const size_t & capacity() const\n {\n return _capacity;\n }\n\n void push_back(const T & e)\n {\n BOSS_ASSERT(_size < capacity(),\"Array over capacity: Capacity = %d, Size = %d\",capacity(), _size);\n _arr[_size] = e;\n ++_size;\n }\n\n const T & back() const\n {\n BOSS_ASSERT(!empty(),\"Vector back() with empty array\");\n\n return get(_size);\n }\n\n void remove(const size_t & index)\n {\n remove_by_swap(index);\n }\n\n void removeByShift(const size_t & index)\n {\n copyShiftLeft(index);\n }\n\n void remove_by_swap(const size_t & index)\n {\n BOSS_ASSERT(index < size(),\"Vector out of bounds exception, Size = %d, Index = %d\",size(),index);\n\n std::swap(_arr[index],_arr[size()-1]);\n pop_back();\n }\n\n void pop_back()\n {\n BOSS_ASSERT(!empty(),\"Vector pop_back() with empty array\");\n\n _size--;\n }\n\n void sort()\n {\n std::sort(_arr, _arr + _size);\n }\n\n const bool empty() const\n {\n return size() == 0;\n }\n\n void clear()\n {\n _size = 0;\n }\n\n const size_t & size() const\n {\n return _size;\n }\n\n inline void fill(const T & val)\n {\n std::fill(_arr,_arr + _size,val);\n }\n\n class iterator\n {\n T * _ptr;\n public:\n iterator(T * ptr) : _ptr(ptr) { }\n iterator operator ++ () { iterator i = *this; _ptr++; return i; }\n iterator operator ++ (int junk) { _ptr++; return *this; }\n T & operator * () { return *_ptr; }\n T * operator -> () { return _ptr; }\n bool operator == (const iterator & rhs) { return _ptr == rhs._ptr; }\n bool operator != (const iterator & rhs) { return _ptr != rhs._ptr; }\n };\n \n class const_iterator\n {\n T * _ptr;\n public:\n const_iterator(T * ptr) : _ptr(ptr) { }\n const_iterator operator ++ () { const_iterator i = *this; _ptr++; return i; }\n const_iterator operator ++ (int junk) { _ptr++; return *this; }\n const T & operator * () { return *_ptr; }\n const T * operator -> () { return _ptr; }\n bool operator == (const const_iterator & rhs) { return _ptr == rhs._ptr; }\n bool operator != (const const_iterator & rhs) { return _ptr != rhs._ptr; }\n };\n \n iterator begin()\n {\n return iterator(_arr);\n }\n\n iterator end()\n {\n return iterator(_arr + size());\n }\n\n};\n\n}<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2016 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n#include \"CommentedNode.h\"\n\n#include \"ModelBase\/src\/nodes\/composite\/CompositeNode.h\"\n\n#include \"ReviewComment.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedList.hpp\"\n\ntemplate class Model::TypedList<CodeReview::CommentedNode>;\n\nnamespace CodeReview\n{\nDEFINE_COMPOSITE_EMPTY_CONSTRUCTORS(CommentedNode)\nDEFINE_COMPOSITE_TYPE_REGISTRATION_METHODS(CommentedNode)\n\nDEFINE_ATTRIBUTE(CommentedNode, nodeId, Text, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, reviewComments, TypedListOfReviewComment, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, offsetX, Integer, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, offsetY, Integer, false, false, true)\n\nCommentedNode::CommentedNode(QString associatedNodeId, QPoint offset) : Super{nullptr, CommentedNode::getMetaData()}\n{\n\tsetNodeId(new Model::Text{associatedNodeId});\n\tauto offsetX = new Model::Integer{};\n\toffsetX->set(offset.x());\n\tsetOffsetX(offsetX);\n\tauto offsetY = new Model::Integer{};\n\toffsetY->set(offset.y());\n\tsetOffsetY(offsetY);\n}\n\n}\n<commit_msg>Remove instantiation of new Model::Integer for required attribute<commit_after>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2016 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n#include \"CommentedNode.h\"\n\n#include \"ModelBase\/src\/nodes\/composite\/CompositeNode.h\"\n\n#include \"ReviewComment.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedList.hpp\"\n\ntemplate class Model::TypedList<CodeReview::CommentedNode>;\n\nnamespace CodeReview\n{\nDEFINE_COMPOSITE_EMPTY_CONSTRUCTORS(CommentedNode)\nDEFINE_COMPOSITE_TYPE_REGISTRATION_METHODS(CommentedNode)\n\nDEFINE_ATTRIBUTE(CommentedNode, nodeId, Text, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, reviewComments, TypedListOfReviewComment, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, offsetX, Integer, false, false, true)\nDEFINE_ATTRIBUTE(CommentedNode, offsetY, Integer, false, false, true)\n\nCommentedNode::CommentedNode(QString associatedNodeId, QPoint offset) : Super{nullptr, CommentedNode::getMetaData()}\n{\n\tsetNodeId(new Model::Text{associatedNodeId});\n\toffsetX()->set(offset.x());\n\toffsetY()->set(offset.y());\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Theo Weidmann on 26.02.18.\n\/\/\n\n#include \"SemanticAnalyser.hpp\"\n#include \"Compiler.hpp\"\n#include \"DeinitializerBuilder.hpp\"\n#include \"FunctionAnalyser.hpp\"\n#include \"AST\/ASTExpr.hpp\"\n#include \"Scoping\/SemanticScoper.hpp\"\n#include \"Types\/TypeExpectation.hpp\"\n#include \"Package\/Package.hpp\"\n#include \"ThunkBuilder.hpp\"\n#include \"Types\/Class.hpp\"\n#include \"Types\/Protocol.hpp\"\n#include \"Types\/TypeDefinition.hpp\"\n#include \"Types\/ValueType.hpp\"\n\nnamespace EmojicodeCompiler {\n\nCompiler* SemanticAnalyser::compiler() const {\n return package_->compiler();\n}\n\nvoid SemanticAnalyser::analyse(bool executable) {\n for (auto &vt : package_->valueTypes()) {\n finalizeProtocols(Type(vt.get()));\n vt->analyseConstraints(TypeContext(Type(vt.get())));\n }\n for (auto &klass : package_->classes()) {\n klass->analyseSuperType();\n finalizeProtocols(Type(klass.get()));\n klass->analyseConstraints(TypeContext(Type(klass.get())));\n }\n\n package_->recreateClassTypes();\n\n \/\/ Now all types are ready to be used with compatibleTo\n\n for (auto &protocol : package_->protocols()) {\n protocol->eachFunction([this](Function *function) {\n analyseFunctionDeclaration(function);\n });\n }\n for (auto &vt : package_->valueTypes()) {\n checkProtocolConformance(Type(vt.get()));\n declareInstanceVariables(Type(vt.get()));\n buildDeinitializer(vt.get());\n buildCopyRetain(vt.get());\n enqueueFunction(vt->deinitializer());\n enqueueFunction(vt->copyRetain());\n enqueueFunctionsOfTypeDefinition(vt.get());\n }\n for (auto &klass : package_->classes()) {\n for (auto init : klass->initializerList()) {\n if (!init->required()) {\n continue;\n }\n klass->addTypeMethod(buildRequiredInitThunk(klass.get(), init));\n }\n \n klass->inherit(this);\n checkProtocolConformance(Type(klass.get()));\n\n buildDeinitializer(klass.get());\n enqueueFunction(klass->deinitializer());\n\n enqueueFunctionsOfTypeDefinition(klass.get());\n\n if (!klass->hasSubclass() && !klass->exported()) {\n klass->setFinal();\n }\n }\n for (auto &function : package_->functions()) {\n enqueueFunction(function.get());\n }\n\n analyseQueue();\n checkStartFlagFunction(executable);\n}\n\nvoid SemanticAnalyser::checkStartFlagFunction(bool executable) {\n if (package_->hasStartFlagFunction()) {\n auto returnType = package_->startFlagFunction()->returnType()->type();\n if (returnType.type() != TypeType::NoReturn &&\n !returnType.compatibleTo(Type(package_->compiler()->sInteger), TypeContext())) {\n package_->compiler()->error(CompilerError(package_->startFlagFunction()->position(),\n \"🏁 must either have no return or return 🔢.\"));\n }\n if (!executable) {\n package_->startFlagFunction()->makeExternal(); \/\/ Prevent function from being included in object file\n }\n }\n else if (executable) {\n compiler()->error(CompilerError(SourcePosition(), \"No 🏁 block was found.\"));\n }\n}\n\nvoid SemanticAnalyser::analyseQueue() {\n while (!queue_.empty()) {\n try {\n FunctionAnalyser(queue_.front(), this).analyse();\n }\n catch (CompilerError &ce) {\n package_->compiler()->error(ce);\n }\n queue_.pop();\n }\n}\n\nvoid SemanticAnalyser::enqueueFunctionsOfTypeDefinition(TypeDefinition *typeDef) {\n typeDef->eachFunction([this](Function *function) {\n enqueueFunction(function);\n });\n}\n\nvoid SemanticAnalyser::enqueueFunction(Function *function) {\n analyseFunctionDeclaration(function);\n if (!function->isExternal()) {\n queue_.emplace(function);\n }\n}\n\nvoid SemanticAnalyser::analyseFunctionDeclaration(Function *function) const {\n if (function->returnType() == nullptr) {\n function->setReturnType(std::make_unique<ASTLiteralType>(Type::noReturn()));\n }\n else if (function->returnType()->wasAnalysed()) {\n return;\n }\n\n auto context = function->typeContext();\n\n function->analyseConstraints(context);\n for (auto ¶m : function->parameters()) {\n param.type->analyseType(context);\n if (!function->externalName().empty() && param.type->type().type() == TypeType::ValueType &&\n !param.type->type().valueType()->isPrimitive()) {\n param.type->type().setReference();\n }\n }\n\n if (auto initializer = dynamic_cast<Initializer*>(function)) {\n if (initializer->errorProne() && initializer->errorType()->analyseType(context).type() != TypeType::Enum) {\n throw CompilerError(initializer->errorType()->position(), \"Error type must be a non-optional 🦃.\");\n }\n return;\n }\n function->returnType()->analyseType(context, true);\n}\n\nvoid SemanticAnalyser::declareInstanceVariables(const Type &type) {\n TypeDefinition *typeDef = type.typeDefinition();\n\n auto context = TypeContext(type);\n auto scoper = std::make_unique<SemanticScoper>();\n scoper->pushScope(); \/\/ For closure analysis\n ExpressionAnalyser analyser(this, context, package_, std::move(scoper));\n\n for (auto &var : typeDef->instanceVariables()) {\n typeDef->instanceScope().declareVariable(var.name, var.type->analyseType(context), false,\n var.position);\n\n if (var.expr != nullptr) {\n auto type = var.expr->analyse(&analyser, TypeExpectation(var.type->type()));\n if (!type.compatibleTo(var.type->type(), context)) {\n package_->compiler()->error(CompilerError(var.expr->position(),\n \"Cannot initialize instance variable of type \",\n var.type->type().toString(context), \" with value of type \",\n type.toString(context), \".\"));\n }\n }\n }\n\n if (!typeDef->instanceVariables().empty() && typeDef->initializerList().empty()) {\n package_->compiler()->warn(typeDef->position(), \"Type defines \", typeDef->instanceVariables().size(),\n \" instances variables but has no initializers.\");\n }\n}\n\nbool SemanticAnalyser::checkReturnPromise(const Function *sub, const TypeContext &subContext,\n const Function *super, const TypeContext &superContext,\n const Type &superSource) const {\n auto superReturn = super->returnType()->type().resolveOn(superContext);\n auto subReturn = sub->returnType()->type().resolveOn(subContext);\n if (!subReturn.compatibleTo(superReturn, subContext)) {\n auto supername = superReturn.toString(subContext);\n auto thisname = sub->returnType()->type().toString(subContext);\n package_->compiler()->error(CompilerError(sub->position(), \"Return type \",\n sub->returnType()->type().toString(subContext), \" of \",\n utf8(sub->name()),\n \" is not compatible to the return type defined in \",\n superSource.toString(subContext)));\n }\n return subReturn.storageType() == superReturn.storageType() && subReturn.isReference() == superReturn.isReference();\n}\n\nstd::unique_ptr<Function> SemanticAnalyser::enforcePromises(Function *sub, Function *super,\n const Type &superSource,\n const TypeContext &subContext,\n const TypeContext &superContext) {\n analyseFunctionDeclaration(sub);\n analyseFunctionDeclaration(super);\n if (super->final()) {\n package_->compiler()->error(CompilerError(sub->position(), superSource.toString(subContext),\n \"’s implementation of \", utf8(sub->name()), \" was marked 🔏.\"));\n }\n if (sub->accessLevel() == AccessLevel::Private || (sub->accessLevel() == AccessLevel::Protected &&\n super->accessLevel() == AccessLevel::Public)) {\n package_->compiler()->error(CompilerError(sub->position(), \"Overriding method must be as accessible or more \",\n \"accessible than the overridden method.\"));\n }\n\n bool isReturnOk = checkReturnPromise(sub, subContext, super, superContext, superSource);\n bool isParamsOk = checkArgumentPromise(sub, super, subContext, superContext) ;\n if (!isParamsOk || !isReturnOk) {\n return buildBoxingThunk(superContext, super, sub);\n }\n return nullptr;\n}\n\nbool SemanticAnalyser::checkArgumentPromise(const Function *sub, const Function *super, const TypeContext &subContext,\n const TypeContext &superContext) const {\n if (super->parameters().size() != sub->parameters().size()) {\n package_->compiler()->error(CompilerError(sub->position(), \"Parameter count does not match.\"));\n return true;\n }\n\n bool compatible = true;\n for (size_t i = 0; i < super->parameters().size(); i++) { \/\/ More general arguments are OK\n auto superArgumentType = super->parameters()[i].type->type().resolveOn(superContext);\n if (!superArgumentType.compatibleTo(sub->parameters()[i].type->type().resolveOn(subContext), subContext)) {\n auto supertype = superArgumentType.toString(subContext);\n auto thisname = sub->parameters()[i].type->type().toString(subContext);\n package_->compiler()->error(CompilerError(sub->position(), \"Type \", thisname, \" of argument \", i + 1,\n \" is not compatible with its \", thisname, \" argument type \",\n supertype, \".\"));\n }\n if (sub->parameters()[i].type->type().resolveOn(subContext).storageType() != superArgumentType.storageType()) {\n compatible = false; \/\/ Boxing Thunk required for parameter i\n }\n }\n return compatible;\n}\n\nvoid SemanticAnalyser::finalizeProtocol(const Type &type, const Type &protocol, const SourcePosition &p) {\n for (auto method : protocol.protocol()->methodList()) {\n auto methodImplementation = type.typeDefinition()->lookupMethod(method->name(), method->mood());\n if (methodImplementation == nullptr) {\n package_->compiler()->error(\n CompilerError(p, type.toString(TypeContext()), \" does not conform to protocol \",\n protocol.toString(TypeContext()), \": Method \",\n utf8(method->name()), \" not provided.\"));\n continue;\n }\n\n if (imported_) {\n continue;\n }\n\n methodImplementation->createUnspecificReification();\n auto layer = enforcePromises(methodImplementation, method, protocol, TypeContext(type), TypeContext(protocol));\n if (layer != nullptr) {\n type.typeDefinition()->addMethod(std::move(layer));\n }\n }\n}\n\nvoid SemanticAnalyser::checkProtocolConformance(const Type &type) {\n for (auto &protocol : type.typeDefinition()->protocols()) {\n finalizeProtocol(type, protocol->type(), protocol->position());\n }\n}\n\nvoid SemanticAnalyser::finalizeProtocols(const Type &type) {\n std::set<Type> protocols;\n\n for (auto &protocol : type.typeDefinition()->protocols()) {\n auto &protocolType = protocol->analyseType(TypeContext(type));\n if (protocolType.unboxedType() != TypeType::Protocol) {\n package_->compiler()->error(CompilerError(protocol->position(), \"Type is not a protocol.\"));\n continue;\n }\n if (protocols.find(protocolType.unboxed()) != protocols.end()) {\n package_->compiler()->error(CompilerError(protocol->position(),\n \"Conformance to protocol was already declared.\"));\n continue;\n }\n protocols.emplace(protocolType.unboxed());\n }\n}\n\n} \/\/ namespace EmojicodeCompiler\n<commit_msg>⚪️ Fix SemanticAnalyser::analyseFunctionDeclaration<commit_after>\/\/\n\/\/ Created by Theo Weidmann on 26.02.18.\n\/\/\n\n#include \"SemanticAnalyser.hpp\"\n#include \"Compiler.hpp\"\n#include \"DeinitializerBuilder.hpp\"\n#include \"FunctionAnalyser.hpp\"\n#include \"AST\/ASTExpr.hpp\"\n#include \"Scoping\/SemanticScoper.hpp\"\n#include \"Types\/TypeExpectation.hpp\"\n#include \"Package\/Package.hpp\"\n#include \"ThunkBuilder.hpp\"\n#include \"Types\/Class.hpp\"\n#include \"Types\/Protocol.hpp\"\n#include \"Types\/TypeDefinition.hpp\"\n#include \"Types\/ValueType.hpp\"\n\nnamespace EmojicodeCompiler {\n\nCompiler* SemanticAnalyser::compiler() const {\n return package_->compiler();\n}\n\nvoid SemanticAnalyser::analyse(bool executable) {\n for (auto &vt : package_->valueTypes()) {\n finalizeProtocols(Type(vt.get()));\n vt->analyseConstraints(TypeContext(Type(vt.get())));\n }\n for (auto &klass : package_->classes()) {\n klass->analyseSuperType();\n finalizeProtocols(Type(klass.get()));\n klass->analyseConstraints(TypeContext(Type(klass.get())));\n }\n\n package_->recreateClassTypes();\n\n \/\/ Now all types are ready to be used with compatibleTo\n\n for (auto &protocol : package_->protocols()) {\n protocol->eachFunction([this](Function *function) {\n analyseFunctionDeclaration(function);\n });\n }\n for (auto &vt : package_->valueTypes()) {\n checkProtocolConformance(Type(vt.get()));\n declareInstanceVariables(Type(vt.get()));\n buildDeinitializer(vt.get());\n buildCopyRetain(vt.get());\n enqueueFunction(vt->deinitializer());\n enqueueFunction(vt->copyRetain());\n enqueueFunctionsOfTypeDefinition(vt.get());\n }\n for (auto &klass : package_->classes()) {\n for (auto init : klass->initializerList()) {\n if (!init->required()) {\n continue;\n }\n klass->addTypeMethod(buildRequiredInitThunk(klass.get(), init));\n }\n \n klass->inherit(this);\n checkProtocolConformance(Type(klass.get()));\n\n buildDeinitializer(klass.get());\n enqueueFunction(klass->deinitializer());\n\n enqueueFunctionsOfTypeDefinition(klass.get());\n\n if (!klass->hasSubclass() && !klass->exported()) {\n klass->setFinal();\n }\n }\n for (auto &function : package_->functions()) {\n enqueueFunction(function.get());\n }\n\n analyseQueue();\n checkStartFlagFunction(executable);\n}\n\nvoid SemanticAnalyser::checkStartFlagFunction(bool executable) {\n if (package_->hasStartFlagFunction()) {\n auto returnType = package_->startFlagFunction()->returnType()->type();\n if (returnType.type() != TypeType::NoReturn &&\n !returnType.compatibleTo(Type(package_->compiler()->sInteger), TypeContext())) {\n package_->compiler()->error(CompilerError(package_->startFlagFunction()->position(),\n \"🏁 must either have no return or return 🔢.\"));\n }\n if (!executable) {\n package_->startFlagFunction()->makeExternal(); \/\/ Prevent function from being included in object file\n }\n }\n else if (executable) {\n compiler()->error(CompilerError(SourcePosition(), \"No 🏁 block was found.\"));\n }\n}\n\nvoid SemanticAnalyser::analyseQueue() {\n while (!queue_.empty()) {\n try {\n FunctionAnalyser(queue_.front(), this).analyse();\n }\n catch (CompilerError &ce) {\n package_->compiler()->error(ce);\n }\n queue_.pop();\n }\n}\n\nvoid SemanticAnalyser::enqueueFunctionsOfTypeDefinition(TypeDefinition *typeDef) {\n typeDef->eachFunction([this](Function *function) {\n enqueueFunction(function);\n });\n}\n\nvoid SemanticAnalyser::enqueueFunction(Function *function) {\n analyseFunctionDeclaration(function);\n if (!function->isExternal()) {\n queue_.emplace(function);\n }\n}\n\nvoid SemanticAnalyser::analyseFunctionDeclaration(Function *function) const {\n if (function->returnType() == nullptr) {\n function->setReturnType(std::make_unique<ASTLiteralType>(Type::noReturn()));\n }\n\n auto context = function->typeContext();\n\n function->analyseConstraints(context);\n for (auto ¶m : function->parameters()) {\n param.type->analyseType(context);\n if (!function->externalName().empty() && param.type->type().type() == TypeType::ValueType &&\n !param.type->type().valueType()->isPrimitive()) {\n param.type->type().setReference();\n }\n }\n\n if (auto initializer = dynamic_cast<Initializer*>(function)) {\n if (initializer->errorProne() && initializer->errorType()->analyseType(context).type() != TypeType::Enum) {\n throw CompilerError(initializer->errorType()->position(), \"Error type must be a non-optional 🦃.\");\n }\n return;\n }\n function->returnType()->analyseType(context, true);\n}\n\nvoid SemanticAnalyser::declareInstanceVariables(const Type &type) {\n TypeDefinition *typeDef = type.typeDefinition();\n\n auto context = TypeContext(type);\n auto scoper = std::make_unique<SemanticScoper>();\n scoper->pushScope(); \/\/ For closure analysis\n ExpressionAnalyser analyser(this, context, package_, std::move(scoper));\n\n for (auto &var : typeDef->instanceVariables()) {\n typeDef->instanceScope().declareVariable(var.name, var.type->analyseType(context), false,\n var.position);\n\n if (var.expr != nullptr) {\n auto type = var.expr->analyse(&analyser, TypeExpectation(var.type->type()));\n if (!type.compatibleTo(var.type->type(), context)) {\n package_->compiler()->error(CompilerError(var.expr->position(),\n \"Cannot initialize instance variable of type \",\n var.type->type().toString(context), \" with value of type \",\n type.toString(context), \".\"));\n }\n }\n }\n\n if (!typeDef->instanceVariables().empty() && typeDef->initializerList().empty()) {\n package_->compiler()->warn(typeDef->position(), \"Type defines \", typeDef->instanceVariables().size(),\n \" instances variables but has no initializers.\");\n }\n}\n\nbool SemanticAnalyser::checkReturnPromise(const Function *sub, const TypeContext &subContext,\n const Function *super, const TypeContext &superContext,\n const Type &superSource) const {\n auto superReturn = super->returnType()->type().resolveOn(superContext);\n auto subReturn = sub->returnType()->type().resolveOn(subContext);\n if (!subReturn.compatibleTo(superReturn, subContext)) {\n auto supername = superReturn.toString(subContext);\n auto thisname = sub->returnType()->type().toString(subContext);\n package_->compiler()->error(CompilerError(sub->position(), \"Return type \",\n sub->returnType()->type().toString(subContext), \" of \",\n utf8(sub->name()),\n \" is not compatible to the return type defined in \",\n superSource.toString(subContext)));\n }\n return subReturn.storageType() == superReturn.storageType() && subReturn.isReference() == superReturn.isReference();\n}\n\nstd::unique_ptr<Function> SemanticAnalyser::enforcePromises(Function *sub, Function *super,\n const Type &superSource,\n const TypeContext &subContext,\n const TypeContext &superContext) {\n analyseFunctionDeclaration(sub);\n analyseFunctionDeclaration(super);\n if (super->final()) {\n package_->compiler()->error(CompilerError(sub->position(), superSource.toString(subContext),\n \"’s implementation of \", utf8(sub->name()), \" was marked 🔏.\"));\n }\n if (sub->accessLevel() == AccessLevel::Private || (sub->accessLevel() == AccessLevel::Protected &&\n super->accessLevel() == AccessLevel::Public)) {\n package_->compiler()->error(CompilerError(sub->position(), \"Overriding method must be as accessible or more \",\n \"accessible than the overridden method.\"));\n }\n\n bool isReturnOk = checkReturnPromise(sub, subContext, super, superContext, superSource);\n bool isParamsOk = checkArgumentPromise(sub, super, subContext, superContext) ;\n if (!isParamsOk || !isReturnOk) {\n return buildBoxingThunk(superContext, super, sub);\n }\n return nullptr;\n}\n\nbool SemanticAnalyser::checkArgumentPromise(const Function *sub, const Function *super, const TypeContext &subContext,\n const TypeContext &superContext) const {\n if (super->parameters().size() != sub->parameters().size()) {\n package_->compiler()->error(CompilerError(sub->position(), \"Parameter count does not match.\"));\n return true;\n }\n\n bool compatible = true;\n for (size_t i = 0; i < super->parameters().size(); i++) { \/\/ More general arguments are OK\n auto superArgumentType = super->parameters()[i].type->type().resolveOn(superContext);\n if (!superArgumentType.compatibleTo(sub->parameters()[i].type->type().resolveOn(subContext), subContext)) {\n auto supertype = superArgumentType.toString(subContext);\n auto thisname = sub->parameters()[i].type->type().toString(subContext);\n package_->compiler()->error(CompilerError(sub->position(), \"Type \", thisname, \" of argument \", i + 1,\n \" is not compatible with its \", thisname, \" argument type \",\n supertype, \".\"));\n }\n if (sub->parameters()[i].type->type().resolveOn(subContext).storageType() != superArgumentType.storageType()) {\n compatible = false; \/\/ Boxing Thunk required for parameter i\n }\n }\n return compatible;\n}\n\nvoid SemanticAnalyser::finalizeProtocol(const Type &type, const Type &protocol, const SourcePosition &p) {\n for (auto method : protocol.protocol()->methodList()) {\n auto methodImplementation = type.typeDefinition()->lookupMethod(method->name(), method->mood());\n if (methodImplementation == nullptr) {\n package_->compiler()->error(\n CompilerError(p, type.toString(TypeContext()), \" does not conform to protocol \",\n protocol.toString(TypeContext()), \": Method \",\n utf8(method->name()), \" not provided.\"));\n continue;\n }\n\n if (imported_) {\n continue;\n }\n\n methodImplementation->createUnspecificReification();\n auto layer = enforcePromises(methodImplementation, method, protocol, TypeContext(type), TypeContext(protocol));\n if (layer != nullptr) {\n type.typeDefinition()->addMethod(std::move(layer));\n }\n }\n}\n\nvoid SemanticAnalyser::checkProtocolConformance(const Type &type) {\n for (auto &protocol : type.typeDefinition()->protocols()) {\n finalizeProtocol(type, protocol->type(), protocol->position());\n }\n}\n\nvoid SemanticAnalyser::finalizeProtocols(const Type &type) {\n std::set<Type> protocols;\n\n for (auto &protocol : type.typeDefinition()->protocols()) {\n auto &protocolType = protocol->analyseType(TypeContext(type));\n if (protocolType.unboxedType() != TypeType::Protocol) {\n package_->compiler()->error(CompilerError(protocol->position(), \"Type is not a protocol.\"));\n continue;\n }\n if (protocols.find(protocolType.unboxed()) != protocols.end()) {\n package_->compiler()->error(CompilerError(protocol->position(),\n \"Conformance to protocol was already declared.\"));\n continue;\n }\n protocols.emplace(protocolType.unboxed());\n }\n}\n\n} \/\/ namespace EmojicodeCompiler\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkStateMachine.h\"\n#include \"mitkStateMachineFactory.h\"\n#include \"mitkStateTransitionOperation.h\"\n#include \"mitkOperationEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkInteractionConst.h\"\n#include <itkMacro.h>\n#include \"mitkInteractor.h\"\n\n\n\/\/##ModelId=3E5B2DB301FD\n\/\/##Documentation\n\/\/## Constructor\n\/\/## daclares a new StateMachine and connects\n\/\/## it to a StateMachine of Type type;\nmitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)\n{\n if(type!=NULL)\n {\n m_Type = type;\n\t m_CurrentState = mitk::StateMachineFactory::GetStartState(type);\n if (m_CurrentState == NULL)\n itkWarningMacro(\"Error: no start-state defined in state-machine definition \"<<type<<\".\");\n }\n \/\/else\n \/\/ itkWarningMacro(\"Error from \"<<this->GetNameOfClass()<<\"; Message: Type of StateMachine is NULL!\");\n \/\/\\*todo: check the process with BaseControllers, cause they are always instantiated with type ==NULL! So here we can't check and warn the user.\n \n m_UndoController = new UndoController(LIMITEDLINEARUNDO);\/\/switch to LLU or add LLU\n\tm_UndoEnabled = true;\n}\nmitk::StateMachine::~StateMachine()\n{\n delete m_UndoController;\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetType() const\n{\n\treturn m_Type;\n}\n\nconst mitk::State* mitk::StateMachine::GetCurrentState() const\n{\n if (m_CurrentState)\n return m_CurrentState;\n return NULL;\n}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n if (m_CurrentState == NULL)\n return false;\/\/m_CurrentState needs to be set first!\n\n \/\/get the Transition from m_CurrentState which waits for this EventId\n const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n if (tempTransition == NULL) \/\/no transition in this state for that EventId\n {\n return false;\n }\n\n \/\/get next State\n State *tempNextState = tempTransition->GetNextState();\n if (tempNextState == NULL) \/\/wrong built up statemachine!\n return false;\n\n \/\/and ActionId to execute later on\n if ( m_CurrentState->GetId() != tempNextState->GetId() )\/\/statechange only if there is a real statechange\n {\n if ( m_UndoEnabled )\t\/\/write to UndoMechanism if Undo is enabled\n {\n \/\/UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false\n \t StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);\n StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);\n\t OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);\n\t m_UndoController->SetOperationEvent(operationEvent);\n }\n\/\/#define INTERDEBUG\n #ifdef INTERDEBUG\n \/\/Debug StateChanges through cout output! Thus very slow!\n \/\/itkWarningMacro(<<this->GetType()<<\": Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<tempNextState->GetId());\n itkWarningMacro(<<\": Changing from State \"<<m_CurrentState->GetName()<<\" to State \"<<tempNextState->GetName() << \" via Transition \" << tempTransition->GetName() << \" due to Event \" << stateEvent->GetId());\n #endif\n\n \/\/first following StateChange(or calling ExecuteOperation(tempNextStateOp)), then operation(action)\n m_CurrentState = tempNextState;\n }\n else\n {\n #ifdef INTERDEBUG\n if( (tempTransition != m_CurrentState->GetTransition(0)) \/\/dont show 0 events\n && (m_CurrentState->GetName()!=\"neutral\"))\n {\n \/\/Debug StateChanges through cout output! Thus very slow!\n \/\/itkWarningMacro(<<this->GetType()<<\": Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<tempNextState->GetId());\n itkWarningMacro(<<\": Keeping State \"<<m_CurrentState->GetName()<< \" at Transition \" << tempTransition->GetName() << \" due to Event \" << stateEvent->GetId());\n }\n #endif\n }\n\n\n std::vector<Action*>::iterator actionIdIterator = tempTransition->GetActionBeginIterator();\n const std::vector<Action*>::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();\n bool ok = true;\n\n while ( actionIdIterator != actionIdIteratorEnd ) \n {\n if ( !ExecuteAction(*actionIdIterator, stateEvent) )\n {\n #ifdef INTERDEBUG\n itkWarningMacro( << \"Warning: no action defind for \" << *actionIdIterator << \" in \" << m_Type );\n #endif\n\n ok = false;\n }\n actionIdIterator++;\n }\n return ok;\n}\n\n\/\/##ModelId=3EDCAECB0175\nvoid mitk::StateMachine::EnableUndo(bool enable)\n{\n\tm_UndoEnabled = enable;\n}\n\n\/\/##ModelId=3EF099EA03C0\nvoid mitk::StateMachine::IncCurrGroupEventId()\n{\n\tmitk::OperationEvent::IncCurrGroupEventId();\n}\n\nvoid mitk::StateMachine::ExecuteOperation(Operation* operation)\n{\n\tswitch (operation->GetOperationType())\n\t{\n\tcase OpNOTHING:\n\t\tbreak;\n\tcase OpSTATECHANGE:\n\t\t{\n\t\t\tmitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);\n\t\t\tif (stateTransOp == NULL)\n\t\t\t{\n\t\t\t\titkWarningMacro(\"Error! see mitkStateMachine.cpp\");\n\t\t\t\treturn;\n\t\t\t}\n#ifdef INTERDEBUG\n\/\/Debug StateChanges through cout output! Thus very slow!\nstd::cout<<this->GetType()<<\": Undo: Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<stateTransOp->GetState()->GetId()<<std::endl;\nstd::cout<<this->GetType()<<\": Undo: Changing from State \"<<m_CurrentState->GetName()<<\" to State \"<<stateTransOp->GetState()->GetName()<<std::endl;\n#endif\n\t\t\tm_CurrentState = stateTransOp->GetState();\n\t\t}\n\t\tbreak;\n case OpDELETE:\n {\n \/\/delete this!\n \/\/before all lower statemachines has to be deleted in a action\n \/\/this->Delete();\/\/might not work!!!check itk!\n }\n case OpUNDELETE:\n {\n \/\/this is just new! and now the m_CurrentState has to be set on a special State\n \/\/that way a delete of a StateMachine can be undone \n \/\/IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!\n mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);\n\t\t\tif (stateTransOp != NULL)\n {\n m_CurrentState = stateTransOp->GetState();\n }\n }\n\tdefault:\n\t\t;\n\t}\n}\n<commit_msg>modified debug information<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkStateMachine.h\"\n#include \"mitkStateMachineFactory.h\"\n#include \"mitkStateTransitionOperation.h\"\n#include \"mitkOperationEvent.h\"\n#include \"mitkUndoController.h\"\n#include \"mitkInteractionConst.h\"\n#include <itkMacro.h>\n#include \"mitkInteractor.h\"\n\n\n\/\/##ModelId=3E5B2DB301FD\n\/\/##Documentation\n\/\/## Constructor\n\/\/## daclares a new StateMachine and connects\n\/\/## it to a StateMachine of Type type;\nmitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)\n{\n if(type!=NULL)\n {\n m_Type = type;\n\t m_CurrentState = mitk::StateMachineFactory::GetStartState(type);\n if (m_CurrentState == NULL)\n itkWarningMacro(\"Error: no start-state defined in state-machine definition \"<<type<<\".\");\n }\n \/\/else\n \/\/ itkWarningMacro(\"Error from \"<<this->GetNameOfClass()<<\"; Message: Type of StateMachine is NULL!\");\n \/\/\\*todo: check the process with BaseControllers, cause they are always instantiated with type ==NULL! So here we can't check and warn the user.\n \n m_UndoController = new UndoController(LIMITEDLINEARUNDO);\/\/switch to LLU or add LLU\n\tm_UndoEnabled = true;\n}\nmitk::StateMachine::~StateMachine()\n{\n delete m_UndoController;\n}\n\n\/\/##ModelId=3E5B2E660087\nstd::string mitk::StateMachine::GetType() const\n{\n\treturn m_Type;\n}\n\nconst mitk::State* mitk::StateMachine::GetCurrentState() const\n{\n if (m_CurrentState)\n return m_CurrentState;\n return NULL;\n}\n\n\/\/##ModelId=3E5B2DE30378\nbool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)\n{\n if (m_CurrentState == NULL)\n return false;\/\/m_CurrentState needs to be set first!\n\n \/\/get the Transition from m_CurrentState which waits for this EventId\n const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());\n if (tempTransition == NULL) \/\/no transition in this state for that EventId\n {\n return false;\n #ifdef INTERDEBUG\n \/\/Debug StateChanges through cout output! Thus very slow!\n \/\/itkWarningMacro(<<this->GetType()<<\": Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<tempNextState->GetId());\n itkWarningMacro(<<\": Did not find transition for Event Id \" << stateEvent->GetId());\n #endif\n }\n\n \/\/get next State\n State *tempNextState = tempTransition->GetNextState();\n if (tempNextState == NULL) \/\/wrong built up statemachine!\n return false;\n\n \/\/and ActionId to execute later on\n if ( m_CurrentState->GetId() != tempNextState->GetId() )\/\/statechange only if there is a real statechange\n {\n if ( m_UndoEnabled )\t\/\/write to UndoMechanism if Undo is enabled\n {\n \/\/UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false\n \t StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);\n StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);\n\t OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);\n\t m_UndoController->SetOperationEvent(operationEvent);\n }\n\/\/#define INTERDEBUG\n #ifdef INTERDEBUG\n \/\/Debug StateChanges through cout output! Thus very slow!\n \/\/itkWarningMacro(<<this->GetType()<<\": Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<tempNextState->GetId());\n itkWarningMacro(<<\": Changing from State \"<<m_CurrentState->GetName()<<\" to State \"<<tempNextState->GetName() << \" via Transition \" << tempTransition->GetName() << \" due to Event \" << stateEvent->GetId());\n #endif\n\n \/\/first following StateChange(or calling ExecuteOperation(tempNextStateOp)), then operation(action)\n m_CurrentState = tempNextState;\n }\n else\n {\n #ifdef INTERDEBUG\n if( (tempTransition != m_CurrentState->GetTransition(0)) \/\/dont show 0 events\n && (m_CurrentState->GetName()!=\"neutral\"))\n {\n \/\/Debug StateChanges through cout output! Thus very slow!\n \/\/itkWarningMacro(<<this->GetType()<<\": Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<tempNextState->GetId());\n itkWarningMacro(<<\": Keeping State \"<<m_CurrentState->GetName()<< \" at Transition \" << tempTransition->GetName() << \" due to Event \" << stateEvent->GetId());\n }\n #endif\n }\n\n\n std::vector<Action*>::iterator actionIdIterator = tempTransition->GetActionBeginIterator();\n const std::vector<Action*>::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();\n bool ok = true;\n\n while ( actionIdIterator != actionIdIteratorEnd ) \n {\n if ( !ExecuteAction(*actionIdIterator, stateEvent) )\n {\n #ifdef INTERDEBUG\n itkWarningMacro( << \"Warning: no action defind for \" << *actionIdIterator << \" in \" << m_Type );\n #endif\n\n ok = false;\n }\n actionIdIterator++;\n }\n return ok;\n}\n\n\/\/##ModelId=3EDCAECB0175\nvoid mitk::StateMachine::EnableUndo(bool enable)\n{\n\tm_UndoEnabled = enable;\n}\n\n\/\/##ModelId=3EF099EA03C0\nvoid mitk::StateMachine::IncCurrGroupEventId()\n{\n\tmitk::OperationEvent::IncCurrGroupEventId();\n}\n\nvoid mitk::StateMachine::ExecuteOperation(Operation* operation)\n{\n\tswitch (operation->GetOperationType())\n\t{\n\tcase OpNOTHING:\n\t\tbreak;\n\tcase OpSTATECHANGE:\n\t\t{\n\t\t\tmitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);\n\t\t\tif (stateTransOp == NULL)\n\t\t\t{\n\t\t\t\titkWarningMacro(\"Error! see mitkStateMachine.cpp\");\n\t\t\t\treturn;\n\t\t\t}\n#ifdef INTERDEBUG\n\/\/Debug StateChanges through cout output! Thus very slow!\nstd::cout<<this->GetType()<<\": Undo: Changing from StateId \"<<m_CurrentState->GetId()<<\" to StateId \"<<stateTransOp->GetState()->GetId()<<std::endl;\nstd::cout<<this->GetType()<<\": Undo: Changing from State \"<<m_CurrentState->GetName()<<\" to State \"<<stateTransOp->GetState()->GetName()<<std::endl;\n#endif\n\t\t\tm_CurrentState = stateTransOp->GetState();\n\t\t}\n\t\tbreak;\n case OpDELETE:\n {\n \/\/delete this!\n \/\/before all lower statemachines has to be deleted in a action\n \/\/this->Delete();\/\/might not work!!!check itk!\n }\n case OpUNDELETE:\n {\n \/\/this is just new! and now the m_CurrentState has to be set on a special State\n \/\/that way a delete of a StateMachine can be undone \n \/\/IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!\n mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);\n\t\t\tif (stateTransOp != NULL)\n {\n m_CurrentState = stateTransOp->GetState();\n }\n }\n\tdefault:\n\t\t;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2022 Jean-Francois Poilpret\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/*\n * TODO comments Simple LED chaser. Take #1\n * This program shows usage of FastArduino events support and GPIO port API.\n * The number of LED roundtrips is limited to one because all events are pushed \n * at startup and not regenerated.\n * \n * Wiring: TODO\n * - on Arduino UNO:\n * - D0-D7 (port D) branch 8 LED (in series with 330 Ohm resistors to limit \n * current) connected to ground\n *\/\n\n#include <fastarduino\/uart.h>\n#include <fastarduino\/soft_uart.h>\n#include <fastarduino\/devices\/grove_rfid_reader.h>\n#include <fastarduino\/time.h>\n\n#if !defined(ARDUINO_UNO)\n#error \"Current target is not yet supported!\"\n#endif\n\n#define USART_NUM 0\nstatic constexpr board::USART USART = board::USART::USART0;\nusing UARX = serial::hard::UARX<USART>;\nusing GROVE = devices::rfid::Grove125KHzRFIDReaderUART<UARX>;\n\nstatic constexpr board::DigitalPin UATX_TX = board::DigitalPin::D2;\nusing UATX = serial::soft::UATX<UATX_TX>;\n\nstatic constexpr uint8_t RFID_INPUT_BUFFER_SIZE = 64;\nstatic char input_buffer[RFID_INPUT_BUFFER_SIZE];\n\nstatic constexpr uint8_t DEBUG_OUTPUT_BUFFER_SIZE = 64;\nstatic char output_buffer[DEBUG_OUTPUT_BUFFER_SIZE];\n\nstatic constexpr uint8_t TAG_DATA_SIZE = 16;\n\nREGISTER_UARX_ISR(USART_NUM)\nREGISTER_OSTREAMBUF_LISTENERS(UATX)\n\nusing streams::endl;\n\nint main() __attribute__((OS_main));\nint main()\n{\n\tboard::init();\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\n\tUATX uatx{output_buffer};\n\tuatx.begin(115200);\n\tauto out = uatx.out();\n\tout << F(\"Starting...\") << endl;\n\n\tUARX uarx{input_buffer};\n\tGROVE rfid{uarx};\n\trfid.begin();\n\n\twhile (true)\n\t{\n\t\tif (rfid.has_data())\n\t\t{\n\t\t\tchar data[TAG_DATA_SIZE];\n\t\t\trfid.get_data(data, TAG_DATA_SIZE);\n\t\t\t\/\/TODO display data to SW serial\n\t\t\tout << data << endl;\n\t\t}\n\t\ttime::delay_ms(100);\n\t}\n\n\trfid.end();\n\treturn 0;\n}\n<commit_msg>Update doc of 1st Grove RFID reader example<commit_after>\/\/ Copyright 2016-2022 Jean-Francois Poilpret\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/*\n * RFID 125KHz Grove reader example, UART mode, using Hardware UART.\n * This program shows usage of FastArduino Grove 125KHz RFID Reader support.\n * It displays the ID of tags that are nearing the device coil.\n * \n * Wiring:\n * - on Arduino UNO:\n * - RX (D0): connect to Grove TX (yellow cable)\n * - D2: connect to serial USB converter, connected to a console\n *\/\n\n#include <fastarduino\/uart.h>\n#include <fastarduino\/soft_uart.h>\n#include <fastarduino\/devices\/grove_rfid_reader.h>\n#include <fastarduino\/time.h>\n\n#if !defined(ARDUINO_UNO)\n#error \"Current target is not yet supported!\"\n#endif\n\n#define USART_NUM 0\nstatic constexpr board::USART USART = board::USART::USART0;\nusing UARX = serial::hard::UARX<USART>;\nusing GROVE = devices::rfid::Grove125KHzRFIDReaderUART<UARX>;\n\nstatic constexpr board::DigitalPin UATX_TX = board::DigitalPin::D2;\nusing UATX = serial::soft::UATX<UATX_TX>;\n\nstatic constexpr uint8_t RFID_INPUT_BUFFER_SIZE = 64;\nstatic char input_buffer[RFID_INPUT_BUFFER_SIZE];\n\nstatic constexpr uint8_t DEBUG_OUTPUT_BUFFER_SIZE = 64;\nstatic char output_buffer[DEBUG_OUTPUT_BUFFER_SIZE];\n\nstatic constexpr uint8_t TAG_DATA_SIZE = 16;\n\nREGISTER_UARX_ISR(USART_NUM)\nREGISTER_OSTREAMBUF_LISTENERS(UATX)\n\nusing streams::endl;\n\nint main() __attribute__((OS_main));\nint main()\n{\n\tboard::init();\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\n\tUATX uatx{output_buffer};\n\tuatx.begin(115200);\n\tauto out = uatx.out();\n\tout << F(\"Starting...\") << endl;\n\n\tUARX uarx{input_buffer};\n\tGROVE rfid{uarx};\n\trfid.begin();\n\n\twhile (true)\n\t{\n\t\tif (rfid.has_data())\n\t\t{\n\t\t\tchar data[TAG_DATA_SIZE];\n\t\t\trfid.get_data(data, TAG_DATA_SIZE);\n\t\t\t\/\/ display data to SW serial\n\t\t\tout << data << endl;\n\t\t}\n\t\ttime::delay_ms(100);\n\t}\n\n\trfid.end();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Jamoma DSP Soundfile Player\n * Copyright © 2010, Tim Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTSoundfilePlayer.h\"\n\n#define thisTTClass\t\t\tTTSoundfilePlayer\n#define thisTTClassName\t\t\"soundfile.player\"\n#define thisTTClassTags\t\t\"audio, soundfile, playback\"\n\n\nTT_AUDIO_CONSTRUCTOR,\nmFilePath(kTTSymEmpty),\nmSoundFile(NULL),\nmPlay(false),\nmLoop(false),\nmContinue(false),\nmSeek(0),\nmNumChannels(0),\nmNumBufferFrames(0)\n{\n\taddAttributeWithSetter(\tFilePath,\t\tkTypeSymbol);\n\taddAttributeWithSetter(\tPlay,\t\t\tkTypeBoolean);\n\taddAttributeWithSetter(\tSeek,\t\t\tkTypeFloat64);\n\taddAttribute(\t\t\tLoop,\t\t\tkTypeBoolean);\n\taddAttribute(\t\t\tNumChannels,\tkTypeUInt16);\n\taddAttributeProperty(\tNumChannels,\treadOnly, kTTBoolYes);\n\t\n\taddMessage(Pause);\n\taddMessage(Resume);\n\tsetProcessMethod(processAudio);\n\t\/\/setAttributeValue(TT(\"MaxNumChannels\"),\targuments);\t\t\t\/\/ This attribute is inherited\n}\n\n\nTTSoundfilePlayer::~TTSoundfilePlayer()\n{\n\tsetAttributeValue(TT(\"Play\"), kTTBoolNo);\n\tif (mSoundFile)\n\t\tsf_close(mSoundFile);\n}\n\n\n\/\/ takes a POSIX path, e.g. \/Users\/tim\/Music\/Demos\/whiteandnerdy.aif\nTTErr TTSoundfilePlayer::setFilePath(const TTValue& newValue)\n{\n\tTTSymbolPtr potentialFilePath = newValue;\n\tSNDFILE*\tsoundfile;\n#ifdef TT_PLATFORM_WIN\n\t\/\/ There is a bug in libsndfile on Windows where upon return from this function a runtime check fails\n\t\/\/ because the stack is corrupted around soundfileInfo when sf_open() is called.\n\t\/\/ We work around this by allocating some extra memory to absorb the overrun. [tap]\n\tSF_INFO\t\tsoundfileInfo[2];\n#else\n\tSF_INFO\t\tsoundfileInfo[1];\n#endif\n\n\tmemset(&soundfileInfo, 0, sizeof(SF_INFO));\n\t\/\/soundfileInfo.format = 0;\n\tsoundfile = sf_open(potentialFilePath->getCString(), SFM_READ, soundfileInfo);\n\t\n\tif (soundfile) {\n\t\tSNDFILE* oldSoundFile = mSoundFile;\n\n\t\tmSoundFile = soundfile;\n\t\tif (oldSoundFile)\n\t\t\tsf_close(oldSoundFile);\n\t\tmemcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO));\n\t\tmFilePath = potentialFilePath;\n\t\tmPlay = 0;\n\t\tmContinue = 1; \/\/eliminating previous pause state\n\t\t\/\/ TODO: fill in things like the NumChannels attr here\n\t\treturn kTTErrNone;\n\t}\n\telse\n\t\treturn kTTErrGeneric;\n}\n\nTTErr TTSoundfilePlayer::setPlay(const TTValue& newValue)\n{ \n\tmPlay = newValue; \n\tmContinue = 1; \/\/eliminating previous pause state\n\tif (mPlay == 0){\n\t\tif (mSoundFile){\n\t\t\tmSeek = 0;\n\t\t\tsf_seek(mSoundFile, 0, SEEK_SET);\n\t\t}\n\t}\t\nreturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::setSeek(const TTValue& newValue)\n{ \n\tif (mSoundFile) {\n\t\tmSeek = newValue;\n\t\tmSeek = mSeek * sr\/1000.0;\n\t\tmContinue = 1; \/\/eliminating previous pause state\n\t\tsf_seek(mSoundFile, mSeek, SEEK_SET);\n\t\tmPlay = 1;\n\t\treturn kTTErrNone;\n\t}\n\telse\n\t\treturn kTTErrGeneric;\t\n}\n\nTTErr TTSoundfilePlayer::Pause()\n{ \n\tmContinue = 0;\n\treturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::Resume()\n{ \n\tmContinue = 1;\n\treturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n{\n\tTTAudioSignal&\tout = outputs->getSignal(0);\n\tTTUInt16\t\toutChannelCount = out.getMaxNumChannelsAsInt();\n\tTTUInt16\t\tnumFrames = out.getVectorSizeAsInt();\n\tTTBoolean\t\tbufferNeedsResize = NO;\n\tsf_count_t\t\t\tnumSamplesRead; \n\tTTUInt16\t\t\tn;\n\tTTSampleValuePtr\toutSample;\n\tTTUInt16\t\t\tchannel;\n\t\n \n\tif (mSoundFile) {\t\n\t\/\/ resize of the number of output channels, if needed\n\tif (outChannelCount != mSoundFileInfo.channels || !mNumChannels) {\n\t\tmNumChannels = mSoundFileInfo.channels;\n\t\tout.setMaxNumChannels(mNumChannels);\n\t\tbufferNeedsResize = YES;\n\t}\n\tout.setNumChannelsWithInt(mNumChannels);\n\t\n\tif (mNumBufferFrames != numFrames) {\n\t\tmNumBufferFrames = numFrames;\n\t\tbufferNeedsResize = YES;\n\t}\n\tif (bufferNeedsResize)\n\t\tmBuffer.resize(mNumBufferFrames * mNumChannels);\n\t\n\tif (!mNumChannels)\n\t\treturn TTAudioObject::muteProcess(inputs, outputs);\n\t\n\t\/\/ if there is an input, we want to treat it as a sample-accurate on\/off switch for playback\n\t\/\/if (inputs->numAudioSignals) {\n\t\/\/\t; \/\/ TODO: implement this\n\t\/\/}\n\t\/\/else {\n\t\n\t\t\t\t\n\t\tmBuffer.assign(mBuffer.size(), 0.0);\n\t\t\n\t\tif (mPlay && mContinue) {\n\t\t\tnumSamplesRead = sf_read_double(mSoundFile, &mBuffer[0], numFrames*mNumChannels);\n\t\t\tif (numSamplesRead < numFrames*mNumChannels) {\n\t\t\t\tsf_seek(mSoundFile, mSeek, SEEK_SET);\n\t\t\t\tmPlay = mLoop;\t\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tfor (channel=0; channel<mNumChannels; channel++) {\n\t\t\toutSample = out.mSampleVectors[channel];\n\n\t\t\tfor (n=0; n<numFrames; n++)\n\t\t\t\toutSample[n] = mBuffer[n * mNumChannels + channel];\n\t\t}\n\t}\t\n\telse { \/\/no soundfile selected, we send out a zero signal on one channel \n\t\tout.setMaxNumChannels(1);\n\t\tout.setNumChannelsWithInt(1);\n\t\tfor (n=0; n<numFrames; n++)\n\t\tout.mSampleVectors[0][n] = 0.0;\n\t}\n\t\t\n\treturn kTTErrNone;\n}\n<commit_msg>TTSoundfilePlayer : avoid to set the number of output channels if not necessary. <commit_after>\/* \n * Jamoma DSP Soundfile Player\n * Copyright © 2010, Tim Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTSoundfilePlayer.h\"\n\n#define thisTTClass\t\t\tTTSoundfilePlayer\n#define thisTTClassName\t\t\"soundfile.player\"\n#define thisTTClassTags\t\t\"audio, soundfile, playback\"\n\n\nTT_AUDIO_CONSTRUCTOR,\nmFilePath(kTTSymEmpty),\nmSoundFile(NULL),\nmPlay(false),\nmLoop(false),\nmContinue(false),\nmSeek(0),\nmNumChannels(0),\nmNumBufferFrames(0)\n{\n\taddAttributeWithSetter(\tFilePath,\t\tkTypeSymbol);\n\taddAttributeWithSetter(\tPlay,\t\t\tkTypeBoolean);\n\taddAttributeWithSetter(\tSeek,\t\t\tkTypeFloat64);\n\taddAttribute(\t\t\tLoop,\t\t\tkTypeBoolean);\n\taddAttribute(\t\t\tNumChannels,\tkTypeUInt16);\n\taddAttributeProperty(\tNumChannels,\treadOnly, kTTBoolYes);\n\t\n\taddMessage(Pause);\n\taddMessage(Resume);\n\tsetProcessMethod(processAudio);\n\t\/\/setAttributeValue(TT(\"MaxNumChannels\"),\targuments);\t\t\t\/\/ This attribute is inherited\n}\n\n\nTTSoundfilePlayer::~TTSoundfilePlayer()\n{\n\tsetAttributeValue(TT(\"Play\"), kTTBoolNo);\n\tif (mSoundFile)\n\t\tsf_close(mSoundFile);\n}\n\n\n\/\/ takes a POSIX path, e.g. \/Users\/tim\/Music\/Demos\/whiteandnerdy.aif\nTTErr TTSoundfilePlayer::setFilePath(const TTValue& newValue)\n{\n\tTTSymbolPtr potentialFilePath = newValue;\n\tSNDFILE*\tsoundfile;\n#ifdef TT_PLATFORM_WIN\n\t\/\/ There is a bug in libsndfile on Windows where upon return from this function a runtime check fails\n\t\/\/ because the stack is corrupted around soundfileInfo when sf_open() is called.\n\t\/\/ We work around this by allocating some extra memory to absorb the overrun. [tap]\n\tSF_INFO\t\tsoundfileInfo[2];\n#else\n\tSF_INFO\t\tsoundfileInfo[1];\n#endif\n\n\tmemset(&soundfileInfo, 0, sizeof(SF_INFO));\n\t\/\/soundfileInfo.format = 0;\n\tsoundfile = sf_open(potentialFilePath->getCString(), SFM_READ, soundfileInfo);\n\t\n\tif (soundfile) {\n\t\tSNDFILE* oldSoundFile = mSoundFile;\n\n\t\tmSoundFile = soundfile;\n\t\tif (oldSoundFile)\n\t\t\tsf_close(oldSoundFile);\n\t\tmemcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO));\n\t\tmFilePath = potentialFilePath;\n\t\tmPlay = 0;\n\t\tmContinue = 1; \/\/eliminating previous pause state\n\t\t\/\/ TODO: fill in things like the NumChannels attr here\n\t\treturn kTTErrNone;\n\t}\n\telse\n\t\treturn kTTErrGeneric;\n}\n\nTTErr TTSoundfilePlayer::setPlay(const TTValue& newValue)\n{ \n\tmPlay = newValue; \n\tmContinue = 1; \/\/eliminating previous pause state\n\tif (mPlay == 0){\n\t\tif (mSoundFile){\n\t\t\tmSeek = 0;\n\t\t\tsf_seek(mSoundFile, 0, SEEK_SET);\n\t\t}\n\t}\t\nreturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::setSeek(const TTValue& newValue)\n{ \n\tif (mSoundFile) {\n\t\tmSeek = newValue;\n\t\tmSeek = mSeek * sr\/1000.0;\n\t\tmContinue = 1; \/\/eliminating previous pause state\n\t\tsf_seek(mSoundFile, mSeek, SEEK_SET);\n\t\tmPlay = 1;\n\t\treturn kTTErrNone;\n\t}\n\telse\n\t\treturn kTTErrGeneric;\t\n}\n\nTTErr TTSoundfilePlayer::Pause()\n{ \n\tmContinue = 0;\n\treturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::Resume()\n{ \n\tmContinue = 1;\n\treturn kTTErrNone;\n}\n\nTTErr TTSoundfilePlayer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n{\n\tTTAudioSignal&\tout = outputs->getSignal(0);\n\tTTUInt16\t\toutChannelCount = out.getMaxNumChannelsAsInt();\n\tTTUInt16\t\tnumFrames = out.getVectorSizeAsInt();\n\tTTBoolean\t\tbufferNeedsResize = NO;\n\tsf_count_t\t\t\tnumSamplesRead; \n\tTTUInt16\t\t\tn;\n\tTTSampleValuePtr\toutSample;\n\tTTUInt16\t\t\tchannel;\n\t\n \n\tif (mSoundFile) {\t\n\t\/\/ resize of the number of output channels, if needed\n\tif (outChannelCount != mSoundFileInfo.channels || !mNumChannels) {\n\t\tmNumChannels = mSoundFileInfo.channels;\n\t\tout.setMaxNumChannels(mNumChannels);\n\t\tbufferNeedsResize = YES;\n\t\tout.setNumChannelsWithInt(mNumChannels);\n\t}\n\t\n\tif (mNumBufferFrames != numFrames) {\n\t\tmNumBufferFrames = numFrames;\n\t\tbufferNeedsResize = YES;\n\t}\n\tif (bufferNeedsResize)\n\t\tmBuffer.resize(mNumBufferFrames * mNumChannels);\n\t\n\tif (!mNumChannels)\n\t\treturn TTAudioObject::muteProcess(inputs, outputs);\n\t\n\t\/\/ if there is an input, we want to treat it as a sample-accurate on\/off switch for playback\n\t\/\/if (inputs->numAudioSignals) {\n\t\/\/\t; \/\/ TODO: implement this\n\t\/\/}\n\t\/\/else {\n\t\n\t\t\t\t\n\t\tmBuffer.assign(mBuffer.size(), 0.0);\n\t\t\n\t\tif (mPlay && mContinue) {\n\t\t\tnumSamplesRead = sf_read_double(mSoundFile, &mBuffer[0], numFrames*mNumChannels);\n\t\t\tif (numSamplesRead < numFrames*mNumChannels) {\n\t\t\t\tsf_seek(mSoundFile, mSeek, SEEK_SET);\n\t\t\t\tmPlay = mLoop;\t\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tfor (channel=0; channel<mNumChannels; channel++) {\n\t\t\toutSample = out.mSampleVectors[channel];\n\n\t\t\tfor (n=0; n<numFrames; n++)\n\t\t\t\toutSample[n] = mBuffer[n * mNumChannels + channel];\n\t\t}\n\t}\t\n\telse { \/\/no soundfile selected, we send out a zero signal on one channel \n\t\tout.setMaxNumChannels(1);\n\t\tout.setNumChannelsWithInt(1);\n\t\tfor (n=0; n<numFrames; n++)\n\t\tout.mSampleVectors[0][n] = 0.0;\n\t}\n\t\t\n\treturn kTTErrNone;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <assert.h>\n#include <sys\/socket.h>\n\n#include \"server.h\"\n#include \"utils.h\"\n#include \"client_binary.h\"\n#include \"xapiand.h\"\n#include \"length.h\"\n\n\/\/\n\/\/ Xapian binary client\n\/\/\n\nBinaryClient::BinaryClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(server_, loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_),\n\t RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true),\n\t running(false),\n started(false)\n{\n\tpthread_mutex_lock(&XapiandServer::static_mutex);\n\tint total_clients = XapiandServer::total_clients;\n\tint binary_clients = ++XapiandServer::binary_clients;\n\tpthread_mutex_unlock(&XapiandServer::static_mutex);\n\t\n\tLOG_CONN(this, \"Got connection (sock=%d), %d binary client(s) of a total of %d connected.\\n\", sock, binary_clients, XapiandServer::total_clients);\n\n\tthread_pool->addTask(this);\n\n\tLOG_OBJ(this, \"CREATED BINARY CLIENT! (%d clients)\\n\", binary_clients);\n\tassert(binary_clients <= total_clients);\n}\n\n\nBinaryClient::~BinaryClient()\n{\n\tstd::unordered_map<Xapian::Database *, Database *>::const_iterator it(databases.begin());\n\tfor (; it != databases.end(); it++) {\n\t\tDatabase *database = it->second;\n\t\tdatabase_pool->checkin(&database);\n\t}\n\n\tpthread_mutex_lock(&XapiandServer::static_mutex);\n\tint binary_clients = --XapiandServer::binary_clients;\n\tpthread_mutex_unlock(&XapiandServer::static_mutex);\n\n\tLOG_OBJ(this, \"DELETED BINARY CLIENT! (%d clients left)\\n\", binary_clients);\n\tassert(binary_clients >= 0);\n}\n\n\nvoid BinaryClient::on_read(const char *buf, ssize_t received)\n{\n\tbuffer.append(buf, received);\n\twhile (buffer.length() >= 2) {\n\t\tconst char *o = buffer.data();\n\t\tconst char *p = o;\n\t\tconst char *p_end = p + buffer.size();\n\t\t\n\t\tmessage_type type = static_cast<message_type>(*p++);\n\t\tsize_t len = decode_length(&p, p_end, true);\n\t\tif (len == -1) {\n\t\t\treturn;\n\t\t}\n\t\tstd::string data = std::string(p, len);\n\t\tbuffer.erase(0, p - o + len);\n\t\t\n\t\tBuffer *msg = new Buffer(type, data.c_str(), data.size());\n\t\t\n\t\tmessages_queue.push(msg);\n\t}\n pthread_mutex_lock(&qmtx);\n if (!messages_queue.empty()) {\n if (!running) {\n running = true;\n thread_pool->addTask(this);\n }\n }\n pthread_mutex_unlock(&qmtx);\n}\n\n\nmessage_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type)\n{\n\tBuffer* msg;\n\tif (!messages_queue.pop(msg)) {\n\t\tthrow Xapian::NetworkError(\"No message available\");\n\t}\n\n\tconst char *msg_str = msg->dpos();\n\tsize_t msg_size = msg->nbytes();\n\n\tstd::string message = std::string(msg_str, msg_size);\n\n\tstd::string buf(&msg->type, 1);\n\tbuf += encode_length(msg_size);\n\tbuf += message;\n\tLOG_BINARY_PROTO(this, \"get_message: '%s'\\n\", repr(buf).c_str());\n\n\tresult = message;\n\n\tmessage_type type = static_cast<message_type>(msg->type);\n\n\tdelete msg;\n\n\treturn type;\n}\n\n\nvoid BinaryClient::send_message(reply_type type, const std::string &message) {\n\tchar type_as_char = static_cast<char>(type);\n\tstd::string buf(&type_as_char, 1);\n\tbuf += encode_length(message.size());\n\tbuf += message;\n\n\tLOG_BINARY_PROTO(this, \"send_message: '%s'\\n\", repr(buf).c_str());\n\n\twrite(buf);\n}\n\n\nvoid BinaryClient::send_message(reply_type type, const std::string &message, double end_time)\n{\n\tsend_message(type, message);\n}\n\n\nvoid BinaryClient::shutdown()\n{\n\tserver->manager->async_shutdown.send();\n}\n\n\nXapian::Database * BinaryClient::get_db(bool writable_)\n{\n\tpthread_mutex_lock(&qmtx);\n\tif (endpoints.empty()) {\n\t\tpthread_mutex_unlock(&qmtx);\n\t\treturn NULL;\n\t}\n\tEndpoints endpoints_ = endpoints;\n\tpthread_mutex_unlock(&qmtx);\n\n\tDatabase *database = NULL;\n\tif (!database_pool->checkout(&database, endpoints_, writable_)) {\n\t\treturn NULL;\n\t}\n\n\tpthread_mutex_lock(&qmtx);\n\tdatabases[database->db] = database;\n\tpthread_mutex_unlock(&qmtx);\n\n\treturn database->db;\n}\n\n\nvoid BinaryClient::release_db(Xapian::Database *db_)\n{\n\tif (db_) {\n\t\tpthread_mutex_lock(&qmtx);\n\t\tDatabase *database = databases[db_];\n\t\tdatabases.erase(db_);\n\t\tpthread_mutex_unlock(&qmtx);\n\t\t\n\t\tdatabase_pool->checkin(&database);\n\t}\n}\n\n\nvoid BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_, int flags)\n{\n\tpthread_mutex_lock(&qmtx);\n\tstd::vector<std::string>::const_iterator i(dbpaths_.begin());\n\tendpoints.clear();\n\tfor (; i != dbpaths_.end(); i++) {\n\t\tEndpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_SERVERPORT);\n\t\tendpoints.push_back(endpoint);\n\t}\n\tdbpaths = dbpaths_;\n\tpthread_mutex_unlock(&qmtx);\n}\n\n\/\/ FIXME: The following is a legacy method for old 1.3.2, remove it!\nvoid BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_)\n{\n\tselect_db(dbpaths_, writable_, Xapian::DB_OPEN);\n}\n\n\nvoid BinaryClient::run()\n{\n while (true) {\n pthread_mutex_lock(&qmtx);\n if (started && messages_queue.empty()) {\n running = false;\n pthread_mutex_unlock(&qmtx);\n break;\n }\n pthread_mutex_unlock(&qmtx);\n\n try {\n if (started) {\n run_one();\n } else {\n started = true;\n msg_update(std::string());\n }\n } catch (const Xapian::NetworkError &e) {\n LOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n } catch (...) {\n LOG_ERR(this, \"ERROR!\\n\");\n }\n }\n}\n\n<commit_msg>RemoteProtocol is in a public xapian header after latest patches<commit_after>\/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <assert.h>\n#include <sys\/socket.h>\n\n#include \"server.h\"\n#include \"utils.h\"\n#include \"client_binary.h\"\n#include \"xapiand.h\"\n#include \"length.h\"\n\n\/\/\n\/\/ Xapian binary client\n\/\/\n\nBinaryClient::BinaryClient(XapiandServer *server_, ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(server_, loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_),\n\t RemoteProtocol(std::vector<std::string>(), active_timeout_, idle_timeout_, true),\n\t running(false),\n started(false)\n{\n\tpthread_mutex_lock(&XapiandServer::static_mutex);\n\tint total_clients = XapiandServer::total_clients;\n\tint binary_clients = ++XapiandServer::binary_clients;\n\tpthread_mutex_unlock(&XapiandServer::static_mutex);\n\t\n\tLOG_CONN(this, \"Got connection (sock=%d), %d binary client(s) of a total of %d connected.\\n\", sock, binary_clients, XapiandServer::total_clients);\n\n\tthread_pool->addTask(this);\n\n\tLOG_OBJ(this, \"CREATED BINARY CLIENT! (%d clients)\\n\", binary_clients);\n\tassert(binary_clients <= total_clients);\n}\n\n\nBinaryClient::~BinaryClient()\n{\n\tstd::unordered_map<Xapian::Database *, Database *>::const_iterator it(databases.begin());\n\tfor (; it != databases.end(); it++) {\n\t\tDatabase *database = it->second;\n\t\tdatabase_pool->checkin(&database);\n\t}\n\n\tpthread_mutex_lock(&XapiandServer::static_mutex);\n\tint binary_clients = --XapiandServer::binary_clients;\n\tpthread_mutex_unlock(&XapiandServer::static_mutex);\n\n\tLOG_OBJ(this, \"DELETED BINARY CLIENT! (%d clients left)\\n\", binary_clients);\n\tassert(binary_clients >= 0);\n}\n\n\nvoid BinaryClient::on_read(const char *buf, ssize_t received)\n{\n\tbuffer.append(buf, received);\n\twhile (buffer.length() >= 2) {\n\t\tconst char *o = buffer.data();\n\t\tconst char *p = o;\n\t\tconst char *p_end = p + buffer.size();\n\t\t\n\t\tmessage_type type = static_cast<message_type>(*p++);\n\t\tsize_t len = decode_length(&p, p_end, true);\n\t\tif (len == -1) {\n\t\t\treturn;\n\t\t}\n\t\tstd::string data = std::string(p, len);\n\t\tbuffer.erase(0, p - o + len);\n\t\t\n\t\tBuffer *msg = new Buffer(type, data.c_str(), data.size());\n\t\t\n\t\tmessages_queue.push(msg);\n\t}\n pthread_mutex_lock(&qmtx);\n if (!messages_queue.empty()) {\n if (!running) {\n running = true;\n thread_pool->addTask(this);\n }\n }\n pthread_mutex_unlock(&qmtx);\n}\n\n\nmessage_type BinaryClient::get_message(double timeout, std::string & result, message_type required_type)\n{\n\tBuffer* msg;\n\tif (!messages_queue.pop(msg)) {\n\t\tthrow Xapian::NetworkError(\"No message available\");\n\t}\n\n\tconst char *msg_str = msg->dpos();\n\tsize_t msg_size = msg->nbytes();\n\n\tstd::string message = std::string(msg_str, msg_size);\n\n\tstd::string buf(&msg->type, 1);\n\tbuf += encode_length(msg_size);\n\tbuf += message;\n\tLOG_BINARY_PROTO(this, \"get_message: '%s'\\n\", repr(buf).c_str());\n\n\tresult = message;\n\n\tmessage_type type = static_cast<message_type>(msg->type);\n\n\tdelete msg;\n\n\treturn type;\n}\n\n\nvoid BinaryClient::send_message(reply_type type, const std::string &message) {\n\tchar type_as_char = static_cast<char>(type);\n\tstd::string buf(&type_as_char, 1);\n\tbuf += encode_length(message.size());\n\tbuf += message;\n\n\tLOG_BINARY_PROTO(this, \"send_message: '%s'\\n\", repr(buf).c_str());\n\n\twrite(buf);\n}\n\n\nvoid BinaryClient::send_message(reply_type type, const std::string &message, double end_time)\n{\n\tsend_message(type, message);\n}\n\n\nvoid BinaryClient::shutdown()\n{\n\tserver->manager->async_shutdown.send();\n}\n\n\nXapian::Database * BinaryClient::get_db(bool writable_)\n{\n\tpthread_mutex_lock(&qmtx);\n\tif (endpoints.empty()) {\n\t\tpthread_mutex_unlock(&qmtx);\n\t\treturn NULL;\n\t}\n\tEndpoints endpoints_ = endpoints;\n\tpthread_mutex_unlock(&qmtx);\n\n\tDatabase *database = NULL;\n\tif (!database_pool->checkout(&database, endpoints_, writable_)) {\n\t\treturn NULL;\n\t}\n\n\tpthread_mutex_lock(&qmtx);\n\tdatabases[database->db] = database;\n\tpthread_mutex_unlock(&qmtx);\n\n\treturn database->db;\n}\n\n\nvoid BinaryClient::release_db(Xapian::Database *db_)\n{\n\tif (db_) {\n\t\tpthread_mutex_lock(&qmtx);\n\t\tDatabase *database = databases[db_];\n\t\tdatabases.erase(db_);\n\t\tpthread_mutex_unlock(&qmtx);\n\t\t\n\t\tdatabase_pool->checkin(&database);\n\t}\n}\n\n\nvoid BinaryClient::select_db(const std::vector<std::string> &dbpaths_, bool writable_, int flags)\n{\n\tpthread_mutex_lock(&qmtx);\n\tstd::vector<std::string>::const_iterator i(dbpaths_.begin());\n\tendpoints.clear();\n\tfor (; i != dbpaths_.end(); i++) {\n\t\tEndpoint endpoint = Endpoint(*i, std::string(), XAPIAND_BINARY_SERVERPORT);\n\t\tendpoints.push_back(endpoint);\n\t}\n\tdbpaths = dbpaths_;\n\tpthread_mutex_unlock(&qmtx);\n}\n\n\nvoid BinaryClient::run()\n{\n while (true) {\n pthread_mutex_lock(&qmtx);\n if (started && messages_queue.empty()) {\n running = false;\n pthread_mutex_unlock(&qmtx);\n break;\n }\n pthread_mutex_unlock(&qmtx);\n\n try {\n if (started) {\n run_one();\n } else {\n started = true;\n msg_update(std::string());\n }\n } catch (const Xapian::NetworkError &e) {\n LOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n } catch (...) {\n LOG_ERR(this, \"ERROR!\\n\");\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"graycom.h\"\r\n\r\n#ifndef _WIN32\r\n#include <errno.h>\t\/\/ errno\r\n#endif\r\n\r\n\r\nbool CFile::SetFilePath( LPCTSTR pszName )\r\n{\r\n\tADDTOCALLSTACK(\"CFile::SetFilePath\");\r\n\tif ( pszName == NULL )\r\n\t\treturn false;\r\n\tif ( ! m_strFileName.CompareNoCase( pszName ))\r\n\t\treturn( true );\r\n\tbool fIsOpen = ( m_hFile != NOFILE_HANDLE );\r\n\tif ( fIsOpen )\r\n\t{\r\n\t\tClose();\r\n\t}\r\n\tm_strFileName = pszName;\r\n\tif ( fIsOpen )\r\n\t{\r\n\t\treturn( Open( NULL, OF_READ|OF_BINARY )); \/\/ GetMode()\t\/\/ open it back up. (in same mode as before)\r\n\t}\r\n\treturn( true );\r\n}\r\n\r\nLPCTSTR CFile::GetFileTitle() const\r\n{\r\n\tADDTOCALLSTACK(\"CFile::GetFileTitle\");\r\n\treturn( CGFile::GetFilesTitle( GetFilePath()));\r\n}\r\n\r\nbool CFile::Open( LPCTSTR pszName, UINT uMode, CFileException * e )\r\n{\r\n\tUNREFERENCED_PARAMETER(e);\r\n\tASSERT( m_hFile == NOFILE_HANDLE );\r\n\tSetFilePath( pszName );\r\n\r\n#ifdef _WIN32\r\n\tDWORD dwShareMode, dwCreationDisposition, dwDesiredAccess;\r\n\r\n\tdwDesiredAccess = GENERIC_READ;\r\n\tif ( uMode & OF_WRITE )\r\n\t\tdwDesiredAccess |= GENERIC_WRITE;\r\n\tif ( uMode & OF_READWRITE )\r\n\t\tdwDesiredAccess |= (GENERIC_READ | GENERIC_WRITE);\r\n\r\n\tif ( uMode & OF_SHARE_COMPAT )\r\n\t\tdwShareMode = (FILE_SHARE_READ | FILE_SHARE_WRITE);\r\n\telse if ( uMode & OF_SHARE_EXCLUSIVE )\r\n\t\tdwShareMode = 0;\r\n\telse if ( uMode & OF_SHARE_DENY_WRITE )\r\n\t\tdwShareMode = FILE_SHARE_READ;\r\n\telse if ( uMode & OF_SHARE_DENY_READ )\r\n\t\tdwShareMode = FILE_SHARE_WRITE;\r\n\telse if ( uMode & OF_SHARE_DENY_NONE )\r\n\t\tdwShareMode = (FILE_SHARE_READ | FILE_SHARE_WRITE);\r\n\telse\r\n\t\tdwShareMode = 0;\r\n\r\n\tif ( uMode & OF_CREATE )\r\n\t\tdwCreationDisposition = (OPEN_ALWAYS|CREATE_NEW);\r\n\telse\r\n\t\tdwCreationDisposition = OPEN_EXISTING;\r\n\r\n\tm_hFile = CreateFile( GetFilePath(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL );\r\n#else \/\/ _WIN32\r\n\tm_hFile = open( GetFilePath(), uMode );\r\n#endif \/\/ _WIN32\r\n\treturn( m_hFile != NOFILE_HANDLE );\r\n}\r\n\r\nvoid CFile::Close()\r\n{\r\n\tif ( m_hFile != NOFILE_HANDLE )\r\n\t{\r\n#ifdef _WIN32\r\n\t\tCloseHandle( m_hFile );\r\n#else\r\n\t\tclose( m_hFile );\r\n#endif\r\n\t\tm_hFile = NOFILE_HANDLE;\r\n\t}\r\n}\r\n\r\nDWORD CFile::GetLength()\r\n{\r\n\t\/\/ Get the size of the file.\r\n\tDWORD lPos = GetPosition();\t\/\/ save current pos.\r\n\tDWORD lSize = SeekToEnd();\r\n\tSeek( lPos, SEEK_SET );\t\/\/ restore previous pos.\r\n\treturn( lSize );\r\n}\r\n\r\nDWORD CFile::GetPosition() const\r\n{\r\n#ifdef _WIN32\r\n\treturn SetFilePointer( m_hFile, 0, NULL, FILE_CURRENT );\r\n#else\r\n\treturn( lseek( m_hFile, 0, SEEK_CUR ) );\r\n#endif\r\n}\r\n\r\nDWORD CFile::Seek( LONG lOffset, UINT iOrigin )\r\n{\r\n#ifdef _WIN32\r\n\treturn SetFilePointer( m_hFile, lOffset, NULL, iOrigin );\r\n#else\r\n\tif ( m_hFile <= 0 )\r\n\t\treturn( -1 );\r\n\treturn( lseek( m_hFile, lOffset, iOrigin ));\r\n#endif\r\n}\r\n\r\nDWORD CFile::Read( void * pData, DWORD dwLength ) const\r\n{\r\n#ifdef _WIN32\r\n\tDWORD dwRead;\r\n\tif ( ! ReadFile( m_hFile, pData, dwLength, &dwRead, NULL ))\r\n\t{\r\n\t\tNotifyIOError(\"read\");\r\n\t\treturn 0;\r\n\t}\r\n\treturn dwRead;\r\n#else\r\n\treturn( read( m_hFile, pData, (long) dwLength ));\r\n#endif\r\n}\r\n\r\nbool CFile::Write( const void * pData, DWORD dwLength ) const\r\n{\r\n#ifdef _WIN32\r\n\tDWORD dwWritten;\r\n\tBOOL ret = ::WriteFile( m_hFile, pData, dwLength, &dwWritten, NULL );\r\n\tif ( ret == FALSE )\r\n\t{\r\n\t\tNotifyIOError(\"write\");\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n#else\r\n\treturn( write( m_hFile, (const char *) pData, (long) dwLength ) == (long) dwLength );\r\n#endif\r\n}\r\n\r\n#ifdef _WIN32\r\nvoid CFile::NotifyIOError( LPCTSTR szMessage )\r\n{\r\n\tLPVOID lpMsgBuf;\r\n\tFormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL );\r\n\tDEBUG_ERR(( \"File I\/O \\\"%s\\\" failed on file \\\"%s\\\" (%ld): %s\\n\", szMessage, static_cast<LPCTSTR>(GetFilePath()), GetLastError(), static_cast<LPTSTR>(lpMsgBuf) ));\r\n\r\n\tLocalFree( lpMsgBuf );\r\n}\r\n#endif\r\n\r\n\r\n\/\/***************************************************************************\r\n\/\/ -CGFile\r\n\r\nint CGFile::GetLastError()\t\/\/ static\r\n{\r\n#ifdef _WIN32\r\n\treturn ::GetLastError();\r\n#else\r\n\treturn errno;\r\n#endif\r\n}\r\n\r\nCGString CGFile::GetMergedFileName( LPCTSTR pszBase, LPCTSTR pszName ) \/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetMergedFileName\");\r\n\t\/\/ Merge path and file name.\r\n\r\n\tTCHAR szFilePath[ _MAX_PATH ];\r\n\tif ( pszBase && pszBase[0] )\r\n\t{\r\n\t\tstrcpy( szFilePath, pszBase );\r\n\t\tint len = static_cast<int>(strlen( szFilePath ));\r\n\t\tif ( len && szFilePath[ len-1 ] != '\\\\' &&\r\n\t\t\tszFilePath[ len-1 ] != '\/' )\t\/\/ Might be LINUX\r\n\t\t{\r\n\t\t\tstrcat( szFilePath, \"\\\\\" );\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tszFilePath[0] = '\\0';\r\n\t}\r\n\tif ( pszName )\r\n\t{\r\n\t\tstrcat( szFilePath, pszName );\r\n\t}\r\n\treturn static_cast<CGString>(szFilePath);\r\n}\r\n\r\nLPCTSTR CGFile::GetFilesTitle( LPCTSTR pszPath )\t\/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFilesTitle\");\r\n\t\/\/ Just use COMMDLG.H GetFileTitle(LPCTSTR, LPTSTR, WORD) instead ?\r\n\t\/\/ strrchr\r\n\tsize_t len = strlen(pszPath);\r\n\twhile ( len > 0 )\r\n\t{\r\n\t\tlen--;\r\n\t\tif ( pszPath[len] == '\\\\' || pszPath[len] == '\/' )\r\n\t\t{\r\n\t\t\tlen++;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn( pszPath + len );\r\n}\r\n\r\nLPCTSTR CGFile::GetFilesExt( LPCTSTR pszName )\t\/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFilesExt\");\r\n\t\/\/ get the EXTension including the .\r\n\tsize_t lenall = strlen( pszName );\r\n\tsize_t len = lenall;\r\n\twhile ( len > 0 )\r\n\t{\r\n\t\tlen--;\r\n\t\tif ( pszName[len] == '\\\\' || pszName[len] == '\/' )\r\n\t\t\tbreak;\r\n\t\tif ( pszName[len] == '.' )\r\n\t\t{\r\n\t\t\treturn( pszName + len );\r\n\t\t}\r\n\t}\r\n\treturn( NULL );\t\/\/ has no ext.\r\n}\r\n\r\nLPCTSTR CGFile::GetFileExt() const\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFileExt\");\r\n\t\/\/ get the EXTension including the .\r\n\treturn( GetFilesExt( GetFilePath()));\r\n}\r\n\r\n\r\nbool CGFile::OpenBase( void * pExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::OpenBase\");\r\n\tUNREFERENCED_PARAMETER(pExtra);\r\n\r\n\treturn static_cast<CFile *>(this)->Open(GetFilePath(), GetMode());\r\n}\r\n\r\nvoid CGFile::CloseBase()\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::CloseBase\");\r\n\tCFile::Close();\r\n}\r\n\r\nbool CGFile::Open( LPCTSTR pszFilename, UINT uModeFlags, void FAR * pExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::Open\");\r\n\t\/\/ RETURN: true = success.\r\n\t\/\/ OF_BINARY | OF_WRITE\r\n\tif ( pszFilename == NULL )\r\n\t{\r\n\t\tif ( IsFileOpen())\r\n\t\t\treturn( true );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tClose();\t\/\/ Make sure it's closed first.\r\n\t}\r\n\r\n\tif ( pszFilename == NULL )\r\n\t\tpszFilename = GetFilePath();\r\n\telse\r\n\t\tm_strFileName = pszFilename;\r\n\r\n\tif ( m_strFileName.IsEmpty())\r\n\t\treturn( false );\r\n\r\n\tm_uMode = uModeFlags;\r\n\tif ( ! OpenBase( pExtra ))\r\n\t\treturn( false );\r\n\r\n\treturn( true );\r\n}\r\n\r\nvoid CGFile::Close()\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::Close\");\r\n\tif ( ! IsFileOpen())\r\n\t\treturn;\r\n\r\n\tCloseBase();\r\n\tm_hFile = NOFILE_HANDLE;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ -CFileText\r\n\r\nLPCTSTR CFileText::GetModeStr() const\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::GetModeStr\");\r\n\t\/\/ end of line translation is crap. ftell and fseek don't work correctly when you use it.\r\n\t\/\/ fopen() args\r\n\tif ( IsBinaryMode())\r\n\t\treturn ( IsWriteMode()) ? \"wb\" : \"rb\";\r\n\tif ( GetMode() & OF_READWRITE )\r\n\t\treturn \"a+b\";\r\n\tif ( GetMode() & OF_CREATE )\r\n\t\treturn \"w\";\r\n\tif ( IsWriteMode() )\r\n\t\treturn \"w\";\r\n\telse\r\n\t\treturn \"rb\";\t\/\/ don't parse out the \\n\\r\r\n}\r\n\r\nvoid CFileText::CloseBase()\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::CloseBase\");\r\n\tif ( IsWriteMode())\r\n\t{\r\n\t\tfflush(m_pStream);\r\n\t}\r\n\t\r\n\tfclose(m_pStream);\r\n\tm_pStream = NULL;\r\n}\r\n\r\nbool CFileText::OpenBase( void FAR * pszExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::OpenBase\");\r\n\tUNREFERENCED_PARAMETER(pszExtra);\r\n\r\n\t\/\/ Open a file.\r\n\tm_pStream = fopen( GetFilePath(), GetModeStr());\r\n\tif ( m_pStream == NULL )\r\n\t{\r\n\t\treturn( false );\r\n\t}\r\n\t\/\/ Get the low level handle for it.\r\n\tm_hFile = (OSFILE_TYPE)STDFUNC_FILENO(m_pStream);\r\n\r\n\treturn( true );\r\n}\r\n\r\nDWORD CFileText::Seek( LONG offset, UINT origin )\r\n{\r\n\t\/\/ true = success\r\n\tif ( ! IsFileOpen())\r\n\t\treturn 0;\r\n\tif ( offset < 0 )\r\n\t\treturn 0;\r\n\tif ( fseek( m_pStream, offset, origin ) != 0 )\r\n\t\treturn 0;\r\n\tlong position = ftell(m_pStream);\r\n\tif (position < 0)\r\n\t\treturn 0;\r\n\treturn position;\r\n}\r\n\r\nvoid CFileText::Flush() const\r\n{\r\n\tif ( ! IsFileOpen())\r\n\t\treturn;\r\n\tASSERT(m_pStream);\r\n\tfflush(m_pStream);\r\n}\r\n\r\nDWORD CFileText::GetPosition() const\r\n{\r\n\t\/\/ RETURN: -1 = error.\r\n\tif ( ! IsFileOpen())\r\n\t\treturn static_cast<DWORD>(-1);\r\n\treturn( ftell(m_pStream));\r\n}\r\n\r\nDWORD CFileText::Read( void * pBuffer, size_t sizemax ) const\r\n{\r\n\t\/\/ This can return: EOF(-1) constant.\r\n\t\/\/ returns the number of full items actually read\r\n\tASSERT(pBuffer);\r\n\tif ( IsEOF())\r\n\t\treturn( 0 );\t\/\/ LINUX will ASSERT if we read past end.\r\n\treturn( static_cast<DWORD>(fread( pBuffer, 1, sizemax, m_pStream )));\r\n}\r\n\r\nTCHAR * CFileText::ReadString( TCHAR * pBuffer, size_t sizemax ) const\r\n{\r\n\t\/\/ Read a line of text. NULL = EOF\r\n\tASSERT(pBuffer);\r\n\tif ( IsEOF())\r\n\t\treturn( NULL );\t\/\/ LINUX will ASSERT if we read past end.\r\n\treturn( fgets( pBuffer, static_cast<int>(sizemax), m_pStream ));\r\n}\r\n\r\n#ifndef _WIN32\r\n\tbool CFileText::Write( const void * pData, DWORD iLen ) const\r\n#else\r\n\tbool CFileText::Write( const void * pData, DWORD iLen )\r\n#endif\r\n{\r\n\t\/\/ RETURN: 1 = success else fail.\r\n\tASSERT(pData);\r\n\tif ( ! IsFileOpen())\r\n\t\treturn( false );\r\n#ifdef _WIN32 \/\/\tWindows flushing, the only safe mode to cancel it ;)\r\n\tif ( !bNoBuffer )\r\n\t{\r\n\t\tsetvbuf(m_pStream, NULL, _IONBF, 0);\r\n\t\tbNoBuffer = true;\r\n\t}\r\n#endif\r\n\tsize_t iStatus = fwrite( pData, iLen, 1, m_pStream );\r\n#ifndef _WIN32\t\/\/ However, in unix, it works\r\n\tfflush( m_pStream );\r\n#endif\r\n\treturn ( iStatus == 1 );\r\n}\r\n\r\nbool CFileText::WriteString( LPCTSTR pStr )\r\n{\r\n\t\/\/ RETURN: < 0 = failed.\r\n\tASSERT(pStr);\r\n\treturn( Write( pStr, static_cast<DWORD>(strlen( pStr ))));\r\n}\r\n\r\nbool CFileText::IsEOF() const\r\n{\r\n\tif ( ! IsFileOpen())\r\n\t\treturn( true );\r\n\treturn(( feof( m_pStream )) ? true : false );\r\n}\r\n\r\nsize_t CFileText::VPrintf( LPCTSTR pFormat, va_list args )\r\n{\r\n\tASSERT(pFormat);\r\n\tif ( ! IsFileOpen())\r\n\t\treturn static_cast<size_t>(-1);\r\n\r\n\tsize_t lenret = vfprintf( m_pStream, pFormat, args );\r\n\treturn( lenret );\r\n}\r\n\r\nsize_t _cdecl CFileText::Printf( LPCTSTR pFormat, ... )\r\n{\r\n\tASSERT(pFormat);\r\n\tva_list vargs;\r\n\tva_start( vargs, pFormat );\r\n\tsize_t iRet = VPrintf( pFormat, vargs );\r\n\tva_end( vargs );\r\n\treturn( iRet );\r\n}\r\n<commit_msg>Fix for problems with last doc commint and _WIN32 (sorry windows devs :-()<commit_after>#include \"graycom.h\"\r\n\r\n#ifndef _WIN32\r\n#include <errno.h>\t\/\/ errno\r\n#endif\r\n\r\n#include \"CString.h\"\r\n\r\nbool CFile::SetFilePath( LPCTSTR pszName )\r\n{\r\n\tADDTOCALLSTACK(\"CFile::SetFilePath\");\r\n\tif ( pszName == NULL )\r\n\t\treturn false;\r\n\tif ( ! m_strFileName.CompareNoCase( pszName ))\r\n\t\treturn( true );\r\n\tbool fIsOpen = ( m_hFile != NOFILE_HANDLE );\r\n\tif ( fIsOpen )\r\n\t{\r\n\t\tClose();\r\n\t}\r\n\tm_strFileName = pszName;\r\n\tif ( fIsOpen )\r\n\t{\r\n\t\treturn( Open( NULL, OF_READ|OF_BINARY )); \/\/ GetMode()\t\/\/ open it back up. (in same mode as before)\r\n\t}\r\n\treturn( true );\r\n}\r\n\r\nLPCTSTR CFile::GetFileTitle() const\r\n{\r\n\tADDTOCALLSTACK(\"CFile::GetFileTitle\");\r\n\treturn( CGFile::GetFilesTitle( GetFilePath()));\r\n}\r\n\r\nbool CFile::Open( LPCTSTR pszName, UINT uMode, CFileException * e )\r\n{\r\n\tUNREFERENCED_PARAMETER(e);\r\n\tASSERT( m_hFile == NOFILE_HANDLE );\r\n\tSetFilePath( pszName );\r\n\r\n#ifdef _WIN32\r\n\tDWORD dwShareMode, dwCreationDisposition, dwDesiredAccess;\r\n\r\n\tdwDesiredAccess = GENERIC_READ;\r\n\tif ( uMode & OF_WRITE )\r\n\t\tdwDesiredAccess |= GENERIC_WRITE;\r\n\tif ( uMode & OF_READWRITE )\r\n\t\tdwDesiredAccess |= (GENERIC_READ | GENERIC_WRITE);\r\n\r\n\tif ( uMode & OF_SHARE_COMPAT )\r\n\t\tdwShareMode = (FILE_SHARE_READ | FILE_SHARE_WRITE);\r\n\telse if ( uMode & OF_SHARE_EXCLUSIVE )\r\n\t\tdwShareMode = 0;\r\n\telse if ( uMode & OF_SHARE_DENY_WRITE )\r\n\t\tdwShareMode = FILE_SHARE_READ;\r\n\telse if ( uMode & OF_SHARE_DENY_READ )\r\n\t\tdwShareMode = FILE_SHARE_WRITE;\r\n\telse if ( uMode & OF_SHARE_DENY_NONE )\r\n\t\tdwShareMode = (FILE_SHARE_READ | FILE_SHARE_WRITE);\r\n\telse\r\n\t\tdwShareMode = 0;\r\n\r\n\tif ( uMode & OF_CREATE )\r\n\t\tdwCreationDisposition = (OPEN_ALWAYS|CREATE_NEW);\r\n\telse\r\n\t\tdwCreationDisposition = OPEN_EXISTING;\r\n\r\n\tm_hFile = CreateFile( GetFilePath(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL );\r\n#else \/\/ _WIN32\r\n\tm_hFile = open( GetFilePath(), uMode );\r\n#endif \/\/ _WIN32\r\n\treturn( m_hFile != NOFILE_HANDLE );\r\n}\r\n\r\nvoid CFile::Close()\r\n{\r\n\tif ( m_hFile != NOFILE_HANDLE )\r\n\t{\r\n#ifdef _WIN32\r\n\t\tCloseHandle( m_hFile );\r\n#else\r\n\t\tclose( m_hFile );\r\n#endif\r\n\t\tm_hFile = NOFILE_HANDLE;\r\n\t}\r\n}\r\n\r\nDWORD CFile::GetLength()\r\n{\r\n\t\/\/ Get the size of the file.\r\n\tDWORD lPos = GetPosition();\t\/\/ save current pos.\r\n\tDWORD lSize = SeekToEnd();\r\n\tSeek( lPos, SEEK_SET );\t\/\/ restore previous pos.\r\n\treturn( lSize );\r\n}\r\n\r\nDWORD CFile::GetPosition() const\r\n{\r\n#ifdef _WIN32\r\n\treturn SetFilePointer( m_hFile, 0, NULL, FILE_CURRENT );\r\n#else\r\n\treturn( lseek( m_hFile, 0, SEEK_CUR ) );\r\n#endif\r\n}\r\n\r\nDWORD CFile::Seek( LONG lOffset, UINT iOrigin )\r\n{\r\n#ifdef _WIN32\r\n\treturn SetFilePointer( m_hFile, lOffset, NULL, iOrigin );\r\n#else\r\n\tif ( m_hFile <= 0 )\r\n\t\treturn( -1 );\r\n\treturn( lseek( m_hFile, lOffset, iOrigin ));\r\n#endif\r\n}\r\n\r\nDWORD CFile::Read( void * pData, DWORD dwLength ) const\r\n{\r\n#ifdef _WIN32\r\n\tDWORD dwRead;\r\n\tif ( ! ReadFile( m_hFile, pData, dwLength, &dwRead, NULL ))\r\n\t{\r\n\t\tNotifyIOError(\"read\");\r\n\t\treturn 0;\r\n\t}\r\n\treturn dwRead;\r\n#else\r\n\treturn( read( m_hFile, pData, (long) dwLength ));\r\n#endif\r\n}\r\n\r\nbool CFile::Write( const void * pData, DWORD dwLength ) const\r\n{\r\n#ifdef _WIN32\r\n\tDWORD dwWritten;\r\n\tBOOL ret = ::WriteFile( m_hFile, pData, dwLength, &dwWritten, NULL );\r\n\tif ( ret == FALSE )\r\n\t{\r\n\t\tNotifyIOError(\"write\");\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n#else\r\n\treturn( write( m_hFile, (const char *) pData, (long) dwLength ) == (long) dwLength );\r\n#endif\r\n}\r\n\r\n#ifdef _WIN32\r\nvoid CFile::NotifyIOError( LPCTSTR szMessage ) const\r\n{\r\n\tLPVOID lpMsgBuf;\r\n\tFormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL );\r\n\tDEBUG_ERR(( \"File I\/O \\\"%s\\\" failed on file \\\"%s\\\" (%ld): %s\\n\", szMessage, static_cast<LPCTSTR>(GetFilePath()), GetLastError(), static_cast<LPTSTR>(lpMsgBuf) ));\r\n\r\n\tLocalFree( lpMsgBuf );\r\n}\r\n#endif\r\n\r\n\r\n\/\/***************************************************************************\r\n\/\/ -CGFile\r\n\r\nint CGFile::GetLastError()\t\/\/ static\r\n{\r\n#ifdef _WIN32\r\n\treturn ::GetLastError();\r\n#else\r\n\treturn errno;\r\n#endif\r\n}\r\n\r\nCGString CGFile::GetMergedFileName( LPCTSTR pszBase, LPCTSTR pszName ) \/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetMergedFileName\");\r\n\t\/\/ Merge path and file name.\r\n\r\n\tTCHAR szFilePath[ _MAX_PATH ];\r\n\tif ( pszBase && pszBase[0] )\r\n\t{\r\n\t\tstrcpy( szFilePath, pszBase );\r\n\t\tint len = static_cast<int>(strlen( szFilePath ));\r\n\t\tif ( len && szFilePath[ len-1 ] != '\\\\' &&\r\n\t\t\tszFilePath[ len-1 ] != '\/' )\t\/\/ Might be LINUX\r\n\t\t{\r\n\t\t\tstrcat( szFilePath, \"\\\\\" );\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tszFilePath[0] = '\\0';\r\n\t}\r\n\tif ( pszName )\r\n\t{\r\n\t\tstrcat( szFilePath, pszName );\r\n\t}\r\n\treturn static_cast<CGString>(szFilePath);\r\n}\r\n\r\nLPCTSTR CGFile::GetFilesTitle( LPCTSTR pszPath )\t\/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFilesTitle\");\r\n\t\/\/ Just use COMMDLG.H GetFileTitle(LPCTSTR, LPTSTR, WORD) instead ?\r\n\t\/\/ strrchr\r\n\tsize_t len = strlen(pszPath);\r\n\twhile ( len > 0 )\r\n\t{\r\n\t\tlen--;\r\n\t\tif ( pszPath[len] == '\\\\' || pszPath[len] == '\/' )\r\n\t\t{\r\n\t\t\tlen++;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn( pszPath + len );\r\n}\r\n\r\nLPCTSTR CGFile::GetFilesExt( LPCTSTR pszName )\t\/\/ static\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFilesExt\");\r\n\t\/\/ get the EXTension including the .\r\n\tsize_t lenall = strlen( pszName );\r\n\tsize_t len = lenall;\r\n\twhile ( len > 0 )\r\n\t{\r\n\t\tlen--;\r\n\t\tif ( pszName[len] == '\\\\' || pszName[len] == '\/' )\r\n\t\t\tbreak;\r\n\t\tif ( pszName[len] == '.' )\r\n\t\t{\r\n\t\t\treturn( pszName + len );\r\n\t\t}\r\n\t}\r\n\treturn( NULL );\t\/\/ has no ext.\r\n}\r\n\r\nLPCTSTR CGFile::GetFileExt() const\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::GetFileExt\");\r\n\t\/\/ get the EXTension including the .\r\n\treturn( GetFilesExt( GetFilePath()));\r\n}\r\n\r\n\r\nbool CGFile::OpenBase( void * pExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::OpenBase\");\r\n\tUNREFERENCED_PARAMETER(pExtra);\r\n\r\n\treturn static_cast<CFile *>(this)->Open(GetFilePath(), GetMode());\r\n}\r\n\r\nvoid CGFile::CloseBase()\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::CloseBase\");\r\n\tCFile::Close();\r\n}\r\n\r\nbool CGFile::Open( LPCTSTR pszFilename, UINT uModeFlags, void FAR * pExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::Open\");\r\n\t\/\/ RETURN: true = success.\r\n\t\/\/ OF_BINARY | OF_WRITE\r\n\tif ( pszFilename == NULL )\r\n\t{\r\n\t\tif ( IsFileOpen())\r\n\t\t\treturn( true );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tClose();\t\/\/ Make sure it's closed first.\r\n\t}\r\n\r\n\tif ( pszFilename == NULL )\r\n\t\tpszFilename = GetFilePath();\r\n\telse\r\n\t\tm_strFileName = pszFilename;\r\n\r\n\tif ( m_strFileName.IsEmpty())\r\n\t\treturn( false );\r\n\r\n\tm_uMode = uModeFlags;\r\n\tif ( ! OpenBase( pExtra ))\r\n\t\treturn( false );\r\n\r\n\treturn( true );\r\n}\r\n\r\nvoid CGFile::Close()\r\n{\r\n\tADDTOCALLSTACK(\"CGFile::Close\");\r\n\tif ( ! IsFileOpen())\r\n\t\treturn;\r\n\r\n\tCloseBase();\r\n\tm_hFile = NOFILE_HANDLE;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ -CFileText\r\n\r\nLPCTSTR CFileText::GetModeStr() const\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::GetModeStr\");\r\n\t\/\/ end of line translation is crap. ftell and fseek don't work correctly when you use it.\r\n\t\/\/ fopen() args\r\n\tif ( IsBinaryMode())\r\n\t\treturn ( IsWriteMode()) ? \"wb\" : \"rb\";\r\n\tif ( GetMode() & OF_READWRITE )\r\n\t\treturn \"a+b\";\r\n\tif ( GetMode() & OF_CREATE )\r\n\t\treturn \"w\";\r\n\tif ( IsWriteMode() )\r\n\t\treturn \"w\";\r\n\telse\r\n\t\treturn \"rb\";\t\/\/ don't parse out the \\n\\r\r\n}\r\n\r\nvoid CFileText::CloseBase()\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::CloseBase\");\r\n\tif ( IsWriteMode())\r\n\t{\r\n\t\tfflush(m_pStream);\r\n\t}\r\n\t\r\n\tfclose(m_pStream);\r\n\tm_pStream = NULL;\r\n}\r\n\r\nbool CFileText::OpenBase( void FAR * pszExtra )\r\n{\r\n\tADDTOCALLSTACK(\"CFileText::OpenBase\");\r\n\tUNREFERENCED_PARAMETER(pszExtra);\r\n\r\n\t\/\/ Open a file.\r\n\tm_pStream = fopen( GetFilePath(), GetModeStr());\r\n\tif ( m_pStream == NULL )\r\n\t{\r\n\t\treturn( false );\r\n\t}\r\n\t\/\/ Get the low level handle for it.\r\n\tm_hFile = (OSFILE_TYPE)STDFUNC_FILENO(m_pStream);\r\n\r\n\treturn( true );\r\n}\r\n\r\nDWORD CFileText::Seek( LONG offset, UINT origin )\r\n{\r\n\t\/\/ true = success\r\n\tif ( ! IsFileOpen())\r\n\t\treturn 0;\r\n\tif ( offset < 0 )\r\n\t\treturn 0;\r\n\tif ( fseek( m_pStream, offset, origin ) != 0 )\r\n\t\treturn 0;\r\n\tlong position = ftell(m_pStream);\r\n\tif (position < 0)\r\n\t\treturn 0;\r\n\treturn position;\r\n}\r\n\r\nvoid CFileText::Flush() const\r\n{\r\n\tif ( ! IsFileOpen())\r\n\t\treturn;\r\n\tASSERT(m_pStream);\r\n\tfflush(m_pStream);\r\n}\r\n\r\nDWORD CFileText::GetPosition() const\r\n{\r\n\t\/\/ RETURN: -1 = error.\r\n\tif ( ! IsFileOpen())\r\n\t\treturn static_cast<DWORD>(-1);\r\n\treturn( ftell(m_pStream));\r\n}\r\n\r\nDWORD CFileText::Read( void * pBuffer, size_t sizemax ) const\r\n{\r\n\t\/\/ This can return: EOF(-1) constant.\r\n\t\/\/ returns the number of full items actually read\r\n\tASSERT(pBuffer);\r\n\tif ( IsEOF())\r\n\t\treturn( 0 );\t\/\/ LINUX will ASSERT if we read past end.\r\n\treturn( static_cast<DWORD>(fread( pBuffer, 1, sizemax, m_pStream )));\r\n}\r\n\r\nTCHAR * CFileText::ReadString( TCHAR * pBuffer, size_t sizemax ) const\r\n{\r\n\t\/\/ Read a line of text. NULL = EOF\r\n\tASSERT(pBuffer);\r\n\tif ( IsEOF())\r\n\t\treturn( NULL );\t\/\/ LINUX will ASSERT if we read past end.\r\n\treturn( fgets( pBuffer, static_cast<int>(sizemax), m_pStream ));\r\n}\r\n\r\n#ifndef _WIN32\r\n\tbool CFileText::Write( const void * pData, DWORD iLen ) const\r\n#else\r\n\tbool CFileText::Write( const void * pData, DWORD iLen )\r\n#endif\r\n{\r\n\t\/\/ RETURN: 1 = success else fail.\r\n\tASSERT(pData);\r\n\tif ( ! IsFileOpen())\r\n\t\treturn( false );\r\n#ifdef _WIN32 \/\/\tWindows flushing, the only safe mode to cancel it ;)\r\n\tif ( !bNoBuffer )\r\n\t{\r\n\t\tsetvbuf(m_pStream, NULL, _IONBF, 0);\r\n\t\tbNoBuffer = true;\r\n\t}\r\n#endif\r\n\tsize_t iStatus = fwrite( pData, iLen, 1, m_pStream );\r\n#ifndef _WIN32\t\/\/ However, in unix, it works\r\n\tfflush( m_pStream );\r\n#endif\r\n\treturn ( iStatus == 1 );\r\n}\r\n\r\nbool CFileText::WriteString( LPCTSTR pStr )\r\n{\r\n\t\/\/ RETURN: < 0 = failed.\r\n\tASSERT(pStr);\r\n\treturn( Write( pStr, static_cast<DWORD>(strlen( pStr ))));\r\n}\r\n\r\nbool CFileText::IsEOF() const\r\n{\r\n\tif ( ! IsFileOpen())\r\n\t\treturn( true );\r\n\treturn(( feof( m_pStream )) ? true : false );\r\n}\r\n\r\nsize_t CFileText::VPrintf( LPCTSTR pFormat, va_list args )\r\n{\r\n\tASSERT(pFormat);\r\n\tif ( ! IsFileOpen())\r\n\t\treturn static_cast<size_t>(-1);\r\n\r\n\tsize_t lenret = vfprintf( m_pStream, pFormat, args );\r\n\treturn( lenret );\r\n}\r\n\r\nsize_t _cdecl CFileText::Printf( LPCTSTR pFormat, ... )\r\n{\r\n\tASSERT(pFormat);\r\n\tva_list vargs;\r\n\tva_start( vargs, pFormat );\r\n\tsize_t iRet = VPrintf( pFormat, vargs );\r\n\tva_end( vargs );\r\n\treturn( iRet );\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ______ __ __ __\n * \/\\ _ \\ __ \/\\ \\\/\\ \\ \/\\ \\__\n * \\ \\ \\L\\ \\ __ __ \/\\_\\ \\_\\ \\ \\ \\____ ___\\ \\ ,_\\ ____\n * \\ \\ __ \\\/\\ \\\/\\ \\\\\/\\ \\ \/'_` \\ \\ '__`\\ \/ __`\\ \\ \\\/ \/',__\\\n * \\ \\ \\\/\\ \\ \\ \\_\/ |\\ \\ \\\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\ \\ \\_\/\\__, `\\\n * \\ \\_\\ \\_\\ \\___\/ \\ \\_\\ \\___,_\\ \\_,__\/\\ \\____\/\\ \\__\\\/\\____\/\n * \\\/_\/\\\/_\/\\\/__\/ \\\/_\/\\\/__,_ \/\\\/___\/ \\\/___\/ \\\/__\/\\\/___\/\n * @copyright Copyright 2017 Avidbots Corp.\n * @name service_manager_test.cpp\n * @brief Testing service manager functionalities\n * @author Chunshang Li\n *\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2017, Avidbots Corp.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Avidbots Corp. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <flatland_msgs\/DeleteModel.h>\n#include <flatland_msgs\/MoveModel.h>\n#include <flatland_msgs\/SpawnModel.h>\n#include <flatland_server\/simulation_manager.h>\n#include <flatland_server\/timekeeper.h>\n#include <flatland_server\/world.h>\n#include <gtest\/gtest.h>\n#include <regex>\n#include <thread>\n\nnamespace fs = boost::filesystem;\nusing namespace flatland_server;\n\nclass ServiceManagerTest : public ::testing::Test {\n protected:\n SimulationManager* sim_man;\n boost::filesystem::path this_file_dir;\n boost::filesystem::path world_yaml;\n boost::filesystem::path robot_yaml;\n Timekeeper timekeeper;\n ros::NodeHandle nh;\n ros::ServiceClient client;\n std::thread simulation_thread;\n\n void SetUp() override {\n sim_man = nullptr;\n this_file_dir = boost::filesystem::path(__FILE__).parent_path();\n timekeeper.SetMaxStepSize(1.0);\n }\n\n void TearDown() override {\n StopSimulationThread();\n if (sim_man) delete sim_man;\n }\n\n void StartSimulationThread() {\n sim_man =\n new SimulationManager(world_yaml.string(), 1000, 1 \/ 1000.0, false, 0);\n simulation_thread = std::thread(&ServiceManagerTest::SimulationThread,\n dynamic_cast<ServiceManagerTest*>(this));\n }\n\n void StopSimulationThread() {\n sim_man->Shutdown();\n simulation_thread.join();\n }\n\n void SimulationThread() { sim_man->Main(); }\n};\n\n\/**\n * Testing service for loading a model which should succeed\n *\/\nTEST_F(ServiceManagerTest, spawn_valid_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n robot_yaml = this_file_dir \/\n fs::path(\"load_world_tests\/simple_test_A\/person.model.yaml\");\n\n flatland_msgs::SpawnModel srv;\n\n srv.request.name = \"service_manager_test_robot\";\n srv.request.ns = \"robot123\";\n srv.request.yaml_path = robot_yaml.string();\n srv.request.pose.x = 101.1;\n srv.request.pose.y = 102.1;\n srv.request.pose.theta = 0.23;\n\n client = nh.serviceClient<flatland_msgs::SpawnModel>(\"spawn_model\");\n\n \/\/ Threading is required since client.call blocks executing until return\n StartSimulationThread();\n\n ros::service::waitForService(\"spawn_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n ASSERT_STREQ(\"\", srv.response.message.c_str());\n\n World* w = sim_man->world_;\n ASSERT_EQ(5, w->models_.size());\n EXPECT_STREQ(\"service_manager_test_robot\", w->models_[4]->name_.c_str());\n EXPECT_STREQ(\"robot123\", w->models_[4]->namespace_.c_str());\n EXPECT_FLOAT_EQ(101.1,\n w->models_[4]->bodies_[0]->physics_body_->GetPosition().x);\n EXPECT_FLOAT_EQ(102.1,\n w->models_[4]->bodies_[0]->physics_body_->GetPosition().y);\n EXPECT_FLOAT_EQ(0.23, w->models_[4]->bodies_[0]->physics_body_->GetAngle());\n EXPECT_EQ(1, w->models_[4]->bodies_.size());\n}\n\n\/**\n * Testing service for loading a model which should fail\n *\/\nTEST_F(ServiceManagerTest, spawn_invalid_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n robot_yaml = this_file_dir \/ fs::path(\"random_path\/turtlebot.model.yaml\");\n\n flatland_msgs::SpawnModel srv;\n\n srv.request.name = \"service_manager_test_robot\";\n srv.request.yaml_path = robot_yaml.string();\n srv.request.pose.x = 1;\n srv.request.pose.y = 2;\n srv.request.pose.theta = 3;\n\n client = nh.serviceClient<flatland_msgs::SpawnModel>(\"spawn_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"spawn_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n\n std::cmatch match;\n std::string regex_str =\n \"Flatland YAML: File does not exist, \"\n \"path=\\\".*\/random_path\/turtlebot.model.yaml\\\".*\";\n std::regex regex(regex_str);\n EXPECT_TRUE(std::regex_match(srv.response.message.c_str(), match, regex))\n << \"Error Message '\" + srv.response.message + \"'\" +\n \" did not match against regex '\" + regex_str + \"'\";\n}\n\n\/**\n * Testing service for moving a valid model\n *\/\nTEST_F(ServiceManagerTest, move_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n flatland_msgs::MoveModel srv;\n srv.request.name = \"turtlebot1\";\n srv.request.pose.x = 5.5;\n srv.request.pose.y = 9.9;\n srv.request.pose.theta = 0.77;\n\n client = nh.serviceClient<flatland_msgs::MoveModel>(\"move_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"move_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n\n World* w = sim_man->world_;\n EXPECT_NEAR(5.5, w->models_[0]->bodies_[0]->physics_body_->GetPosition().x,\n 1e-4);\n EXPECT_NEAR(9.9, w->models_[0]->bodies_[0]->physics_body_->GetPosition().y,\n 1e-4);\n EXPECT_NEAR(0.77, w->models_[0]->bodies_[0]->physics_body_->GetAngle(), 1e-2);\n}\n\n\/**\n * Testing service for moving a nonexistent model\n *\/\nTEST_F(ServiceManagerTest, move_nonexistent_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n flatland_msgs::MoveModel srv;\n srv.request.name = \"not_a_robot\";\n srv.request.pose.x = 4;\n srv.request.pose.y = 5;\n srv.request.pose.theta = 0;\n\n client = nh.serviceClient<flatland_msgs::MoveModel>(\"move_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"move_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n EXPECT_STREQ(\n \"Flatland World: failed to move model, model with name \"\n \"\\\"not_a_robot\\\" does not exist\",\n srv.response.message.c_str());\n}\n\n\/**\n * Testing service for deleting a model\n *\/\nTEST_F(ServiceManagerTest, delete_model) {\n world_yaml = this_file_dir \/\n fs::path(\"plugin_manager_tests\/load_dummy_test\/world.yaml\");\n\n flatland_msgs::DeleteModel srv;\n srv.request.name = \"turtlebot1\";\n\n client = nh.serviceClient<flatland_msgs::DeleteModel>(\"delete_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"delete_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n World* w = sim_man->world_;\n \/\/ after deleting a mode, there should be one less model, and one less plugin\n ASSERT_EQ(w->models_.size(), 0);\n ASSERT_EQ(w->plugin_manager_.model_plugins_.size(), 0);\n int count = std::count_if(w->models_.begin(), w->models_.end(),\n [](Model* m) { return m->name_ == \"turtlebot1\"; });\n ASSERT_EQ(count, 0);\n}\n\n\/**\n * Testing service for deleting a model that does not exist, should fail\n *\/\nTEST_F(ServiceManagerTest, delete_nonexistent_model) {\n world_yaml = this_file_dir \/\n fs::path(\"plugin_manager_tests\/load_dummy_test\/world.yaml\");\n\n flatland_msgs::DeleteModel srv;\n srv.request.name = \"random_model\";\n\n client = nh.serviceClient<flatland_msgs::DeleteModel>(\"delete_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"delete_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n EXPECT_STREQ(\n \"Flatland World: failed to delete model, model with name \"\n \"\\\"random_model\\\" does not exist\",\n srv.response.message.c_str());\n}\n\n\/\/ Run all the tests that were declared with TEST()\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"service_manager_test\");\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>Loosened MoveModel unit test tolerance from 1e-4 to 0.01 meters<commit_after>\/*\n * ______ __ __ __\n * \/\\ _ \\ __ \/\\ \\\/\\ \\ \/\\ \\__\n * \\ \\ \\L\\ \\ __ __ \/\\_\\ \\_\\ \\ \\ \\____ ___\\ \\ ,_\\ ____\n * \\ \\ __ \\\/\\ \\\/\\ \\\\\/\\ \\ \/'_` \\ \\ '__`\\ \/ __`\\ \\ \\\/ \/',__\\\n * \\ \\ \\\/\\ \\ \\ \\_\/ |\\ \\ \\\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\ \\ \\_\/\\__, `\\\n * \\ \\_\\ \\_\\ \\___\/ \\ \\_\\ \\___,_\\ \\_,__\/\\ \\____\/\\ \\__\\\/\\____\/\n * \\\/_\/\\\/_\/\\\/__\/ \\\/_\/\\\/__,_ \/\\\/___\/ \\\/___\/ \\\/__\/\\\/___\/\n * @copyright Copyright 2017 Avidbots Corp.\n * @name service_manager_test.cpp\n * @brief Testing service manager functionalities\n * @author Chunshang Li\n *\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2017, Avidbots Corp.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Avidbots Corp. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <flatland_msgs\/DeleteModel.h>\n#include <flatland_msgs\/MoveModel.h>\n#include <flatland_msgs\/SpawnModel.h>\n#include <flatland_server\/simulation_manager.h>\n#include <flatland_server\/timekeeper.h>\n#include <flatland_server\/world.h>\n#include <gtest\/gtest.h>\n#include <regex>\n#include <thread>\n\nnamespace fs = boost::filesystem;\nusing namespace flatland_server;\n\nclass ServiceManagerTest : public ::testing::Test {\n protected:\n SimulationManager* sim_man;\n boost::filesystem::path this_file_dir;\n boost::filesystem::path world_yaml;\n boost::filesystem::path robot_yaml;\n Timekeeper timekeeper;\n ros::NodeHandle nh;\n ros::ServiceClient client;\n std::thread simulation_thread;\n\n void SetUp() override {\n sim_man = nullptr;\n this_file_dir = boost::filesystem::path(__FILE__).parent_path();\n timekeeper.SetMaxStepSize(1.0);\n }\n\n void TearDown() override {\n StopSimulationThread();\n if (sim_man) delete sim_man;\n }\n\n void StartSimulationThread() {\n sim_man =\n new SimulationManager(world_yaml.string(), 1000, 1 \/ 1000.0, false, 0);\n simulation_thread = std::thread(&ServiceManagerTest::SimulationThread,\n dynamic_cast<ServiceManagerTest*>(this));\n }\n\n void StopSimulationThread() {\n sim_man->Shutdown();\n simulation_thread.join();\n }\n\n void SimulationThread() { sim_man->Main(); }\n};\n\n\/**\n * Testing service for loading a model which should succeed\n *\/\nTEST_F(ServiceManagerTest, spawn_valid_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n robot_yaml = this_file_dir \/\n fs::path(\"load_world_tests\/simple_test_A\/person.model.yaml\");\n\n flatland_msgs::SpawnModel srv;\n\n srv.request.name = \"service_manager_test_robot\";\n srv.request.ns = \"robot123\";\n srv.request.yaml_path = robot_yaml.string();\n srv.request.pose.x = 101.1;\n srv.request.pose.y = 102.1;\n srv.request.pose.theta = 0.23;\n\n client = nh.serviceClient<flatland_msgs::SpawnModel>(\"spawn_model\");\n\n \/\/ Threading is required since client.call blocks executing until return\n StartSimulationThread();\n\n ros::service::waitForService(\"spawn_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n ASSERT_STREQ(\"\", srv.response.message.c_str());\n\n World* w = sim_man->world_;\n ASSERT_EQ(5, w->models_.size());\n EXPECT_STREQ(\"service_manager_test_robot\", w->models_[4]->name_.c_str());\n EXPECT_STREQ(\"robot123\", w->models_[4]->namespace_.c_str());\n EXPECT_FLOAT_EQ(101.1,\n w->models_[4]->bodies_[0]->physics_body_->GetPosition().x);\n EXPECT_FLOAT_EQ(102.1,\n w->models_[4]->bodies_[0]->physics_body_->GetPosition().y);\n EXPECT_FLOAT_EQ(0.23, w->models_[4]->bodies_[0]->physics_body_->GetAngle());\n EXPECT_EQ(1, w->models_[4]->bodies_.size());\n}\n\n\/**\n * Testing service for loading a model which should fail\n *\/\nTEST_F(ServiceManagerTest, spawn_invalid_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n robot_yaml = this_file_dir \/ fs::path(\"random_path\/turtlebot.model.yaml\");\n\n flatland_msgs::SpawnModel srv;\n\n srv.request.name = \"service_manager_test_robot\";\n srv.request.yaml_path = robot_yaml.string();\n srv.request.pose.x = 1;\n srv.request.pose.y = 2;\n srv.request.pose.theta = 3;\n\n client = nh.serviceClient<flatland_msgs::SpawnModel>(\"spawn_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"spawn_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n\n std::cmatch match;\n std::string regex_str =\n \"Flatland YAML: File does not exist, \"\n \"path=\\\".*\/random_path\/turtlebot.model.yaml\\\".*\";\n std::regex regex(regex_str);\n EXPECT_TRUE(std::regex_match(srv.response.message.c_str(), match, regex))\n << \"Error Message '\" + srv.response.message + \"'\" +\n \" did not match against regex '\" + regex_str + \"'\";\n}\n\n\/**\n * Testing service for moving a valid model\n *\/\nTEST_F(ServiceManagerTest, move_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n flatland_msgs::MoveModel srv;\n srv.request.name = \"turtlebot1\";\n srv.request.pose.x = 5.5;\n srv.request.pose.y = 9.9;\n srv.request.pose.theta = 0.77;\n\n client = nh.serviceClient<flatland_msgs::MoveModel>(\"move_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"move_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n\n World* w = sim_man->world_;\n EXPECT_NEAR(5.5, w->models_[0]->bodies_[0]->physics_body_->GetPosition().x,\n 1e-2);\n EXPECT_NEAR(9.9, w->models_[0]->bodies_[0]->physics_body_->GetPosition().y,\n 1e-2);\n EXPECT_NEAR(0.77, w->models_[0]->bodies_[0]->physics_body_->GetAngle(), 1e-2);\n}\n\n\/**\n * Testing service for moving a nonexistent model\n *\/\nTEST_F(ServiceManagerTest, move_nonexistent_model) {\n world_yaml =\n this_file_dir \/ fs::path(\"load_world_tests\/simple_test_A\/world.yaml\");\n\n flatland_msgs::MoveModel srv;\n srv.request.name = \"not_a_robot\";\n srv.request.pose.x = 4;\n srv.request.pose.y = 5;\n srv.request.pose.theta = 0;\n\n client = nh.serviceClient<flatland_msgs::MoveModel>(\"move_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"move_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n EXPECT_STREQ(\n \"Flatland World: failed to move model, model with name \"\n \"\\\"not_a_robot\\\" does not exist\",\n srv.response.message.c_str());\n}\n\n\/**\n * Testing service for deleting a model\n *\/\nTEST_F(ServiceManagerTest, delete_model) {\n world_yaml = this_file_dir \/\n fs::path(\"plugin_manager_tests\/load_dummy_test\/world.yaml\");\n\n flatland_msgs::DeleteModel srv;\n srv.request.name = \"turtlebot1\";\n\n client = nh.serviceClient<flatland_msgs::DeleteModel>(\"delete_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"delete_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_TRUE(srv.response.success);\n World* w = sim_man->world_;\n \/\/ after deleting a mode, there should be one less model, and one less plugin\n ASSERT_EQ(w->models_.size(), 0);\n ASSERT_EQ(w->plugin_manager_.model_plugins_.size(), 0);\n int count = std::count_if(w->models_.begin(), w->models_.end(),\n [](Model* m) { return m->name_ == \"turtlebot1\"; });\n ASSERT_EQ(count, 0);\n}\n\n\/**\n * Testing service for deleting a model that does not exist, should fail\n *\/\nTEST_F(ServiceManagerTest, delete_nonexistent_model) {\n world_yaml = this_file_dir \/\n fs::path(\"plugin_manager_tests\/load_dummy_test\/world.yaml\");\n\n flatland_msgs::DeleteModel srv;\n srv.request.name = \"random_model\";\n\n client = nh.serviceClient<flatland_msgs::DeleteModel>(\"delete_model\");\n\n StartSimulationThread();\n\n ros::service::waitForService(\"delete_model\", 1000);\n ASSERT_TRUE(client.call(srv));\n\n ASSERT_FALSE(srv.response.success);\n EXPECT_STREQ(\n \"Flatland World: failed to delete model, model with name \"\n \"\\\"random_model\\\" does not exist\",\n srv.response.message.c_str());\n}\n\n\/\/ Run all the tests that were declared with TEST()\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"service_manager_test\");\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n\n#if defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf() {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*LineOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*LineOutFct) (std::string(\" \") + strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\nvoid DumpCallstackPrintf() { printf(\"DumpCallstackPrintf() not implemented in this version.\\n\"); }\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) { (*LineOutFct) (\"DumpCallstack() not implemented in this version.\"); }\n\n#endif\n\nLogger notes(1,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nusing namespace std;\n\nstatic void CoutPrintLn(const std::string& str) {\n\tcout << str << \"\\n\";\n}\n\ntemplate<int col> void ConPrintLn(const std::string& str) {\n\tCon_AddText(col, str, false);\n}\n\nLogger& Logger::flush() {\n\tif(!tLXOptions || tLXOptions->iVerbosity >= minCoutVerb) {\n\t\tPrettyPrint(prefix, buffer, CoutPrintLn);\n\t\tcout.flush();\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buffer, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(minIngameConVerb < 0)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_ERROR>);\n\t\t\telse if(minIngameConVerb == 0)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_WARNING>);\n\t\t\telse if(minIngameConVerb == 1)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_NOTIFY>);\n\t\t\telse if(minIngameConVerb < 5)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_NORMAL>);\n\t\t\telse \/\/ >=5\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_DEV>);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrintLn<CNC_DEV>);\n\t\t}\n\t}\n\tbuffer = \"\";\n\treturn *this;\n}\n<commit_msg>notes should be shown on console by default<commit_after>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n\n#if defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf() {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*LineOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*LineOutFct) (std::string(\" \") + strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\nvoid DumpCallstackPrintf() { printf(\"DumpCallstackPrintf() not implemented in this version.\\n\"); }\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) { (*LineOutFct) (\"DumpCallstack() not implemented in this version.\"); }\n\n#endif\n\nLogger notes(0,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nusing namespace std;\n\nstatic void CoutPrintLn(const std::string& str) {\n\tcout << str << \"\\n\";\n}\n\ntemplate<int col> void ConPrintLn(const std::string& str) {\n\tCon_AddText(col, str, false);\n}\n\nLogger& Logger::flush() {\n\tif(!tLXOptions || tLXOptions->iVerbosity >= minCoutVerb) {\n\t\tPrettyPrint(prefix, buffer, CoutPrintLn);\n\t\tcout.flush();\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buffer, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(minIngameConVerb < 0)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_ERROR>);\n\t\t\telse if(minIngameConVerb == 0)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_WARNING>);\n\t\t\telse if(minIngameConVerb == 1)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_NOTIFY>);\n\t\t\telse if(minIngameConVerb < 5)\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_NORMAL>);\n\t\t\telse \/\/ >=5\n\t\t\t\tPrettyPrint(prefix, buffer, ConPrintLn<CNC_DEV>);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrintLn<CNC_DEV>);\n\t\t}\n\t}\n\tbuffer = \"\";\n\treturn *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <uielement\/menubarwrapper.hxx>\n#include <threadhelp\/resetableguard.hxx>\n#include <framework\/actiontriggerhelper.hxx>\n#include <services.h>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/awt\/XSystemDependentMenuPeer.hpp>\n#include <com\/sun\/star\/awt\/XMenuBar.hpp>\n#include <com\/sun\/star\/container\/XIndexContainer.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/ui\/UIElementType.hpp>\n#include <com\/sun\/star\/frame\/ModuleManager.hpp>\n#include <com\/sun\/star\/util\/URLTransformer.hpp>\n\n#include <comphelper\/processfactory.hxx>\n#include <tools\/solar.h>\n#include <vcl\/svapp.hxx>\n#include <rtl\/logfile.hxx>\n\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::frame;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::awt;\nusing namespace com::sun::star::util;\nusing namespace ::com::sun::star::ui;\n\nnamespace framework\n{\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider\n\/\/*****************************************************************************************************************\nDEFINE_XINTERFACE_11 ( MenuBarWrapper ,\n UIConfigElementWrapperBase ,\n DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementSettings ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XComponent ),\n DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIConfigurationListener ),\n DERIVED_INTERFACE( ::com::sun::star::container::XNameAccess, ::com::sun::star::container::XElementAccess )\n )\n\nDEFINE_XTYPEPROVIDER_11 ( MenuBarWrapper ,\n ::com::sun::star::lang::XTypeProvider ,\n ::com::sun::star::ui::XUIElement ,\n ::com::sun::star::ui::XUIElementSettings ,\n ::com::sun::star::beans::XMultiPropertySet ,\n ::com::sun::star::beans::XFastPropertySet ,\n ::com::sun::star::beans::XPropertySet ,\n ::com::sun::star::lang::XInitialization ,\n ::com::sun::star::lang::XComponent ,\n ::com::sun::star::util::XUpdatable ,\n ::com::sun::star::ui::XUIConfigurationListener ,\n ::com::sun::star::container::XNameAccess\n )\n\nMenuBarWrapper::MenuBarWrapper(\n const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager\n )\n: UIConfigElementWrapperBase( UIElementType::MENUBAR,xServiceManager ),\n m_bRefreshPopupControllerCache( sal_True )\n{\n}\n\nMenuBarWrapper::~MenuBarWrapper()\n{\n}\n\nvoid SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );\n\n com::sun::star::lang::EventObject aEvent( xThis );\n m_aListenerContainer.disposeAndClear( aEvent );\n\n ResetableGuard aLock( m_aLock );\n\n m_xMenuBarManager->dispose();\n m_xMenuBarManager.clear();\n m_xConfigSource.clear();\n m_xConfigData.clear();\n\n m_xMenuBar.clear();\n m_bDisposed = sal_True;\n}\n\n\/\/void generateFullMenuBar( MenuBarManager *pMenuBarManager, MenuBar *pMenuBar )\n\/\/{\n\/\/ for (int i=0; i < pMenuBar->GetItemCount(); i++)\n\/\/ {\n\/\/ sal_Int16 nId = pMenuBar->GetItemId( i );\n\n\/\/ String aCommandLabel = pMenuBar->GetItemCommand( nId );\n\n\/\/ String label = pMenuBarManager->RetrieveLabelFromCommand( aCommandLabel );\n\/\/ pMenuBar->SetItemText( nId, label );\n\/\/ }\n\/\/}\n\n\/\/ XInitialization\nvoid SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"framework (cd100003) ::MenuBarWrapper::initialize\" );\n\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( !m_bInitialized )\n {\n rtl::OUString aModuleIdentifier;\n UIConfigElementWrapperBase::initialize( aArguments );\n\n Reference< XFrame > xFrame( m_xWeakFrame );\n if ( xFrame.is() && m_xConfigSource.is() )\n {\n \/\/ Create VCL menubar which will be filled with settings data\n MenuBar* pVCLMenuBar = 0;\n VCLXMenuBar* pAwtMenuBar = 0;\n {\n SolarMutexGuard aSolarMutexGuard;\n pVCLMenuBar = new MenuBar();\n }\n\n Reference< XModuleManager2 > xModuleManager = ModuleManager::create( comphelper::getComponentContext(m_xServiceFactory) );\n\n try\n {\n aModuleIdentifier = xModuleManager->identify( xFrame );\n }\n catch( const Exception& )\n {\n }\n\n Reference< XURLTransformer > xTrans;\n try\n {\n xTrans.set( URLTransformer::create(::comphelper::getComponentContext(m_xServiceFactory)) );\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n {\n \/\/ Fill menubar with container contents\n sal_uInt16 nId = 1;\n MenuBarManager::FillMenuWithConfiguration( nId, pVCLMenuBar, aModuleIdentifier, m_xConfigData, xTrans );\n }\n }\n catch ( const NoSuchElementException& )\n {\n }\n\n sal_Bool bMenuOnly( sal_False );\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name == \"MenuOnly\" )\n aPropValue.Value >>= bMenuOnly;\n }\n }\n\n if ( !bMenuOnly )\n {\n \/\/ Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any\n \/\/ interaction which is done by the menu bar manager. This must be requested by a special property called \"MenuOnly\". Be careful\n \/\/ a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full\n \/\/ support. This feature is currently used for \"Inplace editing\"!\n Reference< XDispatchProvider > xDispatchProvider;\n\n MenuBarManager* pMenuBarManager = new MenuBarManager( m_xServiceFactory,\n xFrame,\n xTrans,\n xDispatchProvider,\n aModuleIdentifier,\n pVCLMenuBar,\n sal_False,\n sal_True );\n\n m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );\n\n\/\/ pMenuBarManager->GenerateFullMenuHierarchy( pVCLMenuBar );\n pVCLMenuBar->Freeze();\n }\n\n \/\/ Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.\n \/\/ Don't use this toolkit menu bar or one of its functions. It is only used as a data container!\n pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );\n m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );\n }\n }\n}\n\n\/\/ XUIElementSettings\nvoid SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_xMenuBarManager.is() )\n {\n if ( m_xConfigSource.is() && m_bPersistent )\n {\n try\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n }\n catch ( const NoSuchElementException& )\n {\n }\n }\n else if ( !m_bPersistent )\n {\n \/\/ Transient menubar: do nothing\n }\n }\n}\nvoid MenuBarWrapper::impl_fillNewData()\n{\n \/\/ Transient menubar => Fill menubar with new data\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n if ( pMenuBarManager )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n}\n\n\nvoid MenuBarWrapper::fillPopupControllerCache()\n{\n if ( m_bRefreshPopupControllerCache )\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n if ( pMenuBarManager )\n pMenuBarManager->GetPopupController( m_aPopupControllerCache );\n if ( !m_aPopupControllerCache.empty() )\n m_bRefreshPopupControllerCache = sal_False;\n }\n}\n\n\/\/ XElementAccess\nType SAL_CALL MenuBarWrapper::getElementType()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n return ::getCppuType(( Reference< XDispatchProvider >*)0);\n}\n\n::sal_Bool SAL_CALL MenuBarWrapper::hasElements()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n return ( !m_aPopupControllerCache.empty() );\n}\n\n\/\/ XNameAccess\nAny SAL_CALL MenuBarWrapper::getByName(\n const ::rtl::OUString& aName )\nthrow ( container::NoSuchElementException,\n lang::WrappedTargetException,\n uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.find( aName );\n if ( pIter != m_aPopupControllerCache.end() )\n {\n uno::Reference< frame::XDispatchProvider > xDispatchProvider;\n xDispatchProvider = pIter->second.m_xDispatchProvider;\n return uno::makeAny( xDispatchProvider );\n }\n else\n throw container::NoSuchElementException();\n}\n\nSequence< ::rtl::OUString > SAL_CALL MenuBarWrapper::getElementNames()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n Sequence< rtl::OUString > aSeq( m_aPopupControllerCache.size() );\n\n sal_Int32 i( 0 );\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.begin();\n while ( pIter != m_aPopupControllerCache.end() )\n {\n aSeq[i++] = pIter->first;\n ++pIter;\n }\n\n return aSeq;\n}\n\n::sal_Bool SAL_CALL MenuBarWrapper::hasByName(\n const ::rtl::OUString& aName )\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.find( aName );\n if ( pIter != m_aPopupControllerCache.end() )\n return sal_True;\n else\n return sal_False;\n}\n\n\/\/ XUIElement\nReference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )\n{\n if ( m_bDisposed )\n throw DisposedException();\n\n return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>more cleanup<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <uielement\/menubarwrapper.hxx>\n#include <threadhelp\/resetableguard.hxx>\n#include <framework\/actiontriggerhelper.hxx>\n#include <services.h>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/awt\/XSystemDependentMenuPeer.hpp>\n#include <com\/sun\/star\/awt\/XMenuBar.hpp>\n#include <com\/sun\/star\/container\/XIndexContainer.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/ui\/UIElementType.hpp>\n#include <com\/sun\/star\/frame\/ModuleManager.hpp>\n#include <com\/sun\/star\/util\/URLTransformer.hpp>\n\n#include <comphelper\/processfactory.hxx>\n#include <tools\/solar.h>\n#include <vcl\/svapp.hxx>\n#include <rtl\/logfile.hxx>\n\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::frame;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::awt;\nusing namespace com::sun::star::util;\nusing namespace ::com::sun::star::ui;\n\nnamespace framework\n{\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider\n\/\/*****************************************************************************************************************\nDEFINE_XINTERFACE_11 ( MenuBarWrapper ,\n UIConfigElementWrapperBase ,\n DIRECT_INTERFACE( ::com::sun::star::lang::XTypeProvider ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElement ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementSettings ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XMultiPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XFastPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::beans::XPropertySet ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XInitialization ),\n DIRECT_INTERFACE( ::com::sun::star::lang::XComponent ),\n DIRECT_INTERFACE( ::com::sun::star::util::XUpdatable ),\n DIRECT_INTERFACE( ::com::sun::star::ui::XUIConfigurationListener ),\n DERIVED_INTERFACE( ::com::sun::star::container::XNameAccess, ::com::sun::star::container::XElementAccess )\n )\n\nDEFINE_XTYPEPROVIDER_11 ( MenuBarWrapper ,\n ::com::sun::star::lang::XTypeProvider ,\n ::com::sun::star::ui::XUIElement ,\n ::com::sun::star::ui::XUIElementSettings ,\n ::com::sun::star::beans::XMultiPropertySet ,\n ::com::sun::star::beans::XFastPropertySet ,\n ::com::sun::star::beans::XPropertySet ,\n ::com::sun::star::lang::XInitialization ,\n ::com::sun::star::lang::XComponent ,\n ::com::sun::star::util::XUpdatable ,\n ::com::sun::star::ui::XUIConfigurationListener ,\n ::com::sun::star::container::XNameAccess\n )\n\nMenuBarWrapper::MenuBarWrapper(\n const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager\n )\n: UIConfigElementWrapperBase( UIElementType::MENUBAR,xServiceManager ),\n m_bRefreshPopupControllerCache( sal_True )\n{\n}\n\nMenuBarWrapper::~MenuBarWrapper()\n{\n}\n\nvoid SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );\n\n com::sun::star::lang::EventObject aEvent( xThis );\n m_aListenerContainer.disposeAndClear( aEvent );\n\n ResetableGuard aLock( m_aLock );\n\n m_xMenuBarManager->dispose();\n m_xMenuBarManager.clear();\n m_xConfigSource.clear();\n m_xConfigData.clear();\n\n m_xMenuBar.clear();\n m_bDisposed = sal_True;\n}\n\n\/\/ XInitialization\nvoid SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"framework (cd100003) ::MenuBarWrapper::initialize\" );\n\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( !m_bInitialized )\n {\n rtl::OUString aModuleIdentifier;\n UIConfigElementWrapperBase::initialize( aArguments );\n\n Reference< XFrame > xFrame( m_xWeakFrame );\n if ( xFrame.is() && m_xConfigSource.is() )\n {\n \/\/ Create VCL menubar which will be filled with settings data\n MenuBar* pVCLMenuBar = 0;\n VCLXMenuBar* pAwtMenuBar = 0;\n {\n SolarMutexGuard aSolarMutexGuard;\n pVCLMenuBar = new MenuBar();\n }\n\n Reference< XModuleManager2 > xModuleManager = ModuleManager::create( comphelper::getComponentContext(m_xServiceFactory) );\n\n try\n {\n aModuleIdentifier = xModuleManager->identify( xFrame );\n }\n catch( const Exception& )\n {\n }\n\n Reference< XURLTransformer > xTrans;\n try\n {\n xTrans.set( URLTransformer::create(::comphelper::getComponentContext(m_xServiceFactory)) );\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n {\n \/\/ Fill menubar with container contents\n sal_uInt16 nId = 1;\n MenuBarManager::FillMenuWithConfiguration( nId, pVCLMenuBar, aModuleIdentifier, m_xConfigData, xTrans );\n }\n }\n catch ( const NoSuchElementException& )\n {\n }\n\n sal_Bool bMenuOnly( sal_False );\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name == \"MenuOnly\" )\n aPropValue.Value >>= bMenuOnly;\n }\n }\n\n if ( !bMenuOnly )\n {\n \/\/ Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any\n \/\/ interaction which is done by the menu bar manager. This must be requested by a special property called \"MenuOnly\". Be careful\n \/\/ a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full\n \/\/ support. This feature is currently used for \"Inplace editing\"!\n Reference< XDispatchProvider > xDispatchProvider;\n\n MenuBarManager* pMenuBarManager = new MenuBarManager( m_xServiceFactory,\n xFrame,\n xTrans,\n xDispatchProvider,\n aModuleIdentifier,\n pVCLMenuBar,\n sal_False,\n sal_True );\n\n m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );\n\n pVCLMenuBar->Freeze();\n }\n\n \/\/ Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.\n \/\/ Don't use this toolkit menu bar or one of its functions. It is only used as a data container!\n pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );\n m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );\n }\n }\n}\n\n\/\/ XUIElementSettings\nvoid SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_xMenuBarManager.is() )\n {\n if ( m_xConfigSource.is() && m_bPersistent )\n {\n try\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n }\n catch ( const NoSuchElementException& )\n {\n }\n }\n else if ( !m_bPersistent )\n {\n \/\/ Transient menubar: do nothing\n }\n }\n}\nvoid MenuBarWrapper::impl_fillNewData()\n{\n \/\/ Transient menubar => Fill menubar with new data\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n if ( pMenuBarManager )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n}\n\n\nvoid MenuBarWrapper::fillPopupControllerCache()\n{\n if ( m_bRefreshPopupControllerCache )\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n if ( pMenuBarManager )\n pMenuBarManager->GetPopupController( m_aPopupControllerCache );\n if ( !m_aPopupControllerCache.empty() )\n m_bRefreshPopupControllerCache = sal_False;\n }\n}\n\n\/\/ XElementAccess\nType SAL_CALL MenuBarWrapper::getElementType()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n return ::getCppuType(( Reference< XDispatchProvider >*)0);\n}\n\n::sal_Bool SAL_CALL MenuBarWrapper::hasElements()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n return ( !m_aPopupControllerCache.empty() );\n}\n\n\/\/ XNameAccess\nAny SAL_CALL MenuBarWrapper::getByName(\n const ::rtl::OUString& aName )\nthrow ( container::NoSuchElementException,\n lang::WrappedTargetException,\n uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.find( aName );\n if ( pIter != m_aPopupControllerCache.end() )\n {\n uno::Reference< frame::XDispatchProvider > xDispatchProvider;\n xDispatchProvider = pIter->second.m_xDispatchProvider;\n return uno::makeAny( xDispatchProvider );\n }\n else\n throw container::NoSuchElementException();\n}\n\nSequence< ::rtl::OUString > SAL_CALL MenuBarWrapper::getElementNames()\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n Sequence< rtl::OUString > aSeq( m_aPopupControllerCache.size() );\n\n sal_Int32 i( 0 );\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.begin();\n while ( pIter != m_aPopupControllerCache.end() )\n {\n aSeq[i++] = pIter->first;\n ++pIter;\n }\n\n return aSeq;\n}\n\n::sal_Bool SAL_CALL MenuBarWrapper::hasByName(\n const ::rtl::OUString& aName )\nthrow (::com::sun::star::uno::RuntimeException)\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n fillPopupControllerCache();\n\n PopupControllerCache::const_iterator pIter = m_aPopupControllerCache.find( aName );\n if ( pIter != m_aPopupControllerCache.end() )\n return sal_True;\n else\n return sal_False;\n}\n\n\/\/ XUIElement\nReference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )\n{\n if ( m_bDisposed )\n throw DisposedException();\n\n return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: menubarwrapper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 09:51:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_\n#include <uielement\/menubarwrapper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_\n#include <threadhelp\/resetableguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_\n#include <helper\/actiontriggerhelper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_\n#include <uielement\/constitemcontainer.hxx>\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_\n#include <uielement\/rootitemcontainer.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_\n#include <com\/sun\/star\/awt\/XSystemDependentMenuPeer.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_\n#include <com\/sun\/star\/awt\/XMenuBar.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_\n#include <com\/sun\/star\/container\/XIndexContainer.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_\n#include <drafts\/com\/sun\/star\/ui\/UIElementType.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#include <tools\/solar.h>\n#include <vcl\/svapp.hxx>\n#include <rtl\/logfile.hxx>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::frame;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::awt;\nusing namespace drafts::com::sun::star::ui;\n\nnamespace framework\n{\n\n\/\/ #110897#\nMenuBarWrapper::MenuBarWrapper(\n const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager\n )\n: \/\/ #110897#\n mxServiceFactory( xServiceManager ),\n UIConfigElementWrapperBase( UIElementType::MENUBAR )\n{\n}\n\nMenuBarWrapper::~MenuBarWrapper()\n{\n}\n\n\/\/ #110897#\nconst ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& MenuBarWrapper::getServiceFactory()\n{\n \/\/ #110897#\n return mxServiceFactory;\n}\n\nvoid SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );\n\n com::sun::star::lang::EventObject aEvent( xThis );\n m_aListenerContainer.disposeAndClear( aEvent );\n\n ResetableGuard aLock( m_aLock );\n\n m_xMenuBarManager->dispose();\n m_xMenuBarManager.clear();\n m_xConfigSource.clear();\n m_xConfigData.clear();\n\n m_xMenuBar.clear();\n m_bDisposed = sal_True;\n}\n\n\/\/ XInitialization\nvoid SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"framework (cd100003) ::MenuBarWrapper::initialize\" );\n\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( !m_bInitialized )\n {\n UIConfigElementWrapperBase::initialize( aArguments );\n\n Reference< XFrame > xFrame( m_xWeakFrame );\n if ( xFrame.is() && m_xConfigSource.is() )\n {\n \/\/ Create VCL menubar which will be filled with settings data\n MenuBar* pVCLMenuBar = 0;\n VCLXMenuBar* pAwtMenuBar = 0;\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n pVCLMenuBar = new MenuBar();\n }\n\n try\n {\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n {\n \/\/ Fill menubar with container contents\n USHORT nId = 1;\n MenuBarManager::FillMenu( nId, pVCLMenuBar, m_xConfigData );\n }\n }\n catch ( NoSuchElementException& )\n {\n }\n\n sal_Bool bMenuOnly( sal_False );\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name.equalsAscii( \"MenuOnly\" ))\n aPropValue.Value >>= bMenuOnly;\n }\n }\n\n if ( !bMenuOnly )\n {\n \/\/ Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any\n \/\/ interaction which is done by the menu bar manager. This must be requested by a special property called \"MenuOnly\". Be careful\n \/\/ a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full\n \/\/ support. This feature is currently used for \"Inplace editing\"!\n \/\/ #110897# MenuBarManager* pMenuBarManager = new MenuBarManager( xFrame, pVCLMenuBar, sal_False, sal_True );\n MenuBarManager* pMenuBarManager = new MenuBarManager( getServiceFactory(), xFrame, pVCLMenuBar, sal_False, sal_True );\n\n m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );\n }\n\n \/\/ Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.\n \/\/ Don't use this toolkit menu bar or one of its functions. It is only used as a data container!\n pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );\n m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );\n }\n }\n}\n\n\/\/ XUIElementSettings\nvoid SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_bPersistent &&\n m_xConfigSource.is() &&\n m_xMenuBarManager.is() )\n {\n try\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n }\n catch ( NoSuchElementException& )\n {\n }\n }\n}\n\nvoid SAL_CALL MenuBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( xSettings.is() )\n {\n \/\/ Create a copy of the data if the container is not const\n Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );\n if ( xReplace.is() )\n m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );\n else\n m_xConfigData = xSettings;\n\n if ( m_xConfigSource.is() && m_bPersistent )\n {\n OUString aResourceURL( m_aResourceURL );\n Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );\n\n aLock.unlock();\n\n try\n {\n xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );\n }\n catch( NoSuchElementException& )\n {\n }\n }\n }\n}\n\nReference< XIndexAccess > SAL_CALL MenuBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( bWriteable )\n return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );\n else\n return m_xConfigData;\n}\n\nReference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )\n{\n if ( m_bDisposed )\n throw DisposedException();\n\n return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );\n}\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS perform01 (1.4.102); FILE MERGED 2005\/02\/03 15:14:30 mt 1.4.102.4: fixed wrong solved merge conflict 2005\/02\/02 15:22:25 mt 1.4.102.3: fixed compile error 2005\/02\/01 13:31:12 mt 1.4.102.2: RESYNC: (1.4-1.5); FILE MERGED 2005\/01\/26 10:11:25 cd 1.4.102.1: #i40989# Performance and usability improvements<commit_after>\/*************************************************************************\n *\n * $RCSfile: menubarwrapper.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2005-02-16 16:32:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_\n#include <uielement\/menubarwrapper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_\n#include <threadhelp\/resetableguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_\n#include <helper\/actiontriggerhelper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_\n#include <uielement\/constitemcontainer.hxx>\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_\n#include <uielement\/rootitemcontainer.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_\n#include <com\/sun\/star\/awt\/XSystemDependentMenuPeer.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_\n#include <com\/sun\/star\/awt\/XMenuBar.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_\n#include <com\/sun\/star\/container\/XIndexContainer.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_\n#include <drafts\/com\/sun\/star\/ui\/UIElementType.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#include <tools\/solar.h>\n#include <vcl\/svapp.hxx>\n#include <rtl\/logfile.hxx>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::frame;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::awt;\nusing namespace drafts::com::sun::star::ui;\n\nnamespace framework\n{\n\n\/\/ #110897#\nMenuBarWrapper::MenuBarWrapper(\n const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager\n )\n: \/\/ #110897#\n mxServiceFactory( xServiceManager ),\n UIConfigElementWrapperBase( UIElementType::MENUBAR )\n{\n}\n\nMenuBarWrapper::~MenuBarWrapper()\n{\n}\n\n\/\/ #110897#\nconst ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& MenuBarWrapper::getServiceFactory()\n{\n \/\/ #110897#\n return mxServiceFactory;\n}\n\nvoid SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)\n{\n Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );\n\n com::sun::star::lang::EventObject aEvent( xThis );\n m_aListenerContainer.disposeAndClear( aEvent );\n\n ResetableGuard aLock( m_aLock );\n\n m_xMenuBarManager->dispose();\n m_xMenuBarManager.clear();\n m_xConfigSource.clear();\n m_xConfigData.clear();\n\n m_xMenuBar.clear();\n m_bDisposed = sal_True;\n}\n\n\/\/ XInitialization\nvoid SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"framework (cd100003) ::MenuBarWrapper::initialize\" );\n\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( !m_bInitialized )\n {\n UIConfigElementWrapperBase::initialize( aArguments );\n\n Reference< XFrame > xFrame( m_xWeakFrame );\n if ( xFrame.is() && m_xConfigSource.is() )\n {\n \/\/ Create VCL menubar which will be filled with settings data\n MenuBar* pVCLMenuBar = 0;\n VCLXMenuBar* pAwtMenuBar = 0;\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n pVCLMenuBar = new MenuBar();\n }\n\n try\n {\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n {\n \/\/ Fill menubar with container contents\n USHORT nId = 1;\n MenuBarManager::FillMenu( nId, pVCLMenuBar, m_xConfigData );\n }\n }\n catch ( NoSuchElementException& )\n {\n }\n\n sal_Bool bMenuOnly( sal_False );\n for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )\n {\n PropertyValue aPropValue;\n if ( aArguments[n] >>= aPropValue )\n {\n if ( aPropValue.Name.equalsAscii( \"MenuOnly\" ))\n aPropValue.Value >>= bMenuOnly;\n }\n }\n\n if ( !bMenuOnly )\n {\n \/\/ Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any\n \/\/ interaction which is done by the menu bar manager. This must be requested by a special property called \"MenuOnly\". Be careful\n \/\/ a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full\n \/\/ support. This feature is currently used for \"Inplace editing\"!\n \/\/ #110897# MenuBarManager* pMenuBarManager = new MenuBarManager( xFrame, pVCLMenuBar, sal_False, sal_True );\n MenuBarManager* pMenuBarManager = new MenuBarManager( getServiceFactory(), xFrame, pVCLMenuBar, sal_False, sal_True );\n\n m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );\n }\n\n \/\/ Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.\n \/\/ Don't use this toolkit menu bar or one of its functions. It is only used as a data container!\n pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );\n m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );\n }\n }\n}\n\n\/\/ XUIElementSettings\nvoid SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_bPersistent &&\n m_xConfigSource.is() &&\n m_xMenuBarManager.is() )\n {\n try\n {\n MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );\n\n m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );\n if ( m_xConfigData.is() )\n pMenuBarManager->SetItemContainer( m_xConfigData );\n }\n catch ( NoSuchElementException& )\n {\n }\n }\n}\n\nvoid SAL_CALL MenuBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( xSettings.is() )\n {\n \/\/ Create a copy of the data if the container is not const\n Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );\n if ( xReplace.is() )\n m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );\n else\n m_xConfigData = xSettings;\n\n if ( m_xConfigSource.is() && m_bPersistent )\n {\n OUString aResourceURL( m_aResourceURL );\n Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );\n\n aLock.unlock();\n\n try\n {\n xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );\n }\n catch( NoSuchElementException& )\n {\n }\n }\n }\n}\n\nReference< XIndexAccess > SAL_CALL MenuBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )\n{\n ResetableGuard aLock( m_aLock );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( bWriteable )\n return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );\n else\n return m_xConfigData;\n}\n\nReference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )\n{\n if ( m_bDisposed )\n throw DisposedException();\n\n return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );\n}\n\n} \/\/ namespace framework\n\n<|endoftext|>"} {"text":"<commit_before>#include \"configparser.h\"\n\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <pwd.h>\n#include <sys\/types.h>\n\n#include \"config.h\"\n#include \"exceptions.h\"\n#include \"logger.h\"\n#include \"strprintf.h\"\n#include \"tagsouppullparser.h\"\n#include \"utils.h\"\n\nnamespace newsboat {\n\nConfigParser::ConfigParser()\n{\n\tregister_handler(\"include\", this);\n}\n\nConfigParser::~ConfigParser() {}\n\nvoid ConfigParser::handle_action(const std::string& action,\n\tconst std::vector<std::string>& params)\n{\n\t\/*\n\t * ConfigParser also acts as ConfigActionHandler to implement\n\t * recursive \"include\" command.\n\t *\/\n\tif (action == \"include\") {\n\t\tif (params.size() < 1) {\n\t\t\tthrow ConfigHandlerException(\n\t\t\t\tActionHandlerStatus::TOO_FEW_PARAMS);\n\t\t}\n\n\t\tif (!this->parse(utils::resolve_tilde(params[0])))\n\t\t\tthrow ConfigHandlerException(\n\t\t\t\tActionHandlerStatus::FILENOTFOUND);\n\t} else\n\t\tthrow ConfigHandlerException(\n\t\t\tActionHandlerStatus::INVALID_COMMAND);\n}\n\nbool ConfigParser::parse(const std::string& filename, bool double_include)\n{\n\t\/*\n\t * this function parses a config file.\n\t *\n\t * First, it checks whether this file has already been included, and if\n\t * not, it does the following:\n\t * - open the file\n\t * - read it line by line\n\t * - tokenize every line\n\t * - if there is at least one token, look up a registered\n\t * ConfigActionHandler to handle the command (which is specified in\n\t * the first token)\n\t * - hand over the tokenize results to the ConfigActionHandler\n\t * - if an error happens, react accordingly.\n\t *\/\n\tif (!double_include &&\n\t\tstd::find(included_files.begin(), included_files.end(), filename) != included_files.end()) {\n\t\tLOG(Level::WARN,\n\t\t\t\"ConfigParser::parse: file %s has already been \"\n\t\t\t\"included\",\n\t\t\tfilename);\n\t\treturn true;\n\t}\n\tincluded_files.push_back(filename);\n\n\tunsigned int linecounter = 0;\n\tstd::ifstream f(filename.c_str());\n\tstd::string line;\n\tif (!f.is_open()) {\n\t\tLOG(Level::WARN,\n\t\t\t\"ConfigParser::parse: file %s couldn't be opened\",\n\t\t\tfilename);\n\t\treturn false;\n\t}\n\n\twhile (f.is_open() && !f.eof()) {\n\t\tgetline(f, line);\n\t\t++linecounter;\n\t\tLOG(Level::DEBUG, \"ConfigParser::parse: tokenizing %s\", line);\n\t\tstd::vector<std::string> tokens = utils::tokenize_quoted(line);\n\t\tif (!tokens.empty()) {\n\t\t\tstd::string cmd = tokens[0];\n\t\t\tConfigActionHandler* handler = action_handlers[cmd];\n\t\t\tif (handler) {\n\t\t\t\ttokens.erase(\n\t\t\t\t\ttokens.begin()); \/\/ delete first element\n\t\t\t\ttry {\n\t\t\t\t\tevaluate_backticks(tokens);\n\t\t\t\t\thandler->handle_action(cmd, tokens);\n\t\t\t\t} catch (const ConfigHandlerException& e) {\n\t\t\t\t\tthrow ConfigException(strprintf::fmt(\n\t\t\t\t\t\t_(\"Error while processing \"\n\t\t\t\t\t\t \"command `%s' (%s line %u): \"\n\t\t\t\t\t\t \"%s\"),\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tfilename,\n\t\t\t\t\t\tlinecounter,\n\t\t\t\t\t\te.what()));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow ConfigException(strprintf::fmt(\n\t\t\t\t\t_(\"unknown command `%s'\"), cmd));\n\t\t\t}\n\t\t}\n\t}\n\tincluded_files.pop_back();\n\treturn true;\n}\n\nvoid ConfigParser::register_handler(const std::string& cmd,\n\tConfigActionHandler* handler)\n{\n\taction_handlers[cmd] = handler;\n}\n\nvoid ConfigParser::unregister_handler(const std::string& cmd)\n{\n\taction_handlers[cmd] = 0;\n}\n\nvoid ConfigParser::evaluate_backticks(std::vector<std::string>& tokens)\n{\n\tfor (auto& token : tokens) {\n\t\ttoken = evaluate_backticks(token);\n\t}\n}\n\n\/* Note that this function not only finds next backtick that isn't prefixed\n * with a backslash, but also un-escapes all the escaped backticks it finds in\n * the process *\/\nstd::string::size_type find_non_escaped_backtick(std::string& input,\n\tconst std::string::size_type startpos)\n{\n\tif (startpos == std::string::npos)\n\t\treturn startpos;\n\n\tstd::string::size_type result = startpos;\n\tresult = input.find_first_of(\"`\", result);\n\n\twhile (result != std::string::npos && result > 0 &&\n\t\tinput[result - 1] == '\\\\') {\n\t\t\/\/ remove the backslash\n\t\tinput.erase(result - 1, 1);\n\n\t\t\/\/ *not* adding one to start position as we already shortened\n\t\t\/\/ the input by one character\n\t\tresult = input.find_first_of(\"`\", result);\n\t}\n\n\treturn result;\n}\n\nstd::string ConfigParser::evaluate_backticks(std::string token)\n{\n\tstd::string::size_type pos1 = find_non_escaped_backtick(token, 0);\n\tstd::string::size_type pos2 =\n\t\tfind_non_escaped_backtick(token, pos1 + 1);\n\n\twhile (pos1 != std::string::npos && pos2 != std::string::npos) {\n\t\tstd::string cmd = token.substr(pos1 + 1, pos2 - pos1 - 1);\n\t\ttoken.erase(pos1, pos2 - pos1 + 1);\n\t\tstd::string result = utils::get_command_output(cmd);\n\t\tutils::trim_end(result);\n\t\ttoken.insert(pos1, result);\n\n\t\tpos1 = find_non_escaped_backtick(\n\t\t\ttoken, pos1 + result.length() + 1);\n\t\tpos2 = find_non_escaped_backtick(token, pos1 + 1);\n\t}\n\n\treturn token;\n}\n\n} \/\/ namespace newsboat\n<commit_msg>Enable relative path including<commit_after>#include \"configparser.h\"\n\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <pwd.h>\n#include <sys\/types.h>\n\n#include \"config.h\"\n#include \"exceptions.h\"\n#include \"logger.h\"\n#include \"strprintf.h\"\n#include \"tagsouppullparser.h\"\n#include \"utils.h\"\n\nnamespace newsboat {\n\nConfigParser::ConfigParser()\n{\n\tregister_handler(\"include\", this);\n}\n\nConfigParser::~ConfigParser() {}\n\nvoid ConfigParser::handle_action(const std::string& action,\n\tconst std::vector<std::string>& params)\n{\n\t\/*\n\t * ConfigParser also acts as ConfigActionHandler to implement\n\t * recursive \"include\" command.\n\t *\/\n\tif (action == \"include\") {\n\t\tif (params.size() < 1) {\n\t\t\tthrow ConfigHandlerException(\n\t\t\t\tActionHandlerStatus::TOO_FEW_PARAMS);\n\t\t}\n\n\t\tstd::string tilde_expanded = utils::resolve_tilde(params[0]);\n\t\tstd::string current_fpath = included_files.back();\n\t\tif (!this->parse(utils::resolve_relative(current_fpath, tilde_expanded)))\n\t\t\tthrow ConfigHandlerException(\n\t\t\t\tActionHandlerStatus::FILENOTFOUND);\n\t} else\n\t\tthrow ConfigHandlerException(\n\t\t\tActionHandlerStatus::INVALID_COMMAND);\n}\n\nbool ConfigParser::parse(const std::string& tmp_filename, bool double_include)\n{\n\t\/*\n\t * this function parses a config file.\n\t *\n\t * First, it checks whether this file has already been included, and if\n\t * not, it does the following:\n\t * - open the file\n\t * - read it line by line\n\t * - tokenize every line\n\t * - if there is at least one token, look up a registered\n\t * ConfigActionHandler to handle the command (which is specified in\n\t * the first token)\n\t * - hand over the tokenize results to the ConfigActionHandler\n\t * - if an error happens, react accordingly.\n\t *\/\n\n\t\/\/ It would be nice if this function was only give absolute paths, but the\n\t\/\/ tests are easier as relative paths\n\tconst std::string filename = (tmp_filename.front() == '\/') ? tmp_filename : utils::getcwd() + '\/' + tmp_filename;\n\n\tif (!double_include &&\n\t\tstd::find(included_files.begin(), included_files.end(), filename) != included_files.end()) {\n\t\tLOG(Level::WARN,\n\t\t\t\"ConfigParser::parse: file %s has already been \"\n\t\t\t\"included\",\n\t\t\tfilename);\n\t\treturn true;\n\t}\n\tincluded_files.push_back(filename);\n\n\tunsigned int linecounter = 0;\n\tstd::ifstream f(filename.c_str());\n\tstd::string line;\n\tif (!f.is_open()) {\n\t\tLOG(Level::WARN,\n\t\t\t\"ConfigParser::parse: file %s couldn't be opened\",\n\t\t\tfilename);\n\t\treturn false;\n\t}\n\n\twhile (f.is_open() && !f.eof()) {\n\t\tgetline(f, line);\n\t\t++linecounter;\n\t\tLOG(Level::DEBUG, \"ConfigParser::parse: tokenizing %s\", line);\n\t\tstd::vector<std::string> tokens = utils::tokenize_quoted(line);\n\t\tif (!tokens.empty()) {\n\t\t\tstd::string cmd = tokens[0];\n\t\t\tConfigActionHandler* handler = action_handlers[cmd];\n\t\t\tif (handler) {\n\t\t\t\ttokens.erase(\n\t\t\t\t\ttokens.begin()); \/\/ delete first element\n\t\t\t\ttry {\n\t\t\t\t\tevaluate_backticks(tokens);\n\t\t\t\t\thandler->handle_action(cmd, tokens);\n\t\t\t\t} catch (const ConfigHandlerException& e) {\n\t\t\t\t\tthrow ConfigException(strprintf::fmt(\n\t\t\t\t\t\t_(\"Error while processing \"\n\t\t\t\t\t\t \"command `%s' (%s line %u): \"\n\t\t\t\t\t\t \"%s\"),\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tfilename,\n\t\t\t\t\t\tlinecounter,\n\t\t\t\t\t\te.what()));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow ConfigException(strprintf::fmt(\n\t\t\t\t\t_(\"unknown command `%s'\"), cmd));\n\t\t\t}\n\t\t}\n\t}\n\tincluded_files.pop_back();\n\treturn true;\n}\n\nvoid ConfigParser::register_handler(const std::string& cmd,\n\tConfigActionHandler* handler)\n{\n\taction_handlers[cmd] = handler;\n}\n\nvoid ConfigParser::unregister_handler(const std::string& cmd)\n{\n\taction_handlers[cmd] = 0;\n}\n\nvoid ConfigParser::evaluate_backticks(std::vector<std::string>& tokens)\n{\n\tfor (auto& token : tokens) {\n\t\ttoken = evaluate_backticks(token);\n\t}\n}\n\n\/* Note that this function not only finds next backtick that isn't prefixed\n * with a backslash, but also un-escapes all the escaped backticks it finds in\n * the process *\/\nstd::string::size_type find_non_escaped_backtick(std::string& input,\n\tconst std::string::size_type startpos)\n{\n\tif (startpos == std::string::npos)\n\t\treturn startpos;\n\n\tstd::string::size_type result = startpos;\n\tresult = input.find_first_of(\"`\", result);\n\n\twhile (result != std::string::npos && result > 0 &&\n\t\tinput[result - 1] == '\\\\') {\n\t\t\/\/ remove the backslash\n\t\tinput.erase(result - 1, 1);\n\n\t\t\/\/ *not* adding one to start position as we already shortened\n\t\t\/\/ the input by one character\n\t\tresult = input.find_first_of(\"`\", result);\n\t}\n\n\treturn result;\n}\n\nstd::string ConfigParser::evaluate_backticks(std::string token)\n{\n\tstd::string::size_type pos1 = find_non_escaped_backtick(token, 0);\n\tstd::string::size_type pos2 =\n\t\tfind_non_escaped_backtick(token, pos1 + 1);\n\n\twhile (pos1 != std::string::npos && pos2 != std::string::npos) {\n\t\tstd::string cmd = token.substr(pos1 + 1, pos2 - pos1 - 1);\n\t\ttoken.erase(pos1, pos2 - pos1 + 1);\n\t\tstd::string result = utils::get_command_output(cmd);\n\t\tutils::trim_end(result);\n\t\ttoken.insert(pos1, result);\n\n\t\tpos1 = find_non_escaped_backtick(\n\t\t\ttoken, pos1 + result.length() + 1);\n\t\tpos2 = find_non_escaped_backtick(token, pos1 + 1);\n\t}\n\n\treturn token;\n}\n\n} \/\/ namespace newsboat\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#ifdef SEASTAR_HAVE_DPDK\n\n#include <cinttypes>\n#include <seastar\/net\/dpdk.hh>\n#include <seastar\/core\/dpdk_rte.hh>\n#include <seastar\/util\/conversions.hh>\n#include <seastar\/util\/std-compat.hh>\n#include <rte_pci.h>\n\nnamespace seastar {\n\nnamespace dpdk {\n\nbool eal::initialized = false;\n\nvoid eal::init(cpuset cpus, const std::string& argv0, const std::optional<std::string>& hugepages_path, bool dpdk_pmd)\n{\n if (initialized) {\n return;\n }\n\n std::stringstream mask;\n cpuset nibble = 0xF;\n while (cpus.any()) {\n mask << std::hex << (cpus & nibble).to_ulong();\n cpus >>= 4;\n }\n\n std::string mask_str = mask.str();\n std::reverse(mask_str.begin(), mask_str.end());\n\n std::vector<std::vector<char>> args {\n string2vector(argv0),\n string2vector(\"-c\"), string2vector(mask_str),\n string2vector(\"-n\"), string2vector(\"1\")\n };\n\n \/\/ If \"hugepages\" is not provided and DPDK PMD drivers mode is requested -\n \/\/ use the default DPDK huge tables configuration.\n if (hugepages_path) {\n args.push_back(string2vector(\"--huge-dir\"));\n args.push_back(string2vector(hugepages_path.value()));\n\n \/\/\n \/\/ We don't know what is going to be our networking configuration so we\n \/\/ assume there is going to be a queue per-CPU. Plus we'll give a DPDK\n \/\/ 64MB for \"other stuff\".\n \/\/\n size_t size_MB = mem_size(cpus.count()) >> 20;\n std::stringstream size_MB_str;\n size_MB_str << size_MB;\n\n args.push_back(string2vector(\"-m\"));\n args.push_back(string2vector(size_MB_str.str()));\n } else if (!dpdk_pmd) {\n args.push_back(string2vector(\"--no-huge\"));\n }\n#ifdef HAVE_OSV\n args.push_back(string2vector(\"--no-shconf\"));\n#endif\n\n std::vector<char*> cargs;\n\n for (auto&& a: args) {\n cargs.push_back(a.data());\n }\n \/* initialise the EAL for all *\/\n int ret = rte_eal_init(cargs.size(), cargs.data());\n if (ret < 0) {\n rte_exit(EXIT_FAILURE, \"Cannot init EAL\\n\");\n }\n\n initialized = true;\n}\n\nuint32_t __attribute__((weak)) qp_mempool_obj_size(bool hugetlbfs_membackend)\n{\n return 0;\n}\n\nsize_t eal::mem_size(int num_cpus, bool hugetlbfs_membackend)\n{\n size_t memsize = 0;\n \/\/\n \/\/ PMD mempool memory:\n \/\/\n \/\/ We don't know what is going to be our networking configuration so we\n \/\/ assume there is going to be a queue per-CPU.\n \/\/\n memsize += num_cpus * qp_mempool_obj_size(hugetlbfs_membackend);\n\n \/\/ Plus we'll give a DPDK 64MB for \"other stuff\".\n memsize += (64UL << 20);\n\n return memsize;\n}\n\n} \/\/ namespace dpdk\n\n}\n\n#endif \/\/ SEASTAR_HAVE_DPDK\n<commit_msg>fix cpuset count is zero after shift<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n#ifdef SEASTAR_HAVE_DPDK\n\n#include <cinttypes>\n#include <seastar\/net\/dpdk.hh>\n#include <seastar\/core\/dpdk_rte.hh>\n#include <seastar\/util\/conversions.hh>\n#include <seastar\/util\/std-compat.hh>\n#include <rte_pci.h>\n\nnamespace seastar {\n\nnamespace dpdk {\n\nbool eal::initialized = false;\n\nvoid eal::init(cpuset cpus, const std::string& argv0, const std::optional<std::string>& hugepages_path, bool dpdk_pmd)\n{\n if (initialized) {\n return;\n }\n\n size_t cpu_count = cpus.count();\n std::stringstream mask;\n cpuset nibble = 0xF;\n while (cpus.any()) {\n mask << std::hex << (cpus & nibble).to_ulong();\n cpus >>= 4;\n }\n\n std::string mask_str = mask.str();\n std::reverse(mask_str.begin(), mask_str.end());\n\n std::vector<std::vector<char>> args {\n string2vector(argv0),\n string2vector(\"-c\"), string2vector(mask_str),\n string2vector(\"-n\"), string2vector(\"1\")\n };\n\n \/\/ If \"hugepages\" is not provided and DPDK PMD drivers mode is requested -\n \/\/ use the default DPDK huge tables configuration.\n if (hugepages_path) {\n args.push_back(string2vector(\"--huge-dir\"));\n args.push_back(string2vector(hugepages_path.value()));\n\n \/\/\n \/\/ We don't know what is going to be our networking configuration so we\n \/\/ assume there is going to be a queue per-CPU. Plus we'll give a DPDK\n \/\/ 64MB for \"other stuff\".\n \/\/\n size_t size_MB = mem_size(cpu_count) >> 20;\n std::stringstream size_MB_str;\n size_MB_str << size_MB;\n\n args.push_back(string2vector(\"-m\"));\n args.push_back(string2vector(size_MB_str.str()));\n } else if (!dpdk_pmd) {\n args.push_back(string2vector(\"--no-huge\"));\n }\n#ifdef HAVE_OSV\n args.push_back(string2vector(\"--no-shconf\"));\n#endif\n\n std::vector<char*> cargs;\n\n for (auto&& a: args) {\n cargs.push_back(a.data());\n }\n \/* initialise the EAL for all *\/\n int ret = rte_eal_init(cargs.size(), cargs.data());\n if (ret < 0) {\n rte_exit(EXIT_FAILURE, \"Cannot init EAL\\n\");\n }\n\n initialized = true;\n}\n\nuint32_t __attribute__((weak)) qp_mempool_obj_size(bool hugetlbfs_membackend)\n{\n return 0;\n}\n\nsize_t eal::mem_size(int num_cpus, bool hugetlbfs_membackend)\n{\n size_t memsize = 0;\n \/\/\n \/\/ PMD mempool memory:\n \/\/\n \/\/ We don't know what is going to be our networking configuration so we\n \/\/ assume there is going to be a queue per-CPU.\n \/\/\n memsize += num_cpus * qp_mempool_obj_size(hugetlbfs_membackend);\n\n \/\/ Plus we'll give a DPDK 64MB for \"other stuff\".\n memsize += (64UL << 20);\n\n return memsize;\n}\n\n} \/\/ namespace dpdk\n\n}\n\n#endif \/\/ SEASTAR_HAVE_DPDK\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ELFHeader.cpp ----------------------------------------- -*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <cstring>\n\n#include \"lldb\/Core\/DataExtractor.h\"\n#include \"lldb\/Core\/Section.h\"\n#include \"lldb\/Core\/Stream.h\"\n\n#include \"ELFHeader.h\"\n\nusing namespace elf;\nusing namespace lldb;\nusing namespace llvm::ELF;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Static utility functions.\n\/\/\n\/\/ GetMaxU64 and GetMaxS64 wrap the similarly named methods from DataExtractor\n\/\/ with error handling code and provide for parsing a sequence of values.\nstatic bool\nGetMaxU64(const lldb_private::DataExtractor &data,\n lldb::offset_t *offset,\n uint64_t *value,\n uint32_t byte_size)\n{\n const lldb::offset_t saved_offset = *offset;\n *value = data.GetMaxU64(offset, byte_size);\n return *offset != saved_offset;\n}\n\nstatic bool\nGetMaxU64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n uint64_t *value,\n uint32_t byte_size,\n uint32_t count) \n{\n lldb::offset_t saved_offset = *offset;\n\n for (uint32_t i = 0; i < count; ++i, ++value)\n {\n if (GetMaxU64(data, offset, value, byte_size) == false) \n {\n *offset = saved_offset;\n return false;\n }\n }\n return true;\n}\n\nstatic bool\nGetMaxS64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n int64_t *value,\n uint32_t byte_size)\n{\n const lldb::offset_t saved_offset = *offset;\n *value = data.GetMaxS64(offset, byte_size);\n return *offset != saved_offset;\n}\n\nstatic bool\nGetMaxS64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n int64_t *value,\n uint32_t byte_size,\n uint32_t count) \n{\n lldb::offset_t saved_offset = *offset;\n\n for (uint32_t i = 0; i < count; ++i, ++value)\n {\n if (GetMaxS64(data, offset, value, byte_size) == false) \n {\n *offset = saved_offset;\n return false;\n }\n }\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFHeader\n\nELFHeader::ELFHeader()\n{\n memset(this, 0, sizeof(ELFHeader)); \n}\n\nByteOrder\nELFHeader::GetByteOrder() const \n{\n if (e_ident[EI_DATA] == ELFDATA2MSB)\n return eByteOrderBig;\n if (e_ident[EI_DATA] == ELFDATA2LSB)\n return eByteOrderLittle;\n return eByteOrderInvalid;\n}\n\nbool\nELFHeader::Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset) \n{\n \/\/ Read e_ident. This provides byte order and address size info.\n if (data.GetU8(offset, &e_ident, EI_NIDENT) == NULL)\n return false;\n\n const unsigned byte_size = Is32Bit() ? 4 : 8;\n data.SetByteOrder(GetByteOrder());\n data.SetAddressByteSize(byte_size);\n\n \/\/ Read e_type and e_machine.\n if (data.GetU16(offset, &e_type, 2) == NULL)\n return false;\n\n \/\/ Read e_version.\n if (data.GetU32(offset, &e_version, 1) == NULL)\n return false;\n\n \/\/ Read e_entry, e_phoff and e_shoff.\n if (GetMaxU64(data, offset, &e_entry, byte_size, 3) == false)\n return false;\n\n \/\/ Read e_flags.\n if (data.GetU32(offset, &e_flags, 1) == NULL)\n return false;\n\n \/\/ Read e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum and\n \/\/ e_shstrndx.\n if (data.GetU16(offset, &e_ehsize, 6) == NULL)\n return false;\n\n return true;\n}\n\nbool\nELFHeader::MagicBytesMatch(const uint8_t *magic)\n{\n return memcmp(magic, ElfMagic, strlen(ElfMagic)) == 0;\n}\n\nunsigned\nELFHeader::AddressSizeInBytes(const uint8_t *magic)\n{\n unsigned address_size = 0;\n\n switch (magic[EI_CLASS]) \n {\n case ELFCLASS32:\n address_size = 4;\n break;\n \n case ELFCLASS64:\n address_size = 8;\n break;\n }\n return address_size;\n}\n\nunsigned\nELFHeader::GetRelocationJumpSlotType() const\n{\n unsigned slot = 0;\n\n switch (e_machine)\n {\n default:\n assert(false && \"architecture not supported\");\n break;\n case EM_PPC:\n slot = R_PPC_JMP_SLOT;\n break;\n case EM_PPC64:\n slot = R_PPC64_JMP_SLOT;\n break;\n case EM_386:\n case EM_IAMCU: \/\/ FIXME: is this correct?\n slot = R_386_JUMP_SLOT;\n break;\n case EM_X86_64:\n slot = R_X86_64_JUMP_SLOT;\n break;\n case EM_ARM:\n slot = R_ARM_JUMP_SLOT;\n break;\n case EM_HEXAGON:\n slot = R_HEX_JMP_SLOT;\n break;\n case EM_AARCH64:\n slot = R_AARCH64_JUMP_SLOT;\n break;\n case EM_MIPS:\n slot = R_MIPS_JUMP_SLOT;\n break;\n }\n\n return slot;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFSectionHeader\n\nELFSectionHeader::ELFSectionHeader() \n{\n memset(this, 0, sizeof(ELFSectionHeader));\n}\n\nbool\nELFSectionHeader::Parse(const lldb_private::DataExtractor &data,\n lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read sh_name and sh_type.\n if (data.GetU32(offset, &sh_name, 2) == NULL)\n return false;\n\n \/\/ Read sh_flags.\n if (GetMaxU64(data, offset, &sh_flags, byte_size) == false)\n return false;\n\n \/\/ Read sh_addr, sh_off and sh_size.\n if (GetMaxU64(data, offset, &sh_addr, byte_size, 3) == false)\n return false;\n\n \/\/ Read sh_link and sh_info.\n if (data.GetU32(offset, &sh_link, 2) == NULL)\n return false;\n\n \/\/ Read sh_addralign and sh_entsize.\n if (GetMaxU64(data, offset, &sh_addralign, byte_size, 2) == false)\n return false;\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFSymbol\n\nELFSymbol::ELFSymbol() \n{\n memset(this, 0, sizeof(ELFSymbol));\n}\n\n#define ENUM_TO_CSTR(e) case e: return #e\n\nconst char *\nELFSymbol::bindingToCString(unsigned char binding)\n{\n switch (binding)\n {\n ENUM_TO_CSTR(STB_LOCAL);\n ENUM_TO_CSTR(STB_GLOBAL);\n ENUM_TO_CSTR(STB_WEAK);\n ENUM_TO_CSTR(STB_LOOS);\n ENUM_TO_CSTR(STB_HIOS);\n ENUM_TO_CSTR(STB_LOPROC);\n ENUM_TO_CSTR(STB_HIPROC);\n }\n return \"\";\n}\n\nconst char *\nELFSymbol::typeToCString(unsigned char type)\n{\n switch (type)\n {\n ENUM_TO_CSTR(STT_NOTYPE);\n ENUM_TO_CSTR(STT_OBJECT);\n ENUM_TO_CSTR(STT_FUNC);\n ENUM_TO_CSTR(STT_SECTION);\n ENUM_TO_CSTR(STT_FILE);\n ENUM_TO_CSTR(STT_COMMON);\n ENUM_TO_CSTR(STT_TLS);\n ENUM_TO_CSTR(STT_LOOS);\n ENUM_TO_CSTR(STT_HIOS);\n ENUM_TO_CSTR(STT_GNU_IFUNC);\n ENUM_TO_CSTR(STT_LOPROC);\n ENUM_TO_CSTR(STT_HIPROC);\n }\n return \"\";\n}\n\nconst char *\nELFSymbol::sectionIndexToCString (elf_half shndx,\n const lldb_private::SectionList *section_list)\n{\n switch (shndx)\n {\n ENUM_TO_CSTR(SHN_UNDEF);\n ENUM_TO_CSTR(SHN_LOPROC);\n ENUM_TO_CSTR(SHN_HIPROC);\n ENUM_TO_CSTR(SHN_LOOS);\n ENUM_TO_CSTR(SHN_HIOS);\n ENUM_TO_CSTR(SHN_ABS);\n ENUM_TO_CSTR(SHN_COMMON);\n ENUM_TO_CSTR(SHN_XINDEX);\n default:\n {\n const lldb_private::Section *section = section_list->GetSectionAtIndex(shndx).get();\n if (section)\n return section->GetName().AsCString(\"\");\n }\n break;\n }\n return \"\";\n}\n\nvoid\nELFSymbol::Dump (lldb_private::Stream *s,\n uint32_t idx,\n const lldb_private::DataExtractor *strtab_data,\n const lldb_private::SectionList *section_list)\n{\n s->Printf(\"[%3u] 0x%16.16\" PRIx64 \" 0x%16.16\" PRIx64 \" 0x%8.8x 0x%2.2x (%-10s %-13s) 0x%2.2x 0x%4.4x (%-10s) %s\\n\",\n idx,\n st_value,\n st_size,\n st_name,\n st_info,\n bindingToCString (getBinding()),\n typeToCString (getType()),\n st_other,\n st_shndx,\n sectionIndexToCString (st_shndx, section_list),\n strtab_data ? strtab_data->PeekCStr(st_name) : \"\");\n}\n\nbool\nELFSymbol::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n const bool parsing_32 = byte_size == 4;\n\n \/\/ Read st_name.\n if (data.GetU32(offset, &st_name, 1) == NULL)\n return false;\n\n if (parsing_32) \n {\n \/\/ Read st_value and st_size.\n if (GetMaxU64(data, offset, &st_value, byte_size, 2) == false)\n return false;\n\n \/\/ Read st_info and st_other.\n if (data.GetU8(offset, &st_info, 2) == NULL)\n return false;\n \n \/\/ Read st_shndx.\n if (data.GetU16(offset, &st_shndx, 1) == NULL)\n return false;\n }\n else \n {\n \/\/ Read st_info and st_other.\n if (data.GetU8(offset, &st_info, 2) == NULL)\n return false;\n \n \/\/ Read st_shndx.\n if (data.GetU16(offset, &st_shndx, 1) == NULL)\n return false;\n\n \/\/ Read st_value and st_size.\n if (data.GetU64(offset, &st_value, 2) == NULL)\n return false;\n }\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFProgramHeader\n\nELFProgramHeader::ELFProgramHeader() \n{\n memset(this, 0, sizeof(ELFProgramHeader));\n}\n\nbool\nELFProgramHeader::Parse(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset)\n{\n const uint32_t byte_size = data.GetAddressByteSize();\n const bool parsing_32 = byte_size == 4;\n\n \/\/ Read p_type;\n if (data.GetU32(offset, &p_type, 1) == NULL)\n return false;\n\n if (parsing_32) {\n \/\/ Read p_offset, p_vaddr, p_paddr, p_filesz and p_memsz.\n if (GetMaxU64(data, offset, &p_offset, byte_size, 5) == false)\n return false;\n\n \/\/ Read p_flags.\n if (data.GetU32(offset, &p_flags, 1) == NULL)\n return false;\n\n \/\/ Read p_align.\n if (GetMaxU64(data, offset, &p_align, byte_size) == false)\n return false;\n }\n else {\n \/\/ Read p_flags.\n if (data.GetU32(offset, &p_flags, 1) == NULL)\n return false;\n\n \/\/ Read p_offset, p_vaddr, p_paddr, p_filesz, p_memsz and p_align.\n if (GetMaxU64(data, offset, &p_offset, byte_size, 6) == false)\n return false;\n }\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFDynamic\n\nELFDynamic::ELFDynamic() \n{ \n memset(this, 0, sizeof(ELFDynamic)); \n}\n\nbool\nELFDynamic::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n return GetMaxS64(data, offset, &d_tag, byte_size, 2);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFRel\n\nELFRel::ELFRel()\n{\n memset(this, 0, sizeof(ELFRel));\n}\n\nbool\nELFRel::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read r_offset and r_info.\n if (GetMaxU64(data, offset, &r_offset, byte_size, 2) == false)\n return false;\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFRela\n\nELFRela::ELFRela()\n{\n memset(this, 0, sizeof(ELFRela));\n}\n\nbool\nELFRela::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read r_offset and r_info.\n if (GetMaxU64(data, offset, &r_offset, byte_size, 2) == false)\n return false;\n\n \/\/ Read r_addend;\n if (GetMaxS64(data, offset, &r_addend, byte_size) == false)\n return false;\n\n return true;\n}\n\n\n<commit_msg>Fix build breakage after llvm r240426<commit_after>\/\/===-- ELFHeader.cpp ----------------------------------------- -*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <cstring>\n\n#include \"lldb\/Core\/DataExtractor.h\"\n#include \"lldb\/Core\/Section.h\"\n#include \"lldb\/Core\/Stream.h\"\n\n#include \"ELFHeader.h\"\n\nusing namespace elf;\nusing namespace lldb;\nusing namespace llvm::ELF;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Static utility functions.\n\/\/\n\/\/ GetMaxU64 and GetMaxS64 wrap the similarly named methods from DataExtractor\n\/\/ with error handling code and provide for parsing a sequence of values.\nstatic bool\nGetMaxU64(const lldb_private::DataExtractor &data,\n lldb::offset_t *offset,\n uint64_t *value,\n uint32_t byte_size)\n{\n const lldb::offset_t saved_offset = *offset;\n *value = data.GetMaxU64(offset, byte_size);\n return *offset != saved_offset;\n}\n\nstatic bool\nGetMaxU64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n uint64_t *value,\n uint32_t byte_size,\n uint32_t count) \n{\n lldb::offset_t saved_offset = *offset;\n\n for (uint32_t i = 0; i < count; ++i, ++value)\n {\n if (GetMaxU64(data, offset, value, byte_size) == false) \n {\n *offset = saved_offset;\n return false;\n }\n }\n return true;\n}\n\nstatic bool\nGetMaxS64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n int64_t *value,\n uint32_t byte_size)\n{\n const lldb::offset_t saved_offset = *offset;\n *value = data.GetMaxS64(offset, byte_size);\n return *offset != saved_offset;\n}\n\nstatic bool\nGetMaxS64(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset,\n int64_t *value,\n uint32_t byte_size,\n uint32_t count) \n{\n lldb::offset_t saved_offset = *offset;\n\n for (uint32_t i = 0; i < count; ++i, ++value)\n {\n if (GetMaxS64(data, offset, value, byte_size) == false) \n {\n *offset = saved_offset;\n return false;\n }\n }\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFHeader\n\nELFHeader::ELFHeader()\n{\n memset(this, 0, sizeof(ELFHeader)); \n}\n\nByteOrder\nELFHeader::GetByteOrder() const \n{\n if (e_ident[EI_DATA] == ELFDATA2MSB)\n return eByteOrderBig;\n if (e_ident[EI_DATA] == ELFDATA2LSB)\n return eByteOrderLittle;\n return eByteOrderInvalid;\n}\n\nbool\nELFHeader::Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset) \n{\n \/\/ Read e_ident. This provides byte order and address size info.\n if (data.GetU8(offset, &e_ident, EI_NIDENT) == NULL)\n return false;\n\n const unsigned byte_size = Is32Bit() ? 4 : 8;\n data.SetByteOrder(GetByteOrder());\n data.SetAddressByteSize(byte_size);\n\n \/\/ Read e_type and e_machine.\n if (data.GetU16(offset, &e_type, 2) == NULL)\n return false;\n\n \/\/ Read e_version.\n if (data.GetU32(offset, &e_version, 1) == NULL)\n return false;\n\n \/\/ Read e_entry, e_phoff and e_shoff.\n if (GetMaxU64(data, offset, &e_entry, byte_size, 3) == false)\n return false;\n\n \/\/ Read e_flags.\n if (data.GetU32(offset, &e_flags, 1) == NULL)\n return false;\n\n \/\/ Read e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum and\n \/\/ e_shstrndx.\n if (data.GetU16(offset, &e_ehsize, 6) == NULL)\n return false;\n\n return true;\n}\n\nbool\nELFHeader::MagicBytesMatch(const uint8_t *magic)\n{\n return memcmp(magic, ElfMagic, strlen(ElfMagic)) == 0;\n}\n\nunsigned\nELFHeader::AddressSizeInBytes(const uint8_t *magic)\n{\n unsigned address_size = 0;\n\n switch (magic[EI_CLASS]) \n {\n case ELFCLASS32:\n address_size = 4;\n break;\n \n case ELFCLASS64:\n address_size = 8;\n break;\n }\n return address_size;\n}\n\nunsigned\nELFHeader::GetRelocationJumpSlotType() const\n{\n unsigned slot = 0;\n\n switch (e_machine)\n {\n default:\n assert(false && \"architecture not supported\");\n break;\n case EM_PPC:\n slot = R_PPC_JMP_SLOT;\n break;\n case EM_PPC64:\n slot = R_PPC64_JMP_SLOT;\n break;\n case EM_386:\n case EM_IAMCU: \/\/ FIXME: is this correct?\n slot = R_386_JUMP_SLOT;\n break;\n case EM_X86_64:\n slot = R_X86_64_JUMP_SLOT;\n break;\n case EM_ARM:\n slot = R_ARM_JUMP_SLOT;\n break;\n case EM_HEXAGON:\n slot = R_HEX_JMP_SLOT;\n break;\n case EM_AARCH64:\n slot = R_AARCH64_JUMP_SLOT;\n break;\n case EM_MIPS:\n slot = R_MIPS_JUMP_SLOT;\n break;\n }\n\n return slot;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFSectionHeader\n\nELFSectionHeader::ELFSectionHeader() \n{\n memset(this, 0, sizeof(ELFSectionHeader));\n}\n\nbool\nELFSectionHeader::Parse(const lldb_private::DataExtractor &data,\n lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read sh_name and sh_type.\n if (data.GetU32(offset, &sh_name, 2) == NULL)\n return false;\n\n \/\/ Read sh_flags.\n if (GetMaxU64(data, offset, &sh_flags, byte_size) == false)\n return false;\n\n \/\/ Read sh_addr, sh_off and sh_size.\n if (GetMaxU64(data, offset, &sh_addr, byte_size, 3) == false)\n return false;\n\n \/\/ Read sh_link and sh_info.\n if (data.GetU32(offset, &sh_link, 2) == NULL)\n return false;\n\n \/\/ Read sh_addralign and sh_entsize.\n if (GetMaxU64(data, offset, &sh_addralign, byte_size, 2) == false)\n return false;\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFSymbol\n\nELFSymbol::ELFSymbol() \n{\n memset(this, 0, sizeof(ELFSymbol));\n}\n\n#define ENUM_TO_CSTR(e) case e: return #e\n\nconst char *\nELFSymbol::bindingToCString(unsigned char binding)\n{\n switch (binding)\n {\n ENUM_TO_CSTR(STB_LOCAL);\n ENUM_TO_CSTR(STB_GLOBAL);\n ENUM_TO_CSTR(STB_WEAK);\n ENUM_TO_CSTR(STB_LOOS);\n ENUM_TO_CSTR(STB_HIOS);\n ENUM_TO_CSTR(STB_LOPROC);\n ENUM_TO_CSTR(STB_HIPROC);\n }\n return \"\";\n}\n\nconst char *\nELFSymbol::typeToCString(unsigned char type)\n{\n switch (type)\n {\n ENUM_TO_CSTR(STT_NOTYPE);\n ENUM_TO_CSTR(STT_OBJECT);\n ENUM_TO_CSTR(STT_FUNC);\n ENUM_TO_CSTR(STT_SECTION);\n ENUM_TO_CSTR(STT_FILE);\n ENUM_TO_CSTR(STT_COMMON);\n ENUM_TO_CSTR(STT_TLS);\n ENUM_TO_CSTR(STT_GNU_IFUNC);\n ENUM_TO_CSTR(STT_HIOS);\n ENUM_TO_CSTR(STT_LOPROC);\n ENUM_TO_CSTR(STT_HIPROC);\n }\n return \"\";\n}\n\nconst char *\nELFSymbol::sectionIndexToCString (elf_half shndx,\n const lldb_private::SectionList *section_list)\n{\n switch (shndx)\n {\n ENUM_TO_CSTR(SHN_UNDEF);\n ENUM_TO_CSTR(SHN_LOPROC);\n ENUM_TO_CSTR(SHN_HIPROC);\n ENUM_TO_CSTR(SHN_LOOS);\n ENUM_TO_CSTR(SHN_HIOS);\n ENUM_TO_CSTR(SHN_ABS);\n ENUM_TO_CSTR(SHN_COMMON);\n ENUM_TO_CSTR(SHN_XINDEX);\n default:\n {\n const lldb_private::Section *section = section_list->GetSectionAtIndex(shndx).get();\n if (section)\n return section->GetName().AsCString(\"\");\n }\n break;\n }\n return \"\";\n}\n\nvoid\nELFSymbol::Dump (lldb_private::Stream *s,\n uint32_t idx,\n const lldb_private::DataExtractor *strtab_data,\n const lldb_private::SectionList *section_list)\n{\n s->Printf(\"[%3u] 0x%16.16\" PRIx64 \" 0x%16.16\" PRIx64 \" 0x%8.8x 0x%2.2x (%-10s %-13s) 0x%2.2x 0x%4.4x (%-10s) %s\\n\",\n idx,\n st_value,\n st_size,\n st_name,\n st_info,\n bindingToCString (getBinding()),\n typeToCString (getType()),\n st_other,\n st_shndx,\n sectionIndexToCString (st_shndx, section_list),\n strtab_data ? strtab_data->PeekCStr(st_name) : \"\");\n}\n\nbool\nELFSymbol::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n const bool parsing_32 = byte_size == 4;\n\n \/\/ Read st_name.\n if (data.GetU32(offset, &st_name, 1) == NULL)\n return false;\n\n if (parsing_32) \n {\n \/\/ Read st_value and st_size.\n if (GetMaxU64(data, offset, &st_value, byte_size, 2) == false)\n return false;\n\n \/\/ Read st_info and st_other.\n if (data.GetU8(offset, &st_info, 2) == NULL)\n return false;\n \n \/\/ Read st_shndx.\n if (data.GetU16(offset, &st_shndx, 1) == NULL)\n return false;\n }\n else \n {\n \/\/ Read st_info and st_other.\n if (data.GetU8(offset, &st_info, 2) == NULL)\n return false;\n \n \/\/ Read st_shndx.\n if (data.GetU16(offset, &st_shndx, 1) == NULL)\n return false;\n\n \/\/ Read st_value and st_size.\n if (data.GetU64(offset, &st_value, 2) == NULL)\n return false;\n }\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFProgramHeader\n\nELFProgramHeader::ELFProgramHeader() \n{\n memset(this, 0, sizeof(ELFProgramHeader));\n}\n\nbool\nELFProgramHeader::Parse(const lldb_private::DataExtractor &data, \n lldb::offset_t *offset)\n{\n const uint32_t byte_size = data.GetAddressByteSize();\n const bool parsing_32 = byte_size == 4;\n\n \/\/ Read p_type;\n if (data.GetU32(offset, &p_type, 1) == NULL)\n return false;\n\n if (parsing_32) {\n \/\/ Read p_offset, p_vaddr, p_paddr, p_filesz and p_memsz.\n if (GetMaxU64(data, offset, &p_offset, byte_size, 5) == false)\n return false;\n\n \/\/ Read p_flags.\n if (data.GetU32(offset, &p_flags, 1) == NULL)\n return false;\n\n \/\/ Read p_align.\n if (GetMaxU64(data, offset, &p_align, byte_size) == false)\n return false;\n }\n else {\n \/\/ Read p_flags.\n if (data.GetU32(offset, &p_flags, 1) == NULL)\n return false;\n\n \/\/ Read p_offset, p_vaddr, p_paddr, p_filesz, p_memsz and p_align.\n if (GetMaxU64(data, offset, &p_offset, byte_size, 6) == false)\n return false;\n }\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFDynamic\n\nELFDynamic::ELFDynamic() \n{ \n memset(this, 0, sizeof(ELFDynamic)); \n}\n\nbool\nELFDynamic::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n return GetMaxS64(data, offset, &d_tag, byte_size, 2);\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFRel\n\nELFRel::ELFRel()\n{\n memset(this, 0, sizeof(ELFRel));\n}\n\nbool\nELFRel::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read r_offset and r_info.\n if (GetMaxU64(data, offset, &r_offset, byte_size, 2) == false)\n return false;\n\n return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ ELFRela\n\nELFRela::ELFRela()\n{\n memset(this, 0, sizeof(ELFRela));\n}\n\nbool\nELFRela::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)\n{\n const unsigned byte_size = data.GetAddressByteSize();\n\n \/\/ Read r_offset and r_info.\n if (GetMaxU64(data, offset, &r_offset, byte_size, 2) == false)\n return false;\n\n \/\/ Read r_addend;\n if (GetMaxS64(data, offset, &r_addend, byte_size) == false)\n return false;\n\n return true;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2012 Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"coverage_join.hh\"\n#include \"helper.hh\"\n\nCoverage_Join::Coverage_Join(Log& l,const std::string& param)\n : Coverage(l), child(NULL)\n{\n commalist(param,subs);\n if (subs.size()>1) {\n child=new_coverage(l,subs.back());\n }\n status&=(child!=NULL);\n}\n\nvoid Coverage_Join::handle_sub(const std::string& sub)\n{\n std::string mapped_to;\n std::string tmp;\n std::vector<std::string> mapped_from;\n \n param_cut(sub,mapped_to,tmp);\n commalist(tmp,mapped_from);\n \/\/ mapped_to is the _new_ alphabet\n \/\/ mapped_from is the alphas found in the current alphabet\n \/\/ Let's check that mapped_to doesn't exist in the ActionNames\n if (find(ActionNames,mapped_to)) {\n status=false;\n errormsg=mapped_to+\" found twice\";\n }\n\n log.debug(\"Mapping action %s\\n\",mapped_to.c_str());\n\n ActionNames.push_back(mapped_to);\n for(unsigned i=0;i<mapped_from.size();i++) {\n int pos=find(ActionNames_from,mapped_from[i]);\n log.debug(\"Handling mapping at %i (%s) pos %i\\n\",i,mapped_from[i].c_str(),pos);\n if (!pos) {\n \/\/ No luck? RegExp?\n log.debug(\"No luck... %s\\n\",mapped_from[i].c_str());\n } else {\n int m=ActionNames.size()-1;\n action_mapper[pos]=m;\n ActionNames_from[pos]=\"\"; \/\/ Only one map....\n }\n }\n}\n\nvoid Coverage_Join::set_model(Model* _model)\n{\n Coverage::set_model(_model);\n ActionNames.push_back(\"\"); \/\/ TAU\n\n ActionNames_from=model->getActionNames();\n\n for(unsigned i=0;i<subs.size()-1;i++) {\n if (!status) {\n return;\n }\n handle_sub(subs[i]);\n }\n\n log.debug(\"action_names count %i\\n\",ActionNames.size());\n\n \/\/ Let's handle not mapped actions\n\n for(unsigned i=0;i<ActionNames_from.size();i++) {\n if (ActionNames_from[i]!=\"\") {\n int m=ActionNames.size();\n\n log.debug(\"Action %i (%s) not mapped. Mapping to %i\\n\",\n\t i,ActionNames_from[i].c_str(),m);\n\n ActionNames.push_back(ActionNames_from[i]);\n action_mapper[i]=m;\n }\n }\n\n ActionNames_from.clear();\n\n alpha=new Alphabet_impl(ActionNames,SPNames);\n submodel=new Model_yes(log,\"\");\n submodel->set_model(alpha);\n child->set_model(submodel);\n}\n\nFACTORY_DEFAULT_CREATOR(Coverage, Coverage_Join, \"join\")\n<commit_msg>coverage join: Better error handling<commit_after>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2012 Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"coverage_join.hh\"\n#include \"helper.hh\"\n\nCoverage_Join::Coverage_Join(Log& l,const std::string& param)\n : Coverage(l), child(NULL)\n{\n commalist(param,subs);\n\n if (subs.size()>1) {\n child=new_coverage(l,subs.back());\n }\n\n if (child==NULL) {\n status=false;\n errormsg=\"Can't create coverage:\"+subs.back();\n return;\n }\n\n if (!child->status) {\n status=false;\n errormsg=\"coverage error at \"+subs.back()+ \":\"+ child->errormsg;\n }\n\n}\n\nvoid Coverage_Join::handle_sub(const std::string& sub)\n{\n std::string mapped_to;\n std::string tmp;\n std::vector<std::string> mapped_from;\n \n param_cut(sub,mapped_to,tmp);\n commalist(tmp,mapped_from);\n \/\/ mapped_to is the _new_ alphabet\n \/\/ mapped_from is the alphas found in the current alphabet\n \/\/ Let's check that mapped_to doesn't exist in the ActionNames\n if (find(ActionNames,mapped_to)) {\n status=false;\n errormsg=mapped_to+\" found twice\";\n }\n\n log.debug(\"Mapping action %s\\n\",mapped_to.c_str());\n\n ActionNames.push_back(mapped_to);\n for(unsigned i=0;i<mapped_from.size();i++) {\n int pos=find(ActionNames_from,mapped_from[i]);\n log.debug(\"Handling mapping at %i (%s) pos %i\\n\",i,mapped_from[i].c_str(),pos);\n if (!pos) {\n \/\/ No luck? RegExp?\n log.debug(\"No luck... %s\\n\",mapped_from[i].c_str());\n } else {\n int m=ActionNames.size()-1;\n action_mapper[pos]=m;\n ActionNames_from[pos]=\"\"; \/\/ Only one map....\n }\n }\n}\n\nvoid Coverage_Join::set_model(Model* _model)\n{\n Coverage::set_model(_model);\n ActionNames.push_back(\"\"); \/\/ TAU\n\n ActionNames_from=model->getActionNames();\n\n for(unsigned i=0;i<subs.size()-1;i++) {\n if (!status) {\n return;\n }\n handle_sub(subs[i]);\n }\n\n log.debug(\"action_names count %i\\n\",ActionNames.size());\n\n \/\/ Let's handle not mapped actions\n\n for(unsigned i=0;i<ActionNames_from.size();i++) {\n if (ActionNames_from[i]!=\"\") {\n int m=ActionNames.size();\n\n log.debug(\"Action %i (%s) not mapped. Mapping to %i\\n\",\n\t i,ActionNames_from[i].c_str(),m);\n\n ActionNames.push_back(ActionNames_from[i]);\n action_mapper[i]=m;\n }\n }\n\n ActionNames_from.clear();\n\n alpha=new Alphabet_impl(ActionNames,SPNames);\n submodel=new Model_yes(log,\"\");\n submodel->set_model(alpha);\n child->set_model(submodel);\n}\n\nFACTORY_DEFAULT_CREATOR(Coverage, Coverage_Join, \"join\")\n<|endoftext|>"} {"text":"<commit_before>#include <istream>\n\n#include \"..\/..\/hpp\/tom\/tom.hpp\"\n\n#include \"..\/..\/hpp\/ax\/ax.hpp\"\n\nnamespace ax\n{\n \/\/ A trivial program type to demonstrate the eventable program mixin.\n class eventable_test : public eventable<eventable_test>\n {\n protected:\n enable_cast(eventable_test, eventable<eventable_test>);\n };\n\n class inspectable_test : public inspectable\n {\n protected:\n\n enable_cast(inspectable_test, inspectable);\n\n const std::shared_ptr<type_t> type = register_sub_type<inspectable_test>(typeid(inspectable),\n {\n { \"bool_value\", register_field<bool> (offsetof(inspectable_test, bool_value)) },\n { \"int_value\", register_field<int> (offsetof(inspectable_test, int_value)) },\n { \"float_value\", register_field<float> (offsetof(inspectable_test, float_value)) },\n { \"name_value\", register_field<name_t> (offsetof(inspectable_test, name_value)) },\n { \"address_value\", register_field<address> (offsetof(inspectable_test, address_value)) },\n { \"vector_int_value\", register_field<std::vector<int>> (offsetof(inspectable_test, vector_int_value)) },\n { \"vector_string_value\", register_field<std::vector<std::string>> (offsetof(inspectable_test, vector_string_value)) },\n { \"unique_int_value\", register_field<std::unique_ptr<int>> (offsetof(inspectable_test, unique_int_value)) },\n { \"shared_int_value\", register_field<std::shared_ptr<int>> (offsetof(inspectable_test, shared_int_value)) },\n { \"pair_value\", register_field<pair<int, int>> (offsetof(inspectable_test, pair_value)) },\n { \"record_value\", register_field<record<int, int, int>> (offsetof(inspectable_test, record_value)) },\n { \"option_some_value\", register_field<option<int>> (offsetof(inspectable_test, option_some_value)) },\n { \"option_none_value\", register_field<option<int>> (offsetof(inspectable_test, option_none_value)) },\n { \"either_right_value\", register_field<either<std::string, int>> (offsetof(inspectable_test, either_right_value)) },\n { \"either_left_value\", register_field<either<std::string, int>> (offsetof(inspectable_test, either_left_value)) },\n { \"choice_value\", register_field<choice<int, int, int>> (offsetof(inspectable_test, choice_value)) }\n });\n\n std::shared_ptr<type_t> get_type_impl() const override\n {\n return type;\n };\n\n public:\n\n int bool_value;\n int int_value;\n float float_value;\n name_t name_value;\n address address_value;\n std::vector<int> vector_int_value;\n std::vector<std::string> vector_string_value;\n std::unique_ptr<int> unique_int_value;\n std::shared_ptr<int> shared_int_value;\n pair<int, int> pair_value;\n record<int, int, int> record_value;\n option<int> option_some_value;\n option<int> option_none_value;\n either<std::string, int> either_right_value;\n either<std::string, int> either_left_value;\n choice<int, int, int> choice_value;\n\n inspectable_test() :\n bool_value(),\n int_value(),\n float_value(),\n name_value(),\n address_value(),\n vector_int_value(),\n vector_string_value(),\n unique_int_value(std::make_unique<int>()),\n shared_int_value(std::make_shared<int>()),\n pair_value(),\n record_value(),\n option_some_value(),\n option_none_value(),\n either_right_value(),\n either_left_value(),\n choice_value()\n { }\n\n inspectable_test(\n bool bool_value,\n int int_value,\n float float_value,\n name_t name_value,\n address address_value,\n const std::vector<int>& vector_int_value,\n const std::vector<std::string>& vector_string_value,\n int unique_int_value,\n int shared_int_value,\n pair<int, int> pair_value,\n record<int, int, int> record_value,\n option<int> option_some_value,\n option<int> option_none_value,\n either<std::string, int> either_right_value,\n either<std::string, int> either_left_value,\n choice<int, int, int> choice_value) :\n bool_value(bool_value),\n int_value(int_value),\n float_value(float_value),\n name_value(name_value),\n address_value(address_value),\n vector_int_value(vector_int_value),\n vector_string_value(vector_string_value),\n unique_int_value(std::make_unique<int>(unique_int_value)),\n shared_int_value(std::make_shared<int>(shared_int_value)),\n pair_value(pair_value),\n record_value(record_value),\n option_some_value(option_some_value),\n option_none_value(option_none_value),\n either_right_value(either_right_value),\n either_left_value(either_left_value),\n choice_value(choice_value)\n { }\n };\n\n TEST(\"hash works\")\n {\n CHECK(ax::get_hash(0) == std::hash<int>()(0));\n }\n\n TEST(\"castable works\")\n {\n \/\/ TODO: implement\n }\n\n TEST(\"events work\")\n {\n var i = 0;\n ax::eventable_test program{};\n val& event_address = address(\"event\");\n val& participant = std::make_shared<ax::addressable>(\"participant\");\n var handler = [&](val&, val&) { return ++i, true; };\n var unsubscriber = ax::subscribe_event<std::string>(program, event_address, participant, handler);\n ax::publish_event(program, \"Event handled!\"_s, event_address, participant);\n unsubscriber(program);\n ax::publish_event(program, \"Event unhandled.\"_s, event_address, participant);\n CHECK(i == 1);\n }\n\n TEST(\"read and write value works\")\n {\n symbol symbol{};\n inspectable_test source(\n true, 5, 10.0f, \"jim bob\", address(\"s\/compton\/la\"),\n { 1, 3, 5 }, { \"a\", \"bb\", \"ccc\" }, 666, 777,\n make_pair(50, 100), make_record(150, 200, 250),\n some(2), none<int>(), right<std::string>(4), left<std::string, int>(\"msg\"), third<int, int>(3));\n inspectable_test target{};\n write_value(source, symbol);\n read_value(symbol, target);\n CHECK(target.bool_value);\n CHECK(target.int_value == 5);\n CHECK(target.float_value == 10.0f);\n CHECK(target.name_value == \"jim bob\");\n CHECK(target.address_value == address(\"s\/compton\/la\"));\n CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 }));\n CHECK(target.vector_string_value == std::vector<std::string>({ \"a\", \"bb\", \"ccc\" }));\n CHECK(*target.unique_int_value == 666);\n CHECK(*target.shared_int_value == 777);\n CHECK(fst(target.pair_value) == 50);\n CHECK(snd(target.pair_value) == 100);\n CHECK(fst(target.record_value) == 150);\n CHECK(snd(target.record_value) == 200);\n CHECK(thd(target.record_value) == 250);\n CHECK(*target.option_some_value == 2);\n CHECK(is_none(target.option_none_value));\n CHECK(*target.either_right_value == 4);\n CHECK(~target.either_left_value == \"msg\");\n CHECK(get_third(target.choice_value) == 3);\n }\n\n TEST(\"parser works\")\n {\n val& str =\n \"[true 5 10.0 \\\n \\\"jim bob\\\" \\\n \\\"s\/compton\/la\\\" \\\n [1 3 5] \\\n [\\\"a\\\" \\\"bb\\\" \\\"ccc\\\"] \\\n 666 \\\n 777 \\\n [50 100] \\\n [150 200 250] \\\n [some 2] \\\n none \\\n [right 4] \\\n [left \\\"msg\\\"] \\\n [third 3]]\";\n std::stringstream sstr(str);\n sstr << std::noskipws; \/\/ apparently avoids skipping whitespace\n std::istream_iterator<char> iter(sstr);\n val& parse = parse_symbol_from_stream(iter, std::istream_iterator<char>());\n val& symbol = get_parse_success(parse);\n inspectable_test target{};\n read_value(symbol, target);\n CHECK(target.bool_value);\n CHECK(target.int_value == 5);\n CHECK(target.float_value == 10.0f);\n CHECK(target.name_value == \"jim bob\");\n CHECK(target.address_value == address(\"s\/compton\/la\"));\n CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 }));\n CHECK(target.vector_string_value == std::vector<std::string>({ \"a\", \"bb\", \"ccc\" }));\n CHECK(*target.unique_int_value == 666);\n CHECK(*target.shared_int_value == 777);\n CHECK(fst(target.pair_value) == 50);\n CHECK(snd(target.pair_value) == 100);\n CHECK(fst(target.record_value) == 150);\n CHECK(snd(target.record_value) == 200);\n CHECK(thd(target.record_value) == 250);\n CHECK(*target.option_some_value == 2);\n CHECK(is_none(target.option_none_value));\n CHECK(*target.either_right_value == 4);\n CHECK(~target.either_left_value == \"msg\");\n CHECK(get_third(target.choice_value) == 3);\n }\n\n TEST(\"properties work\")\n {\n \/\/ TODO: implement\n }\n}\n<commit_msg>Added a little extra whitespace to try to throw off parser.<commit_after>#include <istream>\n\n#include \"..\/..\/hpp\/tom\/tom.hpp\"\n\n#include \"..\/..\/hpp\/ax\/ax.hpp\"\n\nnamespace ax\n{\n \/\/ A trivial program type to demonstrate the eventable program mixin.\n class eventable_test : public eventable<eventable_test>\n {\n protected:\n enable_cast(eventable_test, eventable<eventable_test>);\n };\n\n class inspectable_test : public inspectable\n {\n protected:\n\n enable_cast(inspectable_test, inspectable);\n\n const std::shared_ptr<type_t> type = register_sub_type<inspectable_test>(typeid(inspectable),\n {\n { \"bool_value\", register_field<bool> (offsetof(inspectable_test, bool_value)) },\n { \"int_value\", register_field<int> (offsetof(inspectable_test, int_value)) },\n { \"float_value\", register_field<float> (offsetof(inspectable_test, float_value)) },\n { \"name_value\", register_field<name_t> (offsetof(inspectable_test, name_value)) },\n { \"address_value\", register_field<address> (offsetof(inspectable_test, address_value)) },\n { \"vector_int_value\", register_field<std::vector<int>> (offsetof(inspectable_test, vector_int_value)) },\n { \"vector_string_value\", register_field<std::vector<std::string>> (offsetof(inspectable_test, vector_string_value)) },\n { \"unique_int_value\", register_field<std::unique_ptr<int>> (offsetof(inspectable_test, unique_int_value)) },\n { \"shared_int_value\", register_field<std::shared_ptr<int>> (offsetof(inspectable_test, shared_int_value)) },\n { \"pair_value\", register_field<pair<int, int>> (offsetof(inspectable_test, pair_value)) },\n { \"record_value\", register_field<record<int, int, int>> (offsetof(inspectable_test, record_value)) },\n { \"option_some_value\", register_field<option<int>> (offsetof(inspectable_test, option_some_value)) },\n { \"option_none_value\", register_field<option<int>> (offsetof(inspectable_test, option_none_value)) },\n { \"either_right_value\", register_field<either<std::string, int>> (offsetof(inspectable_test, either_right_value)) },\n { \"either_left_value\", register_field<either<std::string, int>> (offsetof(inspectable_test, either_left_value)) },\n { \"choice_value\", register_field<choice<int, int, int>> (offsetof(inspectable_test, choice_value)) }\n });\n\n std::shared_ptr<type_t> get_type_impl() const override\n {\n return type;\n };\n\n public:\n\n int bool_value;\n int int_value;\n float float_value;\n name_t name_value;\n address address_value;\n std::vector<int> vector_int_value;\n std::vector<std::string> vector_string_value;\n std::unique_ptr<int> unique_int_value;\n std::shared_ptr<int> shared_int_value;\n pair<int, int> pair_value;\n record<int, int, int> record_value;\n option<int> option_some_value;\n option<int> option_none_value;\n either<std::string, int> either_right_value;\n either<std::string, int> either_left_value;\n choice<int, int, int> choice_value;\n\n inspectable_test() :\n bool_value(),\n int_value(),\n float_value(),\n name_value(),\n address_value(),\n vector_int_value(),\n vector_string_value(),\n unique_int_value(std::make_unique<int>()),\n shared_int_value(std::make_shared<int>()),\n pair_value(),\n record_value(),\n option_some_value(),\n option_none_value(),\n either_right_value(),\n either_left_value(),\n choice_value()\n { }\n\n inspectable_test(\n bool bool_value,\n int int_value,\n float float_value,\n name_t name_value,\n address address_value,\n const std::vector<int>& vector_int_value,\n const std::vector<std::string>& vector_string_value,\n int unique_int_value,\n int shared_int_value,\n pair<int, int> pair_value,\n record<int, int, int> record_value,\n option<int> option_some_value,\n option<int> option_none_value,\n either<std::string, int> either_right_value,\n either<std::string, int> either_left_value,\n choice<int, int, int> choice_value) :\n bool_value(bool_value),\n int_value(int_value),\n float_value(float_value),\n name_value(name_value),\n address_value(address_value),\n vector_int_value(vector_int_value),\n vector_string_value(vector_string_value),\n unique_int_value(std::make_unique<int>(unique_int_value)),\n shared_int_value(std::make_shared<int>(shared_int_value)),\n pair_value(pair_value),\n record_value(record_value),\n option_some_value(option_some_value),\n option_none_value(option_none_value),\n either_right_value(either_right_value),\n either_left_value(either_left_value),\n choice_value(choice_value)\n { }\n };\n\n TEST(\"hash works\")\n {\n CHECK(ax::get_hash(0) == std::hash<int>()(0));\n }\n\n TEST(\"castable works\")\n {\n \/\/ TODO: implement\n }\n\n TEST(\"events work\")\n {\n var i = 0;\n ax::eventable_test program{};\n val& event_address = address(\"event\");\n val& participant = std::make_shared<ax::addressable>(\"participant\");\n var handler = [&](val&, val&) { return ++i, true; };\n var unsubscriber = ax::subscribe_event<std::string>(program, event_address, participant, handler);\n ax::publish_event(program, \"Event handled!\"_s, event_address, participant);\n unsubscriber(program);\n ax::publish_event(program, \"Event unhandled.\"_s, event_address, participant);\n CHECK(i == 1);\n }\n\n TEST(\"read and write value works\")\n {\n symbol symbol{};\n inspectable_test source(\n true, 5, 10.0f, \"jim bob\", address(\"s\/compton\/la\"),\n { 1, 3, 5 }, { \"a\", \"bb\", \"ccc\" }, 666, 777,\n make_pair(50, 100), make_record(150, 200, 250),\n some(2), none<int>(), right<std::string>(4), left<std::string, int>(\"msg\"), third<int, int>(3));\n inspectable_test target{};\n write_value(source, symbol);\n read_value(symbol, target);\n CHECK(target.bool_value);\n CHECK(target.int_value == 5);\n CHECK(target.float_value == 10.0f);\n CHECK(target.name_value == \"jim bob\");\n CHECK(target.address_value == address(\"s\/compton\/la\"));\n CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 }));\n CHECK(target.vector_string_value == std::vector<std::string>({ \"a\", \"bb\", \"ccc\" }));\n CHECK(*target.unique_int_value == 666);\n CHECK(*target.shared_int_value == 777);\n CHECK(fst(target.pair_value) == 50);\n CHECK(snd(target.pair_value) == 100);\n CHECK(fst(target.record_value) == 150);\n CHECK(snd(target.record_value) == 200);\n CHECK(thd(target.record_value) == 250);\n CHECK(*target.option_some_value == 2);\n CHECK(is_none(target.option_none_value));\n CHECK(*target.either_right_value == 4);\n CHECK(~target.either_left_value == \"msg\");\n CHECK(get_third(target.choice_value) == 3);\n }\n\n TEST(\"parser works\")\n {\n val& str =\n \"[true 5 10.0 \\\n \\\"jim bob\\\" \\\n \\\"s\/compton\/la\\\" \\\n [1 3 5] \\\n [\\\"a\\\" \\\"bb\\\" \\\"ccc\\\"] \\\n 666 \\\n 777 \\\n [50 100] \\\n [150 200 250] \\\n [some 2] \\\n none \\\n [right 4] \\\n [left \\\"msg\\\"] \\\n [ third 3 ] ]\"; \/\/ a little extra whitespace to try to throw off parser\n std::stringstream sstr(str);\n sstr << std::noskipws; \/\/ apparently avoids skipping whitespace\n std::istream_iterator<char> iter(sstr);\n val& parse = parse_symbol_from_stream(iter, std::istream_iterator<char>());\n val& symbol = get_parse_success(parse);\n inspectable_test target{};\n read_value(symbol, target);\n CHECK(target.bool_value);\n CHECK(target.int_value == 5);\n CHECK(target.float_value == 10.0f);\n CHECK(target.name_value == \"jim bob\");\n CHECK(target.address_value == address(\"s\/compton\/la\"));\n CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 }));\n CHECK(target.vector_string_value == std::vector<std::string>({ \"a\", \"bb\", \"ccc\" }));\n CHECK(*target.unique_int_value == 666);\n CHECK(*target.shared_int_value == 777);\n CHECK(fst(target.pair_value) == 50);\n CHECK(snd(target.pair_value) == 100);\n CHECK(fst(target.record_value) == 150);\n CHECK(snd(target.record_value) == 200);\n CHECK(thd(target.record_value) == 250);\n CHECK(*target.option_some_value == 2);\n CHECK(is_none(target.option_none_value));\n CHECK(*target.either_right_value == 4);\n CHECK(~target.either_left_value == \"msg\");\n CHECK(get_third(target.choice_value) == 3);\n }\n\n TEST(\"properties work\")\n {\n \/\/ TODO: implement\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"foo.hpp\"\n\ntemplate <typename T>\nT foo(T x) {\n return 2 * x;\n}\n\n<commit_msg>added header guard to template instantiation demo<commit_after>#ifndef _FOO_DEF_HPP\n#define _FOO_DEF_HPP\n\n#include \"foo.hpp\"\n\ntemplate <typename T>\nT foo(T x) {\n return 2 * x;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/scal\/meta\/ad_promotable.hpp>\n#include <gtest\/gtest.h>\n\nTEST(MathMeta, primitive_to_double) {\n EXPECT_TRUE((stan::math::ad_promotable<bool, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<char, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<unsigned char, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<short, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<unsigned short, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<int, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<unsigned int, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<long, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<unsigned long, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<long long, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<unsigned long long, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<float, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<double, double>::value)); \n EXPECT_TRUE((stan::math::ad_promotable<long double, double>::value)); \n}\n\nTEST(MathMeta, primitive_to_float) {\n EXPECT_FALSE((stan::math::ad_promotable<bool, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<char, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<unsigned char, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<short, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<unsigned short, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<int, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<unsigned int, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<long, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<unsigned long, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<long long, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<unsigned long long, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<double, float>::value)); \n EXPECT_FALSE((stan::math::ad_promotable<long double, float>::value));\n \n EXPECT_TRUE((stan::math::ad_promotable<float, float>::value))\n << \"All primitive types should be promotable to the same type\";\n}\n<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags\/RELEASE_500\/final)<commit_after>#include <stan\/math\/prim\/scal\/meta\/ad_promotable.hpp>\n#include <gtest\/gtest.h>\n\nTEST(MathMeta, primitive_to_double) {\n EXPECT_TRUE((stan::math::ad_promotable<bool, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<char, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<unsigned char, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<short, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<unsigned short, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<int, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<unsigned int, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<long, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<unsigned long, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<long long, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<unsigned long long, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<float, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<double, double>::value));\n EXPECT_TRUE((stan::math::ad_promotable<long double, double>::value));\n}\n\nTEST(MathMeta, primitive_to_float) {\n EXPECT_FALSE((stan::math::ad_promotable<bool, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<char, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<unsigned char, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<short, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<unsigned short, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<int, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<unsigned int, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<long, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<unsigned long, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<long long, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<unsigned long long, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<double, float>::value));\n EXPECT_FALSE((stan::math::ad_promotable<long double, float>::value));\n\n EXPECT_TRUE((stan::math::ad_promotable<float, float>::value))\n << \"All primitive types should be promotable to the same type\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief SerialPort class implementation\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/devices\/communication\/SerialPort.hpp\"\n\n#include \"distortos\/internal\/devices\/UartLowLevel.hpp\"\n\n#include \"distortos\/architecture\/InterruptMaskingLock.hpp\"\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"estd\/ScopeGuard.hpp\"\n\n#include <cerrno>\n#include <cstring>\n\nnamespace distortos\n{\n\nnamespace devices\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Reads data from ring buffer.\n *\n * \\param [in] ringBuffer is a reference to ring buffer from which the data will be read\n * \\param [out] buffer is a buffer to which the data will be written\n * \\param [in] size is the size of \\a buffer, bytes\n *\n * \\return number of bytes read from \\a ringBuffer and written to \\a buffer\n *\/\n\nsize_t readFromRingBuffer(SerialPort::RingBuffer& ringBuffer, uint8_t* const buffer, const size_t size)\n{\n\tdecltype(ringBuffer.getReadBlock()) readBlock;\n\tsize_t bytesRead {};\n\twhile (readBlock = ringBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)\n\t{\n\t\tconst auto copySize = std::min(readBlock.second, size - bytesRead);\n\t\tmemcpy(buffer + bytesRead, readBlock.first, copySize);\n\t\tringBuffer.increaseReadPosition(copySize);\n\t\tbytesRead += copySize;\n\t}\n\n\treturn bytesRead;\n}\n\n\/**\n * \\brief Writes data to ring buffer.\n *\n * \\param [in] buffer is a buffer from which the data will be read\n * \\param [in] size is the size of \\a buffer, bytes\n * \\param [in] ringBuffer is a reference to ring buffer to which the data will be written\n *\n * \\return number of bytes read from \\a buffer and written to \\a ringBuffer\n *\/\n\nsize_t writeToRingBuffer(const uint8_t* const buffer, const size_t size, SerialPort::RingBuffer& ringBuffer)\n{\n\tdecltype(ringBuffer.getWriteBlock()) writeBlock;\n\tsize_t bytesWritten {};\n\twhile (writeBlock = ringBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)\n\t{\n\t\tconst auto copySize = std::min(writeBlock.second, size - bytesWritten);\n\t\tmemcpy(writeBlock.first, buffer + bytesWritten, copySize);\n\t\tringBuffer.increaseWritePosition(copySize);\n\t\tbytesWritten += copySize;\n\t}\n\n\treturn bytesWritten;\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SerialPort::RingBuffer public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nstd::pair<const uint8_t*, size_t> SerialPort::RingBuffer::getReadBlock() const\n{\n\tconst auto readPosition = readPosition_;\n\tconst auto writePosition = writePosition_;\n\treturn {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};\n}\n\nstd::pair<uint8_t*, size_t> SerialPort::RingBuffer::getWriteBlock() const\n{\n\tconst auto readPosition = readPosition_;\n\tconst auto writePosition = writePosition_;\n\tconst auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :\n\t\t\tsize_ - writePosition + readPosition) - 2;\n\tconst auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;\n\treturn {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nSerialPort::~SerialPort()\n{\n\tif (openCount_ == 0)\n\t\treturn;\n\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tuart_.stopRead();\n\tuart_.stopWrite();\n\tuart_.stop();\n}\n\nint SerialPort::close()\n{\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\t\/\/ device is not open anymore?\n\t\treturn EBADF;\n\n\tif (openCount_ == 1)\t\/\/ last close?\n\t{\n\t\twhile (transmitInProgress_ == true)\t\/\/ wait for physical end of write operation\n\t\t{\n\t\t\tSemaphore semaphore {0};\n\t\t\ttransmitSemaphore_ = &semaphore;\n\t\t\tconst auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t\t[this]()\n\t\t\t\t\t{\n\t\t\t\t\t\ttransmitSemaphore_ = {};\n\t\t\t\t\t});\n\n\t\t\tif (transmitInProgress_ == true)\n\t\t\t{\n\t\t\t\tconst auto ret = semaphore.wait();\n\t\t\t\tif (ret != 0)\n\t\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\tuart_.stopRead();\n\n\t\tconst auto ret = uart_.stop();\n\t\tif (ret != 0)\n\t\t\treturn ret;\n\n\t\treadBuffer_.clear();\n\t\twriteBuffer_.clear();\n\t}\n\n\t--openCount_;\n\treturn 0;\n}\n\nint SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,\n\t\t\tconst bool _2StopBits)\n{\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == std::numeric_limits<decltype(openCount_)>::max())\t\/\/ device is already opened too many times?\n\t\treturn EMFILE;\n\n\tif (openCount_ == 0)\t\/\/ first open?\n\t{\n\t\tif (readBuffer_.getSize() < 4 || writeBuffer_.getSize() < 4)\n\t\t\treturn ENOBUFS;\n\n\t\t{\n\t\t\tconst auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);\n\t\t\tif (ret.first != 0)\n\t\t\t\treturn ret.first;\n\t\t}\n\t\t{\n\t\t\tconst auto ret = startReadWrapper(SIZE_MAX);\n\t\t\tif (ret != 0)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\tbaudRate_ = baudRate;\n\t\tcharacterLength_ = characterLength;\n\t\tparity_ = parity;\n\t\t_2StopBits_ = _2StopBits;\n\t}\n\telse\t\/\/ if (openCount_ != 0)\n\t{\n\t\t\/\/ provided arguments don't match current configuration of already opened device?\n\t\tif (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||\n\t\t\t\t_2StopBits_ != _2StopBits)\n\t\t\treturn EINVAL;\n\t}\n\n\t++openCount_;\n\treturn 0;\n}\n\nstd::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)\n{\n\tif (buffer == nullptr || size == 0)\n\t\treturn {EINVAL, {}};\n\n\treadMutex_.lock();\n\tconst auto readMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\n\t\treturn {EBADF, {}};\n\n\tif (characterLength_ > 8 && size % 2 != 0)\n\t\treturn {EINVAL, {}};\n\n\tconst size_t minSize = characterLength_ <= 8 ? 1 : 2;\n\tconst auto bufferUint8 = static_cast<uint8_t*>(buffer);\n\tsize_t bytesRead {};\n\twhile (bytesRead < minSize)\n\t{\n\t\tbytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);\n\t\tif (bytesRead == size)\t\/\/ buffer already full?\n\t\t\treturn {{}, bytesRead};\n\n\t\tSemaphore semaphore {0};\n\t\treadSemaphore_ = &semaphore;\n\t\tconst auto readSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t[this]()\n\t\t\t\t{\n\t\t\t\t\treadSemaphore_ = {};\n\t\t\t\t});\n\n\t\t{\n\t\t\t\/\/ stop and restart the read operation to get the characters that were already received;\n\t\t\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\t\t\tconst auto bytesReceived = uart_.stopRead();\n\t\t\treadBuffer_.increaseWritePosition(bytesReceived);\n\t\t\t\/\/ limit of new read operation is selected to have a notification when requested minimum will be received\n\t\t\tconst auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?\n\t\t\t\t\tminSize - bytesRead - bytesReceived : SIZE_MAX);\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesRead};\n\t\t}\n\n\t\tbytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);\n\n\t\tif (bytesRead < minSize)\t\/\/ wait for data only if requested minimum is not already read\n\t\t{\n\t\t\tconst auto ret = semaphore.wait();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesRead};\n\t\t}\n\t}\n\n\treturn {{}, bytesRead};\n}\n\nstd::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)\n{\n\tif (buffer == nullptr || size == 0)\n\t\treturn {EINVAL, {}};\n\n\twriteMutex_.lock();\n\tconst auto writeMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\n\t\treturn {EBADF, {}};\n\n\tif (characterLength_ > 8 && size % 2 != 0)\n\t\treturn {EINVAL, {}};\n\n\tconst auto bufferUint8 = static_cast<const uint8_t*>(buffer);\n\tsize_t bytesWritten {};\n\twhile (bytesWritten < size)\n\t{\n\t\tSemaphore semaphore {0};\n\t\twriteSemaphore_ = &semaphore;\n\t\tconst auto writeSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t[this]()\n\t\t\t\t{\n\t\t\t\t\twriteSemaphore_ = {};\n\t\t\t\t});\n\n\t\tbytesWritten += writeToRingBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);\n\n\t\t\/\/ restart write operation if it is not currently in progress and the write buffer is not already empty\n\t\tif (writeInProgress_ == false && writeBuffer_.isEmpty() == false)\n\t\t{\n\t\t\tconst auto ret = startWriteWrapper();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesWritten};\n\t\t}\n\t\t\/\/ wait for free space only if write operation is in progress and there is still some data left to write\n\t\telse if (bytesWritten != size)\n\t\t{\n\t\t\tconst auto ret = semaphore.wait();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesWritten};\n\t\t}\n\t}\n\n\treturn {{}, bytesWritten};\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid SerialPort::readCompleteEvent(const size_t bytesRead)\n{\n\treadBuffer_.increaseWritePosition(bytesRead);\n\n\tif (readSemaphore_ != nullptr)\n\t{\n\t\treadSemaphore_->post();\n\t\treadSemaphore_ = {};\n\t}\n\n\tif (readBuffer_.isFull() == true)\n\t\treturn;\n\n\tstartReadWrapper(SIZE_MAX);\n}\n\nvoid SerialPort::receiveErrorEvent(ErrorSet)\n{\n\n}\n\nint SerialPort::startReadWrapper(const size_t limit)\n{\n\tconst auto writeBlock = readBuffer_.getWriteBlock();\n\treturn uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBuffer_.getSize() \/ 2, limit}));\n}\n\nint SerialPort::startWriteWrapper()\n{\n\ttransmitInProgress_ = true;\n\twriteInProgress_ = true;\n\tconst auto outBlock = writeBuffer_.getReadBlock();\n\treturn uart_.startWrite(outBlock.first, outBlock.second);\n}\n\nvoid SerialPort::transmitCompleteEvent()\n{\n\tif (transmitSemaphore_ != nullptr)\n\t{\n\t\ttransmitSemaphore_->post();\n\t\ttransmitSemaphore_ = {};\n\t}\n\n\ttransmitInProgress_ = false;\n}\n\nvoid SerialPort::writeCompleteEvent(const size_t bytesWritten)\n{\n\twriteBuffer_.increaseReadPosition(bytesWritten);\n\n\tif (writeSemaphore_ != nullptr)\n\t{\n\t\twriteSemaphore_->post();\n\t\twriteSemaphore_ = {};\n\t}\n\n\tif (writeBuffer_.isEmpty() == true)\n\t{\n\t\twriteInProgress_ = false;\n\t\treturn;\n\t}\n\n\tstartWriteWrapper();\n}\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n<commit_msg>Rename local variable in SerialPort::startWriteWrapper()<commit_after>\/**\n * \\file\n * \\brief SerialPort class implementation\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/devices\/communication\/SerialPort.hpp\"\n\n#include \"distortos\/internal\/devices\/UartLowLevel.hpp\"\n\n#include \"distortos\/architecture\/InterruptMaskingLock.hpp\"\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"estd\/ScopeGuard.hpp\"\n\n#include <cerrno>\n#include <cstring>\n\nnamespace distortos\n{\n\nnamespace devices\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Reads data from ring buffer.\n *\n * \\param [in] ringBuffer is a reference to ring buffer from which the data will be read\n * \\param [out] buffer is a buffer to which the data will be written\n * \\param [in] size is the size of \\a buffer, bytes\n *\n * \\return number of bytes read from \\a ringBuffer and written to \\a buffer\n *\/\n\nsize_t readFromRingBuffer(SerialPort::RingBuffer& ringBuffer, uint8_t* const buffer, const size_t size)\n{\n\tdecltype(ringBuffer.getReadBlock()) readBlock;\n\tsize_t bytesRead {};\n\twhile (readBlock = ringBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)\n\t{\n\t\tconst auto copySize = std::min(readBlock.second, size - bytesRead);\n\t\tmemcpy(buffer + bytesRead, readBlock.first, copySize);\n\t\tringBuffer.increaseReadPosition(copySize);\n\t\tbytesRead += copySize;\n\t}\n\n\treturn bytesRead;\n}\n\n\/**\n * \\brief Writes data to ring buffer.\n *\n * \\param [in] buffer is a buffer from which the data will be read\n * \\param [in] size is the size of \\a buffer, bytes\n * \\param [in] ringBuffer is a reference to ring buffer to which the data will be written\n *\n * \\return number of bytes read from \\a buffer and written to \\a ringBuffer\n *\/\n\nsize_t writeToRingBuffer(const uint8_t* const buffer, const size_t size, SerialPort::RingBuffer& ringBuffer)\n{\n\tdecltype(ringBuffer.getWriteBlock()) writeBlock;\n\tsize_t bytesWritten {};\n\twhile (writeBlock = ringBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)\n\t{\n\t\tconst auto copySize = std::min(writeBlock.second, size - bytesWritten);\n\t\tmemcpy(writeBlock.first, buffer + bytesWritten, copySize);\n\t\tringBuffer.increaseWritePosition(copySize);\n\t\tbytesWritten += copySize;\n\t}\n\n\treturn bytesWritten;\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SerialPort::RingBuffer public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nstd::pair<const uint8_t*, size_t> SerialPort::RingBuffer::getReadBlock() const\n{\n\tconst auto readPosition = readPosition_;\n\tconst auto writePosition = writePosition_;\n\treturn {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};\n}\n\nstd::pair<uint8_t*, size_t> SerialPort::RingBuffer::getWriteBlock() const\n{\n\tconst auto readPosition = readPosition_;\n\tconst auto writePosition = writePosition_;\n\tconst auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :\n\t\t\tsize_ - writePosition + readPosition) - 2;\n\tconst auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;\n\treturn {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nSerialPort::~SerialPort()\n{\n\tif (openCount_ == 0)\n\t\treturn;\n\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tuart_.stopRead();\n\tuart_.stopWrite();\n\tuart_.stop();\n}\n\nint SerialPort::close()\n{\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\t\/\/ device is not open anymore?\n\t\treturn EBADF;\n\n\tif (openCount_ == 1)\t\/\/ last close?\n\t{\n\t\twhile (transmitInProgress_ == true)\t\/\/ wait for physical end of write operation\n\t\t{\n\t\t\tSemaphore semaphore {0};\n\t\t\ttransmitSemaphore_ = &semaphore;\n\t\t\tconst auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t\t[this]()\n\t\t\t\t\t{\n\t\t\t\t\t\ttransmitSemaphore_ = {};\n\t\t\t\t\t});\n\n\t\t\tif (transmitInProgress_ == true)\n\t\t\t{\n\t\t\t\tconst auto ret = semaphore.wait();\n\t\t\t\tif (ret != 0)\n\t\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\tuart_.stopRead();\n\n\t\tconst auto ret = uart_.stop();\n\t\tif (ret != 0)\n\t\t\treturn ret;\n\n\t\treadBuffer_.clear();\n\t\twriteBuffer_.clear();\n\t}\n\n\t--openCount_;\n\treturn 0;\n}\n\nint SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,\n\t\t\tconst bool _2StopBits)\n{\n\treadMutex_.lock();\n\twriteMutex_.lock();\n\tconst auto readWriteMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == std::numeric_limits<decltype(openCount_)>::max())\t\/\/ device is already opened too many times?\n\t\treturn EMFILE;\n\n\tif (openCount_ == 0)\t\/\/ first open?\n\t{\n\t\tif (readBuffer_.getSize() < 4 || writeBuffer_.getSize() < 4)\n\t\t\treturn ENOBUFS;\n\n\t\t{\n\t\t\tconst auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);\n\t\t\tif (ret.first != 0)\n\t\t\t\treturn ret.first;\n\t\t}\n\t\t{\n\t\t\tconst auto ret = startReadWrapper(SIZE_MAX);\n\t\t\tif (ret != 0)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\tbaudRate_ = baudRate;\n\t\tcharacterLength_ = characterLength;\n\t\tparity_ = parity;\n\t\t_2StopBits_ = _2StopBits;\n\t}\n\telse\t\/\/ if (openCount_ != 0)\n\t{\n\t\t\/\/ provided arguments don't match current configuration of already opened device?\n\t\tif (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||\n\t\t\t\t_2StopBits_ != _2StopBits)\n\t\t\treturn EINVAL;\n\t}\n\n\t++openCount_;\n\treturn 0;\n}\n\nstd::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)\n{\n\tif (buffer == nullptr || size == 0)\n\t\treturn {EINVAL, {}};\n\n\treadMutex_.lock();\n\tconst auto readMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\treadMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\n\t\treturn {EBADF, {}};\n\n\tif (characterLength_ > 8 && size % 2 != 0)\n\t\treturn {EINVAL, {}};\n\n\tconst size_t minSize = characterLength_ <= 8 ? 1 : 2;\n\tconst auto bufferUint8 = static_cast<uint8_t*>(buffer);\n\tsize_t bytesRead {};\n\twhile (bytesRead < minSize)\n\t{\n\t\tbytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);\n\t\tif (bytesRead == size)\t\/\/ buffer already full?\n\t\t\treturn {{}, bytesRead};\n\n\t\tSemaphore semaphore {0};\n\t\treadSemaphore_ = &semaphore;\n\t\tconst auto readSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t[this]()\n\t\t\t\t{\n\t\t\t\t\treadSemaphore_ = {};\n\t\t\t\t});\n\n\t\t{\n\t\t\t\/\/ stop and restart the read operation to get the characters that were already received;\n\t\t\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\t\t\tconst auto bytesReceived = uart_.stopRead();\n\t\t\treadBuffer_.increaseWritePosition(bytesReceived);\n\t\t\t\/\/ limit of new read operation is selected to have a notification when requested minimum will be received\n\t\t\tconst auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?\n\t\t\t\t\tminSize - bytesRead - bytesReceived : SIZE_MAX);\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesRead};\n\t\t}\n\n\t\tbytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);\n\n\t\tif (bytesRead < minSize)\t\/\/ wait for data only if requested minimum is not already read\n\t\t{\n\t\t\tconst auto ret = semaphore.wait();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesRead};\n\t\t}\n\t}\n\n\treturn {{}, bytesRead};\n}\n\nstd::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)\n{\n\tif (buffer == nullptr || size == 0)\n\t\treturn {EINVAL, {}};\n\n\twriteMutex_.lock();\n\tconst auto writeMutexScopeGuard = estd::makeScopeGuard(\n\t\t\t[this]()\n\t\t\t{\n\t\t\t\twriteMutex_.unlock();\n\t\t\t});\n\n\tif (openCount_ == 0)\n\t\treturn {EBADF, {}};\n\n\tif (characterLength_ > 8 && size % 2 != 0)\n\t\treturn {EINVAL, {}};\n\n\tconst auto bufferUint8 = static_cast<const uint8_t*>(buffer);\n\tsize_t bytesWritten {};\n\twhile (bytesWritten < size)\n\t{\n\t\tSemaphore semaphore {0};\n\t\twriteSemaphore_ = &semaphore;\n\t\tconst auto writeSemaphoreScopeGuard = estd::makeScopeGuard(\n\t\t\t\t[this]()\n\t\t\t\t{\n\t\t\t\t\twriteSemaphore_ = {};\n\t\t\t\t});\n\n\t\tbytesWritten += writeToRingBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);\n\n\t\t\/\/ restart write operation if it is not currently in progress and the write buffer is not already empty\n\t\tif (writeInProgress_ == false && writeBuffer_.isEmpty() == false)\n\t\t{\n\t\t\tconst auto ret = startWriteWrapper();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesWritten};\n\t\t}\n\t\t\/\/ wait for free space only if write operation is in progress and there is still some data left to write\n\t\telse if (bytesWritten != size)\n\t\t{\n\t\t\tconst auto ret = semaphore.wait();\n\t\t\tif (ret != 0)\n\t\t\t\treturn {ret, bytesWritten};\n\t\t}\n\t}\n\n\treturn {{}, bytesWritten};\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid SerialPort::readCompleteEvent(const size_t bytesRead)\n{\n\treadBuffer_.increaseWritePosition(bytesRead);\n\n\tif (readSemaphore_ != nullptr)\n\t{\n\t\treadSemaphore_->post();\n\t\treadSemaphore_ = {};\n\t}\n\n\tif (readBuffer_.isFull() == true)\n\t\treturn;\n\n\tstartReadWrapper(SIZE_MAX);\n}\n\nvoid SerialPort::receiveErrorEvent(ErrorSet)\n{\n\n}\n\nint SerialPort::startReadWrapper(const size_t limit)\n{\n\tconst auto writeBlock = readBuffer_.getWriteBlock();\n\treturn uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBuffer_.getSize() \/ 2, limit}));\n}\n\nint SerialPort::startWriteWrapper()\n{\n\ttransmitInProgress_ = true;\n\twriteInProgress_ = true;\n\tconst auto readBlock = writeBuffer_.getReadBlock();\n\treturn uart_.startWrite(readBlock.first, readBlock.second);\n}\n\nvoid SerialPort::transmitCompleteEvent()\n{\n\tif (transmitSemaphore_ != nullptr)\n\t{\n\t\ttransmitSemaphore_->post();\n\t\ttransmitSemaphore_ = {};\n\t}\n\n\ttransmitInProgress_ = false;\n}\n\nvoid SerialPort::writeCompleteEvent(const size_t bytesWritten)\n{\n\twriteBuffer_.increaseReadPosition(bytesWritten);\n\n\tif (writeSemaphore_ != nullptr)\n\t{\n\t\twriteSemaphore_->post();\n\t\twriteSemaphore_ = {};\n\t}\n\n\tif (writeBuffer_.isEmpty() == true)\n\t{\n\t\twriteInProgress_ = false;\n\t\treturn;\n\t}\n\n\tstartWriteWrapper();\n}\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"messages_connector.h\"\n#include <pqxx\/pqxx>\n#include <boost\/make_shared.hpp>\n#include \"utils\/exception.h\"\n#include \"utils\/logger.h\"\n#include \"type\/data.h\"\n#include \"type\/pt_data.h\"\n\nnamespace ed{ namespace connectors{\n\nnamespace pt = boost::posix_time;\n\nstd::map<std::string, boost::shared_ptr<navitia::type::Message>> load_messages(\n const RealtimeLoaderConfig& conf,\n const boost::posix_time::ptime& current_time){\n \/\/pour le moment on vire les timezone et on considére que c'est de l'heure local\n std::string request = \"SELECT id, uri, start_publication_date::timestamp, \"\n \"end_publication_date::timestamp, start_application_date::timestamp, \"\n \"end_application_date::timestamp, start_application_daily_hour::time, \"\n \"end_application_daily_hour::time, active_days, object_uri, \"\n \"object_type_id, language, body, title, message_status_id \"\n \"FROM realtime.message m \"\n \"JOIN realtime.localized_message l ON l.message_id = m.id \"\n \"where end_publication_date >= ($1::timestamp - $2::interval) \"\n \"order by id\";\n \/\/on tris par id pour les regrouper ensemble\n pqxx::result result;\n std::unique_ptr<pqxx::connection> conn;\n try{\n conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(conf.connection_string));\n conn->prepare(\"messages\", request);\n std::string st_current_time = boost::posix_time::to_iso_string(current_time);\n std::string st_shift_days = std::to_string(conf.shift_days) + \" days\";\n pqxx::work work(*conn, \"chargement des messages\");\n result = work.prepared(\"messages\")(st_current_time)(st_shift_days).exec();\n }catch(const pqxx::pqxx_exception &e){\n throw navitia::exception(e.base().what());\n\n }\n\n std::map<std::string, boost::shared_ptr<navitia::type::Message>> messages;\n boost::shared_ptr<navitia::type::Message> message;\n std::string current_uri = \"\";\n\n for(auto cursor = result.begin(); cursor != result.end(); ++cursor){\n if(cursor[\"uri\"].as<std::string>() != current_uri){\/\/on traite un nouveau message\n if(message){\/\/si on a un message précédent, on le rajoute au map de résultat\n messages[message->uri] = message;\n }\n cursor[\"uri\"].to(current_uri);\n \/\/on construit le message\n message = boost::make_shared<navitia::type::Message>();\n message->uri = current_uri;\n cursor[\"object_uri\"].to(message->object_uri);\n\n message->object_type = static_cast<navitia::type::Type_e>(\n cursor[\"object_type_id\"].as<int>());\n\n message->message_status = static_cast<navitia::type::MessageStatus>(\n cursor[\"message_status_id\"].as<int>());\n\n message->application_daily_start_hour = pt::duration_from_string(\n cursor[\"start_application_daily_hour\"].as<std::string>());\n\n message->application_daily_end_hour = pt::duration_from_string(\n cursor[\"end_application_daily_hour\"].as<std::string>());\n\n pt::ptime start = pt::time_from_string(\n cursor[\"start_application_date\"].as<std::string>());\n\n pt::ptime end = pt::time_from_string(\n cursor[\"end_application_date\"].as<std::string>());\n message->application_period = pt::time_period(start, end);\n\n start = pt::time_from_string(\n cursor[\"start_publication_date\"].as<std::string>());\n\n end = pt::time_from_string(\n cursor[\"end_publication_date\"].as<std::string>());\n message->publication_period = pt::time_period(start, end);\n\n message->active_days = std::bitset<8>(\n cursor[\"active_days\"].as<std::string>());\n }\n std::string language = cursor[\"language\"].as<std::string>();\n cursor[\"body\"].to(message->localized_messages[language].body);\n cursor[\"title\"].to(message->localized_messages[language].title);\n }\n if(message){\/\/on ajoute le dernier message traité\n messages[message->uri] = message;\n }\n\n return messages;\n}\n\nvoid apply_messages(navitia::type::Data& data){\n for(const auto message_pair : data.pt_data->message_holder.messages){\n if(message_pair.second->object_type == navitia::type::Type_e::StopArea){\n auto it = data.pt_data->stop_areas_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->stop_areas_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::StopPoint){\n auto it = data.pt_data->stop_points_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->stop_points_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Route){\n auto it = data.pt_data->routes_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->routes_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::VehicleJourney){\n auto it = data.pt_data->vehicle_journeys_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->vehicle_journeys_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Line){\n auto it = data.pt_data->lines_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->lines_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Network){\n auto it = data.pt_data->networks_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->networks_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n }\n}\n\nstd::vector<navitia::type::AtPerturbation> load_at_perturbations(\n const RealtimeLoaderConfig& conf,\n const boost::posix_time::ptime& current_time){\n \/\/pour le moment on vire les timezone et on considére que c'est de l'heure local\n std::string request = \"SELECT id, uri, start_application_date::timestamp, \"\n \"end_application_date::timestamp, start_application_daily_hour::time, \"\n \"end_application_daily_hour::time, active_days, object_uri, \"\n \"object_type_id \"\n \"FROM realtime.at_perturbation \"\n \"where end_application_date >= ($1::timestamp - $2::interval) \";\n pqxx::result result;\n std::unique_ptr<pqxx::connection> conn;\n try{\n conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(conf.connection_string));\n conn->prepare(\"messages\", request);\n std::string st_current_time = boost::posix_time::to_iso_string(current_time);\n std::string st_shift_days = std::to_string(conf.shift_days) + \" days\";\n pqxx::work work(*conn, \"chargement des perturbations at\");\n result = work.prepared(\"messages\")(st_current_time)(st_shift_days).exec();\n\n }catch(const pqxx::pqxx_exception &e){\n throw navitia::exception(e.base().what());\n\n }\n\n std::vector<navitia::type::AtPerturbation> perturbations;\n for(auto cursor = result.begin(); cursor != result.end(); ++cursor){\n navitia::type::AtPerturbation perturbation;\n cursor[\"uri\"].to(perturbation.uri);\n \/\/on construit le message\n cursor[\"object_uri\"].to(perturbation.object_uri);\n\n perturbation.object_type = static_cast<navitia::type::Type_e>(\n cursor[\"object_type_id\"].as<int>());\n\n perturbation.application_daily_start_hour = pt::duration_from_string(\n cursor[\"start_application_daily_hour\"].as<std::string>());\n\n perturbation.application_daily_end_hour = pt::duration_from_string(\n cursor[\"end_application_daily_hour\"].as<std::string>());\n\n pt::ptime start = pt::time_from_string(\n cursor[\"start_application_date\"].as<std::string>());\n\n pt::ptime end = pt::time_from_string(\n cursor[\"end_application_date\"].as<std::string>());\n perturbation.application_period = pt::time_period(start, end);\n\n perturbation.active_days = std::bitset<8>(\n cursor[\"active_days\"].as<std::string>());\n\n perturbations.push_back(perturbation);\n }\n\n return perturbations;\n}\n\n}}\/\/namespace\n<commit_msg>ed: support pqxx v3 and v4<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"messages_connector.h\"\n#include <pqxx\/pqxx>\n#include <boost\/make_shared.hpp>\n#include \"utils\/exception.h\"\n#include \"utils\/logger.h\"\n#include \"type\/data.h\"\n#include \"type\/pt_data.h\"\n\nnamespace ed{ namespace connectors{\n\nnamespace pt = boost::posix_time;\n\nstd::map<std::string, boost::shared_ptr<navitia::type::Message>> load_messages(\n const RealtimeLoaderConfig& conf,\n const boost::posix_time::ptime& current_time){\n \/\/pour le moment on vire les timezone et on considére que c'est de l'heure local\n std::string request = \"SELECT id, uri, start_publication_date::timestamp, \"\n \"end_publication_date::timestamp, start_application_date::timestamp, \"\n \"end_application_date::timestamp, start_application_daily_hour::time, \"\n \"end_application_daily_hour::time, active_days, object_uri, \"\n \"object_type_id, language, body, title, message_status_id \"\n \"FROM realtime.message m \"\n \"JOIN realtime.localized_message l ON l.message_id = m.id \"\n \"where end_publication_date >= ($1::timestamp - $2::interval) \"\n \"order by id\";\n \/\/on tris par id pour les regrouper ensemble\n pqxx::result result;\n std::unique_ptr<pqxx::connection> conn;\n try{\n conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(conf.connection_string));\n\n#if PQXX_VERSION_MAJOR < 4\n conn->prepare(\"messages\", request)(\"timestamp\")(\"INTERVAL\", pqxx::prepare::treat_string);\n#else\n conn->prepare(\"messages\", request);\n#endif\n\n std::string st_current_time = boost::posix_time::to_iso_string(current_time);\n std::string st_shift_days = std::to_string(conf.shift_days) + \" days\";\n pqxx::work work(*conn, \"chargement des messages\");\n result = work.prepared(\"messages\")(st_current_time)(st_shift_days).exec();\n }catch(const pqxx::pqxx_exception &e){\n throw navitia::exception(e.base().what());\n\n }\n\n std::map<std::string, boost::shared_ptr<navitia::type::Message>> messages;\n boost::shared_ptr<navitia::type::Message> message;\n std::string current_uri = \"\";\n\n for(auto cursor = result.begin(); cursor != result.end(); ++cursor){\n if(cursor[\"uri\"].as<std::string>() != current_uri){\/\/on traite un nouveau message\n if(message){\/\/si on a un message précédent, on le rajoute au map de résultat\n messages[message->uri] = message;\n }\n cursor[\"uri\"].to(current_uri);\n \/\/on construit le message\n message = boost::make_shared<navitia::type::Message>();\n message->uri = current_uri;\n cursor[\"object_uri\"].to(message->object_uri);\n\n message->object_type = static_cast<navitia::type::Type_e>(\n cursor[\"object_type_id\"].as<int>());\n\n message->message_status = static_cast<navitia::type::MessageStatus>(\n cursor[\"message_status_id\"].as<int>());\n\n message->application_daily_start_hour = pt::duration_from_string(\n cursor[\"start_application_daily_hour\"].as<std::string>());\n\n message->application_daily_end_hour = pt::duration_from_string(\n cursor[\"end_application_daily_hour\"].as<std::string>());\n\n pt::ptime start = pt::time_from_string(\n cursor[\"start_application_date\"].as<std::string>());\n\n pt::ptime end = pt::time_from_string(\n cursor[\"end_application_date\"].as<std::string>());\n message->application_period = pt::time_period(start, end);\n\n start = pt::time_from_string(\n cursor[\"start_publication_date\"].as<std::string>());\n\n end = pt::time_from_string(\n cursor[\"end_publication_date\"].as<std::string>());\n message->publication_period = pt::time_period(start, end);\n\n message->active_days = std::bitset<8>(\n cursor[\"active_days\"].as<std::string>());\n }\n std::string language = cursor[\"language\"].as<std::string>();\n cursor[\"body\"].to(message->localized_messages[language].body);\n cursor[\"title\"].to(message->localized_messages[language].title);\n }\n if(message){\/\/on ajoute le dernier message traité\n messages[message->uri] = message;\n }\n\n return messages;\n}\n\nvoid apply_messages(navitia::type::Data& data){\n for(const auto message_pair : data.pt_data->message_holder.messages){\n if(message_pair.second->object_type == navitia::type::Type_e::StopArea){\n auto it = data.pt_data->stop_areas_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->stop_areas_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::StopPoint){\n auto it = data.pt_data->stop_points_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->stop_points_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Route){\n auto it = data.pt_data->routes_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->routes_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::VehicleJourney){\n auto it = data.pt_data->vehicle_journeys_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->vehicle_journeys_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Line){\n auto it = data.pt_data->lines_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->lines_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n\n if(message_pair.second->object_type == navitia::type::Type_e::Network){\n auto it = data.pt_data->networks_map.find(message_pair.second->object_uri);\n if(it != data.pt_data->networks_map.end()){\n it->second->messages.push_back(message_pair.second);\n }\n }\n }\n}\n\nstd::vector<navitia::type::AtPerturbation> load_at_perturbations(\n const RealtimeLoaderConfig& conf,\n const boost::posix_time::ptime& current_time){\n \/\/pour le moment on vire les timezone et on considére que c'est de l'heure local\n std::string request = \"SELECT id, uri, start_application_date::timestamp, \"\n \"end_application_date::timestamp, start_application_daily_hour::time, \"\n \"end_application_daily_hour::time, active_days, object_uri, \"\n \"object_type_id \"\n \"FROM realtime.at_perturbation \"\n \"where end_application_date >= ($1::timestamp - $2::interval) \";\n pqxx::result result;\n std::unique_ptr<pqxx::connection> conn;\n try{\n conn = std::unique_ptr<pqxx::connection>(new pqxx::connection(conf.connection_string));\n\n#if PQXX_VERSION_MAJOR < 4\n conn->prepare(\"messages\", request)(\"timestamp\")(\"INTERVAL\", pqxx::prepare::treat_string);\n#else\n conn->prepare(\"messages\", request);\n#endif\n\n std::string st_current_time = boost::posix_time::to_iso_string(current_time);\n std::string st_shift_days = std::to_string(conf.shift_days) + \" days\";\n pqxx::work work(*conn, \"chargement des perturbations at\");\n result = work.prepared(\"messages\")(st_current_time)(st_shift_days).exec();\n\n }catch(const pqxx::pqxx_exception &e){\n throw navitia::exception(e.base().what());\n\n }\n\n std::vector<navitia::type::AtPerturbation> perturbations;\n for(auto cursor = result.begin(); cursor != result.end(); ++cursor){\n navitia::type::AtPerturbation perturbation;\n cursor[\"uri\"].to(perturbation.uri);\n \/\/on construit le message\n cursor[\"object_uri\"].to(perturbation.object_uri);\n\n perturbation.object_type = static_cast<navitia::type::Type_e>(\n cursor[\"object_type_id\"].as<int>());\n\n perturbation.application_daily_start_hour = pt::duration_from_string(\n cursor[\"start_application_daily_hour\"].as<std::string>());\n\n perturbation.application_daily_end_hour = pt::duration_from_string(\n cursor[\"end_application_daily_hour\"].as<std::string>());\n\n pt::ptime start = pt::time_from_string(\n cursor[\"start_application_date\"].as<std::string>());\n\n pt::ptime end = pt::time_from_string(\n cursor[\"end_application_date\"].as<std::string>());\n perturbation.application_period = pt::time_period(start, end);\n\n perturbation.active_days = std::bitset<8>(\n cursor[\"active_days\"].as<std::string>());\n\n perturbations.push_back(perturbation);\n }\n\n return perturbations;\n}\n\n}}\/\/namespace\n<|endoftext|>"} {"text":"<commit_before>\/* FiberTaskingLib - A tasking library that uses fibers for efficient task switching\n *\n * This library was created as a proof of concept of the ideas presented by\n * Christian Gyrling in his 2015 GDC Talk 'Parallelizing the Naughty Dog Engine Using Fibers'\n *\n * http:\/\/gdcvault.com\/play\/1022186\/Parallelizing-the-Naughty-Dog-Engine\n *\n * FiberTaskingLib is the legal property of Adrian Astley\n * Copyright Adrian Astley 2015\n *\/\n\n#include \"fiber_tasking_lib\/task_scheduler.h\"\n\n#include \"fiber_tasking_lib\/global_args.h\"\n\n#include <process.h>\n\n\nnamespace FiberTaskingLib {\n\n__declspec(thread) uint tls_threadId;\n\n__declspec(thread) void *tls_fiberToSwitchTo;\n__declspec(thread) void *tls_currentFiber;\n__declspec(thread) AtomicCounter *tls_waitingCounter;\n__declspec(thread) int tls_waitingValue;\n\n\n\nstruct ThreadStartArgs {\n\tGlobalArgs *globalArgs;\n\tuint threadId;\n};\n\nuint TaskScheduler::ThreadStart(void *arg) {\n\tThreadStartArgs *threadArgs = (ThreadStartArgs *)arg;\n\ttls_threadId = threadArgs->threadId;\n\tGlobalArgs *globalArgs = threadArgs->globalArgs;\n\n\t\/\/ Clean up\n\tdelete threadArgs;\n\n\tConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);\n\tFiberStart(globalArgs);\n\n\tConvertFiberToThread();\n\treturn 1;\n}\n\nvoid TaskScheduler::FiberStart(void *arg) {\n\tGlobalArgs *globalArgs = (GlobalArgs *)arg;\n\tTaskScheduler *taskScheduler = &globalArgs->TaskScheduler;\n\n\twhile (!taskScheduler->m_quit.load()) {\n\t\t\/\/ Check if any of the waiting tasks are ready\n\t\tWaitingTask waitingTask;\n\t\tbool waitingTaskReady = false;\n\n\t\tEnterCriticalSection(&taskScheduler->m_waitingTaskLock);\n\t\tauto iter = taskScheduler->m_waitingTasks.begin();\n\t\tfor ( ; iter != taskScheduler->m_waitingTasks.end(); ++iter) {\n\t\t\tif (iter->Counter->load() == iter->Value) {\n\t\t\t\twaitingTaskReady = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (waitingTaskReady) {\n\t\t\twaitingTask = *iter;\n\t\t\ttaskScheduler->m_waitingTasks.erase(iter);\n\t\t}\n\t\tLeaveCriticalSection(&taskScheduler->m_waitingTaskLock);\n\n\t\tif (waitingTaskReady) {\n\t\t\ttaskScheduler->SwitchFibers(waitingTask.Fiber);\n\t\t}\n\n\n\t\tTaskBundle nextTask;\n\t\tif (!taskScheduler->GetNextTask(&nextTask)) {\n\t\t\tSleep(1);\n\t\t} else {\n\t\t\tnextTask.Task.Function(&globalArgs->TaskScheduler, nextTask.Task.ArgData);\n\t\t\tnextTask.Counter->fetch_sub(1);\n\t\t}\n\t}\n}\n\nvoid __stdcall TaskScheduler::FiberSwitchStart(void *arg) {\n\tTaskScheduler *taskScheduler = (TaskScheduler *)arg;\n\n\twhile (true) {\n\t\ttaskScheduler->m_fiberPool.enqueue(tls_currentFiber);\n\t\tSwitchToFiber(tls_fiberToSwitchTo);\n\t}\n}\n\nvoid __stdcall TaskScheduler::CounterWaitStart(void *arg) {\n\tTaskScheduler *taskScheduler = (TaskScheduler *)arg;\n\n\twhile (true) {\n\t\tEnterCriticalSection(&taskScheduler->m_waitingTaskLock);\n\t\ttaskScheduler->m_waitingTasks.emplace_back(tls_currentFiber, tls_waitingCounter, tls_waitingValue);\n\t\tLeaveCriticalSection(&taskScheduler->m_waitingTaskLock);\n\n\t\tSwitchToFiber(tls_fiberToSwitchTo);\n\t}\n}\n\n\n\nTaskScheduler::TaskScheduler()\n\t\t: m_numThreads(0),\n\t\t m_threads(nullptr) {\n\tm_quit.store(false, std::memory_order_relaxed);\n\tInitializeCriticalSection(&m_waitingTaskLock);\n}\n\nTaskScheduler::~TaskScheduler() {\n\tdelete[] m_threads;\n\n\tvoid *fiber;\n\twhile (m_fiberPool.try_dequeue(fiber)) {\n\t\tDeleteFiber(fiber);\n\t}\n\n\tDeleteCriticalSection(&m_waitingTaskLock);\n}\n\nvoid TaskScheduler::Initialize(GlobalArgs *globalArgs) {\n\tfor (uint i = 0; i < FIBER_POOL_SIZE; ++i) {\n\t\tm_fiberPool.enqueue(CreateFiberEx(524288, 0, FIBER_FLAG_FLOAT_SWITCH, FiberStart, globalArgs));\n\t}\n\n\tSYSTEM_INFO sysinfo;\n\tGetSystemInfo(&sysinfo);\n\n\t\/\/ Create an additional thread for each logical processor\n\tm_numThreads = sysinfo.dwNumberOfProcessors;\n\tm_threads = new HANDLE[m_numThreads];\n\tm_fiberSwitchingFibers = new void *[m_numThreads];\n\tm_counterWaitingFibers = new void *[m_numThreads];\n\n\n\t\/\/ Create a switching fiber for each thread\n\tfor (uint i = 0; i < m_numThreads; ++i) {\n\t\tm_fiberSwitchingFibers[i] = CreateFiberEx(32768, 0, FIBER_FLAG_FLOAT_SWITCH, FiberSwitchStart, &globalArgs->TaskScheduler);\n\t\tm_counterWaitingFibers[i] = CreateFiberEx(32768, 0, FIBER_FLAG_FLOAT_SWITCH, CounterWaitStart, &globalArgs->TaskScheduler);\n\t}\n\n\t\/\/ Set the affinity for the current thread and convert it to a fiber\n\tSetThreadAffinityMask(GetCurrentThread(), 1);\n\tConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);\n\tm_threads[0] = GetCurrentThread();\n\ttls_threadId = 0;\n\t\n\t\/\/ Create the remaining threads\n\tfor (DWORD i = 1; i < m_numThreads; ++i) {\n\t\tThreadStartArgs *threadArgs = new ThreadStartArgs();\n\t\tthreadArgs->globalArgs = globalArgs;\n\t\tthreadArgs->threadId = i;\n\n\t\tHANDLE threadHandle = (HANDLE)_beginthreadex(nullptr, 524288, ThreadStart, threadArgs, CREATE_SUSPENDED, nullptr);\n\t\tm_threads[i] = threadHandle;\n\n\t\tDWORD_PTR mask = 1 << i;\n\t\tSetThreadAffinityMask(threadHandle, mask);\n\t\tResumeThread(threadHandle);\n\t}\n}\n\nstd::shared_ptr<AtomicCounter> TaskScheduler::AddTask(Task task) {\n\tstd::shared_ptr<AtomicCounter> counter(new AtomicCounter());\n\tcounter->store(1, std::memory_order_relaxed);\n\n\tTaskBundle bundle = {task, counter};\n\tm_taskQueue.enqueue(bundle);\n\n\treturn counter;\n}\n\nstd::shared_ptr<AtomicCounter> TaskScheduler::AddTasks(uint numTasks, Task *tasks) {\n\tstd::shared_ptr<AtomicCounter> counter(new AtomicCounter());\n\tcounter->store(numTasks, std::memory_order_relaxed);\n\n\tfor (uint i = 0; i < numTasks; ++i) {\n\t\tTaskBundle bundle = {tasks[i], counter};\n\t\tm_taskQueue.enqueue(bundle);\n\t}\n\t\n\treturn counter;\n}\n\nbool TaskScheduler::GetNextTask(TaskBundle *nextTask) {\n\tbool success = m_taskQueue.try_dequeue(*nextTask);\n\n\treturn success;\n}\n\nvoid TaskScheduler::SwitchFibers(void *fiberToSwitchTo) {\n\ttls_currentFiber = GetCurrentFiber();\n\ttls_fiberToSwitchTo = fiberToSwitchTo;\n\n\tSwitchToFiber(m_fiberSwitchingFibers[tls_threadId]);\n}\n\nvoid TaskScheduler::WaitForCounter(std::shared_ptr<AtomicCounter> &counter, int value) {\n\tif (counter->load() == value) {\n\t\treturn;\n\t}\n\n\t\/\/ Switch to a new Fiber\n\tm_fiberPool.wait_dequeue(tls_fiberToSwitchTo);\n\n\ttls_currentFiber = GetCurrentFiber();\n\ttls_waitingCounter = counter.get();\n\ttls_waitingValue = value;\n\t\n\tSwitchToFiber(m_counterWaitingFibers[tls_threadId]);\n}\n\nvoid TaskScheduler::Quit() {\n\tm_quit.store(true, std::memory_order_relaxed);\n\tConvertFiberToThread();\n\n\tstd::vector<HANDLE> workerThreads;\n\tfor (uint i = 0; i < m_numThreads; ++i) {\n\t\tif (m_threads != GetCurrentThread()) {\n\t\t\tworkerThreads.push_back(m_threads[i]);\n\t\t}\n\t}\n\n\tDWORD result = WaitForMultipleObjects(workerThreads.size(), &workerThreads[0], true, INFINITE);\n\n\tfor (auto &workerThread : workerThreads) {\n\t\tCloseHandle(workerThread);\n\t}\n}\n\n} \/\/ End of namespace FiberTaskingLib\n<commit_msg>FIBER_TASKING_LIB: Use the default sequential memory ordering for all atomics<commit_after>\/* FiberTaskingLib - A tasking library that uses fibers for efficient task switching\n *\n * This library was created as a proof of concept of the ideas presented by\n * Christian Gyrling in his 2015 GDC Talk 'Parallelizing the Naughty Dog Engine Using Fibers'\n *\n * http:\/\/gdcvault.com\/play\/1022186\/Parallelizing-the-Naughty-Dog-Engine\n *\n * FiberTaskingLib is the legal property of Adrian Astley\n * Copyright Adrian Astley 2015\n *\/\n\n#include \"fiber_tasking_lib\/task_scheduler.h\"\n\n#include \"fiber_tasking_lib\/global_args.h\"\n\n#include <process.h>\n\n\nnamespace FiberTaskingLib {\n\n__declspec(thread) uint tls_threadId;\n\n__declspec(thread) void *tls_fiberToSwitchTo;\n__declspec(thread) void *tls_currentFiber;\n__declspec(thread) AtomicCounter *tls_waitingCounter;\n__declspec(thread) int tls_waitingValue;\n\n\n\nstruct ThreadStartArgs {\n\tGlobalArgs *globalArgs;\n\tuint threadId;\n};\n\nuint TaskScheduler::ThreadStart(void *arg) {\n\tThreadStartArgs *threadArgs = (ThreadStartArgs *)arg;\n\ttls_threadId = threadArgs->threadId;\n\tGlobalArgs *globalArgs = threadArgs->globalArgs;\n\n\t\/\/ Clean up\n\tdelete threadArgs;\n\n\tConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);\n\tFiberStart(globalArgs);\n\n\tConvertFiberToThread();\n\treturn 1;\n}\n\nvoid TaskScheduler::FiberStart(void *arg) {\n\tGlobalArgs *globalArgs = (GlobalArgs *)arg;\n\tTaskScheduler *taskScheduler = &globalArgs->TaskScheduler;\n\n\twhile (!taskScheduler->m_quit.load()) {\n\t\t\/\/ Check if any of the waiting tasks are ready\n\t\tWaitingTask waitingTask;\n\t\tbool waitingTaskReady = false;\n\n\t\tEnterCriticalSection(&taskScheduler->m_waitingTaskLock);\n\t\tauto iter = taskScheduler->m_waitingTasks.begin();\n\t\tfor ( ; iter != taskScheduler->m_waitingTasks.end(); ++iter) {\n\t\t\tif (iter->Counter->load() == iter->Value) {\n\t\t\t\twaitingTaskReady = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (waitingTaskReady) {\n\t\t\twaitingTask = *iter;\n\t\t\ttaskScheduler->m_waitingTasks.erase(iter);\n\t\t}\n\t\tLeaveCriticalSection(&taskScheduler->m_waitingTaskLock);\n\n\t\tif (waitingTaskReady) {\n\t\t\ttaskScheduler->SwitchFibers(waitingTask.Fiber);\n\t\t}\n\n\n\t\tTaskBundle nextTask;\n\t\tif (!taskScheduler->GetNextTask(&nextTask)) {\n\t\t\tSleep(1);\n\t\t} else {\n\t\t\tnextTask.Task.Function(&globalArgs->TaskScheduler, nextTask.Task.ArgData);\n\t\t\tnextTask.Counter->fetch_sub(1);\n\t\t}\n\t}\n}\n\nvoid __stdcall TaskScheduler::FiberSwitchStart(void *arg) {\n\tTaskScheduler *taskScheduler = (TaskScheduler *)arg;\n\n\twhile (true) {\n\t\ttaskScheduler->m_fiberPool.enqueue(tls_currentFiber);\n\t\tSwitchToFiber(tls_fiberToSwitchTo);\n\t}\n}\n\nvoid __stdcall TaskScheduler::CounterWaitStart(void *arg) {\n\tTaskScheduler *taskScheduler = (TaskScheduler *)arg;\n\n\twhile (true) {\n\t\tEnterCriticalSection(&taskScheduler->m_waitingTaskLock);\n\t\ttaskScheduler->m_waitingTasks.emplace_back(tls_currentFiber, tls_waitingCounter, tls_waitingValue);\n\t\tLeaveCriticalSection(&taskScheduler->m_waitingTaskLock);\n\n\t\tSwitchToFiber(tls_fiberToSwitchTo);\n\t}\n}\n\n\n\nTaskScheduler::TaskScheduler()\n\t\t: m_numThreads(0),\n\t\t m_threads(nullptr) {\n\tInitializeCriticalSection(&m_waitingTaskLock);\n\tm_quit.store(false);\n}\n\nTaskScheduler::~TaskScheduler() {\n\tdelete[] m_threads;\n\n\tvoid *fiber;\n\twhile (m_fiberPool.try_dequeue(fiber)) {\n\t\tDeleteFiber(fiber);\n\t}\n\n\tDeleteCriticalSection(&m_waitingTaskLock);\n}\n\nvoid TaskScheduler::Initialize(GlobalArgs *globalArgs) {\n\tfor (uint i = 0; i < FIBER_POOL_SIZE; ++i) {\n\t\tm_fiberPool.enqueue(CreateFiberEx(524288, 0, FIBER_FLAG_FLOAT_SWITCH, FiberStart, globalArgs));\n\t}\n\n\tSYSTEM_INFO sysinfo;\n\tGetSystemInfo(&sysinfo);\n\n\t\/\/ Create an additional thread for each logical processor\n\tm_numThreads = sysinfo.dwNumberOfProcessors;\n\tm_threads = new HANDLE[m_numThreads];\n\tm_fiberSwitchingFibers = new void *[m_numThreads];\n\tm_counterWaitingFibers = new void *[m_numThreads];\n\n\n\t\/\/ Create a switching fiber for each thread\n\tfor (uint i = 0; i < m_numThreads; ++i) {\n\t\tm_fiberSwitchingFibers[i] = CreateFiberEx(32768, 0, FIBER_FLAG_FLOAT_SWITCH, FiberSwitchStart, &globalArgs->TaskScheduler);\n\t\tm_counterWaitingFibers[i] = CreateFiberEx(32768, 0, FIBER_FLAG_FLOAT_SWITCH, CounterWaitStart, &globalArgs->TaskScheduler);\n\t}\n\n\t\/\/ Set the affinity for the current thread and convert it to a fiber\n\tSetThreadAffinityMask(GetCurrentThread(), 1);\n\tConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);\n\tm_threads[0] = GetCurrentThread();\n\ttls_threadId = 0;\n\t\n\t\/\/ Create the remaining threads\n\tfor (DWORD i = 1; i < m_numThreads; ++i) {\n\t\tThreadStartArgs *threadArgs = new ThreadStartArgs();\n\t\tthreadArgs->globalArgs = globalArgs;\n\t\tthreadArgs->threadId = i;\n\n\t\tHANDLE threadHandle = (HANDLE)_beginthreadex(nullptr, 524288, ThreadStart, threadArgs, CREATE_SUSPENDED, nullptr);\n\t\tm_threads[i] = threadHandle;\n\n\t\tDWORD_PTR mask = 1 << i;\n\t\tSetThreadAffinityMask(threadHandle, mask);\n\t\tResumeThread(threadHandle);\n\t}\n}\n\nstd::shared_ptr<AtomicCounter> TaskScheduler::AddTask(Task task) {\n\tstd::shared_ptr<AtomicCounter> counter(new AtomicCounter());\n\tcounter->store(1);\n\n\tTaskBundle bundle = {task, counter};\n\tm_taskQueue.enqueue(bundle);\n\n\treturn counter;\n}\n\nstd::shared_ptr<AtomicCounter> TaskScheduler::AddTasks(uint numTasks, Task *tasks) {\n\tstd::shared_ptr<AtomicCounter> counter(new AtomicCounter());\n\tcounter->store(numTasks);\n\n\tfor (uint i = 0; i < numTasks; ++i) {\n\t\tTaskBundle bundle = {tasks[i], counter};\n\t\tm_taskQueue.enqueue(bundle);\n\t}\n\t\n\treturn counter;\n}\n\nbool TaskScheduler::GetNextTask(TaskBundle *nextTask) {\n\tbool success = m_taskQueue.try_dequeue(*nextTask);\n\n\treturn success;\n}\n\nvoid TaskScheduler::SwitchFibers(void *fiberToSwitchTo) {\n\ttls_currentFiber = GetCurrentFiber();\n\ttls_fiberToSwitchTo = fiberToSwitchTo;\n\n\tSwitchToFiber(m_fiberSwitchingFibers[tls_threadId]);\n}\n\nvoid TaskScheduler::WaitForCounter(std::shared_ptr<AtomicCounter> &counter, int value) {\n\tif (counter->load() == value) {\n\t\treturn;\n\t}\n\n\t\/\/ Switch to a new Fiber\n\tm_fiberPool.wait_dequeue(tls_fiberToSwitchTo);\n\n\ttls_currentFiber = GetCurrentFiber();\n\ttls_waitingCounter = counter.get();\n\ttls_waitingValue = value;\n\t\n\tSwitchToFiber(m_counterWaitingFibers[tls_threadId]);\n}\n\nvoid TaskScheduler::Quit() {\n\tm_quit.store(true);\n\tConvertFiberToThread();\n\n\tstd::vector<HANDLE> workerThreads;\n\tfor (uint i = 0; i < m_numThreads; ++i) {\n\t\tif (m_threads != GetCurrentThread()) {\n\t\t\tworkerThreads.push_back(m_threads[i]);\n\t\t}\n\t}\n\n\tDWORD result = WaitForMultipleObjects((DWORD)workerThreads.size(), &workerThreads[0], true, INFINITE);\n\n\tfor (auto &workerThread : workerThreads) {\n\t\tCloseHandle(workerThread);\n\t}\n}\n\n} \/\/ End of namespace FiberTaskingLib\n<|endoftext|>"} {"text":"<commit_before>#include \"labels.h\"\n\n#include \"tangram.h\"\n#include \"platform.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"gl\/primitives.h\"\n#include \"view\/view.h\"\n#include \"style\/material.h\"\n#include \"style\/style.h\"\n#include \"tile\/tile.h\"\n#include \"tile\/tileCache.h\"\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"glm\/gtx\/rotate_vector.hpp\"\n#include \"glm\/gtx\/norm.hpp\"\n\nnamespace Tangram {\n\nLabels::Labels()\n : m_needUpdate(false),\n m_lastZoom(0.0f)\n{}\n\nLabels::~Labels() {}\n\nint Labels::LODDiscardFunc(float _maxZoom, float _zoom) {\n return (int) MIN(floor(((log(-_zoom + (_maxZoom + 2)) \/ log(_maxZoom + 2) * (_maxZoom )) * 0.5)), MAX_LOD);\n}\n\nvoid Labels::update(const View& _view, float _dt, const std::vector<std::unique_ptr<Style>>& _styles,\n const std::vector<std::shared_ptr<Tile>>& _tiles, std::unique_ptr<TileCache>& _cache) {\n\n m_needUpdate = false;\n\n \/\/ float zoom = _view.getZoom();\n \/\/ int lodDiscard = LODDiscardFunc(View::s_maxZoom, zoom);\n \/\/ LOG(\"loddiscard %f %d\", zoom, lodDiscard);\n\n std::set<std::pair<Label*, Label*>> occlusions;\n\n \/\/ Could clear this at end of function unless debug draw is active\n m_labels.clear();\n m_aabbs.clear();\n m_visibleTextSet.clear();\n m_collideComponents.clear();\n m_repeatGroups.clear();\n\n glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());\n\n float currentZoom = _view.getZoom();\n float dz = currentZoom - std::floor(currentZoom);\n\n \/\/\/\/ Collect labels from visible tiles\n\n for (const auto& tile : _tiles) {\n\n \/\/ discard based on level of detail\n \/\/ if ((zoom - tile->getID().z) > lodDiscard) {\n \/\/ LOG(\"discard %d %d %d\", tile->getID().z, tile->getID().x, tile->getID().y);\n \/\/ continue;\n \/\/ }\n\n bool proxyTile = tile->isProxy();\n\n glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();\n\n for (const auto& style : _styles) {\n const auto& mesh = tile->getMesh(*style);\n if (!mesh) { continue; }\n\n const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());\n if (!labelMesh) { continue; }\n\n for (auto& label : labelMesh->getLabels()) {\n m_needUpdate |= label->update(mvp, screenSize, _dt, dz);\n\n label->setProxy(proxyTile);\n\n if (label->canOcclude()) {\n m_aabbs.push_back(label->aabb());\n m_aabbs.back().m_userData = (void*)label.get();\n }\n m_labels.push_back(label.get());\n }\n }\n }\n\n \/\/\/\/ Manage occlusions\n\n \/\/ broad phase\n m_isect2d.resize({_view.getWidth() \/ 256, _view.getHeight() \/ 256}, {_view.getWidth(), _view.getHeight()});\n m_isect2d.intersect(m_aabbs);\n\n \/\/ narrow phase\n for (auto pair : m_isect2d.pairs) {\n const auto& aabb1 = m_aabbs[pair.first];\n const auto& aabb2 = m_aabbs[pair.second];\n\n auto l1 = static_cast<Label*>(aabb1.m_userData);\n auto l2 = static_cast<Label*>(aabb2.m_userData);\n\n if (intersect(l1->obb(), l2->obb())) { occlusions.insert({l1, l2}); }\n }\n\n for (auto& pair : occlusions) {\n if (!pair.first->occludedLastFrame() || !pair.second->occludedLastFrame()) {\n \/\/ check first is the label belongs to a proxy tile\n if (pair.first->isProxy() && !pair.second->isProxy()) {\n pair.first->setOcclusion(true);\n } else if (!pair.first->isProxy() && pair.second->isProxy()) {\n pair.second->setOcclusion(true);\n } else {\n \/\/ lower numeric priority means higher priority\n if (pair.first->options().priority < pair.second->options().priority) {\n pair.second->setOcclusion(true);\n } else {\n pair.first->setOcclusion(true);\n }\n }\n }\n }\n\n \/\/\/\/ Mark labels to skip transitions\n\n if ((int) m_lastZoom != (int) currentZoom) {\n for (const auto& t0 : _tiles) {\n TileID tileID = t0->getID();\n std::vector<std::shared_ptr<Tile>> tiles;\n\n if (m_lastZoom < currentZoom) {\n \/\/ zooming in, add the one cached parent tile\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getParent()));\n } else {\n \/\/ zooming out, add the 4 cached children tiles\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(0)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(1)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(2)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(3)));\n }\n\n for (const auto& t1 : tiles) {\n if (!t1) { continue; }\n for (const auto& style : _styles) {\n const auto& m0 = t0->getMesh(*style);\n if (!m0) { continue; }\n const LabelMesh* mesh0 = dynamic_cast<const LabelMesh*>(m0.get());\n if (!mesh0) { continue; }\n const auto& m1 = t1->getMesh(*style);\n if (!m1) { continue; }\n const LabelMesh* mesh1 = static_cast<const LabelMesh*>(m1.get());\n\n for (auto& l0 : mesh0->getLabels()) {\n if (!l0->canOcclude()) { continue; }\n\n for (auto& l1 : mesh1->getLabels()) {\n if (!l1 || !l1->canOcclude() || l0->hash() != l1->hash()) {\n continue;\n }\n float d2 = glm::distance2(l0->transform().state.screenPos,\n l1->transform().state.screenPos);\n\n \/\/ The new label lies within the circle defined by the bbox of l0\n if (sqrt(d2) < std::max(l0->dimension().x, l0->dimension().y)) {\n l0->skipTransitions();\n }\n }\n }\n }\n }\n }\n }\n\n \/\/\/\/ Update label meshes\n\n for (auto label : m_labels) {\n label->occlusionSolved();\n label->pushTransform();\n\n if (label->canOcclude()) {\n if (!label->visibleState()) { continue; }\n TextLabel* textLabel = dynamic_cast<TextLabel*>(label);\n if (!textLabel) { continue; }\n m_visibleTextSet.push_back(textLabel);\n }\n }\n\n \/\/\/ Apply repeat groups\n\n \/\/ TODO: optimize\n \/\/ Ensure the labels are always treated in the same order\n std::sort(m_visibleTextSet.begin(), m_visibleTextSet.end(), [](TextLabel* _a, TextLabel* _b) {\n std::size_t seed0 = 0;\n std::size_t seed1 = 0;\n hash_combine(seed0, _a->hash());\n hash_combine(seed0, _a->transform().modelPosition1.x);\n hash_combine(seed0, _a->transform().modelPosition1.y);\n hash_combine(seed1, _b->hash());\n hash_combine(seed1, _b->transform().modelPosition1.x);\n hash_combine(seed1, _b->transform().modelPosition1.y);\n return seed0 < seed1;\n });\n\n auto textLabelIt = m_visibleTextSet.begin();\n while (textLabelIt != m_visibleTextSet.end()) {\n auto textLabel = *textLabelIt;\n CollideComponent component;\n component.position = textLabel->transform().state.screenPos;\n component.userData = (void*)textLabel;\n\n std::size_t seed = 0;\n hash_combine(seed, textLabel->text);\n\n component.group = seed;\n component.mask = seed;\n\n auto it = m_repeatGroups.find(seed);\n if (it != m_repeatGroups.end()) {\n std::vector<CollideComponent>& group = m_repeatGroups[seed];\n\n if (std::find(group.begin(), group.end(), component) == group.end()) {\n std::vector<CollideComponent> newGroup(group);\n newGroup.push_back(component);\n\n isect2d::CollideOption options;\n options.thresholdDistance = 300.0f;\n options.rule = isect2d::CollideRuleOption::UNIDIRECTIONNAL;\n\n auto collisionMaskPairs = isect2d::intersect(newGroup, options);\n\n if (collisionMaskPairs.size() == 0) {\n group.push_back(component);\n textLabelIt++;\n } else {\n textLabel->setOcclusion(true);\n m_visibleTextSet.erase(textLabelIt);\n }\n } else {\n textLabelIt++;\n }\n } else {\n m_repeatGroups[seed].push_back(component);\n textLabelIt++;\n }\n }\n\n \/\/ Request for render if labels are in fading in\/out states\n if (m_needUpdate) {\n requestRender();\n }\n\n m_lastZoom = currentZoom;\n}\n\n\n\n\nconst std::vector<TouchItem>& Labels::getFeaturesAtPoint(const View& _view, float _dt,\n const std::vector<std::unique_ptr<Style>>& _styles,\n const std::vector<std::shared_ptr<Tile>>& _tiles,\n float _x, float _y, bool _visibleOnly) {\n \/\/ FIXME dpi dependent threshold\n const float thumbSize = 50;\n\n m_touchItems.clear();\n\n glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());\n glm::vec2 touchPoint(_x, _y);\n\n OBB obb(_x - thumbSize\/2, _y - thumbSize\/2, 0, thumbSize, thumbSize);\n\n float z = _view.getZoom();\n float dz = z - std::floor(z);\n\n for (const auto& tile : _tiles) {\n\n glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();\n\n for (const auto& style : _styles) {\n const auto& mesh = tile->getMesh(*style);\n if (!mesh) { continue; }\n\n const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());\n if (!labelMesh) { continue; }\n\n for (auto& label : labelMesh->getLabels()) {\n\n auto& options = label->options();\n if (!options.interactive) { continue; }\n\n if (!_visibleOnly) {\n label->updateScreenTransform(mvp, screenSize, false);\n label->updateBBoxes(dz);\n }\n\n if (isect2d::intersect(label->obb(), obb)) {\n float distance = glm::length2(label->transform().state.screenPos - touchPoint);\n\n m_touchItems.push_back({options.properties, std::sqrt(distance)});\n }\n }\n }\n }\n\n std::sort(m_touchItems.begin(), m_touchItems.end(),\n [](auto& a, auto& b){ return a.distance < b.distance; });\n\n\n return m_touchItems;\n}\n\n\n\nvoid Labels::drawDebug(const View& _view) {\n\n if (!Tangram::getDebugFlag(Tangram::DebugFlags::labels)) {\n return;\n }\n\n for (auto label : m_labels) {\n if (label->canOcclude()) {\n glm::vec2 offset = label->options().offset;\n glm::vec2 sp = label->transform().state.screenPos;\n float angle = label->transform().state.rotation;\n offset = glm::rotate(offset, angle);\n\n \/\/ draw bounding box\n Label::State state = label->state();\n switch (state) {\n case Label::State::sleep:\n Primitives::setColor(0x00ff00);\n break;\n case Label::State::visible:\n Primitives::setColor(0x000000);\n break;\n case Label::State::wait_occ:\n Primitives::setColor(0x0000ff);\n break;\n case Label::State::fading_in:\n case Label::State::fading_out:\n Primitives::setColor(0xffff00);\n break;\n default:\n Primitives::setColor(0xff0000);\n }\n\n Primitives::drawPoly(&(label->obb().getQuad())[0], 4);\n\n \/\/ draw offset\n Primitives::setColor(0x000000);\n Primitives::drawLine(sp, sp - offset);\n\n \/\/ draw projected anchor point\n Primitives::setColor(0x0000ff);\n Primitives::drawRect(sp - glm::vec2(1.f), sp + glm::vec2(1.f));\n }\n }\n\n glm::vec2 split(_view.getWidth() \/ 256, _view.getHeight() \/ 256);\n glm::vec2 res(_view.getWidth(), _view.getHeight());\n const short xpad = short(ceilf(res.x \/ split.x));\n const short ypad = short(ceilf(res.y \/ split.y));\n\n Primitives::setColor(0x7ef586);\n short x = 0, y = 0;\n for (int j = 0; j < split.y; ++j) {\n for (int i = 0; i < split.x; ++i) {\n AABB cell(x, y, x + xpad, y + ypad);\n Primitives::drawRect({x, y}, {x + xpad, y + ypad});\n x += xpad;\n if (x >= res.x) {\n x = 0;\n y += ypad;\n }\n }\n }\n}\n\n}\n<commit_msg>Sort by distance of the feature world position<commit_after>#include \"labels.h\"\n\n#include \"tangram.h\"\n#include \"platform.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"gl\/primitives.h\"\n#include \"view\/view.h\"\n#include \"style\/material.h\"\n#include \"style\/style.h\"\n#include \"tile\/tile.h\"\n#include \"tile\/tileCache.h\"\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"glm\/gtx\/rotate_vector.hpp\"\n#include \"glm\/gtx\/norm.hpp\"\n\nnamespace Tangram {\n\nLabels::Labels()\n : m_needUpdate(false),\n m_lastZoom(0.0f)\n{}\n\nLabels::~Labels() {}\n\nint Labels::LODDiscardFunc(float _maxZoom, float _zoom) {\n return (int) MIN(floor(((log(-_zoom + (_maxZoom + 2)) \/ log(_maxZoom + 2) * (_maxZoom )) * 0.5)), MAX_LOD);\n}\n\nvoid Labels::update(const View& _view, float _dt, const std::vector<std::unique_ptr<Style>>& _styles,\n const std::vector<std::shared_ptr<Tile>>& _tiles, std::unique_ptr<TileCache>& _cache) {\n\n m_needUpdate = false;\n\n \/\/ float zoom = _view.getZoom();\n \/\/ int lodDiscard = LODDiscardFunc(View::s_maxZoom, zoom);\n \/\/ LOG(\"loddiscard %f %d\", zoom, lodDiscard);\n\n std::set<std::pair<Label*, Label*>> occlusions;\n\n \/\/ Could clear this at end of function unless debug draw is active\n m_labels.clear();\n m_aabbs.clear();\n m_visibleTextSet.clear();\n m_collideComponents.clear();\n m_repeatGroups.clear();\n\n glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());\n\n float currentZoom = _view.getZoom();\n float dz = currentZoom - std::floor(currentZoom);\n\n \/\/\/\/ Collect labels from visible tiles\n\n for (const auto& tile : _tiles) {\n\n \/\/ discard based on level of detail\n \/\/ if ((zoom - tile->getID().z) > lodDiscard) {\n \/\/ LOG(\"discard %d %d %d\", tile->getID().z, tile->getID().x, tile->getID().y);\n \/\/ continue;\n \/\/ }\n\n bool proxyTile = tile->isProxy();\n\n glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();\n\n for (const auto& style : _styles) {\n const auto& mesh = tile->getMesh(*style);\n if (!mesh) { continue; }\n\n const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());\n if (!labelMesh) { continue; }\n\n for (auto& label : labelMesh->getLabels()) {\n m_needUpdate |= label->update(mvp, screenSize, _dt, dz);\n\n label->setProxy(proxyTile);\n\n if (label->canOcclude()) {\n m_aabbs.push_back(label->aabb());\n m_aabbs.back().m_userData = (void*)label.get();\n }\n m_labels.push_back(label.get());\n }\n }\n }\n\n \/\/\/\/ Manage occlusions\n\n \/\/ broad phase\n m_isect2d.resize({_view.getWidth() \/ 256, _view.getHeight() \/ 256}, {_view.getWidth(), _view.getHeight()});\n m_isect2d.intersect(m_aabbs);\n\n \/\/ narrow phase\n for (auto pair : m_isect2d.pairs) {\n const auto& aabb1 = m_aabbs[pair.first];\n const auto& aabb2 = m_aabbs[pair.second];\n\n auto l1 = static_cast<Label*>(aabb1.m_userData);\n auto l2 = static_cast<Label*>(aabb2.m_userData);\n\n if (intersect(l1->obb(), l2->obb())) { occlusions.insert({l1, l2}); }\n }\n\n for (auto& pair : occlusions) {\n if (!pair.first->occludedLastFrame() || !pair.second->occludedLastFrame()) {\n \/\/ check first is the label belongs to a proxy tile\n if (pair.first->isProxy() && !pair.second->isProxy()) {\n pair.first->setOcclusion(true);\n } else if (!pair.first->isProxy() && pair.second->isProxy()) {\n pair.second->setOcclusion(true);\n } else {\n \/\/ lower numeric priority means higher priority\n if (pair.first->options().priority < pair.second->options().priority) {\n pair.second->setOcclusion(true);\n } else {\n pair.first->setOcclusion(true);\n }\n }\n }\n }\n\n \/\/\/\/ Mark labels to skip transitions\n\n if ((int) m_lastZoom != (int) currentZoom) {\n for (const auto& t0 : _tiles) {\n TileID tileID = t0->getID();\n std::vector<std::shared_ptr<Tile>> tiles;\n\n if (m_lastZoom < currentZoom) {\n \/\/ zooming in, add the one cached parent tile\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getParent()));\n } else {\n \/\/ zooming out, add the 4 cached children tiles\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(0)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(1)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(2)));\n tiles.push_back(_cache->contains(t0->sourceID(), tileID.getChild(3)));\n }\n\n for (const auto& t1 : tiles) {\n if (!t1) { continue; }\n for (const auto& style : _styles) {\n const auto& m0 = t0->getMesh(*style);\n if (!m0) { continue; }\n const LabelMesh* mesh0 = dynamic_cast<const LabelMesh*>(m0.get());\n if (!mesh0) { continue; }\n const auto& m1 = t1->getMesh(*style);\n if (!m1) { continue; }\n const LabelMesh* mesh1 = static_cast<const LabelMesh*>(m1.get());\n\n for (auto& l0 : mesh0->getLabels()) {\n if (!l0->canOcclude()) { continue; }\n\n for (auto& l1 : mesh1->getLabels()) {\n if (!l1 || !l1->canOcclude() || l0->hash() != l1->hash()) {\n continue;\n }\n float d2 = glm::distance2(l0->transform().state.screenPos,\n l1->transform().state.screenPos);\n\n \/\/ The new label lies within the circle defined by the bbox of l0\n if (sqrt(d2) < std::max(l0->dimension().x, l0->dimension().y)) {\n l0->skipTransitions();\n }\n }\n }\n }\n }\n }\n }\n\n \/\/\/\/ Update label meshes\n\n for (auto label : m_labels) {\n label->occlusionSolved();\n label->pushTransform();\n\n if (label->canOcclude()) {\n if (!label->visibleState()) { continue; }\n TextLabel* textLabel = dynamic_cast<TextLabel*>(label);\n if (!textLabel) { continue; }\n m_visibleTextSet.push_back(textLabel);\n }\n }\n\n \/\/\/ Apply repeat groups\n\n \/\/ Ensure the labels are always treated in the same order\n std::sort(m_visibleTextSet.begin(), m_visibleTextSet.end(), [](TextLabel* _a, TextLabel* _b) {\n return glm::length2(_a->transform().modelPosition1) < glm::length2(_b->transform().modelPosition1);\n });\n\n auto textLabelIt = m_visibleTextSet.begin();\n while (textLabelIt != m_visibleTextSet.end()) {\n auto textLabel = *textLabelIt;\n CollideComponent component;\n component.position = textLabel->transform().state.screenPos;\n component.userData = (void*)textLabel;\n\n std::size_t seed = 0;\n hash_combine(seed, textLabel->text);\n\n component.group = seed;\n component.mask = seed;\n\n auto it = m_repeatGroups.find(seed);\n if (it != m_repeatGroups.end()) {\n std::vector<CollideComponent>& group = m_repeatGroups[seed];\n\n if (std::find(group.begin(), group.end(), component) == group.end()) {\n std::vector<CollideComponent> newGroup(group);\n newGroup.push_back(component);\n\n isect2d::CollideOption options;\n options.thresholdDistance = 100.0f;\n options.rule = isect2d::CollideRuleOption::UNIDIRECTIONNAL;\n\n auto collisionMaskPairs = isect2d::intersect(newGroup, options);\n\n if (collisionMaskPairs.size() == 0) {\n group.push_back(component);\n textLabelIt++;\n } else {\n textLabel->setOcclusion(true);\n m_visibleTextSet.erase(textLabelIt);\n }\n } else {\n textLabelIt++;\n }\n } else {\n m_repeatGroups[seed].push_back(component);\n textLabelIt++;\n }\n }\n\n \/\/ Request for render if labels are in fading in\/out states\n if (m_needUpdate) {\n requestRender();\n }\n\n m_lastZoom = currentZoom;\n}\n\n\n\n\nconst std::vector<TouchItem>& Labels::getFeaturesAtPoint(const View& _view, float _dt,\n const std::vector<std::unique_ptr<Style>>& _styles,\n const std::vector<std::shared_ptr<Tile>>& _tiles,\n float _x, float _y, bool _visibleOnly) {\n \/\/ FIXME dpi dependent threshold\n const float thumbSize = 50;\n\n m_touchItems.clear();\n\n glm::vec2 screenSize = glm::vec2(_view.getWidth(), _view.getHeight());\n glm::vec2 touchPoint(_x, _y);\n\n OBB obb(_x - thumbSize\/2, _y - thumbSize\/2, 0, thumbSize, thumbSize);\n\n float z = _view.getZoom();\n float dz = z - std::floor(z);\n\n for (const auto& tile : _tiles) {\n\n glm::mat4 mvp = _view.getViewProjectionMatrix() * tile->getModelMatrix();\n\n for (const auto& style : _styles) {\n const auto& mesh = tile->getMesh(*style);\n if (!mesh) { continue; }\n\n const LabelMesh* labelMesh = dynamic_cast<const LabelMesh*>(mesh.get());\n if (!labelMesh) { continue; }\n\n for (auto& label : labelMesh->getLabels()) {\n\n auto& options = label->options();\n if (!options.interactive) { continue; }\n\n if (!_visibleOnly) {\n label->updateScreenTransform(mvp, screenSize, false);\n label->updateBBoxes(dz);\n }\n\n if (isect2d::intersect(label->obb(), obb)) {\n float distance = glm::length2(label->transform().state.screenPos - touchPoint);\n\n m_touchItems.push_back({options.properties, std::sqrt(distance)});\n }\n }\n }\n }\n\n std::sort(m_touchItems.begin(), m_touchItems.end(),\n [](auto& a, auto& b){ return a.distance < b.distance; });\n\n\n return m_touchItems;\n}\n\n\n\nvoid Labels::drawDebug(const View& _view) {\n\n if (!Tangram::getDebugFlag(Tangram::DebugFlags::labels)) {\n return;\n }\n\n for (auto label : m_labels) {\n if (label->canOcclude()) {\n glm::vec2 offset = label->options().offset;\n glm::vec2 sp = label->transform().state.screenPos;\n float angle = label->transform().state.rotation;\n offset = glm::rotate(offset, angle);\n\n \/\/ draw bounding box\n Label::State state = label->state();\n switch (state) {\n case Label::State::sleep:\n Primitives::setColor(0x00ff00);\n break;\n case Label::State::visible:\n Primitives::setColor(0x000000);\n break;\n case Label::State::wait_occ:\n Primitives::setColor(0x0000ff);\n break;\n case Label::State::fading_in:\n case Label::State::fading_out:\n Primitives::setColor(0xffff00);\n break;\n default:\n Primitives::setColor(0xff0000);\n }\n\n Primitives::drawPoly(&(label->obb().getQuad())[0], 4);\n\n \/\/ draw offset\n Primitives::setColor(0x000000);\n Primitives::drawLine(sp, sp - offset);\n\n \/\/ draw projected anchor point\n Primitives::setColor(0x0000ff);\n Primitives::drawRect(sp - glm::vec2(1.f), sp + glm::vec2(1.f));\n }\n }\n\n glm::vec2 split(_view.getWidth() \/ 256, _view.getHeight() \/ 256);\n glm::vec2 res(_view.getWidth(), _view.getHeight());\n const short xpad = short(ceilf(res.x \/ split.x));\n const short ypad = short(ceilf(res.y \/ split.y));\n\n Primitives::setColor(0x7ef586);\n short x = 0, y = 0;\n for (int j = 0; j < split.y; ++j) {\n for (int i = 0; i < split.x; ++i) {\n AABB cell(x, y, x + xpad, y + ypad);\n Primitives::drawRect({x, y}, {x + xpad, y + ypad});\n x += xpad;\n if (x >= res.x) {\n x = 0;\n y += ypad;\n }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n===========================================================================\nCopyright (C) 1999-2005 Id Software, Inc.\nCopyright (C) 2007 HermitWorks Entertainment Corporation\nCopyright (C) 2006-2009 Robert Beckebans <trebor_7@users.sourceforge.net>\n\nThis file is part of Daemon source code.\n\nDaemon source code is free software; you can redistribute it\nand\/or modify it under the terms of the GNU General Public License as\npublished by the Free Software Foundation; either version 2 of the License,\nor (at your option) any later version.\n\nDaemon source code is distributed in the hope that it will be\nuseful, but WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon source code; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n===========================================================================\n*\/\n\n#include \"tr_local.h\"\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n#endif\n\n\/\/ HACK: Try to crash less when asked to decode invalid inputs.\nclass crnd_decompression_exception : public std::exception {};\n#define CRND_ASSERT(_exp) (!!(_exp) ? (void)0 : throw crnd_decompression_exception())\n\n#include \"crunch\/inc\/crn_decomp.h\"\n\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\nbool LoadInMemoryCRN(void* buff, size_t buffLen, byte **data, int *width, int *height,\n int *numLayers, int *numMips, int *bits)\n{\n if (crnd::crnd_validate_file(buff, buffLen, nullptr)) { \/\/ Checks the header, not the whole file.\n \/\/ Found height and width in [1, 4096], num mip levels in [1, 13], faces in {1, 6}\n } else {\n return false;\n }\n crnd::crn_texture_info ti;\n if (!crnd::crnd_get_texture_info(buff, buffLen, &ti)) {\n return false;\n }\n\n switch (ti.m_format) {\n case cCRNFmtDXT1:\n *bits |= IF_BC1;\n break;\n case cCRNFmtDXT3:\n *bits |= IF_BC2;\n break;\n case cCRNFmtDXT5:\n *bits |= IF_BC3;\n break;\n case cCRNFmtDXT5A:\n *bits |= IF_BC4;\n break;\n case cCRNFmtDXN_XY:\n *bits |= IF_BC5;\n break;\n default:\n return false;\n }\n\n *width = ti.m_width;\n *height = ti.m_height;\n *numMips = ti.m_levels;\n *numLayers = ti.m_faces == 6 ? 6 : 0;\n\n uint32_t totalSize = 0;\n uint32_t sizes[cCRNMaxLevels];\n for (unsigned i = 0; i < ti.m_levels; i++) {\n crnd::crn_level_info li;\n if (!crnd::crnd_get_level_info(buff, buffLen, i, &li)) {\n return false;\n }\n sizes[i] = li.m_blocks_x * li.m_blocks_y * li.m_bytes_per_block;\n totalSize += sizes[i] * ti.m_faces;\n }\n\n crnd::crnd_unpack_context ctx = crnd::crnd_unpack_begin(buff, buffLen);\n if (!ctx) {\n return false;\n }\n byte* nextImage = (byte *)ri.Z_Malloc(totalSize);\n bool success = true;\n for (unsigned i = 0; i < ti.m_levels; i++) {\n for (unsigned j = 0; j < ti.m_faces; j++) {\n data[i * ti.m_faces + j] = nextImage;\n nextImage += sizes[i];\n }\n try {\n if (!crnd::crnd_unpack_level(ctx, (void **)&data[i * ti.m_faces], sizes[i], 0, i)) {\n success = false;\n break;\n }\n } catch (const crnd_decompression_exception&) {\n \/\/ Exception added as a hack to try and avoid crashing on files using the old format.\n \/\/ In general though, it seems the crunch library does not try to validate the files and may crash while decoding.\n success = false;\n break;\n }\n }\n crnd::crnd_unpack_end(ctx);\n return success;\n}\n\nvoid LoadCRN(const char* name, byte **data, int *width, int *height,\n int *numLayers, int *numMips, int *bits, byte)\n{\n void* buff;\n size_t buffLen = ri.FS_ReadFile(name, &buff);\n *numLayers = 0;\n if (!buff) {\n return;\n }\n if (!LoadInMemoryCRN(buff, buffLen, data, width, height, numLayers, numMips, bits)) {\n if (*data) {\n ri.Free(*data);\n *data = nullptr; \/\/ This signals failure.\n }\n Log::Warn(\"CRN image '%s' has an invalid format\", name);\n }\n ri.FS_FreeFile(buff);\n}\n<commit_msg>Show detailed CRN image load warnings<commit_after>\/*\n===========================================================================\nCopyright (C) 1999-2005 Id Software, Inc.\nCopyright (C) 2007 HermitWorks Entertainment Corporation\nCopyright (C) 2006-2009 Robert Beckebans <trebor_7@users.sourceforge.net>\n\nThis file is part of Daemon source code.\n\nDaemon source code is free software; you can redistribute it\nand\/or modify it under the terms of the GNU General Public License as\npublished by the Free Software Foundation; either version 2 of the License,\nor (at your option) any later version.\n\nDaemon source code is distributed in the hope that it will be\nuseful, but WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon source code; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n===========================================================================\n*\/\n\n#include \"tr_local.h\"\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n#endif\n\n\/\/ HACK: Try to crash less when asked to decode invalid inputs.\nclass crnd_decompression_exception : public std::exception {};\n#define CRND_ASSERT(_exp) (!!(_exp) ? (void)0 : throw crnd_decompression_exception())\n\n#include \"crunch\/inc\/crn_decomp.h\"\n\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n#define CASE_CRN_FORMAT(format) \\\n case format: return STRING(format);\n\nnamespace {\nstd::string CRNFormatToString(crn_format format)\n{\n switch (format)\n {\n CASE_CRN_FORMAT(cCRNFmtDXT1);\n CASE_CRN_FORMAT(cCRNFmtDXT3);\n CASE_CRN_FORMAT(cCRNFmtDXT5);\n CASE_CRN_FORMAT(cCRNFmtDXT5_CCxY);\n CASE_CRN_FORMAT(cCRNFmtDXT5_xGxR);\n CASE_CRN_FORMAT(cCRNFmtDXT5_xGBR);\n CASE_CRN_FORMAT(cCRNFmtDXT5_AGBR);\n CASE_CRN_FORMAT(cCRNFmtDXN_XY);\n CASE_CRN_FORMAT(cCRNFmtDXN_YX);\n CASE_CRN_FORMAT(cCRNFmtDXT5A);\n CASE_CRN_FORMAT(cCRNFmtETC1);\n CASE_CRN_FORMAT(cCRNFmtETC2);\n CASE_CRN_FORMAT(cCRNFmtETC2A);\n CASE_CRN_FORMAT(cCRNFmtETC1S);\n CASE_CRN_FORMAT(cCRNFmtETC2AS);\n default:\n return \"unknown (\" + std::to_string(Util::ordinal(format)) + \")\";\n }\n}\n\nbool LoadInMemoryCRN(const char* name, void* buff, size_t buffLen, byte **data, int *width, int *height,\n int *numLayers, int *numMips, int *bits)\n{\n if (crnd::crnd_validate_file(buff, buffLen, nullptr)) { \/\/ Checks the header, not the whole file.\n \/\/ Found height and width in [1, 4096], num mip levels in [1, 13], faces in {1, 6}\n } else {\n Log::Warn(\"CRN image '%s' has an invalid header\", name);\n return false;\n }\n crnd::crn_texture_info ti;\n if (!crnd::crnd_get_texture_info(buff, buffLen, &ti)) {\n Log::Warn(\"CRN image '%s' has bad texture info\", name);\n return false;\n }\n\n switch (ti.m_format) {\n case cCRNFmtDXT1:\n *bits |= IF_BC1;\n break;\n case cCRNFmtDXT3:\n *bits |= IF_BC2;\n break;\n case cCRNFmtDXT5:\n *bits |= IF_BC3;\n break;\n case cCRNFmtDXT5A:\n *bits |= IF_BC4;\n break;\n case cCRNFmtDXN_XY:\n *bits |= IF_BC5;\n break;\n default:\n Log::Warn(\"CRN image '%s' has unsupported format '%s'\", name, CRNFormatToString(ti.m_format));\n return false;\n }\n\n *width = ti.m_width;\n *height = ti.m_height;\n *numMips = ti.m_levels;\n *numLayers = ti.m_faces == 6 ? 6 : 0;\n\n uint32_t totalSize = 0;\n uint32_t sizes[cCRNMaxLevels];\n for (unsigned i = 0; i < ti.m_levels; i++) {\n crnd::crn_level_info li;\n if (!crnd::crnd_get_level_info(buff, buffLen, i, &li)) {\n Log::Warn(\"CRN image '%s' has bad info on level '%d'\", name, i);\n return false;\n }\n sizes[i] = li.m_blocks_x * li.m_blocks_y * li.m_bytes_per_block;\n totalSize += sizes[i] * ti.m_faces;\n }\n\n crnd::crnd_unpack_context ctx = crnd::crnd_unpack_begin(buff, buffLen);\n if (!ctx) {\n Log::Warn(\"CRN image '%s' has bad data\", name);\n return false;\n }\n byte* nextImage = (byte *)ri.Z_Malloc(totalSize);\n bool success = true;\n for (unsigned i = 0; i < ti.m_levels; i++) {\n for (unsigned j = 0; j < ti.m_faces; j++) {\n data[i * ti.m_faces + j] = nextImage;\n nextImage += sizes[i];\n }\n try {\n if (!crnd::crnd_unpack_level(ctx, (void **)&data[i * ti.m_faces], sizes[i], 0, i)) {\n Log::Warn(\"CRN image '%s' has bad level '%d'\", name, i);\n success = false;\n break;\n }\n } catch (const crnd_decompression_exception& ex) {\n \/\/ Exception added as a hack to try and avoid crashing on files using the old format.\n \/\/ In general though, it seems the crunch library does not try to validate the files and may crash while decoding.\n Log::Warn(\"CRN image '%s' decompression failure for level '%d': %s\", name, i, ex.what());\n success = false;\n break;\n }\n }\n crnd::crnd_unpack_end(ctx);\n return success;\n}\n} \/\/ namespace\n\nvoid LoadCRN(const char* name, byte **data, int *width, int *height,\n int *numLayers, int *numMips, int *bits, byte)\n{\n void* buff;\n size_t buffLen = ri.FS_ReadFile(name, &buff);\n *numLayers = 0;\n if (!buff) {\n return;\n }\n if (!LoadInMemoryCRN(name, buff, buffLen, data, width, height, numLayers, numMips, bits)) {\n if (*data) {\n ri.Free(*data);\n *data = nullptr; \/\/ This signals failure.\n }\n }\n ri.FS_FreeFile(buff);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>\n**\n** This file is part of chemkit. For more information see\n** <http:\/\/www.chemkit.org>.\n**\n** chemkit is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** chemkit is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU Lesser General Public License\n** along with chemkit. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\n******************************************************************************\/\n\n#include <QtTest>\n\n#include <chemkit\/staticmatrix.h>\n\nclass StaticMatrixTest : public QObject\n{\n Q_OBJECT\n\n private slots:\n void multiply();\n void multiplyScalar();\n void determinant();\n void invert();\n};\n\nvoid StaticMatrixTest::multiply()\n{\n chemkit::StaticMatrix<chemkit::Float, 2, 3> a;\n a(0, 0) = 8;\n a(0, 1) = -6;\n a(0, 2) = 1;\n a(1, 0) = 4;\n a(1, 1) = 7;\n a(1, 2) = -2;\n\n chemkit::StaticMatrix<chemkit::Float, 3, 2> b;\n b(0, 0) = 0;\n b(0, 1) = 3;\n b(1, 0) = 3;\n b(1, 1) = 4;\n b(2, 0) = 7;\n b(2, 1) = -2;\n\n \/\/ c = a * b\n chemkit::StaticMatrix<chemkit::Float, 2, 2> c = a.multiply(b);\n QCOMPARE(c(0, 0), chemkit::Float(-11.0));\n QCOMPARE(c(0, 1), chemkit::Float(-2.0));\n QCOMPARE(c(1, 0), chemkit::Float(7.0));\n QCOMPARE(c(1, 1), chemkit::Float(44.0));\n\n \/\/ d = b * a\n chemkit::StaticMatrix<chemkit::Float, 3, 3> d = b.multiply(a);\n QCOMPARE(d(0, 0), chemkit::Float(12.0));\n QCOMPARE(d(0, 1), chemkit::Float(21.0));\n QCOMPARE(d(0, 2), chemkit::Float(-6.0));\n QCOMPARE(d(1, 0), chemkit::Float(40.0));\n QCOMPARE(d(1, 1), chemkit::Float(10.0));\n QCOMPARE(d(1, 2), chemkit::Float(-5.0));\n QCOMPARE(d(2, 0), chemkit::Float(48.0));\n QCOMPARE(d(2, 1), chemkit::Float(-56.0));\n QCOMPARE(d(2, 2), chemkit::Float(11.0));\n}\n\nvoid StaticMatrixTest::multiplyScalar()\n{\n chemkit::StaticMatrix<int, 2, 3> a;\n a << 1, 2, 3,\n 4, 5, 6;\n\n chemkit::StaticMatrix<int, 2, 3> b = a.multiply(4);\n QCOMPARE(b(0, 0), 4);\n QCOMPARE(b(0, 1), 8);\n QCOMPARE(b(0, 2), 12);\n QCOMPARE(b(1, 0), 16);\n QCOMPARE(b(1, 1), 20);\n QCOMPARE(b(1, 2), 24);\n\n chemkit::StaticMatrix<int, 3, 3> c;\n c << 2, 4, 6,\n 8, 10, 12,\n 14, 16, 18;\n\n chemkit::StaticMatrix<int, 3, 3> d = c.multiply(-1);\n QCOMPARE(d(0, 0), -2);\n QCOMPARE(d(0, 1), -4);\n QCOMPARE(d(0, 2), -6);\n QCOMPARE(d(1, 0), -8);\n QCOMPARE(d(1, 1), -10);\n QCOMPARE(d(1, 2), -12);\n QCOMPARE(d(2, 0), -14);\n QCOMPARE(d(2, 1), -16);\n QCOMPARE(d(2, 2), -18);\n}\n\nvoid StaticMatrixTest::determinant()\n{\n \/\/ 3x3 matrix filled with 2's\n chemkit::StaticMatrix<chemkit::Float, 3, 3> matrix3;\n matrix3.fill(2);\n QCOMPARE(qRound(matrix3.determinant()), 0);\n\n \/\/ another matrix\n matrix3.fill(0);\n matrix3(0, 0) = 6;\n matrix3(0, 1) = 3;\n matrix3(0, 2) = 2;\n matrix3(1, 0) = 4;\n matrix3(1, 1) = -3;\n matrix3(1, 2) = 2;\n matrix3(2, 0) = -1;\n matrix3(2, 1) = 9;\n matrix3(2, 2) = -2;\n QCOMPARE(qRound(matrix3.determinant()), 12);\n\n \/\/ change last row\n matrix3(2, 0) = 0;\n matrix3(2, 1) = 4;\n matrix3(2, 2) = 0;\n QCOMPARE(qRound(matrix3.determinant()), -16);\n\n \/\/ change first row\n matrix3(0, 0) = 0;\n matrix3(0, 1) = 4;\n matrix3(0, 2) = 0;\n QCOMPARE(qRound(matrix3.determinant()), 0);\n}\n\nvoid StaticMatrixTest::invert()\n{\n chemkit::StaticMatrix<chemkit::Float, 3, 3> matrix3;\n matrix3(0, 0) = 1;\n matrix3(0, 1) = 2;\n matrix3(0, 2) = 3;\n matrix3(1, 0) = 0;\n matrix3(1, 1) = 1;\n matrix3(1, 2) = 0;\n matrix3(2, 0) = 4;\n matrix3(2, 1) = 0;\n matrix3(2, 2) = 4;\n\n chemkit::StaticMatrix<chemkit::Float, 3, 3> inverse3 = matrix3.inverted();\n QCOMPARE(inverse3(0, 0), chemkit::Float(-0.5));\n QCOMPARE(inverse3(0, 1), chemkit::Float(1.0));\n QCOMPARE(inverse3(0, 2), chemkit::Float(0.375));\n QCOMPARE(inverse3(1, 0), chemkit::Float(0.0));\n QCOMPARE(inverse3(1, 1), chemkit::Float(1.0));\n QCOMPARE(inverse3(1, 2), chemkit::Float(0.0));\n QCOMPARE(inverse3(2, 0), chemkit::Float(0.5));\n QCOMPARE(inverse3(2, 1), chemkit::Float(-1.0));\n QCOMPARE(inverse3(2, 2), chemkit::Float(-0.125));\n}\n\nQTEST_APPLESS_MAIN(StaticMatrixTest)\n#include \"staticmatrixtest.moc\"\n<commit_msg>Add test for StaticMatrix::multiply()<commit_after>\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>\n**\n** This file is part of chemkit. For more information see\n** <http:\/\/www.chemkit.org>.\n**\n** chemkit is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** chemkit is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU Lesser General Public License\n** along with chemkit. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\n******************************************************************************\/\n\n#include <QtTest>\n\n#include <chemkit\/staticmatrix.h>\n#include <chemkit\/staticvector.h>\n\nclass StaticMatrixTest : public QObject\n{\n Q_OBJECT\n\n private slots:\n void multiply();\n void multiplyScalar();\n void multiplyVector();\n void determinant();\n void invert();\n};\n\nvoid StaticMatrixTest::multiply()\n{\n chemkit::StaticMatrix<chemkit::Float, 2, 3> a;\n a(0, 0) = 8;\n a(0, 1) = -6;\n a(0, 2) = 1;\n a(1, 0) = 4;\n a(1, 1) = 7;\n a(1, 2) = -2;\n\n chemkit::StaticMatrix<chemkit::Float, 3, 2> b;\n b(0, 0) = 0;\n b(0, 1) = 3;\n b(1, 0) = 3;\n b(1, 1) = 4;\n b(2, 0) = 7;\n b(2, 1) = -2;\n\n \/\/ c = a * b\n chemkit::StaticMatrix<chemkit::Float, 2, 2> c = a.multiply(b);\n QCOMPARE(c(0, 0), chemkit::Float(-11.0));\n QCOMPARE(c(0, 1), chemkit::Float(-2.0));\n QCOMPARE(c(1, 0), chemkit::Float(7.0));\n QCOMPARE(c(1, 1), chemkit::Float(44.0));\n\n \/\/ d = b * a\n chemkit::StaticMatrix<chemkit::Float, 3, 3> d = b.multiply(a);\n QCOMPARE(d(0, 0), chemkit::Float(12.0));\n QCOMPARE(d(0, 1), chemkit::Float(21.0));\n QCOMPARE(d(0, 2), chemkit::Float(-6.0));\n QCOMPARE(d(1, 0), chemkit::Float(40.0));\n QCOMPARE(d(1, 1), chemkit::Float(10.0));\n QCOMPARE(d(1, 2), chemkit::Float(-5.0));\n QCOMPARE(d(2, 0), chemkit::Float(48.0));\n QCOMPARE(d(2, 1), chemkit::Float(-56.0));\n QCOMPARE(d(2, 2), chemkit::Float(11.0));\n}\n\nvoid StaticMatrixTest::multiplyScalar()\n{\n chemkit::StaticMatrix<int, 2, 3> a;\n a << 1, 2, 3,\n 4, 5, 6;\n\n chemkit::StaticMatrix<int, 2, 3> b = a.multiply(4);\n QCOMPARE(b(0, 0), 4);\n QCOMPARE(b(0, 1), 8);\n QCOMPARE(b(0, 2), 12);\n QCOMPARE(b(1, 0), 16);\n QCOMPARE(b(1, 1), 20);\n QCOMPARE(b(1, 2), 24);\n\n chemkit::StaticMatrix<int, 3, 3> c;\n c << 2, 4, 6,\n 8, 10, 12,\n 14, 16, 18;\n\n chemkit::StaticMatrix<int, 3, 3> d = c.multiply(-1);\n QCOMPARE(d(0, 0), -2);\n QCOMPARE(d(0, 1), -4);\n QCOMPARE(d(0, 2), -6);\n QCOMPARE(d(1, 0), -8);\n QCOMPARE(d(1, 1), -10);\n QCOMPARE(d(1, 2), -12);\n QCOMPARE(d(2, 0), -14);\n QCOMPARE(d(2, 1), -16);\n QCOMPARE(d(2, 2), -18);\n}\n\nvoid StaticMatrixTest::multiplyVector()\n{\n chemkit::StaticMatrix<double, 3, 3> a;\n a << 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9;\n\n chemkit::StaticVector<double, 3> p;\n p << 4, 0, -12;\n\n chemkit::StaticVector<double, 3> ap = a.multiply(p);\n QCOMPARE(qRound(ap[0]), -32);\n QCOMPARE(qRound(ap[1]), -56);\n QCOMPARE(qRound(ap[2]), -80);\n\n a << -10, 15, 20,\n 0, 3, 9,\n 1, 2, 8;\n p << 5, 1, 9;\n ap = a.multiply(p);\n QCOMPARE(qRound(ap[0]), 145);\n QCOMPARE(qRound(ap[1]), 84);\n QCOMPARE(qRound(ap[2]), 79);\n}\n\nvoid StaticMatrixTest::determinant()\n{\n \/\/ 3x3 matrix filled with 2's\n chemkit::StaticMatrix<chemkit::Float, 3, 3> matrix3;\n matrix3.fill(2);\n QCOMPARE(qRound(matrix3.determinant()), 0);\n\n \/\/ another matrix\n matrix3.fill(0);\n matrix3(0, 0) = 6;\n matrix3(0, 1) = 3;\n matrix3(0, 2) = 2;\n matrix3(1, 0) = 4;\n matrix3(1, 1) = -3;\n matrix3(1, 2) = 2;\n matrix3(2, 0) = -1;\n matrix3(2, 1) = 9;\n matrix3(2, 2) = -2;\n QCOMPARE(qRound(matrix3.determinant()), 12);\n\n \/\/ change last row\n matrix3(2, 0) = 0;\n matrix3(2, 1) = 4;\n matrix3(2, 2) = 0;\n QCOMPARE(qRound(matrix3.determinant()), -16);\n\n \/\/ change first row\n matrix3(0, 0) = 0;\n matrix3(0, 1) = 4;\n matrix3(0, 2) = 0;\n QCOMPARE(qRound(matrix3.determinant()), 0);\n}\n\nvoid StaticMatrixTest::invert()\n{\n chemkit::StaticMatrix<chemkit::Float, 3, 3> matrix3;\n matrix3(0, 0) = 1;\n matrix3(0, 1) = 2;\n matrix3(0, 2) = 3;\n matrix3(1, 0) = 0;\n matrix3(1, 1) = 1;\n matrix3(1, 2) = 0;\n matrix3(2, 0) = 4;\n matrix3(2, 1) = 0;\n matrix3(2, 2) = 4;\n\n chemkit::StaticMatrix<chemkit::Float, 3, 3> inverse3 = matrix3.inverted();\n QCOMPARE(inverse3(0, 0), chemkit::Float(-0.5));\n QCOMPARE(inverse3(0, 1), chemkit::Float(1.0));\n QCOMPARE(inverse3(0, 2), chemkit::Float(0.375));\n QCOMPARE(inverse3(1, 0), chemkit::Float(0.0));\n QCOMPARE(inverse3(1, 1), chemkit::Float(1.0));\n QCOMPARE(inverse3(1, 2), chemkit::Float(0.0));\n QCOMPARE(inverse3(2, 0), chemkit::Float(0.5));\n QCOMPARE(inverse3(2, 1), chemkit::Float(-1.0));\n QCOMPARE(inverse3(2, 2), chemkit::Float(-0.125));\n}\n\nQTEST_APPLESS_MAIN(StaticMatrixTest)\n#include \"staticmatrixtest.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: plocroot.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: np $ $Date: 2002-03-08 14:25:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CSV_PLOCROOT_HXX\n#define CSV_PLOCROOT_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n#include <cosv\/string.hxx>\n \/\/ PARAMETERS\n#include <cosv\/csv_ostream.hxx>\n#include <cosv\/persist.hxx>\n\n\nnamespace csv\n{\n\nclass bostream;\n\n\nnamespace ploc\n{\n\n\nclass Root\n{\n public:\n virtual ~Root();\n\n static DYN Root * Create_(\n const char * & o_sPathAfterRoot,\n const char * i_sPath,\n const char * i_sDelimiter = Delimiter() );\n\n virtual void Get( \/\/\/ Does not add a '\\0' at the end,\n ostream & o_rPath ) const = 0;\n virtual void Get( \/\/\/ Does not add a '\\0' at the end.\n bostream & so_rPath ) const = 0;\n virtual DYN Root * CreateCopy() const = 0;\n virtual const char *\n OwnDelimiter() const = 0;\n};\n\n\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n\n#endif\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.118); FILE MERGED 2005\/09\/05 14:08:52 rt 1.1.1.1.118.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: plocroot.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:56:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef CSV_PLOCROOT_HXX\n#define CSV_PLOCROOT_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ COMPONENTS\n#include <cosv\/string.hxx>\n \/\/ PARAMETERS\n#include <cosv\/csv_ostream.hxx>\n#include <cosv\/persist.hxx>\n\n\nnamespace csv\n{\n\nclass bostream;\n\n\nnamespace ploc\n{\n\n\nclass Root\n{\n public:\n virtual ~Root();\n\n static DYN Root * Create_(\n const char * & o_sPathAfterRoot,\n const char * i_sPath,\n const char * i_sDelimiter = Delimiter() );\n\n virtual void Get( \/\/\/ Does not add a '\\0' at the end,\n ostream & o_rPath ) const = 0;\n virtual void Get( \/\/\/ Does not add a '\\0' at the end.\n bostream & so_rPath ) const = 0;\n virtual DYN Root * CreateCopy() const = 0;\n virtual const char *\n OwnDelimiter() const = 0;\n};\n\n\n\n} \/\/ namespace ploc\n} \/\/ namespace csv\n\n\n\n#endif\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/** \\file EmailSender.cc\n * \\brief Utility functions etc. related to the sending of email messages.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n * \\author Artur Kedzierski\n * \\author Dr. Gordon W. Paynter\n *\n * \\copyright 2015 Universitätsbibliothek Tübingen.\n * \\copyright 2002-2008 Project iVia.\n * \\copyright 2002-2008 The Regents of The University of California.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"EmailSender.h\"\n#include <iostream>\n#include <memory>\n#include <list>\n#include <stdexcept>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DnsUtil.h\"\n#include \"FileDescriptor.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"SocketUtil.h\"\n#include \"SslConnection.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n \n\/\/ GetDateInRFC822Format() -- returns current date and time in an RFC-822 compliant format.\n\/\/\nstd::string GetDateInRFC822Format() {\n const time_t now(std::time(nullptr));\n\n \/\/ Convert struct time to an RFC-822 formatted string:\n char date_string[100 + 1];\n std::strftime(date_string, sizeof(date_string), \"%a, %e %b %Y %H:%M:%S %z\", std::localtime(&now));\n\n return date_string;\n}\n\n\nstatic std::string smtp_server;\n\n\nstd::string GetSmtpServer() {\n if (smtp_server.empty()) {\n IniFile ini_file(\"\/usr\/local\/var\/lib\/tuelib\/cronjobs\/smtp_server.conf\");\n smtp_server = ini_file.getString(\"SMTPServer\", \"server_address\");\n }\n\n return smtp_server;\n}\n\n\nvoid WriteToConnection(const int socket_fd, const TimeLimit &time_limit, const std::string &data,\n SslConnection * const ssl_connection)\n{\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, data, ssl_connection) == -1))\n throw std::runtime_error(\"in WriteToConnection(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \"))\");\n}\n\n\nstd::string GetDotStuffedMessage(const std::string &message) {\n std::list<std::string> lines;\n StringUtil::SplitThenTrim(message, \"\\n\", \"\\r\", &lines, \/* suppress_empty_words = *\/ false);\n for (std::list<std::string>::iterator line(lines.begin()); line != lines.end(); ++line) {\n if (*line == \".\")\n *line = \".\" + *line;\n }\n\n std::string dot_stuffed_message(message);\n StringUtil::Join(lines, \"\\r\\n\", &dot_stuffed_message);\n\n return dot_stuffed_message;\n}\n\n\nstd::string CreateEmailMessage(const EmailSender::Priority priority, const EmailSender::Format format,\n const std::string &sender, const std::string &recipient, const std::string &subject,\n const std::string &message_body, const std::string &cc = \"\")\n{\n std::string message;\n message = \"Date: \" + GetDateInRFC822Format() + \"\\r\\n\";\n message += \"From: \" + sender + \"\\r\\n\";\n message += \"To: \" + recipient + \"\\r\\n\";\n if (not cc.empty())\n message += \"Cc: \" + cc + \"\\r\\n\";\n message += \"Subject: \" + subject + \"\\r\\n\\r\\n\";\n if (format == EmailSender::PLAIN_TEXT)\n message += \"Content-Type: text\/plain; charset=\\\"utf-8\\\"\";\n else\n message += \"Content-Type: text\/html; charset=\\\"utf-8\\\"\";\n if (priority != EmailSender::DO_NOT_SET_PRIORITY)\n message += \"X-Priority: \" + std::to_string(priority) + \"\\r\\n\\r\\n\";\n message += GetDotStuffedMessage(message_body) + \".\\r\\n\";\n\n return message;\n}\n\n\n} \/\/ unnamed namespace\n\n\nnamespace EmailSender {\n\n\nbool SendEmail(const std::string &sender, const std::string &recipient, const std::string &subject,\n const std::string &message_body, const Priority priority, const Format format,\n const std::string &reply_to, const bool use_ssl)\n{\n if (unlikely(sender.empty() and reply_to.empty()))\n Error(\"in EmailSender::SendEmail: both \\\"sender\\\" and \\\"reply_to\\\" can't be empty!\");\n\n const TimeLimit time_limit(10000 \/* ms *\/);\n\n const bool log(not MiscUtil::SafeGetEnv(\"ENABLE_SMPT_CLIENT_LOGGING\").empty());\n\n \/\/ Open connection:\n const unsigned short PORT(use_ssl ? 587 : 25);\n std::string error_message;\n const FileDescriptor socket_fd(\n SocketUtil::TcpConnect(GetSmtpServer(), PORT, time_limit, &error_message, SocketUtil::DISABLE_NAGLE));\n if (socket_fd == -1) {\n Warning(\"in EmailSender::SendEmail: can't connect to SMTP server \\\"\" + GetSmtpServer() + \":\"\n + std::to_string(PORT) + \" (\" + error_message + \")!\");\n return false;\n }\n\n std::unique_ptr<SslConnection> ssl_connection;\n if (use_ssl)\n ssl_connection.reset(new SslConnection(socket_fd));\n\n \/\/ Read the welcome message:\n char buf[1000];\n ssize_t response_size;\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) {\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's welcome message!\");\n return false;\n }\n if (log) {\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n std::clog << \"Sever sent: \" << buf << '\\n';\n } \n\n \/\/ HELO <hostname>\n WriteToConnection(socket_fd, time_limit, \"HELO \" + DnsUtil::GetHostname() + \"\\r\\n\", ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to HELO!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"HELO\\\" command: \" + std::string(buf));\n return false;\n }\n\n \/\/ MAIL FROM: <email address of sender>\n WriteToConnection(socket_fd, time_limit, \"MAIL FROM:<\" + sender + \">\\r\\n\", ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to MAIL FROM:!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"MAIL FROM:\\\" command: \"\n + std::string(buf));\n return false;\n }\n\n \/\/ Send email to each recipient:\n const std::list<std::string> receiver_email_address_list{ recipient };\n for (std::list<std::string>::const_iterator receiver_email_address(receiver_email_address_list.begin());\n receiver_email_address != receiver_email_address_list.end(); ++receiver_email_address)\n {\n \/\/ RCPT TO: <email address of receiver>\n WriteToConnection(socket_fd, time_limit, \"RCPT TO:<\" + *receiver_email_address + \">\\r\\n\", ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to RCPT TO:!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"RCPT TO:\\\" command: \"\n + std::string(buf));\n return false;\n }\n }\n\n \/\/ DATA\n WriteToConnection(socket_fd, time_limit, \"DATA\\r\\n\", ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf))) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to DATA!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 3xx code:\n if (not StringUtil::Match(\"3[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"DATA\\\" command: \" + std::string(buf));\n return false;\n }\n\n \/\/ <data terminated by \".\" on a line by itself>\n WriteToConnection(socket_fd, time_limit,\n CreateEmailMessage(priority, format, sender, recipient, subject, message_body) + \"\\r\\n.\\r\\n\",\n ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to sent data!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to sent data: \" + std::string(buf));\n return false;\n }\n\n \/\/ QUIT\n WriteToConnection(socket_fd, time_limit, \"QUIT\\r\\n\", ssl_connection.get());\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf))) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to QUIT!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = '\\0';\n \/\/ Expect a 2xx code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"QUIT\\\" command: \" + std::string(buf));\n return false;\n }\n \n return true;\n}\n\n\n} \/\/ namespace EmailSender\n<commit_msg>Refactored a lot of code.<commit_after>\/** \\file EmailSender.cc\n * \\brief Utility functions etc. related to the sending of email messages.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n * \\author Artur Kedzierski\n * \\author Dr. Gordon W. Paynter\n *\n * \\copyright 2015 Universitätsbibliothek Tübingen.\n * \\copyright 2002-2008 Project iVia.\n * \\copyright 2002-2008 The Regents of The University of California.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"EmailSender.h\"\n#include <iostream>\n#include <memory>\n#include <list>\n#include <stdexcept>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DnsUtil.h\"\n#include \"FileDescriptor.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"SocketUtil.h\"\n#include \"SslConnection.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\n#define NUL '\\0'\n\n\nnamespace {\n\n\n\/\/ GetDateInRFC822Format() -- returns current date and time in an RFC-822 compliant format.\n\/\/\nstd::string GetDateInRFC822Format() {\n const time_t now(std::time(nullptr));\n\n \/\/ Convert struct time to an RFC-822 formatted string:\n char date_string[100 + 1];\n std::strftime(date_string, sizeof(date_string), \"%a, %e %b %Y %H:%M:%S %z\", std::localtime(&now));\n\n return date_string;\n}\n\n\nstatic std::string smtp_server;\n\n\nstd::string GetSmtpServer() {\n if (smtp_server.empty()) {\n IniFile ini_file(\"\/usr\/local\/var\/lib\/tuelib\/cronjobs\/smtp_server.conf\");\n smtp_server = ini_file.getString(\"SMTPServer\", \"server_address\");\n }\n\n return smtp_server;\n}\n\n\nstd::string GetDotStuffedMessage(const std::string &message) {\n std::list<std::string> lines;\n StringUtil::SplitThenTrim(message, \"\\n\", \"\\r\", &lines, \/* suppress_empty_words = *\/ false);\n for (auto &line : lines) {\n if (line == \".\")\n line = \".\" + line;\n }\n\n std::string dot_stuffed_message(message);\n StringUtil::Join(lines, \"\\r\\n\", &dot_stuffed_message);\n\n return dot_stuffed_message;\n}\n\n\nstd::string CreateEmailMessage(const EmailSender::Priority priority, const EmailSender::Format format,\n const std::string &sender, const std::string &recipient, const std::string &subject,\n const std::string &message_body, const std::string &cc = \"\")\n{\n std::string message;\n message = \"Date: \" + GetDateInRFC822Format() + \"\\r\\n\";\n message += \"From: \" + sender + \"\\r\\n\";\n message += \"To: \" + recipient + \"\\r\\n\";\n if (not cc.empty())\n message += \"Cc: \" + cc + \"\\r\\n\";\n message += \"Subject: \" + subject + \"\\r\\n\\r\\n\";\n if (format == EmailSender::PLAIN_TEXT)\n message += \"Content-Type: text\/plain; charset=\\\"utf-8\\\"\";\n else\n message += \"Content-Type: text\/html; charset=\\\"utf-8\\\"\";\n if (priority != EmailSender::DO_NOT_SET_PRIORITY)\n message += \"X-Priority: \" + std::to_string(priority) + \"\\r\\n\\r\\n\";\n message += GetDotStuffedMessage(message_body) + \".\\r\\n\";\n\n return message;\n}\n\n\nbool PerformHeloExchange(const int socket_fd, const TimeLimit &time_limit, SslConnection * const ssl_connection) {\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, \"HELO \" + DnsUtil::GetHostname() + \"\\r\\n\",\n ssl_connection) == -1))\n throw std::runtime_error(\"in PerformHeloExchange(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \"))\");\n\n \/\/ Read the response:\n ssize_t response_size;\n char buf[1000];\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection)) <= 0) {\n Warning(\"in PerformHeloExchange(EmailSender.cc): Can't read SMTP server's response to HELO!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in PerformHeloExchange(SendEmail.cc): Bad status code in response to \\\"HELO\\\" command: \"\n + std::string(buf));\n return false;\n }\n\n return true;\n}\n\n\nbool PerformMailFromExchange(const int socket_fd, const std::string &sender_email_address,\n const TimeLimit &time_limit, SslConnection * const ssl_connection)\n{\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, \"MAIL FROM:<\" + sender_email_address + \"\\r\\n\",\n ssl_connection) == -1))\n throw std::runtime_error(\"in PerformMailFromExchange(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \"))\");\n\n \/\/ Read the response:\n ssize_t response_size;\n char buf[1000];\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection)) <= 0) {\n Warning(\"in PerformMailFromExchange(EmailSender.cc): Can't read SMTP server's response to MAIL FROM:!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in PerformMailFromExchange(EmailSender.cc): Bad status code in response to \\\"MAIL FROM:\\\" command: \"\n + std::string(buf));\n return false;\n }\n\n return true;\n}\n\n\nbool PerformReceipientToExchange(const int socket_fd, const std::string &receiver_email_address,\n const TimeLimit &time_limit, SslConnection * const ssl_connection)\n{\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, \"MAIL FROM:<\" + receiver_email_address + \"\\r\\n\",\n ssl_connection) == -1))\n throw std::runtime_error(\"in PerformReceipientToExchange(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \"))\");\n\n \/\/ Read the response:\n ssize_t response_size;\n char buf[1000];\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection)) <= 0) {\n Warning(\"in PerformReceipientToExchange(EmailSender.cc): Can't read SMTP server's response to MAIL FROM:!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in PerformReceipientToExchange(EmailSender.cc): Bad status code in response to \\\"RCPT TO:\\\" \"\n \"command: \" + std::string(buf));\n return false;\n }\n\n return true;\n}\n\n\nbool ProcessSendEmailExchange(const int socket_fd, const EmailSender::Priority priority,\n const EmailSender::Format format, const std::string &sender,\n const std::string &recipient, const std::string &subject,\n const std::string &message_body, const TimeLimit &time_limit,\n SslConnection * const ssl_connection)\n{\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, \"DATA\\r\\n\", ssl_connection) == -1))\n throw std::runtime_error(\"in ProcessSendEmailExchange(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \")) (1)\");\n\n char buf[1000];\n ssize_t response_size;\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf))) <= 0) { \/\/ read the response\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's response to DATA!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 3xx code:\n if (not StringUtil::Match(\"3[0-9][0-9]*\", buf)) {\n Warning(\"in EmailSender::SendEmail: Bad status code in response to \\\"DATA\\\" command: \" + std::string(buf));\n return false;\n }\n\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit,\n CreateEmailMessage(priority, format, sender, recipient, subject, message_body) + \"\\r\\n.\\r\\n\",\n ssl_connection) == -1))\n throw std::runtime_error(\"in ProcessSendEmailExchange(EmailSender.cc): SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \")) (2)\");\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection)) <= 0) {\n Warning(\"in ProcessSendEmailExchange(EmailSender.cc): Can't read SMTP server's response to sent data!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in ProcessSendEmailExchange(EmailSender.cc): Bad status code in response to sent data: \"\n + std::string(buf));\n return false;\n }\n\n return true;\n}\n\n\nbool PerformQuitExchange(const int socket_fd, const TimeLimit &time_limit, SslConnection * const ssl_connection) {\n if (unlikely(SocketUtil::TimedWrite(socket_fd, time_limit, \"QUIT\\r\\n\",\n ssl_connection) == -1))\n throw std::runtime_error(\"in PerformQuitExchange(EmailSender.cc) SocketUtil::TimedWrite failed! (\"\n + std::string(strerror(errno)) + \"))\");\n\n \/\/ Read the response:\n ssize_t response_size;\n char buf[1000];\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection)) <= 0) {\n Warning(\"in PerformQuitExchange(EmailSender.cc): Can't read SMTP server's response to QUIT!\");\n return false;\n }\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n \/\/ Expect a 2xx success code:\n if (not StringUtil::Match(\"2[0-9][0-9]*\", buf)) {\n Warning(\"in PerformQuitExchange(SendEmail.cc): Bad status code in response to \\\"QUIT\\\" command: \"\n + std::string(buf));\n return false;\n }\n\n return true;\n}\n\n\n} \/\/ unnamed namespace\n\n\nnamespace EmailSender {\n\n\nbool SendEmail(const std::string &sender, const std::string &recipient, const std::string &subject,\n const std::string &message_body, const Priority priority, const Format format,\n const std::string &reply_to, const bool use_ssl)\n{\n if (unlikely(sender.empty() and reply_to.empty()))\n Error(\"in EmailSender::SendEmail: both \\\"sender\\\" and \\\"reply_to\\\" can't be empty!\");\n\n const TimeLimit time_limit(10000 \/* ms *\/);\n\n const bool log(not MiscUtil::SafeGetEnv(\"ENABLE_SMPT_CLIENT_LOGGING\").empty());\n\n \/\/ Open connection:\n const unsigned short PORT(use_ssl ? 587 : 25);\n std::string error_message;\n const FileDescriptor socket_fd(\n SocketUtil::TcpConnect(GetSmtpServer(), PORT, time_limit, &error_message, SocketUtil::DISABLE_NAGLE));\n if (socket_fd == -1) {\n Warning(\"in EmailSender::SendEmail: can't connect to SMTP server \\\"\" + GetSmtpServer() + \":\"\n + std::to_string(PORT) + \" (\" + error_message + \")!\");\n return false;\n }\n\n std::unique_ptr<SslConnection> ssl_connection;\n if (use_ssl)\n ssl_connection.reset(new SslConnection(socket_fd));\n\n \/\/ Read the welcome message:\n char buf[1000];\n ssize_t response_size;\n if ((response_size = SocketUtil::TimedRead(socket_fd, time_limit, buf, sizeof(buf), ssl_connection.get())) <= 0) {\n Warning(\"in EmailSender::SendEmail: Can't read SMTP server's welcome message!\");\n return false;\n }\n if (log) {\n buf[std::min(static_cast<size_t>(response_size), sizeof(buf) - 1)] = NUL;\n std::clog << \"Sever sent: \" << buf << '\\n';\n }\n\n if (not PerformHeloExchange(socket_fd, time_limit, ssl_connection.get()))\n return false;\n\n if (not PerformMailFromExchange(socket_fd, sender, time_limit, ssl_connection.get()))\n return false;\n\n \/\/ Send email to each recipient:\n const std::list<std::string> receiver_email_address_list{ recipient };\n for (const auto &receiver_email_address : receiver_email_address_list) {\n if (not PerformReceipientToExchange(socket_fd, receiver_email_address, time_limit, ssl_connection.get()))\n return false;\n }\n\n if (not ProcessSendEmailExchange(socket_fd, priority, format, sender, recipient, subject, message_body,\n time_limit, ssl_connection.get()))\n return false;\n\n if (not PerformQuitExchange(socket_fd, time_limit, ssl_connection.get()))\n return false;\n\n return true;\n}\n\n\n} \/\/ namespace EmailSender\n<|endoftext|>"} {"text":"<commit_before>#ifndef __EXTENSION_INTERACTIVE_STRATEGY_HPP\n#define __EXTENSION_INTERACTIVE_STRATEGY_HPP\n\n#include <boost\/algorithm\/string.hpp>\n\n\n\/**\n * A class that opens an interactive shell to allow examining the property of strategies computed\n *\n *\/\ntemplate<class T> class XInteractiveStrategy : public T {\nprotected:\n XInteractiveStrategy<T>(std::list<std::string> &filenames) : T(filenames) {}\n\n using T::checkRealizability;\n using T::realizable;\n using T::variables;\n using T::variableNames;\n using T::variableTypes;\n using T::mgr;\n using T::winningPositions;\n using T::livenessAssumptions;\n using T::livenessGuarantees;\n using T::safetyEnv;\n using T::safetySys;\n using T::strategyDumpingData;\n using T::varCubePostOutput;\n using T::postOutputVars;\n using T::determinize;\n\npublic:\n static GR1Context* makeInstance(std::list<std::string> &filenames) {\n return new XInteractiveStrategy<T>(filenames);\n }\n\n void execute() {\n checkRealizability();\n\n std::vector<BF> positionalStrategiesForTheIndividualGoals(livenessGuarantees.size());\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n BF casesCovered = mgr.constantFalse();\n BF strategy = mgr.constantFalse();\n for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) {\n if (it->first == i) {\n BF newCases = it->second.ExistAbstract(varCubePostOutput) & !casesCovered;\n strategy |= newCases & it->second;\n casesCovered |= newCases;\n }\n }\n positionalStrategiesForTheIndividualGoals[i] = strategy;\n \/\/BF_newDumpDot(*this,strategy,\"PreInput PreOutput PostInput PostOutput\",\"\/tmp\/generalStrategy.dot\");\n }\n\n if (realizable) {\n\n BF currentPosition = mgr.constantFalse();\n\n while(true) {\n\n \/\/ The prompt\n std::cout << \"> \";\n std::cout.flush();\n std::string command;\n std::getline(std::cin,command);\n\n \/\/ Check the command\n boost::trim(command);\n boost::to_upper(command);\n\n if ((command==\"QUIT\") || (command==\"EXIT\")) {\n return;\n } else if (command==\"CHECKTRANS\") {\n\n std::cout << \"From: \\n\";\n BF from = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PreInput) || (variableTypes[i]==PreOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n\n std::cout << \"To: \\n\";\n BF to = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostInput) || (variableTypes[i]==PostOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n\n std::cout << \"Result: \\n\";\n if ((from & winningPositions).isFalse()) {\n std::cout << \"- The pre-position is not winning.\\n\";\n } else {\n std::cout << \"- The pre-position is winning.\\n\";\n }\n if ((from & to & safetyEnv).isFalse()) {\n std::cout << \"- The transition VIOLATES the SAFETY ASSUMPTIONS\\n\";\n } else {\n std::cout << \"- The transition SATISFIES the SAFETY ASSUMPTIONS\\n\";\n }\n if ((from & to & safetySys).isFalse()) {\n std::cout << \"- The transition VIOLATES the SAFETY GUARANTEES\\n\";\n } else {\n std::cout << \"- The transition SATISFIES the SAFETY GUARANTEES\\n\";\n }\n std::cout << \"- The transition is a goal transition for the following liveness assumptions: \";\n bool foundOne = false;\n for (uint i=0;i<livenessAssumptions.size();i++) {\n if (!(livenessAssumptions[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n std::cout << \"- The transition is a goal transition for the following liveness guarantees: \";\n foundOne = false;\n for (uint i=0;i<livenessGuarantees.size();i++) {\n if (!(livenessGuarantees[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n \/\/ Analyse if it is part of a possible strategy\n std::cout << \"- The transition is a possible transition in a strategy for the following goals: \";\n foundOne = false;\n for (uint i=0;i<livenessGuarantees.size();i++) {\n if (!(positionalStrategiesForTheIndividualGoals[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n } else if (command==\"SETPOS\") {\n\n std::cout << \"Position: \\n\";\n BF from = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PreInput) || (variableTypes[i]==PreOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n currentPosition = from;\n } else if (command==\"MOVE\") {\n\n std::cout << \"Guarantee No.: \";\n std::cout.flush();\n unsigned int guarantee;\n std::cin >> guarantee;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Aborting \\n\";\n } else if (guarantee>=livenessGuarantees.size()) {\n std::cout << \" -> Number too large. Aborting \\n\";\n } else {\n\n BF allowedInputs = (currentPosition & safetyEnv);\n BF_newDumpDot(*this,allowedInputs,NULL,\"\/tmp\/allowedInputs.dot\");\n\n std::cout << \"To: \\n\";\n BF to = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostInput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n to &= !variables[i];\n } else if (value==1) {\n to &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n to &= variables[i];\n }\n }\n }\n\n BF transition = currentPosition & to & positionalStrategiesForTheIndividualGoals[guarantee];\n\n if (transition.isFalse()) {\n std::cout << \" -> Error: Input not allowed here.\\n\";\n if (!(currentPosition & to & safetyEnv).isFalse()) {\n std::cout << \" -> Actually, that's an internal error!\\n\";\n }\n } else {\n\n transition = determinize(transition,postOutputVars);\n\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostOutput)) {\n if ((variables[i] & transition).isFalse()) {\n std::cout << \" - \" << variableNames[i] << \" = 0\\n\";\n } else {\n std::cout << \" - \" << variableNames[i] << \" = 1\\n\";\n }\n }\n }\n\n std::cout << \"- The transition is a goal transition for the following liveness assumptions: \";\n bool foundOne = false;\n for (uint i=0;i<livenessAssumptions.size();i++) {\n if (!(livenessAssumptions[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n std::cout << \"- The transition is a goal transition for the following liveness guarantees: \";\n foundOne = false;\n for (uint i=0;i<livenessGuarantees.size();i++) {\n if (!(livenessGuarantees[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n \/\/ Analyse if it is part of a possible strategy\n std::cout << \"- The transition is a possible transition in a strategy for the following goals: \";\n foundOne = false;\n for (uint i=0;i<livenessGuarantees.size();i++) {\n if (!(positionalStrategiesForTheIndividualGoals[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n }\n }\n\n\n\n\n\n }\n }\n\n }\n\n }\n\n\n};\n\n\n#endif\n<commit_msg>uint to unsigned int<commit_after>#ifndef __EXTENSION_INTERACTIVE_STRATEGY_HPP\n#define __EXTENSION_INTERACTIVE_STRATEGY_HPP\n\n#include <boost\/algorithm\/string.hpp>\n\n\n\/**\n * A class that opens an interactive shell to allow examining the property of strategies computed\n *\n *\/\ntemplate<class T> class XInteractiveStrategy : public T {\nprotected:\n XInteractiveStrategy<T>(std::list<std::string> &filenames) : T(filenames) {}\n\n using T::checkRealizability;\n using T::realizable;\n using T::variables;\n using T::variableNames;\n using T::variableTypes;\n using T::mgr;\n using T::winningPositions;\n using T::livenessAssumptions;\n using T::livenessGuarantees;\n using T::safetyEnv;\n using T::safetySys;\n using T::strategyDumpingData;\n using T::varCubePostOutput;\n using T::postOutputVars;\n using T::determinize;\n\npublic:\n static GR1Context* makeInstance(std::list<std::string> &filenames) {\n return new XInteractiveStrategy<T>(filenames);\n }\n\n void execute() {\n checkRealizability();\n\n std::vector<BF> positionalStrategiesForTheIndividualGoals(livenessGuarantees.size());\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n BF casesCovered = mgr.constantFalse();\n BF strategy = mgr.constantFalse();\n for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) {\n if (it->first == i) {\n BF newCases = it->second.ExistAbstract(varCubePostOutput) & !casesCovered;\n strategy |= newCases & it->second;\n casesCovered |= newCases;\n }\n }\n positionalStrategiesForTheIndividualGoals[i] = strategy;\n \/\/BF_newDumpDot(*this,strategy,\"PreInput PreOutput PostInput PostOutput\",\"\/tmp\/generalStrategy.dot\");\n }\n\n if (realizable) {\n\n BF currentPosition = mgr.constantFalse();\n\n while(true) {\n\n \/\/ The prompt\n std::cout << \"> \";\n std::cout.flush();\n std::string command;\n std::getline(std::cin,command);\n\n \/\/ Check the command\n boost::trim(command);\n boost::to_upper(command);\n\n if ((command==\"QUIT\") || (command==\"EXIT\")) {\n return;\n } else if (command==\"CHECKTRANS\") {\n\n std::cout << \"From: \\n\";\n BF from = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PreInput) || (variableTypes[i]==PreOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n\n std::cout << \"To: \\n\";\n BF to = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostInput) || (variableTypes[i]==PostOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n\n std::cout << \"Result: \\n\";\n if ((from & winningPositions).isFalse()) {\n std::cout << \"- The pre-position is not winning.\\n\";\n } else {\n std::cout << \"- The pre-position is winning.\\n\";\n }\n if ((from & to & safetyEnv).isFalse()) {\n std::cout << \"- The transition VIOLATES the SAFETY ASSUMPTIONS\\n\";\n } else {\n std::cout << \"- The transition SATISFIES the SAFETY ASSUMPTIONS\\n\";\n }\n if ((from & to & safetySys).isFalse()) {\n std::cout << \"- The transition VIOLATES the SAFETY GUARANTEES\\n\";\n } else {\n std::cout << \"- The transition SATISFIES the SAFETY GUARANTEES\\n\";\n }\n std::cout << \"- The transition is a goal transition for the following liveness assumptions: \";\n bool foundOne = false;\n for (unsigned int i=0;i<livenessAssumptions.size();i++) {\n if (!(livenessAssumptions[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n std::cout << \"- The transition is a goal transition for the following liveness guarantees: \";\n foundOne = false;\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n if (!(livenessGuarantees[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n \/\/ Analyse if it is part of a possible strategy\n std::cout << \"- The transition is a possible transition in a strategy for the following goals: \";\n foundOne = false;\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n if (!(positionalStrategiesForTheIndividualGoals[i] & from & to).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n } else if (command==\"SETPOS\") {\n\n std::cout << \"Position: \\n\";\n BF from = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PreInput) || (variableTypes[i]==PreOutput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n from &= !variables[i];\n } else if (value==1) {\n from &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n from &= variables[i];\n }\n }\n }\n currentPosition = from;\n } else if (command==\"MOVE\") {\n\n std::cout << \"Guarantee No.: \";\n std::cout.flush();\n unsigned int guarantee;\n std::cin >> guarantee;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Aborting \\n\";\n } else if (guarantee>=livenessGuarantees.size()) {\n std::cout << \" -> Number too large. Aborting \\n\";\n } else {\n\n BF allowedInputs = (currentPosition & safetyEnv);\n BF_newDumpDot(*this,allowedInputs,NULL,\"\/tmp\/allowedInputs.dot\");\n\n std::cout << \"To: \\n\";\n BF to = mgr.constantTrue();\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostInput)) {\n std::cout << \" - \" << variableNames[i] << \": \";\n std::cout.flush();\n int value;\n std::cin >> value;\n if (std::cin.fail()) {\n std::cout << \" -> Error reading value. Assuming 0.\\n\";\n value = 0;\n }\n if (value==0) {\n to &= !variables[i];\n } else if (value==1) {\n to &= variables[i];\n } else {\n std::cout << \" -> Value != 0 or 1. Assuming 1.\\n\";\n to &= variables[i];\n }\n }\n }\n\n BF transition = currentPosition & to & positionalStrategiesForTheIndividualGoals[guarantee];\n\n if (transition.isFalse()) {\n std::cout << \" -> Error: Input not allowed here.\\n\";\n if (!(currentPosition & to & safetyEnv).isFalse()) {\n std::cout << \" -> Actually, that's an internal error!\\n\";\n }\n } else {\n\n transition = determinize(transition,postOutputVars);\n\n for (unsigned int i=0;i<variables.size();i++) {\n if ((variableTypes[i]==PostOutput)) {\n if ((variables[i] & transition).isFalse()) {\n std::cout << \" - \" << variableNames[i] << \" = 0\\n\";\n } else {\n std::cout << \" - \" << variableNames[i] << \" = 1\\n\";\n }\n }\n }\n\n std::cout << \"- The transition is a goal transition for the following liveness assumptions: \";\n bool foundOne = false;\n for (unsigned int i=0;i<livenessAssumptions.size();i++) {\n if (!(livenessAssumptions[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n std::cout << \"- The transition is a goal transition for the following liveness guarantees: \";\n foundOne = false;\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n if (!(livenessGuarantees[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n \/\/ Analyse if it is part of a possible strategy\n std::cout << \"- The transition is a possible transition in a strategy for the following goals: \";\n foundOne = false;\n for (unsigned int i=0;i<livenessGuarantees.size();i++) {\n if (!(positionalStrategiesForTheIndividualGoals[i] & transition).isFalse()) {\n if (foundOne) std::cout << \", \";\n foundOne = true;\n std::cout << i;\n }\n }\n if (!foundOne) std::cout << \"none\";\n std::cout << std::endl;\n\n }\n }\n\n\n\n\n\n }\n }\n\n }\n\n }\n\n\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"World.h\"\n#include \"Hatchery.h\"\n\nHatchery::Hatchery(QWidget *parent) : QDialog(parent) {\n\tsetWindowTitle(tr(\"Hatchery\"));\n\tsetAttribute(Qt::WA_QuitOnClose, false);\n\n\tstd::string hatcherybgfile = world.findFile(\"hatchery\/hatchery.bmp\");\n\tif (hatcherybgfile.empty()) return;\n\tQPixmap hatcherybg(QString(hatcherybgfile.c_str()));\n\n\tresize(hatcherybg.width() + 6, hatcherybg.height() + 6);\n\t\n\tgraphicsScene = new QGraphicsScene();\n\tgraphicsView = new QGraphicsView(graphicsScene, this);\n\tQHBoxLayout *layout = new QHBoxLayout(this);\n\tlayout->addWidget(graphicsView);\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\t\n\tgraphicsScene->addPixmap(hatcherybg);\n}\n\nHatchery::~Hatchery() {\n}\n\n<commit_msg>Hatchery: add mask, comments<commit_after>\/*\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"World.h\"\n#include \"Hatchery.h\"\n\n\/*\n C1 hatchery resources:\n hatchery.bmp and htchmask.bmp used for the background\/foreground\n SCAN*.BMP and hdsk.wav used for egg disk animation\n EGG*.BMP and hegg.wav used for egg movement animation\n FAN*.BMP and hfan.wav used for the fan animation\n lightoff.bmp and hlgt.wav used for the light flickering\n GENSPIN.BMP, and hmle.wav\/hfml.wav used for male\/female animation (male.bmp and female.bmp also present)\n *\/\n\nHatchery::Hatchery(QWidget *parent) : QDialog(parent) {\n\tsetWindowTitle(tr(\"Hatchery\"));\n\tsetAttribute(Qt::WA_QuitOnClose, false);\n\n\t\/* hatchery background *\/\n\tstd::string hatcherybgfile = world.findFile(\"hatchery\/hatchery.bmp\");\n\tif (hatcherybgfile.empty()) return;\n\tQPixmap hatcherybg(QString(hatcherybgfile.c_str()));\n\n\tresize(hatcherybg.width() + 6, hatcherybg.height() + 6);\n\t\n\t\/* create the widgets\/layout *\/\n\tgraphicsScene = new QGraphicsScene();\n\tgraphicsView = new QGraphicsView(graphicsScene, this);\n\tQHBoxLayout *layout = new QHBoxLayout(this);\n\tlayout->addWidget(graphicsView);\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\t\n\tgraphicsScene->addPixmap(hatcherybg);\n\n\t\/* mask which goes over the eggs *\/\n\tstd::string hatcherymaskfile = world.findFile(\"hatchery\/htchmask.bmp\");\n\tif (hatcherymaskfile.size()) {\n\t\tQPixmap hatcherymask(QString(hatcherymaskfile.c_str()));\n\t\tQColor maskcolour(0xff, 0x00, 0x80);\n\t\thatcherymask.setMask(hatcherymask.createMaskFromColor(maskcolour));\n\t\n\t\tQGraphicsPixmapItem *maskitem = graphicsScene->addPixmap(hatcherymask);\n\t\tmaskitem->setPos(0, 168);\n\t}\n\n\t\/* fan animation *\/\n\tfor (unsigned int i = 0; i < 4; i++) {\n\t\t\/\/ TODO\n\t}\n\t\n\t\/* 'off' state for the light *\/\n\t\/\/ TODO\n\t\n\t\/* eggs *\/\n\t\/\/ TODO\n\t\n\t\/* gender marker animation *\/\n\t\/\/ TODO\n}\n\nHatchery::~Hatchery() {\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"std_incl.h\"\n#include \"ResultManager.h\"\n#include \"utils.h\"\n\nResultManager::ResultManager(const char *outfile, const char* frameInfoFile, ResultManagerConfig *cfg)\n{\n\tconfig = *cfg;\n\toutputFile = outfile;\n\tthis->frameInfoFile = frameInfoFile;\n\n\tstartFrame = 0;\n\tlastSaveFrame = 0;\n\tprocessedFrames = 0;\n\tcapturedFrames = 0;\n\tlocalizationsDone = 0;\n\n\tqtrk = 0;\n\n\tthread = Threads::Create(ThreadLoop, this);\n\tquit=false;\n\n\tremove(outfile);\n\tremove(frameInfoFile);\n\n\tif(config.binaryOutput) {\n\t\tFILE *f = fopen(outfile, \"w\");\n\t\tfwrite(&cfg->numBeads, sizeof(int), 1, f);\n\t\tfclose(f);\n\t}\n\n\tdbgprintf(\"Allocating ResultManager with %d beads and writeinterval %d\\n\", cfg->numBeads, cfg->writeInterval);\n}\n\nResultManager::~ResultManager()\n{\n\tquit = true;\n\tThreads::WaitAndClose(thread);\n\n\tDeleteAllElems(frameResults);\n}\n\n\nvoid ResultManager::StoreResult(LocalizationResult *r)\n{\n\tint index = r->job.frame - startFrame;\n\n\tif (index >= frameResults.size()) {\n\t\tdbgprintf(\"dropping result. Result provided for unregistered frame %d. Current frames registered: %d\\n\", \n\t\t\tr->job.frame, startFrame + frameResults.size());\n\t\treturn; \/\/ add errors?\n\t}\n\n\tLocalizationResult scaled = *r;\n\t\/\/ Make roi-centered pos\n\tscaled.pos = scaled.pos - vector3f( qtrk->cfg.width*0.5f, qtrk->cfg.height*0.5f, 0);\n\tscaled.pos = ( scaled.pos + config.offset ) * config.scaling;\n\tFrameResult* fr = frameResults[index];\n\tfr->results[r->job.zlutIndex] = scaled;\n\tfr->count++;\n\n\t\/\/ Advance fullFrames\n\tframeCountMutex.lock();\n\twhile (processedFrames - startFrame < frameResults.size() && frameResults[processedFrames-startFrame]->count == config.numBeads)\n\t\tprocessedFrames ++;\n\tlocalizationsDone ++;\n\tframeCountMutex.unlock();\n}\n\nvoid ResultManager::Write()\n{\n\tFILE* f = outputFile.empty () ? 0 : fopen(outputFile.c_str(), \"a\");\n\tFILE* finfo = frameInfoFile.empty() ? 0 : fopen(frameInfoFile.c_str(), \"a\");\n\t\n\tresultMutex.lock();\n\tif (config.binaryOutput) {\n\t\tfor (uint j=lastSaveFrame; j<processedFrames;j++)\n\t\t{\n\t\t\tauto fr = frameResults[j-startFrame];\n\t\t\tif (f) {\n\t\t\t\tfwrite(&j, sizeof(uint), 1, f);\n\t\t\t\tfwrite(&fr->timestamp, sizeof(double), 1, f);\n\t\t\t\tfor (int i=0;i<config.numBeads;i++) \n\t\t\t\t{\n\t\t\t\t\tLocalizationResult *r = &fr->results[i];\n\t\t\t\t\tfwrite(&r->pos, sizeof(vector3f), 1, f);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (finfo)\n\t\t\t\tfwrite(&fr->timestamp, sizeof(double), 1, finfo);\n\t\t}\n\t}\n\telse {\n\t\tfor (uint k=lastSaveFrame; k<processedFrames;k++)\n\t\t{\n\t\t\tauto fr = frameResults[k-startFrame];\n\t\t\tif (f) {\n\t\t\t\tfprintf(f,\"%d\\t%f\\t\", k, fr->timestamp);\n\t\t\t\tfor (int i=0;i<config.numBeads;i++) \n\t\t\t\t{\n\t\t\t\t\tLocalizationResult *r = &fr->results[i];\n\t\t\t\t\tfprintf(f, \"%.5f\\t%.5f\\t%.5f\\t\", r->pos.x,r->pos.y,r->pos.z);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", f);\n\t\t\t}\n\t\t\tif (finfo) {\n\t\t\t\tfprintf(finfo,\"%d\\t%f\\t\", k, fr->timestamp);\n\t\t\t\tfor (int i=0;i<config.numFrameInfoColumns;i++)\n\t\t\t\t\tfprintf(finfo, \"%.5f\\t\", fr->frameInfo[i]);\n\t\t\t\tfputs(\"\\n\", finfo);\n\t\t\t}\n\t\t}\n\t}\n\n\tdbgprintf(\"Saved frame %d to %d\\n\", lastSaveFrame, processedFrames);\n\n\tif(f) fclose(f);\n\tif(finfo) fclose(finfo);\n\tframeCountMutex.lock();\n\tlastSaveFrame = processedFrames;\n\tframeCountMutex.unlock();\n\n\tresultMutex.unlock();\n}\n\n\nvoid ResultManager::SetTracker(QueuedTracker *qtrk)\n{\n\ttrackerMutex.lock();\n\tthis->qtrk = qtrk;\n\ttrackerMutex.unlock();\n}\n\nbool ResultManager::Update()\n{\n\ttrackerMutex.lock();\n\n\tif (!qtrk) {\n\t\ttrackerMutex.unlock();\n\t\treturn 0;\n\t}\n\n\tconst int NResultBuf = 40;\n\tLocalizationResult resultbuf[NResultBuf];\n\n\tint count = qtrk->PollFinished( resultbuf, NResultBuf );\n\n\tresultMutex.lock();\n\tfor (int i=0;i<count;i++)\n\t\tStoreResult(&resultbuf[i]);\n\tresultMutex.unlock();\n\n\ttrackerMutex.unlock();\n\n\tif (processedFrames - lastSaveFrame >= config.writeInterval) {\n\t\tWrite();\n\t}\n\n\tif (config.maxFramesInMemory>0 && frameResults.size () > config.maxFramesInMemory) {\n\t\tint del = frameResults.size()-config.maxFramesInMemory;\n\t\tdbgprintf(\"Removing %d frames from memory\\n\", del);\n\t\t\n\t\tfor (int i=0;i<del;i++)\n\t\t\tdelete frameResults[i];\n\t\tframeResults.erase(frameResults.begin(), frameResults.begin()+del);\n\n\t\tframeCountMutex.lock();\n\t\tstartFrame += del;\n\t\tframeCountMutex.unlock();\n\t}\n\n\treturn count>0;\n}\n\nvoid ResultManager::ThreadLoop(void *param)\n{\n\tResultManager* rm = (ResultManager*)param;\n\n\twhile(true) {\n\t\tif (!rm->Update())\n\t\t\tThreads::Sleep(20);\n\n\t\tif (rm->quit)\n\t\t\tbreak;\n\t}\n}\n\nint ResultManager::GetBeadPositions(int startFrame, int endFrame, int bead, LocalizationResult* results)\n{\n\tframeCountMutex.lock();\n\tint start = startFrame - this->startFrame;\n\n\tif (endFrame > processedFrames)\n\t\tendFrame = processedFrames;\n\n\tint end = endFrame - this->startFrame;\n\tframeCountMutex.unlock();\n\n\tif (start < 0)\n\t\treturn 0;\n\n\tresultMutex.lock();\n\tfor (int i=start;i<end;i++){\n\t\tresults[i-start] = frameResults[i]->results[bead];\n\t}\n\tresultMutex.unlock();\n\n\treturn end-start;\n}\n\n\nvoid ResultManager::Flush()\n{\n\tWrite();\n\n\tresultMutex.lock();\n\n\t\/\/ Dump stats about unfinished frames for debugging\n\tfor (int i=0;i<frameResults.size();i++) {\n\t\tFrameResult *fr = frameResults[i];\n\t\tdbgprintf(\"Frame %d. TS: %f, Count: %d\\n\", i, fr->timestamp, fr->count);\n\t\tif (fr->count != config.numBeads) {\n\t\t\tfor (int j=0;j<fr->results.size();j++) {\n\t\t\t\tif( fr->results[j].job.locType == 0 )\n\t\t\t\t\tdbgprintf(\"%d, \", j );\n\t\t\t}\n\t\t\tdbgprintf(\"\\n\");\n\t\t}\n\t}\n\n\tresultMutex.unlock();\n}\n\n\nvoid ResultManager::GetFrameCounters(int* startFrame, int *processedFrames, int *lastSaveFrame, int *capturedFrames, int *localizationsDone)\n{\n\tframeCountMutex.lock();\n\tif (startFrame) *startFrame = this->startFrame;\n\tif (processedFrames) *processedFrames = this->processedFrames;\n\tif (lastSaveFrame) *lastSaveFrame = this->lastSaveFrame;\n\tif (localizationsDone) *localizationsDone = this->localizationsDone;\n\tframeCountMutex.unlock();\n\n\tif (capturedFrames) {\n\t\tresultMutex.lock();\n\t\t*capturedFrames = this->capturedFrames;\n\t\tresultMutex.unlock();\n\t}\n}\n\nint ResultManager::GetResults(LocalizationResult* results, int startFrame, int numFrames)\n{\n\tframeCountMutex.lock();\n\n\tif (startFrame >= this->startFrame && numFrames+startFrame <= processedFrames) {\n\t\tresultMutex.lock();\n\t\tfor (int f=0;f<numFrames;f++) {\n\t\t\tint index = f + startFrame - this->startFrame;\n\t\t\tfor (int j=0;j<config.numBeads;j++)\n\t\t\t\tresults[config.numBeads*f+j] = frameResults[index]->results[j];\n\t\t}\n\n\t\tresultMutex.unlock();\n\t}\n\tframeCountMutex.unlock();\n\n\treturn numFrames;\n}\n\n\nint ResultManager::StoreFrameInfo(double timestamp, float* columns)\n{\n\tresultMutex.lock();\n\tauto fr = new FrameResult( config.numBeads, config.numFrameInfoColumns);\n\tfr->timestamp = timestamp;\n\tfor(int i=0;i<config.numFrameInfoColumns;i++)\n\t\tfr->frameInfo[i]=columns[i];\n\tframeResults.push_back (fr);\n\tint nfr = ++capturedFrames;\n\tresultMutex.unlock();\n\treturn nfr;\n}\n\n\nint ResultManager::GetFrameCount()\n{\n\tresultMutex.lock();\n\tint nfr = capturedFrames;\n\tresultMutex.unlock();\n\treturn nfr;\n}\n\n<commit_msg>* return partial GetBeadPositions() if range is too large<commit_after>#include \"std_incl.h\"\n#include \"ResultManager.h\"\n#include \"utils.h\"\n\nResultManager::ResultManager(const char *outfile, const char* frameInfoFile, ResultManagerConfig *cfg)\n{\n\tconfig = *cfg;\n\toutputFile = outfile;\n\tthis->frameInfoFile = frameInfoFile;\n\n\tstartFrame = 0;\n\tlastSaveFrame = 0;\n\tprocessedFrames = 0;\n\tcapturedFrames = 0;\n\tlocalizationsDone = 0;\n\n\tqtrk = 0;\n\n\tthread = Threads::Create(ThreadLoop, this);\n\tquit=false;\n\n\tremove(outfile);\n\tremove(frameInfoFile);\n\n\tdbgprintf(\"Allocating ResultManager with %d beads and writeinterval %d\\n\", cfg->numBeads, cfg->writeInterval);\n}\n\nResultManager::~ResultManager()\n{\n\tquit = true;\n\tThreads::WaitAndClose(thread);\n\n\tDeleteAllElems(frameResults);\n}\n\n\nvoid ResultManager::StoreResult(LocalizationResult *r)\n{\n\tint index = r->job.frame - startFrame;\n\n\tif (index >= frameResults.size()) {\n\t\tdbgprintf(\"dropping result. Result provided for unregistered frame %d. Current frames registered: %d\\n\", \n\t\t\tr->job.frame, startFrame + frameResults.size());\n\t\treturn; \/\/ add errors?\n\t}\n\n\tLocalizationResult scaled = *r;\n\t\/\/ Make roi-centered pos\n\tscaled.pos = scaled.pos - vector3f( qtrk->cfg.width*0.5f, qtrk->cfg.height*0.5f, 0);\n\tscaled.pos = ( scaled.pos + config.offset ) * config.scaling;\n\tFrameResult* fr = frameResults[index];\n\tfr->results[r->job.zlutIndex] = scaled;\n\tfr->count++;\n\n\t\/\/ Advance fullFrames\n\tframeCountMutex.lock();\n\twhile (processedFrames - startFrame < frameResults.size() && frameResults[processedFrames-startFrame]->count == config.numBeads)\n\t\tprocessedFrames ++;\n\tlocalizationsDone ++;\n\tframeCountMutex.unlock();\n}\n\nvoid ResultManager::Write()\n{\n\tFILE* f = outputFile.empty () ? 0 : fopen(outputFile.c_str(), \"a\");\n\tFILE* finfo = frameInfoFile.empty() ? 0 : fopen(frameInfoFile.c_str(), \"a\");\n\t\n\tresultMutex.lock();\n\tif (config.binaryOutput) {\n\t\tif (lastSaveFrame == 0) {\n\t\t\tfwrite(&config.numBeads, sizeof(int), 1, f);\n\t\t\tdbgprintf(\"writing %d beads into file %s\\n\", config.numBeads, outputFile.c_str());\n\t\t}\n\n\t\tfor (uint j=lastSaveFrame; j<processedFrames;j++)\n\t\t{\n\t\t\tauto fr = frameResults[j-startFrame];\n\t\t\tif (f) {\n\t\t\t\tfwrite(&j, sizeof(uint), 1, f);\n\t\t\t\tfwrite(&fr->timestamp, sizeof(double), 1, f);\n\t\t\t\tfor (int i=0;i<config.numBeads;i++) \n\t\t\t\t{\n\t\t\t\t\tLocalizationResult *r = &fr->results[i];\n\t\t\t\t\tfwrite(&r->pos, sizeof(vector3f), 1, f);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (finfo)\n\t\t\t\tfwrite(&fr->timestamp, sizeof(double), 1, finfo);\n\t\t}\n\t}\n\telse {\n\t\tfor (uint k=lastSaveFrame; k<processedFrames;k++)\n\t\t{\n\t\t\tauto fr = frameResults[k-startFrame];\n\t\t\tif (f) {\n\t\t\t\tfprintf(f,\"%d\\t%f\\t\", k, fr->timestamp);\n\t\t\t\tfor (int i=0;i<config.numBeads;i++) \n\t\t\t\t{\n\t\t\t\t\tLocalizationResult *r = &fr->results[i];\n\t\t\t\t\tfprintf(f, \"%.5f\\t%.5f\\t%.5f\\t\", r->pos.x,r->pos.y,r->pos.z);\n\t\t\t\t}\n\t\t\t\tfputs(\"\\n\", f);\n\t\t\t}\n\t\t\tif (finfo) {\n\t\t\t\tfprintf(finfo,\"%d\\t%f\\t\", k, fr->timestamp);\n\t\t\t\tfor (int i=0;i<config.numFrameInfoColumns;i++)\n\t\t\t\t\tfprintf(finfo, \"%.5f\\t\", fr->frameInfo[i]);\n\t\t\t\tfputs(\"\\n\", finfo);\n\t\t\t}\n\t\t}\n\t}\n\n\tdbgprintf(\"Saved frame %d to %d\\n\", lastSaveFrame, processedFrames);\n\n\tif(f) fclose(f);\n\tif(finfo) fclose(finfo);\n\tframeCountMutex.lock();\n\tlastSaveFrame = processedFrames;\n\tframeCountMutex.unlock();\n\n\tresultMutex.unlock();\n}\n\n\nvoid ResultManager::SetTracker(QueuedTracker *qtrk)\n{\n\ttrackerMutex.lock();\n\tthis->qtrk = qtrk;\n\ttrackerMutex.unlock();\n}\n\nbool ResultManager::Update()\n{\n\ttrackerMutex.lock();\n\n\tif (!qtrk) {\n\t\ttrackerMutex.unlock();\n\t\treturn 0;\n\t}\n\n\tconst int NResultBuf = 40;\n\tLocalizationResult resultbuf[NResultBuf];\n\n\tint count = qtrk->PollFinished( resultbuf, NResultBuf );\n\n\tresultMutex.lock();\n\tfor (int i=0;i<count;i++)\n\t\tStoreResult(&resultbuf[i]);\n\tresultMutex.unlock();\n\n\ttrackerMutex.unlock();\n\n\tif (processedFrames - lastSaveFrame >= config.writeInterval) {\n\t\tWrite();\n\t}\n\n\tif (config.maxFramesInMemory>0 && frameResults.size () > config.maxFramesInMemory) {\n\t\tint del = frameResults.size()-config.maxFramesInMemory;\n\t\tdbgprintf(\"Removing %d frames from memory\\n\", del);\n\t\t\n\t\tfor (int i=0;i<del;i++)\n\t\t\tdelete frameResults[i];\n\t\tframeResults.erase(frameResults.begin(), frameResults.begin()+del);\n\n\t\tframeCountMutex.lock();\n\t\tstartFrame += del;\n\t\tframeCountMutex.unlock();\n\t}\n\n\treturn count>0;\n}\n\nvoid ResultManager::ThreadLoop(void *param)\n{\n\tResultManager* rm = (ResultManager*)param;\n\n\twhile(true) {\n\t\tif (!rm->Update())\n\t\t\tThreads::Sleep(20);\n\n\t\tif (rm->quit)\n\t\t\tbreak;\n\t}\n}\n\nint ResultManager::GetBeadPositions(int startFrame, int endFrame, int bead, LocalizationResult* results)\n{\n\tint count = endFrame-startFrame;\n\n\tframeCountMutex.lock();\n\tif (endFrame > processedFrames)\n\t\tendFrame = processedFrames;\n\n\tint start = startFrame - this->startFrame;\n\tif (start < 0) start = 0;\n\tif (count > processedFrames-this->startFrame)\n\t\tcount = processedFrames-this->startFrame;\n\n\tframeCountMutex.unlock();\n\n\tresultMutex.lock();\n\tfor (int i=0;i<count;i++){\n\t\tresults[i] = frameResults[i+start]->results[bead];\n\t}\n\tresultMutex.unlock();\n\n\treturn count;\n}\n\n\nvoid ResultManager::Flush()\n{\n\tWrite();\n\n\tresultMutex.lock();\n\n\t\/\/ Dump stats about unfinished frames for debugging\n\tfor (int i=0;i<frameResults.size();i++) {\n\t\tFrameResult *fr = frameResults[i];\n\t\tdbgprintf(\"Frame %d. TS: %f, Count: %d\\n\", i, fr->timestamp, fr->count);\n\t\tif (fr->count != config.numBeads) {\n\t\t\tfor (int j=0;j<fr->results.size();j++) {\n\t\t\t\tif( fr->results[j].job.locType == 0 )\n\t\t\t\t\tdbgprintf(\"%d, \", j );\n\t\t\t}\n\t\t\tdbgprintf(\"\\n\");\n\t\t}\n\t}\n\n\tresultMutex.unlock();\n}\n\n\nvoid ResultManager::GetFrameCounters(int* startFrame, int *processedFrames, int *lastSaveFrame, int *capturedFrames, int *localizationsDone)\n{\n\tframeCountMutex.lock();\n\tif (startFrame) *startFrame = this->startFrame;\n\tif (processedFrames) *processedFrames = this->processedFrames;\n\tif (lastSaveFrame) *lastSaveFrame = this->lastSaveFrame;\n\tif (localizationsDone) *localizationsDone = this->localizationsDone;\n\tframeCountMutex.unlock();\n\n\tif (capturedFrames) {\n\t\tresultMutex.lock();\n\t\t*capturedFrames = this->capturedFrames;\n\t\tresultMutex.unlock();\n\t}\n}\n\nint ResultManager::GetResults(LocalizationResult* results, int startFrame, int numFrames)\n{\n\tframeCountMutex.lock();\n\n\tif (startFrame >= this->startFrame && numFrames+startFrame <= processedFrames) {\n\t\tresultMutex.lock();\n\t\tfor (int f=0;f<numFrames;f++) {\n\t\t\tint index = f + startFrame - this->startFrame;\n\t\t\tfor (int j=0;j<config.numBeads;j++)\n\t\t\t\tresults[config.numBeads*f+j] = frameResults[index]->results[j];\n\t\t}\n\n\t\tresultMutex.unlock();\n\t}\n\tframeCountMutex.unlock();\n\n\treturn numFrames;\n}\n\n\nint ResultManager::StoreFrameInfo(double timestamp, float* columns)\n{\n\tresultMutex.lock();\n\tauto fr = new FrameResult( config.numBeads, config.numFrameInfoColumns);\n\tfr->timestamp = timestamp;\n\tfor(int i=0;i<config.numFrameInfoColumns;i++)\n\t\tfr->frameInfo[i]=columns[i];\n\tframeResults.push_back (fr);\n\tint nfr = ++capturedFrames;\n\tresultMutex.unlock();\n\treturn nfr;\n}\n\n\nint ResultManager::GetFrameCount()\n{\n\tresultMutex.lock();\n\tint nfr = capturedFrames;\n\tresultMutex.unlock();\n\treturn nfr;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp\n * RUN: %t\n * HIT_END\n *\/\n\n\/\/ Test under-development. Call hipStreamAddCallback function and see if it works as expected.\n\n#include \"hip\/hip_runtime.h\"\n#include \"test_common.h\"\n#define HIPRT_CB\nconst int NN = 1 << 21;\n\n__global__ void kernel(hipLaunchParm lp, float *x, float *y, int n){\n\tint tid = hipThreadIdx_x;\n\tif(tid < 1){\n\t\tfor(int i=0;i<n;i++){\n\t\t\tx[i] = sqrt(pow(3.14159,i));\n\t\t}\n\t\ty[tid] = y[tid] + 1.0f;\n\t}\n}\n__global__ void nKernel(hipLaunchParm lp, float *y){\n\tint tid = hipThreadIdx_x;\n\ty[tid] = y[tid] + 1.0f;\n}\n\nclass CallbackClass\n{\npublic:\n static void HIPRT_CB Callback(hipStream_t stream, hipError_t status, void *userData);\n\nprivate:\n void callbackFunc(hipError_t status);\n};\n\nvoid HIPRT_CB CallbackClass::Callback(hipStream_t stream, hipError_t status, void *userData)\n{\n CallbackClass* obj = (CallbackClass*) userData;\n obj->callbackFunc(status);\n}\n\nvoid CallbackClass::callbackFunc(hipError_t status)\n{\n HIPASSERT(status==hipSuccess);\n}\n\nint main(){\n\tconst int num_streams = 8;\n\thipStream_t streams[num_streams];\n \/* float *data[num_streams], *yd, *xd;*\/\n\t\/\/float y = 1.0f, x = 1.0f;\n\t\/\/HIPCHECK(hipMalloc((void**)&yd, sizeof(float)));\n\t\/\/HIPCHECK(hipMalloc((void**)&xd, sizeof(float)));\n\t\/\/HIPCHECK(hipMemcpy(yd, &y, sizeof(float), hipMemcpyHostToDevice));\n\t\/\/HIPCHECK(hipMemcpy(xd, &x, sizeof(float), hipMemcpyHostToDevice));\n\t\/\/for(int i=0;i<num_streams;i++){\n\t\t\/\/HIPCHECK(hipStreamCreate(&streams[i]));\n\t\t\/\/HIPCHECK(hipMalloc(&data[i], NN * sizeof(float)));\n\t\t\/\/hipLaunchKernel(HIP_KERNEL_NAME(kernel), dim3(1), dim3(1), 0, streams[i], data[i], xd, N);\n\t\t\/\/hipLaunchKernel(HIP_KERNEL_NAME(nKernel), dim3(1), dim3(1), 0, 0, yd);\n\t\/\/}\n\n\t\/\/HIPCHECK(hipMemcpy(&x, xd, sizeof(float), hipMemcpyDeviceToHost));\n\t\/\/HIPCHECK(hipMemcpy(&y, yd, sizeof(float), hipMemcpyDeviceToHost));\n\t\/\/std::cout<<x<<\" \"<<y<<std::endl;\n\t\/\/HIPASSERT(x<y);\n\n \/\/hipStream_t mystream = streams[0];\n hipStream_t mystream = NULL;\n CallbackClass* obj = new CallbackClass;\n hipStreamAddCallback(mystream, CallbackClass::Callback, obj, 0);\n\n\n\tpassed();\n}\n<commit_msg>Modify hipStreamAddCallback test case to consider both NULL stream and stream<commit_after>\/*\nCopyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp\n * RUN: %t\n * HIT_END\n *\/\n\n\/\/ Test under-development. Call hipStreamAddCallback function and see if it works as expected.\n\n#include \"hip\/hip_runtime.h\"\n#include \"test_common.h\"\n#define HIPRT_CB\n\nclass CallbackClass\n{\npublic:\n static void HIPRT_CB Callback(hipStream_t stream, hipError_t status, void *userData);\n\nprivate:\n void callbackFunc(hipError_t status);\n};\n\nvoid HIPRT_CB CallbackClass::Callback(hipStream_t stream, hipError_t status, void *userData)\n{\n CallbackClass* obj = (CallbackClass*) userData;\n obj->callbackFunc(status);\n}\n\nvoid CallbackClass::callbackFunc(hipError_t status)\n{\n HIPASSERT(status==hipSuccess);\n}\n\nint main(){\n hipStream_t mystream;\n HIPCHECK(hipStreamCreate(&mystream));\n CallbackClass* obj = new CallbackClass;\n HIPCHECK(hipStreamAddCallback(mystream, CallbackClass::Callback, obj, 0));\n HIPCHECK(hipStreamAddCallback(NULL, CallbackClass::Callback, obj, 0));\n\n\tpassed();\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2015, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Pipe.cxx\n * This file imlements POSIX pipe().\n *\n * @author Stuart W. Baker\n * @date 27 January 2015\n *\/\n\n#include <sys\/select.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include \"Devtab.hxx\"\n#include \"utils\/constants.hxx\"\n#include \"utils\/RingBuffer.hxx\"\n\nconst size_t DEFAULT_PIPE_SIZE = 256;\n\n\/** Private data for a can device *\/\nclass Pipe : public Node\n{\npublic:\n \/** Constructor\n * @param name device name in file system\n *\/\n Pipe(const char *name)\n : Node(name)\n , selInfoRd()\n , selInfoWr()\n , ring(NULL)\n , size(DEFAULT_PIPE_SIZE)\n {\n } \n\n \/** Destructor.\n *\/\n ~Pipe()\n {\n if (ring)\n {\n ring->destroy();\n }\n }\n\n \/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\n static int pipe(int pipefds[2]);\n\nprivate:\n \/** Close method. Returns negative errno on failure.\n * @param file reference to close\n * @return 0 upon success or negative error number upon error.\n *\/\n int close(File *file) OVERRIDE;\n\n \/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\n ssize_t read(File *file, void *buf, size_t count) OVERRIDE;\n\n \/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\n ssize_t write(File *file, const void *buf, size_t count) OVERRIDE;\n\n \/** Manipulate a file descriptor.\n * @param file file reference for this device\n * @param cmd operation to perform\n * @param data parameter to the cmd operation\n * @return dependent on the operation (POSIX compliant where applicable)\n * or negative error number upon error.\n *\/\n int fcntl(File *file, int cmd, unsigned long data) OVERRIDE;\n\n \/** Device select method. Default impementation returns true.\n * @param file reference to the file\n * @param mode FREAD for read active, FWRITE for write active, 0 for\n * exceptions\n * @return true if active, false if inactive\n *\/\n bool select(File* file, int mode) OVERRIDE;\n\n void enable() OVERRIDE {} \/**< function to enable device *\/\n void disable() OVERRIDE {}; \/**< function to disable device *\/\n void flush_buffers() OVERRIDE {}; \/**< called after disable *\/\n\n SelectInfo selInfoRd; \/**< select wakeup metadata for read active *\/\n SelectInfo selInfoWr; \/**< select wakeup metadata for write active *\/\n\n RingBuffer<uint8_t> *ring; \/**< ring buffer for storing the data *\/\n\n size_t size; \/**< pipe size *\/\n\n DISALLOW_COPY_AND_ASSIGN(Pipe);\n};\n\n\/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Pipe::read(File *file, void *buf, size_t count)\n{\n if ((file->flags & O_ACCMODE) == O_WRONLY)\n {\n return -EBADF;\n }\n\n uint8_t *data = (uint8_t*)buf;\n ssize_t result = 0;\n \n while (count)\n {\n size_t bytes;\n {\n OSMutexLock locker(&lock_);\n if (ring == NULL)\n {\n ring = RingBuffer<uint8_t>::create(size);\n }\n bytes = ring->get(data, count);\n\n count -= bytes;\n result += bytes;\n data += bytes;\n }\n\n if (bytes)\n {\n select_wakeup(&selInfoWr);\n }\n\n if (count)\n {\n \/* no more data to receive *\/\n if (file->flags & O_NONBLOCK || result > 0)\n {\n break;\n }\n else\n {\n \/* blocking mode, wait for writer *\/\n fd_set rdfds;\n FD_ZERO(&rdfds);\n int fd = fd_lookup(file);\n FD_SET(fd, &rdfds);\n ::select(fd + 1, &rdfds, NULL, NULL, NULL);\n }\n }\n }\n \n return result;\n}\n\n\/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Pipe::write(File *file, const void *buf, size_t count)\n{\n if ((file->flags & O_ACCMODE) == O_RDONLY)\n {\n return -EBADF;\n }\n\n const uint8_t *data = (const uint8_t*)buf;\n ssize_t result = 0;\n \n while (count)\n {\n size_t bytes;\n {\n OSMutexLock locker(&lock_);\n if (ring == NULL)\n {\n ring = RingBuffer<uint8_t>::create(size);\n }\n bytes = ring->put(data, count);\n\n count -= bytes;\n result += bytes;\n data += bytes;\n }\n\n if (bytes)\n {\n select_wakeup(&selInfoRd);\n }\n\n if (count)\n {\n \/* no more room left *\/\n if (file->flags & O_NONBLOCK || result > 0)\n {\n break;\n }\n else\n {\n \/* blocking mode, wait for reader *\/\n fd_set wrfds;\n FD_ZERO(&wrfds);\n int fd = fd_lookup(file);\n FD_SET(fd, &wrfds);\n ::select(fd + 1, NULL, &wrfds, NULL, NULL);\n }\n }\n }\n \n return result;\n}\n\n\/** Close method. Returns negative errno on failure.\n * @param file reference to close\n * @return 0 upon success or negative error number upon error.\n *\/\nint Pipe::close(File *file)\n{\n mutex.lock();\n if (--references_ == 0)\n {\n mutex.unlock();\n delete file->dev;\n }\n else\n {\n mutex.unlock();\n }\n\n return 0;\n}\n\n\/** Manipulate a file descriptor.\n * @param file file reference for this device\n * @param cmd operation to perform\n * @param data parameter to the cmd operation\n * @return dependent on the operation (POSIX compliant where applicable)\n * or negative error number upon error.\n *\/\nint Pipe::fcntl(File *file, int cmd, unsigned long data)\n{\n switch (cmd)\n {\n default:\n return 0;\n case F_SETPIPE_SZ:\n size = data;\n return 0;\n }\n}\n\n\/** Device select method. Default impementation returns true.\n * @param file reference to the file\n * @param mode FREAD for read active, FWRITE for write active, 0 for\n * exceptions\n * @return true if active, false if inactive\n *\/\nbool Pipe::select(File* file, int mode)\n{\n bool retval = false;\n switch (mode)\n {\n case FREAD:\n portENTER_CRITICAL();\n if (ring->items())\n {\n retval = true;\n }\n else\n {\n select_insert(&selInfoRd);\n }\n portEXIT_CRITICAL();\n break;\n case FWRITE:\n portENTER_CRITICAL();\n if (ring->space())\n {\n retval = true;\n }\n else\n {\n select_insert(&selInfoWr);\n }\n portEXIT_CRITICAL();\n break;\n default:\n case 0:\n \/* we don't support any exceptions *\/\n break;\n }\n return retval;\n}\n\n\n\/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\nint Pipe::pipe(int pipefds[2])\n{\n Pipe *new_pipe = new Pipe(NULL);\n\n mutex.lock();\n pipefds[0] = fd_alloc();\n if (pipefds[0] < 0)\n {\n mutex.unlock();\n errno = EMFILE;\n return -1;\n }\n pipefds[1] = fd_alloc();\n mutex.unlock();\n if (pipefds[1] < 0)\n {\n fd_free(pipefds[0]);\n errno = EMFILE;\n return -1;\n }\n\n File *files[2] = {file_lookup(pipefds[0]), file_lookup(pipefds[1])};\n\n files[0]->dev = new_pipe;\n files[1]->dev = new_pipe;\n files[0]->flags = O_RDONLY;\n files[1]->flags = O_WRONLY;\n\n new_pipe->references_ = 2;\n new_pipe->enable();\n\n return 0;\n}\n\n\/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\nint pipe(int pipefds[2])\n{\n return Pipe::pipe(pipefds);\n}\n<commit_msg>Trivial comment update<commit_after>\/** \\copyright\n * Copyright (c) 2015, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Pipe.cxx\n * This file implements POSIX pipe().\n *\n * @author Stuart W. Baker\n * @date 27 January 2015\n *\/\n\n#include <sys\/select.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include \"Devtab.hxx\"\n#include \"utils\/constants.hxx\"\n#include \"utils\/RingBuffer.hxx\"\n\nconst size_t DEFAULT_PIPE_SIZE = 256;\n\n\/** Private data for a can device *\/\nclass Pipe : public Node\n{\npublic:\n \/** Constructor\n * @param name device name in file system\n *\/\n Pipe(const char *name)\n : Node(name)\n , selInfoRd()\n , selInfoWr()\n , ring(NULL)\n , size(DEFAULT_PIPE_SIZE)\n {\n } \n\n \/** Destructor.\n *\/\n ~Pipe()\n {\n if (ring)\n {\n ring->destroy();\n }\n }\n\n \/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\n static int pipe(int pipefds[2]);\n\nprivate:\n \/** Close method. Returns negative errno on failure.\n * @param file reference to close\n * @return 0 upon success or negative error number upon error.\n *\/\n int close(File *file) OVERRIDE;\n\n \/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\n ssize_t read(File *file, void *buf, size_t count) OVERRIDE;\n\n \/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\n ssize_t write(File *file, const void *buf, size_t count) OVERRIDE;\n\n \/** Manipulate a file descriptor.\n * @param file file reference for this device\n * @param cmd operation to perform\n * @param data parameter to the cmd operation\n * @return dependent on the operation (POSIX compliant where applicable)\n * or negative error number upon error.\n *\/\n int fcntl(File *file, int cmd, unsigned long data) OVERRIDE;\n\n \/** Device select method. Default impementation returns true.\n * @param file reference to the file\n * @param mode FREAD for read active, FWRITE for write active, 0 for\n * exceptions\n * @return true if active, false if inactive\n *\/\n bool select(File* file, int mode) OVERRIDE;\n\n void enable() OVERRIDE {} \/**< function to enable device *\/\n void disable() OVERRIDE {}; \/**< function to disable device *\/\n void flush_buffers() OVERRIDE {}; \/**< called after disable *\/\n\n SelectInfo selInfoRd; \/**< select wakeup metadata for read active *\/\n SelectInfo selInfoWr; \/**< select wakeup metadata for write active *\/\n\n RingBuffer<uint8_t> *ring; \/**< ring buffer for storing the data *\/\n\n size_t size; \/**< pipe size *\/\n\n DISALLOW_COPY_AND_ASSIGN(Pipe);\n};\n\n\/** Read from a file or device.\n * @param file file reference for this device\n * @param buf location to place read data\n * @param count number of bytes to read\n * @return number of bytes read upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Pipe::read(File *file, void *buf, size_t count)\n{\n if ((file->flags & O_ACCMODE) == O_WRONLY)\n {\n return -EBADF;\n }\n\n uint8_t *data = (uint8_t*)buf;\n ssize_t result = 0;\n \n while (count)\n {\n size_t bytes;\n {\n OSMutexLock locker(&lock_);\n if (ring == NULL)\n {\n ring = RingBuffer<uint8_t>::create(size);\n }\n bytes = ring->get(data, count);\n\n count -= bytes;\n result += bytes;\n data += bytes;\n }\n\n if (bytes)\n {\n select_wakeup(&selInfoWr);\n }\n\n if (count)\n {\n \/* no more data to receive *\/\n if (file->flags & O_NONBLOCK || result > 0)\n {\n break;\n }\n else\n {\n \/* blocking mode, wait for writer *\/\n fd_set rdfds;\n FD_ZERO(&rdfds);\n int fd = fd_lookup(file);\n FD_SET(fd, &rdfds);\n ::select(fd + 1, &rdfds, NULL, NULL, NULL);\n }\n }\n }\n \n return result;\n}\n\n\/** Write to a file or device.\n * @param file file reference for this device\n * @param buf location to find write data\n * @param count number of bytes to write\n * @return number of bytes written upon success, -1 upon failure with errno containing the cause\n *\/\nssize_t Pipe::write(File *file, const void *buf, size_t count)\n{\n if ((file->flags & O_ACCMODE) == O_RDONLY)\n {\n return -EBADF;\n }\n\n const uint8_t *data = (const uint8_t*)buf;\n ssize_t result = 0;\n \n while (count)\n {\n size_t bytes;\n {\n OSMutexLock locker(&lock_);\n if (ring == NULL)\n {\n ring = RingBuffer<uint8_t>::create(size);\n }\n bytes = ring->put(data, count);\n\n count -= bytes;\n result += bytes;\n data += bytes;\n }\n\n if (bytes)\n {\n select_wakeup(&selInfoRd);\n }\n\n if (count)\n {\n \/* no more room left *\/\n if (file->flags & O_NONBLOCK || result > 0)\n {\n break;\n }\n else\n {\n \/* blocking mode, wait for reader *\/\n fd_set wrfds;\n FD_ZERO(&wrfds);\n int fd = fd_lookup(file);\n FD_SET(fd, &wrfds);\n ::select(fd + 1, NULL, &wrfds, NULL, NULL);\n }\n }\n }\n \n return result;\n}\n\n\/** Close method. Returns negative errno on failure.\n * @param file reference to close\n * @return 0 upon success or negative error number upon error.\n *\/\nint Pipe::close(File *file)\n{\n mutex.lock();\n if (--references_ == 0)\n {\n mutex.unlock();\n delete file->dev;\n }\n else\n {\n mutex.unlock();\n }\n\n return 0;\n}\n\n\/** Manipulate a file descriptor.\n * @param file file reference for this device\n * @param cmd operation to perform\n * @param data parameter to the cmd operation\n * @return dependent on the operation (POSIX compliant where applicable)\n * or negative error number upon error.\n *\/\nint Pipe::fcntl(File *file, int cmd, unsigned long data)\n{\n switch (cmd)\n {\n default:\n return 0;\n case F_SETPIPE_SZ:\n size = data;\n return 0;\n }\n}\n\n\/** Device select method. Default impementation returns true.\n * @param file reference to the file\n * @param mode FREAD for read active, FWRITE for write active, 0 for\n * exceptions\n * @return true if active, false if inactive\n *\/\nbool Pipe::select(File* file, int mode)\n{\n bool retval = false;\n switch (mode)\n {\n case FREAD:\n portENTER_CRITICAL();\n if (ring->items())\n {\n retval = true;\n }\n else\n {\n select_insert(&selInfoRd);\n }\n portEXIT_CRITICAL();\n break;\n case FWRITE:\n portENTER_CRITICAL();\n if (ring->space())\n {\n retval = true;\n }\n else\n {\n select_insert(&selInfoWr);\n }\n portEXIT_CRITICAL();\n break;\n default:\n case 0:\n \/* we don't support any exceptions *\/\n break;\n }\n return retval;\n}\n\n\n\/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\nint Pipe::pipe(int pipefds[2])\n{\n Pipe *new_pipe = new Pipe(NULL);\n\n mutex.lock();\n pipefds[0] = fd_alloc();\n if (pipefds[0] < 0)\n {\n mutex.unlock();\n errno = EMFILE;\n return -1;\n }\n pipefds[1] = fd_alloc();\n mutex.unlock();\n if (pipefds[1] < 0)\n {\n fd_free(pipefds[0]);\n errno = EMFILE;\n return -1;\n }\n\n File *files[2] = {file_lookup(pipefds[0]), file_lookup(pipefds[1])};\n\n files[0]->dev = new_pipe;\n files[1]->dev = new_pipe;\n files[0]->flags = O_RDONLY;\n files[1]->flags = O_WRONLY;\n\n new_pipe->references_ = 2;\n new_pipe->enable();\n\n return 0;\n}\n\n\/** Create a Unix style pipe.\n * @param pipefds index 0, file descriptor open for reading.\n * index 1, file descriptor open for writing.\n * @return 0 upon success, -1 on errer with errno set appropriately\n *\/\nint pipe(int pipefds[2])\n{\n return Pipe::pipe(pipefds);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* Copyright (c) European Southern Observatory, 2012 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: AlarmSourceThread.cpp,v 1.1 2012\/04\/26 12:35:42 acaproni Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* acaproni 2012-04-24 created \n*\/\n\n#include <ace\/Guard_T.h>\n#include <ace\/Time_Value.h>\n#include <ace\/OS.h>\n\n#include <ACSErrTypeCommon.h>\n#include <acstimeTimeUtil.h>\n#include \"AlarmSourceThread.h\"\n\nusing namespace acsalarm;\nusing namespace acsthreadErrType;\n\nAlarmSourceThread::AlarmSourceThread():\n\tACS::Thread(\"AlarmSourceThread\", 10000000),\n\tm_alarmSources()\n{\n\t\/\/ Start the thread\n\tresume();\n}\n\nAlarmSourceThread::~AlarmSourceThread()\n{\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\tm_alarmSources.clear();\n\t\/\/ Stop the thread\n\tterminate();\n}\n\nvoid AlarmSourceThread::runLoop()\n{\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\t std::set<AlarmSource*>::iterator it;\n\t for (it=m_alarmSources.begin(); it!=m_alarmSources.end() && check(); ++it)\n\t {\n\t\t ACE_Time_Value nowAceTime=ACE_OS::gettimeofday();\n\t\t acstime::Epoch now=TimeUtil::ace2epoch(nowAceTime);\n\t\t try {\n\t\t\t (*it)->update(now.value);\n\t\t } catch (...) {\n\t\t\t ACS_SHORT_LOG((LM_CRITICAL,\"Exception caught callin AlarmSource->update()\"));\n\t\t\t ACSErrTypeCommon::UnexpectedExceptionExImpl uex(__FILE__, __LINE__, \"AlarmSourceThread::runLoop\");\n\t\t\t ExceptionInRunLoopExImpl ex(uex, __FILE__, __LINE__, \"ACS::Thread::runLoop\");\n\t\t\t ex.setThreadName(getName());\n\t\t\t throw ex;\n\t\t }\n\t }\n}\n\n\nbool AlarmSourceThread::registerForUpdating(AlarmSource* src)\n{\n\tif (src==NULL) {\n\t\treturn false;\n\t}\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\tstd::pair<std::set<AlarmSource*>::iterator,bool> ret= m_alarmSources.insert(src);\n\treturn ret.second;\n}\n\nbool AlarmSourceThread::unregisterFromUpdating(AlarmSource* src)\n{\n\tif (src==NULL) {\n\t\treturn false;\n\t}\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\treturn m_alarmSources.erase(src)==1;\n}\n\n\/*___oOo___*\/\n<commit_msg>Removed the dependency from acstime. The actual time passed in update() is in msec.<commit_after>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* Copyright (c) European Southern Observatory, 2012 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: AlarmSourceThread.cpp,v 1.2 2012\/04\/27 09:10:28 acaproni Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* acaproni 2012-04-24 created \n*\/\n\n#include <ace\/Guard_T.h>\n#include <ace\/Time_Value.h>\n#include <ace\/OS.h>\n\n#include <ACSErrTypeCommon.h>\n#include \"AlarmSourceThread.h\"\n\nusing namespace acsalarm;\nusing namespace acsthreadErrType;\n\nAlarmSourceThread::AlarmSourceThread():\n\tACS::Thread(\"AlarmSourceThread\", 1000000),\n\tm_alarmSources()\n{\n\t\/\/ Start the thread\n\tresume();\n}\n\nAlarmSourceThread::~AlarmSourceThread()\n{\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\tm_alarmSources.clear();\n\t\/\/ Stop the thread\n\tterminate();\n}\n\nvoid AlarmSourceThread::runLoop()\n{\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\t std::set<AlarmSource*>::iterator it;\n\t for (it=m_alarmSources.begin(); it!=m_alarmSources.end() && check(); ++it)\n\t {\n\t\t ACE_Time_Value nowAceTime=ACE_OS::gettimeofday();\n\t\t try {\n\t\t\t (*it)->update(nowAceTime.msec());\n\t\t } catch (...) {\n\t\t\t ACS_SHORT_LOG((LM_CRITICAL,\"Exception caught callin AlarmSource->update()\"));\n\t\t\t ACSErrTypeCommon::UnexpectedExceptionExImpl uex(__FILE__, __LINE__, \"AlarmSourceThread::runLoop\");\n\t\t\t ExceptionInRunLoopExImpl ex(uex, __FILE__, __LINE__, \"ACS::Thread::runLoop\");\n\t\t\t ex.setThreadName(getName());\n\t\t\t throw ex;\n\t\t }\n\t }\n}\n\n\nbool AlarmSourceThread::registerForUpdating(AlarmSource* src)\n{\n\tif (src==NULL) {\n\t\treturn false;\n\t}\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\tstd::pair<std::set<AlarmSource*>::iterator,bool> ret= m_alarmSources.insert(src);\n\treturn ret.second;\n}\n\nbool AlarmSourceThread::unregisterFromUpdating(AlarmSource* src)\n{\n\tif (src==NULL) {\n\t\treturn false;\n\t}\n\tACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_mutex);\n\treturn m_alarmSources.erase(src)==1;\n}\n\n\/*___oOo___*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_Optional_inl_\n#define _Stroika_Foundation_Memory_Optional_inl_ 1\n\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \"..\/Debug\/Assertions.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Memory {\n\n\n \/*\n ********************************************************************************\n ********************************** Optional<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Optional<T>::Optional ()\n : fValue_ (nullptr)\n {\n }\n template <typename T>\n inline Optional<T>::Optional (const T& from)\n : fValue_ (new BlockAllocated<T> (from))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (T && from)\n : fValue_ (new BlockAllocated<T> (std::move (from)))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (const Optional<T>& from)\n : fValue_ (from.fValue_ == nullptr ? nullptr : new BlockAllocated<T> (*from.fValue_))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (Optional<T> && from)\n : fValue_ (from.fValue_)\n {\n from.fValue_ = nullptr;\n }\n template <typename T>\n inline Optional<T>::~Optional ()\n {\n delete fValue_;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (const T& from)\n {\n delete fValue_;\n fValue_ = nullptr;\n fValue_ = new BlockAllocated<T> (from);\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (T && from)\n {\n fValue_ = new BlockAllocated<T> (std::move (from));\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (const Optional<T>& from)\n {\n delete fValue_;\n fValue_ = nullptr;\n if (from.fValue_ != nullptr) {\n fValue_ = new BlockAllocated<T> (*from.fValue_);\n }\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (Optional<T> && from)\n {\n fValue_ = from.fValue_;\n from.fValue_ = nullptr;\n return *this;\n }\n template <typename T>\n inline void Optional<T>::clear ()\n {\n delete fValue_;\n fValue_ = nullptr;\n }\n template <typename T>\n inline const T* Optional<T>::get () const\n {\n return fValue_;\n }\n template <typename T>\n inline bool Optional<T>::empty () const\n {\n return fValue_ == nullptr;\n }\n template <typename T>\n inline const T* Optional<T>::operator-> () const\n {\n Require (not empty ())\n AssertNotNull (fValue_);\n return fValue_;\n }\n template <typename T>\n inline T* Optional<T>::operator-> ()\n {\n Require (not empty ());\n AssertNotNull (fValue_);\n return fValue_->get ();\n }\n template <typename T>\n inline const T& Optional<T>::operator* () const\n {\n Require (not empty ())\n return *fValue_->get ();\n }\n template <typename T>\n inline T& Optional<T>::operator* ()\n {\n Require (not empty ())\n return *fValue_->get ();\n }\n template <typename T>\n inline Optional<T>::operator T () const\n {\n Require (not empty ())\n return *fValue_;\n }\n template <typename T>\n bool Optional<T>::operator< (const Optional<T>& rhs) const\n {\n if (fValue_ == nullptr) {\n return (rhs.fValue_ == nullptr) ? false : true; \/\/ arbitrary choice - but assume if lhs is empty thats less than any T value\n }\n if (rhs.fValue_ == nullptr) {\n return false;\n }\n return *fValue_ < *rhs.fValue_;\n }\n template <typename T>\n bool Optional<T>::operator<= (const Optional<T>& rhs) const\n {\n return *this < rhs or * this == rhs;\n }\n template <typename T>\n inline bool Optional<T>::operator> (const Optional<T>& rhs) const\n {\n return rhs < *this;\n }\n template <typename T>\n bool Optional<T>::operator>= (const Optional<T>& rhs) const\n {\n return *this > rhs or * this == rhs;\n }\n template <typename T>\n bool Optional<T>::operator== (const Optional<T>& rhs) const\n {\n if (fValue_ == nullptr) {\n return rhs.fValue_ == nullptr;\n }\n if (rhs.fValue_ == nullptr) {\n return false;\n }\n return *fValue_ == *rhs.fValue_;\n }\n template <typename T>\n inline bool Optional<T>::operator!= (const Optional<T>& rhs) const\n {\n return not (*this == rhs);\n }\n\n\n }\n }\n}\n#endif \/*_Stroika_Foundation_Memory_Optional_inl_*\/\n<commit_msg>small bugs with Optional<T> fixed<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_Optional_inl_\n#define _Stroika_Foundation_Memory_Optional_inl_ 1\n\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \"..\/Debug\/Assertions.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Memory {\n\n\n \/*\n ********************************************************************************\n ********************************** Optional<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Optional<T>::Optional ()\n : fValue_ (nullptr)\n {\n }\n template <typename T>\n inline Optional<T>::Optional (const T& from)\n : fValue_ (new BlockAllocated<T> (from))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (T && from)\n : fValue_ (new BlockAllocated<T> (std::move (from)))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (const Optional<T>& from)\n : fValue_ (from.fValue_ == nullptr ? nullptr : new BlockAllocated<T> (*from.fValue_))\n {\n }\n template <typename T>\n inline Optional<T>::Optional (Optional<T> && from)\n : fValue_ (from.fValue_)\n {\n from.fValue_ = nullptr;\n }\n template <typename T>\n inline Optional<T>::~Optional ()\n {\n delete fValue_;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (const T& from)\n {\n delete fValue_;\n fValue_ = nullptr;\n fValue_ = new BlockAllocated<T> (from);\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (T && from)\n {\n fValue_ = new BlockAllocated<T> (std::move (from));\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (const Optional<T>& from)\n {\n delete fValue_;\n fValue_ = nullptr;\n if (from.fValue_ != nullptr) {\n fValue_ = new BlockAllocated<T> (*from.fValue_);\n }\n return *this;\n }\n template <typename T>\n inline Optional<T>& Optional<T>::operator= (Optional<T> && from)\n {\n fValue_ = from.fValue_;\n from.fValue_ = nullptr;\n return *this;\n }\n template <typename T>\n inline void Optional<T>::clear ()\n {\n delete fValue_;\n fValue_ = nullptr;\n }\n template <typename T>\n inline const T* Optional<T>::get () const\n {\n return fValue_;\n }\n template <typename T>\n inline bool Optional<T>::empty () const\n {\n return fValue_ == nullptr;\n }\n template <typename T>\n inline const T* Optional<T>::operator-> () const\n {\n Require (not empty ())\n AssertNotNull (fValue_);\n EnsureNotNull (fValue_->get ());\n return fValue_->get ();\n }\n template <typename T>\n inline T* Optional<T>::operator-> ()\n {\n Require (not empty ());\n AssertNotNull (fValue_);\n EnsureNotNull (fValue_->get ());\n return fValue_->get ();\n }\n template <typename T>\n inline const T& Optional<T>::operator* () const\n {\n Require (not empty ())\n AssertNotNull (fValue_);\n EnsureNotNull (fValue_->get ());\n return *fValue_->get ();\n }\n template <typename T>\n inline T& Optional<T>::operator* ()\n {\n Require (not empty ())\n AssertNotNull (fValue_);\n EnsureNotNull (fValue_->get ());\n return *fValue_->get ();\n }\n template <typename T>\n inline Optional<T>::operator T () const\n {\n Require (not empty ())\n AssertNotNull (fValue_);\n return *fValue_;\n }\n template <typename T>\n bool Optional<T>::operator< (const Optional<T>& rhs) const\n {\n if (fValue_ == nullptr) {\n return (rhs.fValue_ == nullptr) ? false : true; \/\/ arbitrary choice - but assume if lhs is empty thats less than any T value\n }\n if (rhs.fValue_ == nullptr) {\n return false;\n }\n return *fValue_ < *rhs.fValue_;\n }\n template <typename T>\n bool Optional<T>::operator<= (const Optional<T>& rhs) const\n {\n return *this < rhs or * this == rhs;\n }\n template <typename T>\n inline bool Optional<T>::operator> (const Optional<T>& rhs) const\n {\n return rhs < *this;\n }\n template <typename T>\n bool Optional<T>::operator>= (const Optional<T>& rhs) const\n {\n return *this > rhs or * this == rhs;\n }\n template <typename T>\n bool Optional<T>::operator== (const Optional<T>& rhs) const\n {\n if (fValue_ == nullptr) {\n return rhs.fValue_ == nullptr;\n }\n if (rhs.fValue_ == nullptr) {\n return false;\n }\n return *fValue_ == *rhs.fValue_;\n }\n template <typename T>\n inline bool Optional<T>::operator!= (const Optional<T>& rhs) const\n {\n return not (*this == rhs);\n }\n\n\n }\n }\n}\n#endif \/*_Stroika_Foundation_Memory_Optional_inl_*\/\n<|endoftext|>"} {"text":"<commit_before>#include \"details\/compiler\/compile.h\"\n#include \"details\/compiler\/compiler.h\"\n#include \"details\/program\/program.h\"\n#include \"details\/reporting\/report.h\"\n#include \"details\/errors\/errors.h\"\n#include \"details\/pass\/a-src2ast\/ast-from-source.h\"\n#include <yuni\/io\/file.h>\n#include <libnanyc.h>\n#include <utility>\n#include <memory>\n\nnamespace ny {\nnamespace compiler {\n\nnamespace {\n\nconstexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;\n\nLogs::Report buildGenerateReport(void* ptr, Logs::Level level) {\n\treturn (*((ny::Logs::Report*) ptr)).fromErrLevel(level);\n}\n\nnyprogram_t* complainNoSource(ny::Logs::Report& report) {\n\treport.error() << \"no input source code\";\n\treturn nullptr;\n}\n\nvoid copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tif (opts.filename.len != 0) {\n\t\tif (unlikely(opts.filename.len > memoryHardlimit))\n\t\t\tthrow \"input filename bigger than internal limit\";\n\t\tyuni::IO::Canonicalize(source.filename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});\n\t}\n\tif (opts.content.len != 0) {\n\t\tif (unlikely(opts.content.len > memoryHardlimit))\n\t\t\tthrow \"input source content bigger than internal limit\";\n\t\tsource.content.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));\n\t}\n}\n\nvoid compileSource(ny::compiler::Source& source) {\n\tbool compiled = true;\n\tcompiled &= makeASTFromSource(source);\n\treturn compiled;\n}\n\nbool importSourceAndCompile(ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tcopySourceOpts(source, opts);\n\treturn compileSource(source);\n}\n\n} \/\/ namespace\n\ninline Compiler::Compiler(const nycompile_opts_t& opts)\n\t: opts(opts) {\n}\n\ninline nyprogram_t* Compiler::compile() {\n\tny::Logs::Report report{messages};\n\tLogs::Handler errorHandler{&report, &buildGenerateReport};\n\ttry {\n\t\tuint32_t scount = opts.sources.count;\n\t\tif (unlikely(scount == 0))\n\t\t\treturn complainNoSource(report);\n\t\tsources.count = scount;\n\t\tsources.items = std::make_unique<Source[]>(scount);\n\t\tfor (uint32_t i = 0; i != opts.sources.count; ++i)\n\t\t\timportSourceAndCompile(sources[i], opts.sources.items[i]);\n\t\tauto program = std::make_unique<ny::Program>();\n\t\treturn ny::Program::pointer(program.release());\n\t}\n\tcatch (const std::bad_alloc& e) {\n\t\treport.ice() << \"not enough memory when compiling\";\n\t}\n\tcatch (const std::exception& e) {\n\t\treport.ice() << \"exception: \" << e.what();\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << e;\n\t}\n\tcatch (...) {\n\t\treport.ice() << \"uncaught exception when compiling\";\n\t}\n\treturn nullptr;\n}\n\nnyprogram_t* compile(nycompile_opts_t& opts) {\n\ttry {\n\t\tif (opts.on_build_start)\n\t\t\topts.userdata = opts.on_build_start(opts.userdata);\n\t\tauto* program = Compiler{opts}.compile();\n\t\tif (opts.on_build_stop)\n\t\t\topts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));\n\t\treturn program;\n\t}\n\tcatch (...) {\n\t}\n\tif (opts.on_build_stop)\n\t\topts.on_build_stop(opts.userdata, nyfalse);\n\treturn nullptr;\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace ny\n<commit_msg>compiler: add error report per source<commit_after>#include \"details\/compiler\/compile.h\"\n#include \"details\/compiler\/compiler.h\"\n#include \"details\/program\/program.h\"\n#include \"details\/reporting\/report.h\"\n#include \"details\/errors\/errors.h\"\n#include \"details\/pass\/a-src2ast\/ast-from-source.h\"\n#include <yuni\/io\/file.h>\n#include <libnanyc.h>\n#include <utility>\n#include <memory>\n\nnamespace ny {\nnamespace compiler {\n\nnamespace {\n\nconstexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;\n\nLogs::Report buildGenerateReport(void* ptr, Logs::Level level) {\n\treturn (*((ny::Logs::Report*) ptr)).fromErrLevel(level);\n}\n\nnyprogram_t* complainNoSource(ny::Logs::Report& report) {\n\treport.error() << \"no input source code\";\n\treturn nullptr;\n}\n\nvoid copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tif (opts.filename.len != 0) {\n\t\tif (unlikely(opts.filename.len > memoryHardlimit))\n\t\t\tthrow \"input filename bigger than internal limit\";\n\t\tyuni::IO::Canonicalize(source.filename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});\n\t}\n\tif (opts.content.len != 0) {\n\t\tif (unlikely(opts.content.len > memoryHardlimit))\n\t\t\tthrow \"input source content bigger than internal limit\";\n\t\tsource.content.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));\n\t}\n}\n\nbool compileSource(ny::Logs::Report& mainreport, ny::compiler::Source& source) {\n\tauto report = mainreport.subgroup();\n\treport.data().origins.location.filename = source.filename;\n\treport.data().origins.location.target.clear();\n\tbool compiled = true;\n\tcompiled &= makeASTFromSource(source);\n\treturn compiled;\n}\n\nbool importSourceAndCompile(ny::Logs::Report& mainreport, ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tcopySourceOpts(source, opts);\n\treturn compileSource(mainreport, source);\n}\n\n} \/\/ namespace\n\ninline Compiler::Compiler(const nycompile_opts_t& opts)\n\t: opts(opts) {\n}\n\ninline nyprogram_t* Compiler::compile() {\n\tny::Logs::Report report{messages};\n\tLogs::Handler errorHandler{&report, &buildGenerateReport};\n\ttry {\n\t\tuint32_t scount = opts.sources.count;\n\t\tif (unlikely(scount == 0))\n\t\t\treturn complainNoSource(report);\n\t\tsources.count = scount;\n\t\tsources.items = std::make_unique<Source[]>(scount);\n\t\tbool compiled = true;\n\t\tfor (uint32_t i = 0; i != opts.sources.count; ++i)\n\t\t\tcompiled &= importSourceAndCompile(report, sources[i], opts.sources.items[i]);\n\t\tif (compiled) {\n\t\t\tauto program = std::make_unique<ny::Program>();\n\t\t\treturn ny::Program::pointer(program.release());\n\t\t}\n\t}\n\tcatch (const std::bad_alloc& e) {\n\t\treport.ice() << \"not enough memory when compiling\";\n\t}\n\tcatch (const std::exception& e) {\n\t\treport.ice() << \"exception: \" << e.what();\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << e;\n\t}\n\tcatch (...) {\n\t\treport.ice() << \"uncaught exception when compiling\";\n\t}\n\treturn nullptr;\n}\n\nnyprogram_t* compile(nycompile_opts_t& opts) {\n\ttry {\n\t\tif (opts.on_build_start)\n\t\t\topts.userdata = opts.on_build_start(opts.userdata);\n\t\tauto* program = Compiler{opts}.compile();\n\t\tif (opts.on_build_stop)\n\t\t\topts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));\n\t\treturn program;\n\t}\n\tcatch (...) {\n\t}\n\tif (opts.on_build_stop)\n\t\topts.on_build_stop(opts.userdata, nyfalse);\n\treturn nullptr;\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace ny\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n\nclass Point\n{\n public:\n\n Point();\n Point(double , double);\n double x();\n void set_x(double);\n double y();\n void set_y(double);\n\n private:\n double m_x;\n double m_y;\n\n};\n\nvoid Point::set_x(double x)\n{\n m_x = x;\n}\nvoid Point::set_y(double y)\n{\n m_y = y;\n\n}\nPoint::Point()\n{\n set_x(0);\n set_y(0);\n\n}\nPoint::Point( double x, double y)\n{\n set_x(x);\n set_y(y);\n\n}\n\n\n\n\n<commit_msg> created point. closes<commit_after>#include <iostream>\n\n\nclass Point\n{\n public:\n\n Point();\n Point(double , double);\n double x();\n void set_x(double);\n double y();\n void set_y(double);\n\n private:\n double m_x;\n double m_y;\n\n};\n\nvoid Point::set_x(double x)\n{\n m_x = x;\n}\n\nvoid Point::set_y(double y)\n{\n m_y = y;\n\n}\n\nPoint::Point()\n{\n set_x(0);\n set_y(0);\n\n}\n\nPoint::Point( double x, double y)\n{\n set_x(x);\n set_y(y);\n\n}\n\nint main (int argc, char* argv[])\n{\n Point p1;\n p1.set_x(4);\n p1.set_y(6);\n\n std::cout << \" Point x is: \" << p1.set_x <<std::endl;\n std::cout << \" Point y is: \" << p1.set_y << std::endl;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef __SEVMGR_SEVMGR_TYPES_HPP\n#define __SEVMGR_SEVMGR_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Sevmgr\n#include <sevmgr\/SEVMGR_Exceptions.hpp>\n\nnamespace SEVMGR {\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions specific to Sevmgr \/\/\/\/\/\/\/\/\/\n \/\/ No specific type for now\n \n}\n#endif \/\/ __SEVMGR_SEVMGR_TYPES_HPP\n\n<commit_msg>[dev] Added the pointer on SEvMgr service handler.<commit_after>#ifndef __SEVMGR_SEVMGR_TYPES_HPP\n#define __SEVMGR_SEVMGR_TYPES_HPP\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boost\n#include <boost\/shared_ptr.hpp>\n\/\/ Sevmgr\n#include <sevmgr\/SEVMGR_Exceptions.hpp>\n\nnamespace SEVMGR {\n\n \/\/ Forward declarations\n class SEVMGR_Service;\n\n \/\/ \/\/\/\/\/\/\/\/ Type definitions specific to to Sevmgr \/\/\/\/\/\/\/\/\/\n \/**\n * (Smart) Pointer on the SEvMgr service handler.\n *\/\n typedef boost::shared_ptr<SEVMGR_Service> SEVMGR_ServicePtr_T;\n \n}\n#endif \/\/ __SEVMGR_SEVMGR_TYPES_HPP\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ fdp.hpp : include file containing templated C++ interfaces to fused dot product\n\/\/\n\/\/ Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include <vector>\n\nnamespace sw {\n\tnamespace unum {\n\n\/\/ dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well\n\/\/ since we do not support arbitrary posit configuration conversions, the element type of the vectors x and y are declared to be the same.\n\/\/ TODO: investigate if the vector<> index is always a 32bit entity?\ntemplate<typename Ty>\nTy dot(size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) {\n\tTy sum_of_products = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {\n\t\tTy product = x[ix] * y[iy];\n\t\tsum_of_products += product;\n\t}\n\treturn sum_of_products;\n}\n\n\/\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ fused dot product operators\n\/\/\/ fdp_qc fused dot product with quire continuation\n\/\/\/ fdp_stride fused dot product with non-negative stride\n\/\/\/ fdp fused dot product of two vectors\n\n\/\/ Fused dot product with quire continuation\ntemplate<typename Qy, typename Vector>\nvoid fdp_qc(Qy& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tsum_of_products += sw::unum::quire_mul(x[ix], y[iy]);\n\t}\n}\n\n\/\/ Resolved fused dot product, with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tquire<nbits, es, capacity> q = 0;\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tq += sw::unum::quire_mul(x[ix], y[iy]);\n\t\tif (sw::unum::_trace_quire_add) std::cout << q << '\\n';\n\t}\n\ttypename Vector::value_type sum;\n\tconvert(q.to_value(), sum); \/\/ one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n\/\/ Specialized resolved fused dot product that assumes unit stride and a standard vector,\n\/\/ with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp(const Vector& x, const Vector& y) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tquire<nbits, es, capacity> q = 0;\n\tsize_t ix, iy, n = x.size();\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) {\n\t\tq += sw::unum::quire_mul(x[ix], y[iy]);\n\t}\n\ttypename Vector::value_type sum;\n\tconvert(q.to_value(), sum); \/\/ one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n#ifdef BLAS_L2\n\/\/ LEVEL 2 BLAS operators\ntemplate<typename Ty>\nvoid matvec(const std::vector<Ty>& A, const std::vector<Ty>& x, std::vector<Ty>& b) {\n\t\/\/ preconditions\n\tsize_t d = x.size();\n\tassert(A.size() == d*d);\n\tassert(b.size() == d);\n\tfor (size_t i = 0; i < d; ++i) {\n\t\tb[i] = 0;\n\t\tfor (size_t j = 0; j < d; ++j) {\n\t\t\t\/\/std::cout << \"b[\" << i << \"] = \" << b[i] << std::endl;\n\t\t\t\/\/std::cout << \"A[\" << i << \"][\" << j << \"] = \" << A[i*d + j] << std::endl;\n\t\t\t\/\/std::cout << \"x[\" << j << \"] = \" << x[j] << std::endl;\n\t\t\tb[i] = b[i] + A[i*d + j] * x[j];\n\t\t}\n\t\t\/\/std::cout << \"b[\" << i << \"] = \" << b[i] << std::endl;\n\t}\n}\n\n\/\/ leverage template parameter inference to specialize matvec to use the quire when the inputs are posit vectors\ntemplate<size_t nbits, size_t es, size_t capacity = 10>\nvoid matvec(const std::vector< posit<nbits, es> >& A, const std::vector< posit<nbits, es> >& x, std::vector< posit<nbits, es> >& b) {\n\t\/\/ preconditions\n\tsize_t d = x.size();\n\tassert(A.size() == d*d);\n\tassert(b.size() == d);\n\tfor (size_t i = 0; i < d; ++i) {\n\t\tb[i] = 0;\n\t\tquire<nbits, es, capacity> q; \/\/ initialized to 0 by constructor\n\t\tfor (size_t j = 0; j < d; ++j) {\n\t\t\tq += quire_mul(A[i*d + j], x[j]);\n\t\t\tif (sw::unum::_trace_quire_add) std::cout << q << '\\n';\n\t\t} \n\t\tconvert(q.to_value(), b[i]); \/\/ one and only rounding step of the fused-dot product\n\t\t\/\/std::cout << \"b[\" << i << \"] = \" << b[i] << std::endl;\n\t}\n}\n#endif \/\/ BLAS_L2\n\n#ifdef BLAS_L3\n\/\/ LEVEL 3 BLAS operators\n\n\/\/ matrix-matrix multiplication\ntemplate<typename Ty>\nvoid matmul(const std::vector<Ty>& A, const std::vector<Ty>& B, std::vector<Ty>& C) {\n\t\/\/ preconditions\n\tsize_t d = size_t(std::sqrt(A.size()));\n\tassert(A.size() == d*d);\n\tassert(B.size() == d*d);\n\tassert(C.size() == d*d);\n\tfor (size_t i = 0; i < d; ++i) {\n\t\tfor (size_t j = 0; j < d; ++j) {\n\t\t\tC[i*d + j] = Ty(0);\n\t\t\tfor (size_t k = 0; k < d; ++k) {\n\t\t\t\tC[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ leverage template parameter inference to specialize matmul to use the quire when the inputs are posit vectors\ntemplate<size_t nbits, size_t es, size_t capacity = 10>\nvoid matmul(const std::vector<posit<nbits,es> >& A, const std::vector< posit<nbits, es> >& B, std::vector< posit<nbits, es> >& C) {\n\t\/\/ preconditions\n\tsize_t d = size_t(std::sqrt(A.size()));\n\tassert(A.size() == d*d);\n\tassert(B.size() == d*d);\n\tassert(C.size() == d*d);\n\tfor (size_t i = 0; i < d; ++i) {\n\t\tfor (size_t j = 0; j < d; ++j) {\n\t\t\tC[i*d + j] = 0;\n\t\t\tquire<nbits, es, capacity> q; \/\/ initialized to 0 by constructor\n\t\t\tfor (size_t k = 0; k < d; ++k) {\n\t\t\t\t\/\/ C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j];\n\t\t\t\tq += quire_mul(A[i*d + k], B[k*d + j]);\n\t\t\t\tif (sw::unum::_trace_quire_add) std::cout << q << '\\n';\n\t\t\t}\n\t\t\tconvert(q.to_value(), C[i*d + j]); \/\/ one and only rounding step of the fused-dot product\n\t\t}\n\t}\n}\n\n#endif \/\/ BLAS_L3\n\n} \/\/ namespace unum\n} \/\/ namespace sw\n\n<commit_msg>removing BLAS L2 and L3 operators from fdp<commit_after>\/\/ fdp.hpp : include file containing templated C++ interfaces to fused dot product\n\/\/\n\/\/ Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n\/\/\n\/\/ This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include <vector>\n\nnamespace sw {\n\tnamespace unum {\n\n\/\/ dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well\n\/\/ since we do not support arbitrary posit configuration conversions, the element type of the vectors x and y are declared to be the same.\n\/\/ TODO: investigate if the vector<> index is always a 32bit entity?\ntemplate<typename Ty>\nTy dot(size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) {\n\tTy sum_of_products = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) {\n\t\tTy product = x[ix] * y[iy];\n\t\tsum_of_products += product;\n\t}\n\treturn sum_of_products;\n}\n\n\/\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ fused dot product operators\n\/\/\/ fdp_qc fused dot product with quire continuation\n\/\/\/ fdp_stride fused dot product with non-negative stride\n\/\/\/ fdp fused dot product of two vectors\n\n\/\/ Fused dot product with quire continuation\ntemplate<typename Qy, typename Vector>\nvoid fdp_qc(Qy& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tsum_of_products += sw::unum::quire_mul(x[ix], y[iy]);\n\t}\n}\n\n\/\/ Resolved fused dot product, with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tquire<nbits, es, capacity> q = 0;\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tq += sw::unum::quire_mul(x[ix], y[iy]);\n\t\tif (sw::unum::_trace_quire_add) std::cout << q << '\\n';\n\t}\n\ttypename Vector::value_type sum;\n\tconvert(q.to_value(), sum); \/\/ one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n\/\/ Specialized resolved fused dot product that assumes unit stride and a standard vector,\n\/\/ with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp(const Vector& x, const Vector& y) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tquire<nbits, es, capacity> q = 0;\n\tsize_t ix, iy, n = x.size();\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) {\n\t\tq += sw::unum::quire_mul(x[ix], y[iy]);\n\t}\n\ttypename Vector::value_type sum;\n\tconvert(q.to_value(), sum); \/\/ one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n} \/\/ namespace unum\n} \/\/ namespace sw\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ UndefCapturedBlockVarChecker.cpp - Uninitialized captured vars -*- C++ -*-=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This checker detects blocks that capture uninitialized values.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangSACheckers.h\"\n#include \"clang\/AST\/Attr.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugType.h\"\n#include \"clang\/StaticAnalyzer\/Core\/Checker.h\"\n#include \"clang\/StaticAnalyzer\/Core\/CheckerManager.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CheckerContext.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ExprEngine.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace ento;\n\nnamespace {\nclass UndefCapturedBlockVarChecker\n : public Checker< check::PostStmt<BlockExpr> > {\n mutable OwningPtr<BugType> BT;\n\npublic:\n void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;\n};\n} \/\/ end anonymous namespace\n\nstatic const DeclRefExpr *FindBlockDeclRefExpr(const Stmt *S,\n const VarDecl *VD) {\n if (const DeclRefExpr *BR = dyn_cast<DeclRefExpr>(S))\n if (BR->getDecl() == VD)\n return BR;\n\n for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();\n I!=E; ++I)\n if (const Stmt *child = *I) {\n const DeclRefExpr *BR = FindBlockDeclRefExpr(child, VD);\n if (BR)\n return BR;\n }\n\n return NULL;\n}\n\nvoid\nUndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE,\n CheckerContext &C) const {\n if (!BE->getBlockDecl()->hasCaptures())\n return;\n\n ProgramStateRef state = C.getState();\n const BlockDataRegion *R =\n cast<BlockDataRegion>(state->getSVal(BE,\n C.getLocationContext()).getAsRegion());\n\n BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),\n E = R->referenced_vars_end();\n\n for (; I != E; ++I) {\n \/\/ This VarRegion is the region associated with the block; we need\n \/\/ the one associated with the encompassing context.\n const VarRegion *VR = *I;\n const VarDecl *VD = VR->getDecl();\n\n if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage())\n continue;\n\n \/\/ Get the VarRegion associated with VD in the local stack frame.\n const LocationContext *LC = C.getLocationContext();\n VR = C.getSValBuilder().getRegionManager().getVarRegion(VD, LC);\n SVal VRVal = state->getSVal(VR);\n\n if (VRVal.isUndef())\n if (ExplodedNode *N = C.generateSink()) {\n if (!BT)\n BT.reset(new BuiltinBug(\"uninitialized variable captured by block\"));\n\n \/\/ Generate a bug report.\n SmallString<128> buf;\n llvm::raw_svector_ostream os(buf);\n\n os << \"Variable '\" << VD->getName() \n << \"' is uninitialized when captured by block\";\n\n BugReport *R = new BugReport(*BT, os.str(), N);\n if (const Expr *Ex = FindBlockDeclRefExpr(BE->getBody(), VD))\n R->addRange(Ex->getSourceRange());\n R->addVisitor(new FindLastStoreBRVisitor(VRVal, VR));\n R->disablePathPruning();\n \/\/ need location of block\n C.emitReport(R);\n }\n }\n}\n\nvoid ento::registerUndefCapturedBlockVarChecker(CheckerManager &mgr) {\n mgr.registerChecker<UndefCapturedBlockVarChecker>();\n}\n<commit_msg>Use 'getOriginalRegion()' rather than going through the logic to recreate it.<commit_after>\/\/ UndefCapturedBlockVarChecker.cpp - Uninitialized captured vars -*- C++ -*-=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This checker detects blocks that capture uninitialized values.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangSACheckers.h\"\n#include \"clang\/AST\/Attr.h\"\n#include \"clang\/StaticAnalyzer\/Core\/BugReporter\/BugType.h\"\n#include \"clang\/StaticAnalyzer\/Core\/Checker.h\"\n#include \"clang\/StaticAnalyzer\/Core\/CheckerManager.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CheckerContext.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/ExprEngine.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace ento;\n\nnamespace {\nclass UndefCapturedBlockVarChecker\n : public Checker< check::PostStmt<BlockExpr> > {\n mutable OwningPtr<BugType> BT;\n\npublic:\n void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;\n};\n} \/\/ end anonymous namespace\n\nstatic const DeclRefExpr *FindBlockDeclRefExpr(const Stmt *S,\n const VarDecl *VD) {\n if (const DeclRefExpr *BR = dyn_cast<DeclRefExpr>(S))\n if (BR->getDecl() == VD)\n return BR;\n\n for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();\n I!=E; ++I)\n if (const Stmt *child = *I) {\n const DeclRefExpr *BR = FindBlockDeclRefExpr(child, VD);\n if (BR)\n return BR;\n }\n\n return NULL;\n}\n\nvoid\nUndefCapturedBlockVarChecker::checkPostStmt(const BlockExpr *BE,\n CheckerContext &C) const {\n if (!BE->getBlockDecl()->hasCaptures())\n return;\n\n ProgramStateRef state = C.getState();\n const BlockDataRegion *R =\n cast<BlockDataRegion>(state->getSVal(BE,\n C.getLocationContext()).getAsRegion());\n\n BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),\n E = R->referenced_vars_end();\n\n for (; I != E; ++I) {\n \/\/ This VarRegion is the region associated with the block; we need\n \/\/ the one associated with the encompassing context.\n const VarRegion *VR = *I;\n const VarDecl *VD = VR->getDecl();\n\n if (VD->getAttr<BlocksAttr>() || !VD->hasLocalStorage())\n continue;\n\n \/\/ Get the VarRegion associated with VD in the local stack frame.\n SVal VRVal = state->getSVal(I.getOriginalRegion());\n\n if (VRVal.isUndef())\n if (ExplodedNode *N = C.generateSink()) {\n if (!BT)\n BT.reset(new BuiltinBug(\"uninitialized variable captured by block\"));\n\n \/\/ Generate a bug report.\n SmallString<128> buf;\n llvm::raw_svector_ostream os(buf);\n\n os << \"Variable '\" << VD->getName() \n << \"' is uninitialized when captured by block\";\n\n BugReport *R = new BugReport(*BT, os.str(), N);\n if (const Expr *Ex = FindBlockDeclRefExpr(BE->getBody(), VD))\n R->addRange(Ex->getSourceRange());\n R->addVisitor(new FindLastStoreBRVisitor(VRVal, VR));\n R->disablePathPruning();\n \/\/ need location of block\n C.emitReport(R);\n }\n }\n}\n\nvoid ento::registerUndefCapturedBlockVarChecker(CheckerManager &mgr) {\n mgr.registerChecker<UndefCapturedBlockVarChecker>();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"ir.h\"\n#include \"ir_hierarchical_visitor.h\"\n\nir_hierarchical_visitor::ir_hierarchical_visitor()\n{\n this->callback = NULL;\n this->data = NULL;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_variable *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_constant *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_loop_jump *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_dereference_variable *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_loop *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_loop *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_function_signature *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_function_signature *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_function *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_function *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_expression *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_expression *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_texture *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_texture *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_swizzle *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_swizzle *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_dereference_array *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_dereference_array *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_dereference_record *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_dereference_record *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_assignment *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_assignment *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_call *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_call *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_return *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_return *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_discard *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_discard *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_if *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_if *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nvoid\nir_hierarchical_visitor::run(exec_list *instructions)\n{\n visit_list_elements(this, instructions);\n}\n\n\nvoid\nvisit_tree(ir_instruction *ir,\n\t void (*callback)(class ir_instruction *ir, void *data),\n\t void *data)\n{\n ir_hierarchical_visitor v;\n\n v.callback = callback;\n v.data = data;\n\n ir->accept(&v);\n}\n<commit_msg>glsl: Fix uninitialized member in ir_hierarchical_vistor constructor.<commit_after>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"ir.h\"\n#include \"ir_hierarchical_visitor.h\"\n\nir_hierarchical_visitor::ir_hierarchical_visitor()\n{\n this->base_ir = NULL;\n this->callback = NULL;\n this->data = NULL;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_variable *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_constant *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_loop_jump *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit(ir_dereference_variable *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_loop *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_loop *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_function_signature *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_function_signature *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_function *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_function *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_expression *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_expression *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_texture *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_texture *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_swizzle *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_swizzle *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_dereference_array *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_dereference_array *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_dereference_record *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_dereference_record *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_assignment *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_assignment *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_call *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_call *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_return *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_return *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_discard *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_discard *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_enter(ir_if *ir)\n{\n if (this->callback != NULL)\n this->callback(ir, this->data);\n\n return visit_continue;\n}\n\nir_visitor_status\nir_hierarchical_visitor::visit_leave(ir_if *ir)\n{\n (void) ir;\n return visit_continue;\n}\n\nvoid\nir_hierarchical_visitor::run(exec_list *instructions)\n{\n visit_list_elements(this, instructions);\n}\n\n\nvoid\nvisit_tree(ir_instruction *ir,\n\t void (*callback)(class ir_instruction *ir, void *data),\n\t void *data)\n{\n ir_hierarchical_visitor v;\n\n v.callback = callback;\n v.data = data;\n\n ir->accept(&v);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tproxyImage.cpp\n\tArsh Chauhan\n\t05\/02\/2016\n\n\tSource for class Proxyimage\n*\/\n\n#include \"proxyImage.hpp\"\n\n\/*\n\t2 parameter constructor\n\tPre: None\n\tPost: Creates new Proxyimage with filename fileName\n*\/\nProxyimage::Proxyimage(string fileName): fileName_(fileName)\n{\n\tcout << \"Proxy image created for file \" << fileName << endl;\n}\n\n\/*\n\tdisplay\n\tPre: None\n\tPost: Creates a bew RealImage with filename \n\t fileName_ and sets realImage_ to that object\n\t\t Calls RealImage's display function with realImage_\n*\/\nvoid Proxyimage::display()\n{\n\trealImage_ = Realimage(fileName_);\n\trealImage_.display();\n}<commit_msg>Implemented method getFIles to return all files<commit_after>\/*\n\tproxyImage.cpp\n\tArsh Chauhan\n\t05\/02\/2016\n\n\tSource for class Proxyimage\n*\/\n\n#include \"proxyImage.hpp\"\n\nvector<string> Proxyimage::files_;\n\n\/*\n\t2 parameter constructor\n\tPre: None\n\tPost: Creates new Proxyimage with filename fileName\n*\/\nProxyimage::Proxyimage(string fileName): fileName_(fileName)\n{\n\tcout << \"Proxy image created for file \" << fileName_ << endl;\n\tfiles_.push_back(fileName_);\n}\n\n\/*\n\tdisplay\n\tPre: None\n\tPost: Creates a bew RealImage with filename \n\t fileName_ and sets realImage_ to that object\n\t\t Calls RealImage's display function with realImage_\n*\/\nvoid Proxyimage::display()\n{\n\trealImage_ = Realimage(fileName_);\n\trealImage_.display();\n}\n\nvector<string> Proxyimage::getFiles()\n{\n\treturn files_;\n}<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <set>\n#include <list>\n#include <iterator>\n\n#include \"otc\/otcli.h\"\n#include \"otc\/tree_operations.h\"\n#include \"otc\/tree_iter.h\"\nusing namespace otc;\nusing std::vector;\nusing std::unique_ptr;\nusing std::set;\nusing std::list;\nusing std::map;\nusing std::string;\nusing namespace otc;\n\ntypedef TreeMappedWithSplits Tree_t;\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& o, const std::set<T>& s)\n{\n auto it = s.begin();\n o<<*it++;\n for(; it != s.end(); it++)\n o<<\" \"<<*it;\n return o;\n}\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& o, const std::list<T>& s)\n{\n auto it = s.begin();\n o<<*it++;\n for(; it != s.end(); it++)\n o<<\" \"<<*it;\n return o;\n}\n\nstruct RSplit\n{\n set<long> in;\n set<long> out;\n set<long> all;\n RSplit() = default;\n RSplit(const set<long>& i, const set<long>& a)\n :in(i),all(a)\n {\n out = set_difference_as_set(all,in);\n assert(in.size() + out.size() == all.size());\n }\n};\n\nstd::ostream& operator<<(std::ostream& o, const RSplit& s)\n{\n o<<s.in<<\" | \"<<s.out;\n return o;\n}\n\n\/\/\/ Merge components c1 and c2 and return the component name that survived\nlong merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements)\n{\n if (elements[c2].size() > elements[c1].size())\n std::swap(c1,c2);\n\n for(long i:elements[c2])\n component[i] = c1;\n\n elements[c1].splice(elements[c1].begin(), elements[c2]);\n \n return c1;\n}\n\nbool empty_intersection(const set<long>& x, const set<long>& y)\n{\n std::set<long>::const_iterator i = x.begin();\n std::set<long>::const_iterator j = y.begin();\n while (i != x.end() && j != y.end())\n {\n if (*i == *j)\n return false;\n else if (*i < *j)\n ++i;\n else\n ++j;\n }\n return true;\n}\n\n\/\/\/ Construct a tree with all the splits mentioned, and return a null pointer if this is not possible\nunique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits)\n{\n std::unique_ptr<Tree_t> tree(new Tree_t());\n tree->createRoot();\n\n \/\/ 1. First handle trees of size 1 and 2\n if (tips.size() == 1)\n {\n tree->getRoot()->setOttId(*tips.begin());\n return tree;\n }\n else if (tips.size() == 2)\n {\n auto Node1a = tree->createChild(tree->getRoot());\n auto Node1b = tree->createChild(tree->getRoot());\n auto it = tips.begin();\n Node1a->setOttId(*it++);\n Node1b->setOttId(*it++);\n return tree;\n }\n\n \/\/ 2. Initialize the mapping from elements to components\n map<long,long> component; \/\/ element -> component\n map<long,list<long>> elements; \/\/ component -> elements\n for(long i: tips)\n {\n component[i] = i;\n elements[i].push_back(i);\n }\n\n \/\/ 3. For each split, all the leaves in the include group must be in the same component\n for(const auto& split: splits)\n {\n long c1 = -1;\n for(long i: split.in)\n {\n long c2 = component[i];\n if (c1 != -1 and c1 != c2)\n\tmerge_components(c1,c2,component,elements);\n c1 = component[i];\n }\n }\n\n \/\/ 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure\n long first = *tips.begin();\n if (elements[component[first]].size() == tips.size())\n return {};\n\n \/\/ 5. Create the set of tips in each connected component \n map<long,set<long>> subtips;\n for(long c: tips)\n {\n if (c != component[c]) continue;\n \n set<long>& s = subtips[c];\n for(long l: elements[c])\n s.insert(l);\n }\n\n \/\/ 6. Determine the splits that are not satisfied yet and go into each component\n map<long,vector<RSplit>> subsplits;\n for(const auto& split: splits)\n {\n long first = *split.in.begin();\n long c = component[first];\n\n \/\/ if none of the exclude group are in the component, then the split is satisfied by the top-level partition.\n if (empty_intersection(split.out, subtips[c])) continue;\n\n subsplits[c].push_back(split);\n }\n \n \/\/ 7. Recursively solve the sub-problems of the partition components\n for(const auto& x: subtips)\n {\n auto subtree = BUILD(x.second, subsplits[x.first]);\n if (not subtree) return {};\n\n tree->addSubtree(tree->getRoot(), *subtree);\n }\n\n return tree;\n}\n\n\n\/\/\/ Run the BUILD algorithm on the first n splits\nunique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits, int n)\n{\n vector<RSplit> splits2;\n for(int i=0;i<n;i++)\n splits2.push_back(splits[i]);\n return BUILD(tips,splits2);\n}\n\n\/\/\/ Copy node names from taxonomy to tree based on ott ids, and copy the root name also\nvoid add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy)\n{\n map<long,string> names;\n \n \/\/ 1. Determine the names for each ottid\n for(auto nd: iter_post(*taxonomy))\n if (nd->isTip())\n names[nd->getOttId()] = nd->getName();\n \n \/\/ 2. Set the names of nodes based on their ottid\n for(auto nd: iter_post(*tree))\n if (nd->hasOttId())\n nd->setName( names[nd->getOttId()] );\n \n \/\/ 3. Name the root node too\n string rootname = taxonomy->getRoot()->getName();\n tree->getRoot()->setName(rootname);\n}\n\n\/\/\/ Get the list of splits, and add them one at a time if they are consistent with previous splits\nunique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees)\n{\n \/\/ Standardize names to 0..n-1 for this subproblem\n const auto& taxonomy = trees.back();\n auto all_leaves = taxonomy->getRoot()->getData().desIds;\n \n \/\/ 1. Find splits in order of input trees\n vector<RSplit> splits;\n for(const auto& tree: trees)\n {\n auto root = tree->getRoot();\n const auto leafTaxa = root->getData().desIds;\n\n for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves))\n throw OTCError()<<\"OTT Id \"<<leaf<<\" not in taxonomy!\";\n \n for(auto nd: iter_post_const(*tree))\n {\n const auto& descendants = nd->getData().desIds;\n RSplit split{descendants, leafTaxa};\n if (split.in.size()>1 and split.out.size())\n \tsplits.push_back(split);\n }\n }\n\n \/\/ 2. Add splits sequentially if they are consistent with previous splits.\n vector<RSplit> consistent;\n for(const auto& split: splits)\n {\n consistent.push_back(split);\n auto result = BUILD(all_leaves, consistent);\n if (not result)\n {\n consistent.pop_back();\n LOG(DEBUG)<<\"Reject: \"<<split<<\"\\n\";\n }\n else\n LOG(DEBUG)<<\"Keep: \"<<split<<\"\\n\";\n }\n\n \/\/ 3. Construct final tree and add names\n auto tree = BUILD(all_leaves, consistent);\n add_names(tree, taxonomy);\n return tree;\n}\n\nbool handleRequireOttIds(OTCLI & otCLI, const std::string & arg)\n{\n if (arg == \"true\" or arg == \"yes\" or arg == \"True\" or arg == \"Yes\")\n otCLI.getParsingRules().requireOttIds = true;\n else if (arg == \"false\" or arg == \"no\" or arg == \"False\" or arg == \"no\")\n otCLI.getParsingRules().requireOttIds = false;\n else\n return false;\n \n return true;\n}\n\nbool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg)\n{\n if (arg == \"true\" or arg == \"yes\" or arg == \"True\" or arg == \"Yes\")\n otCLI.getParsingRules().pruneUnrecognizedInputTips = true;\n else if (arg == \"false\" or arg == \"no\" or arg == \"False\" or arg == \"no\")\n otCLI.getParsingRules().pruneUnrecognizedInputTips = false;\n else\n return false;\n \n return true;\n}\n\nbool synthesize_taxonomy = false;\n\nbool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg)\n{\n if (arg == \"true\" or \"yes\" or \"True\" or \"Yes\")\n synthesize_taxonomy = true;\n else if (arg == \"false\" or \"no\" or \"False\" or \"no\")\n synthesize_taxonomy = false;\n else\n return false;\n \n return true;\n}\n\nint main(int argc, char *argv[]) {\n OTCLI otCLI(\"otc-solve-subproblem\",\n \"takes at series of tree files. Each is treated as a subproblem.\\n\",\n\t\t\"subproblem.tre\");\n\n otCLI.addFlag('o',\n\t\t \"Require OTT ids. Defaults to true\",\n\t\t handleRequireOttIds,\n\t\t true);\n otCLI.addFlag('p',\n\t\t \"Prune unrecognized tips. Defaults to false\",\n\t\t handlePruneUnrecognizedTips,\n\t\t true);\n otCLI.addFlag('t',\n\t\t \"Synthesize unresolved taxonomy from all mentioned taxa. Defaults to false\",\n\t\t handleSynthesizeTaxonomy,\n\t\t true);\n\n vector<unique_ptr<Tree_t>> trees;\n auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;};\n \n if (argc < 2)\n\tthrow OTCError(\"No subproblem provided!\");\n \n \/\/ I think multiple subproblem files are essentially concatenated.\n \/\/ Is it possible to read a single subproblem from cin?\n if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1))\n std::exit(1);\n\n \/\/ Add fake Ott Ids to tips and compute desIds\n if (not otCLI.getParsingRules().requireOttIds)\n {\n auto& taxonomy = trees.back();\n\n \/\/ 1. Compute mapping from name -> id\n long id = 1;\n map<string,long> name_to_id;\n for(auto nd: iter_pre(*taxonomy))\n\tif (nd->isTip())\n\t{\n\t string name = nd->getName();\n\t if (not name.size())\n\t throw OTCError()<<\"Taxonomy tip has no label or OTT id!\";\n\t auto it = name_to_id.find(name);\n\t if (it != name_to_id.end())\n\t throw OTCError()<<\"Tip label '\"<<name<<\"' occurs twice in taxonomy!\";\n\t name_to_id[name] = id++;\n\t}\n\n \/\/ 2. Set ids\n for(auto& tree: trees)\n\tfor(auto nd: iter_post(*tree))\n\t if (nd->isTip())\n\t {\n\t string name = nd->getName();\n\t if (not name.size())\n\t throw OTCError()<<\"Tip has no label or OTT id!\";\n\t auto it = name_to_id.find(name);\n\t if (it == name_to_id.end())\n\t throw OTCError()<<\"Can't find label '\"<<name<<\"' in taxonomy!\";\n\t auto id = it->second;\n\t nd->setOttId(id);\n\t }\n\n \/\/ 3. Compute DesIds.\n for(auto& tree: trees)\n\tclearAndfillDesIdSets(*tree);\n }\n\n auto tree = combine(trees);\n \n writeTreeAsNewick(std::cout, *tree);\n std::cout<<\"\\n\";\n}\n<commit_msg>Allow generating a taxonomy if one is not supplied.<commit_after>#include <algorithm>\n#include <set>\n#include <list>\n#include <iterator>\n\n#include \"otc\/otcli.h\"\n#include \"otc\/tree_operations.h\"\n#include \"otc\/tree_iter.h\"\nusing namespace otc;\nusing std::vector;\nusing std::unique_ptr;\nusing std::set;\nusing std::list;\nusing std::map;\nusing std::string;\nusing namespace otc;\n\ntypedef TreeMappedWithSplits Tree_t;\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& o, const std::set<T>& s)\n{\n auto it = s.begin();\n o<<*it++;\n for(; it != s.end(); it++)\n o<<\" \"<<*it;\n return o;\n}\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& o, const std::list<T>& s)\n{\n auto it = s.begin();\n o<<*it++;\n for(; it != s.end(); it++)\n o<<\" \"<<*it;\n return o;\n}\n\nstruct RSplit\n{\n set<long> in;\n set<long> out;\n set<long> all;\n RSplit() = default;\n RSplit(const set<long>& i, const set<long>& a)\n :in(i),all(a)\n {\n out = set_difference_as_set(all,in);\n assert(in.size() + out.size() == all.size());\n }\n};\n\nstd::ostream& operator<<(std::ostream& o, const RSplit& s)\n{\n o<<s.in<<\" | \"<<s.out;\n return o;\n}\n\n\/\/\/ Merge components c1 and c2 and return the component name that survived\nlong merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements)\n{\n if (elements[c2].size() > elements[c1].size())\n std::swap(c1,c2);\n\n for(long i:elements[c2])\n component[i] = c1;\n\n elements[c1].splice(elements[c1].begin(), elements[c2]);\n \n return c1;\n}\n\nbool empty_intersection(const set<long>& x, const set<long>& y)\n{\n std::set<long>::const_iterator i = x.begin();\n std::set<long>::const_iterator j = y.begin();\n while (i != x.end() && j != y.end())\n {\n if (*i == *j)\n return false;\n else if (*i < *j)\n ++i;\n else\n ++j;\n }\n return true;\n}\n\n\/\/\/ Construct a tree with all the splits mentioned, and return a null pointer if this is not possible\nunique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits)\n{\n std::unique_ptr<Tree_t> tree(new Tree_t());\n tree->createRoot();\n\n \/\/ 1. First handle trees of size 1 and 2\n if (tips.size() == 1)\n {\n tree->getRoot()->setOttId(*tips.begin());\n return tree;\n }\n else if (tips.size() == 2)\n {\n auto Node1a = tree->createChild(tree->getRoot());\n auto Node1b = tree->createChild(tree->getRoot());\n auto it = tips.begin();\n Node1a->setOttId(*it++);\n Node1b->setOttId(*it++);\n return tree;\n }\n\n \/\/ 2. Initialize the mapping from elements to components\n map<long,long> component; \/\/ element -> component\n map<long,list<long>> elements; \/\/ component -> elements\n for(long i: tips)\n {\n component[i] = i;\n elements[i].push_back(i);\n }\n\n \/\/ 3. For each split, all the leaves in the include group must be in the same component\n for(const auto& split: splits)\n {\n long c1 = -1;\n for(long i: split.in)\n {\n long c2 = component[i];\n if (c1 != -1 and c1 != c2)\n\tmerge_components(c1,c2,component,elements);\n c1 = component[i];\n }\n }\n\n \/\/ 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure\n long first = *tips.begin();\n if (elements[component[first]].size() == tips.size())\n return {};\n\n \/\/ 5. Create the set of tips in each connected component \n map<long,set<long>> subtips;\n for(long c: tips)\n {\n if (c != component[c]) continue;\n \n set<long>& s = subtips[c];\n for(long l: elements[c])\n s.insert(l);\n }\n\n \/\/ 6. Determine the splits that are not satisfied yet and go into each component\n map<long,vector<RSplit>> subsplits;\n for(const auto& split: splits)\n {\n long first = *split.in.begin();\n long c = component[first];\n\n \/\/ if none of the exclude group are in the component, then the split is satisfied by the top-level partition.\n if (empty_intersection(split.out, subtips[c])) continue;\n\n subsplits[c].push_back(split);\n }\n \n \/\/ 7. Recursively solve the sub-problems of the partition components\n for(const auto& x: subtips)\n {\n auto subtree = BUILD(x.second, subsplits[x.first]);\n if (not subtree) return {};\n\n tree->addSubtree(tree->getRoot(), *subtree);\n }\n\n return tree;\n}\n\n\n\/\/\/ Run the BUILD algorithm on the first n splits\nunique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits, int n)\n{\n vector<RSplit> splits2;\n for(int i=0;i<n;i++)\n splits2.push_back(splits[i]);\n return BUILD(tips,splits2);\n}\n\n\/\/\/ Copy node names from taxonomy to tree based on ott ids, and copy the root name also\nvoid add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy)\n{\n map<long,string> names;\n \n \/\/ 1. Determine the names for each ottid\n for(auto nd: iter_post(*taxonomy))\n if (nd->isTip())\n names[nd->getOttId()] = nd->getName();\n \n \/\/ 2. Set the names of nodes based on their ottid\n for(auto nd: iter_post(*tree))\n if (nd->hasOttId())\n nd->setName( names[nd->getOttId()] );\n \n \/\/ 3. Name the root node too\n string rootname = taxonomy->getRoot()->getName();\n tree->getRoot()->setName(rootname);\n}\n\n\/\/\/ Get the list of splits, and add them one at a time if they are consistent with previous splits\nunique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees)\n{\n \/\/ Standardize names to 0..n-1 for this subproblem\n const auto& taxonomy = trees.back();\n auto all_leaves = taxonomy->getRoot()->getData().desIds;\n \n \/\/ 1. Find splits in order of input trees\n vector<RSplit> splits;\n for(const auto& tree: trees)\n {\n auto root = tree->getRoot();\n const auto leafTaxa = root->getData().desIds;\n\n for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves))\n throw OTCError()<<\"OTT Id \"<<leaf<<\" not in taxonomy!\";\n \n for(auto nd: iter_post_const(*tree))\n {\n const auto& descendants = nd->getData().desIds;\n RSplit split{descendants, leafTaxa};\n if (split.in.size()>1 and split.out.size())\n \tsplits.push_back(split);\n }\n }\n\n \/\/ 2. Add splits sequentially if they are consistent with previous splits.\n vector<RSplit> consistent;\n for(const auto& split: splits)\n {\n consistent.push_back(split);\n auto result = BUILD(all_leaves, consistent);\n if (not result)\n {\n consistent.pop_back();\n LOG(DEBUG)<<\"Reject: \"<<split<<\"\\n\";\n }\n else\n LOG(DEBUG)<<\"Keep: \"<<split<<\"\\n\";\n }\n\n \/\/ 3. Construct final tree and add names\n auto tree = BUILD(all_leaves, consistent);\n add_names(tree, taxonomy);\n return tree;\n}\n\nbool handleRequireOttIds(OTCLI & otCLI, const std::string & arg)\n{\n if (arg == \"true\" or arg == \"yes\" or arg == \"True\" or arg == \"Yes\")\n otCLI.getParsingRules().requireOttIds = true;\n else if (arg == \"false\" or arg == \"no\" or arg == \"False\" or arg == \"no\")\n otCLI.getParsingRules().requireOttIds = false;\n else\n return false;\n \n return true;\n}\n\nbool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg)\n{\n if (arg == \"true\" or arg == \"yes\" or arg == \"True\" or arg == \"Yes\")\n otCLI.getParsingRules().pruneUnrecognizedInputTips = true;\n else if (arg == \"false\" or arg == \"no\" or arg == \"False\" or arg == \"no\")\n otCLI.getParsingRules().pruneUnrecognizedInputTips = false;\n else\n return false;\n \n return true;\n}\n\nbool synthesize_taxonomy = false;\n\nbool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg)\n{\n if (arg == \"true\" or \"yes\" or \"True\" or \"Yes\")\n synthesize_taxonomy = true;\n else if (arg == \"false\" or \"no\" or \"False\" or \"no\")\n synthesize_taxonomy = false;\n else\n return false;\n \n return true;\n}\n\nunique_ptr<Tree_t> make_unresolved_tree(const vector<unique_ptr<Tree_t>>& trees, bool use_ids)\n{\n std::unique_ptr<Tree_t> tree(new Tree_t());\n tree->createRoot();\n\n if (use_ids)\n {\n map<long,string> names;\n for(const auto& tree: trees)\n for(auto nd: iter_pre_const(*tree))\n\tif (nd->isTip())\n\t{\n\t long id = nd->getOttId();\n\t auto it = names.find(id);\n\t if (it == names.end())\n\t names[id] = nd->getName();\n\t}\n \n for(const auto& n: names)\n {\n auto node = tree->createChild(tree->getRoot());\n node->setOttId(n.first);\n node->setName(n.second);\n }\n clearAndfillDesIdSets(*tree);\n }\n else\n {\n set<string> names;\n for(const auto& tree: trees)\n for(auto nd: iter_pre_const(*tree))\n\tif (nd->isTip())\n\t names.insert(nd->getName());\n\n for(const auto& n: names)\n {\n auto node = tree->createChild(tree->getRoot());\n node->setName(n);\n }\n }\n\n return tree;\n}\n\nstring newick(const Tree_t &t)\n{\n std::ostringstream s;\n writeTreeAsNewick(s, t);\n return s.str();\n}\n\nint main(int argc, char *argv[]) {\n OTCLI otCLI(\"otc-solve-subproblem\",\n \"takes at series of tree files. Each is treated as a subproblem.\\n\",\n\t\t\"subproblem.tre\");\n\n otCLI.addFlag('o',\n\t\t \"Require OTT ids. Defaults to true\",\n\t\t handleRequireOttIds,\n\t\t true);\n otCLI.addFlag('p',\n\t\t \"Prune unrecognized tips. Defaults to false\",\n\t\t handlePruneUnrecognizedTips,\n\t\t true);\n otCLI.addFlag('T',\n\t\t \"Synthesize unresolved taxonomy from all mentioned taxa. Defaults to false\",\n\t\t handleSynthesizeTaxonomy,\n\t\t false);\n\n vector<unique_ptr<Tree_t>> trees;\n auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;};\n \n if (argc < 2)\n\tthrow OTCError(\"No subproblem provided!\");\n \n \/\/ I think multiple subproblem files are essentially concatenated.\n \/\/ Is it possible to read a single subproblem from cin?\n if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1))\n std::exit(1);\n\n bool requireOttIds = otCLI.getParsingRules().requireOttIds;\n if (synthesize_taxonomy)\n {\n trees.push_back(make_unresolved_tree(trees,requireOttIds));\n LOG(DEBUG)<<\"taxonomy = \"<<newick(*trees.back())<<\"\\n\";\n }\n \n \/\/ Add fake Ott Ids to tips and compute desIds\n if (not requireOttIds)\n {\n auto& taxonomy = trees.back();\n\n \/\/ 1. Compute mapping from name -> id\n long id = 1;\n map<string,long> name_to_id;\n for(auto nd: iter_pre(*taxonomy))\n\tif (nd->isTip())\n\t{\n\t string name = nd->getName();\n\t if (not name.size())\n\t throw OTCError()<<\"Taxonomy tip has no label or OTT id!\";\n\t auto it = name_to_id.find(name);\n\t if (it != name_to_id.end())\n\t throw OTCError()<<\"Tip label '\"<<name<<\"' occurs twice in taxonomy!\";\n\t name_to_id[name] = id++;\n\t}\n\n \/\/ 2. Set ids\n for(auto& tree: trees)\n\tfor(auto nd: iter_post(*tree))\n\t if (nd->isTip())\n\t {\n\t string name = nd->getName();\n\t if (not name.size())\n\t throw OTCError()<<\"Tip has no label or OTT id!\";\n\t auto it = name_to_id.find(name);\n\t if (it == name_to_id.end())\n\t throw OTCError()<<\"Can't find label '\"<<name<<\"' in taxonomy!\";\n\t auto id = it->second;\n\t nd->setOttId(id);\n\t }\n\n \/\/ 3. Compute DesIds.\n for(auto& tree: trees)\n\tclearAndfillDesIdSets(*tree);\n }\n\n auto tree = combine(trees);\n \n writeTreeAsNewick(std::cout, *tree);\n std::cout<<\"\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/ffdc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file ffdc.H\n * @brief Defines the FirstFailureData class\n *\/\n\n#ifndef FAPI2_FFDC_H_\n#define FAPI2_FFDC_H_\n\n#include <memory>\n#include <hwp_return_codes.H>\n#include <return_code_defs.H>\n#include <plat_trace.H>\n#include <error_info.H>\n#include <target.H>\n\nusing fapi2::TARGET_TYPE_ALL;\n\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @brief Check the type of a variable\n\/\/\/\n\/\/\/ This function can be called to check that a variable type is as expected\n\/\/\/ @note This mechanism will allow for cast ctor's which other static type\n\/\/\/ checking might not.\n\/\/\/\ntemplate<typename T>\ninline\nvoid checkType(const T&) {}\n\nclass ReturnCode;\n\n\/\/\/\n\/\/\/ @class FirstFailureData\n\/\/\/\n\/\/\/ This class provides storage and methods for creating and manipulating\n\/\/\/ FFDC.\n\/\/\/ It is not needed on all platforms - platforms which need this class have\n\/\/\/ specified this by forcing their fapi2::ReturnCode to be a subclass of\n\/\/\/ this class.\n\/\/\/\ntemplate< class R = fapi2::ReturnCode >\nclass FirstFailureData\n{\n public:\n\n \/\/\/\n \/\/\/ @brief Default constructor.\n \/\/\/ @note We don't create our error info by default. It will be created\n \/\/\/ when its needed in the setHwpError() method. Note that dereferencing\n \/\/\/ the error info without first calling setHwpError() will create a\n \/\/ problem.\n \/\/\/\n FirstFailureData(void):\n iv_info( nullptr ), iv_platDataPtr(nullptr)\n {}\n\n \/\/\/\n \/\/\/ @brief Copy Constructor\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to copy\n \/\/\/ @note Generates default copy constructor - no deep pointer\n \/\/\/ copies necessary.\n \/\/\/\n FirstFailureData(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Destructor\n \/\/\/\n ~FirstFailureData(void) = default;\n\n \/\/\/\n \/\/\/ @brief Assignment Operator.\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to assign from.\n \/\/\/ @return Reference to 'this' FirstFailureData\n \/\/\/\n FirstFailureData& operator=(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Sets a HWP error. Sets the rcValue to the supplied value (from\n \/\/\/ the HwpFirstFailureData enumeration) and deletes any\n \/\/\/ associated data.\n \/\/\/\n \/\/\/ HWP code must call the FAPI_SET_HWP_ERROR macro rather than this\n \/\/\/ function\n \/\/\/ directly to generate an error so that any error information is\n \/\/\/ automatically added to the FirstFailureData\n \/\/\/\n \/\/\/ @param[in] i_rcValue Error value to set\n \/\/\/\n inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)\n {\n FAPI_ERR(\"_setHwpError: Creating HWP error 0x%x\", i_rcValue);\n static_cast<R*>(this)->operator=(i_rcValue);\n\n \/\/ Forget about any associated data (this is a new error)\n iv_info.reset(new ErrorInfo());\n }\n\n \/\/\/\n \/\/\/ @return void *. Pointer to error info data. If NULL then no data\n \/\/\/\n void* getData(void) const;\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any error info and release ownership from\n \/\/\/ FirstFailureData. The caller is responsible for deletion.\n \/\/\/\n \/\/\/ This is called by PLAT. The expected use-case is to retrieve a\n \/\/\/ platform error log.\n \/\/\/\n \/\/\/ @return void*. Pointer to any Error data. If NULL then no data\n \/\/\/\n inline void* releaseData(void)\n {\n void* l_pData = iv_info;\n iv_info = NULL;\n return l_pData;\n }\n\n \/\/\/\n \/\/\/ @brief Add ErrorInfo\n \/\/\/\n \/\/\/ This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo\n \/\/\/ to the FirstFailureData when a HWP generates an error. The function\n \/\/\/ is designed to add all the ErrorInfo at once rather than the\n \/\/\/ FAPI_SET_HWP_ERROR macro making multiple function calls to add each\n \/\/\/ piece of ErrorInfo individually in order to minimize code size\n \/\/\/\n \/\/\/ @param[in] i_pObjects Pointer to array of const pointers to const\n \/\/\/ objects that are referred to by ErrorInfoEntry objects\n \/\/\/ @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects\n \/\/\/ defining the ErrorInfo that needs to be added\n \/\/\/ @param[in] i_count Number of ErrorInfoEntry entries\n \/\/\/\n void addErrorInfo(const void* const* i_pObjects,\n const ErrorInfoEntry* i_pEntries,\n const uint8_t i_count);\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any ErrorInfo\n \/\/\/\n \/\/\/ This is called by PLAT to find information about an error\n \/\/\/\n \/\/\/ @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info\n \/\/\/\n inline const fapi2::ErrorInfo* getErrorInfo(void) const\n {\n return iv_info.get();\n }\n\n \/\/\/\n \/\/\/ @brief Forgets about any associated data (PlatData and ErrorInfo)\n \/\/\/\n \/\/\/ If this is the only FirstFailureData pointing to the data then the\n \/\/\/ data is deleted\n \/\/\/\n inline void forgetData(void)\n {\n iv_info = nullptr;\n }\n\n \/\/\/\n \/\/\/ @brief Returns the platform data pointer value to the caller.\n \/\/\/\n inline void* getPlatDataPtr()\n {\n return iv_platDataPtr;\n };\n\n \/\/\/\n \/\/\/ @brief Sets objects platform data pointer to the passed in value.\n \/\/\/\n \/\/\/\n inline void setPlatDataPtr( void* i_ptr )\n {\n static_cast<R*>(this)->operator=(FAPI2_RC_PLAT_ERR_SEE_DATA);\n iv_platDataPtr = i_ptr;\n };\n\n private:\n\n \/\/ Pointer to the error info\n std::shared_ptr<ErrorInfo> iv_info;\n\n \/\/ free format data, to be used by the platform\n void* iv_platDataPtr;\n};\n\n}\n#endif \/\/ FAPI2_FFDC_H_\n<commit_msg>Add new addErrorInfo method to enable collectFfdc and collectRegFfdc<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/ffdc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file ffdc.H\n * @brief Defines the FirstFailureData class\n *\/\n\n#ifndef FAPI2_FFDC_H_\n#define FAPI2_FFDC_H_\n\n#include <memory>\n#include <hwp_return_codes.H>\n#include <return_code_defs.H>\n#include <plat_trace.H>\n#include <error_info.H>\n#include <target.H>\n\nusing fapi2::TARGET_TYPE_ALL;\n\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @brief Check the type of a variable\n\/\/\/\n\/\/\/ This function can be called to check that a variable type is as expected\n\/\/\/ @note This mechanism will allow for cast ctor's which other static type\n\/\/\/ checking might not.\n\/\/\/\ntemplate<typename T>\ninline\nvoid checkType(const T&) {}\n\nclass ReturnCode;\n\n\/\/\/\n\/\/\/ @class FirstFailureData\n\/\/\/\n\/\/\/ This class provides storage and methods for creating and manipulating\n\/\/\/ FFDC.\n\/\/\/ It is not needed on all platforms - platforms which need this class have\n\/\/\/ specified this by forcing their fapi2::ReturnCode to be a subclass of\n\/\/\/ this class.\n\/\/\/\ntemplate< class R = fapi2::ReturnCode >\nclass FirstFailureData\n{\n public:\n\n \/\/\/\n \/\/\/ @brief Default constructor.\n \/\/\/ @note We don't create our error info by default. It will be created\n \/\/\/ when its needed in the setHwpError() method. Note that dereferencing\n \/\/\/ the error info without first calling setHwpError() will create a\n \/\/ problem.\n \/\/\/\n FirstFailureData(void):\n iv_info( nullptr ), iv_platDataPtr(nullptr)\n {}\n\n \/\/\/\n \/\/\/ @brief Copy Constructor\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to copy\n \/\/\/ @note Generates default copy constructor - no deep pointer\n \/\/\/ copies necessary.\n \/\/\/\n FirstFailureData(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Destructor\n \/\/\/\n ~FirstFailureData(void) = default;\n\n \/\/\/\n \/\/\/ @brief Assignment Operator.\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to assign from.\n \/\/\/ @return Reference to 'this' FirstFailureData\n \/\/\/\n FirstFailureData& operator=(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Sets a HWP error. Sets the rcValue to the supplied value (from\n \/\/\/ the HwpFirstFailureData enumeration) and deletes any\n \/\/\/ associated data.\n \/\/\/\n \/\/\/ HWP code must call the FAPI_SET_HWP_ERROR macro rather than this\n \/\/\/ function\n \/\/\/ directly to generate an error so that any error information is\n \/\/\/ automatically added to the FirstFailureData\n \/\/\/\n \/\/\/ @param[in] i_rcValue Error value to set\n \/\/\/\n inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)\n {\n FAPI_ERR(\"_setHwpError: Creating HWP error 0x%x\", i_rcValue);\n static_cast<R*>(this)->operator=(i_rcValue);\n\n \/\/ Forget about any associated data (this is a new error)\n iv_info.reset(new ErrorInfo());\n }\n\n \/\/\/\n \/\/\/ @return void *. Pointer to error info data. If NULL then no data\n \/\/\/\n void* getData(void) const;\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any error info and release ownership from\n \/\/\/ FirstFailureData. The caller is responsible for deletion.\n \/\/\/\n \/\/\/ This is called by PLAT. The expected use-case is to retrieve a\n \/\/\/ platform error log.\n \/\/\/\n \/\/\/ @return void*. Pointer to any Error data. If NULL then no data\n \/\/\/\n inline void* releaseData(void)\n {\n void* l_pData = iv_info;\n iv_info = NULL;\n return l_pData;\n }\n\n \/\/\/\n \/\/\/ @brief Add ErrorInfo\n \/\/\/\n \/\/\/ This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo\n \/\/\/ to the FirstFailureData when a HWP generates an error. The function\n \/\/\/ is designed to add all the ErrorInfo at once rather than the\n \/\/\/ FAPI_SET_HWP_ERROR macro making multiple function calls to add each\n \/\/\/ piece of ErrorInfo individually in order to minimize code size\n \/\/\/\n \/\/\/ @param[in] i_pObjects Pointer to array of const pointers to const\n \/\/\/ objects that are referred to by ErrorInfoEntry objects\n \/\/\/ @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects\n \/\/\/ defining the ErrorInfo that needs to be added\n \/\/\/ @param[in] i_count Number of ErrorInfoEntry entries\n \/\/\/\n void addErrorInfo(const void* const* i_pObjects,\n const ErrorInfoEntry* i_pEntries,\n const uint8_t i_count);\n\n\n \/\/\/\n \/\/\/ @brief Add ErrorInfo\n \/\/\/\n \/\/\/ This is called by the collectFfdc and collectRegFfdc functions\n \/\/\/ following the call to actually collect the ffdc data, the ffdc\n \/\/\/ collection functions return a vector of shared pointers to the\n \/\/\/ ErrorInfoFfdc objects\n \/\/\/\n \/\/\/ @param[in] i_errorInfo - vector of shared pointers to\n \/\/\/ errorInfoFfdc objects\n \/\/\/\n inline void addErrorInfo(std::vector<std::shared_ptr<ErrorInfoFfdc>>& i_errorInfo)\n {\n for( auto p : i_errorInfo )\n {\n iv_info->iv_ffdcs.push_back(p);\n }\n };\n\n \/\/\/\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any ErrorInfo\n \/\/\/\n \/\/\/ This is called by PLAT to find information about an error\n \/\/\/\n \/\/\/ @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info\n \/\/\/\n inline const fapi2::ErrorInfo* getErrorInfo(void) const\n {\n return iv_info.get();\n }\n\n \/\/\/\n \/\/\/ @brief Forgets about any associated data (PlatData and ErrorInfo)\n \/\/\/\n \/\/\/ If this is the only FirstFailureData pointing to the data then the\n \/\/\/ data is deleted\n \/\/\/\n inline void forgetData(void)\n {\n iv_info = nullptr;\n }\n\n \/\/\/\n \/\/\/ @brief Returns the platform data pointer value to the caller.\n \/\/\/\n inline void* getPlatDataPtr()\n {\n return iv_platDataPtr;\n };\n\n \/\/\/\n \/\/\/ @brief Sets objects platform data pointer to the passed in value.\n \/\/\/\n \/\/\/\n inline void setPlatDataPtr( void* i_ptr )\n {\n static_cast<R*>(this)->operator=(FAPI2_RC_PLAT_ERR_SEE_DATA);\n iv_platDataPtr = i_ptr;\n };\n\n private:\n\n \/\/ Pointer to the error info\n std::shared_ptr<ErrorInfo> iv_info;\n\n \/\/ free format data, to be used by the platform\n void* iv_platDataPtr;\n};\n\n}\n#endif \/\/ FAPI2_FFDC_H_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/ffdc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file ffdc.H\n * @brief Defines the FirstFailureData class\n *\/\n\n#ifndef FAPI2_FFDC_H_\n#define FAPI2_FFDC_H_\n\n#include <memory>\n#include <hwp_return_codes.H>\n#include <plat_trace.H>\n#include <error_info.H>\n#include <target.H>\n\nusing fapi2::TARGET_TYPE_ALL;\n\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @brief Check the type of a variable\n\/\/\/\n\/\/\/ This function can be called to check that a variable type is as expected\n\/\/\/ @note This mechanism will allow for cast ctor's which other static type\n\/\/\/ checking might not.\n\/\/\/\ntemplate<typename T>\ninline\nvoid checkType(const T&) {}\n\nclass ReturnCode;\n\n\/\/\/\n\/\/\/ @class FirstFailureData\n\/\/\/\n\/\/\/ This class provides storage and methods for creating and manipulating\n\/\/\/ FFDC.\n\/\/\/ It is not needed on all platforms - platforms which need this class have\n\/\/\/ specified this by forcing their fapi2::ReturnCode to be a subclass of\n\/\/\/ this class.\n\/\/\/\ntemplate< class R = fapi2::ReturnCode >\nclass FirstFailureData\n{\n public:\n\n \/\/\/\n \/\/\/ @brief Default constructor.\n \/\/\/ @note We don't create our error info by default. It will be created\n \/\/\/ when its needed in the setHwpError() method. Note that dereferencing\n \/\/\/ the error info without first calling setHwpError() will create a\n \/\/ problem.\n \/\/\/\n FirstFailureData(void):\n iv_info( nullptr ), iv_platDataPtr(nullptr)\n {}\n\n \/\/\/\n \/\/\/ @brief Copy Constructor\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to copy\n \/\/\/ @note Generates default copy constructor - no deep pointer\n \/\/\/ copies necessary.\n \/\/\/\n FirstFailureData(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Destructor\n \/\/\/\n ~FirstFailureData(void) = default;\n\n \/\/\/\n \/\/\/ @brief Assignment Operator.\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to assign from.\n \/\/\/ @return Reference to 'this' FirstFailureData\n \/\/\/\n FirstFailureData& operator=(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Sets a HWP error. Sets the rcValue to the supplied value (from\n \/\/\/ the HwpFirstFailureData enumeration) and deletes any\n \/\/\/ associated data.\n \/\/\/\n \/\/\/ HWP code must call the FAPI_SET_HWP_ERROR macro rather than this\n \/\/\/ function\n \/\/\/ directly to generate an error so that any error information is\n \/\/\/ automatically added to the FirstFailureData\n \/\/\/\n \/\/\/ @param[in] i_rcValue Error value to set\n \/\/\/\n inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)\n {\n FAPI_ERR(\"_setHwpError: Creating HWP error 0x%x\", i_rcValue);\n static_cast<R*>(this)->operator=(i_rcValue);\n\n \/\/ Forget about any associated data (this is a new error)\n iv_info.reset(new ErrorInfo());\n }\n\n \/\/\/\n \/\/\/ @return void *. Pointer to error info data. If NULL then no data\n \/\/\/\n void* getData(void) const;\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any error info and release ownership from\n \/\/\/ FirstFailureData. The caller is responsible for deletion.\n \/\/\/\n \/\/\/ This is called by PLAT. The expected use-case is to retrieve a\n \/\/\/ platform error log.\n \/\/\/\n \/\/\/ @return void*. Pointer to any Error data. If NULL then no data\n \/\/\/\n inline void* releaseData(void)\n {\n void* l_pData = iv_info;\n iv_info = NULL;\n return l_pData;\n }\n\n \/\/\/\n \/\/\/ @brief Add ErrorInfo\n \/\/\/\n \/\/\/ This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo\n \/\/\/ to the FirstFailureData when a HWP generates an error. The function\n \/\/\/ is designed to add all the ErrorInfo at once rather than the\n \/\/\/ FAPI_SET_HWP_ERROR macro making multiple function calls to add each\n \/\/\/ piece of ErrorInfo individually in order to minimize code size\n \/\/\/\n \/\/\/ @param[in] i_pObjects Pointer to array of const pointers to const\n \/\/\/ objects that are referred to by ErrorInfoEntry objects\n \/\/\/ @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects\n \/\/\/ defining the ErrorInfo that needs to be added\n \/\/\/ @param[in] i_count Number of ErrorInfoEntry entries\n \/\/\/\n void addErrorInfo(const void* const* i_pObjects,\n const ErrorInfoEntry* i_pEntries,\n const uint8_t i_count);\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any ErrorInfo\n \/\/\/\n \/\/\/ This is called by PLAT to find information about an error\n \/\/\/\n \/\/\/ @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info\n \/\/\/\n inline const fapi2::ErrorInfo* getErrorInfo(void) const\n {\n return iv_info.get();\n }\n\n \/\/\/\n \/\/\/ @brief Forgets about any associated data (PlatData and ErrorInfo)\n \/\/\/\n \/\/\/ If this is the only FirstFailureData pointing to the data then the\n \/\/\/ data is deleted\n \/\/\/\n inline void forgetData(void)\n {\n iv_info = nullptr;\n }\n\n \/\/\/\n \/\/\/ @brief Returns the platform data pointer value to the caller.\n \/\/\/\n inline void* getPlatDataPtr()\n {\n return iv_platDataPtr;\n };\n\n \/\/\/\n \/\/\/ @brief Sets objects platform data pointer to the passed in value.\n \/\/\/\n \/\/\/\n inline void setPlatDataPtr( void* i_ptr )\n {\n iv_platDataPtr = i_ptr;\n };\n\n private:\n\n \/\/ Pointer to the error info\n std::shared_ptr<ErrorInfo> iv_info;\n\n \/\/ free format data, to be used by the platform\n void* iv_platDataPtr;\n};\n\n}\n#endif \/\/ FAPI2_FFDC_H_\n<commit_msg>Add mcbist L2 function<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/ffdc.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file ffdc.H\n * @brief Defines the FirstFailureData class\n *\/\n\n#ifndef FAPI2_FFDC_H_\n#define FAPI2_FFDC_H_\n\n#include <memory>\n#include <hwp_return_codes.H>\n#include <plat_trace.H>\n#include <error_info.H>\n#include <target.H>\n\nusing fapi2::TARGET_TYPE_ALL;\n\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @brief Check the type of a variable\n\/\/\/\n\/\/\/ This function can be called to check that a variable type is as expected\n\/\/\/ @note This mechanism will allow for cast ctor's which other static type\n\/\/\/ checking might not.\n\/\/\/\ntemplate<typename T>\ninline\nvoid checkType(const T&) {}\n\nclass ReturnCode;\n\n\/\/\/\n\/\/\/ @class FirstFailureData\n\/\/\/\n\/\/\/ This class provides storage and methods for creating and manipulating\n\/\/\/ FFDC.\n\/\/\/ It is not needed on all platforms - platforms which need this class have\n\/\/\/ specified this by forcing their fapi2::ReturnCode to be a subclass of\n\/\/\/ this class.\n\/\/\/\ntemplate< class R = fapi2::ReturnCode >\nclass FirstFailureData\n{\n public:\n\n \/\/\/\n \/\/\/ @brief Default constructor.\n \/\/\/ @note We don't create our error info by default. It will be created\n \/\/\/ when its needed in the setHwpError() method. Note that dereferencing\n \/\/\/ the error info without first calling setHwpError() will create a\n \/\/ problem.\n \/\/\/\n FirstFailureData(void):\n iv_info( nullptr )\n\/\/ iv_info( nullptr ), iv_platDataPtr(nullptr)\n {}\n\n \/\/\/\n \/\/\/ @brief Copy Constructor\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to copy\n \/\/\/ @note Generates default copy constructor - no deep pointer\n \/\/\/ copies necessary.\n \/\/\/\n FirstFailureData(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Destructor\n \/\/\/\n ~FirstFailureData(void) = default;\n\n \/\/\/\n \/\/\/ @brief Assignment Operator.\n \/\/\/\n \/\/\/ @param[in] i_right Reference to FirstFailureData to assign from.\n \/\/\/ @return Reference to 'this' FirstFailureData\n \/\/\/\n FirstFailureData& operator=(const FirstFailureData& i_right) = default;\n\n \/\/\/\n \/\/\/ @brief Sets a HWP error. Sets the rcValue to the supplied value (from\n \/\/\/ the HwpFirstFailureData enumeration) and deletes any\n \/\/\/ associated data.\n \/\/\/\n \/\/\/ HWP code must call the FAPI_SET_HWP_ERROR macro rather than this\n \/\/\/ function\n \/\/\/ directly to generate an error so that any error information is\n \/\/\/ automatically added to the FirstFailureData\n \/\/\/\n \/\/\/ @param[in] i_rcValue Error value to set\n \/\/\/\n inline void _setHwpError(const fapi2::HwpReturnCode i_rcValue)\n {\n FAPI_ERR(\"_setHwpError: Creating HWP error 0x%x\", i_rcValue);\n static_cast<R*>(this)->operator=(i_rcValue);\n\n \/\/ Forget about any associated data (this is a new error)\n iv_info.reset(new ErrorInfo());\n }\n\n \/\/\/\n \/\/\/ @return void *. Pointer to error info data. If NULL then no data\n \/\/\/\n void* getData(void) const;\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any error info and release ownership from\n \/\/\/ FirstFailureData. The caller is responsible for deletion.\n \/\/\/\n \/\/\/ This is called by PLAT. The expected use-case is to retrieve a\n \/\/\/ platform error log.\n \/\/\/\n \/\/\/ @return void*. Pointer to any Error data. If NULL then no data\n \/\/\/\n inline void* releaseData(void)\n {\n void* l_pData = iv_info;\n iv_info = NULL;\n return l_pData;\n }\n\n \/\/\/\n \/\/\/ @brief Add ErrorInfo\n \/\/\/\n \/\/\/ This is called by the FAPI_SET_HWP_ERROR and macro to add ErrorInfo\n \/\/\/ to the FirstFailureData when a HWP generates an error. The function\n \/\/\/ is designed to add all the ErrorInfo at once rather than the\n \/\/\/ FAPI_SET_HWP_ERROR macro making multiple function calls to add each\n \/\/\/ piece of ErrorInfo individually in order to minimize code size\n \/\/\/\n \/\/\/ @param[in] i_pObjects Pointer to array of const pointers to const\n \/\/\/ objects that are referred to by ErrorInfoEntry objects\n \/\/\/ @param[in] i_pEntries Pointer to array of ErrorInfoEntry objects\n \/\/\/ defining the ErrorInfo that needs to be added\n \/\/\/ @param[in] i_count Number of ErrorInfoEntry entries\n \/\/\/\n void addErrorInfo(const void* const* i_pObjects,\n const ErrorInfoEntry* i_pEntries,\n const uint8_t i_count);\n\n \/\/\/\n \/\/\/ @brief Get a pointer to any ErrorInfo\n \/\/\/\n \/\/\/ This is called by PLAT to find information about an error\n \/\/\/\n \/\/\/ @return ErrorInfo *. Pointer to any ErrorInfo. If NULL then no info\n \/\/\/\n inline const fapi2::ErrorInfo* getErrorInfo(void) const\n {\n return iv_info.get();\n }\n\n \/\/\/\n \/\/\/ @brief Forgets about any associated data (PlatData and ErrorInfo)\n \/\/\/\n \/\/\/ If this is the only FirstFailureData pointing to the data then the\n \/\/\/ data is deleted\n \/\/\/\n inline void forgetData(void)\n {\n iv_info = nullptr;\n }\n#if 0\n \/\/\/\n \/\/\/ @brief Returns the platform data pointer value to the caller.\n \/\/\/\n inline void* getPlatDataPtr()\n {\n return iv_platDataPtr;\n };\n\n \/\/\/\n \/\/\/ @brief Sets objects platform data pointer to the passed in value.\n \/\/\/\n \/\/\/\n inline void setPlatDataPtr( void* i_ptr )\n {\n iv_platDataPtr = i_ptr;\n };\n#endif\n private:\n\n \/\/ Pointer to the error info\n std::shared_ptr<ErrorInfo> iv_info;\n\n \/\/ free format data, to be used by the platform\n\/\/ void* iv_platDataPtr;\n};\n\n}\n#endif \/\/ FAPI2_FFDC_H_\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <sys\/ioctl.h>\n#include <netdb.h>\n#include <errno.h>\n#include <stdlib.h>\n\n#include \"NetworkDetect.h\"\n\nINetworkDetection* NetworkDetectionFactory::createNetworkDetection() {\n return new CNetworkDetection();\n}\n\nvoid CNetworkDetection::Cleanup()\n{\n\tstop(1000);\n \n}\n\nvoid CNetworkDetection::Startup()\n{\n}\n\nvoid CNetworkDetection::CheckConnectivity()\n{\n bool bConnectSuccessful = false;\n \n struct addrinfo hints, *result = NULL, *ptr = NULL;\n\tint sockfd = -1;\n memset(&hints,0,sizeof(hints));\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_protocol = IPPROTO_TCP;\n\tchar szPortAsString[5 + 1];\n snprintf(szPortAsString,5,\"%d\",m_iPort);\n\tchar* szHost = new char[m_szHost.length() + 1];\n\tmemset(szHost, 0, m_szHost.length() + 1);\n\tstrcpy(szHost, m_szHost.c_str());\n\tint iResult = getaddrinfo(szHost, szPortAsString, &hints, &result);\n\tif (iResult != 0)\n {\n\t\t\/\/ Log the Fact that we can't get the addr info\n int iErr = errno;\n\t\tm_szLastError = \"Attempted to resolve hostname to connect to but did not succeed, return value (\" + itos(iResult) +\n \"), last error (\" + itos(iErr) + \")\";\n\t\tLOG(INFO) + m_szLastError;\n\t}\n\telse\n\t{\n\t\tptr=result;\n\t\tsockfd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);\n \n\t\tif (sockfd == -1)\n\t\t{\n int iErr = errno;\n\t\t\tm_szLastError = \"Unable to create communications socket, last error was \" + itos(iErr);\n\t\t\tLOG(INFO) + m_szLastError;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint iNonBlockRes = fcntl(sockfd, F_SETFL, O_NONBLOCK);\n\t\t\tif (iNonBlockRes == -1)\n\t\t\t{\n\t\t\t\tm_szLastError = \"Error setting socket into Non Blocking mode\";\n\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint iConnectSuccess = connect(sockfd, ptr->ai_addr, ptr->ai_addrlen);\n\t\t\t\tif (!(iConnectSuccess == -1 && errno == EINPROGRESS))\n\t\t\t\t{\n\t\t\t\t\tm_szLastError = \"Socket Operation unexpectedly blocked, are you connected to a PC?\";\n\t\t\t\t\tLOG(WARNING) + m_szLastError;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfd_set WriteFDs;\n\t\t\t\t\tFD_ZERO(&WriteFDs);\n\t\t\t\t\tFD_SET(sockfd, &WriteFDs);\n timeval to = m_connectionTimeout;\n\t\t\t\t\tint iSelectReturnVal = select(sockfd+1, 0, &WriteFDs, 0, &to);\n\t\t\t\t\tif (iSelectReturnVal > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ We have a socket to connect to\n\t\t\t\t\t\tbConnectSuccessful = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (iSelectReturnVal == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_szLastError = \"Unable to connect to specified host \" + m_szHost + \" on port \" + itos(m_iPort);\n\t\t\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Some form of error occured\n int iErr = errno;\n\t\t\t\t\t\tm_szLastError = \"Unable to connect to specified host, last error was \" + itos(iErr);\n\t\t\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(sockfd);\n\t\t\tsockfd = -1;\n\t\t}\n\t}\n\tdelete[] szHost;\n if (result != 0) {\n freeaddrinfo(result);\n }\n\tif (bConnectSuccessful)\n\t{\n\t\tif (m_NetworkState != NETWORK_CONNECTED)\n\t\t{\n\t\t\tm_NetworkState = NETWORK_CONNECTED;\n\t\t\trho::Hashtable<rho::String, rho::String> detectedCallbackData;\n\t\t\tdetectedCallbackData.put(\"connectionInformation\", \"Connected\");\n\t\t\tdetectedCallbackData.put(\"failureMessage\", \"Connected\");\n\t\t\tm_pDetectCallback.set(detectedCallbackData);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ We are not connected\n\t\tif (m_NetworkState != NETWORK_DISCONNECTED)\n\t\t{\n\t\t\tm_NetworkState = NETWORK_DISCONNECTED;\n\t\t\trho::Hashtable<rho::String, rho::String> detectedCallbackData;\n\t\t\tdetectedCallbackData.put(\"connectionInformation\", \"Disconnected\");\n\t\t\tdetectedCallbackData.put(\"failureMessage\", m_szLastError);\n\t\t\tm_pDetectCallback.set(detectedCallbackData);\n\t\t}\n\t}\n \n}\n\n<commit_msg>Update CNetworkDetect.cpp<commit_after>#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <sys\/ioctl.h>\n#include <netdb.h>\n#include <errno.h>\n#include <stdlib.h>\n\n#include \"NetworkDetect.h\"\n\nINetworkDetection* NetworkDetectionFactory::createNetworkDetection() {\n return new CNetworkDetection();\n}\n\nvoid CNetworkDetection::Cleanup()\n{\n\tstop(1000);\n \n}\n\nvoid CNetworkDetection::Startup()\n{\n}\n\nbool CNetworkDetection::CheckConnectivity()\n{\n bool bConnectSuccessful = false;\n \n struct addrinfo hints, *result = NULL, *ptr = NULL;\n\tint sockfd = -1;\n memset(&hints,0,sizeof(hints));\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_protocol = IPPROTO_TCP;\n\tchar szPortAsString[5 + 1];\n snprintf(szPortAsString,5,\"%d\",m_iPort);\n\tchar* szHost = new char[m_szHost.length() + 1];\n\tmemset(szHost, 0, m_szHost.length() + 1);\n\tstrcpy(szHost, m_szHost.c_str());\n\tint iResult = getaddrinfo(szHost, szPortAsString, &hints, &result);\n\tif (iResult != 0)\n {\n\t\t\/\/ Log the Fact that we can't get the addr info\n int iErr = errno;\n\t\tm_szLastError = \"Attempted to resolve hostname to connect to but did not succeed, return value (\" + itos(iResult) +\n \"), last error (\" + itos(iErr) + \")\";\n\t\tLOG(INFO) + m_szLastError;\n\t}\n\telse\n\t{\n\t\tptr=result;\n\t\tsockfd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);\n \n\t\tif (sockfd == -1)\n\t\t{\n int iErr = errno;\n\t\t\tm_szLastError = \"Unable to create communications socket, last error was \" + itos(iErr);\n\t\t\tLOG(INFO) + m_szLastError;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint iNonBlockRes = fcntl(sockfd, F_SETFL, O_NONBLOCK);\n\t\t\tif (iNonBlockRes == -1)\n\t\t\t{\n\t\t\t\tm_szLastError = \"Error setting socket into Non Blocking mode\";\n\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint iConnectSuccess = connect(sockfd, ptr->ai_addr, ptr->ai_addrlen);\n\t\t\t\tif (!(iConnectSuccess == -1 && errno == EINPROGRESS))\n\t\t\t\t{\n\t\t\t\t\tm_szLastError = \"Socket Operation unexpectedly blocked, are you connected to a PC?\";\n\t\t\t\t\tLOG(WARNING) + m_szLastError;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfd_set WriteFDs;\n\t\t\t\t\tFD_ZERO(&WriteFDs);\n\t\t\t\t\tFD_SET(sockfd, &WriteFDs);\n timeval to = m_connectionTimeout;\n\t\t\t\t\tint iSelectReturnVal = select(sockfd+1, 0, &WriteFDs, 0, &to);\n\t\t\t\t\tif (iSelectReturnVal > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ We have a socket to connect to\n\t\t\t\t\t\tbConnectSuccessful = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (iSelectReturnVal == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_szLastError = \"Unable to connect to specified host \" + m_szHost + \" on port \" + itos(m_iPort);\n\t\t\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Some form of error occured\n int iErr = errno;\n\t\t\t\t\t\tm_szLastError = \"Unable to connect to specified host, last error was \" + itos(iErr);\n\t\t\t\t\t\tLOG(INFO) + m_szLastError;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(sockfd);\n\t\t\tsockfd = -1;\n\t\t}\n\t}\n\tdelete[] szHost;\n if (result != 0) {\n freeaddrinfo(result);\n }\n\tif (bConnectSuccessful)\n\t{\n\t\tif (m_NetworkState != NETWORK_CONNECTED)\n\t\t{\n\t\t\tm_NetworkState = NETWORK_CONNECTED;\n\t\t\trho::Hashtable<rho::String, rho::String> detectedCallbackData;\n\t\t\tdetectedCallbackData.put(\"connectionInformation\", \"Connected\");\n\t\t\tdetectedCallbackData.put(\"failureMessage\", \"Connected\");\n\t\t\tm_pDetectCallback.set(detectedCallbackData);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ We are not connected\n\t\tif (m_NetworkState != NETWORK_DISCONNECTED)\n\t\t{\n\t\t\tm_NetworkState = NETWORK_DISCONNECTED;\n\t\t\trho::Hashtable<rho::String, rho::String> detectedCallbackData;\n\t\t\tdetectedCallbackData.put(\"connectionInformation\", \"Disconnected\");\n\t\t\tdetectedCallbackData.put(\"failureMessage\", m_szLastError);\n\t\t\tm_pDetectCallback.set(detectedCallbackData);\n\t\t}\n\t}\n\treturn bConnectSuccessful;\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ Copyright (c) 2008-2014 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include <Atomic\/Atomic.h>\r\n#include <Atomic\/Engine\/Engine.h>\r\n#include <Atomic\/IO\/FileSystem.h>\r\n#include <Atomic\/IO\/Log.h>\r\n#include <Atomic\/IO\/IOEvents.h>\r\n#include <Atomic\/Input\/InputEvents.h>\r\n#include <Atomic\/Core\/Main.h>\r\n#include <Atomic\/Core\/ProcessUtils.h>\r\n#include <Atomic\/Resource\/ResourceCache.h>\r\n#include <Atomic\/Resource\/ResourceEvents.h>\r\n#include <Atomic\/UI\/UI.h>\r\n\r\n\/\/ Move me\r\n#include <Atomic\/Environment\/Environment.h>\r\n\r\n#include <AtomicJS\/Javascript\/Javascript.h>\r\n\r\n#include <AtomicPlayer\/Player.h>\r\n\r\n#include \"AtomicPlayer.h\"\r\n\r\n#include <Atomic\/DebugNew.h>\r\n\r\n#ifdef __APPLE__\r\n#include <unistd.h>\r\n#endif\r\n\r\nDEFINE_APPLICATION_MAIN(AtomicPlayer::AtomicPlayerApp)\r\n\r\nnamespace AtomicPlayer\r\n{\r\n\r\nextern void jsapi_init_atomicplayer(JSVM* vm);\r\n\r\nAtomicPlayerApp::AtomicPlayerApp(Context* context) :\r\n Application(context)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::Setup()\r\n{\r\n FileSystem* filesystem = GetSubsystem<FileSystem>();\r\n\r\n engineParameters_[\"WindowTitle\"] = \"AtomicPlayer\";\r\n\r\n#if (ATOMIC_PLATFORM_ANDROID)\r\n engineParameters_[\"FullScreen\"] = true;\r\n engineParameters_[\"ResourcePaths\"] = \"CoreData;AtomicResources\";\r\n#elif ATOMIC_PLATFORM_WEB\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n \/\/ engineParameters_[\"WindowWidth\"] = 1280;\r\n \/\/ engineParameters_[\"WindowHeight\"] = 720;\r\n#elif ATOMIC_PLATFORM_IOS\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n#else\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"WindowWidth\"] = 1280;\r\n engineParameters_[\"WindowHeight\"] = 720;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n#endif\r\n\r\n#if ATOMIC_PLATFORM_WINDOWS\r\n engineParameters_[\"WindowIcon\"] = \"Images\/AtomicLogo32.png\";\r\n engineParameters_[\"ResourcePrefixPath\"] = \"AtomicPlayer_Resources\";\r\n#elif ATOMIC_PLATFORM_ANDROID\r\n \/\/engineParameters_[\"ResourcePrefixPath\"] = \"assets\";\r\n#elif ATOMIC_PLATFORM_OSX\r\n engineParameters_[\"ResourcePrefixPath\"] = \"..\/Resources\";\r\n#endif\r\n\r\n const Vector<String>& arguments = GetArguments();\r\n\r\n for (unsigned i = 0; i < arguments.Size(); ++i)\r\n {\r\n if (arguments[i].Length() > 1)\r\n {\r\n String argument = arguments[i].ToLower();\r\n String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;\r\n\r\n if (argument == \"--log-std\")\r\n {\r\n SubscribeToEvent(E_LOGMESSAGE, HANDLER(AtomicPlayerApp, HandleLogMessage));\r\n }\r\n }\r\n }\r\n\r\n \/\/ Use the script file name as the base name for the log file\r\n engineParameters_[\"LogName\"] = filesystem->GetAppPreferencesDir(\"AtomicPlayer\", \"Logs\") + \"AtomicPlayer.log\";\r\n}\r\n\r\nvoid AtomicPlayerApp::Start()\r\n{\r\n Application::Start();\r\n\r\n \/\/ Instantiate and register the Javascript subsystem\r\n Javascript* javascript = new Javascript(context_);\r\n context_->RegisterSubsystem(javascript);\r\n\r\n vm_ = javascript->InstantiateVM(\"MainVM\");\r\n vm_->InitJSContext();\r\n\r\n UI* ui = GetSubsystem<UI>();\r\n ui->Initialize(\"DefaultUI\/language\/lng_en.tb.txt\");\r\n ui->LoadDefaultPlayerSkin();\r\n\r\n SubscribeToEvent(E_JSERROR, HANDLER(AtomicPlayerApp, HandleJSError));\r\n\r\n vm_->SetModuleSearchPaths(\"Modules\");\r\n\r\n \/\/ Instantiate and register the Player subsystem\r\n context_->RegisterSubsystem(new AtomicPlayer::Player(context_));\r\n AtomicPlayer::jsapi_init_atomicplayer(vm_);\r\n\r\n JSVM* vm = JSVM::GetJSVM(0);\r\n\r\n if (!vm->ExecuteMain())\r\n {\r\n SendEvent(E_EXITREQUESTED);\r\n }\r\n\r\n return;\r\n}\r\n\r\nvoid AtomicPlayerApp::Stop()\r\n{\r\n Application::Stop();\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)\r\n{\r\n ErrorExit();\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleLogMessage(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace LogMessage;\r\n\r\n int level = eventData[P_LEVEL].GetInt();\r\n \/\/ The message may be multi-line, so split to rows in that case\r\n Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\\n');\r\n\r\n for (unsigned i = 0; i < rows.Size(); ++i)\r\n {\r\n if (level == LOG_ERROR)\r\n {\r\n fprintf(stderr, \"%s\\n\", rows[i].CString());\r\n }\r\n else\r\n {\r\n fprintf(stdout, \"%s\\n\", rows[i].CString());\r\n }\r\n }\r\n\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleJSError(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace JSError;\r\n \/\/String errName = eventData[P_ERRORNAME].GetString();\r\n \/\/String errStack = eventData[P_ERRORSTACK].GetString();\r\n String errMessage = eventData[P_ERRORMESSAGE].GetString();\r\n String errFilename = eventData[P_ERRORFILENAME].GetString();\r\n int errLineNumber = eventData[P_ERRORLINENUMBER].GetInt();\r\n\r\n String errorString = ToString(\"%s - %s - Line: %i\",\r\n errFilename.CString(), errMessage.CString(), errLineNumber);\r\n\r\n}\r\n\r\n\r\n}\r\n<commit_msg>Shutdown JS vm at application stop<commit_after>\/\/\r\n\/\/ Copyright (c) 2008-2014 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include <Atomic\/Atomic.h>\r\n#include <Atomic\/Engine\/Engine.h>\r\n#include <Atomic\/IO\/FileSystem.h>\r\n#include <Atomic\/IO\/Log.h>\r\n#include <Atomic\/IO\/IOEvents.h>\r\n#include <Atomic\/Input\/InputEvents.h>\r\n#include <Atomic\/Core\/Main.h>\r\n#include <Atomic\/Core\/ProcessUtils.h>\r\n#include <Atomic\/Resource\/ResourceCache.h>\r\n#include <Atomic\/Resource\/ResourceEvents.h>\r\n#include <Atomic\/UI\/UI.h>\r\n\r\n\/\/ Move me\r\n#include <Atomic\/Environment\/Environment.h>\r\n\r\n#include <AtomicJS\/Javascript\/Javascript.h>\r\n\r\n#include <AtomicPlayer\/Player.h>\r\n\r\n#include \"AtomicPlayer.h\"\r\n\r\n#include <Atomic\/DebugNew.h>\r\n\r\n#ifdef __APPLE__\r\n#include <unistd.h>\r\n#endif\r\n\r\nDEFINE_APPLICATION_MAIN(AtomicPlayer::AtomicPlayerApp)\r\n\r\nnamespace AtomicPlayer\r\n{\r\n\r\nextern void jsapi_init_atomicplayer(JSVM* vm);\r\n\r\nAtomicPlayerApp::AtomicPlayerApp(Context* context) :\r\n Application(context)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::Setup()\r\n{\r\n FileSystem* filesystem = GetSubsystem<FileSystem>();\r\n\r\n engineParameters_[\"WindowTitle\"] = \"AtomicPlayer\";\r\n\r\n#if (ATOMIC_PLATFORM_ANDROID)\r\n engineParameters_[\"FullScreen\"] = true;\r\n engineParameters_[\"ResourcePaths\"] = \"CoreData;AtomicResources\";\r\n#elif ATOMIC_PLATFORM_WEB\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n \/\/ engineParameters_[\"WindowWidth\"] = 1280;\r\n \/\/ engineParameters_[\"WindowHeight\"] = 720;\r\n#elif ATOMIC_PLATFORM_IOS\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n#else\r\n engineParameters_[\"FullScreen\"] = false;\r\n engineParameters_[\"WindowWidth\"] = 1280;\r\n engineParameters_[\"WindowHeight\"] = 720;\r\n engineParameters_[\"ResourcePaths\"] = \"AtomicResources\";\r\n#endif\r\n\r\n#if ATOMIC_PLATFORM_WINDOWS\r\n engineParameters_[\"WindowIcon\"] = \"Images\/AtomicLogo32.png\";\r\n engineParameters_[\"ResourcePrefixPath\"] = \"AtomicPlayer_Resources\";\r\n#elif ATOMIC_PLATFORM_ANDROID\r\n \/\/engineParameters_[\"ResourcePrefixPath\"] = \"assets\";\r\n#elif ATOMIC_PLATFORM_OSX\r\n engineParameters_[\"ResourcePrefixPath\"] = \"..\/Resources\";\r\n#endif\r\n\r\n const Vector<String>& arguments = GetArguments();\r\n\r\n for (unsigned i = 0; i < arguments.Size(); ++i)\r\n {\r\n if (arguments[i].Length() > 1)\r\n {\r\n String argument = arguments[i].ToLower();\r\n String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;\r\n\r\n if (argument == \"--log-std\")\r\n {\r\n SubscribeToEvent(E_LOGMESSAGE, HANDLER(AtomicPlayerApp, HandleLogMessage));\r\n }\r\n }\r\n }\r\n\r\n \/\/ Use the script file name as the base name for the log file\r\n engineParameters_[\"LogName\"] = filesystem->GetAppPreferencesDir(\"AtomicPlayer\", \"Logs\") + \"AtomicPlayer.log\";\r\n}\r\n\r\nvoid AtomicPlayerApp::Start()\r\n{\r\n Application::Start();\r\n\r\n \/\/ Instantiate and register the Javascript subsystem\r\n Javascript* javascript = new Javascript(context_);\r\n context_->RegisterSubsystem(javascript);\r\n\r\n vm_ = javascript->InstantiateVM(\"MainVM\");\r\n vm_->InitJSContext();\r\n\r\n UI* ui = GetSubsystem<UI>();\r\n ui->Initialize(\"DefaultUI\/language\/lng_en.tb.txt\");\r\n ui->LoadDefaultPlayerSkin();\r\n\r\n SubscribeToEvent(E_JSERROR, HANDLER(AtomicPlayerApp, HandleJSError));\r\n\r\n vm_->SetModuleSearchPaths(\"Modules\");\r\n\r\n \/\/ Instantiate and register the Player subsystem\r\n context_->RegisterSubsystem(new AtomicPlayer::Player(context_));\r\n AtomicPlayer::jsapi_init_atomicplayer(vm_);\r\n\r\n JSVM* vm = JSVM::GetJSVM(0);\r\n\r\n if (!vm->ExecuteMain())\r\n {\r\n SendEvent(E_EXITREQUESTED);\r\n }\r\n\r\n return;\r\n}\r\n\r\nvoid AtomicPlayerApp::Stop()\r\n{\r\n\r\n vm_ = 0;\r\n context_->RemoveSubsystem<Javascript>();\r\n \/\/ make sure JSVM is really down and no outstanding refs\r\n \/\/ as if not, will hold on engine subsystems, which is bad\r\n assert(!JSVM::GetJSVM(0));\r\n\r\n Application::Stop();\r\n\r\n\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)\r\n{\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)\r\n{\r\n ErrorExit();\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleLogMessage(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace LogMessage;\r\n\r\n int level = eventData[P_LEVEL].GetInt();\r\n \/\/ The message may be multi-line, so split to rows in that case\r\n Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\\n');\r\n\r\n for (unsigned i = 0; i < rows.Size(); ++i)\r\n {\r\n if (level == LOG_ERROR)\r\n {\r\n fprintf(stderr, \"%s\\n\", rows[i].CString());\r\n }\r\n else\r\n {\r\n fprintf(stdout, \"%s\\n\", rows[i].CString());\r\n }\r\n }\r\n\r\n}\r\n\r\nvoid AtomicPlayerApp::HandleJSError(StringHash eventType, VariantMap& eventData)\r\n{\r\n using namespace JSError;\r\n \/\/String errName = eventData[P_ERRORNAME].GetString();\r\n \/\/String errStack = eventData[P_ERRORSTACK].GetString();\r\n String errMessage = eventData[P_ERRORMESSAGE].GetString();\r\n String errFilename = eventData[P_ERRORFILENAME].GetString();\r\n int errLineNumber = eventData[P_ERRORLINENUMBER].GetInt();\r\n\r\n String errorString = ToString(\"%s - %s - Line: %i\",\r\n errFilename.CString(), errMessage.CString(), errLineNumber);\r\n\r\n}\r\n\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 - 2020 Code 4 Game, Org. All Rights Reserved.\n\n#include \"glTFForUE4EdPrivatePCH.h\"\n#include \"glTFFactory.h\"\n\n#include \"glTF\/glTFImporterOptions.h\"\n#include \"glTF\/glTFImporterOptionsWindowEd.h\"\n#include \"glTF\/glTFImporterEd.h\"\n\n#include \"Engine\/StaticMesh.h\"\n#include \"Engine\/SkeletalMesh.h\"\n#include \"Misc\/FeedbackContext.h\"\n#include \"Misc\/Paths.h\"\n\n#include \"ObjectTools.h\"\n\n#define LOCTEXT_NAMESPACE \"glTFForUE4EdModule\"\n\nUglTFFactory::UglTFFactory()\n : Super()\n , ImportClass(nullptr)\n{\n \/\/\n}\n\nUglTFFactory::UglTFFactory(const FObjectInitializer& InObjectInitializer)\n : Super(InObjectInitializer)\n , ImportClass(nullptr)\n{\n if (Formats.Num() > 0) Formats.Empty();\n Formats.Add(TEXT(\"gltf;glTF 2.0\"));\n\n bCreateNew = false;\n bText = true;\n bEditorImport = true;\n}\n\nbool UglTFFactory::DoesSupportClass(UClass* InClass)\n{\n return (InClass == UStaticMesh::StaticClass()\n || InClass == USkeletalMesh::StaticClass());\n}\n\nUClass* UglTFFactory::ResolveSupportedClass()\n{\n if (ImportClass == nullptr) ImportClass = UStaticMesh::StaticClass();\n return ImportClass;\n}\n\nbool UglTFFactory::FactoryCanImport(const FString& InFilePathInOS)\n{\n return FPaths::GetExtension(InFilePathInOS).Equals(TEXT(\"gltf\"), ESearchCase::IgnoreCase);\n}\n\nUObject* UglTFFactory::FactoryCreateText(UClass* InClass, UObject* InParent, FName InName, EObjectFlags InFlags, UObject* InContext, const TCHAR* InType, const TCHAR*& InBuffer, const TCHAR* InBufferEnd, FFeedbackContext* InWarn)\n{\n if (!InBuffer || !InBufferEnd || InBuffer >= InBufferEnd)\n {\n InWarn->Log(ELogVerbosity::Error, FText::Format(NSLOCTEXT(\"glTFForUE4Ed\", \"BufferHasErrorInFactoryCreateText\", \"Buffer has some errors when create the glTF file {0}\"), FText::FromName(InName)).ToString());\n return nullptr;\n }\n\n uint64 BufferSize = InBufferEnd - InBuffer;\n\n FString glTFJson;\n glTFJson.Append(InBuffer, BufferSize);\n return FactoryCreate(InClass, InParent, InName, InFlags, InContext, InType, InWarn, glTFJson);\n}\n\nUObject* UglTFFactory::FactoryCreate(UClass* InClass, UObject* InParent, FName InName, EObjectFlags InFlags, UObject* InContext, const TCHAR* InType, FFeedbackContext* InWarn, const FString& InglTFJson, TSharedPtr<FglTFBuffers> InglTFBuffers \/*= nullptr*\/)\n{\n const FString& FilePathInOS = UFactory::GetCurrentFilename();\n if (!ObjectTools::SanitizeObjectName(FPaths::GetBaseFilename(FilePathInOS)).Equals(InName.ToString()))\n {\n UE_LOG(LogglTFForUE4Ed, Error, TEXT(\"It is different between current filename(%s) and name(%s)!!\"), *FilePathInOS, *InName.ToString());\n return nullptr;\n }\n\n \/\/\/ Parse and check the buffer\n std::shared_ptr<libgltf::SGlTF> GlTF;\n#if defined(UNICODE)\n std::wstring GlTFString = *InglTFJson;\n#else\n std::string GlTFString = *InglTFJson;\n#endif\n if (!(GlTF << GlTFString))\n {\n InWarn->Log(ELogVerbosity::Error, FText::Format(NSLOCTEXT(\"glTFForUE4Ed\", \"FailedToParseTheglTFFile\", \"Failed to parse the glTF file {0}\"), FText::FromName(InName)).ToString());\n return nullptr;\n }\n\n \/\/\/ Open import window, allow to configure some options\n bool bCancel = false;\n TSharedPtr<FglTFImporterOptions> glTFImporterOptions = SglTFImporterOptionsWindowEd::Open(FilePathInOS, InParent->GetPathName(), *GlTF, bCancel);\n if (glTFImporterOptions.IsValid())\n {\n if (glTFImporterOptions->ImportType == EglTFImportType::StaticMesh)\n {\n ImportClass = UStaticMesh::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::SkeletalMesh)\n {\n ImportClass = USkeletalMesh::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::Actor)\n {\n ImportClass = AActor::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::Level)\n {\n ImportClass = ULevel::StaticClass();\n }\n else\n {\n \/\/TODO:\n ImportClass = UStaticMesh::StaticClass();\n }\n }\n if (bCancel)\n {\n UE_LOG(LogglTFForUE4Ed, Display, TEXT(\"Cancel to import the file - %s\"), *FilePathInOS);\n return nullptr;\n }\n if (!glTFImporterOptions.IsValid())\n {\n UE_LOG(LogglTFForUE4Ed, Error, TEXT(\"Failed to open import window\"));\n return nullptr;\n }\n\n if (!InglTFBuffers.IsValid())\n {\n InglTFBuffers = MakeShareable(new FglTFBuffers);\n }\n const FString FolderPathInOS = FPaths::GetPath(glTFImporterOptions->FilePathInOS);\n InglTFBuffers->Cache(FolderPathInOS, GlTF);\n\n return FglTFImporterEd::Get(this, ImportClass, InParent, InName, InFlags, InWarn)->Create(glTFImporterOptions, GlTF, *InglTFBuffers);\n}\n\n#undef LOCTEXT_NAMESPACE\n<commit_msg>[skip ci] convert the `TCHAR` to `WCHAR`<commit_after>\/\/ Copyright 2016 - 2020 Code 4 Game, Org. All Rights Reserved.\n\n#include \"glTFForUE4EdPrivatePCH.h\"\n#include \"glTFFactory.h\"\n\n#include \"glTF\/glTFImporterOptions.h\"\n#include \"glTF\/glTFImporterOptionsWindowEd.h\"\n#include \"glTF\/glTFImporterEd.h\"\n\n#include \"Engine\/StaticMesh.h\"\n#include \"Engine\/SkeletalMesh.h\"\n#include \"Misc\/FeedbackContext.h\"\n#include \"Misc\/Paths.h\"\n\n#include \"ObjectTools.h\"\n\n#define LOCTEXT_NAMESPACE \"glTFForUE4EdModule\"\n\nUglTFFactory::UglTFFactory()\n : Super()\n , ImportClass(nullptr)\n{\n \/\/\n}\n\nUglTFFactory::UglTFFactory(const FObjectInitializer& InObjectInitializer)\n : Super(InObjectInitializer)\n , ImportClass(nullptr)\n{\n if (Formats.Num() > 0) Formats.Empty();\n Formats.Add(TEXT(\"gltf;glTF 2.0\"));\n\n bCreateNew = false;\n bText = true;\n bEditorImport = true;\n}\n\nbool UglTFFactory::DoesSupportClass(UClass* InClass)\n{\n return (InClass == UStaticMesh::StaticClass()\n || InClass == USkeletalMesh::StaticClass());\n}\n\nUClass* UglTFFactory::ResolveSupportedClass()\n{\n if (ImportClass == nullptr) ImportClass = UStaticMesh::StaticClass();\n return ImportClass;\n}\n\nbool UglTFFactory::FactoryCanImport(const FString& InFilePathInOS)\n{\n return FPaths::GetExtension(InFilePathInOS).Equals(TEXT(\"gltf\"), ESearchCase::IgnoreCase);\n}\n\nUObject* UglTFFactory::FactoryCreateText(UClass* InClass, UObject* InParent, FName InName, EObjectFlags InFlags, UObject* InContext, const TCHAR* InType, const TCHAR*& InBuffer, const TCHAR* InBufferEnd, FFeedbackContext* InWarn)\n{\n if (!InBuffer || !InBufferEnd || InBuffer >= InBufferEnd)\n {\n InWarn->Log(ELogVerbosity::Error, FText::Format(NSLOCTEXT(\"glTFForUE4Ed\", \"BufferHasErrorInFactoryCreateText\", \"Buffer has some errors when create the glTF file {0}\"), FText::FromName(InName)).ToString());\n return nullptr;\n }\n\n uint64 BufferSize = InBufferEnd - InBuffer;\n\n FString glTFJson;\n glTFJson.Append(InBuffer, BufferSize);\n return FactoryCreate(InClass, InParent, InName, InFlags, InContext, InType, InWarn, glTFJson);\n}\n\nUObject* UglTFFactory::FactoryCreate(UClass* InClass, UObject* InParent, FName InName, EObjectFlags InFlags, UObject* InContext, const TCHAR* InType, FFeedbackContext* InWarn, const FString& InglTFJson, TSharedPtr<FglTFBuffers> InglTFBuffers \/*= nullptr*\/)\n{\n const FString& FilePathInOS = UFactory::GetCurrentFilename();\n if (!ObjectTools::SanitizeObjectName(FPaths::GetBaseFilename(FilePathInOS)).Equals(InName.ToString()))\n {\n UE_LOG(LogglTFForUE4Ed, Error, TEXT(\"It is different between current filename(%s) and name(%s)!!\"), *FilePathInOS, *InName.ToString());\n return nullptr;\n }\n\n \/\/\/ Parse and check the buffer\n std::shared_ptr<libgltf::SGlTF> GlTF;\n#if defined(UNICODE)\n std::wstring GlTFString = TCHAR_TO_WCHAR(*InglTFJson);\n#else\n std::string GlTFString = *InglTFJson;\n#endif\n if (!(GlTF << GlTFString))\n {\n InWarn->Log(ELogVerbosity::Error, FText::Format(NSLOCTEXT(\"glTFForUE4Ed\", \"FailedToParseTheglTFFile\", \"Failed to parse the glTF file {0}\"), FText::FromName(InName)).ToString());\n return nullptr;\n }\n\n \/\/\/ Open import window, allow to configure some options\n bool bCancel = false;\n TSharedPtr<FglTFImporterOptions> glTFImporterOptions = SglTFImporterOptionsWindowEd::Open(FilePathInOS, InParent->GetPathName(), *GlTF, bCancel);\n if (glTFImporterOptions.IsValid())\n {\n if (glTFImporterOptions->ImportType == EglTFImportType::StaticMesh)\n {\n ImportClass = UStaticMesh::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::SkeletalMesh)\n {\n ImportClass = USkeletalMesh::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::Actor)\n {\n ImportClass = AActor::StaticClass();\n }\n else if (glTFImporterOptions->ImportType == EglTFImportType::Level)\n {\n ImportClass = ULevel::StaticClass();\n }\n else\n {\n \/\/TODO:\n ImportClass = UStaticMesh::StaticClass();\n }\n }\n if (bCancel)\n {\n UE_LOG(LogglTFForUE4Ed, Display, TEXT(\"Cancel to import the file - %s\"), *FilePathInOS);\n return nullptr;\n }\n if (!glTFImporterOptions.IsValid())\n {\n UE_LOG(LogglTFForUE4Ed, Error, TEXT(\"Failed to open import window\"));\n return nullptr;\n }\n\n if (!InglTFBuffers.IsValid())\n {\n InglTFBuffers = MakeShareable(new FglTFBuffers);\n }\n const FString FolderPathInOS = FPaths::GetPath(glTFImporterOptions->FilePathInOS);\n InglTFBuffers->Cache(FolderPathInOS, GlTF);\n\n return FglTFImporterEd::Get(this, ImportClass, InParent, InName, InFlags, InWarn)->Create(glTFImporterOptions, GlTF, *InglTFBuffers);\n}\n\n#undef LOCTEXT_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>#include <rai\/cli\/daemon.hpp>\n\n#include <rai\/working.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <iostream>\n#include <fstream>\n#include <thread>\n\nrai_daemon::daemon_config::daemon_config () :\nrpc_enable (false),\nrpc_address (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4::loopback ())),\nrpc_enable_control (false)\n{\n}\n\nvoid rai_daemon::daemon_config::serialize (std::ostream & output_a)\n{\n boost::property_tree::ptree tree;\n tree.put (\"rpc_address\", rpc_address.to_string ());\n tree.put (\"rpc_port\", std::to_string (rpc_port));\n tree.put (\"rpc_enable\", rpc_enable);\n tree.put (\"rpc_enable_control\", rpc_enable_control);\n\tboost::property_tree::ptree node_l;\n\tnode.serialize_json (node_l);\n\ttree.add_child (\"node\", node_l);\n boost::property_tree::write_json (output_a, tree);\n}\n\nrai_daemon::daemon_config::daemon_config (bool & error_a, std::istream & input_a)\n{\n error_a = false;\n boost::property_tree::ptree tree;\n try\n {\n boost::property_tree::read_json (input_a, tree);\n auto rpc_address_l (tree.get <std::string> (\"rpc_address\"));\n auto rpc_port_l (tree.get <std::string> (\"rpc_port\"));\n rpc_enable = tree.get <bool> (\"rpc_enable\");\n rpc_enable_control = tree.get <bool> (\"rpc_enable_control\");\n auto bootstrap_peers_l (tree.get_child (\"bootstrap_peers\"));\n\t\tauto node_l (tree.get_child (\"node\"));\n\t\terror_a = error_a | node.deserialize_json (node_l);\n try\n {\n rpc_port = std::stoul (rpc_port_l);\n error_a = rpc_port > std::numeric_limits <uint16_t>::max ();\n }\n catch (std::logic_error const &)\n {\n error_a = true;\n }\n boost::system::error_code ec;\n rpc_address = boost::asio::ip::address_v6::from_string (rpc_address_l, ec);\n if (ec)\n {\n error_a = true;\n }\n }\n catch (std::runtime_error const &)\n {\n error_a = true;\n }\n}\n\nrai_daemon::daemon::daemon ()\n{\n}\n\nvoid rai_daemon::daemon::run ()\n{\n auto working (rai::working_path ());\n\tboost::filesystem::create_directories (working);\n auto config_error (false);\n rai_daemon::daemon_config config;\n auto config_path ((working \/ \"config.json\").string ());\n std::ifstream config_file;\n config_file.open (config_path);\n if (!config_file.fail ())\n {\n config = rai_daemon::daemon_config (config_error, config_file);\n }\n else\n {\n std::ofstream config_file;\n config_file.open (config_path);\n if (!config_file.fail ())\n {\n config.serialize (config_file);\n }\n }\n if (!config_error)\n {\n auto service (boost::make_shared <boost::asio::io_service> ());\n auto pool (boost::make_shared <boost::network::utils::thread_pool> ());\n rai::processor_service processor;\n rai::node_init init;\n auto node (std::make_shared <rai::node> (init, service, working, processor, config.node));\n if (!init.error ())\n {\n node->start ();\n rai::rpc rpc (service, pool, config.rpc_address, config.rpc_port, *node, config.rpc_enable_control);\n if (config.rpc_enable)\n {\n rpc.start ();\n }\n std::thread network_thread ([&service] ()\n {\n try\n {\n service->run ();\n }\n catch (...)\n {\n assert (false);\n }\n });\n std::thread processor_thread ([&processor] ()\n {\n try\n {\n processor.run ();\n }\n catch (...)\n {\n assert (false);\n }\n });\n network_thread.join ();\n processor_thread.join ();\n }\n else\n {\n std::cerr << \"Error initializing node\\n\";\n }\n }\n else\n {\n std::cerr << \"Error loading configuration\\n\";\n }\n}\n<commit_msg>Readding default rpc port.<commit_after>#include <rai\/cli\/daemon.hpp>\n\n#include <rai\/working.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <iostream>\n#include <fstream>\n#include <thread>\n\nrai_daemon::daemon_config::daemon_config () :\nrpc_enable (false),\nrpc_address (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4::loopback ())),\nrpc_port (rai::network::rpc_port),\nrpc_enable_control (false)\n{\n}\n\nvoid rai_daemon::daemon_config::serialize (std::ostream & output_a)\n{\n boost::property_tree::ptree tree;\n tree.put (\"rpc_address\", rpc_address.to_string ());\n tree.put (\"rpc_port\", std::to_string (rpc_port));\n tree.put (\"rpc_enable\", rpc_enable);\n tree.put (\"rpc_enable_control\", rpc_enable_control);\n\tboost::property_tree::ptree node_l;\n\tnode.serialize_json (node_l);\n\ttree.add_child (\"node\", node_l);\n boost::property_tree::write_json (output_a, tree);\n}\n\nrai_daemon::daemon_config::daemon_config (bool & error_a, std::istream & input_a)\n{\n error_a = false;\n boost::property_tree::ptree tree;\n try\n {\n boost::property_tree::read_json (input_a, tree);\n auto rpc_address_l (tree.get <std::string> (\"rpc_address\"));\n auto rpc_port_l (tree.get <std::string> (\"rpc_port\"));\n rpc_enable = tree.get <bool> (\"rpc_enable\");\n rpc_enable_control = tree.get <bool> (\"rpc_enable_control\");\n auto bootstrap_peers_l (tree.get_child (\"bootstrap_peers\"));\n\t\tauto node_l (tree.get_child (\"node\"));\n\t\terror_a = error_a | node.deserialize_json (node_l);\n try\n {\n rpc_port = std::stoul (rpc_port_l);\n error_a = rpc_port > std::numeric_limits <uint16_t>::max ();\n }\n catch (std::logic_error const &)\n {\n error_a = true;\n }\n boost::system::error_code ec;\n rpc_address = boost::asio::ip::address_v6::from_string (rpc_address_l, ec);\n if (ec)\n {\n error_a = true;\n }\n }\n catch (std::runtime_error const &)\n {\n error_a = true;\n }\n}\n\nrai_daemon::daemon::daemon ()\n{\n}\n\nvoid rai_daemon::daemon::run ()\n{\n auto working (rai::working_path ());\n\tboost::filesystem::create_directories (working);\n auto config_error (false);\n rai_daemon::daemon_config config;\n auto config_path ((working \/ \"config.json\").string ());\n std::ifstream config_file;\n config_file.open (config_path);\n if (!config_file.fail ())\n {\n config = rai_daemon::daemon_config (config_error, config_file);\n }\n else\n {\n std::ofstream config_file;\n config_file.open (config_path);\n if (!config_file.fail ())\n {\n config.serialize (config_file);\n }\n }\n if (!config_error)\n {\n auto service (boost::make_shared <boost::asio::io_service> ());\n auto pool (boost::make_shared <boost::network::utils::thread_pool> ());\n rai::processor_service processor;\n rai::node_init init;\n auto node (std::make_shared <rai::node> (init, service, working, processor, config.node));\n if (!init.error ())\n {\n node->start ();\n rai::rpc rpc (service, pool, config.rpc_address, config.rpc_port, *node, config.rpc_enable_control);\n if (config.rpc_enable)\n {\n rpc.start ();\n }\n std::thread network_thread ([&service] ()\n {\n try\n {\n service->run ();\n }\n catch (...)\n {\n assert (false);\n }\n });\n std::thread processor_thread ([&processor] ()\n {\n try\n {\n processor.run ();\n }\n catch (...)\n {\n assert (false);\n }\n });\n network_thread.join ();\n processor_thread.join ();\n }\n else\n {\n std::cerr << \"Error initializing node\\n\";\n }\n }\n else\n {\n std::cerr << \"Error loading configuration\\n\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/ImageProcessing.hpp>\n# include <Siv3D\/OpenCV_Bridge.hpp>\n\nnamespace s3d\n{\n\tnamespace detail\n\t{\n\t\tstatic Image GenerateMip(const Image& src)\n\t\t{\n\t\t\tif (not src)\n\t\t\t{\n\t\t\t\treturn{};\n\t\t\t}\n\n\t\t\tconst Color* pSrc = src.data();\n\t\t\tconst int32 srcW = src.width();\n\t\t\tconst int32 srcH = src.height();\n\n\t\t\tconst int32 targetWidth = Max(src.width() \/ 2, 1);\n\t\t\tconst int32 targetHeight = Max(src.height() \/ 2, 1);\n\t\t\tImage result(targetWidth, targetHeight);\n\t\t\tColor* pDst = result.data();\n\n\t\t\tconst float sddx = (srcW - 1.0f) \/ Max(targetWidth - 1, 1);\n\t\t\tconst float sddy = (srcH - 1.0f) \/ Max(targetHeight - 1, 1);\n\n\t\t\tfor (int32 y = 0; y < targetHeight; ++y)\n\t\t\t{\n\t\t\t\tfloat sy = y * sddy;\n\n\t\t\t\tconst int32 dy = static_cast<int32>(sy);\n\n\t\t\t\tsy -= dy;\n\n\t\t\t\tconst int32 dyO = Min(dy + 1, srcH - 1);\n\n\t\t\t\tfor (int32 x = 0; x < targetWidth; ++x)\n\t\t\t\t{\n\t\t\t\t\tfloat sx = x * sddx;\n\n\t\t\t\t\tconst int32 dx = static_cast<int32>(sx);\n\n\t\t\t\t\tsx -= dx;\n\n\t\t\t\t\tconst int32 dxO = Min(dx + 1, srcW - 1);\n\n\t\t\t\t\tconst Color& c0 = pSrc[dy * srcW + dx];\n\t\t\t\t\tconst Color& c1 = pSrc[dy * srcW + dxO];\n\t\t\t\t\tconst Color& c2 = pSrc[dyO * srcW + dx];\n\t\t\t\t\tconst Color& c3 = pSrc[dyO * srcW + dxO];\n\n\t\t\t\t\tconst uint8 r = static_cast<uint8>((c0.r * (1 - sx) + c1.r * sx) * (1 - sy) + (c2.r * (1 - sx) + c3.r * sx) * sy);\n\t\t\t\t\tconst uint8 g = static_cast<uint8>((c0.g * (1 - sx) + c1.g * sx) * (1 - sy) + (c2.g * (1 - sx) + c3.g * sx) * sy);\n\t\t\t\t\tconst uint8 b = static_cast<uint8>((c0.b * (1 - sx) + c1.b * sx) * (1 - sy) + (c2.b * (1 - sx) + c3.b * sx) * sy);\n\t\t\t\t\tconst uint8 a = static_cast<uint8>((c0.a * (1 - sx) + c1.a * sx) * (1 - sy) + (c2.a * (1 - sx) + c3.a * sx) * sy);\n\n\t\t\t\t\t(pDst++)->set(r, g, b, a);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tnamespace ImageProcessing\n\t{\n\t\tArray<Image> GenerateMips(const Image& src)\n\t\t{\n\t\t\tconst size_t mipCount = (CalculateMipCount(src.width(), src.height()) - 1);\n\n\t\t\tif (mipCount < 1)\n\t\t\t{\n\t\t\t\treturn{};\n\t\t\t}\n\n\t\t\tArray<Image> mipImages(mipCount);\n\n\t\t\tmipImages[0] = detail::GenerateMip(src);\n\n\t\t\tfor (size_t i = 1; i < mipCount; ++i)\n\t\t\t{\n\t\t\t\tmipImages[i] = detail::GenerateMip(mipImages[i - 1]);\n\t\t\t}\n\n\t\t\treturn mipImages;\n\t\t}\n\n\t\tvoid Sobel(const Image& src, Image& dst, const int32 dx, const int32 dy, int32 apertureSize)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::Sobel(gray, detected_edges, CV_8U, dx, dy, apertureSize);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Laplacian(const Image& src, Image& dst, int32 apertureSize)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::Laplacian(gray, detected_edges, CV_8U, apertureSize);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Canny(const Image& src, Image& dst, const uint8 lowThreshold, const uint8 highThreshold, int32 apertureSize, const bool useL2Gradient)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::blur(gray, detected_edges, cv::Size(3, 3));\n\t\t\t\tcv::Canny(detected_edges, detected_edges, lowThreshold, highThreshold, apertureSize, useL2Gradient);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid EdgePreservingFilter(const Image& src, Image& dst, EdgePreservingFilterType filterType, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::edgePreservingFilter(matSrc, matDst,\n\t\t\t\t\t(filterType == EdgePreservingFilterType::Recursive)\n\t\t\t\t\t? cv::RECURS_FILTER : cv::NORMCONV_FILTER,\n\t\t\t\t\tstatic_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid DetailEnhance(const Image& src, Image& dst, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::detailEnhance(matSrc, matDst, static_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Stylization(const Image& src, Image& dst, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::stylization(matSrc, matDst, static_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tColorF SSIM(const Image& image1, const Image& image2)\n\t\t{\n\t\t\tif (image1.size() != image2.size())\n\t\t\t{\n\t\t\t\treturn ColorF{ 1.0 };\n\t\t\t}\n\n\t\t\tconst double C1 = 6.5025, C2 = 58.5225;\n\t\t\tconst int32 x = image1.width(), y = image1.height();\n\n\t\t\tcv::Mat_<cv::Vec3f> I1(y, x), I2(y, x);\n\t\t\tOpenCV_Bridge::ToMatVec3f255(image1, I1);\n\t\t\tOpenCV_Bridge::ToMatVec3f255(image2, I2);\n\n\t\t\tcv::Mat I2_2 = I2.mul(I2); \/\/ I2^2\n\t\t\tcv::Mat I1_2 = I1.mul(I1); \/\/ I1^2\n\t\t\tcv::Mat I1_I2 = I1.mul(I2); \/\/ I1 * I2\n\n\t\t\t\/*************************** END INITS **********************************\/\n\n\t\t\tcv::Mat mu1, mu2; \/\/ PRELIMINARY COMPUTING\n\t\t\tcv::GaussianBlur(I1, mu1, cv::Size(11, 11), 1.5);\n\t\t\tcv::GaussianBlur(I2, mu2, cv::Size(11, 11), 1.5);\n\n\n\t\t\tcv::Mat mu1_2 = mu1.mul(mu1);\n\t\t\tcv::Mat mu2_2 = mu2.mul(mu2);\n\t\t\tcv::Mat mu1_mu2 = mu1.mul(mu2);\n\n\t\t\tcv::Mat sigma1_2, sigma2_2, sigma12;\n\n\t\t\tcv::GaussianBlur(I1_2, sigma1_2, cv::Size(11, 11), 1.5);\n\t\t\tsigma1_2 -= mu1_2;\n\n\t\t\tcv::GaussianBlur(I2_2, sigma2_2, cv::Size(11, 11), 1.5);\n\t\t\tsigma2_2 -= mu2_2;\n\n\t\t\tcv::GaussianBlur(I1_I2, sigma12, cv::Size(11, 11), 1.5);\n\t\t\tsigma12 -= mu1_mu2;\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ FORMULA \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\tcv::Mat t1, t2, t3;\n\n\t\t\tt1 = 2 * mu1_mu2 + C1;\n\t\t\tt2 = 2 * sigma12 + C2;\n\t\t\tt3 = t1.mul(t2); \/\/ t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))\n\n\t\t\tt1 = mu1_2 + mu2_2 + C1;\n\t\t\tt2 = sigma1_2 + sigma2_2 + C2;\n\t\t\tt1 = t1.mul(t2); \/\/ t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))\n\n\t\t\tcv::Mat ssim_map;\n\t\t\tcv::divide(t3, t1, ssim_map); \/\/ ssim_map = t3.\/t1;\n\n\t\t\tcv::Scalar mssim = cv::mean(ssim_map); \/\/ mssim = average of ssim map\n\t\t\treturn{ mssim[2], mssim[1], mssim[0], 1.0 };\n\t\t}\n\n\t\tvoid Inpaint(const Image& image, const Image& maskImage, const Color& maskColor, Image& result, int32 radius)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif ((not image) || (not maskImage))\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (image.size() != maskImage.size())\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tradius = Max(radius, 0);\n\t\t\t}\n\n\t\t\t\/\/ 2. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(image);\n\n\t\t\t\tcv::Mat_<uint8> matMask(image.height(), image.width());\n\t\t\t\tOpenCV_Bridge::MaskByColor(maskImage, matMask, maskColor);\n\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::inpaint(matSrc, matMask, matDst, radius, cv::INPAINT_TELEA);\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, result, OverwriteAlpha::Yes);\n\t\t\t}\n\t\t}\n\n\t\tvoid Inpaint(const Image& image, const Grid<uint8>& maskImage, Image& result, int32 radius)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif ((not image) || (not maskImage))\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (image.size() != maskImage.size())\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tradius = Max(radius, 0);\n\t\t\t}\n\n\t\t\t\/\/ 2. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(image);\n\t\t\t\tcv::Mat_<uint8> matMask(static_cast<int32>(maskImage.height()), static_cast<int32>(maskImage.width()), const_cast<uint8*>(maskImage.data()), static_cast<int32>(maskImage.width()));\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::inpaint(matSrc, matMask, matDst, radius, cv::INPAINT_TELEA);\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, result, OverwriteAlpha::Yes);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>[共通] improve GenerateMip()<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/ImageProcessing.hpp>\n# include <Siv3D\/OpenCV_Bridge.hpp>\n\nnamespace s3d\n{\n\tnamespace detail\n\t{\n\t\tstatic Image GenerateMip(const Image& src)\n\t\t{\n\t\t\tif (not src)\n\t\t\t{\n\t\t\t\treturn{};\n\t\t\t}\n\n\t\t\tconst Color* pSrc = src.data();\n\t\t\tconst int32 srcW = src.width();\n\t\t\tconst int32 srcH = src.height();\n\n\t\t\tconst int32 targetWidth = Max(src.width() \/ 2, 1);\n\t\t\tconst int32 targetHeight = Max(src.height() \/ 2, 1);\n\t\t\t\n\t\t\tif ((targetWidth <= 4) && (targetHeight <= 4))\n\t\t\t{\n\t\t\t\treturn src.scaled(targetWidth, targetHeight, InterpolationAlgorithm::Area);\n\t\t\t}\n\t\t\t\n\t\t\tImage result(targetWidth, targetHeight);\n\t\t\tColor* pDst = result.data();\n\n\t\t\tconst float sddx = (srcW - 1.0f) \/ Max(targetWidth - 1, 1);\n\t\t\tconst float sddy = (srcH - 1.0f) \/ Max(targetHeight - 1, 1);\n\n\t\t\tfor (int32 y = 0; y < targetHeight; ++y)\n\t\t\t{\n\t\t\t\tfloat sy = y * sddy;\n\n\t\t\t\tconst int32 dy = static_cast<int32>(sy);\n\n\t\t\t\tsy -= dy;\n\n\t\t\t\tconst int32 dyO = Min(dy + 1, srcH - 1);\n\n\t\t\t\tfor (int32 x = 0; x < targetWidth; ++x)\n\t\t\t\t{\n\t\t\t\t\tfloat sx = x * sddx;\n\n\t\t\t\t\tconst int32 dx = static_cast<int32>(sx);\n\n\t\t\t\t\tsx -= dx;\n\n\t\t\t\t\tconst int32 dxO = Min(dx + 1, srcW - 1);\n\n\t\t\t\t\tconst Color& c0 = pSrc[dy * srcW + dx];\n\t\t\t\t\tconst Color& c1 = pSrc[dy * srcW + dxO];\n\t\t\t\t\tconst Color& c2 = pSrc[dyO * srcW + dx];\n\t\t\t\t\tconst Color& c3 = pSrc[dyO * srcW + dxO];\n\n\t\t\t\t\tconst uint8 r = static_cast<uint8>((c0.r * (1 - sx) + c1.r * sx) * (1 - sy) + (c2.r * (1 - sx) + c3.r * sx) * sy);\n\t\t\t\t\tconst uint8 g = static_cast<uint8>((c0.g * (1 - sx) + c1.g * sx) * (1 - sy) + (c2.g * (1 - sx) + c3.g * sx) * sy);\n\t\t\t\t\tconst uint8 b = static_cast<uint8>((c0.b * (1 - sx) + c1.b * sx) * (1 - sy) + (c2.b * (1 - sx) + c3.b * sx) * sy);\n\t\t\t\t\tconst uint8 a = static_cast<uint8>((c0.a * (1 - sx) + c1.a * sx) * (1 - sy) + (c2.a * (1 - sx) + c3.a * sx) * sy);\n\n\t\t\t\t\t(pDst++)->set(r, g, b, a);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tnamespace ImageProcessing\n\t{\n\t\tArray<Image> GenerateMips(const Image& src)\n\t\t{\n\t\t\tconst size_t mipCount = (CalculateMipCount(src.width(), src.height()) - 1);\n\n\t\t\tif (mipCount < 1)\n\t\t\t{\n\t\t\t\treturn{};\n\t\t\t}\n\n\t\t\tArray<Image> mipImages(mipCount);\n\n\t\t\tmipImages[0] = detail::GenerateMip(src);\n\n\t\t\tfor (size_t i = 1; i < mipCount; ++i)\n\t\t\t{\n\t\t\t\tmipImages[i] = detail::GenerateMip(mipImages[i - 1]);\n\t\t\t}\n\n\t\t\treturn mipImages;\n\t\t}\n\n\t\tvoid Sobel(const Image& src, Image& dst, const int32 dx, const int32 dy, int32 apertureSize)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::Sobel(gray, detected_edges, CV_8U, dx, dy, apertureSize);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Laplacian(const Image& src, Image& dst, int32 apertureSize)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::Laplacian(gray, detected_edges, CV_8U, apertureSize);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Canny(const Image& src, Image& dst, const uint8 lowThreshold, const uint8 highThreshold, int32 apertureSize, const bool useL2Gradient)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (&src == &dst)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (IsEven(apertureSize))\n\t\t\t\t{\n\t\t\t\t\t++apertureSize;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<uint8> gray = OpenCV_Bridge::ToGrayScale(src);\n\t\t\t\tcv::Mat_<uint8> detected_edges;\n\t\t\t\tcv::blur(gray, detected_edges, cv::Size(3, 3));\n\t\t\t\tcv::Canny(detected_edges, detected_edges, lowThreshold, highThreshold, apertureSize, useL2Gradient);\n\t\t\t\tOpenCV_Bridge::FromGrayScale(detected_edges, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid EdgePreservingFilter(const Image& src, Image& dst, EdgePreservingFilterType filterType, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tconst cv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::edgePreservingFilter(matSrc, matDst,\n\t\t\t\t\t(filterType == EdgePreservingFilterType::Recursive)\n\t\t\t\t\t? cv::RECURS_FILTER : cv::NORMCONV_FILTER,\n\t\t\t\t\tstatic_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid DetailEnhance(const Image& src, Image& dst, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::detailEnhance(matSrc, matDst, static_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tvoid Stylization(const Image& src, Image& dst, double sigma_s, double sigma_r)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif (not src)\n\t\t\t\t{\n\t\t\t\t\treturn dst.clear();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ 2. 出力画像のサイズ変更\n\t\t\t{\n\t\t\t\tdst.resize(src.size());\n\t\t\t\tstd::memcpy(dst.data(), src.data(), dst.size_bytes());\n\t\t\t}\n\n\t\t\t\/\/ 3. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(src);\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::stylization(matSrc, matDst, static_cast<float>(sigma_s), static_cast<float>(sigma_r));\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, dst, OverwriteAlpha::No);\n\t\t\t}\n\t\t}\n\n\t\tColorF SSIM(const Image& image1, const Image& image2)\n\t\t{\n\t\t\tif (image1.size() != image2.size())\n\t\t\t{\n\t\t\t\treturn ColorF{ 1.0 };\n\t\t\t}\n\n\t\t\tconst double C1 = 6.5025, C2 = 58.5225;\n\t\t\tconst int32 x = image1.width(), y = image1.height();\n\n\t\t\tcv::Mat_<cv::Vec3f> I1(y, x), I2(y, x);\n\t\t\tOpenCV_Bridge::ToMatVec3f255(image1, I1);\n\t\t\tOpenCV_Bridge::ToMatVec3f255(image2, I2);\n\n\t\t\tcv::Mat I2_2 = I2.mul(I2); \/\/ I2^2\n\t\t\tcv::Mat I1_2 = I1.mul(I1); \/\/ I1^2\n\t\t\tcv::Mat I1_I2 = I1.mul(I2); \/\/ I1 * I2\n\n\t\t\t\/*************************** END INITS **********************************\/\n\n\t\t\tcv::Mat mu1, mu2; \/\/ PRELIMINARY COMPUTING\n\t\t\tcv::GaussianBlur(I1, mu1, cv::Size(11, 11), 1.5);\n\t\t\tcv::GaussianBlur(I2, mu2, cv::Size(11, 11), 1.5);\n\n\n\t\t\tcv::Mat mu1_2 = mu1.mul(mu1);\n\t\t\tcv::Mat mu2_2 = mu2.mul(mu2);\n\t\t\tcv::Mat mu1_mu2 = mu1.mul(mu2);\n\n\t\t\tcv::Mat sigma1_2, sigma2_2, sigma12;\n\n\t\t\tcv::GaussianBlur(I1_2, sigma1_2, cv::Size(11, 11), 1.5);\n\t\t\tsigma1_2 -= mu1_2;\n\n\t\t\tcv::GaussianBlur(I2_2, sigma2_2, cv::Size(11, 11), 1.5);\n\t\t\tsigma2_2 -= mu2_2;\n\n\t\t\tcv::GaussianBlur(I1_I2, sigma12, cv::Size(11, 11), 1.5);\n\t\t\tsigma12 -= mu1_mu2;\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ FORMULA \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\tcv::Mat t1, t2, t3;\n\n\t\t\tt1 = 2 * mu1_mu2 + C1;\n\t\t\tt2 = 2 * sigma12 + C2;\n\t\t\tt3 = t1.mul(t2); \/\/ t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))\n\n\t\t\tt1 = mu1_2 + mu2_2 + C1;\n\t\t\tt2 = sigma1_2 + sigma2_2 + C2;\n\t\t\tt1 = t1.mul(t2); \/\/ t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))\n\n\t\t\tcv::Mat ssim_map;\n\t\t\tcv::divide(t3, t1, ssim_map); \/\/ ssim_map = t3.\/t1;\n\n\t\t\tcv::Scalar mssim = cv::mean(ssim_map); \/\/ mssim = average of ssim map\n\t\t\treturn{ mssim[2], mssim[1], mssim[0], 1.0 };\n\t\t}\n\n\t\tvoid Inpaint(const Image& image, const Image& maskImage, const Color& maskColor, Image& result, int32 radius)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif ((not image) || (not maskImage))\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (image.size() != maskImage.size())\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tradius = Max(radius, 0);\n\t\t\t}\n\n\t\t\t\/\/ 2. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(image);\n\n\t\t\t\tcv::Mat_<uint8> matMask(image.height(), image.width());\n\t\t\t\tOpenCV_Bridge::MaskByColor(maskImage, matMask, maskColor);\n\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::inpaint(matSrc, matMask, matDst, radius, cv::INPAINT_TELEA);\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, result, OverwriteAlpha::Yes);\n\t\t\t}\n\t\t}\n\n\t\tvoid Inpaint(const Image& image, const Grid<uint8>& maskImage, Image& result, int32 radius)\n\t\t{\n\t\t\t\/\/ 1. パラメータチェック\n\t\t\t{\n\t\t\t\tif ((not image) || (not maskImage))\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (image.size() != maskImage.size())\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tradius = Max(radius, 0);\n\t\t\t}\n\n\t\t\t\/\/ 2. 処理\n\t\t\t{\n\t\t\t\tcv::Mat_<cv::Vec3b> matSrc = OpenCV_Bridge::ToMatVec3bBGR(image);\n\t\t\t\tcv::Mat_<uint8> matMask(static_cast<int32>(maskImage.height()), static_cast<int32>(maskImage.width()), const_cast<uint8*>(maskImage.data()), static_cast<int32>(maskImage.width()));\n\t\t\t\tcv::Mat_<cv::Vec3b> matDst;\n\t\t\t\tcv::inpaint(matSrc, matMask, matDst, radius, cv::INPAINT_TELEA);\n\t\t\t\tOpenCV_Bridge::FromMatVec3b(matDst, result, OverwriteAlpha::Yes);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/SimpleAnimation.hpp>\n# include <Siv3D\/Math.hpp>\n\nnamespace s3d\n{\n\tSimpleAnimation::SimpleAnimation(ISteadyClock* pSteadyClock)\n\t\t: m_stopwatch{ StartImmediately::No, pSteadyClock } {}\n\n\tSimpleAnimation& SimpleAnimation::set(const StringView name, const KeyFrame& a, const KeyFrame& b, double func(double))\n\t{\n\t\tif ((b.time <= a.time)\n\t\t\t|| (func == nullptr))\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\tm_animationDurationSec = Max(m_animationDurationSec, b.time.count());\n\n\t\tm_animations[name].push_back({ a, b, func });\n\n\t\tm_animations[name].sort_by([](const Animation& a, const Animation& b) { return (a.a.time < b.a.time); });\n\n\t\treturn *this;\n\t}\n\n\tSimpleAnimation& SimpleAnimation::setLoop(const SecondsF& loopEnd)\n\t{\n\t\tm_loopTiming.first = 0.0;\n\t\tm_loopTiming.second = loopEnd.count();\n\t\treturn *this;\n\t}\n\n\tSimpleAnimation& SimpleAnimation::setLoop(const SecondsF& loopBegin, const SecondsF& loopEnd)\n\t{\n\t\tm_loopTiming.first = loopBegin.count();\n\t\tm_loopTiming.second = loopEnd.count();\n\t\treturn *this;\n\t}\n\n\tdouble SimpleAnimation::operator [](const StringView name) const\n\t{\n\t\tauto it = m_animations.find(name);\n\n\t\tif (it == m_animations.end())\n\t\t{\n\t\t\treturn 0.0;\n\t\t}\n\n\t\treturn GetValue(it->second, posSec());\n\t}\n\n\tvoid SimpleAnimation::start()\n\t{\n\t\tm_stopwatch.start();\n\t}\n\n\tvoid SimpleAnimation::pause()\n\t{\n\t\tm_stopwatch.pause();\n\t}\n\n\tvoid SimpleAnimation::resume()\n\t{\n\t\tm_stopwatch.resume();\n\t}\n\n\tvoid SimpleAnimation::restart()\n\t{\n\t\tm_stopwatch.restart();\n\t}\n\n\tdouble SimpleAnimation::posSec() const\n\t{\n\t\tconst double t = m_stopwatch.sF();\n\n\t\tif (m_loopTiming.second == 0.0)\n\t\t{\n\t\t\treturn t;\n\t\t}\n\n\t\tif (t <= m_loopTiming.second)\n\t\t{\n\t\t\treturn t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double loopLength = (m_loopTiming.second - m_loopTiming.first);\n\n\t\t\tconst double ext = (t - m_loopTiming.second);\n\n\t\t\treturn (m_loopTiming.first + Math::Fmod(ext, loopLength));\n\t\t}\n\t}\n\n\tdouble SimpleAnimation::lengthSec() const noexcept\n\t{\n\t\treturn m_animationDurationSec;\n\t}\n\n\tbool SimpleAnimation::isDone() const\n\t{\n\t\tif (m_loopTiming.second != 0.0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (m_stopwatch.sF() <= m_animationDurationSec);\n\t}\n\n\tsize_t SimpleAnimation::loopCount() const\n\t{\n\t\tif (m_loopTiming.second == 0.0)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst double t = m_stopwatch.sF();\n\n\t\tif (t <= m_loopTiming.second)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double loopLength = (m_loopTiming.second - m_loopTiming.first);\n\n\t\t\tconst double ext = (t - m_loopTiming.second);\n\n\t\t\treturn static_cast<size_t>(1 + (ext \/ loopLength));\n\t\t}\n\t}\n\n\tdouble SimpleAnimation::GetValue(const Array<Animation>& animations, const double timeSec)\n\t{\n\t\tif (timeSec < animations.front().a.time.count())\n\t\t{\n\t\t\treturn animations.front().a.value;\n\t\t}\n\n\t\tif (animations.back().b.time.count() <= timeSec)\n\t\t{\n\t\t\treturn animations.back().b.value;\n\t\t}\n\n\t\tfor (size_t i = 0; i < animations.size(); ++i)\n\t\t{\n\t\t\tconst auto& animation = animations[i];\n\t\t\tconst double tA = animation.a.time.count();\n\t\t\tconst double tB = animation.b.time.count();\n\n\t\t\tif (timeSec < tA)\n\t\t\t{\n\t\t\t\treturn animations[i - 1].b.value;\n\t\t\t}\n\n\t\t\tif (InRange(timeSec, tA, tB))\n\t\t\t{\n\t\t\t\tconst double duration = (tB - tA);\n\t\t\t\tconst double f = ((timeSec - tA) \/ duration);\n\t\t\t\treturn Math::Lerp(animation.a.value, animation.b.value, animation.func(f));\n\t\t\t}\n\t\t}\n\n\t\treturn animations.back().b.value;\n\t}\n}\n<commit_msg>SimpleAnimation::isDone()の戻り値(bool)を修正 (#711)<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/SimpleAnimation.hpp>\n# include <Siv3D\/Math.hpp>\n\nnamespace s3d\n{\n\tSimpleAnimation::SimpleAnimation(ISteadyClock* pSteadyClock)\n\t\t: m_stopwatch{ StartImmediately::No, pSteadyClock } {}\n\n\tSimpleAnimation& SimpleAnimation::set(const StringView name, const KeyFrame& a, const KeyFrame& b, double func(double))\n\t{\n\t\tif ((b.time <= a.time)\n\t\t\t|| (func == nullptr))\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\tm_animationDurationSec = Max(m_animationDurationSec, b.time.count());\n\n\t\tm_animations[name].push_back({ a, b, func });\n\n\t\tm_animations[name].sort_by([](const Animation& a, const Animation& b) { return (a.a.time < b.a.time); });\n\n\t\treturn *this;\n\t}\n\n\tSimpleAnimation& SimpleAnimation::setLoop(const SecondsF& loopEnd)\n\t{\n\t\tm_loopTiming.first = 0.0;\n\t\tm_loopTiming.second = loopEnd.count();\n\t\treturn *this;\n\t}\n\n\tSimpleAnimation& SimpleAnimation::setLoop(const SecondsF& loopBegin, const SecondsF& loopEnd)\n\t{\n\t\tm_loopTiming.first = loopBegin.count();\n\t\tm_loopTiming.second = loopEnd.count();\n\t\treturn *this;\n\t}\n\n\tdouble SimpleAnimation::operator [](const StringView name) const\n\t{\n\t\tauto it = m_animations.find(name);\n\n\t\tif (it == m_animations.end())\n\t\t{\n\t\t\treturn 0.0;\n\t\t}\n\n\t\treturn GetValue(it->second, posSec());\n\t}\n\n\tvoid SimpleAnimation::start()\n\t{\n\t\tm_stopwatch.start();\n\t}\n\n\tvoid SimpleAnimation::pause()\n\t{\n\t\tm_stopwatch.pause();\n\t}\n\n\tvoid SimpleAnimation::resume()\n\t{\n\t\tm_stopwatch.resume();\n\t}\n\n\tvoid SimpleAnimation::restart()\n\t{\n\t\tm_stopwatch.restart();\n\t}\n\n\tdouble SimpleAnimation::posSec() const\n\t{\n\t\tconst double t = m_stopwatch.sF();\n\n\t\tif (m_loopTiming.second == 0.0)\n\t\t{\n\t\t\treturn t;\n\t\t}\n\n\t\tif (t <= m_loopTiming.second)\n\t\t{\n\t\t\treturn t;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double loopLength = (m_loopTiming.second - m_loopTiming.first);\n\n\t\t\tconst double ext = (t - m_loopTiming.second);\n\n\t\t\treturn (m_loopTiming.first + Math::Fmod(ext, loopLength));\n\t\t}\n\t}\n\n\tdouble SimpleAnimation::lengthSec() const noexcept\n\t{\n\t\treturn m_animationDurationSec;\n\t}\n\n\tbool SimpleAnimation::isDone() const\n\t{\n\t\tif (m_loopTiming.second != 0.0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (m_animationDurationSec <= m_stopwatch.sF());\n\t}\n\n\tsize_t SimpleAnimation::loopCount() const\n\t{\n\t\tif (m_loopTiming.second == 0.0)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst double t = m_stopwatch.sF();\n\n\t\tif (t <= m_loopTiming.second)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double loopLength = (m_loopTiming.second - m_loopTiming.first);\n\n\t\t\tconst double ext = (t - m_loopTiming.second);\n\n\t\t\treturn static_cast<size_t>(1 + (ext \/ loopLength));\n\t\t}\n\t}\n\n\tdouble SimpleAnimation::GetValue(const Array<Animation>& animations, const double timeSec)\n\t{\n\t\tif (timeSec < animations.front().a.time.count())\n\t\t{\n\t\t\treturn animations.front().a.value;\n\t\t}\n\n\t\tif (animations.back().b.time.count() <= timeSec)\n\t\t{\n\t\t\treturn animations.back().b.value;\n\t\t}\n\n\t\tfor (size_t i = 0; i < animations.size(); ++i)\n\t\t{\n\t\t\tconst auto& animation = animations[i];\n\t\t\tconst double tA = animation.a.time.count();\n\t\t\tconst double tB = animation.b.time.count();\n\n\t\t\tif (timeSec < tA)\n\t\t\t{\n\t\t\t\treturn animations[i - 1].b.value;\n\t\t\t}\n\n\t\t\tif (InRange(timeSec, tA, tB))\n\t\t\t{\n\t\t\t\tconst double duration = (tB - tA);\n\t\t\t\tconst double f = ((timeSec - tA) \/ duration);\n\t\t\t\treturn Math::Lerp(animation.a.value, animation.b.value, animation.func(f));\n\t\t\t}\n\t\t}\n\n\t\treturn animations.back().b.value;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* tcpstream.cpp\n *\n * cxxtools - general purpose C++-toolbox\n * Copyright (C) 2003 Tommi Maekitalo\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include <sys\/poll.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <errno.h>\n#include <string.h>\n#include \"cxxtools\/log.h\"\n\nlog_define(\"cxxtools.net.tcp\")\n\nnamespace cxxtools\n{\n\nnamespace net\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n listen(ipaddr, port, backlog);\n }\n\n void Server::listen(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n log_debug(\"listen on \" << ipaddr << \" port \" << port << \" backlog \" << backlog);\n\n Addrinfo ai(ipaddr, port);\n\n int reuseAddr = 1;\n\n \/\/ getaddrinfo() may return more than one addrinfo structure, so work\n \/\/ them all out, until we find a pretty useable one\n for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)\n {\n try\n {\n Socket::create(it->ai_family, SOCK_STREAM, 0);\n }\n catch (const Exception&)\n {\n continue;\n }\n\n log_debug(\"setsockopt SO_REUSEADDR\");\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"setsockopt\");\n\n log_debug(\"bind\");\n if (::bind(getFd(), it->ai_addr, it->ai_addrlen) == 0)\n {\n \/\/ save our information\n memmove(&servaddr, it->ai_addr, it->ai_addrlen);\n\n log_debug(\"listen\");\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"listen\");\n\n return;\n }\n }\n\n throw Exception(\"bind\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n accept(server);\n }\n\n Stream::Stream(const std::string& ipaddr, unsigned short int port)\n {\n connect(ipaddr, port);\n }\n\n void Stream::accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n log_debug(\"accept \" << server.getFd());\n int fd = ::accept(server.getFd(), reinterpret_cast <struct sockaddr *> (&peeraddr), &peeraddr_len);\n if (fd < 0)\n throw Exception(\"accept\");\n setFd(fd);\n log_debug(\"accepted \" << server.getFd() << \" => \" << getFd());\n }\n\n void Stream::connect(const std::string& ipaddr, unsigned short int port)\n {\n log_debug(\"connect to \" << ipaddr << \" port \" << port);\n\n Addrinfo ai(ipaddr, port);\n\n log_debug(\"do connect\");\n for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)\n {\n try\n {\n Socket::create(it->ai_family, SOCK_STREAM, 0);\n }\n catch (const Exception&)\n {\n continue;\n }\n\n if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)\n {\n \/\/ save our information\n memmove(&peeraddr, it->ai_addr, it->ai_addrlen);\n return;\n }\n\n if (errno == EINPROGRESS && getTimeout() > 0)\n {\n poll(POLLOUT);\n\n int sockerr;\n socklen_t optlen = sizeof(sockerr);\n if (::getsockopt(getFd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0)\n {\n ::close(getFd());\n throw Exception(\"getsockopt\");\n }\n\n if (sockerr != 0)\n throw Exception(sockerr, \"connect\");\n\n \/\/ save our information\n memmove(&peeraddr, it->ai_addr, it->ai_addrlen);\n return;\n }\n\n }\n\n throw Exception(\"connect\");\n }\n\n Stream::size_type Stream::read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n do\n {\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0 && errno != ECONNRESET)\n throw Exception(errno, \"read\");\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n do\n {\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_debug(\"read timeout (\" << getTimeout() << \"ms)\");\n throw Timeout();\n }\n\n if (poll(POLLIN) & POLLHUP)\n {\n log_debug(\"eof in read\");\n return 0;\n }\n\n do\n {\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n throw Exception(\"read\");\n }\n else if (errno != 0 && errno != ECONNRESET)\n throw Exception(\"read\");\n }\n\n }\n\n return n < 0 ? 0 : n;\n }\n\n Stream::size_type Stream::write(const char* buffer,\n Stream::size_type bufsize, bool flush) const\n {\n log_debug(\"Stream::write \" << bufsize << \" bytes\");\n\n ssize_t n = 0;\n size_type s = bufsize; \/\/ number of bytes left\n\n while (true)\n {\n do\n {\n n = ::write(getFd(), buffer, s);\n log_debug(\"::write returns \" << n << \" errno=\" << errno);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n {\n if (errno == EAGAIN)\n n = 0;\n else\n {\n log_error(\"error in write; errno=\" << errno << \" (\" << strerror(errno) << ')');\n throw Exception(\"write\");\n }\n }\n\n buffer += n;\n s -= n;\n\n if (s > 0 && n > 0 && !flush)\n {\n log_debug(\"partial write; \" << n << \" bytes written from \" << bufsize << \"; return \" << (bufsize - s));\n return bufsize - s;\n }\n\n if (s <= 0)\n break;\n\n if (getTimeout() <= 0)\n {\n log_debug(\"write timeout (\" << getTimeout() << \"ms)\");\n throw Timeout();\n }\n\n if (poll(POLLOUT) & POLLHUP)\n {\n log_debug(\"eof in write\");\n return bufsize - s;\n }\n }\n\n log_debug(\"full write - return \" << bufsize);\n return bufsize;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n log_debug(\"streambuf::overflow\");\n\n if (pptr())\n {\n Stream::size_type N = pptr() - m_buffer; \/\/ bytes to write\n Stream::size_type n = m_stream.write(m_buffer, N, false);\n if (n <= 0)\n return traits_type::eof();\n\n if (n < N)\n {\n \/\/ there are bytes left - move them to the start of our buffer\n memmove(m_buffer, m_buffer + n, N - n);\n setp(m_buffer + N - n, m_buffer + m_bufsize);\n }\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n else\n setp(m_buffer, m_buffer + m_bufsize);\n\n if (c != traits_type::eof())\n {\n *pptr() = traits_type::to_char_type(c);\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n log_debug(\"streambuf::underflow\");\n\n Stream::size_type n = m_stream.read(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return traits_type::to_int_type(m_buffer[0]);\n }\n\n int streambuf::sync()\n {\n log_debug(\"streambuf::sync\");\n\n if (pptr())\n {\n Stream::size_type N = pptr() - m_buffer; \/\/ bytes to write\n if (N > 0)\n {\n Stream::size_type n = m_stream.write(m_buffer, N);\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n }\n return 0;\n }\n\n} \/\/ namespace net\n\n} \/\/ namespace cxxtools\n<commit_msg>use separate input and output buffers in tcpstream<commit_after>\/* tcpstream.cpp\n *\n * cxxtools - general purpose C++-toolbox\n * Copyright (C) 2003 Tommi Maekitalo\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include <sys\/poll.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <errno.h>\n#include <string.h>\n#include \"cxxtools\/log.h\"\n\nlog_define(\"cxxtools.net.tcp\")\n\nnamespace cxxtools\n{\n\nnamespace net\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n listen(ipaddr, port, backlog);\n }\n\n void Server::listen(const std::string& ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n log_debug(\"listen on \" << ipaddr << \" port \" << port << \" backlog \" << backlog);\n\n Addrinfo ai(ipaddr, port);\n\n int reuseAddr = 1;\n\n \/\/ getaddrinfo() may return more than one addrinfo structure, so work\n \/\/ them all out, until we find a pretty useable one\n for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)\n {\n try\n {\n Socket::create(it->ai_family, SOCK_STREAM, 0);\n }\n catch (const Exception&)\n {\n continue;\n }\n\n log_debug(\"setsockopt SO_REUSEADDR\");\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"setsockopt\");\n\n log_debug(\"bind\");\n if (::bind(getFd(), it->ai_addr, it->ai_addrlen) == 0)\n {\n \/\/ save our information\n memmove(&servaddr, it->ai_addr, it->ai_addrlen);\n\n log_debug(\"listen\");\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"listen\");\n\n return;\n }\n }\n\n throw Exception(\"bind\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n accept(server);\n }\n\n Stream::Stream(const std::string& ipaddr, unsigned short int port)\n {\n connect(ipaddr, port);\n }\n\n void Stream::accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n log_debug(\"accept \" << server.getFd());\n int fd = ::accept(server.getFd(), reinterpret_cast <struct sockaddr *> (&peeraddr), &peeraddr_len);\n if (fd < 0)\n throw Exception(\"accept\");\n setFd(fd);\n log_debug(\"accepted \" << server.getFd() << \" => \" << getFd());\n }\n\n void Stream::connect(const std::string& ipaddr, unsigned short int port)\n {\n log_debug(\"connect to \" << ipaddr << \" port \" << port);\n\n Addrinfo ai(ipaddr, port);\n\n log_debug(\"do connect\");\n for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)\n {\n try\n {\n Socket::create(it->ai_family, SOCK_STREAM, 0);\n }\n catch (const Exception&)\n {\n continue;\n }\n\n if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)\n {\n \/\/ save our information\n memmove(&peeraddr, it->ai_addr, it->ai_addrlen);\n return;\n }\n\n if (errno == EINPROGRESS && getTimeout() > 0)\n {\n poll(POLLOUT);\n\n int sockerr;\n socklen_t optlen = sizeof(sockerr);\n if (::getsockopt(getFd(), SOL_SOCKET, SO_ERROR, &sockerr, &optlen) != 0)\n {\n ::close(getFd());\n throw Exception(\"getsockopt\");\n }\n\n if (sockerr != 0)\n throw Exception(sockerr, \"connect\");\n\n \/\/ save our information\n memmove(&peeraddr, it->ai_addr, it->ai_addrlen);\n return;\n }\n\n }\n\n throw Exception(\"connect\");\n }\n\n Stream::size_type Stream::read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n do\n {\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0 && errno != ECONNRESET)\n throw Exception(errno, \"read\");\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n do\n {\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_debug(\"read timeout (\" << getTimeout() << \"ms)\");\n throw Timeout();\n }\n\n if (poll(POLLIN) & POLLHUP)\n {\n log_debug(\"eof in read\");\n return 0;\n }\n\n do\n {\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n throw Exception(\"read\");\n }\n else if (errno != 0 && errno != ECONNRESET)\n throw Exception(\"read\");\n }\n\n }\n\n return n < 0 ? 0 : n;\n }\n\n Stream::size_type Stream::write(const char* buffer,\n Stream::size_type bufsize, bool flush) const\n {\n log_debug(\"Stream::write \" << bufsize << \" bytes\");\n\n ssize_t n = 0;\n size_type s = bufsize; \/\/ number of bytes left\n\n while (true)\n {\n do\n {\n n = ::write(getFd(), buffer, s);\n log_debug(\"::write returns \" << n << \" errno=\" << errno);\n } while (n < 0 && errno == EINTR);\n\n if (n < 0)\n {\n if (errno == EAGAIN)\n n = 0;\n else\n {\n log_error(\"error in write; errno=\" << errno << \" (\" << strerror(errno) << ')');\n throw Exception(\"write\");\n }\n }\n\n buffer += n;\n s -= n;\n\n if (s > 0 && n > 0 && !flush)\n {\n log_debug(\"partial write; \" << n << \" bytes written from \" << bufsize << \"; return \" << (bufsize - s));\n return bufsize - s;\n }\n\n if (s <= 0)\n break;\n\n if (getTimeout() <= 0)\n {\n log_debug(\"write timeout (\" << getTimeout() << \"ms)\");\n throw Timeout();\n }\n\n if (poll(POLLOUT) & POLLHUP)\n {\n log_debug(\"eof in write\");\n return bufsize - s;\n }\n }\n\n log_debug(\"full write - return \" << bufsize);\n return bufsize;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize * 2])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n log_debug(\"streambuf::overflow\");\n\n if (pptr())\n {\n Stream::size_type N = pptr() - m_buffer; \/\/ bytes to write\n Stream::size_type n = m_stream.write(m_buffer, N, false);\n if (n <= 0)\n return traits_type::eof();\n\n if (n < N)\n {\n \/\/ there are bytes left - move them to the start of our buffer\n memmove(m_buffer, m_buffer + n, N - n);\n setp(m_buffer + N - n, m_buffer + m_bufsize);\n }\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n else\n setp(m_buffer, m_buffer + m_bufsize);\n\n if (c != traits_type::eof())\n {\n *pptr() = traits_type::to_char_type(c);\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n log_debug(\"streambuf::underflow\");\n\n Stream::size_type n = m_stream.read(m_buffer + m_bufsize, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer + m_bufsize, m_buffer + m_bufsize, m_buffer + m_bufsize + n);\n return traits_type::to_int_type(m_buffer[m_bufsize]);\n }\n\n int streambuf::sync()\n {\n log_debug(\"streambuf::sync\");\n\n if (pptr())\n {\n Stream::size_type N = pptr() - m_buffer; \/\/ bytes to write\n if (N > 0)\n {\n Stream::size_type n = m_stream.write(m_buffer, N);\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n }\n return 0;\n }\n\n} \/\/ namespace net\n\n} \/\/ namespace cxxtools\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\r\n\/\/ Main source file\r\n\/\/==============================================================================\r\n\r\n#include \"common.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <iostream>\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QCoreApplication>\r\n#include <QDir>\r\n#include <QFileInfo>\r\n#include <QPointer>\r\n#include <QProcess>\r\n\r\n\/\/==============================================================================\r\n\r\nusing namespace OpenCOR;\r\n\r\n\/\/==============================================================================\r\n\r\nint main(int pArgc, char *pArgv[])\r\n{\r\n \/\/ Create the application\r\n\r\n QCoreApplication *app = new QCoreApplication(pArgc, pArgv);\r\n\r\n \/\/ Some general initialisations\r\n\r\n initApplication(app);\r\n\r\n \/\/ Try to run OpenCOR as a console application\r\n\r\n int res;\r\n\r\n if (!consoleApplication(app, &res)) {\r\n \/\/ OpenCOR wasn't run as a proper console application, so start its GUI\r\n \/\/ version instead\r\n\r\n static const QString dotExe = \".exe\";\r\n\r\n if (app->applicationFilePath().right(dotExe.size()) == dotExe) {\r\n \/\/ This is a safeguard from accidentally running a non-renamed (to\r\n \/\/ '.com') console version of OpenCOR\r\n\r\n error(app, \"the console version of \"+app->applicationName()+\" has the wrong extension ('.exe' instead of '.com').\");\r\n\r\n res = -1;\r\n } else {\r\n QString guiAppFilePath = app->applicationDirPath()+QDir::separator()+app->applicationName()+dotExe;\r\n\r\n if (!QFileInfo(guiAppFilePath).exists()) {\r\n \/\/ We can't find the GUI version of OpenCOR, so...\r\n\r\n error(app, \"the GUI version of \"+app->applicationName()+\" cannot be found.\");\r\n\r\n res = -1;\r\n } else {\r\n QProcess().startDetached(guiAppFilePath, app->arguments(), QProcess().workingDirectory());\r\n\r\n res = 0;\r\n }\r\n }\r\n }\r\n\r\n \/\/ Release some memory\r\n\r\n delete app;\r\n\r\n \/\/ We are done, so...\r\n\r\n return res;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<commit_msg>Some minor cleaning up (#57).<commit_after>\/\/==============================================================================\r\n\/\/ Main source file\r\n\/\/==============================================================================\r\n\r\n#include \"common.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <iostream>\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QCoreApplication>\r\n#include <QDir>\r\n#include <QFileInfo>\r\n#include <QPointer>\r\n#include <QProcess>\r\n\r\n\/\/==============================================================================\r\n\r\nint main(int pArgc, char *pArgv[])\r\n{\r\n \/\/ Create the application\r\n\r\n QCoreApplication *app = new QCoreApplication(pArgc, pArgv);\r\n\r\n \/\/ Some general initialisations\r\n\r\n OpenCOR::initApplication(app);\r\n\r\n \/\/ Try to run OpenCOR as a console application\r\n\r\n int res;\r\n\r\n if (!OpenCOR::consoleApplication(app, &res)) {\r\n \/\/ OpenCOR wasn't run as a proper console application, so start its GUI\r\n \/\/ version instead\r\n\r\n static const QString dotExe = \".exe\";\r\n\r\n if (app->applicationFilePath().right(dotExe.size()) == dotExe) {\r\n \/\/ This is a safeguard from accidentally running a non-renamed (to\r\n \/\/ '.com') console version of OpenCOR\r\n\r\n OpenCOR::error(app, \"the console version of \"+app->applicationName()+\" has the wrong extension ('.exe' instead of '.com').\");\r\n\r\n res = -1;\r\n } else {\r\n QString guiAppFilePath = app->applicationDirPath()+QDir::separator()+app->applicationName()+dotExe;\r\n\r\n if (!QFileInfo(guiAppFilePath).exists()) {\r\n \/\/ We can't find the GUI version of OpenCOR, so...\r\n\r\n OpenCOR::error(app, \"the GUI version of \"+app->applicationName()+\" cannot be found.\");\r\n\r\n res = -1;\r\n } else {\r\n QProcess().startDetached(guiAppFilePath, app->arguments(), QProcess().workingDirectory());\r\n\r\n res = 0;\r\n }\r\n }\r\n }\r\n\r\n \/\/ Release some memory\r\n\r\n delete app;\r\n\r\n \/\/ We are done, so...\r\n\r\n return res;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/dom\/DOMArrayBufferDeallocationObserver.h\"\n\n#include \"wtf\/StdLibExtras.h\"\n#include <v8.h>\n\nnamespace blink {\n\nDOMArrayBufferDeallocationObserver* DOMArrayBufferDeallocationObserver::instance()\n{\n DEFINE_STATIC_LOCAL(DOMArrayBufferDeallocationObserver, deallocationObserver, ());\n return &deallocationObserver;\n}\n\nvoid DOMArrayBufferDeallocationObserver::arrayBufferDeallocated(unsigned sizeInBytes)\n{\n v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-static_cast<int>(sizeInBytes));\n}\n\nvoid DOMArrayBufferDeallocationObserver::blinkAllocatedMemory(unsigned sizeInBytes)\n{\n v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(static_cast<int>(sizeInBytes));\n}\n\n} \/\/ namespace blink\n<commit_msg>bindings: Makes DOMArrayBufferDeallocationObserver::instance thread-safe.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/dom\/DOMArrayBufferDeallocationObserver.h\"\n\n#include \"wtf\/Threading.h\"\n#include <v8.h>\n\nnamespace blink {\n\nDOMArrayBufferDeallocationObserver* DOMArrayBufferDeallocationObserver::instance()\n{\n AtomicallyInitializedStatic(\n DOMArrayBufferDeallocationObserver*,\n deallocationObserver = new DOMArrayBufferDeallocationObserver);\n return deallocationObserver;\n}\n\nvoid DOMArrayBufferDeallocationObserver::arrayBufferDeallocated(unsigned sizeInBytes)\n{\n v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-static_cast<int>(sizeInBytes));\n}\n\nvoid DOMArrayBufferDeallocationObserver::blinkAllocatedMemory(unsigned sizeInBytes)\n{\n v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(static_cast<int>(sizeInBytes));\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: itkListSampleTest.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) Insight Software Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even \nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkArray.h\"\n#include \"itkListSample.h\"\n\nint itkListSampleTest(int argc, char *argv[] ) \n{\n std::cout << \"ListSample Test \\n \\n\"; \n if( argc< 2 ) \n {\n std::cerr << \"itkListSampleTest LengthOfMeasurementVector\" << std::endl;\n }\n \n typedef itk::Array< float > MeasurementVectorType ;\n typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;\n\n SampleType::MeasurementVectorSizeType measurementVectorSize = atoi(argv[1]);\n std::cerr << \"Measurement vector size: \" << measurementVectorSize \n << std::endl;\n\n unsigned int sampleSize = 25;\n\n SampleType::Pointer sample = SampleType::New() ;\n\n sample->SetMeasurementVectorSize( measurementVectorSize );\n\n MeasurementVectorType mv( measurementVectorSize ) ;\n for ( unsigned int i = 0 ; i < sampleSize ; i++ )\n {\n for (unsigned int j = 0 ; j < measurementVectorSize ; j++ )\n {\n mv[j] = rand() \/ (RAND_MAX+1.0) ;\n }\n sample->PushBack(mv) ;\n }\n\n \/\/ tests begin\n\n \/\/\n \/\/ general interface\n \/\/\n std::cerr << \"General interface...\" << std::endl;\n if ( sampleSize != sample->Size() )\n {\n std::cerr << \"Size() failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if (sample->GetMeasurementVectorSize() != measurementVectorSize)\n {\n std::cerr << \"GetMeasurementVectorSize() failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ get and set measurements\n mv = sample->GetMeasurementVector(4) ;\n if ( mv != sample->GetMeasurementVector(4) )\n {\n std::cerr << \"GetMeasurementVector failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n float tmp = mv[0];\n mv[0] += 1.0;\n sample->SetMeasurementVector(4,mv);\n if (mv != sample->GetMeasurementVector(4))\n {\n std::cerr << \"SetMeasurementVector failed\" << std::endl;\n return EXIT_FAILURE;\n } \n\n mv[0] = tmp;\n sample->SetMeasurement(4,0,tmp);\n if (mv != sample->GetMeasurementVector(4))\n {\n std::cerr << \"SetMeasurement failed\" << std::endl;\n return EXIT_FAILURE;\n } \n \n \/\/ frequency\n if (sample->GetTotalFrequency() != sampleSize)\n {\n std::cerr << \"GetTotalFrequency failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/\n \/\/ iterator tests\n \/\/\n std::cerr << \"Iterators...\" << std::endl;\n {\n \/\/ forward iterator\n SampleType::Iterator s_iter = sample->Begin() ;\n \n \/\/ copy constructor\n SampleType::Iterator bs_iter(s_iter);\n if (bs_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n SampleType::InstanceIdentifier id = 0 ;\n while (s_iter != sample->End())\n {\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (s_iter.GetFrequency() != 1)\n {\n std::cerr << \"Iterator::GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n if (sample->GetFrequency(id) != 1)\n {\n std::cerr << \"GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n ++id ;\n ++s_iter ;\n }\n \n if (s_iter != sample->End())\n {\n std::cerr << \"Iterator::End (forward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n \/\/ backwards iterator\n do \n {\n --s_iter;\n --id;\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n } \n } while (!(s_iter == sample->Begin())); \/\/ explicitly test ==\n \n if (!(s_iter == sample->Begin()))\n {\n std::cerr << \"Iterator::Begin (backward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n }\n\n \/\/ ConstIterator test\n std::cerr << \"Const Iterators...\" << std::endl;\n {\n \/\/ forward iterator\n SampleType::ConstIterator s_iter = sample->Begin() ;\n \n \/\/ copy constructor\n SampleType::ConstIterator bs_iter(s_iter);\n if (bs_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor (from const) failed\" \n << std::endl;\n return EXIT_FAILURE; \n }\n\n \/\/ copy from non-const iterator\n SampleType::Iterator nonconst_iter = sample->Begin();\n SampleType::ConstIterator s2_iter(nonconst_iter);\n if (s2_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor (from non-const) failed\" \n << std::endl;\n return EXIT_FAILURE; \n }\n \/\/ assignment from non-const iterator\n s2_iter = nonconst_iter;\n if (s2_iter != s_iter)\n {\n std::cerr << \"Iterator::assignment (from non-const) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n SampleType::InstanceIdentifier id = 0 ;\n while (s_iter != sample->End())\n {\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (s_iter.GetFrequency() != 1)\n {\n std::cerr << \"Iterator::GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n ++id ;\n ++s_iter ;\n }\n \n if (s_iter != sample->End())\n {\n std::cerr << \"Iterator::End (forward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n \/\/ backwards iterator\n do \n {\n --s_iter;\n --id;\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n } \n } while (!(s_iter == sample->Begin())); \/\/ explicitly test ==\n \n if (!(s_iter == sample->Begin()))\n {\n std::cerr << \"Iterator::Begin (backward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n }\n\n std::cerr << \"Search...\" << std::endl; \n SampleType::SearchResultVectorType searchResult ;\n sample->Search(sample->GetMeasurementVector(sampleSize\/2), 0.01, \n searchResult) ;\n\n\n \/\/\n \/\/ resizing\n \/\/\n sample->Clear();\n if (sample->Size() != 0)\n {\n std::cerr << \"Clear() failed\" << std::endl;\n return EXIT_FAILURE; \n }\n\n sample->Resize(sampleSize);\n if (sample->Size() != sampleSize)\n {\n std::cerr << \"Resize() failed\" << std::endl;\n return EXIT_FAILURE; \n }\n}\n\n\n\n<commit_msg>BUG: added back return of EXIT_SUCCESS---it was accidentally removed<commit_after>\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: itkListSampleTest.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) Insight Software Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even \nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n#include \"itkArray.h\"\n#include \"itkListSample.h\"\n\nint itkListSampleTest(int argc, char *argv[] ) \n{\n std::cout << \"ListSample Test \\n \\n\"; \n if( argc< 2 ) \n {\n std::cerr << \"itkListSampleTest LengthOfMeasurementVector\" << std::endl;\n }\n \n typedef itk::Array< float > MeasurementVectorType ;\n typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;\n\n SampleType::MeasurementVectorSizeType measurementVectorSize = atoi(argv[1]);\n std::cerr << \"Measurement vector size: \" << measurementVectorSize \n << std::endl;\n\n unsigned int sampleSize = 25;\n\n SampleType::Pointer sample = SampleType::New() ;\n\n sample->SetMeasurementVectorSize( measurementVectorSize );\n\n MeasurementVectorType mv( measurementVectorSize ) ;\n for ( unsigned int i = 0 ; i < sampleSize ; i++ )\n {\n for (unsigned int j = 0 ; j < measurementVectorSize ; j++ )\n {\n mv[j] = rand() \/ (RAND_MAX+1.0) ;\n }\n sample->PushBack(mv) ;\n }\n\n \/\/ tests begin\n\n \/\/\n \/\/ general interface\n \/\/\n std::cerr << \"General interface...\" << std::endl;\n if ( sampleSize != sample->Size() )\n {\n std::cerr << \"Size() failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if (sample->GetMeasurementVectorSize() != measurementVectorSize)\n {\n std::cerr << \"GetMeasurementVectorSize() failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ get and set measurements\n mv = sample->GetMeasurementVector(4) ;\n if ( mv != sample->GetMeasurementVector(4) )\n {\n std::cerr << \"GetMeasurementVector failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n float tmp = mv[0];\n mv[0] += 1.0;\n sample->SetMeasurementVector(4,mv);\n if (mv != sample->GetMeasurementVector(4))\n {\n std::cerr << \"SetMeasurementVector failed\" << std::endl;\n return EXIT_FAILURE;\n } \n\n mv[0] = tmp;\n sample->SetMeasurement(4,0,tmp);\n if (mv != sample->GetMeasurementVector(4))\n {\n std::cerr << \"SetMeasurement failed\" << std::endl;\n return EXIT_FAILURE;\n } \n \n \/\/ frequency\n if (sample->GetTotalFrequency() != sampleSize)\n {\n std::cerr << \"GetTotalFrequency failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/\n \/\/ iterator tests\n \/\/\n std::cerr << \"Iterators...\" << std::endl;\n {\n \/\/ forward iterator\n SampleType::Iterator s_iter = sample->Begin() ;\n \n \/\/ copy constructor\n SampleType::Iterator bs_iter(s_iter);\n if (bs_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n SampleType::InstanceIdentifier id = 0 ;\n while (s_iter != sample->End())\n {\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (s_iter.GetFrequency() != 1)\n {\n std::cerr << \"Iterator::GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n if (sample->GetFrequency(id) != 1)\n {\n std::cerr << \"GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n ++id ;\n ++s_iter ;\n }\n \n if (s_iter != sample->End())\n {\n std::cerr << \"Iterator::End (forward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n \/\/ backwards iterator\n do \n {\n --s_iter;\n --id;\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n } \n } while (!(s_iter == sample->Begin())); \/\/ explicitly test ==\n \n if (!(s_iter == sample->Begin()))\n {\n std::cerr << \"Iterator::Begin (backward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n }\n\n \/\/ ConstIterator test\n std::cerr << \"Const Iterators...\" << std::endl;\n {\n \/\/ forward iterator\n SampleType::ConstIterator s_iter = sample->Begin() ;\n \n \/\/ copy constructor\n SampleType::ConstIterator bs_iter(s_iter);\n if (bs_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor (from const) failed\" \n << std::endl;\n return EXIT_FAILURE; \n }\n\n \/\/ copy from non-const iterator\n SampleType::Iterator nonconst_iter = sample->Begin();\n SampleType::ConstIterator s2_iter(nonconst_iter);\n if (s2_iter != s_iter)\n {\n std::cerr << \"Iterator::Copy Constructor (from non-const) failed\" \n << std::endl;\n return EXIT_FAILURE; \n }\n \/\/ assignment from non-const iterator\n s2_iter = nonconst_iter;\n if (s2_iter != s_iter)\n {\n std::cerr << \"Iterator::assignment (from non-const) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n SampleType::InstanceIdentifier id = 0 ;\n while (s_iter != sample->End())\n {\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (forward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (s_iter.GetFrequency() != 1)\n {\n std::cerr << \"Iterator::GetFrequency (forward) failed\" << std::endl;\n return EXIT_FAILURE;\n }\n ++id ;\n ++s_iter ;\n }\n \n if (s_iter != sample->End())\n {\n std::cerr << \"Iterator::End (forward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n \n \/\/ backwards iterator\n do \n {\n --s_iter;\n --id;\n if (sample->GetMeasurementVector(id) != \n s_iter.GetMeasurementVector())\n {\n std::cerr << \"Iterator::GetMeasurementVector (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n }\n if (id != s_iter.GetInstanceIdentifier())\n {\n std::cerr << \"Iterator::GetInstanceIdentifier (backward) failed\" \n << std::endl;\n return EXIT_FAILURE;\n } \n } while (!(s_iter == sample->Begin())); \/\/ explicitly test ==\n \n if (!(s_iter == sample->Begin()))\n {\n std::cerr << \"Iterator::Begin (backward) failed\" << std::endl;\n return EXIT_FAILURE; \n }\n }\n\n std::cerr << \"Search...\" << std::endl; \n SampleType::SearchResultVectorType searchResult ;\n sample->Search(sample->GetMeasurementVector(sampleSize\/2), 0.01, \n searchResult) ;\n\n\n \/\/\n \/\/ resizing\n \/\/\n sample->Clear();\n if (sample->Size() != 0)\n {\n std::cerr << \"Clear() failed\" << std::endl;\n return EXIT_FAILURE; \n }\n\n sample->Resize(sampleSize);\n if (sample->Size() != sampleSize)\n {\n std::cerr << \"Resize() failed\" << std::endl;\n return EXIT_FAILURE; \n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Suburb.png}\n\/\/ OUTPUTS: {TutorialsScalingPipelineOutput.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{itk}{RescaleIntensityImageFilter} to convert\n\/\/ the result for proper display.\n\/\/\n\/\/ We include the required header including the header\n\/\/ for the \\doxygen{itk}{CannyEdgeImageFilter} and the\n\/\/ \\doxygen{itk}{RescaleIntensityImageFilter}.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"itkCannyEdgeDetectionImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n if (argc != 3)\n {\n std::cerr << \"Usage: \"\n << argv[0]\n << \" <input_filename> <output_filename>\"\n << std::endl;\n }\n\/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We need to declare two different image types, one for the internal\n \/\/ processing and one to output the results:\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef double PixelType;\n typedef otb::Image<PixelType, 2> ImageType;\n\n typedef unsigned char OutputPixelType;\n typedef otb::Image<OutputPixelType, 2> OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the reader with the image template using the pixel type\n \/\/ double. It is worth noticing that this instanciation does not imply\n \/\/ anything about the type of the input image. The original image can be\n \/\/ anything, the reader will just convert the result to double.\n \/\/\n \/\/ The writer is templated with the unsigned char image to be able to save\n \/\/ the result on one byte images (like png for example).\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::ImageFileReader<ImageType> ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n\n typedef otb::ImageFileWriter<OutputImageType> WriterType;\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Now we are declaring the edge detection filter which is going to work with\n \/\/ double input and output.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::CannyEdgeDetectionImageFilter\n <ImageType, ImageType> FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Here comes the interesting part: we declare the\n \/\/ \\doxygen{itk}{RescaleIntensityImageFilter}. The input\n \/\/ image type is the output type of the edge detection\n \/\/ filter. The output type is the same as the input type\n \/\/ of the writer.\n \/\/\n \/\/ Desired minimum and maximum values for the output are\n \/\/ specified by the methods \\code{SetOutputMinimum()} and\n \/\/ \\code{SetOutputMaximum()}.\n \/\/\n \/\/ This filter will actually rescale all the pixels of\n \/\/ the image but also cast the type of these pixels.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::RescaleIntensityImageFilter\n <ImageType, OutputImageType> RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n\n rescaler->SetOutputMinimum(0);\n rescaler->SetOutputMaximum(255);\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Let's plug the pipeline:\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput(reader->GetOutput());\n rescaler->SetInput(filter->GetOutput());\n writer->SetInput(rescaler->GetOutput());\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ And finally, we trigger the pipeline execution calling the Update()\n \/\/ method on the writer\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\/\/ Software Guide : EndCodeSnippet\n<commit_msg>Fix typo in ScalingPipeline example<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Suburb.png}\n\/\/ OUTPUTS: {TutorialsScalingPipelineOutput.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{itk}{RescaleIntensityImageFilter} to convert\n\/\/ the result for proper display.\n\/\/\n\/\/ We include the required header including the header\n\/\/ for the \\doxygen{itk}{CannyEdgeDetectionImageFilter} and the\n\/\/ \\doxygen{itk}{RescaleIntensityImageFilter}.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"itkCannyEdgeDetectionImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n if (argc != 3)\n {\n std::cerr << \"Usage: \"\n << argv[0]\n << \" <input_filename> <output_filename>\"\n << std::endl;\n }\n\/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We need to declare two different image types, one for the internal\n \/\/ processing and one to output the results:\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef double PixelType;\n typedef otb::Image<PixelType, 2> ImageType;\n\n typedef unsigned char OutputPixelType;\n typedef otb::Image<OutputPixelType, 2> OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the reader with the image template using the pixel type\n \/\/ double. It is worth noticing that this instanciation does not imply\n \/\/ anything about the type of the input image. The original image can be\n \/\/ anything, the reader will just convert the result to double.\n \/\/\n \/\/ The writer is templated with the unsigned char image to be able to save\n \/\/ the result on one byte images (like png for example).\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::ImageFileReader<ImageType> ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n\n typedef otb::ImageFileWriter<OutputImageType> WriterType;\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Now we are declaring the edge detection filter which is going to work with\n \/\/ double input and output.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::CannyEdgeDetectionImageFilter\n <ImageType, ImageType> FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Here comes the interesting part: we declare the\n \/\/ \\doxygen{itk}{RescaleIntensityImageFilter}. The input\n \/\/ image type is the output type of the edge detection\n \/\/ filter. The output type is the same as the input type\n \/\/ of the writer.\n \/\/\n \/\/ Desired minimum and maximum values for the output are\n \/\/ specified by the methods \\code{SetOutputMinimum()} and\n \/\/ \\code{SetOutputMaximum()}.\n \/\/\n \/\/ This filter will actually rescale all the pixels of\n \/\/ the image but also cast the type of these pixels.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::RescaleIntensityImageFilter\n <ImageType, OutputImageType> RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n\n rescaler->SetOutputMinimum(0);\n rescaler->SetOutputMaximum(255);\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Let's plug the pipeline:\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput(reader->GetOutput());\n rescaler->SetInput(filter->GetOutput());\n writer->SetInput(rescaler->GetOutput());\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ And finally, we trigger the pipeline execution calling the Update()\n \/\/ method on the writer\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\/\/ Software Guide : EndCodeSnippet\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2017, Vadim Malyshev, lboss75@gmail.com\nAll rights reserved\n*\/\n\n#include \"stdafx.h\"\n#include \"root_user_transaction.h\"\n#include \"binary_serialize.h\"\n\nvds::root_user_transaction::root_user_transaction(\n const guid & id,\n const certificate & user_cert,\n const std::string & user_name,\n const const_data_buffer & user_private_key,\n const const_data_buffer & password_hash)\n : id_(id),\n user_cert_(user_cert),\n user_name_(user_name),\n user_private_key_(user_private_key),\n password_hash_(password_hash)\n{\n}\n\nvds::root_user_transaction::root_user_transaction(struct binary_deserializer &b) {\n const_data_buffer cert_der;\n b >> this->id_ >> cert_der >> this->user_private_key_ >> this->password_hash_;\n this->user_cert_ = certificate::parse_der(cert_der);\n}\n\nvoid vds::root_user_transaction::serialize(vds::binary_serializer &b) const {\n b << this->id_ << this->user_cert_.der() << this->user_private_key_ << this->password_hash_;\n}\n<commit_msg>cryptochannel design<commit_after>\/*\nCopyright (c) 2017, Vadim Malyshev, lboss75@gmail.com\nAll rights reserved\n*\/\n\n#include \"stdafx.h\"\n#include \"root_user_transaction.h\"\n#include \"binary_serialize.h\"\n\nvds::root_user_transaction::root_user_transaction(\n const guid & id,\n const certificate & user_cert,\n const std::string & user_name,\n const const_data_buffer & user_private_key,\n const const_data_buffer & password_hash)\n : id_(id),\n user_cert_(user_cert),\n user_name_(user_name),\n user_private_key_(user_private_key),\n password_hash_(password_hash)\n{\n}\n\nvds::root_user_transaction::root_user_transaction(struct binary_deserializer &b) {\n const_data_buffer cert_der;\n b >> this->id_ >> cert_der >> this->user_name_ >> this->user_private_key_ >> this->password_hash_;\n this->user_cert_ = certificate::parse_der(cert_der);\n}\n\nvoid vds::root_user_transaction::serialize(vds::binary_serializer &b) const {\n b << this->id_ << this->user_cert_.der() << this->user_name_ << this->user_private_key_ << this->password_hash_;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <utility>\n#include <memory>\n#include <cassert>\n#include <mutex>\n\n#include \"Stack.hpp\"\n\nnamespace AO\n{\n\tnamespace Allocator\n\t{\n\t\tinline namespace Version_1\n\t\t{\n\t\t\t\/\/ Methods\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\ttemplate <typename Type, typename... Args>\n\t\t\tinline Type *Stack<Capacity>::create(Args &&...args)\n\t\t\t{\n\t\t\t\treturn new (allocate(sizeof(Type), alignof(Type))) Type(std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\ttemplate <typename Type>\n\t\t\tinline void Stack<Capacity>::destroy(Type const *instance)\n\t\t\t{\n\t\t\t\tif (instance)\n\t\t\t\t{\n\t\t\t\t\tinstance->~Type();\n\t\t\t\t\tdeallocate(static_cast<void const *>(instance), sizeof(Type));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Inherited Methods\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline bool Stack<Capacity>::empty(void) const noexcept\n\t\t\t{\n\t\t\t\treturn size() == 0;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline std::size_t Stack<Capacity>::size(void) const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<std::uint8_t *>(bufferPointer) - buffer;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline std::size_t Stack<Capacity>::capacity(void) const noexcept\n\t\t\t{\n\t\t\t\treturn Capacity;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void Stack<Capacity>::reset(void) noexcept\n\t\t\t{\n\t\t\t\tbufferPointer = static_cast<void *>(buffer);\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void *Stack<Capacity>::allocate(std::size_t numberOfBytes, std::size_t alignment)\n\t\t\t{\n\t\t\t\tstd::size_t space = capacity() - size();\n\t\t\t\tif (std::align(alignment, numberOfBytes, bufferPointer, space))\n\t\t\t\t{\n\t\t\t\t\tvoid *allocatedMemory = bufferPointer;\n\t\t\t\t\tbufferPointer = static_cast<void *>(static_cast<std::uint8_t *>(bufferPointer) + numberOfBytes);\n\t\t\t\t\treturn allocatedMemory;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvoid *allocatedMemory = std::malloc(numberOfBytes + alignment + sizeof(void *));\n\t\t\t\t\tvoid **pointerToAlignedMemory = reinterpret_cast<void **>(reinterpret_cast<std::uintptr_t>(static_cast<std::uint8_t *>(allocatedMemory) + alignment + sizeof(void *)) & ~(alignment - 1));\n\t\t\t\t\tpointerToAlignedMemory[-1] = allocatedMemory;\n\t\t\t\t\treturn static_cast<void *>(pointerToAlignedMemory);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void Stack<Capacity>::deallocate(void const *memory, std::size_t numberOfBytes)\n\t\t\t{\n\t\t\t\tstd::uint8_t const *endOfMemory = static_cast<std::uint8_t const *>(memory) + numberOfBytes;\n\t\t\t\tif (buffer <= memory && endOfMemory <= buffer + Capacity)\n\t\t\t\t{\n\t\t\t\t\tassert(endOfMemory == bufferPointer && \"Invalid memory\");\n\t\t\t\t\tif (endOfMemory == bufferPointer)\n\t\t\t\t\t{\n\t\t\t\t\t\tbufferPointer = const_cast<void *>(memory);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstd::free(static_cast<void **>(const_cast<void *>(memory))[-1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>Update Stack.inl<commit_after>#pragma once\n\n#include <utility>\n#include <cassert>\n#include <mutex>\n\n#include \"Stack.hpp\"\n\nnamespace AO\n{\n\tnamespace Allocator\n\t{\n\t\tinline namespace Version_1\n\t\t{\n\t\t\t\/\/ Methods\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\ttemplate <typename Type, typename... Args>\n\t\t\tinline Type *Stack<Capacity>::create(Args &&...args)\n\t\t\t{\n\t\t\t\treturn new (allocate(sizeof(Type), alignof(Type))) Type(std::forward<Args>(args)...);\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\ttemplate <typename Type>\n\t\t\tinline void Stack<Capacity>::destroy(Type const *instance)\n\t\t\t{\n\t\t\t\tif (instance)\n\t\t\t\t{\n\t\t\t\t\tinstance->~Type();\n\t\t\t\t\tdeallocate(static_cast<void const *>(instance), sizeof(Type));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Inherited Methods\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline bool Stack<Capacity>::empty(void) const noexcept\n\t\t\t{\n\t\t\t\treturn size() == 0;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline std::size_t Stack<Capacity>::size(void) const noexcept\n\t\t\t{\n\t\t\t\treturn static_cast<std::uint8_t *>(bufferPointer) - buffer;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline std::size_t Stack<Capacity>::capacity(void) const noexcept\n\t\t\t{\n\t\t\t\treturn Capacity;\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void Stack<Capacity>::reset(void) noexcept\n\t\t\t{\n\t\t\t\tbufferPointer = static_cast<void *>(buffer);\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void *Stack<Capacity>::allocate(std::size_t numberOfBytes, std::size_t alignment)\n\t\t\t{\n\t\t\t\tstd::size_t space = capacity() - size();\n\t\t\t\tif (std::align(alignment, numberOfBytes, bufferPointer, space))\n\t\t\t\t{\n\t\t\t\t\tvoid *allocatedMemory = bufferPointer;\n\t\t\t\t\tbufferPointer = static_cast<void *>(static_cast<std::uint8_t *>(bufferPointer) + numberOfBytes);\n\t\t\t\t\treturn allocatedMemory;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvoid *allocatedMemory = std::malloc(numberOfBytes + alignment + sizeof(void *));\n\t\t\t\t\tvoid **pointerToAlignedMemory = reinterpret_cast<void **>(reinterpret_cast<std::uintptr_t>(static_cast<std::uint8_t *>(allocatedMemory) + alignment + sizeof(void *)) & ~(alignment - 1));\n\t\t\t\t\tpointerToAlignedMemory[-1] = allocatedMemory;\n\t\t\t\t\treturn static_cast<void *>(pointerToAlignedMemory);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplate <std::size_t Capacity>\n\t\t\tinline void Stack<Capacity>::deallocate(void const *memory, std::size_t numberOfBytes)\n\t\t\t{\n\t\t\t\tstd::uint8_t const *endOfMemory = static_cast<std::uint8_t const *>(memory) + numberOfBytes;\n\t\t\t\tif (buffer <= memory && endOfMemory <= buffer + Capacity)\n\t\t\t\t{\n\t\t\t\t\tassert(endOfMemory == bufferPointer && \"Invalid memory\");\n\t\t\t\t\tif (endOfMemory == bufferPointer)\n\t\t\t\t\t{\n\t\t\t\t\t\tbufferPointer = const_cast<void *>(memory);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstd::free(static_cast<void **>(const_cast<void *>(memory))[-1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: ThreadGroup.C\n\/\/ Description: This file contains the ThreadGroup class methods\n\/\/ Rel: 01.00\n\/\/ Created: May, 2001\n\/\/ Author: Juan A. Caceres Exposito ( caceres@tid.es )\n\/\/\n\/\/ Revised:\n\/\/\n\/\/ (C) Copyright 2009 Telefonica Investigacion y Desarrollo\n\/\/ S.A.Unipersonal (Telefonica I+D)\n\/\/\n\/\/ This file is part of Morfeo CORBA Platform.\n\/\/\n\/\/ Morfeo CORBA Platform is free software: you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the License,\n\/\/ or (at your option) any later version.\n\/\/\n\/\/ Morfeo CORBA Platform is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Morfeo CORBA Platform. If not, see\n\/\/\n\/\/ http:\/\/www.gnu.org\/licenses\n\/\/\n\/\/ Info about members and contributors of the MORFEO project\n\/\/ is available at\n\/\/\n\/\/ http:\/\/morfeo-project.org\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TIDThr.h\"\n#include <pthread.h>\n\nnamespace TIDThr {\n\nThreadGroup::ThreadGroup(const char* name)\n throw(IllegalThreadStateException,\n IllegalArgumentException)\n : m_group_name(name),\n m_group_id(0),\n m_destroyed(false),\n m_group_father(NULL)\n{\n pthread_attr_init(&m_group_attributes);\n pthread_attr_setscope(&m_group_attributes,PTHREAD_SCOPE_PROCESS);\n pthread_attr_setdetachstate(&m_group_attributes,PTHREAD_CREATE_DETACHED);\n\n m_state_mutex = new Mutex();\n}\n\nThreadGroup::ThreadGroup(ThreadGroup *father,\n const char* name,\n const pthread_attr_t* attr)\n throw(IllegalThreadStateException,\n IllegalArgumentException)\n : m_group_name(name),\n m_group_id(0), \n m_destroyed(false),\n m_group_father(father)\n{\n if(father != NULL){ \n ThreadGroupHandle this_group(this);\n m_destroyed = father->m_destroyed;\n father->addGroup(this_group);\n }\n\n pthread_attr_init(&m_group_attributes);\n\n if (attr != NULL) {\n attrCopy(attr, &m_group_attributes);\n } else if(father != NULL) {\n attrCopy(father->getAttributes(), &m_group_attributes);\n }\n\n m_state_mutex = new Mutex();\n}\n\nThreadGroup::~ThreadGroup() \n throw (SystemException)\n{\n pthread_attr_destroy(&m_group_attributes);\n\n if(!m_group_father.is_null()) {\n m_group_father->removeGroup(getId());\n }\n}\n\nvoid ThreadGroup::destroy()\n throw (IllegalThreadStateException)\n{\n Synchronized synchro(*m_state_mutex);\n\n if(m_destroyed) {\n throw IllegalThreadStateException(\"ThreadGroup Already destroyed\");\n }\n\n if((activeCount() > 0) || (activeGroupCount() > 0)) {\n throw IllegalThreadStateException(\"ThreadGroup not empty\");\n }\n\n m_destroyed = true;\n}\n\n\nvoid \nThreadGroup::addGroup(const ThreadGroupHandle& child) \n throw (IllegalThreadStateException)\n{\n Synchronized syncrho(*m_state_mutex);\n \n if(m_destroyed) {\n throw IllegalThreadStateException(\"Destroyed ThreadGroup\");\n }\n \n child->setId(m_last_child_id);\n \n m_groups_table.insert(ThreadGroupTable::value_type(m_last_child_id,child));\n\n ++m_last_child_id;\n}\n\nvoid \nThreadGroup::removeGroup(const ThreadGroupId& child_id)\n{\n Synchronized syncrho(*m_state_mutex);\n m_groups_table.erase(child_id);\n}\n\nvoid ThreadGroup::addThread(const ThreadHandle& child)\n throw (IllegalThreadStateException)\n{\n Synchronized synchro(*m_state_mutex);\n \n if(m_destroyed) {\n throw IllegalThreadStateException(\"Destroyed ThreadGroup\");\n }\n \n m_threads_table.insert(ThreadTable::value_type(child->getId(),child));\n}\n \nvoid \nThreadGroup::removeThread(const ThreadId& child_id)\n{\n Synchronized synchro(*m_state_mutex);\n m_threads_table.erase(child_id);\n}\n\nsize_t \nThreadGroup::enumerate(ThreadHandle* list,\n size_t list_size,\n bool recurse) const\n{\n Synchronized synchro(*m_state_mutex);\n \n \/\/ current group list\n \n ThreadTable::const_iterator thread_iter = m_threads_table.begin();\n \n size_t count = 0;\n \n size_t threads_table_size = m_threads_table.size();\n\n while((count < list_size) && (count < threads_table_size)) {\n list[count++] = (*thread_iter).second;\n thread_iter++;\n }\n \n \/\/ child groups list\n \n if((count > list_size) || (!recurse)) {\n return count;\n }\n \n ThreadGroupTable::const_iterator group_iter = m_groups_table.begin();\n \n \n while((count < list_size) && (group_iter != m_groups_table.end())) {\n count += ((*group_iter).second)->enumerate(&(list[count]), \n list_size - count,\n recurse);\n group_iter++;\n } \n \n return count;\n}\n\n\nvoid\nThreadGroup::list() const\n{ \n Synchronized synchro(*m_state_mutex);\n \n cout << *this << endl;\n \n \/\/ groups \n \n ThreadGroupTable::const_iterator group_iter = m_groups_table.begin();\n\n const ThreadGroup* group = NULL;\n \n while(group_iter != m_groups_table.end()) {\n group = (const ThreadGroup *) ((*group_iter).second);\n if(group){\n cout << '\\t'<< *group << endl;\n }\n group_iter++;\n }\n \n \/\/ threads\n \n \n ThreadTable::const_iterator thread_iter = m_threads_table.begin();\n \n const Thread* thread = NULL; \n \n while(thread_iter != m_threads_table.end()) {\n thread = (*thread_iter).second;\n if(thread){\n cout << '\\t' << *thread << endl;\n } \n thread_iter++;\n }\n \n}\n\nsize_t\nThreadGroup::enumerate(ThreadGroupHandle* list, \n size_t list_size, \n bool recurse) const\n{\n Synchronized synchro(*m_state_mutex);\n \n \/\/ current group list\n \n ThreadGroupTable::const_iterator groups_iter = m_groups_table.begin();\n \n size_t count = 0;\n \n size_t groups_table_size = m_groups_table.size();\n \n while((count < list_size) && (count < groups_table_size)) {\n list[count++] = (*groups_iter).second;\n groups_iter++;\n }\n \n \/\/ child groups list\n \n if((count >= list_size) || (!recurse)) {\n return count;\n }\n \n ThreadGroupTable::const_iterator child_groups_iter = m_groups_table.begin();\n \n while((count < list_size) && (child_groups_iter != m_groups_table.end())) {\n count += ((*child_groups_iter).second)->enumerate(&(list[count]), \n list_size - count,\n recurse);\n child_groups_iter++;\n } \n \n return count;\n}\n\nvoid \nThreadGroup::attrCopy(const pthread_attr_t* from, pthread_attr_t* to)\n throw (IllegalArgumentException)\n{\n if((from == NULL) || (to == NULL)) {\n throw IllegalArgumentException(\"Null pthread_attr_t pointer\");\n }\n \n int ret = 0; \n\n int deatached;\n ret= pthread_attr_getdetachstate(from,&deatached);\n if(ret) {\n throw IllegalArgumentException(\"Null from pthread_attr_t pointer\",ret);\n }\n ret= pthread_attr_setdetachstate(to,deatached);\n if(ret) {\n throw IllegalArgumentException(\"Null to pthread_attr_t pointer\",ret);\n }\n\n size_t size;\n \n\/\/ #if !defined(__linux__)\n#if !defined(__CYGWIN__)\n pthread_attr_getguardsize(from, &size);\n pthread_attr_setguardsize(to, size);\n#endif\n\/\/ #endif\n pthread_attr_getstacksize(from, &size);\n pthread_attr_setstacksize(to, size);\n\n int scope;\n pthread_attr_getscope(from, &scope);\n pthread_attr_setscope(to, scope);\n\n int policy;\n pthread_attr_getschedpolicy(from, &policy);\n pthread_attr_setschedpolicy(to, policy);\n\n pthread_attr_getinheritsched(from, &policy);\n pthread_attr_setinheritsched(to, policy);\n \n sched_param param;\n \n pthread_attr_getschedparam(from, ¶m);\n pthread_attr_setschedparam(to, ¶m);\n}\n\n} \/\/ namespace TIDThr \n\nostream& operator<<(ostream& os, const TIDThr::ThreadGroup& group)\n{\n os << \"ThreadGroup \" << group.getId() << \" \\\"\" << group.getName() << \"\\\"\";\n return os;\n}\n<commit_msg>Android NDK, MIPS and minimun CORBA support added<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: ThreadGroup.C\n\/\/ Description: This file contains the ThreadGroup class methods\n\/\/ Rel: 01.00\n\/\/ Created: May, 2001\n\/\/ Author: Juan A. Caceres Exposito ( caceres@tid.es )\n\/\/\n\/\/ Revised:\n\/\/\n\/\/ (C) Copyright 2009 Telefonica Investigacion y Desarrollo\n\/\/ S.A.Unipersonal (Telefonica I+D)\n\/\/\n\/\/ This file is part of Morfeo CORBA Platform.\n\/\/\n\/\/ Morfeo CORBA Platform is free software: you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the License,\n\/\/ or (at your option) any later version.\n\/\/\n\/\/ Morfeo CORBA Platform is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Morfeo CORBA Platform. If not, see\n\/\/\n\/\/ http:\/\/www.gnu.org\/licenses\n\/\/\n\/\/ Info about members and contributors of the MORFEO project\n\/\/ is available at\n\/\/\n\/\/ http:\/\/morfeo-project.org\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TIDThr.h\"\n#include <pthread.h>\n\nnamespace TIDThr {\n\nThreadGroup::ThreadGroup(const char* name)\n throw(IllegalThreadStateException,\n IllegalArgumentException)\n : m_group_name(name),\n m_group_id(0),\n m_destroyed(false),\n m_group_father(NULL)\n{\n pthread_attr_init(&m_group_attributes);\n pthread_attr_setscope(&m_group_attributes,PTHREAD_SCOPE_PROCESS);\n pthread_attr_setdetachstate(&m_group_attributes,PTHREAD_CREATE_DETACHED);\n\n m_state_mutex = new Mutex();\n}\n\nThreadGroup::ThreadGroup(ThreadGroup *father,\n const char* name,\n const pthread_attr_t* attr)\n throw(IllegalThreadStateException,\n IllegalArgumentException)\n : m_group_name(name),\n m_group_id(0), \n m_destroyed(false),\n m_group_father(father)\n{\n if(father != NULL){ \n ThreadGroupHandle this_group(this);\n m_destroyed = father->m_destroyed;\n father->addGroup(this_group);\n }\n\n pthread_attr_init(&m_group_attributes);\n\n if (attr != NULL) {\n attrCopy(attr, &m_group_attributes);\n } else if(father != NULL) {\n attrCopy(father->getAttributes(), &m_group_attributes);\n }\n\n m_state_mutex = new Mutex();\n}\n\nThreadGroup::~ThreadGroup() \n throw (SystemException)\n{\n pthread_attr_destroy(&m_group_attributes);\n\n if(!m_group_father.is_null()) {\n m_group_father->removeGroup(getId());\n }\n}\n\nvoid ThreadGroup::destroy()\n throw (IllegalThreadStateException)\n{\n Synchronized synchro(*m_state_mutex);\n\n if(m_destroyed) {\n throw IllegalThreadStateException(\"ThreadGroup Already destroyed\");\n }\n\n if((activeCount() > 0) || (activeGroupCount() > 0)) {\n throw IllegalThreadStateException(\"ThreadGroup not empty\");\n }\n\n m_destroyed = true;\n}\n\n\nvoid \nThreadGroup::addGroup(const ThreadGroupHandle& child) \n throw (IllegalThreadStateException)\n{\n Synchronized syncrho(*m_state_mutex);\n \n if(m_destroyed) {\n throw IllegalThreadStateException(\"Destroyed ThreadGroup\");\n }\n \n child->setId(m_last_child_id);\n \n m_groups_table.insert(ThreadGroupTable::value_type(m_last_child_id,child));\n\n ++m_last_child_id;\n}\n\nvoid \nThreadGroup::removeGroup(const ThreadGroupId& child_id)\n{\n Synchronized syncrho(*m_state_mutex);\n m_groups_table.erase(child_id);\n}\n\nvoid ThreadGroup::addThread(const ThreadHandle& child)\n throw (IllegalThreadStateException)\n{\n Synchronized synchro(*m_state_mutex);\n \n if(m_destroyed) {\n throw IllegalThreadStateException(\"Destroyed ThreadGroup\");\n }\n \n m_threads_table.insert(ThreadTable::value_type(child->getId(),child));\n}\n \nvoid \nThreadGroup::removeThread(const ThreadId& child_id)\n{\n Synchronized synchro(*m_state_mutex);\n m_threads_table.erase(child_id);\n}\n\nsize_t \nThreadGroup::enumerate(ThreadHandle* list,\n size_t list_size,\n bool recurse) const\n{\n Synchronized synchro(*m_state_mutex);\n \n \/\/ current group list\n \n ThreadTable::const_iterator thread_iter = m_threads_table.begin();\n \n size_t count = 0;\n \n size_t threads_table_size = m_threads_table.size();\n\n while((count < list_size) && (count < threads_table_size)) {\n list[count++] = (*thread_iter).second;\n thread_iter++;\n }\n \n \/\/ child groups list\n \n if((count > list_size) || (!recurse)) {\n return count;\n }\n \n ThreadGroupTable::const_iterator group_iter = m_groups_table.begin();\n \n \n while((count < list_size) && (group_iter != m_groups_table.end())) {\n count += ((*group_iter).second)->enumerate(&(list[count]), \n list_size - count,\n recurse);\n group_iter++;\n } \n \n return count;\n}\n\n\nvoid\nThreadGroup::list() const\n{ \n Synchronized synchro(*m_state_mutex);\n \n cout << *this << endl;\n \n \/\/ groups \n \n ThreadGroupTable::const_iterator group_iter = m_groups_table.begin();\n\n const ThreadGroup* group = NULL;\n \n while(group_iter != m_groups_table.end()) {\n group = (const ThreadGroup *) ((*group_iter).second);\n if(group){\n cout << '\\t'<< *group << endl;\n }\n group_iter++;\n }\n \n \/\/ threads\n \n \n ThreadTable::const_iterator thread_iter = m_threads_table.begin();\n \n const Thread* thread = NULL; \n \n while(thread_iter != m_threads_table.end()) {\n thread = (*thread_iter).second;\n if(thread){\n cout << '\\t' << *thread << endl;\n } \n thread_iter++;\n }\n \n}\n\nsize_t\nThreadGroup::enumerate(ThreadGroupHandle* list, \n size_t list_size, \n bool recurse) const\n{\n Synchronized synchro(*m_state_mutex);\n \n \/\/ current group list\n \n ThreadGroupTable::const_iterator groups_iter = m_groups_table.begin();\n \n size_t count = 0;\n \n size_t groups_table_size = m_groups_table.size();\n \n while((count < list_size) && (count < groups_table_size)) {\n list[count++] = (*groups_iter).second;\n groups_iter++;\n }\n \n \/\/ child groups list\n \n if((count >= list_size) || (!recurse)) {\n return count;\n }\n \n ThreadGroupTable::const_iterator child_groups_iter = m_groups_table.begin();\n \n while((count < list_size) && (child_groups_iter != m_groups_table.end())) {\n count += ((*child_groups_iter).second)->enumerate(&(list[count]), \n list_size - count,\n recurse);\n child_groups_iter++;\n } \n \n return count;\n}\n\nvoid \nThreadGroup::attrCopy(const pthread_attr_t* from, pthread_attr_t* to)\n throw (IllegalArgumentException)\n{\n if((from == NULL) || (to == NULL)) {\n throw IllegalArgumentException(\"Null pthread_attr_t pointer\");\n }\n \n int ret = 0; \n\n int deatached;\n ret= pthread_attr_getdetachstate(from,&deatached);\n if(ret) {\n throw IllegalArgumentException(\"Null from pthread_attr_t pointer\",ret);\n }\n ret= pthread_attr_setdetachstate(to,deatached);\n if(ret) {\n throw IllegalArgumentException(\"Null to pthread_attr_t pointer\",ret);\n }\n\n size_t size;\n \n\/\/ #if !defined(__linux__)\n#if !defined(__CYGWIN__)\n pthread_attr_getguardsize(from, &size);\n pthread_attr_setguardsize(to, size);\n#endif\n\/\/ #endif\n pthread_attr_getstacksize(from, &size);\n pthread_attr_setstacksize(to, size);\n\n#if !defined(__ANDROID__)\n int scope;\n pthread_attr_getscope(from, &scope);\n pthread_attr_setscope(to, scope);\n#endif\n\n#if !defined(__ANDROID__)\n int policy;\n pthread_attr_getschedpolicy(from, &policy);\n pthread_attr_setschedpolicy(to, policy);\n\n pthread_attr_getinheritsched(from, &policy);\n pthread_attr_setinheritsched(to, policy);\n#endif\n\n sched_param param;\n \n pthread_attr_getschedparam(from, ¶m);\n pthread_attr_setschedparam(to, ¶m);\n}\n\n} \/\/ namespace TIDThr \n\nostream& operator<<(ostream& os, const TIDThr::ThreadGroup& group)\n{\n os << \"ThreadGroup \" << group.getId() << \" \\\"\" << group.getName() << \"\\\"\";\n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * HLSLKeywords.cpp\n * \n * This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include \"HLSLKeywords.h\"\n\n\nnamespace Xsc\n{\n\n\nstatic KeywordMapType GenerateKeywordMap()\n{\n using Ty = Token::Types;\n\n return\n {\n { \"true\", Ty::BoolLiteral },\n { \"false\", Ty::BoolLiteral },\n\n { \"void\", Ty::Void },\n\n { \"bool\", Ty::ScalarType },\n { \"bool1\", Ty::ScalarType },\n { \"bool1x1\", Ty::ScalarType },\n { \"int\", Ty::ScalarType },\n { \"int1\", Ty::ScalarType },\n { \"int1x1\", Ty::ScalarType },\n { \"uint\", Ty::ScalarType },\n { \"uint1\", Ty::ScalarType },\n { \"uint1x1\", Ty::ScalarType },\n { \"half\", Ty::ScalarType },\n { \"half1\", Ty::ScalarType },\n { \"half1x1\", Ty::ScalarType },\n { \"float\", Ty::ScalarType },\n { \"float1\", Ty::ScalarType },\n { \"float1x1\", Ty::ScalarType },\n { \"double\", Ty::ScalarType },\n { \"double1\", Ty::ScalarType },\n { \"double1x1\", Ty::ScalarType },\n\n { \"bool2\", Ty::VectorType },\n { \"bool3\", Ty::VectorType },\n { \"bool4\", Ty::VectorType },\n { \"int2\", Ty::VectorType },\n { \"int3\", Ty::VectorType },\n { \"int4\", Ty::VectorType },\n { \"uint2\", Ty::VectorType },\n { \"uint3\", Ty::VectorType },\n { \"uint4\", Ty::VectorType },\n { \"half2\", Ty::VectorType },\n { \"half3\", Ty::VectorType },\n { \"half4\", Ty::VectorType },\n { \"float2\", Ty::VectorType },\n { \"float3\", Ty::VectorType },\n { \"float4\", Ty::VectorType },\n { \"double2\", Ty::VectorType },\n { \"double3\", Ty::VectorType },\n { \"double4\", Ty::VectorType },\n\n { \"bool2x2\", Ty::MatrixType },\n { \"bool2x3\", Ty::MatrixType },\n { \"bool2x4\", Ty::MatrixType },\n { \"bool3x2\", Ty::MatrixType },\n { \"bool3x3\", Ty::MatrixType },\n { \"bool3x4\", Ty::MatrixType },\n { \"bool4x2\", Ty::MatrixType },\n { \"bool4x3\", Ty::MatrixType },\n { \"bool4x4\", Ty::MatrixType },\n { \"int2x2\", Ty::MatrixType },\n { \"int2x3\", Ty::MatrixType },\n { \"int2x4\", Ty::MatrixType },\n { \"int3x2\", Ty::MatrixType },\n { \"int3x3\", Ty::MatrixType },\n { \"int3x4\", Ty::MatrixType },\n { \"int4x2\", Ty::MatrixType },\n { \"int4x3\", Ty::MatrixType },\n { \"int4x4\", Ty::MatrixType },\n { \"uint2x2\", Ty::MatrixType },\n { \"uint2x3\", Ty::MatrixType },\n { \"uint2x4\", Ty::MatrixType },\n { \"uint3x2\", Ty::MatrixType },\n { \"uint3x3\", Ty::MatrixType },\n { \"uint3x4\", Ty::MatrixType },\n { \"uint4x2\", Ty::MatrixType },\n { \"uint4x3\", Ty::MatrixType },\n { \"uint4x4\", Ty::MatrixType },\n { \"half2x2\", Ty::MatrixType },\n { \"half2x3\", Ty::MatrixType },\n { \"half2x4\", Ty::MatrixType },\n { \"half3x2\", Ty::MatrixType },\n { \"half3x3\", Ty::MatrixType },\n { \"half3x4\", Ty::MatrixType },\n { \"half4x2\", Ty::MatrixType },\n { \"half4x3\", Ty::MatrixType },\n { \"half4x4\", Ty::MatrixType },\n { \"float2x2\", Ty::MatrixType },\n { \"float2x3\", Ty::MatrixType },\n { \"float2x4\", Ty::MatrixType },\n { \"float3x2\", Ty::MatrixType },\n { \"float3x3\", Ty::MatrixType },\n { \"float3x4\", Ty::MatrixType },\n { \"float4x2\", Ty::MatrixType },\n { \"float4x3\", Ty::MatrixType },\n { \"float4x4\", Ty::MatrixType },\n { \"double2x2\", Ty::MatrixType },\n { \"double2x3\", Ty::MatrixType },\n { \"double2x4\", Ty::MatrixType },\n { \"double3x2\", Ty::MatrixType },\n { \"double3x3\", Ty::MatrixType },\n { \"double3x4\", Ty::MatrixType },\n { \"double4x2\", Ty::MatrixType },\n { \"double4x3\", Ty::MatrixType },\n { \"double4x4\", Ty::MatrixType },\n\n { \"do\", Ty::Do },\n { \"while\", Ty::While },\n { \"for\", Ty::For },\n\n { \"if\", Ty::If },\n { \"else\", Ty::Else },\n\n { \"switch\", Ty::Switch },\n { \"case\", Ty::Case },\n { \"default\", Ty::Default },\n\n { \"struct\", Ty::Struct },\n { \"register\", Ty::Register },\n { \"packoffset\", Ty::PackOffset },\n\n { \"sampler\", Ty::Sampler },\n { \"sampler1D\", Ty::Sampler },\n { \"sampler2D\", Ty::Sampler },\n { \"sampler3D\", Ty::Sampler },\n { \"samplerCUBE\", Ty::Sampler },\n { \"sampler_state\", Ty::Sampler },\n { \"SamplerState\", Ty::Sampler },\n\n { \"Texture1D\", Ty::Texture },\n { \"Texture1DArray\", Ty::Texture },\n { \"Texture2D\", Ty::Texture },\n { \"Texture2DArray\", Ty::Texture },\n { \"Texture3D\", Ty::Texture },\n { \"TextureCube\", Ty::Texture },\n { \"TextureCubeArray\", Ty::Texture },\n { \"Texture2DMS\", Ty::Texture },\n { \"Texture2DMSArray\", Ty::Texture },\n { \"RWTexture1D\", Ty::Texture },\n { \"RWTexture1DArray\", Ty::Texture },\n { \"RWTexture2D\", Ty::Texture },\n { \"RWTexture2DArray\", Ty::Texture },\n { \"RWTexture3D\", Ty::Texture },\n\n { \"AppendStructuredBuffer\", Ty::StorageBuffer },\n { \"Buffer\", Ty::StorageBuffer },\n { \"ByteAddressBuffer\", Ty::StorageBuffer },\n { \"ConsumeStructuredBuffer\", Ty::StorageBuffer },\n { \"StructuredBuffer\", Ty::StorageBuffer },\n { \"RWBuffer\", Ty::StorageBuffer },\n { \"RWByteAddressBuffer\", Ty::StorageBuffer },\n { \"RWStructuredBuffer\", Ty::StorageBuffer },\n\n { \"cbuffer\", Ty::UniformBuffer },\n { \"tbuffer\", Ty::UniformBuffer },\n\n { \"break\", Ty::CtrlTransfer },\n { \"continue\", Ty::CtrlTransfer },\n { \"discard\", Ty::CtrlTransfer },\n\n { \"return\", Ty::Return },\n\n { \"uniform\", Ty::InputModifier },\n { \"in\", Ty::InputModifier },\n { \"out\", Ty::InputModifier },\n { \"inout\", Ty::InputModifier },\n\n { \"extern\", Ty::StorageModifier },\n { \"nointerpolation\", Ty::StorageModifier },\n { \"precise\", Ty::StorageModifier },\n { \"shared\", Ty::StorageModifier },\n { \"groupshared\", Ty::StorageModifier },\n { \"static\", Ty::StorageModifier },\n \/\/{ \"uniform\", Ty::StorageModifier }, \/\/ Already used as \"InputModifier\"\n { \"volatile\", Ty::StorageModifier },\n { \"linear\", Ty::StorageModifier },\n { \"centroid\", Ty::StorageModifier },\n { \"noperspective\", Ty::StorageModifier },\n { \"sample\", Ty::StorageModifier },\n\n { \"const\", Ty::TypeModifier },\n { \"row_major\", Ty::TypeModifier },\n { \"column_major\", Ty::TypeModifier },\n };\n}\n\nstatic KeywordMapType keywordMap = GenerateKeywordMap();\n\nconst KeywordMapType& HLSLKeywords()\n{\n return keywordMap;\n}\n\n\n} \/\/ \/namespace Xsc\n\n\n\n\/\/ ================================================================================<commit_msg>Added \"SamplerComparisonState\" to HLSL keywords.<commit_after>\/*\n * HLSLKeywords.cpp\n * \n * This file is part of the XShaderCompiler project (Copyright (c) 2014-2016 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include \"HLSLKeywords.h\"\n\n\nnamespace Xsc\n{\n\n\nstatic KeywordMapType GenerateKeywordMap()\n{\n using Ty = Token::Types;\n\n return\n {\n { \"true\", Ty::BoolLiteral },\n { \"false\", Ty::BoolLiteral },\n\n { \"void\", Ty::Void },\n\n { \"bool\", Ty::ScalarType },\n { \"bool1\", Ty::ScalarType },\n { \"bool1x1\", Ty::ScalarType },\n { \"int\", Ty::ScalarType },\n { \"int1\", Ty::ScalarType },\n { \"int1x1\", Ty::ScalarType },\n { \"uint\", Ty::ScalarType },\n { \"uint1\", Ty::ScalarType },\n { \"uint1x1\", Ty::ScalarType },\n { \"half\", Ty::ScalarType },\n { \"half1\", Ty::ScalarType },\n { \"half1x1\", Ty::ScalarType },\n { \"float\", Ty::ScalarType },\n { \"float1\", Ty::ScalarType },\n { \"float1x1\", Ty::ScalarType },\n { \"double\", Ty::ScalarType },\n { \"double1\", Ty::ScalarType },\n { \"double1x1\", Ty::ScalarType },\n\n { \"bool2\", Ty::VectorType },\n { \"bool3\", Ty::VectorType },\n { \"bool4\", Ty::VectorType },\n { \"int2\", Ty::VectorType },\n { \"int3\", Ty::VectorType },\n { \"int4\", Ty::VectorType },\n { \"uint2\", Ty::VectorType },\n { \"uint3\", Ty::VectorType },\n { \"uint4\", Ty::VectorType },\n { \"half2\", Ty::VectorType },\n { \"half3\", Ty::VectorType },\n { \"half4\", Ty::VectorType },\n { \"float2\", Ty::VectorType },\n { \"float3\", Ty::VectorType },\n { \"float4\", Ty::VectorType },\n { \"double2\", Ty::VectorType },\n { \"double3\", Ty::VectorType },\n { \"double4\", Ty::VectorType },\n\n { \"bool2x2\", Ty::MatrixType },\n { \"bool2x3\", Ty::MatrixType },\n { \"bool2x4\", Ty::MatrixType },\n { \"bool3x2\", Ty::MatrixType },\n { \"bool3x3\", Ty::MatrixType },\n { \"bool3x4\", Ty::MatrixType },\n { \"bool4x2\", Ty::MatrixType },\n { \"bool4x3\", Ty::MatrixType },\n { \"bool4x4\", Ty::MatrixType },\n { \"int2x2\", Ty::MatrixType },\n { \"int2x3\", Ty::MatrixType },\n { \"int2x4\", Ty::MatrixType },\n { \"int3x2\", Ty::MatrixType },\n { \"int3x3\", Ty::MatrixType },\n { \"int3x4\", Ty::MatrixType },\n { \"int4x2\", Ty::MatrixType },\n { \"int4x3\", Ty::MatrixType },\n { \"int4x4\", Ty::MatrixType },\n { \"uint2x2\", Ty::MatrixType },\n { \"uint2x3\", Ty::MatrixType },\n { \"uint2x4\", Ty::MatrixType },\n { \"uint3x2\", Ty::MatrixType },\n { \"uint3x3\", Ty::MatrixType },\n { \"uint3x4\", Ty::MatrixType },\n { \"uint4x2\", Ty::MatrixType },\n { \"uint4x3\", Ty::MatrixType },\n { \"uint4x4\", Ty::MatrixType },\n { \"half2x2\", Ty::MatrixType },\n { \"half2x3\", Ty::MatrixType },\n { \"half2x4\", Ty::MatrixType },\n { \"half3x2\", Ty::MatrixType },\n { \"half3x3\", Ty::MatrixType },\n { \"half3x4\", Ty::MatrixType },\n { \"half4x2\", Ty::MatrixType },\n { \"half4x3\", Ty::MatrixType },\n { \"half4x4\", Ty::MatrixType },\n { \"float2x2\", Ty::MatrixType },\n { \"float2x3\", Ty::MatrixType },\n { \"float2x4\", Ty::MatrixType },\n { \"float3x2\", Ty::MatrixType },\n { \"float3x3\", Ty::MatrixType },\n { \"float3x4\", Ty::MatrixType },\n { \"float4x2\", Ty::MatrixType },\n { \"float4x3\", Ty::MatrixType },\n { \"float4x4\", Ty::MatrixType },\n { \"double2x2\", Ty::MatrixType },\n { \"double2x3\", Ty::MatrixType },\n { \"double2x4\", Ty::MatrixType },\n { \"double3x2\", Ty::MatrixType },\n { \"double3x3\", Ty::MatrixType },\n { \"double3x4\", Ty::MatrixType },\n { \"double4x2\", Ty::MatrixType },\n { \"double4x3\", Ty::MatrixType },\n { \"double4x4\", Ty::MatrixType },\n\n { \"do\", Ty::Do },\n { \"while\", Ty::While },\n { \"for\", Ty::For },\n\n { \"if\", Ty::If },\n { \"else\", Ty::Else },\n\n { \"switch\", Ty::Switch },\n { \"case\", Ty::Case },\n { \"default\", Ty::Default },\n\n { \"struct\", Ty::Struct },\n { \"register\", Ty::Register },\n { \"packoffset\", Ty::PackOffset },\n\n { \"sampler\", Ty::Sampler },\n { \"sampler1D\", Ty::Sampler },\n { \"sampler2D\", Ty::Sampler },\n { \"sampler3D\", Ty::Sampler },\n { \"samplerCUBE\", Ty::Sampler },\n { \"sampler_state\", Ty::Sampler },\n { \"SamplerState\", Ty::Sampler },\n { \"SamplerComparisonState\", Ty::Sampler }, \/\/ since D3D10+\n\n { \"Texture1D\", Ty::Texture },\n { \"Texture1DArray\", Ty::Texture },\n { \"Texture2D\", Ty::Texture },\n { \"Texture2DArray\", Ty::Texture },\n { \"Texture3D\", Ty::Texture },\n { \"TextureCube\", Ty::Texture },\n { \"TextureCubeArray\", Ty::Texture },\n { \"Texture2DMS\", Ty::Texture },\n { \"Texture2DMSArray\", Ty::Texture },\n { \"RWTexture1D\", Ty::Texture },\n { \"RWTexture1DArray\", Ty::Texture },\n { \"RWTexture2D\", Ty::Texture },\n { \"RWTexture2DArray\", Ty::Texture },\n { \"RWTexture3D\", Ty::Texture },\n\n { \"AppendStructuredBuffer\", Ty::StorageBuffer },\n { \"Buffer\", Ty::StorageBuffer },\n { \"ByteAddressBuffer\", Ty::StorageBuffer },\n { \"ConsumeStructuredBuffer\", Ty::StorageBuffer },\n { \"StructuredBuffer\", Ty::StorageBuffer },\n { \"RWBuffer\", Ty::StorageBuffer },\n { \"RWByteAddressBuffer\", Ty::StorageBuffer },\n { \"RWStructuredBuffer\", Ty::StorageBuffer },\n\n { \"cbuffer\", Ty::UniformBuffer },\n { \"tbuffer\", Ty::UniformBuffer },\n\n { \"break\", Ty::CtrlTransfer },\n { \"continue\", Ty::CtrlTransfer },\n { \"discard\", Ty::CtrlTransfer },\n\n { \"return\", Ty::Return },\n\n { \"uniform\", Ty::InputModifier },\n { \"in\", Ty::InputModifier },\n { \"out\", Ty::InputModifier },\n { \"inout\", Ty::InputModifier },\n\n { \"extern\", Ty::StorageModifier },\n { \"nointerpolation\", Ty::StorageModifier },\n { \"precise\", Ty::StorageModifier },\n { \"shared\", Ty::StorageModifier },\n { \"groupshared\", Ty::StorageModifier },\n { \"static\", Ty::StorageModifier },\n \/\/{ \"uniform\", Ty::StorageModifier }, \/\/ Already used as \"InputModifier\"\n { \"volatile\", Ty::StorageModifier },\n { \"linear\", Ty::StorageModifier },\n { \"centroid\", Ty::StorageModifier },\n { \"noperspective\", Ty::StorageModifier },\n { \"sample\", Ty::StorageModifier },\n\n { \"const\", Ty::TypeModifier },\n { \"row_major\", Ty::TypeModifier },\n { \"column_major\", Ty::TypeModifier },\n };\n}\n\nstatic KeywordMapType keywordMap = GenerateKeywordMap();\n\nconst KeywordMapType& HLSLKeywords()\n{\n return keywordMap;\n}\n\n\n} \/\/ \/namespace Xsc\n\n\n\n\/\/ ================================================================================<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2018 sysmocom - s.f.m.c. GmbH\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <string.h>\n#include <cstdio>\n#include <fstream>\n#include <string>\n#include <stdarg.h>\n#include <sys\/time.h>\t\/\/ For gettimeofday\n\n#include \"Logger.h\"\n#include \"Threads.h\"\t\/\/ pat added\n\nusing namespace std;\n\nMutex gLogToLock;\n\nstd::ostream& operator<<(std::ostream& os, std::ostringstream& ss)\n{\n\treturn os << ss.str();\n}\n\nLog::~Log()\n{\n\tint mlen = mStream.str().size();\n\tint neednl = (mlen==0 || mStream.str()[mlen-1] != '\\n');\n\tconst char *fmt = neednl ? \"%s\\n\" : \"%s\";\n\tScopedLock lock(gLogToLock);\n\t\/\/ The COUT() macro prevents messages from stomping each other but adds uninteresting thread numbers,\n\t\/\/ so just use std::cout.\n\tLOGPSRC(mCategory, mPriority, filename, line, fmt, mStream.str().c_str());\n}\n\nostringstream& Log::get()\n{\n\treturn mStream;\n}\n\n\/\/ vim: ts=4 sw=4\n<commit_msg>Logger: Disable pthread cancel point inside Logger destructor<commit_after>\/*\n* Copyright (C) 2018 sysmocom - s.f.m.c. GmbH\n*\n*\n* This software is distributed under the terms of the GNU Affero Public License.\n* See the COPYING file in the main directory for details.\n*\n* This use of this software may be subject to additional restrictions.\n* See the LEGAL file in the main directory for details.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <string.h>\n#include <cstdio>\n#include <fstream>\n#include <string>\n#include <stdarg.h>\n#include <sys\/time.h>\t\/\/ For gettimeofday\n\n#include \"Logger.h\"\n#include \"Threads.h\"\t\/\/ pat added\n\nusing namespace std;\n\nMutex gLogToLock;\n\nstd::ostream& operator<<(std::ostream& os, std::ostringstream& ss)\n{\n\treturn os << ss.str();\n}\n\nLog::~Log()\n{\n\tint old_state;\n\tpthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);\n\tint mlen = mStream.str().size();\n\tint neednl = (mlen==0 || mStream.str()[mlen-1] != '\\n');\n\tconst char *fmt = neednl ? \"%s\\n\" : \"%s\";\n\tScopedLock lock(gLogToLock);\n\t\/\/ The COUT() macro prevents messages from stomping each other but adds uninteresting thread numbers,\n\t\/\/ so just use std::cout.\n\tLOGPSRC(mCategory, mPriority, filename, line, fmt, mStream.str().c_str());\n\tpthread_setcancelstate(old_state, NULL);\n}\n\nostringstream& Log::get()\n{\n\treturn mStream;\n}\n\n\/\/ vim: ts=4 sw=4\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#ifndef _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_\n#define _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_\n\n#include \"..\/Concrete\/Stack_LinkedList.h\"\n\nnamespace Stroika::Foundation::Containers::Factory {\n\n \/*\n ********************************************************************************\n ******************************* Stack_Factory<T> *******************************\n ********************************************************************************\n *\/\n#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy\n template <typename T>\n atomic<Stack<T> (*) ()> Stack_Factory<T>::sFactory_ (nullptr);\n#endif\n template <typename T>\n inline Stack<T> Stack_Factory<T>::operator() () const\n {\n \/*\n * Would have been more performant to just and assure always properly set, but to initialize\n * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems\n * with containers constructed before main.\n *\n * This works more generally (and with hopefully modest enough performance impact).\n *\/\n if (auto f = sFactory_.load ()) {\n return f ();\n }\n else {\n return Default_ ();\n }\n }\n template <typename T>\n inline void Stack_Factory<T>::Register (Stack<T> (*factory) ())\n {\n sFactory_ = factory;\n }\n template <typename T>\n inline Stack<T> Stack_Factory<T>::Default_ ()\n {\n return Concrete::Stack_LinkedList<T>{};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_ *\/\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#ifndef _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_\n#define _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_\n\n#include \"..\/Concrete\/Stack_LinkedList.h\"\n\nnamespace Stroika::Foundation::Containers::Factory {\n\n \/*\n ********************************************************************************\n ******************************* Stack_Factory<T> *******************************\n ********************************************************************************\n *\/\n#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy\n template <typename T>\n atomic<Stack<T> (*) ()> Stack_Factory<T>::sFactory_{nullptr};\n#endif\n template <typename T>\n inline Stack<T> Stack_Factory<T>::operator() () const\n {\n \/*\n * Would have been more performant to just and assure always properly set, but to initialize\n * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems\n * with containers constructed before main.\n *\n * This works more generally (and with hopefully modest enough performance impact).\n *\/\n if (auto f = sFactory_.load ()) {\n return f ();\n }\n else {\n return Default_ ();\n }\n }\n template <typename T>\n inline void Stack_Factory<T>::Register (Stack<T> (*factory) ())\n {\n sFactory_ = factory;\n }\n template <typename T>\n inline Stack<T> Stack_Factory<T>::Default_ ()\n {\n return Concrete::Stack_LinkedList<T>{};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Containers_Concrete_Stack_Factory_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageLiveWireContourModelFilter.h\"\n\n\n#include <itkImageRegionIterator.h>\n#include <itkCastImageFilter.h>\n#include <itkGradientMagnitudeImageFilter.h>\n\n\nmitk::ImageLiveWireContourModelFilter::ImageLiveWireContourModelFilter()\n{\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNumberOfRequiredInputs(1);\n this->SetNumberOfIndexedOutputs( 1 );\n this->SetNthOutput(0, output.GetPointer());\n m_CostFunction = ImageLiveWireContourModelFilter::CostFunctionType::New();\n m_ShortestPathFilter = ShortestPathImageFilterType::New();\n m_ShortestPathFilter->SetCostFunction(m_CostFunction);\n m_UseDynamicCostMap = false;\n m_ImageModified = false;\n m_Timestep = 0;\n}\n\nmitk::ImageLiveWireContourModelFilter::~ImageLiveWireContourModelFilter()\n{\n\n}\n\n\nmitk::ImageLiveWireContourModelFilter::OutputType* mitk::ImageLiveWireContourModelFilter::GetOutput()\n{\n return Superclass::GetOutput();\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n this->SetInput( 0, input );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( unsigned int idx, const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n if ( idx + 1 > this->GetNumberOfInputs() )\n {\n this->SetNumberOfRequiredInputs(idx + 1);\n }\n if ( input != static_cast<InputType*> ( this->ProcessObject::GetInput ( idx ) ) )\n {\n this->ProcessObject::SetNthInput ( idx, const_cast<InputType*> ( input ) );\n this->Modified();\n this->m_ImageModified = true;\n m_ShortestPathFilter = ShortestPathImageFilterType::New();\n m_ShortestPathFilter->SetCostFunction(m_CostFunction);\n }\n}\n\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( void )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(0));\n}\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( unsigned int idx )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(idx));\n}\n\n\nvoid mitk::ImageLiveWireContourModelFilter::GenerateData()\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n if(!input)\n {\n MITK_ERROR << \"No input available.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: No input available. Please set the input!\");\n return;\n }\n\n if( input->GetDimension() != 2 )\n {\n MITK_ERROR << \"Filter is only working on 2D images.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: Filter is only working on 2D images.. Please make sure that the input is 2D!\");\n return;\n }\n\n if( m_ImageModified )\n {\n AccessFixedDimensionByItk(input, ItkPreProcessImage, 2);\n m_ImageModified = false;\n }\n\n input->GetGeometry()->WorldToIndex(m_StartPoint, m_StartPointInIndex);\n input->GetGeometry()->WorldToIndex(m_EndPoint, m_EndPointInIndex);\n\n \/\/only start calculating if both indices are inside image geometry\n if( input->GetGeometry()->IsIndexInside(this->m_StartPointInIndex) && input->GetGeometry()->IsIndexInside(this->m_EndPointInIndex) )\n {\n try\n {\n this->UpdateLiveWire();\n }\n catch( itk::ExceptionObject & e )\n {\n MITK_INFO << \"Exception caught during live wiring calculation: \" << e;\n m_ImageModified = true;\n return;\n }\n }\n}\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::ItkPreProcessImage (itk::Image<TPixel, VImageDimension>* inputImage)\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef itk::CastImageFilter< InputImageType, FloatImageType > CastFilterType;\n\n typename CastFilterType::Pointer castFilter = CastFilterType::New();\n castFilter->SetInput(inputImage);\n castFilter->Update();\n m_PreProcessedImage = castFilter->GetOutput();\n m_CostFunction->SetImage( m_PreProcessedImage );\n m_ShortestPathFilter->SetInput( m_PreProcessedImage );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::UpdateLiveWire()\n{\n\/\/ compute the requested region for itk filters\n FloatImageType::IndexType startPoint, endPoint;\n\n startPoint[0] = m_StartPointInIndex[0];\n startPoint[1] = m_StartPointInIndex[1];\n\n endPoint[0] = m_EndPointInIndex[0];\n endPoint[1] = m_EndPointInIndex[1];\n\n \/\/minimum value in each direction for startRegion\n FloatImageType::IndexType startRegion;\n startRegion[0] = startPoint[0] < endPoint[0] ? startPoint[0] : endPoint[0];\n startRegion[1] = startPoint[1] < endPoint[1] ? startPoint[1] : endPoint[1];\n\n \/\/maximum value in each direction for size\n FloatImageType::SizeType size;\n size[0] = abs( startPoint[0] - endPoint[0] );\n size[1] = abs( startPoint[1] - endPoint[1] );\n\n MITK_INFO << \"start region: \" << startRegion[0] << \" \" << startRegion[1];\n MITK_INFO << \"size: \" << size[0] << \" \" << size[1];\n\n CostFunctionType::RegionType region;\n region.SetSize( size );\n region.SetIndex( startRegion );\n\n \/\/inputImage->SetRequestedRegion(region);\n\n \/\/ extracts features from image and calculates costs\n \/\/m_CostFunction->SetImage(m_PreProcessedImage);\n m_CostFunction->SetStartIndex(startPoint);\n m_CostFunction->SetEndIndex(endPoint);\n m_CostFunction->SetRequestedRegion(region);\n m_CostFunction->SetUseCostMap(m_UseDynamicCostMap);\n\n \/\/ calculate shortest path between start and end point\n m_ShortestPathFilter->SetFullNeighborsMode(true);\n \/\/m_ShortestPathFilter->SetInput( m_CostFunction->SetImage(m_PreProcessedImage) );\n m_ShortestPathFilter->SetMakeOutputImage(false);\n\n \/\/m_ShortestPathFilter->SetCalcAllDistances(true);\n m_ShortestPathFilter->SetStartIndex(startPoint);\n m_ShortestPathFilter->SetEndIndex(endPoint);\n\n m_ShortestPathFilter->Update();\n\n \/\/ construct contour from path image\n \/\/get the shortest path as vector\n ShortestPathType shortestPath = m_ShortestPathFilter->GetVectorPath();\n\n \/\/fill the output contour with control points from the path\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNthOutput(0, output.GetPointer());\n\n\/\/ OutputType::Pointer output = dynamic_cast<OutputType*> ( this->GetOutput() );\n output->Expand(m_Timestep+1);\n\n\/\/ output->Clear();\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n ShortestPathType::const_iterator pathIterator = shortestPath.begin();\n\n while(pathIterator != shortestPath.end())\n {\n mitk::Point3D currentPoint;\n currentPoint[0] = (*pathIterator)[0];\n currentPoint[1] = (*pathIterator)[1];\n currentPoint[2] = 0;\n\n input->GetGeometry()->IndexToWorld(currentPoint, currentPoint);\n output->AddVertex(currentPoint, false, m_Timestep);\n\n pathIterator++;\n }\n}\n\n\nbool mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMap(mitk::ContourModel* path)\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n if(input)\n {\n AccessFixedDimensionByItk_1(input,CreateDynamicCostMapByITK, 2, path);\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMapByITK( itk::Image<TPixel, VImageDimension>* inputImage, mitk::ContourModel* path )\n{\n \/*++++++++++ create dynamic cost transfer map ++++++++++*\/\n\n \/* Compute the costs of the gradient magnitude dynamically.\n * using a map of the histogram of gradient magnitude image.\n * Use the histogram gradient map to interpolate the costs\n * with gaussing function including next two bins right and left\n * to current position x. With the histogram gradient costs are interpolated\n * with a gaussing function summation of next two bins right and left\n * to current position x.\n *\/\n std::vector< itk::Index<VImageDimension> > shortestPath;\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n if(path == NULL)\n {\n OutputType::Pointer output = this->GetOutput();\n mitk::ContourModel::VertexIterator it = output->IteratorBegin();\n while( it != output->IteratorEnd() )\n {\n itk::Index<VImageDimension> cur;\n mitk::Point3D c = (*it)->Coordinates;\n input->GetGeometry()->WorldToIndex(c, c);\n cur[0] = c[0];\n cur[1] = c[1];\n\n shortestPath.push_back( cur);\n it++;\n }\n }\n else\n {\n\n mitk::ContourModel::VertexIterator it = path->IteratorBegin();\n while( it != path->IteratorEnd() )\n {\n itk::Index<VImageDimension> cur;\n mitk::Point3D c = (*it)->Coordinates;\n input->GetGeometry()->WorldToIndex(c, c);\n cur[0] = c[0];\n cur[1] = c[1];\n\n shortestPath.push_back( cur);\n it++;\n }\n\n }\n\n\n \/*+++ filter image gradient magnitude +++*\/\n typedef itk::GradientMagnitudeImageFilter< itk::Image<TPixel, VImageDimension>, itk::Image<TPixel, VImageDimension> > GradientMagnitudeFilterType;\n typename GradientMagnitudeFilterType::Pointer gradientFilter = GradientMagnitudeFilterType::New();\n gradientFilter->SetInput(inputImage);\n gradientFilter->Update();\n typename itk::Image<TPixel, VImageDimension>::Pointer gradientMagnImage = gradientFilter->GetOutput();\n\n \/\/get the path\n\n\n \/\/iterator of path\n typename std::vector< itk::Index<VImageDimension> >::iterator pathIterator = shortestPath.begin();\n\n std::map< int, int > histogram;\n\n \/\/create histogram within path\n while(pathIterator != shortestPath.end())\n {\n \/\/count pixel values\n \/\/use scale factor to avoid mapping gradients between 0.0 and 1.0 to same bin\n histogram[ static_cast<int>( gradientMagnImage->GetPixel((*pathIterator)) * ImageLiveWireContourModelFilter::CostFunctionType::MAPSCALEFACTOR ) ] += 1;\n\n pathIterator++;\n }\n\n double max = 1.0;\n\n if( !histogram.empty() )\n {\n\n std::map< int, int >::iterator itMAX;\n\n \/\/get max of histogramm\n int currentMaxValue = 0;\n std::map< int, int >::iterator it = histogram.begin();\n while( it != histogram.end())\n {\n if((*it).second > currentMaxValue)\n {\n itMAX = it;\n currentMaxValue = (*it).second;\n }\n it++;\n }\n\n\n std::map< int, int >::key_type keyOfMax = itMAX->first;\n\n\n \/*+++++++++++++++++++++++++ compute the to max of gaussian summation ++++++++++++++++++++++++*\/\n std::map< int, int >::iterator end = histogram.end();\n std::map< int, int >::iterator last = --(histogram.end());\n\n std::map< int, int >::iterator left2;\n std::map< int, int >::iterator left1;\n std::map< int, int >::iterator right1;\n std::map< int, int >::iterator right2;\n\n right1 = itMAX;\n\n\n if(right1 == end || right1 == last )\n {\n right2 = end;\n }\n else\/\/( right1 <= last )\n {\n std::map< int, int >::iterator temp = right1;\n right2 = ++right1;\/\/rght1 + 1\n right1 = temp;\n }\n\n\n if( right1 == histogram.begin() )\n {\n left1 = end;\n left2 = end;\n }\n else if( right1 == (++(histogram.begin())) )\n {\n std::map< int, int >::iterator temp = right1;\n left1 = --right1;\/\/rght1 - 1\n right1 = temp;\n left2 = end;\n }\n else\n {\n std::map< int, int >::iterator temp = right1;\n left1 = --right1;\/\/rght1 - 1\n left2 = --right1;\/\/rght1 - 2\n right1 = temp;\n }\n\n double partRight1, partRight2, partLeft1, partLeft2;\n partRight1 = partRight2 = partLeft1 = partLeft2 = 0.0;\n\n\n \/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n f(x) = v(bin) * e^ ( -1\/2 * (|x-k(bin)| \/ sigma)^2 )\n\n gaussian approximation\n\n where\n v(bin) is the value in the map\n k(bin) is the key\n *\/\n if( left2 != end )\n {\n partLeft2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left2->first, left2->second);\n }\n\n if( left1 != end )\n {\n partLeft1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left1->first, left1->second);\n }\n\n if( right1 != end )\n {\n partRight1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right1->first, right1->second);\n }\n\n if( right2 != end )\n {\n partRight2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right2->first, right2->second);\n }\n \/*----------------------------------------------------------------------------*\/\n\n max = (partRight1 + partRight2 + partLeft1 + partLeft2);\n\n }\n\n this->m_CostFunction->SetDynamicCostMap(histogram);\n this->m_CostFunction->SetCostMapMaximum(max);\n\n}\n<commit_msg>use a bigger region<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageLiveWireContourModelFilter.h\"\n\n\n#include <itkImageRegionIterator.h>\n#include <itkCastImageFilter.h>\n#include <itkGradientMagnitudeImageFilter.h>\n\n\nmitk::ImageLiveWireContourModelFilter::ImageLiveWireContourModelFilter()\n{\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNumberOfRequiredInputs(1);\n this->SetNumberOfIndexedOutputs( 1 );\n this->SetNthOutput(0, output.GetPointer());\n m_CostFunction = ImageLiveWireContourModelFilter::CostFunctionType::New();\n m_ShortestPathFilter = ShortestPathImageFilterType::New();\n m_ShortestPathFilter->SetCostFunction(m_CostFunction);\n m_UseDynamicCostMap = false;\n m_ImageModified = false;\n m_Timestep = 0;\n}\n\nmitk::ImageLiveWireContourModelFilter::~ImageLiveWireContourModelFilter()\n{\n\n}\n\n\nmitk::ImageLiveWireContourModelFilter::OutputType* mitk::ImageLiveWireContourModelFilter::GetOutput()\n{\n return Superclass::GetOutput();\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n this->SetInput( 0, input );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::SetInput ( unsigned int idx, const mitk::ImageLiveWireContourModelFilter::InputType* input )\n{\n if ( idx + 1 > this->GetNumberOfInputs() )\n {\n this->SetNumberOfRequiredInputs(idx + 1);\n }\n if ( input != static_cast<InputType*> ( this->ProcessObject::GetInput ( idx ) ) )\n {\n this->ProcessObject::SetNthInput ( idx, const_cast<InputType*> ( input ) );\n this->Modified();\n this->m_ImageModified = true;\n m_ShortestPathFilter = ShortestPathImageFilterType::New();\n m_ShortestPathFilter->SetCostFunction(m_CostFunction);\n }\n}\n\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( void )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(0));\n}\n\n\nconst mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( unsigned int idx )\n{\n if (this->GetNumberOfInputs() < 1)\n return NULL;\n return static_cast<const mitk::ImageLiveWireContourModelFilter::InputType*>(this->ProcessObject::GetInput(idx));\n}\n\n\nvoid mitk::ImageLiveWireContourModelFilter::GenerateData()\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n if(!input)\n {\n MITK_ERROR << \"No input available.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: No input available. Please set the input!\");\n return;\n }\n\n if( input->GetDimension() != 2 )\n {\n MITK_ERROR << \"Filter is only working on 2D images.\";\n itkExceptionMacro(\"mitk::ImageToLiveWireContourFilter: Filter is only working on 2D images.. Please make sure that the input is 2D!\");\n return;\n }\n\n if( m_ImageModified )\n {\n AccessFixedDimensionByItk(input, ItkPreProcessImage, 2);\n m_ImageModified = false;\n }\n\n input->GetGeometry()->WorldToIndex(m_StartPoint, m_StartPointInIndex);\n input->GetGeometry()->WorldToIndex(m_EndPoint, m_EndPointInIndex);\n\n \/\/only start calculating if both indices are inside image geometry\n if( input->GetGeometry()->IsIndexInside(this->m_StartPointInIndex) && input->GetGeometry()->IsIndexInside(this->m_EndPointInIndex) )\n {\n try\n {\n this->UpdateLiveWire();\n }\n catch( itk::ExceptionObject & e )\n {\n MITK_INFO << \"Exception caught during live wiring calculation: \" << e;\n m_ImageModified = true;\n return;\n }\n }\n}\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::ItkPreProcessImage (itk::Image<TPixel, VImageDimension>* inputImage)\n{\n typedef itk::Image< TPixel, VImageDimension > InputImageType;\n typedef itk::CastImageFilter< InputImageType, FloatImageType > CastFilterType;\n\n typename CastFilterType::Pointer castFilter = CastFilterType::New();\n castFilter->SetInput(inputImage);\n castFilter->Update();\n m_PreProcessedImage = castFilter->GetOutput();\n m_CostFunction->SetImage( m_PreProcessedImage );\n m_ShortestPathFilter->SetInput( m_PreProcessedImage );\n}\n\nvoid mitk::ImageLiveWireContourModelFilter::UpdateLiveWire()\n{\n\/\/ compute the requested region for itk filters\n FloatImageType::IndexType startPoint, endPoint;\n\n startPoint[0] = m_StartPointInIndex[0];\n startPoint[1] = m_StartPointInIndex[1];\n\n endPoint[0] = m_EndPointInIndex[0];\n endPoint[1] = m_EndPointInIndex[1];\n\n \/\/minimum value in each direction for startRegion\n FloatImageType::IndexType startRegion;\n startRegion[0] = startPoint[0] < endPoint[0] ? startPoint[0] : endPoint[0];\n startRegion[1] = startPoint[1] < endPoint[1] ? startPoint[1] : endPoint[1];\n\n \/\/maximum value in each direction for size\n FloatImageType::SizeType size;\n size[0] = abs( startPoint[0] - endPoint[0] ) + 1;\n size[1] = abs( startPoint[1] - endPoint[1] ) + 1;\n\n MITK_INFO << \"start region: \" << startRegion[0] << \" \" << startRegion[1];\n MITK_INFO << \"size: \" << size[0] << \" \" << size[1];\n\n CostFunctionType::RegionType region;\n region.SetSize( size );\n region.SetIndex( startRegion );\n\n \/\/inputImage->SetRequestedRegion(region);\n\n \/\/ extracts features from image and calculates costs\n \/\/m_CostFunction->SetImage(m_PreProcessedImage);\n m_CostFunction->SetStartIndex(startPoint);\n m_CostFunction->SetEndIndex(endPoint);\n m_CostFunction->SetRequestedRegion(region);\n m_CostFunction->SetUseCostMap(m_UseDynamicCostMap);\n\n \/\/ calculate shortest path between start and end point\n m_ShortestPathFilter->SetFullNeighborsMode(true);\n \/\/m_ShortestPathFilter->SetInput( m_CostFunction->SetImage(m_PreProcessedImage) );\n m_ShortestPathFilter->SetMakeOutputImage(false);\n\n \/\/m_ShortestPathFilter->SetCalcAllDistances(true);\n m_ShortestPathFilter->SetStartIndex(startPoint);\n m_ShortestPathFilter->SetEndIndex(endPoint);\n\n m_ShortestPathFilter->Update();\n\n \/\/ construct contour from path image\n \/\/get the shortest path as vector\n ShortestPathType shortestPath = m_ShortestPathFilter->GetVectorPath();\n\n \/\/fill the output contour with control points from the path\n OutputType::Pointer output = dynamic_cast<OutputType*> ( this->MakeOutput( 0 ).GetPointer() );\n this->SetNthOutput(0, output.GetPointer());\n\n\/\/ OutputType::Pointer output = dynamic_cast<OutputType*> ( this->GetOutput() );\n output->Expand(m_Timestep+1);\n\n\/\/ output->Clear();\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n\n ShortestPathType::const_iterator pathIterator = shortestPath.begin();\n\n while(pathIterator != shortestPath.end())\n {\n mitk::Point3D currentPoint;\n currentPoint[0] = (*pathIterator)[0];\n currentPoint[1] = (*pathIterator)[1];\n currentPoint[2] = 0;\n\n input->GetGeometry()->IndexToWorld(currentPoint, currentPoint);\n output->AddVertex(currentPoint, false, m_Timestep);\n\n pathIterator++;\n }\n}\n\n\nbool mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMap(mitk::ContourModel* path)\n{\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n if(input)\n {\n AccessFixedDimensionByItk_1(input,CreateDynamicCostMapByITK, 2, path);\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMapByITK( itk::Image<TPixel, VImageDimension>* inputImage, mitk::ContourModel* path )\n{\n \/*++++++++++ create dynamic cost transfer map ++++++++++*\/\n\n \/* Compute the costs of the gradient magnitude dynamically.\n * using a map of the histogram of gradient magnitude image.\n * Use the histogram gradient map to interpolate the costs\n * with gaussing function including next two bins right and left\n * to current position x. With the histogram gradient costs are interpolated\n * with a gaussing function summation of next two bins right and left\n * to current position x.\n *\/\n std::vector< itk::Index<VImageDimension> > shortestPath;\n\n mitk::Image::ConstPointer input = dynamic_cast<const mitk::Image*>(this->GetInput());\n if(path == NULL)\n {\n OutputType::Pointer output = this->GetOutput();\n mitk::ContourModel::VertexIterator it = output->IteratorBegin();\n while( it != output->IteratorEnd() )\n {\n itk::Index<VImageDimension> cur;\n mitk::Point3D c = (*it)->Coordinates;\n input->GetGeometry()->WorldToIndex(c, c);\n cur[0] = c[0];\n cur[1] = c[1];\n\n shortestPath.push_back( cur);\n it++;\n }\n }\n else\n {\n\n mitk::ContourModel::VertexIterator it = path->IteratorBegin();\n while( it != path->IteratorEnd() )\n {\n itk::Index<VImageDimension> cur;\n mitk::Point3D c = (*it)->Coordinates;\n input->GetGeometry()->WorldToIndex(c, c);\n cur[0] = c[0];\n cur[1] = c[1];\n\n shortestPath.push_back( cur);\n it++;\n }\n\n }\n\n\n \/*+++ filter image gradient magnitude +++*\/\n typedef itk::GradientMagnitudeImageFilter< itk::Image<TPixel, VImageDimension>, itk::Image<TPixel, VImageDimension> > GradientMagnitudeFilterType;\n typename GradientMagnitudeFilterType::Pointer gradientFilter = GradientMagnitudeFilterType::New();\n gradientFilter->SetInput(inputImage);\n gradientFilter->Update();\n typename itk::Image<TPixel, VImageDimension>::Pointer gradientMagnImage = gradientFilter->GetOutput();\n\n \/\/get the path\n\n\n \/\/iterator of path\n typename std::vector< itk::Index<VImageDimension> >::iterator pathIterator = shortestPath.begin();\n\n std::map< int, int > histogram;\n\n \/\/create histogram within path\n while(pathIterator != shortestPath.end())\n {\n \/\/count pixel values\n \/\/use scale factor to avoid mapping gradients between 0.0 and 1.0 to same bin\n histogram[ static_cast<int>( gradientMagnImage->GetPixel((*pathIterator)) * ImageLiveWireContourModelFilter::CostFunctionType::MAPSCALEFACTOR ) ] += 1;\n\n pathIterator++;\n }\n\n double max = 1.0;\n\n if( !histogram.empty() )\n {\n\n std::map< int, int >::iterator itMAX;\n\n \/\/get max of histogramm\n int currentMaxValue = 0;\n std::map< int, int >::iterator it = histogram.begin();\n while( it != histogram.end())\n {\n if((*it).second > currentMaxValue)\n {\n itMAX = it;\n currentMaxValue = (*it).second;\n }\n it++;\n }\n\n\n std::map< int, int >::key_type keyOfMax = itMAX->first;\n\n\n \/*+++++++++++++++++++++++++ compute the to max of gaussian summation ++++++++++++++++++++++++*\/\n std::map< int, int >::iterator end = histogram.end();\n std::map< int, int >::iterator last = --(histogram.end());\n\n std::map< int, int >::iterator left2;\n std::map< int, int >::iterator left1;\n std::map< int, int >::iterator right1;\n std::map< int, int >::iterator right2;\n\n right1 = itMAX;\n\n\n if(right1 == end || right1 == last )\n {\n right2 = end;\n }\n else\/\/( right1 <= last )\n {\n std::map< int, int >::iterator temp = right1;\n right2 = ++right1;\/\/rght1 + 1\n right1 = temp;\n }\n\n\n if( right1 == histogram.begin() )\n {\n left1 = end;\n left2 = end;\n }\n else if( right1 == (++(histogram.begin())) )\n {\n std::map< int, int >::iterator temp = right1;\n left1 = --right1;\/\/rght1 - 1\n right1 = temp;\n left2 = end;\n }\n else\n {\n std::map< int, int >::iterator temp = right1;\n left1 = --right1;\/\/rght1 - 1\n left2 = --right1;\/\/rght1 - 2\n right1 = temp;\n }\n\n double partRight1, partRight2, partLeft1, partLeft2;\n partRight1 = partRight2 = partLeft1 = partLeft2 = 0.0;\n\n\n \/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n f(x) = v(bin) * e^ ( -1\/2 * (|x-k(bin)| \/ sigma)^2 )\n\n gaussian approximation\n\n where\n v(bin) is the value in the map\n k(bin) is the key\n *\/\n if( left2 != end )\n {\n partLeft2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left2->first, left2->second);\n }\n\n if( left1 != end )\n {\n partLeft1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left1->first, left1->second);\n }\n\n if( right1 != end )\n {\n partRight1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right1->first, right1->second);\n }\n\n if( right2 != end )\n {\n partRight2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right2->first, right2->second);\n }\n \/*----------------------------------------------------------------------------*\/\n\n max = (partRight1 + partRight2 + partLeft1 + partLeft2);\n\n }\n\n this->m_CostFunction->SetDynamicCostMap(histogram);\n this->m_CostFunction->SetCostMapMaximum(max);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n* @file Simulation.cpp\n* @author <a href=\"mailto:schlottb@informatik.hu-berlin.de\">Benjamin Schlotter<\/a>\n* Implementation of class Simulation\n*\/\n\n#include \"Simulation.h\"\n\nusing namespace naoth;\nusing namespace std;\n\nSimulation::Simulation()\n{\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_one_action_point:global\",\"draw_one_action_point:global\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_ball\",\"draw_ball\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:ActionTarget\",\"ActionTarget\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_best_action\",\"best action\",false);\n \/\/DEBUG_REQUEST_REGISTER(\"Simulation:draw_pessimistic_best_action\",\"best pessimistic action\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:GoalLinePreview\",\"GoalLinePreview\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_potential_field\",\"Draw Potential Field\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:use_Parameters\",\"use_Parameters\",false);\n\n getDebugParameterList().add(&theParameters);\n\n \/\/actionRingBuffer.resize(ActionModel::numOfActions);\n \/\/calculate the actions \n action_local.reserve(KickActionModel::numOfActions);\n\n action_local.push_back(Action(KickActionModel::none, Vector2d()));\n action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); \/\/ long\n action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); \/\/ short\n action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); \/\/ right\n action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); \/\/ left\n\n actionRingBuffer.resize(KickActionModel::numOfActions);\n}\n\nSimulation::~Simulation(){}\n\nvoid Simulation::execute()\n{\n DEBUG_REQUEST(\"Simulation:use_Parameters\",\n action_local.clear();\n action_local.reserve(KickActionModel::numOfActions);\n\n action_local.push_back(Action(KickActionModel::none, Vector2d()));\n action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); \/\/ long\n action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); \/\/ short\n action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); \/\/ right\n action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); \/\/ left\n\n actionRingBuffer.resize(KickActionModel::numOfActions);\n );\n\n \n if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1)\n {\n return;\n }\n else\n {\n int best_action = 0;\n \/\/int pessimistic_best_action = 0;\n for(size_t i=0; i<actionRingBuffer.size(); i++)\n {\n simulate(action_local[i], actionRingBuffer[i]);\n\n if(action_local[i].potential < action_local[best_action].potential)\n {\t\n best_action = i;\n }\n \/\/The pessimistic option\n \/*if(action_local[i].pessimistPotential < action_local[best_action].pessimistPotential)\n {\t\n pessimistic_best_action = i;\n }*\/\n\n }\n\n getKickActionModel().myAction = action_local[best_action].id();\n\n DEBUG_REQUEST(\"Simulation:draw_best_action\",\n {\n FIELD_DRAWING_CONTEXT;\n PEN(\"FF69B4\", 7);\n Vector2d actionGlobal = action_local[best_action].target;\n FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50);\n });\n\n \/\/DEBUG_REQUEST(\"Simulation:draw_pessimistic_best_action\",\n \/\/{\n \/\/ FIELD_DRAWING_CONTEXT;\n \/\/ PEN(\"0000FF\", 7);\n \/\/ Vector2d actionGlobal = action_local[pessimistic_best_action].target;\n \/\/ FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50);\n \/\/});\n DEBUG_REQUEST(\"Simulation:draw_potential_field\",\n draw_potential_field();\n );\n\n \n }\n}\/\/end execute\n\nvoid Simulation::simulate(Simulation::Action& action, RingBufferWithSum<double, 30>& oneActionRingBuffer)const\n{\n\n Vector2d ballPositionResult = calculateOneAction(action);\n\n DEBUG_REQUEST(\"Simulation:draw_one_action_point:global\",\n {\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 1);\n CIRCLE( ballPositionResult.x, ballPositionResult.y, 50);\n \/\/TEXT_DRAWING(ballPositionResult.x,ballPositionResult.y-150,action.maximum);\n \/\/TEXT_DRAWING(ballPositionResult.x,ballPositionResult.y-250,action.minimum);\n });\n\n double v = evaluateAction(ballPositionResult);\n\n oneActionRingBuffer.add(v);\n\n \/\/ HACK\n action.potential = oneActionRingBuffer.getAverage();\n action.target = ballPositionResult;\n \/\/double s = 0;\n \/\/int z = 0;\n \/\/\/\/Durch den Buffer durchgehen und alle Werte kleiner Average aufsummieren\n \/\/for (int k=0; k < oneActionRingBuffer.size(); k++){\n \/\/ if(oneActionRingBuffer[k] <= action.potential){\n \/\/ s += oneActionRingBuffer[k];\n \/\/ z++;\n \/\/ }\n \/\/}\n \/\/action.pessimistPotential = s\/z;\n \/\/\/\/Todo: als text minimum und maximum ausgeben\n \/\/action.minimum = oneActionRingBuffer.getMinimum();\n\n \/\/double max = oneActionRingBuffer[0];\n \/\/for(int i = 0; i < oneActionRingBuffer.size();i++)\n \/\/ {\n \/\/ if(oneActionRingBuffer[i] > max) max = oneActionRingBuffer[i];\n \/\/ }\n \/\/action.maximum = max;\n \/\/if there is big gap between our values(average and median), we know it is not good\n \/\/action.goodness = actionRingBuffer.getAverage()\/actionRingBuffer.getMedian();\n}\n\nVector2d Simulation::calculateOneAction(const Action& action) const\n{\n \/\/ STEP 1: predict the action outcome\n const Vector2d& ballRelativePreview = getBallModel().positionPreview;\n\n DEBUG_REQUEST(\"Simulation:draw_ball\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"FF0000\", 1);\n Vector2d ball = getRobotPose() * getBallModel().positionPreview;\n CIRCLE( ball.x, ball.y, 50);\n );\n\n Vector2d result = action.predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance);\n\n DEBUG_REQUEST(\"Simulation:ActionTarget\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"0000FF\", 1);\n Vector2d ball = getRobotPose() * result;\n CIRCLE( ball.x, ball.y, 50);\n );\n\n\n \/\/ STEP 2: calculate the goal line\n GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());\n Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip \/ oppGoalModel.leftPost;\n Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip \/ oppGoalModel.rightPost;\n\n \/\/the endpoints of our line are a shortened version of the goal line\n Vector2d goalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize();\n Vector2d leftEndpoint = oppGoalPostLeftPreview + goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);\n Vector2d rightEndpoint = oppGoalPostRightPreview - goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);\n\n \/\/ this is the goalline we are shooting for\n Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);\n \n \/\/ note: the drawing is global\n DEBUG_REQUEST(\"Simulation:GoalLinePreview\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 1);\n Vector2d globalLeft = getRobotPose() * leftEndpoint;\n Vector2d globalRight = getRobotPose() * rightEndpoint;\n LINE(globalLeft.x,globalLeft.y,globalRight.x,globalRight.y);\n );\n\n \/\/ STEP 3: estimate external factors (shooting a goal, ball moved by referee)\n \/\/Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));\/\/hmm\n Math::LineSegment shootLine(ballRelativePreview, result);\n\n Vector2d resultingBallPosition;\n\n if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) {\n resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);\n } else {\n resultingBallPosition = outsideField(getRobotPose() * result);\n }\n\n return resultingBallPosition;\n}\n \n \/\/correction of distance in percentage, angle in degrees\n Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const\n {\n double random_length = 2.0*Math::random()-1.0;\n double random_angle = 2.0*Math::random()-1.0;\n\n Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);\n noisyAction.rotate(angle_variance*random_angle);\n\n return ball + noisyAction;\n }\n\n\/\/calcualte according to the rules, without the roboter position, the ball position\n\/\/if it goes outside the field\nVector2d Simulation::outsideField(const Vector2d& globalPoint) const\n{ \n Vector2d point = globalPoint;\n\n \/\/Schusslinie\n Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint);\n\n if(getFieldInfo().fieldRect.inside(point)){\n return point;\n }\n else\n \/\/Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat\n { \/\/Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht\n if(point.x > getFieldInfo().xPosOpponentGroundline)\n { \n Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine));\n if(OppOutPoint.y < 0)\n {\n return Vector2d(0, getFieldInfo().yThrowInLineRight);\/\/range check\n } else\n {\n return Vector2d(0, getFieldInfo().yThrowInLineLeft); \n }\n }\n \/\/Own Groundline out - an der seite wo raus geht\n else if(point.x < getFieldInfo().xPosOwnGroundline)\n {\n Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine));\n if(OwnOutPoint.y < 0)\n {\n return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);\/\/range check\n } else\n { \n return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); \n }\n }\n \/\/an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter\n else if(point.y > getFieldInfo().yPosLeftSideline )\n { \n Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine));\n point.x = min(leftOutPoint.x,getRobotPose().translation.x);\n\n if(point.x-1000 < getFieldInfo().xThrowInLineOwn)\n { \n point.x = getFieldInfo().xThrowInLineOwn;\n } else\n { \n point.x -= 1000;\n }\n return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); \/\/range check\n }\n \/\/an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter\n else \/\/(point.y < getFieldInfo().yPosRightSideline)\n { \n Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine));\n point.x = min(rightOutPoint.x,getRobotPose().translation.x);\n\n if(point.x-1000 < getFieldInfo().xThrowInLineOwn)\n {\n point.x = getFieldInfo().xThrowInLineOwn;\n } else\n { \n point.x -= 1000;\n }\n return Vector2d(point.x, getFieldInfo().yThrowInLineRight);\/\/range check\n }\n }\n}\n\ndouble Simulation::evaluateAction(const Vector2d& a) const{\n Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0);\n Vector2d oppDiff = oppGoal - a;\n\n double oppValueX = 0.1;\n double oppValueY = 1;\n MODIFY(\"Simulation:oppValueX\", oppValueX);\n MODIFY(\"Simulation:oppValueY\", oppValueY);\n double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y;\n \n \/\/Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0);\n \/\/Vector2d ownDiff = ownGoal - a;\n \n \/\/double ownValueX = 0.01;\n \/\/double ownValueY = 0.1;\n \/\/MODIFY(\"Simulation:ownValueX\", ownValueX);\n \/\/MODIFY(\"Simulation:ownValueY\", ownValueY);\n \/\/double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y;\n\n \/\/return value_opp - value_own;\n return value_opp;\n}\n\nvoid Simulation::draw_potential_field() const\n{\n static const int ySize = 20;\n static const int xSize = 30;\n double yWidth = 0.5*getFieldInfo().yFieldLength\/(double)ySize;\n double xWidth = 0.5*getFieldInfo().xFieldLength\/(double)xSize;\n\n FIELD_DRAWING_CONTEXT;\n Color white(0.0,0.0,1.0,0.5); \/\/ transparent\n Color black(1.0,0.0,0.0,0.5);\n\n \/\/ create new sample set\n std::vector<double> potential(xSize*ySize);\n int idx = 0;\n\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));\n potential[idx] = evaluateAction(point);\n idx++;\n }\n }\n \n double maxValue = 0;\n idx = 0;\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n maxValue = max(maxValue, potential[idx++]);\n }\n }\n\n if(maxValue == 0) return;\n\n idx = 0;\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));\n \n double t = potential[idx++] \/ maxValue;\n Color color = black*t + white*(1-t);\n PEN(color, 20);\n FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth);\n }\n }\n}\/\/end draw_closest_points<commit_msg>Cleanup DebugRequest<commit_after>\/**\n* @file Simulation.cpp\n* @author <a href=\"mailto:schlottb@informatik.hu-berlin.de\">Benjamin Schlotter<\/a>\n* Implementation of class Simulation\n*\/\n\n#include \"Simulation.h\"\n\nusing namespace naoth;\nusing namespace std;\n\nSimulation::Simulation()\n{\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_one_action_point:global\",\"draw_one_action_point:global\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_ball\",\"draw_ball\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:ActionTarget\",\"ActionTarget\", false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_best_action\",\"best action\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:GoalLinePreview\",\"GoalLinePreview\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:draw_potential_field\",\"Draw Potential Field\",false);\n DEBUG_REQUEST_REGISTER(\"Simulation:use_Parameters\",\"use_Parameters\",false);\n\n getDebugParameterList().add(&theParameters);\n\n \/\/calculate the actions \n action_local.reserve(KickActionModel::numOfActions);\n\n action_local.push_back(Action(KickActionModel::none, Vector2d()));\n action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); \/\/ long\n action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); \/\/ short\n action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); \/\/ right\n action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); \/\/ left\n\n actionRingBuffer.resize(KickActionModel::numOfActions);\n}\n\nSimulation::~Simulation(){}\n\nvoid Simulation::execute()\n{\n DEBUG_REQUEST(\"Simulation:use_Parameters\",\n action_local.clear();\n action_local.reserve(KickActionModel::numOfActions);\n\n action_local.push_back(Action(KickActionModel::none, Vector2d()));\n action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); \/\/ long\n action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); \/\/ short\n action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); \/\/ right\n action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); \/\/ left\n\n actionRingBuffer.resize(KickActionModel::numOfActions);\n );\n\n \n if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1)\n {\n return;\n }\n else\n {\n int best_action = 0;\n for(size_t i=0; i<actionRingBuffer.size(); i++)\n {\n simulate(action_local[i], actionRingBuffer[i]);\n\n if(action_local[i].potential < action_local[best_action].potential)\n {\t\n best_action = i;\n }\n }\n\n getKickActionModel().myAction = action_local[best_action].id();\n\n DEBUG_REQUEST(\"Simulation:draw_best_action\",\n {\n FIELD_DRAWING_CONTEXT;\n PEN(\"FF69B4\", 7);\n Vector2d actionGlobal = action_local[best_action].target;\n FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50);\n });\n\n DEBUG_REQUEST(\"Simulation:draw_potential_field\",\n draw_potential_field();\n );\n\n \n }\n}\/\/end execute\n\nvoid Simulation::simulate(Simulation::Action& action, RingBufferWithSum<double, 30>& oneActionRingBuffer)const\n{\n Vector2d ballPositionResult = calculateOneAction(action);\n\n DEBUG_REQUEST(\"Simulation:draw_one_action_point:global\",\n {\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 1);\n CIRCLE( ballPositionResult.x, ballPositionResult.y, 50);\n });\n\n double v = evaluateAction(ballPositionResult);\n\n oneActionRingBuffer.add(v);\n\n \/\/ HACK\n action.potential = oneActionRingBuffer.getAverage();\n action.target = ballPositionResult;\n}\n\nVector2d Simulation::calculateOneAction(const Action& action) const\n{\n \/\/ STEP 1: predict the action outcome\n const Vector2d& ballRelativePreview = getBallModel().positionPreview;\n\n DEBUG_REQUEST(\"Simulation:draw_ball\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"FF0000\", 1);\n Vector2d ball = getRobotPose() * getBallModel().positionPreview;\n CIRCLE( ball.x, ball.y, 50);\n );\n\n Vector2d result = action.predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance);\n\n DEBUG_REQUEST(\"Simulation:ActionTarget\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"0000FF\", 1);\n Vector2d ball = getRobotPose() * result;\n CIRCLE( ball.x, ball.y, 50);\n );\n\n\n \/\/ STEP 2: calculate the goal line\n GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());\n Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip \/ oppGoalModel.leftPost;\n Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip \/ oppGoalModel.rightPost;\n\n \/\/the endpoints of our line are a shortened version of the goal line\n Vector2d goalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize();\n Vector2d leftEndpoint = oppGoalPostLeftPreview + goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);\n Vector2d rightEndpoint = oppGoalPostRightPreview - goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);\n\n \/\/ this is the goalline we are shooting for\n Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);\n \n \/\/ note: the drawing is global\n DEBUG_REQUEST(\"Simulation:GoalLinePreview\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 1);\n Vector2d globalLeft = getRobotPose() * leftEndpoint;\n Vector2d globalRight = getRobotPose() * rightEndpoint;\n LINE(globalLeft.x,globalLeft.y,globalRight.x,globalRight.y);\n );\n\n \/\/ STEP 3: estimate external factors (shooting a goal, ball moved by referee)\n \/\/Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));\/\/hmm\n Math::LineSegment shootLine(ballRelativePreview, result);\n\n Vector2d resultingBallPosition;\n\n if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) {\n resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);\n } else {\n resultingBallPosition = outsideField(getRobotPose() * result);\n }\n\n return resultingBallPosition;\n}\n \n \/\/correction of distance in percentage, angle in degrees\n Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const\n {\n double random_length = 2.0*Math::random()-1.0;\n double random_angle = 2.0*Math::random()-1.0;\n\n Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);\n noisyAction.rotate(angle_variance*random_angle);\n\n return ball + noisyAction;\n }\n\n\/\/calcualte according to the rules, without the roboter position, the ball position\n\/\/if it goes outside the field\nVector2d Simulation::outsideField(const Vector2d& globalPoint) const\n{ \n Vector2d point = globalPoint;\n\n \/\/Schusslinie\n Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint);\n\n if(getFieldInfo().fieldRect.inside(point)){\n return point;\n }\n else\n \/\/Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat\n { \/\/Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht\n if(point.x > getFieldInfo().xPosOpponentGroundline)\n { \n Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine));\n if(OppOutPoint.y < 0)\n {\n return Vector2d(0, getFieldInfo().yThrowInLineRight);\/\/range check\n } else\n {\n return Vector2d(0, getFieldInfo().yThrowInLineLeft); \n }\n }\n \/\/Own Groundline out - an der seite wo raus geht\n else if(point.x < getFieldInfo().xPosOwnGroundline)\n {\n Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine));\n if(OwnOutPoint.y < 0)\n {\n return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);\/\/range check\n } else\n { \n return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); \n }\n }\n \/\/an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter\n else if(point.y > getFieldInfo().yPosLeftSideline )\n { \n Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine));\n point.x = min(leftOutPoint.x,getRobotPose().translation.x);\n\n if(point.x-1000 < getFieldInfo().xThrowInLineOwn)\n { \n point.x = getFieldInfo().xThrowInLineOwn;\n } else\n { \n point.x -= 1000;\n }\n return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); \/\/range check\n }\n \/\/an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter\n else \/\/(point.y < getFieldInfo().yPosRightSideline)\n { \n Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine));\n point.x = min(rightOutPoint.x,getRobotPose().translation.x);\n\n if(point.x-1000 < getFieldInfo().xThrowInLineOwn)\n {\n point.x = getFieldInfo().xThrowInLineOwn;\n } else\n { \n point.x -= 1000;\n }\n return Vector2d(point.x, getFieldInfo().yThrowInLineRight);\/\/range check\n }\n }\n}\n\ndouble Simulation::evaluateAction(const Vector2d& a) const{\n Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0);\n Vector2d oppDiff = oppGoal - a;\n\n double oppValueX = 0.1;\n double oppValueY = 1;\n MODIFY(\"Simulation:oppValueX\", oppValueX);\n MODIFY(\"Simulation:oppValueY\", oppValueY);\n double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y;\n \n \/\/Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0);\n \/\/Vector2d ownDiff = ownGoal - a;\n \n \/\/double ownValueX = 0.01;\n \/\/double ownValueY = 0.1;\n \/\/MODIFY(\"Simulation:ownValueX\", ownValueX);\n \/\/MODIFY(\"Simulation:ownValueY\", ownValueY);\n \/\/double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y;\n\n \/\/return value_opp - value_own;\n return value_opp;\n}\n\nvoid Simulation::draw_potential_field() const\n{\n static const int ySize = 20;\n static const int xSize = 30;\n double yWidth = 0.5*getFieldInfo().yFieldLength\/(double)ySize;\n double xWidth = 0.5*getFieldInfo().xFieldLength\/(double)xSize;\n\n FIELD_DRAWING_CONTEXT;\n Color white(0.0,0.0,1.0,0.5); \/\/ transparent\n Color black(1.0,0.0,0.0,0.5);\n\n \/\/ create new sample set\n std::vector<double> potential(xSize*ySize);\n int idx = 0;\n\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));\n potential[idx] = evaluateAction(point);\n idx++;\n }\n }\n \n double maxValue = 0;\n idx = 0;\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n maxValue = max(maxValue, potential[idx++]);\n }\n }\n\n if(maxValue == 0) return;\n\n idx = 0;\n for (int x = 0; x < xSize; x++) {\n for (int y = 0; y < ySize; y++)\n {\n Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));\n \n double t = potential[idx++] \/ maxValue;\n Color color = black*t + white*(1-t);\n PEN(color, 20);\n FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth);\n }\n }\n}\/\/end draw_closest_points<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\/* @file\n * Device model for Intel's 8254x line of gigabit ethernet controllers.\n * In particular an 82547 revision 2 (82547GI) MAC because it seems to have the\n * fewest workarounds in the driver. It will probably work with most of the\n * other MACs with slight modifications.\n *\/\n\n#include \"base\/inet.hh\"\n#include \"dev\/i8254xGBe.hh\"\n#include \"mem\/packet.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace iGbReg;\n\nIGbE::IGbE(Params *p)\n : PciDev(p), etherInt(NULL)\n{\n \/\/ Initialized internal registers per Intel documentation\n regs.tctl.reg = 0;\n regs.rctl.reg = 0;\n regs.ctrl.reg = 0;\n regs.ctrl.fd = 1;\n regs.ctrl.lrst = 1;\n regs.ctrl.speed = 2;\n regs.ctrl.frcspd = 1;\n regs.sts.reg = 0;\n regs.eecd.reg = 0;\n regs.eecd.fwe = 1;\n regs.eecd.ee_type = 1;\n regs.eerd.reg = 0;\n regs.icd.reg = 0;\n regs.imc.reg = 0;\n regs.rctl.reg = 0;\n regs.tctl.reg = 0;\n regs.manc.reg = 0;\n\n eeOpBits = 0;\n eeAddrBits = 0;\n eeDataBits = 0;\n eeOpcode = 0;\n\n memset(&flash, 0, EEPROM_SIZE);\n \/\/ Magic happy checksum value\n flash[0] = 0xBABA;\n}\n\n\nTick\nIGbE::writeConfig(PacketPtr pkt)\n{\n int offset = pkt->getAddr() & PCI_CONFIG_SIZE;\n if (offset < PCI_DEVICE_SPECIFIC)\n PciDev::writeConfig(pkt);\n else\n panic(\"Device specific PCI config space not implemented.\\n\");\n\n \/\/\/\n \/\/\/ Some work may need to be done here based for the pci COMMAND bits.\n \/\/\/\n\n return pioDelay;\n}\n\nTick\nIGbE::read(PacketPtr pkt)\n{\n int bar;\n Addr daddr;\n\n if (!getBAR(pkt->getAddr(), bar, daddr))\n panic(\"Invalid PCI memory access to unmapped memory.\\n\");\n\n \/\/ Only Memory register BAR is allowed\n assert(bar == 0);\n\n \/\/ Only 32bit accesses allowed\n assert(pkt->getSize() == 4);\n\n DPRINTF(Ethernet, \"Read device register %#X\\n\", daddr);\n\n pkt->allocate();\n\n \/\/\/\n \/\/\/ Handle read of register here\n \/\/\/\n\n switch (daddr) {\n case CTRL:\n pkt->set<uint32_t>(regs.ctrl.reg);\n break;\n case STATUS:\n pkt->set<uint32_t>(regs.sts.reg);\n break;\n case EECD:\n pkt->set<uint32_t>(regs.eecd.reg);\n break;\n case EERD:\n pkt->set<uint32_t>(regs.eerd.reg);\n break;\n case ICR:\n pkt->set<uint32_t>(regs.icd.reg);\n break;\n case IMC:\n pkt->set<uint32_t>(regs.imc.reg);\n break;\n case RCTL:\n pkt->set<uint32_t>(regs.rctl.reg);\n break;\n case TCTL:\n pkt->set<uint32_t>(regs.tctl.reg);\n break;\n case MANC:\n pkt->set<uint32_t>(regs.manc.reg);\n break;\n default:\n panic(\"Read request to unknown register number: %#x\\n\", daddr);\n };\n\n pkt->result = Packet::Success;\n return pioDelay;\n}\n\nTick\nIGbE::write(PacketPtr pkt)\n{\n int bar;\n Addr daddr;\n\n\n if (!getBAR(pkt->getAddr(), bar, daddr))\n panic(\"Invalid PCI memory access to unmapped memory.\\n\");\n\n \/\/ Only Memory register BAR is allowed\n assert(bar == 0);\n\n \/\/ Only 32bit accesses allowed\n assert(pkt->getSize() == sizeof(uint32_t));\n\n DPRINTF(Ethernet, \"Wrote device register %#X value %#X\\n\", daddr, pkt->get<uint32_t>());\n\n \/\/\/\n \/\/\/ Handle write of register here\n \/\/\/\n uint32_t val = pkt->get<uint32_t>();\n\n switch (daddr) {\n case CTRL:\n regs.ctrl.reg = val;\n break;\n case STATUS:\n regs.sts.reg = val;\n break;\n case EECD:\n int oldClk;\n oldClk = regs.eecd.sk;\n regs.eecd.reg = val;\n \/\/ See if this is a eeprom access and emulate accordingly\n if (!oldClk && regs.eecd.sk) {\n if (eeOpBits < 8) {\n eeOpcode = eeOpcode << 1 | regs.eecd.din;\n eeOpBits++;\n } else if (eeAddrBits < 8 && eeOpcode == EEPROM_READ_OPCODE_SPI) {\n eeAddr = eeAddr << 1 | regs.eecd.din;\n eeAddrBits++;\n } else if (eeDataBits < 16 && eeOpcode == EEPROM_READ_OPCODE_SPI) {\n assert(eeAddr < EEPROM_SIZE);\n DPRINTF(Ethernet, \"EEPROM bit read: %d word: %#X\\n\",\n flash[eeAddr] >> eeDataBits & 0x1, flash[eeAddr]);\n regs.eecd.dout = (flash[eeAddr] >> eeDataBits) & 0x1;\n eeDataBits++;\n } else if (eeDataBits < 8 && eeOpcode == EEPROM_RDSR_OPCODE_SPI) {\n regs.eecd.dout = 0;\n eeDataBits++;\n } else\n panic(\"What's going on with eeprom interface? opcode:\"\n \" %#x:%d addr: %#x:%d, data: %d\\n\", (uint32_t)eeOpcode,\n (uint32_t)eeOpBits, (uint32_t)eeAddr,\n (uint32_t)eeAddrBits, (uint32_t)eeDataBits);\n\n \/\/ Reset everything for the next command\n if ((eeDataBits == 16 && eeOpcode == EEPROM_READ_OPCODE_SPI) ||\n (eeDataBits == 8 && eeOpcode == EEPROM_RDSR_OPCODE_SPI)) {\n eeOpBits = 0;\n eeAddrBits = 0;\n eeDataBits = 0;\n eeOpcode = 0;\n eeAddr = 0;\n }\n\n DPRINTF(Ethernet, \"EEPROM: opcode: %#X:%d\\n\",\n (uint32_t)eeOpcode, (uint32_t) eeOpBits);\n if (eeOpBits == 8 && !(eeOpcode == EEPROM_READ_OPCODE_SPI ||\n eeOpcode == EEPROM_RDSR_OPCODE_SPI ))\n panic(\"Unknown eeprom opcode: %#X:%d\\n\", (uint32_t)eeOpcode,\n (uint32_t)eeOpBits);\n\n\n }\n \/\/ If driver requests eeprom access, immediately give it to it\n regs.eecd.ee_gnt = regs.eecd.ee_req;\n break;\n case EERD:\n regs.eerd.reg = val;\n break;\n case ICR:\n regs.icd.reg = val;\n break;\n case IMC:\n regs.imc.reg = val;\n break;\n case RCTL:\n regs.rctl.reg = val;\n break;\n case TCTL:\n regs.tctl.reg = val;\n break;\n case MANC:\n regs.manc.reg = val;\n break;\n default:\n panic(\"Write request to unknown register number: %#x\\n\", daddr);\n };\n\n pkt->result = Packet::Success;\n return pioDelay;\n}\n\n\nbool\nIGbE::ethRxPkt(EthPacketPtr packet)\n{\n panic(\"Need to implemenet\\n\");\n}\n\n\nvoid\nIGbE::ethTxDone()\n{\n panic(\"Need to implemenet\\n\");\n}\n\nvoid\nIGbE::serialize(std::ostream &os)\n{\n panic(\"Need to implemenet\\n\");\n}\n\nvoid\nIGbE::unserialize(Checkpoint *cp, const std::string §ion)\n{\n panic(\"Need to implemenet\\n\");\n}\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(IGbEInt)\n\n SimObjectParam<EtherInt *> peer;\n SimObjectParam<IGbE *> device;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(IGbEInt)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(IGbEInt)\n\n INIT_PARAM_DFLT(peer, \"peer interface\", NULL),\n INIT_PARAM(device, \"Ethernet device of this interface\")\n\nEND_INIT_SIM_OBJECT_PARAMS(IGbEInt)\n\nCREATE_SIM_OBJECT(IGbEInt)\n{\n IGbEInt *dev_int = new IGbEInt(getInstanceName(), device);\n\n EtherInt *p = (EtherInt *)peer;\n if (p) {\n dev_int->setPeer(p);\n p->setPeer(dev_int);\n }\n\n return dev_int;\n}\n\nREGISTER_SIM_OBJECT(\"IGbEInt\", IGbEInt)\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(IGbE)\n\n SimObjectParam<System *> system;\n SimObjectParam<Platform *> platform;\n SimObjectParam<PciConfigData *> configdata;\n Param<uint32_t> pci_bus;\n Param<uint32_t> pci_dev;\n Param<uint32_t> pci_func;\n Param<Tick> pio_latency;\n Param<Tick> config_latency;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(IGbE)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(IGbE)\n\n INIT_PARAM(system, \"System pointer\"),\n INIT_PARAM(platform, \"Platform pointer\"),\n INIT_PARAM(configdata, \"PCI Config data\"),\n INIT_PARAM(pci_bus, \"PCI bus ID\"),\n INIT_PARAM(pci_dev, \"PCI device number\"),\n INIT_PARAM(pci_func, \"PCI function code\"),\n INIT_PARAM_DFLT(pio_latency, \"Programmed IO latency in bus cycles\", 1),\n INIT_PARAM(config_latency, \"Number of cycles for a config read or write\")\n\nEND_INIT_SIM_OBJECT_PARAMS(IGbE)\n\n\nCREATE_SIM_OBJECT(IGbE)\n{\n IGbE::Params *params = new IGbE::Params;\n\n params->name = getInstanceName();\n params->platform = platform;\n params->system = system;\n params->configData = configdata;\n params->busNum = pci_bus;\n params->deviceNum = pci_dev;\n params->functionNum = pci_func;\n params->pio_delay = pio_latency;\n params->config_delay = config_latency;\n\n return new IGbE(params);\n}\n\nREGISTER_SIM_OBJECT(\"IGbE\", IGbE)\n<commit_msg>add packet_access.hh<commit_after>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\/* @file\n * Device model for Intel's 8254x line of gigabit ethernet controllers.\n * In particular an 82547 revision 2 (82547GI) MAC because it seems to have the\n * fewest workarounds in the driver. It will probably work with most of the\n * other MACs with slight modifications.\n *\/\n\n#include \"base\/inet.hh\"\n#include \"dev\/i8254xGBe.hh\"\n#include \"mem\/packet.hh\"\n#include \"mem\/packet_access.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace iGbReg;\n\nIGbE::IGbE(Params *p)\n : PciDev(p), etherInt(NULL)\n{\n \/\/ Initialized internal registers per Intel documentation\n regs.tctl.reg = 0;\n regs.rctl.reg = 0;\n regs.ctrl.reg = 0;\n regs.ctrl.fd = 1;\n regs.ctrl.lrst = 1;\n regs.ctrl.speed = 2;\n regs.ctrl.frcspd = 1;\n regs.sts.reg = 0;\n regs.eecd.reg = 0;\n regs.eecd.fwe = 1;\n regs.eecd.ee_type = 1;\n regs.eerd.reg = 0;\n regs.icd.reg = 0;\n regs.imc.reg = 0;\n regs.rctl.reg = 0;\n regs.tctl.reg = 0;\n regs.manc.reg = 0;\n\n regs.pba.rxa = 0x30;\n regs.pba.txa = 0x10;\n\n eeOpBits = 0;\n eeAddrBits = 0;\n eeDataBits = 0;\n eeOpcode = 0;\n\n \/\/ clear all 64 16 bit words of the eeprom\n memset(&flash, 0, EEPROM_SIZE*2);\n\n \/\/ Magic happy checksum value\n flash[0] = 0xBABA;\n}\n\n\nTick\nIGbE::writeConfig(PacketPtr pkt)\n{\n int offset = pkt->getAddr() & PCI_CONFIG_SIZE;\n if (offset < PCI_DEVICE_SPECIFIC)\n PciDev::writeConfig(pkt);\n else\n panic(\"Device specific PCI config space not implemented.\\n\");\n\n \/\/\/\n \/\/\/ Some work may need to be done here based for the pci COMMAND bits.\n \/\/\/\n\n return pioDelay;\n}\n\nTick\nIGbE::read(PacketPtr pkt)\n{\n int bar;\n Addr daddr;\n\n if (!getBAR(pkt->getAddr(), bar, daddr))\n panic(\"Invalid PCI memory access to unmapped memory.\\n\");\n\n \/\/ Only Memory register BAR is allowed\n assert(bar == 0);\n\n \/\/ Only 32bit accesses allowed\n assert(pkt->getSize() == 4);\n\n \/\/DPRINTF(Ethernet, \"Read device register %#X\\n\", daddr);\n\n pkt->allocate();\n\n \/\/\/\n \/\/\/ Handle read of register here\n \/\/\/\n\n\n switch (daddr) {\n case CTRL:\n pkt->set<uint32_t>(regs.ctrl.reg);\n break;\n case STATUS:\n pkt->set<uint32_t>(regs.sts.reg);\n break;\n case EECD:\n pkt->set<uint32_t>(regs.eecd.reg);\n break;\n case EERD:\n pkt->set<uint32_t>(regs.eerd.reg);\n break;\n case ICR:\n pkt->set<uint32_t>(regs.icd.reg);\n break;\n case IMC:\n pkt->set<uint32_t>(regs.imc.reg);\n break;\n case RCTL:\n pkt->set<uint32_t>(regs.rctl.reg);\n break;\n case TCTL:\n pkt->set<uint32_t>(regs.tctl.reg);\n break;\n case PBA:\n pkt->set<uint32_t>(regs.pba.reg);\n break;\n case WUC:\n case LEDCTL:\n pkt->set<uint32_t>(0); \/\/ We don't care, so just return 0\n break;\n case MANC:\n pkt->set<uint32_t>(regs.manc.reg);\n break;\n default:\n if (!(daddr >= VFTA && daddr < (VFTA + VLAN_FILTER_TABLE_SIZE)*4) &&\n !(daddr >= RAL && daddr < (RAL + RCV_ADDRESS_TABLE_SIZE)*4) &&\n !(daddr >= MTA && daddr < (MTA + MULTICAST_TABLE_SIZE)*4))\n pkt->set<uint32_t>(0);\n else\n panic(\"Read request to unknown register number: %#x\\n\", daddr);\n };\n\n pkt->result = Packet::Success;\n return pioDelay;\n}\n\nTick\nIGbE::write(PacketPtr pkt)\n{\n int bar;\n Addr daddr;\n\n\n if (!getBAR(pkt->getAddr(), bar, daddr))\n panic(\"Invalid PCI memory access to unmapped memory.\\n\");\n\n \/\/ Only Memory register BAR is allowed\n assert(bar == 0);\n\n \/\/ Only 32bit accesses allowed\n assert(pkt->getSize() == sizeof(uint32_t));\n\n \/\/DPRINTF(Ethernet, \"Wrote device register %#X value %#X\\n\", daddr, pkt->get<uint32_t>());\n\n \/\/\/\n \/\/\/ Handle write of register here\n \/\/\/\n uint32_t val = pkt->get<uint32_t>();\n\n switch (daddr) {\n case CTRL:\n regs.ctrl.reg = val;\n break;\n case STATUS:\n regs.sts.reg = val;\n break;\n case EECD:\n int oldClk;\n oldClk = regs.eecd.sk;\n regs.eecd.reg = val;\n \/\/ See if this is a eeprom access and emulate accordingly\n if (!oldClk && regs.eecd.sk) {\n if (eeOpBits < 8) {\n eeOpcode = eeOpcode << 1 | regs.eecd.din;\n eeOpBits++;\n } else if (eeAddrBits < 8 && eeOpcode == EEPROM_READ_OPCODE_SPI) {\n eeAddr = eeAddr << 1 | regs.eecd.din;\n eeAddrBits++;\n } else if (eeDataBits < 16 && eeOpcode == EEPROM_READ_OPCODE_SPI) {\n assert(eeAddr>>1 < EEPROM_SIZE);\n DPRINTF(EthernetEEPROM, \"EEPROM bit read: %d word: %#X\\n\",\n flash[eeAddr>>1] >> eeDataBits & 0x1, flash[eeAddr>>1]);\n regs.eecd.dout = (flash[eeAddr>>1] >> (15-eeDataBits)) & 0x1;\n eeDataBits++;\n } else if (eeDataBits < 8 && eeOpcode == EEPROM_RDSR_OPCODE_SPI) {\n regs.eecd.dout = 0;\n eeDataBits++;\n } else\n panic(\"What's going on with eeprom interface? opcode:\"\n \" %#x:%d addr: %#x:%d, data: %d\\n\", (uint32_t)eeOpcode,\n (uint32_t)eeOpBits, (uint32_t)eeAddr,\n (uint32_t)eeAddrBits, (uint32_t)eeDataBits);\n\n \/\/ Reset everything for the next command\n if ((eeDataBits == 16 && eeOpcode == EEPROM_READ_OPCODE_SPI) ||\n (eeDataBits == 8 && eeOpcode == EEPROM_RDSR_OPCODE_SPI)) {\n eeOpBits = 0;\n eeAddrBits = 0;\n eeDataBits = 0;\n eeOpcode = 0;\n eeAddr = 0;\n }\n\n DPRINTF(EthernetEEPROM, \"EEPROM: opcode: %#X:%d addr: %#X:%d\\n\",\n (uint32_t)eeOpcode, (uint32_t) eeOpBits,\n (uint32_t)eeAddr>>1, (uint32_t)eeAddrBits);\n if (eeOpBits == 8 && !(eeOpcode == EEPROM_READ_OPCODE_SPI ||\n eeOpcode == EEPROM_RDSR_OPCODE_SPI ))\n panic(\"Unknown eeprom opcode: %#X:%d\\n\", (uint32_t)eeOpcode,\n (uint32_t)eeOpBits);\n\n\n }\n \/\/ If driver requests eeprom access, immediately give it to it\n regs.eecd.ee_gnt = regs.eecd.ee_req;\n break;\n case EERD:\n regs.eerd.reg = val;\n break;\n case ICR:\n regs.icd.reg = val;\n break;\n case IMC:\n regs.imc.reg = val;\n break;\n case RCTL:\n regs.rctl.reg = val;\n break;\n case TCTL:\n regs.tctl.reg = val;\n break;\n case PBA:\n regs.pba.rxa = val;\n regs.pba.txa = 64 - regs.pba.rxa;\n break;\n case WUC:\n case LEDCTL:\n ; \/\/ We don't care, so don't store anything\n break;\n case MANC:\n regs.manc.reg = val;\n break;\n default:\n if (!(daddr >= VFTA && daddr < (VFTA + VLAN_FILTER_TABLE_SIZE)*4) &&\n !(daddr >= RAL && daddr < (RAL + RCV_ADDRESS_TABLE_SIZE)*4) &&\n !(daddr >= MTA && daddr < (MTA + MULTICAST_TABLE_SIZE)*4))\n panic(\"Write request to unknown register number: %#x\\n\", daddr);\n };\n\n pkt->result = Packet::Success;\n return pioDelay;\n}\n\n\nbool\nIGbE::ethRxPkt(EthPacketPtr packet)\n{\n panic(\"Need to implemenet\\n\");\n}\n\n\nvoid\nIGbE::ethTxDone()\n{\n panic(\"Need to implemenet\\n\");\n}\n\nvoid\nIGbE::serialize(std::ostream &os)\n{\n panic(\"Need to implemenet\\n\");\n}\n\nvoid\nIGbE::unserialize(Checkpoint *cp, const std::string §ion)\n{\n panic(\"Need to implemenet\\n\");\n}\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(IGbEInt)\n\n SimObjectParam<EtherInt *> peer;\n SimObjectParam<IGbE *> device;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(IGbEInt)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(IGbEInt)\n\n INIT_PARAM_DFLT(peer, \"peer interface\", NULL),\n INIT_PARAM(device, \"Ethernet device of this interface\")\n\nEND_INIT_SIM_OBJECT_PARAMS(IGbEInt)\n\nCREATE_SIM_OBJECT(IGbEInt)\n{\n IGbEInt *dev_int = new IGbEInt(getInstanceName(), device);\n\n EtherInt *p = (EtherInt *)peer;\n if (p) {\n dev_int->setPeer(p);\n p->setPeer(dev_int);\n }\n\n return dev_int;\n}\n\nREGISTER_SIM_OBJECT(\"IGbEInt\", IGbEInt)\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(IGbE)\n\n SimObjectParam<System *> system;\n SimObjectParam<Platform *> platform;\n SimObjectParam<PciConfigData *> configdata;\n Param<uint32_t> pci_bus;\n Param<uint32_t> pci_dev;\n Param<uint32_t> pci_func;\n Param<Tick> pio_latency;\n Param<Tick> config_latency;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(IGbE)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(IGbE)\n\n INIT_PARAM(system, \"System pointer\"),\n INIT_PARAM(platform, \"Platform pointer\"),\n INIT_PARAM(configdata, \"PCI Config data\"),\n INIT_PARAM(pci_bus, \"PCI bus ID\"),\n INIT_PARAM(pci_dev, \"PCI device number\"),\n INIT_PARAM(pci_func, \"PCI function code\"),\n INIT_PARAM_DFLT(pio_latency, \"Programmed IO latency in bus cycles\", 1),\n INIT_PARAM(config_latency, \"Number of cycles for a config read or write\")\n\nEND_INIT_SIM_OBJECT_PARAMS(IGbE)\n\n\nCREATE_SIM_OBJECT(IGbE)\n{\n IGbE::Params *params = new IGbE::Params;\n\n params->name = getInstanceName();\n params->platform = platform;\n params->system = system;\n params->configData = configdata;\n params->busNum = pci_bus;\n params->deviceNum = pci_dev;\n params->functionNum = pci_func;\n params->pio_delay = pio_latency;\n params->config_delay = config_latency;\n\n return new IGbE(params);\n}\n\nREGISTER_SIM_OBJECT(\"IGbE\", IGbE)\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Instruction.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 15\/01\/21.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_M50740_Instruction_h\n#define InstructionSets_M50740_Instruction_h\n\n#include <cstdint>\n#include \"..\/AccessType.hpp\"\n\nnamespace InstructionSet {\nnamespace M50740 {\n\nenum class AddressingMode {\n\tImplied,\t\t\t\tAccumulator,\t\t\tImmediate,\n\tAbsolute,\t\t\t\tAbsoluteX,\t\t\t\tAbsoluteY,\n\tZeroPage,\t\t\t\tZeroPageX,\t\t\t\tZeroPageY,\n\tXIndirect,\t\t\t\tIndirectY,\n\tRelative,\n\tAbsoluteIndirect,\t\tZeroPageIndirect,\n\tSpecialPage,\n\tImmediateZeroPage,\n\tAccumulatorRelative,\tZeroPageRelative\n};\n\nstatic constexpr auto MaxAddressingMode = int(AddressingMode::ZeroPageRelative);\nstatic constexpr auto MinAddressingMode = int(AddressingMode::Implied);\n\nconstexpr int size(AddressingMode mode) {\n\t\/\/ This is coupled to the AddressingMode list above; be careful!\n\tconstexpr int sizes[] = {\n\t\t0, 0, 1,\n\t\t2, 2, 2,\n\t\t1, 1, 1,\n\t\t1, 1,\n\t\t1,\n\t\t2, 1,\n\t\t1,\n\t\t2,\n\t\t1,\t2\n\t};\n\tstatic_assert(sizeof(sizes)\/sizeof(*sizes) == int(MaxAddressingMode) + 1);\n\treturn sizes[int(mode)];\n}\n\nenum class Operation: uint8_t {\n\tInvalid,\n\n\t\/\/ Operations that don't access memory.\n\tBBC0,\tBBS0,\tBBC1,\tBBS1,\tBBC2,\tBBS2,\tBBC3,\tBBS3,\n\tBBC4,\tBBS4,\tBBC5,\tBBS5,\tBBC6,\tBBS6,\tBBC7,\tBBS7,\n\tBCC,\tBCS,\n\tBEQ,\tBMI,\tBNE,\tBPL,\n\tBVC,\tBVS,\tBRA,\tBRK,\n\tJMP,\tJSR,\n\tRTI,\tRTS,\n\tCLC,\tCLD,\tCLI,\tCLT,\tCLV,\n\tSEC,\tSED,\tSEI,\tSET,\n\tINX,\tINY,\tDEX,\tDEY,\n\tFST,\tSLW,\n\tNOP,\n\tPHA, \tPHP, \tPLA,\tPLP,\n\tSTP,\n\tTAX,\tTAY,\tTSX,\tTXA,\n\tTXS,\tTYA,\n\n\t\/\/ Read operations.\n\tADC,\tSBC,\n\tAND,\tORA,\tEOR,\tBIT,\n\tCMP,\tCPX,\tCPY,\n\tLDA,\tLDX,\tLDY,\n\tTST,\n\n\t\/\/ Read-modify-write operations.\n\tASL,\tLSR,\n\tCLB0,\tSEB0,\tCLB1,\tSEB1,\tCLB2,\tSEB2,\tCLB3,\tSEB3,\n\tCLB4,\tSEB4,\tCLB5,\tSEB5,\tCLB6,\tSEB6,\tCLB7,\tSEB7,\n\tCOM,\n\tDEC,\tINC,\n\tROL,\tROR,\tRRF,\n\n\t\/\/ Write operations.\n\tLDM,\n\tSTA,\tSTX,\tSTY,\n};\n\nstatic constexpr auto MaxOperation = int(Operation::STY);\nstatic constexpr auto MinOperation = int(Operation::BBC0);\n\nconstexpr AccessType access_type(Operation operation) {\n\tif(operation < Operation::ADC)\treturn AccessType::None;\n\tif(operation < Operation::ASL)\treturn AccessType::Read;\n\tif(operation < Operation::LDM)\treturn AccessType::Write;\n\treturn AccessType::ReadModifyWrite;\n}\n\nconstexpr bool uses_index_mode(Operation operation) {\n\treturn\n\t\toperation == Operation::ADC || operation == Operation::AND ||\n\t\toperation == Operation::CMP || operation == Operation::EOR ||\n\t\toperation == Operation::LDA || operation == Operation::ORA ||\n\t\toperation == Operation::SBC;\n}\n\nstruct Instruction {\n\tOperation operation = Operation::Invalid;\n\tAddressingMode addressing_mode = AddressingMode::Implied;\n\tuint8_t opcode = 0;\n\n\tInstruction(Operation operation, AddressingMode addressing_mode, uint8_t opcode) : operation(operation), addressing_mode(addressing_mode), opcode(opcode) {}\n\tInstruction(uint8_t opcode) : opcode(opcode) {}\n\tInstruction() {}\n};\n\n}\n}\n\n\n#endif \/* InstructionSets_M50740_Instruction_h *\/\n<commit_msg>Corrects bit-selection shifts.<commit_after>\/\/\n\/\/ Instruction.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 15\/01\/21.\n\/\/ Copyright © 2021 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_M50740_Instruction_h\n#define InstructionSets_M50740_Instruction_h\n\n#include <cstdint>\n#include \"..\/AccessType.hpp\"\n\nnamespace InstructionSet {\nnamespace M50740 {\n\nenum class AddressingMode {\n\tImplied,\t\t\t\tAccumulator,\t\t\tImmediate,\n\tAbsolute,\t\t\t\tAbsoluteX,\t\t\t\tAbsoluteY,\n\tZeroPage,\t\t\t\tZeroPageX,\t\t\t\tZeroPageY,\n\tXIndirect,\t\t\t\tIndirectY,\n\tRelative,\n\tAbsoluteIndirect,\t\tZeroPageIndirect,\n\tSpecialPage,\n\tImmediateZeroPage,\n\tAccumulatorRelative,\tZeroPageRelative\n};\n\nstatic constexpr auto MaxAddressingMode = int(AddressingMode::ZeroPageRelative);\nstatic constexpr auto MinAddressingMode = int(AddressingMode::Implied);\n\nconstexpr int size(AddressingMode mode) {\n\t\/\/ This is coupled to the AddressingMode list above; be careful!\n\tconstexpr int sizes[] = {\n\t\t0, 0, 1,\n\t\t2, 2, 2,\n\t\t1, 1, 1,\n\t\t1, 1,\n\t\t1,\n\t\t2, 1,\n\t\t1,\n\t\t2,\n\t\t1,\t2\n\t};\n\tstatic_assert(sizeof(sizes)\/sizeof(*sizes) == int(MaxAddressingMode) + 1);\n\treturn sizes[int(mode)];\n}\n\nenum class Operation: uint8_t {\n\tInvalid,\n\n\t\/\/ Operations that don't access memory.\n\tBBC0,\tBBC1,\tBBC2,\tBBC3,\tBBC4,\tBBC5,\tBBC6,\tBBC7,\n\tBBS0,\tBBS1,\tBBS2,\tBBS3,\tBBS4,\tBBS5,\tBBS6,\tBBS7,\n\tBCC,\tBCS,\n\tBEQ,\tBMI,\tBNE,\tBPL,\n\tBVC,\tBVS,\tBRA,\tBRK,\n\tJMP,\tJSR,\n\tRTI,\tRTS,\n\tCLC,\tCLD,\tCLI,\tCLT,\tCLV,\n\tSEC,\tSED,\tSEI,\tSET,\n\tINX,\tINY,\tDEX,\tDEY,\n\tFST,\tSLW,\n\tNOP,\n\tPHA, \tPHP, \tPLA,\tPLP,\n\tSTP,\n\tTAX,\tTAY,\tTSX,\tTXA,\n\tTXS,\tTYA,\n\n\t\/\/ Read operations.\n\tADC,\tSBC,\n\tAND,\tORA,\tEOR,\tBIT,\n\tCMP,\tCPX,\tCPY,\n\tLDA,\tLDX,\tLDY,\n\tTST,\n\n\t\/\/ Read-modify-write operations.\n\tASL,\tLSR,\n\tCLB0,\tCLB1,\tCLB2,\tCLB3,\tCLB4,\tCLB5,\tCLB6,\tCLB7,\n\tSEB0,\tSEB1,\tSEB2,\tSEB3,\tSEB4,\tSEB5,\tSEB6,\tSEB7,\n\tCOM,\n\tDEC,\tINC,\n\tROL,\tROR,\tRRF,\n\n\t\/\/ Write operations.\n\tLDM,\n\tSTA,\tSTX,\tSTY,\n};\n\nstatic constexpr auto MaxOperation = int(Operation::STY);\nstatic constexpr auto MinOperation = int(Operation::BBC0);\n\nconstexpr AccessType access_type(Operation operation) {\n\tif(operation < Operation::ADC)\treturn AccessType::None;\n\tif(operation < Operation::ASL)\treturn AccessType::Read;\n\tif(operation < Operation::LDM)\treturn AccessType::Write;\n\treturn AccessType::ReadModifyWrite;\n}\n\nconstexpr bool uses_index_mode(Operation operation) {\n\treturn\n\t\toperation == Operation::ADC || operation == Operation::AND ||\n\t\toperation == Operation::CMP || operation == Operation::EOR ||\n\t\toperation == Operation::LDA || operation == Operation::ORA ||\n\t\toperation == Operation::SBC;\n}\n\nstruct Instruction {\n\tOperation operation = Operation::Invalid;\n\tAddressingMode addressing_mode = AddressingMode::Implied;\n\tuint8_t opcode = 0;\n\n\tInstruction(Operation operation, AddressingMode addressing_mode, uint8_t opcode) : operation(operation), addressing_mode(addressing_mode), opcode(opcode) {}\n\tInstruction(uint8_t opcode) : opcode(opcode) {}\n\tInstruction() {}\n};\n\n}\n}\n\n\n#endif \/* InstructionSets_M50740_Instruction_h *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013-2018 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"response_p.h\"\n\n#include \"context_p.h\"\n#include \"engine.h\"\n#include \"enginerequest.h\"\n#include \"common.h\"\n\n#include <QtCore\/QJsonDocument>\n\n#include <QCryptographicHash>\n#include <QEventLoop>\n\nusing namespace Cutelyst;\n\nResponse::Response(const Headers &defaultHeaders, EngineRequest *engineRequest)\n : d_ptr(new ResponsePrivate(defaultHeaders, engineRequest))\n{\n open(QIODevice::WriteOnly);\n}\n\nqint64 Response::readData(char *data, qint64 maxlen)\n{\n Q_UNUSED(data)\n Q_UNUSED(maxlen)\n return -1;\n}\n\nqint64 Response::writeData(const char *data, qint64 len)\n{\n Q_D(Response);\n\n if (len <= 0) {\n return len;\n }\n\n \/\/ Finalize headers if someone manually writes output\n if (!(d->engineRequest->status & EngineRequest::FinalizedHeaders)) {\n if (d->headers.header(QStringLiteral(\"TRANSFER_ENCODING\")) == QLatin1String(\"chunked\")) {\n d->engineRequest->status |= EngineRequest::IOWrite | EngineRequest::Chunked;\n } else {\n \/\/ When chunked encoding is not set the client can only know\n \/\/ that data is finished if we close the connection\n d->headers.setHeader(QStringLiteral(\"CONNECTION\"), QStringLiteral(\"close\"));\n d->engineRequest->status |= EngineRequest::IOWrite;\n }\n delete d->bodyIODevice;\n d->bodyIODevice = nullptr;\n d->bodyData = QByteArray();\n\n d->engineRequest->finalizeHeaders();\n }\n\n return d->engineRequest->write(data, len);\n}\n\nResponse::~Response()\n{\n delete d_ptr->bodyIODevice;\n delete d_ptr;\n}\n\nquint16 Response::status() const\n{\n Q_D(const Response);\n return d->status;\n}\n\nvoid Response::setStatus(quint16 status)\n{\n Q_D(Response);\n d->status = status;\n}\n\nbool Response::hasBody() const\n{\n Q_D(const Response);\n return !d->bodyData.isEmpty() || d->bodyIODevice || d->engineRequest->status & EngineRequest::IOWrite;\n}\n\nQByteArray &Response::body()\n{\n Q_D(Response);\n if (d->bodyIODevice) {\n delete d->bodyIODevice;\n d->bodyIODevice = nullptr;\n }\n\n return d->bodyData;\n}\n\nQIODevice *Response::bodyDevice() const\n{\n Q_D(const Response);\n return d->bodyIODevice;\n}\n\nvoid Response::setBody(QIODevice *body)\n{\n Q_D(Response);\n Q_ASSERT(body && body->isOpen() && body->isReadable());\n\n if (!(d->engineRequest->status & EngineRequest::IOWrite)) {\n d->bodyData = QByteArray();\n d->bodyIODevice = body;\n }\n}\n\nvoid Response::setBody(const QByteArray &body)\n{\n Q_D(Response);\n d->setBodyData(body);\n}\n\nvoid Response::setJsonBody(const QJsonDocument &documment)\n{\n Q_D(Response);\n const QByteArray body = documment.toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonBody(const QString &json)\n{\n Q_D(Response);\n d->setBodyData(json.toUtf8());\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonObjectBody(const QJsonObject &object)\n{\n Q_D(Response);\n const QByteArray body = QJsonDocument(object).toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonArrayBody(const QJsonArray &array)\n{\n Q_D(Response);\n const QByteArray body = QJsonDocument(array).toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nQString Response::contentEncoding() const\n{\n Q_D(const Response);\n return d->headers.contentEncoding();\n}\n\nvoid Cutelyst::Response::setContentEncoding(const QString &encoding)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setContentEncoding\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setContentEncoding(encoding);\n}\n\nqint64 Response::contentLength() const\n{\n Q_D(const Response);\n return d->headers.contentLength();\n}\n\nvoid Response::setContentLength(qint64 length)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setContentLength\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setContentLength(length);\n}\n\nQString Response::contentType() const\n{\n Q_D(const Response);\n return d->headers.contentType();\n}\n\nQString Response::contentTypeCharset() const\n{\n Q_D(const Response);\n return d->headers.contentTypeCharset();\n}\n\nQVariant Response::cookie(const QByteArray &name) const\n{\n Q_D(const Response);\n return QVariant::fromValue(d->cookies.value(name));\n}\n\nQList<QNetworkCookie> Response::cookies() const\n{\n Q_D(const Response);\n return d->cookies.values();\n}\n\nvoid Response::setCookie(const QNetworkCookie &cookie)\n{\n Q_D(Response);\n d->cookies.insert(cookie.name(), cookie);\n}\n\nvoid Response::setCookies(const QList<QNetworkCookie> &cookies)\n{\n Q_D(Response);\n for (const QNetworkCookie &cookie : cookies) {\n d->cookies.insert(cookie.name(), cookie);\n }\n}\n\nint Response::removeCookies(const QByteArray &name)\n{\n Q_D(Response);\n return d->cookies.remove(name);\n}\n\nvoid Response::redirect(const QUrl &url, quint16 status)\n{\n Q_D(Response);\n d->location = url;\n d->status = status;\n\n if (url.isValid()) {\n const QString location = QString::fromLatin1(url.toEncoded(QUrl::FullyEncoded));\n qCDebug(CUTELYST_RESPONSE) << \"Redirecting to\" << location << status;\n\n d->headers.setHeader(QStringLiteral(\"LOCATION\"), location);\n d->headers.setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n const QString buf = QStringLiteral(\n \"<!DOCTYPE html PUBLIC \\\"-\/\/W3C\/\/DTD XHTML 1.0\"\n \"Strict\/\/EN\\\" \\\"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd\\\">\\n\"\n \"<html xmlns=\\\"http:\/\/www.w3.org\/1999\/xhtml\\\">\\n\"\n \" <head>\\n\"\n \" <title>Moved<\/title>\\n\"\n \" <\/head>\\n\"\n \" <body>\\n\"\n \" <p>This item has moved <a href=\") + location +\n QStringLiteral(\">here<\/a>.<\/p>\\n\"\n \" <\/body>\\n\"\n \"<\/html>\\n\");\n setBody(buf);\n } else {\n d->headers.removeHeader(QStringLiteral(\"LOCATION\"));\n qCDebug(CUTELYST_ENGINE) << \"Invalid redirect removing header\" << url << status;\n }\n}\n\nvoid Response::redirect(const QString &url, quint16 status)\n{\n redirect(QUrl(url), status);\n}\n\nQUrl Response::location() const\n{\n Q_D(const Response);\n return d->location;\n}\n\nQString Response::header(const QString &field) const\n{\n Q_D(const Response);\n return d->headers.header(field);\n}\n\nvoid Response::setHeader(const QString &field, const QString &value)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setHeader\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setHeader(field, value);\n}\n\nHeaders &Response::headers()\n{\n Q_D(Response);\n return d->headers;\n}\n\nbool Response::isSequential() const\n{\n return true;\n}\n\nqint64 Response::size() const\n{\n Q_D(const Response);\n if (d->engineRequest->status & EngineRequest::IOWrite) {\n return -1;\n } else if (d->bodyIODevice) {\n return d->bodyIODevice->size();\n } else {\n return d->bodyData.size();\n }\n}\n\nbool Response::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)\n{\n Q_D(Response);\n return d->engineRequest->webSocketHandshake(key, origin, protocol);\n}\n\nbool Response::webSocketTextMessage(const QString &message)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendTextMessage(message);\n}\n\nbool Response::webSocketBinaryMessage(const QByteArray &message)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendBinaryMessage(message);\n}\n\nbool Response::webSocketPing(const QByteArray &payload)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendPing(payload);\n}\n\nbool Response::webSocketClose(quint16 code, const QString &reason)\n{\n Q_D(Response);\n return d->engineRequest->webSocketClose(code, reason);\n}\n\nvoid ResponsePrivate::setBodyData(const QByteArray &body)\n{\n if (!(engineRequest->status & EngineRequest::IOWrite)) {\n if (bodyIODevice) {\n delete bodyIODevice;\n bodyIODevice = nullptr;\n }\n bodyData = body;\n headers.setContentLength(body.size());\n }\n}\n\n#include \"moc_response.cpp\"\n<commit_msg>core: Fix not deleting QIODevice body when another body is set<commit_after>\/*\n * Copyright (C) 2013-2018 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"response_p.h\"\n\n#include \"context_p.h\"\n#include \"engine.h\"\n#include \"enginerequest.h\"\n#include \"common.h\"\n\n#include <QtCore\/QJsonDocument>\n\n#include <QCryptographicHash>\n#include <QEventLoop>\n\nusing namespace Cutelyst;\n\nResponse::Response(const Headers &defaultHeaders, EngineRequest *engineRequest)\n : d_ptr(new ResponsePrivate(defaultHeaders, engineRequest))\n{\n open(QIODevice::WriteOnly);\n}\n\nqint64 Response::readData(char *data, qint64 maxlen)\n{\n Q_UNUSED(data)\n Q_UNUSED(maxlen)\n return -1;\n}\n\nqint64 Response::writeData(const char *data, qint64 len)\n{\n Q_D(Response);\n\n if (len <= 0) {\n return len;\n }\n\n \/\/ Finalize headers if someone manually writes output\n if (!(d->engineRequest->status & EngineRequest::FinalizedHeaders)) {\n if (d->headers.header(QStringLiteral(\"TRANSFER_ENCODING\")) == QLatin1String(\"chunked\")) {\n d->engineRequest->status |= EngineRequest::IOWrite | EngineRequest::Chunked;\n } else {\n \/\/ When chunked encoding is not set the client can only know\n \/\/ that data is finished if we close the connection\n d->headers.setHeader(QStringLiteral(\"CONNECTION\"), QStringLiteral(\"close\"));\n d->engineRequest->status |= EngineRequest::IOWrite;\n }\n delete d->bodyIODevice;\n d->bodyIODevice = nullptr;\n d->bodyData = QByteArray();\n\n d->engineRequest->finalizeHeaders();\n }\n\n return d->engineRequest->write(data, len);\n}\n\nResponse::~Response()\n{\n delete d_ptr->bodyIODevice;\n delete d_ptr;\n}\n\nquint16 Response::status() const\n{\n Q_D(const Response);\n return d->status;\n}\n\nvoid Response::setStatus(quint16 status)\n{\n Q_D(Response);\n d->status = status;\n}\n\nbool Response::hasBody() const\n{\n Q_D(const Response);\n return !d->bodyData.isEmpty() || d->bodyIODevice || d->engineRequest->status & EngineRequest::IOWrite;\n}\n\nQByteArray &Response::body()\n{\n Q_D(Response);\n if (d->bodyIODevice) {\n delete d->bodyIODevice;\n d->bodyIODevice = nullptr;\n }\n\n return d->bodyData;\n}\n\nQIODevice *Response::bodyDevice() const\n{\n Q_D(const Response);\n return d->bodyIODevice;\n}\n\nvoid Response::setBody(QIODevice *body)\n{\n Q_D(Response);\n Q_ASSERT(body && body->isOpen() && body->isReadable());\n\n if (!(d->engineRequest->status & EngineRequest::IOWrite)) {\n d->bodyData = QByteArray();\n if (d->bodyIODevice) {\n delete d->bodyIODevice;\n }\n d->bodyIODevice = body;\n }\n}\n\nvoid Response::setBody(const QByteArray &body)\n{\n Q_D(Response);\n d->setBodyData(body);\n}\n\nvoid Response::setJsonBody(const QJsonDocument &documment)\n{\n Q_D(Response);\n const QByteArray body = documment.toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonBody(const QString &json)\n{\n Q_D(Response);\n d->setBodyData(json.toUtf8());\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonObjectBody(const QJsonObject &object)\n{\n Q_D(Response);\n const QByteArray body = QJsonDocument(object).toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nvoid Response::setJsonArrayBody(const QJsonArray &array)\n{\n Q_D(Response);\n const QByteArray body = QJsonDocument(array).toJson(QJsonDocument::Compact);\n d->setBodyData(body);\n d->headers.setContentType(QStringLiteral(\"application\/json\"));\n}\n\nQString Response::contentEncoding() const\n{\n Q_D(const Response);\n return d->headers.contentEncoding();\n}\n\nvoid Cutelyst::Response::setContentEncoding(const QString &encoding)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setContentEncoding\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setContentEncoding(encoding);\n}\n\nqint64 Response::contentLength() const\n{\n Q_D(const Response);\n return d->headers.contentLength();\n}\n\nvoid Response::setContentLength(qint64 length)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setContentLength\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setContentLength(length);\n}\n\nQString Response::contentType() const\n{\n Q_D(const Response);\n return d->headers.contentType();\n}\n\nQString Response::contentTypeCharset() const\n{\n Q_D(const Response);\n return d->headers.contentTypeCharset();\n}\n\nQVariant Response::cookie(const QByteArray &name) const\n{\n Q_D(const Response);\n return QVariant::fromValue(d->cookies.value(name));\n}\n\nQList<QNetworkCookie> Response::cookies() const\n{\n Q_D(const Response);\n return d->cookies.values();\n}\n\nvoid Response::setCookie(const QNetworkCookie &cookie)\n{\n Q_D(Response);\n d->cookies.insert(cookie.name(), cookie);\n}\n\nvoid Response::setCookies(const QList<QNetworkCookie> &cookies)\n{\n Q_D(Response);\n for (const QNetworkCookie &cookie : cookies) {\n d->cookies.insert(cookie.name(), cookie);\n }\n}\n\nint Response::removeCookies(const QByteArray &name)\n{\n Q_D(Response);\n return d->cookies.remove(name);\n}\n\nvoid Response::redirect(const QUrl &url, quint16 status)\n{\n Q_D(Response);\n d->location = url;\n d->status = status;\n\n if (url.isValid()) {\n const QString location = QString::fromLatin1(url.toEncoded(QUrl::FullyEncoded));\n qCDebug(CUTELYST_RESPONSE) << \"Redirecting to\" << location << status;\n\n d->headers.setHeader(QStringLiteral(\"LOCATION\"), location);\n d->headers.setContentType(QStringLiteral(\"text\/html; charset=utf-8\"));\n\n const QString buf = QStringLiteral(\n \"<!DOCTYPE html PUBLIC \\\"-\/\/W3C\/\/DTD XHTML 1.0\"\n \"Strict\/\/EN\\\" \\\"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd\\\">\\n\"\n \"<html xmlns=\\\"http:\/\/www.w3.org\/1999\/xhtml\\\">\\n\"\n \" <head>\\n\"\n \" <title>Moved<\/title>\\n\"\n \" <\/head>\\n\"\n \" <body>\\n\"\n \" <p>This item has moved <a href=\") + location +\n QStringLiteral(\">here<\/a>.<\/p>\\n\"\n \" <\/body>\\n\"\n \"<\/html>\\n\");\n setBody(buf);\n } else {\n d->headers.removeHeader(QStringLiteral(\"LOCATION\"));\n qCDebug(CUTELYST_ENGINE) << \"Invalid redirect removing header\" << url << status;\n }\n}\n\nvoid Response::redirect(const QString &url, quint16 status)\n{\n redirect(QUrl(url), status);\n}\n\nQUrl Response::location() const\n{\n Q_D(const Response);\n return d->location;\n}\n\nQString Response::header(const QString &field) const\n{\n Q_D(const Response);\n return d->headers.header(field);\n}\n\nvoid Response::setHeader(const QString &field, const QString &value)\n{\n Q_D(Response);\n Q_ASSERT_X(!(d->engineRequest->status & EngineRequest::FinalizedHeaders),\n \"setHeader\",\n \"setting a header value after finalize_headers and the response callback has been called. Not what you want.\");\n\n d->headers.setHeader(field, value);\n}\n\nHeaders &Response::headers()\n{\n Q_D(Response);\n return d->headers;\n}\n\nbool Response::isSequential() const\n{\n return true;\n}\n\nqint64 Response::size() const\n{\n Q_D(const Response);\n if (d->engineRequest->status & EngineRequest::IOWrite) {\n return -1;\n } else if (d->bodyIODevice) {\n return d->bodyIODevice->size();\n } else {\n return d->bodyData.size();\n }\n}\n\nbool Response::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol)\n{\n Q_D(Response);\n return d->engineRequest->webSocketHandshake(key, origin, protocol);\n}\n\nbool Response::webSocketTextMessage(const QString &message)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendTextMessage(message);\n}\n\nbool Response::webSocketBinaryMessage(const QByteArray &message)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendBinaryMessage(message);\n}\n\nbool Response::webSocketPing(const QByteArray &payload)\n{\n Q_D(Response);\n return d->engineRequest->webSocketSendPing(payload);\n}\n\nbool Response::webSocketClose(quint16 code, const QString &reason)\n{\n Q_D(Response);\n return d->engineRequest->webSocketClose(code, reason);\n}\n\nvoid ResponsePrivate::setBodyData(const QByteArray &body)\n{\n if (!(engineRequest->status & EngineRequest::IOWrite)) {\n if (bodyIODevice) {\n delete bodyIODevice;\n bodyIODevice = nullptr;\n }\n bodyData = body;\n headers.setContentLength(body.size());\n }\n}\n\n#include \"moc_response.cpp\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Ensure correct initialization of vision info at BeginPlay.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=====================================================================\n \n QGroundControl Open Source Ground Control Station\n \n (c) 2009 - 2015 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n \n This file is part of the QGROUNDCONTROL project\n \n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \n ======================================================================*\/\n\n\/\/\/ @file\n\/\/\/ @author Don Gagne <don@thegagnes.com>\n\n#include \"APMFirmwarePlugin.h\"\n#include \"Generic\/GenericFirmwarePlugin.h\"\n#include \"QGCMAVLink.h\"\n\n#include <QDebug>\n\nIMPLEMENT_QGC_SINGLETON(APMFirmwarePlugin, FirmwarePlugin)\nQGC_LOGGING_CATEGORY(APMFirmwarePluginLog, \"APMFirmwarePluginLog\")\n\nstatic const QRegExp APM_COPTER_REXP(\"^(ArduCopter|APM:Copter)\");\nstatic const QRegExp APM_PLANE_REXP(\"^(ArduPlane|APM:Plane)\");\nstatic const QRegExp APM_ROVER_REXP(\"^(ArduRover|APM:Rover)\");\n\n\/\/ Regex to parse version text coming from APM, gives out firmware type, major, minor and patch level numbers\nstatic const QRegExp VERSION_REXP(\"^(APM:Copter|APM:Plane|APM:Rover|ArduCopter|ArduPlane|ArduRover) +[vV](\\\\d*)\\\\.*(\\\\d*)*\\\\.*(\\\\d*)*\");\n\n\/\/ minimum firmware versions that don't suffer from mavlink severity inversion bug.\n\/\/ https:\/\/github.com\/diydrones\/apm_planner\/issues\/788\nstatic const QString MIN_COPTER_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Copter V3.4.0\");\nstatic const QString MIN_PLANE_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Plane V3.4.0\");\nstatic const QString MIN_ROVER_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Rover V2.6.0\");\n\n\n\/*\n * @brief APMFirmwareVersion is a small class to represent the firmware version\n * It encabsules vehicleType, major version, minor version and patch level version\n * and provides accessors for the same.\n * isValid() can be used, to know whether version infromation is available or not\n * supports < operator\n *\/\nAPMFirmwareVersion::APMFirmwareVersion(const QString &versionText)\n{\n _major = 0;\n _minor = 0;\n _patch = 0;\n\n _parseVersion(versionText);\n}\n\nbool APMFirmwareVersion::isValid() const\n{\n return !_versionString.isEmpty();\n}\n\nbool APMFirmwareVersion::isBeta() const\n{\n return _versionString.contains(QStringLiteral(\".rc\"));\n}\n\nbool APMFirmwareVersion::isDev() const\n{\n return _versionString.contains(QStringLiteral(\".dev\"));\n}\n\nbool APMFirmwareVersion::operator <(const APMFirmwareVersion& other) const\n{\n int myVersion = _major << 16 | _minor << 8 | _patch ;\n int otherVersion = other.majorNumber() << 16 | other.minorNumber() << 8 | other.patchNumber();\n return myVersion < otherVersion;\n}\n\nvoid APMFirmwareVersion::_parseVersion(const QString &versionText)\n{\n if (versionText.isEmpty()) {\n return;\n }\n\n\n if (VERSION_REXP.indexIn(versionText) == -1) {\n qCWarning(APMFirmwarePluginLog) << \"firmware version regex didn't match anything\"\n << \"version text to be parsed\" << versionText;\n return;\n }\n\n QStringList capturedTexts = VERSION_REXP.capturedTexts();\n\n if (capturedTexts.count() < 5) {\n qCWarning(APMFirmwarePluginLog) << \"something wrong with parsing the version text, not hitting anything\"\n << VERSION_REXP.captureCount() << VERSION_REXP.capturedTexts();\n return;\n }\n\n \/\/ successful extraction of version numbers\n \/\/ even though we could have collected the version string atleast\n \/\/ but if the parsing has faild, not much point\n _versionString = versionText;\n _vehicleType = capturedTexts[1];\n _major = capturedTexts[2].toInt();\n _minor = capturedTexts[3].toInt();\n _patch = capturedTexts[4].toInt();\n}\n\nAPMFirmwarePlugin::APMFirmwarePlugin(QObject* parent) :\n FirmwarePlugin(parent)\n{\n _textSeverityAdjustmentNeeded = false;\n}\n\nbool APMFirmwarePlugin::isCapable(FirmwareCapabilities capabilities)\n{\n Q_UNUSED(capabilities);\n \n \/\/ FIXME: No capabilitis yet supported\n \n return false;\n}\n\nQList<VehicleComponent*> APMFirmwarePlugin::componentsForVehicle(AutoPilotPlugin* vehicle)\n{\n Q_UNUSED(vehicle);\n \n return QList<VehicleComponent*>();\n}\n\nQStringList APMFirmwarePlugin::flightModes(void)\n{\n \/\/ FIXME: NYI\n \n qWarning() << \"APMFirmwarePlugin::flightModes not supported\";\n \n return QStringList();\n}\n\nQString APMFirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode)\n{\n \/\/ FIXME: Nothing more than generic support yet\n return GenericFirmwarePlugin::instance()->flightMode(base_mode, custom_mode);\n}\n\nbool APMFirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode)\n{\n Q_UNUSED(flightMode);\n Q_UNUSED(base_mode);\n Q_UNUSED(custom_mode);\n \n qWarning() << \"APMFirmwarePlugin::setFlightMode called on base class, not supported\";\n \n return false;\n}\n\nint APMFirmwarePlugin::manualControlReservedButtonCount(void)\n{\n \/\/ We don't know whether the firmware is going to used any of these buttons.\n \/\/ So reserve them all.\n return -1;\n}\n\nvoid APMFirmwarePlugin::adjustMavlinkMessage(mavlink_message_t* message)\n{\n if (message->msgid == MAVLINK_MSG_ID_PARAM_VALUE) {\n mavlink_param_value_t paramValue;\n mavlink_param_union_t paramUnion;\n \n \/\/ APM stack passes all parameter values in mavlink_param_union_t.param_float no matter what\n \/\/ type they are. Fix that up to correct usage.\n \n mavlink_msg_param_value_decode(message, ¶mValue);\n \n switch (paramValue.param_type) {\n case MAV_PARAM_TYPE_UINT8:\n paramUnion.param_uint8 = (uint8_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT8:\n paramUnion.param_int8 = (int8_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_UINT16:\n paramUnion.param_uint16 = (uint16_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT16:\n paramUnion.param_int16 = (int16_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_UINT32:\n paramUnion.param_uint32 = (uint32_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT32:\n paramUnion.param_int32 = (int32_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_REAL32:\n paramUnion.param_float = paramValue.param_value;\n break;\n default:\n qCCritical(APMFirmwarePluginLog) << \"Invalid\/Unsupported data type used in parameter:\" << paramValue.param_type;\n }\n \n paramValue.param_value = paramUnion.param_float;\n \n mavlink_msg_param_value_encode(message->sysid, message->compid, message, ¶mValue);\n \n } else if (message->msgid == MAVLINK_MSG_ID_PARAM_SET) {\n mavlink_param_set_t paramSet;\n mavlink_param_union_t paramUnion;\n \n \/\/ APM stack passes all parameter values in mavlink_param_union_t.param_float no matter what\n \/\/ type they are. Fix it back to the wrong way on the way out.\n \n mavlink_msg_param_set_decode(message, ¶mSet);\n \n paramUnion.param_float = paramSet.param_value;\n\n switch (paramSet.param_type) {\n case MAV_PARAM_TYPE_UINT8:\n paramSet.param_value = paramUnion.param_uint8;\n break;\n case MAV_PARAM_TYPE_INT8:\n paramSet.param_value = paramUnion.param_int8;\n break;\n case MAV_PARAM_TYPE_UINT16:\n paramSet.param_value = paramUnion.param_uint16;\n break;\n case MAV_PARAM_TYPE_INT16:\n paramSet.param_value = paramUnion.param_int16;\n break;\n case MAV_PARAM_TYPE_UINT32:\n paramSet.param_value = paramUnion.param_uint32;\n break;\n case MAV_PARAM_TYPE_INT32:\n paramSet.param_value = paramUnion.param_int32;\n break;\n case MAV_PARAM_TYPE_REAL32:\n \/\/ Already in param_float\n break;\n default:\n qCCritical(APMFirmwarePluginLog) << \"Invalid\/Unsupported data type used in parameter:\" << paramSet.param_type;\n }\n \n mavlink_msg_param_set_encode(message->sysid, message->compid, message, ¶mSet);\n }\n\n if (message->msgid == MAVLINK_MSG_ID_STATUSTEXT)\n {\n QByteArray b;\n b.resize(MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN+1);\n mavlink_msg_statustext_get_text(message, b.data());\n \/\/ Ensure NUL-termination\n b[b.length()-1] = '\\0';\n QString text = QString(b);\n qCDebug(APMFirmwarePluginLog) << text;\n\n \/\/ if don't know firmwareVersion yet, try and see this message contains it\n if (!_firmwareVersion.isValid()) {\n if (text.contains(APM_COPTER_REXP) || text.contains(APM_PLANE_REXP) || text.contains(APM_ROVER_REXP)) {\n \/\/ found version string\n _firmwareVersion = APMFirmwareVersion(text);\n _textSeverityAdjustmentNeeded = _isTextSeverityAdjustmentNeeded(_firmwareVersion);\n }\n }\n\n \/\/ adjust mesasge if needed\n if (_textSeverityAdjustmentNeeded) {\n _adjustSeverity(message);\n }\n }\n}\n\nbool APMFirmwarePlugin::_isTextSeverityAdjustmentNeeded(const APMFirmwareVersion& firmwareVersion)\n{\n if (!firmwareVersion.isValid()) {\n return false;\n }\n\n bool adjustmentNeeded = false;\n if (firmwareVersion.vehicleType().contains(APM_COPTER_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_COPTER_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n } else if (firmwareVersion.vehicleType().contains(APM_PLANE_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_PLANE_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n } else if (firmwareVersion.vehicleType().contains(APM_ROVER_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_ROVER_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n }\n\n return adjustmentNeeded;\n}\n\nvoid APMFirmwarePlugin::_adjustSeverity(mavlink_message_t* message) const\n{\n \/\/ lets make QGC happy with right severity values\n mavlink_statustext_t statusText;\n mavlink_msg_statustext_decode(message, &statusText);\n switch(statusText.severity) {\n case MAV_SEVERITY_ALERT: \/* SEVERITY_LOW according to old codes *\/\n statusText.severity = MAV_SEVERITY_WARNING;\n break;\n case MAV_SEVERITY_CRITICAL: \/*SEVERITY_MEDIUM according to old codes *\/\n statusText.severity = MAV_SEVERITY_ALERT;\n break;\n case MAV_SEVERITY_ERROR: \/*SEVERITY_HIGH according to old codes *\/\n statusText.severity = MAV_SEVERITY_CRITICAL;\n break;\n }\n\n mavlink_msg_statustext_encode(message->sysid, message->compid, message, &statusText);\n}\n\nvoid APMFirmwarePlugin::initializeVehicle(Vehicle* vehicle)\n{\n \/\/ Streams are not started automatically on APM stack\n vehicle->requestDataStream(MAV_DATA_STREAM_RAW_SENSORS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTENDED_STATUS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_RC_CHANNELS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_POSITION, 3);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA1, 10);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA2, 10);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA3, 3);\n}\n<commit_msg>fixed more review comments<commit_after>\/*=====================================================================\n \n QGroundControl Open Source Ground Control Station\n \n (c) 2009 - 2015 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n \n This file is part of the QGROUNDCONTROL project\n \n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \n ======================================================================*\/\n\n\/\/\/ @file\n\/\/\/ @author Don Gagne <don@thegagnes.com>\n\n#include \"APMFirmwarePlugin.h\"\n#include \"Generic\/GenericFirmwarePlugin.h\"\n#include \"QGCMAVLink.h\"\n\n#include <QDebug>\n\nIMPLEMENT_QGC_SINGLETON(APMFirmwarePlugin, FirmwarePlugin)\nQGC_LOGGING_CATEGORY(APMFirmwarePluginLog, \"APMFirmwarePluginLog\")\n\nstatic const QRegExp APM_COPTER_REXP(\"^(ArduCopter|APM:Copter)\");\nstatic const QRegExp APM_PLANE_REXP(\"^(ArduPlane|APM:Plane)\");\nstatic const QRegExp APM_ROVER_REXP(\"^(ArduRover|APM:Rover)\");\n\n\/\/ Regex to parse version text coming from APM, gives out firmware type, major, minor and patch level numbers\nstatic const QRegExp VERSION_REXP(\"^(APM:Copter|APM:Plane|APM:Rover|ArduCopter|ArduPlane|ArduRover) +[vV](\\\\d*)\\\\.*(\\\\d*)*\\\\.*(\\\\d*)*\");\n\n\/\/ minimum firmware versions that don't suffer from mavlink severity inversion bug.\n\/\/ https:\/\/github.com\/diydrones\/apm_planner\/issues\/788\nstatic const QString MIN_COPTER_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Copter V3.4.0\");\nstatic const QString MIN_PLANE_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Plane V3.4.0\");\nstatic const QString MIN_ROVER_VERSION_WITH_CORRECT_SEVERITY_MSGS(\"APM:Rover V2.6.0\");\n\n\n\/*\n * @brief APMFirmwareVersion is a small class to represent the firmware version\n * It encabsules vehicleType, major version, minor version and patch level version\n * and provides accessors for the same.\n * isValid() can be used, to know whether version infromation is available or not\n * supports < operator\n *\/\nAPMFirmwareVersion::APMFirmwareVersion(const QString &versionText)\n{\n _major = 0;\n _minor = 0;\n _patch = 0;\n\n _parseVersion(versionText);\n}\n\nbool APMFirmwareVersion::isValid() const\n{\n return !_versionString.isEmpty();\n}\n\nbool APMFirmwareVersion::isBeta() const\n{\n return _versionString.contains(QStringLiteral(\".rc\"));\n}\n\nbool APMFirmwareVersion::isDev() const\n{\n return _versionString.contains(QStringLiteral(\".dev\"));\n}\n\nbool APMFirmwareVersion::operator <(const APMFirmwareVersion& other) const\n{\n int myVersion = _major << 16 | _minor << 8 | _patch ;\n int otherVersion = other.majorNumber() << 16 | other.minorNumber() << 8 | other.patchNumber();\n return myVersion < otherVersion;\n}\n\nvoid APMFirmwareVersion::_parseVersion(const QString &versionText)\n{\n if (versionText.isEmpty()) {\n return;\n }\n\n\n if (VERSION_REXP.indexIn(versionText) == -1) {\n qCWarning(APMFirmwarePluginLog) << \"firmware version regex didn't match anything\"\n << \"version text to be parsed\" << versionText;\n return;\n }\n\n QStringList capturedTexts = VERSION_REXP.capturedTexts();\n\n if (capturedTexts.count() < 5) {\n qCWarning(APMFirmwarePluginLog) << \"something wrong with parsing the version text, not hitting anything\"\n << VERSION_REXP.captureCount() << VERSION_REXP.capturedTexts();\n return;\n }\n\n \/\/ successful extraction of version numbers\n \/\/ even though we could have collected the version string atleast\n \/\/ but if the parsing has faild, not much point\n _versionString = versionText;\n _vehicleType = capturedTexts[1];\n _major = capturedTexts[2].toInt();\n _minor = capturedTexts[3].toInt();\n _patch = capturedTexts[4].toInt();\n}\n\nAPMFirmwarePlugin::APMFirmwarePlugin(QObject* parent) :\n FirmwarePlugin(parent)\n{\n _textSeverityAdjustmentNeeded = false;\n}\n\nbool APMFirmwarePlugin::isCapable(FirmwareCapabilities capabilities)\n{\n Q_UNUSED(capabilities);\n \n \/\/ FIXME: No capabilitis yet supported\n \n return false;\n}\n\nQList<VehicleComponent*> APMFirmwarePlugin::componentsForVehicle(AutoPilotPlugin* vehicle)\n{\n Q_UNUSED(vehicle);\n \n return QList<VehicleComponent*>();\n}\n\nQStringList APMFirmwarePlugin::flightModes(void)\n{\n \/\/ FIXME: NYI\n \n qWarning() << \"APMFirmwarePlugin::flightModes not supported\";\n \n return QStringList();\n}\n\nQString APMFirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode)\n{\n \/\/ FIXME: Nothing more than generic support yet\n return GenericFirmwarePlugin::instance()->flightMode(base_mode, custom_mode);\n}\n\nbool APMFirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode)\n{\n Q_UNUSED(flightMode);\n Q_UNUSED(base_mode);\n Q_UNUSED(custom_mode);\n \n qWarning() << \"APMFirmwarePlugin::setFlightMode called on base class, not supported\";\n \n return false;\n}\n\nint APMFirmwarePlugin::manualControlReservedButtonCount(void)\n{\n \/\/ We don't know whether the firmware is going to used any of these buttons.\n \/\/ So reserve them all.\n return -1;\n}\n\nvoid APMFirmwarePlugin::adjustMavlinkMessage(mavlink_message_t* message)\n{\n if (message->msgid == MAVLINK_MSG_ID_PARAM_VALUE) {\n mavlink_param_value_t paramValue;\n mavlink_param_union_t paramUnion;\n \n \/\/ APM stack passes all parameter values in mavlink_param_union_t.param_float no matter what\n \/\/ type they are. Fix that up to correct usage.\n \n mavlink_msg_param_value_decode(message, ¶mValue);\n \n switch (paramValue.param_type) {\n case MAV_PARAM_TYPE_UINT8:\n paramUnion.param_uint8 = (uint8_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT8:\n paramUnion.param_int8 = (int8_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_UINT16:\n paramUnion.param_uint16 = (uint16_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT16:\n paramUnion.param_int16 = (int16_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_UINT32:\n paramUnion.param_uint32 = (uint32_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_INT32:\n paramUnion.param_int32 = (int32_t)paramValue.param_value;\n break;\n case MAV_PARAM_TYPE_REAL32:\n paramUnion.param_float = paramValue.param_value;\n break;\n default:\n qCCritical(APMFirmwarePluginLog) << \"Invalid\/Unsupported data type used in parameter:\" << paramValue.param_type;\n }\n \n paramValue.param_value = paramUnion.param_float;\n \n mavlink_msg_param_value_encode(message->sysid, message->compid, message, ¶mValue);\n \n } else if (message->msgid == MAVLINK_MSG_ID_PARAM_SET) {\n mavlink_param_set_t paramSet;\n mavlink_param_union_t paramUnion;\n \n \/\/ APM stack passes all parameter values in mavlink_param_union_t.param_float no matter what\n \/\/ type they are. Fix it back to the wrong way on the way out.\n \n mavlink_msg_param_set_decode(message, ¶mSet);\n \n paramUnion.param_float = paramSet.param_value;\n\n switch (paramSet.param_type) {\n case MAV_PARAM_TYPE_UINT8:\n paramSet.param_value = paramUnion.param_uint8;\n break;\n case MAV_PARAM_TYPE_INT8:\n paramSet.param_value = paramUnion.param_int8;\n break;\n case MAV_PARAM_TYPE_UINT16:\n paramSet.param_value = paramUnion.param_uint16;\n break;\n case MAV_PARAM_TYPE_INT16:\n paramSet.param_value = paramUnion.param_int16;\n break;\n case MAV_PARAM_TYPE_UINT32:\n paramSet.param_value = paramUnion.param_uint32;\n break;\n case MAV_PARAM_TYPE_INT32:\n paramSet.param_value = paramUnion.param_int32;\n break;\n case MAV_PARAM_TYPE_REAL32:\n \/\/ Already in param_float\n break;\n default:\n qCCritical(APMFirmwarePluginLog) << \"Invalid\/Unsupported data type used in parameter:\" << paramSet.param_type;\n }\n \n mavlink_msg_param_set_encode(message->sysid, message->compid, message, ¶mSet);\n }\n\n if (message->msgid == MAVLINK_MSG_ID_STATUSTEXT)\n {\n if (!_firmwareVersion.isValid()) {\n QByteArray b;\n b.resize(MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN+1);\n mavlink_msg_statustext_get_text(message, b.data());\n \/\/ Ensure NUL-termination\n b[b.length()-1] = '\\0';\n QString text = QString(b);\n qCDebug(APMFirmwarePluginLog) << text;\n\n \/\/ if don't know firmwareVersion yet, try and see this message contains it\n if (text.contains(APM_COPTER_REXP) || text.contains(APM_PLANE_REXP) || text.contains(APM_ROVER_REXP)) {\n \/\/ found version string\n _firmwareVersion = APMFirmwareVersion(text);\n _textSeverityAdjustmentNeeded = _isTextSeverityAdjustmentNeeded(_firmwareVersion);\n }\n }\n\n \/\/ adjust mesasge if needed\n if (_textSeverityAdjustmentNeeded) {\n _adjustSeverity(message);\n }\n }\n}\n\nbool APMFirmwarePlugin::_isTextSeverityAdjustmentNeeded(const APMFirmwareVersion& firmwareVersion)\n{\n if (!firmwareVersion.isValid()) {\n return false;\n }\n\n bool adjustmentNeeded = false;\n if (firmwareVersion.vehicleType().contains(APM_COPTER_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_COPTER_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n } else if (firmwareVersion.vehicleType().contains(APM_PLANE_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_PLANE_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n } else if (firmwareVersion.vehicleType().contains(APM_ROVER_REXP)) {\n if (firmwareVersion < APMFirmwareVersion(MIN_ROVER_VERSION_WITH_CORRECT_SEVERITY_MSGS)) {\n adjustmentNeeded = true;\n }\n }\n\n return adjustmentNeeded;\n}\n\nvoid APMFirmwarePlugin::_adjustSeverity(mavlink_message_t* message) const\n{\n \/\/ lets make QGC happy with right severity values\n mavlink_statustext_t statusText;\n mavlink_msg_statustext_decode(message, &statusText);\n switch(statusText.severity) {\n case MAV_SEVERITY_ALERT: \/* SEVERITY_LOW according to old codes *\/\n statusText.severity = MAV_SEVERITY_WARNING;\n break;\n case MAV_SEVERITY_CRITICAL: \/*SEVERITY_MEDIUM according to old codes *\/\n statusText.severity = MAV_SEVERITY_ALERT;\n break;\n case MAV_SEVERITY_ERROR: \/*SEVERITY_HIGH according to old codes *\/\n statusText.severity = MAV_SEVERITY_CRITICAL;\n break;\n }\n\n mavlink_msg_statustext_encode(message->sysid, message->compid, message, &statusText);\n}\n\nvoid APMFirmwarePlugin::initializeVehicle(Vehicle* vehicle)\n{\n \/\/ Streams are not started automatically on APM stack\n vehicle->requestDataStream(MAV_DATA_STREAM_RAW_SENSORS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTENDED_STATUS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_RC_CHANNELS, 2);\n vehicle->requestDataStream(MAV_DATA_STREAM_POSITION, 3);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA1, 10);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA2, 10);\n vehicle->requestDataStream(MAV_DATA_STREAM_EXTRA3, 3);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Include <string><commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Sandeep Mistry. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include <LoRa.h>\n\n\/\/ registers\n#define REG_FIFO 0x00\n#define REG_OP_MODE 0x01\n#define REG_FRF_MSB 0x06\n#define REG_FRF_MID 0x07\n#define REG_FRF_LSB 0x08\n#define REG_PA_CONFIG 0x09\n#define REG_LNA 0x0c\n#define REG_FIFO_ADDR_PTR 0x0d\n#define REG_FIFO_TX_BASE_ADDR 0x0e\n#define REG_FIFO_RX_BASE_ADDR 0x0f\n#define REG_FIFO_RX_CURRENT_ADDR 0x10\n#define REG_IRQ_FLAGS 0x12\n#define REG_RX_NB_BYTES 0x13\n#define REG_PKT_SNR_VALUE 0x19\n#define REG_PKT_RSSI_VALUE 0x1a\n#define REG_MODEM_CONFIG_1 0x1d\n#define REG_MODEM_CONFIG_2 0x1e\n#define REG_PREAMBLE_MSB 0x20\n#define REG_PREAMBLE_LSB 0x21\n#define REG_PAYLOAD_LENGTH 0x22\n#define REG_MODEM_CONFIG_3 0x26\n#define REG_RSSI_WIDEBAND 0x2c\n#define REG_DETECTION_OPTIMIZE 0x31\n#define REG_DETECTION_THRESHOLD 0x37\n#define REG_SYNC_WORD 0x39\n#define REG_DIO_MAPPING_1 0x40\n#define REG_VERSION 0x42\n\n\/\/ modes\n#define MODE_LONG_RANGE_MODE 0x80\n#define MODE_SLEEP 0x00\n#define MODE_STDBY 0x01\n#define MODE_TX 0x03\n#define MODE_RX_CONTINUOUS 0x05\n#define MODE_RX_SINGLE 0x06\n\n\/\/ PA config\n#define PA_BOOST 0x80\n\n\/\/ IRQ masks\n#define IRQ_TX_DONE_MASK 0x08\n#define IRQ_PAYLOAD_CRC_ERROR_MASK 0x20\n#define IRQ_RX_DONE_MASK 0x40\n\n#define MAX_PKT_LENGTH 255\n\nLoRaClass::LoRaClass() :\n _spiSettings(8E6, MSBFIRST, SPI_MODE0),\n _ss(LORA_DEFAULT_SS_PIN), _reset(LORA_DEFAULT_RESET_PIN), _dio0(LORA_DEFAULT_DIO0_PIN),\n _frequency(0),\n _packetIndex(0),\n _implicitHeaderMode(0),\n _onReceive(NULL)\n{\n \/\/ overide Stream timeout value\n setTimeout(0);\n}\n\nint LoRaClass::begin(long frequency)\n{\n \/\/ setup pins\n pinMode(_ss, OUTPUT);\n pinMode(_reset, OUTPUT);\n\n \/\/ perform reset\n digitalWrite(_reset, LOW);\n delay(10);\n digitalWrite(_reset, HIGH);\n delay(10);\n\n \/\/ set SS high\n digitalWrite(_ss, HIGH);\n\n \/\/ start SPI\n SPI.begin();\n\n \/\/ check version\n uint8_t version = readRegister(REG_VERSION);\n if (version != 0x12) {\n return 0;\n }\n\n \/\/ put in sleep mode\n sleep();\n\n \/\/ set frequency\n setFrequency(frequency);\n\n \/\/ set base addresses\n writeRegister(REG_FIFO_TX_BASE_ADDR, 0);\n writeRegister(REG_FIFO_RX_BASE_ADDR, 0);\n\n \/\/ set LNA boost\n writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03);\n\n \/\/ set auto AGC\n writeRegister(REG_MODEM_CONFIG_3, 0x04);\n\n \/\/ set output power to 17 dBm\n setTxPower(17);\n\n \/\/ put in standby mode\n idle();\n\n return 1;\n}\n\nvoid LoRaClass::end()\n{\n \/\/ put in sleep mode\n sleep();\n\n \/\/ stop SPI\n SPI.end();\n}\n\nint LoRaClass::beginPacket(int implicitHeader)\n{\n \/\/ put in standby mode\n idle();\n\n if (implicitHeader) {\n implicitHeaderMode();\n } else {\n explicitHeaderMode();\n }\n\n \/\/ reset FIFO address and paload length\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n writeRegister(REG_PAYLOAD_LENGTH, 0);\n\n return 1;\n}\n\nint LoRaClass::endPacket()\n{\n \/\/ put in TX mode\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX);\n\n \/\/ wait for TX done\n while((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0);\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK);\n\n return 1;\n}\n\nint LoRaClass::parsePacket(int size)\n{\n int packetLength = 0;\n int irqFlags = readRegister(REG_IRQ_FLAGS);\n\n if (size > 0) {\n implicitHeaderMode();\n\n writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);\n } else {\n explicitHeaderMode();\n }\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, irqFlags);\n\n if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {\n \/\/ received a packet\n _packetIndex = 0;\n\n \/\/ read packet length\n if (_implicitHeaderMode) {\n packetLength = readRegister(REG_PAYLOAD_LENGTH);\n } else {\n packetLength = readRegister(REG_RX_NB_BYTES);\n }\n\n \/\/ set FIFO address to current RX address\n writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));\n\n \/\/ put in standby mode\n idle();\n } else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) {\n \/\/ not currently in RX mode\n\n \/\/ reset FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n\n \/\/ put in single RX mode\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE);\n }\n\n return packetLength;\n}\n\nint LoRaClass::packetRssi()\n{\n return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157));\n}\n\nfloat LoRaClass::packetSnr()\n{\n return ((int8_t)readRegister(REG_PKT_SNR_VALUE)) * 0.25;\n}\n\nsize_t LoRaClass::write(uint8_t byte)\n{\n return write(&byte, sizeof(byte));\n}\n\nsize_t LoRaClass::write(const uint8_t *buffer, size_t size)\n{\n int currentLength = readRegister(REG_PAYLOAD_LENGTH);\n\n \/\/ check size\n if ((currentLength + size) > MAX_PKT_LENGTH) {\n size = MAX_PKT_LENGTH - currentLength;\n }\n\n \/\/ write data\n for (size_t i = 0; i < size; i++) {\n writeRegister(REG_FIFO, buffer[i]);\n }\n\n \/\/ update length\n writeRegister(REG_PAYLOAD_LENGTH, currentLength + size);\n\n return size;\n}\n\nint LoRaClass::available()\n{\n return (readRegister(REG_RX_NB_BYTES) - _packetIndex);\n}\n\nint LoRaClass::read()\n{\n if (!available()) {\n return -1;\n }\n\n _packetIndex++;\n\n return readRegister(REG_FIFO);\n}\n\nint LoRaClass::peek()\n{\n if (!available()) {\n return -1;\n }\n\n \/\/ store current FIFO address\n int currentAddress = readRegister(REG_FIFO_ADDR_PTR);\n\n \/\/ read\n uint8_t b = readRegister(REG_FIFO);\n\n \/\/ restore FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, currentAddress);\n\n return b;\n}\n\nvoid LoRaClass::flush()\n{\n}\n\nvoid LoRaClass::onReceive(void(*callback)(int))\n{\n _onReceive = callback;\n\n if (callback) {\n writeRegister(REG_DIO_MAPPING_1, 0x00);\n\n attachInterrupt(digitalPinToInterrupt(_dio0), LoRaClass::onDio0Rise, RISING);\n } else {\n detachInterrupt(digitalPinToInterrupt(_dio0));\n }\n}\n\nvoid LoRaClass::receive(int size)\n{\n if (size > 0) {\n implicitHeaderMode();\n\n writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);\n } else {\n explicitHeaderMode();\n }\n\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS);\n}\n\nvoid LoRaClass::idle()\n{\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY);\n}\n\nvoid LoRaClass::sleep()\n{\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP);\n}\n\nvoid LoRaClass::setTxPower(int level, int outputPin)\n{\n if (PA_OUTPUT_RFO_PIN == outputPin) {\n \/\/ RFO\n if (level < 0) {\n level = 0;\n } else if (level > 14) {\n level = 14;\n }\n\n writeRegister(REG_PA_CONFIG, 0x70 | level);\n } else {\n \/\/ PA BOOST\n if (level < 2) {\n level = 2;\n } else if (level > 17) {\n level = 17;\n }\n\n writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2));\n }\n}\n\nvoid LoRaClass::setFrequency(long frequency)\n{\n _frequency = frequency;\n\n uint64_t frf = ((uint64_t)frequency << 19) \/ 32000000;\n\n writeRegister(REG_FRF_MSB, (uint8_t)(frf >> 16));\n writeRegister(REG_FRF_MID, (uint8_t)(frf >> 8));\n writeRegister(REG_FRF_LSB, (uint8_t)(frf >> 0));\n}\n\nvoid LoRaClass::setSpreadingFactor(int sf)\n{\n if (sf < 6) {\n sf = 6;\n } else if (sf > 12) {\n sf = 12;\n }\n\n if (sf == 6) {\n writeRegister(REG_DETECTION_OPTIMIZE, 0xc5);\n writeRegister(REG_DETECTION_THRESHOLD, 0x0c);\n } else {\n writeRegister(REG_DETECTION_OPTIMIZE, 0xc3);\n writeRegister(REG_DETECTION_THRESHOLD, 0x0a);\n }\n\n writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0));\n}\n\nvoid LoRaClass::setSignalBandwidth(long sbw)\n{\n int bw;\n\n if (sbw <= 7.8E3) {\n bw = 0;\n } else if (sbw <= 10.4E3) {\n bw = 1;\n } else if (sbw <= 15.6E3) {\n bw = 2;\n } else if (sbw <= 20.8E3) {\n bw = 3;\n } else if (sbw <= 31.25E3) {\n bw = 4;\n } else if (sbw <= 41.7E3) {\n bw = 5;\n } else if (sbw <= 62.5E3) {\n bw = 6;\n } else if (sbw <= 125E3) {\n bw = 7;\n } else if (sbw <= 250E3) {\n bw = 8;\n } else \/*if (sbw <= 250E3)*\/ {\n bw = 9;\n }\n\n writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4));\n}\n\nvoid LoRaClass::setCodingRate4(int denominator)\n{\n if (denominator < 5) {\n denominator = 5;\n } else if (denominator > 8) {\n denominator = 8;\n }\n\n int cr = denominator - 4;\n\n writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1));\n}\n\nvoid LoRaClass::setPreambleLength(long length)\n{\n writeRegister(REG_PREAMBLE_MSB, (uint8_t)(length >> 8));\n writeRegister(REG_PREAMBLE_LSB, (uint8_t)(length >> 0));\n}\n\nvoid LoRaClass::setSyncWord(int sw)\n{\n writeRegister(REG_SYNC_WORD, sw);\n}\n\nvoid LoRaClass::enableCrc()\n{\n writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) | 0x04);\n}\n\nvoid LoRaClass::disableCrc()\n{\n writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) & 0xfb);\n}\n\nbyte LoRaClass::random()\n{\n return readRegister(REG_RSSI_WIDEBAND);\n}\n\nvoid LoRaClass::setPins(int ss, int reset, int dio0)\n{\n _ss = ss;\n _reset = reset;\n _dio0 = dio0;\n}\n\nvoid LoRaClass::setSPIFrequency(uint32_t frequency)\n{\n _spiSettings = SPISettings(frequency, MSBFIRST, SPI_MODE0);\n}\n\nvoid LoRaClass::dumpRegisters(Stream& out)\n{\n for (int i = 0; i < 128; i++) {\n out.print(\"0x\");\n out.print(i, HEX);\n out.print(\": 0x\");\n out.println(readRegister(i), HEX);\n }\n}\n\nvoid LoRaClass::explicitHeaderMode()\n{\n _implicitHeaderMode = 0;\n\n writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe);\n}\n\nvoid LoRaClass::implicitHeaderMode()\n{\n _implicitHeaderMode = 1;\n\n writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01);\n}\n\nvoid LoRaClass::handleDio0Rise()\n{\n int irqFlags = readRegister(REG_IRQ_FLAGS);\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, irqFlags);\n\n if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {\n \/\/ received a packet\n _packetIndex = 0;\n\n \/\/ read packet length\n int packetLength = _implicitHeaderMode ? readRegister(REG_PAYLOAD_LENGTH) : readRegister(REG_RX_NB_BYTES);\n\n \/\/ set FIFO address to current RX address\n writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));\n\n if (_onReceive) {\n _onReceive(packetLength);\n }\n\n \/\/ reset FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n }\n}\n\nuint8_t LoRaClass::readRegister(uint8_t address)\n{\n return singleTransfer(address & 0x7f, 0x00);\n}\n\nvoid LoRaClass::writeRegister(uint8_t address, uint8_t value)\n{\n singleTransfer(address | 0x80, value);\n}\n\nuint8_t LoRaClass::singleTransfer(uint8_t address, uint8_t value)\n{\n uint8_t response;\n\n digitalWrite(_ss, LOW);\n\n SPI.beginTransaction(_spiSettings);\n SPI.transfer(address);\n response = SPI.transfer(value);\n SPI.endTransaction();\n\n digitalWrite(_ss, HIGH);\n\n return response;\n}\n\nvoid LoRaClass::onDio0Rise()\n{\n LoRa.handleDio0Rise();\n}\n\nLoRaClass LoRa;\n<commit_msg>stabilize ESP8266 watchdog (#61)<commit_after>\/\/ Copyright (c) Sandeep Mistry. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include <LoRa.h>\n\n\/\/ registers\n#define REG_FIFO 0x00\n#define REG_OP_MODE 0x01\n#define REG_FRF_MSB 0x06\n#define REG_FRF_MID 0x07\n#define REG_FRF_LSB 0x08\n#define REG_PA_CONFIG 0x09\n#define REG_LNA 0x0c\n#define REG_FIFO_ADDR_PTR 0x0d\n#define REG_FIFO_TX_BASE_ADDR 0x0e\n#define REG_FIFO_RX_BASE_ADDR 0x0f\n#define REG_FIFO_RX_CURRENT_ADDR 0x10\n#define REG_IRQ_FLAGS 0x12\n#define REG_RX_NB_BYTES 0x13\n#define REG_PKT_SNR_VALUE 0x19\n#define REG_PKT_RSSI_VALUE 0x1a\n#define REG_MODEM_CONFIG_1 0x1d\n#define REG_MODEM_CONFIG_2 0x1e\n#define REG_PREAMBLE_MSB 0x20\n#define REG_PREAMBLE_LSB 0x21\n#define REG_PAYLOAD_LENGTH 0x22\n#define REG_MODEM_CONFIG_3 0x26\n#define REG_RSSI_WIDEBAND 0x2c\n#define REG_DETECTION_OPTIMIZE 0x31\n#define REG_DETECTION_THRESHOLD 0x37\n#define REG_SYNC_WORD 0x39\n#define REG_DIO_MAPPING_1 0x40\n#define REG_VERSION 0x42\n\n\/\/ modes\n#define MODE_LONG_RANGE_MODE 0x80\n#define MODE_SLEEP 0x00\n#define MODE_STDBY 0x01\n#define MODE_TX 0x03\n#define MODE_RX_CONTINUOUS 0x05\n#define MODE_RX_SINGLE 0x06\n\n\/\/ PA config\n#define PA_BOOST 0x80\n\n\/\/ IRQ masks\n#define IRQ_TX_DONE_MASK 0x08\n#define IRQ_PAYLOAD_CRC_ERROR_MASK 0x20\n#define IRQ_RX_DONE_MASK 0x40\n\n#define MAX_PKT_LENGTH 255\n\nLoRaClass::LoRaClass() :\n _spiSettings(8E6, MSBFIRST, SPI_MODE0),\n _ss(LORA_DEFAULT_SS_PIN), _reset(LORA_DEFAULT_RESET_PIN), _dio0(LORA_DEFAULT_DIO0_PIN),\n _frequency(0),\n _packetIndex(0),\n _implicitHeaderMode(0),\n _onReceive(NULL)\n{\n \/\/ overide Stream timeout value\n setTimeout(0);\n}\n\nint LoRaClass::begin(long frequency)\n{\n \/\/ setup pins\n pinMode(_ss, OUTPUT);\n pinMode(_reset, OUTPUT);\n\n \/\/ perform reset\n digitalWrite(_reset, LOW);\n delay(10);\n digitalWrite(_reset, HIGH);\n delay(10);\n\n \/\/ set SS high\n digitalWrite(_ss, HIGH);\n\n \/\/ start SPI\n SPI.begin();\n\n \/\/ check version\n uint8_t version = readRegister(REG_VERSION);\n if (version != 0x12) {\n return 0;\n }\n\n \/\/ put in sleep mode\n sleep();\n\n \/\/ set frequency\n setFrequency(frequency);\n\n \/\/ set base addresses\n writeRegister(REG_FIFO_TX_BASE_ADDR, 0);\n writeRegister(REG_FIFO_RX_BASE_ADDR, 0);\n\n \/\/ set LNA boost\n writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03);\n\n \/\/ set auto AGC\n writeRegister(REG_MODEM_CONFIG_3, 0x04);\n\n \/\/ set output power to 17 dBm\n setTxPower(17);\n\n \/\/ put in standby mode\n idle();\n\n return 1;\n}\n\nvoid LoRaClass::end()\n{\n \/\/ put in sleep mode\n sleep();\n\n \/\/ stop SPI\n SPI.end();\n}\n\nint LoRaClass::beginPacket(int implicitHeader)\n{\n \/\/ put in standby mode\n idle();\n\n if (implicitHeader) {\n implicitHeaderMode();\n } else {\n explicitHeaderMode();\n }\n\n \/\/ reset FIFO address and paload length\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n writeRegister(REG_PAYLOAD_LENGTH, 0);\n\n return 1;\n}\n\nint LoRaClass::endPacket()\n{\n \/\/ put in TX mode\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX);\n\n \/\/ wait for TX done\n while ((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0) {\n yield();\n }\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK);\n\n return 1;\n}\n\nint LoRaClass::parsePacket(int size)\n{\n int packetLength = 0;\n int irqFlags = readRegister(REG_IRQ_FLAGS);\n\n if (size > 0) {\n implicitHeaderMode();\n\n writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);\n } else {\n explicitHeaderMode();\n }\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, irqFlags);\n\n if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {\n \/\/ received a packet\n _packetIndex = 0;\n\n \/\/ read packet length\n if (_implicitHeaderMode) {\n packetLength = readRegister(REG_PAYLOAD_LENGTH);\n } else {\n packetLength = readRegister(REG_RX_NB_BYTES);\n }\n\n \/\/ set FIFO address to current RX address\n writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));\n\n \/\/ put in standby mode\n idle();\n } else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) {\n \/\/ not currently in RX mode\n\n \/\/ reset FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n\n \/\/ put in single RX mode\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE);\n }\n\n return packetLength;\n}\n\nint LoRaClass::packetRssi()\n{\n return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157));\n}\n\nfloat LoRaClass::packetSnr()\n{\n return ((int8_t)readRegister(REG_PKT_SNR_VALUE)) * 0.25;\n}\n\nsize_t LoRaClass::write(uint8_t byte)\n{\n return write(&byte, sizeof(byte));\n}\n\nsize_t LoRaClass::write(const uint8_t *buffer, size_t size)\n{\n int currentLength = readRegister(REG_PAYLOAD_LENGTH);\n\n \/\/ check size\n if ((currentLength + size) > MAX_PKT_LENGTH) {\n size = MAX_PKT_LENGTH - currentLength;\n }\n\n \/\/ write data\n for (size_t i = 0; i < size; i++) {\n writeRegister(REG_FIFO, buffer[i]);\n }\n\n \/\/ update length\n writeRegister(REG_PAYLOAD_LENGTH, currentLength + size);\n\n return size;\n}\n\nint LoRaClass::available()\n{\n return (readRegister(REG_RX_NB_BYTES) - _packetIndex);\n}\n\nint LoRaClass::read()\n{\n if (!available()) {\n return -1;\n }\n\n _packetIndex++;\n\n return readRegister(REG_FIFO);\n}\n\nint LoRaClass::peek()\n{\n if (!available()) {\n return -1;\n }\n\n \/\/ store current FIFO address\n int currentAddress = readRegister(REG_FIFO_ADDR_PTR);\n\n \/\/ read\n uint8_t b = readRegister(REG_FIFO);\n\n \/\/ restore FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, currentAddress);\n\n return b;\n}\n\nvoid LoRaClass::flush()\n{\n}\n\nvoid LoRaClass::onReceive(void(*callback)(int))\n{\n _onReceive = callback;\n\n if (callback) {\n writeRegister(REG_DIO_MAPPING_1, 0x00);\n\n attachInterrupt(digitalPinToInterrupt(_dio0), LoRaClass::onDio0Rise, RISING);\n } else {\n detachInterrupt(digitalPinToInterrupt(_dio0));\n }\n}\n\nvoid LoRaClass::receive(int size)\n{\n if (size > 0) {\n implicitHeaderMode();\n\n writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);\n } else {\n explicitHeaderMode();\n }\n\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS);\n}\n\nvoid LoRaClass::idle()\n{\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY);\n}\n\nvoid LoRaClass::sleep()\n{\n writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP);\n}\n\nvoid LoRaClass::setTxPower(int level, int outputPin)\n{\n if (PA_OUTPUT_RFO_PIN == outputPin) {\n \/\/ RFO\n if (level < 0) {\n level = 0;\n } else if (level > 14) {\n level = 14;\n }\n\n writeRegister(REG_PA_CONFIG, 0x70 | level);\n } else {\n \/\/ PA BOOST\n if (level < 2) {\n level = 2;\n } else if (level > 17) {\n level = 17;\n }\n\n writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2));\n }\n}\n\nvoid LoRaClass::setFrequency(long frequency)\n{\n _frequency = frequency;\n\n uint64_t frf = ((uint64_t)frequency << 19) \/ 32000000;\n\n writeRegister(REG_FRF_MSB, (uint8_t)(frf >> 16));\n writeRegister(REG_FRF_MID, (uint8_t)(frf >> 8));\n writeRegister(REG_FRF_LSB, (uint8_t)(frf >> 0));\n}\n\nvoid LoRaClass::setSpreadingFactor(int sf)\n{\n if (sf < 6) {\n sf = 6;\n } else if (sf > 12) {\n sf = 12;\n }\n\n if (sf == 6) {\n writeRegister(REG_DETECTION_OPTIMIZE, 0xc5);\n writeRegister(REG_DETECTION_THRESHOLD, 0x0c);\n } else {\n writeRegister(REG_DETECTION_OPTIMIZE, 0xc3);\n writeRegister(REG_DETECTION_THRESHOLD, 0x0a);\n }\n\n writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0));\n}\n\nvoid LoRaClass::setSignalBandwidth(long sbw)\n{\n int bw;\n\n if (sbw <= 7.8E3) {\n bw = 0;\n } else if (sbw <= 10.4E3) {\n bw = 1;\n } else if (sbw <= 15.6E3) {\n bw = 2;\n } else if (sbw <= 20.8E3) {\n bw = 3;\n } else if (sbw <= 31.25E3) {\n bw = 4;\n } else if (sbw <= 41.7E3) {\n bw = 5;\n } else if (sbw <= 62.5E3) {\n bw = 6;\n } else if (sbw <= 125E3) {\n bw = 7;\n } else if (sbw <= 250E3) {\n bw = 8;\n } else \/*if (sbw <= 250E3)*\/ {\n bw = 9;\n }\n\n writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4));\n}\n\nvoid LoRaClass::setCodingRate4(int denominator)\n{\n if (denominator < 5) {\n denominator = 5;\n } else if (denominator > 8) {\n denominator = 8;\n }\n\n int cr = denominator - 4;\n\n writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1));\n}\n\nvoid LoRaClass::setPreambleLength(long length)\n{\n writeRegister(REG_PREAMBLE_MSB, (uint8_t)(length >> 8));\n writeRegister(REG_PREAMBLE_LSB, (uint8_t)(length >> 0));\n}\n\nvoid LoRaClass::setSyncWord(int sw)\n{\n writeRegister(REG_SYNC_WORD, sw);\n}\n\nvoid LoRaClass::enableCrc()\n{\n writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) | 0x04);\n}\n\nvoid LoRaClass::disableCrc()\n{\n writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) & 0xfb);\n}\n\nbyte LoRaClass::random()\n{\n return readRegister(REG_RSSI_WIDEBAND);\n}\n\nvoid LoRaClass::setPins(int ss, int reset, int dio0)\n{\n _ss = ss;\n _reset = reset;\n _dio0 = dio0;\n}\n\nvoid LoRaClass::setSPIFrequency(uint32_t frequency)\n{\n _spiSettings = SPISettings(frequency, MSBFIRST, SPI_MODE0);\n}\n\nvoid LoRaClass::dumpRegisters(Stream& out)\n{\n for (int i = 0; i < 128; i++) {\n out.print(\"0x\");\n out.print(i, HEX);\n out.print(\": 0x\");\n out.println(readRegister(i), HEX);\n }\n}\n\nvoid LoRaClass::explicitHeaderMode()\n{\n _implicitHeaderMode = 0;\n\n writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe);\n}\n\nvoid LoRaClass::implicitHeaderMode()\n{\n _implicitHeaderMode = 1;\n\n writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01);\n}\n\nvoid LoRaClass::handleDio0Rise()\n{\n int irqFlags = readRegister(REG_IRQ_FLAGS);\n\n \/\/ clear IRQ's\n writeRegister(REG_IRQ_FLAGS, irqFlags);\n\n if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {\n \/\/ received a packet\n _packetIndex = 0;\n\n \/\/ read packet length\n int packetLength = _implicitHeaderMode ? readRegister(REG_PAYLOAD_LENGTH) : readRegister(REG_RX_NB_BYTES);\n\n \/\/ set FIFO address to current RX address\n writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));\n\n if (_onReceive) {\n _onReceive(packetLength);\n }\n\n \/\/ reset FIFO address\n writeRegister(REG_FIFO_ADDR_PTR, 0);\n }\n}\n\nuint8_t LoRaClass::readRegister(uint8_t address)\n{\n return singleTransfer(address & 0x7f, 0x00);\n}\n\nvoid LoRaClass::writeRegister(uint8_t address, uint8_t value)\n{\n singleTransfer(address | 0x80, value);\n}\n\nuint8_t LoRaClass::singleTransfer(uint8_t address, uint8_t value)\n{\n uint8_t response;\n\n digitalWrite(_ss, LOW);\n\n SPI.beginTransaction(_spiSettings);\n SPI.transfer(address);\n response = SPI.transfer(value);\n SPI.endTransaction();\n\n digitalWrite(_ss, HIGH);\n\n return response;\n}\n\nvoid LoRaClass::onDio0Rise()\n{\n LoRa.handleDio0Rise();\n}\n\nLoRaClass LoRa;\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- C++ -*-\n\n\/**\n * @file gnuwrapper.cpp\n * @brief Replaces malloc family on GNU\/Linux with custom versions.\n * @author Emery Berger <http:\/\/www.cs.umass.edu\/~emery>\n * @note Copyright (C) 2010 by Emery Berger, University of Massachusetts Amherst.\n *\/\n\n\n#ifndef __GNUC__\n#error \"This file requires the GNU compiler.\"\n#endif\n\n#include <errno.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <malloc.h>\n#include <new>\n#include <pthread.h>\n#include <sys\/cdefs.h>\n\n#include \"heaplayers.h\"\n\n\/*\n To use this library,\n you only need to define the following allocation functions:\n \n - xxmalloc\n - xxfree\n - xxmalloc_usable_size\n - xxmalloc_lock\n - xxmalloc_unlock\n\n See the extern \"C\" block below for function prototypes and more\n details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO\n SUPPORT ANY ALLOCATOR.\n\n\n LIMITATIONS:\n\n - This wrapper assumes that the underlying allocator will do \"the\n right thing\" when xxfree() is called with a pointer internal to an\n allocated object. Header-based allocators, for example, need not\n apply.\n\n*\/\n\n#define WEAK(x) __attribute__ ((weak, alias(#x)))\n#ifndef __THROW\n#define __THROW\n#endif\n\n#define CUSTOM_PREFIX(x) custom##x\n\n#define WEAK_REDEF1(type,fname,arg1) type fname(arg1) __THROW WEAK(custom##fname)\n#define WEAK_REDEF2(type,fname,arg1,arg2) type fname(arg1,arg2) __THROW WEAK(custom##fname)\n#define WEAK_REDEF3(type,fname,arg1,arg2,arg3) type fname(arg1,arg2,arg3) __THROW WEAK(custom##fname)\n\nextern \"C\" {\n WEAK_REDEF1(void *, malloc, size_t);\n WEAK_REDEF1(void, free, void *);\n WEAK_REDEF1(void, cfree, void *);\n WEAK_REDEF2(void *, calloc, size_t, size_t);\n WEAK_REDEF2(void *, realloc, void *, size_t);\n WEAK_REDEF2(void *, memalign, size_t, size_t);\n WEAK_REDEF3(int, posix_memalign, void **, size_t, size_t);\n WEAK_REDEF2(void *, aligned_alloc, size_t, size_t);\n WEAK_REDEF1(size_t, malloc_usable_size, void *);\n}\n\n#include \"wrapper.cpp\"\n#include \"gnuwrapper-hooks.cpp\"\n<commit_msg>Force export visibility.<commit_after>\/\/ -*- C++ -*-\n\n\/**\n * @file gnuwrapper.cpp\n * @brief Replaces malloc family on GNU\/Linux with custom versions.\n * @author Emery Berger <http:\/\/www.cs.umass.edu\/~emery>\n * @note Copyright (C) 2010 by Emery Berger, University of Massachusetts Amherst.\n *\/\n\n\n#ifndef __GNUC__\n#error \"This file requires the GNU compiler.\"\n#endif\n\n#include <errno.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <malloc.h>\n#include <new>\n#include <pthread.h>\n#include <sys\/cdefs.h>\n\n#include \"heaplayers.h\"\n\n\/*\n To use this library,\n you only need to define the following allocation functions:\n \n - xxmalloc\n - xxfree\n - xxmalloc_usable_size\n - xxmalloc_lock\n - xxmalloc_unlock\n\n See the extern \"C\" block below for function prototypes and more\n details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO\n SUPPORT ANY ALLOCATOR.\n\n\n LIMITATIONS:\n\n - This wrapper assumes that the underlying allocator will do \"the\n right thing\" when xxfree() is called with a pointer internal to an\n allocated object. Header-based allocators, for example, need not\n apply.\n\n*\/\n\n#define WEAK(x) __attribute__ ((weak, alias(#x)))\n#ifndef __THROW\n#define __THROW\n#endif\n\n#define CUSTOM_PREFIX(x) custom##x\n#define ATTRIBUTE_EXPORT __attribute__((visibility(\"default\")))\n\n#define WEAK_REDEF1(type,fname,arg1) ATTRIBUTE_EXPORT type fname(arg1) __THROW WEAK(custom##fname)\n#define WEAK_REDEF2(type,fname,arg1,arg2) ATTRIBUTE_EXPORT type fname(arg1,arg2) __THROW WEAK(custom##fname)\n#define WEAK_REDEF3(type,fname,arg1,arg2,arg3) ATTRIBUTE_EXPORT type fname(arg1,arg2,arg3) __THROW WEAK(custom##fname)\n\nextern \"C\" {\n WEAK_REDEF1(void *, malloc, size_t);\n WEAK_REDEF1(void, free, void *);\n WEAK_REDEF1(void, cfree, void *);\n WEAK_REDEF2(void *, calloc, size_t, size_t);\n WEAK_REDEF2(void *, realloc, void *, size_t);\n WEAK_REDEF2(void *, memalign, size_t, size_t);\n WEAK_REDEF3(int, posix_memalign, void **, size_t, size_t);\n WEAK_REDEF2(void *, aligned_alloc, size_t, size_t);\n WEAK_REDEF1(size_t, malloc_usable_size, void *);\n}\n\n#include \"wrapper.cpp\"\n#include \"gnuwrapper-hooks.cpp\"\n<|endoftext|>"} {"text":"<commit_before>#include <nan.h>\n#include <native-json.h>\n#include \"dvbtee-parser.h\"\n\nTableData::TableData(const uint8_t &tableId,\n const std::string &decoderName,\n const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTableReceiver::TableReceiver(dvbteeParser *dvbteeParser)\n: m_dvbteeParser(dvbteeParser) {\n uv_mutex_init(&m_ev_mutex);\n uv_async_init(uv_default_loop(), &m_async, completeCb);\n m_async.data = this;\n}\n\nTableReceiver::~TableReceiver() {\n unregisterInterface();\n\n m_cb.Reset();\n\n uv_mutex_lock(&m_ev_mutex);\n while (!m_eq.empty()) {\n TableData *data = m_eq.front();\n delete data;\n m_eq.pop();\n }\n uv_mutex_unlock(&m_ev_mutex);\n\n uv_mutex_destroy(&m_ev_mutex);\n}\n\nvoid TableReceiver::subscribe(const v8::Local<v8::Function> &fn) {\n m_cb.SetFunction(fn);\n registerInterface();\n}\n\nvoid TableReceiver::registerInterface() {\n m_dvbteeParser->m_parser.subscribeTables(this);\n}\n\nvoid TableReceiver::unregisterInterface() {\n m_dvbteeParser->m_parser.subscribeTables(NULL);\n}\n\nvoid TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table) {\n uv_mutex_lock(&m_ev_mutex);\n m_eq.push(\n new TableData(table->getTableid(),\n table->getDecoderName(),\n table->toJson())\n );\n uv_mutex_unlock(&m_ev_mutex);\n\n uv_async_send(&m_async);\n}\n\n#if defined(NODE_MAJOR_VERSION) && (NODE_MAJOR_VERSION == 0 && \\\n defined(NODE_MINOR_VERSION) && (NODE_MINOR_VERSION < 12))\n#define v8_JSON Native::JSON\n#else\n#define v8_JSON v8::JSON\n#endif\n\nvoid TableReceiver::notify() {\n Nan::HandleScope scope;\n uv_mutex_lock(&m_ev_mutex);\n while (!m_eq.empty()) {\n TableData *data = m_eq.front();\n uv_mutex_unlock(&m_ev_mutex);\n\n if (!m_cb.IsEmpty()) {\n v8::Local<v8::String> jsonStr = Nan::New(data->json).ToLocalChecked();\n v8::Local<v8::Value> jsonObj = v8_JSON::Parse(jsonStr);\n\n v8::Local<v8::Value> argv[] = {\n Nan::New(data->tableId),\n Nan::New(data->decoderName).ToLocalChecked(),\n jsonObj\n };\n\n m_cb.Call(3, argv);\n }\n\n delete data;\n\n uv_mutex_lock(&m_ev_mutex);\n m_eq.pop();\n }\n uv_mutex_unlock(&m_ev_mutex);\n}\n\nvoid TableReceiver::completeCb(uv_async_t *handle\n#if NODE_MODULE_VERSION<=11\n , int status \/*UNUSED*\/\n#endif\n ) {\n TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);\n rcvr->notify();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent<v8::Function> dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser()\n: m_tableReceiver(this) {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(v8::Handle<v8::Object> exports) {\n Nan::HandleScope scope;\n\n \/\/ Prepare constructor template\n v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"feed\", feed);\n Nan::SetPrototypeMethod(tpl, \"push\", feed); \/\/ deprecated\n Nan::SetPrototypeMethod(tpl, \"parse\", feed); \/\/ deprecated\n Nan::SetPrototypeMethod(tpl, \"listenTables\", listenTables);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n dvbteeParser* obj = new dvbteeParser();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 0;\n v8::Local<v8::Value> argv[argc] = { };\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\nvoid dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n obj->m_tableReceiver.subscribe(info[lastArg].As<v8::Function>());\n }\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\npublic:\n ResetWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback) {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n }\n ~ResetWorker() {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(0)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As<v8::Function>()\n );\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(info.Holder());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass FeedWorker : public Nan::AsyncWorker {\npublic:\n FeedWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n , m_buf(NULL)\n , m_buf_len(0)\n , m_ret(-1) {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n const char *key = \"buf\";\n SaveToPersistent(key, info[0]);\n m_buf = node::Buffer::Data(GetFromPersistent(key)->ToObject());\n m_buf_len = info[1]->Uint32Value();\n }\n }\n ~FeedWorker() {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n if ((m_buf) && (m_buf_len)) {\n m_ret = m_obj->m_parser.feed(m_buf_len, (uint8_t*)m_buf);\n }\n if (m_ret < 0) {\n SetErrorMessage(\"invalid buffer \/ length\");\n }\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n};\n\n\nvoid dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n \/\/\n \/\/ Note: when packets are pushed to the parser, the parser will start\n \/\/ generating async events containing PSIP table data regardless of\n \/\/ whether this function was called synchronously or not\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As<v8::Function>()\n );\n Nan::AsyncQueueWorker(new FeedWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n int ret = -1;\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n unsigned int len = info[1]->Uint32Value();\n const char* buf = node::Buffer::Data(bufferObj);\n\n ret = obj->m_parser.feed(len, (uint8_t*)buf);\n }\n\n info.GetReturnValue().Set(Nan::New(ret));\n }\n}\n<commit_msg>At least two spaces is best between code and comments [whitespace\/comments] [2]<commit_after>#include <nan.h>\n#include <native-json.h>\n#include \"dvbtee-parser.h\"\n\nTableData::TableData(const uint8_t &tableId,\n const std::string &decoderName,\n const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTableReceiver::TableReceiver(dvbteeParser *dvbteeParser)\n: m_dvbteeParser(dvbteeParser) {\n uv_mutex_init(&m_ev_mutex);\n uv_async_init(uv_default_loop(), &m_async, completeCb);\n m_async.data = this;\n}\n\nTableReceiver::~TableReceiver() {\n unregisterInterface();\n\n m_cb.Reset();\n\n uv_mutex_lock(&m_ev_mutex);\n while (!m_eq.empty()) {\n TableData *data = m_eq.front();\n delete data;\n m_eq.pop();\n }\n uv_mutex_unlock(&m_ev_mutex);\n\n uv_mutex_destroy(&m_ev_mutex);\n}\n\nvoid TableReceiver::subscribe(const v8::Local<v8::Function> &fn) {\n m_cb.SetFunction(fn);\n registerInterface();\n}\n\nvoid TableReceiver::registerInterface() {\n m_dvbteeParser->m_parser.subscribeTables(this);\n}\n\nvoid TableReceiver::unregisterInterface() {\n m_dvbteeParser->m_parser.subscribeTables(NULL);\n}\n\nvoid TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table) {\n uv_mutex_lock(&m_ev_mutex);\n m_eq.push(\n new TableData(table->getTableid(),\n table->getDecoderName(),\n table->toJson())\n );\n uv_mutex_unlock(&m_ev_mutex);\n\n uv_async_send(&m_async);\n}\n\n#if defined(NODE_MAJOR_VERSION) && (NODE_MAJOR_VERSION == 0 && \\\n defined(NODE_MINOR_VERSION) && (NODE_MINOR_VERSION < 12))\n#define v8_JSON Native::JSON\n#else\n#define v8_JSON v8::JSON\n#endif\n\nvoid TableReceiver::notify() {\n Nan::HandleScope scope;\n uv_mutex_lock(&m_ev_mutex);\n while (!m_eq.empty()) {\n TableData *data = m_eq.front();\n uv_mutex_unlock(&m_ev_mutex);\n\n if (!m_cb.IsEmpty()) {\n v8::Local<v8::String> jsonStr = Nan::New(data->json).ToLocalChecked();\n v8::Local<v8::Value> jsonObj = v8_JSON::Parse(jsonStr);\n\n v8::Local<v8::Value> argv[] = {\n Nan::New(data->tableId),\n Nan::New(data->decoderName).ToLocalChecked(),\n jsonObj\n };\n\n m_cb.Call(3, argv);\n }\n\n delete data;\n\n uv_mutex_lock(&m_ev_mutex);\n m_eq.pop();\n }\n uv_mutex_unlock(&m_ev_mutex);\n}\n\nvoid TableReceiver::completeCb(uv_async_t *handle\n#if NODE_MODULE_VERSION<=11\n , int status \/*UNUSED*\/\n#endif\n ) {\n TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);\n rcvr->notify();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent<v8::Function> dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser()\n: m_tableReceiver(this) {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(v8::Handle<v8::Object> exports) {\n Nan::HandleScope scope;\n\n \/\/ Prepare constructor template\n v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"feed\", feed);\n Nan::SetPrototypeMethod(tpl, \"push\", feed); \/\/ deprecated\n Nan::SetPrototypeMethod(tpl, \"parse\", feed); \/\/ deprecated\n Nan::SetPrototypeMethod(tpl, \"listenTables\", listenTables);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n dvbteeParser* obj = new dvbteeParser();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 0;\n v8::Local<v8::Value> argv[argc] = { };\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\nvoid dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n obj->m_tableReceiver.subscribe(info[lastArg].As<v8::Function>());\n }\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\npublic:\n ResetWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback) {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n }\n ~ResetWorker() {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(0)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As<v8::Function>()\n );\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(info.Holder());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass FeedWorker : public Nan::AsyncWorker {\npublic:\n FeedWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n , m_buf(NULL)\n , m_buf_len(0)\n , m_ret(-1) {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n const char *key = \"buf\";\n SaveToPersistent(key, info[0]);\n m_buf = node::Buffer::Data(GetFromPersistent(key)->ToObject());\n m_buf_len = info[1]->Uint32Value();\n }\n }\n ~FeedWorker() {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n if ((m_buf) && (m_buf_len)) {\n m_ret = m_obj->m_parser.feed(m_buf_len, (uint8_t*)m_buf);\n }\n if (m_ret < 0) {\n SetErrorMessage(\"invalid buffer \/ length\");\n }\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n};\n\n\nvoid dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n \/\/\n \/\/ Note: when packets are pushed to the parser, the parser will start\n \/\/ generating async events containing PSIP table data regardless of\n \/\/ whether this function was called synchronously or not\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As<v8::Function>()\n );\n Nan::AsyncQueueWorker(new FeedWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n int ret = -1;\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n unsigned int len = info[1]->Uint32Value();\n const char* buf = node::Buffer::Data(bufferObj);\n\n ret = obj->m_parser.feed(len, (uint8_t*)buf);\n }\n\n info.GetReturnValue().Set(Nan::New(ret));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_TYPES_HPP_INCLUDED\n#define TORRENT_ALERT_TYPES_HPP_INCLUDED\n\n#include <string>\n\n#include \"libtorrent\/alert.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n\nnamespace libtorrent\n{\n\tstruct tracker_alert: alert\n\t{\n\t\ttracker_alert(const torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::warning, msg)\n\t\t\t, handle(h)\n\t\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new tracker_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct hash_failed_alert: alert\n\t{\n\t\thash_failed_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, int index\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::info, msg)\n\t\t\t, handle(h)\n\t\t\t, piece_index(index)\n\t\t\t{ assert(index >= 0);}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new hash_failed_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\tint piece_index;\n\t};\n\n\tstruct peer_error_alert: alert\n\t{\n\t\tpeer_error_alert(const address& pip, const std::string& msg)\n\t\t\t: alert(alert::debug, msg)\n\t\t\t, ip(pip)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new peer_error_alert(*this)); }\n\n\t\taddress ip;\n\t};\n\n\tstruct chat_message_alert: alert\n\t{\n\t\tchat_message_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const address& sender\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::critical, msg)\n\t\t\t, handle(h)\n\t\t\t, ip(sender)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new chat_message_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\taddress ip;\n\t};\n\n\tstruct invalid_request_alert: alert\n\t{\n\t\tinvalid_request_alert(\n\t\t\tconst peer_request& r\n\t\t\t, const torrent_handle& h\n\t\t\t, const address& sender\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::debug, msg)\n\t\t\t, handle(h)\n\t\t\t, ip(sender)\n\t\t\t, request(r)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new invalid_request_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\taddress ip;\n\t\tpeer_request request;\n\t};\n\n\tstruct torrent_finished_alert: alert\n\t{\n\t\ttorrent_finished_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::warning, msg)\n\t\t\t, handle(h)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new torrent_finished_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct file_error_alert: alert\n\t{\n\t\tfile_error_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::fatal, msg)\n\t\t\t, handle(h)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new file_error_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct listen_failed_alert: alert\n\t{\n\t\tlisten_failed_alert(\n\t\t\tconst std::string& msg)\n\t\t\t: alert(alert::fatal, msg)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new listen_failed_alert(*this)); }\n\t};\n}\n\n\n#endif\n<commit_msg>*** empty log message ***<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_TYPES_HPP_INCLUDED\n#define TORRENT_ALERT_TYPES_HPP_INCLUDED\n\n#include \"libtorrent\/alert.hpp\"\n#include \"libtorrent\/torrent_handle.hpp\"\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/peer_connection.hpp\"\n\nnamespace libtorrent\n{\n\tstruct tracker_alert: alert\n\t{\n\t\ttracker_alert(const torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::warning, msg)\n\t\t\t, handle(h)\n\t\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new tracker_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct hash_failed_alert: alert\n\t{\n\t\thash_failed_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, int index\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::info, msg)\n\t\t\t, handle(h)\n\t\t\t, piece_index(index)\n\t\t\t{ assert(index >= 0);}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new hash_failed_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\tint piece_index;\n\t};\n\n\tstruct peer_error_alert: alert\n\t{\n\t\tpeer_error_alert(const address& pip, const std::string& msg)\n\t\t\t: alert(alert::debug, msg)\n\t\t\t, ip(pip)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new peer_error_alert(*this)); }\n\n\t\taddress ip;\n\t};\n\n\tstruct chat_message_alert: alert\n\t{\n\t\tchat_message_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const address& sender\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::critical, msg)\n\t\t\t, handle(h)\n\t\t\t, ip(sender)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new chat_message_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\taddress ip;\n\t};\n\n\tstruct invalid_request_alert: alert\n\t{\n\t\tinvalid_request_alert(\n\t\t\tconst peer_request& r\n\t\t\t, const torrent_handle& h\n\t\t\t, const address& sender\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::debug, msg)\n\t\t\t, handle(h)\n\t\t\t, ip(sender)\n\t\t\t, request(r)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new invalid_request_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t\taddress ip;\n\t\tpeer_request request;\n\t};\n\n\tstruct torrent_finished_alert: alert\n\t{\n\t\ttorrent_finished_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::warning, msg)\n\t\t\t, handle(h)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new torrent_finished_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct file_error_alert: alert\n\t{\n\t\tfile_error_alert(\n\t\t\tconst torrent_handle& h\n\t\t\t, const std::string& msg)\n\t\t\t: alert(alert::fatal, msg)\n\t\t\t, handle(h)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new file_error_alert(*this)); }\n\n\t\ttorrent_handle handle;\n\t};\n\n\tstruct listen_failed_alert: alert\n\t{\n\t\tlisten_failed_alert(\n\t\t\tconst std::string& msg)\n\t\t\t: alert(alert::fatal, msg)\n\t\t{}\n\n\t\tvirtual std::auto_ptr<alert> clone() const\n\t\t{ return std::auto_ptr<alert>(new listen_failed_alert(*this)); }\n\t};\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP\n#define MAPNIK_TEXT_SYMBOLIZER_HPP\n\n\/\/ mapnik\n#include <mapnik\/color.hpp>\n#include <mapnik\/font_set.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/text_placements.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ stl\n#include <string>\n\nnamespace mapnik\n{\n\nstruct MAPNIK_DECL text_symbolizer : public symbolizer_base\n{\n text_symbolizer(expression_ptr name, std::string const& face_name,\n float size, color const& fill,\n text_placements_ptr placements = boost::make_shared<text_placements_dummy>()\n );\n text_symbolizer(expression_ptr name, float size, color const& fill,\n text_placements_ptr placements = boost::make_shared<text_placements_dummy>()\n );\n text_symbolizer(text_symbolizer const& rhs);\n text_symbolizer& operator=(text_symbolizer const& rhs);\n expression_ptr get_name() const;\n void set_name(expression_ptr expr);\n\n expression_ptr get_orientation() const; \/\/ orienation (rotation angle atm)\n void set_orientation(expression_ptr expr);\n \n unsigned get_text_ratio() const; \/\/ target ratio for text bounding box in pixels\n void set_text_ratio(unsigned ratio);\n unsigned get_wrap_width() const; \/\/ width to wrap text at, or trigger ratio\n void set_wrap_width(unsigned ratio);\n unsigned char get_wrap_char() const; \/\/ character used to wrap lines\n std::string get_wrap_char_string() const; \/\/ character used to wrap lines as std::string\n void set_wrap_char(unsigned char character);\n void set_wrap_char_from_string(std::string const& character);\n text_transform_e get_text_transform() const; \/\/ text conversion on strings before display\n void set_text_transform(text_transform_e convert);\n unsigned get_line_spacing() const; \/\/ spacing between lines of text\n void set_line_spacing(unsigned spacing);\n unsigned get_character_spacing() const; \/\/ spacing between characters in text\n void set_character_spacing(unsigned spacing);\n unsigned get_label_spacing() const; \/\/ spacing between repeated labels on lines\n void set_label_spacing(unsigned spacing);\n unsigned get_label_position_tolerance() const; \/\/distance the label can be moved on the line to fit, if 0 the default is used\n void set_label_position_tolerance(unsigned tolerance);\n bool get_force_odd_labels() const; \/\/ try render an odd amount of labels\n void set_force_odd_labels(bool force);\n double get_max_char_angle_delta() const; \/\/ maximum change in angle between adjacent characters\n void set_max_char_angle_delta(double angle);\n float get_text_size() const;\n void set_text_size(float size);\n std::string const& get_face_name() const;\n void set_face_name(std::string face_name);\n font_set const& get_fontset() const;\n void set_fontset(font_set const& fset);\n color const& get_fill() const;\n void set_fill(color const& fill);\n void set_halo_fill(color const& fill);\n color const& get_halo_fill() const;\n void set_halo_radius(double radius);\n double get_halo_radius() const;\n void set_label_placement(label_placement_e label_p);\n label_placement_e get_label_placement() const;\n void set_vertical_alignment(vertical_alignment_e valign);\n vertical_alignment_e get_vertical_alignment() const;\n void set_anchor(double x, double y);\n position const& get_anchor() const;\n void set_displacement(double x, double y);\n void set_displacement(position const& p);\n position const& get_displacement() const;\n void set_avoid_edges(bool avoid);\n bool get_avoid_edges() const;\n void set_minimum_distance(double distance);\n double get_minimum_distance() const;\n void set_minimum_padding(double distance);\n double get_minimum_padding() const;\n void set_minimum_path_length(double size);\n double get_minimum_path_length() const;\n void set_allow_overlap(bool overlap);\n bool get_allow_overlap() const;\n void set_text_opacity(double opacity);\n double get_text_opacity() const;\n bool get_wrap_before() const; \/\/ wrap text at wrap_char immediately before current work\n void set_wrap_before(bool wrap_before);\n void set_horizontal_alignment(horizontal_alignment_e valign);\n horizontal_alignment_e get_horizontal_alignment() const;\n void set_justify_alignment(justify_alignment_e valign);\n justify_alignment_e get_justify_alignment() const;\n text_placements_ptr get_placement_options() const;\n void set_placement_options(text_placements_ptr placement_options);\n\nprivate:\n expression_ptr name_;\n expression_ptr orientation_;\n std::string face_name_;\n font_set fontset_;\n unsigned text_ratio_;\n unsigned wrap_width_;\n unsigned char wrap_char_;\n text_transform_e text_transform_;\n unsigned line_spacing_;\n unsigned character_spacing_;\n unsigned label_spacing_;\n unsigned label_position_tolerance_;\n bool force_odd_labels_;\n double max_char_angle_delta_;\n color fill_;\n color halo_fill_;\n double halo_radius_;\n label_placement_e label_p_;\n position anchor_;\n bool avoid_edges_;\n double minimum_distance_;\n double minimum_padding_;\n double minimum_path_length_;\n bool overlap_;\n double text_opacity_;\n bool wrap_before_;\n text_placements_ptr placement_options_;\n};\n}\n\n#endif \/\/ MAPNIK_TEXT_SYMBOLIZER_HPP\n<commit_msg>allow compile with msvs - make_shared is preferable but vs compiler cannot handle it<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP\n#define MAPNIK_TEXT_SYMBOLIZER_HPP\n\n\/\/ mapnik\n#include <mapnik\/color.hpp>\n#include <mapnik\/font_set.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/filter_factory.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/text_placements.hpp>\n\n\/\/ boost\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ stl\n#include <string>\n\nnamespace mapnik\n{\n\nstruct MAPNIK_DECL text_symbolizer : public symbolizer_base\n{\n \/\/ Note - we do not use boost::make_shared below as VC2010 is \n\t\/\/ not able to compile make_shared used within a constructor\n\ttext_symbolizer(expression_ptr name, std::string const& face_name,\n float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(expression_ptr name, float size, color const& fill,\n text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)\n );\n text_symbolizer(text_symbolizer const& rhs);\n text_symbolizer& operator=(text_symbolizer const& rhs);\n expression_ptr get_name() const;\n void set_name(expression_ptr expr);\n\n expression_ptr get_orientation() const; \/\/ orienation (rotation angle atm)\n void set_orientation(expression_ptr expr);\n \n unsigned get_text_ratio() const; \/\/ target ratio for text bounding box in pixels\n void set_text_ratio(unsigned ratio);\n unsigned get_wrap_width() const; \/\/ width to wrap text at, or trigger ratio\n void set_wrap_width(unsigned ratio);\n unsigned char get_wrap_char() const; \/\/ character used to wrap lines\n std::string get_wrap_char_string() const; \/\/ character used to wrap lines as std::string\n void set_wrap_char(unsigned char character);\n void set_wrap_char_from_string(std::string const& character);\n text_transform_e get_text_transform() const; \/\/ text conversion on strings before display\n void set_text_transform(text_transform_e convert);\n unsigned get_line_spacing() const; \/\/ spacing between lines of text\n void set_line_spacing(unsigned spacing);\n unsigned get_character_spacing() const; \/\/ spacing between characters in text\n void set_character_spacing(unsigned spacing);\n unsigned get_label_spacing() const; \/\/ spacing between repeated labels on lines\n void set_label_spacing(unsigned spacing);\n unsigned get_label_position_tolerance() const; \/\/distance the label can be moved on the line to fit, if 0 the default is used\n void set_label_position_tolerance(unsigned tolerance);\n bool get_force_odd_labels() const; \/\/ try render an odd amount of labels\n void set_force_odd_labels(bool force);\n double get_max_char_angle_delta() const; \/\/ maximum change in angle between adjacent characters\n void set_max_char_angle_delta(double angle);\n float get_text_size() const;\n void set_text_size(float size);\n std::string const& get_face_name() const;\n void set_face_name(std::string face_name);\n font_set const& get_fontset() const;\n void set_fontset(font_set const& fset);\n color const& get_fill() const;\n void set_fill(color const& fill);\n void set_halo_fill(color const& fill);\n color const& get_halo_fill() const;\n void set_halo_radius(double radius);\n double get_halo_radius() const;\n void set_label_placement(label_placement_e label_p);\n label_placement_e get_label_placement() const;\n void set_vertical_alignment(vertical_alignment_e valign);\n vertical_alignment_e get_vertical_alignment() const;\n void set_anchor(double x, double y);\n position const& get_anchor() const;\n void set_displacement(double x, double y);\n void set_displacement(position const& p);\n position const& get_displacement() const;\n void set_avoid_edges(bool avoid);\n bool get_avoid_edges() const;\n void set_minimum_distance(double distance);\n double get_minimum_distance() const;\n void set_minimum_padding(double distance);\n double get_minimum_padding() const;\n void set_minimum_path_length(double size);\n double get_minimum_path_length() const;\n void set_allow_overlap(bool overlap);\n bool get_allow_overlap() const;\n void set_text_opacity(double opacity);\n double get_text_opacity() const;\n bool get_wrap_before() const; \/\/ wrap text at wrap_char immediately before current work\n void set_wrap_before(bool wrap_before);\n void set_horizontal_alignment(horizontal_alignment_e valign);\n horizontal_alignment_e get_horizontal_alignment() const;\n void set_justify_alignment(justify_alignment_e valign);\n justify_alignment_e get_justify_alignment() const;\n text_placements_ptr get_placement_options() const;\n void set_placement_options(text_placements_ptr placement_options);\n\nprivate:\n expression_ptr name_;\n expression_ptr orientation_;\n std::string face_name_;\n font_set fontset_;\n unsigned text_ratio_;\n unsigned wrap_width_;\n unsigned char wrap_char_;\n text_transform_e text_transform_;\n unsigned line_spacing_;\n unsigned character_spacing_;\n unsigned label_spacing_;\n unsigned label_position_tolerance_;\n bool force_odd_labels_;\n double max_char_angle_delta_;\n color fill_;\n color halo_fill_;\n double halo_radius_;\n label_placement_e label_p_;\n position anchor_;\n bool avoid_edges_;\n double minimum_distance_;\n double minimum_padding_;\n double minimum_path_length_;\n bool overlap_;\n double text_opacity_;\n bool wrap_before_;\n text_placements_ptr placement_options_;\n};\n}\n\n#endif \/\/ MAPNIK_TEXT_SYMBOLIZER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#ifndef IMPL_CONTAINER_H\n#define IMPL_CONTAINER_H\n\n#include <memory>\n#include <vector>\n#include <list>\n#include <functional>\n\n#include <nix\/Platform.hpp> \/\/for pragma warnings on windows\n#include <nix\/None.hpp>\n#include <nix\/Exception.hpp>\n\nnamespace nix {\nnamespace base {\n\ntemplate<typename T>\nclass ImplContainer {\nprotected:\n\n std::shared_ptr<T> impl_ptr;\n\n \/**\n * Low level helper to get multiple entities via a getter function\n * that has to be provided.\n * \n * Get multiple entities of given type and return them as vector.\n * The template param specifies which type.\n * The parameter \"getEnt\" is the function used to get the entities \n * of given type T_ENT and has to be of return type T_ENT with \n * parameter \"size_t\" specifying the index of the entity to get.\n * The parameter \"nT\" should give the number of entities to get and\n * should be =>0 & <= the total number of existing entities.\n * The parameter \"filter\" is defaulted to giving back all entities \n * of given type. To use your own filter pass a lambda that accepts \n * an entity of given type as parameter and returns a bool telling \n * whether to get it or not.\n * NOTE: there is no need to specify 2nd template param TFUNC as it\n * should be automatically deduced.\n * \n * @param class \"get function\": std::function of return type T_ENT and \n * param type \"int\" to get entities\n * @param size_t number of entities to get\n * @param class \"filter function\": std::function of return type bool\n * and param type T_ENT to filter which entities to get\n * @return class entities of the given type as a vector\n *\/\n template<typename TENT, typename TFUNC>\n std::vector<TENT> getEntities(\n TFUNC const &getEntity,\n size_t nT,\n std::function<bool(TENT)> filter) const \n {\n std::vector<TENT> e;\n size_t i = 0;\n\n if(nT < 1) { return e; }\n e.resize(nT);\n\n for (typename std::vector<TENT>::iterator it = e.begin(); it!=e.end(); ++it) {\n if(filter(*it)) {\n *it = getEntity( i++ );\n }\n }\n\n return e;\n }\n \npublic:\n\n ImplContainer()\n : impl_ptr(nullptr)\n {\n }\n\n\n ImplContainer(T *p_impl)\n : impl_ptr(p_impl)\n {\n }\n\n\n ImplContainer(const std::shared_ptr<T> &p_impl)\n : impl_ptr(p_impl)\n {\n }\n\n\n ImplContainer(const ImplContainer<T> &other)\n : impl_ptr(other.impl_ptr)\n {\n }\n\n bool isNone() const {\n return !impl_ptr;\n }\n\n\n explicit operator bool() const {\n return !isNone();\n }\n\n\n virtual ImplContainer<T> &operator=(const ImplContainer<T> &other) {\n if (*this != other) {\n ImplContainer tmp(other);\n swap(tmp);\n }\n return *this;\n }\n\n\n virtual ImplContainer<T> &operator=(std::nullptr_t nullp) {\n impl_ptr = nullp;\n return *this;\n }\n\n\n virtual bool operator==(const ImplContainer<T> &other) const {\n return this->impl_ptr == other.impl_ptr;\n }\n\n\n virtual bool operator!=(const ImplContainer<T> &other) const {\n return !(*this == other);\n }\n\n \/\/ bool \"==\" operator \"boost::none_t\" overload: when an object\n \/\/ is compared to \"none_t\" (e.g. boost::none) internally we compare\n \/\/ the \"impl_ptr\" to the null pointer.\n virtual bool operator==(none_t t) const {\n return impl_ptr == nullptr;\n }\n\n \/\/ bool \"=!\" operator \"boost::none_t\" overload: same as \"==\" operator.\n virtual bool operator!=(none_t t) const {\n return impl_ptr != nullptr;\n }\n\n\n virtual void swap(ImplContainer<T> &second) {\n using std::swap;\n\n swap(impl_ptr, second.impl_ptr);\n }\n\n\n virtual ~ImplContainer() {}\n\n\n std::shared_ptr<T> impl() const {\n return impl_ptr;\n }\n\nprotected:\n T* backend() {\n if (isNone()) {\n throw std::runtime_error(\"Trying to access object with invalid object\");\n }\n\n return impl_ptr.get();\n }\n\n const T* backend() const {\n return const_cast<ImplContainer *>(this)->backend();\n }\n};\n\n\n} \/\/ namespace base\n} \/\/ namespace nix\n\n#endif\n<commit_msg>ImplContainer::nullify() new function to nullify the impl_ptr<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#ifndef IMPL_CONTAINER_H\n#define IMPL_CONTAINER_H\n\n#include <memory>\n#include <vector>\n#include <list>\n#include <functional>\n\n#include <nix\/Platform.hpp> \/\/for pragma warnings on windows\n#include <nix\/None.hpp>\n#include <nix\/Exception.hpp>\n\nnamespace nix {\nnamespace base {\n\ntemplate<typename T>\nclass ImplContainer {\nprotected:\n\n std::shared_ptr<T> impl_ptr;\n\n \/**\n * Low level helper to get multiple entities via a getter function\n * that has to be provided.\n * \n * Get multiple entities of given type and return them as vector.\n * The template param specifies which type.\n * The parameter \"getEnt\" is the function used to get the entities \n * of given type T_ENT and has to be of return type T_ENT with \n * parameter \"size_t\" specifying the index of the entity to get.\n * The parameter \"nT\" should give the number of entities to get and\n * should be =>0 & <= the total number of existing entities.\n * The parameter \"filter\" is defaulted to giving back all entities \n * of given type. To use your own filter pass a lambda that accepts \n * an entity of given type as parameter and returns a bool telling \n * whether to get it or not.\n * NOTE: there is no need to specify 2nd template param TFUNC as it\n * should be automatically deduced.\n * \n * @param class \"get function\": std::function of return type T_ENT and \n * param type \"int\" to get entities\n * @param size_t number of entities to get\n * @param class \"filter function\": std::function of return type bool\n * and param type T_ENT to filter which entities to get\n * @return class entities of the given type as a vector\n *\/\n template<typename TENT, typename TFUNC>\n std::vector<TENT> getEntities(\n TFUNC const &getEntity,\n size_t nT,\n std::function<bool(TENT)> filter) const \n {\n std::vector<TENT> e;\n size_t i = 0;\n\n if(nT < 1) { return e; }\n e.resize(nT);\n\n for (typename std::vector<TENT>::iterator it = e.begin(); it!=e.end(); ++it) {\n if(filter(*it)) {\n *it = getEntity( i++ );\n }\n }\n\n return e;\n }\n \npublic:\n\n ImplContainer()\n : impl_ptr(nullptr)\n {\n }\n\n\n ImplContainer(T *p_impl)\n : impl_ptr(p_impl)\n {\n }\n\n\n ImplContainer(const std::shared_ptr<T> &p_impl)\n : impl_ptr(p_impl)\n {\n }\n\n\n ImplContainer(const ImplContainer<T> &other)\n : impl_ptr(other.impl_ptr)\n {\n }\n\n bool isNone() const {\n return !impl_ptr;\n }\n\n\n explicit operator bool() const {\n return !isNone();\n }\n\n\n virtual ImplContainer<T> &operator=(const ImplContainer<T> &other) {\n if (*this != other) {\n ImplContainer tmp(other);\n swap(tmp);\n }\n return *this;\n }\n\n\n virtual ImplContainer<T> &operator=(std::nullptr_t nullp) {\n impl_ptr = nullp;\n return *this;\n }\n\n\n virtual bool operator==(const ImplContainer<T> &other) const {\n return this->impl_ptr == other.impl_ptr;\n }\n\n\n virtual bool operator!=(const ImplContainer<T> &other) const {\n return !(*this == other);\n }\n\n \/\/ bool \"==\" operator \"boost::none_t\" overload: when an object\n \/\/ is compared to \"none_t\" (e.g. boost::none) internally we compare\n \/\/ the \"impl_ptr\" to the null pointer.\n virtual bool operator==(none_t t) const {\n return impl_ptr == nullptr;\n }\n\n \/\/ bool \"=!\" operator \"boost::none_t\" overload: same as \"==\" operator.\n virtual bool operator!=(none_t t) const {\n return impl_ptr != nullptr;\n }\n\n\n virtual void swap(ImplContainer<T> &second) {\n using std::swap;\n\n swap(impl_ptr, second.impl_ptr);\n }\n\n\n virtual ~ImplContainer() {}\n\n\n std::shared_ptr<T> impl() const {\n return impl_ptr;\n }\n\nprotected:\n T* backend() {\n if (isNone()) {\n throw std::runtime_error(\"Trying to access object with invalid object\");\n }\n\n return impl_ptr.get();\n }\n\n const T* backend() const {\n return const_cast<ImplContainer *>(this)->backend();\n }\n\n void nullify() {\n impl_ptr = nullptr;\n }\n};\n\n\n} \/\/ namespace base\n} \/\/ namespace nix\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include <sstream>\nusing namespace std;\n\n#include <PLCM.hpp>\n\n#include <internals\/Counters.hpp>\n#include <internals\/Dataset.hpp>\n#include <internals\/ExplorationStep.hpp>\n#include <io\/MultiThreadedFileCollector.hpp>\n#include <io\/NullCollector.hpp>\n#include <io\/PatternSortCollector.hpp>\n#include <io\/StdOutCollector.hpp>\n#include <util\/MemoryPeakWatcherThread.hpp>\n#include <util\/ProgressWatcherThread.hpp>\n#include <util\/Helpers.h>\n\nusing namespace util;\nusing namespace io;\n\nunique_ptr<PLCM::thread_map> PLCM::threads = nullptr;\n\nPLCM::PLCM(struct Options *options) {\n\tuint32_t nbThreads = options->num_threads;\n\tif (nbThreads < 1) {\n\t\tcerr << \"nbThreads has to be > 0, given \" << nbThreads <<\n\t\t\t\t\". Aborting.\";\n\t\texit(EXIT_FAILURE);\n\t}\n\tcollector = instanciateCollector(options);\n\tthreads = unique_ptr<thread_map>(new thread_map());\n\tcreateThreads(nbThreads);\n\tprogressWatch = unique_ptr<ProgressWatcherThread>(\n\t\t\tnew ProgressWatcherThread());\n\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\t\t\tglobalCounters[i] = 0;\n\t}\n}\n\nPLCM::~PLCM() {\n}\n\nvoid PLCM::collect(int32_t support, vector<int32_t>* pattern) {\n\tcollector->collect(support, pattern);\n}\n\nvoid PLCM::lcm(shared_ptr<ExplorationStep> initState) {\n\tif (initState->pattern->size() > 0) {\n\t\tcollector->collect(\n\t\t\t\tinitState->counters->transactionsCount,\n\t\t\t\tinitState->pattern.get());\n\t}\n\n\tprogressWatch->setInitState(initState);\n\n\tinitializeAndStartThreads(initState);\n\n\tprogressWatch->start();\n\n\tfor (auto it = threads->begin(); it != threads->end(); ++it) {\n\t\tauto t = it->second.get();\n\t\tt->join();\n\t\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\t\tglobalCounters[i] += t->counters[i];\n\t\t}\n\t}\n\n\tprogressWatch->stop();\n}\n\nvoid PLCM::display(ostream& stream,\n\t\tmap<string, uint64_t>* additionalcounters) {\n\tstream << \"{\\\"name\\\":\\\"PLCM\\\", \\\"threads\\\":\" << threads->size();\n\n\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\tstream << \", \\\"\" << PLCMCountersNames[(PLCMCounters)i] <<\n\t\t\t\t\"\\\":\" << globalCounters[i];\n\t}\n\n\tif (additionalcounters != nullptr) {\n\t\tfor (auto entry : (*additionalcounters)) {\n\t\t\tstream << \", \\\"\" << entry.first << \"\\\":\" << entry.second;\n\t\t}\n\t}\n\n\tstream << \"}\" << endl;\n}\n\nint64_t PLCM::closeCollector() {\n\treturn collector->close();\n}\n\nint32_t PLCM::getAveragePatternLength() {\n\treturn collector->getAveragePatternLength();\n}\n\nuint32_t PLCM::getDefaultNumThreads() {\n\tunsigned concurentThreadsSupported = thread::hardware_concurrency();\n\tif (concurentThreadsSupported == 0)\n\t{\n\t\tcerr << \"Warning: could not get the number of concurrent threads supported\"\n\t\t\t\t\" by your system.\" << endl;\n\t\tconcurentThreadsSupported = 4;\n\t}\n\telse\n\t{\n\t cout << \"Info: your system supports \" << concurentThreadsSupported <<\n\t \t\t\" concurrent threads.\" << endl;\n\t}\n\n\treturn concurentThreadsSupported;\n}\n\nint PLCM::main(int argc, char** argv) {\n\n\tuint32_t default_num_threads = getDefaultNumThreads();\n\n\tTCLAP::CmdLine cmd(\"Parallel LCM, C++ implementation.\");\n\n\tTCLAP::SwitchArg benchmark_mode(\"b\",\"benchmark\",\n\t\t\t\"Benchmark mode: patterns are not outputted at \"\n\t\t\t\"all (in which case OUTPUT_PATH is ignored)\", cmd);\n\tTCLAP::SwitchArg memory_usage(\"m\",\"mem-usage\",\n\t\t\t\"Give peak memory usage after mining \"\n\t\t\t\"(instanciates a periodic watcher thread)\", cmd);\n\tTCLAP::SwitchArg sort_items(\"s\", \"sort-items\",\n\t\t\t\"Sort items in outputted patterns, in ascending order\", cmd);\n\tostringstream oss_explain;\n\toss_explain << \"How many threads will be launched (defaults to \" <<\n\t\tdefault_num_threads << \")\";\n\tTCLAP::ValueArg<uint32_t> num_threads(\"t\", \"num-threads\",\n\t\t\toss_explain.str(), false, default_num_threads,\n\t\t\t\"num_threads\", cmd);\n\tTCLAP::SwitchArg verbose(\"v\", \"verbose\",\n\t\t\t\"Enable verbose mode, which logs every extension \"\n\t\t\t\"of the empty pattern\", cmd);\n\tTCLAP::SwitchArg ultra_verbose(\"V\", \"ultra-verbose\",\n\t\t\t\"Enable ultra-verbose mode, which logs every pattern extension\"\n\t\t\t\" (use with care: it may produce a LOT of output)\", cmd);\n\tTCLAP::UnlabeledValueArg<string> input_path(\"INPUT_PATH\",\n\t\t\t\"The path of the file to mine into.\", true, \"None\", \"in_file\", cmd);\n\tTCLAP::UnlabeledValueArg<uint32_t> minsup(\"MINSUP\",\n\t\t\t\"The minimum support of items.\", true, 10, \"min_support\", cmd);\n\tTCLAP::UnlabeledValueArg<string> output_path(\"OUTPUT_PATH\",\n\t\t\t\"The path of the file where results should be dumped \"\n\t\t\t\"(defaults to standard output).\", false, \"-\", \"out_file\", cmd);\n\n\t\/\/ Parse the argv array\t(will exit if invalid)\n\tcmd.parse( argc, argv );\n\n\tunique_ptr<PLCM::Options> options(new PLCM::Options {\n\t\t\tbenchmark_mode.getValue(),\n\t\t\tmemory_usage.getValue(),\n\t\t\tsort_items.getValue(),\n\t\t\tnum_threads.getValue(),\n\t\t\tverbose.getValue(),\n\t\t\tultra_verbose.getValue(),\n\t\t\tinput_path.getValue(),\n\t\t\tminsup.getValue(),\n\t\t\toutput_path.getValue()\n\t});\n\n\t\/\/ run the main procedure\n\tstandalone(move(options) \/* transfer ownership *\/);\n\treturn 0;\n}\n\nvoid PLCM::standalone(unique_ptr<PLCM::Options> options) {\n\tunique_ptr<MemoryPeakWatcherThread> memoryWatch = nullptr;\n\n\tif (options->memory_usage) {\n\t\tmemoryWatch = unique_ptr<MemoryPeakWatcherThread>(\n\t\t\t\tnew MemoryPeakWatcherThread());\n\t\tmemoryWatch->start();\n\t}\n\n\tif (options->ultra_verbose)\n\t{\n\t\tExplorationStep::verbose = true;\n\t\tExplorationStep::ultraVerbose = true;\n\t}\n\telse\n\t{\n\t\tExplorationStep::verbose = options->verbose;\n\t}\n\n\tdouble chrono = Helpers::precise_time();\n\tshared_ptr<ExplorationStep> initState = make_shared<ExplorationStep>(\n\t\t\toptions->minsup, options->input_path);\n\tdouble loadingTime = Helpers::precise_time() - chrono;\n\tcerr << \"Dataset loaded in \" << loadingTime << \"s\" << endl;\n\n\tunique_ptr<PLCM> miner(new PLCM(options.get()));\n\n\tchrono = Helpers::precise_time();\n\tminer->lcm(initState);\n\tchrono = Helpers::precise_time() - chrono;\n\n\tunique_ptr<map<string, uint64_t> > additionalcounters(\n\t\t\tnew map<string, uint64_t>());\n\t(*additionalcounters)[\"miningTime\"] = chrono*1000 \/* milliseconds *\/;\n\t(*additionalcounters)[\"outputtedPatterns\"] = miner->closeCollector();\n\t(*additionalcounters)[\"loadingTime\"] = loadingTime*1000 \/* milliseconds *\/;\n\t(*additionalcounters)[\"avgPatternLength\"] =\n\t\t\t(uint64_t) miner->getAveragePatternLength();\n\n\tif (memoryWatch != nullptr) {\n\t\tmemoryWatch->stop();\n\t\t(*additionalcounters)[\"maxUsedMemory\"] = memoryWatch->getMaxUsedMemory();\n\t}\n\n\tminer->display(cerr, additionalcounters.get());\n}\n\nPLCMThread* PLCM::getCurrentThread() {\n\treturn (*threads)[this_thread::get_id()].get();\n}\n\nvoid PLCM::createThreads(int32_t nbThreads) {\n\tcpu_set_t cpu_set;\n\tsched_getaffinity(0, sizeof(cpu_set_t), &cpu_set);\n\tint num_cpus = CPU_COUNT(&cpu_set);\n\tint index_cpu;\n\n\tfor (int i = 0; i < nbThreads; i++) {\n\t\tindex_cpu = i%num_cpus;\n\t\tauto t = new PLCMThread(this, index_cpu);\n\t\t(*threads)[t->getId()] = unique_ptr<PLCMThread>(t);\n\t}\n}\n\nvoid PLCM::initializeAndStartThreads(shared_ptr<ExplorationStep> initState) {\n\tfor (auto it = threads->begin(); it != threads->end(); ++it) {\n\t\tit->second->init(initState);\n\t\tit->second->start();\n\t}\n}\n\nshared_ptr<ExplorationStep> PLCM::stealJob(PLCMThread* thief) {\n\tfor (auto it = threads->begin(); it != threads->end(); ++it) {\n\t\tauto victim = it->second.get();\n\t\tif (victim != thief) {\n\t\t\tauto e = victim->giveJob(thief);\n\t\t\tif (e != nullptr) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nunique_ptr<PatternsCollector> PLCM::instanciateCollector(PLCM::Options *options) {\n\tPatternsCollector* collector = nullptr;\n\n\tif (options->benchmark_mode) {\n\t\tcollector = new NullCollector();\n\t} else {\n\t\tif (options->output_path != \"-\") {\n\t\t\tcollector = new MultiThreadedFileCollector(\n\t\t\t\t\t\toptions->output_path);\n\t\t} else {\n\t\t\tcollector = new StdOutCollector();\n\t\t}\n\n\t\tif (options->sort_items) {\n\t\t\tcollector = new PatternSortCollector(collector);\n\t\t}\n\t}\n\n\treturn unique_ptr<PatternsCollector>(collector);\n}\n\nPLCMThread::PLCMThread(PLCM* PLCM_instance, int index_cpu) {\n\tstackedJobs = new vector<shared_ptr<ExplorationStep> >();\n\tstackedJobs_storage = unique_ptr<vector<shared_ptr<ExplorationStep> > >(\n\t\t\tstackedJobs); \/\/ auto delete\n\n\t_PLCM_instance = PLCM_instance;\n\t_index_cpu = index_cpu;\n\tshould_start = false; \/\/ wait for the signal\n\t_thread = new thread(&PLCMThread::run, this);\n\t_thread_storage = unique_ptr<thread>(_thread); \/\/ auto delete\n\tfor (uint i = 0; i < PLCM::PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\tcounters[i] = 0;\n\t}\n}\n\nthread::id PLCMThread::getId() {\n\treturn _thread->get_id();\n}\n\nvoid PLCMThread::run() {\n\t\/\/ 1st, set the thread affinity\n\tcpu_set_t cpu_set;\n\tCPU_ZERO(&cpu_set);\n\tCPU_SET(_index_cpu, &cpu_set);\n\tsched_setaffinity(0, sizeof(cpu_set_t), &cpu_set);\n\n\t\/\/ then, wait for the start condition\n\t{\n\t\tunique_lock<mutex> ul(starting_mutex);\n\t\twhile (!should_start)\t\/\/ handle spurious wake-ups\n\t\t{\n\t\t\tcond_should_start.wait(ul);\n\t\t}\n\t}\n\n\t\/\/ no need to readlock, this thread is the only one that can do\n\t\/\/ writes\n\tbool exit = false;\n\twhile (!exit) {\n\t\tExplorationStep *sj = nullptr;\n\t\tif (!stackedJobs->empty()) {\n\t\t\tsj = stackedJobs->back().get();\n\n\t\t\tunique_ptr<ExplorationStep> extended = sj->next();\n\t\t\t\/\/ iterator is finished, remove it from the stack\n\t\t\tif (extended == nullptr) {\n\t\t\t\tReadWriteLock::WriteGuard lg(_lock);\n\t\t\t\tstackedJobs->pop_back();\n\t\t\t\tcounters[PLCM::PLCMCounters::ExplorationStepInstances]++;\n\t\t\t\tcounters[PLCM::PLCMCounters::ExplorationStepCatchedWrongFirstParents] +=\n\t\t\t\t\t\tsj->getCatchedWrongFirstParentCount();\n\t\t\t} else {\n\t\t\t\tlcm(move(extended) \/* transfer ownership *\/);\n\t\t\t}\n\t\t} else { \/\/ our list was empty, we should steal from another\n\t\t\t\t\t\/\/ thread\n\t\t\tshared_ptr<ExplorationStep> stolj = _PLCM_instance->stealJob(this);\n\t\t\tif (stolj == nullptr) {\n\t\t\t\texit = true;\n\t\t\t} else {\n\t\t\t\tlcm(stolj);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid PLCMThread::init(shared_ptr<ExplorationStep> initState) {\n\tReadWriteLock::WriteGuard lg(_lock);\n\tstackedJobs->push_back(initState);\n}\n\nvoid PLCMThread::join() {\n\t_thread->join();\n}\n\nvoid PLCMThread::start() {\n\t{\n\t\tlock_guard<mutex> lg(starting_mutex);\n\t\tshould_start = true;\n\t}\n\tcond_should_start.notify_one();\n}\n\nvoid PLCMThread::lcm(shared_ptr<ExplorationStep> state) {\n\t_PLCM_instance->collect(\n\t\t\tstate->counters->transactionsCount,\n\t\t\tstate->pattern.get());\n\t{\n\t\tReadWriteLock::WriteGuard lg(_lock);\n\t\tstackedJobs->push_back(state);\n\t}\n}\n\nshared_ptr<ExplorationStep> PLCMThread::giveJob(PLCMThread* thief) {\n\t\/\/ here we need to readlock because the owner thread can write\n\tReadWriteLock::ReadGuard lg(_lock);\n\tfor (uint32_t stealPos = 0; stealPos < stackedJobs->size(); stealPos++) {\n\t\tshared_ptr<ExplorationStep> sj = stackedJobs->at(stealPos);\n\t\tshared_ptr<ExplorationStep> next = Helpers::unique_to_shared(sj->next());\n\n\t\tif (next != nullptr) {\n\t\t\tthief->init(sj);\n\t\t\treturn next;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\n<commit_msg>Reduce concurrency when stealing jobs.<commit_after>\n#include <sstream>\nusing namespace std;\n\n#include <PLCM.hpp>\n\n#include <internals\/Counters.hpp>\n#include <internals\/Dataset.hpp>\n#include <internals\/ExplorationStep.hpp>\n#include <io\/MultiThreadedFileCollector.hpp>\n#include <io\/NullCollector.hpp>\n#include <io\/PatternSortCollector.hpp>\n#include <io\/StdOutCollector.hpp>\n#include <util\/MemoryPeakWatcherThread.hpp>\n#include <util\/ProgressWatcherThread.hpp>\n#include <util\/Helpers.h>\n\nusing namespace util;\nusing namespace io;\n\nunique_ptr<PLCM::thread_map> PLCM::threads = nullptr;\n\nPLCM::PLCM(struct Options *options) {\n\tuint32_t nbThreads = options->num_threads;\n\tif (nbThreads < 1) {\n\t\tcerr << \"nbThreads has to be > 0, given \" << nbThreads <<\n\t\t\t\t\". Aborting.\";\n\t\texit(EXIT_FAILURE);\n\t}\n\tcollector = instanciateCollector(options);\n\tthreads = unique_ptr<thread_map>(new thread_map());\n\tcreateThreads(nbThreads);\n\tprogressWatch = unique_ptr<ProgressWatcherThread>(\n\t\t\tnew ProgressWatcherThread());\n\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\t\t\tglobalCounters[i] = 0;\n\t}\n}\n\nPLCM::~PLCM() {\n}\n\nvoid PLCM::collect(int32_t support, vector<int32_t>* pattern) {\n\tcollector->collect(support, pattern);\n}\n\nvoid PLCM::lcm(shared_ptr<ExplorationStep> initState) {\n\tif (initState->pattern->size() > 0) {\n\t\tcollector->collect(\n\t\t\t\tinitState->counters->transactionsCount,\n\t\t\t\tinitState->pattern.get());\n\t}\n\n\tprogressWatch->setInitState(initState);\n\n\tinitializeAndStartThreads(initState);\n\n\tprogressWatch->start();\n\n\tfor (auto it = threads->begin(); it != threads->end(); ++it) {\n\t\tauto t = it->second.get();\n\t\tt->join();\n\t\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\t\tglobalCounters[i] += t->counters[i];\n\t\t}\n\t}\n\n\tprogressWatch->stop();\n}\n\nvoid PLCM::display(ostream& stream,\n\t\tmap<string, uint64_t>* additionalcounters) {\n\tstream << \"{\\\"name\\\":\\\"PLCM\\\", \\\"threads\\\":\" << threads->size();\n\n\tfor (uint i = 0; i < PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\tstream << \", \\\"\" << PLCMCountersNames[(PLCMCounters)i] <<\n\t\t\t\t\"\\\":\" << globalCounters[i];\n\t}\n\n\tif (additionalcounters != nullptr) {\n\t\tfor (auto entry : (*additionalcounters)) {\n\t\t\tstream << \", \\\"\" << entry.first << \"\\\":\" << entry.second;\n\t\t}\n\t}\n\n\tstream << \"}\" << endl;\n}\n\nint64_t PLCM::closeCollector() {\n\treturn collector->close();\n}\n\nint32_t PLCM::getAveragePatternLength() {\n\treturn collector->getAveragePatternLength();\n}\n\nuint32_t PLCM::getDefaultNumThreads() {\n\tunsigned concurentThreadsSupported = thread::hardware_concurrency();\n\tif (concurentThreadsSupported == 0)\n\t{\n\t\tcerr << \"Warning: could not get the number of concurrent threads supported\"\n\t\t\t\t\" by your system.\" << endl;\n\t\tconcurentThreadsSupported = 4;\n\t}\n\telse\n\t{\n\t cout << \"Info: your system supports \" << concurentThreadsSupported <<\n\t \t\t\" concurrent threads.\" << endl;\n\t}\n\n\treturn concurentThreadsSupported;\n}\n\nint PLCM::main(int argc, char** argv) {\n\n\tuint32_t default_num_threads = getDefaultNumThreads();\n\n\tTCLAP::CmdLine cmd(\"Parallel LCM, C++ implementation.\");\n\n\tTCLAP::SwitchArg benchmark_mode(\"b\",\"benchmark\",\n\t\t\t\"Benchmark mode: patterns are not outputted at \"\n\t\t\t\"all (in which case OUTPUT_PATH is ignored)\", cmd);\n\tTCLAP::SwitchArg memory_usage(\"m\",\"mem-usage\",\n\t\t\t\"Give peak memory usage after mining \"\n\t\t\t\"(instanciates a periodic watcher thread)\", cmd);\n\tTCLAP::SwitchArg sort_items(\"s\", \"sort-items\",\n\t\t\t\"Sort items in outputted patterns, in ascending order\", cmd);\n\tostringstream oss_explain;\n\toss_explain << \"How many threads will be launched (defaults to \" <<\n\t\tdefault_num_threads << \")\";\n\tTCLAP::ValueArg<uint32_t> num_threads(\"t\", \"num-threads\",\n\t\t\toss_explain.str(), false, default_num_threads,\n\t\t\t\"num_threads\", cmd);\n\tTCLAP::SwitchArg verbose(\"v\", \"verbose\",\n\t\t\t\"Enable verbose mode, which logs every extension \"\n\t\t\t\"of the empty pattern\", cmd);\n\tTCLAP::SwitchArg ultra_verbose(\"V\", \"ultra-verbose\",\n\t\t\t\"Enable ultra-verbose mode, which logs every pattern extension\"\n\t\t\t\" (use with care: it may produce a LOT of output)\", cmd);\n\tTCLAP::UnlabeledValueArg<string> input_path(\"INPUT_PATH\",\n\t\t\t\"The path of the file to mine into.\", true, \"None\", \"in_file\", cmd);\n\tTCLAP::UnlabeledValueArg<uint32_t> minsup(\"MINSUP\",\n\t\t\t\"The minimum support of items.\", true, 10, \"min_support\", cmd);\n\tTCLAP::UnlabeledValueArg<string> output_path(\"OUTPUT_PATH\",\n\t\t\t\"The path of the file where results should be dumped \"\n\t\t\t\"(defaults to standard output).\", false, \"-\", \"out_file\", cmd);\n\n\t\/\/ Parse the argv array\t(will exit if invalid)\n\tcmd.parse( argc, argv );\n\n\tunique_ptr<PLCM::Options> options(new PLCM::Options {\n\t\t\tbenchmark_mode.getValue(),\n\t\t\tmemory_usage.getValue(),\n\t\t\tsort_items.getValue(),\n\t\t\tnum_threads.getValue(),\n\t\t\tverbose.getValue(),\n\t\t\tultra_verbose.getValue(),\n\t\t\tinput_path.getValue(),\n\t\t\tminsup.getValue(),\n\t\t\toutput_path.getValue()\n\t});\n\n\t\/\/ run the main procedure\n\tstandalone(move(options) \/* transfer ownership *\/);\n\treturn 0;\n}\n\nvoid PLCM::standalone(unique_ptr<PLCM::Options> options) {\n\tunique_ptr<MemoryPeakWatcherThread> memoryWatch = nullptr;\n\n\tif (options->memory_usage) {\n\t\tmemoryWatch = unique_ptr<MemoryPeakWatcherThread>(\n\t\t\t\tnew MemoryPeakWatcherThread());\n\t\tmemoryWatch->start();\n\t}\n\n\tif (options->ultra_verbose)\n\t{\n\t\tExplorationStep::verbose = true;\n\t\tExplorationStep::ultraVerbose = true;\n\t}\n\telse\n\t{\n\t\tExplorationStep::verbose = options->verbose;\n\t}\n\n\tdouble chrono = Helpers::precise_time();\n\tshared_ptr<ExplorationStep> initState = make_shared<ExplorationStep>(\n\t\t\toptions->minsup, options->input_path);\n\tdouble loadingTime = Helpers::precise_time() - chrono;\n\tcerr << \"Dataset loaded in \" << loadingTime << \"s\" << endl;\n\n\tunique_ptr<PLCM> miner(new PLCM(options.get()));\n\n\tchrono = Helpers::precise_time();\n\tminer->lcm(initState);\n\tchrono = Helpers::precise_time() - chrono;\n\n\tunique_ptr<map<string, uint64_t> > additionalcounters(\n\t\t\tnew map<string, uint64_t>());\n\t(*additionalcounters)[\"miningTime\"] = chrono*1000 \/* milliseconds *\/;\n\t(*additionalcounters)[\"outputtedPatterns\"] = miner->closeCollector();\n\t(*additionalcounters)[\"loadingTime\"] = loadingTime*1000 \/* milliseconds *\/;\n\t(*additionalcounters)[\"avgPatternLength\"] =\n\t\t\t(uint64_t) miner->getAveragePatternLength();\n\n\tif (memoryWatch != nullptr) {\n\t\tmemoryWatch->stop();\n\t\t(*additionalcounters)[\"maxUsedMemory\"] = memoryWatch->getMaxUsedMemory();\n\t}\n\n\tminer->display(cerr, additionalcounters.get());\n}\n\nPLCMThread* PLCM::getCurrentThread() {\n\treturn (*threads)[this_thread::get_id()].get();\n}\n\nvoid PLCM::createThreads(int32_t nbThreads) {\n\tcpu_set_t cpu_set;\n\tsched_getaffinity(0, sizeof(cpu_set_t), &cpu_set);\n\tint num_cpus = CPU_COUNT(&cpu_set);\n\tint index_cpu;\n\n\tfor (int i = 0; i < nbThreads; i++) {\n\t\tindex_cpu = i%num_cpus;\n\t\tauto t = new PLCMThread(this, index_cpu);\n\t\t(*threads)[t->getId()] = unique_ptr<PLCMThread>(t);\n\t}\n}\n\nvoid PLCM::initializeAndStartThreads(shared_ptr<ExplorationStep> initState) {\n\tfor (auto it = threads->begin(); it != threads->end(); ++it) {\n\t\tit->second->init(initState);\n\t\tit->second->start();\n\t}\n}\n\nshared_ptr<ExplorationStep> PLCM::stealJob(PLCMThread* thief) {\n\n\t\/* we try to avoid too much concurrency, with all thread trying\n\t * to steal jobs to the same victim.\n\t *\n\t * For example, thread 3 will preferably steal a job to thread 4,\n\t * or 5, or 6, ... or N, or 0, or 1, or 2.\n\t *\/\n\n\tconst thread::id thief_id = thief->getId();\n\n\t\/\/ point to the thread following the thief\n\tauto it = threads->begin();\n\tfor (; it->first != thief_id; ++it) { }\n\t++it;\n\n\t\/\/ the thief can steal a job to any thread except itself\n\tsize_t num_stealable_threads = threads->size() -1;\n\n\t\/\/ try each thread pointed by it, in turn\n\tfor (size_t index = 0; index < num_stealable_threads; ++index) {\n\t\tif (it == threads->end())\n\t\t\tit = threads->begin();\n\t\tauto job = it->second->giveJob(thief);\n\t\tif (job != nullptr) {\n\t\t\t\/\/cout << \"Job stolen: thread \" << it->second->getId()\n\t\t\t\/\/\t\t<< \" to \" << thief_id << endl;\n\t\t\treturn job;\n\t\t}\n\n\t\t++it;\n\t}\n\treturn nullptr;\n}\n\nunique_ptr<PatternsCollector> PLCM::instanciateCollector(PLCM::Options *options) {\n\tPatternsCollector* collector = nullptr;\n\n\tif (options->benchmark_mode) {\n\t\tcollector = new NullCollector();\n\t} else {\n\t\tif (options->output_path != \"-\") {\n\t\t\tcollector = new MultiThreadedFileCollector(\n\t\t\t\t\t\toptions->output_path);\n\t\t} else {\n\t\t\tcollector = new StdOutCollector();\n\t\t}\n\n\t\tif (options->sort_items) {\n\t\t\tcollector = new PatternSortCollector(collector);\n\t\t}\n\t}\n\n\treturn unique_ptr<PatternsCollector>(collector);\n}\n\nPLCMThread::PLCMThread(PLCM* PLCM_instance, int index_cpu) {\n\tstackedJobs = new vector<shared_ptr<ExplorationStep> >();\n\tstackedJobs_storage = unique_ptr<vector<shared_ptr<ExplorationStep> > >(\n\t\t\tstackedJobs); \/\/ auto delete\n\n\t_PLCM_instance = PLCM_instance;\n\t_index_cpu = index_cpu;\n\tshould_start = false; \/\/ wait for the signal\n\t_thread = new thread(&PLCMThread::run, this);\n\t_thread_storage = unique_ptr<thread>(_thread); \/\/ auto delete\n\tfor (uint i = 0; i < PLCM::PLCMCounters::Number_of_PLCMCounters; ++i) {\n\t\tcounters[i] = 0;\n\t}\n}\n\nthread::id PLCMThread::getId() {\n\treturn _thread->get_id();\n}\n\nvoid PLCMThread::run() {\n\t\/\/ 1st, set the thread affinity\n\tcpu_set_t cpu_set;\n\tCPU_ZERO(&cpu_set);\n\tCPU_SET(_index_cpu, &cpu_set);\n\tsched_setaffinity(0, sizeof(cpu_set_t), &cpu_set);\n\n\t\/\/ then, wait for the start condition\n\t{\n\t\tunique_lock<mutex> ul(starting_mutex);\n\t\twhile (!should_start)\t\/\/ handle spurious wake-ups\n\t\t{\n\t\t\tcond_should_start.wait(ul);\n\t\t}\n\t}\n\n\t\/\/ no need to readlock, this thread is the only one that can do\n\t\/\/ writes\n\tbool exit = false;\n\twhile (!exit) {\n\t\tExplorationStep *sj = nullptr;\n\t\tif (!stackedJobs->empty()) {\n\t\t\tsj = stackedJobs->back().get();\n\n\t\t\tunique_ptr<ExplorationStep> extended = sj->next();\n\t\t\t\/\/ iterator is finished, remove it from the stack\n\t\t\tif (extended == nullptr) {\n\t\t\t\tReadWriteLock::WriteGuard lg(_lock);\n\t\t\t\tstackedJobs->pop_back();\n\t\t\t\tcounters[PLCM::PLCMCounters::ExplorationStepInstances]++;\n\t\t\t\tcounters[PLCM::PLCMCounters::ExplorationStepCatchedWrongFirstParents] +=\n\t\t\t\t\t\tsj->getCatchedWrongFirstParentCount();\n\t\t\t} else {\n\t\t\t\tlcm(move(extended) \/* transfer ownership *\/);\n\t\t\t}\n\t\t} else { \/\/ our list was empty, we should steal from another\n\t\t\t\t\t\/\/ thread\n\t\t\tshared_ptr<ExplorationStep> stolj = _PLCM_instance->stealJob(this);\n\t\t\tif (stolj == nullptr) {\n\t\t\t\texit = true;\n\t\t\t} else {\n\t\t\t\tlcm(stolj);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid PLCMThread::init(shared_ptr<ExplorationStep> initState) {\n\tReadWriteLock::WriteGuard lg(_lock);\n\tstackedJobs->push_back(initState);\n}\n\nvoid PLCMThread::join() {\n\t_thread->join();\n}\n\nvoid PLCMThread::start() {\n\t{\n\t\tlock_guard<mutex> lg(starting_mutex);\n\t\tshould_start = true;\n\t}\n\tcond_should_start.notify_one();\n}\n\nvoid PLCMThread::lcm(shared_ptr<ExplorationStep> state) {\n\t_PLCM_instance->collect(\n\t\t\tstate->counters->transactionsCount,\n\t\t\tstate->pattern.get());\n\t{\n\t\tReadWriteLock::WriteGuard lg(_lock);\n\t\tstackedJobs->push_back(state);\n\t}\n}\n\nshared_ptr<ExplorationStep> PLCMThread::giveJob(PLCMThread* thief) {\n\t\/\/ here we need to readlock because the owner thread can write\n\tReadWriteLock::ReadGuard lg(_lock);\n\tfor (uint32_t stealPos = 0; stealPos < stackedJobs->size(); stealPos++) {\n\t\tshared_ptr<ExplorationStep> sj = stackedJobs->at(stealPos);\n\t\tshared_ptr<ExplorationStep> next = Helpers::unique_to_shared(sj->next());\n\n\t\tif (next != nullptr) {\n\t\t\tthief->init(sj);\n\t\t\treturn next;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <type_traits>\n#include <std\/experimental\/tagged.hpp>\n\nnamespace named_types {\n\n\/\/ String literals, GNU Extension only\n#ifdef __GNUG__\ntemplate <typename T, T ... chars> class string_literal {\n const char data_[sizeof ... (chars) + 1u];\n const size_t size_;\n public:\n constexpr string_literal() : data_ {chars..., '\\0'}, size_(sizeof ... (chars)) {}\n constexpr char const* str() const { return data_; }\n constexpr size_t size() const { return size_; }\n constexpr char operator[] (size_t index) const { return data_[index]; }\n};\n#endif \/\/ __GNUG__\n\n\/\/ Traits for compile time name extraction\n\ntemplate<typename T> class has_user_defined_name {\n template <typename TT> static auto test(int) -> decltype(TT::classname);\n template <typename TT> static auto test(int) -> decltype(TT::name);\n template <typename TT> static auto test(int) -> decltype(TT::classname());\n template <typename TT> static auto test(int) -> decltype(TT::name());\n template <typename TT> static auto test(...) -> void;\n public:\n static constexpr bool value = std::is_same<decltype(test<T>(0)),char const *>::value;\n};\n\ntemplate<typename T> class constexpr_type_name {\n template <typename TT> static inline constexpr auto extract(int) -> decltype(TT::classname) { return TT::classname; }\n template <typename TT> static inline constexpr auto extract(int) -> decltype(TT::name) { return TT::name; }\n template <typename TT> static inline constexpr auto extract(int) -> decltype(TT::classname()) { return TT::classname(); }\n template <typename TT> static inline constexpr auto extract(int) -> decltype(TT::name()) { return TT::name(); }\n public:\n static constexpr char const* value = extract<T>();\n};\n\n\/\/ Name extractors specified to work with string literals\n#ifdef __GNUG__\ntemplate<typename T, T... chars> class has_user_defined_name<string_literal<T,chars...>> {\n public:\n static constexpr bool value = true;\n};\n\ntemplate<typename T, T... chars> class constexpr_type_name <string_literal<T,chars...>> {\n static const string_literal<T,chars...> literal_value;\n public:\n static constexpr char const* value = literal_value.str();\n};\ntemplate<typename T, T... chars> const string_literal<T,chars...> constexpr_type_name<string_literal<T,chars...>>::literal_value {};\n#endif \/\/ __GNUG__\n\n\/\/ Private types\n\ntemplate <class Tag, typename Value> class __attribute_const_reference_holder;\ntemplate <class Tag, typename Value> class __attribute_reference_holder;\ntemplate <class Tag, typename Value> class __attribute_value_holder;\n\n\/\/ Tag, shared by every one\n\ntemplate <class Tag> struct named_tag;\ntemplate <class Tag, typename Value> class named_attribute_holder;\n\n\/\/ Specific types : named_tuple\n\ntemplate <class...Types> struct named_tuple;\ntemplate <class T> struct __ntuple_tag_spec {};\ntemplate <class Spec, class Arg> struct __ntuple_tag_spec<Arg(Spec)> { using type = typename named_tag<Spec>::type; };\ntemplate <class T> struct __ntuple_tag_elem {};\ntemplate <class Spec, class Arg> struct __ntuple_tag_elem<Arg(Spec)> { using type = Arg; };\n\n\/\/ Tag\n\ntemplate <class Tag> struct named_tag : std::tag::basic_tag {\n private:\n template <typename T> struct unnested_ { using type = named_tag; };\n template <typename T> struct unnested_<named_tag<T>> { using type = named_tag<T>; };\n template <typename T> struct unnested_value_ { using type = T; };\n template <typename T> struct unnested_value_<named_tag<T>> { using type = T; };\n\n public:\n using type = typename unnested_<Tag>::type;\n using value_type = typename unnested_value_<Tag>::type;\n constexpr named_tag() = default;\n\n \/\/ Attribute holder generation\n\n template <typename T>\n __attribute_const_reference_holder<type, T>\n operator=(T const& value)\n { return __attribute_const_reference_holder<type,T>(value); }\n\n template <typename T>\n __attribute_reference_holder<type, T>\n operator=(T& value)\n { return __attribute_reference_holder<type,T>(value); }\n\n template <typename T>\n __attribute_value_holder<type, T>\n operator=(T&& value)\n { return __attribute_value_holder<type,T>(std::move(value)); }\n\n \/\/ Specific behavior : named_tuple\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type const&\n operator() (named_tuple<Types...> const& input) const \n { return std::get<type>(input); }\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type &\n operator() (named_tuple<Types...> & input) const \n { return std::get<type>(input); }\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type &&\n operator() (named_tuple<Types...>&& input) const \n { return std::move(std::get<type>(std::forward<named_tuple<Types...>>(input))); }\n};\n\n\/\/ Attribute holders\n\ntemplate <class Tag, typename Value> class __attribute_const_reference_holder {\n Value const& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_const_reference_holder(Value const& input) : value_(input) {}\n __attribute_const_reference_holder(__attribute_const_reference_holder const&) = delete;\n __attribute_const_reference_holder(__attribute_const_reference_holder&&) = default;\n __attribute_const_reference_holder& operator=(__attribute_const_reference_holder const&) = delete;\n __attribute_const_reference_holder& operator=(__attribute_const_reference_holder&&) = default;\n Value const& get() && { return value_; }\n};\n\ntemplate <class Tag, typename Value> class __attribute_reference_holder {\n Value& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_reference_holder(Value& input) : value_(input) {}\n __attribute_reference_holder(__attribute_reference_holder const&) = delete;\n __attribute_reference_holder(__attribute_reference_holder&&) = default;\n __attribute_reference_holder& operator=(__attribute_reference_holder const&) = delete;\n __attribute_reference_holder& operator=(__attribute_reference_holder&&) = default;\n Value& get() && { return value_; }\n};\n\ntemplate <class Tag, typename Value> class __attribute_value_holder {\n Value&& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_value_holder (Value&& input) : value_(std::move(input)) {}\n __attribute_value_holder(__attribute_value_holder const&) = delete;\n __attribute_value_holder(__attribute_value_holder&&) = default;\n __attribute_value_holder& operator=(__attribute_value_holder const&) = delete;\n __attribute_value_holder& operator=(__attribute_value_holder&&) = default;\n Value&& get() && { return std::move(value_); }\n};\n\n} \/\/ namespace named_types\n<commit_msg>Making string data more static.<commit_after>#pragma once\n#include <type_traits>\n#include <std\/experimental\/tagged.hpp>\n\nnamespace named_types {\n\n\/\/ String literals, GNU Extension only\n#ifdef __GNUG__\ntemplate <class T, T ... chars> struct string_literal {\n static const char data[sizeof ... (chars) + 1u];\n static const size_t data_size = sizeof ... (chars);\n\n constexpr string_literal() = default;\n constexpr char const* str() const { return data; }\n constexpr size_t size() const { return sizeof ... (chars); }\n constexpr char operator[] (size_t index) const { return data[index]; }\n};\ntemplate <class T, T ... chars> const char string_literal<T,chars...>::data[sizeof ... (chars) + 1u] = {chars..., '\\0'};\n#endif \/\/ __GNUG__\n\n\/\/ Traits for compile time name extraction\n\ntemplate <class T> class has_user_defined_name {\n template <class TT> static auto test(int) -> decltype(TT::classname);\n template <class TT> static auto test(int) -> decltype(TT::name);\n template <class TT> static auto test(int) -> decltype(TT::classname());\n template <class TT> static auto test(int) -> decltype(TT::name());\n template <class TT> static auto test(...) -> void;\n public:\n static constexpr bool value = std::is_same<decltype(test<T>(0)),char const *>::value;\n};\n\ntemplate<class T> class constexpr_type_name {\n template <class TT> static inline constexpr auto extract(int) -> decltype(TT::classname) { return TT::classname; }\n template <class TT> static inline constexpr auto extract(int) -> decltype(TT::name) { return TT::name; }\n template <class TT> static inline constexpr auto extract(int) -> decltype(TT::classname()) { return TT::classname(); }\n template <class TT> static inline constexpr auto extract(int) -> decltype(TT::name()) { return TT::name(); }\n public:\n static constexpr char const* value = extract<T>();\n};\n\n\/\/ Name extractors specified to work with string literals\n#ifdef __GNUG__\ntemplate<class T, T... chars> class has_user_defined_name<string_literal<T,chars...>> {\n public:\n static constexpr bool value = true;\n};\n\ntemplate<class T, T... chars> class constexpr_type_name <string_literal<T,chars...>> {\n public:\n static constexpr char const* value = string_literal<T,chars...>::data;\n};\n#endif \/\/ __GNUG__\n\n\/\/ Private types\n\ntemplate <class Tag, typename Value> class __attribute_const_reference_holder;\ntemplate <class Tag, typename Value> class __attribute_reference_holder;\ntemplate <class Tag, typename Value> class __attribute_value_holder;\n\n\/\/ Tag, shared by every one\n\ntemplate <class Tag> struct named_tag;\ntemplate <class Tag, typename Value> class named_attribute_holder;\n\n\/\/ Specific types : named_tuple\n\ntemplate <class...Types> struct named_tuple;\ntemplate <class T> struct __ntuple_tag_spec {};\ntemplate <class Spec, class Arg> struct __ntuple_tag_spec<Arg(Spec)> { using type = typename named_tag<Spec>::type; };\ntemplate <class T> struct __ntuple_tag_elem {};\ntemplate <class Spec, class Arg> struct __ntuple_tag_elem<Arg(Spec)> { using type = Arg; };\n\n\/\/ Tag\n\ntemplate <class Tag> struct named_tag : std::tag::basic_tag {\n private:\n template <typename T> struct unnested_ { using type = named_tag; };\n template <typename T> struct unnested_<named_tag<T>> { using type = named_tag<T>; };\n template <typename T> struct unnested_value_ { using type = T; };\n template <typename T> struct unnested_value_<named_tag<T>> { using type = T; };\n\n public:\n using type = typename unnested_<Tag>::type;\n using value_type = typename unnested_value_<Tag>::type;\n constexpr named_tag() = default;\n\n \/\/ Attribute holder generation\n\n template <typename T>\n __attribute_const_reference_holder<type, T>\n operator=(T const& value)\n { return __attribute_const_reference_holder<type,T>(value); }\n\n template <typename T>\n __attribute_reference_holder<type, T>\n operator=(T& value)\n { return __attribute_reference_holder<type,T>(value); }\n\n template <typename T>\n __attribute_value_holder<type, T>\n operator=(T&& value)\n { return __attribute_value_holder<type,T>(std::move(value)); }\n\n \/\/ Specific behavior : named_tuple\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type const&\n operator() (named_tuple<Types...> const& input) const \n { return std::get<type>(input); }\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type &\n operator() (named_tuple<Types...> & input) const \n { return std::get<type>(input); }\n\n template <typename...Types> \n inline constexpr typename named_tuple<Types...>::template type_at<type>::raw_type &&\n operator() (named_tuple<Types...>&& input) const \n { return std::move(std::get<type>(std::forward<named_tuple<Types...>>(input))); }\n};\n\n\/\/ Attribute holders\n\ntemplate <class Tag, typename Value> class __attribute_const_reference_holder {\n Value const& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_const_reference_holder(Value const& input) : value_(input) {}\n __attribute_const_reference_holder(__attribute_const_reference_holder const&) = delete;\n __attribute_const_reference_holder(__attribute_const_reference_holder&&) = default;\n __attribute_const_reference_holder& operator=(__attribute_const_reference_holder const&) = delete;\n __attribute_const_reference_holder& operator=(__attribute_const_reference_holder&&) = default;\n Value const& get() && { return value_; }\n};\n\ntemplate <class Tag, typename Value> class __attribute_reference_holder {\n Value& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_reference_holder(Value& input) : value_(input) {}\n __attribute_reference_holder(__attribute_reference_holder const&) = delete;\n __attribute_reference_holder(__attribute_reference_holder&&) = default;\n __attribute_reference_holder& operator=(__attribute_reference_holder const&) = delete;\n __attribute_reference_holder& operator=(__attribute_reference_holder&&) = default;\n Value& get() && { return value_; }\n};\n\ntemplate <class Tag, typename Value> class __attribute_value_holder {\n Value&& value_;\n public:\n using tag_type = Tag;\n using value_type = Value;\n __attribute_value_holder (Value&& input) : value_(std::move(input)) {}\n __attribute_value_holder(__attribute_value_holder const&) = delete;\n __attribute_value_holder(__attribute_value_holder&&) = default;\n __attribute_value_holder& operator=(__attribute_value_holder const&) = delete;\n __attribute_value_holder& operator=(__attribute_value_holder&&) = default;\n Value&& get() && { return std::move(value_); }\n};\n\n} \/\/ namespace named_types\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file llexternaleditor.cpp\n * @brief A convenient class to run external editor.\n *\n * $LicenseInfo:firstyear=2010&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llexternaleditor.h\"\n\n#include \"lltrans.h\"\n#include \"llui.h\"\n#include \"llprocess.h\"\n#include \"llsdutil.h\"\n#include <boost\/foreach.hpp>\n\n\/\/ static\nconst std::string LLExternalEditor::sFilenameMarker = \"%s\";\n\n\/\/ static\nconst std::string LLExternalEditor::sSetting = \"ExternalEditor\";\n\nLLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env_var, const std::string& override)\n{\n\tstd::string cmd = findCommand(env_var, override);\n\tif (cmd.empty())\n\t{\n\t\tllwarns << \"Editor command is empty or not set\" << llendl;\n\/\/ <FS:CR> FIRE-10320 If no editor is set, fallback on the system open handler\n\t\t\/\/return EC_NOT_SPECIFIED;\n\t\tllwarns << \"Falling back on generic open handler\" << llendl;\n#ifdef WIN32\n\t\tcmd = findCommand(\"\", \"%comspec% \/C START \\\"%s\\\"\")\n#endif\n#ifdef DARWIN\n\t\tcmd = findCommand(\"\", \"\/usr\/bin\/open \\\"%s\\\"\")\n#endif\n#ifdef LINUX\n\t\t\/\/ xdg-open might not actually be installed, but it's out best shot\n\t\tcmd = findCommand(\"\", \"\/usr\/bin\/xdg-open \\\"%s\\\"\")\n#endif\n\t\tif (cmd.empty())\n\t\t{\n\t\t\treturn EC_NOT_SPECIFIED;\n\t\t}\n\/\/ <\/FS:CR>\n\t}\n\n\tstring_vec_t tokens;\n\ttokenize(tokens, cmd);\n\n\t\/\/ Check executable for existence.\n\tstd::string bin_path = tokens[0];\n\tif (!LLFile::isfile(bin_path))\n\t{\n\t\tllwarns << \"Editor binary [\" << bin_path << \"] not found\" << llendl;\n\t\treturn EC_BINARY_NOT_FOUND;\n\t}\n\n\t\/\/ Save command.\n\tmProcessParams = LLProcess::Params();\n\tmProcessParams.executable = bin_path;\n\tfor (size_t i = 1; i < tokens.size(); ++i)\n\t{\n\t\tmProcessParams.args.add(tokens[i]);\n\t}\n\n\t\/\/ Add the filename marker if missing.\n\tif (cmd.find(sFilenameMarker) == std::string::npos)\n\t{\n\t\tmProcessParams.args.add(sFilenameMarker);\n\t\tllinfos << \"Adding the filename marker (\" << sFilenameMarker << \")\" << llendl;\n\t}\n\n\tllinfos << \"Setting command [\" << mProcessParams << \"]\" << llendl;\n\n\treturn EC_SUCCESS;\n}\n\nLLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path)\n{\n\tif (std::string(mProcessParams.executable).empty() || mProcessParams.args.empty())\n\t{\n\t\tllwarns << \"Editor command not set\" << llendl;\n\t\treturn EC_NOT_SPECIFIED;\n\t}\n\n\t\/\/ Copy params block so we can replace sFilenameMarker\n\tLLProcess::Params params;\n\tparams.executable = mProcessParams.executable;\n\n\t\/\/ Substitute the filename marker in the command with the actual passed file name.\n\tBOOST_FOREACH(const std::string& arg, mProcessParams.args)\n\t{\n\t\tstd::string fixed(arg);\n\t\tLLStringUtil::replaceString(fixed, sFilenameMarker, file_path);\n\t\tparams.args.add(fixed);\n\t}\n\n\t\/\/ Run the editor. Prevent killing the process in destructor.\n\tparams.autokill = false;\n\treturn LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN;\n}\n\n\/\/ static\nstd::string LLExternalEditor::getErrorMessage(EErrorCode code)\n{\n\tswitch (code)\n\t{\n\tcase EC_SUCCESS: \t\t\treturn LLTrans::getString(\"ok\");\n\tcase EC_NOT_SPECIFIED: \t\treturn LLTrans::getString(\"ExternalEditorNotSet\");\n\tcase EC_PARSE_ERROR:\t\treturn LLTrans::getString(\"ExternalEditorCommandParseError\");\n\tcase EC_BINARY_NOT_FOUND:\treturn LLTrans::getString(\"ExternalEditorNotFound\");\n\tcase EC_FAILED_TO_RUN:\t\treturn LLTrans::getString(\"ExternalEditorFailedToRun\");\n\t}\n\n\treturn LLTrans::getString(\"Unknown\");\n}\n\n\/\/ TODO:\n\/\/ - Unit-test this with tests like LLStringUtil::getTokens() (the\n\/\/ command-line overload that supports quoted tokens)\n\/\/ - Unless there are significant semantic differences, eliminate this method\n\/\/ and use LLStringUtil::getTokens() instead.\n\n\/\/ static\nsize_t LLExternalEditor::tokenize(string_vec_t& tokens, const std::string& str)\n{\n\ttokens.clear();\n\n\t\/\/ Split the argument string into separate strings for each argument\n\ttypedef boost::tokenizer< boost::char_separator<char> > tokenizer;\n\tboost::char_separator<char> sep(\"\", \"\\\" \", boost::drop_empty_tokens);\n\n\ttokenizer tokens_list(str, sep);\n\ttokenizer::iterator token_iter;\n\tBOOL inside_quotes = FALSE;\n\tBOOL last_was_space = FALSE;\n\tfor (token_iter = tokens_list.begin(); token_iter != tokens_list.end(); ++token_iter)\n\t{\n\t\tif (!strncmp(\"\\\"\",(*token_iter).c_str(),2))\n\t\t{\n\t\t\tinside_quotes = !inside_quotes;\n\t\t}\n\t\telse if (!strncmp(\" \",(*token_iter).c_str(),2))\n\t\t{\n\t\t\tif(inside_quotes)\n\t\t\t{\n\t\t\t\ttokens.back().append(std::string(\" \"));\n\t\t\t\tlast_was_space = TRUE;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::string to_push = *token_iter;\n\t\t\tif (last_was_space)\n\t\t\t{\n\t\t\t\ttokens.back().append(to_push);\n\t\t\t\tlast_was_space = FALSE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttokens.push_back(to_push);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokens.size();\n}\n\n\/\/ static\nstd::string LLExternalEditor::findCommand(\n\tconst std::string& env_var,\n\tconst std::string& override)\n{\n\tstd::string cmd;\n\n\t\/\/ Get executable path.\n\tif (!override.empty())\t\/\/ try the supplied override first\n\t{\n\t\tcmd = override;\n\t\tllinfos << \"Using override\" << llendl;\n\t}\n\telse if (!LLUI::sSettingGroups[\"config\"]->getString(sSetting).empty())\n\t{\n\t\tcmd = LLUI::sSettingGroups[\"config\"]->getString(sSetting);\n\t\tllinfos << \"Using setting\" << llendl;\n\t}\n\telse\t\t\t\t\t\/\/ otherwise use the path specified by the environment variable\n\t{\n\t\tchar* env_var_val = getenv(env_var.c_str());\n\t\tif (env_var_val)\n\t\t{\n\t\t\tcmd = env_var_val;\n\t\t\tllinfos << \"Using env var \" << env_var << llendl;\n\t\t}\n\t}\n\n\tllinfos << \"Found command [\" << cmd << \"]\" << llendl;\n\treturn cmd;\n}\n<commit_msg>More fixing. I forgot semicolons. -_-<commit_after>\/** \n * @file llexternaleditor.cpp\n * @brief A convenient class to run external editor.\n *\n * $LicenseInfo:firstyear=2010&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llexternaleditor.h\"\n\n#include \"lltrans.h\"\n#include \"llui.h\"\n#include \"llprocess.h\"\n#include \"llsdutil.h\"\n#include <boost\/foreach.hpp>\n\n\/\/ static\nconst std::string LLExternalEditor::sFilenameMarker = \"%s\";\n\n\/\/ static\nconst std::string LLExternalEditor::sSetting = \"ExternalEditor\";\n\nLLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env_var, const std::string& override)\n{\n\tstd::string cmd = findCommand(env_var, override);\n\tif (cmd.empty())\n\t{\n\t\tllwarns << \"Editor command is empty or not set\" << llendl;\n\/\/ <FS:CR> FIRE-10320 If no editor is set, fallback on the system open handler\n\t\t\/\/return EC_NOT_SPECIFIED;\n\t\tllwarns << \"Falling back on generic open handler\" << llendl;\n#ifdef WIN32\n\t\tcmd = \"%comspec% \/C START \\\"%s\\\"\";\n#endif\n#ifdef DARWIN\n\t\tcmd = \"\/usr\/bin\/open \\\"%s\\\"\";\n#endif\n#ifdef LINUX\n\t\t\/\/ xdg-open might not actually be installed, but it's out best shot\n\t\tcmd = findCommand(\"\", \"\/usr\/bin\/xdg-open \\\"%s\\\"\");\n#endif\n\t\tif (cmd.empty())\n\t\t{\n\t\t\treturn EC_NOT_SPECIFIED;\n\t\t}\n\/\/ <\/FS:CR>\n\t}\n\n\tstring_vec_t tokens;\n\ttokenize(tokens, cmd);\n\n\t\/\/ Check executable for existence.\n\tstd::string bin_path = tokens[0];\n\tif (!LLFile::isfile(bin_path))\n\t{\n\t\tllwarns << \"Editor binary [\" << bin_path << \"] not found\" << llendl;\n\t\treturn EC_BINARY_NOT_FOUND;\n\t}\n\n\t\/\/ Save command.\n\tmProcessParams = LLProcess::Params();\n\tmProcessParams.executable = bin_path;\n\tfor (size_t i = 1; i < tokens.size(); ++i)\n\t{\n\t\tmProcessParams.args.add(tokens[i]);\n\t}\n\n\t\/\/ Add the filename marker if missing.\n\tif (cmd.find(sFilenameMarker) == std::string::npos)\n\t{\n\t\tmProcessParams.args.add(sFilenameMarker);\n\t\tllinfos << \"Adding the filename marker (\" << sFilenameMarker << \")\" << llendl;\n\t}\n\n\tllinfos << \"Setting command [\" << mProcessParams << \"]\" << llendl;\n\n\treturn EC_SUCCESS;\n}\n\nLLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path)\n{\n\tif (std::string(mProcessParams.executable).empty() || mProcessParams.args.empty())\n\t{\n\t\tllwarns << \"Editor command not set\" << llendl;\n\t\treturn EC_NOT_SPECIFIED;\n\t}\n\n\t\/\/ Copy params block so we can replace sFilenameMarker\n\tLLProcess::Params params;\n\tparams.executable = mProcessParams.executable;\n\n\t\/\/ Substitute the filename marker in the command with the actual passed file name.\n\tBOOST_FOREACH(const std::string& arg, mProcessParams.args)\n\t{\n\t\tstd::string fixed(arg);\n\t\tLLStringUtil::replaceString(fixed, sFilenameMarker, file_path);\n\t\tparams.args.add(fixed);\n\t}\n\n\t\/\/ Run the editor. Prevent killing the process in destructor.\n\tparams.autokill = false;\n\treturn LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN;\n}\n\n\/\/ static\nstd::string LLExternalEditor::getErrorMessage(EErrorCode code)\n{\n\tswitch (code)\n\t{\n\tcase EC_SUCCESS: \t\t\treturn LLTrans::getString(\"ok\");\n\tcase EC_NOT_SPECIFIED: \t\treturn LLTrans::getString(\"ExternalEditorNotSet\");\n\tcase EC_PARSE_ERROR:\t\treturn LLTrans::getString(\"ExternalEditorCommandParseError\");\n\tcase EC_BINARY_NOT_FOUND:\treturn LLTrans::getString(\"ExternalEditorNotFound\");\n\tcase EC_FAILED_TO_RUN:\t\treturn LLTrans::getString(\"ExternalEditorFailedToRun\");\n\t}\n\n\treturn LLTrans::getString(\"Unknown\");\n}\n\n\/\/ TODO:\n\/\/ - Unit-test this with tests like LLStringUtil::getTokens() (the\n\/\/ command-line overload that supports quoted tokens)\n\/\/ - Unless there are significant semantic differences, eliminate this method\n\/\/ and use LLStringUtil::getTokens() instead.\n\n\/\/ static\nsize_t LLExternalEditor::tokenize(string_vec_t& tokens, const std::string& str)\n{\n\ttokens.clear();\n\n\t\/\/ Split the argument string into separate strings for each argument\n\ttypedef boost::tokenizer< boost::char_separator<char> > tokenizer;\n\tboost::char_separator<char> sep(\"\", \"\\\" \", boost::drop_empty_tokens);\n\n\ttokenizer tokens_list(str, sep);\n\ttokenizer::iterator token_iter;\n\tBOOL inside_quotes = FALSE;\n\tBOOL last_was_space = FALSE;\n\tfor (token_iter = tokens_list.begin(); token_iter != tokens_list.end(); ++token_iter)\n\t{\n\t\tif (!strncmp(\"\\\"\",(*token_iter).c_str(),2))\n\t\t{\n\t\t\tinside_quotes = !inside_quotes;\n\t\t}\n\t\telse if (!strncmp(\" \",(*token_iter).c_str(),2))\n\t\t{\n\t\t\tif(inside_quotes)\n\t\t\t{\n\t\t\t\ttokens.back().append(std::string(\" \"));\n\t\t\t\tlast_was_space = TRUE;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::string to_push = *token_iter;\n\t\t\tif (last_was_space)\n\t\t\t{\n\t\t\t\ttokens.back().append(to_push);\n\t\t\t\tlast_was_space = FALSE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttokens.push_back(to_push);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokens.size();\n}\n\n\/\/ static\nstd::string LLExternalEditor::findCommand(\n\tconst std::string& env_var,\n\tconst std::string& override)\n{\n\tstd::string cmd;\n\n\t\/\/ Get executable path.\n\tif (!override.empty())\t\/\/ try the supplied override first\n\t{\n\t\tcmd = override;\n\t\tllinfos << \"Using override\" << llendl;\n\t}\n\telse if (!LLUI::sSettingGroups[\"config\"]->getString(sSetting).empty())\n\t{\n\t\tcmd = LLUI::sSettingGroups[\"config\"]->getString(sSetting);\n\t\tllinfos << \"Using setting\" << llendl;\n\t}\n\telse\t\t\t\t\t\/\/ otherwise use the path specified by the environment variable\n\t{\n\t\tchar* env_var_val = getenv(env_var.c_str());\n\t\tif (env_var_val)\n\t\t{\n\t\t\tcmd = env_var_val;\n\t\t\tllinfos << \"Using env var \" << env_var << llendl;\n\t\t}\n\t}\n\n\tllinfos << \"Found command [\" << cmd << \"]\" << llendl;\n\treturn cmd;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ManageGamesMenu.h\"\n#include <sstream>\n\n#include \"NewGameMenu.h\"\n#include \"ChooseYourLevelMenu.h\"\n\n\/** @namespace Symp *\/\nnamespace Symp {\n\nextern int g_WindowHeight;\nextern int g_WindowWidth;\n\n\/**\n* @brief ManageGamesMenu constructor\n* Responsible for the initialization of the private attributes of the #ManageGamesMenuMenu class. This function\n* is not responsible for drawing the graphical elements that compose the menu, the #init() function is.\n* @see Player\n* @see MenuManager\n* @see State\n* @see init()\n* @see ~ManageGamesMenu()\n*\/\nManageGamesMenu::ManageGamesMenu()\n\t:State(){\n\t\n}\n\n\/**\n* @brief ManageGamesMenu elements initialization\n* The elements that compose the menu are created in this function.\n* @see Player\n* @see MenuManager\n* @see State\n* @see end()\n*\/\nvoid ManageGamesMenu::init(){\n\n\tm_background = new Image(\"..\/assets\/menu\/manage-games-background.png\");\n\tm_background->setWidth(g_WindowWidth);\n\tm_background->setHeight(g_WindowHeight);\n\tm_background->setAspectRatio(AspectRatio::IGNORE_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_background, 0);\n\tm_background->update();\n\n\t\/\/ The go back button up-left of the window\n\tm_pBackButton = new Image(\"..\/assets\/menu\/back-to-menu-outgame.png\", g_WindowWidth*0.05, g_WindowHeight*0.05, 0.5);\n\tm_pBackButton->setColor(Color::YELLOWDINO);\n\tm_pBackButton->enable();\n\tm_pBackButton->setAspectRatio(AspectRatio::EXPAND_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_pBackButton, 1);\n\n\n\t\/\/Image that display the \"Current Game\" Label\n\tm_pCurrentGameLabel = new Image(\"..\/assets\/menu\/current_game.png\", g_WindowWidth*0.25, g_WindowHeight*0.26, 0.7);\n\tMenuManager::getInstance()->addGuiComponent(m_pCurrentGameLabel, 2);\n\n\t\/\/ Last Player panel\n\tcreatePlayerPanel(MenuManager::getInstance()->getLastPlayer(), g_WindowWidth*0.25, g_WindowHeight*0.3, g_WindowWidth*0.6, g_WindowHeight*0.1, Color::YELLOWDINO, Color::BLUEDINO);\n\n\t\/\/ If there is more than one player\n\tif(MenuManager::getInstance()->getPlayers().size() > 1 ) {\n\t\t\/\/Image that display the \"Load another game\" Label\n\t\tm_pLoadAnotherGameLabel = new Image(\"..\/assets\/menu\/load_another_game.png\", g_WindowWidth*0.25, g_WindowHeight*0.46, 0.7);\n\t\tMenuManager::getInstance()->addGuiComponent(m_pLoadAnotherGameLabel, 2);\n\n\t\t\/\/Other players panel\n\t\tint posY = g_WindowHeight*0.5;\n\t\tfor (unsigned int i = 0; i < MenuManager::getInstance()->getPlayers().size(); ++i){\n\t\t\tif(MenuManager::getInstance()->getPlayers()[i] != MenuManager::getInstance()->getLastPlayer()) {\n\t\t\t\tcreatePlayerPanel(MenuManager::getInstance()->getPlayers()[i], g_WindowWidth*0.25, posY + i*g_WindowHeight*0.12, g_WindowWidth*0.6, g_WindowHeight*0.1, Color::YELLOWDINO, Color::BLUEDINO);\n\t\t\t}\t\t\n\t\t}\n\n\t}\n\t\n\t\/\/Create a new Player Button\n\tm_pCreateNewGameButton = new Image(\"..\/assets\/menu\/create-new-game.png\", g_WindowWidth*0.6, g_WindowHeight*0.8);\n\tm_pCreateNewGameButton->setHeight(g_WindowHeight*0.1);\n\tm_pCreateNewGameButton->setColor(Color::YELLOWDINO);\n\tm_pCreateNewGameButton->enable();\n\tm_pCreateNewGameButton->setAspectRatio(AspectRatio::KEEP_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_pCreateNewGameButton, 0);\n\n}\n\n\/**\n* @brief Create a panel with the #Player data\n* The elements that compose the #Player panel are created in this function. This panel\n* is composed by a #Layout that group elements but that do not manage their position and shape, and a #Button\n* that can receive events. The panel can be customized with two colors : one for the border of the #Layout component, one for the background of the #Button component.\n* @param pPlayer the reference to the #Player this panel is made for\n* @param iPosX the x coordinate of the upper-left corner of the panel in pixels\n* @param iPosY the y coordinate of the upper-left corner of the panel in pixels\n* @param iWidth the width of the panel in pixels\n* @param iHeight the height of the panel in pixels\n* @param borderColor the color of the border of the panel\n* @param backgoundColor the color of the background of the panel\n* @return pLayout the reference to the #Layout that contain the #Player graphcal data\n* @see Player\n* @see MenuManager\n* @see State\n* @see init()\n*\/\nLayout* ManageGamesMenu::createPlayerPanel(Player* pPlayer, int iPosX, int iPosY, int iWidth, int iHeight, \n\tColor borderColor, Color backgroundColor){\n\t\/\/Creation of the main Layout\n\t\/\/Layout* pLayout = new Layout(iPosX, iPosY, iWidth, iHeight, borderColor, LayoutFillAttribute::BORDER);\n\n\tint iCrossWidth = g_WindowWidth*0.1;\n\n\tLayout* persoLayout = new Layout(iPosX, iPosY, iWidth - (iCrossWidth + 10), iHeight, borderColor, LayoutFillAttribute::BORDER);\n\tint iVMargin = persoLayout->getVerticalMargin();\n\tint iHMargin = persoLayout->getHorizontalMargin();\n\n\t\/\/Creation of the Button\n\tButton* button = new Button(backgroundColor, iPosX, iPosY, iWidth - (iCrossWidth + 10), iHeight);\n\tMenuManager::getInstance()->addGuiComponent(button, 0);\n\n\t\/\/Retrieve the avatar index\n\tstd::ostringstream oss;\n\toss << pPlayer->getAvatarIndex();\n\tstd::string avatarIndex = oss.str();\n\n\t\/\/ Display the avatar \n\tImage* image = new Image(std::string(\"..\/assets\/menu\/avatar\" + avatarIndex + \".png\").c_str(), iPosX + iHMargin, iPosY + iVMargin);\n\timage->setWidth(iWidth - 2*iHMargin);\n\timage->setHeight(iHeight - 2*iVMargin);\n\tpersoLayout->addComponent(image, 0, 0, false);\n\timage->update();\n\n\t\/\/ Display the Player progression bar\n\tint level = pPlayer->getCurrentLevel();\n\tint sliderHeight = g_WindowHeight*0.03;\n\tint sliderPosX = image->getIND_Entity2d()->getSurface()->getWidth()*image->getIND_Entity2d()->getScaleX() + image->getPosX() + 2 * iHMargin;\n\tint sliderPosY = iPosY + iHeight - (sliderHeight + iVMargin);\n\tint sliderWidth = iWidth - iCrossWidth - 6*iHMargin - image->getIND_Entity2d()->getSurface()->getWidth()*image->getIND_Entity2d()->getScaleY();\n\tSlider* slider = new Slider((float)level\/gTotalLevelNumber, sliderPosX, sliderPosY, sliderWidth, sliderHeight);\n\tpersoLayout->addComponent(slider, 1, 0, false);\n\tMenuManager::getInstance()->addGuiComponent(slider->getImage(), 2);\n\tslider->update();\n\tMenuManager::getInstance()->addGuiLayout(persoLayout, 1);\n\n\t\/\/ Retrieve the last level unlocked\n\tText* lastLevel = new Text(\"Last level unlocked : \" + getLevelName(pPlayer->getCurrentLevel()), Color(20, 20, 20), sliderPosX + sliderWidth - 10, iPosY + sliderHeight, true);\n\tlastLevel->getIND_Entity2d()->setAlign(IND_RIGHT);\n\tMenuManager::getInstance()->addGuiComponent(lastLevel, 1);\n\n\t\/\/Retrieve the player's name\n\tText* name = new Text(pPlayer->getName(), Color::BLUEDINO, sliderPosX, iPosY);\n\tname->getIND_Entity2d()->setAlign(IND_LEFT);\n\tMenuManager::getInstance()->addGuiComponent(name, 1);\n\n\t\/\/Cross Image\n\tImage* cross = new Image(\"..\/assets\/menu\/cross.png\", iPosX + iWidth - (iCrossWidth + 2*iHMargin), iPosY + 2*iVMargin);\n\tcross->setColor(Color::RED);\n\tcross->enable();\n\tMenuManager::getInstance()->addGuiComponent(cross, 0);\n\n\t\/\/Associate the button with the player\n\tm_buttonMap.insert(std::pair<Button*, Player*>(button, pPlayer));\n\tm_crossMap.insert(std::pair<Image*, Player*>(cross, pPlayer));\n\n\t\/\/Return the main Layout\n\treturn persoLayout;\n}\n\n\/**\n* @brief Handle mouse clic events\n* @param mouseX the x coordinate of the mouse position\n* @param mouseY the y coordinate of the mouse position\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::handleMouseClic(int mouseX, int mouseY){\n\tif (m_pCreateNewGameButton->isTargetedByMouse(mouseX, mouseY)){\n\t\t\/\/Creates a new Player\n\t\tNewGameMenu* newGameMenu = new NewGameMenu();\n\t\tMenuManager::getInstance()->setState(newGameMenu);\n\t}\n\telse if (m_pBackButton->isTargetedByMouse(mouseX, mouseY)){\n\t\t\/\/Go back\n\t\tMenuManager::getInstance()->goBack();\n\t}\n\telse{\n\t\t\/\/ Click on a Player, then display its data in the ChooseYourLevelMenu\n\t\tfor (std::map<Button*,Player*>::iterator it=m_buttonMap.begin(); it!=m_buttonMap.end(); ++it){\n\t\t\tif (it->first->isTargetedByMouse(mouseX, mouseY)){\n\t\t\t\tChooseYourLevelMenu* chooseYourLevelMenu = new ChooseYourLevelMenu(it->second);\n\t\t\t\tMenuManager::getInstance()->setState(chooseYourLevelMenu);\n\t\t\t}\n\t\t}\n\t\tfor (std::map<Image*,Player*>::iterator it=m_crossMap.begin(); it!=m_crossMap.end(); ++it){\n\t\t\tif (it->first->isTargetedByMouse(mouseX, mouseY)){\n\t\t\t\tMenuManager::getInstance()->erasePlayerData(it->second);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstd::string ManageGamesMenu::getLevelName(int level){\n\tstd::string chapter = \" CHAPTER \";\n\tstd::string index = \" LEVEL \";\n\tfor (int i =1; i<4; ++i){\n\t\tif(level- i*3 > 0 ){\n\t\t\tlevel = level-i*3;\n\t\t}else if(level- i*3 < 0){\n\t\t\tstd::ostringstream oss;\n\t\t\toss << level;\n\t\t\tindex += oss.str();\n\n\t\t\tstd::ostringstream ossBis;\n\t\t\tossBis << i;\n\t\t\tchapter += ossBis.str();\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn chapter + \"-\" + index;\t\n}\n\n\/**\n* @brief Handle key down event\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::keyDownPressed(){\n\tstd::cout << \"Key down pressed\" <<std::endl;\n}\n\n\/**\n* @brief Handle key up event\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::keyUpPressed(){\n\tstd::cout << \"Key up pressed\" <<std::endl;\n}\n\n}<commit_msg>Center \"Create a New Game\" in \"ManageGameMenu\". fix #172<commit_after>#include \"ManageGamesMenu.h\"\n#include <sstream>\n\n#include \"NewGameMenu.h\"\n#include \"ChooseYourLevelMenu.h\"\n\n\/** @namespace Symp *\/\nnamespace Symp {\n\nextern int g_WindowHeight;\nextern int g_WindowWidth;\n\n\/**\n* @brief ManageGamesMenu constructor\n* Responsible for the initialization of the private attributes of the #ManageGamesMenuMenu class. This function\n* is not responsible for drawing the graphical elements that compose the menu, the #init() function is.\n* @see Player\n* @see MenuManager\n* @see State\n* @see init()\n* @see ~ManageGamesMenu()\n*\/\nManageGamesMenu::ManageGamesMenu()\n\t:State(){\n\t\n}\n\n\/**\n* @brief ManageGamesMenu elements initialization\n* The elements that compose the menu are created in this function.\n* @see Player\n* @see MenuManager\n* @see State\n* @see end()\n*\/\nvoid ManageGamesMenu::init(){\n\n\tm_background = new Image(\"..\/assets\/menu\/manage-games-background.png\");\n\tm_background->setWidth(g_WindowWidth);\n\tm_background->setHeight(g_WindowHeight);\n\tm_background->setAspectRatio(AspectRatio::IGNORE_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_background, 0);\n\tm_background->update();\n\n\t\/\/ The go back button up-left of the window\n\tm_pBackButton = new Image(\"..\/assets\/menu\/back-to-menu-outgame.png\", g_WindowWidth*0.05, g_WindowHeight*0.05, 0.5);\n\tm_pBackButton->setColor(Color::YELLOWDINO);\n\tm_pBackButton->enable();\n\tm_pBackButton->setAspectRatio(AspectRatio::EXPAND_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_pBackButton, 1);\n\n\n\t\/\/Image that display the \"Current Game\" Label\n\tm_pCurrentGameLabel = new Image(\"..\/assets\/menu\/current_game.png\", g_WindowWidth*0.25, g_WindowHeight*0.26, 0.7);\n\tMenuManager::getInstance()->addGuiComponent(m_pCurrentGameLabel, 2);\n\n\t\/\/ Last Player panel\n\tcreatePlayerPanel(MenuManager::getInstance()->getLastPlayer(), g_WindowWidth*0.25, g_WindowHeight*0.3, g_WindowWidth*0.6, g_WindowHeight*0.1, Color::YELLOWDINO, Color::BLUEDINO);\n\n\t\/\/ If there is more than one player\n\tif(MenuManager::getInstance()->getPlayers().size() > 1 ) {\n\t\t\/\/Image that display the \"Load another game\" Label\n\t\tm_pLoadAnotherGameLabel = new Image(\"..\/assets\/menu\/load_another_game.png\", g_WindowWidth*0.25, g_WindowHeight*0.46, 0.7);\n\t\tMenuManager::getInstance()->addGuiComponent(m_pLoadAnotherGameLabel, 2);\n\n\t\t\/\/Other players panel\n\t\tint posY = g_WindowHeight*0.5;\n\t\tfor (unsigned int i = 0; i < MenuManager::getInstance()->getPlayers().size(); ++i){\n\t\t\tif(MenuManager::getInstance()->getPlayers()[i] != MenuManager::getInstance()->getLastPlayer()) {\n\t\t\t\tcreatePlayerPanel(MenuManager::getInstance()->getPlayers()[i], g_WindowWidth*0.25, posY + i*g_WindowHeight*0.12, g_WindowWidth*0.6, g_WindowHeight*0.1, Color::YELLOWDINO, Color::BLUEDINO);\n\t\t\t}\t\t\n\t\t}\n\n\t}\n\t\n\t\/\/Create a new Player Button\n\tm_pCreateNewGameButton = new Image(\"..\/assets\/menu\/create-new-game.png\", g_WindowWidth*0.42, g_WindowHeight*0.8);\n\tm_pCreateNewGameButton->setHeight(g_WindowHeight*0.1);\n\tm_pCreateNewGameButton->setColor(Color::YELLOWDINO);\n\tm_pCreateNewGameButton->enable();\n\tm_pCreateNewGameButton->setAspectRatio(AspectRatio::KEEP_ASPECT_RATIO);\n\tMenuManager::getInstance()->addGuiComponent(m_pCreateNewGameButton, 0);\n\n}\n\n\/**\n* @brief Create a panel with the #Player data\n* The elements that compose the #Player panel are created in this function. This panel\n* is composed by a #Layout that group elements but that do not manage their position and shape, and a #Button\n* that can receive events. The panel can be customized with two colors : one for the border of the #Layout component, one for the background of the #Button component.\n* @param pPlayer the reference to the #Player this panel is made for\n* @param iPosX the x coordinate of the upper-left corner of the panel in pixels\n* @param iPosY the y coordinate of the upper-left corner of the panel in pixels\n* @param iWidth the width of the panel in pixels\n* @param iHeight the height of the panel in pixels\n* @param borderColor the color of the border of the panel\n* @param backgoundColor the color of the background of the panel\n* @return pLayout the reference to the #Layout that contain the #Player graphcal data\n* @see Player\n* @see MenuManager\n* @see State\n* @see init()\n*\/\nLayout* ManageGamesMenu::createPlayerPanel(Player* pPlayer, int iPosX, int iPosY, int iWidth, int iHeight, \n\tColor borderColor, Color backgroundColor){\n\t\/\/Creation of the main Layout\n\t\/\/Layout* pLayout = new Layout(iPosX, iPosY, iWidth, iHeight, borderColor, LayoutFillAttribute::BORDER);\n\n\tint iCrossWidth = g_WindowWidth*0.1;\n\n\tLayout* persoLayout = new Layout(iPosX, iPosY, iWidth - (iCrossWidth + 10), iHeight, borderColor, LayoutFillAttribute::BORDER);\n\tint iVMargin = persoLayout->getVerticalMargin();\n\tint iHMargin = persoLayout->getHorizontalMargin();\n\n\t\/\/Creation of the Button\n\tButton* button = new Button(backgroundColor, iPosX, iPosY, iWidth - (iCrossWidth + 10), iHeight);\n\tMenuManager::getInstance()->addGuiComponent(button, 0);\n\n\t\/\/Retrieve the avatar index\n\tstd::ostringstream oss;\n\toss << pPlayer->getAvatarIndex();\n\tstd::string avatarIndex = oss.str();\n\n\t\/\/ Display the avatar \n\tImage* image = new Image(std::string(\"..\/assets\/menu\/avatar\" + avatarIndex + \".png\").c_str(), iPosX + iHMargin, iPosY + iVMargin);\n\timage->setWidth(iWidth - 2*iHMargin);\n\timage->setHeight(iHeight - 2*iVMargin);\n\tpersoLayout->addComponent(image, 0, 0, false);\n\timage->update();\n\n\t\/\/ Display the Player progression bar\n\tint level = pPlayer->getCurrentLevel();\n\tint sliderHeight = g_WindowHeight*0.03;\n\tint sliderPosX = image->getIND_Entity2d()->getSurface()->getWidth()*image->getIND_Entity2d()->getScaleX() + image->getPosX() + 2 * iHMargin;\n\tint sliderPosY = iPosY + iHeight - (sliderHeight + iVMargin);\n\tint sliderWidth = iWidth - iCrossWidth - 6*iHMargin - image->getIND_Entity2d()->getSurface()->getWidth()*image->getIND_Entity2d()->getScaleY();\n\tSlider* slider = new Slider((float)level\/gTotalLevelNumber, sliderPosX, sliderPosY, sliderWidth, sliderHeight);\n\tpersoLayout->addComponent(slider, 1, 0, false);\n\tMenuManager::getInstance()->addGuiComponent(slider->getImage(), 2);\n\tslider->update();\n\tMenuManager::getInstance()->addGuiLayout(persoLayout, 1);\n\n\t\/\/ Retrieve the last level unlocked\n\tText* lastLevel = new Text(\"Last level unlocked : \" + getLevelName(pPlayer->getCurrentLevel()), Color(20, 20, 20), sliderPosX + sliderWidth - 10, iPosY + sliderHeight, true);\n\tlastLevel->getIND_Entity2d()->setAlign(IND_RIGHT);\n\tMenuManager::getInstance()->addGuiComponent(lastLevel, 1);\n\n\t\/\/Retrieve the player's name\n\tText* name = new Text(pPlayer->getName(), Color::BLUEDINO, sliderPosX, iPosY);\n\tname->getIND_Entity2d()->setAlign(IND_LEFT);\n\tMenuManager::getInstance()->addGuiComponent(name, 1);\n\n\t\/\/Cross Image\n\tImage* cross = new Image(\"..\/assets\/menu\/cross.png\", iPosX + iWidth - (iCrossWidth + 2*iHMargin), iPosY + 2*iVMargin);\n\tcross->setColor(Color::RED);\n\tcross->enable();\n\tMenuManager::getInstance()->addGuiComponent(cross, 0);\n\n\t\/\/Associate the button with the player\n\tm_buttonMap.insert(std::pair<Button*, Player*>(button, pPlayer));\n\tm_crossMap.insert(std::pair<Image*, Player*>(cross, pPlayer));\n\n\t\/\/Return the main Layout\n\treturn persoLayout;\n}\n\n\/**\n* @brief Handle mouse clic events\n* @param mouseX the x coordinate of the mouse position\n* @param mouseY the y coordinate of the mouse position\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::handleMouseClic(int mouseX, int mouseY){\n\tif (m_pCreateNewGameButton->isTargetedByMouse(mouseX, mouseY)){\n\t\t\/\/Creates a new Player\n\t\tNewGameMenu* newGameMenu = new NewGameMenu();\n\t\tMenuManager::getInstance()->setState(newGameMenu);\n\t}\n\telse if (m_pBackButton->isTargetedByMouse(mouseX, mouseY)){\n\t\t\/\/Go back\n\t\tMenuManager::getInstance()->goBack();\n\t}\n\telse{\n\t\t\/\/ Click on a Player, then display its data in the ChooseYourLevelMenu\n\t\tfor (std::map<Button*,Player*>::iterator it=m_buttonMap.begin(); it!=m_buttonMap.end(); ++it){\n\t\t\tif (it->first->isTargetedByMouse(mouseX, mouseY)){\n\t\t\t\tChooseYourLevelMenu* chooseYourLevelMenu = new ChooseYourLevelMenu(it->second);\n\t\t\t\tMenuManager::getInstance()->setState(chooseYourLevelMenu);\n\t\t\t}\n\t\t}\n\t\tfor (std::map<Image*,Player*>::iterator it=m_crossMap.begin(); it!=m_crossMap.end(); ++it){\n\t\t\tif (it->first->isTargetedByMouse(mouseX, mouseY)){\n\t\t\t\tMenuManager::getInstance()->erasePlayerData(it->second);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstd::string ManageGamesMenu::getLevelName(int level){\n\tstd::string chapter = \" CHAPTER \";\n\tstd::string index = \" LEVEL \";\n\tfor (int i =1; i<4; ++i){\n\t\tif(level- i*3 > 0 ){\n\t\t\tlevel = level-i*3;\n\t\t}else if(level- i*3 < 0){\n\t\t\tstd::ostringstream oss;\n\t\t\toss << level;\n\t\t\tindex += oss.str();\n\n\t\t\tstd::ostringstream ossBis;\n\t\t\tossBis << i;\n\t\t\tchapter += ossBis.str();\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn chapter + \"-\" + index;\t\n}\n\n\/**\n* @brief Handle key down event\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::keyDownPressed(){\n\tstd::cout << \"Key down pressed\" <<std::endl;\n}\n\n\/**\n* @brief Handle key up event\n* @see MenuManager\n* @see State\n* @see InputManager\n* @see init()\n*\/\nvoid ManageGamesMenu::keyUpPressed(){\n\tstd::cout << \"Key up pressed\" <<std::endl;\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/canbus\/vehicle\/lincoln\/protocol\/brakeinfo_74.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace lincoln {\n\nclass Brakeinfo74Test : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Brakeinfo74Test, simple) {\n Brakeinfo74 brakeinfo;\n uint8_t data[8] = {0x64U};\n int32_t length = 8;\n ChassisDetail cd;\n brakeinfo.Parse(data, length, &cd);\n\n EXPECT_FALSE(cd.esp().is_abs_active());\n EXPECT_FALSE(cd.esp().is_abs_enabled());\n EXPECT_FALSE(cd.esp().is_stab_active());\n EXPECT_FALSE(cd.esp().is_stab_enabled());\n EXPECT_FALSE(cd.esp().is_trac_active());\n EXPECT_FALSE(cd.esp().is_trac_enabled());\n\n EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);\n EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 400.0);\n EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);\n EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 0.0);\n EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);\n EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 0.0);\n EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());\n EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.0);\n}\n\n} \/\/ namespace lincoln\n} \/\/ namespace apollo\n} \/\/ namespace canbus\n<commit_msg>Use full length test data in brakeinfo_74_test<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/canbus\/vehicle\/lincoln\/protocol\/brakeinfo_74.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace apollo {\nnamespace canbus {\nnamespace lincoln {\n\nclass Brakeinfo74Test : public ::testing::Test {\n public:\n virtual void SetUp() {}\n};\n\nTEST_F(Brakeinfo74Test, simple) {\n Brakeinfo74 brakeinfo;\n uint8_t data[8] = {0x64U, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};\n int32_t length = 8;\n ChassisDetail cd;\n brakeinfo.Parse(data, length, &cd);\n\n EXPECT_TRUE(cd.esp().is_abs_active());\n EXPECT_FALSE(cd.esp().is_abs_enabled());\n EXPECT_TRUE(cd.esp().is_stab_active());\n EXPECT_FALSE(cd.esp().is_stab_enabled());\n EXPECT_FALSE(cd.esp().is_trac_active());\n EXPECT_FALSE(cd.esp().is_trac_enabled());\n\n EXPECT_EQ(cd.epb().parking_brake_status(), Epb::PBRAKE_OFF);\n EXPECT_DOUBLE_EQ(cd.brake().brake_torque_req(), 2448.0);\n EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_INACTIVE);\n EXPECT_DOUBLE_EQ(cd.brake().brake_torque_act(), 4108.0);\n EXPECT_EQ(cd.brake().hsa_status(), Brake::HSA_OFF);\n EXPECT_DOUBLE_EQ(cd.brake().wheel_torque_act(), 18500.0);\n EXPECT_FALSE(cd.vehicle_spd().is_vehicle_standstill());\n EXPECT_DOUBLE_EQ(cd.vehicle_spd().acc_est(), 0.665);\n}\n\n} \/\/ namespace lincoln\n} \/\/ namespace apollo\n} \/\/ namespace canbus\n<|endoftext|>"} {"text":"<commit_before>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"end_condition.hh\"\n\n#include <stdlib.h>\n\n#include <stdio.h> \/\/ DEBUG\n\n#ifndef DROI\n#include <glib.h>\n#endif\n\nEnd_condition::End_condition(Verdict::Verdict v, Counter c, std::string* p)\n : verdict(v), counter(c), param(p),\n param_float(-1.0), param_long(-1), param_time(-1)\n{\n switch (counter) {\n\n case STEPS:\n param_long = atol(param->c_str());\n status = true;\n break;\n\n case COVERAGE:\n param_float = atof(param->c_str());\n status = true;\n break;\n\n case STATETAG:\n \/\/ param already contains the state tag string, but it cannot be\n \/\/ converted into index (param_long) because the model is not\n \/\/ initialized\n status = true;\n break;\n\n case DURATION:\n {\n param_time = -1;\n#ifndef DROI\n char* out = NULL;\n int stat;\n std::string ss = \"date --date='\" + *param + \"' +%s.%N\";\n\n if (g_spawn_command_line_sync(ss.c_str(), &out, NULL, &stat, NULL)) {\n if (!stat) {\n \/\/ Store seconds to param_time and microseconds to param_long\n param_time = atoi(out);\n param_long = (strtod(out, NULL) - param_time) * 1000000;\n status = true;\n } else {\n errormsg = \"Parsing 'duration' parameter '\" + *param + \"' failed.\";\n errormsg += \" Date returned an error when executing '\" + ss + \"'\";\n status = false;\n }\n } else {\n errormsg = \"Parsing 'duration' parameter '\" + *param + \"' failed, could not execute '\";\n errormsg += ss + \"'\";\n status = false;\n }\n#else\n char* endp;\n long r = strtol(param->c_str(), &endp, 10);\n if (*endp == 0) {\n param_time = r;\n status = true;\n } else {\n \/\/ Error on str?\n errormsg = \"Parsing duration '\" + *param + \"' failed.\";\n status = false;\n }\n#endif\n }\n\n case NOPROGRESS:\n param_long = atol(param->c_str());\n status = true;\n break;\n\n } \/* switch (counter) ... *\/ \n}\n\nEnd_condition::~End_condition()\n{\n delete param;\n}\n<commit_msg>fix duration end condition accuracy bug<commit_after>\/*\n * fMBT, free Model Based Testing tool\n * Copyright (c) 2011, Intel Corporation.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along with\n * this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"end_condition.hh\"\n\n#include <stdlib.h>\n\n#include <stdio.h> \/\/ DEBUG\n\n#ifndef DROI\n#include <glib.h>\n#endif\n\nEnd_condition::End_condition(Verdict::Verdict v, Counter c, std::string* p)\n : verdict(v), counter(c), param(p),\n param_float(-1.0), param_long(-1), param_time(-1)\n{\n switch (counter) {\n\n case STEPS:\n param_long = atol(param->c_str());\n status = true;\n break;\n\n case COVERAGE:\n param_float = atof(param->c_str());\n status = true;\n break;\n\n case STATETAG:\n \/\/ param already contains the state tag string, but it cannot be\n \/\/ converted into index (param_long) because the model is not\n \/\/ initialized\n status = true;\n break;\n\n case DURATION:\n {\n param_time = -1;\n#ifndef DROI\n char* out = NULL;\n int stat;\n std::string ss = \"date --date='\" + *param + \"' +%s.%N\";\n\n if (g_spawn_command_line_sync(ss.c_str(), &out, NULL, &stat, NULL)) {\n if (!stat) {\n \/\/ Store seconds to param_time and microseconds to param_long\n param_time = atoi(out);\n param_long = (strtod(out, NULL) - param_time) * 1000000;\n status = true;\n } else {\n errormsg = \"Parsing 'duration' parameter '\" + *param + \"' failed.\";\n errormsg += \" Date returned an error when executing '\" + ss + \"'\";\n status = false;\n }\n } else {\n errormsg = \"Parsing 'duration' parameter '\" + *param + \"' failed, could not execute '\";\n errormsg += ss + \"'\";\n status = false;\n }\n#else\n char* endp;\n long r = strtol(param->c_str(), &endp, 10);\n if (*endp == 0) {\n param_time = r;\n status = true;\n } else {\n \/\/ Error on str?\n errormsg = \"Parsing duration '\" + *param + \"' failed.\";\n status = false;\n }\n#endif\n break;\n }\n\n case NOPROGRESS:\n param_long = atol(param->c_str());\n status = true;\n break;\n\n } \/* switch (counter) ... *\/ \n}\n\nEnd_condition::~End_condition()\n{\n delete param;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file Parser.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"Parser.h\"\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix.hpp>\n#include <boost\/spirit\/include\/support_utree.hpp>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nnamespace qi = boost::spirit::qi;\nnamespace px = boost::phoenix;\nnamespace sp = boost::spirit;\n\nvoid dev::eth::killBigints(sp::utree const& _this)\n{\n\tswitch (_this.which())\n\t{\n\tcase sp::utree_type::list_type: for (auto const& i: _this) killBigints(i); break;\n\tcase sp::utree_type::any_type: delete _this.get<bigint*>(); break;\n\tdefault:;\n\t}\n}\n\nvoid dev::eth::debugOutAST(ostream& _out, sp::utree const& _this)\n{\n\tswitch (_this.which())\n\t{\n\tcase sp::utree_type::list_type:\n\t\tswitch (_this.tag())\n\t\t{\n\t\tcase 0: _out << \"( \"; for (auto const& i: _this) { debugOutAST(_out, i); _out << \" \"; } _out << \")\"; break;\n\t\tcase 1: _out << \"@ \"; debugOutAST(_out, _this.front()); break;\n\t\tcase 2: _out << \"@@ \"; debugOutAST(_out, _this.front()); break;\n\t\tcase 3: _out << \"[ \"; debugOutAST(_out, _this.front()); _out << \" ] \"; debugOutAST(_out, _this.back()); break;\n\t\tcase 4: _out << \"[[ \"; debugOutAST(_out, _this.front()); _out << \" ]] \"; debugOutAST(_out, _this.back()); break;\n\t\tcase 5: _out << \"{ \"; for (auto const& i: _this) { debugOutAST(_out, i); _out << \" \"; } _out << \"}\"; break;\n\t\tcase 6: _out << \"$ \"; debugOutAST(_out, _this.front()); break;\n\t\tdefault:;\n\t\t}\n\n\t\tbreak;\n\tcase sp::utree_type::int_type: _out << _this.get<int>(); break;\n\tcase sp::utree_type::string_type: _out << \"\\\"\" << _this.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::string_type>>() << \"\\\"\"; break;\n\tcase sp::utree_type::symbol_type: _out << _this.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::symbol_type>>(); break;\n\tcase sp::utree_type::any_type: _out << *_this.get<bigint*>(); break;\n\tdefault: _out << \"nil\";\n\t}\n}\n\nnamespace dev { namespace eth {\nnamespace parseTreeLLL_ {\n\ntemplate<unsigned N>\nstruct tagNode\n{\n\tvoid operator()(sp::utree& n, qi::rule<string::const_iterator, qi::ascii::space_type, sp::utree()>::context_type& c) const\n\t{\n\t\t(boost::fusion::at_c<0>(c.attributes) = n).tag(N);\n\t}\n};\n\n}}}\n\nvoid dev::eth::parseTreeLLL(string const& _s, sp::utree& o_out)\n{\n\tusing qi::standard::space;\n\tusing qi::standard::space_type;\n\tusing dev::eth::parseTreeLLL_::tagNode;\n\ttypedef sp::basic_string<std::string, sp::utree_type::symbol_type> symbol_type;\n\ttypedef string::const_iterator it;\n\n\tstatic const u256 ether = u256(1000000000) * 1000000000;\n\tstatic const u256 finney = u256(1000000000) * 1000000;\n\tstatic const u256 szabo = u256(1000000000) * 1000;\n\n\tqi::rule<it, space_type, sp::utree()> element;\n\tqi::rule<it, string()> str = '\"' > qi::lexeme[+(~qi::char_(std::string(\"\\\"\") + '\\0'))] > '\"';\n\tqi::rule<it, string()> strsh = '\\'' > qi::lexeme[+(~qi::char_(std::string(\" ;$@()[]{}:\\n\\t\") + '\\0'))];\n\tqi::rule<it, symbol_type()> symbol = qi::lexeme[+(~qi::char_(std::string(\" $@[]{}:();\\\"\\x01-\\x1f\\x7f\") + '\\0'))];\n\tqi::rule<it, string()> intstr = qi::lexeme[ qi::no_case[\"0x\"][qi::_val = \"0x\"] >> *qi::char_(\"0-9a-fA-F\")[qi::_val += qi::_1]] | qi::lexeme[+qi::char_(\"0-9\")[qi::_val += qi::_1]];\n\tqi::rule<it, bigint()> integer = intstr;\n\tqi::rule<it, bigint()> multiplier = qi::lit(\"wei\")[qi::_val = 1] | qi::lit(\"szabo\")[qi::_val = szabo] | qi::lit(\"finney\")[qi::_val = finney] | qi::lit(\"ether\")[qi::_val = ether];\n\tqi::rule<it, space_type, bigint()> quantity = integer[qi::_val = qi::_1] >> -multiplier[qi::_val *= qi::_1];\n\tqi::rule<it, space_type, sp::utree()> atom = quantity[qi::_val = px::construct<sp::any_ptr>(px::new_<bigint>(qi::_1))] | (str | strsh)[qi::_val = qi::_1] | symbol[qi::_val = qi::_1];\n\tqi::rule<it, space_type, sp::utree::list_type()> seq = '{' > *element > '}';\n\tqi::rule<it, space_type, sp::utree::list_type()> mload = '@' > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> sload = qi::lit(\"@@\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> mstore = '[' > element > ']' > -qi::lit(\":\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> sstore = qi::lit(\"[[\") > element > qi::lit(\"]]\") > -qi::lit(\":\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> calldataload = qi::lit(\"$\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> list = '(' > *element > ')';\n\n\tqi::rule<it, space_type, sp::utree()> extra = sload[tagNode<2>()] | mload[tagNode<1>()] | sstore[tagNode<4>()] | mstore[tagNode<3>()] | seq[tagNode<5>()] | calldataload[tagNode<6>()];\n\telement = atom | list | extra;\n\n\tstring s;\n\ts.reserve(_s.size());\n\tbool incomment = false;\n\tbool instring = false;\n\tbool insstring = false;\n\tfor (auto i: _s)\n\t{\n\t\tif (i == ';' && !instring && !insstring)\n\t\t\tincomment = true;\n\t\telse if (i == '\\n')\n\t\t\tincomment = instring = insstring = false;\n\t\telse if (i == '\"' && !insstring)\n\t\t\tinstring = !instring;\n\t\telse if (i == '\\'')\n\t\t\tinsstring = true;\n\t\telse if (i == ' ')\n\t\t\tinsstring = false;\n\t\tif (!incomment)\n\t\t\ts.push_back(i);\n\t}\n\tauto ret = s.cbegin();\n\tqi::phrase_parse(ret, s.cend(), element, space, qi::skip_flag::dont_postskip, o_out);\n\tfor (auto i = ret; i != s.cend(); ++i)\n\t\tif (!isspace(*i))\n\t\t\tBOOST_THROW_EXCEPTION(std::exception());\n}\n\n<commit_msg>change typedef to using according to preferred coding style<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file Parser.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n\n#include \"Parser.h\"\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix.hpp>\n#include <boost\/spirit\/include\/support_utree.hpp>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nnamespace qi = boost::spirit::qi;\nnamespace px = boost::phoenix;\nnamespace sp = boost::spirit;\n\nvoid dev::eth::killBigints(sp::utree const& _this)\n{\n\tswitch (_this.which())\n\t{\n\tcase sp::utree_type::list_type: for (auto const& i: _this) killBigints(i); break;\n\tcase sp::utree_type::any_type: delete _this.get<bigint*>(); break;\n\tdefault:;\n\t}\n}\n\nvoid dev::eth::debugOutAST(ostream& _out, sp::utree const& _this)\n{\n\tswitch (_this.which())\n\t{\n\tcase sp::utree_type::list_type:\n\t\tswitch (_this.tag())\n\t\t{\n\t\tcase 0: _out << \"( \"; for (auto const& i: _this) { debugOutAST(_out, i); _out << \" \"; } _out << \")\"; break;\n\t\tcase 1: _out << \"@ \"; debugOutAST(_out, _this.front()); break;\n\t\tcase 2: _out << \"@@ \"; debugOutAST(_out, _this.front()); break;\n\t\tcase 3: _out << \"[ \"; debugOutAST(_out, _this.front()); _out << \" ] \"; debugOutAST(_out, _this.back()); break;\n\t\tcase 4: _out << \"[[ \"; debugOutAST(_out, _this.front()); _out << \" ]] \"; debugOutAST(_out, _this.back()); break;\n\t\tcase 5: _out << \"{ \"; for (auto const& i: _this) { debugOutAST(_out, i); _out << \" \"; } _out << \"}\"; break;\n\t\tcase 6: _out << \"$ \"; debugOutAST(_out, _this.front()); break;\n\t\tdefault:;\n\t\t}\n\n\t\tbreak;\n\tcase sp::utree_type::int_type: _out << _this.get<int>(); break;\n\tcase sp::utree_type::string_type: _out << \"\\\"\" << _this.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::string_type>>() << \"\\\"\"; break;\n\tcase sp::utree_type::symbol_type: _out << _this.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::symbol_type>>(); break;\n\tcase sp::utree_type::any_type: _out << *_this.get<bigint*>(); break;\n\tdefault: _out << \"nil\";\n\t}\n}\n\nnamespace dev { namespace eth {\nnamespace parseTreeLLL_ {\n\ntemplate<unsigned N>\nstruct tagNode\n{\n\tvoid operator()(sp::utree& n, qi::rule<string::const_iterator, qi::ascii::space_type, sp::utree()>::context_type& c) const\n\t{\n\t\t(boost::fusion::at_c<0>(c.attributes) = n).tag(N);\n\t}\n};\n\n}}}\n\nvoid dev::eth::parseTreeLLL(string const& _s, sp::utree& o_out)\n{\n\tusing qi::standard::space;\n\tusing qi::standard::space_type;\n\tusing dev::eth::parseTreeLLL_::tagNode;\n\tusing symbol_type = sp::basic_string<std::string, sp::utree_type::symbol_type>;\n\tusing it = string::const_iterator;\n\n\tstatic const u256 ether = u256(1000000000) * 1000000000;\n\tstatic const u256 finney = u256(1000000000) * 1000000;\n\tstatic const u256 szabo = u256(1000000000) * 1000;\n\n\tqi::rule<it, space_type, sp::utree()> element;\n\tqi::rule<it, string()> str = '\"' > qi::lexeme[+(~qi::char_(std::string(\"\\\"\") + '\\0'))] > '\"';\n\tqi::rule<it, string()> strsh = '\\'' > qi::lexeme[+(~qi::char_(std::string(\" ;$@()[]{}:\\n\\t\") + '\\0'))];\n\tqi::rule<it, symbol_type()> symbol = qi::lexeme[+(~qi::char_(std::string(\" $@[]{}:();\\\"\\x01-\\x1f\\x7f\") + '\\0'))];\n\tqi::rule<it, string()> intstr = qi::lexeme[ qi::no_case[\"0x\"][qi::_val = \"0x\"] >> *qi::char_(\"0-9a-fA-F\")[qi::_val += qi::_1]] | qi::lexeme[+qi::char_(\"0-9\")[qi::_val += qi::_1]];\n\tqi::rule<it, bigint()> integer = intstr;\n\tqi::rule<it, bigint()> multiplier = qi::lit(\"wei\")[qi::_val = 1] | qi::lit(\"szabo\")[qi::_val = szabo] | qi::lit(\"finney\")[qi::_val = finney] | qi::lit(\"ether\")[qi::_val = ether];\n\tqi::rule<it, space_type, bigint()> quantity = integer[qi::_val = qi::_1] >> -multiplier[qi::_val *= qi::_1];\n\tqi::rule<it, space_type, sp::utree()> atom = quantity[qi::_val = px::construct<sp::any_ptr>(px::new_<bigint>(qi::_1))] | (str | strsh)[qi::_val = qi::_1] | symbol[qi::_val = qi::_1];\n\tqi::rule<it, space_type, sp::utree::list_type()> seq = '{' > *element > '}';\n\tqi::rule<it, space_type, sp::utree::list_type()> mload = '@' > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> sload = qi::lit(\"@@\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> mstore = '[' > element > ']' > -qi::lit(\":\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> sstore = qi::lit(\"[[\") > element > qi::lit(\"]]\") > -qi::lit(\":\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> calldataload = qi::lit(\"$\") > element;\n\tqi::rule<it, space_type, sp::utree::list_type()> list = '(' > *element > ')';\n\n\tqi::rule<it, space_type, sp::utree()> extra = sload[tagNode<2>()] | mload[tagNode<1>()] | sstore[tagNode<4>()] | mstore[tagNode<3>()] | seq[tagNode<5>()] | calldataload[tagNode<6>()];\n\telement = atom | list | extra;\n\n\tstring s;\n\ts.reserve(_s.size());\n\tbool incomment = false;\n\tbool instring = false;\n\tbool insstring = false;\n\tfor (auto i: _s)\n\t{\n\t\tif (i == ';' && !instring && !insstring)\n\t\t\tincomment = true;\n\t\telse if (i == '\\n')\n\t\t\tincomment = instring = insstring = false;\n\t\telse if (i == '\"' && !insstring)\n\t\t\tinstring = !instring;\n\t\telse if (i == '\\'')\n\t\t\tinsstring = true;\n\t\telse if (i == ' ')\n\t\t\tinsstring = false;\n\t\tif (!incomment)\n\t\t\ts.push_back(i);\n\t}\n\tauto ret = s.cbegin();\n\tqi::phrase_parse(ret, s.cend(), element, space, qi::skip_flag::dont_postskip, o_out);\n\tfor (auto i = ret; i != s.cend(); ++i)\n\t\tif (!isspace(*i))\n\t\t\tBOOST_THROW_EXCEPTION(std::exception());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: handleinteractionrequest.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2007-11-07 10:07:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n#define INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include \"com\/sun\/star\/uno\/Exception.hpp\"\n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#endif\n#ifndef _RTL_REF_HXX_\n#include \"rtl\/ref.hxx\"\n#endif\n#ifndef _SAL_TYPES_H_\n#include \"sal\/types.h\"\n#endif\n\n#ifndef INCLUDED_UTILITY\n#include <utility>\n#define INCLUDED_UTILITY\n#endif\n\nnamespace com { namespace sun { namespace star { namespace ucb {\n class XCommandEnvironment;\n} } } }\nnamespace ucbhelper {\n class InteractionSupplyAuthentication;\n class SimpleAuthenticationRequest;\n class SimpleInteractionRequest;\n class SimpleCertificateValidationRequest;\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleInteractionRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleInteractionRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n the constant (defined in ucbhelper\/simpelinteractionrequest.hxx) that\n corresponds to the continuation selected by the interaction handler.\n The constant <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> will\n never be returned.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nsal_Int32\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleInteractionRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleAuthenticationRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleAuthenticationRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n either a pair consisting of one of the constants\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> or\n <const scope=\"ucbhelper\">CONTINUATION_RETRY<\/const> (defined in\n ucbhelper\/simpelinteractionrequest.hxx) and an empty reference, or a pair\n consisting of the constant\n <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> and a reference to\n an <type scope=\"ucbhelper\">InteractionSupplyAuthentication<\/type> that\n contains the supplied data.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nstd::pair< sal_Int32,\n rtl::Reference< ucbhelper::InteractionSupplyAuthentication > >\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleAuthenticationRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleCertificateValidationRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleCertificateValidationRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n the constant (defined in ucbhelper\/simpelinteractionrequest.hxx) that\n corresponds to the continuation selected by the interaction handler.\n The constant <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> will\n never be returned.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nsal_Int32\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleCertificateValidationRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n#endif \/\/ INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.22); FILE MERGED 2008\/04\/01 16:02:44 thb 1.3.22.3: #i85898# Stripping all external header guards 2008\/04\/01 12:58:43 thb 1.3.22.2: #i85898# Stripping all external header guards 2008\/03\/31 15:31:28 rt 1.3.22.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: handleinteractionrequest.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n#define INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n\n#include \"com\/sun\/star\/uno\/Exception.hpp\"\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"sal\/types.h\"\n\n#ifndef INCLUDED_UTILITY\n#include <utility>\n#define INCLUDED_UTILITY\n#endif\n\nnamespace com { namespace sun { namespace star { namespace ucb {\n class XCommandEnvironment;\n} } } }\nnamespace ucbhelper {\n class InteractionSupplyAuthentication;\n class SimpleAuthenticationRequest;\n class SimpleInteractionRequest;\n class SimpleCertificateValidationRequest;\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleInteractionRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleInteractionRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n the constant (defined in ucbhelper\/simpelinteractionrequest.hxx) that\n corresponds to the continuation selected by the interaction handler.\n The constant <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> will\n never be returned.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nsal_Int32\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleInteractionRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleAuthenticationRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleAuthenticationRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n either a pair consisting of one of the constants\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> or\n <const scope=\"ucbhelper\">CONTINUATION_RETRY<\/const> (defined in\n ucbhelper\/simpelinteractionrequest.hxx) and an empty reference, or a pair\n consisting of the constant\n <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> and a reference to\n an <type scope=\"ucbhelper\">InteractionSupplyAuthentication<\/type> that\n contains the supplied data.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nstd::pair< sal_Int32,\n rtl::Reference< ucbhelper::InteractionSupplyAuthentication > >\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleAuthenticationRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n\n\/** Pass a <type scope=\"ucbhelper\">SimpleCertificateValidationRequest<\/type> to an\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type>, and handle\n (by throwing the request as an exception) those cases where an interaction\n handler is either not available or does not handle the request.\n\n @param rRequest\n a <type scope=\"ucbhelper\">SimpleCertificateValidationRequest<\/type>. Must not be\n <NULL\/>.\n\n @param rEnvironment\n At the moment, only the\n <type scope=\"com::sun::star::task\">XInteractionHandler<\/type> part is\n used. May be <NULL\/>.\n\n @param bThrowOnAbort\n determines what is done if the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation: If\n <TRUE\/>, an appropriate\n <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> is thrown.\n If <FALSE\/>, <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> is passed\n to the caller of this function.\n\n @returns\n the constant (defined in ucbhelper\/simpelinteractionrequest.hxx) that\n corresponds to the continuation selected by the interaction handler.\n The constant <const scope=\"ucbhelper\">CONTINUATION_UNKNOWN<\/const> will\n never be returned.\n\n @throws\n <ul>\n <li>the exception specified by the request, if an interaction handler is\n either not available or does not handle the request;<\/li>\n <li>a <type scope=\"com::sun::star::ucb\">CommandFailedException<\/type> if\n the interaction handler selects a\n <const scope=\"ucbhelper\">CONTINUATION_ABORT<\/const> continuation and\n <code>bThrowOnAbort<\/code> is <TRUE\/>;<\/li>\n <li>a <type scope=\"com::sun::star::uno\">RuntimeException<\/type> if such an\n exception is thrown by code called from within this function.<\/li>\n <\/ul>\n *\/\nnamespace ucbhelper {\n\nsal_Int32\nhandleInteractionRequest(\n rtl::Reference< ucbhelper::SimpleCertificateValidationRequest > const & rRequest,\n com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > const &\n rEnvironment,\n bool bThrowOnAbort = true)\n SAL_THROW((com::sun::star::uno::Exception));\n\n}\n#endif \/\/ INCLUDED_UCBHELPER_HANDLEINTERACTIONREQUEST_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2020 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include \"sensor.h\"\n#include \"json.h\"\n\n\/*! Returns a fingerprint as JSON string. *\/\nQString SensorFingerprint::toString() const\n{\n if (endpoint == 0xFF || profileId == 0xFFFF)\n {\n return QString();\n }\n\n QVariantMap map;\n map[\"ep\"] = (double)endpoint;\n map[\"p\"] = (double)profileId;\n map[\"d\"] = (double)deviceId;\n\n if (!inClusters.empty())\n {\n QVariantList ls;\n for (uint i = 0; i < inClusters.size(); i++)\n {\n ls.append((double)inClusters[i]);\n }\n map[\"in\"] = ls;\n }\n\n if (!outClusters.empty())\n {\n QVariantList ls;\n for (uint i = 0; i < outClusters.size(); i++)\n {\n ls.append((double)outClusters[i]);\n }\n map[\"out\"] = ls;\n }\n\n return deCONZ::jsonStringFromMap(map);\n}\n\n\/*! Parses a fingerprint from JSON string.\n \\returns true on success\n*\/\nbool SensorFingerprint::readFromJsonString(const QString &json)\n{\n if (json.isEmpty())\n {\n return false;\n }\n\n bool ok = false;\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return false;\n }\n\n QVariantMap map = var.toMap();\n\n if (map.contains(\"ep\") && map.contains(\"p\") && map.contains(\"d\"))\n {\n endpoint = map[\"ep\"].toUInt(&ok);\n if (!ok) { return false; }\n profileId = map[\"p\"].toUInt(&ok);\n if (!ok) { return false; }\n deviceId = map[\"d\"].toUInt(&ok);\n if (!ok) { return false; }\n\n inClusters.clear();\n outClusters.clear();\n\n if (map.contains(\"in\") && map[\"in\"].type() == QVariant::List)\n {\n QVariantList ls = map[\"in\"].toList();\n QVariantList::const_iterator i = ls.constBegin();\n QVariantList::const_iterator end = ls.constEnd();\n for (; i != end; ++i)\n {\n quint16 clusterId = i->toUInt(&ok);\n if (ok)\n {\n inClusters.push_back(clusterId);\n }\n }\n }\n\n if (map.contains(\"out\") && map[\"out\"].type() == QVariant::List)\n {\n QVariantList ls = map[\"out\"].toList();\n QVariantList::const_iterator i = ls.constBegin();\n QVariantList::const_iterator end = ls.constEnd();\n for (; i != end; ++i)\n {\n quint16 clusterId = i->toUInt(&ok);\n if (ok)\n {\n outClusters.push_back(clusterId);\n }\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n\/*! Returns true if server cluster is part of the finger print.\n *\/\nbool SensorFingerprint::hasInCluster(quint16 clusterId) const\n{\n for (size_t i = 0; i < inClusters.size(); i++)\n {\n if (inClusters[i] == clusterId)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\/*! Returns true if server cluster is part of the finger print.\n *\/\nbool SensorFingerprint::hasOutCluster(quint16 clusterId) const\n{\n for (size_t i = 0; i < outClusters.size(); i++)\n {\n if (outClusters[i] == clusterId)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\/*! Constructor. *\/\nSensor::Sensor() :\n Resource(RSensors),\n m_deletedstate(Sensor::StateNormal),\n m_mode(ModeTwoGroups),\n m_resetRetryCount(0),\n m_rxCounter(0)\n{\n QDateTime now = QDateTime::currentDateTime();\n lastStatePush = now;\n lastConfigPush = now;\n durationDue = QDateTime();\n\n \/\/ common sensor items\n addItem(DataTypeString, RAttrName);\n addItem(DataTypeString, RAttrManufacturerName);\n addItem(DataTypeString, RAttrModelId);\n addItem(DataTypeString, RAttrType);\n addItem(DataTypeString, RAttrSwVersion);\n addItem(DataTypeString, RAttrId);\n addItem(DataTypeString, RAttrUniqueId);\n addItem(DataTypeBool, RConfigOn);\n addItem(DataTypeBool, RConfigReachable);\n addItem(DataTypeTime, RStateLastUpdated);\n\n previousDirection = 0xFF;\n previousCt = 0xFFFF;\n previousSequenceNumber = 0xFF;\n previousCommandId = 0xFF;\n}\n\n\/*! Returns the sensor deleted state.\n *\/\nSensor::DeletedState Sensor::deletedState() const\n{\n return m_deletedstate;\n}\n\n\/*! Sets the sensor deleted state.\n \\param deletedState the sensor deleted state\n *\/\nvoid Sensor::setDeletedState(DeletedState deletedstate)\n{\n m_deletedstate = deletedstate;\n}\n\n\/*! Returns true if the sensor is reachable.\n *\/\nbool Sensor::isAvailable() const\n{\n const ResourceItem *i = item(RConfigReachable);\n if (i)\n {\n return i->toBool();\n }\n return true;\n}\n\n\/*! Returns the sensor name.\n *\/\nconst QString &Sensor::name() const\n{\n return item(RAttrName)->toString();\n}\n\n\/*! Sets the sensor name.\n \\param name the sensor name\n *\/\nvoid Sensor::setName(const QString &name)\n{\n item(RAttrName)->setValue(name);\n}\n\n\/*! Returns the sensor mode.\n *\/\nSensor::SensorMode Sensor::mode() const\n{\n return m_mode;\n}\n\n\/*! Sets the sensor mode (Lighting Switch).\n * 1 = Secenes\n * 2 = Groups\n * 3 = Color Temperature\n \\param mode the sensor mode\n *\/\nvoid Sensor::setMode(SensorMode mode)\n{\n m_mode = mode;\n}\n\n\/*! Returns the sensor type.\n *\/\nconst QString &Sensor::type() const\n{\n return item(RAttrType)->toString();\n}\n\n\/*! Sets the sensor type.\n \\param type the sensor type\n *\/\nvoid Sensor::setType(const QString &type)\n{\n item(RAttrType)->setValue(type);\n}\n\n\/*! Returns the sensor modelId.\n *\/\nconst QString &Sensor::modelId() const\n{\n return item(RAttrModelId)->toString();\n}\n\n\/*! Sets the sensor modelId.\n \\param mid the sensor modelId\n *\/\nvoid Sensor::setModelId(const QString &mid)\n{\n item(RAttrModelId)->setValue(mid.trimmed());\n}\n\n\/*! Returns the resetRetryCount.\n *\/\nuint8_t Sensor::resetRetryCount() const\n{\n return m_resetRetryCount;\n}\n\n\/*! Sets the resetRetryCount.\n \\param resetRetryCount the resetRetryCount\n *\/\nvoid Sensor::setResetRetryCount(uint8_t resetRetryCount)\n{\n m_resetRetryCount = resetRetryCount;\n}\n\n\/*! Returns the zdpResetSeq number.\n *\/\nuint8_t Sensor::zdpResetSeq() const\n{\n return m_zdpResetSeq;\n}\n\n\/*! Sets the zdpResetSeq number.\n \\param resetRetryCount the resetRetryCount\n *\/\nvoid Sensor::setZdpResetSeq(uint8_t zdpResetSeq)\n{\n m_zdpResetSeq = zdpResetSeq;\n}\n\nvoid Sensor::updateStateTimestamp()\n{\n ResourceItem *i = item(RStateLastUpdated);\n if (i)\n {\n i->setValue(QDateTime::currentDateTimeUtc());\n m_rxCounter++;\n }\n}\n\n\/*! Increments the number of received commands during this session. *\/\nvoid Sensor::incrementRxCounter()\n{\n m_rxCounter++;\n}\n\n\/*! Returns number of received commands during this session. *\/\nint Sensor::rxCounter() const\n{\n return m_rxCounter;\n}\n\n\/*! Returns the sensor manufacturer.\n *\/\nconst QString &Sensor::manufacturer() const\n{\n return item(RAttrManufacturerName)->toString();\n}\n\n\/*! Sets the sensor manufacturer.\n \\param manufacturer the sensor manufacturer\n *\/\nvoid Sensor::setManufacturer(const QString &manufacturer)\n{\n item(RAttrManufacturerName)->setValue(manufacturer.trimmed());\n}\n\n\/*! Returns the sensor software version.\n Not supported for ZGP Sensortype\n *\/\nconst QString &Sensor::swVersion() const\n{\n return item(RAttrSwVersion)->toString();\n}\n\n\/*! Sets the sensor software version.\n \\param swVersion the sensor software version\n *\/\nvoid Sensor::setSwVersion(const QString &swversion)\n{\n item(RAttrSwVersion)->setValue(swversion.trimmed());\n}\n\n\/*! Transfers state into JSONString.\n *\/\nQString Sensor::stateToString()\n{\n QVariantMap map;\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"state\/\", 6) == 0)\n {\n const char *key = item->descriptor().suffix + 6;\n map[key] = item->toVariant();\n }\n }\n\n return Json::serialize(map);\n}\n\n\/*! Transfers config into JSONString.\n *\/\nQString Sensor::configToString()\n{\n QVariantMap map;\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"config\/\", 7) == 0)\n {\n const char *key = item->descriptor().suffix + 7;\n map[key] = item->toVariant();\n }\n }\n\n return Json::serialize(map);\n}\n\n\/*! Parse the sensor state from a JSON string. *\/\nvoid Sensor::jsonToState(const QString &json)\n{\n bool ok;\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return;\n }\n\n QVariantMap map = var.toMap();\n\n if (map.contains(\"lastset\"))\n {\n QString lastset = map[\"lastset\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime ls = QDateTime::fromString(lastset, format);\n ls.setTimeSpec(Qt::UTC);\n map[\"lastset\"] = ls;\n }\n\n \/\/ use old time stamp before deCONZ was started\n QDateTime dt = QDateTime::currentDateTime().addSecs(-120);\n if (map.contains(\"lastupdated\"))\n {\n QString lastupdated = map[\"lastupdated\"].toString();\n QString format = lastupdated.length() == 19 ? QLatin1String(\"yyyy-MM-ddTHH:mm:ss\") : QLatin1String(\"yyyy-MM-ddTHH:mm:ss.zzz\");\n QDateTime lu = QDateTime::fromString(lastupdated, format);\n if (lu < dt)\n {\n dt = lu;\n }\n lu.setTimeSpec(Qt::UTC);\n map[\"lastupdated\"] = lu;\n }\n\n if (map.contains(\"localtime\"))\n {\n QString localtime = map[\"localtime\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ss\");\n QDateTime lt = QDateTime::fromString(localtime, format);\n map[\"localtime\"] = lt;\n }\n\n if (map.contains(\"utc\"))\n {\n QString utc = map[\"utc\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime u = QDateTime::fromString(utc, format);\n u.setTimeSpec(Qt::UTC);\n map[\"utc\"] = u;\n }\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"state\/\", 6) == 0)\n {\n const char *key = item->descriptor().suffix + 6;\n\n if (map.contains(QLatin1String(key)))\n {\n item->setValue(map[key]);\n item->setTimeStamps(dt);\n }\n }\n }\n}\n\n\/*! Parse the sensor config from a JSON string. *\/\nvoid Sensor::jsonToConfig(const QString &json)\n{\n bool ok;\n\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return;\n }\n QVariantMap map = var.toMap();\n\n if (map.contains(\"lastchange_time\"))\n {\n QString lastchange_time = map[\"lastchange_time\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime lct = QDateTime::fromString(lastchange_time, format);\n lct.setTimeSpec(Qt::UTC);\n map[\"lastchange_time\"] = lct;\n }\n\n QDateTime dt = QDateTime::currentDateTime().addSecs(-120);\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (type().startsWith(QLatin1String(\"CLIP\")))\n {}\n else if (item->descriptor().suffix == RConfigReachable)\n { \/\/ set only from live data\n item->setValue(false);\n continue;\n }\n\n if (strncmp(rid.suffix, \"config\/\", 7) == 0 && rid.suffix != RConfigPending)\n {\n const char *key = item->descriptor().suffix + 7;\n\n if (map.contains(QLatin1String(key)))\n {\n QVariant val = map[key];\n\n if (val.isNull())\n {\n if (rid.suffix == RConfigOn)\n {\n map[key] = true; \/\/ default value\n setNeedSaveDatabase(true);\n }\n else\n {\n continue;\n }\n }\n\n item->setValue(map[key]);\n item->setTimeStamps(dt);\n }\n }\n }\n}\n\n\/*! Returns the sensor fingerprint. *\/\nSensorFingerprint &Sensor::fingerPrint()\n{\n return m_fingerPrint;\n}\n\n\/*! Returns the sensor fingerprint. *\/\nconst SensorFingerprint &Sensor::fingerPrint() const\n{\n return m_fingerPrint;\n}\n\nconst std::vector<Sensor::ButtonMap> Sensor::buttonMap(const QMap<QString, std::vector<Sensor::ButtonMap>> &buttonMapData, QMap<QString, QString> &buttonMapForModelId)\n{\n if (m_buttonMap.empty())\n {\n const QString &modelid = item(RAttrModelId)->toString();\n\n for (auto i = buttonMapForModelId.constBegin(); i != buttonMapForModelId.constEnd(); ++i)\n {\n if (modelid.startsWith(QString(i.key())))\n {\n m_buttonMap = buttonMapData.value(i.value());\n }\n }\n }\n\n return m_buttonMap;\n}\n\n<commit_msg>Workaround for Tuya<commit_after>\/*\n * Copyright (c) 2013-2020 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include \"sensor.h\"\n#include \"json.h\"\n\n\/*! Returns a fingerprint as JSON string. *\/\nQString SensorFingerprint::toString() const\n{\n if (endpoint == 0xFF || profileId == 0xFFFF)\n {\n return QString();\n }\n\n QVariantMap map;\n map[\"ep\"] = (double)endpoint;\n map[\"p\"] = (double)profileId;\n map[\"d\"] = (double)deviceId;\n\n if (!inClusters.empty())\n {\n QVariantList ls;\n for (uint i = 0; i < inClusters.size(); i++)\n {\n ls.append((double)inClusters[i]);\n }\n map[\"in\"] = ls;\n }\n\n if (!outClusters.empty())\n {\n QVariantList ls;\n for (uint i = 0; i < outClusters.size(); i++)\n {\n ls.append((double)outClusters[i]);\n }\n map[\"out\"] = ls;\n }\n\n return deCONZ::jsonStringFromMap(map);\n}\n\n\/*! Parses a fingerprint from JSON string.\n \\returns true on success\n*\/\nbool SensorFingerprint::readFromJsonString(const QString &json)\n{\n if (json.isEmpty())\n {\n return false;\n }\n\n bool ok = false;\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return false;\n }\n\n QVariantMap map = var.toMap();\n\n if (map.contains(\"ep\") && map.contains(\"p\") && map.contains(\"d\"))\n {\n endpoint = map[\"ep\"].toUInt(&ok);\n if (!ok) { return false; }\n profileId = map[\"p\"].toUInt(&ok);\n if (!ok) { return false; }\n deviceId = map[\"d\"].toUInt(&ok);\n if (!ok) { return false; }\n\n inClusters.clear();\n outClusters.clear();\n\n if (map.contains(\"in\") && map[\"in\"].type() == QVariant::List)\n {\n QVariantList ls = map[\"in\"].toList();\n QVariantList::const_iterator i = ls.constBegin();\n QVariantList::const_iterator end = ls.constEnd();\n for (; i != end; ++i)\n {\n quint16 clusterId = i->toUInt(&ok);\n if (ok)\n {\n inClusters.push_back(clusterId);\n }\n }\n }\n\n if (map.contains(\"out\") && map[\"out\"].type() == QVariant::List)\n {\n QVariantList ls = map[\"out\"].toList();\n QVariantList::const_iterator i = ls.constBegin();\n QVariantList::const_iterator end = ls.constEnd();\n for (; i != end; ++i)\n {\n quint16 clusterId = i->toUInt(&ok);\n if (ok)\n {\n outClusters.push_back(clusterId);\n }\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n\/*! Returns true if server cluster is part of the finger print.\n *\/\nbool SensorFingerprint::hasInCluster(quint16 clusterId) const\n{\n for (size_t i = 0; i < inClusters.size(); i++)\n {\n if (inClusters[i] == clusterId)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\/*! Returns true if server cluster is part of the finger print.\n *\/\nbool SensorFingerprint::hasOutCluster(quint16 clusterId) const\n{\n for (size_t i = 0; i < outClusters.size(); i++)\n {\n if (outClusters[i] == clusterId)\n {\n return true;\n }\n }\n\n return false;\n}\n\n\/*! Constructor. *\/\nSensor::Sensor() :\n Resource(RSensors),\n m_deletedstate(Sensor::StateNormal),\n m_mode(ModeTwoGroups),\n m_resetRetryCount(0),\n m_rxCounter(0)\n{\n QDateTime now = QDateTime::currentDateTime();\n lastStatePush = now;\n lastConfigPush = now;\n durationDue = QDateTime();\n\n \/\/ common sensor items\n addItem(DataTypeString, RAttrName);\n addItem(DataTypeString, RAttrManufacturerName);\n addItem(DataTypeString, RAttrModelId);\n addItem(DataTypeString, RAttrType);\n addItem(DataTypeString, RAttrSwVersion);\n addItem(DataTypeString, RAttrId);\n addItem(DataTypeString, RAttrUniqueId);\n addItem(DataTypeBool, RConfigOn);\n addItem(DataTypeBool, RConfigReachable);\n addItem(DataTypeTime, RStateLastUpdated);\n\n previousDirection = 0xFF;\n previousCt = 0xFFFF;\n previousSequenceNumber = 0xFF;\n previousCommandId = 0xFF;\n}\n\n\/*! Returns the sensor deleted state.\n *\/\nSensor::DeletedState Sensor::deletedState() const\n{\n return m_deletedstate;\n}\n\n\/*! Sets the sensor deleted state.\n \\param deletedState the sensor deleted state\n *\/\nvoid Sensor::setDeletedState(DeletedState deletedstate)\n{\n m_deletedstate = deletedstate;\n}\n\n\/*! Returns true if the sensor is reachable.\n *\/\nbool Sensor::isAvailable() const\n{\n const ResourceItem *i = item(RConfigReachable);\n if (i)\n {\n return i->toBool();\n }\n return true;\n}\n\n\/*! Returns the sensor name.\n *\/\nconst QString &Sensor::name() const\n{\n return item(RAttrName)->toString();\n}\n\n\/*! Sets the sensor name.\n \\param name the sensor name\n *\/\nvoid Sensor::setName(const QString &name)\n{\n item(RAttrName)->setValue(name);\n}\n\n\/*! Returns the sensor mode.\n *\/\nSensor::SensorMode Sensor::mode() const\n{\n return m_mode;\n}\n\n\/*! Sets the sensor mode (Lighting Switch).\n * 1 = Secenes\n * 2 = Groups\n * 3 = Color Temperature\n \\param mode the sensor mode\n *\/\nvoid Sensor::setMode(SensorMode mode)\n{\n m_mode = mode;\n}\n\n\/*! Returns the sensor type.\n *\/\nconst QString &Sensor::type() const\n{\n return item(RAttrType)->toString();\n}\n\n\/*! Sets the sensor type.\n \\param type the sensor type\n *\/\nvoid Sensor::setType(const QString &type)\n{\n item(RAttrType)->setValue(type);\n}\n\n\/*! Returns the sensor modelId.\n *\/\nconst QString &Sensor::modelId() const\n{\n return item(RAttrModelId)->toString();\n}\n\n\/*! Sets the sensor modelId.\n \\param mid the sensor modelId\n *\/\nvoid Sensor::setModelId(const QString &mid)\n{\n item(RAttrModelId)->setValue(mid.trimmed());\n}\n\n\/*! Returns the resetRetryCount.\n *\/\nuint8_t Sensor::resetRetryCount() const\n{\n return m_resetRetryCount;\n}\n\n\/*! Sets the resetRetryCount.\n \\param resetRetryCount the resetRetryCount\n *\/\nvoid Sensor::setResetRetryCount(uint8_t resetRetryCount)\n{\n m_resetRetryCount = resetRetryCount;\n}\n\n\/*! Returns the zdpResetSeq number.\n *\/\nuint8_t Sensor::zdpResetSeq() const\n{\n return m_zdpResetSeq;\n}\n\n\/*! Sets the zdpResetSeq number.\n \\param resetRetryCount the resetRetryCount\n *\/\nvoid Sensor::setZdpResetSeq(uint8_t zdpResetSeq)\n{\n m_zdpResetSeq = zdpResetSeq;\n}\n\nvoid Sensor::updateStateTimestamp()\n{\n ResourceItem *i = item(RStateLastUpdated);\n if (i)\n {\n i->setValue(QDateTime::currentDateTimeUtc());\n m_rxCounter++;\n }\n}\n\n\/*! Increments the number of received commands during this session. *\/\nvoid Sensor::incrementRxCounter()\n{\n m_rxCounter++;\n}\n\n\/*! Returns number of received commands during this session. *\/\nint Sensor::rxCounter() const\n{\n return m_rxCounter;\n}\n\n\/*! Returns the sensor manufacturer.\n *\/\nconst QString &Sensor::manufacturer() const\n{\n return item(RAttrManufacturerName)->toString();\n}\n\n\/*! Sets the sensor manufacturer.\n \\param manufacturer the sensor manufacturer\n *\/\nvoid Sensor::setManufacturer(const QString &manufacturer)\n{\n item(RAttrManufacturerName)->setValue(manufacturer.trimmed());\n}\n\n\/*! Returns the sensor software version.\n Not supported for ZGP Sensortype\n *\/\nconst QString &Sensor::swVersion() const\n{\n return item(RAttrSwVersion)->toString();\n}\n\n\/*! Sets the sensor software version.\n \\param swVersion the sensor software version\n *\/\nvoid Sensor::setSwVersion(const QString &swversion)\n{\n item(RAttrSwVersion)->setValue(swversion.trimmed());\n}\n\n\/*! Transfers state into JSONString.\n *\/\nQString Sensor::stateToString()\n{\n QVariantMap map;\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"state\/\", 6) == 0)\n {\n const char *key = item->descriptor().suffix + 6;\n map[key] = item->toVariant();\n }\n }\n\n return Json::serialize(map);\n}\n\n\/*! Transfers config into JSONString.\n *\/\nQString Sensor::configToString()\n{\n QVariantMap map;\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"config\/\", 7) == 0)\n {\n const char *key = item->descriptor().suffix + 7;\n map[key] = item->toVariant();\n }\n }\n\n return Json::serialize(map);\n}\n\n\/*! Parse the sensor state from a JSON string. *\/\nvoid Sensor::jsonToState(const QString &json)\n{\n bool ok;\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return;\n }\n\n QVariantMap map = var.toMap();\n\n if (map.contains(\"lastset\"))\n {\n QString lastset = map[\"lastset\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime ls = QDateTime::fromString(lastset, format);\n ls.setTimeSpec(Qt::UTC);\n map[\"lastset\"] = ls;\n }\n\n \/\/ use old time stamp before deCONZ was started\n QDateTime dt = QDateTime::currentDateTime().addSecs(-120);\n if (map.contains(\"lastupdated\"))\n {\n QString lastupdated = map[\"lastupdated\"].toString();\n QString format = lastupdated.length() == 19 ? QLatin1String(\"yyyy-MM-ddTHH:mm:ss\") : QLatin1String(\"yyyy-MM-ddTHH:mm:ss.zzz\");\n QDateTime lu = QDateTime::fromString(lastupdated, format);\n if (lu < dt)\n {\n dt = lu;\n }\n lu.setTimeSpec(Qt::UTC);\n map[\"lastupdated\"] = lu;\n }\n\n if (map.contains(\"localtime\"))\n {\n QString localtime = map[\"localtime\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ss\");\n QDateTime lt = QDateTime::fromString(localtime, format);\n map[\"localtime\"] = lt;\n }\n\n if (map.contains(\"utc\"))\n {\n QString utc = map[\"utc\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime u = QDateTime::fromString(utc, format);\n u.setTimeSpec(Qt::UTC);\n map[\"utc\"] = u;\n }\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (strncmp(rid.suffix, \"state\/\", 6) == 0)\n {\n const char *key = item->descriptor().suffix + 6;\n\n if (map.contains(QLatin1String(key)))\n {\n item->setValue(map[key]);\n item->setTimeStamps(dt);\n }\n }\n }\n}\n\n\/*! Parse the sensor config from a JSON string. *\/\nvoid Sensor::jsonToConfig(const QString &json)\n{\n bool ok;\n\n QVariant var = Json::parse(json, ok);\n\n if (!ok)\n {\n return;\n }\n QVariantMap map = var.toMap();\n\n if (map.contains(\"lastchange_time\"))\n {\n QString lastchange_time = map[\"lastchange_time\"].toString();\n QString format = QLatin1String(\"yyyy-MM-ddTHH:mm:ssZ\");\n QDateTime lct = QDateTime::fromString(lastchange_time, format);\n lct.setTimeSpec(Qt::UTC);\n map[\"lastchange_time\"] = lct;\n }\n\n QDateTime dt = QDateTime::currentDateTime().addSecs(-120);\n\n for (int i = 0; i < itemCount(); i++)\n {\n ResourceItem *item = itemForIndex(i);\n const ResourceItemDescriptor &rid = item->descriptor();\n\n if (type().startsWith(QLatin1String(\"CLIP\")))\n {}\n else if (item->descriptor().suffix == RConfigReachable)\n { \/\/ set only from live data\n item->setValue(false);\n continue;\n }\n\n if (strncmp(rid.suffix, \"config\/\", 7) == 0 && rid.suffix != RConfigPending)\n {\n const char *key = item->descriptor().suffix + 7;\n\n if (map.contains(QLatin1String(key)))\n {\n QVariant val = map[key];\n\n if (val.isNull())\n {\n if (rid.suffix == RConfigOn)\n {\n map[key] = true; \/\/ default value\n setNeedSaveDatabase(true);\n }\n else\n {\n continue;\n }\n }\n\n item->setValue(map[key]);\n item->setTimeStamps(dt);\n }\n }\n }\n}\n\n\/*! Returns the sensor fingerprint. *\/\nSensorFingerprint &Sensor::fingerPrint()\n{\n return m_fingerPrint;\n}\n\n\/*! Returns the sensor fingerprint. *\/\nconst SensorFingerprint &Sensor::fingerPrint() const\n{\n return m_fingerPrint;\n}\n\nconst std::vector<Sensor::ButtonMap> Sensor::buttonMap(const QMap<QString, std::vector<Sensor::ButtonMap>> &buttonMapData, QMap<QString, QString> &buttonMapForModelId)\n{\n if (m_buttonMap.empty())\n {\n const QString &modelid = item(RAttrModelId)->toString();\n const QString &manufacturer = item(RAttrManufacturerName)->toString();\n\n for (auto i = buttonMapForModelId.constBegin(); i != buttonMapForModelId.constEnd(); ++i)\n {\n if (modelid.startsWith(QString(i.key())))\n {\n m_buttonMap = buttonMapData.value(i.value());\n }\n }\n \/\/ Workaround for Tuya without usable modelid\n if (manufacturer == QLatin1String(\"_TZ3000_bi6lpsew\")) \/\/ can't use model id but manufacture name is device specific\n {\n m_buttonMap = buttonMapData.value(\"Tuya3gangMap\");\n }\n }\n\n return m_buttonMap;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Prediction: Fix lint error.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Piezas.h\"\n#include <vector>\n\/** CLASS Piezas\n * Class for representing a Piezas vertical board, which is roughly based\n * on the game \"Connect Four\" where pieces are placed in a column and\n * fall to the bottom of the column, or on top of other pieces already in\n * that column. For an illustration of the board, see:\n * https:\/\/en.wikipedia.org\/wiki\/Connect_Four\n *\n * Board coordinates [row,col] should match with:\n * [2,0][2,1][2,2][2,3]\n * [1,0][1,1][1,2][1,3]\n * [0,0][0,1][0,2][0,3]\n * So that a piece dropped in column 2 should take [0,2] and the next one\n * dropped in column 2 should take [1,2].\n**\/\n\nusing namespace std;\n\nvoid Piezas::toggleTurn()\n{\n if(this->turn == X)\n {\n this->turn = O;\n }\n else if(this->turn == O)\n {\n this->turn = X;\n }\n}\n\n\n\/**\n * Constructor sets an empty board (default 3 rows, 4 columns) and\n * specifies it is X's turn first\n**\/\nPiezas::Piezas()\n{\n board.resize(BOARD_ROWS);\n for(int i=0; i<BOARD_ROWS; i++)\n {\n board[i].resize(BOARD_COLS);\n for(int j=0; j<BOARD_COLS;j++)\n {\n board[i][j] = Blank;\n }\n }\n this->turn = X;\n}\n\n\n\/**\n * Resets each board location to the Blank Piece value, with a board of the\n * same size as previously specified\n**\/\nvoid Piezas::reset()\n{\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n board[i][j] = Blank;\n }\n }\n}\n\n\/**\n * Places a piece of the current turn on the board, returns what\n * piece is placed, and toggles which Piece's turn it is. dropPiece does\n * NOT allow to place a piece in a location where a column is full.\n * In that case, placePiece returns Piece Blank value\n * Out of bounds coordinates return the Piece Invalid value\n * Trying to drop a piece where it cannot be placed loses the player's turn\n**\/\nPiece Piezas::dropPiece(int column)\n{\n if(column > 3 || column < 0)\n {\n toggleTurn();\n return Invalid;\n }\n for(int i=0; i<BOARD_ROWS; i++)\n {\n if(board[i][column] == Blank)\n {\n board[i][column] = turn;\n Piece temp = turn;\n toggleTurn();\n return temp;\n }\n }\n toggleTurn();\n return Blank;\n}\n\n\/**\n * Returns what piece is at the provided coordinates, or Blank if there\n * are no pieces there, or Invalid if the coordinates are out of bounds\n**\/\nPiece Piezas::pieceAt(int row, int column)\n{\n if(row > 2 || row < 0 || column > 3 || column < 0)\n {\n return Invalid;\n }\n else return board[row][column];\n}\n\n\/**\n * Returns which Piece has won, if there is a winner, Invalid if the game\n * is not over, or Blank if the board is filled and no one has won (\"tie\").\n * For a game to be over, all locations on the board must be filled with X's\n * and O's (i.e. no remaining Blank spaces). The winner is which player has\n * the most adjacent pieces in a single line. Lines can go either vertically\n * or horizontally. If both X's and O's have the same max number of pieces in a\n * line, it is a tie.\n**\/\nPiece Piezas::gameState()\n{\n bool board_full = true;\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n if(board[i][j] == Blank)\n {\n board_full = false;\n }\n }\n }\n if(board_full == false)\n {\n return Invalid;\n }\n\n int X_count = 0;\n int max_X = 0;\n int O_count = 0;\n int max_O = 0;\n\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n if(board[i][j] == X)\n {\n X_count++;\n if(X_count > max_X)\n {\n max_X = X_count;\n }\n O_count = 0;\n }\n else if(board[i][j] == O)\n {\n O_count++;\n if(O_count > max_O)\n {\n max_O = O_count;\n }\n X_count = 0;\n }\n }\n }\n\n for(int i=0; i<BOARD_COLS; i++)\n {\n for(int j=0; j<BOARD_ROWS;j++)\n {\n if(board[i][j] == X)\n {\n X_count++;\n if(X_count > max_X)\n {\n max_X = X_count;\n }\n O_count = 0;\n }\n else if(board[i][j] == O)\n {\n O_count++;\n if(O_count > max_O)\n {\n max_O = O_count;\n }\n X_count = 0;\n }\n }\n }\n\n if(max_X > max_O)\n {\n return X;\n }\n\n else if(max_O > max_X)\n {\n return O;\n }\n\n return Blank;\n}\n<commit_msg>fifth commit<commit_after>#include \"Piezas.h\"\n#include <vector>\n\/** CLASS Piezas\n * Class for representing a Piezas vertical board, which is roughly based\n * on the game \"Connect Four\" where pieces are placed in a column and\n * fall to the bottom of the column, or on top of other pieces already in\n * that column. For an illustration of the board, see:\n * https:\/\/en.wikipedia.org\/wiki\/Connect_Four\n *\n * Board coordinates [row,col] should match with:\n * [2,0][2,1][2,2][2,3]\n * [1,0][1,1][1,2][1,3]\n * [0,0][0,1][0,2][0,3]\n * So that a piece dropped in column 2 should take [0,2] and the next one\n * dropped in column 2 should take [1,2].\n**\/\n\nusing namespace std;\n\nvoid Piezas::toggleTurn()\n{\n if(this->turn == X)\n {\n this->turn = O;\n }\n else if(this->turn == O)\n {\n this->turn = X;\n }\n}\n\n\n\/**\n * Constructor sets an empty board (default 3 rows, 4 columns) and\n * specifies it is X's turn first\n**\/\nPiezas::Piezas()\n{\n board.resize(BOARD_ROWS);\n for(int i=0; i<BOARD_ROWS; i++)\n {\n board[i].resize(BOARD_COLS);\n for(int j=0; j<BOARD_COLS;j++)\n {\n board[i][j] = Blank;\n }\n }\n this->turn = X;\n}\n\n\n\/**\n * Resets each board location to the Blank Piece value, with a board of the\n * same size as previously specified\n**\/\nvoid Piezas::reset()\n{\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n board[i][j] = Blank;\n }\n }\n}\n\n\/**\n * Places a piece of the current turn on the board, returns what\n * piece is placed, and toggles which Piece's turn it is. dropPiece does\n * NOT allow to place a piece in a location where a column is full.\n * In that case, placePiece returns Piece Blank value\n * Out of bounds coordinates return the Piece Invalid value\n * Trying to drop a piece where it cannot be placed loses the player's turn\n**\/\nPiece Piezas::dropPiece(int column)\n{\n if(column > 3 || column < 0)\n {\n toggleTurn();\n return Invalid;\n }\n for(int i=0; i<BOARD_ROWS; i++)\n {\n if(board[i][column] == Blank)\n {\n board[i][column] = turn;\n Piece temp = turn;\n toggleTurn();\n return temp;\n }\n }\n toggleTurn();\n return Blank;\n}\n\n\/**\n * Returns what piece is at the provided coordinates, or Blank if there\n * are no pieces there, or Invalid if the coordinates are out of bounds\n**\/\nPiece Piezas::pieceAt(int row, int column)\n{\n if(row > 2 || row < 0 || column > 3 || column < 0)\n {\n return Invalid;\n }\n else return board[row][column];\n}\n\n\/**\n * Returns which Piece has won, if there is a winner, Invalid if the game\n * is not over, or Blank if the board is filled and no one has won (\"tie\").\n * For a game to be over, all locations on the board must be filled with X's\n * and O's (i.e. no remaining Blank spaces). The winner is which player has\n * the most adjacent pieces in a single line. Lines can go either vertically\n * or horizontally. If both X's and O's have the same max number of pieces in a\n * line, it is a tie.\n**\/\nPiece Piezas::gameState()\n{\n bool board_full = true;\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n if(board[i][j] == Blank)\n {\n board_full = false;\n }\n }\n }\n if(board_full == false)\n {\n return Invalid;\n }\n\n int X_count = 0;\n int max_X = 0;\n int O_count = 0;\n int max_O = 0;\n\n for(int i=0; i<BOARD_ROWS; i++)\n {\n for(int j=0; j<BOARD_COLS;j++)\n {\n if(board[i][j] == X)\n {\n X_count++;\n if(X_count > max_X)\n {\n max_X = X_count;\n }\n O_count = 0;\n }\n else if(board[i][j] == O)\n {\n O_count++;\n if(O_count > max_O)\n {\n max_O = O_count;\n }\n X_count = 0;\n }\n }\n }\n\n for(int i=0; i<BOARD_COLS; i++)\n {\n for(int j=0; j<BOARD_ROWS;j++)\n {\n if(board[j][i] == X)\n {\n X_count++;\n if(X_count > max_X)\n {\n max_X = X_count;\n }\n O_count = 0;\n }\n else if(board[j][i] == O)\n {\n O_count++;\n if(O_count > max_O)\n {\n max_O = O_count;\n }\n X_count = 0;\n }\n }\n }\n\n if(max_X > max_O)\n {\n return X;\n }\n\n else if(max_O > max_X)\n {\n return O;\n }\n\n return Blank;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: sysinfo.C,v 1.5 2005\/01\/25 17:15:50 amoll Exp $\n\/\/\n\n#include <BALL\/SYSTEM\/sysinfo.h>\n\n#ifndef BALL_PLATFORM_WINDOWS\n #include <sys\/sysinfo.h>\n #include <BALL\/SYSTEM\/file.h>\n#else\n #define WIN32_LEAN_AND_MEAN\n #include <windows.h>\n#endif\n\nnamespace BALL\n{\n\tnamespace SysInfo\n\t{\n\n\t\tfloat getAvailableMemory()\n\t\t{\n\t\t\tfloat mem = getFreeMemory();\n#ifndef BALL_PLATFORM_WINDOWS\n\t\t\tmem += getBufferdMemory();\n#endif\n\t\t\treturn mem;\n\t\t}\n\n\t\tfloat getFreeMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\t\/*\n\t\t\tMEMORYSTATUS ms;\n\t\t\tGlobalMemoryStatus (&ms);\n\t\t\treturn (float) ms.dwAvailPhys;\n\t\t\t*\/\n\t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullAvailPhys\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/meminfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"MemFree:\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tline = line.after(\":\");\n\t\t\t\t\t\tline.trimLeft();\n\t\t\t\t\t\tline = line.before(\" \");\n\t\t\t\t\t\treturn line.toFloat() * 1024;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\t\/\/ sysinfo seems to return somewhat unsane values, but better than nothing...\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.freeram;\n#endif\n\t\t}\n\n\t\tfloat getTotalMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\t\/*\n\t\t\tMEMORYSTATUS ms;\n\t\t\tGlobalMemoryStatus (&ms);\n\t\t\treturn (float) ms.dwTotalPhys;\n\t\t\t*\/\n \t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullFullPhys\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.totalram;\n#endif\n\t\t}\n\n\t\tfloat getBufferdMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/meminfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"Cached:\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tline = line.after(\":\");\n\t\t\t\t\t\tline.trimLeft();\n\t\t\t\t\t\tline = line.before(\" \");\n\t\t\t\t\t\treturn line.toFloat() * 1024;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.bufferram;\n#endif\n\t\t}\n\n\t\tfloat getUptime()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\treturn -1;\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.uptime;\n#endif\n\t\t}\n\n\t\tIndex getNumberOfProcessors()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\tstruct SYSTEM_INFO sysinfo;\n\t\t\tGetSystemInfo(&sysinfo);\n\t\t\treturn sysinfo.dwNumberOfProcessors;\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/cpuinfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\tIndex nr_processors = 0;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"processor\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tnr_processors++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (nr_processors == 0) return -1;\n\n\t\t\t\treturn nr_processors;\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\treturn -1;\n#endif\n\t\t}\n\n\n\t\tfloat getFreeSwapSpace()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n \t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullAvailPageFile;\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.freeswap;\n#endif\n\n\t\t}\n\n\t} \/\/ namespace SysInfo\n} \/\/ namespace BALL\n\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: sysinfo.C,v 1.6 2005\/01\/27 12:39:15 amoll Exp $\n\/\/\n\n#include <BALL\/SYSTEM\/sysinfo.h>\n\n#ifndef BALL_PLATFORM_WINDOWS\n #include <sys\/sysinfo.h>\n #include <BALL\/SYSTEM\/file.h>\n#else\n #define WIN32_LEAN_AND_MEAN\n #include <windows.h>\n#endif\n\nnamespace BALL\n{\n\tnamespace SysInfo\n\t{\n\n\t\tfloat getAvailableMemory()\n\t\t{\n\t\t\tfloat mem = getFreeMemory();\n#ifndef BALL_PLATFORM_WINDOWS\n\t\t\tmem += getBufferdMemory();\n#endif\n\t\t\treturn mem;\n\t\t}\n\n\t\tfloat getFreeMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\t\/*\n\t\t\tMEMORYSTATUS ms;\n\t\t\tGlobalMemoryStatus (&ms);\n\t\t\treturn (float) ms.dwAvailPhys;\n\t\t\t*\/\n\t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullAvailPhys;\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/meminfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"MemFree:\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tline = line.after(\":\");\n\t\t\t\t\t\tline.trimLeft();\n\t\t\t\t\t\tline = line.before(\" \");\n\t\t\t\t\t\treturn line.toFloat() * 1024;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\t\/\/ sysinfo seems to return somewhat unsane values, but better than nothing...\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.freeram;\n#endif\n\t\t}\n\n\t\tfloat getTotalMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\t\/*\n\t\t\tMEMORYSTATUS ms;\n\t\t\tGlobalMemoryStatus (&ms);\n\t\t\treturn (float) ms.dwTotalPhys;\n\t\t\t*\/\n \t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullTotalPhys;\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.totalram;\n#endif\n\t\t}\n\n\t\tfloat getBufferdMemory()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/meminfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"Cached:\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tline = line.after(\":\");\n\t\t\t\t\t\tline.trimLeft();\n\t\t\t\t\t\tline = line.before(\" \");\n\t\t\t\t\t\treturn line.toFloat() * 1024;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.bufferram;\n#endif\n\t\t}\n\n\t\tfloat getUptime()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\treturn -1;\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.uptime;\n#endif\n\t\t}\n\n\t\tIndex getNumberOfProcessors()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n\t\t\tSYSTEM_INFO sysinfo;\n\t\t\tGetSystemInfo(&sysinfo);\n\t\t\treturn sysinfo.dwNumberOfProcessors;\n#else\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile cpuinfo(\"\/proc\/cpuinfo\");\n\t\t\t\tchar buffer[1024];\n\t\t\t\tString line;\n\t\t\t\tIndex nr_processors = 0;\n\t\t\t\twhile (!cpuinfo.eof())\n\t\t\t\t{\n\t\t\t\t\tcpuinfo.getline(buffer, 1024);\n\t\t\t\t\tline.assign(buffer);\n\t\t\t\t\tif (line.hasPrefix(\"processor\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tnr_processors++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (nr_processors == 0) return -1;\n\n\t\t\t\treturn nr_processors;\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t}\n\n\t\t\treturn -1;\n#endif\n\t\t}\n\n\n\t\tfloat getFreeSwapSpace()\n\t\t{\n#ifdef BALL_PLATFORM_WINDOWS\n \t\t\tMEMORYSTATUSEX statex;\n\t\t\tGlobalMemoryStatusEx (&statex);\n\t\t\treturn (float) statex.ullAvailPageFile;\n#else\n\t\t\tstruct sysinfo info;\n\t\t\tfloat result = sysinfo(&info);\n\t\t\tif (result == -1) return result;\n\t\t\treturn info.freeswap;\n#endif\n\n\t\t}\n\n\t} \/\/ namespace SysInfo\n} \/\/ namespace BALL\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2020 Intel Corporation. All Rights Reserved.\n\n#include \"common.h\"\n#include <common\/utilities\/string\/string-utilities.h>\n#include <ostream>\nusing namespace utilities::string;\n\ntemplate <typename T, typename std::enable_if <std::is_arithmetic<T>::value>::type* = nullptr> \/\/ check if T is arithmetic during compile\nstd::string to_str(const T& t)\n{ \n \/\/\/ The std::to_string will make the min float value equal zero, so another function is \n \/\/\/ params: a value type T \n \/\/\/ returns: a string of the given number\n std::ostringstream os;\n os << t;\n return os.str();\n}\n\ntemplate<typename T>\nstruct string_checker\n{\n std::string str;\n T value;\n bool expected_res;\n};\n\ntemplate<typename T>\nvoid check_tests(std::vector<string_checker<T>>& tests)\n{\n T value;\n for (const auto& test : tests)\n {\n CHECK(string_to_value<T>(test.str, value) == test.expected_res);\n if (test.expected_res)\n {\n CHECK(value == test.value);\n }\n }\n}\n\nTEST_CASE(\"string to value\", \"[string]\")\n{\n \/\/ int\n std::vector<string_checker<int>> int_tests;\n int_tests.push_back(string_checker<int>{ \"123\", 123, true });\n int_tests.push_back(string_checker<int>{ \"-123\", -123, true });\n int_tests.push_back(string_checker<int>{ \"-123456789\", -123456789, true });\n int_tests.push_back(string_checker<int>{ std::to_string(std::numeric_limits<int>::max())+\"0\", 0, false });\n int_tests.push_back(string_checker<int>{ std::to_string(std::numeric_limits<int>::min())+\"0\", 0, false });\n int_tests.push_back(string_checker<int>{ \"abc\", 0, false });\n\n check_tests<int>(int_tests);\n \n \/\/ unsigned int \n std::vector<string_checker<unsigned int>> uint_tests;\n uint_tests.push_back(string_checker<unsigned int>{ \"123\", 123, true });\n uint_tests.push_back(string_checker<unsigned int>{ \"123456789\", 123456789, true });\n uint_tests.push_back(string_checker<unsigned int>{ \"-123456789\", 0, false });\n uint_tests.push_back(string_checker<unsigned int>{ std::to_string(std::numeric_limits<unsigned int>::max())+\"0\", 0, false });\n uint_tests.push_back(string_checker<unsigned int>{ \"abc\", 0, false });\n\n check_tests<unsigned int>(uint_tests);\n\n \/\/ short\n std::vector<string_checker<short>> s_tests;\n s_tests.push_back(string_checker<short>{ \"123\", 123, true });\n s_tests.push_back(string_checker<short>{ \"-123\", -123, true });\n s_tests.push_back(string_checker<short>{ std::to_string(std::numeric_limits<short>::max())+\"0\", 0, false });\n s_tests.push_back(string_checker<short>{ std::to_string(std::numeric_limits<short>::min())+\"0\", 0, false });\n s_tests.push_back(string_checker<short>{ \"abc\", 0, false });\n\n check_tests<short>(s_tests);\n\n \/\/ unsigned short\n std::vector<string_checker<unsigned short>> us_tests;\n us_tests.push_back(string_checker<unsigned short>{ \"123\", 123, true });\n us_tests.push_back(string_checker<unsigned short>{ \"-123\", 0, false });\n us_tests.push_back(string_checker<unsigned short>{std::to_string(std::numeric_limits<unsigned short>::max())+\"0\", 0, false });\n us_tests.push_back(string_checker<unsigned short>{ \"abc\", 0, false });\n\n check_tests<unsigned short>(us_tests);\n\n \/\/ long\n std::vector<string_checker<long>> l_tests;\n l_tests.push_back(string_checker<long>{ \"123\", 123, true });\n l_tests.push_back(string_checker<long>{ \"-123\", -123, true });\n l_tests.push_back(string_checker<long>{ \"-123456789\", -123456789, true });\n l_tests.push_back(string_checker<long>{ std::to_string(std::numeric_limits<long>::max())+\"0\", 0, false });\n l_tests.push_back(string_checker<long>{ std::to_string(std::numeric_limits<long>::min())+\"0\", 0, false });\n l_tests.push_back(string_checker<long>{ \"abc\", 0, false });\n\n check_tests<long>(l_tests);\n\n \/\/ long long\n std::vector<string_checker<long long>> ll_tests;\n ll_tests.push_back(string_checker<long long>{ \"123\", 123, true });\n ll_tests.push_back(string_checker<long long>{ \"-123\", -123, true });\n ll_tests.push_back(string_checker<long long>{ \"12345\", 12345, true });\n ll_tests.push_back(string_checker<long long>{ \"-12345\", -12345, true });\n ll_tests.push_back(string_checker<long long>{ std::to_string(std::numeric_limits<long long>::max())+\"0\", 0, false });\n ll_tests.push_back(string_checker<long long>{ std::to_string(std::numeric_limits<long long>::min()) + \"0\", 0, false });\n ll_tests.push_back(string_checker<long long>{ \"abc\", 0, false });\n\n check_tests<long long>(ll_tests);\n\n \/\/ ungined long long\n std::vector<string_checker<unsigned long long>> ull_tests;\n ull_tests.push_back(string_checker<unsigned long long>{ \"123\", 123, true });\n ull_tests.push_back(string_checker<unsigned long long>{ \"123456789\", 123456789, true });\n ull_tests.push_back(string_checker<unsigned long long>{ \"-123456789\", 0, false });\n ull_tests.push_back(string_checker<unsigned long long>{ std::to_string(std::numeric_limits<unsigned long long>::max())+\"0\", 0, false });\n ull_tests.push_back(string_checker<unsigned long long>{ \"abc\", 0, false });\n\n check_tests<unsigned long long>(ull_tests);\n\n \/\/ float\n std::vector<string_checker<float>> f_tests;\n f_tests.push_back(string_checker<float>{ \"1.23456789\", 1.23456789f, true });\n f_tests.push_back(string_checker<float>{ \"2.12121212\", 2.12121212f, true });\n f_tests.push_back(string_checker<float>{ \"-1.23456789\", -1.23456789f, true });\n f_tests.push_back(string_checker<float>{ \"-2.12121212\", -2.12121212f, true });\n f_tests.push_back(string_checker<float>{ \"INF\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"-INF\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::max()) + \"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::min())+\"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::lowest())+\"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"NaN\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"abc\", 0.f, false });\n \n check_tests<float>(f_tests);\n\n \/\/ double\n std::vector<string_checker<double>> d_tests;\n d_tests.push_back(string_checker<double>{ \"1.2345\", 1.2345, true });\n d_tests.push_back(string_checker<double>{ \"2.12121212\", 2.12121212, true });\n d_tests.push_back(string_checker<double>{ \"-1.2345\", -1.2345, true });\n d_tests.push_back(string_checker<double>{ \"-2.12121212\", -2.12121212, true });\n d_tests.push_back(string_checker<double>{ \"INF\", 0., false });\n d_tests.push_back(string_checker<double>{ \"-INF\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::max())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::min())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::lowest())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ \"NaN\", 0., false });\n d_tests.push_back(string_checker<double>{ \"abc\", 0., false });\n\n check_tests<double>(d_tests);\n\n \/\/ long double\n std::vector<string_checker<long double>> ld_tests;\n ld_tests.push_back(string_checker<long double>{ \"1.23456789\", 1.23456789, true });\n ld_tests.push_back(string_checker<long double>{ \"-1.23456789\", -1.23456789, true });\n ld_tests.push_back(string_checker<long double>{ \"2.12121212\", 2.12121212, true });\n ld_tests.push_back(string_checker<long double>{ \"-2.12121212\", -2.12121212, true });\n ld_tests.push_back(string_checker<long double>{ \"INF\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"-INF\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::max())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::min())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::lowest())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"NaN\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"abc\", 0., false });\n\n check_tests<long double>(ld_tests);\n}\n<commit_msg>adjustments for string_to_num unit-test<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2020 Intel Corporation. All Rights Reserved.\n\n#include \"common.h\"\n#include <common\/utilities\/string\/string-utilities.h>\n#include <ostream>\nusing namespace utilities::string;\n\ntemplate <typename T, typename std::enable_if <std::is_arithmetic<T>::value>::type* = nullptr> \/\/ check if T is arithmetic during compile\nstd::string to_str(const T& t)\n{ \n \/\/\/ The std::to_string will make the min float value equal zero, so another function is \n \/\/\/ params: a value type T \n \/\/\/ returns: a string of the given number\n std::ostringstream os;\n os << t;\n return os.str();\n}\n\ntemplate<typename T>\nstruct string_checker\n{\n std::string str;\n T value;\n bool expected_res;\n};\n\ntemplate<typename T>\nvoid check_tests(std::vector<string_checker<T>>& tests)\n{\n T value;\n for (const auto test : tests)\n {\n CAPTURE(test.str);\n CAPTURE(test.expected_res);\n CHECK(string_to_value<T>(test.str, value) == test.expected_res);\n if (test.expected_res)\n {\n CAPTURE(value);\n CAPTURE(test.value);\n if (std::is_integral<T>::value)\n CHECK(value == test.value);\n else \/\/ floating-point\n {\n CHECK(value == Approx(test.value));\n }\n }\n }\n}\n\nTEST_CASE(\"string to value\", \"[string]\")\n{\n \/\/ int\n std::vector<string_checker<int>> int_tests;\n int_tests.push_back(string_checker<int>{ \"123\", 123, true });\n int_tests.push_back(string_checker<int>{ \"-123\", -123, true });\n int_tests.push_back(string_checker<int>{ \"-123456789\", -123456789, true });\n int_tests.push_back(string_checker<int>{ std::to_string(std::numeric_limits<int>::max())+\"0\", 0, false });\n int_tests.push_back(string_checker<int>{ std::to_string(std::numeric_limits<int>::min())+\"0\", 0, false });\n int_tests.push_back(string_checker<int>{ \"abc\", 0, false });\n\n check_tests<int>(int_tests);\n \n \/\/ unsigned int \n std::vector<string_checker<unsigned int>> uint_tests;\n uint_tests.push_back(string_checker<unsigned int>{ \"123\", 123, true });\n uint_tests.push_back(string_checker<unsigned int>{ \"123456789\", 123456789, true });\n uint_tests.push_back(string_checker<unsigned int>{ \"-123456789\", 0, false });\n uint_tests.push_back(string_checker<unsigned int>{ std::to_string(std::numeric_limits<unsigned int>::max())+\"0\", 0, false });\n uint_tests.push_back(string_checker<unsigned int>{ \"abc\", 0, false });\n\n check_tests<unsigned int>(uint_tests);\n\n \/\/ short\n std::vector<string_checker<short>> s_tests;\n s_tests.push_back(string_checker<short>{ \"123\", 123, true });\n s_tests.push_back(string_checker<short>{ \"-123\", -123, true });\n s_tests.push_back(string_checker<short>{ std::to_string(std::numeric_limits<short>::max())+\"0\", 0, false });\n s_tests.push_back(string_checker<short>{ std::to_string(std::numeric_limits<short>::min())+\"0\", 0, false });\n s_tests.push_back(string_checker<short>{ \"abc\", 0, false });\n\n check_tests<short>(s_tests);\n\n \/\/ unsigned short\n std::vector<string_checker<unsigned short>> us_tests;\n us_tests.push_back(string_checker<unsigned short>{ \"123\", 123, true });\n us_tests.push_back(string_checker<unsigned short>{ \"-123\", 0, false });\n us_tests.push_back(string_checker<unsigned short>{std::to_string(std::numeric_limits<unsigned short>::max())+\"0\", 0, false });\n us_tests.push_back(string_checker<unsigned short>{ \"abc\", 0, false });\n\n check_tests<unsigned short>(us_tests);\n\n \/\/ long\n std::vector<string_checker<long>> l_tests;\n l_tests.push_back(string_checker<long>{ \"123\", 123, true });\n l_tests.push_back(string_checker<long>{ \"-123\", -123, true });\n l_tests.push_back(string_checker<long>{ \"-123456789\", -123456789, true });\n l_tests.push_back(string_checker<long>{ std::to_string(std::numeric_limits<long>::max())+\"0\", 0, false });\n l_tests.push_back(string_checker<long>{ std::to_string(std::numeric_limits<long>::min())+\"0\", 0, false });\n l_tests.push_back(string_checker<long>{ \"abc\", 0, false });\n\n check_tests<long>(l_tests);\n\n \/\/ long long\n std::vector<string_checker<long long>> ll_tests;\n ll_tests.push_back(string_checker<long long>{ \"123\", 123, true });\n ll_tests.push_back(string_checker<long long>{ \"-123\", -123, true });\n ll_tests.push_back(string_checker<long long>{ \"12345\", 12345, true });\n ll_tests.push_back(string_checker<long long>{ \"-12345\", -12345, true });\n ll_tests.push_back(string_checker<long long>{ std::to_string(std::numeric_limits<long long>::max())+\"0\", 0, false });\n ll_tests.push_back(string_checker<long long>{ std::to_string(std::numeric_limits<long long>::min()) + \"0\", 0, false });\n ll_tests.push_back(string_checker<long long>{ \"abc\", 0, false });\n\n check_tests<long long>(ll_tests);\n\n \/\/ ungined long long\n std::vector<string_checker<unsigned long long>> ull_tests;\n ull_tests.push_back(string_checker<unsigned long long>{ \"123\", 123, true });\n ull_tests.push_back(string_checker<unsigned long long>{ \"123456789\", 123456789, true });\n ull_tests.push_back(string_checker<unsigned long long>{ \"-123456789\", 0, false });\n ull_tests.push_back(string_checker<unsigned long long>{ std::to_string(std::numeric_limits<unsigned long long>::max())+\"0\", 0, false });\n ull_tests.push_back(string_checker<unsigned long long>{ \"abc\", 0, false });\n\n check_tests<unsigned long long>(ull_tests);\n\n \/\/ float\n std::vector<string_checker<float>> f_tests;\n f_tests.push_back(string_checker<float>{ \"1.23456789\", 1.23456789f, true });\n f_tests.push_back(string_checker<float>{ \"2.12121212\", 2.12121212f, true });\n f_tests.push_back(string_checker<float>{ \"-1.23456789\", -1.23456789f, true });\n f_tests.push_back(string_checker<float>{ \"-2.12121212\", -2.12121212f, true });\n f_tests.push_back(string_checker<float>{ \"INF\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"-INF\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::max()) + \"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::min())+\"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ to_str(std::numeric_limits<float>::lowest())+\"0\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"NaN\", 0.f, false });\n f_tests.push_back(string_checker<float>{ \"abc\", 0.f, false });\n\n check_tests<float>(f_tests);\n\n \/\/ double\n std::vector<string_checker<double>> d_tests;\n d_tests.push_back(string_checker<double>{ \"9.876543\", 9.876543, true });\n d_tests.push_back(string_checker<double>{ \"2.12121212\", 2.12121212, true });\n d_tests.push_back(string_checker<double>{ \"-1.234598765\", -1.234598765, true });\n d_tests.push_back(string_checker<double>{ \"-2.12121212\", -2.12121212, true });\n d_tests.push_back(string_checker<double>{ \"INF\", 0., false });\n d_tests.push_back(string_checker<double>{ \"-INF\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::max())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::min())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ to_str(std::numeric_limits<double>::lowest())+\"0\", 0., false });\n d_tests.push_back(string_checker<double>{ \"NaN\", 0., false });\n d_tests.push_back(string_checker<double>{ \"abc\", 0., false });\n\n check_tests<double>(d_tests);\n\n \/\/ long double\n std::vector<string_checker<long double>> ld_tests;\n ld_tests.push_back(string_checker<long double>{ \"12345.6789123456789\", 12345.6789123456789, true });\n ld_tests.push_back(string_checker<long double>{ \"5432.123456789\", 5432.123456789, true });\n ld_tests.push_back(string_checker<long double>{ \"-12345678.23456789\", -12345678.23456789, true });\n ld_tests.push_back(string_checker<long double>{ \"INF\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"-INF\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::max())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::min())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ to_str(std::numeric_limits<long double>::lowest())+\"0\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"NaN\", 0., false });\n ld_tests.push_back(string_checker<long double>{ \"abc\", 0., false });\n\n check_tests<long double>(ld_tests);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n *\n * Copyright (C) 2012 One Laptop per Child Association\n *\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n\/\/ This file is based on mkeyboardstatetracker.cpp from libmeegotouch\n\n#include <QSocketNotifier>\n\n#include <libudev.h>\n#include <linux\/input.h>\n\n#include \"mimhwkeyboardtracker.h\"\n#include \"mimhwkeyboardtracker_p.h\"\n\n\/* bit array ops *\/\n#define BITS2BYTES(x) ((((x) - 1) \/ 8) + 1)\n#define TEST_BIT(bit, array) (array[(bit) \/ 8] & (1 << (bit) % 8))\n\nnamespace {\n const char * const keyboardPresent(\"\/maemo\/InternalKeyboard\/Present\");\n const char * const keyboardOpen(\"\/maemo\/InternalKeyboard\/Open\");\n}\n\nMImHwKeyboardTrackerPrivate::MImHwKeyboardTrackerPrivate(MImHwKeyboardTracker *q_ptr) :\n#ifdef HAVE_CONTEXTSUBSCRIBER\n keyboardOpenProperty(),\n#elif defined(Q_WS_MAEMO_5)\n keyboardOpenConf(\"\/system\/osso\/af\/slide-open\"),\n#else\n evdevTabletModePending(-1),\n#endif\n present(false)\n{\n#ifdef HAVE_CONTEXTSUBSCRIBER\n ContextProperty keyboardPresentProperty(keyboardPresent);\n keyboardOpenProperty.reset(new ContextProperty(keyboardOpen));\n keyboardPresentProperty.waitForSubscription(true);\n keyboardOpenProperty->waitForSubscription(true);\n present = keyboardPresentProperty.value().toBool();\n if (present) {\n QObject::connect(keyboardOpenProperty.data(), SIGNAL(valueChanged()),\n q_ptr, SIGNAL(stateChanged()));\n } else {\n keyboardOpenProperty.reset();\n }\n#elif defined(Q_WS_MAEMO_5)\n present = true;\n QObject::connect(&keyboardOpenConf, SIGNAL(valueChanged()),\n q_ptr, SIGNAL(stateChanged()));\n#else\n Q_UNUSED(q_ptr);\n QObject::connect(this, SIGNAL(stateChanged()),\n q_ptr, SIGNAL(stateChanged()));\n\n detectEvdev();\n#endif\n}\n\nvoid MImHwKeyboardTrackerPrivate::detectEvdev()\n{\n \/\/ Use udev to enumerate all input devices, using evdev on each device to\n \/\/ find the first device offering a SW_TABLET_MODE switch. If found, this\n \/\/ switch is used to determine keyboard presence.\n\n struct udev_list_entry *device;\n struct udev_list_entry *devices;\n\n struct udev *udev = udev_new();\n if (!udev)\n return;\n\n struct udev_enumerate *enumerate = udev_enumerate_new(udev);\n if (!enumerate) {\n udev_unref(udev);\n return;\n }\n\n udev_enumerate_add_match_subsystem(enumerate, \"input\");\n udev_enumerate_add_match_property(enumerate, \"ID_INPUT\", \"1\");\n udev_enumerate_scan_devices(enumerate);\n devices = udev_enumerate_get_list_entry(enumerate);\n\n udev_list_entry_foreach(device, devices) {\n const char *syspath = udev_list_entry_get_name(device);\n struct udev_device *udev_device =\n udev_device_new_from_syspath(udev, syspath);\n const char *device = udev_device_get_devnode(udev_device);\n\n if (device)\n tryEvdevDevice(device);\n\n udev_device_unref(udev_device);\n if (present)\n break;\n }\n udev_enumerate_unref(enumerate);\n udev_unref(udev);\n}\n\nvoid MImHwKeyboardTrackerPrivate::evdevEvent()\n{\n \/\/ Parse the evdev event and look for SW_TABLET_MODE status.\n\n struct input_event ev;\n\n qint64 len = evdevFile->read((char *) &ev, sizeof(ev));\n if (len != sizeof(ev))\n return;\n\n \/\/ We wait for a SYN before \"committing\" the new state, just in case.\n if (ev.type == EV_SW && ev.code == SW_TABLET_MODE) {\n evdevTabletModePending = ev.value;\n } else if (ev.type == EV_SYN && ev.code == SYN_REPORT\n && evdevTabletModePending != -1) {\n evdevTabletMode = evdevTabletModePending;\n evdevTabletModePending = -1;\n Q_EMIT stateChanged();\n }\n\n}\n\nvoid MImHwKeyboardTrackerPrivate::tryEvdevDevice(const char *device)\n{\n QFile *qfile = new QFile(this);\n unsigned char evbits[BITS2BYTES(EV_MAX)];\n int fd;\n\n qfile->setFileName(device);\n if (!qfile->open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {\n delete qfile;\n return;\n }\n\n fd = qfile->handle();\n if (fd == -1) {\n delete qfile;\n return;\n }\n\n if (ioctl(fd, EVIOCGBIT(0, EV_MAX), evbits) < 0) {\n delete qfile;\n return;\n }\n\n \/\/ Check that this input device has switches\n if (!TEST_BIT(EV_SW, evbits)) {\n delete qfile;\n return;\n }\n\n unsigned char swbit[BITS2BYTES(EV_MAX)];\n if (ioctl(fd, EVIOCGBIT(EV_SW, SW_CNT), swbit) < 0) {\n delete qfile;\n return;\n }\n\n \/\/ Check that there is a tablet mode switch here\n if (!TEST_BIT(SW_TABLET_MODE, swbit)) {\n delete qfile;\n return;\n }\n\n \/\/ Found an appropriate device - start monitoring it\n QSocketNotifier *sn = new QSocketNotifier(fd, QSocketNotifier::Read, qfile);\n sn->setEnabled(true);\n QObject::connect(sn, SIGNAL(activated(int)), this, SLOT(evdevEvent()));\n\n evdevFile = qfile;\n present = true;\n\n \/\/ Initialise initial tablet mode state\n unsigned long state[BITS2BYTES(SW_MAX)];\n if (ioctl(fd, EV_SW, state) < 0)\n return;\n\n evdevTabletMode = TEST_BIT(SW_TABLET_MODE, state);\n}\n\nMImHwKeyboardTrackerPrivate::~MImHwKeyboardTrackerPrivate()\n{\n}\n\nMImHwKeyboardTracker::MImHwKeyboardTracker()\n : QObject(),\n d_ptr(new MImHwKeyboardTrackerPrivate(this))\n{\n}\n\nMImHwKeyboardTracker::~MImHwKeyboardTracker()\n{\n}\n\nbool MImHwKeyboardTracker::isPresent() const\n{\n Q_D(const MImHwKeyboardTracker);\n\n return d->present;\n}\n\nbool MImHwKeyboardTracker::isOpen() const\n{\n Q_D(const MImHwKeyboardTracker);\n\n if (!d->present) {\n return false;\n }\n\n#ifdef HAVE_CONTEXTSUBSCRIBER\n return d->keyboardOpenProperty->value().toBool();\n#elif defined(Q_WS_MAEMO_5)\n return d->keyboardOpenConf.value().toBool();\n#else\n \/\/ If we found a talet mode switch, we report that the hardware keyboard\n \/\/ is available when the system is not in tablet mode (switch closed),\n \/\/ and is not available otherwise (switch open).\n if (d->evdevFile)\n return !d->evdevTabletMode;\n\n return false;\n#endif\n}\n<commit_msg>Fixes: MALIIT#197 - Read initial SW_TABLET_MODE state correctly<commit_after>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n *\n * Copyright (C) 2012 One Laptop per Child Association\n *\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n\/\/ This file is based on mkeyboardstatetracker.cpp from libmeegotouch\n\n#include <QSocketNotifier>\n\n#include <libudev.h>\n#include <linux\/input.h>\n\n#include \"mimhwkeyboardtracker.h\"\n#include \"mimhwkeyboardtracker_p.h\"\n\n\/* bit array ops *\/\n#define BITS2BYTES(x) ((((x) - 1) \/ 8) + 1)\n#define TEST_BIT(bit, array) (array[(bit) \/ 8] & (1 << (bit) % 8))\n\nnamespace {\n const char * const keyboardPresent(\"\/maemo\/InternalKeyboard\/Present\");\n const char * const keyboardOpen(\"\/maemo\/InternalKeyboard\/Open\");\n}\n\nMImHwKeyboardTrackerPrivate::MImHwKeyboardTrackerPrivate(MImHwKeyboardTracker *q_ptr) :\n#ifdef HAVE_CONTEXTSUBSCRIBER\n keyboardOpenProperty(),\n#elif defined(Q_WS_MAEMO_5)\n keyboardOpenConf(\"\/system\/osso\/af\/slide-open\"),\n#else\n evdevTabletModePending(-1),\n evdevTabletMode(0),\n#endif\n present(false)\n{\n#ifdef HAVE_CONTEXTSUBSCRIBER\n ContextProperty keyboardPresentProperty(keyboardPresent);\n keyboardOpenProperty.reset(new ContextProperty(keyboardOpen));\n keyboardPresentProperty.waitForSubscription(true);\n keyboardOpenProperty->waitForSubscription(true);\n present = keyboardPresentProperty.value().toBool();\n if (present) {\n QObject::connect(keyboardOpenProperty.data(), SIGNAL(valueChanged()),\n q_ptr, SIGNAL(stateChanged()));\n } else {\n keyboardOpenProperty.reset();\n }\n#elif defined(Q_WS_MAEMO_5)\n present = true;\n QObject::connect(&keyboardOpenConf, SIGNAL(valueChanged()),\n q_ptr, SIGNAL(stateChanged()));\n#else\n Q_UNUSED(q_ptr);\n QObject::connect(this, SIGNAL(stateChanged()),\n q_ptr, SIGNAL(stateChanged()));\n\n detectEvdev();\n#endif\n}\n\nvoid MImHwKeyboardTrackerPrivate::detectEvdev()\n{\n \/\/ Use udev to enumerate all input devices, using evdev on each device to\n \/\/ find the first device offering a SW_TABLET_MODE switch. If found, this\n \/\/ switch is used to determine keyboard presence.\n\n struct udev_list_entry *device;\n struct udev_list_entry *devices;\n\n struct udev *udev = udev_new();\n if (!udev)\n return;\n\n struct udev_enumerate *enumerate = udev_enumerate_new(udev);\n if (!enumerate) {\n udev_unref(udev);\n return;\n }\n\n udev_enumerate_add_match_subsystem(enumerate, \"input\");\n udev_enumerate_add_match_property(enumerate, \"ID_INPUT\", \"1\");\n udev_enumerate_scan_devices(enumerate);\n devices = udev_enumerate_get_list_entry(enumerate);\n\n udev_list_entry_foreach(device, devices) {\n const char *syspath = udev_list_entry_get_name(device);\n struct udev_device *udev_device =\n udev_device_new_from_syspath(udev, syspath);\n const char *device = udev_device_get_devnode(udev_device);\n\n if (device)\n tryEvdevDevice(device);\n\n udev_device_unref(udev_device);\n if (present)\n break;\n }\n udev_enumerate_unref(enumerate);\n udev_unref(udev);\n}\n\nvoid MImHwKeyboardTrackerPrivate::evdevEvent()\n{\n \/\/ Parse the evdev event and look for SW_TABLET_MODE status.\n\n struct input_event ev;\n\n qint64 len = evdevFile->read((char *) &ev, sizeof(ev));\n if (len != sizeof(ev))\n return;\n\n \/\/ We wait for a SYN before \"committing\" the new state, just in case.\n if (ev.type == EV_SW && ev.code == SW_TABLET_MODE) {\n evdevTabletModePending = ev.value;\n } else if (ev.type == EV_SYN && ev.code == SYN_REPORT\n && evdevTabletModePending != -1) {\n evdevTabletMode = evdevTabletModePending;\n evdevTabletModePending = -1;\n Q_EMIT stateChanged();\n }\n\n}\n\nvoid MImHwKeyboardTrackerPrivate::tryEvdevDevice(const char *device)\n{\n QFile *qfile = new QFile(this);\n unsigned char evbits[BITS2BYTES(EV_MAX)];\n int fd;\n\n qfile->setFileName(device);\n if (!qfile->open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {\n delete qfile;\n return;\n }\n\n fd = qfile->handle();\n if (fd == -1) {\n delete qfile;\n return;\n }\n\n if (ioctl(fd, EVIOCGBIT(0, EV_MAX), evbits) < 0) {\n delete qfile;\n return;\n }\n\n \/\/ Check that this input device has switches\n if (!TEST_BIT(EV_SW, evbits)) {\n delete qfile;\n return;\n }\n\n unsigned char swbit[BITS2BYTES(EV_MAX)];\n if (ioctl(fd, EVIOCGBIT(EV_SW, SW_CNT), swbit) < 0) {\n delete qfile;\n return;\n }\n\n \/\/ Check that there is a tablet mode switch here\n if (!TEST_BIT(SW_TABLET_MODE, swbit)) {\n delete qfile;\n return;\n }\n\n \/\/ Found an appropriate device - start monitoring it\n QSocketNotifier *sn = new QSocketNotifier(fd, QSocketNotifier::Read, qfile);\n sn->setEnabled(true);\n QObject::connect(sn, SIGNAL(activated(int)), this, SLOT(evdevEvent()));\n\n evdevFile = qfile;\n present = true;\n\n \/\/ Initialise initial tablet mode state\n unsigned long state[BITS2BYTES(SW_MAX)];\n if (ioctl(fd, EVIOCGSW(SW_MAX), state) < 0)\n return;\n\n evdevTabletMode = TEST_BIT(SW_TABLET_MODE, state);\n}\n\nMImHwKeyboardTrackerPrivate::~MImHwKeyboardTrackerPrivate()\n{\n}\n\nMImHwKeyboardTracker::MImHwKeyboardTracker()\n : QObject(),\n d_ptr(new MImHwKeyboardTrackerPrivate(this))\n{\n}\n\nMImHwKeyboardTracker::~MImHwKeyboardTracker()\n{\n}\n\nbool MImHwKeyboardTracker::isPresent() const\n{\n Q_D(const MImHwKeyboardTracker);\n\n return d->present;\n}\n\nbool MImHwKeyboardTracker::isOpen() const\n{\n Q_D(const MImHwKeyboardTracker);\n\n if (!d->present) {\n return false;\n }\n\n#ifdef HAVE_CONTEXTSUBSCRIBER\n return d->keyboardOpenProperty->value().toBool();\n#elif defined(Q_WS_MAEMO_5)\n return d->keyboardOpenConf.value().toBool();\n#else\n \/\/ If we found a talet mode switch, we report that the hardware keyboard\n \/\/ is available when the system is not in tablet mode (switch closed),\n \/\/ and is not available otherwise (switch open).\n if (d->evdevFile)\n return !d->evdevTabletMode;\n\n return false;\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Player.h\"\n#include \"SDL.h\"\n#include \"InputHandler.h\"\n\nPlayer::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { }\n\nvoid Player::draw()\n{\n\tSDLGameObject::draw();\t\/\/we now use SDLGameObject\n}\n\nvoid Player::update()\n{\t\n\tm_velocity.setX(0);\n\tm_velocity.setY(0);\n\n\tm_acceleration.setX(0);\n\tm_acceleration.setY(0);\n\n\thandleInput();\t\/\/adding our function\n\n\tm_currentFrame = int(((SDL_GetTicks() \/ 100) % 6));\n\n\tSDLGameObject::update();\n}\n\nvoid Player::clean()\n{\n\t\/\/blank clean() function\n}\n\nvoid Player::handleInput()\n{\n\tif (TheInputHandler::Instance()->joysticksInitialised())\n\t{\t\n\t\t\/\/for analog sticks of the first joystick\n\t\tif ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0))\n\t\t{\n\t\t\t\/\/if we are moving the player with analog stick while pressing Y\n\t\t\t\/\/it will get an acceleration of 2 in that direction\n\t\t\tm_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\t\/\/Button 3(Yellow)\n\t\t\t{\n\t\t\t\t\/\/give the player some acceleration\n\t\t\t\tm_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0))\n\t\t{\n\t\t\tm_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 1));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0,1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0))\n\t\t{\n\t\t\tm_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 2));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0))\n\t\t{\n\t\t\tm_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 2));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0, 1));\n\t\t\t}\n\t\t}\n\t\t\/*\tCode as in the book\n\t\t\/\/for buttons of the first joystick\n\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\t\/\/Button 3(Yellow)\n\t\t{\n\t\t\t\/\/give the player some acceleration\n\t\t\tm_acceleration.setX(1);\n\t\t}\n\t\t*\/\n\t}\n}<commit_msg>Player function sets acceleration to 1 if LEFT mouse button is pressed<commit_after>#include \"Player.h\"\n#include \"SDL.h\"\n#include \"InputHandler.h\"\n\nPlayer::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { }\n\nvoid Player::draw()\n{\n\tSDLGameObject::draw();\t\/\/we now use SDLGameObject\n}\n\nvoid Player::update()\n{\t\n\tm_velocity.setX(0);\n\tm_velocity.setY(0);\n\n\tm_acceleration.setX(0);\n\tm_acceleration.setY(0);\n\n\thandleInput();\t\/\/adding our function\n\n\tm_currentFrame = int(((SDL_GetTicks() \/ 100) % 6));\n\n\tSDLGameObject::update();\n}\n\nvoid Player::clean()\n{\n\t\/\/blank clean() function\n}\n\nvoid Player::handleInput()\n{\n\tif (TheInputHandler::Instance()->joysticksInitialised())\n\t{\t\n\t\t\/\/for analog sticks of the first joystick\n\t\tif ((TheInputHandler::Instance()->xvalue(0, 1) > 0) || (TheInputHandler::Instance()->xvalue(0, 1) < 0))\n\t\t{\n\t\t\t\/\/if we are moving the player with analog stick while pressing Y\n\t\t\t\/\/it will get an acceleration of 2 in that direction\n\t\t\tm_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\t\/\/Button 3(Yellow)\n\t\t\t{\n\t\t\t\t\/\/give the player some acceleration\n\t\t\t\tm_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->yvalue(0, 1) > 0) || (TheInputHandler::Instance()->yvalue(0, 1) < 0))\n\t\t{\n\t\t\tm_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 1));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0,1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->xvalue(0, 2) > 0) || (TheInputHandler::Instance()->xvalue(0, 2) < 0))\n\t\t{\n\t\t\tm_velocity.setX((float)1 * TheInputHandler::Instance()->xvalue(0, 2));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setX((float)2 * TheInputHandler::Instance()->xvalue(0, 1));\n\t\t\t}\n\t\t}\n\n\t\tif ((TheInputHandler::Instance()->yvalue(0, 2) > 0) || (TheInputHandler::Instance()->yvalue(0, 2) < 0))\n\t\t{\n\t\t\tm_velocity.setY((float)1 * TheInputHandler::Instance()->yvalue(0, 2));\n\t\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\n\t\t\t{\n\t\t\t\tm_acceleration.setY((float)2 * TheInputHandler::Instance()->yvalue(0, 1));\n\t\t\t}\n\t\t}\n\t\t\/*\tCode as in the book\n\t\t\/\/for buttons of the first joystick\n\t\tif (TheInputHandler::Instance()->getButtonState(0, 3))\t\/\/Button 3(Yellow)\n\t\t{\n\t\t\t\/\/give the player some acceleration\n\t\t\tm_acceleration.setX(1);\n\t\t}\n\t\t*\/\n\n\t\t\/\/check for mouse button input\n\t\tif (InputHandler::Instance()->getMouseButtonState[LEFT])\n\t\t{\n\t\t\tm_acceleration.setX(1);\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <boost\/lexical_cast.hpp>\n#include \"packet.h\"\n\n#define USAGE \"Usage:\\r\\nc \\r\\n[tux machine number] \\r\\n[probability of packet corruption in int form] \\r\\n[probability of packet loss in int form] \\r\\n[probability of packet delay] \\r\\n[length of delay in ms] \\r\\n\"\n#define PORT 10038\n#define PAKSIZE 512\n#define ACK 0\n#define NAK 1\n#define BUFSIZE 505\n#define FILENAME \"Testfile\"\n#define TIMEOUT 100 \/\/in ms\n#define WIN_SIZE 16\n\nusing namespace std;\n\nbool isvpack(unsigned char * p);\nbool init(int argc, char** argv);\nbool loadFile();\nbool getFile();\nbool sendFile();\nbool isAck();\nvoid handleAck();\nvoid handleNak(int& x);\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);\nPacket createPacket(int index);\nvoid loadWindow();\nbool sendPacket();\nbool getGet();\n\nstruct sockaddr_in a;\nstruct sockaddr_in ca;\nsocklen_t calen;\nint rlen;\nint s;\nbool ack;\nstring fstr;\nchar * file;\nint probCorrupt;\nint probLoss;\nint probDelay;\nint delayT;\nPacket p;\nPacket window[16];\nint length;\nbool dropPck;\nbool delayPck;\nint toms;\nunsigned char b[BUFSIZE];\nint base;\n\nint main(int argc, char** argv) {\n \n if(!init(argc, argv)) return -1;\n \n sendFile();\n \n return 0;\n}\n\nbool init(int argc, char** argv){\n\n if(argc != 6) { \n cout << USAGE << endl;\n return false;\n }\n\n char * probCorruptStr = argv[2];\n probCorrupt = boost::lexical_cast<int>(probCorruptStr);\n char * probLossStr = argv[3];\n probLoss = boost::lexical_cast<int>(probLossStr);\n char * probDelayStr = argv[4];\n probDelay = boost::lexical_cast<int>(probDelayStr);\n char* delayTStr = argv[5];\n delayT = boost::lexical_cast<int>(delayTStr);\n \n struct timeval timeout;\n timeout.tv_usec = TIMEOUT * 1000;\n toms = TIMEOUT;\n\n \/* Create our socket. *\/\n if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n cout << \"Socket creation failed. (socket s)\" << endl;\n return 0;\n }\n\n setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));\n\n \/* \n * Bind our socket to an IP (whatever the computer decides) \n * and a specified port. \n *\n *\/\n\n if (!loadFile()) {\n cout << \"Loading file failed. (filename FILENAME)\" << endl;\n return false; \n }\n \n memset((char *)&a, 0, sizeof(a));\n a.sin_family = AF_INET;\n a.sin_addr.s_addr = htonl(INADDR_ANY);\n a.sin_port = htons(PORT);\n\n if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {\n cout << \"Socket binding failed. (socket s, address a)\" << endl;\n return 0;\n }\n \n fstr = string(file);\n cout << \"File: \" << endl << fstr << endl;\n\n base = 0;\n dropPck = false;\n calen = sizeof(ca);\n\n getGet();\n \n return true;\n}\n\nbool getGet(){\n\tunsigned char packet[PAKSIZE + 1];\n\trlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\treturn (rlen > 0) ? true : false;\n}\n\nbool isvpack(unsigned char * p) {\n cout << endl << \"=== IS VALID PACKET TESTING\" << endl;\n\n char * sns = new char[2];\n memcpy(sns, &p[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[7];\n memcpy(css, &p[1], 6);\n css[6] = '\\0';\n \n char * db = new char[121 + 1];\n memcpy(db, &p[2], 121);\n db[121] = '\\0';\n\n cout << \"Seq. num: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Message: \" << db << endl;\n\n int sn = boost::lexical_cast<int>(sns);\n int cs = boost::lexical_cast<int>(css);\n\n Packet pk (0, db);\n pk.setSequenceNum(sn);\n\n \/\/ change to validate based on checksum and sequence number\n\n if(sn == 0) return false; \/\/doesn't matter, only for the old version (netwark)\n if(cs != pk.generateCheckSum()) return false;\n return true;\n}\n\nbool getFile(){\n\n \/* Loop forever, waiting for messages from a client. *\/\n cout << \"Waiting on port \" << PORT << \"...\" << endl;\n\n ofstream file(\"Dumpfile\");\n\n for (;;) {\n unsigned char packet[PAKSIZE + 1];\n unsigned char dataPull[PAKSIZE - 7 + 1];\n rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\n for(int x = 0; x < PAKSIZE - 7; x++) {\n dataPull[x] = packet[x + 7];\n }\n dataPull[PAKSIZE - 7] = '\\0';\n packet[PAKSIZE] = '\\0';\n if (rlen > 0) {\n char * css = new char[6];\n memcpy(css, &packet[1], 5);\n css[5] = '\\0';\n cout << endl << endl << \"=== RECEIPT\" << endl;\n cout << \"Seq. num: \" << packet[0] << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Received message: \" << dataPull << endl;\n cout << \"Sent response: \";\n if(isvpack(packet)) {\n ack = ACK;\n \/\/seqNum = (seqNum) ? false : true;\n file << dataPull;\n } else { \n ack = NAK;\n }\n cout << ((ack == ACK) ? \"ACK\" : \"NAK\") << endl;\n Packet p (false, reinterpret_cast<const char *>(dataPull));\n p.setCheckSum(boost::lexical_cast<int>(css));\n p.setAckNack(ack);\n\n if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {\n cout << \"Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)\" << endl;\n return 0;\n }\n delete css;\n }\n }\n file.close();\n return true;\n}\n\nbool loadFile() {\n\n ifstream is (FILENAME, ifstream::binary);\n\n if(is) {\n is.seekg(0, is.end);\n length = is.tellg();\n is.seekg(0, is.beg);\n\n file = new char[length];\n\n cout << \"Reading \" << length << \" characters...\" << endl;\n is.read(file, length);\n\n if(!is) { cout << \"File reading failed. (filename \" << FILENAME << \"). Only \" << is.gcount() << \" could be read.\"; return false; }\n is.close();\n }\n return true;\n}\n\nvoid loadWindow(){\n\tfor(int i = base; i < base + WIN_SIZE; i++) {\n\t\twindow[i-base] = createPacket(i);\n\t\tif(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') { \n\t\t\tfor(++i; i < base + WIN_SIZE; i++){\n\t\t\t\twindow[i-base].loadDataBuffer(\"\\0\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nbool sendFile() {\n\t\/*Currently causes the program to only send the first 16 packets of file out\n\t\trequires additional code later to sendFile again with updated window*\/\n\tbase = 0;\n\twhile(base * BUFSIZE < length) {\n\t\tloadWindow();\n\n\t\tcout << \"packet \" << base << \": \" << window[0].str() << endl;\n\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tp = window[x];\n\t\t\tif(!sendPacket()) continue;\n\t\t}\n\t\tif(p.str()[0] == '\\0') break;\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tif(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {\n\t\t\t\tcout << \"=== ACK TIMEOUT\" << endl;\n\t\t\t\tx--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(isAck()) { \n\t\t\t\thandleAck();\n\t\t\t} else { \n\t\t\t\thandleAck();\n\t\t\t\t\/\/handleNak(x);\n\t\t\t}\n\n\t\t\tmemset(b, 0, BUFSIZE);\n\t\t}\n\t}\n\n\tif(sendto(s, \"\\0\", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Final package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nPacket createPacket(int index){\n string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);\n\n\tif(mstr.length() < BUFSIZE) {\n\t\tcout << \"Null terminated mstr.\" << endl;\n\t\tmstr[length - (index * BUFSIZE)] = '\\0';\n }\n return Packet (index, mstr.c_str());\n}\n\nbool sendPacket(){\n\tcout << endl;\n cout << \"=== TRANSMISSION START\" << endl;\n\tcout << \"Sequence number before gremlin function: \" << p.getSequenceNum() << endl;\n int pc = probCorrupt; int pl = probLoss; int pd = probDelay;\n\tbool* pckStatus = gremlin(&p, pc, pl, pd);\n\n\tdropPck = pckStatus[0];\n\tdelayPck = pckStatus[1];\n\n\tif (dropPck == true) return false;\n\tif (delayPck == true) p.setAckNack(1);\n\n if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n }\n return true;\n}\nbool isAck() {\n cout << endl << \"=== SERVER RESPONSE TEST\" << endl;\n cout << \"Data: \" << b << endl;\n if(b[6] == '0') return true;\n else return false;\n}\nvoid handleAck() {\n\tint ack = boost::lexical_cast<int>(b);\n\tif(base < ack) base = ack;\n\tcout << \"Window base: \" << base << endl;\n}\nvoid handleNak(int& x) {\n\n char * sns = new char[2];\n memcpy(sns, &b[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[5];\n memcpy(css, &b[1], 5);\n \n char * db = new char[BUFSIZE + 1];\n memcpy(db, &b[2], BUFSIZE);\n db[BUFSIZE] = '\\0';\n\n cout << \"Sequence number: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n\n Packet pk (0, db);\n pk.setSequenceNum(boost::lexical_cast<int>(sns));\n pk.setCheckSum(boost::lexical_cast<int>(css));\n\n if(!pk.chksm()) x--; \n else x = (x - 2 > 0) ? x - 2 : 0;\n}\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){\n\n bool* packStatus = new bool[2];\n int r = rand() % 100;\n\n cout << \"Corruption probability: \" << corruptProb << endl;\n cout << \"Random number: \" << r << endl;\n\n packStatus[0] = false;\n packStatus[1] = false;\n\n if(r <= (lossProb)){\n\tpackStatus[0] = true;\n cout << \"Dropped!\" << endl;\n }\n else if(r <= (delayProb)){\n\t packStatus[1] = true;\n\t cout << \"Delayed!\" << endl;\n }\n else if(r <= (corruptProb)){\n cout << \"Corrupted!\" << endl;\n\tcout << \"Seq. num (pre-gremlin): \" << pack->getSequenceNum() << endl;\n pack->loadDataBuffer((char*)\"GREMLIN LOL\");\n }\n cout << \"Seq. num: \" << pack->getSequenceNum() << endl;\n cout << \"Checksum: \" << pack->getCheckSum() << endl;\n \/\/cout << \"Message: \" << pack->getDataBuffer() << endl;\n\n return packStatus;\n}<commit_msg>Expand further on testing<commit_after>#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <boost\/lexical_cast.hpp>\n#include \"packet.h\"\n\n#define USAGE \"Usage:\\r\\nc \\r\\n[tux machine number] \\r\\n[probability of packet corruption in int form] \\r\\n[probability of packet loss in int form] \\r\\n[probability of packet delay] \\r\\n[length of delay in ms] \\r\\n\"\n#define PORT 10038\n#define PAKSIZE 512\n#define ACK 0\n#define NAK 1\n#define BUFSIZE 505\n#define FILENAME \"Testfile\"\n#define TIMEOUT 100 \/\/in ms\n#define WIN_SIZE 16\n\nusing namespace std;\n\nbool isvpack(unsigned char * p);\nbool init(int argc, char** argv);\nbool loadFile();\nbool getFile();\nbool sendFile();\nbool isAck();\nvoid handleAck();\nvoid handleNak(int& x);\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);\nPacket createPacket(int index);\nvoid loadWindow();\nbool sendPacket();\nbool getGet();\n\nstruct sockaddr_in a;\nstruct sockaddr_in ca;\nsocklen_t calen;\nint rlen;\nint s;\nbool ack;\nstring fstr;\nchar * file;\nint probCorrupt;\nint probLoss;\nint probDelay;\nint delayT;\nPacket p;\nPacket window[16];\nint length;\nbool dropPck;\nbool delayPck;\nint toms;\nunsigned char b[BUFSIZE];\nint base;\n\nint main(int argc, char** argv) {\n \n if(!init(argc, argv)) return -1;\n \n sendFile();\n \n return 0;\n}\n\nbool init(int argc, char** argv){\n\n if(argc != 6) { \n cout << USAGE << endl;\n return false;\n }\n\n char * probCorruptStr = argv[2];\n probCorrupt = boost::lexical_cast<int>(probCorruptStr);\n char * probLossStr = argv[3];\n probLoss = boost::lexical_cast<int>(probLossStr);\n char * probDelayStr = argv[4];\n probDelay = boost::lexical_cast<int>(probDelayStr);\n char* delayTStr = argv[5];\n delayT = boost::lexical_cast<int>(delayTStr);\n \n struct timeval timeout;\n timeout.tv_usec = TIMEOUT * 1000;\n toms = TIMEOUT;\n\n \/* Create our socket. *\/\n if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n cout << \"Socket creation failed. (socket s)\" << endl;\n return 0;\n }\n\n setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));\n\n \/* \n * Bind our socket to an IP (whatever the computer decides) \n * and a specified port. \n *\n *\/\n\n if (!loadFile()) {\n cout << \"Loading file failed. (filename FILENAME)\" << endl;\n return false; \n }\n \n memset((char *)&a, 0, sizeof(a));\n a.sin_family = AF_INET;\n a.sin_addr.s_addr = htonl(INADDR_ANY);\n a.sin_port = htons(PORT);\n\n if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {\n cout << \"Socket binding failed. (socket s, address a)\" << endl;\n return 0;\n }\n \n fstr = string(file);\n cout << \"File: \" << endl << fstr << endl;\n\n base = 0;\n dropPck = false;\n calen = sizeof(ca);\n\n getGet();\n \n return true;\n}\n\nbool getGet(){\n\tunsigned char packet[PAKSIZE + 1];\n\trlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\treturn (rlen > 0) ? true : false;\n}\n\nbool isvpack(unsigned char * p) {\n cout << endl << \"=== IS VALID PACKET TESTING\" << endl;\n\n char * sns = new char[2];\n memcpy(sns, &p[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[7];\n memcpy(css, &p[1], 6);\n css[6] = '\\0';\n \n char * db = new char[121 + 1];\n memcpy(db, &p[2], 121);\n db[121] = '\\0';\n\n cout << \"Seq. num: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Message: \" << db << endl;\n\n int sn = boost::lexical_cast<int>(sns);\n int cs = boost::lexical_cast<int>(css);\n\n Packet pk (0, db);\n pk.setSequenceNum(sn);\n\n \/\/ change to validate based on checksum and sequence number\n\n if(sn == 0) return false; \/\/doesn't matter, only for the old version (netwark)\n if(cs != pk.generateCheckSum()) return false;\n return true;\n}\n\nbool getFile(){\n\n \/* Loop forever, waiting for messages from a client. *\/\n cout << \"Waiting on port \" << PORT << \"...\" << endl;\n\n ofstream file(\"Dumpfile\");\n\n for (;;) {\n unsigned char packet[PAKSIZE + 1];\n unsigned char dataPull[PAKSIZE - 7 + 1];\n rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\n for(int x = 0; x < PAKSIZE - 7; x++) {\n dataPull[x] = packet[x + 7];\n }\n dataPull[PAKSIZE - 7] = '\\0';\n packet[PAKSIZE] = '\\0';\n if (rlen > 0) {\n char * css = new char[6];\n memcpy(css, &packet[1], 5);\n css[5] = '\\0';\n cout << endl << endl << \"=== RECEIPT\" << endl;\n cout << \"Seq. num: \" << packet[0] << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Received message: \" << dataPull << endl;\n cout << \"Sent response: \";\n if(isvpack(packet)) {\n ack = ACK;\n \/\/seqNum = (seqNum) ? false : true;\n file << dataPull;\n } else { \n ack = NAK;\n }\n cout << ((ack == ACK) ? \"ACK\" : \"NAK\") << endl;\n Packet p (false, reinterpret_cast<const char *>(dataPull));\n p.setCheckSum(boost::lexical_cast<int>(css));\n p.setAckNack(ack);\n\n if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {\n cout << \"Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)\" << endl;\n return 0;\n }\n delete css;\n }\n }\n file.close();\n return true;\n}\n\nbool loadFile() {\n\n ifstream is (FILENAME, ifstream::binary);\n\n if(is) {\n is.seekg(0, is.end);\n length = is.tellg();\n is.seekg(0, is.beg);\n\n file = new char[length];\n\n cout << \"Reading \" << length << \" characters...\" << endl;\n is.read(file, length);\n\n if(!is) { cout << \"File reading failed. (filename \" << FILENAME << \"). Only \" << is.gcount() << \" could be read.\"; return false; }\n is.close();\n }\n return true;\n}\n\nvoid loadWindow(){\n\tfor(int i = base; i < base + WIN_SIZE; i++) {\n\t\twindow[i-base] = createPacket(i);\n\t\tif(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') { \n\t\t\tfor(++i; i < base + WIN_SIZE; i++){\n\t\t\t\twindow[i-base].loadDataBuffer(\"\\0\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nbool sendFile() {\n\t\/*Currently causes the program to only send the first 16 packets of file out\n\t\trequires additional code later to sendFile again with updated window*\/\n\tbase = 0;\n\twhile(base * BUFSIZE < length) {\n\t\tloadWindow();\n\n\t\tcout << \"packet \" << base << \": \" << window[0].str() << endl;\n\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tp = window[x];\n\t\t\tif(!sendPacket()) continue;\n\t\t}\n\t\tif(p.str()[0] == '\\0') break;\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tif(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {\n\t\t\t\tcout << \"=== ACK TIMEOUT\" << endl;\n\t\t\t\tx--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(isAck()) { \n\t\t\t\thandleAck();\n\t\t\t} else { \n\t\t\t\thandleAck();\n\t\t\t\t\/\/handleNak(x);\n\t\t\t}\n\n\t\t\tmemset(b, 0, BUFSIZE);\n\t\t}\n\t}\n\n\tif(sendto(s, \"\\0\", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Final package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nPacket createPacket(int index){\n string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);\n\n\tif(mstr.length() < BUFSIZE) {\n\t\tcout << \"Null terminated mstr.\" << endl;\n\t\tmstr[length - (index * BUFSIZE)] = '\\0';\n }\n\n\tcout << \"index: \" << index << endl;\n return Packet (index, mstr.c_str());\n}\n\nbool sendPacket(){\n\tcout << endl;\n cout << \"=== TRANSMISSION START\" << endl;\n\tcout << \"Sequence number before gremlin function: \" << p.getSequenceNum() << endl;\n int pc = probCorrupt; int pl = probLoss; int pd = probDelay;\n\tbool* pckStatus = gremlin(&p, pc, pl, pd);\n\n\tdropPck = pckStatus[0];\n\tdelayPck = pckStatus[1];\n\n\tif (dropPck == true) return false;\n\tif (delayPck == true) p.setAckNack(1);\n\n if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n }\n return true;\n}\nbool isAck() {\n cout << endl << \"=== SERVER RESPONSE TEST\" << endl;\n cout << \"Data: \" << b << endl;\n if(b[6] == '0') return true;\n else return false;\n}\nvoid handleAck() {\n\tint ack = boost::lexical_cast<int>(b);\n\tif(base < ack) base = ack;\n\tcout << \"Window base: \" << base << endl;\n}\nvoid handleNak(int& x) {\n\n char * sns = new char[2];\n memcpy(sns, &b[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[5];\n memcpy(css, &b[1], 5);\n \n char * db = new char[BUFSIZE + 1];\n memcpy(db, &b[2], BUFSIZE);\n db[BUFSIZE] = '\\0';\n\n cout << \"Sequence number: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n\n Packet pk (0, db);\n pk.setSequenceNum(boost::lexical_cast<int>(sns));\n pk.setCheckSum(boost::lexical_cast<int>(css));\n\n if(!pk.chksm()) x--; \n else x = (x - 2 > 0) ? x - 2 : 0;\n}\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){\n\n bool* packStatus = new bool[2];\n int r = rand() % 100;\n\n cout << \"Corruption probability: \" << corruptProb << endl;\n cout << \"Random number: \" << r << endl;\n\n packStatus[0] = false;\n packStatus[1] = false;\n\n if(r <= (lossProb)){\n\tpackStatus[0] = true;\n cout << \"Dropped!\" << endl;\n }\n else if(r <= (delayProb)){\n\t packStatus[1] = true;\n\t cout << \"Delayed!\" << endl;\n }\n else if(r <= (corruptProb)){\n cout << \"Corrupted!\" << endl;\n\tcout << \"Seq. num (pre-gremlin): \" << pack->getSequenceNum() << endl;\n pack->loadDataBuffer((char*)\"GREMLIN LOL\");\n }\n cout << \"Seq. num: \" << pack->getSequenceNum() << endl;\n cout << \"Checksum: \" << pack->getCheckSum() << endl;\n \/\/cout << \"Message: \" << pack->getDataBuffer() << endl;\n\n return packStatus;\n}<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <sstream>\n#include <string>\n\n#include \"Module\/Extractor\/Polar\/Extractor_polar.hpp\"\n#include \"Tools\/Exception\/exception.hpp\"\n#include \"Tools\/Noise\/Sigma.hpp\"\n#include \"Tools\/Noise\/Event_probability.hpp\"\n#include \"Factory\/Module\/Encoder\/Encoder.hpp\"\n#include \"Factory\/Module\/Puncturer\/Puncturer.hpp\"\n#include \"Tools\/Codec\/Polar_MK\/Codec_polar_MK.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::tools;\n\ntemplate <typename B, typename Q>\nCodec_polar_MK<B,Q>\n::Codec_polar_MK(const factory::Polar_code &pc_params,\n const factory::Frozenbits_generator_MK &fb_params,\n const factory::Encoder_polar_MK &enc_params,\n const factory::Decoder_polar_MK &dec_params,\n const module::CRC<B> *crc)\n: Codec_SIHO<B,Q>(enc_params.K, enc_params.N_cw, enc_params.N_cw, enc_params.n_frames),\n adaptive_fb(fb_params.noise == -1.f),\n frozen_bits(new std::vector<bool>(fb_params.N_cw, true)),\n fb_decoder(nullptr),\n fb_encoder(nullptr),\n fb_extractor(nullptr)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------- exceptions\n\tif (enc_params.K != dec_params.K)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = \" << enc_params.K\n\t\t << \", 'dec_params.K' = \" << dec_params.K << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (enc_params.N_cw != dec_params.N_cw)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = \" << enc_params.N_cw\n\t\t << \", 'dec_params.N_cw' = \" << dec_params.N_cw << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (enc_params.n_frames != dec_params.n_frames)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = \"\n\t\t << enc_params.n_frames << \", 'dec_params.n_frames' = \" << dec_params.n_frames << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- tools\n\t\/\/ build the polar code\n\tcode.reset(pc_params.build());\n\n\t\/\/ build the frozen bits generator\n\tfb_generator.reset(fb_params.build(*code.get()));\n\n\t\/\/ ---------------------------------------------------------------------------------------------------- allocations\n\tfactory::Puncturer pct_params;\n\tpct_params.type = \"NO\";\n\tpct_params.K = enc_params.K;\n\tpct_params.N = enc_params.N_cw;\n\tpct_params.N_cw = enc_params.N_cw;\n\tpct_params.n_frames = enc_params.n_frames;\n\n\tthis->set_puncturer(pct_params.build<B,Q>());\n\n\tstd::fill(frozen_bits->begin(), frozen_bits->begin() + this->K, false);\n\n\ttry\n\t{\n\t\tthis->set_encoder(enc_params.build<B>(*code.get(), *frozen_bits));\n\t\tfb_encoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_encoder());\n\t}\n\tcatch (tools::cannot_allocate const&)\n\t{\n\t\tthis->set_encoder(static_cast<const factory::Encoder*>(&enc_params)->build<B>());\n\t}\n\n\tthis->set_decoder_siho(dec_params.build<B,Q>(*code.get(), *frozen_bits, crc, &this->get_encoder()));\n\tthis->fb_decoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_decoder_siho());\n\n\tthis->set_extractor(new module::Extractor_polar<B,Q>(enc_params.K,\n\t enc_params.N_cw,\n\t *frozen_bits,\n\t enc_params.n_frames));\n\tfb_extractor = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_extractor());\n\n\t\/\/ ------------------------------------------------------------------------------------------------- frozen bit gen\n\tif (!adaptive_fb)\n\t{\n\t\tif (fb_params.type == \"BEC\")\n\t\t{\n\t\t\tauto ep = tools::Event_probability<float>(fb_params.noise);\n\t\t\tfb_generator->set_noise(ep);\n\t\t}\n\t\telse \/* type = GA, TV or FILE *\/\n\t\t{\n\t\t\tauto sigma = tools::Sigma<float>(fb_params.noise);\n\t\t\tfb_generator->set_noise(sigma);\n\t\t}\n\n\t\tfb_generator->generate(*frozen_bits);\n\t\tthis->notify_frozenbits_update();\n\t}\n}\n\ntemplate <typename B, typename Q>\nCodec_polar_MK<B,Q>* Codec_polar_MK<B,Q>\n::clone() const\n{\n\tauto t = new Codec_polar_MK(*this);\n\tt->deep_copy(*this);\n\treturn t;\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::deep_copy(const Codec_polar_MK<B,Q> &t)\n{\n\tCodec_SIHO<B,Q>::deep_copy(t);\n\tif (t.fb_encoder != nullptr)\n\t\tthis->fb_encoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_encoder());\n\tif (t.fb_decoder != nullptr)\n\t\tthis->fb_decoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_decoder_siho());\n\tif (t.fb_extractor != nullptr)\n\t\tthis->fb_extractor = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_extractor());\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::notify_frozenbits_update()\n{\n\tif (this->fb_decoder)\n\t\tthis->fb_decoder->notify_noise_update();\n\tif (this->fb_encoder)\n\t\tthis->fb_encoder->notify_noise_update();\n\tif (this->fb_extractor)\n\t\tthis->fb_extractor->notify_noise_update();\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::notify_noise_update()\n{\n\tCodec<B,Q>::notify_noise_update();\n\tif (this->adaptive_fb)\n\t{\n\t\tthis->fb_generator->set_noise(*this->noise);\n\t\tthis->fb_generator->generate(*this->frozen_bits);\n\t\tthis->notify_frozenbits_update();\n\t}\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::check_noise()\n{\n\tCodec<B,Q>::check_noise();\n\tif (!this->noise->is_of_type(Noise_type::SIGMA) && !this->noise->is_of_type(Noise_type::EP))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"Incompatible noise type, expected noise types are SIGMA or EP ('noise->get_type()' = \"\n\t\t << Noise<>::type_to_str(this->noise->get_type()) << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n}\n\ntemplate <typename B, typename Q>\nconst std::vector<bool>& Codec_polar_MK<B,Q>\n::get_frozen_bits() const\n{\n\treturn *this->frozen_bits;\n}\n\ntemplate <typename B, typename Q>\nbool Codec_polar_MK<B,Q>\n::is_adaptive_frozen_bits() const\n{\n\treturn this->adaptive_fb;\n}\n\ntemplate <typename B, typename Q>\nconst Polar_code& Codec_polar_MK<B,Q>\n::get_code() const\n{\n\treturn *this->code;\n}\n\n\/\/ ==================================================================================== explicit template instantiation\n#include \"Tools\/types.h\"\n#ifdef AFF3CT_MULTI_PREC\ntemplate class aff3ct::tools::Codec_polar_MK<B_8,Q_8>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_16,Q_16>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_32,Q_32>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_64,Q_64>;\n#else\ntemplate class aff3ct::tools::Codec_polar_MK<B,Q>;\n#endif\n\/\/ ==================================================================================== explicit template instantiation\n<commit_msg>Add missing getter in MK Polar codec.<commit_after>#include <algorithm>\n#include <sstream>\n#include <string>\n\n#include \"Module\/Extractor\/Polar\/Extractor_polar.hpp\"\n#include \"Tools\/Exception\/exception.hpp\"\n#include \"Tools\/Noise\/Sigma.hpp\"\n#include \"Tools\/Noise\/Event_probability.hpp\"\n#include \"Factory\/Module\/Encoder\/Encoder.hpp\"\n#include \"Factory\/Module\/Puncturer\/Puncturer.hpp\"\n#include \"Tools\/Codec\/Polar_MK\/Codec_polar_MK.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::tools;\n\ntemplate <typename B, typename Q>\nCodec_polar_MK<B,Q>\n::Codec_polar_MK(const factory::Polar_code &pc_params,\n const factory::Frozenbits_generator_MK &fb_params,\n const factory::Encoder_polar_MK &enc_params,\n const factory::Decoder_polar_MK &dec_params,\n const module::CRC<B> *crc)\n: Codec_SIHO<B,Q>(enc_params.K, enc_params.N_cw, enc_params.N_cw, enc_params.n_frames),\n adaptive_fb(fb_params.noise == -1.f),\n frozen_bits(new std::vector<bool>(fb_params.N_cw, true)),\n fb_decoder(nullptr),\n fb_encoder(nullptr),\n fb_extractor(nullptr)\n{\n\t\/\/ ----------------------------------------------------------------------------------------------------- exceptions\n\tif (enc_params.K != dec_params.K)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = \" << enc_params.K\n\t\t << \", 'dec_params.K' = \" << dec_params.K << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (enc_params.N_cw != dec_params.N_cw)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = \" << enc_params.N_cw\n\t\t << \", 'dec_params.N_cw' = \" << dec_params.N_cw << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\tif (enc_params.n_frames != dec_params.n_frames)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = \"\n\t\t << enc_params.n_frames << \", 'dec_params.n_frames' = \" << dec_params.n_frames << \").\";\n\t\tthrow tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\t\/\/ ---------------------------------------------------------------------------------------------------------- tools\n\t\/\/ build the polar code\n\tcode.reset(pc_params.build());\n\n\t\/\/ build the frozen bits generator\n\tfb_generator.reset(fb_params.build(*code.get()));\n\n\t\/\/ ---------------------------------------------------------------------------------------------------- allocations\n\tfactory::Puncturer pct_params;\n\tpct_params.type = \"NO\";\n\tpct_params.K = enc_params.K;\n\tpct_params.N = enc_params.N_cw;\n\tpct_params.N_cw = enc_params.N_cw;\n\tpct_params.n_frames = enc_params.n_frames;\n\n\tthis->set_puncturer(pct_params.build<B,Q>());\n\n\tstd::fill(frozen_bits->begin(), frozen_bits->begin() + this->K, false);\n\n\ttry\n\t{\n\t\tthis->set_encoder(enc_params.build<B>(*code.get(), *frozen_bits));\n\t\tfb_encoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_encoder());\n\t}\n\tcatch (tools::cannot_allocate const&)\n\t{\n\t\tthis->set_encoder(static_cast<const factory::Encoder*>(&enc_params)->build<B>());\n\t}\n\n\tthis->set_decoder_siho(dec_params.build<B,Q>(*code.get(), *frozen_bits, crc, &this->get_encoder()));\n\tthis->fb_decoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_decoder_siho());\n\n\tthis->set_extractor(new module::Extractor_polar<B,Q>(enc_params.K,\n\t enc_params.N_cw,\n\t *frozen_bits,\n\t enc_params.n_frames));\n\tfb_extractor = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_extractor());\n\n\t\/\/ ------------------------------------------------------------------------------------------------- frozen bit gen\n\tif (!adaptive_fb)\n\t{\n\t\tif (fb_params.type == \"BEC\")\n\t\t{\n\t\t\tauto ep = tools::Event_probability<float>(fb_params.noise);\n\t\t\tfb_generator->set_noise(ep);\n\t\t}\n\t\telse \/* type = GA, TV or FILE *\/\n\t\t{\n\t\t\tauto sigma = tools::Sigma<float>(fb_params.noise);\n\t\t\tfb_generator->set_noise(sigma);\n\t\t}\n\n\t\tfb_generator->generate(*frozen_bits);\n\t\tthis->notify_frozenbits_update();\n\t}\n}\n\ntemplate <typename B, typename Q>\nCodec_polar_MK<B,Q>* Codec_polar_MK<B,Q>\n::clone() const\n{\n\tauto t = new Codec_polar_MK(*this);\n\tt->deep_copy(*this);\n\treturn t;\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::deep_copy(const Codec_polar_MK<B,Q> &t)\n{\n\tCodec_SIHO<B,Q>::deep_copy(t);\n\tif (t.fb_encoder != nullptr)\n\t\tthis->fb_encoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_encoder());\n\tif (t.fb_decoder != nullptr)\n\t\tthis->fb_decoder = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_decoder_siho());\n\tif (t.fb_extractor != nullptr)\n\t\tthis->fb_extractor = dynamic_cast<Interface_notify_frozenbits_update*>(&this->get_extractor());\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::notify_frozenbits_update()\n{\n\tif (this->fb_decoder)\n\t\tthis->fb_decoder->notify_noise_update();\n\tif (this->fb_encoder)\n\t\tthis->fb_encoder->notify_noise_update();\n\tif (this->fb_extractor)\n\t\tthis->fb_extractor->notify_noise_update();\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::notify_noise_update()\n{\n\tCodec<B,Q>::notify_noise_update();\n\tif (this->adaptive_fb)\n\t{\n\t\tthis->fb_generator->set_noise(*this->noise);\n\t\tthis->fb_generator->generate(*this->frozen_bits);\n\t\tthis->notify_frozenbits_update();\n\t}\n}\n\ntemplate <typename B, typename Q>\nvoid Codec_polar_MK<B,Q>\n::check_noise()\n{\n\tCodec<B,Q>::check_noise();\n\tif (!this->noise->is_of_type(Noise_type::SIGMA) && !this->noise->is_of_type(Noise_type::EP))\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"Incompatible noise type, expected noise types are SIGMA or EP ('noise->get_type()' = \"\n\t\t << Noise<>::type_to_str(this->noise->get_type()) << \").\";\n\t\tthrow invalid_argument(__FILE__, __LINE__, __func__, message.str());\n\t}\n}\n\ntemplate <typename B, typename Q>\nconst std::vector<bool>& Codec_polar_MK<B,Q>\n::get_frozen_bits() const\n{\n\treturn *this->frozen_bits;\n}\n\ntemplate <typename B, typename Q>\nbool Codec_polar_MK<B,Q>\n::is_adaptive_frozen_bits() const\n{\n\treturn this->adaptive_fb;\n}\n\ntemplate <typename B, typename Q>\nconst Polar_code& Codec_polar_MK<B,Q>\n::get_code() const\n{\n\treturn *this->code;\n}\n\ntemplate <typename B, typename Q>\nconst Frozenbits_generator& Codec_polar_MK<B,Q>\n::get_frozen_bits_generator() const\n{\n\tif (this->fb_generator == nullptr)\n\t{\n\t\tstd::stringstream message;\n\t\tmessage << \"'fb_generator' can't be nullptr.\";\n\t\tthrow runtime_error(__FILE__, __LINE__, __func__, message.str());\n\t}\n\n\treturn *this->fb_generator.get();\n}\n\n\/\/ ==================================================================================== explicit template instantiation\n#include \"Tools\/types.h\"\n#ifdef AFF3CT_MULTI_PREC\ntemplate class aff3ct::tools::Codec_polar_MK<B_8,Q_8>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_16,Q_16>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_32,Q_32>;\ntemplate class aff3ct::tools::Codec_polar_MK<B_64,Q_64>;\n#else\ntemplate class aff3ct::tools::Codec_polar_MK<B,Q>;\n#endif\n\/\/ ==================================================================================== explicit template instantiation\n<|endoftext|>"} {"text":"<commit_before>#ifndef __FACTOR_MASTER_H__\n#define __FACTOR_MASTER_H__\n\n#ifndef _THREAD_SAFE\n#define _THREAD_SAFE\n#endif\n\n#ifndef _REENTRANT\n#define _REENTRANT\n#endif\n\n#include <errno.h>\n\n\/\/ C headers\n#include <fcntl.h>\n#include <limits.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <wchar.h>\n#include <stdint.h>\n\n\/\/ C++ headers\n#include <algorithm>\n#include <list>\n#include <map>\n#include <set>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <sstream>\n#include <string>\n\n#define FACTOR_STRINGIZE_I(x) #x\n#define FACTOR_STRINGIZE(x) FACTOR_STRINGIZE_I(x)\n\n\/\/ Record compiler version\n#if defined(__clang__)\n#define FACTOR_COMPILER_VERSION \"Clang (GCC \" __VERSION__ \")\"\n#elif defined(__INTEL_COMPILER)\n#define FACTOR_COMPILER_VERSION \\\n \"Intel C Compiler \" FACTOR_STRINGIZE(__INTEL_COMPILER)\n#elif defined(__GNUC__)\n#define FACTOR_COMPILER_VERSION \"GCC \" __VERSION__\n#elif defined(_MSC_FULL_VER)\n#define FACTOR_COMPILER_VERSION \\\n \"Microsoft Visual C++ \" FACTOR_STRINGIZE(_MSC_FULL_VER)\n#else\n#define FACTOR_COMPILER_VERSION \"unknown\"\n#endif\n\n\/\/ Record compilation time\n#define FACTOR_COMPILE_TIME __TIMESTAMP__\n\n\/\/ Detect target CPU type\n#if defined(__arm__)\n#define FACTOR_ARM\n#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)\n#define FACTOR_AMD64\n#define FACTOR_64\n#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86)\n#define FACTOR_X86\n#elif(defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)) && \\\n (defined(__PPC64__) || defined(__64BIT__))\n#define FACTOR_PPC64\n#define FACTOR_PPC\n#define FACTOR_64\n#elif defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)\n#define FACTOR_PPC32\n#define FACTOR_PPC\n#else\n#error \"Unsupported architecture\"\n#endif\n\n#if defined(_MSC_VER)\n#define WINDOWS\n#define WINNT\n#elif defined(WIN32)\n#define WINDOWS\n#endif\n\n\/\/ Forward-declare this since it comes up in function prototypes\nnamespace factor { struct factor_vm; }\n\n\/\/ Factor headers\n#include \"assert.hpp\"\n#include \"debug.hpp\"\n#include \"layouts.hpp\"\n#include \"platform.hpp\"\n#include \"utilities.hpp\"\n#include \"primitives.hpp\"\n#include \"errors.hpp\"\n#include \"segments.hpp\"\n#include \"gc_info.hpp\"\n#include \"contexts.hpp\"\n#include \"run.hpp\"\n#include \"objects.hpp\"\n#include \"sampling_profiler.hpp\"\n#include \"bignumint.hpp\"\n#include \"bignum.hpp\"\n#include \"booleans.hpp\"\n#include \"instruction_operands.hpp\"\n#include \"tagged.hpp\"\n#include \"code_blocks.hpp\"\n#include \"bump_allocator.hpp\"\n#include \"bitwise_hacks.hpp\"\n#include \"mark_bits.hpp\"\n#include \"fixup.hpp\"\n#include \"free_list.hpp\"\n#include \"write_barrier.hpp\"\n#include \"object_start_map.hpp\"\n#include \"aging_space.hpp\"\n#include \"tenured_space.hpp\"\n#include \"data_heap.hpp\"\n#include \"code_heap.hpp\"\n#include \"gc.hpp\"\n#include \"float_bits.hpp\"\n#include \"io.hpp\"\n#include \"image.hpp\"\n#include \"callbacks.hpp\"\n#include \"dispatch.hpp\"\n#include \"vm.hpp\"\n#include \"allot.hpp\"\n#include \"data_roots.hpp\"\n#include \"code_roots.hpp\"\n#include \"generic_arrays.hpp\"\n#include \"callstack.hpp\"\n#include \"slot_visitor.hpp\"\n#include \"to_tenured_collector.hpp\"\n#include \"arrays.hpp\"\n#include \"math.hpp\"\n#include \"byte_arrays.hpp\"\n#include \"jit.hpp\"\n#include \"quotations.hpp\"\n#include \"inline_cache.hpp\"\n#include \"mvm.hpp\"\n#include \"factor.hpp\"\n\n#endif \/\/ __FACTOR_MASTER_H__\n<commit_msg>vm: fix COMPILE-TIME to use __DATE__ and __TIME__<commit_after>#ifndef __FACTOR_MASTER_H__\n#define __FACTOR_MASTER_H__\n\n#ifndef _THREAD_SAFE\n#define _THREAD_SAFE\n#endif\n\n#ifndef _REENTRANT\n#define _REENTRANT\n#endif\n\n#include <errno.h>\n\n\/\/ C headers\n#include <fcntl.h>\n#include <limits.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <wchar.h>\n#include <stdint.h>\n\n\/\/ C++ headers\n#include <algorithm>\n#include <list>\n#include <map>\n#include <set>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <sstream>\n#include <string>\n\n#define FACTOR_STRINGIZE_I(x) #x\n#define FACTOR_STRINGIZE(x) FACTOR_STRINGIZE_I(x)\n\n\/\/ Record compiler version\n#if defined(__clang__)\n#define FACTOR_COMPILER_VERSION \"Clang (GCC \" __VERSION__ \")\"\n#elif defined(__INTEL_COMPILER)\n#define FACTOR_COMPILER_VERSION \\\n \"Intel C Compiler \" FACTOR_STRINGIZE(__INTEL_COMPILER)\n#elif defined(__GNUC__)\n#define FACTOR_COMPILER_VERSION \"GCC \" __VERSION__\n#elif defined(_MSC_FULL_VER)\n#define FACTOR_COMPILER_VERSION \\\n \"Microsoft Visual C++ \" FACTOR_STRINGIZE(_MSC_FULL_VER)\n#else\n#define FACTOR_COMPILER_VERSION \"unknown\"\n#endif\n\n\/\/ Record compilation time\n#define FACTOR_COMPILE_TIME __DATE__ \" \" __TIME__\n\n\/\/ Detect target CPU type\n#if defined(__arm__)\n#define FACTOR_ARM\n#elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)\n#define FACTOR_AMD64\n#define FACTOR_64\n#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86)\n#define FACTOR_X86\n#elif(defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)) && \\\n (defined(__PPC64__) || defined(__64BIT__))\n#define FACTOR_PPC64\n#define FACTOR_PPC\n#define FACTOR_64\n#elif defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)\n#define FACTOR_PPC32\n#define FACTOR_PPC\n#else\n#error \"Unsupported architecture\"\n#endif\n\n#if defined(_MSC_VER)\n#define WINDOWS\n#define WINNT\n#elif defined(WIN32)\n#define WINDOWS\n#endif\n\n\/\/ Forward-declare this since it comes up in function prototypes\nnamespace factor { struct factor_vm; }\n\n\/\/ Factor headers\n#include \"assert.hpp\"\n#include \"debug.hpp\"\n#include \"layouts.hpp\"\n#include \"platform.hpp\"\n#include \"utilities.hpp\"\n#include \"primitives.hpp\"\n#include \"errors.hpp\"\n#include \"segments.hpp\"\n#include \"gc_info.hpp\"\n#include \"contexts.hpp\"\n#include \"run.hpp\"\n#include \"objects.hpp\"\n#include \"sampling_profiler.hpp\"\n#include \"bignumint.hpp\"\n#include \"bignum.hpp\"\n#include \"booleans.hpp\"\n#include \"instruction_operands.hpp\"\n#include \"tagged.hpp\"\n#include \"code_blocks.hpp\"\n#include \"bump_allocator.hpp\"\n#include \"bitwise_hacks.hpp\"\n#include \"mark_bits.hpp\"\n#include \"fixup.hpp\"\n#include \"free_list.hpp\"\n#include \"write_barrier.hpp\"\n#include \"object_start_map.hpp\"\n#include \"aging_space.hpp\"\n#include \"tenured_space.hpp\"\n#include \"data_heap.hpp\"\n#include \"code_heap.hpp\"\n#include \"gc.hpp\"\n#include \"float_bits.hpp\"\n#include \"io.hpp\"\n#include \"image.hpp\"\n#include \"callbacks.hpp\"\n#include \"dispatch.hpp\"\n#include \"vm.hpp\"\n#include \"allot.hpp\"\n#include \"data_roots.hpp\"\n#include \"code_roots.hpp\"\n#include \"generic_arrays.hpp\"\n#include \"callstack.hpp\"\n#include \"slot_visitor.hpp\"\n#include \"to_tenured_collector.hpp\"\n#include \"arrays.hpp\"\n#include \"math.hpp\"\n#include \"byte_arrays.hpp\"\n#include \"jit.hpp\"\n#include \"quotations.hpp\"\n#include \"inline_cache.hpp\"\n#include \"mvm.hpp\"\n#include \"factor.hpp\"\n\n#endif \/\/ __FACTOR_MASTER_H__\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/include\/dkm.hpp\"\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\nint main() {\n\tstd::vector<std::array<float, 2>> data{{1.f, 1.f}, {2.f, 2.f}, {1200.f, 1200.f}, {2.f, 2.f}};\n\tauto cluster_data = dkm::kmeans_lloyd(data, 2);\n\n\tstd::cout << \"Means:\" << std::endl;\n\tfor (const auto& mean : std::get<0>(cluster_data)) {\n\t\tstd::cout << \"\\t(\" << mean[0] << \",\" << mean[1] << \")\" << std::endl;\n\t}\n\tstd::cout << \"\\nCluster labels:\" << std::endl;\n\tstd::cout << \"\\tPoint:\";\n\tfor (const auto& point : data) {\n\t\tstd::stringstream value;\n\t\tvalue << \"(\" << point[0] << \",\" << point[1] << \")\";\n\t\tstd::cout << std::setw(14) << value.str();\n\t}\n\tstd::cout << std::endl;\n\tstd::cout << \"\\tLabel:\";\n\tfor (const auto& label : std::get<1>(cluster_data)) {\n\t\tstd::cout << std::setw(14) << label;\n\t}\n\tstd::cout << std::endl;\n}\n<commit_msg>Fixed missing braces warning on clang.<commit_after>#include \"..\/..\/include\/dkm.hpp\"\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wmissing-braces\"\n#endif\n\nint main() {\n\tstd::vector<std::array<float, 2>> data{{1.f, 1.f}, {2.f, 2.f}, {1200.f, 1200.f}, {2.f, 2.f}};\n\tauto cluster_data = dkm::kmeans_lloyd(data, 2);\n\n\tstd::cout << \"Means:\" << std::endl;\n\tfor (const auto& mean : std::get<0>(cluster_data)) {\n\t\tstd::cout << \"\\t(\" << mean[0] << \",\" << mean[1] << \")\" << std::endl;\n\t}\n\tstd::cout << \"\\nCluster labels:\" << std::endl;\n\tstd::cout << \"\\tPoint:\";\n\tfor (const auto& point : data) {\n\t\tstd::stringstream value;\n\t\tvalue << \"(\" << point[0] << \",\" << point[1] << \")\";\n\t\tstd::cout << std::setw(14) << value.str();\n\t}\n\tstd::cout << std::endl;\n\tstd::cout << \"\\tLabel:\";\n\tfor (const auto& label : std::get<1>(cluster_data)) {\n\t\tstd::cout << std::setw(14) << label;\n\t}\n\tstd::cout << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Request.hxx\"\n#include \"Stock.hxx\"\n#include \"Client.hxx\"\n#include \"http\/ResponseHandler.hxx\"\n#include \"lease.hxx\"\n#include \"access_log\/ChildErrorLog.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"pool\/LeakDetector.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"io\/UniqueFileDescriptor.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"stopwatch.hxx\"\n\n#include <sys\/socket.h>\n\nclass FcgiRequest final : Lease, Cancellable, PoolLeakDetector {\n\tstruct pool &pool;\n\n\tStockItem *stock_item;\n\n\tChildErrorLog log;\n\n\tCancellablePointer cancel_ptr;\n\npublic:\n\tFcgiRequest(struct pool &_pool, StockItem &_stock_item) noexcept\n\t\t:PoolLeakDetector(_pool),\n\t\t pool(_pool), stock_item(&_stock_item)\n\t{\n\t}\n\n\tvoid Start(EventLoop &event_loop, StopwatchPtr &&stopwatch,\n\t\t const char *site_name,\n\t\t const char *path,\n\t\t http_method_t method, const char *uri,\n\t\t const char *script_name, const char *path_info,\n\t\t const char *query_string,\n\t\t const char *document_root,\n\t\t const char *remote_addr,\n\t\t StringMap &&headers, UnusedIstreamPtr body,\n\t\t ConstBuffer<const char *> params,\n\t\t UniqueFileDescriptor &&stderr_fd,\n\t\t SocketDescriptor log_socket,\n\t\t const ChildErrorLogOptions &log_options,\n\t\t HttpResponseHandler &handler,\n\t\t CancellablePointer &caller_cancel_ptr) {\n\t\tcaller_cancel_ptr = *this;\n\n\t\tfcgi_stock_item_set_site(*stock_item, site_name);\n\t\tfcgi_stock_item_set_uri(*stock_item, uri);\n\n\t\tif (!stderr_fd.IsDefined())\n\t\t\tstderr_fd = fcgi_stock_item_get_stderr(*stock_item);\n\n\t\tif (log_socket.IsDefined() && !stderr_fd.IsDefined())\n\t\t\tstderr_fd = log.EnableClient(event_loop, log_socket,\n\t\t\t\t\t\t log_options,\n\t\t\t\t\t\t \/* TODO? *\/ true);\n\n\t\tlog.SetSite(site_name);\n\n\t\tconst char *script_filename = path;\n\n\t\tfcgi_client_request(&pool, event_loop, std::move(stopwatch),\n\t\t\t\t fcgi_stock_item_get(*stock_item),\n\t\t\t\t fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL\n\t\t\t\t ? FdType::FD_SOCKET : FdType::FD_TCP,\n\t\t\t\t *this,\n\t\t\t\t method, uri,\n\t\t\t\t script_filename,\n\t\t\t\t script_name, path_info,\n\t\t\t\t query_string,\n\t\t\t\t document_root,\n\t\t\t\t remote_addr,\n\t\t\t\t std::move(headers), std::move(body),\n\t\t\t\t params,\n\t\t\t\t std::move(stderr_fd),\n\t\t\t\t handler, cancel_ptr);\n\t}\n\nprivate:\n\tvoid Destroy() noexcept {\n\t\tDeleteFromPool(pool, this);\n\t}\n\n\t\/* virtual methods from class Cancellable *\/\n\tvoid Cancel() noexcept override {\n\t\tfcgi_stock_aborted(*stock_item);\n\n\t\tcancel_ptr.Cancel();\n\t}\n\n\t\/* virtual methods from class Lease *\/\n\tvoid ReleaseLease(bool reuse) noexcept override {\n\t\tstock_item->Put(!reuse);\n\t\tstock_item = nullptr;\n\n\t\tDestroy();\n\t}\n};\n\nvoid\nfcgi_request(struct pool *pool, EventLoop &event_loop,\n\t FcgiStock *fcgi_stock,\n\t const StopwatchPtr &parent_stopwatch,\n\t const char *site_name,\n\t const ChildOptions &options,\n\t const char *action,\n\t const char *path,\n\t ConstBuffer<const char *> args,\n\t unsigned parallelism,\n\t http_method_t method, const char *uri,\n\t const char *script_name, const char *path_info,\n\t const char *query_string,\n\t const char *document_root,\n\t const char *remote_addr,\n\t StringMap &&headers, UnusedIstreamPtr body,\n\t ConstBuffer<const char *> params,\n\t UniqueFileDescriptor &&stderr_fd,\n\t HttpResponseHandler &handler,\n\t CancellablePointer &cancel_ptr) noexcept\n{\n\tif (action == nullptr)\n\t\taction = path;\n\n\tStopwatchPtr stopwatch(parent_stopwatch, \"fcgi\", action);\n\n\tStockItem *stock_item;\n\ttry {\n\t\tstock_item = fcgi_stock_get(fcgi_stock, options,\n\t\t\t\t\t action, args, parallelism);\n\t} catch (...) {\n\t\tstopwatch.RecordEvent(\"launch_error\");\n\t\tbody.Clear();\n\t\thandler.InvokeError(std::current_exception());\n\t\treturn;\n\t}\n\n\tstopwatch.RecordEvent(\"fork\");\n\n\tauto request = NewFromPool<FcgiRequest>(*pool, *pool, *stock_item);\n\n\trequest->Start(event_loop, std::move(stopwatch),\n\t\t site_name, path, method, uri,\n\t\t script_name, path_info,\n\t\t query_string, document_root, remote_addr,\n\t\t std::move(headers), std::move(body),\n\t\t params, std::move(stderr_fd),\n\t\t fcgi_stock_get_log_socket(*fcgi_stock),\n\t\t fcgi_stock_get_log_options(*fcgi_stock),\n\t\t handler, cancel_ptr);\n}\n<commit_msg>fcgi\/Request: add `noexcept`<commit_after>\/*\n * Copyright 2007-2022 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Request.hxx\"\n#include \"Stock.hxx\"\n#include \"Client.hxx\"\n#include \"http\/ResponseHandler.hxx\"\n#include \"lease.hxx\"\n#include \"access_log\/ChildErrorLog.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"pool\/LeakDetector.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"io\/UniqueFileDescriptor.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"stopwatch.hxx\"\n\n#include <sys\/socket.h>\n\nclass FcgiRequest final : Lease, Cancellable, PoolLeakDetector {\n\tstruct pool &pool;\n\n\tStockItem *stock_item;\n\n\tChildErrorLog log;\n\n\tCancellablePointer cancel_ptr;\n\npublic:\n\tFcgiRequest(struct pool &_pool, StockItem &_stock_item) noexcept\n\t\t:PoolLeakDetector(_pool),\n\t\t pool(_pool), stock_item(&_stock_item)\n\t{\n\t}\n\n\tvoid Start(EventLoop &event_loop, StopwatchPtr &&stopwatch,\n\t\t const char *site_name,\n\t\t const char *path,\n\t\t http_method_t method, const char *uri,\n\t\t const char *script_name, const char *path_info,\n\t\t const char *query_string,\n\t\t const char *document_root,\n\t\t const char *remote_addr,\n\t\t StringMap &&headers, UnusedIstreamPtr body,\n\t\t ConstBuffer<const char *> params,\n\t\t UniqueFileDescriptor &&stderr_fd,\n\t\t SocketDescriptor log_socket,\n\t\t const ChildErrorLogOptions &log_options,\n\t\t HttpResponseHandler &handler,\n\t\t CancellablePointer &caller_cancel_ptr) noexcept {\n\t\tcaller_cancel_ptr = *this;\n\n\t\tfcgi_stock_item_set_site(*stock_item, site_name);\n\t\tfcgi_stock_item_set_uri(*stock_item, uri);\n\n\t\tif (!stderr_fd.IsDefined())\n\t\t\tstderr_fd = fcgi_stock_item_get_stderr(*stock_item);\n\n\t\tif (log_socket.IsDefined() && !stderr_fd.IsDefined())\n\t\t\tstderr_fd = log.EnableClient(event_loop, log_socket,\n\t\t\t\t\t\t log_options,\n\t\t\t\t\t\t \/* TODO? *\/ true);\n\n\t\tlog.SetSite(site_name);\n\n\t\tconst char *script_filename = path;\n\n\t\tfcgi_client_request(&pool, event_loop, std::move(stopwatch),\n\t\t\t\t fcgi_stock_item_get(*stock_item),\n\t\t\t\t fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL\n\t\t\t\t ? FdType::FD_SOCKET : FdType::FD_TCP,\n\t\t\t\t *this,\n\t\t\t\t method, uri,\n\t\t\t\t script_filename,\n\t\t\t\t script_name, path_info,\n\t\t\t\t query_string,\n\t\t\t\t document_root,\n\t\t\t\t remote_addr,\n\t\t\t\t std::move(headers), std::move(body),\n\t\t\t\t params,\n\t\t\t\t std::move(stderr_fd),\n\t\t\t\t handler, cancel_ptr);\n\t}\n\nprivate:\n\tvoid Destroy() noexcept {\n\t\tDeleteFromPool(pool, this);\n\t}\n\n\t\/* virtual methods from class Cancellable *\/\n\tvoid Cancel() noexcept override {\n\t\tfcgi_stock_aborted(*stock_item);\n\n\t\tcancel_ptr.Cancel();\n\t}\n\n\t\/* virtual methods from class Lease *\/\n\tvoid ReleaseLease(bool reuse) noexcept override {\n\t\tstock_item->Put(!reuse);\n\t\tstock_item = nullptr;\n\n\t\tDestroy();\n\t}\n};\n\nvoid\nfcgi_request(struct pool *pool, EventLoop &event_loop,\n\t FcgiStock *fcgi_stock,\n\t const StopwatchPtr &parent_stopwatch,\n\t const char *site_name,\n\t const ChildOptions &options,\n\t const char *action,\n\t const char *path,\n\t ConstBuffer<const char *> args,\n\t unsigned parallelism,\n\t http_method_t method, const char *uri,\n\t const char *script_name, const char *path_info,\n\t const char *query_string,\n\t const char *document_root,\n\t const char *remote_addr,\n\t StringMap &&headers, UnusedIstreamPtr body,\n\t ConstBuffer<const char *> params,\n\t UniqueFileDescriptor &&stderr_fd,\n\t HttpResponseHandler &handler,\n\t CancellablePointer &cancel_ptr) noexcept\n{\n\tif (action == nullptr)\n\t\taction = path;\n\n\tStopwatchPtr stopwatch(parent_stopwatch, \"fcgi\", action);\n\n\tStockItem *stock_item;\n\ttry {\n\t\tstock_item = fcgi_stock_get(fcgi_stock, options,\n\t\t\t\t\t action, args, parallelism);\n\t} catch (...) {\n\t\tstopwatch.RecordEvent(\"launch_error\");\n\t\tbody.Clear();\n\t\thandler.InvokeError(std::current_exception());\n\t\treturn;\n\t}\n\n\tstopwatch.RecordEvent(\"fork\");\n\n\tauto request = NewFromPool<FcgiRequest>(*pool, *pool, *stock_item);\n\n\trequest->Start(event_loop, std::move(stopwatch),\n\t\t site_name, path, method, uri,\n\t\t script_name, path_info,\n\t\t query_string, document_root, remote_addr,\n\t\t std::move(headers), std::move(body),\n\t\t params, std::move(stderr_fd),\n\t\t fcgi_stock_get_log_socket(*fcgi_stock),\n\t\t fcgi_stock_get_log_options(*fcgi_stock),\n\t\t handler, cancel_ptr);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fffuncparser.h>\n\n#ifdef FF_DEBUG\n# include <cstdio>\n#endif\n\nusing namespace ff;\n\nFuncParser::FuncParser(int argc, const char ** argv)\n :m_index(clang_createIndex(0, 0))\n ,m_tunit()\n ,m_argc(argc)\n ,m_argv(argv)\n ,m_func_list()\n ,m_file()\n{\n\n}\n\nFuncParser::~FuncParser()\n{\n clang_disposeIndex(this->m_index);\n clang_disposeTranslationUnit(this->m_tunit);\n}\n\nbool\nFuncParser::parse(const std::string &file)\n{\n if (file.empty()) {\n return false;\n }\n\n this->m_file = file;\n\n return this->startParse();\n}\n\nvoid FuncParser::unregisterKind(CXCursorKind kind)\n{\n for (std::vector<CXCursorKind>::iterator it = this->m_kind.begin();\n it != this->m_kind.end();it ++) {\n if (*it == kind) {\n this->m_kind.erase(it);\n break;\n }\n }\n}\n\nbool\nFuncParser::startParse()\n{\n this->m_tunit = clang_parseTranslationUnit(this->m_index,\n this->m_file.c_str(),\n this->m_argv,\n this->m_argc,\n nullptr,\n 0,\n CXTranslationUnit_None);\n\n CXCursor cursor = clang_getTranslationUnitCursor(this->m_tunit);\n\n int ret = clang_visitChildren(cursor, FuncParser::FP_vistor, CXClientData(this));\n\n return bool(ret == 0);\n}\n\nvoid\nFuncParser::visitCursor(CXCursor cursor)\n{\n CXCursorKind kind = clang_getCursorKind(cursor);\n\n#ifndef FF_DEBUG\n if (this->filterKind(kind)) {\n return ;\n }\n#endif\n\n CXString str = clang_getCursorKindSpelling(kind);\n\n FF_AVOID_WARNING(str);\n \/\/add parser cpp or header file\n\n#ifdef FF_DEBUG\n std::fprintf(stderr, \"CursorKind:%s\\n\", clang_getCString(str));\n#endif\n}\n\nCXChildVisitResult\nFuncParser::FP_vistor(CXCursor cursor, CXCursor parent, CXClientData data)\n{\n FF_AVOID_WARNING(parent);\n\n FuncParser* fp = static_cast<FuncParser*>(data);\n\n fp->visitCursor(cursor);\n\n return CXChildVisit_Continue;\n}\n\nbool\nFuncParser::filterKind(CXCursorKind kind)\n{\n for (std::vector<CXCursorKind>::iterator it = this->m_kind.begin();\n it != this->m_kind.end();it ++) {\n if (*it == kind) {\n return false;\n }\n }\n\n return true;\n}\n\n\n<commit_msg>add parse CursorKind switch..<commit_after>#include <fffuncparser.h>\n\n#ifdef FF_DEBUG\n# include <cstdio>\n#endif\n\nusing namespace ff;\n\nFuncParser::FuncParser(int argc, const char ** argv)\n :m_index(clang_createIndex(0, 0))\n ,m_tu()\n ,m_argc(argc)\n ,m_argv(argv)\n ,m_func_list()\n ,m_file()\n{\n this->registerKind(CXCursor_FunctionDecl);\n this->registerKind(CXCursor_FunctionTemplate);\n this->registerKind(CXCursor_CXXMethod);\n this->registerKind(CXCursor_Constructor);\n this->registerKind(CXCursor_Destructor);\n this->registerKind(CXCursor_ConversionFunction);\n this->registerKind(CXCursor_ClassDecl);\n this->registerKind(CXCursor_StructDecl);\n}\n\nFuncParser::~FuncParser()\n{\n\n}\n\nbool\nFuncParser::parse(const std::string &file)\n{\n if (file.empty()) {\n return false;\n }\n\n m_file = file;\n\n return this->startParse();\n}\n\nvoid FuncParser::unregisterKind(CXCursorKind kind)\n{\n m_kind.erase(kind);\n}\n\nbool\nFuncParser::startParse()\n{\n m_tu = clang_parseTranslationUnit(\n m_index,\n m_file.c_str(),\n m_argv,\n m_argc,\n nullptr,\n 0,\n CXTranslationUnit_None\n );\n\n CXCursor cursor = clang_getTranslationUnitCursor(m_tu);\n\n int ret = clang_visitChildren(cursor, FuncParser::FP_vistor, CXClientData(this));\n\n return bool(ret == 0);\n}\n\nCXChildVisitResult\nFuncParser::visitCursor(CXCursor cursor)\n{\n CXCursorKind kind = clang_getCursorKind(cursor);\n\n if (this->filterKind(kind)) {\n return CXChildVisit_Continue;\n }\n\n switch(kind) {\n case CXCursor_FunctionDecl: { }\n case CXCursor_FunctionTemplate: { }\n case CXCursor_CXXMethod: { }\n case CXCursor_Constructor: { }\n case CXCursor_Destructor: { }\n case CXCursor_ConversionFunction: { }\n case CXCursor_ClassDecl: { }\n case CXCursor_StructDecl: { }\n default: { }\n }\n\n return CXChildVisit_Continue;\n}\n\nCXChildVisitResult\nFuncParser::FP_vistor(CXCursor cursor, CXCursor parent, CXClientData data)\n{\n FF_AVOID_WARNING(parent);\n\n FuncParser* fp = static_cast<FuncParser*>(data);\n\n return fp->visitCursor(cursor);\n}\n\nbool\nFuncParser::filterKind(CXCursorKind kind)\n{\n return m_kind.count(kind) > 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003-2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/file_storage.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include <boost\/bind.hpp>\n\n\nnamespace libtorrent\n{\n\tfile_storage::file_storage()\n\t\t: m_piece_length(0)\n\t\t, m_total_size(0)\n\t\t, m_num_pieces(0)\n\t{}\n\n\tint file_storage::piece_size(int index) const\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < num_pieces());\n\t\tif (index == num_pieces()-1)\n\t\t{\n\t\t\tint size = int(total_size()\n\t\t\t\t- size_type(num_pieces() - 1) * piece_length());\n\t\t\tTORRENT_ASSERT(size > 0);\n\t\t\tTORRENT_ASSERT(size <= piece_length());\n\t\t\treturn int(size);\n\t\t}\n\t\telse\n\t\t\treturn piece_length();\n\t}\n\n\tvoid file_storage::set_name(std::wstring const& n)\n\t{\n\t\tstd::string utf8;\n\t\twchar_utf8(n, utf8);\n\t\tm_name = utf8;\n\t}\n\n\tvoid file_storage::rename_file(int index, std::string const& new_filename)\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < int(m_files.size()));\n\t\tm_files[index].path = new_filename;\n\t}\n\n\tvoid file_storage::rename_file(int index, std::wstring const& new_filename)\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < int(m_files.size()));\n\t\tstd::string utf8;\n\t\twchar_utf8(new_filename, utf8);\n\t\tm_files[index].path = utf8;\n\t}\n\n\tfile_storage::iterator file_storage::file_at_offset(size_type offset) const\n\t{\n\t\t\/\/ TODO: do a binary search\n\t\tstd::vector<file_entry>::const_iterator i;\n\t\tfor (i = begin(); i != end(); ++i)\n\t\t{\n\t\t\tif (i->offset <= offset && i->offset + i->size > offset)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn i;\n\t}\n\n\tstd::vector<file_slice> file_storage::map_block(int piece, size_type offset\n\t\t, int size_) const\n\t{\n\t\tTORRENT_ASSERT(num_files() > 0);\n\t\tstd::vector<file_slice> ret;\n\n\t\tsize_type start = piece * (size_type)m_piece_length + offset;\n\t\tsize_type size = size_;\n\t\tTORRENT_ASSERT(start + size <= m_total_size);\n\n\t\t\/\/ find the file iterator and file offset\n\t\t\/\/ TODO: do a binary search on the file offsets\n\t\tsize_type file_offset = start;\n\t\tstd::vector<file_entry>::const_iterator file_iter;\n\n\t\tint counter = 0;\n\t\tfor (file_iter = begin();; ++counter, ++file_iter)\n\t\t{\n\t\t\tTORRENT_ASSERT(file_iter != end());\n\t\t\tif (file_offset < file_iter->size)\n\t\t\t{\n\t\t\t\tfile_slice f;\n\t\t\t\tf.file_index = counter;\n\t\t\t\tf.offset = file_offset + file_iter->file_base;\n\t\t\t\tf.size = (std::min)(file_iter->size - file_offset, (size_type)size);\n\t\t\t\tsize -= f.size;\n\t\t\t\tfile_offset += f.size;\n\t\t\t\tret.push_back(f);\n\t\t\t}\n\t\t\t\n\t\t\tTORRENT_ASSERT(size >= 0);\n\t\t\tif (size <= 0) break;\n\n\t\t\tfile_offset -= file_iter->size;\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\tpeer_request file_storage::map_file(int file_index, size_type file_offset\n\t\t, int size) const\n\t{\n\t\tTORRENT_ASSERT(file_index < num_files());\n\t\tTORRENT_ASSERT(file_index >= 0);\n\t\tsize_type offset = file_offset + at(file_index).offset;\n\n\t\tpeer_request ret;\n\t\tret.piece = int(offset \/ piece_length());\n\t\tret.start = int(offset - ret.piece * piece_length());\n\t\tret.length = size;\n\t\treturn ret;\n\t}\n\n\tvoid file_storage::add_file(fs::wpath const& file, size_type size, int flags)\n\t{\n\t\tstd::string utf8;\n\t\twchar_utf8(file.string(), utf8);\n\t\tadd_file(utf8, size, flags);\n\t}\n\n\tvoid file_storage::add_file(fs::path const& file, size_type size, int flags)\n\t{\n\t\tTORRENT_ASSERT(size >= 0);\n#if BOOST_VERSION < 103600\n\t\tif (!file.has_branch_path())\n#else\n\t\tif (!file.has_parent_path())\n#endif\n\t\t{\n\t\t\t\/\/ you have already added at least one file with a\n\t\t\t\/\/ path to the file (branch_path), which means that\n\t\t\t\/\/ all the other files need to be in the same top\n\t\t\t\/\/ directory as the first file.\n\t\t\tTORRENT_ASSERT(m_files.empty());\n\t\t\tm_name = file.string();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (m_files.empty())\n\t\t\t\tm_name = *file.begin();\n\t\t}\n\t\tTORRENT_ASSERT(m_name == *file.begin());\n\t\tm_files.push_back(file_entry());\n\t\tfile_entry& e = m_files.back();\n\t\te.size = size;\n\t\te.path = file;\n\t\te.offset = m_total_size;\n\t\te.pad_file = bool(flags & pad_file);\n\t\te.hidden_attribute = bool(flags & attribute_hidden);\n\t\te.executable_attribute = bool(flags & attribute_executable);\n\t\tm_total_size += size;\n\t}\n\n\tvoid file_storage::add_file(file_entry const& ent)\n\t{\n#if BOOST_VERSION < 103600\n\t\tif (!ent.path.has_branch_path())\n#else\n\t\tif (!ent.path.has_parent_path())\n#endif\n\t\t{\n\t\t\t\/\/ you have already added at least one file with a\n\t\t\t\/\/ path to the file (branch_path), which means that\n\t\t\t\/\/ all the other files need to be in the same top\n\t\t\t\/\/ directory as the first file.\n\t\t\tTORRENT_ASSERT(m_files.empty());\n\t\t\tm_name = ent.path.string();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (m_files.empty())\n\t\t\t\tm_name = *ent.path.begin();\n\t\t}\n\t\tm_files.push_back(ent);\n\t\tfile_entry& e = m_files.back();\n\t\te.offset = m_total_size;\n\t\tm_total_size += ent.size;\n\t}\n\n\tvoid file_storage::optimize(int pad_file_limit)\n\t{\n\t\t\/\/ the main purpuse of padding is to optimize disk\n\t\t\/\/ I\/O. This is a conservative memory page size assumption\n\t\tint alignment = 8*1024;\n\n\t\t\/\/ it doesn't make any sense to pad files that\n\t\t\/\/ are smaller than one piece\n\t\tif (pad_file_limit >= 0 && pad_file_limit < alignment)\n\t\t\tpad_file_limit = alignment;\n\n\t\t\/\/ put the largest file at the front, to make sure\n\t\t\/\/ it's aligned\n\t\tstd::vector<file_entry>::iterator i = std::max_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&file_entry::size, _1) < boost::bind(&file_entry::size, _2));\n\n\t\tusing std::iter_swap;\n\t\titer_swap(i, m_files.begin());\n\n\t\tsize_type off = 0;\n\t\tint padding_file = 0;\n\t\tfor (std::vector<file_entry>::iterator i = m_files.begin();\n\t\t\ti != m_files.end(); ++i)\n\t\t{\n\t\t\tif (pad_file_limit >= 0\n\t\t\t\t&& (off & (alignment-1)) != 0\n\t\t\t\t&& i->size > pad_file_limit\n\t\t\t\t&& i->pad_file == false)\n\t\t\t{\n\t\t\t\t\/\/ if we have pad files enabled, and this file is\n\t\t\t\t\/\/ not piece-aligned and the file size exceeds the\n\t\t\t\t\/\/ limit, and it's not a padding file itself.\n\t\t\t\t\/\/ so add a padding file in front of it\n\t\t\t\tint pad_size = alignment - (off & (alignment-1));\n\t\t\t\t\n\t\t\t\t\/\/ find the largest file that fits in pad_size\n\t\t\t\tstd::vector<file_entry>::iterator best_match = m_files.end();\n\t\t\t\tfor (std::vector<file_entry>::iterator j = i+1; j < m_files.end(); ++j)\n\t\t\t\t{\n\t\t\t\t\tif (j->size > pad_size) continue;\n\t\t\t\t\tif (best_match == m_files.end() || j->size > best_match->size)\n\t\t\t\t\t\tbest_match = j;\n\t\t\t\t}\n\n\t\t\t\tif (best_match != m_files.end())\n\t\t\t\t{\n\t\t\t\t\t\/\/ we found one\n\t\t\t\t\tfile_entry e = *best_match;\n\t\t\t\t\tm_files.erase(best_match);\n\t\t\t\t\ti = m_files.insert(i, e);\n\t\t\t\t\ti->offset = off;\n\t\t\t\t\toff += i->size;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ we could not find a file that fits in pad_size\n\t\t\t\t\/\/ add a padding file\n\n\t\t\t\tfile_entry e;\n\t\t\t\ti = m_files.insert(i, e);\n\t\t\t\ti->size = pad_size;\n\t\t\t\ti->offset = off;\n\t\t\t\ti->file_base = 0;\n\t\t\t\tchar name[10];\n\t\t\t\tsprintf(name, \"%d\", padding_file);\n\t\t\t\ti->path = *(i+1)->path.begin();\n\t\t\t\ti->path \/= \"_____padding_file_\";\n\t\t\t\ti->path \/= name;\n\t\t\t\ti->pad_file = true;\n\t\t\t\toff += pad_size;\n\t\t\t\t++padding_file;\n\t\t\t\t++i;\n\t\t\t}\n\t\t\ti->offset = off;\n\t\t\toff += i->size;\n\t\t}\n\t\tm_total_size = off;\n\t}\n}\n\n<commit_msg>optimized file_storage::map_block to use lower_bound instead of linear search<commit_after>\/*\n\nCopyright (c) 2003-2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/file_storage.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include <boost\/bind.hpp>\n\n\nnamespace libtorrent\n{\n\tfile_storage::file_storage()\n\t\t: m_piece_length(0)\n\t\t, m_total_size(0)\n\t\t, m_num_pieces(0)\n\t{}\n\n\tint file_storage::piece_size(int index) const\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < num_pieces());\n\t\tif (index == num_pieces()-1)\n\t\t{\n\t\t\tint size = int(total_size()\n\t\t\t\t- size_type(num_pieces() - 1) * piece_length());\n\t\t\tTORRENT_ASSERT(size > 0);\n\t\t\tTORRENT_ASSERT(size <= piece_length());\n\t\t\treturn int(size);\n\t\t}\n\t\telse\n\t\t\treturn piece_length();\n\t}\n\n\tvoid file_storage::set_name(std::wstring const& n)\n\t{\n\t\tstd::string utf8;\n\t\twchar_utf8(n, utf8);\n\t\tm_name = utf8;\n\t}\n\n\tvoid file_storage::rename_file(int index, std::string const& new_filename)\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < int(m_files.size()));\n\t\tm_files[index].path = new_filename;\n\t}\n\n\tvoid file_storage::rename_file(int index, std::wstring const& new_filename)\n\t{\n\t\tTORRENT_ASSERT(index >= 0 && index < int(m_files.size()));\n\t\tstd::string utf8;\n\t\twchar_utf8(new_filename, utf8);\n\t\tm_files[index].path = utf8;\n\t}\n\n\tfile_storage::iterator file_storage::file_at_offset(size_type offset) const\n\t{\n\t\t\/\/ TODO: do a binary search\n\t\tstd::vector<file_entry>::const_iterator i;\n\t\tfor (i = begin(); i != end(); ++i)\n\t\t{\n\t\t\tif (i->offset <= offset && i->offset + i->size > offset)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn i;\n\t}\n\n\tnamespace\n\t{\n\t\tbool compare_file_offset(file_entry const& lhs, file_entry const& rhs)\n\t\t{\n\t\t\treturn lhs.offset + lhs.size < rhs.offset + rhs.size;\n\t\t}\n\t}\n\n\tstd::vector<file_slice> file_storage::map_block(int piece, size_type offset\n\t\t, int size) const\n\t{\n\t\tTORRENT_ASSERT(num_files() > 0);\n\t\tstd::vector<file_slice> ret;\n\n\t\t\/\/ find the file iterator and file offset\n\t\tfile_entry target;\n\t\ttarget.offset = piece * (size_type)m_piece_length + offset;\n\t\ttarget.size = 0;\n\t\tTORRENT_ASSERT(target.offset + size <= m_total_size);\n\n\t\tstd::vector<file_entry>::const_iterator file_iter = std::upper_bound(\n\t\t\tbegin(), end(), target, compare_file_offset);\n\n\t\tif (file_iter == end()) return ret;\n\n\t\tsize_type file_offset = file_iter->offset;\n\t\tfor (; size > 0; file_offset -= file_iter->size, ++file_iter)\n\t\t{\n\t\t\tTORRENT_ASSERT(file_iter != end());\n\t\t\tif (file_offset < file_iter->size)\n\t\t\t{\n\t\t\t\tfile_slice f;\n\t\t\t\tf.file_index = file_iter - begin();\n\t\t\t\tf.offset = file_offset + file_iter->file_base;\n\t\t\t\tf.size = (std::min)(file_iter->size - file_offset, (size_type)size);\n\t\t\t\tsize -= f.size;\n\t\t\t\tfile_offset += f.size;\n\t\t\t\tret.push_back(f);\n\t\t\t}\n\t\t\t\n\t\t\tTORRENT_ASSERT(size >= 0);\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\tpeer_request file_storage::map_file(int file_index, size_type file_offset\n\t\t, int size) const\n\t{\n\t\tTORRENT_ASSERT(file_index < num_files());\n\t\tTORRENT_ASSERT(file_index >= 0);\n\t\tsize_type offset = file_offset + at(file_index).offset;\n\n\t\tpeer_request ret;\n\t\tret.piece = int(offset \/ piece_length());\n\t\tret.start = int(offset - ret.piece * piece_length());\n\t\tret.length = size;\n\t\treturn ret;\n\t}\n\n\tvoid file_storage::add_file(fs::wpath const& file, size_type size, int flags)\n\t{\n\t\tstd::string utf8;\n\t\twchar_utf8(file.string(), utf8);\n\t\tadd_file(utf8, size, flags);\n\t}\n\n\tvoid file_storage::add_file(fs::path const& file, size_type size, int flags)\n\t{\n\t\tTORRENT_ASSERT(size >= 0);\n#if BOOST_VERSION < 103600\n\t\tif (!file.has_branch_path())\n#else\n\t\tif (!file.has_parent_path())\n#endif\n\t\t{\n\t\t\t\/\/ you have already added at least one file with a\n\t\t\t\/\/ path to the file (branch_path), which means that\n\t\t\t\/\/ all the other files need to be in the same top\n\t\t\t\/\/ directory as the first file.\n\t\t\tTORRENT_ASSERT(m_files.empty());\n\t\t\tm_name = file.string();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (m_files.empty())\n\t\t\t\tm_name = *file.begin();\n\t\t}\n\t\tTORRENT_ASSERT(m_name == *file.begin());\n\t\tm_files.push_back(file_entry());\n\t\tfile_entry& e = m_files.back();\n\t\te.size = size;\n\t\te.path = file;\n\t\te.offset = m_total_size;\n\t\te.pad_file = bool(flags & pad_file);\n\t\te.hidden_attribute = bool(flags & attribute_hidden);\n\t\te.executable_attribute = bool(flags & attribute_executable);\n\t\tm_total_size += size;\n\t}\n\n\tvoid file_storage::add_file(file_entry const& ent)\n\t{\n#if BOOST_VERSION < 103600\n\t\tif (!ent.path.has_branch_path())\n#else\n\t\tif (!ent.path.has_parent_path())\n#endif\n\t\t{\n\t\t\t\/\/ you have already added at least one file with a\n\t\t\t\/\/ path to the file (branch_path), which means that\n\t\t\t\/\/ all the other files need to be in the same top\n\t\t\t\/\/ directory as the first file.\n\t\t\tTORRENT_ASSERT(m_files.empty());\n\t\t\tm_name = ent.path.string();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (m_files.empty())\n\t\t\t\tm_name = *ent.path.begin();\n\t\t}\n\t\tm_files.push_back(ent);\n\t\tfile_entry& e = m_files.back();\n\t\te.offset = m_total_size;\n\t\tm_total_size += ent.size;\n\t}\n\n\tvoid file_storage::optimize(int pad_file_limit)\n\t{\n\t\t\/\/ the main purpuse of padding is to optimize disk\n\t\t\/\/ I\/O. This is a conservative memory page size assumption\n\t\tint alignment = 8*1024;\n\n\t\t\/\/ it doesn't make any sense to pad files that\n\t\t\/\/ are smaller than one piece\n\t\tif (pad_file_limit >= 0 && pad_file_limit < alignment)\n\t\t\tpad_file_limit = alignment;\n\n\t\t\/\/ put the largest file at the front, to make sure\n\t\t\/\/ it's aligned\n\t\tstd::vector<file_entry>::iterator i = std::max_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&file_entry::size, _1) < boost::bind(&file_entry::size, _2));\n\n\t\tusing std::iter_swap;\n\t\titer_swap(i, m_files.begin());\n\n\t\tsize_type off = 0;\n\t\tint padding_file = 0;\n\t\tfor (std::vector<file_entry>::iterator i = m_files.begin();\n\t\t\ti != m_files.end(); ++i)\n\t\t{\n\t\t\tif (pad_file_limit >= 0\n\t\t\t\t&& (off & (alignment-1)) != 0\n\t\t\t\t&& i->size > pad_file_limit\n\t\t\t\t&& i->pad_file == false)\n\t\t\t{\n\t\t\t\t\/\/ if we have pad files enabled, and this file is\n\t\t\t\t\/\/ not piece-aligned and the file size exceeds the\n\t\t\t\t\/\/ limit, and it's not a padding file itself.\n\t\t\t\t\/\/ so add a padding file in front of it\n\t\t\t\tint pad_size = alignment - (off & (alignment-1));\n\t\t\t\t\n\t\t\t\t\/\/ find the largest file that fits in pad_size\n\t\t\t\tstd::vector<file_entry>::iterator best_match = m_files.end();\n\t\t\t\tfor (std::vector<file_entry>::iterator j = i+1; j < m_files.end(); ++j)\n\t\t\t\t{\n\t\t\t\t\tif (j->size > pad_size) continue;\n\t\t\t\t\tif (best_match == m_files.end() || j->size > best_match->size)\n\t\t\t\t\t\tbest_match = j;\n\t\t\t\t}\n\n\t\t\t\tif (best_match != m_files.end())\n\t\t\t\t{\n\t\t\t\t\t\/\/ we found one\n\t\t\t\t\tfile_entry e = *best_match;\n\t\t\t\t\tm_files.erase(best_match);\n\t\t\t\t\ti = m_files.insert(i, e);\n\t\t\t\t\ti->offset = off;\n\t\t\t\t\toff += i->size;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ we could not find a file that fits in pad_size\n\t\t\t\t\/\/ add a padding file\n\n\t\t\t\tfile_entry e;\n\t\t\t\ti = m_files.insert(i, e);\n\t\t\t\ti->size = pad_size;\n\t\t\t\ti->offset = off;\n\t\t\t\ti->file_base = 0;\n\t\t\t\tchar name[10];\n\t\t\t\tsprintf(name, \"%d\", padding_file);\n\t\t\t\ti->path = *(i+1)->path.begin();\n\t\t\t\ti->path \/= \"_____padding_file_\";\n\t\t\t\ti->path \/= name;\n\t\t\t\ti->pad_file = true;\n\t\t\t\toff += pad_size;\n\t\t\t\t++padding_file;\n\t\t\t\t++i;\n\t\t\t}\n\t\t\ti->offset = off;\n\t\t\toff += i->size;\n\t\t}\n\t\tm_total_size = off;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"build.h\"\n\n#include <stdio.h>\n\n#include \"build_log.h\"\n#include \"graph.h\"\n#include \"ninja.h\"\n#include \"subprocess.h\"\n\nstruct BuildStatus {\n BuildStatus();\n virtual void PlanHasTotalEdges(int total);\n virtual void BuildEdgeStarted(Edge* edge);\n virtual void BuildEdgeFinished(Edge* edge);\n\n time_t last_update_;\n int finished_edges_, total_edges_;\n\n BuildConfig::Verbosity verbosity_;\n};\n\nBuildStatus::BuildStatus()\n : last_update_(time(NULL)), finished_edges_(0), total_edges_(0),\n verbosity_(BuildConfig::NORMAL) {}\n\nvoid BuildStatus::PlanHasTotalEdges(int total) {\n total_edges_ = total;\n}\n\nvoid BuildStatus::BuildEdgeStarted(Edge* edge) {\n string desc = edge->GetDescription();\n if (verbosity_ != BuildConfig::QUIET) {\n if (verbosity_ != BuildConfig::VERBOSE && !desc.empty())\n printf(\"%s\\n\", desc.c_str());\n else\n printf(\"%s\\n\", edge->EvaluateCommand().c_str());\n }\n}\n\nvoid BuildStatus::BuildEdgeFinished(Edge* edge) {\n ++finished_edges_;\n time_t now = time(NULL);\n if (now - last_update_ > 5) {\n printf(\"%.1f%% %d\/%d\\n\", finished_edges_ * 100 \/ (float)total_edges_,\n finished_edges_, total_edges_);\n last_update_ = now;\n }\n}\n\nbool Plan::AddTarget(Node* node, string* err) {\n vector<Node*> stack;\n return AddSubTarget(node, &stack, err);\n}\n\nbool Plan::AddSubTarget(Node* node, vector<Node*>* stack, string* err) {\n Edge* edge = node->in_edge_;\n if (!edge) { \/\/ Leaf node.\n if (node->dirty_) {\n string referenced;\n if (!stack->empty())\n referenced = \", needed by '\" + stack->back()->file_->path_ + \"',\";\n *err = \"'\" + node->file_->path_ + \"'\" + referenced + \" missing \"\n \"and no known rule to make it\";\n }\n return false;\n }\n assert(edge);\n\n if (CheckDependencyCycle(node, stack, err))\n return false;\n\n if (!node->dirty())\n return false; \/\/ Don't need to do anything.\n if (want_.find(edge) != want_.end())\n return true; \/\/ We've already enqueued it.\n want_.insert(edge);\n\n stack->push_back(node);\n bool awaiting_inputs = false;\n for (vector<Node*>::iterator i = edge->inputs_.begin();\n i != edge->inputs_.end(); ++i) {\n if (!edge->is_implicit(i - edge->inputs_.begin()) &&\n AddSubTarget(*i, stack, err)) {\n awaiting_inputs = true;\n } else if (!err->empty()) {\n return false;\n }\n }\n assert(stack->back() == node);\n stack->pop_back();\n\n if (!awaiting_inputs)\n ready_.insert(edge);\n\n return true;\n}\n\nbool Plan::CheckDependencyCycle(Node* node, vector<Node*>* stack, string* err) {\n vector<Node*>::reverse_iterator ri =\n find(stack->rbegin(), stack->rend(), node);\n if (ri == stack->rend())\n return false;\n\n \/\/ Add this node onto the stack to make it clearer where the loop\n \/\/ is.\n stack->push_back(node);\n\n vector<Node*>::iterator start = find(stack->begin(), stack->end(), node);\n *err = \"dependency cycle: \";\n for (vector<Node*>::iterator i = start; i != stack->end(); ++i) {\n if (i != start)\n err->append(\" -> \");\n err->append((*i)->file_->path_);\n }\n return true;\n}\n\nEdge* Plan::FindWork() {\n if (ready_.empty())\n return NULL;\n set<Edge*>::iterator i = ready_.begin();\n Edge* edge = *i;\n ready_.erase(i);\n return edge;\n}\n\nvoid Plan::EdgeFinished(Edge* edge) {\n want_.erase(edge);\n\n \/\/ Check off any nodes we were waiting for with this edge.\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n NodeFinished(*i);\n }\n}\n\nvoid Plan::NodeFinished(Node* node) {\n \/\/ See if we we want any edges from this node.\n for (vector<Edge*>::iterator i = node->out_edges_.begin();\n i != node->out_edges_.end(); ++i) {\n if (want_.find(*i) != want_.end()) {\n \/\/ See if the edge is now ready.\n bool ready = true;\n for (vector<Node*>::iterator j = (*i)->inputs_.begin();\n j != (*i)->inputs_.end(); ++j) {\n if ((*j)->dirty()) {\n ready = false;\n break;\n }\n }\n if (ready)\n ready_.insert(*i);\n }\n }\n}\n\nvoid Plan::Dump() {\n printf(\"pending: %d\\n\", (int)want_.size());\n for (set<Edge*>::iterator i = want_.begin(); i != want_.end(); ++i) {\n (*i)->Dump();\n }\n printf(\"ready: %d\\n\", (int)ready_.size());\n}\n\nstruct RealCommandRunner : public CommandRunner {\n virtual ~RealCommandRunner() {}\n virtual bool CanRunMore();\n virtual bool StartCommand(Edge* edge);\n virtual bool WaitForCommands();\n virtual Edge* NextFinishedCommand(bool* success);\n\n SubprocessSet subprocs_;\n map<Subprocess*, Edge*> subproc_to_edge_;\n};\n\nbool RealCommandRunner::CanRunMore() {\n const size_t kConcurrency = 8; \/\/ XXX make configurable etc.\n return subprocs_.running_.size() < kConcurrency;\n}\n\nbool RealCommandRunner::StartCommand(Edge* edge) {\n string command = edge->EvaluateCommand();\n Subprocess* subproc = new Subprocess;\n subproc_to_edge_.insert(make_pair(subproc, edge));\n if (!subproc->Start(command))\n return false;\n\n subprocs_.Add(subproc);\n return true;\n}\n\nbool RealCommandRunner::WaitForCommands() {\n if (subprocs_.running_.empty())\n return false;\n\n while (subprocs_.finished_.empty()) {\n subprocs_.DoWork();\n }\n return true;\n}\n\nEdge* RealCommandRunner::NextFinishedCommand(bool* success) {\n Subprocess* subproc = subprocs_.NextFinished();\n if (!subproc)\n return NULL;\n\n *success = subproc->Finish();\n\n map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);\n Edge* edge = i->second;\n subproc_to_edge_.erase(i);\n\n if (!*success)\n printf(\"FAILED: %s\\n\", edge->EvaluateCommand().c_str());\n if (!subproc->stdout_.buf_.empty())\n printf(\"%s\\n\", subproc->stdout_.buf_.c_str());\n if (!subproc->stderr_.buf_.empty())\n printf(\"%s\\n\", subproc->stderr_.buf_.c_str());\n\n delete subproc;\n return edge;\n}\n\nstruct DryRunCommandRunner : public CommandRunner {\n virtual ~DryRunCommandRunner() {}\n virtual bool CanRunMore() {\n return true;\n }\n virtual bool StartCommand(Edge* edge) {\n finished_.push(edge);\n return true;\n }\n virtual bool WaitForCommands() {\n return true;\n }\n virtual Edge* NextFinishedCommand(bool* success) {\n if (finished_.empty())\n return NULL;\n *success = true;\n Edge* edge = finished_.front();\n finished_.pop();\n return edge;\n }\n\n queue<Edge*> finished_;\n};\n\nBuilder::Builder(State* state, const BuildConfig& config)\n : state_(state) {\n disk_interface_ = new RealDiskInterface;\n if (config.dry_run)\n command_runner_ = new DryRunCommandRunner;\n else\n command_runner_ = new RealCommandRunner;\n status_ = new BuildStatus;\n status_->verbosity_ = config.verbosity;\n log_ = state->build_log_;\n}\n\nNode* Builder::AddTarget(const string& name, string* err) {\n Node* node = state_->LookupNode(name);\n if (!node) {\n *err = \"unknown target: '\" + name + \"'\";\n return NULL;\n }\n node->file_->StatIfNecessary(disk_interface_);\n if (node->in_edge_) {\n if (!node->in_edge_->RecomputeDirty(state_, disk_interface_, err))\n return NULL;\n }\n if (!node->dirty_)\n return NULL; \/\/ Intentionally no error.\n\n if (!plan_.AddTarget(node, err))\n return NULL;\n return node;\n}\n\nbool Builder::Build(string* err) {\n if (!plan_.more_to_do()) {\n *err = \"no work to do\";\n return true;\n }\n\n status_->PlanHasTotalEdges(plan_.edge_count());\n while (plan_.more_to_do()) {\n while (command_runner_->CanRunMore()) {\n Edge* edge = plan_.FindWork();\n if (!edge)\n break;\n\n if (edge->rule_ == &State::kPhonyRule) {\n FinishEdge(edge);\n continue;\n }\n\n if (!StartEdge(edge, err))\n return false;\n }\n\n bool success;\n if (Edge* edge = command_runner_->NextFinishedCommand(&success)) {\n if (!success) {\n *err = \"subcommand failed\";\n return false;\n }\n FinishEdge(edge);\n } else {\n if (!command_runner_->WaitForCommands()) {\n *err = \"stuck [this is a bug]\";\n return false;\n }\n }\n }\n\n return true;\n}\n\nbool Builder::StartEdge(Edge* edge, string* err) {\n status_->BuildEdgeStarted(edge);\n\n \/\/ Create directories necessary for outputs.\n \/\/ XXX: this will block; do we care?\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n if (!disk_interface_->MakeDirs((*i)->file_->path_))\n return false;\n }\n\n \/\/ Compute command and start it.\n string command = edge->EvaluateCommand();\n if (!command_runner_->StartCommand(edge)) {\n err->assign(\"command '\" + command + \"' failed.\");\n return false;\n }\n\n return true;\n}\n\nvoid Builder::FinishEdge(Edge* edge) {\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n \/\/ XXX check that the output actually changed\n \/\/ XXX just notify node and have it propagate?\n (*i)->dirty_ = false;\n }\n plan_.EdgeFinished(edge);\n status_->BuildEdgeFinished(edge);\n log_->RecordCommand(edge, 0); \/\/ XXX get edge timing.\n}\n<commit_msg>compute edge timing<commit_after>#include \"build.h\"\n\n#include <stdio.h>\n#include <sys\/time.h>\n\n#include \"build_log.h\"\n#include \"graph.h\"\n#include \"ninja.h\"\n#include \"subprocess.h\"\n\nstruct BuildStatus {\n BuildStatus();\n virtual void PlanHasTotalEdges(int total);\n virtual void BuildEdgeStarted(Edge* edge);\n virtual void BuildEdgeFinished(Edge* edge);\n\n time_t last_update_;\n int finished_edges_, total_edges_;\n\n typedef map<Edge*, timeval> RunningEdgeMap;\n RunningEdgeMap running_edges_;\n\n BuildConfig::Verbosity verbosity_;\n};\n\nBuildStatus::BuildStatus()\n : last_update_(time(NULL)), finished_edges_(0), total_edges_(0),\n verbosity_(BuildConfig::NORMAL) {}\n\nvoid BuildStatus::PlanHasTotalEdges(int total) {\n total_edges_ = total;\n}\n\nvoid BuildStatus::BuildEdgeStarted(Edge* edge) {\n timeval now;\n gettimeofday(&now, NULL);\n running_edges_.insert(make_pair(edge, now));\n\n if (edge->rule_ == &State::kPhonyRule)\n return;\n\n string desc = edge->GetDescription();\n if (verbosity_ != BuildConfig::QUIET) {\n if (verbosity_ != BuildConfig::VERBOSE && !desc.empty())\n printf(\"%s\\n\", desc.c_str());\n else\n printf(\"%s\\n\", edge->EvaluateCommand().c_str());\n }\n}\n\nvoid BuildStatus::BuildEdgeFinished(Edge* edge) {\n timeval now;\n gettimeofday(&now, NULL);\n ++finished_edges_;\n\n if (now.tv_sec - last_update_ > 5) {\n printf(\"%.1f%% %d\/%d\\n\", finished_edges_ * 100 \/ (float)total_edges_,\n finished_edges_, total_edges_);\n last_update_ = now.tv_sec;\n }\n\n RunningEdgeMap::iterator i = running_edges_.find(edge);\n timeval delta;\n timersub(&now, &i->second, &delta);\n printf(\"%dms\\n\", (int)((delta.tv_sec * 1000) + (delta.tv_usec \/ 1000)));\n running_edges_.erase(i);\n}\n\nbool Plan::AddTarget(Node* node, string* err) {\n vector<Node*> stack;\n return AddSubTarget(node, &stack, err);\n}\n\nbool Plan::AddSubTarget(Node* node, vector<Node*>* stack, string* err) {\n Edge* edge = node->in_edge_;\n if (!edge) { \/\/ Leaf node.\n if (node->dirty_) {\n string referenced;\n if (!stack->empty())\n referenced = \", needed by '\" + stack->back()->file_->path_ + \"',\";\n *err = \"'\" + node->file_->path_ + \"'\" + referenced + \" missing \"\n \"and no known rule to make it\";\n }\n return false;\n }\n assert(edge);\n\n if (CheckDependencyCycle(node, stack, err))\n return false;\n\n if (!node->dirty())\n return false; \/\/ Don't need to do anything.\n if (want_.find(edge) != want_.end())\n return true; \/\/ We've already enqueued it.\n want_.insert(edge);\n\n stack->push_back(node);\n bool awaiting_inputs = false;\n for (vector<Node*>::iterator i = edge->inputs_.begin();\n i != edge->inputs_.end(); ++i) {\n if (!edge->is_implicit(i - edge->inputs_.begin()) &&\n AddSubTarget(*i, stack, err)) {\n awaiting_inputs = true;\n } else if (!err->empty()) {\n return false;\n }\n }\n assert(stack->back() == node);\n stack->pop_back();\n\n if (!awaiting_inputs)\n ready_.insert(edge);\n\n return true;\n}\n\nbool Plan::CheckDependencyCycle(Node* node, vector<Node*>* stack, string* err) {\n vector<Node*>::reverse_iterator ri =\n find(stack->rbegin(), stack->rend(), node);\n if (ri == stack->rend())\n return false;\n\n \/\/ Add this node onto the stack to make it clearer where the loop\n \/\/ is.\n stack->push_back(node);\n\n vector<Node*>::iterator start = find(stack->begin(), stack->end(), node);\n *err = \"dependency cycle: \";\n for (vector<Node*>::iterator i = start; i != stack->end(); ++i) {\n if (i != start)\n err->append(\" -> \");\n err->append((*i)->file_->path_);\n }\n return true;\n}\n\nEdge* Plan::FindWork() {\n if (ready_.empty())\n return NULL;\n set<Edge*>::iterator i = ready_.begin();\n Edge* edge = *i;\n ready_.erase(i);\n return edge;\n}\n\nvoid Plan::EdgeFinished(Edge* edge) {\n want_.erase(edge);\n\n \/\/ Check off any nodes we were waiting for with this edge.\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n NodeFinished(*i);\n }\n}\n\nvoid Plan::NodeFinished(Node* node) {\n \/\/ See if we we want any edges from this node.\n for (vector<Edge*>::iterator i = node->out_edges_.begin();\n i != node->out_edges_.end(); ++i) {\n if (want_.find(*i) != want_.end()) {\n \/\/ See if the edge is now ready.\n bool ready = true;\n for (vector<Node*>::iterator j = (*i)->inputs_.begin();\n j != (*i)->inputs_.end(); ++j) {\n if ((*j)->dirty()) {\n ready = false;\n break;\n }\n }\n if (ready)\n ready_.insert(*i);\n }\n }\n}\n\nvoid Plan::Dump() {\n printf(\"pending: %d\\n\", (int)want_.size());\n for (set<Edge*>::iterator i = want_.begin(); i != want_.end(); ++i) {\n (*i)->Dump();\n }\n printf(\"ready: %d\\n\", (int)ready_.size());\n}\n\nstruct RealCommandRunner : public CommandRunner {\n virtual ~RealCommandRunner() {}\n virtual bool CanRunMore();\n virtual bool StartCommand(Edge* edge);\n virtual bool WaitForCommands();\n virtual Edge* NextFinishedCommand(bool* success);\n\n SubprocessSet subprocs_;\n map<Subprocess*, Edge*> subproc_to_edge_;\n};\n\nbool RealCommandRunner::CanRunMore() {\n const size_t kConcurrency = 8; \/\/ XXX make configurable etc.\n return subprocs_.running_.size() < kConcurrency;\n}\n\nbool RealCommandRunner::StartCommand(Edge* edge) {\n string command = edge->EvaluateCommand();\n Subprocess* subproc = new Subprocess;\n subproc_to_edge_.insert(make_pair(subproc, edge));\n if (!subproc->Start(command))\n return false;\n\n subprocs_.Add(subproc);\n return true;\n}\n\nbool RealCommandRunner::WaitForCommands() {\n if (subprocs_.running_.empty())\n return false;\n\n while (subprocs_.finished_.empty()) {\n subprocs_.DoWork();\n }\n return true;\n}\n\nEdge* RealCommandRunner::NextFinishedCommand(bool* success) {\n Subprocess* subproc = subprocs_.NextFinished();\n if (!subproc)\n return NULL;\n\n *success = subproc->Finish();\n\n map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);\n Edge* edge = i->second;\n subproc_to_edge_.erase(i);\n\n if (!*success)\n printf(\"FAILED: %s\\n\", edge->EvaluateCommand().c_str());\n if (!subproc->stdout_.buf_.empty())\n printf(\"%s\\n\", subproc->stdout_.buf_.c_str());\n if (!subproc->stderr_.buf_.empty())\n printf(\"%s\\n\", subproc->stderr_.buf_.c_str());\n\n delete subproc;\n return edge;\n}\n\nstruct DryRunCommandRunner : public CommandRunner {\n virtual ~DryRunCommandRunner() {}\n virtual bool CanRunMore() {\n return true;\n }\n virtual bool StartCommand(Edge* edge) {\n finished_.push(edge);\n return true;\n }\n virtual bool WaitForCommands() {\n return true;\n }\n virtual Edge* NextFinishedCommand(bool* success) {\n if (finished_.empty())\n return NULL;\n *success = true;\n Edge* edge = finished_.front();\n finished_.pop();\n return edge;\n }\n\n queue<Edge*> finished_;\n};\n\nBuilder::Builder(State* state, const BuildConfig& config)\n : state_(state) {\n disk_interface_ = new RealDiskInterface;\n if (config.dry_run)\n command_runner_ = new DryRunCommandRunner;\n else\n command_runner_ = new RealCommandRunner;\n status_ = new BuildStatus;\n status_->verbosity_ = config.verbosity;\n log_ = state->build_log_;\n}\n\nNode* Builder::AddTarget(const string& name, string* err) {\n Node* node = state_->LookupNode(name);\n if (!node) {\n *err = \"unknown target: '\" + name + \"'\";\n return NULL;\n }\n node->file_->StatIfNecessary(disk_interface_);\n if (node->in_edge_) {\n if (!node->in_edge_->RecomputeDirty(state_, disk_interface_, err))\n return NULL;\n }\n if (!node->dirty_)\n return NULL; \/\/ Intentionally no error.\n\n if (!plan_.AddTarget(node, err))\n return NULL;\n return node;\n}\n\nbool Builder::Build(string* err) {\n if (!plan_.more_to_do()) {\n *err = \"no work to do\";\n return true;\n }\n\n status_->PlanHasTotalEdges(plan_.edge_count());\n while (plan_.more_to_do()) {\n while (command_runner_->CanRunMore()) {\n Edge* edge = plan_.FindWork();\n if (!edge)\n break;\n\n if (!StartEdge(edge, err))\n return false;\n\n if (edge->rule_ == &State::kPhonyRule)\n FinishEdge(edge);\n }\n\n bool success;\n if (Edge* edge = command_runner_->NextFinishedCommand(&success)) {\n if (!success) {\n *err = \"subcommand failed\";\n return false;\n }\n FinishEdge(edge);\n } else {\n if (!command_runner_->WaitForCommands()) {\n *err = \"stuck [this is a bug]\";\n return false;\n }\n }\n }\n\n return true;\n}\n\nbool Builder::StartEdge(Edge* edge, string* err) {\n status_->BuildEdgeStarted(edge);\n\n if (edge->rule_ == &State::kPhonyRule)\n return true;\n\n \/\/ Create directories necessary for outputs.\n \/\/ XXX: this will block; do we care?\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n if (!disk_interface_->MakeDirs((*i)->file_->path_))\n return false;\n }\n\n \/\/ Compute command and start it.\n string command = edge->EvaluateCommand();\n if (!command_runner_->StartCommand(edge)) {\n err->assign(\"command '\" + command + \"' failed.\");\n return false;\n }\n\n return true;\n}\n\nvoid Builder::FinishEdge(Edge* edge) {\n for (vector<Node*>::iterator i = edge->outputs_.begin();\n i != edge->outputs_.end(); ++i) {\n \/\/ XXX check that the output actually changed\n \/\/ XXX just notify node and have it propagate?\n (*i)->dirty_ = false;\n }\n plan_.EdgeFinished(edge);\n status_->BuildEdgeFinished(edge);\n log_->RecordCommand(edge, 0); \/\/ XXX get edge timing.\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file DccDebugFlow.hxx\n *\n * Component useful for debugging DCC packet reception\/decoding code.\n *\n * @author Balazs Racz\n * @date 13 Dec 2015\n *\/\n\n#ifndef _NMRANET_DCCDEBUGFLOW_HXX_\n#define _NMRANET_DCCDEBUGFLOW_HXX_\n\nnamespace nmranet {\n\nclass DccPacketDebugFlow : public StateFlow<Buffer<dcc::Packet>, QList<1>> {\n public:\n DccPacketDebugFlow(nmranet::Node* node)\n : StateFlow<Buffer<dcc::Packet>, QList<1>>(\n node->iface()->dispatcher()->service()),\n node_(node) {}\n\n private:\n Action entry() override {\n Debug::DccPacketDelay::set(false);\n return allocate_and_call(node_->iface()->global_message_write_flow(),\n STATE(msg_allocated));\n }\n\n Action msg_allocated() {\n auto* b =\n get_allocation_result(node_->iface()->global_message_write_flow());\n\n b->data()->reset(\n static_cast<nmranet::Defs::MTI>(nmranet::Defs::MTI_XPRESSNET + 1),\n node_->node_id(),\n string((char*)message()->data()->payload, message()->data()->dlc));\n node_->iface()->global_message_write_flow()->send(b);\n return release_and_exit();\n }\n\n nmranet::Node* node_;\n}; \n\nclass DccDecodeFlow : public dcc::DccDecodeFlow {\n public:\n DccDecodeFlow() : dcc::DccDecodeFlow(&g_service, \"\/dev\/nrz0\") {}\n\n private:\n void dcc_packet_finished(const uint8_t* payload, size_t len) override {\n auto* b = g_packet_debug_flow.alloc();\n b->data()->dlc = len;\n memcpy(b->data()->payload, payload, len);\n g_packet_debug_flow.send(b);\n }\n\n void mm_packet_finished(const uint8_t* payload, size_t len) override {\n auto* b = g_packet_debug_flow.alloc();\n b->data()->dlc = len;\n memcpy(b->data()->payload, payload, len);\n b->data()->payload[0] |= 0xFC;\n g_packet_debug_flow.send(b);\n }\n\n void debug_data(uint32_t value) override {\n value \/= (configCPU_CLOCK_HZ \/ 1000000);\n log(decoder_.state());\n log(value);\n }\n\n void log(uint8_t value) {\n dbuffer[ptr] = value;\n ++ptr;\n if (ptr >= sizeof(dbuffer)) ptr = 0;\n }\n uint8_t dbuffer[1024];\n uint16_t ptr = 0;\n};\n\n\n} \/\/ namespace\n\n#endif \/\/ _NMRANET_DCCDEBUGFLOW_HXX_\n<commit_msg>make flow name more clear.<commit_after>\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file DccDebugFlow.hxx\n *\n * Component useful for debugging DCC packet reception\/decoding code.\n *\n * @author Balazs Racz\n * @date 13 Dec 2015\n *\/\n\n#ifndef _NMRANET_DCCDEBUGFLOW_HXX_\n#define _NMRANET_DCCDEBUGFLOW_HXX_\n\nnamespace nmranet {\n\nclass DccPacketDebugFlow : public StateFlow<Buffer<dcc::Packet>, QList<1>> {\n public:\n DccPacketDebugFlow(nmranet::Node* node)\n : StateFlow<Buffer<dcc::Packet>, QList<1>>(\n node->iface()->dispatcher()->service()),\n node_(node) {}\n\n private:\n Action entry() override {\n Debug::DccPacketDelay::set(false);\n return allocate_and_call(node_->iface()->global_message_write_flow(),\n STATE(msg_allocated));\n }\n\n Action msg_allocated() {\n auto* b =\n get_allocation_result(node_->iface()->global_message_write_flow());\n\n b->data()->reset(\n static_cast<nmranet::Defs::MTI>(nmranet::Defs::MTI_XPRESSNET + 1),\n node_->node_id(),\n string((char*)message()->data()->payload, message()->data()->dlc));\n node_->iface()->global_message_write_flow()->send(b);\n return release_and_exit();\n }\n\n nmranet::Node* node_;\n}; \n\nclass DccDebugDecodeFlow : public dcc::DccDecodeFlow {\n public:\n DccDebugDecodeFlow(Service* service, const char* path) : dcc::DccDecodeFlow(service, path) {}\n\n private:\n void dcc_packet_finished(const uint8_t* payload, size_t len) override {\n auto* b = g_packet_debug_flow.alloc();\n b->data()->dlc = len;\n memcpy(b->data()->payload, payload, len);\n g_packet_debug_flow.send(b);\n }\n\n void mm_packet_finished(const uint8_t* payload, size_t len) override {\n auto* b = g_packet_debug_flow.alloc();\n b->data()->dlc = len;\n memcpy(b->data()->payload, payload, len);\n b->data()->payload[0] |= 0xFC;\n g_packet_debug_flow.send(b);\n }\n\n void debug_data(uint32_t value) override {\n value \/= (configCPU_CLOCK_HZ \/ 1000000);\n log(decoder_.state());\n log(value);\n }\n\n void log(uint8_t value) {\n dbuffer[ptr] = value;\n ++ptr;\n if (ptr >= sizeof(dbuffer)) ptr = 0;\n }\n uint8_t dbuffer[1024];\n uint16_t ptr = 0;\n};\n\n\n} \/\/ namespace\n\n#endif \/\/ _NMRANET_DCCDEBUGFLOW_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/********************************************************************\n * Author: Carlos Moreno\n * Created: 2015-06-04\n * \n * Description:\n * \n * This is a sample code to connect to a server through TCP.\n * You are allowed to use this as a sample \/ starting point \n * for the assignment (both problems require a program that \n * connects to something)\n * \n * Copytight and permissions:\n * This file is for the exclusive purpose of our ECE-458 \n * assignment 2, and you are not allowed to use it for any \n * other purpose.\n * \n ********************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <cerrno>\n\n#include <inttypes.h>\n#include <math.h>\nusing namespace std;\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <wait.h>\n#include <unistd.h>\n\nstatic __inline__ uint64_t rdtsc();\nbool password_ok (const string &pwd);\n\nint main(int argc, char *argv[])\n{\n\tstring possiblePwd = \"\";\n\tif(argc == 2){\n\t\tpossiblePwd = argv[1];\n\t}\n\tsrand(time(NULL));\n\tbool finished = false;\n\tint letters = 0;\n\tif((finished = password_ok (possiblePwd)) == true) cout<<\"password correct: \" <<possiblePwd <<endl;\n\t\/\/static const char alphabet[] = \"ghijnoptuvwabcxyzdefqrsklm\";\n\tstatic const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n\twhile(!finished){\n\t\tuint64_t timevalues [26] = {};\n\t\tuint64_t squarevalues [26] = {};\n\t\tint times_picked [26] = {};\n\t\t\/\/destroy possible caching\n\t\tfor(int i = 0; i < 1000000; i++){\n\t\t\tint chosen_char = rand()%(sizeof(alphabet)-1);\n\t\t\tconst char ¤t = alphabet[chosen_char];\n\t\t\tconst string &pwd_attempt = possiblePwd + current;\n password_ok (pwd_attempt);\n \n\t\t}\n\t\tfor(int i = 0; i < 10000000; i++){\n int chosen_char = rand()%(sizeof(alphabet)-1);\n if(i%10 == 0 || i%10 == 9) continue;\n\t\t\tchar current = alphabet[chosen_char];\n\t\t\t\n\t\t\tconst string &pwd_attempt = possiblePwd + current;\n\t\t\tuint64_t start = rdtsc();\n\t\t\tfinished = password_ok (pwd_attempt);\n\t\t\tuint64_t end = rdtsc();\n\t\t\tif(finished){\n\t\t\t\tcout<<\"password guessed correct: \" <<pwd_attempt <<endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tuint64_t difference = end - start;\n\t\t\t\/\/cout<< alphabet[chosen_char]<< \": time of \" <<difference <<endl; \n\t\t\ttimevalues[chosen_char] += difference;\n\t\t\tsquarevalues[chosen_char] += (difference*difference);\n\t\t\ttimes_picked[chosen_char] = times_picked[chosen_char] + 1;\n\t\t\t\n\t\t}\n\t\t\/\/initialize to \"a\"\n\t\tdouble highest_mean = 0.0;\n\t\tdouble highest_var = 0.0;\n\t\tchar highest_char = 'a';\n\t\tdouble nexthighest_mean = 0.0;\n\t\tint highest_picktime = 0;\n\t\tfor(int i = 0; i < 26; i++){\n\t\t\tdouble current_mean = (double)timevalues[i] \/ times_picked[i];\n\t\t\tdouble current_var = ((double)1\/ (double)(times_picked[i] - 1)) * (double)(squarevalues[i] - times_picked[i] * (current_mean * current_mean));\n\t\t\tif(current_mean > nexthighest_mean && current_mean < highest_mean){\n\t\t\t\tnexthighest_mean = current_mean;\n\t\t\t}\n\t\t\tif(current_mean > highest_mean){\n\t\t\t\tnexthighest_mean = highest_mean;\n\t\t\t\thighest_mean = current_mean;\n\t\t\t\thighest_var = current_var;\n\t\t\t\thighest_picktime = times_picked[i];\n\t\t\t\thighest_char = alphabet[i];\n\t\t\t}\n\t\t\tcout<< alphabet[i] <<\" mean: \" <<current_mean << \" ms, \\tvariance: \" <<current_var << \" \\tpicked \" << times_picked[i] <<\" times\" <<endl;\n\t\t}\n\t\tdouble confidence95 = 1.96*sqrt(highest_var) \/ sqrt(highest_picktime);\n\t\tdouble confidence99 = 2.58*sqrt(highest_var) \/ sqrt(highest_picktime);\n\t\tcout<< \"\\nBEST GUESS: \" << possiblePwd+highest_char << \", with time: \" << highest_mean << \" variance: \" << highest_var <<endl;\n\t\tcout<<\"\\n95\\% confidence interval: \" <<highest_mean << \" +- \" <<confidence95 <<\"\\n99\\% confidence interval: \" <<highest_mean << \" +- \" <<confidence99<< endl; \n\t\tcout<<\"next longest time: \" << nexthighest_mean <<endl;\n\t\t\n\t\tif(highest_mean\/nexthighest_mean < 1.01 ||confidence99\/highest_mean > 0.02 || (highest_mean - confidence99) < nexthighest_mean){\n\t\t\tcout<< \"Not confident about attempted password, try a shorter guess?\" <<endl;\n\t\t}\n\t\treturn 0;\n\t\t\n\t}\n\t\n return 0;\n}\n\nstatic __inline__ uint64_t rdtsc()\n{\n\tuint32_t hi, lo;\n\t__asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n\treturn ((uint64_t)lo) | (((uint64_t)hi) << 32);\n}\n\nbool password_ok (const string &pwd)\n{\n\treturn pwd == \"mypassword\";\n \/\/return strcmp(pwd.c_str(), \"mypassword\") == 0;\n}\n\n<commit_msg>small change in part 2<commit_after>\/********************************************************************\n * Author: Carlos Moreno\n * Created: 2015-06-04\n * \n * Description:\n * \n * This is a sample code to connect to a server through TCP.\n * You are allowed to use this as a sample \/ starting point \n * for the assignment (both problems require a program that \n * connects to something)\n * \n * Copytight and permissions:\n * This file is for the exclusive purpose of our ECE-458 \n * assignment 2, and you are not allowed to use it for any \n * other purpose.\n * \n ********************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <cerrno>\n\n#include <inttypes.h>\n#include <math.h>\nusing namespace std;\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <wait.h>\n#include <unistd.h>\n\nstatic __inline__ uint64_t rdtsc();\nbool password_ok (const string &pwd);\n\nint main(int argc, char *argv[])\n{\n\tstring possiblePwd = \"\";\n\tif(argc == 2){\n\t\tpossiblePwd = argv[1];\n\t}\n\tsrand(time(NULL));\n\tbool finished = false;\n\tint letters = 0;\n\tif((finished = password_ok (possiblePwd)) == true) cout<<\"password correct: \" <<possiblePwd <<endl;\n\t\/\/static const char alphabet[] = \"ghijnoptuvwabcxyzdefqrsklm\";\n\tstatic const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n\twhile(!finished){\n\t\tuint64_t timevalues [26] = {};\n\t\tuint64_t squarevalues [26] = {};\n\t\tint times_picked [26] = {};\n\t\t\/\/destroy possible caching\n\t\tfor(int i = 0; i < 100000; i++){\n\t\t\tint chosen_char = rand()%(sizeof(alphabet)-1);\n\t\t\tconst char ¤t = alphabet[chosen_char];\n\t\t\tconst string &pwd_attempt = possiblePwd + current;\n password_ok (pwd_attempt);\n \n\t\t}\n\t\tsrand(time(NULL));\n\t\tfor(int i = 0; i < 10000000; i++){\n int chosen_char = rand()%(sizeof(alphabet)-1);\n\t\t\tchar current = alphabet[chosen_char];\n\t\t\t\n\t\t\tconst string &pwd_attempt = possiblePwd + current;\n\t\t\tuint64_t start = rdtsc();\n\t\t\tfinished = password_ok (pwd_attempt);\n\t\t\tuint64_t end = rdtsc();\n\t\t\tif(finished){\n\t\t\t\tcout<<\"password guessed correct: \" <<pwd_attempt <<endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tuint64_t difference = end - start;\n\t\t\t\/\/cout<< alphabet[chosen_char]<< \": time of \" <<difference <<endl; \n\t\t\ttimevalues[chosen_char] += difference;\n\t\t\tsquarevalues[chosen_char] += (difference*difference);\n\t\t\ttimes_picked[chosen_char] = times_picked[chosen_char] + 1;\n\t\t\t\n\t\t}\n\t\t\/\/initialize to \"a\"\n\t\tdouble highest_mean = 0.0;\n\t\tdouble highest_var = 0.0;\n\t\tchar highest_char = 'a';\n\t\tdouble nexthighest_mean = 0.0;\n\t\tint highest_picktime = 0;\n\t\tfor(int i = 0; i < 26; i++){\n\t\t\tdouble current_mean = (double)timevalues[i] \/ times_picked[i];\n\t\t\tdouble current_var = ((double)1\/ (double)(times_picked[i] - 1)) * (double)(squarevalues[i] - times_picked[i] * (current_mean * current_mean));\n\t\t\tif(current_mean > nexthighest_mean && current_mean < highest_mean){\n\t\t\t\tnexthighest_mean = current_mean;\n\t\t\t}\n\t\t\tif(current_mean > highest_mean){\n\t\t\t\tnexthighest_mean = highest_mean;\n\t\t\t\thighest_mean = current_mean;\n\t\t\t\thighest_var = current_var;\n\t\t\t\thighest_picktime = times_picked[i];\n\t\t\t\thighest_char = alphabet[i];\n\t\t\t}\n\t\t\tcout<< alphabet[i] <<\" mean: \" <<current_mean << \" ms, \\tvariance: \" <<current_var << \" \\tpicked \" << times_picked[i] <<\" times\" <<endl;\n\t\t}\n\t\tdouble confidence95 = 1.96*sqrt(highest_var) \/ sqrt(highest_picktime);\n\t\tdouble confidence99 = 2.58*sqrt(highest_var) \/ sqrt(highest_picktime);\n\t\tcout<< \"\\nBEST GUESS: \" << possiblePwd+highest_char << \", with time: \" << highest_mean << \" variance: \" << highest_var <<endl;\n\t\tcout<<\"\\n95\\% confidence interval: \" <<highest_mean << \" +- \" <<confidence95 <<\"\\n99\\% confidence interval: \" <<highest_mean << \" +- \" <<confidence99<< endl; \n\t\tcout<<\"next longest time: \" << nexthighest_mean <<endl;\n\t\t\n\t\tif(highest_mean\/nexthighest_mean < 1.01 ||confidence99\/highest_mean > 0.02 || (highest_mean - confidence99) < nexthighest_mean){\n\t\t\tcout<< \"Not confident about attempted password, try a shorter guess?\" <<endl;\n\t\t}\n\t\treturn 0;\n\t\t\n\t}\n\t\n return 0;\n}\n\nstatic __inline__ uint64_t rdtsc()\n{\n\tuint32_t hi, lo;\n\t__asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n\treturn ((uint64_t)lo) | (((uint64_t)hi) << 32);\n}\n\nbool password_ok (const string &pwd)\n{\n\treturn pwd == \"mypassword\";\n \/\/return strcmp(pwd.c_str(), \"mypassword\") == 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2018 by the individuals mentioned in the source code history\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"omxExpectation.h\"\n#include \"omxFitFunction.h\"\n#include \"omxDefines.h\"\n#include \"EnableWarnings.h\"\n\nstruct omxNormalExpectation : public omxExpectation {\n\n\tomxMatrix *cov, *means; \/\/ observed covariance and means\n\tomxMatrix *thresholds; \/\/ same as thresholdsMat? TODO\n\n\tdouble logDetObserved;\n\tdouble n;\n\n\tvirtual void init();\n\tvirtual void compute(FitContext *fc, const char *what, const char *how);\n\tvirtual void populateAttr(SEXP expectation);\n\tvirtual omxMatrix *getComponent(const char*);\n};\n\nvoid omxNormalExpectation::compute(FitContext *fc, const char *, const char *) {\n\tomxNormalExpectation* one = this;\n\n\tomxRecompute(one->cov, fc);\n\tif(one->means != NULL)\n\t omxRecompute(one->means, fc);\n\tif (one->thresholds) omxRecompute(one->thresholds, fc);\n}\n\nvoid omxNormalExpectation::populateAttr(SEXP algebra) {\n if(OMX_DEBUG) { mxLog(\"Populating Normal Attributes.\"); }\n\n\tomxRecompute(cov, NULL);\n\tif(means != NULL) omxRecompute(means, NULL);\n\n\t{\n\t\tSEXP expCovExt;\n\tScopedProtect p1(expCovExt, Rf_allocMatrix(REALSXP, cov->rows, cov->cols));\n\tfor(int row = 0; row < cov->rows; row++)\n\t\tfor(int col = 0; col < cov->cols; col++)\n\t\t\tREAL(expCovExt)[col * cov->rows + row] =\n\t\t\t\tomxMatrixElement(cov, row, col);\n\tRf_setAttrib(algebra, Rf_install(\"ExpCov\"), expCovExt);\n\t}\n\n\t\n\tif (means != NULL) {\n\t\tSEXP expMeanExt;\n\t\tScopedProtect p1(expMeanExt, Rf_allocMatrix(REALSXP, means->rows, means->cols));\n\t\tfor(int row = 0; row < means->rows; row++)\n\t\t\tfor(int col = 0; col < means->cols; col++)\n\t\t\t\tREAL(expMeanExt)[col * means->rows + row] =\n\t\t\t\t\tomxMatrixElement(means, row, col);\n\t\tRf_setAttrib(algebra, Rf_install(\"ExpMean\"), expMeanExt);\n\t} else {\n\t\tSEXP expMeanExt;\n\t\tScopedProtect p1(expMeanExt, Rf_allocMatrix(REALSXP, 0, 0));\n\t\tRf_setAttrib(algebra, Rf_install(\"ExpMean\"), expMeanExt);\n\t}\n\n\tProtectedSEXP RnumStats(Rf_ScalarReal(omxDataDF(data)));\n\tRf_setAttrib(algebra, Rf_install(\"numStats\"), RnumStats);\n}\n\nomxExpectation *omxInitNormalExpectation() { return new omxNormalExpectation; }\n\nvoid omxNormalExpectation::init()\n{\n if(OMX_DEBUG) { mxLog(\"Initializing Normal expectation.\"); }\n\n omxNormalExpectation *one = this;\n\t\n\t\/* Set up expectation structures *\/\n\tif(OMX_DEBUG) { mxLog(\"Processing cov.\"); }\n\tone->cov = omxNewMatrixFromSlot(rObj, currentState, \"covariance\");\n\n\tif(OMX_DEBUG) { mxLog(\"Processing Means.\"); }\n\tone->means = omxNewMatrixFromSlot(rObj, currentState, \"means\");\n\n\tone->thresholds = omxNewMatrixFromSlot(rObj, currentState, \"thresholds\");\n}\n\nomxMatrix* omxNormalExpectation::getComponent(const char* component){\n\/* Return appropriate parts of Expectation to the Fit Function *\/\n\tif(OMX_DEBUG) { mxLog(\"Normal expectation: %s requested--\", component); }\n\n\tomxNormalExpectation* one = this;\n\tomxMatrix* retval = NULL;\n\n\tif(strEQ(\"cov\", component)) {\n\t\tretval = one->cov;\n\t} else if(strEQ(\"means\", component)) {\n\t\tretval = one->means;\n\t} else if(strEQ(\"pvec\", component)) {\n\t\t\/\/ Once implemented, change compute function and return pvec\n\t}\n\tif (retval) omxRecompute(retval, NULL);\n\t\n\treturn retval;\n}\n<commit_msg>Remove redundent copy of thresholds<commit_after>\/*\n * Copyright 2007-2018 by the individuals mentioned in the source code history\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"omxExpectation.h\"\n#include \"omxFitFunction.h\"\n#include \"omxDefines.h\"\n#include \"EnableWarnings.h\"\n\nstruct omxNormalExpectation : public omxExpectation {\n\n\tomxMatrix *cov, *means; \/\/ observed covariance and means\n\n\tdouble logDetObserved;\n\tdouble n;\n\n\tvirtual void init();\n\tvirtual void compute(FitContext *fc, const char *what, const char *how);\n\tvirtual void populateAttr(SEXP expectation);\n\tvirtual omxMatrix *getComponent(const char*);\n};\n\nvoid omxNormalExpectation::compute(FitContext *fc, const char *, const char *) {\n\tomxNormalExpectation* one = this;\n\n\tomxRecompute(one->cov, fc);\n\tif(one->means != NULL)\n\t omxRecompute(one->means, fc);\n\tif (one->thresholdsMat) omxRecompute(one->thresholdsMat, fc);\n}\n\nvoid omxNormalExpectation::populateAttr(SEXP algebra) {\n if(OMX_DEBUG) { mxLog(\"Populating Normal Attributes.\"); }\n\n\tomxRecompute(cov, NULL);\n\tif(means != NULL) omxRecompute(means, NULL);\n\n\t{\n\t\tSEXP expCovExt;\n\tScopedProtect p1(expCovExt, Rf_allocMatrix(REALSXP, cov->rows, cov->cols));\n\tfor(int row = 0; row < cov->rows; row++)\n\t\tfor(int col = 0; col < cov->cols; col++)\n\t\t\tREAL(expCovExt)[col * cov->rows + row] =\n\t\t\t\tomxMatrixElement(cov, row, col);\n\tRf_setAttrib(algebra, Rf_install(\"ExpCov\"), expCovExt);\n\t}\n\n\t\n\tif (means != NULL) {\n\t\tSEXP expMeanExt;\n\t\tScopedProtect p1(expMeanExt, Rf_allocMatrix(REALSXP, means->rows, means->cols));\n\t\tfor(int row = 0; row < means->rows; row++)\n\t\t\tfor(int col = 0; col < means->cols; col++)\n\t\t\t\tREAL(expMeanExt)[col * means->rows + row] =\n\t\t\t\t\tomxMatrixElement(means, row, col);\n\t\tRf_setAttrib(algebra, Rf_install(\"ExpMean\"), expMeanExt);\n\t} else {\n\t\tSEXP expMeanExt;\n\t\tScopedProtect p1(expMeanExt, Rf_allocMatrix(REALSXP, 0, 0));\n\t\tRf_setAttrib(algebra, Rf_install(\"ExpMean\"), expMeanExt);\n\t}\n\n\tProtectedSEXP RnumStats(Rf_ScalarReal(omxDataDF(data)));\n\tRf_setAttrib(algebra, Rf_install(\"numStats\"), RnumStats);\n}\n\nomxExpectation *omxInitNormalExpectation() { return new omxNormalExpectation; }\n\nvoid omxNormalExpectation::init()\n{\n if(OMX_DEBUG) { mxLog(\"Initializing Normal expectation.\"); }\n\n omxNormalExpectation *one = this;\n\t\n\t\/* Set up expectation structures *\/\n\tif(OMX_DEBUG) { mxLog(\"Processing cov.\"); }\n\tone->cov = omxNewMatrixFromSlot(rObj, currentState, \"covariance\");\n\n\tif(OMX_DEBUG) { mxLog(\"Processing Means.\"); }\n\tone->means = omxNewMatrixFromSlot(rObj, currentState, \"means\");\n}\n\nomxMatrix* omxNormalExpectation::getComponent(const char* component){\n\/* Return appropriate parts of Expectation to the Fit Function *\/\n\tif(OMX_DEBUG) { mxLog(\"Normal expectation: %s requested--\", component); }\n\n\tomxNormalExpectation* one = this;\n\tomxMatrix* retval = NULL;\n\n\tif(strEQ(\"cov\", component)) {\n\t\tretval = one->cov;\n\t} else if(strEQ(\"means\", component)) {\n\t\tretval = one->means;\n\t} else if(strEQ(\"pvec\", component)) {\n\t\t\/\/ Once implemented, change compute function and return pvec\n\t}\n\tif (retval) omxRecompute(retval, NULL);\n\t\n\treturn retval;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"LagInfo.h\"\n\nfloat LagInfo::threshold = 0.0;\nfloat LagInfo::max = 0.0;\n\nLagInfo::LagInfo(PlayerInfo *_info)\n : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),\n jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),\n pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {\n}\n\nvoid LagInfo::reset()\n{\n nextping = info->now;\n nextping += 10.0;\n lastupdate = info->now;\n}\n\nint LagInfo::getLag()\n{\n return int(lagavg * 1000);\n}\n\nvoid LagInfo::getLagStats(char* msg) {\n msg[0] = 0;\n if (!info->isPlaying() || !info->isHuman())\n return;\n\n \/\/ don't wait for ping to come back\n int lag\t = int(lagavg * 1000);\n if (pingpending) {\n float timepassed = info->now - lastping;\n int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed)\n\t\t\t * 1000);\n if (lastLag > lag)\n lag = lastLag;\n }\n sprintf(msg,\"%-16s :\\t %3d +- %2dms\", info->getCallSign(),\n\t lag,\n\t int(jitteravg * 1000));\n if (lostavg >= 0.01f)\n sprintf(msg + strlen(msg), \" %d%% lost\/ooo\", int(lostavg * 100));\n}\n\n\/\/ update absolute latency based on LagPing messages\nint LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {\n uint16_t _pingseqno;\n int lag = 0;\n nboUnpackUShort(buf, _pingseqno);\n if (pingseqno == _pingseqno) {\n float timepassed = info->now - lastping;\n \/\/ time is smoothed exponentially using a dynamic smoothing factor\n lagavg = lagavg * (1 - lagalpha) + lagalpha * timepassed;\n lagalpha = lagalpha \/ (0.9f + lagalpha);\n lag = int(lagavg * 1000);\n lagcount++;\n\n \/\/ warn players from time to time whose lag is > threshold (-lagwarn)\n if (!info->isObserver() && (threshold > 0) && lagavg > threshold\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n laglastwarn = lagcount;\n lagwarncount++;\n warn = true;\n kick = (lagwarncount++ > max);\n } else {\n warn = false;\n kick = false;\n }\n lostavg = lostavg * (1 - lostalpha);\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n pingpending = false;\n } else {\n warn = false;\n kick = false;\n }\n return lag;\n}\n\nvoid LagInfo::updateLag(float timestamp, bool ooo) {\n if (!info->isPlaying())\n return;\n if (ooo) {\n lostavg = lostavg * (1 - lostalpha) + lostalpha;\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n }\n \/\/ don't calc jitter if more than 2 seconds between packets\n if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {\n const float jitter = fabs(info->now - lastupdate\n\t\t\t - (timestamp - lasttimestamp));\n \/\/ time is smoothed exponentially using a dynamic smoothing factor\n jitteravg = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);\n jitteralpha = jitteralpha \/ (0.99f + jitteralpha);\n lostavg = lostavg * (1 - lostalpha);\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n }\n lasttimestamp = timestamp;\n lastupdate = info->now;\n}\n\nint LagInfo::getNextPingSeqno(bool &warn, bool &kick) {\n\n warn = false;\n kick = false;\n\n if (!info->isPlaying() || !info->isHuman())\n return -1;\n\n if (nextping - info->now >= 0)\n \/\/ no time for pinging\n return -1;\n\n pingseqno = (pingseqno + 1) % 10000;\n if (pingpending) {\n \/\/ ping lost\n lostavg = lostavg * (1 - lostalpha) + lostalpha;\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n if (!info->isObserver() && (threshold > 0)\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n laglastwarn = lagcount;\n lagwarncount++;\n warn = true;\n kick = (lagwarncount++ > max);\n }\n }\n\n pingpending = true;\n lastping = info->now;\n nextping = info->now;\n nextping += 10.0f;\n pingssent++;\n return pingseqno;\n}\n\n\/\/ update absolute latency based on LagPing messages\nvoid LagInfo::updateLatency(float &waitTime) {\n if (!info->isPlaying() || !info->isHuman())\n return;\n float delta = nextping - info->now;\n if (delta < waitTime)\n waitTime = delta;\n}\n\nvoid LagInfo::setThreshold(float _threshold, float _max) {\n threshold = _threshold;\n max = _max;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>hopefully get lagstats display lined up properly horizontally<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"LagInfo.h\"\n\nfloat LagInfo::threshold = 0.0;\nfloat LagInfo::max = 0.0;\n\nLagInfo::LagInfo(PlayerInfo *_info)\n : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),\n jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),\n pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {\n}\n\nvoid LagInfo::reset()\n{\n nextping = info->now;\n nextping += 10.0;\n lastupdate = info->now;\n}\n\nint LagInfo::getLag()\n{\n return int(lagavg * 1000);\n}\n\nvoid LagInfo::getLagStats(char* msg) {\n msg[0] = 0;\n if (!info->isPlaying() || !info->isHuman())\n return;\n\n \/\/ don't wait for ping to come back\n int lag = int(lagavg * 1000);\n if (pingpending) {\n float timepassed = info->now - lastping;\n int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);\n if (lastLag > lag)\n lag = lastLag;\n }\n sprintf(msg,\"%s \\t: %3d +- %2dms\", info->getCallSign(),\n\t lag, int(jitteravg * 1000));\n if (lostavg >= 0.01f)\n sprintf(msg + strlen(msg), \" %d%% lost\/ooo\", int(lostavg * 100));\n}\n\n\/\/ update absolute latency based on LagPing messages\nint LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {\n uint16_t _pingseqno;\n int lag = 0;\n nboUnpackUShort(buf, _pingseqno);\n if (pingseqno == _pingseqno) {\n float timepassed = info->now - lastping;\n \/\/ time is smoothed exponentially using a dynamic smoothing factor\n lagavg = lagavg * (1 - lagalpha) + lagalpha * timepassed;\n lagalpha = lagalpha \/ (0.9f + lagalpha);\n lag = int(lagavg * 1000);\n lagcount++;\n\n \/\/ warn players from time to time whose lag is > threshold (-lagwarn)\n if (!info->isObserver() && (threshold > 0) && lagavg > threshold\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n laglastwarn = lagcount;\n lagwarncount++;\n warn = true;\n kick = (lagwarncount++ > max);\n } else {\n warn = false;\n kick = false;\n }\n lostavg = lostavg * (1 - lostalpha);\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n pingpending = false;\n } else {\n warn = false;\n kick = false;\n }\n return lag;\n}\n\nvoid LagInfo::updateLag(float timestamp, bool ooo) {\n if (!info->isPlaying())\n return;\n if (ooo) {\n lostavg = lostavg * (1 - lostalpha) + lostalpha;\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n }\n \/\/ don't calc jitter if more than 2 seconds between packets\n if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {\n const float jitter = fabs(info->now - lastupdate\n\t\t\t - (timestamp - lasttimestamp));\n \/\/ time is smoothed exponentially using a dynamic smoothing factor\n jitteravg = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);\n jitteralpha = jitteralpha \/ (0.99f + jitteralpha);\n lostavg = lostavg * (1 - lostalpha);\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n }\n lasttimestamp = timestamp;\n lastupdate = info->now;\n}\n\nint LagInfo::getNextPingSeqno(bool &warn, bool &kick) {\n\n warn = false;\n kick = false;\n\n if (!info->isPlaying() || !info->isHuman())\n return -1;\n\n if (nextping - info->now >= 0)\n \/\/ no time for pinging\n return -1;\n\n pingseqno = (pingseqno + 1) % 10000;\n if (pingpending) {\n \/\/ ping lost\n lostavg = lostavg * (1 - lostalpha) + lostalpha;\n lostalpha = lostalpha \/ (0.99f + lostalpha);\n if (!info->isObserver() && (threshold > 0)\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n laglastwarn = lagcount;\n lagwarncount++;\n warn = true;\n kick = (lagwarncount++ > max);\n }\n }\n\n pingpending = true;\n lastping = info->now;\n nextping = info->now;\n nextping += 10.0f;\n pingssent++;\n return pingseqno;\n}\n\n\/\/ update absolute latency based on LagPing messages\nvoid LagInfo::updateLatency(float &waitTime) {\n if (!info->isPlaying() || !info->isHuman())\n return;\n float delta = nextping - info->now;\n if (delta < waitTime)\n waitTime = delta;\n}\n\nvoid LagInfo::setThreshold(float _threshold, float _max) {\n threshold = _threshold;\n max = _max;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include <osgGA\/UFOManipulator>\n#include <osgUtil\/IntersectVisitor>\n\nusing namespace osgGA;\n\nUFOManipulator::UFOManipulator():\n _t0(0.0),\n _shift(false),\n _ctrl(false)\n{ \n _minHeightAboveGround = 2.0;\n _minDistanceInFront = 5.0;\n\n _speedAccelerationFactor = 0.4;\n _speedDecelerationFactor = 0.90;\n\n _directionRotationRate = 0.0;\n _directionRotationAcceleration = M_PI*0.00005;\n _directionRotationDeceleration = 0.90;\n\n _speedEpsilon = 0.02;\n _directionRotationEpsilon = 0.0001;\n\n _viewOffsetDelta = M_PI * 0.0025;\n _pitchOffsetRate = 0.0;\n _pitchOffset = 0.0;\n\n _yawOffsetRate = 0.0;\n _yawOffset = 0.0;\n _offset.makeIdentity();\n\n _decelerateOffsetRate = true;\n _straightenOffset = false;\n\n _direction.set( 0,1,0);\n _stop();\n}\n\nvoid UFOManipulator::setNode( osg::Node *node )\n{\n _node = node;\n\n if (getAutoComputeHomePosition()) \n computeHomePosition();\n\n _home();\n}\n\nconst osg::Node* UFOManipulator::getNode() const\n{\n return _node.get();\n}\n\nosg::Node* UFOManipulator::getNode()\n{\n return _node.get();\n}\n\n\nconst char* UFOManipulator::className() const \n{ \n return \"UFOManipulator\"; \n}\n\nvoid UFOManipulator::setByMatrix( const osg::Matrix &mat ) \n{\n _inverseMatrix = mat;\n _matrix.invert( _inverseMatrix );\n}\n\nvoid UFOManipulator::setByInverseMatrix( const osg::Matrix &invmat) \n{\n _matrix = invmat;\n _inverseMatrix.invert( _matrix );\n}\n\nosg::Matrix UFOManipulator::getMatrix() const\n{\n return (_offset * _matrix);\n}\n\nosg::Matrix UFOManipulator::getInverseMatrix() const \n{\n return (_inverseMatrix * _offset);\n}\n\nvoid UFOManipulator::computeHomePosition()\n{\n if( !_node.valid() )\n return;\n\n osg::BoundingSphere bs = _node->getBound();\n\n \/*\n * Find the ground - Assumption: The ground is the hit of an intersection\n * from a line segment extending from above to below the database at its \n * horizontal center, that intersects the database closest to zero. *\/\n osgUtil::IntersectVisitor iv;\n osg::ref_ptr<osg::LineSegment> seg = new osg::LineSegment;\n osg::Vec3 A = bs.center() + (osg::Vec3(0,0,1)*(bs.radius()*2));\n osg::Vec3 B = bs.center() + (osg::Vec3(0,0,-1)*(bs.radius()*2));\n\n if( (B-A).length() == 0.0)\n {\n puts( \"DOH\" ); fflush(stdout);\n return;\n }\n\n \/*\n seg->set( bs.center() + (osg::Vec3(0,0,1)*(bs.radius()*2)), \n bs.center() + (osg::Vec3(0,0,-1)*(bs.radius()*2)) );\n *\/\n seg->set( A, B );\n\n iv.addLineSegment( seg.get() );\n _node->accept(iv);\n\n \/\/ start with it high\n double ground = bs.radius() * 3;\n\n if (iv.hits())\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(seg.get());\n for(osgUtil::IntersectVisitor::HitList::iterator hitr=hitList.begin();\n hitr!=hitList.end(); ++hitr)\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n if( fabs(ip[3]) < ground )\n ground = ip[3];\n }\n }\n else\n {\n osg::notify(osg::WARN)<<\"UFOManipulator : I can't find the ground!\"<<std::endl;\n ground = 0.0;\n }\n\n\n osg::Vec3 p(bs.center()[0], bs.center()[1], ground + (_minHeightAboveGround*1.25) );\n setHomePosition( p, p + osg::Vec3(0,1,0), osg::Vec3(0,0,1) );\n}\n\nvoid UFOManipulator::home(const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&) \n{\n _home();\n}\n\nvoid UFOManipulator::_home() \n{\n if (getAutoComputeHomePosition()) \n computeHomePosition();\n\n _position = _homeEye;\n _direction = _homeCenter - _homeEye;\n _direction.normalize();\n _directionRotationRate = 0.0;\n\n _inverseMatrix.makeLookAt( _homeEye, _homeCenter, _homeUp );\n _matrix.invert( _matrix );\n\n _offset.makeIdentity();\n\n _forwardSpeed = 0.0;\n _sideSpeed = 0.0;\n _upSpeed = 0.0;\n}\n\nbool UFOManipulator::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter &aa)\n{\n\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYUP):\n _keyUp( ea, aa );\n return false;\n break;\n\n case(osgGA::GUIEventAdapter::KEYDOWN):\n _keyDown(ea, aa);\n return false;\n break;\n\n case(osgGA::GUIEventAdapter::FRAME):\n _frame(ea,aa);\n return false;\n break;\n\n default:\n return false;\n }\n\n return false;\n}\n\nvoid UFOManipulator::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <SpaceBar>\", \"Reset the viewing angle to 0.0\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <UpArrow>\", \"Acceleration forward.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <DownArrow>\", \"Acceleration backward (or deceleration forward\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <LeftArrow>\", \"Rotate view and direction of travel to the left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <RightArrow>\", \"Rotate view and direction of travel to the right.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <SpaceBar>\", \"Brake. Gradually decelerates linear and rotational movement.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/UpArrow>\", \"Accelerate up.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/DownArrow>\", \"Accelerate down.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/LeftArrow>\", \"Accelerate (linearly) left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/RightArrow>\",\"Accelerate (linearly) right.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/SpaceBar>\", \"Instant brake. Immediately stop all linear and rotational movement.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/UpArrow>\", \"Rotate view (but not direction of travel) up.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/DownArrow>\", \"Rotate view (but not direction of travel) down.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/LeftArrow>\", \"Rotate view (but not direction of travel) left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/RightArrow>\", \"Rotate view (but not direction of travel) right.\");\n}\n\n\n\nvoid UFOManipulator::_keyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter & )\n{\n switch( ea.getKey() )\n {\n case Producer::KeyChar_Control_L:\n case Producer::KeyChar_Control_R:\n _ctrl = false;\n _decelerateOffsetRate = true;\n _straightenOffset = false;\n break;\n\n case Producer::KeyChar_Shift_L:\n case Producer::KeyChar_Shift_R:\n _shift = false;\n _decelerateUpSideRate = true;\n break;\n }\n}\n\nvoid UFOManipulator::_keyDown( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter & )\n{\n switch( ea.getKey() )\n {\n case Producer::KeyChar_Control_L:\n case Producer::KeyChar_Control_R:\n _ctrl = true;\n break;\n\n case Producer::KeyChar_Shift_L :\n case Producer::KeyChar_Shift_R :\n _shift = true;\n break;\n\n case Producer::KeyChar_Up:\n if( _ctrl )\n {\n _pitchOffsetRate -= _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if( _shift )\n {\n _upSpeed += _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _forwardSpeed += _speedAccelerationFactor;\n }\n break;\n\n case Producer::KeyChar_Down:\n if( _ctrl )\n {\n _pitchOffsetRate += _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if( _shift )\n {\n _upSpeed -= _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _forwardSpeed -= _speedAccelerationFactor;\n }\n break;\n\n case Producer::KeyChar_Right:\n if( _ctrl )\n {\n _yawOffsetRate += _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if(_shift)\n {\n _sideSpeed += _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _directionRotationRate -= _directionRotationAcceleration;\n }\n break;\n\n case Producer::KeyChar_Left:\n if( _ctrl )\n {\n _yawOffsetRate -= _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if(_shift)\n {\n _sideSpeed -= _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _directionRotationRate += _directionRotationAcceleration;\n }\n break;\n\n case Producer::KeyChar_Return:\n if( _ctrl )\n {\n _straightenOffset = true;\n }\n break;\n\n case ' ':\n if( _shift )\n {\n _stop();\n }\n else\n {\n if( fabs(_forwardSpeed) > 0.0 )\n {\n _forwardSpeed *= _speedDecelerationFactor;\n\n if( fabs(_forwardSpeed ) < _speedEpsilon )\n _forwardSpeed = 0.0;\n }\n if( fabs(_sideSpeed) > 0.0 )\n {\n _sideSpeed *= _speedDecelerationFactor;\n\n if( fabs( _sideSpeed ) < _speedEpsilon )\n _sideSpeed = 0.0;\n }\n\n if( fabs(_upSpeed) > 0.0 )\n {\n _upSpeed *= _speedDecelerationFactor;\n\n if( fabs( _upSpeed ) < _speedEpsilon )\n _sideSpeed = 0.0;\n }\n\n\n if( fabs(_directionRotationRate ) > 0.0 )\n {\n _directionRotationRate *= _directionRotationDeceleration;\n if( fabs( _directionRotationRate ) < _directionRotationEpsilon )\n _directionRotationRate = 0.0;\n }\n \n }\n break;\n\n case 'H':\n _home();\n break;\n }\n}\n\nvoid UFOManipulator::_frame( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter & )\n{\n double t1 = ea.time();\n if( _t0 == 0.0 )\n {\n _t0 = ea.time();\n _dt = 0.0;\n }\n else\n {\n _dt = t1 - _t0;\n _t0 = t1;\n }\n\n if( fabs( _directionRotationRate ) > _directionRotationEpsilon )\n {\n _direction = _direction * osg::Matrix::rotate( _directionRotationRate, osg::Vec3(0,0,1));\n }\n\n {\n osg::Vec3 _sideVec = _direction * osg::Matrix::rotate( -M_PI*0.5, osg::Vec3(0,0,1));\n\n _position += ((_direction * _forwardSpeed) + \n (_sideVec * _sideSpeed) +\n (osg::Vec3(0,0,1) * _upSpeed))\n * _dt;\n }\n\n _pitchOffset += _pitchOffsetRate * _dt;\n if( _pitchOffset >= M_PI || _pitchOffset < -M_PI )\n _pitchOffset *= -1;\n\n _yawOffset += _yawOffsetRate * _dt;\n if( _yawOffset >= M_PI || _yawOffset < -M_PI ) \n _yawOffset *= -1;\n\n _offset = osg::Matrix::rotate( _yawOffset, osg::Vec3(0,1,0),\n _pitchOffset, osg::Vec3(1,0,0),\n 0.0, osg::Vec3(0,0,1));\n\n _adjustPosition();\n\n _inverseMatrix.makeLookAt( _position, _position + _direction, osg::Vec3(0,0,1)); \n _matrix.invert(_inverseMatrix);\n\n if( _decelerateUpSideRate )\n {\n _upSpeed *= 0.98;\n _sideSpeed *= 0.98;\n }\n\n if( _decelerateOffsetRate )\n {\n _yawOffsetRate *= 0.98;\n _pitchOffsetRate *= 0.98;\n }\n\n if( _straightenOffset )\n {\n _pitchOffsetRate = 0.0;\n _yawOffsetRate = 0.0;\n _pitchOffset *= 0.99;\n _yawOffset *= 0.99;\n\n if( fabs(_pitchOffset ) < 0.01 )\n _pitchOffset = 0.0;\n if( fabs(_yawOffset ) < 0.01 )\n _pitchOffset = 0.0;\n\n if( _pitchOffset == 0.0 && _yawOffset == 0.0 )\n _straightenOffset = false;\n }\n}\n\nvoid UFOManipulator::_adjustPosition()\n{\n if( !_node.valid() )\n return;\n\n osgUtil::IntersectVisitor iv;\n\n \/\/ Forward line segment at 3 times our intersect distance\n osg::ref_ptr<osg::LineSegment> segForward = new osg::LineSegment;\n segForward->set(_position, _position + (_direction * (_minDistanceInFront * 3.0)) );\n iv.addLineSegment( segForward.get() );\n\n\n \/\/ Down line segment at 3 times our intersect distance\n osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;\n segDown->set( _position, \n _position - (osg::Vec3(0,0, _minHeightAboveGround*3)));\n iv.addLineSegment( segDown.get() );\n\n _node->accept(iv);\n\n if (iv.hits())\n {\n \/\/ Check intersects infront.\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segForward.get());\n if (!hitList.empty())\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n\n double d = (ip - _position).length();\n \n if( d < _minDistanceInFront )\n {\n osg::Vec3 op = _position;\n _position = ip + (_direction * -_minDistanceInFront);\n _stop();\n }\n }\n }\n\n \/\/ Check intersects below.\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());\n if (!hitList.empty())\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n if( _position[2] - ip[2] < _minHeightAboveGround )\n _position[2] = ip[2] + _minHeightAboveGround;\n }\n }\n\n }\n}\n\n\nvoid UFOManipulator::_stop()\n{\n _forwardSpeed = 0.0;\n _sideSpeed = 0.0;\n _upSpeed = 0.0;\n _directionRotationRate = 0.0;\n}\n<commit_msg>Added the 'H' - home to usage message<commit_after>#include <osgGA\/UFOManipulator>\n#include <osgUtil\/IntersectVisitor>\n\nusing namespace osgGA;\n\nUFOManipulator::UFOManipulator():\n _t0(0.0),\n _shift(false),\n _ctrl(false)\n{ \n _minHeightAboveGround = 2.0;\n _minDistanceInFront = 5.0;\n\n _speedAccelerationFactor = 0.4;\n _speedDecelerationFactor = 0.90;\n\n _directionRotationRate = 0.0;\n _directionRotationAcceleration = M_PI*0.00005;\n _directionRotationDeceleration = 0.90;\n\n _speedEpsilon = 0.02;\n _directionRotationEpsilon = 0.0001;\n\n _viewOffsetDelta = M_PI * 0.0025;\n _pitchOffsetRate = 0.0;\n _pitchOffset = 0.0;\n\n _yawOffsetRate = 0.0;\n _yawOffset = 0.0;\n _offset.makeIdentity();\n\n _decelerateOffsetRate = true;\n _straightenOffset = false;\n\n _direction.set( 0,1,0);\n _stop();\n}\n\nvoid UFOManipulator::setNode( osg::Node *node )\n{\n _node = node;\n\n if (getAutoComputeHomePosition()) \n computeHomePosition();\n\n _home();\n}\n\nconst osg::Node* UFOManipulator::getNode() const\n{\n return _node.get();\n}\n\nosg::Node* UFOManipulator::getNode()\n{\n return _node.get();\n}\n\n\nconst char* UFOManipulator::className() const \n{ \n return \"UFO\"; \n}\n\nvoid UFOManipulator::setByMatrix( const osg::Matrix &mat ) \n{\n _inverseMatrix = mat;\n _matrix.invert( _inverseMatrix );\n}\n\nvoid UFOManipulator::setByInverseMatrix( const osg::Matrix &invmat) \n{\n _matrix = invmat;\n _inverseMatrix.invert( _matrix );\n}\n\nosg::Matrix UFOManipulator::getMatrix() const\n{\n return (_offset * _matrix);\n}\n\nosg::Matrix UFOManipulator::getInverseMatrix() const \n{\n return (_inverseMatrix * _offset);\n}\n\nvoid UFOManipulator::computeHomePosition()\n{\n if( !_node.valid() )\n return;\n\n osg::BoundingSphere bs = _node->getBound();\n\n \/*\n * Find the ground - Assumption: The ground is the hit of an intersection\n * from a line segment extending from above to below the database at its \n * horizontal center, that intersects the database closest to zero. *\/\n osgUtil::IntersectVisitor iv;\n osg::ref_ptr<osg::LineSegment> seg = new osg::LineSegment;\n osg::Vec3 A = bs.center() + (osg::Vec3(0,0,1)*(bs.radius()*2));\n osg::Vec3 B = bs.center() + (osg::Vec3(0,0,-1)*(bs.radius()*2));\n\n if( (B-A).length() == 0.0)\n {\n puts( \"DOH\" ); fflush(stdout);\n return;\n }\n\n \/*\n seg->set( bs.center() + (osg::Vec3(0,0,1)*(bs.radius()*2)), \n bs.center() + (osg::Vec3(0,0,-1)*(bs.radius()*2)) );\n *\/\n seg->set( A, B );\n\n iv.addLineSegment( seg.get() );\n _node->accept(iv);\n\n \/\/ start with it high\n double ground = bs.radius() * 3;\n\n if (iv.hits())\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(seg.get());\n for(osgUtil::IntersectVisitor::HitList::iterator hitr=hitList.begin();\n hitr!=hitList.end(); ++hitr)\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n if( fabs(ip[3]) < ground )\n ground = ip[3];\n }\n }\n else\n {\n osg::notify(osg::WARN)<<\"UFOManipulator : I can't find the ground!\"<<std::endl;\n ground = 0.0;\n }\n\n\n osg::Vec3 p(bs.center()[0], bs.center()[1], ground + (_minHeightAboveGround*1.25) );\n setHomePosition( p, p + osg::Vec3(0,1,0), osg::Vec3(0,0,1) );\n}\n\nvoid UFOManipulator::home(const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&) \n{\n _home();\n}\n\nvoid UFOManipulator::_home() \n{\n if (getAutoComputeHomePosition()) \n computeHomePosition();\n\n _position = _homeEye;\n _direction = _homeCenter - _homeEye;\n _direction.normalize();\n _directionRotationRate = 0.0;\n\n _inverseMatrix.makeLookAt( _homeEye, _homeCenter, _homeUp );\n _matrix.invert( _matrix );\n\n _offset.makeIdentity();\n\n _forwardSpeed = 0.0;\n _sideSpeed = 0.0;\n _upSpeed = 0.0;\n}\n\nbool UFOManipulator::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter &aa)\n{\n\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYUP):\n _keyUp( ea, aa );\n return false;\n break;\n\n case(osgGA::GUIEventAdapter::KEYDOWN):\n _keyDown(ea, aa);\n return false;\n break;\n\n case(osgGA::GUIEventAdapter::FRAME):\n _frame(ea,aa);\n return false;\n break;\n\n default:\n return false;\n }\n\n return false;\n}\n\nvoid UFOManipulator::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <SpaceBar>\", \"Reset the viewing angle to 0.0\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <UpArrow>\", \"Acceleration forward.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <DownArrow>\", \"Acceleration backward (or deceleration forward\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <LeftArrow>\", \"Rotate view and direction of travel to the left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <RightArrow>\", \"Rotate view and direction of travel to the right.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <SpaceBar>\", \"Brake. Gradually decelerates linear and rotational movement.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/UpArrow>\", \"Accelerate up.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/DownArrow>\", \"Accelerate down.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/LeftArrow>\", \"Accelerate (linearly) left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/RightArrow>\",\"Accelerate (linearly) right.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Shift\/SpaceBar>\", \"Instant brake. Immediately stop all linear and rotational movement.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/UpArrow>\", \"Rotate view (but not direction of travel) up.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/DownArrow>\", \"Rotate view (but not direction of travel) down.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/LeftArrow>\", \"Rotate view (but not direction of travel) left.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: <Ctrl\/RightArrow>\", \"Rotate view (but not direction of travel) right.\");\n usage.addKeyboardMouseBinding(\"UFO Manipulator: 'H'\", \"go to Home position.\");\n}\n\n\n\nvoid UFOManipulator::_keyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter & )\n{\n switch( ea.getKey() )\n {\n case Producer::KeyChar_Control_L:\n case Producer::KeyChar_Control_R:\n _ctrl = false;\n _decelerateOffsetRate = true;\n _straightenOffset = false;\n break;\n\n case Producer::KeyChar_Shift_L:\n case Producer::KeyChar_Shift_R:\n _shift = false;\n _decelerateUpSideRate = true;\n break;\n }\n}\n\nvoid UFOManipulator::_keyDown( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter & )\n{\n switch( ea.getKey() )\n {\n case Producer::KeyChar_Control_L:\n case Producer::KeyChar_Control_R:\n _ctrl = true;\n break;\n\n case Producer::KeyChar_Shift_L :\n case Producer::KeyChar_Shift_R :\n _shift = true;\n break;\n\n case Producer::KeyChar_Up:\n if( _ctrl )\n {\n _pitchOffsetRate -= _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if( _shift )\n {\n _upSpeed += _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _forwardSpeed += _speedAccelerationFactor;\n }\n break;\n\n case Producer::KeyChar_Down:\n if( _ctrl )\n {\n _pitchOffsetRate += _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if( _shift )\n {\n _upSpeed -= _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _forwardSpeed -= _speedAccelerationFactor;\n }\n break;\n\n case Producer::KeyChar_Right:\n if( _ctrl )\n {\n _yawOffsetRate += _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if(_shift)\n {\n _sideSpeed += _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _directionRotationRate -= _directionRotationAcceleration;\n }\n break;\n\n case Producer::KeyChar_Left:\n if( _ctrl )\n {\n _yawOffsetRate -= _viewOffsetDelta;\n _decelerateOffsetRate = false;\n }\n else\n {\n if(_shift)\n {\n _sideSpeed -= _speedAccelerationFactor;\n _decelerateUpSideRate = false;\n }\n else\n _directionRotationRate += _directionRotationAcceleration;\n }\n break;\n\n case Producer::KeyChar_Return:\n if( _ctrl )\n {\n _straightenOffset = true;\n }\n break;\n\n case ' ':\n if( _shift )\n {\n _stop();\n }\n else\n {\n if( fabs(_forwardSpeed) > 0.0 )\n {\n _forwardSpeed *= _speedDecelerationFactor;\n\n if( fabs(_forwardSpeed ) < _speedEpsilon )\n _forwardSpeed = 0.0;\n }\n if( fabs(_sideSpeed) > 0.0 )\n {\n _sideSpeed *= _speedDecelerationFactor;\n\n if( fabs( _sideSpeed ) < _speedEpsilon )\n _sideSpeed = 0.0;\n }\n\n if( fabs(_upSpeed) > 0.0 )\n {\n _upSpeed *= _speedDecelerationFactor;\n\n if( fabs( _upSpeed ) < _speedEpsilon )\n _sideSpeed = 0.0;\n }\n\n\n if( fabs(_directionRotationRate ) > 0.0 )\n {\n _directionRotationRate *= _directionRotationDeceleration;\n if( fabs( _directionRotationRate ) < _directionRotationEpsilon )\n _directionRotationRate = 0.0;\n }\n \n }\n break;\n\n case 'H':\n _home();\n break;\n }\n}\n\nvoid UFOManipulator::_frame( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter & )\n{\n double t1 = ea.time();\n if( _t0 == 0.0 )\n {\n _t0 = ea.time();\n _dt = 0.0;\n }\n else\n {\n _dt = t1 - _t0;\n _t0 = t1;\n }\n\n if( fabs( _directionRotationRate ) > _directionRotationEpsilon )\n {\n _direction = _direction * osg::Matrix::rotate( _directionRotationRate, osg::Vec3(0,0,1));\n }\n\n {\n osg::Vec3 _sideVec = _direction * osg::Matrix::rotate( -M_PI*0.5, osg::Vec3(0,0,1));\n\n _position += ((_direction * _forwardSpeed) + \n (_sideVec * _sideSpeed) +\n (osg::Vec3(0,0,1) * _upSpeed))\n * _dt;\n }\n\n _pitchOffset += _pitchOffsetRate * _dt;\n if( _pitchOffset >= M_PI || _pitchOffset < -M_PI )\n _pitchOffset *= -1;\n\n _yawOffset += _yawOffsetRate * _dt;\n if( _yawOffset >= M_PI || _yawOffset < -M_PI ) \n _yawOffset *= -1;\n\n _offset = osg::Matrix::rotate( _yawOffset, osg::Vec3(0,1,0),\n _pitchOffset, osg::Vec3(1,0,0),\n 0.0, osg::Vec3(0,0,1));\n\n _adjustPosition();\n\n _inverseMatrix.makeLookAt( _position, _position + _direction, osg::Vec3(0,0,1)); \n _matrix.invert(_inverseMatrix);\n\n if( _decelerateUpSideRate )\n {\n _upSpeed *= 0.98;\n _sideSpeed *= 0.98;\n }\n\n if( _decelerateOffsetRate )\n {\n _yawOffsetRate *= 0.98;\n _pitchOffsetRate *= 0.98;\n }\n\n if( _straightenOffset )\n {\n _pitchOffsetRate = 0.0;\n _yawOffsetRate = 0.0;\n _pitchOffset *= 0.99;\n _yawOffset *= 0.99;\n\n if( fabs(_pitchOffset ) < 0.01 )\n _pitchOffset = 0.0;\n if( fabs(_yawOffset ) < 0.01 )\n _pitchOffset = 0.0;\n\n if( _pitchOffset == 0.0 && _yawOffset == 0.0 )\n _straightenOffset = false;\n }\n}\n\nvoid UFOManipulator::_adjustPosition()\n{\n if( !_node.valid() )\n return;\n\n osgUtil::IntersectVisitor iv;\n\n \/\/ Forward line segment at 3 times our intersect distance\n osg::ref_ptr<osg::LineSegment> segForward = new osg::LineSegment;\n segForward->set(_position, _position + (_direction * (_minDistanceInFront * 3.0)) );\n iv.addLineSegment( segForward.get() );\n\n\n \/\/ Down line segment at 3 times our intersect distance\n osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;\n segDown->set( _position, \n _position - (osg::Vec3(0,0, _minHeightAboveGround*3)));\n iv.addLineSegment( segDown.get() );\n\n _node->accept(iv);\n\n if (iv.hits())\n {\n \/\/ Check intersects infront.\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segForward.get());\n if (!hitList.empty())\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n\n double d = (ip - _position).length();\n \n if( d < _minDistanceInFront )\n {\n osg::Vec3 op = _position;\n _position = ip + (_direction * -_minDistanceInFront);\n _stop();\n }\n }\n }\n\n \/\/ Check intersects below.\n {\n osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());\n if (!hitList.empty())\n {\n osg::Vec3d ip = hitList.front().getWorldIntersectPoint();\n if( _position[2] - ip[2] < _minHeightAboveGround )\n _position[2] = ip[2] + _minHeightAboveGround;\n }\n }\n\n }\n}\n\n\nvoid UFOManipulator::_stop()\n{\n _forwardSpeed = 0.0;\n _sideSpeed = 0.0;\n _upSpeed = 0.0;\n _directionRotationRate = 0.0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <bcc\/BPF.h>\nextern \"C\" {\n#include <unistd.h>\n#include <stdarg.h>\n#include <sys\/time.h>\n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\nOptional arguments:\n -d Print debugging information (-dd shows more)\n -h Print this help and exit\n -l Print the list of handled USDTs and exit\n -s RESPONSE_HEADER_NAMES Response header names to show, e.g. \"content-type\"\n -t EVENT_TYPES Fully-qualified probe names to show, e.g. \"quicly:accept\"\n -w Path to write the output (default: stdout)\n\nExamples:\n h2olog quic -p $(pgrep -o h2o)\n h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free\n h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector<std::string> &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)\n{\n std::vector<std::string> conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector<std::string> exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr<h2o_tracer> tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n int debug = 0;\n int list_and_exit = 0;\n FILE *outfp = stdout;\n std::vector<std::string> event_type_filters;\n std::vector<std::string> response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdp:t:s:w:l\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't':\n event_type_filters.push_back(optarg);\n break;\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'l':\n list_and_exit++;\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (list_and_exit) {\n for (const auto &usdt : tracer->usdt_probes()) {\n fprintf(stderr, \"%s:%s\\n\", usdt.provider.c_str(), usdt.name.c_str());\n }\n exit(EXIT_SUCCESS);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector<std::string> cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"event_type_filters=\");\n for (size_t i = 0; i < event_type_filters.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \",\");\n }\n fprintf(stderr, \"%s\", event_type_filters[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"<BPF>\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector<ebpf::USDT> probes;\n for (const auto &probe_def : tracer->usdt_probes()) {\n if (event_type_filters.empty() || std::find(event_type_filters.cbegin(), event_type_filters.cend(),\n probe_def.provider + \":\" + probe_def.name) != event_type_filters.cend()) {\n probes.push_back(ebpf::USDT(h2o_pid, probe_def.provider, probe_def.name, probe_def.probe_func));\n }\n }\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\n<commit_msg>h2olog: use bool for boolean<commit_after>\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <bcc\/BPF.h>\nextern \"C\" {\n#include <unistd.h>\n#include <stdarg.h>\n#include <sys\/time.h>\n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\nOptional arguments:\n -d Print debugging information (-dd shows more)\n -h Print this help and exit\n -l Print the list of handled USDTs and exit\n -s RESPONSE_HEADER_NAMES Response header names to show, e.g. \"content-type\"\n -t EVENT_TYPES Fully-qualified probe names to show, e.g. \"quicly:accept\"\n -w Path to write the output (default: stdout)\n\nExamples:\n h2olog quic -p $(pgrep -o h2o)\n h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free\n h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector<std::string> &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)\n{\n std::vector<std::string> conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector<std::string> exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr<h2o_tracer> tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n int debug = 0;\n bool list_and_exit = false;\n FILE *outfp = stdout;\n std::vector<std::string> event_type_filters;\n std::vector<std::string> response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdp:t:s:w:l\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't':\n event_type_filters.push_back(optarg);\n break;\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'l':\n list_and_exit = true;\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (list_and_exit) {\n for (const auto &usdt : tracer->usdt_probes()) {\n fprintf(stderr, \"%s:%s\\n\", usdt.provider.c_str(), usdt.name.c_str());\n }\n exit(EXIT_SUCCESS);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector<std::string> cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"event_type_filters=\");\n for (size_t i = 0; i < event_type_filters.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \",\");\n }\n fprintf(stderr, \"%s\", event_type_filters[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"<BPF>\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector<ebpf::USDT> probes;\n for (const auto &probe_def : tracer->usdt_probes()) {\n if (event_type_filters.empty() || std::find(event_type_filters.cbegin(), event_type_filters.cend(),\n probe_def.provider + \":\" + probe_def.name) != event_type_filters.cend()) {\n probes.push_back(ebpf::USDT(h2o_pid, probe_def.provider, probe_def.name, probe_def.probe_func));\n }\n }\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <bcc\/BPF.h>\nextern \"C\" {\n#include <unistd.h>\n#include <stdarg.h>\n#include <sys\/time.h>\n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\nOptional arguments:\n -d Print debugging information (-dd shows more)\n -h Print this help and exit\n -l Print the list of handled USDTs and exit\n -s RESPONSE_HEADER_NAMES Response header names to show, e.g. \"content-type\"\n -t EVENT_TYPES Fully-qualified probe names to show, e.g. \"quicly:accept\"\n -w Path to write the output (default: stdout)\n\nExamples:\n h2olog quic -p $(pgrep -o h2o)\n h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free\n h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector<std::string> &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)\n{\n std::vector<std::string> conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector<std::string> exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr<h2o_tracer> tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n std::vector<h2o_tracer::usdt> available_usdts = tracer->usdt_probes();\n\n int debug = 0;\n bool list_and_exit = false;\n FILE *outfp = stdout;\n std::vector<h2o_tracer::usdt> event_type_filters;\n std::vector<std::string> response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdp:t:s:w:l\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't': {\n auto found = std::find_if(available_usdts.cbegin(), available_usdts.cend(),\n [](const h2o_tracer::usdt &usdt) { return optarg == usdt.fully_qualified_name(); });\n if (found == available_usdts.cend()) {\n fprintf(stderr, \"No such event type: %s\\n\", optarg);\n exit(EXIT_FAILURE);\n }\n event_type_filters.push_back(*found);\n break;\n }\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'l':\n list_and_exit = true;\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (list_and_exit) {\n for (const auto &usdt : tracer->usdt_probes()) {\n printf(\"%s:%s\\n\", usdt.provider.c_str(), usdt.name.c_str());\n }\n exit(EXIT_SUCCESS);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector<std::string> cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (event_type_filters.empty()) {\n event_type_filters = available_usdts;\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"event_type_filters=\");\n for (auto iter = event_type_filters.cbegin(); iter != event_type_filters.cend(); iter++) {\n if (iter != event_type_filters.cbegin()) {\n fprintf(stderr, \",\");\n }\n fprintf(stderr, \"%s\", iter->fully_qualified_name().c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"<BPF>\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector<ebpf::USDT> probes;\n\n for (const auto &usdt : event_type_filters) {\n probes.push_back(ebpf::USDT(h2o_pid, usdt.provider, usdt.name, usdt.probe_func));\n }\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\n<commit_msg>h2olog: refine the code<commit_after>\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <bcc\/BPF.h>\nextern \"C\" {\n#include <unistd.h>\n#include <stdarg.h>\n#include <sys\/time.h>\n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\nOptional arguments:\n -d Print debugging information (-dd shows more)\n -h Print this help and exit\n -l Print the list of available probe names and exit\n -s RESPONSE_HEADER_NAME A response header name to show, e.g. \"content-type\"\n -t PROBE_NAME A fully-qualified probe name to show, e.g. \"quicly:accept\"\n -w Path to write the output (default: stdout)\n\nExamples:\n h2olog quic -p $(pgrep -o h2o)\n h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free\n h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector<std::string> &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)\n{\n std::vector<std::string> conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector<std::string> exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr<h2o_tracer> tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n const std::vector<h2o_tracer::usdt> available_usdts = tracer->usdt_probes();\n\n int debug = 0;\n FILE *outfp = stdout;\n std::vector<h2o_tracer::usdt> selected_usdts;\n std::vector<std::string> response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdp:t:s:w:l\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't': {\n auto found = std::find_if(available_usdts.cbegin(), available_usdts.cend(),\n [](const h2o_tracer::usdt &usdt) { return optarg == usdt.fully_qualified_name(); });\n if (found == available_usdts.cend()) {\n fprintf(stderr, \"No such event type: %s\\n\", optarg);\n exit(EXIT_FAILURE);\n }\n selected_usdts.push_back(*found);\n break;\n }\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'l':\n for (const auto &usdt : available_usdts) {\n printf(\"%s\\n\", usdt.fully_qualified_name().c_str());\n }\n exit(EXIT_SUCCESS);\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector<std::string> cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (selected_usdts.empty()) {\n selected_usdts = available_usdts;\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"selected_usdts=\");\n for (auto iter = selected_usdts.cbegin(); iter != selected_usdts.cend(); iter++) {\n if (iter != selected_usdts.cbegin()) {\n fprintf(stderr, \",\");\n }\n fprintf(stderr, \"%s\", iter->fully_qualified_name().c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"<BPF>\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector<ebpf::USDT> probes;\n\n for (const auto &usdt : selected_usdts) {\n probes.push_back(ebpf::USDT(h2o_pid, usdt.provider, usdt.name, usdt.probe_func));\n }\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2009-2010 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"heap-profiler.h\"\n#include \"profile-generator.h\"\n\nnamespace v8 {\nnamespace internal {\n\nHeapProfiler::HeapProfiler()\n : snapshots_(new HeapSnapshotsCollection()),\n next_snapshot_uid_(1) {\n}\n\n\nHeapProfiler::~HeapProfiler() {\n delete snapshots_;\n}\n\n\nvoid HeapProfiler::ResetSnapshots() {\n delete snapshots_;\n snapshots_ = new HeapSnapshotsCollection();\n}\n\n\nvoid HeapProfiler::SetUp() {\n Isolate* isolate = Isolate::Current();\n if (isolate->heap_profiler() == NULL) {\n isolate->set_heap_profiler(new HeapProfiler());\n }\n}\n\n\nvoid HeapProfiler::TearDown() {\n Isolate* isolate = Isolate::Current();\n delete isolate->heap_profiler();\n isolate->set_heap_profiler(NULL);\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshot(const char* name,\n int type,\n v8::ActivityControl* control) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->TakeSnapshotImpl(name,\n type,\n control);\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshot(String* name,\n int type,\n v8::ActivityControl* control) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->TakeSnapshotImpl(name,\n type,\n control);\n}\n\n\nvoid HeapProfiler::StartHeapObjectsTracking() {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n Isolate::Current()->heap_profiler()->StartHeapObjectsTrackingImpl();\n}\n\n\nvoid HeapProfiler::StopHeapObjectsTracking() {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n Isolate::Current()->heap_profiler()->StopHeapObjectsTrackingImpl();\n}\n\n\nvoid HeapProfiler::PushHeapObjectsStats(v8::OutputStream* stream) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->PushHeapObjectsStatsImpl(stream);\n}\n\n\nvoid HeapProfiler::DefineWrapperClass(\n uint16_t class_id, v8::HeapProfiler::WrapperInfoCallback callback) {\n ASSERT(class_id != v8::HeapProfiler::kPersistentHandleNoClassId);\n if (wrapper_callbacks_.length() <= class_id) {\n wrapper_callbacks_.AddBlock(\n NULL, class_id - wrapper_callbacks_.length() + 1);\n }\n wrapper_callbacks_[class_id] = callback;\n}\n\n\nv8::RetainedObjectInfo* HeapProfiler::ExecuteWrapperClassCallback(\n uint16_t class_id, Object** wrapper) {\n if (wrapper_callbacks_.length() <= class_id) return NULL;\n return wrapper_callbacks_[class_id](\n class_id, Utils::ToLocal(Handle<Object>(wrapper)));\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshotImpl(const char* name,\n int type,\n v8::ActivityControl* control) {\n HeapSnapshot::Type s_type = static_cast<HeapSnapshot::Type>(type);\n HeapSnapshot* result =\n snapshots_->NewSnapshot(s_type, name, next_snapshot_uid_++);\n bool generation_completed = true;\n switch (s_type) {\n case HeapSnapshot::kFull: {\n HeapSnapshotGenerator generator(result, control);\n generation_completed = generator.GenerateSnapshot();\n break;\n }\n default:\n UNREACHABLE();\n }\n if (!generation_completed) {\n delete result;\n result = NULL;\n }\n snapshots_->SnapshotGenerationFinished(result);\n return result;\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshotImpl(String* name,\n int type,\n v8::ActivityControl* control) {\n return TakeSnapshotImpl(snapshots_->names()->GetName(name), type, control);\n}\n\nvoid HeapProfiler::StartHeapObjectsTrackingImpl() {\n snapshots_->StartHeapObjectsTracking();\n}\n\n\nvoid HeapProfiler::PushHeapObjectsStatsImpl(OutputStream* stream) {\n snapshots_->PushHeapObjectsStats(stream);\n}\n\n\nvoid HeapProfiler::StopHeapObjectsTrackingImpl() {\n snapshots_->StopHeapObjectsTracking();\n}\n\n\nint HeapProfiler::GetSnapshotsCount() {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->snapshots()->length();\n}\n\n\nHeapSnapshot* HeapProfiler::GetSnapshot(int index) {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->snapshots()->at(index);\n}\n\n\nHeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->GetSnapshot(uid);\n}\n\n\nSnapshotObjectId HeapProfiler::GetSnapshotObjectId(Handle<Object> obj) {\n if (!obj->IsHeapObject())\n return v8::HeapProfiler::kUnknownObjectId;\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->FindObjectId(HeapObject::cast(*obj) ->address());\n}\n\n\nvoid HeapProfiler::DeleteAllSnapshots() {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n profiler->ResetSnapshots();\n}\n\n\nvoid HeapProfiler::ObjectMoveEvent(Address from, Address to) {\n snapshots_->ObjectMoveEvent(from, to);\n}\n\n\n} } \/\/ namespace v8::internal\n<commit_msg>Remove extra whitespace added in r11339<commit_after>\/\/ Copyright 2009-2010 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"heap-profiler.h\"\n#include \"profile-generator.h\"\n\nnamespace v8 {\nnamespace internal {\n\nHeapProfiler::HeapProfiler()\n : snapshots_(new HeapSnapshotsCollection()),\n next_snapshot_uid_(1) {\n}\n\n\nHeapProfiler::~HeapProfiler() {\n delete snapshots_;\n}\n\n\nvoid HeapProfiler::ResetSnapshots() {\n delete snapshots_;\n snapshots_ = new HeapSnapshotsCollection();\n}\n\n\nvoid HeapProfiler::SetUp() {\n Isolate* isolate = Isolate::Current();\n if (isolate->heap_profiler() == NULL) {\n isolate->set_heap_profiler(new HeapProfiler());\n }\n}\n\n\nvoid HeapProfiler::TearDown() {\n Isolate* isolate = Isolate::Current();\n delete isolate->heap_profiler();\n isolate->set_heap_profiler(NULL);\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshot(const char* name,\n int type,\n v8::ActivityControl* control) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->TakeSnapshotImpl(name,\n type,\n control);\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshot(String* name,\n int type,\n v8::ActivityControl* control) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->TakeSnapshotImpl(name,\n type,\n control);\n}\n\n\nvoid HeapProfiler::StartHeapObjectsTracking() {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n Isolate::Current()->heap_profiler()->StartHeapObjectsTrackingImpl();\n}\n\n\nvoid HeapProfiler::StopHeapObjectsTracking() {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n Isolate::Current()->heap_profiler()->StopHeapObjectsTrackingImpl();\n}\n\n\nvoid HeapProfiler::PushHeapObjectsStats(v8::OutputStream* stream) {\n ASSERT(Isolate::Current()->heap_profiler() != NULL);\n return Isolate::Current()->heap_profiler()->PushHeapObjectsStatsImpl(stream);\n}\n\n\nvoid HeapProfiler::DefineWrapperClass(\n uint16_t class_id, v8::HeapProfiler::WrapperInfoCallback callback) {\n ASSERT(class_id != v8::HeapProfiler::kPersistentHandleNoClassId);\n if (wrapper_callbacks_.length() <= class_id) {\n wrapper_callbacks_.AddBlock(\n NULL, class_id - wrapper_callbacks_.length() + 1);\n }\n wrapper_callbacks_[class_id] = callback;\n}\n\n\nv8::RetainedObjectInfo* HeapProfiler::ExecuteWrapperClassCallback(\n uint16_t class_id, Object** wrapper) {\n if (wrapper_callbacks_.length() <= class_id) return NULL;\n return wrapper_callbacks_[class_id](\n class_id, Utils::ToLocal(Handle<Object>(wrapper)));\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshotImpl(const char* name,\n int type,\n v8::ActivityControl* control) {\n HeapSnapshot::Type s_type = static_cast<HeapSnapshot::Type>(type);\n HeapSnapshot* result =\n snapshots_->NewSnapshot(s_type, name, next_snapshot_uid_++);\n bool generation_completed = true;\n switch (s_type) {\n case HeapSnapshot::kFull: {\n HeapSnapshotGenerator generator(result, control);\n generation_completed = generator.GenerateSnapshot();\n break;\n }\n default:\n UNREACHABLE();\n }\n if (!generation_completed) {\n delete result;\n result = NULL;\n }\n snapshots_->SnapshotGenerationFinished(result);\n return result;\n}\n\n\nHeapSnapshot* HeapProfiler::TakeSnapshotImpl(String* name,\n int type,\n v8::ActivityControl* control) {\n return TakeSnapshotImpl(snapshots_->names()->GetName(name), type, control);\n}\n\nvoid HeapProfiler::StartHeapObjectsTrackingImpl() {\n snapshots_->StartHeapObjectsTracking();\n}\n\n\nvoid HeapProfiler::PushHeapObjectsStatsImpl(OutputStream* stream) {\n snapshots_->PushHeapObjectsStats(stream);\n}\n\n\nvoid HeapProfiler::StopHeapObjectsTrackingImpl() {\n snapshots_->StopHeapObjectsTracking();\n}\n\n\nint HeapProfiler::GetSnapshotsCount() {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->snapshots()->length();\n}\n\n\nHeapSnapshot* HeapProfiler::GetSnapshot(int index) {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->snapshots()->at(index);\n}\n\n\nHeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->GetSnapshot(uid);\n}\n\n\nSnapshotObjectId HeapProfiler::GetSnapshotObjectId(Handle<Object> obj) {\n if (!obj->IsHeapObject())\n return v8::HeapProfiler::kUnknownObjectId;\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n return profiler->snapshots_->FindObjectId(HeapObject::cast(*obj)->address());\n}\n\n\nvoid HeapProfiler::DeleteAllSnapshots() {\n HeapProfiler* profiler = Isolate::Current()->heap_profiler();\n ASSERT(profiler != NULL);\n profiler->ResetSnapshots();\n}\n\n\nvoid HeapProfiler::ObjectMoveEvent(Address from, Address to) {\n snapshots_->ObjectMoveEvent(from, to);\n}\n\n\n} } \/\/ namespace v8::internal\n<|endoftext|>"} {"text":"<commit_before>\/* junctions_extractor.h -- Declarations for `junctions extract` command\n\n Copyright (c) 2015, The Griffith Lab\n\n Author: Avinash Ramu <aramu@genome.wustl.edu>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE. *\/\n\n#include <algorithm>\n#include <getopt.h>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <stdexcept>\n#include \"common.h\"\n#include \"junctions_extractor.h\"\n#include \"sam.h\"\n#include \"hts.h\"\n#include \"faidx.h\"\n#include \"kstring.h\"\n\nusing namespace std;\n\n\/\/Parse the options passed to this tool\nint JunctionsExtractor::parse_options(int argc, char *argv[]) {\n optind = 1; \/\/Reset before parsing again.\n int c;\n stringstream help_ss;\n while((c = getopt(argc, argv, \"ha:i:I:o:r:\")) != -1) {\n switch(c) {\n case 'a':\n min_anchor_length_ = atoi(optarg);\n break;\n case 'i':\n min_intron_length_ = atoi(optarg);\n break;\n case 'I':\n max_intron_length_ = atoi(optarg);\n break;\n case 'o':\n output_file_ = string(optarg);\n break;\n case 'r':\n region_ = string(optarg);\n break;\n case 'h':\n usage(help_ss);\n throw cmdline_help_exception(help_ss.str());\n case '?':\n default:\n throw runtime_error(\"Error parsing inputs!\");\n }\n }\n if(argc == optind) {\n throw runtime_error(\"\\nError parsing inputs!\");\n }\n bam_ = string(argv[optind]);\n cerr << endl << \"Minimum junction anchor length: \" << min_anchor_length_;\n cerr << endl << \"Minimum intron length: \" << min_intron_length_;\n cerr << endl << \"Maximum intron length: \" << max_intron_length_;\n cerr << endl << \"Alignment: \" << bam_;\n cerr << endl << \"Output file: \" << output_file_;\n cerr << endl;\n return 0;\n}\n\n\/\/Usage statement for this tool\nint JunctionsExtractor::usage(ostream& out) {\n out << \"\\nUsage:\\t\\t\" << \"regtools junctions extract [options] indexed_alignments.bam\";\n out << \"\\nOptions:\";\n out << \"\\t\" << \"-a INT\\tMinimum anchor length. Junctions which satisfy a minimum \"\n \"anchor length on both sides are reported. [8]\";\n out << \"\\n\\t\\t\" << \"-i INT\\tMinimum intron length. [70]\";\n out << \"\\n\\t\\t\" << \"-I INT\\tMaximum intron length. [500000]\";\n out << \"\\n\\t\\t\" << \"-o FILE\\tThe file to write output to. [STDOUT]\";\n out << \"\\n\\t\\t\" << \"-r STR\\tThe region to identify junctions \"\n \"in \\\"chr:start-end\\\" format. Entire BAM by default.\";\n out << \"\\n\";\n return 0;\n}\n\n\/\/Get the BAM filename\nstring JunctionsExtractor::get_bam() {\n return bam_;\n}\n\n\/\/Name the junction based on the number of junctions\n\/\/ in the map.\nstring JunctionsExtractor::get_new_junction_name() {\n int index = junctions_.size() + 1;\n stringstream name_ss;\n name_ss << \"JUNC\" << setfill('0') << setw(8) << index;\n return name_ss.str();\n}\n\n\/\/Do some basic qc on the junction\nbool JunctionsExtractor::junction_qc(Junction &j1) {\n if(j1.end - j1.start < min_intron_length_ ||\n j1.end - j1.start > max_intron_length_) {\n return false;\n }\n if(j1.start - j1.thick_start >= min_anchor_length_)\n j1.has_left_min_anchor = true;\n if(j1.thick_end - j1.end >= min_anchor_length_)\n j1.has_right_min_anchor = true;\n return true;\n}\n\n\/\/Add a junction to the junctions map\n\/\/The read_count field is the number of reads supporting the junction.\nint JunctionsExtractor::add_junction(Junction j1) {\n \/\/Check junction_qc\n if(!junction_qc(j1)) {\n return 0;\n }\n\n \/\/Construct key chr:start-end:strand\n stringstream s1;\n string start, end;\n s1 << j1.start; start = s1.str();\n s1 << j1.end; end = s1.str();\n string key = j1.chrom + string(\":\") + start + \"-\" + end + \":\" + j1.strand;\n\n \/\/Check if new junction\n if(!junctions_.count(key)) {\n j1.name = get_new_junction_name();\n j1.read_count = 1;\n } else { \/\/existing junction\n Junction j0 = junctions_[key];\n \/\/increment read count\n j1.read_count = j0.read_count + 1;\n \/\/Keep the same name\n j1.name = j0.name;\n \/\/Check if thick starts are any better\n if(j0.thick_start < j1.thick_start)\n j1.thick_start = j0.thick_start;\n if(j0.thick_end > j1.thick_end)\n j1.thick_end = j0.thick_end;\n \/\/preserve min anchor information\n j1.has_left_min_anchor = j1.has_left_min_anchor || j0.has_left_min_anchor;\n j1.has_right_min_anchor = j1.has_right_min_anchor || j0.has_right_min_anchor;\n }\n \/\/Add junction and check anchor while printing.\n junctions_[key] = j1;\n return 0;\n}\n\n\/\/Print one junction\nvoid JunctionsExtractor::print_one_junction(const Junction j1, ostream& out) {\n out << j1.chrom <<\n \"\\t\" << j1.thick_start << \"\\t\" << j1.thick_end <<\n \"\\t\" << j1.name << \"\\t\" << j1.read_count << \"\\t\" << j1.strand <<\n \"\\t\" << j1.thick_start << \"\\t\" << j1.thick_end <<\n \"\\t\" << j1.color << \"\\t\" << j1.nblocks <<\n \"\\t\" << j1.start - j1.thick_start << \",\" << j1.thick_end - j1.end <<\n \"\\t\" << \"0,\" << j1.end - j1.thick_start << endl;\n}\n\n\/\/Print all the junctions - this function needs work\nvoid JunctionsExtractor::print_all_junctions(ostream& out) {\n ofstream fout;\n if(output_file_ != string(\"NA\")) {\n fout.open(output_file_.c_str());\n }\n \/\/Sort junctions by position\n if(!junctions_sorted_) {\n create_junctions_vector();\n sort_junctions();\n }\n for(vector<Junction> :: iterator it = junctions_vector_.begin();\n it != junctions_vector_.end(); it++) {\n Junction j1 = *it;\n if(j1.has_left_min_anchor && j1.has_right_min_anchor) {\n if(fout.is_open())\n print_one_junction(j1, fout);\n else\n print_one_junction(j1, out);\n }\n }\n if(fout.is_open())\n fout.close();\n}\n\n\/\/Get the strand from the XS aux tag\nvoid JunctionsExtractor::set_junction_strand(bam1_t *aln, Junction& j1) {\n uint8_t *p = bam_aux_get(aln, \"XS\");\n if(p != NULL) {\n char strand = bam_aux2A(p);\n strand ? j1.strand = string(1, strand) : j1.strand = string(1, '?');\n } else {\n j1.strand = string(1, '?');\n return;\n }\n}\n\n\/\/Parse junctions from the read and store in junction map\nint JunctionsExtractor::parse_alignment_into_junctions(bam_hdr_t *header, bam1_t *aln) {\n int n_cigar = aln->core.n_cigar;\n if (n_cigar <= 1) \/\/ max one cigar operation exists(likely all matches)\n return 0;\n\n int chr_id = aln->core.tid;\n int read_pos = aln->core.pos;\n string chr(header->target_name[chr_id]);\n uint32_t *cigar = bam_get_cigar(aln);\n\n \/*\n \/\/Skip duplicates\n int flag = aln->core.flag;\n if(flag & 1024) {\n cerr << \"Skipping read_pos \" << read_pos << \" flag \" << flag << endl;\n return 0;\n }\n *\/\n\n Junction j1;\n j1.chrom = chr;\n j1.start = read_pos; \/\/maintain start pos of junction\n j1.thick_start = read_pos;\n set_junction_strand(aln, j1);\n bool started_junction = false;\n for (int i = 0; i < n_cigar; ++i) {\n char op =\n bam_cigar_opchr(cigar[i]);\n int len =\n bam_cigar_oplen(cigar[i]);\n switch(op) {\n case 'N':\n if(!started_junction) {\n j1.end = j1.start + len;\n j1.thick_end = j1.end;\n \/\/Start the first one and remains started\n started_junction = true;\n } else {\n \/\/Add the previous junction\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n j1.thick_start = j1.end;\n j1.start = j1.thick_end;\n j1.end = j1.start + len;\n j1.thick_end = j1.end;\n \/\/For clarity - the next junction is now open\n started_junction = true;\n }\n break;\n case '=':\n case 'M':\n if(!started_junction)\n j1.start += len;\n else\n j1.thick_end += len;\n break;\n \/\/No mismatches allowed in anchor\n case 'D':\n case 'X':\n if(!started_junction) {\n j1.start += len;\n j1.thick_start = j1.start;\n } else {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n \/\/Don't include these in the next anchor\n j1.start = j1.thick_end + len;\n j1.thick_start = j1.start;\n }\n started_junction = false;\n break;\n case 'I':\n case 'S':\n if(!started_junction)\n j1.thick_start = j1.start;\n else {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n \/\/Don't include these in the next anchor\n j1.start = j1.thick_end;\n j1.thick_start = j1.start;\n }\n started_junction = false;\n break;\n case 'H':\n break;\n default:\n cerr << \"Unknown cigar \" << op;\n break;\n }\n }\n if(started_junction) {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n }\n return 0;\n}\n\n\/\/The workhorse - identifies junctions from BAM\nint JunctionsExtractor::identify_junctions_from_BAM() {\n if(!bam_.empty()) {\n \/\/open BAM for reading\n samFile *in = sam_open(bam_.c_str(), \"r\");\n if(in == NULL) {\n throw runtime_error(\"Unable to open BAM\/SAM file.\");\n }\n \/\/Load the index\n hts_idx_t *idx = sam_index_load(in, bam_.c_str());\n if(idx == NULL) {\n throw runtime_error(\"Unable to open BAM\/SAM index.\"\n \" Make sure alignments are indexed\");\n }\n \/\/Get the header\n bam_hdr_t *header = sam_hdr_read(in);\n \/\/Initialize iterator\n hts_itr_t *iter = NULL;\n \/\/Move the iterator to the region we are interested in\n iter = sam_itr_querys(idx, header, region_.c_str());\n if(header == NULL || iter == NULL) {\n sam_close(in);\n throw runtime_error(\"Unable to iterate to region within BAM.\");\n }\n \/\/Initiate the alignment record\n bam1_t *aln = bam_init1();\n while(sam_itr_next(in, iter, aln) >= 0) {\n parse_alignment_into_junctions(header, aln);\n }\n hts_itr_destroy(iter);\n hts_idx_destroy(idx);\n bam_destroy1(aln);\n bam_hdr_destroy(header);\n sam_close(in);\n }\n return 0;\n}\n\n\/\/Create the junctions vector from the map\nvoid JunctionsExtractor::create_junctions_vector() {\n for(map<string, Junction> :: iterator it = junctions_.begin();\n it != junctions_.end(); it++) {\n Junction j1 = it->second;\n junctions_vector_.push_back(j1);\n }\n}\n\n\/\/Sort all the junctions by their position\nvoid JunctionsExtractor::sort_junctions() {\n sort(junctions_vector_.begin(), junctions_vector_.end(), compare_junctions);\n junctions_sorted_ = true;\n}\n<commit_msg>Fix option parsing.<commit_after>\/* junctions_extractor.h -- Declarations for `junctions extract` command\n\n Copyright (c) 2015, The Griffith Lab\n\n Author: Avinash Ramu <aramu@genome.wustl.edu>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE. *\/\n\n#include <algorithm>\n#include <getopt.h>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <stdexcept>\n#include \"common.h\"\n#include \"junctions_extractor.h\"\n#include \"sam.h\"\n#include \"hts.h\"\n#include \"faidx.h\"\n#include \"kstring.h\"\n\nusing namespace std;\n\n\/\/Parse the options passed to this tool\nint JunctionsExtractor::parse_options(int argc, char *argv[]) {\n optind = 1; \/\/Reset before parsing again.\n int c;\n stringstream help_ss;\n while((c = getopt(argc, argv, \"ha:i:I:o:r:\")) != -1) {\n switch(c) {\n case 'a':\n min_anchor_length_ = atoi(optarg);\n break;\n case 'i':\n min_intron_length_ = atoi(optarg);\n break;\n case 'I':\n max_intron_length_ = atoi(optarg);\n break;\n case 'o':\n output_file_ = string(optarg);\n break;\n case 'r':\n region_ = string(optarg);\n break;\n case 'h':\n usage(help_ss);\n throw cmdline_help_exception(help_ss.str());\n case '?':\n default:\n throw runtime_error(\"Error parsing inputs!\");\n }\n }\n if(argc - optind >= 1) {\n bam_ = string(argv[optind++]);\n }\n if(optind < argc || bam_ == \"NA\") {\n throw runtime_error(\"\\nError parsing inputs!\");\n }\n cerr << endl << \"Minimum junction anchor length: \" << min_anchor_length_;\n cerr << endl << \"Minimum intron length: \" << min_intron_length_;\n cerr << endl << \"Maximum intron length: \" << max_intron_length_;\n cerr << endl << \"Alignment: \" << bam_;\n cerr << endl << \"Output file: \" << output_file_;\n cerr << endl;\n return 0;\n}\n\n\/\/Usage statement for this tool\nint JunctionsExtractor::usage(ostream& out) {\n out << \"\\nUsage:\\t\\t\" << \"regtools junctions extract [options] indexed_alignments.bam\";\n out << \"\\nOptions:\";\n out << \"\\t\" << \"-a INT\\tMinimum anchor length. Junctions which satisfy a minimum \"\n \"anchor length on both sides are reported. [8]\";\n out << \"\\n\\t\\t\" << \"-i INT\\tMinimum intron length. [70]\";\n out << \"\\n\\t\\t\" << \"-I INT\\tMaximum intron length. [500000]\";\n out << \"\\n\\t\\t\" << \"-o FILE\\tThe file to write output to. [STDOUT]\";\n out << \"\\n\\t\\t\" << \"-r STR\\tThe region to identify junctions \"\n \"in \\\"chr:start-end\\\" format. Entire BAM by default.\";\n out << \"\\n\";\n return 0;\n}\n\n\/\/Get the BAM filename\nstring JunctionsExtractor::get_bam() {\n return bam_;\n}\n\n\/\/Name the junction based on the number of junctions\n\/\/ in the map.\nstring JunctionsExtractor::get_new_junction_name() {\n int index = junctions_.size() + 1;\n stringstream name_ss;\n name_ss << \"JUNC\" << setfill('0') << setw(8) << index;\n return name_ss.str();\n}\n\n\/\/Do some basic qc on the junction\nbool JunctionsExtractor::junction_qc(Junction &j1) {\n if(j1.end - j1.start < min_intron_length_ ||\n j1.end - j1.start > max_intron_length_) {\n return false;\n }\n if(j1.start - j1.thick_start >= min_anchor_length_)\n j1.has_left_min_anchor = true;\n if(j1.thick_end - j1.end >= min_anchor_length_)\n j1.has_right_min_anchor = true;\n return true;\n}\n\n\/\/Add a junction to the junctions map\n\/\/The read_count field is the number of reads supporting the junction.\nint JunctionsExtractor::add_junction(Junction j1) {\n \/\/Check junction_qc\n if(!junction_qc(j1)) {\n return 0;\n }\n\n \/\/Construct key chr:start-end:strand\n stringstream s1;\n string start, end;\n s1 << j1.start; start = s1.str();\n s1 << j1.end; end = s1.str();\n string key = j1.chrom + string(\":\") + start + \"-\" + end + \":\" + j1.strand;\n\n \/\/Check if new junction\n if(!junctions_.count(key)) {\n j1.name = get_new_junction_name();\n j1.read_count = 1;\n } else { \/\/existing junction\n Junction j0 = junctions_[key];\n \/\/increment read count\n j1.read_count = j0.read_count + 1;\n \/\/Keep the same name\n j1.name = j0.name;\n \/\/Check if thick starts are any better\n if(j0.thick_start < j1.thick_start)\n j1.thick_start = j0.thick_start;\n if(j0.thick_end > j1.thick_end)\n j1.thick_end = j0.thick_end;\n \/\/preserve min anchor information\n j1.has_left_min_anchor = j1.has_left_min_anchor || j0.has_left_min_anchor;\n j1.has_right_min_anchor = j1.has_right_min_anchor || j0.has_right_min_anchor;\n }\n \/\/Add junction and check anchor while printing.\n junctions_[key] = j1;\n return 0;\n}\n\n\/\/Print one junction\nvoid JunctionsExtractor::print_one_junction(const Junction j1, ostream& out) {\n out << j1.chrom <<\n \"\\t\" << j1.thick_start << \"\\t\" << j1.thick_end <<\n \"\\t\" << j1.name << \"\\t\" << j1.read_count << \"\\t\" << j1.strand <<\n \"\\t\" << j1.thick_start << \"\\t\" << j1.thick_end <<\n \"\\t\" << j1.color << \"\\t\" << j1.nblocks <<\n \"\\t\" << j1.start - j1.thick_start << \",\" << j1.thick_end - j1.end <<\n \"\\t\" << \"0,\" << j1.end - j1.thick_start << endl;\n}\n\n\/\/Print all the junctions - this function needs work\nvoid JunctionsExtractor::print_all_junctions(ostream& out) {\n ofstream fout;\n if(output_file_ != string(\"NA\")) {\n fout.open(output_file_.c_str());\n }\n \/\/Sort junctions by position\n if(!junctions_sorted_) {\n create_junctions_vector();\n sort_junctions();\n }\n for(vector<Junction> :: iterator it = junctions_vector_.begin();\n it != junctions_vector_.end(); it++) {\n Junction j1 = *it;\n if(j1.has_left_min_anchor && j1.has_right_min_anchor) {\n if(fout.is_open())\n print_one_junction(j1, fout);\n else\n print_one_junction(j1, out);\n }\n }\n if(fout.is_open())\n fout.close();\n}\n\n\/\/Get the strand from the XS aux tag\nvoid JunctionsExtractor::set_junction_strand(bam1_t *aln, Junction& j1) {\n uint8_t *p = bam_aux_get(aln, \"XS\");\n if(p != NULL) {\n char strand = bam_aux2A(p);\n strand ? j1.strand = string(1, strand) : j1.strand = string(1, '?');\n } else {\n j1.strand = string(1, '?');\n return;\n }\n}\n\n\/\/Parse junctions from the read and store in junction map\nint JunctionsExtractor::parse_alignment_into_junctions(bam_hdr_t *header, bam1_t *aln) {\n int n_cigar = aln->core.n_cigar;\n if (n_cigar <= 1) \/\/ max one cigar operation exists(likely all matches)\n return 0;\n\n int chr_id = aln->core.tid;\n int read_pos = aln->core.pos;\n string chr(header->target_name[chr_id]);\n uint32_t *cigar = bam_get_cigar(aln);\n\n \/*\n \/\/Skip duplicates\n int flag = aln->core.flag;\n if(flag & 1024) {\n cerr << \"Skipping read_pos \" << read_pos << \" flag \" << flag << endl;\n return 0;\n }\n *\/\n\n Junction j1;\n j1.chrom = chr;\n j1.start = read_pos; \/\/maintain start pos of junction\n j1.thick_start = read_pos;\n set_junction_strand(aln, j1);\n bool started_junction = false;\n for (int i = 0; i < n_cigar; ++i) {\n char op =\n bam_cigar_opchr(cigar[i]);\n int len =\n bam_cigar_oplen(cigar[i]);\n switch(op) {\n case 'N':\n if(!started_junction) {\n j1.end = j1.start + len;\n j1.thick_end = j1.end;\n \/\/Start the first one and remains started\n started_junction = true;\n } else {\n \/\/Add the previous junction\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n j1.thick_start = j1.end;\n j1.start = j1.thick_end;\n j1.end = j1.start + len;\n j1.thick_end = j1.end;\n \/\/For clarity - the next junction is now open\n started_junction = true;\n }\n break;\n case '=':\n case 'M':\n if(!started_junction)\n j1.start += len;\n else\n j1.thick_end += len;\n break;\n \/\/No mismatches allowed in anchor\n case 'D':\n case 'X':\n if(!started_junction) {\n j1.start += len;\n j1.thick_start = j1.start;\n } else {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n \/\/Don't include these in the next anchor\n j1.start = j1.thick_end + len;\n j1.thick_start = j1.start;\n }\n started_junction = false;\n break;\n case 'I':\n case 'S':\n if(!started_junction)\n j1.thick_start = j1.start;\n else {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n \/\/Don't include these in the next anchor\n j1.start = j1.thick_end;\n j1.thick_start = j1.start;\n }\n started_junction = false;\n break;\n case 'H':\n break;\n default:\n cerr << \"Unknown cigar \" << op;\n break;\n }\n }\n if(started_junction) {\n try {\n add_junction(j1);\n } catch (const std::logic_error& e) {\n cout << e.what() << '\\n';\n }\n }\n return 0;\n}\n\n\/\/The workhorse - identifies junctions from BAM\nint JunctionsExtractor::identify_junctions_from_BAM() {\n if(!bam_.empty()) {\n \/\/open BAM for reading\n samFile *in = sam_open(bam_.c_str(), \"r\");\n if(in == NULL) {\n throw runtime_error(\"Unable to open BAM\/SAM file.\");\n }\n \/\/Load the index\n hts_idx_t *idx = sam_index_load(in, bam_.c_str());\n if(idx == NULL) {\n throw runtime_error(\"Unable to open BAM\/SAM index.\"\n \" Make sure alignments are indexed\");\n }\n \/\/Get the header\n bam_hdr_t *header = sam_hdr_read(in);\n \/\/Initialize iterator\n hts_itr_t *iter = NULL;\n \/\/Move the iterator to the region we are interested in\n iter = sam_itr_querys(idx, header, region_.c_str());\n if(header == NULL || iter == NULL) {\n sam_close(in);\n throw runtime_error(\"Unable to iterate to region within BAM.\");\n }\n \/\/Initiate the alignment record\n bam1_t *aln = bam_init1();\n while(sam_itr_next(in, iter, aln) >= 0) {\n parse_alignment_into_junctions(header, aln);\n }\n hts_itr_destroy(iter);\n hts_idx_destroy(idx);\n bam_destroy1(aln);\n bam_hdr_destroy(header);\n sam_close(in);\n }\n return 0;\n}\n\n\/\/Create the junctions vector from the map\nvoid JunctionsExtractor::create_junctions_vector() {\n for(map<string, Junction> :: iterator it = junctions_.begin();\n it != junctions_.end(); it++) {\n Junction j1 = it->second;\n junctions_vector_.push_back(j1);\n }\n}\n\n\/\/Sort all the junctions by their position\nvoid JunctionsExtractor::sort_junctions() {\n sort(junctions_vector_.begin(), junctions_vector_.end(), compare_junctions);\n junctions_sorted_ = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <libtorrent\/kademlia\/traversal_algorithm.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/node.hpp>\n#include <libtorrent\/session_status.hpp>\n\n#include <boost\/bind.hpp>\n\nnamespace libtorrent { namespace dht\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(traversal)\n#endif\n\nobserver_ptr traversal_algorithm::new_observer(void* ptr\n\t, udp::endpoint const& ep, node_id const& id)\n{\n\tobserver_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id));\n#ifdef TORRENT_DEBUG\n\to->m_in_constructor = false;\n#endif\n\treturn o;\n}\n\nvoid traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)\n{\n\tTORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer));\n\tvoid* ptr = m_node.m_rpc.allocate_observer();\n\tif (ptr == 0)\n\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \"[\" << this << \"] failed to \"\n\t\t\t\"allocate memory for observer. aborting!\";\n#endif\n\t\tdone();\n\t\treturn;\n\t}\n\tobserver_ptr o = new_observer(ptr, addr, id);\n\tif (id.is_all_zeros())\n\t{\n\t\to->set_id(generate_id());\n\t\to->flags |= observer::flag_no_id;\n\t}\n\n\to->flags |= flags;\n\n\tstd::vector<observer_ptr>::iterator i = std::lower_bound(\n\t\tm_results.begin()\n\t\t, m_results.end()\n\t\t, o\n\t\t, boost::bind(\n\t\t\tcompare_ref\n\t\t\t, boost::bind(&observer::id, _1)\n\t\t\t, boost::bind(&observer::id, _2)\n\t\t\t, m_target\n\t\t)\n\t);\n\n\tif (i == m_results.end() || (*i)->id() != id)\n\t{\n\t\tTORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()\n\t\t\t, boost::bind(&observer::id, _1) == id) == m_results.end());\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \"[\" << this << \"] adding result: \" << id << \" \" << addr;\n#endif\n\t\ti = m_results.insert(i, o);\n\t}\n\n\tif (m_results.size() > 100) m_results.resize(100);\n}\n\nvoid traversal_algorithm::start()\n{\n\t\/\/ in case the routing table is empty, use the\n\t\/\/ router nodes in the table\n\tif (m_results.empty()) add_router_entries();\n\tinit();\n\tadd_requests();\n}\n\nvoid* traversal_algorithm::allocate_observer()\n{\n\treturn m_node.m_rpc.allocate_observer();\n}\n\nvoid traversal_algorithm::free_observer(void* ptr)\n{\n\tm_node.m_rpc.free_observer(ptr);\n}\n\nvoid traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tif (id.is_all_zeros())\n\t\tTORRENT_LOG(traversal) << time_now_string() << \"[\" << this << \"] WARNING: \"\n\t\t\t\"node returned a list which included a node with id 0\";\n#endif\n\tadd_entry(id, addr, 0);\n}\n\nvoid traversal_algorithm::finished(observer_ptr o)\n{\n#ifdef TORRENT_DEBUG\n\tstd::vector<observer_ptr>::iterator i = std::find(\n\t\tm_results.begin(), m_results.end(), o);\n\n\tTORRENT_ASSERT(i != m_results.end());\n#endif\n\n\t\/\/ if this flag is set, it means we increased the\n\t\/\/ branch factor for it, and we should restore it\n\tif (o->flags & observer::flag_short_timeout)\n\t\t--m_branch_factor;\n\n\to->flags |= observer::flag_alive;\n\n\t++m_responses;\n\t--m_invoke_count;\n\tTORRENT_ASSERT(m_invoke_count >= 0);\n\tadd_requests();\n\tif (m_invoke_count == 0) done();\n}\n\n\/\/ prevent request means that the total number of requests has\n\/\/ overflown. This query failed because it was the oldest one.\n\/\/ So, if this is true, don't make another request\nvoid traversal_algorithm::failed(observer_ptr o, int flags)\n{\n\tTORRENT_ASSERT(m_invoke_count >= 0);\n\n\tif (m_results.empty()) return;\n\n\tTORRENT_ASSERT(o->flags & observer::flag_queried);\n\tif (flags & short_timeout)\n\t{\n\t\t\/\/ short timeout means that it has been more than\n\t\t\/\/ two seconds since we sent the request, and that\n\t\t\/\/ we'll most likely not get a response. But, in case\n\t\t\/\/ we do get a late response, keep the handler\n\t\t\/\/ around for some more, but open up the slot\n\t\t\/\/ by increasing the branch factor\n\t\tif ((o->flags & observer::flag_short_timeout) == 0)\n\t\t\t++m_branch_factor;\n\t\to->flags |= observer::flag_short_timeout;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"] first chance timeout: \"\n\t\t\t<< o->id() << \" \" << o->target_ep()\n\t\t\t<< \" branch-factor: \" << m_branch_factor\n\t\t\t<< \" invoke-count: \" << m_invoke_count;\n#endif\n\t}\n\telse\n\t{\n\t\to->flags |= observer::flag_failed;\n\t\t\/\/ if this flag is set, it means we increased the\n\t\t\/\/ branch factor for it, and we should restore it\n\t\tif (o->flags & observer::flag_short_timeout)\n\t\t\t--m_branch_factor;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"] failed: \"\n\t\t\t<< o->id() << \" \" << o->target_ep()\n\t\t\t<< \" branch-factor: \" << m_branch_factor\n\t\t\t<< \" invoke-count: \" << m_invoke_count;\n#endif\n\t\t\/\/ don't tell the routing table about\n\t\t\/\/ node ids that we just generated ourself\n\t\tif ((o->flags & observer::flag_no_id) == 0)\n\t\t\tm_node.m_table.node_failed(o->id());\n\t\t++m_timeouts;\n\t\t--m_invoke_count;\n\t\tTORRENT_ASSERT(m_invoke_count >= 0);\n\t}\n\n\tif (flags & prevent_request)\n\t{\n\t\t--m_branch_factor;\n\t\tif (m_branch_factor <= 0) m_branch_factor = 1;\n\t}\n\tadd_requests();\n\tif (m_invoke_count == 0) done();\n}\n\nvoid traversal_algorithm::done()\n{\n\t\/\/ delete all our references to the observer objects so\n\t\/\/ they will in turn release the traversal algorithm\n\tm_results.clear();\n}\n\nnamespace\n{\n\tbool bitwise_nand(unsigned char lhs, unsigned char rhs)\n\t{\n\t\treturn (lhs & rhs) == 0;\n\t}\n}\n\nvoid traversal_algorithm::add_requests()\n{\n\tint results_target = m_node.m_table.bucket_size();\n\n\t\/\/ Find the first node that hasn't already been queried.\n\tfor (std::vector<observer_ptr>::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end\n\t\t&& results_target > 0 && m_invoke_count < m_branch_factor; ++i)\n\t{\n\t\tif ((*i)->flags & observer::flag_alive) --results_target;\n\t\tif ((*i)->flags & observer::flag_queried) continue;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"]\"\n\t\t\t<< \" nodes-left: \" << (m_results.end() - i)\n\t\t\t<< \" invoke-count: \" << m_invoke_count\n\t\t\t<< \" branch-factor: \" << m_branch_factor;\n#endif\n\n\t\tif (invoke(*i))\n\t\t{\n\t\t\tTORRENT_ASSERT(m_invoke_count >= 0);\n\t\t\t++m_invoke_count;\n\t\t\t(*i)->flags |= observer::flag_queried;\n\t\t}\n\t}\n}\n\nvoid traversal_algorithm::add_router_entries()\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(traversal) << \" using router nodes to initiate traversal algorithm. \"\n\t\t<< std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << \" routers\";\n#endif\n\tfor (routing_table::router_iterator i = m_node.m_table.router_begin()\n\t\t, end(m_node.m_table.router_end()); i != end; ++i)\n\t{\n\t\tadd_entry(node_id(0), *i, observer::flag_initial);\n\t}\n}\n\nvoid traversal_algorithm::init()\n{\n\t\/\/ update the last activity of this bucket\n\tm_node.m_table.touch_bucket(m_target);\n\tm_branch_factor = m_node.branch_factor();\n\tm_node.add_traversal_algorithm(this);\n}\n\ntraversal_algorithm::~traversal_algorithm()\n{\n\tm_node.remove_traversal_algorithm(this);\n}\n\nvoid traversal_algorithm::status(dht_lookup& l)\n{\n\tl.timeouts = m_timeouts;\n\tl.responses = m_responses;\n\tl.outstanding_requests = m_invoke_count;\n\tl.branch_factor = m_branch_factor;\n\tl.type = name();\n\tl.nodes_left = 0;\n\tfor (std::vector<observer_ptr>::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end; ++i)\n\t{\n\t\tif ((*i)->flags & observer::flag_queried) continue;\n\t\t++l.nodes_left;\n\t}\n}\n\n} } \/\/ namespace libtorrent::dht\n\n<commit_msg>dht assert fix<commit_after>\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include <libtorrent\/kademlia\/traversal_algorithm.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/node.hpp>\n#include <libtorrent\/session_status.hpp>\n\n#include <boost\/bind.hpp>\n\nnamespace libtorrent { namespace dht\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(traversal)\n#endif\n\nobserver_ptr traversal_algorithm::new_observer(void* ptr\n\t, udp::endpoint const& ep, node_id const& id)\n{\n\tobserver_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id));\n#ifdef TORRENT_DEBUG\n\to->m_in_constructor = false;\n#endif\n\treturn o;\n}\n\nvoid traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)\n{\n\tTORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer));\n\tvoid* ptr = m_node.m_rpc.allocate_observer();\n\tif (ptr == 0)\n\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \"[\" << this << \"] failed to \"\n\t\t\t\"allocate memory for observer. aborting!\";\n#endif\n\t\tdone();\n\t\treturn;\n\t}\n\tobserver_ptr o = new_observer(ptr, addr, id);\n\tif (id.is_all_zeros())\n\t{\n\t\to->set_id(generate_id());\n\t\to->flags |= observer::flag_no_id;\n\t}\n\n\to->flags |= flags;\n\n\tstd::vector<observer_ptr>::iterator i = std::lower_bound(\n\t\tm_results.begin()\n\t\t, m_results.end()\n\t\t, o\n\t\t, boost::bind(\n\t\t\tcompare_ref\n\t\t\t, boost::bind(&observer::id, _1)\n\t\t\t, boost::bind(&observer::id, _2)\n\t\t\t, m_target\n\t\t)\n\t);\n\n\tif (i == m_results.end() || (*i)->id() != id)\n\t{\n\t\tTORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()\n\t\t\t, boost::bind(&observer::id, _1) == id) == m_results.end());\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \"[\" << this << \"] adding result: \" << id << \" \" << addr;\n#endif\n\t\ti = m_results.insert(i, o);\n\t}\n\n\tif (m_results.size() > 100) m_results.resize(100);\n}\n\nvoid traversal_algorithm::start()\n{\n\t\/\/ in case the routing table is empty, use the\n\t\/\/ router nodes in the table\n\tif (m_results.empty()) add_router_entries();\n\tinit();\n\tadd_requests();\n}\n\nvoid* traversal_algorithm::allocate_observer()\n{\n\treturn m_node.m_rpc.allocate_observer();\n}\n\nvoid traversal_algorithm::free_observer(void* ptr)\n{\n\tm_node.m_rpc.free_observer(ptr);\n}\n\nvoid traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tif (id.is_all_zeros())\n\t\tTORRENT_LOG(traversal) << time_now_string() << \"[\" << this << \"] WARNING: \"\n\t\t\t\"node returned a list which included a node with id 0\";\n#endif\n\tadd_entry(id, addr, 0);\n}\n\nvoid traversal_algorithm::finished(observer_ptr o)\n{\n#ifdef TORRENT_DEBUG\n\tstd::vector<observer_ptr>::iterator i = std::find(\n\t\tm_results.begin(), m_results.end(), o);\n\n\tTORRENT_ASSERT(i != m_results.end() || m_results.size() == 100);\n#endif\n\n\t\/\/ if this flag is set, it means we increased the\n\t\/\/ branch factor for it, and we should restore it\n\tif (o->flags & observer::flag_short_timeout)\n\t\t--m_branch_factor;\n\n\to->flags |= observer::flag_alive;\n\n\t++m_responses;\n\t--m_invoke_count;\n\tTORRENT_ASSERT(m_invoke_count >= 0);\n\tadd_requests();\n\tif (m_invoke_count == 0) done();\n}\n\n\/\/ prevent request means that the total number of requests has\n\/\/ overflown. This query failed because it was the oldest one.\n\/\/ So, if this is true, don't make another request\nvoid traversal_algorithm::failed(observer_ptr o, int flags)\n{\n\tTORRENT_ASSERT(m_invoke_count >= 0);\n\n\tif (m_results.empty()) return;\n\n\tTORRENT_ASSERT(o->flags & observer::flag_queried);\n\tif (flags & short_timeout)\n\t{\n\t\t\/\/ short timeout means that it has been more than\n\t\t\/\/ two seconds since we sent the request, and that\n\t\t\/\/ we'll most likely not get a response. But, in case\n\t\t\/\/ we do get a late response, keep the handler\n\t\t\/\/ around for some more, but open up the slot\n\t\t\/\/ by increasing the branch factor\n\t\tif ((o->flags & observer::flag_short_timeout) == 0)\n\t\t\t++m_branch_factor;\n\t\to->flags |= observer::flag_short_timeout;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"] first chance timeout: \"\n\t\t\t<< o->id() << \" \" << o->target_ep()\n\t\t\t<< \" branch-factor: \" << m_branch_factor\n\t\t\t<< \" invoke-count: \" << m_invoke_count;\n#endif\n\t}\n\telse\n\t{\n\t\to->flags |= observer::flag_failed;\n\t\t\/\/ if this flag is set, it means we increased the\n\t\t\/\/ branch factor for it, and we should restore it\n\t\tif (o->flags & observer::flag_short_timeout)\n\t\t\t--m_branch_factor;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"] failed: \"\n\t\t\t<< o->id() << \" \" << o->target_ep()\n\t\t\t<< \" branch-factor: \" << m_branch_factor\n\t\t\t<< \" invoke-count: \" << m_invoke_count;\n#endif\n\t\t\/\/ don't tell the routing table about\n\t\t\/\/ node ids that we just generated ourself\n\t\tif ((o->flags & observer::flag_no_id) == 0)\n\t\t\tm_node.m_table.node_failed(o->id());\n\t\t++m_timeouts;\n\t\t--m_invoke_count;\n\t\tTORRENT_ASSERT(m_invoke_count >= 0);\n\t}\n\n\tif (flags & prevent_request)\n\t{\n\t\t--m_branch_factor;\n\t\tif (m_branch_factor <= 0) m_branch_factor = 1;\n\t}\n\tadd_requests();\n\tif (m_invoke_count == 0) done();\n}\n\nvoid traversal_algorithm::done()\n{\n\t\/\/ delete all our references to the observer objects so\n\t\/\/ they will in turn release the traversal algorithm\n\tm_results.clear();\n}\n\nnamespace\n{\n\tbool bitwise_nand(unsigned char lhs, unsigned char rhs)\n\t{\n\t\treturn (lhs & rhs) == 0;\n\t}\n}\n\nvoid traversal_algorithm::add_requests()\n{\n\tint results_target = m_node.m_table.bucket_size();\n\n\t\/\/ Find the first node that hasn't already been queried.\n\tfor (std::vector<observer_ptr>::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end\n\t\t&& results_target > 0 && m_invoke_count < m_branch_factor; ++i)\n\t{\n\t\tif ((*i)->flags & observer::flag_alive) --results_target;\n\t\tif ((*i)->flags & observer::flag_queried) continue;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(traversal) << \" [\" << this << \"]\"\n\t\t\t<< \" nodes-left: \" << (m_results.end() - i)\n\t\t\t<< \" invoke-count: \" << m_invoke_count\n\t\t\t<< \" branch-factor: \" << m_branch_factor;\n#endif\n\n\t\tif (invoke(*i))\n\t\t{\n\t\t\tTORRENT_ASSERT(m_invoke_count >= 0);\n\t\t\t++m_invoke_count;\n\t\t\t(*i)->flags |= observer::flag_queried;\n\t\t}\n\t}\n}\n\nvoid traversal_algorithm::add_router_entries()\n{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(traversal) << \" using router nodes to initiate traversal algorithm. \"\n\t\t<< std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << \" routers\";\n#endif\n\tfor (routing_table::router_iterator i = m_node.m_table.router_begin()\n\t\t, end(m_node.m_table.router_end()); i != end; ++i)\n\t{\n\t\tadd_entry(node_id(0), *i, observer::flag_initial);\n\t}\n}\n\nvoid traversal_algorithm::init()\n{\n\t\/\/ update the last activity of this bucket\n\tm_node.m_table.touch_bucket(m_target);\n\tm_branch_factor = m_node.branch_factor();\n\tm_node.add_traversal_algorithm(this);\n}\n\ntraversal_algorithm::~traversal_algorithm()\n{\n\tm_node.remove_traversal_algorithm(this);\n}\n\nvoid traversal_algorithm::status(dht_lookup& l)\n{\n\tl.timeouts = m_timeouts;\n\tl.responses = m_responses;\n\tl.outstanding_requests = m_invoke_count;\n\tl.branch_factor = m_branch_factor;\n\tl.type = name();\n\tl.nodes_left = 0;\n\tfor (std::vector<observer_ptr>::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end; ++i)\n\t{\n\t\tif ((*i)->flags & observer::flag_queried) continue;\n\t\t++l.nodes_left;\n\t}\n}\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"} {"text":"<commit_before>#include <bitcoin\/consensus\/libethash\/internal.h>\n#include <bitcoin\/consensus\/libdevcore\/Guards.h>\n#include <bitcoin\/consensus\/libdevcore\/Log.h>\n#include <bitcoin\/consensus\/libdevcore\/SHA3.h>\n#include <bitcoin\/bitcoin\/chain\/header.hpp>\n#include <boost\/detail\/endian.hpp>\n#include <boost\/filesystem.hpp>\n#include <chrono>\n#include <array>\n#include <thread>\n#include <bitcoin\/consensus\/miner\/MinerAux.h>\n\n\nusing namespace dev;\nusing namespace std;\n\nMinerAux* dev::MinerAux::s_this = nullptr;\n\nMinerAux::~MinerAux()\n{\n}\n\nMinerAux* MinerAux::get()\n{\n static std::once_flag flag;\n std::call_once(flag, []{s_this = new MinerAux();});\n return s_this;\n}\n\n\nLightType MinerAux::get_light(h256& _seedHash)\n{\n\tUpgradableGuard l(get()->x_lights);\n\tif (get()->m_lights.count(_seedHash))\n\t\treturn get()->m_lights.at(_seedHash);\n\tUpgradeGuard l2(l);\n\treturn (get()->m_lights[_seedHash] = make_shared<LightAllocation>(_seedHash));\n}\n\n\/\/static std::function<int(unsigned)> s_dagCallback;\n\nstatic int dagCallbackShim(unsigned _p)\n{\n\treturn 0;\n}\nFullType MinerAux::get_full(h256& _seedHash)\n{\n\tFullType ret;\n\tauto l = get_light(_seedHash);\n\tDEV_GUARDED(get()->x_fulls)\n\tif ((ret = get()->m_fulls[_seedHash].lock()))\n\t{\n\t\t\/\/get()->m_lastUsedFull = ret;\n\t\treturn ret;\n\t}\n\t\/\/s_dagCallback = _f;\n\tret = make_shared<FullAllocation>(l->light, dagCallbackShim);\n\tDEV_GUARDED(get()->x_fulls)\n\tget()->m_fulls[_seedHash] = ret;\n\treturn ret;\n}\n\nethash_return_value_t MinerAux::search(libbitcoin::chain::header& header, std::function<bool (void)> is_exit)\n{\n\tauto tid = std::this_thread::get_id();\n\tstatic std::mt19937_64 s_eng((utcTime() + std::hash<decltype(tid)>()(tid)));\n\tuint64_t tryNonce = s_eng();\n\tethash_return_value ethashReturn;\n\tFullType dag;\n\tunsigned hashCount = 1;\n\th256 seed = HeaderAux::seedHash(header);\n\th256 header_hash = HeaderAux::hashHead(header);\n\th256 boundary = HeaderAux::boundary(header);\n\n\tdag = get_full(seed);\n\n\n\n\tfor (; ; tryNonce++, hashCount++)\n\t{\n\t\tethashReturn = ethash_full_compute(dag->full, *(ethash_h256_t*)header_hash.data(), tryNonce);\n\t\th256 value = h256((uint8_t*)ðashReturn.result, h256::ConstructFromPointer);\n\t\tif (value <= boundary )\n\t\t\tbreak;\n\t\tif(is_exit() == true)\n\t\t{\n\t\t\tethashReturn.success = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn ethashReturn;\n}\n\nbool MinerAux::verifySeal(libbitcoin::chain::header& _header)\n{\n\tdev::Result result;\n\th256 seedHash = HeaderAux::seedHash(_header);\n\th256 headerHash = HeaderAux::hashHead(_header);\n\tNonce nonce = _header.getNonce();\n\tDEV_GUARDED(get()->x_fulls)\n\tif (FullType dag = get()->m_fulls[seedHash].lock())\n\t{\n\t\tresult = dag->compute(headerHash, nonce);\n\t\treturn ( result.value <= dev::HeaderAux::boundary(_header) && result.mixHash == _header.getMixhash() );\n\t}\n\tresult = get()->get_light(seedHash)->compute(headerHash, nonce);\n\treturn ( result.value <= dev::HeaderAux::boundary(_header) && result.mixHash == _header.getMixhash() );\n}\n\n\n\n\n\n\n<commit_msg>rm consensus\/miner\/MinerAux.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"gpu\/command_buffer\/service\/texture_manager.h\"\n#include \"base\/bits.h\"\n\nnamespace gpu {\nnamespace gles2 {\n\nstatic GLsizei ComputeMipMapCount(\n GLsizei width, GLsizei height, GLsizei depth) {\n return 1 + base::bits::Log2Floor(std::max(std::max(width, height), depth));\n}\n\nstatic size_t GLTargetToFaceIndex(GLenum target) {\n switch (target) {\n case GL_TEXTURE_2D:\n return 0;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_X:\n return 0;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:\n return 1;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:\n return 2;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:\n return 3;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:\n return 4;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:\n return 5;\n default:\n NOTREACHED();\n return 0;\n }\n}\n\nstatic size_t FaceIndexToGLTarget(size_t index) {\n switch (index) {\n case 0:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_X;\n case 1:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;\n case 2:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;\n case 3:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;\n case 4:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;\n case 5:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;\n default:\n NOTREACHED();\n return 0;\n }\n}\n\nvoid TextureManager::TextureInfo::MarkMipmapsGenerated() {\n DCHECK(CanGenerateMipmaps());\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const TextureInfo::LevelInfo& info1 = level_infos_[ii][0];\n GLsizei width = info1.width;\n GLsizei height = info1.height;\n GLsizei depth = info1.depth;\n int num_mips = ComputeMipMapCount(width, height, depth);\n for (int level = 1; level < num_mips; ++level) {\n width = std::max(1, width >> 1);\n height = std::max(1, height >> 1);\n depth = std::max(1, depth >> 1);\n SetLevelInfo(target_ == GL_TEXTURE_2D ? GL_TEXTURE_2D :\n FaceIndexToGLTarget(ii),\n level,\n info1.internal_format,\n width,\n height,\n depth,\n info1.border,\n info1.format,\n info1.type);\n }\n }\n}\n\nbool TextureManager::TextureInfo::CanGenerateMipmaps() const {\n if (npot()) {\n return false;\n }\n const TextureInfo::LevelInfo& first = level_infos_[0][0];\n \/\/ TODO(gman): Check internal_format, format and type.\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const LevelInfo& info = level_infos_[ii][0];\n if (!info.valid ||\n info.width != first.width &&\n info.height != first.height &&\n info.depth != 1 &&\n info.format != first.format &&\n info.internal_format != first.internal_format &&\n info.type != first.type) {\n return false;\n }\n }\n return true;\n}\n\nvoid TextureManager::TextureInfo::SetLevelInfo(\n GLenum target,\n GLint level,\n GLint internal_format,\n GLsizei width,\n GLsizei height,\n GLsizei depth,\n GLint border,\n GLenum format,\n GLenum type) {\n DCHECK_GE(level, 0);\n DCHECK_LT(static_cast<size_t>(GLTargetToFaceIndex(target)),\n level_infos_.size());\n DCHECK_LT(static_cast<size_t>(level),\n level_infos_[GLTargetToFaceIndex(target)].size());\n DCHECK_GE(width, 0);\n DCHECK_GE(height, 0);\n DCHECK_GE(depth, 0);\n TextureInfo::LevelInfo& info =\n level_infos_[GLTargetToFaceIndex(target)][level];\n info.valid = true;\n info.internal_format = internal_format;\n info.width = width;\n info.height = height;\n info.depth = depth;\n info.border = border;\n info.format = format;\n info.type = type;\n max_level_set_ = std::max(max_level_set_, level);\n Update();\n}\n\nvoid TextureManager::TextureInfo::Update() {\n \/\/ Update npot status.\n npot_ = false;\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const TextureInfo::LevelInfo& info = level_infos_[ii][0];\n if (((info.width & (info.width - 1)) != 0) ||\n ((info.height & (info.height - 1)) != 0) ||\n ((info.depth & (info.depth - 1)) != 0)) {\n npot_ = true;\n break;\n }\n }\n\n \/\/ Update texture_complete status.\n const TextureInfo::LevelInfo& first_face = level_infos_[0][0];\n texture_complete_ =\n (max_level_set_ == ComputeMipMapCount(first_face.width,\n first_face.height,\n first_face.depth) - 1) &&\n max_level_set_ >= 0;\n cube_complete_ = (level_infos_.size() == 6) &&\n (first_face.width == first_face.height);\n for (size_t ii = 0;\n ii < level_infos_.size() && cube_complete_ && texture_complete_;\n ++ii) {\n const TextureInfo::LevelInfo& level0 = level_infos_[ii][0];\n if (!level0.valid ||\n level0.width != first_face.width ||\n level0.height != first_face.height ||\n level0.depth != 1 ||\n level0.internal_format != first_face.internal_format ||\n level0.format != first_face.format ||\n level0.type != first_face.type) {\n cube_complete_ = false;\n }\n \/\/ Get level0 dimensions\n GLsizei width = level0.width;\n GLsizei height = level0.height;\n GLsizei depth = level0.depth;\n for (GLint jj = 0; jj <= max_level_set_; ++jj) {\n \/\/ compute required size for mip.\n width = std::max(1, width >> 1);\n height = std::max(1, height >> 1);\n depth = std::max(1, depth >> 1);\n const TextureInfo::LevelInfo& info = level_infos_[ii][jj];\n if (!info.valid ||\n info.width != width ||\n info.height != height ||\n info.depth != depth ||\n info.internal_format != level0.internal_format ||\n info.format != level0.format ||\n info.type != level0.type) {\n texture_complete_ = false;\n break;\n }\n }\n }\n}\n\nTextureManager::TextureManager(\n GLint max_texture_size, GLint max_cube_map_texture_size)\n : max_texture_size_(max_texture_size),\n max_cube_map_texture_size_(max_cube_map_texture_size),\n max_levels_(ComputeMipMapCount(max_texture_size,\n max_texture_size,\n max_texture_size)),\n max_cube_map_levels_(ComputeMipMapCount(max_cube_map_texture_size,\n max_cube_map_texture_size,\n max_cube_map_texture_size)) {\n}\n\nvoid TextureManager::CreateTextureInfo(GLuint texture) {\n TextureInfo* info = new TextureInfo(texture);\n std::pair<TextureInfoMap::iterator, bool> result =\n texture_infos_.insert(\n std::make_pair(texture, linked_ptr<TextureInfo>(info)));\n DCHECK(result.second);\n}\n\nTextureManager::TextureInfo* TextureManager::GetTextureInfo(\n GLuint texture) {\n TextureInfoMap::iterator it = texture_infos_.find(texture);\n return it != texture_infos_.end() ? &(*it->second) : NULL;\n}\n\nvoid TextureManager::RemoveTextureInfo(GLuint texture_id) {\n texture_infos_.erase(texture_id);\n}\n\n} \/\/ namespace gles2\n} \/\/ namespace gpu\n\n\n<commit_msg>Fix for build breakage<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"gpu\/command_buffer\/service\/texture_manager.h\"\n#include \"base\/bits.h\"\n\nnamespace gpu {\nnamespace gles2 {\n\nstatic GLsizei ComputeMipMapCount(\n GLsizei width, GLsizei height, GLsizei depth) {\n return 1 + base::bits::Log2Floor(std::max(std::max(width, height), depth));\n}\n\nstatic size_t GLTargetToFaceIndex(GLenum target) {\n switch (target) {\n case GL_TEXTURE_2D:\n return 0;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_X:\n return 0;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:\n return 1;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:\n return 2;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:\n return 3;\n case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:\n return 4;\n case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:\n return 5;\n default:\n NOTREACHED();\n return 0;\n }\n}\n\nstatic size_t FaceIndexToGLTarget(size_t index) {\n switch (index) {\n case 0:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_X;\n case 1:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;\n case 2:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;\n case 3:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;\n case 4:\n return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;\n case 5:\n return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;\n default:\n NOTREACHED();\n return 0;\n }\n}\n\nvoid TextureManager::TextureInfo::MarkMipmapsGenerated() {\n DCHECK(CanGenerateMipmaps());\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const TextureInfo::LevelInfo& info1 = level_infos_[ii][0];\n GLsizei width = info1.width;\n GLsizei height = info1.height;\n GLsizei depth = info1.depth;\n int num_mips = ComputeMipMapCount(width, height, depth);\n for (int level = 1; level < num_mips; ++level) {\n width = std::max(1, width >> 1);\n height = std::max(1, height >> 1);\n depth = std::max(1, depth >> 1);\n SetLevelInfo(target_ == GL_TEXTURE_2D ? GL_TEXTURE_2D :\n FaceIndexToGLTarget(ii),\n level,\n info1.internal_format,\n width,\n height,\n depth,\n info1.border,\n info1.format,\n info1.type);\n }\n }\n}\n\nbool TextureManager::TextureInfo::CanGenerateMipmaps() const {\n if (npot()) {\n return false;\n }\n const TextureInfo::LevelInfo& first = level_infos_[0][0];\n \/\/ TODO(gman): Check internal_format, format and type.\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const LevelInfo& info = level_infos_[ii][0];\n if ((!info.valid) ||\n (info.width != first.width) ||\n (info.height != first.height) ||\n (info.depth != 1) ||\n (info.format != first.format) ||\n (info.internal_format != first.internal_format) ||\n (info.type != first.type)) {\n return false;\n }\n }\n return true;\n}\n\nvoid TextureManager::TextureInfo::SetLevelInfo(\n GLenum target,\n GLint level,\n GLint internal_format,\n GLsizei width,\n GLsizei height,\n GLsizei depth,\n GLint border,\n GLenum format,\n GLenum type) {\n DCHECK_GE(level, 0);\n DCHECK_LT(static_cast<size_t>(GLTargetToFaceIndex(target)),\n level_infos_.size());\n DCHECK_LT(static_cast<size_t>(level),\n level_infos_[GLTargetToFaceIndex(target)].size());\n DCHECK_GE(width, 0);\n DCHECK_GE(height, 0);\n DCHECK_GE(depth, 0);\n TextureInfo::LevelInfo& info =\n level_infos_[GLTargetToFaceIndex(target)][level];\n info.valid = true;\n info.internal_format = internal_format;\n info.width = width;\n info.height = height;\n info.depth = depth;\n info.border = border;\n info.format = format;\n info.type = type;\n max_level_set_ = std::max(max_level_set_, level);\n Update();\n}\n\nvoid TextureManager::TextureInfo::Update() {\n \/\/ Update npot status.\n npot_ = false;\n for (size_t ii = 0; ii < level_infos_.size(); ++ii) {\n const TextureInfo::LevelInfo& info = level_infos_[ii][0];\n if (((info.width & (info.width - 1)) != 0) ||\n ((info.height & (info.height - 1)) != 0) ||\n ((info.depth & (info.depth - 1)) != 0)) {\n npot_ = true;\n break;\n }\n }\n\n \/\/ Update texture_complete status.\n const TextureInfo::LevelInfo& first_face = level_infos_[0][0];\n texture_complete_ =\n (max_level_set_ == ComputeMipMapCount(first_face.width,\n first_face.height,\n first_face.depth) - 1) &&\n max_level_set_ >= 0;\n cube_complete_ = (level_infos_.size() == 6) &&\n (first_face.width == first_face.height);\n for (size_t ii = 0;\n ii < level_infos_.size() && cube_complete_ && texture_complete_;\n ++ii) {\n const TextureInfo::LevelInfo& level0 = level_infos_[ii][0];\n if (!level0.valid ||\n level0.width != first_face.width ||\n level0.height != first_face.height ||\n level0.depth != 1 ||\n level0.internal_format != first_face.internal_format ||\n level0.format != first_face.format ||\n level0.type != first_face.type) {\n cube_complete_ = false;\n }\n \/\/ Get level0 dimensions\n GLsizei width = level0.width;\n GLsizei height = level0.height;\n GLsizei depth = level0.depth;\n for (GLint jj = 0; jj <= max_level_set_; ++jj) {\n \/\/ compute required size for mip.\n width = std::max(1, width >> 1);\n height = std::max(1, height >> 1);\n depth = std::max(1, depth >> 1);\n const TextureInfo::LevelInfo& info = level_infos_[ii][jj];\n if (!info.valid ||\n info.width != width ||\n info.height != height ||\n info.depth != depth ||\n info.internal_format != level0.internal_format ||\n info.format != level0.format ||\n info.type != level0.type) {\n texture_complete_ = false;\n break;\n }\n }\n }\n}\n\nTextureManager::TextureManager(\n GLint max_texture_size, GLint max_cube_map_texture_size)\n : max_texture_size_(max_texture_size),\n max_cube_map_texture_size_(max_cube_map_texture_size),\n max_levels_(ComputeMipMapCount(max_texture_size,\n max_texture_size,\n max_texture_size)),\n max_cube_map_levels_(ComputeMipMapCount(max_cube_map_texture_size,\n max_cube_map_texture_size,\n max_cube_map_texture_size)) {\n}\n\nvoid TextureManager::CreateTextureInfo(GLuint texture) {\n TextureInfo* info = new TextureInfo(texture);\n std::pair<TextureInfoMap::iterator, bool> result =\n texture_infos_.insert(\n std::make_pair(texture, linked_ptr<TextureInfo>(info)));\n DCHECK(result.second);\n}\n\nTextureManager::TextureInfo* TextureManager::GetTextureInfo(\n GLuint texture) {\n TextureInfoMap::iterator it = texture_infos_.find(texture);\n return it != texture_infos_.end() ? &(*it->second) : NULL;\n}\n\nvoid TextureManager::RemoveTextureInfo(GLuint texture_id) {\n texture_infos_.erase(texture_id);\n}\n\n} \/\/ namespace gles2\n} \/\/ namespace gpu\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/tabbed_pane\/native_tabbed_pane_win.h\"\n\n#include <vssym32.h>\n\n#include \"app\/gfx\/canvas.h\"\n#include \"app\/gfx\/font.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/gfx\/native_theme.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"views\/fill_layout.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n\nnamespace views {\n\n\/\/ A background object that paints the tab panel background which may be\n\/\/ rendered by the system visual styles system.\nclass TabBackground : public Background {\n public:\n explicit TabBackground() {\n \/\/ TMT_FILLCOLORHINT returns a color value that supposedly\n \/\/ approximates the texture drawn by PaintTabPanelBackground.\n SkColor tab_page_color =\n gfx::NativeTheme::instance()->GetThemeColorWithDefault(\n gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,\n COLOR_3DFACE);\n SetNativeControlColor(tab_page_color);\n }\n virtual ~TabBackground() {}\n\n virtual void Paint(gfx::Canvas* canvas, View* view) const {\n HDC dc = canvas->beginPlatformPaint();\n RECT r = {0, 0, view->width(), view->height()};\n gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);\n canvas->endPlatformPaint();\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(TabBackground);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, public:\n\nNativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)\n : NativeControlWin(),\n tabbed_pane_(tabbed_pane),\n content_window_(NULL),\n selected_index_(-1) {\n \/\/ Associates the actual HWND with the tabbed-pane so the tabbed-pane is\n \/\/ the one considered as having the focus (not the wrapper) when the HWND is\n \/\/ focused directly (with a click for example).\n set_focus_view(tabbed_pane);\n}\n\nNativeTabbedPaneWin::~NativeTabbedPaneWin() {\n \/\/ We own the tab views, let's delete them.\n STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:\n\nvoid NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {\n AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true);\n}\n\nvoid NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,\n View* contents,\n bool select_if_first_tab) {\n DCHECK(index <= static_cast<int>(tab_views_.size()));\n contents->SetParentOwned(false);\n tab_views_.insert(tab_views_.begin() + index, contents);\n tab_titles_.insert(tab_titles_.begin() + index, title);\n\n if (!contents->background())\n contents->set_background(new TabBackground);\n\n if (tab_views_.size() == 1 && select_if_first_tab) {\n \/\/ If this is the only tab displayed, make sure the contents is set.\n selected_index_ = 0;\n if (content_window_)\n content_window_->GetRootView()->AddChildView(contents);\n }\n\n \/\/ Add native tab only if the native control is alreay created.\n if (content_window_) {\n AddNativeTab(index, title, contents);\n\n \/\/ The newly added tab may have made the contents window smaller.\n ResizeContents();\n }\n}\n\nvoid NativeTabbedPaneWin::AddNativeTab(int index,\n const std::wstring &title,\n views::View* contents) {\n TCITEM tcitem;\n tcitem.mask = TCIF_TEXT;\n\n \/\/ If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is\n \/\/ rendered properly on the tabs.\n if (UILayoutIsRightToLeft()) {\n tcitem.mask |= TCIF_RTLREADING;\n }\n\n tcitem.pszText = const_cast<wchar_t*>(title.c_str());\n int result = TabCtrl_InsertItem(native_view(), index, &tcitem);\n DCHECK(result != -1);\n}\n\nView* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {\n int tab_count = static_cast<int>(tab_views_.size());\n DCHECK(index >= 0 && index < tab_count);\n\n if (index < (tab_count - 1)) {\n \/\/ Select the next tab.\n SelectTabAt(index + 1);\n } else {\n \/\/ We are the last tab, select the previous one.\n if (index > 0) {\n SelectTabAt(index - 1);\n } else if (content_window_) {\n \/\/ That was the last tab. Remove the contents.\n content_window_->GetRootView()->RemoveAllChildViews(false);\n }\n }\n TabCtrl_DeleteItem(native_view(), index);\n\n \/\/ The removed tab may have made the contents window bigger.\n ResizeContents();\n\n std::vector<View*>::iterator iter = tab_views_.begin() + index;\n View* removed_tab = *iter;\n tab_views_.erase(iter);\n tab_titles_.erase(tab_titles_.begin() + index);\n\n return removed_tab;\n}\n\nvoid NativeTabbedPaneWin::SelectTabAt(int index) {\n DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size())));\n if (native_view())\n TabCtrl_SetCurSel(native_view(), index);\n DoSelectTabAt(index, true);\n}\n\nint NativeTabbedPaneWin::GetTabCount() {\n return TabCtrl_GetItemCount(native_view());\n}\n\nint NativeTabbedPaneWin::GetSelectedTabIndex() {\n return TabCtrl_GetCurSel(native_view());\n}\n\nView* NativeTabbedPaneWin::GetSelectedTab() {\n if (selected_index_ < 0)\n return NULL;\n return tab_views_[selected_index_];\n}\n\nView* NativeTabbedPaneWin::GetView() {\n return this;\n}\n\nvoid NativeTabbedPaneWin::SetFocus() {\n \/\/ Focus the associated HWND.\n Focus();\n}\n\ngfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {\n return native_view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeControlWin override:\n\nvoid NativeTabbedPaneWin::CreateNativeControl() {\n \/\/ Create the tab control.\n \/\/\n \/\/ Note that we don't follow the common convention for NativeControl\n \/\/ subclasses and we don't pass the value returned from\n \/\/ NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is\n \/\/ why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when\n \/\/ we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If\n \/\/ we do that, then the HWND we create for |content_window_| below will\n \/\/ inherit the WS_EX_LAYOUTRTL property and this will result in the contents\n \/\/ being flipped, which is not what we want (because we handle mirroring in\n \/\/ views without the use of Windows' support for mirroring). Therefore,\n \/\/ we initially create our HWND without the aforementioned property and we\n \/\/ explicitly set this property our child is created. This way, on RTL\n \/\/ locales, our tabs will be nicely rendered from right to left (by virtue of\n \/\/ Windows doing the right thing with the TabbedPane HWND) and each tab\n \/\/ contents will use an RTL layout correctly (by virtue of the mirroring\n \/\/ infrastructure in views doing the right thing with each View we put\n \/\/ in the tab).\n HWND tab_control = ::CreateWindowEx(0,\n WC_TABCONTROL,\n L\"\",\n WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,\n 0, 0, width(), height(),\n GetWidget()->GetNativeView(), NULL, NULL,\n NULL);\n\n HFONT font = ResourceBundle::GetSharedInstance().\n GetFont(ResourceBundle::BaseFont).hfont();\n SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);\n\n \/\/ Create the view container which is a child of the TabControl.\n content_window_ = new WidgetWin();\n content_window_->Init(tab_control, gfx::Rect());\n\n \/\/ Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above\n \/\/ for a thorough explanation regarding why we waited until |content_window_|\n \/\/ if created before we set this property for the tabbed pane's HWND).\n if (UILayoutIsRightToLeft())\n l10n_util::HWNDSetRTLLayout(tab_control);\n\n RootView* root_view = content_window_->GetRootView();\n root_view->SetLayoutManager(new FillLayout());\n DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);\n SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),\n GetBValue(sys_color));\n root_view->set_background(Background::CreateSolidBackground(color));\n\n content_window_->SetFocusTraversableParentView(this);\n\n NativeControlCreated(tab_control);\n\n \/\/ Add tabs that are already added if any.\n if (tab_views_.size() > 0) {\n InitializeTabs();\n if (selected_index_ >= 0)\n DoSelectTabAt(selected_index_, false);\n }\n\n ResizeContents();\n}\n\nbool NativeTabbedPaneWin::ProcessMessage(UINT message,\n WPARAM w_param,\n LPARAM l_param,\n LRESULT* result) {\n if (message == WM_NOTIFY &&\n reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) {\n int selected_tab = TabCtrl_GetCurSel(native_view());\n DCHECK(selected_tab != -1);\n DoSelectTabAt(selected_tab, true);\n return TRUE;\n }\n return NativeControlWin::ProcessMessage(message, w_param, l_param, result);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ View override:\n\nvoid NativeTabbedPaneWin::Layout() {\n NativeControlWin::Layout();\n ResizeContents();\n}\n\nFocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {\n return content_window_;\n}\n\nvoid NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,\n View *parent,\n View *child) {\n NativeControlWin::ViewHierarchyChanged(is_add, parent, child);\n\n if (is_add && (child == this) && content_window_) {\n \/\/ We have been added to a view hierarchy, update the FocusTraversable\n \/\/ parent.\n content_window_->SetFocusTraversableParent(GetRootView());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, private:\n\nvoid NativeTabbedPaneWin::InitializeTabs() {\n for (size_t i = 0; i < tab_views_.size(); ++i) {\n AddNativeTab(i, tab_titles_[i], tab_views_[i]);\n }\n}\n\nvoid NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {\n selected_index_ = index;\n if (content_window_) {\n RootView* content_root = content_window_->GetRootView();\n\n \/\/ Clear the focus if the focused view was on the tab.\n FocusManager* focus_manager = GetFocusManager();\n DCHECK(focus_manager);\n View* focused_view = focus_manager->GetFocusedView();\n if (focused_view && content_root->IsParentOf(focused_view))\n focus_manager->ClearFocus();\n\n content_root->RemoveAllChildViews(false);\n content_root->AddChildView(tab_views_[index]);\n content_root->Layout();\n }\n if (invoke_listener && tabbed_pane_->listener())\n tabbed_pane_->listener()->TabSelectedAt(index);\n}\n\nvoid NativeTabbedPaneWin::ResizeContents() {\n CRect content_bounds;\n if (!GetClientRect(native_view(), &content_bounds))\n return;\n TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);\n content_window_->MoveWindow(content_bounds.left, content_bounds.top,\n content_bounds.Width(), content_bounds.Height(),\n TRUE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWrapper, public:\n\n\/\/ static\nNativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(\n TabbedPane* tabbed_pane) {\n return new NativeTabbedPaneWin(tabbed_pane);\n}\n\n} \/\/ namespace views\n<commit_msg>Fix possible null pointer dereference.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/tabbed_pane\/native_tabbed_pane_win.h\"\n\n#include <vssym32.h>\n\n#include \"app\/gfx\/canvas.h\"\n#include \"app\/gfx\/font.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/gfx\/native_theme.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"views\/controls\/tabbed_pane\/tabbed_pane.h\"\n#include \"views\/fill_layout.h\"\n#include \"views\/widget\/root_view.h\"\n#include \"views\/widget\/widget_win.h\"\n\nnamespace views {\n\n\/\/ A background object that paints the tab panel background which may be\n\/\/ rendered by the system visual styles system.\nclass TabBackground : public Background {\n public:\n explicit TabBackground() {\n \/\/ TMT_FILLCOLORHINT returns a color value that supposedly\n \/\/ approximates the texture drawn by PaintTabPanelBackground.\n SkColor tab_page_color =\n gfx::NativeTheme::instance()->GetThemeColorWithDefault(\n gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,\n COLOR_3DFACE);\n SetNativeControlColor(tab_page_color);\n }\n virtual ~TabBackground() {}\n\n virtual void Paint(gfx::Canvas* canvas, View* view) const {\n HDC dc = canvas->beginPlatformPaint();\n RECT r = {0, 0, view->width(), view->height()};\n gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r);\n canvas->endPlatformPaint();\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(TabBackground);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, public:\n\nNativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)\n : NativeControlWin(),\n tabbed_pane_(tabbed_pane),\n content_window_(NULL),\n selected_index_(-1) {\n \/\/ Associates the actual HWND with the tabbed-pane so the tabbed-pane is\n \/\/ the one considered as having the focus (not the wrapper) when the HWND is\n \/\/ focused directly (with a click for example).\n set_focus_view(tabbed_pane);\n}\n\nNativeTabbedPaneWin::~NativeTabbedPaneWin() {\n \/\/ We own the tab views, let's delete them.\n STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:\n\nvoid NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) {\n AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true);\n}\n\nvoid NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title,\n View* contents,\n bool select_if_first_tab) {\n DCHECK(index <= static_cast<int>(tab_views_.size()));\n contents->SetParentOwned(false);\n tab_views_.insert(tab_views_.begin() + index, contents);\n tab_titles_.insert(tab_titles_.begin() + index, title);\n\n if (!contents->background())\n contents->set_background(new TabBackground);\n\n if (tab_views_.size() == 1 && select_if_first_tab) {\n \/\/ If this is the only tab displayed, make sure the contents is set.\n selected_index_ = 0;\n if (content_window_)\n content_window_->GetRootView()->AddChildView(contents);\n }\n\n \/\/ Add native tab only if the native control is alreay created.\n if (content_window_) {\n AddNativeTab(index, title, contents);\n\n \/\/ The newly added tab may have made the contents window smaller.\n ResizeContents();\n }\n}\n\nvoid NativeTabbedPaneWin::AddNativeTab(int index,\n const std::wstring &title,\n views::View* contents) {\n TCITEM tcitem;\n tcitem.mask = TCIF_TEXT;\n\n \/\/ If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is\n \/\/ rendered properly on the tabs.\n if (UILayoutIsRightToLeft()) {\n tcitem.mask |= TCIF_RTLREADING;\n }\n\n tcitem.pszText = const_cast<wchar_t*>(title.c_str());\n int result = TabCtrl_InsertItem(native_view(), index, &tcitem);\n DCHECK(result != -1);\n}\n\nView* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {\n int tab_count = static_cast<int>(tab_views_.size());\n DCHECK(index >= 0 && index < tab_count);\n\n if (index < (tab_count - 1)) {\n \/\/ Select the next tab.\n SelectTabAt(index + 1);\n } else {\n \/\/ We are the last tab, select the previous one.\n if (index > 0) {\n SelectTabAt(index - 1);\n } else if (content_window_) {\n \/\/ That was the last tab. Remove the contents.\n content_window_->GetRootView()->RemoveAllChildViews(false);\n }\n }\n TabCtrl_DeleteItem(native_view(), index);\n\n \/\/ The removed tab may have made the contents window bigger.\n if (content_window_)\n ResizeContents();\n\n std::vector<View*>::iterator iter = tab_views_.begin() + index;\n View* removed_tab = *iter;\n tab_views_.erase(iter);\n tab_titles_.erase(tab_titles_.begin() + index);\n\n return removed_tab;\n}\n\nvoid NativeTabbedPaneWin::SelectTabAt(int index) {\n DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size())));\n if (native_view())\n TabCtrl_SetCurSel(native_view(), index);\n DoSelectTabAt(index, true);\n}\n\nint NativeTabbedPaneWin::GetTabCount() {\n return TabCtrl_GetItemCount(native_view());\n}\n\nint NativeTabbedPaneWin::GetSelectedTabIndex() {\n return TabCtrl_GetCurSel(native_view());\n}\n\nView* NativeTabbedPaneWin::GetSelectedTab() {\n if (selected_index_ < 0)\n return NULL;\n return tab_views_[selected_index_];\n}\n\nView* NativeTabbedPaneWin::GetView() {\n return this;\n}\n\nvoid NativeTabbedPaneWin::SetFocus() {\n \/\/ Focus the associated HWND.\n Focus();\n}\n\ngfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {\n return native_view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, NativeControlWin override:\n\nvoid NativeTabbedPaneWin::CreateNativeControl() {\n \/\/ Create the tab control.\n \/\/\n \/\/ Note that we don't follow the common convention for NativeControl\n \/\/ subclasses and we don't pass the value returned from\n \/\/ NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is\n \/\/ why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when\n \/\/ we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If\n \/\/ we do that, then the HWND we create for |content_window_| below will\n \/\/ inherit the WS_EX_LAYOUTRTL property and this will result in the contents\n \/\/ being flipped, which is not what we want (because we handle mirroring in\n \/\/ views without the use of Windows' support for mirroring). Therefore,\n \/\/ we initially create our HWND without the aforementioned property and we\n \/\/ explicitly set this property our child is created. This way, on RTL\n \/\/ locales, our tabs will be nicely rendered from right to left (by virtue of\n \/\/ Windows doing the right thing with the TabbedPane HWND) and each tab\n \/\/ contents will use an RTL layout correctly (by virtue of the mirroring\n \/\/ infrastructure in views doing the right thing with each View we put\n \/\/ in the tab).\n HWND tab_control = ::CreateWindowEx(0,\n WC_TABCONTROL,\n L\"\",\n WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,\n 0, 0, width(), height(),\n GetWidget()->GetNativeView(), NULL, NULL,\n NULL);\n\n HFONT font = ResourceBundle::GetSharedInstance().\n GetFont(ResourceBundle::BaseFont).hfont();\n SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);\n\n \/\/ Create the view container which is a child of the TabControl.\n content_window_ = new WidgetWin();\n content_window_->Init(tab_control, gfx::Rect());\n\n \/\/ Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above\n \/\/ for a thorough explanation regarding why we waited until |content_window_|\n \/\/ if created before we set this property for the tabbed pane's HWND).\n if (UILayoutIsRightToLeft())\n l10n_util::HWNDSetRTLLayout(tab_control);\n\n RootView* root_view = content_window_->GetRootView();\n root_view->SetLayoutManager(new FillLayout());\n DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);\n SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),\n GetBValue(sys_color));\n root_view->set_background(Background::CreateSolidBackground(color));\n\n content_window_->SetFocusTraversableParentView(this);\n\n NativeControlCreated(tab_control);\n\n \/\/ Add tabs that are already added if any.\n if (tab_views_.size() > 0) {\n InitializeTabs();\n if (selected_index_ >= 0)\n DoSelectTabAt(selected_index_, false);\n }\n\n ResizeContents();\n}\n\nbool NativeTabbedPaneWin::ProcessMessage(UINT message,\n WPARAM w_param,\n LPARAM l_param,\n LRESULT* result) {\n if (message == WM_NOTIFY &&\n reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) {\n int selected_tab = TabCtrl_GetCurSel(native_view());\n DCHECK(selected_tab != -1);\n DoSelectTabAt(selected_tab, true);\n return TRUE;\n }\n return NativeControlWin::ProcessMessage(message, w_param, l_param, result);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ View override:\n\nvoid NativeTabbedPaneWin::Layout() {\n NativeControlWin::Layout();\n ResizeContents();\n}\n\nFocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {\n return content_window_;\n}\n\nvoid NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,\n View *parent,\n View *child) {\n NativeControlWin::ViewHierarchyChanged(is_add, parent, child);\n\n if (is_add && (child == this) && content_window_) {\n \/\/ We have been added to a view hierarchy, update the FocusTraversable\n \/\/ parent.\n content_window_->SetFocusTraversableParent(GetRootView());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWin, private:\n\nvoid NativeTabbedPaneWin::InitializeTabs() {\n for (size_t i = 0; i < tab_views_.size(); ++i) {\n AddNativeTab(i, tab_titles_[i], tab_views_[i]);\n }\n}\n\nvoid NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {\n selected_index_ = index;\n if (content_window_) {\n RootView* content_root = content_window_->GetRootView();\n\n \/\/ Clear the focus if the focused view was on the tab.\n FocusManager* focus_manager = GetFocusManager();\n DCHECK(focus_manager);\n View* focused_view = focus_manager->GetFocusedView();\n if (focused_view && content_root->IsParentOf(focused_view))\n focus_manager->ClearFocus();\n\n content_root->RemoveAllChildViews(false);\n content_root->AddChildView(tab_views_[index]);\n content_root->Layout();\n }\n if (invoke_listener && tabbed_pane_->listener())\n tabbed_pane_->listener()->TabSelectedAt(index);\n}\n\nvoid NativeTabbedPaneWin::ResizeContents() {\n CRect content_bounds;\n if (!GetClientRect(native_view(), &content_bounds))\n return;\n TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);\n content_window_->MoveWindow(content_bounds.left, content_bounds.top,\n content_bounds.Width(), content_bounds.Height(),\n TRUE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabbedPaneWrapper, public:\n\n\/\/ static\nNativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(\n TabbedPane* tabbed_pane) {\n return new NativeTabbedPaneWin(tabbed_pane);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright (C) 2011-2012 by Paul-Louis Ageneau *\n * paul-louis (at) ageneau (dot) org *\n * *\n * This file is part of Arcanet. *\n * *\n * Arcanet is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * Arcanet is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with Arcanet. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n#include \"core.h\"\n\nnamespace arc\n{\n\nCore::Core(void)\n{\n\n}\n\nCore::~Core(void)\n{\n\n}\n\nvoid Core::add(Socket *sock)\n{\n\tassert(sock != NULL);\n\tHandler *handler = new Handler(this,sock);\n\thandler->start();\n\tadd(sock->getRemoteAddress(), handler);\n}\n\nvoid Core::add(const Address &addr, Core::Handler *handler)\n{\n\tassert(handler != NULL);\n\tmHandlers.insert(addr, handler);\n}\n\nvoid Core::remove(const Address &addr)\n{\n\tif(mHandlers.contains(addr))\n\t{\n\t\tdelete mHandlers.get(addr);\n\t\tmHandlers.erase(addr);\n\t}\n}\n\nCore::Handler::Handler(Core *core, Stream *stream) :\n\tmCore(core),\n\tmStream(stream)\n{\n\n}\n\nCore::Handler::~Handler(void)\n{\n\tdelete mStream;\n\tdelete mHandler;\n}\n\nvoid Core::Handler::run(void)\n{\n\tString line;\n\tif(!mStream->readLine(line))\n\t\treturn;\n\n\tString proto;\n\tString version;\n\tline.readString(proto);\n\tline.readString(version);\n\n\twhile(mStream->readLine(line))\n\t{\n\t\tunsigned channel, size;\n\t\tline.read(channel);\n\t\tline.read(size);\n\n\t\tPipe *pipe;\n\t\tif(mChannel.get(channel,pipe))\n\t\t{\n\t\t\t\/\/ TODO: Limited read\n\t\t\t\/\/mStream->read(*pipe);\n\t\t}\n\t}\n\n\t\/\/mCore->remove(this);\n}\n\n}\n<commit_msg>Need correct multiplexing algorithm<commit_after>\/*************************************************************************\n * Copyright (C) 2011-2012 by Paul-Louis Ageneau *\n * paul-louis (at) ageneau (dot) org *\n * *\n * This file is part of Arcanet. *\n * *\n * Arcanet is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * Arcanet is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public *\n * License along with Arcanet. *\n * If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n *************************************************************************\/\n\n#include \"core.h\"\n\nnamespace arc\n{\n\nCore::Core(void)\n{\n\n}\n\nCore::~Core(void)\n{\n\n}\n\nvoid Core::add(Socket *sock)\n{\n\tassert(sock != NULL);\n\tHandler *handler = new Handler(this,sock);\n\thandler->start();\n\tadd(sock->getRemoteAddress(), handler);\n}\n\nvoid Core::add(const Address &addr, Core::Handler *handler)\n{\n\tassert(handler != NULL);\n\tmHandlers.insert(addr, handler);\n}\n\nvoid Core::remove(const Address &addr)\n{\n\tif(mHandlers.contains(addr))\n\t{\n\t\tdelete mHandlers.get(addr);\n\t\tmHandlers.erase(addr);\n\t}\n}\n\nCore::Handler::Handler(Core *core, Stream *stream) :\n\tmCore(core),\n\tmStream(stream)\n{\n\n}\n\nCore::Handler::~Handler(void)\n{\n\tdelete mStream;\n\tdelete mHandler;\n}\n\nvoid Core::Handler::run(void)\n{\n\tString line;\n\tif(!mStream->readLine(line))\n\t\treturn;\n\n\tString proto;\n\tString version;\n\tline.readString(proto);\n\tline.readString(version);\t\n\n\twhile(mStream->readLine(line))\n\t{\n\t\tunsigned channel, size;\n\t\tline.read(channel);\n\t\tline.read(size);\n\t\t\n\t\tif(channel == 0)\n\t\t{\n\n\t\t}\n\t\telse {\t\n\t\t\tPipe *pipe;\n\t\t\tif(mChannels.get(channel,pipe))\n\t\t\t{\n\t\t\t\t\/\/ TODO: Limited read\n\t\t\t\t\/\/mStream->read(*pipe);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/mCore->remove(this);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"declarativeviewtexture.h\"\n\n#include <QtGui\/QPainter>\n#include <QtGui\/QImage>\n#include <QtGui\/QPaintEvent>\n#include <QtCore\/QDebug>\n\nstatic inline void qgl_byteSwapImage(QImage &img, GLenum pixel_type)\n{\n const int width = img.width();\n const int height = img.height();\n\n if (pixel_type == GL_UNSIGNED_BYTE && QSysInfo::ByteOrder == QSysInfo::LittleEndian)\n {\n for (int i = 0; i < height; ++i) {\n uint *p = (uint *) img.scanLine(i);\n for (int x = 0; x < width; ++x)\n p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);\n }\n } else {\n for (int i = 0; i < height; ++i) {\n uint *p = (uint *) img.scanLine(i);\n for (int x = 0; x < width; ++x)\n p[x] = (p[x] << 8) | ((p[x] >> 24) & 0xff);\n }\n }\n}\n\nDeclarativeViewTexture::DeclarativeViewTexture(QWidget *parent) :\n QDeclarativeView(parent),\n m_bufferPainter(0)\n{\n setAttribute(Qt::WA_DontShowOnScreen);\n setOptimizationFlag(QGraphicsView::IndirectPainting);\n setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);\n\n glGenTextures(1, &m_textureId);\n}\n\nDeclarativeViewTexture::~DeclarativeViewTexture()\n{\n\n}\n\nvoid DeclarativeViewTexture::paintEvent(QPaintEvent *event)\n{\n \/\/ Render the view in an offscreen image\n delete m_bufferPainter;\n m_bufferPainter = new QPainter;\n QRegion exposedRegion = event->region();\n QImage im(exposedRegion.boundingRect().size(), QImage::Format_ARGB32_Premultiplied);\n im.fill(Qt::transparent);\n m_bufferPainter->begin(&im);\n m_bufferPainter->translate(-exposedRegion.boundingRect().topLeft());\n m_bufferPainter->setClipRegion(exposedRegion);\n QDeclarativeView::paintEvent(event);\n m_bufferPainter->end();\n\n \/\/ Upload the image in graphics memory\n glBindTexture(GL_TEXTURE_2D, m_textureId);\n qgl_byteSwapImage(im, GL_UNSIGNED_BYTE);\n foreach (const QRect &rect, exposedRegion.rects()) {\n if (rect.size() == size()) {\n glTexImage2D(GL_TEXTURE_2D, 0, 4, rect.width(), rect.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, im.bits());\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);\n break;\n } else {\n QRect adjustedRect = rect.translated(-exposedRegion.boundingRect().topLeft());\n QImage subIm = im.copy(adjustedRect);\n glTexSubImage2D(GL_TEXTURE_2D, 0, rect.left(), rect.top(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, subIm.bits());\n }\n }\n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\nvoid DeclarativeViewTexture::drawItems(QPainter *painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[])\n{\n QDeclarativeView::drawItems(m_bufferPainter, numItems, items, options);\n}\n\nvoid DeclarativeViewTexture::drawBackground(QPainter *painter, const QRectF &rect)\n{\n QDeclarativeView::drawBackground(m_bufferPainter, rect);\n}\n\nvoid DeclarativeViewTexture::drawForeground(QPainter *painter, const QRectF &rect)\n{\n QDeclarativeView::drawForeground(m_bufferPainter, rect);\n}\n<commit_msg>Activates anti-aliasing for QML rendering.<commit_after>#include \"declarativeviewtexture.h\"\n\n#include <QtGui\/QPainter>\n#include <QtGui\/QImage>\n#include <QtGui\/QPaintEvent>\n#include <QtCore\/QDebug>\n\nstatic inline void qgl_byteSwapImage(QImage &img, GLenum pixel_type)\n{\n const int width = img.width();\n const int height = img.height();\n\n if (pixel_type == GL_UNSIGNED_BYTE && QSysInfo::ByteOrder == QSysInfo::LittleEndian)\n {\n for (int i = 0; i < height; ++i) {\n uint *p = (uint *) img.scanLine(i);\n for (int x = 0; x < width; ++x)\n p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);\n }\n } else {\n for (int i = 0; i < height; ++i) {\n uint *p = (uint *) img.scanLine(i);\n for (int x = 0; x < width; ++x)\n p[x] = (p[x] << 8) | ((p[x] >> 24) & 0xff);\n }\n }\n}\n\nDeclarativeViewTexture::DeclarativeViewTexture(QWidget *parent) :\n QDeclarativeView(parent),\n m_bufferPainter(0)\n{\n setAttribute(Qt::WA_DontShowOnScreen);\n setOptimizationFlag(QGraphicsView::IndirectPainting);\n\n glGenTextures(1, &m_textureId);\n}\n\nDeclarativeViewTexture::~DeclarativeViewTexture()\n{\n\n}\n\nvoid DeclarativeViewTexture::paintEvent(QPaintEvent *event)\n{\n \/\/ Render the view in an offscreen image\n delete m_bufferPainter;\n m_bufferPainter = new QPainter;\n QRegion exposedRegion = event->region();\n QImage im(exposedRegion.boundingRect().size(), QImage::Format_ARGB32_Premultiplied);\n im.fill(Qt::transparent);\n m_bufferPainter->begin(&im);\n m_bufferPainter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);\n m_bufferPainter->translate(-exposedRegion.boundingRect().topLeft());\n m_bufferPainter->setClipRegion(exposedRegion);\n QDeclarativeView::paintEvent(event);\n m_bufferPainter->end();\n\n \/\/ Upload the image in graphics memory\n glBindTexture(GL_TEXTURE_2D, m_textureId);\n qgl_byteSwapImage(im, GL_UNSIGNED_BYTE);\n foreach (const QRect &rect, exposedRegion.rects()) {\n if (rect.size() == size()) {\n glTexImage2D(GL_TEXTURE_2D, 0, 4, rect.width(), rect.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, im.bits());\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);\n glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);\n break;\n } else {\n QRect adjustedRect = rect.translated(-exposedRegion.boundingRect().topLeft());\n QImage subIm = im.copy(adjustedRect);\n glTexSubImage2D(GL_TEXTURE_2D, 0, rect.left(), rect.top(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, subIm.bits());\n }\n }\n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\nvoid DeclarativeViewTexture::drawItems(QPainter *painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[])\n{\n QDeclarativeView::drawItems(m_bufferPainter, numItems, items, options);\n}\n\nvoid DeclarativeViewTexture::drawBackground(QPainter *painter, const QRectF &rect)\n{\n QDeclarativeView::drawBackground(m_bufferPainter, rect);\n}\n\nvoid DeclarativeViewTexture::drawForeground(QPainter *painter, const QRectF &rect)\n{\n QDeclarativeView::drawForeground(m_bufferPainter, rect);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/component\/forcefield\/EdgePressureForceField.h>\n#include <sofa\/component\/topology\/EdgeSubsetData.inl>\n#include <sofa\/helper\/gl\/template.h>\n#include <vector>\n#include <set>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\n\/\/ #define DEBUG_TRIANGLEFEM\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace forcefield\n{\n\nusing namespace sofa::defaulttype;\nusing namespace core::componentmodel::topology;\n\n\n\n\n\ntemplate <class DataTypes> EdgePressureForceField<DataTypes>::~EdgePressureForceField()\n{\n}\n\/\/ Handle topological changes\ntemplate <class DataTypes> void EdgePressureForceField<DataTypes>::handleTopologyChange()\n{\n std::list<const TopologyChange *>::const_iterator itBegin=_topology->firstChange();\n std::list<const TopologyChange *>::const_iterator itEnd=_topology->lastChange();\n\n\n edgePressureMap.handleTopologyEvents(itBegin,itEnd,_topology->getNbEdges());\n\n}\ntemplate <class DataTypes> void EdgePressureForceField<DataTypes>::init()\n{\n this->core::componentmodel::behavior::ForceField<DataTypes>::init();\n\n _topology = this->getContext()->getMeshTopology();\n this->getContext()->get(_completeTopology, core::objectmodel::BaseContext::SearchUp);\n\n this->getContext()->get(edgeGeo);\n\n assert(edgeGeo!=0);\n\n if (edgeGeo==NULL)\n {\n serr << \"ERROR(EdgePressureForceField): object must have an EdgeSetTopology.\"<<sendl;\n return;\n }\n\n if(_completeTopology == NULL)\n {\n serr << \"ERROR(EdgePressureForceField): assume that pressure vector is provdided otherwise TriangleSetTopology is required\" << sendl;\n }\n\n if (dmin.getValue()!=dmax.getValue())\n {\n selectEdgesAlongPlane();\n }\n if (edgeList.getValue().size()>0)\n {\n selectEdgesFromString();\n }\n\n initEdgeInformation();\n\n}\n\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::addForce(VecDeriv& f, const VecCoord& \/*x*\/, const VecDeriv& \/*v*\/)\n{\n Deriv force;\n\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n force=(*it).second.force\/2;\n f[_topology->getEdge((*it).first)[0]]+=force;\n f[_topology->getEdge((*it).first)[1]]+=force;\n\n }\n}\n\ntemplate <class DataTypes>\ndouble EdgePressureForceField<DataTypes>::getPotentialEnergy(const VecCoord& \/*x*\/)\n{\n serr<<\"EdgePressureForceField::getPotentialEnergy-not-implemented !!!\"<<sendl;\n return 0;\n}\n\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::initEdgeInformation()\n{\n const VecCoord& x = *this->mstate->getX();\n\n if(pressure.getValue().norm() > 0)\n {\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n (*it).second.length=edgeGeo->computeRestEdgeLength((*it).first);\n (*it).second.force=pressure.getValue()*(*it).second.length;\n }\n }\n else \/\/ if no pressure is provided, assume that boundary edges received pressure along their normal\n {\n\n for(int i = 0; i < _topology->getNbEdges() ; i++)\n {\n Edge e = _topology->getEdge(i), f;\n\n Vec3d tang, n1, n2;\n n2 = Vec3d(0,0,1);\n tang = x[e[1]] - x[e[0]]; tang.normalize();\n\n Vec3d sum;\n bool found = false;\n int k = 0;\n while ((!found) && (k < _completeTopology->getNbEdges()))\n {\n f = _completeTopology->getEdge(k);\n\n Vec3d l1 = x[f[0]] - x[e[0]];\n Vec3d l2 = x[f[1]] - x[e[1]];\n\n if((l1.norm() < 1e-6) && (l2.norm() < 1e-6))\n {\n found = true;\n }\n else\n k++;\n\n }\n TrianglesAroundEdge t_a_E = _completeTopology->getTrianglesAroundEdge(k);\n\n if(t_a_E.size() == 1) \/\/ 2D cases\n {\n Triangle t = _completeTopology->getTriangle(t_a_E[0]);\n Vec3d vert;\n\n\n if((t[0] == e[0]) || (t[0] == e[1]))\n {\n if((t[1] == e[0]) || (t[1] == e[1]))\n vert = x[t[2]];\n else\n vert = x[t[1]];\n }\n else\n vert = x[t[0]];\n\n Vec3d tt = vert - x[e[0]];\n n1 = n2.cross(tang);\n if(n1*tt < 0)\n {\n n1 = -n1;\n }\n\n EdgePressureInformation ei;\n ei.length = edgeGeo->computeRestEdgeLength(i);\n ei.force = n1 * ei.length * p_intensity.getValue();\n edgePressureMap[i] = ei;\n }\n\n }\n }\n\n return;\n}\n\n\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::updateEdgeInformation()\n{\n \/*typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n const VecCoord& x = *this->mstate->getX();\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n \tVec3d p1 = x[_topology->getEdge((*it).first)[0]];\n \tVec3d p2 = x[_topology->getEdge((*it).first)[1]];\n \tVec3d orig(0,0,0);\n\n \tVec3d tang = p2 - p1;\n \ttang.norm();\n\n \tDeriv myPressure;\n\n \tif( (p1[0] - orig[0]) * tang[1] > 0)\n \t\tmyPressure[0] = tang[1];\n \telse\n \t\tmyPressure[0] = - tang[1];\n\n \tif( (p1[1] - orig[1]) * tang[0] > 0)\n \t\tmyPressure[1] = tang[0];\n \telse\n \t\tmyPressure[1] = - tang[0];\n\n \t\/\/(*it).second.force=pressure.getValue()*((*it).second.length);\n \t(*it).second.force=myPressure*((*it).second.length);\n\n }*\/\n initEdgeInformation();\n}\n\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::selectEdgesAlongPlane()\n{\n const VecCoord& x = *this->mstate->getX0();\n std::vector<bool> vArray;\n unsigned int i;\n\n vArray.resize(x.size());\n\n for( i=0; i<x.size(); ++i)\n {\n vArray[i]=isPointInPlane(x[i]);\n }\n\n for (int n=0; n<_topology->getNbEdges(); ++n)\n {\n if ((vArray[_topology->getEdge(n)[0]]) && (vArray[_topology->getEdge(n)[1]]))\n {\n \/\/ insert a dummy element : computation of pressure done later\n EdgePressureInformation t;\n edgePressureMap[n]=t;\n }\n }\n}\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::selectEdgesFromString()\n{\n helper::vector<int> inputString=edgeList.getValue();\n for (unsigned int i = 0; i < inputString.size(); i++)\n {\n EdgePressureInformation t;\n edgePressureMap[inputString[i]]=t;\n\n }\n\n}\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::draw()\n{\n\n if (!this->getContext()->getShowForceFields()) return;\n if (!this->mstate) return;\n\n\n\n if (this->getContext()->getShowWireFrame())\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\n\n const VecCoord& x = *this->mstate->getX();\n\n glDisable(GL_LIGHTING);\n\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n \/*for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n \thelper::gl::glVertexT(x[_topology->getEdge((*it).first)[0]]);\n \thelper::gl::glVertexT(x[_topology->getEdge((*it).first)[1]]);\n }*\/\n glEnd();\n\n glBegin(GL_LINES);\n glColor4f(1,1,0,1);\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n Vec3d p = (x[_topology->getEdge((*it).first)[0]] + x[_topology->getEdge((*it).first)[1]]) \/ 2.0;\n helper::gl::glVertexT(p);\n\n Vec3d f = (*it).second.force;\n f.normalize();\n f \/= 5.0;\n helper::gl::glVertexT(p + f);\n }\n glEnd();\n\n if (this->getContext()->getShowWireFrame())\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n}\n\n} \/\/ namespace forcefield\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<commit_msg>r6720\/sofa-dev : Update: force pressure update<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/component\/forcefield\/EdgePressureForceField.h>\n#include <sofa\/component\/topology\/EdgeSubsetData.inl>\n#include <sofa\/helper\/gl\/template.h>\n#include <vector>\n#include <set>\n\n#ifdef _WIN32\n#include <windows.h>\n#endif\n\n\/\/ #define DEBUG_TRIANGLEFEM\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace forcefield\n{\n\nusing namespace sofa::defaulttype;\nusing namespace core::componentmodel::topology;\n\n\n\n\n\ntemplate <class DataTypes> EdgePressureForceField<DataTypes>::~EdgePressureForceField()\n{\n}\n\/\/ Handle topological changes\ntemplate <class DataTypes> void EdgePressureForceField<DataTypes>::handleTopologyChange()\n{\n std::list<const TopologyChange *>::const_iterator itBegin=_topology->firstChange();\n std::list<const TopologyChange *>::const_iterator itEnd=_topology->lastChange();\n\n\n edgePressureMap.handleTopologyEvents(itBegin,itEnd,_topology->getNbEdges());\n\n}\ntemplate <class DataTypes> void EdgePressureForceField<DataTypes>::init()\n{\n this->core::componentmodel::behavior::ForceField<DataTypes>::init();\n\n _topology = this->getContext()->getMeshTopology();\n this->getContext()->get(_completeTopology, core::objectmodel::BaseContext::SearchUp);\n\n this->getContext()->get(edgeGeo);\n\n assert(edgeGeo!=0);\n\n if (edgeGeo==NULL)\n {\n serr << \"ERROR(EdgePressureForceField): object must have an EdgeSetTopology.\"<<sendl;\n return;\n }\n\n if(_completeTopology == NULL)\n {\n serr << \"ERROR(EdgePressureForceField): assume that pressure vector is provdided otherwise TriangleSetTopology is required\" << sendl;\n }\n\n if (dmin.getValue()!=dmax.getValue())\n {\n selectEdgesAlongPlane();\n }\n if (edgeList.getValue().size()>0)\n {\n selectEdgesFromString();\n }\n\n initEdgeInformation();\n\n}\n\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::addForce(VecDeriv& f, const VecCoord& \/*x*\/, const VecDeriv& \/*v*\/)\n{\n Deriv force;\n\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n force=(*it).second.force\/2;\n f[_topology->getEdge((*it).first)[0]]+=force;\n f[_topology->getEdge((*it).first)[1]]+=force;\n\n }\n}\n\ntemplate <class DataTypes>\ndouble EdgePressureForceField<DataTypes>::getPotentialEnergy(const VecCoord& \/*x*\/)\n{\n serr<<\"EdgePressureForceField::getPotentialEnergy-not-implemented !!!\"<<sendl;\n return 0;\n}\n\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::initEdgeInformation()\n{\n const VecCoord& x = *this->mstate->getX();\n\n if(pressure.getValue().norm() > 0)\n {\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n (*it).second.length=edgeGeo->computeRestEdgeLength((*it).first);\n (*it).second.force=pressure.getValue()*(*it).second.length;\n }\n }\n else \/\/ if no pressure is provided, assume that boundary edges received pressure along their normal\n {\n for(int i = 0; i < _topology->getNbEdges() ; i++)\n {\n Edge e = _topology->getEdge(i), f;\n\n Vec3d tang, n1, n2;\n n2 = Vec3d(0,0,1);\n tang = x[e[1]] - x[e[0]]; tang.normalize();\n\n Vec3d sum;\n bool found = false;\n int k = 0;\n while ((!found) && (k < _completeTopology->getNbEdges()))\n {\n f = _completeTopology->getEdge(k);\n\n Vec3d l1 = x[f[0]] - x[e[0]];\n Vec3d l2 = x[f[1]] - x[e[1]];\n\n if((l1.norm() < 1e-6) && (l2.norm() < 1e-6))\n {\n found = true;\n }\n else\n k++;\n\n }\n TrianglesAroundEdge t_a_E = _completeTopology->getTrianglesAroundEdge(k);\n\n if(t_a_E.size() == 1) \/\/ 2D cases\n {\n Triangle t = _completeTopology->getTriangle(t_a_E[0]);\n Vec3d vert;\n\n\n if((t[0] == e[0]) || (t[0] == e[1]))\n {\n if((t[1] == e[0]) || (t[1] == e[1]))\n vert = x[t[2]];\n else\n vert = x[t[1]];\n }\n else\n vert = x[t[0]];\n\n Vec3d tt = vert - x[e[0]];\n n1 = n2.cross(tang);\n if(n1*tt < 0)\n {\n n1 = -n1;\n }\n\n EdgePressureInformation ei;\n ei.length = edgeGeo->computeRestEdgeLength(i);\n ei.force = n1 * ei.length * p_intensity.getValue();\n edgePressureMap[i] = ei;\n }\n\n }\n }\n\n return;\n}\n\n\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::updateEdgeInformation()\n{\n \/*typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n const VecCoord& x = *this->mstate->getX();\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n \tVec3d p1 = x[_topology->getEdge((*it).first)[0]];\n \tVec3d p2 = x[_topology->getEdge((*it).first)[1]];\n \tVec3d orig(0,0,0);\n\n \tVec3d tang = p2 - p1;\n \ttang.norm();\n\n \tDeriv myPressure;\n\n \tif( (p1[0] - orig[0]) * tang[1] > 0)\n \t\tmyPressure[0] = tang[1];\n \telse\n \t\tmyPressure[0] = - tang[1];\n\n \tif( (p1[1] - orig[1]) * tang[0] > 0)\n \t\tmyPressure[1] = tang[0];\n \telse\n \t\tmyPressure[1] = - tang[0];\n\n \t\/\/(*it).second.force=pressure.getValue()*((*it).second.length);\n \t(*it).second.force=myPressure*((*it).second.length);\n\n }*\/\n initEdgeInformation();\n}\n\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::selectEdgesAlongPlane()\n{\n const VecCoord& x = *this->mstate->getX0();\n std::vector<bool> vArray;\n unsigned int i;\n\n vArray.resize(x.size());\n\n for( i=0; i<x.size(); ++i)\n {\n vArray[i]=isPointInPlane(x[i]);\n }\n\n for (int n=0; n<_topology->getNbEdges(); ++n)\n {\n if ((vArray[_topology->getEdge(n)[0]]) && (vArray[_topology->getEdge(n)[1]]))\n {\n \/\/ insert a dummy element : computation of pressure done later\n EdgePressureInformation t;\n edgePressureMap[n]=t;\n }\n }\n}\n\ntemplate <class DataTypes>\nvoid EdgePressureForceField<DataTypes>::selectEdgesFromString()\n{\n helper::vector<int> inputString=edgeList.getValue();\n for (unsigned int i = 0; i < inputString.size(); i++)\n {\n EdgePressureInformation t;\n edgePressureMap[inputString[i]]=t;\n\n }\n\n}\ntemplate<class DataTypes>\nvoid EdgePressureForceField<DataTypes>::draw()\n{\n\n updateEdgeInformation();\n\n if (!this->getContext()->getShowForceFields()) return;\n if (!this->mstate) return;\n\n\n\n if (this->getContext()->getShowWireFrame())\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\n\n const VecCoord& x = *this->mstate->getX();\n\n glDisable(GL_LIGHTING);\n\n typename topology::EdgeSubsetData<EdgePressureInformation>::iterator it;\n\n \/*for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n \thelper::gl::glVertexT(x[_topology->getEdge((*it).first)[0]]);\n \thelper::gl::glVertexT(x[_topology->getEdge((*it).first)[1]]);\n }*\/\n glEnd();\n\n glBegin(GL_LINES);\n glColor4f(1,1,0,1);\n\n for(it=edgePressureMap.begin(); it!=edgePressureMap.end(); it++ )\n {\n Vec3d p = (x[_topology->getEdge((*it).first)[0]] + x[_topology->getEdge((*it).first)[1]]) \/ 2.0;\n helper::gl::glVertexT(p);\n\n Vec3d f = (*it).second.force;\n f.normalize();\n f \/= 5.0;\n helper::gl::glVertexT(p + f);\n }\n glEnd();\n\n if (this->getContext()->getShowWireFrame())\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n}\n\n} \/\/ namespace forcefield\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"<commit_before>#include \"demo.h\"\r\n\r\nDemo::Demo(void) {\r\n\tthis->root = NULL;\r\n\tthis->sceneMgr = NULL;\r\n\tthis->window = NULL;\r\n\t\r\n\tthis->resourcesCfg = \"resources.cfg\";\r\n\tthis->pluginsCfg = \"plugins.cfg\";\r\n\t\r\n\tthis->camera = NULL;\r\n\t\r\n\tthis->shutDown = false;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nDemo::~Demo(void) {\r\n\t\/\/ remove ourself as a Window listener\r\n\tOgre::WindowEventUtilities::removeWindowEventListener(this->window, this);\r\n\twindowClosed(this->window);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nbool Demo::start(void) {\r\n\t\/\/ construct Ogre::Root\r\n\tthis->root = new Ogre::Root(this->pluginsCfg);\r\n \r\n\t\/\/ load the ressources\r\n\tthis->loadRessources();\r\n\t\r\n\t\/\/ restore the config or show the configuration dialog and \r\n\tif(! this->root->restoreConfig() && ! this->root->showConfigDialog())\r\n\t\treturn false;\r\n\r\n\t\/\/ initialise the system, create the default rendering window\r\n\tthis->window = this->root->initialise(true, \"Diablotin\");\r\n\r\n\t\/\/ get the generic SceneManager\r\n\tthis->sceneMgr = this->root->createSceneManager(Ogre::ST_GENERIC);\r\n\t\r\n\t\/\/ init the input manager and create the listeners\r\n\tthis->initListeners();\r\n\t\r\n\t\/\/ create the scene\r\n\tthis->initScene();\r\n\t\r\n\t\/\/ create the camera\r\n\tthis->camera = this->sceneMgr->createCamera(\"mainCam\");\r\n\tthis->camera->setPosition(Ogre::Vector3(90, 25, 90));\r\n\tthis->camera->lookAt(this->sceneMgr->getRootSceneNode()->getPosition());\r\n\t\r\n\t\/\/ create one viewport, entire window\r\n\t\/\/ use the same color for the fog and viewport background\r\n\t\/\/Ogre::Viewport* viewPort = this->window->addViewport(this->camera);\r\n\tOgre::Viewport* viewPort = this->window->addViewport(this->camera, 0);\r\n\tviewPort->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));\r\n\tthis->camera->setAspectRatio(Ogre::Real(viewPort->getActualWidth()) \/ Ogre::Real(viewPort->getActualHeight()));\t\r\n\t\t\r\n\t\/\/ start the scene rendering (main loop)\r\n\tthis->root->startRendering();\r\n\t\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::initListeners(void) {\r\n\t\/\/ Init the input system\r\n\tOIS::ParamList pl;\r\n\tsize_t windowHnd = 0;\r\n\tstd::ostringstream windowHndStr;\r\n \r\n\twindow->getCustomAttribute(\"WINDOW\", &windowHnd);\r\n\twindowHndStr << windowHnd;\r\n\tpl.insert(std::make_pair(std::string(\"WINDOW\"), windowHndStr.str()));\r\n \r\n\tthis->inputManager = OIS::InputManager::createInputSystem(pl);\r\n \r\n\tthis->keyboard = static_cast<OIS::Keyboard*>(inputManager->createInputObject(OIS::OISKeyboard, true));\r\n\tthis->mouse = static_cast<OIS::Mouse*>(inputManager->createInputObject(OIS::OISMouse, true));\r\n \r\n\t\/\/ Set initial mouse clipping size\r\n\twindowResized(this->window);\r\n\t\r\n\t\/\/ Register the listeners\r\n\tOgre::WindowEventUtilities::addWindowEventListener(this->window, this);\r\n\tthis->root->addFrameListener(this);\r\n\tthis->mouse->setEventCallback(this);\r\n\tthis->keyboard->setEventCallback(this);\r\n\r\n}\r\n\r\nvoid Demo::initScene(void) {\t\r\n\t\r\n\tOgre::Plane plane(Ogre::Vector3::UNIT_Y, 0);\r\n\tOgre::MeshManager::getSingleton().createPlane(\"ground\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\r\n\t\t\tplane, 150, 150, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);\r\n\tOgre::Entity* entGround = this->sceneMgr->createEntity(\"GroundEntity\", \"ground\");\r\n\tentGround->setMaterialName(\"Rockwall\");\r\n\tentGround->setCastShadows(false);\r\n\tOgre::SceneNode *groundNode = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"ground\");\r\n\tgroundNode->attachObject(entGround);\r\n\tgroundNode->setPosition(0, -50, 0);\r\n\r\n\r\n\tOgre::SceneNode *headNodeObject = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"HeadNodeObject\");\t\r\n\tOgre::SceneNode *headNodeLight = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"HeadNodeLight\");\t\r\n\t\t\r\n\t\/\/ charger le « mesh » à partir du nom de fichier et le nommer\r\n\tOgre::Entity *entity = this->sceneMgr->createEntity(\"Suzanne\", \"suzanne.mesh\");\r\n\tOgre::SceneNode *nodeObjectSuzanne = headNodeObject->createChildSceneNode(\"NodeObjectSuzanne\");\r\n\tnodeObjectSuzanne->attachObject(entity);\r\n\tnodeObjectSuzanne->setPosition(0, 0, 0);\r\n\tnodeObjectSuzanne->scale(10, 10, 10);\r\n\t\r\n\t\/*Ogre::Entity *entity1 = this->sceneMgr->createEntity(\"SuzanneBoiteBas\", \"boite_bas.mesh\");\r\n\tOgre::Entity *entity2 = this->sceneMgr->createEntity(\"SuzanneBoiteFermeture\", \"fermeture.mesh\");\r\n\tentity = this->sceneMgr->createEntity(\"SuzanneBoiteHaut\", \"boite_haut.mesh\");\r\n\tOgre::SceneNode *nodeObjectSuzanneBoiteHaut = headNodeObject->createChildSceneNode(\"NodeObjectSuzanneBoiteHaut\");\r\n\tnodeObjectSuzanneBoiteHaut->attachObject(entity);\r\n\tnodeObjectSuzanneBoiteHaut->setPosition(0, 0, 0);\r\n\tnodeObjectSuzanneBoiteHaut->scale(10, 10, 10);*\/\r\n\r\n \/\/ Set ambient light\r\n \/\/this->sceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));\r\n this->sceneMgr->setAmbientLight(Ogre::ColourValue(1.0, 1.0, 1.0));\r\n \r\n \/\/ Create a light\r\n Ogre::Light* l = this->sceneMgr->createLight(\"MainLight\"); \r\n l->setPosition(20,80,50);\r\n\tOgre::SceneNode *nodeLight1 = headNodeLight->createChildSceneNode(\"NodeLight1\");\r\n\tnodeLight1->attachObject(l);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::loadRessources(void) {\r\n\t\/\/ setup resources\r\n\t\/\/ Load resource paths from config file\r\n\tOgre::ConfigFile cf;\r\n\tcf.load(this->resourcesCfg);\r\n \r\n\t\/\/ Go through all sections & settings in the file\r\n\tOgre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\r\n \r\n\tOgre::String secName, typeName, archName;\r\n\twhile (seci.hasMoreElements())\r\n\t{\r\n\t\tsecName = seci.peekNextKey();\r\n\t\tOgre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\r\n\t\tOgre::ConfigFile::SettingsMultiMap::iterator i;\r\n\t\tfor (i = settings->begin(); i != settings->end(); ++i)\r\n\t\t{\r\n\t\t\ttypeName = i->first;\r\n\t\t\tarchName = i->second;\r\n\t\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tOgre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nbool Demo::frameRenderingQueued(const Ogre::FrameEvent& evt) {\r\n\tint newStatus;\r\n\t\r\n\t\/\/ Stop the rendering if the window was closed, or the application stoped\r\n\tif(this->window->isClosed() || this->shutDown)\r\n\t\treturn false;\r\n\r\n \/\/ capture value of each device\r\n this->keyboard->capture();\r\n this->mouse->capture();\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::windowResized(Ogre::RenderWindow *rw)\r\n{\r\n\tunsigned int width, height, depth;\r\n\tint left, top;\r\n\r\n\t\/\/ Adjust mouse clipping area\r\n\trw->getMetrics(width, height, depth, left, top); \r\n\tconst OIS::MouseState &ms = this->mouse->getMouseState();\r\n\tms.width = width;\r\n\tms.height = height;\r\n\r\n}\r\n \r\nvoid Demo::windowClosed(Ogre::RenderWindow *rw)\r\n{\r\n\t\/\/ Only close for window that created OIS (the main window)\r\n\tif(rw == this->window)\r\n\t{\r\n\t\tif(this->inputManager)\r\n\t\t{\r\n\t\t\t\/\/ Unattach OIS before window shutdown (very important under Linux)\r\n\t\t\tthis->inputManager->destroyInputObject(this->mouse);\r\n\t\t\tthis->inputManager->destroyInputObject(this->keyboard);\r\n \r\n\t\t\tOIS::InputManager::destroyInputSystem(this->inputManager);\r\n\t\t\tthis->inputManager = 0;\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nbool Demo::keyPressed(const OIS::KeyEvent &evt) {\r\n\t\r\n\t\/\/ Quit\r\n\tswitch(evt.key)\r\n\t{\r\n\t\tcase OIS::KC_ESCAPE:\r\n\t\t\tthis->shutDown = true;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_UP:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 0, 5));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_DOWN:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 0, -5));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_H:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 5, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_N:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, -5, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_G:\r\n\t\t\tthis->camera->move(Ogre::Vector3(5, 0, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_B:\r\n\t\t\tthis->camera->move(Ogre::Vector3(-5, 0, 0));\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\tstd::cout << \"PosCamera : \" << this->camera->getPosition()[0] << \"\/\" << this->camera->getPosition()[1] << \"\/\" << this->camera->getPosition()[2] << std::endl;\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::keyReleased(const OIS::KeyEvent &evt) {\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mouseMoved(const OIS::MouseEvent &evt) {\r\n\t\r\n\tfloat mRotateSpeed = 0.1f;\r\n\t\r\n\tthis->camera->yaw(Ogre::Degree(-evt.state.X.rel * mRotateSpeed));\r\n\tthis->camera->pitch(Ogre::Degree(-evt.state.Y.rel * mRotateSpeed));\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nint main(void) {\r\n\tDemo demo;\r\n\t\r\n\ttry {\r\n\t\tdemo.start();\r\n\t} catch( Ogre::Exception& e ) {\r\n\t\tstd::cerr << \"An exception has occured: \" << e.getFullDescription().c_str() << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n<commit_msg>Chargement des fichiers plugins.cfg et resources.cfg en fonction du mode de compilation (Debug ou Release)<commit_after>#include \"demo.h\"\r\n\r\nDemo::Demo(void) {\r\n\tthis->root = NULL;\r\n\tthis->sceneMgr = NULL;\r\n\tthis->window = NULL;\r\n\t\r\n#ifdef _DEBUG\r\n\tthis->resourcesCfg = \"resources_d.cfg\";\r\n#else\r\n\tthis->resourcesCfg = \"resources.cfg\";\r\n#endif\r\n\r\n#ifdef _DEBUG\r\n\tthis->pluginsCfg = \"plugins_d.cfg\";\r\n#else\r\n\tthis->pluginsCfg = \"plugins.cfg\";\r\n#endif\r\n\t\r\n\tthis->camera = NULL;\r\n\t\r\n\tthis->shutDown = false;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nDemo::~Demo(void) {\r\n\t\/\/ remove ourself as a Window listener\r\n\tOgre::WindowEventUtilities::removeWindowEventListener(this->window, this);\r\n\twindowClosed(this->window);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nbool Demo::start(void) {\r\n\t\/\/ construct Ogre::Root\r\n\tthis->root = new Ogre::Root(this->pluginsCfg);\r\n \r\n\t\/\/ load the ressources\r\n\tthis->loadRessources();\r\n\t\r\n\t\/\/ restore the config or show the configuration dialog and \r\n\tif(! this->root->restoreConfig() && ! this->root->showConfigDialog())\r\n\t\treturn false;\r\n\r\n\t\/\/ initialise the system, create the default rendering window\r\n\tthis->window = this->root->initialise(true, \"Diablotin\");\r\n\r\n\t\/\/ get the generic SceneManager\r\n\tthis->sceneMgr = this->root->createSceneManager(Ogre::ST_GENERIC);\r\n\t\r\n\t\/\/ init the input manager and create the listeners\r\n\tthis->initListeners();\r\n\t\r\n\t\/\/ create the scene\r\n\tthis->initScene();\r\n\t\r\n\t\/\/ create the camera\r\n\tthis->camera = this->sceneMgr->createCamera(\"mainCam\");\r\n\tthis->camera->setPosition(Ogre::Vector3(90, 25, 90));\r\n\tthis->camera->lookAt(this->sceneMgr->getRootSceneNode()->getPosition());\r\n\t\r\n\t\/\/ create one viewport, entire window\r\n\t\/\/ use the same color for the fog and viewport background\r\n\t\/\/Ogre::Viewport* viewPort = this->window->addViewport(this->camera);\r\n\tOgre::Viewport* viewPort = this->window->addViewport(this->camera, 0);\r\n\tviewPort->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));\r\n\tthis->camera->setAspectRatio(Ogre::Real(viewPort->getActualWidth()) \/ Ogre::Real(viewPort->getActualHeight()));\t\r\n\t\t\r\n\t\/\/ start the scene rendering (main loop)\r\n\tthis->root->startRendering();\r\n\t\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::initListeners(void) {\r\n\t\/\/ Init the input system\r\n\tOIS::ParamList pl;\r\n\tsize_t windowHnd = 0;\r\n\tstd::ostringstream windowHndStr;\r\n \r\n\twindow->getCustomAttribute(\"WINDOW\", &windowHnd);\r\n\twindowHndStr << windowHnd;\r\n\tpl.insert(std::make_pair(std::string(\"WINDOW\"), windowHndStr.str()));\r\n \r\n\tthis->inputManager = OIS::InputManager::createInputSystem(pl);\r\n \r\n\tthis->keyboard = static_cast<OIS::Keyboard*>(inputManager->createInputObject(OIS::OISKeyboard, true));\r\n\tthis->mouse = static_cast<OIS::Mouse*>(inputManager->createInputObject(OIS::OISMouse, true));\r\n \r\n\t\/\/ Set initial mouse clipping size\r\n\twindowResized(this->window);\r\n\t\r\n\t\/\/ Register the listeners\r\n\tOgre::WindowEventUtilities::addWindowEventListener(this->window, this);\r\n\tthis->root->addFrameListener(this);\r\n\tthis->mouse->setEventCallback(this);\r\n\tthis->keyboard->setEventCallback(this);\r\n\r\n}\r\n\r\nvoid Demo::initScene(void) {\t\r\n\t\r\n\tOgre::Plane plane(Ogre::Vector3::UNIT_Y, 0);\r\n\tOgre::MeshManager::getSingleton().createPlane(\"ground\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\r\n\t\t\tplane, 150, 150, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);\r\n\tOgre::Entity* entGround = this->sceneMgr->createEntity(\"GroundEntity\", \"ground\");\r\n\tentGround->setMaterialName(\"Rockwall\");\r\n\tentGround->setCastShadows(false);\r\n\tOgre::SceneNode *groundNode = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"ground\");\r\n\tgroundNode->attachObject(entGround);\r\n\tgroundNode->setPosition(0, -50, 0);\r\n\r\n\r\n\tOgre::SceneNode *headNodeObject = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"HeadNodeObject\");\t\r\n\tOgre::SceneNode *headNodeLight = this->sceneMgr->getRootSceneNode()->createChildSceneNode(\"HeadNodeLight\");\t\r\n\t\t\r\n\t\/\/ charger le « mesh » à partir du nom de fichier et le nommer\r\n\tOgre::Entity *entity = this->sceneMgr->createEntity(\"Suzanne\", \"suzanne.mesh\");\r\n\tOgre::SceneNode *nodeObjectSuzanne = headNodeObject->createChildSceneNode(\"NodeObjectSuzanne\");\r\n\tnodeObjectSuzanne->attachObject(entity);\r\n\tnodeObjectSuzanne->setPosition(0, 0, 0);\r\n\tnodeObjectSuzanne->scale(10, 10, 10);\r\n\t\r\n\t\/*Ogre::Entity *entity1 = this->sceneMgr->createEntity(\"SuzanneBoiteBas\", \"boite_bas.mesh\");\r\n\tOgre::Entity *entity2 = this->sceneMgr->createEntity(\"SuzanneBoiteFermeture\", \"fermeture.mesh\");\r\n\tentity = this->sceneMgr->createEntity(\"SuzanneBoiteHaut\", \"boite_haut.mesh\");\r\n\tOgre::SceneNode *nodeObjectSuzanneBoiteHaut = headNodeObject->createChildSceneNode(\"NodeObjectSuzanneBoiteHaut\");\r\n\tnodeObjectSuzanneBoiteHaut->attachObject(entity);\r\n\tnodeObjectSuzanneBoiteHaut->setPosition(0, 0, 0);\r\n\tnodeObjectSuzanneBoiteHaut->scale(10, 10, 10);*\/\r\n\r\n \/\/ Set ambient light\r\n \/\/this->sceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));\r\n this->sceneMgr->setAmbientLight(Ogre::ColourValue(1.0, 1.0, 1.0));\r\n \r\n \/\/ Create a light\r\n Ogre::Light* l = this->sceneMgr->createLight(\"MainLight\"); \r\n l->setPosition(20,80,50);\r\n\tOgre::SceneNode *nodeLight1 = headNodeLight->createChildSceneNode(\"NodeLight1\");\r\n\tnodeLight1->attachObject(l);\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::loadRessources(void) {\r\n\t\/\/ setup resources\r\n\t\/\/ Load resource paths from config file\r\n\tOgre::ConfigFile cf;\r\n\tcf.load(this->resourcesCfg);\r\n \r\n\t\/\/ Go through all sections & settings in the file\r\n\tOgre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\r\n \r\n\tOgre::String secName, typeName, archName;\r\n\twhile (seci.hasMoreElements())\r\n\t{\r\n\t\tsecName = seci.peekNextKey();\r\n\t\tOgre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\r\n\t\tOgre::ConfigFile::SettingsMultiMap::iterator i;\r\n\t\tfor (i = settings->begin(); i != settings->end(); ++i)\r\n\t\t{\r\n\t\t\ttypeName = i->first;\r\n\t\t\tarchName = i->second;\r\n\t\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);\r\n\t\t}\r\n\t}\r\n\t\r\n\tOgre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nbool Demo::frameRenderingQueued(const Ogre::FrameEvent& evt) {\r\n\tint newStatus;\r\n\t\r\n\t\/\/ Stop the rendering if the window was closed, or the application stoped\r\n\tif(this->window->isClosed() || this->shutDown)\r\n\t\treturn false;\r\n\r\n \/\/ capture value of each device\r\n this->keyboard->capture();\r\n this->mouse->capture();\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nvoid Demo::windowResized(Ogre::RenderWindow *rw)\r\n{\r\n\tunsigned int width, height, depth;\r\n\tint left, top;\r\n\r\n\t\/\/ Adjust mouse clipping area\r\n\trw->getMetrics(width, height, depth, left, top); \r\n\tconst OIS::MouseState &ms = this->mouse->getMouseState();\r\n\tms.width = width;\r\n\tms.height = height;\r\n\r\n}\r\n \r\nvoid Demo::windowClosed(Ogre::RenderWindow *rw)\r\n{\r\n\t\/\/ Only close for window that created OIS (the main window)\r\n\tif(rw == this->window)\r\n\t{\r\n\t\tif(this->inputManager)\r\n\t\t{\r\n\t\t\t\/\/ Unattach OIS before window shutdown (very important under Linux)\r\n\t\t\tthis->inputManager->destroyInputObject(this->mouse);\r\n\t\t\tthis->inputManager->destroyInputObject(this->keyboard);\r\n \r\n\t\t\tOIS::InputManager::destroyInputSystem(this->inputManager);\r\n\t\t\tthis->inputManager = 0;\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nbool Demo::keyPressed(const OIS::KeyEvent &evt) {\r\n\t\r\n\t\/\/ Quit\r\n\tswitch(evt.key)\r\n\t{\r\n\t\tcase OIS::KC_ESCAPE:\r\n\t\t\tthis->shutDown = true;\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_UP:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 0, 5));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_DOWN:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 0, -5));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_H:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, 5, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_N:\r\n\t\t\tthis->camera->move(Ogre::Vector3(0, -5, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_G:\r\n\t\t\tthis->camera->move(Ogre::Vector3(5, 0, 0));\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase OIS::KC_B:\r\n\t\t\tthis->camera->move(Ogre::Vector3(-5, 0, 0));\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\tstd::cout << \"PosCamera : \" << this->camera->getPosition()[0] << \"\/\" << this->camera->getPosition()[1] << \"\/\" << this->camera->getPosition()[2] << std::endl;\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::keyReleased(const OIS::KeyEvent &evt) {\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mouseMoved(const OIS::MouseEvent &evt) {\r\n\t\r\n\tfloat mRotateSpeed = 0.1f;\r\n\t\r\n\tthis->camera->yaw(Ogre::Degree(-evt.state.X.rel * mRotateSpeed));\r\n\tthis->camera->pitch(Ogre::Degree(-evt.state.Y.rel * mRotateSpeed));\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool Demo::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\r\nint main(void) {\r\n\tDemo demo;\r\n\t\r\n\ttry {\r\n\t\tdemo.start();\r\n\t} catch( Ogre::Exception& e ) {\r\n\t\tstd::cerr << \"An exception has occured: \" << e.getFullDescription().c_str() << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_MAPPING_DistanceFromTargetMapping_INL\n#define SOFA_COMPONENT_MAPPING_DistanceFromTargetMapping_INL\n\n#include \"DistanceFromTargetMapping.h\"\n#include <sofa\/core\/visual\/VisualParams.h>\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\nusing namespace sofa::defaulttype;\n\n\ntemplate <class TIn, class TOut>\nDistanceFromTargetMapping<TIn, TOut>::DistanceFromTargetMapping()\n : Inherit()\n , f_indices(initData(&f_indices, \"indices\", \"Indices of the parent points\"))\n , f_targetPositions(initData(&f_targetPositions, \"targetPositions\", \"Positions to compute the distances from\"))\n , f_restDistances(initData(&f_restDistances, \"restLengths\", \"Rest lengths of the connections.\"))\n , _arrowSize(-1)\n , _color( 1,0,0,1 )\n{\n}\n\ntemplate <class TIn, class TOut>\nDistanceFromTargetMapping<TIn, TOut>::~DistanceFromTargetMapping()\n{\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::createTarget( unsigned index, InCoord position, Real distance)\n{\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::WriteAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n\n indices.push_back(index);\n targetPositions.push_back(position);\n distances.push_back(distance);\n\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::createTarget index \" << index << \" at position \" << position << \", distance = \" << distances << endl;\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::updateTarget( unsigned index, InCoord position)\n{\n helper::WriteAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::updateTarget index \" << index << \" at position \" << position << endl;\n\n \/\/ find the target with given index\n unsigned i=0; while(i<indices.size() && indices[i]!=index) i++;\n\n targetPositions[i] = position;\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::clear()\n{\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n helper::WriteAccessor< Data<InVecCoord > > positions(f_targetPositions);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n distances.clear();\n positions.clear();\n indices.clear();\n\n this->getToModel()->resize( 0 );\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::init()\n{\n assert( f_indices.getValue().size()==f_targetPositions.getValue().size()) ;\n\n \/\/ unset distances are set to 0\n if(f_restDistances.getValue().size() != f_indices.getValue().size())\n {\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n unsigned prevsize = distances.size();\n distances.resize( f_indices.getValue().size() );\n for(unsigned i=prevsize; i<distances.size(); i++ )\n distances[i] = 0;\n }\n\n this->getToModel()->resize( f_indices.getValue().size() );\n\n\n baseMatrices.resize( 1 );\n baseMatrices[0] = &jacobian;\n\n stiffnessBaseMatrices.resize(1);\n stiffnessBaseMatrices[0] = &K;\n\n this->Inherit::init(); \/\/ applies the mapping, so after the Data init\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::apply(const core::MechanicalParams * \/*mparams*\/ , Data<OutVecCoord>& dOut, const Data<InVecCoord>& dIn)\n{\n helper::WriteAccessor< Data<OutVecCoord> > out = dOut;\n helper::ReadAccessor< Data<InVecCoord> > in = dIn;\n helper::WriteAccessor<Data<vector<Real> > > restDistances(f_restDistances);\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::ReadAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n\n jacobian.resizeBlocks(out.size(),in.size());\n directions.resize(out.size());\n invlengths.resize(out.size());\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n InDeriv& gap = directions[i];\n gap = TIn::coordDifference(in[indices[i]],targetPositions[i]);\n Real gapNorm = TIn::getDPos(gap).norm();\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, gap = \" << gap <<\", norm = \" << gapNorm << endl;\n out[i] = gapNorm - restDistances[i]; \/\/ output\n\n if( gapNorm>1.e-10 )\n {\n invlengths[i] = 1\/gapNorm;\n gap *= invlengths[i];\n }\n else\n {\n invlengths[i] = 0;\n gap = InDeriv();\n gap[0]=1.0; \/\/ arbitrary unit vector\n }\n\n\/\/ jacobian.beginRow(i);\n for(unsigned j=0; j<Nout; j++)\n {\n for(unsigned k=0; k<Nin; k++ )\n {\n jacobian.insertBack( i*Nout+j, indices[i]*Nin+k, gap[k] );\n\/\/ jacobian.add( i*Nout+j, indices[i]*Nin+k, gap[k] );\n }\n }\n\n }\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, in = \" << in << endl;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, target positions = \" << positions << endl;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, out = \" << out << endl;\n\n jacobian.compress();\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, jacobian: \"<<endl<< jacobian << endl;\n\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJ(const core::MechanicalParams * \/*mparams*\/ , Data<OutVecDeriv>& dOut, const Data<InVecDeriv>& dIn)\n{\n if( jacobian.rowSize() > 0 )\n jacobian.mult(dOut,dIn);\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJT(const core::MechanicalParams * \/*mparams*\/ , Data<InVecDeriv>& dIn, const Data<OutVecDeriv>& dOut)\n{\n if( jacobian.rowSize() > 0 )\n jacobian.addMultTranspose(dIn,dOut);\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJT(const core::ConstraintParams*, Data<InMatrixDeriv>& , const Data<OutMatrixDeriv>& )\n{\n \/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::applyJT does nothing \" << endl;\n}\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyDJT(const core::MechanicalParams* mparams, core::MultiVecDerivId parentDfId, core::ConstMultiVecDerivId )\n{\n helper::WriteAccessor<Data<InVecDeriv> > parentForce (*parentDfId[this->fromModel.get(mparams)].write());\n helper::ReadAccessor<Data<InVecDeriv> > parentDisplacement (*mparams->readDx(this->fromModel)); \/\/ parent displacement\n Real kfactor = mparams->kFactor();\n helper::ReadAccessor<Data<OutVecDeriv> > childForce (*mparams->readF(this->toModel));\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n Mat<Nin,Nin,Real> b; \/\/ = (I - uu^T)\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n if( j==k )\n b[j][k] = 1. - directions[i][j]*directions[i][k];\n else\n b[j][k] = - directions[i][j]*directions[i][k];\n }\n }\n b *= childForce[i][0] * invlengths[i] * kfactor; \/\/ (I - uu^T)*f\/l*kfactor do not forget kfactor !\n \/\/ note that computing a block is not efficient here, but it would makes sense for storing a stiffness matrix\n\n InDeriv dx = parentDisplacement[indices[i]];\n InDeriv df;\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n df[j]+=b[j][k]*dx[k];\n }\n }\n \/\/ InDeriv df = b*dx;\n parentForce[indices[i]] += df;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::applyDJT, df = \" << df << endl;\n }\n}\n\n\n\n\ntemplate <class TIn, class TOut>\nconst sofa::defaulttype::BaseMatrix* DistanceFromTargetMapping<TIn, TOut>::getJ()\n{\n return &jacobian;\n}\n\ntemplate <class TIn, class TOut>\nconst vector<sofa::defaulttype::BaseMatrix*>* DistanceFromTargetMapping<TIn, TOut>::getJs()\n{\n return &baseMatrices;\n}\n\ntemplate <class TIn, class TOut>\nconst vector<defaulttype::BaseMatrix*>* DistanceFromTargetMapping<TIn, TOut>::getKs()\n{\n\/\/ helper::ReadAccessor<Data<OutVecDeriv> > childForce (*this->toModel->read(core::ConstVecDerivId::force()));\n const OutVecDeriv& childForce = this->toModel->readForces().ref();\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::ReadAccessor<Data<InVecCoord> > in (*this->fromModel->read(core::ConstVecCoordId::position()));\n\n K.resizeBlocks(in.size(),in.size());\n for(size_t i=0; i<indices.size(); i++)\n {\n size_t idx = indices[i];\n\n Mat<Nin,Nin,Real> b; \/\/ = (I - uu^T)\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n if( j==k )\n b[j][k] = 1. - directions[i][j]*directions[i][k];\n else\n b[j][k] = - directions[i][j]*directions[i][k];\n }\n }\n b *= childForce[i][0] * invlengths[i]; \/\/ (I - uu^T)*f\/l\n\n\/\/ std::cerr<<SOFA_CLASS_METHOD<<childForce[i][0]<<std::endl;\n\n K.beginBlockRow(idx);\n K.createBlock(idx,b);\n K.endBlockRow();\n }\n K.compress();\n\n return &stiffnessBaseMatrices;\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::draw(const core::visual::VisualParams* vparams)\n{\n if( _arrowSize<0 ) return;\n\n typename core::behavior::MechanicalState<In>::ReadVecCoord pos = this->getFromModel()->readPositions();\n helper::ReadAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n\tvector< Vector3 > points;\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n points.push_back( Vector3(TIn::getCPos(targetPositions[i]) ) );\n points.push_back( Vector3(TIn::getCPos(pos[indices[i]]) ) );\n }\n\n if( !_arrowSize )\n vparams->drawTool()->drawLines ( points, 1, _color );\n else\n for (unsigned int i=0; i<points.size()\/2; ++i)\n vparams->drawTool()->drawArrow( points[2*i+1], points[2*i], _arrowSize, _color );\n\n}\n\n\n\n} \/\/ namespace mapping\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n<commit_msg>r11095\/sofa : Fix: Rigid manipulation with CompliantAttachButtonSetting component<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_MAPPING_DistanceFromTargetMapping_INL\n#define SOFA_COMPONENT_MAPPING_DistanceFromTargetMapping_INL\n\n#include \"DistanceFromTargetMapping.h\"\n#include <sofa\/core\/visual\/VisualParams.h>\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\nusing namespace sofa::defaulttype;\n\n\ntemplate <class TIn, class TOut>\nDistanceFromTargetMapping<TIn, TOut>::DistanceFromTargetMapping()\n : Inherit()\n , f_indices(initData(&f_indices, \"indices\", \"Indices of the parent points\"))\n , f_targetPositions(initData(&f_targetPositions, \"targetPositions\", \"Positions to compute the distances from\"))\n , f_restDistances(initData(&f_restDistances, \"restLengths\", \"Rest lengths of the connections.\"))\n , _arrowSize(-1)\n , _color( 1,0,0,1 )\n{\n}\n\ntemplate <class TIn, class TOut>\nDistanceFromTargetMapping<TIn, TOut>::~DistanceFromTargetMapping()\n{\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::createTarget( unsigned index, InCoord position, Real distance)\n{\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::WriteAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n\n indices.push_back(index);\n targetPositions.push_back(position);\n distances.push_back(distance);\n\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::createTarget index \" << index << \" at position \" << position << \", distance = \" << distances << endl;\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::updateTarget( unsigned index, InCoord position)\n{\n helper::WriteAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::updateTarget index \" << index << \" at position \" << position << endl;\n\n \/\/ find the target with given index\n unsigned i=0; while(i<indices.size() && indices[i]!=index) i++;\n\n targetPositions[i] = position;\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::clear()\n{\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n helper::WriteAccessor< Data<InVecCoord > > positions(f_targetPositions);\n helper::WriteAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n distances.clear();\n positions.clear();\n indices.clear();\n\n this->getToModel()->resize( 0 );\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::init()\n{\n assert( f_indices.getValue().size()==f_targetPositions.getValue().size()) ;\n\n \/\/ unset distances are set to 0\n if(f_restDistances.getValue().size() != f_indices.getValue().size())\n {\n helper::WriteAccessor< Data< vector<Real> > > distances(f_restDistances);\n unsigned prevsize = distances.size();\n distances.resize( f_indices.getValue().size() );\n for(unsigned i=prevsize; i<distances.size(); i++ )\n distances[i] = 0;\n }\n\n this->getToModel()->resize( f_indices.getValue().size() );\n\n\n baseMatrices.resize( 1 );\n baseMatrices[0] = &jacobian;\n\n stiffnessBaseMatrices.resize(1);\n stiffnessBaseMatrices[0] = &K;\n\n this->Inherit::init(); \/\/ applies the mapping, so after the Data init\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::apply(const core::MechanicalParams * \/*mparams*\/ , Data<OutVecCoord>& dOut, const Data<InVecCoord>& dIn)\n{\n helper::WriteAccessor< Data<OutVecCoord> > out = dOut;\n helper::ReadAccessor< Data<InVecCoord> > in = dIn;\n helper::WriteAccessor<Data<vector<Real> > > restDistances(f_restDistances);\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::ReadAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n\n jacobian.resizeBlocks(out.size(),in.size());\n directions.resize(out.size());\n invlengths.resize(out.size());\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n InDeriv& gap = directions[i];\n TIn::setDPos(gap, TIn::getDPos(TIn::coordDifference(in[indices[i]],targetPositions[i]))); \/\/Hack for Rigid template, TODO: create a specialized function.\n Real gapNorm = TIn::getDPos(gap).norm();\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, gap = \" << gap <<\", norm = \" << gapNorm << endl;\n out[i] = gapNorm - restDistances[i]; \/\/ output\n\n if( gapNorm>1.e-10 )\n {\n invlengths[i] = 1\/gapNorm;\n gap *= invlengths[i];\n }\n else\n {\n invlengths[i] = 0;\n gap = InDeriv();\n gap[0]=1.0; \/\/ arbitrary unit vector\n }\n\n\/\/ jacobian.beginRow(i);\n for(unsigned j=0; j<Nout; j++)\n {\n for(unsigned k=0; k<Nin; k++ )\n {\n jacobian.insertBack( i*Nout+j, indices[i]*Nin+k, gap[k] );\n\/\/ jacobian.add( i*Nout+j, indices[i]*Nin+k, gap[k] );\n }\n }\n\n }\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, in = \" << in << endl;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, target positions = \" << positions << endl;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, out = \" << out << endl;\n\n jacobian.compress();\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::apply, jacobian: \"<<endl<< jacobian << endl;\n\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJ(const core::MechanicalParams * \/*mparams*\/ , Data<OutVecDeriv>& dOut, const Data<InVecDeriv>& dIn)\n{\n if( jacobian.rowSize() > 0 )\n jacobian.mult(dOut,dIn);\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJT(const core::MechanicalParams * \/*mparams*\/ , Data<InVecDeriv>& dIn, const Data<OutVecDeriv>& dOut)\n{\n if( jacobian.rowSize() > 0 )\n jacobian.addMultTranspose(dIn,dOut);\n}\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyJT(const core::ConstraintParams*, Data<InMatrixDeriv>& , const Data<OutMatrixDeriv>& )\n{\n \/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::applyJT does nothing \" << endl;\n}\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::applyDJT(const core::MechanicalParams* mparams, core::MultiVecDerivId parentDfId, core::ConstMultiVecDerivId )\n{\n helper::WriteAccessor<Data<InVecDeriv> > parentForce (*parentDfId[this->fromModel.get(mparams)].write());\n helper::ReadAccessor<Data<InVecDeriv> > parentDisplacement (*mparams->readDx(this->fromModel)); \/\/ parent displacement\n Real kfactor = mparams->kFactor();\n helper::ReadAccessor<Data<OutVecDeriv> > childForce (*mparams->readF(this->toModel));\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n Mat<Nin,Nin,Real> b; \/\/ = (I - uu^T)\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n if( j==k )\n b[j][k] = 1. - directions[i][j]*directions[i][k];\n else\n b[j][k] = - directions[i][j]*directions[i][k];\n }\n }\n b *= childForce[i][0] * invlengths[i] * kfactor; \/\/ (I - uu^T)*f\/l*kfactor do not forget kfactor !\n \/\/ note that computing a block is not efficient here, but it would makes sense for storing a stiffness matrix\n\n InDeriv dx = parentDisplacement[indices[i]];\n InDeriv df;\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n df[j]+=b[j][k]*dx[k];\n }\n }\n \/\/ InDeriv df = b*dx;\n parentForce[indices[i]] += df;\n\/\/ cerr<<\"DistanceFromTargetMapping<TIn, TOut>::applyDJT, df = \" << df << endl;\n }\n}\n\n\n\n\ntemplate <class TIn, class TOut>\nconst sofa::defaulttype::BaseMatrix* DistanceFromTargetMapping<TIn, TOut>::getJ()\n{\n return &jacobian;\n}\n\ntemplate <class TIn, class TOut>\nconst vector<sofa::defaulttype::BaseMatrix*>* DistanceFromTargetMapping<TIn, TOut>::getJs()\n{\n return &baseMatrices;\n}\n\ntemplate <class TIn, class TOut>\nconst vector<defaulttype::BaseMatrix*>* DistanceFromTargetMapping<TIn, TOut>::getKs()\n{\n\/\/ helper::ReadAccessor<Data<OutVecDeriv> > childForce (*this->toModel->read(core::ConstVecDerivId::force()));\n const OutVecDeriv& childForce = this->toModel->readForces().ref();\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n helper::ReadAccessor<Data<InVecCoord> > in (*this->fromModel->read(core::ConstVecCoordId::position()));\n\n K.resizeBlocks(in.size(),in.size());\n for(size_t i=0; i<indices.size(); i++)\n {\n size_t idx = indices[i];\n\n Mat<Nin,Nin,Real> b; \/\/ = (I - uu^T)\n for(unsigned j=0; j<Nin; j++)\n {\n for(unsigned k=0; k<Nin; k++)\n {\n if( j==k )\n b[j][k] = 1. - directions[i][j]*directions[i][k];\n else\n b[j][k] = - directions[i][j]*directions[i][k];\n }\n }\n b *= childForce[i][0] * invlengths[i]; \/\/ (I - uu^T)*f\/l\n\n\/\/ std::cerr<<SOFA_CLASS_METHOD<<childForce[i][0]<<std::endl;\n\n K.beginBlockRow(idx);\n K.createBlock(idx,b);\n K.endBlockRow();\n }\n K.compress();\n\n return &stiffnessBaseMatrices;\n}\n\n\n\ntemplate <class TIn, class TOut>\nvoid DistanceFromTargetMapping<TIn, TOut>::draw(const core::visual::VisualParams* vparams)\n{\n if( _arrowSize<0 ) return;\n\n typename core::behavior::MechanicalState<In>::ReadVecCoord pos = this->getFromModel()->readPositions();\n helper::ReadAccessor< Data<InVecCoord > > targetPositions(f_targetPositions);\n helper::ReadAccessor< Data<vector<unsigned> > > indices(f_indices);\n\n\tvector< Vector3 > points;\n\n for(unsigned i=0; i<indices.size(); i++ )\n {\n points.push_back( Vector3(TIn::getCPos(targetPositions[i]) ) );\n points.push_back( Vector3(TIn::getCPos(pos[indices[i]]) ) );\n }\n\n if( !_arrowSize )\n vparams->drawTool()->drawLines ( points, 1, _color );\n else\n for (unsigned int i=0; i<points.size()\/2; ++i)\n vparams->drawTool()->drawArrow( points[2*i+1], points[2*i], _arrowSize, _color );\n\n}\n\n\n\n} \/\/ namespace mapping\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2012,2013 Renard Wellnitz\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <jni.h>\n#include \"image_processing.h\"\n#include <cstring>\n#include \"android\/bitmap.h\"\n#include \"allheaders.h\"\n#include <sstream>\n#include <iostream>\n#include <pthread.h>\n#include <cmath>\n#include \"pageseg.h\"\n#include \"PixBlurDetect.h\"\n#include \"pixFunc.hpp\"\n#include \"combine_pixa.h\"\n#include \"ProgressCallback.h\"\n#include <fcntl.h>\n#include <sstream>\n#include <cmath>\n\n\nusing namespace std;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\n static jmethodID onProgressImage, onProgressText, onLayoutElements;\n static jfieldID field_mNativeData;\n static JavaVM* g_vm;\n\n\n class native_data_t : public ProgressCallback{\n\n public:\n virtual void sendMessage(int message) {\n JNIEnv *env;\n bool needDetach = false;\n \/\/ double check it's all ok\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->CallVoidMethod(cachedObject, onProgressText, message);\n\n if (env->ExceptionCheck()) {\n env->ExceptionDescribe();\n }\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n }\n\n virtual void sendPix(Pix* pix) {\n JNIEnv *env;\n bool needDetach = false;\n \/\/ double check it's all ok\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->CallVoidMethod(cachedObject, onProgressImage, (jlong) pix);\n\n if (env->ExceptionCheck()) {\n env->ExceptionDescribe();\n }\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n }\n\n jobject cachedObject;\n\n ~native_data_t(){\n JNIEnv *env;\n bool needDetach = false;\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->DeleteGlobalRef(cachedObject);\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n\n }\n };\n\n\n static inline native_data_t * get_native_data(JNIEnv *env, jobject object) {\n return (native_data_t *) (env->GetLongField(object, field_mNativeData));\n }\n\n jint JNI_OnLoad(JavaVM* vm, void* reserved) {\n g_vm = vm;\n return JNI_VERSION_1_6;\n }\n\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeClassInit(JNIEnv *env, jobject _thiz) {\n jclass cls = env->FindClass(\"com\/googlecode\/tesseract\/android\/NativeBinding\");\n onProgressImage = env->GetMethodID(cls, \"onProgressImage\", \"(J)V\");\n onProgressText = env->GetMethodID(cls, \"onProgressText\", \"(I)V\");\n onLayoutElements = env->GetMethodID(cls, \"onLayoutElements\", \"(JJ)V\");\n field_mNativeData = env->GetFieldID(cls, \"mNativeData\", \"J\");\n }\n\n void JNI_OnUnload(JavaVM *vm, void *reserved) {\n }\n\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeConstruct(JNIEnv* env, jobject object) {\n\n native_data_t *nat = new native_data_t;\n\n nat->cachedObject = env->NewGlobalRef(object);\n\n env->SetLongField(object, field_mNativeData, (jlong) nat);\n }\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeDestruct(JNIEnv* env, jobject object) {\n native_data_t *nat = (native_data_t *) (env->GetLongField(object, field_mNativeData));\n delete nat;\n }\n\n jlongArray Java_com_googlecode_tesseract_android_NativeBinding_combineSelectedPixa(JNIEnv *env, jobject thiz, jlong nativePixaText, jlong nativePixaImage, jintArray selectedTexts, jintArray selectedImages) {\n LOGV(__FUNCTION__);\n Pixa *pixaTexts = (PIXA *) nativePixaText;\n Pixa *pixaImages = (PIXA *) nativePixaImage;\n jint* textindexes = env->GetIntArrayElements(selectedTexts, NULL);\n jsize textCount = env->GetArrayLength(selectedTexts);\n jint* imageindexes = env->GetIntArrayElements(selectedImages, NULL);\n jsize imageCount = env->GetArrayLength(selectedImages);\n\n Pix* pixFinal;\n Pix* pixOcr;\n Boxa* boxaColumns;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n combineSelectedPixa(pixaTexts, pixaImages, textindexes, textCount, imageindexes, imageCount, nat, &pixFinal, &pixOcr, &boxaColumns, false);\n nat->sendPix(pixFinal);\n\n jlongArray result;\n result = env->NewLongArray(3);\n if (result == NULL) {\n return NULL; \/* out of memory error thrown *\/\n }\n\n jlong fill[3];\n fill[0] = (jlong) pixFinal;\n fill[1] = (jlong) pixOcr;\n fill[2] = (jlong) boxaColumns;\n \/\/ move from the temp structure to the java structure\n env->SetLongArrayRegion(result, 0, 3, fill);\n\n env->ReleaseIntArrayElements(selectedTexts, textindexes, 0);\n env->ReleaseIntArrayElements(selectedImages, imageindexes, 0);\n return result;\n }\n\n\n\n jint Java_com_googlecode_tesseract_android_NativeBinding_nativeAnalyseLayout(JNIEnv *env, jobject thiz, jint nativePix) {\n LOGV(__FUNCTION__);\n Pix *pixOrg = (PIX *) nativePix;\n Pix* pixTextlines = NULL;\n Pixa* pixaTexts, *pixaImages;\n Pix* pixb, *pixhm;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n nat->sendMessage(MESSAGE_IMAGE_DETECTION);\n\n pixb = pixPrepareLayoutAnalysis(pixOrg, nat);\n \n nat->sendPix(pixb);\n\n segmentComplexLayout(pixOrg, NULL, pixb, &pixaImages, &pixaTexts, nat, false);\n \n pixDestroy(&pixb);\n\n env->CallVoidMethod(thiz, onLayoutElements, (jlong)pixaTexts, (jlong)pixaImages);\n\n return (jint) 0;\n }\n\n jobject Java_com_renard_ocr_cropimage_image_1processing_Blur_nativeBlurDetect(JNIEnv *env, jobject thiz, jlong nativePix) {\n Pix *pixOrg = (PIX *) nativePix;\n PixBlurDetect blurDetector(false);\n l_float32 blurValue;\n L_TIMER timer = startTimerNested();\n Box* maxBlurLoc = NULL;\n Pix* pixBlended = blurDetector.makeBlurIndicator(pixOrg,&blurValue, &maxBlurLoc);\n l_int32 w,h,x,y;\n boxGetGeometry(maxBlurLoc,&x,&y,&w,&h);\n \/\/pixRenderBox(pixBlended,maxBlurLoc,2,L_SET_PIXELS);\n \/\/create result\n jclass cls = env->FindClass(\"com\/renard\/ocr\/cropimage\/image_processing\/BlurDetectionResult\");\n jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(JDJ)V\");\n return env->NewObject(cls, constructor, (jlong)pixBlended, (jdouble)blurValue, (jlong)maxBlurLoc);\n }\n\n jlong Java_com_googlecode_tesseract_android_NativeBinding_nativeOCRBook(JNIEnv *env, jobject thiz, jlong nativePix) {\n LOGV(__FUNCTION__);\n Pix *pixOrg = (PIX *) nativePix;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n Pix* pixText = pixPrepareForOcr(pixOrg, nat);\n\n return (jlong)pixText;\n\n }\n\n#ifdef __cplusplus\n}\n#endif \/* __cplusplus *\/\n<commit_msg>fix: crash when using column detection<commit_after>\/*\n * Copyright (C) 2012,2013 Renard Wellnitz\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <jni.h>\n#include \"image_processing.h\"\n#include <cstring>\n#include \"android\/bitmap.h\"\n#include \"allheaders.h\"\n#include <sstream>\n#include <iostream>\n#include <pthread.h>\n#include <cmath>\n#include \"pageseg.h\"\n#include \"PixBlurDetect.h\"\n#include \"pixFunc.hpp\"\n#include \"combine_pixa.h\"\n#include \"ProgressCallback.h\"\n#include <fcntl.h>\n#include <sstream>\n#include <cmath>\n\n\nusing namespace std;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\n static jmethodID onProgressImage, onProgressText, onLayoutElements;\n static jfieldID field_mNativeData;\n static JavaVM* g_vm;\n\n\n class native_data_t : public ProgressCallback{\n\n public:\n virtual void sendMessage(int message) {\n JNIEnv *env;\n bool needDetach = false;\n \/\/ double check it's all ok\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->CallVoidMethod(cachedObject, onProgressText, message);\n\n if (env->ExceptionCheck()) {\n env->ExceptionDescribe();\n }\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n }\n\n virtual void sendPix(Pix* pix) {\n JNIEnv *env;\n bool needDetach = false;\n \/\/ double check it's all ok\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->CallVoidMethod(cachedObject, onProgressImage, (jlong) pix);\n\n if (env->ExceptionCheck()) {\n env->ExceptionDescribe();\n }\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n }\n\n jobject cachedObject;\n\n ~native_data_t(){\n JNIEnv *env;\n bool needDetach = false;\n int getEnvStat = g_vm->GetEnv((void **) &env, JNI_VERSION_1_6);\n if (getEnvStat == JNI_EDETACHED) {\n LOGW(\"GetEnv: not attached\");\n needDetach = true;\n if (g_vm->AttachCurrentThread(&env, NULL) != 0) {\n LOGE(\"Failed to attach\");\n return;\n }\n }\n\n env->DeleteGlobalRef(cachedObject);\n\n if (needDetach) {\n g_vm->DetachCurrentThread();\n }\n\n }\n };\n\n\n static inline native_data_t * get_native_data(JNIEnv *env, jobject object) {\n return (native_data_t *) (env->GetLongField(object, field_mNativeData));\n }\n\n jint JNI_OnLoad(JavaVM* vm, void* reserved) {\n g_vm = vm;\n return JNI_VERSION_1_6;\n }\n\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeClassInit(JNIEnv *env, jobject _thiz) {\n jclass cls = env->FindClass(\"com\/googlecode\/tesseract\/android\/NativeBinding\");\n onProgressImage = env->GetMethodID(cls, \"onProgressImage\", \"(J)V\");\n onProgressText = env->GetMethodID(cls, \"onProgressText\", \"(I)V\");\n onLayoutElements = env->GetMethodID(cls, \"onLayoutElements\", \"(JJ)V\");\n field_mNativeData = env->GetFieldID(cls, \"mNativeData\", \"J\");\n }\n\n void JNI_OnUnload(JavaVM *vm, void *reserved) {\n }\n\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeConstruct(JNIEnv* env, jobject object) {\n\n native_data_t *nat = new native_data_t;\n\n nat->cachedObject = env->NewGlobalRef(object);\n\n env->SetLongField(object, field_mNativeData, (jlong) nat);\n }\n\n void Java_com_googlecode_tesseract_android_NativeBinding_nativeDestruct(JNIEnv* env, jobject object) {\n native_data_t *nat = (native_data_t *) (env->GetLongField(object, field_mNativeData));\n delete nat;\n }\n\n jlongArray Java_com_googlecode_tesseract_android_NativeBinding_combineSelectedPixa(JNIEnv *env, jobject thiz, jlong nativePixaText, jlong nativePixaImage, jintArray selectedTexts, jintArray selectedImages) {\n LOGV(__FUNCTION__);\n Pixa *pixaTexts = (PIXA *) nativePixaText;\n Pixa *pixaImages = (PIXA *) nativePixaImage;\n jint* textindexes = env->GetIntArrayElements(selectedTexts, NULL);\n jsize textCount = env->GetArrayLength(selectedTexts);\n jint* imageindexes = env->GetIntArrayElements(selectedImages, NULL);\n jsize imageCount = env->GetArrayLength(selectedImages);\n\n Pix* pixFinal;\n Pix* pixOcr;\n Boxa* boxaColumns;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n combineSelectedPixa(pixaTexts, pixaImages, textindexes, textCount, imageindexes, imageCount, nat, &pixFinal, &pixOcr, &boxaColumns, false);\n nat->sendPix(pixFinal);\n\n jlongArray result;\n result = env->NewLongArray(3);\n if (result == NULL) {\n return NULL; \/* out of memory error thrown *\/\n }\n\n jlong fill[3];\n fill[0] = (jlong) pixFinal;\n fill[1] = (jlong) pixOcr;\n fill[2] = (jlong) boxaColumns;\n \/\/ move from the temp structure to the java structure\n env->SetLongArrayRegion(result, 0, 3, fill);\n\n env->ReleaseIntArrayElements(selectedTexts, textindexes, 0);\n env->ReleaseIntArrayElements(selectedImages, imageindexes, 0);\n return result;\n }\n\n\n\n jint Java_com_googlecode_tesseract_android_NativeBinding_nativeAnalyseLayout(JNIEnv *env, jobject thiz, jlong nativePix) {\n LOGV(__FUNCTION__);\n Pix *pixOrg = (PIX *) nativePix;\n Pix* pixTextlines = NULL;\n Pixa* pixaTexts, *pixaImages;\n Pix* pixb, *pixhm;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n nat->sendMessage(MESSAGE_IMAGE_DETECTION);\n\n pixb = pixPrepareLayoutAnalysis(pixOrg, nat);\n \n nat->sendPix(pixb);\n\n segmentComplexLayout(pixOrg, NULL, pixb, &pixaImages, &pixaTexts, nat, false);\n \n pixDestroy(&pixb);\n\n env->CallVoidMethod(thiz, onLayoutElements, (jlong)pixaTexts, (jlong)pixaImages);\n\n return (jint) 0;\n }\n\n jobject Java_com_renard_ocr_cropimage_image_1processing_Blur_nativeBlurDetect(JNIEnv *env, jobject thiz, jlong nativePix) {\n Pix *pixOrg = (PIX *) nativePix;\n PixBlurDetect blurDetector(false);\n l_float32 blurValue;\n L_TIMER timer = startTimerNested();\n Box* maxBlurLoc = NULL;\n Pix* pixBlended = blurDetector.makeBlurIndicator(pixOrg,&blurValue, &maxBlurLoc);\n l_int32 w,h,x,y;\n boxGetGeometry(maxBlurLoc,&x,&y,&w,&h);\n \/\/pixRenderBox(pixBlended,maxBlurLoc,2,L_SET_PIXELS);\n \/\/create result\n jclass cls = env->FindClass(\"com\/renard\/ocr\/cropimage\/image_processing\/BlurDetectionResult\");\n jmethodID constructor = env->GetMethodID(cls, \"<init>\", \"(JDJ)V\");\n return env->NewObject(cls, constructor, (jlong)pixBlended, (jdouble)blurValue, (jlong)maxBlurLoc);\n }\n\n jlong Java_com_googlecode_tesseract_android_NativeBinding_nativeOCRBook(JNIEnv *env, jobject thiz, jlong nativePix) {\n LOGV(__FUNCTION__);\n Pix *pixOrg = (PIX *) nativePix;\n\n native_data_t *nat = get_native_data(env, thiz);\n\n Pix* pixText = pixPrepareForOcr(pixOrg, nat);\n\n return (jlong)pixText;\n\n }\n\n#ifdef __cplusplus\n}\n#endif \/* __cplusplus *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _WIN32\n\/\/ windows part\n#include \"libtorrent\/utf8.hpp\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _MODE_T_\ntypedef int mode_t;\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n#else\n\/\/ unix part\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <errno.h>\n\n#include <boost\/static_assert.hpp>\n\/\/ make sure the _FILE_OFFSET_BITS define worked\n\/\/ on this platform\nBOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);\n\n#endif\n\n#include <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n\n#ifdef WIN32\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstd::wstring ws;\n\t\t\tlibtorrent::utf8_wchar(s, ws);\n\t\t\tstd::size_t size = wcstombs(0, ws.c_str(), 0);\n\t\t\tif (size == std::size_t(-1)) return s;\n\t\t\tstd::string ret;\n\t\t\tret.resize(size);\n\t\t\tsize = wcstombs(&ret[0], ws.c_str(), size + 1);\n\t\t\tif (size == wchar_t(-1)) return s;\n\t\t\tret.resize(size);\n\t\t\treturn ret;\n\t\t}\n\t\tcatch(std::exception)\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t}\n#else\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\treturn s;\n\t}\n#endif\n\n}\n\nnamespace libtorrent\n{\n\n\tnamespace fs = boost::filesystem;\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tassert(path.is_complete());\n\t\t\tclose();\n#if defined(_WIN32) && defined(UNICODE)\n\t\t\tstd::wstring wpath(safe_convert(path.native_file_string()));\n\t\t\tm_fd = ::_wopen(\n\t\t\t\twpath.c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n#ifdef _WIN32\n\t\t\tm_fd = ::_open(\n#else\n\t\t\tm_fd = ::open(\n#endif\n\t\t\t\tutf8_native(path.native_file_string()).c_str()\n\t\t\t\t, map_open_mode(mode)\n#ifdef _WIN32\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n\t\t\t\t, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n#endif\n#endif\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n#ifdef _WIN32\n\t\t\t::_close(m_fd);\n#else\n\t\t\t::close(m_fd);\n#endif\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_in);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_read(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\t\/\/ TODO: Test this a bit more, what happens with random failures in\n\t\t\t\/\/ the files?\n\/\/\t\t\tif ((rand() % 100) > 80)\n\/\/\t\t\t\tthrow file_error(\"debug\");\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_write(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid set_size(size_type s)\n\t\t{\n\t\t\tsize_type pos = tell();\n\t\t\t\/\/ Only set size if current file size not equals s.\n\t\t\t\/\/ 2 as \"m\" argument is to be sure seek() sets SEEK_END on\n\t\t\t\/\/ all compilers.\n\t\t\tif(s != seek(0, 2))\n\t\t\t{\n\t\t\t\tseek(s - 1);\n\t\t\t\tchar dummy = 0;\n\t\t\t\tread(&dummy, 1);\n\t\t\t\tseek(s - 1);\n\t\t\t\twrite(&dummy, 1);\n\t\t\t}\n\t\t\tseek(pos);\n\t\t}\n\n\t\tsize_type seek(size_type offset, int m = 1)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef _WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(fs::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(fs::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::set_size(size_type s)\n\t{\n\t\tm_impl->set_size(s);\n\t}\n\n\tsize_type file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\treturn m_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<commit_msg>changed to use ftruncate to allocate files<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _WIN32\n\/\/ windows part\n#include \"libtorrent\/utf8.hpp\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _MODE_T_\ntypedef int mode_t;\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n#else\n\/\/ unix part\n#define _FILE_OFFSET_BITS 64\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <errno.h>\n\n#include <boost\/static_assert.hpp>\n\/\/ make sure the _FILE_OFFSET_BITS define worked\n\/\/ on this platform\nBOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);\n\n#endif\n\n#include <boost\/filesystem\/operations.hpp>\n#include \"libtorrent\/file.hpp\"\n#include <sstream>\n\n#ifndef O_BINARY\n#define O_BINARY 0\n#endif\n\n#ifndef O_RANDOM\n#define O_RANDOM 0\n#endif\n\n#ifdef UNICODE\n#include \"libtorrent\/storage.hpp\"\n#endif\n\n\nnamespace\n{\n\tenum { mode_in = 1, mode_out = 2 };\n\n\tmode_t map_open_mode(int m)\n\t{\n\t\tif (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;\n\t\tif (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;\n\t\tassert(false);\n\t\treturn 0;\n\t}\n\n#ifdef WIN32\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstd::wstring ws;\n\t\t\tlibtorrent::utf8_wchar(s, ws);\n\t\t\tstd::size_t size = wcstombs(0, ws.c_str(), 0);\n\t\t\tif (size == std::size_t(-1)) return s;\n\t\t\tstd::string ret;\n\t\t\tret.resize(size);\n\t\t\tsize = wcstombs(&ret[0], ws.c_str(), size + 1);\n\t\t\tif (size == wchar_t(-1)) return s;\n\t\t\tret.resize(size);\n\t\t\treturn ret;\n\t\t}\n\t\tcatch(std::exception)\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t}\n#else\n\tstd::string utf8_native(std::string const& s)\n\t{\n\t\treturn s;\n\t}\n#endif\n\n}\n\nnamespace libtorrent\n{\n\n\tnamespace fs = boost::filesystem;\n\n\tconst file::open_mode file::in(mode_in);\n\tconst file::open_mode file::out(mode_out);\n\n\tconst file::seek_mode file::begin(1);\n\tconst file::seek_mode file::end(2);\n\n\tstruct file::impl\n\t{\n\t\timpl()\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{}\n\n\t\timpl(fs::path const& path, int mode)\n\t\t\t: m_fd(-1)\n\t\t\t, m_open_mode(0)\n\t\t{\n\t\t\topen(path, mode);\n\t\t}\n\n\t\t~impl()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tvoid open(fs::path const& path, int mode)\n\t\t{\n\t\t\tassert(path.is_complete());\n\t\t\tclose();\n#if defined(_WIN32) && defined(UNICODE)\n\t\t\tstd::wstring wpath(safe_convert(path.native_file_string()));\n\t\t\tm_fd = ::_wopen(\n\t\t\t\twpath.c_str()\n\t\t\t\t, map_open_mode(mode)\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n#ifdef _WIN32\n\t\t\tm_fd = ::_open(\n#else\n\t\t\tm_fd = ::open(\n#endif\n\t\t\t\tutf8_native(path.native_file_string()).c_str()\n\t\t\t\t, map_open_mode(mode)\n#ifdef _WIN32\n\t\t\t\t, S_IREAD | S_IWRITE);\n#else\n\t\t\t\t, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n#endif\n#endif\n\t\t\tif (m_fd == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"open failed: '\" << path.native_file_string() << \"'. \"\n\t\t\t\t\t<< strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\tm_open_mode = mode;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_fd == -1) return;\n\n#ifdef _WIN32\n\t\t\t::_close(m_fd);\n#else\n\t\t\t::close(m_fd);\n#endif\n\t\t\tm_fd = -1;\n\t\t\tm_open_mode = 0;\n\t\t}\n\n\t\tsize_type read(char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_in);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_read(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::read(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"read failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type write(const char* buf, size_type num_bytes)\n\t\t{\n\t\t\tassert(m_open_mode & mode_out);\n\t\t\tassert(m_fd != -1);\n\n\t\t\t\/\/ TODO: Test this a bit more, what happens with random failures in\n\t\t\t\/\/ the files?\n\/\/\t\t\tif ((rand() % 100) > 80)\n\/\/\t\t\t\tthrow file_error(\"debug\");\n\n#ifdef _WIN32\n\t\t\tsize_type ret = ::_write(m_fd, buf, num_bytes);\n#else\n\t\t\tsize_type ret = ::write(m_fd, buf, num_bytes);\n#endif\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"write failed: \" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tvoid set_size(size_type s)\n\t\t{\n#ifdef _WIN32\n#error file.cpp is for posix systems only. use file_win.cpp on windows\n#else\n\t\t\tif (ftruncate(m_fd, s) < 0)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"ftruncate failed: '\" << strerror(errno);\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n#endif\n\t\t}\n\n\t\tsize_type seek(size_type offset, int m = 1)\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n\t\t\tint seekdir = (m == 1)?SEEK_SET:SEEK_END;\n#ifdef _WIN32\n\t\t\tsize_type ret = _lseeki64(m_fd, offset, seekdir);\n#else\n\t\t\tsize_type ret = lseek(m_fd, offset, seekdir);\n#endif\n\n\t\t\t\/\/ For some strange reason this fails\n\t\t\t\/\/ on win32. Use windows specific file\n\t\t\t\/\/ wrapper instead.\n\t\t\tif (ret == -1)\n\t\t\t{\n\t\t\t\tstd::stringstream msg;\n\t\t\t\tmsg << \"seek failed: '\" << strerror(errno)\n\t\t\t\t\t<< \"' fd: \" << m_fd\n\t\t\t\t\t<< \" offset: \" << offset\n\t\t\t\t\t<< \" seekdir: \" << seekdir;\n\t\t\t\tthrow file_error(msg.str());\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tsize_type tell()\n\t\t{\n\t\t\tassert(m_open_mode);\n\t\t\tassert(m_fd != -1);\n\n#ifdef _WIN32\n\t\t\treturn _telli64(m_fd);\n#else\n\t\t\treturn lseek(m_fd, 0, SEEK_CUR);\n#endif\n\t\t}\n\n\t\tint m_fd;\n\t\tint m_open_mode;\n\t};\n\n\t\/\/ pimpl forwardings\n\n\tfile::file() : m_impl(new impl()) {}\n\n\tfile::file(fs::path const& p, file::open_mode m)\n\t\t: m_impl(new impl(p, m.m_mask))\n\t{}\n\n\tfile::~file() {}\n\n\tvoid file::open(fs::path const& p, file::open_mode m)\n\t{\n\t\tm_impl->open(p, m.m_mask);\n\t}\n\n\tvoid file::close()\n\t{\n\t\tm_impl->close();\n\t}\n\n\tsize_type file::write(const char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->write(buf, num_bytes);\n\t}\n\n\tsize_type file::read(char* buf, size_type num_bytes)\n\t{\n\t\treturn m_impl->read(buf, num_bytes);\n\t}\n\n\tvoid file::set_size(size_type s)\n\t{\n\t\tm_impl->set_size(s);\n\t}\n\n\tsize_type file::seek(size_type pos, file::seek_mode m)\n\t{\n\t\treturn m_impl->seek(pos, m.m_val);\n\t}\n\n\tsize_type file::tell()\n\t{\n\t\treturn m_impl->tell();\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) Extensible Service Proxy Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"src\/api_manager\/service_management_fetch.h\"\n\nnamespace google {\nnamespace api_manager {\n\nnamespace {\n\/\/ The default HTTP request timeout in ms.\nconst int kHttpRequestTimeout = 1000;\n\/\/ Maximum number of HTTP request retries\nconst int kHttpRequestRetries = 5;\n\n\/\/ Default service management API url\nconst char kServiceManagementHost[] =\n \"https:\/\/servicemanagement.googleapis.com\";\nconst char kServiceManagementPath[] =\n \"\/google.api.servicemanagement.v1.ServiceManager\";\n} \/\/ namespace anonymous\n\nServiceManagementFetch::ServiceManagementFetch(\n std::shared_ptr<context::GlobalContext> global_context)\n : global_context_(global_context), host_(kServiceManagementHost) {\n if (global_context_->server_config() &&\n global_context->server_config()->has_service_management_config()) {\n if (!global_context->server_config()\n ->service_management_config()\n .url()\n .empty()) {\n host_ =\n global_context->server_config()->service_management_config().url();\n }\n }\n\n if (global_context_->service_account_token()) {\n \/\/ register auth token for servicemanagement services\n global_context_->service_account_token()->SetAudience(\n auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES,\n host_ + kServiceManagementPath);\n }\n}\n\nvoid ServiceManagementFetch::GetConfig(const std::string& config_id,\n HttpCallbackFunction on_done) {\n const std::string url = host_ + \"\/v1\/services\/\" +\n global_context_->service_name() + \"\/configs\/\" +\n config_id;\n Call(url, on_done);\n}\n\nvoid ServiceManagementFetch::GetRollouts(HttpCallbackFunction on_done) {\n const std::string url = host_ + \"\/v1\/services\/\" +\n global_context_->service_name() +\n \"\/rollouts?filter=status=SUCCESS\";\n Call(url, on_done);\n}\n\nvoid ServiceManagementFetch::Call(const std::string& url,\n HttpCallbackFunction on_done) {\n std::unique_ptr<HTTPRequest> http_request(new HTTPRequest([this, url,\n on_done](\n utils::Status status, std::map<std::string, std::string>&& headers,\n std::string&& body) {\n\n if (!status.ok()) {\n global_context_->env()->LogError(std::string(\"Failed to call \") + url +\n \", Error: \" + status.ToString() +\n \", Response body: \" + body);\n\n \/\/ Handle NGX error as opposed to pass-through error code\n if (status.code() < 0) {\n status = utils::Status(Code::UNAVAILABLE,\n \"Failed to connect to the service management\");\n } else {\n status = utils::Status(Code::UNAVAILABLE,\n \"Service management request was failed with \"\n \"HTTP response code \" +\n std::to_string(status.code()));\n }\n }\n\n on_done(status, std::move(body));\n }));\n\n http_request->set_url(url)\n .set_method(\"GET\")\n .set_auth_token(GetAuthToken())\n .set_timeout_ms(kHttpRequestTimeout)\n .set_max_retries(kHttpRequestRetries);\n\n global_context_->env()->RunHTTPRequest(std::move(http_request));\n}\n\nconst std::string& ServiceManagementFetch::GetAuthToken() {\n if (global_context_->service_account_token()) {\n return global_context_->service_account_token()->GetAuthToken(\n auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES);\n } else {\n static std::string empty;\n return empty;\n }\n}\n\n} \/\/ namespace api_manager\n} \/\/ namespace google\n<commit_msg>Increase timeout to call servicemanagement to 5s (#543)<commit_after>\/* Copyright (C) Extensible Service Proxy Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"src\/api_manager\/service_management_fetch.h\"\n\nnamespace google {\nnamespace api_manager {\n\nnamespace {\n\/\/ The default HTTP request timeout in ms.\n\/\/ The latency to the service management service could be in seconds.\n\/\/ This is a background checking process, is ok to have a big timeout.\n\/\/ Hence use 5 seconds timeout.\nconst int kHttpRequestTimeout = 5000;\n\/\/ Maximum number of HTTP request retries\nconst int kHttpRequestRetries = 5;\n\n\/\/ Default service management API url\nconst char kServiceManagementHost[] =\n \"https:\/\/servicemanagement.googleapis.com\";\nconst char kServiceManagementPath[] =\n \"\/google.api.servicemanagement.v1.ServiceManager\";\n} \/\/ namespace anonymous\n\nServiceManagementFetch::ServiceManagementFetch(\n std::shared_ptr<context::GlobalContext> global_context)\n : global_context_(global_context), host_(kServiceManagementHost) {\n if (global_context_->server_config() &&\n global_context->server_config()->has_service_management_config()) {\n if (!global_context->server_config()\n ->service_management_config()\n .url()\n .empty()) {\n host_ =\n global_context->server_config()->service_management_config().url();\n }\n }\n\n if (global_context_->service_account_token()) {\n \/\/ register auth token for servicemanagement services\n global_context_->service_account_token()->SetAudience(\n auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES,\n host_ + kServiceManagementPath);\n }\n}\n\nvoid ServiceManagementFetch::GetConfig(const std::string& config_id,\n HttpCallbackFunction on_done) {\n const std::string url = host_ + \"\/v1\/services\/\" +\n global_context_->service_name() + \"\/configs\/\" +\n config_id;\n Call(url, on_done);\n}\n\nvoid ServiceManagementFetch::GetRollouts(HttpCallbackFunction on_done) {\n const std::string url = host_ + \"\/v1\/services\/\" +\n global_context_->service_name() +\n \"\/rollouts?filter=status=SUCCESS\";\n Call(url, on_done);\n}\n\nvoid ServiceManagementFetch::Call(const std::string& url,\n HttpCallbackFunction on_done) {\n std::unique_ptr<HTTPRequest> http_request(new HTTPRequest([this, url,\n on_done](\n utils::Status status, std::map<std::string, std::string>&& headers,\n std::string&& body) {\n\n if (!status.ok()) {\n global_context_->env()->LogError(std::string(\"Failed to call \") + url +\n \", Error: \" + status.ToString() +\n \", Response body: \" + body);\n\n \/\/ Handle NGX error as opposed to pass-through error code\n if (status.code() < 0) {\n status = utils::Status(Code::UNAVAILABLE,\n \"Failed to connect to the service management\");\n } else {\n status = utils::Status(Code::UNAVAILABLE,\n \"Service management request was failed with \"\n \"HTTP response code \" +\n std::to_string(status.code()));\n }\n }\n\n on_done(status, std::move(body));\n }));\n\n http_request->set_url(url)\n .set_method(\"GET\")\n .set_auth_token(GetAuthToken())\n .set_timeout_ms(kHttpRequestTimeout)\n .set_max_retries(kHttpRequestRetries);\n\n global_context_->env()->RunHTTPRequest(std::move(http_request));\n}\n\nconst std::string& ServiceManagementFetch::GetAuthToken() {\n if (global_context_->service_account_token()) {\n return global_context_->service_account_token()->GetAuthToken(\n auth::ServiceAccountToken::JWT_TOKEN_FOR_SERVICEMANAGEMENT_SERVICES);\n } else {\n static std::string empty;\n return empty;\n }\n}\n\n} \/\/ namespace api_manager\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n#include \"game.h\"\n\n#include <enginefactory.h>\n#include <guiinterface.h>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nGame::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,\n\t\t const PlayerDataList &playerDataList, const GameData &gameData,\n\t\t const StartData &startData, int gameId)\n: myFactory(factory), myGui(gui), actualHand(0), actualBoard(0),\n startQuantityPlayers(startData.numberOfPlayers),\n startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind),\n startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise),\n myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0), lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData)\n{\n\tif(DEBUG_MODE) {\n\t\tstartSmallBlind = 20;\n\t\tactualSmallBlind = startSmallBlind;\n\t}\n\n\/\/ \tcout << \"Create Game Object\" << \"\\n\";\n\tint i;\n\n\tactualHandID = 0;\n\n\/\/ \tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\/\/ \t\tplayerArray[i] = 0;\n\/\/ \t}\n\n\t\/\/ Dealer Position bestimmen\n\tPlayerDataList::const_iterator player_i = playerDataList.begin();\n\tPlayerDataList::const_iterator player_end = playerDataList.end();\n\n\twhile (player_i != player_end)\n\t{\n\t\tif ((*player_i)->GetUniqueId() == startData.startDealerPlayerId)\n\t\t\tbreak;\n\t\t++player_i;\n\t}\n\tassert(player_i != player_end);\n\tdealerPosition = startData.startDealerPlayerId;\n\n\t\/\/ Board erstellen\n\tactualBoard = myFactory->createBoard();\n\n\tseatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\tactivePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\trunningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\n\t\/\/ Player erstellen\n\n\tplayer_i = playerDataList.begin();\n\tplayer_end = playerDataList.end();\n\tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\n\t\tstring myName;\n\t\tstring myAvatarFile;\n\t\tunsigned uniqueId = 0;\n\t\tPlayerType type = PLAYER_TYPE_COMPUTER;\n\t\tboost::shared_ptr<SessionData> myNetSession;\n\n\t\tif (player_i != player_end)\n\t\t{\n\t\t\tuniqueId = (*player_i)->GetUniqueId();\n\t\t\ttype = (*player_i)->GetType();\n\t\t\tmyName = (*player_i)->GetName();\n\t\t\tmyAvatarFile = (*player_i)->GetAvatarFile();\n\t\t\tmyNetSession = (*player_i)->GetNetSessionData();\n\t\t\t\/\/ TODO: set player type\n\t\t\t++player_i;\n\t\t}\n\n\t\t\/\/ create Player Objects\n\t\tboost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0);\n\n\t\ttmpPlayer->setNetSessionData(myNetSession);\n\n\t\t\/\/ fill player lists\n\t\tplayerArray.push_back(tmpPlayer); \/\/ delete\n\t\tseatsList->push_back(tmpPlayer);\n\t\tif(startQuantityPlayers > i) {\n\t\t\tactivePlayerList->push_back(tmpPlayer);\n\t\t}\n\n\t\t(*runningPlayerList) = (*activePlayerList);\n\n\t\tplayerArray[i]->setNetSessionData(myNetSession); \/\/ delete\n\t\t\n\t}\n\tactualBoard->setPlayerLists(playerArray, seatsList, activePlayerList, runningPlayerList); \/\/ delete playerArray\n\n\t\/\/start timer\n\tblindsTimer.reset();\n\tblindsTimer.start();\n}\n\nGame::~Game()\n{\n\/\/ \tcout << \"Delete Game Object\" << \"\\n\";\n\n\tdelete actualBoard;\n\tactualBoard = 0;\n\tdelete actualHand;\n\tactualHand = 0;\n\n}\n\nHandInterface *Game::getCurrentHand()\n{\n\treturn actualHand;\n}\n\nconst HandInterface *Game::getCurrentHand() const\n{\n\treturn actualHand;\n}\n\nvoid Game::initHand()\n{\n\n\tsize_t i;\n\tPlayerListConstIterator it_c;\n\tPlayerListIterator it, it_2;\n\n\t\/\/ eventuell vorhandene Hand löschen\n\tif(actualHand) {\n\t\tdelete actualHand;\n\t\tactualHand = 0;\n\t}\n\t\n\tactualHandID++;\n\n\t\/\/ calculate smallBlind\n\traiseBlinds();\n\n\t\/\/Spieler Action auf 0 setzen\n\/\/ \tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\/\/ \t\tplayerArray[i]->setMyAction(0);\n\/\/ \t}\n\n\t\/\/Spieler Action auf 0 setzen\n\tfor(it_c=seatsList->begin(); it_c!=seatsList->end(); it_c++) {\n\t\t(*it_c)->setMyAction(PLAYER_ACTION_NONE);\n\t}\n\n\t\/\/ Spieler mit leerem Cash auf inactive setzen\n\tit = activePlayerList->begin();\n\n\twhile( it!=activePlayerList->end() ) {\n\n\t\tif((*it)->getMyCash() == 0) {\n\/\/ \t\t\tcout << \"playerID: \" << (*it)->getMyID() << endl;\n\t\t\t(*it)->setMyActiveStatus(0);\n\t\t\tit = activePlayerList->erase(it);\n\t\t} else {\n\t\t\tit++;\n\t\t}\n\t}\n\n\/\/ TODO HACK\n\tfor(it=runningPlayerList->begin(); it!=runningPlayerList->end(); it++) {\n\t\tif (!(*it)->getMyActiveStatus())\n\t\t{\n\t\t\tif ((*it)->getMyUniqueID() == getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId())\n\t\t\t{\n\t\t\t\tit_2 = it;\n\t\t\t\tit_2++;\n\t\t\t\tif (it_2 == runningPlayerList->end())\n\t\t\t\t\tit_2 = runningPlayerList->begin();\n\t\t\t\tgetCurrentHand()->getCurrentBeRo()->setCurrentPlayersTurnId((*it_2)->getMyUniqueID());\n\t\t\t}\n\t\t}\n\t}\n\n\n\trunningPlayerList->clear();\n\t(*runningPlayerList) = (*activePlayerList);\n\n\t\/\/ Hand erstellen\n\tactualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, seatsList, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); \/\/ delete playerArray\n\n\n\t\/\/ Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!! DELETE\n\/\/ \tfor(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) {\n\/\/ \t\n\/\/ \t\tdealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS);\n\/\/ \t}\n\n\t\/\/ Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!!\n\tbool nextDealerFound = false;\n\tPlayerListConstIterator dealerPositionIt = actualHand->getSeatIt(dealerPosition);\n\tassert( dealerPositionIt != seatsList->end() );\n\n\tfor(i=0; i<seatsList->size(); i++) {\n\n\t\tdealerPositionIt++;\n\t\tif(dealerPositionIt == seatsList->end()) dealerPositionIt = seatsList->begin();\n\n\t\tit = actualHand->getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() );\n\t\tif(it != activePlayerList->end() ) {\n\t\t\tnextDealerFound = true;\n\t\t\tdealerPosition = (*it)->getMyUniqueID();\n\t\t\tbreak;\n\t\t}\n\n\t}\n\tassert(nextDealerFound);\n\n\n}\n\nvoid Game::startHand()\n{\n\tassert(actualHand);\n\n\t\/\/GUI bereinigen \n\tmyGui->nextRoundCleanGui();\n\n\tmyGui->logNewGameHandMsg(myGameID, actualHandID);\n\n\tactualHand->start();\n}\n\nboost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id)\n{\n\tboost::shared_ptr<PlayerInterface> tmpPlayer;\n\tPlayerListIterator i = getSeatsList()->begin();\n\tPlayerListIterator end = getSeatsList()->end();\n\twhile (i != end)\n\t{\n\t\tif ((*i)->getMyUniqueID() == id)\n\t\t{\n\t\t\ttmpPlayer = *i;\n\t\t\tbreak;\n\t\t}\n\t\t++i;\n\t}\n\treturn tmpPlayer;\n}\n\nboost::shared_ptr<PlayerInterface> Game::getCurrentPlayer()\n{\n\tboost::shared_ptr<PlayerInterface> tmpPlayer = getPlayerByUniqueId(getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId());\n\tassert(tmpPlayer.get());\n\treturn tmpPlayer;\n}\n\nvoid Game::raiseBlinds() {\n\n\/\/ \tcout << \"timer minutes \" << blindsTimer.elapsed().total_seconds()\/60 << \"\\n\";\n\/\/ \tcout << \"gameData.RaiseIntervalMode \" << myGameData.RaiseIntervalMode << \"\\n\";\n\/\/ \tcout << \"gameData.raiseMode \" << myGameData.raiseMode << \"\\n\";\n\/\/ \tcout << \"gameData.afterManualBlindsMode \" << myGameData.afterManualBlindsMode << \"\\n\";\n\n\tbool raiseBlinds = false;\n\n\tif (myGameData.raiseIntervalMode == RAISE_ON_HANDNUMBER) {\n\n\t\tif (lastHandBlindsRaised + myGameData.raiseSmallBlindEveryHandsValue <= actualHandID) {\n\t\t\traiseBlinds = true;\n\t\t\tlastHandBlindsRaised = actualHandID;\n\n\/\/ \t\t\tcout << \"raise now on hands \\n\";\n\t\t}\n\t}\n\telse {\n\t\tif (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()\/60) {\n\t\t\traiseBlinds = true;\n\t\t\tlastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()\/60;\n\n\/\/ \t\t\tcout << \"raise now on minutes \\n\";\n\t\t}\n\t}\n\n\tif (raiseBlinds) {\n\n\t\t\/\/ At this point, the blinds must be raised\n\t\t\/\/ Now we check how the blinds should be raised\n\t\n\t\tif (myGameData.raiseMode == DOUBLE_BLINDS) { \n\t\t\tactualSmallBlind *= 2; \n\/\/ \t\t\tcout << \"double small blind \\n\";\n\t\t}\t\n\t\telse {\n\t\t\t\/\/ Increase the position of the list\n\t\t\tlist<int> blindsList = myGameData.manualBlindsList;\n\t\t\tlist<int>::iterator it;\n\t\t\t\n\t\t\tif(!blindsList.empty()) {\n\t\t\t\tit = find(blindsList.begin(), blindsList.end(), actualSmallBlind);\n\t\t\t\tif(it != blindsList.end()) { \n\t\t\t\t\tit++;\n\/\/ \t\t\t\t\tcout << \"increase position in blindslist \\n\";\n\t\t\t\t}\n\t\t\t\telse { \n\/\/ \t\t\t\t\tcout << \"blindslist exceeds\\n\"; \n\t\t\t\t\tif(actualSmallBlind == myGameData.firstSmallBlind) {\n\t\t\t\t\t\tit = blindsList.begin();\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\/\/ \t\t\telse {\tcout << \"blindslist is empty \\n\"; }\n\t\t\t\/\/ Check if we can get an element of the list or the position exceeds the lis\n\t\t\tif (blindsList.empty() || it == blindsList.end()) {\n\t\t\t\t\n\t\t\t\t\/\/ The position exceeds the list\n\t\t\t\tif (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) { \n\t\t\t\t\tactualSmallBlind *= 2; \n\/\/ \t\t\t\t\tcout << \"after blindslist double blind\\n\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) { \n\t\t\t\t\t\tactualSmallBlind += myGameData.afterMBAlwaysRaiseValue;\n\/\/ \t\t\t\t\t\tcout << \"after blindslist increase about x \\n\";\n\t\t\t\t\t}\n\/\/ \t\t\t\t\telse { \/* Stay at last blind *\/ cout << \"after blindslist stay at last blind \\n\"; }\n\t\t\t\t}\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\/\/ Grab the blinds amount from the list\n\t\t\t\tactualSmallBlind = *it;\n\/\/ \t\t\t\tcout << \"set new small blind from blindslist \\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fixed assertion fix.<commit_after>\/***************************************************************************\n * Copyright (C) 2006 by FThauer FHammer *\n * f.thauer@web.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n#include \"game.h\"\n\n#include <enginefactory.h>\n#include <guiinterface.h>\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nGame::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory,\n\t\t const PlayerDataList &playerDataList, const GameData &gameData,\n\t\t const StartData &startData, int gameId)\n: myFactory(factory), myGui(gui), actualHand(0), actualBoard(0),\n startQuantityPlayers(startData.numberOfPlayers),\n startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind),\n startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise),\n myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0), lastHandBlindsRaised(1), lastTimeBlindsRaised(0), myGameData(gameData)\n{\n\tif(DEBUG_MODE) {\n\t\tstartSmallBlind = 20;\n\t\tactualSmallBlind = startSmallBlind;\n\t}\n\n\/\/ \tcout << \"Create Game Object\" << \"\\n\";\n\tint i;\n\n\tactualHandID = 0;\n\n\/\/ \tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\/\/ \t\tplayerArray[i] = 0;\n\/\/ \t}\n\n\t\/\/ Dealer Position bestimmen\n\tPlayerDataList::const_iterator player_i = playerDataList.begin();\n\tPlayerDataList::const_iterator player_end = playerDataList.end();\n\n\twhile (player_i != player_end)\n\t{\n\t\tif ((*player_i)->GetUniqueId() == startData.startDealerPlayerId)\n\t\t\tbreak;\n\t\t++player_i;\n\t}\n\tassert(player_i != player_end);\n\tdealerPosition = startData.startDealerPlayerId;\n\n\t\/\/ Board erstellen\n\tactualBoard = myFactory->createBoard();\n\n\tseatsList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\tactivePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\trunningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >);\n\n\t\/\/ Player erstellen\n\n\tplayer_i = playerDataList.begin();\n\tplayer_end = playerDataList.end();\n\tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\n\t\tstring myName;\n\t\tstring myAvatarFile;\n\t\tunsigned uniqueId = 0;\n\t\tPlayerType type = PLAYER_TYPE_COMPUTER;\n\t\tboost::shared_ptr<SessionData> myNetSession;\n\n\t\tif (player_i != player_end)\n\t\t{\n\t\t\tuniqueId = (*player_i)->GetUniqueId();\n\t\t\ttype = (*player_i)->GetType();\n\t\t\tmyName = (*player_i)->GetName();\n\t\t\tmyAvatarFile = (*player_i)->GetAvatarFile();\n\t\t\tmyNetSession = (*player_i)->GetNetSessionData();\n\t\t\t\/\/ TODO: set player type\n\t\t\t++player_i;\n\t\t}\n\n\t\t\/\/ create Player Objects\n\t\tboost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0);\n\n\t\ttmpPlayer->setNetSessionData(myNetSession);\n\n\t\t\/\/ fill player lists\n\t\tplayerArray.push_back(tmpPlayer); \/\/ delete\n\t\tseatsList->push_back(tmpPlayer);\n\t\tif(startQuantityPlayers > i) {\n\t\t\tactivePlayerList->push_back(tmpPlayer);\n\t\t}\n\n\t\t(*runningPlayerList) = (*activePlayerList);\n\n\t\tplayerArray[i]->setNetSessionData(myNetSession); \/\/ delete\n\t\t\n\t}\n\tactualBoard->setPlayerLists(playerArray, seatsList, activePlayerList, runningPlayerList); \/\/ delete playerArray\n\n\t\/\/start timer\n\tblindsTimer.reset();\n\tblindsTimer.start();\n}\n\nGame::~Game()\n{\n\/\/ \tcout << \"Delete Game Object\" << \"\\n\";\n\n\tdelete actualBoard;\n\tactualBoard = 0;\n\tdelete actualHand;\n\tactualHand = 0;\n\n}\n\nHandInterface *Game::getCurrentHand()\n{\n\treturn actualHand;\n}\n\nconst HandInterface *Game::getCurrentHand() const\n{\n\treturn actualHand;\n}\n\nvoid Game::initHand()\n{\n\n\tsize_t i;\n\tPlayerListConstIterator it_c;\n\tPlayerListIterator it, it_2;\n\n\t\/\/ eventuell vorhandene Hand löschen\n\tif(actualHand) {\n\t\tdelete actualHand;\n\t\tactualHand = 0;\n\t}\n\t\n\tactualHandID++;\n\n\t\/\/ calculate smallBlind\n\traiseBlinds();\n\n\t\/\/Spieler Action auf 0 setzen\n\/\/ \tfor(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) {\n\/\/ \t\tplayerArray[i]->setMyAction(0);\n\/\/ \t}\n\n\t\/\/Spieler Action auf 0 setzen\n\tfor(it_c=seatsList->begin(); it_c!=seatsList->end(); it_c++) {\n\t\t(*it_c)->setMyAction(PLAYER_ACTION_NONE);\n\t}\n\n\t\/\/ Spieler mit leerem Cash auf inactive setzen\n\tit = activePlayerList->begin();\n\n\twhile( it!=activePlayerList->end() ) {\n\n\t\tif((*it)->getMyCash() == 0) {\n\/\/ \t\t\tcout << \"playerID: \" << (*it)->getMyID() << endl;\n\t\t\t(*it)->setMyActiveStatus(0);\n\t\t\tit = activePlayerList->erase(it);\n\t\t} else {\n\t\t\tit++;\n\t\t}\n\t}\n\n\/\/ TODO HACK\n\tfor(it=seatsList->begin(); it!=seatsList->end(); it++) {\n\t\tif (!(*it)->getMyActiveStatus())\n\t\t{\n\t\t\tif ((*it)->getMyUniqueID() == getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId())\n\t\t\t{\n\t\t\t\tit_2 = it;\n\t\t\t\tit_2++;\n\t\t\t\tif (it_2 == seatsList->end())\n\t\t\t\t\tit_2 = seatsList->begin();\n\t\t\t\tgetCurrentHand()->getCurrentBeRo()->setCurrentPlayersTurnId((*it_2)->getMyUniqueID());\n\t\t\t}\n\t\t}\n\t}\n\n\n\trunningPlayerList->clear();\n\t(*runningPlayerList) = (*activePlayerList);\n\n\t\/\/ Hand erstellen\n\tactualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, seatsList, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); \/\/ delete playerArray\n\n\n\t\/\/ Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!! DELETE\n\/\/ \tfor(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) {\n\/\/ \t\n\/\/ \t\tdealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS);\n\/\/ \t}\n\n\t\/\/ Dealer-Button weiterschieben --> Achtung inactive -> TODO exception-rule !!!\n\tbool nextDealerFound = false;\n\tPlayerListConstIterator dealerPositionIt = actualHand->getSeatIt(dealerPosition);\n\tassert( dealerPositionIt != seatsList->end() );\n\n\tfor(i=0; i<seatsList->size(); i++) {\n\n\t\tdealerPositionIt++;\n\t\tif(dealerPositionIt == seatsList->end()) dealerPositionIt = seatsList->begin();\n\n\t\tit = actualHand->getActivePlayerIt( (*dealerPositionIt)->getMyUniqueID() );\n\t\tif(it != activePlayerList->end() ) {\n\t\t\tnextDealerFound = true;\n\t\t\tdealerPosition = (*it)->getMyUniqueID();\n\t\t\tbreak;\n\t\t}\n\n\t}\n\tassert(nextDealerFound);\n\n\n}\n\nvoid Game::startHand()\n{\n\tassert(actualHand);\n\n\t\/\/GUI bereinigen \n\tmyGui->nextRoundCleanGui();\n\n\tmyGui->logNewGameHandMsg(myGameID, actualHandID);\n\n\tactualHand->start();\n}\n\nboost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id)\n{\n\tboost::shared_ptr<PlayerInterface> tmpPlayer;\n\tPlayerListIterator i = getSeatsList()->begin();\n\tPlayerListIterator end = getSeatsList()->end();\n\twhile (i != end)\n\t{\n\t\tif ((*i)->getMyUniqueID() == id)\n\t\t{\n\t\t\ttmpPlayer = *i;\n\t\t\tbreak;\n\t\t}\n\t\t++i;\n\t}\n\treturn tmpPlayer;\n}\n\nboost::shared_ptr<PlayerInterface> Game::getCurrentPlayer()\n{\n\tboost::shared_ptr<PlayerInterface> tmpPlayer = getPlayerByUniqueId(getCurrentHand()->getCurrentBeRo()->getCurrentPlayersTurnId());\n\tassert(tmpPlayer.get());\n\treturn tmpPlayer;\n}\n\nvoid Game::raiseBlinds() {\n\n\/\/ \tcout << \"timer minutes \" << blindsTimer.elapsed().total_seconds()\/60 << \"\\n\";\n\/\/ \tcout << \"gameData.RaiseIntervalMode \" << myGameData.RaiseIntervalMode << \"\\n\";\n\/\/ \tcout << \"gameData.raiseMode \" << myGameData.raiseMode << \"\\n\";\n\/\/ \tcout << \"gameData.afterManualBlindsMode \" << myGameData.afterManualBlindsMode << \"\\n\";\n\n\tbool raiseBlinds = false;\n\n\tif (myGameData.raiseIntervalMode == RAISE_ON_HANDNUMBER) {\n\n\t\tif (lastHandBlindsRaised + myGameData.raiseSmallBlindEveryHandsValue <= actualHandID) {\n\t\t\traiseBlinds = true;\n\t\t\tlastHandBlindsRaised = actualHandID;\n\n\/\/ \t\t\tcout << \"raise now on hands \\n\";\n\t\t}\n\t}\n\telse {\n\t\tif (lastTimeBlindsRaised + myGameData.raiseSmallBlindEveryMinutesValue <= blindsTimer.elapsed().total_seconds()\/60) {\n\t\t\traiseBlinds = true;\n\t\t\tlastTimeBlindsRaised = blindsTimer.elapsed().total_seconds()\/60;\n\n\/\/ \t\t\tcout << \"raise now on minutes \\n\";\n\t\t}\n\t}\n\n\tif (raiseBlinds) {\n\n\t\t\/\/ At this point, the blinds must be raised\n\t\t\/\/ Now we check how the blinds should be raised\n\t\n\t\tif (myGameData.raiseMode == DOUBLE_BLINDS) { \n\t\t\tactualSmallBlind *= 2; \n\/\/ \t\t\tcout << \"double small blind \\n\";\n\t\t}\t\n\t\telse {\n\t\t\t\/\/ Increase the position of the list\n\t\t\tlist<int> blindsList = myGameData.manualBlindsList;\n\t\t\tlist<int>::iterator it;\n\t\t\t\n\t\t\tif(!blindsList.empty()) {\n\t\t\t\tit = find(blindsList.begin(), blindsList.end(), actualSmallBlind);\n\t\t\t\tif(it != blindsList.end()) { \n\t\t\t\t\tit++;\n\/\/ \t\t\t\t\tcout << \"increase position in blindslist \\n\";\n\t\t\t\t}\n\t\t\t\telse { \n\/\/ \t\t\t\t\tcout << \"blindslist exceeds\\n\"; \n\t\t\t\t\tif(actualSmallBlind == myGameData.firstSmallBlind) {\n\t\t\t\t\t\tit = blindsList.begin();\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\/\/ \t\t\telse {\tcout << \"blindslist is empty \\n\"; }\n\t\t\t\/\/ Check if we can get an element of the list or the position exceeds the lis\n\t\t\tif (blindsList.empty() || it == blindsList.end()) {\n\t\t\t\t\n\t\t\t\t\/\/ The position exceeds the list\n\t\t\t\tif (myGameData.afterManualBlindsMode == AFTERMB_DOUBLE_BLINDS) { \n\t\t\t\t\tactualSmallBlind *= 2; \n\/\/ \t\t\t\t\tcout << \"after blindslist double blind\\n\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif(myGameData.afterManualBlindsMode == AFTERMB_RAISE_ABOUT) { \n\t\t\t\t\t\tactualSmallBlind += myGameData.afterMBAlwaysRaiseValue;\n\/\/ \t\t\t\t\t\tcout << \"after blindslist increase about x \\n\";\n\t\t\t\t\t}\n\/\/ \t\t\t\t\telse { \/* Stay at last blind *\/ cout << \"after blindslist stay at last blind \\n\"; }\n\t\t\t\t}\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\/\/ Grab the blinds amount from the list\n\t\t\t\tactualSmallBlind = *it;\n\/\/ \t\t\t\tcout << \"set new small blind from blindslist \\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ncurses.h>\n#include <time.h>\n#include <stdio.h>\n\n#include <string>\n\n#include \"game.h\"\n#include \"menu.h\"\n#include \"classes\/Player.h\"\n#include \"classes\/Enemy.h\"\n#include \"classes\/Coin.h\"\n#include \"classes\/InfoPanel.h\"\n\nusing namespace std;\n\nconst int numCoins = 10;\n\n\nint startGame() {\n\n \/\/ Declared internally, to prevent ctors from running before main\n InfoPanel *infoPanel_game = new InfoPanel();\n Player player;\n Enemy enemy;\n Coin coins[numCoins];\n\n WINDOW *wgame = newwin(game_area.height(), game_area.width(), 1, 1);\n\n initscr();\n start_color();\n use_default_colors();\n init_pair(1, COLOR_RED, -1);\n init_pair(2, COLOR_YELLOW, -1);\n box(wgame, 0, 0);\n keypad(wgame, true);\n\n \/*\n * Check if Player & Enemy are too near each other.\n * `42' here is the maximum allowable value, given\n * that Player may spawn in the middle (39, 19) of\n * the game_area.\n *\/\n while (player.getDistance(enemy.getPos()) <= 42) {\n \/\/ Reroll ctor for new random start\n enemy = Enemy();\n }\n\n \/\/ Init placement of Player, Enemy, and Coins\n wmove(wgame, player.getPos().y, player.getPos().x);\n waddch(wgame, player.getDispChar());\n\n wmove(wgame, enemy.getPos().y, enemy.getPos().x);\n waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));\n\n for (auto &coin : coins) {\n wmove(wgame, coin.getPos().y, coin.getPos().x);\n waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));\n }\n\n int ch, steps = 0, difficulty = 1;\n string infoKey, infoMsg = \"\";\n bool gameover = false;\n while (( ch = wgetch(wgame)) != 'q') {\n\n infoKey = to_string(ch);\n\n steps++;\n\n werase(wgame);\n box(wgame, 0, 0);\n\n\n int px = player.getPos().x;\n int py = player.getPos().y;\n\n switch (ch) {\n case KEY_UP:\n case 'k':\n if (py > (int) game_area.top()) player.moveUp();\n infoMsg = \"up(\" + to_string(py) + \" > \" + to_string(game_area.top()) + \")\";\n break;\n case KEY_DOWN:\n case 'j':\n if (py < (int) game_area.bot()) player.moveDown(); \/\/ want bot:40\n infoMsg = \"down(\" + to_string(py) + \" < \" + to_string(game_area.bot()) + \")\";\n break;\n case KEY_LEFT:\n case 'h':\n if (px > (int) game_area.left()) player.moveLeft();\n infoMsg = \"left(\" + to_string(px) + \" > \" + to_string(game_area.left()) + \")\";\n break;\n case KEY_RIGHT:\n case 'l':\n if (px < (int) game_area.right()) player.moveRight(); \/\/ want right:80\n infoMsg = \"right(\" + to_string(px) + \" < \" + to_string(game_area.right()) + \")\";\n break;\n case KEY_ENTER: \/* numpad enter *\/\n case '\\n': \/* keyboard return *\/\n break;\n default:\n player.wait();\n infoMsg = \"waiting...\";\n\n }\n\n \/\/ Draw Coins again, and check if player has landed on\n for (auto &coin : coins) {\n wmove(wgame, coin.getPos().y, coin.getPos().x);\n waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));\n if (player.atop(coin.getPos())) {\n player.addScore(coin.getValue());\n\n \/\/ Just zero out coin value and display for now\n coin.setValue(0);\n coin.setChar(' ');\n }\n }\n\n \/\/ Move Player to indicated position\n wmove(wgame, player.getPos().y, player.getPos().x);\n waddch(wgame, player.getDispChar());\n\n \/\/ Enemy, seek out player\n enemy.seek(player); \/\/ Discard return (updated pos)\n wmove(wgame, enemy.getPos().y, enemy.getPos().x);\n waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));\n\n string proximityAlert = \"\";\n if (enemy.isAdjacent(player.getPos())) {\n proximityAlert = \"!\";\n }\n infoPanel_game->push('{'\n + std::to_string(player.getPos().x) + ','\n + std::to_string(player.getPos().y) + '}'\n + '{'\n + std::to_string(enemy.getPos().x) + ','\n + std::to_string(enemy.getPos().y) + '}'\n + \" dist: \"\n + std::to_string(player.getDistance(enemy.getPos()))\n + \" steps: \"\n + std::to_string(player.getSteps())\n + \" ticks: \"\n + std::to_string(player.getTicks())\n + \" score: \"\n + std::to_string(player.getScore())\n + \" info: \" + infoMsg\n + \" \" + proximityAlert\n );\n\n wrefresh(wgame);\n\n if (enemy.atop(player.getPos())) {\n \/\/ Game Over\n gameover = true;\n infoPanel_game->push(\"GAME OVER!\");\n infoPanel_game->push(\"Press `q' to quit.\");\n while (wgetch(wgame) != 'q'); \/\/ TODO prompt restart or quit\n break;\n }\n }\n\n delwin(wgame);\n return player.getScore() + steps * difficulty; \/\/ TODO eventually return more information\n}\n\n<commit_msg>Add diagonal movement to Actor (for Player).<commit_after>#include <ncurses.h>\n#include <time.h>\n#include <stdio.h>\n\n#include <string>\n\n#include \"game.h\"\n#include \"menu.h\"\n#include \"classes\/Player.h\"\n#include \"classes\/Enemy.h\"\n#include \"classes\/Coin.h\"\n#include \"classes\/InfoPanel.h\"\n\nusing namespace std;\n\nconst int numCoins = 10;\n\n\nint startGame() {\n\n \/\/ Declared internally, to prevent ctors from running before main\n InfoPanel *infoPanel_game = new InfoPanel();\n Player player;\n Enemy enemy;\n Coin coins[numCoins];\n\n WINDOW *wgame = newwin(game_area.height(), game_area.width(), 1, 1);\n\n initscr();\n start_color();\n use_default_colors();\n init_pair(1, COLOR_RED, -1);\n init_pair(2, COLOR_YELLOW, -1);\n box(wgame, 0, 0);\n keypad(wgame, true);\n\n \/*\n * Check if Player & Enemy are too near each other.\n * `42' here is the maximum allowable value, given\n * that Player may spawn in the middle (39, 19) of\n * the game_area.\n *\/\n while (player.getDistance(enemy.getPos()) <= 42) {\n \/\/ Reroll ctor for new random start\n enemy = Enemy();\n }\n\n \/\/ Init placement of Player, Enemy, and Coins\n wmove(wgame, player.getPos().y, player.getPos().x);\n waddch(wgame, player.getDispChar());\n\n wmove(wgame, enemy.getPos().y, enemy.getPos().x);\n waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));\n\n for (auto &coin : coins) {\n wmove(wgame, coin.getPos().y, coin.getPos().x);\n waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));\n }\n\n int ch, steps = 0, difficulty = 1;\n string infoKey, infoMsg = \"\";\n bool gameover = false;\n while (( ch = wgetch(wgame)) != 'q') {\n\n infoKey = to_string(ch);\n infoMsg = \"\";\n\n steps++;\n\n werase(wgame);\n box(wgame, 0, 0);\n\n\n int px = player.getPos().x;\n int py = player.getPos().y;\n\n switch (ch) {\n case 55: \/\/ Key up-left\n if (py > (int) game_area.top() && px > (int) game_area.left()) {\n player.moveUp();\n player.moveLeft();\n }\n break;\n case 57: \/\/ Key up-right\n if (py > (int) game_area.top() && px < (int) game_area.right()) {\n player.moveUp();\n player.moveRight();\n }\n break;\n case 51: \/\/ Key down-right\n if (py < (int) game_area.bot() && px < (int) game_area.right()) {\n player.moveDown();\n player.moveRight();\n }\n break;\n case 49: \/\/ Key down-left\n if (py < (int) game_area.bot() && px > (int) game_area.left()) {\n player.moveDown();\n player.moveLeft();\n }\n break;\n case KEY_UP:\n case 56:\n case 'k':\n if (py > (int) game_area.top()) player.moveUp();\n infoMsg = \"up(\" + to_string(py) + \" > \" + to_string(game_area.top()) + \")\";\n break;\n case KEY_DOWN:\n case 50:\n case 'j':\n if (py < (int) game_area.bot()) player.moveDown();\n infoMsg = \"down(\" + to_string(py) + \" < \" + to_string(game_area.bot()) + \")\";\n break;\n case KEY_LEFT:\n case 52:\n case 'h':\n if (px > (int) game_area.left()) player.moveLeft();\n infoMsg = \"left(\" + to_string(px) + \" > \" + to_string(game_area.left()) + \")\";\n break;\n case KEY_RIGHT:\n case 54:\n case 'l':\n if (px < (int) game_area.right()) player.moveRight();\n infoMsg = \"right(\" + to_string(px) + \" < \" + to_string(game_area.right()) + \")\";\n break;\n case KEY_ENTER: \/* numpad enter *\/\n case '\\n': \/* keyboard return *\/\n break;\n default:\n player.wait();\n infoMsg = \"waiting...\";\n\n }\n\n \/\/ Draw Coins again, and check if player has landed on\n for (auto &coin : coins) {\n wmove(wgame, coin.getPos().y, coin.getPos().x);\n waddch(wgame, coin.getDispChar() | COLOR_PAIR(2));\n if (player.atop(coin.getPos())) {\n player.addScore(coin.getValue());\n\n \/\/ Just zero out coin value and display for now\n coin.setValue(0);\n coin.setChar(' ');\n }\n }\n\n \/\/ Move Player to indicated position\n wmove(wgame, player.getPos().y, player.getPos().x);\n waddch(wgame, player.getDispChar());\n\n \/\/ Enemy, seek out player\n enemy.seek(player); \/\/ Discard return (updated pos)\n wmove(wgame, enemy.getPos().y, enemy.getPos().x);\n waddch(wgame, enemy.getDispChar() | COLOR_PAIR(1));\n\n string proximityAlert = \"\";\n if (enemy.isAdjacent(player.getPos())) {\n proximityAlert = \"!\";\n }\n infoPanel_game->push('{'\n + std::to_string(player.getPos().x) + ','\n + std::to_string(player.getPos().y) + '}'\n + '{'\n + std::to_string(enemy.getPos().x) + ','\n + std::to_string(enemy.getPos().y) + '}'\n + \" dist: \"\n + std::to_string(player.getDistance(enemy.getPos()))\n + \" steps: \"\n + std::to_string(player.getSteps())\n + \" ticks: \"\n + std::to_string(player.getTicks())\n + \" score: \"\n + std::to_string(player.getScore())\n + \" info: \" + infoMsg\n + \" \" + proximityAlert\n );\n\n wrefresh(wgame);\n\n if (enemy.atop(player.getPos())) {\n \/\/ Game Over\n gameover = true;\n infoPanel_game->push(\"GAME OVER!\");\n infoPanel_game->push(\"Press `q' to quit.\");\n while (wgetch(wgame) != 'q'); \/\/ TODO prompt restart or quit\n break;\n }\n }\n\n delwin(wgame);\n return player.getScore() + steps * difficulty; \/\/ TODO eventually return more information\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"toplayer.h\"\n#include \"domain.h\"\n#include <iostream>\n\n\nusing namespace std;\n\ntoplayer::toplayer()\n{\n\n}\nvoid toplayer::run()\n{\n help();\n cout << \"\\n Enter -help to display the command list again \" << endl;\n while(selection())\n {\n\n }\n}\nvoid toplayer::help()\n{\n cout << \"*********************************************************\" << endl;\n cout << \"** Notable Computer Scientists In History **\" << endl;\n cout << \"** **\" << endl;\n cout << \"** Enter -new to add a new person **\" << endl;\n cout << \"** Enter -list for a full list **\" << endl;\n cout << \"** Enter -search to search the list **\" << endl;\n cout << \"** Enter -remove to remove element from the list **\" << endl;\n cout << \"** Enter -sort to sort the list **\" << endl;\n cout << \"** Enter -exit to exit the program **\" << endl;\n cout << \"** **\" << endl;\n cout << \"*********************************************************\" << endl;\n}\n\nvoid toplayer::print(vector<Person>& pers) {\n\n for(unsigned int i = 0; i < pers.size(); i++) {\n cout.width(12);\n cout<<left;\n cout << pers[i].getFirstname();\n cout.width(12);\n cout<<left;\n cout << pers[i].getLastname();\n cout.width(10);\n cout<<left;\n cout << pers[i].getSex();\n cout.width(10);\n cout<<left;\n cout << pers[i].getBirth();\n cout.width(10);\n cout<<left;\n cout << pers[i].getDeath()<<endl;\n }\n cout << \"================================================\" << endl;\n}\n\nbool toplayer::selection()\n{\n string input;\n cin >> input;\n if (input == \"-list\")\n {\n vector<Person> p;\n domain d;\n p = d.list();\n cout << \"===================== List =====================\" << endl;\n print(p);\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-search\")\n {\n vector<Person> p;\n domain d;\n string whattype, input;\n cout << \"What do you want to search for?\" << endl;\n cout << \"-firstname\" << endl << \"-lastname\" << endl << \"-sex\"\n << endl << \"-birth\" << endl << \"-death\" << endl;\n cout << \"Enter your choice: \";\n do {\n cin >> whattype;\n if (whattype != \"-firstname\" && whattype != \"-lastname\" && whattype != \"-sex\" &&\n whattype != \"-birth\" && whattype != \"-death\") {\n cout << whattype << \" is not valid input! Try again: \";\n }\n } while (whattype != \"-firstname\" && whattype != \"-lastname\" && whattype != \"-sex\" &&\n whattype != \"-birth\" && whattype != \"-death\");\n\n cout << \"What is the word you want to search for? \";\n cin >> input;\n p = d.search(whattype, input);\n if (p.size() == 0){\n cout << \"Sorry, no results!\" << endl;\n } else {\n cout << \"===== Search results =====\" << endl;\n print(p);\n }\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-new\")\n {\n string firstname, lastname, sex, birth, death;\n\n cout << \"Enter first name: \";\n do {\n cin >> firstname;\n if (contains_number(firstname)) {\n cout << \"First name can not contain numbers try again: \";\n }\n } while (contains_number(firstname));\n\n cout << \"Enter last name: \";\n do {\n cin >> lastname;\n if (contains_number(lastname)) {\n cout << \"Last name can not contain numbers try again: \";\n }\n } while (contains_number(lastname));\n\n cout << \"Enter sex: \";\n do {\n cin >> sex;\n if (sex != \"male\" && sex != \"female\"){\n cout << sex << \" is not a gender, please choose male or female: \";\n }\n } while (sex != \"male\" && sex != \"female\");\n\n cout << \"Enter year of birth: \";\n do {\n cin >> birth;\n if (contains_letters(birth)){\n cout << \"Year of death can not contain letters, try again: \";\n }\n } while (contains_letters(birth));\n\n cout << \"Enter year of death, if the person has not died please type \\\"-\\\": \";\n do {\n cin >> death;\n if (contains_letters(death)){\n cout << \"Year of death can not contain letters, try again: \";\n }\n } while (contains_letters(death));\n domain d;\n d.add(firstname, lastname, sex, birth, death);\n cout << \"You successfully added a new person!\" << endl << endl;\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-sort\")\n {\n vector<Person> p;\n string input;\n cout << \"What do you want to sort by?\" << endl;\n cout << \"-firstname\" << endl << \"-lastname\" << endl << \"-sex\" << endl\n << \"-birth\" << endl << \"-death\" << endl;\n do {\n cin >> input;\n if (input != \"-firstname\" && input != \"-lastname\" && input != \"-sex\" &&\n input != \"-birth\" && input != \"-death\") {\n cout << input << \" is not valid command! Try again: \";\n }\n } while (input != \"-firstname\" && input != \"-lastname\" && input != \"-sex\" &&\n input != \"-birth\" && input != \"-death\");\n domain d;\n p = d.sort(input);\n\n cout << \"===== Sorted list =====\" << endl;\n print(p);\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-remove\")\n {\n unsigned int lineNumber = 1;\n vector<Person> p;\n domain d;\n p = d.list();\n cout << \"=========================== List ===========================\" << endl;\n for(unsigned int i = 0; i < p.size(); i++){\n cout.width(10);\n cout << left;\n cout << i+1;\n cout.width(12);\n cout << left;\n cout << p[i].getFirstname();\n cout.width(12);\n cout << left;\n cout << p[i].getLastname();\n cout.width(10);\n cout << left;\n cout << p[i].getSex();\n cout.width(10);\n cout << left;\n cout << p[i].getBirth();\n cout.width(10);\n cout << left;\n cout << p[i].getDeath() << endl;\n\n }\n cout << \"Which entry do you want to remove?\" << endl;\n cout << \"Type the line number: \";\n do {\n if (lineNumber <= 0 || lineNumber > p.size()) {\n cout << \"Sorry this isn't a valid line, try again: \";\n }\n while (!(cin >> lineNumber)) {\n cin.clear();\n cin.ignore();\n cout << \"Invalid input, try again: \";\n }\n\n } while (lineNumber <= 0 || lineNumber > p.size());\n p.erase (p.begin()+(lineNumber-1));\n d.remove(p);\n cout << \"You successfully removed a line \" << lineNumber << endl << endl;\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-help\")\n {\n clearScreen();\n help();\n }\n else if (input == \"-exit\")\n {\n return false;\n }\n else\n {\n cout << \"This command does not exist\" << endl;\n }\n return true;\n}\n\n\/\/ Villutjekk, athugar hvort thad se tolustafur i strengnum\nbool toplayer::contains_number(const string &c)\n{\n return (c.find_first_of(\"0123456789\") != string::npos);\n}\n\nbool toplayer::contains_letters(const string &c)\n{\n return (c.find_first_of(\"qwertyuioplkjhgfdsazxcvbnm\") != string::npos);\n}\n\nvoid toplayer::clearScreen()\n{\n system(\"cls\");\n}\n<commit_msg>sorted<commit_after>#include \"toplayer.h\"\n#include \"domain.h\"\n#include <iostream>\n\n\nusing namespace std;\n\ntoplayer::toplayer()\n{\n\n}\nvoid toplayer::run()\n{\n help();\n cout << \"\\n Enter -help to display the command list again \" << endl;\n while(selection())\n {\n\n }\n}\nvoid toplayer::help()\n{\n cout << \"*********************************************************\" << endl;\n cout << \"** Notable Computer Scientists In History **\" << endl;\n cout << \"** **\" << endl;\n cout << \"** Enter -new to add a new person **\" << endl;\n cout << \"** Enter -list for a full list **\" << endl;\n cout << \"** Enter -search to search the list **\" << endl;\n cout << \"** Enter -remove to remove element from the list **\" << endl;\n cout << \"** Enter -sort to sort the list **\" << endl;\n cout << \"** Enter -exit to exit the program **\" << endl;\n cout << \"** **\" << endl;\n cout << \"*********************************************************\" << endl;\n}\n\nvoid toplayer::print(vector<Person>& pers) {\n\n for(unsigned int i = 0; i < pers.size(); i++) {\n cout.width(12);\n cout<<left;\n cout << pers[i].getFirstname();\n cout.width(12);\n cout<<left;\n cout << pers[i].getLastname();\n cout.width(10);\n cout<<left;\n cout << pers[i].getSex();\n cout.width(10);\n cout<<left;\n cout << pers[i].getBirth();\n cout.width(10);\n cout<<left;\n cout << pers[i].getDeath()<<endl;\n }\n cout << \"================================================\" << endl;\n}\n\nbool toplayer::selection()\n{\n string input;\n cin >> input;\n if (input == \"-list\")\n {\n vector<Person> p;\n domain d;\n p = d.list();\n cout << \"===================== List =====================\" << endl;\n print(p);\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-search\")\n {\n vector<Person> p;\n domain d;\n string whattype, input;\n cout << \"What do you want to search for?\" << endl;\n cout << \"-firstname\" << endl << \"-lastname\" << endl << \"-sex\"\n << endl << \"-birth\" << endl << \"-death\" << endl;\n cout << \"Enter your choice: \";\n do {\n cin >> whattype;\n if (whattype != \"-firstname\" && whattype != \"-lastname\" && whattype != \"-sex\" &&\n whattype != \"-birth\" && whattype != \"-death\") {\n cout << whattype << \" is not valid input! Try again: \";\n }\n } while (whattype != \"-firstname\" && whattype != \"-lastname\" && whattype != \"-sex\" &&\n whattype != \"-birth\" && whattype != \"-death\");\n\n cout << \"What is the word you want to search for? \";\n cin >> input;\n p = d.search(whattype, input);\n if (p.size() == 0){\n cout << \"Sorry, no results!\" << endl;\n } else {\n cout << \"===== Search results =====\" << endl;\n print(p);\n }\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-new\")\n {\n string firstname, lastname, sex, birth, death;\n\n cout << \"Enter first name: \";\n do {\n cin >> firstname;\n if (contains_number(firstname)) {\n cout << \"First name can not contain numbers try again: \";\n }\n } while (contains_number(firstname));\n\n cout << \"Enter last name: \";\n do {\n cin >> lastname;\n if (contains_number(lastname)) {\n cout << \"Last name can not contain numbers try again: \";\n }\n } while (contains_number(lastname));\n\n cout << \"Enter sex: \";\n do {\n cin >> sex;\n if (sex != \"male\" && sex != \"female\"){\n cout << sex << \" is not a gender, please choose male or female: \";\n }\n } while (sex != \"male\" && sex != \"female\");\n\n cout << \"Enter year of birth: \";\n do {\n cin >> birth;\n if (contains_letters(birth)){\n cout << \"Year of death can not contain letters, try again: \";\n }\n } while (contains_letters(birth));\n\n cout << \"Enter year of death, if the person has not died please type \\\"-\\\": \";\n do {\n cin >> death;\n if (contains_letters(death)){\n cout << \"Year of death can not contain letters, try again: \";\n }\n } while (contains_letters(death));\n domain d;\n d.add(firstname, lastname, sex, birth, death);\n cout << \"You successfully added a new person!\" << endl << endl;\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-sort\")\n {\n vector<Person> p;\n string input;\n cout << \"What do you want to sort by?\" << endl;\n cout << \"-firstname\" << endl << \"-lastname\" << endl << \"-sex\" << endl\n << \"-birth\" << endl << \"-death\" << endl;\n do {\n cin >> input;\n if (input != \"-firstname\" && input != \"-lastname\" && input != \"-sex\" &&\n input != \"-birth\" && input != \"-death\") {\n cout << input << \" is not valid command! Try again: \";\n }\n } while (input != \"-firstname\" && input != \"-lastname\" && input != \"-sex\" &&\n input != \"-birth\" && input != \"-death\");\n domain d;\n p = d.sort(input);\n\n cout << \"================== Sorted list =================\" << endl;\n print(p);\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-remove\")\n {\n unsigned int lineNumber = 1;\n vector<Person> p;\n domain d;\n p = d.list();\n cout << \"=========================== List ===========================\" << endl;\n for(unsigned int i = 0; i < p.size(); i++){\n cout.width(10);\n cout << left;\n cout << i+1;\n cout.width(12);\n cout << left;\n cout << p[i].getFirstname();\n cout.width(12);\n cout << left;\n cout << p[i].getLastname();\n cout.width(10);\n cout << left;\n cout << p[i].getSex();\n cout.width(10);\n cout << left;\n cout << p[i].getBirth();\n cout.width(10);\n cout << left;\n cout << p[i].getDeath() << endl;\n\n }\n cout << \"Which entry do you want to remove?\" << endl;\n cout << \"Type the line number: \";\n do {\n if (lineNumber <= 0 || lineNumber > p.size()) {\n cout << \"Sorry this isn't a valid line, try again: \";\n }\n while (!(cin >> lineNumber)) {\n cin.clear();\n cin.ignore();\n cout << \"Invalid input, try again: \";\n }\n\n } while (lineNumber <= 0 || lineNumber > p.size());\n p.erase (p.begin()+(lineNumber-1));\n d.remove(p);\n cout << \"You successfully removed a line \" << lineNumber << endl << endl;\n system(\"pause\");\n clearScreen();\n help();\n }\n else if (input == \"-help\")\n {\n clearScreen();\n help();\n }\n else if (input == \"-exit\")\n {\n return false;\n }\n else\n {\n cout << \"This command does not exist\" << endl;\n }\n return true;\n}\n\n\/\/ Villutjekk, athugar hvort thad se tolustafur i strengnum\nbool toplayer::contains_number(const string &c)\n{\n return (c.find_first_of(\"0123456789\") != string::npos);\n}\n\nbool toplayer::contains_letters(const string &c)\n{\n return (c.find_first_of(\"qwertyuioplkjhgfdsazxcvbnm\") != string::npos);\n}\n\nvoid toplayer::clearScreen()\n{\n system(\"cls\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/http:\/\/keccak.noekeon.org\/specs_summary.html\r\n\r\n#include \"hash.hpp\"\r\n\r\n#include <cstdint>\r\n#include <stdexcept>\r\n\r\nstatic const uint64_t round_constants[24]=\r\n{\r\n\t0x0000000000000001,\r\n\t0x0000000000008082,\r\n\t0x800000000000808a,\r\n\t0x8000000080008000,\r\n\t0x000000000000808b,\r\n\t0x0000000080000001,\r\n\t0x8000000080008081,\r\n\t0x8000000000008009,\r\n\t0x000000000000008a,\r\n\t0x0000000000000088,\r\n\t0x0000000080008009,\r\n\t0x000000008000000a,\r\n\t0x000000008000808b,\r\n\t0x800000000000008b,\r\n\t0x8000000000008089,\r\n\t0x8000000000008003,\r\n\t0x8000000000008002,\r\n\t0x8000000000000080,\r\n\t0x000000000000800a,\r\n\t0x800000008000000a,\r\n\t0x8000000080008081,\r\n\t0x8000000000008080,\r\n\t0x0000000080000001,\r\n\t0x8000000080008008\r\n};\r\n\r\nstatic const uint64_t rotation_offsets[5][5]=\r\n{\r\n\t{0,36,3,41,18},\r\n\t{1,44,10,45,2},\r\n\t{62,6,43,15,61},\r\n\t{28,55,25,21,56},\r\n\t{27,20,39,8,14}\r\n};\r\n\r\nstatic uint64_t rotl(const uint64_t xx,const size_t shift)\r\n{\r\n\treturn (xx<<(shift))|(xx>>(64-shift));\r\n}\r\n\r\nstd::string hash_sha3_512(std::string message)\r\n{\r\n\tsize_t padding_length=72-((message.size())%72);\r\n\r\n\tfor(size_t ii=0;ii<padding_length;++ii)\r\n\t\tmessage+=(char)0x00;\r\n\r\n\tif(padding_length>0)\r\n\t{\r\n\t\tmessage[message.size()-padding_length]|=0x01;\r\n\t\tmessage[message.size()-1]|=0x80;\r\n\t}\r\n\r\n\tuint64_t states[5][5];\r\n\r\n\tfor(size_t yy=0;yy<5;++yy)\r\n\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t\tstates[xx][yy]=0;\r\n\r\n\tfor(size_t ii=0;ii<message.size()\/72;++ii)\r\n\t{\r\n\t\tstd::string block=message.substr(ii*72,72);\r\n\r\n\t\tfor(size_t yy=0;yy<5;++yy)\r\n\t\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t\t\tif(xx+5*yy<9)\r\n\t\t\t\t\tstates[xx][yy]^=*(uint64_t*)block.substr((xx+5*yy)*8,8).data();\r\n\r\n\t\tfor(size_t round=0;round<24;++round)\r\n\t\t{\r\n\t\t\tuint64_t C[5];\r\n\t\t\tuint64_t D[5];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tC[ii]=states[ii][0]^states[ii][1]^states[ii][2]^states[ii][3]^states[ii][4];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tD[ii]=C[(ii+4)%5]^rotl(C[(ii+1)%5],1);\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tstates[ii][jj]^=D[ii];\r\n\r\n\t\t\tuint64_t B[5][5];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tB[jj][(2*ii+3*jj)%5]=rotl(states[ii][jj],rotation_offsets[ii][jj]);\r\n\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tstates[ii][jj]=B[ii][jj]^((~B[(ii+1)%5][jj])&B[(ii+2)%5][jj]);\r\n\r\n\t\t\tstates[0][0]^=round_constants[round];\r\n\t\t}\r\n\t}\r\n\r\n\tstd::string digest;\r\n\r\n\tfor(size_t yy=0;yy<5;++yy)\r\n\t{\r\n\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t{\r\n\t\t\tif(xx+5*yy<9)\r\n\t\t\t{\r\n\t\t\t\tdigest+=std::string((char*)&states[xx][yy],8);\r\n\r\n\t\t\t\tif(digest.size()>=64)\r\n\t\t\t\t\treturn digest;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tthrow std::runtime_error(\"Error calculating SHA3-512 hash.\");\r\n}<commit_msg>Cleaned up theta step a bit...<commit_after>\/\/http:\/\/keccak.noekeon.org\/specs_summary.html\r\n\r\n#include \"hash.hpp\"\r\n\r\n#include <cstdint>\r\n#include <stdexcept>\r\n\r\nstatic const uint64_t round_constants[24]=\r\n{\r\n\t0x0000000000000001,\r\n\t0x0000000000008082,\r\n\t0x800000000000808a,\r\n\t0x8000000080008000,\r\n\t0x000000000000808b,\r\n\t0x0000000080000001,\r\n\t0x8000000080008081,\r\n\t0x8000000000008009,\r\n\t0x000000000000008a,\r\n\t0x0000000000000088,\r\n\t0x0000000080008009,\r\n\t0x000000008000000a,\r\n\t0x000000008000808b,\r\n\t0x800000000000008b,\r\n\t0x8000000000008089,\r\n\t0x8000000000008003,\r\n\t0x8000000000008002,\r\n\t0x8000000000000080,\r\n\t0x000000000000800a,\r\n\t0x800000008000000a,\r\n\t0x8000000080008081,\r\n\t0x8000000000008080,\r\n\t0x0000000080000001,\r\n\t0x8000000080008008\r\n};\r\n\r\nstatic const uint64_t rotation_offsets[5][5]=\r\n{\r\n\t{0,36,3,41,18},\r\n\t{1,44,10,45,2},\r\n\t{62,6,43,15,61},\r\n\t{28,55,25,21,56},\r\n\t{27,20,39,8,14}\r\n};\r\n\r\nstatic uint64_t rotl(const uint64_t xx,const size_t shift)\r\n{\r\n\treturn (xx<<(shift))|(xx>>(64-shift));\r\n}\r\n\r\nstd::string hash_sha3_512(std::string message)\r\n{\r\n\tsize_t padding_length=72-((message.size())%72);\r\n\r\n\tfor(size_t ii=0;ii<padding_length;++ii)\r\n\t\tmessage+=(char)0x00;\r\n\r\n\tif(padding_length>0)\r\n\t{\r\n\t\tmessage[message.size()-padding_length]|=0x01;\r\n\t\tmessage[message.size()-1]|=0x80;\r\n\t}\r\n\r\n\tuint64_t states[5][5];\r\n\r\n\tfor(size_t yy=0;yy<5;++yy)\r\n\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t\tstates[xx][yy]=0;\r\n\r\n\tfor(size_t ii=0;ii<message.size()\/72;++ii)\r\n\t{\r\n\t\tstd::string block=message.substr(ii*72,72);\r\n\r\n\t\tfor(size_t yy=0;yy<5;++yy)\r\n\t\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t\t\tif(xx+5*yy<9)\r\n\t\t\t\t\tstates[xx][yy]^=*(uint64_t*)block.substr((xx+5*yy)*8,8).data();\r\n\r\n\t\tfor(size_t round=0;round<24;++round)\r\n\t\t{\r\n\t\t\tuint64_t C[5];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tC[ii]=states[ii][0]^states[ii][1]^states[ii][2]^states[ii][3]^states[ii][4];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tstates[ii][jj]^=C[(ii+4)%5]^rotl(C[(ii+1)%5],1);\r\n\r\n\t\t\tuint64_t B[5][5];\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tB[jj][(2*ii+3*jj)%5]=rotl(states[ii][jj],rotation_offsets[ii][jj]);\r\n\r\n\t\t\tfor(size_t ii=0;ii<5;++ii)\r\n\t\t\t\tfor(size_t jj=0;jj<5;++jj)\r\n\t\t\t\t\tstates[ii][jj]=B[ii][jj]^((~B[(ii+1)%5][jj])&B[(ii+2)%5][jj]);\r\n\r\n\t\t\tstates[0][0]^=round_constants[round];\r\n\t\t}\r\n\t}\r\n\r\n\tstd::string digest;\r\n\r\n\tfor(size_t yy=0;yy<5;++yy)\r\n\t{\r\n\t\tfor(size_t xx=0;xx<5;++xx)\r\n\t\t{\r\n\t\t\tif(xx+5*yy<9)\r\n\t\t\t{\r\n\t\t\t\tdigest+=std::string((char*)&states[xx][yy],8);\r\n\r\n\t\t\t\tif(digest.size()>=64)\r\n\t\t\t\t\treturn digest;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tthrow std::runtime_error(\"Error calculating SHA3-512 hash.\");\r\n}<|endoftext|>"} {"text":"<commit_before>#include\"ics3\/ics3.hpp\"\n\n#include\"core.hpp\"\n#include\"ics3\/eeprom.hpp\"\n#include\"ics3\/parameter.hpp\"\n#include\"ics3\/id.hpp\"\n\nstatic inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept {\n return (rx[4] << 7) | rx[5];\n}\n\nstatic inline ics::Core::value getCmd(const int head, const ics::ID& id) {\n return head | id.get();\n}\n\nics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)\n: core {Core::getCore(path, baudrate.getSpeed())}\n{}\n\nics::Angle ics::ICS3::move(const ID& id, Angle angle) {\n static Core::Container tx(3), rx(6); \/\/ cache for runtime speed\n const auto send = angle.getRaw();\n tx[0] = getCmd(0x80, id);\n tx[1] = 0x7F & (send >> 7);\n tx[2] = 0x7F & send;\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n angle.rawData = getReceiveAngle(rx); \/\/ avoid invalid check. need friend\n return angle;\n}\n\nics::Angle ics::ICS3::free(const ID& id, Angle unit) {\n static Core::Container tx(3), rx(6); \/\/ cache for runtime speed\n tx[0] = getCmd(0x80, id); \/\/ tx[1] == tx[2] == 0\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n unit.rawData = getReceiveAngle(rx); \/\/ avoid invalid check. need friend\n return unit;\n}\n\nics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) {\n const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()};\n Core::Container rx(5);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n return Parameter::newParameter(type, rx[4]);\n}\n\nvoid ics::ICS3::set(const ID& id, const Parameter& param) {\n const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()};\n Core::Container rx(6);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n}\n\nics::EepRom ics::ICS3::getRom(const ID& id) {\n const Core::Container tx {getCmd(0xA0, id), 0};\n Core::Container rx(68);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n EepRom::Container romData;\n std::copy(rx.cbegin() + 4, rx.cend(), romData.begin());\n return EepRom {romData}; \/\/ need friend\n}\n\nvoid ics::ICS3::setRom(const ID& id, const EepRom& rom) {\n Core::Container tx(66), rx(68);\n tx[0] = getCmd(0xC0, id); \/\/ tx[1] == 0\n rom.write(tx.begin() + 2);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n}\n\nics::ID ics::ICS3::getID() {\n constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00};\n Core::IDContainerRx rx;\n core->communicateID(tx, rx);\n return ID {static_cast<ID::type>(0x1F & rx[4])};\n}\n\nvoid ics::ICS3::setID(const ID& id) {\n const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1};\n Core::IDContainerRx rx;\n core->communicateID(tx, rx);\n}\n<commit_msg>Update non explicit return object<commit_after>#include\"ics3\/ics3.hpp\"\n\n#include\"core.hpp\"\n#include\"ics3\/eeprom.hpp\"\n#include\"ics3\/parameter.hpp\"\n#include\"ics3\/id.hpp\"\n\nstatic inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept {\n return (rx[4] << 7) | rx[5];\n}\n\nstatic inline ics::Core::value getCmd(const int head, const ics::ID& id) {\n return head | id.get();\n}\n\nics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate)\n: core {Core::getCore(path, baudrate.getSpeed())}\n{}\n\nics::Angle ics::ICS3::move(const ID& id, Angle angle) {\n static Core::Container tx(3), rx(6); \/\/ cache for runtime speed\n const auto send = angle.getRaw();\n tx[0] = getCmd(0x80, id);\n tx[1] = 0x7F & (send >> 7);\n tx[2] = 0x7F & send;\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n angle.rawData = getReceiveAngle(rx); \/\/ avoid invalid check. need friend\n return angle;\n}\n\nics::Angle ics::ICS3::free(const ID& id, Angle unit) {\n static Core::Container tx(3), rx(6); \/\/ cache for runtime speed\n tx[0] = getCmd(0x80, id); \/\/ tx[1] == tx[2] == 0\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n unit.rawData = getReceiveAngle(rx); \/\/ avoid invalid check. need friend\n return unit;\n}\n\nics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) {\n const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()};\n Core::Container rx(5);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n return Parameter::newParameter(type, rx[4]);\n}\n\nvoid ics::ICS3::set(const ID& id, const Parameter& param) {\n const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()};\n Core::Container rx(6);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n}\n\nics::EepRom ics::ICS3::getRom(const ID& id) {\n const Core::Container tx {getCmd(0xA0, id), 0};\n Core::Container rx(68);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n EepRom::Container romData;\n std::copy(rx.cbegin() + 4, rx.cend(), romData.begin());\n return EepRom {romData}; \/\/ need friend\n}\n\nvoid ics::ICS3::setRom(const ID& id, const EepRom& rom) {\n Core::Container tx(66), rx(68);\n tx[0] = getCmd(0xC0, id); \/\/ tx[1] == 0\n rom.write(tx.begin() + 2);\n core->communicate(tx, rx); \/\/ throw std::runtime_error\n}\n\nics::ID ics::ICS3::getID() {\n constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00};\n Core::IDContainerRx rx;\n core->communicateID(tx, rx);\n return {static_cast<ID::type>(0x1F & rx[4])};\n}\n\nvoid ics::ICS3::setID(const ID& id) {\n const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1};\n Core::IDContainerRx rx;\n core->communicateID(tx, rx);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <merlin.h>\n\nnamespace merlin {\n\nvoid\nMerlin::Initialize(Handle<Object> target) {\n HandleScope scope;\n\n Handle<ObjectTemplate> merlin = ObjectTemplate::New();\n merlin->Set(String::NewSymbol(\"version\"),\n String::New(MERLIN_VERSION));\n\n MagickWandGenesis();\n \n target->Set(String::NewSymbol(\"merlin\"), merlin->NewInstance());\n}\n\n} \/\/ namespace\n\nextern \"C\" void\ninit(Handle<Object> target)\n{\n HandleScope scope;\n\n merlin::Merlin::Initialize(target);\n}\n\n<commit_msg>added constructors and initialized IM<commit_after>#include <merlin.h>\n\nnamespace merlin {\n\nMerlin::Merlin() {\n \/\/ MagickWandGenesis();\n}\n\nMerlin::~Merlin() {\n MagickWandTerminus();\n}\n\nvoid\nMerlin::Initialize(Handle<Object> target) {\n HandleScope scope;\n\n Handle<ObjectTemplate> merlin = ObjectTemplate::New();\n merlin->Set(String::NewSymbol(\"version\"),\n String::New(MERLIN_VERSION));\n\n MagickWandGenesis();\n\n target->Set(String::NewSymbol(\"merlin\"), merlin->NewInstance());\n}\n\n} \/\/ namespace\n\nextern \"C\" void\ninit(Handle<Object> target)\n{\n HandleScope scope;\n\n merlin::Merlin::Initialize(target);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n\nbool is_unique() {\n return true;\n}\n\nTEST(is_unique_test, Dummy) {\n EXPECT_EQ(is_unique(), true);\n}\n<commit_msg>Solve IsUnique<commit_after>\/\/ Is Unique: Implement an algorithm to determine if a string has all unique\n\/\/ characters. What if you cannot use additional data structures?\n\n#include \"gtest\/gtest.h\"\n\n#include <algorithm>\n\nbool is_unique(const std::string &s) {\n auto sorted = s;\n std::sort(sorted.begin(), sorted.end());\n for (int i = 1; i < sorted.size(); ++i) {\n if (sorted[i-1] == sorted[i]) {\n return false;\n }\n }\n return true;\n}\n\nTEST(is_unique_test, EmptyString) {\n EXPECT_EQ(is_unique(\"\"), true);\n}\n\nTEST(is_unique_test, 2Chars_Duplicated) {\n EXPECT_EQ(is_unique(\"aa\"), false);\n}\n\nTEST(is_unique_test, 2Chars_Unique) {\n EXPECT_EQ(is_unique(\"ab\"), true);\n}\n\nTEST(is_unique_test, 4Chars_Duplicated) {\n EXPECT_EQ(is_unique(\"aaaa\"), false);\n}\n\nTEST(is_unique_test, 4Chars_Unique) {\n EXPECT_EQ(is_unique(\"syen\"), true);\n}\n\nTEST(is_unique_test, 4Chars_Duplicated_Start_End) {\n EXPECT_EQ(is_unique(\"abca\"), false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"TypeAlias.h\"\n#include \"..\/types\/SymbolProviderType.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedList.hpp\"\ntemplate class Model::TypedList<OOModel::TypeAlias>;\n\nnamespace OOModel {\n\nCOMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(TypeAlias)\nCOMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(TypeAlias)\n\nREGISTER_ATTRIBUTE(TypeAlias, typeExpression, Expression, false, false, true)\nREGISTER_ATTRIBUTE(TypeAlias, typeArguments, TypedListOfFormalTypeArgument, false, false, true)\n\nTypeAlias::TypeAlias(const QString &name, Expression *typeExpression)\n: Super(nullptr, TypeAlias::getMetaData())\n{\n\tsetName(name);\n\tif (typeExpression) setTypeExpression(typeExpression);\n}\n\nModel::Node* TypeAlias::target() const\n{\n\tModel::Node* ret{};\n\n\tauto type = this->typeExpression()->type();\n\tif (auto sp = dynamic_cast<SymbolProviderType*>(type))\n\t\tret = sp->symbolProvider();\n\n\tSAFE_DELETE(type);\n\n\treturn ret;\n}\n\nTypeAlias::SymbolTypes TypeAlias::symbolType() const\n{\n\tif (auto t = target()) return t->symbolType();\n\telse return UNSPECIFIED;\n}\n\nbool TypeAlias::findSymbols(QSet<Node*>& result, const Model::SymbolMatcher& matcher, const Model::Node* source,\n\t\tFindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) const\n{\n\t\/\/ TODO: Search type arguments\n\n\tif (direction == SEARCH_HERE)\n\t{\n\t\tif (symbolMatches(matcher, symbolTypes))\n\t\t{\n\t\t\tresult.insert(const_cast<TypeAlias*>(this));\n\t\t\treturn true;\n\t\t}\n\t}\n\telse if (direction == SEARCH_DOWN)\n\t{\n\t\tif (auto t = target())\n\t\t\treturn t->findSymbols(result, matcher, t, SEARCH_DOWN, symbolTypes, false);\n\t}\n\telse if (direction == SEARCH_UP)\n\t{\n\t\tif (parent())\n\t\t\treturn parent()->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes);\n\t}\n\n\treturn false;\n}\n\n}\n<commit_msg>Resolve type arguments in TypeAlias<commit_after>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"TypeAlias.h\"\n#include \"..\/types\/SymbolProviderType.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedList.hpp\"\ntemplate class Model::TypedList<OOModel::TypeAlias>;\n\nnamespace OOModel {\n\nCOMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(TypeAlias)\nCOMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(TypeAlias)\n\nREGISTER_ATTRIBUTE(TypeAlias, typeExpression, Expression, false, false, true)\nREGISTER_ATTRIBUTE(TypeAlias, typeArguments, TypedListOfFormalTypeArgument, false, false, true)\n\nTypeAlias::TypeAlias(const QString &name, Expression *typeExpression)\n: Super(nullptr, TypeAlias::getMetaData())\n{\n\tsetName(name);\n\tif (typeExpression) setTypeExpression(typeExpression);\n}\n\nModel::Node* TypeAlias::target() const\n{\n\tModel::Node* ret{};\n\n\tauto type = this->typeExpression()->type();\n\tif (auto sp = dynamic_cast<SymbolProviderType*>(type))\n\t\tret = sp->symbolProvider();\n\n\tSAFE_DELETE(type);\n\n\treturn ret;\n}\n\nTypeAlias::SymbolTypes TypeAlias::symbolType() const\n{\n\tif (auto t = target()) return t->symbolType();\n\telse return UNSPECIFIED;\n}\n\nbool TypeAlias::findSymbols(QSet<Node*>& result, const Model::SymbolMatcher& matcher, const Model::Node* source,\n\t\tFindSymbolDirection direction, SymbolTypes symbolTypes, bool exhaustAllScopes) const\n{\n\tbool found{};\n\n\tif (direction == SEARCH_HERE)\n\t{\n\t\tif (symbolMatches(matcher, symbolTypes))\n\t\t{\n\t\t\tresult.insert(const_cast<TypeAlias*>(this));\n\t\t\tfound = true;\n\t\t}\n\t}\n\telse if (direction == SEARCH_DOWN)\n\t{\n\t\tif (auto t = target())\n\t\t\tfound = t->findSymbols(result, matcher, t, SEARCH_DOWN, symbolTypes, false);\n\t}\n\telse if (direction == SEARCH_UP)\n\t{\n\t\tauto ignore = childToSubnode(source);\n\t\tQ_ASSERT(ignore);\n\t\tif (typeArguments() != ignore)\n\t\t{\n\t\t\tfound = typeArguments()->findSymbols(result, matcher, source, SEARCH_HERE, symbolTypes, false) || found;\n\t\t\tqDebug() << typeArguments()->size() << found << matcher.matchPattern();\n\t\t}\n\n\t\tif ((exhaustAllScopes || !found) && parent())\n\t\t\tfound = parent()->findSymbols(result, matcher, source, SEARCH_UP, symbolTypes, exhaustAllScopes);\n\t}\n\n\treturn found;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/odbc:$Name: $:$Id: TODBCServer.cxx,v 1.7 2005\/02\/17 14:35:37 rdm Exp $\n\/\/ Author: Sergey Linev 6\/02\/2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TODBCServer.h\"\n\n#include \"TODBCResult.h\"\n#include \"TODBCStatement.h\"\n#include \"TUrl.h\"\n\n#include \"TString.h\"\n#include \"Riostream.h\"\n\n#include <sqlext.h>\n\n\nClassImp(TODBCServer)\n\n\/\/______________________________________________________________________________\nTODBCServer::TODBCServer(const char *db, const char *uid, const char *pw) :\n TSQLServer()\n{\n \/\/ Open a connection to a ODBC server. The db arguments can be:\n \/\/ 1. Form \"odbc:\/\/[user[:passwd]@]<host>[:<port>][\/<database>][?Driver]\",\n \/\/ e.g.: \"odbc:\/\/pcroot.cern.ch:3306\/test?MySQL\".\n \/\/ Driver argument specifies ODBC driver, which should be used for connection.\n \/\/ By default, MyODBC driver name is used\n \/\/ The uid is the username and pw the password that should be used for the connection.\n \/\/ If uid and pw are not specified (==0), user and passwd arguments from\n \/\/ URL will be used. Works only with MySQL ODBC, probably with PostrSQL ODBC.\n \/\/ 2. Form \"odbcd:\/\/DRIVER={MyODBC};SERVER=pcroot.cern.ch;DATABASE=test;USER=user;PASSWORD=pass;OPTION=3;PORT=3306;\"\n \/\/ This is a form, which is accepted by SQLDriverConnect function of ODBC.\n \/\/ Here some other arguments can be specified, which are not included in standard\n \/\/ URL format.\n \/\/ 3. Form \"odbcn:\/\/MySpecialConfig\", where MySpecialConfig is entry, defined in\n \/\/ user DSN (user data source). Here uid and pw should be always specified\n \/\/\n \/\/ Configuring unixODBC under Linux: http:\/\/www.unixodbc.org\/odbcinst.html\n \/\/ Remarks: for variants 1 & 2 it is enough to create\/configure odbcinst.ini file.\n \/\/ For variant 3 file odbc.ini should be created. Path to this files can be specified\n \/\/ in enviromental variables like\n \/\/ export ODBCINI=\/home\/my\/unixODBC\/etc\/odbc.ini\n \/\/ export ODBCSYSINI=\/home\/my\/unixODBC\/etc\n \/\/\n \/\/ Configuring MySQL ODBC under Windows.\n \/\/ Installing ODBC driver for MySQL is enough to use it under Windows.\n \/\/ Afer odbcd:\/\/ variant can be used with DRIVER={MySQL ODBC 3.51 Driver};\n \/\/ To configure User DSN, go into Start menu -> Settings -> Control panel ->\n \/\/ Administrative tools-> Data Sources (ODBC).\n \/\/\n \/\/ To install Oracle ODBC driver for Windows, one should download\n \/\/ and install either complete Oracle client (~500 MB), or so-called\n \/\/ Instant Client Basic and Instant Client ODBC (~20 MB together).\n \/\/ Some remark about Instant Client:\n \/\/ 1) Two additional DLLs are required: mfc71.dll & msver71.dll\n \/\/ They can be found either in MS VC++ 7.1 Free Toolkit or\n \/\/ downloaded from other Internet sites\n \/\/ 2) ORACLE_HOME enviroment variable should be specified and point to\n \/\/ location, where Instant Client files are extracted\n \/\/ 3) Run odbc_install.exe from account with administrative rights\n \/\/ 3) In $ORACLE_HOME\/network\/admin\/ directory appropriate *.ora files\n \/\/ like ldap.ora, sqlnet.ora, tnsnames.ora should be installed.\n \/\/ Contact your Oracle administrator to get these files.\n \/\/ After Oracle ODBC driver is installed, appropriate entry in ODBC drivers\n \/\/ list like \"Oracle in instantclient10_2\" should appiar. Connection string example:\n \/\/ \"odbcd:\/\/DRIVER={Oracle in instantclient10_2};DBQ=db-test;UID=user_name;PWD=user_pass;\";\n \/\/\n\n TString connstr;\n Bool_t simpleconnect = kTRUE;\n\n SQLRETURN retcode;\n SQLHWND hwnd;\n\n fPort = 1; \/\/ indicate that we are connected\n\n if ((strncmp(db, \"odbc\", 4)!=0) || (strlen(db)<8)) {\n Error(\"TODBCServer\", \"db argument should be started from odbc...\");\n goto zombie;\n }\n\n if (strncmp(db, \"odbc:\/\/\", 7)==0) {\n TUrl url(db);\n if (!url.IsValid()) {\n Error(\"TODBCServer\", \"not valid URL: %s\", db);\n goto zombie;\n }\n cout << \"URL is VALID !!!!\" << endl;\n\n const char* driver = \"MyODBC\";\n const char* dbase = 0;\n if (strcmp(url.GetFile(), \"\/\")!=0)\n dbase = url.GetFile()+1; \/\/skip leading \/\n\n if ((uid==0) || (*uid==0) && (strlen(url.GetUser())>0)) {\n uid = url.GetUser();\n pw = url.GetPasswd();\n }\n\n if (strlen(url.GetOptions())!=0) driver = url.GetOptions();\n\n connstr.Form(\"DRIVER={%s};\"\n \"SERVER=%s;\"\n \"DATABASE=%s;\"\n \"USER=%s;\"\n \"PASSWORD=%s;\"\n \"OPTION=3;\",\n driver, url.GetHost(), dbase, uid, pw);\n if (url.GetPort()>0)\n connstr += Form(\"PORT=%d;\", url.GetPort());\n\n fHost = url.GetHost();\n fPort = url.GetPort()>0 ? url.GetPort() : 1;\n simpleconnect = kFALSE;\n } else\n if (strncmp(db, \"odbcd:\/\/\", 8)==0) {\n connstr = db+8;\n simpleconnect = kFALSE;\n } else\n if (strncmp(db, \"odbcn:\/\/\", 8)==0) {\n connstr = db+8;\n simpleconnect = kTRUE;\n } else {\n Error(\"TODBCServer\", \"db argument is invalid\");\n goto zombie;\n }\n\n retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &fHenv);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Set the ODBC version environment attribute *\/\n retcode = SQLSetEnvAttr(fHenv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Allocate connection handle *\/\n retcode = SQLAllocHandle(SQL_HANDLE_DBC, fHenv, &fHdbc);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Set login timeout to 5 seconds. *\/\n retcode = SQLSetConnectAttr(fHdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER) 5, 0);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n char sbuf[2048];\n\n SQLSMALLINT reslen;\n\n cout << \"Conn: \" << connstr << \" simple = \" << simpleconnect << endl;\n\n hwnd = 0;\n\n if (simpleconnect)\n retcode = SQLConnect(fHdbc, (SQLCHAR*) connstr.Data(), SQL_NTS,\n (SQLCHAR*) uid, SQL_NTS,\n (SQLCHAR*) pw, SQL_NTS);\n else\n retcode = SQLDriverConnect(fHdbc, hwnd,\n (SQLCHAR*) connstr.Data(), SQL_NTS,\n (SQLCHAR*) sbuf, 2048, &reslen, SQL_DRIVER_COMPLETE);\n\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n fType = \"ODBC\";\n fDB = db;\n if (!simpleconnect) fInfo = sbuf;\n else fInfo = connstr;\n\n return;\n\nzombie:\n fPort = -1;\n fHost = \"\";\n MakeZombie();\n}\n\n\n\/\/______________________________________________________________________________\nTODBCServer::~TODBCServer()\n{\n \/\/ Close connection to MySQL DB server.\n\n if (IsConnected())\n Close();\n}\n\n\/\/______________________________________________________________________________\nBool_t TODBCServer::ExtractErrors(SQLRETURN retcode, const char* method)\n{\n if ((retcode==SQL_SUCCESS) || (retcode==SQL_SUCCESS_WITH_INFO)) return kFALSE;\n\n SQLINTEGER i = 0;\n SQLINTEGER native;\n SQLCHAR state[7];\n SQLCHAR text[256];\n SQLSMALLINT len;\n\n while (SQLGetDiagRec(SQL_HANDLE_ENV, fHenv, ++i, state, &native, text,\n sizeof(text), &len ) == SQL_SUCCESS)\n Error(method, \"%s:%ld:%ld:%s\\n\", state, i, native, text);\n\n i = 0;\n\n while (SQLGetDiagRec(SQL_HANDLE_DBC, fHdbc, ++i, state, &native, text,\n sizeof(text), &len ) == SQL_SUCCESS)\n Error(method, \"%s:%ld:%ld:%s\\n\", state, i, native, text);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TODBCServer::Close(Option_t *)\n{\n \/\/ Close connection to MySQL DB server.\n\n SQLDisconnect(fHdbc);\n SQLFreeHandle(SQL_HANDLE_DBC, fHdbc);\n SQLFreeHandle(SQL_HANDLE_ENV, fHenv);\n fPort = -1;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::Query(const char *sql)\n{\n \/\/ Execute SQL command. Result object must be deleted by the user.\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"Query\",\"ODBC not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLExecDirect(hstmt, (SQLCHAR*) sql, SQL_NTS);\n if (ExtractErrors(retcode, \"Query\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::SelectDataBase(const char *)\n{\n \/\/ Select a database. Returns 0 if successful, non-zero otherwise.\n \/\/ Does not implemented for ODBC driver. User should specify database\n \/\/ name at time of connection\n\n if (!IsConnected()) {\n Error(\"SelectDataBase\", \"not connected\");\n return -1;\n }\n\n Info(\"SelectDataBase\",\"Does not implemented for ODBC\");\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetDataBases(const char *)\n{\n \/\/ List all available databases. Wild is for wildcarding \"t%\" list all\n \/\/ databases starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetDataBases\", \"not connected\");\n return 0;\n }\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetTables(const char *, const char *)\n{\n \/\/ List all tables in the specified database. Wild is for wildcarding\n \/\/ \"t%\" list all tables starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetTables\", \"not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLTables(hstmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0);\n if (ExtractErrors(retcode, \"GetTables\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetColumns(const char*, const char *table, const char*)\n{\n \/\/ List all columns in specified table in the specified database.\n \/\/ Wild is for wildcarding \"t%\" list all columns starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetColumns\", \"not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLColumns(hstmt, NULL, 0, NULL, 0, (SQLCHAR*) table, SQL_NTS, NULL, 0);\n if (ExtractErrors(retcode, \"GetColumns\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::CreateDataBase(const char*)\n{\n \/\/ Create a database. Returns 0 if successful, non-zero otherwise.\n\n if (!IsConnected()) {\n Error(\"CreateDataBase\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::DropDataBase(const char*)\n{\n \/\/ Drop (i.e. delete) a database. Returns 0 if successful, non-zero\n \/\/ otherwise.\n\n if (!IsConnected()) {\n Error(\"DropDataBase\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::Reload()\n{\n \/\/ Reload permission tables. Returns 0 if successful, non-zero\n \/\/ otherwise. User must have reload permissions.\n\n if (!IsConnected()) {\n Error(\"Reload\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::Shutdown()\n{\n \/\/ Shutdown the database server. Returns 0 if successful, non-zero\n \/\/ otherwise. User must have shutdown permissions.\n\n if (!IsConnected()) {\n Error(\"Shutdown\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nconst char *TODBCServer::ServerInfo()\n{\n \/\/ Return server info.\n\n if (!IsConnected()) {\n Error(\"ServerInfo\", \"not connected\");\n return 0;\n }\n\n return fInfo;\n}\n\n\n\/\/______________________________________________________________________________\nTSQLStatement *TODBCServer::Statement(const char *sql, Int_t bufsize)\n{\n if (!IsConnected()) {\n Error(\"Statement\", \"not connected\");\n return 0;\n }\n\n if (!sql || !*sql) {\n Error(\"Statement\", \"no query string specified\");\n return 0;\n }\n\n\/\/ SQLUINTEGER info = 0;\n\/\/ SQLGetInfo(fHdbc, SQL_PARAM_ARRAY_ROW_COUNTS, (SQLPOINTER)&info, sizeof(info), NULL);\n\/\/ if (info==SQL_PARC_BATCH) Info(\"Statement\",\"info==SQL_PARC_BATCH\"); else\n\/\/ if (info==SQL_PARC_NO_BATCH) Info(\"Statement\",\"info==SQL_PARC_NO_BATCH\"); else\n\/\/ Info(\"Statement\",\"info==%u\", info);\n\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n if (ExtractErrors(retcode, \"Statement\")) return 0;\n\n retcode = SQLPrepare(hstmt, (SQLCHAR*) sql, SQL_NTS);\n if (ExtractErrors(retcode, \"Statement\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCStatement(hstmt, bufsize);\n}\n\n<commit_msg>reformatting of comment.<commit_after>\/\/ @(#)root\/odbc:$Name: $:$Id: TODBCServer.cxx,v 1.1 2006\/04\/17 14:12:52 rdm Exp $\n\/\/ Author: Sergey Linev 6\/02\/2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TODBCServer.h\"\n\n#include \"TODBCResult.h\"\n#include \"TODBCStatement.h\"\n#include \"TUrl.h\"\n\n#include \"TString.h\"\n#include \"Riostream.h\"\n\n#include <sqlext.h>\n\n\nClassImp(TODBCServer)\n\n\/\/______________________________________________________________________________\nTODBCServer::TODBCServer(const char *db, const char *uid, const char *pw) :\n TSQLServer()\n{\n \/\/ Open a connection to a ODBC server. The db arguments can be:\n \/\/ 1. Form \"odbc:\/\/[user[:passwd]@]<host>[:<port>][\/<database>][?Driver]\",\n \/\/ e.g.: \"odbc:\/\/pcroot.cern.ch:3306\/test?MySQL\".\n \/\/ Driver argument specifies ODBC driver, which should be used for\n \/\/ connection. By default, MyODBC driver name is used.\n \/\/ The uid is the username and pw the password that should be used\n \/\/ for the connection.\n \/\/ If uid and pw are not specified (==0), user and passwd arguments from\n \/\/ URL will be used. Works only with MySQL ODBC, probably with PostrSQL\n \/\/ ODBC.\n \/\/ 2. Form \"odbcd:\/\/DRIVER={MyODBC};SERVER=pcroot.cern.ch;DATABASE=test;USER=user;PASSWORD=pass;OPTION=3;PORT=3306;\"\n \/\/ This is a form, which is accepted by SQLDriverConnect function of ODBC.\n \/\/ Here some other arguments can be specified, which are not included\n \/\/ in standard URL format.\n \/\/ 3. Form \"odbcn:\/\/MySpecialConfig\", where MySpecialConfig is entry,\n \/\/ defined in user DSN (user data source). Here uid and pw should be\n \/\/ always specified.\n \/\/\n \/\/ Configuring unixODBC under Linux: http:\/\/www.unixodbc.org\/odbcinst.html\n \/\/ Remarks: for variants 1 & 2 it is enough to create\/configure\n \/\/ odbcinst.ini file. For variant 3 file odbc.ini should be created.\n \/\/ Path to this files can be specified in enviromental variables like\n \/\/ export ODBCINI=\/home\/my\/unixODBC\/etc\/odbc.ini\n \/\/ export ODBCSYSINI=\/home\/my\/unixODBC\/etc\n \/\/\n \/\/ Configuring MySQL ODBC under Windows.\n \/\/ Installing ODBC driver for MySQL is enough to use it under Windows.\n \/\/ Afer odbcd:\/\/ variant can be used with DRIVER={MySQL ODBC 3.51 Driver};\n \/\/ To configure User DSN, go into Start menu -> Settings ->\n \/\/ Control panel -> Administrative tools-> Data Sources (ODBC).\n \/\/\n \/\/ To install Oracle ODBC driver for Windows, one should download\n \/\/ and install either complete Oracle client (~500 MB), or so-called\n \/\/ Instant Client Basic and Instant Client ODBC (~20 MB together).\n \/\/ Some remark about Instant Client:\n \/\/ 1) Two additional DLLs are required: mfc71.dll & msver71.dll\n \/\/ They can be found either in MS VC++ 7.1 Free Toolkit or\n \/\/ downloaded from other Internet sites\n \/\/ 2) ORACLE_HOME enviroment variable should be specified and point to\n \/\/ location, where Instant Client files are extracted\n \/\/ 3) Run odbc_install.exe from account with administrative rights\n \/\/ 3) In $ORACLE_HOME\/network\/admin\/ directory appropriate *.ora files\n \/\/ like ldap.ora, sqlnet.ora, tnsnames.ora should be installed.\n \/\/ Contact your Oracle administrator to get these files.\n \/\/ After Oracle ODBC driver is installed, appropriate entry in ODBC drivers\n \/\/ list like \"Oracle in instantclient10_2\" should appiar. Connection\n \/\/ string example:\n \/\/ \"odbcd:\/\/DRIVER={Oracle in instantclient10_2};DBQ=db-test;UID=user_name;PWD=user_pass;\";\n\n TString connstr;\n Bool_t simpleconnect = kTRUE;\n\n SQLRETURN retcode;\n SQLHWND hwnd;\n\n fPort = 1; \/\/ indicate that we are connected\n\n if ((strncmp(db, \"odbc\", 4)!=0) || (strlen(db)<8)) {\n Error(\"TODBCServer\", \"db argument should be started from odbc...\");\n goto zombie;\n }\n\n if (strncmp(db, \"odbc:\/\/\", 7)==0) {\n TUrl url(db);\n if (!url.IsValid()) {\n Error(\"TODBCServer\", \"not valid URL: %s\", db);\n goto zombie;\n }\n cout << \"URL is VALID !!!!\" << endl;\n\n const char* driver = \"MyODBC\";\n const char* dbase = 0;\n if (strcmp(url.GetFile(), \"\/\")!=0)\n dbase = url.GetFile()+1; \/\/skip leading \/\n\n if ((uid==0) || (*uid==0) && (strlen(url.GetUser())>0)) {\n uid = url.GetUser();\n pw = url.GetPasswd();\n }\n\n if (strlen(url.GetOptions())!=0) driver = url.GetOptions();\n\n connstr.Form(\"DRIVER={%s};\"\n \"SERVER=%s;\"\n \"DATABASE=%s;\"\n \"USER=%s;\"\n \"PASSWORD=%s;\"\n \"OPTION=3;\",\n driver, url.GetHost(), dbase, uid, pw);\n if (url.GetPort()>0)\n connstr += Form(\"PORT=%d;\", url.GetPort());\n\n fHost = url.GetHost();\n fPort = url.GetPort()>0 ? url.GetPort() : 1;\n simpleconnect = kFALSE;\n } else\n if (strncmp(db, \"odbcd:\/\/\", 8)==0) {\n connstr = db+8;\n simpleconnect = kFALSE;\n } else\n if (strncmp(db, \"odbcn:\/\/\", 8)==0) {\n connstr = db+8;\n simpleconnect = kTRUE;\n } else {\n Error(\"TODBCServer\", \"db argument is invalid\");\n goto zombie;\n }\n\n retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &fHenv);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Set the ODBC version environment attribute *\/\n retcode = SQLSetEnvAttr(fHenv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Allocate connection handle *\/\n retcode = SQLAllocHandle(SQL_HANDLE_DBC, fHenv, &fHdbc);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n \/* Set login timeout to 5 seconds. *\/\n retcode = SQLSetConnectAttr(fHdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER) 5, 0);\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n char sbuf[2048];\n\n SQLSMALLINT reslen;\n\n cout << \"Conn: \" << connstr << \" simple = \" << simpleconnect << endl;\n\n hwnd = 0;\n\n if (simpleconnect)\n retcode = SQLConnect(fHdbc, (SQLCHAR*) connstr.Data(), SQL_NTS,\n (SQLCHAR*) uid, SQL_NTS,\n (SQLCHAR*) pw, SQL_NTS);\n else\n retcode = SQLDriverConnect(fHdbc, hwnd,\n (SQLCHAR*) connstr.Data(), SQL_NTS,\n (SQLCHAR*) sbuf, 2048, &reslen, SQL_DRIVER_COMPLETE);\n\n if (ExtractErrors(retcode, \"TODBCServer\")) goto zombie;\n\n fType = \"ODBC\";\n fDB = db;\n if (!simpleconnect) fInfo = sbuf;\n else fInfo = connstr;\n\n return;\n\nzombie:\n fPort = -1;\n fHost = \"\";\n MakeZombie();\n}\n\n\n\/\/______________________________________________________________________________\nTODBCServer::~TODBCServer()\n{\n \/\/ Close connection to MySQL DB server.\n\n if (IsConnected())\n Close();\n}\n\n\/\/______________________________________________________________________________\nBool_t TODBCServer::ExtractErrors(SQLRETURN retcode, const char* method)\n{\n if ((retcode==SQL_SUCCESS) || (retcode==SQL_SUCCESS_WITH_INFO)) return kFALSE;\n\n SQLINTEGER i = 0;\n SQLINTEGER native;\n SQLCHAR state[7];\n SQLCHAR text[256];\n SQLSMALLINT len;\n\n while (SQLGetDiagRec(SQL_HANDLE_ENV, fHenv, ++i, state, &native, text,\n sizeof(text), &len ) == SQL_SUCCESS)\n Error(method, \"%s:%ld:%ld:%s\\n\", state, i, native, text);\n\n i = 0;\n\n while (SQLGetDiagRec(SQL_HANDLE_DBC, fHdbc, ++i, state, &native, text,\n sizeof(text), &len ) == SQL_SUCCESS)\n Error(method, \"%s:%ld:%ld:%s\\n\", state, i, native, text);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TODBCServer::Close(Option_t *)\n{\n \/\/ Close connection to MySQL DB server.\n\n SQLDisconnect(fHdbc);\n SQLFreeHandle(SQL_HANDLE_DBC, fHdbc);\n SQLFreeHandle(SQL_HANDLE_ENV, fHenv);\n fPort = -1;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::Query(const char *sql)\n{\n \/\/ Execute SQL command. Result object must be deleted by the user.\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"Query\",\"ODBC not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLExecDirect(hstmt, (SQLCHAR*) sql, SQL_NTS);\n if (ExtractErrors(retcode, \"Query\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::SelectDataBase(const char *)\n{\n \/\/ Select a database. Returns 0 if successful, non-zero otherwise.\n \/\/ Does not implemented for ODBC driver. User should specify database\n \/\/ name at time of connection\n\n if (!IsConnected()) {\n Error(\"SelectDataBase\", \"not connected\");\n return -1;\n }\n\n Info(\"SelectDataBase\",\"Does not implemented for ODBC\");\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetDataBases(const char *)\n{\n \/\/ List all available databases. Wild is for wildcarding \"t%\" list all\n \/\/ databases starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetDataBases\", \"not connected\");\n return 0;\n }\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetTables(const char *, const char *)\n{\n \/\/ List all tables in the specified database. Wild is for wildcarding\n \/\/ \"t%\" list all tables starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetTables\", \"not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLTables(hstmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0);\n if (ExtractErrors(retcode, \"GetTables\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nTSQLResult *TODBCServer::GetColumns(const char*, const char *table, const char*)\n{\n \/\/ List all columns in specified table in the specified database.\n \/\/ Wild is for wildcarding \"t%\" list all columns starting with \"t\".\n \/\/ Returns a pointer to a TSQLResult object if successful, 0 otherwise.\n \/\/ The result object must be deleted by the user.\n\n if (!IsConnected()) {\n Error(\"GetColumns\", \"not connected\");\n return 0;\n }\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n\n retcode = SQLColumns(hstmt, NULL, 0, NULL, 0, (SQLCHAR*) table, SQL_NTS, NULL, 0);\n if (ExtractErrors(retcode, \"GetColumns\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCResult(hstmt);\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::CreateDataBase(const char*)\n{\n \/\/ Create a database. Returns 0 if successful, non-zero otherwise.\n\n if (!IsConnected()) {\n Error(\"CreateDataBase\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::DropDataBase(const char*)\n{\n \/\/ Drop (i.e. delete) a database. Returns 0 if successful, non-zero\n \/\/ otherwise.\n\n if (!IsConnected()) {\n Error(\"DropDataBase\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::Reload()\n{\n \/\/ Reload permission tables. Returns 0 if successful, non-zero\n \/\/ otherwise. User must have reload permissions.\n\n if (!IsConnected()) {\n Error(\"Reload\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TODBCServer::Shutdown()\n{\n \/\/ Shutdown the database server. Returns 0 if successful, non-zero\n \/\/ otherwise. User must have shutdown permissions.\n\n if (!IsConnected()) {\n Error(\"Shutdown\", \"not connected\");\n return -1;\n }\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nconst char *TODBCServer::ServerInfo()\n{\n \/\/ Return server info.\n\n if (!IsConnected()) {\n Error(\"ServerInfo\", \"not connected\");\n return 0;\n }\n\n return fInfo;\n}\n\n\n\/\/______________________________________________________________________________\nTSQLStatement *TODBCServer::Statement(const char *sql, Int_t bufsize)\n{\n if (!IsConnected()) {\n Error(\"Statement\", \"not connected\");\n return 0;\n }\n\n if (!sql || !*sql) {\n Error(\"Statement\", \"no query string specified\");\n return 0;\n }\n\n\/\/ SQLUINTEGER info = 0;\n\/\/ SQLGetInfo(fHdbc, SQL_PARAM_ARRAY_ROW_COUNTS, (SQLPOINTER)&info, sizeof(info), NULL);\n\/\/ if (info==SQL_PARC_BATCH) Info(\"Statement\",\"info==SQL_PARC_BATCH\"); else\n\/\/ if (info==SQL_PARC_NO_BATCH) Info(\"Statement\",\"info==SQL_PARC_NO_BATCH\"); else\n\/\/ Info(\"Statement\",\"info==%u\", info);\n\n\n SQLRETURN retcode;\n SQLHSTMT hstmt;\n\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, fHdbc, &hstmt);\n if (ExtractErrors(retcode, \"Statement\")) return 0;\n\n retcode = SQLPrepare(hstmt, (SQLCHAR*) sql, SQL_NTS);\n if (ExtractErrors(retcode, \"Statement\")) {\n SQLFreeHandle(SQL_HANDLE_STMT, hstmt);\n return 0;\n }\n\n return new TODBCStatement(hstmt, bufsize);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ Basket ball demo.\n\/\/ Serves as a test for the sphere vs trimesh collider\n\/\/ By Bram Stolk.\n\n#include <ode\/config.h>\n#include <assert.h>\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n#include <ode\/ode.h>\n#include <drawstuff\/drawstuff.h>\n\n#include \"basket_geom.h\" \/\/ this is our world mesh\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ some constants\n\n#define RADIUS 0.14\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\n\nstatic dBodyID sphbody;\nstatic dGeomID sphgeom;\n\nstatic dJointGroupID contactgroup;\nstatic dGeomID world_mesh;\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n assert(o1);\n assert(o2);\n\n if (dGeomIsSpace(o1) || dGeomIsSpace(o2))\n {\n fprintf(stderr,\"testing space %p %p\\n\", o1,o2);\n \/\/ colliding a space with something\n dSpaceCollide2(o1,o2,data,&nearCallback);\n \/\/ Note we do not want to test intersections within a space,\n \/\/ only between spaces.\n return;\n }\n\n\/\/ fprintf(stderr,\"testing geoms %p %p\\n\", o1, o2);\n\n const int N = 32;\n dContact contact[N];\n int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));\n if (n > 0) \n {\n for (int i=0; i<n; i++) \n {\n contact[i].surface.slip1 = 0.7;\n contact[i].surface.slip2 = 0.7;\n contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;\n contact[i].surface.mu = 50.0; \/\/ was: dInfinity\n contact[i].surface.soft_erp = 0.96;\n contact[i].surface.soft_cfm = 0.04;\n dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);\n dJointAttach (c,\n\t\t dGeomGetBody(contact[i].geom.g1),\n\t\t dGeomGetBody(contact[i].geom.g2));\n }\n }\n}\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n static float xyz[3] = {-8,0,5};\n static float hpr[3] = {0.0f,-29.5000f,0.0000f};\n dsSetViewpoint (xyz,hpr);\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n switch (cmd) \n {\n case ' ':\n break;\n }\n}\n\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n double simstep = 0.001; \/\/ 1ms simulation steps\n double dt = dsElapsedTime();\n\n int nrofsteps = (int) ceilf(dt\/simstep);\n\/\/ fprintf(stderr, \"dt=%f, nr of steps = %d\\n\", dt, nrofsteps);\n\n for (int i=0; i<nrofsteps && !pause; i++)\n {\n dSpaceCollide (space,0,&nearCallback);\n dWorldQuickStep (world, simstep);\n dJointGroupEmpty (contactgroup);\n }\n\n dsSetColor (1,1,1);\n const dReal *SPos = dBodyGetPosition(sphbody);\n const dReal *SRot = dBodyGetRotation(sphbody);\n float spos[3] = {SPos[0], SPos[1], SPos[2]};\n float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };\n dsDrawSphere\n (\n spos, \n srot, \n RADIUS\n );\n\n \/\/ draw world trimesh\n dsSetColor(0.4,0.7,0.9);\n dsSetTexture (DS_NONE);\n\n const dReal* Pos = dGeomGetPosition(world_mesh);\n float pos[3] = { Pos[0], Pos[1], Pos[2] };\n\n const dReal* Rot = dGeomGetRotation(world_mesh);\n float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };\n\n int numi = sizeof(world_indices) \/ sizeof(int);\n\n for (int i=0; i<numi\/3; i++)\n {\n int i0 = world_indices[i*3+0];\n int i1 = world_indices[i*3+1];\n int i2 = world_indices[i*3+2];\n float *v0 = world_vertices+i0*3;\n float *v1 = world_vertices+i1*3;\n float *v2 = world_vertices+i2*3;\n dsDrawTriangle(pos, rot, v0,v1,v2, true); \/\/ single precision draw\n }\n}\n\n\nint main (int argc, char **argv)\n{\n dMass m;\n dMatrix3 R;\n\n \/\/ setup pointers to drawstuff callback functions\n dsFunctions fn;\n fn.version = DS_VERSION;\n fn.start = &start;\n fn.step = &simLoop;\n fn.command = &command;\n fn.stop = 0;\n fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n if(argc==2)\n fn.path_to_textures = argv[1];\n\n \/\/ create world\n world = dWorldCreate();\n space = dHashSpaceCreate (0);\n contactgroup = dJointGroupCreate (0);\n dWorldSetGravity (world,0,0,-9.8);\n dWorldSetQuickStepNumIterations (world, 64);\n\n \/\/ Create a static world using a triangle mesh that we can collide with.\n int numv = sizeof(world_vertices)\/sizeof(dReal);\n int numi = sizeof(world_indices)\/ sizeof(int);\n printf(\"numv=%d, numi=%d\\n\", numv, numi);\n dTriMeshDataID Data = dGeomTriMeshDataCreate();\n\n\/\/ fprintf(stderr,\"Building Single Precision Mesh\\n\");\n\n dGeomTriMeshDataBuildSingle\n (\n Data, \n world_vertices, \n 3 * sizeof(float), \n numv, \n world_indices, \n numi, \n 3 * sizeof(int)\n );\n\n world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);\n dGeomSetPosition(world_mesh, 0, 0, 0.5);\n dRFromAxisAndAngle (R, 0,1,0, 0.0);\n dGeomSetRotation (world_mesh, R);\n\n float sx=0.0, sy=3.40, sz=6.80;\n sphbody = dBodyCreate (world);\n dMassSetSphere (&m,1,RADIUS);\n dBodySetMass (sphbody,&m);\n sphgeom = dCreateSphere(0, RADIUS);\n dGeomSetBody (sphgeom,sphbody);\n dBodySetPosition (sphbody, sx, sy, sz);\n dSpaceAdd (space, sphgeom);\n\n \/\/ run simulation\n dsSimulationLoop (argc,argv,352,288,&fn);\n\n \/\/ Causes segm violation? Why?\n \/\/ (because dWorldDestroy() destroys body connected to geom; must call first!)\n dGeomDestroy(sphgeom);\n dGeomDestroy (world_mesh);\n\n dJointGroupEmpty (contactgroup);\n dJointGroupDestroy (contactgroup);\n dSpaceDestroy (space);\n dWorldDestroy (world);\n\n return 0;\n}\n\n<commit_msg>Added sim reset<commit_after>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ Basket ball demo.\n\/\/ Serves as a test for the sphere vs trimesh collider\n\/\/ By Bram Stolk.\n\/\/ Press the spacebar to reset the position of the ball.\n\n#include <ode\/config.h>\n#include <assert.h>\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n#include <ode\/ode.h>\n#include <drawstuff\/drawstuff.h>\n\n#include \"basket_geom.h\" \/\/ this is our world mesh\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ some constants\n\n#define RADIUS 0.14\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\n\nstatic dBodyID sphbody;\nstatic dGeomID sphgeom;\n\nstatic dJointGroupID contactgroup;\nstatic dGeomID world_mesh;\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n assert(o1);\n assert(o2);\n\n if (dGeomIsSpace(o1) || dGeomIsSpace(o2))\n {\n fprintf(stderr,\"testing space %p %p\\n\", o1,o2);\n \/\/ colliding a space with something\n dSpaceCollide2(o1,o2,data,&nearCallback);\n \/\/ Note we do not want to test intersections within a space,\n \/\/ only between spaces.\n return;\n }\n\n\/\/ fprintf(stderr,\"testing geoms %p %p\\n\", o1, o2);\n\n const int N = 32;\n dContact contact[N];\n int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));\n if (n > 0) \n {\n for (int i=0; i<n; i++) \n {\n contact[i].surface.slip1 = 0.7;\n contact[i].surface.slip2 = 0.7;\n contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;\n contact[i].surface.mu = 50.0; \/\/ was: dInfinity\n contact[i].surface.soft_erp = 0.96;\n contact[i].surface.soft_cfm = 0.04;\n dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);\n dJointAttach (c,\n\t\t dGeomGetBody(contact[i].geom.g1),\n\t\t dGeomGetBody(contact[i].geom.g2));\n }\n }\n}\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n static float xyz[3] = {-8,0,5};\n static float hpr[3] = {0.0f,-29.5000f,0.0000f};\n dsSetViewpoint (xyz,hpr);\n}\n\n\n\nstatic void reset_ball(void)\n{\n float sx=0.0, sy=3.40, sz=6.80;\n dBodySetPosition (sphbody, sx, sy, sz);\r\n dBodySetLinearVel (sphbody, 0,0,0);\r\n dBodySetAngularVel (sphbody, 0,0,0);\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n switch (cmd) \n {\n case ' ':\n\t reset_ball();\n break;\n }\n}\n\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n double simstep = 0.001; \/\/ 1ms simulation steps\n double dt = dsElapsedTime();\n\n int nrofsteps = (int) ceilf(dt\/simstep);\n\/\/ fprintf(stderr, \"dt=%f, nr of steps = %d\\n\", dt, nrofsteps);\n\n for (int i=0; i<nrofsteps && !pause; i++)\n {\n dSpaceCollide (space,0,&nearCallback);\n dWorldQuickStep (world, simstep);\n dJointGroupEmpty (contactgroup);\n }\n\n dsSetColor (1,1,1);\n const dReal *SPos = dBodyGetPosition(sphbody);\n const dReal *SRot = dBodyGetRotation(sphbody);\n float spos[3] = {SPos[0], SPos[1], SPos[2]};\n float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };\n dsDrawSphere\n (\n spos, \n srot, \n RADIUS\n );\n\n \/\/ draw world trimesh\n dsSetColor(0.4,0.7,0.9);\n dsSetTexture (DS_NONE);\n\n const dReal* Pos = dGeomGetPosition(world_mesh);\n float pos[3] = { Pos[0], Pos[1], Pos[2] };\n\n const dReal* Rot = dGeomGetRotation(world_mesh);\n float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };\n\n int numi = sizeof(world_indices) \/ sizeof(int);\n\n for (int i=0; i<numi\/3; i++)\n {\n int i0 = world_indices[i*3+0];\n int i1 = world_indices[i*3+1];\n int i2 = world_indices[i*3+2];\n float *v0 = world_vertices+i0*3;\n float *v1 = world_vertices+i1*3;\n float *v2 = world_vertices+i2*3;\n dsDrawTriangle(pos, rot, v0,v1,v2, true); \/\/ single precision draw\n }\n}\n\n\nint main (int argc, char **argv)\n{\n dMass m;\n dMatrix3 R;\n\n \/\/ setup pointers to drawstuff callback functions\n dsFunctions fn;\n fn.version = DS_VERSION;\n fn.start = &start;\n fn.step = &simLoop;\n fn.command = &command;\n fn.stop = 0;\n fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n if(argc==2)\n fn.path_to_textures = argv[1];\n\n \/\/ create world\n world = dWorldCreate();\n space = dHashSpaceCreate (0);\n contactgroup = dJointGroupCreate (0);\n dWorldSetGravity (world,0,0,-9.8);\n dWorldSetQuickStepNumIterations (world, 64);\n\n \/\/ Create a static world using a triangle mesh that we can collide with.\n int numv = sizeof(world_vertices)\/sizeof(dReal);\n int numi = sizeof(world_indices)\/ sizeof(int);\n printf(\"numv=%d, numi=%d\\n\", numv, numi);\n dTriMeshDataID Data = dGeomTriMeshDataCreate();\n\n\/\/ fprintf(stderr,\"Building Single Precision Mesh\\n\");\n\n dGeomTriMeshDataBuildSingle\n (\n Data, \n world_vertices, \n 3 * sizeof(float), \n numv, \n world_indices, \n numi, \n 3 * sizeof(int)\n );\n\n world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);\n dGeomSetPosition(world_mesh, 0, 0, 0.5);\n dRFromAxisAndAngle (R, 0,1,0, 0.0);\n dGeomSetRotation (world_mesh, R);\n\n float sx=0.0, sy=3.40, sz=6.80;\n sphbody = dBodyCreate (world);\n dMassSetSphere (&m,1,RADIUS);\n dBodySetMass (sphbody,&m);\n sphgeom = dCreateSphere(0, RADIUS);\n dGeomSetBody (sphgeom,sphbody);\n reset_ball();\n dSpaceAdd (space, sphgeom);\n\n \/\/ run simulation\n dsSimulationLoop (argc,argv,352,288,&fn);\n\n \/\/ Causes segm violation? Why?\n \/\/ (because dWorldDestroy() destroys body connected to geom; must call first!)\n dGeomDestroy(sphgeom);\n dGeomDestroy (world_mesh);\n\n dJointGroupEmpty (contactgroup);\n dJointGroupDestroy (contactgroup);\n dSpaceDestroy (space);\n dWorldDestroy (world);\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 6\/14\/2020, 3:53:32 AM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} \/ rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n ll W, H, K;\n\npublic:\n Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}\n\n ll answer()\n {\n ll ans{0};\n for (auto s{0LL}; s < W - 1; ++s)\n {\n for (auto y{1LL}; 2 * K - (H - y) * s + H - 2 >= 0 && y < H; ++y)\n {\n ll tmp{calc(s, y)};\n if (s == 0)\n {\n ans += tmp;\n }\n else\n {\n ans += 2 * tmp;\n }\n }\n }\n return ans;\n }\n\nprivate:\n ll calc(ll s, ll y)\n {\n ll R{2 * K - (H - y) * s + gcd(H, s) - 2};\n if (R < 0)\n {\n return 0;\n }\n ll ans{min(W - s - 1, R \/ H)};\n ll x{R \/ H + 1};\n if (x + s < W && H * x - gcd(H - y, x) - gcd(y, x + s) <= R)\n {\n ++ans;\n }\n return ans;\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll W, H, K;\n cin >> W >> H >> K;\n Solve solve(W, H, K), solve2(H, W, K);\n ll ans{2 * solve.answer() + 2 * solve2.answer()};\n cout << ans << endl;\n}\n<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1\n\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 6\/14\/2020, 3:53:32 AM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} \/ rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n ll W, H, K;\n\npublic:\n Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}\n\n ll answer()\n {\n ll ans{0};\n for (auto s{0LL}; s < W - 1; ++s)\n {\n for (auto y{H - 1}; 2 * K - (H - y) * s + H - 2 >= 0 && y >= 0LL; --y)\n {\n ll tmp{calc(s, y)};\n if (s == 0)\n {\n ans += tmp;\n }\n else\n {\n ans += 2 * tmp;\n }\n }\n }\n return ans;\n }\n\nprivate:\n ll calc(ll s, ll y)\n {\n ll R{2 * K - (H - y) * s + gcd(H, s) - 2};\n if (R < 0)\n {\n return 0;\n }\n ll ans{min(W - s - 1, R \/ H)};\n ll x{R \/ H + 1};\n if (x + s < W && H * x - gcd(H - y, x) - gcd(y, x + s) <= R)\n {\n ++ans;\n }\n return ans;\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll W, H, K;\n cin >> W >> H >> K;\n Solve solve(W, H, K), solve2(H, W, K);\n ll ans{2 * solve.answer() + 2 * solve2.answer()};\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ MOOSE includes\n#include \"MultiAppVariableValueSamplePostprocessorTransfer.h\"\n#include \"MooseTypes.h\"\n#include \"FEProblem.h\"\n#include \"MultiApp.h\"\n#include \"MooseMesh.h\"\n\n\/\/ libMesh includes\n#include \"libmesh\/meshfree_interpolation.h\"\n#include \"libmesh\/system.h\"\n\ntemplate<>\nInputParameters validParams<MultiAppVariableValueSamplePostprocessorTransfer>()\n{\n InputParameters params = validParams<MultiAppTransfer>();\n params.addRequiredParam<PostprocessorName>(\"postprocessor\", \"The name of the postprocessor in the MultiApp to transfer the value to. This should most likely be a Reporter Postprocessor.\");\n params.addRequiredParam<VariableName>(\"source_variable\", \"The variable to transfer from.\");\n return params;\n}\n\nMultiAppVariableValueSamplePostprocessorTransfer::MultiAppVariableValueSamplePostprocessorTransfer(const InputParameters & parameters) :\n MultiAppTransfer(parameters),\n _postprocessor_name(getParam<PostprocessorName>(\"postprocessor\")),\n _from_var_name(getParam<VariableName>(\"source_variable\"))\n{\n}\n\nvoid\nMultiAppVariableValueSamplePostprocessorTransfer::execute()\n{\n _console << \"Beginning VariableValueSamplePostprocessorTransfer \" << name() << std::endl;\n\n switch (_direction)\n {\n case TO_MULTIAPP:\n {\n FEProblemBase & from_problem = _multi_app->problemBase();\n MooseVariable & from_var = from_problem.getVariable(0, _from_var_name);\n SystemBase & from_system_base = from_var.sys();\n SubProblem & from_sub_problem = from_system_base.subproblem();\n\n MooseMesh & from_mesh = from_problem.mesh();\n\n std::unique_ptr<PointLocatorBase> pl = from_mesh.getPointLocator();\n\n for (unsigned int i=0; i<_multi_app->numGlobalApps(); i++)\n {\n Real value = -std::numeric_limits<Real>::max();\n\n { \/\/ Get the value of the variable at the point where this multiapp is in the master domain\n\n Point multi_app_position = _multi_app->position(i);\n\n std::vector<Point> point_vec(1, multi_app_position);\n\n \/\/ First find the element the hit lands in\n const Elem * elem = (*pl)(multi_app_position);\n\n if (elem && elem->processor_id() == from_mesh.processor_id())\n {\n from_sub_problem.reinitElemPhys(elem, point_vec, 0);\n\n mooseAssert(from_var.sln().size() == 1, \"No values in u!\");\n value = from_var.sln()[0];\n }\n\n _communicator.max(value);\n }\n\n if (_multi_app->hasLocalApp(i))\n _multi_app->appProblemBase(i).getPostprocessorValue(_postprocessor_name) = value;\n }\n\n break;\n }\n case FROM_MULTIAPP:\n {\n mooseError(\"Can't transfer a variable value from a MultiApp to a Postprocessor in the Master.\");\n break;\n }\n }\n\n _console << \"Finished VariableValueSamplePostprocessorTransfer \" << name() << std::endl;\n}\n<commit_msg>One more out_of_mesh_mode() call<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ MOOSE includes\n#include \"MultiAppVariableValueSamplePostprocessorTransfer.h\"\n#include \"MooseTypes.h\"\n#include \"FEProblem.h\"\n#include \"MultiApp.h\"\n#include \"MooseMesh.h\"\n\n\/\/ libMesh includes\n#include \"libmesh\/meshfree_interpolation.h\"\n#include \"libmesh\/system.h\"\n\ntemplate<>\nInputParameters validParams<MultiAppVariableValueSamplePostprocessorTransfer>()\n{\n InputParameters params = validParams<MultiAppTransfer>();\n params.addRequiredParam<PostprocessorName>(\"postprocessor\", \"The name of the postprocessor in the MultiApp to transfer the value to. This should most likely be a Reporter Postprocessor.\");\n params.addRequiredParam<VariableName>(\"source_variable\", \"The variable to transfer from.\");\n return params;\n}\n\nMultiAppVariableValueSamplePostprocessorTransfer::MultiAppVariableValueSamplePostprocessorTransfer(const InputParameters & parameters) :\n MultiAppTransfer(parameters),\n _postprocessor_name(getParam<PostprocessorName>(\"postprocessor\")),\n _from_var_name(getParam<VariableName>(\"source_variable\"))\n{\n}\n\nvoid\nMultiAppVariableValueSamplePostprocessorTransfer::execute()\n{\n _console << \"Beginning VariableValueSamplePostprocessorTransfer \" << name() << std::endl;\n\n switch (_direction)\n {\n case TO_MULTIAPP:\n {\n FEProblemBase & from_problem = _multi_app->problemBase();\n MooseVariable & from_var = from_problem.getVariable(0, _from_var_name);\n SystemBase & from_system_base = from_var.sys();\n SubProblem & from_sub_problem = from_system_base.subproblem();\n\n MooseMesh & from_mesh = from_problem.mesh();\n\n std::unique_ptr<PointLocatorBase> pl = from_mesh.getPointLocator();\n\n pl->enable_out_of_mesh_mode();\n\n for (unsigned int i=0; i<_multi_app->numGlobalApps(); i++)\n {\n Real value = -std::numeric_limits<Real>::max();\n\n { \/\/ Get the value of the variable at the point where this multiapp is in the master domain\n\n Point multi_app_position = _multi_app->position(i);\n\n std::vector<Point> point_vec(1, multi_app_position);\n\n \/\/ First find the element the hit lands in\n const Elem * elem = (*pl)(multi_app_position);\n\n if (elem && elem->processor_id() == from_mesh.processor_id())\n {\n from_sub_problem.reinitElemPhys(elem, point_vec, 0);\n\n mooseAssert(from_var.sln().size() == 1, \"No values in u!\");\n value = from_var.sln()[0];\n }\n\n _communicator.max(value);\n }\n\n if (_multi_app->hasLocalApp(i))\n _multi_app->appProblemBase(i).getPostprocessorValue(_postprocessor_name) = value;\n }\n\n break;\n }\n case FROM_MULTIAPP:\n {\n mooseError(\"Can't transfer a variable value from a MultiApp to a Postprocessor in the Master.\");\n break;\n }\n }\n\n _console << \"Finished VariableValueSamplePostprocessorTransfer \" << name() << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <cstring>\n#include <sstream>\n\n#include <sys\/wait.h>\n#include <signal.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <osquery\/core.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/sql.h>\n\n#include \"osquery\/core\/watcher.h\"\n\nextern char** environ;\n\nnamespace fs = boost::filesystem;\n\nnamespace osquery {\n\nconst std::map<WatchdogLimitType, std::vector<size_t> > kWatchdogLimits = {\n {MEMORY_LIMIT, {50, 20, 10}},\n {UTILIZATION_LIMIT, {90, 70, 60}},\n \/\/ Number of seconds the worker should run, else consider the exit fatal.\n {RESPAWN_LIMIT, {20, 20, 20}},\n \/\/ If the worker respawns too quickly, backoff on creating additional.\n {RESPAWN_DELAY, {5, 5, 5}},\n \/\/ Seconds of tolerable sustained latency.\n {LATENCY_LIMIT, {5, 5, 3}},\n \/\/ How often to poll for performance limit violations.\n {INTERVAL, {3, 3, 3}}, };\n\nFLAG(int32,\n watchdog_level,\n 1,\n \"Performance limit level (0=loose, 1=normal, 2=restrictive)\");\n\nFLAG(bool, disable_watchdog, false, \"Disable userland watchdog process\");\n\nbool Watcher::ok() {\n ::sleep(getWorkerLimit(INTERVAL));\n return (worker_ >= 0);\n}\n\nbool Watcher::watch() {\n int status;\n pid_t result = waitpid(worker_, &status, WNOHANG);\n if (worker_ == 0 || result == worker_) {\n \/\/ Worker does not exist or never existed.\n return false;\n } else if (result == 0) {\n \/\/ If the inspect finds problems it will stop\/restart the worker.\n if (!isWorkerSane()) {\n stopWorker();\n return false;\n }\n }\n return true;\n}\n\nvoid Watcher::stopWorker() {\n kill(worker_, SIGKILL);\n worker_ = 0;\n \/\/ Clean up the defunct (zombie) process.\n waitpid(-1, 0, 0);\n}\n\nbool Watcher::isWorkerSane() {\n auto rows =\n SQL::selectAllFrom(\"processes\", \"pid\", tables::EQUALS, INTEGER(worker_));\n if (rows.size() == 0) {\n \/\/ Could not find worker process?\n return false;\n }\n\n \/\/ Compare CPU utilization since last check.\n BIGINT_LITERAL footprint, user_time, system_time;\n \/\/ IV is the check interval in seconds, and utilization is set per-second.\n auto iv = getWorkerLimit(INTERVAL);\n\n try {\n user_time = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"user_time\")) \/ iv;\n system_time = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"system_time\")) \/ iv;\n footprint = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"phys_footprint\"));\n } catch (const std::exception& e) {\n sustained_latency_ = 0;\n }\n\n if (current_user_time_ + getWorkerLimit(UTILIZATION_LIMIT) < user_time ||\n current_system_time_ + getWorkerLimit(UTILIZATION_LIMIT) < system_time) {\n sustained_latency_++;\n } else {\n sustained_latency_ = 0;\n }\n\n current_user_time_ = user_time;\n current_system_time_ = system_time;\n\n if (sustained_latency_ * iv >= getWorkerLimit(LATENCY_LIMIT)) {\n LOG(WARNING) << \"osqueryd worker system performance limits exceeded\";\n return false;\n }\n\n if (footprint > getWorkerLimit(MEMORY_LIMIT) * 1024 * 1024) {\n LOG(WARNING) << \"osqueryd worker memory limits exceeded\";\n return false;\n }\n\n \/\/ The worker is sane, no action needed.\n return true;\n}\n\nvoid Watcher::createWorker() {\n if (last_respawn_time_ > getUnixTime() - getWorkerLimit(RESPAWN_LIMIT)) {\n LOG(WARNING) << \"osqueryd worker respawning too quickly\";\n ::sleep(getWorkerLimit(RESPAWN_DELAY));\n }\n\n worker_ = fork();\n if (worker_ < 0) {\n \/\/ Unrecoverable error, cannot create a worker process.\n LOG(ERROR) << \"osqueryd could not create a worker process\";\n ::exit(EXIT_FAILURE);\n } else if (worker_ == 0) {\n \/\/ This is the new worker process, no watching needed.\n setenv(\"OSQUERYD_WORKER\", std::to_string(getpid()).c_str(), 1);\n fs::path exec_path(fs::initial_path<fs::path>());\n exec_path = fs::system_complete(fs::path(argv_[0]));\n execve(exec_path.string().c_str(), argv_, environ);\n \/\/ Code will never reach this point.\n ::exit(EXIT_FAILURE);\n }\n\n VLOG(1) << \"osqueryd watcher (\" << getpid() << \") executing worker (\"\n << worker_ << \")\";\n}\n\nvoid Watcher::resetCounters() {\n \/\/ Reset the monitoring counters for the watcher.\n sustained_latency_ = 0;\n current_user_time_ = 0;\n current_system_time_ = 0;\n last_respawn_time_ = getUnixTime();\n}\n\nvoid Watcher::initWorker() {\n \/\/ Set the worker's process name.\n size_t name_size = strlen(argv_[0]);\n for (int i = 0; i < argc_; i++) {\n if (argv_[i] != nullptr) {\n memset(argv_[i], 0, strlen(argv_[i]));\n }\n }\n strncpy(argv_[0], name_.c_str(), name_size);\n\n \/\/ Start a watcher watcher thread to exit the process if the watcher exits.\n Dispatcher::getInstance().addService(\n std::make_shared<WatcherWatcherRunner>(getppid()));\n}\n\nbool isOsqueryWorker() {\n return (getenv(\"OSQUERYD_WORKER\") != nullptr);\n}\n\nvoid WatcherWatcherRunner::enter() {\n while (true) {\n if (getppid() != watcher_) {\n \/\/ Watcher died, the worker must follow.\n VLOG(1) << \"osqueryd worker (\" << getpid()\n << \") detected killed watcher (\" << watcher_ << \")\";\n ::exit(EXIT_SUCCESS);\n }\n interruptableSleep(getWorkerLimit(INTERVAL) * 1000);\n }\n}\n\nsize_t getWorkerLimit(WatchdogLimitType name, int level) {\n if (kWatchdogLimits.count(name) == 0) {\n return 0;\n }\n\n \/\/ If no level was provided then use the default (config\/switch).\n if (level == -1) {\n level = FLAGS_watchdog_level;\n }\n if (level > 3) {\n return kWatchdogLimits.at(name).back();\n }\n return kWatchdogLimits.at(name).at(level);\n}\n\nvoid initWorkerWatcher(const std::string& name, int argc, char* argv[]) {\n \/\/ The watcher will forever monitor and spawn additional workers.\n Watcher watcher(argc, argv);\n watcher.setWorkerName(name);\n\n if (isOsqueryWorker()) {\n \/\/ Do not start watching\/spawning if this process is a worker.\n watcher.initWorker();\n } else {\n do {\n if (!watcher.watch()) {\n \/\/ The watcher failed, create a worker.\n watcher.createWorker();\n watcher.resetCounters();\n }\n } while (watcher.ok());\n\n \/\/ Executation should never reach this point.\n ::exit(EXIT_FAILURE);\n }\n}\n}\n<commit_msg>Use full path for exec in watcher<commit_after>\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include <cstring>\n#include <sstream>\n\n#include <sys\/wait.h>\n#include <signal.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <osquery\/core.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/sql.h>\n\n#include \"osquery\/core\/watcher.h\"\n\nextern char** environ;\n\nnamespace fs = boost::filesystem;\n\nnamespace osquery {\n\nconst std::map<WatchdogLimitType, std::vector<size_t> > kWatchdogLimits = {\n {MEMORY_LIMIT, {50, 20, 10}},\n {UTILIZATION_LIMIT, {90, 70, 60}},\n \/\/ Number of seconds the worker should run, else consider the exit fatal.\n {RESPAWN_LIMIT, {20, 20, 20}},\n \/\/ If the worker respawns too quickly, backoff on creating additional.\n {RESPAWN_DELAY, {5, 5, 5}},\n \/\/ Seconds of tolerable sustained latency.\n {LATENCY_LIMIT, {5, 5, 3}},\n \/\/ How often to poll for performance limit violations.\n {INTERVAL, {3, 3, 3}}, };\n\nFLAG(int32,\n watchdog_level,\n 1,\n \"Performance limit level (0=loose, 1=normal, 2=restrictive)\");\n\nFLAG(bool, disable_watchdog, false, \"Disable userland watchdog process\");\n\nbool Watcher::ok() {\n ::sleep(getWorkerLimit(INTERVAL));\n return (worker_ >= 0);\n}\n\nbool Watcher::watch() {\n int status;\n pid_t result = waitpid(worker_, &status, WNOHANG);\n if (worker_ == 0 || result == worker_) {\n \/\/ Worker does not exist or never existed.\n return false;\n } else if (result == 0) {\n \/\/ If the inspect finds problems it will stop\/restart the worker.\n if (!isWorkerSane()) {\n stopWorker();\n return false;\n }\n }\n return true;\n}\n\nvoid Watcher::stopWorker() {\n kill(worker_, SIGKILL);\n worker_ = 0;\n \/\/ Clean up the defunct (zombie) process.\n waitpid(-1, 0, 0);\n}\n\nbool Watcher::isWorkerSane() {\n auto rows =\n SQL::selectAllFrom(\"processes\", \"pid\", tables::EQUALS, INTEGER(worker_));\n if (rows.size() == 0) {\n \/\/ Could not find worker process?\n return false;\n }\n\n \/\/ Compare CPU utilization since last check.\n BIGINT_LITERAL footprint, user_time, system_time;\n \/\/ IV is the check interval in seconds, and utilization is set per-second.\n auto iv = getWorkerLimit(INTERVAL);\n\n try {\n user_time = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"user_time\")) \/ iv;\n system_time = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"system_time\")) \/ iv;\n footprint = AS_LITERAL(BIGINT_LITERAL, rows[0].at(\"phys_footprint\"));\n } catch (const std::exception& e) {\n sustained_latency_ = 0;\n }\n\n if (current_user_time_ + getWorkerLimit(UTILIZATION_LIMIT) < user_time ||\n current_system_time_ + getWorkerLimit(UTILIZATION_LIMIT) < system_time) {\n sustained_latency_++;\n } else {\n sustained_latency_ = 0;\n }\n\n current_user_time_ = user_time;\n current_system_time_ = system_time;\n\n if (sustained_latency_ * iv >= getWorkerLimit(LATENCY_LIMIT)) {\n LOG(WARNING) << \"osqueryd worker system performance limits exceeded\";\n return false;\n }\n\n if (footprint > getWorkerLimit(MEMORY_LIMIT) * 1024 * 1024) {\n LOG(WARNING) << \"osqueryd worker memory limits exceeded\";\n return false;\n }\n\n \/\/ The worker is sane, no action needed.\n return true;\n}\n\nvoid Watcher::createWorker() {\n if (last_respawn_time_ > getUnixTime() - getWorkerLimit(RESPAWN_LIMIT)) {\n LOG(WARNING) << \"osqueryd worker respawning too quickly\";\n ::sleep(getWorkerLimit(RESPAWN_DELAY));\n }\n\n \/\/ Get the path of the current process.\n auto qd = SQL::selectAllFrom(\"processes\", \"pid\", tables::EQUALS,\n INTEGER(getpid()));\n if (qd.size() != 1 || qd[0].count(\"path\") == 0 || qd[0][\"path\"].size() == 0) {\n LOG(ERROR) << \"osquery watcher cannot determine process path\";\n ::exit(EXIT_FAILURE);\n }\n\n worker_ = fork();\n if (worker_ < 0) {\n \/\/ Unrecoverable error, cannot create a worker process.\n LOG(ERROR) << \"osqueryd could not create a worker process\";\n ::exit(EXIT_FAILURE);\n } else if (worker_ == 0) {\n \/\/ This is the new worker process, no watching needed.\n setenv(\"OSQUERYD_WORKER\", std::to_string(getpid()).c_str(), 1);\n \/\/ Get the complete path of the osquery process binary.\n auto exec_path = fs::system_complete(fs::path(qd[0][\"path\"]));\n execve(exec_path.string().c_str(), argv_, environ);\n \/\/ Code will never reach this point.\n ::exit(EXIT_FAILURE);\n }\n\n VLOG(1) << \"osqueryd watcher (\" << getpid() << \") executing worker (\"\n << worker_ << \")\";\n}\n\nvoid Watcher::resetCounters() {\n \/\/ Reset the monitoring counters for the watcher.\n sustained_latency_ = 0;\n current_user_time_ = 0;\n current_system_time_ = 0;\n last_respawn_time_ = getUnixTime();\n}\n\nvoid Watcher::initWorker() {\n \/\/ Set the worker's process name.\n size_t name_size = strlen(argv_[0]);\n for (int i = 0; i < argc_; i++) {\n if (argv_[i] != nullptr) {\n memset(argv_[i], 0, strlen(argv_[i]));\n }\n }\n strncpy(argv_[0], name_.c_str(), name_size);\n\n \/\/ Start a watcher watcher thread to exit the process if the watcher exits.\n Dispatcher::getInstance().addService(\n std::make_shared<WatcherWatcherRunner>(getppid()));\n}\n\nbool isOsqueryWorker() {\n return (getenv(\"OSQUERYD_WORKER\") != nullptr);\n}\n\nvoid WatcherWatcherRunner::enter() {\n while (true) {\n if (getppid() != watcher_) {\n \/\/ Watcher died, the worker must follow.\n VLOG(1) << \"osqueryd worker (\" << getpid()\n << \") detected killed watcher (\" << watcher_ << \")\";\n ::exit(EXIT_SUCCESS);\n }\n interruptableSleep(getWorkerLimit(INTERVAL) * 1000);\n }\n}\n\nsize_t getWorkerLimit(WatchdogLimitType name, int level) {\n if (kWatchdogLimits.count(name) == 0) {\n return 0;\n }\n\n \/\/ If no level was provided then use the default (config\/switch).\n if (level == -1) {\n level = FLAGS_watchdog_level;\n }\n if (level > 3) {\n return kWatchdogLimits.at(name).back();\n }\n return kWatchdogLimits.at(name).at(level);\n}\n\nvoid initWorkerWatcher(const std::string& name, int argc, char* argv[]) {\n \/\/ The watcher will forever monitor and spawn additional workers.\n Watcher watcher(argc, argv);\n watcher.setWorkerName(name);\n\n if (isOsqueryWorker()) {\n \/\/ Do not start watching\/spawning if this process is a worker.\n watcher.initWorker();\n } else {\n do {\n if (!watcher.watch()) {\n \/\/ The watcher failed, create a worker.\n watcher.createWorker();\n watcher.resetCounters();\n }\n } while (watcher.ok());\n\n \/\/ Executation should never reach this point.\n ::exit(EXIT_FAILURE);\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * lengthPrefixStrings.cpp\n *\n * Author: Patrick Rummage (patrickbrummage@gmail.com)\n *\n * Objective:\n * Implement a string type that stores its length at location[0]. \n * Define functions to append, concatenate, create substrings, and \n * retrieve characters from strings of this type.\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\ntypedef char *lengthString;\n\nchar characterAt(lengthString s, int position)\n{\n return s[position + 1];\n}\n\nvoid append(lengthString &s, char c)\n{\n int oldLength = s[0];\n s[oldLength + 1] = c;\n s[0] = oldLength + 1;\n}\n\nvoid concatenate(lengthString &s1, lengthString s2)\n{\n int s1_length = s1[0];\n int s2_length = s2[0];\n int s1_newLength = s1_length + s2_length;\n for (int i = 1; i <= s2_length; i++)\n {\n s1[s1_length + i] = s2[i];\n }\n s1[0] = s1_newLength;\n}\n\nlengthString substring(lengthString s, int position, int length)\n{\n lengthString sub = new char[length + 1];\n sub[0] = length;\n for (int i = 1; i <= length; i++)\n {\n sub[i] = s[position + i];\n }\n return sub;\n}\n\nvoid output(lengthString s)\n{\n int length = s[0];\n for(int i = 1; i <= length; i++)\n {\n cout << s[i];\n }\n cout << \"\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n \/\/Test append()\n lengthString input1 = new char[0];\n cout << \"Enter a string: \";\n char inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input1, inputChar);\n inputChar = cin.get(); \n }\n output(input1);\n\n \/\/Test concatenate()\n lengthString input2 = new char[0];\n cout << \"Enter another string: \";\n inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input2, inputChar);\n inputChar = cin.get(); \n }\n concatenate(input1, input2);\n output(input1);\n\n \/\/Test substring()\n lengthString subString = substring(input1, 3, 4);\n output(subString);\n \n return 0;\n}\n\n<commit_msg>concatenate function creates new array<commit_after>\/**\n * lengthPrefixStrings.cpp\n *\n * Author: Patrick Rummage (patrickbrummage@gmail.com)\n *\n * Objective:\n * Implement a string type that stores its length at location[0]. \n * Define functions to append, concatenate, create substrings, and \n * retrieve characters from strings of this type.\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\ntypedef char *lengthString;\n\nchar characterAt(lengthString s, int position)\n{\n return s[position + 1];\n}\n\nvoid append(lengthString &s, char c)\n{\n int oldLength = s[0];\n s[oldLength + 1] = c;\n s[0] = oldLength + 1;\n}\n\nvoid concatenate(lengthString &s1, lengthString s2)\n{\n int s1_length = s1[0];\n int s2_length = s2[0];\n int newLength = s1_length + s2_length;\n lengthString newS = new char[newLength + 1];\n newS[0] = newLength;\n for (int i = 1; i <= s1_length; i++)\n {\n newS[i] = s1[1];\n }\n for (int i = 1; i <= s2_length; i++)\n {\n s1[s1_length + i] = s2[i];\n }\n delete[] s1;\n s1 = newS;\n}\n\nlengthString substring(lengthString s, int position, int length)\n{\n lengthString sub = new char[length + 1];\n sub[0] = length;\n for (int i = 1; i <= length; i++)\n {\n sub[i] = s[position + i];\n }\n return sub;\n}\n\/\/BROKEN!!\nvoid replaceString(lengthString &s, lengthString target, lengthString replaceText)\n{\n int s_length = s[0];\n int target_length = target[0];\n int replace_length = replaceText[0];\n int matchPosition = 0;\n for (int pos = 1; pos <= s_length; pos++)\n {\n if (s[pos] == target[1])\n {\n matchPosition = s[pos];\n }\n }\n if (matchPosition > 0)\n {\n lengthString matchString = substring(s, matchPosition, target_length);\n if (matchString == target)\n {\n for (int i = 1; i <= replace_length; i++)\n {\n s[matchPosition + i] = replaceText[i];\n }\n }\n }\n}\n\nvoid input(lengthString &s)\n{\n\n char inputChar = cin.get();\n while (inputChar != 10)\n {\n append(s, inputChar);\n inputChar = cin.get(); \n }\n}\nvoid output(lengthString s)\n{\n int length = s[0];\n for(int i = 1; i <= length; i++)\n {\n cout << s[i];\n }\n cout << \"\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n \/\/Test append()\n lengthString string1 = new char[0];\n cout << \"Enter a string: \";\n input(string1);\n output(string1);\n\n \/\/Test concatenate()\n lengthString string2 = new char[0];\n cout << \"Enter another string: \";\n input(string2);\n concatenate(string1, string2);\n output(string1);\n\n \/\/Test substring()\n lengthString subString = substring(string1, 3, 4);\n output(subString);\n\n \/\/Test replaceString\n lengthString find = new char[0];\n lengthString replace = new char[0];\n cout << \"Enter a string to find: \";\n input(find);\n cout << \"Replace with: \";\n input(replace);\n replaceString(string1, find, replace);\n output(string1);\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n**\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2013 Aldebaran Robotics\n*\/\n#include \"pyobject.hpp\"\n#include <boost\/python.hpp>\n#include <boost\/python\/raw_function.hpp>\n#include \"pyfuture.hpp\"\n#include \"pysignal.hpp\"\n#include \"pyproperty.hpp\"\n#include \"gil.hpp\"\n#include \"error.hpp\"\n#include <qitype\/genericobjectbuilder.hpp>\n\nqiLogCategory(\"qipy.object\");\n\nnamespace qi { namespace py {\n\n\n boost::python::object import_inspect() {\n static bool plouf = false;\n static boost::python::object obj;\n if (!plouf) {\n obj = boost::python::import(\"inspect\");\n plouf = true;\n }\n return obj;\n }\n\n struct PyQiFunctor {\n public:\n PyQiFunctor(const std::string &funName, qi::ObjectPtr obj)\n : _object(obj)\n , _funName(funName)\n {}\n\n boost::python::object operator()(boost::python::tuple pyargs, boost::python::dict pykwargs) {\n qi::GenericValue val = qi::GenericValue::from(pyargs);\n bool async = boost::python::extract<bool>(pykwargs.get(\"_async\", false));\n std::string funN = boost::python::extract<std::string>(pykwargs.get(\"_overload\", _funName));\n qiLogDebug() << \"calling a method: \" << funN << \" args:\" << qi::encodeJSON(val);\n\n qi::Future<qi::GenericValuePtr> fut;\n {\n \/\/calling c++, so release the GIL.\n GILScopedUnlock _unlock;\n fut = _object->metaCall(funN, val.asDynamic().asTupleValuePtr());\n }\n if (!async)\n return fut.value().to<boost::python::object>();\n else\n return qi::py::makeFuture(fut);\n }\n\n public:\n qi::ObjectPtr _object;\n std::string _funName;\n };\n\n\n void populateMethods(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::MethodMap mm = obj->metaObject().methodMap();\n qi::MetaObject::MethodMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaMethod &mem = it->second;\n \/\/drop special methods\n if (mem.uid() < qiObjectSpecialMethodMaxUid)\n continue;\n qiLogDebug() << \"adding method:\" << mem.toString();\n boost::python::object fun = boost::python::raw_function(PyQiFunctor(mem.name().c_str(), obj));\n boost::python::api::setattr(pyobj, mem.name().c_str(), fun);\n \/\/ Fill __doc__ with Signature and description\n std::stringstream ssdocstring;\n ssdocstring << \"Signature: \" << mem.returnSignature().toString() << \"\\n\";\n ssdocstring << mem.description();\n boost::python::object docstring(ssdocstring.str());\n boost::python::api::setattr(fun, \"__doc__\", docstring);\n }\n }\n\n void populateSignals(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::SignalMap mm = obj->metaObject().signalMap();\n qi::MetaObject::SignalMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaSignal &ms = it->second;\n \/\/drop special methods\n if (ms.uid() < qiObjectSpecialMethodMaxUid)\n continue;\n qiLogDebug() << \"adding signal:\" << ms.toString();\n boost::python::object fun = qi::py::makePyProxySignal(obj, ms);\n boost::python::api::setattr(pyobj, ms.name(), fun);\n }\n }\n\n void populateProperties(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::PropertyMap mm = obj->metaObject().propertyMap();\n qi::MetaObject::PropertyMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaProperty &mp = it->second;\n \/\/drop special methods\n if (mp.uid() < qiObjectSpecialMethodMaxUid)\n continue;\n qiLogDebug() << \"adding property:\" << mp.toString();\n boost::python::object fun = qi::py::makePyProxyProperty(obj, mp);\n boost::python::api::setattr(pyobj, mp.name().c_str(), fun);\n }\n }\n\n\n class PyQiObject {\n public:\n PyQiObject()\n {}\n\n PyQiObject(const qi::ObjectPtr &obj)\n : _object(obj)\n {}\n\n boost::python::object call(boost::python::str pyname, boost::python::tuple pyargs, boost::python::dict pykws) {\n return PyQiFunctor(boost::python::extract<std::string>(pyname), _object)(pyargs, pykws);\n }\n\n boost::python::object metaObject() {\n return qi::GenericValueRef(_object->metaObject()).to<boost::python::object>();\n }\n\n qi::ObjectPtr object() {\n return _object;\n }\n\n private:\n qi::ObjectPtr _object;\n };\n\n boost::python::object makePyQiObject(qi::ObjectPtr obj, const std::string &name) {\n boost::python::object result = boost::python::object(qi::py::PyQiObject(obj));\n qi::py::populateMethods(result, obj);\n qi::py::populateSignals(result, obj);\n qi::py::populateProperties(result, obj);\n return result;\n }\n\n\n \/\/TODO: DO NOT DUPLICATE\n static qi::GenericValuePtr pyCallMethod(const std::vector<qi::GenericValuePtr>& cargs, boost::python::object callable) {\n qi::py::GILScopedLock _lock;\n boost::python::list args;\n boost::python::object ret;\n\n std::vector<qi::GenericValuePtr>::const_iterator it = cargs.begin();\n ++it; \/\/drop the first arg which is DynamicObject*\n for (; it != cargs.end(); ++it) {\n qiLogDebug() << \"argument: \" << qi::encodeJSON(*it);\n args.append(it->to<boost::python::object>());\n }\n qiLogDebug() << \"before method call\";\n try {\n ret = callable(*boost::python::tuple(args));\n } catch (const boost::python::error_already_set &e) {\n std::string err = PyFormatError();\n qiLogDebug() << \"call exception:\" << err;\n throw std::runtime_error(err);\n }\n\n qi::GenericValuePtr gvret = qi::GenericValueRef(ret).clone();\n qiLogDebug() << \"method returned:\" << qi::encodeJSON(gvret);\n return gvret;\n }\n\n \/\/callback just needed to keep a ref on obj\n static void doNothing(qi::GenericObject *go, boost::python::object obj)\n {\n (void)go;\n (void)obj;\n }\n\n qi::ObjectPtr makeQiObjectPtr(boost::python::object obj)\n {\n \/\/is that a qi::ObjectPtr?\n boost::python::extract<PyQiObject*> isthatyoumum(obj);\n\n if (isthatyoumum.check()) {\n qiLogDebug() << \"this PyObject is already a qi::ObjectPtr. Just returning it.\";\n return isthatyoumum()->object();\n }\n\n qi::GenericObjectBuilder gob;\n GILScopedLock _lock;\n boost::python::object attrs(boost::python::borrowed(PyObject_Dir(obj.ptr())));\n\n for (int i = 0; i < boost::python::len(attrs); ++i) {\n std::string key = boost::python::extract<std::string>(attrs[i]);\n boost::python::object m = obj.attr(attrs[i]);\n if (PyMethod_Check(m.ptr())) {\n qi::MetaMethodBuilder mmb;\n mmb.setName(key);\n boost::python::object desc = m.attr(\"__doc__\");\n if (desc)\n mmb.setDescription(boost::python::extract<std::string>(desc));\n boost::python::object inspect = import_inspect();\n \/\/returns: (args, varargs, keywords, defaults)\n boost::python::object tu = inspect.attr(\"getargspec\")(m);\n int argsz = boost::python::len(tu[0]);\n\n argsz = argsz > 0 ? argsz - 1 : 0;\n\n if (argsz < 0) {\n qiLogError() << \"Method \" << key << \" is missing the self argument.\";\n continue;\n }\n std::stringstream ss;\n ss << \"(\";\n for (int i = 0; i < argsz; ++i)\n ss << \"m\";\n ss << \")\";\n qiLogDebug() << \"Adding method: \" << ss.str();\n mmb.setName(key);\n mmb.setParametersSignature(ss.str());\n mmb.setReturnSignature(\"m\");\n gob.xAdvertiseMethod(mmb, qi::makeDynamicGenericFunction(boost::bind(pyCallMethod, _1, m)));\n continue;\n }\n\n \/\/store a pointer on PySignal class\n static boost::python::object asignal = qi::py::makePySignal(\"(i)\").attr(\"__class__\");\n if (PyObject_IsInstance(m.ptr(), asignal.ptr())) {\n qiLogDebug() << \"Adding signal:\" << key;\n gob.advertiseSignal(key, qi::py::getSignal(m));\n continue;\n }\n\n \/\/TODO: check for Property\n static boost::python::object aproperty = qi::py::makePyProperty(\"(i)\").attr(\"__class__\");\n if (PyObject_IsInstance(m.ptr(), aproperty.ptr())) {\n qiLogDebug() << \"Adding property:\" << key;\n gob.advertiseProperty(key, qi::py::getProperty(m));\n continue;\n }\n\n }\n \/\/this is a useless callback, needed to keep a ref on obj.\n \/\/when the GO is destructed, the ref is released.\n return gob.object(boost::bind<void>(&doNothing, _1, obj));\n }\n\n static boost::python::object pyobject_param_shrinker(boost::python::tuple args, boost::python::dict kwargs) {\n PyQiObject& pys = boost::python::extract<PyQiObject&>(args[0]);\n boost::python::list l;\n for (int i = 2; i < boost::python::len(args); ++i)\n l.append(args[i]);\n return pys.call(boost::python::extract<boost::python::str>(args[1]), boost::python::tuple(l), kwargs);\n }\n\n void export_pyobject() {\n boost::python::class_<qi::py::PyQiObject>(\"Object\", boost::python::no_init)\n .def(\"call\", boost::python::raw_function(&pyobject_param_shrinker, 1))\n \/\/TODO: .def(\"post\")\n \/\/TODO: .def(\"setProperty\")\n \/\/TODO: .def(\"property\")\n .def(\"metaObject\", &qi::py::PyQiObject::metaObject);\n \/\/import inspect in our current namespace\n import_inspect();\n }\n }\n}\n<commit_msg>rename occurences of qiObjectSpecialMethodMaxUid to qiObjectSpecialMemberMaxUid<commit_after>\/*\n**\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2013 Aldebaran Robotics\n*\/\n#include \"pyobject.hpp\"\n#include <boost\/python.hpp>\n#include <boost\/python\/raw_function.hpp>\n#include \"pyfuture.hpp\"\n#include \"pysignal.hpp\"\n#include \"pyproperty.hpp\"\n#include \"gil.hpp\"\n#include \"error.hpp\"\n#include <qitype\/genericobjectbuilder.hpp>\n\nqiLogCategory(\"qipy.object\");\n\nnamespace qi { namespace py {\n\n\n boost::python::object import_inspect() {\n static bool plouf = false;\n static boost::python::object obj;\n if (!plouf) {\n obj = boost::python::import(\"inspect\");\n plouf = true;\n }\n return obj;\n }\n\n struct PyQiFunctor {\n public:\n PyQiFunctor(const std::string &funName, qi::ObjectPtr obj)\n : _object(obj)\n , _funName(funName)\n {}\n\n boost::python::object operator()(boost::python::tuple pyargs, boost::python::dict pykwargs) {\n qi::GenericValue val = qi::GenericValue::from(pyargs);\n bool async = boost::python::extract<bool>(pykwargs.get(\"_async\", false));\n std::string funN = boost::python::extract<std::string>(pykwargs.get(\"_overload\", _funName));\n qiLogDebug() << \"calling a method: \" << funN << \" args:\" << qi::encodeJSON(val);\n\n qi::Future<qi::GenericValuePtr> fut;\n {\n \/\/calling c++, so release the GIL.\n GILScopedUnlock _unlock;\n fut = _object->metaCall(funN, val.asDynamic().asTupleValuePtr());\n }\n if (!async)\n return fut.value().to<boost::python::object>();\n else\n return qi::py::makeFuture(fut);\n }\n\n public:\n qi::ObjectPtr _object;\n std::string _funName;\n };\n\n\n void populateMethods(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::MethodMap mm = obj->metaObject().methodMap();\n qi::MetaObject::MethodMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaMethod &mem = it->second;\n \/\/drop special methods\n if (mem.uid() < qiObjectSpecialMemberMaxUid)\n continue;\n qiLogDebug() << \"adding method:\" << mem.toString();\n boost::python::object fun = boost::python::raw_function(PyQiFunctor(mem.name().c_str(), obj));\n boost::python::api::setattr(pyobj, mem.name().c_str(), fun);\n \/\/ Fill __doc__ with Signature and description\n std::stringstream ssdocstring;\n ssdocstring << \"Signature: \" << mem.returnSignature().toString() << \"\\n\";\n ssdocstring << mem.description();\n boost::python::object docstring(ssdocstring.str());\n boost::python::api::setattr(fun, \"__doc__\", docstring);\n }\n }\n\n void populateSignals(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::SignalMap mm = obj->metaObject().signalMap();\n qi::MetaObject::SignalMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaSignal &ms = it->second;\n \/\/drop special methods\n if (ms.uid() < qiObjectSpecialMemberMaxUid)\n continue;\n qiLogDebug() << \"adding signal:\" << ms.toString();\n boost::python::object fun = qi::py::makePyProxySignal(obj, ms);\n boost::python::api::setattr(pyobj, ms.name(), fun);\n }\n }\n\n void populateProperties(boost::python::object pyobj, qi::ObjectPtr obj) {\n qi::MetaObject::PropertyMap mm = obj->metaObject().propertyMap();\n qi::MetaObject::PropertyMap::iterator it;\n for (it = mm.begin(); it != mm.end(); ++it) {\n qi::MetaProperty &mp = it->second;\n \/\/drop special methods\n if (mp.uid() < qiObjectSpecialMemberMaxUid)\n continue;\n qiLogDebug() << \"adding property:\" << mp.toString();\n boost::python::object fun = qi::py::makePyProxyProperty(obj, mp);\n boost::python::api::setattr(pyobj, mp.name().c_str(), fun);\n }\n }\n\n\n class PyQiObject {\n public:\n PyQiObject()\n {}\n\n PyQiObject(const qi::ObjectPtr &obj)\n : _object(obj)\n {}\n\n boost::python::object call(boost::python::str pyname, boost::python::tuple pyargs, boost::python::dict pykws) {\n return PyQiFunctor(boost::python::extract<std::string>(pyname), _object)(pyargs, pykws);\n }\n\n boost::python::object metaObject() {\n return qi::GenericValueRef(_object->metaObject()).to<boost::python::object>();\n }\n\n qi::ObjectPtr object() {\n return _object;\n }\n\n private:\n qi::ObjectPtr _object;\n };\n\n boost::python::object makePyQiObject(qi::ObjectPtr obj, const std::string &name) {\n boost::python::object result = boost::python::object(qi::py::PyQiObject(obj));\n qi::py::populateMethods(result, obj);\n qi::py::populateSignals(result, obj);\n qi::py::populateProperties(result, obj);\n return result;\n }\n\n\n \/\/TODO: DO NOT DUPLICATE\n static qi::GenericValuePtr pyCallMethod(const std::vector<qi::GenericValuePtr>& cargs, boost::python::object callable) {\n qi::py::GILScopedLock _lock;\n boost::python::list args;\n boost::python::object ret;\n\n std::vector<qi::GenericValuePtr>::const_iterator it = cargs.begin();\n ++it; \/\/drop the first arg which is DynamicObject*\n for (; it != cargs.end(); ++it) {\n qiLogDebug() << \"argument: \" << qi::encodeJSON(*it);\n args.append(it->to<boost::python::object>());\n }\n qiLogDebug() << \"before method call\";\n try {\n ret = callable(*boost::python::tuple(args));\n } catch (const boost::python::error_already_set &e) {\n std::string err = PyFormatError();\n qiLogDebug() << \"call exception:\" << err;\n throw std::runtime_error(err);\n }\n\n qi::GenericValuePtr gvret = qi::GenericValueRef(ret).clone();\n qiLogDebug() << \"method returned:\" << qi::encodeJSON(gvret);\n return gvret;\n }\n\n \/\/callback just needed to keep a ref on obj\n static void doNothing(qi::GenericObject *go, boost::python::object obj)\n {\n (void)go;\n (void)obj;\n }\n\n qi::ObjectPtr makeQiObjectPtr(boost::python::object obj)\n {\n \/\/is that a qi::ObjectPtr?\n boost::python::extract<PyQiObject*> isthatyoumum(obj);\n\n if (isthatyoumum.check()) {\n qiLogDebug() << \"this PyObject is already a qi::ObjectPtr. Just returning it.\";\n return isthatyoumum()->object();\n }\n\n qi::GenericObjectBuilder gob;\n GILScopedLock _lock;\n boost::python::object attrs(boost::python::borrowed(PyObject_Dir(obj.ptr())));\n\n for (int i = 0; i < boost::python::len(attrs); ++i) {\n std::string key = boost::python::extract<std::string>(attrs[i]);\n boost::python::object m = obj.attr(attrs[i]);\n if (PyMethod_Check(m.ptr())) {\n qi::MetaMethodBuilder mmb;\n mmb.setName(key);\n boost::python::object desc = m.attr(\"__doc__\");\n if (desc)\n mmb.setDescription(boost::python::extract<std::string>(desc));\n boost::python::object inspect = import_inspect();\n \/\/returns: (args, varargs, keywords, defaults)\n boost::python::object tu = inspect.attr(\"getargspec\")(m);\n int argsz = boost::python::len(tu[0]);\n\n argsz = argsz > 0 ? argsz - 1 : 0;\n\n if (argsz < 0) {\n qiLogError() << \"Method \" << key << \" is missing the self argument.\";\n continue;\n }\n std::stringstream ss;\n ss << \"(\";\n for (int i = 0; i < argsz; ++i)\n ss << \"m\";\n ss << \")\";\n qiLogDebug() << \"Adding method: \" << ss.str();\n mmb.setName(key);\n mmb.setParametersSignature(ss.str());\n mmb.setReturnSignature(\"m\");\n gob.xAdvertiseMethod(mmb, qi::makeDynamicGenericFunction(boost::bind(pyCallMethod, _1, m)));\n continue;\n }\n\n \/\/store a pointer on PySignal class\n static boost::python::object asignal = qi::py::makePySignal(\"(i)\").attr(\"__class__\");\n if (PyObject_IsInstance(m.ptr(), asignal.ptr())) {\n qiLogDebug() << \"Adding signal:\" << key;\n gob.advertiseSignal(key, qi::py::getSignal(m));\n continue;\n }\n\n \/\/TODO: check for Property\n static boost::python::object aproperty = qi::py::makePyProperty(\"(i)\").attr(\"__class__\");\n if (PyObject_IsInstance(m.ptr(), aproperty.ptr())) {\n qiLogDebug() << \"Adding property:\" << key;\n gob.advertiseProperty(key, qi::py::getProperty(m));\n continue;\n }\n\n }\n \/\/this is a useless callback, needed to keep a ref on obj.\n \/\/when the GO is destructed, the ref is released.\n return gob.object(boost::bind<void>(&doNothing, _1, obj));\n }\n\n static boost::python::object pyobject_param_shrinker(boost::python::tuple args, boost::python::dict kwargs) {\n PyQiObject& pys = boost::python::extract<PyQiObject&>(args[0]);\n boost::python::list l;\n for (int i = 2; i < boost::python::len(args); ++i)\n l.append(args[i]);\n return pys.call(boost::python::extract<boost::python::str>(args[1]), boost::python::tuple(l), kwargs);\n }\n\n void export_pyobject() {\n boost::python::class_<qi::py::PyQiObject>(\"Object\", boost::python::no_init)\n .def(\"call\", boost::python::raw_function(&pyobject_param_shrinker, 1))\n \/\/TODO: .def(\"post\")\n \/\/TODO: .def(\"setProperty\")\n \/\/TODO: .def(\"property\")\n .def(\"metaObject\", &qi::py::PyQiObject::metaObject);\n \/\/import inspect in our current namespace\n import_inspect();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n#define ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n\n#include \"..\/call-script.h\"\n#include \"..\/change-working-dir.h\"\n\n#include <QFileInfo>\n\nnamespace AngelScriptIntegration {\nnamespace Implementation {\n\nclass ScriptContextReleaser\n{\n AngelScript::asIScriptContext* const context;\npublic:\n\n ScriptContextReleaser(AngelScript::asIScriptContext* context)\n : context(context)\n {\n }\n\n ~ScriptContextReleaser()\n {\n context->Release();\n }\n};\n\ninline void _pass_arguments_to_angelscript(AngelScript::asIScriptContext*, int)\n{\n}\n\ntemplate<typename T_arg_i, typename... T_args>\nvoid _pass_arguments_to_angelscript(AngelScript::asIScriptContext* context, int i, const T_arg_i& arg_i, const T_args&... other_args)\n{\n pass_arg_to_angelscript(context, i, arg_i);\n\n _pass_arguments_to_angelscript(context, i+1, other_args...);\n}\n\n} \/\/ namespace Implementation\n\nvoid CheckExecutionResult(AngelScript::asIScriptContext* context, int r);\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScriptFunction(AngelScript::asIScriptFunction* function, const T_args&... args)\n{\n Q_ASSERT(function != nullptr);\n AngelScript::asIScriptEngine* engine = function->GetEngine();\n\n AngelScript::asIScriptContext* context = engine->CreateContext();\n\n \/\/ Using the destructor to release the context to allow returning the return value directly\n Implementation::ScriptContextReleaser scriptContextReleaser(context);\n Q_UNUSED(scriptContextReleaser);\n\n Implementation::_pass_arguments_to_angelscript(context, 0, args...);\n\n context->Prepare(function);\n\n int r = context->Execute();\n\n CheckExecutionResult(context, r);\n\n return ResultFromAngelScript<T_return>::value(context);\n}\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScriptExt(AngelScript::asIScriptEngine* engine,\n const std::string& filepath,\n const char* functionDeclarationToCall,\n const char* preferredModuleName,\n const ConfigCallScript& config,\n const T_args&... args)\n{\n QFileInfo file(QString::fromStdString(filepath));\n\n std::string absoluteFilepath = file.absoluteFilePath().toStdString();\n\n ChangeWorkingDir cd(file.dir());\n\n std::string moduleName = getUniqueModuleName(engine, preferredModuleName);\n AngelScript::asIScriptModule* module = loadAndCompileModule(engine, absoluteFilepath.c_str(), moduleName.c_str(), config.accessMask);\n\n AngelScript::asIScriptFunction* function = module->GetFunctionByDecl(functionDeclarationToCall);\n\n Q_ASSERT(function != nullptr);\n Q_UNUSED(cd);\n\n return callScriptFunction<T_return>(function, args...);\n}\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScript(AngelScript::asIScriptEngine* engine,\n const std::string& filepath,\n const char* functionDeclarationToCall,\n const char* preferredModuleName,\n const T_args&... args)\n{\n return callScript(engine, filepath, functionDeclarationToCall, preferredModuleName, ConfigCallScript(), args...);\n}\n\n\n\n} \/\/ namespace AngelScriptIntegration\n\n#endif \/\/ ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n\n<commit_msg>major bugfix<commit_after>#ifndef ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n#define ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n\n#include \"..\/call-script.h\"\n#include \"..\/change-working-dir.h\"\n\n#include <QFileInfo>\n\nnamespace AngelScriptIntegration {\nnamespace Implementation {\n\nclass ScriptContextReleaser\n{\n AngelScript::asIScriptContext* const context;\npublic:\n\n ScriptContextReleaser(AngelScript::asIScriptContext* context)\n : context(context)\n {\n }\n\n ~ScriptContextReleaser()\n {\n context->Release();\n }\n};\n\ninline void _pass_arguments_to_angelscript(AngelScript::asIScriptContext*, int)\n{\n}\n\ntemplate<typename T_arg_i, typename... T_args>\nvoid _pass_arguments_to_angelscript(AngelScript::asIScriptContext* context, int i, const T_arg_i& arg_i, const T_args&... other_args)\n{\n pass_arg_to_angelscript(context, i, arg_i);\n\n _pass_arguments_to_angelscript(context, i+1, other_args...);\n}\n\n} \/\/ namespace Implementation\n\nvoid CheckExecutionResult(AngelScript::asIScriptContext* context, int r);\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScriptFunction(AngelScript::asIScriptFunction* function, const T_args&... args)\n{\n Q_ASSERT(function != nullptr);\n AngelScript::asIScriptEngine* engine = function->GetEngine();\n\n AngelScript::asIScriptContext* context = engine->CreateContext();\n\n \/\/ Using the destructor to release the context to allow returning the return value directly\n Implementation::ScriptContextReleaser scriptContextReleaser(context);\n Q_UNUSED(scriptContextReleaser);\n\n context->Prepare(function);\n\n Implementation::_pass_arguments_to_angelscript(context, 0, args...);\n\n int r = context->Execute();\n\n CheckExecutionResult(context, r);\n\n return ResultFromAngelScript<T_return>::value(context);\n}\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScriptExt(AngelScript::asIScriptEngine* engine,\n const std::string& filepath,\n const char* functionDeclarationToCall,\n const char* preferredModuleName,\n const ConfigCallScript& config,\n const T_args&... args)\n{\n QFileInfo file(QString::fromStdString(filepath));\n\n std::string absoluteFilepath = file.absoluteFilePath().toStdString();\n\n ChangeWorkingDir cd(file.dir());\n\n std::string moduleName = getUniqueModuleName(engine, preferredModuleName);\n AngelScript::asIScriptModule* module = loadAndCompileModule(engine, absoluteFilepath.c_str(), moduleName.c_str(), config.accessMask);\n\n AngelScript::asIScriptFunction* function = module->GetFunctionByDecl(functionDeclarationToCall);\n\n Q_ASSERT(function != nullptr);\n Q_UNUSED(cd);\n\n return callScriptFunction<T_return>(function, args...);\n}\n\n\ntemplate<typename T_return, typename... T_args>\nT_return callScript(AngelScript::asIScriptEngine* engine,\n const std::string& filepath,\n const char* functionDeclarationToCall,\n const char* preferredModuleName,\n const T_args&... args)\n{\n return callScript(engine, filepath, functionDeclarationToCall, preferredModuleName, ConfigCallScript(), args...);\n}\n\n\n\n} \/\/ namespace AngelScriptIntegration\n\n#endif \/\/ ANGELSCRIPTINTEGRATION_CALLSCRIPT_INL\n\n<|endoftext|>"} {"text":"<commit_before>#include <QPrintDialog>\n#include <QPainter>\n#include <QDebug>\n#include <QPrintPreviewWidget>\n#include <QPrintPreviewDialog>\n#include \"converters\/convertertopdf.hpp\"\n#include \"converters\/convertertohtml.hpp\"\n#include \"engine.hpp\"\n\nnamespace qtreports\n{\n\n Engine::Engine( QObject * parent ) :\n QObject( parent ),\n m_isOpened( false ),\n m_connectionIsSet( false ),\n m_dataSourceIsSet( false )\n {}\n\n Engine::Engine( const QString & path, QObject * parent ) :\n Engine( parent )\n {\n open( path );\n }\n\n Engine::~Engine() {}\n\n bool\tEngine::open( const QString & path )\n {\n if( isOpened() )\n {\n close();\n }\n\n detail::Parser parser;\n if( !parser.parse( path ) )\n {\n m_lastError = \"Parsing error: \" + parser.getLastError();\n return false;\n }\n\n m_isOpened = true;\n m_compiledPath = path;\n m_report = parser.getReport();\n\n fillColumnsFromReport(); \/\/MB as ProcessedDB::createColumns( ReportPtr )\n\n return true;\n }\n\n bool Engine::close()\n {\n m_isOpened = false;\n m_compiledPath.clear();\n m_report.clear();\n\n return true;\n }\n\n bool\tEngine::setParameters( const QMap< QString, QString > & map )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n auto detail = m_report->getDetail();\n if( detail.isNull() )\n {\n m_lastError = \"Report->Detail is empty. Please open report file\";\n return false;\n }\n\n for( auto && band : detail->getBands() )\n {\n for( auto && textField : band->getTextFields() )\n {\n auto text = textField->getText();\n text = text.replace( \"\\n\", \"\" ).replace( \"\\r\", \"\" ).replace( \" \", \"\" );\n if( text.startsWith( \"$P{\" ) && text.contains( \"}\" ) )\n {\n auto name = text.split( \"{\" ).at( 1 ).split( \"}\" ).at( 0 );\n textField->setText( map[ name ] );\n }\n }\n }\n\n return true;\n }\n\n bool\tEngine::setConnection( const QSqlDatabase & connection )\n {\n if( !connection.isOpen() )\n {\n m_lastError = \"Connection not open\";\n return false;\n }\n\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n m_dbConnection = connection;\n m_connectionIsSet = true;\n\n if( !prepareDB() )\n {\n m_lastError = \"Error in prepareDB: \" + m_lastError;\n return false;\n }\n\n m_report->setRowCount( m_processedDB.getMaxRowCount() );\n\n for( auto && field : m_report->getFields() )\n {\n QVector < QVariant > tmp_vec;\n if( m_processedDB.getColumn( field->getName(), tmp_vec ) )\n {\n m_report->setFieldData( field->getName(), tmp_vec );\n }\n }\n\n return true;\n }\n\n bool Engine::setDataSource( const QMap< QString, QVector< QVariant > > & source )\n {\n \/\/Need check parameters\n \/\/m_dataSource = columnsSet;\n m_dataSourceIsSet = true;\n\n prepareDataSource( source );\n\n return true;\n }\n\n bool Engine::setQuery( const QString & query )\n {\n \/\/Need check parameters\n auto queries = query.split( \";\", QString::SkipEmptyParts );\n executeQueries( queries );\n\n m_lastError = query;\n return true;\n }\n\n bool Engine::addScript( const QString & script )\n {\n \/\/Need check parameters\n m_scripts.append( script );\n\n return true;\n }\n\n bool Engine::setDataModel( const QAbstractItemModel & model )\n {\n \/\/Need check parameters\n Q_UNUSED( model )\n return true;\n }\n\n bool\tEngine::createPDF( const QString & path )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n detail::ConverterToPDF converter( m_report );\n auto result = converter.convert( path );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return false;\n }\n\n return true;\n }\n\n bool\tEngine::createHTML( const QString & path )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n detail::ConverterToHTML converter( m_report );\n auto result = converter.convert( path );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return false;\n }\n\n return true;\n }\n\n const QWidgetPtr\tEngine::createWidget()\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return QWidgetPtr();\n }\n\n detail::ConverterToQWidget converter( m_report );\n auto result = converter.convert( detail::ConverterToQWidget::WidgetType::Report );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return QWidgetPtr();\n }\n\n return converter.getQWidget();\n }\n\n const QWidgetPtr\tEngine::createLayout()\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return QWidgetPtr();\n }\n\n detail::ConverterToQWidget converter( m_report );\n auto result = converter.convert( detail::ConverterToQWidget::WidgetType::Layout );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return QWidgetPtr();\n }\n\n return converter.getQWidget();\n }\n\n bool\tEngine::print()\n {\n QPrinter printer;\n\n m_printedWidget = createWidget();\n if( m_printedWidget.isNull() )\n {\n m_lastError = \"Cannot create widget. Error: \" + m_lastError;\n return false;\n }\n\n m_printedWidget->resize( 595, 595 );\n\n \/\/Magic\n m_printedWidget->show();\n m_printedWidget->hide();\n\n QPrintPreviewDialog preview( &printer );\n connect(\n &preview, &QPrintPreviewDialog::paintRequested,\n this, &Engine::drawPreview\n );\n preview.exec();\n\n m_printedWidget.clear();\n\n return true;\n }\n\n void\tEngine::drawPreview( QPrinter * printer )\n {\n if( m_printedWidget.isNull() )\n {\n return;\n }\n\n QRectF rect = printer->pageRect();\n QPainter painter( printer );\n qreal scale = rect.width() \/ m_printedWidget->width();\n\n m_printedWidget->resize( m_printedWidget->width(), rect.height() \/ scale );\n painter.scale( scale, scale );\n\n auto height = m_printedWidget->height() * scale;\n auto count = static_cast< int >( std::ceil( height \/ rect.height() ) );\n for( int i = 0; i < count; ++i )\n {\n i != 0 ? printer->newPage() : 0;\n m_printedWidget->render( &painter, QPoint( 0, -i * rect.height() \/ scale ) );\n }\n }\n\n bool Engine::prepareDB() {\n return setQuery( m_report->getQuery() );\n }\n\n void Engine::prepareDataSource( const QMap< QString, QVector< QVariant > > & source )\n {\n QMapIterator <QString, QVector <QVariant> > iterator( source );\n while( iterator.hasNext() )\n {\n iterator.next();\n \/\/m_processedDB.addFieldData( iterator.key(), iterator.value() );\n auto field = m_report->getField( iterator.key() );\n if( field.isNull() )\n {\n continue;\n }\n\n field->setData( iterator.value() );\n }\n }\n\n void Engine::fillColumnsFromReport()\n {\n QMap <QString, detail::FieldPtr> fieldMap = m_report->getFields();\n QMapIterator <QString, detail::FieldPtr> fieldIterator( fieldMap );\n while( fieldIterator.hasNext() )\n {\n fieldIterator.next();\n m_processedDB.addColumn( fieldIterator.key() );\n }\n\n \/*for( auto && field : m_report->getFields() )\n {\n m_processedDB.addColumn( field->getName() );\n }*\/\n }\n\n void Engine::executeQueries( const QStringList & queries )\n {\n \/*\n QStringListIterator iterator(m_queriesList);\n while(iterator.hasNext()) {\n QString query = iterator.next();\n QSqlQueryModel * model = new QSqlQueryModel();\n *\/\n for( auto && query : queries )\n {\n auto model = new QSqlQueryModel();\n model->setQuery( query, m_dbConnection );\n for( int row = 0; row < model->rowCount(); row++ )\n {\n QSqlRecord rec = model->record( row );\n for( int col = 0; col < rec.count(); col++ )\n {\n m_processedDB.addFieldData( rec.fieldName( col ), rec.field( col ).value() );\n }\n }\n }\n }\n\n bool Engine::isOpened() const\n {\n return m_isOpened;\n }\n\n const QString Engine::getLastError() const\n {\n return m_lastError;\n }\n\n}\n<commit_msg>Update engine.cpp<commit_after>#include <QPrintDialog>\n#include <QPainter>\n#include <QDebug>\n#include <QPrintPreviewWidget>\n#include <QPrintPreviewDialog>\n#include \"converters\/convertertopdf.hpp\"\n#include \"converters\/convertertohtml.hpp\"\n#include \"engine.hpp\"\n\nnamespace qtreports\n{\n\n Engine::Engine( QObject * parent ) :\n QObject( parent ),\n m_isOpened( false ),\n m_connectionIsSet( false ),\n m_dataSourceIsSet( false )\n {}\n\n Engine::Engine( const QString & path, QObject * parent ) :\n Engine( parent )\n {\n open( path );\n }\n\n Engine::~Engine() {}\n\n bool\tEngine::open( const QString & path )\n {\n if( isOpened() )\n {\n close();\n }\n\n detail::Parser parser;\n if( !parser.parse( path ) )\n {\n m_lastError = \"Parsing error: \" + parser.getLastError();\n return false;\n }\n\n m_isOpened = true;\n m_compiledPath = path;\n m_report = parser.getReport();\n\n fillColumnsFromReport(); \/\/MB as ProcessedDB::createColumns( ReportPtr )\n\n return true;\n }\n\n bool Engine::close()\n {\n m_isOpened = false;\n m_compiledPath.clear();\n m_report.clear();\n\n return true;\n }\n\n bool\tEngine::setParameters( const QMap< QString, QString > & map )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n auto detail = m_report->getDetail();\n if( detail.isNull() )\n {\n m_lastError = \"Report->Detail is empty. Please open report file\";\n return false;\n }\n\n for( auto && band : detail->getBands() )\n {\n for( auto && textField : band->getTextFields() )\n {\n auto text = textField->getText();\n text = text.replace( \"\\n\", \"\" ).replace( \"\\r\", \"\" ).replace( \" \", \"\" );\n if( text.startsWith( \"$P{\" ) && text.contains( \"}\" ) )\n {\n auto name = text.split( \"{\" ).at( 1 ).split( \"}\" ).at( 0 );\n textField->setText( map[ name ] );\n }\n }\n }\n\n return true;\n }\n\n bool\tEngine::setConnection( const QSqlDatabase & connection )\n {\n if( !connection.isOpen() )\n {\n m_lastError = \"Connection not open\";\n return false;\n }\n\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n m_dbConnection = connection;\n m_connectionIsSet = true;\n\n if( !prepareDB() )\n {\n m_lastError = \"Error in prepareDB: \" + m_lastError;\n return false;\n }\n\n m_report->setRowCount( m_processedDB.getMaxRowCount() );\n\n for( auto && field : m_report->getFields() )\n {\n QVector < QVariant > tmp_vec;\n if( m_processedDB.getColumn( field->getName(), tmp_vec ) )\n {\n m_report->setFieldData( field->getName(), tmp_vec );\n }\n }\n\n return true;\n }\n\n bool Engine::setDataSource( const QMap< QString, QVector< QVariant > > & source )\n {\n \/\/Need check parameters\n \/\/m_dataSource = columnsSet;\n m_dataSourceIsSet = true;\n\n prepareDataSource( source );\n \n m_report->setRowCount( m_processedDB.getMaxRowCount() );\n\n for( auto && field : m_report->getFields() )\n {\n QVector < QVariant > tmp_vec;\n if( m_processedDB.getColumn( field->getName(), tmp_vec ) )\n {\n m_report->setFieldData( field->getName(), tmp_vec );\n }\n }\n\n return true;\n }\n\n bool Engine::setQuery( const QString & query )\n {\n \/\/Need check parameters\n auto queries = query.split( \";\", QString::SkipEmptyParts );\n executeQueries( queries );\n\n m_lastError = query;\n return true;\n }\n\n bool Engine::addScript( const QString & script )\n {\n \/\/Need check parameters\n m_scripts.append( script );\n\n return true;\n }\n\n bool Engine::setDataModel( const QAbstractItemModel & model )\n {\n \/\/Need check parameters\n Q_UNUSED( model )\n return true;\n }\n\n bool\tEngine::createPDF( const QString & path )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n detail::ConverterToPDF converter( m_report );\n auto result = converter.convert( path );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return false;\n }\n\n return true;\n }\n\n bool\tEngine::createHTML( const QString & path )\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return false;\n }\n\n detail::ConverterToHTML converter( m_report );\n auto result = converter.convert( path );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return false;\n }\n\n return true;\n }\n\n const QWidgetPtr\tEngine::createWidget()\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return QWidgetPtr();\n }\n\n detail::ConverterToQWidget converter( m_report );\n auto result = converter.convert( detail::ConverterToQWidget::WidgetType::Report );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return QWidgetPtr();\n }\n\n return converter.getQWidget();\n }\n\n const QWidgetPtr\tEngine::createLayout()\n {\n if( m_report.isNull() )\n {\n m_lastError = \"Report is empty. Please open report file\";\n return QWidgetPtr();\n }\n\n detail::ConverterToQWidget converter( m_report );\n auto result = converter.convert( detail::ConverterToQWidget::WidgetType::Layout );\n if( !result )\n {\n m_lastError = converter.getLastError();\n return QWidgetPtr();\n }\n\n return converter.getQWidget();\n }\n\n bool\tEngine::print()\n {\n QPrinter printer;\n\n m_printedWidget = createWidget();\n if( m_printedWidget.isNull() )\n {\n m_lastError = \"Cannot create widget. Error: \" + m_lastError;\n return false;\n }\n\n m_printedWidget->resize( 595, 595 );\n\n \/\/Magic\n m_printedWidget->show();\n m_printedWidget->hide();\n\n QPrintPreviewDialog preview( &printer );\n connect(\n &preview, &QPrintPreviewDialog::paintRequested,\n this, &Engine::drawPreview\n );\n preview.exec();\n\n m_printedWidget.clear();\n\n return true;\n }\n\n void\tEngine::drawPreview( QPrinter * printer )\n {\n if( m_printedWidget.isNull() )\n {\n return;\n }\n\n QRectF rect = printer->pageRect();\n QPainter painter( printer );\n qreal scale = rect.width() \/ m_printedWidget->width();\n\n m_printedWidget->resize( m_printedWidget->width(), rect.height() \/ scale );\n painter.scale( scale, scale );\n\n auto height = m_printedWidget->height() * scale;\n auto count = static_cast< int >( std::ceil( height \/ rect.height() ) );\n for( int i = 0; i < count; ++i )\n {\n i != 0 ? printer->newPage() : 0;\n m_printedWidget->render( &painter, QPoint( 0, -i * rect.height() \/ scale ) );\n }\n }\n\n bool Engine::prepareDB() {\n return setQuery( m_report->getQuery() );\n }\n\n void Engine::prepareDataSource( const QMap< QString, QVector< QVariant > > & source )\n {\n QMapIterator <QString, QVector <QVariant> > iterator( source );\n while( iterator.hasNext() )\n {\n iterator.next();\n \/\/m_processedDB.addFieldData( iterator.key(), iterator.value() );\n auto field = m_report->getField( iterator.key() );\n if( field.isNull() )\n {\n continue;\n }\n\n field->setData( iterator.value() );\n }\n }\n\n void Engine::fillColumnsFromReport()\n {\n QMap <QString, detail::FieldPtr> fieldMap = m_report->getFields();\n QMapIterator <QString, detail::FieldPtr> fieldIterator( fieldMap );\n while( fieldIterator.hasNext() )\n {\n fieldIterator.next();\n m_processedDB.addColumn( fieldIterator.key() );\n }\n\n \/*for( auto && field : m_report->getFields() )\n {\n m_processedDB.addColumn( field->getName() );\n }*\/\n }\n\n void Engine::executeQueries( const QStringList & queries )\n {\n \/*\n QStringListIterator iterator(m_queriesList);\n while(iterator.hasNext()) {\n QString query = iterator.next();\n QSqlQueryModel * model = new QSqlQueryModel();\n *\/\n for( auto && query : queries )\n {\n auto model = new QSqlQueryModel();\n model->setQuery( query, m_dbConnection );\n for( int row = 0; row < model->rowCount(); row++ )\n {\n QSqlRecord rec = model->record( row );\n for( int col = 0; col < rec.count(); col++ )\n {\n m_processedDB.addFieldData( rec.fieldName( col ), rec.field( col ).value() );\n }\n }\n }\n }\n\n bool Engine::isOpened() const\n {\n return m_isOpened;\n }\n\n const QString Engine::getLastError() const\n {\n return m_lastError;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ir\/index_manager\/index\/SkipListReader.h>\r\n#include <ir\/index_manager\/utility\/system.h>\r\n\r\n\/\/#define SKIP_DEBUG\r\n\r\nNS_IZENELIB_IR_BEGIN\r\n\r\nnamespace indexmanager{\r\n\r\nSkipListReader::SkipListReader(IndexInput* pSkipInput, int skipInterval, int numSkipLevels)\r\n : loaded_(false)\r\n , defaultSkipInterval_(skipInterval)\r\n , numSkipLevels_(numSkipLevels)\r\n , numSkipped_(0)\r\n , totalSkipped_(0)\r\n , lastDoc_(0)\r\n , lastSkipInterval_(0)\r\n , lastChildPointer_(0)\r\n{\r\n init();\r\n skipStream_[0] = pSkipInput->clone();\r\n}\t\t\r\n\r\nSkipListReader::SkipListReader(VariantDataPool** pSkipLevels, int skipInterval, int numSkipLevels)\r\n\t: loaded_(false)\r\n\t, defaultSkipInterval_(skipInterval)\r\n\t, numSkipLevels_(numSkipLevels)\r\n\t, numSkipped_(0)\r\n\t, totalSkipped_(0)\r\n\t, lastDoc_(0)\r\n\t, lastSkipInterval_(0)\r\n\t, lastChildPointer_(0)\r\n{\r\n init();\r\n for(int i = 0;i < numSkipLevels_;i++)\r\n\tskipStream_[i] = new VariantDataPoolInput(pSkipLevels[i]);\r\n}\r\n\r\nSkipListReader::~SkipListReader()\r\n{\r\n std::vector<IndexInput*>::iterator iter =skipStream_.begin();\r\n for( ; iter != skipStream_.end(); ++iter)\r\n if(*iter)\r\n delete *iter;\r\n}\r\n\r\ndocid_t SkipListReader::skipTo(docid_t target)\r\n{\r\n if (!loaded_) \r\n {\r\n loadSkipLevels();\r\n loaded_ = true;\r\n }\r\n \/\/\/ walk up the levels until highest level is found that has a skip for this target\r\n int level = 0;\r\n while (level < (numSkipLevels_-1) && target > skipDoc_[level + 1]) \r\n {\r\n level++;\r\n }\r\n\r\n while (level >= 0) \r\n {\r\n if (target > skipDoc_[level]) \r\n {\r\n#ifdef SKIP_DEBUG\r\n cout<<\"in level \"<<level<<\":\";\r\n#endif\r\n if (!loadNextSkip(level)) \r\n continue;\r\n }\r\n else \r\n {\r\n \/\/\/ no more skips on this level, go down one level\r\n if (level > 0 && lastChildPointer_ > skipStream_[level - 1]->getFilePointer()) \r\n {\r\n seekChild(level - 1);\r\n } \r\n level--;\r\n }\r\n }\r\n#ifdef SKIP_DEBUG\r\n cout<<\"skipto result: doc \"<<lastDoc_<<\" totalskipped \"<<totalSkipped_<<endl;\t\r\n#endif\r\n return lastDoc_;\r\n}\r\n\r\nbool SkipListReader::nextSkip(docid_t docID)\r\n{\r\n if (!loaded_) \r\n {\r\n loadSkipLevels();\r\n loaded_ = true;\r\n }\r\n if(skipDoc_[0] == 0)\r\n {\r\n if(!loadNextSkip(0))\r\n return false;\r\n }\r\n if(skipDoc_[0] <= docID)\r\n {\r\n loadNextSkip(0);\r\n return true;\r\n }\r\n return false;\r\n}\r\n\r\nvoid SkipListReader::seekChild(int level)\r\n{\r\n skipStream_[level]->seek(lastChildPointer_);\r\n skipDoc_[level] = lastDoc_;\r\n offsets_[level] = lastOffset_;\r\n pOffsets_[level] = lastPOffset_;\r\n numSkipped_[level] = totalSkipped_;\r\n if (level > 0)\r\n {\r\n childPointer_[level] = skipStream_[level]->readVLong() + skipPointer_[level - 1];\r\n }\r\n}\r\n\r\nbool SkipListReader::loadNextSkip(int level)\r\n{\r\n lastDoc_ = skipDoc_[level];\r\n lastSkipInterval_ = skipInterval_[level];\r\n lastChildPointer_ = childPointer_[level];\r\n lastOffset_ = offsets_[level];\r\n lastPOffset_ = pOffsets_[level];\r\n totalSkipped_ = numSkipped_[level];\r\n#ifdef SKIP_DEBUG\r\n cout<<\"lastdoc \"<<lastDoc_<<\" totalskipped \"<<totalSkipped_<<\",\";\r\n#endif\r\n if (skipStream_[level]->isEof()) \r\n {\r\n \/\/\/ this skip list is exhausted\r\n skipDoc_[level] = BAD_DOCID;\r\n return false;\r\n }\r\n\r\n \/\/\/ read next skip entry\r\n readSkipPoint(level, skipStream_[level]);\r\n return true;\r\n}\r\n\r\nvoid SkipListReader::readSkipPoint(int level,IndexInput* pLevelInput)\r\n{\r\n docid_t nDocDelta = pLevelInput->readVInt();\r\n if( (nDocDelta & 1) == 1)\r\n skipInterval_[level] = pLevelInput->readVInt();\r\n else\r\n skipInterval_[level] = getLevelSkipInterval(level);\r\n\r\n skipDoc_[level] += (nDocDelta >> 1);\/\/pLevelInput->readVInt();\r\n offsets_[level] += pLevelInput->readVLong();\r\n pOffsets_[level] += pLevelInput->readVLong();\r\n numSkipped_[level] += skipInterval_[level];\r\n#ifdef SKIP_DEBUG\r\n cout<<\"doc \"<<skipDoc_[level]<<\" numSkipped_[level] \"<<numSkipped_[level]<<\",\";\r\n#endif\r\n if (level > 0) \r\n {\r\n \/\/\/ read the child pointer if we are not on the leaf level\r\n childPointer_[level] = pLevelInput->readVLong() + skipPointer_[level- 1];\r\n }\r\n}\r\n\r\nvoid SkipListReader::loadSkipLevels()\r\n{\r\n for (int i = numSkipLevels_-1; i >= 0; i--)\r\n {\r\n fileoffset_t length = skipStream_[0]->readVLong();\r\n skipPointer_[i] = skipStream_[0]->getFilePointer();\r\n if(i > 0)\r\n {\r\n skipStream_[i] = skipStream_[0]->clone();\r\n }\r\n skipStream_[i]->setlength(skipStream_[0]->getFilePointer() + length);\r\n if(i > 0)\r\n {\r\n skipStream_[0]->seek(skipStream_[0]->getFilePointer() + length);\r\n }\r\n }\r\n}\r\n\r\n}\r\nNS_IZENELIB_IR_END\r\n\r\n<commit_msg>in code review, fix potential bug in SkipListReader::skipTo(), it should load next skip point when the target equals to current point.<commit_after>#include <ir\/index_manager\/index\/SkipListReader.h>\r\n#include <ir\/index_manager\/utility\/system.h>\r\n\r\n\/\/#define SKIP_DEBUG\r\n\r\nNS_IZENELIB_IR_BEGIN\r\n\r\nnamespace indexmanager{\r\n\r\nSkipListReader::SkipListReader(IndexInput* pSkipInput, int skipInterval, int numSkipLevels)\r\n : loaded_(false)\r\n , defaultSkipInterval_(skipInterval)\r\n , numSkipLevels_(numSkipLevels)\r\n , numSkipped_(0)\r\n , totalSkipped_(0)\r\n , lastDoc_(0)\r\n , lastSkipInterval_(0)\r\n , lastChildPointer_(0)\r\n{\r\n init();\r\n skipStream_[0] = pSkipInput->clone();\r\n}\t\t\r\n\r\nSkipListReader::SkipListReader(VariantDataPool** pSkipLevels, int skipInterval, int numSkipLevels)\r\n\t: loaded_(false)\r\n\t, defaultSkipInterval_(skipInterval)\r\n\t, numSkipLevels_(numSkipLevels)\r\n\t, numSkipped_(0)\r\n\t, totalSkipped_(0)\r\n\t, lastDoc_(0)\r\n\t, lastSkipInterval_(0)\r\n\t, lastChildPointer_(0)\r\n{\r\n init();\r\n for(int i = 0;i < numSkipLevels_;i++)\r\n\tskipStream_[i] = new VariantDataPoolInput(pSkipLevels[i]);\r\n}\r\n\r\nSkipListReader::~SkipListReader()\r\n{\r\n std::vector<IndexInput*>::iterator iter =skipStream_.begin();\r\n for( ; iter != skipStream_.end(); ++iter)\r\n if(*iter)\r\n delete *iter;\r\n}\r\n\r\ndocid_t SkipListReader::skipTo(docid_t target)\r\n{\r\n if (!loaded_) \r\n {\r\n loadSkipLevels();\r\n loaded_ = true;\r\n }\r\n \/\/\/ walk up the levels until highest level is found that has a skip for this target\r\n int level = 0;\r\n while (level < (numSkipLevels_-1) && target > skipDoc_[level + 1]) \r\n {\r\n level++;\r\n }\r\n\r\n while (level >= 0) \r\n {\r\n if (target >= skipDoc_[level]) \r\n {\r\n#ifdef SKIP_DEBUG\r\n cout<<\"in level \"<<level<<\":\";\r\n#endif\r\n if (!loadNextSkip(level)) \r\n continue;\r\n }\r\n else \r\n {\r\n \/\/\/ no more skips on this level, go down one level\r\n if (level > 0 && lastChildPointer_ > skipStream_[level - 1]->getFilePointer()) \r\n {\r\n seekChild(level - 1);\r\n } \r\n level--;\r\n }\r\n }\r\n#ifdef SKIP_DEBUG\r\n cout<<\"skipto result: doc \"<<lastDoc_<<\" totalskipped \"<<totalSkipped_<<endl;\t\r\n#endif\r\n return lastDoc_;\r\n}\r\n\r\nbool SkipListReader::nextSkip(docid_t docID)\r\n{\r\n if (!loaded_) \r\n {\r\n loadSkipLevels();\r\n loaded_ = true;\r\n }\r\n if(skipDoc_[0] == 0)\r\n {\r\n if(!loadNextSkip(0))\r\n return false;\r\n }\r\n if(skipDoc_[0] <= docID)\r\n {\r\n loadNextSkip(0);\r\n return true;\r\n }\r\n return false;\r\n}\r\n\r\nvoid SkipListReader::seekChild(int level)\r\n{\r\n skipStream_[level]->seek(lastChildPointer_);\r\n skipDoc_[level] = lastDoc_;\r\n offsets_[level] = lastOffset_;\r\n pOffsets_[level] = lastPOffset_;\r\n numSkipped_[level] = totalSkipped_;\r\n if (level > 0)\r\n {\r\n childPointer_[level] = skipStream_[level]->readVLong() + skipPointer_[level - 1];\r\n }\r\n}\r\n\r\nbool SkipListReader::loadNextSkip(int level)\r\n{\r\n lastDoc_ = skipDoc_[level];\r\n lastSkipInterval_ = skipInterval_[level];\r\n lastChildPointer_ = childPointer_[level];\r\n lastOffset_ = offsets_[level];\r\n lastPOffset_ = pOffsets_[level];\r\n totalSkipped_ = numSkipped_[level];\r\n#ifdef SKIP_DEBUG\r\n cout<<\"lastdoc \"<<lastDoc_<<\" totalskipped \"<<totalSkipped_<<\",\";\r\n#endif\r\n if (skipStream_[level]->isEof()) \r\n {\r\n \/\/\/ this skip list is exhausted\r\n skipDoc_[level] = BAD_DOCID;\r\n return false;\r\n }\r\n\r\n \/\/\/ read next skip entry\r\n readSkipPoint(level, skipStream_[level]);\r\n return true;\r\n}\r\n\r\nvoid SkipListReader::readSkipPoint(int level,IndexInput* pLevelInput)\r\n{\r\n docid_t nDocDelta = pLevelInput->readVInt();\r\n if( (nDocDelta & 1) == 1)\r\n skipInterval_[level] = pLevelInput->readVInt();\r\n else\r\n skipInterval_[level] = getLevelSkipInterval(level);\r\n\r\n skipDoc_[level] += (nDocDelta >> 1);\/\/pLevelInput->readVInt();\r\n offsets_[level] += pLevelInput->readVLong();\r\n pOffsets_[level] += pLevelInput->readVLong();\r\n numSkipped_[level] += skipInterval_[level];\r\n#ifdef SKIP_DEBUG\r\n cout<<\"doc \"<<skipDoc_[level]<<\" numSkipped_[level] \"<<numSkipped_[level]<<\",\";\r\n#endif\r\n if (level > 0) \r\n {\r\n \/\/\/ read the child pointer if we are not on the leaf level\r\n childPointer_[level] = pLevelInput->readVLong() + skipPointer_[level- 1];\r\n }\r\n}\r\n\r\nvoid SkipListReader::loadSkipLevels()\r\n{\r\n for (int i = numSkipLevels_-1; i >= 0; i--)\r\n {\r\n fileoffset_t length = skipStream_[0]->readVLong();\r\n skipPointer_[i] = skipStream_[0]->getFilePointer();\r\n if(i > 0)\r\n {\r\n skipStream_[i] = skipStream_[0]->clone();\r\n }\r\n skipStream_[i]->setlength(skipStream_[0]->getFilePointer() + length);\r\n if(i > 0)\r\n {\r\n skipStream_[0]->seek(skipStream_[0]->getFilePointer() + length);\r\n }\r\n }\r\n}\r\n\r\n}\r\nNS_IZENELIB_IR_END\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"Game.h\"\n#include \"Renderer.h\"\n#include <algorithm>\n\nGame::Game(Field f, std::vector<Player *> p)\n{\n\tGameField = f;\n\tPlayers = p;\n\tCurrentFrame = 0;\n\tPacmanLives = 3;\n\tGameOver = 0;\n\tPaused = 0;\n\n\tfor (std::size_t i = 0; i < FIELD_WIDTH; i++)\n\t{\n\t\tfor (std::size_t j = 0; j < FIELD_HEIGHT; j++)\n\t\t{\n\t\t\tif ((f.Tiles[i][j] & Field::Pellet) == Field::Pellet)\n\t\t\t{\n\t\t\t\tAllPellets.Eat(i, j);\n\t\t\t}\n\t\t}\n\t}\n}\n\nGame::Game(const Game &other)\n{\n\tGameField = other.GameField;\n\tAllPellets = other.AllPellets;\n\tPellets = other.Pellets;\n\tCurrentFrame = other.CurrentFrame;\n\tPacmanLives = other.PacmanLives;\n\tGameOver = other.GameOver;\n\tPaused = other.Paused;\n\tPlayers = std::vector<Player *>();\n\tfor (std::size_t i = 0, size = other.Players.size(); i < size; i++)\n\t{\n\t\tPlayers.push_back(other.Players[i]->Clone());\n\t}\n}\n\nGame::~Game()\n{\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tdelete Players[i];\n\t}\n}\n\nGame& Game::operator=(const Game& rhs)\n{\n\tGameField = rhs.GameField;\n\tAllPellets = rhs.AllPellets;\n\tPellets = rhs.Pellets;\n\tCurrentFrame = rhs.CurrentFrame;\n\tPacmanLives = rhs.PacmanLives;\n\tGameOver = rhs.GameOver;\n\tPaused = rhs.Paused;\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tdelete Players[i];\n\t}\n\tPlayers = std::vector<Player *>();\n\tfor (std::size_t i = 0, size = rhs.Players.size(); i < size; i++)\n\t{\n\t\tPlayers.push_back(rhs.Players[i]->Clone());\n\t}\n\treturn *this;\n}\n\nbool Game::update()\n{\n\tif (Paused > 0)\n\t{\n\t\tPaused--;\n\t\tCurrentFrame++;\n\t\treturn true;\n\t}\n\n\tif (GameOver > 0)\n\t{\n\t\tGameOver--;\n\t\tCurrentFrame++;\n\t\tif (GameOver == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\telse if (GameOver < 0)\n\t{\n\t\tGameOver++;\n\t\tCurrentFrame++;\n\t\tif (GameOver == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tPlayer::Event event = Player::None;\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tPlayer *p = Players[i];\n\t\tevent = (Player::Event)(event | p->Move(&GameField, Pellets));\n\t}\n\tfor (unsigned int i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tfor (unsigned int j = 0; j < size; j++)\n\t\t{\n\t\t\tPosition difference =\n\t\t\t\tPlayers[i]->CurrentPos + (Players[j]->CurrentPos * -1);\n\t\t\tif (i != j\n\t\t\t\t\t&& difference.X > -8 && difference.X < 8\n\t\t\t\t\t&& difference.Y > -8 && difference.Y < 8)\n\t\t\t{\n\t\t\t\tPlayer::Event e;\n\t\t\t\tPlayer *clone_i = Players[i]->Clone();\n\t\t\t\tPlayer *clone_j = Players[j]->Clone();\n\t\t\t\tevent = (Player::Event)(event | Players[i]->CollideWith(clone_j));\n\t\t\t\tevent = (Player::Event)(event | Players[j]->CollideWith(clone_i));\n\t\t\t\tdelete clone_i;\n\t\t\t\tdelete clone_j;\n\t\t\t}\n\t\t}\n\t}\n\tif (event != Player::None)\n\t{\n\t\tif (event & Player::PacmanRespawned)\n\t\t{\n\t\t\tPacmanLives--;\n\t\t}\n\t\tif (event & Player::GhostDied)\n\t\t{\n\t\t\tPaused += 30;\n\t\t}\n\t\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t\t{\n\t\t\tPlayers[i]->ProcessEvent(event);\n\t\t}\n\t}\n\n\tif (Pellets == AllPellets)\n\t{\n\t\tGameOver = 180;\n\t}\n\telse if (PacmanLives == 0)\n\t{\n\t\tGameOver = -180;\n\t}\n\tCurrentFrame++;\n\treturn true;\n}\n\nvoid Game::draw() const\n{\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tPlayers[i]->Draw();\n\t}\n\tif (GameOver > 0)\n\t{\n\t\tRenderer::DrawText(\"Pac-Man wins!\", 24, 228, 444);\n\t}\n\telse if (GameOver < 0)\n\t{\n\t\tRenderer::DrawText(\"Ghosts win!\", 24, 252, 444);\n\t}\n}\n<commit_msg>Removed unused variable<commit_after>#include \"Game.h\"\n#include \"Renderer.h\"\n#include <algorithm>\n\nGame::Game(Field f, std::vector<Player *> p)\n{\n\tGameField = f;\n\tPlayers = p;\n\tCurrentFrame = 0;\n\tPacmanLives = 3;\n\tGameOver = 0;\n\tPaused = 0;\n\n\tfor (std::size_t i = 0; i < FIELD_WIDTH; i++)\n\t{\n\t\tfor (std::size_t j = 0; j < FIELD_HEIGHT; j++)\n\t\t{\n\t\t\tif ((f.Tiles[i][j] & Field::Pellet) == Field::Pellet)\n\t\t\t{\n\t\t\t\tAllPellets.Eat(i, j);\n\t\t\t}\n\t\t}\n\t}\n}\n\nGame::Game(const Game &other)\n{\n\tGameField = other.GameField;\n\tAllPellets = other.AllPellets;\n\tPellets = other.Pellets;\n\tCurrentFrame = other.CurrentFrame;\n\tPacmanLives = other.PacmanLives;\n\tGameOver = other.GameOver;\n\tPaused = other.Paused;\n\tPlayers = std::vector<Player *>();\n\tfor (std::size_t i = 0, size = other.Players.size(); i < size; i++)\n\t{\n\t\tPlayers.push_back(other.Players[i]->Clone());\n\t}\n}\n\nGame::~Game()\n{\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tdelete Players[i];\n\t}\n}\n\nGame& Game::operator=(const Game& rhs)\n{\n\tGameField = rhs.GameField;\n\tAllPellets = rhs.AllPellets;\n\tPellets = rhs.Pellets;\n\tCurrentFrame = rhs.CurrentFrame;\n\tPacmanLives = rhs.PacmanLives;\n\tGameOver = rhs.GameOver;\n\tPaused = rhs.Paused;\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tdelete Players[i];\n\t}\n\tPlayers = std::vector<Player *>();\n\tfor (std::size_t i = 0, size = rhs.Players.size(); i < size; i++)\n\t{\n\t\tPlayers.push_back(rhs.Players[i]->Clone());\n\t}\n\treturn *this;\n}\n\nbool Game::update()\n{\n\tif (Paused > 0)\n\t{\n\t\tPaused--;\n\t\tCurrentFrame++;\n\t\treturn true;\n\t}\n\n\tif (GameOver > 0)\n\t{\n\t\tGameOver--;\n\t\tCurrentFrame++;\n\t\tif (GameOver == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\telse if (GameOver < 0)\n\t{\n\t\tGameOver++;\n\t\tCurrentFrame++;\n\t\tif (GameOver == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tPlayer::Event event = Player::None;\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tPlayer *p = Players[i];\n\t\tevent = (Player::Event)(event | p->Move(&GameField, Pellets));\n\t}\n\tfor (unsigned int i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tfor (unsigned int j = 0; j < size; j++)\n\t\t{\n\t\t\tPosition difference =\n\t\t\t\tPlayers[i]->CurrentPos + (Players[j]->CurrentPos * -1);\n\t\t\tif (i != j\n\t\t\t\t\t&& difference.X > -8 && difference.X < 8\n\t\t\t\t\t&& difference.Y > -8 && difference.Y < 8)\n\t\t\t{\n\t\t\t\tPlayer *clone_i = Players[i]->Clone();\n\t\t\t\tPlayer *clone_j = Players[j]->Clone();\n\t\t\t\tevent = (Player::Event)(event | Players[i]->CollideWith(clone_j));\n\t\t\t\tevent = (Player::Event)(event | Players[j]->CollideWith(clone_i));\n\t\t\t\tdelete clone_i;\n\t\t\t\tdelete clone_j;\n\t\t\t}\n\t\t}\n\t}\n\tif (event != Player::None)\n\t{\n\t\tif (event & Player::PacmanRespawned)\n\t\t{\n\t\t\tPacmanLives--;\n\t\t}\n\t\tif (event & Player::GhostDied)\n\t\t{\n\t\t\tPaused += 30;\n\t\t}\n\t\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t\t{\n\t\t\tPlayers[i]->ProcessEvent(event);\n\t\t}\n\t}\n\n\tif (Pellets == AllPellets)\n\t{\n\t\tGameOver = 180;\n\t}\n\telse if (PacmanLives == 0)\n\t{\n\t\tGameOver = -180;\n\t}\n\tCurrentFrame++;\n\treturn true;\n}\n\nvoid Game::draw() const\n{\n\tfor (std::size_t i = 0, size = Players.size(); i < size; i++)\n\t{\n\t\tPlayers[i]->Draw();\n\t}\n\tif (GameOver > 0)\n\t{\n\t\tRenderer::DrawText(\"Pac-Man wins!\", 24, 228, 444);\n\t}\n\telse if (GameOver < 0)\n\t{\n\t\tRenderer::DrawText(\"Ghosts win!\", 24, 252, 444);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageWriter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageWriter.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkErrorCode.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkImageData.h\"\n\n#if !defined(_WIN32) || defined(__CYGWIN__)\n# include <unistd.h> \/* unlink *\/\n#else\n# include <io.h> \/* unlink *\/\n#endif\n\nvtkCxxRevisionMacro(vtkImageWriter, \"1.60\");\nvtkStandardNewMacro(vtkImageWriter);\n\n#ifdef write\n#undef write\n#endif\n\n#ifdef close\n#undef close\n#endif\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageWriter::vtkImageWriter()\n{\n this->FilePrefix = NULL;\n this->FilePattern = NULL;\n this->FileName = NULL;\n this->InternalFileName = NULL;\n this->FileNumber = 0;\n this->FileDimensionality = 2;\n\n this->FilePattern = new char[strlen(\"%s.%d\") + 1];\n strcpy(this->FilePattern, \"%s.%d\");\n \n this->FileLowerLeft = 0;\n \n this->MinimumFileNumber = this->MaximumFileNumber = 0;\n this->FilesDeleted = 0;\n this->SetNumberOfOutputPorts(0);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageWriter::~vtkImageWriter()\n{\n \/\/ get rid of memory allocated for file names\n if (this->FilePrefix)\n {\n delete [] this->FilePrefix;\n this->FilePrefix = NULL;\n }\n if (this->FilePattern)\n {\n delete [] this->FilePattern;\n this->FilePattern = NULL;\n }\n if (this->FileName)\n {\n delete [] this->FileName;\n this->FileName = NULL;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"FileName: \" <<\n (this->FileName ? this->FileName : \"(none)\") << \"\\n\";\n os << indent << \"FilePrefix: \" << \n (this->FilePrefix ? this->FilePrefix : \"(none)\") << \"\\n\";\n os << indent << \"FilePattern: \" << \n (this->FilePattern ? this->FilePattern : \"(none)\") << \"\\n\";\n\n os << indent << \"FileDimensionality: \" << this->FileDimensionality << \"\\n\";\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageWriter::GetInput()\n{\n if (this->GetNumberOfInputConnections(0) < 1)\n {\n return 0;\n }\n return vtkImageData::SafeDownCast(\n this->GetExecutive()->GetInputData(0, 0));\n}\n\/\/----------------------------------------------------------------------------\n\nint vtkImageWriter::RequestData(\n vtkInformation* vtkNotUsed( request ),\n vtkInformationVector** inputVector,\n vtkInformationVector* vtkNotUsed( outputVector) )\n{\n this->SetErrorCode(vtkErrorCode::NoError);\n\n vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n vtkImageData *input = \n vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ Error checking\n if (input == NULL )\n {\n vtkErrorMacro(<<\"Write:Please specify an input!\");\n return 0;\n }\n if ( !this->FileName && !this->FilePattern)\n {\n vtkErrorMacro(<<\"Write:Please specify either a FileName or a file prefix and pattern\");\n this->SetErrorCode(vtkErrorCode::NoFileNameError);\n return 0;\n }\n \n \/\/ Make sure the file name is allocated\n this->InternalFileName = \n new char[(this->FileName ? strlen(this->FileName) : 1) +\n (this->FilePrefix ? strlen(this->FilePrefix) : 1) +\n (this->FilePattern ? strlen(this->FilePattern) : 1) + 10];\n \n \/\/ Fill in image information.\n int *wExt = inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT());\n this->FileNumber = wExt[4];\n this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber;\n this->FilesDeleted = 0;\n \n \/\/ Write\n this->InvokeEvent(vtkCommand::StartEvent);\n this->UpdateProgress(0.0);\n this->RecursiveWrite(2, input, NULL);\n\n if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n {\n this->DeleteFiles();\n }\n\n this->UpdateProgress(1.0);\n this->InvokeEvent(vtkCommand::EndEvent);\n\n delete [] this->InternalFileName;\n this->InternalFileName = NULL;\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes all the data from the input.\nvoid vtkImageWriter::Write()\n{\n \/\/ we always write, even if nothing has changed, so send a modified\n this->Modified();\n this->UpdateInformation();\n this->GetInput()->SetUpdateExtent(this->GetInput()->GetWholeExtent());\n this->Update();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Breaks region into pieces with correct dimensionality.\nvoid vtkImageWriter::RecursiveWrite(int axis, vtkImageData *cache,\n ofstream *file)\n{\n vtkImageData *data;\n int fileOpenedHere = 0;\n int *ext;\n\n \/\/ if we need to open another slice, do it\n if (!file && (axis + 1) == this->FileDimensionality)\n {\n \/\/ determine the name\n if (this->FileName)\n {\n sprintf(this->InternalFileName,\"%s\",this->FileName);\n }\n else \n {\n if (this->FilePrefix)\n {\n sprintf(this->InternalFileName, this->FilePattern, \n this->FilePrefix, this->FileNumber);\n }\n else\n {\n sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n }\n if (this->FileNumber < this->MinimumFileNumber)\n {\n this->MinimumFileNumber = this->FileNumber;\n }\n else if (this->FileNumber > this->MaximumFileNumber)\n {\n this->MaximumFileNumber = this->FileNumber;\n }\n }\n \/\/ Open the file\n#ifdef _WIN32\n file = new ofstream(this->InternalFileName, ios::out | ios::binary);\n#else\n file = new ofstream(this->InternalFileName, ios::out);\n#endif\n fileOpenedHere = 1;\n if (file->fail())\n {\n vtkErrorMacro(\"RecursiveWrite: Could not open file \" << \n this->InternalFileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n delete file;\n return;\n }\n\n \/\/ Subclasses can write a header with this method call.\n this->WriteFileHeader(file, cache);\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n ++this->FileNumber;\n }\n \n \/\/ Propagate the update extent so we can determine pipeline size\n this->GetInput()->PropagateUpdateExtent();\n\n \/\/ just get the data and write it out\n ext = cache->GetUpdateExtent();\n vtkDebugMacro(\"Getting input extent: \" << ext[0] << \", \" << \n ext[1] << \", \" << ext[2] << \", \" << ext[3] << \", \" << \n ext[4] << \", \" << ext[5] << endl);\n cache->Update();\n data = cache;\n this->RecursiveWrite(axis,cache,data,file);\n if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n {\n this->DeleteFiles();\n return;\n }\n if (file && fileOpenedHere)\n {\n this->WriteFileTrailer(file,cache);\n file->flush();\n if (file->fail())\n {\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n file->close();\n delete file;\n }\n return;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ same idea as the previous method, but it knows that the data is ready\nvoid vtkImageWriter::RecursiveWrite(int axis, vtkImageData *cache,\n vtkImageData *data, ofstream *file)\n{\n int idx, min, max;\n \n \/\/ if the file is already open then just write to it\n if (file)\n {\n this->WriteFile(file,data,cache->GetUpdateExtent());\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n return;\n }\n \n \/\/ if we need to open another slice, do it\n if (!file && (axis + 1) == this->FileDimensionality)\n {\n \/\/ determine the name\n if (this->FileName)\n {\n sprintf(this->InternalFileName,\"%s\",this->FileName);\n }\n else \n {\n if (this->FilePrefix)\n {\n sprintf(this->InternalFileName, this->FilePattern, \n this->FilePrefix, this->FileNumber);\n }\n else\n {\n sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n }\n if (this->FileNumber < this->MinimumFileNumber)\n {\n this->MinimumFileNumber = this->FileNumber;\n }\n else if (this->FileNumber > this->MaximumFileNumber)\n {\n this->MaximumFileNumber = this->FileNumber;\n }\n }\n \/\/ Open the file\n#ifdef _WIN32\n file = new ofstream(this->InternalFileName, ios::out | ios::binary);\n#else\n file = new ofstream(this->InternalFileName, ios::out);\n#endif\n if (file->fail())\n {\n vtkErrorMacro(\"RecursiveWrite: Could not open file \" << \n this->InternalFileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n delete file;\n return;\n }\n\n \/\/ Subclasses can write a header with this method call.\n this->WriteFileHeader(file, cache);\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n this->WriteFile(file,data,cache->GetUpdateExtent());\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n ++this->FileNumber;\n this->WriteFileTrailer(file,cache);\n file->flush();\n if (file->fail())\n {\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n file->close();\n delete file;\n return;\n }\n \n \/\/ if the current region is too high a dimension forthe file\n \/\/ the we will split the current axis\n cache->GetAxisUpdateExtent(axis, min, max);\n \n \/\/ if it is the y axis then flip by default\n if (axis == 1 && !this->FileLowerLeft)\n {\n for(idx = max; idx >= min; idx--)\n {\n cache->SetAxisUpdateExtent(axis, idx, idx);\n if (this->ErrorCode != vtkErrorCode::OutOfDiskSpaceError)\n {\n this->RecursiveWrite(axis - 1, cache, data, file);\n }\n else\n {\n this->DeleteFiles();\n }\n }\n }\n else\n {\n for(idx = min; idx <= max; idx++)\n {\n cache->SetAxisUpdateExtent(axis, idx, idx);\n if (this->ErrorCode != vtkErrorCode::OutOfDiskSpaceError)\n {\n this->RecursiveWrite(axis - 1, cache, data, file);\n }\n else\n {\n this->DeleteFiles();\n }\n }\n }\n \n \/\/ restore original extent\n cache->SetAxisUpdateExtent(axis, min, max);\n}\n \n\n\/\/----------------------------------------------------------------------------\ntemplate <class T>\nunsigned long vtkImageWriterGetSize(T*)\n{\n return sizeof(T);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes a region in a file. Subclasses can override this method\n\/\/ to produce a header. This method only hanldes 3d data (plus components).\nvoid vtkImageWriter::WriteFile(ofstream *file, vtkImageData *data,\n int extent[6])\n{\n int idxY, idxZ;\n int rowLength; \/\/ in bytes\n void *ptr;\n unsigned long count = 0;\n unsigned long target;\n float progress = this->Progress;\n float area;\n int *wExtent;\n \n \/\/ Make sure we actually have data.\n if ( !data->GetPointData()->GetScalars())\n {\n vtkErrorMacro(<< \"Could not get data from input.\");\n return;\n }\n\n \/\/ take into consideration the scalar type\n switch (data->GetScalarType())\n {\n vtkTemplateMacro(\n rowLength = vtkImageWriterGetSize(static_cast<VTK_TT*>(0))\n );\n default:\n vtkErrorMacro(<< \"Execute: Unknown output ScalarType\");\n return; \n }\n rowLength *= data->GetNumberOfScalarComponents();\n rowLength *= (extent[1] - extent[0] + 1);\n\n wExtent = this->GetInput()->GetWholeExtent();\n area = (float) ((extent[5] - extent[4] + 1)*\n (extent[3] - extent[2] + 1)*\n (extent[1] - extent[0] + 1)) \/ \n (float) ((wExtent[5] -wExtent[4] + 1)*\n (wExtent[3] -wExtent[2] + 1)*\n (wExtent[1] -wExtent[0] + 1));\n \n target = (unsigned long)((extent[5]-extent[4]+1)*\n (extent[3]-extent[2]+1)\/(50.0*area));\n target++;\n\n int ystart = extent[3];\n int yend = extent[2] - 1;\n int yinc = -1;\n if (this->FileLowerLeft)\n {\n ystart = extent[2];\n yend = extent[3]+1;\n yinc = 1;\n }\n \n for (idxZ = extent[4]; idxZ <= extent[5]; ++idxZ)\n {\n for (idxY = ystart; idxY != yend; idxY = idxY + yinc)\n {\n if (!(count%target))\n {\n this->UpdateProgress(progress + count\/(50.0*target));\n }\n count++;\n ptr = data->GetScalarPointer(extent[0], idxY, idxZ);\n if ( ! file->write((char *)ptr, rowLength))\n {\n return;\n }\n }\n }\n}\n\nvoid vtkImageWriter::DeleteFiles()\n{\n if (this->FilesDeleted)\n {\n return;\n }\n int i;\n char *fileName;\n \n vtkErrorMacro(\"Ran out of disk space; deleting file(s) already written\");\n \n if (this->FileName)\n {\n unlink(this->FileName);\n }\n else\n {\n if (this->FilePrefix)\n {\n fileName =\n new char[strlen(this->FilePrefix) + strlen(this->FilePattern) + 10];\n \n for (i = this->MinimumFileNumber; i <= this->MaximumFileNumber; i++)\n {\n sprintf(fileName, this->FilePattern, this->FilePrefix, i);\n unlink(fileName);\n }\n delete [] fileName;\n }\n else\n {\n fileName = new char[strlen(this->FilePattern) + 10];\n \n for (i = this->MinimumFileNumber; i <= this->MaximumFileNumber; i++)\n {\n sprintf(fileName, this->FilePattern, i);\n unlink(fileName);\n }\n delete [] fileName;\n }\n }\n this->FilesDeleted = 1;\n}\n<commit_msg>ENH: more robust way to remove file on win32<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageWriter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageWriter.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkErrorCode.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkImageData.h\"\n\n#include <vtksys\/SystemTools.hxx>\n\nvtkCxxRevisionMacro(vtkImageWriter, \"1.61\");\nvtkStandardNewMacro(vtkImageWriter);\n\n\/\/----------------------------------------------------------------------------\nvtkImageWriter::vtkImageWriter()\n{\n this->FilePrefix = NULL;\n this->FilePattern = NULL;\n this->FileName = NULL;\n this->InternalFileName = NULL;\n this->FileNumber = 0;\n this->FileDimensionality = 2;\n\n this->FilePattern = new char[strlen(\"%s.%d\") + 1];\n strcpy(this->FilePattern, \"%s.%d\");\n \n this->FileLowerLeft = 0;\n \n this->MinimumFileNumber = this->MaximumFileNumber = 0;\n this->FilesDeleted = 0;\n this->SetNumberOfOutputPorts(0);\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageWriter::~vtkImageWriter()\n{\n \/\/ get rid of memory allocated for file names\n if (this->FilePrefix)\n {\n delete [] this->FilePrefix;\n this->FilePrefix = NULL;\n }\n if (this->FilePattern)\n {\n delete [] this->FilePattern;\n this->FilePattern = NULL;\n }\n if (this->FileName)\n {\n delete [] this->FileName;\n this->FileName = NULL;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"FileName: \" <<\n (this->FileName ? this->FileName : \"(none)\") << \"\\n\";\n os << indent << \"FilePrefix: \" << \n (this->FilePrefix ? this->FilePrefix : \"(none)\") << \"\\n\";\n os << indent << \"FilePattern: \" << \n (this->FilePattern ? this->FilePattern : \"(none)\") << \"\\n\";\n\n os << indent << \"FileDimensionality: \" << this->FileDimensionality << \"\\n\";\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageWriter::GetInput()\n{\n if (this->GetNumberOfInputConnections(0) < 1)\n {\n return 0;\n }\n return vtkImageData::SafeDownCast(\n this->GetExecutive()->GetInputData(0, 0));\n}\n\/\/----------------------------------------------------------------------------\n\nint vtkImageWriter::RequestData(\n vtkInformation* vtkNotUsed( request ),\n vtkInformationVector** inputVector,\n vtkInformationVector* vtkNotUsed( outputVector) )\n{\n this->SetErrorCode(vtkErrorCode::NoError);\n\n vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n vtkImageData *input = \n vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ Error checking\n if (input == NULL )\n {\n vtkErrorMacro(<<\"Write:Please specify an input!\");\n return 0;\n }\n if ( !this->FileName && !this->FilePattern)\n {\n vtkErrorMacro(<<\"Write:Please specify either a FileName or a file prefix and pattern\");\n this->SetErrorCode(vtkErrorCode::NoFileNameError);\n return 0;\n }\n \n \/\/ Make sure the file name is allocated\n this->InternalFileName = \n new char[(this->FileName ? strlen(this->FileName) : 1) +\n (this->FilePrefix ? strlen(this->FilePrefix) : 1) +\n (this->FilePattern ? strlen(this->FilePattern) : 1) + 10];\n \n \/\/ Fill in image information.\n int *wExt = inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT());\n this->FileNumber = wExt[4];\n this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber;\n this->FilesDeleted = 0;\n \n \/\/ Write\n this->InvokeEvent(vtkCommand::StartEvent);\n this->UpdateProgress(0.0);\n this->RecursiveWrite(2, input, NULL);\n\n if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n {\n this->DeleteFiles();\n }\n\n this->UpdateProgress(1.0);\n this->InvokeEvent(vtkCommand::EndEvent);\n\n delete [] this->InternalFileName;\n this->InternalFileName = NULL;\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes all the data from the input.\nvoid vtkImageWriter::Write()\n{\n \/\/ we always write, even if nothing has changed, so send a modified\n this->Modified();\n this->UpdateInformation();\n this->GetInput()->SetUpdateExtent(this->GetInput()->GetWholeExtent());\n this->Update();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Breaks region into pieces with correct dimensionality.\nvoid vtkImageWriter::RecursiveWrite(int axis, vtkImageData *cache,\n ofstream *file)\n{\n vtkImageData *data;\n int fileOpenedHere = 0;\n int *ext;\n\n \/\/ if we need to open another slice, do it\n if (!file && (axis + 1) == this->FileDimensionality)\n {\n \/\/ determine the name\n if (this->FileName)\n {\n sprintf(this->InternalFileName,\"%s\",this->FileName);\n }\n else \n {\n if (this->FilePrefix)\n {\n sprintf(this->InternalFileName, this->FilePattern, \n this->FilePrefix, this->FileNumber);\n }\n else\n {\n sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n }\n if (this->FileNumber < this->MinimumFileNumber)\n {\n this->MinimumFileNumber = this->FileNumber;\n }\n else if (this->FileNumber > this->MaximumFileNumber)\n {\n this->MaximumFileNumber = this->FileNumber;\n }\n }\n \/\/ Open the file\n#ifdef _WIN32\n file = new ofstream(this->InternalFileName, ios::out | ios::binary);\n#else\n file = new ofstream(this->InternalFileName, ios::out);\n#endif\n fileOpenedHere = 1;\n if (file->fail())\n {\n vtkErrorMacro(\"RecursiveWrite: Could not open file \" << \n this->InternalFileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n delete file;\n return;\n }\n\n \/\/ Subclasses can write a header with this method call.\n this->WriteFileHeader(file, cache);\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n ++this->FileNumber;\n }\n \n \/\/ Propagate the update extent so we can determine pipeline size\n this->GetInput()->PropagateUpdateExtent();\n\n \/\/ just get the data and write it out\n ext = cache->GetUpdateExtent();\n vtkDebugMacro(\"Getting input extent: \" << ext[0] << \", \" << \n ext[1] << \", \" << ext[2] << \", \" << ext[3] << \", \" << \n ext[4] << \", \" << ext[5] << endl);\n cache->Update();\n data = cache;\n this->RecursiveWrite(axis,cache,data,file);\n if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n {\n this->DeleteFiles();\n return;\n }\n if (file && fileOpenedHere)\n {\n this->WriteFileTrailer(file,cache);\n file->flush();\n if (file->fail())\n {\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n file->close();\n delete file;\n }\n return;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ same idea as the previous method, but it knows that the data is ready\nvoid vtkImageWriter::RecursiveWrite(int axis, vtkImageData *cache,\n vtkImageData *data, ofstream *file)\n{\n int idx, min, max;\n \n \/\/ if the file is already open then just write to it\n if (file)\n {\n this->WriteFile(file,data,cache->GetUpdateExtent());\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n return;\n }\n \n \/\/ if we need to open another slice, do it\n if (!file && (axis + 1) == this->FileDimensionality)\n {\n \/\/ determine the name\n if (this->FileName)\n {\n sprintf(this->InternalFileName,\"%s\",this->FileName);\n }\n else \n {\n if (this->FilePrefix)\n {\n sprintf(this->InternalFileName, this->FilePattern, \n this->FilePrefix, this->FileNumber);\n }\n else\n {\n sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n }\n if (this->FileNumber < this->MinimumFileNumber)\n {\n this->MinimumFileNumber = this->FileNumber;\n }\n else if (this->FileNumber > this->MaximumFileNumber)\n {\n this->MaximumFileNumber = this->FileNumber;\n }\n }\n \/\/ Open the file\n#ifdef _WIN32\n file = new ofstream(this->InternalFileName, ios::out | ios::binary);\n#else\n file = new ofstream(this->InternalFileName, ios::out);\n#endif\n if (file->fail())\n {\n vtkErrorMacro(\"RecursiveWrite: Could not open file \" << \n this->InternalFileName);\n this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n delete file;\n return;\n }\n\n \/\/ Subclasses can write a header with this method call.\n this->WriteFileHeader(file, cache);\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n this->WriteFile(file,data,cache->GetUpdateExtent());\n file->flush();\n if (file->fail())\n {\n file->close();\n delete file;\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n return;\n }\n ++this->FileNumber;\n this->WriteFileTrailer(file,cache);\n file->flush();\n if (file->fail())\n {\n this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n }\n file->close();\n delete file;\n return;\n }\n \n \/\/ if the current region is too high a dimension forthe file\n \/\/ the we will split the current axis\n cache->GetAxisUpdateExtent(axis, min, max);\n \n \/\/ if it is the y axis then flip by default\n if (axis == 1 && !this->FileLowerLeft)\n {\n for(idx = max; idx >= min; idx--)\n {\n cache->SetAxisUpdateExtent(axis, idx, idx);\n if (this->ErrorCode != vtkErrorCode::OutOfDiskSpaceError)\n {\n this->RecursiveWrite(axis - 1, cache, data, file);\n }\n else\n {\n this->DeleteFiles();\n }\n }\n }\n else\n {\n for(idx = min; idx <= max; idx++)\n {\n cache->SetAxisUpdateExtent(axis, idx, idx);\n if (this->ErrorCode != vtkErrorCode::OutOfDiskSpaceError)\n {\n this->RecursiveWrite(axis - 1, cache, data, file);\n }\n else\n {\n this->DeleteFiles();\n }\n }\n }\n \n \/\/ restore original extent\n cache->SetAxisUpdateExtent(axis, min, max);\n}\n \n\n\/\/----------------------------------------------------------------------------\ntemplate <class T>\nunsigned long vtkImageWriterGetSize(T*)\n{\n return sizeof(T);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes a region in a file. Subclasses can override this method\n\/\/ to produce a header. This method only hanldes 3d data (plus components).\nvoid vtkImageWriter::WriteFile(ofstream *file, vtkImageData *data,\n int extent[6])\n{\n int idxY, idxZ;\n int rowLength; \/\/ in bytes\n void *ptr;\n unsigned long count = 0;\n unsigned long target;\n float progress = this->Progress;\n float area;\n int *wExtent;\n \n \/\/ Make sure we actually have data.\n if ( !data->GetPointData()->GetScalars())\n {\n vtkErrorMacro(<< \"Could not get data from input.\");\n return;\n }\n\n \/\/ take into consideration the scalar type\n switch (data->GetScalarType())\n {\n vtkTemplateMacro(\n rowLength = vtkImageWriterGetSize(static_cast<VTK_TT*>(0))\n );\n default:\n vtkErrorMacro(<< \"Execute: Unknown output ScalarType\");\n return; \n }\n rowLength *= data->GetNumberOfScalarComponents();\n rowLength *= (extent[1] - extent[0] + 1);\n\n wExtent = this->GetInput()->GetWholeExtent();\n area = (float) ((extent[5] - extent[4] + 1)*\n (extent[3] - extent[2] + 1)*\n (extent[1] - extent[0] + 1)) \/ \n (float) ((wExtent[5] -wExtent[4] + 1)*\n (wExtent[3] -wExtent[2] + 1)*\n (wExtent[1] -wExtent[0] + 1));\n \n target = (unsigned long)((extent[5]-extent[4]+1)*\n (extent[3]-extent[2]+1)\/(50.0*area));\n target++;\n\n int ystart = extent[3];\n int yend = extent[2] - 1;\n int yinc = -1;\n if (this->FileLowerLeft)\n {\n ystart = extent[2];\n yend = extent[3]+1;\n yinc = 1;\n }\n \n for (idxZ = extent[4]; idxZ <= extent[5]; ++idxZ)\n {\n for (idxY = ystart; idxY != yend; idxY = idxY + yinc)\n {\n if (!(count%target))\n {\n this->UpdateProgress(progress + count\/(50.0*target));\n }\n count++;\n ptr = data->GetScalarPointer(extent[0], idxY, idxZ);\n if ( ! file->write((char *)ptr, rowLength))\n {\n return;\n }\n }\n }\n}\n\nvoid vtkImageWriter::DeleteFiles()\n{\n if (this->FilesDeleted)\n {\n return;\n }\n int i;\n char *fileName;\n \n vtkErrorMacro(\"Ran out of disk space; deleting file(s) already written\");\n \n if (this->FileName)\n {\n vtksys::SystemTools::RemoveFile(this->FileName);\n }\n else\n {\n if (this->FilePrefix)\n {\n fileName =\n new char[strlen(this->FilePrefix) + strlen(this->FilePattern) + 10];\n \n for (i = this->MinimumFileNumber; i <= this->MaximumFileNumber; i++)\n {\n sprintf(fileName, this->FilePattern, this->FilePrefix, i);\n vtksys::SystemTools::RemoveFile(fileName);\n }\n delete [] fileName;\n }\n else\n {\n fileName = new char[strlen(this->FilePattern) + 10];\n \n for (i = this->MinimumFileNumber; i <= this->MaximumFileNumber; i++)\n {\n sprintf(fileName, this->FilePattern, i);\n vtksys::SystemTools::RemoveFile(fileName);\n }\n delete [] fileName;\n }\n }\n this->FilesDeleted = 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"ros\/ros.h\"\n#include <iostream>\n#include \"std_msgs\/String.h\"\n#include <sstream>\n#include <thread>\n#include \"tortuga\/imuapi.h\"\n#include \"tortuga\/sensorapi.h\"\n\nbool checkError(int, char*);\n\n\/\/ This is the code used to open and publish all of the \n\/\/ file descriptors for tortuga device boards\n\n\nstd::string imu_file = \"\/dev\/magboom\";\nstd::string sensor_file = \"\/dev\/sensor\";\n\nint main(){\n\t\n\t\/\/imu\n\tif(ros::param::has(imu_file)){\n\t\tros::param::get(\"imu_device_file\", imu_file);\n\t}else{\n\t\tros::param::set(\"imu_device_file\", imu_file);\n\t}\n\n\tint fd = openIMU(imu_file.c_str());\n\tcheckError(fd, \"IMU\");\n\n\tros::param::set(\"imu_file_descriptor\", fd);\n\n\t\/\/sensor board\n\tif(ros::param::has(sensor_file)){\n\t\tros::param::get(\"sensor_board_file\", sensor_file);\n\t}else{\n\t\tros::param::set(\"sensor_board_file\", sensor_file);\n\t}\n\n\tfd = openSensorBoard(sensor_file.c_str());\n\tcheckError(fd, \"Sensor Board\");\n\n\tros::param::set(\"sensor_board_file_descriptor\", fd);\n\n}\n\n\n\nbool checkError(int e, char *name) {\n switch(e) {\n case SB_IOERROR:\n ROS_DEBUG(\"IO ERROR in %s\", name);\n return true;\n case SB_BADCC:\n ROS_DEBUG(\"BAD CC ERROR in %s\", name);\n return true;\n case SB_HWFAIL:\n ROS_DEBUG(\"HW FAILURE ERROR in %s\", name);\n return true;\n case SB_ERROR:\n ROS_DEBUG(\"ERROR in %s\", name);\n return true;\n default:\n return false;\n }\n}<commit_msg>board opener works now<commit_after>\n#include \"ros\/ros.h\"\n#include <iostream>\n#include \"std_msgs\/String.h\"\n#include <sstream>\n#include <thread>\n#include \"tortuga\/imuapi.h\"\n#include \"tortuga\/sensorapi.h\"\n\nbool checkError(int, char*);\n\n\/\/ This is the code used to open and publish all of the \n\/\/ file descriptors for tortuga device boards\n\n\nstd::string imu_file = \"\/dev\/magboom\";\nstd::string sensor_file = \"\/dev\/sensor\";\n\nint main(int argc, char **argv){\n\n\tros::init(argc, argv, \"board_opener\");\n\n\t\/\/imu\n\tif(ros::param::has(imu_file)){\n\t\tros::param::get(\"imu_device_file\", imu_file);\n\t}else{\n\t\tros::param::set(\"imu_device_file\", imu_file);\n\t}\n\n\tint fd = openIMU(imu_file.c_str());\n\tcheckError(fd, \"IMU\");\n\n\tros::param::set(\"imu_file_descriptor\", fd);\n\n\t\/\/sensor board\n\tif(ros::param::has(sensor_file)){\n\t\tros::param::get(\"sensor_board_file\", sensor_file);\n\t}else{\n\t\tros::param::set(\"sensor_board_file\", sensor_file);\n\t}\n\n\tfd = openSensorBoard(sensor_file.c_str());\n\tcheckError(fd, \"Sensor Board\");\n\n\tros::param::set(\"sensor_board_file_descriptor\", fd);\n\n}\n\n\n\nbool checkError(int e, char *name) {\n switch(e) {\n case SB_IOERROR:\n ROS_DEBUG(\"IO ERROR in %s\", name);\n return true;\n case SB_BADCC:\n ROS_DEBUG(\"BAD CC ERROR in %s\", name);\n return true;\n case SB_HWFAIL:\n ROS_DEBUG(\"HW FAILURE ERROR in %s\", name);\n return true;\n case SB_ERROR:\n ROS_DEBUG(\"ERROR in %s\", name);\n return true;\n default:\n return false;\n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"pt_data.h\"\n#include \"utils\/functions.h\"\nnamespace navitia{namespace type {\n\n\nPT_Data& PT_Data::operator=(PT_Data&& other){\n#define COPY_FROM_OTHER(type_name, collection_name) collection_name = other.collection_name; collection_name##_map = other.collection_name##_map;\n ITERATE_NAVITIA_PT_TYPES(COPY_FROM_OTHER)\n\n stop_point_connections = other.stop_point_connections;\n journey_pattern_point_connections = other.journey_pattern_point_connections;\n stop_times = other.stop_times;\n\n \/\/ First letter\n stop_area_autocomplete = other.stop_area_autocomplete;\n stop_point_autocomplete = other.stop_point_autocomplete;\n line_autocomplete = other.line_autocomplete;\n\n \/\/ Proximity list\n stop_area_proximity_list = other.stop_area_proximity_list;\n stop_point_proximity_list = other.stop_point_proximity_list;\n\n return *this;\n}\n\n\nvoid PT_Data::sort(){\n#define SORT_AND_INDEX(type_name, collection_name) std::sort(collection_name.begin(), collection_name.end(), Less());\\\n std::for_each(collection_name.begin(), collection_name.end(), Indexer<nt::idx_t>());\n ITERATE_NAVITIA_PT_TYPES(SORT_AND_INDEX)\n\n std::sort(journey_pattern_point_connections.begin(), journey_pattern_point_connections.end());\n std::for_each(journey_pattern_point_connections.begin(), journey_pattern_point_connections.end(), Indexer<idx_t>());\n\n std::sort(stop_point_connections.begin(), stop_point_connections.end());\n std::for_each(stop_point_connections.begin(), stop_point_connections.end(), Indexer<idx_t>());\n\n for(auto* vj: this->vehicle_journeys){\n std::sort(vj->stop_time_list.begin(), vj->stop_time_list.end(), Less());\n }\n}\n\n\n\/\/void PT_Data::build_autocomplete(const std::map<std::string, std::string> & map_alias, const std::map<std::string, std::string> & map_synonymes){\nvoid PT_Data::build_autocomplete(const navitia::georef::GeoRef & georef){\n this->stop_area_autocomplete.clear();\n for(const StopArea* sa : this->stop_areas){\n \/\/ A ne pas ajouter dans le disctionnaire si pas ne nom ou n'a pas d'admin\n if ((!sa->name.empty()) && (sa->admin_list.size() > 0)){\n std::string key=\"\";\n for( navitia::georef::Admin* admin : sa->admin_list){\n if (admin->level ==8){key +=\" \" + admin->name;}\n }\n this->stop_area_autocomplete.add_string(sa->name + \" \" + key, sa->idx, georef.alias, georef.synonymes);\n }\n }\n this->stop_area_autocomplete.build();\n \/\/this->stop_area_autocomplete.compute_score((*this), georef, type::Type_e::StopArea);\n\n this->stop_point_autocomplete.clear();\n for(const StopPoint* sp : this->stop_points){\n \/\/ A ne pas ajouter dans le disctionnaire si pas ne nom ou n'a pas d'admin\n if ((!sp->name.empty()) && (sp->admin_list.size() > 0)){\n std::string key=\"\";\n for(navitia::georef::Admin* admin : sp->admin_list){\n if (admin->level == 8){key += key + \" \" + admin->name;}\n }\n this->stop_point_autocomplete.add_string(sp->name + \" \" + key, sp->idx, georef.alias, georef.synonymes);\n }\n }\n this->stop_point_autocomplete.build();\n\n this->line_autocomplete.clear();\n for(const Line* line : this->lines){\n if (!line->name.empty()){\n this->line_autocomplete.add_string(line->name, line->idx, georef.alias, georef.synonymes);\n }\n }\n this->line_autocomplete.build();\n}\n\nvoid PT_Data::compute_score_autocomplete(navitia::georef::GeoRef& georef){\n\n \/\/Commencer par calculer le score des admin\n georef.fl_admin.compute_score((*this), georef, type::Type_e::Admin);\n \/\/Affecter le score de chaque admin à ses ObjectTC\n georef.fl_way.compute_score((*this), georef, type::Type_e::Way);\n georef.fl_poi.compute_score((*this), georef, type::Type_e::POI);\n this->stop_area_autocomplete.compute_score((*this), georef, type::Type_e::StopArea);\n this->stop_point_autocomplete.compute_score((*this), georef, type::Type_e::StopPoint);\n}\n\n\nvoid PT_Data::build_proximity_list() {\n this->stop_area_proximity_list.clear();\n for(const StopArea* stop_area : this->stop_areas){\n this->stop_area_proximity_list.add(stop_area->coord, stop_area->idx);\n }\n this->stop_area_proximity_list.build();\n\n this->stop_point_proximity_list.clear();\n for(const StopPoint* stop_point : this->stop_points){\n this->stop_point_proximity_list.add(stop_point->coord, stop_point->idx);\n }\n this->stop_point_proximity_list.build();\n}\n\nvoid PT_Data::build_uri() {\n#define NORMALIZE_EXT_CODE(type_name, collection_name) for(auto &element : collection_name) collection_name##_map[element->uri] = element;\n ITERATE_NAVITIA_PT_TYPES(NORMALIZE_EXT_CODE)\n}\n\n\/** Foncteur fixe le membre \"idx\" d'un objet en incrémentant toujours de 1\n *\n * Cela permet de numéroter tous les objets de 0 à n-1 d'un vecteur de pointeurs\n *\/\nstruct Indexer{\n idx_t idx;\n Indexer(): idx(0){}\n\n template<class T>\n void operator()(T* obj){obj->idx = idx; idx++;}\n};\n\nvoid PT_Data::index(){\n#define INDEX(type_name, collection_name) std::for_each(collection_name.begin(), collection_name.end(), Indexer());\n ITERATE_NAVITIA_PT_TYPES(INDEX)\n}\n\nPT_Data::~PT_Data() {\n auto func_delete = \n#define DELETE_PTDATA(type_name, collection_name) \\\n std::for_each(collection_name.begin(), collection_name.end(),\\\n [](type_name* obj){delete obj;});\n ITERATE_NAVITIA_PT_TYPES(DELETE_PTDATA)\n\n for(StopTime* st : stop_times) {\n delete st;\n }\n}\n}}\n<commit_msg>pt_data : Suppression d'une ligne qui ne servait à rien<commit_after>#include \"pt_data.h\"\n#include \"utils\/functions.h\"\nnamespace navitia{namespace type {\n\n\nPT_Data& PT_Data::operator=(PT_Data&& other){\n#define COPY_FROM_OTHER(type_name, collection_name) collection_name = other.collection_name; collection_name##_map = other.collection_name##_map;\n ITERATE_NAVITIA_PT_TYPES(COPY_FROM_OTHER)\n\n stop_point_connections = other.stop_point_connections;\n journey_pattern_point_connections = other.journey_pattern_point_connections;\n stop_times = other.stop_times;\n\n \/\/ First letter\n stop_area_autocomplete = other.stop_area_autocomplete;\n stop_point_autocomplete = other.stop_point_autocomplete;\n line_autocomplete = other.line_autocomplete;\n\n \/\/ Proximity list\n stop_area_proximity_list = other.stop_area_proximity_list;\n stop_point_proximity_list = other.stop_point_proximity_list;\n\n return *this;\n}\n\n\nvoid PT_Data::sort(){\n#define SORT_AND_INDEX(type_name, collection_name) std::sort(collection_name.begin(), collection_name.end(), Less());\\\n std::for_each(collection_name.begin(), collection_name.end(), Indexer<nt::idx_t>());\n ITERATE_NAVITIA_PT_TYPES(SORT_AND_INDEX)\n\n std::sort(journey_pattern_point_connections.begin(), journey_pattern_point_connections.end());\n std::for_each(journey_pattern_point_connections.begin(), journey_pattern_point_connections.end(), Indexer<idx_t>());\n\n std::sort(stop_point_connections.begin(), stop_point_connections.end());\n std::for_each(stop_point_connections.begin(), stop_point_connections.end(), Indexer<idx_t>());\n\n for(auto* vj: this->vehicle_journeys){\n std::sort(vj->stop_time_list.begin(), vj->stop_time_list.end(), Less());\n }\n}\n\n\nvoid PT_Data::build_autocomplete(const navitia::georef::GeoRef & georef){\n this->stop_area_autocomplete.clear();\n for(const StopArea* sa : this->stop_areas){\n \/\/ A ne pas ajouter dans le disctionnaire si pas ne nom ou n'a pas d'admin\n if ((!sa->name.empty()) && (sa->admin_list.size() > 0)){\n std::string key=\"\";\n for( navitia::georef::Admin* admin : sa->admin_list){\n if (admin->level ==8){key +=\" \" + admin->name;}\n }\n this->stop_area_autocomplete.add_string(sa->name + \" \" + key, sa->idx, georef.alias, georef.synonymes);\n }\n }\n this->stop_area_autocomplete.build();\n \/\/this->stop_area_autocomplete.compute_score((*this), georef, type::Type_e::StopArea);\n\n this->stop_point_autocomplete.clear();\n for(const StopPoint* sp : this->stop_points){\n \/\/ A ne pas ajouter dans le disctionnaire si pas ne nom ou n'a pas d'admin\n if ((!sp->name.empty()) && (sp->admin_list.size() > 0)){\n std::string key=\"\";\n for(navitia::georef::Admin* admin : sp->admin_list){\n if (admin->level == 8){key += key + \" \" + admin->name;}\n }\n this->stop_point_autocomplete.add_string(sp->name + \" \" + key, sp->idx, georef.alias, georef.synonymes);\n }\n }\n this->stop_point_autocomplete.build();\n\n this->line_autocomplete.clear();\n for(const Line* line : this->lines){\n if (!line->name.empty()){\n this->line_autocomplete.add_string(line->name, line->idx, georef.alias, georef.synonymes);\n }\n }\n this->line_autocomplete.build();\n}\n\nvoid PT_Data::compute_score_autocomplete(navitia::georef::GeoRef& georef){\n\n \/\/Commencer par calculer le score des admin\n georef.fl_admin.compute_score((*this), georef, type::Type_e::Admin);\n \/\/Affecter le score de chaque admin à ses ObjectTC\n georef.fl_way.compute_score((*this), georef, type::Type_e::Way);\n georef.fl_poi.compute_score((*this), georef, type::Type_e::POI);\n this->stop_area_autocomplete.compute_score((*this), georef, type::Type_e::StopArea);\n this->stop_point_autocomplete.compute_score((*this), georef, type::Type_e::StopPoint);\n}\n\n\nvoid PT_Data::build_proximity_list() {\n this->stop_area_proximity_list.clear();\n for(const StopArea* stop_area : this->stop_areas){\n this->stop_area_proximity_list.add(stop_area->coord, stop_area->idx);\n }\n this->stop_area_proximity_list.build();\n\n this->stop_point_proximity_list.clear();\n for(const StopPoint* stop_point : this->stop_points){\n this->stop_point_proximity_list.add(stop_point->coord, stop_point->idx);\n }\n this->stop_point_proximity_list.build();\n}\n\nvoid PT_Data::build_uri() {\n#define NORMALIZE_EXT_CODE(type_name, collection_name) for(auto &element : collection_name) collection_name##_map[element->uri] = element;\n ITERATE_NAVITIA_PT_TYPES(NORMALIZE_EXT_CODE)\n}\n\n\/** Foncteur fixe le membre \"idx\" d'un objet en incrémentant toujours de 1\n *\n * Cela permet de numéroter tous les objets de 0 à n-1 d'un vecteur de pointeurs\n *\/\nstruct Indexer{\n idx_t idx;\n Indexer(): idx(0){}\n\n template<class T>\n void operator()(T* obj){obj->idx = idx; idx++;}\n};\n\nvoid PT_Data::index(){\n#define INDEX(type_name, collection_name) std::for_each(collection_name.begin(), collection_name.end(), Indexer());\n ITERATE_NAVITIA_PT_TYPES(INDEX)\n}\n\nPT_Data::~PT_Data() {\n auto func_delete = \n#define DELETE_PTDATA(type_name, collection_name) \\\n std::for_each(collection_name.begin(), collection_name.end(),\\\n [](type_name* obj){delete obj;});\n ITERATE_NAVITIA_PT_TYPES(DELETE_PTDATA)\n\n for(StopTime* st : stop_times) {\n delete st;\n }\n}\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and\/or associated documentation files (the\n\/\/ \"Materials\"), to deal in the Materials without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Materials, and to\n\/\/ permit persons to whom the Materials are furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Materials.\n\/\/\n\/\/ MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS\n\/\/ KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS\n\/\/ SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT\n\/\/ https:\/\/www.khronos.org\/registry\/\n\/\/\n\/\/ THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n\n#include \"val\/Function.h\"\n\n#include <cassert>\n\n#include <algorithm>\n#include <unordered_set>\n#include <unordered_map>\n#include <utility>\n\n#include \"val\/BasicBlock.h\"\n#include \"val\/Construct.h\"\n#include \"validate.h\"\n\nusing std::ignore;\nusing std::list;\nusing std::make_pair;\nusing std::pair;\nusing std::tie;\nusing std::vector;\n\nnamespace {\n\nusing libspirv::BasicBlock;\n\n\/\/ Computes a minimal set of root nodes required to traverse, in the forward\n\/\/ direction, the CFG represented by the given vector of blocks, and successor\n\/\/ and predecessor functions.\nstd::vector<BasicBlock*> TraversalRoots(const std::vector<BasicBlock*>& blocks,\n libspirv::get_blocks_func succ_func,\n libspirv::get_blocks_func pred_func) {\n \/\/ The set of nodes which have been visited from any of the roots so far.\n std::unordered_set<const BasicBlock*> visited;\n\n auto mark_visited = [&visited](const BasicBlock* b) { visited.insert(b); };\n auto ignore_block = [](const BasicBlock*) {};\n auto ignore_blocks = [](const BasicBlock*, const BasicBlock*) {};\n\n auto traverse_from_root = [&mark_visited, &succ_func, &ignore_block,\n &ignore_blocks](const BasicBlock* entry) {\n DepthFirstTraversal(entry, succ_func, mark_visited, ignore_block,\n ignore_blocks);\n };\n\n std::vector<BasicBlock*> result;\n\n \/\/ First collect nodes without predecessors.\n for (auto block : blocks) {\n if (pred_func(block)->empty()) {\n assert(visited.count(block) == 0 && \"Malformed graph!\");\n result.push_back(block);\n traverse_from_root(block);\n }\n }\n\n \/\/ Now collect other stranded nodes. These must be in unreachable cycles.\n for (auto block : blocks) {\n if (visited.count(block) == 0) {\n result.push_back(block);\n traverse_from_root(block);\n }\n }\n\n return result;\n}\n\n} \/\/ anonymous namespace\n\nnamespace libspirv {\n\n\/\/ Universal Limit of ResultID + 1\nstatic const uint32_t kInvalidId = 0x400000;\n\nFunction::Function(uint32_t function_id, uint32_t result_type_id,\n SpvFunctionControlMask function_control,\n uint32_t function_type_id)\n : id_(function_id),\n function_type_id_(function_type_id),\n result_type_id_(result_type_id),\n function_control_(function_control),\n declaration_type_(FunctionDecl::kFunctionDeclUnknown),\n end_has_been_registered_(false),\n blocks_(),\n current_block_(nullptr),\n pseudo_entry_block_(0),\n pseudo_exit_block_(kInvalidId),\n cfg_constructs_(),\n variable_ids_(),\n parameter_ids_() {}\n\nbool Function::IsFirstBlock(uint32_t block_id) const {\n return !ordered_blocks_.empty() && *first_block() == block_id;\n}\n\nspv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,\n uint32_t type_id) {\n assert(current_block_ == nullptr &&\n \"RegisterFunctionParameter can only be called when parsing the binary \"\n \"ouside of a block\");\n \/\/ TODO(umar): Validate function parameter type order and count\n \/\/ TODO(umar): Use these variables to validate parameter type\n (void)parameter_id;\n (void)type_id;\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterLoopMerge(uint32_t merge_id,\n uint32_t continue_id) {\n RegisterBlock(merge_id, false);\n RegisterBlock(continue_id, false);\n BasicBlock& merge_block = blocks_.at(merge_id);\n BasicBlock& continue_block = blocks_.at(continue_id);\n assert(current_block_ &&\n \"RegisterLoopMerge must be called when called within a block\");\n\n current_block_->set_type(kBlockTypeLoop);\n merge_block.set_type(kBlockTypeMerge);\n continue_block.set_type(kBlockTypeContinue);\n cfg_constructs_.emplace_back(ConstructType::kLoop, current_block_,\n &merge_block);\n Construct& loop_construct = cfg_constructs_.back();\n cfg_constructs_.emplace_back(ConstructType::kContinue, &continue_block);\n Construct& continue_construct = cfg_constructs_.back();\n continue_construct.set_corresponding_constructs({&loop_construct});\n loop_construct.set_corresponding_constructs({&continue_construct});\n\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {\n RegisterBlock(merge_id, false);\n BasicBlock& merge_block = blocks_.at(merge_id);\n current_block_->set_type(kBlockTypeHeader);\n merge_block.set_type(kBlockTypeMerge);\n\n cfg_constructs_.emplace_back(ConstructType::kSelection, current_block(),\n &merge_block);\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {\n assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);\n declaration_type_ = type;\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {\n assert(\n declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&\n \"RegisterBlocks can only be called after declaration_type_ is defined\");\n\n std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;\n bool success = false;\n tie(inserted_block, success) =\n blocks_.insert({block_id, BasicBlock(block_id)});\n if (is_definition) { \/\/ new block definition\n assert(current_block_ == nullptr &&\n \"Register Block can only be called when parsing a binary outside of \"\n \"a BasicBlock\");\n\n undefined_blocks_.erase(block_id);\n current_block_ = &inserted_block->second;\n ordered_blocks_.push_back(current_block_);\n if (IsFirstBlock(block_id)) current_block_->set_reachable(true);\n } else if (success) { \/\/ Block doesn't exsist but this is not a definition\n undefined_blocks_.insert(block_id);\n }\n\n return SPV_SUCCESS;\n}\n\nvoid Function::RegisterBlockEnd(vector<uint32_t> next_list,\n SpvOp branch_instruction) {\n assert(\n current_block_ &&\n \"RegisterBlockEnd can only be called when parsing a binary in a block\");\n\n vector<BasicBlock*> next_blocks;\n next_blocks.reserve(next_list.size());\n\n std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;\n bool success;\n for (uint32_t successor_id : next_list) {\n tie(inserted_block, success) =\n blocks_.insert({successor_id, BasicBlock(successor_id)});\n if (success) {\n undefined_blocks_.insert(successor_id);\n }\n next_blocks.push_back(&inserted_block->second);\n }\n\n current_block_->RegisterBranchInstruction(branch_instruction);\n current_block_->RegisterSuccessors(next_blocks);\n current_block_ = nullptr;\n return;\n}\n\nvoid Function::RegisterFunctionEnd() {\n if (!end_has_been_registered_) {\n end_has_been_registered_ = true;\n\n ComputeAugmentedCFG();\n }\n}\n\nsize_t Function::block_count() const { return blocks_.size(); }\n\nsize_t Function::undefined_block_count() const {\n return undefined_blocks_.size();\n}\n\nconst vector<BasicBlock*>& Function::ordered_blocks() const {\n return ordered_blocks_;\n}\nvector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }\n\nconst BasicBlock* Function::current_block() const { return current_block_; }\nBasicBlock* Function::current_block() { return current_block_; }\n\nconst list<Construct>& Function::constructs() const { return cfg_constructs_; }\nlist<Construct>& Function::constructs() { return cfg_constructs_; }\n\nconst BasicBlock* Function::first_block() const {\n if (ordered_blocks_.empty()) return nullptr;\n return ordered_blocks_[0];\n}\nBasicBlock* Function::first_block() {\n if (ordered_blocks_.empty()) return nullptr;\n return ordered_blocks_[0];\n}\n\nbool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {\n bool ret = false;\n const BasicBlock* block;\n tie(block, ignore) = GetBlock(merge_block_id);\n if (block) {\n ret = block->is_type(type);\n }\n return ret;\n}\n\npair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {\n const auto b = blocks_.find(block_id);\n if (b != end(blocks_)) {\n const BasicBlock* block = &(b->second);\n bool defined =\n undefined_blocks_.find(block->id()) == end(undefined_blocks_);\n return make_pair(block, defined);\n } else {\n return make_pair(nullptr, false);\n }\n}\n\npair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {\n const BasicBlock* out;\n bool defined;\n tie(out, defined) = const_cast<const Function*>(this)->GetBlock(block_id);\n return make_pair(const_cast<BasicBlock*>(out), defined);\n}\n\nFunction::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {\n return [this](const BasicBlock* block) {\n auto where = augmented_successors_map_.find(block);\n return where == augmented_successors_map_.end() ? block->successors()\n : &(*where).second;\n };\n}\n\nFunction::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {\n return [this](const BasicBlock* block) {\n auto where = augmented_predecessors_map_.find(block);\n return where == augmented_predecessors_map_.end() ? block->predecessors()\n : &(*where).second;\n };\n}\n\nvoid Function::ComputeAugmentedCFG() {\n \/\/ Compute the successors of the pseudo-entry block, and\n \/\/ the predecessors of the pseudo exit block.\n auto succ_func = [](const BasicBlock* b) { return b->successors(); };\n auto pred_func = [](const BasicBlock* b) { return b->predecessors(); };\n auto sources = TraversalRoots(ordered_blocks_, succ_func, pred_func);\n auto sinks = TraversalRoots(ordered_blocks_, pred_func, succ_func);\n\n \/\/ Wire up the pseudo entry block.\n augmented_successors_map_[&pseudo_entry_block_] = sources;\n for (auto block : sources) {\n auto& augmented_preds = augmented_predecessors_map_[block];\n const auto& preds = *block->predecessors();\n augmented_preds.reserve(1 + preds.size());\n augmented_preds.push_back(&pseudo_entry_block_);\n augmented_preds.insert(augmented_preds.end(), preds.begin(), preds.end());\n }\n\n \/\/ Wire up the pseudo exit block.\n augmented_predecessors_map_[&pseudo_exit_block_] = sinks;\n for (auto block : sinks) {\n auto& augmented_succ = augmented_successors_map_[block];\n const auto& succ = *block->successors();\n augmented_succ.reserve(1 + succ.size());\n augmented_succ.push_back(&pseudo_exit_block_);\n augmented_succ.insert(augmented_succ.end(), succ.begin(), succ.end());\n }\n};\n} \/\/\/ namespace libspirv\n<commit_msg>Rename a variable so it's consistent with spec<commit_after>\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and\/or associated documentation files (the\n\/\/ \"Materials\"), to deal in the Materials without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Materials, and to\n\/\/ permit persons to whom the Materials are furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Materials.\n\/\/\n\/\/ MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS\n\/\/ KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS\n\/\/ SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT\n\/\/ https:\/\/www.khronos.org\/registry\/\n\/\/\n\/\/ THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n\n#include \"val\/Function.h\"\n\n#include <cassert>\n\n#include <algorithm>\n#include <unordered_set>\n#include <unordered_map>\n#include <utility>\n\n#include \"val\/BasicBlock.h\"\n#include \"val\/Construct.h\"\n#include \"validate.h\"\n\nusing std::ignore;\nusing std::list;\nusing std::make_pair;\nusing std::pair;\nusing std::tie;\nusing std::vector;\n\nnamespace {\n\nusing libspirv::BasicBlock;\n\n\/\/ Computes a minimal set of root nodes required to traverse, in the forward\n\/\/ direction, the CFG represented by the given vector of blocks, and successor\n\/\/ and predecessor functions.\nstd::vector<BasicBlock*> TraversalRoots(const std::vector<BasicBlock*>& blocks,\n libspirv::get_blocks_func succ_func,\n libspirv::get_blocks_func pred_func) {\n \/\/ The set of nodes which have been visited from any of the roots so far.\n std::unordered_set<const BasicBlock*> visited;\n\n auto mark_visited = [&visited](const BasicBlock* b) { visited.insert(b); };\n auto ignore_block = [](const BasicBlock*) {};\n auto ignore_blocks = [](const BasicBlock*, const BasicBlock*) {};\n\n auto traverse_from_root = [&mark_visited, &succ_func, &ignore_block,\n &ignore_blocks](const BasicBlock* entry) {\n DepthFirstTraversal(entry, succ_func, mark_visited, ignore_block,\n ignore_blocks);\n };\n\n std::vector<BasicBlock*> result;\n\n \/\/ First collect nodes without predecessors.\n for (auto block : blocks) {\n if (pred_func(block)->empty()) {\n assert(visited.count(block) == 0 && \"Malformed graph!\");\n result.push_back(block);\n traverse_from_root(block);\n }\n }\n\n \/\/ Now collect other stranded nodes. These must be in unreachable cycles.\n for (auto block : blocks) {\n if (visited.count(block) == 0) {\n result.push_back(block);\n traverse_from_root(block);\n }\n }\n\n return result;\n}\n\n} \/\/ anonymous namespace\n\nnamespace libspirv {\n\n\/\/ Universal Limit of ResultID + 1\nstatic const uint32_t kInvalidId = 0x400000;\n\nFunction::Function(uint32_t function_id, uint32_t result_type_id,\n SpvFunctionControlMask function_control,\n uint32_t function_type_id)\n : id_(function_id),\n function_type_id_(function_type_id),\n result_type_id_(result_type_id),\n function_control_(function_control),\n declaration_type_(FunctionDecl::kFunctionDeclUnknown),\n end_has_been_registered_(false),\n blocks_(),\n current_block_(nullptr),\n pseudo_entry_block_(0),\n pseudo_exit_block_(kInvalidId),\n cfg_constructs_(),\n variable_ids_(),\n parameter_ids_() {}\n\nbool Function::IsFirstBlock(uint32_t block_id) const {\n return !ordered_blocks_.empty() && *first_block() == block_id;\n}\n\nspv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,\n uint32_t type_id) {\n assert(current_block_ == nullptr &&\n \"RegisterFunctionParameter can only be called when parsing the binary \"\n \"ouside of a block\");\n \/\/ TODO(umar): Validate function parameter type order and count\n \/\/ TODO(umar): Use these variables to validate parameter type\n (void)parameter_id;\n (void)type_id;\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterLoopMerge(uint32_t merge_id,\n uint32_t continue_id) {\n RegisterBlock(merge_id, false);\n RegisterBlock(continue_id, false);\n BasicBlock& merge_block = blocks_.at(merge_id);\n BasicBlock& continue_target_block = blocks_.at(continue_id);\n assert(current_block_ &&\n \"RegisterLoopMerge must be called when called within a block\");\n\n current_block_->set_type(kBlockTypeLoop);\n merge_block.set_type(kBlockTypeMerge);\n continue_target_block.set_type(kBlockTypeContinue);\n cfg_constructs_.emplace_back(ConstructType::kLoop, current_block_,\n &merge_block);\n Construct& loop_construct = cfg_constructs_.back();\n cfg_constructs_.emplace_back(ConstructType::kContinue,\n &continue_target_block);\n Construct& continue_construct = cfg_constructs_.back();\n continue_construct.set_corresponding_constructs({&loop_construct});\n loop_construct.set_corresponding_constructs({&continue_construct});\n\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {\n RegisterBlock(merge_id, false);\n BasicBlock& merge_block = blocks_.at(merge_id);\n current_block_->set_type(kBlockTypeHeader);\n merge_block.set_type(kBlockTypeMerge);\n\n cfg_constructs_.emplace_back(ConstructType::kSelection, current_block(),\n &merge_block);\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {\n assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);\n declaration_type_ = type;\n return SPV_SUCCESS;\n}\n\nspv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {\n assert(\n declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&\n \"RegisterBlocks can only be called after declaration_type_ is defined\");\n\n std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;\n bool success = false;\n tie(inserted_block, success) =\n blocks_.insert({block_id, BasicBlock(block_id)});\n if (is_definition) { \/\/ new block definition\n assert(current_block_ == nullptr &&\n \"Register Block can only be called when parsing a binary outside of \"\n \"a BasicBlock\");\n\n undefined_blocks_.erase(block_id);\n current_block_ = &inserted_block->second;\n ordered_blocks_.push_back(current_block_);\n if (IsFirstBlock(block_id)) current_block_->set_reachable(true);\n } else if (success) { \/\/ Block doesn't exsist but this is not a definition\n undefined_blocks_.insert(block_id);\n }\n\n return SPV_SUCCESS;\n}\n\nvoid Function::RegisterBlockEnd(vector<uint32_t> next_list,\n SpvOp branch_instruction) {\n assert(\n current_block_ &&\n \"RegisterBlockEnd can only be called when parsing a binary in a block\");\n\n vector<BasicBlock*> next_blocks;\n next_blocks.reserve(next_list.size());\n\n std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;\n bool success;\n for (uint32_t successor_id : next_list) {\n tie(inserted_block, success) =\n blocks_.insert({successor_id, BasicBlock(successor_id)});\n if (success) {\n undefined_blocks_.insert(successor_id);\n }\n next_blocks.push_back(&inserted_block->second);\n }\n\n current_block_->RegisterBranchInstruction(branch_instruction);\n current_block_->RegisterSuccessors(next_blocks);\n current_block_ = nullptr;\n return;\n}\n\nvoid Function::RegisterFunctionEnd() {\n if (!end_has_been_registered_) {\n end_has_been_registered_ = true;\n\n ComputeAugmentedCFG();\n }\n}\n\nsize_t Function::block_count() const { return blocks_.size(); }\n\nsize_t Function::undefined_block_count() const {\n return undefined_blocks_.size();\n}\n\nconst vector<BasicBlock*>& Function::ordered_blocks() const {\n return ordered_blocks_;\n}\nvector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }\n\nconst BasicBlock* Function::current_block() const { return current_block_; }\nBasicBlock* Function::current_block() { return current_block_; }\n\nconst list<Construct>& Function::constructs() const { return cfg_constructs_; }\nlist<Construct>& Function::constructs() { return cfg_constructs_; }\n\nconst BasicBlock* Function::first_block() const {\n if (ordered_blocks_.empty()) return nullptr;\n return ordered_blocks_[0];\n}\nBasicBlock* Function::first_block() {\n if (ordered_blocks_.empty()) return nullptr;\n return ordered_blocks_[0];\n}\n\nbool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {\n bool ret = false;\n const BasicBlock* block;\n tie(block, ignore) = GetBlock(merge_block_id);\n if (block) {\n ret = block->is_type(type);\n }\n return ret;\n}\n\npair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {\n const auto b = blocks_.find(block_id);\n if (b != end(blocks_)) {\n const BasicBlock* block = &(b->second);\n bool defined =\n undefined_blocks_.find(block->id()) == end(undefined_blocks_);\n return make_pair(block, defined);\n } else {\n return make_pair(nullptr, false);\n }\n}\n\npair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {\n const BasicBlock* out;\n bool defined;\n tie(out, defined) = const_cast<const Function*>(this)->GetBlock(block_id);\n return make_pair(const_cast<BasicBlock*>(out), defined);\n}\n\nFunction::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {\n return [this](const BasicBlock* block) {\n auto where = augmented_successors_map_.find(block);\n return where == augmented_successors_map_.end() ? block->successors()\n : &(*where).second;\n };\n}\n\nFunction::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {\n return [this](const BasicBlock* block) {\n auto where = augmented_predecessors_map_.find(block);\n return where == augmented_predecessors_map_.end() ? block->predecessors()\n : &(*where).second;\n };\n}\n\nvoid Function::ComputeAugmentedCFG() {\n \/\/ Compute the successors of the pseudo-entry block, and\n \/\/ the predecessors of the pseudo exit block.\n auto succ_func = [](const BasicBlock* b) { return b->successors(); };\n auto pred_func = [](const BasicBlock* b) { return b->predecessors(); };\n auto sources = TraversalRoots(ordered_blocks_, succ_func, pred_func);\n auto sinks = TraversalRoots(ordered_blocks_, pred_func, succ_func);\n\n \/\/ Wire up the pseudo entry block.\n augmented_successors_map_[&pseudo_entry_block_] = sources;\n for (auto block : sources) {\n auto& augmented_preds = augmented_predecessors_map_[block];\n const auto& preds = *block->predecessors();\n augmented_preds.reserve(1 + preds.size());\n augmented_preds.push_back(&pseudo_entry_block_);\n augmented_preds.insert(augmented_preds.end(), preds.begin(), preds.end());\n }\n\n \/\/ Wire up the pseudo exit block.\n augmented_predecessors_map_[&pseudo_exit_block_] = sinks;\n for (auto block : sinks) {\n auto& augmented_succ = augmented_successors_map_[block];\n const auto& succ = *block->successors();\n augmented_succ.reserve(1 + succ.size());\n augmented_succ.push_back(&pseudo_exit_block_);\n augmented_succ.insert(augmented_succ.end(), succ.begin(), succ.end());\n }\n};\n} \/\/\/ namespace libspirv\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Runtime.JS project authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"thread.h\"\n#include <kernel\/kernel.h>\n#include <kernel\/thread-manager.h>\n#include <kernel\/mem-manager.h>\n#include <kernel\/engine.h>\n#include <kernel\/engines.h>\n\nnamespace rt {\n\nThread::Thread(ThreadManager* thread_mgr, ResourceHandle<EngineThread> ethread)\n :\tthread_mgr_(thread_mgr),\n type_(ethread.get()->type()),\n iv8_(nullptr),\n tpl_cache_(nullptr),\n stack_(GLOBAL_mem_manager()->virtual_allocator().AllocStack()),\n ethread_(ethread),\n exports_(this),\n ref_count_(0),\n terminate_(false),\n parent_promise_id_(0) {\n priority_.Set(1);\n}\n\nThread::~Thread() {\n \/\/ Can't destroy idle thread\n RT_ASSERT(ThreadType::IDLE != type_);\n\n RT_ASSERT(thread_mgr_);\n RT_ASSERT(this != thread_mgr_->current_thread());\n\n timeout_data_.Clear();\n irq_data_.Clear();\n promises_.Clear();\n\n printf(\"[V8] delete context\\n\");\n context_.Reset();\n args_.Reset();\n exit_value_.Reset();\n call_wrapper_.Reset();\n\n RT_ASSERT(tpl_cache_);\n delete tpl_cache_;\n\n RT_ASSERT(iv8_);\n printf(\"[V8] delete isolate\\n\");\n iv8_->Dispose(); \/\/ This deletes v8 isolate object\n\n \/\/ TODO: delete stack\n}\n\nExternalFunction* FunctionExports::Add(v8::Local<v8::Value> v,\n ResourceHandle<EngineThread> recv) {\n uint32_t index = data_.size();\n RT_ASSERT(thread_);\n v8::Isolate* iv8 { thread_->IsolateV8() };\n RT_ASSERT(iv8);\n size_t export_id = ++export_id_;\n data_.push_back(std::move(FunctionExportData(iv8, v, export_id)));\n return new ExternalFunction(index, export_id, thread_, recv);\n}\n\nv8::Local<v8::Value> FunctionExports::Get(uint32_t index, size_t export_id) {\n RT_ASSERT(thread_);\n v8::Isolate* iv8 { thread_->IsolateV8() };\n\n RT_ASSERT(index < data_.size());\n v8::EscapableHandleScope scope(iv8);\n if (data_[index].export_id() != export_id) {\n return scope.Escape(v8::Local<v8::Value>());\n }\n\n return scope.Escape(data_[index].GetValue(iv8));\n}\n\n\nvoid Thread::SetTimeout(uint32_t timeout_id, uint64_t timeout_ms) {\n uint64_t ticks_now { thread_mgr_->ticks_count() };\n uint64_t when = ticks_now + timeout_ms \/ GLOBAL_engines()->MsPerTick();\n timeouts_.Set(timeout_id, when);\n}\n\nvoid Thread::Init() {\n \/\/ Skip initialization for idle thread\n if (ThreadType::IDLE == type_) {\n return;\n }\n\n RT_ASSERT(nullptr == iv8_);\n RT_ASSERT(nullptr == tpl_cache_);\n iv8_ = v8::Isolate::New();\n iv8_->SetData(0, this);\n printf(\"[V8] new isolate\\n\");\n v8::Locker lock(iv8_);\n v8::Isolate::Scope ivscope(iv8_);\n v8::HandleScope local_handle_scope(iv8_);\n tpl_cache_ = new TemplateCache(iv8_);\n}\n\nvoid Thread::Run() {\n \/\/ Idle thread does nothing\n if (ThreadType::IDLE == type_) {\n return;\n }\n\n RT_ASSERT(iv8_);\n RT_ASSERT(tpl_cache_);\n\n uint64_t ticks_now { thread_mgr_->ticks_count() };\n while (timeouts_.Elapsed(ticks_now)) {\n uint32_t timeout_id { timeouts_.Take() };\n\n {\tstd::unique_ptr<ThreadMessage> msg(new ThreadMessage(\n ThreadMessage::Type::TIMEOUT_EVENT,\n ResourceHandle<EngineThread>(), TransportData(), nullptr, timeout_id));\n ethread_.get()->PushMessage(std::move(msg));\n }\n }\n\n EngineThread::ThreadMessagesVector messages = ethread_.get()->TakeMessages();\n if (0 == messages.size()) {\n return;\n }\n\n v8::Locker lock(iv8_);\n v8::Isolate::Scope ivscope(iv8_);\n v8::HandleScope local_handle_scope(iv8_);\n\n if (context_.IsEmpty()) {\n printf(\"[V8] new context\\n\");\n v8::Local<v8::Context> context = tpl_cache_->NewContext();\n context_ = std::move(v8::UniquePersistent<v8::Context>(iv8_, context));\n }\n\n RT_ASSERT(!context_.IsEmpty());\n v8::Local<v8::Context> context = v8::Local<v8::Context>::New(iv8_, context_);\n v8::Context::Scope cs(context);\n\n v8::TryCatch trycatch;\n\n for (ThreadMessage* message : messages) {\n RT_ASSERT(message);\n\n ThreadMessage::Type type = message->type();\n\n switch (type) {\n case ThreadMessage::Type::SET_ARGUMENTS_NOPARENT: {\n RT_ASSERT(args_.IsEmpty());\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n args_ = std::move(v8::UniquePersistent<v8::Value>(iv8_, unpacked));\n }\n break;\n case ThreadMessage::Type::SET_ARGUMENTS: {\n RT_ASSERT(args_.IsEmpty());\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n args_ = std::move(v8::UniquePersistent<v8::Value>(iv8_, unpacked));\n parent_thread_ = message->sender();\n parent_promise_id_ = message->recv_index();\n }\n break;\n case ThreadMessage::Type::EVALUATE: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::ScriptCompiler::Source source(unpacked->ToString());\n v8::Local<v8::Script> script = v8::ScriptCompiler::Compile(iv8_, &source,\n v8::ScriptCompiler::CompileOptions::kNoCompileOptions);\n if (!script.IsEmpty()) {\n script->Run();\n }\n }\n break;\n case ThreadMessage::Type::FUNCTION_CALL: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n ExternalFunction* efn { message->exported_func() };\n RT_ASSERT(efn);\n\n v8::Local<v8::Value> fnval { exports_.Get(efn->index(), efn->export_id()) };\n if (fnval.IsEmpty()) {\n fnval = v8::Null(iv8_);\n } else {\n RT_ASSERT(fnval->IsFunction());\n }\n\n {\tv8::Local<v8::Function> fnwrap { v8::Local<v8::Function>::New(iv8_, call_wrapper_) };\n v8::Local<v8::Value> argv[] {\n fnval,\n message->sender().NewExternal(iv8_),\n unpacked,\n v8::Uint32::NewFromUnsigned(iv8_, message->recv_index()),\n };\n fnwrap->Call(context->Global(), 4, argv);\n }\n }\n break;\n case ThreadMessage::Type::FUNCTION_RETURN_RESOLVE: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::Local<v8::Promise::Resolver> resolver {\n v8::Local<v8::Promise::Resolver>::New(iv8_, TakePromise(message->recv_index())) };\n\n resolver->Resolve(unpacked);\n iv8_->RunMicrotasks();\n }\n break;\n case ThreadMessage::Type::FUNCTION_RETURN_REJECT: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::Local<v8::Promise::Resolver> resolver {\n v8::Local<v8::Promise::Resolver>::New(iv8_, TakePromise(message->recv_index())) };\n\n resolver->Reject(unpacked);\n iv8_->RunMicrotasks();\n }\n break;\n case ThreadMessage::Type::TIMEOUT_EVENT: {\n v8::Local<v8::Value> fnv { v8::Local<v8::Value>::New(iv8_,\n TakeTimeoutData(message->recv_index())) };\n RT_ASSERT(fnv->IsFunction());\n v8::Local<v8::Function> fn { v8::Local<v8::Function>::Cast(fnv) };\n fn->Call(context->Global(), 0, nullptr);\n }\n break;\n case ThreadMessage::Type::IRQ_RAISE: {\n v8::Local<v8::Value> fnv { v8::Local<v8::Value>::New(iv8_,\n GetIRQData(message->recv_index())) };\n RT_ASSERT(fnv->IsFunction());\n v8::Local<v8::Function> fn { v8::Local<v8::Function>::Cast(fnv) };\n fn->Call(context->Global(), 0, nullptr);\n }\n break;\n case ThreadMessage::Type::EMPTY:\n break;\n default:\n RT_ASSERT(!\"Unknown thread message\");\n break;\n }\n\n if (!message->reusable()) {\n delete message;\n }\n }\n\n if (0 == ref_count_ || terminate_) {\n terminate_ = true;\n printf(\"[ terminate thread ]\\n\");\n auto promise_id = parent_promise_id();\n auto thread = parent_thread();\n\n LockingPtr<EngineThread> lptr { thread.get() };\n Thread* recv { lptr->thread() };\n RT_ASSERT(recv);\n\n TransportData data;\n if (!exit_value_.IsEmpty()) {\n TransportData::SerializeError err { data.MoveValue(this, recv,\n v8::Local<v8::Value>::New(iv8_, exit_value_)) };\n }\n\n {\tstd::unique_ptr<ThreadMessage> msg(new ThreadMessage(\n ThreadMessage::Type::FUNCTION_RETURN_RESOLVE,\n handle(),\n std::move(data), nullptr, promise_id));\n lptr->PushMessage(std::move(msg));\n }\n return;\n }\n\n v8::Local<v8::Value> ex = trycatch.Exception();\n if (!ex.IsEmpty()) {\n\n v8::String::Utf8Value exception_str(ex);\n v8::Local<v8::Message> message = trycatch.Message();\n if (message.IsEmpty()) {\n printf(\"Uncaught exception: %s\\n\", *exception_str);\n } else {\n v8::String::Utf8Value script_name(message->GetScriptResourceName());\n int linenum = message->GetLineNumber();\n printf(\"Uncaught exception: %s:%i: %s\\n\", *script_name, linenum, *exception_str);\n }\n\n v8::String::Utf8Value stack(trycatch.StackTrace());\n if (stack.length() > 0) {\n printf(\"%s\\n\", *stack);\n }\n }\n\n trycatch.Reset();\n}\n\n} \/\/ namespace rt\n<commit_msg>add thread termination reason debug message<commit_after>\/\/ Copyright 2014 Runtime.JS project authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"thread.h\"\n#include <kernel\/kernel.h>\n#include <kernel\/thread-manager.h>\n#include <kernel\/mem-manager.h>\n#include <kernel\/engine.h>\n#include <kernel\/engines.h>\n\nnamespace rt {\n\nThread::Thread(ThreadManager* thread_mgr, ResourceHandle<EngineThread> ethread)\n :\tthread_mgr_(thread_mgr),\n type_(ethread.get()->type()),\n iv8_(nullptr),\n tpl_cache_(nullptr),\n stack_(GLOBAL_mem_manager()->virtual_allocator().AllocStack()),\n ethread_(ethread),\n exports_(this),\n ref_count_(0),\n terminate_(false),\n parent_promise_id_(0) {\n priority_.Set(1);\n}\n\nThread::~Thread() {\n \/\/ Can't destroy idle thread\n RT_ASSERT(ThreadType::IDLE != type_);\n\n RT_ASSERT(thread_mgr_);\n RT_ASSERT(this != thread_mgr_->current_thread());\n\n timeout_data_.Clear();\n irq_data_.Clear();\n promises_.Clear();\n\n printf(\"[V8] delete context\\n\");\n context_.Reset();\n args_.Reset();\n exit_value_.Reset();\n call_wrapper_.Reset();\n\n RT_ASSERT(tpl_cache_);\n delete tpl_cache_;\n\n RT_ASSERT(iv8_);\n printf(\"[V8] delete isolate\\n\");\n iv8_->Dispose(); \/\/ This deletes v8 isolate object\n\n \/\/ TODO: delete stack\n}\n\nExternalFunction* FunctionExports::Add(v8::Local<v8::Value> v,\n ResourceHandle<EngineThread> recv) {\n uint32_t index = data_.size();\n RT_ASSERT(thread_);\n v8::Isolate* iv8 { thread_->IsolateV8() };\n RT_ASSERT(iv8);\n size_t export_id = ++export_id_;\n data_.push_back(std::move(FunctionExportData(iv8, v, export_id)));\n return new ExternalFunction(index, export_id, thread_, recv);\n}\n\nv8::Local<v8::Value> FunctionExports::Get(uint32_t index, size_t export_id) {\n RT_ASSERT(thread_);\n v8::Isolate* iv8 { thread_->IsolateV8() };\n\n RT_ASSERT(index < data_.size());\n v8::EscapableHandleScope scope(iv8);\n if (data_[index].export_id() != export_id) {\n return scope.Escape(v8::Local<v8::Value>());\n }\n\n return scope.Escape(data_[index].GetValue(iv8));\n}\n\n\nvoid Thread::SetTimeout(uint32_t timeout_id, uint64_t timeout_ms) {\n uint64_t ticks_now { thread_mgr_->ticks_count() };\n uint64_t when = ticks_now + timeout_ms \/ GLOBAL_engines()->MsPerTick();\n timeouts_.Set(timeout_id, when);\n}\n\nvoid Thread::Init() {\n \/\/ Skip initialization for idle thread\n if (ThreadType::IDLE == type_) {\n return;\n }\n\n RT_ASSERT(nullptr == iv8_);\n RT_ASSERT(nullptr == tpl_cache_);\n iv8_ = v8::Isolate::New();\n iv8_->SetData(0, this);\n printf(\"[V8] new isolate\\n\");\n v8::Locker lock(iv8_);\n v8::Isolate::Scope ivscope(iv8_);\n v8::HandleScope local_handle_scope(iv8_);\n tpl_cache_ = new TemplateCache(iv8_);\n}\n\nvoid Thread::Run() {\n \/\/ Idle thread does nothing\n if (ThreadType::IDLE == type_) {\n return;\n }\n\n RT_ASSERT(iv8_);\n RT_ASSERT(tpl_cache_);\n\n uint64_t ticks_now { thread_mgr_->ticks_count() };\n while (timeouts_.Elapsed(ticks_now)) {\n uint32_t timeout_id { timeouts_.Take() };\n\n {\tstd::unique_ptr<ThreadMessage> msg(new ThreadMessage(\n ThreadMessage::Type::TIMEOUT_EVENT,\n ResourceHandle<EngineThread>(), TransportData(), nullptr, timeout_id));\n ethread_.get()->PushMessage(std::move(msg));\n }\n }\n\n EngineThread::ThreadMessagesVector messages = ethread_.get()->TakeMessages();\n if (0 == messages.size()) {\n return;\n }\n\n v8::Locker lock(iv8_);\n v8::Isolate::Scope ivscope(iv8_);\n v8::HandleScope local_handle_scope(iv8_);\n\n if (context_.IsEmpty()) {\n printf(\"[V8] new context\\n\");\n v8::Local<v8::Context> context = tpl_cache_->NewContext();\n context_ = std::move(v8::UniquePersistent<v8::Context>(iv8_, context));\n }\n\n RT_ASSERT(!context_.IsEmpty());\n v8::Local<v8::Context> context = v8::Local<v8::Context>::New(iv8_, context_);\n v8::Context::Scope cs(context);\n\n v8::TryCatch trycatch;\n\n for (ThreadMessage* message : messages) {\n RT_ASSERT(message);\n\n ThreadMessage::Type type = message->type();\n\n switch (type) {\n case ThreadMessage::Type::SET_ARGUMENTS_NOPARENT: {\n RT_ASSERT(args_.IsEmpty());\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n args_ = std::move(v8::UniquePersistent<v8::Value>(iv8_, unpacked));\n }\n break;\n case ThreadMessage::Type::SET_ARGUMENTS: {\n RT_ASSERT(args_.IsEmpty());\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n args_ = std::move(v8::UniquePersistent<v8::Value>(iv8_, unpacked));\n parent_thread_ = message->sender();\n parent_promise_id_ = message->recv_index();\n }\n break;\n case ThreadMessage::Type::EVALUATE: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::ScriptCompiler::Source source(unpacked->ToString());\n v8::Local<v8::Script> script = v8::ScriptCompiler::Compile(iv8_, &source,\n v8::ScriptCompiler::CompileOptions::kNoCompileOptions);\n if (!script.IsEmpty()) {\n script->Run();\n }\n }\n break;\n case ThreadMessage::Type::FUNCTION_CALL: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n ExternalFunction* efn { message->exported_func() };\n RT_ASSERT(efn);\n\n v8::Local<v8::Value> fnval { exports_.Get(efn->index(), efn->export_id()) };\n if (fnval.IsEmpty()) {\n fnval = v8::Null(iv8_);\n } else {\n RT_ASSERT(fnval->IsFunction());\n }\n\n {\tv8::Local<v8::Function> fnwrap { v8::Local<v8::Function>::New(iv8_, call_wrapper_) };\n v8::Local<v8::Value> argv[] {\n fnval,\n message->sender().NewExternal(iv8_),\n unpacked,\n v8::Uint32::NewFromUnsigned(iv8_, message->recv_index()),\n };\n fnwrap->Call(context->Global(), 4, argv);\n }\n }\n break;\n case ThreadMessage::Type::FUNCTION_RETURN_RESOLVE: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::Local<v8::Promise::Resolver> resolver {\n v8::Local<v8::Promise::Resolver>::New(iv8_, TakePromise(message->recv_index())) };\n\n resolver->Resolve(unpacked);\n iv8_->RunMicrotasks();\n }\n break;\n case ThreadMessage::Type::FUNCTION_RETURN_REJECT: {\n v8::Local<v8::Value> unpacked { message->data().Unpack(this) };\n RT_ASSERT(!unpacked.IsEmpty());\n\n v8::Local<v8::Promise::Resolver> resolver {\n v8::Local<v8::Promise::Resolver>::New(iv8_, TakePromise(message->recv_index())) };\n\n resolver->Reject(unpacked);\n iv8_->RunMicrotasks();\n }\n break;\n case ThreadMessage::Type::TIMEOUT_EVENT: {\n v8::Local<v8::Value> fnv { v8::Local<v8::Value>::New(iv8_,\n TakeTimeoutData(message->recv_index())) };\n RT_ASSERT(fnv->IsFunction());\n v8::Local<v8::Function> fn { v8::Local<v8::Function>::Cast(fnv) };\n fn->Call(context->Global(), 0, nullptr);\n }\n break;\n case ThreadMessage::Type::IRQ_RAISE: {\n v8::Local<v8::Value> fnv { v8::Local<v8::Value>::New(iv8_,\n GetIRQData(message->recv_index())) };\n RT_ASSERT(fnv->IsFunction());\n v8::Local<v8::Function> fn { v8::Local<v8::Function>::Cast(fnv) };\n fn->Call(context->Global(), 0, nullptr);\n }\n break;\n case ThreadMessage::Type::EMPTY:\n break;\n default:\n RT_ASSERT(!\"Unknown thread message\");\n break;\n }\n\n if (!message->reusable()) {\n delete message;\n }\n }\n\n if (0 == ref_count_ || terminate_) {\n if (terminate_) {\n printf(\"[ terminate thread (reason: runtime.exit() called) ]\\n\");\n } else {\n printf(\"[ terminate thread (reason: refcount 0) ]\\n\");\n }\n\n terminate_ = true;\n auto promise_id = parent_promise_id();\n auto thread = parent_thread();\n\n LockingPtr<EngineThread> lptr { thread.get() };\n Thread* recv { lptr->thread() };\n RT_ASSERT(recv);\n\n TransportData data;\n if (!exit_value_.IsEmpty()) {\n TransportData::SerializeError err { data.MoveValue(this, recv,\n v8::Local<v8::Value>::New(iv8_, exit_value_)) };\n }\n\n {\tstd::unique_ptr<ThreadMessage> msg(new ThreadMessage(\n ThreadMessage::Type::FUNCTION_RETURN_RESOLVE,\n handle(),\n std::move(data), nullptr, promise_id));\n lptr->PushMessage(std::move(msg));\n }\n return;\n }\n\n v8::Local<v8::Value> ex = trycatch.Exception();\n if (!ex.IsEmpty()) {\n\n v8::String::Utf8Value exception_str(ex);\n v8::Local<v8::Message> message = trycatch.Message();\n if (message.IsEmpty()) {\n printf(\"Uncaught exception: %s\\n\", *exception_str);\n } else {\n v8::String::Utf8Value script_name(message->GetScriptResourceName());\n int linenum = message->GetLineNumber();\n printf(\"Uncaught exception: %s:%i: %s\\n\", *script_name, linenum, *exception_str);\n }\n\n v8::String::Utf8Value stack(trycatch.StackTrace());\n if (stack.length() > 0) {\n printf(\"%s\\n\", *stack);\n }\n }\n\n trycatch.Reset();\n}\n\n} \/\/ namespace rt\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Movie.cpp\n *\n * Created on: Sep 25, 2009\n * Author: travel\n *\/\n\n#include \"Movie.hpp\"\n#include \"..\/io\/imageio.hpp\"\n#include \"..\/include\/default_params.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n#include <errno.h>\n\/\/#include <iostream>\n\nnamespace PV {\n\nMovie::Movie() {\n initialize_base();\n}\n\nMovie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames) {\n initialize_base();\n initialize(name, hc, fileOfFileNames, DISPLAY_PERIOD);\n}\n\nMovie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {\n initialize_base();\n initialize(name, hc, fileOfFileNames, defaultDisplayPeriod);\n}\n\nint Movie::initialize_base() {\n movieOutputPath = NULL;\n skipFrameIndex = 0;\n echoFramePathnameFlag = false;\n filename = NULL;\n displayPeriod = DISPLAY_PERIOD;\n readPvpFile = false;\n fileOfFileNames = NULL;\n frameNumber = 0;\n numFrames = 0;\n newImageFlag = false;\n return PV_SUCCESS;\n}\n\nint Movie::checkpointRead(const char * cpDir, double * timef){\n Image::checkpointRead(cpDir, timef);\n\n if (this->useParamsImage) { \/\/Sets nextDisplayTime = simulationtime (i.e. effectively restarting)\n nextDisplayTime += parent->simulationTime();\n }\n\n return PV_SUCCESS;\n}\n\n\/\/\n\/*\n * Notes:\n * - writeImages, offsetX, offsetY are initialized by Image::initialize()\n *\/\nint Movie::initialize(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {\n displayPeriod = defaultDisplayPeriod; \/\/ Will be replaced with params value when setParams is called.\n int status = Image::initialize(name, hc, NULL);\n if (status != PV_SUCCESS) {\n fprintf(stderr, \"Image::initialize failed on Movie layer \\\"%s\\\". Exiting.\\n\", name);\n exit(PV_FAILURE);\n }\n\n if (fileOfFileNames != NULL) {\n this->fileOfFileNames = strdup(fileOfFileNames);\n if (this->fileOfFileNames==NULL) {\n fprintf(stderr, \"Movie::initialize error in layer \\\"%s\\\": unable to copy fileOfFileNames: %s\\n\", name, strerror(errno));\n }\n }\n\n PVParams * params = hc->parameters();\n\n assert(!params->presentAndNotBeenRead(name, \"displayPeriod\"));\n nextDisplayTime = hc->simulationTime() + displayPeriod;\n\n assert(!params->presentAndNotBeenRead(name, \"randomMovie\")); \/\/ randomMovie should have been set in setParams\n if (randomMovie) return status; \/\/ Nothing else to be done until data buffer is allocated, in allocateDataStructures\n\n assert(!params->presentAndNotBeenRead(name, \"readPvpFile\")); \/\/ readPvpFile should have been set in setParams\n\n \/\/If not pvp file, open fileOfFileNames \n if( getParent()->icCommunicator()->commRank()==0 && !readPvpFile) {\n filenamestream = PV_fopen(fileOfFileNames, \"r\");\n if( filenamestream == NULL ) {\n fprintf(stderr, \"Movie::initialize error opening \\\"%s\\\": %s\\n\", fileOfFileNames, strerror(errno));\n abort();\n }\n }\n\n if (!randomMovie) {\n if(readPvpFile){\n \/\/Set filename as param\n filename = strdup(fileOfFileNames);\n assert(filename != NULL);\n \/\/One indexed start_frame_index needs to be translated to zero indexed pvp file\n if (startFrameIndex <= 1){\n frameNumber = 0;\n }\n else{\n frameNumber = startFrameIndex - 1;\n }\n \/\/Grab number of frames from header\n PV_Stream * pvstream = NULL;\n if (getParent()->icCommunicator()->commRank()==0) {\n pvstream = PV::PV_fopen(filename, \"rb\");\n }\n int numParams = NUM_PAR_BYTE_PARAMS;\n int params[numParams];\n pvp_read_header(pvstream, getParent()->icCommunicator(), params, &numParams);\n PV::PV_fclose(pvstream); pvstream = NULL;\n if(numParams != NUM_PAR_BYTE_PARAMS || params[INDEX_FILE_TYPE] != PVP_NONSPIKING_ACT_FILE_TYPE) {\n fprintf(stderr, \"Movie layer \\\"%s\\\" error: file \\\"%s\\\" is not a nonspiking-activity pvp file.\\n\", name, filename);\n abort();\n }\n numFrames = params[INDEX_NBANDS];\n }\n else{\n \/\/ echoFramePathnameFlag = params->value(name,\"echoFramePathnameFlag\", false);\n filename = strdup(getNextFileName(startFrameIndex));\n assert(filename != NULL);\n }\n }\n\n \/\/ getImageInfo\/constrainOffsets\/readImage calls moved to Movie::allocateDataStructures\n\n \/\/ set output path for movie frames\n if(writeImages){\n \/\/ if ( params->stringPresent(name, \"movieOutputPath\") ) {\n \/\/ movieOutputPath = strdup(params->stringValue(name, \"movieOutputPath\"));\n \/\/ assert(movieOutputPath != NULL);\n \/\/ }\n \/\/ else {\n \/\/ movieOutputPath = strdup( hc->getOutputPath());\n \/\/ assert(movieOutputPath != NULL);\n \/\/ printf(\"movieOutputPath is not specified in params file.\\n\"\n \/\/ \"movieOutputPath set to default \\\"%s\\\"\\n\",movieOutputPath);\n \/\/ }\n status = parent->ensureDirExists(movieOutputPath);\n }\n\n return PV_SUCCESS;\n}\n\nint Movie::setParams(PVParams * params) {\n int status = Image::setParams(params);\n displayPeriod = params->value(name,\"displayPeriod\", displayPeriod);\n randomMovie = (int) params->value(name,\"randomMovie\",0);\n if (randomMovie) {\n randomMovieProb = params->value(name,\"randomMovieProb\", 0.05); \/\/ 100 Hz\n }\n else {\n readPvpFile = (bool)params->value(name, \"readPvpFile\", 0);\n if (!readPvpFile) {\n echoFramePathnameFlag = params->value(name,\"echoFramePathnameFlag\", false);\n }\n startFrameIndex = params->value(name,\"start_frame_index\", 0);\n skipFrameIndex = params->value(name,\"skip_frame_index\", 0);\n autoResizeFlag = (bool)params->value(name,\"autoResizeFlag\",false);\n }\n assert(!params->presentAndNotBeenRead(name, \"writeImages\"));\n if(writeImages){\n if ( params->stringPresent(name, \"movieOutputPath\") ) {\n movieOutputPath = strdup(params->stringValue(name, \"movieOutputPath\"));\n assert(movieOutputPath != NULL);\n }\n else {\n movieOutputPath = strdup( parent->getOutputPath());\n assert(movieOutputPath != NULL);\n printf(\"movieOutputPath is not specified in params file.\\n\"\n \"movieOutputPath set to default \\\"%s\\\"\\n\",movieOutputPath);\n }\n }\n return status;\n}\n\nMovie::~Movie()\n{\n if (imageData != NULL) {\n delete imageData;\n imageData = NULL;\n }\n if (getParent()->icCommunicator()->commRank()==0 && filenamestream != NULL && filenamestream->isfile) {\n PV_fclose(filenamestream);\n }\n free(fileOfFileNames); fileOfFileNames = NULL;\n}\n\nint Movie::allocateDataStructures() {\n int status = Image::allocateDataStructures();\n\n if (!randomMovie) {\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"start_frame_index\"));\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"skip_frame_index\"));\n \/\/ skip to start_frame_index if provided\n \/\/ int start_frame_index = params->value(name,\"start_frame_index\", 0);\n \/\/ skipFrameIndex = params->value(name,\"skip_frame_index\", 0);\n\n \/\/ get size info from image so that data buffer can be allocated\n GDALColorInterp * colorbandtypes = NULL;\n status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);\n if(status != 0) {\n fprintf(stderr, \"Movie: Unable to get image info for \\\"%s\\\"\\n\", filename);\n abort();\n }\n\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"autoResizeFlag\"));\n if (!autoResizeFlag){\n constrainOffsets(); \/\/ ensure that offsets keep loc within image bounds\n }\n\n status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);\n assert(status == PV_SUCCESS);\n\n free(colorbandtypes); colorbandtypes = NULL;\n }\n else {\n status = randomFrame();\n }\n\n \/\/ exchange border information\n exchange();\n\n newImageFlag = true;\n return status;\n}\n\npvdata_t * Movie::getImageBuffer()\n{\n \/\/ return imageData;\n return data;\n}\n\nPVLayerLoc Movie::getImageLoc()\n{\n return imageLoc;\n \/\/ return clayer->loc;\n \/\/ imageLoc contains size information of the image file being loaded;\n \/\/ clayer->loc contains size information of the layer, which may\n \/\/ be smaller than the whole image. To get information on the layer, use\n \/\/ getLayerLoc(). --pete 2011-07-10\n}\n\nint Movie::updateState(double time, double dt)\n{\n updateImage(time, dt);\n return 0;\n}\n\n\/**\n * - Update the image buffers\n * - If the time is a multiple of biasChangetime then the position of the bias (biasX, biasY) changes.\n * - With probability persistenceProb the offset position (offsetX, offsetY) remains unchanged.\n * - Otherwise, with probability (1-persistenceProb) the offset position performs a random walk\n * around the bias position (biasX, biasY).\n *\n * - If the time is a multiple of displayPeriod then load the next image.\n * - If nf=1 then the image is converted to grayscale during the call to read(filename, offsetX, offsetY).\n * If nf>1 then the image is loaded with color information preserved.\n * - Return true if buffers have changed\n *\/\nbool Movie::updateImage(double time, double dt)\n{\n InterColComm * icComm = getParent()->icCommunicator();\n if(randomMovie){\n randomFrame();\n lastUpdateTime = time;\n } else {\n bool needNewImage = false;\n while (time >= nextDisplayTime) {\n needNewImage = true;\n if (readPvpFile){\n \/\/If set to 0 or 1, normal frame\n if (skipFrameIndex <= 1){\n frameNumber += 1;\n }\n \/\/Otherwise, skip based on skipFrameIndex\n else{\n frameNumber += skipFrameIndex;\n }\n \/\/Loop when frame number reaches numFrames\n if (frameNumber >= numFrames){\n if( icComm->commRank()==0 ) {\n fprintf(stderr, \"Movie %s: EOF reached, rewinding file \\\"%s\\\"\\n\", name, filename);\n }\n frameNumber = 0;\n }\n }\n else{\n if (filename != NULL) free(filename);\n filename = strdup(getNextFileName(skipFrameIndex));\n assert(filename != NULL);\n }\n nextDisplayTime += displayPeriod;\n\n if(writePosition && parent->icCommunicator()->commRank()==0){\n fprintf(fp_pos->fp,\"%f %s: \\n\",time,filename);\n }\n lastUpdateTime = time;\n } \/\/ time >= nextDisplayTime\n\n if( jitterFlag ) {\n bool jittered = jitter();\n needNewImage |= jittered;\n } \/\/ jitterFlag\n\n if( needNewImage ){\n GDALColorInterp * colorbandtypes = NULL;\n int status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);\n if( status != PV_SUCCESS ) {\n fprintf(stderr, \"Movie %s: Error getting image info \\\"%s\\\"\\n\", name, filename);\n abort();\n }\n \/\/Set frame number (member variable in Image)\n if( status == PV_SUCCESS ) status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);\n free(colorbandtypes); colorbandtypes = NULL;\n if( status != PV_SUCCESS ) {\n fprintf(stderr, \"Movie %s: Error reading file \\\"%s\\\"\\n\", name, filename);\n abort();\n }\n newImageFlag = true;\n }\n else{\n newImageFlag = false;\n }\n } \/\/ randomMovie\n\n \/\/ exchange border information\n exchange();\n\n return true;\n}\n\n\/**\n * When we play a random frame - in order to perform a reverse correlation analysis -\n * we call writeActivitySparse(time) in order to write the \"activity\" in the image.\n *\n *\/\nint Movie::outputState(double time, bool last)\n{\n if (writeImages) {\n char basicFilename[PV_PATH_MAX + 1];\n snprintf(basicFilename, PV_PATH_MAX, \"%s\/Movie_%.2f.%s\", movieOutputPath, time, writeImagesExtension);\n write(basicFilename);\n }\n\n int status = PV_SUCCESS;\n if (randomMovie != 0) {\n status = writeActivitySparse(time);\n }\n else {\n status = HyPerLayer::outputState(time, last);\n }\n\n return status;\n}\n\nint Movie::copyReducedImagePortion()\n{\n const PVLayerLoc * loc = getLayerLoc();\n\n const int nx = loc->nx;\n const int ny = loc->ny;\n\n const int nx0 = imageLoc.nx;\n const int ny0 = imageLoc.ny;\n\n assert(nx0 <= nx);\n assert(ny0 <= ny);\n\n const int i0 = nx\/2 - nx0\/2;\n const int j0 = ny\/2 - ny0\/2;\n\n int ii = 0;\n for (int j = j0; j < j0+ny0; j++) {\n for (int i = i0; i < i0+nx0; i++) {\n imageData[ii++] = data[i+nx*j];\n }\n }\n\n return 0;\n}\n\n\/**\n * This creates a random image patch (frame) that is used to perform a reverse correlation analysis\n * as the input signal propagates up the visual system's hierarchy.\n * NOTE: Check Image::toGrayScale() method which was the inspiration for this routine\n *\/\nint Movie::randomFrame()\n{\n assert(randomMovie); \/\/ randomMovieProb was set only if randomMovie is true\n for (int kex = 0; kex < clayer->numExtended; kex++) {\n double p = uniformRand01(&rand_state);\n data[kex] = (p < randomMovieProb) ? 1: 0;\n }\n return 0;\n}\n\n\/\/ skip n_skip lines before reading next frame\nconst char * Movie::getNextFileName(int n_skip)\n{\n for (int i_skip = 0; i_skip < n_skip-1; i_skip++){\n getNextFileName();\n }\n return getNextFileName();\n}\n\n\nconst char * Movie::getNextFileName()\n{\n InterColComm * icComm = getParent()->icCommunicator();\n if( icComm->commRank()==0 ) {\n int c;\n size_t len = PV_PATH_MAX;\n\n \/\/TODO: add recovery procedure to handle case where access to file is temporarily unavailable\n \/\/ use stat to verify status of filepointer, keep running tally of current frame index so that file can be reopened and advanced to current frame\n\n\n \/\/ if at end of file (EOF), rewind\n if ((c = fgetc(filenamestream->fp)) == EOF) {\n PV_fseek(filenamestream, 0L, SEEK_SET);\n fprintf(stderr, \"Movie %s: EOF reached, rewinding file \\\"%s\\\"\\n\", name, filename);\n }\n else {\n ungetc(c, filenamestream->fp);\n }\n\n char * path = fgets(inputfile, len, filenamestream->fp);\n if (path) {\n filenamestream->filepos += strlen(path)+1;\n }\n\n if (echoFramePathnameFlag){\n fprintf(stderr, \"%s\", path);\n }\n\n\n if (path != NULL) {\n path[PV_PATH_MAX-1] = '\\0';\n len = strlen(path);\n if (len > 1) {\n if (path[len-1] == '\\n') {\n path[len-1] = '\\0';\n }\n }\n }\n }\n#ifdef PV_USE_MPI\n MPI_Bcast(inputfile, PV_PATH_MAX, MPI_CHAR, 0, icComm->communicator());\n#endif \/\/ PV_USE_MPI\n return inputfile;\n}\n\nbool Movie::getNewImageFlag(){\n return newImageFlag;\n}\n\nconst char * Movie::getCurrentImage(){\n return inputfile;\n}\n\n}\n<commit_msg>Bugfix: filenamestream pointer in Movie was not getting initialized to NULL <commit_after>\/*\n * Movie.cpp\n *\n * Created on: Sep 25, 2009\n * Author: travel\n *\/\n\n#include \"Movie.hpp\"\n#include \"..\/io\/imageio.hpp\"\n#include \"..\/include\/default_params.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n#include <errno.h>\n\/\/#include <iostream>\n\nnamespace PV {\n\nMovie::Movie() {\n initialize_base();\n}\n\nMovie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames) {\n initialize_base();\n initialize(name, hc, fileOfFileNames, DISPLAY_PERIOD);\n}\n\nMovie::Movie(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {\n initialize_base();\n initialize(name, hc, fileOfFileNames, defaultDisplayPeriod);\n}\n\nint Movie::initialize_base() {\n movieOutputPath = NULL;\n skipFrameIndex = 0;\n echoFramePathnameFlag = false;\n filenamestream = NULL;\n displayPeriod = DISPLAY_PERIOD;\n readPvpFile = false;\n fileOfFileNames = NULL;\n frameNumber = 0;\n numFrames = 0;\n newImageFlag = false;\n return PV_SUCCESS;\n}\n\nint Movie::checkpointRead(const char * cpDir, double * timef){\n Image::checkpointRead(cpDir, timef);\n\n if (this->useParamsImage) { \/\/Sets nextDisplayTime = simulationtime (i.e. effectively restarting)\n nextDisplayTime += parent->simulationTime();\n }\n\n return PV_SUCCESS;\n}\n\n\/\/\n\/*\n * Notes:\n * - writeImages, offsetX, offsetY are initialized by Image::initialize()\n *\/\nint Movie::initialize(const char * name, HyPerCol * hc, const char * fileOfFileNames, float defaultDisplayPeriod) {\n displayPeriod = defaultDisplayPeriod; \/\/ Will be replaced with params value when setParams is called.\n int status = Image::initialize(name, hc, NULL);\n if (status != PV_SUCCESS) {\n fprintf(stderr, \"Image::initialize failed on Movie layer \\\"%s\\\". Exiting.\\n\", name);\n exit(PV_FAILURE);\n }\n\n if (fileOfFileNames != NULL) {\n this->fileOfFileNames = strdup(fileOfFileNames);\n if (this->fileOfFileNames==NULL) {\n fprintf(stderr, \"Movie::initialize error in layer \\\"%s\\\": unable to copy fileOfFileNames: %s\\n\", name, strerror(errno));\n }\n }\n\n PVParams * params = hc->parameters();\n\n assert(!params->presentAndNotBeenRead(name, \"displayPeriod\"));\n nextDisplayTime = hc->simulationTime() + displayPeriod;\n\n assert(!params->presentAndNotBeenRead(name, \"randomMovie\")); \/\/ randomMovie should have been set in setParams\n if (randomMovie) return status; \/\/ Nothing else to be done until data buffer is allocated, in allocateDataStructures\n\n assert(!params->presentAndNotBeenRead(name, \"readPvpFile\")); \/\/ readPvpFile should have been set in setParams\n\n \/\/If not pvp file, open fileOfFileNames \n if( getParent()->icCommunicator()->commRank()==0 && !readPvpFile) {\n filenamestream = PV_fopen(fileOfFileNames, \"r\");\n if( filenamestream == NULL ) {\n fprintf(stderr, \"Movie::initialize error opening \\\"%s\\\": %s\\n\", fileOfFileNames, strerror(errno));\n abort();\n }\n }\n\n if (!randomMovie) {\n if(readPvpFile){\n \/\/Set filename as param\n filename = strdup(fileOfFileNames);\n assert(filename != NULL);\n \/\/One indexed start_frame_index needs to be translated to zero indexed pvp file\n if (startFrameIndex <= 1){\n frameNumber = 0;\n }\n else{\n frameNumber = startFrameIndex - 1;\n }\n \/\/Grab number of frames from header\n PV_Stream * pvstream = NULL;\n if (getParent()->icCommunicator()->commRank()==0) {\n pvstream = PV::PV_fopen(filename, \"rb\");\n }\n int numParams = NUM_PAR_BYTE_PARAMS;\n int params[numParams];\n pvp_read_header(pvstream, getParent()->icCommunicator(), params, &numParams);\n PV::PV_fclose(pvstream); pvstream = NULL;\n if(numParams != NUM_PAR_BYTE_PARAMS || params[INDEX_FILE_TYPE] != PVP_NONSPIKING_ACT_FILE_TYPE) {\n fprintf(stderr, \"Movie layer \\\"%s\\\" error: file \\\"%s\\\" is not a nonspiking-activity pvp file.\\n\", name, filename);\n abort();\n }\n numFrames = params[INDEX_NBANDS];\n }\n else{\n \/\/ echoFramePathnameFlag = params->value(name,\"echoFramePathnameFlag\", false);\n filename = strdup(getNextFileName(startFrameIndex));\n assert(filename != NULL);\n }\n }\n\n \/\/ getImageInfo\/constrainOffsets\/readImage calls moved to Movie::allocateDataStructures\n\n \/\/ set output path for movie frames\n if(writeImages){\n \/\/ if ( params->stringPresent(name, \"movieOutputPath\") ) {\n \/\/ movieOutputPath = strdup(params->stringValue(name, \"movieOutputPath\"));\n \/\/ assert(movieOutputPath != NULL);\n \/\/ }\n \/\/ else {\n \/\/ movieOutputPath = strdup( hc->getOutputPath());\n \/\/ assert(movieOutputPath != NULL);\n \/\/ printf(\"movieOutputPath is not specified in params file.\\n\"\n \/\/ \"movieOutputPath set to default \\\"%s\\\"\\n\",movieOutputPath);\n \/\/ }\n status = parent->ensureDirExists(movieOutputPath);\n }\n\n return PV_SUCCESS;\n}\n\nint Movie::setParams(PVParams * params) {\n int status = Image::setParams(params);\n displayPeriod = params->value(name,\"displayPeriod\", displayPeriod);\n randomMovie = (int) params->value(name,\"randomMovie\",0);\n if (randomMovie) {\n randomMovieProb = params->value(name,\"randomMovieProb\", 0.05); \/\/ 100 Hz\n }\n else {\n readPvpFile = (bool)params->value(name, \"readPvpFile\", 0);\n if (!readPvpFile) {\n echoFramePathnameFlag = params->value(name,\"echoFramePathnameFlag\", false);\n }\n startFrameIndex = params->value(name,\"start_frame_index\", 0);\n skipFrameIndex = params->value(name,\"skip_frame_index\", 0);\n autoResizeFlag = (bool)params->value(name,\"autoResizeFlag\",false);\n }\n assert(!params->presentAndNotBeenRead(name, \"writeImages\"));\n if(writeImages){\n if ( params->stringPresent(name, \"movieOutputPath\") ) {\n movieOutputPath = strdup(params->stringValue(name, \"movieOutputPath\"));\n assert(movieOutputPath != NULL);\n }\n else {\n movieOutputPath = strdup( parent->getOutputPath());\n assert(movieOutputPath != NULL);\n printf(\"movieOutputPath is not specified in params file.\\n\"\n \"movieOutputPath set to default \\\"%s\\\"\\n\",movieOutputPath);\n }\n }\n return status;\n}\n\nMovie::~Movie()\n{\n if (imageData != NULL) {\n delete imageData;\n imageData = NULL;\n }\n if (getParent()->icCommunicator()->commRank()==0 && filenamestream != NULL && filenamestream->isfile) {\n PV_fclose(filenamestream);\n }\n free(fileOfFileNames); fileOfFileNames = NULL;\n}\n\nint Movie::allocateDataStructures() {\n int status = Image::allocateDataStructures();\n\n if (!randomMovie) {\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"start_frame_index\"));\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"skip_frame_index\"));\n \/\/ skip to start_frame_index if provided\n \/\/ int start_frame_index = params->value(name,\"start_frame_index\", 0);\n \/\/ skipFrameIndex = params->value(name,\"skip_frame_index\", 0);\n\n \/\/ get size info from image so that data buffer can be allocated\n GDALColorInterp * colorbandtypes = NULL;\n status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);\n if(status != 0) {\n fprintf(stderr, \"Movie: Unable to get image info for \\\"%s\\\"\\n\", filename);\n abort();\n }\n\n assert(!parent->parameters()->presentAndNotBeenRead(name, \"autoResizeFlag\"));\n if (!autoResizeFlag){\n constrainOffsets(); \/\/ ensure that offsets keep loc within image bounds\n }\n\n status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);\n assert(status == PV_SUCCESS);\n\n free(colorbandtypes); colorbandtypes = NULL;\n }\n else {\n status = randomFrame();\n }\n\n \/\/ exchange border information\n exchange();\n\n newImageFlag = true;\n return status;\n}\n\npvdata_t * Movie::getImageBuffer()\n{\n \/\/ return imageData;\n return data;\n}\n\nPVLayerLoc Movie::getImageLoc()\n{\n return imageLoc;\n \/\/ return clayer->loc;\n \/\/ imageLoc contains size information of the image file being loaded;\n \/\/ clayer->loc contains size information of the layer, which may\n \/\/ be smaller than the whole image. To get information on the layer, use\n \/\/ getLayerLoc(). --pete 2011-07-10\n}\n\nint Movie::updateState(double time, double dt)\n{\n updateImage(time, dt);\n return 0;\n}\n\n\/**\n * - Update the image buffers\n * - If the time is a multiple of biasChangetime then the position of the bias (biasX, biasY) changes.\n * - With probability persistenceProb the offset position (offsetX, offsetY) remains unchanged.\n * - Otherwise, with probability (1-persistenceProb) the offset position performs a random walk\n * around the bias position (biasX, biasY).\n *\n * - If the time is a multiple of displayPeriod then load the next image.\n * - If nf=1 then the image is converted to grayscale during the call to read(filename, offsetX, offsetY).\n * If nf>1 then the image is loaded with color information preserved.\n * - Return true if buffers have changed\n *\/\nbool Movie::updateImage(double time, double dt)\n{\n InterColComm * icComm = getParent()->icCommunicator();\n if(randomMovie){\n randomFrame();\n lastUpdateTime = time;\n } else {\n bool needNewImage = false;\n while (time >= nextDisplayTime) {\n needNewImage = true;\n if (readPvpFile){\n \/\/If set to 0 or 1, normal frame\n if (skipFrameIndex <= 1){\n frameNumber += 1;\n }\n \/\/Otherwise, skip based on skipFrameIndex\n else{\n frameNumber += skipFrameIndex;\n }\n \/\/Loop when frame number reaches numFrames\n if (frameNumber >= numFrames){\n if( icComm->commRank()==0 ) {\n fprintf(stderr, \"Movie %s: EOF reached, rewinding file \\\"%s\\\"\\n\", name, filename);\n }\n frameNumber = 0;\n }\n }\n else{\n if (filename != NULL) free(filename);\n filename = strdup(getNextFileName(skipFrameIndex));\n assert(filename != NULL);\n }\n nextDisplayTime += displayPeriod;\n\n if(writePosition && parent->icCommunicator()->commRank()==0){\n fprintf(fp_pos->fp,\"%f %s: \\n\",time,filename);\n }\n lastUpdateTime = time;\n } \/\/ time >= nextDisplayTime\n\n if( jitterFlag ) {\n bool jittered = jitter();\n needNewImage |= jittered;\n } \/\/ jitterFlag\n\n if( needNewImage ){\n GDALColorInterp * colorbandtypes = NULL;\n int status = getImageInfo(filename, parent->icCommunicator(), &imageLoc, &colorbandtypes);\n if( status != PV_SUCCESS ) {\n fprintf(stderr, \"Movie %s: Error getting image info \\\"%s\\\"\\n\", name, filename);\n abort();\n }\n \/\/Set frame number (member variable in Image)\n if( status == PV_SUCCESS ) status = readImage(filename, getOffsetX(), getOffsetY(), colorbandtypes);\n free(colorbandtypes); colorbandtypes = NULL;\n if( status != PV_SUCCESS ) {\n fprintf(stderr, \"Movie %s: Error reading file \\\"%s\\\"\\n\", name, filename);\n abort();\n }\n newImageFlag = true;\n }\n else{\n newImageFlag = false;\n }\n } \/\/ randomMovie\n\n \/\/ exchange border information\n exchange();\n\n return true;\n}\n\n\/**\n * When we play a random frame - in order to perform a reverse correlation analysis -\n * we call writeActivitySparse(time) in order to write the \"activity\" in the image.\n *\n *\/\nint Movie::outputState(double time, bool last)\n{\n if (writeImages) {\n char basicFilename[PV_PATH_MAX + 1];\n snprintf(basicFilename, PV_PATH_MAX, \"%s\/Movie_%.2f.%s\", movieOutputPath, time, writeImagesExtension);\n write(basicFilename);\n }\n\n int status = PV_SUCCESS;\n if (randomMovie != 0) {\n status = writeActivitySparse(time);\n }\n else {\n status = HyPerLayer::outputState(time, last);\n }\n\n return status;\n}\n\nint Movie::copyReducedImagePortion()\n{\n const PVLayerLoc * loc = getLayerLoc();\n\n const int nx = loc->nx;\n const int ny = loc->ny;\n\n const int nx0 = imageLoc.nx;\n const int ny0 = imageLoc.ny;\n\n assert(nx0 <= nx);\n assert(ny0 <= ny);\n\n const int i0 = nx\/2 - nx0\/2;\n const int j0 = ny\/2 - ny0\/2;\n\n int ii = 0;\n for (int j = j0; j < j0+ny0; j++) {\n for (int i = i0; i < i0+nx0; i++) {\n imageData[ii++] = data[i+nx*j];\n }\n }\n\n return 0;\n}\n\n\/**\n * This creates a random image patch (frame) that is used to perform a reverse correlation analysis\n * as the input signal propagates up the visual system's hierarchy.\n * NOTE: Check Image::toGrayScale() method which was the inspiration for this routine\n *\/\nint Movie::randomFrame()\n{\n assert(randomMovie); \/\/ randomMovieProb was set only if randomMovie is true\n for (int kex = 0; kex < clayer->numExtended; kex++) {\n double p = uniformRand01(&rand_state);\n data[kex] = (p < randomMovieProb) ? 1: 0;\n }\n return 0;\n}\n\n\/\/ skip n_skip lines before reading next frame\nconst char * Movie::getNextFileName(int n_skip)\n{\n for (int i_skip = 0; i_skip < n_skip-1; i_skip++){\n getNextFileName();\n }\n return getNextFileName();\n}\n\n\nconst char * Movie::getNextFileName()\n{\n InterColComm * icComm = getParent()->icCommunicator();\n if( icComm->commRank()==0 ) {\n int c;\n size_t len = PV_PATH_MAX;\n\n \/\/TODO: add recovery procedure to handle case where access to file is temporarily unavailable\n \/\/ use stat to verify status of filepointer, keep running tally of current frame index so that file can be reopened and advanced to current frame\n\n\n \/\/ if at end of file (EOF), rewind\n if ((c = fgetc(filenamestream->fp)) == EOF) {\n PV_fseek(filenamestream, 0L, SEEK_SET);\n fprintf(stderr, \"Movie %s: EOF reached, rewinding file \\\"%s\\\"\\n\", name, filename);\n }\n else {\n ungetc(c, filenamestream->fp);\n }\n\n char * path = fgets(inputfile, len, filenamestream->fp);\n if (path) {\n filenamestream->filepos += strlen(path)+1;\n }\n\n if (echoFramePathnameFlag){\n fprintf(stderr, \"%s\", path);\n }\n\n\n if (path != NULL) {\n path[PV_PATH_MAX-1] = '\\0';\n len = strlen(path);\n if (len > 1) {\n if (path[len-1] == '\\n') {\n path[len-1] = '\\0';\n }\n }\n }\n }\n#ifdef PV_USE_MPI\n MPI_Bcast(inputfile, PV_PATH_MAX, MPI_CHAR, 0, icComm->communicator());\n#endif \/\/ PV_USE_MPI\n return inputfile;\n}\n\nbool Movie::getNewImageFlag(){\n return newImageFlag;\n}\n\nconst char * Movie::getCurrentImage(){\n return inputfile;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Removed USE_REVERSE_DEPTHBUFFER boolean definition<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"UT\/UT_StringMMPattern.h\"\n\n#include \"IECore\/CompoundData.h\"\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/MessageHandler.h\"\n\n#include \"IECoreHoudini\/Convert.h\"\n#include \"IECoreHoudini\/ToHoudiniAttribConverter.h\"\n#include \"IECoreHoudini\/ToHoudiniGeometryConverter.h\"\n#include \"IECoreHoudini\/ToHoudiniStringAttribConverter.h\"\n\nusing namespace IECore;\nusing namespace IECoreHoudini;\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter );\n\nToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const IECore::Object *object, const std::string &description )\n\t:\tToHoudiniConverter( description, ObjectTypeId )\n{\n\tsrcParameter()->setValue( const_cast<Object*>( object ) ); \/\/ safe because the object is const in doConversion\n\t\n\tm_nameParameter = new StringParameter(\n\t\t\"name\",\n\t\t\"The name given to the converted primitive(s). If empty, primitives will be unnamed\",\n\t\t\"\"\n\t);\n\t\n\tm_attributeFilterParameter = new StringParameter(\n\t\t\"attributeFilter\",\n\t\t\"A list of attribute names to convert, if they exist. Uses Houdini matching syntax.\",\n\t\t\"*\"\n\t);\n\t\n\tm_convertStandardAttributesParameter = new BoolParameter(\n\t\t\"convertStandardAttributes\",\n\t\t\"Performs automated conversion of standard PrimitiveVariables to Houdini Attributes (i.e. Pref->rest ; Cs->Cd ; s,t->uv)\",\n\t\ttrue\n\t);\n\t\n\tparameters()->addParameter( m_nameParameter );\n\tparameters()->addParameter( m_attributeFilterParameter );\n\tparameters()->addParameter( m_convertStandardAttributesParameter );\n}\n\nToHoudiniGeometryConverter::~ToHoudiniGeometryConverter()\n{\n}\n\nBoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter()\n{\n\treturn m_convertStandardAttributesParameter;\n}\n\nconst BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() const\n{\n\treturn m_convertStandardAttributesParameter;\n}\n\nStringParameter *ToHoudiniGeometryConverter::nameParameter()\n{\n\treturn m_nameParameter;\n}\n\nconst StringParameter *ToHoudiniGeometryConverter::nameParameter() const\n{\n\treturn m_nameParameter;\n}\n\nStringParameter *ToHoudiniGeometryConverter::attributeFilterParameter()\n{\n\treturn m_attributeFilterParameter;\n}\n\nconst StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() const\n{\n\treturn m_attributeFilterParameter;\n}\n\nbool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const\n{\n\tConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>();\n\tGU_DetailHandleAutoWriteLock writeHandle( handle );\n\t\n\tGU_Detail *geo = writeHandle.getGdp();\n\tif ( !geo )\n\t{\n\t\treturn false;\n\t}\n\t\n\tbool result = doConversion( srcParameter()->getValidatedValue(), geo );\n\tif ( result )\n\t{\n\t\tgeo->incrementMetaCacheCount();\n\t}\n\t\n\treturn result;\n}\n\nGA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, size_t numPoints ) const\n{\n\tif ( !numPoints )\n\t{\n\t\treturn GA_Range();\n\t}\n\t\n\tGA_OffsetList offsets;\n\toffsets.reserve( numPoints );\n\t\n\tfor ( size_t i=0; i < numPoints; ++i )\n\t{\n\t\toffsets.append( geo->appendPoint() );\n\t}\n\t\n\treturn GA_Range( geo->getPointMap(), offsets );\n}\n\nPrimitiveVariable ToHoudiniGeometryConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const\n{\n\treturn primVar;\n}\n\nvoid ToHoudiniGeometryConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const\n{\n\tconst Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() );\n\tif ( primitive )\n\t{\n\t\ttransferAttribValues( primitive, geo, points, prims );\n\t}\n\t\n\tsetName( geo, prims );\n}\n\nvoid ToHoudiniGeometryConverter::setName( GU_Detail *geo, const GA_Range &prims ) const\n{\n\t\/\/ add the name attribute based on the parameter\n\tconst std::string &name = nameParameter()->getTypedValue();\n\tif ( name != \"\" && prims.isValid() )\n\t{\n\t\tToHoudiniStringVectorAttribConverter::convertString( \"name\", name, geo, prims );\n\t}\n}\n\nvoid ToHoudiniGeometryConverter::transferAttribValues(\n\tconst Primitive *primitive, GU_Detail *geo,\n\tconst GA_Range &points, const GA_Range &prims,\n\tPrimitiveVariable::Interpolation vertexInterpolation,\n\tPrimitiveVariable::Interpolation primitiveInterpolation,\n\tPrimitiveVariable::Interpolation pointInterpolation,\n\tPrimitiveVariable::Interpolation detailInterpolation\n) const\n{\n\tGA_OffsetList offsets;\n\tif ( prims.isValid() )\n\t{\n\t\tconst GA_PrimitiveList &primitives = geo->getPrimitiveList();\n\t\tfor ( GA_Iterator it=prims.begin(); !it.atEnd(); ++it )\n\t\t{\n\t\t\tconst GA_Primitive *prim = primitives.get( it.getOffset() );\n\t\t\tsize_t numPrimVerts = prim->getVertexCount();\n\t\t\tfor ( size_t v=0; v < numPrimVerts; v++ )\n\t\t\t{\n\t\t\t\tif ( prim->getTypeId() == GEO_PRIMPOLY )\n\t\t\t\t{\n\t\t\t\t\toffsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\toffsets.append( prim->getVertexOffset( v ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tGA_Range vertRange( geo->getVertexMap(), offsets );\n\t\n\tUT_String filter( attributeFilterParameter()->getTypedValue() );\n\t\n\t\/\/ match all the string variables to each associated indices variable\n\t\/\/\/ \\todo: replace all this logic with IECore::IndexedData once it exists...\n\tPrimitiveVariableMap stringsToIndices;\n\tfor ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ )\n\t{\n\t\tif ( !primitive->isPrimitiveVariableValid( it->second ) )\n\t\t{\n\t\t\tIECore::msg( IECore::MessageHandler::Warning, \"ToHoudiniGeometryConverter\", \"PrimitiveVariable \" + it->first + \" is invalid. Ignoring.\" );\n\t\t\tfilter += UT_String( \" ^\" + it->first );\n\t\t\tcontinue;\n\t\t}\n\n\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data );\n\t\tif ( !converter )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif ( it->second.data->isInstanceOf( StringVectorDataTypeId ) )\n\t\t{\n\t\t\tstd::string indicesVariableName = it->first + \"Indices\";\n\t\t\tPrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName );\n\t\t\tif ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) )\n\t\t\t{\n\t\t\t\tstringsToIndices[it->first] = indices->second;\n\t\t\t\tfilter += UT_String( \" ^\" + indicesVariableName );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tbool convertStandardAttributes = m_convertStandardAttributesParameter->getTypedValue();\n\tif ( convertStandardAttributes && UT_String( \"s\" ).multiMatch( filter ) && UT_String( \"t\" ).multiMatch( filter ) )\n\t{\n\t\t\/\/ convert s and t to uv\n\t\tPrimitiveVariableMap::const_iterator sPrimVar = primitive->variables.find( \"s\" );\n\t\tPrimitiveVariableMap::const_iterator tPrimVar = primitive->variables.find( \"t\" );\n\t\tif ( sPrimVar != primitive->variables.end() && tPrimVar != primitive->variables.end() )\n\t\t{\n\t\t\tif ( sPrimVar->second.interpolation == tPrimVar->second.interpolation )\n\t\t\t{\n\t\t\t\tconst FloatVectorData *sData = runTimeCast<const FloatVectorData>( sPrimVar->second.data );\n\t\t\t\tconst FloatVectorData *tData = runTimeCast<const FloatVectorData>( tPrimVar->second.data );\n\t\t\t\tif ( sData && tData )\n\t\t\t\t{\n\t\t\t\t\tconst std::vector<float> &s = sData->readable();\n\t\t\t\t\tconst std::vector<float> &t = tData->readable();\n\t\t\t\t\t\n\t\t\t\t\tstd::vector<Imath::V3f> uvw;\n\t\t\t\t\tuvw.reserve( s.size() );\n\t\t\t\t\tfor ( size_t i=0; i < s.size(); ++i )\n\t\t\t\t\t{\n\t\t\t\t\t\tuvw.push_back( Imath::V3f( s[i], 1 - t[i], 0 ) );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tGA_Range range = vertRange;\n\t\t\t\t\tif ( sPrimVar->second.interpolation == pointInterpolation )\n\t\t\t\t\t{\n\t\t\t\t\t\trange = points;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( new V3fVectorData( uvw ) );\n\t\t\t\t\tconverter->convert( \"uv\", geo, range );\n\t\t\t\t\tfilter += \" ^s ^t\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n \tUT_StringMMPattern attribFilter;\n\tattribFilter.compile( filter );\n\t\n\t\/\/ add the primitive variables to the various GEO_AttribDicts based on interpolation type\n\tfor ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ )\n\t{\n\t\tUT_String varName( it->first );\n\t\tif ( !varName.multiMatch( attribFilter ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tPrimitiveVariable primVar = processPrimitiveVariable( primitive, it->second );\n\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( primVar.data );\n\t\tif ( !converter )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tPrimitiveVariable::Interpolation interpolation = primVar.interpolation;\n\t\t\n\t\tif ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) )\n\t\t{\n\t\t\tPrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first );\n\t\t\tif ( indices != stringsToIndices.end() )\n\t\t\t{\n\t\t\t\tToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter );\n\t\t\t\tPrimitiveVariable indicesPrimVar = processPrimitiveVariable( primitive, indices->second );\n\t\t\t\tstringVectorConverter->indicesParameter()->setValidatedValue( indicesPrimVar.data );\n\t\t\t\tinterpolation = indices->second.interpolation;\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst std::string name = ( convertStandardAttributes ) ? processPrimitiveVariableName( it->first ) : it->first;\n\t\t\n\t\tif ( interpolation == detailInterpolation )\n \t\t{\n\t\t\t\/\/ add detail attribs\n\t\t\tconverter->convert( name, geo );\n\t \t}\n\t\telse if ( interpolation == pointInterpolation )\n\t\t{\n\t\t\t\/\/ add point attribs\n\t\t\tif ( name == \"P\" )\n\t\t\t{\n\t\t\t\t\/\/ special case for P\n\t\t\t\ttransferP( runTimeCast<const V3fVectorData>( primVar.data ), geo, points );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n \t\t\t\tconverter->convert( name, geo, points );\n\t\t\t}\n\t\t}\n\t\telse if ( interpolation == primitiveInterpolation )\n\t\t{\n\t\t\t\/\/ add primitive attribs\n\t\t\tconverter->convert( name, geo, prims );\n\t\t}\n\t\telse if ( interpolation == vertexInterpolation )\n\t\t{\n\t\t\t\/\/ add vertex attribs\n\t\t\tconverter->convert( name, geo, vertRange );\n\t\t}\n\t}\n\t\n\t\/\/ backwards compatibility with older data\n\tconst StringData *nameData = primitive->blindData()->member<StringData>( \"name\" );\n\tif ( nameData && prims.isValid() )\n\t{\n\t\tToHoudiniStringVectorAttribConverter::convertString( \"name\", nameData->readable(), geo, prims );\n\t}\n}\n\nvoid ToHoudiniGeometryConverter::transferP( const IECore::V3fVectorData *positions, GU_Detail *geo, const GA_Range &points ) const\n{\n\tif ( !positions )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst std::vector<Imath::V3f> &pos = positions->readable();\n\t\n\tsize_t i = 0;\n\tfor ( GA_Iterator it=points.begin(); !it.atEnd(); ++it, ++i )\n\t{\n\t\tgeo->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[i] ) );\n\t}\n}\n\nconst std::string ToHoudiniGeometryConverter::processPrimitiveVariableName( const std::string &name ) const\n{\n\t\/\/\/ \\todo: This should probably be some formal static map. Make sure to update FromHoudiniGeometryConverter as well.\n\tif ( name == \"Cs\" )\n\t{\n\t\treturn \"Cd\";\n\t}\n\telse if ( name == \"Os\" )\n\t{\n\t\treturn \"Alpha\";\n\t}\n\telse if ( name == \"Pref\" )\n\t{\n\t\treturn \"rest\";\n\t}\n\telse if ( name == \"width\" )\n\t{\n\t\treturn \"pscale\";\n\t}\n\t\n\treturn name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Factory\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const Object *object )\n{\n\tconst TypesToFnsMap *m = typesToFns();\n\tTypesToFnsMap::const_iterator it = m->find( Types( object->typeId() ) );\n\tif( it!=m->end() )\n\t{\n\t\treturn it->second( object );\n\t}\n\t\n\t\/\/ no exact match, so check for base class matches\n\tfor ( TypesToFnsMap::const_iterator it = m->begin(); it != m->end(); ++it )\n\t{\n\t\tif ( object->isInstanceOf( it->first.fromType ) )\n\t\t{\n\t\t\treturn it->second( object );\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nvoid ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator )\n{\n\tTypesToFnsMap *m = typesToFns();\n\tm->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) );\n}\n\nToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns()\n{\n\tstatic TypesToFnsMap *m = new TypesToFnsMap;\n\treturn m;\n}\n\nvoid ToHoudiniGeometryConverter::supportedTypes( std::set<IECore::TypeId> &types )\n{\n\ttypes.clear();\n\t\n\tconst TypesToFnsMap *m = typesToFns();\n\tfor ( TypesToFnsMap::const_iterator it=m->begin(); it != m->end(); it ++ )\n\t{\n\t\ttypes.insert( it->first.fromType );\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of nested Types class\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from )\n{\n}\n\nbool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const\n{\n\treturn fromType < other.fromType;\n}\n<commit_msg>Fixing factory function to search base classes in the correct order<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"UT\/UT_StringMMPattern.h\"\n\n#include \"IECore\/CompoundData.h\"\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/MessageHandler.h\"\n\n#include \"IECoreHoudini\/Convert.h\"\n#include \"IECoreHoudini\/ToHoudiniAttribConverter.h\"\n#include \"IECoreHoudini\/ToHoudiniGeometryConverter.h\"\n#include \"IECoreHoudini\/ToHoudiniStringAttribConverter.h\"\n\nusing namespace IECore;\nusing namespace IECoreHoudini;\n\nIE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter );\n\nToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const IECore::Object *object, const std::string &description )\n\t:\tToHoudiniConverter( description, ObjectTypeId )\n{\n\tsrcParameter()->setValue( const_cast<Object*>( object ) ); \/\/ safe because the object is const in doConversion\n\t\n\tm_nameParameter = new StringParameter(\n\t\t\"name\",\n\t\t\"The name given to the converted primitive(s). If empty, primitives will be unnamed\",\n\t\t\"\"\n\t);\n\t\n\tm_attributeFilterParameter = new StringParameter(\n\t\t\"attributeFilter\",\n\t\t\"A list of attribute names to convert, if they exist. Uses Houdini matching syntax.\",\n\t\t\"*\"\n\t);\n\t\n\tm_convertStandardAttributesParameter = new BoolParameter(\n\t\t\"convertStandardAttributes\",\n\t\t\"Performs automated conversion of standard PrimitiveVariables to Houdini Attributes (i.e. Pref->rest ; Cs->Cd ; s,t->uv)\",\n\t\ttrue\n\t);\n\t\n\tparameters()->addParameter( m_nameParameter );\n\tparameters()->addParameter( m_attributeFilterParameter );\n\tparameters()->addParameter( m_convertStandardAttributesParameter );\n}\n\nToHoudiniGeometryConverter::~ToHoudiniGeometryConverter()\n{\n}\n\nBoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter()\n{\n\treturn m_convertStandardAttributesParameter;\n}\n\nconst BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() const\n{\n\treturn m_convertStandardAttributesParameter;\n}\n\nStringParameter *ToHoudiniGeometryConverter::nameParameter()\n{\n\treturn m_nameParameter;\n}\n\nconst StringParameter *ToHoudiniGeometryConverter::nameParameter() const\n{\n\treturn m_nameParameter;\n}\n\nStringParameter *ToHoudiniGeometryConverter::attributeFilterParameter()\n{\n\treturn m_attributeFilterParameter;\n}\n\nconst StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() const\n{\n\treturn m_attributeFilterParameter;\n}\n\nbool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const\n{\n\tConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>();\n\tGU_DetailHandleAutoWriteLock writeHandle( handle );\n\t\n\tGU_Detail *geo = writeHandle.getGdp();\n\tif ( !geo )\n\t{\n\t\treturn false;\n\t}\n\t\n\tbool result = doConversion( srcParameter()->getValidatedValue(), geo );\n\tif ( result )\n\t{\n\t\tgeo->incrementMetaCacheCount();\n\t}\n\t\n\treturn result;\n}\n\nGA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, size_t numPoints ) const\n{\n\tif ( !numPoints )\n\t{\n\t\treturn GA_Range();\n\t}\n\t\n\tGA_OffsetList offsets;\n\toffsets.reserve( numPoints );\n\t\n\tfor ( size_t i=0; i < numPoints; ++i )\n\t{\n\t\toffsets.append( geo->appendPoint() );\n\t}\n\t\n\treturn GA_Range( geo->getPointMap(), offsets );\n}\n\nPrimitiveVariable ToHoudiniGeometryConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const\n{\n\treturn primVar;\n}\n\nvoid ToHoudiniGeometryConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const\n{\n\tconst Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() );\n\tif ( primitive )\n\t{\n\t\ttransferAttribValues( primitive, geo, points, prims );\n\t}\n\t\n\tsetName( geo, prims );\n}\n\nvoid ToHoudiniGeometryConverter::setName( GU_Detail *geo, const GA_Range &prims ) const\n{\n\t\/\/ add the name attribute based on the parameter\n\tconst std::string &name = nameParameter()->getTypedValue();\n\tif ( name != \"\" && prims.isValid() )\n\t{\n\t\tToHoudiniStringVectorAttribConverter::convertString( \"name\", name, geo, prims );\n\t}\n}\n\nvoid ToHoudiniGeometryConverter::transferAttribValues(\n\tconst Primitive *primitive, GU_Detail *geo,\n\tconst GA_Range &points, const GA_Range &prims,\n\tPrimitiveVariable::Interpolation vertexInterpolation,\n\tPrimitiveVariable::Interpolation primitiveInterpolation,\n\tPrimitiveVariable::Interpolation pointInterpolation,\n\tPrimitiveVariable::Interpolation detailInterpolation\n) const\n{\n\tGA_OffsetList offsets;\n\tif ( prims.isValid() )\n\t{\n\t\tconst GA_PrimitiveList &primitives = geo->getPrimitiveList();\n\t\tfor ( GA_Iterator it=prims.begin(); !it.atEnd(); ++it )\n\t\t{\n\t\t\tconst GA_Primitive *prim = primitives.get( it.getOffset() );\n\t\t\tsize_t numPrimVerts = prim->getVertexCount();\n\t\t\tfor ( size_t v=0; v < numPrimVerts; v++ )\n\t\t\t{\n\t\t\t\tif ( prim->getTypeId() == GEO_PRIMPOLY )\n\t\t\t\t{\n\t\t\t\t\toffsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\toffsets.append( prim->getVertexOffset( v ) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tGA_Range vertRange( geo->getVertexMap(), offsets );\n\t\n\tUT_String filter( attributeFilterParameter()->getTypedValue() );\n\t\n\t\/\/ match all the string variables to each associated indices variable\n\t\/\/\/ \\todo: replace all this logic with IECore::IndexedData once it exists...\n\tPrimitiveVariableMap stringsToIndices;\n\tfor ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ )\n\t{\n\t\tif ( !primitive->isPrimitiveVariableValid( it->second ) )\n\t\t{\n\t\t\tIECore::msg( IECore::MessageHandler::Warning, \"ToHoudiniGeometryConverter\", \"PrimitiveVariable \" + it->first + \" is invalid. Ignoring.\" );\n\t\t\tfilter += UT_String( \" ^\" + it->first );\n\t\t\tcontinue;\n\t\t}\n\n\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data );\n\t\tif ( !converter )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif ( it->second.data->isInstanceOf( StringVectorDataTypeId ) )\n\t\t{\n\t\t\tstd::string indicesVariableName = it->first + \"Indices\";\n\t\t\tPrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName );\n\t\t\tif ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) )\n\t\t\t{\n\t\t\t\tstringsToIndices[it->first] = indices->second;\n\t\t\t\tfilter += UT_String( \" ^\" + indicesVariableName );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tbool convertStandardAttributes = m_convertStandardAttributesParameter->getTypedValue();\n\tif ( convertStandardAttributes && UT_String( \"s\" ).multiMatch( filter ) && UT_String( \"t\" ).multiMatch( filter ) )\n\t{\n\t\t\/\/ convert s and t to uv\n\t\tPrimitiveVariableMap::const_iterator sPrimVar = primitive->variables.find( \"s\" );\n\t\tPrimitiveVariableMap::const_iterator tPrimVar = primitive->variables.find( \"t\" );\n\t\tif ( sPrimVar != primitive->variables.end() && tPrimVar != primitive->variables.end() )\n\t\t{\n\t\t\tif ( sPrimVar->second.interpolation == tPrimVar->second.interpolation )\n\t\t\t{\n\t\t\t\tconst FloatVectorData *sData = runTimeCast<const FloatVectorData>( sPrimVar->second.data );\n\t\t\t\tconst FloatVectorData *tData = runTimeCast<const FloatVectorData>( tPrimVar->second.data );\n\t\t\t\tif ( sData && tData )\n\t\t\t\t{\n\t\t\t\t\tconst std::vector<float> &s = sData->readable();\n\t\t\t\t\tconst std::vector<float> &t = tData->readable();\n\t\t\t\t\t\n\t\t\t\t\tstd::vector<Imath::V3f> uvw;\n\t\t\t\t\tuvw.reserve( s.size() );\n\t\t\t\t\tfor ( size_t i=0; i < s.size(); ++i )\n\t\t\t\t\t{\n\t\t\t\t\t\tuvw.push_back( Imath::V3f( s[i], 1 - t[i], 0 ) );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tGA_Range range = vertRange;\n\t\t\t\t\tif ( sPrimVar->second.interpolation == pointInterpolation )\n\t\t\t\t\t{\n\t\t\t\t\t\trange = points;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( new V3fVectorData( uvw ) );\n\t\t\t\t\tconverter->convert( \"uv\", geo, range );\n\t\t\t\t\tfilter += \" ^s ^t\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n \tUT_StringMMPattern attribFilter;\n\tattribFilter.compile( filter );\n\t\n\t\/\/ add the primitive variables to the various GEO_AttribDicts based on interpolation type\n\tfor ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ )\n\t{\n\t\tUT_String varName( it->first );\n\t\tif ( !varName.multiMatch( attribFilter ) )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tPrimitiveVariable primVar = processPrimitiveVariable( primitive, it->second );\n\t\tToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( primVar.data );\n\t\tif ( !converter )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tPrimitiveVariable::Interpolation interpolation = primVar.interpolation;\n\t\t\n\t\tif ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) )\n\t\t{\n\t\t\tPrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first );\n\t\t\tif ( indices != stringsToIndices.end() )\n\t\t\t{\n\t\t\t\tToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter );\n\t\t\t\tPrimitiveVariable indicesPrimVar = processPrimitiveVariable( primitive, indices->second );\n\t\t\t\tstringVectorConverter->indicesParameter()->setValidatedValue( indicesPrimVar.data );\n\t\t\t\tinterpolation = indices->second.interpolation;\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst std::string name = ( convertStandardAttributes ) ? processPrimitiveVariableName( it->first ) : it->first;\n\t\t\n\t\tif ( interpolation == detailInterpolation )\n \t\t{\n\t\t\t\/\/ add detail attribs\n\t\t\tconverter->convert( name, geo );\n\t \t}\n\t\telse if ( interpolation == pointInterpolation )\n\t\t{\n\t\t\t\/\/ add point attribs\n\t\t\tif ( name == \"P\" )\n\t\t\t{\n\t\t\t\t\/\/ special case for P\n\t\t\t\ttransferP( runTimeCast<const V3fVectorData>( primVar.data ), geo, points );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n \t\t\t\tconverter->convert( name, geo, points );\n\t\t\t}\n\t\t}\n\t\telse if ( interpolation == primitiveInterpolation )\n\t\t{\n\t\t\t\/\/ add primitive attribs\n\t\t\tconverter->convert( name, geo, prims );\n\t\t}\n\t\telse if ( interpolation == vertexInterpolation )\n\t\t{\n\t\t\t\/\/ add vertex attribs\n\t\t\tconverter->convert( name, geo, vertRange );\n\t\t}\n\t}\n\t\n\t\/\/ backwards compatibility with older data\n\tconst StringData *nameData = primitive->blindData()->member<StringData>( \"name\" );\n\tif ( nameData && prims.isValid() )\n\t{\n\t\tToHoudiniStringVectorAttribConverter::convertString( \"name\", nameData->readable(), geo, prims );\n\t}\n}\n\nvoid ToHoudiniGeometryConverter::transferP( const IECore::V3fVectorData *positions, GU_Detail *geo, const GA_Range &points ) const\n{\n\tif ( !positions )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst std::vector<Imath::V3f> &pos = positions->readable();\n\t\n\tsize_t i = 0;\n\tfor ( GA_Iterator it=points.begin(); !it.atEnd(); ++it, ++i )\n\t{\n\t\tgeo->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[i] ) );\n\t}\n}\n\nconst std::string ToHoudiniGeometryConverter::processPrimitiveVariableName( const std::string &name ) const\n{\n\t\/\/\/ \\todo: This should probably be some formal static map. Make sure to update FromHoudiniGeometryConverter as well.\n\tif ( name == \"Cs\" )\n\t{\n\t\treturn \"Cd\";\n\t}\n\telse if ( name == \"Os\" )\n\t{\n\t\treturn \"Alpha\";\n\t}\n\telse if ( name == \"Pref\" )\n\t{\n\t\treturn \"rest\";\n\t}\n\telse if ( name == \"width\" )\n\t{\n\t\treturn \"pscale\";\n\t}\n\t\n\treturn name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Factory\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const Object *object )\n{\n\tconst TypesToFnsMap *m = typesToFns();\n\tTypesToFnsMap::const_iterator it = m->find( Types( object->typeId() ) );\n\tif( it!=m->end() )\n\t{\n\t\treturn it->second( object );\n\t}\n\t\n\t\/\/ no exact match, so check for base class matches\n\tconst std::vector<IECore::TypeId> &bases = RunTimeTyped::baseTypeIds( object->typeId() );\n\tfor ( std::vector<IECore::TypeId>::const_iterator it = bases.begin(); it != bases.end(); ++it )\n\t{\n\t\tTypesToFnsMap::const_iterator cIt = m->find( Types( *it ) );\n\t\tif ( cIt != m->end() )\n\t\t{\n\t\t\treturn cIt->second( object );\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nvoid ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator )\n{\n\tTypesToFnsMap *m = typesToFns();\n\tm->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) );\n}\n\nToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns()\n{\n\tstatic TypesToFnsMap *m = new TypesToFnsMap;\n\treturn m;\n}\n\nvoid ToHoudiniGeometryConverter::supportedTypes( std::set<IECore::TypeId> &types )\n{\n\ttypes.clear();\n\t\n\tconst TypesToFnsMap *m = typesToFns();\n\tfor ( TypesToFnsMap::const_iterator it=m->begin(); it != m->end(); it ++ )\n\t{\n\t\ttypes.insert( it->first.fromType );\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of nested Types class\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from )\n{\n}\n\nbool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const\n{\n\treturn fromType < other.fromType;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2011-2012 Alessandro Tasora\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be \n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n\n#include <cmath>\n#include <algorithm>\n\n#include \"physics\/ChContactDEM.h\"\n#include \"physics\/ChSystemDEM.h\"\n#include \"physics\/ChBodyDEM.h\"\n\n\/\/ Memory leak debugger (must be included last).\n#include \"core\/ChMemory.h\"\n\n\nnamespace chrono {\n\nusing namespace collision;\n\n\n\/\/ Initialize static members\ndouble ChContactDEM::m_minSlipVelocity = 1e-4;\ndouble ChContactDEM::m_characteristicVelocity = 1;\n\n\n\/\/ Construct a new DEM contact between two models using the specified contact pair information.\nChContactDEM::ChContactDEM(collision::ChModelBulletBody* mod1,\n collision::ChModelBulletBody* mod2,\n const collision::ChCollisionInfo& cinfo)\n{\n Reset(mod1, mod2, cinfo);\n}\n\n\n\/\/ Worker function for populating a new or reusing an exsting contact.\nvoid ChContactDEM::Reset(collision::ChModelBulletBody* mod1,\n collision::ChModelBulletBody* mod2,\n const collision::ChCollisionInfo& cinfo)\n{\n assert(cinfo.distance < 0);\n\n m_mod1 = mod1;\n m_mod2 = mod2;\n\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n \/\/ Contact points, penetration, normal\n m_p1 = cinfo.vpA;\n m_p2 = cinfo.vpB;\n m_delta = -cinfo.distance;\n m_normal = cinfo.vN;\n\n \/\/ Contact plane\n ChVector<> Vx, Vy, Vz;\n cinfo.vN.DirToDxDyDz(Vx, Vy, Vz);\n m_contact_plane.Set_A_axis(Vx, Vy, Vz);\n\n \/\/ Contact points in local frames\n m_p1_loc = body1->Point_World2Body(m_p1);\n m_p2_loc = body2->Point_World2Body(m_p2);\n\n \/\/ Calculate contact force\n CalculateForce();\n}\n\n\n\/\/ Calculate the contact force to be applied to body2, based on the\n\/\/ globally specified contact force model.\nvoid ChContactDEM::CalculateForce()\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChSystemDEM* sys = static_cast<ChSystemDEM*>(body1->GetSystem());\n\n double dT = sys->GetStep();\n bool use_mat_props = sys->UseMaterialProperties();\n ContactForceModel force_model = sys->GetContactForceModel();\n\n \/\/ Relative velocity at contact\n ChVector<> vel2 = body2->PointSpeedLocalToParent(m_p2_loc);\n ChVector<> vel1 = body1->PointSpeedLocalToParent(m_p1_loc);\n ChVector<> relvel = vel2 - vel1;\n double relvel_n_mag = relvel.Dot(m_normal);\n ChVector<> relvel_n = relvel_n_mag * m_normal;\n ChVector<> relvel_t = relvel - relvel_n;\n double relvel_t_mag = relvel_t.Length();\n\n \/\/ Calculate effective mass\n double m_eff = body1->GetMass() * body2->GetMass() \/ (body1->GetMass() + body2->GetMass());\n\n \/\/ Calculate effective contact radius\n \/\/\/\/ TODO: how can I get this with current collision system!?!?!?\n double R_eff = 1;\n\n \/\/ Calculate composite material properties\n ChCompositeMaterialDEM mat = ChMaterialSurfaceDEM::CompositeMaterial(body1->GetMaterialSurfaceDEM(), body2->GetMaterialSurfaceDEM());\n\n \/\/ Contact forces.\n \/\/ All models use the following formulas for normal and tangential forces:\n \/\/ Fn = kn * delta_n - gn * v_n\n \/\/ Ft = kt * delta_t - gt * v_t\n double kn;\n double kt;\n double gn;\n double gt;\n\n double delta_t = 0;\n\n switch (force_model) {\n\n case Hooke_history:\n delta_t = relvel_t_mag * dT;\n\n case Hooke:\n if (use_mat_props) {\n double tmp_k = (16.0 \/ 15) * std::sqrt(R_eff) * mat.E_eff;\n double v2 = m_characteristicVelocity * m_characteristicVelocity;\n double tmp_g = 1 + std::pow(CH_C_PI \/ std::log(mat.cr_eff), 2);\n kn = tmp_k * std::pow(m_eff * v2 \/ tmp_k, 1.0 \/ 5);\n kt = kn;\n gn = std::sqrt(4 * m_eff * kn \/ tmp_g);\n gt = gn;\n } else {\n kn = mat.kn;\n kt = mat.kt;\n gn = m_eff * mat.gn;\n gt = m_eff * mat.gt;\n }\n\n break;\n\n case Hertz_history:\n delta_t = relvel_t_mag * dT;\n\n case Hertz:\n if (use_mat_props) {\n double sqrt_Rd = std::sqrt(R_eff * m_delta);\n double Sn = 2 * mat.E_eff * sqrt_Rd;\n double St = 8 * mat.G_eff * sqrt_Rd;\n double loge = std::log(mat.cr_eff);\n double beta = loge \/ std::sqrt(loge * loge + CH_C_PI * CH_C_PI);\n kn = (2.0 \/ 3) * Sn;\n kt = St;\n gn = -2 * std::sqrt(5.0 \/ 6) * beta * std::sqrt(Sn * m_eff);\n gt = -2 * std::sqrt(5.0 \/ 6) * beta * std::sqrt(St * m_eff);\n } else {\n double tmp = R_eff * std::sqrt(m_delta);\n kn = tmp * mat.kn;\n kt = tmp * mat.kt;\n gn = tmp * m_eff * mat.gn;\n gt = tmp * m_eff * mat.gt;\n }\n\n break;\n }\n\n \/\/ Calculate the magnitudes of the normal and tangential contact forces\n double forceN = kn * m_delta - gn * relvel_n_mag;\n double forceT = kt * delta_t - gt * relvel_t_mag;\n\n \/\/ Coulomb law\n forceT = std::min<double>(forceT, mat.mu_eff * std::abs(forceN));\n\n \/\/ Accumulate normal and tangential forces\n m_force = forceN * m_normal;\n if (relvel_t_mag >= m_minSlipVelocity)\n m_force += (forceT \/ relvel_t_mag) * relvel_t;\n}\n\n\n\/\/ Include the contact force from this contact into the body forces and\n\/\/ torques of the two bodies involved in this contact. Recall that the\n\/\/ contact force as calculated must be applied to body2 and inverted for\n\/\/ body1.\n\/\/ NOTE: SEE NEW VERSION BELOW...\nvoid ChContactDEM::ConstraintsFbLoadForces(double factor)\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChVector<> force1_loc = body1->Dir_World2Body(m_force);\n ChVector<> force2_loc = body2->Dir_World2Body(m_force);\n ChVector<> torque1_loc = Vcross(m_p1_loc, -force1_loc);\n ChVector<> torque2_loc = Vcross(m_p2_loc, force2_loc);\n\n body1->Variables().Get_fb().PasteSumVector(-m_force*factor, 0, 0);\n body1->Variables().Get_fb().PasteSumVector(torque1_loc*factor, 3, 0);\n\n body2->Variables().Get_fb().PasteSumVector(m_force*factor, 0, 0);\n body2->Variables().Get_fb().PasteSumVector(torque2_loc*factor, 3, 0);\n}\n\n\/\/ Apply contact forces to bodies (new version, for interfacing to ChTimestepper and ChIntegrable)\n\/\/ Replaces ConstraintsFbLoadForces.\n\/\/ Include the contact force from this contact into the body forces and\n\/\/ torques of the two bodies involved in this contact. Recall that the\n\/\/ contact force as calculated must be applied to body2 and inverted for\n\/\/ body1.\nvoid ChContactDEM::DemIntLoadResidual_F(ChVectorDynamic<>& R, const double c )\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChVector<> force1_loc = body1->Dir_World2Body(m_force);\n ChVector<> force2_loc = body2->Dir_World2Body(m_force);\n ChVector<> torque1_loc = Vcross(m_p1_loc, -force1_loc);\n ChVector<> torque2_loc = Vcross(m_p2_loc, force2_loc);\n\n R.PasteSumVector(-m_force*c, body1->Variables().GetOffset() + 0, 0);\n R.PasteSumVector(torque1_loc*c, body1->Variables().GetOffset() + 3, 0);\n\n R.PasteSumVector(m_force*c, body2->Variables().GetOffset() + 0, 0);\n R.PasteSumVector(torque2_loc*c, body2->Variables().GetOffset() + 3, 0);\n}\n\n\n\/\/ Return the coordinate system for this contact (centered at point P2\n\/\/ and oriented based on the contact plane and normal)\nChCoordsys<> ChContactDEM::GetContactCoords() const\n{\n ChCoordsys<> mcsys;\n ChQuaternion<float> mrot = m_contact_plane.Get_A_quaternion();\n\n mcsys.rot.Set(mrot.e0, mrot.e1, mrot.e2, mrot.e3);\n mcsys.pos = m_p2;\n\n return mcsys;\n}\n\n\n} \/\/ end namespace chrono\n<commit_msg>Fix sign in tangential force and put back in the check for pulling normal force.<commit_after>\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2011-2012 Alessandro Tasora\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be \n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n\n#include <cmath>\n#include <algorithm>\n\n#include \"physics\/ChContactDEM.h\"\n#include \"physics\/ChSystemDEM.h\"\n#include \"physics\/ChBodyDEM.h\"\n\n\/\/ Memory leak debugger (must be included last).\n#include \"core\/ChMemory.h\"\n\n\nnamespace chrono {\n\nusing namespace collision;\n\n\n\/\/ Initialize static members\ndouble ChContactDEM::m_minSlipVelocity = 1e-4;\ndouble ChContactDEM::m_characteristicVelocity = 1;\n\n\n\/\/ Construct a new DEM contact between two models using the specified contact pair information.\nChContactDEM::ChContactDEM(collision::ChModelBulletBody* mod1,\n collision::ChModelBulletBody* mod2,\n const collision::ChCollisionInfo& cinfo)\n{\n Reset(mod1, mod2, cinfo);\n}\n\n\n\/\/ Worker function for populating a new or reusing an exsting contact.\nvoid ChContactDEM::Reset(collision::ChModelBulletBody* mod1,\n collision::ChModelBulletBody* mod2,\n const collision::ChCollisionInfo& cinfo)\n{\n assert(cinfo.distance < 0);\n\n m_mod1 = mod1;\n m_mod2 = mod2;\n\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n \/\/ Contact points, penetration, normal\n m_p1 = cinfo.vpA;\n m_p2 = cinfo.vpB;\n m_delta = -cinfo.distance;\n m_normal = cinfo.vN;\n\n \/\/ Contact plane\n ChVector<> Vx, Vy, Vz;\n cinfo.vN.DirToDxDyDz(Vx, Vy, Vz);\n m_contact_plane.Set_A_axis(Vx, Vy, Vz);\n\n \/\/ Contact points in local frames\n m_p1_loc = body1->Point_World2Body(m_p1);\n m_p2_loc = body2->Point_World2Body(m_p2);\n\n \/\/ Calculate contact force\n CalculateForce();\n}\n\n\n\/\/ Calculate the contact force to be applied to body2, based on the\n\/\/ globally specified contact force model.\nvoid ChContactDEM::CalculateForce()\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChSystemDEM* sys = static_cast<ChSystemDEM*>(body1->GetSystem());\n\n double dT = sys->GetStep();\n bool use_mat_props = sys->UseMaterialProperties();\n ContactForceModel force_model = sys->GetContactForceModel();\n\n \/\/ Relative velocity at contact\n ChVector<> vel2 = body2->PointSpeedLocalToParent(m_p2_loc);\n ChVector<> vel1 = body1->PointSpeedLocalToParent(m_p1_loc);\n ChVector<> relvel = vel2 - vel1;\n double relvel_n_mag = relvel.Dot(m_normal);\n ChVector<> relvel_n = relvel_n_mag * m_normal;\n ChVector<> relvel_t = relvel - relvel_n;\n double relvel_t_mag = relvel_t.Length();\n\n \/\/ Calculate effective mass\n double m_eff = body1->GetMass() * body2->GetMass() \/ (body1->GetMass() + body2->GetMass());\n\n \/\/ Calculate effective contact radius\n \/\/\/\/ TODO: how can I get this with current collision system!?!?!?\n double R_eff = 1;\n\n \/\/ Calculate composite material properties\n ChCompositeMaterialDEM mat = ChMaterialSurfaceDEM::CompositeMaterial(body1->GetMaterialSurfaceDEM(), body2->GetMaterialSurfaceDEM());\n\n \/\/ Contact forces.\n \/\/ All models use the following formulas for normal and tangential forces:\n \/\/ Fn = kn * delta_n - gn * v_n\n \/\/ Ft = kt * delta_t - gt * v_t\n double kn;\n double kt;\n double gn;\n double gt;\n\n double delta_t = 0;\n\n switch (force_model) {\n\n case Hooke_history:\n delta_t = relvel_t_mag * dT;\n\n case Hooke:\n if (use_mat_props) {\n double tmp_k = (16.0 \/ 15) * std::sqrt(R_eff) * mat.E_eff;\n double v2 = m_characteristicVelocity * m_characteristicVelocity;\n double tmp_g = 1 + std::pow(CH_C_PI \/ std::log(mat.cr_eff), 2);\n kn = tmp_k * std::pow(m_eff * v2 \/ tmp_k, 1.0 \/ 5);\n kt = kn;\n gn = std::sqrt(4 * m_eff * kn \/ tmp_g);\n gt = gn;\n } else {\n kn = mat.kn;\n kt = mat.kt;\n gn = m_eff * mat.gn;\n gt = m_eff * mat.gt;\n }\n\n break;\n\n case Hertz_history:\n delta_t = relvel_t_mag * dT;\n\n case Hertz:\n if (use_mat_props) {\n double sqrt_Rd = std::sqrt(R_eff * m_delta);\n double Sn = 2 * mat.E_eff * sqrt_Rd;\n double St = 8 * mat.G_eff * sqrt_Rd;\n double loge = std::log(mat.cr_eff);\n double beta = loge \/ std::sqrt(loge * loge + CH_C_PI * CH_C_PI);\n kn = (2.0 \/ 3) * Sn;\n kt = St;\n gn = -2 * std::sqrt(5.0 \/ 6) * beta * std::sqrt(Sn * m_eff);\n gt = -2 * std::sqrt(5.0 \/ 6) * beta * std::sqrt(St * m_eff);\n } else {\n double tmp = R_eff * std::sqrt(m_delta);\n kn = tmp * mat.kn;\n kt = tmp * mat.kt;\n gn = tmp * m_eff * mat.gn;\n gt = tmp * m_eff * mat.gt;\n }\n\n break;\n }\n\n \/\/ Calculate the magnitudes of the normal and tangential contact forces\n double forceN = kn * m_delta - gn * relvel_n_mag;\n double forceT = kt * delta_t + gt * relvel_t_mag;\n\n \/\/ If the resulting force is negative, the two shapes are moving away from\n \/\/ each other so fast that no contact force is generated.\n if (forceN < 0) {\n forceN = 0;\n forceT = 0;\n }\n\n \/\/ Coulomb law\n forceT = std::min<double>(forceT, mat.mu_eff * std::abs(forceN));\n\n \/\/ Accumulate normal and tangential forces\n m_force = forceN * m_normal;\n if (relvel_t_mag >= m_minSlipVelocity)\n m_force -= (forceT \/ relvel_t_mag) * relvel_t;\n}\n\n\n\/\/ Include the contact force from this contact into the body forces and\n\/\/ torques of the two bodies involved in this contact. Recall that the\n\/\/ contact force as calculated must be applied to body2 and inverted for\n\/\/ body1.\n\/\/ NOTE: SEE NEW VERSION BELOW...\nvoid ChContactDEM::ConstraintsFbLoadForces(double factor)\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChVector<> force1_loc = body1->Dir_World2Body(m_force);\n ChVector<> force2_loc = body2->Dir_World2Body(m_force);\n ChVector<> torque1_loc = Vcross(m_p1_loc, -force1_loc);\n ChVector<> torque2_loc = Vcross(m_p2_loc, force2_loc);\n\n body1->Variables().Get_fb().PasteSumVector(-m_force*factor, 0, 0);\n body1->Variables().Get_fb().PasteSumVector(torque1_loc*factor, 3, 0);\n\n body2->Variables().Get_fb().PasteSumVector(m_force*factor, 0, 0);\n body2->Variables().Get_fb().PasteSumVector(torque2_loc*factor, 3, 0);\n}\n\n\/\/ Apply contact forces to bodies (new version, for interfacing to ChTimestepper and ChIntegrable)\n\/\/ Replaces ConstraintsFbLoadForces.\n\/\/ Include the contact force from this contact into the body forces and\n\/\/ torques of the two bodies involved in this contact. Recall that the\n\/\/ contact force as calculated must be applied to body2 and inverted for\n\/\/ body1.\nvoid ChContactDEM::DemIntLoadResidual_F(ChVectorDynamic<>& R, const double c )\n{\n ChBodyDEM* body1 = (ChBodyDEM*)m_mod1->GetBody();\n ChBodyDEM* body2 = (ChBodyDEM*)m_mod2->GetBody();\n\n ChVector<> force1_loc = body1->Dir_World2Body(m_force);\n ChVector<> force2_loc = body2->Dir_World2Body(m_force);\n ChVector<> torque1_loc = Vcross(m_p1_loc, -force1_loc);\n ChVector<> torque2_loc = Vcross(m_p2_loc, force2_loc);\n\n R.PasteSumVector(-m_force*c, body1->Variables().GetOffset() + 0, 0);\n R.PasteSumVector(torque1_loc*c, body1->Variables().GetOffset() + 3, 0);\n\n R.PasteSumVector(m_force*c, body2->Variables().GetOffset() + 0, 0);\n R.PasteSumVector(torque2_loc*c, body2->Variables().GetOffset() + 3, 0);\n}\n\n\n\/\/ Return the coordinate system for this contact (centered at point P2\n\/\/ and oriented based on the contact plane and normal)\nChCoordsys<> ChContactDEM::GetContactCoords() const\n{\n ChCoordsys<> mcsys;\n ChQuaternion<float> mrot = m_contact_plane.Get_A_quaternion();\n\n mcsys.rot.Set(mrot.e0, mrot.e1, mrot.e2, mrot.e3);\n mcsys.pos = m_p2;\n\n return mcsys;\n}\n\n\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/scalar_ode.h\"\n\n\/\/ GRINS\n#include \"grins\/generic_ic_handler.h\"\n#include \"grins\/variable_name_defaults.h\"\n\n\/\/ libMesh\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n\nnamespace GRINS\n{\n\n ScalarODE::ScalarODE( const std::string& physics_name, const GetPot& input )\n : Physics(physics_name, input), _order(1), _epsilon(1e-6)\n {\n this->read_input_options(input);\n\n this->_ic_handler = new GenericICHandler( physics_name, input );\n\n return;\n }\n\n ScalarODE::~ScalarODE()\n {\n return;\n }\n\n void ScalarODE::init_variables( libMesh::FEMSystem* system )\n {\n this->_scalar_ode_var = system->add_variable(_scalar_ode_var_name,\n libMesh::Order(this->_order),\n libMesh::SCALAR);\n }\n\n void ScalarODE::set_time_evolving_vars( libMesh::FEMSystem* system )\n {\n system->time_evolving(this->scalar_ode_var());\n\n \/\/ FIXME: this doesn't fit here at all, but it's the only time\n \/\/ we've clearly got a System to grab hold of with all it's\n \/\/ variables initialized.\n\n this->time_deriv_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->time_deriv_function_string));\n\n this->mass_residual_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->mass_residual_function_string));\n\n this->constraint_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->constraint_function_string));\n }\n\n\n void ScalarODE::read_input_options( const GetPot& input )\n {\n this->time_deriv_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/time_deriv\",\n std::string(\"0\"));\n\n if (this->time_deriv_function_string == \"0\")\n std::cout << \"Warning! Zero time_deriv function specified!\" << std::endl;\n\n this->mass_residual_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/mass_residual\",\n std::string(\"0\"));\n\n if (this->mass_residual_function_string == \"0\")\n std::cout << \"Warning! Zero mass_residual function specified!\" << std::endl;\n\n this->constraint_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/constraint\",\n std::string(\"0\"));\n\n if (this->constraint_function_string == \"0\")\n std::cout << \"Warning! Zero constraint function specified!\" << std::endl;\n\n this->_epsilon = input(\"Physics\/\"+scalar_ode+\"\/epsilon\", 1e-6);\n\n this->_order = input(\"Physics\/\"+scalar_ode+\"\/order\", 1);\n\n _scalar_ode_var_name = input(\"Physics\/VariableNames\/scalar_ode\",\n scalar_ode_var_name_default);\n }\n\n\n void ScalarODE::init_context( AssemblyContext& context )\n {\n mass_residual_function->init_context(context);\n time_deriv_function->init_context(context);\n constraint_function->init_context(context);\n }\n\n\n void ScalarODE::nonlocal_time_derivative(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const std::vector<libMesh::dof_id_type>& dof_indices =\n context.get_dof_indices(_scalar_ode_var);\n\n const libMesh::Number time_deriv =\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += time_deriv;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number time_deriv_jacobian =\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n time_deriv_jacobian -=\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n time_deriv_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += time_deriv_jacobian;\n }\n\n return;\n }\n\n\n void ScalarODE::nonlocal_mass_residual(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const std::vector<libMesh::dof_id_type>& dof_indices =\n context.get_dof_indices(_scalar_ode_var);\n\n const libMesh::Number mass_res =\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += mass_res;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number mass_residual_jacobian =\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n mass_residual_jacobian -=\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n mass_residual_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += mass_residual_jacobian;\n }\n\n return;\n }\n\n\n void ScalarODE::nonlocal_constraint(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const std::vector<libMesh::dof_id_type>& dof_indices =\n context.get_dof_indices(_scalar_ode_var);\n\n const libMesh::Number constraint =\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += constraint;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number constraint_jacobian =\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n constraint_jacobian -=\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n constraint_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += constraint_jacobian;\n }\n\n return;\n }\n\n} \/\/ namespace GRINS\n<commit_msg>Get rid of unused dof_indices in ScalarODE<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/scalar_ode.h\"\n\n\/\/ GRINS\n#include \"grins\/generic_ic_handler.h\"\n#include \"grins\/variable_name_defaults.h\"\n\n\/\/ libMesh\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n\nnamespace GRINS\n{\n\n ScalarODE::ScalarODE( const std::string& physics_name, const GetPot& input )\n : Physics(physics_name, input), _order(1), _epsilon(1e-6)\n {\n this->read_input_options(input);\n\n this->_ic_handler = new GenericICHandler( physics_name, input );\n\n return;\n }\n\n ScalarODE::~ScalarODE()\n {\n return;\n }\n\n void ScalarODE::init_variables( libMesh::FEMSystem* system )\n {\n this->_scalar_ode_var = system->add_variable(_scalar_ode_var_name,\n libMesh::Order(this->_order),\n libMesh::SCALAR);\n }\n\n void ScalarODE::set_time_evolving_vars( libMesh::FEMSystem* system )\n {\n system->time_evolving(this->scalar_ode_var());\n\n \/\/ FIXME: this doesn't fit here at all, but it's the only time\n \/\/ we've clearly got a System to grab hold of with all it's\n \/\/ variables initialized.\n\n this->time_deriv_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->time_deriv_function_string));\n\n this->mass_residual_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->mass_residual_function_string));\n\n this->constraint_function.reset\n (new libMesh::ParsedFEMFunction<libMesh::Number>\n (*system, this->constraint_function_string));\n }\n\n\n void ScalarODE::read_input_options( const GetPot& input )\n {\n this->time_deriv_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/time_deriv\",\n std::string(\"0\"));\n\n if (this->time_deriv_function_string == \"0\")\n std::cout << \"Warning! Zero time_deriv function specified!\" << std::endl;\n\n this->mass_residual_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/mass_residual\",\n std::string(\"0\"));\n\n if (this->mass_residual_function_string == \"0\")\n std::cout << \"Warning! Zero mass_residual function specified!\" << std::endl;\n\n this->constraint_function_string =\n input(\"Physics\/\"+scalar_ode+\"\/constraint\",\n std::string(\"0\"));\n\n if (this->constraint_function_string == \"0\")\n std::cout << \"Warning! Zero constraint function specified!\" << std::endl;\n\n this->_epsilon = input(\"Physics\/\"+scalar_ode+\"\/epsilon\", 1e-6);\n\n this->_order = input(\"Physics\/\"+scalar_ode+\"\/order\", 1);\n\n _scalar_ode_var_name = input(\"Physics\/VariableNames\/scalar_ode\",\n scalar_ode_var_name_default);\n }\n\n\n void ScalarODE::init_context( AssemblyContext& context )\n {\n mass_residual_function->init_context(context);\n time_deriv_function->init_context(context);\n constraint_function->init_context(context);\n }\n\n\n void ScalarODE::nonlocal_time_derivative(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const libMesh::Number time_deriv =\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += time_deriv;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number time_deriv_jacobian =\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n time_deriv_jacobian -=\n (*time_deriv_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n time_deriv_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += time_deriv_jacobian;\n }\n\n return;\n }\n\n\n void ScalarODE::nonlocal_mass_residual(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const libMesh::Number mass_res =\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += mass_res;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number mass_residual_jacobian =\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n mass_residual_jacobian -=\n (*mass_residual_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n mass_residual_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += mass_residual_jacobian;\n }\n\n return;\n }\n\n\n void ScalarODE::nonlocal_constraint(bool compute_jacobian,\n\t\t\t\t AssemblyContext& context,\n\t\t\t\t CachedValues& \/* cache *\/ )\n {\n libMesh::DenseSubMatrix<libMesh::Number> &Kss =\n context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); \/\/ R_{s},{s}\n\n libMesh::DenseSubVector<libMesh::Number> &Fs =\n context.get_elem_residual(_scalar_ode_var); \/\/ R_{s}\n\n const libMesh::Number constraint =\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n\n Fs(0) += constraint;\n\n if (compute_jacobian && context.elem_solution_derivative)\n {\n \/\/ FIXME: we should replace this hacky FDM with a hook to the\n \/\/ AD fparser stuff\n libMesh::DenseSubVector<libMesh::Number> &Us =\n const_cast<libMesh::DenseSubVector<libMesh::Number>&>\n (context.get_elem_solution(_scalar_ode_var)); \/\/ U_{s}\n\n const libMesh::Number s = Us(0);\n Us(0) = s + this->_epsilon;\n libMesh::Number constraint_jacobian =\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n\n Us(0) = s - this->_epsilon;\n constraint_jacobian -=\n (*constraint_function)(context, libMesh::Point(0),\n context.get_time());\n \n Us(0) = s;\n constraint_jacobian \/= (2*this->_epsilon);\n\n libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);\n\n Kss(0,0) += constraint_jacobian;\n }\n\n return;\n }\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"<commit_before>#include <apollo\/builtin_types.hpp>\n#include <apollo\/error.hpp>\n#include <apollo\/lapi.hpp>\n#include <apollo\/detail\/light_key.hpp>\n\n#include <boost\/exception\/info.hpp>\n#include <boost\/throw_exception.hpp>\n\n\nnamespace apollo {\n\nstatic apollo::detail::light_key const msghKey = {};\n\nAPOLLO_API void set_error_msg_handler(lua_State* L)\n{\n lua_rawsetp(L, LUA_REGISTRYINDEX, &msghKey);\n}\n\nAPOLLO_API bool push_error_msg_handler(lua_State* L)\n{\n lua_rawgetp(L, LUA_REGISTRYINDEX, &msghKey);\n if lua_isnil(L, -1) {\n lua_pop(L, 1);\n return false;\n }\n return true;\n}\n\nAPOLLO_API void pcall(lua_State* L, int nargs, int nresults, int msgh)\n{\n int const r = lua_pcall(L, nargs, nresults, msgh);\n if (r != LUA_OK) {\n auto lua_msg = from_stack(L, -1, std::string(\"(no error message)\"));\n lua_pop(L, 1);\n BOOST_THROW_EXCEPTION(lua_api_error()\n << errinfo::lua_state(L)\n << errinfo::lua_msg(lua_msg)\n << errinfo::lua_error_code(r)\n << errinfo::msg(\"lua_pcall() failed\"));\n }\n}\n\nAPOLLO_API void pcall(lua_State* L, int nargs, int nresults)\n{\n int const msgh = push_error_msg_handler(L) ? lua_absindex(L, -nargs - 2) : 0;\n if (msgh)\n lua_insert(L, msgh); \/\/ move beneath arguments and function\n\n auto cleanup = [L, msgh]() -> void {\n if (msgh)\n lua_remove(L, msgh);\n };\n \n try { pcall(L, nargs, nresults, msgh); }\n catch (...) {\n cleanup();\n throw;\n }\n cleanup();\n}\n\n} \/\/ namespace apollo\n<commit_msg>Fix missing parantheses (macros...).<commit_after>#include <apollo\/builtin_types.hpp>\n#include <apollo\/error.hpp>\n#include <apollo\/lapi.hpp>\n#include <apollo\/detail\/light_key.hpp>\n\n#include <boost\/exception\/info.hpp>\n#include <boost\/throw_exception.hpp>\n\n\nnamespace apollo {\n\nstatic apollo::detail::light_key const msghKey = {};\n\nAPOLLO_API void set_error_msg_handler(lua_State* L)\n{\n lua_rawsetp(L, LUA_REGISTRYINDEX, &msghKey);\n}\n\nAPOLLO_API bool push_error_msg_handler(lua_State* L)\n{\n lua_rawgetp(L, LUA_REGISTRYINDEX, &msghKey);\n if (lua_isnil(L, -1)) {\n lua_pop(L, 1);\n return false;\n }\n return true;\n}\n\nAPOLLO_API void pcall(lua_State* L, int nargs, int nresults, int msgh)\n{\n int const r = lua_pcall(L, nargs, nresults, msgh);\n if (r != LUA_OK) {\n auto lua_msg = from_stack(L, -1, std::string(\"(no error message)\"));\n lua_pop(L, 1);\n BOOST_THROW_EXCEPTION(lua_api_error()\n << errinfo::lua_state(L)\n << errinfo::lua_msg(lua_msg)\n << errinfo::lua_error_code(r)\n << errinfo::msg(\"lua_pcall() failed\"));\n }\n}\n\nAPOLLO_API void pcall(lua_State* L, int nargs, int nresults)\n{\n int const msgh = push_error_msg_handler(L) ? lua_absindex(L, -nargs - 2) : 0;\n if (msgh)\n lua_insert(L, msgh); \/\/ move beneath arguments and function\n\n auto cleanup = [L, msgh]() -> void {\n if (msgh)\n lua_remove(L, msgh);\n };\n\n try { pcall(L, nargs, nresults, msgh); }\n catch (...) {\n cleanup();\n throw;\n }\n cleanup();\n}\n\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n\n#include \"logging.h\"\n#include \"stringprintf.h\"\n#include \"utils.h\"\n\nnamespace art {\n\nLogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)\n : data_(new LogMessageData(line, severity, error)) {\n const char* last_slash = strrchr(file, '\/');\n data_->file = (last_slash == NULL) ? file : last_slash + 1;\n}\n\nvoid LogMessage::LogLine(const char* message) {\n std::ostream& os(std::cerr);\n os << \"VDIWEFF\"[data_->severity] << ' '\n << StringPrintf(\"%5d %5d\", getpid(), ::art::GetTid()) << ' '\n << data_->file << ':' << data_->line_number << \"] \" << message << \"\\n\" << std::flush;\n}\n\n} \/\/ namespace art\n<commit_msg>Make strace(1) output more readable by using a single write(2) for logging.<commit_after>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n\n#include \"logging.h\"\n#include \"stringprintf.h\"\n#include \"utils.h\"\n\nnamespace art {\n\nLogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)\n : data_(new LogMessageData(line, severity, error)) {\n const char* last_slash = strrchr(file, '\/');\n data_->file = (last_slash == NULL) ? file : last_slash + 1;\n}\n\nvoid LogMessage::LogLine(const char* message) {\n char severity = \"VDIWEFF\"[data_->severity];\n fprintf(stderr, \"%c %5d %5d %s:%d] %s\\n\", severity, getpid(), ::art::GetTid(),\n data_->file, data_->line_number, message);\n}\n\n} \/\/ namespace art\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"swirl_user.h\"\n#include <fclaw2d_forestclaw.h>\n#include <fclaw2d_clawpatch.h>\n#include <fc2d_clawpack5.h>\n#include <fc2d_dummy.h>\n\n\/* Leave these in for demonstration purposes *\/\n#include <fclaw2d_output_ascii.h>\n#include <fclaw2d_regrid_default.h>\n\nstatic fclaw2d_vtable_t vt;\nstatic fc2d_clawpack5_vtable_t classic_claw;\n\nvoid swirl_link_solvers(fclaw2d_domain_t *domain)\n{\n fclaw2d_init_vtable(&vt);\n\n vt.problem_setup = &fc2d_clawpack5_setprob;\n\n vt.patch_setup = &swirl_patch_setup;\n vt.patch_initialize = &swirl_patch_initialize;\n vt.patch_physical_bc = &swirl_patch_physical_bc;\n vt.patch_single_step_update = &fc2d_clawpack5_update; \/* Includes b4step2 and src2 *\/\n\n vt.regrid_tag4refinement = &swirl_patch_tag4refinement;\n vt.fort_tag4refinement = &TAG4REFINEMENT;\n\n vt.regrid_tag4coarsening = &swirl_patch_tag4coarsening;\n vt.fort_tag4coarsening = &TAG4COARSENING;\n\n vt.write_header = &fclaw2d_output_header_ascii;\n vt.fort_write_header = &FCLAW2D_FORT_WRITE_HEADER;\n\n vt.patch_write_file = &fclaw2d_output_patch_ascii;\n vt.fort_write_file = &FCLAW2D_FORT_WRITE_FILE;\n\n fclaw2d_set_vtable(domain,&vt);\n\n \/* Needed for the clawpack5 package *\/\n classic_claw.qinit = &QINIT;\n classic_claw.bc2 = &BC2;\n classic_claw.setaux = &SETAUX;\n classic_claw.setprob = &SETPROB;\n classic_claw.b4step2 = &B4STEP2;\n classic_claw.rpn2 = &RPN2;\n classic_claw.rpt2 = &RPT2;\n\n fc2d_clawpack5_set_vtable(&classic_claw);\n\n}\n\n\nvoid swirl_patch_setup(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n \/* Dummy setup - use multiple libraries *\/\n fc2d_clawpack5_setaux(domain,this_patch,this_block_idx,this_patch_idx);\n fc2d_dummy_setup_patch(domain,this_patch,this_block_idx,this_patch_idx);\n}\n\nvoid swirl_patch_initialize(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n \/* This is an example of how to call the initialization routines explicitly\n This routine can be replaced by setting the appropriate fclaw2d_vtable_t,\n entry above, or by calling fclaw2d_clawpack5_qinit(...) from here. *\/\n\n int mx,my,mbc,meqn, maux, maxmx, maxmy;\n double xlower,ylower,dx,dy;\n double *q, *aux;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);\n fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);\n\n \/* Call to used defined, classic Clawpack (ver. 4.6) 'qinit' routine.\n Header is in the Clawpack package\n *\/\n maxmx = mx;\n maxmy = my;\n QINIT(&meqn,&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,q,&maux,aux);\n}\n\n\n\nvoid swirl_patch_physical_bc(fclaw2d_domain *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n double t,\n double dt,\n fclaw_bool intersects_bc[],\n fclaw_bool time_interp)\n{\n \/* This calls bc2 in swirl\/user_4.6; that file isn't changed but\n is included to show that both the local version of bc2.f and the\n clawpack5 library code can be included *\/\n fc2d_clawpack5_bc2(domain,this_patch,this_block_idx,this_patch_idx,\n t,dt,intersects_bc,time_interp);\n}\n\n\nint swirl_patch_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int blockno, int this_patch_idx,\n int initflag)\n{\n fclaw2d_vtable_t vt;\n int mx,my,mbc,meqn;\n double xlower,ylower,dx,dy;\n double *q;\n int tag_patch;\n const amr_options_t *amropt;\n double rt;\n\n amropt = get_domain_parms(domain);\n rt = amropt->refine_threshold;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);\n\n tag_patch = 0;\n vt.fort_tag4refinement(&mx,&my,&mbc,&meqn,&xlower,&ylower,\n &dx,&dy,&blockno, q,&rt,&initflag,\n &tag_patch);\n return tag_patch;\n}\n\nint swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno, int patchno)\n\n{\n fclaw2d_vtable_t vt;\n\n int mx,my,mbc,meqn;\n double xlower,ylower,dx,dy;\n double *q[4];\n int tag_patch,igrid;\n double coarsen_threshold;\n fclaw2d_patch_t *patch0;\n\n patch0 = &fine_patches[0];\n\n const amr_options_t *amropt;\n amropt = get_domain_parms(domain);\n\n coarsen_threshold = amropt->coarsen_threshold;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,patch0,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n for (igrid = 0; igrid < 4; igrid++)\n {\n fclaw2d_clawpatch_soln_data(domain,&fine_patches[igrid],&q[igrid],&meqn);\n }\n tag_patch = 0;\n vt.fort_tag4coarsening(&mx,&my,&mbc,&meqn,&xlower,&ylower,&dx,&dy,\n &blockno, q[0],q[1],q[2],q[3],\n &coarsen_threshold, &tag_patch);\n return tag_patch;\n\n}\n<commit_msg>slightly modified<commit_after>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"swirl_user.h\"\n#include <fclaw2d_forestclaw.h>\n#include <fclaw2d_clawpatch.h>\n#include <fc2d_clawpack5.h>\n#include <fc2d_dummy.h>\n\n\/* Leave these in for demonstration purposes *\/\n#include <fclaw2d_output_ascii.h>\n#include <fclaw2d_regrid_default.h>\n\nstatic fclaw2d_vtable_t vt;\nstatic fc2d_clawpack5_vtable_t classic_claw;\n\nvoid swirl_link_solvers(fclaw2d_domain_t *domain)\n{\n fclaw2d_init_vtable(&vt);\n\n vt.problem_setup = &fc2d_clawpack5_setprob;\n\n vt.patch_setup = &swirl_patch_setup;\n vt.patch_initialize = &swirl_patch_initialize;\n vt.patch_physical_bc = &swirl_patch_physical_bc;\n vt.patch_single_step_update = &fc2d_clawpack5_update; \/* Includes b4step2 and src2 *\/\n\n vt.regrid_tag4refinement = &swirl_patch_tag4refinement;\n vt.fort_tag4refinement = &TAG4REFINEMENT;\n\n vt.regrid_tag4coarsening = &swirl_patch_tag4coarsening;\n vt.fort_tag4coarsening = &TAG4COARSENING;\n\n vt.write_header = &fclaw2d_output_header_ascii;\n vt.fort_write_header = &FCLAW2D_FORT_WRITE_HEADER;\n\n vt.patch_write_file = &fclaw2d_output_patch_ascii;\n vt.fort_write_file = &FCLAW2D_FORT_WRITE_FILE;\n\n fclaw2d_set_vtable(domain,&vt);\n\n \/* Needed for the clawpack5 package *\/\n classic_claw.qinit = &QINIT;\n classic_claw.bc2 = &BC2;\n classic_claw.setaux = &SETAUX;\n classic_claw.setprob = &SETPROB;\n classic_claw.b4step2 = &B4STEP2;\n classic_claw.rpn2 = &RPN2;\n classic_claw.rpt2 = &RPT2;\n\n fc2d_clawpack5_set_vtable(&classic_claw);\n\n}\n\n\nvoid swirl_patch_setup(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n \/* Dummy setup - use multiple libraries *\/\n fc2d_clawpack5_setaux(domain,this_patch,this_block_idx,this_patch_idx);\n fc2d_dummy_setup_patch(domain,this_patch,this_block_idx,this_patch_idx);\n}\n\nvoid swirl_patch_initialize(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx)\n{\n \/* This is an example of how to call the initialization routines explicitly\n This routine can be replaced by setting the appropriate fclaw2d_vtable_t,\n entry above, or by calling fclaw2d_clawpack5_qinit(...) from here. *\/\n\n int mx,my,mbc,meqn, maux, maxmx, maxmy;\n double xlower,ylower,dx,dy;\n double *q, *aux;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);\n fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);\n\n \/* Call to used defined, classic Clawpack (ver. 4.6) 'qinit' routine.\n Header is in the Clawpack package\n *\/\n maxmx = mx;\n maxmy = my;\n \n QINIT(&meqn,&mbc,&mx,&my,&xlower,&ylower,&dx,&dy,q,&maux,aux);\n}\n\n\n\nvoid swirl_patch_physical_bc(fclaw2d_domain *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n double t,\n double dt,\n fclaw_bool intersects_bc[],\n fclaw_bool time_interp)\n{\n \/* This calls bc2 in swirl\/user_4.6; that file isn't changed but\n is included to show that both the local version of bc2.f and the\n clawpack5 library code can be included *\/\n fc2d_clawpack5_bc2(domain,this_patch,this_block_idx,this_patch_idx,\n t,dt,intersects_bc,time_interp);\n}\n\n\nint swirl_patch_tag4refinement(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int blockno, int this_patch_idx,\n int initflag)\n{\n fclaw2d_vtable_t vt;\n int mx,my,mbc,meqn;\n double xlower,ylower,dx,dy;\n double *q;\n int tag_patch;\n const amr_options_t *amropt;\n double rt;\n\n amropt = get_domain_parms(domain);\n rt = amropt->refine_threshold;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n fclaw2d_clawpatch_soln_data(domain,this_patch,&q,&meqn);\n\n tag_patch = 0;\n vt.fort_tag4refinement(&mx,&my,&mbc,&meqn,&xlower,&ylower,\n &dx,&dy,&blockno, q,&rt,&initflag,\n &tag_patch);\n return tag_patch;\n}\n\nint swirl_patch_tag4coarsening(fclaw2d_domain_t *domain,\n fclaw2d_patch_t *fine_patches,\n int blockno, int patchno)\n\n{\n fclaw2d_vtable_t vt;\n\n int mx,my,mbc,meqn;\n double xlower,ylower,dx,dy;\n double *q[4];\n int tag_patch,igrid;\n double coarsen_threshold;\n fclaw2d_patch_t *patch0;\n\n patch0 = &fine_patches[0];\n\n const amr_options_t *amropt;\n amropt = get_domain_parms(domain);\n\n coarsen_threshold = amropt->coarsen_threshold;\n\n vt = fclaw2d_get_vtable(domain);\n\n fclaw2d_clawpatch_grid_data(domain,patch0,&mx,&my,&mbc,\n &xlower,&ylower,&dx,&dy);\n\n for (igrid = 0; igrid < 4; igrid++)\n {\n fclaw2d_clawpatch_soln_data(domain,&fine_patches[igrid],&q[igrid],&meqn);\n }\n tag_patch = 0;\n vt.fort_tag4coarsening(&mx,&my,&mbc,&meqn,&xlower,&ylower,&dx,&dy,\n &blockno, q[0],q[1],q[2],q[3],\n &coarsen_threshold, &tag_patch);\n return tag_patch;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\n * @brief Read key sets using yaml-cpp\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"read.hpp\"\n#include \"log.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include <kdb.hpp>\n#include <kdblogger.h>\n#include <kdbplugin.h>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace kdb;\n\nnamespace\n{\n\/**\n * @brief This function converts a given number to an array base name.\n *\n * @param index This number specifies the index of the array entry.\n *\n * @return A string representing the given indices as Elektra array name.\n *\/\nstring indexToArrayBaseName (uintmax_t const index)\n{\n\tsize_t digits = 1;\n\n\tfor (uintmax_t value = index; value > 9; digits++)\n\t{\n\t\tvalue \/= 10;\n\t}\n\n\treturn \"#\" + string (digits - 1, '_') + to_string (index);\n}\n\n\/**\n * @brief This function creates a new key from the given parameters.\n *\n * @param name This string specifies the postfix of the name of the key produced by this function.\n * @param parent This key specifies the prefix of the name of the key produced by this function.\n *\n * @returns The function returns a new key that combines the name of the parent key and `name`.\n *\/\nKey newKey (string const & name, Key const & parent)\n{\n\tELEKTRA_LOG_DEBUG (\"Add new key with base name “%s”\", name.c_str ());\n\n\tKey key{ parent.getFullName (), KEY_BINARY, KEY_END };\n\tkey.addBaseName (name);\n\n\treturn key;\n}\n\n\/**\n * @brief This function creates a new array key from the given parameters.\n *\n * @param arrayKey This argument specifies the key that represents the root of the array.\n * @param index This parameter specifies the index of the array key this function creates.\n *\n * @returns The function returns a new key that is part of the array represented by `arrayKey`.\n *\/\nKey newArrayKey (Key & arrayKey, uintmax_t const index)\n{\n\tELEKTRA_LOG_DEBUG (\"Add new array element to array parent “%s”\", arrayKey.getName ().c_str ());\n\n\tKey newKey{ arrayKey.getName (), KEY_BINARY, KEY_END };\n\tnewKey.addBaseName (indexToArrayBaseName (index));\n\tarrayKey.setMeta (\"array\", newKey.getBaseName ());\n\n\treturn newKey;\n}\n\n\/**\n * @brief Add metadata saved in a YAML map to the specified key\n *\n * @param key This parameter saves the key to which this function should add the metadata stored in `node`.\n * @param node This YAML node stores a map containing metadata.\n *\/\nvoid addMetadata (Key & key, YAML::Node const & node)\n{\n\tfor (auto & element : node)\n\t{\n\t\tauto metakey = element.first.as<string> ();\n\t\tauto metavalue = element.second.IsNull () ? \"\" : element.second.as<string> ();\n\t\tELEKTRA_LOG_DEBUG (\"Add metakey “%s: %s”\", metakey.c_str (), metavalue.c_str ());\n\t\tkey.setMeta (metakey, metavalue);\n\t}\n}\n\n\/**\n * @brief Create a key containing a (possibly empty) value.\n *\n * @param node This YAML node stores the data that should be converted to a new `Key`.\n * @param name This text specifies the name of the key this function creates.\n *\n * @return A new key containing the data specified in `node`\n *\/\nKey createLeafKey (YAML::Node const & node, string const & name)\n{\n\tKey key{ name, KEY_BINARY, KEY_END };\n\tif (!node.IsNull ())\n\t{\n\t\tauto value = node.as<string> ();\n\t\tif (value == \"true\" || value == \"false\")\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tkey.set<bool> (node.as<bool> ());\n\t\t\t}\n\t\t\tcatch (YAML::BadConversion const &)\n\t\t\t{\n\t\t\t\tkey.set<string> (value); \/\/ Save value as string, if `node` is a quoted scalar\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tkey.set<string> (value);\n\t\t}\n\t}\n\tif (node.Tag () == \"tag:yaml.org,2002:binary\")\n\t{\n\t\tELEKTRA_LOG_DEBUG (\"Set metadata type of key to binary\");\n\t\tkey.setMeta (\"type\", \"binary\");\n\t}\n\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (),\n\t\t\t key.getBinarySize () == 0 ? \"NULL\" : key.isBinary () ? \"binary value!\" : key.get<string> ().c_str ());\n\treturn key;\n}\n\n\/**\n * @brief Convert the key value of a YAML meta node to a key\n *\n * @param node This YAML meta node stores the data this function stores in the returned key\n * @param parent This key stores the prefix for the key name\n *\n * @return A key representing the key value stored in `node`\n *\/\nKey convertMetaNodeToKey (YAML::Node const & node, Key & parent)\n{\n\tauto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } :\n\t\t\t\t Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END };\n\tELEKTRA_LOG_DEBUG (\"Add key “%s”: “%s”\", key.getName ().c_str (),\n\t\t\t key.getBinarySize () == 0 ? \"NULL\" : key.isString () ? key.getString ().c_str () : \"binary value!\");\n\treturn key;\n}\n\n\/**\n * @brief Convert a YAML node to a key set\n *\n * @param node This YAML node stores the data that should be added to the keyset `mappings`\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the prefix for the key name\n *\/\nvoid convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent)\n{\n\tif (node.Tag () == \"!elektra\/meta\")\n\t{\n\t\tauto key = convertMetaNodeToKey (node, parent);\n\t\tmappings.append (key);\n\t\taddMetadata (key, node[1]);\n\t}\n\telse if (node.IsScalar () || node.IsNull ())\n\t{\n\t\tauto key = createLeafKey (node, parent.getFullName ());\n\t\tmappings.append (key);\n\t}\n\telse if (node.IsMap ())\n\t{\n\t\tfor (auto element : node)\n\t\t{\n\t\t\tKey key = newKey (element.first.as<string> (), parent);\n\t\t\tconvertNodeToKeySet (element.second, mappings, key);\n\t\t}\n\t}\n\telse if (node.IsSequence ())\n\t{\n\t\tuintmax_t index = 0;\n\t\tuintmax_t lastIndex = 0;\n\t\tparent.setMeta (\"array\", \"\");\n\t\tfor (auto const & element : node)\n\t\t{\n\t\t\tif (lastIndex == UINTMAX_MAX)\n\t\t\t{\n\t\t\t\tKey key = newArrayKey (parent, lastIndex);\n\t\t\t\tthrow std::overflow_error (\"Unable to add element after “\" + key.getName () + \"” in array “\" +\n\t\t\t\t\t\t\t parent.getName () + \"”\");\n\t\t\t}\n\t\t\tKey key = newArrayKey (parent, index);\n\t\t\tconvertNodeToKeySet (element, mappings, key);\n\t\t\tlastIndex = index++;\n\t\t}\n\t\tmappings.append (parent); \/\/ Update array metadata\n\t}\n}\n} \/\/ end namespace\n\n\/**\n * @brief Read a YAML file and add the resulting data to a given key set\n *\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the path to the YAML data file that should be read\n *\/\nvoid yamlcpp::yamlRead (KeySet & mappings, Key & parent)\n{\n\tYAML::Node config = YAML::LoadFile (parent.getString ());\n\n\tELEKTRA_LOG_DEBUG (\"Read file “%s”\", parent.getString ().c_str ());\n\n#ifdef HAVE_LOGGER\n\tostringstream data;\n\tdata << config;\n\n\tELEKTRA_LOG_DEBUG (\"Read Data:\");\n\tELEKTRA_LOG_DEBUG (\"——————————\");\n\n\tistringstream stream (data.str ());\n\tfor (string line; std::getline (stream, line);)\n\t{\n\t\tELEKTRA_LOG_DEBUG (\"%s\", line.c_str ());\n\t}\n\n\tELEKTRA_LOG_DEBUG (\"——————————\");\n#endif\n\n\tKey parentWithoutValue{ parent.getName (), KEY_BINARY, KEY_END }; \/\/ We do **not** want to save the filename inside the read key set\n\tconvertNodeToKeySet (config, mappings, parentWithoutValue);\n\n#ifdef HAVE_LOGGER\n\tELEKTRA_LOG_DEBUG (\"Converted keys:\");\n\tlogKeySet (mappings);\n#endif\n}\n<commit_msg>YAML CPP: Use explicit imports in read code<commit_after>\/**\n * @file\n *\n * @brief Read key sets using yaml-cpp\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"read.hpp\"\n#include \"log.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include <kdb.hpp>\n#include <kdblogger.h>\n#include <kdbplugin.h>\n\n#include <sstream>\n\nnamespace\n{\n\nusing std::istringstream;\nusing std::ostringstream;\nusing std::string;\nusing std::to_string;\n\nusing kdb::Key;\nusing kdb::KeySet;\n\n\/**\n * @brief This function converts a given number to an array base name.\n *\n * @param index This number specifies the index of the array entry.\n *\n * @return A string representing the given indices as Elektra array name.\n *\/\nstring indexToArrayBaseName (uintmax_t const index)\n{\n\tsize_t digits = 1;\n\n\tfor (uintmax_t value = index; value > 9; digits++)\n\t{\n\t\tvalue \/= 10;\n\t}\n\n\treturn \"#\" + string (digits - 1, '_') + to_string (index);\n}\n\n\/**\n * @brief This function creates a new key from the given parameters.\n *\n * @param name This string specifies the postfix of the name of the key produced by this function.\n * @param parent This key specifies the prefix of the name of the key produced by this function.\n *\n * @returns The function returns a new key that combines the name of the parent key and `name`.\n *\/\nKey newKey (string const & name, Key const & parent)\n{\n\tELEKTRA_LOG_DEBUG (\"Add new key with base name “%s”\", name.c_str ());\n\n\tKey key{ parent.getFullName (), KEY_BINARY, KEY_END };\n\tkey.addBaseName (name);\n\n\treturn key;\n}\n\n\/**\n * @brief This function creates a new array key from the given parameters.\n *\n * @param arrayKey This argument specifies the key that represents the root of the array.\n * @param index This parameter specifies the index of the array key this function creates.\n *\n * @returns The function returns a new key that is part of the array represented by `arrayKey`.\n *\/\nKey newArrayKey (Key & arrayKey, uintmax_t const index)\n{\n\tELEKTRA_LOG_DEBUG (\"Add new array element to array parent “%s”\", arrayKey.getName ().c_str ());\n\n\tKey newKey{ arrayKey.getName (), KEY_BINARY, KEY_END };\n\tnewKey.addBaseName (indexToArrayBaseName (index));\n\tarrayKey.setMeta (\"array\", newKey.getBaseName ());\n\n\treturn newKey;\n}\n\n\/**\n * @brief Add metadata saved in a YAML map to the specified key\n *\n * @param key This parameter saves the key to which this function should add the metadata stored in `node`.\n * @param node This YAML node stores a map containing metadata.\n *\/\nvoid addMetadata (Key & key, YAML::Node const & node)\n{\n\tfor (auto & element : node)\n\t{\n\t\tauto metakey = element.first.as<string> ();\n\t\tauto metavalue = element.second.IsNull () ? \"\" : element.second.as<string> ();\n\t\tELEKTRA_LOG_DEBUG (\"Add metakey “%s: %s”\", metakey.c_str (), metavalue.c_str ());\n\t\tkey.setMeta (metakey, metavalue);\n\t}\n}\n\n\/**\n * @brief Create a key containing a (possibly empty) value.\n *\n * @param node This YAML node stores the data that should be converted to a new `Key`.\n * @param name This text specifies the name of the key this function creates.\n *\n * @return A new key containing the data specified in `node`\n *\/\nKey createLeafKey (YAML::Node const & node, string const & name)\n{\n\tKey key{ name, KEY_BINARY, KEY_END };\n\tif (!node.IsNull ())\n\t{\n\t\tauto value = node.as<string> ();\n\t\tif (value == \"true\" || value == \"false\")\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tkey.set<bool> (node.as<bool> ());\n\t\t\t}\n\t\t\tcatch (YAML::BadConversion const &)\n\t\t\t{\n\t\t\t\tkey.set<string> (value); \/\/ Save value as string, if `node` is a quoted scalar\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tkey.set<string> (value);\n\t\t}\n\t}\n\tif (node.Tag () == \"tag:yaml.org,2002:binary\")\n\t{\n\t\tELEKTRA_LOG_DEBUG (\"Set metadata type of key to binary\");\n\t\tkey.setMeta (\"type\", \"binary\");\n\t}\n\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (),\n\t\t\t key.getBinarySize () == 0 ? \"NULL\" : key.isBinary () ? \"binary value!\" : key.get<string> ().c_str ());\n\treturn key;\n}\n\n\/**\n * @brief Convert the key value of a YAML meta node to a key\n *\n * @param node This YAML meta node stores the data this function stores in the returned key\n * @param parent This key stores the prefix for the key name\n *\n * @return A key representing the key value stored in `node`\n *\/\nKey convertMetaNodeToKey (YAML::Node const & node, Key & parent)\n{\n\tauto key = node[0].IsNull () ? Key{ parent.getFullName (), KEY_BINARY, KEY_END } :\n\t\t\t\t Key{ parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END };\n\tELEKTRA_LOG_DEBUG (\"Add key “%s”: “%s”\", key.getName ().c_str (),\n\t\t\t key.getBinarySize () == 0 ? \"NULL\" : key.isString () ? key.getString ().c_str () : \"binary value!\");\n\treturn key;\n}\n\n\/**\n * @brief Convert a YAML node to a key set\n *\n * @param node This YAML node stores the data that should be added to the keyset `mappings`\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the prefix for the key name\n *\/\nvoid convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent)\n{\n\tif (node.Tag () == \"!elektra\/meta\")\n\t{\n\t\tauto key = convertMetaNodeToKey (node, parent);\n\t\tmappings.append (key);\n\t\taddMetadata (key, node[1]);\n\t}\n\telse if (node.IsScalar () || node.IsNull ())\n\t{\n\t\tauto key = createLeafKey (node, parent.getFullName ());\n\t\tmappings.append (key);\n\t}\n\telse if (node.IsMap ())\n\t{\n\t\tfor (auto element : node)\n\t\t{\n\t\t\tKey key = newKey (element.first.as<string> (), parent);\n\t\t\tconvertNodeToKeySet (element.second, mappings, key);\n\t\t}\n\t}\n\telse if (node.IsSequence ())\n\t{\n\t\tuintmax_t index = 0;\n\t\tuintmax_t lastIndex = 0;\n\t\tparent.setMeta (\"array\", \"\");\n\t\tfor (auto const & element : node)\n\t\t{\n\t\t\tif (lastIndex == UINTMAX_MAX)\n\t\t\t{\n\t\t\t\tKey key = newArrayKey (parent, lastIndex);\n\t\t\t\tthrow std::overflow_error (\"Unable to add element after “\" + key.getName () + \"” in array “\" +\n\t\t\t\t\t\t\t parent.getName () + \"”\");\n\t\t\t}\n\t\t\tKey key = newArrayKey (parent, index);\n\t\t\tconvertNodeToKeySet (element, mappings, key);\n\t\t\tlastIndex = index++;\n\t\t}\n\t\tmappings.append (parent); \/\/ Update array metadata\n\t}\n}\n} \/\/ end namespace\n\n\/**\n * @brief Read a YAML file and add the resulting data to a given key set\n *\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the path to the YAML data file that should be read\n *\/\nvoid yamlcpp::yamlRead (KeySet & mappings, Key & parent)\n{\n\tYAML::Node config = YAML::LoadFile (parent.getString ());\n\n\tELEKTRA_LOG_DEBUG (\"Read file “%s”\", parent.getString ().c_str ());\n\n#ifdef HAVE_LOGGER\n\tostringstream data;\n\tdata << config;\n\n\tELEKTRA_LOG_DEBUG (\"Read Data:\");\n\tELEKTRA_LOG_DEBUG (\"——————————\");\n\n\tistringstream stream (data.str ());\n\tfor (string line; std::getline (stream, line);)\n\t{\n\t\tELEKTRA_LOG_DEBUG (\"%s\", line.c_str ());\n\t}\n\n\tELEKTRA_LOG_DEBUG (\"——————————\");\n#endif\n\n\tKey parentWithoutValue{ parent.getName (), KEY_BINARY, KEY_END }; \/\/ We do **not** want to save the filename inside the read key set\n\tconvertNodeToKeySet (config, mappings, parentWithoutValue);\n\n#ifdef HAVE_LOGGER\n\tELEKTRA_LOG_DEBUG (\"Converted keys:\");\n\tlogKeySet (mappings);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp\n *\n * contains main function\n *\n *\/\n\n#include \"clutter.hpp\"\n\nint main(int argc, char* argv[])\n{\n\tinitPaths();\n\tinit_screen(\"Particle-Viewer\");\n\tcam.initGL();\n\tpart = new Particle();\n\tsetupGLStuff();\n\tsetupScreenFBO();\n\n\twhile (!glfwWindowShouldClose(window))\n\t{\n\n\t\tglfwPollEvents();\n\t\tcam.Move();\n\t\t\/\/readInput(event);\n\n\t\tbeforeDraw();\n\t\tdrawFunct();\n\t\tcam.RenderSphere();\n\t\tdrawFBO();\n\t\t\/\/render GUI\n\n\t\tglfwSwapBuffers(window);\n\n\t\tif(set->frames > 1)\t\t\t{ set->readPosVelFile(curFrame,part,false);}\n\t\tif(set->isPlaying)\t\t\t{ curFrame++;}\n\t\tif(curFrame > set->frames)\t{ curFrame = set->frames;}\n\t\tminor_keyCallback();\n\t\tif (curFrame < 0)\t\t\t{ curFrame = 0;}\n\t}\n\tcleanup();\n\treturn 0;\n}\n\nvoid beforeDraw()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglBindFramebuffer(GL_FRAMEBUFFER, framebuffer);\n\tcam.update(deltaTime);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tupDeltaTime();\n\tview = cam.setupCam();\n\n}\n\nvoid drawFunct()\n{\n\tset->getCOM(curFrame, com);\n\tcam.setSphereCenter(com);\n\tsphereShader.Use();\n\tpart->pushVBO();\n\tglBindVertexArray(circleVAO);\n\tglBindBuffer(GL_ARRAY_BUFFER, part->instanceVBO);\n\tglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\n\tglUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, \"view\"), 1, GL_FALSE, glm::value_ptr(view));\n\tglUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, \"projection\"), 1, GL_FALSE, glm::value_ptr(cam.projection));\n\tglUniform1f(glGetUniformLocation(sphereShader.Program, \"radius\"), sphereRadius);\n\tglUniform1f(glGetUniformLocation(sphereShader.Program, \"scale\"), sphereScale);\n\tglDrawArraysInstanced(GL_POINTS,0,1,part->n);\n\tglBindVertexArray(0);\n\t\/\/take screenshot\n\tif(set->isPlaying && isRecording)\n\t{\n\t\tglReadPixels(0,0,(int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);\n\t\tfor (int i = 0; i < SCREEN_WIDTH * 3; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < SCREEN_HEIGHT; j++)\n\t\t\t{\n\t\t\t\tpixels2[i + SCREEN_WIDTH* 3 * j] = pixels[i+ SCREEN_WIDTH* 3 * (SCREEN_HEIGHT - j)];\n\t\t\t}\n\t\t}\n\t\t\/\/\n\t\tif(!stbi_write_tga(std::string(recordFolder+\"\/\" + std::to_string(curFrame) + \".tga\").c_str(), (int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, 3, pixels2))\n\t\t{\n\t\t\tif(imageError < imageErrorMax)\n\t\t\t{\n\t\t\t\timageError++;\n\t\t\t\tstd::cout << \"Unable to save image: Error \"<< imageError << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"Max Image Error Count Reached! Ending Recording!\"<< std::endl;\n\t\t\t\tisRecording = false;\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\/*\n * Sets up the basic OpenGL stuff.\n *\/\nvoid setupGLStuff()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_PROGRAM_POINT_SIZE );\n\tglEnable(GL_MULTISAMPLE);\n\tsphereShader = Shader(sphereVertexShader.c_str(),sphereFragmentShader.c_str());\n\tscreenShader = Shader(screenVertexShader.c_str(),screenFragmentShader.c_str());\n\t\/* Sets up sphere array in OpenGL *\/\n\tglGenVertexArrays(1, &circleVAO);\n\tglGenBuffers(1, &circleVBO);\n\tglBindVertexArray(circleVAO);\n\tglBindBuffer(GL_ARRAY_BUFFER, circleVBO);\n\n\tglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);\n\tglEnableVertexAttribArray(0);\n\tpart->setUpInstanceArray();\n\tglBindVertexArray(0);\n\t\/* ============================== *\/\n}\n\n\/*\n * Increment \/ decrement current frame by x amount.\n *\/\nvoid seekFrame(int frame, bool isForward)\n{\n\tif(isForward)\t{ curFrame += frame;}\n\telse\t\t\t{ curFrame -= frame;}\n\n}\n\nvoid cleanup()\n{\n\tdelete part;\n\tdelete[] pixels;\n\tdelete[] pixels2;\n\tglDeleteFramebuffers(1, &framebuffer);\n}\n<commit_msg>Last feature commit<commit_after>\/*\n * main.cpp\n *\n * contains main function\n *\n *\/\n\n#include \"clutter.hpp\"\n\nint main(int argc, char* argv[])\n{\n\tinitPaths();\n\tinit_screen(\"Particle-Viewer\");\n\tcam.initGL();\n\tpart = new Particle();\n\tsetupGLStuff();\n\tsetupScreenFBO();\n\n\twhile (!glfwWindowShouldClose(window))\n\t{\n\n\t\tglfwPollEvents();\n\t\tcam.Move();\n\t\t\/\/readInput(event);\n\n\t\tbeforeDraw();\n\t\tdrawFunct();\n\t\tcam.RenderSphere();\n\t\tdrawFBO();\n\t\t\/\/render GUI\n\n\t\tglfwSwapBuffers(window);\n\n\t\tif(set->frames > 1)\t\t\t{ set->readPosVelFile(curFrame,part,false);}\n\t\tif(set->isPlaying)\t\t\t{ curFrame++;}\n\t\tif(curFrame > set->frames)\t{ curFrame = set->frames;}\n\t\tminor_keyCallback();\n\t\tif (curFrame < 0)\t\t\t{ curFrame = 0;}\n\t}\n\tcleanup();\n\treturn 0;\n}\n\nvoid beforeDraw()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglBindFramebuffer(GL_FRAMEBUFFER, framebuffer);\n\tcam.update(deltaTime);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tupDeltaTime();\n\tview = cam.setupCam();\n\n}\n\nvoid drawFunct()\n{\n\tset->getCOM(curFrame, com);\n\tcam.setSphereCenter(com);\n\tsphereShader.Use();\n\tpart->pushVBO();\n\tglBindVertexArray(circleVAO);\n\tglBindBuffer(GL_ARRAY_BUFFER, part->instanceVBO);\n\tglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\n\tglUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, \"view\"), 1, GL_FALSE, glm::value_ptr(view));\n\tglUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, \"projection\"), 1, GL_FALSE, glm::value_ptr(cam.projection));\n\tglUniform1f(glGetUniformLocation(sphereShader.Program, \"radius\"), sphereRadius);\n\tglUniform1f(glGetUniformLocation(sphereShader.Program, \"scale\"), sphereScale);\n\tglDrawArraysInstanced(GL_POINTS,0,1,part->n);\n\tglBindVertexArray(0);\n\t\/\/take screenshot\n\t\/\/std::cout << \"FPS: \" << 1\/deltaTime << std::endl; \/\/get FPS\n\tif(set->isPlaying && isRecording)\n\t{\n\t\tglReadPixels(0,0,(int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);\n\t\tfor (int i = 0; i < SCREEN_WIDTH * 3; i++)\n\t\t{\n\t\t\tfor(int j = 0; j < SCREEN_HEIGHT; j++)\n\t\t\t{\n\t\t\t\tpixels2[i + SCREEN_WIDTH* 3 * j] = pixels[i+ SCREEN_WIDTH* 3 * (SCREEN_HEIGHT - j)];\n\t\t\t}\n\t\t}\n\n\t\tif(!stbi_write_tga(std::string(recordFolder+\"\/\" + std::to_string(curFrame) + \".tga\").c_str(), (int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, 3, pixels2))\n\t\t{\n\t\t\tif(imageError < imageErrorMax)\n\t\t\t{\n\t\t\t\timageError++;\n\t\t\t\tstd::cout << \"Unable to save image: Error \"<< imageError << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"Max Image Error Count Reached! Ending Recording!\"<< std::endl;\n\t\t\t\tisRecording = false;\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\/*\n * Sets up the basic OpenGL stuff.\n *\/\nvoid setupGLStuff()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_PROGRAM_POINT_SIZE );\n\tglEnable(GL_MULTISAMPLE);\n\tsphereShader = Shader(sphereVertexShader.c_str(),sphereFragmentShader.c_str());\n\tscreenShader = Shader(screenVertexShader.c_str(),screenFragmentShader.c_str());\n\t\/* Sets up sphere array in OpenGL *\/\n\tglGenVertexArrays(1, &circleVAO);\n\tglGenBuffers(1, &circleVBO);\n\tglBindVertexArray(circleVAO);\n\tglBindBuffer(GL_ARRAY_BUFFER, circleVBO);\n\n\tglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);\n\tglEnableVertexAttribArray(0);\n\tpart->setUpInstanceArray();\n\tglBindVertexArray(0);\n\t\/* ============================== *\/\n}\n\n\/*\n * Increment \/ decrement current frame by x amount.\n *\/\nvoid seekFrame(int frame, bool isForward)\n{\n\tif(isForward)\t{ curFrame += frame;}\n\telse\t\t\t{ curFrame -= frame;}\n\n}\n\nvoid cleanup()\n{\n\tdelete part;\n\tdelete[] pixels;\n\tdelete[] pixels2;\n\tglDeleteFramebuffers(1, &framebuffer);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <sstream>\n#include <vector>\n#include <vector>\n#include <map>\n\n#include \"util\/SequencedMap.h\"\n#include \"util\/Sysout.h\"\n#include \"util\/Sysin.h\"\n\n#include \"Grammar.h\"\n\nSequencedMap<std::string, std::string> cmdByAlias;\n\nbool alistatify(std::vector<std::string>* inputWords)\n{\n \/\/ If we have no words\n if(inputWords->size() == 0)\n {\n \/\/ Then obviously it cannot match anything\n\n \/\/ Return unsuccessful\n return false;\n }\n\n \/\/ Loop through all commands\n for(unsigned int cait = 0; cait < cmdByAlias.size(); ++ cait)\n {\n \/\/ Info\n Sysout::print(\" Testing for \");\n Sysout::println(cmdByAlias.first(cait));\n\n \/\/ Split the command's alias into a vector of individual words\n std::vector<std::string> cmdsWords;\n Sysin::splitWords(cmdByAlias.first(cait), &cmdsWords);\n\n \/\/ Check if we have enough input for it to be possible\n if(inputWords->size() < cmdsWords.size())\n {\n \/\/ [It cannot be this command]\n\n \/\/ Skip this one\n continue;\n }\n\n \/\/ Keeps track if the command comparison proves the input to start with the needed command\n bool commandMatches = true;\n\n \/\/ Get iterator for command words\n std::vector<std::string>::iterator commandWordFocus = cmdsWords.begin();\n\n \/\/ Iterate through the input words parallel\n std::vector<std::string>::iterator inputWordFocus = inputWords->begin();\n\n \/\/ Iterate through the command words\n while(commandWordFocus != cmdsWords.end())\n {\n \/\/ Check if this word is different\n if(*commandWordFocus != *inputWordFocus)\n {\n \/\/ [It is not]\n\n \/\/ The command therefore does not match\n commandMatches = false;\n\n \/\/ Stop checking, because it cannot possibly be it anymore\n break;\n }\n\n \/\/ Next\n ++ commandWordFocus;\n ++ inputWordFocus;\n }\n\n \/\/ If the command matches\n if(commandMatches)\n {\n \/\/ Loop through that command's sentence structures\n \/\/ To see if they fit.\n\n \/\/ Return successful\n return true;\n }\n }\n\n \/\/ [None of the commands matched]\n\n \/\/ Return unsuccessful\n return false;\n}\n\nint main()\n{\n \/\/ Register commands\n cmdByAlias.append(\"eat\", \"MUNCH!\");\n cmdByAlias.append(\"two words\", \"DOUBLE TROUBLE!\");\n cmdByAlias.append(\"take a dump\", \"PLOP!\");\n cmdByAlias.append(\"take\", \"KLEPTOMANIA!\");\n\n \/\/ Legend\n Sysout::println(\"Fuzzy Computing Machine\");\n\n \/\/ Running\n bool running = true;\n\n \/\/ Last input vector\n std::vector<std::string> lastInput;\n\n \/\/ While running, run!\n while(running)\n {\n Sysout::println(\"Enter something:\");\n\n Sysout::print(\"FCM:\\\\>\");\n Sysin::getWords(&lastInput);\n Sysout::println();\n\n Sysout::print(\"You entered:\");\n Sysout::println(&lastInput);\n\n Sysout::println(\"Trying to recognize command...\");\n\n alistatify(&lastInput);\n\n Sysout::println();\n }\n\n \/\/ Died quietly\n return 0;\n}\n<commit_msg>Comment brackets<commit_after>#include <string>\n#include <sstream>\n#include <vector>\n#include <vector>\n#include <map>\n\n#include \"util\/SequencedMap.h\"\n#include \"util\/Sysout.h\"\n#include \"util\/Sysin.h\"\n\n#include \"Grammar.h\"\n\nSequencedMap<std::string, std::string> cmdByAlias;\n\nbool alistatify(std::vector<std::string>* inputWords)\n{\n \/\/ If we have no words\n if(inputWords->size() == 0)\n {\n \/\/ [Then obviously it cannot match anything]\n\n \/\/ Return unsuccessful\n return false;\n }\n\n \/\/ Loop through all commands\n for(unsigned int cait = 0; cait < cmdByAlias.size(); ++ cait)\n {\n \/\/ Info\n Sysout::print(\" Testing for \");\n Sysout::println(cmdByAlias.first(cait));\n\n \/\/ Split the command's alias into a vector of individual words\n std::vector<std::string> cmdsWords;\n Sysin::splitWords(cmdByAlias.first(cait), &cmdsWords);\n\n \/\/ Check if we have enough input for it to be possible\n if(inputWords->size() < cmdsWords.size())\n {\n \/\/ [It cannot be this command]\n\n \/\/ Skip this one\n continue;\n }\n\n \/\/ Keeps track if the command comparison proves the input to start with the needed command\n bool commandMatches = true;\n\n \/\/ Get iterator for command words\n std::vector<std::string>::iterator commandWordFocus = cmdsWords.begin();\n\n \/\/ Iterate through the input words parallel\n std::vector<std::string>::iterator inputWordFocus = inputWords->begin();\n\n \/\/ Iterate through the command words\n while(commandWordFocus != cmdsWords.end())\n {\n \/\/ Check if this word is different\n if(*commandWordFocus != *inputWordFocus)\n {\n \/\/ [It is not]\n\n \/\/ The command therefore does not match\n commandMatches = false;\n\n \/\/ Stop checking, because it cannot possibly be it anymore\n break;\n }\n\n \/\/ Next\n ++ commandWordFocus;\n ++ inputWordFocus;\n }\n\n \/\/ If the command matches\n if(commandMatches)\n {\n \/\/ Loop through that command's sentence structures\n \/\/ To see if they fit.\n\n \/\/ Return successful\n return true;\n }\n }\n\n \/\/ [None of the commands matched]\n\n \/\/ Return unsuccessful\n return false;\n}\n\nint main()\n{\n \/\/ Register commands\n cmdByAlias.append(\"eat\", \"MUNCH!\");\n cmdByAlias.append(\"two words\", \"DOUBLE TROUBLE!\");\n cmdByAlias.append(\"take a dump\", \"PLOP!\");\n cmdByAlias.append(\"take\", \"KLEPTOMANIA!\");\n\n \/\/ Legend\n Sysout::println(\"Fuzzy Computing Machine\");\n\n \/\/ Running\n bool running = true;\n\n \/\/ Last input vector\n std::vector<std::string> lastInput;\n\n \/\/ While running, run!\n while(running)\n {\n Sysout::println(\"Enter something:\");\n\n Sysout::print(\"FCM:\\\\>\");\n Sysin::getWords(&lastInput);\n Sysout::println();\n\n Sysout::print(\"You entered:\");\n Sysout::println(&lastInput);\n\n Sysout::println(\"Trying to recognize command...\");\n\n alistatify(&lastInput);\n\n Sysout::println();\n }\n\n \/\/ Died quietly\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"GamepadWin.h\"\n#include \"Engine.h\"\n#include \"Utils.h\"\n\nnamespace ouzel\n{\n GamepadWin::GamepadWin(int32_t playerIndex):\n _playerIndex(playerIndex)\n {\n memset(&_state, 0, sizeof(XINPUT_STATE));\n }\n\n void GamepadWin::update(XINPUT_STATE const& state)\n {\n if (state.dwPacketNumber > _state.dwPacketNumber)\n {\n checkButton(state, XINPUT_GAMEPAD_DPAD_UP, GamepadButton::DPAD_UP);\n checkButton(state, XINPUT_GAMEPAD_DPAD_DOWN, GamepadButton::DPAD_DOWN);\n checkButton(state, XINPUT_GAMEPAD_DPAD_LEFT, GamepadButton::DPAD_LEFT);\n checkButton(state, XINPUT_GAMEPAD_DPAD_RIGHT, GamepadButton::DPAD_RIGHT);\n checkButton(state, XINPUT_GAMEPAD_START, GamepadButton::START);\n checkButton(state, XINPUT_GAMEPAD_BACK, GamepadButton::BACK);\n checkButton(state, XINPUT_GAMEPAD_LEFT_THUMB, GamepadButton::LEFT_THUMB);\n checkButton(state, XINPUT_GAMEPAD_RIGHT_THUMB, GamepadButton::RIGHT_THUMB);\n checkButton(state, XINPUT_GAMEPAD_LEFT_SHOULDER, GamepadButton::LEFT_SHOULDER);\n checkButton(state, XINPUT_GAMEPAD_RIGHT_SHOULDER, GamepadButton::RIGHT_SHOULDER);\n checkButton(state, XINPUT_GAMEPAD_A, GamepadButton::A);\n checkButton(state, XINPUT_GAMEPAD_B, GamepadButton::B);\n checkButton(state, XINPUT_GAMEPAD_X, GamepadButton::X);\n checkButton(state, XINPUT_GAMEPAD_Y, GamepadButton::Y);\n\n if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)\n {\n handleButtonValueChange(GamepadButton::LEFT_TRIGGER, state.Gamepad.bLeftTrigger != 0, static_cast<float>(state.Gamepad.bLeftTrigger) \/ 255.0f);\n }\n\n if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)\n {\n handleButtonValueChange(GamepadButton::RIGHT_TRIGGER, state.Gamepad.bRightTrigger != 0, static_cast<float>(state.Gamepad.bRightTrigger) \/ 255.0f);\n }\n\n _state = state;\n }\n }\n \n int32_t GamepadWin::getPlayerIndex() const\n {\n return _playerIndex;\n }\n\n void GamepadWin::checkButton(XINPUT_STATE const& state, WORD mask, GamepadButton button)\n {\n if ((state.Gamepad.wButtons & mask) != (_state.Gamepad.wButtons & mask))\n {\n bool pressed = (state.Gamepad.wButtons & mask);\n handleButtonValueChange(button, pressed, pressed ? 1.0f : 0.0f);\n }\n }\n\n void GamepadWin::handleButtonValueChange(GamepadButton button, bool pressed, float value)\n {\n GamepadEvent event;\n event.type = Event::Type::GAMEPAD_BUTTON_CHANGE;\n event.gamepad = shared_from_this();\n event.button = button;\n event.pressed = pressed;\n event.value = value;\n\n Engine::getInstance()->getEventDispatcher()->dispatchGamepadButtonChangeEvent(event, Engine::getInstance()->getInput());\n }\n}\n<commit_msg>Implement XInput thumbstick events<commit_after>\/\/ Copyright (C) 2015 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"GamepadWin.h\"\n#include \"Engine.h\"\n#include \"Utils.h\"\n\nnamespace ouzel\n{\n const int32_t MAX_THUMB_VALUE = 32767;\n const int32_t MIN_THUMB_VALUE = -32768;\n\n GamepadWin::GamepadWin(int32_t playerIndex):\n _playerIndex(playerIndex)\n {\n memset(&_state, 0, sizeof(XINPUT_STATE));\n }\n\n void GamepadWin::update(XINPUT_STATE const& state)\n {\n if (state.dwPacketNumber > _state.dwPacketNumber)\n {\n checkButton(state, XINPUT_GAMEPAD_DPAD_UP, GamepadButton::DPAD_UP);\n checkButton(state, XINPUT_GAMEPAD_DPAD_DOWN, GamepadButton::DPAD_DOWN);\n checkButton(state, XINPUT_GAMEPAD_DPAD_LEFT, GamepadButton::DPAD_LEFT);\n checkButton(state, XINPUT_GAMEPAD_DPAD_RIGHT, GamepadButton::DPAD_RIGHT);\n checkButton(state, XINPUT_GAMEPAD_START, GamepadButton::START);\n checkButton(state, XINPUT_GAMEPAD_BACK, GamepadButton::BACK);\n checkButton(state, XINPUT_GAMEPAD_LEFT_THUMB, GamepadButton::LEFT_THUMB);\n checkButton(state, XINPUT_GAMEPAD_RIGHT_THUMB, GamepadButton::RIGHT_THUMB);\n checkButton(state, XINPUT_GAMEPAD_LEFT_SHOULDER, GamepadButton::LEFT_SHOULDER);\n checkButton(state, XINPUT_GAMEPAD_RIGHT_SHOULDER, GamepadButton::RIGHT_SHOULDER);\n checkButton(state, XINPUT_GAMEPAD_A, GamepadButton::A);\n checkButton(state, XINPUT_GAMEPAD_B, GamepadButton::B);\n checkButton(state, XINPUT_GAMEPAD_X, GamepadButton::X);\n checkButton(state, XINPUT_GAMEPAD_Y, GamepadButton::Y);\n\n if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)\n {\n handleButtonValueChange(GamepadButton::LEFT_TRIGGER,\n state.Gamepad.bLeftTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD,\n static_cast<float>(state.Gamepad.bLeftTrigger) \/ 255.0f);\n }\n\n if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)\n {\n handleButtonValueChange(GamepadButton::RIGHT_TRIGGER,\n state.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD,\n static_cast<float>(state.Gamepad.bRightTrigger) \/ 255.0f);\n }\n\n if (state.Gamepad.sThumbLX != _state.Gamepad.sThumbLX)\n {\n if (state.Gamepad.sThumbLX > 0)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_RIGHT,\n state.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbLX) \/ static_cast<float>(MAX_THUMB_VALUE));\n }\n else if (state.Gamepad.sThumbLX < 0)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_LEFT,\n state.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbLX) \/ static_cast<float>(MIN_THUMB_VALUE));\n }\n else \/\/ thumbstick is 0\n {\n if (_state.Gamepad.sThumbLX > state.Gamepad.sThumbLX)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_RIGHT, false, 0.0f);\n }\n else\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_LEFT, false, 0.0f);\n }\n }\n }\n\n if (state.Gamepad.sThumbLY != _state.Gamepad.sThumbLY)\n {\n if (state.Gamepad.sThumbLY > 0)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_UP,\n state.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbLY) \/ static_cast<float>(MAX_THUMB_VALUE));\n }\n else if (state.Gamepad.sThumbLY < 0)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_DOWN,\n state.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbLY) \/ static_cast<float>(MIN_THUMB_VALUE));\n }\n else \/\/ thumbstick is 0\n {\n if (_state.Gamepad.sThumbLY > state.Gamepad.sThumbLY)\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_UP, false, 0.0f);\n }\n else\n {\n handleButtonValueChange(GamepadButton::LEFT_THUMB_DOWN, false, 0.0f);\n }\n }\n }\n\n if (state.Gamepad.sThumbRX != _state.Gamepad.sThumbRX)\n {\n if (state.Gamepad.sThumbRX > 0)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_RIGHT,\n state.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbRX) \/ static_cast<float>(MAX_THUMB_VALUE));\n }\n else if (state.Gamepad.sThumbRX < 0)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_LEFT,\n state.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbRX) \/ static_cast<float>(MIN_THUMB_VALUE));\n }\n else \/\/ thumbstick is 0\n {\n if (_state.Gamepad.sThumbRX > state.Gamepad.sThumbRX)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_RIGHT, false, 0.0f);\n }\n else\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_LEFT, false, 0.0f);\n }\n }\n }\n\n if (state.Gamepad.sThumbRY != _state.Gamepad.sThumbRY)\n {\n if (state.Gamepad.sThumbRY > 0)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_UP,\n state.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbRY) \/ static_cast<float>(MAX_THUMB_VALUE));\n }\n else if (state.Gamepad.sThumbRY < 0)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_DOWN,\n state.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,\n static_cast<float>(state.Gamepad.sThumbRY) \/ static_cast<float>(MIN_THUMB_VALUE));\n }\n else \/\/ thumbstick is 0\n {\n if (_state.Gamepad.sThumbRY > state.Gamepad.sThumbRY)\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_UP, false, 0.0f);\n }\n else\n {\n handleButtonValueChange(GamepadButton::RIGHT_THUMB_DOWN, false, 0.0f);\n }\n }\n }\n\n _state = state;\n }\n }\n \n int32_t GamepadWin::getPlayerIndex() const\n {\n return _playerIndex;\n }\n\n void GamepadWin::checkButton(XINPUT_STATE const& state, WORD mask, GamepadButton button)\n {\n if ((state.Gamepad.wButtons & mask) != (_state.Gamepad.wButtons & mask))\n {\n bool pressed = (state.Gamepad.wButtons & mask);\n handleButtonValueChange(button, pressed, pressed ? 1.0f : 0.0f);\n }\n }\n\n void GamepadWin::handleButtonValueChange(GamepadButton button, bool pressed, float value)\n {\n GamepadEvent event;\n event.type = Event::Type::GAMEPAD_BUTTON_CHANGE;\n event.gamepad = shared_from_this();\n event.button = button;\n event.pressed = pressed;\n event.value = value;\n\n Engine::getInstance()->getEventDispatcher()->dispatchGamepadButtonChangeEvent(event, Engine::getInstance()->getInput());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003 Thomer M. Gil (thomer@csail.mit.edu)\n * Massachusetts Institute of Technology\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"topologies\/topologyfactory.h\"\n#include \"failuremodels\/failuremodelfactory.h\"\n#include \"network.h\"\n#include \"parse.h\"\n#include <iostream>\nusing namespace std;\n\nTopology::Topology()\n{\n _med_lat = 0;\n _lossrate = 0;\n}\n\nTopology::~Topology()\n{\n}\n\n\nTopology*\nTopology::parse(char *filename)\n{\n extern bool with_failure_model;\n\n ifstream in(filename);\n if(!in) {\n cerr << \"no such file \" << filename << endl;\n threadexitsall(0);\n }\n\n string line;\n Topology *top = 0;\n FailureModel *failure_model = 0;\n while(getline(in,line)) {\n vector<string> words = split(line);\n\n \/\/ break on first empty line\n if(words.empty())\n break;\n\n \/\/ skip empty lines and commented lines\n if(words[0][0] == '#')\n continue;\n\n \/\/ topology\n if(words[0] == \"topology\") {\n words.erase(words.begin());\n string topology = words[0];\n words.erase(words.begin());\n top = TopologyFactory::create(topology, &words);\n\n \/\/ noise\n } else if(words[0] == \"noise\") {\n if(!top) {\n cerr << \"topology keyword must appear before noise keyword\" << filename << endl;\n\tcontinue;\n }\n top->_noise = (unsigned) (atof(words[1].c_str()) * 100);\n cout << \"noise = \" << top->noise_variance() << endl;\n assert(top->noise_variance() >= 0);\n\n \/\/ loss_rate\n } else if(words[0] == \"loss_rate\") {\n if(!top) {\n cerr << \"topology keyword must appear before loss_rate keyword\" << filename << endl;\n\tcontinue;\n }\n top->_lossrate = (unsigned) (atof(words[1].c_str()) * 100);\n assert(top->lossrate() >= 0 && top->lossrate() <= 10000);\n\n \/\/ failure_model\n } else if(words[0] == \"failure_model\") {\n if(!with_failure_model) {\n cerr << \"warning: -f flag but found failure_model keyword. ignoring failure_model!\" << filename << endl;\n\tcontinue;\n }\n words.erase(words.begin());\n string fm = words[0];\n words.erase(words.begin());\n failure_model = FailureModelFactory::create(fm, &words);\n } else {\n cerr << \"header lines in topology file should be ``topology [T]'' or ``failure_model [F]\" << endl;\n exit(-1);\n }\n }\n\n if(!top) {\n cerr << \"the topology you specified is unknown\" << endl;\n exit(-1);\n }\n\n if(!failure_model) {\n if (!with_failure_model) {\n vector<string> words;\n failure_model = FailureModelFactory::create(\"NullFailureModel\", &words);\n assert (failure_model);\n } else {\n cerr << \"the failure_model you specified is unknown\" << endl;\n exit(-1);\n }\n }\n\n \/\/ create the network.\n Network::Instance(top, failure_model);\n\n \/\/ leave the rest of the file to the specific topology\n top->parse(in);\n\n return top;\n}\n<commit_msg>default value for noise is zero<commit_after>\/*\n * Copyright (c) 2003 Thomer M. Gil (thomer@csail.mit.edu)\n * Massachusetts Institute of Technology\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"topologies\/topologyfactory.h\"\n#include \"failuremodels\/failuremodelfactory.h\"\n#include \"network.h\"\n#include \"parse.h\"\n#include <iostream>\nusing namespace std;\n\nTopology::Topology()\n{\n _med_lat = 0;\n _lossrate = 0;\n _noise = 0;\n}\n\nTopology::~Topology()\n{\n}\n\n\nTopology*\nTopology::parse(char *filename)\n{\n extern bool with_failure_model;\n\n ifstream in(filename);\n if(!in) {\n cerr << \"no such file \" << filename << endl;\n threadexitsall(0);\n }\n\n string line;\n Topology *top = 0;\n FailureModel *failure_model = 0;\n while(getline(in,line)) {\n vector<string> words = split(line);\n\n \/\/ break on first empty line\n if(words.empty())\n break;\n\n \/\/ skip empty lines and commented lines\n if(words[0][0] == '#')\n continue;\n\n \/\/ topology\n if(words[0] == \"topology\") {\n words.erase(words.begin());\n string topology = words[0];\n words.erase(words.begin());\n top = TopologyFactory::create(topology, &words);\n\n \/\/ noise\n } else if(words[0] == \"noise\") {\n if(!top) {\n cerr << \"topology keyword must appear before noise keyword\" << filename << endl;\n\tcontinue;\n }\n top->_noise = (unsigned) (atof(words[1].c_str()) * 100);\n cout << \"noise = \" << top->noise_variance() << endl;\n assert(top->noise_variance() >= 0);\n\n \/\/ loss_rate\n } else if(words[0] == \"loss_rate\") {\n if(!top) {\n cerr << \"topology keyword must appear before loss_rate keyword\" << filename << endl;\n\tcontinue;\n }\n top->_lossrate = (unsigned) (atof(words[1].c_str()) * 100);\n assert(top->lossrate() >= 0 && top->lossrate() <= 10000);\n\n \/\/ failure_model\n } else if(words[0] == \"failure_model\") {\n if(!with_failure_model) {\n cerr << \"warning: -f flag but found failure_model keyword. ignoring failure_model!\" << filename << endl;\n\tcontinue;\n }\n words.erase(words.begin());\n string fm = words[0];\n words.erase(words.begin());\n failure_model = FailureModelFactory::create(fm, &words);\n } else {\n cerr << \"header lines in topology file should be ``topology [T]'' or ``failure_model [F]\" << endl;\n exit(-1);\n }\n }\n\n if(!top) {\n cerr << \"the topology you specified is unknown\" << endl;\n exit(-1);\n }\n\n if(!failure_model) {\n if (!with_failure_model) {\n vector<string> words;\n failure_model = FailureModelFactory::create(\"NullFailureModel\", &words);\n assert (failure_model);\n } else {\n cerr << \"the failure_model you specified is unknown\" << endl;\n exit(-1);\n }\n }\n\n \/\/ create the network.\n Network::Instance(top, failure_model);\n\n \/\/ leave the rest of the file to the specific topology\n top->parse(in);\n\n return top;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"backend\/bridge\/dml\/expr\/pg_func_map.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/**\n * @brief Mapping PG Function Id to Peloton Function Meta Info.\n *\/\nstd::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({\n\n \/\/====--------------------------------\n \/\/ Relational comparison\n \/\/====--------------------------------\n {63, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {65, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {67, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {158, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {159, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {287, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {293, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {1718, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n\n {84, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {144, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {145, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {157, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {164, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {165, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {288, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {294, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {1719, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n\n {56, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {64, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {66, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {160, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {161, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {1246, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {289, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {295, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {1722, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n\n {57, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {73, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {146, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {147, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {162, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {163, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {291, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {297, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {1720, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n\n {74, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {150, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {151, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {168, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {169, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {1692, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {292, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {298, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {1721, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n\n {72, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {148, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {149, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {166, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {167, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {1691, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {290, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {296, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {1723, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n\n \/\/====--------------------------------\n \/\/ Basic arithmetics\n \/\/====--------------------------------\n {176, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {177, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {178, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {179, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {204, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {218, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {1724, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n\n {180, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {181, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {182, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {183, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {205, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {219, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {1725, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n\n {141, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {152, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {170, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {171, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {202, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {216, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {1726, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n\n {153, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {154, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {172, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {173, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {203, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {217, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {1727, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n\n \/\/====--------------------------------\n \/\/ Cast\n \/\/====--------------------------------\n {480, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int8 -> int4\n {481, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int4 -> int8\n {668, {EXPRESSION_TYPE_CAST, 3}}, \/\/ bpchar -> bpchar\n {669, {EXPRESSION_TYPE_CAST, 3}}, \/\/ varchar -> varchar\n {1703, {EXPRESSION_TYPE_CAST, 2}}, \/\/ numeric -> numeric\n {1740, {EXPRESSION_TYPE_CAST, 3}}, \/\/ int8 -> numeric\n {1742, {EXPRESSION_TYPE_CAST, 3}}, \/\/ float4 -> numeric\n {1743, {EXPRESSION_TYPE_CAST, 3}}, \/\/ float8 -> numeric\n {1744, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> int4\n {1745, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> float4\n {1746, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> float8\n {1781, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int8 -> numeric\n {1782, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int2 -> numeric\n\n});\n\n\/**\n * @brief Mapping PG transit function to Aggregate types.\n * We have to separate it from kPgFuncMap,\n * because the two maps may have overlapping functions that have\n * different meaning in Peloton.\n * For example, PG Function Id 218 (float8pl) means an PLUS in\n * 'ordinary' expressions,\n * but means a SUM(float) in an aggregation.\n *\/\nstd::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap(\n {\/\/====--------------------------------\n \/\/ \"Transit function\" of Aggregates\n \/\/====--------------------------------\n {768, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n {770, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n {223, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n\n {769, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n {771, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n {224, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n\n {1840, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {1841, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {1842, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {218, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n\n {222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n\n {1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}},\n {2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}}\n\n });\n}\n}\n<commit_msg>Add function mapping for timestamp operators and sum aggregate function<commit_after>\n#include \"backend\/bridge\/dml\/expr\/pg_func_map.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/**\n * @brief Mapping PG Function Id to Peloton Function Meta Info.\n *\/\nstd::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({\n\n \/\/====--------------------------------\n \/\/ Relational comparison\n \/\/====--------------------------------\n {63, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {65, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {67, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {158, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {159, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {287, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {293, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {1718, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n {2052, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},\n\n {84, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {144, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {145, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {157, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {164, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {165, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {288, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {294, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {1719, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n {2053, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},\n\n {56, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {64, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {66, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {160, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {161, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {1246, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {289, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {295, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {1722, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n {2054, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},\n\n {57, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {73, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {146, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {147, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {162, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {163, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {291, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {297, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {1720, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n {2057, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},\n\n {74, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {150, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {151, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {168, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {169, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {1692, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {292, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {298, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {1721, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n {2056, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},\n\n {72, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {148, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {149, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {166, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {167, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {1691, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {290, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {296, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {1723, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n {2055, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},\n\n \/\/====--------------------------------\n \/\/ Basic arithmetics\n \/\/====--------------------------------\n {176, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {177, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {178, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {179, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {204, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {218, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n {1724, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},\n\n {180, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {181, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {182, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {183, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {205, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {219, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n {1725, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},\n\n {141, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {152, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {170, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {171, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {202, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {216, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n {1726, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},\n\n {153, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {154, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {172, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {173, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {203, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {217, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n {1727, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},\n\n \/\/====--------------------------------\n \/\/ Cast\n \/\/====--------------------------------\n {480, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int8 -> int4\n {481, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int4 -> int8\n {668, {EXPRESSION_TYPE_CAST, 3}}, \/\/ bpchar -> bpchar\n {669, {EXPRESSION_TYPE_CAST, 3}}, \/\/ varchar -> varchar\n {1703, {EXPRESSION_TYPE_CAST, 2}}, \/\/ numeric -> numeric\n {1740, {EXPRESSION_TYPE_CAST, 3}}, \/\/ int8 -> numeric\n {1742, {EXPRESSION_TYPE_CAST, 3}}, \/\/ float4 -> numeric\n {1743, {EXPRESSION_TYPE_CAST, 3}}, \/\/ float8 -> numeric\n {1744, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> int4\n {1745, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> float4\n {1746, {EXPRESSION_TYPE_CAST, 1}}, \/\/ numeric -> float8\n {1781, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int8 -> numeric\n {1782, {EXPRESSION_TYPE_CAST, 1}}, \/\/ int2 -> numeric\n\n});\n\n\/**\n * @brief Mapping PG transit function to Aggregate types.\n * We have to separate it from kPgFuncMap,\n * because the two maps may have overlapping functions that have\n * different meaning in Peloton.\n * For example, PG Function Id 218 (float8pl) means an PLUS in\n * 'ordinary' expressions,\n * but means a SUM(float) in an aggregation.\n *\/\nstd::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap(\n {\/\/====--------------------------------\n \/\/ \"Transit function\" of Aggregates\n \/\/====--------------------------------\n {768, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n {770, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n {223, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},\n\n {769, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n {771, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n {224, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},\n\n {1840, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {1841, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {1842, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n {218, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},\n\n {222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n {2858, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},\n\n {1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}},\n {2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}}\n\n });\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <string>\n#include <iostream>\n#include \"utils.h\"\n#include \"Lexer.h\"\n#include \"Parser.h\"\n#include <exception>\n#include \"ParseException.h\"\n#include \"opcodes.h\"\n\nstatic uint16_t generate_opcode(const std::string& op, const std::vector<std::string>& args)\n{\n auto itr = OPERATORS.find(op);\n return itr->second(args);\n}\n\nstatic void write_rom(const std::string& filePath, const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)\n{\n std::FILE *fp = std::fopen(filePath.c_str(), \"wb\");\n if (!fp) {\n throw std::runtime_error(\"Unable to open file for writing.\");\n }\n\n \/* Now perform the binary conversion and write it to the file *\/\n for (const auto& i : instructions) {\n uint16_t op = 0;\n \/* Replace labels with their addresses *\/\n if (one_of<std::string>(i.op, { \"JMP\", \"CALL\", \"ZJMP\", \"ILOAD\" })) {\n auto label = i.args[0];\n auto arg = from_hex(labels.at(label));\n op = generate_opcode(i.op, { arg });\n } else {\n op = generate_opcode(i.op, i.args);\n }\n \/* Correct for the host machine endianness to chip 8 big endian *\/\n op = endi(op);\n\n std::fwrite(&op, sizeof(op), 1, fp);\n }\n std::fclose(fp);\n\n#ifndef NDEBUG\n LOG(\"-------- Label Addresses --------\");\n for (const auto& it : labels) {\n LOG(\"%s -> 0x%04X\", it.first.c_str(), it.second);\n }\n LOG(\"-------- End Addresses --------\");\n#endif\n}\n\nstatic void dump_asm(const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)\n{\n std::cout << \"-------- Asm Dump --------\\n\";\n for (const auto& i : instructions) {\n uint16_t op = 0;\n \/* Replace labels with their addresses *\/\n if (one_of<std::string>(i.op, { \"JMP\", \"CALL\", \"ZJMP\", \"ILOAD\" })) {\n auto label = i.args[0];\n auto arg = from_hex(labels.at(label));\n op = generate_opcode(i.op, { arg });\n } else {\n op = generate_opcode(i.op, i.args);\n }\n std::cout << from_hex(i.addr) << \" -- \" << from_hex(op) << \" ; \";\n std::string s = i.op + \" \";\n for (const auto& a : i.args) {\n s += a;\n s += \", \";\n }\n \/* Remove the last comma *\/\n s = s.substr(0, s.find_last_of(\",\"));\n std::cout << s << \"\\n\";\n }\n std::cout << \"-------- End Dump --------\\n\";\n}\n\nstatic std::string read_file(const char *path)\n{\n std::FILE *fp = std::fopen(path, \"r\");\n if (!fp) { return \"\"; }\n\n fseek(fp, 0, SEEK_END);\n auto fsize = std::ftell(fp);\n std::rewind(fp);\n\n std::string buf(fsize, '\\0');\n std::fread(&buf[0], sizeof(char), fsize, fp);\n std::fclose(fp);\n\n return buf;\n}\n\nstatic bool parse_args(int argc, char **argv, AsmOpts *opts)\n{\n if (argc < 2) {\n return false;\n }\n\n std::string first(argv[1]);\n if (first == \"-h\") {\n opts->show_help = true;\n return true;\n }\n opts->in_file = argv[1];\n\n for (int i = 2; i < argc; ++i) {\n std::string arg(argv[i]);\n if (arg == \"--dump-asm\") {\n opts->dump_asm = true;\n } else if (arg == \"--output\" || arg == \"-o\") {\n opts->out_file = argv[i + 1];\n if (opts->out_file == nullptr) {\n std::cerr << \"Output flag specified without an output file!\\n\";\n return false;\n }\n ++i;\n } else {\n return false;\n }\n }\n return true;\n}\n\nstatic void show_help()\n{\n std::cout << \"chip8asm is an assembler for the chip 8 VM.\\n\";\n std::cout << \"The only required argument is the input .asm file.\\n\";\n std::cout << \"The first argument should be one of the input file or help.\\n\";\n std::cout << \"Here are the supported options:\\n\";\n std::cout << \" --dump-asm | -dasm -- dumps the assembled statements with memory locations\\n\";\n std::cout << \" --output | -o -- the name of the output ROM file. By default, it is 'a.rom'\\n\";\n std::cout << \" --help | -h -- displays this help screen\\n\";\n}\n\nint main(int argc, char **argv)\n{\n try {\n AsmOpts opts;\n if (!parse_args(argc, argv, &opts)) {\n show_help();\n return EXIT_FAILURE;\n }\n\n if (opts.show_help) {\n show_help();\n return EXIT_SUCCESS;\n }\n\n std::cout << \"Reading from '\" << opts.in_file << \"' and writing to '\" << opts.out_file << \"'.\\n\";\n std::cout << \"Dump ASM: \" << (opts.dump_asm ? \"true\" : \"false\") << \"\\n\";\n\n const std::string text = read_file(argv[1]);\n if (text.empty()) {\n std::cerr << \"Error reading from \" << argv[1] << \"!\\n\";\n return EXIT_FAILURE;\n }\n\n emu::Lexer lexer(text);\n c8::Parser parser(lexer);\n parser.parse();\n\n auto instructions = parser.getInstructions();\n auto labels = parser.getLabels();\n write_rom(opts.out_file, instructions, labels);\n if (opts.dump_asm) {\n dump_asm(instructions, labels);\n }\n \n std::cout << \"Binary ROM successfully generated!\\n\";\n\n } catch (const std::invalid_argument& e) {\n std::cerr << \"Caught invalid argument: \" << e.what() << \"\\n\";\n } catch (const ParseException& e) {\n std::cerr << \"Caught Parse Exception: \" << e.what() << \"\\n\";\n } catch (const std::exception& e) {\n std::cerr << \"Caught generic exception: \" << e.what() << \"\\n\";\n } catch (...) {\n std::cerr << \"Unknown error! Please retry!\\n\";\n }\n}\n<commit_msg>Moved to C I\/O<commit_after>#include <cstdlib>\n#include <string>\n#include \"utils.h\"\n#include \"Lexer.h\"\n#include \"Parser.h\"\n#include <exception>\n#include \"ParseException.h\"\n#include \"opcodes.h\"\n\nstatic uint16_t generate_opcode(const std::string& op, const std::vector<std::string>& args)\n{\n auto itr = OPERATORS.find(op);\n return itr->second(args);\n}\n\nstatic void write_rom(const std::string& filePath, const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)\n{\n std::FILE *fp = std::fopen(filePath.c_str(), \"wb\");\n if (!fp) {\n throw std::runtime_error(\"Unable to open file for writing.\");\n }\n\n \/* Now perform the binary conversion and write it to the file *\/\n for (const auto& i : instructions) {\n uint16_t op = 0;\n \/* Replace labels with their addresses *\/\n if (one_of<std::string>(i.op, { \"JMP\", \"CALL\", \"ZJMP\", \"ILOAD\" })) {\n auto label = i.args[0];\n auto arg = from_hex(labels.at(label));\n op = generate_opcode(i.op, { arg });\n } else {\n op = generate_opcode(i.op, i.args);\n }\n \/* Correct for the host machine endianness to chip 8 big endian *\/\n op = endi(op);\n\n std::fwrite(&op, sizeof(op), 1, fp);\n }\n std::fclose(fp);\n\n#ifndef NDEBUG\n LOG(\"-------- Label Addresses --------\");\n for (const auto& it : labels) {\n LOG(\"%s -> 0x%04X\", it.first.c_str(), it.second);\n }\n LOG(\"-------- End Addresses --------\");\n#endif\n}\n\nstatic void dump_asm(const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)\n{\n std::puts(\"-------- ASM Dump --------\");\n for (const auto& i : instructions) {\n uint16_t op = 0;\n \/* Replace labels with their addresses *\/\n if (one_of<std::string>(i.op, { \"JMP\", \"CALL\", \"ZJMP\", \"ILOAD\" })) {\n auto label = i.args[0];\n auto arg = from_hex(labels.at(label));\n op = generate_opcode(i.op, { arg });\n } else {\n op = generate_opcode(i.op, i.args);\n }\n std::string s = i.op + \" \";\n for (const auto& a : i.args) {\n s += a;\n s += \", \";\n }\n \/* Remove the last comma *\/\n s = s.substr(0, s.find_last_of(\",\"));\n std::printf(\"0x%04X | 0x%04X ; %s\\n\", i.addr, op, s.c_str());\n }\n std::puts(\"-------- End Dump --------\");\n}\n\nstatic std::string read_file(const char *path)\n{\n std::FILE *fp = std::fopen(path, \"r\");\n if (!fp) { return \"\"; }\n\n fseek(fp, 0, SEEK_END);\n auto fsize = std::ftell(fp);\n std::rewind(fp);\n\n std::string buf(fsize, '\\0');\n std::fread(&buf[0], sizeof(char), fsize, fp);\n std::fclose(fp);\n\n return buf;\n}\n\nstatic bool parse_args(int argc, char **argv, AsmOpts *opts)\n{\n if (argc < 2) {\n return false;\n }\n\n std::string first(argv[1]);\n if (first == \"-h\") {\n opts->show_help = true;\n return true;\n }\n opts->in_file = argv[1];\n\n for (int i = 2; i < argc; ++i) {\n std::string arg(argv[i]);\n if (arg == \"--dump-asm\") {\n opts->dump_asm = true;\n } else if (arg == \"--output\" || arg == \"-o\") {\n opts->out_file = argv[i + 1];\n if (opts->out_file == nullptr) {\n std::fprintf(stderr, \"Output flag specified without an output file!\\n\");\n return false;\n }\n ++i;\n } else {\n return false;\n }\n }\n return true;\n}\n\nstatic void show_help()\n{\n std::puts(\"chip8asm is an assembler for the chip 8 VM.\");\n std::puts(\"The only required argument is the input .asm file.\");\n std::puts(\"The first argument should be one of the input file or help.\");\n std::puts(\"Here are the supported options:\");\n std::puts(\" --dump-asm | -dasm -- dumps the assembled statements with memory locations\");\n std::puts(\" --output | -o -- the name of the output ROM file. By default, it is 'a.rom'\");\n std::puts(\" --help | -h -- displays this help screen\");\n}\n\nint main(int argc, char **argv)\n{\n try {\n AsmOpts opts;\n if (!parse_args(argc, argv, &opts)) {\n show_help();\n return EXIT_FAILURE;\n }\n\n if (opts.show_help) {\n show_help();\n return EXIT_SUCCESS;\n }\n\n const std::string text = read_file(argv[1]);\n if (text.empty()) {\n std::fprintf(stderr, \"Error reading from '%s'\\n\", text.c_str());\n return EXIT_FAILURE;\n }\n\n emu::Lexer lexer(text);\n c8::Parser parser(lexer);\n parser.parse();\n\n auto instructions = parser.getInstructions();\n auto labels = parser.getLabels();\n write_rom(opts.out_file, instructions, labels);\n if (opts.dump_asm) {\n dump_asm(instructions, labels);\n }\n \n std::puts(\"Done.\");\n\n } catch (const ParseException& e) {\n std::fprintf(stderr, \"Caught Parse Exception: %s\\n\", e.what());\n } catch (const std::exception& e) {\n std::fprintf(stderr, \"Caught generic exception: %s\\n\", e.what());\n } catch (...) {\n std::fprintf(stderr, \"Unknown error! Please retry!\\n\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include \"..\/include\/ImageViewer.h\"\n#include \"..\/include\/SharedQueue.h\"\n#include \"..\/include\/ThreadPool.h\"\n\n#include <args.hxx>\n#include <ImfThreading.h>\n\n#include <iostream>\n#include <thread>\n\nusing namespace args;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\nint mainFunc(int argc, char* argv[]) {\n Imf::setGlobalThreadCount(thread::hardware_concurrency());\n\n ArgumentParser parser{\n \"Inspection tool for images with a high dynamic range.\",\n \"\",\n };\n\n HelpFlag helpFlag{\n parser,\n \"help\",\n \"Display this help menu\",\n {'h', \"help\"},\n };\n\n ValueFlag<float> exposureFlag{\n parser,\n \"exposure\",\n \"Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. \"\n \"It can be controlled via the GUI, or by pressing E\/Shift+E.\",\n {'e', \"exposure\"},\n };\n\n ValueFlag<string> filterFlag{\n parser,\n \"filter\",\n \"Filters visible images and layers according to a supplied string. \"\n \"The string must have the format 'image:layer'. \"\n \"Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.\",\n {'f', \"filter\"},\n };\n\n ValueFlag<bool> maximizeFlag{\n parser,\n \"maximize\",\n \"Whether to maximize the window on startup or not. \"\n \"If no images were supplied via the command line, then the default is false. \"\n \"Otherwise, the default is true.\",\n {\"max\", \"maximize\"},\n };\n\n ValueFlag<string> metricFlag{\n parser,\n \"metric\",\n \"The metric to use when comparing two images. \"\n R\"(\n The available metrics are:\n E - Error\n AE - Absolute Error\n SE - Squared Error\n RAE - Relative Absolute Error\n RSE - Relative Squared Error\n )\"\n \"Default is E.\",\n {'m', \"metric\"},\n };\n\n ValueFlag<float> offsetFlag{\n parser,\n \"offset\",\n \"The offset is added to the image after exposure has been applied. \"\n \"It can be controlled via the GUI, or by pressing O\/Shift+O.\",\n {'o', \"offset\"},\n };\n\n ValueFlag<string> tonemapFlag{\n parser,\n \"tonemap\",\n \"The tonemapping algorithm to use. \"\n R\"(\n The available tonemaps are:\n sRGB - sRGB\n Gamma - Gamma curve (2.2)\n FC - False Color\n PN - Positive=Green, Negative=Red\n )\"\n \"Default is sRGB.\",\n {'t', \"tonemap\"},\n };\n\n PositionalList<string> imageFiles{\n parser,\n \"images or channel selectors\",\n \"The image files to be opened by the viewer. \"\n \"If a filename starting with a ':' is encountered, \"\n \"then this filename is not treated as an image file \"\n \"but as a comma-separated channel selector. Until the next channel \"\n \"selector is encountered only channels containing \"\n \"elements from the current selector will be loaded. This is \"\n \"especially useful for selectively loading a specific \"\n \"part of a multi-part EXR file.\",\n };\n\n \/\/ Parse command line arguments and react to parsing\n \/\/ errors using exceptions.\n try {\n parser.ParseCLI(argc, argv);\n } catch (args::Help) {\n std::cout << parser;\n return 0;\n } catch (args::ParseError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return -1;\n } catch (args::ValidationError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return -2;\n }\n\n auto ipc = make_shared<Ipc>();\n\n \/\/ If we're not the primary instance, simply send the to-be-opened images\n \/\/ to the primary instance.\n if (!ipc->isPrimaryInstance()) {\n string channelSelector;\n for (auto imageFile : get(imageFiles)) {\n if (!imageFile.empty() && imageFile[0] == ':') {\n channelSelector = imageFile.substr(1);\n continue;\n }\n\n try {\n ipc->sendToPrimaryInstance(absolutePath(imageFile) + \":\" + channelSelector);\n } catch (runtime_error e) {\n cerr << \"Invalid file '\" << imageFile << \"': \" << e.what() << endl;\n }\n }\n\n return 0;\n }\n\n cout << \"Loading window...\" << endl;\n\n \/\/ Load images passed via command line in the background prior to\n \/\/ creating our main application such that they are not stalled\n \/\/ by the potentially slow initialization of opengl \/ glfw.\n shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();\n string channelSelector;\n for (auto imageFile : get(imageFiles)) {\n if (!imageFile.empty() && imageFile[0] == ':') {\n channelSelector = imageFile.substr(1);\n continue;\n }\n\n ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {\n auto image = tryLoadImage(imageFile, channelSelector);\n if (image) {\n imagesToAdd->push({false, image});\n }\n });\n }\n\n \/\/ Init nanogui application\n nanogui::init();\n\n {\n auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd}};\n app->drawAll();\n app->setVisible(true);\n\n \/\/ Do what the maximize flag tells us---if it exists---and\n \/\/ maximize if we have images otherwise.\n if (maximizeFlag ? get(maximizeFlag) : imageFiles) {\n app->maximize();\n }\n\n \/\/ Apply parameter flags\n if (exposureFlag) { app->setExposure(get(exposureFlag)); }\n if (filterFlag) { app->setFilter(get(filterFlag)); }\n if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); }\n if (offsetFlag) { app->setOffset(get(offsetFlag)); }\n if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); }\n\n \/\/ Refresh only every 250ms if there are no user interactions.\n \/\/ This makes an idling tev surprisingly energy-efficient. :)\n nanogui::mainloop(250);\n }\n\n \/\/ On some linux distributions glfwTerminate() (which is called by\n \/\/ nanogui::shutdown()) causes segfaults. Since we are done with our\n \/\/ program here anyways, let's let the OS clean up after us.\n \/\/nanogui::shutdown();\n\n \/\/ Let all threads gracefully terminate.\n ThreadPool::shutdown();\n\n return 0;\n}\n\nTEV_NAMESPACE_END\n\nint main(int argc, char* argv[]) {\n try {\n tev::mainFunc(argc, argv);\n } catch (const runtime_error& e) {\n cerr << \"Uncaught exception: \" << e.what() << endl;\n return 1;\n }\n}\n<commit_msg>Only spin up Imf threads in the primary instance<commit_after>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include \"..\/include\/ImageViewer.h\"\n#include \"..\/include\/SharedQueue.h\"\n#include \"..\/include\/ThreadPool.h\"\n\n#include <args.hxx>\n#include <ImfThreading.h>\n\n#include <iostream>\n#include <thread>\n\nusing namespace args;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\nint mainFunc(int argc, char* argv[]) {\n ArgumentParser parser{\n \"Inspection tool for images with a high dynamic range.\",\n \"\",\n };\n\n HelpFlag helpFlag{\n parser,\n \"help\",\n \"Display this help menu\",\n {'h', \"help\"},\n };\n\n ValueFlag<float> exposureFlag{\n parser,\n \"exposure\",\n \"Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. \"\n \"It can be controlled via the GUI, or by pressing E\/Shift+E.\",\n {'e', \"exposure\"},\n };\n\n ValueFlag<string> filterFlag{\n parser,\n \"filter\",\n \"Filters visible images and layers according to a supplied string. \"\n \"The string must have the format 'image:layer'. \"\n \"Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.\",\n {'f', \"filter\"},\n };\n\n ValueFlag<bool> maximizeFlag{\n parser,\n \"maximize\",\n \"Whether to maximize the window on startup or not. \"\n \"If no images were supplied via the command line, then the default is false. \"\n \"Otherwise, the default is true.\",\n {\"max\", \"maximize\"},\n };\n\n ValueFlag<string> metricFlag{\n parser,\n \"metric\",\n \"The metric to use when comparing two images. \"\n R\"(\n The available metrics are:\n E - Error\n AE - Absolute Error\n SE - Squared Error\n RAE - Relative Absolute Error\n RSE - Relative Squared Error\n )\"\n \"Default is E.\",\n {'m', \"metric\"},\n };\n\n ValueFlag<float> offsetFlag{\n parser,\n \"offset\",\n \"The offset is added to the image after exposure has been applied. \"\n \"It can be controlled via the GUI, or by pressing O\/Shift+O.\",\n {'o', \"offset\"},\n };\n\n ValueFlag<string> tonemapFlag{\n parser,\n \"tonemap\",\n \"The tonemapping algorithm to use. \"\n R\"(\n The available tonemaps are:\n sRGB - sRGB\n Gamma - Gamma curve (2.2)\n FC - False Color\n PN - Positive=Green, Negative=Red\n )\"\n \"Default is sRGB.\",\n {'t', \"tonemap\"},\n };\n\n PositionalList<string> imageFiles{\n parser,\n \"images or channel selectors\",\n \"The image files to be opened by the viewer. \"\n \"If a filename starting with a ':' is encountered, \"\n \"then this filename is not treated as an image file \"\n \"but as a comma-separated channel selector. Until the next channel \"\n \"selector is encountered only channels containing \"\n \"elements from the current selector will be loaded. This is \"\n \"especially useful for selectively loading a specific \"\n \"part of a multi-part EXR file.\",\n };\n\n \/\/ Parse command line arguments and react to parsing\n \/\/ errors using exceptions.\n try {\n parser.ParseCLI(argc, argv);\n } catch (args::Help) {\n std::cout << parser;\n return 0;\n } catch (args::ParseError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return -1;\n } catch (args::ValidationError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return -2;\n }\n\n auto ipc = make_shared<Ipc>();\n\n \/\/ If we're not the primary instance, simply send the to-be-opened images\n \/\/ to the primary instance.\n if (!ipc->isPrimaryInstance()) {\n string channelSelector;\n for (auto imageFile : get(imageFiles)) {\n if (!imageFile.empty() && imageFile[0] == ':') {\n channelSelector = imageFile.substr(1);\n continue;\n }\n\n try {\n ipc->sendToPrimaryInstance(absolutePath(imageFile) + \":\" + channelSelector);\n } catch (runtime_error e) {\n cerr << \"Invalid file '\" << imageFile << \"': \" << e.what() << endl;\n }\n }\n\n return 0;\n }\n\n Imf::setGlobalThreadCount(thread::hardware_concurrency());\n\n cout << \"Loading window...\" << endl;\n\n \/\/ Load images passed via command line in the background prior to\n \/\/ creating our main application such that they are not stalled\n \/\/ by the potentially slow initialization of opengl \/ glfw.\n shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();\n string channelSelector;\n for (auto imageFile : get(imageFiles)) {\n if (!imageFile.empty() && imageFile[0] == ':') {\n channelSelector = imageFile.substr(1);\n continue;\n }\n\n ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {\n auto image = tryLoadImage(imageFile, channelSelector);\n if (image) {\n imagesToAdd->push({false, image});\n }\n });\n }\n\n \/\/ Init nanogui application\n nanogui::init();\n\n {\n auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd}};\n app->drawAll();\n app->setVisible(true);\n\n \/\/ Do what the maximize flag tells us---if it exists---and\n \/\/ maximize if we have images otherwise.\n if (maximizeFlag ? get(maximizeFlag) : imageFiles) {\n app->maximize();\n }\n\n \/\/ Apply parameter flags\n if (exposureFlag) { app->setExposure(get(exposureFlag)); }\n if (filterFlag) { app->setFilter(get(filterFlag)); }\n if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); }\n if (offsetFlag) { app->setOffset(get(offsetFlag)); }\n if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); }\n\n \/\/ Refresh only every 250ms if there are no user interactions.\n \/\/ This makes an idling tev surprisingly energy-efficient. :)\n nanogui::mainloop(250);\n }\n\n \/\/ On some linux distributions glfwTerminate() (which is called by\n \/\/ nanogui::shutdown()) causes segfaults. Since we are done with our\n \/\/ program here anyways, let's let the OS clean up after us.\n \/\/nanogui::shutdown();\n\n \/\/ Let all threads gracefully terminate.\n ThreadPool::shutdown();\n\n return 0;\n}\n\nTEV_NAMESPACE_END\n\nint main(int argc, char* argv[]) {\n try {\n tev::mainFunc(argc, argv);\n } catch (const runtime_error& e) {\n cerr << \"Uncaught exception: \" << e.what() << endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"TwitchBot.h\"\n\nstatic struct botData {\n\tstd::string name;\n\tstd::string channel;\n\tstd::string pass;\n};\n\nbotData readSettings(const std::string &appDir);\n\nint main() {\n\n\tbotData bd;\n\n\ttry {\n\t\tbd = readSettings(utils::getApplicationDirectory());\n\t\tif (bd.name.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract name from settings.txt\");\n\t\t}\n\t\tif (bd.channel.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract channel from settings.txt\");\n\t\t}\n\t\tif (bd.pass.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract password from settings.txt\");\n\t\t}\n\t}\n\tcatch (std::runtime_error &e) {\n\t\tstd::cerr << e.what();\n\t\tstd::cin.get();\n\t\treturn 1;\n\t}\n\n\tTwitchBot bot(bd.name, bd.channel, bd.pass);\n\n\tif (bot.isConnected()) {\n\t\tbot.serverLoop();\n\t}\n\n\treturn 0;\n\n}\n\nbotData readSettings(const std::string &appDir) {\n\n\t\/\/ open settings.cfg\n\tstd::ifstream reader(appDir + \"\\\\settings.txt\");\n\tif (!reader.is_open()) {\n\t\tthrow std::runtime_error(\"Could not locate settings.txt\");\n\t}\n\n\tstd::string line;\n\tuint8_t lineNum = 0;\n\tbotData bd;\n\n\twhile (std::getline(reader, line)) {\n\n\t\tlineNum++;\n\t\t\/\/ remove whitespace\n\t\tline.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());\n\n\t\t\/\/ lines starting with * are comments\n\t\tif (utils::startsWith(line, \"*\")) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tstd::regex lineRegex(\"(name|channel|password):(.+?)\");\n\t\t\tstd::smatch match;\n\t\t\tconst std::string s = line;\n\t\t\tif (std::regex_match(s.begin(), s.end(), match, lineRegex)) {\n\t\t\t\tif (match[1].str() == \"name\") {\n\t\t\t\t\tbd.name = match[2];\n\t\t\t\t}\n\t\t\t\telse if (match[1].str() == \"channel\") {\n\t\t\t\t\tif (!utils::startsWith(match[2].str(), \"#\")) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Channel name must start with #.\");\n\t\t\t\t\t}\n\t\t\t\t\tbd.channel = match[2];\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!utils::startsWith(match[2].str(), \"oauth:\")) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Password must be a valid oauth token, starting with \\\"oauth:\\\".\");\n\t\t\t\t\t}\n\t\t\t\t\tbd.pass = match[2];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow std::runtime_error(\"Syntax error on line \" + std::to_string(lineNum) + \" of settings.txt.\");\n\t\t\t}\n\t\t}\n\n\t}\n\n\treader.close();\n\treturn bd;\n\n}<commit_msg>Minor change<commit_after>#include \"stdafx.h\"\n#include \"TwitchBot.h\"\n#include <pencode.h>\n\nstruct botData {\n\tstd::string name;\n\tstd::string channel;\n\tstd::string pass;\n};\n\nbotData readSettings(const std::string &appDir);\n\nint main() {\n\n\tbotData bd;\n\n\ttry {\n\t\tbd = readSettings(utils::getApplicationDirectory());\n\t\tif (bd.name.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract name from settings.txt\");\n\t\t}\n\t\tif (bd.channel.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract channel from settings.txt\");\n\t\t}\n\t\tif (bd.pass.empty()) {\n\t\t\tthrow std::runtime_error(\"Could not extract password from settings.txt\");\n\t\t}\n\t}\n\tcatch (std::runtime_error &e) {\n\t\tstd::cerr << e.what();\n\t\tstd::cin.get();\n\t\treturn 1;\n\t}\n\n\tTwitchBot bot(bd.name, bd.channel, bd.pass);\n\n\tif (bot.isConnected()) {\n\t\tbot.serverLoop();\n\t}\n\n\treturn 0;\n\n}\n\nbotData readSettings(const std::string &appDir) {\n\n\t\/\/ open settings.cfg\n\tstd::ifstream reader(appDir + \"\\\\settings.txt\");\n\tif (!reader.is_open()) {\n\t\tthrow std::runtime_error(\"Could not locate settings.txt\");\n\t}\n\n\tstd::string line;\n\tuint8_t lineNum = 0;\n\tbotData bd;\n\n\twhile (std::getline(reader, line)) {\n\n\t\tlineNum++;\n\t\t\/\/ remove whitespace\n\t\tline.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());\n\n\t\t\/\/ lines starting with * are comments\n\t\tif (utils::startsWith(line, \"*\")) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tstd::regex lineRegex(\"(name|channel|password):(.+?)\");\n\t\t\tstd::smatch match;\n\t\t\tconst std::string s = line;\n\t\t\tif (std::regex_match(s.begin(), s.end(), match, lineRegex)) {\n\t\t\t\tif (match[1].str() == \"name\") {\n\t\t\t\t\tbd.name = match[2];\n\t\t\t\t}\n\t\t\t\telse if (match[1].str() == \"channel\") {\n\t\t\t\t\tif (!utils::startsWith(match[2].str(), \"#\")) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Channel name must start with #.\");\n\t\t\t\t\t}\n\t\t\t\t\tbd.channel = match[2];\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!utils::startsWith(match[2].str(), \"oauth:\")) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Password must be a valid oauth token, starting with \\\"oauth:\\\".\");\n\t\t\t\t\t}\n\t\t\t\t\tbd.pass = match[2];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow std::runtime_error(\"Syntax error on line \" + std::to_string(lineNum) + \" of settings.txt.\");\n\t\t\t}\n\t\t}\n\n\t}\n\n\treader.close();\n\treturn bd;\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/download\/download_file_manager.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/download\/download_util.h\"\n#include \"chrome\/browser\/history\/download_create_info.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_service.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/common\/win_safe_util.h\"\n#elif defined(OS_MACOSX)\n#include \"chrome\/browser\/ui\/cocoa\/file_metadata.h\"\n#endif\n\nnamespace {\n\n\/\/ Throttle updates to the UI thread so that a fast moving download doesn't\n\/\/ cause it to become unresponsive (in milliseconds).\nconst int kUpdatePeriodMs = 500;\n\nDownloadManager* DownloadManagerForRenderViewHost(int render_process_id,\n int render_view_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n TabContents* contents = tab_util::GetTabContentsByID(render_process_id,\n render_view_id);\n if (contents) {\n Profile* profile = contents->profile();\n if (profile)\n return profile->GetDownloadManager();\n }\n\n return NULL;\n}\n\n} \/\/ namespace\n\nDownloadFileManager::DownloadFileManager(ResourceDispatcherHost* rdh)\n : next_id_(0),\n resource_dispatcher_host_(rdh) {\n}\n\nDownloadFileManager::~DownloadFileManager() {\n DCHECK(downloads_.empty());\n}\n\nvoid DownloadFileManager::Shutdown() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::OnShutdown));\n}\n\nvoid DownloadFileManager::OnShutdown() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n StopUpdateTimer();\n STLDeleteValues(&downloads_);\n}\n\nvoid DownloadFileManager::CreateDownloadFile(DownloadCreateInfo* info,\n DownloadManager* download_manager,\n bool get_hash) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" info = \" << info->DebugString();\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n scoped_ptr<DownloadFile>\n download_file(new DownloadFile(info, download_manager));\n if (!download_file->Initialize(get_hash)) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableFunction(&download_util::CancelDownloadRequest,\n resource_dispatcher_host_,\n info->child_id,\n info->request_id));\n delete info;\n return;\n }\n\n DCHECK(GetDownloadFile(info->download_id) == NULL);\n downloads_[info->download_id] = download_file.release();\n \/\/ TODO(phajdan.jr): fix the duplication of path info below.\n info->path = info->save_info.file_path;\n\n \/\/ The file is now ready, we can un-pause the request and start saving data.\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::ResumeDownloadRequest,\n info->child_id, info->request_id));\n\n StartUpdateTimer();\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(download_manager,\n &DownloadManager::StartDownload, info));\n}\n\nvoid DownloadFileManager::ResumeDownloadRequest(int child_id, int request_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n \/\/ This balances the pause in DownloadResourceHandler::OnResponseStarted.\n resource_dispatcher_host_->PauseRequest(child_id, request_id, false);\n}\n\nDownloadFile* DownloadFileManager::GetDownloadFile(int id) {\n DownloadFileMap::iterator it = downloads_.find(id);\n return it == downloads_.end() ? NULL : it->second;\n}\n\nvoid DownloadFileManager::StartUpdateTimer() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n if (!update_timer_.IsRunning()) {\n update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdatePeriodMs),\n this, &DownloadFileManager::UpdateInProgressDownloads);\n }\n}\n\nvoid DownloadFileManager::StopUpdateTimer() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n update_timer_.Stop();\n}\n\nvoid DownloadFileManager::UpdateInProgressDownloads() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n for (DownloadFileMap::iterator i = downloads_.begin();\n i != downloads_.end(); ++i) {\n int id = i->first;\n DownloadFile* download_file = i->second;\n DownloadManager* manager = download_file->GetDownloadManager();\n if (manager) {\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(manager, &DownloadManager::UpdateDownload,\n id, download_file->bytes_so_far()));\n }\n }\n}\n\n\/\/ Called on the IO thread once the ResourceDispatcherHost has decided that a\n\/\/ request is a download.\nint DownloadFileManager::GetNextId() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n return next_id_++;\n}\n\nvoid DownloadFileManager::StartDownload(DownloadCreateInfo* info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n DCHECK(info);\n\n DownloadManager* manager = DownloadManagerForRenderViewHost(\n info->child_id, info->render_view_id);\n if (!manager) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableFunction(&download_util::CancelDownloadRequest,\n resource_dispatcher_host_,\n info->child_id,\n info->request_id));\n delete info;\n return;\n }\n\n manager->CreateDownloadItem(info);\n\n bool hash_needed = resource_dispatcher_host_->safe_browsing_service()->\n DownloadBinHashNeeded();\n\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::CreateDownloadFile,\n info, make_scoped_refptr(manager), hash_needed));\n}\n\n\/\/ We don't forward an update to the UI thread here, since we want to throttle\n\/\/ the UI update rate via a periodic timer. If the user has cancelled the\n\/\/ download (in the UI thread), we may receive a few more updates before the IO\n\/\/ thread gets the cancel message: we just delete the data since the\n\/\/ DownloadFile has been deleted.\nvoid DownloadFileManager::UpdateDownload(int id, DownloadBuffer* buffer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n std::vector<DownloadBuffer::Contents> contents;\n {\n base::AutoLock auto_lock(buffer->lock);\n contents.swap(buffer->contents);\n }\n\n DownloadFile* download = GetDownloadFile(id);\n for (size_t i = 0; i < contents.size(); ++i) {\n net::IOBuffer* data = contents[i].first;\n const int data_len = contents[i].second;\n if (download)\n download->AppendDataToFile(data->data(), data_len);\n data->Release();\n }\n}\n\nvoid DownloadFileManager::OnResponseCompleted(int id, DownloadBuffer* buffer) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n delete buffer;\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it != downloads_.end()) {\n DownloadFile* download = it->second;\n download->Finish();\n\n DownloadManager* download_manager = download->GetDownloadManager();\n if (download_manager) {\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(\n download_manager, &DownloadManager::OnAllDataSaved,\n id, download->bytes_so_far()));\n }\n\n \/\/ We need to keep the download around until the UI thread has finalized\n \/\/ the name.\n if (download->path_renamed()) {\n downloads_.erase(it);\n delete download;\n }\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\n\/\/ This method will be sent via a user action, or shutdown on the UI thread, and\n\/\/ run on the download thread. Since this message has been sent from the UI\n\/\/ thread, the download may have already completed and won't exist in our map.\nvoid DownloadFileManager::CancelDownload(int id) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it != downloads_.end()) {\n DownloadFile* download = it->second;\n VLOG(20) << __FUNCTION__ << \"()\"\n << \" download = \" << download->DebugString();\n download->Cancel();\n\n if (download->path_renamed()) {\n downloads_.erase(it);\n delete download;\n }\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\nvoid DownloadFileManager::OnDownloadManagerShutdown(DownloadManager* manager) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DCHECK(manager);\n\n std::set<DownloadFile*> to_remove;\n\n for (DownloadFileMap::iterator i = downloads_.begin();\n i != downloads_.end(); ++i) {\n DownloadFile* download_file = i->second;\n if (download_file->GetDownloadManager() == manager) {\n download_file->CancelDownloadRequest(resource_dispatcher_host_);\n to_remove.insert(download_file);\n }\n }\n\n for (std::set<DownloadFile*>::iterator i = to_remove.begin();\n i != to_remove.end(); ++i) {\n downloads_.erase((*i)->id());\n delete *i;\n }\n}\n\n\/\/ Actions from the UI thread and run on the download thread\n\n\/\/ The DownloadManager in the UI thread has provided an intermediate .crdownload\n\/\/ name for the download specified by 'id'. Rename the in progress download.\nvoid DownloadFileManager::OnIntermediateDownloadName(\n int id, const FilePath& full_path, DownloadManager* download_manager)\n{\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id\n << \" full_path = \\\"\" << full_path.value() << \"\\\"\";\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it == downloads_.end())\n return;\n\n DownloadFile* download = it->second;\n VLOG(20) << __FUNCTION__ << \"()\" << \" download = \" << download->DebugString();\n if (!download->Rename(full_path, false \/* is_final_rename *\/)) {\n \/\/ Error. Between the time the UI thread generated 'full_path' to the time\n \/\/ this code runs, something happened that prevents us from renaming.\n CancelDownloadOnRename(id);\n }\n}\n\n\/\/ The DownloadManager in the UI thread has provided a final name for the\n\/\/ download specified by 'id'. Rename the in progress download, and remove it\n\/\/ from our table if it has been completed or cancelled already.\n\/\/ |need_delete_crdownload| indicates if we explicitly delete an intermediate\n\/\/ .crdownload file or not.\n\/\/\n\/\/ There are 3 possible rename cases where this method can be called:\n\/\/ 1. tmp -> foo (need_delete_crdownload=T)\n\/\/ 2. foo.crdownload -> foo (need_delete_crdownload=F)\n\/\/ 3. tmp-> Unconfirmed.xxx.crdownload (need_delete_crdownload=F)\nvoid DownloadFileManager::OnFinalDownloadName(\n int id, const FilePath& full_path, bool need_delete_crdownload,\n DownloadManager* download_manager) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id\n << \" full_path = \\\"\" << full_path.value() << \"\\\"\"\n << \" need_delete_crdownload = \" << need_delete_crdownload;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n DownloadFile* download = GetDownloadFile(id);\n if (!download)\n return;\n VLOG(20) << __FUNCTION__ << \"()\" << \" download = \" << download->DebugString();\n if (download->Rename(full_path, true \/* is_final_rename *\/)) {\n#if defined(OS_MACOSX)\n \/\/ Done here because we only want to do this once; see\n \/\/ http:\/\/crbug.com\/13120 for details.\n download->AnnotateWithSourceInformation();\n#endif\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(\n download_manager, &DownloadManager::DownloadRenamedToFinalName, id,\n full_path));\n } else {\n \/\/ Error. Between the time the UI thread generated 'full_path' to the time\n \/\/ this code runs, something happened that prevents us from renaming.\n CancelDownloadOnRename(id);\n }\n\n if (need_delete_crdownload)\n download->DeleteCrDownload();\n\n \/\/ If the download has completed before we got this final name, we remove it\n \/\/ from our in progress map.\n if (!download->in_progress()) {\n downloads_.erase(id);\n delete download;\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\n\/\/ Called only from OnFinalDownloadName or OnIntermediateDownloadName\n\/\/ on the FILE thread.\nvoid DownloadFileManager::CancelDownloadOnRename(int id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n DownloadFile* download = GetDownloadFile(id);\n if (!download)\n return;\n\n DownloadManager* download_manager = download->GetDownloadManager();\n if (!download_manager) {\n download->CancelDownloadRequest(resource_dispatcher_host_);\n return;\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(download_manager,\n &DownloadManager::DownloadCancelled, id));\n}\n<commit_msg>Carnitas: Remove unneeded include from download_file_manager.cc<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/download\/download_file_manager.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/download\/download_util.h\"\n#include \"chrome\/browser\/history\/download_create_info.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_service.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n\nnamespace {\n\n\/\/ Throttle updates to the UI thread so that a fast moving download doesn't\n\/\/ cause it to become unresponsive (in milliseconds).\nconst int kUpdatePeriodMs = 500;\n\nDownloadManager* DownloadManagerForRenderViewHost(int render_process_id,\n int render_view_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n TabContents* contents = tab_util::GetTabContentsByID(render_process_id,\n render_view_id);\n if (contents) {\n Profile* profile = contents->profile();\n if (profile)\n return profile->GetDownloadManager();\n }\n\n return NULL;\n}\n\n} \/\/ namespace\n\nDownloadFileManager::DownloadFileManager(ResourceDispatcherHost* rdh)\n : next_id_(0),\n resource_dispatcher_host_(rdh) {\n}\n\nDownloadFileManager::~DownloadFileManager() {\n DCHECK(downloads_.empty());\n}\n\nvoid DownloadFileManager::Shutdown() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::OnShutdown));\n}\n\nvoid DownloadFileManager::OnShutdown() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n StopUpdateTimer();\n STLDeleteValues(&downloads_);\n}\n\nvoid DownloadFileManager::CreateDownloadFile(DownloadCreateInfo* info,\n DownloadManager* download_manager,\n bool get_hash) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" info = \" << info->DebugString();\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n scoped_ptr<DownloadFile>\n download_file(new DownloadFile(info, download_manager));\n if (!download_file->Initialize(get_hash)) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableFunction(&download_util::CancelDownloadRequest,\n resource_dispatcher_host_,\n info->child_id,\n info->request_id));\n delete info;\n return;\n }\n\n DCHECK(GetDownloadFile(info->download_id) == NULL);\n downloads_[info->download_id] = download_file.release();\n \/\/ TODO(phajdan.jr): fix the duplication of path info below.\n info->path = info->save_info.file_path;\n\n \/\/ The file is now ready, we can un-pause the request and start saving data.\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::ResumeDownloadRequest,\n info->child_id, info->request_id));\n\n StartUpdateTimer();\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(download_manager,\n &DownloadManager::StartDownload, info));\n}\n\nvoid DownloadFileManager::ResumeDownloadRequest(int child_id, int request_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n \/\/ This balances the pause in DownloadResourceHandler::OnResponseStarted.\n resource_dispatcher_host_->PauseRequest(child_id, request_id, false);\n}\n\nDownloadFile* DownloadFileManager::GetDownloadFile(int id) {\n DownloadFileMap::iterator it = downloads_.find(id);\n return it == downloads_.end() ? NULL : it->second;\n}\n\nvoid DownloadFileManager::StartUpdateTimer() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n if (!update_timer_.IsRunning()) {\n update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdatePeriodMs),\n this, &DownloadFileManager::UpdateInProgressDownloads);\n }\n}\n\nvoid DownloadFileManager::StopUpdateTimer() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n update_timer_.Stop();\n}\n\nvoid DownloadFileManager::UpdateInProgressDownloads() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n for (DownloadFileMap::iterator i = downloads_.begin();\n i != downloads_.end(); ++i) {\n int id = i->first;\n DownloadFile* download_file = i->second;\n DownloadManager* manager = download_file->GetDownloadManager();\n if (manager) {\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(manager, &DownloadManager::UpdateDownload,\n id, download_file->bytes_so_far()));\n }\n }\n}\n\n\/\/ Called on the IO thread once the ResourceDispatcherHost has decided that a\n\/\/ request is a download.\nint DownloadFileManager::GetNextId() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n return next_id_++;\n}\n\nvoid DownloadFileManager::StartDownload(DownloadCreateInfo* info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n DCHECK(info);\n\n DownloadManager* manager = DownloadManagerForRenderViewHost(\n info->child_id, info->render_view_id);\n if (!manager) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableFunction(&download_util::CancelDownloadRequest,\n resource_dispatcher_host_,\n info->child_id,\n info->request_id));\n delete info;\n return;\n }\n\n manager->CreateDownloadItem(info);\n\n bool hash_needed = resource_dispatcher_host_->safe_browsing_service()->\n DownloadBinHashNeeded();\n\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(this, &DownloadFileManager::CreateDownloadFile,\n info, make_scoped_refptr(manager), hash_needed));\n}\n\n\/\/ We don't forward an update to the UI thread here, since we want to throttle\n\/\/ the UI update rate via a periodic timer. If the user has cancelled the\n\/\/ download (in the UI thread), we may receive a few more updates before the IO\n\/\/ thread gets the cancel message: we just delete the data since the\n\/\/ DownloadFile has been deleted.\nvoid DownloadFileManager::UpdateDownload(int id, DownloadBuffer* buffer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n std::vector<DownloadBuffer::Contents> contents;\n {\n base::AutoLock auto_lock(buffer->lock);\n contents.swap(buffer->contents);\n }\n\n DownloadFile* download = GetDownloadFile(id);\n for (size_t i = 0; i < contents.size(); ++i) {\n net::IOBuffer* data = contents[i].first;\n const int data_len = contents[i].second;\n if (download)\n download->AppendDataToFile(data->data(), data_len);\n data->Release();\n }\n}\n\nvoid DownloadFileManager::OnResponseCompleted(int id, DownloadBuffer* buffer) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n delete buffer;\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it != downloads_.end()) {\n DownloadFile* download = it->second;\n download->Finish();\n\n DownloadManager* download_manager = download->GetDownloadManager();\n if (download_manager) {\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(\n download_manager, &DownloadManager::OnAllDataSaved,\n id, download->bytes_so_far()));\n }\n\n \/\/ We need to keep the download around until the UI thread has finalized\n \/\/ the name.\n if (download->path_renamed()) {\n downloads_.erase(it);\n delete download;\n }\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\n\/\/ This method will be sent via a user action, or shutdown on the UI thread, and\n\/\/ run on the download thread. Since this message has been sent from the UI\n\/\/ thread, the download may have already completed and won't exist in our map.\nvoid DownloadFileManager::CancelDownload(int id) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it != downloads_.end()) {\n DownloadFile* download = it->second;\n VLOG(20) << __FUNCTION__ << \"()\"\n << \" download = \" << download->DebugString();\n download->Cancel();\n\n if (download->path_renamed()) {\n downloads_.erase(it);\n delete download;\n }\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\nvoid DownloadFileManager::OnDownloadManagerShutdown(DownloadManager* manager) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DCHECK(manager);\n\n std::set<DownloadFile*> to_remove;\n\n for (DownloadFileMap::iterator i = downloads_.begin();\n i != downloads_.end(); ++i) {\n DownloadFile* download_file = i->second;\n if (download_file->GetDownloadManager() == manager) {\n download_file->CancelDownloadRequest(resource_dispatcher_host_);\n to_remove.insert(download_file);\n }\n }\n\n for (std::set<DownloadFile*>::iterator i = to_remove.begin();\n i != to_remove.end(); ++i) {\n downloads_.erase((*i)->id());\n delete *i;\n }\n}\n\n\/\/ Actions from the UI thread and run on the download thread\n\n\/\/ The DownloadManager in the UI thread has provided an intermediate .crdownload\n\/\/ name for the download specified by 'id'. Rename the in progress download.\nvoid DownloadFileManager::OnIntermediateDownloadName(\n int id, const FilePath& full_path, DownloadManager* download_manager)\n{\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id\n << \" full_path = \\\"\" << full_path.value() << \"\\\"\";\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n DownloadFileMap::iterator it = downloads_.find(id);\n if (it == downloads_.end())\n return;\n\n DownloadFile* download = it->second;\n VLOG(20) << __FUNCTION__ << \"()\" << \" download = \" << download->DebugString();\n if (!download->Rename(full_path, false \/* is_final_rename *\/)) {\n \/\/ Error. Between the time the UI thread generated 'full_path' to the time\n \/\/ this code runs, something happened that prevents us from renaming.\n CancelDownloadOnRename(id);\n }\n}\n\n\/\/ The DownloadManager in the UI thread has provided a final name for the\n\/\/ download specified by 'id'. Rename the in progress download, and remove it\n\/\/ from our table if it has been completed or cancelled already.\n\/\/ |need_delete_crdownload| indicates if we explicitly delete an intermediate\n\/\/ .crdownload file or not.\n\/\/\n\/\/ There are 3 possible rename cases where this method can be called:\n\/\/ 1. tmp -> foo (need_delete_crdownload=T)\n\/\/ 2. foo.crdownload -> foo (need_delete_crdownload=F)\n\/\/ 3. tmp-> Unconfirmed.xxx.crdownload (need_delete_crdownload=F)\nvoid DownloadFileManager::OnFinalDownloadName(\n int id, const FilePath& full_path, bool need_delete_crdownload,\n DownloadManager* download_manager) {\n VLOG(20) << __FUNCTION__ << \"()\" << \" id = \" << id\n << \" full_path = \\\"\" << full_path.value() << \"\\\"\"\n << \" need_delete_crdownload = \" << need_delete_crdownload;\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n DownloadFile* download = GetDownloadFile(id);\n if (!download)\n return;\n VLOG(20) << __FUNCTION__ << \"()\" << \" download = \" << download->DebugString();\n if (download->Rename(full_path, true \/* is_final_rename *\/)) {\n#if defined(OS_MACOSX)\n \/\/ Done here because we only want to do this once; see\n \/\/ http:\/\/crbug.com\/13120 for details.\n download->AnnotateWithSourceInformation();\n#endif\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(\n download_manager, &DownloadManager::DownloadRenamedToFinalName, id,\n full_path));\n } else {\n \/\/ Error. Between the time the UI thread generated 'full_path' to the time\n \/\/ this code runs, something happened that prevents us from renaming.\n CancelDownloadOnRename(id);\n }\n\n if (need_delete_crdownload)\n download->DeleteCrDownload();\n\n \/\/ If the download has completed before we got this final name, we remove it\n \/\/ from our in progress map.\n if (!download->in_progress()) {\n downloads_.erase(id);\n delete download;\n }\n\n if (downloads_.empty())\n StopUpdateTimer();\n}\n\n\/\/ Called only from OnFinalDownloadName or OnIntermediateDownloadName\n\/\/ on the FILE thread.\nvoid DownloadFileManager::CancelDownloadOnRename(int id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n DownloadFile* download = GetDownloadFile(id);\n if (!download)\n return;\n\n DownloadManager* download_manager = download->GetDownloadManager();\n if (!download_manager) {\n download->CancelDownloadRequest(resource_dispatcher_host_);\n return;\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(download_manager,\n &DownloadManager::DownloadCancelled, id));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <errno.h>\n#include <iostream>\n#include <string>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <vector>\n#include <pwd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <sys\/utsname.h>\n#include <boost\/foreach.hpp>\n#include <boost\/tokenizer.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nstring shell_prompt(); \/\/prototype for prompt function\nint cmd_interpreter(string); \/\/prototype for command interpreter\nvoid input_redir(vector<string>); \/\/prototype for input redirection function\nint input_helper(string, string);\nvoid output_redir(vector<string>); \/\/prototype for output redirection function\nint output_helper(string, string);\n\nint main (int argc, char** argv)\n{\n\twhile(true)\n\t{\t\n\t\tvector<string> inVector;\n\t\tstring input;\n\t\tinput = shell_prompt();\n\t\t\/\/while (inVector.back() != \"\")\n\t\tif (input == \"exit\")\n\t\t{\n\t\t\tcout << \"Exiting rshell.\" << endl;\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tchar_separator<char> sep(\";\", \"|&#<>\");\n\t\t\tstring t;\n\t\t\ttokenizer< char_separator<char> > tokens(input, sep);\n\t\t\tBOOST_FOREACH(t, tokens)\n\t\t\t{\n\t\t\t\t\/\/TODO do different things depending on delimiters in vector\n\t\t\t\tinVector.push_back(t); \n\t\t\t} \/\/end BOOST_FOREACH\n\t\t\t\n\t\t\tbool comment_sentinel = true;\n\t\t\tbool pipe_sentinel = false;\n\n\t\t\tfor (unsigned i = 0; i < inVector.size(); i++) \/\/go through vector of commands - looking for comments\n\t\t\t{\n\t\t\t\tif(comment_sentinel)\t\/\/if a comment sign is not found, execute\n\t\t\t\t{\n\t\t\t\t\tstring in = inVector.at(i);\n\t\t\tcerr << \"[ \" << in << \" ]\" << endl;\n\t\t\t\t\tif (in.at(0) == '#')\n\t\t\t\t\t{\n\t\t\t\t\t\tcomment_sentinel = false;\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned k = 0; k < inVector.size(); k++)\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tif (inVector.at(k).at(0) == '&')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/TODO: remove later and fix\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '|')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (inVector.at(i + 1).at(0) == '|') \/\/likely to go out of range if at end of command\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tpipe_sentinel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (pipe_sentinel)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\/\/TODO: remove later and fix\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '<')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/input redirection\n\t\t\t\t\t\/\/\tcerr << \"we indir i hope\" << endl;\n\t\t\t\t\t\t\t\tinput_redir(inVector);\n\t\t\t\t\t\t\t\t \/\/input_redir handles\n\t\t\t\t\t\t\t\t comment_sentinel = false; \/\/force a skip\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '>')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/output redirection\n\t\t\t\t\t\/\/\tcerr << \"we outdir i hope\" << endl;\n\t\t\t\t\t\t\t\toutput_redir(inVector);\n\t\t\t\t\t\t\t\t \/\/output_redir function handles this\n\t\t\t\t\t\t\t\t comment_sentinel = false; \/\/force a skip\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\t\t\t\t\t\n\t\t\t\t\t\t\t\t; \/\/nothing\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcmd_interpreter(in);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/TODO: this is for connectors\n\t\t\t\t\/\/ check if the current in.at(0) character equals a connector\n\t\t\t\t\/\/ if it does, check if the next one equals a connector\n\t\t\t\t\/\/ if it does, run both commands\n\t\t\t\t\/\/ check return values of both commands\n\t\t\t\t\/\/ ????\n\t\t\t\t\/\/ profit\n\t\t\t}\/\/endfor\n\t\t}\/\/endif\n\t}\/\/endwhile\n\n\treturn 0;\n}\n\nvoid input_redir(vector<string> input)\n{\n\t\/\/handles all of input redirection\n\tfor (unsigned i = 0; i < input.size(); i++)\n\t{\n\t\tif (input.at(i).at(0) == '<')\n\t\t{\n\/\/\tcerr << \"we input now\" << endl;\n\t\t\tinput_helper(input.at(i-1), input.at(i+1));\n\t\t}\n\t}\n}\n\nint input_helper(string one, string two)\n{\n\tint pid = fork();\n\tif (pid == 0)\n\t{\n\t\t\/\/child\n\t\t\/\/open close dup\n\t\tif (open(two.c_str(), O_RDONLY) != -1)\n\t\t{\n\t\t\tif(close(0) != -1) \/\/stdin\n\t\t\t{\n\t\t\t\tif(dup(0) != -1)\n\t\t\t\t{\n\t\t\/\/cerr << one << endl;\n\t\t\t\t\tcmd_interpreter(one);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tperror(\"dup\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tperror(\"close\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(0) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/parent\n\/\/\t\tclose(0);\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t\tif(close(0) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nvoid output_redir(vector<string> input)\n{\n\t\/\/handles all output redirection\n\tfor (unsigned i = 0; i < input.size(); i++)\n\t{\n\t\t\/\/iterate through vector and finds redirection\t\t\n\t\tif (input.at(i).at(0) == '>')\n\t\t{\n\/\/\t\tcerr << \"we output now\" << endl;\n\t\t\toutput_helper(input.at(i-1), input.at(i+1));\n\t\t}\n\t}\n}\n\nint output_helper(string one, string two)\n{\ncerr << one << \" \" << two << endl;\n\tint pid = fork();\n\tif (pid == 0)\n\t{\n\t\t\/\/child\n\t\t\/\/open close dup\n\t\tif (open(two.c_str(), O_WRONLY | O_CREAT) != -1)\n\t\t{\n\t\t\tif(close(1) != -1) \/\/stdin\n\t\t\t{\n\t\t\t\tif(dup(1) != -1)\n\t\t\t\t{\n\t\t\t\t\tcmd_interpreter(one);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tperror(\"dup\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tperror(\"close\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(1) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/parent\n\/\/\t\tclose(1);\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(1) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nint cmd_interpreter(string input)\/\/, char** argv)\n{\n\t\/\/parse command to seperate command and parameters\n\n\t\/\/int len = input.length();\n\t\n\tvector<string> invector;\n\tstring t;\n\tchar_separator<char> sep(\" \");\n\ttokenizer< char_separator<char> > tokens(input, sep);\n\t\/\/int i = 0;\n\tBOOST_FOREACH(t, tokens)\t\t\/\/tokenize input string with flags to seperate items\n\t{\n\t\tinvector.push_back(t);\n\t}\n\tunsigned len = invector.size();\t\n\n\tconst char** cinput = new const char*[len+2];\n\tconst char* program = invector.at(0).c_str();\n\n\tcinput[0] = program;\n\n\tfor(unsigned i = 1; i < 1 + len; i++)\n\t{\n\t\tcinput[i] = invector[i].c_str();\n\t}\n\tcinput[len] = '\\0';\n\n\/\/\tint pipefd[\n\tint pid = fork();\n\tif(pid == 0)\n\t{\n\t\tif (execvp(program, (char**)cinput) == -1)\n\t\t{\n\t\t\tperror(\"execvp\"); \/\/ throw an error\n\t\t\texit(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/append stuff here\n\n\t\t\/\/parent wait\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\treturn 0;\n} \n\nstring shell_prompt()\n{\n\tstring in;\n\t\/\/TODO - error checking for getlogin and gethostname\n\t\/\/implement later\n\/\/\tstruct utsname name;\n\/\/\terrno = 0;\n\n\/\/\tuname(&name)\n\t\/*\n\tchar name[256];\n\tint maxlen = 64;\n\tif (!gethostname(name, maxlen))\n\t{\n\t\tstring strname(name);\n\t\tcout << getlogin() << \"@\" << name << \"$ \"; \/\/custom prompt with hostname and login name\n\t\tcin >> in;\n\t}\n\telse\n\t{\n\t\tperror(\"gethostname\"); \/\/throw error if not found\n\t}\n\t*\/\n\tcout << \"rshell$ \";\n\tgetline(cin, in);\n\tcin.clear();\n\treturn in;\n}\n<commit_msg>create a change<commit_after>#include <errno.h>\n#include <iostream>\n#include <string>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <vector>\n#include <pwd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <sys\/utsname.h>\n#include <boost\/foreach.hpp>\n#include <boost\/tokenizer.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nstring shell_prompt(); \/\/prototype for prompt function\nint cmd_interpreter(string); \/\/prototype for command interpreter\nvoid input_redir(vector<string>); \/\/prototype for input redirection function\nint input_helper(string, string);\nvoid output_redir(vector<string>); \/\/prototype for output redirection function\nint output_helper(string, string);\n\nint main (int argc, char** argv)\n{\n\twhile(true)\n\t{\t\n\t\tvector<string> inVector;\n\t\tstring input;\n\t\tinput = shell_prompt();\n\t\t\/\/while (inVector.back() != \"\")\n\t\tif (input == \"exit\")\n\t\t{\n\t\t\tcout << \"Exiting rshell.\" << endl;\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tchar_separator<char> sep(\";\", \"|&#<>\");\n\t\t\tstring t;\n\t\t\ttokenizer< char_separator<char> > tokens(input, sep);\n\t\t\tBOOST_FOREACH(t, tokens)\n\t\t\t{\n\t\t\t\t\/\/TODO do different things depending on delimiters in vector\n\t\t\t\tinVector.push_back(t); \n\t\t\t} \/\/end BOOST_FOREACH\n\t\t\t\n\t\t\tbool comment_sentinel = true;\n\t\t\tbool pipe_sentinel = false;\n\n\t\t\tfor (unsigned i = 0; i < inVector.size(); i++) \/\/go through vector of commands - looking for comments\n\t\t\t{\n\t\t\t\tif(comment_sentinel)\t\/\/if a comment sign is not found, execute\n\t\t\t\t{\n\t\t\t\t\tstring in = inVector.at(i);\n\t\t\tcerr << \"[ \" << in << \" ]\" << endl;\n\t\t\t\t\tif (in.at(0) == '#')\n\t\t\t\t\t{\n\t\t\t\t\t\tcomment_sentinel = false;\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned k = 0; k < inVector.size(); k++)\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tif (inVector.at(k).at(0) == '&')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/TODO: remove later and fix\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '|')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (inVector.at(i + 1).at(0) == '|') \/\/likely to go out of range if at end of command\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tpipe_sentinel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (pipe_sentinel)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\/\/TODO: remove later and fix\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '<')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/input redirection\n\t\t\t\t\t\/\/\tcerr << \"we indir i hope\" << endl;\n\t\t\t\t\t\t\t\tinput_redir(inVector);\n\t\t\t\t\t\t\t\t \/\/input_redir handles\n\t\t\t\t\t\t\t\t comment_sentinel = false; \/\/force a skip\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\telse if (inVector.at(k).at(0) == '>')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\/\/output redirection\n\t\t\t\t\t\/\/\tcerr << \"we outdir i hope\" << endl;\n\t\t\t\t\t\t\t\toutput_redir(inVector);\n\t\t\t\t\t\t\t\t \/\/output_redir function handles this\n\t\t\t\t\t\t\t\t comment_sentinel = false; \/\/force a skip\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\t\t\t\t\t\n\t\t\t\t\t\t\t\t; \/\/nothing\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcmd_interpreter(in);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/TODO: this is for connectors\n\t\t\t\t\/\/ check if the current in.at(0) character equals a connector\n\t\t\t\t\/\/ if it does, check if the next one equals a connector\n\t\t\t\t\/\/ if it does, run both commands\n\t\t\t\t\/\/ check return values of both commands\n\t\t\t\t\/\/ ????\n\t\t\t\t\/\/ profit\n\t\t\t}\/\/endfor\n\t\t}\/\/endif\n\t}\/\/endwhile\n\n\treturn 0;\n}\n\nvoid input_redir(vector<string> input)\n{\n\t\/\/handles all of input redirection\n\tfor (unsigned i = 0; i < input.size(); i++)\n\t{\n\t\tif (input.at(i).at(0) == '<')\n\t\t{\n\/\/\tcerr << \"we input now\" << endl;\n\t\t\tinput_helper(input.at(i-1), input.at(i+1));\n\t\t}\n\t}\n}\n\nint input_helper(string one, string two)\n{\n\tint pid = fork();\n\tif (pid == 0)\n\t{\n\t\t\/\/child\n\t\t\/\/open close dup\n\t\tif (open(two.c_str(), O_RDONLY) != -1)\n\t\t{\n\t\t\tif(close(0) != -1) \/\/stdin\n\t\t\t{\n\t\t\t\tif(dup(0) != -1)\n\t\t\t\t{\n\t\t\/\/cerr << one << endl;\n\t\t\t\t\tcmd_interpreter(one);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tperror(\"dup\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tperror(\"close\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(0) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/parent\n\/\/\t\tclose(0);\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t\tif(close(0) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nvoid output_redir(vector<string> input)\n{\n\t\/\/handles all output redirection\n\tfor (unsigned i = 0; i < input.size(); i++)\n\t{\n\t\t\/\/iterate through vector and finds redirection\t\t\n\t\tif (input.at(i).at(0) == '>')\n\t\t{\n\/\/\t\tcerr << \"we output now\" << endl;\n\t\t\toutput_helper(input.at(i-1), input.at(i+1));\n\t\t}\n\t}\n}\n\nint output_helper(string one, string two)\n{\ncerr << one << \" \" << two << endl;\n\tint pid = fork();\n\tif (pid == 0)\n\t{\n\t\t\/\/child\n\t\t\/\/open close dup\n\t\tif (open(two.c_str(), O_WRONLY | O_CREAT) != -1)\n\t\t{\n\t\t\tif(close(1) != -1) \/\/stdin\n\t\t\t{\n\t\t\t\tif(dup(1) != -1)\n\t\t\t\t{\n\t\t\t\t\tcmd_interpreter(one);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tperror(\"dup\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tperror(\"close\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(1) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/parent\n\/\/\t\tclose(1);\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t\tif (close(1) == -1)\n\t\t{\n\t\t\tperror(\"close\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nint cmd_interpreter(string input)\/\/, char** argv)\n{\n\t\/\/parse command to seperate command and parameters\n\n\t\/\/int len = input.length();\n\t\n\tvector<string> invector;\n\tstring t;\n\tchar_separator<char> sep(\" \");\n\ttokenizer< char_separator<char> > tokens(input, sep);\n\t\/\/int i = 0;\n\tBOOST_FOREACH(t, tokens)\t\t\/\/tokenize input string with flags to seperate items\n\t{\n\t\tinvector.push_back(t);\n\t}\n\tunsigned len = invector.size();\t\n\n\tconst char** cinput = new const char*[len+2];\n\tconst char* program = invector.at(0).c_str();\n\n\tcinput[0] = program;\n\n\tfor(unsigned i = 1; i < 1 + len; i++)\n\t{\n\t\tcinput[i] = invector[i].c_str();\n\t}\n\tcinput[len] = '\\0';\n\n\/\/\tint pipefd[\n\tint pid = fork();\n\tif(pid == 0)\n\t{\n\t\tif (execvp(program, (char**)cinput) == -1)\n\t\t{\n\t\t\tperror(\"execvp\"); \/\/ throw an error\n\t\t\texit(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/append stuff here\n\n\t\t\/\/parent wait\n\t\tif (waitpid(-1, NULL, 0) == -1)\n\t\t{\n\t\t\tperror(\"waitpid\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\treturn 0;\n} \n\nstring shell_prompt()\n{\n\tstring in;\n\t\/\/TODO - error checking for getlogin and gethostname\n\t\/\/implement later\n\/\/\tstruct utsname name;\n\/\/\terrno = 0;\n\/\/\tuname(&name)\n\t\/*\n\tchar name[256];\n\tint maxlen = 64;\n\tif (!gethostname(name, maxlen))\n\t{\n\t\tstring strname(name);\n\t\tcout << getlogin() << \"@\" << name << \"$ \"; \/\/custom prompt with hostname and login name\n\t\tcin >> in;\n\t}\n\telse\n\t{\n\t\tperror(\"gethostname\"); \/\/throw error if not found\n\t}\n\t*\/\n\tcout << \"rshell$ \";\n\tgetline(cin, in);\n\tcin.clear();\n\treturn in;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\n#endif \/\/ !defined(OS_MACOSX)\n\nnamespace {\n\nclass SavePageFinishedObserver : public NotificationObserver {\n public:\n SavePageFinishedObserver() {\n registrar_.Add(this, NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n ui_test_utils::RunMessageLoop();\n }\n\n GURL page_url() const { return page_url_; }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED) {\n page_url_ = *Details<GURL>(details).ptr();\n MessageLoopForUI::current()->Quit();\n } else {\n NOTREACHED();\n }\n }\n\n private:\n NotificationRegistrar registrar_;\n\n GURL page_url_;\n\n DISALLOW_COPY_AND_ASSIGN(SavePageFinishedObserver);\n};\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n} \/\/ namespace\n<commit_msg>Enable browser_tests: SavePageBrowserTest.FileNameFromPageTitle & SavePageBrowserTest.SaveHTMLOnly on the Mac.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\nnamespace {\n\nclass SavePageFinishedObserver : public NotificationObserver {\n public:\n SavePageFinishedObserver() {\n registrar_.Add(this, NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n ui_test_utils::RunMessageLoop();\n }\n\n GURL page_url() const { return page_url_; }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED) {\n page_url_ = *Details<GURL>(details).ptr();\n MessageLoopForUI::current()->Quit();\n } else {\n NOTREACHED();\n }\n }\n\n private:\n NotificationRegistrar registrar_;\n\n GURL page_url_;\n\n DISALLOW_COPY_AND_ASSIGN(SavePageFinishedObserver);\n};\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#include \"MuMaterial.h\"\n#include \"counter_point.hpp\"\n\nusing namespace std;\n\nvoid ValidateArguments (int argc, char* argv[]);\nvoid PrintVector (vector<int> v, string message);\nvector<int> GetHarmonicRange (int note_pitch);\nvector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs);\nvector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs);\n\nint main (int argc, char* argv[])\n{\n \/\/ ValidateArguments(argc, argv);\n\n \/\/ string output_path = argc > 2 ? argv[2] : \".\/\";\n \/\/ string score_file_path = argv[1];\n\n \/\/ MuInit();\n \/\/ MuMaterial material;\n \/\/ material.LoadScore(argv[1]);\n\n \/\/ material.SetDefaultFunctionTables();\n \/\/ material.Score(output_path + \"score\");\n \/\/ material.Orchestra(output_path + \"orchestra\");\n\n MuNote note;\n MuMaterial material;\n\n note.SetPitch(60);\n material += note;\n\n note.SetPitch(62);\n material += note;\n\n note.SetPitch(64);\n material += note;\n\n CounterPoint counter_point(material);\n counter_point.PrintHarmonicPitchs();\n\n return 0;\n}\n\nvoid ValidateArguments (int argc, char* argv[])\n{\n bool has_arguments = argc < 2;\n if (has_arguments)\n {\n cout << \"Usage: \" << argv[0] << \" [score_file_path] [output_path]\" << endl;\n exit(-1);\n }\n}\n\nvoid PrintVector (vector<int> v, string message)\n{\n cout << message << \": \";\n for (unsigned int index = 0; index < v.size(); index++)\n {\n cout << v[index] << \" \";\n }\n cout << endl;\n}\n\nvector<int> GetHarmonicRange (int note_pitch)\n{\n int unison = note_pitch;\n int third_minor = note_pitch - 3;\n int third_major = note_pitch - 4;\n int fifith_perfect = note_pitch - 7;\n int sixth_minor = note_pitch - 8;\n int sixth_major = note_pitch - 9;\n\n vector<int> harmonic_range {unison, third_minor, third_major,\n fifith_perfect, sixth_minor, sixth_major};\n\n return harmonic_range;\n}\n\nvector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs)\n{\n scale_pitch = scale_pitch % 12;\n\n vector<int> scale_pitchs = { 0 + scale_pitch, 2 + scale_pitch,\n 4 + scale_pitch, 5 + scale_pitch,\n 7 + scale_pitch, 9 + scale_pitch,\n 11 + scale_pitch };\n\n vector<int> pitchs_on_scale;\n\n for (unsigned int index = 0; index < pitchs.size(); index++)\n {\n int pitch = pitchs[index] % 12;\n bool found_pitch = find(scale_pitchs.begin(), scale_pitchs.end(),\n pitch) != scale_pitchs.end();\n\n if(found_pitch)\n {\n pitchs_on_scale.push_back(pitchs[index]);\n }\n }\n\n return pitchs_on_scale;\n}\n\nvector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs)\n{\n vector<int> pitchs_without_unison = pitchs;\n\n pitchs_without_unison.erase(remove(pitchs_without_unison.begin(),\n pitchs_without_unison.end(),\n unison_pitch),\n pitchs_without_unison.end());\n\n return pitchs_without_unison;\n}\n<commit_msg>Back main.cpp to load file<commit_after>#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#include \"MuMaterial.h\"\n#include \"counter_point.hpp\"\n\nusing namespace std;\n\nvoid ValidateArguments (int argc, char* argv[]);\nvoid PrintVector (vector<int> v, string message);\nvector<int> GetHarmonicRange (int note_pitch);\nvector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs);\nvector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs);\n\nint main (int argc, char* argv[])\n{\n ValidateArguments(argc, argv);\n\n string output_path = argc > 2 ? argv[2] : \".\/\";\n string score_file_path = argv[1];\n\n MuInit();\n MuMaterial material;\n material.LoadScore(argv[1]);\n\n CounterPoint counter_point(material);\n counter_point.SetScalePitch(60);\n counter_point.PrintHarmonicPitchs();\n\n material.SetDefaultFunctionTables();\n material.Score(output_path + \"score\");\n material.Orchestra(output_path + \"orchestra\");\n\n \/\/ MuNote note;\n \/\/ MuMaterial material;\n\n \/\/ note.SetPitch(60);\n \/\/ material += note;\n\n \/\/ note.SetPitch(62);\n \/\/ material += note;\n\n \/\/ note.SetPitch(64);\n \/\/ material += note;\n\n \/\/ CounterPoint counter_point(material);\n \/\/ counter_point.PrintHarmonicPitchs();\n\n return 0;\n}\n\nvoid ValidateArguments (int argc, char* argv[])\n{\n bool has_arguments = argc < 2;\n if (has_arguments)\n {\n cout << \"Usage: \" << argv[0] << \" [score_file_path] [output_path]\" << endl;\n exit(-1);\n }\n}\n\nvoid PrintVector (vector<int> v, string message)\n{\n cout << message << \": \";\n for (unsigned int index = 0; index < v.size(); index++)\n {\n cout << v[index] << \" \";\n }\n cout << endl;\n}\n\nvector<int> GetHarmonicRange (int note_pitch)\n{\n int unison = note_pitch;\n int third_minor = note_pitch - 3;\n int third_major = note_pitch - 4;\n int fifith_perfect = note_pitch - 7;\n int sixth_minor = note_pitch - 8;\n int sixth_major = note_pitch - 9;\n\n vector<int> harmonic_range {unison, third_minor, third_major,\n fifith_perfect, sixth_minor, sixth_major};\n\n return harmonic_range;\n}\n\nvector<int> FixPitchsToScale (int scale_pitch, vector<int> pitchs)\n{\n scale_pitch = scale_pitch % 12;\n\n vector<int> scale_pitchs = { 0 + scale_pitch, 2 + scale_pitch,\n 4 + scale_pitch, 5 + scale_pitch,\n 7 + scale_pitch, 9 + scale_pitch,\n 11 + scale_pitch };\n\n vector<int> pitchs_on_scale;\n\n for (unsigned int index = 0; index < pitchs.size(); index++)\n {\n int pitch = pitchs[index] % 12;\n bool found_pitch = find(scale_pitchs.begin(), scale_pitchs.end(),\n pitch) != scale_pitchs.end();\n\n if(found_pitch)\n {\n pitchs_on_scale.push_back(pitchs[index]);\n }\n }\n\n return pitchs_on_scale;\n}\n\nvector<int> RemoveUnisonFromPitchs(int unison_pitch, vector<int> pitchs)\n{\n vector<int> pitchs_without_unison = pitchs;\n\n pitchs_without_unison.erase(remove(pitchs_without_unison.begin(),\n pitchs_without_unison.end(),\n unison_pitch),\n pitchs_without_unison.end());\n\n return pitchs_without_unison;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2014 Jonas Platte\n *\n * This file is part of Cyvasse Online.\n *\n * Cyvasse Online is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU Affero General Public License as published by the Free Software Foundation,\n * either version 3 of the License, or (at your option) any later version.\n *\n * Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License along with this program.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <tnt\/tntconfig.h>\n#include <tnt\/tntnet.h>\n#include <cxxtools\/log.h>\n#include <yaml-cpp\/yaml.h>\n\nusing namespace std;\n\nint main()\n{\n\tlog_init(\"log.xml\");\n\n\tauto config = YAML::LoadFile(\"config.yml\");\n\tauto listenPort = config[\"listenPort\"].as<int>();\n\tauto staticDir = config[\"staticDir\"].as<string>();\n\n\ttry\n\t{\n\t\ttnt::Tntnet app;\n\n\t\tapp.listen(listenPort);\n\t\tapp.setAppName(\"cyvasse-online\");\n\n\t\t\/\/ setArg() and setting the documentRoot per\n\t\t\/\/ mapping require the git version of tntnet\n\n\t\t\/\/ static files\n\t\tapp.mapUrl(\"^\/(.+)$\", \"static@tntnet\").setPathInfo(\"$1\")\n\t\t\t.setArg(\"documentRoot\", staticDir);\n\t\tapp.mapUrl(\"^\/css\/(.+)$\", \"static@tntnet\").setPathInfo(\"$1\")\n\t\t\t.setArg(\"documentRoot\", \"resources\/css\");\n\n\t\t\/\/ non-page dynamic content\n\t\tapp.mapUrl(\"^\/random-matches$\", \"random-game-view\");\n\n\t\t\/\/ pages\n\t\tapp.mapUrl(\"^\/$\", \"page\" ).setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/index(\\\\.json)?$\", \"page$1\").setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/index\\\\.htm(l)?$\", \"page\" ).setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/legal$\", \"page\" ).setArg(\"content\", \"legal\");\n\t\tapp.mapUrl(\"^\/match\/.{4}(\\\\.json)?$\", \"page$1\").setArg(\"content\", \"game\");\n\t\tapp.mapUrl(\"^\/rule_sets\/([^.]+)(\\\\.json)?$\", \"page$2\").setArg(\"content\", \"rule-set\").setArg(\"name\", \"$1\");\n\t\t\/\/ 404 if nothing matched\n\t\tapp.mapUrl(\".*\", \"page\" ).setArg(\"content\", \"404\");\n\n\t\tapp.run();\n\t}\n\tcatch(exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Automatically write .pid-file<commit_after>\/* Copyright 2014 Jonas Platte\n *\n * This file is part of Cyvasse Online.\n *\n * Cyvasse Online is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU Affero General Public License as published by the Free Software Foundation,\n * either version 3 of the License, or (at your option) any later version.\n *\n * Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License along with this program.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <csignal>\n#include <cstdio>\n\n#include <unistd.h>\n#include <tnt\/tntconfig.h>\n#include <tnt\/tntnet.h>\n#include <cxxtools\/log.h>\n#include <yaml-cpp\/yaml.h>\n\nusing namespace std;\n\nstatic constexpr const char* pidFileName = \"cyvasse-online.pid\";\n\nvoid createPidFile();\nvoid removePidFile();\nvoid setupSignals();\n\nint main()\n{\n\tsetupSignals();\n\n\tlog_init(\"log.xml\");\n\n\tauto config = YAML::LoadFile(\"config.yml\");\n\tauto listenPort = config[\"listenPort\"].as<int>();\n\tauto staticDir = config[\"staticDir\"].as<string>();\n\n\tint retVal = 0;\n\n\ttry\n\t{\n\t\tcreatePidFile();\n\n\t\ttnt::Tntnet app;\n\n\t\tapp.listen(listenPort);\n\t\tapp.setAppName(\"cyvasse-online\");\n\n\t\t\/\/ setArg() and setting the documentRoot per\n\t\t\/\/ mapping require the git version of tntnet\n\n\t\t\/\/ static files\n\t\tapp.mapUrl(\"^\/(.+)$\", \"static@tntnet\").setPathInfo(\"$1\")\n\t\t\t.setArg(\"documentRoot\", staticDir);\n\t\tapp.mapUrl(\"^\/css\/(.+)$\", \"static@tntnet\").setPathInfo(\"$1\")\n\t\t\t.setArg(\"documentRoot\", \"resources\/css\");\n\n\t\t\/\/ non-page dynamic content\n\t\tapp.mapUrl(\"^\/random-matches$\", \"random-game-view\");\n\n\t\t\/\/ pages\n\t\tapp.mapUrl(\"^\/$\", \"page\" ).setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/index(\\\\.json)?$\", \"page$1\").setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/index\\\\.htm(l)?$\", \"page\" ).setArg(\"content\", \"index\");\n\t\tapp.mapUrl(\"^\/legal$\", \"page\" ).setArg(\"content\", \"legal\");\n\t\tapp.mapUrl(\"^\/match\/.{4}(\\\\.json)?$\", \"page$1\").setArg(\"content\", \"game\");\n\t\tapp.mapUrl(\"^\/rule_sets\/([^.]+)(\\\\.json)?$\", \"page$2\").setArg(\"content\", \"rule-set\").setArg(\"name\", \"$1\");\n\t\t\/\/ 404 if nothing matched\n\t\tapp.mapUrl(\".*\", \"page\" ).setArg(\"content\", \"404\");\n\n\t\tapp.run();\n\t}\n\tcatch(exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t\tretVal = 1;\n\t}\n\n\tremovePidFile();\n\treturn retVal;\n}\n\nvoid createPidFile()\n{\n\tofstream pidFile(pidFileName);\n\tif(pidFile)\n\t{\n\t\tpidFile << getpid();\n\t\tpidFile.close();\n\t}\n}\n\nvoid removePidFile()\n{\n\tremove(pidFileName);\n}\n\nextern \"C\" void stopWebapp(int \/* signal *\/)\n{\n\tremovePidFile();\n\texit(0);\n}\n\nvoid setupSignals()\n{\n#ifdef HAVE_SIGACTION\n\tstruct sigaction newAction, oldAction;\n\n\t\/\/ setup sigaction struct for stopWebapp\n\tnewAction.sa_handler = stopWebapp;\n\tsigemptyset(&newAction.sa_mask);\n\tnewAction.sa_flags = 0;\n\n\tsigaction(SIGHUP, nullptr, &oldAction);\n\tif(oldAction.sa_handler != SIG_IGN)\n\t\tsigaction(SIGHUP, &newAction, nullptr);\n\n\tsigaction(SIGINT, nullptr, &oldAction);\n\tif(oldAction.sa_handler != SIG_IGN)\n\t\tsigaction(SIGINT, &newAction, nullptr);\n\n\tsigaction(SIGTERM, nullptr, &oldAction);\n\tif(oldAction.sa_handler != SIG_IGN)\n\t\tsigaction(SIGTERM, &newAction, nullptr);\n#else\n\tif(signal(SIGHUP, stopWebapp) == SIG_IGN)\n\t\tsignal(SIGHUP, SIG_IGN);\n\n\tif(signal(SIGINT, stopWebapp) == SIG_IGN)\n\t\tsignal(SIGINT, SIG_IGN);\n\n\tif(signal(SIGTERM, stopWebapp) == SIG_IGN)\n\t\tsignal(SIGTERM, SIG_IGN);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"main.hpp\"\n#include \"system\/printer.hpp\"\n\n#ifndef OBJ_PATH\n#define OBJ_PATH \"share\/cube.obj\"\n#endif\n#ifndef MTL_PATH\n#define MTL_PATH \"share\/cube.mtl\"\n#endif\n#ifndef VERT_PATH\n#define VERT_PATH \"share\/fallback.vert\"\n#endif\n#ifndef FRAG_PATH\n#define FRAG_PATH \"share\/shade.frag\"\n#endif\n\nvoid printErrors(void) {}\n\ntemplate<typename T1, typename... TN>\nvoid printErrors(T1 &t1, TN &... tn) {\n\tfor(auto e : t1) {\n\t\tstd::cout << e << std::endl;\n\t}\n\tprintErrors(tn...);\n}\n\n\nint main(int argc, const char **argv) {\n\tusing namespace Util;\n\tif(glfwInit() == 0) {\n\t\tstd::cout << \"Failed to initialize GLFW \"\n\t\t\t<< glfwGetVersionString() << std::endl;\n\t\treturn 1;\n\t}\n\t\n\tconst char *obj_fname, *mtl_fname, *vert_fname, *frag_fname;\n\n\tif(argc >= 2) obj_fname = argv[1];\n\telse obj_fname = OBJ_PATH;\n\tif(argc >= 3) mtl_fname = argv[2];\n\telse mtl_fname = MTL_PATH;\n\tif(argc >= 4) vert_fname = argv[3];\n\telse vert_fname = VERT_PATH;\n\tif(argc >= 5) frag_fname = argv[4];\n\telse frag_fname = FRAG_PATH;\n\n\tstd::atomic_bool alive(true);\n\tControl::control ctl(alive, obj_fname);\n\tif(!alive) {\n\t\tstd::cout << \"Control construction failed.\" << std::endl;\n\t\tprintErrors(ctl.viewer.errors, ctl.errors);\n\t\treturn 1;\n\t}\n\tif(!ctl.viewer.setProg(alive, vert_fname, frag_fname)) {\n\t\tstd::cout << \"Failed to compile or link shaders.\" << std::endl;\n\t\tstd::cout << \"For shaders \" << vert_fname << \", \"\n\t\t\t<< frag_fname << std::endl;\n\t\tprintErrors(ctl.viewer.errors, ctl.errors);\n\t\treturn 1;\n\t} else {\n\t\tusing namespace System;\n\t\tPrinter<6> printer;\n\t\tstd::string cols[]{\"GLFW\", \"OpenGL\", \"Path\"},\n\t\t\trows[]{\"\", \"Major\", \"Minor\", \"Revision\", \"\",\n\t\t\t\t\"\", \"Wavefront obj\", \"Wavefront mtl\",\n\t\t\t\t\"Vertex shader\", \"Fragment shader\", \"\"},\n\t\t\tpaths[]{obj_fname, mtl_fname, vert_fname, frag_fname};\n\t\tint versions[6]{0};\n\t\tglfwGetVersion(&versions[0], &versions[2], &versions[4]);\n\t\tglGetIntegerv(GL_MAJOR_VERSION, &versions[1]);\n\t\tglGetIntegerv(GL_MINOR_VERSION, &versions[3]);\n\t\tprinter.push(&rows[0], &rows[5]).level()\n\t\t\t.push<int, 3, 2>(versions, &cols[0], &cols[2]).level()\n\t\t\t.insert(0, Printer_Base::repeat(3)).level()\n\t\t\t.push(&rows[5], &rows[5]+6).level()\n\t\t\t.push<std::string, 4, 1, 31>(paths, &cols[2], &cols[3]+1).level();\n\t\tstd::cout << printer << std::endl;\n\n\t\tif(!task::init(alive, &ctl)) {\n\t\t\tstd::cout << \"Control Initialization failed.\" << std::endl;\n\t\t\tprintErrors(ctl.viewer.errors, ctl.errors);\n\t\t\treturn 1;\n\t\t}\n\t}\n\tif(!task::run(alive, &ctl)) {\n\t\tprintErrors(ctl.viewer.errors, ctl.errors);\n\t}\n\n\tglfwTerminate();\n\n\treturn 0;\n}\n<commit_msg>Added error printing back into main<commit_after>#include <iostream>\n\n#include \"main.hpp\"\n#include \"util.hpp\"\n#include \"system\/printer.hpp\"\n\n#ifndef OBJ_PATH\n#define OBJ_PATH \"share\/cube.obj\"\n#endif\n#ifndef MTL_PATH\n#define MTL_PATH \"share\/cube.mtl\"\n#endif\n#ifndef VERT_PATH\n#define VERT_PATH \"share\/fallback.vert\"\n#endif\n#ifndef FRAG_PATH\n#define FRAG_PATH \"share\/shade.frag\"\n#endif\n\nvoid printErrors(std::ostream oss) {}\n\ntemplate<typename T1, typename... TN>\nvoid printErrors(std::ostream oss, T1 &t1, TN &... tn) {\n\tfor(auto e : t1) {\n\t\toss << e << std::endl;\n\t}\n\tprintErrors(oss, tn...);\n}\n\nint main(int argc, const char **argv) {\n\tusing namespace Util;\n\tusing namespace System;\n\tif(glfwInit() == 0) {\n\t\tstd::cout << \"Failed to initialize GLFW \"\n\t\t\t<< glfwGetVersionString() << std::endl;\n\t\treturn 1;\n\t}\n\t\n\tconst char *obj_fname, *mtl_fname, *vert_fname, *frag_fname;\n\n\tif(argc >= 2) obj_fname = argv[1];\n\telse obj_fname = OBJ_PATH;\n\tif(argc >= 3) mtl_fname = argv[2];\n\telse mtl_fname = MTL_PATH;\n\tif(argc >= 4) vert_fname = argv[3];\n\telse vert_fname = VERT_PATH;\n\tif(argc >= 5) frag_fname = argv[4];\n\telse frag_fname = FRAG_PATH;\n\n\tstd::atomic_bool alive(true);\n\tControl::control ctl(alive, obj_fname);\n\tif(!alive) {\n\t\tstd::cout << \"Control construction failed.\" << std::endl;\n\t\tprintErrors(std::cout, ctl.viewer.errors, ctl.errors);\n\t\treturn 1;\n\t}\n\tif(!ctl.viewer.setProg(alive, vert_fname, frag_fname)) {\n\t\tstd::cout << \"Failed to compile or link shaders.\" << std::endl;\n\t\tstd::cout << \"For shaders \" << vert_fname << \", \"\n\t\t\t<< frag_fname << std::endl;\n\t\tprintErrors(std::cout, ctl.viewer.errors, ctl.errors);\n\t\treturn 1;\n\t} else {\n\t\tusing namespace System;\n\t\tPrinter<6> printer;\n\t\tstd::string cols[]{\"GLFW\", \"OpenGL\", \"Path\"},\n\t\t\trows[]{\"\", \"Major\", \"Minor\", \"Revision\", \"\",\n\t\t\t\t\"\", \"Wavefront obj\", \"Wavefront mtl\",\n\t\t\t\t\"Vertex shader\", \"Fragment shader\", \"\"},\n\t\t\tpaths[]{obj_fname, mtl_fname, vert_fname, frag_fname};\n\t\tint versions[6]{0};\n\t\tglfwGetVersion(&versions[0], &versions[2], &versions[4]);\n\t\tglGetIntegerv(GL_MAJOR_VERSION, &versions[1]);\n\t\tglGetIntegerv(GL_MINOR_VERSION, &versions[3]);\n\t\tprinter.push(&rows[0], &rows[5]).level()\n\t\t\t.push<int, 3, 2>(versions, &cols[0], &cols[2]).level()\n\t\t\t.insert(0, Printer_Base::repeat(3)).level()\n\t\t\t.push(&rows[5], &rows[5]+6).level()\n\t\t\t.push<std::string, 4, 1, 31>(paths, &cols[2], &cols[3]+1).level();\n\t\tstd::cout << printer << std::endl;\n\n\t\tif(!task::init(alive, &ctl)) {\n\t\t\tstd::cout << \"Control Initialization failed.\" << std::endl;\n\t\t\tprintErrors(std::cout, ctl.viewer.errors, ctl.errors);\n\t\t\treturn 1;\n\t\t}\n\t}\n\tif(!task::run(alive, &ctl)) {\n\t\tprintErrors(std::cout, ctl.viewer.errors, ctl.errors);\n\t}\n\n\tglfwTerminate();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\r\n\/\/ Main\r\n\/\/==============================================================================\r\n\r\n#include \"mainwindow.h\"\r\n#include \"common.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QDir>\r\n#include <QPointer>\r\n#include <QProcess>\r\n#include <QSettings>\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QtSingleApplication>\r\n\r\n\/\/==============================================================================\r\n\r\nusing namespace OpenCOR;\r\n\r\n\/\/==============================================================================\r\n\r\nvoid removeInstances()\r\n{\r\n \/\/ Remove all 'global' instances\r\n\r\n QSettings(qApp->applicationName()).remove(\"Instances\");\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nint main(int pArgc, char *pArgv[])\r\n{\r\n int res;\r\n\r\n \/\/ Create the application\r\n\r\n QtSingleApplication *app = new QtSingleApplication(pArgc, pArgv);\r\n\r\n \/\/ Some general initialisations\r\n\r\n initApplication(app);\r\n\r\n#ifndef Q_WS_WIN\r\n \/\/ Try to run OpenCOR as a console application\r\n \/\/ Note: in the case of Windows, we have two binaries (.com and .exe which\r\n \/\/ are for the pure console and GUI versions of OpenCOR, resp.). This\r\n \/\/ means that when a console window is open, to enter something like:\r\n \/\/ C:\\>OpenCOR\r\n \/\/ will effectively call OpenCOR.com. From there, should there be no\r\n \/\/ argument that requires console treatment, the GUI version of\r\n \/\/ OpenCOR will then be launched. This is, unfortunately, the only way\r\n \/\/ to have OpenCOR behave as both a console and GUI application on\r\n \/\/ Windows, hence the ..\/winConsole\/main.cpp file which is used to\r\n \/\/ generate the console version of OpenCOR...\r\n\r\n if (consoleApplication(app, &res)) {\r\n \/\/ OpenCOR was run as a proper console application, so...\r\n\r\n delete app;\r\n\r\n return res;\r\n }\r\n#endif\r\n\r\n \/\/ Send a message (containing the arguments that were passed to this\r\n \/\/ instance of OpenCOR) to the 'official' instance of OpenCOR, should there\r\n \/\/ be one. If there is no 'official' instance of OpenCOR, then just carry\r\n \/\/ on as normal, otherwise exit since we only want one instance of OpenCOR\r\n \/\/ at any given time\r\n\r\n QString arguments = app->arguments().join(\"|\");\r\n\r\n if (app->isRunning()) {\r\n app->sendMessage(arguments);\r\n\r\n delete app;\r\n\r\n return 0;\r\n }\r\n\r\n \/\/ Specify where to find non-OpenCOR plugins (only required on Windows)\r\n\r\n#ifdef Q_WS_WIN\r\n app->addLibraryPath( QDir(app->applicationDirPath()).canonicalPath()\r\n +QDir::separator()+QString(\"..\")\r\n +QDir::separator()+\"plugins\");\r\n#endif\r\n\r\n \/\/ Remove all 'global' instances, in case OpenCOR previously crashed or\r\n \/\/ something (and therefore didn't remove all of them before quitting)\r\n\r\n removeInstances();\r\n\r\n \/\/ Create the main window\r\n\r\n MainWindow *win = new MainWindow();\r\n\r\n \/\/ Keep track of the main window (required by QtSingleApplication so that it\r\n \/\/ can do what it's supposed to be doing)\r\n\r\n app->setActivationWindow(win);\r\n\r\n \/\/ Make sure that OpenCOR can handle the message sent by another instance of\r\n \/\/ itself\r\n\r\n QObject::connect(app, SIGNAL(messageReceived(const QString &)),\r\n win, SLOT(singleAppMsgRcvd(const QString &)));\r\n\r\n \/\/ Show the main window\r\n\r\n win->show();\r\n\r\n \/\/ Handle the arguments\r\n\r\n win->handleArguments(arguments);\r\n\r\n \/\/ Execute the application\r\n\r\n res = app->exec();\r\n\r\n \/\/ Keep track of the application file and directory paths (in case we need\r\n \/\/ to restart OpenCOR)\r\n\r\n QString appFilePath = app->applicationFilePath();\r\n QString appDirPath = app->applicationDirPath();\r\n\r\n \/\/ Delete the main window\r\n\r\n delete win;\r\n\r\n \/\/ Remove all 'global' instances that were created and used during this\r\n \/\/ session\r\n\r\n removeInstances();\r\n\r\n \/\/ Delete the application\r\n\r\n delete app;\r\n\r\n \/\/ We are done with the execution of the application, so now the question is\r\n \/\/ whether we need to restart or not\r\n \/\/ Note: we do this here rather than 'within' the GUI because once we have\r\n \/\/ launched a new instance of OpenCOR, we want this instance of\r\n \/\/ OpenCOR to finish as soon as possible which will be the case here\r\n \/\/ since all that remains to be done is to return the result of the\r\n \/\/ execution of the application...\r\n\r\n if (res == OpenCOR::NeedRestart)\r\n \/\/ Restart OpenCOR, but without providing any of the argument with which\r\n \/\/ OpenCOR was originally started, since we want to reset everything\r\n\r\n QProcess::startDetached(appFilePath, QStringList(), appDirPath);\r\n\r\n \/\/ We are done, so...\r\n\r\n return res;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<commit_msg>Working on the opening of OpenCOR-supported files from the file manager (#94).<commit_after>\/\/==============================================================================\r\n\/\/ Main\r\n\/\/==============================================================================\r\n\r\n#include \"mainwindow.h\"\r\n#include \"common.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QDir>\r\n#include <QPointer>\r\n#include <QProcess>\r\n#include <QSettings>\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QtSingleApplication>\r\n\r\n\/\/==============================================================================\r\n\r\nusing namespace OpenCOR;\r\n\r\n\/\/==============================================================================\r\n\r\nvoid removeInstances()\r\n{\r\n \/\/ Remove all 'global' instances\r\n\r\n QSettings(qApp->applicationName()).remove(\"Instances\");\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nint main(int pArgc, char *pArgv[])\r\n{\r\n int res;\r\n\r\n \/\/ Create the application\r\n\r\n QtSingleApplication *app = new QtSingleApplication(pArgc, pArgv);\r\n\r\n \/\/ Some general initialisations\r\n\r\n initApplication(app);\r\n\r\n#ifndef Q_WS_WIN\r\n \/\/ Try to run OpenCOR as a console application\r\n \/\/ Note: in the case of Windows, we have two binaries (.com and .exe which\r\n \/\/ are for the pure console and GUI versions of OpenCOR, resp.). This\r\n \/\/ means that when a console window is open, to enter something like:\r\n \/\/ C:\\>OpenCOR\r\n \/\/ will effectively call OpenCOR.com. From there, should there be no\r\n \/\/ argument that requires console treatment, the GUI version of\r\n \/\/ OpenCOR will then be launched. This is, unfortunately, the only way\r\n \/\/ to have OpenCOR behave as both a console and GUI application on\r\n \/\/ Windows, hence the ..\/winConsole\/main.cpp file which is used to\r\n \/\/ generate the console version of OpenCOR...\r\n\r\n if (consoleApplication(app, &res)) {\r\n \/\/ OpenCOR was run as a proper console application, so...\r\n\r\n delete app;\r\n\r\n return res;\r\n }\r\n#endif\r\n\r\n \/\/ Send a message (containing the arguments that were passed to this\r\n \/\/ instance of OpenCOR) to the 'official' instance of OpenCOR, should there\r\n \/\/ be one. If there is no 'official' instance of OpenCOR, then just carry\r\n \/\/ on as normal, otherwise exit since we only want one instance of OpenCOR\r\n \/\/ at any given time\r\n\r\n QString arguments = app->arguments().join(\"|\");\r\n\r\n if (app->isRunning()) {\r\n app->sendMessage(arguments);\r\n\r\n delete app;\r\n\r\n return 0;\r\n }\r\n\r\n \/\/ Specify where to find non-OpenCOR plugins (only required on Windows)\r\n\r\n#ifdef Q_WS_WIN\r\n app->addLibraryPath( QDir(app->applicationDirPath()).canonicalPath()\r\n +QDir::separator()+QString(\"..\")\r\n +QDir::separator()+\"plugins\");\r\n#endif\r\n\r\n \/\/ Remove all 'global' instances, in case OpenCOR previously crashed or\r\n \/\/ something (and therefore didn't remove all of them before quitting)\r\n\r\n removeInstances();\r\n\r\n \/\/ Create the main window\r\n\r\n MainWindow *win = new MainWindow();\r\n\r\n \/\/ Keep track of the main window (required by QtSingleApplication so that it\r\n \/\/ can do what it's supposed to be doing)\r\n\r\n app->setActivationWindow(win);\r\n\r\n \/\/ Make sure that OpenCOR can handle the message sent by another instance of\r\n \/\/ itself\r\n\r\n QObject::connect(app, SIGNAL(messageReceived(const QString &)),\r\n win, SLOT(singleAppMsgRcvd(const QString &)));\r\n\r\n \/\/ Handle the arguments\r\n\r\n win->handleArguments(arguments);\r\n\r\n \/\/ Show the main window\r\n\r\n win->show();\r\n\r\n \/\/ Execute the application\r\n\r\n res = app->exec();\r\n\r\n \/\/ Keep track of the application file and directory paths (in case we need\r\n \/\/ to restart OpenCOR)\r\n\r\n QString appFilePath = app->applicationFilePath();\r\n QString appDirPath = app->applicationDirPath();\r\n\r\n \/\/ Delete the main window\r\n\r\n delete win;\r\n\r\n \/\/ Remove all 'global' instances that were created and used during this\r\n \/\/ session\r\n\r\n removeInstances();\r\n\r\n \/\/ Delete the application\r\n\r\n delete app;\r\n\r\n \/\/ We are done with the execution of the application, so now the question is\r\n \/\/ whether we need to restart or not\r\n \/\/ Note: we do this here rather than 'within' the GUI because once we have\r\n \/\/ launched a new instance of OpenCOR, we want this instance of\r\n \/\/ OpenCOR to finish as soon as possible which will be the case here\r\n \/\/ since all that remains to be done is to return the result of the\r\n \/\/ execution of the application...\r\n\r\n if (res == OpenCOR::NeedRestart)\r\n \/\/ Restart OpenCOR, but without providing any of the argument with which\r\n \/\/ OpenCOR was originally started, since we want to reset everything\r\n\r\n QProcess::startDetached(appFilePath, QStringList(), appDirPath);\r\n\r\n \/\/ We are done, so...\r\n\r\n return res;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <memory>\n#include <csignal>\n#include <vector>\n#include <thread>\n\n#include \"RtMidi.h\"\n#include \"portaudio.h\"\n\n#define tcm(x){ try{ x } catch(RtMidiError& e){ puts(\"Had an exception:\"); e.printMessage(); exit(1); } };\n#define tcpa(err){ if(err != paNoError){ puts(Pa_GetErrorText(err)); exit(1); } }\n\nusing namespace std;\n\nconstexpr int sample_rate = 44100;\n\nenum MIDI_Action{\n NoteOn = 144,\n NoteOff = 128\n};\n\ninline float midi2hz(unsigned char note){\n float a = (note - 69) \/ 12.0f;\n return 440.0f * powf(2.0f, a);\n}\n\ninline float hz2dphase(float hz){\n return 2.0f * hz \/ float(sample_rate);\n}\n\nbool run = true;\nstatic void on_sigint(int signal){\n run = false;\n}\n\ninline float lerp(float a, float b, float alpha){\n return (1.0f - alpha) * a + alpha * b;\n}\n\nfloat saw_wave(float phase){\n phase \/= 6.2831853f;\n return lerp(-1.0f, 1.0f, phase);\n}\nfloat sine_wave(float phase){\n return sinf(phase);\n}\nfloat square_wave(float phase){\n return phase < 3.141592f ? 1.0f : -1.0f;\n}\nfloat triangle_wave(float phase){\n if(phase < 3.141592f){\n return lerp(-1.0f, 1.0f, phase \/ 3.141592f);\n }\n else{\n phase -= 3.141592f;\n return lerp(1.0f, -1.0f, phase \/ 3.141592f);\n }\n}\n\ntypedef float (*wave_func)(float);\n\nstruct voices{\n float phase[8];\n float dphase[8];\n float amplitude[8];\n wave_func func;\n int tail;\n float out;\n voices() : func(&saw_wave), tail(0), out(0.0f){\n for(int i = 0; i < 8; i++){\n amplitude[i] = 0.0f;\n phase[i] = 0.0f;\n dphase[i] = 0.0f;\n }\n }\n inline void onnote(unsigned char anote){\n dphase[tail] = hz2dphase(midi2hz(anote));\n amplitude[tail] = 1.0f;\n tail = (tail+1) & 7;\n }\n inline void ontick(){\n out = 0.0f;\n for(int i = 0; i < 8; i++){\n out += amplitude[i] * func(phase[i]);\n phase[i] += dphase[i];\n phase[i] = fmod(phase[i], 6.2831853f);\n amplitude[i] *= 0.9999f;\n }\n }\n};\n\nstruct midiud{\n unsigned char note;\n voices* voice;\n};\n\nstatic void on_message(double timestamp, vector<unsigned char>* pmessage, void* userdata){\n if(!pmessage)\n return;\n auto& message = *pmessage;\n midiud* ud = (midiud*)userdata;\n if(message.size() == 3){\n auto& action = message[0];\n auto& note = message[1];\n auto& velocity = message[2];\n if(action == NoteOn){\n ud->voice->onnote(note);\n }\n else if(action == NoteOff){\n }\n }\n}\n\n\nstatic int on_audio(const void* inbuf, void* outbuf, unsigned long num_frames, \n const PaStreamCallbackTimeInfo* timeinfo, PaStreamCallbackFlags flags, void* userdata){\n \n float* output = (float*)outbuf;\n voices* vcs = (voices*)userdata;\n for(unsigned i = 0; i < num_frames; i++){\n *output = vcs->out;\n output++;\n *output = vcs->out;\n output++;\n vcs->ontick();\n }\n\n return 0;\n}\n\nint main(){\n unique_ptr<RtMidiIn> midiin;\n tcm( midiin = make_unique<RtMidiIn>(); )\n\n if(midiin->getPortCount() < 1){\n puts(\"No ports open, quitting.\");\n exit(1);\n }\n puts(midiin->getPortName(0).c_str());\n\n midiin->openPort(0);\n signal(SIGINT, on_sigint);\n voices phase;\n\n midiud midiuserdata;\n midiuserdata.note = 40;\n midiuserdata.voice = &phase;\n midiin->setCallback(on_message, &midiuserdata);\n\n auto err = Pa_Initialize();\n tcpa(err)\n\n PaStream* stream = nullptr; \n err = Pa_OpenDefaultStream(&stream, 0, 2, paFloat32, sample_rate, 32, on_audio, &phase);\n tcpa(err)\n\n err = Pa_StartStream(stream);\n tcpa(err)\n\n while(run){\n this_thread::sleep_for(0.1s);\n }\n\n err = Pa_StopStream(stream);\n tcpa(err)\n\n err = Pa_Terminate();\n tcpa(err)\n\n return 0;\n}<commit_msg>lower amplitude to prevent clipping<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <memory>\n#include <csignal>\n#include <vector>\n#include <thread>\n\n#include \"RtMidi.h\"\n#include \"portaudio.h\"\n\n#define tcm(x){ try{ x } catch(RtMidiError& e){ puts(\"Had an exception:\"); e.printMessage(); exit(1); } };\n#define tcpa(err){ if(err != paNoError){ puts(Pa_GetErrorText(err)); exit(1); } }\n\nusing namespace std;\n\nconstexpr int sample_rate = 44100;\n\nenum MIDI_Action{\n NoteOn = 144,\n NoteOff = 128\n};\n\ninline float midi2hz(unsigned char note){\n float a = (note - 69) \/ 12.0f;\n return 440.0f * powf(2.0f, a);\n}\n\ninline float hz2dphase(float hz){\n return 2.0f * hz \/ float(sample_rate);\n}\n\nbool run = true;\nstatic void on_sigint(int signal){\n run = false;\n}\n\ninline float lerp(float a, float b, float alpha){\n return (1.0f - alpha) * a + alpha * b;\n}\n\nfloat saw_wave(float phase){\n phase \/= 6.2831853f;\n return lerp(-1.0f, 1.0f, phase);\n}\nfloat sine_wave(float phase){\n return sinf(phase);\n}\nfloat square_wave(float phase){\n return phase < 3.141592f ? 1.0f : -1.0f;\n}\nfloat triangle_wave(float phase){\n if(phase < 3.141592f){\n return lerp(-1.0f, 1.0f, phase \/ 3.141592f);\n }\n else{\n phase -= 3.141592f;\n return lerp(1.0f, -1.0f, phase \/ 3.141592f);\n }\n}\n\ntypedef float (*wave_func)(float);\n\nstruct voices{\n float phase[8];\n float dphase[8];\n float amplitude[8];\n wave_func func;\n int tail;\n float out;\n voices() : func(&saw_wave), tail(0), out(0.0f){\n for(int i = 0; i < 8; i++){\n amplitude[i] = 0.0f;\n phase[i] = 0.0f;\n dphase[i] = 0.0f;\n }\n }\n inline void onnote(unsigned char anote){\n dphase[tail] = hz2dphase(midi2hz(anote));\n amplitude[tail] = 0.5f;\n tail = (tail+1) & 7;\n }\n inline void ontick(){\n out = 0.0f;\n for(int i = 0; i < 8; i++){\n out += amplitude[i] * func(phase[i]);\n phase[i] += dphase[i];\n phase[i] = fmod(phase[i], 6.2831853f);\n amplitude[i] *= 0.9999f;\n }\n }\n};\n\nstruct midiud{\n unsigned char note;\n voices* voice;\n};\n\nstatic void on_message(double timestamp, vector<unsigned char>* pmessage, void* userdata){\n if(!pmessage)\n return;\n auto& message = *pmessage;\n midiud* ud = (midiud*)userdata;\n if(message.size() == 3){\n auto& action = message[0];\n auto& note = message[1];\n auto& velocity = message[2];\n if(action == NoteOn){\n ud->voice->onnote(note);\n }\n else if(action == NoteOff){\n }\n }\n}\n\n\nstatic int on_audio(const void* inbuf, void* outbuf, unsigned long num_frames, \n const PaStreamCallbackTimeInfo* timeinfo, PaStreamCallbackFlags flags, void* userdata){\n \n float* output = (float*)outbuf;\n voices* vcs = (voices*)userdata;\n for(unsigned i = 0; i < num_frames; i++){\n *output = vcs->out;\n output++;\n *output = vcs->out;\n output++;\n vcs->ontick();\n }\n\n return 0;\n}\n\nint main(){\n unique_ptr<RtMidiIn> midiin;\n tcm( midiin = make_unique<RtMidiIn>(); )\n\n if(midiin->getPortCount() < 1){\n puts(\"No ports open, quitting.\");\n exit(1);\n }\n puts(midiin->getPortName(0).c_str());\n\n midiin->openPort(0);\n signal(SIGINT, on_sigint);\n voices phase;\n\n midiud midiuserdata;\n midiuserdata.note = 40;\n midiuserdata.voice = &phase;\n midiin->setCallback(on_message, &midiuserdata);\n\n auto err = Pa_Initialize();\n tcpa(err)\n\n PaStream* stream = nullptr; \n err = Pa_OpenDefaultStream(&stream, 0, 2, paFloat32, sample_rate, 32, on_audio, &phase);\n tcpa(err)\n\n err = Pa_StartStream(stream);\n tcpa(err)\n\n while(run){\n this_thread::sleep_for(0.1s);\n }\n\n err = Pa_StopStream(stream);\n tcpa(err)\n\n err = Pa_Terminate();\n tcpa(err)\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_drag_dest_gtk.h\"\n\n#include <string>\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/base\/net_util.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nWebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)\n : tab_contents_(tab_contents),\n widget_(widget),\n context_(NULL),\n method_factory_(this) {\n gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),\n NULL, 0,\n static_cast<GdkDragAction>(GDK_ACTION_COPY |\n GDK_ACTION_LINK |\n GDK_ACTION_MOVE));\n g_signal_connect(widget, \"drag-motion\",\n G_CALLBACK(OnDragMotionThunk), this);\n g_signal_connect(widget, \"drag-leave\",\n G_CALLBACK(OnDragLeaveThunk), this);\n g_signal_connect(widget, \"drag-drop\",\n G_CALLBACK(OnDragDropThunk), this);\n g_signal_connect(widget, \"drag-data-received\",\n G_CALLBACK(OnDragDataReceivedThunk), this);\n \/\/ TODO(tony): Need a drag-data-delete handler for moving content out of\n \/\/ the tab contents. http:\/\/crbug.com\/38989\n\n destroy_handler_ = g_signal_connect(\n widget, \"destroy\", G_CALLBACK(gtk_widget_destroyed), &widget_);\n}\n\nWebDragDestGtk::~WebDragDestGtk() {\n if (widget_) {\n gtk_drag_dest_unset(widget_);\n g_signal_handler_disconnect(widget_, destroy_handler_);\n }\n}\n\nvoid WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {\n if (context_) {\n is_drop_target_ = operation != WebDragOperationNone;\n gdk_drag_status(context_, gtk_dnd_util::WebDragOpToGdkDragAction(operation),\n drag_over_time_);\n }\n}\n\nvoid WebDragDestGtk::DragLeave() {\n tab_contents_->render_view_host()->DragTargetDragLeave();\n\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);\n }\n}\n\ngboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,\n GdkDragContext* context,\n gint x, gint y,\n guint time) {\n if (context_ != context) {\n context_ = context;\n drop_data_.reset(new WebDropData);\n bookmark_drag_data_.Clear();\n is_drop_target_ = false;\n\n static int supported_targets[] = {\n gtk_dnd_util::TEXT_PLAIN,\n gtk_dnd_util::TEXT_URI_LIST,\n gtk_dnd_util::TEXT_HTML,\n gtk_dnd_util::NETSCAPE_URL,\n gtk_dnd_util::CHROME_NAMED_URL,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n \/\/ TODO(estade): support image drags?\n };\n\n data_requests_ = arraysize(supported_targets);\n for (size_t i = 0; i < arraysize(supported_targets); ++i) {\n gtk_drag_get_data(widget_, context,\n gtk_dnd_util::GetAtomForTarget(supported_targets[i]),\n time);\n }\n } else if (data_requests_ == 0) {\n tab_contents_->render_view_host()->\n DragTargetDragOver(\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);\n drag_over_time_ = time;\n }\n\n \/\/ Pretend we are a drag destination because we don't want to wait for\n \/\/ the renderer to tell us if we really are or not.\n return TRUE;\n}\n\nvoid WebDragDestGtk::OnDragDataReceived(\n GtkWidget* sender, GdkDragContext* context, gint x, gint y,\n GtkSelectionData* data, guint info, guint time) {\n \/\/ We might get the data from an old get_data() request that we no longer\n \/\/ care about.\n if (context != context_)\n return;\n\n data_requests_--;\n\n \/\/ Decode the data.\n if (data->data && data->length > 0) {\n \/\/ If the source can't provide us with valid data for a requested target,\n \/\/ data->data will be NULL.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {\n guchar* text = gtk_selection_data_get_text(data);\n if (text) {\n drop_data_->plain_text =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),\n data->length));\n g_free(text);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {\n gchar** uris = gtk_selection_data_get_uris(data);\n if (uris) {\n for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {\n \/\/ TODO(estade): Can the filenames have a non-UTF8 encoding?\n FilePath file_path;\n if (net::FileURLToFilePath(GURL(*uri_iter), &file_path))\n drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));\n }\n \/\/ Also, write the first URI as the URL.\n if (uris[0])\n drop_data_->url = GURL(uris[0]);\n g_strfreev(uris);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {\n \/\/ TODO(estade): Can the html have a non-UTF8 encoding?\n drop_data_->text_html =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),\n data->length));\n \/\/ We leave the base URL empty.\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {\n std::string netscape_url(reinterpret_cast<char*>(data->data),\n data->length);\n size_t split = netscape_url.find_first_of('\\n');\n if (split != std::string::npos) {\n drop_data_->url = GURL(netscape_url.substr(0, split));\n if (split < netscape_url.size() - 1)\n drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {\n gtk_dnd_util::ExtractNamedURL(data,\n &drop_data_->url, &drop_data_->url_title);\n }\n }\n\n \/\/ For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source\n \/\/ doesn't have any data available for us. In this case we try to synthesize a\n \/\/ URL bookmark.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM)) {\n if (data->data && data->length > 0) {\n bookmark_drag_data_.ReadFromVector(\n bookmark_utils::GetNodesFromSelection(\n NULL, data,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n tab_contents_->profile(), NULL, NULL));\n bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());\n } else {\n bookmark_drag_data_.ReadFromTuple(drop_data_->url,\n drop_data_->url_title);\n }\n }\n\n if (data_requests_ == 0) {\n \/\/ Tell the renderer about the drag.\n \/\/ |x| and |y| are seemingly arbitrary at this point.\n tab_contents_->render_view_host()->\n DragTargetDragEnter(*drop_data_.get(),\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(\n bookmark_drag_data_);\n }\n\n drag_over_time_ = time;\n }\n}\n\n\/\/ The drag has left our widget; forward this information to the renderer.\nvoid WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,\n guint time) {\n \/\/ Set |context_| to NULL to make sure we will recognize the next DragMotion\n \/\/ as an enter.\n context_ = NULL;\n drop_data_.reset();\n \/\/ When GTK sends us a drag-drop signal, it is shortly (and synchronously)\n \/\/ preceded by a drag-leave. The renderer doesn't like getting the signals\n \/\/ in this order so delay telling it about the drag-leave till we are sure\n \/\/ we are not getting a drop as well.\n MessageLoop::current()->PostTask(FROM_HERE,\n method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));\n}\n\n\/\/ Called by GTK when the user releases the mouse, executing a drop.\ngboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,\n gint x, gint y, guint time) {\n \/\/ Cancel that drag leave!\n method_factory_.RevokeAll();\n\n tab_contents_->render_view_host()->\n DragTargetDrop(gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);\n\n \/\/ The second parameter is just an educated guess as to whether or not the\n \/\/ drag succeeded, but at least we will get the drag-end animation right\n \/\/ sometimes.\n gtk_drag_finish(context, is_drop_target_, FALSE, time);\n return TRUE;\n}\n<commit_msg>Don't populate WebDropData with file URLs when dragging files.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_drag_dest_gtk.h\"\n\n#include <string>\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/base\/net_util.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nWebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)\n : tab_contents_(tab_contents),\n widget_(widget),\n context_(NULL),\n method_factory_(this) {\n gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),\n NULL, 0,\n static_cast<GdkDragAction>(GDK_ACTION_COPY |\n GDK_ACTION_LINK |\n GDK_ACTION_MOVE));\n g_signal_connect(widget, \"drag-motion\",\n G_CALLBACK(OnDragMotionThunk), this);\n g_signal_connect(widget, \"drag-leave\",\n G_CALLBACK(OnDragLeaveThunk), this);\n g_signal_connect(widget, \"drag-drop\",\n G_CALLBACK(OnDragDropThunk), this);\n g_signal_connect(widget, \"drag-data-received\",\n G_CALLBACK(OnDragDataReceivedThunk), this);\n \/\/ TODO(tony): Need a drag-data-delete handler for moving content out of\n \/\/ the tab contents. http:\/\/crbug.com\/38989\n\n destroy_handler_ = g_signal_connect(\n widget, \"destroy\", G_CALLBACK(gtk_widget_destroyed), &widget_);\n}\n\nWebDragDestGtk::~WebDragDestGtk() {\n if (widget_) {\n gtk_drag_dest_unset(widget_);\n g_signal_handler_disconnect(widget_, destroy_handler_);\n }\n}\n\nvoid WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {\n if (context_) {\n is_drop_target_ = operation != WebDragOperationNone;\n gdk_drag_status(context_, gtk_dnd_util::WebDragOpToGdkDragAction(operation),\n drag_over_time_);\n }\n}\n\nvoid WebDragDestGtk::DragLeave() {\n tab_contents_->render_view_host()->DragTargetDragLeave();\n\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);\n }\n}\n\ngboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,\n GdkDragContext* context,\n gint x, gint y,\n guint time) {\n if (context_ != context) {\n context_ = context;\n drop_data_.reset(new WebDropData);\n bookmark_drag_data_.Clear();\n is_drop_target_ = false;\n\n \/\/ text\/plain must come before text\/uri-list. This is a hack that works in\n \/\/ conjunction with OnDragDataReceived. Since some file managers populate\n \/\/ text\/plain with file URLs when dragging files, we want to handle\n \/\/ text\/uri-list after text\/plain so that the plain text can be cleared if\n \/\/ it's a file drag.\n static int supported_targets[] = {\n gtk_dnd_util::TEXT_PLAIN,\n gtk_dnd_util::TEXT_URI_LIST,\n gtk_dnd_util::TEXT_HTML,\n gtk_dnd_util::NETSCAPE_URL,\n gtk_dnd_util::CHROME_NAMED_URL,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n \/\/ TODO(estade): support image drags?\n };\n\n data_requests_ = arraysize(supported_targets);\n for (size_t i = 0; i < arraysize(supported_targets); ++i) {\n gtk_drag_get_data(widget_, context,\n gtk_dnd_util::GetAtomForTarget(supported_targets[i]),\n time);\n }\n } else if (data_requests_ == 0) {\n tab_contents_->render_view_host()->\n DragTargetDragOver(\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);\n drag_over_time_ = time;\n }\n\n \/\/ Pretend we are a drag destination because we don't want to wait for\n \/\/ the renderer to tell us if we really are or not.\n return TRUE;\n}\n\nvoid WebDragDestGtk::OnDragDataReceived(\n GtkWidget* sender, GdkDragContext* context, gint x, gint y,\n GtkSelectionData* data, guint info, guint time) {\n \/\/ We might get the data from an old get_data() request that we no longer\n \/\/ care about.\n if (context != context_)\n return;\n\n data_requests_--;\n\n \/\/ Decode the data.\n if (data->data && data->length > 0) {\n \/\/ If the source can't provide us with valid data for a requested target,\n \/\/ data->data will be NULL.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {\n guchar* text = gtk_selection_data_get_text(data);\n if (text) {\n drop_data_->plain_text =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),\n data->length));\n g_free(text);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {\n gchar** uris = gtk_selection_data_get_uris(data);\n if (uris) {\n drop_data_->url = GURL();\n for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {\n \/\/ Most file managers populate text\/uri-list with file URLs when\n \/\/ dragging files. To avoid exposing file system paths to web content,\n \/\/ file URLs are never set as the URL content for the drop.\n \/\/ TODO(estade): Can the filenames have a non-UTF8 encoding?\n FilePath file_path;\n if (net::FileURLToFilePath(GURL(*uri_iter), &file_path)) {\n drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));\n \/\/ This is a hack. Some file managers also populate text\/plain with\n \/\/ a file URL when dragging files, so we clear it to avoid exposing\n \/\/ it to the web content.\n drop_data_->plain_text.clear();\n } else if (!drop_data_->url.is_valid()) {\n \/\/ Also set the first non-file URL as the URL content for the drop.\n drop_data_->url = GURL(*uri_iter);\n }\n }\n g_strfreev(uris);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {\n \/\/ TODO(estade): Can the html have a non-UTF8 encoding?\n drop_data_->text_html =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),\n data->length));\n \/\/ We leave the base URL empty.\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {\n std::string netscape_url(reinterpret_cast<char*>(data->data),\n data->length);\n size_t split = netscape_url.find_first_of('\\n');\n if (split != std::string::npos) {\n drop_data_->url = GURL(netscape_url.substr(0, split));\n if (split < netscape_url.size() - 1)\n drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {\n gtk_dnd_util::ExtractNamedURL(data,\n &drop_data_->url, &drop_data_->url_title);\n }\n }\n\n \/\/ For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source\n \/\/ doesn't have any data available for us. In this case we try to synthesize a\n \/\/ URL bookmark.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM)) {\n if (data->data && data->length > 0) {\n bookmark_drag_data_.ReadFromVector(\n bookmark_utils::GetNodesFromSelection(\n NULL, data,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n tab_contents_->profile(), NULL, NULL));\n bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());\n } else {\n bookmark_drag_data_.ReadFromTuple(drop_data_->url,\n drop_data_->url_title);\n }\n }\n\n if (data_requests_ == 0) {\n \/\/ Tell the renderer about the drag.\n \/\/ |x| and |y| are seemingly arbitrary at this point.\n tab_contents_->render_view_host()->\n DragTargetDragEnter(*drop_data_.get(),\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(\n bookmark_drag_data_);\n }\n\n drag_over_time_ = time;\n }\n}\n\n\/\/ The drag has left our widget; forward this information to the renderer.\nvoid WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,\n guint time) {\n \/\/ Set |context_| to NULL to make sure we will recognize the next DragMotion\n \/\/ as an enter.\n context_ = NULL;\n drop_data_.reset();\n \/\/ When GTK sends us a drag-drop signal, it is shortly (and synchronously)\n \/\/ preceded by a drag-leave. The renderer doesn't like getting the signals\n \/\/ in this order so delay telling it about the drag-leave till we are sure\n \/\/ we are not getting a drop as well.\n MessageLoop::current()->PostTask(FROM_HERE,\n method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));\n}\n\n\/\/ Called by GTK when the user releases the mouse, executing a drop.\ngboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,\n gint x, gint y, guint time) {\n \/\/ Cancel that drag leave!\n method_factory_.RevokeAll();\n\n tab_contents_->render_view_host()->\n DragTargetDrop(gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);\n\n \/\/ The second parameter is just an educated guess as to whether or not the\n \/\/ drag succeeded, but at least we will get the drag-end animation right\n \/\/ sometimes.\n gtk_drag_finish(context, is_drop_target_, FALSE, time);\n return TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_drag_dest_gtk.h\"\n\n#include <string>\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_drag_data.h\"\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/base\/net_util.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nnamespace {\n\n\/\/ Returns the bookmark target atom, based on the underlying toolkit.\n\/\/\n\/\/ For GTK, bookmark drag data is encoded as pickle and associated with\n\/\/ gtk_dnd_util::CHROME_BOOKMARK_ITEM. See\n\/\/ bookmark_utils::WriteBookmarksToSelection() for details.\n\/\/ For Views, bookmark drag data is encoded in the same format, and\n\/\/ associated with a custom format. See BookmarkDragData::Write() for\n\/\/ details.\nGdkAtom GetBookmarkTargetAtom() {\n#if defined(TOOLKIT_VIEWS)\n return BookmarkDragData::GetBookmarkCustomFormat();\n#else\n return gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM);\n#endif\n}\n\n} \/\/ namespace\n\nWebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)\n : tab_contents_(tab_contents),\n widget_(widget),\n context_(NULL),\n method_factory_(this) {\n gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),\n NULL, 0,\n static_cast<GdkDragAction>(GDK_ACTION_COPY |\n GDK_ACTION_LINK |\n GDK_ACTION_MOVE));\n g_signal_connect(widget, \"drag-motion\",\n G_CALLBACK(OnDragMotionThunk), this);\n g_signal_connect(widget, \"drag-leave\",\n G_CALLBACK(OnDragLeaveThunk), this);\n g_signal_connect(widget, \"drag-drop\",\n G_CALLBACK(OnDragDropThunk), this);\n g_signal_connect(widget, \"drag-data-received\",\n G_CALLBACK(OnDragDataReceivedThunk), this);\n \/\/ TODO(tony): Need a drag-data-delete handler for moving content out of\n \/\/ the tab contents. http:\/\/crbug.com\/38989\n\n destroy_handler_ = g_signal_connect(\n widget, \"destroy\", G_CALLBACK(gtk_widget_destroyed), &widget_);\n}\n\nWebDragDestGtk::~WebDragDestGtk() {\n if (widget_) {\n gtk_drag_dest_unset(widget_);\n g_signal_handler_disconnect(widget_, destroy_handler_);\n }\n}\n\nvoid WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {\n if (context_) {\n is_drop_target_ = operation != WebDragOperationNone;\n gdk_drag_status(context_, gtk_util::WebDragOpToGdkDragAction(operation),\n drag_over_time_);\n }\n}\n\nvoid WebDragDestGtk::DragLeave() {\n tab_contents_->render_view_host()->DragTargetDragLeave();\n\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);\n }\n}\n\ngboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,\n GdkDragContext* context,\n gint x, gint y,\n guint time) {\n if (context_ != context) {\n context_ = context;\n drop_data_.reset(new WebDropData);\n bookmark_drag_data_.Clear();\n is_drop_target_ = false;\n\n \/\/ text\/plain must come before text\/uri-list. This is a hack that works in\n \/\/ conjunction with OnDragDataReceived. Since some file managers populate\n \/\/ text\/plain with file URLs when dragging files, we want to handle\n \/\/ text\/uri-list after text\/plain so that the plain text can be cleared if\n \/\/ it's a file drag.\n static int supported_targets[] = {\n gtk_dnd_util::TEXT_PLAIN,\n gtk_dnd_util::TEXT_URI_LIST,\n gtk_dnd_util::TEXT_HTML,\n gtk_dnd_util::NETSCAPE_URL,\n gtk_dnd_util::CHROME_NAMED_URL,\n \/\/ TODO(estade): support image drags?\n };\n\n \/\/ Add the bookmark target as well.\n data_requests_ = arraysize(supported_targets) + 1;\n for (size_t i = 0; i < arraysize(supported_targets); ++i) {\n gtk_drag_get_data(widget_, context,\n gtk_dnd_util::GetAtomForTarget(supported_targets[i]),\n time);\n }\n\n gtk_drag_get_data(widget_, context, GetBookmarkTargetAtom(), time);\n } else if (data_requests_ == 0) {\n tab_contents_->render_view_host()->\n DragTargetDragOver(\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_util::GdkDragActionToWebDragOp(context->actions));\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);\n drag_over_time_ = time;\n }\n\n \/\/ Pretend we are a drag destination because we don't want to wait for\n \/\/ the renderer to tell us if we really are or not.\n return TRUE;\n}\n\nvoid WebDragDestGtk::OnDragDataReceived(\n GtkWidget* sender, GdkDragContext* context, gint x, gint y,\n GtkSelectionData* data, guint info, guint time) {\n \/\/ We might get the data from an old get_data() request that we no longer\n \/\/ care about.\n if (context != context_)\n return;\n\n data_requests_--;\n\n \/\/ Decode the data.\n if (data->data && data->length > 0) {\n \/\/ If the source can't provide us with valid data for a requested target,\n \/\/ data->data will be NULL.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {\n guchar* text = gtk_selection_data_get_text(data);\n if (text) {\n drop_data_->plain_text =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),\n data->length));\n g_free(text);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {\n gchar** uris = gtk_selection_data_get_uris(data);\n if (uris) {\n drop_data_->url = GURL();\n for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {\n \/\/ Most file managers populate text\/uri-list with file URLs when\n \/\/ dragging files. To avoid exposing file system paths to web content,\n \/\/ file URLs are never set as the URL content for the drop.\n \/\/ TODO(estade): Can the filenames have a non-UTF8 encoding?\n FilePath file_path;\n if (net::FileURLToFilePath(GURL(*uri_iter), &file_path)) {\n drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));\n \/\/ This is a hack. Some file managers also populate text\/plain with\n \/\/ a file URL when dragging files, so we clear it to avoid exposing\n \/\/ it to the web content.\n drop_data_->plain_text.clear();\n } else if (!drop_data_->url.is_valid()) {\n \/\/ Also set the first non-file URL as the URL content for the drop.\n drop_data_->url = GURL(*uri_iter);\n }\n }\n g_strfreev(uris);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {\n \/\/ TODO(estade): Can the html have a non-UTF8 encoding?\n drop_data_->text_html =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),\n data->length));\n \/\/ We leave the base URL empty.\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {\n std::string netscape_url(reinterpret_cast<char*>(data->data),\n data->length);\n size_t split = netscape_url.find_first_of('\\n');\n if (split != std::string::npos) {\n drop_data_->url = GURL(netscape_url.substr(0, split));\n if (split < netscape_url.size() - 1)\n drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {\n gtk_dnd_util::ExtractNamedURL(data,\n &drop_data_->url, &drop_data_->url_title);\n }\n }\n\n \/\/ For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source\n \/\/ doesn't have any data available for us. In this case we try to synthesize a\n \/\/ URL bookmark.\n \/\/ Note that bookmark drag data is encoded in the same format for both\n \/\/ GTK and Views, hence we can share the same logic here.\n if (data->target == GetBookmarkTargetAtom()) {\n if (data->data && data->length > 0) {\n bookmark_drag_data_.ReadFromVector(\n bookmark_utils::GetNodesFromSelection(\n NULL, data,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n tab_contents_->profile(), NULL, NULL));\n bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());\n } else {\n bookmark_drag_data_.ReadFromTuple(drop_data_->url,\n drop_data_->url_title);\n }\n }\n\n if (data_requests_ == 0) {\n \/\/ Tell the renderer about the drag.\n \/\/ |x| and |y| are seemingly arbitrary at this point.\n tab_contents_->render_view_host()->\n DragTargetDragEnter(*drop_data_.get(),\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_util::GdkDragActionToWebDragOp(context->actions));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(\n bookmark_drag_data_);\n }\n\n drag_over_time_ = time;\n }\n}\n\n\/\/ The drag has left our widget; forward this information to the renderer.\nvoid WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,\n guint time) {\n \/\/ Set |context_| to NULL to make sure we will recognize the next DragMotion\n \/\/ as an enter.\n context_ = NULL;\n drop_data_.reset();\n \/\/ When GTK sends us a drag-drop signal, it is shortly (and synchronously)\n \/\/ preceded by a drag-leave. The renderer doesn't like getting the signals\n \/\/ in this order so delay telling it about the drag-leave till we are sure\n \/\/ we are not getting a drop as well.\n MessageLoop::current()->PostTask(FROM_HERE,\n method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));\n}\n\n\/\/ Called by GTK when the user releases the mouse, executing a drop.\ngboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,\n gint x, gint y, guint time) {\n \/\/ Cancel that drag leave!\n method_factory_.RevokeAll();\n\n tab_contents_->render_view_host()->\n DragTargetDrop(gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);\n\n \/\/ The second parameter is just an educated guess as to whether or not the\n \/\/ drag succeeded, but at least we will get the drag-end animation right\n \/\/ sometimes.\n gtk_drag_finish(context, is_drop_target_, FALSE, time);\n return TRUE;\n}\n<commit_msg>Fix file URL detection in WebDragDestGtk.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_drag_dest_gtk.h\"\n\n#include <string>\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_drag_data.h\"\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"net\/base\/net_util.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nnamespace {\n\n\/\/ Returns the bookmark target atom, based on the underlying toolkit.\n\/\/\n\/\/ For GTK, bookmark drag data is encoded as pickle and associated with\n\/\/ gtk_dnd_util::CHROME_BOOKMARK_ITEM. See\n\/\/ bookmark_utils::WriteBookmarksToSelection() for details.\n\/\/ For Views, bookmark drag data is encoded in the same format, and\n\/\/ associated with a custom format. See BookmarkDragData::Write() for\n\/\/ details.\nGdkAtom GetBookmarkTargetAtom() {\n#if defined(TOOLKIT_VIEWS)\n return BookmarkDragData::GetBookmarkCustomFormat();\n#else\n return gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM);\n#endif\n}\n\n} \/\/ namespace\n\nWebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)\n : tab_contents_(tab_contents),\n widget_(widget),\n context_(NULL),\n method_factory_(this) {\n gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),\n NULL, 0,\n static_cast<GdkDragAction>(GDK_ACTION_COPY |\n GDK_ACTION_LINK |\n GDK_ACTION_MOVE));\n g_signal_connect(widget, \"drag-motion\",\n G_CALLBACK(OnDragMotionThunk), this);\n g_signal_connect(widget, \"drag-leave\",\n G_CALLBACK(OnDragLeaveThunk), this);\n g_signal_connect(widget, \"drag-drop\",\n G_CALLBACK(OnDragDropThunk), this);\n g_signal_connect(widget, \"drag-data-received\",\n G_CALLBACK(OnDragDataReceivedThunk), this);\n \/\/ TODO(tony): Need a drag-data-delete handler for moving content out of\n \/\/ the tab contents. http:\/\/crbug.com\/38989\n\n destroy_handler_ = g_signal_connect(\n widget, \"destroy\", G_CALLBACK(gtk_widget_destroyed), &widget_);\n}\n\nWebDragDestGtk::~WebDragDestGtk() {\n if (widget_) {\n gtk_drag_dest_unset(widget_);\n g_signal_handler_disconnect(widget_, destroy_handler_);\n }\n}\n\nvoid WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {\n if (context_) {\n is_drop_target_ = operation != WebDragOperationNone;\n gdk_drag_status(context_, gtk_util::WebDragOpToGdkDragAction(operation),\n drag_over_time_);\n }\n}\n\nvoid WebDragDestGtk::DragLeave() {\n tab_contents_->render_view_host()->DragTargetDragLeave();\n\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);\n }\n}\n\ngboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,\n GdkDragContext* context,\n gint x, gint y,\n guint time) {\n if (context_ != context) {\n context_ = context;\n drop_data_.reset(new WebDropData);\n bookmark_drag_data_.Clear();\n is_drop_target_ = false;\n\n \/\/ text\/plain must come before text\/uri-list. This is a hack that works in\n \/\/ conjunction with OnDragDataReceived. Since some file managers populate\n \/\/ text\/plain with file URLs when dragging files, we want to handle\n \/\/ text\/uri-list after text\/plain so that the plain text can be cleared if\n \/\/ it's a file drag.\n static int supported_targets[] = {\n gtk_dnd_util::TEXT_PLAIN,\n gtk_dnd_util::TEXT_URI_LIST,\n gtk_dnd_util::TEXT_HTML,\n gtk_dnd_util::NETSCAPE_URL,\n gtk_dnd_util::CHROME_NAMED_URL,\n \/\/ TODO(estade): support image drags?\n };\n\n \/\/ Add the bookmark target as well.\n data_requests_ = arraysize(supported_targets) + 1;\n for (size_t i = 0; i < arraysize(supported_targets); ++i) {\n gtk_drag_get_data(widget_, context,\n gtk_dnd_util::GetAtomForTarget(supported_targets[i]),\n time);\n }\n\n gtk_drag_get_data(widget_, context, GetBookmarkTargetAtom(), time);\n } else if (data_requests_ == 0) {\n tab_contents_->render_view_host()->\n DragTargetDragOver(\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_util::GdkDragActionToWebDragOp(context->actions));\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);\n drag_over_time_ = time;\n }\n\n \/\/ Pretend we are a drag destination because we don't want to wait for\n \/\/ the renderer to tell us if we really are or not.\n return TRUE;\n}\n\nvoid WebDragDestGtk::OnDragDataReceived(\n GtkWidget* sender, GdkDragContext* context, gint x, gint y,\n GtkSelectionData* data, guint info, guint time) {\n \/\/ We might get the data from an old get_data() request that we no longer\n \/\/ care about.\n if (context != context_)\n return;\n\n data_requests_--;\n\n \/\/ Decode the data.\n if (data->data && data->length > 0) {\n \/\/ If the source can't provide us with valid data for a requested target,\n \/\/ data->data will be NULL.\n if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {\n guchar* text = gtk_selection_data_get_text(data);\n if (text) {\n drop_data_->plain_text =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),\n data->length));\n g_free(text);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {\n gchar** uris = gtk_selection_data_get_uris(data);\n if (uris) {\n drop_data_->url = GURL();\n for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {\n \/\/ Most file managers populate text\/uri-list with file URLs when\n \/\/ dragging files. To avoid exposing file system paths to web content,\n \/\/ file URLs are never set as the URL content for the drop.\n \/\/ TODO(estade): Can the filenames have a non-UTF8 encoding?\n GURL url(*uri_iter);\n FilePath file_path;\n if (url.SchemeIs(chrome::kFileScheme) &&\n net::FileURLToFilePath(url, &file_path)) {\n drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));\n \/\/ This is a hack. Some file managers also populate text\/plain with\n \/\/ a file URL when dragging files, so we clear it to avoid exposing\n \/\/ it to the web content.\n drop_data_->plain_text.clear();\n } else if (!drop_data_->url.is_valid()) {\n \/\/ Also set the first non-file URL as the URL content for the drop.\n drop_data_->url = url;\n }\n }\n g_strfreev(uris);\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {\n \/\/ TODO(estade): Can the html have a non-UTF8 encoding?\n drop_data_->text_html =\n UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),\n data->length));\n \/\/ We leave the base URL empty.\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {\n std::string netscape_url(reinterpret_cast<char*>(data->data),\n data->length);\n size_t split = netscape_url.find_first_of('\\n');\n if (split != std::string::npos) {\n drop_data_->url = GURL(netscape_url.substr(0, split));\n if (split < netscape_url.size() - 1)\n drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));\n }\n } else if (data->target ==\n gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {\n gtk_dnd_util::ExtractNamedURL(data,\n &drop_data_->url, &drop_data_->url_title);\n }\n }\n\n \/\/ For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source\n \/\/ doesn't have any data available for us. In this case we try to synthesize a\n \/\/ URL bookmark.\n \/\/ Note that bookmark drag data is encoded in the same format for both\n \/\/ GTK and Views, hence we can share the same logic here.\n if (data->target == GetBookmarkTargetAtom()) {\n if (data->data && data->length > 0) {\n bookmark_drag_data_.ReadFromVector(\n bookmark_utils::GetNodesFromSelection(\n NULL, data,\n gtk_dnd_util::CHROME_BOOKMARK_ITEM,\n tab_contents_->profile(), NULL, NULL));\n bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());\n } else {\n bookmark_drag_data_.ReadFromTuple(drop_data_->url,\n drop_data_->url_title);\n }\n }\n\n if (data_requests_ == 0) {\n \/\/ Tell the renderer about the drag.\n \/\/ |x| and |y| are seemingly arbitrary at this point.\n tab_contents_->render_view_host()->\n DragTargetDragEnter(*drop_data_.get(),\n gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_),\n gtk_util::GdkDragActionToWebDragOp(context->actions));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate()) {\n tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(\n bookmark_drag_data_);\n }\n\n drag_over_time_ = time;\n }\n}\n\n\/\/ The drag has left our widget; forward this information to the renderer.\nvoid WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,\n guint time) {\n \/\/ Set |context_| to NULL to make sure we will recognize the next DragMotion\n \/\/ as an enter.\n context_ = NULL;\n drop_data_.reset();\n \/\/ When GTK sends us a drag-drop signal, it is shortly (and synchronously)\n \/\/ preceded by a drag-leave. The renderer doesn't like getting the signals\n \/\/ in this order so delay telling it about the drag-leave till we are sure\n \/\/ we are not getting a drop as well.\n MessageLoop::current()->PostTask(FROM_HERE,\n method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));\n}\n\n\/\/ Called by GTK when the user releases the mouse, executing a drop.\ngboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,\n gint x, gint y, guint time) {\n \/\/ Cancel that drag leave!\n method_factory_.RevokeAll();\n\n tab_contents_->render_view_host()->\n DragTargetDrop(gtk_util::ClientPoint(widget_),\n gtk_util::ScreenPoint(widget_));\n\n \/\/ This is non-null if tab_contents_ is showing an ExtensionDOMUI with\n \/\/ support for (at the moment experimental) drag and drop extensions.\n if (tab_contents_->GetBookmarkDragDelegate())\n tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);\n\n \/\/ The second parameter is just an educated guess as to whether or not the\n \/\/ drag succeeded, but at least we will get the drag-end animation right\n \/\/ sometimes.\n gtk_drag_finish(context, is_drop_target_, FALSE, time);\n return TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <highgui.h>\n#include <cxcore.h>\n#include <vector>\n#include \"utils.hpp\"\n\nstruct PointAngle{\n\tCvPoint p;\n\tfloat angle;\n};\n\nint comp_point_with_angle(const void * a, const void * b) {\n\tif ( ((PointAngle*)a)->angle < ((PointAngle*)b)->angle ) return -1;\n\telse if ( ((PointAngle*)a)->angle > ((PointAngle*)b)->angle ) return 1;\n\telse \/\/if ( ((PointAngle*)a)->angle == ((PointAngle*)b)->angle ) return 0;\n\t\treturn 0;\n}\n\nconst char * title = \"Convex Polygon Intersection\";\nclass UIPolyIntersection {\n\tfloat _resolution;\n\tint _nb_grid;\n\tint _width ;\n\tint _height;\n\tstd::vector<CvPoint> _poly[2];\n\tstd::vector<CvPoint> _inter;\n\tstd::vector<CvPoint *> _all;\n\tIplImage * curr_rgb;\n\tCvPoint pCurr;\n\tint key;\n\tint selected_point;\n\tint hover_point;\n\tstatic void mouseCallback(int event, int x, int y, int flags, void* param) {\n\t\tstatic_cast<UIPolyIntersection*>(param)->mouseEvent(event, x, y, flags,param); \n\t}\npublic:\n\n\tUIPolyIntersection(int width) { \n\t\t_width = width;\n\t\t_height = _width*9\/16;\n\t\thover_point = selected_point = -1;\n\t\tcurr_rgb = cvCreateImage(cvSize(_width,_height),8,3);\n\t\tpCurr = cvPoint(0,0);\n\t\t\n\t\tinitRandom();\n\t\tcvZero(curr_rgb);\n\t\tcvNamedWindow(title, CV_WINDOW_AUTOSIZE);\n\t\tcvSetMouseCallback(title, &UIPolyIntersection::mouseCallback , this );\n\t}\n\n\t~UIPolyIntersection() {\n\t\tcvReleaseImage(&curr_rgb);\n\t}\n\n\tvoid initRandom() {\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tint n = 5;\n\t\t\t_poly[j].reserve(n);\n\t\t\t_poly[j].clear();\n\t\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\t\tCvPoint p = cvPoint(rand()%_width,rand()%_height);\n\t\t\t\t_poly[j].push_back(p);\n\t\t\t\t_all.push_back(&_poly[j][i]);\n\t\t\t}\n\t\t}\n\t\t_nb_grid = 50;\n\t\t_resolution = _width \/(float)_nb_grid;\n\t\tupdateIntersection();\n\t}\n\n\tvoid mouseEvent( int event, int x, int y, int flags, void* ) {\n\t\tpCurr = cvPoint(x,y);\n\t\thover_point = -1;\n\t\tfor(size_t i = 0 ; i < _all.size() ; i++ ){\n\t\t\tif(distPoint(pCurr,*_all[i]) < 5) {\n\t\t\t\thover_point = i ;break;\n\t\t\t}\n\t\t}\n\t\tif( event == CV_EVENT_LBUTTONDOWN && hover_point != -1 ) {\n\t\t\tselected_point = hover_point;\n\t\t} else if(event == CV_EVENT_MOUSEMOVE && selected_point != -1 ) {\n\t\t\t_all[selected_point]->x = pCurr.x;\n\t\t\t_all[selected_point]->y = pCurr.y;\n\t\t} else if(event == CV_EVENT_LBUTTONUP ) {\n\t\t\tif(selected_point != -1) {\n\t\t\t\tupdateIntersection();\n\t\t\t\tselected_point = -1;\n\t\t\t} else {\n\n\t\t\t}\n\t\t} \n\t}\n\t\n\tvoid drawGrid() {\n\t\tfor (int r = 0 ; r < _nb_grid ; r++ ) {\n\t\t\tint var = (int)(_resolution * r);\n\t\t\tcvDrawLine(curr_rgb,cvPoint(0,var),cvPoint(_width,var),CV_RGB(50,50,50));\n\t\t\tcvDrawLine(curr_rgb,cvPoint(var,0),cvPoint(var,_width),CV_RGB(50,50,50));\n\t\t}\n\t}\n\n\tvoid drawPoints() {\n\t\tchar buff[128];\n\t\tCvFont font = cvFont(1,1);\n\t\tCvScalar c[3];\n\t\tc[0] = CV_RGB(255,0,0);\n\t\tc[1] = CV_RGB(84,255,0);\n\t\tc[2] = CV_RGB(0,169,255);\n\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tfor (size_t i = 0 ; i < _poly[j].size() ; i++ ) {\n\t\t\t\tcvDrawLine(curr_rgb,_poly[j][i],_poly[j][(i+1)%_poly[j].size()],c[j],1,CV_AA);\n\t\t\t\tsprintf(buff,\"%d\",i); cvPutText(curr_rgb,buff,_poly[j][i],&font,c[j]);\n\t\t\t}\n\t\t\tfloat area = computeArea(&_poly[j][0],(int)_poly[j].size());\n\t\t\tCvPoint center = getCenter(&_poly[j][0],(int)_poly[j].size());\n\t\t\tsprintf(buff,\"Area = %0.1f\",area\/(_resolution*_resolution)); cvPutText(curr_rgb,buff,center,&font,c[j]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _all.size() ; i++ ) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[i],5,CV_RGB(0,255,255),1,CV_AA);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _inter.size() ; i++ ) {\n\t\t\tcvDrawLine(curr_rgb,_inter[i],_inter[(i+1)%_inter.size()],c[2],2,CV_AA);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _inter.size() ; i++ ) {\n\t\t\tcvDrawCircle(curr_rgb,_inter[i],1,CV_RGB(250,250,250),2,CV_AA);\n\t\t}\n\t\tif( _inter.size() ) {\n\t\t\tfloat area = computeArea(&_inter[0],(int)_inter.size());\n\t\t\tCvPoint center = getCenter(&_inter[0],(int)_inter.size());\n\t\t\tsprintf(buff,\"Area intersected = %0.1f\",area\/(_resolution*_resolution)); cvPutText(curr_rgb,buff,center,&font,c[2]);\n\t\t}\n\t}\n\n\tvoid paintImage() {\n\t\tcvZero(curr_rgb);\n\t\tdrawGrid();\n\t\tcvDrawLine(curr_rgb,cvPoint(pCurr.x,0),cvPoint(pCurr.x,curr_rgb->height),CV_RGB(255,0,255));\n\t\tcvDrawLine(curr_rgb,cvPoint(0,pCurr.y),cvPoint(curr_rgb->width,pCurr.y),CV_RGB(255,0,255));\n\t\tdrawPoints();\n\n\t\tif( hover_point != -1) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[hover_point],10,CV_RGB(255,255,0),1,CV_AA,0);\n\t\t}\n\n\t\tif( selected_point != -1) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[selected_point],10,CV_RGB(255,255,0),1,CV_AA,0);\n\t\t}\n\t}\n\n\tCvPoint getCenter(CvPoint * points,int n) {\n\t\tCvPoint center;\n\t\tcenter.x = 0;\n\t\tcenter.y = 0;\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tcenter.x += points[i].x;\n\t\t\tcenter.y += points[i].y;\n\t\t}\n\t\tcenter.x \/= n;\n\t\tcenter.y \/= n;\n\t\treturn center;\n\t}\n\n\tfloat computeArea(const CvPoint * points,int n) {\n\t\tfloat area0 = 0.;\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tint j = (i+1)%n;\n\t\t\tarea0 += points[i].x * points[j].y;\n\t\t\tarea0 -= points[i].y * points[j].x;\n\t\t}\n\t\treturn 0.5f * abs(area0);\n\t}\n\n\tvoid pointsOrdered(CvPoint * points,int n) {\n\t\tCvPoint center = getCenter(points,n);\n\t\tPointAngle pc[400];\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tpc[i].p.x = points[i].x;\n\t\t\tpc[i].p.y = points[i].y;\n\t\t\tpc[i].angle = atan2f((float)(points[i].y - center.y),(float)(points[i].x - center.x));\n\t\t}\n\t\tqsort(pc,n,sizeof(PointAngle),comp_point_with_angle);\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tpoints[i].x = pc[i].p.x;\n\t\t\tpoints[i].y = pc[i].p.y;\n\t\t}\n\t}\n\n\tvoid updateIntersection() {\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tpointsOrdered(&_poly[j][0],(int)_poly[j].size());\n\t\t}\n\n\t\t_inter.clear();\n\t\tfor (size_t i = 0 ; i < _poly[0].size() ;i++) {\n\t\t\tif( pointInPolygon(_poly[0][i],&_poly[1][0],(int)_poly[1].size()) ) \n\t\t\t\t_inter.push_back(_poly[0][i]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _poly[1].size() ;i++) { \n\t\t\tif( pointInPolygon(_poly[1][i],&_poly[0][0],(int)_poly[0].size()) ) \n\t\t\t\t_inter.push_back(_poly[1][i]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _poly[0].size() ;i++) {\n\t\t\tCvPoint p0,p1,p2,p3;\n\t\t\tp0 = _poly[0][i];\n\t\t\tp1 = _poly[0][(i+1)%_poly[0].size()];\n\t\t\tfor (size_t j = 0 ; j < _poly[1].size() ;j++) {\n\t\t\t\tp2 = _poly[1][j];\n\t\t\t\tp3 = _poly[1][(j+1)%_poly[1].size()];\n\t\t\t\tCvPoint inter;\n\t\t\t\tif(segementIntersection(p0,p1,p2,p3,&inter)) {\n\t\t\t\t\t_inter.push_back(inter);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(_inter.size())pointsOrdered(&_inter[0],(int)_inter.size());\n\t}\n\n\tvoid run() {\n\t\twhile(true) {\n\t\t\ttry {\n\t\t\t\tpaintImage();\n\t\t\t} catch (std::exception &e) {\n\t\t\t\tprintf(\"Err : %s\\n\",e.what());\n\t\t\t}\n\t\t\tcvShowImage(title,curr_rgb);\n\t\t\tswitch( key = cvWaitKey(30)) {\n\t\t\tcase 'r' : initRandom();break;\n\t\t\tcase 27 : return ;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(int argc,char **argv) {\n\ttry {\n\t\tUIPolyIntersection ui(1280);\n\t\tui.run();\n\t} catch (std::exception &e) {\n\t\tprintf(\"Err : %s\\n\",e.what());\n\t}\n\treturn 1;\n}<commit_msg>move correctly init data in constructor.<commit_after>#include <highgui.h>\n#include <cxcore.h>\n#include <vector>\n#include \"utils.hpp\"\n\nstruct PointAngle{\n\tCvPoint p;\n\tfloat angle;\n};\n\nint comp_point_with_angle(const void * a, const void * b) {\n\tif ( ((PointAngle*)a)->angle < ((PointAngle*)b)->angle ) return -1;\n\telse if ( ((PointAngle*)a)->angle > ((PointAngle*)b)->angle ) return 1;\n\telse \/\/if ( ((PointAngle*)a)->angle == ((PointAngle*)b)->angle ) return 0;\n\t\treturn 0;\n}\n\nconst char * title = \"Convex Polygon Intersection\";\nclass UIPolyIntersection {\n\tfloat _resolution;\n\tint _nb_grid;\n\tint _width ;\n\tint _height;\n\tstd::vector<CvPoint> _poly[2];\n\tstd::vector<CvPoint> _inter;\n\tstd::vector<CvPoint *> _all;\n\tIplImage * curr_rgb;\n\tCvPoint pCurr;\n\tint key;\n\tint selected_point;\n\tint hover_point;\n\tstatic void mouseCallback(int event, int x, int y, int flags, void* param) {\n\t\tstatic_cast<UIPolyIntersection*>(param)->mouseEvent(event, x, y, flags,param); \n\t}\npublic:\n\n\tUIPolyIntersection(int width) { \n\t\t_nb_grid = 50;\n\t\t_width = width;\n\t\t_height = _width*9\/16;\n\t\thover_point = selected_point = -1;\n\t\tcurr_rgb = cvCreateImage(cvSize(_width,_height),8,3);\n\t\tpCurr = cvPoint(0,0);\n\t\t_resolution = _width \/(float)_nb_grid;\n\t\tinitRandom();\n\t\tcvZero(curr_rgb);\n\t\tcvNamedWindow(title, CV_WINDOW_AUTOSIZE);\n\t\tcvSetMouseCallback(title, &UIPolyIntersection::mouseCallback , this );\n\t}\n\n\t~UIPolyIntersection() {\n\t\tcvReleaseImage(&curr_rgb);\n\t}\n\n\tvoid initRandom() {\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tint n = 5;\n\t\t\t_poly[j].reserve(n);\n\t\t\t_poly[j].clear();\n\t\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\t\tCvPoint p = cvPoint(rand()%_width,rand()%_height);\n\t\t\t\t_poly[j].push_back(p);\n\t\t\t\t_all.push_back(&_poly[j][i]);\n\t\t\t}\n\t\t}\n\t\tupdateIntersection();\n\t}\n\n\tvoid mouseEvent( int event, int x, int y, int flags, void* ) {\n\t\tpCurr = cvPoint(x,y);\n\t\thover_point = -1;\n\t\tfor(size_t i = 0 ; i < _all.size() ; i++ ){\n\t\t\tif(distPoint(pCurr,*_all[i]) < 5) {\n\t\t\t\thover_point = i ;break;\n\t\t\t}\n\t\t}\n\t\tif( event == CV_EVENT_LBUTTONDOWN && hover_point != -1 ) {\n\t\t\tselected_point = hover_point;\n\t\t} else if(event == CV_EVENT_MOUSEMOVE && selected_point != -1 ) {\n\t\t\t_all[selected_point]->x = pCurr.x;\n\t\t\t_all[selected_point]->y = pCurr.y;\n\t\t} else if(event == CV_EVENT_LBUTTONUP ) {\n\t\t\tif(selected_point != -1) {\n\t\t\t\tupdateIntersection();\n\t\t\t\tselected_point = -1;\n\t\t\t} else {\n\n\t\t\t}\n\t\t} \n\t}\n\t\n\tvoid drawGrid() {\n\t\tfor (int r = 0 ; r < _nb_grid ; r++ ) {\n\t\t\tint var = (int)(_resolution * r);\n\t\t\tcvDrawLine(curr_rgb,cvPoint(0,var),cvPoint(_width,var),CV_RGB(50,50,50));\n\t\t\tcvDrawLine(curr_rgb,cvPoint(var,0),cvPoint(var,_width),CV_RGB(50,50,50));\n\t\t}\n\t}\n\n\tvoid drawPoints() {\n\t\tchar buff[128];\n\t\tCvFont font = cvFont(1,1);\n\t\tCvScalar c[3];\n\t\tc[0] = CV_RGB(255,0,0);\n\t\tc[1] = CV_RGB(84,255,0);\n\t\tc[2] = CV_RGB(0,169,255);\n\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tfor (size_t i = 0 ; i < _poly[j].size() ; i++ ) {\n\t\t\t\tcvDrawLine(curr_rgb,_poly[j][i],_poly[j][(i+1)%_poly[j].size()],c[j],1,CV_AA);\n\t\t\t\tsprintf(buff,\"%d\",i); cvPutText(curr_rgb,buff,_poly[j][i],&font,c[j]);\n\t\t\t}\n\t\t\tfloat area = computeArea(&_poly[j][0],(int)_poly[j].size());\n\t\t\tCvPoint center = getCenter(&_poly[j][0],(int)_poly[j].size());\n\t\t\tsprintf(buff,\"Area = %0.1f\",area\/(_resolution*_resolution)); cvPutText(curr_rgb,buff,center,&font,c[j]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _all.size() ; i++ ) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[i],5,CV_RGB(0,255,255),1,CV_AA);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _inter.size() ; i++ ) {\n\t\t\tcvDrawLine(curr_rgb,_inter[i],_inter[(i+1)%_inter.size()],c[2],2,CV_AA);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _inter.size() ; i++ ) {\n\t\t\tcvDrawCircle(curr_rgb,_inter[i],1,CV_RGB(250,250,250),2,CV_AA);\n\t\t}\n\t\tif( _inter.size() ) {\n\t\t\tfloat area = computeArea(&_inter[0],(int)_inter.size());\n\t\t\tCvPoint center = getCenter(&_inter[0],(int)_inter.size());\n\t\t\tsprintf(buff,\"Area intersected = %0.1f\",area\/(_resolution*_resolution)); cvPutText(curr_rgb,buff,center,&font,c[2]);\n\t\t}\n\t}\n\n\tvoid paintImage() {\n\t\tcvZero(curr_rgb);\n\t\tdrawGrid();\n\t\tcvDrawLine(curr_rgb,cvPoint(pCurr.x,0),cvPoint(pCurr.x,curr_rgb->height),CV_RGB(255,0,255));\n\t\tcvDrawLine(curr_rgb,cvPoint(0,pCurr.y),cvPoint(curr_rgb->width,pCurr.y),CV_RGB(255,0,255));\n\t\tdrawPoints();\n\n\t\tif( hover_point != -1) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[hover_point],10,CV_RGB(255,255,0),1,CV_AA,0);\n\t\t}\n\n\t\tif( selected_point != -1) {\n\t\t\tcvDrawCircle(curr_rgb,*_all[selected_point],10,CV_RGB(255,255,0),1,CV_AA,0);\n\t\t}\n\t}\n\n\tCvPoint getCenter(CvPoint * points,int n) {\n\t\tCvPoint center;\n\t\tcenter.x = 0;\n\t\tcenter.y = 0;\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tcenter.x += points[i].x;\n\t\t\tcenter.y += points[i].y;\n\t\t}\n\t\tcenter.x \/= n;\n\t\tcenter.y \/= n;\n\t\treturn center;\n\t}\n\n\tfloat computeArea(const CvPoint * points,int n) {\n\t\tfloat area0 = 0.;\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tint j = (i+1)%n;\n\t\t\tarea0 += points[i].x * points[j].y;\n\t\t\tarea0 -= points[i].y * points[j].x;\n\t\t}\n\t\treturn 0.5f * abs(area0);\n\t}\n\n\tvoid pointsOrdered(CvPoint * points,int n) {\n\t\tCvPoint center = getCenter(points,n);\n\t\tPointAngle pc[400];\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tpc[i].p.x = points[i].x;\n\t\t\tpc[i].p.y = points[i].y;\n\t\t\tpc[i].angle = atan2f((float)(points[i].y - center.y),(float)(points[i].x - center.x));\n\t\t}\n\t\tqsort(pc,n,sizeof(PointAngle),comp_point_with_angle);\n\t\tfor (int i = 0 ; i < n ; i++ ) {\n\t\t\tpoints[i].x = pc[i].p.x;\n\t\t\tpoints[i].y = pc[i].p.y;\n\t\t}\n\t}\n\n\tvoid updateIntersection() {\n\t\tfor (int j = 0 ; j < 2 ; j++ ) {\n\t\t\tpointsOrdered(&_poly[j][0],(int)_poly[j].size());\n\t\t}\n\n\t\t_inter.clear();\n\t\tfor (size_t i = 0 ; i < _poly[0].size() ;i++) {\n\t\t\tif( pointInPolygon(_poly[0][i],&_poly[1][0],(int)_poly[1].size()) ) \n\t\t\t\t_inter.push_back(_poly[0][i]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _poly[1].size() ;i++) { \n\t\t\tif( pointInPolygon(_poly[1][i],&_poly[0][0],(int)_poly[0].size()) ) \n\t\t\t\t_inter.push_back(_poly[1][i]);\n\t\t}\n\n\t\tfor (size_t i = 0 ; i < _poly[0].size() ;i++) {\n\t\t\tCvPoint p0,p1,p2,p3;\n\t\t\tp0 = _poly[0][i];\n\t\t\tp1 = _poly[0][(i+1)%_poly[0].size()];\n\t\t\tfor (size_t j = 0 ; j < _poly[1].size() ;j++) {\n\t\t\t\tp2 = _poly[1][j];\n\t\t\t\tp3 = _poly[1][(j+1)%_poly[1].size()];\n\t\t\t\tCvPoint inter;\n\t\t\t\tif(segementIntersection(p0,p1,p2,p3,&inter)) {\n\t\t\t\t\t_inter.push_back(inter);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(_inter.size())pointsOrdered(&_inter[0],(int)_inter.size());\n\t}\n\n\tvoid run() {\n\t\twhile(true) {\n\t\t\ttry {\n\t\t\t\tpaintImage();\n\t\t\t} catch (std::exception &e) {\n\t\t\t\tprintf(\"Err : %s\\n\",e.what());\n\t\t\t}\n\t\t\tcvShowImage(title,curr_rgb);\n\t\t\tswitch( key = cvWaitKey(30)) {\n\t\t\tcase 'r' : initRandom();break;\n\t\t\tcase 27 : return ;\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main(int argc,char **argv) {\n\ttry {\n\t\tUIPolyIntersection ui(1280);\n\t\tui.run();\n\t} catch (std::exception &e) {\n\t\tprintf(\"Err : %s\\n\",e.what());\n\t}\n\treturn 1;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/downloads_dom_handler.h\"\n\n#include <algorithm>\n#include <functional>\n\n#include \"base\/basictypes.h\"\n#include \"base\/callback.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/download\/chrome_download_manager_delegate.h\"\n#include \"chrome\/browser\/download\/download_history.h\"\n#include \"chrome\/browser\/download\/download_prefs.h\"\n#include \"chrome\/browser\/download\/download_util.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/fileicon_source.h\"\n#include \"chrome\/browser\/ui\/webui\/fileicon_source_cros.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/download\/download_item.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/user_metrics.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/gfx\/image\/image.h\"\n\nnamespace {\n\n\/\/ Maximum number of downloads to show. TODO(glen): Remove this and instead\n\/\/ stuff the downloads down the pipe slowly.\nstatic const int kMaxDownloads = 150;\n\n\/\/ Sort DownloadItems into descending order by their start time.\nclass DownloadItemSorter : public std::binary_function<DownloadItem*,\n DownloadItem*,\n bool> {\n public:\n bool operator()(const DownloadItem* lhs, const DownloadItem* rhs) {\n return lhs->start_time() > rhs->start_time();\n }\n};\n\n} \/\/ namespace\n\nclass DownloadsDOMHandler::OriginalDownloadManagerObserver\n : public DownloadManager::Observer {\n public:\n explicit OriginalDownloadManagerObserver(\n DownloadManager::Observer* observer,\n Profile* original_profile)\n : observer_(observer) {\n original_profile_download_manager_ = original_profile->GetDownloadManager();\n original_profile_download_manager_->AddObserver(this);\n }\n\n virtual ~OriginalDownloadManagerObserver() {\n if (original_profile_download_manager_)\n original_profile_download_manager_->RemoveObserver(this);\n }\n\n \/\/ Observer interface.\n virtual void ModelChanged() {\n observer_->ModelChanged();\n }\n\n virtual void ManagerGoingDown() {\n original_profile_download_manager_ = NULL;\n }\n\n private:\n \/\/ The DownloadsDOMHandler for the off-the-record profile.\n DownloadManager::Observer* observer_;\n\n \/\/ The original profile's download manager.\n DownloadManager* original_profile_download_manager_;\n};\n\nDownloadsDOMHandler::DownloadsDOMHandler(DownloadManager* dlm)\n : search_text_(),\n download_manager_(dlm),\n callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n \/\/ Create our fileicon data source.\n Profile::FromBrowserContext(dlm->browser_context())->\n GetChromeURLDataManager()->AddDataSource(\n#if defined(OS_CHROMEOS)\n new FileIconSourceCros());\n#else\n new FileIconSource());\n#endif \/\/ OS_CHROMEOS\n}\n\nDownloadsDOMHandler::~DownloadsDOMHandler() {\n ClearDownloadItems();\n download_manager_->RemoveObserver(this);\n}\n\n\/\/ DownloadsDOMHandler, public: -----------------------------------------------\n\nvoid DownloadsDOMHandler::Init() {\n download_manager_->AddObserver(this);\n\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n Profile* original_profile = profile->GetOriginalProfile();\n if (original_profile != profile) {\n original_download_manager_observer_.reset(\n new OriginalDownloadManagerObserver(this, original_profile));\n }\n}\n\nvoid DownloadsDOMHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(\"getDownloads\",\n NewCallback(this, &DownloadsDOMHandler::HandleGetDownloads));\n web_ui_->RegisterMessageCallback(\"openFile\",\n NewCallback(this, &DownloadsDOMHandler::HandleOpenFile));\n\n web_ui_->RegisterMessageCallback(\"drag\",\n NewCallback(this, &DownloadsDOMHandler::HandleDrag));\n\n web_ui_->RegisterMessageCallback(\"saveDangerous\",\n NewCallback(this, &DownloadsDOMHandler::HandleSaveDangerous));\n web_ui_->RegisterMessageCallback(\"discardDangerous\",\n NewCallback(this, &DownloadsDOMHandler::HandleDiscardDangerous));\n web_ui_->RegisterMessageCallback(\"show\",\n NewCallback(this, &DownloadsDOMHandler::HandleShow));\n web_ui_->RegisterMessageCallback(\"togglepause\",\n NewCallback(this, &DownloadsDOMHandler::HandlePause));\n web_ui_->RegisterMessageCallback(\"resume\",\n NewCallback(this, &DownloadsDOMHandler::HandlePause));\n web_ui_->RegisterMessageCallback(\"remove\",\n NewCallback(this, &DownloadsDOMHandler::HandleRemove));\n web_ui_->RegisterMessageCallback(\"cancel\",\n NewCallback(this, &DownloadsDOMHandler::HandleCancel));\n web_ui_->RegisterMessageCallback(\"clearAll\",\n NewCallback(this, &DownloadsDOMHandler::HandleClearAll));\n web_ui_->RegisterMessageCallback(\"openDownloadsFolder\",\n NewCallback(this, &DownloadsDOMHandler::HandleOpenDownloadsFolder));\n}\n\nvoid DownloadsDOMHandler::OnDownloadUpdated(DownloadItem* download) {\n \/\/ Get the id for the download. Our downloads are sorted latest to first,\n \/\/ and the id is the index into that list. We should be careful of sync\n \/\/ errors between the UI and the download_items_ list (we may wish to use\n \/\/ something other than 'id').\n OrderedDownloads::iterator it = find(download_items_.begin(),\n download_items_.end(),\n download);\n if (it == download_items_.end())\n return;\n\n if (download->state() == DownloadItem::REMOVING) {\n (*it)->RemoveObserver(this);\n *it = NULL;\n \/\/ A later ModelChanged() notification will change the WebUI's\n \/\/ view of the downloads list.\n return;\n }\n\n const int id = static_cast<int>(it - download_items_.begin());\n\n ListValue results_value;\n results_value.Append(download_util::CreateDownloadItemValue(download, id));\n web_ui_->CallJavascriptFunction(\"downloadUpdated\", results_value);\n}\n\n\/\/ A download has started or been deleted. Query our DownloadManager for the\n\/\/ current set of downloads.\nvoid DownloadsDOMHandler::ModelChanged() {\n ClearDownloadItems();\n download_manager_->SearchDownloads(WideToUTF16(search_text_),\n &download_items_);\n \/\/ If we have a parent profile, let it add its downloads to the results.\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n if (profile->GetOriginalProfile() != profile) {\n profile->GetOriginalProfile()->GetDownloadManager()->SearchDownloads(\n WideToUTF16(search_text_), &download_items_);\n }\n\n sort(download_items_.begin(), download_items_.end(), DownloadItemSorter());\n\n \/\/ Remove any extension downloads.\n for (size_t i = 0; i < download_items_.size();) {\n if (ChromeDownloadManagerDelegate::IsExtensionDownload(download_items_[i]))\n download_items_.erase(download_items_.begin() + i);\n else\n i++;\n }\n\n \/\/ Add ourself to all download items as an observer.\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (static_cast<int>(it - download_items_.begin()) > kMaxDownloads)\n break;\n\n \/\/ TODO(rdsmith): Convert to DCHECK()s when http:\/\/crbug.com\/84508 is\n \/\/ fixed.\n \/\/ We should never see anything that isn't already in the history.\n CHECK(*it);\n CHECK_NE(DownloadItem::kUninitializedHandle, (*it)->db_handle());\n\n (*it)->AddObserver(this);\n }\n\n SendCurrentDownloads();\n}\n\nvoid DownloadsDOMHandler::HandleGetDownloads(const ListValue* args) {\n std::wstring new_search = UTF16ToWideHack(ExtractStringValue(args));\n if (search_text_.compare(new_search) != 0) {\n search_text_ = new_search;\n ModelChanged();\n } else {\n SendCurrentDownloads();\n }\n\n download_manager_->CheckForHistoryFilesRemoval();\n}\n\nvoid DownloadsDOMHandler::HandleOpenFile(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->OpenDownload();\n}\n\nvoid DownloadsDOMHandler::HandleDrag(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file) {\n IconManager* im = g_browser_process->icon_manager();\n gfx::Image* icon = im->LookupIcon(file->GetUserVerifiedFilePath(),\n IconLoader::NORMAL);\n gfx::NativeView view = web_ui_->tab_contents()->GetNativeView();\n {\n \/\/ Enable nested tasks during DnD, while |DragDownload()| blocks.\n MessageLoop::ScopedNestableTaskAllower allower(MessageLoop::current());\n download_util::DragDownload(file, icon, view);\n }\n }\n}\n\nvoid DownloadsDOMHandler::HandleSaveDangerous(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->DangerousDownloadValidated();\n}\n\nvoid DownloadsDOMHandler::HandleDiscardDangerous(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);\n}\n\nvoid DownloadsDOMHandler::HandleShow(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->ShowDownloadInShell();\n}\n\nvoid DownloadsDOMHandler::HandlePause(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->TogglePause();\n}\n\nvoid DownloadsDOMHandler::HandleRemove(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file) {\n \/\/ TODO(rdsmith): Change to DCHECK when http:\/\/crbug.com\/84508 is fixed.\n CHECK_NE(DownloadItem::kUninitializedHandle, file->db_handle());\n file->Remove();\n }\n}\n\nvoid DownloadsDOMHandler::HandleCancel(const ListValue* args) {\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->Cancel(true);\n}\n\nvoid DownloadsDOMHandler::HandleClearAll(const ListValue* args) {\n download_manager_->RemoveAllDownloads();\n\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n \/\/ If this is an incognito downloader, clear All should clear main download\n \/\/ manager as well.\n if (profile->GetOriginalProfile() != profile)\n profile->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();\n}\n\nvoid DownloadsDOMHandler::HandleOpenDownloadsFolder(const ListValue* args) {\n FilePath path = DownloadPrefs::FromDownloadManager(download_manager_)->\n download_path();\n\n#if defined(OS_MACOSX)\n \/\/ Must be called from the UI thread on Mac.\n platform_util::OpenItem(path);\n#else\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableFunction(&platform_util::OpenItem, path));\n#endif\n}\n\n\/\/ DownloadsDOMHandler, private: ----------------------------------------------\n\nvoid DownloadsDOMHandler::SendCurrentDownloads() {\n ListValue results_value;\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n int index = static_cast<int>(it - download_items_.begin());\n if (index > kMaxDownloads)\n break;\n if (!*it)\n continue;\n results_value.Append(download_util::CreateDownloadItemValue(*it, index));\n }\n\n web_ui_->CallJavascriptFunction(\"downloadsList\", results_value);\n}\n\nvoid DownloadsDOMHandler::ClearDownloadItems() {\n \/\/ Clear out old state and remove self as observer for each download.\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (!*it)\n continue;\n (*it)->RemoveObserver(this);\n }\n download_items_.clear();\n}\n\nDownloadItem* DownloadsDOMHandler::GetDownloadById(int id) {\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (static_cast<int>(it - download_items_.begin() == id)) {\n return (*it);\n }\n }\n\n return NULL;\n}\n\nDownloadItem* DownloadsDOMHandler::GetDownloadByValue(const ListValue* args) {\n int id;\n if (ExtractIntegerValue(args, &id)) {\n return GetDownloadById(id);\n }\n return NULL;\n}\n<commit_msg>UMA in DownloadsDOMHandler<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/downloads_dom_handler.h\"\n\n#include <algorithm>\n#include <functional>\n\n#include \"base\/basictypes.h\"\n#include \"base\/callback.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/download\/chrome_download_manager_delegate.h\"\n#include \"chrome\/browser\/download\/download_history.h\"\n#include \"chrome\/browser\/download\/download_prefs.h\"\n#include \"chrome\/browser\/download\/download_util.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_url_data_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/fileicon_source.h\"\n#include \"chrome\/browser\/ui\/webui\/fileicon_source_cros.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/download\/download_item.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/user_metrics.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/gfx\/image\/image.h\"\n\nnamespace {\n\n\/\/ Maximum number of downloads to show. TODO(glen): Remove this and instead\n\/\/ stuff the downloads down the pipe slowly.\nstatic const int kMaxDownloads = 150;\n\n\/\/ Sort DownloadItems into descending order by their start time.\nclass DownloadItemSorter : public std::binary_function<DownloadItem*,\n DownloadItem*,\n bool> {\n public:\n bool operator()(const DownloadItem* lhs, const DownloadItem* rhs) {\n return lhs->start_time() > rhs->start_time();\n }\n};\n\nenum DownloadsDOMEvent {\n DOWNLOADS_DOM_EVENT_GET_DOWNLOADS = 0,\n DOWNLOADS_DOM_EVENT_OPEN_FILE = 1,\n DOWNLOADS_DOM_EVENT_DRAG = 2,\n DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS = 3,\n DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS = 4,\n DOWNLOADS_DOM_EVENT_SHOW = 5,\n DOWNLOADS_DOM_EVENT_PAUSE = 6,\n DOWNLOADS_DOM_EVENT_REMOVE = 7,\n DOWNLOADS_DOM_EVENT_CANCEL = 8,\n DOWNLOADS_DOM_EVENT_CLEAR_ALL = 9,\n DOWNLOADS_DOM_EVENT_OPEN_FOLDER = 10,\n DOWNLOADS_DOM_EVENT_MAX\n};\n\nvoid CountDownloadsDOMEvents(DownloadsDOMEvent event) {\n UMA_HISTOGRAM_ENUMERATION(\"Download.DOMEvent\",\n event,\n DOWNLOADS_DOM_EVENT_MAX);\n}\n\n} \/\/ namespace\n\nclass DownloadsDOMHandler::OriginalDownloadManagerObserver\n : public DownloadManager::Observer {\n public:\n explicit OriginalDownloadManagerObserver(\n DownloadManager::Observer* observer,\n Profile* original_profile)\n : observer_(observer) {\n original_profile_download_manager_ = original_profile->GetDownloadManager();\n original_profile_download_manager_->AddObserver(this);\n }\n\n virtual ~OriginalDownloadManagerObserver() {\n if (original_profile_download_manager_)\n original_profile_download_manager_->RemoveObserver(this);\n }\n\n \/\/ Observer interface.\n virtual void ModelChanged() {\n observer_->ModelChanged();\n }\n\n virtual void ManagerGoingDown() {\n original_profile_download_manager_ = NULL;\n }\n\n private:\n \/\/ The DownloadsDOMHandler for the off-the-record profile.\n DownloadManager::Observer* observer_;\n\n \/\/ The original profile's download manager.\n DownloadManager* original_profile_download_manager_;\n};\n\nDownloadsDOMHandler::DownloadsDOMHandler(DownloadManager* dlm)\n : search_text_(),\n download_manager_(dlm),\n callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n \/\/ Create our fileicon data source.\n Profile::FromBrowserContext(dlm->browser_context())->\n GetChromeURLDataManager()->AddDataSource(\n#if defined(OS_CHROMEOS)\n new FileIconSourceCros());\n#else\n new FileIconSource());\n#endif \/\/ OS_CHROMEOS\n}\n\nDownloadsDOMHandler::~DownloadsDOMHandler() {\n ClearDownloadItems();\n download_manager_->RemoveObserver(this);\n}\n\n\/\/ DownloadsDOMHandler, public: -----------------------------------------------\n\nvoid DownloadsDOMHandler::Init() {\n download_manager_->AddObserver(this);\n\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n Profile* original_profile = profile->GetOriginalProfile();\n if (original_profile != profile) {\n original_download_manager_observer_.reset(\n new OriginalDownloadManagerObserver(this, original_profile));\n }\n}\n\nvoid DownloadsDOMHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(\"getDownloads\",\n NewCallback(this, &DownloadsDOMHandler::HandleGetDownloads));\n web_ui_->RegisterMessageCallback(\"openFile\",\n NewCallback(this, &DownloadsDOMHandler::HandleOpenFile));\n\n web_ui_->RegisterMessageCallback(\"drag\",\n NewCallback(this, &DownloadsDOMHandler::HandleDrag));\n\n web_ui_->RegisterMessageCallback(\"saveDangerous\",\n NewCallback(this, &DownloadsDOMHandler::HandleSaveDangerous));\n web_ui_->RegisterMessageCallback(\"discardDangerous\",\n NewCallback(this, &DownloadsDOMHandler::HandleDiscardDangerous));\n web_ui_->RegisterMessageCallback(\"show\",\n NewCallback(this, &DownloadsDOMHandler::HandleShow));\n web_ui_->RegisterMessageCallback(\"togglepause\",\n NewCallback(this, &DownloadsDOMHandler::HandlePause));\n web_ui_->RegisterMessageCallback(\"resume\",\n NewCallback(this, &DownloadsDOMHandler::HandlePause));\n web_ui_->RegisterMessageCallback(\"remove\",\n NewCallback(this, &DownloadsDOMHandler::HandleRemove));\n web_ui_->RegisterMessageCallback(\"cancel\",\n NewCallback(this, &DownloadsDOMHandler::HandleCancel));\n web_ui_->RegisterMessageCallback(\"clearAll\",\n NewCallback(this, &DownloadsDOMHandler::HandleClearAll));\n web_ui_->RegisterMessageCallback(\"openDownloadsFolder\",\n NewCallback(this, &DownloadsDOMHandler::HandleOpenDownloadsFolder));\n}\n\nvoid DownloadsDOMHandler::OnDownloadUpdated(DownloadItem* download) {\n \/\/ Get the id for the download. Our downloads are sorted latest to first,\n \/\/ and the id is the index into that list. We should be careful of sync\n \/\/ errors between the UI and the download_items_ list (we may wish to use\n \/\/ something other than 'id').\n OrderedDownloads::iterator it = find(download_items_.begin(),\n download_items_.end(),\n download);\n if (it == download_items_.end())\n return;\n\n if (download->state() == DownloadItem::REMOVING) {\n (*it)->RemoveObserver(this);\n *it = NULL;\n \/\/ A later ModelChanged() notification will change the WebUI's\n \/\/ view of the downloads list.\n return;\n }\n\n const int id = static_cast<int>(it - download_items_.begin());\n\n ListValue results_value;\n results_value.Append(download_util::CreateDownloadItemValue(download, id));\n web_ui_->CallJavascriptFunction(\"downloadUpdated\", results_value);\n}\n\n\/\/ A download has started or been deleted. Query our DownloadManager for the\n\/\/ current set of downloads.\nvoid DownloadsDOMHandler::ModelChanged() {\n ClearDownloadItems();\n download_manager_->SearchDownloads(WideToUTF16(search_text_),\n &download_items_);\n \/\/ If we have a parent profile, let it add its downloads to the results.\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n if (profile->GetOriginalProfile() != profile) {\n profile->GetOriginalProfile()->GetDownloadManager()->SearchDownloads(\n WideToUTF16(search_text_), &download_items_);\n }\n\n sort(download_items_.begin(), download_items_.end(), DownloadItemSorter());\n\n \/\/ Remove any extension downloads.\n for (size_t i = 0; i < download_items_.size();) {\n if (ChromeDownloadManagerDelegate::IsExtensionDownload(download_items_[i]))\n download_items_.erase(download_items_.begin() + i);\n else\n i++;\n }\n\n \/\/ Add ourself to all download items as an observer.\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (static_cast<int>(it - download_items_.begin()) > kMaxDownloads)\n break;\n\n \/\/ TODO(rdsmith): Convert to DCHECK()s when http:\/\/crbug.com\/84508 is\n \/\/ fixed.\n \/\/ We should never see anything that isn't already in the history.\n CHECK(*it);\n CHECK_NE(DownloadItem::kUninitializedHandle, (*it)->db_handle());\n\n (*it)->AddObserver(this);\n }\n\n SendCurrentDownloads();\n}\n\nvoid DownloadsDOMHandler::HandleGetDownloads(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_GET_DOWNLOADS);\n std::wstring new_search = UTF16ToWideHack(ExtractStringValue(args));\n if (search_text_.compare(new_search) != 0) {\n search_text_ = new_search;\n ModelChanged();\n } else {\n SendCurrentDownloads();\n }\n\n download_manager_->CheckForHistoryFilesRemoval();\n}\n\nvoid DownloadsDOMHandler::HandleOpenFile(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FILE);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->OpenDownload();\n}\n\nvoid DownloadsDOMHandler::HandleDrag(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DRAG);\n DownloadItem* file = GetDownloadByValue(args);\n if (file) {\n IconManager* im = g_browser_process->icon_manager();\n gfx::Image* icon = im->LookupIcon(file->GetUserVerifiedFilePath(),\n IconLoader::NORMAL);\n gfx::NativeView view = web_ui_->tab_contents()->GetNativeView();\n {\n \/\/ Enable nested tasks during DnD, while |DragDownload()| blocks.\n MessageLoop::ScopedNestableTaskAllower allower(MessageLoop::current());\n download_util::DragDownload(file, icon, view);\n }\n }\n}\n\nvoid DownloadsDOMHandler::HandleSaveDangerous(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->DangerousDownloadValidated();\n}\n\nvoid DownloadsDOMHandler::HandleDiscardDangerous(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);\n}\n\nvoid DownloadsDOMHandler::HandleShow(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SHOW);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->ShowDownloadInShell();\n}\n\nvoid DownloadsDOMHandler::HandlePause(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_PAUSE);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->TogglePause();\n}\n\nvoid DownloadsDOMHandler::HandleRemove(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_REMOVE);\n DownloadItem* file = GetDownloadByValue(args);\n if (file) {\n \/\/ TODO(rdsmith): Change to DCHECK when http:\/\/crbug.com\/84508 is fixed.\n CHECK_NE(DownloadItem::kUninitializedHandle, file->db_handle());\n file->Remove();\n }\n}\n\nvoid DownloadsDOMHandler::HandleCancel(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CANCEL);\n DownloadItem* file = GetDownloadByValue(args);\n if (file)\n file->Cancel(true);\n}\n\nvoid DownloadsDOMHandler::HandleClearAll(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CLEAR_ALL);\n download_manager_->RemoveAllDownloads();\n\n Profile* profile =\n Profile::FromBrowserContext(download_manager_->browser_context());\n \/\/ If this is an incognito downloader, clear All should clear main download\n \/\/ manager as well.\n if (profile->GetOriginalProfile() != profile)\n profile->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();\n}\n\nvoid DownloadsDOMHandler::HandleOpenDownloadsFolder(const ListValue* args) {\n CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FOLDER);\n FilePath path = DownloadPrefs::FromDownloadManager(download_manager_)->\n download_path();\n\n#if defined(OS_MACOSX)\n \/\/ Must be called from the UI thread on Mac.\n platform_util::OpenItem(path);\n#else\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableFunction(&platform_util::OpenItem, path));\n#endif\n}\n\n\/\/ DownloadsDOMHandler, private: ----------------------------------------------\n\nvoid DownloadsDOMHandler::SendCurrentDownloads() {\n ListValue results_value;\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n int index = static_cast<int>(it - download_items_.begin());\n if (index > kMaxDownloads)\n break;\n if (!*it)\n continue;\n results_value.Append(download_util::CreateDownloadItemValue(*it, index));\n }\n\n web_ui_->CallJavascriptFunction(\"downloadsList\", results_value);\n}\n\nvoid DownloadsDOMHandler::ClearDownloadItems() {\n \/\/ Clear out old state and remove self as observer for each download.\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (!*it)\n continue;\n (*it)->RemoveObserver(this);\n }\n download_items_.clear();\n}\n\nDownloadItem* DownloadsDOMHandler::GetDownloadById(int id) {\n for (OrderedDownloads::iterator it = download_items_.begin();\n it != download_items_.end(); ++it) {\n if (static_cast<int>(it - download_items_.begin() == id)) {\n return (*it);\n }\n }\n\n return NULL;\n}\n\nDownloadItem* DownloadsDOMHandler::GetDownloadByValue(const ListValue* args) {\n int id;\n if (ExtractIntegerValue(args, &id)) {\n return GetDownloadById(id);\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n#ifndef INCLUDED_WRITERFILTER_SOURCE_DMAPPER_TABLEPOSITIONHANDLER_HXX\n#define INCLUDED_WRITERFILTER_SOURCE_DMAPPER_TABLEPOSITIONHANDLER_HXX\n\n#include <resourcemodel\/LoggedResources.hxx>\n#include <boost\/shared_ptr.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n\nnamespace writerfilter\n{\nnamespace dmapper\n{\n\n\/\/\/ Handler for floating table positioning\nclass TablePositionHandler\n : public LoggedProperties\n{\n OUString m_aVertAnchor;\n OUString m_aYSpec;\n OUString m_aHorzAnchor;\n OUString m_aXSpec;\n sal_Int32 m_nY;\n sal_Int32 m_nX;\n sal_Int32 m_nLeftFromText;\n sal_Int32 m_nRightFromText;\n sal_Int32 m_nTopFromText;\n sal_Int32 m_nBottomFromText;\n\n \/\/ Properties\n virtual void lcl_attribute(Id Name, Value& val) SAL_OVERRIDE;\n virtual void lcl_sprm(Sprm& sprm) SAL_OVERRIDE;\n\npublic:\n int getY()\n {\n return m_nY;\n }\n int getX()\n {\n return m_nX;\n }\n int getLeftFromText()\n {\n return m_nLeftFromText;\n }\n int getRightFromText()\n {\n return m_nRightFromText;\n }\n int getTopFromText()\n {\n return m_nTopFromText;\n }\n int getBottomFromText()\n {\n return m_nBottomFromText;\n }\n\n OUString getVertAnchor()\n {\n return m_aVertAnchor;\n }\n OUString getYSpec()\n {\n return m_aYSpec;\n }\n OUString getHorzAnchor()\n {\n return m_aHorzAnchor;\n }\n OUString getXSpec()\n {\n return m_aXSpec;\n }\n\n TablePositionHandler();\n virtual ~TablePositionHandler();\n\n \/** Compute the UNO properties for the frame containing the table based\n on the received tokens.\n\n Note that the properties will need to be adjusted with the table\n properties before actually using them.\n *\/\n com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> getTablePosition() const;\n\n bool operator== (const TablePositionHandler& rHandler) const;\n};\n\ntypedef boost::shared_ptr<TablePositionHandler> TablePositionHandlerPtr;\n} \/\/ namespace dmapper\n} \/\/ namespace writerfilter\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>writerfilter: try to fix 32-bit builds<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n#ifndef INCLUDED_WRITERFILTER_SOURCE_DMAPPER_TABLEPOSITIONHANDLER_HXX\n#define INCLUDED_WRITERFILTER_SOURCE_DMAPPER_TABLEPOSITIONHANDLER_HXX\n\n#include <resourcemodel\/LoggedResources.hxx>\n#include <boost\/shared_ptr.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n\nnamespace writerfilter\n{\nnamespace dmapper\n{\n\n\/\/\/ Handler for floating table positioning\nclass TablePositionHandler\n : public LoggedProperties\n{\n OUString m_aVertAnchor;\n OUString m_aYSpec;\n OUString m_aHorzAnchor;\n OUString m_aXSpec;\n sal_Int32 m_nY;\n sal_Int32 m_nX;\n sal_Int32 m_nLeftFromText;\n sal_Int32 m_nRightFromText;\n sal_Int32 m_nTopFromText;\n sal_Int32 m_nBottomFromText;\n\n \/\/ Properties\n virtual void lcl_attribute(Id Name, Value& val) SAL_OVERRIDE;\n virtual void lcl_sprm(Sprm& sprm) SAL_OVERRIDE;\n\npublic:\n sal_Int32 getY()\n {\n return m_nY;\n }\n sal_Int32 getX()\n {\n return m_nX;\n }\n sal_Int32 getLeftFromText()\n {\n return m_nLeftFromText;\n }\n sal_Int32 getRightFromText()\n {\n return m_nRightFromText;\n }\n sal_Int32 getTopFromText()\n {\n return m_nTopFromText;\n }\n sal_Int32 getBottomFromText()\n {\n return m_nBottomFromText;\n }\n\n OUString getVertAnchor()\n {\n return m_aVertAnchor;\n }\n OUString getYSpec()\n {\n return m_aYSpec;\n }\n OUString getHorzAnchor()\n {\n return m_aHorzAnchor;\n }\n OUString getXSpec()\n {\n return m_aXSpec;\n }\n\n TablePositionHandler();\n virtual ~TablePositionHandler();\n\n \/** Compute the UNO properties for the frame containing the table based\n on the received tokens.\n\n Note that the properties will need to be adjusted with the table\n properties before actually using them.\n *\/\n com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> getTablePosition() const;\n\n bool operator== (const TablePositionHandler& rHandler) const;\n};\n\ntypedef boost::shared_ptr<TablePositionHandler> TablePositionHandlerPtr;\n} \/\/ namespace dmapper\n} \/\/ namespace writerfilter\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by user on 16.03.19.\n\/\/\n\n#include <chrono>\n#include <random>\n#include <iostream>\n\n#define NDEBUG\n\n#include <cassert>\n\n#define CALCULATE_RECURSION (0)\n#if CALCULATE_RECURSION\nstatic size_t rec = 0;\nstatic size_t maxrec = 0;\n#endif\n\n\ntemplate<typename T>\nvoid print(const T *a, const T *b)\n{\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tstd::cout << n << \": \" << *n << std::endl;\n\t}\n\tstd::cout << b << \": \" << *b << std::endl;\n}\n\ntemplate<typename T>\nT hash(const T *a, const T *b)\n{\n\tT H = *b;\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tH ^= *n;\n\t}\n\treturn H;\n}\n\n\ntemplate<typename T>\nlong long int sum(const T *a, const T *b)\n{\n\tlong long int S = *b;\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tS += *n;\n\t}\n\treturn S;\n}\n\ntemplate<typename T>\nbool verify(const T *a, const T *b, const T h)\n{\n\treturn (h == hash(a, b));\n}\n\n\ntemplate<typename T>\nbool test(const T *a, const T *b)\n{\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tif (*n > *(n + 1))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\ninline void swap(T *a, T *b)\n{\n\t\/\/std::cout << \"swap: \" << a << \" <-> \" << b << std::endl;\n\tconst T t = *a;\n\t*a = *b;\n\t*b = t;\n}\n\ntemplate<typename T>\ninline void sort(T *a, T *b)\n{\n\tif (*b < *a)\n\t\tswap(a, b);\n}\n\ntemplate<typename T>\ninline void sort(T *a, T *b, T *c)\n{\n\tT A = *a;\n\tT B = *b;\n\tT C = *c;\n\n\tchar abc = 0;\n\tabc |= ((A < B) ? 001 : 0) | ((B < A) ? 010 : 0);\n\tabc |= ((B < C) ? 002 : 0) | ((C < B) ? 020 : 0);\n\tabc |= ((A < C) ? 004 : 0) | ((C < A) ? 040 : 0);\n\n\n\tswitch (abc)\n\t{\n\t\tcase 000:\n\t\t\t\/\/ A:1 B:1 C:1\n\t\t\t\/\/ A:2 B:2 C:2\n\t\t\t\/\/ A:3 B:3 C:3\n\t\tcase 005:\n\t\t\t\/\/ A:1 B:2 C:2\n\t\t\t\/\/ A:1 B:3 C:3\n\t\t\t\/\/ A:2 B:3 C:3\n\t\tcase 006:\n\t\t\t\/\/ A:1 B:1 C:2\n\t\t\t\/\/ A:1 B:1 C:3\n\t\t\t\/\/ A:2 B:2 C:3\n\t\tcase 007:\n\t\t\t\/\/ A:1 B:2 C:3\n\t\t\tbreak;\n\n\t\tcase 012:\n\t\t\t\/\/ A:3 B:2 C:3\n\t\t\t\/\/ A:2 B:1 C:2\n\t\t\t\/\/ A:3 B:1 C:3\n\t\tcase 016:\n\t\t\t\/\/ A:2 B:1 C:3\n\t\t\t*a = B;\n\t\t\t*b = A;\n\t\t\tbreak;\n\n\n\t\tcase 021:\n\t\t\t\/\/ A:1 B:2 C:1\n\t\t\t\/\/ A:1 B:3 C:1\n\t\t\t\/\/ A:2 B:3 C:2\n\t\tcase 025:\n\t\t\t\/\/ A:1 B:3 C:2\n\t\t\t*b = C;\n\t\t\t*c = B;\n\t\t\tbreak;\n\n\n\t\tcase 050:\n\t\t\t\/\/ A:2 B:1 C:1\n\t\t\t\/\/ A:3 B:1 C:1\n\t\t\t\/\/ A:3 B:2 C:2\n\t\tcase 060:\n\t\t\t\/\/ A:2 B:2 C:1\n\t\t\t\/\/ A:3 B:3 C:1\n\t\t\t\/\/ A:3 B:3 C:2\n\t\tcase 070:\n\t\t\t\/\/ A:3 B:2 C:1\n\t\t\t*a = C;\n\t\t\t*c = A;\n\t\t\tbreak;\n\n\n\t\tcase 052:\n\t\t\t\/\/ A:3 B:1 C:2\n\t\t\t*a = B;\n\t\t\t*b = C;\n\t\t\t*c = A;\n\t\t\tbreak;\n\n\t\tcase 061:\n\t\t\t\/\/ A:2 B:3 C:1\n\t\t\t*a = C;\n\t\t\t*b = A;\n\t\t\t*c = B;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t{\n\t\t\tstd::cerr << \"wrong case:\" << std::oct << static_cast<short>(abc) \/\/\n\t\t\t\t\t << \" A:\" << A << \" B:\" << B << \" C:\" << C << std::endl;\n\t\t}\n\t\t\tbreak;\n\t}\n}\n\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid qsort3(T *aa, T *bb)\n{\n\n#if CALCULATE_RECURSION\n\trec++;\n\tif (rec > maxrec)\n\t\tmaxrec = rec;\n#endif\n\tif (aa >= bb)\n\t{\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((aa + 1) == bb)\n\t{\n\t\t\/\/std::cout << \"duo sort: \" << aa << \" , \" << bb << std::endl;\n\t\tsort(aa, bb);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((aa + 2) == bb)\n\t{\n\t\t\/\/ std::cout << \"triple sort: \" << aa << \" , \" << bb << std::endl;\n\n\t\tsort(aa, aa + 1, bb);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\t\/\/ todo case of 3 elements\n\tT *a = aa;\n\tT *b = bb;\n\n\tT *x = (a + ((b - a) >> 1));\n\n\tsort(a, x, b);\n\n\tT A = *a;\n\tT B = *b;\n\tconst T X = *x;\n\t\/\/std::cout << \"quick sort: \" << aa << \" , \" << bb << \" : \" << X << std::endl;\n\n\tT *_a = x;\n\tT *b_ = x;\n\twhile (true)\n\t{\n\t\twhile (a < _a)\n\t\t{\n\t\t\twhile (A < X)\n\t\t\t{\n\t\t\t\t++a;\n\t\t\t\tA = *a;\n\t\t\t}\n\t\t\twhile (A == X)\n\t\t\t{\n\t\t\t\t--_a;\n\t\t\t\tif (_a < a)\n\t\t\t\t{\n\t\t\t\t\t_a = a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/swap(a, _a);\n\t\t\t\tA = *_a;\n\t\t\t\t*_a = X;\n\t\t\t\t*a = A;\n\t\t\t}\n\t\t\tif (X < A)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\twhile (b_ < b)\n\t\t{\n\t\t\twhile (X < B)\n\t\t\t{\n\t\t\t\t--b;\n\t\t\t\tB = *b;\n\t\t\t}\n\t\t\twhile (B == X)\n\t\t\t{\n\t\t\t\t++b_;\n\t\t\t\tif (b < b_)\n\t\t\t\t{\n\t\t\t\t\tb_ = b;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/swap(b, b_);\n\t\t\t\tB = *b_;\n\t\t\t\t*b_ = X;\n\t\t\t\t*b = B;\n\t\t\t}\n\t\t\tif (B < X)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (a < _a and b_ < b)\n\t\t{\n\t\t\tassert(*_a == X);\n\t\t\tassert(*b_ == X);\n\t\t\tassert(X < A);\n\t\t\tassert(B < X);\n\t\t\tassert(*a == A);\n\t\t\tassert(*b == B);\n\t\t\t*b = A;\n\t\t\t*a = B;\n\t\t\t++a;\n\t\t\t--b;\n\t\t\tA = *a;\n\t\t\tB = *b;\n\t\t}\n\t\telse if (a == _a and b_ < b)\n\t\t{\n\t\t\tassert(*a == X);\n\t\t\tassert(*_a == X);\n\t\t\tassert(*b == B);\n\t\t\tassert(*b_ == X);\n\t\t\tassert(B < X);\n\t\t\t++b_;\n\t\t\tif (b_ < b)\n\t\t\t{\n\t\t\t\t*a = B;\n\t\t\t\t++a;\n\t\t\t\t++_a;\n\t\t\t\tB = *b_;\n\t\t\t\t*b = B;\n\t\t\t\t*b_ = X;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*a = B;\n\t\t\t\t*b = X;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (a < _a and b_ == b)\n\t\t{\n\t\t\tassert(*a == A);\n\t\t\tassert(X < A);\n\n\t\t\tassert(*b == X);\n\t\t\tassert(*b_ == X);\n\t\t\t--_a;\n\t\t\tif (a < _a)\n\t\t\t{\n\t\t\t\t*b = A;\n\t\t\t\t--b;\n\t\t\t\t--b_;\n\t\t\t\tA = *_a;\n\t\t\t\t*a = A;\n\t\t\t\t*_a = X;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*b = A;\n\t\t\t\t*a = X;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(b == b_);\n\t\t\tassert(a == _a);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\tassert(b == b_);\n\tassert(a == _a);\n\n\tif (aa < a)\n\t\tqsort3(aa, a);\n\tif (b < bb)\n\t\tqsort3(b, bb);\n#if CALCULATE_RECURSION\n\trec--;\n#endif\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid qsort2(T *a, T *b)\n{\n#if CALCULATE_RECURSION\n\trec++;\n\tif (rec > maxrec)\n\t\tmaxrec = rec;\n#endif\n\tif (not(a < b))\n\t{\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((a + 1) == b)\n\t{\n\t\tif (*b < *a)\n\t\t\tswap(a, b);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\n\tT *A = a;\n\tT *B = b;\n\tconst T *c = a + ((b - a) >> 1);\n\tT P = *c;\n\n\tdo\n\t{\n\t\twhile (*a < P)\n\t\t\t++a;\n\n\t\twhile (P < *b )\n\t\t\t--b;\n\n\t\tif (a < b)\n\t\t{\n\t\t\tswap(a, b);\n\t\t\t++a;\n\t\t\t--b;\n\t\t}\n\t}\n\twhile (a < b);\n\n\n\tif (A < b)\n\t\tqsort2(A, b);\n\tif (a < B)\n\t\tqsort2(a, B);\n#if CALCULATE_RECURSION\n\trec--;\n#endif\n}\n\n\/\/------------------------------------------------------------------------------\n\nint main()\n{\n\n\tconst unsigned lim = 1000000;\n\t\/*\n\n\t10000000\n\n\tunsigned\n\n\tqs3\n\tAVG=2397.97\n\tSIGM=72.0195\n\n\tqs2\n\tAVG=1825.08\n\tSIGM=14.4573\n\n\n\tchar\n\tqs3\n\tAVG=665.82\n\tSIGM=21.6039\n\n\tqs2\n\tAVG=1196.53\n\tSIGM=10.4244\n\n\tshort\n\tqs2\n\tAVG=1502.58\n\tSIGM=10.5482\n\tqs3\n\tAVG=1485.86\n\tSIGM=23.222\n\n\t1000000\n\tlong long int\n\tqs3\n\tAVG=201.7\n\tSIGM=2.52784\n\tqs2\n\tAVG=164.03\n\tSIGM=2.44726\n\n\t-O\n\tqs3\n\tAVG=108.32\n\tSIGM=10.4727\n\tqs2\n\tAVG=74.94\n\tSIGM=2.17633\n\t*\/\n\ttypedef long long int T;\n\tT *V = new T[lim];\/\/\n\tconst T W[lim] = {9, 8, 7, 6};\n\tT *a = V;\n\tT *b = V + lim - 1;\n\n\tstd::mt19937_64 generator(time(nullptr));\n\tassert(0);\n\tdouble S = 0;\n\tconst unsigned stat_size = 100;\n\tlong long stat[stat_size];\n\tfor (unsigned s = 0; s < stat_size; ++s)\n\t{\n\t\tfor (int n = 0; n < lim; ++n)\n\t\t{\n\t\t\tV[n] = generator();\n\t\t\t\/\/V[n] = W[n];\n\t\t}\n\t\tconst T H = hash(a, b);\n\t\tconst auto sm = sum(a, b);\n\n\t\t\/\/std::cout << H << std::endl;\n\t\t\/\/print(0, lim - 1, V);\n\t\tif (test(V, b))\n\t\t{\n\t\t\t\/\/std::cout << \"sorted?!?!?!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::cout << \"test:\" << s << \" hash:\" << H << \" sum:\" << sm\n\t\t\t\t << std::endl;\n\t\t\/\/print(a, b);\n#if CALCULATE_RECURSION\n\t\trec = 0;\n#endif\n\t\tconst auto start = std::chrono::system_clock::now();\n\t\tqsort3(a, b);\n\t\tconst auto duration = std::chrono::system_clock::now() - start;\n\t\tif (not verify(a, b, H) or sm != sum(a, b))\n\t\t{\n\t\t\tstd::cout << \"FAIL array:\" << s << std::endl;\n\t\t\t\/\/print(a, b);\n\t\t\treturn 1;\n\t\t}\n\t\tif (not test(a, b))\n\t\t{\n\t\t\tstd::cout << \"FAIL sort:\" << s << std::endl;\n\t\t\t\/\/print(a, b);\n\t\t\treturn 1;\n\t\t}\n\t\tstat[s] = std::chrono::duration_cast<std::chrono::milliseconds>(\n\t\t\tduration).count();\n\n\t\tstd::cout << \"PASS:\" << stat[s] << \" msec\" << std::endl;\n\t\tS += stat[s];\n\t}\n\n\tS \/= (1.0 * stat_size);\n\tstd::cout << \" AVG=\" << S << std::endl;\n\n\n\tdouble Z = 0;\n\tfor (unsigned s = 0; s < stat_size; ++s)\n\t{\n\t\tconst double t = (stat[s] - S);\n\t\tZ += (t * t);\n\t}\n\tstd::cout << \" SIGM=\" << sqrt(Z \/ (1.0 * stat_size)) << std::endl;\n#if CALCULATE_RECURSION\n\tstd::cout << \" MAXREC=\" << maxrec << std::endl;\n#endif\n\tdelete[]V;\n\treturn 0;\n}<commit_msg>bruteforce search<commit_after>\/\/\n\/\/ Created by user on 16.03.19.\n\/\/\n\n#include <chrono>\n#include <random>\n#include <iostream>\n\n#define NDEBUG\n\n#include <cassert>\n\n#define CALCULATE_RECURSION (0)\n#if CALCULATE_RECURSION\nstatic size_t rec = 0;\nstatic size_t maxrec = 0;\n#endif\n\n\ntemplate<typename T>\nconst T *brute_search(const T *a, const T *b, const T X)\n{\n\tfor (const T *x = a; x <= b; ++x)\n\t{\n\t\tif (X == *x)\n\t\t\treturn x;\n\t}\n\treturn nullptr;\n}\n\n\ntemplate<typename T>\nvoid print(const T *a, const T *b)\n{\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tstd::cout << n << \": \" << *n << std::endl;\n\t}\n\tstd::cout << b << \": \" << *b << std::endl;\n}\n\ntemplate<typename T>\nT hash(const T *a, const T *b)\n{\n\tT H = *b;\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tH ^= *n;\n\t}\n\treturn H;\n}\n\n\ntemplate<typename T>\nlong long int sum(const T *a, const T *b)\n{\n\tlong long int S = *b;\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tS += *n;\n\t}\n\treturn S;\n}\n\ntemplate<typename T>\nbool verify(const T *a, const T *b, const T h)\n{\n\treturn (h == hash(a, b));\n}\n\n\ntemplate<typename T>\nbool test(const T *a, const T *b)\n{\n\tfor (const T *n = a; n != b; ++n)\n\t{\n\t\tif (*n > *(n + 1))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\ninline void swap(T *a, T *b)\n{\n\t\/\/std::cout << \"swap: \" << a << \" <-> \" << b << std::endl;\n\tconst T t = *a;\n\t*a = *b;\n\t*b = t;\n}\n\ntemplate<typename T>\ninline void sort(T *a, T *b)\n{\n\tif (*b < *a)\n\t\tswap(a, b);\n}\n\ntemplate<typename T>\ninline void sort(T *a, T *b, T *c)\n{\n\tT A = *a;\n\tT B = *b;\n\tT C = *c;\n\n\tchar abc = 0;\n\tabc |= ((A < B) ? 001 : 0) | ((B < A) ? 010 : 0);\n\tabc |= ((B < C) ? 002 : 0) | ((C < B) ? 020 : 0);\n\tabc |= ((A < C) ? 004 : 0) | ((C < A) ? 040 : 0);\n\n\n\tswitch (abc)\n\t{\n\t\tcase 000:\n\t\t\t\/\/ A:1 B:1 C:1\n\t\t\t\/\/ A:2 B:2 C:2\n\t\t\t\/\/ A:3 B:3 C:3\n\t\tcase 005:\n\t\t\t\/\/ A:1 B:2 C:2\n\t\t\t\/\/ A:1 B:3 C:3\n\t\t\t\/\/ A:2 B:3 C:3\n\t\tcase 006:\n\t\t\t\/\/ A:1 B:1 C:2\n\t\t\t\/\/ A:1 B:1 C:3\n\t\t\t\/\/ A:2 B:2 C:3\n\t\tcase 007:\n\t\t\t\/\/ A:1 B:2 C:3\n\t\t\tbreak;\n\n\t\tcase 012:\n\t\t\t\/\/ A:3 B:2 C:3\n\t\t\t\/\/ A:2 B:1 C:2\n\t\t\t\/\/ A:3 B:1 C:3\n\t\tcase 016:\n\t\t\t\/\/ A:2 B:1 C:3\n\t\t\t*a = B;\n\t\t\t*b = A;\n\t\t\tbreak;\n\n\n\t\tcase 021:\n\t\t\t\/\/ A:1 B:2 C:1\n\t\t\t\/\/ A:1 B:3 C:1\n\t\t\t\/\/ A:2 B:3 C:2\n\t\tcase 025:\n\t\t\t\/\/ A:1 B:3 C:2\n\t\t\t*b = C;\n\t\t\t*c = B;\n\t\t\tbreak;\n\n\n\t\tcase 050:\n\t\t\t\/\/ A:2 B:1 C:1\n\t\t\t\/\/ A:3 B:1 C:1\n\t\t\t\/\/ A:3 B:2 C:2\n\t\tcase 060:\n\t\t\t\/\/ A:2 B:2 C:1\n\t\t\t\/\/ A:3 B:3 C:1\n\t\t\t\/\/ A:3 B:3 C:2\n\t\tcase 070:\n\t\t\t\/\/ A:3 B:2 C:1\n\t\t\t*a = C;\n\t\t\t*c = A;\n\t\t\tbreak;\n\n\n\t\tcase 052:\n\t\t\t\/\/ A:3 B:1 C:2\n\t\t\t*a = B;\n\t\t\t*b = C;\n\t\t\t*c = A;\n\t\t\tbreak;\n\n\t\tcase 061:\n\t\t\t\/\/ A:2 B:3 C:1\n\t\t\t*a = C;\n\t\t\t*b = A;\n\t\t\t*c = B;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t{\n\t\t\tstd::cerr << \"wrong case:\" << std::oct << static_cast<short>(abc) \/\/\n\t\t\t\t\t << \" A:\" << A << \" B:\" << B << \" C:\" << C << std::endl;\n\t\t}\n\t\t\tbreak;\n\t}\n}\n\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid qsort3(T *aa, T *bb)\n{\n\n#if CALCULATE_RECURSION\n\trec++;\n\tif (rec > maxrec)\n\t\tmaxrec = rec;\n#endif\n\tif (aa >= bb)\n\t{\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((aa + 1) == bb)\n\t{\n\t\t\/\/std::cout << \"duo sort: \" << aa << \" , \" << bb << std::endl;\n\t\tsort(aa, bb);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((aa + 2) == bb)\n\t{\n\t\t\/\/ std::cout << \"triple sort: \" << aa << \" , \" << bb << std::endl;\n\n\t\tsort(aa, aa + 1, bb);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\t\/\/ todo case of 3 elements\n\tT *a = aa;\n\tT *b = bb;\n\n\tT *x = (a + ((b - a) >> 1));\n\n\tsort(a, x, b);\n\n\tT A = *a;\n\tT B = *b;\n\tconst T X = *x;\n\t\/\/std::cout << \"quick sort: \" << aa << \" , \" << bb << \" : \" << X << std::endl;\n\n\tT *_a = x;\n\tT *b_ = x;\n\twhile (true)\n\t{\n\t\twhile (a < _a)\n\t\t{\n\t\t\twhile (A < X)\n\t\t\t{\n\t\t\t\t++a;\n\t\t\t\tA = *a;\n\t\t\t}\n\t\t\twhile (A == X)\n\t\t\t{\n\t\t\t\t--_a;\n\t\t\t\tif (_a < a)\n\t\t\t\t{\n\t\t\t\t\t_a = a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/swap(a, _a);\n\t\t\t\tA = *_a;\n\t\t\t\t*_a = X;\n\t\t\t\t*a = A;\n\t\t\t}\n\t\t\tif (X < A)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\twhile (b_ < b)\n\t\t{\n\t\t\twhile (X < B)\n\t\t\t{\n\t\t\t\t--b;\n\t\t\t\tB = *b;\n\t\t\t}\n\t\t\twhile (B == X)\n\t\t\t{\n\t\t\t\t++b_;\n\t\t\t\tif (b < b_)\n\t\t\t\t{\n\t\t\t\t\tb_ = b;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\/\/swap(b, b_);\n\t\t\t\tB = *b_;\n\t\t\t\t*b_ = X;\n\t\t\t\t*b = B;\n\t\t\t}\n\t\t\tif (B < X)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (a < _a and b_ < b)\n\t\t{\n\t\t\tassert(*_a == X);\n\t\t\tassert(*b_ == X);\n\t\t\tassert(X < A);\n\t\t\tassert(B < X);\n\t\t\tassert(*a == A);\n\t\t\tassert(*b == B);\n\t\t\t*b = A;\n\t\t\t*a = B;\n\t\t\t++a;\n\t\t\t--b;\n\t\t\tA = *a;\n\t\t\tB = *b;\n\t\t}\n\t\telse if (a == _a and b_ < b)\n\t\t{\n\t\t\tassert(*a == X);\n\t\t\tassert(*_a == X);\n\t\t\tassert(*b == B);\n\t\t\tassert(*b_ == X);\n\t\t\tassert(B < X);\n\t\t\t++b_;\n\t\t\tif (b_ < b)\n\t\t\t{\n\t\t\t\t*a = B;\n\t\t\t\t++a;\n\t\t\t\t++_a;\n\t\t\t\tB = *b_;\n\t\t\t\t*b = B;\n\t\t\t\t*b_ = X;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*a = B;\n\t\t\t\t*b = X;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (a < _a and b_ == b)\n\t\t{\n\t\t\tassert(*a == A);\n\t\t\tassert(X < A);\n\n\t\t\tassert(*b == X);\n\t\t\tassert(*b_ == X);\n\t\t\t--_a;\n\t\t\tif (a < _a)\n\t\t\t{\n\t\t\t\t*b = A;\n\t\t\t\t--b;\n\t\t\t\t--b_;\n\t\t\t\tA = *_a;\n\t\t\t\t*a = A;\n\t\t\t\t*_a = X;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*b = A;\n\t\t\t\t*a = X;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(b == b_);\n\t\t\tassert(a == _a);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\tassert(b == b_);\n\tassert(a == _a);\n\n\tif (aa < a)\n\t\tqsort3(aa, a);\n\tif (b < bb)\n\t\tqsort3(b, bb);\n#if CALCULATE_RECURSION\n\trec--;\n#endif\n}\n\n\/\/------------------------------------------------------------------------------\n\ntemplate<typename T>\nvoid qsort2(T *a, T *b)\n{\n#if CALCULATE_RECURSION\n\trec++;\n\tif (rec > maxrec)\n\t\tmaxrec = rec;\n#endif\n\tif (not(a < b))\n\t{\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\tif ((a + 1) == b)\n\t{\n\t\tif (*b < *a)\n\t\t\tswap(a, b);\n#if CALCULATE_RECURSION\n\t\trec--;\n#endif\n\t\treturn;\n\t}\n\n\tT *A = a;\n\tT *B = b;\n\tconst T *c = a + ((b - a) >> 1);\n\tT P = *c;\n\n\tdo\n\t{\n\t\twhile (*a < P)\n\t\t\t++a;\n\n\t\twhile (P < *b)\n\t\t\t--b;\n\n\t\tif (a < b)\n\t\t{\n\t\t\tswap(a, b);\n\t\t\t++a;\n\t\t\t--b;\n\t\t}\n\t}\n\twhile (a < b);\n\n\n\tif (A < b)\n\t\tqsort2(A, b);\n\tif (a < B)\n\t\tqsort2(a, B);\n#if CALCULATE_RECURSION\n\trec--;\n#endif\n}\n\n\/\/------------------------------------------------------------------------------\n\nint main()\n{\n\n\tconst unsigned lim = 1000000000;\n\ttypedef short T;\n\t\/*\n\n\t10000000\n\n\tunsigned\n\n\tqs3\n\tAVG=2397.97\n\tSIGM=72.0195\n\n\tqs2\n\tAVG=1825.08\n\tSIGM=14.4573\n\n\n\tchar\n\tqs3\n\tAVG=665.82\n\tSIGM=21.6039\n\n\tqs2\n\tAVG=1196.53\n\tSIGM=10.4244\n\n\tshort\n\tqs2\n\tAVG=1502.58\n\tSIGM=10.5482\n\tqs3\n\tAVG=1485.86\n\tSIGM=23.222\n\n\t1000000\n\tlong long int\n\tqs3\n\tAVG=201.7\n\tSIGM=2.52784\n\tqs2\n\tAVG=164.03\n\tSIGM=2.44726\n\n\t-O\n\tqs3\n\tAVG=108.32\n\tSIGM=10.4727\n\tqs2\n\tAVG=74.94\n\tSIGM=2.17633\n\t*\/\n\tT *V = new T[lim];\/\/\n\tconst T W[lim] = {9, 8, 7, 6};\n\tT *a = V;\n\tT *b = V + lim - 1;\n\n\tstd::mt19937_64 generator(time(nullptr));\n\tassert(0);\n\tdouble S = 0;\n\tconst unsigned stat_size = 100;\n\tlong long stat[stat_size];\n\tfor (unsigned s = 0; s < stat_size; ++s)\n\t{\n\t\tfor (int n = 0; n < lim; ++n)\n\t\t{\n\t\t\tV[n] = generator();\n\t\t\t\/\/V[n] = W[n];\n\t\t}\n\n\t\t\/\/std::cout << H << std::endl;\n\t\t\/\/print(0, lim - 1, V);\n\t\tif (test(V, b))\n\t\t{\n\t\t\t\/\/std::cout << \"sorted?!?!?!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/print(a, b);\n#if CALCULATE_RECURSION\n\t\trec = 0;\n#endif\n\n\t\tconst T H = hash(a, b);\n\t\tconst auto sm = sum(a, b);\n\n\t\tstd::cout << \"test:\" << s << \" hash:\" << H << \" sum:\" << sm\n\t\t\t\t << std::endl;\n\n\t\tqsort2(a, b);\n\n\t\tconst T X = *(b-1);\n\n\t\tif (not verify(a, b, H) or sm != sum(a, b))\n\t\t{\n\t\t\tstd::cout << \"FAIL array:\" << s << std::endl;\n\t\t\t\/\/print(a, b);\n\t\t\treturn 1;\n\t\t}\n\t\tif (not test(a, b))\n\t\t{\n\t\t\tstd::cout << \"FAIL sort:\" << s << std::endl;\n\t\t\t\/\/print(a, b);\n\t\t\treturn 1;\n\t\t}\n\n\n\t\tconst auto start = std::chrono::system_clock::now();\n\t\tconst T *x = brute_search(a, b, X);\n\t\tconst auto duration = std::chrono::system_clock::now() - start;\n\t\tif (nullptr == x or *x != X)\n\t\t{\n\t\t\tstd::cout << X << \" not found\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tstat[s] = std::chrono::duration_cast<std::chrono::milliseconds>(\n\t\t\tduration).count();\n\n\t\tstd::cout << \"PASS:\" << stat[s] << \" msec\" << std::endl;\n\t\tS += stat[s];\n\t}\n\n\tS \/= (1.0 * stat_size);\n\tstd::cout << \" AVG=\" << S << std::endl;\n\n\n\tdouble Z = 0;\n\tfor (unsigned s = 0; s < stat_size; ++s)\n\t{\n\t\tconst double t = (stat[s] - S);\n\t\tZ += (t * t);\n\t}\n\tstd::cout << \" SIGM=\" << sqrt(Z \/ (1.0 * stat_size)) << std::endl;\n#if CALCULATE_RECURSION\n\tstd::cout << \" MAXREC=\" << maxrec << std::endl;\n#endif\n\tdelete[]V;\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLError.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\nusing WebKit::WebCompositionCommand;\nusing WebKit::WebFrame;\nusing WebKit::WebString;\nusing WebKit::WebTextDirection;\nusing WebKit::WebURLError;\n\ntypedef RenderViewTest FormAutocompleteTest;\n\n\/\/ Tests that submitting a form generates a FormSubmitted message\n\/\/ with the form fields.\nTEST_F(FormAutocompleteTest, NormalFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm'><input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/><\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1<FormData> forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(2U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n\n form_field = forms.a.fields[1];\n EXPECT_EQ(WebString(\"lname\"), form_field.name());\n EXPECT_EQ(WebString(\"Deckard\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has autocomplete=\"off\" does not generate a\n\/\/ FormSubmitted message.\nTEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm' autocomplete='off'>\"\n \"<input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/>\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n\n\/\/ Tests that fields with autocomplete off are not submitted.\nTEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm'>\"\n \"<input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard' autocomplete='off'\/>\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1<FormData> forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(1U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has been dynamically set as autocomplete\n\/\/ off does not generate a FormSubmitted message.\n\/\/ http:\/\/crbug.com\/36520\n\/\/ TODO(jcampan): Waiting on WebKit bug 35823.\nTEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {\n LoadHTML(\"<html><form id='myForm'><input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/><\/form><\/html>\");\n\n WebKit::WebElement element =\n GetMainFrame()->document().getElementById(WebKit::WebString(\"myForm\"));\n ASSERT_FALSE(element.isNull());\n WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();\n EXPECT_TRUE(form.autoComplete());\n\n \/\/ Dynamically mark the form as autocomplete off.\n ExecuteJavaScript(\"document.getElementById('myForm').autocomplete='off';\");\n ProcessPendingMessages();\n EXPECT_FALSE(form.autoComplete());\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n<commit_msg>Fix a build failure caused by the patch of https:\/\/bugs.webkit.org\/show_bug.cgi?id=41244<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/test\/render_view_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebURLError.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\nusing WebKit::WebFrame;\nusing WebKit::WebString;\nusing WebKit::WebTextDirection;\nusing WebKit::WebURLError;\n\ntypedef RenderViewTest FormAutocompleteTest;\n\n\/\/ Tests that submitting a form generates a FormSubmitted message\n\/\/ with the form fields.\nTEST_F(FormAutocompleteTest, NormalFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm'><input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/><\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1<FormData> forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(2U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n\n form_field = forms.a.fields[1];\n EXPECT_EQ(WebString(\"lname\"), form_field.name());\n EXPECT_EQ(WebString(\"Deckard\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has autocomplete=\"off\" does not generate a\n\/\/ FormSubmitted message.\nTEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm' autocomplete='off'>\"\n \"<input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/>\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n\n\/\/ Tests that fields with autocomplete off are not submitted.\nTEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) {\n \/\/ Load a form.\n LoadHTML(\"<html><form id='myForm'>\"\n \"<input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard' autocomplete='off'\/>\"\n \"<\/form><\/html>\");\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID);\n ASSERT_TRUE(message != NULL);\n\n Tuple1<FormData> forms;\n ViewHostMsg_FormSubmitted::Read(message, &forms);\n ASSERT_EQ(1U, forms.a.fields.size());\n\n webkit_glue::FormField& form_field = forms.a.fields[0];\n EXPECT_EQ(WebString(\"fname\"), form_field.name());\n EXPECT_EQ(WebString(\"Rick\"), form_field.value());\n}\n\n\/\/ Tests that submitting a form that has been dynamically set as autocomplete\n\/\/ off does not generate a FormSubmitted message.\n\/\/ http:\/\/crbug.com\/36520\n\/\/ TODO(jcampan): Waiting on WebKit bug 35823.\nTEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) {\n LoadHTML(\"<html><form id='myForm'><input name='fname' value='Rick'\/>\"\n \"<input name='lname' value='Deckard'\/><\/form><\/html>\");\n\n WebKit::WebElement element =\n GetMainFrame()->document().getElementById(WebKit::WebString(\"myForm\"));\n ASSERT_FALSE(element.isNull());\n WebKit::WebFormElement form = element.to<WebKit::WebFormElement>();\n EXPECT_TRUE(form.autoComplete());\n\n \/\/ Dynamically mark the form as autocomplete off.\n ExecuteJavaScript(\"document.getElementById('myForm').autocomplete='off';\");\n ProcessPendingMessages();\n EXPECT_FALSE(form.autoComplete());\n\n \/\/ Submit the form.\n ExecuteJavaScript(\"document.getElementById('myForm').submit();\");\n ProcessPendingMessages();\n\n \/\/ No FormSubmitted message should have been sent.\n EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching(\n ViewHostMsg_FormSubmitted::ID));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Socket.h\"\n\n#include \"Common.h\"\n\n#include <cstring>\n#include <errno.h>\n#include <unistd.h>\n#include <iostream>\n#include <fstream>\n#include <relay\/RelayServer.h>\n#include <iomanip>\n#include \"proxy\/ProxyServer.h\"\n#include \"ConnectionData.h\"\n#include \"Util.h\"\n#include \"MasterController.h\"\n\nusing namespace std;\n\nstruct Config\n{\n\tConfig() {\n\t\tproxyPort = -1;\n\t\trelayPort = -1;\n\t\tmasterAddress;\n\t\tmasterPort = -1;\n\t}\n\n\tint proxyPort;\n\tint relayPort;\n\tstd::string masterAddress;\n\tint masterPort;\n};\n\nvoid initMasterController(Config& config) {\n\n\tif (config.masterAddress.empty()) {\n\t\treturn;\n\t}\n\n\tauto master = MasterController::getInstance();\n\tchar ipo[INET_ADDRSTRLEN];\n\tinet_pton(AF_INET, config.masterAddress.c_str(), (void*)ipo);\n\n\tAddressDetails masterInfo;\n\tmasterInfo.addressType = IPV4_ADDRESS;\n\tmasterInfo.address = std::string();\n\tmasterInfo.address.append(ipo, 4);\n\tmasterInfo.port = (uint16_t)config.masterPort;\n\n\tstring ip;\n\tstring data;\n\n\tSocket::getLocalIPAddress(ip, data);\n\tif (ip.empty()) {\n\t\tcerr << \"Could not get Local IP Address: \" << ip << endl;\n\t\texit(1);\n\t}\n\n\tAddressDetails relayInfo;\n\trelayInfo.addressType = IPV4_ADDRESS;\n\trelayInfo.address = data;\n\trelayInfo.port = (uint16_t)config.relayPort;\n\n\tmaster->connect(relayInfo, masterInfo);\n}\n\n\/\/ Print an error message, usage, and then exit.\nvoid Usage(string errorMessage)\n{\n\tcerr << errorMessage << \"\\n\"\n\"Usage: [-config <config.cfg (default)>] [-proxy port <port, default 1080>] [-relay port <port, default 1090>] [-master <ip>:<port]\\n\"\n\"Command line options supersedes options in the config file.\\n\";\n\texit(1);\n}\n\nConfig ReadConfigFromFile(string filename)\n{\n\tConfig cfg;\n\tifstream input(filename.c_str());\n\n\tstring key;\n\tstring temp;\n\twhile (true) {\n\n\t\tinput >> key;\n\t\tif (input.eof() || key.empty())\n\t\t\tbreak;\n\n\t\tif (key == \"-proxy\") {\n\t\t\tstring type;\n\t\t\tinput >> type;\n\t\t\tif (type == \"port\") {\n\t\t\t\tinput >> cfg.proxyPort;\n\t\t\t\tif (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {\n\t\t\t\t\tUsage(\"Proxy Port must be between 1 and 65535. You specified \" + cfg.proxyPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-relay\") {\n\t\t\tstring type;\n\t\t\tinput >> type;\n\t\t\tif (type == \"port\") {\n\t\t\t\tinput >> cfg.relayPort;\n\t\t\t\tif (cfg.relayPort < 1 || cfg.relayPort > 65535) {\n\t\t\t\t\tUsage(\"Relay Port must be between 1 and 65535. You specified \" + cfg.relayPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-master\") {\n\t\t\tstring value;\n\t\t\tinput >> value;\n\t\t\tcfg.masterAddress = value.substr(0, value.find(':'));\n\t\t\tcfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);\n\t\t\tif (cfg.masterPort < 1 || cfg.masterPort > 65535) {\n\t\t\t\tUsage(\"Master Port must be between 1 and 65535. You specified \" + cfg.masterPort);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cfg;\n}\n\nConfig ParseCommandLine(int argc, char* argv[])\n{\n\tConfig cfg;\n\n\tstring configFile = \"config.cfg\";\n\n\tint i = 1;\n\twhile (i < argc - 1) {\n\t\tstring key = argv[i++];\n\n\t\tif (key == \"-config\") {\n\t\t\tconfigFile = argv[i++];\n\t\t}\n\t\telse if (key == \"-proxy\") {\n\t\t\tstring type = argv[i++];\n\t\t\tif (type == \"port\") {\n\t\t\t\tcfg.proxyPort = StoI(argv[i++], -1);\n\t\t\t\tif (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {\n\t\t\t\t\tUsage(\"Proxy Port must be between 1 and 65535. You specified \" + cfg.proxyPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-relay\") {\n\t\t\tstring type = argv[i++];\n\t\t\tif (type == \"port\") {\n\t\t\t\tcfg.relayPort = StoI(argv[i++], -1);\n\t\t\t\tif (cfg.relayPort < 1 || cfg.relayPort > 65535) {\n\t\t\t\t\tUsage(\"Relay Port must be between 1 and 65535. You specified \" + cfg.relayPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-master\") {\n\t\t\tstring value = argv[i++];\n\t\t\t\/\/ parse ip\n\t\t\tcfg.masterAddress = value.substr(0, value.find(':'));\n\t\t\tcfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);\n\t\t\tif (cfg.masterPort < 1 || cfg.masterPort > 65535) {\n\t\t\t\tUsage(\"Master Port must be between 1 and 65535. You specified \" + cfg.masterPort);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tUsage(\"Unknown option: \" + key);\n\t\t}\n\t}\n\n\n\tConfig cfgFromFile = ReadConfigFromFile(configFile);\n\t\/\/ Load in defaults\n\tif (cfg.relayPort == -1)\n\t\tcfg.relayPort = cfgFromFile.relayPort;\n\tif (cfg.relayPort == -1)\n\t\tcfg.relayPort = 1090;\n\n\tif (cfg.proxyPort == -1)\n\t\tcfg.proxyPort = cfgFromFile.proxyPort ;\n\tif (cfg.proxyPort == -1)\n\t\tcfg.proxyPort = 1080;\n\n\tif (cfg.masterPort == -1)\n\t\tcfg.masterPort = cfgFromFile.masterPort ;\n\tif (cfg.masterPort == -1)\n\t\tcfg.masterPort = 1090;\n\n\tif (cfg.masterAddress.empty())\n\t\tcfg.masterAddress = cfgFromFile.masterAddress ;\n\tif (cfg.masterAddress.empty())\n\t\tcfg.masterAddress = \"127.0.0.1\";\n\n\treturn cfg;\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ Command line options will be:\n\t\/\/ -config <file>\n\t\/\/ -proxy port <port>\n\t\/\/ -relay port <port>\n\t\/\/ -master <address>:<port>\n\tConfig cfg = ParseCommandLine(argc, argv);\n\n\tAddressDetails t;\n\tt.addressType = DOMAIN_ADDRESS;\n\tt.address = \"localhost\";\n\tt.port = 443;\n\n\tstringstream ss;\n\tss << t;\n\tstring pp = ss.str();\n\n\tstring ip;\n\tstring data;\n\tSocket::getLocalIPAddress(ip, data);\n\n\tcout << \"Local IP Address: \" << ip << endl;\n\n\tthread p([&] {\n\t\tProxyServer proxy = ProxyServer(cfg.proxyPort);\n\t\tproxy.Listen();\n\t});\n\n\tthread r([&] {\n\t\tRelayServer relay = RelayServer(cfg.relayPort);\n\t\trelay.Listen();\n\t});\n\tinitMasterController(cfg);\n\n\tp.join();\n\tr.join();\n\n\treturn 0;\n}\n<commit_msg>Fixed up by using pton<commit_after>#include \"Socket.h\"\n\n#include \"Common.h\"\n\n#include <cstring>\n#include <errno.h>\n#include <unistd.h>\n#include <iostream>\n#include <fstream>\n#include <relay\/RelayServer.h>\n#include <iomanip>\n#include \"proxy\/ProxyServer.h\"\n#include \"ConnectionData.h\"\n#include \"Util.h\"\n#include \"MasterController.h\"\n\nusing namespace std;\n\nstruct Config\n{\n\tConfig() {\n\t\tproxyPort = -1;\n\t\trelayPort = -1;\n\t\tmasterAddress;\n\t\tmasterPort = -1;\n\t}\n\n\tint proxyPort;\n\tint relayPort;\n\tstd::string masterAddress;\n\tint masterPort;\n};\n\nvoid initMasterController(Config& config) {\n\n\tif (config.masterAddress.empty()) {\n\t\treturn;\n\t}\n\n\tauto master = MasterController::getInstance();\n\n\tAddressDetails masterInfo;\n\tmasterInfo.addressType = IPV4_ADDRESS;\n\tmasterInfo.address = Util::PresentationToNetwork(config.masterAddress);\n\tmasterInfo.port = (uint16_t)config.masterPort;\n\n\tstring ip;\n\tstring data;\n\n\tSocket::getLocalIPAddress(ip, data);\n\tif (ip.empty()) {\n\t\tcerr << \"Could not get Local IP Address: \" << ip << endl;\n\t\texit(1);\n\t}\n\n\tAddressDetails relayInfo;\n\trelayInfo.addressType = IPV4_ADDRESS;\n\trelayInfo.address = Util::PresentationToNetwork(ip);\n\trelayInfo.port = (uint16_t)config.relayPort;\n\n\tmaster->connect(relayInfo, masterInfo);\n}\n\n\/\/ Print an error message, usage, and then exit.\nvoid Usage(string errorMessage)\n{\n\tcerr << errorMessage << \"\\n\"\n\"Usage: [-config <config.cfg (default)>] [-proxy port <port, default 1080>] [-relay port <port, default 1090>] [-master <ip>:<port]\\n\"\n\"Command line options supersedes options in the config file.\\n\";\n\texit(1);\n}\n\nConfig ReadConfigFromFile(string filename)\n{\n\tConfig cfg;\n\tifstream input(filename.c_str());\n\n\tstring key;\n\tstring temp;\n\twhile (true) {\n\n\t\tinput >> key;\n\t\tif (input.eof() || key.empty())\n\t\t\tbreak;\n\n\t\tif (key == \"-proxy\") {\n\t\t\tstring type;\n\t\t\tinput >> type;\n\t\t\tif (type == \"port\") {\n\t\t\t\tinput >> cfg.proxyPort;\n\t\t\t\tif (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {\n\t\t\t\t\tUsage(\"Proxy Port must be between 1 and 65535. You specified \" + cfg.proxyPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-relay\") {\n\t\t\tstring type;\n\t\t\tinput >> type;\n\t\t\tif (type == \"port\") {\n\t\t\t\tinput >> cfg.relayPort;\n\t\t\t\tif (cfg.relayPort < 1 || cfg.relayPort > 65535) {\n\t\t\t\t\tUsage(\"Relay Port must be between 1 and 65535. You specified \" + cfg.relayPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-master\") {\n\t\t\tstring value;\n\t\t\tinput >> value;\n\t\t\tcfg.masterAddress = value.substr(0, value.find(':'));\n\t\t\tcfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);\n\t\t\tif (cfg.masterPort < 1 || cfg.masterPort > 65535) {\n\t\t\t\tUsage(\"Master Port must be between 1 and 65535. You specified \" + cfg.masterPort);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cfg;\n}\n\nConfig ParseCommandLine(int argc, char* argv[])\n{\n\tConfig cfg;\n\n\tstring configFile = \"config.cfg\";\n\n\tint i = 1;\n\twhile (i < argc - 1) {\n\t\tstring key = argv[i++];\n\n\t\tif (key == \"-config\") {\n\t\t\tconfigFile = argv[i++];\n\t\t}\n\t\telse if (key == \"-proxy\") {\n\t\t\tstring type = argv[i++];\n\t\t\tif (type == \"port\") {\n\t\t\t\tcfg.proxyPort = StoI(argv[i++], -1);\n\t\t\t\tif (cfg.proxyPort < 1 || cfg.proxyPort > 65535) {\n\t\t\t\t\tUsage(\"Proxy Port must be between 1 and 65535. You specified \" + cfg.proxyPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-relay\") {\n\t\t\tstring type = argv[i++];\n\t\t\tif (type == \"port\") {\n\t\t\t\tcfg.relayPort = StoI(argv[i++], -1);\n\t\t\t\tif (cfg.relayPort < 1 || cfg.relayPort > 65535) {\n\t\t\t\t\tUsage(\"Relay Port must be between 1 and 65535. You specified \" + cfg.relayPort);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (key == \"-master\") {\n\t\t\tstring value = argv[i++];\n\t\t\t\/\/ parse ip\n\t\t\tcfg.masterAddress = value.substr(0, value.find(':'));\n\t\t\tcfg.masterPort = StoI(value.substr(value.find(':') + 1), -1);\n\t\t\tif (cfg.masterPort < 1 || cfg.masterPort > 65535) {\n\t\t\t\tUsage(\"Master Port must be between 1 and 65535. You specified \" + cfg.masterPort);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tUsage(\"Unknown option: \" + key);\n\t\t}\n\t}\n\n\n\tConfig cfgFromFile = ReadConfigFromFile(configFile);\n\t\/\/ Load in defaults\n\tif (cfg.relayPort == -1)\n\t\tcfg.relayPort = cfgFromFile.relayPort;\n\tif (cfg.relayPort == -1)\n\t\tcfg.relayPort = 1090;\n\n\tif (cfg.proxyPort == -1)\n\t\tcfg.proxyPort = cfgFromFile.proxyPort ;\n\tif (cfg.proxyPort == -1)\n\t\tcfg.proxyPort = 1080;\n\n\tif (cfg.masterPort == -1)\n\t\tcfg.masterPort = cfgFromFile.masterPort ;\n\tif (cfg.masterPort == -1)\n\t\tcfg.masterPort = 1090;\n\n\tif (cfg.masterAddress.empty())\n\t\tcfg.masterAddress = cfgFromFile.masterAddress ;\n\tif (cfg.masterAddress.empty())\n\t\tcfg.masterAddress = \"127.0.0.1\";\n\n\treturn cfg;\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ Command line options will be:\n\t\/\/ -config <file>\n\t\/\/ -proxy port <port>\n\t\/\/ -relay port <port>\n\t\/\/ -master <address>:<port>\n\tConfig cfg = ParseCommandLine(argc, argv);\n\n\tAddressDetails t;\n\tt.addressType = DOMAIN_ADDRESS;\n\tt.address = \"localhost\";\n\tt.port = 443;\n\n\tstringstream ss;\n\tss << t;\n\tstring pp = ss.str();\n\n\tstring ip;\n\tstring data;\n\tSocket::getLocalIPAddress(ip, data);\n\n\tcout << \"Local IP Address: \" << ip << endl;\n\n\tthread p([&] {\n\t\tProxyServer proxy = ProxyServer(cfg.proxyPort);\n\t\tproxy.Listen();\n\t});\n\n\tthread r([&] {\n\t\tRelayServer relay = RelayServer(cfg.relayPort);\n\t\trelay.Listen();\n\t});\n\tinitMasterController(cfg);\n\n\tp.join();\n\tr.join();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include <QApplication>\n#include <exception>\n#include <iostream>\n#include <cstdlib>\n\nint main(int argc, char *argv[])\n{\n try\n {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n }\n catch (const std::exception &ex)\n {\n std::cerr << \"Fatal Error: \" << ex.what() << \"\\nThe application will now exit.\" << std::endl;\n return EXIT_FAILURE;\n }\n}\n<commit_msg>Added messagebox for caught exceptions<commit_after>#include \"mainwindow.h\"\n#include <QApplication>\n#include <QMessageBox>\n#include <QString>\n#include <cstdlib>\n#include <exception>\n\nint main(int argc, char *argv[])\n{\n \/\/ The QApplication is outside the try-catch because\n \/\/ QMessageBox requires an active QApplication to work.\n\n QApplication a(argc, argv);\n\n try\n {\n MainWindow w;\n w.show();\n\n return a.exec();\n }\n catch (const std::exception &ex)\n {\n QString errMsg = QString(ex.what()) + \"\\nThe application will now exit.\";\n QMessageBox::critical(nullptr, \"Fatal Error\", errMsg);\n return EXIT_FAILURE;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright 2011-2013 The University of North Carolina at Chapel Hill\n * All rights reserved.\n *\n * Licensed under the MADAI Software License. You may obtain a copy of\n * this license at\n *\n * https:\/\/madai-public.cs.unc.edu\/visualization\/software-license\/\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include <cassert> \/\/ assert\n#include <cstdlib> \/\/ std::atof\n#include <cmath> \/\/ std::sqrt, std::pow\n#include <iostream> \/\/ std::cout\n#include <fstream> \/\/ std::ifstream\n#include <vector> \/\/ std::vector\n#include <string> \/\/ std::string\n#include <sstream> \/\/ std::stringstream\n#include <iomanip> \/\/ std::setw\n#include <limits> \/\/ inifity\n\n#include \"ApplicationUtilities.h\"\n#include \"GaussianProcessEmulatorDirectoryFormatIO.h\"\n#include \"Paths.h\"\n#include \"System.h\"\n\nint main(int argc, char ** argv) {\n if (argc < 3) {\n std::cerr\n << \"Usage\\n \" << argv[0]\n << \" statistics_directory trace_file\\n\\n\";\n return EXIT_FAILURE;\n }\n std::string statisticsDirectory( argv[1] );\n madai::EnsurePathSeparatorAtEnd( statisticsDirectory );\n\n std::vector< madai::Parameter > parameters;\n int numberOfParameters = 0;\n\n if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(\n parameters, numberOfParameters, statisticsDirectory, false )) {\n std::cerr\n << \"Could not read parameters from prior file '\"\n << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << \"'\\n\";\n return EXIT_FAILURE;\n }\n assert (numberOfParameters = parameters.size());\n\n std::string traceFile( statisticsDirectory );\n traceFile.append( argv[2] );\n\n if ( !madai::System::IsFile( traceFile ) ) {\n std::cerr << \"Trace file '\" << traceFile << \"' does not exist or is a directory.\\n\";\n return EXIT_FAILURE;\n }\n\n std::ifstream trace(traceFile.c_str());\n if ( !trace.good() ) {\n std::cerr << \"Error reading trace file '\" << traceFile << \"'.\\n\";\n return EXIT_FAILURE;\n }\n\n std::string header;\n std::getline(trace,header);\n std::vector<std::string> headers = madai::SplitString(header, ',');\n\n size_t numberOfFields = headers.size();\n assert(static_cast<int>(numberOfFields) > numberOfParameters);\n\n std::string line;\n size_t lineCount = 0, bestIndex = 0;\n std::vector< double > sums(numberOfParameters, 0.0);\n std::vector< std::vector< double > > values(numberOfParameters);\n\n double bestLogLikelihood = -std::numeric_limits< double >::infinity();\n\n while (std::getline(trace,line)) {\n std::vector<std::string> fields = madai::SplitString(line, ',');\n assert(numberOfFields == fields.size());\n for (int i = 0; i < numberOfParameters; ++i) {\n double value = std::atof(fields[i].c_str());\n values[i].push_back(value);\n sums[i] += value;\n }\n double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());\n if (logLikelihood > bestLogLikelihood) {\n bestLogLikelihood = logLikelihood;\n bestIndex = lineCount;\n }\n ++lineCount;\n }\n\n trace.close();\n std::vector< double > means(numberOfParameters,0.0);\n\n std::vector< double > priorStdDev(numberOfParameters,0.0);\n for (int i = 0; i < numberOfParameters; ++i) {\n priorStdDev[i] =\n parameters[i].GetPriorDistribution()->GetStandardDeviation();\n }\n std::cout << std::setw(14) << \"parameter\";\n std::cout << std::setw(14) << \"mean\";\n std::cout << std::setw(14) << \"std.dev.\";\n std::cout << std::setw(14) << \"scaled dev.\";\n std::cout << std::setw(14) << \"best value\";\n std::cout << '\\n';\n\n for (int i = 0; i < numberOfParameters; ++i) {\n means[i] = sums[i] \/ lineCount;\n double variance = 0.0;\n for (size_t k = 0; k < lineCount; ++k) {\n variance += std::pow(values[i][k] - means[i], 2);\n }\n variance \/= lineCount;\n std::cout\n << std::setw(14) << parameters[i].m_Name\n << std::setw(14) << means[i]\n << std::setw(14) << std::sqrt(variance)\n << std::setw(14) << std::sqrt(variance) \/ priorStdDev[i]\n << std::setw(14) << values[i][bestIndex]\n << '\\n';\n }\n\n \/\/ Print the relative log-likelihood from the best point\n std::cout << \"\\nbest log likelihood\\n\";\n std::cout << std::setw(14) << bestLogLikelihood << \"\\n\";\n\n std::vector< std::vector< double > > covariancematrix;\n for (int i = 0; i < numberOfParameters; ++i)\n covariancematrix.push_back(std::vector< double >(numberOfParameters, 0.0));\n\n for (int i = 0; i < numberOfParameters; ++i) {\n for (int j = 0; j <= i; ++j) {\n double covariance = 0.0;\n for (size_t k = 0; k < lineCount; ++k) {\n covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);\n }\n covariancematrix[i][j] = covariance \/= lineCount;\n if (i != j)\n covariancematrix[j][i] = covariancematrix[i][j];\n }\n }\n\n std::cout << \"\\ncovariance:\\n\";\n std::cout << std::setw(14) << \"\";\n for (int j = 0; j < numberOfParameters; ++j)\n std::cout << std::setw(14) << parameters[j].m_Name;\n std::cout << \"\\n\";\n for (int i = 0; i < numberOfParameters; ++i) {\n std::cout << std::setw(14) << parameters[i].m_Name;\n for (int j = 0; j < numberOfParameters; ++j) {\n std::cout << std::setw(14) << covariancematrix[i][j];\n }\n std::cout << \"\\n\";\n }\n\n std::cout << \"\\nscaled covariance:\\n\";\n std::cout << std::setw(14) << \"\";\n for (int j = 0; j < numberOfParameters; ++j)\n std::cout << std::setw(14) << parameters[j].m_Name;\n std::cout << \"\\n\";\n for (int i = 0; i < numberOfParameters; ++i) {\n std::cout << std::setw(14) << parameters[i].m_Name;\n for (int j = 0; j < numberOfParameters; ++j) {\n std::cout << std::setw(14) << covariancematrix[i][j] \/ (\n priorStdDev[i] * priorStdDev[j]);\n }\n std::cout << \"\\n\";\n }\n\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Added the printout of the correlation matrix between observables and parameters. The absolute values of these are related to the resolving power of a variable.<commit_after>\/*=========================================================================\n *\n * Copyright 2011-2013 The University of North Carolina at Chapel Hill\n * All rights reserved.\n *\n * Licensed under the MADAI Software License. You may obtain a copy of\n * this license at\n *\n * https:\/\/madai-public.cs.unc.edu\/visualization\/software-license\/\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include <cassert> \/\/ assert\n#include <cstdlib> \/\/ std::atof\n#include <cmath> \/\/ std::sqrt, std::pow\n#include <iostream> \/\/ std::cout\n#include <fstream> \/\/ std::ifstream\n#include <vector> \/\/ std::vector\n#include <string> \/\/ std::string\n#include <sstream> \/\/ std::stringstream\n#include <iomanip> \/\/ std::setw\n#include <limits> \/\/ inifity\n\n#include \"ApplicationUtilities.h\"\n#include \"GaussianProcessEmulatorDirectoryFormatIO.h\"\n#include \"Paths.h\"\n#include \"System.h\"\n\nint main(int argc, char ** argv) {\n if (argc < 3) {\n std::cerr\n << \"Usage\\n \" << argv[0]\n << \" statistics_directory trace_file\\n\\n\";\n return EXIT_FAILURE;\n }\n std::string statisticsDirectory( argv[1] );\n madai::EnsurePathSeparatorAtEnd( statisticsDirectory );\n\n std::vector< madai::Parameter > parameters;\n int numberOfParameters = 0;\n\n if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(\n parameters, numberOfParameters, statisticsDirectory, false )) {\n std::cerr\n << \"Could not read parameters from prior file '\"\n << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << \"'\\n\";\n return EXIT_FAILURE;\n }\n assert (numberOfParameters = parameters.size());\n\n std::vector< std::string > outputNames;\n int numberOfOutputs = 0;\n\n if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs(\n outputNames, numberOfOutputs, statisticsDirectory, false )) {\n std::cerr\n << \"Could not read outputs from prior file '\"\n << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << \"'\\n\";\n return EXIT_FAILURE;\n }\n assert (numberOfOutputs = outputNames.size());\n\n std::string traceFile( statisticsDirectory );\n traceFile.append( argv[2] );\n\n if ( !madai::System::IsFile( traceFile ) ) {\n std::cerr << \"Trace file '\" << traceFile << \"' does not exist or is a directory.\\n\";\n return EXIT_FAILURE;\n }\n\n std::ifstream trace(traceFile.c_str());\n if ( !trace.good() ) {\n std::cerr << \"Error reading trace file '\" << traceFile << \"'.\\n\";\n return EXIT_FAILURE;\n }\n\n std::string header;\n std::getline(trace,header);\n std::vector<std::string> headers = madai::SplitString(header, ',');\n\n int numberOfFields = headers.size();\n assert(numberOfFields == numberOfParameters + numberOfOutputs + 1);\n\n std::string line;\n size_t lineCount = 0, bestIndex = 0;\n std::vector< double > sums(numberOfFields - 1, 0.0);\n std::vector< std::vector< double > > values(numberOfFields - 1);\n\n double bestLogLikelihood = -std::numeric_limits< double >::infinity();\n\n while (std::getline(trace,line)) {\n std::vector<std::string> fields = madai::SplitString(line, ',');\n assert(numberOfFields == (int) fields.size());\n for (int i = 0; i < numberOfFields - 1; ++i) {\n double value = std::atof(fields[i].c_str());\n values[i].push_back(value);\n sums[i] += value;\n }\n double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());\n if (logLikelihood > bestLogLikelihood) {\n bestLogLikelihood = logLikelihood;\n bestIndex = lineCount;\n }\n ++lineCount;\n }\n\n trace.close();\n std::vector< double > means(numberOfFields - 1,0.0);\n\n std::vector< double > priorStdDev(numberOfFields - 1,0.0);\n for (int i = 0; i < numberOfParameters; ++i) {\n priorStdDev[i] =\n parameters[i].GetPriorDistribution()->GetStandardDeviation();\n }\n std::cout << std::setw(14) << \"parameter\";\n std::cout << std::setw(14) << \"mean\";\n std::cout << std::setw(14) << \"std.dev.\";\n std::cout << std::setw(14) << \"scaled dev.\";\n std::cout << std::setw(14) << \"best value\";\n std::cout << '\\n';\n\n for (int i = 0; i < numberOfFields - 1; ++i) {\n means[i] = sums[i] \/ lineCount;\n }\n for (int i = 0; i < numberOfParameters; ++i) {\n double variance = 0.0;\n for (size_t k = 0; k < lineCount; ++k) {\n variance += std::pow(values[i][k] - means[i], 2);\n }\n variance \/= lineCount;\n std::cout\n << std::setw(14) << parameters[i].m_Name\n << std::setw(14) << means[i]\n << std::setw(14) << std::sqrt(variance)\n << std::setw(14) << std::sqrt(variance) \/ priorStdDev[i]\n << std::setw(14) << values[i][bestIndex]\n << '\\n';\n }\n\n \/\/ Print the relative log-likelihood from the best point\n std::cout << \"\\nbest log likelihood\\n\";\n std::cout << std::setw(14) << bestLogLikelihood << \"\\n\";\n\n std::vector< std::vector< double > > covariancematrix;\n for (int i = 0; i < numberOfFields - 1; ++i)\n covariancematrix.push_back(std::vector< double >(numberOfFields - 1, 0.0));\n\n for (int i = 0; i < numberOfFields - 1; ++i) {\n for (int j = 0; j <= i; ++j) {\n double covariance = 0.0;\n for (size_t k = 0; k < lineCount; ++k) {\n covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);\n }\n covariancematrix[i][j] = covariance \/= lineCount;\n if (i != j)\n covariancematrix[j][i] = covariancematrix[i][j];\n }\n }\n\n std::cout << \"\\ncovariance:\\n\";\n std::cout << std::setw(14) << \"\";\n for (int j = 0; j < numberOfParameters; ++j)\n std::cout << std::setw(14) << parameters[j].m_Name;\n std::cout << \"\\n\";\n for (int i = 0; i < numberOfParameters; ++i) {\n std::cout << std::setw(14) << parameters[i].m_Name;\n for (int j = 0; j < numberOfParameters; ++j) {\n std::cout << std::setw(14) << covariancematrix[i][j];\n }\n std::cout << \"\\n\";\n }\n\n std::cout << \"\\nscaled covariance:\\n\";\n std::cout << std::setw(14) << \"\";\n for (int j = 0; j < numberOfParameters; ++j)\n std::cout << std::setw(14) << parameters[j].m_Name;\n std::cout << \"\\n\";\n for (int i = 0; i < numberOfParameters; ++i) {\n std::cout << std::setw(14) << parameters[i].m_Name;\n for (int j = 0; j < numberOfParameters; ++j) {\n std::cout << std::setw(14) << covariancematrix[i][j] \/ (\n priorStdDev[i] * priorStdDev[j]);\n }\n std::cout << \"\\n\";\n }\n\n std::cout << \"\\nobservable-parameter correlation:\\n\";\n std::cout << std::setw(14) << \"\";\n for (int j = 0; j < numberOfParameters; ++j)\n std::cout << std::setw(14) << parameters[j].m_Name;\n std::cout << \"\\n\";\n for (int i = 0; i < numberOfOutputs; ++i) {\n std::cout << std::setw(14) << outputNames[i];\n for (int j = 0; j < numberOfParameters; ++j) {\n std::cout << std::setw(14) << covariancematrix[numberOfParameters + i][j] \/ (\n std::sqrt(covariancematrix[numberOfParameters + i][numberOfParameters + i]*\n covariancematrix[j][j]));\n }\n std::cout << \"\\n\";\n }\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2019 Alain Dargelas\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/* \n * File: main.cpp\n * Author: alain\n *\n * Created on January 15, 2017, 12:15 AM\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <sys\/stat.h>\n#include <sys\/param.h>\n#include <unistd.h>\n#include <fstream>\n\n#include \"surelog.h\"\n#include \"ErrorReporting\/Report.h\"\n#include \"API\/PythonAPI.h\"\n#include \"Utils\/StringUtils.h\"\n\nunsigned int executeCompilation(int argc, const char ** argv, bool diff_comp_mode, \n bool fileunit, SURELOG::ErrorContainer::Stats* overallStats = NULL)\n{\n bool success = true;\n bool noFatalErrors = true;\n unsigned int codedReturn = 0;\n SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();\n SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);\n SURELOG::CommandLineParser* clp = new SURELOG::CommandLineParser (errors, symbolTable, diff_comp_mode, fileunit);\n success = clp->parseCommandLine (argc, argv);\n bool parseOnly = clp->parseOnly();\n errors->printMessages (clp->muteStdout ());\n if (success && (!clp->help()))\n {\n SURELOG::scompiler* compiler = SURELOG::start_compiler(clp); \n if (!compiler)\n codedReturn |= 1;\n SURELOG::shutdown_compiler(compiler);\n }\n SURELOG::ErrorContainer::Stats stats;\n if (!clp->help()) {\n stats = errors->getErrorStats ();\n if (overallStats)\n (*overallStats) += stats;\n if (stats.nbFatal)\n codedReturn |= 1;\n if (stats.nbSyntax)\n codedReturn |= 2;\n if (stats.nbError)\n codedReturn |= 4;\n }\n bool noFErrors = true;\n if (!clp->help())\n noFErrors = errors->printStats (stats,clp->muteStdout ());\n if (noFErrors == false) {\n noFatalErrors = false;\n }\n \n std::string ext_command = clp->getExeCommand();\n if (ext_command != \"\") {\n std::string directory = symbolTable->getSymbol(clp->getFullCompileDir());\n std::string fileList = directory + \"\/file.lst\";\n std::string command = ext_command + \" \" + fileList;\n int result = system(command.c_str());\n codedReturn |= result;\n std::cout << \"Command result: \" << result << std::endl;\n }\n clp->logFooter();\n if (diff_comp_mode && fileunit) \n {\n SURELOG::Report* report = new SURELOG::Report();\n std::pair<bool, bool> results = report->makeDiffCompUnitReport(clp, symbolTable );\n success = results.first;\n noFatalErrors = results.second; \n delete report;\n }\n delete clp;\n delete symbolTable;\n delete errors;\n if ((!noFatalErrors) || (!success))\n codedReturn |= 1;\n if (parseOnly)\n return 0;\n else \n return codedReturn; \n}\ntypedef enum {\n NORMAL,\n DIFF,\n BATCH \n} COMP_MODE;\n\nint batchCompilation(const char* argv0, std::string batchFile)\n{\n char path [10000];\n int returnCode = 0;\n SURELOG::ErrorContainer::Stats overallStats;\n char* p = getcwd(path, 9999);\n if (!p)\n returnCode |= 1;\n std::ifstream stream;\n stream.open(batchFile);\n if (!stream.good()) {\n returnCode |= 1;\n return returnCode;\n }\n std::string line;\n int count = 0;\n while (std::getline(stream, line)) {\n std::cout << \"Processing: \" << line << std::endl << std::flush;\n std::vector<std::string> args;\n SURELOG::StringUtils::tokenize(line, \" \", args);\n int argc = args.size() + 1;\n char** argv = new char*[argc];\n argv[0] = new char [strlen(argv0) + 1];\n strcpy(argv[0], argv0);\n for (int i = 0; i < argc-1; i++) {\n argv[i+1] = new char [args[i].length() + 1];\n strcpy(argv[i+1], args[i].c_str());\n }\n returnCode |= executeCompilation(argc, (const char**) argv, false, false, &overallStats);\n for (int i = 0; i < argc; i++) {\n delete [] argv[i];\n }\n delete [] argv;\n count++;\n int ret = chdir(path);\n if (ret < 0) {\n std::cout << \"Could not change directory to \" << path << \"\\n\" << std::endl;\n returnCode |= 1;\n } \n }\n std::cout << \"Processed \" << count << \" tests.\" << std::endl << std::flush;\n SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();\n SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);\n errors->printStats (overallStats);\n delete errors;\n delete symbolTable;\n stream.close();\n return returnCode;\n}\n\nint main(int argc, const char ** argv) {\n SURELOG::Waiver::initWaivers();\n\n unsigned int codedReturn = 0;\n COMP_MODE mode = NORMAL;\n bool python_mode = true;\n \n std::string batchFile;\n std::string diff_unit_opt = \"-diffcompunit\";\n std::string nopython_opt = \"-nopython\";\n std::string parseonly_opt = \"-parseonly\";\n std::string batch_opt = \"-batch\";\n for (int i = 1; i < argc; i++) {\n if (parseonly_opt == argv[i]) {\n int ret = chdir(\"..\");\n if (ret < 0) {\n std::cout << \"Could not change directory to ..\/\\n\" << std::endl;\n }\n } else if (diff_unit_opt == argv[i]) {\n mode = DIFF;\n } else if (nopython_opt == argv[i]) {\n python_mode = false;\n } else if (batch_opt == argv[i]) {\n batchFile = argv[i+1];\n i++;\n mode = BATCH;\n }\n }\n\n if (python_mode)\n SURELOG::PythonAPI::init(argc, argv);\n\n switch (mode) {\n case DIFF:\n {\n pid_t pid = fork();\n if (pid == 0) {\n \/\/ child process\n executeCompilation(argc, argv, true, false);\n } else if (pid > 0) {\n \/\/ parent process\n codedReturn = executeCompilation(argc, argv, true, true);\n } else {\n \/\/ fork failed\n printf(\"fork() failed!\\n\");\n return 1;\n }\n break;\n }\n case NORMAL:\n codedReturn = executeCompilation(argc, argv, false, false);\n break;\n case BATCH:\n codedReturn = batchCompilation(argv[0], batchFile);\n break;\n }\n\n if (python_mode)\n SURELOG::PythonAPI::shutdown();\n return codedReturn;\n}\n\n\n<commit_msg>Only return non-zero for fatal and syntax errors<commit_after>\/*\n Copyright 2019 Alain Dargelas\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/* \n * File: main.cpp\n * Author: alain\n *\n * Created on January 15, 2017, 12:15 AM\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <sys\/stat.h>\n#include <sys\/param.h>\n#include <unistd.h>\n#include <fstream>\n\n#include \"surelog.h\"\n#include \"ErrorReporting\/Report.h\"\n#include \"API\/PythonAPI.h\"\n#include \"Utils\/StringUtils.h\"\n\nunsigned int executeCompilation(int argc, const char ** argv, bool diff_comp_mode, \n bool fileunit, SURELOG::ErrorContainer::Stats* overallStats = NULL)\n{\n bool success = true;\n bool noFatalErrors = true;\n unsigned int codedReturn = 0;\n SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();\n SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);\n SURELOG::CommandLineParser* clp = new SURELOG::CommandLineParser (errors, symbolTable, diff_comp_mode, fileunit);\n success = clp->parseCommandLine (argc, argv);\n bool parseOnly = clp->parseOnly();\n errors->printMessages (clp->muteStdout ());\n if (success && (!clp->help()))\n {\n SURELOG::scompiler* compiler = SURELOG::start_compiler(clp); \n if (!compiler)\n codedReturn |= 1;\n SURELOG::shutdown_compiler(compiler);\n }\n SURELOG::ErrorContainer::Stats stats;\n if (!clp->help()) {\n stats = errors->getErrorStats ();\n if (overallStats)\n (*overallStats) += stats;\n if (stats.nbFatal)\n codedReturn |= 1;\n if (stats.nbSyntax)\n codedReturn |= 2;\n \/\/ Only return non-zero for fatal and syntax errors\n \/\/if (stats.nbError)\n \/\/ codedReturn |= 4;\n }\n bool noFErrors = true;\n if (!clp->help())\n noFErrors = errors->printStats (stats,clp->muteStdout ());\n if (noFErrors == false) {\n noFatalErrors = false;\n }\n \n std::string ext_command = clp->getExeCommand();\n if (ext_command != \"\") {\n std::string directory = symbolTable->getSymbol(clp->getFullCompileDir());\n std::string fileList = directory + \"\/file.lst\";\n std::string command = ext_command + \" \" + fileList;\n int result = system(command.c_str());\n codedReturn |= result;\n std::cout << \"Command result: \" << result << std::endl;\n }\n clp->logFooter();\n if (diff_comp_mode && fileunit) \n {\n SURELOG::Report* report = new SURELOG::Report();\n std::pair<bool, bool> results = report->makeDiffCompUnitReport(clp, symbolTable );\n success = results.first;\n noFatalErrors = results.second; \n delete report;\n }\n delete clp;\n delete symbolTable;\n delete errors;\n if ((!noFatalErrors) || (!success))\n codedReturn |= 1;\n if (parseOnly)\n return 0;\n else \n return codedReturn; \n}\ntypedef enum {\n NORMAL,\n DIFF,\n BATCH \n} COMP_MODE;\n\nint batchCompilation(const char* argv0, std::string batchFile)\n{\n char path [10000];\n int returnCode = 0;\n SURELOG::ErrorContainer::Stats overallStats;\n char* p = getcwd(path, 9999);\n if (!p)\n returnCode |= 1;\n std::ifstream stream;\n stream.open(batchFile);\n if (!stream.good()) {\n returnCode |= 1;\n return returnCode;\n }\n std::string line;\n int count = 0;\n while (std::getline(stream, line)) {\n std::cout << \"Processing: \" << line << std::endl << std::flush;\n std::vector<std::string> args;\n SURELOG::StringUtils::tokenize(line, \" \", args);\n int argc = args.size() + 1;\n char** argv = new char*[argc];\n argv[0] = new char [strlen(argv0) + 1];\n strcpy(argv[0], argv0);\n for (int i = 0; i < argc-1; i++) {\n argv[i+1] = new char [args[i].length() + 1];\n strcpy(argv[i+1], args[i].c_str());\n }\n returnCode |= executeCompilation(argc, (const char**) argv, false, false, &overallStats);\n for (int i = 0; i < argc; i++) {\n delete [] argv[i];\n }\n delete [] argv;\n count++;\n int ret = chdir(path);\n if (ret < 0) {\n std::cout << \"Could not change directory to \" << path << \"\\n\" << std::endl;\n returnCode |= 1;\n } \n }\n std::cout << \"Processed \" << count << \" tests.\" << std::endl << std::flush;\n SURELOG::SymbolTable* symbolTable = new SURELOG::SymbolTable ();\n SURELOG::ErrorContainer* errors = new SURELOG::ErrorContainer (symbolTable);\n errors->printStats (overallStats);\n delete errors;\n delete symbolTable;\n stream.close();\n return returnCode;\n}\n\nint main(int argc, const char ** argv) {\n SURELOG::Waiver::initWaivers();\n\n unsigned int codedReturn = 0;\n COMP_MODE mode = NORMAL;\n bool python_mode = true;\n \n std::string batchFile;\n std::string diff_unit_opt = \"-diffcompunit\";\n std::string nopython_opt = \"-nopython\";\n std::string parseonly_opt = \"-parseonly\";\n std::string batch_opt = \"-batch\";\n for (int i = 1; i < argc; i++) {\n if (parseonly_opt == argv[i]) {\n int ret = chdir(\"..\");\n if (ret < 0) {\n std::cout << \"Could not change directory to ..\/\\n\" << std::endl;\n }\n } else if (diff_unit_opt == argv[i]) {\n mode = DIFF;\n } else if (nopython_opt == argv[i]) {\n python_mode = false;\n } else if (batch_opt == argv[i]) {\n batchFile = argv[i+1];\n i++;\n mode = BATCH;\n }\n }\n\n if (python_mode)\n SURELOG::PythonAPI::init(argc, argv);\n\n switch (mode) {\n case DIFF:\n {\n pid_t pid = fork();\n if (pid == 0) {\n \/\/ child process\n executeCompilation(argc, argv, true, false);\n } else if (pid > 0) {\n \/\/ parent process\n codedReturn = executeCompilation(argc, argv, true, true);\n } else {\n \/\/ fork failed\n printf(\"fork() failed!\\n\");\n return 1;\n }\n break;\n }\n case NORMAL:\n codedReturn = executeCompilation(argc, argv, false, false);\n break;\n case BATCH:\n codedReturn = batchCompilation(argv[0], batchFile);\n break;\n }\n\n if (python_mode)\n SURELOG::PythonAPI::shutdown();\n return codedReturn;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * PartsBasedDetectorOnVideo\n *\n * Huge chuncks of code shamelessly taken from Hilton Bristow's demo for\n * PartsBasedDetector.\n *\n *\n * File: main.cpp\n * Author: Mirko Raca\n * Created: November 5, 2013\n *\n *\/\n\n#include <glog\/logging.h>\n#include <boost\/filesystem.hpp>\n\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include \"PartsBasedDetector.hpp\"\n#include \"Candidate.hpp\"\n#include \"FileStorageModel.hpp\"\n\n#define WITH_MATLABIO\n#ifdef WITH_MATLABIO\n #include \"MatlabIOModel.hpp\"\n#endif\n\nusing namespace cv;\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n google::InitGoogleLogging(argv[0]);\n DLOG(INFO) << \"Execution started\";\n if (argc != 5) {\n printf(\"Usage: PartsBasedDetectorOnVideo model_file video_file output_folder\\n\");\n exit(-1);\n }\n\n \/\/ determine the type of model to read\n boost::scoped_ptr<Model> model;\n string ext = boost::filesystem::path(argv[1]).extension().string();\n if (ext.compare(\".xml\") == 0 || ext.compare(\".yaml\") == 0) {\n model.reset(new FileStorageModel);\n }\n#ifdef WITH_MATLABIO\n else if (ext.compare(\".mat\") == 0) {\n model.reset(new MatlabIOModel);\n }\n#endif\n else {\n printf(\"Unsupported model format: %s\\n\", ext.c_str());\n LOG(FATAL) << \"Unsupported model format: \" << ext.c_str();\n exit(-2);\n }\n bool ok = model->deserialize(argv[1]);\n if (!ok) {\n printf(\"Error deserializing file\\n\");\n LOG(FATAL) << \"Error deserializing file.\";\n exit(-3);\n }\n\n \/\/ create the PartsBasedDetector and distribute the model parameters\n Mat_<float> depth; \/\/ we don't have one for the video, so it's just a dummy variable\n PartsBasedDetector<float> pbd;\n pbd.distributeModel(*model);\n\n \/\/ load video sequence\n VideoCapture videoSrc((string)argv[2]);\n if( !videoSrc.isOpened() ){\n printf(\"Could not read video file\\n\");\n LOG(FATAL) << \"Could not read video file: \" << argv[2];\n exit(-4);\n }\n double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT);\n\n \/\/ main loop\n \/\/ detect potential candidates in the image\n DLOG(INFO) << \"main loop\";\n vector<Candidate> candidates;\n Mat curFrameIm;\n while(1){\n candidates.clear();\n videoSrc >> curFrameIm;\n pbd.detect(curFrameIm, depth, candidates);\n }\n\n \/\/ cleanup\n DLOG(INFO) << \"Cleanup part\";\n videoSrc.release();\n\n DLOG(INFO) << \"Execution finished\";\n return 0;\n}\n<commit_msg>w.i.p.<commit_after>\/**\n * PartsBasedDetectorOnVideo\n *\n * Huge chunks of code shamelessly taken from Hilton Bristow's demo for\n * PartsBasedDetector.\n *\n *\n * File: main.cpp\n * Author: Mirko Raca\n * Created: November 5, 2013\n *\n *\/\n\n#include <glog\/logging.h>\n#include <boost\/filesystem.hpp>\n#include <stdio.h>\n\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include \"PartsBasedDetector.hpp\"\n#include \"Candidate.hpp\"\n#include \"FileStorageModel.hpp\"\n\n#define WITH_MATLABIO\n#ifdef WITH_MATLABIO\n #include \"MatlabIOModel.hpp\"\n#endif\n\nusing namespace cv;\nusing namespace std;\n\n#define OUTPUT_FILENAME_FORMAT \"detection_frame%06d.txt\"\n\nint main(int argc, char *argv[])\n{\n google::InitGoogleLogging(argv[0]);\n DLOG(INFO) << \"Execution started\";\n if (argc != 5) {\n printf(\"Usage: PartsBasedDetectorOnVideo model_file video_file output_folder\\n\");\n exit(-1);\n }\n\n \/\/ determine the type of model to read\n boost::scoped_ptr<Model> model;\n string ext = boost::filesystem::path(argv[1]).extension().string();\n if (ext.compare(\".xml\") == 0 || ext.compare(\".yaml\") == 0) {\n model.reset(new FileStorageModel);\n }\n#ifdef WITH_MATLABIO\n else if (ext.compare(\".mat\") == 0) {\n model.reset(new MatlabIOModel);\n }\n#endif\n else {\n printf(\"Unsupported model format: %s\\n\", ext.c_str());\n LOG(FATAL) << \"Unsupported model format: \" << ext.c_str();\n exit(-2);\n }\n bool ok = model->deserialize(argv[1]);\n if (!ok) {\n printf(\"Error deserializing file\\n\");\n LOG(FATAL) << \"Error deserializing file.\";\n exit(-3);\n }\n\n \/\/ TODO: check\n \/\/ check output folder\n string outputFilePattern = (string) argv[3];\n if( outputFilePattern[outputFilePattern.length()-1] != '\/' ){\n outputFilePattern.append(\"\/\");\n }\n outputFilePattern.append(OUTPUT_FILENAME_FORMAT);\n\n \/\/ create the PartsBasedDetector and distribute the model parameters\n Mat_<float> depth; \/\/ we don't have one for the video, so it's just a dummy variable\n PartsBasedDetector<float> pbd;\n pbd.distributeModel(*model);\n\n \/\/ load video sequence\n VideoCapture videoSrc((string)argv[2]);\n if( !videoSrc.isOpened() ){\n printf(\"Could not read video file\\n\");\n LOG(FATAL) << \"Could not read video file: \" << argv[2];\n exit(-4);\n }\n double frameCount = videoSrc.get(CV_CAP_PROP_FRAME_COUNT);\n double frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES);\n DLOG(INFO) << \"Frame count: \" << frameCount;\n DLOG(INFO) << \"Start frame no: \" << frameNo;\n\n \/\/ main loop\n DLOG(INFO) << \"main loop\";\n vector<Candidate> candidates;\n Mat curFrameIm;\n char outputFilenameBuffer[1024];\n while(frameNo < frameCount){\n candidates.clear();\n videoSrc >> curFrameIm;\n frameNo = videoSrc.get(CV_CAP_PROP_POS_FRAMES);\n pbd.detect(curFrameIm, depth, candidates);\n \/\/ TODO: non-maximum suppression here\n\n sprintf(outputFilenameBuffer, outputFilePattern.c_str(), frameNo);\n \/\/ TODO: output part here\n \/\/ cleanup\n if(!curFrameIm.empty())\n curFrameIm.release();\n }\n\n \/\/ cleanup\n DLOG(INFO) << \"Cleanup part\";\n videoSrc.release();\n\n DLOG(INFO) << \"Execution finished\";\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"libaps.h\"\n#include \"constants.h\"\n#include <thread>\n\nusing namespace std;\n\nint main ()\n{\n cout << \"BBN X6-1000 Test Executable\" << endl;\n\n set_logging_level(5);\n\n int numDevices;\n numDevices = get_numDevices();\n\n cout << numDevices << \" X6 device\" << (numDevices > 1 ? \"s\": \"\") << \" found\" << endl;\n\n if (numDevices < 1)\n \treturn 0;\n\n char s[] = \"stdout\";\n set_log(s);\n\n cout << \"Attempting to initialize libaps\" << endl;\n\n init();\n\n char serialBuffer[100];\n\n for (int cnt; cnt < numDevices; cnt++) {\n \tget_deviceSerial(cnt, serialBuffer);\n \tcout << \"Device \" << cnt << \" serial #: \" << serialBuffer << endl;\n }\n\n int rc;\n rc = connect_by_ID(0);\n\n cout << \"connect_by_ID(0) returned \" << rc << endl;\n\n cout << \"current logic temperature = \" << get_logic_temperature(0) << endl;\n\n cout << \"current PLL frequency = \" << get_sampleRate(0) << \" MHz\" << endl;\n\n cout << \"setting trigger source = EXTERNAL\" << endl;\n\n set_trigger_source(0, EXTERNAL);\n\n cout << \"get trigger source returns \" << ((get_trigger_source(0) == INTERNAL) ? \"INTERNAL\" : \"EXTERNAL\") << endl;\n\n cout << \"setting trigger source = INTERNAL\" << endl;\n\n set_trigger_source(0, INTERNAL);\n\n cout << \"get trigger source returns \" << ((get_trigger_source(0) == INTERNAL) ? \"INTERNAL\" : \"EXTERNAL\") << endl;\n\n cout << \"get channel(0) enable: \" << get_channel_enabled(0,0) << endl;\n\n cout << \"set channel(0) enabled = 1\" << endl;\n\n set_channel_enabled(0,0,true);\n\n#if 0\n\n cout << \"enable ramp output\" << endl;\n \n enable_test_generator(0,0,0.001);\n\n std::this_thread::sleep_for(std::chrono::seconds(5));\n\n\n cout << \"enable sine wave output\" << endl;\n\n disable_test_generator(0);\n enable_test_generator(0,1,0.001);\n\n std::this_thread::sleep_for(std::chrono::seconds(5));\n\n cout << \"disabling channel\" << endl;\n disable_test_generator(0);\n\n#else\n\n\n const int wfs = 10000;\n short wf[wfs];\n for (int cnt = 0; cnt < wfs; cnt++)\n wf[cnt] = (cnt < wfs\/2) ? 32767 : -32767;\n\n set_waveform_int(0, 0, wf, wfs);\n\n cout << \"Running\" << endl;\n\n run(0);\n\n std::this_thread::sleep_for(std::chrono::seconds(10));\n\n cout << \"Stopping\" << endl;\n\n stop(0);\n\n std::this_thread::sleep_for(std::chrono::seconds(1));\n#endif\n\n set_channel_enabled(0,0,false);\n\n cout << \"get channel(0) enable: \" << get_channel_enabled(0,0) << endl;\n\n rc = disconnect_by_ID(0);\n\n cout << \"disconnect_by_ID(0) returned \" << rc << endl;\n\n return 0;\n}<commit_msg>Enabled generator tests in main test<commit_after>#include <iostream>\n\n#include \"libaps.h\"\n#include \"constants.h\"\n#include <thread>\n\nusing namespace std;\n\nint main ()\n{\n cout << \"BBN X6-1000 Test Executable\" << endl;\n\n set_logging_level(5);\n\n int numDevices;\n numDevices = get_numDevices();\n\n cout << numDevices << \" X6 device\" << (numDevices > 1 ? \"s\": \"\") << \" found\" << endl;\n\n if (numDevices < 1)\n \treturn 0;\n\n char s[] = \"stdout\";\n set_log(s);\n\n cout << \"Attempting to initialize libaps\" << endl;\n\n init();\n\n char serialBuffer[100];\n\n for (int cnt; cnt < numDevices; cnt++) {\n \tget_deviceSerial(cnt, serialBuffer);\n \tcout << \"Device \" << cnt << \" serial #: \" << serialBuffer << endl;\n }\n\n int rc;\n rc = connect_by_ID(0);\n\n cout << \"connect_by_ID(0) returned \" << rc << endl;\n\n cout << \"current logic temperature = \" << get_logic_temperature(0) << endl;\n\n cout << \"current PLL frequency = \" << get_sampleRate(0) << \" MHz\" << endl;\n\n cout << \"setting trigger source = EXTERNAL\" << endl;\n\n set_trigger_source(0, EXTERNAL);\n\n cout << \"get trigger source returns \" << ((get_trigger_source(0) == INTERNAL) ? \"INTERNAL\" : \"EXTERNAL\") << endl;\n\n cout << \"setting trigger source = INTERNAL\" << endl;\n\n set_trigger_source(0, INTERNAL);\n\n cout << \"get trigger source returns \" << ((get_trigger_source(0) == INTERNAL) ? \"INTERNAL\" : \"EXTERNAL\") << endl;\n\n cout << \"get channel(0) enable: \" << get_channel_enabled(0,0) << endl;\n\n cout << \"set channel(0) enabled = 1\" << endl;\n\n set_channel_enabled(0,0,true);\n\n\n\n cout << \"enable ramp output\" << endl;\n \n enable_test_generator(0,0,0.001);\n\n std::this_thread::sleep_for(std::chrono::seconds(5));\n\n\n cout << \"enable sine wave output\" << endl;\n\n disable_test_generator(0);\n enable_test_generator(0,1,0.001);\n\n std::this_thread::sleep_for(std::chrono::seconds(5));\n\n cout << \"disabling test generator\" << endl;\n disable_test_generator(0);\n\n\n const int wfs = 10000;\n short wf[wfs];\n for (int cnt = 0; cnt < wfs; cnt++)\n wf[cnt] = (cnt < wfs\/2) ? 32767 : -32767;\n\n cout << \"loading waveform\" << endl;\n\n set_waveform_int(0, 0, wf, wfs);\n\n cout << \"Running\" << endl;\n\n run(0);\n\n std::this_thread::sleep_for(std::chrono::seconds(10));\n\n cout << \"Stopping\" << endl;\n\n stop(0);\n\n set_channel_enabled(0,0,false);\n\n cout << \"get channel(0) enable: \" << get_channel_enabled(0,0) << endl;\n\n rc = disconnect_by_ID(0);\n\n cout << \"disconnect_by_ID(0) returned \" << rc << endl;\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\nstatic void error_callback(int error, const char* description)\n{\n fputs(description, stderr);\n}\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GL_TRUE);\n}\nint main(int argc, const char ** argv)\n{\n \n \n GLFWwindow* window;\n glfwSetErrorCallback(error_callback);\n if (!glfwInit())\n exit(EXIT_FAILURE);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n window = glfwCreateWindow(640, 480, \"Edit Academy 3D\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n glfwMakeContextCurrent(window);\n glfwSetKeyCallback(window, key_callback);\n \n\/\/ glewInit();\n cout<< glGetString(GL_VERSION)<<endl;\n glClear(GL_COLOR_BUFFER_BIT);\n while (!glfwWindowShouldClose(window))\n {\n float ratio;\n int width, height;\n glfwGetFramebufferSize(window, &width, &height);\n ratio = width \/ (float) height;\n glViewport(0, 0, width, height);\n \n \/\/\tglMatrixMode(GL_PROJECTION);\n \/\/\tglLoadIdentity();\n \/\/\tglOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);\n \/\/\tglMatrixMode(GL_MODELVIEW);\n \/\/\tglLoadIdentity();\n \/\/\tglRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);\n \/\/\tglBegin(GL_TRIANGLES);\n \/\/\tglColor3f(1.f, 0.f, 0.f);\n \/\/\tglVertex3f(-0.6f, -0.4f, 0.f);\n \/\/\tglColor3f(0.f, 1.f, 0.f);\n \/\/\tglVertex3f(0.6f, -0.4f, 0.f);\n \/\/\tglColor3f(0.f, 0.f, 1.f);\n \/\/\tglVertex3f(0.f, 0.6f, 0.f);\n \/\/\tglEnd();\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<commit_msg>skip glew<commit_after>\n#include <GLFW\/glfw3.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\nstatic void error_callback(int error, const char* description)\n{\n fputs(description, stderr);\n}\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n glfwSetWindowShouldClose(window, GL_TRUE);\n}\nint main(int argc, const char ** argv)\n{\n \n \n GLFWwindow* window;\n glfwSetErrorCallback(error_callback);\n if (!glfwInit())\n exit(EXIT_FAILURE);\n\/\/ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n\/\/ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\/\/ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\/\/ glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n window = glfwCreateWindow(640, 480, \"Edit Academy 3D\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n glfwMakeContextCurrent(window);\n glfwSetKeyCallback(window, key_callback);\n \n\/\/ cout<< glGetString(GL_VERSION)<<endl;\n\/\/\n while (!glfwWindowShouldClose(window))\n {\n float ratio;\n int width, height;\n glfwGetFramebufferSize(window, &width, &height);\n ratio = width \/ (float) height;\n glViewport(0, 0, width, height);\n glClear(GL_COLOR_BUFFER_BIT);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);\n glMatrixMode(GL_MODELVIEW);\n \n \n glLoadIdentity();\n glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);\n glBegin(GL_TRIANGLES);\n glColor3f(1.f, 0.f, 0.f);\n glVertex3f(-0.6f, -0.4f, 0.f);\n glColor3f(0.f, 1.f, 0.f);\n glVertex3f(0.6f, -0.4f, 0.f);\n glColor3f(0.f, 0.f, 1.f);\n glVertex3f(0.f, 0.6f, 0.f);\n glEnd();\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n glfwDestroyWindow(window);\n glfwTerminate();\n exit(EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if defined(BROWSER_SYNC)\n\n#include \"chrome\/test\/live_sync\/bookmark_model_verifier.h\"\n\n#include <vector>\n#include <stack>\n\n#include \"app\/tree_node_iterator.h\"\n#include \"base\/rand_util.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_utils.h\"\n#include \"chrome\/test\/live_sync\/live_bookmarks_sync_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\n\/\/ static\nvoid BookmarkModelVerifier::ExpectBookmarkInfoMatch(\n const BookmarkNode* expected, const BookmarkNode* actual) {\n EXPECT_EQ(expected->GetTitle(), actual->GetTitle());\n EXPECT_EQ(expected->is_folder(), actual->is_folder());\n EXPECT_EQ(expected->GetURL(), actual->GetURL());\n EXPECT_EQ(expected->GetParent()->IndexOfChild(expected),\n actual->GetParent()->IndexOfChild(actual));\n}\n\nBookmarkModelVerifier::BookmarkModelVerifier() {\n verifier_profile_.reset(LiveBookmarksSyncTest::MakeProfile(L\"verifier\"));\n verifier_ = verifier_profile_->GetBookmarkModel();\n}\n\nBookmarkModelVerifier* BookmarkModelVerifier::Create() {\n BookmarkModelVerifier* v = new BookmarkModelVerifier();\n LiveBookmarksSyncTest::BlockUntilLoaded(v->verifier_);\n return v;\n}\n\nvoid BookmarkModelVerifier::ExpectMatch(BookmarkModel* actual) {\n ExpectModelsMatch(verifier_, actual);\n}\n\n\/\/ static\nvoid BookmarkModelVerifier::ExpectModelsMatchIncludingFavicon(\n BookmarkModel* expected, BookmarkModel* actual, bool compare_favicon) {\n TreeNodeIterator<const BookmarkNode> e_iterator(expected->root_node());\n TreeNodeIterator<const BookmarkNode> a_iterator(actual->root_node());\n\n \/\/ Pre-order traversal of each model, comparing at each step.\n while (e_iterator.has_next()) {\n const BookmarkNode* e_node = e_iterator.Next();\n ASSERT_TRUE(a_iterator.has_next());\n const BookmarkNode* a_node = a_iterator.Next();\n ExpectBookmarkInfoMatch(e_node, a_node);\n \/\/ Get Favicon and compare if compare_favicon flag is true.\n if (compare_favicon) {\n const SkBitmap& e_node_favicon = expected->GetFavIcon(e_node);\n const SkBitmap& a_node_favicon = actual->GetFavIcon(a_node);\n EXPECT_GT(e_node_favicon.getSize(), (size_t) 0);\n EXPECT_EQ(e_node_favicon.getSize(), a_node_favicon.getSize());\n EXPECT_EQ(e_node_favicon.width(), a_node_favicon.width());\n EXPECT_EQ(e_node_favicon.height(), a_node_favicon.height());\n SkAutoLockPixels bitmap_lock_e(e_node_favicon);\n SkAutoLockPixels bitmap_lock_a(a_node_favicon);\n void* e_node_pixel_addr = e_node_favicon.getPixels();\n ASSERT_TRUE(e_node_pixel_addr);\n void* a_node_pixel_addr = a_node_favicon.getPixels();\n ASSERT_TRUE(a_node_pixel_addr);\n EXPECT_EQ(memcmp(e_node_pixel_addr, a_node_pixel_addr,\n e_node_favicon.getSize()), 0);\n }\n }\n ASSERT_FALSE(a_iterator.has_next());\n}\n\nvoid BookmarkModelVerifier::VerifyNoDuplicates(BookmarkModel* model) {\n TreeNodeIterator<const BookmarkNode> iterator(model->root_node());\n \/\/ Pre-order traversal of model tree, looking for duplicate node at\n \/\/ each step.\n while (iterator.has_next()) {\n const BookmarkNode* node = iterator.Next();\n std::vector<const BookmarkNode*> nodes;\n if (node->type() != BookmarkNode::URL) { continue; }\n \/\/ Get nodes with same URL.\n model->GetNodesByURL(node->GetURL(),&nodes);\n EXPECT_TRUE(nodes.size()>=1);\n for(std::vector<const BookmarkNode*>::const_iterator i=nodes.begin(), e=nodes.end(); i!=e; i++) {\n \/\/ Skip if it's same node.\n int64 id = node->id();\n if ( id == (*i)->id()) { continue; }\n else {\n \/\/ Make sure title are not same.\n EXPECT_NE(node->GetTitle(),(*i)->GetTitle());\n }\n }\n } \/\/ end of while\n}\n\nvoid BookmarkModelVerifier::FindNodeInVerifier(BookmarkModel* foreign_model,\n const BookmarkNode* foreign_node,\n const BookmarkNode** result) {\n \/\/ Climb the tree.\n std::stack<int> path;\n const BookmarkNode* walker = foreign_node;\n while (walker != foreign_model->root_node()) {\n path.push(walker->GetParent()->IndexOfChild(walker));\n walker = walker->GetParent();\n }\n\n \/\/ Swing over to the other tree.\n walker = verifier_->root_node();\n\n \/\/ Climb down.\n while (!path.empty()) {\n ASSERT_TRUE(walker->is_folder());\n ASSERT_LT(path.top(), walker->GetChildCount());\n walker = walker->GetChild(path.top());\n path.pop();\n }\n\n ExpectBookmarkInfoMatch(foreign_node, walker);\n *result = walker;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddGroup(BookmarkModel* model,\n const BookmarkNode* parent, int index, const string16& title) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n const BookmarkNode* result = model->AddGroup(parent, index, title);\n EXPECT_TRUE(result);\n if (!result) return NULL;\n const BookmarkNode* v_node = verifier_->AddGroup(v_parent, index, title);\n EXPECT_TRUE(v_node);\n if (!v_node) return NULL;\n ExpectBookmarkInfoMatch(v_node, result);\n return result;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddNonEmptyGroup(\n BookmarkModel* model, const BookmarkNode* parent, int index,\n const string16& title, int children_count) {\n const BookmarkNode* bm_folder = AddGroup(model, parent, index, title);\n EXPECT_TRUE(bm_folder);\n if (!bm_folder) return NULL;\n for (int child_index = 0; child_index < children_count; child_index++) {\n int random_int = base::RandInt(1, 100);\n \/\/ To create randomness in order, 60% of time add bookmarks\n if (random_int > 40) {\n string16 child_bm_title(bm_folder->GetTitle());\n child_bm_title.append(L\"-ChildBM\");\n string16 url(L\"http:\/\/www.nofaviconurl\");\n string16 index_str = IntToString16(child_index);\n child_bm_title.append(index_str);\n url.append(index_str);\n url.append(L\".com\");\n const BookmarkNode* child_nofavicon_bm =\n AddURL(model, bm_folder, child_index, child_bm_title, GURL(url));\n } else {\n \/\/ Remaining % of time - Add Bookmark folders\n string16 child_bmfolder_title(bm_folder->GetTitle());\n child_bmfolder_title.append(L\"-ChildBMFolder\");\n string16 index_str = IntToString16(child_index);\n child_bmfolder_title.append(index_str);\n const BookmarkNode* child_bm_folder =\n AddGroup(model, bm_folder, child_index, child_bmfolder_title);\n }\n }\n return bm_folder;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddURL(BookmarkModel* model,\n const BookmarkNode* parent, int index, const string16& title,\n const GURL& url) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n const BookmarkNode* result = model->AddURL(parent, index, title, url);\n EXPECT_TRUE(result);\n if (!result) return NULL;\n const BookmarkNode* v_node = verifier_->AddURL(v_parent, index, title, url);\n EXPECT_TRUE(v_node);\n if (!v_node) return NULL;\n ExpectBookmarkInfoMatch(v_node, result);\n return result;\n}\n\nvoid BookmarkModelVerifier::SetTitle(BookmarkModel* model,\n const BookmarkNode* node,\n const string16& title) {\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, node, &v_node);\n model->SetTitle(node, title);\n verifier_->SetTitle(v_node, title);\n}\n\nvoid BookmarkModelVerifier::Move(BookmarkModel* model, const BookmarkNode* node,\n const BookmarkNode* new_parent, int index) {\n const BookmarkNode* v_new_parent = NULL;\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, new_parent, &v_new_parent);\n FindNodeInVerifier(model, node, &v_node);\n model->Move(node, new_parent, index);\n verifier_->Move(v_node, v_new_parent, index);\n}\n\nvoid BookmarkModelVerifier::Remove(BookmarkModel* model,\n const BookmarkNode* parent,\n int index) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n ExpectBookmarkInfoMatch(parent->GetChild(index), v_parent->GetChild(index));\n model->Remove(parent, index);\n verifier_->Remove(v_parent, index);\n}\n\nvoid BookmarkModelVerifier::SortChildren(BookmarkModel* model,\n const BookmarkNode* parent) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n model->SortChildren(parent);\n verifier_->SortChildren(v_parent);\n}\n\nvoid BookmarkModelVerifier::ReverseChildOrder(BookmarkModel* model,\n const BookmarkNode* parent) {\n int child_count = parent->GetChildCount();\n if (child_count <= 0) return;\n for (int index = 0; index < child_count; index++) {\n Move(model, parent->GetChild(index), parent, child_count-index);\n }\n}\n\nconst BookmarkNode* BookmarkModelVerifier::SetURL(BookmarkModel* model,\n const BookmarkNode* node,\n const GURL& new_url) {\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, node, &v_node);\n const BookmarkNode* result = bookmark_utils::ApplyEditsWithNoGroupChange(\n model, node->GetParent(), BookmarkEditor::EditDetails(node),\n node->GetTitle(), new_url, NULL);\n bookmark_utils::ApplyEditsWithNoGroupChange(verifier_, v_node->GetParent(),\n BookmarkEditor::EditDetails(v_node), v_node->GetTitle(), new_url, NULL);\n return result;\n}\n\n#endif \/\/ defined(BROWSER_SYNC)\n<commit_msg>Fix style issues in BookmarkModelVerifier class.<commit_after>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if defined(BROWSER_SYNC)\n\n#include \"chrome\/test\/live_sync\/bookmark_model_verifier.h\"\n\n#include <vector>\n#include <stack>\n\n#include \"app\/tree_node_iterator.h\"\n#include \"base\/rand_util.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_utils.h\"\n#include \"chrome\/test\/live_sync\/live_bookmarks_sync_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\n\/\/ static\nvoid BookmarkModelVerifier::ExpectBookmarkInfoMatch(\n const BookmarkNode* expected, const BookmarkNode* actual) {\n EXPECT_EQ(expected->GetTitle(), actual->GetTitle());\n EXPECT_EQ(expected->is_folder(), actual->is_folder());\n EXPECT_EQ(expected->GetURL(), actual->GetURL());\n EXPECT_EQ(expected->GetParent()->IndexOfChild(expected),\n actual->GetParent()->IndexOfChild(actual));\n}\n\nBookmarkModelVerifier::BookmarkModelVerifier() {\n verifier_profile_.reset(LiveBookmarksSyncTest::MakeProfile(L\"verifier\"));\n verifier_ = verifier_profile_->GetBookmarkModel();\n}\n\nBookmarkModelVerifier* BookmarkModelVerifier::Create() {\n BookmarkModelVerifier* v = new BookmarkModelVerifier();\n LiveBookmarksSyncTest::BlockUntilLoaded(v->verifier_);\n return v;\n}\n\nvoid BookmarkModelVerifier::ExpectMatch(BookmarkModel* actual) {\n ExpectModelsMatch(verifier_, actual);\n}\n\n\/\/ static\nvoid BookmarkModelVerifier::ExpectModelsMatchIncludingFavicon(\n BookmarkModel* expected, BookmarkModel* actual, bool compare_favicon) {\n TreeNodeIterator<const BookmarkNode> e_iterator(expected->root_node());\n TreeNodeIterator<const BookmarkNode> a_iterator(actual->root_node());\n\n \/\/ Pre-order traversal of each model, comparing at each step.\n while (e_iterator.has_next()) {\n const BookmarkNode* e_node = e_iterator.Next();\n ASSERT_TRUE(a_iterator.has_next());\n const BookmarkNode* a_node = a_iterator.Next();\n ExpectBookmarkInfoMatch(e_node, a_node);\n \/\/ Get Favicon and compare if compare_favicon flag is true.\n if (compare_favicon) {\n const SkBitmap& e_node_favicon = expected->GetFavIcon(e_node);\n const SkBitmap& a_node_favicon = actual->GetFavIcon(a_node);\n EXPECT_GT(e_node_favicon.getSize(), (size_t) 0);\n EXPECT_EQ(e_node_favicon.getSize(), a_node_favicon.getSize());\n EXPECT_EQ(e_node_favicon.width(), a_node_favicon.width());\n EXPECT_EQ(e_node_favicon.height(), a_node_favicon.height());\n SkAutoLockPixels bitmap_lock_e(e_node_favicon);\n SkAutoLockPixels bitmap_lock_a(a_node_favicon);\n void* e_node_pixel_addr = e_node_favicon.getPixels();\n ASSERT_TRUE(e_node_pixel_addr);\n void* a_node_pixel_addr = a_node_favicon.getPixels();\n ASSERT_TRUE(a_node_pixel_addr);\n EXPECT_EQ(memcmp(e_node_pixel_addr, a_node_pixel_addr,\n e_node_favicon.getSize()), 0);\n }\n }\n ASSERT_FALSE(a_iterator.has_next());\n}\n\nvoid BookmarkModelVerifier::VerifyNoDuplicates(BookmarkModel* model) {\n TreeNodeIterator<const BookmarkNode> iterator(model->root_node());\n \/\/ Pre-order traversal of model tree, looking for duplicate node at\n \/\/ each step.\n while (iterator.has_next()) {\n const BookmarkNode* node = iterator.Next();\n std::vector<const BookmarkNode*> nodes;\n if (node->type() != BookmarkNode::URL)\n continue;\n \/\/ Get nodes with same URL.\n model->GetNodesByURL(node->GetURL(), &nodes);\n EXPECT_TRUE(nodes.size() >= 1);\n for (std::vector<const BookmarkNode*>::const_iterator i = nodes.begin(),\n e = nodes.end(); i != e; i++) {\n \/\/ Skip if it's same node.\n int64 id = node->id();\n if (id == (*i)->id()) {\n continue;\n } else {\n \/\/ Make sure title are not same.\n EXPECT_NE(node->GetTitle(), (*i)->GetTitle());\n }\n }\n } \/\/ end of while\n}\n\nvoid BookmarkModelVerifier::FindNodeInVerifier(BookmarkModel* foreign_model,\n const BookmarkNode* foreign_node,\n const BookmarkNode** result) {\n \/\/ Climb the tree.\n std::stack<int> path;\n const BookmarkNode* walker = foreign_node;\n while (walker != foreign_model->root_node()) {\n path.push(walker->GetParent()->IndexOfChild(walker));\n walker = walker->GetParent();\n }\n\n \/\/ Swing over to the other tree.\n walker = verifier_->root_node();\n\n \/\/ Climb down.\n while (!path.empty()) {\n ASSERT_TRUE(walker->is_folder());\n ASSERT_LT(path.top(), walker->GetChildCount());\n walker = walker->GetChild(path.top());\n path.pop();\n }\n\n ExpectBookmarkInfoMatch(foreign_node, walker);\n *result = walker;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddGroup(BookmarkModel* model,\n const BookmarkNode* parent, int index, const string16& title) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n const BookmarkNode* result = model->AddGroup(parent, index, title);\n EXPECT_TRUE(result);\n if (!result)\n return NULL;\n const BookmarkNode* v_node = verifier_->AddGroup(v_parent, index, title);\n EXPECT_TRUE(v_node);\n if (!v_node)\n return NULL;\n ExpectBookmarkInfoMatch(v_node, result);\n return result;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddNonEmptyGroup(\n BookmarkModel* model, const BookmarkNode* parent, int index,\n const string16& title, int children_count) {\n const BookmarkNode* bm_folder = AddGroup(model, parent, index, title);\n EXPECT_TRUE(bm_folder);\n if (!bm_folder)\n return NULL;\n for (int child_index = 0; child_index < children_count; child_index++) {\n int random_int = base::RandInt(1, 100);\n \/\/ To create randomness in order, 60% of time add bookmarks\n if (random_int > 40) {\n string16 child_bm_title(bm_folder->GetTitle());\n child_bm_title.append(L\"-ChildBM\");\n string16 url(L\"http:\/\/www.nofaviconurl\");\n string16 index_str = IntToString16(child_index);\n child_bm_title.append(index_str);\n url.append(index_str);\n url.append(L\".com\");\n const BookmarkNode* child_nofavicon_bm =\n AddURL(model, bm_folder, child_index, child_bm_title, GURL(url));\n } else {\n \/\/ Remaining % of time - Add Bookmark folders\n string16 child_bmfolder_title(bm_folder->GetTitle());\n child_bmfolder_title.append(L\"-ChildBMFolder\");\n string16 index_str = IntToString16(child_index);\n child_bmfolder_title.append(index_str);\n const BookmarkNode* child_bm_folder =\n AddGroup(model, bm_folder, child_index, child_bmfolder_title);\n }\n }\n return bm_folder;\n}\n\nconst BookmarkNode* BookmarkModelVerifier::AddURL(BookmarkModel* model,\n const BookmarkNode* parent, int index, const string16& title,\n const GURL& url) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n const BookmarkNode* result = model->AddURL(parent, index, title, url);\n EXPECT_TRUE(result);\n if (!result)\n return NULL;\n const BookmarkNode* v_node = verifier_->AddURL(v_parent, index, title, url);\n EXPECT_TRUE(v_node);\n if (!v_node)\n return NULL;\n ExpectBookmarkInfoMatch(v_node, result);\n return result;\n}\n\nvoid BookmarkModelVerifier::SetTitle(BookmarkModel* model,\n const BookmarkNode* node,\n const string16& title) {\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, node, &v_node);\n model->SetTitle(node, title);\n verifier_->SetTitle(v_node, title);\n}\n\nvoid BookmarkModelVerifier::Move(BookmarkModel* model, const BookmarkNode* node,\n const BookmarkNode* new_parent, int index) {\n const BookmarkNode* v_new_parent = NULL;\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, new_parent, &v_new_parent);\n FindNodeInVerifier(model, node, &v_node);\n model->Move(node, new_parent, index);\n verifier_->Move(v_node, v_new_parent, index);\n}\n\nvoid BookmarkModelVerifier::Remove(BookmarkModel* model,\n const BookmarkNode* parent,\n int index) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n ExpectBookmarkInfoMatch(parent->GetChild(index), v_parent->GetChild(index));\n model->Remove(parent, index);\n verifier_->Remove(v_parent, index);\n}\n\nvoid BookmarkModelVerifier::SortChildren(BookmarkModel* model,\n const BookmarkNode* parent) {\n const BookmarkNode* v_parent = NULL;\n FindNodeInVerifier(model, parent, &v_parent);\n model->SortChildren(parent);\n verifier_->SortChildren(v_parent);\n}\n\nvoid BookmarkModelVerifier::ReverseChildOrder(BookmarkModel* model,\n const BookmarkNode* parent) {\n int child_count = parent->GetChildCount();\n if (child_count <= 0)\n return;\n for (int index = 0; index < child_count; index++)\n Move(model, parent->GetChild(index), parent, child_count-index);\n}\n\nconst BookmarkNode* BookmarkModelVerifier::SetURL(BookmarkModel* model,\n const BookmarkNode* node,\n const GURL& new_url) {\n const BookmarkNode* v_node = NULL;\n FindNodeInVerifier(model, node, &v_node);\n const BookmarkNode* result = bookmark_utils::ApplyEditsWithNoGroupChange(\n model, node->GetParent(), BookmarkEditor::EditDetails(node),\n node->GetTitle(), new_url, NULL);\n bookmark_utils::ApplyEditsWithNoGroupChange(verifier_, v_node->GetParent(),\n BookmarkEditor::EditDetails(v_node), v_node->GetTitle(), new_url, NULL);\n return result;\n}\n\n#endif \/\/ defined(BROWSER_SYNC)\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <unistd.h>\n#include <pwd.h>\n#include <sys\/types.h>\n#include <stdio.h>\n#include <errno.h>\n\nusing namespace std;\n\nint main() {\n string userinput = \"\";\n\tchar hostname[64];\n\tif(gethostname(hostname, sizeof hostname))\n\t\tperror(\"failed to obtain hostname\");\n\twhile(userinput != \"exit\") {\n\t\tcout << getlogin() << \"@\" << hostname << \"$ \";\n\t\tgetline(cin, userinput);\n\t}\n\treturn 0;\n}\n<commit_msg>changed perror<commit_after>#include <iostream>\n#include <unistd.h>\n#include <pwd.h>\n#include <sys\/types.h>\n#include <stdio.h>\n#include <errno.h>\n\nusing namespace std;\n\nint main() {\n string userinput = \"\";\n\tstring login;\n\tchar hostname[64];\n\tif(gethostname(hostname, sizeof hostname))\n\t\tperror(\"gethostname\");\n\twhile(userinput != \"exit\") {\n\t\tcout << getlogin() << \"@\" << hostname << \"$ \";\n\t\tgetline(cin, userinput);\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2015 WinT 3794 <http:\/\/wint3794.org>\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n\/\/=============================================================================\r\n\/\/ System includes\r\n\/\/=============================================================================\r\n\r\n#include <QObject>\r\n#include <QSpinBox>\r\n#include <QComboBox>\r\n#include <QCheckBox>\r\n#include <QTabWidget>\r\n#include <QPushButton>\r\n#include <QApplication>\r\n#include <QInputDialog>\r\n\r\n#include <qlogging.h>\r\n#include <QtMessageHandler>\r\n\r\n\/\/=============================================================================\r\n\/\/ Application includes\r\n\/\/=============================================================================\r\n\r\n#include \"Global\/Global.h\"\r\n#include \"Global\/Beeper.h\"\r\n#include \"Global\/AppTheme.h\"\r\n#include \"Global\/Settings.h\"\r\n#include \"Global\/Languages.h\"\r\n\r\n#include \"Updater\/Updater.h\"\r\n#include \"MainWindow\/MainWindow.h\"\r\n\r\n\/\/=============================================================================\r\n\/\/ Called when a widget is clicked\r\n\/\/=============================================================================\r\n\r\nvoid BEEP()\r\n{\r\n BEEPER()->beep (440, 100);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ Avoid logging Qt warnings about our UI hacks\r\n\/\/=============================================================================\r\n\r\nvoid messageHandler (QtMsgType type,\r\n const QMessageLogContext& context,\r\n const QString& msg)\r\n{\r\n QByteArray localMsg = msg.toLocal8Bit();\r\n\r\n switch (type)\r\n {\r\n case QtDebugMsg:\r\n fprintf (stderr,\r\n \"DEBUG: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n case QtInfoMsg:\r\n fprintf (stderr,\r\n \"INFO: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n case QtWarningMsg:\r\n break;\r\n case QtCriticalMsg:\r\n fprintf (stderr,\r\n \"CRITICAL: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n case QtFatalMsg:\r\n fprintf (stderr,\r\n \"FATAL: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n }\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ Main entry-point of the application\r\n\/\/=============================================================================\r\n\r\nint main (int argc, char* argv[])\r\n{\r\n qInstallMessageHandler (messageHandler);\r\n DS_LogMessage (kInfoLevel, \"Starting application....\");\r\n\r\n \/* Configure application information *\/\r\n QApplication app (argc, argv);\r\n app.setApplicationVersion (\"0.15\");\r\n app.setOrganizationName (\"WinT 3794\");\r\n app.setApplicationName (\"QDriverStation\");\r\n app.setOrganizationDomain (\"www.wint3794.org\");\r\n app.installTranslator (Languages::translator());\r\n\r\n \/* Create the main window and check for updates *\/\r\n app.setFont (Languages::appFont());\r\n Updater updater;\r\n MainWindow mainwindow;\r\n\r\n \/* Repeat this line to be sure that font is applied on everything *\/\r\n GLOBAL_INIT();\r\n AppTheme::init();\r\n app.setFont (Languages::appFont());\r\n\r\n \/* Avoid compilation warnings *\/\r\n Q_UNUSED (updater);\r\n Q_UNUSED (mainwindow);\r\n\r\n \/* Beep whenever a button or checkbox is clicked *\/\r\n foreach (QWidget* widget, app.allWidgets())\r\n {\r\n \/* Do the conversions *\/\r\n QSpinBox* spin = qobject_cast<QSpinBox*> (widget);\r\n QCheckBox* check = qobject_cast<QCheckBox*> (widget);\r\n QComboBox* combo = qobject_cast<QComboBox*> (widget);\r\n QTabWidget* tabwid = qobject_cast<QTabWidget*> (widget);\r\n QPushButton* button = qobject_cast<QPushButton*> (widget);\r\n\r\n \/* The widget is a spin box *\/\r\n if (spin != Q_NULLPTR)\r\n QObject::connect (spin,\r\n static_cast<void (QSpinBox::*) (int)\r\n > (&QSpinBox::valueChanged),\r\n BEEP);\r\n\r\n \/* The widget is a combo box *\/\r\n else if (combo != Q_NULLPTR)\r\n QObject::connect (combo,\r\n static_cast<void (QComboBox::*) (int)\r\n > (&QComboBox::currentIndexChanged),\r\n BEEP);\r\n\r\n \/* The widget is a check box *\/\r\n else if (check != Q_NULLPTR)\r\n QObject::connect (check, &QCheckBox::clicked, BEEP);\r\n\r\n \/* The widget is a tab widget *\/\r\n else if (tabwid != Q_NULLPTR)\r\n QObject::connect (tabwid, &QTabWidget::currentChanged, BEEP);\r\n\r\n \/* The widget is a button *\/\r\n else if (button != Q_NULLPTR)\r\n QObject::connect (button, &QPushButton::clicked, BEEP);\r\n }\r\n\r\n \/* Ask for team number on first launch *\/\r\n if (Settings::get (\"First launch\", true).toBool())\r\n {\r\n DS()->setTeamNumber (QInputDialog::getInt (Q_NULLPTR,\r\n QObject::tr (\"QDriverStation\"),\r\n QObject::tr (\"Please input your team number:\"),\r\n 0, 0, 9999, 1, 0,\r\n Qt::WindowStaysOnTopHint));\r\n Settings::set (\"First launch\", false);\r\n }\r\n\r\n return app.exec();\r\n}\r\n<commit_msg>Update main.cpp<commit_after>\/*\r\n * Copyright (c) 2015 WinT 3794 <http:\/\/wint3794.org>\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n\/\/=============================================================================\r\n\/\/ System includes\r\n\/\/=============================================================================\r\n\r\n#include <QObject>\r\n#include <QSpinBox>\r\n#include <QComboBox>\r\n#include <QCheckBox>\r\n#include <QTabWidget>\r\n#include <QPushButton>\r\n#include <QApplication>\r\n#include <QInputDialog>\r\n\r\n\/\/=============================================================================\r\n\/\/ Application includes\r\n\/\/=============================================================================\r\n\r\n#include \"Global\/Global.h\"\r\n#include \"Global\/Beeper.h\"\r\n#include \"Global\/AppTheme.h\"\r\n#include \"Global\/Settings.h\"\r\n#include \"Global\/Languages.h\"\r\n\r\n#include \"Updater\/Updater.h\"\r\n#include \"MainWindow\/MainWindow.h\"\r\n\r\n\/\/=============================================================================\r\n\/\/ Called when a widget is clicked\r\n\/\/=============================================================================\r\n\r\nvoid BEEP()\r\n{\r\n BEEPER()->beep (440, 100);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ Avoid logging Qt warnings about our UI hacks\r\n\/\/=============================================================================\r\n\r\nvoid messageHandler (QtMsgType type,\r\n const QMessageLogContext& context,\r\n const QString& msg)\r\n{\r\n QByteArray localMsg = msg.toLocal8Bit();\r\n\r\n switch (type)\r\n {\r\n case QtDebugMsg:\r\n fprintf (stderr,\r\n \"DEBUG: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n case QtWarningMsg:\r\n break;\r\n case QtCriticalMsg:\r\n fprintf (stderr,\r\n \"CRITICAL: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n case QtFatalMsg:\r\n fprintf (stderr,\r\n \"FATAL: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n default:\r\n fprintf (stderr,\r\n \"INFO: %s (%s:%u, %s)\\n\",\r\n localMsg.constData(),\r\n context.file,\r\n context.line,\r\n context.function);\r\n break;\r\n }\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ Main entry-point of the application\r\n\/\/=============================================================================\r\n\r\nint main (int argc, char* argv[])\r\n{\r\n qInstallMessageHandler (messageHandler);\r\n DS_LogMessage (kInfoLevel, \"Starting application....\");\r\n\r\n \/* Configure application information *\/\r\n QApplication app (argc, argv);\r\n app.setApplicationVersion (\"0.15\");\r\n app.setOrganizationName (\"WinT 3794\");\r\n app.setApplicationName (\"QDriverStation\");\r\n app.setOrganizationDomain (\"www.wint3794.org\");\r\n app.installTranslator (Languages::translator());\r\n\r\n \/* Create the main window and check for updates *\/\r\n app.setFont (Languages::appFont());\r\n Updater updater;\r\n MainWindow mainwindow;\r\n\r\n \/* Repeat this line to be sure that font is applied on everything *\/\r\n GLOBAL_INIT();\r\n AppTheme::init();\r\n app.setFont (Languages::appFont());\r\n\r\n \/* Avoid compilation warnings *\/\r\n Q_UNUSED (updater);\r\n Q_UNUSED (mainwindow);\r\n\r\n \/* Beep whenever a button or checkbox is clicked *\/\r\n foreach (QWidget* widget, app.allWidgets())\r\n {\r\n \/* Do the conversions *\/\r\n QSpinBox* spin = qobject_cast<QSpinBox*> (widget);\r\n QCheckBox* check = qobject_cast<QCheckBox*> (widget);\r\n QComboBox* combo = qobject_cast<QComboBox*> (widget);\r\n QTabWidget* tabwid = qobject_cast<QTabWidget*> (widget);\r\n QPushButton* button = qobject_cast<QPushButton*> (widget);\r\n\r\n \/* The widget is a spin box *\/\r\n if (spin != Q_NULLPTR)\r\n QObject::connect (spin,\r\n static_cast<void (QSpinBox::*) (int)\r\n > (&QSpinBox::valueChanged),\r\n BEEP);\r\n\r\n \/* The widget is a combo box *\/\r\n else if (combo != Q_NULLPTR)\r\n QObject::connect (combo,\r\n static_cast<void (QComboBox::*) (int)\r\n > (&QComboBox::currentIndexChanged),\r\n BEEP);\r\n\r\n \/* The widget is a check box *\/\r\n else if (check != Q_NULLPTR)\r\n QObject::connect (check, &QCheckBox::clicked, BEEP);\r\n\r\n \/* The widget is a tab widget *\/\r\n else if (tabwid != Q_NULLPTR)\r\n QObject::connect (tabwid, &QTabWidget::currentChanged, BEEP);\r\n\r\n \/* The widget is a button *\/\r\n else if (button != Q_NULLPTR)\r\n QObject::connect (button, &QPushButton::clicked, BEEP);\r\n }\r\n\r\n \/* Ask for team number on first launch *\/\r\n if (Settings::get (\"First launch\", true).toBool())\r\n {\r\n DS()->setTeamNumber (QInputDialog::getInt (Q_NULLPTR,\r\n QObject::tr (\"QDriverStation\"),\r\n QObject::tr (\"Please input your team number:\"),\r\n 0, 0, 9999, 1, 0,\r\n Qt::WindowStaysOnTopHint));\r\n Settings::set (\"First launch\", false);\r\n }\r\n\r\n return app.exec();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of qtagger.\n *\n * © 2010 Fernando Tarlá Cardoso Lemos\n *\n * Refer to the LICENSE file for licensing information.\n *\n *\/\n\n#include <boost\/scoped_ptr.hpp>\n#include <cstdlib>\n#include <getopt.h>\n#include <iostream>\n#include <locale>\n#include <string>\n\n#include \"BasicStringFilter.h\"\n#include \"InteractiveTagger.h\"\n#include \"SimpleCapitalizationFilter.h\"\n#include \"StandardConsole.h\"\n#include \"TitleCapitalizationFilter.h\"\n\nstatic void print_usage(std::ostream &out)\n{\n out << \"\\\nUsage: \\n\\\n qtagger [--dir-rename-format] [--file-rename-format format] \\\\\\n\\\n [--input-filter filter] [--output-filter filter] \\\\\\n\\\n <path> [path2] [path3] ...\\n\\\n qtagger --help\\n\\\n\\n\\\nAvailable filters: basic, first_upper, lower, title, upper\\n\\\n\\n\\\nExample:\\n\\\n qtagger --file-rename-format '%%track. %%album' \\\\\\n\\\n --dir-rename-format '%%album (%%year)' \\\\\\n\\\n --input-filter title --output-filter basic\\n\\\n\" << std::endl;\n}\n\nstatic BasicStringFilter *select_string_filter(const std::string &filter)\n{\n if (filter == \"basic\")\n return new BasicStringFilter;\n else if (filter == \"title\")\n return new TitleCapitalizationFilter;\n else if (filter == \"lower\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_LOWER);\n else if (filter == \"upper\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_UPPER);\n else if (filter == \"first_upper\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_FIRST_UPPER);\n else\n return NULL;\n}\n\nint main(int argc, char **argv)\n{\n \/\/ Set the global locale for case conversion purposes\n const char *locale_name = getenv(\"LANG\");\n if (locale_name) {\n std::ios_base::sync_with_stdio(false);\n std::locale locale(std::locale::classic(), locale_name, std::locale::ctype);\n std::locale::global(locale);\n std::wcout.imbue(locale);\n std::wcin.imbue(locale);\n }\n else {\n std::cerr << \"WARNING: $LANG is not defined\" << std::endl;\n }\n\n struct option long_options[] = {\n {\"dir-rename-format\", required_argument, NULL, 'd'},\n {\"input-filter\", required_argument, NULL, 'i'},\n {\"file-rename-format\", required_argument, NULL, 'f'},\n {\"help\", no_argument, NULL, 'h'},\n {\"output-filter\", required_argument, NULL, 'o'},\n {NULL, 0, NULL, 0}\n };\n\n \/\/ Create the interactive tagger\n InteractiveTagger itag;\n boost::scoped_ptr<BasicStringFilter> input_filter, output_filter;\n\n \/\/ Parse the command line options\n int opt;\n while ((opt = getopt_long(argc, argv, \"d:i:f:o:h\", long_options, NULL)) != -1) {\n switch (opt) {\n case 'd':\n itag.set_dir_rename_format(optarg);\n break;\n case 'f':\n itag.set_file_rename_format(optarg);\n break;\n case 'i':\n input_filter.reset(select_string_filter(optarg));\n if (!input_filter.get()) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n break;\n case 'h':\n print_usage(std::cout);\n return EXIT_SUCCESS;\n case 'o':\n output_filter.reset(select_string_filter(optarg));\n if (!output_filter.get()) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n break;\n default:\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ We need at least one path\n if (optind >= argc) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n\n \/\/ Add the filters\n if (!input_filter.get())\n input_filter.reset(new BasicStringFilter);\n itag.set_input_filter(input_filter.get());\n itag.set_output_filter(output_filter.get());\n\n \/\/ Create the interactive terminal\n StandardConsole console;\n itag.set_terminal(&console);\n\n \/\/ Perform the interactive tagging\n itag.tag(argc - optind, (const char **)&argv[optind]);\n\n return EXIT_SUCCESS;\n}\n<commit_msg>This is not printf, no need for %%.<commit_after>\/*\n * This file is part of qtagger.\n *\n * © 2010 Fernando Tarlá Cardoso Lemos\n *\n * Refer to the LICENSE file for licensing information.\n *\n *\/\n\n#include <boost\/scoped_ptr.hpp>\n#include <cstdlib>\n#include <getopt.h>\n#include <iostream>\n#include <locale>\n#include <string>\n\n#include \"BasicStringFilter.h\"\n#include \"InteractiveTagger.h\"\n#include \"SimpleCapitalizationFilter.h\"\n#include \"StandardConsole.h\"\n#include \"TitleCapitalizationFilter.h\"\n\nstatic void print_usage(std::ostream &out)\n{\n out << \"\\\nUsage: \\n\\\n qtagger [--dir-rename-format] [--file-rename-format format] \\\\\\n\\\n [--input-filter filter] [--output-filter filter] \\\\\\n\\\n <path> [path2] [path3] ...\\n\\\n qtagger --help\\n\\\n\\n\\\nAvailable filters: basic, first_upper, lower, title, upper\\n\\\n\\n\\\nExample:\\n\\\n qtagger --file-rename-format '%track. %album' \\\\\\n\\\n --dir-rename-format '%album (%year)' \\\\\\n\\\n --input-filter title --output-filter basic\\n\\\n\" << std::endl;\n}\n\nstatic BasicStringFilter *select_string_filter(const std::string &filter)\n{\n if (filter == \"basic\")\n return new BasicStringFilter;\n else if (filter == \"title\")\n return new TitleCapitalizationFilter;\n else if (filter == \"lower\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_LOWER);\n else if (filter == \"upper\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_UPPER);\n else if (filter == \"first_upper\")\n return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_FIRST_UPPER);\n else\n return NULL;\n}\n\nint main(int argc, char **argv)\n{\n \/\/ Set the global locale for case conversion purposes\n const char *locale_name = getenv(\"LANG\");\n if (locale_name) {\n std::ios_base::sync_with_stdio(false);\n std::locale locale(std::locale::classic(), locale_name, std::locale::ctype);\n std::locale::global(locale);\n std::wcout.imbue(locale);\n std::wcin.imbue(locale);\n }\n else {\n std::cerr << \"WARNING: $LANG is not defined\" << std::endl;\n }\n\n struct option long_options[] = {\n {\"dir-rename-format\", required_argument, NULL, 'd'},\n {\"input-filter\", required_argument, NULL, 'i'},\n {\"file-rename-format\", required_argument, NULL, 'f'},\n {\"help\", no_argument, NULL, 'h'},\n {\"output-filter\", required_argument, NULL, 'o'},\n {NULL, 0, NULL, 0}\n };\n\n \/\/ Create the interactive tagger\n InteractiveTagger itag;\n boost::scoped_ptr<BasicStringFilter> input_filter, output_filter;\n\n \/\/ Parse the command line options\n int opt;\n while ((opt = getopt_long(argc, argv, \"d:i:f:o:h\", long_options, NULL)) != -1) {\n switch (opt) {\n case 'd':\n itag.set_dir_rename_format(optarg);\n break;\n case 'f':\n itag.set_file_rename_format(optarg);\n break;\n case 'i':\n input_filter.reset(select_string_filter(optarg));\n if (!input_filter.get()) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n break;\n case 'h':\n print_usage(std::cout);\n return EXIT_SUCCESS;\n case 'o':\n output_filter.reset(select_string_filter(optarg));\n if (!output_filter.get()) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n break;\n default:\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n }\n\n \/\/ We need at least one path\n if (optind >= argc) {\n print_usage(std::cerr);\n return EXIT_FAILURE;\n }\n\n \/\/ Add the filters\n if (!input_filter.get())\n input_filter.reset(new BasicStringFilter);\n itag.set_input_filter(input_filter.get());\n itag.set_output_filter(output_filter.get());\n\n \/\/ Create the interactive terminal\n StandardConsole console;\n itag.set_terminal(&console);\n\n \/\/ Perform the interactive tagging\n itag.tag(argc - optind, (const char **)&argv[optind]);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GameCtrl.h\"\n\nint main() {\n auto game = GameCtrl::getInstance();\n\n \/\/ Set FPS. Default is 60.0\n game->setFPS(60.0);\n\n \/\/ Set whether to enable the snake AI. Default is true.\n game->setEnableAI(true);\n\n \/\/ Set interval time between each snake's movement. Default is 30 ms.\n \/\/ To play classic snake game, set to 200ms is perfect.\n game->setMoveInterval(30);\n\n \/\/ Set whether to record snake's movements to file. Default is false.\n \/\/ Movements will be written to file \"movements.txt\".\n game->setRecordMovements(false);\n\n \/\/ Set whether to run the test program. Default is false.\n game->setRunTest(false);\n\n \/\/ Set map's size(including boundaries)\n \/\/ Default is 10*10. Minimum is 4*4.\n game->setMapRow(10);\n game->setMapCol(10);\n\n return game->run();\n}\n<commit_msg>Resize grid to 20x20 for better visibility<commit_after>#include \"GameCtrl.h\"\n\nint main() {\n auto game = GameCtrl::getInstance();\n\n \/\/ Set FPS. Default is 60.0\n game->setFPS(60.0);\n\n \/\/ Set whether to enable the snake AI. Default is true.\n game->setEnableAI(true);\n\n \/\/ Set interval time between each snake's movement. Default is 30 ms.\n \/\/ To play classic snake game, set to 200ms is perfect.\n game->setMoveInterval(30);\n\n \/\/ Set whether to record snake's movements to file. Default is false.\n \/\/ Movements will be written to file \"movements.txt\".\n game->setRecordMovements(false);\n\n \/\/ Set whether to run the test program. Default is false.\n game->setRunTest(false);\n\n \/\/ Set map's size(including boundaries)\n \/\/ Default is 10*10. Minimum is 4*4.\n game->setMapRow(20);\n game->setMapCol(20);\n\n return game->run();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"input\/filter.h\"\n#include \"input\/format.h\"\n#include \"encoder\/encoder.h\"\n#include \"sjoin\/sjoin.h\"\n#include \"virtualizer\/virtualizer.h\"\n#include <ctime>\n#include <stdio.h>\n\nint process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {\n FILE *f;\n const char *filename = \"FL.aac\";\n\n AVPacket packet, packet0;\n AVFrame *frame = av_frame_alloc();\n AVFrame *filt_frame = av_frame_alloc();\n int got_frame;\n\n\n std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;\n complete_sofa sofa_;\n\n\n AVPacket packet_out;\n int got_output;\n\n Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,\n fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);\n\n SJoin *sjoin = new SJoin(encoder);\n\n f = fopen(filename, \"wb\");\n if(!f) {\n std::cout << \"Error opening file\" << std::endl;\n }\n\n int ret = 0;\n\n \/* Read all of the packets *\/\n packet0.data = NULL;\n packet.data = NULL;\n while(1) {\n\n if(!packet0.data) {\n ret = av_read_frame(fmt->format_ctx, &packet);\n if(ret < 0) break;\n packet0 = packet;\n }\n\n if(packet.stream_index == fmt->audio_stream_index) {\n got_frame = 0;\n ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);\n\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error decoding audio\\n\");\n continue;\n }\n\n packet.size -= ret;\n packet.data += ret;\n\n if(got_frame) {\n\n \/* push audio from decoded frame through filter graph *\/\n if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n\n while(ret >= 0) {\n \/\/ This is where you will work with each processed frame.\n\n int i;\n\n i = 0;\n for (auto it = filter->abuffersink_ctx_map.begin();\n it != filter->abuffersink_ctx_map.end(); it++) {\n\n ret = av_buffersink_get_frame(it->second, filt_frame);\n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n\n\n int sample_count = filt_frame->nb_samples;\n int sample_rate = filt_frame->sample_rate;\n\n if (c2v_.count(it->first) == 0) {\n float x;\n float y;\n float z;\n Filter::get_coords(it->first, &x, &y, &z);\n\n if (sofa_.hrtf == NULL) {\n \/\/TODO: delete these after execution\n Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);\n c2v_.insert(std::make_pair(it->first, virt));\n sofa_ = virt->get_hrtf();\n }\n else {\n \/\/TODO: delete these after execution\n Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);\n c2v_.insert(std::make_pair(it->first, virt));\n }\n }\n\n float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n float ** float_results = c2v_[it->first]->process(samples, sample_count);\n\n uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n delete[] float_results[0];\n delete[] float_results[1];\n delete[] float_results;\n delete[] samples;\n\n AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,\n result_l);\n\n if(it->first == 0) {\n \/\/std::cout << l_frame->nb_samples << std::endl;\n \/\/std::cout << l_frame->format << std::endl;\n \/\/ This will move once virtualizaiton works\n av_init_packet(&packet_out);\n packet_out.data = NULL;\n packet_out.size = 0;\n\n\n ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);\n if(ret < 0) exit(1);\n if(got_output) {\n fwrite(packet_out.data, 1, packet_out.size, f);\n av_free_packet(&packet_out);\n }\n }\n\n\n \/\/AVFrame *r_frame = encoder->fill_new_frame(result_r, 2);\n\n \/*\n if(av_buffersrc_add_frame_flags(sjoin->right_abuffers_ctx[i], r_frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n *\/\n \/\/ TODO: do something with the result\n\n \/\/std::cout << \"FR\";\n av_frame_unref(filt_frame);\n \/\/av_frame_unref(r_frame);\n i++;\n }\n av_frame_unref(filt_frame);\n }\n }\n if(packet.size <= 0) av_free_packet(&packet0);\n } else {\n av_free_packet(&packet0);\n }\n }\n fclose(f);\n av_frame_free(&frame);\n av_frame_free(&filt_frame);\n delete filter;\n delete fmt;\n}\n\nint main(int argc, char *argv[]) {\n std::string videoFile = std::string(argv[1]);\n std::string sofaFile = std::string(argv[2]);\n\n clock_t begin = clock();\n Format *format = new Format(videoFile);\n Filter *filter = new Filter(format);\n clock_t end = clock();\n\n std::cout << \"Filter initialization: \" << (double)(end - begin) \/ CLOCKS_PER_SEC << \" s\" << std::endl;\n\n begin = clock();\n process_filter_graph(format, filter, sofaFile);\n end = clock();\n\n std::cout << \"Processing Time: \" << (double)(end - begin) \/ CLOCKS_PER_SEC << \" s\" << std::endl;\n return 0;\n}\n<commit_msg>Fixed bad commits<commit_after>#include <iostream>\n#include \"input\/filter.h\"\n#include \"input\/format.h\"\n#include \"encoder\/encoder.h\"\n\/\/#include \"sjoin\/sjoin.h\"\n#include \"sjoin\/testjoin.h\"\n#include \"virtualizer\/virtualizer.h\"\n#include <ctime>\n#include <stdio.h>\n#include <libavutil\/fifo.h>\n\ntypedef struct {\n const AVClass *classs;\n AVFifoBuffer *fifo;\n AVRational time_base; \/\/\/< time_base to set in the output link\n AVRational frame_rate; \/\/\/< frame_rate to set in the output link\n unsigned nb_failed_requests;\n unsigned warning_limit;\n \n \/* video only *\/\n int w, h;\n enum AVPixelFormat pix_fmt;\n AVRational pixel_aspect;\n char *sws_param;\n \n \/* audio only *\/\n int sample_rate;\n enum AVSampleFormat sample_fmt;\n char *sample_fmt_str;\n int channels;\n uint64_t channel_layout;\n char *channel_layout_str;\n \n int eof;\n } BufferSourceContext;\n\n\nint process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {\n FILE *f;\n const char *filename = \"FL.aac\";\n\n AVPacket packet, packet0;\n AVFrame *frame = av_frame_alloc();\n AVFrame *filt_frame = av_frame_alloc();\n int got_frame;\n\n\n std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;\n complete_sofa sofa_;\n\n\n AVPacket packet_out;\n int got_output;\n\n Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,\n fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);\n\n \/\/SJoin *sjoin = new SJoin(encoder);\n TestJoin *testjoin = new TestJoin(encoder);\n\n f = fopen(filename, \"wb\");\n if(!f) {\n std::cout << \"Error opening file\" << std::endl;\n }\n\n int ret = 0;\n\n \/* Read all of the packets *\/\n packet0.data = NULL;\n packet.data = NULL;\n while(1) {\n\n if(!packet0.data) {\n ret = av_read_frame(fmt->format_ctx, &packet);\n if(ret < 0) break;\n packet0 = packet;\n }\n\n if(packet.stream_index == fmt->audio_stream_index) {\n got_frame = 0;\n ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);\n\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error decoding audio\\n\");\n continue;\n }\n\n packet.size -= ret;\n packet.data += ret;\n\n if(got_frame) {\n\n \/* push audio from decoded frame through filter graph *\/\n if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n\n while(ret >= 0) {\n \/\/ This is where you will work with each processed frame.\n\n int i;\n\n i = 0;\n for (auto it = filter->abuffersink_ctx_map.begin();\n it != filter->abuffersink_ctx_map.end(); it++) {\n\n ret = av_buffersink_get_frame(it->second, filt_frame);\n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n\n\n int sample_count = filt_frame->nb_samples;\n int sample_rate = filt_frame->sample_rate;\n\n if (c2v_.count(it->first) == 0) {\n float x;\n float y;\n float z;\n Filter::get_coords(it->first, &x, &y, &z);\n\n if (sofa_.hrtf == NULL) {\n \/\/TODO: delete these after execution\n Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);\n c2v_.insert(std::make_pair(it->first, virt));\n sofa_ = virt->get_hrtf();\n }\n else {\n \/\/TODO: delete these after execution\n Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);\n c2v_.insert(std::make_pair(it->first, virt));\n }\n }\n\n float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n float ** float_results = c2v_[it->first]->process(samples, sample_count);\n\n uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],\n fmt->decoder_ctx->sample_fmt, sample_count);\n\n delete[] float_results[0];\n delete[] float_results[1];\n delete[] float_results;\n delete[] samples;\n\n AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,\n result_l);\n \n virt_frame->format = AV_SAMPLE_FMT_FLTP;\n virt_frame->sample_rate = 48000;\n virt_frame->channel_layout = 3;\n\n if(it->first == 0) {\n \/\/std::cout << l_frame->nb_samples << std::endl;\n \/\/std::cout << l_frame->format << std::endl;\n \/\/ This will move once virtualizaiton works\n av_init_packet(&packet_out);\n packet_out.data = NULL;\n packet_out.size = 0;\n\n\n ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);\n if(ret < 0) exit(1);\n if(got_output) {\n fwrite(packet_out.data, 1, packet_out.size, f);\n av_free_packet(&packet_out);\n }\n }\n\n if(av_buffersrc_add_frame_flags(testjoin->abuffer_ctx, virt_frame, 0) < 0)\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filtergraph\\n\");\n AVFrame *test_virt_frame = av_frame_alloc();\n ret = av_buffersink_get_frame(testjoin->abuffersink_ctx, test_virt_frame);\n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n\n\n \/*\n if(av_buffersrc_add_frame_flags(sjoin->right_abuffers_ctx[i], r_frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n *\/\n \/\/ TODO: do something with the result\n\n \/\/std::cout << \"FR\";\n av_frame_unref(virt_frame);\n av_frame_unref(filt_frame);\n \/\/av_frame_unref(r_frame);\n i++;\n }\n av_frame_unref(filt_frame);\n }\n }\n if(packet.size <= 0) av_free_packet(&packet0);\n } else {\n av_free_packet(&packet0);\n }\n }\n fclose(f);\n av_frame_free(&frame);\n av_frame_free(&filt_frame);\n delete filter;\n delete fmt;\n}\n\nint main(int argc, char *argv[]) {\n std::string videoFile = std::string(argv[1]);\n std::string sofaFile = std::string(argv[2]);\n\n clock_t begin = clock();\n Format *format = new Format(videoFile);\n Filter *filter = new Filter(format);\n clock_t end = clock();\n\n std::cout << \"Filter initialization: \" << (double)(end - begin) \/ CLOCKS_PER_SEC << \" s\" << std::endl;\n\n begin = clock();\n process_filter_graph(format, filter, sofaFile);\n end = clock();\n\n std::cout << \"Processing Time: \" << (double)(end - begin) \/ CLOCKS_PER_SEC << \" s\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"math\/vec.hpp\"\n#include <iostream>\n\nint main(int , char *[]) {\n\tstd::cout << \"Hello World!\\n\";\n}<commit_msg>Add main loop<commit_after>#include \"math\/vec.hpp\"\n#include <iostream>\n#include <algorithm>\n#include <SDL2\/SDL.h>\n\nstatic void show_error(const char* message) {\n\tif (SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Error\", message, nullptr) != 0) {\n\t\tstd::cerr << message << std::endl;\n\t}\n}\n\nvoid game_loop(SDL_Window* window) {\n\tbool running = true;\n\n\tSint32 frame_time_behind = 0;\n\tstatic const Sint32 MAX_LAG_TIME = 100;\n\n\tconst Sint32 fixed_frame_time = 1000 \/ 60;\n\n\twhile (running) {\n\t\t\/\/ The duration we're hoping to have on this frame\n\t\tconst Sint32 desired_frame_time = fixed_frame_time - frame_time_behind;\n\n\t\tconst Uint32 frame_start = SDL_GetTicks();\n\n\t\tSDL_Event ev;\n\t\twhile (SDL_PollEvent(&ev)) {\n\t\t\tswitch (ev.type) {\n\t\t\tcase SDL_QUIT:\n\t\t\t\trunning = false;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ do update here\n\n\t\tSDL_GL_SwapWindow(window);\n\n\t\tconst Sint32 time_elapsed_in_frame = SDL_GetTicks() - frame_start;\n\n\t\tstd::cout << \"FRAMETIME: \" << time_elapsed_in_frame << '\\n';\n\n\t\tif (time_elapsed_in_frame < desired_frame_time) {\n\t\t\tconst Sint32 sleep_len = desired_frame_time - time_elapsed_in_frame;\n\t\t\tSDL_Delay(sleep_len);\n\t\t}\n\n\t\tframe_time_behind -= fixed_frame_time;\n\t\tframe_time_behind += SDL_GetTicks() - frame_start;\n\t\tif (frame_time_behind > MAX_LAG_TIME) {\n\t\t\tframe_time_behind = MAX_LAG_TIME;\n\t\t}\n\t}\n}\n\nint main(int , char *[]) {\n\tif (SDL_Init(SDL_INIT_VIDEO) != 0) {\n\t\tshow_error(\"Failed to initialize SDL\");\n\t\treturn 1;\n\t}\n\n\tSDL_Window* window = SDL_CreateWindow(\"Super Match 5 DX\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL);\n\tif (window == nullptr) {\n\t\tshow_error(\"Failed to create window.\");\n\t\treturn 1;\n\t}\n\n\tgame_loop(window);\n\n\tSDL_DestroyWindow(window);\n\tSDL_Quit();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"axisanalogbinding.h\"\n\n\n\/**********************************************************************************************************************\/\n\/* Public API *\/\n\/**********************************************************************************************************************\/\n\n\/**\n * @brief Default Constructor\n * @param parent The parent QObject.\n *\/\nAxisAnalogBinding::AxisAnalogBinding(QObject *parent) :\n ControlBinding(parent),\n _sensitivity(0),\n _offset(0),\n _deadzone(0),\n _instantaneousValue(0)\n{\n} \/\/ end AxisAnalogBinding\n\n\/**********************************************************************************************************************\/\n\/* Slots *\/\n\/**********************************************************************************************************************\/\n\n\/**\n * @brief Should get called whenever the connected InputSignal's value changes.\n * @param position The position of the axis.\n *\/\nvoid AxisAnalogBinding::onSignalUpdated(float position)\n{\n _instantaneousValue = position;\n emit stateChanged();\n} \/\/ onSignalUpdated\n<commit_msg>started taking sensitivity, deadzone and offset into account.<commit_after>#include \"axisanalogbinding.h\"\n\n\n\/**********************************************************************************************************************\/\n\/* Public API *\/\n\/**********************************************************************************************************************\/\n\n\/**\n * @brief Default Constructor\n * @param parent The parent QObject.\n *\/\nAxisAnalogBinding::AxisAnalogBinding(QObject *parent) :\n ControlBinding(parent),\n _sensitivity(0),\n _offset(0),\n _deadzone(0),\n _instantaneousValue(0)\n{\n} \/\/ end AxisAnalogBinding\n\n\/**********************************************************************************************************************\/\n\/* Slots *\/\n\/**********************************************************************************************************************\/\n\n\/**\n * @brief Should get called whenever the connected InputSignal's value changes.\n * @param position The position of the axis.\n *\/\nvoid AxisAnalogBinding::onSignalUpdated(float position)\n{\n float value = position + _offset;\n if(value > 0)\n {\n if(value < _deadzone)\n {\n value = 0;\n }\n else\n {\n value -= _deadzone;\n } \/\/ end if\n }\n else\n {\n if(value > -_deadzone)\n {\n value = 0;\n }\n else\n {\n value += _deadzone;\n } \/\/ end if\n } \/\/ end if\n\n _instantaneousValue = _sensitivity * value;\n emit stateChanged();\n} \/\/ onSignalUpdated\n<|endoftext|>"} {"text":"<commit_before>\/*\n * DesktopMacDetectRHome.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"DesktopDetectRHome.hpp\"\n\n#include <vector>\n\n#include <boost\/algorithm\/string\/trim.hpp>\n\n#include <QtCore>\n#include <QMessageBox>\n\n#include <core\/Error.hpp>\n#include <core\/Log.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/system\/System.hpp>\n\n#include \"config.h\"\n\nusing namespace core;\n\nnamespace desktop {\n\nnamespace {\n\n\/\/ MacOS X Specific\n#ifdef __APPLE__\n\n#define kLibRFileName \"libR.dylib \"\n#define kLibraryPathEnvVariable \"DYLD_LIBRARY_PATH\"\n\n \/\/ define search paths to match shell search path behavior (including\n \/\/ \/opt\/local\/bin being first since that is where macports puts it)\n std::vector<std::string> rSearchPaths()\n {\n std::vector<std::string> rPaths;\n rPaths.push_back(\"\/opt\/local\/bin\/R\");\n rPaths.push_back(\"\/usr\/bin\/R\");\n rPaths.push_back(\"\/usr\/local\/bin\/R\");\n return rPaths;\n }\n\n \/\/ no extra paths on the mac\n std::string extraLibrayPaths()\n {\n return std::string();\n }\n\n\n\/\/ Linux specific\n#else\n\n#define kLibRFileName \"libR.so\"\n#define kLibraryPathEnvVariable \"LD_LIBRARY_PATH\"\n\n \/\/ define search paths to match shell search path behavior (note differs\n \/\/ from macox by having \/usr\/local\/bin first)\n std::vector<std::string> rSearchPaths()\n {\n std::vector<std::string> rPaths;\n rPaths.push_back(\"\/usr\/local\/bin\/R\");\n rPaths.push_back(\"\/usr\/bin\/R\");\n return rPaths;\n }\n\n \/\/ extra paths from R (for rjava) on linux\n std::string extraLibraryPaths()\n {\n std::string libraryPaths;\n\n FilePath supportingFilePath = desktop::options().supportingFilePath();\n FilePath scriptPath = supportingFilePath.complete(\"bin\/r-ldpath\");\n if (!scriptPath.exists())\n scriptPath = supportingFilePath.complete(\"session\/r-ldpath\");\n if (scriptPath.exists())\n {\n \/\/ run script\n Error error = system::captureCommand(scriptPath.absolutePath(),\n &libraryPaths);\n if (error)\n LOG_ERROR(error);\n }\n\n return libraryPaths;\n }\n\n\n#endif\n\n\nFilePath detectRHome()\n{\n \/\/ scan possible locations for R (need these because on the mac\n \/\/ our path as a GUI app is very limited)\n FilePath rPath;\n std::vector<std::string> rPaths = rSearchPaths();\n for(std::vector<std::string>::const_iterator it = rPaths.begin();\n it != rPaths.end(); ++it)\n {\n FilePath candidatePath(*it);\n if (candidatePath.exists())\n {\n rPath = candidatePath ;\n break;\n }\n }\n\n \/\/ if we didn't find one then bail\n if (rPath.empty())\n {\n LOG_ERROR_MESSAGE(\"Couldn't find R on known path\");\n return FilePath();\n }\n\n \/\/ run R to detect R home\n std::string output;\n std::string command = rPath.absolutePath() + \" RHOME\";\n Error error = core::system::captureCommand(command, &output);\n if (error)\n {\n LOG_ERROR(error);\n return FilePath();\n }\n boost::algorithm::trim(output);\n\n \/\/ return the home path if we got one\n if (!output.empty())\n return FilePath(output);\n else\n return FilePath();\n}\n\nvoid showRNotFoundError(const std::string& msg)\n{\n QMessageBox::critical(NULL, \"R Not Found\", QString::fromStdString(msg));\n}\n\n} \/\/ anonymous namespace\n\nbool prepareEnvironment(Options&)\n{\n \/\/ declare home path and doc dir -- can get them from the environment\n \/\/ or by probing the system\n FilePath homePath, rDocDir;\n\n \/\/ first check environment\n std::string home = core::system::getenv(\"R_HOME\");\n if (!home.empty())\n homePath = FilePath(home);\n std::string doc = core::system::getenv(\"R_DOC_DIR\");\n if (!doc.empty())\n rDocDir = FilePath(doc);\n\n \/\/ probe for home path if necessary\n if (homePath.empty())\n homePath = detectRHome();\n\n \/\/ if that didn't work then try the configured path as a last ditch\n if (!homePath.exists())\n homePath = FilePath(CONFIG_R_HOME_PATH);\n\n \/\/ verify and set home path\n if (homePath.exists())\n {\n core::system::setenv(\"R_HOME\", homePath.absolutePath());\n }\n else\n {\n showRNotFoundError(\"R home path (\" + homePath.absolutePath() +\n \") does not exist. Is R installed on \"\n \"this system?\");\n return false;\n }\n\n \/\/ complete doc dir if necesary\n if (rDocDir.empty())\n rDocDir = homePath.complete(\"doc\");\n\n \/\/ doc dir may be in configured location (\/usr\/share) rather than\n \/\/ a subdirectory of R_HOME (this is in fact the case for the\n \/\/ debian r-base package). so check the configuired location as\n \/\/ a last ditch\n if (!rDocDir.exists())\n rDocDir = FilePath(CONFIG_R_DOC_PATH);\n\n \/\/ verify and set doc dir\n if (rDocDir.exists())\n {\n core::system::setenv(\"R_DOC_DIR\", rDocDir.absolutePath());\n }\n else\n {\n showRNotFoundError(\"R doc directory (\" + rDocDir.absolutePath() +\n \") does not exist.\");\n return false;\n }\n\n \/\/ verify and set library path\n FilePath rLibPath = homePath.complete(\"lib\");\n if (rLibPath.exists())\n {\n \/\/ make sure the R lib was built\n FilePath libRpath = rLibPath.complete(kLibRFileName);\n if (libRpath.exists())\n {\n \/\/ initialize library path from existing value + any extras\n std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);\n if (!libraryPath.empty())\n libraryPath.append(\":\");\n libraryPath.append(rLibPath.absolutePath());\n std::string extraPaths = extraLibraryPaths();\n if (!extraPaths.empty())\n libraryPath.append(\":\" + extraPaths);\n\n \/\/ set it\n core::system::setenv(kLibraryPathEnvVariable, libraryPath);\n }\n else\n {\n showRNotFoundError(rLibPath.filename() + \" not found in R library \"\n \"path. If this is a custom build of R, was it \"\n \"built with the --enable-R-shlib option?\");\n return false;\n }\n }\n else\n {\n showRNotFoundError(\"R library directory (\" + rLibPath.absolutePath() +\n \") does not exist.\");\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace desktop\n<commit_msg>fix mac build issue<commit_after>\/*\n * DesktopMacDetectRHome.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"DesktopDetectRHome.hpp\"\n\n#include <vector>\n\n#include <boost\/algorithm\/string\/trim.hpp>\n\n#include <QtCore>\n#include <QMessageBox>\n\n#include <core\/Error.hpp>\n#include <core\/Log.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/system\/System.hpp>\n\n#include \"config.h\"\n\nusing namespace core;\n\nnamespace desktop {\n\nnamespace {\n\n\/\/ MacOS X Specific\n#ifdef __APPLE__\n\n#define kLibRFileName \"libR.dylib \"\n#define kLibraryPathEnvVariable \"DYLD_LIBRARY_PATH\"\n\n \/\/ define search paths to match shell search path behavior (including\n \/\/ \/opt\/local\/bin being first since that is where macports puts it)\n std::vector<std::string> rSearchPaths()\n {\n std::vector<std::string> rPaths;\n rPaths.push_back(\"\/opt\/local\/bin\/R\");\n rPaths.push_back(\"\/usr\/bin\/R\");\n rPaths.push_back(\"\/usr\/local\/bin\/R\");\n return rPaths;\n }\n\n \/\/ no extra paths on the mac\n std::string extraLibraryPaths()\n {\n return std::string();\n }\n\n\n\/\/ Linux specific\n#else\n\n#define kLibRFileName \"libR.so\"\n#define kLibraryPathEnvVariable \"LD_LIBRARY_PATH\"\n\n \/\/ define search paths to match shell search path behavior (note differs\n \/\/ from macox by having \/usr\/local\/bin first)\n std::vector<std::string> rSearchPaths()\n {\n std::vector<std::string> rPaths;\n rPaths.push_back(\"\/usr\/local\/bin\/R\");\n rPaths.push_back(\"\/usr\/bin\/R\");\n return rPaths;\n }\n\n \/\/ extra paths from R (for rjava) on linux\n std::string extraLibraryPaths()\n {\n std::string libraryPaths;\n\n FilePath supportingFilePath = desktop::options().supportingFilePath();\n FilePath scriptPath = supportingFilePath.complete(\"bin\/r-ldpath\");\n if (!scriptPath.exists())\n scriptPath = supportingFilePath.complete(\"session\/r-ldpath\");\n if (scriptPath.exists())\n {\n \/\/ run script\n Error error = system::captureCommand(scriptPath.absolutePath(),\n &libraryPaths);\n if (error)\n LOG_ERROR(error);\n }\n\n return libraryPaths;\n }\n\n\n#endif\n\n\nFilePath detectRHome()\n{\n \/\/ scan possible locations for R (need these because on the mac\n \/\/ our path as a GUI app is very limited)\n FilePath rPath;\n std::vector<std::string> rPaths = rSearchPaths();\n for(std::vector<std::string>::const_iterator it = rPaths.begin();\n it != rPaths.end(); ++it)\n {\n FilePath candidatePath(*it);\n if (candidatePath.exists())\n {\n rPath = candidatePath ;\n break;\n }\n }\n\n \/\/ if we didn't find one then bail\n if (rPath.empty())\n {\n LOG_ERROR_MESSAGE(\"Couldn't find R on known path\");\n return FilePath();\n }\n\n \/\/ run R to detect R home\n std::string output;\n std::string command = rPath.absolutePath() + \" RHOME\";\n Error error = core::system::captureCommand(command, &output);\n if (error)\n {\n LOG_ERROR(error);\n return FilePath();\n }\n boost::algorithm::trim(output);\n\n \/\/ return the home path if we got one\n if (!output.empty())\n return FilePath(output);\n else\n return FilePath();\n}\n\nvoid showRNotFoundError(const std::string& msg)\n{\n QMessageBox::critical(NULL, \"R Not Found\", QString::fromStdString(msg));\n}\n\n} \/\/ anonymous namespace\n\nbool prepareEnvironment(Options&)\n{\n \/\/ declare home path and doc dir -- can get them from the environment\n \/\/ or by probing the system\n FilePath homePath, rDocDir;\n\n \/\/ first check environment\n std::string home = core::system::getenv(\"R_HOME\");\n if (!home.empty())\n homePath = FilePath(home);\n std::string doc = core::system::getenv(\"R_DOC_DIR\");\n if (!doc.empty())\n rDocDir = FilePath(doc);\n\n \/\/ probe for home path if necessary\n if (homePath.empty())\n homePath = detectRHome();\n\n \/\/ if that didn't work then try the configured path as a last ditch\n if (!homePath.exists())\n homePath = FilePath(CONFIG_R_HOME_PATH);\n\n \/\/ verify and set home path\n if (homePath.exists())\n {\n core::system::setenv(\"R_HOME\", homePath.absolutePath());\n }\n else\n {\n showRNotFoundError(\"R home path (\" + homePath.absolutePath() +\n \") does not exist. Is R installed on \"\n \"this system?\");\n return false;\n }\n\n \/\/ complete doc dir if necesary\n if (rDocDir.empty())\n rDocDir = homePath.complete(\"doc\");\n\n \/\/ doc dir may be in configured location (\/usr\/share) rather than\n \/\/ a subdirectory of R_HOME (this is in fact the case for the\n \/\/ debian r-base package). so check the configuired location as\n \/\/ a last ditch\n if (!rDocDir.exists())\n rDocDir = FilePath(CONFIG_R_DOC_PATH);\n\n \/\/ verify and set doc dir\n if (rDocDir.exists())\n {\n core::system::setenv(\"R_DOC_DIR\", rDocDir.absolutePath());\n }\n else\n {\n showRNotFoundError(\"R doc directory (\" + rDocDir.absolutePath() +\n \") does not exist.\");\n return false;\n }\n\n \/\/ verify and set library path\n FilePath rLibPath = homePath.complete(\"lib\");\n if (rLibPath.exists())\n {\n \/\/ make sure the R lib was built\n FilePath libRpath = rLibPath.complete(kLibRFileName);\n if (libRpath.exists())\n {\n \/\/ initialize library path from existing value + any extras\n std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);\n if (!libraryPath.empty())\n libraryPath.append(\":\");\n libraryPath.append(rLibPath.absolutePath());\n std::string extraPaths = extraLibraryPaths();\n if (!extraPaths.empty())\n libraryPath.append(\":\" + extraPaths);\n\n \/\/ set it\n core::system::setenv(kLibraryPathEnvVariable, libraryPath);\n }\n else\n {\n showRNotFoundError(rLibPath.filename() + \" not found in R library \"\n \"path. If this is a custom build of R, was it \"\n \"built with the --enable-R-shlib option?\");\n return false;\n }\n }\n else\n {\n showRNotFoundError(\"R library directory (\" + rLibPath.absolutePath() +\n \") does not exist.\");\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace desktop\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Incognito\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"main.h\"\n\n#include \"core.h\"\n#include \"natives.h\"\n#include \"utility.h\"\n\n#include <boost\/scoped_ptr.hpp>\n\n#include <sampgdk\/core.h>\n\n#include <set>\n\nextern void *pAMXFunctions;\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()\n{\n\treturn SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)\n{\n\tcore.reset(new Core);\n\tpAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n\tsampgdk::logprintf(\"\\n\\n*** Streamer Plugin v%s by Incognito loaded ***\\n\", PLUGIN_VERSION);\n\treturn sampgdk::Load(sampgdk::GetCurrentPluginHandle(), ppData);\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload()\n{\n\tcore.reset();\n\tsampgdk::logprintf(\"\\n\\n*** Streamer Plugin v%s by Incognito unloaded ***\\n\", PLUGIN_VERSION);\n\tsampgdk::Unload(sampgdk::GetCurrentPluginHandle());\n}\n\nAMX_NATIVE_INFO natives[] =\n{\n\t\/\/ Settings\n\t{ \"Streamer_GetTickRate\", Natives::Streamer_GetTickRate },\n\t{ \"Streamer_SetTickRate\", Natives::Streamer_SetTickRate },\n\t{ \"Streamer_GetMaxItems\", Natives::Streamer_GetMaxItems },\n\t{ \"Streamer_SetMaxItems\", Natives::Streamer_SetMaxItems },\n\t{ \"Streamer_GetVisibleItems\", Natives::Streamer_GetVisibleItems },\n\t{ \"Streamer_SetVisibleItems\", Natives::Streamer_SetVisibleItems },\n\t{ \"Streamer_GetCellDistance\", Natives::Streamer_GetCellDistance },\n\t{ \"Streamer_SetCellDistance\", Natives::Streamer_SetCellDistance },\n\t{ \"Streamer_GetCellSize\", Natives::Streamer_GetCellSize },\n\t{ \"Streamer_SetCellSize\", Natives::Streamer_SetCellSize },\n\t\/\/ Updates\n\t{ \"Streamer_ProcessActiveItems\", Natives::Streamer_ProcessActiveItems },\n\t{ \"Streamer_ToggleIdleUpdate\", Natives::Streamer_ToggleIdleUpdate },\n\t{ \"Streamer_IsToggleIdleUpdate\", Natives::Streamer_IsToggleIdleUpdate },\n\t{ \"Streamer_ToggleItemUpdate\", Natives::Streamer_ToggleItemUpdate },\n\t{ \"Streamer_IsToggleItemUpdate\", Natives::Streamer_IsToggleItemUpdate },\n\t{ \"Streamer_Update\", Natives::Streamer_Update },\n\t{ \"Streamer_UpdateEx\", Natives::Streamer_UpdateEx },\n\t\/\/ Data Manipulation\n\t{ \"Streamer_GetFloatData\", Natives::Streamer_GetFloatData },\n\t{ \"Streamer_SetFloatData\", Natives::Streamer_SetFloatData },\n\t{ \"Streamer_GetIntData\", Natives::Streamer_GetIntData },\n\t{ \"Streamer_SetIntData\", Natives::Streamer_SetIntData },\n\t{ \"Streamer_GetArrayData\", Natives::Streamer_GetArrayData },\n\t{ \"Streamer_SetArrayData\", Natives::Streamer_SetArrayData },\n\t{ \"Streamer_IsInArrayData\", Natives::Streamer_IsInArrayData },\n\t{ \"Streamer_AppendArrayData\", Natives::Streamer_AppendArrayData },\n\t{ \"Streamer_RemoveArrayData\", Natives::Streamer_RemoveArrayData },\n\t{ \"Streamer_GetUpperBound\", Natives::Streamer_GetUpperBound },\n\t\/\/ Miscellaneous\n\t{ \"Streamer_GetDistanceToItem\", Natives::Streamer_GetDistanceToItem },\n\t{ \"Streamer_GetItemInternalID\", Natives::Streamer_GetItemInternalID },\n\t{ \"Streamer_GetItemStreamerID\", Natives::Streamer_GetItemStreamerID },\n\t{ \"Streamer_IsItemVisible\", Natives::Streamer_IsItemVisible },\n\t{ \"Streamer_DestroyAllVisibleItems\", Natives::Streamer_DestroyAllVisibleItems },\n\t{ \"Streamer_CountVisibleItems\", Natives::Streamer_CountVisibleItems },\n\t{ \"Streamer_DestroyAllItems\", Natives::Streamer_DestroyAllItems },\n\t{ \"Streamer_CountItems\", Natives::Streamer_CountItems },\n\t\/\/ Objects\n\t{ \"CreateDynamicObject\", Natives::CreateDynamicObject },\n\t{ \"DestroyDynamicObject\", Natives::DestroyDynamicObject },\n\t{ \"IsValidDynamicObject\", Natives::IsValidDynamicObject },\n\t{ \"SetDynamicObjectPos\", Natives::SetDynamicObjectPos },\n\t{ \"GetDynamicObjectPos\", Natives::GetDynamicObjectPos },\n\t{ \"SetDynamicObjectRot\", Natives::SetDynamicObjectRot },\n\t{ \"GetDynamicObjectRot\", Natives::GetDynamicObjectRot },\n\t{ \"MoveDynamicObject\", Natives::MoveDynamicObject },\n\t{ \"StopDynamicObject\", Natives::StopDynamicObject },\n\t{ \"IsDynamicObjectMoving\", Natives::IsDynamicObjectMoving },\n\t{ \"AttachCameraToDynamicObject\", Natives::AttachCameraToDynamicObject },\n\t{ \"AttachDynamicObjectToVehicle\", Natives::AttachDynamicObjectToVehicle },\n\t{ \"EditDynamicObject\", Natives::EditDynamicObject },\n\t{ \"GetDynamicObjectMaterial\", Natives::GetDynamicObjectMaterial },\n\t{ \"SetDynamicObjectMaterial\", Natives::SetDynamicObjectMaterial },\n\t{ \"GetDynamicObjectMaterialText\", Natives::GetDynamicObjectMaterialText },\n\t{ \"SetDynamicObjectMaterialText\", Natives::SetDynamicObjectMaterialText },\n\t\/\/ Pickups\n\t{ \"CreateDynamicPickup\", Natives::CreateDynamicPickup },\n\t{ \"DestroyDynamicPickup\", Natives::DestroyDynamicPickup },\n\t{ \"IsValidDynamicPickup\", Natives::IsValidDynamicPickup },\n\t\/\/ Checkpoints\n\t{ \"CreateDynamicCP\", Natives::CreateDynamicCP },\n\t{ \"DestroyDynamicCP\", Natives::DestroyDynamicCP },\n\t{ \"IsValidDynamicCP\", Natives::IsValidDynamicCP },\n\t{ \"TogglePlayerDynamicCP\", Natives::TogglePlayerDynamicCP },\n\t{ \"TogglePlayerAllDynamicCPs\", Natives::TogglePlayerAllDynamicCPs },\n\t{ \"IsPlayerInDynamicCP\", Natives::IsPlayerInDynamicCP },\n\t{ \"GetPlayerVisibleDynamicCP\", Natives::GetPlayerVisibleDynamicCP },\n\t\/\/ Race Checkpoints\n\t{ \"CreateDynamicRaceCP\", Natives::CreateDynamicRaceCP },\n\t{ \"DestroyDynamicRaceCP\", Natives::DestroyDynamicRaceCP },\n\t{ \"IsValidDynamicRaceCP\", Natives::IsValidDynamicRaceCP },\n\t{ \"TogglePlayerDynamicRaceCP\", Natives::TogglePlayerDynamicRaceCP },\n\t{ \"TogglePlayerAllDynamicRaceCPs\", Natives::TogglePlayerAllDynamicRaceCPs },\n\t{ \"IsPlayerInDynamicRaceCP\", Natives::IsPlayerInDynamicRaceCP },\n\t{ \"GetPlayerVisibleDynamicRaceCP\", Natives::GetPlayerVisibleDynamicRaceCP },\n\t\/\/ Map Icons\n\t{ \"CreateDynamicMapIcon\", Natives::CreateDynamicMapIcon },\n\t{ \"DestroyDynamicMapIcon\", Natives::DestroyDynamicMapIcon },\n\t{ \"IsValidDynamicMapIcon\", Natives::IsValidDynamicMapIcon },\n\t\/\/ 3D Text Labels\n\t{ \"CreateDynamic3DTextLabel\", Natives::CreateDynamic3DTextLabel },\n\t{ \"DestroyDynamic3DTextLabel\", Natives::DestroyDynamic3DTextLabel },\n\t{ \"IsValidDynamic3DTextLabel\", Natives::IsValidDynamic3DTextLabel },\n\t{ \"GetDynamic3DTextLabelText\", Natives::GetDynamic3DTextLabelText },\n\t{ \"UpdateDynamic3DTextLabelText\", Natives::UpdateDynamic3DTextLabelText },\n\t\/\/ Areas\n\t{ \"CreateDynamicCircle\", Natives::CreateDynamicCircle },\n\t{ \"CreateDynamicRectangle\", Natives::CreateDynamicRectangle },\n\t{ \"CreateDynamicSphere\", Natives::CreateDynamicSphere },\n\t{ \"CreateDynamicCube\", Natives::CreateDynamicCube },\n\t{ \"CreateDynamicPolygon\", Natives::CreateDynamicPolygon },\n\t{ \"DestroyDynamicArea\", Natives::DestroyDynamicArea },\n\t{ \"IsValidDynamicArea\", Natives::IsValidDynamicArea },\n\t{ \"GetDynamicPolygonPoints\", Natives::GetDynamicPolygonPoints },\n\t{ \"GetDynamicPolygonNumberPoints\", Natives::GetDynamicPolygonNumberPoints },\n\t{ \"TogglePlayerDynamicArea\", Natives::TogglePlayerDynamicArea },\n\t{ \"TogglePlayerAllDynamicAreas\", Natives::TogglePlayerAllDynamicAreas },\n\t{ \"IsPlayerInDynamicArea\", Natives::IsPlayerInDynamicArea },\n\t{ \"IsPlayerInAnyDynamicArea\", Natives::IsPlayerInAnyDynamicArea },\n\t{ \"IsAnyPlayerInDynamicArea\", Natives::IsAnyPlayerInDynamicArea },\n\t{ \"IsAnyPlayerInAnyDynamicArea\", Natives::IsAnyPlayerInAnyDynamicArea },\n\t{ \"IsPointInDynamicArea\", Natives::IsPointInDynamicArea },\n\t{ \"IsPointInAnyDynamicArea\", Natives::IsPointInAnyDynamicArea },\n\t{ \"GetPlayerDynamicAreas\", Natives::GetPlayerDynamicAreas },\n\t{ \"GetPlayerNumberDynamicAreas\", Natives::GetPlayerNumberDynamicAreas },\n\t{ \"AttachDynamicAreaToObject\", Natives::AttachDynamicAreaToObject },\n\t{ \"AttachDynamicAreaToPlayer\", Natives::AttachDynamicAreaToPlayer },\n\t{ \"AttachDynamicAreaToVehicle\", Natives::AttachDynamicAreaToVehicle },\n\t\/\/ Extended\n\t{ \"CreateDynamicObjectEx\", Natives::CreateDynamicObjectEx },\n\t{ \"CreateDynamicPickupEx\", Natives::CreateDynamicPickupEx },\n\t{ \"CreateDynamicCPEx\", Natives::CreateDynamicCPEx },\n\t{ \"CreateDynamicRaceCPEx\", Natives::CreateDynamicRaceCPEx },\n\t{ \"CreateDynamicMapIconEx\", Natives::CreateDynamicMapIconEx },\n\t{ \"CreateDynamic3DTextLabelEx\", Natives::CreateDynamic3DTextLabelEx },\n\t{ \"CreateDynamicCircleEx\", Natives::CreateDynamicCircleEx },\n\t{ \"CreateDynamicRectangleEx\", Natives::CreateDynamicRectangleEx },\n\t{ \"CreateDynamicSphereEx\", Natives::CreateDynamicSphereEx },\n\t{ \"CreateDynamicCubeEx\", Natives::CreateDynamicCubeEx },\n\t{ \"CreateDynamicPolygonEx\", Natives::CreateDynamicPolygonEx },\n\t\/\/ Internal\n\t{ \"Streamer_CallbackHook\", Natives::Streamer_CallbackHook },\n\t\/\/ Deprecated\n\t{ \"Streamer_TickRate\", Natives::Streamer_SetTickRate },\n\t{ \"Streamer_MaxItems\", Natives::Streamer_SetMaxItems },\n\t{ \"Streamer_VisibleItems\", Natives::Streamer_SetVisibleItems },\n\t{ \"Streamer_CellDistance\", Natives::Streamer_SetCellDistance },\n\t{ \"Streamer_CellSize\", Natives::Streamer_SetCellSize },\n\t{ \"DestroyAllDynamicObjects\", Natives::DestroyAllDynamicObjects },\n\t{ \"CountDynamicObjects\", Natives::CountDynamicObjects },\n\t{ \"DestroyAllDynamicPickups\", Natives::DestroyAllDynamicPickups },\n\t{ \"CountDynamicPickups\", Natives::CountDynamicPickups },\n\t{ \"DestroyAllDynamicCPs\", Natives::DestroyAllDynamicCPs },\n\t{ \"CountDynamicCPs\", Natives::CountDynamicCPs },\n\t{ \"DestroyAllDynamicRaceCPs\", Natives::DestroyAllDynamicRaceCPs },\n\t{ \"CountDynamicRaceCPs\", Natives::CountDynamicRaceCPs },\n\t{ \"DestroyAllDynamicMapIcons\", Natives::DestroyAllDynamicMapIcons },\n\t{ \"CountDynamicMapIcons\", Natives::CountDynamicMapIcons },\n\t{ \"DestroyAllDynamic3DTextLabels\", Natives::DestroyAllDynamic3DTextLabels },\n\t{ \"CountDynamic3DTextLabels\", Natives::CountDynamic3DTextLabels },\n\t{ \"DestroyAllDynamicAreas\", Natives::DestroyAllDynamicAreas },\n\t{ \"CountDynamicAreas\", Natives::CountDynamicAreas },\n\t{ 0, 0 }\n};\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)\n{\n\tcore->getData()->interfaces.insert(amx);\n\treturn Utility::checkInterfaceAndRegisterNatives(amx, natives);\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)\n{\n\tcore->getData()->interfaces.erase(amx);\n\tUtility::destroyAllItemsInInterface(amx);\n\treturn AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick()\n{\n\tcore->getStreamer()->startAutomaticUpdate();\n}\n<commit_msg>Fix plugin load message on Linux<commit_after>\/*\n * Copyright (C) 2014 Incognito\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"main.h\"\n\n#include \"core.h\"\n#include \"natives.h\"\n#include \"utility.h\"\n\n#include <boost\/scoped_ptr.hpp>\n\n#include <sampgdk\/core.h>\n\n#include <set>\n\ntypedef void (*logprintf_t)(const char*, ...);\n\nextern void *pAMXFunctions;\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()\n{\n\treturn SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)\n{\n\tcore.reset(new Core);\n\tpAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n\tlogprintf_t logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n\tlogprintf(\"\\n\\n*** Streamer Plugin v%s by Incognito loaded ***\\n\", PLUGIN_VERSION);\n\treturn sampgdk::Load(sampgdk::GetCurrentPluginHandle(), ppData);\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload()\n{\n\tcore.reset();\n\tsampgdk::logprintf(\"\\n\\n*** Streamer Plugin v%s by Incognito unloaded ***\\n\", PLUGIN_VERSION);\n\tsampgdk::Unload(sampgdk::GetCurrentPluginHandle());\n}\n\nAMX_NATIVE_INFO natives[] =\n{\n\t\/\/ Settings\n\t{ \"Streamer_GetTickRate\", Natives::Streamer_GetTickRate },\n\t{ \"Streamer_SetTickRate\", Natives::Streamer_SetTickRate },\n\t{ \"Streamer_GetMaxItems\", Natives::Streamer_GetMaxItems },\n\t{ \"Streamer_SetMaxItems\", Natives::Streamer_SetMaxItems },\n\t{ \"Streamer_GetVisibleItems\", Natives::Streamer_GetVisibleItems },\n\t{ \"Streamer_SetVisibleItems\", Natives::Streamer_SetVisibleItems },\n\t{ \"Streamer_GetCellDistance\", Natives::Streamer_GetCellDistance },\n\t{ \"Streamer_SetCellDistance\", Natives::Streamer_SetCellDistance },\n\t{ \"Streamer_GetCellSize\", Natives::Streamer_GetCellSize },\n\t{ \"Streamer_SetCellSize\", Natives::Streamer_SetCellSize },\n\t\/\/ Updates\n\t{ \"Streamer_ProcessActiveItems\", Natives::Streamer_ProcessActiveItems },\n\t{ \"Streamer_ToggleIdleUpdate\", Natives::Streamer_ToggleIdleUpdate },\n\t{ \"Streamer_IsToggleIdleUpdate\", Natives::Streamer_IsToggleIdleUpdate },\n\t{ \"Streamer_ToggleItemUpdate\", Natives::Streamer_ToggleItemUpdate },\n\t{ \"Streamer_IsToggleItemUpdate\", Natives::Streamer_IsToggleItemUpdate },\n\t{ \"Streamer_Update\", Natives::Streamer_Update },\n\t{ \"Streamer_UpdateEx\", Natives::Streamer_UpdateEx },\n\t\/\/ Data Manipulation\n\t{ \"Streamer_GetFloatData\", Natives::Streamer_GetFloatData },\n\t{ \"Streamer_SetFloatData\", Natives::Streamer_SetFloatData },\n\t{ \"Streamer_GetIntData\", Natives::Streamer_GetIntData },\n\t{ \"Streamer_SetIntData\", Natives::Streamer_SetIntData },\n\t{ \"Streamer_GetArrayData\", Natives::Streamer_GetArrayData },\n\t{ \"Streamer_SetArrayData\", Natives::Streamer_SetArrayData },\n\t{ \"Streamer_IsInArrayData\", Natives::Streamer_IsInArrayData },\n\t{ \"Streamer_AppendArrayData\", Natives::Streamer_AppendArrayData },\n\t{ \"Streamer_RemoveArrayData\", Natives::Streamer_RemoveArrayData },\n\t{ \"Streamer_GetUpperBound\", Natives::Streamer_GetUpperBound },\n\t\/\/ Miscellaneous\n\t{ \"Streamer_GetDistanceToItem\", Natives::Streamer_GetDistanceToItem },\n\t{ \"Streamer_GetItemInternalID\", Natives::Streamer_GetItemInternalID },\n\t{ \"Streamer_GetItemStreamerID\", Natives::Streamer_GetItemStreamerID },\n\t{ \"Streamer_IsItemVisible\", Natives::Streamer_IsItemVisible },\n\t{ \"Streamer_DestroyAllVisibleItems\", Natives::Streamer_DestroyAllVisibleItems },\n\t{ \"Streamer_CountVisibleItems\", Natives::Streamer_CountVisibleItems },\n\t{ \"Streamer_DestroyAllItems\", Natives::Streamer_DestroyAllItems },\n\t{ \"Streamer_CountItems\", Natives::Streamer_CountItems },\n\t\/\/ Objects\n\t{ \"CreateDynamicObject\", Natives::CreateDynamicObject },\n\t{ \"DestroyDynamicObject\", Natives::DestroyDynamicObject },\n\t{ \"IsValidDynamicObject\", Natives::IsValidDynamicObject },\n\t{ \"SetDynamicObjectPos\", Natives::SetDynamicObjectPos },\n\t{ \"GetDynamicObjectPos\", Natives::GetDynamicObjectPos },\n\t{ \"SetDynamicObjectRot\", Natives::SetDynamicObjectRot },\n\t{ \"GetDynamicObjectRot\", Natives::GetDynamicObjectRot },\n\t{ \"MoveDynamicObject\", Natives::MoveDynamicObject },\n\t{ \"StopDynamicObject\", Natives::StopDynamicObject },\n\t{ \"IsDynamicObjectMoving\", Natives::IsDynamicObjectMoving },\n\t{ \"AttachCameraToDynamicObject\", Natives::AttachCameraToDynamicObject },\n\t{ \"AttachDynamicObjectToVehicle\", Natives::AttachDynamicObjectToVehicle },\n\t{ \"EditDynamicObject\", Natives::EditDynamicObject },\n\t{ \"GetDynamicObjectMaterial\", Natives::GetDynamicObjectMaterial },\n\t{ \"SetDynamicObjectMaterial\", Natives::SetDynamicObjectMaterial },\n\t{ \"GetDynamicObjectMaterialText\", Natives::GetDynamicObjectMaterialText },\n\t{ \"SetDynamicObjectMaterialText\", Natives::SetDynamicObjectMaterialText },\n\t\/\/ Pickups\n\t{ \"CreateDynamicPickup\", Natives::CreateDynamicPickup },\n\t{ \"DestroyDynamicPickup\", Natives::DestroyDynamicPickup },\n\t{ \"IsValidDynamicPickup\", Natives::IsValidDynamicPickup },\n\t\/\/ Checkpoints\n\t{ \"CreateDynamicCP\", Natives::CreateDynamicCP },\n\t{ \"DestroyDynamicCP\", Natives::DestroyDynamicCP },\n\t{ \"IsValidDynamicCP\", Natives::IsValidDynamicCP },\n\t{ \"TogglePlayerDynamicCP\", Natives::TogglePlayerDynamicCP },\n\t{ \"TogglePlayerAllDynamicCPs\", Natives::TogglePlayerAllDynamicCPs },\n\t{ \"IsPlayerInDynamicCP\", Natives::IsPlayerInDynamicCP },\n\t{ \"GetPlayerVisibleDynamicCP\", Natives::GetPlayerVisibleDynamicCP },\n\t\/\/ Race Checkpoints\n\t{ \"CreateDynamicRaceCP\", Natives::CreateDynamicRaceCP },\n\t{ \"DestroyDynamicRaceCP\", Natives::DestroyDynamicRaceCP },\n\t{ \"IsValidDynamicRaceCP\", Natives::IsValidDynamicRaceCP },\n\t{ \"TogglePlayerDynamicRaceCP\", Natives::TogglePlayerDynamicRaceCP },\n\t{ \"TogglePlayerAllDynamicRaceCPs\", Natives::TogglePlayerAllDynamicRaceCPs },\n\t{ \"IsPlayerInDynamicRaceCP\", Natives::IsPlayerInDynamicRaceCP },\n\t{ \"GetPlayerVisibleDynamicRaceCP\", Natives::GetPlayerVisibleDynamicRaceCP },\n\t\/\/ Map Icons\n\t{ \"CreateDynamicMapIcon\", Natives::CreateDynamicMapIcon },\n\t{ \"DestroyDynamicMapIcon\", Natives::DestroyDynamicMapIcon },\n\t{ \"IsValidDynamicMapIcon\", Natives::IsValidDynamicMapIcon },\n\t\/\/ 3D Text Labels\n\t{ \"CreateDynamic3DTextLabel\", Natives::CreateDynamic3DTextLabel },\n\t{ \"DestroyDynamic3DTextLabel\", Natives::DestroyDynamic3DTextLabel },\n\t{ \"IsValidDynamic3DTextLabel\", Natives::IsValidDynamic3DTextLabel },\n\t{ \"GetDynamic3DTextLabelText\", Natives::GetDynamic3DTextLabelText },\n\t{ \"UpdateDynamic3DTextLabelText\", Natives::UpdateDynamic3DTextLabelText },\n\t\/\/ Areas\n\t{ \"CreateDynamicCircle\", Natives::CreateDynamicCircle },\n\t{ \"CreateDynamicRectangle\", Natives::CreateDynamicRectangle },\n\t{ \"CreateDynamicSphere\", Natives::CreateDynamicSphere },\n\t{ \"CreateDynamicCube\", Natives::CreateDynamicCube },\n\t{ \"CreateDynamicPolygon\", Natives::CreateDynamicPolygon },\n\t{ \"DestroyDynamicArea\", Natives::DestroyDynamicArea },\n\t{ \"IsValidDynamicArea\", Natives::IsValidDynamicArea },\n\t{ \"GetDynamicPolygonPoints\", Natives::GetDynamicPolygonPoints },\n\t{ \"GetDynamicPolygonNumberPoints\", Natives::GetDynamicPolygonNumberPoints },\n\t{ \"TogglePlayerDynamicArea\", Natives::TogglePlayerDynamicArea },\n\t{ \"TogglePlayerAllDynamicAreas\", Natives::TogglePlayerAllDynamicAreas },\n\t{ \"IsPlayerInDynamicArea\", Natives::IsPlayerInDynamicArea },\n\t{ \"IsPlayerInAnyDynamicArea\", Natives::IsPlayerInAnyDynamicArea },\n\t{ \"IsAnyPlayerInDynamicArea\", Natives::IsAnyPlayerInDynamicArea },\n\t{ \"IsAnyPlayerInAnyDynamicArea\", Natives::IsAnyPlayerInAnyDynamicArea },\n\t{ \"IsPointInDynamicArea\", Natives::IsPointInDynamicArea },\n\t{ \"IsPointInAnyDynamicArea\", Natives::IsPointInAnyDynamicArea },\n\t{ \"GetPlayerDynamicAreas\", Natives::GetPlayerDynamicAreas },\n\t{ \"GetPlayerNumberDynamicAreas\", Natives::GetPlayerNumberDynamicAreas },\n\t{ \"AttachDynamicAreaToObject\", Natives::AttachDynamicAreaToObject },\n\t{ \"AttachDynamicAreaToPlayer\", Natives::AttachDynamicAreaToPlayer },\n\t{ \"AttachDynamicAreaToVehicle\", Natives::AttachDynamicAreaToVehicle },\n\t\/\/ Extended\n\t{ \"CreateDynamicObjectEx\", Natives::CreateDynamicObjectEx },\n\t{ \"CreateDynamicPickupEx\", Natives::CreateDynamicPickupEx },\n\t{ \"CreateDynamicCPEx\", Natives::CreateDynamicCPEx },\n\t{ \"CreateDynamicRaceCPEx\", Natives::CreateDynamicRaceCPEx },\n\t{ \"CreateDynamicMapIconEx\", Natives::CreateDynamicMapIconEx },\n\t{ \"CreateDynamic3DTextLabelEx\", Natives::CreateDynamic3DTextLabelEx },\n\t{ \"CreateDynamicCircleEx\", Natives::CreateDynamicCircleEx },\n\t{ \"CreateDynamicRectangleEx\", Natives::CreateDynamicRectangleEx },\n\t{ \"CreateDynamicSphereEx\", Natives::CreateDynamicSphereEx },\n\t{ \"CreateDynamicCubeEx\", Natives::CreateDynamicCubeEx },\n\t{ \"CreateDynamicPolygonEx\", Natives::CreateDynamicPolygonEx },\n\t\/\/ Internal\n\t{ \"Streamer_CallbackHook\", Natives::Streamer_CallbackHook },\n\t\/\/ Deprecated\n\t{ \"Streamer_TickRate\", Natives::Streamer_SetTickRate },\n\t{ \"Streamer_MaxItems\", Natives::Streamer_SetMaxItems },\n\t{ \"Streamer_VisibleItems\", Natives::Streamer_SetVisibleItems },\n\t{ \"Streamer_CellDistance\", Natives::Streamer_SetCellDistance },\n\t{ \"Streamer_CellSize\", Natives::Streamer_SetCellSize },\n\t{ \"DestroyAllDynamicObjects\", Natives::DestroyAllDynamicObjects },\n\t{ \"CountDynamicObjects\", Natives::CountDynamicObjects },\n\t{ \"DestroyAllDynamicPickups\", Natives::DestroyAllDynamicPickups },\n\t{ \"CountDynamicPickups\", Natives::CountDynamicPickups },\n\t{ \"DestroyAllDynamicCPs\", Natives::DestroyAllDynamicCPs },\n\t{ \"CountDynamicCPs\", Natives::CountDynamicCPs },\n\t{ \"DestroyAllDynamicRaceCPs\", Natives::DestroyAllDynamicRaceCPs },\n\t{ \"CountDynamicRaceCPs\", Natives::CountDynamicRaceCPs },\n\t{ \"DestroyAllDynamicMapIcons\", Natives::DestroyAllDynamicMapIcons },\n\t{ \"CountDynamicMapIcons\", Natives::CountDynamicMapIcons },\n\t{ \"DestroyAllDynamic3DTextLabels\", Natives::DestroyAllDynamic3DTextLabels },\n\t{ \"CountDynamic3DTextLabels\", Natives::CountDynamic3DTextLabels },\n\t{ \"DestroyAllDynamicAreas\", Natives::DestroyAllDynamicAreas },\n\t{ \"CountDynamicAreas\", Natives::CountDynamicAreas },\n\t{ 0, 0 }\n};\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)\n{\n\tcore->getData()->interfaces.insert(amx);\n\treturn Utility::checkInterfaceAndRegisterNatives(amx, natives);\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)\n{\n\tcore->getData()->interfaces.erase(amx);\n\tUtility::destroyAllItemsInInterface(amx);\n\treturn AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick()\n{\n\tcore->getStreamer()->startAutomaticUpdate();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionSpelling.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionSpelling.hpp\"\n\n#include <boost\/shared_ptr.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n\n#include <core\/spelling\/SpellChecker.hpp>\n#include <core\/spelling\/HunspellDictionaryManager.hpp>\n\n#include <r\/RSexp.hpp>\n#include <r\/RRoutines.hpp>\n#include <r\/RUtil.hpp>\n#include <r\/RExec.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace spelling {\n\nnamespace {\n\nclass SpellingEngine : boost::noncopyable\n{\nprivate:\n friend SpellingEngine& spellingEngine();\n SpellingEngine()\n : dictManager_(\n session::options().hunspellDictionariesPath(),\n module_context::userScratchPath().complete(\"dictionaries\"))\n {\n }\n\npublic:\n core::spelling::hunspell::DictionaryManager& dictionaryManager()\n {\n return dictManager_;\n }\n\n core::spelling::SpellChecker& spellChecker(const std::string& langId)\n {\n if (!pSpellChecker_ || (langId != currentLangId_))\n {\n core::spelling::hunspell::Dictionary dict =\n dictManager_.dictionaryForLanguageId(langId);\n if (!dict.empty())\n {\n Error error = core::spelling::createHunspell(dict.dicPath(),\n &pSpellChecker_,\n &r::util::iconvstr);\n if (!error)\n currentLangId_ = langId;\n else\n pSpellChecker_.reset(new core::spelling::NoSpellChecker());\n }\n else\n {\n pSpellChecker_.reset(new core::spelling::NoSpellChecker());\n }\n }\n return *pSpellChecker_;\n }\n\n\nprivate:\n core::spelling::hunspell::DictionaryManager dictManager_;\n boost::shared_ptr<core::spelling::SpellChecker> pSpellChecker_;\n std::string currentLangId_;\n};\n\nSpellingEngine& spellingEngine()\n{\n static SpellingEngine instance;\n return instance;\n}\n\n\/\/ R function for testing & debugging\nSEXP rs_checkSpelling(SEXP wordSEXP)\n{\n bool isCorrect;\n std::string word = r::sexp::asString(wordSEXP);\n\n Error error = spellingEngine().spellChecker(\"en_US\").checkSpelling(\n word,\n &isCorrect);\n\n \/\/ We'll return true here so as not to tie up the front end.\n if (error)\n {\n LOG_ERROR(error);\n isCorrect = true;\n }\n\n r::sexp::Protect rProtect;\n return r::sexp::create(isCorrect, &rProtect);\n}\n\njson::Object dictionaryAsJson(const core::spelling::hunspell::Dictionary& dict)\n{\n json::Object dictJson;\n dictJson[\"id\"] = dict.id();\n dictJson[\"name\"] = dict.name();\n return dictJson;\n}\n\nFilePath userDictionariesDir()\n{\n return module_context::userScratchPath().childPath(\"dictionaries\");\n}\n\nFilePath allLanguagesDir()\n{\n return module_context::userScratchPath().childPath(\n \"dictionaries\/languages-system\");\n}\n\n\nError checkSpelling(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n bool isCorrect;\n error = spellingEngine().spellChecker(langId).checkSpelling(word,&isCorrect);\n if (error)\n return error;\n\n pResponse->setResult(isCorrect);\n\n return Success();\n}\n\nError suggestionList(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n std::vector<std::string> sugs;\n error = spellingEngine().spellChecker(langId).suggestionList(word,&sugs);\n if (error)\n return error;\n\n json::Array sugsJson;\n std::transform(sugs.begin(),\n sugs.end(),\n std::back_inserter(sugsJson),\n json::toJsonString);\n pResponse->setResult(sugsJson);\n\n return Success();\n}\n\nError addToDictionary(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n bool added;\n error = spellingEngine().spellChecker(langId).addWord(word,&added);\n if (error)\n return error;\n\n pResponse->setResult(added);\n return Success();\n}\n\nError installAllDictionaries(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ form system path to all languages dir\n std::string targetDir = string_utils::utf8ToSystem(\n allLanguagesDir().absolutePath());\n\n \/\/ perform the download\n r::exec::RFunction dlFunc(\".rs.downloadAllDictionaries\", targetDir);\n Error error = dlFunc.call();\n if (error)\n {\n std::string userMessage = r::endUserErrorMessage(error);\n pResponse->setError(error, json::Value(userMessage));\n return Success();\n }\n else\n {\n pResponse->setResult(spelling::spellingPrefsContextAsJson());\n return Success();\n }\n}\n\n\n\n} \/\/ anonymous namespace\n\n\ncore::json::Object spellingPrefsContextAsJson()\n{\n using namespace core::spelling::hunspell;\n\n core::json::Object contextJson;\n\n DictionaryManager dictManager(options().hunspellDictionariesPath(),\n userDictionariesDir());\n\n std::vector<Dictionary> dictionaries;\n Error error = dictManager.availableLanguages(&dictionaries);\n if (error)\n {\n LOG_ERROR(error);\n return core::json::Object();\n }\n\n core::json::Array dictionariesJson;\n std::transform(dictionaries.begin(),\n dictionaries.end(),\n std::back_inserter(dictionariesJson),\n dictionaryAsJson);\n\n\n \/\/ return json\n contextJson[\"all_languages_installed\"] = dictManager.allLanguagesInstalled();\n contextJson[\"available_languages\"] = dictionariesJson;\n return contextJson;\n}\n\nError initialize()\n{\n \/\/ register rs_ensureFileHidden with R\n R_CallMethodDef methodDef;\n\n methodDef.name = \"rs_checkSpelling\" ;\n methodDef.fun = (DL_FUNC) rs_checkSpelling ;\n methodDef.numArgs = 1;\n r::routines::addCallMethod(methodDef);\n\n \/\/ register rpc methods\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"check_spelling\", checkSpelling))\n (bind(registerRpcMethod, \"suggestion_list\", suggestionList))\n (bind(registerRpcMethod, \"add_to_dictionary\", addToDictionary))\n (bind(registerRpcMethod, \"install_all_dictionaries\", installAllDictionaries))\n (bind(sourceModuleRFile, \"SessionSpelling.R\"));\n return initBlock.execute();\n}\n\n\n} \/\/ namespace spelling\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<commit_msg>route spelling calls through spelling engine<commit_after>\/*\n * SessionSpelling.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionSpelling.hpp\"\n\n#include <boost\/shared_ptr.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n\n#include <core\/spelling\/SpellChecker.hpp>\n#include <core\/spelling\/HunspellDictionaryManager.hpp>\n\n#include <r\/RSexp.hpp>\n#include <r\/RRoutines.hpp>\n#include <r\/RUtil.hpp>\n#include <r\/RExec.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace spelling {\n\nnamespace {\n\nclass SpellingEngine : boost::noncopyable\n{\nprivate:\n friend SpellingEngine& spellingEngine();\n SpellingEngine()\n : dictManager_(\n session::options().hunspellDictionariesPath(),\n module_context::userScratchPath().complete(\"dictionaries\"))\n {\n }\n\npublic:\n core::spelling::hunspell::DictionaryManager& dictionaryManager()\n {\n return dictManager_;\n }\n\n Error checkSpelling(const std::string& langId,\n const std::string& word,\n bool *pCorrect)\n {\n return spellChecker(langId).checkSpelling(word, pCorrect);\n }\n\n Error suggestionList(const std::string& langId,\n const std::string& word,\n std::vector<std::string>* pSugs)\n {\n return spellChecker(langId).suggestionList(word, pSugs);\n }\n\n Error addWord(const std::string& langId,\n const std::string& word,\n bool* pAdded)\n {\n return spellChecker(langId).addWord(word, pAdded);\n }\n\nprivate:\n core::spelling::SpellChecker& spellChecker(const std::string& langId)\n {\n if (!pSpellChecker_ || (langId != currentLangId_))\n {\n core::spelling::hunspell::Dictionary dict =\n dictManager_.dictionaryForLanguageId(langId);\n if (!dict.empty())\n {\n Error error = core::spelling::createHunspell(dict.dicPath(),\n &pSpellChecker_,\n &r::util::iconvstr);\n if (!error)\n currentLangId_ = langId;\n else\n pSpellChecker_.reset(new core::spelling::NoSpellChecker());\n }\n else\n {\n pSpellChecker_.reset(new core::spelling::NoSpellChecker());\n }\n }\n return *pSpellChecker_;\n }\n\n\nprivate:\n core::spelling::hunspell::DictionaryManager dictManager_;\n boost::shared_ptr<core::spelling::SpellChecker> pSpellChecker_;\n std::string currentLangId_;\n};\n\nSpellingEngine& spellingEngine()\n{\n static SpellingEngine instance;\n return instance;\n}\n\n\/\/ R function for testing & debugging\nSEXP rs_checkSpelling(SEXP wordSEXP)\n{\n bool isCorrect;\n std::string word = r::sexp::asString(wordSEXP);\n\n Error error = spellingEngine().checkSpelling(\"en_US\", word, &isCorrect);\n\n \/\/ We'll return true here so as not to tie up the front end.\n if (error)\n {\n LOG_ERROR(error);\n isCorrect = true;\n }\n\n r::sexp::Protect rProtect;\n return r::sexp::create(isCorrect, &rProtect);\n}\n\njson::Object dictionaryAsJson(const core::spelling::hunspell::Dictionary& dict)\n{\n json::Object dictJson;\n dictJson[\"id\"] = dict.id();\n dictJson[\"name\"] = dict.name();\n return dictJson;\n}\n\nFilePath userDictionariesDir()\n{\n return module_context::userScratchPath().childPath(\"dictionaries\");\n}\n\nFilePath allLanguagesDir()\n{\n return module_context::userScratchPath().childPath(\n \"dictionaries\/languages-system\");\n}\n\n\nError checkSpelling(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n bool isCorrect;\n error = spellingEngine().checkSpelling(langId, word, &isCorrect);\n if (error)\n return error;\n\n pResponse->setResult(isCorrect);\n\n return Success();\n}\n\nError suggestionList(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n std::vector<std::string> sugs;\n error = spellingEngine().suggestionList(langId, word, &sugs);\n if (error)\n return error;\n\n json::Array sugsJson;\n std::transform(sugs.begin(),\n sugs.end(),\n std::back_inserter(sugsJson),\n json::toJsonString);\n pResponse->setResult(sugsJson);\n\n return Success();\n}\n\nError addToDictionary(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string langId, word;\n Error error = json::readParams(request.params, &langId, &word);\n if (error)\n return error;\n\n bool added;\n error = spellingEngine().addWord(langId, word, &added);\n if (error)\n return error;\n\n pResponse->setResult(added);\n return Success();\n}\n\nError installAllDictionaries(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ form system path to all languages dir\n std::string targetDir = string_utils::utf8ToSystem(\n allLanguagesDir().absolutePath());\n\n \/\/ perform the download\n r::exec::RFunction dlFunc(\".rs.downloadAllDictionaries\", targetDir);\n Error error = dlFunc.call();\n if (error)\n {\n std::string userMessage = r::endUserErrorMessage(error);\n pResponse->setError(error, json::Value(userMessage));\n return Success();\n }\n else\n {\n pResponse->setResult(spelling::spellingPrefsContextAsJson());\n return Success();\n }\n}\n\n\n\n} \/\/ anonymous namespace\n\n\ncore::json::Object spellingPrefsContextAsJson()\n{\n using namespace core::spelling::hunspell;\n\n core::json::Object contextJson;\n\n DictionaryManager dictManager(options().hunspellDictionariesPath(),\n userDictionariesDir());\n\n std::vector<Dictionary> dictionaries;\n Error error = dictManager.availableLanguages(&dictionaries);\n if (error)\n {\n LOG_ERROR(error);\n return core::json::Object();\n }\n\n core::json::Array dictionariesJson;\n std::transform(dictionaries.begin(),\n dictionaries.end(),\n std::back_inserter(dictionariesJson),\n dictionaryAsJson);\n\n\n \/\/ return json\n contextJson[\"all_languages_installed\"] = dictManager.allLanguagesInstalled();\n contextJson[\"available_languages\"] = dictionariesJson;\n return contextJson;\n}\n\nError initialize()\n{\n \/\/ register rs_ensureFileHidden with R\n R_CallMethodDef methodDef;\n\n methodDef.name = \"rs_checkSpelling\" ;\n methodDef.fun = (DL_FUNC) rs_checkSpelling ;\n methodDef.numArgs = 1;\n r::routines::addCallMethod(methodDef);\n\n \/\/ register rpc methods\n using boost::bind;\n using namespace module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"check_spelling\", checkSpelling))\n (bind(registerRpcMethod, \"suggestion_list\", suggestionList))\n (bind(registerRpcMethod, \"add_to_dictionary\", addToDictionary))\n (bind(registerRpcMethod, \"install_all_dictionaries\", installAllDictionaries))\n (bind(sourceModuleRFile, \"SessionSpelling.R\"));\n return initBlock.execute();\n}\n\n\n} \/\/ namespace spelling\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Christian Surlykke <christian@surlykke.dk>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <razorqt\/razorapplication.h>\n#include \"razortranslate.h\"\n#include \"razorautosuspend.h\"\n\n#include <QMessageBox>\n\nint main(int argc, char *argv[])\n{\n\n RazorApplication a(argc, argv);\n\n TRANSLATE_APP;\n\n \/*TrayIcon w;\n w.show();*\/\n RazorAutosuspendd razorAutosuspendd;\n return a.exec();\n}\n<commit_msg>razor-autosuspend registers as dbus-service (org.razor-qt.razor-autosuspend) - fixes #346<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Christian Surlykke <christian@surlykke.dk>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QDBusConnection>\n#include <QDebug>\n\n#include <razorqt\/razorapplication.h>\n#include \"razortranslate.h\"\n#include \"razorautosuspend.h\"\n\nint main(int argc, char *argv[])\n{\n\n RazorApplication a(argc, argv);\n\n TRANSLATE_APP;\n\n \/\/ To ensure only one instance of razor-autosuspend is running we register as a DBus service and refuse to run\n \/\/ if not able to do so.\n \/\/ We do not register any object as we don't have any dbus-operations to expose.g\n if (! QDBusConnection::sessionBus().registerService(\"org.razor-qt.razor-autosuspend\"))\n {\n qWarning() << \"Unable to register 'org.razor-qt.razor-autosuspend' service - is another instance of razor-autosuspend running?\";\n return 1;\n }\n else\n {\n RazorAutosuspendd razorAutosuspendd;\n return a.exec();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"client.h\"\n#include \"config.h\"\n#include \"curses.h\"\n#include \"log.h\"\n#include \"queue.h\"\n\n#include <cstdlib>\n#include <experimental\/filesystem>\n#include <iostream>\n#include <memory>\n#include <queue>\n#include <thread>\n\nvoid client_runner(Client& client) {\n client.run();\n}\n\nvoid client_reader(Client& client, std::queue<std::string>& read_q, queue<bool>& end_signal) {\n while (true) {\n const auto line = client.read();\n if (line != \"\") {\n read_q.push(line);\n }\n if (!end_signal.empty()) {\n end_signal.pop();\n break;\n }\n }\n}\n\nint main(int argc, char** argv) {\n fs::path config_path;\n if (argc > 1) {\n config_path = argv[1];\n } else {\n config_path = fs::path(getenv(\"HOME\")) \/ \".config\/courier\/courier.conf\";\n }\n\n Config config(config_path);\n if (!config.okay) {\n return 1;\n }\n\n const auto host = config.get(\"host\");\n const auto port = config.get(\"port\");\n\n if (!host) {\n std::cerr << \"IMAP host not found in config\" << std::endl;\n return 1;\n }\n\n if (!port) {\n std::cerr << \"IMAP port not found in config\" << std::endl;\n return 1;\n }\n\n const auto user = config.get(\"user\");\n const auto pass = config.get(\"pass\");\n\n if (!user || !pass) {\n std::cerr << \"IMAP user or password not found in config\" << std::endl;\n return 1;\n }\n\n Client client(*host, *port);\n Log logfile(\"courier.log\");\n\n if (!client.connect()) {\n return 1;\n } else {\n logfile.info(\"Connected to \" + *host + \":\" + *port);\n }\n\n std::queue<std::string> read_q;\n queue<bool> end_signal;\n std::thread client_thread([&client]() {\n client_runner(client);\n });\n std::thread client_reader_thread([&client, &read_q, &end_signal]() {\n client_reader(client, read_q, end_signal);\n });\n\n curses::init();\n\n const auto dim = curses::dimensions();\n\n curses::Window input(0, std::get<1>(dim) - 5, std::get<0>(dim), 5);\n input.add_border();\n input.write_string(1, 1, \"> \");\n input.disable_delay();\n\n client.login(*user, *pass);\n\n bool running = true;\n std::string buf;\n buf.reserve(256);\n while (running) {\n while (!read_q.empty()) {\n logfile.info(\"< \" + read_q.front());\n read_q.pop();\n input.move_cursor(3 + buf.length(), 1);\n }\n\n char c = input.get_char();\n if (c < 0) {\n continue;\n } else if (c == 27) { \/\/ Escape\n client.stop();\n end_signal.push(true);\n running = false;\n } else if (c == 13) { \/\/ Enter\n if (buf == \"\") {\n continue;\n }\n const auto line = client.next_id() + \" \" + buf;\n client.write(line);\n logfile.info(\"> \" + line);\n buf.clear();\n input.clear_line(1);\n input.write_string(1, 1, \"> \");\n } else if (c == 8 || c == 127) { \/\/ Backspace\n buf = buf.substr(0, buf.length() - 1);\n input.delete_char(3 + buf.length(), 1);\n } else {\n buf += c;\n \/\/ \"|> \"\n input.write_char(2 + buf.length(), 1, c);\n }\n }\n\n client_thread.join();\n client_reader_thread.join();\n\n curses::cleanup();\n\n return 0;\n}\n<commit_msg>Fix end signal<commit_after>#include \"client.h\"\n#include \"config.h\"\n#include \"curses.h\"\n#include \"log.h\"\n#include \"queue.h\"\n\n#include <atomic>\n#include <cstdlib>\n#include <experimental\/filesystem>\n#include <iostream>\n#include <memory>\n#include <queue>\n#include <thread>\n\nvoid client_reader(Client& client, std::queue<std::string>& read_q, std::atomic<bool>& running) {\n while (true) {\n const auto line = client.read();\n if (!line.empty()) {\n read_q.push(line);\n }\n if (!running) {\n break;\n }\n }\n}\n\nint main(int argc, char** argv) {\n fs::path config_path;\n if (argc > 1) {\n config_path = argv[1];\n } else {\n config_path = fs::path(getenv(\"HOME\")) \/ \".config\/courier\/courier.conf\";\n }\n\n Config config(config_path);\n if (!config.okay) {\n return 1;\n }\n\n const auto host = config.get(\"host\");\n const auto port = config.get(\"port\");\n\n if (!host) {\n std::cerr << \"IMAP host not found in config\" << std::endl;\n return 1;\n }\n\n if (!port) {\n std::cerr << \"IMAP port not found in config\" << std::endl;\n return 1;\n }\n\n const auto user = config.get(\"user\");\n const auto pass = config.get(\"pass\");\n\n if (!user || !pass) {\n std::cerr << \"IMAP user or password not found in config\" << std::endl;\n return 1;\n }\n\n Client client(*host, *port);\n Log logfile(\"courier.log\");\n\n if (!client.connect()) {\n return 1;\n } else {\n logfile.info(\"Connected to \" + *host + \":\" + *port);\n }\n\n std::atomic<bool> running;\n running.store(true);\n std::queue<std::string> read_q;\n std::thread client_thread([&client]() {\n client.run();\n });\n std::thread client_reader_thread([&client, &read_q, &running]() {\n client_reader(client, read_q, running);\n });\n\n curses::init();\n\n const auto dim = curses::dimensions();\n\n curses::Window input(0, std::get<1>(dim) - 5, std::get<0>(dim), 5);\n input.add_border();\n input.write_string(1, 1, \"> \");\n input.disable_delay();\n\n client.login(*user, *pass);\n\n std::string buf;\n buf.reserve(256);\n while (running) {\n while (!read_q.empty()) {\n logfile.info(\"< \" + read_q.front());\n read_q.pop();\n input.move_cursor(3 + buf.length(), 1);\n }\n\n char c = input.get_char();\n if (c < 0) {\n continue;\n } else if (c == 27) { \/\/ Escape\n client.stop();\n running.store(false);\n } else if (c == 13) { \/\/ Enter\n if (buf.empty()) {\n continue;\n }\n const auto line = client.next_id() + \" \" + buf;\n client.write(line);\n logfile.info(\"> \" + line);\n buf.clear();\n input.clear_line(1);\n input.write_string(1, 1, \"> \");\n } else if (c == 8 || c == 127) { \/\/ Backspace\n buf = buf.substr(0, buf.length() - 1);\n input.delete_char(3 + buf.length(), 1);\n } else {\n buf += c;\n \/\/ \"|> \"\n input.write_char(2 + buf.length(), 1, c);\n }\n }\n\n client_thread.join();\n client_reader_thread.join();\n\n curses::cleanup();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n\n#include <iostream>\n#include <memory>\n\n#include \"UI\/console.hpp\"\n#include \"pawn.hpp\"\n\nint main()\n{\n Quoridor::UI::Console console(2);\n console.run();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Parse cmd with boost program_options.<commit_after>#include <cstdlib>\n\n#include <iostream>\n#include <memory>\n\n#include <boost\/program_options.hpp>\n\n#include \"UI\/console.hpp\"\n#include \"pawn.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char **argv)\n{\n po::options_description options(\"Options\");\n options.add_options()\n (\"players,p\", po::value<int>(), \"number of players\")\n (\"help,h\", \"show help message\")\n ;\n po::variables_map vm;\n\n try {\n po::store(po::parse_command_line(argc, argv, options), vm);\n }\n catch (po::error &e) {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << options << std::endl;\n return EXIT_FAILURE;\n }\n\n int players = 2;\n if (vm.count(\"players\")) {\n players = vm[\"players\"].as<int>();\n }\n\n Quoridor::UI::Console console(players);\n console.run();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tOptimal Read Normalization Algorithm:\n\tDeveloped by : Dilip A Durai and Marcel H Schulz\n\tORNA uses GATB library for graph building and k-mer counting. We are thankful for their support\n*\/\n\n#include <gatb\/gatb_core.hpp>\n#include <iostream>\n#include <string.h>\n#include <math.h>\n#include <algorithm>\n\ntypedef Kmer<>::Type bloom;\nstatic const char* STR_BASE = \"-base\";\nstatic const char* STR_INPUT = \"-input\";\nstatic const char* STR_OUTPUT = \"-output\";\nstatic const char* STR_KMER = \"-kmer\";\nstatic const char* STR_PAIR1 = \"-pair1\";\nstatic const char* STR_PAIR2 = \"-pair2\";\n\nint readacceptance(Graph graph, Kmer<>::ModelCanonical::Iterator itKmer, Kmer<>::ModelCanonical model, unsigned short *counter, double base){\n\tint acceptance=0;\n\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t{\n\t\tstd::string s = model.toString (itKmer->value());\n\t\tconst char* sq = s.c_str();\n\t\tNode node = graph.buildNode(sq);\n\t\tdouble threshold=0;\n\t\t\/\/Checking whether the node exists.\n\t\tauto index = graph.nodeMPHFIndex(node);\n\t\tauto abund = graph.queryAbundance(node);\n\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\tif(threshold>abund)\n\t\t{\n\t\t\tthreshold=abund;\n\t\t}\n\t\tif(threshold<1)\n\t\t{\n\t\t\tthreshold=1;\n\t\t}\n\t\tif(counter[index] < threshold)\n\t\t{\n\t\t\tacceptance=acceptance+1;\n\t\t\tbreak;\t\t\t\n\t\t\t\/\/__sync_fetch_and_add (&counter[index], 1);\n\t \t}\n\t}\n\treturn acceptance;\n}\n\nvoid singleend(const char* filename, const char* out_file, double base, unsigned short kmer, int nbCores)\n{\n\tint count=0;\n\t\n\t\/\/Multithreading functionality provided by GATB library\n\tDispatcher dispatcher(nbCores) ;\n\tISynchronizer* sync = System::thread().newSynchronizer();\t\/\/Locking a section\n\n\t\/\/Variables required for GATB\n\tIBank* InputDataset = Bank::open (filename);\n\tProgressIterator<Sequence> itSeq (*InputDataset);\n\tIBank* OutDataset = new BankFasta (out_file);\n\t\n\t\/\/Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1\n\tGraph graph = Graph::create (Bank::open(filename), \"-kmer-size %d -abundance-min 1\", kmer);\n\tGraphIterator<Node> it = graph.iterator();\n\n\tlong node_size= it.size();\n\tunsigned short *counter = new unsigned short[node_size];\n\n\t\/\/Initializing the counter for each node in the de Bruijn graph\n\tfor(int i=0;i<node_size;i++)\n\t{\n\t counter[i]=0;\n\t}\n\n\t\/\/Iterating over sequences the GATB way\n\tdispatcher.iterate (itSeq, [&] (Sequence& seq)\n\t{\n\t\tint length = seq.getDataSize();\n\t\tint flag=1;\n\t\tint gb = 1;\n\t\tint acceptance=0;\n\n\t\tKmer<>::ModelCanonical model (kmer);\n\t\tKmer<>::ModelCanonical::Iterator itKmer (model);\n\t\titKmer.setData (seq.getData());\n\t\tchar* data = seq.getDataBuffer();\n\t\n\t\t\/\/checking the thresholding\n\t\tif(flag==1){\n\t\t\tacceptance=readacceptance(graph, itKmer, model, counter, base);\n\t\t}\n\t\tif(acceptance > 0)\n\t\t{\n\t\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t\t\t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str(); \n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node))\n\t \t\t\t{\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\t__sync_fetch_and_add (&counter[index], 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsync->lock();\n\t\t\tOutDataset->insert(seq);\n\t\t\tcount++;\n\t\t\tsync->unlock();\n\t\t}\n\n\t});\n\tstd::cout << \"Kept \" << count << \" reads\" << std::endl;\n\n\t\/\/Free the memory\n\tstd::string filename1 = string(filename).substr(string(filename).find_last_of(\"\/\\\\\") + 1);\n\tsize_t lindex = filename1.find_last_of(\".\");\n\tfilename1 = (filename1.substr(0,lindex)) + string(\".h5\");\n\tremove(filename1.c_str());\n\t\n\tdelete [] counter;\n\tInputDataset->flush();\n\tOutDataset->flush();\t\n}\n\nvoid pairedend(const char* read1, const char* read2, const char* out_file, double base, unsigned short kmer )\n{\n\tIBank* InputDataset1 = Bank::open (read1); \n\tLOCAL (InputDataset1);\n IBank* InputDataset2 = Bank::open (read2); \n\tLOCAL (InputDataset2);\n\t\n\tIBank* OutDataset = new BankFasta (out_file);\n\n\tGraph graph = Graph::create (\"-in %s,%s -kmer-size %d -abundance-min 1\", read1, read2, kmer);\n\tGraphIterator<Node> NodeIterator = graph.iterator();\t\n\tlong node_size= NodeIterator.size();\n\tunsigned short *counter = new unsigned short[node_size];\n\t\n\tfor(int i=0;i<node_size;i++)\n {\n counter[i]=0;\n }\n\n\tint cnt=0;\n\tint count=0;\n\tint num_sequence=0;\t\n\tint *pos;\t\n\tint size;\n\tint index;\n\tunsigned short length;\n\tint tmp=0;\n\t\n\t\/\/Iterating paired end sequences using GATB's paired end iterator\t\n PairedIterator<Sequence> itPair (InputDataset1->iterator(), InputDataset2->iterator());\n for(itPair.first(); !itPair.isDone(); itPair.next())\n {\n \tnum_sequence++;\n }\n std::vector<int> tempBank;\n\t\n\tKmer<>::ModelCanonical model (kmer);\n\tKmer<>::ModelCanonical::Iterator itKmer (model);\n\tKmer<>::ModelCanonical::Iterator itKmer1 (model);\n \n\t\/\/Iteration 1\t\n\t \n\tfor (itPair.first(); !itPair.isDone(); itPair.next())\n {\n Sequence& s1 = itPair.item().first;\n Sequence& s2 = itPair.item().second;\n\t \n\t int acceptance1=0;\n\t int acceptance2=0;\n\n\t itKmer.setData (s1.getData());\n\t itKmer1.setData (s2.getData());\n\t \t \n\t \/\/checking the threshold\n\t acceptance1 = readacceptance(graph, itKmer, model, counter, base);\n\t acceptance2 = readacceptance(graph, itKmer1, model, counter, base);\n\t if(acceptance1 > 0 && acceptance2>0)\n\t {\n\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t \t{\n\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\tconst char* sq = s.c_str();\n\t\t\tNode node = graph.buildNode(sq);\n\t\t\tdouble threshold=0;\n\t\t\t\/\/Checking whether the node exists.\n\t\t\tif(graph.contains(node))\n\t\t\t{\n\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\tif(threshold>abund)\n\t\t\t\t{\n\t\t\t\t\tthreshold=abund;\n\t\t\t\t}\n\t\t\t\tif(threshold<1)\n\t\t\t\t{\n\t\t\t\t\tthreshold=1;\n\t\t\t\t}\n\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t{\n\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())\n\t \t{\n\t\t\tstd::string s = model.toString (itKmer1->value());\n\t\t\tconst char* sq = s.c_str();\n\t\t\tNode node = graph.buildNode(sq);\n\t\t\tdouble threshold=0;\n\t\t\t\/\/Checking whether the node exists.\n\t\t\tif(graph.contains(node))\n\t\t\t{\n\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\tif(threshold>abund)\n\t\t\t\t{\n\t\t\t\t\tthreshold=abund;\n\t\t\t\t}\n\t\t\t\tif(threshold<1)\n\t\t\t\t{\n\t\t\t\t\tthreshold=1;\n\t\t\t\t}\n\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t{\n\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t}\n\t\t\t}\n\t \t}\n\t \tOutDataset->insert(s1);\n\t\tOutDataset->insert(s2);\n\t\tcount++;\n\t }\n\t else if(acceptance1>0 || acceptance2>0){\n\t \ttempBank.push_back(tmp);\n\t }\n\t else{\n\t }\n\t tmp++;\n }\n \n\tint coun=0;\n\tint tmp_index=0;\n\tstd::cout << \"Second Iteration\" << std::endl;\n\t\n\tfor (itPair.first(); !itPair.isDone() && tmp_index<tempBank.size(); itPair.next())\n\t{\n \tif(coun==tempBank[tmp_index])\n \t{\n\t\t Sequence& s1 = itPair.item().first;\n\t\t Sequence& s2 = itPair.item().second;\n\t\t \n\t\t int acceptance1=0;\n\t\t int acceptance2=0;\n\t\t int acceptance=0;\n\n\t\t itKmer.setData (s1.getData());\n\t\t itKmer1.setData (s2.getData());\n\t\t \t \n\t\t \/\/checking the threshold\n\t\t acceptance1 = readacceptance(graph, itKmer, model, counter, base);\n\t\t acceptance2 = readacceptance(graph, itKmer1, model, counter, base);\n\t\t \t \n\t\t if(acceptance1 > 0 || acceptance2 > 0)\n\t\t {\n\t\t\tfor (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())\n\t\t \t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str();\n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\tdouble threshold=0;\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node)){\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\t\tif(threshold>abund){\n\t\t\t\t\t\tthreshold=abund;\n\t\t\t\t\t}\n\t\t\t\t\tif(threshold<1){\n\t\t\t\t\t\tthreshold=1;\n\t\t\t\t\t}\n\t\t\t\t\tif(counter[index] < threshold){\n\t\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t\t \t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str();\n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\tdouble threshold=0;\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node))\n\t\t\t\t{\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\t\tif(threshold>abund)\n\t\t\t\t\t{\n\t\t\t\t\t\tthreshold=abund;\n\t\t\t\t\t}\n\t\t\t\t\tif(threshold<1)\n\t\t\t\t\t{\n\t\t\t\t\t\tthreshold=1;\n\t\t\t\t\t}\n\t\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t\t{\n\t\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t \t}\n\t\t\tOutDataset->insert(s1);\n\t\t\tOutDataset->insert(s2);\n\t\t\tcount++;\n\t\t }\n\t\t tmp_index++;\n\t\t}\n\t\tcoun++;\n }\n\tstd::cout << \"kept \" << count << \" reads\" << std::endl;\n\tbank1->flush();\n\tbank2->flush();\n\tdelete [] counter;\n\toutBank->flush();\n}\n\n\nclass ORNA : public Tool\n{\npublic:\n\tORNA(): Tool(\"ORNA\")\n\t{\n\t\tgetParser()->push_front (new OptionOneParam (STR_KMER, \"kmer required\", false, \"21\"));\n\t getParser()->push_front (new OptionOneParam (STR_INPUT, \"Input File\", false, \"ORNAERROR\"));\n\t getParser()->push_front (new OptionOneParam (STR_OUTPUT, \"Output File\", false, \"Normalized.fa\"));\n\t\tgetParser()->push_front (new OptionOneParam (STR_BASE, \"Base for the logarithmic function\", false, \"1.7\"));\n\t\tgetParser()->push_front (new OptionOneParam (STR_PAIR1, \"First read of the pair\", false, \"ORNAERROR\" ));\n\t\tgetParser()->push_front (new OptionOneParam (STR_PAIR2, \"Second read of the pair\", false, \"ORNAERROR\" ));\n\t}\n\tvoid execute()\n\t{\n\t\tconst char* filename = (getInput()->get(STR_INPUT))->getString();\n\t\tconst char* read1= (getInput()->get(STR_PAIR1))->getString(); \n\t\tconst char* read2= (getInput()->get(STR_PAIR2))->getString();\n\t\tdouble base=getInput()->getDouble(STR_BASE);\n\t\tint user_kmer = getInput()->getInt(STR_KMER);\n\t\tconst char* out_file= (getInput()->get(STR_OUTPUT))->getString();\n\t\tint nbCores = getInput()->getInt(STR_NB_CORES);\n\t\tunsigned short pairflag = 0; \n\t\tunsigned short kmer = user_kmer + 1; \n\t\tunsigned short cores = sysconf(_SC_NPROCESSORS_ONLN); \n\t\tif(nbCores==cores){\n\t\t\tnbCores=1;\t\t\n\t\t} \n\t\tif(std::strcmp(filename, \"ORNAERROR\") == 0)\n\t\t{\n\t\t\tif((std::strcmp(read1, \"ORNAERROR\") == 0) && (std::strcmp(read2, \"ORNAERROR\") == 0))\n\t\t\t{\n\t\t\t\tstd::cout << \"Input File(s) missing. Please refer to the help\" << std::endl;\n\t\t\t}\n\t\t\tif (((std::strcmp(read1, \"ORNAERROR\") != 0) && (std::strcmp(read2, \"ORNAERROR\") == 0)) || ((std::strcmp(read1, \"ORNAERROR\") == 0) && (std::strcmp(read2, \"ORNAERROR\") != 0)))\n\t\t\t{\n\t\t\t\tstd::cout << \"One of the pair files is missing. Please refer to the help\" << std::endl;\t\n\t\t\t}\n\t\t\tif((std::strcmp(read1, \"ORNAERROR\") != 0) && (std::strcmp(read2, \"ORNAERROR\") != 0))\n\t\t\t{\n\t\t\t\tpairflag = 1; \n\t\t\t}\t\t\t\t\n\t\t}\n\t\tif(pairflag==0)\n\t\t{\n\t\t\tstd::cout << \"Running ORNA in single end mode\" << std::endl;\n\t\t\tsingleend(filename, out_file, base, kmer, nbCores);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Running ORNA in paired end mode\" << std::endl;\n\t\t\tpairedend(read1, read2, out_file, base, kmer);\n\t\t}\t\n\t}\n};\n\nint main (int argc, char* argv[])\n{\n\ttry{\n\t\tORNA().run(argc,argv);\n\t\treturn EXIT_SUCCESS;\t\n\t}\n\tcatch(Exception& e){\n\t\tstd::cout << \"EXCEPTION: \" << e.getMessage() << std::endl;\n \treturn EXIT_FAILURE;\n\t}\n \t\n}\n\n\n<commit_msg>Update main.cpp<commit_after>\/*\n\tOptimal Read Normalization Algorithm:\n\tDeveloped by : Dilip A Durai and Marcel H Schulz\n\tORNA uses GATB library for graph building and k-mer counting. We are thankful for their support\n*\/\n\n#include <gatb\/gatb_core.hpp>\n#include <iostream>\n#include <string.h>\n#include <math.h>\n#include <algorithm>\n\ntypedef Kmer<>::Type bloom;\nstatic const char* STR_BASE = \"-base\";\nstatic const char* STR_INPUT = \"-input\";\nstatic const char* STR_OUTPUT = \"-output\";\nstatic const char* STR_KMER = \"-kmer\";\nstatic const char* STR_PAIR1 = \"-pair1\";\nstatic const char* STR_PAIR2 = \"-pair2\";\n\nint readacceptance(Graph graph, Kmer<>::ModelCanonical::Iterator itKmer, Kmer<>::ModelCanonical model, unsigned short *counter, double base){\n\tint acceptance=0;\n\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t{\n\t\tstd::string s = model.toString (itKmer->value());\n\t\tconst char* sq = s.c_str();\n\t\tNode node = graph.buildNode(sq);\n\t\tdouble threshold=0;\n\t\t\/\/Checking whether the node exists.\n\t\tauto index = graph.nodeMPHFIndex(node);\n\t\tauto abund = graph.queryAbundance(node);\n\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\tif(threshold>abund)\n\t\t{\n\t\t\tthreshold=abund;\n\t\t}\n\t\tif(threshold<1)\n\t\t{\n\t\t\tthreshold=1;\n\t\t}\n\t\tif(counter[index] < threshold)\n\t\t{\n\t\t\tacceptance=acceptance+1;\n\t\t\tbreak;\t\t\t\n\t\t\t\/\/__sync_fetch_and_add (&counter[index], 1);\n\t \t}\n\t}\n\treturn acceptance;\n}\n\nvoid singleend(const char* filename, const char* out_file, double base, unsigned short kmer, int nbCores)\n{\n\tint count=0;\n\t\n\t\/\/Multithreading functionality provided by GATB library\n\tDispatcher dispatcher(nbCores) ;\n\tISynchronizer* sync = System::thread().newSynchronizer();\t\/\/Locking a section\n\n\t\/\/Variables required for GATB\n\tIBank* InputDataset = Bank::open (filename);\n\tProgressIterator<Sequence> itSeq (*InputDataset);\n\tIBank* OutDataset = new BankFasta (out_file);\n\t\n\t\/\/Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1\n\tGraph graph = Graph::create (Bank::open(filename), \"-kmer-size %d -abundance-min 1\", kmer);\n\tGraphIterator<Node> it = graph.iterator();\n\n\tlong node_size= it.size();\n\tunsigned short *counter = new unsigned short[node_size];\n\n\t\/\/Initializing the counter for each node in the de Bruijn graph\n\tfor(int i=0;i<node_size;i++)\n\t{\n\t counter[i]=0;\n\t}\n\n\t\/\/Iterating over sequences the GATB way\n\tdispatcher.iterate (itSeq, [&] (Sequence& seq)\n\t{\n\t\tint length = seq.getDataSize();\n\t\tint flag=1;\n\t\tint gb = 1;\n\t\tint acceptance=0;\n\n\t\tKmer<>::ModelCanonical model (kmer);\n\t\tKmer<>::ModelCanonical::Iterator itKmer (model);\n\t\titKmer.setData (seq.getData());\n\t\tchar* data = seq.getDataBuffer();\n\t\n\t\t\/\/checking the thresholding\n\t\tif(flag==1){\n\t\t\tacceptance=readacceptance(graph, itKmer, model, counter, base);\n\t\t}\n\t\tif(acceptance > 0)\n\t\t{\n\t\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t\t\t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str(); \n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node))\n\t \t\t\t{\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\t__sync_fetch_and_add (&counter[index], 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsync->lock();\n\t\t\tOutDataset->insert(seq);\n\t\t\tcount++;\n\t\t\tsync->unlock();\n\t\t}\n\n\t});\n\tstd::cout << \"Kept \" << count << \" reads\" << std::endl;\n\n\t\/\/Free the memory\n\tstd::string filename1 = string(filename).substr(string(filename).find_last_of(\"\/\\\\\") + 1);\n\tsize_t lindex = filename1.find_last_of(\".\");\n\tfilename1 = (filename1.substr(0,lindex)) + string(\".h5\");\n\tremove(filename1.c_str());\n\t\n\tdelete [] counter;\n\tInputDataset->flush();\n\tOutDataset->flush();\t\n}\n\nvoid pairedend(const char* read1, const char* read2, const char* out_file, double base, unsigned short kmer )\n{\n\tIBank* InputDataset1 = Bank::open (read1); \n\tLOCAL (InputDataset1);\n IBank* InputDataset2 = Bank::open (read2); \n\tLOCAL (InputDataset2);\n\t\n\tIBank* OutDataset = new BankFasta (out_file);\n\n\tGraph graph = Graph::create (\"-in %s,%s -kmer-size %d -abundance-min 1\", read1, read2, kmer);\n\tGraphIterator<Node> NodeIterator = graph.iterator();\t\n\tlong node_size= NodeIterator.size();\n\tunsigned short *counter = new unsigned short[node_size];\n\t\n\tfor(int i=0;i<node_size;i++)\n {\n counter[i]=0;\n }\n\n\tint cnt=0;\n\tint count=0;\n\tint num_sequence=0;\t\n\tint *pos;\t\n\tint size;\n\tint index;\n\tunsigned short length;\n\tint tmp=0;\n\t\n\t\/\/Iterating paired end sequences using GATB's paired end iterator\t\n PairedIterator<Sequence> itPair (InputDataset1->iterator(), InputDataset2->iterator());\n for(itPair.first(); !itPair.isDone(); itPair.next())\n {\n \tnum_sequence++;\n }\n std::vector<int> tempBank;\n\t\n\tKmer<>::ModelCanonical model (kmer);\n\tKmer<>::ModelCanonical::Iterator itKmer (model);\n\tKmer<>::ModelCanonical::Iterator itKmer1 (model);\n \n\t\/\/Iteration 1\t\n\t \n\tfor (itPair.first(); !itPair.isDone(); itPair.next())\n {\n Sequence& s1 = itPair.item().first;\n Sequence& s2 = itPair.item().second;\n\t \n\t int acceptance1=0;\n\t int acceptance2=0;\n\n\t itKmer.setData (s1.getData());\n\t itKmer1.setData (s2.getData());\n\t \t \n\t \/\/checking the threshold\n\t acceptance1 = readacceptance(graph, itKmer, model, counter, base);\n\t acceptance2 = readacceptance(graph, itKmer1, model, counter, base);\n\t if(acceptance1 > 0 && acceptance2>0)\n\t {\n\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t \t{\n\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\tconst char* sq = s.c_str();\n\t\t\tNode node = graph.buildNode(sq);\n\t\t\tdouble threshold=0;\n\t\t\t\/\/Checking whether the node exists.\n\t\t\tif(graph.contains(node))\n\t\t\t{\n\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\tif(threshold>abund)\n\t\t\t\t{\n\t\t\t\t\tthreshold=abund;\n\t\t\t\t}\n\t\t\t\tif(threshold<1)\n\t\t\t\t{\n\t\t\t\t\tthreshold=1;\n\t\t\t\t}\n\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t{\n\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())\n\t \t{\n\t\t\tstd::string s = model.toString (itKmer1->value());\n\t\t\tconst char* sq = s.c_str();\n\t\t\tNode node = graph.buildNode(sq);\n\t\t\tdouble threshold=0;\n\t\t\t\/\/Checking whether the node exists.\n\t\t\tif(graph.contains(node))\n\t\t\t{\n\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\tif(threshold>abund)\n\t\t\t\t{\n\t\t\t\t\tthreshold=abund;\n\t\t\t\t}\n\t\t\t\tif(threshold<1)\n\t\t\t\t{\n\t\t\t\t\tthreshold=1;\n\t\t\t\t}\n\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t{\n\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t}\n\t\t\t}\n\t \t}\n\t \tOutDataset->insert(s1);\n\t\tOutDataset->insert(s2);\n\t\tcount++;\n\t }\n\t else if(acceptance1>0 || acceptance2>0){\n\t \ttempBank.push_back(tmp);\n\t }\n\t else{\n\t }\n\t tmp++;\n }\n \n\tint coun=0;\n\tint tmp_index=0;\n\tstd::cout << \"Second Iteration\" << std::endl;\n\t\n\tfor (itPair.first(); !itPair.isDone() && tmp_index<tempBank.size(); itPair.next())\n\t{\n \tif(coun==tempBank[tmp_index])\n \t{\n\t\t Sequence& s1 = itPair.item().first;\n\t\t Sequence& s2 = itPair.item().second;\n\t\t \n\t\t int acceptance1=0;\n\t\t int acceptance2=0;\n\t\t int acceptance=0;\n\n\t\t itKmer.setData (s1.getData());\n\t\t itKmer1.setData (s2.getData());\n\t\t \t \n\t\t \/\/checking the threshold\n\t\t acceptance1 = readacceptance(graph, itKmer, model, counter, base);\n\t\t acceptance2 = readacceptance(graph, itKmer1, model, counter, base);\n\t\t \t \n\t\t if(acceptance1 > 0 || acceptance2 > 0)\n\t\t {\n\t\t\tfor (itKmer1.first(); !itKmer1.isDone(); itKmer1.next())\n\t\t \t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str();\n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\tdouble threshold=0;\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node)){\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\t\tif(threshold>abund){\n\t\t\t\t\t\tthreshold=abund;\n\t\t\t\t\t}\n\t\t\t\t\tif(threshold<1){\n\t\t\t\t\t\tthreshold=1;\n\t\t\t\t\t}\n\t\t\t\t\tif(counter[index] < threshold){\n\t\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (itKmer.first(); !itKmer.isDone(); itKmer.next())\n\t\t \t{\n\t\t\t\tstd::string s = model.toString (itKmer->value());\n\t\t\t\tconst char* sq = s.c_str();\n\t\t\t\tNode node = graph.buildNode(sq);\n\t\t\t\tdouble threshold=0;\n\t\t\t\t\/\/Checking whether the node exists.\n\t\t\t\tif(graph.contains(node))\n\t\t\t\t{\n\t\t\t\t\tauto index = graph.nodeMPHFIndex(node);\n\t\t\t\t\tauto abund = graph.queryAbundance(node);\n\t\t\t\t\tthreshold = ceil((log(abund)\/log(base)));\n\t\t\t\t\tif(threshold>abund)\n\t\t\t\t\t{\n\t\t\t\t\t\tthreshold=abund;\n\t\t\t\t\t}\n\t\t\t\t\tif(threshold<1)\n\t\t\t\t\t{\n\t\t\t\t\t\tthreshold=1;\n\t\t\t\t\t}\n\t\t\t\t\tif(counter[index] < threshold)\n\t\t\t\t\t{\n\t\t\t\t\t\tcounter[index]=counter[index]+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t \t}\n\t\t\tOutDataset->insert(s1);\n\t\t\tOutDataset->insert(s2);\n\t\t\tcount++;\n\t\t }\n\t\t tmp_index++;\n\t\t}\n\t\tcoun++;\n }\n\tstd::cout << \"kept \" << count << \" reads\" << std::endl;\n\tInputDataset1->flush();\n\tInputDataset2->flush();\n\tdelete [] counter;\n\tOutDataset->flush();\n}\n\n\nclass ORNA : public Tool\n{\npublic:\n\tORNA(): Tool(\"ORNA\")\n\t{\n\t\tgetParser()->push_front (new OptionOneParam (STR_KMER, \"kmer required\", false, \"21\"));\n\t getParser()->push_front (new OptionOneParam (STR_INPUT, \"Input File\", false, \"ORNAERROR\"));\n\t getParser()->push_front (new OptionOneParam (STR_OUTPUT, \"Output File\", false, \"Normalized.fa\"));\n\t\tgetParser()->push_front (new OptionOneParam (STR_BASE, \"Base for the logarithmic function\", false, \"1.7\"));\n\t\tgetParser()->push_front (new OptionOneParam (STR_PAIR1, \"First read of the pair\", false, \"ORNAERROR\" ));\n\t\tgetParser()->push_front (new OptionOneParam (STR_PAIR2, \"Second read of the pair\", false, \"ORNAERROR\" ));\n\t}\n\tvoid execute()\n\t{\n\t\tconst char* filename = (getInput()->get(STR_INPUT))->getString();\n\t\tconst char* read1= (getInput()->get(STR_PAIR1))->getString(); \n\t\tconst char* read2= (getInput()->get(STR_PAIR2))->getString();\n\t\tdouble base=getInput()->getDouble(STR_BASE);\n\t\tint user_kmer = getInput()->getInt(STR_KMER);\n\t\tconst char* out_file= (getInput()->get(STR_OUTPUT))->getString();\n\t\tint nbCores = getInput()->getInt(STR_NB_CORES);\n\t\tunsigned short pairflag = 0; \n\t\tunsigned short kmer = user_kmer + 1; \n\t\tunsigned short cores = sysconf(_SC_NPROCESSORS_ONLN); \n\t\tif(nbCores==cores){\n\t\t\tnbCores=1;\t\t\n\t\t} \n\t\tif(std::strcmp(filename, \"ORNAERROR\") == 0)\n\t\t{\n\t\t\tif((std::strcmp(read1, \"ORNAERROR\") == 0) && (std::strcmp(read2, \"ORNAERROR\") == 0))\n\t\t\t{\n\t\t\t\tstd::cout << \"Input File(s) missing. Please refer to the help\" << std::endl;\n\t\t\t}\n\t\t\tif (((std::strcmp(read1, \"ORNAERROR\") != 0) && (std::strcmp(read2, \"ORNAERROR\") == 0)) || ((std::strcmp(read1, \"ORNAERROR\") == 0) && (std::strcmp(read2, \"ORNAERROR\") != 0)))\n\t\t\t{\n\t\t\t\tstd::cout << \"One of the pair files is missing. Please refer to the help\" << std::endl;\t\n\t\t\t}\n\t\t\tif((std::strcmp(read1, \"ORNAERROR\") != 0) && (std::strcmp(read2, \"ORNAERROR\") != 0))\n\t\t\t{\n\t\t\t\tpairflag = 1; \n\t\t\t}\t\t\t\t\n\t\t}\n\t\tif(pairflag==0)\n\t\t{\n\t\t\tstd::cout << \"Running ORNA in single end mode\" << std::endl;\n\t\t\tsingleend(filename, out_file, base, kmer, nbCores);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Running ORNA in paired end mode\" << std::endl;\n\t\t\tpairedend(read1, read2, out_file, base, kmer);\n\t\t}\t\n\t}\n};\n\nint main (int argc, char* argv[])\n{\n\ttry{\n\t\tORNA().run(argc,argv);\n\t\treturn EXIT_SUCCESS;\t\n\t}\n\tcatch(Exception& e){\n\t\tstd::cout << \"EXCEPTION: \" << e.getMessage() << std::endl;\n \treturn EXIT_FAILURE;\n\t}\n \t\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n#include <cstdint>\n#include <exception>\n\n#include \"components\/command_line.hpp\"\n#include \"spdlog\/spdlog.h\"\n#include \"config.hpp\"\n\nusing add_arg = command_line::option;\n\nint main(int argc, char *argv[])\n{\n const command_line::options opts{\n add_arg(\"-h\", \"--help\", \"Display this text and exit \"),\n add_arg(\"-v\", \"--version\", \"Print version information\"),\n add_arg(\"-l\", \"--log\", \"Set logging level to info\"),\n\n \/* Exclusive arguments; cannot be combined with any other arguments. *\/\n add_arg(\"-d\", \"--ident\", \"Specify an item identification (such as DOI, URL, etc.)\", \"IDENT\"),\n\n \/* Main arguments; at least one of these are required. *\/\n \/* auto main = command_line::add_group( *\/\n \/* \"main\", \"necessarily inclusive arguments; at least one required\" *\/\n \/* ); *\/\n add_arg(\"-a\", \"--author\", \"Specify authors\", \"AUTHOR\"),\n add_arg(\"-t\", \"--title\", \"Specify title\", \"TITLE\"),\n add_arg(\"-s\", \"--serie\", \"Specify serie\", \"SERIE\"),\n add_arg(\"-p\", \"--publisher\", \"Specify publisher\", \"PUBLISHER\"),\n\n \/* Exact data arguments; all are optional. *\/\n add_arg(\"-y\", \"--year\", \"Specify year of release\", \"YEAR\"),\n add_arg(\"-L\", \"--language\", \"Specify text language\", \"LANG\"),\n add_arg(\"-e\", \"--edition\", \"Specify item edition\", \"EDITION\"),\n add_arg(\"-E\", \"--extension\", \"Specify item extension\", \"EXT\",\n {\"epub\", \"pdf\", \"djvu\"}),\n add_arg(\"-i\", \"--isbn\", \"Specify item ISBN\", \"ISBN\"),\n };\n\n uint8_t exit_code = EXIT_SUCCESS;\n\n auto logger = spdlog::stdout_color_mt(\"logger\");\n spdlog::set_pattern(\"%l: %v\");\n spdlog::set_level(spdlog::level::err);\n\n try {\n \/* Parse command line arguments. *\/\n std::string progname = argv[0];\n std::vector<std::string> args(argv + 1, argv + argc);\n\n cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));\n cli->process_arguments(args);\n\n if (cli->has(\"log\"))\n spdlog::set_level(spdlog::level::info);\n\n logger->info(\"the mighty eldwyrm has been summoned!\");\n\n if (cli->has(\"help\")) {\n cli->usage();\n return EXIT_SUCCESS;\n } else if (cli->has(\"version\")) {\n print_build_info();\n return EXIT_SUCCESS;\n } else if (args.empty()) {\n cli->usage();\n return EXIT_FAILURE;\n }\n\n } catch (const std::exception &err) {\n logger->error(err.what());\n exit_code = EXIT_FAILURE;\n }\n\n return exit_code;\n}\n<commit_msg>don't forget to drop all loggers<commit_after>\/*\n * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n#include <cstdint>\n#include <exception>\n\n#include \"components\/command_line.hpp\"\n#include \"spdlog\/spdlog.h\"\n#include \"config.hpp\"\n\nusing add_arg = command_line::option;\n\nint main(int argc, char *argv[])\n{\n const command_line::options opts{\n add_arg(\"-h\", \"--help\", \"Display this text and exit \"),\n add_arg(\"-v\", \"--version\", \"Print version information\"),\n add_arg(\"-l\", \"--log\", \"Set logging level to info\"),\n\n \/* Exclusive arguments; cannot be combined with any other arguments. *\/\n add_arg(\"-d\", \"--ident\", \"Specify an item identification (such as DOI, URL, etc.)\", \"IDENT\"),\n\n \/* Main arguments; at least one of these are required. *\/\n \/* auto main = command_line::add_group( *\/\n \/* \"main\", \"necessarily inclusive arguments; at least one required\" *\/\n \/* ); *\/\n add_arg(\"-a\", \"--author\", \"Specify authors\", \"AUTHOR\"),\n add_arg(\"-t\", \"--title\", \"Specify title\", \"TITLE\"),\n add_arg(\"-s\", \"--serie\", \"Specify serie\", \"SERIE\"),\n add_arg(\"-p\", \"--publisher\", \"Specify publisher\", \"PUBLISHER\"),\n\n \/* Exact data arguments; all are optional. *\/\n add_arg(\"-y\", \"--year\", \"Specify year of release\", \"YEAR\"),\n add_arg(\"-L\", \"--language\", \"Specify text language\", \"LANG\"),\n add_arg(\"-e\", \"--edition\", \"Specify item edition\", \"EDITION\"),\n add_arg(\"-E\", \"--extension\", \"Specify item extension\", \"EXT\",\n {\"epub\", \"pdf\", \"djvu\"}),\n add_arg(\"-i\", \"--isbn\", \"Specify item ISBN\", \"ISBN\"),\n };\n\n uint8_t exit_code = EXIT_SUCCESS;\n\n auto logger = spdlog::stdout_color_mt(\"logger\");\n spdlog::set_pattern(\"%l: %v\");\n spdlog::set_level(spdlog::level::err);\n\n try {\n \/* Parse command line arguments. *\/\n std::string progname = argv[0];\n std::vector<std::string> args(argv + 1, argv + argc);\n\n cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));\n cli->process_arguments(args);\n\n if (cli->has(\"log\"))\n spdlog::set_level(spdlog::level::info);\n\n logger->info(\"the mighty eldwyrm has been summoned!\");\n\n if (cli->has(\"help\")) {\n cli->usage();\n return EXIT_SUCCESS;\n } else if (cli->has(\"version\")) {\n print_build_info();\n return EXIT_SUCCESS;\n } else if (args.empty()) {\n cli->usage();\n return EXIT_FAILURE;\n }\n\n } catch (const std::exception &err) {\n logger->error(err.what());\n exit_code = EXIT_FAILURE;\n }\n\n spdlog::drop_all();\n return exit_code;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/config.h\"\n#include <ESP8266WiFi.h>\n#include <WiFiClient.h>\n#include <ESP8266WebServer.h>\n#include <ESP8266mDNS.h>\n#include <runningaverage.h>\n\n\n#ifdef SENSOR_DS18S20\n#include <OneWire.h>\n#define ONE_WIRE_BUS 2 \/\/ DS18S20 pin\nOneWire ds(ONE_WIRE_BUS);\n#endif\n\n#ifdef SENSOR_DHT22\n#include <DHT.h>\n#include \"..\/config.h\"\n#define DHTPIN 2\nDHT dht(DHTPIN, DHTTYPE, 11); \/\/ 11 works fine for ESP8266\n#endif\n\nMDNSResponder mdns;\nESP8266WebServer server(80);\nRunningAverage temp_aggregator(6);\nRunningAverage hum_aggregator(6);\nbool sensor_ok = false;\nenum SensorState {\n\tMEASURED_OK,\n\tMEASURED_FAILED,\n\tTOO_EARLY\n};\n\nString webString=\"\"; \/\/ String to display\n\/\/ Generally, you should use \"unsigned long\" for variables that hold time\nunsigned long previousMillis = 0; \/\/ will store last temp was read\nconst long interval = 10000; \/\/ interval at which to read sensor\n\nint ICACHE_FLASH_ATTR gettemperature(float& temp, float& humidity) {\n \/\/ Wait at least 2 seconds seconds between measurements.\n \/\/ if the difference between the current time and last time you read\n \/\/ the sensor is bigger than the interval you set, read the sensor\n \/\/ Works better than delay for things happening elsewhere also\n unsigned long currentMillis = millis();\n \n if(currentMillis - previousMillis >= interval) {\n \/\/ save the last time you read the sensor \n previousMillis = currentMillis;\n\n#ifdef SENSOR_DS18S20\n\t\t\/\/ This is the code for receiving temperature readings from a DS18S20.\n\t\t\/\/ see https:\/\/github.com\/esp8266\/Arduino\/blob\/esp8266\/libraries\/OneWire\/examples\/DS18x20_Temperature\/DS18x20_Temperature.pde\n\t\tbyte i;\n\t\tbyte present = 0;\n\t\tbyte type_s;\n\t\tbyte data[12];\n\t\tbyte addr[8];\n\n\t\tds.reset();\n\t\tds.reset_search();\n\t\tif ( !ds.search(addr)) {\n\t\t\tSerial.println(\"No more addresses.\");\n\t\t\tSerial.println();\n\t\t\tds.reset_search();\n\t\t\tdelay(250);\n\t\t\treturn MEASURED_FAILED;\n\t\t}\n\n\t\t\/\/Serial.print(\"ROM =\");\n\t\t\/\/for( i = 0; i < 8; i++) {\n\t\t\/\/\tSerial.write(' ');\n\t\t\/\/\tSerial.print(addr[i], HEX);\n\t\t\/\/}\n\n\t\tif (OneWire::crc8(addr, 7) != addr[7]) {\n\t\t\tSerial.println(\"CRC is not valid!\");\n\t\t\treturn MEASURED_FAILED;\n\t\t}\n\t\t\/\/Serial.println();\n\n\t\t\/\/ the first ROM byte indicates which chip\n\t\tswitch (addr[0]) {\n\t\t\tcase 0x10:\n\t\t\t\t\/\/Serial.println(\" Chip = DS18S20\"); \/\/ or old DS1820\n\t\t\t\ttype_s = 1;\n\t\t\t\tbreak;\n\t\t\tcase 0x28:\n\t\t\t\t\/\/Serial.println(\" Chip = DS18B20\");\n\t\t\t\ttype_s = 0;\n\t\t\t\tbreak;\n\t\t\tcase 0x22:\n\t\t\t\t\/\/Serial.println(\" Chip = DS1822\");\n\t\t\t\ttype_s = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tSerial.println(\"Device is not a DS18x20 family device.\");\n\t\t\t\treturn MEASURED_FAILED;\n\t\t} \n\n\t\tds.reset();\n\t\tds.select(addr);\n\t\tds.write(0x44, 0); \/\/ start conversion, no parasitic power\n\n\t\tdelay(750); \/\/ maybe 750ms is enough, maybe not\n\t\t\/\/ we might do a ds.depower() here, but the reset will take care of it.\n\n\t\tpresent = ds.reset();\n\t\tds.select(addr);\n\t\tds.write(0xBE); \/\/ Read Scratchpad\n\n\t\t\/\/Serial.print(\" Data = \");\n\t\t\/\/Serial.print(present, HEX);\n\t\t\/\/Serial.print(\" \");\n\t\tfor ( i = 0; i < 9; i++) { \/\/ we need 9 bytes\n\t\t\tdata[i] = ds.read();\n\t\t\t\/\/Serial.print(data[i], HEX);\n\t\t\t\/\/Serial.print(\" \");\n\t\t}\n\t\t\/\/Serial.print(\" CRC=\");\n\t\t\/\/Serial.print(OneWire::crc8(data, 8), HEX);\n\t\t\/\/Serial.println();\n\n\t\t\/\/ Convert the data to actual temperature\n\t\t\/\/ because the result is a 16 bit signed integer, it should\n\t\t\/\/ be stored to an \"int16_t\" type, which is always 16 bits\n\t\t\/\/ even when compiled on a 32 bit processor.\n\t\tint16_t raw = (data[1] << 8) | data[0];\n\t\tif (type_s) {\n\t\t\traw = raw << 3; \/\/ 9 bit resolution default\n\t\t\tif (data[7] == 0x10) {\n\t\t\t\t\/\/ \"count remain\" gives full 12 bit resolution\n\t\t\t\traw = (raw & 0xFFF0) + 12 - data[6];\n\t\t\t}\n\t\t} else {\n\t\t\tbyte cfg = (data[4] & 0x60);\n\t\t\t\/\/ at lower res, the low bits are undefined, so let's zero them\n\t\t\tif (cfg == 0x00) raw = raw & ~7; \/\/ 9 bit resolution, 93.75 ms\n\t\t\telse if (cfg == 0x20) raw = raw & ~3; \/\/ 10 bit res, 187.5 ms\n\t\t\telse if (cfg == 0x40) raw = raw & ~1; \/\/ 11 bit res, 375 ms\n\t\t\t\/\/\/\/ default is 12 bit resolution, 750 ms conversion time\n\t\t}\n\t\ttemp = (float)raw \/ 16.0;\n\t\t\/\/Serial.print(\"Temperature: \");\n\t\t\/\/Serial.println(temp);\n#endif \/\/ of DS18S20-related code\n\n#ifdef SENSOR_DHT22 \/\/ Read temp&hum from DHT22\n\t\t\/\/ Reading temperature for humidity takes about 250 milliseconds!\n\t\t\/\/ Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)\n\t\thumidity = dht.readHumidity(); \/\/ Read humidity (percent)\n\t\ttemp = dht.readTemperature(false); \/\/ Read temperature as Celsius\n#endif\n\n\t\t\/\/Serial.print(\"Free heap:\");\n\t\t\/\/Serial.println(ESP.getFreeHeap(),DEC);\n\n\t\tif (isnan(temp) || temp==85.0 || temp==(-127.0)) {\n\t\t\tSerial.println(\"Failed to read from sensor\");\n\t\t\t\/\/ resetting the previous measurement time so that a failed attempt\n\t\t\t\/\/ will be repeated with the next query.\n\t\t\tpreviousMillis=currentMillis-2000;\n\t\t\tif (previousMillis < 0) previousMillis = 0;\n\t\t\treturn MEASURED_FAILED;\n\t\t} else {\n\t\t\treturn MEASURED_OK;\n\t\t}\n\t} else {\n\t\treturn TOO_EARLY; \/\/ no measurement taken - time not elapsed\n\t}\n}\n\n\nvoid ICACHE_FLASH_ATTR handleNotFound(){\n\tString message = \"File Not Found\\n\\n\";\n\tmessage += \"URI: \";\n\tmessage += server.uri();\n\tmessage += \"\\nMethod: \";\n\tmessage += (server.method() == HTTP_GET)?\"GET\":\"POST\";\n\tmessage += \"\\nArguments: \";\n\tmessage += server.args();\n\tmessage += \"\\n\";\n\tfor (uint8_t i=0; i<server.args(); i++){\n\t\tmessage += \" \" + server.argName(i) + \": \" + server.arg(i) + \"\\n\";\n\t}\n\tserver.send(404, \"text\/plain\", message);\n}\n\nvoid ICACHE_FLASH_ATTR setup(void){\n\tSerial.begin(9600);\n\tWiFi.begin(ssid, password);\n\tSerial.println(\"\");\n\tSerial.println(\"Wifi temperature sensor v0.1\");\n\n\t\/\/ Wait for connection\n\twhile (WiFi.status() != WL_CONNECTED) {\n\t\tdelay(500);\n\t\tSerial.print(\".\");\n\t}\n\n\tSerial.println(\"\");\n\tSerial.print(\"Connected to \");\n\tSerial.println(ssid);\n\tSerial.print(\"IP address: \");\n\tSerial.println(WiFi.localIP());\n\n\tif (mdns.begin(hostname, WiFi.localIP())) {\n\t\tSerial.println(\"MDNS responder started\");\n\t}\n\n\tserver.on(\"\/\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString = \"Sensor \" + String(hostname) + \" reports:\\n\";\n\t\t\t\twebString+=\"Temperature: \"+String(temp_aggregator.getAverage())+\" degree Celsius\\n\";\n#ifdef SENSOR_DHT22 \/\/ Read temp&hum from DHT22\n\t\t\t\twebString+=\"Humidity: \"+String(hum_aggregator.getAverage())+\" % r.H.\\n\";\n#endif\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n\tserver.on(\"\/temperature\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString=\"{\\\"temperature\\\": \"+String(temp_aggregator.getAverage())+\",\\\"unit\\\": \\\"Celsius\\\"}\";\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n#ifdef SENSOR_DHT22 \/\/ Read humidity from DHT22\n\tserver.on(\"\/humidity\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString=\"{\\\"humidity\\\": \"+String(hum_aggregator.getAverage())+\",\\\"unit\\\": \\\"% r.H.\\\"}\";\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n\n#endif\n\n\tserver.onNotFound(handleNotFound);\n\n\tserver.begin();\n\tESP.wdtEnable(5000);\n}\n\nvoid ICACHE_FLASH_ATTR loop(void){\n\tserver.handleClient();\n\tESP.wdtFeed();\n\tfloat temp = 0.0;\n\tfloat humidity = 0.0;\n\tswitch (gettemperature(temp, humidity)) {\n\t\tcase MEASURED_OK:\n\t\t\tsensor_ok = true;\n\t\t\tSerial.println(\"Updating accumulator w\/ new measurements\");\n\t\t\ttemp_aggregator.addValue(temp);\n\t\t\thum_aggregator.addValue(humidity);\n\t\t\tbreak;\n\t\tcase MEASURED_FAILED:\n\t\t\tSerial.println(\"Measurement failed\");\n\t\t\tsensor_ok = false;\n\t\t\tbreak;\n\t\tcase TOO_EARLY:\n\t\t\t;;\n\t\t\tbreak;\n\t}\n}\n\n<commit_msg>scanning onewire bus for more than one sensor - still need a multiplexer for the runningaverage class<commit_after>#include \"..\/config.h\"\n#include <ESP8266WiFi.h>\n#include <WiFiClient.h>\n#include <ESP8266WebServer.h>\n#include <ESP8266mDNS.h>\n#include <runningaverage.h>\n\n\n#ifdef SENSOR_DS18S20\n#include <OneWire.h>\n#define ONE_WIRE_BUS 2 \/\/ DS18S20 pin\nOneWire ds(ONE_WIRE_BUS);\n#endif\n\n#ifdef SENSOR_DHT22\n#include <DHT.h>\n#include \"..\/config.h\"\n#define DHTPIN 2\nDHT dht(DHTPIN, DHTTYPE, 11); \/\/ 11 works fine for ESP8266\n#endif\n\nMDNSResponder mdns;\nESP8266WebServer server(80);\nRunningAverage temp_aggregator(6);\nRunningAverage hum_aggregator(6);\nbool sensor_ok = false;\nenum SensorState {\n\tMEASURED_OK,\n\tMEASURED_FAILED,\n\tTOO_EARLY\n};\n\nString webString=\"\"; \/\/ String to display\n\/\/ Generally, you should use \"unsigned long\" for variables that hold time\nunsigned long previousMillis = 0; \/\/ will store last temp was read\nconst long interval = 10000; \/\/ interval at which to read sensor\n\n\/\/ read the sensor with the given bus index. Sets temperature in temp,\n\/\/ humidity in humidity. Returns the SensorState.\nint ICACHE_FLASH_ATTR read_sensors(byte bus_idx, float& temp, float& humidity) {\n \/\/ Wait at least 2 seconds seconds between measurements.\n \/\/ if the difference between the current time and last time you read\n \/\/ the sensor is bigger than the interval you set, read the sensor\n \/\/ Works better than delay for things happening elsewhere also\n unsigned long currentMillis = millis();\n \n if(currentMillis - previousMillis >= interval) {\n \/\/ save the last time you read the sensor \n previousMillis = currentMillis;\n\n#ifdef SENSOR_DS18S20\n\t\t\/\/ This is the code for receiving temperature readings from a DS18S20.\n\t\t\/\/ see https:\/\/github.com\/esp8266\/Arduino\/blob\/esp8266\/libraries\/OneWire\/examples\/DS18x20_Temperature\/DS18x20_Temperature.pde\n\t\tbyte i;\n\t\tbyte present = 0;\n\t\tbyte type_s;\n\t\tbyte data[12];\n\t\tbyte max_addr = 4;\n\t\tbyte addr[max_addr][8]; \/\/ can hold four addresses of 8 byte each\n\t\tbyte addr_count = 0;\n\n\t\tds.reset();\n\t\tds.reset_search();\n\n\t\tfor (addr_count = 0; addr_count < max_addr; ++addr_count) {\n\t\t\tif ( !ds.search(addr[addr_count])) {\n\t\t\t\t\/\/Serial.println(\"No more addresses.\");\n\t\t\t\tds.reset_search();\n\t\t\t\tdelay(250);\n\t\t\t\tbreak;\n\t\t\t} \/\/else {\n\t\t\t\t\/\/Serial.print(\"found address \");\n\t\t\t\t\/\/for( i = 0; i < 8; i++) {\n\t\t\t\t\/\/\tSerial.write(' ');\n\t\t\t\t\/\/\tSerial.print(addr[addr_count][i], HEX);\n\t\t\t\t\/\/}\n\t\t\t\t\/\/Serial.println();\n\t\t\t\/\/}\n\t\t}\n\n\t\t\/\/Serial.print(\"found \");\n\t\t\/\/Serial.print(addr_count);\n\t\t\/\/Serial.println(\" addresses.\");\n\n\t\tif (addr_count == 0) {\n\t\t\tSerial.println(\"No sensors found.\");\n\t\t\treturn MEASURED_FAILED;\n\t\t}\n\n\t\tif (bus_idx >= addr_count) {\n\t\t\tSerial.print(\"Requested sensor \");\n\t\t\tSerial.print(bus_idx);\n\t\t\tSerial.println(\" but not that many sensors on bus.\");\n\t\t\treturn MEASURED_FAILED;\n\t\t}\n\n\t\tif (OneWire::crc8(addr[bus_idx], 7) != addr[bus_idx][7]) {\n\t\t\tSerial.println(\"CRC is not valid!\");\n\t\t\treturn MEASURED_FAILED;\n\t\t}\n\t\t\/\/Serial.println();\n\n\t\t\/\/ the first ROM byte indicates which chip\n\t\tswitch (addr[bus_idx][0]) {\n\t\t\tcase 0x10:\n\t\t\t\t\/\/Serial.println(\" Chip = DS18S20\"); \/\/ or old DS1820\n\t\t\t\ttype_s = 1;\n\t\t\t\tbreak;\n\t\t\tcase 0x28:\n\t\t\t\t\/\/Serial.println(\" Chip = DS18B20\");\n\t\t\t\ttype_s = 0;\n\t\t\t\tbreak;\n\t\t\tcase 0x22:\n\t\t\t\t\/\/Serial.println(\" Chip = DS1822\");\n\t\t\t\ttype_s = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tSerial.println(\"Device is not a DS18x20 family device.\");\n\t\t\t\treturn MEASURED_FAILED;\n\t\t} \n\n\t\tds.reset();\n\t\tds.select(addr[bus_idx]);\n\n\t\tds.write(0x44, 0); \/\/ start conversion, no parasitic power\n\n\t\tdelay(750); \/\/ maybe 750ms is enough, maybe not\n\t\t\/\/ we might do a ds.depower() here, but the reset will take care of it.\n\n\t\tpresent = ds.reset();\n\t\tds.select(addr[bus_idx]);\n\t\tds.write(0xBE); \/\/ Read Scratchpad\n\n\t\t\/\/Serial.print(\" Data = \");\n\t\t\/\/Serial.print(present, HEX);\n\t\t\/\/Serial.print(\" \");\n\t\tfor ( i = 0; i < 9; i++) { \/\/ we need 9 bytes\n\t\t\tdata[i] = ds.read();\n\t\t\t\/\/Serial.print(data[i], HEX);\n\t\t\t\/\/Serial.print(\" \");\n\t\t}\n\t\t\/\/Serial.print(\" CRC=\");\n\t\t\/\/Serial.print(OneWire::crc8(data, 8), HEX);\n\t\t\/\/Serial.println();\n\n\t\t\/\/ Convert the data to actual temperature\n\t\t\/\/ because the result is a 16 bit signed integer, it should\n\t\t\/\/ be stored to an \"int16_t\" type, which is always 16 bits\n\t\t\/\/ even when compiled on a 32 bit processor.\n\t\tint16_t raw = (data[1] << 8) | data[0];\n\t\tif (type_s) {\n\t\t\traw = raw << 3; \/\/ 9 bit resolution default\n\t\t\tif (data[7] == 0x10) {\n\t\t\t\t\/\/ \"count remain\" gives full 12 bit resolution\n\t\t\t\traw = (raw & 0xFFF0) + 12 - data[6];\n\t\t\t}\n\t\t} else {\n\t\t\tbyte cfg = (data[4] & 0x60);\n\t\t\t\/\/ at lower res, the low bits are undefined, so let's zero them\n\t\t\tif (cfg == 0x00) raw = raw & ~7; \/\/ 9 bit resolution, 93.75 ms\n\t\t\telse if (cfg == 0x20) raw = raw & ~3; \/\/ 10 bit res, 187.5 ms\n\t\t\telse if (cfg == 0x40) raw = raw & ~1; \/\/ 11 bit res, 375 ms\n\t\t\t\/\/\/\/ default is 12 bit resolution, 750 ms conversion time\n\t\t}\n\t\ttemp = (float)raw \/ 16.0;\n\t\t\/\/Serial.print(\"Temperature: \");\n\t\t\/\/Serial.println(temp);\n#endif \/\/ of DS18S20-related code\n\n#ifdef SENSOR_DHT22 \/\/ Read temp&hum from DHT22\n\t\t\/\/ Reading temperature for humidity takes about 250 milliseconds!\n\t\t\/\/ Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)\n\t\thumidity = dht.readHumidity(); \/\/ Read humidity (percent)\n\t\ttemp = dht.readTemperature(false); \/\/ Read temperature as Celsius\n#endif\n\n\t\t\/\/Serial.print(\"Free heap:\");\n\t\t\/\/Serial.println(ESP.getFreeHeap(),DEC);\n\n\t\tif (isnan(temp) || temp==85.0 || temp==(-127.0)) {\n\t\t\tSerial.println(\"Failed to read from sensor\");\n\t\t\t\/\/ resetting the previous measurement time so that a failed attempt\n\t\t\t\/\/ will be repeated with the next query.\n\t\t\tpreviousMillis=currentMillis-2000;\n\t\t\tif (previousMillis < 0) previousMillis = 0;\n\t\t\treturn MEASURED_FAILED;\n\t\t} else {\n\t\t\treturn MEASURED_OK;\n\t\t}\n\t} else {\n\t\treturn TOO_EARLY; \/\/ no measurement taken - time not elapsed\n\t}\n}\n\n\nvoid ICACHE_FLASH_ATTR handleNotFound(){\n\tString message = \"File Not Found\\n\\n\";\n\tmessage += \"URI: \";\n\tmessage += server.uri();\n\tmessage += \"\\nMethod: \";\n\tmessage += (server.method() == HTTP_GET)?\"GET\":\"POST\";\n\tmessage += \"\\nArguments: \";\n\tmessage += server.args();\n\tmessage += \"\\n\";\n\tfor (uint8_t i=0; i<server.args(); i++){\n\t\tmessage += \" \" + server.argName(i) + \": \" + server.arg(i) + \"\\n\";\n\t}\n\tserver.send(404, \"text\/plain\", message);\n}\n\nvoid ICACHE_FLASH_ATTR setup(void){\n\tSerial.begin(9600);\n\tWiFi.begin(ssid, password);\n\tSerial.println(\"\");\n\tSerial.println(\"Wifi temperature sensor v0.1\");\n\n\t\/\/ Wait for connection\n\twhile (WiFi.status() != WL_CONNECTED) {\n\t\tdelay(500);\n\t\tSerial.print(\".\");\n\t}\n\n\tSerial.println(\"\");\n\tSerial.print(\"Connected to \");\n\tSerial.println(ssid);\n\tSerial.print(\"IP address: \");\n\tSerial.println(WiFi.localIP());\n\n\tif (mdns.begin(mdnsname, WiFi.localIP())) {\n\t\tSerial.println(\"MDNS responder started\");\n\t}\n\n\tserver.on(\"\/\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString = \"Sensor \" + String(mdnsname) + \" reports:\\n\";\n\t\t\t\twebString+=\"Temperature: \"+String(temp_aggregator.getAverage())+\" degree Celsius\\n\";\n#ifdef SENSOR_DHT22 \/\/ Read temp&hum from DHT22\n\t\t\t\twebString+=\"Humidity: \"+String(hum_aggregator.getAverage())+\" % r.H.\\n\";\n#endif\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n\tserver.on(\"\/temperature\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString=\"{\\\"temperature\\\": \"+String(temp_aggregator.getAverage())+\",\\\"unit\\\": \\\"Celsius\\\"}\";\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n#ifdef SENSOR_DHT22 \/\/ Read humidity from DHT22\n\tserver.on(\"\/humidity\", [](){\n\t\t\tif (sensor_ok) { \/\/ read sensor\n\t\t\t\twebString=\"{\\\"humidity\\\": \"+String(hum_aggregator.getAverage())+\",\\\"unit\\\": \\\"% r.H.\\\"}\";\n\t\t\t\tserver.send(200, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t} else {\n\t\t\t\twebString=\"{\\\"error\\\": \\\"Cannot read data from sensor.\\\"\";\n\t\t\t\tserver.send(503, \"text\/plain\", webString); \/\/ send to someones browser when asked\n\t\t\t}\n\t\t\t});\n\n#endif\n\n\tserver.onNotFound(handleNotFound);\n\n\tserver.begin();\n\tESP.wdtEnable(5000);\n}\n\nvoid ICACHE_FLASH_ATTR loop(void){\n\tserver.handleClient();\n\tESP.wdtFeed();\n\tfloat temp = 0.0;\n\tfloat humidity = 0.0;\n\tswitch (read_sensors(0, temp, humidity)) {\n\t\tcase MEASURED_OK:\n\t\t\tsensor_ok = true;\n\t\t\t\/\/Serial.println(\"Updating accumulator w\/ new measurements\");\n\t\t\ttemp_aggregator.addValue(temp);\n\t\t\thum_aggregator.addValue(humidity);\n\t\t\tbreak;\n\t\tcase MEASURED_FAILED:\n\t\t\tSerial.println(\"Measurement failed\");\n\t\t\tsensor_ok = false;\n\t\t\tbreak;\n\t\tcase TOO_EARLY:\n\t\t\t;;\n\t\t\tbreak;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef _PNMC_MC_STATISTICS_HH_\n#define _PNMC_MC_STATISTICS_HH_\n\n#include <chrono>\n#include <iosfwd>\n\n#include \"conf\/configuration.hh\"\n\nnamespace pnmc { namespace mc {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstruct statistics\n{\n const conf::pnmc_configuration& conf;\n\n std::chrono::duration<double> relation_duration;\n std::chrono::duration<double> rewrite_duration;\n std::chrono::duration<double> state_space_duration;\n std::chrono::duration<double> dead_states_relation_duration;\n std::chrono::duration<double> dead_states_rewrite_duration;\n std::chrono::duration<double> dead_states_duration;\n\n long double nb_states;\n\n bool interrupted ;\n\n statistics(const conf::pnmc_configuration& c)\n : conf(c), relation_duration(), rewrite_duration(), state_space_duration()\n , dead_states_relation_duration(), dead_states_rewrite_duration(), dead_states_duration()\n , nb_states(0), interrupted(false)\n {}\n\n template<class Archive>\n void\n save(Archive& archive)\n const\n {\n archive( cereal::make_nvp(\"interrupted\", interrupted)\n , cereal::make_nvp(\"relation time\", relation_duration.count())\n , cereal::make_nvp(\"rewrite time\", rewrite_duration.count())\n , cereal::make_nvp(\"state space time\", state_space_duration.count())\n );\n\n if (conf.compute_dead_states)\n {\n archive( cereal::make_nvp(\"dead states relation time\", dead_states_relation_duration.count())\n , cereal::make_nvp(\"dead states rewrite time\", dead_states_rewrite_duration.count())\n , cereal::make_nvp(\"dead states time\", dead_states_duration.count())\n );\n }\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::mc\n\n#endif \/\/ _PNMC_MC_STATISTICS_HH_\n<commit_msg>Put the number of states in the JSON statistics file.<commit_after>#ifndef _PNMC_MC_STATISTICS_HH_\n#define _PNMC_MC_STATISTICS_HH_\n\n#include <chrono>\n#include <iosfwd>\n\n#include \"conf\/configuration.hh\"\n\nnamespace pnmc { namespace mc {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstruct statistics\n{\n const conf::pnmc_configuration& conf;\n\n std::chrono::duration<double> relation_duration;\n std::chrono::duration<double> rewrite_duration;\n std::chrono::duration<double> state_space_duration;\n std::chrono::duration<double> dead_states_relation_duration;\n std::chrono::duration<double> dead_states_rewrite_duration;\n std::chrono::duration<double> dead_states_duration;\n\n long double nb_states;\n\n bool interrupted;\n\n statistics(const conf::pnmc_configuration& c)\n : conf(c), relation_duration(), rewrite_duration(), state_space_duration()\n , dead_states_relation_duration(), dead_states_rewrite_duration(), dead_states_duration()\n , nb_states(0), interrupted(false)\n {}\n\n template<class Archive>\n void\n save(Archive& archive)\n const\n {\n archive( cereal::make_nvp(\"interrupted\", interrupted)\n , cereal::make_nvp(\"states\", nb_states)\n , cereal::make_nvp(\"states as string\", std::to_string(nb_states))\n , cereal::make_nvp(\"relation time\", relation_duration.count())\n , cereal::make_nvp(\"rewrite time\", rewrite_duration.count())\n , cereal::make_nvp(\"state space time\", state_space_duration.count())\n );\n\n if (conf.compute_dead_states)\n {\n archive( cereal::make_nvp(\"dead states relation time\", dead_states_relation_duration.count())\n , cereal::make_nvp(\"dead states rewrite time\", dead_states_rewrite_duration.count())\n , cereal::make_nvp(\"dead states time\", dead_states_duration.count())\n );\n }\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::mc\n\n#endif \/\/ _PNMC_MC_STATISTICS_HH_\n<|endoftext|>"} {"text":"<commit_before>#include \"overlap.h\"\n\nnamespace MHAP {\n\n uint32_t Overlap::read1_id() const {\n return a_id;\n }\n\n uint32_t Overlap::read2_id() const {\n return b_id;\n }\n\n bool Overlap::use_prefix(uint32_t read_id) const {\n if (read_id == a_id) {\n return a_lo == 0;\n } else if (read_id == b_id) {\n return b_lo == 0;\n }\n\n return false;\n }\n\n bool Overlap::use_suffix(uint32_t read_id) const {\n if (read_id == a_id) {\n return a_hi == a_len;\n } else if (read_id == b_id) {\n return b_hi == b_len;\n }\n\n return false;\n }\n}\n<commit_msg>mhap: fix use_suffix and use_prefix functions for rc reads<commit_after>#include \"overlap.h\"\n\nnamespace MHAP {\n\n uint32_t Overlap::read1_id() const {\n return a_id;\n }\n\n uint32_t Overlap::read2_id() const {\n return b_id;\n }\n\n bool Overlap::use_prefix(uint32_t read_id) const {\n if (read_id == a_id) {\n if (a_fwd) {\n return a_lo == 0;\n } else {\n return a_hi == a_len;\n }\n } else if (read_id == b_id) {\n if (b_fwd) {\n return b_lo == 0;\n } else {\n return b_hi == b_len;\n }\n }\n\n return false;\n }\n\n bool Overlap::use_suffix(uint32_t read_id) const {\n if (read_id == a_id) {\n if (a_fwd) {\n return a_hi == a_len;\n } else {\n return a_lo == 0;\n }\n } else if (read_id == b_id) {\n if (a_fwd) {\n return b_hi == b_len;\n } else {\n return b_lo == 0;\n }\n }\n\n return false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <memory>\n#include <vector>\n\n\/* Neste problema, pede-se para armazenar, gerenciar e buscar por \n indivíduos definidos por\n um identificador único (inteiro) \n Primeiro nome\n último nome,\n data de nascimento\n telefone. \n*\/\nstruct Person\n{\n Person( int _id = 0,\n const std::string &_first_name = \"\",\n const std::string &_last_name = \"\",\n const std::string &_birthday = \"\",\n const std::string &_phone = \"\"):\n id(_id),\n first_name(_first_name),\n last_name(_last_name),\n birthday(_birthday),\n phone(_phone)\n {\n }\n int id;\n std::string first_name;\n std::string last_name;\n std::string birthday;\n std::string phone;\n std::shared_ptr<Person> collision;\n};\n\ntypedef std::shared_ptr<Person> Person_ptr;\ntypedef std::vector<Person_ptr> HashTable;\n\n\nclass PersonManager\n{\n public:\n PersonManager(void):\n max_elements(503),\n id_table(max_elements),\n fn_table(max_elements),\n ln_table(max_elements),\n birth_table(max_elements),\n phone_table(max_elements)\n {\n }\n\n \/* somente imprime na saída quando ocorre erro na inserção de um individuo,\n ocorrida na inserção de individuo com identificador duplicado.\n *\/\n void add(int id,\n const std::string &first_name,\n const std::string &last_name,\n const std::string &birthday,\n const std::string &phone)\n {\n if((id < 0) || (id > max_elements))\n {\n std::cout << \"invalid id\" << std::endl;\n return;\n }\n\n if(id_table[id] != NULL)\n {\n std::cout << \"ID \" << id << \" ja cadastrado.\" << std::endl;\n }\n\n std::shared_ptr<Person> person(new Person(id,first_name,last_name,birthday,phone));\n\n id_table[id] = person;\n\n unsigned int hash_number = hash(first_name);\n\n insert_on_table(fn_table,person,hash_number);\n\n hash_number = hash(last_name);\n insert_on_table(ln_table,person,hash_number);\n\n hash_number = hash(birthday);\n insert_on_table(birth_table,person,hash_number);\n\n hash_number = hash(phone);\n insert_on_table(phone_table,person,hash_number);\n }\n\n \/* O comando ''del'' remove todos dados relacionados a um determinado identificador,\n e retorna erro se não existir individuo com o identificador fornecido.\n *\/\n void del(int id)\n {\n if((id < 0) || (id > max_elements) || (id_table[id] == NULL))\n {\n std::cout << \"ID \" << id << \" nao existente\" << std::endl;\n return;\n }\n\n remove_from_table(fn_table,id_table[id],hash(id_table[id]->first_name));\n remove_from_table(ln_table,id_table[id],hash(id_table[id]->last_name));\n remove_from_table(birth_table,id_table[id],hash(id_table[id]->birthday));\n remove_from_table(phone_table,id_table[id],hash(id_table[id]->phone));\n id_table[id].reset();\n }\n private:\n const unsigned int max_elements; \/\/ Large prime number chosen\n HashTable id_table;\n HashTable fn_table;\n HashTable ln_table;\n HashTable birth_table;\n HashTable phone_table;\n\n\n unsigned int hash(const std::string &str)\n {\n unsigned int hash_number = 0;\n unsigned int mult = 1;\n\n for(char c : str)\n {\n hash_number += c * mult;\n ++mult;\n }\n\n return hash_number % max_elements;\n }\n\n void insert_on_table(HashTable &table,Person_ptr person,unsigned int hash_number)\n {\n if(table[hash_number] != NULL)\n {\n person->collision = table[hash_number];\n }\n\n table[hash_number] = person;\n }\n\n void remove_from_table(HashTable &table,Person_ptr person,unsigned int hash_number)\n {\n if(table[hash_number] != NULL)\n {\n Person_ptr last_person;\n Person_ptr people_itr = table[hash_number];\n do\n {\n if(people_itr->id == person->id)\n {\n break;\n }\n last_person = people_itr;\n people_itr = people_itr->collision;\n }while(people_itr != NULL);\n\n if(last_person != NULL)\n {\n last_person->collision = people_itr->collision;\n people_itr.reset();\n }\n else\n {\n table[hash_number] = table[hash_number]->collision;\n }\n }\n }\n};\n\nint main(void)\n{\n return 0;\n}\n<commit_msg>info coded<commit_after>#include <iostream>\n#include <string>\n#include <memory>\n#include <vector>\n\n\/* Neste problema, pede-se para armazenar, gerenciar e buscar por \n indivíduos definidos por\n um identificador único (inteiro) \n Primeiro nome\n último nome,\n data de nascimento\n telefone. \n*\/\nstruct Person\n{\n Person( int _id = 0,\n const std::string &_first_name = \"\",\n const std::string &_last_name = \"\",\n const std::string &_birthday = \"\",\n const std::string &_phone = \"\"):\n id(_id),\n first_name(_first_name),\n last_name(_last_name),\n birthday(_birthday),\n phone(_phone)\n {\n }\n int id;\n std::string first_name;\n std::string last_name;\n std::string birthday;\n std::string phone;\n std::shared_ptr<Person> collision;\n};\n\ntypedef std::shared_ptr<Person> Person_ptr;\ntypedef std::vector<Person_ptr> HashTable;\n\n\nclass PersonManager\n{\n public:\n PersonManager(void):\n max_elements(503),\n id_table(max_elements),\n fn_table(max_elements),\n ln_table(max_elements),\n birth_table(max_elements),\n phone_table(max_elements)\n {\n }\n\n \/* somente imprime na saída quando ocorre erro na inserção de um individuo,\n ocorrida na inserção de individuo com identificador duplicado.\n *\/\n void add(int id,\n const std::string &first_name,\n const std::string &last_name,\n const std::string &birthday,\n const std::string &phone)\n {\n if((id < 0) || (id > max_elements))\n {\n std::cout << \"invalid id\" << std::endl;\n return;\n }\n\n if(id_table[id] != NULL)\n {\n std::cout << \"ID \" << id << \" ja cadastrado.\" << std::endl;\n }\n\n std::shared_ptr<Person> person(new Person(id,first_name,last_name,birthday,phone));\n\n id_table[id] = person;\n\n unsigned int hash_number = hash(first_name);\n\n insert_on_table(fn_table,person,hash_number);\n\n hash_number = hash(last_name);\n insert_on_table(ln_table,person,hash_number);\n\n hash_number = hash(birthday);\n insert_on_table(birth_table,person,hash_number);\n\n hash_number = hash(phone);\n insert_on_table(phone_table,person,hash_number);\n }\n\n \/* O comando ''del'' remove todos dados relacionados a um determinado identificador,\n e retorna erro se não existir individuo com o identificador fornecido.\n *\/\n void del(int id)\n {\n if((id < 0) || (id > max_elements) || (id_table[id] == NULL))\n {\n std::cout << \"ID \" << id << \" nao existente\" << std::endl;\n return;\n }\n\n remove_from_table(fn_table,id_table[id],hash(id_table[id]->first_name));\n remove_from_table(ln_table,id_table[id],hash(id_table[id]->last_name));\n remove_from_table(birth_table,id_table[id],hash(id_table[id]->birthday));\n remove_from_table(phone_table,id_table[id],hash(id_table[id]->phone));\n id_table[id].reset();\n }\n\n void info(int id)\n {\n if((id < 0) || (id > max_elements) || (id_table[id] == NULL))\n {\n std::cout << \"ID \" << id << \" nao existente.\" << std::endl;\n return;\n }\n\n std::cout << id_table[id]->first_name << \" \"\n << id_table[id]->last_name << \" \"\n << id_table[id]->birthday << \" \"\n << id_table[id]->phone << std::endl;\n }\n private:\n const unsigned int max_elements; \/\/ Large prime number chosen\n HashTable id_table;\n HashTable fn_table;\n HashTable ln_table;\n HashTable birth_table;\n HashTable phone_table;\n\n\n unsigned int hash(const std::string &str)\n {\n unsigned int hash_number = 0;\n unsigned int mult = 1;\n\n for(char c : str)\n {\n hash_number += c * mult;\n ++mult;\n }\n\n return hash_number % max_elements;\n }\n\n void insert_on_table(HashTable &table,Person_ptr person,unsigned int hash_number)\n {\n if(table[hash_number] != NULL)\n {\n person->collision = table[hash_number];\n }\n\n table[hash_number] = person;\n }\n\n void remove_from_table(HashTable &table,Person_ptr person,unsigned int hash_number)\n {\n if(table[hash_number] != NULL)\n {\n Person_ptr last_person;\n Person_ptr people_itr = table[hash_number];\n do\n {\n if(people_itr->id == person->id)\n {\n break;\n }\n last_person = people_itr;\n people_itr = people_itr->collision;\n }while(people_itr != NULL);\n\n if(last_person != NULL)\n {\n last_person->collision = people_itr->collision;\n people_itr.reset();\n }\n else\n {\n table[hash_number] = table[hash_number]->collision;\n }\n }\n }\n};\n\nint main(void)\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tclap\/CmdLine.h>\n#include <llvm\/IR\/Module.h>\n#include <fstream>\n#include <sstream>\n#include <chrono>\n\n#include \"utils\/util.hpp\"\n#include \"utils\/error.hpp\"\n#include \"lexer.hpp\"\n#include \"parser\/tokenParser.hpp\"\n#include \"parser\/xmlParser.hpp\"\n#include \"llvm\/compiler.hpp\"\n#include \"llvm\/runner.hpp\"\n\nenum ExitCodes: int {\n NORMAL_EXIT = 0, \/\/\/< Everything is OK\n TCLAP_ERROR = 11, \/\/\/< TCLAP did something bad, should not happen\n CLI_ERROR = 1, \/\/\/< The user used a wrong combination of options\n USER_PROGRAM_ERROR = 2, \/\/\/< The thing we had to lex\/parse\/run has an issue\n INTERNAL_ERROR = 3 \/\/\/< Unrecoverable error in this program, almost always a bug\n};\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-declarations\"\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wmissing-prototypes\"\n#endif\n\nstd::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {\n if (!filePath.empty()) {\n \/\/ Read from file\n auto file = rapidxml::file<>(filePath.c_str());\n return std::make_unique<AST>(XMLParser().parse(file).getTree());\n } else {\n \/\/ Read from CLI\n char* mutableCode = new char[cliEval.size() + 1];\n std::move(ALL(cliEval), mutableCode);\n mutableCode[cliEval.size()] = '\\0';\n return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());\n }\n}\n\nstd::vector<Token> tokenize(fs::path filePath, std::string cliEval) {\n std::string input;\n if (!filePath.empty()) {\n std::ifstream file(filePath);\n std::stringstream buffer;\n buffer << file.rdbuf();\n input = buffer.str();\n } else {\n input = cliEval;\n }\n auto lx = Lexer();\n return lx.tokenize(input, filePath.empty() ? \"<cli-eval>\" : filePath).getTokens();\n}\n\n\/\/\/ Throw if the assertion is false\nvoid assertCliIntegrity(TCLAP::CmdLine& cmd, bool assertion, std::string message) {\n if (!assertion) return;\n TCLAP::ArgException arg(message);\n cmd.getOutput()->failure(cmd, arg);\n}\n\n\/\/\/ Pseudo-main used to allow early returns while measuring execution time\nint notReallyMain(int argc, const char* argv[]) {\n try {\n TCLAP::CmdLine cmd(\"Xylene\", ' ', \"pre-release\");\n \n TCLAP::SwitchArg asXML(\"\", \"xml\", \"Read file using the XML parser\", cmd);\n \n TCLAP::SwitchArg printTokens(\"\", \"tokens\", \"Print token list (if applicable)\", cmd);\n TCLAP::SwitchArg printAST(\"\", \"ast\", \"Print AST (if applicable)\", cmd);\n TCLAP::SwitchArg printIR(\"\", \"ir\", \"Print LLVM IR (if applicable)\", cmd);\n \n TCLAP::SwitchArg doNotParse(\"\", \"no-parse\", \"Don't parse the token list\", cmd);\n TCLAP::SwitchArg doNotRun(\"\", \"no-run\", \"Don't execute the AST\", cmd);\n \n std::vector<std::string> runnerValues {\"interpret\", \"compile\"};\n TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);\n TCLAP::ValueArg<std::string> runner(\"r\", \"runner\", \"How to run this code\", false,\n \"interpret\", &runnerConstraint, cmd, nullptr);\n \n TCLAP::ValueArg<std::string> code(\"e\", \"eval\", \"Code to evaluate\", false,\n std::string(), \"string\", cmd, nullptr);\n TCLAP::ValueArg<std::string> filePath(\"f\", \"file\", \"Load code from this file\",\n false, std::string(), \"path\", cmd, nullptr);\n TCLAP::ValueArg<std::string> outPath(\"o\", \"output\", \"Write exe to this file\",\n false, std::string(), \"path\", cmd, nullptr);\n cmd.parse(argc, argv);\n \n \/\/ There must be at least one input\n assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),\n \"Must specify either option -e or -f\");\n \n \/\/ There is not much you can do to the XML without parsing it\n assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),\n \"--no-parse and --xml are incompatible\");\n \n \/\/ The XML parser does not use tokens\n assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),\n \"--tokens and --xml are incompatible\");\n \n \/\/ Can't print AST without creating it first\n assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),\n \"--no-parse and --ast are incompatible\");\n \n \/\/ Can't print IR without parsing the AST\n assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),\n \"--no-parse and --ir are incompatible\");\n \n std::unique_ptr<AST> ast;\n \n if (asXML.getValue()) {\n ast = parseXML(filePath.getValue(), code.getValue());\n } else {\n auto tokens = tokenize(filePath.getValue(), code.getValue());\n if (printTokens.getValue()) for (auto tok : tokens) println(tok);\n \n if (doNotParse.getValue()) return NORMAL_EXIT;\n ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());\n }\n \n if (printAST.getValue()) ast->print();\n if (doNotRun.getValue()) return NORMAL_EXIT;\n \n ModuleCompiler::Link mc = ModuleCompiler::create(\"Command Line Module\", *ast);\n mc->visit();\n if (printIR.getValue()) mc->getModule()->dump();\n \n if (runner.getValue() == \"interpret\") {\n return Runner(mc).run();\n } else if (runner.getValue() == \"compile\") {\n Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),\n filePath.getValue(), outPath.getValue()).compile();\n return NORMAL_EXIT;\n }\n } catch (const TCLAP::ExitException& arg) {\n return CLI_ERROR;\n } catch (const TCLAP::ArgException& arg) {\n println(\"TCLAP error\", arg.error(), \"for\", arg.argId());\n return TCLAP_ERROR;\n } catch (const Error& err) {\n println(err.what());\n return USER_PROGRAM_ERROR;\n }\n \/\/ If we're debugging, crash the program on InternalError\n #ifndef CRASH_ON_INTERNAL_ERROR\n catch (const InternalError& err) {\n println(err.what());\n return INTERNAL_ERROR;\n }\n #endif\n return 0;\n}\n\n#pragma GCC diagnostic pop\n\n\/\/\/ Measures execution time if XYLENE_MEASURE_TIME is defined \\see notReallyMain\nint main(int argc, const char* argv[]) {\n #ifdef XYLENE_MEASURE_TIME\n auto begin = std::chrono::steady_clock::now();\n #endif\n \n int exitCode = notReallyMain(argc, argv);\n \n #ifdef XYLENE_MEASURE_TIME\n auto end = std::chrono::steady_clock::now();\n println(\n \"Time diff:\",\n std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),\n \"μs\"\n );\n #endif\n\n return exitCode;\n}\n<commit_msg>Fix -Wunused-exception-parameter warning<commit_after>#include <tclap\/CmdLine.h>\n#include <llvm\/IR\/Module.h>\n#include <fstream>\n#include <sstream>\n#include <chrono>\n\n#include \"utils\/util.hpp\"\n#include \"utils\/error.hpp\"\n#include \"lexer.hpp\"\n#include \"parser\/tokenParser.hpp\"\n#include \"parser\/xmlParser.hpp\"\n#include \"llvm\/compiler.hpp\"\n#include \"llvm\/runner.hpp\"\n\nenum ExitCodes: int {\n NORMAL_EXIT = 0, \/\/\/< Everything is OK\n TCLAP_ERROR = 11, \/\/\/< TCLAP did something bad, should not happen\n CLI_ERROR = 1, \/\/\/< The user used a wrong combination of options\n USER_PROGRAM_ERROR = 2, \/\/\/< The thing we had to lex\/parse\/run has an issue\n INTERNAL_ERROR = 3 \/\/\/< Unrecoverable error in this program, almost always a bug\n};\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-declarations\"\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wmissing-prototypes\"\n#endif\n\nstd::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {\n if (!filePath.empty()) {\n \/\/ Read from file\n auto file = rapidxml::file<>(filePath.c_str());\n return std::make_unique<AST>(XMLParser().parse(file).getTree());\n } else {\n \/\/ Read from CLI\n char* mutableCode = new char[cliEval.size() + 1];\n std::move(ALL(cliEval), mutableCode);\n mutableCode[cliEval.size()] = '\\0';\n return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());\n }\n}\n\nstd::vector<Token> tokenize(fs::path filePath, std::string cliEval) {\n std::string input;\n if (!filePath.empty()) {\n std::ifstream file(filePath);\n std::stringstream buffer;\n buffer << file.rdbuf();\n input = buffer.str();\n } else {\n input = cliEval;\n }\n auto lx = Lexer();\n return lx.tokenize(input, filePath.empty() ? \"<cli-eval>\" : filePath).getTokens();\n}\n\n\/\/\/ Throw if the assertion is false\nvoid assertCliIntegrity(TCLAP::CmdLine& cmd, bool assertion, std::string message) {\n if (!assertion) return;\n TCLAP::ArgException arg(message);\n cmd.getOutput()->failure(cmd, arg);\n}\n\n\/\/\/ Pseudo-main used to allow early returns while measuring execution time\nint notReallyMain(int argc, const char* argv[]) {\n try {\n TCLAP::CmdLine cmd(\"Xylene\", ' ', \"pre-release\");\n \n TCLAP::SwitchArg asXML(\"\", \"xml\", \"Read file using the XML parser\", cmd);\n \n TCLAP::SwitchArg printTokens(\"\", \"tokens\", \"Print token list (if applicable)\", cmd);\n TCLAP::SwitchArg printAST(\"\", \"ast\", \"Print AST (if applicable)\", cmd);\n TCLAP::SwitchArg printIR(\"\", \"ir\", \"Print LLVM IR (if applicable)\", cmd);\n \n TCLAP::SwitchArg doNotParse(\"\", \"no-parse\", \"Don't parse the token list\", cmd);\n TCLAP::SwitchArg doNotRun(\"\", \"no-run\", \"Don't execute the AST\", cmd);\n \n std::vector<std::string> runnerValues {\"interpret\", \"compile\"};\n TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);\n TCLAP::ValueArg<std::string> runner(\"r\", \"runner\", \"How to run this code\", false,\n \"interpret\", &runnerConstraint, cmd, nullptr);\n \n TCLAP::ValueArg<std::string> code(\"e\", \"eval\", \"Code to evaluate\", false,\n std::string(), \"string\", cmd, nullptr);\n TCLAP::ValueArg<std::string> filePath(\"f\", \"file\", \"Load code from this file\",\n false, std::string(), \"path\", cmd, nullptr);\n TCLAP::ValueArg<std::string> outPath(\"o\", \"output\", \"Write exe to this file\",\n false, std::string(), \"path\", cmd, nullptr);\n cmd.parse(argc, argv);\n \n \/\/ There must be at least one input\n assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),\n \"Must specify either option -e or -f\");\n \n \/\/ There is not much you can do to the XML without parsing it\n assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),\n \"--no-parse and --xml are incompatible\");\n \n \/\/ The XML parser does not use tokens\n assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),\n \"--tokens and --xml are incompatible\");\n \n \/\/ Can't print AST without creating it first\n assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),\n \"--no-parse and --ast are incompatible\");\n \n \/\/ Can't print IR without parsing the AST\n assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),\n \"--no-parse and --ir are incompatible\");\n \n std::unique_ptr<AST> ast;\n \n if (asXML.getValue()) {\n ast = parseXML(filePath.getValue(), code.getValue());\n } else {\n auto tokens = tokenize(filePath.getValue(), code.getValue());\n if (printTokens.getValue()) for (auto tok : tokens) println(tok);\n \n if (doNotParse.getValue()) return NORMAL_EXIT;\n ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());\n }\n \n if (printAST.getValue()) ast->print();\n if (doNotRun.getValue()) return NORMAL_EXIT;\n \n ModuleCompiler::Link mc = ModuleCompiler::create(\"Command Line Module\", *ast);\n mc->visit();\n if (printIR.getValue()) mc->getModule()->dump();\n \n if (runner.getValue() == \"interpret\") {\n return Runner(mc).run();\n } else if (runner.getValue() == \"compile\") {\n Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),\n filePath.getValue(), outPath.getValue()).compile();\n return NORMAL_EXIT;\n }\n } catch (const TCLAP::ExitException&) {\n return CLI_ERROR;\n } catch (const TCLAP::ArgException& arg) {\n println(\"TCLAP error\", arg.error(), \"for\", arg.argId());\n return TCLAP_ERROR;\n } catch (const Error& err) {\n println(err.what());\n return USER_PROGRAM_ERROR;\n }\n \/\/ If we're debugging, crash the program on InternalError\n #ifndef CRASH_ON_INTERNAL_ERROR\n catch (const InternalError& err) {\n println(err.what());\n return INTERNAL_ERROR;\n }\n #endif\n return 0;\n}\n\n#pragma GCC diagnostic pop\n\n\/\/\/ Measures execution time if XYLENE_MEASURE_TIME is defined \\see notReallyMain\nint main(int argc, const char* argv[]) {\n #ifdef XYLENE_MEASURE_TIME\n auto begin = std::chrono::steady_clock::now();\n #endif\n \n int exitCode = notReallyMain(argc, argv);\n \n #ifdef XYLENE_MEASURE_TIME\n auto end = std::chrono::steady_clock::now();\n println(\n \"Time diff:\",\n std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),\n \"μs\"\n );\n #endif\n\n return exitCode;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"blackmagicsdk_video_source.h\"\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n \/\/ This constructor should never be called,\n \/\/ therefore setting I420 arbitrarily for the\n \/\/ buffer video frame here.\n , _buffer_video_frame(VideoFrame(I420))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _running(false)\n{\n switch(_colour)\n {\n case BGRA:\n break;\n case I420:\n default:\n release_deck_link();\n throw VideoSourceError(\n \"BlackmagicSDK video source supports only BGRA\"\n );\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\"DeckLink drivers do not appear to be installed\");\n }\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n }\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not connect to any Blackmagic DeckLink device\");\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not set the callback of Blackmagic DeckLink device\");\n }\n\n \/\/ Try to set the first available of the following modes (in descending frame-rate order)\n std::vector<BMDDisplayMode> display_modes =\n { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50,\n bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25,\n bmdModeHD1080p24, bmdModeHD1080p2398 };\n \/\/ and BGRA as pixel format\n BMDPixelFormat pixel_format = bmdFormat8BitBGRA;\n \/\/ and these video flags\n BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection;\n \/\/ These two are output variables\n BMDDisplayModeSupport display_mode_support;\n IDeckLinkDisplayMode * deck_link_display_mode = nullptr;\n \/\/ Flag for indicating the result of the video input enable attempt\n bool enabled_video_input = false;\n \/\/ And an error string to be set according to any failing intermediate step\n std::string error_msg = \"\";\n\n \/\/ Now loop through the set of modes\n for (BMDDisplayMode display_mode : display_modes)\n {\n \/\/ Check whether the mode is supported\n res = _deck_link_input->DoesSupportVideoMode(\n display_mode, pixel_format, video_input_flags,\n &display_mode_support, &deck_link_display_mode\n );\n \/\/ No glory (could not even check mode support)\n if (res != S_OK or deck_link_display_mode == nullptr)\n {\n error_msg = \"Could not check video mode support of Blackmagic DeckLink device\";\n break;\n }\n\n \/\/ If mode supported, set it and exit loop\n if (display_mode_support == bmdDisplayModeSupported)\n {\n \/\/ Get frame rate of DeckLink device\n BMDTimeValue frame_rate_duration, frame_rate_scale;\n res = deck_link_display_mode->GetFrameRate(&frame_rate_duration, &frame_rate_scale);\n \/\/ No glory\n if (res != S_OK)\n {\n error_msg = \"Could not infer frame rate of Blackmagic DeckLink device\";\n break;\n }\n _frame_rate = (double) frame_rate_scale \/ (double) frame_rate_duration;\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(display_mode,\n pixel_format,\n video_input_flags);\n \/\/ No glory\n if (res != S_OK)\n {\n error_msg = \"Could not enable video input of Blackmagic DeckLink device\";\n break;\n }\n }\n\n \/\/ Release the DeckLink display mode object at each iteration\n if (deck_link_display_mode != nullptr)\n {\n deck_link_display_mode->Release();\n deck_link_display_mode = nullptr;\n }\n\n if (enabled_video_input)\n break;\n }\n\n \/\/ Release the DeckLink display mode object in case loop pre-maturely broken\n if (deck_link_display_mode != nullptr)\n deck_link_display_mode->Release();\n\n \/\/ No glory (loop exited without success): release everything and throw exception\n if (not enabled_video_input)\n {\n release_deck_link();\n \/\/ If all modes checked, and none is supported!\n if (error_msg.empty())\n error_msg = \"Could not enable video input of Blackmagic DeckLink device\";\n \/\/ Else: an intermediate step went wrong, so put that into the exception\n throw VideoSourceError(error_msg);\n }\n\n \/\/ Disable audio input\n res = _deck_link_input->DisableAudioInput();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not disable audio input of Blackmagic DeckLink device\");\n }\n\n \/\/ Start streaming\n _running = true;\n res = _deck_link_input->StartStreams();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n _running = false;\n release_deck_link();\n throw VideoSourceError(\"Could not start streaming from the Blackmagic DeckLink device\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n \/\/ Make sure streamer thread not trying to access buffer\n std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n _running = false;\n\n \/\/ Stop streaming and disable enabled inputs\n _deck_link_input->StopStreams();\n _deck_link_input->DisableVideoInput();\n\n \/\/ Release DeckLink members\n release_deck_link();\n\n \/\/ Release allocated memory\n free(_video_buffer);\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ TODO\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n \/\/ TODO\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n this->Release();\n\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n}\n\n}\n<commit_msg>Issue #5: added missing line signaling video input enabled to mode selection loop<commit_after>#include \"blackmagicsdk_video_source.h\"\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n \/\/ This constructor should never be called,\n \/\/ therefore setting I420 arbitrarily for the\n \/\/ buffer video frame here.\n , _buffer_video_frame(VideoFrame(I420))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _running(false)\n{\n switch(_colour)\n {\n case BGRA:\n break;\n case I420:\n default:\n release_deck_link();\n throw VideoSourceError(\n \"BlackmagicSDK video source supports only BGRA\"\n );\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\"DeckLink drivers do not appear to be installed\");\n }\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n }\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not connect to any Blackmagic DeckLink device\");\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not set the callback of Blackmagic DeckLink device\");\n }\n\n \/\/ Try to set the first available of the following modes (in descending frame-rate order)\n std::vector<BMDDisplayMode> display_modes =\n { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50,\n bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25,\n bmdModeHD1080p24, bmdModeHD1080p2398 };\n \/\/ and BGRA as pixel format\n BMDPixelFormat pixel_format = bmdFormat8BitBGRA;\n \/\/ and these video flags\n BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection;\n \/\/ These two are output variables\n BMDDisplayModeSupport display_mode_support;\n IDeckLinkDisplayMode * deck_link_display_mode = nullptr;\n \/\/ Flag for indicating the result of the video input enable attempt\n bool enabled_video_input = false;\n \/\/ And an error string to be set according to any failing intermediate step\n std::string error_msg = \"\";\n\n \/\/ Now loop through the set of modes\n for (BMDDisplayMode display_mode : display_modes)\n {\n \/\/ Check whether the mode is supported\n res = _deck_link_input->DoesSupportVideoMode(\n display_mode, pixel_format, video_input_flags,\n &display_mode_support, &deck_link_display_mode\n );\n \/\/ No glory (could not even check mode support)\n if (res != S_OK or deck_link_display_mode == nullptr)\n {\n error_msg = \"Could not check video mode support of Blackmagic DeckLink device\";\n break;\n }\n\n \/\/ If mode supported, set it and exit loop\n if (display_mode_support == bmdDisplayModeSupported)\n {\n \/\/ Get frame rate of DeckLink device\n BMDTimeValue frame_rate_duration, frame_rate_scale;\n res = deck_link_display_mode->GetFrameRate(&frame_rate_duration, &frame_rate_scale);\n \/\/ No glory\n if (res != S_OK)\n {\n error_msg = \"Could not infer frame rate of Blackmagic DeckLink device\";\n break;\n }\n _frame_rate = (double) frame_rate_scale \/ (double) frame_rate_duration;\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(display_mode,\n pixel_format,\n video_input_flags);\n \/\/ No glory\n if (res != S_OK)\n {\n error_msg = \"Could not enable video input of Blackmagic DeckLink device\";\n break;\n }\n\n enabled_video_input = true;\n }\n\n \/\/ Release the DeckLink display mode object at each iteration\n if (deck_link_display_mode != nullptr)\n {\n deck_link_display_mode->Release();\n deck_link_display_mode = nullptr;\n }\n\n if (enabled_video_input)\n break;\n }\n\n \/\/ Release the DeckLink display mode object in case loop pre-maturely broken\n if (deck_link_display_mode != nullptr)\n deck_link_display_mode->Release();\n\n \/\/ No glory (loop exited without success): release everything and throw exception\n if (not enabled_video_input)\n {\n release_deck_link();\n \/\/ If all modes checked, and none is supported!\n if (error_msg.empty())\n error_msg = \"Could not enable video input of Blackmagic DeckLink device\";\n \/\/ Else: an intermediate step went wrong, so put that into the exception\n throw VideoSourceError(error_msg);\n }\n\n \/\/ Disable audio input\n res = _deck_link_input->DisableAudioInput();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not disable audio input of Blackmagic DeckLink device\");\n }\n\n \/\/ Start streaming\n _running = true;\n res = _deck_link_input->StartStreams();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n _running = false;\n release_deck_link();\n throw VideoSourceError(\"Could not start streaming from the Blackmagic DeckLink device\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n \/\/ Make sure streamer thread not trying to access buffer\n std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n _running = false;\n\n \/\/ Stop streaming and disable enabled inputs\n _deck_link_input->StopStreams();\n _deck_link_input->DisableVideoInput();\n\n \/\/ Release DeckLink members\n release_deck_link();\n\n \/\/ Release allocated memory\n free(_video_buffer);\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ TODO\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n \/\/ TODO\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n this->Release();\n\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"term.h\"\n#include \"qutils.h\"\n\n#include <sstream>\n#include <boost\/foreach.hpp>\n\nusing namespace std;\n\nTerm::Term(const std::vector<string> components)\n{\n\tbool first = true;\n\n\tforeach (const string &component, components)\n\t{\n\t\tif (first)\n\t\t\tfirst = false;\n\t\telse\n\t\t\t_asString.append(\" \\xE2\\x9C\\xBB \"); \/\/ star spoked asterisk\n\n\t\t_asString.append(component);\n\t\t_components.append(tq(component));\n\t\t_scomponents.push_back(component);\n\t}\n\n\t_asQString = tq(_asString);\n}\n\nTerm::Term(const string component)\n{\n\t_components.append(tq(component));\n\t_scomponents.push_back(component);\n\t_asString = component;\n\t_asQString = tq(component);\n}\n\nTerm::Term(const QStringList components)\n{\n\tbool first = true;\n\n\tforeach (const QString &component, components)\n\t{\n\t\tif (first)\n\t\t\tfirst = false;\n\t\telse\n\t\t\t_asQString += \" \\xE2\\x9C\\xBB \";\n\n\t\t_asQString += component;\n\t\t_components.append(component);\n\t\t_scomponents.push_back(fq(component));\n\t}\n\n\t_asString = fq(_asQString);\n}\n\nTerm::Term(const QString component)\n{\n\t_components.append(component);\n\t_scomponents.push_back(fq(component));\n\t_asQString = component;\n\t_asString = fq(component);\n}\n\nconst QStringList &Term::components() const\n{\n\treturn _components;\n}\n\nconst std::vector<string> &Term::scomponents() const\n{\n\treturn _scomponents;\n}\n\nconst string &Term::asString() const\n{\n\treturn _asString;\n}\n\nbool Term::contains(const string &component) const\n{\n\tBOOST_FOREACH(const string &termComponent, _scomponents)\n\t{\n\t\tif (component == termComponent)\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool Term::containsAll(const Term &term) const\n{\n\tBOOST_FOREACH(const string &termComponent, term._scomponents)\n\t{\n\t\tif ( ! contains(termComponent))\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool Term::containsAny(const Term &term) const\n{\n\tBOOST_FOREACH(const string &termComponent, _scomponents)\n\t{\n\t\tif (term.contains(termComponent))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nconst QString &Term::asQString() const\n{\n\treturn _asQString;\n}\n\nTerm::iterator Term::begin()\n{\n\treturn _components.begin();\n}\n\nTerm::iterator Term::end()\n{\n\treturn _components.end();\n}\n\nconst QString &Term::at(int index) const\n{\n\treturn _components.at(index);\n}\n\nbool Term::operator==(const Term &other) const\n{\n\tif (this == &other)\n\t\treturn true;\n\n\treturn components() == other.components();\n}\n\nbool Term::operator!=(const Term &other) const\n{\n\treturn this->operator==(other) == false;\n}\n\nsize_t Term::size() const\n{\n\treturn _components.size();\n}\n<commit_msg>Tweak to interaction separator<commit_after>\n#include \"term.h\"\n#include \"qutils.h\"\n\n#include <sstream>\n#include <boost\/foreach.hpp>\n\nusing namespace std;\n\nTerm::Term(const std::vector<string> components)\n{\n\tbool first = true;\n\n\tforeach (const string &component, components)\n\t{\n\t\tif (first)\n\t\t\tfirst = false;\n\t\telse\n#ifdef __WIN32__\n\t\t\t_asString.append(\" * \");\n#else\n\t\t\t_asString.append(\" \\xE2\\x88\\x97 \");\n#endif\n\n\t\t_asString.append(component);\n\t\t_components.append(tq(component));\n\t\t_scomponents.push_back(component);\n\t}\n\n\t_asQString = tq(_asString);\n}\n\nTerm::Term(const string component)\n{\n\t_components.append(tq(component));\n\t_scomponents.push_back(component);\n\t_asString = component;\n\t_asQString = tq(component);\n}\n\nTerm::Term(const QStringList components)\n{\n\tbool first = true;\n\n\tforeach (const QString &component, components)\n\t{\n\t\tif (first)\n\t\t\tfirst = false;\n\t\telse\n#ifdef __WIN32__\n\t\t\t_asQString.append(\" * \");\n#else\n\t\t\t_asQString.append(\" \\xE2\\x88\\x97 \");\n#endif\n\n\t\t_asQString += component;\n\t\t_components.append(component);\n\t\t_scomponents.push_back(fq(component));\n\t}\n\n\t_asString = fq(_asQString);\n}\n\nTerm::Term(const QString component)\n{\n\t_components.append(component);\n\t_scomponents.push_back(fq(component));\n\t_asQString = component;\n\t_asString = fq(component);\n}\n\nconst QStringList &Term::components() const\n{\n\treturn _components;\n}\n\nconst std::vector<string> &Term::scomponents() const\n{\n\treturn _scomponents;\n}\n\nconst string &Term::asString() const\n{\n\treturn _asString;\n}\n\nbool Term::contains(const string &component) const\n{\n\tBOOST_FOREACH(const string &termComponent, _scomponents)\n\t{\n\t\tif (component == termComponent)\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool Term::containsAll(const Term &term) const\n{\n\tBOOST_FOREACH(const string &termComponent, term._scomponents)\n\t{\n\t\tif ( ! contains(termComponent))\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool Term::containsAny(const Term &term) const\n{\n\tBOOST_FOREACH(const string &termComponent, _scomponents)\n\t{\n\t\tif (term.contains(termComponent))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nconst QString &Term::asQString() const\n{\n\treturn _asQString;\n}\n\nTerm::iterator Term::begin()\n{\n\treturn _components.begin();\n}\n\nTerm::iterator Term::end()\n{\n\treturn _components.end();\n}\n\nconst QString &Term::at(int index) const\n{\n\treturn _components.at(index);\n}\n\nbool Term::operator==(const Term &other) const\n{\n\tif (this == &other)\n\t\treturn true;\n\n\treturn components() == other.components();\n}\n\nbool Term::operator!=(const Term &other) const\n{\n\treturn this->operator==(other) == false;\n}\n\nsize_t Term::size() const\n{\n\treturn _components.size();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <rai\/node\/node.hpp>\n#include <rai\/node\/rpc_secure.hpp>\n\nbool rai::rpc_secure::on_verify_certificate (bool preverified, boost::asio::ssl::verify_context & ctx)\n{\n\tX509_STORE_CTX * cts = ctx.native_handle ();\n\tauto error (X509_STORE_CTX_get_error (cts));\n\tswitch (error)\n\t{\n\t\tcase X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Unable to get issuer\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_NOT_YET_VALID:\n\t\tcase X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Certificate not yet valid\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_HAS_EXPIRED:\n\t\tcase X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Certificate expired\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:\n\t\t\tif (config.secure.verbose_logging)\n\t\t\t{\n\t\t\t\tBOOST_LOG (node.log) << \"TLS: self signed certificate in chain\";\n\t\t\t}\n\n\t\t\t\/\/ Allow self-signed certificates\n\t\t\tpreverified = true;\n\t\t\tbreak;\n\t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Self signed certificate not in the list of trusted certs (forgot to subject-hash certificate filename?)\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tif (config.secure.verbose_logging)\n\t{\n\t\tif (error != 0)\n\t\t{\n\t\t\tBOOST_LOG (node.log) << \"TLS: Error: \" << X509_verify_cert_error_string (error);\n\t\t\tBOOST_LOG (node.log) << \"TLS: Error chain depth : \" << X509_STORE_CTX_get_error_depth (cts);\n\t\t}\n\n\t\tX509 * cert = X509_STORE_CTX_get_current_cert (cts);\n\t\tchar subject_name[512];\n\t\tX509_NAME_oneline (X509_get_subject_name (cert), subject_name, sizeof (subject_name) - 1);\n\t\tBOOST_LOG (node.log) << \"TLS: Verifying: \" << subject_name;\n\t\tBOOST_LOG (node.log) << \"TLS: Verification: \" << preverified;\n\t}\n\telse if (!preverified)\n\t{\n\t\tBOOST_LOG (node.log) << \"TLS: Pre-verification failed. Turn on verbose logging for more information.\";\n\t}\n\n\treturn preverified;\n}\n\nvoid rai::rpc_secure::load_certs (boost::asio::ssl::context & context_a)\n{\n\t\/\/ This is called if the key is password protected\n\tcontext_a.set_password_callback (\n\t[this](std::size_t,\n\tboost::asio::ssl::context_base::password_purpose) {\n\t\treturn config.secure.server_key_passphrase;\n\t});\n\n\t\/\/ The following two options disables the session cache and enables stateless session resumption.\n\t\/\/ This is necessary because of the way the RPC server abruptly terminate connections.\n\tSSL_CTX_set_session_cache_mode (context_a.native_handle (), SSL_SESS_CACHE_OFF);\n\tSSL_CTX_set_options (context_a.native_handle (), SSL_OP_NO_TICKET);\n\n\tcontext_a.set_options (\n\tboost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::no_sslv3 | boost::asio::ssl::context::single_dh_use);\n\n\tcontext_a.use_certificate_chain_file (config.secure.server_cert_path);\n\tcontext_a.use_private_key_file (config.secure.server_key_path, boost::asio::ssl::context::pem);\n\tcontext_a.use_tmp_dh_file (config.secure.server_dh_path);\n\n\t\/\/ Verify client certificates?\n\tif (config.secure.client_certs_path.size () > 0)\n\t{\n\t\tcontext_a.set_verify_mode (boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_peer);\n\t\tcontext_a.add_verify_path (config.secure.client_certs_path);\n\t\tcontext_a.set_verify_callback (boost::bind (&rai::rpc_secure::on_verify_certificate, this, _1, _2));\n\t}\n}\n\nrai::rpc_secure::rpc_secure (boost::asio::io_service & service_a, rai::node & node_a, rai::rpc_config const & config_a) :\nrpc (service_a, node_a, config_a),\nssl_context (boost::asio::ssl::context::tlsv12_server)\n{\n\tload_certs (ssl_context);\n}\n\nvoid rai::rpc_secure::accept ()\n{\n\tauto connection (std::make_shared<rai::rpc_connection_secure> (node, *this));\n\tacceptor.async_accept (connection->socket, [this, connection](boost::system::error_code const & ec) {\n\t\tif (acceptor.is_open ())\n\t\t{\n\t\t\taccept ();\n\t\t}\n\t\tif (!ec)\n\t\t{\n\t\t\tconnection->parse_connection ();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_LOG (this->node.log) << boost::str (boost::format (\"Error accepting RPC connections: %1%\") % ec);\n\t\t}\n\t});\n}\n\nrai::rpc_connection_secure::rpc_connection_secure (rai::node & node_a, rai::rpc_secure & rpc_a) :\nrai::rpc_connection (node_a, rpc_a),\nstream (socket, rpc_a.ssl_context)\n{\n}\n\nvoid rai::rpc_connection_secure::parse_connection ()\n{\n\t\/\/ Perform the SSL handshake\n\tstream.async_handshake (boost::asio::ssl::stream_base::server,\n\tstd::bind (\n\t&rai::rpc_connection_secure::handle_handshake,\n\tstd::static_pointer_cast<rai::rpc_connection_secure> (shared_from_this ()),\n\tstd::placeholders::_1));\n}\n\nvoid rai::rpc_connection_secure::on_shutdown (const boost::system::error_code & error)\n{\n\t\/\/ No-op. We initiate the shutdown (since the RPC server kills the connection after each request)\n\t\/\/ and we'll thus get an expected EOF error. If the client disconnects, a short-read error will be expected.\n}\n\nvoid rai::rpc_connection_secure::handle_handshake (const boost::system::error_code & error)\n{\n\tif (!error)\n\t{\n\t\tread ();\n\t}\n\telse\n\t{\n\t\tBOOST_LOG (node->log) << \"TLS: Handshake error: \" << error.message ();\n\t}\n}\n\nvoid rai::rpc_connection_secure::read ()\n{\n\tauto this_l (std::static_pointer_cast<rai::rpc_connection_secure> (shared_from_this ()));\n\tboost::beast::http::async_read (stream, buffer, request, [this_l](boost::system::error_code const & ec, size_t bytes_transferred) {\n\t\tif (!ec)\n\t\t{\n\t\t\tthis_l->node->background ([this_l]() {\n\t\t\t\tauto start (std::chrono::steady_clock::now ());\n\t\t\t\tauto version (this_l->request.version ());\n\t\t\t\tstd::string request_id (boost::str (boost::format (\"%1%\") % boost::io::group (std::hex, std::showbase, reinterpret_cast<uintptr_t> (this_l.get ()))));\n\t\t\t\tauto response_handler ([this_l, version, start, request_id](boost::property_tree::ptree const & tree_a) {\n\t\t\t\t\tstd::stringstream ostream;\n\t\t\t\t\tboost::property_tree::write_json (ostream, tree_a);\n\t\t\t\t\tostream.flush ();\n\t\t\t\t\tauto body (ostream.str ());\n\t\t\t\t\tthis_l->write_result (body, version);\n\t\t\t\t\tboost::beast::http::async_write (this_l->stream, this_l->res, [this_l](boost::system::error_code const & ec, size_t bytes_transferred) {\n\t\t\t\t\t\t\/\/ Perform the SSL shutdown\n\t\t\t\t\t\tthis_l->stream.async_shutdown (\n\t\t\t\t\t\tstd::bind (\n\t\t\t\t\t\t&rai::rpc_connection_secure::on_shutdown,\n\t\t\t\t\t\tthis_l,\n\t\t\t\t\t\tstd::placeholders::_1));\n\t\t\t\t\t});\n\n\t\t\t\t\tif (this_l->node->config.logging.log_rpc ())\n\t\t\t\t\t{\n\t\t\t\t\t\tBOOST_LOG (this_l->node->log) << boost::str (boost::format (\"TLS: RPC request %2% completed in: %1% microseconds\") % std::chrono::duration_cast<std::chrono::microseconds> (std::chrono::steady_clock::now () - start).count () % request_id);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (this_l->request.method () == boost::beast::http::verb::post)\n\t\t\t\t{\n\t\t\t\t\tauto handler (std::make_shared<rai::rpc_handler> (*this_l->node, this_l->rpc, this_l->request.body (), request_id, response_handler));\n\t\t\t\t\thandler->process_request ();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terror_response (response_handler, \"Can only POST requests\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_LOG (this_l->node->log) << \"TLS: Read error: \" << ec.message () << std::endl;\n\t\t}\n\t});\n}\n<commit_msg>Replace bind with lambda (#1498)<commit_after>#include <rai\/node\/node.hpp>\n#include <rai\/node\/rpc_secure.hpp>\n\nbool rai::rpc_secure::on_verify_certificate (bool preverified, boost::asio::ssl::verify_context & ctx)\n{\n\tX509_STORE_CTX * cts = ctx.native_handle ();\n\tauto error (X509_STORE_CTX_get_error (cts));\n\tswitch (error)\n\t{\n\t\tcase X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Unable to get issuer\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_NOT_YET_VALID:\n\t\tcase X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Certificate not yet valid\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_CERT_HAS_EXPIRED:\n\t\tcase X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Certificate expired\";\n\t\t\tbreak;\n\t\tcase X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:\n\t\t\tif (config.secure.verbose_logging)\n\t\t\t{\n\t\t\t\tBOOST_LOG (node.log) << \"TLS: self signed certificate in chain\";\n\t\t\t}\n\n\t\t\t\/\/ Allow self-signed certificates\n\t\t\tpreverified = true;\n\t\t\tbreak;\n\t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n\t\t\tBOOST_LOG (node.log) << \"TLS: Self signed certificate not in the list of trusted certs (forgot to subject-hash certificate filename?)\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tif (config.secure.verbose_logging)\n\t{\n\t\tif (error != 0)\n\t\t{\n\t\t\tBOOST_LOG (node.log) << \"TLS: Error: \" << X509_verify_cert_error_string (error);\n\t\t\tBOOST_LOG (node.log) << \"TLS: Error chain depth : \" << X509_STORE_CTX_get_error_depth (cts);\n\t\t}\n\n\t\tX509 * cert = X509_STORE_CTX_get_current_cert (cts);\n\t\tchar subject_name[512];\n\t\tX509_NAME_oneline (X509_get_subject_name (cert), subject_name, sizeof (subject_name) - 1);\n\t\tBOOST_LOG (node.log) << \"TLS: Verifying: \" << subject_name;\n\t\tBOOST_LOG (node.log) << \"TLS: Verification: \" << preverified;\n\t}\n\telse if (!preverified)\n\t{\n\t\tBOOST_LOG (node.log) << \"TLS: Pre-verification failed. Turn on verbose logging for more information.\";\n\t}\n\n\treturn preverified;\n}\n\nvoid rai::rpc_secure::load_certs (boost::asio::ssl::context & context_a)\n{\n\t\/\/ This is called if the key is password protected\n\tcontext_a.set_password_callback (\n\t[this](std::size_t,\n\tboost::asio::ssl::context_base::password_purpose) {\n\t\treturn config.secure.server_key_passphrase;\n\t});\n\n\t\/\/ The following two options disables the session cache and enables stateless session resumption.\n\t\/\/ This is necessary because of the way the RPC server abruptly terminate connections.\n\tSSL_CTX_set_session_cache_mode (context_a.native_handle (), SSL_SESS_CACHE_OFF);\n\tSSL_CTX_set_options (context_a.native_handle (), SSL_OP_NO_TICKET);\n\n\tcontext_a.set_options (\n\tboost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::no_sslv3 | boost::asio::ssl::context::single_dh_use);\n\n\tcontext_a.use_certificate_chain_file (config.secure.server_cert_path);\n\tcontext_a.use_private_key_file (config.secure.server_key_path, boost::asio::ssl::context::pem);\n\tcontext_a.use_tmp_dh_file (config.secure.server_dh_path);\n\n\t\/\/ Verify client certificates?\n\tif (config.secure.client_certs_path.size () > 0)\n\t{\n\t\tcontext_a.set_verify_mode (boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_peer);\n\t\tcontext_a.add_verify_path (config.secure.client_certs_path);\n\t\tcontext_a.set_verify_callback ([this](auto preverified, auto & ctx) {\n\t\t\treturn on_verify_certificate (preverified, ctx);\n\t\t});\n\t}\n}\n\nrai::rpc_secure::rpc_secure (boost::asio::io_service & service_a, rai::node & node_a, rai::rpc_config const & config_a) :\nrpc (service_a, node_a, config_a),\nssl_context (boost::asio::ssl::context::tlsv12_server)\n{\n\tload_certs (ssl_context);\n}\n\nvoid rai::rpc_secure::accept ()\n{\n\tauto connection (std::make_shared<rai::rpc_connection_secure> (node, *this));\n\tacceptor.async_accept (connection->socket, [this, connection](boost::system::error_code const & ec) {\n\t\tif (acceptor.is_open ())\n\t\t{\n\t\t\taccept ();\n\t\t}\n\t\tif (!ec)\n\t\t{\n\t\t\tconnection->parse_connection ();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_LOG (this->node.log) << boost::str (boost::format (\"Error accepting RPC connections: %1%\") % ec);\n\t\t}\n\t});\n}\n\nrai::rpc_connection_secure::rpc_connection_secure (rai::node & node_a, rai::rpc_secure & rpc_a) :\nrai::rpc_connection (node_a, rpc_a),\nstream (socket, rpc_a.ssl_context)\n{\n}\n\nvoid rai::rpc_connection_secure::parse_connection ()\n{\n\t\/\/ Perform the SSL handshake\n\tauto this_l = std::static_pointer_cast<rai::rpc_connection_secure> (shared_from_this ());\n\tstream.async_handshake (boost::asio::ssl::stream_base::server,\n\t[this_l](auto & ec) {\n\t\tthis_l->handle_handshake (ec);\n\t});\n}\n\nvoid rai::rpc_connection_secure::on_shutdown (const boost::system::error_code & error)\n{\n\t\/\/ No-op. We initiate the shutdown (since the RPC server kills the connection after each request)\n\t\/\/ and we'll thus get an expected EOF error. If the client disconnects, a short-read error will be expected.\n}\n\nvoid rai::rpc_connection_secure::handle_handshake (const boost::system::error_code & error)\n{\n\tif (!error)\n\t{\n\t\tread ();\n\t}\n\telse\n\t{\n\t\tBOOST_LOG (node->log) << \"TLS: Handshake error: \" << error.message ();\n\t}\n}\n\nvoid rai::rpc_connection_secure::read ()\n{\n\tauto this_l (std::static_pointer_cast<rai::rpc_connection_secure> (shared_from_this ()));\n\tboost::beast::http::async_read (stream, buffer, request, [this_l](boost::system::error_code const & ec, size_t bytes_transferred) {\n\t\tif (!ec)\n\t\t{\n\t\t\tthis_l->node->background ([this_l]() {\n\t\t\t\tauto start (std::chrono::steady_clock::now ());\n\t\t\t\tauto version (this_l->request.version ());\n\t\t\t\tstd::string request_id (boost::str (boost::format (\"%1%\") % boost::io::group (std::hex, std::showbase, reinterpret_cast<uintptr_t> (this_l.get ()))));\n\t\t\t\tauto response_handler ([this_l, version, start, request_id](boost::property_tree::ptree const & tree_a) {\n\t\t\t\t\tstd::stringstream ostream;\n\t\t\t\t\tboost::property_tree::write_json (ostream, tree_a);\n\t\t\t\t\tostream.flush ();\n\t\t\t\t\tauto body (ostream.str ());\n\t\t\t\t\tthis_l->write_result (body, version);\n\t\t\t\t\tboost::beast::http::async_write (this_l->stream, this_l->res, [this_l](boost::system::error_code const & ec, size_t bytes_transferred) {\n\t\t\t\t\t\t\/\/ Perform the SSL shutdown\n\t\t\t\t\t\tthis_l->stream.async_shutdown ([this_l](auto const & ec_shutdown) {\n\t\t\t\t\t\t\tthis_l->on_shutdown (ec_shutdown);\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\tif (this_l->node->config.logging.log_rpc ())\n\t\t\t\t\t{\n\t\t\t\t\t\tBOOST_LOG (this_l->node->log) << boost::str (boost::format (\"TLS: RPC request %2% completed in: %1% microseconds\") % std::chrono::duration_cast<std::chrono::microseconds> (std::chrono::steady_clock::now () - start).count () % request_id);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (this_l->request.method () == boost::beast::http::verb::post)\n\t\t\t\t{\n\t\t\t\t\tauto handler (std::make_shared<rai::rpc_handler> (*this_l->node, this_l->rpc, this_l->request.body (), request_id, response_handler));\n\t\t\t\t\thandler->process_request ();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terror_response (response_handler, \"Can only POST requests\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOST_LOG (this_l->node->log) << \"TLS: Read error: \" << ec.message () << std::endl;\n\t\t}\n\t});\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date July 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libwhisper\/WhisperDB.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nBOOST_AUTO_TEST_SUITE(whisperDB)\n\nBOOST_AUTO_TEST_CASE(first)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Whisper DB...\";\n\n\tWhisperDB db;\n\n\th256 h1(0x12345678);\n\th256 h2(0xBADD00DE);\n\n\tstring s;\n\tstring const text1 = \"lorem_ipsum\";\n\tstring const text2 = \"dolor_sit_amet\";\n\n\tdb.erase(h1);\n\tdb.erase(h2);\n\n\tdb.put(h1, text2);\n\ts = db.get(h2);\n\tBOOST_REQUIRE(s.empty());\n\ts = db.get(h1);\n\tBOOST_REQUIRE(!s.compare(text2));\n\n\tdb.put(h1, text1);\n\ts = db.get(h2);\n\tBOOST_REQUIRE(s.empty());\n\ts = db.get(h1);\n\tBOOST_REQUIRE(!s.compare(text1));\n\n\tdb.put(h2, text2);\n\ts = db.get(h2);\n\tBOOST_REQUIRE(!s.compare(text2));\n\ts = db.get(h1);\n\tBOOST_REQUIRE(!s.compare(text1));\n\n\tdb.erase(h1);\n\tdb.erase(h2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>naming conventions changed<commit_after>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date July 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libwhisper\/WhisperDB.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nBOOST_AUTO_TEST_SUITE(whisperDB)\n\nBOOST_AUTO_TEST_CASE(first)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Whisper DB...\";\n\n\tWhisperDB db;\n\n\th256 h1(0x12345678);\n\th256 h2(0xBADD00DE);\n\n\tstring s;\n\tstring const text1 = \"lorem_ipsum\";\n\tstring const text2 = \"dolor_sit_amet\";\n\n\tdb.kill(h1);\n\tdb.kill(h2);\n\n\tdb.insert(h1, text2);\n\ts = db.lookup(h2);\n\tBOOST_REQUIRE(s.empty());\n\ts = db.lookup(h1);\n\tBOOST_REQUIRE(!s.compare(text2));\n\n\tdb.insert(h1, text1);\n\ts = db.lookup(h2);\n\tBOOST_REQUIRE(s.empty());\n\ts = db.lookup(h1);\n\tBOOST_REQUIRE(!s.compare(text1));\n\n\tdb.insert(h2, text2);\n\ts = db.lookup(h2);\n\tBOOST_REQUIRE(!s.compare(text2));\n\ts = db.lookup(h1);\n\tBOOST_REQUIRE(!s.compare(text1));\n\n\tdb.kill(h1);\n\tdb.kill(h2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n\n#ifndef _QI_ATOMIC_HPP_\n#define _QI_ATOMIC_HPP_\n\n#ifdef _MSC_VER\n# include <windows.h>\n# include <intrin.h>\n\nextern \"C\" long __cdecl _InterlockedIncrement(long volatile *);\nextern \"C\" long __cdecl _InterlockedDecrement(long volatile *);\n\n# pragma intrinsic(_InterlockedIncrement)\n# pragma intrinsic(_InterlockedDecrement)\n\n#endif\n\n#include <boost\/static_assert.hpp>\n\n#include <qi\/config.hpp>\n#include <qi\/macro.hpp>\n\nnamespace qi\n{\n inline long testAndSet(long* cond)\n {\n#if defined __GNUC__\n return __sync_bool_compare_and_swap(cond, 0, 1);\n#elif defined _MSC_VER\n return 1 - InterlockedCompareExchange(cond, 1, 0);\n#else\n #error \"Unknown platform, testAndSet not implemented\"\n#endif\n }\n\n \/* \/!\\ WARNING\n * The 'volatile' is needed even though we use atomic compiler builtins.\n * Without the volatile, a thread doing\n * while (!setIfEquals(1,1))\n * Is never unstuck by a thread doing\n * setIfEquals(0,1)\n *\n * AtomicBase has public member so that it can be initialized at\n * static-initialization time (to make thread-safe static initialization inside\n * functions)\n *\/\n template <typename T>\n struct AtomicBase\n {\n public:\n\n\n \/* prefix operators *\/\n inline T operator++();\n inline T operator--();\n inline AtomicBase<T>& operator=(T value);\n \/** If value is \\p testValue, replace it with \\p setValue.\n * \\return true if swap was performed\n *\/\n inline bool setIfEquals(T testValue, T setValue);\n\n inline T swap(T value);\n\n inline T operator*()\n {\n return _value;\n }\n\n public:\n BOOST_STATIC_ASSERT_MSG(sizeof(T) == sizeof(int), \"qi::Atomic is only supprted for int-like types\");\n\n volatile\n#ifdef _MSC_VER\n long\n#else\n T\n#endif\n _value;\n };\n\n template <typename T>\n class Atomic: public AtomicBase<T>\n {\n public:\n Atomic()\n {\n this->_value = 0;\n }\n\n Atomic(T value)\n {\n this->_value = value;\n }\n };\n#ifdef __GNUC__\n template <typename T>\n inline T AtomicBase<T>::operator++()\n {\n return __sync_add_and_fetch(&_value, 1);\n }\n\n template <typename T>\n inline T AtomicBase<T>::operator--()\n {\n return __sync_sub_and_fetch(&_value, 1);\n }\n\n template <typename T>\n inline AtomicBase<T>& AtomicBase<T>::operator=(T value)\n {\n __sync_lock_test_and_set(&_value, value);\n return *this;\n }\n\n template <typename T>\n inline T AtomicBase<T>::swap(T value)\n {\n return __sync_lock_test_and_set(&_value, value);\n }\n template <typename T>\n inline bool AtomicBase<T>::setIfEquals(T testValue, T setValue)\n {\n return __sync_bool_compare_and_swap(&_value, testValue, setValue);\n }\n#endif\n\n#ifdef _MSC_VER\n\n template <>\n inline int AtomicBase<int>::operator++()\n {\n return _InterlockedIncrement(&_value);\n }\n\n template <>\n inline int AtomicBase<int>::operator--()\n {\n return _InterlockedDecrement(&_value);\n }\n\n template<>\n inline AtomicBase<int>& AtomicBase<int>::operator=(int value)\n {\n InterlockedExchange(&_value, value);\n return *this;\n }\n\n template<>\n inline int AtomicBase<int>::swap(int value)\n {\n return InterlockedExchange(&_value, value);\n }\n\n template <>\n inline bool AtomicBase<int>::setIfEquals(int testValue, int setValue)\n {\n return _InterlockedCompareExchange(&_value, setValue, testValue) == testValue;\n }\n\n template <>\n inline unsigned int AtomicBase<unsigned int>::operator++()\n {\n return _InterlockedIncrement(&_value);\n }\n\n template <>\n inline unsigned int AtomicBase<unsigned int>::operator--()\n {\n return _InterlockedDecrement(&_value);\n }\n\n template<>\n inline AtomicBase<unsigned int>& AtomicBase<unsigned int>::operator=(unsigned int value)\n {\n InterlockedExchange(&_value, value);\n return *this;\n }\n\n template<>\n inline unsigned int AtomicBase<unsigned int>::swap(unsigned int value)\n {\n return InterlockedExchange(&_value, value);\n }\n\n template <>\n inline bool AtomicBase<unsigned int>::setIfEquals(unsigned int testValue, unsigned int setValue)\n {\n return _InterlockedCompareExchange(&_value, setValue, testValue) == testValue;\n }\n#endif\n\n}\n\n#define _QI_INSTANCIATE(_, a, elem) ::qi::details::newAndAssign(&elem);\n\n\/* The code below relies on the fact that initialisation of the qi::Atomic\n* can happen at static initialization time, and that proper memory barriers\n* are setup by its ++, swap and get operations.\n *\/\n\/** Accept a list of pointers (expected to be static function variables)\n * and new them once in a thrad-safe manner.\n * Implementation aims for minimal overhead when initialization is done.\n *\/\n#define QI_THREADSAFE_NEW(...) \\\n QI_ONCE(QI_VAARGS_APPLY(_QI_INSTANCIATE, _, __VA_ARGS__);)\n\n\/\/\/ Execute code once, parallel calls are blocked until code finishes.\n#define QI_ONCE(code) \\\n static qi::AtomicBase<int> QI_UNIQ_DEF(atomic_guard_a) = {0}; \\\n static qi::AtomicBase<int> QI_UNIQ_DEF(atomic_guard_b) = {0}; \\\n while (!QI_UNIQ_DEF(atomic_guard_a).setIfEquals(1, 1)) \\\n { \\\n bool tok = QI_UNIQ_DEF(atomic_guard_b).setIfEquals(0,1); \\\n if (tok) \\\n { \\\n code; \\\n ++QI_UNIQ_DEF(atomic_guard_a); \\\n } \\\n }\n\n\n#endif \/\/ _QI_ATOMIC_HPP_\n<commit_msg>Atomic: mark dereference operator const.<commit_after>#pragma once\n\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n\n#ifndef _QI_ATOMIC_HPP_\n#define _QI_ATOMIC_HPP_\n\n#ifdef _MSC_VER\n# include <windows.h>\n# include <intrin.h>\n\nextern \"C\" long __cdecl _InterlockedIncrement(long volatile *);\nextern \"C\" long __cdecl _InterlockedDecrement(long volatile *);\n\n# pragma intrinsic(_InterlockedIncrement)\n# pragma intrinsic(_InterlockedDecrement)\n\n#endif\n\n#include <boost\/static_assert.hpp>\n\n#include <qi\/config.hpp>\n#include <qi\/macro.hpp>\n\nnamespace qi\n{\n inline long testAndSet(long* cond)\n {\n#if defined __GNUC__\n return __sync_bool_compare_and_swap(cond, 0, 1);\n#elif defined _MSC_VER\n return 1 - InterlockedCompareExchange(cond, 1, 0);\n#else\n #error \"Unknown platform, testAndSet not implemented\"\n#endif\n }\n\n \/* \/!\\ WARNING\n * The 'volatile' is needed even though we use atomic compiler builtins.\n * Without the volatile, a thread doing\n * while (!setIfEquals(1,1))\n * Is never unstuck by a thread doing\n * setIfEquals(0,1)\n *\n * AtomicBase has public member so that it can be initialized at\n * static-initialization time (to make thread-safe static initialization inside\n * functions)\n *\/\n template <typename T>\n struct AtomicBase\n {\n public:\n\n\n \/* prefix operators *\/\n inline T operator++();\n inline T operator--();\n inline AtomicBase<T>& operator=(T value);\n \/** If value is \\p testValue, replace it with \\p setValue.\n * \\return true if swap was performed\n *\/\n inline bool setIfEquals(T testValue, T setValue);\n\n inline T swap(T value);\n\n inline T operator*() const\n {\n return _value;\n }\n\n public:\n BOOST_STATIC_ASSERT_MSG(sizeof(T) == sizeof(int), \"qi::Atomic is only supprted for int-like types\");\n\n volatile\n#ifdef _MSC_VER\n long\n#else\n T\n#endif\n _value;\n };\n\n template <typename T>\n class Atomic: public AtomicBase<T>\n {\n public:\n Atomic()\n {\n this->_value = 0;\n }\n\n Atomic(T value)\n {\n this->_value = value;\n }\n };\n#ifdef __GNUC__\n template <typename T>\n inline T AtomicBase<T>::operator++()\n {\n return __sync_add_and_fetch(&_value, 1);\n }\n\n template <typename T>\n inline T AtomicBase<T>::operator--()\n {\n return __sync_sub_and_fetch(&_value, 1);\n }\n\n template <typename T>\n inline AtomicBase<T>& AtomicBase<T>::operator=(T value)\n {\n __sync_lock_test_and_set(&_value, value);\n return *this;\n }\n\n template <typename T>\n inline T AtomicBase<T>::swap(T value)\n {\n return __sync_lock_test_and_set(&_value, value);\n }\n template <typename T>\n inline bool AtomicBase<T>::setIfEquals(T testValue, T setValue)\n {\n return __sync_bool_compare_and_swap(&_value, testValue, setValue);\n }\n#endif\n\n#ifdef _MSC_VER\n\n template <>\n inline int AtomicBase<int>::operator++()\n {\n return _InterlockedIncrement(&_value);\n }\n\n template <>\n inline int AtomicBase<int>::operator--()\n {\n return _InterlockedDecrement(&_value);\n }\n\n template<>\n inline AtomicBase<int>& AtomicBase<int>::operator=(int value)\n {\n InterlockedExchange(&_value, value);\n return *this;\n }\n\n template<>\n inline int AtomicBase<int>::swap(int value)\n {\n return InterlockedExchange(&_value, value);\n }\n\n template <>\n inline bool AtomicBase<int>::setIfEquals(int testValue, int setValue)\n {\n return _InterlockedCompareExchange(&_value, setValue, testValue) == testValue;\n }\n\n template <>\n inline unsigned int AtomicBase<unsigned int>::operator++()\n {\n return _InterlockedIncrement(&_value);\n }\n\n template <>\n inline unsigned int AtomicBase<unsigned int>::operator--()\n {\n return _InterlockedDecrement(&_value);\n }\n\n template<>\n inline AtomicBase<unsigned int>& AtomicBase<unsigned int>::operator=(unsigned int value)\n {\n InterlockedExchange(&_value, value);\n return *this;\n }\n\n template<>\n inline unsigned int AtomicBase<unsigned int>::swap(unsigned int value)\n {\n return InterlockedExchange(&_value, value);\n }\n\n template <>\n inline bool AtomicBase<unsigned int>::setIfEquals(unsigned int testValue, unsigned int setValue)\n {\n return _InterlockedCompareExchange(&_value, setValue, testValue) == testValue;\n }\n#endif\n\n}\n\n#define _QI_INSTANCIATE(_, a, elem) ::qi::details::newAndAssign(&elem);\n\n\/* The code below relies on the fact that initialisation of the qi::Atomic\n* can happen at static initialization time, and that proper memory barriers\n* are setup by its ++, swap and get operations.\n *\/\n\/** Accept a list of pointers (expected to be static function variables)\n * and new them once in a thrad-safe manner.\n * Implementation aims for minimal overhead when initialization is done.\n *\/\n#define QI_THREADSAFE_NEW(...) \\\n QI_ONCE(QI_VAARGS_APPLY(_QI_INSTANCIATE, _, __VA_ARGS__);)\n\n\/\/\/ Execute code once, parallel calls are blocked until code finishes.\n#define QI_ONCE(code) \\\n static qi::AtomicBase<int> QI_UNIQ_DEF(atomic_guard_a) = {0}; \\\n static qi::AtomicBase<int> QI_UNIQ_DEF(atomic_guard_b) = {0}; \\\n while (!QI_UNIQ_DEF(atomic_guard_a).setIfEquals(1, 1)) \\\n { \\\n bool tok = QI_UNIQ_DEF(atomic_guard_b).setIfEquals(0,1); \\\n if (tok) \\\n { \\\n code; \\\n ++QI_UNIQ_DEF(atomic_guard_a); \\\n } \\\n }\n\n\n#endif \/\/ _QI_ATOMIC_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n Q Light Controller Plus\n app.cpp\n\n Copyright (c) Massimo Callegari\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <QXmlStreamReader>\n#include <QXmlStreamWriter>\n#include <QFontDatabase>\n#include <QQmlContext>\n#include <QQuickItem>\n#include <QSettings>\n#include <QKeyEvent>\n#include <QScreen>\n\n#include \"app.h\"\n#include \"mainview2d.h\"\n#include \"showmanager.h\"\n#include \"actionmanager.h\"\n#include \"modelselector.h\"\n#include \"videoprovider.h\"\n#include \"contextmanager.h\"\n#include \"virtualconsole.h\"\n#include \"fixturebrowser.h\"\n#include \"fixturemanager.h\"\n#include \"functionmanager.h\"\n#include \"fixturegroupeditor.h\"\n#include \"inputoutputmanager.h\"\n\n#include \"qlcfixturedefcache.h\"\n#include \"audioplugincache.h\"\n#include \"rgbscriptscache.h\"\n#include \"qlcfixturedef.h\"\n#include \"qlcconfig.h\"\n#include \"qlcfile.h\"\n\n#define SETTINGS_WORKINGPATH \"workspace\/workingpath\"\n#define SETTINGS_RECENTFILE \"workspace\/recent\"\n\n#define MAX_RECENT_FILES 10\n\nApp::App()\n : QQuickView()\n , m_fixtureBrowser(NULL)\n , m_fixtureManager(NULL)\n , m_contextManager(NULL)\n , m_ioManager(NULL)\n , m_videoProvider(NULL)\n , m_doc(NULL)\n , m_docLoaded(false)\n{\n QSettings settings;\n\n updateRecentFilesList();\n\n QVariant dir = settings.value(SETTINGS_WORKINGPATH);\n if (dir.isValid() == true)\n m_workingPath = dir.toString();\n}\n\nApp::~App()\n{\n\n}\n\nvoid App::startup()\n{\n qmlRegisterType<Fixture>(\"com.qlcplus.classes\", 1, 0, \"Fixture\");\n qmlRegisterType<Function>(\"com.qlcplus.classes\", 1, 0, \"Function\");\n qmlRegisterType<ModelSelector>(\"com.qlcplus.classes\", 1, 0, \"ModelSelector\");\n qmlRegisterType<App>(\"com.qlcplus.classes\", 1, 0, \"App\");\n\n setTitle(\"Q Light Controller Plus\");\n setIcon(QIcon(\":\/qlcplus.svg\"));\n\n if (QFontDatabase::addApplicationFont(\":\/RobotoCondensed-Regular.ttf\") < 0)\n qWarning() << \"Roboto font cannot be loaded !\";\n\n rootContext()->setContextProperty(\"qlcplus\", this);\n\n m_pixelDensity = screen()->physicalDotsPerInch() * 0.039370;\n qDebug() << \"Pixel density:\" << m_pixelDensity;\n\n rootContext()->setContextProperty(\"screenPixelDensity\", m_pixelDensity);\n\n initDoc();\n\n m_ioManager = new InputOutputManager(this, m_doc);\n rootContext()->setContextProperty(\"ioManager\", m_ioManager);\n\n m_fixtureBrowser = new FixtureBrowser(this, m_doc);\n rootContext()->setContextProperty(\"fixtureBrowser\", m_fixtureBrowser);\n\n m_fixtureManager = new FixtureManager(this, m_doc);\n rootContext()->setContextProperty(\"fixtureManager\", m_fixtureManager);\n\n m_fixtureGroupEditor = new FixtureGroupEditor(this, m_doc);\n rootContext()->setContextProperty(\"fixtureGroupEditor\", m_fixtureGroupEditor);\n\n m_functionManager = new FunctionManager(this, m_doc);\n rootContext()->setContextProperty(\"functionManager\", m_functionManager);\n\n m_contextManager = new ContextManager(this, m_doc, m_fixtureManager, m_functionManager);\n rootContext()->setContextProperty(\"contextManager\", m_contextManager);\n\n m_virtualConsole = new VirtualConsole(this, m_doc, m_contextManager);\n rootContext()->setContextProperty(\"virtualConsole\", m_virtualConsole);\n\n m_showManager = new ShowManager(this, m_doc);\n rootContext()->setContextProperty(\"showManager\", m_showManager);\n\n \/\/ register an uncreatable type just to use the enums in QML\n qmlRegisterUncreatableType<ShowManager>(\"com.qlcplus.classes\", 1, 0, \"ShowManager\", \"Can't create a ShowManager !\");\n\n m_actionManager = new ActionManager(this, m_functionManager, m_showManager, m_virtualConsole);\n rootContext()->setContextProperty(\"actionManager\", m_actionManager);\n\n \/\/ register an uncreatable type just to use the enums in QML\n qmlRegisterUncreatableType<ActionManager>(\"com.qlcplus.classes\", 1, 0, \"ActionManager\", \"Can't create an ActionManager !\");\n\n m_contextManager->registerContext(m_virtualConsole);\n m_contextManager->registerContext(m_showManager);\n m_contextManager->registerContext(m_ioManager);\n\n \/\/ Start up in non-modified state\n m_doc->resetModified();\n\n \/\/ and here we go !\n setSource(QUrl(\"qrc:\/MainView.qml\"));\n}\n\nvoid App::toggleFullscreen()\n{\n static int wstate = windowState();\n\n if (windowState() & Qt::WindowFullScreen)\n {\n if (wstate & Qt::WindowMaximized)\n showMaximized();\n else\n showNormal();\n wstate = windowState();\n }\n else\n {\n wstate = windowState();\n showFullScreen();\n }\n}\n\nvoid App::show()\n{\n setGeometry(0, 0, 800, 600);\n \/\/setGeometry(0, 0, 1272, 689); \/\/ youtube recording\n showMaximized();\n}\n\nqreal App::pixelDensity() const\n{\n return m_pixelDensity;\n}\n\nvoid App::keyPressEvent(QKeyEvent *e)\n{\n if (m_contextManager)\n m_contextManager->handleKeyPress(e);\n\n QQuickView::keyPressEvent(e);\n}\n\nvoid App::keyReleaseEvent(QKeyEvent *e)\n{\n if (m_contextManager)\n m_contextManager->handleKeyRelease(e);\n\n QQuickView::keyReleaseEvent(e);\n}\n\nvoid App::clearDocument()\n{\n if (m_videoProvider)\n {\n delete m_videoProvider;\n m_videoProvider = NULL;\n }\n\n m_doc->masterTimer()->stop();\n m_doc->clearContents();\n m_virtualConsole->resetContents();\n \/\/SimpleDesk::instance()->clearContents();\n m_showManager->resetContents();\n m_doc->inputOutputMap()->resetUniverses();\n setFileName(QString());\n m_doc->resetModified();\n m_doc->masterTimer()->start();\n\n}\n\nDoc *App::doc()\n{\n return m_doc;\n}\n\nvoid App::slotDocModified(bool state)\n{\n Q_UNUSED(state)\n}\n\nvoid App::initDoc()\n{\n Q_ASSERT(m_doc == NULL);\n m_doc = new Doc(this);\n\n connect(m_doc, &Doc::modified, this, &App::slotDocModified);\n\n \/* Load user fixtures first so that they override system fixtures *\/\n m_doc->fixtureDefCache()->load(QLCFixtureDefCache::userDefinitionDirectory());\n m_doc->fixtureDefCache()->loadMap(QLCFixtureDefCache::systemDefinitionDirectory());\n\n \/* Load channel modifiers templates *\/\n m_doc->modifiersCache()->load(QLCModifiersCache::systemTemplateDirectory(), true);\n m_doc->modifiersCache()->load(QLCModifiersCache::userTemplateDirectory());\n\n \/* Load RGB scripts *\/\n m_doc->rgbScriptsCache()->load(RGBScriptsCache::systemScriptsDirectory());\n m_doc->rgbScriptsCache()->load(RGBScriptsCache::userScriptsDirectory());\n\n \/* Load plugins *\/\n#if defined(__APPLE__) || defined(Q_OS_MAC)\n connect(m_doc->ioPluginCache(), SIGNAL(pluginLoaded(const QString&)),\n this, SLOT(slotSetProgressText(const QString&)));\n#endif\n#if defined Q_OS_ANDROID\n QString pluginsPath = QString(\"%1\/..\/lib\").arg(QDir::currentPath());\n m_doc->ioPluginCache()->load(QDir(pluginsPath));\n#else\n m_doc->ioPluginCache()->load(IOPluginCache::systemPluginDirectory());\n#endif\n\n \/* Load audio decoder plugins\n * This doesn't use a AudioPluginCache::systemPluginDirectory() cause\n * otherwise the qlcconfig.h creation should have been moved into the\n * audio folder, which doesn't make much sense *\/\n m_doc->audioPluginCache()->load(QLCFile::systemDirectory(AUDIOPLUGINDIR, KExtPlugin));\n m_videoProvider = new VideoProvider(this, m_doc);\n\n Q_ASSERT(m_doc->inputOutputMap() != NULL);\n\n \/* Load input plugins & profiles *\/\n m_doc->inputOutputMap()->loadProfiles(InputOutputMap::userProfileDirectory());\n m_doc->inputOutputMap()->loadProfiles(InputOutputMap::systemProfileDirectory());\n m_doc->inputOutputMap()->loadDefaults();\n\n m_doc->inputOutputMap()->setBeatGeneratorType(InputOutputMap::Internal);\n m_doc->masterTimer()->start();\n}\n\nvoid App::enableKioskMode()\n{\n\n}\n\nvoid App::createKioskCloseButton(const QRect &rect)\n{\n Q_UNUSED(rect)\n}\n\n\/*********************************************************************\n * Load & Save\n *********************************************************************\/\n\nvoid App::setFileName(const QString &fileName)\n{\n m_fileName = fileName;\n}\n\nQString App::fileName() const\n{\n return m_fileName;\n}\n\nvoid App::updateRecentFilesList(QString filename)\n{\n QSettings settings;\n if (filename.isEmpty() == false)\n {\n m_recentFiles.removeAll(filename); \/\/ in case the string is already present, remove it...\n m_recentFiles.prepend(filename); \/\/ and add it to the top\n for (int i = 0; i < m_recentFiles.count(); i++)\n {\n settings.setValue(QString(\"%1%2\").arg(SETTINGS_RECENTFILE).arg(i), m_recentFiles.at(i));\n emit recentFilesChanged();\n }\n }\n else\n {\n for (int i = 0; i < MAX_RECENT_FILES; i++)\n {\n QVariant recent = settings.value(QString(\"%1%2\").arg(SETTINGS_RECENTFILE).arg(i));\n if (recent.isValid() == true)\n m_recentFiles.append(recent.toString());\n }\n }\n}\n\nQStringList App::recentFiles() const\n{\n return m_recentFiles;\n}\n\nQString App::workingPath() const\n{\n return m_workingPath;\n}\n\nvoid App::setWorkingPath(QString workingPath)\n{\n QString strippedPath = workingPath.replace(\"file:\/\/\", \"\");\n\n if (m_workingPath == strippedPath)\n return;\n\n m_workingPath = strippedPath;\n\n QSettings settings;\n settings.setValue(SETTINGS_WORKINGPATH, m_workingPath);\n\n emit workingPathChanged(strippedPath);\n}\n\nbool App::newWorkspace()\n{\n \/*\n QString msg(tr(\"Do you wish to save the current workspace?\\n\" \\\n \"Changes will be lost if you don't save them.\"));\n if (saveModifiedDoc(tr(\"New Workspace\"), msg) == false)\n {\n return false;\n }\n *\/\n\n clearDocument();\n m_fixtureManager->slotDocLoaded();\n m_functionManager->slotDocLoaded();\n m_contextManager->resetContexts();\n return true;\n}\n\nbool App::loadWorkspace(const QString &fileName)\n{\n \/* Clear existing document data *\/\n clearDocument();\n m_docLoaded = false;\n emit docLoadedChanged();\n\n QString localFilename = fileName;\n if (localFilename.startsWith(\"file:\"))\n localFilename = QUrl(fileName).toLocalFile();\n\n if (loadXML(localFilename) == QFile::NoError)\n {\n setTitle(QString(\"Q Light Controller Plus - %1\").arg(localFilename));\n setFileName(localFilename);\n m_docLoaded = true;\n updateRecentFilesList(localFilename);\n emit docLoadedChanged();\n m_contextManager->resetContexts();\n m_doc->resetModified();\n m_videoProvider = new VideoProvider(this, m_doc);\n return true;\n }\n return false;\n}\n\nQFileDevice::FileError App::loadXML(const QString &fileName)\n{\n QFile::FileError retval = QFile::NoError;\n\n if (fileName.isEmpty() == true)\n return QFile::OpenError;\n\n QXmlStreamReader *doc = QLCFile::getXMLReader(fileName);\n if (doc == NULL || doc->device() == NULL || doc->hasError())\n {\n qWarning() << Q_FUNC_INFO << \"Unable to read from\" << fileName;\n return QFile::ReadError;\n }\n\n while (!doc->atEnd())\n {\n if (doc->readNext() == QXmlStreamReader::DTD)\n break;\n }\n if (doc->hasError())\n {\n QLCFile::releaseXMLReader(doc);\n return QFile::ResourceError;\n }\n\n \/* Set the workspace path before loading the new XML. In this way local files\n can be loaded even if the workspace file has been moved *\/\n m_doc->setWorkspacePath(QFileInfo(fileName).absolutePath());\n\n if (doc->dtdName() == KXMLQLCWorkspace)\n {\n if (loadXML(*doc) == false)\n {\n retval = QFile::ReadError;\n }\n else\n {\n setFileName(fileName);\n m_doc->resetModified();\n retval = QFile::NoError;\n }\n }\n else\n {\n retval = QFile::ReadError;\n qWarning() << Q_FUNC_INFO << fileName\n << \"is not a workspace file\";\n }\n\n QLCFile::releaseXMLReader(doc);\n\n return retval;\n}\n\nbool App::loadXML(QXmlStreamReader &doc, bool goToConsole, bool fromMemory)\n{\n Q_UNUSED(goToConsole) \/\/ TODO\n if (doc.readNextStartElement() == false)\n return false;\n\n if (doc.name() != KXMLQLCWorkspace)\n {\n qWarning() << Q_FUNC_INFO << \"Workspace node not found\";\n return false;\n }\n\n \/\/QString activeWindowName = doc.attributes().value(KXMLQLCWorkspaceWindow).toString();\n\n while (doc.readNextStartElement())\n {\n if (doc.name() == KXMLQLCEngine)\n {\n m_doc->loadXML(doc);\n }\n else if (doc.name() == KXMLQLCVirtualConsole)\n {\n m_virtualConsole->loadXML(doc);\n }\n#if 0\n else if (doc.name() == KXMLQLCSimpleDesk)\n {\n SimpleDesk::instance()->loadXML(doc);\n }\n#endif\n else if (doc.name() == KXMLQLCCreator)\n {\n \/* Ignore creator information *\/\n doc.skipCurrentElement();\n }\n else\n {\n qWarning() << Q_FUNC_INFO << \"Unknown Workspace tag:\" << doc.name().toString();\n doc.skipCurrentElement();\n }\n }\n\n\/*\n if (goToConsole == true)\n \/\/ Force the active window to be Virtual Console\n setActiveWindow(VirtualConsole::staticMetaObject.className());\n else\n \/\/ Set the active window to what was saved in the workspace file\n setActiveWindow(activeWindowName);\n*\/\n \/\/ Perform post-load operations\n m_virtualConsole->postLoad();\n\n if (m_doc->errorLog().isEmpty() == false &&\n fromMemory == false)\n {\n \/\/ emit a signal to inform the QML UI to display an error message\n \/*\n QMessageBox msg(QMessageBox::Warning, tr(\"Warning\"),\n tr(\"Some errors occurred while loading the project:\") + \"\\n\\n\" + m_doc->errorLog(),\n QMessageBox::Ok);\n msg.exec();\n *\/\n }\n\n return true;\n}\n\n\n\n<commit_msg>qmlui: use the APPNAME define instead of hardcoded strings<commit_after>\/*\n Q Light Controller Plus\n app.cpp\n\n Copyright (c) Massimo Callegari\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <QXmlStreamReader>\n#include <QXmlStreamWriter>\n#include <QFontDatabase>\n#include <QQmlContext>\n#include <QQuickItem>\n#include <QSettings>\n#include <QKeyEvent>\n#include <QScreen>\n\n#include \"app.h\"\n#include \"mainview2d.h\"\n#include \"showmanager.h\"\n#include \"actionmanager.h\"\n#include \"modelselector.h\"\n#include \"videoprovider.h\"\n#include \"contextmanager.h\"\n#include \"virtualconsole.h\"\n#include \"fixturebrowser.h\"\n#include \"fixturemanager.h\"\n#include \"functionmanager.h\"\n#include \"fixturegroupeditor.h\"\n#include \"inputoutputmanager.h\"\n\n#include \"qlcfixturedefcache.h\"\n#include \"audioplugincache.h\"\n#include \"rgbscriptscache.h\"\n#include \"qlcfixturedef.h\"\n#include \"qlcconfig.h\"\n#include \"qlcfile.h\"\n\n#define SETTINGS_WORKINGPATH \"workspace\/workingpath\"\n#define SETTINGS_RECENTFILE \"workspace\/recent\"\n\n#define MAX_RECENT_FILES 10\n\nApp::App()\n : QQuickView()\n , m_fixtureBrowser(NULL)\n , m_fixtureManager(NULL)\n , m_contextManager(NULL)\n , m_ioManager(NULL)\n , m_videoProvider(NULL)\n , m_doc(NULL)\n , m_docLoaded(false)\n{\n QSettings settings;\n\n updateRecentFilesList();\n\n QVariant dir = settings.value(SETTINGS_WORKINGPATH);\n if (dir.isValid() == true)\n m_workingPath = dir.toString();\n}\n\nApp::~App()\n{\n\n}\n\nvoid App::startup()\n{\n qmlRegisterType<Fixture>(\"com.qlcplus.classes\", 1, 0, \"Fixture\");\n qmlRegisterType<Function>(\"com.qlcplus.classes\", 1, 0, \"Function\");\n qmlRegisterType<ModelSelector>(\"com.qlcplus.classes\", 1, 0, \"ModelSelector\");\n qmlRegisterType<App>(\"com.qlcplus.classes\", 1, 0, \"App\");\n\n setTitle(APPNAME);\n setIcon(QIcon(\":\/qlcplus.svg\"));\n\n if (QFontDatabase::addApplicationFont(\":\/RobotoCondensed-Regular.ttf\") < 0)\n qWarning() << \"Roboto font cannot be loaded !\";\n\n rootContext()->setContextProperty(\"qlcplus\", this);\n\n m_pixelDensity = screen()->physicalDotsPerInch() * 0.039370;\n qDebug() << \"Pixel density:\" << m_pixelDensity;\n\n rootContext()->setContextProperty(\"screenPixelDensity\", m_pixelDensity);\n\n initDoc();\n\n m_ioManager = new InputOutputManager(this, m_doc);\n rootContext()->setContextProperty(\"ioManager\", m_ioManager);\n\n m_fixtureBrowser = new FixtureBrowser(this, m_doc);\n rootContext()->setContextProperty(\"fixtureBrowser\", m_fixtureBrowser);\n\n m_fixtureManager = new FixtureManager(this, m_doc);\n rootContext()->setContextProperty(\"fixtureManager\", m_fixtureManager);\n\n m_fixtureGroupEditor = new FixtureGroupEditor(this, m_doc);\n rootContext()->setContextProperty(\"fixtureGroupEditor\", m_fixtureGroupEditor);\n\n m_functionManager = new FunctionManager(this, m_doc);\n rootContext()->setContextProperty(\"functionManager\", m_functionManager);\n\n m_contextManager = new ContextManager(this, m_doc, m_fixtureManager, m_functionManager);\n rootContext()->setContextProperty(\"contextManager\", m_contextManager);\n\n m_virtualConsole = new VirtualConsole(this, m_doc, m_contextManager);\n rootContext()->setContextProperty(\"virtualConsole\", m_virtualConsole);\n\n m_showManager = new ShowManager(this, m_doc);\n rootContext()->setContextProperty(\"showManager\", m_showManager);\n\n \/\/ register an uncreatable type just to use the enums in QML\n qmlRegisterUncreatableType<ShowManager>(\"com.qlcplus.classes\", 1, 0, \"ShowManager\", \"Can't create a ShowManager !\");\n\n m_actionManager = new ActionManager(this, m_functionManager, m_showManager, m_virtualConsole);\n rootContext()->setContextProperty(\"actionManager\", m_actionManager);\n\n \/\/ register an uncreatable type just to use the enums in QML\n qmlRegisterUncreatableType<ActionManager>(\"com.qlcplus.classes\", 1, 0, \"ActionManager\", \"Can't create an ActionManager !\");\n\n m_contextManager->registerContext(m_virtualConsole);\n m_contextManager->registerContext(m_showManager);\n m_contextManager->registerContext(m_ioManager);\n\n \/\/ Start up in non-modified state\n m_doc->resetModified();\n\n \/\/ and here we go !\n setSource(QUrl(\"qrc:\/MainView.qml\"));\n}\n\nvoid App::toggleFullscreen()\n{\n static int wstate = windowState();\n\n if (windowState() & Qt::WindowFullScreen)\n {\n if (wstate & Qt::WindowMaximized)\n showMaximized();\n else\n showNormal();\n wstate = windowState();\n }\n else\n {\n wstate = windowState();\n showFullScreen();\n }\n}\n\nvoid App::show()\n{\n setGeometry(0, 0, 800, 600);\n \/\/setGeometry(0, 0, 1272, 689); \/\/ youtube recording\n showMaximized();\n}\n\nqreal App::pixelDensity() const\n{\n return m_pixelDensity;\n}\n\nvoid App::keyPressEvent(QKeyEvent *e)\n{\n if (m_contextManager)\n m_contextManager->handleKeyPress(e);\n\n QQuickView::keyPressEvent(e);\n}\n\nvoid App::keyReleaseEvent(QKeyEvent *e)\n{\n if (m_contextManager)\n m_contextManager->handleKeyRelease(e);\n\n QQuickView::keyReleaseEvent(e);\n}\n\nvoid App::clearDocument()\n{\n if (m_videoProvider)\n {\n delete m_videoProvider;\n m_videoProvider = NULL;\n }\n\n m_doc->masterTimer()->stop();\n m_doc->clearContents();\n m_virtualConsole->resetContents();\n \/\/SimpleDesk::instance()->clearContents();\n m_showManager->resetContents();\n m_doc->inputOutputMap()->resetUniverses();\n setFileName(QString());\n m_doc->resetModified();\n m_doc->masterTimer()->start();\n\n}\n\nDoc *App::doc()\n{\n return m_doc;\n}\n\nvoid App::slotDocModified(bool state)\n{\n Q_UNUSED(state)\n}\n\nvoid App::initDoc()\n{\n Q_ASSERT(m_doc == NULL);\n m_doc = new Doc(this);\n\n connect(m_doc, &Doc::modified, this, &App::slotDocModified);\n\n \/* Load user fixtures first so that they override system fixtures *\/\n m_doc->fixtureDefCache()->load(QLCFixtureDefCache::userDefinitionDirectory());\n m_doc->fixtureDefCache()->loadMap(QLCFixtureDefCache::systemDefinitionDirectory());\n\n \/* Load channel modifiers templates *\/\n m_doc->modifiersCache()->load(QLCModifiersCache::systemTemplateDirectory(), true);\n m_doc->modifiersCache()->load(QLCModifiersCache::userTemplateDirectory());\n\n \/* Load RGB scripts *\/\n m_doc->rgbScriptsCache()->load(RGBScriptsCache::systemScriptsDirectory());\n m_doc->rgbScriptsCache()->load(RGBScriptsCache::userScriptsDirectory());\n\n \/* Load plugins *\/\n#if defined(__APPLE__) || defined(Q_OS_MAC)\n connect(m_doc->ioPluginCache(), SIGNAL(pluginLoaded(const QString&)),\n this, SLOT(slotSetProgressText(const QString&)));\n#endif\n#if defined Q_OS_ANDROID\n QString pluginsPath = QString(\"%1\/..\/lib\").arg(QDir::currentPath());\n m_doc->ioPluginCache()->load(QDir(pluginsPath));\n#else\n m_doc->ioPluginCache()->load(IOPluginCache::systemPluginDirectory());\n#endif\n\n \/* Load audio decoder plugins\n * This doesn't use a AudioPluginCache::systemPluginDirectory() cause\n * otherwise the qlcconfig.h creation should have been moved into the\n * audio folder, which doesn't make much sense *\/\n m_doc->audioPluginCache()->load(QLCFile::systemDirectory(AUDIOPLUGINDIR, KExtPlugin));\n m_videoProvider = new VideoProvider(this, m_doc);\n\n Q_ASSERT(m_doc->inputOutputMap() != NULL);\n\n \/* Load input plugins & profiles *\/\n m_doc->inputOutputMap()->loadProfiles(InputOutputMap::userProfileDirectory());\n m_doc->inputOutputMap()->loadProfiles(InputOutputMap::systemProfileDirectory());\n m_doc->inputOutputMap()->loadDefaults();\n\n m_doc->inputOutputMap()->setBeatGeneratorType(InputOutputMap::Internal);\n m_doc->masterTimer()->start();\n}\n\nvoid App::enableKioskMode()\n{\n\n}\n\nvoid App::createKioskCloseButton(const QRect &rect)\n{\n Q_UNUSED(rect)\n}\n\n\/*********************************************************************\n * Load & Save\n *********************************************************************\/\n\nvoid App::setFileName(const QString &fileName)\n{\n m_fileName = fileName;\n}\n\nQString App::fileName() const\n{\n return m_fileName;\n}\n\nvoid App::updateRecentFilesList(QString filename)\n{\n QSettings settings;\n if (filename.isEmpty() == false)\n {\n m_recentFiles.removeAll(filename); \/\/ in case the string is already present, remove it...\n m_recentFiles.prepend(filename); \/\/ and add it to the top\n for (int i = 0; i < m_recentFiles.count(); i++)\n {\n settings.setValue(QString(\"%1%2\").arg(SETTINGS_RECENTFILE).arg(i), m_recentFiles.at(i));\n emit recentFilesChanged();\n }\n }\n else\n {\n for (int i = 0; i < MAX_RECENT_FILES; i++)\n {\n QVariant recent = settings.value(QString(\"%1%2\").arg(SETTINGS_RECENTFILE).arg(i));\n if (recent.isValid() == true)\n m_recentFiles.append(recent.toString());\n }\n }\n}\n\nQStringList App::recentFiles() const\n{\n return m_recentFiles;\n}\n\nQString App::workingPath() const\n{\n return m_workingPath;\n}\n\nvoid App::setWorkingPath(QString workingPath)\n{\n QString strippedPath = workingPath.replace(\"file:\/\/\", \"\");\n\n if (m_workingPath == strippedPath)\n return;\n\n m_workingPath = strippedPath;\n\n QSettings settings;\n settings.setValue(SETTINGS_WORKINGPATH, m_workingPath);\n\n emit workingPathChanged(strippedPath);\n}\n\nbool App::newWorkspace()\n{\n \/*\n QString msg(tr(\"Do you wish to save the current workspace?\\n\" \\\n \"Changes will be lost if you don't save them.\"));\n if (saveModifiedDoc(tr(\"New Workspace\"), msg) == false)\n {\n return false;\n }\n *\/\n\n clearDocument();\n m_fixtureManager->slotDocLoaded();\n m_functionManager->slotDocLoaded();\n m_contextManager->resetContexts();\n return true;\n}\n\nbool App::loadWorkspace(const QString &fileName)\n{\n \/* Clear existing document data *\/\n clearDocument();\n m_docLoaded = false;\n emit docLoadedChanged();\n\n QString localFilename = fileName;\n if (localFilename.startsWith(\"file:\"))\n localFilename = QUrl(fileName).toLocalFile();\n\n if (loadXML(localFilename) == QFile::NoError)\n {\n setTitle(QString(\"%1 - %2\").arg(APPNAME).arg(localFilename));\n setFileName(localFilename);\n m_docLoaded = true;\n updateRecentFilesList(localFilename);\n emit docLoadedChanged();\n m_contextManager->resetContexts();\n m_doc->resetModified();\n m_videoProvider = new VideoProvider(this, m_doc);\n return true;\n }\n return false;\n}\n\nQFileDevice::FileError App::loadXML(const QString &fileName)\n{\n QFile::FileError retval = QFile::NoError;\n\n if (fileName.isEmpty() == true)\n return QFile::OpenError;\n\n QXmlStreamReader *doc = QLCFile::getXMLReader(fileName);\n if (doc == NULL || doc->device() == NULL || doc->hasError())\n {\n qWarning() << Q_FUNC_INFO << \"Unable to read from\" << fileName;\n return QFile::ReadError;\n }\n\n while (!doc->atEnd())\n {\n if (doc->readNext() == QXmlStreamReader::DTD)\n break;\n }\n if (doc->hasError())\n {\n QLCFile::releaseXMLReader(doc);\n return QFile::ResourceError;\n }\n\n \/* Set the workspace path before loading the new XML. In this way local files\n can be loaded even if the workspace file has been moved *\/\n m_doc->setWorkspacePath(QFileInfo(fileName).absolutePath());\n\n if (doc->dtdName() == KXMLQLCWorkspace)\n {\n if (loadXML(*doc) == false)\n {\n retval = QFile::ReadError;\n }\n else\n {\n setFileName(fileName);\n m_doc->resetModified();\n retval = QFile::NoError;\n }\n }\n else\n {\n retval = QFile::ReadError;\n qWarning() << Q_FUNC_INFO << fileName\n << \"is not a workspace file\";\n }\n\n QLCFile::releaseXMLReader(doc);\n\n return retval;\n}\n\nbool App::loadXML(QXmlStreamReader &doc, bool goToConsole, bool fromMemory)\n{\n Q_UNUSED(goToConsole) \/\/ TODO\n if (doc.readNextStartElement() == false)\n return false;\n\n if (doc.name() != KXMLQLCWorkspace)\n {\n qWarning() << Q_FUNC_INFO << \"Workspace node not found\";\n return false;\n }\n\n \/\/QString activeWindowName = doc.attributes().value(KXMLQLCWorkspaceWindow).toString();\n\n while (doc.readNextStartElement())\n {\n if (doc.name() == KXMLQLCEngine)\n {\n m_doc->loadXML(doc);\n }\n else if (doc.name() == KXMLQLCVirtualConsole)\n {\n m_virtualConsole->loadXML(doc);\n }\n#if 0\n else if (doc.name() == KXMLQLCSimpleDesk)\n {\n SimpleDesk::instance()->loadXML(doc);\n }\n#endif\n else if (doc.name() == KXMLQLCCreator)\n {\n \/* Ignore creator information *\/\n doc.skipCurrentElement();\n }\n else\n {\n qWarning() << Q_FUNC_INFO << \"Unknown Workspace tag:\" << doc.name().toString();\n doc.skipCurrentElement();\n }\n }\n\n\/*\n if (goToConsole == true)\n \/\/ Force the active window to be Virtual Console\n setActiveWindow(VirtualConsole::staticMetaObject.className());\n else\n \/\/ Set the active window to what was saved in the workspace file\n setActiveWindow(activeWindowName);\n*\/\n \/\/ Perform post-load operations\n m_virtualConsole->postLoad();\n\n if (m_doc->errorLog().isEmpty() == false &&\n fromMemory == false)\n {\n \/\/ emit a signal to inform the QML UI to display an error message\n \/*\n QMessageBox msg(QMessageBox::Warning, tr(\"Warning\"),\n tr(\"Some errors occurred while loading the project:\") + \"\\n\\n\" + m_doc->errorLog(),\n QMessageBox::Ok);\n msg.exec();\n *\/\n }\n\n return true;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"puptent\/SpriteSystem.h\"\n#include \"puptent\/RenderMesh.h\"\n#include \"cinder\/Json.h\"\n\nusing namespace puptent;\nusing namespace cinder;\nusing namespace std;\n\nSpriteAnimationSystemRef SpriteAnimationSystem::create( TextureAtlasRef atlas, const ci::JsonTree &animations )\n{\n return SpriteAnimationSystemRef{ new SpriteAnimationSystem{ atlas, animations } };\n}\n\nSpriteAnimationSystem::SpriteAnimationSystem( TextureAtlasRef atlas, const JsonTree &animations ):\nmAtlas( atlas )\n{\n try\n {\n for( auto &anim : animations )\n {\n vector<Drawing> drawings;\n float frame_duration = 1.0f \/ anim.getChild(\"fps\").getValue<float>();\n string key = anim.getKey();\n auto frames = anim.getChild(\"frames\");\n for( auto &child : frames.getChildren() )\n { \/\/ stored in json as [ \"id\", duration ]\n drawings.emplace_back( mAtlas->get(child[0].getValue()), child[1].getValue<float>() );\n }\n mAnimations.emplace_back( Animation{ key, drawings, frame_duration } );\n mAnimationIds[key] = mAnimations.size() - 1;\n }\n }\n catch( JsonTree::Exception &exc )\n {\n std::cout << __FUNCTION__ << \" error: \" << exc.what() << std::endl;\n }\n}\n\nvoid SpriteAnimationSystem::configure( EventManagerRef events )\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n events->subscribe<ComponentAddedEvent<SpriteAnimation>>( *this );\n}\n\nvoid SpriteAnimationSystem::addAnimation(const string &name, const Animation &animation)\n{\n mAnimations.emplace_back( animation );\n mAnimationIds[name] = mAnimations.size() - 1;\n}\n\nAnimationId SpriteAnimationSystem::getAnimationId( const string &name ) const\n{\n AnimationId index = 0;\n auto iter = mAnimationIds.find( name );\n if( iter != mAnimationIds.end() )\n {\n index = iter->second;\n }\n return index;\n}\n\nSpriteAnimationRef SpriteAnimationSystem::createSpriteAnimation(const string &name) const\n{\n return createSpriteAnimation( getAnimationId( name ) );\n}\n\nSpriteAnimationRef SpriteAnimationSystem::createSpriteAnimation(AnimationId animation_id ) const\n{\n return SpriteAnimationRef{ new SpriteAnimation{ animation_id } };\n}\n\nvoid SpriteAnimationSystem::receive(const ComponentAddedEvent<SpriteAnimation> &event)\n{ \/\/ track the sprite\n auto entity = event.entity;\n auto mesh = entity.component<RenderMesh>();\n if( mesh )\n {\n auto sprite = event.component;\n auto drawings = mAnimations.at( sprite->animation ).drawings;\n sprite->current_index = math<int>::clamp( sprite->current_index, 0, drawings.size() - 1 );\n mesh->matchTexture( drawings.at( sprite->current_index ).drawing );\n }\n}\n\nvoid SpriteAnimationSystem::update( EntityManagerRef es, EventManagerRef events, double dt )\n{\n for( auto entity : es->entities_with_components<SpriteAnimation, RenderMesh>() )\n {\n auto sprite = entity.component<SpriteAnimation>();\n\n const auto &anim = mAnimations.at( sprite->animation );\n const auto ¤t_drawing = anim.drawings.at( sprite->current_index );\n sprite->hold += dt; \/\/ this becomes a problem if many share the same sprite\n int next_index = sprite->current_index;\n \/\/ check timing\n if( sprite->hold > anim.frame_duration * current_drawing.hold )\n { \/\/ move to next frame\n next_index += 1;\n sprite->hold = 0.0f;\n }\n else if ( sprite->hold < 0.0f )\n { \/\/ step back a frame\n next_index -= 1;\n sprite->hold = anim.frame_duration * current_drawing.hold;\n }\n \/\/ handle wrapping around beginning and end\n if( next_index >= static_cast<int>( anim.drawings.size() ) )\n { \/\/ handle wraparound at end\n next_index = sprite->looping ? 0 : anim.drawings.size() - 1;\n if( sprite->finish_fn ){ sprite->finish_fn(); }\n }\n else if( next_index < 0 )\n { \/\/ handle wraparound at beginning\n next_index = sprite->looping ? anim.drawings.size() - 1 : 0;\n if( sprite->finish_fn ){ sprite->finish_fn(); }\n }\n \/\/ actually change the drawing\n if( next_index != sprite->current_index )\n { \/\/ the frame index has changed, update display\n sprite->current_index = next_index;\n const auto new_drawing = anim.drawings.at( sprite->current_index ).drawing;\n auto mesh = entity.component<RenderMesh>();\n if( mesh ){ mesh->matchTexture( new_drawing ); }\n }\n }\n}\n<commit_msg>Sprite update is safe in the case that finish_fn destroys entity.<commit_after>\/*\n * Copyright (c) 2013 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"puptent\/SpriteSystem.h\"\n#include \"puptent\/RenderMesh.h\"\n#include \"cinder\/Json.h\"\n\nusing namespace puptent;\nusing namespace cinder;\nusing namespace std;\n\nSpriteAnimationSystemRef SpriteAnimationSystem::create( TextureAtlasRef atlas, const ci::JsonTree &animations )\n{\n return SpriteAnimationSystemRef{ new SpriteAnimationSystem{ atlas, animations } };\n}\n\nSpriteAnimationSystem::SpriteAnimationSystem( TextureAtlasRef atlas, const JsonTree &animations ):\nmAtlas( atlas )\n{\n try\n {\n for( auto &anim : animations )\n {\n vector<Drawing> drawings;\n float frame_duration = 1.0f \/ anim.getChild(\"fps\").getValue<float>();\n string key = anim.getKey();\n auto frames = anim.getChild(\"frames\");\n for( auto &child : frames.getChildren() )\n { \/\/ stored in json as [ \"id\", duration ]\n drawings.emplace_back( mAtlas->get(child[0].getValue()), child[1].getValue<float>() );\n }\n mAnimations.emplace_back( Animation{ key, drawings, frame_duration } );\n mAnimationIds[key] = mAnimations.size() - 1;\n }\n }\n catch( JsonTree::Exception &exc )\n {\n std::cout << __FUNCTION__ << \" error: \" << exc.what() << std::endl;\n }\n}\n\nvoid SpriteAnimationSystem::configure( EventManagerRef events )\n{\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n events->subscribe<ComponentAddedEvent<SpriteAnimation>>( *this );\n}\n\nvoid SpriteAnimationSystem::addAnimation(const string &name, const Animation &animation)\n{\n mAnimations.emplace_back( animation );\n mAnimationIds[name] = mAnimations.size() - 1;\n}\n\nAnimationId SpriteAnimationSystem::getAnimationId( const string &name ) const\n{\n AnimationId index = 0;\n auto iter = mAnimationIds.find( name );\n if( iter != mAnimationIds.end() )\n {\n index = iter->second;\n }\n return index;\n}\n\nSpriteAnimationRef SpriteAnimationSystem::createSpriteAnimation(const string &name) const\n{\n return createSpriteAnimation( getAnimationId( name ) );\n}\n\nSpriteAnimationRef SpriteAnimationSystem::createSpriteAnimation(AnimationId animation_id ) const\n{\n return SpriteAnimationRef{ new SpriteAnimation{ animation_id } };\n}\n\nvoid SpriteAnimationSystem::receive(const ComponentAddedEvent<SpriteAnimation> &event)\n{ \/\/ track the sprite\n auto entity = event.entity;\n auto mesh = entity.component<RenderMesh>();\n if( mesh )\n {\n auto sprite = event.component;\n auto drawings = mAnimations.at( sprite->animation ).drawings;\n sprite->current_index = math<int>::clamp( sprite->current_index, 0, drawings.size() - 1 );\n mesh->matchTexture( drawings.at( sprite->current_index ).drawing );\n }\n}\n\nvoid SpriteAnimationSystem::update( EntityManagerRef es, EventManagerRef events, double dt )\n{\n for( auto entity : es->entities_with_components<SpriteAnimation, RenderMesh>() )\n {\n auto sprite = entity.component<SpriteAnimation>();\n auto mesh = entity.component<RenderMesh>();\n\n const auto &anim = mAnimations.at( sprite->animation );\n const auto ¤t_drawing = anim.drawings.at( sprite->current_index );\n sprite->hold += dt; \/\/ this becomes a problem if many share the same sprite\n int next_index = sprite->current_index;\n \/\/ check timing\n if( sprite->hold > anim.frame_duration * current_drawing.hold )\n { \/\/ move to next frame\n next_index += 1;\n sprite->hold = 0.0f;\n }\n else if ( sprite->hold < 0.0f )\n { \/\/ step back a frame\n next_index -= 1;\n sprite->hold = anim.frame_duration * current_drawing.hold;\n }\n \/\/ handle wrapping around beginning and end\n if( next_index >= static_cast<int>( anim.drawings.size() ) )\n { \/\/ handle wraparound at end\n next_index = sprite->looping ? 0 : anim.drawings.size() - 1;\n if( sprite->finish_fn ){ sprite->finish_fn(); }\n }\n else if( next_index < 0 )\n { \/\/ handle wraparound at beginning\n next_index = sprite->looping ? anim.drawings.size() - 1 : 0;\n if( sprite->finish_fn ){ sprite->finish_fn(); }\n }\n \/\/ actually change the drawing\n if( next_index != sprite->current_index )\n { \/\/ the frame index has changed, update display\n sprite->current_index = next_index;\n const auto &next_drawing = anim.drawings.at( sprite->current_index ).drawing;\n if( mesh ){ mesh->matchTexture( next_drawing ); }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2015 Marcus Johansson <mcodev31@gmail.com>\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"symmetrywidget.h\"\n#include \"richtextdelegate.h\"\n#include \"symmetryutil.h\"\n#include \"ui_symmetrywidget.h\"\n\n#include <avogadro\/qtgui\/molecule.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QRegExp>\n#include <QtWidgets\/QPlainTextEdit>\n\nusing Avogadro::QtGui::Molecule;\n\nusing namespace msym;\nusing namespace Avogadro::QtPlugins::SymmetryUtil;\n\nnamespace Avogadro {\nnamespace QtPlugins {\n\nmsym_thresholds_t tight_thresholds = { \/\/ all defaults\n \/*.zero =*\/1.0e-3,\n \/*.geometry =*\/1.0e-3,\n \/*.angle =*\/1.0e-3,\n \/*.equivalence =*\/5.0e-4,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/5.0e-3,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t medium_thresholds = {\n \/*.zero =*\/1.0e-2,\n \/*.geometry =*\/1.0e-2,\n \/*.angle =*\/1.0e-2,\n \/*.equivalence =*\/6.3e-3,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.58e-2,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t loose_thresholds = {\n \/*.zero =*\/0.06,\n \/*.geometry =*\/0.06,\n \/*.angle =*\/0.06,\n \/*.equivalence =*\/0.025,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.0e-1,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t sloppy_thresholds = {\n \/*.zero =*\/0.08,\n \/*.geometry =*\/0.1,\n \/*.angle =*\/0.1,\n \/*.equivalence =*\/0.06,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.0e-1,\n \/*.orthogonalization =*\/0.1\n};\n\nSymmetryWidget::SymmetryWidget(QWidget* parent_)\n : QWidget(parent_), m_ui(new Ui::SymmetryWidget), m_molecule(NULL),\n m_equivalenceTreeModel(new QStandardItemModel(this)),\n m_operationsTableModel(new OperationsTableModel(this)),\n m_subgroupsTreeModel(new QStandardItemModel(this)),\n m_es(NULL), m_sops(NULL), m_sg(NULL), m_sopsl(0), m_sgl(0), m_radius(0.0)\n{\n setWindowFlags(Qt::Dialog);\n m_ui->setupUi(this);\n\n m_ui->equivalenceTree->setModel(m_equivalenceTreeModel);\n\n m_ui->operationsTable->setModel(m_operationsTableModel);\n m_ui->operationsTable->setItemDelegateForColumn(\n OperationsTableModel::ColumnType, new RichTextDelegate(this));\n\n m_ui->subgroupsTree->setModel(m_subgroupsTreeModel);\n m_ui->subgroupsTree->setItemDelegateForColumn(0, new RichTextDelegate(this));\n\n connect(m_ui->detectSymmetryButton, SIGNAL(clicked()),\n SIGNAL(detectSymmetry()));\n connect(m_ui->symmetrizeMoleculeButton, SIGNAL(clicked()),\n SIGNAL(symmetrizeMolecule()));\n\n connect(\n m_ui->subgroupsTree->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(\n equivalenceSelectionChanged(const QItemSelection&, const QItemSelection&)));\n\n connect(\n m_ui->operationsTable->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(operationsSelectionChanged(const QItemSelection&,\n const QItemSelection&)));\n connect(\n m_ui->subgroupsTree->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(\n subgroupsSelectionChanged(const QItemSelection&, const QItemSelection&)));\n}\n\nSymmetryWidget::~SymmetryWidget()\n{\n delete m_ui;\n}\n\nvoid SymmetryWidget::setMolecule(QtGui::Molecule* molecule)\n{\n if (molecule != m_molecule) {\n if (m_molecule)\n m_molecule->disconnect(this);\n\n m_molecule = molecule;\n\n if (m_molecule) {\n connect(m_molecule, SIGNAL(changed(uint)), SLOT(moleculeChanged(uint)));\n }\n }\n}\n\nvoid SymmetryWidget::moleculeChanged(unsigned int changes)\n{\n \/*\n if (changes & Molecule::UnitCell)\n revert();*\/\n}\n\nvoid SymmetryWidget::operationsSelectionChanged(\n const QItemSelection& selected, const QItemSelection& deselected)\n{\n\n if (!m_molecule)\n return;\n if (m_ui->tabWidget->currentWidget() != m_ui->subgroupsTab) {\n qDebug() << \"subgroupsTab not selected\";\n m_ui->subgroupsTree->selectionModel()->reset();\n } else\n qDebug() << \"subgroupsTab selected\";\n\n QModelIndexList selection =\n m_ui->operationsTable->selectionModel()->selectedRows();\n\n qDebug() << \"operations changed\";\n\n qDebug() << \"selection \" << selection.size();\n\n QVariantList reflectionVariantList;\n QVariantList properRotationVariantList;\n QVariantList improperRotationVariantList;\n\n m_molecule->setProperty(\"SymmetryOrigo\", QVariant());\n m_molecule->setProperty(\"SymmetryRadius\", QVariant());\n m_molecule->setProperty(\"SymmetryInversion\", QVariant());\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryReflectionVariantList\", QVariant());\n\n qDebug() << \"cleared elements\";\n\n if (m_sopsl > 0 && selection.size() > 0) {\n m_molecule->setProperty(\"SymmetryOrigo\", m_cm);\n m_molecule->setProperty(\"SymmetryRadius\", m_radius);\n }\n\n foreach (QModelIndex i, selection) {\n unsigned int row = i.row();\n if (!i.isValid() || row >= m_sopsl)\n continue;\n float x = m_sops[row].v[0], y = m_sops[row].v[1], z = m_sops[row].v[2];\n switch (m_sops[row].type) {\n case IDENTITY:\n break;\n case PROPER_ROTATION:\n properRotationVariantList.append(QVector3D(x, y, z));\n break;\n case IMPROPER_ROTATION:\n improperRotationVariantList.append(QVector3D(x, y, z));\n break;\n case REFLECTION:\n reflectionVariantList.append(QVector3D(x, y, z));\n break;\n case INVERSION:\n m_molecule->setProperty(\"SymmetryInversion\", m_cm);\n break;\n default:\n break;\n }\n }\n if (properRotationVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\",\n properRotationVariantList);\n if (improperRotationVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\",\n improperRotationVariantList);\n if (reflectionVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryReflectionVariantList\",\n reflectionVariantList);\n\n \/* A little bit ugly, but it'll do for now *\/\n m_molecule->emitChanged(QtGui::Molecule::Atoms);\n}\n\nvoid SymmetryWidget::subgroupsSelectionChanged(const QItemSelection& selected,\n const QItemSelection& deselected)\n{\n \/\/ QModelIndexList selection =\n \/\/ m_ui->subgroupsTree->selectionModel()->selectedIndexes();\n QModelIndex i =\n m_ui->subgroupsTree->selectionModel()->selectedIndexes().first();\n qDebug() << \"subgroupsSelectionChanged\";\n if (!i.isValid())\n return;\n qDebug() << \"valid\";\n int sgi = i.data(Qt::UserRole).value<int>();\n qDebug() << \"index \" << sgi;\n if (sgi < 0 || sgi >= m_sgl)\n return;\n const msym::msym_subgroup_t* sg = &m_sg[sgi];\n \/\/ m_ui->operationsTable->selectionModel()->clear();\n\n QItemSelectionModel* selectionModel = m_ui->operationsTable->selectionModel();\n \/\/ selectionModel->clear();\n\n QItemSelection selection;\n\n for (int j = 0; j < sg->order; j++) {\n int row = static_cast<int>(sg->sops[j] - m_sops);\n QModelIndex left = m_operationsTableModel->index(row, 0);\n QModelIndex right = m_operationsTableModel->index(\n row, m_operationsTableModel->columnCount(left) - 1);\n if (!left.isValid() || !right.isValid())\n qDebug() << \"invalid index \" << j;\n QItemSelection sel(left, right);\n\n selection.merge(sel, QItemSelectionModel::Select);\n }\n\n QModelIndexList tmp = selection.indexes();\n foreach (QModelIndex j, tmp) {\n qDebug() << \"selecting \" << j.row() << \" \" << j.column();\n }\n\n selectionModel->select(selection, QItemSelectionModel::ClearAndSelect);\n}\n\nvoid SymmetryWidget::equivalenceSelectionChanged(const QItemSelection& selected,\n const QItemSelection& deselected)\n{\n QModelIndex i =\n m_ui->equivalenceTree->selectionModel()->selectedIndexes().first();\n qDebug() << \"equivalenceSelectionChanged\";\n if (!i.isValid())\n return;\n int atomInGroup = i.data(Qt::UserRole).value<int>();\n QModelIndex g = i.parent();\n if (!g.isValid())\n return;\n int group = g.data(Qt::UserRole).value<int>();\n\n qDebug() << \"valid \" << group << atomInGroup;\n if (group < 0 || group >= m_esl)\n return;\n\n \/\/ TODO: okay, now we have to find the atoms and select them\n if (!m_molecule)\n return;\n\n const msym_equivalence_set_t *smes = &m_es[group];\n const msym_element_t *a = smes->elements[atomInGroup];\n if (a == NULL)\n return;\n\n unsigned int length = m_molecule->atomCount();\n for (Index i = 0; i < length; ++i) {\n if (m_molecule->atomicNumbers()[i] != a->n)\n continue;\n\n Vector3 ipos = m_molecule->atomPositions3d()[i];\n if (a->v[0] == ipos[0]\n && a->v[1] == ipos[1]\n && a->v[2] == ipos[2])\n m_molecule->setAtomSelected(i, true);\n }\n}\n\nvoid SymmetryWidget::setRadius(double radius)\n{\n m_radius = radius;\n}\n\nvoid SymmetryWidget::setCenterOfMass(double cm[3])\n{\n m_cm = QVector3D(cm[0], cm[1], cm[2]);\n}\n\nvoid SymmetryWidget::setPointGroupSymbol(QString pg)\n{\n m_ui->pointGroupLabel->setText(pg);\n}\n\nvoid SymmetryWidget::setSymmetryOperations(\n int sopsl, const msym::msym_symmetry_operation_t* sops)\n{\n m_sops = sops;\n m_sopsl = sopsl;\n m_operationsTableModel->setOperations(sopsl, sops);\n m_molecule->setProperty(\"SymmetryOrigo\", QVariant());\n m_molecule->setProperty(\"SymmetryRadius\", QVariant());\n m_molecule->setProperty(\"SymmetryInversion\", QVariant());\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryReflectionVariantList\", QVariant());\n \/* need another change event *\/\n m_molecule->emitChanged(QtGui::Molecule::Atoms);\n}\n\nvoid SymmetryWidget::setEquivalenceSets(int esl,\n const msym::msym_equivalence_set_t* es)\n{\n m_esl = esl;\n m_es = es;\n m_equivalenceTreeModel->clear();\n for (int i = 0; i < esl; i++) {\n QStandardItem* const parent = new QStandardItem;\n QString label = tr(\"Group %1\").arg(QString::number(i + 1));\n parent->setText(label);\n parent->setData(i, Qt::UserRole);\n m_equivalenceTreeModel->appendRow(parent);\n const msym_equivalence_set_t *smes = &es[i];\n for (int j = 0; j < smes->length; j++) {\n QStandardItem* const child = new QStandardItem;\n label = tr(\"%1 %2\").arg(smes->elements[j]->name)\n .arg(QString::number(j + 1));\n child->setText(label);\n child->setData(j, Qt::UserRole);\n parent->appendRow(child);\n }\n }\n}\n\nvoid SymmetryWidget::setSubgroups(int sgl, const msym::msym_subgroup_t* sg)\n{\n m_sg = sg;\n m_sgl = sgl;\n m_subgroupsTreeModel->clear();\n for (int i = 0; i < sgl; i++) {\n if (sg[i].order <= 2)\n continue;\n QStandardItem* const parent = new QStandardItem;\n parent->setText(pointGroupSymbol(sg[i].name));\n parent->setData(i, Qt::UserRole);\n m_subgroupsTreeModel->appendRow(parent);\n for (int j = 0; j < 2; j++) {\n if (sg[i].generators[j] == NULL)\n continue;\n qDebug() << \"child \" << sg[i].generators[j] - m_sg << \" \"\n << sg[i].generators[j] << \" \" << m_sg;\n QStandardItem* const child = new QStandardItem;\n child->setText(pointGroupSymbol(sg[i].generators[j]->name));\n\n child->setData(static_cast<int>(sg[i].generators[j] - m_sg),\n Qt::UserRole);\n parent->appendRow(child);\n }\n }\n}\n\nmsym_thresholds_t* SymmetryWidget::getThresholds() const\n{\n msym_thresholds_t* thresholds = NULL;\n switch (m_ui->toleranceCombo->currentIndex()) {\n case 2: \/\/ loose\n thresholds = &loose_thresholds;\n break;\n case 1: \/\/ normal\n thresholds = &medium_thresholds;\n break;\n case 0: \/\/ tight\n default:\n thresholds = &tight_thresholds;\n }\n return thresholds;\n}\n\n} \/\/ namespace QtPlugins\n} \/\/ namespace Avogadro\n<commit_msg>Add support for selecting individual atoms in a group.<commit_after>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2015 Marcus Johansson <mcodev31@gmail.com>\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"symmetrywidget.h\"\n#include \"richtextdelegate.h\"\n#include \"symmetryutil.h\"\n#include \"ui_symmetrywidget.h\"\n\n#include <avogadro\/qtgui\/molecule.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QRegExp>\n#include <QtWidgets\/QPlainTextEdit>\n\nusing Avogadro::QtGui::Molecule;\n\nusing namespace msym;\nusing namespace Avogadro::QtPlugins::SymmetryUtil;\n\nnamespace Avogadro {\nnamespace QtPlugins {\n\nmsym_thresholds_t tight_thresholds = { \/\/ all defaults\n \/*.zero =*\/1.0e-3,\n \/*.geometry =*\/1.0e-3,\n \/*.angle =*\/1.0e-3,\n \/*.equivalence =*\/5.0e-4,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/5.0e-3,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t medium_thresholds = {\n \/*.zero =*\/1.0e-2,\n \/*.geometry =*\/1.0e-2,\n \/*.angle =*\/1.0e-2,\n \/*.equivalence =*\/6.3e-3,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.58e-2,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t loose_thresholds = {\n \/*.zero =*\/0.06,\n \/*.geometry =*\/0.06,\n \/*.angle =*\/0.06,\n \/*.equivalence =*\/0.025,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.0e-1,\n \/*.orthogonalization =*\/0.1\n};\n\nmsym_thresholds_t sloppy_thresholds = {\n \/*.zero =*\/0.08,\n \/*.geometry =*\/0.1,\n \/*.angle =*\/0.1,\n \/*.equivalence =*\/0.06,\n \/*.eigfact =*\/1.0e-3,\n \/*.permutation =*\/1.0e-1,\n \/*.orthogonalization =*\/0.1\n};\n\nSymmetryWidget::SymmetryWidget(QWidget* parent_)\n : QWidget(parent_), m_ui(new Ui::SymmetryWidget), m_molecule(NULL),\n m_equivalenceTreeModel(new QStandardItemModel(this)),\n m_operationsTableModel(new OperationsTableModel(this)),\n m_subgroupsTreeModel(new QStandardItemModel(this)),\n m_es(NULL), m_sops(NULL), m_sg(NULL), m_sopsl(0), m_sgl(0), m_radius(0.0)\n{\n setWindowFlags(Qt::Dialog);\n m_ui->setupUi(this);\n\n m_ui->equivalenceTree->setModel(m_equivalenceTreeModel);\n\n m_ui->operationsTable->setModel(m_operationsTableModel);\n m_ui->operationsTable->setItemDelegateForColumn(\n OperationsTableModel::ColumnType, new RichTextDelegate(this));\n\n m_ui->subgroupsTree->setModel(m_subgroupsTreeModel);\n m_ui->subgroupsTree->setItemDelegateForColumn(0, new RichTextDelegate(this));\n\n connect(m_ui->detectSymmetryButton, SIGNAL(clicked()),\n SIGNAL(detectSymmetry()));\n connect(m_ui->symmetrizeMoleculeButton, SIGNAL(clicked()),\n SIGNAL(symmetrizeMolecule()));\n\n connect(\n m_ui->equivalenceTree->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(\n equivalenceSelectionChanged(const QItemSelection&, const QItemSelection&)));\n\n connect(\n m_ui->operationsTable->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(operationsSelectionChanged(const QItemSelection&,\n const QItemSelection&)));\n connect(\n m_ui->subgroupsTree->selectionModel(),\n SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),\n SLOT(\n subgroupsSelectionChanged(const QItemSelection&, const QItemSelection&)));\n}\n\nSymmetryWidget::~SymmetryWidget()\n{\n delete m_ui;\n}\n\nvoid SymmetryWidget::setMolecule(QtGui::Molecule* molecule)\n{\n if (molecule != m_molecule) {\n if (m_molecule)\n m_molecule->disconnect(this);\n\n m_molecule = molecule;\n\n if (m_molecule) {\n connect(m_molecule, SIGNAL(changed(uint)), SLOT(moleculeChanged(uint)));\n }\n }\n}\n\nvoid SymmetryWidget::moleculeChanged(unsigned int changes)\n{\n \/*\n if (changes & Molecule::UnitCell)\n revert();*\/\n}\n\nvoid SymmetryWidget::operationsSelectionChanged(\n const QItemSelection& selected, const QItemSelection& deselected)\n{\n\n if (!m_molecule)\n return;\n if (m_ui->tabWidget->currentWidget() != m_ui->subgroupsTab) {\n qDebug() << \"subgroupsTab not selected\";\n m_ui->subgroupsTree->selectionModel()->reset();\n } else\n qDebug() << \"subgroupsTab selected\";\n\n QModelIndexList selection =\n m_ui->operationsTable->selectionModel()->selectedRows();\n\n qDebug() << \"operations changed\";\n\n qDebug() << \"selection \" << selection.size();\n\n QVariantList reflectionVariantList;\n QVariantList properRotationVariantList;\n QVariantList improperRotationVariantList;\n\n m_molecule->setProperty(\"SymmetryOrigo\", QVariant());\n m_molecule->setProperty(\"SymmetryRadius\", QVariant());\n m_molecule->setProperty(\"SymmetryInversion\", QVariant());\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryReflectionVariantList\", QVariant());\n\n qDebug() << \"cleared elements\";\n\n if (m_sopsl > 0 && selection.size() > 0) {\n m_molecule->setProperty(\"SymmetryOrigo\", m_cm);\n m_molecule->setProperty(\"SymmetryRadius\", m_radius);\n }\n\n foreach (QModelIndex i, selection) {\n unsigned int row = i.row();\n if (!i.isValid() || row >= m_sopsl)\n continue;\n float x = m_sops[row].v[0], y = m_sops[row].v[1], z = m_sops[row].v[2];\n switch (m_sops[row].type) {\n case IDENTITY:\n break;\n case PROPER_ROTATION:\n properRotationVariantList.append(QVector3D(x, y, z));\n break;\n case IMPROPER_ROTATION:\n improperRotationVariantList.append(QVector3D(x, y, z));\n break;\n case REFLECTION:\n reflectionVariantList.append(QVector3D(x, y, z));\n break;\n case INVERSION:\n m_molecule->setProperty(\"SymmetryInversion\", m_cm);\n break;\n default:\n break;\n }\n }\n if (properRotationVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\",\n properRotationVariantList);\n if (improperRotationVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\",\n improperRotationVariantList);\n if (reflectionVariantList.size() > 0)\n m_molecule->setProperty(\"SymmetryReflectionVariantList\",\n reflectionVariantList);\n\n \/* A little bit ugly, but it'll do for now *\/\n m_molecule->emitChanged(QtGui::Molecule::Atoms);\n}\n\nvoid SymmetryWidget::subgroupsSelectionChanged(const QItemSelection& selected,\n const QItemSelection& deselected)\n{\n \/\/ QModelIndexList selection =\n \/\/ m_ui->subgroupsTree->selectionModel()->selectedIndexes();\n QModelIndex i =\n m_ui->subgroupsTree->selectionModel()->selectedIndexes().first();\n qDebug() << \"subgroupsSelectionChanged\";\n if (!i.isValid())\n return;\n qDebug() << \"valid\";\n int sgi = i.data(Qt::UserRole).value<int>();\n qDebug() << \"index \" << sgi;\n if (sgi < 0 || sgi >= m_sgl)\n return;\n const msym::msym_subgroup_t* sg = &m_sg[sgi];\n \/\/ m_ui->operationsTable->selectionModel()->clear();\n\n QItemSelectionModel* selectionModel = m_ui->operationsTable->selectionModel();\n \/\/ selectionModel->clear();\n\n QItemSelection selection;\n\n for (int j = 0; j < sg->order; j++) {\n int row = static_cast<int>(sg->sops[j] - m_sops);\n QModelIndex left = m_operationsTableModel->index(row, 0);\n QModelIndex right = m_operationsTableModel->index(\n row, m_operationsTableModel->columnCount(left) - 1);\n if (!left.isValid() || !right.isValid())\n qDebug() << \"invalid index \" << j;\n QItemSelection sel(left, right);\n\n selection.merge(sel, QItemSelectionModel::Select);\n }\n\n QModelIndexList tmp = selection.indexes();\n foreach (QModelIndex j, tmp) {\n qDebug() << \"selecting \" << j.row() << \" \" << j.column();\n }\n\n selectionModel->select(selection, QItemSelectionModel::ClearAndSelect);\n}\n\nvoid SymmetryWidget::equivalenceSelectionChanged(const QItemSelection& selected,\n const QItemSelection& deselected)\n{\n QModelIndex i =\n m_ui->equivalenceTree->selectionModel()->selectedIndexes().first();\n qDebug() << \"equivalenceSelectionChanged\";\n if (!i.isValid())\n return;\n int atomInGroup = i.data(Qt::UserRole).value<int>();\n QModelIndex g = i.parent();\n if (!g.isValid())\n return;\n int group = g.data(Qt::UserRole).value<int>();\n\n qDebug() << \"valid \" << group << atomInGroup;\n if (group < 0 || group >= m_esl)\n return;\n\n \/\/ TODO: okay, now we have to find the atoms and select them\n if (!m_molecule)\n return;\n\n const msym_equivalence_set_t *smes = &m_es[group];\n const msym_element_t *a = smes->elements[atomInGroup];\n if (a == NULL)\n return;\n\n unsigned int length = m_molecule->atomCount();\n for (Index i = 0; i < length; ++i) {\n qDebug() << \"checking atom\" << i << \" for \" << a->n;\n m_molecule->setAtomSelected(i, false);\n if (m_molecule->atomicNumbers()[i] != a->n)\n continue;\n\n Vector3 ipos = m_molecule->atomPositions3d()[i];\n qDebug() << a->v[0] << ipos[0] - m_cm[0];\n qDebug() << a->v[1] << ipos[1] - m_cm[1];\n qDebug() << a->v[2] << ipos[2] - m_cm[2];\n if ( fabs(a->v[0] - (ipos[0] - m_cm[0])) < 0.05\n && fabs(a->v[0] - (ipos[0] - m_cm[0])) < 0.05\n && fabs(a->v[0] - (ipos[0] - m_cm[0])) < 0.05\n ) {\n m_molecule->setAtomSelected(i, true);\n qDebug() << \" got one!\";\n }\n }\n m_molecule->emitChanged(QtGui::Molecule::Atoms);\n}\n\nvoid SymmetryWidget::setRadius(double radius)\n{\n m_radius = radius;\n}\n\nvoid SymmetryWidget::setCenterOfMass(double cm[3])\n{\n m_cm = QVector3D(cm[0], cm[1], cm[2]);\n}\n\nvoid SymmetryWidget::setPointGroupSymbol(QString pg)\n{\n m_ui->pointGroupLabel->setText(pg);\n}\n\nvoid SymmetryWidget::setSymmetryOperations(\n int sopsl, const msym::msym_symmetry_operation_t* sops)\n{\n m_sops = sops;\n m_sopsl = sopsl;\n m_operationsTableModel->setOperations(sopsl, sops);\n m_molecule->setProperty(\"SymmetryOrigo\", QVariant());\n m_molecule->setProperty(\"SymmetryRadius\", QVariant());\n m_molecule->setProperty(\"SymmetryInversion\", QVariant());\n m_molecule->setProperty(\"SymmetryProperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryImproperRotationVariantList\", QVariant());\n m_molecule->setProperty(\"SymmetryReflectionVariantList\", QVariant());\n \/* need another change event *\/\n m_molecule->emitChanged(QtGui::Molecule::Atoms);\n}\n\nvoid SymmetryWidget::setEquivalenceSets(int esl,\n const msym::msym_equivalence_set_t* es)\n{\n m_esl = esl;\n m_es = es;\n m_equivalenceTreeModel->clear();\n for (int i = 0; i < esl; i++) {\n QStandardItem* const parent = new QStandardItem;\n QString label = tr(\"Group %1\").arg(QString::number(i + 1));\n parent->setText(label);\n parent->setData(i, Qt::UserRole);\n m_equivalenceTreeModel->appendRow(parent);\n const msym_equivalence_set_t *smes = &es[i];\n for (int j = 0; j < smes->length; j++) {\n QStandardItem* const child = new QStandardItem;\n label = tr(\"%1 %2\").arg(smes->elements[j]->name)\n .arg(QString::number(j + 1));\n child->setText(label);\n child->setData(j, Qt::UserRole);\n parent->appendRow(child);\n }\n }\n}\n\nvoid SymmetryWidget::setSubgroups(int sgl, const msym::msym_subgroup_t* sg)\n{\n m_sg = sg;\n m_sgl = sgl;\n m_subgroupsTreeModel->clear();\n for (int i = 0; i < sgl; i++) {\n if (sg[i].order <= 2)\n continue;\n QStandardItem* const parent = new QStandardItem;\n parent->setText(pointGroupSymbol(sg[i].name));\n parent->setData(i, Qt::UserRole);\n m_subgroupsTreeModel->appendRow(parent);\n for (int j = 0; j < 2; j++) {\n if (sg[i].generators[j] == NULL)\n continue;\n qDebug() << \"child \" << sg[i].generators[j] - m_sg << \" \"\n << sg[i].generators[j] << \" \" << m_sg;\n QStandardItem* const child = new QStandardItem;\n child->setText(pointGroupSymbol(sg[i].generators[j]->name));\n\n child->setData(static_cast<int>(sg[i].generators[j] - m_sg),\n Qt::UserRole);\n parent->appendRow(child);\n }\n }\n}\n\nmsym_thresholds_t* SymmetryWidget::getThresholds() const\n{\n msym_thresholds_t* thresholds = NULL;\n switch (m_ui->toleranceCombo->currentIndex()) {\n case 2: \/\/ loose\n thresholds = &loose_thresholds;\n break;\n case 1: \/\/ normal\n thresholds = &medium_thresholds;\n break;\n case 0: \/\/ tight\n default:\n thresholds = &tight_thresholds;\n }\n return thresholds;\n}\n\n} \/\/ namespace QtPlugins\n} \/\/ namespace Avogadro\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n @brief RX24T CNC ドライバー @n\n\t\t\t・ステッピングモーターパルス出力 @n\n\t\t\t・リミットスイッチによる制御 @n\n\t\t\t・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n\n#include \"cnc_pulse.hpp\"\n\nnamespace {\n\n\tstatic const uint16_t VERSION = 10;\n\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\n\tdevice::cmt_io<device::CMT0, utils::null_task> cmt_;\n\n\ttypedef utils::fixed_fifo<char, 1024> RBF;\n\ttypedef utils::fixed_fifo<char, 128> SBF;\n\ttypedef device::sci_io<device::SCI1, RBF, SBF> SCI;\n\tSCI\t\tsci_;\n\n\ttypedef utils::command<256> COMMAND;\n\tCOMMAND command_;\n\n\ttypedef cnc::pulse<COMMAND>\tCNC;\n\tCNC\t\tcnc_(command_);\n\t\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 80MHz 動作 wait 設定\n\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\tdevice::SYSTEM::OPCCR = 0; \/\/ 高速モード選択\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\n\t\/\/ clock osc 10MHz\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\n\t\/\/ メインクロック・ドライブ能力設定、内部発信\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0; \/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::PLLCR.STC = 0b001111;\t\t\/\/ PLL input: 1, PLL 8 倍(80MHz)\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/4 (80\/4=20)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1)\t\t\/\/ 1\/2 (80\/2=40)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1);\t\/\/ 1\/2 (80\/2=40)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\t\/\/ タイマー設定(100Hz)\n\t{\n\t\tuint8_t intr = 3;\n\t\tcmt_.start(100, intr);\n\t}\n\n\t\/\/ SCI 設定\n\tstatic const uint8_t sci_level = 2;\n\tsci_.start(115200, sci_level);\n\n\tutils::format(\"CNC Driver Version %1d.%02d\\n\") % (VERSION \/ 100) % (VERSION % 100);\n\n\tcnc_.start();\n\n\tcommand_.set_prompt(\"# \");\n\n\tLED::DIR = 1;\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt_.sync();\n\n\t\tcnc_.update();\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\t\t\tauto f = cnc_.service_command();\n\t\t\tif(!f) {\n\t\t\t\tutils::format(\"Error: '%s'\\n\") % command_.get_command();\n\t\t\t}\n\t\t}\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tLED::P = (cnt < 10) ? 0 : 1;\n\t}\n}\n<commit_msg>update: version 0.40 CNC<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n @brief RX24T CNC ドライバー @n\n\t\t\t・ステッピングモーターパルス出力 @n\n\t\t\t・リミットスイッチによる制御 @n\n\t\t\t・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n\n#include \"cnc_pulse.hpp\"\n\nnamespace {\n\n\tstatic const uint16_t VERSION = 40;\n\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\n\tdevice::cmt_io<device::CMT0, utils::null_task> cmt_;\n\n\ttypedef utils::fixed_fifo<char, 1024> RBF;\n\ttypedef utils::fixed_fifo<char, 128> SBF;\n\ttypedef device::sci_io<device::SCI1, RBF, SBF> SCI;\n\tSCI\t\tsci_;\n\n\ttypedef utils::command<256> COMMAND;\n\tCOMMAND command_;\n\n\ttypedef cnc::pulse<COMMAND>\tCNC;\n\tCNC\t\tcnc_(command_);\n\t\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 80MHz 動作 wait 設定\n\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\tdevice::SYSTEM::OPCCR = 0; \/\/ 高速モード選択\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\n\t\/\/ clock osc 10MHz\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\n\t\/\/ メインクロック・ドライブ能力設定、内部発信\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0; \/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::PLLCR.STC = 0b001111;\t\t\/\/ PLL input: 1, PLL 8 倍(80MHz)\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/4 (80\/4=20)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1)\t\t\/\/ 1\/2 (80\/2=40)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1);\t\/\/ 1\/2 (80\/2=40)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\t\/\/ タイマー設定(100Hz)\n\t{\n\t\tuint8_t intr = 3;\n\t\tcmt_.start(100, intr);\n\t}\n\n\t\/\/ SCI 設定\n\tstatic const uint8_t sci_level = 2;\n\tsci_.start(115200, sci_level);\n\n\tutils::format(\"CNC Driver Version %1d.%02d\\n\") % (VERSION \/ 100) % (VERSION % 100);\n\n\tcnc_.start();\n\n\tcommand_.set_prompt(\"# \");\n\n\tLED::DIR = 1;\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt_.sync();\n\n\t\tcnc_.update();\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\t\t\tauto f = cnc_.service_command();\n\t\t\tif(!f) {\n\t\t\t\tutils::format(\"Error: '%s'\\n\") % command_.get_command();\n\t\t\t}\n\t\t}\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tLED::P = (cnt < 10) ? 0 : 1;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include <NDK\/Widgets\/TextAreaWidget.hpp>\n#include <Nazara\/Core\/Unicode.hpp>\n#include <NDK\/Components\/GraphicsComponent.hpp>\n#include <NDK\/Components\/NodeComponent.hpp>\n#include <NDK\/World.hpp>\n#include <limits>\n\nnamespace Ndk\n{\n\tTextAreaWidget::TextAreaWidget(BaseWidget* parent) :\n\tBaseWidget(parent),\n\tm_cursorPosition(0U),\n\tm_multiLineEnabled(false),\n\tm_readOnly(false)\n\t{\n\t\tm_cursorSprite = Nz::Sprite::New();\n\t\tm_cursorSprite->SetColor(Nz::Color(192, 192, 192));\n\t\tm_cursorSprite->SetSize(1.f, float(m_drawer.GetFont()->GetSizeInfo(m_drawer.GetCharacterSize()).lineHeight));\n\n\t\tm_cursorEntity = CreateEntity();\n\t\tm_cursorEntity->AddComponent<GraphicsComponent>().Attach(m_cursorSprite, 10);\n\t\tm_cursorEntity->AddComponent<NodeComponent>().SetParent(this);\n\t\tm_cursorEntity->Enable(false);\n\n\t\tm_textSprite = Nz::TextSprite::New();\n\n\t\tm_textEntity = CreateEntity();\n\t\tm_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite);\n\t\tm_textEntity->AddComponent<NodeComponent>().SetParent(this);\n\n\t\tSetCursor(Nz::SystemCursor_Text);\n\n\t\tLayout();\n\t}\n\n\tvoid TextAreaWidget::AppendText(const Nz::String& text)\n\t{\n\t\tm_drawer.AppendText(text);\n\n\t\tm_textSprite->Update(m_drawer);\n\t}\n\n\tstd::size_t TextAreaWidget::GetHoveredGlyph(float x, float y) const\n\t{\n\t\tstd::size_t glyphCount = m_drawer.GetGlyphCount();\n\t\tif (glyphCount > 0)\n\t\t{\n\t\t\tstd::size_t lineCount = m_drawer.GetLineCount();\n\t\t\tstd::size_t line = 0U;\n\t\t\tfor (; line < lineCount - 1; ++line)\n\t\t\t{\n\t\t\t\tNz::Rectf lineBounds = m_drawer.GetLine(line).bounds;\n\t\t\t\tif (lineBounds.GetMaximum().y > y)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tstd::size_t upperLimit = (line != lineCount - 1) ? m_drawer.GetLine(line + 1).glyphIndex : glyphCount + 1;\n\n\t\t\tstd::size_t i = m_drawer.GetLine(line).glyphIndex;\n\t\t\tfor (; i < upperLimit - 1; ++i)\n\t\t\t{\n\t\t\t\tNz::Rectf bounds = m_drawer.GetGlyph(i).bounds;\n\t\t\t\tif (x < bounds.x + bounds.width * 0.75f)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn i;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tvoid TextAreaWidget::ResizeToContent()\n\t{\n\t\tSetContentSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths()));\n\t}\n\n\tvoid TextAreaWidget::Write(const Nz::String& text)\n\t{\n\t\tif (m_cursorPosition >= m_drawer.GetGlyphCount())\n\t\t{\n\t\t\tAppendText(text);\n\t\t\tSetCursorPosition(m_drawer.GetGlyphCount());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tNz::String currentText = m_drawer.GetText();\n\t\t\tcurrentText.Insert(currentText.GetCharacterPosition(m_cursorPosition), text);\n\t\t\tSetText(currentText);\n\n\t\t\tSetCursorPosition(m_cursorPosition + text.GetLength());\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::Layout()\n\t{\n\t\tBaseWidget::Layout();\n\n\t\tm_textEntity->GetComponent<NodeComponent>().SetPosition(GetContentOrigin());\n\n\t\tRefreshCursor();\n\t}\n\n\tvoid TextAreaWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key)\n\t{\n\t\tswitch (key.code)\n\t\t{\n\t\t\tcase Nz::Keyboard::Delete:\n\t\t\t{\n\t\t\t\tconst Nz::String& text = m_drawer.GetText();\n\n\t\t\t\tNz::String newText;\n\t\t\t\tif (m_cursorPosition > 0)\n\t\t\t\t\tnewText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition) - 1));\n\n\t\t\t\tif (m_cursorPosition < m_drawer.GetGlyphCount())\n\t\t\t\t\tnewText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition + 1)));\n\n\t\t\t\tm_drawer.SetText(newText);\n\t\t\t\tm_textSprite->Update(m_drawer);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Down:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyDown(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/TODO\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Left:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyLeft(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tMoveCursor(-1);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Right:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyRight(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tMoveCursor(1);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Up:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyUp(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/TODO\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& key)\n\t{\n\t}\n\n\tvoid TextAreaWidget::OnMouseEnter()\n\t{\n\t\tm_cursorEntity->Enable(true);\n\t}\n\n\tvoid TextAreaWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button)\n\t{\n\t\tif (button == Nz::Mouse::Left)\n\t\t{\n\t\t\tGrabKeyboard();\n\n\t\t\tSetCursorPosition(GetHoveredGlyph(float(x), float(y)));\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY)\n\t{\n\t}\n\n\tvoid TextAreaWidget::OnMouseExit()\n\t{\n\t\tm_cursorEntity->Enable(false);\n\t}\n\n\tvoid TextAreaWidget::OnTextEntered(char32_t character, bool \/*repeated*\/)\n\t{\n\t\tif (m_readOnly)\n\t\t\treturn;\n\n\t\tswitch (character)\n\t\t{\n\t\t\tcase '\\b':\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyBackspace(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tconst Nz::String& text = m_drawer.GetText();\n\n\t\t\t\tNz::String newText;\n\t\t\t\tif (m_cursorPosition > 1)\n\t\t\t\t\tnewText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition - 1) - 1));\n\n\t\t\t\tif (m_cursorPosition < m_drawer.GetGlyphCount())\n\t\t\t\t\tnewText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition)));\n\n\t\t\t\tMoveCursor(-1);\n\t\t\t\tSetText(newText);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase '\\r':\n\t\t\tcase '\\n':\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyReturn(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction || !m_multiLineEnabled)\n\t\t\t\t\tbreak;\n\n\t\t\t\tWrite(Nz::String('\\n'));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tif (Nz::Unicode::GetCategory(character) == Nz::Unicode::Category_Other_Control)\n\t\t\t\t\tbreak;\n\n\t\t\t\tWrite(Nz::String::Unicode(character));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::RefreshCursor()\n\t{\n\t\tstd::size_t lineCount = m_drawer.GetLineCount();\n\t\tstd::size_t line = 0U;\n\t\tfor (std::size_t i = line + 1; i < lineCount; ++i)\n\t\t{\n\t\t\tif (m_drawer.GetLine(i).glyphIndex > m_cursorPosition)\n\t\t\t\tbreak;\n\n\t\t\tline = i;\n\t\t}\n\n\t\tconst auto& lineInfo = m_drawer.GetLine(line);\n\n\t\tstd::size_t glyphCount = m_drawer.GetGlyphCount();\n\t\tfloat position;\n\t\tif (glyphCount > 0 && lineInfo.glyphIndex < m_cursorPosition)\n\t\t{\n\t\t\tconst auto& glyph = m_drawer.GetGlyph(std::min(m_cursorPosition, glyphCount - 1));\n\t\t\tposition = glyph.bounds.x;\n\t\t\tif (m_cursorPosition >= glyphCount)\n\t\t\t\tposition += glyph.bounds.width;\n\t\t}\n\t\telse\n\t\t\tposition = 0.f;\n\n\t\tNz::Vector2f contentOrigin = GetContentOrigin();\n\n\t\tm_cursorEntity->GetComponent<NodeComponent>().SetPosition(contentOrigin.x + position, contentOrigin.y + lineInfo.bounds.y);\n\t}\n}\n<commit_msg>Sdk\/TextAreaWidget: Make cursor sprite black<commit_after>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include <NDK\/Widgets\/TextAreaWidget.hpp>\n#include <Nazara\/Core\/Unicode.hpp>\n#include <NDK\/Components\/GraphicsComponent.hpp>\n#include <NDK\/Components\/NodeComponent.hpp>\n#include <NDK\/World.hpp>\n#include <limits>\n\nnamespace Ndk\n{\n\tTextAreaWidget::TextAreaWidget(BaseWidget* parent) :\n\tBaseWidget(parent),\n\tm_cursorPosition(0U),\n\tm_multiLineEnabled(false),\n\tm_readOnly(false)\n\t{\n\t\tm_cursorSprite = Nz::Sprite::New();\n\t\tm_cursorSprite->SetColor(Nz::Color::Black);\n\t\tm_cursorSprite->SetSize(1.f, float(m_drawer.GetFont()->GetSizeInfo(m_drawer.GetCharacterSize()).lineHeight));\n\n\t\tm_cursorEntity = CreateEntity();\n\t\tm_cursorEntity->AddComponent<GraphicsComponent>().Attach(m_cursorSprite, 10);\n\t\tm_cursorEntity->AddComponent<NodeComponent>().SetParent(this);\n\t\tm_cursorEntity->Enable(false);\n\n\t\tm_textSprite = Nz::TextSprite::New();\n\n\t\tm_textEntity = CreateEntity();\n\t\tm_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite);\n\t\tm_textEntity->AddComponent<NodeComponent>().SetParent(this);\n\n\t\tSetCursor(Nz::SystemCursor_Text);\n\n\t\tLayout();\n\t}\n\n\tvoid TextAreaWidget::AppendText(const Nz::String& text)\n\t{\n\t\tm_drawer.AppendText(text);\n\n\t\tm_textSprite->Update(m_drawer);\n\t}\n\n\tstd::size_t TextAreaWidget::GetHoveredGlyph(float x, float y) const\n\t{\n\t\tstd::size_t glyphCount = m_drawer.GetGlyphCount();\n\t\tif (glyphCount > 0)\n\t\t{\n\t\t\tstd::size_t lineCount = m_drawer.GetLineCount();\n\t\t\tstd::size_t line = 0U;\n\t\t\tfor (; line < lineCount - 1; ++line)\n\t\t\t{\n\t\t\t\tNz::Rectf lineBounds = m_drawer.GetLine(line).bounds;\n\t\t\t\tif (lineBounds.GetMaximum().y > y)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tstd::size_t upperLimit = (line != lineCount - 1) ? m_drawer.GetLine(line + 1).glyphIndex : glyphCount + 1;\n\n\t\t\tstd::size_t i = m_drawer.GetLine(line).glyphIndex;\n\t\t\tfor (; i < upperLimit - 1; ++i)\n\t\t\t{\n\t\t\t\tNz::Rectf bounds = m_drawer.GetGlyph(i).bounds;\n\t\t\t\tif (x < bounds.x + bounds.width * 0.75f)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn i;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tvoid TextAreaWidget::ResizeToContent()\n\t{\n\t\tSetContentSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths()));\n\t}\n\n\tvoid TextAreaWidget::Write(const Nz::String& text)\n\t{\n\t\tif (m_cursorPosition >= m_drawer.GetGlyphCount())\n\t\t{\n\t\t\tAppendText(text);\n\t\t\tSetCursorPosition(m_drawer.GetGlyphCount());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tNz::String currentText = m_drawer.GetText();\n\t\t\tcurrentText.Insert(currentText.GetCharacterPosition(m_cursorPosition), text);\n\t\t\tSetText(currentText);\n\n\t\t\tSetCursorPosition(m_cursorPosition + text.GetLength());\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::Layout()\n\t{\n\t\tBaseWidget::Layout();\n\n\t\tm_textEntity->GetComponent<NodeComponent>().SetPosition(GetContentOrigin());\n\n\t\tRefreshCursor();\n\t}\n\n\tvoid TextAreaWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key)\n\t{\n\t\tswitch (key.code)\n\t\t{\n\t\t\tcase Nz::Keyboard::Delete:\n\t\t\t{\n\t\t\t\tconst Nz::String& text = m_drawer.GetText();\n\n\t\t\t\tNz::String newText;\n\t\t\t\tif (m_cursorPosition > 0)\n\t\t\t\t\tnewText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition) - 1));\n\n\t\t\t\tif (m_cursorPosition < m_drawer.GetGlyphCount())\n\t\t\t\t\tnewText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition + 1)));\n\n\t\t\t\tm_drawer.SetText(newText);\n\t\t\t\tm_textSprite->Update(m_drawer);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Down:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyDown(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/TODO\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Left:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyLeft(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tMoveCursor(-1);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Right:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyRight(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tMoveCursor(1);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase Nz::Keyboard::Up:\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyUp(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/\/TODO\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& key)\n\t{\n\t}\n\n\tvoid TextAreaWidget::OnMouseEnter()\n\t{\n\t\tm_cursorEntity->Enable(true);\n\t}\n\n\tvoid TextAreaWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button)\n\t{\n\t\tif (button == Nz::Mouse::Left)\n\t\t{\n\t\t\tGrabKeyboard();\n\n\t\t\tSetCursorPosition(GetHoveredGlyph(float(x), float(y)));\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY)\n\t{\n\t}\n\n\tvoid TextAreaWidget::OnMouseExit()\n\t{\n\t\tm_cursorEntity->Enable(false);\n\t}\n\n\tvoid TextAreaWidget::OnTextEntered(char32_t character, bool \/*repeated*\/)\n\t{\n\t\tif (m_readOnly)\n\t\t\treturn;\n\n\t\tswitch (character)\n\t\t{\n\t\t\tcase '\\b':\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyBackspace(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction)\n\t\t\t\t\tbreak;\n\n\t\t\t\tconst Nz::String& text = m_drawer.GetText();\n\n\t\t\t\tNz::String newText;\n\t\t\t\tif (m_cursorPosition > 1)\n\t\t\t\t\tnewText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition - 1) - 1));\n\n\t\t\t\tif (m_cursorPosition < m_drawer.GetGlyphCount())\n\t\t\t\t\tnewText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition)));\n\n\t\t\t\tMoveCursor(-1);\n\t\t\t\tSetText(newText);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase '\\r':\n\t\t\tcase '\\n':\n\t\t\t{\n\t\t\t\tbool ignoreDefaultAction = false;\n\t\t\t\tOnTextAreaKeyReturn(this, &ignoreDefaultAction);\n\n\t\t\t\tif (ignoreDefaultAction || !m_multiLineEnabled)\n\t\t\t\t\tbreak;\n\n\t\t\t\tWrite(Nz::String('\\n'));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tif (Nz::Unicode::GetCategory(character) == Nz::Unicode::Category_Other_Control)\n\t\t\t\t\tbreak;\n\n\t\t\t\tWrite(Nz::String::Unicode(character));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid TextAreaWidget::RefreshCursor()\n\t{\n\t\tstd::size_t lineCount = m_drawer.GetLineCount();\n\t\tstd::size_t line = 0U;\n\t\tfor (std::size_t i = line + 1; i < lineCount; ++i)\n\t\t{\n\t\t\tif (m_drawer.GetLine(i).glyphIndex > m_cursorPosition)\n\t\t\t\tbreak;\n\n\t\t\tline = i;\n\t\t}\n\n\t\tconst auto& lineInfo = m_drawer.GetLine(line);\n\n\t\tstd::size_t glyphCount = m_drawer.GetGlyphCount();\n\t\tfloat position;\n\t\tif (glyphCount > 0 && lineInfo.glyphIndex < m_cursorPosition)\n\t\t{\n\t\t\tconst auto& glyph = m_drawer.GetGlyph(std::min(m_cursorPosition, glyphCount - 1));\n\t\t\tposition = glyph.bounds.x;\n\t\t\tif (m_cursorPosition >= glyphCount)\n\t\t\t\tposition += glyph.bounds.width;\n\t\t}\n\t\telse\n\t\t\tposition = 0.f;\n\n\t\tNz::Vector2f contentOrigin = GetContentOrigin();\n\n\t\tm_cursorEntity->GetComponent<NodeComponent>().SetPosition(contentOrigin.x + position, contentOrigin.y + lineInfo.bounds.y);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <QtCore\/QtDebug>\n#include <QtGui\/QFrame>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QApplication>\n\n#include \"TaskWidget.h\"\n#include \"qtUtilities.h\"\n\n#include \"listviews.h\"\n#include \"DataModelGUI.h\"\n#include \"CQMessageBox.h\"\n#include \"MyLineEdit.h\"\n#include \"CProgressBar.h\"\n#include \"copasiui3window.h\"\n#include \"CQReportDefinitionSelect.h\"\n#include \"DefaultplotDialog.h\"\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskMethodWidget.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"utilities\/CCopasiMethod.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"utilities\/COutputHandler.h\"\n#include \"utilities\/CDirEntry.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n#include \"model\/CModel.h\"\n#include \"math\/CMathContainer.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"UI\/CQTaskThread.h\"\n#include \"plotUI\/CopasiPlot.h\"\n#include \"plotUI\/plotwindow.h\"\n\n\/*\n * Constructs a TaskWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nTaskWidget::TaskWidget(QWidget* parent, const char* name, Qt::WFlags fl):\n CopasiWidget(parent, name, fl),\n mProgressBar(NULL),\n mpHeaderWidget(NULL),\n mpMethodWidget(NULL),\n mpBtnWidget(NULL),\n mpMethodLayout(NULL),\n mpSpacer1(NULL),\n mpSpacer2(NULL),\n mpTask(NULL),\n mpMethod(NULL),\n mChanged(false)\n{\n if (!name)\n setObjectName(\"TaskWidget\");\n\n setWindowTitle(trUtf8(\"TaskWidget\"));\n\n mpTaskThread = new CQTaskThread(this);\n\n mpHeaderWidget = new CQTaskHeaderWidget(this);\n mpMethodWidget = new CQTaskMethodWidget(this);\n mpBtnWidget = new CQTaskBtnWidget(this);\n\n connect(mpBtnWidget->mpBtnRun, SIGNAL(clicked()), this, SLOT(runBtnClicked()));\n connect(mpBtnWidget->mpBtnRevert, SIGNAL(clicked()), this, SLOT(revertBtnClicked()));\n connect(mpBtnWidget->mpBtnReport, SIGNAL(clicked()), this, SLOT(reportBtnClicked()));\n connect(mpBtnWidget->mpBtnAssistant, SIGNAL(clicked()), this, SLOT(assistantBtnClicked()));\n\n connect(mpTaskThread, SIGNAL(finished()), this, SLOT(slotFinishThread()));\n}\n\nTaskWidget::~TaskWidget()\n{\n pdelete(mpTaskThread);\n}\n\nvoid TaskWidget::revertBtnClicked()\n{\n if (!mpTask) return;\n\n CCopasiMethod* pMethod = mpTask->getMethod();\n\n if (pMethod != mpMethod)\n {\n pdelete(mpMethod);\n mpMethod = pMethod;\n }\n\n loadTask();\n}\n\nvoid TaskWidget::runBtnClicked()\n{\n \/\/ Assure that all edits to the current widget are committed.\n mpBtnWidget->mpBtnRun->setFocus();\n\n runTask();\n}\n\nvoid TaskWidget::reportBtnClicked()\n{\n if (!mpTask) return;\n\n CQReportDefinitionSelect * pSelectDlg = new CQReportDefinitionSelect(mpListView);\n pSelectDlg->setReport(&mpTask->getReport());\n pSelectDlg->loadReportDefinitionVector();\n pSelectDlg->exec();\n\n delete pSelectDlg;\n}\n\nvoid TaskWidget::assistantBtnClicked()\n{\n if (!mpTask) return;\n\n saveTask(); \/\/this is necessary since the output may use information from the problem\n\n DefaultPlotDialog * pDlg = new DefaultPlotDialog(this);\n pDlg->setTask(mpTask);\n\n if (pDlg->exec() == QDialog::Accepted)\n {\n protectedNotify(ListViews::PLOT, ListViews::ADD, \"\");\n }\n\n if (pDlg)delete pDlg;\n}\n\n\/\/************ executable button *******************\n\nbool TaskWidget::loadCommon()\n{\n if (!mpTask) return false;\n\n mpHeaderWidget->mpBoxExecutable->setChecked(mpTask->isScheduled());\n mpHeaderWidget->mpUpdateModel->setChecked(mpTask->isUpdateModel());\n\n mpHeaderWidget->saved();\n return true;\n}\n\nbool TaskWidget::saveCommon()\n{\n if (!mpTask) return false;\n\n bool Value = mpHeaderWidget->mpBoxExecutable->isChecked();\n\n if (mpTask->isScheduled() != Value)\n {\n mpTask->setScheduled(Value);\n mChanged = true;\n }\n\n Value = mpHeaderWidget->mpUpdateModel->isChecked();\n\n if (mpTask->isUpdateModel() != Value)\n {\n mpTask->setUpdateModel(Value);\n mChanged = true;\n }\n\n mpHeaderWidget->saved();\n return true;\n}\n\n\/\/************* parameter table ***********************\n\nbool TaskWidget::loadMethod()\n{\n if (!mpTask) return false;\n\n mpMethodWidget->setTask(mpTask);\n\n return mpMethodWidget->loadMethod();\n}\n\nvoid TaskWidget::adjustTable()\n{\n#ifdef DEBUG_UI\n qDebug() << \"--> TaskWidget::adjustTable <--\";\n#endif\n\n \/\/ mpTblParameter->resizeColumnsToContents();\n \/\/ mpTblParameter->resizeRowsToContents();\n\n \/*\n mpTblParameter->setFixedSize(mpTblParameter->columnWidth(0) + mpTblParameter->verticalHeader()->sizeHint().width() + 5,\n mpTblParameter->verticalHeader()->sizeHint().height() * mpTblParameter->rowCount() + 5);\n *\/\n}\n\nbool TaskWidget::saveMethod()\n{\n if (!mpTask) return false;\n\n mChanged &= mpMethodWidget->saveMethod();\n\n return true;\n}\n\nbool TaskWidget::commonBeforeRunTask()\n{\n \/\/ save the state of the widget\n if (!saveTask())\n {\n CQMessageBox::critical(this, \"Simulation Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n return false;\n }\n\n if (!mpTask) return false;\n\n if (mProgressBar != NULL)\n {\n \/\/CQMessageBox::critical(this, \"Task in Progress\",\n \/\/ \"A task is currently running, another cannot be started before the current task ended.\",\n \/\/ QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n return false;\n }\n\n \/\/ if overwrite is enabled and the file exists, then ask\n if (!mpTask->getReport().getTarget().empty() &&\n mpTask->getReport().confirmOverwrite())\n {\n \/\/ The target might be a relative path\n std::string Target = mpTask->getReport().getTarget();\n\n if (CDirEntry::isRelativePath(Target) &&\n !CDirEntry::makePathAbsolute(Target, mpDataModel->getReferenceDirectory()))\n Target = CDirEntry::fileName(Target);\n\n if (CDirEntry::exist(Target) &&\n QMessageBox::question(this,\n QString(\"Confirm Overwrite\"),\n QString(\"The report file already exists. Would you like to overwrite it? \\n\\n(You can disable this dialog by clicking the 'Report' button.)\"),\n QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)\n return false;\n }\n\n \/\/set mouse cursor\n setCursor(Qt::WaitCursor);\n\n \/\/handle autosave feature\n CopasiUI3Window::getMainWindow()->autoSave();\n CopasiUI3Window::getMainWindow()->suspendAutoSave(true);\n\n \/\/create progress bar\n mProgressBar = CProgressBar::create();\n mpTask->setCallBack(mProgressBar);\n\n CCopasiMessage::clearDeque();\n return true;\n}\n\nbool TaskWidget::commonAfterRunTask()\n{\n if (!mpTask) return false;\n\n if (mProgressBar != NULL)\n {\n mProgressBar->finish();\n mProgressBar->deleteLater();\n mProgressBar = NULL;\n }\n\n mpTask->setCallBack(NULL);\n\n CCopasiMessage::clearDeque();\n\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n CCopasiRootContainer::getDatamodelList()->operator[](0).finish();\n\n \/\/ Update all values shown in the GUI\n CMathContainer * pContainer = mpTask->getMathContainer();\n\n pContainer->updateSimulatedValues(false);\n pContainer->updateTransientDataValues();\n pContainer->pushAllTransientValues();\n\n protectedNotify(ListViews::STATE, ListViews::CHANGE, pContainer->getModel().getKey());\n\n unsetCursor();\n CopasiUI3Window::getMainWindow()->suspendAutoSave(false);\n\n return loadTask();\n}\n\nbool TaskWidget::commonRunTask()\n{\n \/\/ Initialize the task\n try\n {\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n\n if (!mpTask->initialize(CCopasiTask::OUTPUT_UI, &CCopasiRootContainer::getDatamodelList()->operator[](0), NULL))\n throw CCopasiException(CCopasiMessage::peekLastMessage());\n }\n\n catch (CCopasiException & \/*Exception*\/)\n {\n if (CCopasiMessage::peekLastMessage().getNumber() != MCCopasiMessage + 1)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Initialization Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n\n finishTask();\n return false;\n }\n }\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::ERROR)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Initialization Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n\n finishTask();\n return false;\n }\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n C_INT Result =\n CQMessageBox::question(this, \"Initialization Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ignore | QMessageBox::Abort, QMessageBox::Ignore);\n\n if (Result == QMessageBox::Abort)\n {\n finishTask();\n return false;\n }\n }\n\n CCopasiMessage::clearDeque();\n\n \/\/ Execute the task\n mpTaskThread->start();\n\n return true;\n}\n\nvoid TaskWidget::slotFinishThread()\n{\n if (!mpTaskThread->success() &&\n CCopasiMessage::size() != 0)\n {\n CQMessageBox::critical(this, \"Calculation Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n else if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n CQMessageBox::information(this, \"Calculation Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n\n finishTask();\n}\n\nvoid TaskWidget::finishTask()\n{\n CCopasiMessage::clearDeque();\n\n try {mpTask->restore();}\n\n catch (CCopasiException & \/*Exception*\/)\n {\n if (CCopasiMessage::peekLastMessage().getNumber() != MCCopasiMessage + 1)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Calculation Error\", CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n CCopasiMessage::clearDeque();\n }\n }\n\n catch (...) {}\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n CQMessageBox::information(this, \"Calculation Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n\n CCopasiMessage::clearDeque();\n\n commonAfterRunTask();\n\n taskFinishedEvent();\n}\n\nbool TaskWidget::taskFinishedEvent()\n{\n return true;\n}\n\nCCopasiTask* TaskWidget::getTask()\n{\n return mpTask;\n}\n\/\/*********************************************************************\n\nbool TaskWidget::update(ListViews::ObjectType objectType, ListViews::Action action, const std::string & C_UNUSED(key))\n{\n if (mIgnoreUpdates || !isVisible())\n {\n return true;\n }\n\n switch (objectType)\n {\n case ListViews::MODEL:\n\n if (action == ListViews::ADD &&\n mpMethodWidget != NULL)\n {\n mpMethodWidget->clearHistory();\n }\n\n break;\n\n default:\n break;\n }\n\n return true;\n}\n\nbool TaskWidget::leave()\n{\n return saveTask();\n}\n\nbool TaskWidget::enterProtected()\n{\n mpTask = dynamic_cast< CCopasiTask * >(mpObject);\n\n \/\/ :TODO: We need a message here.\n if (!mpTask) return false;\n\n mpMethod = mpTask->getMethod();\n\n return loadTask();\n}\n\nCCopasiMethod * TaskWidget::createMethod(const CTaskEnum::Method & type)\n{\n CCopasiMethod * pMethod = NULL;\n\n if (mpTask != NULL)\n {\n pMethod = mpTask->createMethod(type);\n }\n\n return pMethod;\n}\n<commit_msg>Bug 2495: The method history is cleared when a new model is loaded.<commit_after>\/\/ Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <QtCore\/QtDebug>\n#include <QtGui\/QFrame>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QApplication>\n\n#include \"TaskWidget.h\"\n#include \"qtUtilities.h\"\n\n#include \"listviews.h\"\n#include \"DataModelGUI.h\"\n#include \"CQMessageBox.h\"\n#include \"MyLineEdit.h\"\n#include \"CProgressBar.h\"\n#include \"copasiui3window.h\"\n#include \"CQReportDefinitionSelect.h\"\n#include \"DefaultplotDialog.h\"\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskMethodWidget.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"utilities\/CCopasiMethod.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"utilities\/COutputHandler.h\"\n#include \"utilities\/CDirEntry.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n#include \"model\/CModel.h\"\n#include \"math\/CMathContainer.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"UI\/CQTaskThread.h\"\n#include \"plotUI\/CopasiPlot.h\"\n#include \"plotUI\/plotwindow.h\"\n\n\/*\n * Constructs a TaskWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nTaskWidget::TaskWidget(QWidget* parent, const char* name, Qt::WFlags fl):\n CopasiWidget(parent, name, fl),\n mProgressBar(NULL),\n mpHeaderWidget(NULL),\n mpMethodWidget(NULL),\n mpBtnWidget(NULL),\n mpMethodLayout(NULL),\n mpSpacer1(NULL),\n mpSpacer2(NULL),\n mpTask(NULL),\n mpMethod(NULL),\n mChanged(false)\n{\n if (!name)\n setObjectName(\"TaskWidget\");\n\n setWindowTitle(trUtf8(\"TaskWidget\"));\n\n mpTaskThread = new CQTaskThread(this);\n\n mpHeaderWidget = new CQTaskHeaderWidget(this);\n mpMethodWidget = new CQTaskMethodWidget(this);\n mpBtnWidget = new CQTaskBtnWidget(this);\n\n connect(mpBtnWidget->mpBtnRun, SIGNAL(clicked()), this, SLOT(runBtnClicked()));\n connect(mpBtnWidget->mpBtnRevert, SIGNAL(clicked()), this, SLOT(revertBtnClicked()));\n connect(mpBtnWidget->mpBtnReport, SIGNAL(clicked()), this, SLOT(reportBtnClicked()));\n connect(mpBtnWidget->mpBtnAssistant, SIGNAL(clicked()), this, SLOT(assistantBtnClicked()));\n\n connect(mpTaskThread, SIGNAL(finished()), this, SLOT(slotFinishThread()));\n}\n\nTaskWidget::~TaskWidget()\n{\n pdelete(mpTaskThread);\n}\n\nvoid TaskWidget::revertBtnClicked()\n{\n if (!mpTask) return;\n\n CCopasiMethod* pMethod = mpTask->getMethod();\n\n if (pMethod != mpMethod)\n {\n pdelete(mpMethod);\n mpMethod = pMethod;\n }\n\n loadTask();\n}\n\nvoid TaskWidget::runBtnClicked()\n{\n \/\/ Assure that all edits to the current widget are committed.\n mpBtnWidget->mpBtnRun->setFocus();\n\n runTask();\n}\n\nvoid TaskWidget::reportBtnClicked()\n{\n if (!mpTask) return;\n\n CQReportDefinitionSelect * pSelectDlg = new CQReportDefinitionSelect(mpListView);\n pSelectDlg->setReport(&mpTask->getReport());\n pSelectDlg->loadReportDefinitionVector();\n pSelectDlg->exec();\n\n delete pSelectDlg;\n}\n\nvoid TaskWidget::assistantBtnClicked()\n{\n if (!mpTask) return;\n\n saveTask(); \/\/this is necessary since the output may use information from the problem\n\n DefaultPlotDialog * pDlg = new DefaultPlotDialog(this);\n pDlg->setTask(mpTask);\n\n if (pDlg->exec() == QDialog::Accepted)\n {\n protectedNotify(ListViews::PLOT, ListViews::ADD, \"\");\n }\n\n if (pDlg)delete pDlg;\n}\n\n\/\/************ executable button *******************\n\nbool TaskWidget::loadCommon()\n{\n if (!mpTask) return false;\n\n mpHeaderWidget->mpBoxExecutable->setChecked(mpTask->isScheduled());\n mpHeaderWidget->mpUpdateModel->setChecked(mpTask->isUpdateModel());\n\n mpHeaderWidget->saved();\n return true;\n}\n\nbool TaskWidget::saveCommon()\n{\n if (!mpTask) return false;\n\n bool Value = mpHeaderWidget->mpBoxExecutable->isChecked();\n\n if (mpTask->isScheduled() != Value)\n {\n mpTask->setScheduled(Value);\n mChanged = true;\n }\n\n Value = mpHeaderWidget->mpUpdateModel->isChecked();\n\n if (mpTask->isUpdateModel() != Value)\n {\n mpTask->setUpdateModel(Value);\n mChanged = true;\n }\n\n mpHeaderWidget->saved();\n return true;\n}\n\n\/\/************* parameter table ***********************\n\nbool TaskWidget::loadMethod()\n{\n if (!mpTask) return false;\n\n mpMethodWidget->setTask(mpTask);\n\n return mpMethodWidget->loadMethod();\n}\n\nvoid TaskWidget::adjustTable()\n{\n#ifdef DEBUG_UI\n qDebug() << \"--> TaskWidget::adjustTable <--\";\n#endif\n\n \/\/ mpTblParameter->resizeColumnsToContents();\n \/\/ mpTblParameter->resizeRowsToContents();\n\n \/*\n mpTblParameter->setFixedSize(mpTblParameter->columnWidth(0) + mpTblParameter->verticalHeader()->sizeHint().width() + 5,\n mpTblParameter->verticalHeader()->sizeHint().height() * mpTblParameter->rowCount() + 5);\n *\/\n}\n\nbool TaskWidget::saveMethod()\n{\n if (!mpTask) return false;\n\n mChanged &= mpMethodWidget->saveMethod();\n\n return true;\n}\n\nbool TaskWidget::commonBeforeRunTask()\n{\n \/\/ save the state of the widget\n if (!saveTask())\n {\n CQMessageBox::critical(this, \"Simulation Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n return false;\n }\n\n if (!mpTask) return false;\n\n if (mProgressBar != NULL)\n {\n \/\/CQMessageBox::critical(this, \"Task in Progress\",\n \/\/ \"A task is currently running, another cannot be started before the current task ended.\",\n \/\/ QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n return false;\n }\n\n \/\/ if overwrite is enabled and the file exists, then ask\n if (!mpTask->getReport().getTarget().empty() &&\n mpTask->getReport().confirmOverwrite())\n {\n \/\/ The target might be a relative path\n std::string Target = mpTask->getReport().getTarget();\n\n if (CDirEntry::isRelativePath(Target) &&\n !CDirEntry::makePathAbsolute(Target, mpDataModel->getReferenceDirectory()))\n Target = CDirEntry::fileName(Target);\n\n if (CDirEntry::exist(Target) &&\n QMessageBox::question(this,\n QString(\"Confirm Overwrite\"),\n QString(\"The report file already exists. Would you like to overwrite it? \\n\\n(You can disable this dialog by clicking the 'Report' button.)\"),\n QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)\n return false;\n }\n\n \/\/set mouse cursor\n setCursor(Qt::WaitCursor);\n\n \/\/handle autosave feature\n CopasiUI3Window::getMainWindow()->autoSave();\n CopasiUI3Window::getMainWindow()->suspendAutoSave(true);\n\n \/\/create progress bar\n mProgressBar = CProgressBar::create();\n mpTask->setCallBack(mProgressBar);\n\n CCopasiMessage::clearDeque();\n return true;\n}\n\nbool TaskWidget::commonAfterRunTask()\n{\n if (!mpTask) return false;\n\n if (mProgressBar != NULL)\n {\n mProgressBar->finish();\n mProgressBar->deleteLater();\n mProgressBar = NULL;\n }\n\n mpTask->setCallBack(NULL);\n\n CCopasiMessage::clearDeque();\n\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n CCopasiRootContainer::getDatamodelList()->operator[](0).finish();\n\n \/\/ Update all values shown in the GUI\n CMathContainer * pContainer = mpTask->getMathContainer();\n\n pContainer->updateSimulatedValues(false);\n pContainer->updateTransientDataValues();\n pContainer->pushAllTransientValues();\n\n protectedNotify(ListViews::STATE, ListViews::CHANGE, pContainer->getModel().getKey());\n\n unsetCursor();\n CopasiUI3Window::getMainWindow()->suspendAutoSave(false);\n\n return loadTask();\n}\n\nbool TaskWidget::commonRunTask()\n{\n \/\/ Initialize the task\n try\n {\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n\n if (!mpTask->initialize(CCopasiTask::OUTPUT_UI, &CCopasiRootContainer::getDatamodelList()->operator[](0), NULL))\n throw CCopasiException(CCopasiMessage::peekLastMessage());\n }\n\n catch (CCopasiException & \/*Exception*\/)\n {\n if (CCopasiMessage::peekLastMessage().getNumber() != MCCopasiMessage + 1)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Initialization Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n\n finishTask();\n return false;\n }\n }\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::ERROR)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Initialization Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n\n finishTask();\n return false;\n }\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n C_INT Result =\n CQMessageBox::question(this, \"Initialization Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ignore | QMessageBox::Abort, QMessageBox::Ignore);\n\n if (Result == QMessageBox::Abort)\n {\n finishTask();\n return false;\n }\n }\n\n CCopasiMessage::clearDeque();\n\n \/\/ Execute the task\n mpTaskThread->start();\n\n return true;\n}\n\nvoid TaskWidget::slotFinishThread()\n{\n if (!mpTaskThread->success() &&\n CCopasiMessage::size() != 0)\n {\n CQMessageBox::critical(this, \"Calculation Error\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n else if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n CQMessageBox::information(this, \"Calculation Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n\n finishTask();\n}\n\nvoid TaskWidget::finishTask()\n{\n CCopasiMessage::clearDeque();\n\n try {mpTask->restore();}\n\n catch (CCopasiException & \/*Exception*\/)\n {\n if (CCopasiMessage::peekLastMessage().getNumber() != MCCopasiMessage + 1)\n {\n if (mProgressBar != NULL) mProgressBar->finish();\n\n CQMessageBox::critical(this, \"Calculation Error\", CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n CCopasiMessage::clearDeque();\n }\n }\n\n catch (...) {}\n\n if (CCopasiMessage::getHighestSeverity() > CCopasiMessage::COMMANDLINE)\n {\n CQMessageBox::information(this, \"Calculation Warning\",\n CCopasiMessage::getAllMessageText().c_str(),\n QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);\n }\n\n CCopasiMessage::clearDeque();\n\n commonAfterRunTask();\n\n taskFinishedEvent();\n}\n\nbool TaskWidget::taskFinishedEvent()\n{\n return true;\n}\n\nCCopasiTask* TaskWidget::getTask()\n{\n return mpTask;\n}\n\/\/*********************************************************************\n\nbool TaskWidget::update(ListViews::ObjectType objectType, ListViews::Action action, const std::string & C_UNUSED(key))\n{\n if (mIgnoreUpdates)\n {\n return true;\n }\n\n switch (objectType)\n {\n case ListViews::MODEL:\n\n if (action == ListViews::ADD &&\n mpMethodWidget != NULL)\n {\n mpMethodWidget->clearHistory();\n }\n\n break;\n\n default:\n break;\n }\n\n return true;\n}\n\nbool TaskWidget::leave()\n{\n return saveTask();\n}\n\nbool TaskWidget::enterProtected()\n{\n mpTask = dynamic_cast< CCopasiTask * >(mpObject);\n\n \/\/ :TODO: We need a message here.\n if (!mpTask) return false;\n\n mpMethod = mpTask->getMethod();\n\n return loadTask();\n}\n\nCCopasiMethod * TaskWidget::createMethod(const CTaskEnum::Method & type)\n{\n CCopasiMethod * pMethod = NULL;\n\n if (mpTask != NULL)\n {\n pMethod = mpTask->createMethod(type);\n }\n\n return pMethod;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KXForms.\n\n Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \"guihandlerdialogs.h\"\n\n#include \"manager.h\"\n\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QLabel>\n#include <QVBoxLayout>\n#include <QFrame>\n\nusing namespace KXForms;\n\nFormDialog::FormDialog( QWidget *parent, const QString &title, Manager *m )\n : KDialog( parent, title, Ok ),\n mFormGui( 0 ), mManager( m )\n{\n QFrame *topFrame = new QFrame( this );\n setMainWidget( topFrame );\n mTopLayout = new QVBoxLayout( topFrame );\n\n connect( this, SIGNAL( okClicked() ), SLOT( slotOk() ) );\n}\n\nvoid FormDialog::setGui( FormGui *gui )\n{\n mTopLayout->addWidget( gui );\n mFormGui = gui;\n}\n\nvoid FormDialog::slotOk()\n{\n kDebug() << \"FormDialog::slotOk()\" << endl;\n\n mFormGui->saveData();\n \n mManager->unregisterGui( mFormGui );\n \n accept();\n}\n\n\nGuiHandlerDialogs::GuiHandlerDialogs( Manager *m )\n : GuiHandler( m )\n{\n}\n\nQWidget *GuiHandlerDialogs::createRootGui( QWidget *parent )\n{\n kDebug() << \"GuiHandlerDialogs::createRootGui()\" << endl;\n\n Form *f = manager()->rootForm();\n\n if ( !f ) {\n KMessageBox::sorry( parent, i18n(\"Root form not found.\") );\n return 0;\n }\n\n FormGui *gui = createGui( f, parent );\n\n gui->setRef( \"\/\" + f->ref() );\n gui->parseElement( f->element() );\n\n if ( manager()->hasData() ) {\n kDebug() << \"Manager::createGui() Load data on creation\" << endl;\n manager()->loadData( gui );\n }\n\n return gui;\n}\n\nvoid GuiHandlerDialogs::createGui( const Reference &ref, QWidget *parent )\n{\n kDebug() << \"GuiHandlerDialogs::createGui() ref: '\" << ref.toString() << \"'\" << endl;\n\n if ( ref.isEmpty() ) {\n KMessageBox::sorry( parent, i18n(\"No reference.\") );\n return;\n }\n\n QString r = ref.segments().last().name();\n\n Form *f = manager()->form( r );\n\n if ( !f ) {\n KMessageBox::sorry( parent, i18n(\"Form '%1' not found.\", ref.toString() ) );\n return;\n }\n\n FormDialog dlg( parent, i18n(\"Edit %1\", ref.toString() ), manager() );\n\n FormGui *gui = createGui( f, dlg.mainWidget() );\n gui->setRef( ref );\n gui->parseElement( f->element() );\n\n if ( !gui ) {\n KMessageBox::sorry( parent, i18n(\"Unable to create GUI for '%1'.\",\n ref.toString() ) );\n return;\n }\n\n dlg.setGui( gui );\n\n if ( manager()->hasData() ) {\n kDebug() << \"Manager::createGui() Load data on creation\" << endl;\n manager()->loadData( gui );\n }\n\n dlg.exec();\n}\n\nFormGui *GuiHandlerDialogs::createGui( Form *form, QWidget *parent )\n{\n kDebug() << \"Manager::createGui() form: '\" << form->ref() << \"'\" << endl;\n\n if ( !form ) {\n kError() << \"KXForms::Manager::createGui(): form is null.\" << endl;\n return 0;\n }\n\n FormGui *gui = new FormGui( form->label(), manager(), parent );\n if ( gui ) manager()->registerGui( gui );\n\n return gui;\n}\n\n#include \"guihandlerdialogs.moc\"\n<commit_msg>fix crash (CID 1514)<commit_after>\/*\n This file is part of KXForms.\n\n Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\n#include \"guihandlerdialogs.h\"\n\n#include \"manager.h\"\n\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QLabel>\n#include <QVBoxLayout>\n#include <QFrame>\n\nusing namespace KXForms;\n\nFormDialog::FormDialog( QWidget *parent, const QString &title, Manager *m )\n : KDialog( parent, title, Ok ),\n mFormGui( 0 ), mManager( m )\n{\n QFrame *topFrame = new QFrame( this );\n setMainWidget( topFrame );\n mTopLayout = new QVBoxLayout( topFrame );\n\n connect( this, SIGNAL( okClicked() ), SLOT( slotOk() ) );\n}\n\nvoid FormDialog::setGui( FormGui *gui )\n{\n mTopLayout->addWidget( gui );\n mFormGui = gui;\n}\n\nvoid FormDialog::slotOk()\n{\n kDebug() << \"FormDialog::slotOk()\" << endl;\n\n mFormGui->saveData();\n \n mManager->unregisterGui( mFormGui );\n \n accept();\n}\n\n\nGuiHandlerDialogs::GuiHandlerDialogs( Manager *m )\n : GuiHandler( m )\n{\n}\n\nQWidget *GuiHandlerDialogs::createRootGui( QWidget *parent )\n{\n kDebug() << \"GuiHandlerDialogs::createRootGui()\" << endl;\n\n Form *f = manager()->rootForm();\n\n if ( !f ) {\n KMessageBox::sorry( parent, i18n(\"Root form not found.\") );\n return 0;\n }\n\n FormGui *gui = createGui( f, parent );\n\n gui->setRef( \"\/\" + f->ref() );\n gui->parseElement( f->element() );\n\n if ( manager()->hasData() ) {\n kDebug() << \"Manager::createGui() Load data on creation\" << endl;\n manager()->loadData( gui );\n }\n\n return gui;\n}\n\nvoid GuiHandlerDialogs::createGui( const Reference &ref, QWidget *parent )\n{\n kDebug() << \"GuiHandlerDialogs::createGui() ref: '\" << ref.toString() << \"'\" << endl;\n\n if ( ref.isEmpty() ) {\n KMessageBox::sorry( parent, i18n(\"No reference.\") );\n return;\n }\n\n QString r = ref.segments().last().name();\n\n Form *f = manager()->form( r );\n\n if ( !f ) {\n KMessageBox::sorry( parent, i18n(\"Form '%1' not found.\", ref.toString() ) );\n return;\n }\n\n FormDialog dlg( parent, i18n(\"Edit %1\", ref.toString() ), manager() );\n\n FormGui *gui = createGui( f, dlg.mainWidget() );\n if ( !gui ) {\n KMessageBox::sorry( parent, i18n(\"Unable to create GUI for '%1'.\",\n ref.toString() ) );\n return;\n }\n\n gui->setRef( ref );\n gui->parseElement( f->element() );\n\n dlg.setGui( gui );\n\n if ( manager()->hasData() ) {\n kDebug() << \"Manager::createGui() Load data on creation\" << endl;\n manager()->loadData( gui );\n }\n\n dlg.exec();\n}\n\nFormGui *GuiHandlerDialogs::createGui( Form *form, QWidget *parent )\n{\n kDebug() << \"Manager::createGui() form: '\" << form->ref() << \"'\" << endl;\n\n if ( !form ) {\n kError() << \"KXForms::Manager::createGui(): form is null.\" << endl;\n return 0;\n }\n\n FormGui *gui = new FormGui( form->label(), manager(), parent );\n if ( gui ) manager()->registerGui( gui );\n\n return gui;\n}\n\n#include \"guihandlerdialogs.moc\"\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/result_wrapper.hpp\"\n#include \"..\/tags\/Logic.hpp\"\n\n#include <cuddObj.hh>\n\nnamespace metaSMT {\n namespace solver {\n #ifndef _CPPCUDD\n typedef std::vector<BDD> BDDvector;\n #endif\n\n namespace predtags = ::metaSMT::logic::tag;\n \n class CUDD_Context\n {\n struct CUDDAssertion : public std::runtime_error {\n CUDDAssertion(const char* what) \n : std::runtime_error(what) {}\n };\n\n static void _cudd_error(std::string what) {\n throw CUDDAssertion(what.c_str());\n }\n\n public:\n\n CUDD_Context () \n {\n _manager.setHandler(&CUDD_Context::_cudd_error);\n _manager.AutodynEnable(CUDD_REORDER_SIFT);\n _assertions = _manager.bddOne();\n _assumptions = _manager.bddOne();\n }\n\n typedef BDD result_type;\n \n void assertion( result_type e ) { \n _assertions &= e;\n }\n\n void assumption( result_type e ) { \n _assumptions &= e;\n }\n \n void writeDotFile(std::string const & filename) \n {\n#ifdef _CPPCUDD\n BDDvector bvec (3, &_manager, NULL);\n bvec[0] = _assertions & _assumptions;\n bvec[1] = _assertions;\n bvec[2] = _assumptions;\n#else\n BDDvector bvec;\n bvec.push_back(_assertions & _assumptions);\n bvec.push_back(_assertions);\n bvec.push_back(_assumptions);\n#endif\n char comple[] = \"complete\";\n char assert[] = \"assertions\";\n char assume[] = \"assumptions\";\n char *names[]={ comple, assert, assume };\n FILE* fp = fopen(filename.c_str(), \"w\");\n#ifdef _CPPCUDD\n bvec.DumpDot(0, names, fp);\n#else\n _manager.DumpDot(bvec, 0, names, fp);\n#endif\n fclose(fp);\n }\n \n bool solve() {\n _solution.clear();\n BDD complete =_assertions & _assumptions;\n bool ret = complete != _manager.bddZero();\n _assumptions = _manager.bddOne();\n if(ret) {\n unsigned size = _manager.ReadSize();\n char *buf = new char[size];\n complete.PickOneCube(buf);\n _solution.resize(size);\n for (unsigned i = 0; i < size; ++i) {\n if( buf[i] == 2) {\n _solution[i] = boost::logic::indeterminate;\n } else {\n _solution[i] = buf[i];\n }\n }\n delete[] buf;\n }\n return ret;\n }\n\n result_wrapper read_value(result_type var)\n { \n assert( var.NodeReadIndex() < _solution.size() );\n return result_wrapper( _solution[var.NodeReadIndex()] ); \n }\n\n result_type operator() (predtags::var_tag const & , boost::any )\n {\n return _manager.bddVar();\n }\n\n result_type operator() (predtags::false_tag , boost::any ) {\n return _manager.bddZero();\n }\n\n result_type operator() (predtags::true_tag , boost::any ) {\n return _manager.bddOne();\n }\n\n result_type operator() (predtags::not_tag , result_type a) {\n return !a ;\n }\n\n\n result_type operator() (predtags::equal_tag , result_type a, result_type b) {\n return !(a ^ b);\n }\n\n result_type operator() (predtags::nequal_tag , result_type a, result_type b) {\n return a ^ b;\n }\n\n result_type operator() (predtags::and_tag , result_type a, result_type b) {\n return a & b;\n }\n \n result_type operator() (predtags::nand_tag , result_type a, result_type b) {\n return !(a & b);\n }\n \n result_type operator() (predtags::xor_tag , result_type a, result_type b) {\n return a ^ b;\n }\n \n result_type operator() (predtags::xnor_tag , result_type a, result_type b) {\n return !(a ^ b);\n }\n \n result_type operator() (predtags::implies_tag , result_type a, result_type b) {\n return !a | b;\n }\n\n result_type operator() (predtags::or_tag , result_type a, result_type b) {\n return a | b;\n }\n \n result_type operator() (predtags::nor_tag , result_type a, result_type b) {\n return !(a | b);\n }\n\n result_type operator() (predtags::distinct_tag , result_type a, result_type b) {\n return a ^ b;\n }\n\n\n result_type operator() (predtags::ite_tag \n , result_type a, result_type b, result_type c\n ) {\n return a.Ite(b,c);\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Fallback operators \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template <typename TagT>\n result_type operator() (TagT , boost::any ) {\n assert(false && \"fallback op0 called\");\n return _manager.bddZero();\n }\n\n template <typename TagT>\n result_type operator() (TagT , result_type ) {\n assert(false && \"fallback op1 called\");\n return _manager.bddZero();\n }\n\n template <typename TagT, typename T1, typename T2>\n result_type operator() (TagT , T1 , T2 ) {\n assert(false && \"fallback op2 called\");\n return _manager.bddZero();\n }\n\n\n template <typename TagT, typename T1, typename T2, typename T3>\n result_type operator() (TagT , T1 , T2 , T3 ) {\n assert(false && \"fallback op3 called\");\n return _manager.bddZero();\n }\n\n \/* pseudo command *\/\n void command ( CUDD_Context const & ) { };\n\n\n protected:\n Cudd _manager;\n BDD _assertions;\n BDD _assumptions;\n std::vector< boost::logic::tribool> _solution;\n };\n\t\n } \/\/ namespace solver\n} \/\/ namespace metaSMT\n\n\/\/ vim: ft=cpp:ts=2:sw=2:expandtab\n<commit_msg>small improvement CUDD_Context::writeDotFile<commit_after>#pragma once\n\n#include \"..\/result_wrapper.hpp\"\n#include \"..\/tags\/Logic.hpp\"\n\n#include <cuddObj.hh>\n\nnamespace metaSMT {\n namespace solver {\n namespace predtags = ::metaSMT::logic::tag;\n \n class CUDD_Context\n {\n struct CUDDAssertion : public std::runtime_error {\n CUDDAssertion(const char* what) \n : std::runtime_error(what) {}\n };\n\n static void _cudd_error(std::string what) {\n throw CUDDAssertion(what.c_str());\n }\n\n public:\n\n CUDD_Context () \n {\n _manager.setHandler(&CUDD_Context::_cudd_error);\n _manager.AutodynEnable(CUDD_REORDER_SIFT);\n _assertions = _manager.bddOne();\n _assumptions = _manager.bddOne();\n }\n\n typedef BDD result_type;\n \n void assertion( result_type e ) { \n _assertions &= e;\n }\n\n void assumption( result_type e ) { \n _assumptions &= e;\n }\n \n void writeDotFile(std::string const & filename) \n {\n#ifdef _CPPCUDD \/\/ this is defined in CUDD 2.4.x but not in 3.0.0\n BDDvector bvec (3, &_manager, NULL);\n#else\n std::vector<BDD> bvec (3, _manager.bddOne());\n#endif\n bvec[0] = _assertions & _assumptions;\n bvec[1] = _assertions;\n bvec[2] = _assumptions;\n char comple[] = \"complete\";\n char assert[] = \"assertions\";\n char assume[] = \"assumptions\";\n char *names[]={ comple, assert, assume };\n FILE* fp = fopen(filename.c_str(), \"w\");\n#ifdef _CPPCUDD\n bvec.DumpDot(0, names, fp);\n#else\n _manager.DumpDot(bvec, 0, names, fp);\n#endif\n fclose(fp);\n }\n \n bool solve() {\n _solution.clear();\n BDD complete =_assertions & _assumptions;\n bool ret = complete != _manager.bddZero();\n _assumptions = _manager.bddOne();\n if(ret) {\n unsigned size = _manager.ReadSize();\n char *buf = new char[size];\n complete.PickOneCube(buf);\n _solution.resize(size);\n for (unsigned i = 0; i < size; ++i) {\n if( buf[i] == 2) {\n _solution[i] = boost::logic::indeterminate;\n } else {\n _solution[i] = buf[i];\n }\n }\n delete[] buf;\n }\n return ret;\n }\n\n result_wrapper read_value(result_type var)\n { \n assert( var.NodeReadIndex() < _solution.size() );\n return result_wrapper( _solution[var.NodeReadIndex()] ); \n }\n\n result_type operator() (predtags::var_tag const & , boost::any )\n {\n return _manager.bddVar();\n }\n\n result_type operator() (predtags::false_tag , boost::any ) {\n return _manager.bddZero();\n }\n\n result_type operator() (predtags::true_tag , boost::any ) {\n return _manager.bddOne();\n }\n\n result_type operator() (predtags::not_tag , result_type a) {\n return !a ;\n }\n\n\n result_type operator() (predtags::equal_tag , result_type a, result_type b) {\n return !(a ^ b);\n }\n\n result_type operator() (predtags::nequal_tag , result_type a, result_type b) {\n return a ^ b;\n }\n\n result_type operator() (predtags::and_tag , result_type a, result_type b) {\n return a & b;\n }\n \n result_type operator() (predtags::nand_tag , result_type a, result_type b) {\n return !(a & b);\n }\n \n result_type operator() (predtags::xor_tag , result_type a, result_type b) {\n return a ^ b;\n }\n \n result_type operator() (predtags::xnor_tag , result_type a, result_type b) {\n return !(a ^ b);\n }\n \n result_type operator() (predtags::implies_tag , result_type a, result_type b) {\n return !a | b;\n }\n\n result_type operator() (predtags::or_tag , result_type a, result_type b) {\n return a | b;\n }\n \n result_type operator() (predtags::nor_tag , result_type a, result_type b) {\n return !(a | b);\n }\n\n result_type operator() (predtags::distinct_tag , result_type a, result_type b) {\n return a ^ b;\n }\n\n\n result_type operator() (predtags::ite_tag \n , result_type a, result_type b, result_type c\n ) {\n return a.Ite(b,c);\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Fallback operators \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n template <typename TagT>\n result_type operator() (TagT , boost::any ) {\n assert(false && \"fallback op0 called\");\n return _manager.bddZero();\n }\n\n template <typename TagT>\n result_type operator() (TagT , result_type ) {\n assert(false && \"fallback op1 called\");\n return _manager.bddZero();\n }\n\n template <typename TagT, typename T1, typename T2>\n result_type operator() (TagT , T1 , T2 ) {\n assert(false && \"fallback op2 called\");\n return _manager.bddZero();\n }\n\n\n template <typename TagT, typename T1, typename T2, typename T3>\n result_type operator() (TagT , T1 , T2 , T3 ) {\n assert(false && \"fallback op3 called\");\n return _manager.bddZero();\n }\n\n \/* pseudo command *\/\n void command ( CUDD_Context const & ) { };\n\n\n protected:\n Cudd _manager;\n BDD _assertions;\n BDD _assumptions;\n std::vector< boost::logic::tribool> _solution;\n };\n\t\n } \/\/ namespace solver\n} \/\/ namespace metaSMT\n\n\/\/ vim: ft=cpp:ts=2:sw=2:expandtab\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2010 Jukka Jylnki\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License. *\/\r\n\r\n\/** @file FileTransfer.cpp\r\n\t@brief Implements a file transfer application. The server acts as a receiver waiting for a\r\n\t client to connect and send a file. *\/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <string.h>\r\n#include <utility>\r\n\r\n#include \"kNet.h\"\r\n#include \"kNet\/DebugMemoryLeakCheck.h\"\r\n\r\n\/\/ If enabled, this sample is used for network transfer profiling and all disk operations are ignored.\r\n\/\/#define NULLTRANSFER\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\nconst unsigned long cFileTransferStartMessage = 30;\r\nconst unsigned long cFileTransferFragment = 31;\r\n\r\n#ifdef LINUX\r\n#define _stricmp strcasecmp\r\n#endif\r\n\r\nstruct Fragment\r\n{\r\n\tstd::vector<char> data;\r\n\tsize_t fragmentIndex;\r\n};\r\n\r\nclass NetworkApp : public IMessageHandler, public INetworkServerListener\r\n{\r\n\tNetwork network;\r\n\r\n\t\/\/ Used by the receiver to store partial received data.\r\n\tstd::map<size_t, Fragment> fragments;\r\n\r\n\tsize_t nextFragment;\r\n\tsize_t totalFragments;\r\n\tsize_t bytesReceived;\r\n\tstd::ofstream out;\r\n\ttick_t transferStartTick;\r\n\r\n\tPolledTimer statsPrintTimer;\r\n\tstatic const int printIntervalMSecs = 4000;\r\npublic:\r\n\r\n\t\/\/\/ Called to notify the listener that a new connection has been established.\r\n\tvoid NewConnectionEstablished(MessageConnection *connection)\r\n\t{\r\n\t\tconnection->RegisterInboundMessageHandler(this);\r\n\t}\r\n\r\n\tvoid HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes)\r\n\t{\r\n\t\tswitch(id)\r\n\t\t{\r\n\t\tcase cFileTransferStartMessage:\r\n\t\t{\r\n\t\t\tDataDeserializer dd(data, numBytes);\r\n\t\t\tstd::string filename = dd.ReadString();\r\n\t\t\tsize_t fileSize = dd.Read<u32>();\r\n\t\t\ttotalFragments = dd.Read<u32>();\r\n\t\t\tnextFragment = 0;\r\n\t\t\tbytesReceived = 0;\r\n\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\tcout << \"Starting receive of file \\\"\" << filename << \"\\\". File size: \" << fileSize << \"B, which is split into \"\r\n\t\t\t\t<< totalFragments << \" fragments.\" << endl;\r\n\t\t\tchar str[256];\r\n\t\t\tsprintf(str, \"received_%s\", filename.c_str());\r\n\t\t\tout.open(str, ios::binary | ios::trunc);\r\n\t\t\ttransferStartTick = Clock::Tick();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase cFileTransferFragment:\r\n\t\t{\r\n\t\t\tDataDeserializer dd(data, numBytes);\r\n\t\t\tsize_t fragmentIndex = dd.Read<u32>();\r\n\t\t\tif (nextFragment == fragmentIndex)\r\n\t\t\t{\r\n\t\t\t\t++nextFragment;\r\n\t\t\t\tsize_t numDataBytes = dd.BytesLeft();\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tout.write(data + dd.BytePos(), numDataBytes);\r\n#endif\r\n\t\t\t\tbytesReceived += numDataBytes;\r\n\t\t\t\tWriteFinishedFragments();\r\n\r\n\t\t\t\tLOG(LogVerbose, \"Received fragment %d.\", fragmentIndex); \r\n\r\n\t\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t\t{\r\n\t\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\t\tLOG(LogUser, \"Received fragment %d. Elapsed: %.2f seconds. Bytes received: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\t\tnextFragment-1, (float)timespan, bytesReceived, FormatBytes((size_t)(bytesReceived\/timespan)).c_str());\r\n\t\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\telse \/\/ Queue up this fragment.\r\n\t\t\t{\r\n\/\/\t\t\t\tcout << \"Queued up received fragment \" << fragmentIndex << endl;\r\n\t\t\t\tFragment f;\r\n\t\t\t\tsize_t numDataBytes = dd.BytesLeft();\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tf.data.insert(f.data.end(), data + dd.BytePos(), data + numBytes);\r\n#endif\r\n\t\t\t\tf.fragmentIndex = fragmentIndex;\r\n\t\t\t\tfragments[fragmentIndex] = f;\r\n\t\t\t\tbytesReceived += numDataBytes;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tcout << \"Received an unknown message with ID 0x\" << std::hex << id << \"!\" << endl;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid WriteFinishedFragments()\r\n\t{\r\n\t\tstd::map<size_t, Fragment>::iterator iter = fragments.find(nextFragment);\r\n\t\twhile(iter != fragments.end())\r\n\t\t{\r\n#ifndef NULLTRANSFER\r\n\t\t\tout.write(&iter->second.data[0], iter->second.data.size());\r\n#endif\r\n\t\t\tfragments.erase(nextFragment);\r\n\t\t\t++nextFragment;\r\n\t\t\titer = fragments.find(nextFragment);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RunReceiver(unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\tnextFragment = 0;\r\n\t\ttotalFragments = 0xFFFFFFFF;\r\n\r\n\t\t\/\/ Start the server either in TCP or UDP mode.\r\n\t\tNetworkServer *server = network.StartServer(port, transport, this);\r\n\t\tif (!server)\r\n\t\t{\r\n\t\t\tcout << \"Unable to start server in port \" << port << \"!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Server waiting for connection in port \" << port << \".\" << endl;\r\n\r\n\t\twhile(server->GetConnections().size() == 0)\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\tClock::Sleep(2000);\r\n\t\t}\r\n\r\n\t\tPtr(MessageConnection) clientConnection = server->GetConnections().begin()->second;\r\n\r\n\t\t\/\/ Stop accepting any further connections.\r\n\t\tserver->SetAcceptNewConnections(false);\r\n\r\n\t\tclientConnection->WaitToEstablishConnection(10000);\r\n\r\n\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\r\n\t\ttransferStartTick = Clock::Tick();\r\n\r\n\t\tLOG(LogUser, \"Waiting for file receive.\");\r\n\t\twhile(clientConnection->IsReadOpen())\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\t\r\n\t\t\tClock::Sleep(1);\r\n\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t{\r\n\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\tLOG(LogUser, \"Have received fragment %d. Elapsed: %.2f seconds. Bytes received: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\tnextFragment-1, (float)timespan, bytesReceived, FormatBytes((size_t)(bytesReceived\/timespan)).c_str());\r\n\t\t\t\tclientConnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\t\tLOG(LogUser, \"Finished file receive. Closing connection.\");\r\n\t\tclientConnection->Close(15000);\r\n\t}\r\n\r\n\tvoid RunSender(const char *address, unsigned short port, SocketTransportLayer transport, const char *filename)\r\n\t{\r\n\t\tFILE *handle = fopen(filename, \"rb\");\r\n\t\tif (!handle)\r\n\t\t{\r\n\t\t\tLOG(LogUser, \"Failed to open file %s!\", filename);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfseek(handle, 0, SEEK_END);\r\n\t\tlong fileSize = ftell(handle);\r\n\t\tif (fileSize <= 0)\r\n\t\t{\r\n\t\t\tfclose(handle);\r\n\t\t\tLOG(LogUser, \"File %s has zero size!\", filename);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tfseek(handle, 0, SEEK_SET);\r\n\t\tstd::vector<char> tempData;\r\n\r\n\t\tPtr(MessageConnection) connection = network.Connect(address, port, transport, this);\r\n\t\tif (!connection)\r\n\t\t{\r\n\t\t\tcout << \"Unable to connect to \" << address << \":\" << port << \".\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t\/\/ We have nothing better to do while waiting for the connection to build up, so wait modally.\r\n\t\tif (!connection->WaitToEstablishConnection(10000))\r\n\t\t{\r\n\t\t\tcout << \"Failed to connect to server!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Connected to \" << connection->GetSocket()->ToString() << \".\" << endl;\r\n\r\n\t\ttransferStartTick = Clock::Tick();\r\n\r\n\t\tNetworkMessage *msg = connection->StartNewMessage(cFileTransferStartMessage, 2048);\r\n\t\tDataSerializer ds(msg->data, 2048);\r\n\t\tconst size_t fragmentSize = 450;\r\n\t\tconst size_t numFragments = (fileSize + fragmentSize - 1) \/ fragmentSize;\r\n\t\tds.AddString(filename);\r\n\t\tds.Add<u32>(fileSize);\r\n\t\tds.Add<u32>(numFragments);\r\n\t\tmsg->priority = 100;\r\n\t\tmsg->reliable = true;\r\n\t\tmsg->inOrder = true;\r\n\t\tconnection->EndAndQueueMessage(msg, ds.BytesFilled());\r\n\r\n\t\tsize_t nextFragment = 0;\r\n\t\tsize_t bytesSent = 0;\r\n\r\n\t\tLOG(LogUser, \"Starting file transfer. File size: %dB, number of fragments: %d.\",\r\n\t\t\tfileSize, numFragments);\r\n\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\r\n\t\twhile(connection->IsWriteOpen())\r\n\t\t{\r\n\t\t\tconnection->Process();\r\n\r\n\t\t\t\/\/ Add new data fragments into the queue.\r\n\t\t\tconst int outboundMsgQueueSize = 200;\r\n\t\t\tint i = 100;\r\n\t\t\twhile(i-- > 0 && connection->IsWriteOpen() && connection->NumOutboundMessagesPending() < outboundMsgQueueSize && bytesSent < fileSize)\r\n\t\t\t{\r\n\t\t\t\t\/\/ File payload data bytes in this message.\r\n\t\t\t\tconst size_t bytesInThisFragment = min((int)fragmentSize, (int)(fileSize - bytesSent));\r\n\r\n\t\t\t\tNetworkMessage *msg = connection->StartNewMessage(cFileTransferFragment, bytesInThisFragment+4);\r\n\t\t\t\tmsg->priority = 100;\r\n\t\t\t\tmsg->reliable = true;\r\n\t\t\t\tmsg->inOrder = true;\r\n\r\n\t\t\t\tDataSerializer ds(msg->data, msg->Size());\r\n\t\t\t\tds.Add<u32>(nextFragment++);\r\n\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tsize_t read = fread(ds.GetData() + ds.BytesFilled(), sizeof(char), bytesInThisFragment, handle);\r\n#else\r\n\t\t\t\tsize_t read = bytesInThisFragment;\r\n#endif\r\n\t\t\t\tif (read < bytesInThisFragment)\r\n\t\t\t\t{\r\n\t\t\t\t\tLOG(LogUser, \"Failed to read file!\");\r\n\t\t\t\t\tconnection->Close(0);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tconnection->EndAndQueueMessage(msg);\r\n\t\t\t\tbytesSent += bytesInThisFragment;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ If we've put out all file fragments to the network, close the connection down.\r\n\t\t\tif (connection->IsWriteOpen() && bytesSent >= fileSize && connection->NumOutboundMessagesPending() == 0)\r\n\t\t\t{\r\n\t\t\t\tLOG(LogUser, \"All data sent. Disconnecting.\");\r\n\t\t\t\tconnection->Disconnect(15000);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t{\r\n\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\tLOG(LogUser, \"Sending fragment %d. Elapsed: %.2f seconds. Bytes sent: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\tnextFragment-1, (float)timespan, bytesSent, FormatBytes((size_t)(bytesSent\/timespan)).c_str());\r\n\t\t\t\tconnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tLOG(LogUser, \"Waiting for peer to acknowledge all received data.\");\r\n\t\twhile((connection->NumOutboundMessagesPending() > 0 && connection->IsWriteOpen()) || connection->IsReadOpen())\r\n\t\t{\r\n\t\t\tconnection->Process();\r\n\t\t\tClock::Sleep(1);\r\n\r\n\t\t\tif (statsPrintTimer.TriggeredOrNotRunning())\r\n\t\t\t{\r\n\t\t\t\tconnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\tconnection->DumpStatus();\r\n\t\tLOG(LogUser, \"File transfer finished in %.2f seconds. Bytes sent: %d. Transfer rate: %s\/sec. Closing connection.\", \r\n\t\t\t(float)timespan, bytesSent, FormatBytes((size_t)(bytesSent\/timespan)).c_str());\r\n\r\n\t\tconnection->Close(15000);\r\n\t\tfclose(handle);\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \" receive tcp|udp <port>\" << endl;\r\n\tcout << \" send tcp|udp <hostname> <port> <filename>\" << endl;\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 4)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\/\/\tkNet::SetLogChannels((LogChannel)(-1) & ~(LogObjectAlloc | LogVerbose)); \/\/ Enable all log channels.\r\n\tkNet::SetLogChannels(LogUser | LogInfo | LogError);\r\n\r\n\tSocketTransportLayer transport = SocketOverUDP;\r\n\tif (!_stricmp(argv[2], \"tcp\"))\r\n\t\ttransport = SocketOverTCP;\r\n\telse if (!!_stricmp(argv[2], \"udp\"))\r\n\t{\r\n\t\tcout << \"The second parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\tif (!_stricmp(argv[1], \"receive\"))\r\n\t{\r\n\t\tunsigned short port = atoi(argv[3]);\r\n\r\n\t\tapp.RunReceiver(port, transport);\r\n\t}\r\n\telse if (!_stricmp(argv[1], \"send\"))\r\n\t{\r\n\t\tif (argc < 6)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tunsigned short port = atoi(argv[4]);\r\n\t\tapp.RunSender(argv[3], port, transport, argv[5]);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcout << \"The second parameter is either 'send' or 'receive'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n}\r\n<commit_msg>Tuned the FileTransfer sample.<commit_after>\/* Copyright 2010 Jukka Jylnki\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License. *\/\r\n\r\n\/** @file FileTransfer.cpp\r\n\t@brief Implements a file transfer application. The server acts as a receiver waiting for a\r\n\t client to connect and send a file. *\/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <string.h>\r\n#include <utility>\r\n\r\n#include \"kNet.h\"\r\n#include \"kNet\/DebugMemoryLeakCheck.h\"\r\n\r\n\/\/ If enabled, this sample is used for network transfer profiling and all disk operations are ignored.\r\n\/\/#define NULLTRANSFER\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\nconst unsigned long cFileTransferStartMessage = 30;\r\nconst unsigned long cFileTransferFragment = 31;\r\n\r\n#ifdef LINUX\r\n#define _stricmp strcasecmp\r\n#endif\r\n\r\nstruct Fragment\r\n{\r\n\tstd::vector<char> data;\r\n\tsize_t fragmentIndex;\r\n};\r\n\r\nclass NetworkApp : public IMessageHandler, public INetworkServerListener\r\n{\r\n\tNetwork network;\r\n\r\n\t\/\/ Used by the receiver to store partial received data.\r\n\tstd::map<size_t, Fragment> fragments;\r\n\r\n\tsize_t nextFragment;\r\n\tsize_t totalFragments;\r\n\tsize_t bytesReceived;\r\n\tstd::string filename;\r\n\tstd::ofstream out;\r\n\ttick_t transferStartTick;\r\n\r\n\tPolledTimer statsPrintTimer;\r\n\tstatic const int printIntervalMSecs = 4000;\r\npublic:\r\n\r\n\tNetworkApp()\r\n\t:nextFragment(0),\r\n\ttotalFragments(0),\r\n\tbytesReceived(0)\r\n\t{\r\n\t}\r\n\t\/\/\/ Called to notify the listener that a new connection has been established.\r\n\tvoid NewConnectionEstablished(MessageConnection *connection)\r\n\t{\r\n\t\tconnection->RegisterInboundMessageHandler(this);\r\n\t}\r\n\r\n\tvoid HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes)\r\n\t{\r\n\t\tswitch(id)\r\n\t\t{\r\n\t\tcase cFileTransferStartMessage:\r\n\t\t{\r\n\t\t\tDataDeserializer dd(data, numBytes);\r\n\t\t\tfilename = dd.ReadString();\r\n\t\t\tsize_t fileSize = dd.Read<u32>();\r\n\t\t\ttotalFragments = dd.Read<u32>();\r\n\t\t\tnextFragment = 0;\r\n\t\t\tbytesReceived = 0;\r\n\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\tcout << \"Starting receive of file \\\"\" << filename << \"\\\". File size: \" << fileSize << \"B bytes, which is split into \"\r\n\t\t\t\t<< totalFragments << \" fragments.\" << endl;\r\n\t\t\tchar str[256];\r\n\t\t\tsprintf(str, \"received_%s\", filename.c_str());\r\n\t\t\tout.open(str, ios::binary | ios::trunc);\r\n\t\t\ttransferStartTick = Clock::Tick();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase cFileTransferFragment:\r\n\t\t{\r\n\t\t\tDataDeserializer dd(data, numBytes);\r\n\t\t\tsize_t fragmentIndex = dd.Read<u32>();\r\n\t\t\tif (nextFragment == fragmentIndex)\r\n\t\t\t{\r\n\t\t\t\t++nextFragment;\r\n\t\t\t\tsize_t numDataBytes = dd.BytesLeft();\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tout.write(data + dd.BytePos(), numDataBytes);\r\n#endif\r\n\t\t\t\tbytesReceived += numDataBytes;\r\n\t\t\t\tWriteFinishedFragments();\r\n\r\n\t\t\t\tLOG(LogVerbose, \"Received fragment %d.\", fragmentIndex); \r\n\r\n\t\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t\t{\r\n\t\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\t\tLOG(LogUser, \"Received fragment %d. Elapsed: %.2f seconds. Bytes received: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\t\tnextFragment-1, (float)timespan, bytesReceived, FormatBytes((size_t)(bytesReceived\/timespan)).c_str());\r\n\t\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\telse \/\/ Queue up this fragment.\r\n\t\t\t{\r\n\/\/\t\t\t\tcout << \"Queued up received fragment \" << fragmentIndex << endl;\r\n\t\t\t\tFragment f;\r\n\t\t\t\tsize_t numDataBytes = dd.BytesLeft();\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tf.data.insert(f.data.end(), data + dd.BytePos(), data + numBytes);\r\n#endif\r\n\t\t\t\tf.fragmentIndex = fragmentIndex;\r\n\t\t\t\tfragments[fragmentIndex] = f;\r\n\t\t\t\tbytesReceived += numDataBytes;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tcout << \"Received an unknown message with ID 0x\" << std::hex << id << \"!\" << endl;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid WriteFinishedFragments()\r\n\t{\r\n\t\tstd::map<size_t, Fragment>::iterator iter = fragments.find(nextFragment);\r\n\t\twhile(iter != fragments.end())\r\n\t\t{\r\n#ifndef NULLTRANSFER\r\n\t\t\tout.write(&iter->second.data[0], iter->second.data.size());\r\n#endif\r\n\t\t\tfragments.erase(nextFragment);\r\n\t\t\t++nextFragment;\r\n\t\t\titer = fragments.find(nextFragment);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RunReceiver(unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\tnextFragment = 0;\r\n\t\ttotalFragments = 0xFFFFFFFF;\r\n\r\n\t\t\/\/ Start the server either in TCP or UDP mode.\r\n\t\tNetworkServer *server = network.StartServer(port, transport, this);\r\n\t\tif (!server)\r\n\t\t{\r\n\t\t\tcout << \"Unable to start server in port \" << port << \"!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Server waiting for connection in port \" << port << \".\" << endl;\r\n\r\n\t\twhile(server->GetConnections().size() == 0)\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\tClock::Sleep(1);\r\n\t\t}\r\n\r\n\t\tPtr(MessageConnection) clientConnection = server->GetConnections().begin()->second;\r\n\r\n\t\t\/\/ Stop accepting any further connections.\r\n\t\tserver->SetAcceptNewConnections(false);\r\n\r\n\t\tclientConnection->WaitToEstablishConnection(10000);\r\n\r\n\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\r\n\t\ttransferStartTick = Clock::Tick();\r\n\r\n\t\tLOG(LogUser, \"Waiting for file receive.\");\r\n\t\twhile(clientConnection->IsReadOpen())\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\t\r\n\t\t\tClock::Sleep(1);\r\n\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t{\r\n\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\tLOG(LogUser, \"Have received %d fragments (+%d out-of-order) (%.2f%%). Elapsed: %.2f seconds. Bytes received: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\tnextFragment, fragments.size(), (nextFragment + fragments.size()) * 100.f \/ totalFragments,\r\n\t\t\t\t\t(float)timespan, bytesReceived, FormatBytes((size_t)(bytesReceived\/timespan)).c_str());\r\n\t\t\t\tclientConnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (nextFragment == totalFragments)\r\n\t\t{\r\n\t\t\tLOG(LogUser, \"Finished receiving all fragments. File '%s' saved to disk, size: %d bytes. Closing connection.\",\r\n\t\t\t\tfilename.c_str(), bytesReceived);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tLOG(LogUser, \"Error: Sender specified the file '%s' to contain %d fragments, but the connection was closed after \"\r\n\t\t\t\t\"receiving %d fragments. Received a partial file of %d bytes.\", filename.c_str(), totalFragments, nextFragment);\r\n\t\t}\r\n\t\tclientConnection->Close(15000);\r\n\t}\r\n\r\n\tvoid RunSender(const char *address, unsigned short port, SocketTransportLayer transport, const char *filename)\r\n\t{\r\n\t\tFILE *handle = fopen(filename, \"rb\");\r\n\t\tif (!handle)\r\n\t\t{\r\n\t\t\tLOG(LogUser, \"Failed to open file %s!\", filename);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfseek(handle, 0, SEEK_END);\r\n\t\tlong fileSize = ftell(handle);\r\n\t\tif (fileSize <= 0)\r\n\t\t{\r\n\t\t\tfclose(handle);\r\n\t\t\tLOG(LogUser, \"File %s has zero size!\", filename);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tfseek(handle, 0, SEEK_SET);\r\n\t\tstd::vector<char> tempData;\r\n\r\n\t\tPtr(MessageConnection) connection = network.Connect(address, port, transport, this);\r\n\t\tif (!connection)\r\n\t\t{\r\n\t\t\tcout << \"Unable to connect to \" << address << \":\" << port << \".\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t\/\/ We have nothing better to do while waiting for the connection to build up, so wait modally.\r\n\t\tif (!connection->WaitToEstablishConnection(10000))\r\n\t\t{\r\n\t\t\tcout << \"Failed to connect to server!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Connected to \" << connection->GetSocket()->ToString() << \".\" << endl;\r\n\r\n\t\ttransferStartTick = Clock::Tick();\r\n\r\n\t\tNetworkMessage *msg = connection->StartNewMessage(cFileTransferStartMessage, 2048);\r\n\t\tDataSerializer ds(msg->data, 2048);\r\n\t\tconst size_t fragmentSize = 450;\r\n\t\tconst size_t numFragments = (fileSize + fragmentSize - 1) \/ fragmentSize;\r\n\t\tds.AddString(filename);\r\n\t\tds.Add<u32>(fileSize);\r\n\t\tds.Add<u32>(numFragments);\r\n\t\tmsg->priority = 100;\r\n\t\tmsg->reliable = true;\r\n\t\tmsg->inOrder = true;\r\n\t\tconnection->EndAndQueueMessage(msg, ds.BytesFilled());\r\n\r\n\t\tsize_t nextFragment = 0;\r\n\t\tsize_t bytesSent = 0;\r\n\r\n\t\tLOG(LogUser, \"Starting file transfer. File size: %dB, number of fragments: %d.\",\r\n\t\t\tfileSize, numFragments);\r\n\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\r\n\t\twhile(connection->IsWriteOpen())\r\n\t\t{\r\n\t\t\tconnection->Process();\r\n\t\t\tClock::Sleep(1); \/\/ A simple throttle on the send loop to avoid using 100% CPU.\r\n\r\n\t\t\t\/\/ Add new data fragments into the queue.\r\n\t\t\tconst int outboundMsgQueueSize = 200;\r\n\t\t\tint i = 100;\r\n\t\t\twhile(i-- > 0 && connection->IsWriteOpen() && connection->NumOutboundMessagesPending() < outboundMsgQueueSize && bytesSent < fileSize)\r\n\t\t\t{\r\n\t\t\t\t\/\/ File payload data bytes in this message.\r\n\t\t\t\tconst size_t bytesInThisFragment = min((int)fragmentSize, (int)(fileSize - bytesSent));\r\n\r\n\t\t\t\tNetworkMessage *msg = connection->StartNewMessage(cFileTransferFragment, bytesInThisFragment+4);\r\n\t\t\t\tmsg->priority = 100;\r\n\t\t\t\tmsg->reliable = true;\r\n\t\t\t\tmsg->inOrder = true;\r\n\r\n\t\t\t\tDataSerializer ds(msg->data, msg->Size());\r\n\t\t\t\tds.Add<u32>(nextFragment++);\r\n\r\n#ifndef NULLTRANSFER\r\n\t\t\t\tsize_t read = fread(ds.GetData() + ds.BytesFilled(), sizeof(char), bytesInThisFragment, handle);\r\n#else\r\n\t\t\t\tsize_t read = bytesInThisFragment;\r\n#endif\r\n\t\t\t\tif (read < bytesInThisFragment)\r\n\t\t\t\t{\r\n\t\t\t\t\tLOG(LogUser, \"Failed to read file!\");\r\n\t\t\t\t\tconnection->Close(0);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tconnection->EndAndQueueMessage(msg);\r\n\t\t\t\tbytesSent += bytesInThisFragment;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ If we've put out all file fragments to the network, close the connection down.\r\n\t\t\tif (connection->IsWriteOpen() && bytesSent >= fileSize && connection->NumOutboundMessagesPending() == 0)\r\n\t\t\t{\r\n\t\t\t\tLOG(LogUser, \"All data sent. Disconnecting.\");\r\n\t\t\t\tconnection->Disconnect(15000);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (statsPrintTimer.Test())\r\n\t\t\t{\r\n\t\t\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\t\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\t\t\tLOG(LogUser, \"Sending fragment %d. Elapsed: %.2f seconds. Bytes sent: %d. Transfer rate: %s\/sec.\", \r\n\t\t\t\t\tnextFragment-1, (float)timespan, bytesSent, FormatBytes((size_t)(bytesSent\/timespan)).c_str());\r\n\t\t\t\tconnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tLOG(LogUser, \"Waiting for peer to acknowledge all received data.\");\r\n\t\twhile((connection->NumOutboundMessagesPending() > 0 && connection->IsWriteOpen()) || connection->IsReadOpen())\r\n\t\t{\r\n\t\t\tconnection->Process();\r\n\t\t\tClock::Sleep(1);\r\n\r\n\t\t\tif (statsPrintTimer.TriggeredOrNotRunning())\r\n\t\t\t{\r\n\t\t\t\tconnection->DumpStatus();\r\n\t\t\t\tstatsPrintTimer.StartMSecs(printIntervalMSecs);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst tick_t sendFinishTick = Clock::Tick();\r\n\t\tdouble timespan = (float)Clock::TimespanToSecondsD(transferStartTick, sendFinishTick);\r\n\t\tconnection->DumpStatus();\r\n\t\tLOG(LogUser, \"File transfer finished in %.2f seconds. Bytes sent: %d. Transfer rate: %s\/sec. Closing connection.\", \r\n\t\t\t(float)timespan, bytesSent, FormatBytes((size_t)(bytesSent\/timespan)).c_str());\r\n\r\n\t\tconnection->Close(15000);\r\n\t\tfclose(handle);\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \" receive tcp|udp <port>\" << endl;\r\n\tcout << \" send tcp|udp <hostname> <port> <filename>\" << endl;\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 4)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\/\/\tkNet::SetLogChannels((LogChannel)(-1) & ~(LogObjectAlloc | LogVerbose)); \/\/ Enable all log channels.\r\n\tkNet::SetLogChannels(LogUser);\r\n\r\n\tSocketTransportLayer transport = SocketOverUDP;\r\n\tif (!_stricmp(argv[2], \"tcp\"))\r\n\t\ttransport = SocketOverTCP;\r\n\telse if (!!_stricmp(argv[2], \"udp\"))\r\n\t{\r\n\t\tcout << \"The second parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\tif (!_stricmp(argv[1], \"receive\"))\r\n\t{\r\n\t\tunsigned short port = atoi(argv[3]);\r\n\r\n\t\tapp.RunReceiver(port, transport);\r\n\t}\r\n\telse if (!_stricmp(argv[1], \"send\"))\r\n\t{\r\n\t\tif (argc < 6)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tunsigned short port = atoi(argv[4]);\r\n\t\tapp.RunSender(argv[3], port, transport, argv[5]);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcout << \"The second parameter is either 'send' or 'receive'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix coverity report: 63273 Uninitialized scalar field<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/image\/image_skia.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/threading\/non_thread_safe.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n#include \"ui\/gfx\/image\/image_skia_source.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/gfx\/skia_util.h\"\n\nnamespace gfx {\nnamespace {\n\n\/\/ static\ngfx::ImageSkiaRep& NullImageRep() {\n CR_DEFINE_STATIC_LOCAL(ImageSkiaRep, null_image_rep, ());\n return null_image_rep;\n}\n\n} \/\/ namespace\n\nnamespace internal {\nnamespace {\n\nclass Matcher {\n public:\n explicit Matcher(ui::ScaleFactor scale_factor) : scale_factor_(scale_factor) {\n }\n\n bool operator()(const ImageSkiaRep& rep) const {\n return rep.scale_factor() == scale_factor_;\n }\n\n private:\n ui::ScaleFactor scale_factor_;\n};\n\n} \/\/ namespace\n\n\/\/ A helper class such that ImageSkia can be cheaply copied. ImageSkia holds a\n\/\/ refptr instance of ImageSkiaStorage, which in turn holds all of ImageSkia's\n\/\/ information. Having both |base::RefCountedThreadSafe| and\n\/\/ |base::NonThreadSafe| may sounds strange but necessary to turn\n\/\/ the 'thread-non-safe modifiable ImageSkiaStorage' into\n\/\/ the 'thread-safe read-only ImageSkiaStorage'.\nclass ImageSkiaStorage : public base::RefCountedThreadSafe<ImageSkiaStorage>,\n public base::NonThreadSafe {\n public:\n ImageSkiaStorage(ImageSkiaSource* source, const gfx::Size& size)\n : source_(source),\n size_(size),\n read_only_(false) {\n }\n\n ImageSkiaStorage(ImageSkiaSource* source, ui::ScaleFactor scale_factor)\n : source_(source),\n read_only_(false) {\n ImageSkia::ImageSkiaReps::iterator it =\n FindRepresentation(scale_factor, true);\n if (it == image_reps_.end() || it->is_null())\n source_.reset();\n else\n size_.SetSize(it->GetWidth(), it->GetHeight());\n }\n\n bool has_source() const { return source_.get() != NULL; }\n\n std::vector<gfx::ImageSkiaRep>& image_reps() { return image_reps_; }\n\n const gfx::Size& size() const { return size_; }\n\n bool read_only() const { return read_only_; }\n\n void DeleteSource() {\n source_.reset();\n }\n\n void SetReadOnly() {\n read_only_ = true;\n }\n\n void DetachFromThread() {\n base::NonThreadSafe::DetachFromThread();\n }\n\n \/\/ Checks if the current thread can safely modify the storage.\n bool CanModify() const {\n return !read_only_ && CalledOnValidThread();\n }\n\n \/\/ Checks if the current thread can safely read the storage.\n bool CanRead() const {\n return (read_only_ && !source_.get()) || CalledOnValidThread();\n }\n\n \/\/ Returns the iterator of the image rep whose density best matches\n \/\/ |scale_factor|. If the image for the |scale_factor| doesn't exist\n \/\/ in the storage and |storage| is set, it fetches new image by calling\n \/\/ |ImageSkiaSource::GetImageForScale|. If the source returns the\n \/\/ image with different scale factor (if the image doesn't exist in\n \/\/ resource, for example), it will fallback to closest image rep.\n std::vector<ImageSkiaRep>::iterator FindRepresentation(\n ui::ScaleFactor scale_factor, bool fetch_new_image) const {\n ImageSkiaStorage* non_const = const_cast<ImageSkiaStorage*>(this);\n\n float scale = ui::GetScaleFactorScale(scale_factor);\n ImageSkia::ImageSkiaReps::iterator closest_iter =\n non_const->image_reps().end();\n ImageSkia::ImageSkiaReps::iterator exact_iter =\n non_const->image_reps().end();\n float smallest_diff = std::numeric_limits<float>::max();\n for (ImageSkia::ImageSkiaReps::iterator it =\n non_const->image_reps().begin();\n it < image_reps_.end(); ++it) {\n if (it->GetScale() == scale) {\n \/\/ found exact match\n fetch_new_image = false;\n if (it->is_null())\n continue;\n exact_iter = it;\n break;\n }\n float diff = std::abs(it->GetScale() - scale);\n if (diff < smallest_diff && !it->is_null()) {\n closest_iter = it;\n smallest_diff = diff;\n }\n }\n\n if (fetch_new_image && source_.get()) {\n DCHECK(CalledOnValidThread()) <<\n \"An ImageSkia with the source must be accessed by the same thread.\";\n\n ImageSkiaRep image = source_->GetImageForScale(scale_factor);\n\n \/\/ If the source returned the new image, store it.\n if (!image.is_null() &&\n std::find_if(image_reps_.begin(), image_reps_.end(),\n Matcher(image.scale_factor())) == image_reps_.end()) {\n non_const->image_reps().push_back(image);\n }\n\n \/\/ If the result image's scale factor isn't same as the expected\n \/\/ scale factor, create null ImageSkiaRep with the |scale_factor|\n \/\/ so that the next lookup will fallback to the closest scale.\n if (image.is_null() || image.scale_factor() != scale_factor) {\n non_const->image_reps().push_back(\n ImageSkiaRep(SkBitmap(), scale_factor));\n }\n\n \/\/ image_reps_ must have the exact much now, so find again.\n return FindRepresentation(scale_factor, false);\n }\n return exact_iter != image_reps_.end() ? exact_iter : closest_iter;\n }\n\n private:\n virtual ~ImageSkiaStorage() {\n \/\/ We only care if the storage is modified by the same thread.\n \/\/ Don't blow up even if someone else deleted the ImageSkia.\n DetachFromThread();\n }\n\n \/\/ Vector of bitmaps and their associated scale factor.\n std::vector<gfx::ImageSkiaRep> image_reps_;\n\n scoped_ptr<ImageSkiaSource> source_;\n\n \/\/ Size of the image in DIP.\n gfx::Size size_;\n\n bool read_only_;\n\n friend class base::RefCountedThreadSafe<ImageSkiaStorage>;\n};\n\n} \/\/ internal\n\nImageSkia::ImageSkia() : storage_(NULL) {\n}\n\nImageSkia::ImageSkia(ImageSkiaSource* source, const gfx::Size& size)\n : storage_(new internal::ImageSkiaStorage(source, size)) {\n DCHECK(source);\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(ImageSkiaSource* source, ui::ScaleFactor scale_factor)\n : storage_(new internal::ImageSkiaStorage(source, scale_factor)) {\n DCHECK(source);\n if (!storage_->has_source())\n storage_ = NULL;\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const SkBitmap& bitmap) {\n Init(ImageSkiaRep(bitmap, ui::SCALE_FACTOR_100P));\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const ImageSkiaRep& image_rep) {\n Init(image_rep);\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const ImageSkia& other) : storage_(other.storage_) {\n}\n\nImageSkia& ImageSkia::operator=(const ImageSkia& other) {\n storage_ = other.storage_;\n return *this;\n}\n\nImageSkia::~ImageSkia() {\n}\n\nscoped_ptr<ImageSkia> ImageSkia::DeepCopy() const {\n ImageSkia* copy = new ImageSkia;\n if (isNull())\n return scoped_ptr<ImageSkia>(copy);\n\n CHECK(CanRead());\n\n std::vector<gfx::ImageSkiaRep>& reps = storage_->image_reps();\n for (std::vector<gfx::ImageSkiaRep>::iterator iter = reps.begin();\n iter != reps.end(); ++iter) {\n copy->AddRepresentation(*iter);\n }\n \/\/ The copy has its own storage. Detach the copy from the current\n \/\/ thread so that other thread can use this.\n if (!copy->isNull())\n copy->storage_->DetachFromThread();\n return scoped_ptr<ImageSkia>(copy);\n}\n\nbool ImageSkia::BackedBySameObjectAs(const gfx::ImageSkia& other) const {\n return storage_.get() == other.storage_.get();\n}\n\nvoid ImageSkia::AddRepresentation(const ImageSkiaRep& image_rep) {\n DCHECK(!image_rep.is_null());\n\n \/\/ TODO(oshima): This method should be called |SetRepresentation|\n \/\/ and replace the existing rep if there is already one with the\n \/\/ same scale factor so that we can guarantee that a ImageSkia\n \/\/ instance contians only one image rep per scale factor. This is\n \/\/ not possible now as ImageLoadingTracker currently stores need\n \/\/ this feature, but this needs to be fixed.\n if (isNull()) {\n Init(image_rep);\n } else {\n CHECK(CanModify());\n storage_->image_reps().push_back(image_rep);\n }\n}\n\nvoid ImageSkia::RemoveRepresentation(ui::ScaleFactor scale_factor) {\n if (isNull())\n return;\n CHECK(CanModify());\n\n ImageSkiaReps& image_reps = storage_->image_reps();\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(scale_factor, false);\n if (it != image_reps.end() && it->scale_factor() == scale_factor)\n image_reps.erase(it);\n}\n\nbool ImageSkia::HasRepresentation(ui::ScaleFactor scale_factor) const {\n if (isNull())\n return false;\n CHECK(CanRead());\n\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(scale_factor, false);\n return (it != storage_->image_reps().end() &&\n it->scale_factor() == scale_factor);\n}\n\nconst ImageSkiaRep& ImageSkia::GetRepresentation(\n ui::ScaleFactor scale_factor) const {\n if (isNull())\n return NullImageRep();\n\n CHECK(CanRead());\n\n ImageSkiaReps::iterator it = storage_->FindRepresentation(scale_factor, true);\n if (it == storage_->image_reps().end())\n return NullImageRep();\n\n return *it;\n}\n\nvoid ImageSkia::SetReadOnly() {\n CHECK(storage_);\n storage_->SetReadOnly();\n DetachStorageFromThread();\n}\n\nvoid ImageSkia::MakeThreadSafe() {\n CHECK(storage_);\n EnsureRepsForSupportedScaleFactors();\n \/\/ Delete source as we no longer needs it.\n if (storage_)\n storage_->DeleteSource();\n storage_->SetReadOnly();\n CHECK(IsThreadSafe());\n}\n\nbool ImageSkia::IsThreadSafe() const {\n return !storage_ || (storage_->read_only() && !storage_->has_source());\n}\n\nint ImageSkia::width() const {\n return isNull() ? 0 : storage_->size().width();\n}\n\ngfx::Size ImageSkia::size() const {\n return gfx::Size(width(), height());\n}\n\nint ImageSkia::height() const {\n return isNull() ? 0 : storage_->size().height();\n}\n\nstd::vector<ImageSkiaRep> ImageSkia::image_reps() const {\n if (isNull())\n return std::vector<ImageSkiaRep>();\n\n CHECK(CanRead());\n\n ImageSkiaReps internal_image_reps = storage_->image_reps();\n \/\/ Create list of image reps to return, skipping null image reps which were\n \/\/ added for caching purposes only.\n ImageSkiaReps image_reps;\n for (ImageSkiaReps::iterator it = internal_image_reps.begin();\n it != internal_image_reps.end(); ++it) {\n if (!it->is_null())\n image_reps.push_back(*it);\n }\n\n return image_reps;\n}\n\nvoid ImageSkia::EnsureRepsForSupportedScaleFactors() const {\n \/\/ Don't check ReadOnly because the source may generate images\n \/\/ even for read only ImageSkia. Concurrent access will be protected\n \/\/ by |DCHECK(CalledOnValidThread())| in FindRepresentation.\n if (storage_ && storage_->has_source()) {\n std::vector<ui::ScaleFactor> supported_scale_factors =\n ui::GetSupportedScaleFactors();\n for (size_t i = 0; i < supported_scale_factors.size(); ++i)\n storage_->FindRepresentation(supported_scale_factors[i], true);\n }\n}\n\nvoid ImageSkia::Init(const ImageSkiaRep& image_rep) {\n \/\/ TODO(pkotwicz): The image should be null whenever image rep is null.\n if (image_rep.sk_bitmap().empty()) {\n storage_ = NULL;\n return;\n }\n storage_ = new internal::ImageSkiaStorage(\n NULL, gfx::Size(image_rep.GetWidth(), image_rep.GetHeight()));\n storage_->image_reps().push_back(image_rep);\n}\n\nSkBitmap& ImageSkia::GetBitmap() const {\n if (isNull()) {\n \/\/ Callers expect a ImageSkiaRep even if it is |isNull()|.\n \/\/ TODO(pkotwicz): Fix this.\n return NullImageRep().mutable_sk_bitmap();\n }\n\n \/\/ TODO(oshima): This made a few tests flaky on Windows.\n \/\/ Fix the root cause and re-enable this. crbug.com\/145623.\n#if !defined(OS_WIN)\n CHECK(CanRead());\n#endif\n\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(ui::SCALE_FACTOR_100P, true);\n if (it != storage_->image_reps().end())\n return it->mutable_sk_bitmap();\n return NullImageRep().mutable_sk_bitmap();\n}\n\nbool ImageSkia::CanRead() const {\n return !storage_ || storage_->CanRead();\n}\n\nbool ImageSkia::CanModify() const {\n return !storage_ || storage_->CanModify();\n}\n\nvoid ImageSkia::DetachStorageFromThread() {\n if (storage_)\n storage_->DetachFromThread();\n}\n\n} \/\/ namespace gfx\n<commit_msg>Enable DCHECK in GetBitmap on WIN<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/image\/image_skia.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/threading\/non_thread_safe.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n#include \"ui\/gfx\/image\/image_skia_source.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/gfx\/skia_util.h\"\n\nnamespace gfx {\nnamespace {\n\n\/\/ static\ngfx::ImageSkiaRep& NullImageRep() {\n CR_DEFINE_STATIC_LOCAL(ImageSkiaRep, null_image_rep, ());\n return null_image_rep;\n}\n\n} \/\/ namespace\n\nnamespace internal {\nnamespace {\n\nclass Matcher {\n public:\n explicit Matcher(ui::ScaleFactor scale_factor) : scale_factor_(scale_factor) {\n }\n\n bool operator()(const ImageSkiaRep& rep) const {\n return rep.scale_factor() == scale_factor_;\n }\n\n private:\n ui::ScaleFactor scale_factor_;\n};\n\n} \/\/ namespace\n\n\/\/ A helper class such that ImageSkia can be cheaply copied. ImageSkia holds a\n\/\/ refptr instance of ImageSkiaStorage, which in turn holds all of ImageSkia's\n\/\/ information. Having both |base::RefCountedThreadSafe| and\n\/\/ |base::NonThreadSafe| may sounds strange but necessary to turn\n\/\/ the 'thread-non-safe modifiable ImageSkiaStorage' into\n\/\/ the 'thread-safe read-only ImageSkiaStorage'.\nclass ImageSkiaStorage : public base::RefCountedThreadSafe<ImageSkiaStorage>,\n public base::NonThreadSafe {\n public:\n ImageSkiaStorage(ImageSkiaSource* source, const gfx::Size& size)\n : source_(source),\n size_(size),\n read_only_(false) {\n }\n\n ImageSkiaStorage(ImageSkiaSource* source, ui::ScaleFactor scale_factor)\n : source_(source),\n read_only_(false) {\n ImageSkia::ImageSkiaReps::iterator it =\n FindRepresentation(scale_factor, true);\n if (it == image_reps_.end() || it->is_null())\n source_.reset();\n else\n size_.SetSize(it->GetWidth(), it->GetHeight());\n }\n\n bool has_source() const { return source_.get() != NULL; }\n\n std::vector<gfx::ImageSkiaRep>& image_reps() { return image_reps_; }\n\n const gfx::Size& size() const { return size_; }\n\n bool read_only() const { return read_only_; }\n\n void DeleteSource() {\n source_.reset();\n }\n\n void SetReadOnly() {\n read_only_ = true;\n }\n\n void DetachFromThread() {\n base::NonThreadSafe::DetachFromThread();\n }\n\n \/\/ Checks if the current thread can safely modify the storage.\n bool CanModify() const {\n return !read_only_ && CalledOnValidThread();\n }\n\n \/\/ Checks if the current thread can safely read the storage.\n bool CanRead() const {\n return (read_only_ && !source_.get()) || CalledOnValidThread();\n }\n\n \/\/ Returns the iterator of the image rep whose density best matches\n \/\/ |scale_factor|. If the image for the |scale_factor| doesn't exist\n \/\/ in the storage and |storage| is set, it fetches new image by calling\n \/\/ |ImageSkiaSource::GetImageForScale|. If the source returns the\n \/\/ image with different scale factor (if the image doesn't exist in\n \/\/ resource, for example), it will fallback to closest image rep.\n std::vector<ImageSkiaRep>::iterator FindRepresentation(\n ui::ScaleFactor scale_factor, bool fetch_new_image) const {\n ImageSkiaStorage* non_const = const_cast<ImageSkiaStorage*>(this);\n\n float scale = ui::GetScaleFactorScale(scale_factor);\n ImageSkia::ImageSkiaReps::iterator closest_iter =\n non_const->image_reps().end();\n ImageSkia::ImageSkiaReps::iterator exact_iter =\n non_const->image_reps().end();\n float smallest_diff = std::numeric_limits<float>::max();\n for (ImageSkia::ImageSkiaReps::iterator it =\n non_const->image_reps().begin();\n it < image_reps_.end(); ++it) {\n if (it->GetScale() == scale) {\n \/\/ found exact match\n fetch_new_image = false;\n if (it->is_null())\n continue;\n exact_iter = it;\n break;\n }\n float diff = std::abs(it->GetScale() - scale);\n if (diff < smallest_diff && !it->is_null()) {\n closest_iter = it;\n smallest_diff = diff;\n }\n }\n\n if (fetch_new_image && source_.get()) {\n DCHECK(CalledOnValidThread()) <<\n \"An ImageSkia with the source must be accessed by the same thread.\";\n\n ImageSkiaRep image = source_->GetImageForScale(scale_factor);\n\n \/\/ If the source returned the new image, store it.\n if (!image.is_null() &&\n std::find_if(image_reps_.begin(), image_reps_.end(),\n Matcher(image.scale_factor())) == image_reps_.end()) {\n non_const->image_reps().push_back(image);\n }\n\n \/\/ If the result image's scale factor isn't same as the expected\n \/\/ scale factor, create null ImageSkiaRep with the |scale_factor|\n \/\/ so that the next lookup will fallback to the closest scale.\n if (image.is_null() || image.scale_factor() != scale_factor) {\n non_const->image_reps().push_back(\n ImageSkiaRep(SkBitmap(), scale_factor));\n }\n\n \/\/ image_reps_ must have the exact much now, so find again.\n return FindRepresentation(scale_factor, false);\n }\n return exact_iter != image_reps_.end() ? exact_iter : closest_iter;\n }\n\n private:\n virtual ~ImageSkiaStorage() {\n \/\/ We only care if the storage is modified by the same thread.\n \/\/ Don't blow up even if someone else deleted the ImageSkia.\n DetachFromThread();\n }\n\n \/\/ Vector of bitmaps and their associated scale factor.\n std::vector<gfx::ImageSkiaRep> image_reps_;\n\n scoped_ptr<ImageSkiaSource> source_;\n\n \/\/ Size of the image in DIP.\n gfx::Size size_;\n\n bool read_only_;\n\n friend class base::RefCountedThreadSafe<ImageSkiaStorage>;\n};\n\n} \/\/ internal\n\nImageSkia::ImageSkia() : storage_(NULL) {\n}\n\nImageSkia::ImageSkia(ImageSkiaSource* source, const gfx::Size& size)\n : storage_(new internal::ImageSkiaStorage(source, size)) {\n DCHECK(source);\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(ImageSkiaSource* source, ui::ScaleFactor scale_factor)\n : storage_(new internal::ImageSkiaStorage(source, scale_factor)) {\n DCHECK(source);\n if (!storage_->has_source())\n storage_ = NULL;\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const SkBitmap& bitmap) {\n Init(ImageSkiaRep(bitmap, ui::SCALE_FACTOR_100P));\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const ImageSkiaRep& image_rep) {\n Init(image_rep);\n \/\/ No other thread has reference to this, so it's safe to detach the thread.\n DetachStorageFromThread();\n}\n\nImageSkia::ImageSkia(const ImageSkia& other) : storage_(other.storage_) {\n}\n\nImageSkia& ImageSkia::operator=(const ImageSkia& other) {\n storage_ = other.storage_;\n return *this;\n}\n\nImageSkia::~ImageSkia() {\n}\n\nscoped_ptr<ImageSkia> ImageSkia::DeepCopy() const {\n ImageSkia* copy = new ImageSkia;\n if (isNull())\n return scoped_ptr<ImageSkia>(copy);\n\n CHECK(CanRead());\n\n std::vector<gfx::ImageSkiaRep>& reps = storage_->image_reps();\n for (std::vector<gfx::ImageSkiaRep>::iterator iter = reps.begin();\n iter != reps.end(); ++iter) {\n copy->AddRepresentation(*iter);\n }\n \/\/ The copy has its own storage. Detach the copy from the current\n \/\/ thread so that other thread can use this.\n if (!copy->isNull())\n copy->storage_->DetachFromThread();\n return scoped_ptr<ImageSkia>(copy);\n}\n\nbool ImageSkia::BackedBySameObjectAs(const gfx::ImageSkia& other) const {\n return storage_.get() == other.storage_.get();\n}\n\nvoid ImageSkia::AddRepresentation(const ImageSkiaRep& image_rep) {\n DCHECK(!image_rep.is_null());\n\n \/\/ TODO(oshima): This method should be called |SetRepresentation|\n \/\/ and replace the existing rep if there is already one with the\n \/\/ same scale factor so that we can guarantee that a ImageSkia\n \/\/ instance contians only one image rep per scale factor. This is\n \/\/ not possible now as ImageLoadingTracker currently stores need\n \/\/ this feature, but this needs to be fixed.\n if (isNull()) {\n Init(image_rep);\n } else {\n CHECK(CanModify());\n storage_->image_reps().push_back(image_rep);\n }\n}\n\nvoid ImageSkia::RemoveRepresentation(ui::ScaleFactor scale_factor) {\n if (isNull())\n return;\n CHECK(CanModify());\n\n ImageSkiaReps& image_reps = storage_->image_reps();\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(scale_factor, false);\n if (it != image_reps.end() && it->scale_factor() == scale_factor)\n image_reps.erase(it);\n}\n\nbool ImageSkia::HasRepresentation(ui::ScaleFactor scale_factor) const {\n if (isNull())\n return false;\n CHECK(CanRead());\n\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(scale_factor, false);\n return (it != storage_->image_reps().end() &&\n it->scale_factor() == scale_factor);\n}\n\nconst ImageSkiaRep& ImageSkia::GetRepresentation(\n ui::ScaleFactor scale_factor) const {\n if (isNull())\n return NullImageRep();\n\n CHECK(CanRead());\n\n ImageSkiaReps::iterator it = storage_->FindRepresentation(scale_factor, true);\n if (it == storage_->image_reps().end())\n return NullImageRep();\n\n return *it;\n}\n\nvoid ImageSkia::SetReadOnly() {\n CHECK(storage_);\n storage_->SetReadOnly();\n DetachStorageFromThread();\n}\n\nvoid ImageSkia::MakeThreadSafe() {\n CHECK(storage_);\n EnsureRepsForSupportedScaleFactors();\n \/\/ Delete source as we no longer needs it.\n if (storage_)\n storage_->DeleteSource();\n storage_->SetReadOnly();\n CHECK(IsThreadSafe());\n}\n\nbool ImageSkia::IsThreadSafe() const {\n return !storage_ || (storage_->read_only() && !storage_->has_source());\n}\n\nint ImageSkia::width() const {\n return isNull() ? 0 : storage_->size().width();\n}\n\ngfx::Size ImageSkia::size() const {\n return gfx::Size(width(), height());\n}\n\nint ImageSkia::height() const {\n return isNull() ? 0 : storage_->size().height();\n}\n\nstd::vector<ImageSkiaRep> ImageSkia::image_reps() const {\n if (isNull())\n return std::vector<ImageSkiaRep>();\n\n CHECK(CanRead());\n\n ImageSkiaReps internal_image_reps = storage_->image_reps();\n \/\/ Create list of image reps to return, skipping null image reps which were\n \/\/ added for caching purposes only.\n ImageSkiaReps image_reps;\n for (ImageSkiaReps::iterator it = internal_image_reps.begin();\n it != internal_image_reps.end(); ++it) {\n if (!it->is_null())\n image_reps.push_back(*it);\n }\n\n return image_reps;\n}\n\nvoid ImageSkia::EnsureRepsForSupportedScaleFactors() const {\n \/\/ Don't check ReadOnly because the source may generate images\n \/\/ even for read only ImageSkia. Concurrent access will be protected\n \/\/ by |DCHECK(CalledOnValidThread())| in FindRepresentation.\n if (storage_ && storage_->has_source()) {\n std::vector<ui::ScaleFactor> supported_scale_factors =\n ui::GetSupportedScaleFactors();\n for (size_t i = 0; i < supported_scale_factors.size(); ++i)\n storage_->FindRepresentation(supported_scale_factors[i], true);\n }\n}\n\nvoid ImageSkia::Init(const ImageSkiaRep& image_rep) {\n \/\/ TODO(pkotwicz): The image should be null whenever image rep is null.\n if (image_rep.sk_bitmap().empty()) {\n storage_ = NULL;\n return;\n }\n storage_ = new internal::ImageSkiaStorage(\n NULL, gfx::Size(image_rep.GetWidth(), image_rep.GetHeight()));\n storage_->image_reps().push_back(image_rep);\n}\n\nSkBitmap& ImageSkia::GetBitmap() const {\n if (isNull()) {\n \/\/ Callers expect a ImageSkiaRep even if it is |isNull()|.\n \/\/ TODO(pkotwicz): Fix this.\n return NullImageRep().mutable_sk_bitmap();\n }\n\n CHECK(CanRead());\n\n ImageSkiaReps::iterator it =\n storage_->FindRepresentation(ui::SCALE_FACTOR_100P, true);\n if (it != storage_->image_reps().end())\n return it->mutable_sk_bitmap();\n return NullImageRep().mutable_sk_bitmap();\n}\n\nbool ImageSkia::CanRead() const {\n return !storage_ || storage_->CanRead();\n}\n\nbool ImageSkia::CanModify() const {\n return !storage_ || storage_->CanModify();\n}\n\nvoid ImageSkia::DetachStorageFromThread() {\n if (storage_)\n storage_->DetachFromThread();\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"DeviceAttestationConstructor.h\"\n#include \"DeviceAttestationVendorReserved.h\"\n\n#include <lib\/core\/CHIPTLV.h>\n#include <lib\/support\/CodeUtils.h>\n#include <lib\/support\/logging\/CHIPLogging.h>\n\n#include <cstdint>\n\nnamespace chip {\nnamespace Credentials {\n\n\/\/ context tag positions\nenum AttestationInfoId : uint32_t\n{\n kCertificationDeclarationTagId = 1,\n kAttestationNonceTagId = 2,\n kTimestampTagId = 3,\n kFirmwareInfoTagId = 4,\n};\n\nenum OperationalCSRInfoId : uint32_t\n{\n kCsr = 1,\n kCsrNonce = 2,\n kVendorReserved1 = 3,\n kVendorReserved2 = 4,\n kVendorReserved3 = 5,\n};\n\n\/\/ utility to determine number of Vendor Reserved elements in a bytespan\nCHIP_ERROR CountVendorReservedElementsInDA(const ByteSpan & attestationElements, size_t & numOfElements)\n{\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n tlvReader.Init(attestationElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag()));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n size_t count = 0;\n CHIP_ERROR error;\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (TLV::IsProfileTag(tag))\n {\n count++;\n }\n }\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n numOfElements = count;\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DeconstructAttestationElements(const ByteSpan & attestationElements, ByteSpan & certificationDeclaration,\n ByteSpan & attestationNonce, uint32_t & timestamp, ByteSpan & firmwareInfo,\n DeviceAttestationVendorReservedDeconstructor & vendorReserved)\n{\n bool certificationDeclarationExists = false;\n bool attestationNonceExists = false;\n bool timestampExists = false;\n bool gotFirstContextTag = false;\n uint32_t lastContextTagId = 0;\n\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n firmwareInfo = ByteSpan();\n\n tlvReader.Init(attestationElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag()));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n CHIP_ERROR error;\n\n \/\/ process context tags first (should be in sorted order)\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (!TLV::IsContextTag(tag))\n {\n break;\n }\n\n \/\/ Ensure tag-order and correct first expected tag\n uint32_t contextTagId = TLV::TagNumFromTag(tag);\n if (!gotFirstContextTag)\n {\n \/\/ First tag must always be Certification Declaration\n VerifyOrReturnError(contextTagId == kCertificationDeclarationTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n gotFirstContextTag = true;\n }\n else\n {\n \/\/ Subsequent tags must always be in order\n VerifyOrReturnError(contextTagId > lastContextTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n }\n lastContextTagId = contextTagId;\n\n switch (contextTagId)\n {\n case kCertificationDeclarationTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(certificationDeclaration));\n certificationDeclarationExists = true;\n break;\n case kAttestationNonceTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(attestationNonce));\n attestationNonceExists = true;\n break;\n case kTimestampTagId:\n ReturnErrorOnFailure(tlvReader.Get(timestamp));\n timestampExists = true;\n break;\n case kFirmwareInfoTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(firmwareInfo));\n break;\n default:\n \/\/ It's OK to have future context tags before vendor specific tags.\n \/\/ We already checked that the tags are in order.\n break;\n }\n }\n\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n const bool allTagsNeededPresent = certificationDeclarationExists && attestationNonceExists && timestampExists;\n VerifyOrReturnError(allTagsNeededPresent, CHIP_ERROR_MISSING_TLV_ELEMENT);\n\n size_t count = 0;\n ReturnErrorOnFailure(CountVendorReservedElementsInDA(attestationElements, count));\n ReturnErrorOnFailure(vendorReserved.PrepareToReadVendorReservedElements(attestationElements, count));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR ConstructAttestationElements(const ByteSpan & certificationDeclaration, const ByteSpan & attestationNonce,\n uint32_t timestamp, const ByteSpan & firmwareInfo,\n DeviceAttestationVendorReservedConstructor & vendorReserved,\n MutableByteSpan & attestationElements)\n{\n TLV::TLVWriter tlvWriter;\n TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;\n\n VerifyOrReturnError(!certificationDeclaration.empty() && !attestationNonce.empty(), CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrReturnError(attestationNonce.size() == kExpectedAttestationNonceSize, CHIP_ERROR_INVALID_ARGUMENT);\n\n tlvWriter.Init(attestationElements.data(), static_cast<uint32_t>(attestationElements.size()));\n outerContainerType = TLV::kTLVType_NotSpecified;\n ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(1), certificationDeclaration));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), attestationNonce));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(3), timestamp));\n if (!firmwareInfo.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(4), firmwareInfo));\n }\n\n const VendorReservedElement * element = vendorReserved.cbegin();\n while ((element = vendorReserved.Next()) != nullptr)\n {\n ReturnErrorOnFailure(\n tlvWriter.Put(TLV::ProfileTag(element->vendorId, element->profileNum, element->tagNum), element->vendorReservedData));\n }\n\n ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Finalize());\n attestationElements = attestationElements.SubSpan(0, tlvWriter.GetLengthWritten());\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR ConstructNOCSRElements(const ByteSpan & csr, const ByteSpan & csrNonce, const ByteSpan & vendor_reserved1,\n const ByteSpan & vendor_reserved2, const ByteSpan & vendor_reserved3,\n MutableByteSpan & nocsrElements)\n{\n TLV::TLVWriter tlvWriter;\n TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;\n\n VerifyOrReturnError(!csr.empty() && !csrNonce.empty(), CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrReturnError(csrNonce.size() == kExpectedAttestationNonceSize, CHIP_ERROR_INVALID_ARGUMENT);\n\n tlvWriter.Init(nocsrElements.data(), static_cast<uint32_t>(nocsrElements.size()));\n outerContainerType = TLV::kTLVType_NotSpecified;\n ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(1), csr));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), csrNonce));\n if (!vendor_reserved1.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(3), vendor_reserved1));\n }\n if (!vendor_reserved2.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(4), vendor_reserved2));\n }\n if (!vendor_reserved3.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(5), vendor_reserved3));\n }\n\n ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Finalize());\n nocsrElements = nocsrElements.SubSpan(0, tlvWriter.GetLengthWritten());\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DeconstructNOCSRElements(const ByteSpan & nocsrElements, ByteSpan & csr, ByteSpan & csrNonce,\n ByteSpan & vendor_reserved1, ByteSpan & vendor_reserved2, ByteSpan & vendor_reserved3)\n{\n bool csrExists = false;\n bool csrNonceExists = false;\n bool gotFirstContextTag = false;\n uint32_t lastContextTagId = 0;\n\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n \/\/ empty out the optional items initially\n vendor_reserved1 = vendor_reserved2 = vendor_reserved3 = ByteSpan();\n\n tlvReader.Init(nocsrElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n CHIP_ERROR error;\n\n \/\/ process context tags first (should be in sorted order)\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (!TLV::IsContextTag(tag))\n {\n break;\n }\n\n \/\/ Ensure tag-order and correct first expected tag\n uint32_t contextTagId = TLV::TagNumFromTag(tag);\n if (!gotFirstContextTag)\n {\n \/\/ First tag must always be CSR\n VerifyOrReturnError(contextTagId == kCsr, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n gotFirstContextTag = true;\n }\n else\n {\n \/\/ Subsequent tags must always be in order\n VerifyOrReturnError(contextTagId > lastContextTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n }\n lastContextTagId = contextTagId;\n\n switch (contextTagId)\n {\n case kCsr:\n ReturnErrorOnFailure(tlvReader.GetByteView(csr));\n csrExists = true;\n break;\n case kCsrNonce:\n ReturnErrorOnFailure(tlvReader.GetByteView(csrNonce));\n csrNonceExists = true;\n break;\n case kVendorReserved1:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved1));\n break;\n case kVendorReserved2:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved2));\n break;\n case kVendorReserved3:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved3));\n break;\n default:\n \/\/ unrecognized TLV element\n return CHIP_ERROR_INVALID_TLV_ELEMENT;\n }\n }\n\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n const bool allTagsNeededPresent = csrExists && csrNonceExists;\n VerifyOrReturnError(allTagsNeededPresent, CHIP_ERROR_MISSING_TLV_ELEMENT);\n\n return CHIP_NO_ERROR;\n}\n\n} \/\/ namespace Credentials\n\n} \/\/ namespace chip\n<commit_msg>Fix build failure (#13302)<commit_after>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"DeviceAttestationConstructor.h\"\n#include \"DeviceAttestationVendorReserved.h\"\n\n#include <lib\/core\/CHIPTLV.h>\n#include <lib\/support\/CodeUtils.h>\n#include <lib\/support\/logging\/CHIPLogging.h>\n\n#include <cstdint>\n\nnamespace chip {\nnamespace Credentials {\n\n\/\/ context tag positions\nenum AttestationInfoId : uint32_t\n{\n kCertificationDeclarationTagId = 1,\n kAttestationNonceTagId = 2,\n kTimestampTagId = 3,\n kFirmwareInfoTagId = 4,\n};\n\nenum OperationalCSRInfoId : uint32_t\n{\n kCsr = 1,\n kCsrNonce = 2,\n kVendorReserved1 = 3,\n kVendorReserved2 = 4,\n kVendorReserved3 = 5,\n};\n\n\/\/ utility to determine number of Vendor Reserved elements in a bytespan\nCHIP_ERROR CountVendorReservedElementsInDA(const ByteSpan & attestationElements, size_t & numOfElements)\n{\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n tlvReader.Init(attestationElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag()));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n size_t count = 0;\n CHIP_ERROR error;\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (TLV::IsProfileTag(tag))\n {\n count++;\n }\n }\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n numOfElements = count;\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DeconstructAttestationElements(const ByteSpan & attestationElements, ByteSpan & certificationDeclaration,\n ByteSpan & attestationNonce, uint32_t & timestamp, ByteSpan & firmwareInfo,\n DeviceAttestationVendorReservedDeconstructor & vendorReserved)\n{\n bool certificationDeclarationExists = false;\n bool attestationNonceExists = false;\n bool timestampExists = false;\n bool gotFirstContextTag = false;\n uint32_t lastContextTagId = 0;\n\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n firmwareInfo = ByteSpan();\n\n tlvReader.Init(attestationElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag()));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n CHIP_ERROR error;\n\n \/\/ process context tags first (should be in sorted order)\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (!TLV::IsContextTag(tag))\n {\n break;\n }\n\n \/\/ Ensure tag-order and correct first expected tag\n uint32_t contextTagId = TLV::TagNumFromTag(tag);\n if (!gotFirstContextTag)\n {\n \/\/ First tag must always be Certification Declaration\n VerifyOrReturnError(contextTagId == kCertificationDeclarationTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n gotFirstContextTag = true;\n }\n else\n {\n \/\/ Subsequent tags must always be in order\n VerifyOrReturnError(contextTagId > lastContextTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n }\n lastContextTagId = contextTagId;\n\n switch (contextTagId)\n {\n case kCertificationDeclarationTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(certificationDeclaration));\n certificationDeclarationExists = true;\n break;\n case kAttestationNonceTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(attestationNonce));\n attestationNonceExists = true;\n break;\n case kTimestampTagId:\n ReturnErrorOnFailure(tlvReader.Get(timestamp));\n timestampExists = true;\n break;\n case kFirmwareInfoTagId:\n ReturnErrorOnFailure(tlvReader.GetByteView(firmwareInfo));\n break;\n default:\n \/\/ It's OK to have future context tags before vendor specific tags.\n \/\/ We already checked that the tags are in order.\n break;\n }\n }\n\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n const bool allTagsNeededPresent = certificationDeclarationExists && attestationNonceExists && timestampExists;\n VerifyOrReturnError(allTagsNeededPresent, CHIP_ERROR_MISSING_TLV_ELEMENT);\n\n size_t count = 0;\n ReturnErrorOnFailure(CountVendorReservedElementsInDA(attestationElements, count));\n ReturnErrorOnFailure(vendorReserved.PrepareToReadVendorReservedElements(attestationElements, count));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR ConstructAttestationElements(const ByteSpan & certificationDeclaration, const ByteSpan & attestationNonce,\n uint32_t timestamp, const ByteSpan & firmwareInfo,\n DeviceAttestationVendorReservedConstructor & vendorReserved,\n MutableByteSpan & attestationElements)\n{\n TLV::TLVWriter tlvWriter;\n TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;\n\n VerifyOrReturnError(!certificationDeclaration.empty() && !attestationNonce.empty(), CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrReturnError(attestationNonce.size() == kExpectedAttestationNonceSize, CHIP_ERROR_INVALID_ARGUMENT);\n\n tlvWriter.Init(attestationElements.data(), static_cast<uint32_t>(attestationElements.size()));\n outerContainerType = TLV::kTLVType_NotSpecified;\n ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(1), certificationDeclaration));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), attestationNonce));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(3), timestamp));\n if (!firmwareInfo.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(4), firmwareInfo));\n }\n\n const VendorReservedElement * element = vendorReserved.cbegin();\n while ((element = vendorReserved.Next()) != nullptr)\n {\n ReturnErrorOnFailure(\n tlvWriter.Put(TLV::ProfileTag(element->vendorId, element->profileNum, element->tagNum), element->vendorReservedData));\n }\n\n ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Finalize());\n attestationElements = attestationElements.SubSpan(0, tlvWriter.GetLengthWritten());\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR ConstructNOCSRElements(const ByteSpan & csr, const ByteSpan & csrNonce, const ByteSpan & vendor_reserved1,\n const ByteSpan & vendor_reserved2, const ByteSpan & vendor_reserved3,\n MutableByteSpan & nocsrElements)\n{\n TLV::TLVWriter tlvWriter;\n TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;\n\n VerifyOrReturnError(!csr.empty() && !csrNonce.empty(), CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrReturnError(csrNonce.size() == kExpectedAttestationNonceSize, CHIP_ERROR_INVALID_ARGUMENT);\n\n tlvWriter.Init(nocsrElements.data(), static_cast<uint32_t>(nocsrElements.size()));\n outerContainerType = TLV::kTLVType_NotSpecified;\n ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(1), csr));\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), csrNonce));\n if (!vendor_reserved1.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(3), vendor_reserved1));\n }\n if (!vendor_reserved2.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(4), vendor_reserved2));\n }\n if (!vendor_reserved3.empty())\n {\n ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(5), vendor_reserved3));\n }\n\n ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));\n ReturnErrorOnFailure(tlvWriter.Finalize());\n nocsrElements = nocsrElements.SubSpan(0, tlvWriter.GetLengthWritten());\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DeconstructNOCSRElements(const ByteSpan & nocsrElements, ByteSpan & csr, ByteSpan & csrNonce,\n ByteSpan & vendor_reserved1, ByteSpan & vendor_reserved2, ByteSpan & vendor_reserved3)\n{\n bool csrExists = false;\n bool csrNonceExists = false;\n bool gotFirstContextTag = false;\n uint32_t lastContextTagId = 0;\n\n TLV::ContiguousBufferTLVReader tlvReader;\n TLV::TLVType containerType = TLV::kTLVType_Structure;\n\n \/\/ empty out the optional items initially\n vendor_reserved1 = vendor_reserved2 = vendor_reserved3 = ByteSpan();\n\n tlvReader.Init(nocsrElements);\n ReturnErrorOnFailure(tlvReader.Next(containerType, TLV::AnonymousTag()));\n ReturnErrorOnFailure(tlvReader.EnterContainer(containerType));\n\n CHIP_ERROR error;\n\n \/\/ process context tags first (should be in sorted order)\n while ((error = tlvReader.Next()) == CHIP_NO_ERROR)\n {\n TLV::Tag tag = tlvReader.GetTag();\n if (!TLV::IsContextTag(tag))\n {\n break;\n }\n\n \/\/ Ensure tag-order and correct first expected tag\n uint32_t contextTagId = TLV::TagNumFromTag(tag);\n if (!gotFirstContextTag)\n {\n \/\/ First tag must always be CSR\n VerifyOrReturnError(contextTagId == kCsr, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n gotFirstContextTag = true;\n }\n else\n {\n \/\/ Subsequent tags must always be in order\n VerifyOrReturnError(contextTagId > lastContextTagId, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);\n }\n lastContextTagId = contextTagId;\n\n switch (contextTagId)\n {\n case kCsr:\n ReturnErrorOnFailure(tlvReader.GetByteView(csr));\n csrExists = true;\n break;\n case kCsrNonce:\n ReturnErrorOnFailure(tlvReader.GetByteView(csrNonce));\n csrNonceExists = true;\n break;\n case kVendorReserved1:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved1));\n break;\n case kVendorReserved2:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved2));\n break;\n case kVendorReserved3:\n ReturnErrorOnFailure(tlvReader.Get(vendor_reserved3));\n break;\n default:\n \/\/ unrecognized TLV element\n return CHIP_ERROR_INVALID_TLV_ELEMENT;\n }\n }\n\n VerifyOrReturnError(error == CHIP_NO_ERROR || error == CHIP_END_OF_TLV, error);\n\n const bool allTagsNeededPresent = csrExists && csrNonceExists;\n VerifyOrReturnError(allTagsNeededPresent, CHIP_ERROR_MISSING_TLV_ELEMENT);\n\n return CHIP_NO_ERROR;\n}\n\n} \/\/ namespace Credentials\n\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: mba $ $Date: 2000-12-15 15:38:54 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n#include <offmgr\/app.hxx>\n#include <comphelper\/processfactory.hxx>\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n\n#include <setup2\/installer.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#include <vcl\/msgbox.hxx>\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nvoid ReplaceStringHookProc( UniString& rStr )\n{\n static String aBrandName;\n static String aVersion;\n if ( !aBrandName.Len() )\n {\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n rtl::OUString aTmp;\n aRet >>= aTmp;\n aBrandName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n aVersion = aTmp;\n }\n\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", aBrandName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", aVersion );\n}\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n ResMgr::SetReadStringHook( ReplaceStringHookProc );\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n<commit_msg>fix: #82184# added<commit_after>\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: pb $ $Date: 2001-01-23 11:56:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n#include <offmgr\/app.hxx>\n#include <comphelper\/processfactory.hxx>\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n\n#include <setup2\/installer.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#include <vcl\/msgbox.hxx>\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nvoid ReplaceStringHookProc( UniString& rStr )\n{\n static String aBrandName;\n static String aVersion;\n static String aExtension;\n\n static int nAll = 0, nPro = 0;\n\n if ( !aBrandName.Len() )\n {\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n rtl::OUString aTmp;\n aRet >>= aTmp;\n aBrandName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n aVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );\n aRet >>= aTmp;\n aExtension = aTmp;\n }\n\n nAll++;\n if ( rStr.SearchAscii( \"%PRODUCT\" ) != STRING_NOTFOUND )\n {\n nPro++;\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", aBrandName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", aVersion );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTEXTENSION\", aExtension );\n }\n}\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n ResMgr::SetReadStringHook( ReplaceStringHookProc );\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of telepathy-nepomuk-service\n *\n * Copyright (C) 2009-2011 Collabora Ltd. <info@collabora.co.uk>\n * @author George Goldberg <george.goldberg@collabora.co.uk>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"account.h\"\n\n#include \"contact.h\"\n\n#include <KDebug>\n\n#include <TelepathyQt\/ContactManager>\n#include <TelepathyQt\/PendingContacts>\n#include <TelepathyQt\/PendingOperation>\n#include <TelepathyQt\/PendingReady>\n\nAccount::Account(const Tp::AccountPtr &account, QObject *parent)\n : QObject(parent),\n m_account(account)\n{\n \/\/ Do nothing here. Wait for init() to be called to allow\n \/\/ signal\/slot connections to be set up first.\n kDebug() << \"Account Constructed.\";\n}\n\nvoid Account::init()\n{\n \/\/ Connect to all the signals that indicate changes in properties we care about.\n connect(m_account.data(),\n SIGNAL(nicknameChanged(QString)),\n SLOT(onNicknameChanged(QString)));\n connect(m_account.data(),\n SIGNAL(currentPresenceChanged(Tp::Presence)),\n SLOT(onCurrentPresenceChanged(Tp::Presence)));\n \/\/ connect(m_account.data(),\n \/\/ SIGNAL(avatarChanged(Tp::Avatar)),\n \/\/ SLOT(onAvatarChanged(Tp::Avatar)));\n \/\/ ...... and any other properties we want to sync...\n connect(m_account.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n\n \/\/ Emit a signal to notify the storage that a new account has been constructed\n \/\/ FIXME: Some IM Accounts don't have an ID as such, e.g. Link-Local-XMPP.\n emit created(m_account->objectPath(),\n m_account->parameters().value(QLatin1String(\"account\")).toString(),\n m_account->protocolName());\n\n \/\/ Simulate all the accounts properties being changed.\n onCurrentPresenceChanged(m_account->currentPresence());\n onNicknameChanged(m_account->nickname());\n\n \/\/ Now that the storage stuff is done, simulate emission of all the account signals.\n onConnectionChanged(m_account->connection());\n}\n\nAccount::~Account()\n{\n kDebug();\n}\n\nvoid Account::shutdown()\n{\n \/\/ Loop over all our children, and if they're Accounts, shut them down.\n foreach (Contact *contact, m_contacts.values()) {\n contact->shutdown();\n }\n\n kDebug();\n\n \/\/ Emit a signal to say we were destroyed.\n emit accountDestroyed(m_account->objectPath());\n}\n\nvoid Account::onConnectionChanged(const Tp::ConnectionPtr &connection)\n{\n if (! connection.isNull()) {\n m_connection = connection;\n\n if (!m_connection->contactManager()) {\n kWarning() << \"ContactManager is Null. Abort getting contacts.\";\n return;\n }\n\n \/\/add contacts as soon as the contact manager is ready.\n connect(m_connection->contactManager().data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n \/\/ Simulate a state change signal in case it is already ready.\n onContactManagerStateChanged(m_connection->contactManager()->state());\n\n } else {\n \/\/ Connection has gone down. Delete our pointer to it.\n m_connection.reset();\n kDebug() << \"Connection closed:\" << this;\n }\n}\n\nvoid Account::onContactManagerStateChanged(Tp::ContactListState state)\n{\n\/\/ kDebug() << \"contact manager state changed to \" << state;\n\n if (state == Tp::ContactListStateSuccess) {\n Tp::Contacts contacts = m_connection->contactManager()->allKnownContacts();\n\n \/\/ Create the hash containing all the contacts to notify the storage of the\n \/\/ full set of contacts that still exist when the account is connected.\n \/\/ This *must* be done before creating the contact wrapper objects.\n QList<QString> initialContacts;\n foreach (const Tp::ContactPtr &contact, contacts) {\n initialContacts.append(contact->id());\n }\n emit initialContactsLoaded(m_account->objectPath(), initialContacts);\n\n \/\/ Create wrapper objects for all the Contacts.\n foreach (const Tp::ContactPtr &contact, contacts) {\n onNewContact(contact);\n }\n\/\/ kDebug() << \"Loop over.\";\n }\n}\n\n\nvoid Account::onNicknameChanged(const QString& nickname)\n{\n emit nicknameChanged(m_account->objectPath(), nickname);\n}\n\nvoid Account::onCurrentPresenceChanged(const Tp::Presence &presence)\n{\n emit currentPresenceChanged(m_account->objectPath(), presence.barePresence());\n}\n\nvoid Account::onAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed)\n{\n \/\/ For each added contact, let's check if we already have a Contact wrapper for it\n foreach (const Tp::ContactPtr &contact, added) {\n if (!m_contacts.contains(contact)) {\n \/\/ It's a brand new one\n onNewContact(contact);\n }\n }\n\n \/\/ If contacts are removed, we don't actually need to do anything!\n Q_UNUSED(removed);\n}\n\nvoid Account::onNewContact(const Tp::ContactPtr &contact)\n{\n \/\/ Only create a new contact if one doesn't already exist.\n if (!m_contacts.contains(contact)) {\n \/\/ Create a new Contact wrapper objectPath\n Contact *c = new Contact(contact, this);\n\n \/\/ Insert it into the Hash.\n m_contacts.insert(contact, c);\n\n \/\/ Connect to all its signals\n connect(c,\n SIGNAL(created(QString)),\n SLOT(onContactCreated(QString)));\n connect(c,\n SIGNAL(contactDestroyed(QString,Tp::ContactPtr)),\n SLOT(onContactDestroyed(QString,Tp::ContactPtr)));\n connect(c,\n SIGNAL(aliasChanged(QString,QString)),\n SLOT(onContactAliasChanged(QString,QString)));\n connect(c,\n SIGNAL(presenceChanged(QString,Tp::SimplePresence)),\n SLOT(onContactPresenceChanged(QString,Tp::SimplePresence)));\n connect(c,\n SIGNAL(groupsChanged(QString,QStringList)),\n SLOT(onContactGroupsChanged(QString,QStringList)));\n connect(c,\n SIGNAL(blockStatusChanged(QString,bool)),\n SLOT(onContactBlockStatusChanged(QString,bool)));\n connect(c,\n SIGNAL(publishStateChanged(QString,Tp::Contact::PresenceState)),\n SLOT(onContactPublishStateChanged(QString,Tp::Contact::PresenceState)));\n connect(c,\n SIGNAL(subscriptionStateChanged(QString,Tp::Contact::PresenceState)),\n SLOT(onContactSubscriptionStateChanged(QString,Tp::Contact::PresenceState)));\n connect(c,\n SIGNAL(capabilitiesChanged(QString,Tp::ConnectionPtr,Tp::ContactCapabilities)),\n SLOT(onContactCapabilitiesChanged(QString,Tp::ConnectionPtr,Tp::ContactCapabilities)));\n connect(c,\n SIGNAL(avatarChanged(QString,Tp::AvatarData)),\n SLOT(onContactAvatarChanged(QString,Tp::AvatarData)));\n\n c->init();\n }\n}\n\nvoid Account::onContactCreated(const QString &id)\n{\n emit contactCreated(m_account->objectPath(), id);\n}\n\nvoid Account::onContactDestroyed(const QString &id, const Tp::ContactPtr &contact)\n{\n m_contacts.remove(contact);\n\n \/\/ Relay this signal to the controller\n emit contactDestroyed(m_account->objectPath(), id);\n}\n\nvoid Account::onContactAliasChanged(const QString &id, const QString &alias)\n{\n emit contactAliasChanged(m_account->objectPath(), id, alias);\n}\n\nvoid Account::onContactPresenceChanged(const QString &id, const Tp::SimplePresence &presence)\n{\n emit contactPresenceChanged(m_account->objectPath(), id, presence);\n}\n\nvoid Account::onContactGroupsChanged(const QString &id, const QStringList &groups)\n{\n emit contactGroupsChanged(m_account->objectPath(), id, groups);\n}\n\nvoid Account::onContactBlockStatusChanged(const QString &id, bool blocked)\n{\n emit contactBlockStatusChanged(m_account->objectPath(), id, blocked);\n}\n\nvoid Account::onContactPublishStateChanged(const QString &id, const Tp::Contact::PresenceState &state)\n{\n emit contactPublishStateChanged(m_account->objectPath(), id, state);\n}\n\nvoid Account::onContactSubscriptionStateChanged(const QString &id, const Tp::Contact::PresenceState &state)\n{\n emit contactSubscriptionStateChanged(m_account->objectPath(), id, state);\n}\n\nvoid Account::onContactCapabilitiesChanged(const QString &id, const Tp::ConnectionPtr &connection, const Tp::ContactCapabilities &capabilities)\n{\n emit contactCapabilitiesChanged(m_account->objectPath(), id, connection, capabilities);\n}\n\nvoid Account::onContactAvatarChanged(const QString &id, const Tp::AvatarData &avatar)\n{\n emit contactAvatarChanged(m_account->objectPath(), id, avatar);\n}\n\n\n\n#include \"account.moc\"\n\n<commit_msg>Use account service name if available<commit_after>\/*\n * This file is part of telepathy-nepomuk-service\n *\n * Copyright (C) 2009-2011 Collabora Ltd. <info@collabora.co.uk>\n * @author George Goldberg <george.goldberg@collabora.co.uk>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"account.h\"\n\n#include \"contact.h\"\n\n#include <KDebug>\n\n#include <TelepathyQt\/ContactManager>\n#include <TelepathyQt\/PendingContacts>\n#include <TelepathyQt\/PendingOperation>\n#include <TelepathyQt\/PendingReady>\n\nAccount::Account(const Tp::AccountPtr &account, QObject *parent)\n : QObject(parent),\n m_account(account)\n{\n \/\/ Do nothing here. Wait for init() to be called to allow\n \/\/ signal\/slot connections to be set up first.\n kDebug() << \"Account Constructed.\";\n}\n\nvoid Account::init()\n{\n \/\/ Connect to all the signals that indicate changes in properties we care about.\n connect(m_account.data(),\n SIGNAL(nicknameChanged(QString)),\n SLOT(onNicknameChanged(QString)));\n connect(m_account.data(),\n SIGNAL(currentPresenceChanged(Tp::Presence)),\n SLOT(onCurrentPresenceChanged(Tp::Presence)));\n \/\/ connect(m_account.data(),\n \/\/ SIGNAL(avatarChanged(Tp::Avatar)),\n \/\/ SLOT(onAvatarChanged(Tp::Avatar)));\n \/\/ ...... and any other properties we want to sync...\n connect(m_account.data(),\n SIGNAL(connectionChanged(Tp::ConnectionPtr)),\n SLOT(onConnectionChanged(Tp::ConnectionPtr)));\n\n QString protocolName = m_account->serviceName().isEmpty() ? m_account->protocolName() : m_account->serviceName();\n \/\/ Emit a signal to notify the storage that a new account has been constructed\n \/\/ FIXME: Some IM Accounts don't have an ID as such, e.g. Link-Local-XMPP.\n emit created(m_account->objectPath(),\n m_account->parameters().value(QLatin1String(\"account\")).toString(),\n protocolName);\n\n \/\/ Simulate all the accounts properties being changed.\n onCurrentPresenceChanged(m_account->currentPresence());\n onNicknameChanged(m_account->nickname());\n\n \/\/ Now that the storage stuff is done, simulate emission of all the account signals.\n onConnectionChanged(m_account->connection());\n}\n\nAccount::~Account()\n{\n kDebug();\n}\n\nvoid Account::shutdown()\n{\n \/\/ Loop over all our children, and if they're Accounts, shut them down.\n foreach (Contact *contact, m_contacts.values()) {\n contact->shutdown();\n }\n\n kDebug();\n\n \/\/ Emit a signal to say we were destroyed.\n emit accountDestroyed(m_account->objectPath());\n}\n\nvoid Account::onConnectionChanged(const Tp::ConnectionPtr &connection)\n{\n if (! connection.isNull()) {\n m_connection = connection;\n\n if (!m_connection->contactManager()) {\n kWarning() << \"ContactManager is Null. Abort getting contacts.\";\n return;\n }\n\n \/\/add contacts as soon as the contact manager is ready.\n connect(m_connection->contactManager().data(),\n SIGNAL(stateChanged(Tp::ContactListState)),\n SLOT(onContactManagerStateChanged(Tp::ContactListState)));\n \/\/ Simulate a state change signal in case it is already ready.\n onContactManagerStateChanged(m_connection->contactManager()->state());\n\n } else {\n \/\/ Connection has gone down. Delete our pointer to it.\n m_connection.reset();\n kDebug() << \"Connection closed:\" << this;\n }\n}\n\nvoid Account::onContactManagerStateChanged(Tp::ContactListState state)\n{\n\/\/ kDebug() << \"contact manager state changed to \" << state;\n\n if (state == Tp::ContactListStateSuccess) {\n Tp::Contacts contacts = m_connection->contactManager()->allKnownContacts();\n\n \/\/ Create the hash containing all the contacts to notify the storage of the\n \/\/ full set of contacts that still exist when the account is connected.\n \/\/ This *must* be done before creating the contact wrapper objects.\n QList<QString> initialContacts;\n foreach (const Tp::ContactPtr &contact, contacts) {\n initialContacts.append(contact->id());\n }\n emit initialContactsLoaded(m_account->objectPath(), initialContacts);\n\n \/\/ Create wrapper objects for all the Contacts.\n foreach (const Tp::ContactPtr &contact, contacts) {\n onNewContact(contact);\n }\n\/\/ kDebug() << \"Loop over.\";\n }\n}\n\n\nvoid Account::onNicknameChanged(const QString& nickname)\n{\n emit nicknameChanged(m_account->objectPath(), nickname);\n}\n\nvoid Account::onCurrentPresenceChanged(const Tp::Presence &presence)\n{\n emit currentPresenceChanged(m_account->objectPath(), presence.barePresence());\n}\n\nvoid Account::onAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed)\n{\n \/\/ For each added contact, let's check if we already have a Contact wrapper for it\n foreach (const Tp::ContactPtr &contact, added) {\n if (!m_contacts.contains(contact)) {\n \/\/ It's a brand new one\n onNewContact(contact);\n }\n }\n\n \/\/ If contacts are removed, we don't actually need to do anything!\n Q_UNUSED(removed);\n}\n\nvoid Account::onNewContact(const Tp::ContactPtr &contact)\n{\n \/\/ Only create a new contact if one doesn't already exist.\n if (!m_contacts.contains(contact)) {\n \/\/ Create a new Contact wrapper objectPath\n Contact *c = new Contact(contact, this);\n\n \/\/ Insert it into the Hash.\n m_contacts.insert(contact, c);\n\n \/\/ Connect to all its signals\n connect(c,\n SIGNAL(created(QString)),\n SLOT(onContactCreated(QString)));\n connect(c,\n SIGNAL(contactDestroyed(QString,Tp::ContactPtr)),\n SLOT(onContactDestroyed(QString,Tp::ContactPtr)));\n connect(c,\n SIGNAL(aliasChanged(QString,QString)),\n SLOT(onContactAliasChanged(QString,QString)));\n connect(c,\n SIGNAL(presenceChanged(QString,Tp::SimplePresence)),\n SLOT(onContactPresenceChanged(QString,Tp::SimplePresence)));\n connect(c,\n SIGNAL(groupsChanged(QString,QStringList)),\n SLOT(onContactGroupsChanged(QString,QStringList)));\n connect(c,\n SIGNAL(blockStatusChanged(QString,bool)),\n SLOT(onContactBlockStatusChanged(QString,bool)));\n connect(c,\n SIGNAL(publishStateChanged(QString,Tp::Contact::PresenceState)),\n SLOT(onContactPublishStateChanged(QString,Tp::Contact::PresenceState)));\n connect(c,\n SIGNAL(subscriptionStateChanged(QString,Tp::Contact::PresenceState)),\n SLOT(onContactSubscriptionStateChanged(QString,Tp::Contact::PresenceState)));\n connect(c,\n SIGNAL(capabilitiesChanged(QString,Tp::ConnectionPtr,Tp::ContactCapabilities)),\n SLOT(onContactCapabilitiesChanged(QString,Tp::ConnectionPtr,Tp::ContactCapabilities)));\n connect(c,\n SIGNAL(avatarChanged(QString,Tp::AvatarData)),\n SLOT(onContactAvatarChanged(QString,Tp::AvatarData)));\n\n c->init();\n }\n}\n\nvoid Account::onContactCreated(const QString &id)\n{\n emit contactCreated(m_account->objectPath(), id);\n}\n\nvoid Account::onContactDestroyed(const QString &id, const Tp::ContactPtr &contact)\n{\n m_contacts.remove(contact);\n\n \/\/ Relay this signal to the controller\n emit contactDestroyed(m_account->objectPath(), id);\n}\n\nvoid Account::onContactAliasChanged(const QString &id, const QString &alias)\n{\n emit contactAliasChanged(m_account->objectPath(), id, alias);\n}\n\nvoid Account::onContactPresenceChanged(const QString &id, const Tp::SimplePresence &presence)\n{\n emit contactPresenceChanged(m_account->objectPath(), id, presence);\n}\n\nvoid Account::onContactGroupsChanged(const QString &id, const QStringList &groups)\n{\n emit contactGroupsChanged(m_account->objectPath(), id, groups);\n}\n\nvoid Account::onContactBlockStatusChanged(const QString &id, bool blocked)\n{\n emit contactBlockStatusChanged(m_account->objectPath(), id, blocked);\n}\n\nvoid Account::onContactPublishStateChanged(const QString &id, const Tp::Contact::PresenceState &state)\n{\n emit contactPublishStateChanged(m_account->objectPath(), id, state);\n}\n\nvoid Account::onContactSubscriptionStateChanged(const QString &id, const Tp::Contact::PresenceState &state)\n{\n emit contactSubscriptionStateChanged(m_account->objectPath(), id, state);\n}\n\nvoid Account::onContactCapabilitiesChanged(const QString &id, const Tp::ConnectionPtr &connection, const Tp::ContactCapabilities &capabilities)\n{\n emit contactCapabilitiesChanged(m_account->objectPath(), id, connection, capabilities);\n}\n\nvoid Account::onContactAvatarChanged(const QString &id, const Tp::AvatarData &avatar)\n{\n emit contactAvatarChanged(m_account->objectPath(), id, avatar);\n}\n\n\n\n#include \"account.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: autonamecache.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: kz $ $Date: 2006-01-31 18:35:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <unotools\/transliterationwrapper.hxx>\n\n#include \"autonamecache.hxx\"\n#include \"dociter.hxx\"\n#include \"cell.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nScAutoNameCache::ScAutoNameCache( ScDocument* pD ) :\n pDoc( pD ),\n nCurrentTab( 0 ) \/\/ doesn't matter - aNames is empty\n{\n}\n\nScAutoNameCache::~ScAutoNameCache()\n{\n}\n\nconst ScAutoNameAddresses& ScAutoNameCache::GetNameOccurences( const String& rName, SCTAB nTab )\n{\n if ( nTab != nCurrentTab )\n {\n \/\/ the lists are valid only for one sheet, so they are cleared when another sheet is used\n aNames.clear();\n nCurrentTab = nTab;\n }\n\n ScAutoNameHashMap::const_iterator aFound = aNames.find( rName );\n if ( aFound != aNames.end() )\n return aFound->second; \/\/ already initialized\n\n ScAutoNameAddresses& rAddresses = aNames[rName];\n\n ScCellIterator aIter( pDoc, ScRange( 0, 0, nCurrentTab, MAXCOL, MAXROW, nCurrentTab ) );\n for ( ScBaseCell* pCell = aIter.GetFirst(); pCell; pCell = aIter.GetNext() )\n {\n \/\/ don't check code length here, always use the stored result\n \/\/ (AutoCalc is disabled during CompileXML)\n\n if ( pCell->HasStringData() )\n {\n String aStr;\n CellType eType = pCell->GetCellType();\n switch ( eType )\n {\n case CELLTYPE_STRING:\n ((ScStringCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_FORMULA:\n ((ScFormulaCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_EDIT:\n ((ScEditCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_NONE:\n case CELLTYPE_VALUE:\n case CELLTYPE_NOTE:\n case CELLTYPE_SYMBOLS:\n case CELLTYPE_DESTROYED:\n ; \/\/ nothing, prevent compiler warning\n break;\n }\n if ( ScGlobal::pTransliteration->isEqual( aStr, rName ) )\n {\n rAddresses.push_back( ScAddress( aIter.GetCol(), aIter.GetRow(), aIter.GetTab() ) );\n }\n }\n }\n\n return rAddresses;\n}\n\n<commit_msg>INTEGRATION: CWS pchfix01 (1.2.138); FILE MERGED 2006\/07\/12 10:01:28 kaib 1.2.138.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: autonamecache.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 10:47:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <unotools\/transliterationwrapper.hxx>\n\n#include \"autonamecache.hxx\"\n#include \"dociter.hxx\"\n#include \"cell.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nScAutoNameCache::ScAutoNameCache( ScDocument* pD ) :\n pDoc( pD ),\n nCurrentTab( 0 ) \/\/ doesn't matter - aNames is empty\n{\n}\n\nScAutoNameCache::~ScAutoNameCache()\n{\n}\n\nconst ScAutoNameAddresses& ScAutoNameCache::GetNameOccurences( const String& rName, SCTAB nTab )\n{\n if ( nTab != nCurrentTab )\n {\n \/\/ the lists are valid only for one sheet, so they are cleared when another sheet is used\n aNames.clear();\n nCurrentTab = nTab;\n }\n\n ScAutoNameHashMap::const_iterator aFound = aNames.find( rName );\n if ( aFound != aNames.end() )\n return aFound->second; \/\/ already initialized\n\n ScAutoNameAddresses& rAddresses = aNames[rName];\n\n ScCellIterator aIter( pDoc, ScRange( 0, 0, nCurrentTab, MAXCOL, MAXROW, nCurrentTab ) );\n for ( ScBaseCell* pCell = aIter.GetFirst(); pCell; pCell = aIter.GetNext() )\n {\n \/\/ don't check code length here, always use the stored result\n \/\/ (AutoCalc is disabled during CompileXML)\n\n if ( pCell->HasStringData() )\n {\n String aStr;\n CellType eType = pCell->GetCellType();\n switch ( eType )\n {\n case CELLTYPE_STRING:\n ((ScStringCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_FORMULA:\n ((ScFormulaCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_EDIT:\n ((ScEditCell*)pCell)->GetString( aStr );\n break;\n case CELLTYPE_NONE:\n case CELLTYPE_VALUE:\n case CELLTYPE_NOTE:\n case CELLTYPE_SYMBOLS:\n case CELLTYPE_DESTROYED:\n ; \/\/ nothing, prevent compiler warning\n break;\n }\n if ( ScGlobal::pTransliteration->isEqual( aStr, rName ) )\n {\n rAddresses.push_back( ScAddress( aIter.GetCol(), aIter.GetRow(), aIter.GetTab() ) );\n }\n }\n }\n\n return rAddresses;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"feedconfigstore.h\"\n#include \"feedstates.h\"\n#include \"ifeedview.h\"\n#include \"ireplayconfig.h\"\n#include \"replaypacketdispatcher.h\"\n#include <vespa\/searchcore\/proton\/bucketdb\/ibucketdbhandler.h>\n#include <vespa\/searchcore\/proton\/feedoperation\/operations.h>\n#include <vespa\/searchcore\/proton\/common\/eventlogger.h>\n#include <vespa\/searchlib\/common\/idestructorcallback.h>\n#include <vespa\/vespalib\/util\/closuretask.h>\n#include <vespa\/vespalib\/util\/lambdatask.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.feedstates\");\n\nusing search::transactionlog::Packet;\nusing search::transactionlog::client::RPC;\nusing search::SerialNum;\nusing vespalib::Executor;\nusing vespalib::makeClosure;\nusing vespalib::makeLambdaTask;\nusing vespalib::makeTask;\nusing vespalib::make_string;\nusing proton::bucketdb::IBucketDBHandler;\n\nnamespace proton {\n\nnamespace {\ntypedef vespalib::Closure1<const Packet::Entry &>::UP EntryHandler;\n\nconst search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000;\n\nvoid\nhandleProgress(TlsReplayProgress &progress, SerialNum currentSerial)\n{\n progress.updateCurrent(currentSerial);\n if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) ||\n (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0)))\n {\n EventLogger::transactionLogReplayProgress(progress.getDomainName(),\n progress.getProgress(),\n progress.getFirst(),\n progress.getLast(),\n progress.getCurrent());\n }\n}\n\nvoid\nhandlePacket(PacketWrapper & wrap, EntryHandler entryHandler)\n{\n vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size());\n while ( !handle.empty() ) {\n Packet::Entry entry;\n entry.deserialize(handle);\n entryHandler->call(entry);\n if (wrap.progress != nullptr) {\n handleProgress(*wrap.progress, entry.serial());\n }\n }\n wrap.result = RPC::OK;\n wrap.gate.countDown();\n}\n\nclass TransactionLogReplayPacketHandler : public IReplayPacketHandler {\n IFeedView *& _feed_view_ptr; \/\/ Pointer can be changed in executor thread.\n IBucketDBHandler &_bucketDBHandler;\n IReplayConfig &_replay_config;\n FeedConfigStore &_config_store;\n CommitTimeTracker _commitTimeTracker;\n\npublic:\n TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr,\n IBucketDBHandler &bucketDBHandler,\n IReplayConfig &replay_config,\n FeedConfigStore &config_store)\n : _feed_view_ptr(feed_view_ptr),\n _bucketDBHandler(bucketDBHandler),\n _replay_config(replay_config),\n _config_store(config_store),\n _commitTimeTracker(100ms)\n { }\n\n ~TransactionLogReplayPacketHandler() override = default;\n\n void replay(const PutOperation &op) override {\n _feed_view_ptr->handlePut(FeedToken(), op);\n }\n void replay(const RemoveOperation &op) override {\n _feed_view_ptr->handleRemove(FeedToken(), op);\n }\n void replay(const UpdateOperation &op) override {\n _feed_view_ptr->handleUpdate(FeedToken(), op);\n }\n void replay(const NoopOperation &) override {} \/\/ ignored\n void replay(const NewConfigOperation &op) override {\n _replay_config.replayConfig(op.getSerialNum());\n }\n\n void replay(const DeleteBucketOperation &op) override {\n _feed_view_ptr->handleDeleteBucket(op);\n }\n void replay(const SplitBucketOperation &op) override {\n _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(),\n op.getTarget1(), op.getTarget2());\n }\n void replay(const JoinBucketsOperation &op) override {\n _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(),\n op.getSource2(), op.getTarget());\n }\n void replay(const PruneRemovedDocumentsOperation &op) override {\n _feed_view_ptr->handlePruneRemovedDocuments(op);\n }\n void replay(const MoveOperation &op) override {\n _feed_view_ptr->handleMove(op, search::IDestructorCallback::SP());\n }\n void replay(const CreateBucketOperation &) override {\n }\n void replay(const CompactLidSpaceOperation &op) override {\n _feed_view_ptr->handleCompactLidSpace(op);\n }\n NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override {\n return _config_store;\n }\n const document::DocumentTypeRepo &getDeserializeRepo() override {\n return *_feed_view_ptr->getDocumentTypeRepo();\n }\n void optionalCommit(search::SerialNum serialNum) override {\n if (_commitTimeTracker.needCommit()) {\n _feed_view_ptr->forceCommit(serialNum);\n }\n }\n};\n\nvoid startDispatch(IReplayPacketHandler *packet_handler, const Packet::Entry &entry) {\n \/\/ Called by handlePacket() in executor thread.\n LOG(spam, \"replay packet entry: entrySerial(%\" PRIu64 \"), entryType(%u)\", entry.serial(), entry.type());\n\n ReplayPacketDispatcher dispatcher(*packet_handler);\n dispatcher.replayEntry(entry);\n packet_handler->optionalCommit(entry.serial());\n}\n\n} \/\/ namespace\n\nReplayTransactionLogState::ReplayTransactionLogState(\n const vespalib::string &name,\n IFeedView *& feed_view_ptr,\n IBucketDBHandler &bucketDBHandler,\n IReplayConfig &replay_config,\n FeedConfigStore &config_store)\n : FeedState(REPLAY_TRANSACTION_LOG),\n _doc_type_name(name),\n _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store))\n{ }\n\nReplayTransactionLogState::~ReplayTransactionLogState() = default;\n\nvoid\nReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) {\n EntryHandler closure = makeClosure(&startDispatch, _packet_handler.get());\n executor.execute(makeLambdaTask([wrap = wrap, dispatch = std::move(closure)] () mutable { handlePacket(*wrap, std::move(dispatch)); }));\n}\n\n} \/\/ namespace proton\n<commit_msg>Commit every 5ms during TLS replay<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"feedconfigstore.h\"\n#include \"feedstates.h\"\n#include \"ifeedview.h\"\n#include \"ireplayconfig.h\"\n#include \"replaypacketdispatcher.h\"\n#include <vespa\/searchcore\/proton\/bucketdb\/ibucketdbhandler.h>\n#include <vespa\/searchcore\/proton\/feedoperation\/operations.h>\n#include <vespa\/searchcore\/proton\/common\/eventlogger.h>\n#include <vespa\/searchlib\/common\/idestructorcallback.h>\n#include <vespa\/vespalib\/util\/closuretask.h>\n#include <vespa\/vespalib\/util\/lambdatask.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.feedstates\");\n\nusing search::transactionlog::Packet;\nusing search::transactionlog::client::RPC;\nusing search::SerialNum;\nusing vespalib::Executor;\nusing vespalib::makeClosure;\nusing vespalib::makeLambdaTask;\nusing vespalib::makeTask;\nusing vespalib::make_string;\nusing proton::bucketdb::IBucketDBHandler;\n\nnamespace proton {\n\nnamespace {\ntypedef vespalib::Closure1<const Packet::Entry &>::UP EntryHandler;\n\nconst search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000;\n\nvoid\nhandleProgress(TlsReplayProgress &progress, SerialNum currentSerial)\n{\n progress.updateCurrent(currentSerial);\n if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) ||\n (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0)))\n {\n EventLogger::transactionLogReplayProgress(progress.getDomainName(),\n progress.getProgress(),\n progress.getFirst(),\n progress.getLast(),\n progress.getCurrent());\n }\n}\n\nvoid\nhandlePacket(PacketWrapper & wrap, EntryHandler entryHandler)\n{\n vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size());\n while ( !handle.empty() ) {\n Packet::Entry entry;\n entry.deserialize(handle);\n entryHandler->call(entry);\n if (wrap.progress != nullptr) {\n handleProgress(*wrap.progress, entry.serial());\n }\n }\n wrap.result = RPC::OK;\n wrap.gate.countDown();\n}\n\nclass TransactionLogReplayPacketHandler : public IReplayPacketHandler {\n IFeedView *& _feed_view_ptr; \/\/ Pointer can be changed in executor thread.\n IBucketDBHandler &_bucketDBHandler;\n IReplayConfig &_replay_config;\n FeedConfigStore &_config_store;\n CommitTimeTracker _commitTimeTracker;\n\npublic:\n TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr,\n IBucketDBHandler &bucketDBHandler,\n IReplayConfig &replay_config,\n FeedConfigStore &config_store)\n : _feed_view_ptr(feed_view_ptr),\n _bucketDBHandler(bucketDBHandler),\n _replay_config(replay_config),\n _config_store(config_store),\n _commitTimeTracker(5ms)\n { }\n\n ~TransactionLogReplayPacketHandler() override = default;\n\n void replay(const PutOperation &op) override {\n _feed_view_ptr->handlePut(FeedToken(), op);\n }\n void replay(const RemoveOperation &op) override {\n _feed_view_ptr->handleRemove(FeedToken(), op);\n }\n void replay(const UpdateOperation &op) override {\n _feed_view_ptr->handleUpdate(FeedToken(), op);\n }\n void replay(const NoopOperation &) override {} \/\/ ignored\n void replay(const NewConfigOperation &op) override {\n _replay_config.replayConfig(op.getSerialNum());\n }\n\n void replay(const DeleteBucketOperation &op) override {\n _feed_view_ptr->handleDeleteBucket(op);\n }\n void replay(const SplitBucketOperation &op) override {\n _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(),\n op.getTarget1(), op.getTarget2());\n }\n void replay(const JoinBucketsOperation &op) override {\n _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(),\n op.getSource2(), op.getTarget());\n }\n void replay(const PruneRemovedDocumentsOperation &op) override {\n _feed_view_ptr->handlePruneRemovedDocuments(op);\n }\n void replay(const MoveOperation &op) override {\n _feed_view_ptr->handleMove(op, search::IDestructorCallback::SP());\n }\n void replay(const CreateBucketOperation &) override {\n }\n void replay(const CompactLidSpaceOperation &op) override {\n _feed_view_ptr->handleCompactLidSpace(op);\n }\n NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override {\n return _config_store;\n }\n const document::DocumentTypeRepo &getDeserializeRepo() override {\n return *_feed_view_ptr->getDocumentTypeRepo();\n }\n void optionalCommit(search::SerialNum serialNum) override {\n if (_commitTimeTracker.needCommit()) {\n _feed_view_ptr->forceCommit(serialNum);\n }\n }\n};\n\nvoid startDispatch(IReplayPacketHandler *packet_handler, const Packet::Entry &entry) {\n \/\/ Called by handlePacket() in executor thread.\n LOG(spam, \"replay packet entry: entrySerial(%\" PRIu64 \"), entryType(%u)\", entry.serial(), entry.type());\n\n ReplayPacketDispatcher dispatcher(*packet_handler);\n dispatcher.replayEntry(entry);\n packet_handler->optionalCommit(entry.serial());\n}\n\n} \/\/ namespace\n\nReplayTransactionLogState::ReplayTransactionLogState(\n const vespalib::string &name,\n IFeedView *& feed_view_ptr,\n IBucketDBHandler &bucketDBHandler,\n IReplayConfig &replay_config,\n FeedConfigStore &config_store)\n : FeedState(REPLAY_TRANSACTION_LOG),\n _doc_type_name(name),\n _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store))\n{ }\n\nReplayTransactionLogState::~ReplayTransactionLogState() = default;\n\nvoid\nReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) {\n EntryHandler closure = makeClosure(&startDispatch, _packet_handler.get());\n executor.execute(makeLambdaTask([wrap = wrap, dispatch = std::move(closure)] () mutable { handlePacket(*wrap, std::move(dispatch)); }));\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at most\n\/\/ Space: O(n * (C(2n, n) - C(2n, n - 1)))\n\nclass Solution {\n public:\n vector<int> diffWaysToCompute(string input) {\n vector<vector<vector<int>>> lookup(input.length() + 1,\n vector<vector<int>>(input.length() + 1, vector<int>()));\n return diffWaysToComputeRecu(input, 0, input.length(), lookup);\n }\n\n vector<int> diffWaysToComputeRecu(const string& input,\n const int start, const int end,\n vector<vector<vector<int>>>& lookup) {\n if (!lookup[start][end].empty()) {\n return lookup[start][end];\n }\n vector<int> result;\n for (int i = start; i < end; ++i) {\n const auto cur = input[i];\n if (cur == '+' || cur == '-' || cur == '*') {\n vector<int> left = move(diffWaysToComputeRecu(input, start, i, lookup));\n vector<int> right = move(diffWaysToComputeRecu(input, i + 1, end, lookup));\n for (const auto& num1 : left) {\n for (const auto& num2 : right) {\n if (cur == '+') {\n result.emplace_back(num1 + num2);\n } else if (cur == '-') {\n result.emplace_back(num1 - num2);\n } else {\n result.emplace_back(num1 * num2);\n }\n }\n }\n }\n }\n \/\/ If the input string contains only number.\n if (result.empty()) {\n result.emplace_back(stoi(input.substr(start, end - start)));\n }\n lookup[start][end] = move(result);\n return lookup[start][end];\n }\n};\n\n\/\/ Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at least\n\/\/ Space: O(C(2n, n) - C(2n, n - 1))\nclass Solution2 {\n public:\n vector<int> diffWaysToCompute(string input) {\n vector<int> result;\n for (int i = 0; i < input.size(); ++i) {\n const auto cur = input[i];\n if (cur == '+' || cur == '-' || cur == '*') {\n vector<int> left = move(diffWaysToCompute(input.substr(0, i)));\n vector<int> right = move(diffWaysToCompute(input.substr(i + 1)));\n for (const auto& num1 : left) {\n for (const auto& num2 : right) {\n if (cur == '+') {\n result.emplace_back(num1 + num2);\n } else if (cur == '-') {\n result.emplace_back(num1 - num2);\n } else {\n result.emplace_back(num1 * num2);\n }\n }\n }\n }\n }\n \/\/ If the input string contains only number.\n if (result.empty()) {\n result.emplace_back(stoi(input));\n }\n return result;\n }\n};\n<commit_msg>Update different-ways-to-add-parentheses.cpp<commit_after>\/\/ Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at most\n\/\/ Space: O(n * (C(2n, n) - C(2n, n - 1)))\n\nclass Solution {\n public:\n vector<int> diffWaysToCompute(string input) {\n vector<vector<vector<int>>> lookup(input.length() + 1,\n vector<vector<int>>(input.length() + 1));\n return diffWaysToComputeRecu(input, 0, input.length(), lookup);\n }\n\n vector<int> diffWaysToComputeRecu(const string& input,\n const int start, const int end,\n vector<vector<vector<int>>>& lookup) {\n if (!lookup[start][end].empty()) {\n return lookup[start][end];\n }\n vector<int> result;\n for (int i = start; i < end; ++i) {\n const auto cur = input[i];\n if (cur == '+' || cur == '-' || cur == '*') {\n vector<int> left = move(diffWaysToComputeRecu(input, start, i, lookup));\n vector<int> right = move(diffWaysToComputeRecu(input, i + 1, end, lookup));\n for (const auto& num1 : left) {\n for (const auto& num2 : right) {\n if (cur == '+') {\n result.emplace_back(num1 + num2);\n } else if (cur == '-') {\n result.emplace_back(num1 - num2);\n } else {\n result.emplace_back(num1 * num2);\n }\n }\n }\n }\n }\n \/\/ If the input string contains only number.\n if (result.empty()) {\n result.emplace_back(stoi(input.substr(start, end - start)));\n }\n lookup[start][end] = move(result);\n return lookup[start][end];\n }\n};\n\n\/\/ Time: O(n * (C(2n, n) - C(2n, n - 1))), this is at least\n\/\/ Space: O(C(2n, n) - C(2n, n - 1))\nclass Solution2 {\n public:\n vector<int> diffWaysToCompute(string input) {\n vector<int> result;\n for (int i = 0; i < input.size(); ++i) {\n const auto cur = input[i];\n if (cur == '+' || cur == '-' || cur == '*') {\n vector<int> left = move(diffWaysToCompute(input.substr(0, i)));\n vector<int> right = move(diffWaysToCompute(input.substr(i + 1)));\n for (const auto& num1 : left) {\n for (const auto& num2 : right) {\n if (cur == '+') {\n result.emplace_back(num1 + num2);\n } else if (cur == '-') {\n result.emplace_back(num1 - num2);\n } else {\n result.emplace_back(num1 * num2);\n }\n }\n }\n }\n }\n \/\/ If the input string contains only number.\n if (result.empty()) {\n result.emplace_back(stoi(input));\n }\n return result;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of telepathy-nepomuk-service\n *\n * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>\n * @author George Goldberg <george.goldberg@collabora.co.uk>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"contact.h\"\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ContactCapabilities>\n#include <TelepathyQt4\/ContactManager>\n\n#include <KDebug>\n\nContact::Contact(const Tp::ContactPtr &contact, QObject *parent)\n : QObject(parent),\n m_contact(contact)\n{\n \/\/ Do nothing here because the signals\/slots need to be connected in our\n \/\/ parent class before we start doing stuff.\n kDebug() << \"Creating new contact\";\n}\n\nvoid Contact::init()\n{\n \/\/ We need to destroy ourself if the connection goes down.\n connect(m_contact->manager()->connection().data(),\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(deleteLater()));\n\n \/\/ Connect to signals for all properties we want to keep synced.\n connect(m_contact.data(),\n SIGNAL(presenceChanged(Tp::Presence)),\n SLOT(onPresenceChanged(Tp::Presence)));\n connect(m_contact.data(),\n SIGNAL(aliasChanged(QString)),\n SLOT(onAliasChanged(QString)));\n connect(m_contact.data(),\n SIGNAL(addedToGroup(QString)),\n SLOT(onAddedToGroup(QString)));\n connect(m_contact.data(),\n SIGNAL(removedFromGroup(QString)),\n SLOT(onRemovedFromGroup(QString)));\n connect(m_contact.data(),\n SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),\n SLOT(onCapabilitiesChanged(Tp::ContactCapabilities)));\n connect(m_contact.data(),\n SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState,Tp::Channel::GroupMemberChangeDetails)),\n SLOT(onSubscriptionStateChanged(Tp::Contact::PresenceState)));\n connect(m_contact.data(),\n SIGNAL(publishStateChanged(Tp::Contact::PresenceState,Tp::Channel::GroupMemberChangeDetails)),\n SLOT(onPublishStateChanged(Tp::Contact::PresenceState)));\n connect(m_contact.data(),\n SIGNAL(blockStatusChanged(bool,Tp::Channel::GroupMemberChangeDetails)),\n SLOT(onBlockStatusChanged(bool)));\n \/\/ FIXME: Connect to any other signals of sync-worthy properties here.\n\n \/\/ Emit a signal to notify the controller that a new contact has been created.\n emit created(m_contact->id());\n\n \/\/ Synthesize all the properties being changed\n \/\/ FIXME: Make this bit correct\n \/*\n onPublishStateChanged(m_contact->publishState());\n onSubscriptionStateChanged(m_contact->subscriptionState());\n onBlockStatusChanged(m_contact->isBlocked());\n if (contact->capabilities() != 0) {\n onCapabilitiesChanged(m_contact->capabilities());\n }\n *\/\n}\n\nContact::~Contact()\n{\n kDebug();\n}\n\nvoid Contact::shutdown()\n{\n \/\/ Signal this contact is destroyed so it can be removed from the Hash.\n emit contactDestroyed(m_contact->id(), m_contact);\n}\n\n\nvoid Contact::onAliasChanged(const QString& alias)\n{\n emit aliasChanged(m_contact->id(), alias);\n}\n\nvoid Contact::onPresenceChanged(const Tp::Presence &presence)\n{\n emit presenceChanged(m_contact->id(), presence.barePresence());\n}\n\nvoid Contact::onAddedToGroup(const QString &group)\n{\n kDebug() << \"On added to group \" << group;\n\n emit groupsChanged(m_contact->id(), m_contact->groups());\n}\n\nvoid Contact::onRemovedFromGroup(const QString &group)\n{\n kDebug() << \"On removed from group \" << group;\n\n emit groupsChanged(m_contact->id(), m_contact->groups());\n}\n\nvoid Contact::onBlockStatusChanged(bool blocked)\n{\n emit blockStatusChanged(m_contact->id(), blocked);\n}\n\nvoid Contact::onPublishStateChanged(Tp::Contact::PresenceState state)\n{\n emit publishStateChanged(m_contact->id(), state);\n}\n\nvoid Contact::onSubscriptionStateChanged(Tp::Contact::PresenceState state)\n{\n emit subscriptionStateChanged(m_contact->id(), state);\n}\n\nvoid Contact::onCapabilitiesChanged(const Tp::ContactCapabilities &capabilities)\n{\n \/\/ FIXME: Implement me!\n}\n\n\n#include \"contact.moc\"\n\n<commit_msg>Stop using deprecated signals on Contact class.<commit_after>\/*\n * This file is part of telepathy-nepomuk-service\n *\n * Copyright (C) 2010 Collabora Ltd. <info@collabora.co.uk>\n * @author George Goldberg <george.goldberg@collabora.co.uk>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"contact.h\"\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/ContactCapabilities>\n#include <TelepathyQt4\/ContactManager>\n\n#include <KDebug>\n\nContact::Contact(const Tp::ContactPtr &contact, QObject *parent)\n : QObject(parent),\n m_contact(contact)\n{\n \/\/ Do nothing here because the signals\/slots need to be connected in our\n \/\/ parent class before we start doing stuff.\n kDebug() << \"Creating new contact\";\n}\n\nvoid Contact::init()\n{\n \/\/ We need to destroy ourself if the connection goes down.\n connect(m_contact->manager()->connection().data(),\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(deleteLater()));\n\n \/\/ Connect to signals for all properties we want to keep synced.\n connect(m_contact.data(),\n SIGNAL(presenceChanged(Tp::Presence)),\n SLOT(onPresenceChanged(Tp::Presence)));\n connect(m_contact.data(),\n SIGNAL(aliasChanged(QString)),\n SLOT(onAliasChanged(QString)));\n connect(m_contact.data(),\n SIGNAL(addedToGroup(QString)),\n SLOT(onAddedToGroup(QString)));\n connect(m_contact.data(),\n SIGNAL(removedFromGroup(QString)),\n SLOT(onRemovedFromGroup(QString)));\n connect(m_contact.data(),\n SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),\n SLOT(onCapabilitiesChanged(Tp::ContactCapabilities)));\n connect(m_contact.data(),\n SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)),\n SLOT(onSubscriptionStateChanged(Tp::Contact::PresenceState)));\n connect(m_contact.data(),\n SIGNAL(publishStateChanged(Tp::Contact::PresenceState, QString)),\n SLOT(onPublishStateChanged(Tp::Contact::PresenceState)));\n \/\/ FIXME: Add support to the ontology for the message QString.\n connect(m_contact.data(),\n SIGNAL(blockStatusChanged(bool)),\n SLOT(onBlockStatusChanged(bool)));\n \/\/ FIXME: Connect to any other signals of sync-worthy properties here.\n\n \/\/ Emit a signal to notify the controller that a new contact has been created.\n emit created(m_contact->id());\n\n \/\/ Synthesize all the properties being changed\n \/\/ FIXME: Make this bit correct\n \/*\n onPublishStateChanged(m_contact->publishState());\n onSubscriptionStateChanged(m_contact->subscriptionState());\n onBlockStatusChanged(m_contact->isBlocked());\n if (contact->capabilities() != 0) {\n onCapabilitiesChanged(m_contact->capabilities());\n }\n *\/\n}\n\nContact::~Contact()\n{\n kDebug();\n}\n\nvoid Contact::shutdown()\n{\n \/\/ Signal this contact is destroyed so it can be removed from the Hash.\n emit contactDestroyed(m_contact->id(), m_contact);\n}\n\n\nvoid Contact::onAliasChanged(const QString& alias)\n{\n emit aliasChanged(m_contact->id(), alias);\n}\n\nvoid Contact::onPresenceChanged(const Tp::Presence &presence)\n{\n emit presenceChanged(m_contact->id(), presence.barePresence());\n}\n\nvoid Contact::onAddedToGroup(const QString &group)\n{\n kDebug() << \"On added to group \" << group;\n\n emit groupsChanged(m_contact->id(), m_contact->groups());\n}\n\nvoid Contact::onRemovedFromGroup(const QString &group)\n{\n kDebug() << \"On removed from group \" << group;\n\n emit groupsChanged(m_contact->id(), m_contact->groups());\n}\n\nvoid Contact::onBlockStatusChanged(bool blocked)\n{\n emit blockStatusChanged(m_contact->id(), blocked);\n}\n\nvoid Contact::onPublishStateChanged(Tp::Contact::PresenceState state)\n{\n emit publishStateChanged(m_contact->id(), state);\n}\n\nvoid Contact::onSubscriptionStateChanged(Tp::Contact::PresenceState state)\n{\n emit subscriptionStateChanged(m_contact->id(), state);\n}\n\nvoid Contact::onCapabilitiesChanged(const Tp::ContactCapabilities &capabilities)\n{\n \/\/ FIXME: Implement me!\n}\n\n\n#include \"contact.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ReAligner.h\"\n#include <vector>\n#include <iostream>\n#include <list>\n#include <limits>\n\n\nReAligner::ReAligner()\n{\n}\n\n\nReAligner::~ReAligner()\n{\n}\n\nConsensus &ReAligner::getConsensus(Alignment & alignment)\n{\n\t\/\/ TODO (mock object only)\n\treturn *new Consensus(0);\n}\n\nvoid ReAligner::calculateConsensusScore(Consensus & consensus, Alignment & alignment)\n{\n\t\/\/ TODO: after calculating do: consensus.setScore(calculatedScore);\n}\n\nMetasymbol * ReAligner::getConsensusMetasymbol(std::list<char>& column, int height)\n{\n\treturn nullptr;\n}\n\nvoid ReAligner::getAlignment(AlignedFragment & read, Consensus & cons, double eps)\n{\n\tint min = std::numeric_limits<int>::min();\n\tstd::list<Metasymbol*> consPartList;\n\n\tMetasymbol* dashSym = new Metasymbol();\n\tdashSym->addSymbol('-');\n\n\tint delta = (int)(eps \/ 2);\n\n\tint readLen = read.getLength();\n\tint readOff = read.getOffset();\n\tint consLen = cons.getLength();\n\n\n\t\/\/ -- Consensus part construction --\n\tint consPartStart = readOff - delta;\n\tint frontDashes = (consPartStart < 0) ? -consPartStart : 0;\n\tconsPartStart = (consPartStart < 0) ? 0 : consPartStart;\n\tint consPartEnd = readOff + readLen + delta;\n\tint backDashes = (consPartEnd > consLen) ? consPartEnd-consLen : 0;\n\tconsPartEnd = (consPartEnd > consLen) ? consLen : consPartEnd;\n\n\tconsPartList = cons.getPart(consPartStart, consPartEnd);\n\n\tfor (int i = 0; i < backDashes; i++)\n\t\tconsPartList.push_back(dashSym);\n\tfor (int i = 0; i < frontDashes; i++)\n\t\tconsPartList.push_front(dashSym);\n\n\tint consPartLen = consPartList.size();\n\n\tstd::vector<Metasymbol*> consPart(std::begin(consPartList), std::end(consPartList));\n\n\n\t\/\/ -- NeedlemanWunsch algorithm --\n\n\tvector<vector<int>> valueTable;\n\tvector<vector<bool>> isDiagonal;\n\tfor (int i = 0; i <= readLen; i++) {\n\t\tvector<int> rowInt;\n\t\tvector<bool> rowBool;\n\t\tfor (int j = 0; j <= consPartLen; j++) {\n\t\t\trowInt.push_back(min);\n\t\t\trowBool.push_back(false);\n\t\t}\n\t\tvalueTable.push_back(rowInt);\n\t\tisDiagonal.push_back(rowBool);\n\t}\n\n\t\/\/ Initial values\n\tfor (int j = 0; j <= 2 * delta; j++) {\n\t\tvalueTable[0][j] = -abs(j - delta);\n\t}\n\n\t\/\/ Main loop\n\tfor (int i = 1; i <= readLen; i++) {\n\t\tfor (int j = 1; j <= consPartLen; j++) {\n\t\t\tif (j >= i && j <= i + 2 * delta) {\n\t\t\t\tMetasymbol *sym = consPart[j - 1];\n\t\t\t\tint cost = -1;\n\t\t\t\tif (sym->contains(read.getAt(i - 1)) || sym->isDashOnly())\n\t\t\t\t\tcost = 0;\n\n\t\t\t\tint scoreDiag = valueTable[i - 1][j - 1] + cost;\n\t\t\t\tint scoreLeft = (valueTable[i][j - 1] == min) ? min : valueTable[i][j - 1] - 1;\n\n\t\t\t\tif (scoreDiag >= scoreLeft) {\n\t\t\t\t\tvalueTable[i][j] = scoreDiag;\n\t\t\t\t\tisDiagonal[i][j] = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvalueTable[i][j] = scoreLeft;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint score = min;\n\tint endPoisition = 0;\n\tfor (int i = 0; i <= 2 * delta; i++) {\n\t\tint currentValue = valueTable[readLen][consPartLen - i];\n\t\tif (score < currentValue) {\n\t\t\tscore = currentValue;\n\t\t\tendPoisition = consPartLen - i;\n\t\t}\n\t}\n\n\tstd::string newSequence = \"\";\n\tint tabi = readLen;\n\tint tabj = endPoisition;\n\twhile (tabi > 0) {\n\t\tif (isDiagonal[tabi][tabj]) {\n\t\t\tnewSequence = read.getAt(tabi-1) + newSequence;\n\t\t\ttabi--;\n\t\t\ttabj--;\n\t\t}\n\t\telse {\n\t\t\tnewSequence = \"-\" + newSequence;\n\t\t\ttabj--;\n\t\t}\n\t}\n\n\tint newOffset = read.getOffset() + tabj - delta;\n\n\tread.setSequence(newSequence);\n\tread.setOffset(newOffset);\n\n\treturn;\n}\n\nConsensus ReAligner::reAlign(Alignment & alignment, double epsilonPrecision, int numOfIterations)\n{\n\tConsensus consensus = getConsensus(alignment);\n\tcalculateConsensusScore(consensus, alignment);\n\tdouble initialScore = consensus.getScore();\n\tbool shouldContinue = true;\n\tint iteration = 1;\n\tint numOfReads = alignment.getSize();\n\t\n\tdouble minimalScore = initialScore;\n\tConsensus bestConsensus = consensus;\n\n\twhile (shouldContinue) {\n\t\tstd::cout << \"Iterating...\";\n\n\t\tfor (int k = 0; k < numOfReads; k++) {\n\t\t\t\/\/ detach first fragment in a list - append it last after iteration\n\t\t\tAlignedFragment* sequence = alignment.PopFirst();\n\t\t\tdashFunction(*sequence);\n\t\t\tdashFunction(consensus);\n\t\t\tconsensus = getConsensus(alignment);\n\t\t\tgetAlignment(*sequence, consensus, sequence->getLength() * epsilonPrecision);\n\n\t\t\talignment.AddFragment(sequence);\n\t\t\tconsensus = getConsensus(alignment);\n\t\t\tif (consensus.getScore() < minimalScore) {\n\t\t\t\tbestConsensus = consensus;\n\t\t\t\tminimalScore = consensus.getScore();\n\t\t\t}\n\t\t}\n\n\t\tif (bestConsensus.getScore() >= initialScore || iteration == numOfIterations) {\n\t\t\tshouldContinue = false;\n\t\t}\n\n\t\tstd::cout << \"After \" << iteration << \" iterations score is: \" << bestConsensus.getScore() << \" previous score : \" << initialScore;\n\t\tinitialScore = bestConsensus.getScore();\n\t\titeration++;\n\t}\n\n\treturn bestConsensus;\n}\n\nvoid ReAligner::dashFunction(Consensus &consensus)\n{\n\tconsensus.removeDashesFrontAndBack();\n}\n\nvoid ReAligner::dashFunction(AlignedFragment & fragment)\n{\n\tfragment.removeDashesFrontAndBack();\n}\n<commit_msg>ReAligner::getColumn and ReAligner::getNumberOfColumns implemented.<commit_after>#include \"ReAligner.h\"\n#include <vector>\n#include <iostream>\n#include <list>\n#include <limits>\n#include <algorithm>\n\n\nReAligner::ReAligner()\n{\n}\n\n\nReAligner::~ReAligner()\n{\n}\n\nConsensus &ReAligner::getConsensus(Alignment & alignment)\n{\n\t\/\/ TODO (mock object only)\n\treturn *new Consensus(0);\n}\n\nvoid ReAligner::calculateConsensusScore(Consensus & consensus, Alignment & alignment)\n{\n\t\/\/ TODO: after calculating do: consensus.setScore(calculatedScore);\n}\n\nMetasymbol * ReAligner::getConsensusMetasymbol(std::list<char>& column, int height)\n{\n\treturn nullptr;\n}\n\nvoid ReAligner::getAlignment(AlignedFragment & read, Consensus & cons, double eps)\n{\n\tint min = std::numeric_limits<int>::min();\n\tstd::list<Metasymbol*> consPartList;\n\n\tMetasymbol* dashSym = new Metasymbol();\n\tdashSym->addSymbol('-');\n\n\tint delta = (int)(eps \/ 2);\n\n\tint readLen = read.getLength();\n\tint readOff = read.getOffset();\n\tint consLen = cons.getLength();\n\n\n\t\/\/ -- Consensus part construction --\n\tint consPartStart = readOff - delta;\n\tint frontDashes = (consPartStart < 0) ? -consPartStart : 0;\n\tconsPartStart = (consPartStart < 0) ? 0 : consPartStart;\n\tint consPartEnd = readOff + readLen + delta;\n\tint backDashes = (consPartEnd > consLen) ? consPartEnd-consLen : 0;\n\tconsPartEnd = (consPartEnd > consLen) ? consLen : consPartEnd;\n\n\tconsPartList = cons.getPart(consPartStart, consPartEnd);\n\n\tfor (int i = 0; i < backDashes; i++)\n\t\tconsPartList.push_back(dashSym);\n\tfor (int i = 0; i < frontDashes; i++)\n\t\tconsPartList.push_front(dashSym);\n\n\tint consPartLen = consPartList.size();\n\n\tstd::vector<Metasymbol*> consPart(std::begin(consPartList), std::end(consPartList));\n\n\n\t\/\/ -- NeedlemanWunsch algorithm --\n\n\tvector<vector<int>> valueTable;\n\tvector<vector<bool>> isDiagonal;\n\tfor (int i = 0; i <= readLen; i++) {\n\t\tvector<int> rowInt;\n\t\tvector<bool> rowBool;\n\t\tfor (int j = 0; j <= consPartLen; j++) {\n\t\t\trowInt.push_back(min);\n\t\t\trowBool.push_back(false);\n\t\t}\n\t\tvalueTable.push_back(rowInt);\n\t\tisDiagonal.push_back(rowBool);\n\t}\n\n\t\/\/ Initial values\n\tfor (int j = 0; j <= 2 * delta; j++) {\n\t\tvalueTable[0][j] = -abs(j - delta);\n\t}\n\n\t\/\/ Main loop\n\tfor (int i = 1; i <= readLen; i++) {\n\t\tfor (int j = 1; j <= consPartLen; j++) {\n\t\t\tif (j >= i && j <= i + 2 * delta) {\n\t\t\t\tMetasymbol *sym = consPart[j - 1];\n\t\t\t\tint cost = -1;\n\t\t\t\tif (sym->contains(read.getAt(i - 1)) || sym->isDashOnly())\n\t\t\t\t\tcost = 0;\n\n\t\t\t\tint scoreDiag = valueTable[i - 1][j - 1] + cost;\n\t\t\t\tint scoreLeft = (valueTable[i][j - 1] == min) ? min : valueTable[i][j - 1] - 1;\n\n\t\t\t\tif (scoreDiag >= scoreLeft) {\n\t\t\t\t\tvalueTable[i][j] = scoreDiag;\n\t\t\t\t\tisDiagonal[i][j] = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvalueTable[i][j] = scoreLeft;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint score = min;\n\tint endPoisition = 0;\n\tfor (int i = 0; i <= 2 * delta; i++) {\n\t\tint currentValue = valueTable[readLen][consPartLen - i];\n\t\tif (score < currentValue) {\n\t\t\tscore = currentValue;\n\t\t\tendPoisition = consPartLen - i;\n\t\t}\n\t}\n\n\tstd::string newSequence = \"\";\n\tint tabi = readLen;\n\tint tabj = endPoisition;\n\twhile (tabi > 0) {\n\t\tif (isDiagonal[tabi][tabj]) {\n\t\t\tnewSequence = read.getAt(tabi-1) + newSequence;\n\t\t\ttabi--;\n\t\t\ttabj--;\n\t\t}\n\t\telse {\n\t\t\tnewSequence = \"-\" + newSequence;\n\t\t\ttabj--;\n\t\t}\n\t}\n\n\tint newOffset = read.getOffset() + tabj - delta;\n\n\tread.setSequence(newSequence);\n\tread.setOffset(newOffset);\n\n\treturn;\n}\n\nConsensus ReAligner::reAlign(Alignment & alignment, double epsilonPrecision, int numOfIterations)\n{\n\tConsensus consensus = getConsensus(alignment);\n\tcalculateConsensusScore(consensus, alignment);\n\tdouble initialScore = consensus.getScore();\n\tbool shouldContinue = true;\n\tint iteration = 1;\n\tint numOfReads = alignment.getSize();\n\t\n\tdouble minimalScore = initialScore;\n\tConsensus bestConsensus = consensus;\n\n\twhile (shouldContinue) {\n\t\tstd::cout << \"Iterating...\";\n\n\t\tfor (int k = 0; k < numOfReads; k++) {\n\t\t\t\/\/ detach first fragment in a list - append it last after iteration\n\t\t\tAlignedFragment* sequence = alignment.PopFirst();\n\t\t\tdashFunction(*sequence);\n\t\t\tdashFunction(consensus);\n\t\t\tconsensus = getConsensus(alignment);\n\t\t\tgetAlignment(*sequence, consensus, sequence->getLength() * epsilonPrecision);\n\n\t\t\talignment.AddFragment(sequence);\n\t\t\tconsensus = getConsensus(alignment);\n\t\t\tif (consensus.getScore() < minimalScore) {\n\t\t\t\tbestConsensus = consensus;\n\t\t\t\tminimalScore = consensus.getScore();\n\t\t\t}\n\t\t}\n\n\t\tif (bestConsensus.getScore() >= initialScore || iteration == numOfIterations) {\n\t\t\tshouldContinue = false;\n\t\t}\n\n\t\tstd::cout << \"After \" << iteration << \" iterations score is: \" << bestConsensus.getScore() << \" previous score : \" << initialScore;\n\t\tinitialScore = bestConsensus.getScore();\n\t\titeration++;\n\t}\n\n\treturn bestConsensus;\n}\n\nvoid ReAligner::dashFunction(Consensus &consensus)\n{\n\tconsensus.removeDashesFrontAndBack();\n}\n\nvoid ReAligner::dashFunction(AlignedFragment & fragment)\n{\n\tfragment.removeDashesFrontAndBack();\n}\n\nstd::list<char>& ReAligner::getColumn(Alignment & layoutMap, int index)\n{\n\tstd::list<char> &column = *new std::list<char>;\n\tstd::list<AlignedFragment*> &fragments = layoutMap.getAllFragments();\n\tfor (std::list<AlignedFragment*>::const_iterator iter = fragments.begin(); iter != fragments.end(); ++iter) {\n\t\tint offset = (*iter)->getOffset();\n\t\tint length = (*iter)->getLength();\n\t\tif (offset <= index && offset + length > index) {\n\t\t\tchar sym = (*iter)->getAt(index - offset);\n\t\t\tcolumn.push_back(sym);\n\t\t}\n\t}\n\treturn column;\n}\n\nint ReAligner::getNumberOfColumns(Alignment & layoutMap)\n{\n\tint numOfColumns = 0;\n\tstd::list<AlignedFragment*> &fragments = layoutMap.getAllFragments();\n\tfor (std::list<AlignedFragment*>::const_iterator iter = fragments.begin(); iter != fragments.end(); ++iter) {\n\t\tint offset = (*iter)->getOffset();\n\t\tint length = (*iter)->getLength();\n\t\tnumOfColumns = std::max(numOfColumns, offset + length);\n\t}\n\treturn numOfColumns;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <unordered_set>\n\n#include \"FunctionContext.hpp\"\n#include \"likely.hpp\"\n\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/Utils.hpp\"\n\nusing namespace eddic;\n\nbool mtac::merge_basic_blocks(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage;\n\n computeBlockUsage(function, usage);\n\n auto& blocks = function->getBasicBlocks();\n\n auto it = blocks.begin();\n\n \/\/The ENTRY Basic block should not be merged\n ++it;\n\n while(it != blocks.end()){\n auto& block = *it;\n if(likely(!block->statements.empty())){\n auto& last = block->statements[block->statements.size() - 1];\n\n bool merge = false;\n\n if(boost::get<std::shared_ptr<mtac::Quadruple>>(&last)){\n merge = true;\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&last)){\n merge = safe(*ptr); \n } else if(boost::get<std::shared_ptr<mtac::NoOp>>(&last)){\n merge = true;\n }\n\n auto next = it;\n ++next;\n\n if(merge && next != blocks.end() && (*next)->index != -2){\n \/\/Only if the next block is not used because we will remove its label\n if(usage.find(*next) == usage.end()){\n if(!(*next)->statements.empty()){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&(*(*next)->statements.begin()))){\n if(!safe(*ptr)){\n ++it;\n continue;\n }\n }\n }\n\n block->statements.insert(block->statements.end(), (*next)->statements.begin(), (*next)->statements.end());\n\n it = blocks.erase(next);\n optimized = true;\n\n --it;\n continue;\n }\n }\n }\n\n ++it;\n }\n \n return optimized; \n}\n\nbool mtac::remove_dead_basic_blocks(std::shared_ptr<mtac::Function> function){\n std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage;\n\n auto& blocks = function->getBasicBlocks();\n\n unsigned int before = blocks.size();\n\n auto it = blocks.begin();\n auto end = blocks.end();\n\n while(it != end){\n auto& block = *it;\n\n usage.insert(block);\n\n if(likely(!block->statements.empty())){\n auto& last = block->statements[block->statements.size() - 1];\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){\n if(usage.find((*ptr)->block) == usage.end()){\n it = std::find(blocks.begin(), blocks.end(), (*ptr)->block);\n continue;\n }\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&last)){\n usage.insert((*ptr)->block); \n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&last)){\n usage.insert((*ptr)->block); \n }\n }\n\n ++it;\n }\n\n \/\/The ENTRY and EXIT blocks should not be removed\n usage.insert(blocks.front());\n usage.insert(blocks.back());\n\n it = blocks.begin();\n end = blocks.end();\n\n blocks.erase(\n std::remove_if(it, end, \n [&](std::shared_ptr<mtac::BasicBlock>& b){ return usage.find(b) == usage.end(); }), \n end);\n\n return blocks.size() < before;\n}\n<commit_msg>Improve basic block merging<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <unordered_set>\n\n#include \"FunctionContext.hpp\"\n#include \"likely.hpp\"\n\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/Utils.hpp\"\n\nusing namespace eddic;\n\nbool mtac::merge_basic_blocks(std::shared_ptr<mtac::Function> function){\n bool optimized = false;\n\n std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage;\n\n computeBlockUsage(function, usage);\n\n auto& blocks = function->getBasicBlocks();\n\n auto it = blocks.begin();\n\n \/\/The ENTRY Basic block should not be merged\n ++it;\n\n while(it != blocks.end()){\n auto& block = *it;\n if(unlikely(block->statements.empty())){\n if(usage.find(*it) == usage.end()){\n it = blocks.erase(it);\n optimized = true;\n\n --it;\n continue;\n }\n } else {\n auto& last = block->statements[block->statements.size() - 1];\n\n bool merge = false;\n\n if(boost::get<std::shared_ptr<mtac::Quadruple>>(&last)){\n merge = true;\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&last)){\n merge = safe(*ptr); \n } else if(boost::get<std::shared_ptr<mtac::NoOp>>(&last)){\n merge = true;\n }\n\n auto next = it;\n ++next;\n\n if(merge && next != blocks.end() && (*next)->index != -2){\n \/\/Only if the next block is not used because we will remove its label\n if(usage.find(*next) == usage.end()){\n if(!(*next)->statements.empty()){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&(*(*next)->statements.begin()))){\n if(!safe(*ptr)){\n ++it;\n continue;\n }\n }\n }\n\n block->statements.insert(block->statements.end(), (*next)->statements.begin(), (*next)->statements.end());\n\n it = blocks.erase(next);\n optimized = true;\n\n --it;\n continue;\n }\n }\n }\n\n ++it;\n }\n \n return optimized; \n}\n\nbool mtac::remove_dead_basic_blocks(std::shared_ptr<mtac::Function> function){\n std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage;\n\n auto& blocks = function->getBasicBlocks();\n\n unsigned int before = blocks.size();\n\n auto it = blocks.begin();\n auto end = blocks.end();\n\n while(it != end){\n auto& block = *it;\n\n usage.insert(block);\n\n if(likely(!block->statements.empty())){\n auto& last = block->statements[block->statements.size() - 1];\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){\n if(usage.find((*ptr)->block) == usage.end()){\n it = std::find(blocks.begin(), blocks.end(), (*ptr)->block);\n continue;\n }\n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&last)){\n usage.insert((*ptr)->block); \n } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&last)){\n usage.insert((*ptr)->block); \n }\n }\n\n ++it;\n }\n\n \/\/The ENTRY and EXIT blocks should not be removed\n usage.insert(blocks.front());\n usage.insert(blocks.back());\n\n it = blocks.begin();\n end = blocks.end();\n\n blocks.erase(\n std::remove_if(it, end, \n [&](std::shared_ptr<mtac::BasicBlock>& b){ return usage.find(b) == usage.end(); }), \n end);\n\n return blocks.size() < before;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n#include <limits.h>\n\n#include <cursespp\/Screen.h>\n#include <cursespp\/Colors.h>\n#include <cursespp\/TextInput.h>\n\nusing namespace cursespp;\n\ninline static bool removeUtf8Char(std::string& value, size_t position) {\n \/* optimize the normal case, at the end... *\/\n if (position >= value.size()) {\n std::string::iterator it = value.end();\n std::string::iterator start = value.begin();\n if (it != start) {\n utf8::prior(it, start);\n value = std::string(value.begin(), it);\n return true;\n }\n }\n else {\n size_t offset = u8offset(value, position - 1);\n if (offset != std::string::npos) {\n size_t end = u8offset(value, position);\n value.erase(offset, end - offset);\n return true;\n }\n }\n\n return false;\n}\n\nTextInput::TextInput(TextInput::Style style, IInput::InputMode inputMode)\n: Window()\n, bufferLength(0)\n, position(0)\n, style(style)\n, inputMode(inputMode)\n, enterEnabled(true)\n, truncate(false) {\n this->SetFocusedContentColor(Color::TextFocused);\n if (style == StyleLine) {\n this->SetFrameVisible(false);\n }\n}\n\nTextInput::TextInput(IInput::InputMode inputMode)\n: TextInput(TextInput::StyleBox, inputMode) {\n}\n\nTextInput::~TextInput() {\n}\n\nvoid TextInput::OnRedraw() {\n WINDOW* c = this->GetContent();\n werase(c);\n\n std::string trimmed;\n int contentWidth = GetContentWidth();\n int columns = u8cols(buffer);\n\n \/* if the string is larger than our width, we gotta trim it for\n display purposes... *\/\n if (position > contentWidth) {\n trimmed = u8substr(this->buffer, position - contentWidth, INT_MAX);\n }\n else {\n trimmed = buffer;\n }\n\n if (!columns && hintText.size()) {\n \/* draw the hint if we have one and there's no string yet *\/\n int64_t color = Color(Color::TextDisabled);\n wattron(c, color);\n wmove(c, 0, 0);\n checked_waddstr(c, u8substr(hintText, 0, contentWidth).c_str());\n wattroff(c, color);\n }\n else {\n \/* mask the string if we're in password mode *\/\n if (inputMode == InputPassword) {\n trimmed = std::string(columns, '*');\n }\n\n \/* if we're in \"Line\" mode and the string is short, pad the\n end with a bunch of underscores *\/\n if (style == StyleLine) {\n int remaining = contentWidth - columns;\n if (remaining > 0) {\n trimmed += std::string(remaining, '_');\n }\n }\n\n \/* finally, draw the offset\/trimmed, potentially masked, padded\n string to the output *\/\n checked_waddstr(c, trimmed.c_str());\n }\n}\n\nsize_t TextInput::Length() {\n return this->bufferLength;\n}\n\nsize_t TextInput::Position() {\n \/* note we return the COLUMN offset, not the physical or logical\n character offset! *\/\n return u8cols(u8substr(this->buffer, 0, this->position));\n}\n\nbool TextInput::Write(const std::string& key) {\n \/* one character at a time. if it's more than one character, we're\n dealing with an escape sequence and should not print it unless\n the input mode allows for modifiers *\/\n int len = u8len(key);\n if (len == 1 || (len > 1 && this->inputMode == InputRaw)) {\n if (this->inputMode == InputRaw) {\n auto& bl = this->rawBlacklist;\n if (std::find(bl.begin(), bl.end(), key) != bl.end()) {\n return false;\n }\n this->buffer = key;\n this->bufferLength = len;\n this->position = len;\n }\n else {\n if (truncate) {\n int cols = u8cols(this->buffer);\n if (cols >= this->GetWidth()) {\n return false;\n }\n }\n\n size_t offset = u8offset(this->buffer, this->position);\n offset = (offset == std::string::npos) ? 0 : offset;\n this->buffer.insert(offset, key);\n this->bufferLength = u8len(buffer);\n this->position += len;\n }\n\n this->TextChanged(this, this->buffer);\n this->Redraw();\n return true;\n }\n\n return false;\n}\n\nvoid TextInput::SetTruncate(bool truncate) {\n if (this->truncate != truncate) {\n this->truncate = truncate;\n }\n}\n\nvoid TextInput::SetEnterEnabled(bool enabled) {\n this->enterEnabled = enabled;\n}\n\nvoid TextInput::SetRawKeyBlacklist(const std::vector<std::string>&& blacklist) {\n this->rawBlacklist = blacklist;\n}\n\nbool TextInput::KeyPress(const std::string& key) {\n if (this->inputMode == InputMode::InputRaw) {\n return false;\n }\n\n if (key == \"M-KEY_BACKSPACE\") {\n this->SetText(\"\");\n return true;\n }\n else if (key == \"KEY_BACKSPACE\") {\n if (this->position > 0) {\n if (removeUtf8Char(this->buffer, this->position)) {\n --this->bufferLength;\n this->Redraw();\n this->position = std::max(0, this->position - 1);\n this->TextChanged(this, this->buffer);\n }\n }\n return true;\n }\n else if (key == \"KEY_ENTER\") {\n if (enterEnabled) {\n this->EnterPressed(this);\n return true;\n }\n else {\n return false;\n }\n }\n else if (key == \"KEY_LEFT\") {\n return this->OffsetPosition(-1);\n }\n else if (key == \"KEY_RIGHT\") {\n return this->OffsetPosition(1);\n }\n else if (key == \"KEY_HOME\") {\n this->position = 0;\n this->Redraw();\n return true;\n }\n else if (key == \"KEY_END\") {\n this->position = this->bufferLength;\n this->Redraw();\n return true;\n }\n else if (key == \"KEY_DC\") {\n if ((int) this->bufferLength > this->position) {\n removeUtf8Char(this->buffer, this->position + 1);\n this->bufferLength = u8len(buffer);\n this->Redraw();\n this->TextChanged(this, this->buffer);\n return true;\n }\n }\n\n return false;\n}\n\nbool TextInput::OffsetPosition(int delta) {\n int actual = this->position + delta;\n actual = std::max(0, std::min((int) this->bufferLength, actual));\n\n if (this->position != actual) {\n this->position = actual;\n this->Redraw();\n return true; \/* moved *\/\n }\n\n return false; \/* didn't move *\/\n}\n\nvoid TextInput::SetText(const std::string& value) {\n if (value != this->buffer) {\n this->buffer = value;\n this->bufferLength = u8len(buffer);\n this->position = this->bufferLength;\n this->TextChanged(this, this->buffer);\n this->Redraw();\n }\n}\n\nvoid TextInput::SetHint(const std::string& hint) {\n this->hintText = hint;\n this->Redraw();\n}\n\nbool TextInput::MouseEvent(const IMouseHandler::Event& event) {\n if (event.Button1Clicked()) {\n this->position = std::max(0, std::min((int)this->bufferLength, event.x));\n this->FocusInParent();\n return true;\n }\n return false;\n}<commit_msg>Fixed default TextInput focused content color for non-inline-styled controls<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n#include <limits.h>\n\n#include <cursespp\/Screen.h>\n#include <cursespp\/Colors.h>\n#include <cursespp\/TextInput.h>\n\nusing namespace cursespp;\n\ninline static bool removeUtf8Char(std::string& value, size_t position) {\n \/* optimize the normal case, at the end... *\/\n if (position >= value.size()) {\n std::string::iterator it = value.end();\n std::string::iterator start = value.begin();\n if (it != start) {\n utf8::prior(it, start);\n value = std::string(value.begin(), it);\n return true;\n }\n }\n else {\n size_t offset = u8offset(value, position - 1);\n if (offset != std::string::npos) {\n size_t end = u8offset(value, position);\n value.erase(offset, end - offset);\n return true;\n }\n }\n\n return false;\n}\n\nTextInput::TextInput(TextInput::Style style, IInput::InputMode inputMode)\n: Window()\n, bufferLength(0)\n, position(0)\n, style(style)\n, inputMode(inputMode)\n, enterEnabled(true)\n, truncate(false) {\n if (style == StyleLine) {\n this->SetFrameVisible(false);\n this->SetFocusedContentColor(Color::TextFocused);\n }\n}\n\nTextInput::TextInput(IInput::InputMode inputMode)\n: TextInput(TextInput::StyleBox, inputMode) {\n}\n\nTextInput::~TextInput() {\n}\n\nvoid TextInput::OnRedraw() {\n WINDOW* c = this->GetContent();\n werase(c);\n\n std::string trimmed;\n int contentWidth = GetContentWidth();\n int columns = u8cols(buffer);\n\n \/* if the string is larger than our width, we gotta trim it for\n display purposes... *\/\n if (position > contentWidth) {\n trimmed = u8substr(this->buffer, position - contentWidth, INT_MAX);\n }\n else {\n trimmed = buffer;\n }\n\n if (!columns && hintText.size()) {\n \/* draw the hint if we have one and there's no string yet *\/\n int64_t color = Color(Color::TextDisabled);\n wattron(c, color);\n wmove(c, 0, 0);\n checked_waddstr(c, u8substr(hintText, 0, contentWidth).c_str());\n wattroff(c, color);\n }\n else {\n \/* mask the string if we're in password mode *\/\n if (inputMode == InputPassword) {\n trimmed = std::string(columns, '*');\n }\n\n \/* if we're in \"Line\" mode and the string is short, pad the\n end with a bunch of underscores *\/\n if (style == StyleLine) {\n int remaining = contentWidth - columns;\n if (remaining > 0) {\n trimmed += std::string(remaining, '_');\n }\n }\n\n \/* finally, draw the offset\/trimmed, potentially masked, padded\n string to the output *\/\n checked_waddstr(c, trimmed.c_str());\n }\n}\n\nsize_t TextInput::Length() {\n return this->bufferLength;\n}\n\nsize_t TextInput::Position() {\n \/* note we return the COLUMN offset, not the physical or logical\n character offset! *\/\n return u8cols(u8substr(this->buffer, 0, this->position));\n}\n\nbool TextInput::Write(const std::string& key) {\n \/* one character at a time. if it's more than one character, we're\n dealing with an escape sequence and should not print it unless\n the input mode allows for modifiers *\/\n int len = u8len(key);\n if (len == 1 || (len > 1 && this->inputMode == InputRaw)) {\n if (this->inputMode == InputRaw) {\n auto& bl = this->rawBlacklist;\n if (std::find(bl.begin(), bl.end(), key) != bl.end()) {\n return false;\n }\n this->buffer = key;\n this->bufferLength = len;\n this->position = len;\n }\n else {\n if (truncate) {\n int cols = u8cols(this->buffer);\n if (cols >= this->GetWidth()) {\n return false;\n }\n }\n\n size_t offset = u8offset(this->buffer, this->position);\n offset = (offset == std::string::npos) ? 0 : offset;\n this->buffer.insert(offset, key);\n this->bufferLength = u8len(buffer);\n this->position += len;\n }\n\n this->TextChanged(this, this->buffer);\n this->Redraw();\n return true;\n }\n\n return false;\n}\n\nvoid TextInput::SetTruncate(bool truncate) {\n if (this->truncate != truncate) {\n this->truncate = truncate;\n }\n}\n\nvoid TextInput::SetEnterEnabled(bool enabled) {\n this->enterEnabled = enabled;\n}\n\nvoid TextInput::SetRawKeyBlacklist(const std::vector<std::string>&& blacklist) {\n this->rawBlacklist = blacklist;\n}\n\nbool TextInput::KeyPress(const std::string& key) {\n if (this->inputMode == InputMode::InputRaw) {\n return false;\n }\n\n if (key == \"M-KEY_BACKSPACE\") {\n this->SetText(\"\");\n return true;\n }\n else if (key == \"KEY_BACKSPACE\") {\n if (this->position > 0) {\n if (removeUtf8Char(this->buffer, this->position)) {\n --this->bufferLength;\n this->Redraw();\n this->position = std::max(0, this->position - 1);\n this->TextChanged(this, this->buffer);\n }\n }\n return true;\n }\n else if (key == \"KEY_ENTER\") {\n if (enterEnabled) {\n this->EnterPressed(this);\n return true;\n }\n else {\n return false;\n }\n }\n else if (key == \"KEY_LEFT\") {\n return this->OffsetPosition(-1);\n }\n else if (key == \"KEY_RIGHT\") {\n return this->OffsetPosition(1);\n }\n else if (key == \"KEY_HOME\") {\n this->position = 0;\n this->Redraw();\n return true;\n }\n else if (key == \"KEY_END\") {\n this->position = this->bufferLength;\n this->Redraw();\n return true;\n }\n else if (key == \"KEY_DC\") {\n if ((int) this->bufferLength > this->position) {\n removeUtf8Char(this->buffer, this->position + 1);\n this->bufferLength = u8len(buffer);\n this->Redraw();\n this->TextChanged(this, this->buffer);\n return true;\n }\n }\n\n return false;\n}\n\nbool TextInput::OffsetPosition(int delta) {\n int actual = this->position + delta;\n actual = std::max(0, std::min((int) this->bufferLength, actual));\n\n if (this->position != actual) {\n this->position = actual;\n this->Redraw();\n return true; \/* moved *\/\n }\n\n return false; \/* didn't move *\/\n}\n\nvoid TextInput::SetText(const std::string& value) {\n if (value != this->buffer) {\n this->buffer = value;\n this->bufferLength = u8len(buffer);\n this->position = this->bufferLength;\n this->TextChanged(this, this->buffer);\n this->Redraw();\n }\n}\n\nvoid TextInput::SetHint(const std::string& hint) {\n this->hintText = hint;\n this->Redraw();\n}\n\nbool TextInput::MouseEvent(const IMouseHandler::Event& event) {\n if (event.Button1Clicked()) {\n this->position = std::max(0, std::min((int)this->bufferLength, event.x));\n this->FocusInParent();\n return true;\n }\n return false;\n}<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <stdio.h>\n#include <string.h>\n\nusing namespace std;\n\n#define MOD 1000000007\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n vector<int> vec_m;\n vec_m.reserve(n);\n\n int m;\n for (size_t i = 0; i < n; i++) {\n scanf(\"%d\", &m);\n vec_m.push_back(m);\n }\n\n return 0;\n}\n<commit_msg>60.00 points<commit_after>\/\/\n\/\/ main.cpp\n\/\/ test\n\/\/\n\/\/ Created by 吴星煜 on 2018\/4\/7.\n\/\/ Copyright © 2018年 吴星煜. All rights reserved.\n\/\/\n\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <stdio.h>\n#include <string.h>\n\nusing namespace std;\n\n#define MOD 1000000007\n#define MAX_N 15\n\nunsigned long long cnt[MAX_N + 1][MAX_N + 1];\n\nint main() {\n int n;\n scanf(\"%d\", &n);\n\n vector<int> vec_m;\n vec_m.reserve(n);\n\n int m;\n for (size_t i = 0; i < n; i++) {\n scanf(\"%d\", &m);\n vec_m.push_back(m);\n }\n\n for (int c = 1; c <= n; c ++) {\n for (int i = n - c; i >= 0; i --) {\n if (1 == c) {\n cnt[i][c] = 1;\n }\n else {\n if (0 < cnt[i + 1][c - 1] && vec_m[i] < vec_m[i + 1]) {\n if (i + c >= n) {\n cnt[i][c] = 1;\n }\n else {\n unsigned long long tmp = c;\n for (int j = 1, c1 = c; j <= c; j ++, c1 --) {\n cnt[i][c] += cnt[i + c][j] * tmp;\n cnt[i][c] %= MOD;\n tmp *= c1 - 1;\n tmp %= MOD;\n }\n }\n }\n }\n }\n }\n\n unsigned long long ret = 0;\n\n for (int i = 1; i <= n; i ++) {\n ret += cnt[0][i];\n ret %= MOD;\n }\n\n printf(\"%llu\\n\", ret);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"lid_allocator.h\"\n#include <vespa\/searchlib\/query\/queryterm.h>\n#include <vespa\/searchlib\/common\/bitvectoriterator.h>\n#include <mutex>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.documentmetastore.lid_allocator\");\n\nusing search::fef::TermFieldMatchDataArray;\nusing search::queryeval::Blueprint;\nusing search::queryeval::FieldSpecBaseList;\nusing search::queryeval::SearchIterator;\nusing search::queryeval::SimpleLeafBlueprint;\nusing vespalib::GenerationHolder;\n\nnamespace proton::documentmetastore {\n\nLidAllocator::LidAllocator(uint32_t size,\n uint32_t capacity,\n GenerationHolder &genHolder)\n : _holdLids(),\n _freeLids(size, capacity, genHolder, true, false),\n _usedLids(size, capacity, genHolder, false, true),\n _pendingHoldLids(size, capacity, genHolder, false, false),\n _lidFreeListConstructed(false),\n _activeLids(size, capacity, genHolder, false, false),\n _numActiveLids(0u)\n{\n\n}\n\nLidAllocator::~LidAllocator() {}\n\nLidAllocator::DocId\nLidAllocator::getFreeLid(DocId lidLimit)\n{\n DocId lid = _freeLids.getLowest();\n if (lid >= lidLimit) {\n lid = lidLimit;\n } else {\n _freeLids.clearBit(lid);\n }\n return lid;\n}\n\nLidAllocator::DocId\nLidAllocator::peekFreeLid(DocId lidLimit)\n{\n DocId lid = _freeLids.getLowest();\n if (lid >= lidLimit) {\n lid = lidLimit;\n }\n return lid;\n}\n\nvoid\nLidAllocator::ensureSpace(uint32_t newSize,\n uint32_t newCapacity)\n{\n _freeLids.resizeVector(newSize, newCapacity);\n _usedLids.resizeVector(newSize, newCapacity);\n _pendingHoldLids.resizeVector(newSize, newCapacity);\n _activeLids.resizeVector(newSize, newCapacity);\n}\n\nvoid\nLidAllocator::unregisterLid(DocId lid)\n{\n assert(!_pendingHoldLids.testBit(lid));\n if (isFreeListConstructed()) {\n _pendingHoldLids.setBit(lid);\n }\n _usedLids.clearBit(lid);\n if (_activeLids.testBit(lid)) {\n _activeLids.clearBit(lid);\n _numActiveLids = _activeLids.count();\n }\n}\n\nsize_t\nLidAllocator::getUsedLidsSize() const\n{\n return _usedLids.byteSize();\n}\n\nvoid\nLidAllocator::trimHoldLists(generation_t firstUsed)\n{\n _holdLids.trimHoldLists(firstUsed, _freeLids);\n}\n\nvoid\nLidAllocator::moveLidBegin(DocId fromLid, DocId toLid)\n{\n (void) fromLid;\n assert(!_pendingHoldLids.testBit(fromLid));\n assert(!_pendingHoldLids.testBit(toLid));\n if (isFreeListConstructed()) {\n assert(!_freeLids.testBit(fromLid));\n assert(_freeLids.testBit(toLid));\n _freeLids.clearBit(toLid);\n }\n}\n\nvoid\nLidAllocator::moveLidEnd(DocId fromLid, DocId toLid)\n{\n if (isFreeListConstructed()) {\n \/\/ old lid must be scheduled for hold by caller\n _pendingHoldLids.setBit(fromLid);\n }\n _usedLids.setBit(toLid);\n _usedLids.clearBit(fromLid);\n if (_activeLids.testBit(fromLid)) {\n _activeLids.setBit(toLid);\n _activeLids.clearBit(fromLid);\n }\n}\n\nvoid\nLidAllocator::holdLid(DocId lid,\n DocId lidLimit,\n generation_t currentGeneration)\n{\n (void) lidLimit;\n assert(holdLidOK(lid, lidLimit));\n assert(isFreeListConstructed());\n assert(lid < _usedLids.size());\n assert(lid < _pendingHoldLids.size());\n assert(_pendingHoldLids.testBit(lid));\n _pendingHoldLids.clearBit(lid);\n _holdLids.add(lid, currentGeneration);\n}\n\nvoid\nLidAllocator::holdLids(const std::vector<DocId> &lids,\n DocId lidLimit,\n generation_t currentGeneration)\n{\n (void) lidLimit;\n for (const auto &lid : lids) {\n assert(lid > 0);\n assert(holdLidOK(lid, lidLimit));\n _pendingHoldLids.clearBit(lid);\n _holdLids.add(lid, currentGeneration);\n }\n}\n\nbool\nLidAllocator::holdLidOK(DocId lid, DocId lidLimit) const\n{\n if (_lidFreeListConstructed &&\n lid != 0 &&\n lid < lidLimit &&\n lid < _usedLids.size() &&\n lid < _pendingHoldLids.size() &&\n _pendingHoldLids.testBit(lid))\n {\n return true;\n }\n LOG(error,\n \"LidAllocator::holdLidOK(%u, %u): \"\n \"_lidFreeListConstructed=%s, \"\n \"_usedLids.size()=%d, \"\n \"_pendingHoldLids.size()=%d, \"\n \"_pendingHoldLids bit=%s\",\n lid, lidLimit,\n _lidFreeListConstructed ? \"true\" : \"false\",\n (int) _usedLids.size(),\n (int) _pendingHoldLids.size(),\n lid < _pendingHoldLids.size() ?\n (_pendingHoldLids.testBit(lid) ?\n \"true\" : \"false\" ) : \"invalid\"\n );\n return false;\n}\n\nvoid\nLidAllocator::constructFreeList(DocId lidLimit)\n{\n assert(!isFreeListConstructed());\n _holdLids.clear();\n for (uint32_t lid = 1; lid < lidLimit; ++lid) {\n if (!validLid(lid)) {\n _freeLids.setBit(lid);\n }\n }\n}\n\nnamespace {\n\nclass WhiteListBlueprint : public SimpleLeafBlueprint\n{\nprivate:\n const search::GrowableBitVector &_activeLids;\n mutable std::mutex _lock;\n mutable std::vector<search::fef::TermFieldMatchData *> _matchDataVector;\n\n virtual SearchIterator::UP\n createLeafSearch(const TermFieldMatchDataArray &tfmda,\n bool strict) const override\n {\n assert(tfmda.size() == 0);\n (void) tfmda;\n search::fef::TermFieldMatchData *tfmd =\n new search::fef::TermFieldMatchData;\n {\n std::lock_guard<std::mutex> lock(_lock);\n _matchDataVector.push_back(tfmd);\n }\n uint32_t docIdLimit = _activeLids.size();\n return search::BitVectorIterator::create(&_activeLids, docIdLimit, *tfmd, strict);\n }\n\npublic:\n WhiteListBlueprint(const search::GrowableBitVector &activeLids)\n : SimpleLeafBlueprint(FieldSpecBaseList()),\n _activeLids(activeLids),\n _matchDataVector()\n {\n setEstimate(HitEstimate(0, false));\n }\n\n ~WhiteListBlueprint() {\n for (auto matchData : _matchDataVector) {\n delete matchData;\n }\n }\n};\n\n}\n\nBlueprint::UP\nLidAllocator::createWhiteListBlueprint() const\n{\n return std::make_unique<WhiteListBlueprint>(_activeLids.getBitVector());\n}\n\nvoid\nLidAllocator::updateActiveLids(DocId lid, bool active)\n{\n bool oldActive = _activeLids.testBit(lid);\n if (oldActive != active) {\n if (active) {\n _activeLids.setBit(lid);\n } else {\n _activeLids.clearBit(lid);\n }\n _numActiveLids = _activeLids.count();\n }\n}\n\nvoid\nLidAllocator::clearDocs(DocId lidLow, DocId lidLimit)\n{\n (void) lidLow;\n (void) lidLimit;\n assert(_usedLids.getNextTrueBit(lidLow) >= lidLimit);\n}\n\nvoid\nLidAllocator::shrinkLidSpace(DocId committedDocIdLimit)\n{\n ensureSpace(committedDocIdLimit, committedDocIdLimit);\n}\n\nuint32_t\nLidAllocator::getNumUsedLids() const\n{\n return _usedLids.count();\n}\n\n}\n<commit_msg>Don't estimate 0 hits in whitelist.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"lid_allocator.h\"\n#include <vespa\/searchlib\/query\/queryterm.h>\n#include <vespa\/searchlib\/common\/bitvectoriterator.h>\n#include <mutex>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.documentmetastore.lid_allocator\");\n\nusing search::fef::TermFieldMatchDataArray;\nusing search::queryeval::Blueprint;\nusing search::queryeval::FieldSpecBaseList;\nusing search::queryeval::SearchIterator;\nusing search::queryeval::SimpleLeafBlueprint;\nusing vespalib::GenerationHolder;\n\nnamespace proton::documentmetastore {\n\nLidAllocator::LidAllocator(uint32_t size,\n uint32_t capacity,\n GenerationHolder &genHolder)\n : _holdLids(),\n _freeLids(size, capacity, genHolder, true, false),\n _usedLids(size, capacity, genHolder, false, true),\n _pendingHoldLids(size, capacity, genHolder, false, false),\n _lidFreeListConstructed(false),\n _activeLids(size, capacity, genHolder, false, false),\n _numActiveLids(0u)\n{\n\n}\n\nLidAllocator::~LidAllocator() {}\n\nLidAllocator::DocId\nLidAllocator::getFreeLid(DocId lidLimit)\n{\n DocId lid = _freeLids.getLowest();\n if (lid >= lidLimit) {\n lid = lidLimit;\n } else {\n _freeLids.clearBit(lid);\n }\n return lid;\n}\n\nLidAllocator::DocId\nLidAllocator::peekFreeLid(DocId lidLimit)\n{\n DocId lid = _freeLids.getLowest();\n if (lid >= lidLimit) {\n lid = lidLimit;\n }\n return lid;\n}\n\nvoid\nLidAllocator::ensureSpace(uint32_t newSize,\n uint32_t newCapacity)\n{\n _freeLids.resizeVector(newSize, newCapacity);\n _usedLids.resizeVector(newSize, newCapacity);\n _pendingHoldLids.resizeVector(newSize, newCapacity);\n _activeLids.resizeVector(newSize, newCapacity);\n}\n\nvoid\nLidAllocator::unregisterLid(DocId lid)\n{\n assert(!_pendingHoldLids.testBit(lid));\n if (isFreeListConstructed()) {\n _pendingHoldLids.setBit(lid);\n }\n _usedLids.clearBit(lid);\n if (_activeLids.testBit(lid)) {\n _activeLids.clearBit(lid);\n _numActiveLids = _activeLids.count();\n }\n}\n\nsize_t\nLidAllocator::getUsedLidsSize() const\n{\n return _usedLids.byteSize();\n}\n\nvoid\nLidAllocator::trimHoldLists(generation_t firstUsed)\n{\n _holdLids.trimHoldLists(firstUsed, _freeLids);\n}\n\nvoid\nLidAllocator::moveLidBegin(DocId fromLid, DocId toLid)\n{\n (void) fromLid;\n assert(!_pendingHoldLids.testBit(fromLid));\n assert(!_pendingHoldLids.testBit(toLid));\n if (isFreeListConstructed()) {\n assert(!_freeLids.testBit(fromLid));\n assert(_freeLids.testBit(toLid));\n _freeLids.clearBit(toLid);\n }\n}\n\nvoid\nLidAllocator::moveLidEnd(DocId fromLid, DocId toLid)\n{\n if (isFreeListConstructed()) {\n \/\/ old lid must be scheduled for hold by caller\n _pendingHoldLids.setBit(fromLid);\n }\n _usedLids.setBit(toLid);\n _usedLids.clearBit(fromLid);\n if (_activeLids.testBit(fromLid)) {\n _activeLids.setBit(toLid);\n _activeLids.clearBit(fromLid);\n }\n}\n\nvoid\nLidAllocator::holdLid(DocId lid,\n DocId lidLimit,\n generation_t currentGeneration)\n{\n (void) lidLimit;\n assert(holdLidOK(lid, lidLimit));\n assert(isFreeListConstructed());\n assert(lid < _usedLids.size());\n assert(lid < _pendingHoldLids.size());\n assert(_pendingHoldLids.testBit(lid));\n _pendingHoldLids.clearBit(lid);\n _holdLids.add(lid, currentGeneration);\n}\n\nvoid\nLidAllocator::holdLids(const std::vector<DocId> &lids,\n DocId lidLimit,\n generation_t currentGeneration)\n{\n (void) lidLimit;\n for (const auto &lid : lids) {\n assert(lid > 0);\n assert(holdLidOK(lid, lidLimit));\n _pendingHoldLids.clearBit(lid);\n _holdLids.add(lid, currentGeneration);\n }\n}\n\nbool\nLidAllocator::holdLidOK(DocId lid, DocId lidLimit) const\n{\n if (_lidFreeListConstructed &&\n lid != 0 &&\n lid < lidLimit &&\n lid < _usedLids.size() &&\n lid < _pendingHoldLids.size() &&\n _pendingHoldLids.testBit(lid))\n {\n return true;\n }\n LOG(error,\n \"LidAllocator::holdLidOK(%u, %u): \"\n \"_lidFreeListConstructed=%s, \"\n \"_usedLids.size()=%d, \"\n \"_pendingHoldLids.size()=%d, \"\n \"_pendingHoldLids bit=%s\",\n lid, lidLimit,\n _lidFreeListConstructed ? \"true\" : \"false\",\n (int) _usedLids.size(),\n (int) _pendingHoldLids.size(),\n lid < _pendingHoldLids.size() ?\n (_pendingHoldLids.testBit(lid) ?\n \"true\" : \"false\" ) : \"invalid\"\n );\n return false;\n}\n\nvoid\nLidAllocator::constructFreeList(DocId lidLimit)\n{\n assert(!isFreeListConstructed());\n _holdLids.clear();\n for (uint32_t lid = 1; lid < lidLimit; ++lid) {\n if (!validLid(lid)) {\n _freeLids.setBit(lid);\n }\n }\n}\n\nnamespace {\n\nclass WhiteListBlueprint : public SimpleLeafBlueprint\n{\nprivate:\n const search::GrowableBitVector &_activeLids;\n mutable std::mutex _lock;\n mutable std::vector<search::fef::TermFieldMatchData *> _matchDataVector;\n\n virtual SearchIterator::UP\n createLeafSearch(const TermFieldMatchDataArray &tfmda,\n bool strict) const override\n {\n assert(tfmda.size() == 0);\n (void) tfmda;\n search::fef::TermFieldMatchData *tfmd =\n new search::fef::TermFieldMatchData;\n {\n std::lock_guard<std::mutex> lock(_lock);\n _matchDataVector.push_back(tfmd);\n }\n uint32_t docIdLimit = _activeLids.size();\n return search::BitVectorIterator::create(&_activeLids, docIdLimit, *tfmd, strict);\n }\n\npublic:\n WhiteListBlueprint(const search::GrowableBitVector &activeLids)\n : SimpleLeafBlueprint(FieldSpecBaseList()),\n _activeLids(activeLids),\n _matchDataVector()\n {\n setEstimate(HitEstimate(_activeLids.size(), false));\n }\n\n ~WhiteListBlueprint() {\n for (auto matchData : _matchDataVector) {\n delete matchData;\n }\n }\n};\n\n}\n\nBlueprint::UP\nLidAllocator::createWhiteListBlueprint() const\n{\n return std::make_unique<WhiteListBlueprint>(_activeLids.getBitVector());\n}\n\nvoid\nLidAllocator::updateActiveLids(DocId lid, bool active)\n{\n bool oldActive = _activeLids.testBit(lid);\n if (oldActive != active) {\n if (active) {\n _activeLids.setBit(lid);\n } else {\n _activeLids.clearBit(lid);\n }\n _numActiveLids = _activeLids.count();\n }\n}\n\nvoid\nLidAllocator::clearDocs(DocId lidLow, DocId lidLimit)\n{\n (void) lidLow;\n (void) lidLimit;\n assert(_usedLids.getNextTrueBit(lidLow) >= lidLimit);\n}\n\nvoid\nLidAllocator::shrinkLidSpace(DocId committedDocIdLimit)\n{\n ensureSpace(committedDocIdLimit, committedDocIdLimit);\n}\n\nuint32_t\nLidAllocator::getNumUsedLids() const\n{\n return _usedLids.count();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SDD_DD_SUM_HH_\n#define _SDD_DD_SUM_HH_\n\n\/\/\/ @file sum.hh\n\/\/\/ @brief Contain all stuff to implement the union operation.\n\n#include <unordered_map>\n#include <vector>\n\n#include <boost\/container\/flat_set.hpp>\n\n#include \"sdd\/dd\/context_fwd.hh\"\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/dd\/nary.hh\"\n#include \"sdd\/dd\/operations_fwd.hh\"\n#include \"sdd\/dd\/square_union.hh\"\n#include \"sdd\/internal\/util\/hash.hh\"\n\nnamespace sdd {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @cond INTERNAL_DOC\n\n\/\/\/ @brief The union operation in the cache.\ntemplate <typename C>\nstruct _LIBSDD_ATTRIBUTE_PACKED sum_op\n : nary_base<C, sum_op<C>>\n{\n typedef nary_base<C, sum_op<C>> base_type;\n\n template <typename... Args>\n sum_op(Args&&... args)\n : base_type(std::forward<Args>(args)...)\n {\n }\n\n \/\/\/ @brief Get the textual representation of the union operator.\n \/\/\/\n \/\/\/ Called by top to export a textual description.\n static\n char\n symbol()\n noexcept\n {\n return '+';\n }\n\n \/\/\/ @brief Perform the union algorithm.\n \/\/\/\n \/\/\/ It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD.\n \/\/\/ Also, a lot of tests permit to break loops as soon as possible.\n template <enum node_tag tag>\n SDD<C>\n work()\n const\n {\n typedef typename node_for_tag<C, tag>::type node_type;\n typedef typename node_type::valuation_type valuation_type;\n\n auto operands_cit = base_type::begin();\n const auto operands_end = base_type::end();\n\n \/\/ Get the first operand as a node, we need it to initialize the algorithm.\n const node_type& head = internal::mem::variant_cast<node_type>((*operands_cit)->data());\n\n \/\/ Type of the list of successors for a valuation, to be merged with the union operation\n \/\/ right before calling the square union.\n typedef sum_builder<C, SDD<C>> sum_builder_type;\n\n \/\/\/ TODO Use Boost.Intrusive to save on memory allocations?\n \/\/ List all the successors for each valuation in the final alpha.\n std::unordered_map<valuation_type, sum_builder_type> res(head.size());\n\n \/\/ Needed to temporarily store arcs erased from res and arcs from the alpha visited in\n \/\/ the loop (B).\n std::vector<std::pair<valuation_type, sum_builder_type>> save;\n save.reserve(head.size());\n\n \/\/ Used in test (F).\n std::vector<std::pair<valuation_type, sum_builder_type>> remainder;\n remainder.reserve(head.size());\n\n \/\/ Initialize res with the alpha of the first operand.\n for (auto& arc : head)\n {\n sum_builder_type succs;\n succs.add(arc.successor());\n res.emplace(arc.valuation(), std::move(succs));\n }\n\n \/\/ (A).\n for (++operands_cit; operands_cit != operands_end; ++operands_cit)\n {\n const auto res_end = res.end();\n\n const node_type& node = internal::mem::variant_cast<node_type>((*operands_cit)->data());\n const auto alpha_end = node.end();\n\n \/\/ (B). For each arc of the current operand.\n for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit)\n {\n \/\/ The current valuation may be modified, we need a copy.\n valuation_type current_val = alpha_cit->valuation();\n const SDD<C> current_succ = alpha_cit->successor();\n\n \/\/ Initialize the start of the next search.\n auto res_cit = res.begin();\n\n \/\/ (C). While the current valuation is not empty, test it against arcs in res.\n while (not current_val.empty() and res_cit != res_end)\n {\n const valuation_type& res_val = res_cit->first;\n sum_builder_type& res_succs = res_cit->second;\n\n \/\/ (D).\n if (current_val == res_val) \/\/ Same valuations.\n {\n save.emplace_back(res_val, std::move(res_succs));\n save.back().second.add(current_succ);\n const auto to_erase = res_cit;\n ++res_cit;\n res.erase(to_erase);\n \/\/ Avoid useless insertion or temporary variables.\n goto equality;\n }\n\n intersection_builder<C, valuation_type> inter_builder;\n inter_builder.add(current_val);\n inter_builder.add(res_val);\n const valuation_type inter = intersection(base_type::cxt_, std::move(inter_builder));\n\n \/\/ (E). The current valuation and the current arc from res have a common part.\n if (not inter.empty())\n {\n save.emplace_back(inter, res_succs);\n save.back().second.add(current_succ);\n\n \/\/ (F).\n valuation_type diff = difference(base_type::cxt_, res_val, inter);\n if (not diff.empty())\n {\n \/\/ (res_val - inter) can't be in intersection, but we need to keep it\n \/\/ for the next arcs of the current alpha. So we put in a temporary storage.\n \/\/ It will be added back in res when we have finished with the current valuation.\n remainder.emplace_back(std::move(diff), std::move(res_succs));\n }\n\n \/\/ We won't need the current arc of res for the current val, we already have the\n \/\/ common part. Now, the current valuation has to be tested against the next arcs\n \/\/ of res.\n const auto to_erase = res_cit;\n ++res_cit;\n res.erase(to_erase);\n\n \/\/ (G). The current valuation is completely included in the current arc of res.\n if (current_val == inter)\n {\n \/\/ We can move to the next arc of the current operand.\n break;\n }\n\n \/\/ Continue with what remains of val. if val is empy, the loop will stop at the\n \/\/ next iteration.\n current_val = difference(base_type::cxt_, current_val, inter);\n }\n else \/\/ (H). Empty intersection, lookup for next possible common parts.\n {\n ++res_cit;\n }\n } \/\/ While we're not at the end of res and val is not empty.\n\n \/\/ (I). For val or a part of val (it could have been modified during the previous\n \/\/ loop), we didn't find an intersection with any arc of res.\n if (not current_val.empty())\n {\n sum_builder_type succs;\n succs.add(current_succ);\n save.emplace_back(std::move(current_val), std::move(succs));\n }\n\n \/\/ Reinject all parts that were removed in (F).\n for (auto& rem : remainder)\n {\n res.emplace(std::move(rem.first), std::move(rem.second));\n }\n remainder.clear();\n\n \/\/ Both arcs had the same valuation: we just go to the next arc of the current operand.\n equality:;\n\n } \/\/ For each arc of the current operand.\n\n \/\/ Reinject all parts that were removed from res (all parts that have a non-empty\n \/\/ intersection with the current alpha) and all parts of the current alpha that have an\n \/\/ empty intersection with all the parts of res.\n res.insert(save.begin(), save.end());\n\n \/\/ We still need save.\n save.clear();\n } \/\/ End of iteration on operands.\n\n square_union<C, valuation_type> su;\n su.reserve(res.size());\n for (auto& arc : res)\n {\n \/\/ construct an operand for the square union: (successors union) --> valuation\n su.add(sum(base_type::cxt_, std::move(arc.second)), arc.first);\n }\n\n return SDD<C>(head.variable(), su(base_type::cxt_));\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Add an arc to the operands of the sum operation.\n\/\/\/\n\/\/\/ This implementation is meant to be used as a policy by nary_builder which doesn't know how\n\/\/\/ to add an arc.\ntemplate <typename C, typename Valuation>\nstruct _LIBSDD_ATTRIBUTE_PACKED sum_builder_impl\n{\n void\n add(boost::container::flat_set<Valuation>& set, Valuation&& operand)\n {\n if (not operand.empty())\n {\n set.insert(std::move(operand));\n }\n }\n\n void\n add(boost::container::flat_set<Valuation>& set, const Valuation& operand)\n {\n if (not operand.empty())\n {\n set.insert(operand);\n }\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief The sum operation of a set of SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>\nsum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder)\n{\n if (builder.empty())\n {\n return zero<C>();\n }\n else if (builder.size() == 1)\n {\n return *builder.begin();\n }\n return cxt.sum_cache()(sum_op<C>(cxt, builder));\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief The sum operation of a set of values.\n\/\/\/ @details A wrapper around the implementation of sum provided by Values.\ntemplate <typename C, typename Values>\ninline\nValues\nsum(context<C>&, sum_builder<C, Values>&& builder)\n{\n if (builder.empty())\n {\n return Values();\n }\n else if (builder.size() == 1)\n {\n return *builder.begin();\n }\n else\n {\n auto cit = builder.begin();\n const auto end = builder.end();\n Values result = *cit;\n for (++cit; cit != end; ++cit)\n {\n typename C::Values tmp = sum(result, *cit);\n using std::swap;\n swap(tmp, result);\n }\n return result;\n }\n}\n\n\/\/\/ @endcond\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Perform the union of two SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>\noperator+(const SDD<C>& lhs, const SDD<C>& rhs)\n{\n return sum(initial_context<C>(), {lhs, rhs});\n}\n\n\/\/\/ @brief Perform the union of two SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>&\noperator+=(SDD<C>& lhs, const SDD<C>& rhs)\n{\n SDD<C> tmp = sum(initial_context<C>(), {lhs, rhs});\n using std::swap;\n swap(tmp, lhs);\n return lhs;\n}\n\n\/\/\/ @brief Perform the union of an iterable container of SDD.\n\/\/\/ @related SDD\ntemplate <typename C, typename InputIterator>\nSDD<C>\ninline\nsum(InputIterator begin, InputIterator end)\n{\n sum_builder<C, SDD<C>> builder;\n for (; begin != end; ++begin)\n {\n builder.add(*begin);\n }\n return sum(initial_context<C>(), std::move(builder));\n}\n\n\/\/\/ @brief Perform the union of an initializer list of SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\nSDD<C>\ninline\nsum(std::initializer_list<SDD<C>> operands)\n{\n return sum<C>(std::begin(operands), std::end(operands));\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hash specialization for sdd::dd::sum_op\ntemplate <typename C>\nstruct hash<sdd::sum_op<C>>\n{\n std::size_t\n operator()(const sdd::sum_op<C>& sum)\n const noexcept\n {\n std::size_t seed = 0;\n for (const auto& operand : sum)\n {\n sdd::internal::util::hash_combine(seed, operand);\n }\n return seed;\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_DD_SUM_HH_\n<commit_msg>Fix SDD sum.<commit_after>#ifndef _SDD_DD_SUM_HH_\n#define _SDD_DD_SUM_HH_\n\n\/\/\/ @file sum.hh\n\/\/\/ @brief Contain all stuff to implement the union operation.\n\n#include <unordered_map>\n#include <vector>\n\n#include <boost\/container\/flat_set.hpp>\n\n#include \"sdd\/dd\/context_fwd.hh\"\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/dd\/nary.hh\"\n#include \"sdd\/dd\/operations_fwd.hh\"\n#include \"sdd\/dd\/square_union.hh\"\n#include \"sdd\/internal\/util\/hash.hh\"\n\nnamespace sdd {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @cond INTERNAL_DOC\n\n\/\/\/ @brief The union operation in the cache.\ntemplate <typename C>\nstruct _LIBSDD_ATTRIBUTE_PACKED sum_op\n : nary_base<C, sum_op<C>>\n{\n typedef nary_base<C, sum_op<C>> base_type;\n\n template <typename... Args>\n sum_op(Args&&... args)\n : base_type(std::forward<Args>(args)...)\n {\n }\n\n \/\/\/ @brief Get the textual representation of the union operator.\n \/\/\/\n \/\/\/ Called by top to export a textual description.\n static\n char\n symbol()\n noexcept\n {\n return '+';\n }\n\n \/\/\/ @brief Perform the union algorithm.\n \/\/\/\n \/\/\/ It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD.\n \/\/\/ Also, a lot of tests permit to break loops as soon as possible.\n template <enum node_tag tag>\n SDD<C>\n work()\n const\n {\n typedef typename node_for_tag<C, tag>::type node_type;\n typedef typename node_type::valuation_type valuation_type;\n\n auto operands_cit = base_type::begin();\n const auto operands_end = base_type::end();\n\n \/\/ Get the first operand as a node, we need it to initialize the algorithm.\n const node_type& head = internal::mem::variant_cast<node_type>((*operands_cit)->data());\n\n \/\/ Type of the list of successors for a valuation, to be merged with the union operation\n \/\/ right before calling the square union.\n typedef sum_builder<C, SDD<C>> sum_builder_type;\n\n \/\/\/ TODO Use Boost.Intrusive to save on memory allocations?\n \/\/ List all the successors for each valuation in the final alpha.\n std::unordered_map<valuation_type, sum_builder_type> res(head.size());\n\n \/\/ Needed to temporarily store arcs erased from res and arcs from the alpha visited in\n \/\/ the loop (B).\n std::vector<std::pair<valuation_type, sum_builder_type>> save;\n save.reserve(head.size());\n\n \/\/ Used in test (F).\n std::vector<std::pair<valuation_type, sum_builder_type>> remainder;\n remainder.reserve(head.size());\n\n \/\/ Initialize res with the alpha of the first operand.\n for (auto& arc : head)\n {\n sum_builder_type succs;\n succs.add(arc.successor());\n res.emplace(arc.valuation(), std::move(succs));\n }\n\n \/\/ (A).\n for (++operands_cit; operands_cit != operands_end; ++operands_cit)\n {\n const auto res_end = res.end();\n\n const node_type& node = internal::mem::variant_cast<node_type>((*operands_cit)->data());\n const auto alpha_end = node.end();\n\n \/\/ (B). For each arc of the current operand.\n for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit)\n {\n \/\/ The current valuation may be modified, we need a copy.\n valuation_type current_val = alpha_cit->valuation();\n const SDD<C> current_succ = alpha_cit->successor();\n\n \/\/ Initialize the start of the next search.\n auto res_cit = res.begin();\n\n \/\/ (C). While the current valuation is not empty, test it against arcs in res.\n while (not current_val.empty() and res_cit != res_end)\n {\n const valuation_type& res_val = res_cit->first;\n sum_builder_type& res_succs = res_cit->second;\n\n \/\/ (D).\n if (current_val == res_val) \/\/ Same valuations.\n {\n save.emplace_back(res_val, std::move(res_succs));\n save.back().second.add(current_succ);\n const auto to_erase = res_cit;\n ++res_cit;\n res.erase(to_erase);\n \/\/ Avoid useless insertion or temporary variables.\n goto equality;\n }\n\n intersection_builder<C, valuation_type> inter_builder;\n inter_builder.add(current_val);\n inter_builder.add(res_val);\n const valuation_type inter = intersection(base_type::cxt_, std::move(inter_builder));\n\n \/\/ (E). The current valuation and the current arc from res have a common part.\n if (not inter.empty())\n {\n save.emplace_back(inter, res_succs);\n save.back().second.add(current_succ);\n\n \/\/ (F).\n valuation_type diff = difference(base_type::cxt_, res_val, inter);\n if (not diff.empty())\n {\n \/\/ (res_val - inter) can't be in intersection, but we need to keep it\n \/\/ for the next arcs of the current alpha. So we put in a temporary storage.\n \/\/ It will be added back in res when we have finished with the current valuation.\n remainder.emplace_back(std::move(diff), std::move(res_succs));\n }\n\n \/\/ We won't need the current arc of res for the current val, we already have the\n \/\/ common part. Now, the current valuation has to be tested against the next arcs\n \/\/ of res.\n const auto to_erase = res_cit;\n ++res_cit;\n res.erase(to_erase);\n\n \/\/ (G). The current valuation is completely included in the current arc of res.\n if (current_val == inter)\n {\n \/\/ We can move to the next arc of the current operand.\n break;\n }\n\n \/\/ Continue with what remains of val. if val is empy, the loop will stop at the\n \/\/ next iteration.\n current_val = difference(base_type::cxt_, current_val, inter);\n }\n else \/\/ (H). Empty intersection, lookup for next possible common parts.\n {\n ++res_cit;\n }\n } \/\/ While we're not at the end of res and val is not empty.\n\n \/\/ (I). For val or a part of val (it could have been modified during the previous\n \/\/ loop), we didn't find an intersection with any arc of res.\n if (not current_val.empty())\n {\n sum_builder_type succs;\n succs.add(current_succ);\n save.emplace_back(std::move(current_val), std::move(succs));\n }\n\n \/\/ Both arcs had the same valuation.\n equality:;\n\n \/\/ Reinject all parts that were removed in (F).\n for (auto& rem : remainder)\n {\n res.emplace(std::move(rem.first), std::move(rem.second));\n }\n remainder.clear();\n\n } \/\/ For each arc of the current operand.\n\n \/\/ Reinject all parts that were removed from res (all parts that have a non-empty\n \/\/ intersection with the current alpha) and all parts of the current alpha that have an\n \/\/ empty intersection with all the parts of res.\n res.insert(save.begin(), save.end());\n\n \/\/ We still need save.\n save.clear();\n } \/\/ End of iteration on operands.\n\n square_union<C, valuation_type> su;\n su.reserve(res.size());\n for (auto& arc : res)\n {\n \/\/ construct an operand for the square union: (successors union) --> valuation\n su.add(sum(base_type::cxt_, std::move(arc.second)), arc.first);\n }\n\n return SDD<C>(head.variable(), su(base_type::cxt_));\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Add an arc to the operands of the sum operation.\n\/\/\/\n\/\/\/ This implementation is meant to be used as a policy by nary_builder which doesn't know how\n\/\/\/ to add an arc.\ntemplate <typename C, typename Valuation>\nstruct _LIBSDD_ATTRIBUTE_PACKED sum_builder_impl\n{\n void\n add(boost::container::flat_set<Valuation>& set, Valuation&& operand)\n {\n if (not operand.empty())\n {\n set.insert(std::move(operand));\n }\n }\n\n void\n add(boost::container::flat_set<Valuation>& set, const Valuation& operand)\n {\n if (not operand.empty())\n {\n set.insert(operand);\n }\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief The sum operation of a set of SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>\nsum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder)\n{\n if (builder.empty())\n {\n return zero<C>();\n }\n else if (builder.size() == 1)\n {\n return *builder.begin();\n }\n return cxt.sum_cache()(sum_op<C>(cxt, builder));\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief The sum operation of a set of values.\n\/\/\/ @details A wrapper around the implementation of sum provided by Values.\ntemplate <typename C, typename Values>\ninline\nValues\nsum(context<C>&, sum_builder<C, Values>&& builder)\n{\n if (builder.empty())\n {\n return Values();\n }\n else if (builder.size() == 1)\n {\n return *builder.begin();\n }\n else\n {\n auto cit = builder.begin();\n const auto end = builder.end();\n Values result = *cit;\n for (++cit; cit != end; ++cit)\n {\n typename C::Values tmp = sum(result, *cit);\n using std::swap;\n swap(tmp, result);\n }\n return result;\n }\n}\n\n\/\/\/ @endcond\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Perform the union of two SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>\noperator+(const SDD<C>& lhs, const SDD<C>& rhs)\n{\n return sum(initial_context<C>(), {lhs, rhs});\n}\n\n\/\/\/ @brief Perform the union of two SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\ninline\nSDD<C>&\noperator+=(SDD<C>& lhs, const SDD<C>& rhs)\n{\n SDD<C> tmp = sum(initial_context<C>(), {lhs, rhs});\n using std::swap;\n swap(tmp, lhs);\n return lhs;\n}\n\n\/\/\/ @brief Perform the union of an iterable container of SDD.\n\/\/\/ @related SDD\ntemplate <typename C, typename InputIterator>\nSDD<C>\ninline\nsum(InputIterator begin, InputIterator end)\n{\n sum_builder<C, SDD<C>> builder;\n for (; begin != end; ++begin)\n {\n builder.add(*begin);\n }\n return sum(initial_context<C>(), std::move(builder));\n}\n\n\/\/\/ @brief Perform the union of an initializer list of SDD.\n\/\/\/ @related SDD\ntemplate <typename C>\nSDD<C>\ninline\nsum(std::initializer_list<SDD<C>> operands)\n{\n return sum<C>(std::begin(operands), std::end(operands));\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Hash specialization for sdd::dd::sum_op\ntemplate <typename C>\nstruct hash<sdd::sum_op<C>>\n{\n std::size_t\n operator()(const sdd::sum_op<C>& sum)\n const noexcept\n {\n std::size_t seed = 0;\n for (const auto& operand : sum)\n {\n sdd::internal::util::hash_combine(seed, operand);\n }\n return seed;\n }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_DD_SUM_HH_\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <seqan\/sequence.h>\n#include <seqan\/file.h>\n\nusing namespace seqan;\n\/\/ Function to print simple alignment between two sequences with the same length\ntemplate <typename TText1, typename TText2>\nvoid printAlign(TText1 const & genomeFragment, TText2 const & read)\n{\n std::cout << \"Alignment \" << std::endl;\n std::cout << \" genome : \" << genomeFragment << std::endl;\n std::cout << \" read : \" << read << std::endl;\n}\nint main(int, char const **)\n{\n \/\/ Build reads and genomes\n DnaString chr1 = \"TATAATATTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCTAGATGTGCAGCTCGATCGAATGCACGTGTGTGCGATCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATTTAG\";\n \/\/ Build List containing all reads\n typedef String<DnaString> DnaList;\n DnaList readList;\n resize(readList, 4);\n readList[0] = \"TTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCT\";\n readList[1] = \"TCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATT\";\n readList[2] = \"AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACA\";\n readList[3] = \"CGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACA\";\n \/\/ Append a second chromosome sequence fragment to chr1\n DnaString chr2 = \"AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACACGTCTCTGTGTTCCGACGTGTGTCACGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACACATGCTGCTG\";\n append(chr1, chr2);\n \/\/ Print readlist\n std::cout << \" \\n Read list: \" << std::endl;\n for(unsigned i = 0; i < length(readList); ++i)\n std::cout << readList[i] << std::endl;\n \/\/ Assume we have mapped the 4 reads to chr1 (and chr2) and now have the mapping start positions (no gaps).\n \/\/ Store the start position in a String: 7, 100, 172, 272\n String<unsigned> alignPosList;\n resize(alignPosList, 4);\n alignPosList[0] = 7;\n alignPosList[1] = 100;\n alignPosList[2] = 172;\n alignPosList[3] = 272;\n \/\/ Print alignments using Segment\n std::cout << \" \\n Print alignment using Segment: \" << std::endl;\n for(unsigned i = 0; i < length(readList); ++i)\n {\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(readList[i]);\n \/\/ Build infix\n Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, readList[i]);\n }\n \n \/\/ Iterators :)\n \/\/ Print alignments using Iterators: Do the same as above, but use Iterators to iterate over the read list.\n \/\/ First, use Standard Iterators.\n Iterator<DnaList>::Type it = begin(readList);\n Iterator<DnaList, Standard>::Type itEnd = end(readList); \/\/same Iterator as above\n\n std::cout << \" \\n Print alignment using Standard Iterators: \" << std::endl;\n for(; it != itEnd; goNext(it))\n {\n \/\/ Get the right index for alignPosList\n int i = position(it, readList);\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(value(it));\n \/\/ Build Infix\n Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, value(it));\n }\n \n \/\/ Now, use Rooted Iterators.\n Iterator<DnaList, Rooted>::Type it2 = begin(readList);\n std::cout << \" \\n Print alignment using Rooted Iterators: \" << std::endl;\n for(; !atEnd(it2); goNext(it2))\n {\n int i = position(it2);\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(value(it2));\n \/\/ Build Infix\n Infix<DnaString>::Type genomeFragment = infix(bsChr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, value(it2));\n }\n \n \/\/ StringSets\n \/\/ Build StringSet of readList: Build a StringSet of DnaQString and append the reads from readList.\n \/\/ Reuse the Rooted Iterator from above.\n StringSet<DnaString> readStringSet;\n goBegin(it2);\n for(; !atEnd(it2); goNext(it2))\n appendValue(readStringSet, value(it2));\n \n \/\/ Iterate over StringSet\n Iterator<DnaListSet, Rooted>::Type it3 = begin(readStringSet);\n \n std::cout << \" \\n Print alignment using Rooted Iterators: \" << std::endl;\n for(; !atEnd(it3); goNext(it3))\n std::cout << value(it3) << std::endl;\n \n return 1;\n}\n<commit_msg>[DOC] Sequences\/StringSets tutorial assignment4 demo cpp revised.<commit_after>#include <iostream>\n#include <seqan\/sequence.h>\n#include <seqan\/file.h>\n\nusing namespace seqan;\n\/\/ Function to print simple alignment between two sequences with the same length\ntemplate <typename TText1, typename TText2>\nvoid printAlign(TText1 const & genomeFragment, TText2 const & read)\n{\n std::cout << \"Alignment \" << std::endl;\n std::cout << \" genome : \" << genomeFragment << std::endl;\n std::cout << \" read : \" << read << std::endl;\n}\nint main(int, char const **)\n{\n \/\/ Build reads and genomes\n DnaString chr1 = \"TATAATATTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCTAGATGTGCAGCTCGATCGAATGCACGTGTGTGCGATCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATTTAG\";\n \/\/ Build List containing all reads\n typedef String<DnaString> DnaList;\n DnaList readList;\n resize(readList, 4);\n readList[0] = \"TTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCT\";\n readList[1] = \"TCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATT\";\n readList[2] = \"AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACA\";\n readList[3] = \"CGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACA\";\n \/\/ Append a second chromosome sequence fragment to chr1\n DnaString chr2 = \"AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACACGTCTCTGTGTTCCGACGTGTGTCACGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACACATGCTGCTG\";\n append(chr1, chr2);\n \/\/ Print readlist\n std::cout << \" \\n Read list: \" << std::endl;\n for(unsigned i = 0; i < length(readList); ++i)\n std::cout << readList[i] << std::endl;\n \/\/ Assume we have mapped the 4 reads to chr1 (and chr2) and now have the mapping start positions (no gaps).\n \/\/ Store the start position in a String: 7, 100, 172, 272\n String<unsigned> alignPosList;\n resize(alignPosList, 4);\n alignPosList[0] = 7;\n alignPosList[1] = 100;\n alignPosList[2] = 172;\n alignPosList[3] = 272;\n \/\/ Print alignments using Segment\n std::cout << \" \\n Print alignment using Segment: \" << std::endl;\n for(unsigned i = 0; i < length(readList); ++i)\n {\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(readList[i]);\n \/\/ Build infix\n Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, readList[i]);\n }\n \n \/\/ Iterators :)\n \/\/ Print alignments using Iterators: Do the same as above, but use Iterators to iterate over the read list.\n \/\/ First, use Standard Iterators.\n Iterator<DnaList>::Type it = begin(readList);\n Iterator<DnaList, Standard>::Type itEnd = end(readList); \/\/same Iterator as above\n\n std::cout << \" \\n Print alignment using Standard Iterators: \" << std::endl;\n for(; it != itEnd; goNext(it))\n {\n \/\/ Get the right index for alignPosList\n int i = position(it, readList);\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(value(it));\n \/\/ Build Infix\n Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, value(it));\n }\n \n \/\/ Now, use Rooted Iterators.\n Iterator<DnaList, Rooted>::Type it2 = begin(readList);\n std::cout << \" \\n Print alignment using Rooted Iterators: \" << std::endl;\n for(; !atEnd(it2); goNext(it2))\n {\n int i = position(it2);\n \/\/ Begin and end position of a given alignment between the read and the genome\n unsigned beginPosition = alignPosList[i];\n unsigned endPosition = beginPosition + length(value(it2));\n \/\/ Build Infix\n Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);\n \/\/ Call of our function to print the simple alignment\n printAlign(genomeFragment, value(it2));\n }\n \n \/\/ StringSets\n \/\/ Build StringSet of readList: Build a StringSet of DnaQString and append the reads from readList.\n \/\/ Reuse the Rooted Iterator from above.\n typedef StringSet<DnaString> DnaListSet;\n DnaListSet readStringSet;\n goBegin(it2);\n for(; !atEnd(it2); goNext(it2))\n appendValue(readStringSet, value(it2));\n\n \/\/ Iterate over StringSet\n Iterator<DnaListSet, Rooted>::Type it3 = begin(readStringSet);\n \n std::cout << \" \\n Print alignment using Rooted Iterators: \" << std::endl;\n for(; !atEnd(it3); goNext(it3))\n std::cout << value(it3) << std::endl;\n \n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>SDL2: arrow keys on GamePad(#46)<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\/\/ CORE Update line 6\n\n#include \"addresstablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"base58.h\"\n#include \"wallet.h\"\n\n#include <QFont>\n#include <QDebug>\n\nconst QString AddressTableModel::Send = \"S\";\nconst QString AddressTableModel::Receive = \"R\";\n\nstruct AddressTableEntry\n{\n enum Type {\n Sending,\n Receiving,\n Hidden \/* QSortFilterProxyModel will filter these out *\/\n };\n\n Type type;\n QString label;\n QString address;\n\n AddressTableEntry() {}\n AddressTableEntry(Type type, const QString &label, const QString &address):\n type(type), label(label), address(address) {}\n};\n\nstruct AddressTableEntryLessThan\n{\n bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const\n {\n return a.address < b.address;\n }\n bool operator()(const AddressTableEntry &a, const QString &b) const\n {\n return a.address < b;\n }\n bool operator()(const QString &a, const AddressTableEntry &b) const\n {\n return a < b.address;\n }\n};\n\n\/* Determine address type from address purpose *\/\nstatic AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine)\n{\n AddressTableEntry::Type addressType = AddressTableEntry::Hidden;\n \/\/ \"refund\" addresses aren't shown, and change addresses aren't in mapAddressBook at all.\n if (strPurpose == \"send\")\n addressType = AddressTableEntry::Sending;\n else if (strPurpose == \"receive\")\n addressType = AddressTableEntry::Receiving;\n else if (strPurpose == \"unknown\" || strPurpose == \"\") \/\/ if purpose not set, guess\n addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);\n return addressType;\n}\n\n\/\/ Private implementation\nclass AddressTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AddressTableEntry> cachedAddressTable;\n AddressTableModel *parent;\n\n AddressTablePriv(CWallet *wallet, AddressTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAddressTable()\n {\n cachedAddressTable.clear();\n {\n LOCK(wallet->cs_wallet);\n BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook)\n {\n const CBitcoinAddress& address = item.first;\n bool fMine = IsMine(*wallet, address.Get());\n AddressTableEntry::Type addressType = translateTransactionType(\n QString::fromStdString(item.second.purpose), fMine);\n const std::string& strName = item.second.name;\n cachedAddressTable.append(AddressTableEntry(addressType,\n QString::fromStdString(strName),\n QString::fromStdString(address.ToString())));\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order\n \/\/ Even though the map is already sorted this re-sorting step is needed because the originating map\n \/\/ is sorted by binary address, not by base58() address.\n qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());\n }\n\n void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status)\n {\n \/\/ Find address \/ label in model\n QList<AddressTableEntry>::iterator lower = qLowerBound(\n cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());\n QList<AddressTableEntry>::iterator upper = qUpperBound(\n cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());\n int lowerIndex = (lower - cachedAddressTable.begin());\n int upperIndex = (upper - cachedAddressTable.begin());\n bool inModel = (lower != upper);\n AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);\n\n switch(status)\n {\n case CT_NEW:\n if(inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model\";\n break;\n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model\";\n break;\n }\n lower->type = newEntryType;\n lower->label = label;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model\";\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAddressTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAddressTable.size();\n }\n\n AddressTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAddressTable.size())\n {\n return &cachedAddressTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0)\n{\n columns << tr(\"Label\") << tr(\"Address\");\n priv = new AddressTablePriv(wallet, this);\n priv->refreshAddressTable();\n}\n\nAddressTableModel::~AddressTableModel()\n{\n delete priv;\n}\n\nint AddressTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AddressTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AddressTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Label:\n if(rec->label.isEmpty() && role == Qt::DisplayRole)\n {\n return tr(\"(no label)\");\n }\n else\n {\n return rec->label;\n }\n case Address:\n return rec->address;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Address)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AddressTableEntry::Sending:\n return Send;\n case AddressTableEntry::Receiving:\n return Receive;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n std::string strPurpose = (rec->type == AddressTableEntry::Sending ? \"send\" : \"receive\");\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n LOCK(wallet->cs_wallet); \/* For SetAddressBook \/ DelAddressBook *\/\n CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();\n if(index.column() == Label)\n {\n \/\/ Do nothing, if old label == new label\n if(rec->label == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);\n } else if(index.column() == Address) {\n CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();\n \/\/ Refuse to set invalid address, set error status and return false\n if(boost::get<CNoDestination>(&newAddress))\n {\n editStatus = INVALID_ADDRESS;\n return false;\n }\n \/\/ Do nothing, if old address == new address\n else if(newAddress == curAddress)\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate addresses to prevent accidental deletion of addresses, if you try\n \/\/ to paste an existing address over another address (with a different label)\n else if(wallet->mapAddressBook.count(newAddress))\n {\n editStatus = DUPLICATE_ADDRESS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving address\n else if(rec->type == AddressTableEntry::Sending)\n {\n \/\/ Remove old entry\n wallet->DelAddressBook(curAddress);\n \/\/ Add new entry with new address\n wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);\n }\n }\n return true;\n }\n return false;\n}\n\nQVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole && section < columns.size())\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n \/\/ Can edit address and label for sending addresses,\n \/\/ and only label for receiving addresses.\n if(rec->type == AddressTableEntry::Sending ||\n (rec->type == AddressTableEntry::Receiving && index.column()==Label))\n {\n retval |= Qt::ItemIsEditable;\n }\n return retval;\n}\n\nQModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AddressTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AddressTableModel::updateEntry(const QString &address,\n const QString &label, bool isMine, const QString &purpose, int status)\n{\n \/\/ Update address book model from Bitcoin core\n priv->updateEntry(address, label, isMine, purpose, status);\n}\n\nQString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address)\n{\n std::string strLabel = label.toStdString();\n std::string strAddress = address.toStdString();\n\n editStatus = OK;\n\n if(type == Send)\n {\n if(!walletModel->validateAddress(address))\n {\n editStatus = INVALID_ADDRESS;\n return QString();\n }\n \/\/ Check for duplicate addresses\n {\n LOCK(wallet->cs_wallet);\n if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get()))\n {\n editStatus = DUPLICATE_ADDRESS;\n return QString();\n }\n }\n }\n else if(type == Receive)\n {\n \/\/ Generate a new address to associate with given label\n CPubKey newKey;\n if(!wallet->GetKeyFromPool(newKey))\n {\n WalletModel::UnlockContext ctx(walletModel->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet failed or was cancelled\n editStatus = WALLET_UNLOCK_FAILURE;\n return QString();\n }\n if(!wallet->GetKeyFromPool(newKey))\n {\n editStatus = KEY_GENERATION_FAILURE;\n return QString();\n }\n }\n strAddress = CBitcoinAddress(newKey.GetID()).ToString();\n }\n else\n {\n return QString();\n }\n\n \/\/ Add entry\n {\n LOCK(wallet->cs_wallet);\n wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,\n (type == Send ? \"send\" : \"receive\"));\n }\n return QString::fromStdString(strAddress);\n}\n\nbool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent)\n{\n Q_UNUSED(parent);\n AddressTableEntry *rec = priv->index(row);\n if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)\n {\n \/\/ Can only remove one row at a time, and cannot remove rows not in model.\n \/\/ Also refuse to remove receiving addresses.\n return false;\n }\n {\n LOCK(wallet->cs_wallet);\n wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());\n }\n return true;\n}\n\n\/* Look up label for address in address book, if not found return empty string.\n *\/\nQString AddressTableModel::labelForAddress(const QString &address) const\n{\n {\n LOCK(wallet->cs_wallet);\n CBitcoinAddress address_parsed(address.toStdString());\n std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());\n if (mi != wallet->mapAddressBook.end())\n {\n return QString::fromStdString(mi->second.name);\n }\n }\n return QString();\n}\n\nint AddressTableModel::lookupAddress(const QString &address) const\n{\n QModelIndexList lst = match(index(0, Address, QModelIndex()),\n Qt::EditRole, address, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AddressTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<commit_msg>Update addresstablemodel.cpp<commit_after>\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\/\/ CORE Update line 6\n\n#include \"addresstablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"base58.h\"\n#include \"wallet.h\"\n\n#include <QFont>\n#include <QDebug>\n\nconst QString AddressTableModel::Send = \"S\";\nconst QString AddressTableModel::Receive = \"R\";\n\nstruct AddressTableEntry\n{\n enum Type {\n Sending,\n Receiving,\n Hidden \/* QSortFilterProxyModel will filter these out *\/\n };\n\n Type type;\n QString label;\n QString address;\n\n AddressTableEntry() {}\n AddressTableEntry(Type type, const QString &label, const QString &address):\n type(type), label(label), address(address) {}\n};\n\nstruct AddressTableEntryLessThan\n{\n bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const\n {\n return a.address < b.address;\n }\n bool operator()(const AddressTableEntry &a, const QString &b) const\n {\n return a.address < b;\n }\n bool operator()(const QString &a, const AddressTableEntry &b) const\n {\n return a < b.address;\n }\n};\n\n\/* Determine address type from address purpose *\/\nstatic AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine)\n{\n AddressTableEntry::Type addressType = AddressTableEntry::Hidden;\n \/\/ \"refund\" addresses aren't shown, and change addresses aren't in mapAddressBook at all.\n if (strPurpose == \"send\")\n addressType = AddressTableEntry::Sending;\n else if (strPurpose == \"receive\")\n addressType = AddressTableEntry::Receiving;\n else if (strPurpose == \"unknown\" || strPurpose == \"\") \/\/ if purpose not set, guess\n addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);\n return addressType;\n}\n\n\/\/ Private implementation\nclass AddressTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AddressTableEntry> cachedAddressTable;\n AddressTableModel *parent;\n\n AddressTablePriv(CWallet *wallet, AddressTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAddressTable()\n {\n cachedAddressTable.clear();\n {\n LOCK(wallet->cs_wallet);\n BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook)\n {\n const CBitcoinAddress& address = item.first;\n bool fMine = IsMine(*wallet, address.Get());\n AddressTableEntry::Type addressType = translateTransactionType(\n QString::fromStdString(item.second.purpose), fMine);\n const std::string& strName = item.second.name;\n cachedAddressTable.append(AddressTableEntry(addressType,\n QString::fromStdString(strName),\n QString::fromStdString(address.ToString())));\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order\n \/\/ Even though the map is already sorted this re-sorting step is needed because the originating map\n \/\/ is sorted by binary address, not by base58() address.\n qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());\n }\n\n void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status)\n {\n \/\/ Find address \/ label in model\n QList<AddressTableEntry>::iterator lower = qLowerBound(\n cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());\n QList<AddressTableEntry>::iterator upper = qUpperBound(\n cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());\n int lowerIndex = (lower - cachedAddressTable.begin());\n int upperIndex = (upper - cachedAddressTable.begin());\n bool inModel = (lower != upper);\n AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);\n\n switch(status)\n {\n case CT_NEW:\n if(inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model\";\n break;\n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model\";\n break;\n }\n lower->type = newEntryType;\n lower->label = label;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n qWarning() << \"AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model\";\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAddressTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAddressTable.size();\n }\n\n AddressTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAddressTable.size())\n {\n return &cachedAddressTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0)\n{\n columns << tr(\"Label\") << tr(\"Address\");\n priv = new AddressTablePriv(wallet, this);\n priv->refreshAddressTable();\n}\n\nAddressTableModel::~AddressTableModel()\n{\n delete priv;\n}\n\nint AddressTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AddressTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AddressTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Label:\n if(rec->label.isEmpty() && role == Qt::DisplayRole)\n {\n return tr(\"(no label)\");\n }\n else\n {\n return rec->label;\n }\n case Address:\n return rec->address;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Address)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AddressTableEntry::Sending:\n return Send;\n case AddressTableEntry::Receiving:\n return Receive;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n std::string strPurpose = (rec->type == AddressTableEntry::Sending ? \"send\" : \"receive\");\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n LOCK(wallet->cs_wallet); \/* For SetAddressBook \/ DelAddressBook *\/\n CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();\n if(index.column() == Label)\n {\n \/\/ Do nothing, if old label == new label\n if(rec->label == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);\n } else if(index.column() == Address) {\n CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();\n \/\/ Refuse to set invalid address, set error status and return false\n if(boost::get<CNoDestination>(&newAddress))\n {\n editStatus = INVALID_ADDRESS;\n return false;\n }\n \/\/ Do nothing, if old address == new address\n else if(newAddress == curAddress)\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate addresses to prevent accidental deletion of addresses, if you try\n \/\/ to paste an existing address over another address (with a different label)\n else if(wallet->mapAddressBook.count(newAddress))\n {\n editStatus = DUPLICATE_ADDRESS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving address\n else if(rec->type == AddressTableEntry::Sending)\n {\n \/\/ Remove old entry\n wallet->DelAddressBook(curAddress);\n \/\/ Add new entry with new address\n wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);\n }\n }\n return true;\n }\n return false;\n}\n\nQVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole && section < columns.size())\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());\n\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n \/\/ Can edit address and label for sending addresses,\n \/\/ and only label for receiving addresses.\n if(rec->type == AddressTableEntry::Sending ||\n (rec->type == AddressTableEntry::Receiving && index.column()==Label))\n {\n retval |= Qt::ItemIsEditable;\n }\n return retval;\n}\n\nQModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AddressTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AddressTableModel::updateEntry(const QString &address,\n const QString &label, bool isMine, const QString &purpose, int status)\n{\n \/\/ Update address book model from Bitcoin core\n priv->updateEntry(address, label, isMine, purpose, status);\n}\n\nQString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address)\n{\n std::string strLabel = label.toStdString();\n std::string strAddress = address.toStdString();\n\n editStatus = OK;\n\n if(type == Send)\n {\n if(!walletModel->validateAddress(address))\n {\n editStatus = INVALID_ADDRESS;\n return QString();\n }\n \/\/ Check for duplicate addresses\n {\n LOCK(wallet->cs_wallet);\n if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get()))\n {\n editStatus = DUPLICATE_ADDRESS;\n return QString();\n }\n }\n }\n else if(type == Receive)\n {\n \/\/ Generate a new address to associate with given label\n CPubKey newKey;\n if(!wallet->GetKeyFromPool(newKey))\n {\n WalletModel::UnlockContext ctx(walletModel->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet failed or was cancelled\n editStatus = WALLET_UNLOCK_FAILURE;\n return QString();\n }\n if(!wallet->GetKeyFromPool(newKey))\n {\n editStatus = KEY_GENERATION_FAILURE;\n return QString();\n }\n }\n strAddress = CBitcoinAddress(newKey.GetID()).ToString();\n }\n else\n {\n return QString();\n }\n\n \/\/ Add entry\n {\n LOCK(wallet->cs_wallet);\n wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,\n (type == Send ? \"send\" : \"receive\"));\n }\n return QString::fromStdString(strAddress);\n}\n\nbool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent)\n{\n Q_UNUSED(parent);\n AddressTableEntry *rec = priv->index(row);\n if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)\n {\n \/\/ Can only remove one row at a time, and cannot remove rows not in model.\n \/\/ Also refuse to remove receiving addresses.\n return false;\n }\n {\n LOCK(wallet->cs_wallet);\n wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());\n }\n return true;\n}\n\n\/* Look up label for address in address book, if not found return empty string.\n *\/\nQString AddressTableModel::labelForAddress(const QString &address) const\n{\n {\n LOCK(wallet->cs_wallet);\n CBitcoinAddress address_parsed(address.toStdString());\n std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());\n if (mi != wallet->mapAddressBook.end())\n {\n return QString::fromStdString(mi->second.name);\n }\n }\n return QString();\n}\n\nint AddressTableModel::lookupAddress(const QString &address) const\n{\n QModelIndexList lst = match(index(0, Address, QModelIndex()),\n Qt::EditRole, address, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AddressTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"transactionrecord.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n\n\nstd::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);\nstd::string RoundToString(double d, int place);\ndouble DoubleFromAmount(int64_t amount);\n\nbool IsLockTimeWithinMinutes(int64_t locktime, int minutes);\n\n\n\/* Return positive answer if transaction should be shown in list. *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n\t\n\tstd::string ShowOrphans = GetArg(\"-showorphans\", \"false\");\n\tif (ShowOrphans==\"false\" && !wtx.IsInMainChain()) return false;\n\t\/\/R Halford - Discard Orphans after Y mins:\n\tif (wtx.IsCoinStake())\n\t{\n\t\tif (!wtx.IsInMainChain())\n\t\t{\n\t\t\t\/\/Orphaned tx\n\t\t\tif (ShowOrphans==\"true\" && IsLockTimeWithinMinutes(wtx.nTimeReceived,15)) \n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n return true;\n}\n\n\tint64_t GetMyValueOut(const CWallet *wallet,const CWalletTx &wtx)\n {\n int64_t nValueOut = 0;\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n {\n\t if (wallet->IsMine(txout))\n\t\t {\n\t\t\t\tnValueOut += txout.nValue;\n\t\t }\n }\n return nValueOut;\n }\n\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList<TransactionRecord> parts;\n int64_t nTime = wtx.GetTxTime();\n int64_t nCredit = wtx.GetCredit(true);\n int64_t nDebit = wtx.GetDebit();\n int64_t nNet = nCredit - nDebit;\n uint256 hash = wtx.GetHash(), hashPrev = 0;\n std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())\n {\n \/\/\n \/\/ Credit - Calculate Net from CryptoLottery Rob Halford - 4-3-2015-1\n \/\/\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n {\n if(wallet->IsMine(txout))\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.credit = txout.nValue;\n if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.address = mapValue[\"from\"];\n }\n if (wtx.IsCoinBase())\n {\n \/\/ Generated (proof-of-work)\n sub.type = TransactionRecord::Generated;\n }\n if (wtx.IsCoinStake())\n {\n \/\/ Generated (proof-of-stake)\n\t\t\t if (hashPrev == hash)\n continue; \/\/ last coinstake output\n\n\t\t\t\t\tif (wtx.vout.size()==2)\n\t\t\t\t\t{ \n\t\t\t\t\t\t\/\/Standard POR CoinStake\n\t\t\t\t\t\tsub.type = TransactionRecord::Generated;\n\t\t\t\t\t\tsub.credit = nNet > 0 ? nNet : wtx.GetValueOut() - nDebit;\n\t\t\t\t\t\thashPrev = hash;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/CryptoLottery - CoinStake - 4-3-2015\n\t\t\t\t\t\tsub.type = TransactionRecord::Generated;\n\t\t\t\t\t\tif (nDebit == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsub.credit = GetMyValueOut(wallet,wtx);\n\t\t\t\t\t\t\tsub.RemoteFlag = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsub.credit = nNet > 0 ? nNet : GetMyValueOut(wallet,wtx) - nDebit;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\thashPrev = hash;\n\t\t\t\n\t\t\t\t\t}\n }\n\n parts.append(sub);\n }\n }\n }\n else\n {\n bool fAllFromMe = true;\n BOOST_FOREACH(const CTxIn& txin, wtx.vin)\n fAllFromMe = fAllFromMe && wallet->IsMine(txin);\n\n bool fAllToMe = true;\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n fAllToMe = fAllToMe && wallet->IsMine(txout);\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n int64_t nChange = wtx.GetChange();\n\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n -(nDebit - nChange), nCredit - nChange));\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut& txout = wtx.vout[nOut];\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n\n if(wallet->IsMine(txout))\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n CTxDestination address;\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n sub.address = mapValue[\"to\"];\n }\n\n int64_t nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0));\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex* pindex = NULL;\n std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n (wtx.IsCoinBase() ? 1 : 0),\n wtx.nTimeReceived,\n idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = nBestHeight;\n\n if (!IsFinalTx(wtx, nBestHeight + 1))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - nBestHeight;\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n\n \/\/ For generated transactions, determine maturity\n else if(type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != nBestHeight;\n}\n\nstd::string TransactionRecord::getTxID()\n{\n return hash.ToString() + strprintf(\"-%03d\", idx);\n}\n\n\n<commit_msg>3.4.0.8b<commit_after>#include \"transactionrecord.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n\n\nstd::string GetTxProject(uint256 hash, int& out_blocknumber, int& out_blocktype, double& out_rac);\nstd::string RoundToString(double d, int place);\ndouble DoubleFromAmount(int64_t amount);\n\nbool IsLockTimeWithinMinutes(int64_t locktime, int minutes);\n\n\nbool IsSmartContractForDPOR(const CWalletTx &wtx)\n{\n bool result = false;\n QList<TransactionRecord> parts;\n int64_t nTime = wtx.GetTxTime();\n uint256 hash = wtx.GetHash(), hashPrev = 0;\n \n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut& txout = wtx.vout[nOut];\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n \n\n CTxDestination address;\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n sub.type = TransactionRecord::SendToAddress;\n sub.address = CBitcoinAddress(address).ToString();\n\t\t\t\t\tint64_t nDebit = wtx.GetDebit();\n\t\t\t\t if (nDebit=.00001 && sub.address ==\"S67nL4vELWwdDVzjgtEP4MxryarTZ9a8GB\")\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n }\n \n }\n return false;\n}\n\n\n\/* Return positive answer if transaction should be shown in list. *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n\t\n\tstd::string ShowOrphans = GetArg(\"-showorphans\", \"false\");\n\tif (ShowOrphans==\"false\" && !wtx.IsInMainChain()) return false;\n\tif (IsSmartContractForDPOR(wtx)) return false;\n\t\/\/R Halford - Discard Orphans after Y mins:\n\tif (wtx.IsCoinStake())\n\t{\n\t\tif (!wtx.IsInMainChain())\n\t\t{\n\t\t\t\/\/Orphaned tx\n\t\t\tif (ShowOrphans==\"true\" && IsLockTimeWithinMinutes(wtx.nTimeReceived,15)) \n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n return true;\n}\n\n\tint64_t GetMyValueOut(const CWallet *wallet,const CWalletTx &wtx)\n {\n int64_t nValueOut = 0;\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n {\n\t if (wallet->IsMine(txout))\n\t\t {\n\t\t\t\tnValueOut += txout.nValue;\n\t\t }\n }\n return nValueOut;\n }\n\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList<TransactionRecord> parts;\n int64_t nTime = wtx.GetTxTime();\n int64_t nCredit = wtx.GetCredit(true);\n int64_t nDebit = wtx.GetDebit();\n int64_t nNet = nCredit - nDebit;\n uint256 hash = wtx.GetHash(), hashPrev = 0;\n std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())\n {\n \/\/\n \/\/ Credit - Calculate Net from CryptoLottery Rob Halford - 4-3-2015-1\n \/\/\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n {\n if(wallet->IsMine(txout))\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.credit = txout.nValue;\n if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.address = mapValue[\"from\"];\n }\n if (wtx.IsCoinBase())\n {\n \/\/ Generated (proof-of-work)\n sub.type = TransactionRecord::Generated;\n }\n if (wtx.IsCoinStake())\n {\n \/\/ Generated (proof-of-stake)\n\t\t\t if (hashPrev == hash)\n continue; \/\/ last coinstake output\n\n\t\t\t\t\tif (wtx.vout.size()==2)\n\t\t\t\t\t{ \n\t\t\t\t\t\t\/\/Standard POR CoinStake\n\t\t\t\t\t\tsub.type = TransactionRecord::Generated;\n\t\t\t\t\t\tsub.credit = nNet > 0 ? nNet : wtx.GetValueOut() - nDebit;\n\t\t\t\t\t\thashPrev = hash;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/CryptoLottery - CoinStake - 4-3-2015\n\t\t\t\t\t\tsub.type = TransactionRecord::Generated;\n\t\t\t\t\t\tif (nDebit == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsub.credit = GetMyValueOut(wallet,wtx);\n\t\t\t\t\t\t\tsub.RemoteFlag = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsub.credit = nNet > 0 ? nNet : GetMyValueOut(wallet,wtx) - nDebit;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\thashPrev = hash;\n\t\t\t\n\t\t\t\t\t}\n }\n\n parts.append(sub);\n }\n }\n }\n else\n {\n bool fAllFromMe = true;\n BOOST_FOREACH(const CTxIn& txin, wtx.vin)\n fAllFromMe = fAllFromMe && wallet->IsMine(txin);\n\n bool fAllToMe = true;\n BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n fAllToMe = fAllToMe && wallet->IsMine(txout);\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n int64_t nChange = wtx.GetChange();\n\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n -(nDebit - nChange), nCredit - nChange));\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut& txout = wtx.vout[nOut];\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n\n if(wallet->IsMine(txout))\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n CTxDestination address;\n if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n sub.address = CBitcoinAddress(address).ToString();\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n sub.address = mapValue[\"to\"];\n }\n\n int64_t nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0));\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex* pindex = NULL;\n std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n (wtx.IsCoinBase() ? 1 : 0),\n wtx.nTimeReceived,\n idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = nBestHeight;\n\n if (!IsFinalTx(wtx, nBestHeight + 1))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - nBestHeight;\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n\n \/\/ For generated transactions, determine maturity\n else if(type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != nBestHeight;\n}\n\nstd::string TransactionRecord::getTxID()\n{\n return hash.ToString() + strprintf(\"-%03d\", idx);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(nlogn)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n int splitArray(vector<int>& nums, int m) {\n int left = 0, right = 0;\n for (const auto& num : nums) {\n left = max(left, num);\n right += num;\n }\n\n while (left <= right) {\n int mid = left + (right - left) \/ 2;\n if (canSplit(nums, m, mid)) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n\nprivate:\n bool canSplit(vector<int>& nums, int m, int sum) {\n int cnt = 1;\n int curr_sum = 0;\n for (const auto& num : nums) {\n curr_sum += num;\n if (curr_sum > sum) {\n curr_sum = num;\n ++cnt;\n }\n }\n return cnt <= m;\n }\n};\n<commit_msg>Update split-array-largest-sum.cpp<commit_after>\/\/ Time: O(nlogn)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n int splitArray(vector<int>& nums, int m) {\n int left = 0, right = 0;\n for (const auto& num : nums) {\n left = max(left, num);\n right += num;\n }\n\n while (left <= right) {\n const auto mid = left + (right - left) \/ 2;\n if (canSplit(nums, m, mid)) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n\nprivate:\n bool canSplit(vector<int>& nums, int m, int sum) {\n int cnt = 1, curr_sum = 0;\n for (const auto& num : nums) {\n curr_sum += num;\n if (curr_sum > sum) {\n curr_sum = num;\n ++cnt;\n }\n }\n return cnt <= m;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"potholedetector.h\"\n#include <opencv2\/video\/video.hpp>\n#include <sensor_msgs\/image_encodings.h>\n#include <pcl_ros\/point_cloud.h>\n#include <camera_info_manager\/camera_info_manager.h>\n#include <math.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <sensor_msgs\/image_encodings.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\n\ncv_bridge::CvImagePtr cv_ptr;\ntypedef pcl::PointCloud<pcl::PointXYZ> PCLCloud;\n\nconst int maxRadius = 150;\nconst int minRadius = 20;\n\n\/\/ Set 1 to disable\nconst int minWhiteThreshold = 255 * 0.30;\nconst int maxWhiteThreshold = 255 * 1;\n\nconst int sizeThreshold = 200;\n\nvoid PotholeDetector::img_callback(const sensor_msgs::ImageConstPtr& msg) {\n cv_ptr = cv_bridge::toCvCopy(msg, \"\");\n Mat orig = cv_ptr->image.clone();\n src = cv_ptr->image.clone();\n\n \/\/Crops the image (removes sky)\n int topCrop = src.rows \/ 2 - 100;\n cv::Rect myROI(0, topCrop, src.cols, src.rows - topCrop);\n src = src(myROI);\n\n cvtColor(src, src_gray, CV_BGR2GRAY);\n\n \/\/Find the mean and stddev of the grayscale image in order to do adaptive thresholding\n Mat mean;\n Mat stddev;\n meanStdDev(src_gray, mean, stddev);\n\n double thresh = mean.at<double>(0,0) + (stddev.at<double>(0,0) * 2);\n if(thresh > 254) {\n thresh = 254;\n }\n\n threshold(src_gray, src_gray, thresh, 255, THRESH_BINARY);\n\n GaussianBlur(src_gray, src_gray, Size(gaussian_size, gaussian_size), 2, 2);\n\n vector<Vec3f> circles;\n\n \/\/ TODO tune circle radii for actual potholes\n HoughCircles(src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows \/ 8, 50, 10, minRadius, maxRadius);\n\n Mat cloudMat = Mat::zeros(orig.rows, orig.cols, CV_32F);\n \/\/\/ Put the circles into a matrix\n for( size_t i = 0; i < circles.size(); i++ ) {\n Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n int radius = cvRound(circles[i][2]);\n\n \/\/ If the circle is too close to the top \/ bottom edges, filter\n if (center.y <= 100 || center.y >= src_gray.rows - 100) {\n continue;\n }\n\n \/\/ If the circle is too close to the left \/ right edges, filter\n if (center.x <= 200 || center.x >= src_gray.cols - 200) {\n continue;\n }\n\n int cropSize = (100 \/ (double) src_gray.rows) * center.y;\n \/\/Get a matrix around circle center\n cv::Rect myROI(center.x - (cropSize * 2), center.y - cropSize, cropSize * 4, cropSize * 2);\n Mat roi = src_gray(myROI);\n\n \/\/ If the sum of all the pixels in the rectangle is less than sumThreshold\n \/\/ Then this circle is not encompassing mostly white pixels\n const int sumThreshold = (cropSize * cropSize * 8);\n double sum = cv::sum(roi)[0];\n if (sum < sumThreshold * minWhiteThreshold || sum > sumThreshold * maxWhiteThreshold) {\n continue;\n }\n\n \/\/circle(cloudMat, center, radius, Scalar(255), 1, 8, 0);\n rectangle(src, myROI, Scalar(255), 2, 8, 0);\n cerr << \"\" + to_string(cropSize) + \" \" + to_string(radius) << endl;\n circle(src, center, radius, Scalar(255), 2, 8, 0);\n\n Point offset(center.x - (cropSize * 2), center.y - cropSize);\n vector<vector<Point>> contours;\n findContours(roi, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE, Point((center.x - (cropSize * 2)), center.y - cropSize));\n\n \/\/ Filter false positives - small contours and cone stripes\n for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); ++it) {\n vector<Point> curCont = *it;\n if (curCont.size() <= sizeThreshold) {\n contours.erase(it);\n --it;\n }\n }\n\n drawContours(src, contours, -1, Scalar(20, 236, 27), 3, 8);\n }\n\n cvtColor(src_gray, src_gray, CV_GRAY2BGR);\n\n cv_bridge::CvImage out_msg;\n out_msg.header = msg->header;\n out_msg.encoding = msg->encoding;\n out_msg.image = src;\n\n cv_ptr->image = src;\n _pothole_filt_img.publish(cv_ptr->toImageMsg());\n _pothole_thres.publish(out_msg.toImageMsg());\n cloud = toPointCloud(cloudMat);\n _pothole_cloud.publish(cloud);\n}\n\nPotholeDetector::PotholeDetector(ros::NodeHandle &handle)\n : gaussian_size(7),\n _it(handle),\n tf_listener(handle) {\n _src_img = _it.subscribe(\"\/stereo\/right\/image_raw\", 1, &PotholeDetector::img_callback, this);\n _pothole_filt_img = _it.advertise(\"\/pothole_filt_img\", 1);\n _pothole_thres = _it.advertise(\"\/pothole_thres\", 1);\n _pothole_cloud = handle.advertise<PCLCloud>(\"\/pothole_cloud\", 100);\n}\n\n\/\/ FIXME does not take into account distance from groud to camera\nPointCloud<PointXYZ>::Ptr PotholeDetector::toPointCloud(Mat src) {\n PointCloud<PointXYZ>::Ptr cloud(new PointCloud<PointXYZ>);\n for(int r = 0; r < src.rows; r++) {\n float *row = src.ptr<float>(r);\n for(int c = 0; c < src.cols; c++) {\n if(row[c] > 0) {\n cloud->points.push_back(PointXYZ(r, c, 0));\n }\n }\n }\n\tcloud->header.frame_id = \"base_footprint\";\n\treturn cloud;\n}\n<commit_msg>Changed initial sampling and white thresholding code. Need to work on detetecting false positives in the grass.<commit_after>#include \"potholedetector.h\"\n#include <opencv2\/video\/video.hpp>\n#include <sensor_msgs\/image_encodings.h>\n#include <pcl_ros\/point_cloud.h>\n#include <camera_info_manager\/camera_info_manager.h>\n#include <math.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <sensor_msgs\/image_encodings.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\n\ncv_bridge::CvImagePtr cv_ptr;\ntypedef pcl::PointCloud<pcl::PointXYZ> PCLCloud;\n\nconst int maxRadius = 50;\nconst int minRadius = 10;\n\n\/\/ Set 1 to disable\nconst int minWhiteThreshold = 255 * 0.60;\nconst int maxWhiteThreshold = 255 * 1;\nconst int whiteSampleRadius = 30;\n\nconst int sizeThreshold = 200;\n\nconst int lightROrange = 230;\nconst int lightGOrange = 180;\nconst int lightBOrange = 180;\nconst int darkROrange = 140;\nconst int darkGOrange = 50;\nconst int darkBOrange = 40;\n\nint getDiff(int a, int b) {\n return abs(a - b);\n}\n\nvoid PotholeDetector::img_callback(const sensor_msgs::ImageConstPtr& msg) {\n cv_ptr = cv_bridge::toCvCopy(msg, \"\");\n Mat orig = cv_ptr->image.clone();\n src = cv_ptr->image.clone();\n\n \/\/Crops the image (removes sky)\n int topCrop = src.rows \/ 2 - 100;\n cv::Rect myROI(0, topCrop, src.cols, src.rows - topCrop);\n src = src(myROI);\n\n cvtColor(src, src_gray, CV_BGR2GRAY);\n\n \/\/Find the mean and stddev of the grayscale image in order to do adaptive thresholding\n Mat mean;\n Mat stddev;\n meanStdDev(src_gray, mean, stddev);\n\n double thresh = mean.at<double>(0,0) + (stddev.at<double>(0,0) * 2);\n if(thresh > 254) {\n thresh = 254;\n }\n\n threshold(src_gray, src_gray, thresh, 255, THRESH_BINARY);\n\n GaussianBlur(src_gray, src_gray, Size(gaussian_size, gaussian_size), 2, 2);\n\n vector<Vec3f> circles;\n\n \/\/ TODO tune circle radii for actual potholes\n HoughCircles(src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows \/ 8, 50, 10, minRadius, maxRadius);\n\n Mat cloudMat = Mat::zeros(orig.rows, orig.cols, CV_32F);\n \/\/\/ Put the circles into a matrix\n for( size_t i = 0; i < circles.size(); i++ ) {\n Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));\n int radius = cvRound(circles[i][2]);\n\n \/\/ If the circle is too close to the top \/ bottom edges, filter\n if (center.y <= 100 || center.y >= src_gray.rows - 100) {\n continue;\n }\n\n \/\/ If the circle is too close to the left \/ right edges, filter\n if (center.x <= 100 || center.x >= src_gray.cols - 100) {\n continue;\n }\n\n int cropSize = (125 \/ (double) src_gray.rows) * center.y;\n\n int xStart = center.x - (cropSize * 2);\n if (xStart < 0) {\n xStart = 0;\n }\n int yStart = center.y - cropSize;\n if (yStart < 0) {\n yStart = 0;\n }\n int xWidth = cropSize * 4;\n if (xWidth + xStart > src_gray.cols) {\n xWidth = src_gray.cols - xStart;\n }\n int yHeight = cropSize * 2;\n if (yHeight + yStart > src_gray.rows) {\n yHeight = src_gray.rows - yStart;\n }\n\n \/\/Get a matrix around circle center\n cv::Rect myROI(xStart, yStart, xWidth, yHeight);\n Mat roi = src_gray(myROI);\n\n \/\/ If the sum of all the pixels in the rectangle is less than sumThreshold\n \/\/ Then this circle is not encompassing mostly white pixels\n const int sumThreshold = whiteSampleRadius * whiteSampleRadius * (double) 3.141592 * 3;\n double sum = 0;\n for (int i = -whiteSampleRadius; i <= whiteSampleRadius; i++) {\n for (int j = -whiteSampleRadius; j <= whiteSampleRadius; j++) {\n if (i * i + j * j <= whiteSampleRadius * whiteSampleRadius) {\n Vec3b currentPixel = src.at<Vec3b>(j + center.y, i + center.x);\n sum += currentPixel[0] + currentPixel[1] + currentPixel[2];\n }\n }\n }\n Point sampleCenter(center.x, center.y);\n\n if (sum < sumThreshold * minWhiteThreshold || sum > sumThreshold * maxWhiteThreshold) {\n continue;\n }\n\n \/\/circle(cloudMat, center, radius, Scalar(255), 1, 8, 0);\n rectangle(src, myROI, Scalar(255), 2, 8, 0);\n circle(src, sampleCenter, whiteSampleRadius, Scalar(255), 1, 8, 0);\n circle(src, center, radius, Scalar(255), 2, 8, 0);\n\n Point offset(center.x - (cropSize * 2), center.y - cropSize);\n vector<vector<Point>> contours;\n findContours(roi, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE, Point((center.x - (cropSize * 2)), center.y - cropSize));\n\n \/\/ Filter false positives - small contours\n \/*\n for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); ++it) {\n vector<Point> curCont = *it;\n if (curCont.size() <= sizeThreshold) {\n contours.erase(it);\n --it;\n }\n } *\/\n\n \/\/ Filter false positives - small contours and cone stripes\n for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); ++it) {\n if ((*it).size() > sizeThreshold) {\n \/\/ Find center in x frame\n int minY = src_gray.rows;\n int minX = src_gray.cols;\n int maxY = 0;\n int maxX = 0;\n for (Point p : *it) {\n int x = p.x;\n if (x > maxX) {\n maxX = x;\n }\n if (x < minX) {\n minX = x;\n }\n }\n int centerX = (minX + maxX) \/ 2;\n int realMinY = src_gray.rows;\n int realMaxY;\n\n \/\/ Find centers of top and bottom edges\n for (Point p : *it) {\n int x = p.x;\n int y = p.y;\n if (x == centerX && y > maxY) {\n maxY = y;\n }\n if (x == centerX && y < minY) {\n minY = y;\n }\n\n if (y > realMaxY) {\n realMaxY = y;\n }\n if (y < realMinY) {\n realMinY = y;\n }\n }\n\n int realCenterY = (realMinY + realMaxY) \/ 2;\n\n \/\/ Check if contour is within bounds of image\n if (minY - 35 >= 0) {\n \/\/ Average rgb values above and below the contour\n int blueAbove = 0;\n int greenAbove = 0;\n int redAbove = 0;\n int blueBelow = 0;\n int greenBelow = 0;\n int redBelow = 0;\n Vec3b currentPixel;\n for (int j = 5; j < 36; j++) {\n currentPixel = src.at<Vec3b>(minY - j, centerX);\n blueAbove += currentPixel[0];\n greenAbove += currentPixel[1];\n redAbove += currentPixel[2];\n currentPixel[0] = 0;\n currentPixel[1] = 0;\n currentPixel[2] = 0;\n src.at<Vec3b>(minY - j, centerX) = currentPixel;\n currentPixel = src.at<Vec3b>(maxY + j, centerX);\n blueBelow += currentPixel[0];\n greenBelow += currentPixel[1];\n redBelow += currentPixel[2];\n currentPixel[0] = 0;\n currentPixel[1] = 0;\n currentPixel[2] = 0;\n src.at<Vec3b>(maxY + j, centerX) = currentPixel;\n }\n blueAbove \/= 30;\n greenAbove \/= 30;\n redAbove \/= 30;\n blueBelow \/= 30;\n greenBelow \/= 30;\n redBelow \/= 30;\n\n if (redAbove > greenAbove + 50 && redAbove > blueAbove + 50 && redBelow > greenBelow + 50 && redBelow > blueBelow + 50) {\n contours.erase(it);\n --it;\n } else {\n \/\/ Delete if the contour itself is orange\n Vec3b intensity = src.at<Vec3b>((minY + maxY) \/ 2, centerX);\n uchar blue = intensity.val[0];\n uchar green = intensity.val[1];\n uchar red = intensity.val[2];\n if ((getDiff(red, darkROrange) < 50 && getDiff(green, darkGOrange) < 50\n && getDiff(blue, darkBOrange) < 50)\n || (getDiff(red, lightROrange) < 50 && getDiff(green, lightGOrange) < 50\n && getDiff(blue, lightBOrange) < 50)) {\n contours.erase(it);\n --it;\n } else {\n cerr << to_string(maxX - minX) + \" \" + to_string(maxY - minY) << endl;\n int xDist = maxX - minX;\n int yDist = realMaxY - realMinY;\n if (xDist < yDist * 1.9 || xDist > yDist * 3.1) {\n contours.erase(it);\n --it;\n }\n }\n }\n\n \/\/ \/\/ Filter out contours with orange above and below\n \/\/ \/\/ If above is light or dark orange and below is light or dark\n \/\/ if (((getDiff(redAbove, darkROrange) < 50\n \/\/ && getDiff(greenAbove, darkGOrange) < 50\n \/\/ && getDiff(blueAbove, darkBOrange) < 50)\n \/\/ || (getDiff(redAbove, lightROrange) < 50\n \/\/ && getDiff(greenAbove, lightGOrange) < 50\n \/\/ && getDiff(blueAbove, lightBOrange) < 50))\n \/\/ && ((getDiff(redBelow, darkROrange) < 50\n \/\/ && getDiff(greenBelow, darkGOrange) < 50\n \/\/ && getDiff(blueBelow, darkBOrange) < 50)\n \/\/ || (getDiff(redBelow, lightROrange) < 50\n \/\/ && getDiff(greenBelow, lightGOrange) < 50\n \/\/ && getDiff(blueBelow, lightBOrange) < 50))) {\n \/\/ \/\/ Delete contour\n \/\/ contours.erase(it);\n \/\/ --it;\n \/\/ } else {\n \/\/ cerr << \"\" + to_string(blueAbove) + \", \" + to_string(greenAbove) + \", \" + to_string(redAbove) + \" \" + to_string(blueBelow) + \", \" + to_string(greenBelow) + \", \" + to_string(redBelow) << endl;\n \/\/ }\n } else {\n contours.erase(it);\n --it;\n }\n } else {\n contours.erase(it);\n --it;\n }\n }\n\n drawContours(src, contours, -1, Scalar(20, 236, 27), 3, 8);\n }\n\n cvtColor(src_gray, src_gray, CV_GRAY2BGR);\n\n cv_bridge::CvImage out_msg;\n out_msg.header = msg->header;\n out_msg.encoding = msg->encoding;\n out_msg.image = src;\n\n cv_ptr->image = src;\n _pothole_filt_img.publish(cv_ptr->toImageMsg());\n _pothole_thres.publish(out_msg.toImageMsg());\n cloud = toPointCloud(cloudMat);\n _pothole_cloud.publish(cloud);\n}\n\nPotholeDetector::PotholeDetector(ros::NodeHandle &handle)\n : gaussian_size(7),\n _it(handle),\n tf_listener(handle) {\n _src_img = _it.subscribe(\"\/stereo\/right\/image_raw\", 1, &PotholeDetector::img_callback, this);\n _pothole_filt_img = _it.advertise(\"\/pothole_filt_img\", 1);\n _pothole_thres = _it.advertise(\"\/pothole_thres\", 1);\n _pothole_cloud = handle.advertise<PCLCloud>(\"\/pothole_cloud\", 100);\n}\n\n\/\/ FIXME does not take into account distance from groud to camera\nPointCloud<PointXYZ>::Ptr PotholeDetector::toPointCloud(Mat src) {\n PointCloud<PointXYZ>::Ptr cloud(new PointCloud<PointXYZ>);\n for(int r = 0; r < src.rows; r++) {\n float *row = src.ptr<float>(r);\n for(int c = 0; c < src.cols; c++) {\n if(row[c] > 0) {\n cloud->points.push_back(PointXYZ(r, c, 0));\n }\n }\n }\n\tcloud->header.frame_id = \"base_footprint\";\n\treturn cloud;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef HMLIB_LATTICES_POINTACCESSITERATOR_INC\n#define HMLIB_LATTICES_POINTACCESSITERATOR_INC 100\n#\n#include<iterator>\nnamespace hmLib {\n\ttemplate<typename lattice_type_, typename point_iterator_, typename point_iterator_category_ = typename std::iterator_traits<point_iterator_>::iterator_category>\n\tstruct point_access_iterator {};\n\ttemplate<typename lattice_type_, typename point_iterator_>\n\tstruct point_access_iterator<lattice_type_, point_iterator_, std::input_iterator_tag> {\n\tprivate:\n\t\tusing this_type = point_access_iterator<lattice_type_, point_iterator_, std::input_iterator_tag>;\n\t\tusing lattice_type = lattice_type_;\n\t\tusing lattice_reference = lattice_type&;\n\t\tusing point_iterator = point_iterator_;\n\tpublic:\n\t\tusing value_type = typename std::iterator_traits<base_iterator>::value_type;\n\t\tusing difference_type = typename std::iterator_traits<base_iterator>::difference_type;\n\t\tusing reference = typename std::iterator_traits<base_iterator>::reference;\n\t\tusing pointer = typename std::iterator_traits<base_iterator>::pointer;\n\t\tusing iterator_category = std::input_iterator_tag;\n\tprivate:\n\t\tlattice_type Lattice;\n\t\tpoint_iterator IItr;\n\tpublic:\/\/constructer\n\t\tpoint_access_iterator() = default;\n\t\tpoint_access_iterator(base_iterator Beg_, index_iterator_ IItr_):Beg(Beg_), IItr(IItr_) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tpoint_access_iterator(const point_access_iterator<other_iterator_, index_iterator_>& Other) : Beg(Other.Beg), IItr(Other.IItr) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tthis_type& operator=(const point_access_iterator<other_iterator_, index_iterator_>& Other) {\n\t\t\tBeg = Other.Beg;\n\t\t\tIItr = Other.IItr;\n\t\t\treturn *this;\n\t\t}\n\tpublic:\n\t\treference operator*()const { return Beg[*IItr]; }\n\t\tpointer operator->()const { return &Beg[*IItr]; }\n\t\tthis_type& operator++() {\n\t\t\t++IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator++(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator++();\n\t\t\treturn Ans;\n\t\t}\n\t\tbase_iterator base()const { return Beg+(*IItr); }\n\t\tauto index()const { return *IItr; }\n\t\tfriend bool operator==(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr == v2.IItr;\n\t\t}\n\t\tfriend bool operator!=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr != v2.IItr;\n\t\t}\n\t};\n\ttemplate<typename random_access_iterator_, typename index_iterator_>\n\tstruct index_access_iterator<random_access_iterator_, index_iterator_, std::forward_iterator_tag> {\n\tprivate:\n\t\tstatic_assert(std::is_same<typename std::iterator_traits<random_access_iterator_>::iterator_category, std::random_access_iterator_tag>::value, \"index_iterator can use only for random_access_iterator\");\n\t\tusing this_type = index_access_iterator<random_access_iterator_, index_iterator_, std::forward_iterator_tag>;\n\t\tusing base_iterator = random_access_iterator_;\n\t\tusing index_iterator = index_iterator_;\n\tpublic:\n\t\tusing value_type = typename std::iterator_traits<base_iterator>::value_type;\n\t\tusing difference_type = typename std::iterator_traits<base_iterator>::difference_type;\n\t\tusing reference = typename std::iterator_traits<base_iterator>::reference;\n\t\tusing pointer = typename std::iterator_traits<base_iterator>::pointer;\n\t\tusing iterator_category = std::forward_iterator_tag;\n\tprivate:\n\t\tbase_iterator Beg;\n\t\tindex_iterator IItr;\n\tpublic:\/\/constructer\n\t\tindex_access_iterator() = default;\n\t\tindex_access_iterator(base_iterator Beg_, index_iterator_ IItr_):Beg(Beg_), IItr(IItr_) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tindex_access_iterator(const index_access_iterator<other_iterator_, index_iterator_>& Other) : Beg(Other.Beg), IItr(Other.IItr) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tthis_type& operator=(const index_access_iterator<other_iterator_, index_iterator_>& Other) {\n\t\t\tBeg = Other.Beg;\n\t\t\tIItr = Other.IItr;\n\t\t\treturn *this;\n\t\t}\n\tpublic:\n\t\treference operator*()const { return Beg[*IItr]; }\n\t\tpointer operator->()const { return &Beg[*IItr]; }\n\t\tthis_type& operator++() {\n\t\t\t++IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator++(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator++();\n\t\t\treturn Ans;\n\t\t}\n\t\tbase_iterator base() { return Beg+(*IItr); }\n\t\tauto index()const { return *IItr; }\n\t\tfriend bool operator==(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr == v2.IItr;\n\t\t}\n\t\tfriend bool operator!=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr != v2.IItr;\n\t\t}\n\t};\n\ttemplate<typename random_access_iterator_, typename index_iterator_>\n\tstruct index_access_iterator<random_access_iterator_, index_iterator_, std::bidirectional_iterator_tag> {\n\tprivate:\n\t\tstatic_assert(std::is_same<typename std::iterator_traits<random_access_iterator_>::iterator_category, std::random_access_iterator_tag>::value, \"index_iterator can use only for random_access_iterator\");\n\t\tusing this_type = index_access_iterator<random_access_iterator_, index_iterator_, std::bidirectional_iterator_tag>;\n\t\tusing base_iterator = random_access_iterator_;\n\t\tusing index_iterator = index_iterator_;\n\tpublic:\n\t\tusing value_type = typename std::iterator_traits<base_iterator>::value_type;\n\t\tusing difference_type = typename std::iterator_traits<base_iterator>::difference_type;\n\t\tusing reference = typename std::iterator_traits<base_iterator>::reference;\n\t\tusing pointer = typename std::iterator_traits<base_iterator>::pointer;\n\t\tusing iterator_category = std::bidirectional_iterator_tag;\n\tprivate:\n\t\tbase_iterator Beg;\n\t\tindex_iterator IItr;\n\tpublic:\/\/constructer\n\t\tindex_access_iterator() = default;\n\t\tindex_access_iterator(base_iterator Beg_, index_iterator_ IItr_):Beg(Beg_), IItr(IItr_) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tindex_access_iterator(const index_access_iterator<other_iterator_, index_iterator_>& Other) : Beg(Other.Beg), IItr(Other.IItr) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tthis_type& operator=(const index_access_iterator<other_iterator_, index_iterator_>& Other) {\n\t\t\tBeg = Other.Beg;\n\t\t\tIItr = Other.IItr;\n\t\t\treturn *this;\n\t\t}\n\tpublic:\n\t\treference operator*()const { return Beg[*IItr]; }\n\t\tpointer operator->()const { return &Beg[*IItr]; }\n\t\tthis_type& operator++() {\n\t\t\t++IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator++(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator++();\n\t\t\treturn Ans;\n\t\t}\n\t\tthis_type& operator--() {\n\t\t\t--IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator--(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator--();\n\t\t\treturn Ans;\n\t\t}\n\t\tbase_iterator base()const { return Beg+(*IItr); }\n\t\tauto index()const { return *IItr; }\n\t\tfriend bool operator==(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr == v2.IItr;\n\t\t}\n\t\tfriend bool operator!=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr != v2.IItr;\n\t\t}\n\t};\n\ttemplate<typename random_access_iterator_, typename index_iterator_>\n\tstruct index_access_iterator<random_access_iterator_, index_iterator_, std::random_access_iterator_tag> {\n\tprivate:\n\t\tstatic_assert(std::is_same<typename std::iterator_traits<random_access_iterator_>::iterator_category, std::random_access_iterator_tag>::value, \"index_iterator can use only for random_access_iterator\");\n\t\tusing this_type = index_access_iterator<random_access_iterator_, index_iterator_, std::random_access_iterator_tag>;\n\t\tusing base_iterator = random_access_iterator_;\n\t\tusing index_iterator = index_iterator_;\n\tpublic:\n\t\tusing value_type = typename std::iterator_traits<base_iterator>::value_type;\n\t\tusing difference_type = typename std::iterator_traits<base_iterator>::difference_type;\n\t\tusing reference = typename std::iterator_traits<base_iterator>::reference;\n\t\tusing pointer = typename std::iterator_traits<base_iterator>::pointer;\n\t\tusing iterator_category = std::random_access_iterator_tag;\n\tprivate:\n\t\tbase_iterator Beg;\n\t\tindex_iterator IItr;\n\tpublic:\/\/constructer\n\t\tindex_access_iterator() = default;\n\t\tindex_access_iterator(base_iterator Beg_, index_iterator_ IItr_):Beg(Beg_), IItr(IItr_) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tindex_access_iterator(const index_access_iterator<other_iterator_, index_iterator_>& Other) : Beg(Other.Beg), IItr(Other.IItr) {}\n\t\ttemplate<typename other_iterator_, typename std::enable_if<std::is_convertible<base_iterator, other_iterator_>::value&&!std::is_same<base_iterator, other_iterator_>::value>::type *& = hmLib::utility::enabler>\n\t\tthis_type& operator=(const index_access_iterator<other_iterator_, index_iterator_>& Other) {\n\t\t\tBeg = Other.Beg;\n\t\t\tIItr = Other.IItr;\n\t\t\treturn *this;\n\t\t}\n\tpublic:\n\t\treference operator*()const { return Beg[*IItr]; }\n\t\tpointer operator->()const { return &Beg[*IItr]; }\n\t\treference operator[](difference_type d) { return Beg[IItr[d]]; }\n\t\tthis_type& operator++() {\n\t\t\t++IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator++(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator++();\n\t\t\treturn Ans;\n\t\t}\n\t\tthis_type& operator--() {\n\t\t\t--IItr;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type operator--(int) {\n\t\t\tthis_type Ans = *this;\n\t\t\toperator--();\n\t\t\treturn Ans;\n\t\t}\n\t\tthis_type& operator+=(difference_type d) {\n\t\t\tIItr = +d;\n\t\t\treturn *this;\n\t\t}\n\t\tthis_type& operator-=(difference_type d) {\n\t\t\tIItr = -d;\n\t\t\treturn *this;\n\t\t}\n\t\tfriend this_type operator+(const this_type& itr, difference_type d) {\n\t\t\tthis_type ans = itr;\n\t\t\tans += d;\n\t\t\treturn ans;\n\t\t}\n\t\tfriend this_type operator+(difference_type d, const this_type& itr) {\n\t\t\treturn operator+(itr, d);\n\t\t}\n\t\tfriend this_type operator-(const this_type& itr, difference_type d) {\n\t\t\tthis_type ans = itr;\n\t\t\tans -= d;\n\t\t\treturn ans;\n\t\t}\n\t\tfriend difference_type operator-(const this_type& itr1, const this_type& itr2) {\n\t\t\treturn itr1.IItr - itr2.IItr;\n\t\t}\n\t\tbase_iterator base()const { return Beg+(*IItr); }\n\t\tauto index()const { return *IItr; }\n\t\tfriend bool operator==(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr == v2.IItr;\n\t\t}\n\t\tfriend bool operator!=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr != v2.IItr;\n\t\t}\n\t\tfriend bool operator>(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr > v2.IItr;\n\t\t}\n\t\tfriend bool operator<(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr < v2.IItr;\n\t\t}\n\t\tfriend bool operator>=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr >= v2.IItr;\n\t\t}\n\t\tfriend bool operator<=(const this_type& v1, const this_type& v2) {\n\t\t\treturn v1.IItr <= v2.IItr;\n\t\t}\n\t};\n\n\ttemplate<typename lattice_type_, typename point_iterator_>\n\tstruct point_access_iterator {\n\t};\n}\n#\n#endif\n<commit_msg>Remove old point_access iterator.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkTestFriendTemplatedFunction.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/*\n This file tests the syntax that the compiler supports for declaring \n templated functions as friends of a templated class.\n*\/\n\n\/\/\n\/\/ Here is our templated function\n\/\/\ntemplate <class T>\nT compose( const T & a, const T & b )\n{ return a + b; }\n\n\n\/\/\n\/\/ Here is our templated class\n\/\/\ntemplate <class T>\nclass WantToHaveFriend\n{\npublic:\n\n typedef WantToHaveFriend Self;\n\n Self operator+(const Self & other) const\n {\n Self result;\n result.x = this->x + other.x;\n return result;\n }\n\n WantToHaveFriend()\n {\n x = 0;\n }\n \n void DoNothing() const\n {\n \/\/ of course... do nothing.\n }\n\n\/\/\n\/\/ Here are the variants that some compilers use\n\/\/\n\n#ifdef TRY_COMPILE_FRIEND_WITH_NULL_TEMPLATE_STRING\n friend Self compose(const Self &, const Self &);\n#endif\n\n#ifdef TRY_COMPILE_FRIEND_WITH_EMPTY_TEMPLATE_BRACKETS\n friend Self compose<>(const Self &, const Self &);\n#endif\n\n#ifdef TRY_COMPILE_FRIEND_WITH_TEMPLATE_ARGUMENTS\n friend Self compose<Self>(const Self &, const Self &);\n#endif\n\nprivate:\n int x;\n};\n\nint main() \n{ \n typedef WantToHaveFriend<int> FriendlyType;\n\n FriendlyType foo1;\n FriendlyType foo2;\n FriendlyType foo3;\n\n foo1 = compose( foo2, foo3 );\n\n foo1.DoNothing();\n\n return 0;\n}\n\n<commit_msg>ENH: Creating a code example similar to what is found in itk_hashmap and itk_hashtable.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkTestFriendTemplatedFunction.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/*\n This file tests the syntax that the compiler supports for declaring \n templated functions as friends of a templated class.\n*\/\n\n\/\/\n\/\/ Here is our templated function, forward declared\n\/\/\ntemplate <class T> class WantToHaveFriend;\n\ntemplate <class T>\nbool operator==( const WantToHaveFriend<T> & a, const WantToHaveFriend<T> & b );\n\n\n\/\/\n\/\/ Here is our templated class\n\/\/\ntemplate <class T>\nclass WantToHaveFriend\n{\npublic:\n\n typedef WantToHaveFriend Self;\n\n WantToHaveFriend()\n {\n x = 0;\n }\n \n void DoNothing() const\n {\n \/\/ of course... do nothing.\n }\n\n\/\/\n\/\/ Here are the variants that some compilers use\n\/\/\n\n#ifdef TRY_COMPILE_FRIEND_WITH_NULL_TEMPLATE_STRING\n friend bool operator==(const Self &, const Self &);\n#endif\n\n#ifdef TRY_COMPILE_FRIEND_WITH_EMPTY_TEMPLATE_BRACKETS\n friend bool operator==<>(const Self &, const Self &);\n#endif\n\n#ifdef TRY_COMPILE_FRIEND_WITH_TEMPLATE_ARGUMENTS\n friend bool operator==<Self>(const Self &, const Self &);\n#endif\n\nprivate:\n int x;\n};\n\ntemplate <class T>\nbool operator==( const WantToHaveFriend<T> & a, const WantToHaveFriend<T> & b )\n{ return a.x == b.x; }\n\n\nint main() \n{ \n typedef WantToHaveFriend<int> FriendlyType;\n\n FriendlyType foo1;\n FriendlyType foo2;\n\n bool result = ( foo1 == foo2 );\n\n if( result )\n {\n return 1;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete_history_manager.h\"\n\n#include <vector>\n\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autofill\/credit_card.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\n\nnamespace {\n\n\/\/ Limit on the number of suggestions to appear in the pop-up menu under an\n\/\/ text input element in a form.\nconst int kMaxAutocompleteMenuItems = 6;\n\n\/\/ The separator characters for SSNs.\nconst string16 kSSNSeparators = ASCIIToUTF16(\" -\");\n\nbool IsSSN(const string16& text) {\n string16 number_string;\n RemoveChars(text, kSSNSeparators.c_str(), &number_string);\n\n \/\/ A SSN is of the form AAA-GG-SSSS (A = area number, G = group number, S =\n \/\/ serial number). The validation we do here is simply checking if the area,\n \/\/ group, and serial numbers are valid. It is possible to check if the group\n \/\/ number is valid for the given area, but that data changes all the time.\n \/\/\n \/\/ See: http:\/\/www.socialsecurity.gov\/history\/ssn\/geocard.html\n \/\/ http:\/\/www.socialsecurity.gov\/employer\/stateweb.htm\n \/\/ http:\/\/www.socialsecurity.gov\/employer\/ssnvhighgroup.htm\n if (number_string.length() != 9 || !IsStringASCII(number_string))\n return false;\n\n int area;\n if (!base::StringToInt(number_string.begin(),\n number_string.begin() + 3,\n &area))\n return false;\n if (area < 1 ||\n area == 666 ||\n (area > 733 && area < 750) ||\n area > 772)\n return false;\n\n int group;\n if (!base::StringToInt(number_string.begin() + 3,\n number_string.begin() + 5,\n &group) || group == 0)\n return false;\n\n int serial;\n if (!base::StringToInt(number_string.begin() + 5,\n number_string.begin() + 9,\n &serial) || serial == 0)\n return false;\n\n return true;\n}\n\n} \/\/ namespace\n\nAutocompleteHistoryManager::AutocompleteHistoryManager(\n TabContents* tab_contents)\n : tab_contents_(tab_contents),\n pending_query_handle_(0),\n query_id_(0) {\n profile_ = tab_contents_->profile();\n \/\/ May be NULL in unit tests.\n web_data_service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);\n autofill_enabled_.Init(prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL);\n}\n\nAutocompleteHistoryManager::~AutocompleteHistoryManager() {\n CancelPendingQuery();\n}\n\nbool AutocompleteHistoryManager::OnMessageReceived(\n const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(AutocompleteHistoryManager, message)\n IPC_MESSAGE_HANDLER(ViewHostMsg_RemoveAutocompleteEntry,\n OnRemoveAutocompleteEntry)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n}\n\nvoid AutocompleteHistoryManager::OnFormSubmitted(const FormData& form) {\n if (!*autofill_enabled_)\n return;\n\n if (profile_->IsOffTheRecord())\n return;\n\n \/\/ Don't save data that was submitted through JavaScript.\n if (!form.user_submitted)\n return;\n\n \/\/ We put the following restriction on stored FormFields:\n \/\/ - non-empty name\n \/\/ - non-empty value\n \/\/ - text field\n \/\/ - value is not a credit card number\n \/\/ - value is not a SSN\n std::vector<webkit_glue::FormField> values;\n for (std::vector<webkit_glue::FormField>::const_iterator iter =\n form.fields.begin();\n iter != form.fields.end(); ++iter) {\n if (!iter->value().empty() &&\n !iter->name().empty() &&\n iter->form_control_type() == ASCIIToUTF16(\"text\") &&\n !CreditCard::IsCreditCardNumber(iter->value()) &&\n !IsSSN(iter->value()))\n values.push_back(*iter);\n }\n\n if (!values.empty() && web_data_service_.get())\n web_data_service_->AddFormFields(values);\n}\n\nvoid AutocompleteHistoryManager::OnRemoveAutocompleteEntry(\n const string16& name, const string16& value) {\n if (web_data_service_.get())\n web_data_service_->RemoveFormValueForElementName(name, value);\n}\n\nvoid AutocompleteHistoryManager::OnGetAutocompleteSuggestions(\n int query_id,\n const string16& name,\n const string16& prefix,\n const std::vector<string16>& autofill_values,\n const std::vector<string16>& autofill_labels,\n const std::vector<string16>& autofill_icons,\n const std::vector<int>& autofill_unique_ids) {\n CancelPendingQuery();\n\n query_id_ = query_id;\n autofill_values_ = autofill_values;\n autofill_labels_ = autofill_labels;\n autofill_icons_ = autofill_icons;\n autofill_unique_ids_ = autofill_unique_ids;\n if (!*autofill_enabled_) {\n SendSuggestions(NULL);\n return;\n }\n\n if (web_data_service_.get()) {\n pending_query_handle_ = web_data_service_->GetFormValuesForElementName(\n name, prefix, kMaxAutocompleteMenuItems, this);\n }\n}\n\nvoid AutocompleteHistoryManager::OnWebDataServiceRequestDone(\n WebDataService::Handle h,\n const WDTypedResult* result) {\n DCHECK(pending_query_handle_);\n pending_query_handle_ = 0;\n\n if (!*autofill_enabled_) {\n SendSuggestions(NULL);\n return;\n }\n\n DCHECK(result);\n DCHECK(result->GetType() == AUTOFILL_VALUE_RESULT);\n const WDResult<std::vector<string16> >* autofill_result =\n static_cast<const WDResult<std::vector<string16> >*>(result);\n std::vector<string16> suggestions = autofill_result->GetValue();\n SendSuggestions(&suggestions);\n}\n\nAutocompleteHistoryManager::AutocompleteHistoryManager(\n Profile* profile, WebDataService* wds) : tab_contents_(NULL),\n profile_(profile),\n web_data_service_(wds),\n pending_query_handle_(0),\n query_id_(0) {\n autofill_enabled_.Init(\n prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL);\n}\n\nvoid AutocompleteHistoryManager::CancelPendingQuery() {\n if (pending_query_handle_) {\n SendSuggestions(NULL);\n if (web_data_service_.get())\n web_data_service_->CancelRequest(pending_query_handle_);\n pending_query_handle_ = 0;\n }\n}\n\nvoid AutocompleteHistoryManager::SendSuggestions(\n const std::vector<string16>* suggestions) {\n if (suggestions) {\n \/\/ Combine AutoFill and Autocomplete values into values and labels.\n for (size_t i = 0; i < suggestions->size(); ++i) {\n bool unique = true;\n for (size_t j = 0; j < autofill_values_.size(); ++j) {\n \/\/ Don't add duplicate values.\n if (autofill_values_[j] == (*suggestions)[i]) {\n unique = false;\n break;\n }\n }\n\n if (unique) {\n autofill_values_.push_back((*suggestions)[i]);\n autofill_labels_.push_back(string16());\n autofill_icons_.push_back(string16());\n autofill_unique_ids_.push_back(0); \/\/ 0 means no profile.\n }\n }\n }\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (host) {\n host->Send(new ViewMsg_AutoFillSuggestionsReturned(host->routing_id(),\n query_id_,\n autofill_values_,\n autofill_labels_,\n autofill_icons_,\n autofill_unique_ids_));\n }\n\n query_id_ = 0;\n autofill_values_.clear();\n autofill_labels_.clear();\n autofill_icons_.clear();\n autofill_unique_ids_.clear();\n}\n<commit_msg>DCHECK(result) keeps firing in AutocompleteHistoryManager::OnWebDataServiceRequestDone()<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete_history_manager.h\"\n\n#include <vector>\n\n#include \"base\/string16.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autofill\/credit_card.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"webkit\/glue\/form_data.h\"\n\nusing webkit_glue::FormData;\n\nnamespace {\n\n\/\/ Limit on the number of suggestions to appear in the pop-up menu under an\n\/\/ text input element in a form.\nconst int kMaxAutocompleteMenuItems = 6;\n\n\/\/ The separator characters for SSNs.\nconst string16 kSSNSeparators = ASCIIToUTF16(\" -\");\n\nbool IsSSN(const string16& text) {\n string16 number_string;\n RemoveChars(text, kSSNSeparators.c_str(), &number_string);\n\n \/\/ A SSN is of the form AAA-GG-SSSS (A = area number, G = group number, S =\n \/\/ serial number). The validation we do here is simply checking if the area,\n \/\/ group, and serial numbers are valid. It is possible to check if the group\n \/\/ number is valid for the given area, but that data changes all the time.\n \/\/\n \/\/ See: http:\/\/www.socialsecurity.gov\/history\/ssn\/geocard.html\n \/\/ http:\/\/www.socialsecurity.gov\/employer\/stateweb.htm\n \/\/ http:\/\/www.socialsecurity.gov\/employer\/ssnvhighgroup.htm\n if (number_string.length() != 9 || !IsStringASCII(number_string))\n return false;\n\n int area;\n if (!base::StringToInt(number_string.begin(),\n number_string.begin() + 3,\n &area))\n return false;\n if (area < 1 ||\n area == 666 ||\n (area > 733 && area < 750) ||\n area > 772)\n return false;\n\n int group;\n if (!base::StringToInt(number_string.begin() + 3,\n number_string.begin() + 5,\n &group) || group == 0)\n return false;\n\n int serial;\n if (!base::StringToInt(number_string.begin() + 5,\n number_string.begin() + 9,\n &serial) || serial == 0)\n return false;\n\n return true;\n}\n\n} \/\/ namespace\n\nAutocompleteHistoryManager::AutocompleteHistoryManager(\n TabContents* tab_contents)\n : tab_contents_(tab_contents),\n pending_query_handle_(0),\n query_id_(0) {\n profile_ = tab_contents_->profile();\n \/\/ May be NULL in unit tests.\n web_data_service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);\n autofill_enabled_.Init(prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL);\n}\n\nAutocompleteHistoryManager::~AutocompleteHistoryManager() {\n CancelPendingQuery();\n}\n\nbool AutocompleteHistoryManager::OnMessageReceived(\n const IPC::Message& message) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(AutocompleteHistoryManager, message)\n IPC_MESSAGE_HANDLER(ViewHostMsg_RemoveAutocompleteEntry,\n OnRemoveAutocompleteEntry)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n}\n\nvoid AutocompleteHistoryManager::OnFormSubmitted(const FormData& form) {\n if (!*autofill_enabled_)\n return;\n\n if (profile_->IsOffTheRecord())\n return;\n\n \/\/ Don't save data that was submitted through JavaScript.\n if (!form.user_submitted)\n return;\n\n \/\/ We put the following restriction on stored FormFields:\n \/\/ - non-empty name\n \/\/ - non-empty value\n \/\/ - text field\n \/\/ - value is not a credit card number\n \/\/ - value is not a SSN\n std::vector<webkit_glue::FormField> values;\n for (std::vector<webkit_glue::FormField>::const_iterator iter =\n form.fields.begin();\n iter != form.fields.end(); ++iter) {\n if (!iter->value().empty() &&\n !iter->name().empty() &&\n iter->form_control_type() == ASCIIToUTF16(\"text\") &&\n !CreditCard::IsCreditCardNumber(iter->value()) &&\n !IsSSN(iter->value()))\n values.push_back(*iter);\n }\n\n if (!values.empty() && web_data_service_.get())\n web_data_service_->AddFormFields(values);\n}\n\nvoid AutocompleteHistoryManager::OnRemoveAutocompleteEntry(\n const string16& name, const string16& value) {\n if (web_data_service_.get())\n web_data_service_->RemoveFormValueForElementName(name, value);\n}\n\nvoid AutocompleteHistoryManager::OnGetAutocompleteSuggestions(\n int query_id,\n const string16& name,\n const string16& prefix,\n const std::vector<string16>& autofill_values,\n const std::vector<string16>& autofill_labels,\n const std::vector<string16>& autofill_icons,\n const std::vector<int>& autofill_unique_ids) {\n CancelPendingQuery();\n\n query_id_ = query_id;\n autofill_values_ = autofill_values;\n autofill_labels_ = autofill_labels;\n autofill_icons_ = autofill_icons;\n autofill_unique_ids_ = autofill_unique_ids;\n if (!*autofill_enabled_) {\n SendSuggestions(NULL);\n return;\n }\n\n if (web_data_service_.get()) {\n pending_query_handle_ = web_data_service_->GetFormValuesForElementName(\n name, prefix, kMaxAutocompleteMenuItems, this);\n }\n}\n\nvoid AutocompleteHistoryManager::OnWebDataServiceRequestDone(\n WebDataService::Handle h,\n const WDTypedResult* result) {\n DCHECK(pending_query_handle_);\n pending_query_handle_ = 0;\n\n if (!*autofill_enabled_) {\n SendSuggestions(NULL);\n return;\n }\n\n DCHECK(result);\n \/\/ Returning early here if |result| is NULL. We've seen this happen on\n \/\/ Linux due to NFS dismounting and causing sql failures.\n \/\/ See http:\/\/crbug.com\/68783.\n if (!result) {\n SendSuggestions(NULL);\n return;\n }\n\n DCHECK(result->GetType() == AUTOFILL_VALUE_RESULT);\n const WDResult<std::vector<string16> >* autofill_result =\n static_cast<const WDResult<std::vector<string16> >*>(result);\n std::vector<string16> suggestions = autofill_result->GetValue();\n SendSuggestions(&suggestions);\n}\n\nAutocompleteHistoryManager::AutocompleteHistoryManager(\n Profile* profile, WebDataService* wds) : tab_contents_(NULL),\n profile_(profile),\n web_data_service_(wds),\n pending_query_handle_(0),\n query_id_(0) {\n autofill_enabled_.Init(\n prefs::kAutoFillEnabled, profile_->GetPrefs(), NULL);\n}\n\nvoid AutocompleteHistoryManager::CancelPendingQuery() {\n if (pending_query_handle_) {\n SendSuggestions(NULL);\n if (web_data_service_.get())\n web_data_service_->CancelRequest(pending_query_handle_);\n pending_query_handle_ = 0;\n }\n}\n\nvoid AutocompleteHistoryManager::SendSuggestions(\n const std::vector<string16>* suggestions) {\n if (suggestions) {\n \/\/ Combine AutoFill and Autocomplete values into values and labels.\n for (size_t i = 0; i < suggestions->size(); ++i) {\n bool unique = true;\n for (size_t j = 0; j < autofill_values_.size(); ++j) {\n \/\/ Don't add duplicate values.\n if (autofill_values_[j] == (*suggestions)[i]) {\n unique = false;\n break;\n }\n }\n\n if (unique) {\n autofill_values_.push_back((*suggestions)[i]);\n autofill_labels_.push_back(string16());\n autofill_icons_.push_back(string16());\n autofill_unique_ids_.push_back(0); \/\/ 0 means no profile.\n }\n }\n }\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (host) {\n host->Send(new ViewMsg_AutoFillSuggestionsReturned(host->routing_id(),\n query_id_,\n autofill_values_,\n autofill_labels_,\n autofill_icons_,\n autofill_unique_ids_));\n }\n\n query_id_ = 0;\n autofill_values_.clear();\n autofill_labels_.clear();\n autofill_icons_.clear();\n autofill_unique_ids_.clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/tab_contents_drag_source.h\"\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/mime_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"webkit\/glue\/webdropdata.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nTabContentsDragSource::TabContentsDragSource(\n TabContentsView* tab_contents_view)\n : tab_contents_view_(tab_contents_view),\n drag_failed_(false),\n drag_widget_(NULL) {\n drag_widget_ = gtk_invisible_new();\n g_signal_connect(drag_widget_, \"drag-failed\",\n G_CALLBACK(OnDragFailedThunk), this);\n g_signal_connect(drag_widget_, \"drag-end\", G_CALLBACK(OnDragEndThunk), this);\n g_signal_connect(drag_widget_, \"drag-data-get\",\n G_CALLBACK(OnDragDataGetThunk), this);\n g_object_ref_sink(drag_widget_);\n}\n\nTabContentsDragSource::~TabContentsDragSource() {\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragFailedThunk), this);\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragEndThunk), this);\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragDataGetThunk), this);\n\n \/\/ Break the current drag, if any.\n if (drop_data_.get()) {\n gtk_grab_add(drag_widget_);\n gtk_grab_remove(drag_widget_);\n MessageLoopForUI::current()->RemoveObserver(this);\n drop_data_.reset();\n }\n\n gtk_widget_destroy(drag_widget_);\n g_object_unref(drag_widget_);\n drag_widget_ = NULL;\n}\n\nTabContents* TabContentsDragSource::tab_contents() const {\n return tab_contents_view_->tab_contents();\n}\n\nvoid TabContentsDragSource::StartDragging(const WebDropData& drop_data,\n GdkEventButton* last_mouse_down) {\n int targets_mask = 0;\n\n if (!drop_data.plain_text.empty())\n targets_mask |= GtkDndUtil::TEXT_PLAIN;\n if (drop_data.url.is_valid()) {\n targets_mask |= GtkDndUtil::TEXT_URI_LIST;\n targets_mask |= GtkDndUtil::CHROME_NAMED_URL;\n targets_mask |= GtkDndUtil::NETSCAPE_URL;\n }\n if (!drop_data.text_html.empty())\n targets_mask |= GtkDndUtil::TEXT_HTML;\n if (!drop_data.file_contents.empty())\n targets_mask |= GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS;\n\n if (targets_mask == 0) {\n NOTIMPLEMENTED();\n if (tab_contents()->render_view_host())\n tab_contents()->render_view_host()->DragSourceSystemDragEnded();\n }\n\n drop_data_.reset(new WebDropData(drop_data));\n\n GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(targets_mask);\n if (targets_mask & GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS) {\n drag_file_mime_type_ = gdk_atom_intern(\n mime_util::GetDataMimeType(drop_data.file_contents).c_str(), FALSE);\n gtk_target_list_add(list, drag_file_mime_type_,\n 0, GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS);\n }\n\n drag_failed_ = false;\n \/\/ If we don't pass an event, GDK won't know what event time to start grabbing\n \/\/ mouse events. Technically it's the mouse motion event and not the mouse\n \/\/ down event that causes the drag, but there's no reliable way to know\n \/\/ *which* motion event initiated the drag, so this will have to do.\n \/\/ TODO(estade): This can sometimes be very far off, e.g. if the user clicks\n \/\/ and holds and doesn't start dragging for a long time. I doubt it matters\n \/\/ much, but we should probably look into the possibility of getting the\n \/\/ initiating event from webkit.\n gtk_drag_begin(drag_widget_, list,\n static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK),\n 1, \/\/ Drags are always initiated by the left button.\n reinterpret_cast<GdkEvent*>(last_mouse_down));\n MessageLoopForUI::current()->AddObserver(this);\n \/\/ The drag adds a ref; let it own the list.\n gtk_target_list_unref(list);\n}\n\nvoid TabContentsDragSource::WillProcessEvent(GdkEvent* event) {\n \/\/ No-op.\n}\n\nvoid TabContentsDragSource::DidProcessEvent(GdkEvent* event) {\n if (event->type != GDK_MOTION_NOTIFY)\n return;\n\n GdkEventMotion* event_motion = reinterpret_cast<GdkEventMotion*>(event);\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceMovedTo(\n client.x(), client.y(),\n static_cast<int>(event_motion->x_root),\n static_cast<int>(event_motion->y_root));\n }\n}\n\nvoid TabContentsDragSource::OnDragDataGet(\n GdkDragContext* context, GtkSelectionData* selection_data,\n guint target_type, guint time) {\n const int kBitsPerByte = 8;\n\n switch (target_type) {\n case GtkDndUtil::TEXT_PLAIN: {\n std::string utf8_text = UTF16ToUTF8(drop_data_->plain_text);\n gtk_selection_data_set_text(selection_data, utf8_text.c_str(),\n utf8_text.length());\n break;\n }\n\n case GtkDndUtil::TEXT_HTML: {\n \/\/ TODO(estade): change relative links to be absolute using\n \/\/ |html_base_url|.\n std::string utf8_text = UTF16ToUTF8(drop_data_->text_html);\n gtk_selection_data_set(selection_data,\n GtkDndUtil::GetAtomForTarget(\n GtkDndUtil::TEXT_HTML),\n kBitsPerByte,\n reinterpret_cast<const guchar*>(utf8_text.c_str()),\n utf8_text.length());\n break;\n }\n\n case GtkDndUtil::TEXT_URI_LIST:\n case GtkDndUtil::CHROME_NAMED_URL:\n case GtkDndUtil::NETSCAPE_URL: {\n GtkDndUtil::WriteURLWithName(selection_data, drop_data_->url,\n drop_data_->url_title, target_type);\n break;\n }\n\n case GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS: {\n gtk_selection_data_set(\n selection_data,\n drag_file_mime_type_, kBitsPerByte,\n reinterpret_cast<const guchar*>(drop_data_->file_contents.data()),\n drop_data_->file_contents.length());\n break;\n }\n\n default:\n NOTREACHED();\n }\n}\n\ngboolean TabContentsDragSource::OnDragFailed() {\n drag_failed_ = true;\n\n gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView());\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceEndedAt(\n client.x(), client.y(), root.x(), root.y(),\n WebDragOperationNone);\n }\n\n \/\/ Let the native failure animation run.\n return FALSE;\n}\n\nvoid TabContentsDragSource::OnDragEnd(WebDragOperation operation) {\n MessageLoopForUI::current()->RemoveObserver(this);\n\n if (!drag_failed_) {\n gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView());\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceEndedAt(\n client.x(), client.y(), root.x(), root.y(), operation);\n }\n }\n\n if (tab_contents()->render_view_host())\n tab_contents()->render_view_host()->DragSourceSystemDragEnded();\n\n drop_data_.reset();\n}\n\ngfx::NativeView TabContentsDragSource::GetContentNativeView() const {\n return tab_contents_view_->GetContentNativeView();\n}\n<commit_msg>GTK: don't get stuck in render view drag.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/tab_contents_drag_source.h\"\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"base\/mime_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"webkit\/glue\/webdropdata.h\"\n\nusing WebKit::WebDragOperation;\nusing WebKit::WebDragOperationNone;\n\nTabContentsDragSource::TabContentsDragSource(\n TabContentsView* tab_contents_view)\n : tab_contents_view_(tab_contents_view),\n drag_failed_(false),\n drag_widget_(NULL) {\n drag_widget_ = gtk_invisible_new();\n g_signal_connect(drag_widget_, \"drag-failed\",\n G_CALLBACK(OnDragFailedThunk), this);\n g_signal_connect(drag_widget_, \"drag-end\", G_CALLBACK(OnDragEndThunk), this);\n g_signal_connect(drag_widget_, \"drag-data-get\",\n G_CALLBACK(OnDragDataGetThunk), this);\n g_object_ref_sink(drag_widget_);\n}\n\nTabContentsDragSource::~TabContentsDragSource() {\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragFailedThunk), this);\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragEndThunk), this);\n g_signal_handlers_disconnect_by_func(drag_widget_,\n reinterpret_cast<gpointer>(OnDragDataGetThunk), this);\n\n \/\/ Break the current drag, if any.\n if (drop_data_.get()) {\n gtk_grab_add(drag_widget_);\n gtk_grab_remove(drag_widget_);\n MessageLoopForUI::current()->RemoveObserver(this);\n drop_data_.reset();\n }\n\n gtk_widget_destroy(drag_widget_);\n g_object_unref(drag_widget_);\n drag_widget_ = NULL;\n}\n\nTabContents* TabContentsDragSource::tab_contents() const {\n return tab_contents_view_->tab_contents();\n}\n\nvoid TabContentsDragSource::StartDragging(const WebDropData& drop_data,\n GdkEventButton* last_mouse_down) {\n int targets_mask = 0;\n\n if (!drop_data.plain_text.empty())\n targets_mask |= GtkDndUtil::TEXT_PLAIN;\n if (drop_data.url.is_valid()) {\n targets_mask |= GtkDndUtil::TEXT_URI_LIST;\n targets_mask |= GtkDndUtil::CHROME_NAMED_URL;\n targets_mask |= GtkDndUtil::NETSCAPE_URL;\n }\n if (!drop_data.text_html.empty())\n targets_mask |= GtkDndUtil::TEXT_HTML;\n if (!drop_data.file_contents.empty())\n targets_mask |= GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS;\n\n if (targets_mask == 0) {\n NOTIMPLEMENTED();\n if (tab_contents()->render_view_host())\n tab_contents()->render_view_host()->DragSourceSystemDragEnded();\n }\n\n drop_data_.reset(new WebDropData(drop_data));\n\n GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(targets_mask);\n if (targets_mask & GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS) {\n drag_file_mime_type_ = gdk_atom_intern(\n mime_util::GetDataMimeType(drop_data.file_contents).c_str(), FALSE);\n gtk_target_list_add(list, drag_file_mime_type_,\n 0, GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS);\n }\n\n drag_failed_ = false;\n \/\/ If we don't pass an event, GDK won't know what event time to start grabbing\n \/\/ mouse events. Technically it's the mouse motion event and not the mouse\n \/\/ down event that causes the drag, but there's no reliable way to know\n \/\/ *which* motion event initiated the drag, so this will have to do.\n \/\/ TODO(estade): This can sometimes be very far off, e.g. if the user clicks\n \/\/ and holds and doesn't start dragging for a long time. I doubt it matters\n \/\/ much, but we should probably look into the possibility of getting the\n \/\/ initiating event from webkit.\n GdkDragContext* context = gtk_drag_begin(\n drag_widget_, list,\n static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK),\n 1, \/\/ Drags are always initiated by the left button.\n reinterpret_cast<GdkEvent*>(last_mouse_down));\n \/\/ The drag adds a ref; let it own the list.\n gtk_target_list_unref(list);\n\n \/\/ Sometimes the drag fails to start; |context| will be NULL and we won't\n \/\/ get a drag-end signal.\n if (!context) {\n drop_data_.reset();\n if (tab_contents()->render_view_host())\n tab_contents()->render_view_host()->DragSourceSystemDragEnded();\n return;\n }\n\n MessageLoopForUI::current()->AddObserver(this);\n}\n\nvoid TabContentsDragSource::WillProcessEvent(GdkEvent* event) {\n \/\/ No-op.\n}\n\nvoid TabContentsDragSource::DidProcessEvent(GdkEvent* event) {\n if (event->type != GDK_MOTION_NOTIFY)\n return;\n\n GdkEventMotion* event_motion = reinterpret_cast<GdkEventMotion*>(event);\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceMovedTo(\n client.x(), client.y(),\n static_cast<int>(event_motion->x_root),\n static_cast<int>(event_motion->y_root));\n }\n}\n\nvoid TabContentsDragSource::OnDragDataGet(\n GdkDragContext* context, GtkSelectionData* selection_data,\n guint target_type, guint time) {\n const int kBitsPerByte = 8;\n\n switch (target_type) {\n case GtkDndUtil::TEXT_PLAIN: {\n std::string utf8_text = UTF16ToUTF8(drop_data_->plain_text);\n gtk_selection_data_set_text(selection_data, utf8_text.c_str(),\n utf8_text.length());\n break;\n }\n\n case GtkDndUtil::TEXT_HTML: {\n \/\/ TODO(estade): change relative links to be absolute using\n \/\/ |html_base_url|.\n std::string utf8_text = UTF16ToUTF8(drop_data_->text_html);\n gtk_selection_data_set(selection_data,\n GtkDndUtil::GetAtomForTarget(\n GtkDndUtil::TEXT_HTML),\n kBitsPerByte,\n reinterpret_cast<const guchar*>(utf8_text.c_str()),\n utf8_text.length());\n break;\n }\n\n case GtkDndUtil::TEXT_URI_LIST:\n case GtkDndUtil::CHROME_NAMED_URL:\n case GtkDndUtil::NETSCAPE_URL: {\n GtkDndUtil::WriteURLWithName(selection_data, drop_data_->url,\n drop_data_->url_title, target_type);\n break;\n }\n\n case GtkDndUtil::CHROME_WEBDROP_FILE_CONTENTS: {\n gtk_selection_data_set(\n selection_data,\n drag_file_mime_type_, kBitsPerByte,\n reinterpret_cast<const guchar*>(drop_data_->file_contents.data()),\n drop_data_->file_contents.length());\n break;\n }\n\n default:\n NOTREACHED();\n }\n}\n\ngboolean TabContentsDragSource::OnDragFailed() {\n drag_failed_ = true;\n\n gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView());\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceEndedAt(\n client.x(), client.y(), root.x(), root.y(),\n WebDragOperationNone);\n }\n\n \/\/ Let the native failure animation run.\n return FALSE;\n}\n\nvoid TabContentsDragSource::OnDragEnd(WebDragOperation operation) {\n MessageLoopForUI::current()->RemoveObserver(this);\n\n if (!drag_failed_) {\n gfx::Point root = gtk_util::ScreenPoint(GetContentNativeView());\n gfx::Point client = gtk_util::ClientPoint(GetContentNativeView());\n\n if (tab_contents()->render_view_host()) {\n tab_contents()->render_view_host()->DragSourceEndedAt(\n client.x(), client.y(), root.x(), root.y(), operation);\n }\n }\n\n if (tab_contents()->render_view_host())\n tab_contents()->render_view_host()->DragSourceSystemDragEnded();\n\n drop_data_.reset();\n}\n\ngfx::NativeView TabContentsDragSource::GetContentNativeView() const {\n return tab_contents_view_->GetContentNativeView();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the Pangolin HDR extension project\n *\n * http:\/\/github.com\/akramhussein\/hdr\n *\n * Copyright (c) 2012 Akram Hussein\n *\n * Original source code by Steven Lovegrove\n *\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"image.h\"\n\nusing namespace std;\n\nnamespace pangolin\n{\n \n void CopyPPMToJPG(const char* filename_ppm, const char* filename_jpg){\n \n try {\n Magick::Image img;\n img.read(filename_ppm);\n img.write(filename_jpg);\n } \n catch( Magick::ErrorFileOpen &error ) {\n \/\/ Process Magick++ file open error\n cerr << \"Error: \" << error.what() << endl;\n }\n }\n \n void WriteExifData(const pangolin::FirewireVideo* video, const std::string& filename)\n {\n \n Exiv2::ExifData exifData;\n \n try {\n \n \/\/ TO DO - change to metadata instead\n exifData[\"Exif.Image.Make\"] = video->GetCameraVendor();\n exifData[\"Exif.Image.Model\"] = video->GetCameraModel();\n exifData[\"Exif.Photo.FNumber\"] = Exiv2::Rational(7, 5); \/\/ hard coded\n exifData[\"Exif.Photo.ExposureTime\"] = Exiv2::floatToRationalCast(video->GetFeatureValue(DC1394_FEATURE_SHUTTER));\t\n exifData[\"Exif.Photo.ColorSpace\"] = uint16_t(1);\n exifData[\"Exif.Photo.WhiteBalance\"] = uint16_t(video->GetFeatureMode(DC1394_FEATURE_WHITE_BALANCE)); \/\/ 0=auto,1=man\n exifData[\"Exif.Photo.GainControl\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_GAIN));\n exifData[\"Exif.Photo.Saturation\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_SATURATION));\n exifData[\"Exif.Photo.Sharpness\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_SHARPNESS));\n \n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename);\n assert(image.get() != 0);\n \n image->setExifData(exifData);\n image->writeMetadata();\n \n }\n catch (Exiv2::AnyError& e) {\n cout << \"Exiv error: '\" << e << \"'\\n\";\n }\n \n\n }\n\n \/* Borrowed from LuminanceHDR package\n * \n * Credits to Giuseppe Rota <grota@users.sourceforge.net>\n *\n * This function obtains the \"average scene luminance\" (cd\/m^2) from an image file.\n * \"average scene luminance\" is the L (aka B) value mentioned in [1]\n * You have to take a log2f of the returned value to get an EV value.\n * \n * We are using K=12.07488f and the exif-implied value of N=1\/3.125 (see [1]).\n * K=12.07488f is the 1.0592f * 11.4f value in pfscalibration's pfshdrcalibrate.cpp file.\n * Based on [3] we can say that the value can also be 12.5 or even 14.\n * Another reference for APEX is [4] where N is 0.3, closer to the APEX specification of 2^(-7\/4)=0.2973.\n * \n * [1] http:\/\/en.wikipedia.org\/wiki\/APEX_system\n * [2] http:\/\/en.wikipedia.org\/wiki\/Exposure_value\n * [3] http:\/\/en.wikipedia.org\/wiki\/Light_meter\n * [4] http:\/\/doug.kerr.home.att.net\/pumpkin\/#APEX\n * \n * This function tries first to obtain the shutter speed from either of\n * two exif tags (there is no standard between camera manifacturers):\n * ExposureTime or ShutterSpeedValue.\n * Same thing for f-number: it can be found in FNumber or in ApertureValue.\n * \n * F-number and shutter speed are mandatory in exif data for EV calculation, iso is not.\n *\/\n float GetAvgLuminance(const std::string& filename)\n {\n try\n {\n\n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename);\n image->readMetadata();\n \n Exiv2::ExifData exifData;\n exifData = image->exifData();\n \n if (exifData.empty()){\n throw VideoException(\"Exiv Error: No Exif Data in image\");\n }\n\n Exiv2::ExifData::const_iterator _expo = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ExposureTime\"));\n Exiv2::ExifData::const_iterator _expo2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ShutterSpeedValue\"));\n Exiv2::ExifData::const_iterator _iso = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ISOSpeedRatings\"));\n Exiv2::ExifData::const_iterator _fnum = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.FNumber\"));\n Exiv2::ExifData::const_iterator _fnum2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ApertureValue\"));\n \n \/\/ default not valid values\n float expo = -1;\n float iso = -1;\n float fnum = -1;\n \n if (_expo != exifData.end())\n {\n expo=_expo->toFloat();\n }\n else if (_expo2 != exifData.end())\n {\n long num=1, div=1;\n double tmp = std::exp(std::log(2.0) * _expo2->toFloat());\n if (tmp > 1)\n {\n div = static_cast<long>(tmp + 0.5);\n }\n else\n {\n num = static_cast<long>(1\/tmp + 0.5);\n }\n expo = static_cast<float>(num)\/static_cast<float>(div);\n }\n \n if (_fnum != exifData.end())\n {\n fnum = _fnum->toFloat();\n }\n else if (_fnum2 != exifData.end())\n {\n fnum = static_cast<float>(std::exp(std::log(2.0) * _fnum2->toFloat() \/ 2));\n }\n \/\/ some cameras\/lens DO print the fnum but with value 0, and this is not allowed for ev computation purposes.\n if (fnum == 0)\n return -1;\n \n \/\/if iso is found use that value, otherwise assume a value of iso=100. (again, some cameras do not print iso in exif).\n if (_iso == exifData.end())\n {\n iso = 100.0;\n }\n else\n {\n iso = _iso->toFloat();\n }\n \n \/\/At this point the three variables have to be != -1\n if (expo!=-1 && iso!=-1 && fnum!=-1)\n {\n \/\/ \t\tstd::cerr << \"expo=\" << expo << \" fnum=\" << fnum << \" iso=\" << iso << \" |returned=\" << (expo * iso) \/ (fnum*fnum*12.07488f) << std::endl;\n return ( (expo * iso) \/ (fnum*fnum*12.07488f) );\n }\n else\n {\n return -1;\n }\n }\n catch (Exiv2::AnyError& e)\n {\n throw VideoException(\"Exiv Error\");\n }\n }\n \n void CopyExifData(const std::string& from, const std::string& to, bool dont_overwrite)\n {\n \n Exiv2::Image::AutoPtr sourceimage = Exiv2::ImageFactory::open(from);\n Exiv2::Image::AutoPtr destimage = Exiv2::ImageFactory::open(to);\n \n sourceimage->readMetadata();\n Exiv2::ExifData &src_exifData = sourceimage->exifData();\n if (src_exifData.empty())\n {\n throw Exiv2::Error(1, \"No exif data found in the image\");\n }\n if (dont_overwrite)\n {\n destimage->readMetadata();\n Exiv2::ExifData &dest_exifData = destimage->exifData();\n Exiv2::ExifData::const_iterator end_src = src_exifData.end();\n \n for (Exiv2::ExifData::const_iterator i = src_exifData.begin(); i != end_src; ++i)\n {\n\t\t\t\t\/\/check if current source key exists in destination file\n\t\t\t\tExiv2::ExifData::iterator maybe_exists = dest_exifData.findKey( Exiv2::ExifKey(i->key()) );\n\t\t\t\t\/\/if exists AND not to overwrite\n\t\t\t\tif (maybe_exists != dest_exifData.end())\n {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n else\n {\n\t\t\t\t\t\/\/ copy the value\n\t\t\t\t\t\/\/ we create a new tag in the destination file, the tag has the key of the source\n\t\t\t\t\tExiv2::Exifdatum& dest_tag = dest_exifData[i->key()];\n\t\t\t\t\t\/\/now the tag has also the value of the source\n\t\t\t\t\tdest_tag.setValue(&(i->value()));\n\t\t\t\t}\n }\n }\n else\n {\n destimage->setExifData(src_exifData);\n }\n \n destimage->writeMetadata();\n }\n \n\n bool JpgToHDRGEN(const char* filename, FILE* hdrgen, int frame_number)\n {\n \n char file_path[128];\n sprintf(file_path, \".\/%s\/jpg\/image0000%d.jpg\", filename, frame_number);\n \n try\n {\n \n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file_path);\n image->readMetadata();\n \n Exiv2::ExifData exifData;\n exifData = image->exifData();\n \n if (exifData.empty()){\n throw VideoException(\"Exiv Error: No Exif Data in image\");\n }\n \n Exiv2::ExifData::const_iterator _expo = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ExposureTime\"));\n Exiv2::ExifData::const_iterator _expo2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ShutterSpeedValue\"));\n Exiv2::ExifData::const_iterator _iso = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ISOSpeedRatings\"));\n Exiv2::ExifData::const_iterator _fnum = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.FNumber\"));\n Exiv2::ExifData::const_iterator _fnum2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ApertureValue\"));\n \n \/\/ default not valid values\n float expo = -1;\n int iso = -1;\n double fnum = -1;\n \n if (_expo != exifData.end())\n {\n expo=_expo->toFloat();\n }\n else if (_expo2 != exifData.end())\n {\n long num=1, div=1;\n double tmp = std::exp(std::log(2.0) * _expo2->toFloat());\n if (tmp > 1)\n {\n div = static_cast<long>(tmp + 0.5);\n }\n else\n {\n num = static_cast<long>(1\/tmp + 0.5);\n }\n expo = static_cast<float>(num)\/static_cast<float>(div);\n }\n \n if (_fnum != exifData.end())\n {\n fnum = _fnum->toFloat();\n }\n else if (_fnum2 != exifData.end())\n {\n fnum = static_cast<float>(std::exp(std::log(2.0) * _fnum2->toFloat() \/ 2));\n }\n \/\/ some cameras\/lens DO print the fnum but with value 0, and this is not allowed for ev computation purposes.\n if (fnum == 0)\n return false;\n \n \/\/if iso is found use that value, otherwise assume a value of iso=100. (again, some cameras do not print iso in exif).\n if (_iso == exifData.end())\n {\n iso = 100;\n }\n else\n {\n iso = _iso->toFloat();\n }\n \n \/\/At this point the three variables have to be != -1\n if (expo!=-1 && iso!=-1 && fnum!=-1)\n {\n \n \/\/ write new line to file in format:\n \/\/ path_to_an_image inverse_of_exposure_time_in_seconds aperture_size iso_speed 0\n fprintf(hdrgen,\"%s %f %2.2f %d 0\\n\", \n file_path, \n 1\/expo, \n fnum, \n iso\n );\n \n }\n else\n {\n return false;\n }\n }\n catch (Exiv2::AnyError& e)\n {\n throw VideoException(\"Exiv Error\");\n }\n \n return true;\n }\n \n}<commit_msg>Added ExposureBias to Exif tags (EV)<commit_after>\/* This file is part of the Pangolin HDR extension project\n *\n * http:\/\/github.com\/akramhussein\/hdr\n *\n * Copyright (c) 2012 Akram Hussein\n *\n * Original source code by Steven Lovegrove\n *\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"image.h\"\n\nusing namespace std;\n\nnamespace pangolin\n{\n \n void CopyPPMToJPG(const char* filename_ppm, const char* filename_jpg){\n \n try {\n Magick::Image img;\n img.read(filename_ppm);\n img.write(filename_jpg);\n } \n catch( Magick::ErrorFileOpen &error ) {\n \/\/ Process Magick++ file open error\n cerr << \"Error: \" << error.what() << endl;\n }\n }\n \n void WriteExifData(const pangolin::FirewireVideo* video, const std::string& filename)\n {\n \n Exiv2::ExifData exifData;\n \n try {\n \n \/\/ TO DO - change to metadata instead\n exifData[\"Exif.Image.Make\"] = video->GetCameraVendor();\n exifData[\"Exif.Image.Model\"] = video->GetCameraModel();\n exifData[\"Exif.Photo.FNumber\"] = Exiv2::Rational(7, 5); \/\/ hard coded\n exifData[\"Exif.Photo.ExposureTime\"] = Exiv2::floatToRationalCast(video->GetFeatureValue(DC1394_FEATURE_SHUTTER));\t\n exifData[\"Exif.Photo.ExposureBiasValue\"] = Exiv2::floatToRationalCast(video->GetFeatureValue(DC1394_FEATURE_EXPOSURE));\t\n exifData[\"Exif.Photo.ColorSpace\"] = uint16_t(1);\n exifData[\"Exif.Photo.WhiteBalance\"] = uint16_t(video->GetFeatureMode(DC1394_FEATURE_WHITE_BALANCE)); \/\/ 0=auto,1=man\n exifData[\"Exif.Photo.GainControl\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_GAIN));\n exifData[\"Exif.Photo.Saturation\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_SATURATION));\n exifData[\"Exif.Photo.Sharpness\"] = uint16_t(video->GetFeatureValue(DC1394_FEATURE_SHARPNESS));\n\n \n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename);\n assert(image.get() != 0);\n \n image->setExifData(exifData);\n image->writeMetadata();\n \n }\n catch (Exiv2::AnyError& e) {\n cout << \"Exiv error: '\" << e << \"'\\n\";\n }\n \n\n }\n\n \/* Borrowed from LuminanceHDR package\n * \n * Credits to Giuseppe Rota <grota@users.sourceforge.net>\n *\n * This function obtains the \"average scene luminance\" (cd\/m^2) from an image file.\n * \"average scene luminance\" is the L (aka B) value mentioned in [1]\n * You have to take a log2f of the returned value to get an EV value.\n * \n * We are using K=12.07488f and the exif-implied value of N=1\/3.125 (see [1]).\n * K=12.07488f is the 1.0592f * 11.4f value in pfscalibration's pfshdrcalibrate.cpp file.\n * Based on [3] we can say that the value can also be 12.5 or even 14.\n * Another reference for APEX is [4] where N is 0.3, closer to the APEX specification of 2^(-7\/4)=0.2973.\n * \n * [1] http:\/\/en.wikipedia.org\/wiki\/APEX_system\n * [2] http:\/\/en.wikipedia.org\/wiki\/Exposure_value\n * [3] http:\/\/en.wikipedia.org\/wiki\/Light_meter\n * [4] http:\/\/doug.kerr.home.att.net\/pumpkin\/#APEX\n * \n * This function tries first to obtain the shutter speed from either of\n * two exif tags (there is no standard between camera manifacturers):\n * ExposureTime or ShutterSpeedValue.\n * Same thing for f-number: it can be found in FNumber or in ApertureValue.\n * \n * F-number and shutter speed are mandatory in exif data for EV calculation, iso is not.\n *\/\n float GetAvgLuminance(const std::string& filename)\n {\n try\n {\n\n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename);\n image->readMetadata();\n \n Exiv2::ExifData exifData;\n exifData = image->exifData();\n \n if (exifData.empty()){\n throw VideoException(\"Exiv Error: No Exif Data in image\");\n }\n\n Exiv2::ExifData::const_iterator _expo = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ExposureTime\"));\n Exiv2::ExifData::const_iterator _expo2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ShutterSpeedValue\"));\n Exiv2::ExifData::const_iterator _iso = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ISOSpeedRatings\"));\n Exiv2::ExifData::const_iterator _fnum = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.FNumber\"));\n Exiv2::ExifData::const_iterator _fnum2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ApertureValue\"));\n \n \/\/ default not valid values\n float expo = -1;\n float iso = -1;\n float fnum = -1;\n \n if (_expo != exifData.end())\n {\n expo=_expo->toFloat();\n }\n else if (_expo2 != exifData.end())\n {\n long num=1, div=1;\n double tmp = std::exp(std::log(2.0) * _expo2->toFloat());\n if (tmp > 1)\n {\n div = static_cast<long>(tmp + 0.5);\n }\n else\n {\n num = static_cast<long>(1\/tmp + 0.5);\n }\n expo = static_cast<float>(num)\/static_cast<float>(div);\n }\n \n if (_fnum != exifData.end())\n {\n fnum = _fnum->toFloat();\n }\n else if (_fnum2 != exifData.end())\n {\n fnum = static_cast<float>(std::exp(std::log(2.0) * _fnum2->toFloat() \/ 2));\n }\n \/\/ some cameras\/lens DO print the fnum but with value 0, and this is not allowed for ev computation purposes.\n if (fnum == 0)\n return -1;\n \n \/\/if iso is found use that value, otherwise assume a value of iso=100. (again, some cameras do not print iso in exif).\n if (_iso == exifData.end())\n {\n iso = 100.0;\n }\n else\n {\n iso = _iso->toFloat();\n }\n \n \/\/At this point the three variables have to be != -1\n if (expo!=-1 && iso!=-1 && fnum!=-1)\n {\n \/\/ \t\tstd::cerr << \"expo=\" << expo << \" fnum=\" << fnum << \" iso=\" << iso << \" |returned=\" << (expo * iso) \/ (fnum*fnum*12.07488f) << std::endl;\n return ( (expo * iso) \/ (fnum*fnum*12.07488f) );\n }\n else\n {\n return -1;\n }\n }\n catch (Exiv2::AnyError& e)\n {\n throw VideoException(\"Exiv Error\");\n }\n }\n \n void CopyExifData(const std::string& from, const std::string& to, bool dont_overwrite)\n {\n \n Exiv2::Image::AutoPtr sourceimage = Exiv2::ImageFactory::open(from);\n Exiv2::Image::AutoPtr destimage = Exiv2::ImageFactory::open(to);\n \n sourceimage->readMetadata();\n Exiv2::ExifData &src_exifData = sourceimage->exifData();\n if (src_exifData.empty())\n {\n throw Exiv2::Error(1, \"No exif data found in the image\");\n }\n if (dont_overwrite)\n {\n destimage->readMetadata();\n Exiv2::ExifData &dest_exifData = destimage->exifData();\n Exiv2::ExifData::const_iterator end_src = src_exifData.end();\n \n for (Exiv2::ExifData::const_iterator i = src_exifData.begin(); i != end_src; ++i)\n {\n\t\t\t\t\/\/check if current source key exists in destination file\n\t\t\t\tExiv2::ExifData::iterator maybe_exists = dest_exifData.findKey( Exiv2::ExifKey(i->key()) );\n\t\t\t\t\/\/if exists AND not to overwrite\n\t\t\t\tif (maybe_exists != dest_exifData.end())\n {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n else\n {\n\t\t\t\t\t\/\/ copy the value\n\t\t\t\t\t\/\/ we create a new tag in the destination file, the tag has the key of the source\n\t\t\t\t\tExiv2::Exifdatum& dest_tag = dest_exifData[i->key()];\n\t\t\t\t\t\/\/now the tag has also the value of the source\n\t\t\t\t\tdest_tag.setValue(&(i->value()));\n\t\t\t\t}\n }\n }\n else\n {\n destimage->setExifData(src_exifData);\n }\n \n destimage->writeMetadata();\n }\n \n\n bool JpgToHDRGEN(const char* filename, FILE* hdrgen, int frame_number)\n {\n \n char file_path[128];\n sprintf(file_path, \".\/%s\/jpg\/image0000%d.jpg\", filename, frame_number);\n \n try\n {\n \n Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(file_path);\n image->readMetadata();\n \n Exiv2::ExifData exifData;\n exifData = image->exifData();\n \n if (exifData.empty()){\n throw VideoException(\"Exiv Error: No Exif Data in image\");\n }\n \n Exiv2::ExifData::const_iterator _expo = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ExposureTime\"));\n Exiv2::ExifData::const_iterator _expo2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ShutterSpeedValue\"));\n Exiv2::ExifData::const_iterator _iso = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ISOSpeedRatings\"));\n Exiv2::ExifData::const_iterator _fnum = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.FNumber\"));\n Exiv2::ExifData::const_iterator _fnum2 = exifData.findKey(Exiv2::ExifKey(\"Exif.Photo.ApertureValue\"));\n \n \/\/ default not valid values\n float expo = -1;\n int iso = -1;\n double fnum = -1;\n \n if (_expo != exifData.end())\n {\n expo=_expo->toFloat();\n }\n else if (_expo2 != exifData.end())\n {\n long num=1, div=1;\n double tmp = std::exp(std::log(2.0) * _expo2->toFloat());\n if (tmp > 1)\n {\n div = static_cast<long>(tmp + 0.5);\n }\n else\n {\n num = static_cast<long>(1\/tmp + 0.5);\n }\n expo = static_cast<float>(num)\/static_cast<float>(div);\n }\n \n if (_fnum != exifData.end())\n {\n fnum = _fnum->toFloat();\n }\n else if (_fnum2 != exifData.end())\n {\n fnum = static_cast<float>(std::exp(std::log(2.0) * _fnum2->toFloat() \/ 2));\n }\n \/\/ some cameras\/lens DO print the fnum but with value 0, and this is not allowed for ev computation purposes.\n if (fnum == 0)\n return false;\n \n \/\/if iso is found use that value, otherwise assume a value of iso=100. (again, some cameras do not print iso in exif).\n if (_iso == exifData.end())\n {\n iso = 100;\n }\n else\n {\n iso = _iso->toFloat();\n }\n \n \/\/At this point the three variables have to be != -1\n if (expo!=-1 && iso!=-1 && fnum!=-1)\n {\n \n \/\/ write new line to file in format:\n \/\/ path_to_an_image inverse_of_exposure_time_in_seconds aperture_size iso_speed 0\n fprintf(hdrgen,\"%s %f %2.2f %d 0\\n\", \n file_path, \n 1\/expo, \n fnum, \n iso\n );\n \n }\n else\n {\n return false;\n }\n }\n catch (Exiv2::AnyError& e)\n {\n throw VideoException(\"Exiv Error\");\n }\n \n return true;\n }\n \n}<|endoftext|>"} {"text":"<commit_before>#include <cstdint>\n#include <SDL2\/SDL.h>\n\n#include \"Screen.h\"\n#include \"WinAPI.h\"\n\n#define WINDOW_HEIGHT SCREEN_HEIGHT+20\t\/\/Windows menu bar adds 20 pixels\n\nScreen::Screen(void)\n{\n\tif (SDL_Init(SDL_INIT_VIDEO)<0)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL video\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\tatexit(SDL_Quit);\n\n\twindow = SDL_CreateWindow(\"Captain PlaneEd\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);\n\tif (window == NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL Window\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\trender = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\tif (render == NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL Renderer\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\tSDL_RenderSetLogicalSize(render, SCREEN_WIDTH, SCREEN_HEIGHT);\n\tSDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, \"nearest\");\n\n\tsurface = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);\t\/\/ Implicitly ARGB8888, compatible with the below texture\n\tif (surface==NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init screen SDL Surface\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\t\n\ttexture = SDL_CreateTexture(render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);\n\tif (texture==NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init screen SDL Texture\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\tthis->BackgroundColour = {.red = 0, .green = 0, .blue = 0};\n\n\t\/\/ Windows-only crap to generate a menu bar\n\tWinAPI::SaveHWND(window);\n\tWinAPI::CreateMenuBar();\n}\n\nvoid Screen::ProcessDisplay(void)\n{\n\tvoid* pixels;\n\tint pitch;\n\tSDL_LockTexture(texture, NULL, &pixels, &pitch);\n\tmemcpy(pixels, surface->pixels, pitch*surface->h);\n\tSDL_UnlockTexture(texture);\n\n\tSDL_RenderCopy(render, texture, NULL, NULL);\n\tSDL_RenderPresent(render);\n}\n\nvoid Screen::Fill(uint8_t red, uint8_t green, uint8_t blue)\n{\n\tSDL_FillRect(this->surface, NULL, SDL_MapRGB(this->surface->format, red, green, blue));\n}\n<commit_msg>Adding 'this' pointers<commit_after>#include <cstdint>\n#include <SDL2\/SDL.h>\n\n#include \"Screen.h\"\n#include \"WinAPI.h\"\n\n#define WINDOW_HEIGHT SCREEN_HEIGHT+20\t\/\/Windows menu bar adds 20 pixels\n\nScreen::Screen(void)\n{\n\tif (SDL_Init(SDL_INIT_VIDEO)<0)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL video\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\tatexit(SDL_Quit);\n\n\tthis->window = SDL_CreateWindow(\"Captain PlaneEd\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);\n\tif (this->window == NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL Window\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\tthis->render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\tif (this->render == NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init SDL Renderer\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\tSDL_RenderSetLogicalSize(render, SCREEN_WIDTH, SCREEN_HEIGHT);\n\tSDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, \"nearest\");\n\n\tthis->surface = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);\t\/\/ Implicitly ARGB8888, compatible with the below texture\n\tif (this->surface==NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init screen SDL Surface\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\t\n\tthis->texture = SDL_CreateTexture(this->render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);\n\tif (this->texture==NULL)\n\t{\n\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Unable to init screen SDL Texture\", SDL_GetError(), NULL);\n\t\texit(1);\n\t}\n\n\tthis->BackgroundColour = {.red = 0, .green = 0, .blue = 0};\n\n\t\/\/ Windows-only crap to generate a menu bar\n\tWinAPI::SaveHWND(this->window);\n\tWinAPI::CreateMenuBar();\n}\n\nvoid Screen::ProcessDisplay(void)\n{\n\tvoid* pixels;\n\tint pitch;\n\tSDL_LockTexture(this->texture, NULL, &pixels, &pitch);\n\tmemcpy(pixels, this->surface->pixels, pitch*this->surface->h);\n\tSDL_UnlockTexture(this->texture);\n\n\tSDL_RenderCopy(this->render, this->texture, NULL, NULL);\n\tSDL_RenderPresent(this->render);\n}\n\nvoid Screen::Fill(uint8_t red, uint8_t green, uint8_t blue)\n{\n\tSDL_FillRect(this->surface, NULL, SDL_MapRGB(this->surface->format, red, green, blue));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RenderThread.hpp\"\n#include <Core\/Engine.hh>\n#include <Context\/SdlContext.hh>\n#include <Utils\/ThreadName.hpp>\n#include <Threads\/Tasks\/ToRenderTasks.hpp>\n#include <Threads\/Commands\/ToRenderCommands.hpp>\n#include <Threads\/Tasks\/BasicTasks.hpp>\n#include <Context\/SdlContext.hh>\n#include <Utils\/Containers\/Vector.hpp>\n#include <Threads\/ThreadManager.hpp>\n#include <Core\/Engine.hh>\n#include <Context\/SdlContext.hh>\n#include <Render\/GeometryManagement\/Painting\/Painter.hh>\n#include <Render\/Pipelining\/Pipelines\/CustomPipeline\/BasicPipeline.hh>\n#include <Render\/Pipelining\/Pipelines\/CustomPipeline\/DeferredShading.hh>\n#include <Utils\/OpenGL.hh>\n#include <Utils\/Age_Imgui.hpp>\n#include <Render\/Properties\/Transformation.hh>\n#include <SpacePartitioning\/Ouptut\/RenderCamera.hh>\n#include <SpacePartitioning\/Ouptut\/RenderLight.hh>\n#include <SpacePartitioning\/Ouptut\/RenderPipeline.hh>\n#include <Utils\/Debug.hpp>\n#include <Render\/GeometryManagement\/SimpleGeometry.hpp>\n\nnamespace AGE\n{\n\tRenderThread::RenderThread()\n\t\t: Thread(AGE::Thread::ThreadType::Render)\n\t\t, _context(nullptr),\n\t\tpaintingManager(std::make_shared<PaintingManager>()),\n\t\tpipelines(2)\n\t{\n\t}\n\n\tRenderThread::~RenderThread()\n\t{}\n\n\tvoid RenderThread::_recompileShaders()\n\t{\n\t\t\/\/ to be sure that this function is only called in render thread\n\t\tAGE_ASSERT(GetThreadManager()->getCurrentThread() == (AGE::Thread*)GetRenderThread());\n\n\t\tfor (auto &e : pipelines)\n\t\t{\n\t\t\tif (!e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\te->recompileShaders();\n\t\t}\n\t}\n\n\tvoid RenderThread::getQuadGeometry(Key<Vertices> &v, Key<Painter> &p)\n\t{\n\t\t\/\/ to be sure that this function is only called in render thread\n\t\tAGE_ASSERT(GetThreadManager()->getCurrentThread() == (AGE::Thread*)GetRenderThread());\n\n\t\tif (Quad::VerticesKey.isValid())\n\t\t{\n\t\t\tv = Quad::VerticesKey;\n\t\t\tp = Quad::PainterKey;\n\t\t\treturn;\n\t\t}\n\n\t\tauto type = std::make_pair<GLenum, std::string>(GL_FLOAT_VEC4, \"position\");\n\t\tstd::vector<std::pair < GLenum, std::string > > types;\n\t\ttypes.push_back(type);\n\n\t\tif (!paintingManager->has_painter(types))\n\t\t{\n\t\t\tQuad::PainterKey = paintingManager->add_painter(std::move(types));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQuad::PainterKey = paintingManager->get_painter(types);\n\t\t}\n\t\tauto &painterPtr = paintingManager->get_painter(Quad::PainterKey);\n\n\t\tQuad::VerticesKey = painterPtr->add_vertices(Quad::PositionsNumber, Quad::IndicesNumber);\n\t\tauto vertices = painterPtr->get_vertices(Quad::VerticesKey);\n\n\t\tvertices->set_data<glm::vec4>(Quad::Positions, std::string(\"position\"));\n\t\tvertices->set_indices(Quad::Indices);\n\n\t\tv = Quad::VerticesKey;\n\t\tp = Quad::PainterKey;\n\t}\n\n\tbool RenderThread::init()\n\t{\n\t\tregisterCallback<Tasks::Render::CreateRenderContext>([this](Tasks::Render::CreateRenderContext &msg)\n\t\t{\n\t\t\t_context = msg.engine->setInstance<SdlContext, IRenderContext>();\n\t\t\tif (!_context->init(0, 1280, 720, \"~AGE~ V0.00001 Demo\"))\n\t\t\t{\n\t\t\t\tmsg.setValue(false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpipelines[DEFERRED] = std::make_unique<DeferredShading>(_context->getScreenSize(), paintingManager);\n\t\t\tpipelines[BASIC] = std::make_unique<BasicPipeline>(paintingManager);\n\t\t\t_recompileShaders();\n\t\t\tmsg.setValue(true);\n\t\t});\n\n \t\tregisterCallback<Commands::ToRender::Flush>([&](Commands::ToRender::Flush& msg)\n\t\t{\n\t\t\t_context->swapContext();\n\t\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::ReloadShaders>([&](Tasks::Render::ReloadShaders& msg)\n\t\t{\n#ifdef AGE_DEBUG\n\t\t\t_recompileShaders();\n#else\n\t\t\tstd::cerr << \"Error : You cannot recompile shader at runtime. This feature is enabled only in debug mode\\n\";\n#endif\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::GetWindowSize>([&](Tasks::Render::GetWindowSize &msg)\n\t\t{\n\t\t\tmsg.setValue(_context->getScreenSize());\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::SetWindowSize>([&](Tasks::Render::SetWindowSize& msg)\n\t\t{\n\t\t\t_context->setScreenSize(msg.size);\n\t\t});\n\n\t\tregisterCallback<Commands::ToRender::CopyDrawLists>([&](Commands::ToRender::CopyDrawLists& msg)\n\t\t{\n\t\t\t_drawlistPtr = msg.listContainer;\n\t\t});\n\n\t\tregisterCallback<Commands::ToRender::RenderDrawLists>([&](Commands::ToRender::RenderDrawLists& msg)\n\t\t{\n\t\t\tuint32_t pipelineIdx = 0;\n\n\t\t\tif (!_drawlistPtr) \/\/ nothing to draw\n\t\t\t\treturn;\n\t\t\tAGE_ASSERT(_drawlistPtr != nullptr);\n\n\t\t\tfor (auto &curPipeline : pipelines)\n\t\t\t{\n\t\t\t\tauto &drawlist = _drawlistPtr->container.cameras;\n\t\t\t\tfor (auto &curCamera : drawlist)\n\t\t\t\t{\n\t\t\t\t\tif (pipelineIdx < curCamera.pipelines.size()) {\n\t\t\t\t\t\tcurPipeline->render(curCamera.pipelines[pipelineIdx], curCamera.lights, curCamera.camInfos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++pipelineIdx;\n\t\t\t}\n\t\t\t_drawlistPtr = nullptr;\n\t\t});\n\n\t\tregisterSharedCallback<AGE::Tasks::Basic::BoolFunction>([&](AGE::Tasks::Basic::BoolFunction& msg)\n\t\t{\n\t\t\tmsg.setValue(msg.function());\n\t\t});\n\n\t\tregisterCallback<AGE::Tasks::Basic::VoidFunction>([&](AGE::Tasks::Basic::VoidFunction& msg)\n\t\t{\n\t\t\tif (msg.function)\n\t\t\t\tmsg.function();\n\t\t});\n\n\t\tregisterCallback<AGE::Tasks::Basic::Exit>([&](AGE::Tasks::Basic::Exit& msg)\n\t\t{\n\t\t\tAGE::CreateEngine()->deleteInstance<IRenderContext>();\n\t\t\tthis->_insideRun = false;\n\t\t});\n\n#ifdef USE_IMGUI\n\t\tregisterCallback<AGE::RenderImgui>([&](AGE::RenderImgui &msg)\n\t\t{\n\t\t\tAGE::Imgui::getInstance()->renderThreadRenderFn(msg.cmd_lists);\n\t\t});\n#endif\n\n\t\treturn true;\n\t}\n\n\tbool RenderThread::release()\n\t{\n\t\treturn true;\n\t}\n\n\tbool RenderThread::launch()\n\t{\n\t\tif (!init())\n\t\t\treturn false;\n\t\t_threadHandle = std::thread(&RenderThread::update, std::ref(*this));\n\t\treturn true;\n\t}\n\n\tbool RenderThread::stop()\n\t{\n\t\tgetQueue()->emplaceTask<Tasks::Basic::Exit>();\n\t\tif (_threadHandle.joinable())\n\t\t\t_threadHandle.join();\n\t\treturn true;\n\t}\n\n\tbool RenderThread::update()\n\t{\n\t\t\/*\n\t\t- Tant qu'il n'y a pas de command\n\t\t-> je pop des task\n\t\t- Une fois que j'ai mes commandes\n\t\t-> pour chacunes d'elles\n\t\t-> je regarde si c'est a moi de les traiter (ex : changement de scene)\n\t\t-> si ca n'est pas a moi de les traiter\n\t\t-> je les passe au render context actif\n\t\t-> si il n'y a pas de render context actif, c'est que j'ai fait une erreur, et j'assert dans ta face :D\n\t\t*\/\n\n\t\t_registerId();\n\n\t\t_run = true;\n\t\t_insideRun = true;\n\t\tDWORD threadId = GetThreadId(static_cast<HANDLE>(_threadHandle.native_handle()));\n\t\tSetThreadName(threadId, this->_name.c_str());\n\n\t\tTMQ::PtrQueue commands;\n\t\tTMQ::PtrQueue tasks;\n\t\tbool commandSuccess;\n\t\tbool taskSuccess;\n\n\t\tstd::chrono::system_clock::time_point waitStart;\n\t\tstd::chrono::system_clock::time_point waitEnd;\n\t\tstd::chrono::system_clock::time_point workStart;\n\t\tstd::chrono::system_clock::time_point workEnd;\n\n\t\twhile (_run && _insideRun)\n\t\t{\n\t\t\twaitStart = std::chrono::high_resolution_clock::now();\n\t\t\ttaskSuccess = commandSuccess = false;\n\t\t\tdo {\n\t\t\t\tif (_context)\n\t\t\t\t\t_context->refreshInputs();\n\t\t\t\tgetQueue()->getTaskAndCommandQueue(tasks, taskSuccess, commands, commandSuccess, TMQ::HybridQueue::Block);\n\t\t\t} while (!taskSuccess && !commandSuccess);\n\t\t\twaitEnd = std::chrono::high_resolution_clock::now();\n\t\t\tworkStart = std::chrono::high_resolution_clock::now();\n\t\t\tif (taskSuccess)\n\t\t\t{\n\t\t\t\twhile (!tasks.empty() && _insideRun)\n\t\t\t\t{\n\t\t\t\t\t\/\/pop all tasks\n\t\t\t\t\tauto task = tasks.front();\n\t\t\t\t\tauto success = execute(task); \/\/ we receive a task that we cannot treat\n\t\t\t\t\tAGE_ASSERT(success);\n\t\t\t\t\ttasks.pop();\n\t\t\t\t\ttaskCounter--;\n\t\t\t\t\tworkEnd = std::chrono::high_resolution_clock::now();\n\t\t\t\t\tconst std::size_t toWait = 33;\n\t\t\t\t\tconst std::size_t elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(workEnd - workStart).count();\n\t\t\t\t\tif (elapsed >= toWait)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << elapsed << \", \";\n\t\t\t\t\t\twhile (!tasks.empty() && _insideRun)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto task = tasks.front();\n\t\t\t\t\t\t\tgetQueue()->moveTask(task, tasks.getFrontSize());\n\t\t\t\t\t\t\ttasks.pop();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (commandSuccess)\n\t\t\t{\n\t\t\t\t\/\/ pop all commands\n\t\t\t\twhile (!commands.empty() && _insideRun)\n\t\t\t\t{\n\t\t\t\t\tauto command = commands.front();\n\t\t\t\t\tauto success = execute(command);\n\t\t\t\t\tAGE_ASSERT(success);\n\t\t\t\t\tcommands.pop();\n\t\t\t\t}\n\n\t\t\t\tworkEnd = std::chrono::high_resolution_clock::now();\n\t\t\t\tGetThreadManager()->updateThreadStatistics(this->_id\n\t\t\t\t\t, std::chrono::duration_cast<std::chrono::microseconds>(workEnd - workStart).count()\n\t\t\t\t\t, std::chrono::duration_cast<std::chrono::microseconds>(waitEnd - waitStart).count());\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}<commit_msg>small changes<commit_after>#include \"RenderThread.hpp\"\n#include <Core\/Engine.hh>\n#include <Context\/SdlContext.hh>\n#include <Utils\/ThreadName.hpp>\n#include <Threads\/Tasks\/ToRenderTasks.hpp>\n#include <Threads\/Commands\/ToRenderCommands.hpp>\n#include <Threads\/Tasks\/BasicTasks.hpp>\n#include <Context\/SdlContext.hh>\n#include <Utils\/Containers\/Vector.hpp>\n#include <Threads\/ThreadManager.hpp>\n#include <Core\/Engine.hh>\n#include <Context\/SdlContext.hh>\n#include <Render\/GeometryManagement\/Painting\/Painter.hh>\n#include <Render\/Pipelining\/Pipelines\/CustomPipeline\/BasicPipeline.hh>\n#include <Render\/Pipelining\/Pipelines\/CustomPipeline\/DeferredShading.hh>\n#include <Utils\/OpenGL.hh>\n#include <Utils\/Age_Imgui.hpp>\n#include <Render\/Properties\/Transformation.hh>\n#include <SpacePartitioning\/Ouptut\/RenderCamera.hh>\n#include <SpacePartitioning\/Ouptut\/RenderLight.hh>\n#include <SpacePartitioning\/Ouptut\/RenderPipeline.hh>\n#include <Utils\/Debug.hpp>\n#include <Render\/GeometryManagement\/SimpleGeometry.hpp>\n\nnamespace AGE\n{\n\tRenderThread::RenderThread()\n\t\t: Thread(AGE::Thread::ThreadType::Render)\n\t\t, _context(nullptr),\n\t\tpaintingManager(std::make_shared<PaintingManager>()),\n\t\tpipelines(2)\n\t{\n\t}\n\n\tRenderThread::~RenderThread()\n\t{}\n\n\tvoid RenderThread::_recompileShaders()\n\t{\n\t\t\/\/ to be sure that this function is only called in render thread\n\t\tAGE_ASSERT(GetThreadManager()->getCurrentThread() == (AGE::Thread*)GetRenderThread());\n\n\t\tfor (auto &e : pipelines)\n\t\t{\n\t\t\tif (!e)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\te->recompileShaders();\n\t\t}\n\t}\n\n\tvoid RenderThread::getQuadGeometry(Key<Vertices> &v, Key<Painter> &p)\n\t{\n\t\t\/\/ to be sure that this function is only called in render thread\n\t\tAGE_ASSERT(GetThreadManager()->getCurrentThread() == (AGE::Thread*)GetRenderThread());\n\n\t\tif (Quad::VerticesKey.isValid() && Quad::PainterKey.isValid())\n\t\t{\n\t\t\tv = Quad::VerticesKey;\n\t\t\tp = Quad::PainterKey;\n\t\t\treturn;\n\t\t}\n\n\t\tauto type = std::make_pair<GLenum, std::string>(GL_FLOAT_VEC4, \"position\");\n\t\tstd::vector<std::pair < GLenum, std::string > > types;\n\t\ttypes.push_back(type);\n\n\t\tif (!paintingManager->has_painter(types))\n\t\t{\n\t\t\tQuad::PainterKey = paintingManager->add_painter(std::move(types));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQuad::PainterKey = paintingManager->get_painter(types);\n\t\t}\n\t\tauto &painterPtr = paintingManager->get_painter(Quad::PainterKey);\n\n\t\tQuad::VerticesKey = painterPtr->add_vertices(Quad::Positions.size(), Quad::Indices.size());\n\t\tauto vertices = painterPtr->get_vertices(Quad::VerticesKey);\n\n\t\tvertices->set_data<glm::vec4>(Quad::Positions, std::string(\"position\"));\n\t\tvertices->set_indices(Quad::Indices);\n\n\t\tv = Quad::VerticesKey;\n\t\tp = Quad::PainterKey;\n\t}\n\n\tbool RenderThread::init()\n\t{\n\t\tregisterCallback<Tasks::Render::CreateRenderContext>([this](Tasks::Render::CreateRenderContext &msg)\n\t\t{\n\t\t\t_context = msg.engine->setInstance<SdlContext, IRenderContext>();\n\t\t\tif (!_context->init(0, 1280, 720, \"~AGE~ V0.00001 Demo\"))\n\t\t\t{\n\t\t\t\tmsg.setValue(false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpipelines[DEFERRED] = std::make_unique<DeferredShading>(_context->getScreenSize(), paintingManager);\n\t\t\tpipelines[BASIC] = std::make_unique<BasicPipeline>(paintingManager);\n\t\t\t_recompileShaders();\n\t\t\tmsg.setValue(true);\n\t\t});\n\n \t\tregisterCallback<Commands::ToRender::Flush>([&](Commands::ToRender::Flush& msg)\n\t\t{\n\t\t\t_context->swapContext();\n\t\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::ReloadShaders>([&](Tasks::Render::ReloadShaders& msg)\n\t\t{\n#ifdef AGE_DEBUG\n\t\t\t_recompileShaders();\n#else\n\t\t\tstd::cerr << \"Error : You cannot recompile shader at runtime. This feature is enabled only in debug mode\\n\";\n#endif\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::GetWindowSize>([&](Tasks::Render::GetWindowSize &msg)\n\t\t{\n\t\t\tmsg.setValue(_context->getScreenSize());\n\t\t});\n\n\t\tregisterCallback<Tasks::Render::SetWindowSize>([&](Tasks::Render::SetWindowSize& msg)\n\t\t{\n\t\t\t_context->setScreenSize(msg.size);\n\t\t});\n\n\t\tregisterCallback<Commands::ToRender::CopyDrawLists>([&](Commands::ToRender::CopyDrawLists& msg)\n\t\t{\n\t\t\t_drawlistPtr = msg.listContainer;\n\t\t});\n\n\t\tregisterCallback<Commands::ToRender::RenderDrawLists>([&](Commands::ToRender::RenderDrawLists& msg)\n\t\t{\n\t\t\tuint32_t pipelineIdx = 0;\n\n\t\t\tif (!_drawlistPtr) \/\/ nothing to draw\n\t\t\t\treturn;\n\t\t\tAGE_ASSERT(_drawlistPtr != nullptr);\n\n\t\t\tfor (auto &curPipeline : pipelines)\n\t\t\t{\n\t\t\t\tauto &drawlist = _drawlistPtr->container.cameras;\n\t\t\t\tfor (auto &curCamera : drawlist)\n\t\t\t\t{\n\t\t\t\t\tif (pipelineIdx < curCamera.pipelines.size()) {\n\t\t\t\t\t\tcurPipeline->render(curCamera.pipelines[pipelineIdx], curCamera.lights, curCamera.camInfos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++pipelineIdx;\n\t\t\t}\n\t\t\t_drawlistPtr = nullptr;\n\t\t});\n\n\t\tregisterSharedCallback<AGE::Tasks::Basic::BoolFunction>([&](AGE::Tasks::Basic::BoolFunction& msg)\n\t\t{\n\t\t\tmsg.setValue(msg.function());\n\t\t});\n\n\t\tregisterCallback<AGE::Tasks::Basic::VoidFunction>([&](AGE::Tasks::Basic::VoidFunction& msg)\n\t\t{\n\t\t\tif (msg.function)\n\t\t\t\tmsg.function();\n\t\t});\n\n\t\tregisterCallback<AGE::Tasks::Basic::Exit>([&](AGE::Tasks::Basic::Exit& msg)\n\t\t{\n\t\t\tAGE::CreateEngine()->deleteInstance<IRenderContext>();\n\t\t\tthis->_insideRun = false;\n\t\t});\n\n#ifdef USE_IMGUI\n\t\tregisterCallback<AGE::RenderImgui>([&](AGE::RenderImgui &msg)\n\t\t{\n\t\t\tAGE::Imgui::getInstance()->renderThreadRenderFn(msg.cmd_lists);\n\t\t});\n#endif\n\n\t\treturn true;\n\t}\n\n\tbool RenderThread::release()\n\t{\n\t\treturn true;\n\t}\n\n\tbool RenderThread::launch()\n\t{\n\t\tif (!init())\n\t\t\treturn false;\n\t\t_threadHandle = std::thread(&RenderThread::update, std::ref(*this));\n\t\treturn true;\n\t}\n\n\tbool RenderThread::stop()\n\t{\n\t\tgetQueue()->emplaceTask<Tasks::Basic::Exit>();\n\t\tif (_threadHandle.joinable())\n\t\t\t_threadHandle.join();\n\t\treturn true;\n\t}\n\n\tbool RenderThread::update()\n\t{\n\t\t\/*\n\t\t- Tant qu'il n'y a pas de command\n\t\t-> je pop des task\n\t\t- Une fois que j'ai mes commandes\n\t\t-> pour chacunes d'elles\n\t\t-> je regarde si c'est a moi de les traiter (ex : changement de scene)\n\t\t-> si ca n'est pas a moi de les traiter\n\t\t-> je les passe au render context actif\n\t\t-> si il n'y a pas de render context actif, c'est que j'ai fait une erreur, et j'assert dans ta face :D\n\t\t*\/\n\n\t\t_registerId();\n\n\t\t_run = true;\n\t\t_insideRun = true;\n\t\tDWORD threadId = GetThreadId(static_cast<HANDLE>(_threadHandle.native_handle()));\n\t\tSetThreadName(threadId, this->_name.c_str());\n\n\t\tTMQ::PtrQueue commands;\n\t\tTMQ::PtrQueue tasks;\n\t\tbool commandSuccess;\n\t\tbool taskSuccess;\n\n\t\tstd::chrono::system_clock::time_point waitStart;\n\t\tstd::chrono::system_clock::time_point waitEnd;\n\t\tstd::chrono::system_clock::time_point workStart;\n\t\tstd::chrono::system_clock::time_point workEnd;\n\n\t\twhile (_run && _insideRun)\n\t\t{\n\t\t\twaitStart = std::chrono::high_resolution_clock::now();\n\t\t\ttaskSuccess = commandSuccess = false;\n\t\t\tdo {\n\t\t\t\tif (_context)\n\t\t\t\t\t_context->refreshInputs();\n\t\t\t\tgetQueue()->getTaskAndCommandQueue(tasks, taskSuccess, commands, commandSuccess, TMQ::HybridQueue::Block);\n\t\t\t} while (!taskSuccess && !commandSuccess);\n\t\t\twaitEnd = std::chrono::high_resolution_clock::now();\n\t\t\tworkStart = std::chrono::high_resolution_clock::now();\n\t\t\tif (taskSuccess)\n\t\t\t{\n\t\t\t\twhile (!tasks.empty() && _insideRun)\n\t\t\t\t{\n\t\t\t\t\t\/\/pop all tasks\n\t\t\t\t\tauto task = tasks.front();\n\t\t\t\t\tauto success = execute(task); \/\/ we receive a task that we cannot treat\n\t\t\t\t\tAGE_ASSERT(success);\n\t\t\t\t\ttasks.pop();\n\t\t\t\t\ttaskCounter--;\n\t\t\t\t\tworkEnd = std::chrono::high_resolution_clock::now();\n\t\t\t\t\tconst std::size_t toWait = 33;\n\t\t\t\t\tconst std::size_t elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(workEnd - workStart).count();\n\t\t\t\t\tif (elapsed >= toWait)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << elapsed << \", \";\n\t\t\t\t\t\twhile (!tasks.empty() && _insideRun)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto task = tasks.front();\n\t\t\t\t\t\t\tgetQueue()->moveTask(task, tasks.getFrontSize());\n\t\t\t\t\t\t\ttasks.pop();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (commandSuccess)\n\t\t\t{\n\t\t\t\t\/\/ pop all commands\n\t\t\t\twhile (!commands.empty() && _insideRun)\n\t\t\t\t{\n\t\t\t\t\tauto command = commands.front();\n\t\t\t\t\tauto success = execute(command);\n\t\t\t\t\tAGE_ASSERT(success);\n\t\t\t\t\tcommands.pop();\n\t\t\t\t}\n\n\t\t\t\tworkEnd = std::chrono::high_resolution_clock::now();\n\t\t\t\tGetThreadManager()->updateThreadStatistics(this->_id\n\t\t\t\t\t, std::chrono::duration_cast<std::chrono::microseconds>(workEnd - workStart).count()\n\t\t\t\t\t, std::chrono::duration_cast<std::chrono::microseconds>(waitEnd - waitStart).count());\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Dataflow\/Serialization\/Network\/Importer\/NetworkIO.h>\n#include <Dataflow\/Serialization\/Network\/ModuleDescriptionSerialization.h>\n#include <Dataflow\/Serialization\/Network\/NetworkDescriptionSerialization.h>\n#include <Dataflow\/Serialization\/Network\/NetworkXMLSerializer.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include <Dataflow\/Network\/Network.h>\n#include <Dataflow\/Network\/ModuleInterface.h>\n#include <Dataflow\/Network\/ModuleStateInterface.h>\n#include <Dataflow\/Network\/ConnectionId.h>\n#include <Dataflow\/Network\/Tests\/MockNetwork.h>\n#include <Core\/Datatypes\/DenseMatrix.h>\n#include <Core\/Datatypes\/MatrixComparison.h>\n#include <Core\/Datatypes\/MatrixIO.h>\n#include <Modules\/Basic\/SendTestMatrix.h>\n#include <Modules\/Basic\/ReceiveTestMatrix.h>\n#include <Modules\/Math\/EvaluateLinearAlgebraUnary.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <Core\/Algorithms\/Math\/EvaluateLinearAlgebraUnaryAlgo.h>\n#include <Core\/Algorithms\/Math\/EvaluateLinearAlgebraBinaryAlgo.h>\n#include <Core\/Algorithms\/Math\/ReportMatrixInfo.h>\n#include <Dataflow\/Network\/Tests\/MockModuleState.h>\n#include <Dataflow\/State\/SimpleMapModuleState.h>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n#include <Dataflow\/Serialization\/Network\/XMLSerializer.h>\n#include <Dataflow\/Engine\/Scheduler\/DesktopExecutionStrategyFactory.h>\n#include <Core\/Algorithms\/Base\/AlgorithmVariableNames.h>\n#include <Testing\/Utils\/SCIRunUnitTests.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Modules::Basic;\nusing namespace SCIRun::Modules::Math;\nusing namespace SCIRun::Modules::Factory;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Dataflow::Networks::Mocks;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Dataflow::State;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::TestUtils;\n\n#include <stdexcept>\n#include <fstream>\n#include <boost\/assign.hpp>\n\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace boost::assign;\n\nTEST(LegacyNetworkFileImporterTests, CanLoadEmptyNetworkFile)\n{\n auto dtdpath = TestResources::rootDir() \/ \"Other\";\n LegacyNetworkIO lnio(dtdpath.string());;\n auto v4file1 = TestResources::rootDir() \/ \"Other\" \/ \"v4nets\" \/ \"empty.srn\";\n auto networkFile = lnio.load_net(v4file1.string());\n ASSERT_TRUE(networkFile != nullptr);\n\n EXPECT_EQ(0, networkFile->network.modules.size());\n EXPECT_EQ(0, networkFile->network.connections.size());\n EXPECT_EQ(0, networkFile->modulePositions.modulePositions.size());\n EXPECT_EQ(0, networkFile->moduleNotes.notes.size());\n EXPECT_EQ(0, networkFile->connectionNotes.notes.size());\n EXPECT_EQ(0, networkFile->moduleTags.tags.size());\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithSingleModuleNoState)\n{\n auto dtdpath = TestResources::rootDir() \/ \"Other\";\n LegacyNetworkIO lnio(dtdpath.string());\n auto v4file1 = TestResources::rootDir() \/ \"Other\" \/ \"v4nets\" \/ \"oneModule.srn\";\n auto networkFile = lnio.load_net(v4file1.string());\n ASSERT_TRUE(networkFile != nullptr);\n\n EXPECT_EQ(1, networkFile->network.modules.size());\n auto mod = *networkFile->network.modules.begin();\n EXPECT_EQ(\"m1\", mod.first); \/\/TODO: ID conversion??\n EXPECT_EQ(\"CreateLatVol\", mod.second.module.module_name_);\n EXPECT_EQ(\"NewField\", mod.second.module.category_name_);\n EXPECT_EQ(\"SCIRun\", mod.second.module.package_name_);\n \n EXPECT_EQ(0, networkFile->network.connections.size());\n\n EXPECT_EQ(1, networkFile->modulePositions.modulePositions.size());\n EXPECT_EQ(std::make_pair(289.0,151.0), networkFile->modulePositions.modulePositions.begin()->second);\n \n EXPECT_EQ(0, networkFile->moduleNotes.notes.size());\n EXPECT_EQ(0, networkFile->connectionNotes.notes.size());\n EXPECT_EQ(0, networkFile->moduleTags.tags.size());\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithSingleModuleWithState)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesNoConnections)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesOneConnection)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesTwoConnections)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithLotsOfObjects)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithModuleNotes)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithConnectionNotes)\n{\n FAIL() << \"todo\";\n}<commit_msg>Multiple modules are good<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Dataflow\/Serialization\/Network\/Importer\/NetworkIO.h>\n#include <Dataflow\/Serialization\/Network\/ModuleDescriptionSerialization.h>\n#include <Dataflow\/Serialization\/Network\/NetworkDescriptionSerialization.h>\n#include <Dataflow\/Serialization\/Network\/NetworkXMLSerializer.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include <Dataflow\/Network\/Network.h>\n#include <Dataflow\/Network\/ModuleInterface.h>\n#include <Dataflow\/Network\/ModuleStateInterface.h>\n#include <Dataflow\/Network\/ConnectionId.h>\n#include <Dataflow\/Network\/Tests\/MockNetwork.h>\n#include <Core\/Datatypes\/DenseMatrix.h>\n#include <Core\/Datatypes\/MatrixComparison.h>\n#include <Core\/Datatypes\/MatrixIO.h>\n#include <Modules\/Basic\/SendTestMatrix.h>\n#include <Modules\/Basic\/ReceiveTestMatrix.h>\n#include <Modules\/Math\/EvaluateLinearAlgebraUnary.h>\n#include <Modules\/Factory\/HardCodedModuleFactory.h>\n#include <Core\/Algorithms\/Math\/EvaluateLinearAlgebraUnaryAlgo.h>\n#include <Core\/Algorithms\/Math\/EvaluateLinearAlgebraBinaryAlgo.h>\n#include <Core\/Algorithms\/Math\/ReportMatrixInfo.h>\n#include <Dataflow\/Network\/Tests\/MockModuleState.h>\n#include <Dataflow\/State\/SimpleMapModuleState.h>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n#include <Dataflow\/Serialization\/Network\/XMLSerializer.h>\n#include <Dataflow\/Engine\/Scheduler\/DesktopExecutionStrategyFactory.h>\n#include <Core\/Algorithms\/Base\/AlgorithmVariableNames.h>\n#include <Testing\/Utils\/SCIRunUnitTests.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Modules::Basic;\nusing namespace SCIRun::Modules::Math;\nusing namespace SCIRun::Modules::Factory;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Dataflow::Networks::Mocks;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Dataflow::State;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::TestUtils;\n\n#include <stdexcept>\n#include <fstream>\n#include <boost\/assign.hpp>\n\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace boost::assign;\n\nTEST(LegacyNetworkFileImporterTests, CanLoadEmptyNetworkFile)\n{\n auto dtdpath = TestResources::rootDir() \/ \"Other\";\n LegacyNetworkIO lnio(dtdpath.string());;\n auto v4file1 = TestResources::rootDir() \/ \"Other\" \/ \"v4nets\" \/ \"empty.srn\";\n auto networkFile = lnio.load_net(v4file1.string());\n ASSERT_TRUE(networkFile != nullptr);\n\n EXPECT_EQ(0, networkFile->network.modules.size());\n EXPECT_EQ(0, networkFile->network.connections.size());\n EXPECT_EQ(0, networkFile->modulePositions.modulePositions.size());\n EXPECT_EQ(0, networkFile->moduleNotes.notes.size());\n EXPECT_EQ(0, networkFile->connectionNotes.notes.size());\n EXPECT_EQ(0, networkFile->moduleTags.tags.size());\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithSingleModuleNoState)\n{\n auto dtdpath = TestResources::rootDir() \/ \"Other\";\n LegacyNetworkIO lnio(dtdpath.string());\n auto v4file1 = TestResources::rootDir() \/ \"Other\" \/ \"v4nets\" \/ \"oneModule.srn\";\n auto networkFile = lnio.load_net(v4file1.string());\n ASSERT_TRUE(networkFile != nullptr);\n\n EXPECT_EQ(1, networkFile->network.modules.size());\n auto mod = *networkFile->network.modules.begin();\n EXPECT_EQ(\"m1\", mod.first); \/\/TODO: ID conversion??\n EXPECT_EQ(\"CreateLatVol\", mod.second.module.module_name_);\n EXPECT_EQ(\"NewField\", mod.second.module.category_name_);\n EXPECT_EQ(\"SCIRun\", mod.second.module.package_name_);\n\n EXPECT_EQ(0, networkFile->network.connections.size());\n\n EXPECT_EQ(1, networkFile->modulePositions.modulePositions.size());\n EXPECT_EQ(std::make_pair(289.0,151.0), networkFile->modulePositions.modulePositions.begin()->second);\n\n EXPECT_EQ(0, networkFile->moduleNotes.notes.size());\n EXPECT_EQ(0, networkFile->connectionNotes.notes.size());\n EXPECT_EQ(0, networkFile->moduleTags.tags.size());\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithSingleModuleWithState)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesNoConnections)\n{\n auto dtdpath = TestResources::rootDir() \/ \"Other\";\n LegacyNetworkIO lnio(dtdpath.string());\n auto v4file1 = TestResources::rootDir() \/ \"Other\" \/ \"v4nets\" \/ \"threeModulesNoConnections.srn\";\n auto networkFile = lnio.load_net(v4file1.string());\n ASSERT_TRUE(networkFile != nullptr);\n\n EXPECT_EQ(3, networkFile->network.modules.size());\n auto modIter = networkFile->network.modules.begin();\n EXPECT_EQ(\"m1\", modIter->first); \/\/TODO: ID conversion??\n EXPECT_EQ(\"ComputeSVD\", modIter->second.module.module_name_);\n EXPECT_EQ(\"Math\", modIter->second.module.category_name_);\n EXPECT_EQ(\"SCIRun\", modIter->second.module.package_name_);\n ++modIter;\n EXPECT_EQ(\"m2\", modIter->first); \/\/TODO: ID conversion??\n EXPECT_EQ(\"CreateLatVol\", modIter->second.module.module_name_);\n EXPECT_EQ(\"NewField\", modIter->second.module.category_name_);\n EXPECT_EQ(\"SCIRun\", modIter->second.module.package_name_);\n ++modIter;\n EXPECT_EQ(\"m3\", modIter->first); \/\/TODO: ID conversion??\n EXPECT_EQ(\"ShowField\", modIter->second.module.module_name_);\n EXPECT_EQ(\"Visualization\", modIter->second.module.category_name_);\n EXPECT_EQ(\"SCIRun\", modIter->second.module.package_name_);\n\n EXPECT_EQ(0, networkFile->network.connections.size());\n\n EXPECT_EQ(3, networkFile->modulePositions.modulePositions.size());\n auto posIter = networkFile->modulePositions.modulePositions.begin();\n EXPECT_EQ(std::make_pair(357.0,134.0), posIter->second); ++posIter;\n EXPECT_EQ(std::make_pair(304.0,258.0), posIter->second); ++posIter;\n EXPECT_EQ(std::make_pair(386.0,376.0), posIter->second);\n\n EXPECT_EQ(0, networkFile->moduleNotes.notes.size());\n EXPECT_EQ(0, networkFile->connectionNotes.notes.size());\n EXPECT_EQ(0, networkFile->moduleTags.tags.size());\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesOneConnection)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithTwoModulesTwoConnections)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithLotsOfObjects)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithModuleNotes)\n{\n FAIL() << \"todo\";\n}\n\nTEST(LegacyNetworkFileImporterTests, CanLoadNetworkFileWithConnectionNotes)\n{\n FAIL() << \"todo\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <ros\/ros.h>\n#include <pluginlib\/class_list_macros.h>\n#include <nodelet\/nodelet.h>\n\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl_conversions\/pcl_conversions.h>\n\n#include <tf\/transform_listener.h>\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/Image.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <sensor_msgs\/CameraInfo.h>\n#include <stereo_msgs\/DisparityImage.h>\n\n#include <image_transport\/image_transport.h>\n#include <image_transport\/subscriber_filter.h>\n\n#include <image_geometry\/pinhole_camera_model.h>\n\n#include <message_filters\/sync_policies\/approximate_time.h>\n#include <message_filters\/subscriber.h>\n\n#include <cv_bridge\/cv_bridge.h>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <rtabmap_ros\/MsgConversion.h>\n\n#include \"rtabmap\/core\/util3d.h\"\n#include \"rtabmap\/core\/util3d_filtering.h\"\n#include \"rtabmap\/core\/util3d_mapping.h\"\n#include \"rtabmap\/core\/util3d_transforms.h\"\n\nnamespace rtabmap_ros\n{\n\nclass ObstaclesDetection : public nodelet::Nodelet\n{\npublic:\n\tObstaclesDetection() :\n\t\tframeId_(\"base_link\"),\n\t\tnormalEstimationRadius_(0.05),\n\t\tgroundNormalAngle_(M_PI_4),\n\t\tminClusterSize_(20),\n\t\tmaxFloorHeight_(-1),\n\t\tmaxObstaclesHeight_(1.5),\n\t\twaitForTransform_(false),\n\t\tsimpleSegmentation_(false)\n\t{}\n\n\tvirtual ~ObstaclesDetection()\n\t{}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 10;\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\tpnh.param(\"normal_estimation_radius\", normalEstimationRadius_, normalEstimationRadius_);\n\t\tpnh.param(\"ground_normal_angle\", groundNormalAngle_, groundNormalAngle_);\n\t\tpnh.param(\"min_cluster_size\", minClusterSize_, minClusterSize_);\n\t\tpnh.param(\"max_obstacles_height\", maxObstaclesHeight_, maxObstaclesHeight_);\n\t\tpnh.param(\"max_floor_height\", maxFloorHeight_, maxFloorHeight_);\n\t\tpnh.param(\"wait_for_transform\", waitForTransform_, waitForTransform_);\n\t\tpnh.param(\"simple_segmentation\", simpleSegmentation_, simpleSegmentation_);\n\n\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &ObstaclesDetection::callback, this);\n\n\t\tgroundPub_ = nh.advertise<sensor_msgs::PointCloud2>(\"ground\", 1);\n\t\tobstaclesPub_ = nh.advertise<sensor_msgs::PointCloud2>(\"obstacles\", 1);\n\n\t\tthis->_lastFrameTime = ros::Time::now();\n\t}\n\n\n\n\tvoid callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)\n\t\t{\n\t\t\t\/\/ no one wants the results\n\t\t\treturn;\n\t\t}\n\n\t\tROS_ERROR(\"1111111111111111111111\");\n\n\n\t\trtabmap::Transform localTransform;\n\t\ttry\n\t\t{\n\t\t\tif(waitForTransform_)\n\t\t\t{\n\t\t\t\tif(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Could not get transform from %s to %s after 1 second!\", frameId_.c_str(), cloudMsg->header.frame_id.c_str());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tROS_ERROR(\"2222222222222222222222222222222\");\n\n\t\t\ttf::StampedTransform tmp;\n\t\t\ttfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);\n\t\t\tlocalTransform = rtabmap_ros::transformFromTF(tmp);\n\t\t}\n\t\tcatch(tf::TransformException & ex)\n\t\t{\n\t\t\tROS_ERROR(\"%s\",ex.what());\n\t\t\treturn;\n\t\t}\n\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr originalCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tpcl::fromROSMsg(*cloudMsg, *originalCloud);\n\t\tif(originalCloud->size() == 0)\n\t\t{\n\t\t\tROS_ERROR(\"Recieved empty point cloud!\");\n\t\t\treturn;\n\t\t}\n\t\toriginalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);\n\n\t\tROS_ERROR(\"3333333333333333333333333\");\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr hypotheticalGroundCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\thypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", std::numeric_limits<int>::min(), maxFloorHeight_);\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tobstaclesCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", maxFloorHeight_, maxObstaclesHeight_);\n\n\t\tros::Time lasttime = ros::Time::now();\n\n\t\tpcl::IndicesPtr ground, obstacles;\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr groundCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\n\t\tif (!simpleSegmentation_){\n\t\t\tROS_ERROR(\"44444444444444444444444444444\");\n\n\t\t\trtabmap::util3d::segmentObstaclesFromGround<pcl::PointXYZ>(hypotheticalGroundCloud,\n\t\t\t\t\tground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);\n\n\t\t\tif(ground.get() && ground->size())\n\t\t\t{\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);\n\t\t\t}\n\t\t\tif(obstacles.get() && obstacles->size())\n\t\t\t{\n\t\t\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesNearFloorCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);\n\t\t\t\t*obstaclesCloud += *obstaclesNearFloorCloud;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tROS_ERROR(\"555555555555555555555555\");\n\t\t\tgroundCloud = hypotheticalGroundCloud;\n\t\t}\n\n\n\t\tif(groundPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*groundCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tgroundPub_.publish(rosCloud);\n\t\t}\n\n\t\tif(obstaclesPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*obstaclesCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tobstaclesPub_.publish(rosCloud);\n\t\t}\n\n\t\tros::Time curtime = ros::Time::now();\n\n\t\tros::Duration process_duration = curtime - lasttime;\n\t\tros::Duration between_frames = curtime - this->_lastFrameTime;\n\t\tthis->_lastFrameTime = curtime;\n\t\tstd::stringstream buffer;\n\t\tbuffer << \"cloud=\" << originalCloud->size() << \" ground=\" << hypotheticalGroundCloud->size() << \" floor=\" << ground->size() << \" obst=\" << obstacles->size();\n\t\tbuffer << \" t=\" << process_duration.toSec() << \"s; \" << (1.\/between_frames.toSec()) << \"Hz\";\n\t\t\/\/ROS_ERROR(\"3%s: %s\", this->getName().c_str(), buffer.str().c_str());\n\n\t}\n\nprivate:\n\tstd::string frameId_;\n\tdouble normalEstimationRadius_;\n\tdouble groundNormalAngle_;\n\tint minClusterSize_;\n\tdouble maxObstaclesHeight_;\n\tdouble maxFloorHeight_;\n\tbool waitForTransform_;\n\tbool simpleSegmentation_;\n\n\ttf::TransformListener tfListener_;\n\n\tros::Publisher groundPub_;\n\tros::Publisher obstaclesPub_;\n\n\tros::Subscriber cloudSub_;\n\tros::Time _lastFrameTime;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);\n}\n\n<commit_msg>Comment for debugging<commit_after>\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <ros\/ros.h>\n#include <pluginlib\/class_list_macros.h>\n#include <nodelet\/nodelet.h>\n\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl_conversions\/pcl_conversions.h>\n\n#include <tf\/transform_listener.h>\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/Image.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <sensor_msgs\/CameraInfo.h>\n#include <stereo_msgs\/DisparityImage.h>\n\n#include <image_transport\/image_transport.h>\n#include <image_transport\/subscriber_filter.h>\n\n#include <image_geometry\/pinhole_camera_model.h>\n\n#include <message_filters\/sync_policies\/approximate_time.h>\n#include <message_filters\/subscriber.h>\n\n#include <cv_bridge\/cv_bridge.h>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <rtabmap_ros\/MsgConversion.h>\n\n#include \"rtabmap\/core\/util3d.h\"\n#include \"rtabmap\/core\/util3d_filtering.h\"\n#include \"rtabmap\/core\/util3d_mapping.h\"\n#include \"rtabmap\/core\/util3d_transforms.h\"\n\nnamespace rtabmap_ros\n{\n\nclass ObstaclesDetection : public nodelet::Nodelet\n{\npublic:\n\tObstaclesDetection() :\n\t\tframeId_(\"base_link\"),\n\t\tnormalEstimationRadius_(0.05),\n\t\tgroundNormalAngle_(M_PI_4),\n\t\tminClusterSize_(20),\n\t\tmaxFloorHeight_(-1),\n\t\tmaxObstaclesHeight_(1.5),\n\t\twaitForTransform_(false),\n\t\tsimpleSegmentation_(false)\n\t{}\n\n\tvirtual ~ObstaclesDetection()\n\t{}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 10;\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\tpnh.param(\"normal_estimation_radius\", normalEstimationRadius_, normalEstimationRadius_);\n\t\tpnh.param(\"ground_normal_angle\", groundNormalAngle_, groundNormalAngle_);\n\t\tpnh.param(\"min_cluster_size\", minClusterSize_, minClusterSize_);\n\t\tpnh.param(\"max_obstacles_height\", maxObstaclesHeight_, maxObstaclesHeight_);\n\t\tpnh.param(\"max_floor_height\", maxFloorHeight_, maxFloorHeight_);\n\t\tpnh.param(\"wait_for_transform\", waitForTransform_, waitForTransform_);\n\t\tpnh.param(\"simple_segmentation\", simpleSegmentation_, simpleSegmentation_);\n\n\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &ObstaclesDetection::callback, this);\n\n\t\tgroundPub_ = nh.advertise<sensor_msgs::PointCloud2>(\"ground\", 1);\n\t\tobstaclesPub_ = nh.advertise<sensor_msgs::PointCloud2>(\"obstacles\", 1);\n\n\t\tthis->_lastFrameTime = ros::Time::now();\n\t}\n\n\n\n\tvoid callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)\n\t\t{\n\t\t\t\/\/ no one wants the results\n\t\t\treturn;\n\t\t}\n\n\t\trtabmap::Transform localTransform;\n\t\ttry\n\t\t{\n\t\t\tif(waitForTransform_)\n\t\t\t{\n\t\t\t\tif(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Could not get transform from %s to %s after 1 second!\", frameId_.c_str(), cloudMsg->header.frame_id.c_str());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tROS_ERROR(\"2222222222222222222222222222222\");\n\n\t\t\ttf::StampedTransform tmp;\n\t\t\ttfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);\n\t\t\tlocalTransform = rtabmap_ros::transformFromTF(tmp);\n\t\t}\n\t\tcatch(tf::TransformException & ex)\n\t\t{\n\t\t\tROS_ERROR(\"%s\",ex.what());\n\t\t\treturn;\n\t\t}\n\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr originalCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tpcl::fromROSMsg(*cloudMsg, *originalCloud);\n\t\tif(originalCloud->size() == 0)\n\t\t{\n\t\t\tROS_ERROR(\"Recieved empty point cloud!\");\n\t\t\treturn;\n\t\t}\n\t\toriginalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);\n\n\t\tROS_ERROR(\"3333333333333333333333333\");\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr hypotheticalGroundCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\thypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", std::numeric_limits<int>::min(), maxFloorHeight_);\n\n\t\tROS_ERROR(\"AAAa3333333333333333333333333\");\n\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\tobstaclesCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", maxFloorHeight_, maxObstaclesHeight_);\n\n\t\tROS_ERROR(\"BBBb3333333333333333333333333\");\n\n\t\tros::Time lasttime = ros::Time::now();\n\n\t\tpcl::IndicesPtr ground, obstacles;\n\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr groundCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\n\t\tif (!simpleSegmentation_){\n\t\t\tROS_ERROR(\"44444444444444444444444444444\");\n\n\t\t\trtabmap::util3d::segmentObstaclesFromGround<pcl::PointXYZ>(hypotheticalGroundCloud,\n\t\t\t\t\tground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);\n\n\t\t\tif(ground.get() && ground->size())\n\t\t\t{\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);\n\t\t\t}\n\t\t\tif(obstacles.get() && obstacles->size())\n\t\t\t{\n\t\t\t\tpcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesNearFloorCloud(new pcl::PointCloud<pcl::PointXYZ>);\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);\n\t\t\t\t*obstaclesCloud += *obstaclesNearFloorCloud;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tROS_ERROR(\"555555555555555555555555\");\n\t\t\tgroundCloud = hypotheticalGroundCloud;\n\t\t}\n\n\n\t\tif(groundPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*groundCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tgroundPub_.publish(rosCloud);\n\t\t}\n\n\t\tif(obstaclesPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*obstaclesCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tobstaclesPub_.publish(rosCloud);\n\t\t}\n\n\t\tros::Time curtime = ros::Time::now();\n\n\t\tros::Duration process_duration = curtime - lasttime;\n\t\tros::Duration between_frames = curtime - this->_lastFrameTime;\n\t\tthis->_lastFrameTime = curtime;\n\t\tstd::stringstream buffer;\n\t\tbuffer << \"cloud=\" << originalCloud->size() << \" ground=\" << hypotheticalGroundCloud->size() << \" floor=\" << ground->size() << \" obst=\" << obstacles->size();\n\t\tbuffer << \" t=\" << process_duration.toSec() << \"s; \" << (1.\/between_frames.toSec()) << \"Hz\";\n\t\t\/\/ROS_ERROR(\"3%s: %s\", this->getName().c_str(), buffer.str().c_str());\n\n\t}\n\nprivate:\n\tstd::string frameId_;\n\tdouble normalEstimationRadius_;\n\tdouble groundNormalAngle_;\n\tint minClusterSize_;\n\tdouble maxObstaclesHeight_;\n\tdouble maxFloorHeight_;\n\tbool waitForTransform_;\n\tbool simpleSegmentation_;\n\n\ttf::TransformListener tfListener_;\n\n\tros::Publisher groundPub_;\n\tros::Publisher obstaclesPub_;\n\n\tros::Subscriber cloudSub_;\n\tros::Time _lastFrameTime;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef <<<headerguard>>>\n#define <<<headerguard>>>\n\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stddef.h>\n#include <sstream>\n#include <iostream>\n\n#include \"ComponentEssentials.h\"\n#include \"ComponentUtilities.h\"\n\n#include \"FMI\/fmi_import_context.h\"\n#include \"FMI1\/fmi1_import.h\"\n#include \"FMI2\/fmi2_import.h\"\n#include \"JM\/jm_portability.h\"\n\n\nvoid localLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { }\n\nnamespace hopsan {\n\n\/\/!\n\/\/! @brief\n\/\/! @ingroup HydraulicComponents\n\/\/!\nclass <<<className>>> : public ComponentQ\n{\n\nprivate:\n \/\/Node data pointers\n <<<localvars>>>\n\n fmi2_callback_functions_t callBackFunctions;\n jm_callbacks callbacks;\n fmi_import_context_t* context;\n fmi_version_enu_t version;\n jm_status_enu_t status;\n fmi2_status_t fmistatus;\n int k;\n\n double tlast;\n\n fmi2_real_t hcur;\n size_t n_states;\n size_t n_event_indicators;\n fmi2_real_t* states;\n fmi2_real_t* states_der;\n fmi2_real_t* event_indicators;\n fmi2_real_t* event_indicators_prev;\n fmi2_boolean_t callEventUpdate;\n fmi2_boolean_t terminateSimulation;\n fmi2_boolean_t toleranceControlled;\n fmi2_real_t relativeTolerance;\n fmi2_event_info_t eventInfo;\n\n fmi2_import_t* fmu;\n\npublic:\n static Component *Creator()\n {\n return new <<<className>>>();\n }\n\n void configure()\n {\n \/\/Add constants\n <<<addconstants>>>\n\n \/\/Add input variables\n <<<addinputs>>>\n\n \/\/Add output variables\n <<<addoutputs>>>\n\n \/\/Add ports\n <<<addports>>>\n }\n\n void initialize()\n {\n <<<setnodedatapointers>>>\n\n addInfoMessage(\"Initializing FMU 2.0 import\");\n\n fmi2_boolean_t terminateSimulation = fmi2_false;\n fmi2_boolean_t toleranceControlled = fmi2_true;\n fmi2_real_t relativeTolerance = 0.001;\n\n const char* FMUPath = \"<<<fmupath>>>\";\n const char* tmpPath = \"<<<temppath>>>\";\n\n callbacks.malloc = malloc;\n callbacks.calloc = calloc;\n callbacks.realloc = realloc;\n callbacks.free = free;\n callbacks.logger = localLogger;\n callbacks.log_level = jm_log_level_debug;\n callbacks.context = 0;\n\n context = fmi_import_allocate_context(&callbacks);\n\n version = fmi_import_get_fmi_version(context, FMUPath, tmpPath);\n\n if(version != fmi_version_2_0_enu)\n {\n addErrorMessage(\"The code only supports version 2.0\\n\");\n stopSimulation();\n return;\n }\n\n fmu = fmi2_import_parse_xml(context, tmpPath, 0);\n\n if(!fmu)\n {\n addErrorMessage(\"Error parsing XML, exiting\\n\");\n stopSimulation();\n return;\n }\n\n if(fmi2_import_get_fmu_kind(fmu) != fmi2_fmu_kind_me)\n {\n addErrorMessage(\"Only ME 2.0 is supported by this code\\n\");\n stopSimulation();\n return;\n }\n\n callBackFunctions.logger = fmi2_log_forwarding;\n callBackFunctions.allocateMemory = calloc;\n callBackFunctions.freeMemory = free;\n callBackFunctions.componentEnvironment = fmu;\n\n status = fmi2_import_create_dllfmu(fmu, fmi2_fmu_kind_me, &callBackFunctions);\n if (status == jm_status_error)\n {\n std::stringstream ss;\n ss << \"Could not create the DLL loading mechanism(C-API) (error: \" << fmi2_import_get_last_error(fmu) << \").\";\n addErrorMessage(ss.str().c_str());\n stopSimulation();\n return;\n }\n\n n_states = fmi2_import_get_number_of_continuous_states(fmu);\n n_event_indicators = fmi2_import_get_number_of_event_indicators(fmu);\n\n states = new fmi2_real_t[n_states];\n states_der = new fmi2_real_t[n_states];\n event_indicators = new fmi2_real_t[n_event_indicators];\n event_indicators_prev = new fmi2_real_t[n_event_indicators];\n\n \/\/Instantiate FMU\n fmi2_string_t instanceName = \"Test CS model instance\";\n fmi2_string_t fmuLocation = \"\";\n fmi2_boolean_t visible = fmi2_false;\n jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName, fmi2_cosimulation, fmuLocation, visible);\n if (jmstatus == jm_status_error)\n {\n addErrorMessage(\"fmi2_import_instantiate() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Setup experiment\n fmi2_real_t relativeTol = 1e-4;\n fmistatus = fmi2_import_setup_experiment(fmu, fmi2_true, relativeTol, mTime, fmi2_false, 10);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_setup_experiment() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Enter initialization mode\n fmistatus = fmi2_import_enter_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_enter_initialization_mode() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Set parameters\n double value;\n fmi2_value_reference_t vr;\n>>>setpars>>> vr = <<<vr>>>;\n value = <<<var>>>;\n fmistatus = fmi2_import_set_real(fmu, &vr, 1, &value);\n <<<setpars<<<\n\n \/\/Exit initialization mode\n fmistatus = fmi2_import_exit_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_exit_initialization_mode() failed!\");\n stopSimulation();\n return;\n }\n\n callEventUpdate = fmi2_false;\n\n eventInfo.newDiscreteStatesNeeded = fmi2_false;\n eventInfo.terminateSimulation = fmi2_false;\n eventInfo.nominalsOfContinuousStatesChanged = fmi2_false;\n eventInfo.valuesOfContinuousStatesChanged = fmi2_true;\n eventInfo.nextEventTimeDefined = fmi2_false;\n eventInfo.nextEventTime = -0.0;\n\n \/* fmiExitInitializationMode leaves FMU in event mode *\/\n do_event_iteration(fmu, &eventInfo);\n fmi2_import_enter_continuous_time_mode(fmu);\n\n fmistatus = fmi2_import_get_continuous_states(fmu, states, n_states);\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Read inputs\n fmi2_value_reference_t vr;\n double value;\n>>>readvars>>> vr = <<<vr>>>;\n value = (*<<<var>>>);\n fmistatus = fmi2_import_set_real(fmu, &vr, 1, &value);\n <<<readvars<<<\n\n double tStop = mTime+mTimestep;\n\n while(mTime < tStop)\n {\n size_t k;\n fmi2_real_t tlast;\n int zero_crossing_event = 0;\n\n fmistatus = fmi2_import_set_time(fmu, mTime);\n\n { \/* Swap event_indicators and event_indicators_prev so that we can get new indicators *\/\n fmi2_real_t *temp = event_indicators;\n event_indicators = event_indicators_prev;\n event_indicators_prev = temp;\n }\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n\n \/* Check if an event indicator has triggered *\/\n for (k = 0; k < n_event_indicators; k++)\n {\n if ((event_indicators[k] > 0) != (event_indicators_prev[k] > 0))\n {\n zero_crossing_event = 1;\n break;\n }\n }\n\n \/* Handle any events *\/\n if (callEventUpdate || zero_crossing_event ||\n (eventInfo.nextEventTimeDefined && mTime == eventInfo.nextEventTime))\n {\n fmistatus = fmi2_import_enter_event_mode(fmu);\n do_event_iteration(fmu, &eventInfo);\n fmistatus = fmi2_import_enter_continuous_time_mode(fmu);\n\n fmistatus = fmi2_import_get_continuous_states(fmu, states, n_states);\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n }\n\n \/* Calculate next time step *\/\n tlast = mTime;\n mTime = tStop;\n if (eventInfo.nextEventTimeDefined && (mTime >= eventInfo.nextEventTime))\n {\n mTime = eventInfo.nextEventTime;\n }\n hcur = mTime - tlast;\n\n \/* Integrate a step *\/\n fmistatus = fmi2_import_get_derivatives(fmu, states_der, n_states);\n for (k = 0; k < n_states; k++)\n {\n states[k] = states[k] + hcur*states_der[k];\n }\n\n \/* Set states *\/\n fmistatus = fmi2_import_set_continuous_states(fmu, states, n_states);\n\n \/* Step is complete *\/\n fmistatus = fmi2_import_completed_integrator_step(fmu, fmi2_true, &callEventUpdate,\n &terminateSimulation);\n }\n\n\n double rValue;\n>>>writevars>>> vr = <<<vr>>>;\n fmistatus = fmi2_import_get_real(fmu, &vr, 1, &rValue);\n (*<<<var>>>) = rValue;\n <<<writevars<<<\n }\n\n\n void finalize()\n {\n fmistatus = fmi2_import_terminate(fmu);\n\n fmi2_import_free_instance(fmu);\n\n fmi2_import_destroy_dllfmu(fmu);\n\n fmi2_import_free(fmu);\n fmi_import_free_context(context);\n\n addInfoMessage(\"Everything seems to be OK since you got this far=)!\");\n }\n\n\n void do_event_iteration(fmi2_import_t *fmu, fmi2_event_info_t *eventInfo)\n {\n eventInfo->newDiscreteStatesNeeded = fmi2_true;\n eventInfo->terminateSimulation = fmi2_false;\n while (eventInfo->newDiscreteStatesNeeded && !eventInfo->terminateSimulation)\n {\n fmi2_import_new_discrete_states(fmu, eventInfo);\n }\n }\n};\n}\n\n#endif\n<commit_msg>Fixed issue with timestep size for integration in FMI for model exchange. Related to #1366.<commit_after>#ifndef <<<headerguard>>>\n#define <<<headerguard>>>\n\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stddef.h>\n#include <sstream>\n#include <iostream>\n\n#include \"ComponentEssentials.h\"\n#include \"ComponentUtilities.h\"\n\n#include \"FMI\/fmi_import_context.h\"\n#include \"FMI1\/fmi1_import.h\"\n#include \"FMI2\/fmi2_import.h\"\n#include \"JM\/jm_portability.h\"\n\n\nvoid localLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { }\n\nnamespace hopsan {\n\n\/\/!\n\/\/! @brief\n\/\/! @ingroup HydraulicComponents\n\/\/!\nclass <<<className>>> : public ComponentQ\n{\n\nprivate:\n \/\/Node data pointers\n <<<localvars>>>\n\n fmi2_callback_functions_t callBackFunctions;\n jm_callbacks callbacks;\n fmi_import_context_t* context;\n fmi_version_enu_t version;\n jm_status_enu_t status;\n fmi2_status_t fmistatus;\n int k;\n\n double tlast;\n\n fmi2_real_t hcur;\n size_t n_states;\n size_t n_event_indicators;\n fmi2_real_t* states;\n fmi2_real_t* states_der;\n fmi2_real_t* event_indicators;\n fmi2_real_t* event_indicators_prev;\n fmi2_boolean_t callEventUpdate;\n fmi2_boolean_t terminateSimulation;\n fmi2_boolean_t toleranceControlled;\n fmi2_real_t relativeTolerance;\n fmi2_event_info_t eventInfo;\n\n fmi2_import_t* fmu;\n\npublic:\n static Component *Creator()\n {\n return new <<<className>>>();\n }\n\n void configure()\n {\n \/\/Add constants\n <<<addconstants>>>\n\n \/\/Add input variables\n <<<addinputs>>>\n\n \/\/Add output variables\n <<<addoutputs>>>\n\n \/\/Add ports\n <<<addports>>>\n }\n\n void initialize()\n {\n <<<setnodedatapointers>>>\n\n addInfoMessage(\"Initializing FMU 2.0 import\");\n\n fmi2_boolean_t terminateSimulation = fmi2_false;\n fmi2_boolean_t toleranceControlled = fmi2_true;\n fmi2_real_t relativeTolerance = 0.001;\n\n const char* FMUPath = \"<<<fmupath>>>\";\n const char* tmpPath = \"<<<temppath>>>\";\n\n callbacks.malloc = malloc;\n callbacks.calloc = calloc;\n callbacks.realloc = realloc;\n callbacks.free = free;\n callbacks.logger = localLogger;\n callbacks.log_level = jm_log_level_debug;\n callbacks.context = 0;\n\n context = fmi_import_allocate_context(&callbacks);\n\n version = fmi_import_get_fmi_version(context, FMUPath, tmpPath);\n\n if(version != fmi_version_2_0_enu)\n {\n addErrorMessage(\"The code only supports version 2.0\\n\");\n stopSimulation();\n return;\n }\n\n fmu = fmi2_import_parse_xml(context, tmpPath, 0);\n\n if(!fmu)\n {\n addErrorMessage(\"Error parsing XML, exiting\\n\");\n stopSimulation();\n return;\n }\n\n if(fmi2_import_get_fmu_kind(fmu) != fmi2_fmu_kind_me)\n {\n addErrorMessage(\"Only ME 2.0 is supported by this code\\n\");\n stopSimulation();\n return;\n }\n\n callBackFunctions.logger = fmi2_log_forwarding;\n callBackFunctions.allocateMemory = calloc;\n callBackFunctions.freeMemory = free;\n callBackFunctions.componentEnvironment = fmu;\n\n status = fmi2_import_create_dllfmu(fmu, fmi2_fmu_kind_me, &callBackFunctions);\n if (status == jm_status_error)\n {\n std::stringstream ss;\n ss << \"Could not create the DLL loading mechanism(C-API) (error: \" << fmi2_import_get_last_error(fmu) << \").\";\n addErrorMessage(ss.str().c_str());\n stopSimulation();\n return;\n }\n\n n_states = fmi2_import_get_number_of_continuous_states(fmu);\n n_event_indicators = fmi2_import_get_number_of_event_indicators(fmu);\n\n states = new fmi2_real_t[n_states];\n states_der = new fmi2_real_t[n_states];\n event_indicators = new fmi2_real_t[n_event_indicators];\n event_indicators_prev = new fmi2_real_t[n_event_indicators];\n\n \/\/Instantiate FMU\n fmi2_string_t instanceName = \"Test CS model instance\";\n fmi2_string_t fmuLocation = \"\";\n fmi2_boolean_t visible = fmi2_false;\n jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName, fmi2_cosimulation, fmuLocation, visible);\n if (jmstatus == jm_status_error)\n {\n addErrorMessage(\"fmi2_import_instantiate() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Setup experiment\n fmi2_real_t relativeTol = 1e-4;\n fmistatus = fmi2_import_setup_experiment(fmu, fmi2_true, relativeTol, mTime, fmi2_false, 10);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_setup_experiment() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Enter initialization mode\n fmistatus = fmi2_import_enter_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_enter_initialization_mode() failed!\");\n stopSimulation();\n return;\n }\n\n \/\/Set parameters\n double value;\n fmi2_value_reference_t vr;\n>>>setpars>>> vr = <<<vr>>>;\n value = <<<var>>>;\n fmistatus = fmi2_import_set_real(fmu, &vr, 1, &value);\n <<<setpars<<<\n\n \/\/Exit initialization mode\n fmistatus = fmi2_import_exit_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok)\n {\n addErrorMessage(\"fmi2_import_exit_initialization_mode() failed!\");\n stopSimulation();\n return;\n }\n\n callEventUpdate = fmi2_false;\n\n eventInfo.newDiscreteStatesNeeded = fmi2_false;\n eventInfo.terminateSimulation = fmi2_false;\n eventInfo.nominalsOfContinuousStatesChanged = fmi2_false;\n eventInfo.valuesOfContinuousStatesChanged = fmi2_true;\n eventInfo.nextEventTimeDefined = fmi2_false;\n eventInfo.nextEventTime = -0.0;\n\n \/* fmiExitInitializationMode leaves FMU in event mode *\/\n do_event_iteration(fmu, &eventInfo);\n fmi2_import_enter_continuous_time_mode(fmu);\n\n fmistatus = fmi2_import_get_continuous_states(fmu, states, n_states);\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Read inputs\n fmi2_value_reference_t vr;\n double value;\n>>>readvars>>> vr = <<<vr>>>;\n value = (*<<<var>>>);\n fmistatus = fmi2_import_set_real(fmu, &vr, 1, &value);\n <<<readvars<<<\n\n double time = mTime-mTimestep;\n double tStop = mTime;\n\n while(time < tStop)\n {\n size_t k;\n fmi2_real_t tlast;\n int zero_crossing_event = 0;\n\n fmistatus = fmi2_import_set_time(fmu, time);\n\n { \/* Swap event_indicators and event_indicators_prev so that we can get new indicators *\/\n fmi2_real_t *temp = event_indicators;\n event_indicators = event_indicators_prev;\n event_indicators_prev = temp;\n }\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n\n \/* Check if an event indicator has triggered *\/\n for (k = 0; k < n_event_indicators; k++)\n {\n if ((event_indicators[k] > 0) != (event_indicators_prev[k] > 0))\n {\n zero_crossing_event = 1;\n break;\n }\n }\n\n \/* Handle any events *\/\n if (callEventUpdate || zero_crossing_event ||\n (eventInfo.nextEventTimeDefined && time == eventInfo.nextEventTime))\n {\n fmistatus = fmi2_import_enter_event_mode(fmu);\n do_event_iteration(fmu, &eventInfo);\n fmistatus = fmi2_import_enter_continuous_time_mode(fmu);\n\n fmistatus = fmi2_import_get_continuous_states(fmu, states, n_states);\n fmistatus = fmi2_import_get_event_indicators(fmu, event_indicators, n_event_indicators);\n }\n\n \/* Calculate next time step *\/\n tlast = time;\n time = tStop;\n if (eventInfo.nextEventTimeDefined && (time >= eventInfo.nextEventTime))\n {\n time = eventInfo.nextEventTime;\n }\n hcur = time - tlast;\n\n \/* Integrate a step *\/\n fmistatus = fmi2_import_get_derivatives(fmu, states_der, n_states);\n for (k = 0; k < n_states; k++)\n {\n states[k] = states[k] + hcur*states_der[k];\n }\n\n \/* Set states *\/\n fmistatus = fmi2_import_set_continuous_states(fmu, states, n_states);\n\n \/* Step is complete *\/\n fmistatus = fmi2_import_completed_integrator_step(fmu, fmi2_true, &callEventUpdate,\n &terminateSimulation);\n }\n\n\n double rValue;\n>>>writevars>>> vr = <<<vr>>>;\n fmistatus = fmi2_import_get_real(fmu, &vr, 1, &rValue);\n (*<<<var>>>) = rValue;\n <<<writevars<<<\n }\n\n\n void finalize()\n {\n fmistatus = fmi2_import_terminate(fmu);\n\n fmi2_import_free_instance(fmu);\n\n fmi2_import_destroy_dllfmu(fmu);\n\n fmi2_import_free(fmu);\n fmi_import_free_context(context);\n\n addInfoMessage(\"Everything seems to be OK since you got this far=)!\");\n }\n\n\n void do_event_iteration(fmi2_import_t *fmu, fmi2_event_info_t *eventInfo)\n {\n eventInfo->newDiscreteStatesNeeded = fmi2_true;\n eventInfo->terminateSimulation = fmi2_false;\n while (eventInfo->newDiscreteStatesNeeded && !eventInfo->terminateSimulation)\n {\n fmi2_import_new_discrete_states(fmu, eventInfo);\n }\n }\n};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CAddNodeToViewByName.h\"\n\n#include \"VisualizationBase\/src\/items\/ViewItem.h\"\n#include \"ModelBase\/src\/model\/TreeManager.h\"\n\n\nnamespace Interaction {\n\nCAddNodeToViewByName::CAddNodeToViewByName() : Command{\"add\"}{}\n\nbool CAddNodeToViewByName::canInterpret(Visualization::Item*, Visualization::Item*,\n\t\tconst QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)\n{\n\treturn commandTokens.size() >= 1 && commandTokens.first() == name();\n}\n\nCommandResult* CAddNodeToViewByName::execute(Visualization::Item*, Visualization::Item* target,\n\t\tconst QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)\n{\n\tif (commandTokens.size() < 2)\n\t\treturn new CommandResult(new CommandError(\"Please specify a node to add\"));\n\n\tauto tokens = commandTokens.mid(1);\n\ttokens.removeAll(\".\");\n\tif (auto node = findNode(tokens,\n\t\t\tModel::AllTreeManagers::instance().loadedManagers().first()->root()))\n\t{\n\t\ttarget->scene()->currentViewItem()->insertNode(node);\n\t\treturn new CommandResult();\n\t}\n\telse\n\t\treturn new CommandResult(new CommandError(\"Could not find node with name \" + commandTokens[1]));\n}\n\nQList<CommandSuggestion*> CAddNodeToViewByName::suggest(Visualization::Item*, Visualization::Item*,\n\t\tconst QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)\n{\n\tQList<CommandSuggestion*> suggestions;\n\n\tif (textSoFar.trimmed().startsWith(\"add \", Qt::CaseInsensitive))\n\t{\n\t\tauto nodeName = textSoFar.trimmed().mid(4);\n\t\tauto names = findNames(nodeName.split(\".\"),\n\t\t\t\t\t\tModel::AllTreeManagers::instance().loadedManagers().first()->root());\n\t\t\/\/Shorter names usually have less parts to the fully qualified name -> suggest them first\n\t\tstd::sort(names.begin(), names.end(), [](QString first, QString second)\n\t\t\t\t\t\t\t\t\t\t\t{ return first.length() < second.length(); });\n\t\t\/\/Limit the number of suggestions\n\t\tnames = names.mid(0, 10);\n\t\tfor (auto name : names)\n\t\t\tsuggestions.append(new CommandSuggestion(\"add \" + name, \"Add node \" + name + \" to the view\"));\n\t}\n\telse if (QString(\"add \").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive) )\n\t\t\tsuggestions.append(new CommandSuggestion(\"add \", \"Add nodes to the current view\"));\n\n\treturn suggestions;\n}\n\nQStringList CAddNodeToViewByName::findNames(QStringList nameParts, Model::Node* root)\n{\n\tQStringList result;\n\n\t\/\/If it doesn't define a symbol, just pass it on\n\tif (!root->definesSymbol())\n\t\tfor (auto child : root->children())\n\t\t\tresult.append(findNames(nameParts, child));\n\n\t\/\/If it defines a symbol, and the name matches, take the part of name it matches and search for the rest\n\telse if (nameParts.size() > 0 && root->symbolName().startsWith(nameParts[0])\n\t\t\t && isSuggestable(root->symbolType()))\n\t{\n\t\tfor (auto child : root->children())\n\t\t\tfor (auto name : findNames(nameParts.mid(1), child))\n\t\t\t\tresult.append(root->symbolName() + \".\" + name);\n\t\tif (nameParts.size() == 1)\n\t\t\tresult.append(root->symbolName());\n\t}\n\t\/\/If we don't have any name left, accept anything which defines a suggestable symbol\n\telse if (nameParts.size() == 0 && isSuggestable(root->symbolType()))\n\t{\n\t\tfor (auto child : root->children())\n\t\t\tfor (auto name : findNames(nameParts, child))\n\t\t\t\tresult.append(root->symbolName() + \".\" + name);\n\t\tresult.append(root->symbolName());\n\t}\n\treturn result;\n}\n\nModel::Node* CAddNodeToViewByName::findNode(QStringList fullyQualifiedName, Model::Node* root)\n{\n\tQList<Model::Node*> toSearch{root};\n\tint currentPart = 0;\n\twhile (!toSearch.isEmpty() && currentPart < fullyQualifiedName.size())\n\t{\n\t\tauto current = toSearch.takeLast();\n\t\tif (current->definesSymbol() && current->symbolName() == fullyQualifiedName[currentPart]\n\t\t\t\t&& currentPart == fullyQualifiedName.size() - 1)\n\t\t\treturn current;\n\n\t\t\/\/If it doesn't define a symbol, check in the children\n\t\t\/\/Else only continue the path if the name fits\n\t\tif (!current->definesSymbol())\n\t\t\ttoSearch.append(current->children());\n\t\telse if (current->symbolName() == fullyQualifiedName[currentPart])\n\t\t{\n\t\t\ttoSearch.clear();\n\t\t\ttoSearch.append(current->children());\n\t\t\tcurrentPart++;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nbool CAddNodeToViewByName::isSuggestable(Model::Node::SymbolTypes symbolType)\n{\n\treturn symbolType == Model::Node::METHOD || symbolType == Model::Node::CONTAINER;\n}\n\n}\n<commit_msg>Can add nodes of different projects.<commit_after>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"CAddNodeToViewByName.h\"\n\n#include \"VisualizationBase\/src\/items\/ViewItem.h\"\n#include \"ModelBase\/src\/model\/TreeManager.h\"\n\n\nnamespace Interaction {\n\nCAddNodeToViewByName::CAddNodeToViewByName() : Command{\"add\"}{}\n\nbool CAddNodeToViewByName::canInterpret(Visualization::Item*, Visualization::Item*,\n\t\tconst QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)\n{\n\treturn commandTokens.size() >= 1 && commandTokens.first() == name();\n}\n\nCommandResult* CAddNodeToViewByName::execute(Visualization::Item*, Visualization::Item* target,\n\t\tconst QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)\n{\n\tif (commandTokens.size() < 2)\n\t\treturn new CommandResult(new CommandError(\"Please specify a node to add\"));\n\n\tauto tokens = commandTokens.mid(1);\n\ttokens.removeAll(\".\");\n\tfor (auto manager : Model::AllTreeManagers::instance().loadedManagers())\n\t\tif (auto node = findNode(tokens, manager->root()))\n\t\t{\n\t\t\ttarget->scene()->currentViewItem()->insertNode(node);\n\t\t\treturn new CommandResult();\n\t\t}\n\treturn new CommandResult(new CommandError(\"Could not find node with name \" + commandTokens[1]));\n}\n\nQList<CommandSuggestion*> CAddNodeToViewByName::suggest(Visualization::Item*, Visualization::Item*,\n\t\tconst QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)\n{\n\tQList<CommandSuggestion*> suggestions;\n\n\tif (textSoFar.trimmed().startsWith(\"add \", Qt::CaseInsensitive))\n\t{\n\t\tauto nodeName = textSoFar.trimmed().mid(4);\n\t\tQStringList names;\n\t\tfor (auto manager : Model::AllTreeManagers::instance().loadedManagers())\n\t\t\tnames.append(findNames(nodeName.split(\".\"), manager->root()));\n\n\t\t\/\/Shorter names usually have less parts to the fully qualified name -> suggest them first\n\t\tstd::sort(names.begin(), names.end(), [](QString first, QString second)\n\t\t\t\t\t\t\t\t\t\t\t{ return first.length() < second.length(); });\n\t\t\/\/Limit the number of suggestions\n\t\tnames = names.mid(0, 10);\n\t\tfor (auto name : names)\n\t\t\tsuggestions.append(new CommandSuggestion(\"add \" + name, \"Add node \" + name + \" to the view\"));\n\t}\n\telse if (QString(\"add \").startsWith(textSoFar.trimmed(), Qt::CaseInsensitive) )\n\t\t\tsuggestions.append(new CommandSuggestion(\"add \", \"Add nodes to the current view\"));\n\n\treturn suggestions;\n}\n\nQStringList CAddNodeToViewByName::findNames(QStringList nameParts, Model::Node* root)\n{\n\tQStringList result;\n\n\t\/\/If it doesn't define a symbol, just pass it on\n\tif (!root->definesSymbol())\n\t\tfor (auto child : root->children())\n\t\t\tresult.append(findNames(nameParts, child));\n\n\t\/\/If it defines a symbol, and the name matches, take the part of name it matches and search for the rest\n\telse if (nameParts.size() > 0 && root->symbolName().startsWith(nameParts[0])\n\t\t\t && isSuggestable(root->symbolType()))\n\t{\n\t\tfor (auto child : root->children())\n\t\t\tfor (auto name : findNames(nameParts.mid(1), child))\n\t\t\t\tresult.append(root->symbolName() + \".\" + name);\n\t\tif (nameParts.size() == 1)\n\t\t\tresult.append(root->symbolName());\n\t}\n\t\/\/If we don't have any name left, accept anything which defines a suggestable symbol\n\telse if (nameParts.size() == 0 && isSuggestable(root->symbolType()))\n\t{\n\t\tfor (auto child : root->children())\n\t\t\tfor (auto name : findNames(nameParts, child))\n\t\t\t\tresult.append(root->symbolName() + \".\" + name);\n\t\tresult.append(root->symbolName());\n\t}\n\treturn result;\n}\n\nModel::Node* CAddNodeToViewByName::findNode(QStringList fullyQualifiedName, Model::Node* root)\n{\n\tQList<Model::Node*> toSearch{root};\n\tint currentPart = 0;\n\twhile (!toSearch.isEmpty() && currentPart < fullyQualifiedName.size())\n\t{\n\t\tauto current = toSearch.takeLast();\n\t\tif (current->definesSymbol() && current->symbolName() == fullyQualifiedName[currentPart]\n\t\t\t\t&& currentPart == fullyQualifiedName.size() - 1)\n\t\t\treturn current;\n\n\t\t\/\/If it doesn't define a symbol, check in the children\n\t\t\/\/Else only continue the path if the name fits\n\t\tif (!current->definesSymbol())\n\t\t\ttoSearch.append(current->children());\n\t\telse if (current->symbolName() == fullyQualifiedName[currentPart])\n\t\t{\n\t\t\ttoSearch.clear();\n\t\t\ttoSearch.append(current->children());\n\t\t\tcurrentPart++;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nbool CAddNodeToViewByName::isSuggestable(Model::Node::SymbolTypes symbolType)\n{\n\treturn symbolType == Model::Node::METHOD || symbolType == Model::Node::CONTAINER;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bulkDataCallback.h\"\n\nusing namespace ACSBulkDataError;\nusing namespace ACSBulkDataStatus;\n\nBulkDataCallback::BulkDataCallback()\n{\n ACS_TRACE(\"BulkDataCallback::BulkDataCallback\");\n\n state_m = CB_UNS; \n substate_m = CB_SUB_UNS;\n\n dim_m = 0;\n count_m = 0;\n\n \/\/loop_m = 5;\n loop_m = 1000;\n \/\/waitPeriod_m.set(0L, 400000L);\n waitPeriod_m.set(0L, 10L); \/\/ set to 0.01 ms to improve Receiver performance\n \/\/ (similar to Distributor callback)\n\n frameCount_m = 0;\n\n bufParam_p = 0;\n\n timeout_m = false;\n working_m = false;\n error_m = false;\n\n errComp_p = 0;\n\n flowTimeout_m = 0;\n\n isFepAlive_m = true;\n}\n\n\nBulkDataCallback::~BulkDataCallback()\n{\n ACS_TRACE(\"BulkDataCallback::~BulkDataCallback\"); \n\n if (error_m == true)\n\t{\n\tif (errComp_p != 0)\n\t {\n\t delete errComp_p;\n\t errComp_p = 0;\n\t }\n\t}\n error_m = false;\n \n if(bufParam_p)\n\t{\n\tbufParam_p->release();\n\tbufParam_p = 0;\n\t}\n}\n\n\nint BulkDataCallback::handle_start(void)\n{\n \n \/\/ cout << \"BulkDataCallback::handle_start - state_m: \" << state_m << endl;\n \/\/if(timeout_m == true)\n \/\/ACS_SHORT_LOG((LM_INFO,\"BulkDataCallback::handle_start - timeout_m == true !!!\"));\n\n timeout_m = false;\n\n if (error_m == true)\n\t{\n\tif (errComp_p != 0)\n\t {\n\t delete errComp_p;\n\t errComp_p = 0;\n\t }\n\t}\n \/\/ error is cleared\n error_m = false; \n\n \/\/ parameter buffer is cleared (just in case) \n if(bufParam_p)\n\t{\n\tbufParam_p->release();\n\tbufParam_p = 0;\n\t}\n\n state_m = CB_UNS;\n substate_m = CB_SUB_UNS;\n \n frameCount_m = 1; \/\/ we need to wait for 1 following frame before doing anything else \n\n if (flowTimeout_m != 0)\n\tstartTime_m = ACE_OS::gettimeofday();\n\n return 0;\n}\n\n\nint BulkDataCallback::handle_stop (void)\n{\n \/\/ACS_TRACE(\"BulkDataCallback::handle_stop\");\n\n \/\/ cout << \"CCCCCCCCCCCCCCCCC enter stop state \" << state_m << \" \" << substate_m << endl;\n\n try\n\t{\n\tint locLoop;\n\tint res;\n\n\tlocLoop = loop_m;\n\twhile ( (frameCount_m != 0) && locLoop > 0) \n\t {\n\t ACE_OS::sleep(waitPeriod_m);\n\t locLoop--; \n\t } \/\/ we didn't receive the first frame yet\n\n\n\tif(state_m == CB_UNS)\n\t { \n\t res = cbStop();\n\t return 0;\n\t }\n\n\tif((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA))\n\t { \n\n\t if (substate_m == CB_SUB_INIT)\n\t\t{\n\t\tsubstate_m = CB_SUB_UNS;\n\t\treturn 0;\n\t\t}\n\n\n\t if (error_m == true)\n\t\t{\n\t\ttimeout_m = true;\n\t\tthrow CORBA::BAD_OPERATION();\n\t\t}\n\n\t locLoop = loop_m;\n\t while((count_m != dim_m) && locLoop > 0)\n\t\t{\n\t\tACE_OS::sleep(waitPeriod_m);\n\t\tlocLoop--;\n\t\tcheckFlowTimeout();\n\n\t\t\/\/ re-check error_m in case that is not set the first time\n\t\tif (error_m == true)\n\t\t {\n\t\t timeout_m = true;\n\t\t throw CORBA::BAD_OPERATION();\n\t\t }\n\t\t}\n\n\t if ( locLoop == 0 )\n\t\t{\n\t\tACS_SHORT_LOG((LM_ERROR,\"BulkDataCallback::handle_stop timeout ( (%ld sec + %ld usec) * %ld ) expired for flow %s - not all data received\", waitPeriod_m.sec(), waitPeriod_m.usec(), loop_m, flowname_m.c_str()));\n\n\t\ttimeout_m = true;\n\t\t\/\/cleaning the recv buffer\n\t\t\/\/\/cleanRecvBuffer();\n\t\t\/\/cout << \"BulkDataCallback::handle_stop - handle removed: \" << getHandle() << endl;\n\t\tTAO_AV_CORE::instance()->reactor()->remove_handler(getHandle(),ACE_Event_Handler::READ_MASK);\n\t\tACS_SHORT_LOG((LM_DEBUG,\"BulkDataCallback::handle_stop - receiver handler removed from the ACE reactor\"));\n\t\t\/\/ACE_OS::sleep(1); \/\/ seems necessary to give time to remove\n\t\t \/\/ the handler from the reactor\n\t\tthrow CORBA::TIMEOUT();\n\t\t}\n\n\t if(state_m == CB_SEND_PARAM)\n\t\t{\t\t\n\t\t\/\/res ignored by reactor\n\t\tif (dim_m != 0)\n\t\t res = cbStart(bufParam_p);\n\n\t\tif(bufParam_p)\n\t\t {\n\t\t bufParam_p->release();\n\t\t bufParam_p = 0;\n\t\t }\n\t\tcheckFlowTimeout();\n\t\t}\n\n\t state_m = CB_UNS;\n\t substate_m = CB_SUB_UNS;\n\n\t return 0;\n\t }\n\n\t}\n catch(ACSErr::ACSbaseExImpl &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.log();\n\t\/\/ add to the completion\n\terrComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::handle_stop\"); \n\terror_m = true;\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow CORBA::BAD_OPERATION();\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n catch(CORBA::Exception &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.addData(\"CORBA::Exception\", ex._info());\n\terr.log();\n\n\tif (errComp_p == 0)\n\t {\n\t errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::handle_stop\"); \n\t error_m = true;\n\t }\n\t\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow;\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n catch(...)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.addData(\"UNKNOWN Exception\", \"Unknown ex in BulkDataCallback::handle_stop\");\n\terr.log();\n\/\/\terror_m = true;\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow;\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n\n state_m = CB_UNS;\n substate_m = CB_SUB_UNS;\n\n return 0;\n}\n\n\nint BulkDataCallback::handle_destroy (void)\n{\n \/\/ACS_TRACE(\"BulkDataCallback::handle_destroy\");\n\n \/\/cout << \"BulkDataCallback::handle_destroy\" << endl;\n\n isFepAlive_m = false;\n\n return 0;\n}\n\n\n\nint BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &)\n{\n \/\/cout << \"BulkDataCallback::receive_frame - state_m: \" << state_m << endl;\n working_m = true;\n\n if(error_m == true)\n\t{\n\t\/\/\/cleanRecvBuffer();\n\tworking_m = false;\n\treturn 0;\n\t}\n\n \/\/ACS_SHORT_LOG((LM_INFO,\"BulkDataCallback::receive_frame for flow %s\", flowname_m.c_str())); \n \/\/ cout << \"BulkDataCallback::receive_frame - state_m: \" << state_m << endl;\n\n try\n\t{\n\tCORBA::ULong val1, val2;\n\tint res;\n\n\tif(state_m == CB_UNS)\n\t { \n\t char tmp[255];\n\t ACE_OS::strcpy(tmp, frame->rd_ptr());\n\n\t std::string strDataInfo(tmp);\n\t\n\t std::istringstream iss(strDataInfo);\n\n\t iss >> val1 >> val2;\n\n\t \/\/ cout << \"CCCCCCCCCCCCCCC \" << val1 << \" \" << val2 << endl;\n\n\t if(val1 == 1)\n\t\t{\n\t\tstate_m = CB_SEND_PARAM;\n\t\tsubstate_m = CB_SUB_INIT;\n\n\t\tif(val2 != 0)\n\t\t bufParam_p = new ACE_Message_Block(val2);\n\t\telse\n\t\t bufParam_p = 0;\n\t\t}\n\t else if(val1 == 2)\n\t\t{\n\t\tstate_m = CB_SEND_DATA;\n\t\tsubstate_m = CB_SUB_INIT;\n\t\t}\n\t else\n\t\t{\n\t\tstate_m = CB_UNS;\n\t\tsubstate_m = CB_SUB_UNS;\n\t\t}\n\n\t dim_m = val2;\n\t count_m = 0;\n\n\t frameCount_m = 0;\n\t working_m = false;\n\n\t return 0;\n\t }\n\n\tif(state_m == CB_SEND_PARAM)\n\t {\n\n\t if ( dim_m == 0 )\n\t\t{\n\t\tres = cbStart();\n\n\t\tcheckFlowTimeout();\n\t\tworking_m = false;\n\t\treturn 0;\n\t\t}\n\n\t bufParam_p->copy(frame->rd_ptr(),frame->length());\n\t count_m += frame->length();\n\n\t working_m = false;\n\t return 0;\n\t }\n\t\n\tif (state_m == CB_SEND_DATA)\n\t {\n\t res = cbReceive(frame);\n\t count_m += frame->length();\n\n\t checkFlowTimeout();\n\t working_m = false;\n\t return 0;\n\t }\n\n\t}\n catch(ACSErr::ACSbaseExImpl &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.log();\n\t\/\/ add to the completion\n\terrComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::receive_frame\"); \n\terror_m = true;\n\t}\n catch(CORBA::Exception &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.addData(\"CORBA::Exception\", ex._info());\n\terr.log();\n\terror_m = true;\n\t}\n catch(std::exception &stdex)\n {\n \tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n \terr.addData(\"std::exception\", stdex.what());\n \terr.log();\n \terror_m = true;\n }\n catch(...)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.addData(\"UNKNOWN Exception\", \"Unknown ex in BulkDataCallback::receive_frame\");\n\terr.log();\n\terror_m = true;\n\t}\n\n working_m = false;\n return 0;\n}\n\n\nvoid BulkDataCallback::setFlowname (const char * flowname_p)\n{\n ACS_TRACE(\"BulkDataCallback::setFlowname\");\n \/\/ACS_SHORT_LOG((LM_INFO,\"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s\", flow_name));\n flowname_m = flowname_p;\n\n std::string flwName(flowname_p);\n std::string flwNumber(flwName, 4, 1);\n\n flowNumber_m = atol(flwNumber.c_str());\n}\n\n\nvoid BulkDataCallback::setReceiverName(ACE_CString recvName)\n{\n recvName_m = recvName;\n}\n\n\nvoid BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod)\n{\n ACS_TRACE(\"BulkDataCallback::setSleepTime\");\n\n waitPeriod_m = locWaitPeriod;\n}\n\n\nvoid BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop)\n{\n ACS_TRACE(\"BulkDataCallback::setSafeTimeout\");\n\n loop_m = locLoop;\n}\n\n\nCORBA::Boolean BulkDataCallback::isTimeout()\n{\n ACS_TRACE(\"BulkDataCallback::isTimeout\");\n\n return timeout_m;\n}\n\n\nCORBA::Boolean BulkDataCallback::isWorking()\n{\n ACS_TRACE(\"BulkDataCallback::isWorking\");\n\n return working_m;\n}\n\n\nCORBA::Boolean BulkDataCallback::isError()\n{\n\/\/ ACS_TRACE(\"BulkDataCallback::isError\");\n\n return error_m;\n}\n\n\nCompletionImpl *BulkDataCallback::getErrorCompletion()\n{\n ACS_TRACE(\"BulkDataCallback::getErrorCompletion\");\n\n \/\/ error is cleared; completion cannot be retrieved two times\n error_m = false;\n\n return errComp_p;\n}\n\n\nvoid BulkDataCallback::cleanRecvBuffer()\n{\n ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); \n\t\n char buf[BUFSIZ];\n int bufSize = sizeof(buf);\n int nn = 1;\n while(nn > 0)\n\t{\n\tnn = svch->peer().recv(buf,bufSize);\n\t}\n\n\/\/ svch->peer().close(); \n}\n\n\nvoid BulkDataCallback::setFlowTimeout(CORBA::ULong timeout)\n{\n flowTimeout_m = timeout;\n}\n\n\nvoid BulkDataCallback::checkFlowTimeout()\n{\n if(flowTimeout_m == 0)\n\treturn;\n\n ACE_Time_Value elapsedTime = ACE_OS::gettimeofday() - startTime_m;\n double dtime = (elapsedTime.sec() * 1000.) + ( elapsedTime.usec() \/ 1000. );\n if(dtime > flowTimeout_m)\n\t{\n\t\/\/\/cleanRecvBuffer();\n\ttimeout_m = true;\n\tAVCbFlowTimeoutExImpl err = AVCbFlowTimeoutExImpl(__FILE__,__LINE__,\"BulkDataCallback::checkFlowTimeout\");\n\tthrow err;\n\t}\n}\n\n\nvoid BulkDataCallback::closePeer()\n{\n ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = \n\tdynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); \n\n if (svch != 0)\n\t{\n\tsvch->peer().close();\n\t}\n}\n\n\nACE_HANDLE BulkDataCallback::getHandle()\n{\n ACS_TRACE(\"BulkDataCallback::getHandle\");\n\n ACE_Event_Handler *event_handler = handler_->event_handler();\n\n ACE_HANDLE handle = event_handler->get_handle();\n\n return handle;\n}\n<commit_msg>added flow name to commented logs in case we need them at some point<commit_after>#include \"bulkDataCallback.h\"\n\nusing namespace ACSBulkDataError;\nusing namespace ACSBulkDataStatus;\n\nBulkDataCallback::BulkDataCallback()\n{\n ACS_TRACE(\"BulkDataCallback::BulkDataCallback\");\n\n state_m = CB_UNS; \n substate_m = CB_SUB_UNS;\n\n dim_m = 0;\n count_m = 0;\n\n \/\/loop_m = 5;\n loop_m = 1000;\n \/\/waitPeriod_m.set(0L, 400000L);\n waitPeriod_m.set(0L, 10L); \/\/ set to 0.01 ms to improve Receiver performance\n \/\/ (similar to Distributor callback)\n\n frameCount_m = 0;\n\n bufParam_p = 0;\n\n timeout_m = false;\n working_m = false;\n error_m = false;\n\n errComp_p = 0;\n\n flowTimeout_m = 0;\n\n isFepAlive_m = true;\n}\n\n\nBulkDataCallback::~BulkDataCallback()\n{\n ACS_TRACE(\"BulkDataCallback::~BulkDataCallback\"); \n\n if (error_m == true)\n\t{\n\tif (errComp_p != 0)\n\t {\n\t delete errComp_p;\n\t errComp_p = 0;\n\t }\n\t}\n error_m = false;\n \n if(bufParam_p)\n\t{\n\tbufParam_p->release();\n\tbufParam_p = 0;\n\t}\n}\n\n\nint BulkDataCallback::handle_start(void)\n{\n \n \/\/cout << \"BulkDataCallback::handle_start \" << flowname_m << \"- state_m: \" << state_m << endl;\n \/\/if(timeout_m == true)\n \/\/ACS_SHORT_LOG((LM_INFO,\"BulkDataCallback::handle_start - timeout_m == true !!!\"));\n\n timeout_m = false;\n\n if (error_m == true)\n\t{\n\tif (errComp_p != 0)\n\t {\n\t delete errComp_p;\n\t errComp_p = 0;\n\t }\n\t}\n \/\/ error is cleared\n error_m = false; \n\n \/\/ parameter buffer is cleared (just in case) \n if(bufParam_p)\n\t{\n\tbufParam_p->release();\n\tbufParam_p = 0;\n\t}\n\n state_m = CB_UNS;\n substate_m = CB_SUB_UNS;\n \n frameCount_m = 1; \/\/ we need to wait for 1 following frame before doing anything else \n\n if (flowTimeout_m != 0)\n\tstartTime_m = ACE_OS::gettimeofday();\n\n return 0;\n}\n\n\nint BulkDataCallback::handle_stop (void)\n{\n \/\/ACS_TRACE(\"BulkDataCallback::handle_stop\");\n \/\/ cout << \"CCCCCCCCCCCCCCCCC \" << flowname_m << \"enter stop state \" << state_m << \" \" << substate_m << endl;\n\n try\n\t{\n\tint locLoop;\n\tint res;\n\n\tlocLoop = loop_m;\n\twhile ( (frameCount_m != 0) && locLoop > 0) \n\t {\n\t ACE_OS::sleep(waitPeriod_m);\n\t locLoop--; \n\t } \/\/ we didn't receive the first frame yet\n\n\n\tif(state_m == CB_UNS)\n\t { \n\t res = cbStop();\n\t return 0;\n\t }\n\n\tif((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA))\n\t { \n\n\t if (substate_m == CB_SUB_INIT)\n\t\t{\n\t\tsubstate_m = CB_SUB_UNS;\n\t\treturn 0;\n\t\t}\n\n\n\t if (error_m == true)\n\t\t{\n\t\ttimeout_m = true;\n\t\tthrow CORBA::BAD_OPERATION();\n\t\t}\n\n\t locLoop = loop_m;\n\t while((count_m != dim_m) && locLoop > 0)\n\t\t{\n\t\tACE_OS::sleep(waitPeriod_m);\n\t\tlocLoop--;\n\t\tcheckFlowTimeout();\n\n\t\t\/\/ re-check error_m in case that is not set the first time\n\t\tif (error_m == true)\n\t\t {\n\t\t timeout_m = true;\n\t\t throw CORBA::BAD_OPERATION();\n\t\t }\n\t\t}\n\n\t if ( locLoop == 0 )\n\t\t{\n\t\tACS_SHORT_LOG((LM_ERROR,\"BulkDataCallback::handle_stop timeout ( (%ld sec + %ld usec) * %ld ) expired for flow %s - not all data received\", waitPeriod_m.sec(), waitPeriod_m.usec(), loop_m, flowname_m.c_str()));\n\n\t\ttimeout_m = true;\n\t\t\/\/cleaning the recv buffer\n\t\t\/\/\/cleanRecvBuffer();\n\t\t\/\/cout << \"BulkDataCallback::handle_stop - handle removed: \" << getHandle() << endl;\n\t\tTAO_AV_CORE::instance()->reactor()->remove_handler(getHandle(),ACE_Event_Handler::READ_MASK);\n\t\tACS_SHORT_LOG((LM_DEBUG,\"BulkDataCallback::handle_stop - receiver handler removed from the ACE reactor\"));\n\t\t\/\/ACE_OS::sleep(1); \/\/ seems necessary to give time to remove\n\t\t \/\/ the handler from the reactor\n\t\tthrow CORBA::TIMEOUT();\n\t\t}\n\n\t if(state_m == CB_SEND_PARAM)\n\t\t{\t\t\n\t\t\/\/res ignored by reactor\n\t\tif (dim_m != 0)\n\t\t res = cbStart(bufParam_p);\n\n\t\tif(bufParam_p)\n\t\t {\n\t\t bufParam_p->release();\n\t\t bufParam_p = 0;\n\t\t }\n\t\tcheckFlowTimeout();\n\t\t}\n\n\t state_m = CB_UNS;\n\t substate_m = CB_SUB_UNS;\n\n\t return 0;\n\t }\n\n\t}\n catch(ACSErr::ACSbaseExImpl &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.log();\n\t\/\/ add to the completion\n\terrComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::handle_stop\"); \n\terror_m = true;\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow CORBA::BAD_OPERATION();\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n catch(CORBA::Exception &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.addData(\"CORBA::Exception\", ex._info());\n\terr.log();\n\n\tif (errComp_p == 0)\n\t {\n\t errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::handle_stop\"); \n\t error_m = true;\n\t }\n\t\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow;\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n catch(...)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::handle_stop\");\n\terr.addData(\"UNKNOWN Exception\", \"Unknown ex in BulkDataCallback::handle_stop\");\n\terr.log();\n\/\/\terror_m = true;\n\n\tif(bufParam_p)\n\t {\n\t bufParam_p->release();\n\t bufParam_p = 0;\n\t }\n\n\tstate_m = CB_UNS;\n\tsubstate_m = CB_SUB_UNS;\n\n\tthrow;\n\t\/\/throw CORBA::TIMEOUT();\n\t}\n\n state_m = CB_UNS;\n substate_m = CB_SUB_UNS;\n\n return 0;\n}\n\n\nint BulkDataCallback::handle_destroy (void)\n{\n \/\/ACS_TRACE(\"BulkDataCallback::handle_destroy\");\n\n \/\/cout << \"BulkDataCallback::handle_destroy\" << endl;\n\n isFepAlive_m = false;\n\n return 0;\n}\n\n\n\nint BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &)\n{\n \/\/cout << \"BulkDataCallback::receive_frame - state_m: \" << state_m << endl;\n working_m = true;\n\n if(error_m == true)\n\t{\n\t\/\/\/cleanRecvBuffer();\n\tworking_m = false;\n\treturn 0;\n\t}\n\n \/\/ACS_SHORT_LOG((LM_INFO,\"BulkDataCallback::receive_frame for flow %s\", flowname_m.c_str())); \n \/\/ cout << \"BulkDataCallback::receive_frame - state_m: \" << state_m << endl;\n\n try\n\t{\n\tCORBA::ULong val1, val2;\n\tint res;\n\n\tif(state_m == CB_UNS)\n\t { \n\t char tmp[255];\n\t ACE_OS::strcpy(tmp, frame->rd_ptr());\n\n\t std::string strDataInfo(tmp);\n\t\n\t std::istringstream iss(strDataInfo);\n\n\t iss >> val1 >> val2;\n\n\t \/\/ cout << \"CCCCCCCCCCCCCCC \" << val1 << \" \" << val2 << endl;\n\n\t if(val1 == 1)\n\t\t{\n\t\tstate_m = CB_SEND_PARAM;\n\t\tsubstate_m = CB_SUB_INIT;\n\n\t\tif(val2 != 0)\n\t\t bufParam_p = new ACE_Message_Block(val2);\n\t\telse\n\t\t bufParam_p = 0;\n\t\t}\n\t else if(val1 == 2)\n\t\t{\n\t\tstate_m = CB_SEND_DATA;\n\t\tsubstate_m = CB_SUB_INIT;\n\t\t}\n\t else\n\t\t{\n\t\tstate_m = CB_UNS;\n\t\tsubstate_m = CB_SUB_UNS;\n\t\t}\n\n\t dim_m = val2;\n\t count_m = 0;\n\n\t frameCount_m = 0;\n\t working_m = false;\n\n\t return 0;\n\t }\n\n\tif(state_m == CB_SEND_PARAM)\n\t {\n\n\t if ( dim_m == 0 )\n\t\t{\n\t\tres = cbStart();\n\n\t\tcheckFlowTimeout();\n\t\tworking_m = false;\n\t\treturn 0;\n\t\t}\n\n\t bufParam_p->copy(frame->rd_ptr(),frame->length());\n\t count_m += frame->length();\n\n\t working_m = false;\n\t return 0;\n\t }\n\t\n\tif (state_m == CB_SEND_DATA)\n\t {\n\t res = cbReceive(frame);\n\t count_m += frame->length();\n\n\t checkFlowTimeout();\n\t working_m = false;\n\t return 0;\n\t }\n\n\t}\n catch(ACSErr::ACSbaseExImpl &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.log();\n\t\/\/ add to the completion\n\terrComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, \"BulkDataCallback::receive_frame\"); \n\terror_m = true;\n\t}\n catch(CORBA::Exception &ex)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.addData(\"CORBA::Exception\", ex._info());\n\terr.log();\n\terror_m = true;\n\t}\n catch(std::exception &stdex)\n {\n \tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n \terr.addData(\"std::exception\", stdex.what());\n \terr.log();\n \terror_m = true;\n }\n catch(...)\n\t{\n\tAVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,\"BulkDataCallback::receive_frame\");\n\terr.addData(\"UNKNOWN Exception\", \"Unknown ex in BulkDataCallback::receive_frame\");\n\terr.log();\n\terror_m = true;\n\t}\n\n working_m = false;\n return 0;\n}\n\n\nvoid BulkDataCallback::setFlowname (const char * flowname_p)\n{\n ACS_TRACE(\"BulkDataCallback::setFlowname\");\n \/\/ACS_SHORT_LOG((LM_INFO,\"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s\", flow_name));\n flowname_m = flowname_p;\n\n std::string flwName(flowname_p);\n std::string flwNumber(flwName, 4, 1);\n\n flowNumber_m = atol(flwNumber.c_str());\n}\n\n\nvoid BulkDataCallback::setReceiverName(ACE_CString recvName)\n{\n recvName_m = recvName;\n}\n\n\nvoid BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod)\n{\n ACS_TRACE(\"BulkDataCallback::setSleepTime\");\n\n waitPeriod_m = locWaitPeriod;\n}\n\n\nvoid BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop)\n{\n ACS_TRACE(\"BulkDataCallback::setSafeTimeout\");\n\n loop_m = locLoop;\n}\n\n\nCORBA::Boolean BulkDataCallback::isTimeout()\n{\n ACS_TRACE(\"BulkDataCallback::isTimeout\");\n\n return timeout_m;\n}\n\n\nCORBA::Boolean BulkDataCallback::isWorking()\n{\n ACS_TRACE(\"BulkDataCallback::isWorking\");\n\n return working_m;\n}\n\n\nCORBA::Boolean BulkDataCallback::isError()\n{\n\/\/ ACS_TRACE(\"BulkDataCallback::isError\");\n\n return error_m;\n}\n\n\nCompletionImpl *BulkDataCallback::getErrorCompletion()\n{\n ACS_TRACE(\"BulkDataCallback::getErrorCompletion\");\n\n \/\/ error is cleared; completion cannot be retrieved two times\n error_m = false;\n\n return errComp_p;\n}\n\n\nvoid BulkDataCallback::cleanRecvBuffer()\n{\n ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); \n\t\n char buf[BUFSIZ];\n int bufSize = sizeof(buf);\n int nn = 1;\n while(nn > 0)\n\t{\n\tnn = svch->peer().recv(buf,bufSize);\n\t}\n\n\/\/ svch->peer().close(); \n}\n\n\nvoid BulkDataCallback::setFlowTimeout(CORBA::ULong timeout)\n{\n flowTimeout_m = timeout;\n}\n\n\nvoid BulkDataCallback::checkFlowTimeout()\n{\n if(flowTimeout_m == 0)\n\treturn;\n\n ACE_Time_Value elapsedTime = ACE_OS::gettimeofday() - startTime_m;\n double dtime = (elapsedTime.sec() * 1000.) + ( elapsedTime.usec() \/ 1000. );\n if(dtime > flowTimeout_m)\n\t{\n\t\/\/\/cleanRecvBuffer();\n\ttimeout_m = true;\n\tAVCbFlowTimeoutExImpl err = AVCbFlowTimeoutExImpl(__FILE__,__LINE__,\"BulkDataCallback::checkFlowTimeout\");\n\tthrow err;\n\t}\n}\n\n\nvoid BulkDataCallback::closePeer()\n{\n ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = \n\tdynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); \n\n if (svch != 0)\n\t{\n\tsvch->peer().close();\n\t}\n}\n\n\nACE_HANDLE BulkDataCallback::getHandle()\n{\n ACS_TRACE(\"BulkDataCallback::getHandle\");\n\n ACE_Event_Handler *event_handler = handler_->event_handler();\n\n ACE_HANDLE handle = event_handler->get_handle();\n\n return handle;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Halide.h\"\n\n#include <utility>\n#include <vector>\n\nusing namespace Halide;\n\nconst Expr\n _REAL = 0\n , _IMAG = 1\n ;\n\t\t\nconst int _CMPLX_SIZE = 2;\n\nstruct Complex {\n Expr real, imag;\n Complex(Expr r, Expr i) : real(r), imag(i) {}\n Complex operator+(const Complex &other) const {\n return{ real + other.real, imag + other.imag };\n }\n Complex operator*(const Complex &other) const {\n return{\n real * other.real - imag * other.imag\n , real * other.imag + imag * other.real\n };\n }\n Expr unpack(Expr c) { return select(c == _REAL, real, imag); }\n};\n\n\/* Not need it ATM\ninline Func flushAndContinue(const char * new_name, Func & f) {\n Func ret(new_name);\n f.compute_root();\n ret(f.args()) = f(f.args());\n return ret;\n}\n*\/\n\n#define P(a) a(#a)\n#define IP(a,b,c) a(b,c,#a)\n\n\/\/ We generate the kernel for GPU which works on the subset of baselines\n\/\/ having the same convolution size as we did in MS3.\n\/\/ But we also simplify the algorithm a bit using\n\/\/ GCF-per-baseline (with the size equal to convolution size)\n\/\/ instead of GCF-per-point approach.\n\/\/ We've done this for all halide_scatter_1bl_1gcf... family of gridders.\nint main(\/* int argc, char **argv *\/) {\n int\n over = 8\n , grid_size = 2048\n , max_gcf_size = 128\n ;\n\n Param<double>\n P(scale)\n , P(wstep)\n ;\n Param<int>\n P(gcf_layer_size)\n , P(num_of_baselines)\n , P(ts_ch)\n ;\n ImageParam IP(uvwf, type_of<double>(), 3);\n ImageParam IP(vis, type_of<double>(), 3);\n ImageParam IP(gcf, type_of<double>(), 2);\n ImageParam IP(vismap, type_of<int>(), 1);\n\n Func\n P(uvs)\n , P(uv)\n , P(overc)\n , P(gcfoff)\n , P(bloff)\n ;\n\n Var P(t)\n , P(uvdim)\n , P(bl)\n ;\n const Expr\n _U = 0\n , _V = 1\n ;\n \n uvs(uvdim, t, bl) = uvwf(uvdim, t, bl) * scale;\n overc(uvdim, t, bl) = clamp(cast<int>(round(over * (uvs(uvdim, t, bl) - floor(uvs(uvdim, t, bl))))), 0, 7);\n uv(uvdim, t, bl) = cast<int>(round(uvs(uvdim, t, bl)) + grid_size \/ 2 - gcf_layer_size \/ 2);\n gcfoff(t, bl) = (overc(_U, t, bl) * over + overc(_V, t, bl)) * gcf_layer_size * gcf_layer_size;\n bloff(bl) = ts_ch * vismap(bl);\n\n RDom red(\n 0, _CMPLX_SIZE\n , 0, gcf_layer_size\n , 0, ts_ch\n , 0, gcf_layer_size\n , 0, num_of_baselines\n );\n RVar P(rcmplx), P(rgcfx), P(rvis), P(rgcfy), P(rbl);\n rcmplx = red.x;\n rgcfx = red.y;\n rvis = red.z;\n rgcfy = red.w;\n rbl = red[4];\n\n Expr gcf_pix_off = gcfoff(rvis, rbl) + rgcfx + rgcfy * gcf_layer_size; \n Complex gcfC(\n gcf(_REAL, gcf_pix_off)\n , gcf(_IMAG, gcf_pix_off)\n );\n\n Complex visC(\n vis(_REAL, rvis, rbl)\n , vis(_IMAG, rvis, rbl)\n );\n\n Func P(uvg);\n Var P(cmplx)\n , P(x)\n , P(y)\n ;\n uvg(cmplx, x, y) = undef<double>();\n\n Expr\n clampedU = clamp(uv(_U, rvis, rbl), 0, grid_size - 1 - max_gcf_size)\n , clampedV = clamp(uv(_V, rvis, rbl), 0, grid_size - 1 - max_gcf_size)\n , U = clampedU + rgcfx\n , V = clampedV + rgcfy\n ;\n\n uvg(\n rcmplx\n , U\n , V\n ) += (visC * gcfC).unpack(rcmplx)\n ;\n\n uvg.bound(cmplx, 0, _CMPLX_SIZE);\n uvg.bound(x, 0, grid_size);\n uvg.bound(y, 0, grid_size);\n\n std::vector<Halide::Argument> compile_args = {\n scale\n , wstep\n , num_of_baselines\n , ts_ch\n , vismap\n , uvwf\n , vis\n , gcf_layer_size\n , gcf\n };\n uvg.compile_to_lowered_stmt(\"uvg11.html\", compile_args, HTML);\n uvg.compile_to_file(\n \"uvg11_full\"\n , compile_args\n , get_target_from_environment()\n .with_feature(Target::CUDA)\n .with_feature(Target::CUDACapability35)\n );\n}\n<commit_msg>Forgot to turn baseline mapping on.<commit_after>#include \"Halide.h\"\n\n#include <utility>\n#include <vector>\n\nusing namespace Halide;\n\nconst Expr\n _REAL = 0\n , _IMAG = 1\n ;\n\t\t\nconst int _CMPLX_SIZE = 2;\n\nstruct Complex {\n Expr real, imag;\n Complex(Expr r, Expr i) : real(r), imag(i) {}\n Complex operator+(const Complex &other) const {\n return{ real + other.real, imag + other.imag };\n }\n Complex operator*(const Complex &other) const {\n return{\n real * other.real - imag * other.imag\n , real * other.imag + imag * other.real\n };\n }\n Expr unpack(Expr c) { return select(c == _REAL, real, imag); }\n};\n\n\/* Not need it ATM\ninline Func flushAndContinue(const char * new_name, Func & f) {\n Func ret(new_name);\n f.compute_root();\n ret(f.args()) = f(f.args());\n return ret;\n}\n*\/\n\n#define P(a) a(#a)\n#define IP(a,b,c) a(b,c,#a)\n\n\/\/ We generate the kernel for GPU which works on the subset of baselines\n\/\/ having the same convolution size as we did in MS3.\n\/\/ But we also simplify the algorithm a bit using\n\/\/ GCF-per-baseline (with the size equal to convolution size)\n\/\/ instead of GCF-per-point approach.\n\/\/ We've done this for all halide_scatter_1bl_1gcf... family of gridders.\nint main(\/* int argc, char **argv *\/) {\n int\n over = 8\n , grid_size = 2048\n , max_gcf_size = 128\n ;\n\n Param<double>\n P(scale)\n , P(wstep)\n ;\n Param<int>\n P(gcf_layer_size)\n , P(num_of_baselines)\n , P(ts_ch)\n ;\n ImageParam IP(uvwf, type_of<double>(), 3);\n ImageParam IP(vis, type_of<double>(), 3);\n ImageParam IP(gcf, type_of<double>(), 2);\n ImageParam IP(vismap, type_of<int>(), 1);\n\n Func\n P(uvs)\n , P(uv)\n , P(overc)\n , P(gcfoff)\n , P(bloff)\n ;\n\n Var P(t)\n , P(uvdim)\n , P(bl)\n ;\n const Expr\n _U = 0\n , _V = 1\n ;\n \n uvs(uvdim, t, bl) = uvwf(uvdim, t, bl) * scale;\n overc(uvdim, t, bl) = clamp(cast<int>(round(over * (uvs(uvdim, t, bl) - floor(uvs(uvdim, t, bl))))), 0, 7);\n uv(uvdim, t, bl) = cast<int>(round(uvs(uvdim, t, bl)) + grid_size \/ 2 - gcf_layer_size \/ 2);\n gcfoff(t, bl) = (overc(_U, t, bl) * over + overc(_V, t, bl)) * gcf_layer_size * gcf_layer_size;\n bloff(bl) = clamp(ts_ch * vismap(bl), 0, ts_ch * num_of_baselines);\n\n RDom red(\n 0, _CMPLX_SIZE\n , 0, gcf_layer_size\n , 0, ts_ch\n , 0, gcf_layer_size\n , 0, num_of_baselines\n );\n RVar P(rcmplx), P(rgcfx), P(rvis), P(rgcfy), P(rbl0);\n rcmplx = red.x;\n rgcfx = red.y;\n rvis = red.z;\n rgcfy = red.w;\n rbl0 = red[4];\n Expr rbl = bloff(rbl0);\n\n Expr gcf_pix_off = gcfoff(rvis, rbl) + rgcfx + rgcfy * gcf_layer_size; \n Complex gcfC(\n gcf(_REAL, gcf_pix_off)\n , gcf(_IMAG, gcf_pix_off)\n );\n\n Complex visC(\n vis(_REAL, rvis, rbl)\n , vis(_IMAG, rvis, rbl)\n );\n\n Func P(uvg);\n Var P(cmplx)\n , P(x)\n , P(y)\n ;\n uvg(cmplx, x, y) = undef<double>();\n\n Expr\n clampedU = clamp(uv(_U, rvis, rbl), 0, grid_size - 1 - max_gcf_size)\n , clampedV = clamp(uv(_V, rvis, rbl), 0, grid_size - 1 - max_gcf_size)\n , U = clampedU + rgcfx\n , V = clampedV + rgcfy\n ;\n\n uvg(\n rcmplx\n , U\n , V\n ) += (visC * gcfC).unpack(rcmplx)\n ;\n\n uvg.bound(cmplx, 0, _CMPLX_SIZE);\n uvg.bound(x, 0, grid_size);\n uvg.bound(y, 0, grid_size);\n\n std::vector<Halide::Argument> compile_args = {\n scale\n , wstep\n , num_of_baselines\n , ts_ch\n , vismap\n , uvwf\n , vis\n , gcf_layer_size\n , gcf\n };\n uvg.compile_to_lowered_stmt(\"uvg11.html\", compile_args, HTML);\n uvg.compile_to_file(\n \"uvg11_full\"\n , compile_args\n , get_target_from_environment()\n .with_feature(Target::CUDA)\n .with_feature(Target::CUDACapability35)\n );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\n\/\/ OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#include \"api\/util.hpp\"\n#include \"core\/memory.hpp\"\n#include \"core\/format.hpp\"\n\nusing namespace clover;\n\nPUBLIC cl_mem\nclCreateBuffer(cl_context ctx, cl_mem_flags flags, size_t size,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!size)\n throw error(CL_INVALID_BUFFER_SIZE);\n\n if (flags & ~(CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new root_buffer(*ctx, flags, size, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateSubBuffer(cl_mem obj, cl_mem_flags flags, cl_buffer_create_type op,\n const void *op_info, cl_int *errcode_ret) try {\n root_buffer *parent = dynamic_cast<root_buffer *>(obj);\n\n if (!parent)\n throw error(CL_INVALID_MEM_OBJECT);\n\n if ((flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)) ||\n (~flags & parent->flags() & (CL_MEM_READ_ONLY |\n CL_MEM_WRITE_ONLY)))\n throw error(CL_INVALID_VALUE);\n\n if (op == CL_BUFFER_CREATE_TYPE_REGION) {\n const cl_buffer_region *reg = (const cl_buffer_region *)op_info;\n\n if (!reg ||\n reg->origin > parent->size() ||\n reg->origin + reg->size > parent->size())\n throw error(CL_INVALID_VALUE);\n\n if (!reg->size)\n throw error(CL_INVALID_BUFFER_SIZE);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new sub_buffer(*parent, flags, reg->origin, reg->size);\n\n } else {\n throw error(CL_INVALID_VALUE);\n }\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateImage2D(cl_context ctx, cl_mem_flags flags,\n const cl_image_format *format,\n size_t width, size_t height, size_t row_pitch,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!format)\n throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);\n\n if (width < 1 || height < 1)\n throw error(CL_INVALID_IMAGE_SIZE);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE2D).count(*format))\n throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new image2d(*ctx, flags, format, width, height,\n row_pitch, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateImage3D(cl_context ctx, cl_mem_flags flags,\n const cl_image_format *format,\n size_t width, size_t height, size_t depth,\n size_t row_pitch, size_t slice_pitch,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!format)\n throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);\n\n if (width < 1 || height < 1 || depth < 2)\n throw error(CL_INVALID_IMAGE_SIZE);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE3D).count(*format))\n throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new image3d(*ctx, flags, format, width, height, depth,\n row_pitch, slice_pitch, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_int\nclGetSupportedImageFormats(cl_context ctx, cl_mem_flags flags,\n cl_mem_object_type type, cl_uint count,\n cl_image_format *buf, cl_uint *count_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!count && buf)\n throw error(CL_INVALID_VALUE);\n\n auto formats = supported_formats(ctx, type);\n\n if (buf)\n std::copy_n(formats.begin(), std::min((cl_uint)formats.size(), count),\n buf);\n if (count_ret)\n *count_ret = formats.size();\n\n return CL_SUCCESS;\n\n} catch (error &e) {\n return e.get();\n}\n\nPUBLIC cl_int\nclGetMemObjectInfo(cl_mem obj, cl_mem_info param,\n size_t size, void *buf, size_t *size_ret) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n switch (param) {\n case CL_MEM_TYPE:\n return scalar_property<cl_mem_object_type>(buf, size, size_ret,\n obj->type());\n\n case CL_MEM_FLAGS:\n return scalar_property<cl_mem_flags>(buf, size, size_ret, obj->flags());\n\n case CL_MEM_SIZE:\n return scalar_property<size_t>(buf, size, size_ret, obj->size());\n\n case CL_MEM_HOST_PTR:\n return scalar_property<void *>(buf, size, size_ret, obj->host_ptr());\n\n case CL_MEM_MAP_COUNT:\n return scalar_property<cl_uint>(buf, size, size_ret, 0);\n\n case CL_MEM_REFERENCE_COUNT:\n return scalar_property<cl_uint>(buf, size, size_ret, obj->ref_count());\n\n case CL_MEM_CONTEXT:\n return scalar_property<cl_context>(buf, size, size_ret, &obj->ctx);\n\n case CL_MEM_ASSOCIATED_MEMOBJECT: {\n sub_buffer *sub = dynamic_cast<sub_buffer *>(obj);\n return scalar_property<cl_mem>(buf, size, size_ret,\n (sub ? &sub->parent : NULL));\n }\n case CL_MEM_OFFSET: {\n sub_buffer *sub = dynamic_cast<sub_buffer *>(obj);\n return scalar_property<size_t>(buf, size, size_ret,\n (sub ? sub->offset() : 0));\n }\n default:\n return CL_INVALID_VALUE;\n }\n}\n\nPUBLIC cl_int\nclGetImageInfo(cl_mem obj, cl_image_info param,\n size_t size, void *buf, size_t *size_ret) {\n image *img = dynamic_cast<image *>(obj);\n if (!img)\n return CL_INVALID_MEM_OBJECT;\n\n switch (param) {\n case CL_IMAGE_FORMAT:\n return scalar_property<cl_image_format>(buf, size, size_ret,\n img->format());\n\n case CL_IMAGE_ELEMENT_SIZE:\n return scalar_property<size_t>(buf, size, size_ret, 0);\n\n case CL_IMAGE_ROW_PITCH:\n return scalar_property<size_t>(buf, size, size_ret, img->row_pitch());\n\n case CL_IMAGE_SLICE_PITCH:\n return scalar_property<size_t>(buf, size, size_ret, img->slice_pitch());\n\n case CL_IMAGE_WIDTH:\n return scalar_property<size_t>(buf, size, size_ret, img->width());\n\n case CL_IMAGE_HEIGHT:\n return scalar_property<size_t>(buf, size, size_ret, img->height());\n\n case CL_IMAGE_DEPTH:\n return scalar_property<size_t>(buf, size, size_ret, img->depth());\n\n default:\n return CL_INVALID_VALUE;\n }\n}\n\nPUBLIC cl_int\nclRetainMemObject(cl_mem obj) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n obj->retain();\n return CL_SUCCESS;\n}\n\nPUBLIC cl_int\nclReleaseMemObject(cl_mem obj) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n if (obj->release())\n delete obj;\n\n return CL_SUCCESS;\n}\n\nPUBLIC cl_int\nclSetMemObjectDestructorCallback(cl_mem obj,\n void (CL_CALLBACK *pfn_notify)(cl_mem, void *),\n void *user_data) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n if (!pfn_notify)\n return CL_INVALID_VALUE;\n\n obj->destroy_notify([=]{ pfn_notify(obj, user_data); });\n\n return CL_SUCCESS;\n}\n<commit_msg>clover: Accept CL_MEM_READ_WRITE flag<commit_after>\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\n\/\/ OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#include \"api\/util.hpp\"\n#include \"core\/memory.hpp\"\n#include \"core\/format.hpp\"\n\nusing namespace clover;\n\nPUBLIC cl_mem\nclCreateBuffer(cl_context ctx, cl_mem_flags flags, size_t size,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!size)\n throw error(CL_INVALID_BUFFER_SIZE);\n\n if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new root_buffer(*ctx, flags, size, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateSubBuffer(cl_mem obj, cl_mem_flags flags, cl_buffer_create_type op,\n const void *op_info, cl_int *errcode_ret) try {\n root_buffer *parent = dynamic_cast<root_buffer *>(obj);\n\n if (!parent)\n throw error(CL_INVALID_MEM_OBJECT);\n\n if ((flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)) ||\n (~flags & parent->flags() & (CL_MEM_READ_ONLY |\n CL_MEM_WRITE_ONLY)))\n throw error(CL_INVALID_VALUE);\n\n if (op == CL_BUFFER_CREATE_TYPE_REGION) {\n const cl_buffer_region *reg = (const cl_buffer_region *)op_info;\n\n if (!reg ||\n reg->origin > parent->size() ||\n reg->origin + reg->size > parent->size())\n throw error(CL_INVALID_VALUE);\n\n if (!reg->size)\n throw error(CL_INVALID_BUFFER_SIZE);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new sub_buffer(*parent, flags, reg->origin, reg->size);\n\n } else {\n throw error(CL_INVALID_VALUE);\n }\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateImage2D(cl_context ctx, cl_mem_flags flags,\n const cl_image_format *format,\n size_t width, size_t height, size_t row_pitch,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!format)\n throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);\n\n if (width < 1 || height < 1)\n throw error(CL_INVALID_IMAGE_SIZE);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE2D).count(*format))\n throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new image2d(*ctx, flags, format, width, height,\n row_pitch, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_mem\nclCreateImage3D(cl_context ctx, cl_mem_flags flags,\n const cl_image_format *format,\n size_t width, size_t height, size_t depth,\n size_t row_pitch, size_t slice_pitch,\n void *host_ptr, cl_int *errcode_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!format)\n throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);\n\n if (width < 1 || height < 1 || depth < 2)\n throw error(CL_INVALID_IMAGE_SIZE);\n\n if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR |\n CL_MEM_COPY_HOST_PTR)))\n throw error(CL_INVALID_HOST_PTR);\n\n if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE3D).count(*format))\n throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED);\n\n ret_error(errcode_ret, CL_SUCCESS);\n return new image3d(*ctx, flags, format, width, height, depth,\n row_pitch, slice_pitch, host_ptr);\n\n} catch (error &e) {\n ret_error(errcode_ret, e);\n return NULL;\n}\n\nPUBLIC cl_int\nclGetSupportedImageFormats(cl_context ctx, cl_mem_flags flags,\n cl_mem_object_type type, cl_uint count,\n cl_image_format *buf, cl_uint *count_ret) try {\n if (!ctx)\n throw error(CL_INVALID_CONTEXT);\n\n if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY |\n CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR |\n CL_MEM_COPY_HOST_PTR))\n throw error(CL_INVALID_VALUE);\n\n if (!count && buf)\n throw error(CL_INVALID_VALUE);\n\n auto formats = supported_formats(ctx, type);\n\n if (buf)\n std::copy_n(formats.begin(), std::min((cl_uint)formats.size(), count),\n buf);\n if (count_ret)\n *count_ret = formats.size();\n\n return CL_SUCCESS;\n\n} catch (error &e) {\n return e.get();\n}\n\nPUBLIC cl_int\nclGetMemObjectInfo(cl_mem obj, cl_mem_info param,\n size_t size, void *buf, size_t *size_ret) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n switch (param) {\n case CL_MEM_TYPE:\n return scalar_property<cl_mem_object_type>(buf, size, size_ret,\n obj->type());\n\n case CL_MEM_FLAGS:\n return scalar_property<cl_mem_flags>(buf, size, size_ret, obj->flags());\n\n case CL_MEM_SIZE:\n return scalar_property<size_t>(buf, size, size_ret, obj->size());\n\n case CL_MEM_HOST_PTR:\n return scalar_property<void *>(buf, size, size_ret, obj->host_ptr());\n\n case CL_MEM_MAP_COUNT:\n return scalar_property<cl_uint>(buf, size, size_ret, 0);\n\n case CL_MEM_REFERENCE_COUNT:\n return scalar_property<cl_uint>(buf, size, size_ret, obj->ref_count());\n\n case CL_MEM_CONTEXT:\n return scalar_property<cl_context>(buf, size, size_ret, &obj->ctx);\n\n case CL_MEM_ASSOCIATED_MEMOBJECT: {\n sub_buffer *sub = dynamic_cast<sub_buffer *>(obj);\n return scalar_property<cl_mem>(buf, size, size_ret,\n (sub ? &sub->parent : NULL));\n }\n case CL_MEM_OFFSET: {\n sub_buffer *sub = dynamic_cast<sub_buffer *>(obj);\n return scalar_property<size_t>(buf, size, size_ret,\n (sub ? sub->offset() : 0));\n }\n default:\n return CL_INVALID_VALUE;\n }\n}\n\nPUBLIC cl_int\nclGetImageInfo(cl_mem obj, cl_image_info param,\n size_t size, void *buf, size_t *size_ret) {\n image *img = dynamic_cast<image *>(obj);\n if (!img)\n return CL_INVALID_MEM_OBJECT;\n\n switch (param) {\n case CL_IMAGE_FORMAT:\n return scalar_property<cl_image_format>(buf, size, size_ret,\n img->format());\n\n case CL_IMAGE_ELEMENT_SIZE:\n return scalar_property<size_t>(buf, size, size_ret, 0);\n\n case CL_IMAGE_ROW_PITCH:\n return scalar_property<size_t>(buf, size, size_ret, img->row_pitch());\n\n case CL_IMAGE_SLICE_PITCH:\n return scalar_property<size_t>(buf, size, size_ret, img->slice_pitch());\n\n case CL_IMAGE_WIDTH:\n return scalar_property<size_t>(buf, size, size_ret, img->width());\n\n case CL_IMAGE_HEIGHT:\n return scalar_property<size_t>(buf, size, size_ret, img->height());\n\n case CL_IMAGE_DEPTH:\n return scalar_property<size_t>(buf, size, size_ret, img->depth());\n\n default:\n return CL_INVALID_VALUE;\n }\n}\n\nPUBLIC cl_int\nclRetainMemObject(cl_mem obj) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n obj->retain();\n return CL_SUCCESS;\n}\n\nPUBLIC cl_int\nclReleaseMemObject(cl_mem obj) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n if (obj->release())\n delete obj;\n\n return CL_SUCCESS;\n}\n\nPUBLIC cl_int\nclSetMemObjectDestructorCallback(cl_mem obj,\n void (CL_CALLBACK *pfn_notify)(cl_mem, void *),\n void *user_data) {\n if (!obj)\n return CL_INVALID_MEM_OBJECT;\n\n if (!pfn_notify)\n return CL_INVALID_VALUE;\n\n obj->destroy_notify([=]{ pfn_notify(obj, user_data); });\n\n return CL_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"CoolProp.h\"\n#include <vector>\n#include \"CPExceptions.h\"\n#include \"FluidClass.h\"\n#include \"R161.h\"\n\nR161Class::R161Class()\n{\n\tdouble n[] = {0.0, 1.511, -2.3, -0.457, 0.1683, 0.04133, 0.62187, -0.0265, -1.03, -0.285, -0.476, 0.82, -0.3532, -0.116, -0.0220583, -1.63148};\n\tdouble t[] = {0, 0.37, 0.97, 1.14, 0.744, 1, 1.26, 1, 1.8, 3, 2.25, 1, 1.2, 5.3, 1, 4};\n\tdouble d[] = {0, 1, 1, 2, 3, 4, 2, 7, 1, 2, 3, 1, 1, 3, 3, 3};\n\tdouble c[] = {0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0};\n\tdouble eta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.96, 1.35, 1.26, 1.23, 16.8};\n\tdouble beta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7, 5.2, 3.9, 4.7, 413};\n\tdouble gamma[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.9, 0.69, 0.67, 0.67, 1.15};\n\tdouble epsilon[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.683, 0.892, 0.785, 1.33, 0.86};\n\n\t\/\/Critical parameters\n\tcrit.rho = 6.28*48.0595; \/\/[kg\/m^3]\n\tcrit.p = PressureUnit(5010, UNIT_KPA); \/\/[kPa]\n\tcrit.T = 375.25; \/\/[K]\n\tcrit.v = 1\/crit.rho; \n\n\t\/\/ Other fluid parameters\n\tparams.molemass = 48.0595;\n\tparams.Ttriple = 130;\n\tparams.accentricfactor = 0.21624284106618674;\n\tparams.R_u = 8.314472;\n\tparams.ptriple = 0.005512;\n\n\t\/\/ Limits of EOS\n\tlimits.Tmin = 130;\n\tlimits.Tmax = 500.0;\n\tlimits.pmax = 100000.0;\n\tlimits.rhomax = 1000000.0*params.molemass;\n\n\tphirlist.push_back(new phir_power( n,d,t,c,1,10,16));\n\tphirlist.push_back(new phir_gaussian( n,d,t, eta, epsilon, beta, gamma, 11,15,16));\n\n\tconst double a0 = -6.9187, a1 = 5.4788, n0 = 4;\n\tphi0list.push_back(new phi0_lead(a0, a1));\n\tphi0list.push_back(new phi0_logtau(n0-1));\n\n\tconst double u0[] = {0, 420\/crit.T, 1548\/crit.T, 3882\/crit.T};\n\tconst double v0[] = {0, 2.059, 9.253, 6.088};\n\tstd::vector<double> u0_v(u0,u0+sizeof(u0)\/sizeof(double));\n\tstd::vector<double> v0_v(v0,v0+sizeof(v0)\/sizeof(double));\n\n\tphi0list.push_back(new phi0_Planck_Einstein(v0_v,u0_v,1,3));\n\n\tEOSReference.assign(\"Jiangtao Wu and Yong Zhou, \\\"An Equation of State for Fluoroethane (R161)\\\", Int J Thermophys (2012) 33:220�234\");\n\tTransportReference.assign(\"Using ECS in fully predictive mode.\");\n\n\tname.assign(\"R161\");\n\t\/\/aliases.push_back(std::string(\"R161\"));\n\tREFPROPname.assign(\"R161\");\n\n\tBibTeXKeys.EOS = \"Wu-IJT-2012\";\n\tBibTeXKeys.SURFACE_TENSION = \"Mulero-JPCRD-2012\";\n}\ndouble R161Class::psat(double T)\n{\n\t\/\/ Max error is 0.230661857744 % between 130.0 and 375.249999 K\n const double t[]={0, 0.3575, 0.3605, 0.8333333333333334, 1.1666666666666667, 3.6666666666666665, 5.5};\n const double N[]={0, 0.31348208716072901, -0.23919030666253932, -3.2448016166944127, -3.2492132423845081, -1.5585118618296889, -2.427095112126342};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n for (int i=1; i<=6; i++)\n {\n summer += N[i]*pow(theta,t[i]);\n }\n return reduce.p.Pa*exp(reduce.T\/T*summer);\n}\n\ndouble R161Class::rhosatL(double T)\n{\n \/\/ Maximum absolute error is 0.240076 % between 130.000000 K and 375.250000 K\n const double t[] = {0, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0, 1.1666666666666667, 1.3333333333333333, 1.5, 1.6666666666666667, 1.8333333333333333, 2.0};\n const double N[] = {0, -0.047548020147135293, 72.327097393829419, -819.54669834482479, 4946.726597164351, -18870.150565849312, 48463.342332873617, -84949.003918399481, 99927.349954656311, -75150.383145190368, 32522.693777539549, -6140.6005518003303};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n\tfor (int i=1; i<=11; i++)\n\t{\n\t\tsummer += N[i]*pow(theta,t[i]);\n\t}\n\treturn reduce.rho*(summer+1);\n}\n\ndouble R161Class::rhosatV(double T)\n{\n \/\/ Maximum absolute error is 0.294100 % between 130.000000 K and 375.250000 K\n const double t[] = {0, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0, 1.1666666666666667, 1.3333333333333333, 1.5, 1.6666666666666667, 1.8333333333333333, 2.0, 2.1666666666666665};\n const double N[] = {0, 4.4900108859020449, -289.55507432056027, 4058.7708236096973, -29986.440551303382, 137204.7283140849, -417289.03201597766, 870535.22359268588, -1255033.5731927676, 1232137.9562410619, -787892.80993800913, 296355.72520564846, -49815.743244828758};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n\tfor (int i=1; i<=12; i++)\n\t{\n\t\tsummer += N[i]*pow(theta,t[i]);\n\t}\n\treturn reduce.rho*exp(reduce.T\/T*summer);\n}\n<commit_msg>Added alias to old R161 file<commit_after>#include \"CoolProp.h\"\n#include <vector>\n#include \"CPExceptions.h\"\n#include \"FluidClass.h\"\n#include \"R161.h\"\n\nR161Class::R161Class()\n{\n\tdouble n[] = {0.0, 1.511, -2.3, -0.457, 0.1683, 0.04133, 0.62187, -0.0265, -1.03, -0.285, -0.476, 0.82, -0.3532, -0.116, -0.0220583, -1.63148};\n\tdouble t[] = {0, 0.37, 0.97, 1.14, 0.744, 1, 1.26, 1, 1.8, 3, 2.25, 1, 1.2, 5.3, 1, 4};\n\tdouble d[] = {0, 1, 1, 2, 3, 4, 2, 7, 1, 2, 3, 1, 1, 3, 3, 3};\n\tdouble c[] = {0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0};\n\tdouble eta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.96, 1.35, 1.26, 1.23, 16.8};\n\tdouble beta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.7, 5.2, 3.9, 4.7, 413};\n\tdouble gamma[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.9, 0.69, 0.67, 0.67, 1.15};\n\tdouble epsilon[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.683, 0.892, 0.785, 1.33, 0.86};\n\n\t\/\/Critical parameters\n\tcrit.rho = 6.28*48.0595; \/\/[kg\/m^3]\n\tcrit.p = PressureUnit(5010, UNIT_KPA); \/\/[kPa]\n\tcrit.T = 375.25; \/\/[K]\n\tcrit.v = 1\/crit.rho; \n\n\t\/\/ Other fluid parameters\n\tparams.molemass = 48.0595;\n\tparams.Ttriple = 130;\n\tparams.accentricfactor = 0.21624284106618674;\n\tparams.R_u = 8.314472;\n\tparams.ptriple = 0.005512;\n\n\t\/\/ Limits of EOS\n\tlimits.Tmin = 130;\n\tlimits.Tmax = 500.0;\n\tlimits.pmax = 100000.0;\n\tlimits.rhomax = 1000000.0*params.molemass;\n\n\tphirlist.push_back(new phir_power( n,d,t,c,1,10,16));\n\tphirlist.push_back(new phir_gaussian( n,d,t, eta, epsilon, beta, gamma, 11,15,16));\n\n\tconst double a0 = -6.9187, a1 = 5.4788, n0 = 4;\n\tphi0list.push_back(new phi0_lead(a0, a1));\n\tphi0list.push_back(new phi0_logtau(n0-1));\n\n\tconst double u0[] = {0, 420\/crit.T, 1548\/crit.T, 3882\/crit.T};\n\tconst double v0[] = {0, 2.059, 9.253, 6.088};\n\n\tphi0list.push_back(new phi0_Planck_Einstein(v0,u0,1,3,4));\n\n\tEOSReference.assign(\"Jiangtao Wu and Yong Zhou, \\\"An Equation of State for Fluoroethane (R161)\\\", Int J Thermophys (2012) 33:220�234\");\n\tTransportReference.assign(\"Using ECS in fully predictive mode.\");\n\n\tname.assign(\"R161\");\n\taliases.push_back(std::string(\"Fluoroethane\"));\n\tREFPROPname.assign(\"R161\");\n\n\tBibTeXKeys.EOS = \"Wu-IJT-2012\";\n\tBibTeXKeys.SURFACE_TENSION = \"Mulero-JPCRD-2012\";\n}\ndouble R161Class::psat(double T)\n{\n\t\/\/ Max error is 0.230661857744 % between 130.0 and 375.249999 K\n const double t[]={0, 0.3575, 0.3605, 0.8333333333333334, 1.1666666666666667, 3.6666666666666665, 5.5};\n const double N[]={0, 0.31348208716072901, -0.23919030666253932, -3.2448016166944127, -3.2492132423845081, -1.5585118618296889, -2.427095112126342};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n for (int i=1; i<=6; i++)\n {\n summer += N[i]*pow(theta,t[i]);\n }\n return reduce.p.Pa*exp(reduce.T\/T*summer);\n}\n\ndouble R161Class::rhosatL(double T)\n{\n \/\/ Maximum absolute error is 0.240076 % between 130.000000 K and 375.250000 K\n const double t[] = {0, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0, 1.1666666666666667, 1.3333333333333333, 1.5, 1.6666666666666667, 1.8333333333333333, 2.0};\n const double N[] = {0, -0.047548020147135293, 72.327097393829419, -819.54669834482479, 4946.726597164351, -18870.150565849312, 48463.342332873617, -84949.003918399481, 99927.349954656311, -75150.383145190368, 32522.693777539549, -6140.6005518003303};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n\tfor (int i=1; i<=11; i++)\n\t{\n\t\tsummer += N[i]*pow(theta,t[i]);\n\t}\n\treturn reduce.rho*(summer+1);\n}\n\ndouble R161Class::rhosatV(double T)\n{\n \/\/ Maximum absolute error is 0.294100 % between 130.000000 K and 375.250000 K\n const double t[] = {0, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0, 1.1666666666666667, 1.3333333333333333, 1.5, 1.6666666666666667, 1.8333333333333333, 2.0, 2.1666666666666665};\n const double N[] = {0, 4.4900108859020449, -289.55507432056027, 4058.7708236096973, -29986.440551303382, 137204.7283140849, -417289.03201597766, 870535.22359268588, -1255033.5731927676, 1232137.9562410619, -787892.80993800913, 296355.72520564846, -49815.743244828758};\n double summer=0,theta;\n theta=1-T\/reduce.T;\n\tfor (int i=1; i<=12; i++)\n\t{\n\t\tsummer += N[i]*pow(theta,t[i]);\n\t}\n\treturn reduce.rho*exp(reduce.T\/T*summer);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Inspired by http:\/\/opencv-srf.blogspot.com\/2010\/09\/object-detection-using-color-seperation.html\n#include \"CMultiTrackerApp.h\"\n\nstatic \tTColorData\t\t\t\t_colorCal;\n\nCMultiTrackerApp::CMultiTrackerApp( char **argv )\n\t: _cap( atoi( argv[1] ) )\n\t, _controlWindow( argv[2] )\n\t, m_trackedObjects( 0 )\n{\n\t_calibrationData.blue.colorId \t= \"blue\";\n\t_calibrationData.orange.colorId = \"orange\";\n\t_calibrationData.purple.colorId = \"purple\";\n\t_calibrationData.yellow.colorId = \"yellow\";\n\t_calibrationData.green.colorId \t= \"green\";\n\t_calibrationData.red.colorId \t= \"red\";\n\n}\n\nCMultiTrackerApp::~CMultiTrackerApp()\n{\n\n}\n\nbool CMultiTrackerApp::Initialize()\n{\n\n\t\/\/ Set blob parameters\n\t_params.minThreshold \t\t= 10;\n\t_params.maxThreshold \t\t= 200;\n\n\t_params.filterByArea \t\t= true;\n\t_params.minArea \t\t\t= 1500;\n\n\t_params.filterByCircularity = true;\n\t_params.minCircularity \t\t= 0.1;\n\n\t_params.filterByConvexity \t= true;\n\t_params.minConvexity \t\t= 0.87;\n\n\t_params.filterByInertia \t= true;\n\t_params.minInertiaRatio \t= 0.01;\n\n\t\/\/ Init detector with params\n\t_detector = cv::SimpleBlobDetector::create( _params );\n\t\/\/ _detector->detect( image, keyPoints ); \/\/ detect blob\n\n\t\/\/ We use this private class variable to disallow active changes to the calibration.\n\t\/\/ If we use the _calibrationData structure for calibration and adjustment in real time, we have to retrain\n\t\/\/ at this time.\n\t_colorCal.colorId = \"init\";\n\n\t_colorCal.lowH \t= 0;\n\t_colorCal.highH = 179;\n\n\t_colorCal.lowS \t= 0;\n\t_colorCal.highS = 255;\n\n\t_colorCal.lowV \t= 0;\n\t_colorCal.highV = 255;\n\n\t\/\/ Set control window\n\tcv::namedWindow( _controlWindow, CV_WINDOW_AUTOSIZE);\n\n\t\/\/ track bars for HSV tuning\n\tcv::createTrackbar( \"LowH\", _controlWindow, &_colorCal.lowH, 179 );\n\tcv::createTrackbar( \"HighH\", _controlWindow, &_colorCal.highH, 179 );\n\n\tcv::createTrackbar( \"LowS\", _controlWindow, &_colorCal.lowS, 255 );\n\tcv::createTrackbar( \"HighS\", _controlWindow, &_colorCal.highS, 255 );\n\n\tcv::createTrackbar( \"LowV\", _controlWindow, &_colorCal.lowV, 255 );\n\tcv::createTrackbar( \"HighV\", _controlWindow, &_colorCal.highV, 255 );\n\n\t\/\/ Buttons for color calibration\n\tcv::createButton( \"Orange\", CalibrateHSV, &_calibrationData.orange, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Blue\", CalibrateHSV, &_calibrationData.blue, CV_PUSH_BUTTON, 0 );\n\n\tcv::createButton( \"Red\", CalibrateHSV, &_calibrationData.red, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Purple\", CalibrateHSV, &_calibrationData.purple, CV_PUSH_BUTTON, 0 );\n\n\tcv::createButton( \"Yellow\", CalibrateHSV, &_calibrationData.yellow, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Green\", CalibrateHSV, &_calibrationData.green, CV_PUSH_BUTTON, 0 );\n\n\treturn true;\n}\n\nvoid CMultiTrackerApp::CalibrateHSV( int stateIn, void *userDataIn )\n{\n\tTColorData *calData = (TColorData*)userDataIn;\n\n\tLOG( INFO ) << \"Calibratiing: \" << calData->colorId;\n\n\tcalData->lowH \t= _colorCal.lowH;\n\tcalData->highH \t= _colorCal.highH;\n\n\tcalData->lowS \t= _colorCal.lowS;\n\tcalData->highS \t= _colorCal.highS;\n\n\tcalData->lowV \t= _colorCal.lowV;\n\tcalData->highV\t= _colorCal.highV;\n\n}\n\nvoid CMultiTrackerApp::Run()\n{\n\/\/\twhile( true )\n\/\/\t{\n\t\tif( !_cap.read( _origImage ) )\n\t\t{\n\t\t\tLOG( ERROR ) << \">>>> Could not read from video stream: CLOSING <<<<\";\n\/\/\t\t\tbreak;\n\t\t}\n\t\tcv::Mat im = cv::imread( \"roboops_test_image.png\", cv::IMREAD_COLOR );\n\n\t\tcv::cvtColor( im, _imageHSV, cv::COLOR_BGR2HSV );\n\n\n\n\t\tcv::threshold( _imageHSV, _imageThreshold, 127, 255, cv::THRESH_TOZERO );\n\n\t\t\/\/ Morph open - remove small objects from the foreground\n\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\n\t\t\/\/ Morph close - fill small holes in foreground\n\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\n\t\t\/\/ Detect the blobs\n\t\t_detector->detect( _imageThreshold, _keyPoints );\n\n\t\t\/\/ Draw blobs as red circles\n\t\t\/\/ flags ensures the size of the circle corresponds to the size of the blob\n\t\tcv::Mat _imageKeypoints;\n\n\t\tcv::drawKeypoints( _imageThreshold, _keyPoints, _imageKeypoints, cv::Scalar( 0, 0, 255 ), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS );\n\n\/\/\t\t_linesImage = cv::Mat::zeros( _origImage.size(), CV_8UC3 );\n\/\/\t\tfor( std::vector<TTrackObject>::iterator itr = m_trackedObjects.begin(); itr != m_trackedObjects.end(); ++itr)\n\/\/\t\t{\n\/\/\n\/\/\n\/\/\t\t\t\/\/ Convert from BGR to HSV\n\/\/\t\t\tcv::cvtColor( _origImage, _imageHSV, cv::COLOR_BGR2HSV );\n\/\/\n\/\/\t\t\t\/\/ Threshold the image values\n\/\/\t\t\tcv::inRange( _imageHSV, cv::Scalar( itr->colorData.lowH, itr->colorData.lowS, itr->colorData.lowV ), cv::Scalar( itr->colorData.highH,\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titr->colorData.highS, itr->colorData.highV ), _imageThreshold );\n\/\/\n\/\/\t\t\t\/\/ Morph open - remove small objects from the foreground\n\/\/\t\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\t\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\n\/\/\t\t\t\/\/ Morph close - fill small holes in foreground\n\/\/\t\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\t\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\n\/\/\t\t\t\/\/ Moments ofthe threshold image for tracking\n\/\/\t\t\tcv::Moments imageMoments = cv::moments( _imageThreshold );\n\/\/\n\/\/\t\t\tm_trackedObjects[0].moments01 = imageMoments.m01;\n\/\/\t\t\tm_trackedObjects[0].moments10 = imageMoments.m10;\n\/\/\t\t\tm_trackedObjects[0].momentsArea = imageMoments.m00;\n\/\/\n\/\/\t\t\t\/\/ Noise threshold\n\/\/\t\t\tif( m_trackedObjects[0].momentsArea > 1000 )\n\/\/\t\t\t{\n\/\/\t\t\t\tm_trackedObjects[0].posX = m_trackedObjects[0].moments10 \/ m_trackedObjects[0].momentsArea;\n\/\/\t\t\t\tm_trackedObjects[0].posY = m_trackedObjects[0].moments01 \/ m_trackedObjects[0].momentsArea;\n\/\/\n\/\/\t\t\t\tif( m_trackedObjects[0].lastX >= 0 && m_trackedObjects[0].lastY >=0 && m_trackedObjects[0].posX >= 0 && m_trackedObjects[0].posY >= 0 )\n\/\/\t\t\t\t{\n\/\/\t\t\t\t\t\/\/ Draw a line from previous pose to current pose\n\/\/\t\t\t\t\tcv::line( _linesImage, cv::Point( m_trackedObjects[0].posX, m_trackedObjects[0].posY )\n\/\/\t\t\t\t\t\t\t\t, cv::Point( m_trackedObjects[0].lastX, m_trackedObjects[0].lastY ), cv::Scalar( 0, 0, 255 ), 2 );\n\/\/\t\t\t\t}\n\/\/\n\/\/\t\t\t\tm_trackedObjects[0].lastX = m_trackedObjects[0].posX;\n\/\/\t\t\t\tm_trackedObjects[0].lastY = m_trackedObjects[0].posY;\n\/\/\n\/\/\t\t\t\tcv::Scalar color = cv::Scalar( 94, 206, 165 );\n\/\/\n\/\/\t\t\t\tcv::circle( _origImage, cv::Point( m_trackedObjects[0].posX, m_trackedObjects[0].posY ), sqrt( m_trackedObjects[0].momentsArea\/3.14 )\/10, color, 0.5, 8, 0 );\n\/\/\t\t\t}\n\/\/\t\t}\n\t\t\/\/ Display the images\n\/\/\t\tcv::imshow( _controlWindow, _imageThreshold );\n\n\t\t\/\/ Display the combined image\n\/\/\t\t_origImage = _origImage + _linesImage;\n\n\/\/\t\tcv::imshow( \"Original-Image\", _origImage );\n\t\tcv::imshow( \"Blob-Image\", _imageKeypoints );\n\n\t\tif( cv::waitKey( 0 ) == 27 )\n\t\t{\n\t\t\tLOG( INFO ) << \">>>> Exiting <<<<\";\n\/\/\t\t\tbreak;\n\t\t}\n\/\/\t}\n}\n<commit_msg>replced threshold method with inRange<commit_after>\/\/ Inspired by http:\/\/opencv-srf.blogspot.com\/2010\/09\/object-detection-using-color-seperation.html\n#include \"CMultiTrackerApp.h\"\n\nstatic \tTColorData\t\t\t\t_colorCal;\n\nCMultiTrackerApp::CMultiTrackerApp( char **argv )\n\t: _cap( atoi( argv[1] ) )\n\t, _controlWindow( argv[2] )\n\t, m_trackedObjects( 0 )\n{\n\t_calibrationData.blue.colorId \t= \"blue\";\n\t_calibrationData.orange.colorId = \"orange\";\n\t_calibrationData.purple.colorId = \"purple\";\n\t_calibrationData.yellow.colorId = \"yellow\";\n\t_calibrationData.green.colorId \t= \"green\";\n\t_calibrationData.red.colorId \t= \"red\";\n\n}\n\nCMultiTrackerApp::~CMultiTrackerApp()\n{\n\n}\n\nbool CMultiTrackerApp::Initialize()\n{\n\n\t\/\/ Set blob parameters\n\t_params.minThreshold \t\t= 10;\n\t_params.maxThreshold \t\t= 200;\n\n\t_params.filterByArea \t\t= true;\n\t_params.minArea \t\t\t= 1500;\n\n\t_params.filterByCircularity = true;\n\t_params.minCircularity \t\t= 0.1;\n\n\t_params.filterByConvexity \t= true;\n\t_params.minConvexity \t\t= 0.87;\n\n\t_params.filterByInertia \t= true;\n\t_params.minInertiaRatio \t= 0.01;\n\n\t\/\/ Init detector with params\n\t_detector = cv::SimpleBlobDetector::create( _params );\n\t\/\/ _detector->detect( image, keyPoints ); \/\/ detect blob\n\n\t\/\/ We use this private class variable to disallow active changes to the calibration.\n\t\/\/ If we use the _calibrationData structure for calibration and adjustment in real time, we have to retrain\n\t\/\/ at this time.\n\t_colorCal.colorId = \"init\";\n\n\t_colorCal.lowH \t= 0;\n\t_colorCal.highH = 179;\n\n\t_colorCal.lowS \t= 0;\n\t_colorCal.highS = 255;\n\n\t_colorCal.lowV \t= 0;\n\t_colorCal.highV = 255;\n\n\t\/\/ Set control window\n\tcv::namedWindow( _controlWindow, CV_WINDOW_AUTOSIZE);\n\n\t\/\/ track bars for HSV tuning\n\tcv::createTrackbar( \"LowH\", _controlWindow, &_colorCal.lowH, 179 );\n\tcv::createTrackbar( \"HighH\", _controlWindow, &_colorCal.highH, 179 );\n\n\tcv::createTrackbar( \"LowS\", _controlWindow, &_colorCal.lowS, 255 );\n\tcv::createTrackbar( \"HighS\", _controlWindow, &_colorCal.highS, 255 );\n\n\tcv::createTrackbar( \"LowV\", _controlWindow, &_colorCal.lowV, 255 );\n\tcv::createTrackbar( \"HighV\", _controlWindow, &_colorCal.highV, 255 );\n\n\t\/\/ Buttons for color calibration\n\tcv::createButton( \"Orange\", CalibrateHSV, &_calibrationData.orange, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Blue\", CalibrateHSV, &_calibrationData.blue, CV_PUSH_BUTTON, 0 );\n\n\tcv::createButton( \"Red\", CalibrateHSV, &_calibrationData.red, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Purple\", CalibrateHSV, &_calibrationData.purple, CV_PUSH_BUTTON, 0 );\n\n\tcv::createButton( \"Yellow\", CalibrateHSV, &_calibrationData.yellow, CV_PUSH_BUTTON, 0 );\n\tcv::createButton( \"Green\", CalibrateHSV, &_calibrationData.green, CV_PUSH_BUTTON, 0 );\n\n\treturn true;\n}\n\nvoid CMultiTrackerApp::CalibrateHSV( int stateIn, void *userDataIn )\n{\n\tTColorData *calData = (TColorData*)userDataIn;\n\n\tLOG( INFO ) << \"Calibratiing: \" << calData->colorId;\n\n\tcalData->lowH \t= _colorCal.lowH;\n\tcalData->highH \t= _colorCal.highH;\n\n\tcalData->lowS \t= _colorCal.lowS;\n\tcalData->highS \t= _colorCal.highS;\n\n\tcalData->lowV \t= _colorCal.lowV;\n\tcalData->highV\t= _colorCal.highV;\n\n}\n\nvoid CMultiTrackerApp::Run()\n{\n\/\/\twhile( true )\n\/\/\t{\n\t\tif( !_cap.read( _origImage ) )\n\t\t{\n\t\t\tLOG( ERROR ) << \">>>> Could not read from video stream: CLOSING <<<<\";\n\/\/\t\t\tbreak;\n\t\t}\n\t\tcv::Mat im = cv::imread( \"roboops_test_image.png\", cv::IMREAD_COLOR );\n\n\t\tcv::cvtColor( im, _imageHSV, cv::COLOR_BGR2HSV );\n\n\/\/\t\tcv::threshold( _imageHSV, _imageThreshold, 127, 255, cv::THRESH_TOZERO );\n\n\t\tcv::inRange( _imageHSV, cv::Scalar( 70, 87, 42 ), cv::Scalar( 179, 255, 255 ), _imageThreshold );\n\n\t\t\/\/ Morph open - remove small objects from the foreground\n\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\n\t\t\/\/ Morph close - fill small holes in foreground\n\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\n\t\t\/\/ Detect the blobs\n\t\t_detector->detect( _imageThreshold, _keyPoints );\n\n\t\t\/\/ Draw blobs as red circles\n\t\t\/\/ flags ensures the size of the circle corresponds to the size of the blob\n\t\tcv::Mat _imageKeypoints;\n\n\t\tcv::drawKeypoints( _imageThreshold, _keyPoints, _imageKeypoints, cv::Scalar( 0, 0, 255 ), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS );\n\n\/\/\t\t_linesImage = cv::Mat::zeros( _origImage.size(), CV_8UC3 );\n\/\/\t\tfor( std::vector<TTrackObject>::iterator itr = m_trackedObjects.begin(); itr != m_trackedObjects.end(); ++itr)\n\/\/\t\t{\n\/\/\n\/\/\n\/\/\t\t\t\/\/ Convert from BGR to HSV\n\/\/\t\t\tcv::cvtColor( _origImage, _imageHSV, cv::COLOR_BGR2HSV );\n\/\/\n\/\/\t\t\t\/\/ Threshold the image values\n\/\/\t\t\tcv::inRange( _imageHSV, cv::Scalar( itr->colorData.lowH, itr->colorData.lowS, itr->colorData.lowV ), cv::Scalar( itr->colorData.highH,\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titr->colorData.highS, itr->colorData.highV ), _imageThreshold );\n\/\/\n\/\/\t\t\t\/\/ Morph open - remove small objects from the foreground\n\/\/\t\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\t\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\n\/\/\t\t\t\/\/ Morph close - fill small holes in foreground\n\/\/\t\t\tcv::dilate( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\t\t\tcv::erode( _imageThreshold, _imageThreshold, cv::getStructuringElement( cv::MORPH_ELLIPSE, cv::Size( 5, 5 ) ) );\n\/\/\n\/\/\t\t\t\/\/ Moments ofthe threshold image for tracking\n\/\/\t\t\tcv::Moments imageMoments = cv::moments( _imageThreshold );\n\/\/\n\/\/\t\t\tm_trackedObjects[0].moments01 = imageMoments.m01;\n\/\/\t\t\tm_trackedObjects[0].moments10 = imageMoments.m10;\n\/\/\t\t\tm_trackedObjects[0].momentsArea = imageMoments.m00;\n\/\/\n\/\/\t\t\t\/\/ Noise threshold\n\/\/\t\t\tif( m_trackedObjects[0].momentsArea > 1000 )\n\/\/\t\t\t{\n\/\/\t\t\t\tm_trackedObjects[0].posX = m_trackedObjects[0].moments10 \/ m_trackedObjects[0].momentsArea;\n\/\/\t\t\t\tm_trackedObjects[0].posY = m_trackedObjects[0].moments01 \/ m_trackedObjects[0].momentsArea;\n\/\/\n\/\/\t\t\t\tif( m_trackedObjects[0].lastX >= 0 && m_trackedObjects[0].lastY >=0 && m_trackedObjects[0].posX >= 0 && m_trackedObjects[0].posY >= 0 )\n\/\/\t\t\t\t{\n\/\/\t\t\t\t\t\/\/ Draw a line from previous pose to current pose\n\/\/\t\t\t\t\tcv::line( _linesImage, cv::Point( m_trackedObjects[0].posX, m_trackedObjects[0].posY )\n\/\/\t\t\t\t\t\t\t\t, cv::Point( m_trackedObjects[0].lastX, m_trackedObjects[0].lastY ), cv::Scalar( 0, 0, 255 ), 2 );\n\/\/\t\t\t\t}\n\/\/\n\/\/\t\t\t\tm_trackedObjects[0].lastX = m_trackedObjects[0].posX;\n\/\/\t\t\t\tm_trackedObjects[0].lastY = m_trackedObjects[0].posY;\n\/\/\n\/\/\t\t\t\tcv::Scalar color = cv::Scalar( 94, 206, 165 );\n\/\/\n\/\/\t\t\t\tcv::circle( _origImage, cv::Point( m_trackedObjects[0].posX, m_trackedObjects[0].posY ), sqrt( m_trackedObjects[0].momentsArea\/3.14 )\/10, color, 0.5, 8, 0 );\n\/\/\t\t\t}\n\/\/\t\t}\n\t\t\/\/ Display the images\n\/\/\t\tcv::imshow( _controlWindow, _imageThreshold );\n\n\t\t\/\/ Display the combined image\n\/\/\t\t_origImage = _origImage + _linesImage;\n\n\/\/\t\tcv::imshow( \"Original-Image\", _origImage );\n\t\tcv::imshow( \"Blob-Image\", _imageKeypoints );\n\n\t\tif( cv::waitKey( 0 ) == 27 )\n\t\t{\n\t\t\tLOG( INFO ) << \">>>> Exiting <<<<\";\n\/\/\t\t\tbreak;\n\t\t}\n\/\/\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.\n * The following source code is released under an MIT-style license,\n * that can be found in the LICENSE file.\n *\/\n\n#include \"RenderManager.h\"\n#include \"Application.h\"\n#include \"window\/Window.h\"\n#include \"window\/LoadingScreen.h\"\n#include \"window\/MainMenu.h\"\n#include \"render\/window\/MenuRender.h\"\n\nRenderManager::RenderManager(ApplicationContext &applicationContext, Window *window)\n : m_applicationContext(applicationContext) {\n \n if (!this->initWindow()) {\n printf(\"Failed to initialize window!\\n\");\n exit(1); \/\/ TODO replace with exceptions\n } else if (!this->initGL()) {\n printf(\"Unable to initialize OpenGL!\\n\");\n exit(1);\n } else if (!this->initRenders()) {\n printf(\"Unable to initialize window renders!\\n\");\n exit(1);\n } else {\n#ifdef DEF_ANDROID\n initBindings();\n#endif \/\/ DEF_ANDROID\n }\n\n switchWindow(*window);\n}\n\nbool RenderManager::initWindow() {\n bool success = true;\n\n#ifdef USES_SDL\n if (SDL_Init(SDL_INIT_VIDEO) < 0) {\n printf(\"SDL could not initialize! SDL Error: %d\\n\", SDL_GetError());\n success = false;\n } else {\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n\n std::string windowName = m_applicationContext.config().stringValue(\"window.title\", \"Spooky - unnamed project\");\n\n int windowWidth = m_applicationContext.config().intValue(\"window.width\", 1366);\n int windowHeight = m_applicationContext.config().intValue(\"window.height\", 750);\n gWindow = SDL_CreateWindow(windowName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);\n if (gWindow == NULL) {\n printf(\"Window could not be created! SDL Error: %s\\n\", SDL_GetError());\n success = false;\n } else {\n gContext = SDL_GL_CreateContext(gWindow);\n if (gContext == NULL) {\n printf(\"OpenGL context could not be created! SDL Error: %s\\n\", SDL_GetError());\n success = false;\n } else {\n \/\/VSync\n if (SDL_GL_SetSwapInterval(1) < 0) {\n printf(\"Warning: Unable to set VSync! SDL Error: %s\\n\", SDL_GetError());\n }\n }\n }\n m_renderContext.resize(windowWidth, windowHeight);\n }\n#endif \/\/ USES_SDL\n return success;\n}\n\nbool RenderManager::initGL() {\n#ifdef USES_SDL\n glewExperimental = GL_TRUE;\n GLenum glewError = glewInit();\n if (glewError != GLEW_OK) {\n printf(\"Error initializing GLEW! %s\\n\", glewGetErrorString(glewError));\n return false;\n }\n#endif \/\/ USES_SDL\n\n return true;\n}\n\nbool RenderManager::initRenders() {\n windowRenders.insert(windowRenders.begin() + LoadingScreen::TYPE, std::make_unique<MenuRender>(m_renderContext));\n windowRenders.insert(windowRenders.begin() + MainMenu::TYPE, std::make_unique<MenuRender>(m_renderContext));\n return true;\n}\n\nvoid RenderManager::render() {\n m_windowRender->render(*m_currentWindow);\n#ifdef USES_SDL\n SDL_GL_SwapWindow(gWindow);\n#endif \/\/ USES_SDL\n}\n\nvoid RenderManager::reload() {\n glViewport(0, 0, m_renderContext.windowWidth(), m_renderContext.windowHeight());\n m_windowRender->reload();\n}\n\nRenderManager::~RenderManager() {\n#ifdef USES_SDL\n SDL_DestroyWindow(this->gWindow);\n SDL_Quit();\n#endif \/\/ USES_SDL\n}\n\nvoid RenderManager::switchWindow(Window &window) {\n m_currentWindow = &window;\n m_windowRender = windowRenders[window.type()].get();\n m_windowRender->reinit();\n}\n\nvoid RenderManager::resize(uint32_t width, uint32_t height) {\n m_renderContext.resize(width, height);\n reload();\n}\n<commit_msg>Reload renders after initialization<commit_after>\/*\n * Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.\n * The following source code is released under an MIT-style license,\n * that can be found in the LICENSE file.\n *\/\n\n#include \"RenderManager.h\"\n#include \"Application.h\"\n#include \"window\/Window.h\"\n#include \"window\/LoadingScreen.h\"\n#include \"window\/MainMenu.h\"\n#include \"render\/window\/MenuRender.h\"\n\nRenderManager::RenderManager(ApplicationContext &applicationContext, Window *window)\n : m_applicationContext(applicationContext) {\n \n if (!this->initWindow()) {\n printf(\"Failed to initialize window!\\n\");\n exit(1); \/\/ TODO replace with exceptions\n } else if (!this->initGL()) {\n printf(\"Unable to initialize OpenGL!\\n\");\n exit(1);\n } else if (!this->initRenders()) {\n printf(\"Unable to initialize window renders!\\n\");\n exit(1);\n } else {\n#ifdef DEF_ANDROID\n initBindings();\n#endif \/\/ DEF_ANDROID\n }\n\n switchWindow(*window);\n}\n\nbool RenderManager::initWindow() {\n bool success = true;\n\n#ifdef USES_SDL\n if (SDL_Init(SDL_INIT_VIDEO) < 0) {\n printf(\"SDL could not initialize! SDL Error: %d\\n\", SDL_GetError());\n success = false;\n } else {\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n\n std::string windowName = m_applicationContext.config().stringValue(\"window.title\", \"Spooky - unnamed project\");\n\n int windowWidth = m_applicationContext.config().intValue(\"window.width\", 1366);\n int windowHeight = m_applicationContext.config().intValue(\"window.height\", 750);\n gWindow = SDL_CreateWindow(windowName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);\n if (gWindow == NULL) {\n printf(\"Window could not be created! SDL Error: %s\\n\", SDL_GetError());\n success = false;\n } else {\n gContext = SDL_GL_CreateContext(gWindow);\n if (gContext == NULL) {\n printf(\"OpenGL context could not be created! SDL Error: %s\\n\", SDL_GetError());\n success = false;\n } else {\n \/\/VSync\n if (SDL_GL_SetSwapInterval(1) < 0) {\n printf(\"Warning: Unable to set VSync! SDL Error: %s\\n\", SDL_GetError());\n }\n }\n }\n m_renderContext.resize(windowWidth, windowHeight);\n }\n#endif \/\/ USES_SDL\n return success;\n}\n\nbool RenderManager::initGL() {\n#ifdef USES_SDL\n glewExperimental = GL_TRUE;\n GLenum glewError = glewInit();\n if (glewError != GLEW_OK) {\n printf(\"Error initializing GLEW! %s\\n\", glewGetErrorString(glewError));\n return false;\n }\n#endif \/\/ USES_SDL\n\n return true;\n}\n\nbool RenderManager::initRenders() {\n windowRenders.insert(windowRenders.begin() + LoadingScreen::TYPE, std::make_unique<MenuRender>(m_renderContext));\n windowRenders.insert(windowRenders.begin() + MainMenu::TYPE, std::make_unique<MenuRender>(m_renderContext));\n return true;\n}\n\nvoid RenderManager::render() {\n m_windowRender->render(*m_currentWindow);\n#ifdef USES_SDL\n SDL_GL_SwapWindow(gWindow);\n#endif \/\/ USES_SDL\n}\n\nvoid RenderManager::reload() {\n glViewport(0, 0, m_renderContext.windowWidth(), m_renderContext.windowHeight());\n m_windowRender->reload();\n}\n\nRenderManager::~RenderManager() {\n#ifdef USES_SDL\n SDL_DestroyWindow(this->gWindow);\n SDL_Quit();\n#endif \/\/ USES_SDL\n}\n\nvoid RenderManager::switchWindow(Window &window) {\n m_currentWindow = &window;\n m_windowRender = windowRenders[window.type()].get();\n m_windowRender->reinit();\n m_windowRender->reload();\n}\n\nvoid RenderManager::resize(uint32_t width, uint32_t height) {\n m_renderContext.resize(width, height);\n reload();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"otbGeomMetadataSupplier.h\"\n#include \"otbMetaDataKey.h\"\n#include \"otbGeometryMetadata.h\"\n#include \"otbStringUtils.h\"\n\nnamespace otb\n{\nGeomMetadataSupplier::GeomMetadataSupplier(std::string const& fileName)\n : m_FileName(fileName)\n{\n this->ReadGeomFile();\n}\n\nstd::string GeomMetadataSupplier::GetMetadataValue(std::string const& path, bool& hasValue, int band) const\n{\n auto value = this->m_MetadataDic.find(path);\n if(value != this->m_MetadataDic.end())\n {\n hasValue = true;\n return value->second;\n }\n hasValue = false;\n return \"\";\n}\n\nstd::string GeomMetadataSupplier::GetResourceFile(std::string const& s) const\n{\n return this->m_FileName;\n}\n\nint GeomMetadataSupplier::GetNbBands() const\n{\n bool hasValue;\n std::string ret = this->GetMetadataValue(\"support_data.number_bands\", hasValue);\n if (hasValue)\n {\n boost::algorithm::trim_if(ret, boost::algorithm::is_any_of(\"\\\" \"));\n return std::stoi(ret);\n }\n\n ret = this->GetMetadataValue(\"support_data.band_name_list\", hasValue);\n boost::algorithm::trim_if(ret, boost::algorithm::is_any_of(\"\\\" \"));\n if (hasValue)\n {\n std::vector<std::string> ret_vect;\n otb::Utils::ConvertStringToVector(ret, ret_vect, \"band name\");\n return ret_vect.size();\n }\n\n return 0;\n}\n\nbool GeomMetadataSupplier::FetchRPC(ImageMetadata & imd)\n{\n bool hasValue;\n GetMetadataValue(\"polynomial_format\", hasValue);\n if (!hasValue)\n return false;\n\n Projection::RPCParam rpcStruct;\n rpcStruct.LineOffset = this->GetAs<double>(\"line_off\");\n rpcStruct.SampleOffset = this->GetAs<double>(\"samp_off\");\n rpcStruct.LatOffset = this->GetAs<double>(\"lat_off\");\n rpcStruct.LonOffset = this->GetAs<double>(\"long_off\");\n rpcStruct.HeightOffset = this->GetAs<double>(\"height_off\");\n\n rpcStruct.LineScale = this->GetAs<double>(\"line_scale\");\n rpcStruct.SampleScale = this->GetAs<double>(\"samp_scale\");\n rpcStruct.LatScale = this->GetAs<double>(\"lat_scale\");\n rpcStruct.LonScale = this->GetAs<double>(\"long_scale\");\n rpcStruct.HeightScale = this->GetAs<double>(\"height_scale\");\n\n std::vector<double> coeffs;\n int loop = 0;\n std::stringstream path;\n for (auto & coeff : rpcStruct.LineNum)\n {\n path.str(\"\");\n path << \"line_num_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.LineDen)\n {\n path.str(\"\");\n path << \"line_den_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.SampleNum)\n {\n path.str(\"\");\n path << \"samp_num_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.SampleDen)\n {\n path.str(\"\");\n path << \"samp_den_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n\n imd.Add(MDGeom::RPC, rpcStruct);\n assert(imd.Has(MDGeom::RPC));\n assert(rpcStruct == boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC]));\n return true;\n}\n\nstd::string GeomMetadataSupplier::PrintSelf() const\n{\n std::ostringstream oss;\n oss << \"GeomMetadataSupplier: \" << this->m_FileName << '\\n';\n for (const auto& kv : this->m_MetadataDic)\n oss << kv.first << \" : \" << kv.second << '\\n';\n return oss.str();\n}\n\nvoid GeomMetadataSupplier::ReadGeomFile()\n{\n std::ifstream inputFile(this->m_FileName);\n std::string line;\n std::vector< std::string > keyVal;\n while (std::getline(inputFile, line))\n {\n auto pos = line.find(\":\");\n if (pos != std::string::npos)\n {\n auto key = line.substr(0,pos);\n auto value = line.substr(pos+1, line.size());\n boost::trim(key);\n boost::trim(value);\n m_MetadataDic[key] = value;\n }\n }\n}\n\n} \/\/ end namespace otb\n<commit_msg>BUG: consider that the product has one band if no band specific keys are found in the geom product<commit_after>\/*\n * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"otbGeomMetadataSupplier.h\"\n#include \"otbMetaDataKey.h\"\n#include \"otbGeometryMetadata.h\"\n#include \"otbStringUtils.h\"\n\nnamespace otb\n{\nGeomMetadataSupplier::GeomMetadataSupplier(std::string const& fileName)\n : m_FileName(fileName)\n{\n this->ReadGeomFile();\n}\n\nstd::string GeomMetadataSupplier::GetMetadataValue(std::string const& path, bool& hasValue, int band) const\n{\n auto value = this->m_MetadataDic.find(path);\n if(value != this->m_MetadataDic.end())\n {\n hasValue = true;\n return value->second;\n }\n hasValue = false;\n return \"\";\n}\n\nstd::string GeomMetadataSupplier::GetResourceFile(std::string const& s) const\n{\n return this->m_FileName;\n}\n\nint GeomMetadataSupplier::GetNbBands() const\n{\n bool hasValue;\n std::string ret = this->GetMetadataValue(\"support_data.number_bands\", hasValue);\n if (hasValue)\n {\n boost::algorithm::trim_if(ret, boost::algorithm::is_any_of(\"\\\" \"));\n return std::stoi(ret);\n }\n\n ret = this->GetMetadataValue(\"support_data.band_name_list\", hasValue);\n boost::algorithm::trim_if(ret, boost::algorithm::is_any_of(\"\\\" \"));\n if (hasValue)\n {\n std::vector<std::string> ret_vect;\n otb::Utils::ConvertStringToVector(ret, ret_vect, \"band name\");\n return ret_vect.size();\n }\n\n return 1;\n}\n\nbool GeomMetadataSupplier::FetchRPC(ImageMetadata & imd)\n{\n bool hasValue;\n GetMetadataValue(\"polynomial_format\", hasValue);\n if (!hasValue)\n return false;\n\n Projection::RPCParam rpcStruct;\n rpcStruct.LineOffset = this->GetAs<double>(\"line_off\");\n rpcStruct.SampleOffset = this->GetAs<double>(\"samp_off\");\n rpcStruct.LatOffset = this->GetAs<double>(\"lat_off\");\n rpcStruct.LonOffset = this->GetAs<double>(\"long_off\");\n rpcStruct.HeightOffset = this->GetAs<double>(\"height_off\");\n\n rpcStruct.LineScale = this->GetAs<double>(\"line_scale\");\n rpcStruct.SampleScale = this->GetAs<double>(\"samp_scale\");\n rpcStruct.LatScale = this->GetAs<double>(\"lat_scale\");\n rpcStruct.LonScale = this->GetAs<double>(\"long_scale\");\n rpcStruct.HeightScale = this->GetAs<double>(\"height_scale\");\n\n std::vector<double> coeffs;\n int loop = 0;\n std::stringstream path;\n for (auto & coeff : rpcStruct.LineNum)\n {\n path.str(\"\");\n path << \"line_num_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.LineDen)\n {\n path.str(\"\");\n path << \"line_den_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.SampleNum)\n {\n path.str(\"\");\n path << \"samp_num_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n loop = 0;\n for (auto & coeff : rpcStruct.SampleDen)\n {\n path.str(\"\");\n path << \"samp_den_coeff_\" << std::setfill('0') << std::setw(2) << loop++;\n coeff = this->GetAs<double>(path.str());\n }\n\n imd.Add(MDGeom::RPC, rpcStruct);\n assert(imd.Has(MDGeom::RPC));\n assert(rpcStruct == boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC]));\n return true;\n}\n\nstd::string GeomMetadataSupplier::PrintSelf() const\n{\n std::ostringstream oss;\n oss << \"GeomMetadataSupplier: \" << this->m_FileName << '\\n';\n for (const auto& kv : this->m_MetadataDic)\n oss << kv.first << \" : \" << kv.second << '\\n';\n return oss.str();\n}\n\nvoid GeomMetadataSupplier::ReadGeomFile()\n{\n std::ifstream inputFile(this->m_FileName);\n std::string line;\n std::vector< std::string > keyVal;\n while (std::getline(inputFile, line))\n {\n auto pos = line.find(\":\");\n if (pos != std::string::npos)\n {\n auto key = line.substr(0,pos);\n auto value = line.substr(pos+1, line.size());\n boost::trim(key);\n boost::trim(value);\n m_MetadataDic[key] = value;\n }\n }\n}\n\n} \/\/ end namespace otb\n<|endoftext|>"} {"text":"<commit_before>#include \"reflection.h\"\n\n#include <type_traits>\n\nstruct Foo {};\nstatic_assert(std::is_same<void, reflection::reflected_member_t<Foo, 0>>::value);\nstatic_assert(reflection::reflected_member_count_v<Foo> == 0);\n\nstruct Bar\n{\n void bar();\n};\nREFLECT_MEMBER(Bar, bar);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Bar, 0>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_member_t<Bar, 1>>::value);\nstatic_assert(reflection::reflected_member_count_v<Bar> == 1);\n\nstruct Baz\n{\n void baz();\n void baz2();\n};\nREFLECT_MEMBER(Baz, baz);\nREFLECT_MEMBER(Baz, baz2);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Baz, 0>>::value);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Baz, 1>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_member_t<Baz, 2>>::value);\nstatic_assert(reflection::reflected_member_count_v<Baz> == 2);\n\nstruct Bat\n{\n void REFLECT(bat)();\n void REFLECT(bat2)();\n};\n\nstatic_assert(!std::is_same<void, reflection::reflected_class_member_t<Bat, 0>>::value);\nstatic_assert(!std::is_same<void, reflection::reflected_class_member_t<Bat, 1>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_class_member_t<Bat, 2>>::value);\nstatic_assert(reflection::reflected_class_member_count_v<Bat> == 2);\n\nauto _ = []{\n using namespace reflection;\n\n std::cout << \"Foo\" << std::endl;\n std::cout << reflected_member_count_v<Foo> << std::endl;\n\n std::cout << \"Bar\" << std::endl;\n std::cout << reflected_member_count_v<Bar> << std::endl;\n\n std::cout << \"Baz\" << std::endl;\n std::cout << reflected_member_count_v<Baz> << std::endl;\n\n return 0;\n}();\n\nint main()\n{\n}\n<commit_msg>Added missing include<commit_after>#include \"reflection.h\"\n\n#include <iostream>\n#include <type_traits>\n\nstruct Foo {};\nstatic_assert(std::is_same<void, reflection::reflected_member_t<Foo, 0>>::value);\nstatic_assert(reflection::reflected_member_count_v<Foo> == 0);\n\nstruct Bar\n{\n void bar();\n};\nREFLECT_MEMBER(Bar, bar);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Bar, 0>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_member_t<Bar, 1>>::value);\nstatic_assert(reflection::reflected_member_count_v<Bar> == 1);\n\nstruct Baz\n{\n void baz();\n void baz2();\n};\nREFLECT_MEMBER(Baz, baz);\nREFLECT_MEMBER(Baz, baz2);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Baz, 0>>::value);\nstatic_assert(!std::is_same<void, reflection::reflected_member_t<Baz, 1>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_member_t<Baz, 2>>::value);\nstatic_assert(reflection::reflected_member_count_v<Baz> == 2);\n\nstruct Bat\n{\n void REFLECT(bat)();\n void REFLECT(bat2)();\n};\n\nstatic_assert(!std::is_same<void, reflection::reflected_class_member_t<Bat, 0>>::value);\nstatic_assert(!std::is_same<void, reflection::reflected_class_member_t<Bat, 1>>::value);\nstatic_assert( std::is_same<void, reflection::reflected_class_member_t<Bat, 2>>::value);\nstatic_assert(reflection::reflected_class_member_count_v<Bat> == 2);\n\nauto _ = []{\n using namespace reflection;\n\n std::cout << \"Foo\" << std::endl;\n std::cout << reflected_member_count_v<Foo> << std::endl;\n\n std::cout << \"Bar\" << std::endl;\n std::cout << reflected_member_count_v<Bar> << std::endl;\n\n std::cout << \"Baz\" << std::endl;\n std::cout << reflected_member_count_v<Baz> << std::endl;\n\n return 0;\n}();\n\nint main()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"protocol.h\"\n#include \"..\/common\/crash.h\"\nnamespace redc { namespace net\n{\n Step_Client_Result step_client(Client_Context& ctx, ENetEvent const& event) noexcept\n {\n Step_Client_Result res;\n\n switch(ctx.state)\n {\n case Client_State::Starting:\n {\n \/\/ Assuming that the server address has already been set.\n ctx.host = std::move(*make_client_host().ok());\n \/\/ How many channels? Just one?\n enet_host_connect(ctx.host.host, &ctx.server_addr, 1, 0);\n ctx.state = Client_State::Connecting;\n res.context_changed = true;\n break;\n }\n case Client_State::Connecting:\n {\n \/\/ If it's the correct type of event\n if(event.type == ENET_EVENT_TYPE_CONNECT)\n {\n \/\/ From the correct peer? We can probably assume nobody will use our\n \/\/ host that we made but better safe than sorry.\n if(event.peer->address.host == ctx.server_addr.host &&\n event.peer->address.port == ctx.server_addr.port)\n {\n res.event_handled = true;\n res.context_changed = true;\n\n \/\/ Now send our version\n ctx.server_peer = event.peer;\n\n \/\/ Serialize version number\n version_t cur_client_version = 1;\n\n msgpack::sbuffer buf;\n msgpack::pack(buf, cur_client_version);\n\n \/\/ Make the version packet\n auto packet = enet_packet_create(buf.data(), buf.size(),\n ENET_PACKET_FLAG_RELIABLE);\n enet_peer_send(ctx.server_peer, 0, packet);\n\n \/\/ Now we are waiting for a response (or failure due to versioning)\n ctx.state = Client_State::Waiting_For_Info;\n }\n }\n break;\n }\n case Client_State::Waiting_For_Info:\n case Client_State::Sending_Loadouts:\n case Client_State::Waiting_For_Inventory_Confirmation:\n case Client_State::Sending_Team:\n case Client_State::Waiting_For_Spawn:\n break;\n case Client_State::Playing:\n default:\n break;\n }\n\n return res;\n }\n\n Client make_client(std::string addr, uint16_t port) noexcept\n {\n Client client;\n client.host = std::move(*make_client_host().ok());\n\n connect_with_client(client.host, addr, port);\n\n return client;\n }\n Client wait_for_connection(std::string addr, uint16_t port) noexcept\n {\n auto client = make_client(addr, port);\n client.peer = wait_for_connection(client.host, 1000);\n \/\/ Failed to connect if peer is null\n if(!client.peer)\n {\n crash(\"Failed to connect\");\n }\n return client;\n }\n\n void close_connection(Client& client) noexcept\n {\n enet_peer_disconnect(client.peer, 0);\n enet_host_service(client.host.host, NULL, 500);\n enet_host_destroy(client.host.host);\n }\n\n void wait_for_game_info(Client& client, sail::Game& game) noexcept\n {\n }\n void set_name(Client& client, std::string name) noexcept\n {\n }\n} }\n<commit_msg>Add implementation of Client_State::Waiting_For_Info<commit_after>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"protocol.h\"\n#include \"..\/common\/crash.h\"\nnamespace redc { namespace net\n{\n Step_Client_Result step_client(Client_Context& ctx, ENetEvent const& event) noexcept\n {\n Step_Client_Result res;\n\n switch(ctx.state)\n {\n case Client_State::Starting:\n {\n \/\/ Assuming that the server address has already been set.\n ctx.host = std::move(*make_client_host().ok());\n \/\/ How many channels? Just one?\n enet_host_connect(ctx.host.host, &ctx.server_addr, 1, 0);\n ctx.state = Client_State::Connecting;\n res.context_changed = true;\n break;\n }\n case Client_State::Connecting:\n {\n \/\/ If it's the correct type of event\n if(event.type == ENET_EVENT_TYPE_CONNECT)\n {\n \/\/ From the correct peer? We can probably assume nobody will use our\n \/\/ host that we made but better safe than sorry.\n if(event.peer->address.host == ctx.server_addr.host &&\n event.peer->address.port == ctx.server_addr.port)\n {\n res.event_handled = true;\n res.context_changed = true;\n\n \/\/ Now send our version\n ctx.server_peer = event.peer;\n\n \/\/ Serialize version number\n version_t cur_client_version = 1;\n\n msgpack::sbuffer buf;\n msgpack::pack(buf, cur_client_version);\n\n \/\/ Make the version packet\n auto packet = enet_packet_create(buf.data(), buf.size(),\n ENET_PACKET_FLAG_RELIABLE);\n enet_peer_send(ctx.server_peer, 0, packet);\n\n \/\/ Now we are waiting for a response (or failure due to versioning)\n ctx.state = Client_State::Waiting_For_Info;\n }\n }\n break;\n }\n case Client_State::Waiting_For_Info:\n {\n if(event.type == ENET_EVENT_TYPE_RECEIVE)\n {\n if(event.peer == ctx.server_peer)\n {\n \/\/ We got some data from the server!\n if(event.packet->dataLength == 1)\n {\n \/\/ If it is just false:\n if(event.packet->data[0] == 0xc2)\n {\n \/\/ Our version was probably bad\n \/\/ Throw an error?\n }\n }\n\n \/\/ Try to decode Client_Init_Packet struct\n msgpack::unpacked unpacked;\n msgpack::unpack(unpacked, (const char*) event.packet->data,\n event.packet->dataLength);\n try\n {\n ctx.client_init_packet = unpacked.get().as<Client_Init_Packet>();\n }\n catch(...)\n {\n \/\/ Figure out what exception I need to catch\n \/\/ For now rethrow it\n throw;\n }\n\n \/\/ Now we have the client init packet available, that's all we need\n \/\/ then the user should populate the inventory field.\n res.context_changed = true;\n res.event_handled = true;\n ctx.state = Client_State::Sending_Loadouts;\n }\n }\n break;\n }\n case Client_State::Sending_Loadouts:\n case Client_State::Waiting_For_Inventory_Confirmation:\n case Client_State::Sending_Team:\n case Client_State::Waiting_For_Spawn:\n break;\n case Client_State::Playing:\n default:\n break;\n }\n\n return res;\n }\n\n Client make_client(std::string addr, uint16_t port) noexcept\n {\n Client client;\n client.host = std::move(*make_client_host().ok());\n\n connect_with_client(client.host, addr, port);\n\n return client;\n }\n Client wait_for_connection(std::string addr, uint16_t port) noexcept\n {\n auto client = make_client(addr, port);\n client.peer = wait_for_connection(client.host, 1000);\n \/\/ Failed to connect if peer is null\n if(!client.peer)\n {\n crash(\"Failed to connect\");\n }\n return client;\n }\n\n void close_connection(Client& client) noexcept\n {\n enet_peer_disconnect(client.peer, 0);\n enet_host_service(client.host.host, NULL, 500);\n enet_host_destroy(client.host.host);\n }\n\n void wait_for_game_info(Client& client, sail::Game& game) noexcept\n {\n }\n void set_name(Client& client, std::string name) noexcept\n {\n }\n} }\n<|endoftext|>"} {"text":"<commit_before>#include \"mitkRESTServerMicroService.h\"\n#include <mitkCommon.h>\n\nmitk::RESTServerMicroService::RESTServerMicroService(web::uri uri) : m_Listener(uri)\n{\n m_Listener.support(MitkRESTMethods::GET, std::bind(&RESTServerMicroService::HandleGet, this, std::placeholders::_1));\n openListener(); \n}\n\nmitk::RESTServerMicroService::~RESTServerMicroService()\n{\n closeListener();\n}\n\npplx::task<void> mitk::RESTServerMicroService::openListener()\n{\n return m_Listener.open();\n}\n\npplx::task<void> mitk::RESTServerMicroService::closeListener()\n{\n return m_Listener.close();\n}\n\nvoid mitk::RESTServerMicroService::HandleGet(MitkRequest request)\n{\n int port = m_Listener.uri().port();\n MITK_INFO << \"Test for Server at port \"<<port;\n request.reply(MitkRestStatusCodes::OK);\n}<commit_msg>example json value is returned from server<commit_after>#include \"mitkRESTServerMicroService.h\"\n#include <mitkCommon.h>\n\nmitk::RESTServerMicroService::RESTServerMicroService(web::uri uri) : m_Listener(uri)\n{\n m_Listener.support(MitkRESTMethods::GET, std::bind(&RESTServerMicroService::HandleGet, this, std::placeholders::_1));\n openListener(); \n}\n\nmitk::RESTServerMicroService::~RESTServerMicroService()\n{\n closeListener();\n}\n\npplx::task<void> mitk::RESTServerMicroService::openListener()\n{\n return m_Listener.open();\n}\n\npplx::task<void> mitk::RESTServerMicroService::closeListener()\n{\n return m_Listener.close();\n}\n\nvoid mitk::RESTServerMicroService::HandleGet(MitkRequest request)\n{\n int port = m_Listener.uri().port();\n web::json::value content;\n content[L\"key 1\"] = web::json::value::string(U(\"this is a first test\"));\n request.set_body(content);\n auto answer = request.extract_json().get();\n MITK_INFO << \"Test for Server at port \"<<port;\n\n request.reply(MitkRestStatusCodes::OK, answer);\n}<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPickingTool.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkToolManager.h\"\n\n\/\/ us\n#include <usGetModuleContext.h>\n#include <usModule.h>\n#include <usModuleContext.h>\n#include <usModuleResource.h>\n\n#include \"mitkITKImageImport.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageTimeSelector.h\"\n\n#include <itkConnectedThresholdImageFilter.h>\n\n#include <mitkLabelSetImage.h>\n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, PickingTool, \"PickingTool\");\n}\n\nmitk::PickingTool::PickingTool() : m_WorkingData(nullptr)\n{\n m_PointSetNode = mitk::DataNode::New();\n m_PointSetNode->GetPropertyList()->SetProperty(\"name\", mitk::StringProperty::New(\"Picking_Seedpoint\"));\n m_PointSetNode->GetPropertyList()->SetProperty(\"helper object\", mitk::BoolProperty::New(true));\n m_PointSet = mitk::PointSet::New();\n m_PointSetNode->SetData(m_PointSet);\n m_SeedPointInteractor = mitk::SinglePointDataInteractor::New();\n m_SeedPointInteractor->LoadStateMachine(\"PointSet.xml\");\n m_SeedPointInteractor->SetEventConfig(\"PointSetConfig.xml\");\n m_SeedPointInteractor->SetDataNode(m_PointSetNode);\n\n \/\/ Watch for point added or modified\n itk::SimpleMemberCommand<PickingTool>::Pointer pointAddedCommand = itk::SimpleMemberCommand<PickingTool>::New();\n pointAddedCommand->SetCallbackFunction(this, &mitk::PickingTool::OnPointAdded);\n m_PointSetAddObserverTag = m_PointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);\n\n \/\/ create new node for picked region\n m_ResultNode = mitk::DataNode::New();\n \/\/ set some properties\n m_ResultNode->SetProperty(\"name\", mitk::StringProperty::New(\"result\"));\n m_ResultNode->SetProperty(\"helper object\", mitk::BoolProperty::New(true));\n m_ResultNode->SetProperty(\"color\", mitk::ColorProperty::New(0, 1, 0));\n m_ResultNode->SetProperty(\"layer\", mitk::IntProperty::New(1));\n m_ResultNode->SetProperty(\"opacity\", mitk::FloatProperty::New(0.33f));\n}\n\nmitk::PickingTool::~PickingTool()\n{\n m_PointSet->RemoveObserver(m_PointSetAddObserverTag);\n}\n\nconst char **mitk::PickingTool::GetXPM() const\n{\n return nullptr;\n}\n\nconst char *mitk::PickingTool::GetName() const\n{\n return \"Picking\";\n}\n\nus::ModuleResource mitk::PickingTool::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Pick_48x48.png\");\n return resource;\n}\n\nvoid mitk::PickingTool::Activated()\n{\n Superclass::Activated();\n\n DataStorage *dataStorage = this->GetDataStorage();\n m_WorkingData = this->GetWorkingData();\n\n \/\/ add to datastorage and enable interaction\n if (!dataStorage->Exists(m_PointSetNode))\n dataStorage->Add(m_PointSetNode, m_WorkingData);\n\n \/\/ now add result to data tree\n dataStorage->Add(m_ResultNode, m_WorkingData);\n}\n\nvoid mitk::PickingTool::Deactivated()\n{\n m_PointSet->Clear();\n \/\/ remove from data storage and disable interaction\n GetDataStorage()->Remove(m_PointSetNode);\n GetDataStorage()->Remove(m_ResultNode);\n\n Superclass::Deactivated();\n}\n\nmitk::DataNode *mitk::PickingTool::GetReferenceData()\n{\n return this->m_ToolManager->GetReferenceData(0);\n}\n\nmitk::DataStorage *mitk::PickingTool::GetDataStorage()\n{\n return this->m_ToolManager->GetDataStorage();\n}\n\nmitk::DataNode *mitk::PickingTool::GetWorkingData()\n{\n return this->m_ToolManager->GetWorkingData(0);\n}\n\nmitk::DataNode::Pointer mitk::PickingTool::GetPointSetNode()\n{\n return m_PointSetNode;\n}\n\nvoid mitk::PickingTool::OnPointAdded()\n{\n if (m_WorkingData != this->GetWorkingData())\n {\n DataStorage *dataStorage = this->GetDataStorage();\n\n if (dataStorage->Exists(m_PointSetNode))\n {\n dataStorage->Remove(m_PointSetNode);\n dataStorage->Add(m_PointSetNode, this->GetWorkingData());\n }\n\n if (dataStorage->Exists(m_ResultNode))\n {\n dataStorage->Remove(m_ResultNode);\n dataStorage->Add(m_ResultNode, this->GetWorkingData());\n }\n\n m_WorkingData = this->GetWorkingData();\n }\n\n \/\/ Perform region growing\/picking\n\n int timeStep =\n mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName(\"stdmulti.widget1\"))->GetTimeStep();\n\n mitk::PointSet::PointType seedPoint = m_PointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value();\n\n \/\/ as we want to pick a region from our segmentation image use the working data from ToolManager\n mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());\n\n if (orgImage.IsNotNull())\n {\n if (orgImage->GetDimension() == 4)\n { \/\/ there may be 4D segmentation data even though we currently don't support that\n mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();\n timeSelector->SetInput(orgImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n mitk::Image *timedImage = timeSelector->GetOutput();\n\n AccessByItk_2(timedImage, StartRegionGrowing, timedImage->GetGeometry(), seedPoint);\n }\n else if (orgImage->GetDimension() == 3)\n {\n AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint);\n }\n this->m_PointSet->Clear();\n }\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::PickingTool::StartRegionGrowing(itk::Image<TPixel, VImageDimension> *itkImage,\n mitk::BaseGeometry *imageGeometry,\n mitk::PointSet::PointType seedPoint)\n{\n typedef itk::Image<TPixel, VImageDimension> InputImageType;\n typedef typename InputImageType::IndexType IndexType;\n typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType;\n typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New();\n\n \/\/ convert world coordinates to image indices\n IndexType seedIndex;\n imageGeometry->WorldToIndex(seedPoint, seedIndex);\n\n \/\/ perform region growing in desired segmented region\n regionGrower->SetInput(itkImage);\n regionGrower->AddSeed(seedIndex);\n\n regionGrower->SetLower(1);\n regionGrower->SetUpper(255);\n\n try\n {\n regionGrower->Update();\n }\n catch (const itk::ExceptionObject &)\n {\n return; \/\/ can't work\n }\n catch (...)\n {\n return;\n }\n\n \/\/ Store result and preview\n mitk::Image::Pointer resultImage = mitk::ImportItkImage(regionGrower->GetOutput(), imageGeometry)->Clone();\n mitk::LabelSetImage::Pointer resultLabelSetImage = mitk::LabelSetImage::New();\n resultLabelSetImage->InitializeByLabeledImage(resultImage);\n\n m_ResultNode->SetData(resultLabelSetImage);\n\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\nvoid mitk::PickingTool::ConfirmSegmentation()\n{\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetProperty(\"name\", mitk::StringProperty::New(m_WorkingData->GetName() + \"_picked\"));\n\n float rgb[3] = {1.0f, 0.0f, 0.0f};\n m_WorkingData->GetColor(rgb);\n newNode->SetProperty(\"color\", mitk::ColorProperty::New(rgb));\n\n float opacity = 1.0f;\n m_WorkingData->GetOpacity(opacity, nullptr);\n newNode->SetProperty(\"opacity\", mitk::FloatProperty::New(opacity));\n\n newNode->SetData(m_ResultNode->GetData());\n\n GetDataStorage()->Add(newNode, this->GetReferenceData());\n m_WorkingData->SetVisibility(false);\n\n m_ResultNode->SetData(nullptr);\n\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n<commit_msg>move interactor initialization<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPickingTool.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkToolManager.h\"\n\n\/\/ us\n#include <usGetModuleContext.h>\n#include <usModule.h>\n#include <usModuleContext.h>\n#include <usModuleResource.h>\n\n#include \"mitkITKImageImport.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageTimeSelector.h\"\n\n#include <itkConnectedThresholdImageFilter.h>\n\n#include <mitkLabelSetImage.h>\n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, PickingTool, \"PickingTool\");\n}\n\nmitk::PickingTool::PickingTool() : m_WorkingData(nullptr)\n{\n m_PointSetNode = mitk::DataNode::New();\n m_PointSetNode->GetPropertyList()->SetProperty(\"name\", mitk::StringProperty::New(\"Picking_Seedpoint\"));\n m_PointSetNode->GetPropertyList()->SetProperty(\"helper object\", mitk::BoolProperty::New(true));\n m_PointSet = mitk::PointSet::New();\n m_PointSetNode->SetData(m_PointSet);\n\n \/\/ Watch for point added or modified\n itk::SimpleMemberCommand<PickingTool>::Pointer pointAddedCommand = itk::SimpleMemberCommand<PickingTool>::New();\n pointAddedCommand->SetCallbackFunction(this, &mitk::PickingTool::OnPointAdded);\n m_PointSetAddObserverTag = m_PointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);\n\n \/\/ create new node for picked region\n m_ResultNode = mitk::DataNode::New();\n \/\/ set some properties\n m_ResultNode->SetProperty(\"name\", mitk::StringProperty::New(\"result\"));\n m_ResultNode->SetProperty(\"helper object\", mitk::BoolProperty::New(true));\n m_ResultNode->SetProperty(\"color\", mitk::ColorProperty::New(0, 1, 0));\n m_ResultNode->SetProperty(\"layer\", mitk::IntProperty::New(1));\n m_ResultNode->SetProperty(\"opacity\", mitk::FloatProperty::New(0.33f));\n}\n\nmitk::PickingTool::~PickingTool()\n{\n m_PointSet->RemoveObserver(m_PointSetAddObserverTag);\n}\n\nconst char **mitk::PickingTool::GetXPM() const\n{\n return nullptr;\n}\n\nconst char *mitk::PickingTool::GetName() const\n{\n return \"Picking\";\n}\n\nus::ModuleResource mitk::PickingTool::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Pick_48x48.png\");\n return resource;\n}\n\nvoid mitk::PickingTool::Activated()\n{\n Superclass::Activated();\n\n DataStorage *dataStorage = this->GetDataStorage();\n m_WorkingData = this->GetWorkingData();\n\n \/\/ add to datastorage and enable interaction\n if (!dataStorage->Exists(m_PointSetNode))\n dataStorage->Add(m_PointSetNode, m_WorkingData);\n\n m_SeedPointInteractor = mitk::SinglePointDataInteractor::New();\n m_SeedPointInteractor->LoadStateMachine(\"PointSet.xml\");\n m_SeedPointInteractor->SetEventConfig(\"PointSetConfig.xml\");\n m_SeedPointInteractor->SetDataNode(m_PointSetNode);\n\n \/\/ now add result to data tree\n dataStorage->Add(m_ResultNode, m_WorkingData);\n}\n\nvoid mitk::PickingTool::Deactivated()\n{\n m_PointSet->Clear();\n \/\/ remove from data storage and disable interaction\n GetDataStorage()->Remove(m_PointSetNode);\n GetDataStorage()->Remove(m_ResultNode);\n\n Superclass::Deactivated();\n}\n\nmitk::DataNode *mitk::PickingTool::GetReferenceData()\n{\n return this->m_ToolManager->GetReferenceData(0);\n}\n\nmitk::DataStorage *mitk::PickingTool::GetDataStorage()\n{\n return this->m_ToolManager->GetDataStorage();\n}\n\nmitk::DataNode *mitk::PickingTool::GetWorkingData()\n{\n return this->m_ToolManager->GetWorkingData(0);\n}\n\nmitk::DataNode::Pointer mitk::PickingTool::GetPointSetNode()\n{\n return m_PointSetNode;\n}\n\nvoid mitk::PickingTool::OnPointAdded()\n{\n if (m_WorkingData != this->GetWorkingData())\n {\n DataStorage *dataStorage = this->GetDataStorage();\n\n if (dataStorage->Exists(m_PointSetNode))\n {\n dataStorage->Remove(m_PointSetNode);\n dataStorage->Add(m_PointSetNode, this->GetWorkingData());\n }\n\n if (dataStorage->Exists(m_ResultNode))\n {\n dataStorage->Remove(m_ResultNode);\n dataStorage->Add(m_ResultNode, this->GetWorkingData());\n }\n\n m_WorkingData = this->GetWorkingData();\n }\n\n \/\/ Perform region growing\/picking\n\n int timeStep =\n mitk::BaseRenderer::GetInstance(mitk::BaseRenderer::GetRenderWindowByName(\"stdmulti.widget1\"))->GetTimeStep();\n\n mitk::PointSet::PointType seedPoint = m_PointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value();\n\n \/\/ as we want to pick a region from our segmentation image use the working data from ToolManager\n mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());\n\n if (orgImage.IsNotNull())\n {\n if (orgImage->GetDimension() == 4)\n { \/\/ there may be 4D segmentation data even though we currently don't support that\n mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();\n timeSelector->SetInput(orgImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n mitk::Image *timedImage = timeSelector->GetOutput();\n\n AccessByItk_2(timedImage, StartRegionGrowing, timedImage->GetGeometry(), seedPoint);\n }\n else if (orgImage->GetDimension() == 3)\n {\n AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint);\n }\n this->m_PointSet->Clear();\n }\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::PickingTool::StartRegionGrowing(itk::Image<TPixel, VImageDimension> *itkImage,\n mitk::BaseGeometry *imageGeometry,\n mitk::PointSet::PointType seedPoint)\n{\n typedef itk::Image<TPixel, VImageDimension> InputImageType;\n typedef typename InputImageType::IndexType IndexType;\n typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType;\n typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New();\n\n \/\/ convert world coordinates to image indices\n IndexType seedIndex;\n imageGeometry->WorldToIndex(seedPoint, seedIndex);\n\n \/\/ perform region growing in desired segmented region\n regionGrower->SetInput(itkImage);\n regionGrower->AddSeed(seedIndex);\n\n regionGrower->SetLower(1);\n regionGrower->SetUpper(255);\n\n try\n {\n regionGrower->Update();\n }\n catch (const itk::ExceptionObject &)\n {\n return; \/\/ can't work\n }\n catch (...)\n {\n return;\n }\n\n \/\/ Store result and preview\n mitk::Image::Pointer resultImage = mitk::ImportItkImage(regionGrower->GetOutput(), imageGeometry)->Clone();\n mitk::LabelSetImage::Pointer resultLabelSetImage = mitk::LabelSetImage::New();\n resultLabelSetImage->InitializeByLabeledImage(resultImage);\n\n m_ResultNode->SetData(resultLabelSetImage);\n\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\nvoid mitk::PickingTool::ConfirmSegmentation()\n{\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetProperty(\"name\", mitk::StringProperty::New(m_WorkingData->GetName() + \"_picked\"));\n\n float rgb[3] = {1.0f, 0.0f, 0.0f};\n m_WorkingData->GetColor(rgb);\n newNode->SetProperty(\"color\", mitk::ColorProperty::New(rgb));\n\n float opacity = 1.0f;\n m_WorkingData->GetOpacity(opacity, nullptr);\n newNode->SetProperty(\"opacity\", mitk::FloatProperty::New(opacity));\n\n newNode->SetData(m_ResultNode->GetData());\n\n GetDataStorage()->Add(newNode, this->GetReferenceData());\n m_WorkingData->SetVisibility(false);\n\n m_ResultNode->SetData(nullptr);\n\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c)2008-2012, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"ipv4.h\"\n\n#include <stddef.h>\n#include <stdio.h>\n#include <algorithm>\n#include <sstream>\n\nusing namespace std;\n\nnamespace pfi {\nnamespace network {\n\nipv4_address::ipv4_address() : ip() {}\n\nipv4_address::ipv4_address(unsigned char a,\n unsigned char b,\n unsigned char c,\n unsigned char d)\n{\n ip[0]=a;\n ip[1]=b;\n ip[2]=c;\n ip[3]=d;\n}\n\nipv4_address::ipv4_address(const string& s)\n{\n int buf[4];\n if (sscanf(s.c_str(), \"%d.%d.%d.%d\", &buf[0], &buf[1], &buf[2], &buf[3]) != 4) {\n *this = none;\n return;\n }\n for (size_t i = 0; i < sizeof(buf)\/sizeof(buf[0]); ++i) {\n ip[i] = buf[i];\n if (buf[i] < 0 || buf[1] > 255) {\n *this = none;\n return;\n }\n }\n}\n\nbool ipv4_address::operator==(const ipv4_address& p) const\n{\n return std::equal(ip, ip+sizeof(ip), p.ip);\n}\n\nbool ipv4_address::operator!=(const ipv4_address& p) const\n{\n return !(*this==p);\n}\n\nbool ipv4_address::operator<(const ipv4_address& p) const\n{\n if (ip[0]!=p.ip[0]) return ip[0]<p.ip[0];\n if (ip[1]!=p.ip[1]) return ip[1]<p.ip[1];\n if (ip[2]!=p.ip[2]) return ip[2]<p.ip[2];\n return ip[3]<p.ip[3];\n}\n\nconst string ipv4_address::to_string() const\n{\n ostringstream oss;\n oss<<(int)ip[0]<<'.'<<(int)ip[1]<<'.'<<(int)ip[2]<<'.'<<(int)ip[3];\n return oss.str();\n};\n\nconst ipv4_address ipv4_address::any = ipv4_address( 0, 0, 0, 0);\nconst ipv4_address ipv4_address::broadcast = ipv4_address(255,255,255,255);\nconst ipv4_address ipv4_address::loopback = ipv4_address(127, 0, 0, 1);\nconst ipv4_address ipv4_address::none = ipv4_address(255,255,255,255);\n\n} \/\/ network\n} \/\/ pfi\n<commit_msg>Modified ipv4_address::operator<()'s implementation.<commit_after>\/\/ Copyright (c)2008-2012, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"ipv4.h\"\n\n#include <stddef.h>\n#include <stdio.h>\n#include <algorithm>\n#include <sstream>\n\nusing namespace std;\n\nnamespace pfi {\nnamespace network {\n\nipv4_address::ipv4_address() : ip() {}\n\nipv4_address::ipv4_address(unsigned char a,\n unsigned char b,\n unsigned char c,\n unsigned char d)\n{\n ip[0]=a;\n ip[1]=b;\n ip[2]=c;\n ip[3]=d;\n}\n\nipv4_address::ipv4_address(const string& s)\n{\n int buf[4];\n if (sscanf(s.c_str(), \"%d.%d.%d.%d\", &buf[0], &buf[1], &buf[2], &buf[3]) != 4) {\n *this = none;\n return;\n }\n for (size_t i = 0; i < sizeof(buf)\/sizeof(buf[0]); ++i) {\n ip[i] = buf[i];\n if (buf[i] < 0 || buf[1] > 255) {\n *this = none;\n return;\n }\n }\n}\n\nbool ipv4_address::operator==(const ipv4_address& p) const\n{\n return std::equal(ip, ip+sizeof(ip), p.ip);\n}\n\nbool ipv4_address::operator!=(const ipv4_address& p) const\n{\n return !(*this==p);\n}\n\nbool ipv4_address::operator<(const ipv4_address& p) const\n{\n return std::lexicographical_compare(ip, ip+sizeof(ip), p.ip, p.ip+sizeof(p.ip));\n}\n\nconst string ipv4_address::to_string() const\n{\n ostringstream oss;\n oss<<(int)ip[0]<<'.'<<(int)ip[1]<<'.'<<(int)ip[2]<<'.'<<(int)ip[3];\n return oss.str();\n};\n\nconst ipv4_address ipv4_address::any = ipv4_address( 0, 0, 0, 0);\nconst ipv4_address ipv4_address::broadcast = ipv4_address(255,255,255,255);\nconst ipv4_address ipv4_address::loopback = ipv4_address(127, 0, 0, 1);\nconst ipv4_address ipv4_address::none = ipv4_address(255,255,255,255);\n\n} \/\/ network\n} \/\/ pfi\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 1999 Lars Knoll (knoll@kde.org)\n * Copyright (C) 2000 Dirk Mueller (mueller@kde.org)\n * Copyright (C) 2004, 2006, 2009, 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderWidget.h\"\n\n#include \"core\/accessibility\/AXObjectCache.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/html\/HTMLFrameOwnerElement.h\"\n#include \"core\/html\/HTMLPlugInElement.h\"\n#include \"core\/paint\/BoxPainter.h\"\n#include \"core\/rendering\/GraphicsContextAnnotator.h\"\n#include \"core\/rendering\/HitTestResult.h\"\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderView.h\"\n#include \"core\/rendering\/compositing\/CompositedLayerMapping.h\"\n#include \"core\/rendering\/compositing\/RenderLayerCompositor.h\"\n#include \"wtf\/HashMap.h\"\n\nnamespace blink {\n\nRenderWidget::RenderWidget(Element* element)\n : RenderReplaced(element)\n#if !ENABLE(OILPAN)\n \/\/ Reference counting is used to prevent the widget from being\n \/\/ destroyed while inside the Widget code, which might not be\n \/\/ able to handle that.\n , m_refCount(1)\n#endif\n{\n ASSERT(element);\n frameView()->addWidget(this);\n}\n\nvoid RenderWidget::willBeDestroyed()\n{\n frameView()->removeWidget(this);\n\n if (AXObjectCache* cache = document().existingAXObjectCache()) {\n cache->childrenChanged(this->parent());\n cache->remove(this);\n }\n\n Element* element = toElement(node());\n if (element && element->isFrameOwnerElement())\n toHTMLFrameOwnerElement(element)->setWidget(nullptr);\n\n RenderReplaced::willBeDestroyed();\n}\n\nvoid RenderWidget::destroy()\n{\n#if ENABLE(ASSERT) && ENABLE(OILPAN)\n ASSERT(!m_didCallDestroy);\n m_didCallDestroy = true;\n#endif\n willBeDestroyed();\n clearNode();\n#if ENABLE(OILPAN)\n \/\/ In Oilpan, postDestroy doesn't delete |this|. So calling it here is safe\n \/\/ though |this| will be referred in FrameView.\n postDestroy();\n#else\n deref();\n#endif\n}\n\nRenderWidget::~RenderWidget()\n{\n#if !ENABLE(OILPAN)\n ASSERT(m_refCount <= 0);\n#endif\n}\n\nWidget* RenderWidget::widget() const\n{\n \/\/ Plugin widgets are stored in their DOM node. This includes HTMLAppletElement.\n Element* element = toElement(node());\n\n if (element && element->isFrameOwnerElement())\n return toHTMLFrameOwnerElement(element)->ownedWidget();\n\n return 0;\n}\n\n\/\/ Widgets are always placed on integer boundaries, so rounding the size is actually\n\/\/ the desired behavior. This function is here because it's otherwise seldom what we\n\/\/ want to do with a LayoutRect.\nstatic inline IntRect roundedIntRect(const LayoutRect& rect)\n{\n return IntRect(roundedIntPoint(rect.location()), roundedIntSize(rect.size()));\n}\n\nbool RenderWidget::setWidgetGeometry(const LayoutRect& frame)\n{\n if (!node())\n return false;\n\n Widget* widget = this->widget();\n ASSERT(widget);\n\n IntRect newFrame = roundedIntRect(frame);\n\n if (widget->frameRect() == newFrame)\n return false;\n\n RefPtrWillBeRawPtr<RenderWidget> protector(this);\n RefPtrWillBeRawPtr<Node> protectedNode(node());\n widget->setFrameRect(newFrame);\n return widget->frameRect().size() != newFrame.size();\n}\n\nbool RenderWidget::updateWidgetGeometry()\n{\n Widget* widget = this->widget();\n ASSERT(widget);\n\n LayoutRect contentBox = contentBoxRect();\n LayoutRect absoluteContentBox(localToAbsoluteQuad(FloatQuad(contentBox)).boundingBox());\n if (widget->isFrameView()) {\n contentBox.setLocation(absoluteContentBox.location());\n return setWidgetGeometry(contentBox);\n }\n\n return setWidgetGeometry(absoluteContentBox);\n}\n\nvoid RenderWidget::layout()\n{\n ASSERT(needsLayout());\n\n clearNeedsLayout();\n}\n\nvoid RenderWidget::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)\n{\n RenderReplaced::styleDidChange(diff, oldStyle);\n Widget* widget = this->widget();\n\n if (widget) {\n if (style()->visibility() != VISIBLE) {\n widget->hide();\n } else {\n widget->show();\n }\n }\n}\n\nvoid RenderWidget::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n LayoutPoint adjustedPaintOffset = paintOffset + location();\n\n Widget* widget = this->widget();\n ASSERT(widget);\n\n \/\/ Tell the widget to paint now. This is the only time the widget is allowed\n \/\/ to paint itself. That way it will composite properly with z-indexed layers.\n IntPoint widgetLocation = widget->frameRect().location();\n IntPoint paintLocation(roundToInt(adjustedPaintOffset.x() + borderLeft() + paddingLeft()),\n roundToInt(adjustedPaintOffset.y() + borderTop() + paddingTop()));\n IntRect paintRect = paintInfo.rect;\n\n IntSize widgetPaintOffset = paintLocation - widgetLocation;\n \/\/ When painting widgets into compositing layers, tx and ty are relative to the enclosing compositing layer,\n \/\/ not the root. In this case, shift the CTM and adjust the paintRect to be root-relative to fix plug-in drawing.\n if (!widgetPaintOffset.isZero()) {\n paintInfo.context->translate(widgetPaintOffset.width(), widgetPaintOffset.height());\n paintRect.move(-widgetPaintOffset);\n }\n widget->paint(paintInfo.context, paintRect);\n\n if (!widgetPaintOffset.isZero())\n paintInfo.context->translate(-widgetPaintOffset.width(), -widgetPaintOffset.height());\n}\n\nvoid RenderWidget::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);\n\n if (!shouldPaint(paintInfo, paintOffset))\n return;\n\n LayoutPoint adjustedPaintOffset = paintOffset + location();\n\n if (hasBoxDecorationBackground() && (paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection))\n paintBoxDecorationBackground(paintInfo, adjustedPaintOffset);\n\n if (paintInfo.phase == PaintPhaseMask) {\n paintMask(paintInfo, adjustedPaintOffset);\n return;\n }\n\n if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->hasOutline())\n paintOutline(paintInfo, LayoutRect(adjustedPaintOffset, size()));\n\n if (paintInfo.phase != PaintPhaseForeground)\n return;\n\n if (style()->hasBorderRadius()) {\n LayoutRect borderRect = LayoutRect(adjustedPaintOffset, size());\n\n if (borderRect.isEmpty())\n return;\n\n \/\/ Push a clip if we have a border radius, since we want to round the foreground content that gets painted.\n paintInfo.context->save();\n RoundedRect roundedInnerRect = style()->getRoundedInnerBorderFor(borderRect,\n paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), true, true);\n BoxPainter::clipRoundedInnerRect(paintInfo.context, borderRect, roundedInnerRect);\n }\n\n Widget* widget = this->widget();\n if (widget)\n paintContents(paintInfo, paintOffset);\n\n if (style()->hasBorderRadius())\n paintInfo.context->restore();\n\n \/\/ Paint a partially transparent wash over selected widgets.\n if (isSelected() && !document().printing()) {\n LayoutRect rect = localSelectionRect();\n rect.moveBy(adjustedPaintOffset);\n paintInfo.context->fillRect(pixelSnappedIntRect(rect), selectionBackgroundColor());\n }\n\n if (canResize())\n layer()->scrollableArea()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);\n}\n\n#if !ENABLE(OILPAN)\nvoid RenderWidget::deref()\n{\n if (--m_refCount <= 0)\n postDestroy();\n}\n#endif\n\nvoid RenderWidget::updateOnWidgetChange()\n{\n Widget* widget = this->widget();\n if (!widget)\n return;\n\n if (!style())\n return;\n\n if (!needsLayout())\n updateWidgetGeometry();\n\n if (style()->visibility() != VISIBLE) {\n widget->hide();\n } else {\n widget->show();\n \/\/ FIXME: Why do we issue a full paint invalidation in this case, but not the other?\n setShouldDoFullPaintInvalidation(true);\n }\n}\n\nvoid RenderWidget::updateWidgetPosition()\n{\n Widget* widget = this->widget();\n if (!widget || !node()) \/\/ Check the node in case destroy() has been called.\n return;\n\n bool boundsChanged = updateWidgetGeometry();\n\n \/\/ if the frame bounds got changed, or if view needs layout (possibly indicating\n \/\/ content size is wrong) we have to do a layout to set the right widget size\n if (widget && widget->isFrameView()) {\n FrameView* frameView = toFrameView(widget);\n \/\/ Check the frame's page to make sure that the frame isn't in the process of being destroyed.\n if ((boundsChanged || frameView->needsLayout()) && frameView->frame().page())\n frameView->layout();\n }\n}\n\nvoid RenderWidget::widgetPositionsUpdated()\n{\n Widget* widget = this->widget();\n if (!widget)\n return;\n widget->widgetPositionsUpdated();\n}\n\nbool RenderWidget::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)\n{\n bool hadResult = result.innerNode();\n bool inside = RenderReplaced::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, action);\n\n \/\/ Check to see if we are really over the widget itself (and not just in the border\/padding area).\n if ((inside || result.isRectBasedTest()) && !hadResult && result.innerNode() == node())\n result.setIsOverWidget(contentBoxRect().contains(result.localPoint()));\n return inside;\n}\n\nCursorDirective RenderWidget::getCursor(const LayoutPoint& point, Cursor& cursor) const\n{\n if (widget() && widget()->isPluginView()) {\n \/\/ A plug-in is responsible for setting the cursor when the pointer is over it.\n return DoNotSetCursor;\n }\n return RenderReplaced::getCursor(point, cursor);\n}\n\n} \/\/ namespace blink\n<commit_msg>Crash when the widget is 0 in RenderWidget::paintContents.<commit_after>\/*\n * Copyright (C) 1999 Lars Knoll (knoll@kde.org)\n * Copyright (C) 2000 Dirk Mueller (mueller@kde.org)\n * Copyright (C) 2004, 2006, 2009, 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderWidget.h\"\n\n#include \"core\/accessibility\/AXObjectCache.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/html\/HTMLFrameOwnerElement.h\"\n#include \"core\/html\/HTMLPlugInElement.h\"\n#include \"core\/paint\/BoxPainter.h\"\n#include \"core\/rendering\/GraphicsContextAnnotator.h\"\n#include \"core\/rendering\/HitTestResult.h\"\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderView.h\"\n#include \"core\/rendering\/compositing\/CompositedLayerMapping.h\"\n#include \"core\/rendering\/compositing\/RenderLayerCompositor.h\"\n#include \"wtf\/HashMap.h\"\n\nnamespace blink {\n\nRenderWidget::RenderWidget(Element* element)\n : RenderReplaced(element)\n#if !ENABLE(OILPAN)\n \/\/ Reference counting is used to prevent the widget from being\n \/\/ destroyed while inside the Widget code, which might not be\n \/\/ able to handle that.\n , m_refCount(1)\n#endif\n{\n ASSERT(element);\n frameView()->addWidget(this);\n}\n\nvoid RenderWidget::willBeDestroyed()\n{\n frameView()->removeWidget(this);\n\n if (AXObjectCache* cache = document().existingAXObjectCache()) {\n cache->childrenChanged(this->parent());\n cache->remove(this);\n }\n\n Element* element = toElement(node());\n if (element && element->isFrameOwnerElement())\n toHTMLFrameOwnerElement(element)->setWidget(nullptr);\n\n RenderReplaced::willBeDestroyed();\n}\n\nvoid RenderWidget::destroy()\n{\n#if ENABLE(ASSERT) && ENABLE(OILPAN)\n ASSERT(!m_didCallDestroy);\n m_didCallDestroy = true;\n#endif\n willBeDestroyed();\n clearNode();\n#if ENABLE(OILPAN)\n \/\/ In Oilpan, postDestroy doesn't delete |this|. So calling it here is safe\n \/\/ though |this| will be referred in FrameView.\n postDestroy();\n#else\n deref();\n#endif\n}\n\nRenderWidget::~RenderWidget()\n{\n#if !ENABLE(OILPAN)\n ASSERT(m_refCount <= 0);\n#endif\n}\n\nWidget* RenderWidget::widget() const\n{\n \/\/ Plugin widgets are stored in their DOM node. This includes HTMLAppletElement.\n Element* element = toElement(node());\n\n if (element && element->isFrameOwnerElement())\n return toHTMLFrameOwnerElement(element)->ownedWidget();\n\n return 0;\n}\n\n\/\/ Widgets are always placed on integer boundaries, so rounding the size is actually\n\/\/ the desired behavior. This function is here because it's otherwise seldom what we\n\/\/ want to do with a LayoutRect.\nstatic inline IntRect roundedIntRect(const LayoutRect& rect)\n{\n return IntRect(roundedIntPoint(rect.location()), roundedIntSize(rect.size()));\n}\n\nbool RenderWidget::setWidgetGeometry(const LayoutRect& frame)\n{\n if (!node())\n return false;\n\n Widget* widget = this->widget();\n ASSERT(widget);\n\n IntRect newFrame = roundedIntRect(frame);\n\n if (widget->frameRect() == newFrame)\n return false;\n\n RefPtrWillBeRawPtr<RenderWidget> protector(this);\n RefPtrWillBeRawPtr<Node> protectedNode(node());\n widget->setFrameRect(newFrame);\n return widget->frameRect().size() != newFrame.size();\n}\n\nbool RenderWidget::updateWidgetGeometry()\n{\n Widget* widget = this->widget();\n ASSERT(widget);\n\n LayoutRect contentBox = contentBoxRect();\n LayoutRect absoluteContentBox(localToAbsoluteQuad(FloatQuad(contentBox)).boundingBox());\n if (widget->isFrameView()) {\n contentBox.setLocation(absoluteContentBox.location());\n return setWidgetGeometry(contentBox);\n }\n\n return setWidgetGeometry(absoluteContentBox);\n}\n\nvoid RenderWidget::layout()\n{\n ASSERT(needsLayout());\n\n clearNeedsLayout();\n}\n\nvoid RenderWidget::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)\n{\n RenderReplaced::styleDidChange(diff, oldStyle);\n Widget* widget = this->widget();\n\n if (widget) {\n if (style()->visibility() != VISIBLE) {\n widget->hide();\n } else {\n widget->show();\n }\n }\n}\n\nvoid RenderWidget::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n LayoutPoint adjustedPaintOffset = paintOffset + location();\n\n Widget* widget = this->widget();\n RELEASE_ASSERT(widget);\n\n \/\/ Tell the widget to paint now. This is the only time the widget is allowed\n \/\/ to paint itself. That way it will composite properly with z-indexed layers.\n IntPoint widgetLocation = widget->frameRect().location();\n IntPoint paintLocation(roundToInt(adjustedPaintOffset.x() + borderLeft() + paddingLeft()),\n roundToInt(adjustedPaintOffset.y() + borderTop() + paddingTop()));\n IntRect paintRect = paintInfo.rect;\n\n IntSize widgetPaintOffset = paintLocation - widgetLocation;\n \/\/ When painting widgets into compositing layers, tx and ty are relative to the enclosing compositing layer,\n \/\/ not the root. In this case, shift the CTM and adjust the paintRect to be root-relative to fix plug-in drawing.\n if (!widgetPaintOffset.isZero()) {\n paintInfo.context->translate(widgetPaintOffset.width(), widgetPaintOffset.height());\n paintRect.move(-widgetPaintOffset);\n }\n widget->paint(paintInfo.context, paintRect);\n\n if (!widgetPaintOffset.isZero())\n paintInfo.context->translate(-widgetPaintOffset.width(), -widgetPaintOffset.height());\n}\n\nvoid RenderWidget::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)\n{\n ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);\n\n if (!shouldPaint(paintInfo, paintOffset))\n return;\n\n LayoutPoint adjustedPaintOffset = paintOffset + location();\n\n if (hasBoxDecorationBackground() && (paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection))\n paintBoxDecorationBackground(paintInfo, adjustedPaintOffset);\n\n if (paintInfo.phase == PaintPhaseMask) {\n paintMask(paintInfo, adjustedPaintOffset);\n return;\n }\n\n if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->hasOutline())\n paintOutline(paintInfo, LayoutRect(adjustedPaintOffset, size()));\n\n if (paintInfo.phase != PaintPhaseForeground)\n return;\n\n if (style()->hasBorderRadius()) {\n LayoutRect borderRect = LayoutRect(adjustedPaintOffset, size());\n\n if (borderRect.isEmpty())\n return;\n\n \/\/ Push a clip if we have a border radius, since we want to round the foreground content that gets painted.\n paintInfo.context->save();\n RoundedRect roundedInnerRect = style()->getRoundedInnerBorderFor(borderRect,\n paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), true, true);\n BoxPainter::clipRoundedInnerRect(paintInfo.context, borderRect, roundedInnerRect);\n }\n\n Widget* widget = this->widget();\n if (widget)\n paintContents(paintInfo, paintOffset);\n\n if (style()->hasBorderRadius())\n paintInfo.context->restore();\n\n \/\/ Paint a partially transparent wash over selected widgets.\n if (isSelected() && !document().printing()) {\n LayoutRect rect = localSelectionRect();\n rect.moveBy(adjustedPaintOffset);\n paintInfo.context->fillRect(pixelSnappedIntRect(rect), selectionBackgroundColor());\n }\n\n if (canResize())\n layer()->scrollableArea()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);\n}\n\n#if !ENABLE(OILPAN)\nvoid RenderWidget::deref()\n{\n if (--m_refCount <= 0)\n postDestroy();\n}\n#endif\n\nvoid RenderWidget::updateOnWidgetChange()\n{\n Widget* widget = this->widget();\n if (!widget)\n return;\n\n if (!style())\n return;\n\n if (!needsLayout())\n updateWidgetGeometry();\n\n if (style()->visibility() != VISIBLE) {\n widget->hide();\n } else {\n widget->show();\n \/\/ FIXME: Why do we issue a full paint invalidation in this case, but not the other?\n setShouldDoFullPaintInvalidation(true);\n }\n}\n\nvoid RenderWidget::updateWidgetPosition()\n{\n Widget* widget = this->widget();\n if (!widget || !node()) \/\/ Check the node in case destroy() has been called.\n return;\n\n bool boundsChanged = updateWidgetGeometry();\n\n \/\/ if the frame bounds got changed, or if view needs layout (possibly indicating\n \/\/ content size is wrong) we have to do a layout to set the right widget size\n if (widget && widget->isFrameView()) {\n FrameView* frameView = toFrameView(widget);\n \/\/ Check the frame's page to make sure that the frame isn't in the process of being destroyed.\n if ((boundsChanged || frameView->needsLayout()) && frameView->frame().page())\n frameView->layout();\n }\n}\n\nvoid RenderWidget::widgetPositionsUpdated()\n{\n Widget* widget = this->widget();\n if (!widget)\n return;\n widget->widgetPositionsUpdated();\n}\n\nbool RenderWidget::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)\n{\n bool hadResult = result.innerNode();\n bool inside = RenderReplaced::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, action);\n\n \/\/ Check to see if we are really over the widget itself (and not just in the border\/padding area).\n if ((inside || result.isRectBasedTest()) && !hadResult && result.innerNode() == node())\n result.setIsOverWidget(contentBoxRect().contains(result.localPoint()));\n return inside;\n}\n\nCursorDirective RenderWidget::getCursor(const LayoutPoint& point, Cursor& cursor) const\n{\n if (widget() && widget()->isPluginView()) {\n \/\/ A plug-in is responsible for setting the cursor when the pointer is over it.\n return DoNotSetCursor;\n }\n return RenderReplaced::getCursor(point, cursor);\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>#include <core\/stdafx.h>\n#include <core\/interpret\/flags.h>\n#include <core\/utility\/strings.h>\n#include <core\/addin\/addin.h>\n#include <core\/addin\/mfcmapi.h>\n\nnamespace flags\n{\n\t\/\/ Interprets a flag value according to a flag name and returns a string\n\t\/\/ Will not return a string if the flag name is not recognized\n\tstd::wstring InterpretFlags(ULONG ulFlagName, LONG lFlagValue)\n\t{\n\t\tULONG ulCurEntry = 0;\n\n\t\tif (FlagArray.empty()) return L\"\";\n\n\t\twhile (ulCurEntry < FlagArray.size() && FlagArray[ulCurEntry].ulFlagName != ulFlagName)\n\t\t{\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\t\/\/ Don't run off the end of the array\n\t\tif (FlagArray.size() == ulCurEntry) return L\"\";\n\t\tif (FlagArray[ulCurEntry].ulFlagName != ulFlagName) return L\"\";\n\n\t\t\/\/ We've matched our flag name to the array - we SHOULD return a string at this point\n\t\tauto flags = std::vector<std::wstring>{};\n\t\tauto lTempValue = lFlagValue;\n\t\tfor (; FlagArray[ulCurEntry].ulFlagName == ulFlagName; ulCurEntry++)\n\t\t{\n\t\t\tif (flagFLAG == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue & lTempValue)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue &= ~FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagVALUE == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == lTempValue)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagVALUEHIGHBYTES == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue >> 16 & 0xFFFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - (FlagArray[ulCurEntry].lFlagValue << 16);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagVALUE3RDBYTE == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue >> 8 & 0xFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - (FlagArray[ulCurEntry].lFlagValue << 8);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagVALUE4THBYTE == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue & 0xFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagVALUELOWERNIBBLE == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (flagCLEARBITS == FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\t\/\/ find any bits we need to clear\n\t\t\t\tconst auto lClearedBits = FlagArray[ulCurEntry].lFlagValue & lTempValue;\n\t\t\t\t\/\/ report what we found\n\t\t\t\tif (0 != lClearedBits)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(strings::format(L\"0x%X\", lClearedBits)); \/\/ STRING_OK\n\t\t\t\t\t\t\/\/ clear the bits out\n\t\t\t\t\tlTempValue &= ~FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (lTempValue || flags.empty())\n\t\t{\n\t\t\tflags.push_back(strings::format(L\"0x%X\", lTempValue)); \/\/ STRING_OK\n\t\t}\n\n\t\treturn strings::join(flags, L\" | \");\n\t}\n\n\t\/\/ Returns a list of all known flags\/values for a flag name.\n\t\/\/ For instance, for flagFuzzyLevel, would return:\n\t\/\/ 0x00000000 FL_FULLSTRING\\r\\n\\\n\t\/\/ 0x00000001 FL_SUBSTRING\\r\\n\\\n\t\/\/ 0x00000002 FL_PREFIX\\r\\n\\\n\t\/\/ 0x00010000 FL_IGNORECASE\\r\\n\\\n\t\/\/ 0x00020000 FL_IGNORENONSPACE\\r\\n\\\n\t\/\/ 0x00040000 FL_LOOSE\n\t\/\/\n\t\/\/ Since the string is always appended to a prompt we include \\r\\n at the start\n\tstd::wstring AllFlagsToString(ULONG ulFlagName, bool bHex)\n\t{\n\t\tif (!ulFlagName) return L\"\";\n\t\tif (FlagArray.empty()) return L\"\";\n\n\t\tULONG ulCurEntry = 0;\n\n\t\twhile (ulCurEntry < FlagArray.size() && FlagArray[ulCurEntry].ulFlagName != ulFlagName)\n\t\t{\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\tif (ulCurEntry == FlagArray.size() || FlagArray[ulCurEntry].ulFlagName != ulFlagName) return L\"\";\n\n\t\t\/\/ We've matched our flag name to the array - we SHOULD return a string at this point\n\t\tauto flags = std::vector<std::wstring>{};\n\t\twhile (FlagArray[ulCurEntry].ulFlagName == ulFlagName)\n\t\t{\n\t\t\tif (flagCLEARBITS != FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tflags.push_back(strings::formatmessage(\n\t\t\t\t\tbHex ? IDS_FLAGTOSTRINGHEX : IDS_FLAGTOSTRINGDEC,\n\t\t\t\t\tFlagArray[ulCurEntry].lFlagValue,\n\t\t\t\t\tFlagArray[ulCurEntry].lpszName));\n\t\t\t}\n\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\treturn strings::join(flags, L\"\\r\\n\");\n\t}\n} \/\/ namespace flags\n<commit_msg>rewrite as switch<commit_after>#include <core\/stdafx.h>\n#include <core\/interpret\/flags.h>\n#include <core\/utility\/strings.h>\n#include <core\/addin\/addin.h>\n#include <core\/addin\/mfcmapi.h>\n\nnamespace flags\n{\n\t\/\/ Interprets a flag value according to a flag name and returns a string\n\t\/\/ Will not return a string if the flag name is not recognized\n\tstd::wstring InterpretFlags(ULONG ulFlagName, LONG lFlagValue)\n\t{\n\t\tULONG ulCurEntry = 0;\n\n\t\tif (FlagArray.empty()) return L\"\";\n\n\t\twhile (ulCurEntry < FlagArray.size() && FlagArray[ulCurEntry].ulFlagName != ulFlagName)\n\t\t{\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\t\/\/ Don't run off the end of the array\n\t\tif (FlagArray.size() == ulCurEntry) return L\"\";\n\t\tif (FlagArray[ulCurEntry].ulFlagName != ulFlagName) return L\"\";\n\n\t\t\/\/ We've matched our flag name to the array - we SHOULD return a string at this point\n\t\tauto flags = std::vector<std::wstring>{};\n\t\tauto lTempValue = lFlagValue;\n\t\twhile (FlagArray[ulCurEntry].ulFlagName == ulFlagName)\n\t\t{\n\t\t\tswitch (FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\tcase flagFLAG:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue & lTempValue)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue &= ~FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagVALUE:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == lTempValue)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagVALUEHIGHBYTES:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue >> 16 & 0xFFFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - (FlagArray[ulCurEntry].lFlagValue << 16);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagVALUE3RDBYTE:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue >> 8 & 0xFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - (FlagArray[ulCurEntry].lFlagValue << 8);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagVALUE4THBYTE:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue & 0xFF))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagVALUELOWERNIBBLE:\n\t\t\t\tif (FlagArray[ulCurEntry].lFlagValue == (lTempValue & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(FlagArray[ulCurEntry].lpszName);\n\t\t\t\t\tlTempValue = lTempValue - FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase flagCLEARBITS:\n\t\t\t\t\/\/ find any bits we need to clear\n\t\t\t\tconst auto lClearedBits = FlagArray[ulCurEntry].lFlagValue & lTempValue;\n\t\t\t\t\/\/ report what we found\n\t\t\t\tif (lClearedBits != 0)\n\t\t\t\t{\n\t\t\t\t\tflags.push_back(strings::format(L\"0x%X\", lClearedBits)); \/\/ STRING_OK\n\t\t\t\t\t\t\/\/ clear the bits out\n\t\t\t\t\tlTempValue &= ~FlagArray[ulCurEntry].lFlagValue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\tif (lTempValue || flags.empty())\n\t\t{\n\t\t\tflags.push_back(strings::format(L\"0x%X\", lTempValue)); \/\/ STRING_OK\n\t\t}\n\n\t\treturn strings::join(flags, L\" | \");\n\t}\n\n\t\/\/ Returns a list of all known flags\/values for a flag name.\n\t\/\/ For instance, for flagFuzzyLevel, would return:\n\t\/\/ 0x00000000 FL_FULLSTRING\\r\\n\\\n\t\/\/ 0x00000001 FL_SUBSTRING\\r\\n\\\n\t\/\/ 0x00000002 FL_PREFIX\\r\\n\\\n\t\/\/ 0x00010000 FL_IGNORECASE\\r\\n\\\n\t\/\/ 0x00020000 FL_IGNORENONSPACE\\r\\n\\\n\t\/\/ 0x00040000 FL_LOOSE\n\t\/\/\n\t\/\/ Since the string is always appended to a prompt we include \\r\\n at the start\n\tstd::wstring AllFlagsToString(ULONG ulFlagName, bool bHex)\n\t{\n\t\tif (!ulFlagName) return L\"\";\n\t\tif (FlagArray.empty()) return L\"\";\n\n\t\tULONG ulCurEntry = 0;\n\n\t\twhile (ulCurEntry < FlagArray.size() && FlagArray[ulCurEntry].ulFlagName != ulFlagName)\n\t\t{\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\tif (ulCurEntry == FlagArray.size() || FlagArray[ulCurEntry].ulFlagName != ulFlagName) return L\"\";\n\n\t\t\/\/ We've matched our flag name to the array - we SHOULD return a string at this point\n\t\tauto flags = std::vector<std::wstring>{};\n\t\twhile (FlagArray[ulCurEntry].ulFlagName == ulFlagName)\n\t\t{\n\t\t\tif (flagCLEARBITS != FlagArray[ulCurEntry].ulFlagType)\n\t\t\t{\n\t\t\t\tflags.push_back(strings::formatmessage(\n\t\t\t\t\tbHex ? IDS_FLAGTOSTRINGHEX : IDS_FLAGTOSTRINGDEC,\n\t\t\t\t\tFlagArray[ulCurEntry].lFlagValue,\n\t\t\t\t\tFlagArray[ulCurEntry].lpszName));\n\t\t\t}\n\n\t\t\tulCurEntry++;\n\t\t}\n\n\t\treturn strings::join(flags, L\"\\r\\n\");\n\t}\n} \/\/ namespace flags\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n\n#include <memory>\n#include <sstream>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/lobby.hh>\n#include <object\/list.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/call.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n\n\n rObject\n execute_parsed(runner::Runner& r,\n parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n runner::raise_primitive_error(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n scheduler::rJob job = sub;\n libport::Finally finally;\n r.register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const scheduler::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 0); \\\n ::urbiserver->Function();\t\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static rObject\n system_class_sleep (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n\n type_check(args[1], Float::proto);\n\n rFloat arg1 = args[1]->as<Float>();\n libport::utime_t deadline;\n if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n r.yield_until_terminated(r);\n else\n {\n deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000000.0);\n r.yield_until (deadline);\n }\n return void_class;\n }\n\n static rObject\n system_class_time(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(r.scheduler_get().get_time() \/ 1000000.0);\n }\n\n static rObject\n system_class_shiftedTime(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float((r.scheduler_get().get_time() -\n\t\t\t r.time_shift_get()) \/ 1000000.0);\n }\n\n static rObject\n system_class_assert_(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 2);\n type_check(args[2], String::proto);\n rString arg2 = args[2]->as<String>();\n if (!is_true(args[1]))\n runner::raise_primitive_error(\"assertion `\" + arg2->value_get() +\n\t\t\t\t \"' failed\");\n return void_class;\n }\n\n static rObject\n system_class_eval(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], String::proto);\n rString arg1 = args[1]->as<String>();\n return\n execute_parsed(r, parser::parse(arg1->value_get()),\n SYMBOL(eval),\n \"error executing command: \" + arg1->value_get());\n }\n\n static rObject\n system_class_registerAtJob (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 3);\n runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t args[1], args[2], args[3]);\n return object::void_class;\n }\n\n static rObject\n system_class_scopeTag(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n const scheduler::rTag& scope_tag =\n dynamic_cast<runner::Interpreter&>(r).scope_tag();\n return new Tag(scope_tag);\n }\n\n static rObject\n system_class_searchFile (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], String::proto);\n const rString& arg1 = args[1]->as<String>();\n\n UServer& s = r.lobby_get()->value_get().connection.server_get();\n try\n {\n return new String(s.find_file(arg1->value_get()));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), arg1);\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static rObject\n system_class_loadFile(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], String::proto);\n const rString& arg1 = args[1]->as<String>();\n\n const std::string& filename = arg1->value_get();\n\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(r, parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_class_currentRunner (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return r.as_task();\n }\n\n static rObject\n system_class_cycle (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(r.scheduler_get ().cycle_get ());\n }\n\n static rObject\n system_class_fresh (runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new String(libport::Symbol::fresh());\n }\n\n static rObject\n system_class_lobby (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return r.lobby_get();\n }\n\n static rObject\n system_class_nonInterruptible (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n r.non_interruptible_set (true);\n return void_class;\n }\n\n static rObject\n system_class_quit (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n r.lobby_get()->value_get().connection.close();\n return void_class;\n }\n\n static rObject\n system_class_spawn(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n rObject arg1 = args[1]->as<Code>();\n assert(arg1);\n\n runner::Interpreter* new_runner =\n new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),\n\t\t\t rObject(arg1),\n\t\t\t libport::Symbol::fresh(r.name_get()));\n new_runner->copy_tags (r);\n new_runner->time_shift_set (r.time_shift_get ());\n\n new_runner->start_job ();\n\n return object::void_class;\n }\n\n static rObject\n system_class_stats(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n Dictionary::value_type res;\n const scheduler::scheduler_stats_type& stats =\n r.scheduler_get().stats_get();\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1000.0);\n ADDSTAT(Mean, mean, 1000.0);\n ADDSTAT(Min, min, 1000.0);\n ADDSTAT(StdDev, standard_deviation, 1000.0);\n ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static rObject\n system_class_platform(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n#ifdef WIN32\n return to_urbi(SYMBOL(WIN32));\n#else\n return to_urbi(SYMBOL(POSIX));\n#endif\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static rObject\n system_class_backtrace(runner::Runner& r, objects_type args)\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n check_arg_count(args.size() - 1, 0);\n runner::Runner::backtrace_type bt = r.backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n return void_class;\n }\n\n static rObject\n system_class_jobs(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n return new List(res);\n }\n\n static rObject\n system_class_aliveJobs(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(scheduler::Job::alive_jobs());\n }\n\n static rObject\n system_class_breakpoint(runner::Runner&, objects_type)\n {\n return void_class;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 0); \\\n ::urbiserver->Variable = Value;\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_SET_VAR(debugoff, debugOutput, false)\n SERVER_SET_VAR(debugon, debugOutput, true)\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject system_getenv(rObject, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : 0;\n }\n\n static rObject system_setenv(runner::Runner& r, rObject,\n const std::string& name, rObject value)\n {\n rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject system_unsetenv(rObject, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker<Lobby>::set_type system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n void\n system_class_initialize ()\n {\n#define DECLARE(Name) \\\n system_class->slot_set \\\n (SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(getenv);\n DECLARE(lobbies);\n DECLARE(setenv);\n DECLARE(unsetenv);\n\n#undef DECLARE\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(system, Name)\n\n DECLARE(aliveJobs);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(debugoff);\n DECLARE(debugon);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(shiftedTime);\n DECLARE(stats);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stopall);\n DECLARE(platform);\n DECLARE(time);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<commit_msg>Make \"loadFile\" and \"searchFile\" accept a \"Path\" object.<commit_after>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n\n#include <memory>\n#include <sstream>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/lobby.hh>\n#include <object\/list.hh>\n#include <object\/path.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/call.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n\n \/\/ Extract a filename from a String or a Path object\n static std::string\n filename_get(const rObject& o)\n {\n if (o.is_a<Path>())\n return o->as<Path>()->as_string();\n type_check(o, String::proto);\n return o->as<String>()->value_get();\n }\n\n rObject\n execute_parsed(runner::Runner& r,\n parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n runner::raise_primitive_error(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n scheduler::rJob job = sub;\n libport::Finally finally;\n r.register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const scheduler::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 0); \\\n ::urbiserver->Function();\t\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static rObject\n system_class_sleep (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n\n type_check(args[1], Float::proto);\n\n rFloat arg1 = args[1]->as<Float>();\n libport::utime_t deadline;\n if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n r.yield_until_terminated(r);\n else\n {\n deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000000.0);\n r.yield_until (deadline);\n }\n return void_class;\n }\n\n static rObject\n system_class_time(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(r.scheduler_get().get_time() \/ 1000000.0);\n }\n\n static rObject\n system_class_shiftedTime(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float((r.scheduler_get().get_time() -\n\t\t\t r.time_shift_get()) \/ 1000000.0);\n }\n\n static rObject\n system_class_assert_(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 2);\n type_check(args[2], String::proto);\n rString arg2 = args[2]->as<String>();\n if (!is_true(args[1]))\n runner::raise_primitive_error(\"assertion `\" + arg2->value_get() +\n\t\t\t\t \"' failed\");\n return void_class;\n }\n\n static rObject\n system_class_eval(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], String::proto);\n rString arg1 = args[1]->as<String>();\n return\n execute_parsed(r, parser::parse(arg1->value_get()),\n SYMBOL(eval),\n \"error executing command: \" + arg1->value_get());\n }\n\n static rObject\n system_class_registerAtJob (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 3);\n runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t args[1], args[2], args[3]);\n return object::void_class;\n }\n\n static rObject\n system_class_scopeTag(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n const scheduler::rTag& scope_tag =\n dynamic_cast<runner::Interpreter&>(r).scope_tag();\n return new Tag(scope_tag);\n }\n\n static rObject\n system_class_searchFile (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n const std::string filename = filename_get(args[1]);\n\n UServer& s = r.lobby_get()->value_get().connection.server_get();\n try\n {\n return new Path(s.find_file(filename));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static rObject\n system_class_loadFile(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n const std::string filename = filename_get(args[1]);\n\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(r, parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_class_currentRunner (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return r.as_task();\n }\n\n static rObject\n system_class_cycle (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(r.scheduler_get ().cycle_get ());\n }\n\n static rObject\n system_class_fresh (runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new String(libport::Symbol::fresh());\n }\n\n static rObject\n system_class_lobby (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return r.lobby_get();\n }\n\n static rObject\n system_class_nonInterruptible (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n r.non_interruptible_set (true);\n return void_class;\n }\n\n static rObject\n system_class_quit (runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n r.lobby_get()->value_get().connection.close();\n return void_class;\n }\n\n static rObject\n system_class_spawn(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n rObject arg1 = args[1]->as<Code>();\n assert(arg1);\n\n runner::Interpreter* new_runner =\n new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),\n\t\t\t rObject(arg1),\n\t\t\t libport::Symbol::fresh(r.name_get()));\n new_runner->copy_tags (r);\n new_runner->time_shift_set (r.time_shift_get ());\n\n new_runner->start_job ();\n\n return object::void_class;\n }\n\n static rObject\n system_class_stats(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n Dictionary::value_type res;\n const scheduler::scheduler_stats_type& stats =\n r.scheduler_get().stats_get();\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1000.0);\n ADDSTAT(Mean, mean, 1000.0);\n ADDSTAT(Min, min, 1000.0);\n ADDSTAT(StdDev, standard_deviation, 1000.0);\n ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static rObject\n system_class_platform(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n#ifdef WIN32\n return to_urbi(SYMBOL(WIN32));\n#else\n return to_urbi(SYMBOL(POSIX));\n#endif\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static rObject\n system_class_backtrace(runner::Runner& r, objects_type args)\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n check_arg_count(args.size() - 1, 0);\n runner::Runner::backtrace_type bt = r.backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n return void_class;\n }\n\n static rObject\n system_class_jobs(runner::Runner& r, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n return new List(res);\n }\n\n static rObject\n system_class_aliveJobs(runner::Runner&, objects_type args)\n {\n check_arg_count(args.size() - 1, 0);\n return new Float(scheduler::Job::alive_jobs());\n }\n\n static rObject\n system_class_breakpoint(runner::Runner&, objects_type)\n {\n return void_class;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 0); \\\n ::urbiserver->Variable = Value;\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_SET_VAR(debugoff, debugOutput, false)\n SERVER_SET_VAR(debugon, debugOutput, true)\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject system_getenv(rObject, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : 0;\n }\n\n static rObject system_setenv(runner::Runner& r, rObject,\n const std::string& name, rObject value)\n {\n rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject system_unsetenv(rObject, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker<Lobby>::set_type system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n void\n system_class_initialize ()\n {\n#define DECLARE(Name) \\\n system_class->slot_set \\\n (SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(getenv);\n DECLARE(lobbies);\n DECLARE(setenv);\n DECLARE(unsetenv);\n\n#undef DECLARE\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(system, Name)\n\n DECLARE(aliveJobs);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(debugoff);\n DECLARE(debugon);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(shiftedTime);\n DECLARE(stats);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stopall);\n DECLARE(platform);\n DECLARE(time);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/net\/gaia\/oauth_request_signer.h\"\n\n#include <cctype>\n#include <cstddef>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <map>\n#include <string>\n\n#include \"base\/base64.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/logging.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/time.h\"\n#include \"crypto\/hmac.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\nstatic const int kHexBase = 16;\nstatic char kHexDigits[] = \"0123456789ABCDEF\";\nstatic const size_t kHmacDigestLength = 20;\nstatic const int kMaxNonceLength = 30;\nstatic const int kMinNonceLength = 15;\n\nstatic const char kOAuthConsumerKeyLabel[] = \"oauth_consumer_key\";\nstatic const char kOAuthConsumerSecretLabel[] = \"oauth_consumer_secret\";\nstatic const char kOAuthNonceCharacters[] =\n \"abcdefghijklmnopqrstuvwyz\"\n \"ABCDEFGHIJKLMNOPQRSTUVWYZ\"\n \"0123456789_\";\nstatic const char kOAuthNonceLabel[] = \"oauth_nonce\";\nstatic const char kOAuthSignatureLabel[] = \"oauth_signature\";\nstatic const char kOAuthSignatureMethodLabel[] = \"oauth_signature_method\";\nstatic const char kOAuthTimestampLabel[] = \"oauth_timestamp\";\nstatic const char kOAuthTokenLabel[] = \"oauth_token\";\nstatic const char kOAuthTokenSecretLabel[] = \"oauth_token_secret\";\nstatic const char kOAuthVersion[] = \"1.0\";\nstatic const char kOAuthVersionLabel[] = \"oauth_version\";\n\nenum ParseQueryState {\n START_STATE,\n KEYWORD_STATE,\n VALUE_STATE,\n};\n\nconst std::string HttpMethodName(OAuthRequestSigner::HttpMethod method) {\n switch (method) {\n case OAuthRequestSigner::GET_METHOD:\n return \"GET\";\n case OAuthRequestSigner::POST_METHOD:\n return \"POST\";\n }\n NOTREACHED();\n return *(new std::string());\n}\n\nconst std::string SignatureMethodName(\n OAuthRequestSigner::SignatureMethod method) {\n switch (method) {\n case OAuthRequestSigner::HMAC_SHA1_SIGNATURE:\n return \"HMAC-SHA1\";\n case OAuthRequestSigner::RSA_SHA1_SIGNATURE:\n return \"RSA-SHA1\";\n case OAuthRequestSigner::PLAINTEXT_SIGNATURE:\n return \"PLAINTEXT\";\n }\n NOTREACHED();\n return *(new std::string());\n}\n\nstd::string BuildBaseString(const GURL& request_base_url,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string base_parameters) {\n return StringPrintf(\"%s&%s&%s\",\n HttpMethodName(http_method).c_str(),\n OAuthRequestSigner::Encode(\n request_base_url.spec()).c_str(),\n OAuthRequestSigner::Encode(\n base_parameters).c_str());\n}\n\nstd::string BuildBaseStringParameters(\n const OAuthRequestSigner::Parameters& parameters) {\n std::string result = \"\";\n OAuthRequestSigner::Parameters::const_iterator cursor;\n OAuthRequestSigner::Parameters::const_iterator limit;\n bool first = true;\n for (cursor = parameters.begin(), limit = parameters.end();\n cursor != limit;\n ++cursor) {\n if (first)\n first = false;\n else\n result += '&';\n result += OAuthRequestSigner::Encode(cursor->first);\n result += '=';\n result += OAuthRequestSigner::Encode(cursor->second);\n }\n return result;\n}\n\nstd::string GenerateNonce() {\n char result[kMaxNonceLength + 1];\n int length = base::RandUint64() % (kMaxNonceLength - kMinNonceLength + 1) +\n kMinNonceLength;\n result[length] = '\\0';\n for (int index = 0; index < length; ++index)\n result[index] = kOAuthNonceCharacters[\n base::RandUint64() % (sizeof(kOAuthNonceCharacters) - 1)];\n return result;\n}\n\nstd::string GenerateTimestamp() {\n return base::StringPrintf(\n \"%\" PRId64,\n (base::Time::NowFromSystemTime() - base::Time::UnixEpoch()).InSeconds());\n}\n\n\/\/ Creates a string-to-string, keyword-value map from a parameter\/query string\n\/\/ that uses ampersand (&) to seperate paris and equals (=) to seperate\n\/\/ keyword from value.\nbool ParseQuery(const std::string& query,\n OAuthRequestSigner::Parameters* parameters_result) {\n std::string::const_iterator cursor;\n std::string keyword;\n std::string::const_iterator limit;\n OAuthRequestSigner::Parameters parameters;\n ParseQueryState state;\n std::string value;\n\n state = START_STATE;\n for (cursor = query.begin(), limit = query.end();\n cursor != limit;\n ++cursor) {\n char character = *cursor;\n switch (state) {\n case KEYWORD_STATE:\n switch (character) {\n case '&':\n parameters[keyword] = value;\n keyword = \"\";\n value = \"\";\n state = START_STATE;\n break;\n case '=':\n state = VALUE_STATE;\n break;\n default:\n keyword += character;\n }\n break;\n case START_STATE:\n switch (character) {\n case '&': \/\/ Intentionally falling through\n case '=':\n return false;\n default:\n keyword += character;\n state = KEYWORD_STATE;\n }\n break;\n case VALUE_STATE:\n switch (character) {\n case '=':\n return false;\n case '&':\n parameters[keyword] = value;\n keyword = \"\";\n value = \"\";\n state = START_STATE;\n break;\n default:\n value += character;\n }\n break;\n }\n }\n switch (state) {\n case START_STATE:\n break;\n case KEYWORD_STATE: \/\/ Intentionally falling through\n case VALUE_STATE:\n parameters[keyword] = value;\n break;\n default:\n NOTREACHED();\n }\n *parameters_result = parameters;\n return true;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is HMAC-SHA1.\nbool SignHmacSha1(const std::string& text,\n const std::string& key,\n std::string* signature_return) {\n crypto::HMAC hmac(crypto::HMAC::SHA1);\n DCHECK(hmac.DigestLength() == kHmacDigestLength);\n unsigned char digest[kHmacDigestLength];\n bool result = hmac.Init(key) &&\n hmac.Sign(text, digest, kHmacDigestLength) &&\n base::Base64Encode(std::string(reinterpret_cast<const char*>(digest),\n kHmacDigestLength),\n signature_return);\n return result;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is PLAINTEXT.\n\/\/\n\/\/ Not yet implemented, and might never be.\nbool SignPlaintext(const std::string& text,\n const std::string& key,\n std::string* result) {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is RSA-SHA1.\n\/\/\n\/\/ Not yet implemented, and might never be.\nbool SignRsaSha1(const std::string& text,\n const std::string& key,\n std::string* result) {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ Adds parameters that are required by OAuth added as needed to |parameters|.\nvoid PrepareParameters(OAuthRequestSigner::Parameters* parameters,\n OAuthRequestSigner::SignatureMethod signature_method,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& token_key) {\n if (parameters->find(kOAuthNonceLabel) == parameters->end())\n (*parameters)[kOAuthNonceLabel] = GenerateNonce();\n\n if (parameters->find(kOAuthTimestampLabel) == parameters->end())\n (*parameters)[kOAuthTimestampLabel] = GenerateTimestamp();\n\n (*parameters)[kOAuthConsumerKeyLabel] = consumer_key;\n (*parameters)[kOAuthSignatureMethodLabel] =\n SignatureMethodName(signature_method);\n (*parameters)[kOAuthTokenLabel] = token_key;\n (*parameters)[kOAuthVersionLabel] = kOAuthVersion;\n}\n\n\/\/ Implements shared signing logic, generating the signature and storing it in\n\/\/ |parameters|. Returns true if the signature has been generated succesfully.\nbool SignParameters(const GURL& request_base_url,\n OAuthRequestSigner::SignatureMethod signature_method,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n OAuthRequestSigner::Parameters* parameters) {\n DCHECK(request_base_url.is_valid());\n PrepareParameters(parameters, signature_method, http_method,\n consumer_key, token_key);\n std::string base_parameters = BuildBaseStringParameters(*parameters);\n std::string base = BuildBaseString(request_base_url, http_method,\n base_parameters);\n std::string key = consumer_secret + '&' + token_secret;\n bool is_signed = false;\n std::string signature;\n switch (signature_method) {\n case OAuthRequestSigner::HMAC_SHA1_SIGNATURE:\n is_signed = SignHmacSha1(base, key, &signature);\n break;\n case OAuthRequestSigner::RSA_SHA1_SIGNATURE:\n is_signed = SignRsaSha1(base, key, &signature);\n break;\n case OAuthRequestSigner::PLAINTEXT_SIGNATURE:\n is_signed = SignPlaintext(base, key, &signature);\n break;\n default:\n NOTREACHED();\n }\n if (is_signed)\n (*parameters)[kOAuthSignatureLabel] = signature;\n return is_signed;\n}\n\n\n} \/\/ namespace\n\n\/\/ static\nbool OAuthRequestSigner::Decode(const std::string& text,\n std::string* decoded_text) {\n std::string accumulator = \"\";\n std::string::const_iterator cursor;\n std::string::const_iterator limit;\n for (limit = text.end(), cursor = text.begin(); cursor != limit; ++cursor) {\n char character = *cursor;\n if (character == '%') {\n ++cursor;\n if (cursor == limit)\n return false;\n char* first = strchr(kHexDigits, *cursor);\n if (!first)\n return false;\n int high = first - kHexDigits;\n DCHECK(high >= 0 && high < kHexBase);\n\n ++cursor;\n if (cursor == limit)\n return false;\n char* second = strchr(kHexDigits, *cursor);\n if (!second)\n return false;\n int low = second - kHexDigits;\n DCHECK(low >= 0 || low < kHexBase);\n\n char decoded = static_cast<char>(high * kHexBase + low);\n DCHECK(!(IsAsciiAlpha(decoded) || IsAsciiDigit(decoded)));\n DCHECK(!(decoded && strchr(\"-._~\", decoded)));\n accumulator += decoded;\n } else {\n accumulator += character;\n }\n }\n *decoded_text = accumulator;\n return true;\n}\n\n\/\/ static\nstd::string OAuthRequestSigner::Encode(const std::string& text) {\n std::string result = \"\";\n std::string::const_iterator cursor;\n std::string::const_iterator limit;\n for (limit = text.end(), cursor = text.begin(); cursor != limit; ++cursor) {\n char character = *cursor;\n if (IsAsciiAlpha(character) || IsAsciiDigit(character)) {\n result += character;\n } else {\n switch (character) {\n case '-':\n case '.':\n case '_':\n case '~':\n result += character;\n break;\n default:\n unsigned char byte = static_cast<unsigned char>(character);\n result = result + '%' + kHexDigits[byte \/ kHexBase] +\n kHexDigits[byte % kHexBase];\n }\n }\n }\n return result;\n}\n\n\/\/ static\nbool OAuthRequestSigner::ParseAndSign(const GURL& request_url_with_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* result) {\n DCHECK(request_url_with_parameters.is_valid());\n Parameters parameters;\n if (request_url_with_parameters.has_query()) {\n const std::string& query = request_url_with_parameters.query();\n if (!query.empty()) {\n if (!ParseQuery(query, ¶meters))\n return false;\n }\n }\n std::string spec = request_url_with_parameters.spec();\n std::string url_without_parameters = spec;\n std::string::size_type question = spec.find(\"?\");\n if (question != std::string::npos)\n url_without_parameters = spec.substr(0,question);\n return SignURL(GURL(url_without_parameters), parameters, signature_method,\n http_method, consumer_key, consumer_secret, token_key,\n token_secret, result);\n}\n\n\/\/ static\nbool OAuthRequestSigner::SignURL(\n const GURL& request_base_url,\n const Parameters& request_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* signed_text_return) {\n DCHECK(request_base_url.is_valid());\n Parameters parameters(request_parameters);\n bool is_signed = SignParameters(request_base_url, signature_method,\n http_method, consumer_key, consumer_secret,\n token_key, token_secret, ¶meters);\n if (is_signed) {\n std::string signed_text;\n switch (http_method) {\n case GET_METHOD:\n signed_text = request_base_url.spec() + '?';\n \/\/ Intentionally falling through\n case POST_METHOD:\n signed_text += BuildBaseStringParameters(parameters);\n break;\n default:\n NOTREACHED();\n }\n *signed_text_return = signed_text;\n }\n return is_signed;\n}\n\n\/\/ static\nbool OAuthRequestSigner::SignAuthHeader(\n const GURL& request_base_url,\n const Parameters& request_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* signed_text_return) {\n DCHECK(request_base_url.is_valid());\n Parameters parameters(request_parameters);\n bool is_signed = SignParameters(request_base_url, signature_method,\n http_method, consumer_key, consumer_secret,\n token_key, token_secret, ¶meters);\n if (is_signed) {\n std::string signed_text = \"OAuth \";\n bool first = true;\n for (Parameters::const_iterator param = parameters.begin();\n param != parameters.end();\n ++param) {\n if (first)\n first = false;\n else\n signed_text += \", \";\n signed_text +=\n StringPrintf(\"%s=\\\"%s\\\"\",\n OAuthRequestSigner::Encode(param->first).c_str(),\n OAuthRequestSigner::Encode(param->second).c_str());\n }\n *signed_text_return = signed_text;\n }\n return is_signed;\n}\n<commit_msg>[Coverity] Fix pass-by-val to pass-by-ref<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/net\/gaia\/oauth_request_signer.h\"\n\n#include <cctype>\n#include <cstddef>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <map>\n#include <string>\n\n#include \"base\/base64.h\"\n#include \"base\/format_macros.h\"\n#include \"base\/logging.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/time.h\"\n#include \"crypto\/hmac.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nnamespace {\n\nstatic const int kHexBase = 16;\nstatic char kHexDigits[] = \"0123456789ABCDEF\";\nstatic const size_t kHmacDigestLength = 20;\nstatic const int kMaxNonceLength = 30;\nstatic const int kMinNonceLength = 15;\n\nstatic const char kOAuthConsumerKeyLabel[] = \"oauth_consumer_key\";\nstatic const char kOAuthConsumerSecretLabel[] = \"oauth_consumer_secret\";\nstatic const char kOAuthNonceCharacters[] =\n \"abcdefghijklmnopqrstuvwyz\"\n \"ABCDEFGHIJKLMNOPQRSTUVWYZ\"\n \"0123456789_\";\nstatic const char kOAuthNonceLabel[] = \"oauth_nonce\";\nstatic const char kOAuthSignatureLabel[] = \"oauth_signature\";\nstatic const char kOAuthSignatureMethodLabel[] = \"oauth_signature_method\";\nstatic const char kOAuthTimestampLabel[] = \"oauth_timestamp\";\nstatic const char kOAuthTokenLabel[] = \"oauth_token\";\nstatic const char kOAuthTokenSecretLabel[] = \"oauth_token_secret\";\nstatic const char kOAuthVersion[] = \"1.0\";\nstatic const char kOAuthVersionLabel[] = \"oauth_version\";\n\nenum ParseQueryState {\n START_STATE,\n KEYWORD_STATE,\n VALUE_STATE,\n};\n\nconst std::string HttpMethodName(OAuthRequestSigner::HttpMethod method) {\n switch (method) {\n case OAuthRequestSigner::GET_METHOD:\n return \"GET\";\n case OAuthRequestSigner::POST_METHOD:\n return \"POST\";\n }\n NOTREACHED();\n return *(new std::string());\n}\n\nconst std::string SignatureMethodName(\n OAuthRequestSigner::SignatureMethod method) {\n switch (method) {\n case OAuthRequestSigner::HMAC_SHA1_SIGNATURE:\n return \"HMAC-SHA1\";\n case OAuthRequestSigner::RSA_SHA1_SIGNATURE:\n return \"RSA-SHA1\";\n case OAuthRequestSigner::PLAINTEXT_SIGNATURE:\n return \"PLAINTEXT\";\n }\n NOTREACHED();\n return *(new std::string());\n}\n\nstd::string BuildBaseString(const GURL& request_base_url,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string& base_parameters) {\n return StringPrintf(\"%s&%s&%s\",\n HttpMethodName(http_method).c_str(),\n OAuthRequestSigner::Encode(\n request_base_url.spec()).c_str(),\n OAuthRequestSigner::Encode(\n base_parameters).c_str());\n}\n\nstd::string BuildBaseStringParameters(\n const OAuthRequestSigner::Parameters& parameters) {\n std::string result = \"\";\n OAuthRequestSigner::Parameters::const_iterator cursor;\n OAuthRequestSigner::Parameters::const_iterator limit;\n bool first = true;\n for (cursor = parameters.begin(), limit = parameters.end();\n cursor != limit;\n ++cursor) {\n if (first)\n first = false;\n else\n result += '&';\n result += OAuthRequestSigner::Encode(cursor->first);\n result += '=';\n result += OAuthRequestSigner::Encode(cursor->second);\n }\n return result;\n}\n\nstd::string GenerateNonce() {\n char result[kMaxNonceLength + 1];\n int length = base::RandUint64() % (kMaxNonceLength - kMinNonceLength + 1) +\n kMinNonceLength;\n result[length] = '\\0';\n for (int index = 0; index < length; ++index)\n result[index] = kOAuthNonceCharacters[\n base::RandUint64() % (sizeof(kOAuthNonceCharacters) - 1)];\n return result;\n}\n\nstd::string GenerateTimestamp() {\n return base::StringPrintf(\n \"%\" PRId64,\n (base::Time::NowFromSystemTime() - base::Time::UnixEpoch()).InSeconds());\n}\n\n\/\/ Creates a string-to-string, keyword-value map from a parameter\/query string\n\/\/ that uses ampersand (&) to seperate paris and equals (=) to seperate\n\/\/ keyword from value.\nbool ParseQuery(const std::string& query,\n OAuthRequestSigner::Parameters* parameters_result) {\n std::string::const_iterator cursor;\n std::string keyword;\n std::string::const_iterator limit;\n OAuthRequestSigner::Parameters parameters;\n ParseQueryState state;\n std::string value;\n\n state = START_STATE;\n for (cursor = query.begin(), limit = query.end();\n cursor != limit;\n ++cursor) {\n char character = *cursor;\n switch (state) {\n case KEYWORD_STATE:\n switch (character) {\n case '&':\n parameters[keyword] = value;\n keyword = \"\";\n value = \"\";\n state = START_STATE;\n break;\n case '=':\n state = VALUE_STATE;\n break;\n default:\n keyword += character;\n }\n break;\n case START_STATE:\n switch (character) {\n case '&': \/\/ Intentionally falling through\n case '=':\n return false;\n default:\n keyword += character;\n state = KEYWORD_STATE;\n }\n break;\n case VALUE_STATE:\n switch (character) {\n case '=':\n return false;\n case '&':\n parameters[keyword] = value;\n keyword = \"\";\n value = \"\";\n state = START_STATE;\n break;\n default:\n value += character;\n }\n break;\n }\n }\n switch (state) {\n case START_STATE:\n break;\n case KEYWORD_STATE: \/\/ Intentionally falling through\n case VALUE_STATE:\n parameters[keyword] = value;\n break;\n default:\n NOTREACHED();\n }\n *parameters_result = parameters;\n return true;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is HMAC-SHA1.\nbool SignHmacSha1(const std::string& text,\n const std::string& key,\n std::string* signature_return) {\n crypto::HMAC hmac(crypto::HMAC::SHA1);\n DCHECK(hmac.DigestLength() == kHmacDigestLength);\n unsigned char digest[kHmacDigestLength];\n bool result = hmac.Init(key) &&\n hmac.Sign(text, digest, kHmacDigestLength) &&\n base::Base64Encode(std::string(reinterpret_cast<const char*>(digest),\n kHmacDigestLength),\n signature_return);\n return result;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is PLAINTEXT.\n\/\/\n\/\/ Not yet implemented, and might never be.\nbool SignPlaintext(const std::string& text,\n const std::string& key,\n std::string* result) {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ Creates the value for the oauth_signature parameter when the\n\/\/ oauth_signature_method is RSA-SHA1.\n\/\/\n\/\/ Not yet implemented, and might never be.\nbool SignRsaSha1(const std::string& text,\n const std::string& key,\n std::string* result) {\n NOTIMPLEMENTED();\n return false;\n}\n\n\/\/ Adds parameters that are required by OAuth added as needed to |parameters|.\nvoid PrepareParameters(OAuthRequestSigner::Parameters* parameters,\n OAuthRequestSigner::SignatureMethod signature_method,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& token_key) {\n if (parameters->find(kOAuthNonceLabel) == parameters->end())\n (*parameters)[kOAuthNonceLabel] = GenerateNonce();\n\n if (parameters->find(kOAuthTimestampLabel) == parameters->end())\n (*parameters)[kOAuthTimestampLabel] = GenerateTimestamp();\n\n (*parameters)[kOAuthConsumerKeyLabel] = consumer_key;\n (*parameters)[kOAuthSignatureMethodLabel] =\n SignatureMethodName(signature_method);\n (*parameters)[kOAuthTokenLabel] = token_key;\n (*parameters)[kOAuthVersionLabel] = kOAuthVersion;\n}\n\n\/\/ Implements shared signing logic, generating the signature and storing it in\n\/\/ |parameters|. Returns true if the signature has been generated succesfully.\nbool SignParameters(const GURL& request_base_url,\n OAuthRequestSigner::SignatureMethod signature_method,\n OAuthRequestSigner::HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n OAuthRequestSigner::Parameters* parameters) {\n DCHECK(request_base_url.is_valid());\n PrepareParameters(parameters, signature_method, http_method,\n consumer_key, token_key);\n std::string base_parameters = BuildBaseStringParameters(*parameters);\n std::string base = BuildBaseString(request_base_url, http_method,\n base_parameters);\n std::string key = consumer_secret + '&' + token_secret;\n bool is_signed = false;\n std::string signature;\n switch (signature_method) {\n case OAuthRequestSigner::HMAC_SHA1_SIGNATURE:\n is_signed = SignHmacSha1(base, key, &signature);\n break;\n case OAuthRequestSigner::RSA_SHA1_SIGNATURE:\n is_signed = SignRsaSha1(base, key, &signature);\n break;\n case OAuthRequestSigner::PLAINTEXT_SIGNATURE:\n is_signed = SignPlaintext(base, key, &signature);\n break;\n default:\n NOTREACHED();\n }\n if (is_signed)\n (*parameters)[kOAuthSignatureLabel] = signature;\n return is_signed;\n}\n\n\n} \/\/ namespace\n\n\/\/ static\nbool OAuthRequestSigner::Decode(const std::string& text,\n std::string* decoded_text) {\n std::string accumulator = \"\";\n std::string::const_iterator cursor;\n std::string::const_iterator limit;\n for (limit = text.end(), cursor = text.begin(); cursor != limit; ++cursor) {\n char character = *cursor;\n if (character == '%') {\n ++cursor;\n if (cursor == limit)\n return false;\n char* first = strchr(kHexDigits, *cursor);\n if (!first)\n return false;\n int high = first - kHexDigits;\n DCHECK(high >= 0 && high < kHexBase);\n\n ++cursor;\n if (cursor == limit)\n return false;\n char* second = strchr(kHexDigits, *cursor);\n if (!second)\n return false;\n int low = second - kHexDigits;\n DCHECK(low >= 0 || low < kHexBase);\n\n char decoded = static_cast<char>(high * kHexBase + low);\n DCHECK(!(IsAsciiAlpha(decoded) || IsAsciiDigit(decoded)));\n DCHECK(!(decoded && strchr(\"-._~\", decoded)));\n accumulator += decoded;\n } else {\n accumulator += character;\n }\n }\n *decoded_text = accumulator;\n return true;\n}\n\n\/\/ static\nstd::string OAuthRequestSigner::Encode(const std::string& text) {\n std::string result = \"\";\n std::string::const_iterator cursor;\n std::string::const_iterator limit;\n for (limit = text.end(), cursor = text.begin(); cursor != limit; ++cursor) {\n char character = *cursor;\n if (IsAsciiAlpha(character) || IsAsciiDigit(character)) {\n result += character;\n } else {\n switch (character) {\n case '-':\n case '.':\n case '_':\n case '~':\n result += character;\n break;\n default:\n unsigned char byte = static_cast<unsigned char>(character);\n result = result + '%' + kHexDigits[byte \/ kHexBase] +\n kHexDigits[byte % kHexBase];\n }\n }\n }\n return result;\n}\n\n\/\/ static\nbool OAuthRequestSigner::ParseAndSign(const GURL& request_url_with_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* result) {\n DCHECK(request_url_with_parameters.is_valid());\n Parameters parameters;\n if (request_url_with_parameters.has_query()) {\n const std::string& query = request_url_with_parameters.query();\n if (!query.empty()) {\n if (!ParseQuery(query, ¶meters))\n return false;\n }\n }\n std::string spec = request_url_with_parameters.spec();\n std::string url_without_parameters = spec;\n std::string::size_type question = spec.find(\"?\");\n if (question != std::string::npos)\n url_without_parameters = spec.substr(0,question);\n return SignURL(GURL(url_without_parameters), parameters, signature_method,\n http_method, consumer_key, consumer_secret, token_key,\n token_secret, result);\n}\n\n\/\/ static\nbool OAuthRequestSigner::SignURL(\n const GURL& request_base_url,\n const Parameters& request_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* signed_text_return) {\n DCHECK(request_base_url.is_valid());\n Parameters parameters(request_parameters);\n bool is_signed = SignParameters(request_base_url, signature_method,\n http_method, consumer_key, consumer_secret,\n token_key, token_secret, ¶meters);\n if (is_signed) {\n std::string signed_text;\n switch (http_method) {\n case GET_METHOD:\n signed_text = request_base_url.spec() + '?';\n \/\/ Intentionally falling through\n case POST_METHOD:\n signed_text += BuildBaseStringParameters(parameters);\n break;\n default:\n NOTREACHED();\n }\n *signed_text_return = signed_text;\n }\n return is_signed;\n}\n\n\/\/ static\nbool OAuthRequestSigner::SignAuthHeader(\n const GURL& request_base_url,\n const Parameters& request_parameters,\n SignatureMethod signature_method,\n HttpMethod http_method,\n const std::string& consumer_key,\n const std::string& consumer_secret,\n const std::string& token_key,\n const std::string& token_secret,\n std::string* signed_text_return) {\n DCHECK(request_base_url.is_valid());\n Parameters parameters(request_parameters);\n bool is_signed = SignParameters(request_base_url, signature_method,\n http_method, consumer_key, consumer_secret,\n token_key, token_secret, ¶meters);\n if (is_signed) {\n std::string signed_text = \"OAuth \";\n bool first = true;\n for (Parameters::const_iterator param = parameters.begin();\n param != parameters.end();\n ++param) {\n if (first)\n first = false;\n else\n signed_text += \", \";\n signed_text +=\n StringPrintf(\"%s=\\\"%s\\\"\",\n OAuthRequestSigner::Encode(param->first).c_str(),\n OAuthRequestSigner::Encode(param->second).c_str());\n }\n *signed_text_return = signed_text;\n }\n return is_signed;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#ifndef _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_\n#define _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ 1\n\n#include \"..\/..\/..\/Debug\/Trace.h\"\n\nnamespace Stroika::Foundation::Database::SQL::ORM {\n\n \/*\n ********************************************************************************\n ******************************** TableConnection *******************************\n ********************************************************************************\n *\/\n template <typename T, typename TRAITS>\n TableConnection<T, TRAITS>::TableConnection (const Connection::Ptr& conn, const Schema::Table& tableSchema, const ObjectVariantMapper& objectVariantMapper)\n : fConnection_{conn}\n , fTableSchema_{tableSchema}\n , fObjectVariantMapper_{objectVariantMapper}\n , fGetByID_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetByID ())}\n , fGetAll_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetAllElements ())}\n , fAddNew_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.Insert ())}\n , fUpdate_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.UpdateByID ())}\n {\n Require (conn != nullptr); \/\/ too late, but good docs\n }\n template <typename T, typename TRAITS>\n optional<T> TableConnection<T, TRAITS>::GetByID (const typename TRAITS::IDType& id)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fGetByID_Statement_.Reset ();\n fGetByID_Statement_.Bind (initializer_list<KeyValuePair<String, VariantValue>>{{fTableSchema_.GetIDField ()->fName, VariantValue{static_cast<Memory::BLOB> (id)}}});\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (\"SQL: %s\", fGetByID_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n auto rows = fGetByID_Statement_.GetAllRows ()\n .Select<T> ([this] (const Statement::Row& r) {\n return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)});\n });\n if (rows.empty ()) {\n return nullopt;\n }\n Ensure (rows.size () == 1); \/\/ cuz arg sb a key\n return *rows.First ();\n }\n template <typename T, typename TRAITS>\n Sequence<T> TableConnection<T, TRAITS>::GetAll ()\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (\"SQL: %s\", fGetAll_Statement_.GetSQL ().c_str ());\n }\n auto rows = fGetAll_Statement_.GetAllRows ()\n .Select<T> ([this] (const Statement::Row& r) {\n return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)});\n });\n return rows;\n }\n template <typename T, typename TRAITS>\n void TableConnection<T, TRAITS>::AddNew (const T& v)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fAddNew_Statement_.Reset ();\n fAddNew_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).As<Mapping<String, VariantValue>> ()));\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (\"SQL: %s\", fAddNew_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n fAddNew_Statement_.Execute ();\n }\n template <typename T, typename TRAITS>\n void TableConnection<T, TRAITS>::Update (const T& v)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fUpdate_Statement_.Reset ();\n fUpdate_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).As<Mapping<String, VariantValue>> ()));\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (\"SQL: %s\", fUpdate_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n fUpdate_Statement_.Execute ();\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_*\/\n<commit_msg>small fixes to new ORM code (stricly c++ gcc and other bugfixes)<commit_after>\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#ifndef _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_\n#define _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ 1\n\n#include \"..\/..\/..\/Debug\/Trace.h\"\n\nnamespace Stroika::Foundation::Database::SQL::ORM {\n\n \/*\n ********************************************************************************\n ******************************** TableConnection *******************************\n ********************************************************************************\n *\/\n template <typename T, typename TRAITS>\n TableConnection<T, TRAITS>::TableConnection (const Connection::Ptr& conn, const Schema::Table& tableSchema, const ObjectVariantMapper& objectVariantMapper)\n : fConnection_{conn}\n , fTableSchema_{tableSchema}\n , fObjectVariantMapper_{objectVariantMapper}\n , fGetByID_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetByID ())}\n , fGetAll_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetAllElements ())}\n , fAddNew_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.Insert ())}\n , fUpdate_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.UpdateByID ())}\n {\n Require (conn != nullptr); \/\/ too late, but good docs\n }\n template <typename T, typename TRAITS>\n optional<T> TableConnection<T, TRAITS>::GetByID (const typename TRAITS::IDType& id)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fGetByID_Statement_.Reset ();\n fGetByID_Statement_.Bind (initializer_list<KeyValuePair<String, VariantValue>>{{fTableSchema_.GetIDField ()->fName, VariantValue{static_cast<Memory::BLOB> (id)}}});\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (L\"SQL: %s\", fGetByID_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n auto rows = fGetByID_Statement_.GetAllRows ()\n .Select<T> ([this] (const Statement::Row& r) {\n return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)});\n });\n if (rows.empty ()) {\n return nullopt;\n }\n Ensure (rows.size () == 1); \/\/ cuz arg sb a key\n return *rows.First ();\n }\n template <typename T, typename TRAITS>\n Sequence<T> TableConnection<T, TRAITS>::GetAll ()\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (L\"SQL: %s\", fGetAll_Statement_.GetSQL ().c_str ());\n }\n auto rows = fGetAll_Statement_.GetAllRows ()\n .Select<T> ([this] (const Statement::Row& r) {\n return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)});\n });\n return rows;\n }\n template <typename T, typename TRAITS>\n void TableConnection<T, TRAITS>::AddNew (const T& v)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fAddNew_Statement_.Reset ();\n fAddNew_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ()));\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (L\"SQL: %s\", fAddNew_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n fAddNew_Statement_.Execute ();\n }\n template <typename T, typename TRAITS>\n void TableConnection<T, TRAITS>::Update (const T& v)\n {\n lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n using DataExchange::VariantValue;\n using Stroika::Foundation::Common::KeyValuePair;\n fUpdate_Statement_.Reset ();\n fUpdate_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ()));\n if constexpr (TRAITS::kTraceLogEachRequest) {\n DbgTrace (L\"SQL: %s\", fUpdate_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ());\n }\n fUpdate_Statement_.Execute ();\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperCompositeApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbOGRDataToSamplePositionFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TrainRegressionFileHandler\n{\npublic:\n void AddFileNameList(const std::string& key, const std::vector<std::string> & fileNameList)\n {\n fileNameMap[key] = fileNameList;\n }\n \n std::vector<std::string> GetFileNameList(const std::string& key)\n {\n return fileNameMap[key];\n }\n \n bool Clear()\n {\n bool res = true;\n for (const auto & fileNameList : fileNameMap)\n for (const auto & fileName : fileNameList.second)\n res = res && RemoveFile(fileName);\n \n fileNameMap.clear();\n return res;\n }\n \n\nprivate:\n std::map< std::string, std::vector<std::string>> fileNameMap;\n\n bool RemoveFile(const std::string & filename)\n {\n bool res = true;\n if( itksys::SystemTools::FileExists( filename ) )\n {\n size_t posExt = filename.rfind( '.' );\n if( posExt != std::string::npos && filename.compare( posExt, std::string::npos, \".shp\" ) == 0 )\n {\n std::string shxPath = filename.substr( 0, posExt ) + std::string( \".shx\" );\n std::string dbfPath = filename.substr( 0, posExt ) + std::string( \".dbf\" );\n std::string prjPath = filename.substr( 0, posExt ) + std::string( \".prj\" );\n RemoveFile( shxPath );\n RemoveFile( dbfPath );\n RemoveFile( prjPath );\n }\n res = itksys::SystemTools::RemoveFile( filename );\n }\n return res;\n }\n};\n\n\nclass TrainImagesRegression : public CompositeApplication\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TrainImagesRegression Self;\n typedef CompositeApplication Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n \/** Standard macro *\/\n itkTypeMacro( TrainImagesRegression, Superclass );\n \nprotected:\n\n void AddRegressionField(const std::string &inVectorFileName,\n const std::string &outVectorFileName,\n const std::string &fieldName)\n {\n auto setFieldAppli = GetInternalApplication(\"setfield\");\n \n setFieldAppli->SetParameterString(\"in\", inVectorFileName);\n setFieldAppli->SetParameterString(\"out\", outVectorFileName);\n setFieldAppli->SetParameterString(\"fn\", fieldName);\n setFieldAppli->SetParameterString(\"fv\", \"0\");\n \n ExecuteInternal(\"setfield\");\n }\n\n void ComputePolygonStatistics(const std::string &inVectorFileName,\n FloatVectorImageType * inputImage,\n const std::string &statisticFileName,\n const std::string &fieldName)\n {\n auto polygonClassAppli = GetInternalApplication(\"polystat\");\n \n polygonClassAppli->SetParameterInputImage( \"in\", inputImage );\n polygonClassAppli->SetParameterString( \"vec\", inVectorFileName);\n polygonClassAppli->SetParameterString( \"out\", statisticFileName);\n \n polygonClassAppli->UpdateParameters();\n polygonClassAppli->SetParameterString( \"field\", fieldName);\n \n ExecuteInternal( \"polystat\" );\n }\n\n void ComputeSamplingRate(const std::vector<std::string> & statisticsFileNames, \n const std::string & outputFileName,\n int numberOfSample = 0)\n {\n auto samplingRateAppli = GetInternalApplication(\"rates\");\n \n samplingRateAppli->SetParameterStringList( \"il\", statisticsFileNames);\n samplingRateAppli->SetParameterString(\"out\", outputFileName);\n \n if (numberOfSample)\n {\n samplingRateAppli->SetParameterString(\"strategy\", \"constant\");\n \n \/\/ TODO why nb is a string in MultiImageSamplingRate + MultiImageSamplingRate seems to return nb-1 samples ...\n samplingRateAppli->SetParameterString(\"strategy.constant.nb\", std::to_string(numberOfSample));\n }\n else\n {\n samplingRateAppli->SetParameterString(\"strategy\", \"all\");\n }\n \n ExecuteInternal( \"rates\");\n }\n\n void PerformSampleSelection()\n {\n \n }\n \n void PerformSampleExtraction()\n {\n \n }\n\n void InitIO()\n {\n AddParameter( ParameterType_Group, \"io\", \"Input and output data\" );\n SetParameterDescription( \"io\", \"This group of parameters allows setting input and output data.\" );\n\n AddParameter( ParameterType_InputImageList, \"io.il\", \"Input Image List\" );\n SetParameterDescription( \"io.il\", \"A list of input images.\" );\n MandatoryOn( \"io.il\" );\n \n AddParameter( ParameterType_InputVectorDataList, \"io.vd\", \"Input Vector Data List\" );\n SetParameterDescription( \"io.vd\", \"A list of vector data to select the training samples.\" );\n MandatoryOn( \"io.vd\" );\n }\n \n void InitSampling()\n { \n AddApplication( \"VectorDataSetField\", \"setfield\", \"Set additional vector field\");\n AddApplication( \"PolygonClassStatistics\", \"polystat\", \"Polygon analysis\" );\n AddApplication( \"MultiImageSamplingRate\", \"rates\", \"Sampling rates\" );\n \n AddParameter( ParameterType_Group, \"sample\", \"Sampling parameters\" );\n SetParameterDescription( \"sample\", \"This group of parameters allows setting sampling parameters\" );\n\n AddParameter( ParameterType_Int, \"sample.nt\", \"Number of training samples\" );\n SetParameterDescription( \"sample.nt\", \"Number of training samples.\" );\n MandatoryOff( \"sample.nt\" );\n \n AddApplication( \"SampleSelection\", \"select\", \"Sample selection\" );\n \/\/AddApplication( \"SampleExtraction\", \"extraction\", \"Sample extraction\" );\n \n }\n \n void InitLearning()\n {\n }\n\nprivate:\n\n void DoInit() override\n {\n SetName(\"TrainImagesRegression\");\n SetDescription(\" \");\n\n SetDocLongDescription(\" \");\n SetDocLimitations(\" \");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n \n AddDocTag(Tags::Learning);\n \n SetOfficialDocLink();\n \n ClearApplications();\n \n InitIO();\n InitSampling();\n InitLearning();\n }\n \n void DoUpdateParameters() override\n {\n }\n\n void DoExecute() override\n {\n std::string predictorFieldName = \"regclass\";\n \n auto vectorFileNames = GetParameterStringList( \"io.vd\" );\n FloatVectorImageListType* inputImageList = GetParameterImageList( \"io.il\" );\n \n std::vector<std::string> statisticsFileNames;\n \n for (unsigned int i =0; i < vectorFileNames.size(); i++)\n {\n std::string outfile = \"setfield\"+ std::to_string(i) +\".shp\";\/\/ TODO io file handler\n AddRegressionField(vectorFileNames[i], outfile, predictorFieldName);\n \n std::cout << \"Regression field added\" << std::endl;\n \n statisticsFileNames.push_back(\"polygonstat\"+ std::to_string(i) +\".xml\");\n \n ComputePolygonStatistics(outfile, inputImageList->GetNthElement(i), statisticsFileNames[i], predictorFieldName);\n \n std::cout << \"Polygon class statistic done\" << std::endl;\n }\n \n \/\/TODO validation set ??\n \n std::string samplingRateFileName = \"rates.xml\";\n \n if (HasValue(\"sample.nt\"))\n ComputeSamplingRate(statisticsFileNames, samplingRateFileName, GetParameterInt(\"sample.nt\"));\n else\n ComputeSamplingRate(statisticsFileNames, samplingRateFileName);\n \n std::cout << \"Sampling rate computation done\" << std::endl;\n \n for (unsigned int i =0; i < vectorFileNames.size(); i++)\n {\n PerformSampleSelection();\n PerformSampleExtraction();\n }\n \n }\n};\n\n} \/\/end namespace Wrapper\n} \/\/end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::TrainImagesRegression)\n<commit_msg>ENH: refactor the file handler<commit_after>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperCompositeApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbOGRDataToSamplePositionFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TrainImagesRegression : public CompositeApplication\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TrainImagesRegression Self;\n typedef CompositeApplication Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n \/** Standard macro *\/\n itkTypeMacro( TrainImagesRegression, Superclass );\n \nprotected:\n\n void AddRegressionField()\n {\n auto setFieldAppli = GetInternalApplication(\"setfield\");\n auto inputFileNames = GetParameterStringList( \"io.vd\" );\n auto& outputFileNames = m_FileHandler[ \"inputWithClassField\" ]; \n \n setFieldAppli->SetParameterString(\"fn\", m_PredictorFieldName);\n setFieldAppli->SetParameterString(\"fv\", \"0\");\n \n for (unsigned int i =0; i < inputFileNames.size(); i++)\n {\n outputFileNames.push_back(\"setfield\"+ std::to_string(i) +\".shp\");\/\/ TODO io file handler\n setFieldAppli->SetParameterString(\"in\", inputFileNames[i]);\n setFieldAppli->SetParameterString(\"out\", outputFileNames[i]);\n \n \/\/ Call ExecuteAndWriteOutput because VectorDataSetField's ExecuteInternal() does not write vector data.\n setFieldAppli->ExecuteAndWriteOutput();\n }\n }\n\n void ComputePolygonStatistics()\n {\n auto polygonClassAppli = GetInternalApplication(\"polystat\");\n auto& input = m_FileHandler[ \"inputWithClassField\" ];\n auto& output = m_FileHandler[ \"statsFiles\" ];\n FloatVectorImageListType* inputImageList = GetParameterImageList( \"io.il\" );\n \n \n for (unsigned int i =0; i < input.size(); i++)\n {\n output.push_back(\"polygonstat\"+ std::to_string(i) +\".xml\");\n \n polygonClassAppli->SetParameterInputImage( \"in\", inputImageList->GetNthElement(i) );\n polygonClassAppli->SetParameterString( \"vec\", input[i]);\n polygonClassAppli->SetParameterString( \"out\", output[i]);\n \n polygonClassAppli->UpdateParameters();\n polygonClassAppli->SetParameterString( \"field\", m_PredictorFieldName);\n \n ExecuteInternal( \"polystat\" );\n }\n \n }\n\n void ComputeSamplingRate()\n {\n auto samplingRateAppli = GetInternalApplication(\"rates\");\n \n samplingRateAppli->SetParameterStringList( \"il\", m_FileHandler[ \"statsFiles\" ]);\n \n std::string outputFileName = \"rates.xml\";\n samplingRateAppli->SetParameterString(\"out\", outputFileName);\n \n if (HasValue(\"sample.nt\"))\n {\n samplingRateAppli->SetParameterString(\"strategy\", \"constant\");\n \n \/\/ TODO why nb is a string in MultiImageSamplingRate + MultiImageSamplingRate seems to return nb-1 samples ...\n samplingRateAppli->SetParameterString(\"strategy.constant.nb\", std::to_string(GetParameterInt(\"sample.nt\")));\n }\n else\n {\n samplingRateAppli->SetParameterString(\"strategy\", \"all\");\n }\n \n ExecuteInternal( \"rates\");\n \n \/\/TODO add the created file (rates_i.xml) to the file handler for cleaning\n \n }\n\n void SelectSamples()\n {\n \n }\n \n void ExtractSamples()\n {\n \n }\n \n void TrainModel()\n {\n \n }\n \n void InitIO()\n {\n AddParameter( ParameterType_Group, \"io\", \"Input and output data\" );\n SetParameterDescription( \"io\", \"This group of parameters allows setting input and output data.\" );\n\n AddParameter( ParameterType_InputImageList, \"io.il\", \"Input Image List\" );\n SetParameterDescription( \"io.il\", \"A list of input images.\" );\n MandatoryOn( \"io.il\" );\n \n AddParameter( ParameterType_InputVectorDataList, \"io.vd\", \"Input Vector Data List\" );\n SetParameterDescription( \"io.vd\", \"A list of vector data to select the training samples.\" );\n MandatoryOn( \"io.vd\" );\n }\n \n void InitSampling()\n { \n AddApplication( \"VectorDataSetField\", \"setfield\", \"Set additional vector field\");\n AddApplication( \"PolygonClassStatistics\", \"polystat\", \"Polygon analysis\" );\n AddApplication( \"MultiImageSamplingRate\", \"rates\", \"Sampling rates\" );\n \n AddParameter( ParameterType_Group, \"sample\", \"Sampling parameters\" );\n SetParameterDescription( \"sample\", \"This group of parameters allows setting sampling parameters\" );\n\n AddParameter( ParameterType_Int, \"sample.nt\", \"Number of training samples\" );\n SetParameterDescription( \"sample.nt\", \"Number of training samples.\" );\n MandatoryOff( \"sample.nt\" );\n \n AddApplication( \"SampleSelection\", \"select\", \"Sample selection\" );\n \/\/AddApplication( \"SampleExtraction\", \"extraction\", \"Sample extraction\" );\n \n }\n \n void InitLearning()\n {\n }\n\nprivate:\n\n void DoInit() override\n {\n SetName(\"TrainImagesRegression\");\n SetDescription(\" \");\n\n SetDocLongDescription(\" \");\n SetDocLimitations(\" \");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n \n AddDocTag(Tags::Learning);\n \n SetOfficialDocLink();\n \n ClearApplications();\n \n InitIO();\n InitSampling();\n InitLearning();\n }\n \n void DoUpdateParameters() override\n {\n }\n\n bool ClearFileHandler()\n {\n bool res = true;\n for (const auto & fileNameList : m_FileHandler)\n {\n for (const auto & filename : fileNameList.second)\n {\n res = true;\n if( itksys::SystemTools::FileExists( filename ) )\n {\n size_t posExt = filename.rfind( '.' );\n if( posExt != std::string::npos && filename.compare( posExt, std::string::npos, \".shp\" ) == 0 )\n {\n std::string shxPath = filename.substr( 0, posExt ) + std::string( \".shx\" );\n std::string dbfPath = filename.substr( 0, posExt ) + std::string( \".dbf\" );\n std::string prjPath = filename.substr( 0, posExt ) + std::string( \".prj\" );\n itksys::SystemTools::RemoveFile( shxPath );\n itksys::SystemTools::RemoveFile( dbfPath );\n itksys::SystemTools::RemoveFile( prjPath );\n }\n res = itksys::SystemTools::RemoveFile( filename );\n }\n }\n }\n m_FileHandler.clear();\n return res;\n }\n \n void DoExecute() override\n {\n \/\/TODO validation set ??\n \n AddRegressionField();\n \n std::cout << \"Regression field added\" << std::endl;\n \n ComputePolygonStatistics();\n \n std::cout << \"Polygon class statistic done\" << std::endl;\n \n ComputeSamplingRate();\n \n std::cout << \"Sampling rate computation done\" << std::endl;\n \n SelectSamples();\n \n ExtractSamples();\n \n TrainModel();\n \n ClearFileHandler();\n }\n \n std::string m_PredictorFieldName = \"regclass\";\n std::map< std::string, std::vector<std::string>> m_FileHandler;\n \n};\n\n} \/\/end namespace Wrapper\n} \/\/end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::TrainImagesRegression)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/CardSets\/CoreCardsGen.hpp>\n#include <hspp\/Enchants\/Effects.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/AddEnchantmentTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DamageTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DestroyTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DiscardTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/HealFullTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/HealTask.hpp>\n\nusing namespace Hearthstonepp::SimpleTasks;\n\nnamespace Hearthstonepp\n{\nvoid CoreCardsGen::AddHeroes(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHeroPowers(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddDruid(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddDruidNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHunter(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHunterNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddMage(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddMageNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddPaladin(std::map<std::string, Power>& cards)\n{\n (void)cards;\n\n \/\/ --------------------------------------- MINION - PALADIN\n \/\/ [CS2_088] Guardian of Kings - COST:7 [ATK:5\/HP:6]\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Restore 6 Health to your hero.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new HealTask(EntityType::HERO, 6));\n cards.emplace(\"CS2_088\", power);\n}\n\nvoid CoreCardsGen::AddPaladinNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddPriest(std::map<std::string, Power>& cards)\n{\n \/\/ ----------------------------------------- SPELL - PRIEST\n \/\/ [CS1_112] Holy Nova - COST:5\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: Deal $2 damage to all enemies.\n \/\/ Restore #2 Health to all friendly characters.\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new DamageTask(EntityType::ENEMIES, 2));\n power.AddPowerTask(new HealTask(EntityType::FRIENDS, 2));\n cards.emplace(\"CS1_112\", power);\n\n \/\/ ----------------------------------------- SPELL - PRIEST\n \/\/ [CS1_113] Mind Control - COST:10\n \/\/ - Faction: neutral, Set: core, Rarity: free\n \/\/ --------------------------------------------------------\n \/\/ Text: Take control of an enemy minion.\n \/\/ --------------------------------------------------------\n \/\/ PlayReq:\n \/\/ - REQ_TARGET_TO_PLAY = 0\n \/\/ - REQ_MINION_TARGET = 0\n \/\/ - REQ_ENEMY_TARGET = 0\n \/\/ - REQ_NUM_MINION_SLOTS = 1\n \/\/ --------------------------------------------------------\n}\n\nvoid CoreCardsGen::AddPriestNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddRogue(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddRogueNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddShaman(std::map<std::string, Power>& cards)\n{\n \/\/ ----------------------------------------- SPELL - SHAMAN\n \/\/ [CS2_041] Ancestral Healing - COST:0\n \/\/ - Faction: Neutral, Set: Basic, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: Restore a minion\n \/\/ to full Health and\n \/\/ give it <b>Taunt<\/b>.\n \/\/ --------------------------------------------------------\n \/\/ PlayReq:\n \/\/ - REQ_TARGET_TO_PLAY = 0\n \/\/ - REQ_MINION_TARGET = 0\n \/\/ --------------------------------------------------------\n \/\/ Tag:\n \/\/ - TAUNT = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new HealFullTask(EntityType::TARGET));\n power.AddPowerTask(new AddEnchantmentTask(\"CS2_041e\", EntityType::TARGET));\n cards.emplace(\"CS2_041\", power);\n}\n\nvoid CoreCardsGen::AddShamanNonCollect(std::map<std::string, Power>& cards)\n{\n \/\/ ----------------------------------- ENCHANTMENT - SHAMAN\n \/\/ [CS2_041e] Ancestral Infusion (*) - COST:0\n \/\/ - Set: core,\n \/\/ --------------------------------------------------------\n \/\/ Text: Taunt.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - TAUNT = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddEnchant(new Enchant(Effects::Taunt));\n cards.emplace(\"CS2_041e\", power);\n}\n\nvoid CoreCardsGen::AddWarlock(std::map<std::string, Power>& cards)\n{\n \/\/ --------------------------------------- MINION - NEUTRAL\n \/\/ [EX1_306] Succubus - COST:2 [ATK:4\/HP:3]\n \/\/ - Fac: horde, Set: core, Rarity: free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Discard a random card.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new DiscardTask(EntityType::HAND));\n cards.emplace(\"EX1_306\", power);\n}\n\nvoid CoreCardsGen::AddWarlockNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddWarrior(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddWarriorNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddNeutral(std::map<std::string, Power>& cards)\n{\n \/\/ --------------------------------------- MINION - NEUTRAL\n \/\/ [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3\/HP:2]\n \/\/ - Fac: alliance, Set: core, Rarity: free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Destroy your opponent's weapon.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new DestroyTask(EntityType::ENEMY_WEAPON));\n cards.emplace(\"EX1_066\", power);\n}\n\nvoid CoreCardsGen::AddNeutralNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddAll(std::map<std::string, Power>& cards)\n{\n AddHeroes(cards);\n AddHeroPowers(cards);\n\n AddDruid(cards);\n AddDruidNonCollect(cards);\n\n AddHunter(cards);\n AddHunterNonCollect(cards);\n\n AddMage(cards);\n AddMageNonCollect(cards);\n\n AddPaladin(cards);\n AddPaladinNonCollect(cards);\n\n AddPriest(cards);\n AddPriestNonCollect(cards);\n\n AddRogue(cards);\n AddRogueNonCollect(cards);\n\n AddShaman(cards);\n AddShamanNonCollect(cards);\n\n AddWarlock(cards);\n AddWarlockNonCollect(cards);\n\n AddWarrior(cards);\n AddWarriorNonCollect(cards);\n\n AddNeutral(cards);\n AddNeutralNonCollect(cards);\n}\n} \/\/ namespace Hearthstonepp\n<commit_msg>feat(card-impl): Use ClearData() method<commit_after>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/CardSets\/CoreCardsGen.hpp>\n#include <hspp\/Enchants\/Effects.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/AddEnchantmentTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DamageTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DestroyTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/DiscardTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/HealFullTask.hpp>\n#include <hspp\/Tasks\/SimpleTasks\/HealTask.hpp>\n\nusing namespace Hearthstonepp::SimpleTasks;\n\nnamespace Hearthstonepp\n{\nvoid CoreCardsGen::AddHeroes(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHeroPowers(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddDruid(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddDruidNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHunter(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddHunterNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddMage(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddMageNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddPaladin(std::map<std::string, Power>& cards)\n{\n \/\/ --------------------------------------- MINION - PALADIN\n \/\/ [CS2_088] Guardian of Kings - COST:7 [ATK:5\/HP:6]\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Restore 6 Health to your hero.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new HealTask(EntityType::HERO, 6));\n cards.emplace(\"CS2_088\", power);\n}\n\nvoid CoreCardsGen::AddPaladinNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddPriest(std::map<std::string, Power>& cards)\n{\n Power power;\n\n \/\/ ----------------------------------------- SPELL - PRIEST\n \/\/ [CS1_112] Holy Nova - COST:5\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: Deal $2 damage to all enemies.\n \/\/ Restore #2 Health to all friendly characters.\n \/\/ --------------------------------------------------------\n power.ClearData();\n power.AddPowerTask(new DamageTask(EntityType::ENEMIES, 2));\n power.AddPowerTask(new HealTask(EntityType::FRIENDS, 2));\n cards.emplace(\"CS1_112\", power);\n\n \/\/ ----------------------------------------- SPELL - PRIEST\n \/\/ [CS1_113] Mind Control - COST:10\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: Take control of an enemy minion.\n \/\/ --------------------------------------------------------\n \/\/ PlayReq:\n \/\/ - REQ_TARGET_TO_PLAY = 0\n \/\/ - REQ_MINION_TARGET = 0\n \/\/ - REQ_ENEMY_TARGET = 0\n \/\/ - REQ_NUM_MINION_SLOTS = 1\n \/\/ --------------------------------------------------------\n}\n\nvoid CoreCardsGen::AddPriestNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddRogue(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddRogueNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddShaman(std::map<std::string, Power>& cards)\n{\n \/\/ ----------------------------------------- SPELL - SHAMAN\n \/\/ [CS2_041] Ancestral Healing - COST:0\n \/\/ - Faction: Neutral, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: Restore a minion\n \/\/ to full Health and\n \/\/ give it <b>Taunt<\/b>.\n \/\/ --------------------------------------------------------\n \/\/ PlayReq:\n \/\/ - REQ_TARGET_TO_PLAY = 0\n \/\/ - REQ_MINION_TARGET = 0\n \/\/ --------------------------------------------------------\n \/\/ Tag:\n \/\/ - TAUNT = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new HealFullTask(EntityType::TARGET));\n power.AddPowerTask(new AddEnchantmentTask(\"CS2_041e\", EntityType::TARGET));\n cards.emplace(\"CS2_041\", power);\n}\n\nvoid CoreCardsGen::AddShamanNonCollect(std::map<std::string, Power>& cards)\n{\n \/\/ ----------------------------------- ENCHANTMENT - SHAMAN\n \/\/ [CS2_041e] Ancestral Infusion (*) - COST:0\n \/\/ - Set: Core,\n \/\/ --------------------------------------------------------\n \/\/ Text: Taunt.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - TAUNT = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddEnchant(new Enchant(Effects::Taunt));\n cards.emplace(\"CS2_041e\", power);\n}\n\nvoid CoreCardsGen::AddWarlock(std::map<std::string, Power>& cards)\n{\n \/\/ --------------------------------------- MINION - NEUTRAL\n \/\/ [EX1_306] Succubus - COST:2 [ATK:4\/HP:3]\n \/\/ - Faction: Horde, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Discard a random card.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new DiscardTask(EntityType::HAND));\n cards.emplace(\"EX1_306\", power);\n}\n\nvoid CoreCardsGen::AddWarlockNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddWarrior(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddWarriorNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddNeutral(std::map<std::string, Power>& cards)\n{\n \/\/ --------------------------------------- MINION - NEUTRAL\n \/\/ [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3\/HP:2]\n \/\/ - Faction: Alliance, Set: Core, Rarity: Free\n \/\/ --------------------------------------------------------\n \/\/ Text: <b>Battlecry:<\/b> Destroy your opponent's weapon.\n \/\/ --------------------------------------------------------\n \/\/ GameTag:\n \/\/ - BATTLECRY = 1\n \/\/ --------------------------------------------------------\n Power power;\n power.AddPowerTask(new DestroyTask(EntityType::ENEMY_WEAPON));\n cards.emplace(\"EX1_066\", power);\n}\n\nvoid CoreCardsGen::AddNeutralNonCollect(std::map<std::string, Power>& cards)\n{\n (void)cards;\n}\n\nvoid CoreCardsGen::AddAll(std::map<std::string, Power>& cards)\n{\n AddHeroes(cards);\n AddHeroPowers(cards);\n\n AddDruid(cards);\n AddDruidNonCollect(cards);\n\n AddHunter(cards);\n AddHunterNonCollect(cards);\n\n AddMage(cards);\n AddMageNonCollect(cards);\n\n AddPaladin(cards);\n AddPaladinNonCollect(cards);\n\n AddPriest(cards);\n AddPriestNonCollect(cards);\n\n AddRogue(cards);\n AddRogueNonCollect(cards);\n\n AddShaman(cards);\n AddShamanNonCollect(cards);\n\n AddWarlock(cards);\n AddWarlockNonCollect(cards);\n\n AddWarrior(cards);\n AddWarriorNonCollect(cards);\n\n AddNeutral(cards);\n AddNeutralNonCollect(cards);\n}\n} \/\/ namespace Hearthstonepp\n<|endoftext|>"} {"text":"<commit_before>#include \"Streak.h\"\n\nStreak::Streak(uint16_t columns,\n uint16_t rows,\n uint8_t hue,\n uint8_t saturation,\n CRGB * leds)\n: Visualization(columns, rows, hue, saturation, leds)\n{\n this->length = 0;\n this->minLength = 8;\n this->maxLength = 16;\n this->minInterval = 0;\n this->maxInterval = 90;\n}\n\nvoid Streak::inititalize() {\n this->interval = random8(this->minInterval, this->maxInterval);\n this->column = random8(this->columns);\n this->length = random8(this->minLength, this->maxLength);\n if (this->randomHue) {\n this->setHue(random(256));\n }\n}\n\nvoid Streak::display (unsigned long currentTime) {\n int currentFrame = this->frame % (this->rows + this->length);\n\n if (currentFrame == 0) {\n this->inititalize();\n }\n\n if (currentTime > this->nextTime) {\n \/\/ Serial.print(this->id);\n \/\/ Serial.print(\": \");\n \/\/ Serial.println(currentTime);\n this->frame++;\n this->nextTime = currentTime + this->interval;\n }\n\n int y = currentFrame;\n int pos;\n for (uint8_t i=0; i<this->length; i++) {\n if ((y - i >= 0) && (y - i < this->rows)) {\n pos = this->xy2Pos(this->column, y - i);\n this->leds[pos] = this->color;\n\n if (this->fade) {\n this->leds[pos].fadeLightBy((256 \/ this->length) * i);\n }\n }\n }\n}\n\nvoid Streak::setLengthMinMax(uint8_t min, uint8_t max) {\n this->minLength = min;\n this->maxLength = max;\n}\n\nvoid Streak::setIntervalMinMax(uint8_t min, uint8_t max) {\n this->minInterval = min;\n this->maxInterval = max;\n}\n\nvoid Streak::setFade(bool on) {\n this->fade = on;\n}\n\nvoid Streak::setRandomHue(bool on) {\n this->randomHue = on;\n}\n<commit_msg>initialize bools<commit_after>#include \"Streak.h\"\n\nStreak::Streak(uint16_t columns,\n uint16_t rows,\n uint8_t hue,\n uint8_t saturation,\n CRGB * leds)\n: Visualization(columns, rows, hue, saturation, leds)\n{\n this->length = 0;\n this->minLength = 8;\n this->maxLength = 16;\n this->minInterval = 0;\n this->maxInterval = 90;\n this->randomHue = false;\n this->fade = true;\n}\n\nvoid Streak::inititalize() {\n this->interval = random8(this->minInterval, this->maxInterval);\n this->column = random8(this->columns);\n this->length = random8(this->minLength, this->maxLength);\n if (this->randomHue) {\n this->setHue(random(256));\n }\n}\n\nvoid Streak::display (unsigned long currentTime) {\n int currentFrame = this->frame % (this->rows + this->length);\n\n if (currentFrame == 0) {\n this->inititalize();\n }\n\n if (currentTime > this->nextTime) {\n \/\/ Serial.print(this->id);\n \/\/ Serial.print(\": \");\n \/\/ Serial.println(currentTime);\n this->frame++;\n this->nextTime = currentTime + this->interval;\n }\n\n int y = currentFrame;\n int pos;\n for (uint8_t i=0; i<this->length; i++) {\n if ((y - i >= 0) && (y - i < this->rows)) {\n pos = this->xy2Pos(this->column, y - i);\n this->leds[pos] = this->color;\n\n if (this->fade) {\n this->leds[pos].fadeLightBy((256 \/ this->length) * i);\n }\n }\n }\n}\n\nvoid Streak::setLengthMinMax(uint8_t min, uint8_t max) {\n this->minLength = min;\n this->maxLength = max;\n}\n\nvoid Streak::setIntervalMinMax(uint8_t min, uint8_t max) {\n this->minInterval = min;\n this->maxInterval = max;\n}\n\nvoid Streak::setFade(bool on) {\n this->fade = on;\n}\n\nvoid Streak::setRandomHue(bool on) {\n this->randomHue = on;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>add a multiplicity cut for PbPb and XeXe sample<commit_after><|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n Anders Knospe - last modified on 26 March 2016\n Arvind Khuntia - last modified on 20 Nov 2020\n\t \/\/Lauches phi analysis with rsn mini package for Pb-Pb@ 5.02 Tev\n\t \/\/Allows basic configuration of pile-up check and event cuts\n\t ****************************************************************************\/\n#if !defined (__CINT__) || defined (__CLING__)\nR__ADD_INCLUDE_PATH($ALICE_PHYSICS)\n#include <PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPbPb5TeVRun2.C>\n#endif\n\nenum pairYCutSet { kPairDefault=0,\n kCentral \/\/=1\n};\n\nenum eventCutSet { kEvtDefault=0,\n kNoPileUpCut, \/\/=1\n kDefaultVtx8,\/\/=2\n kDefaultVtx12, \/\/=3\n kVertexoff \/\/=4\n};\n\nenum eventMixConfig { kDisabled = -1,\n kMixDefault,\/\/=0 \/\/10 events, Dvz = 1cm, DC = 10\n k5Evts, \/\/=1 \/\/5 events, Dvz = 1cm, DC = 10\n k5Cent, \/\/=2 \/\/10 events, Dvz = 1cm, DC = 5\n k5Evts5Cent \/\/3 \/\/5 events, Dvz = 1 cm, DC = 5\n};\n\nAliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeVRun2\n(\n Bool_t isMC = kFALSE,\n Bool_t isPP = kFALSE,\n AliRsnMiniValue::EType cosThetaType = AliRsnMiniValue::kCosThetaHe,\n TString outNameSuffix = \"tpc2stof3sveto\",\n Int_t evtCutSetID = 0,\n Int_t mixingConfigID = 0,\n Int_t aodFilterBit = 5,\n Int_t customQualityCutsID = 1,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n Float_t nsigmaKa = 2.,\n Bool_t timeRangeCut = kTRUE,\n Bool_t isESD = kFALSE,\n Bool_t enableMonitor = kTRUE,\n Bool_t IsMcTrueOnly = kFALSE,\n TString monitorOpt = \"NoSIGN\",\n Bool_t useMixLS = 0,\n Bool_t checkReflex = 0,\n UInt_t triggerMask = AliVEvent::kINT7,\n Int_t pairCutSetID = 0\n )\n\n{ \n \/\/-------------------------------------------\n \/\/ event cuts\n \/\/-------------------------------------------\n Bool_t rejectPileUp = kTRUE;\n Double_t vtxZcut = 10.0;\/\/cm, default cut on vtx z\n Int_t MultBins = aodFilterBit\/100;\n\n if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;\n if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; \/\/cm\n if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; \/\/cm\n if(evtCutSetID==eventCutSet::kVertexoff) vtxZcut=1.e6; \/\/off\n\n if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;\n \/\/-------------------------------------------\n \/\/ pair cuts\n \/\/-------------------------------------------\n Double_t minYlab=-0.5;\n Double_t maxYlab= 0.5;\n if(pairCutSetID==pairYCutSet::kCentral){ minYlab=-0.3; maxYlab=0.3;} \/\/|y_cm|<0.3\n \/\/-------------------------------------------\n \/\/ mixing settings\n \/\/-------------------------------------------\n Int_t nmix=0;\n Float_t maxDiffVzMix=1.;\n Float_t maxDiffMultMix=10.;\n\n if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;\n if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;\n if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;\n if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}\n \/\/--------------------------------------------\n \/\/ INITIALIZATION\n \/\/--------------------------------------------\n \/\/ retrieve analysis manager\n AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();\n if(!mgr){\n ::Error(\"AddTaskPhiPbPb5TeVRun2\", \"No analysis manager to connect to ==>\");\n return NULL;\n }\n\n \/\/ create the task and configure \n TString taskName=Form(\"phi%s%s_%i\",(isPP? \"pp\" : \"PbPb\"),(isMC ? \"MC\" : \"Data\"),(Int_t)cutKaCandidate);\n AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);\n if (isESD) task->UseESDTriggerMask(triggerMask); \/\/ESD ****** check this *****\n else task->SelectCollisionCandidates(triggerMask); \/\/AOD\n if (isPP) task->UseMultiplicity(\"QUALITY\");\n else task->UseMultiplicity(\"AliMultSelection_V0M\");\/\/only for run2\n\n \/\/ set event mixing options\n task->UseContinuousMix();\n \/\/task->UseBinnedMix();\n task->SetNMix(nmix);\n task->SetMaxDiffVz(maxDiffVzMix);\n task->SetMaxDiffMult(maxDiffMultMix);\n task->SetMaxDiffAngle(20.0*TMath::DegToRad());\n task->SetUseTimeRangeCut(timeRangeCut);\n ::Info(\"AddTaskPhiPbPb5TeVRun2\", Form(\"Event mixing configuration: \\n events to mix = %i \"\n \"\\n max diff. vtxZ = cm %5.3f \\n max diff multi = %5.3f\", nmix, maxDiffVzMix, maxDiffMultMix));\n mgr->AddTask(task);\n \/\/ cut on primary vertex:\n \/\/ - 2nd argument --> |Vz| range\n \/\/ - 3rd argument --> minimum required number of contributors to vtx\n \/\/ - 4th argument --> tells if TPC stand-alone vertexes must be accepted\n\n AliRsnCutEventUtils* cutEventUtils=0;\n cutEventUtils=new AliRsnCutEventUtils(\"cutEventUtils\",kTRUE,rejectPileUp);\n cutEventUtils->SetCheckAcceptedMultSelection();\n\n \/\/AliRsnCutPrimaryVertex* cutVertex=0;\n \/\/cutVertex=new AliRsnCutPrimaryVertex(\"cutVertex\",vtxZcut,0,kFALSE);\n\n \/\/ define and fill cut set for event cut\n AliRsnCutSet* eventCuts=0;\n eventCuts=new AliRsnCutSet(\"eventCuts\",AliRsnTarget::kEvent);\n \/\/eventCuts->AddCut(cutVertex);\n eventCuts->AddCut(cutEventUtils);\n eventCuts->SetCutScheme(Form(\"%s%s\",cutEventUtils->GetName()));\n task->SetEventCuts(eventCuts);\n\n \/\/ ------------ EVENT-ONLY COMPUTATIONS -----------------------\n\n \/\/vertex\n Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);\n AliRsnMiniOutput* outVtx=task->CreateOutput(\"eventVtx\",\"HIST\",\"EVENT\");\n outVtx->AddAxis(vtxID,400,-20.0,20.0);\n\n \/\/multiplicity or centrality\n Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);\n AliRsnMiniOutput* outMult=task->CreateOutput(\"eventMult\",\"HIST\",\"EVENT\");\n if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);\n else outMult->AddAxis(multID,110,0.,110.);\n\n TH2F* hvz=new TH2F(\"hVzVsCent\",\"\",110,0.,110., 240,-12.0,12.0);\n task->SetEventQAHist(\"vz\",hvz);\/\/plugs this histogram into the fHAEventVz data member\n\n TH2F* hmc=new TH2F(\"MultiVsCent\",\"\", 110,0.,110., 400,0.5,400.5);\n hmc->GetYaxis()->SetTitle(\"QUALITY\");\n task->SetEventQAHist(\"multicent\",hmc);\/\/plugs this histogram into the fHAEventMultiCent data member\n\n \/\/--------- PAIR CUTS (common to all resonances) --- ----------\n\n AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair(\"cutRapidity\",AliRsnCutMiniPair::kRapidityRange);\n cutY->SetRangeD(minYlab,maxYlab);\n AliRsnCutSet* cutsPair=new AliRsnCutSet(\"pairCuts\",AliRsnTarget::kMother);\n cutsPair->AddCut(cutY);\n cutsPair->SetCutScheme(cutY->GetName());\n\n \/\/------------------ CONFIG ANALYSIS ----------------------------\n\n \/\/gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPP8TeV.C\");\n#if !defined (__CINT__) || defined (__CLING__)\n if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;\n\n#else\n \/\/ gROOT->LoadMacro(\"ConfigPhiPbPb5TeVRun2.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPbPb5TeVRun2.C\");\n if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;\n#endif\n\n \/\/------------------- CONTAINERS ------------------------\n\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/ outputFileName += \":Rsn\";\n Printf(\"AddAnalysisTaskPhiPbPb5TeVRun2 - Set OutputFileName : \\n %s\\n\",outputFileName.Data());\n\n AliAnalysisDataContainer* output=mgr->CreateContainer(Form(\"RsnOut_%s\",outNameSuffix.Data()),\n\t\t\t\t\t\t\tTList::Class(),\n\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\toutputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n return task;\n}\n\n<commit_msg>bug fix [rsn-phi meson analysis]<commit_after>\/***************************************************************************\n Anders Knospe - last modified on 26 March 2016\n Arvind Khuntia - last modified on 20 Nov 2020\n\t \/\/Lauches phi analysis with rsn mini package for Pb-Pb@ 5.02 Tev\n\t \/\/Allows basic configuration of pile-up check and event cuts\n\t ****************************************************************************\/\n#if !defined (__CINT__) || defined (__CLING__)\nR__ADD_INCLUDE_PATH($ALICE_PHYSICS)\n#include <PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPbPb5TeVRun2.C>\n#endif\n\nenum pairYCutSet { kPairDefault=0,\n kCentral \/\/=1\n};\n\nenum eventCutSet { kEvtDefault=0,\n kNoPileUpCut, \/\/=1\n kDefaultVtx8,\/\/=2\n kDefaultVtx12, \/\/=3\n kVertexoff \/\/=4\n};\n\nenum eventMixConfig { kDisabled = -1,\n kMixDefault,\/\/=0 \/\/10 events, Dvz = 1cm, DC = 10\n k5Evts, \/\/=1 \/\/5 events, Dvz = 1cm, DC = 10\n k5Cent, \/\/=2 \/\/10 events, Dvz = 1cm, DC = 5\n k5Evts5Cent \/\/3 \/\/5 events, Dvz = 1 cm, DC = 5\n};\n\nAliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeVRun2\n(\n Bool_t isMC = kFALSE,\n Bool_t isPP = kFALSE,\n AliRsnMiniValue::EType cosThetaType = AliRsnMiniValue::kCosThetaHe,\n TString outNameSuffix = \"tpc2stof3sveto\",\n Int_t evtCutSetID = 0,\n Int_t mixingConfigID = 0,\n Int_t aodFilterBit = 5,\n Int_t customQualityCutsID = 1,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n Float_t nsigmaKa = 2.,\n Bool_t timeRangeCut = kTRUE,\n Bool_t isESD = kFALSE,\n Bool_t enableMonitor = kTRUE,\n Bool_t IsMcTrueOnly = kFALSE,\n TString monitorOpt = \"PbPb\",\n Bool_t useMixLS = 0,\n Bool_t checkReflex = 0,\n UInt_t triggerMask = AliVEvent::kINT7,\n Int_t pairCutSetID = 0\n )\n\n{ \n \/\/-------------------------------------------\n \/\/ event cuts\n \/\/-------------------------------------------\n Bool_t rejectPileUp = kTRUE;\n Double_t vtxZcut = 10.0;\/\/cm, default cut on vtx z\n Int_t MultBins = aodFilterBit\/100;\n\n if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;\n if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; \/\/cm\n if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; \/\/cm\n if(evtCutSetID==eventCutSet::kVertexoff) vtxZcut=1.e6; \/\/off\n\n if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;\n \/\/-------------------------------------------\n \/\/ pair cuts\n \/\/-------------------------------------------\n Double_t minYlab=-0.5;\n Double_t maxYlab= 0.5;\n if(pairCutSetID==pairYCutSet::kCentral){ minYlab=-0.3; maxYlab=0.3;} \/\/|y_cm|<0.3\n \/\/-------------------------------------------\n \/\/ mixing settings\n \/\/-------------------------------------------\n Int_t nmix=0;\n Float_t maxDiffVzMix=1.;\n Float_t maxDiffMultMix=10.;\n\n if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;\n if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;\n if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;\n if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}\n \/\/--------------------------------------------\n \/\/ INITIALIZATION\n \/\/--------------------------------------------\n \/\/ retrieve analysis manager\n AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();\n if(!mgr){\n ::Error(\"AddTaskPhiPbPb5TeVRun2\", \"No analysis manager to connect to ==>\");\n return NULL;\n }\n\n \/\/ create the task and configure \n TString taskName=Form(\"phi%s%s_%i\",(isPP? \"pp\" : \"PbPb\"),(isMC ? \"MC\" : \"Data\"),(Int_t)cutKaCandidate);\n AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);\n if (isESD) task->UseESDTriggerMask(triggerMask); \/\/ESD ****** check this *****\n else task->SelectCollisionCandidates(triggerMask); \/\/AOD\n if (isPP) task->UseMultiplicity(\"QUALITY\");\n else task->UseMultiplicity(\"AliMultSelection_V0M\");\/\/only for run2\n\n \/\/ set event mixing options\n task->UseContinuousMix();\n \/\/task->UseBinnedMix();\n task->SetNMix(nmix);\n task->SetMaxDiffVz(maxDiffVzMix);\n task->SetMaxDiffMult(maxDiffMultMix);\n task->SetMaxDiffAngle(20.0*TMath::DegToRad());\n task->SetUseTimeRangeCut(timeRangeCut);\n ::Info(\"AddTaskPhiPbPb5TeVRun2\", Form(\"Event mixing configuration: \\n events to mix = %i \"\n \"\\n max diff. vtxZ = cm %5.3f \\n max diff multi = %5.3f\", nmix, maxDiffVzMix, maxDiffMultMix));\n mgr->AddTask(task);\n \/\/ cut on primary vertex:\n \/\/ - 2nd argument --> |Vz| range\n \/\/ - 3rd argument --> minimum required number of contributors to vtx\n \/\/ - 4th argument --> tells if TPC stand-alone vertexes must be accepted\n\n AliRsnCutEventUtils* cutEventUtils=0;\n cutEventUtils=new AliRsnCutEventUtils(\"cutEventUtils\",kTRUE,rejectPileUp);\n cutEventUtils->SetCheckAcceptedMultSelection();\n\n \/\/AliRsnCutPrimaryVertex* cutVertex=0;\n \/\/cutVertex=new AliRsnCutPrimaryVertex(\"cutVertex\",vtxZcut,0,kFALSE);\n\n \/\/ define and fill cut set for event cut\n AliRsnCutSet* eventCuts=0;\n eventCuts=new AliRsnCutSet(\"eventCuts\",AliRsnTarget::kEvent);\n \/\/eventCuts->AddCut(cutVertex);\n eventCuts->AddCut(cutEventUtils);\n eventCuts->SetCutScheme(Form(\"%s\",cutEventUtils->GetName()));\n task->SetEventCuts(eventCuts);\n\n \/\/ ------------ EVENT-ONLY COMPUTATIONS -----------------------\n\n \/\/vertex\n Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);\n AliRsnMiniOutput* outVtx=task->CreateOutput(\"eventVtx\",\"HIST\",\"EVENT\");\n outVtx->AddAxis(vtxID,400,-20.0,20.0);\n\n \/\/multiplicity or centrality\n Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);\n AliRsnMiniOutput* outMult=task->CreateOutput(\"eventMult\",\"HIST\",\"EVENT\");\n if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);\n else outMult->AddAxis(multID,110,0.,110.);\n\n TH2F* hvz=new TH2F(\"hVzVsCent\",\"\",110,0.,110., 240,-12.0,12.0);\n task->SetEventQAHist(\"vz\",hvz);\/\/plugs this histogram into the fHAEventVz data member\n\n TH2F* hmc=new TH2F(\"MultiVsCent\",\"\", 110,0.,110., 400,0.5,400.5);\n hmc->GetYaxis()->SetTitle(\"QUALITY\");\n task->SetEventQAHist(\"multicent\",hmc);\/\/plugs this histogram into the fHAEventMultiCent data member\n\n \/\/--------- PAIR CUTS (common to all resonances) --- ----------\n\n AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair(\"cutRapidity\",AliRsnCutMiniPair::kRapidityRange);\n cutY->SetRangeD(minYlab,maxYlab);\n AliRsnCutSet* cutsPair=new AliRsnCutSet(\"pairCuts\",AliRsnTarget::kMother);\n cutsPair->AddCut(cutY);\n cutsPair->SetCutScheme(cutY->GetName());\n\n \/\/------------------ CONFIG ANALYSIS ----------------------------\n\n \/\/gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPP8TeV.C\");\n#if !defined (__CINT__) || defined (__CLING__)\n if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;\n\n#else\n \/\/ gROOT->LoadMacro(\"ConfigPhiPbPb5TeVRun2.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigPhiPbPb5TeVRun2.C\");\n if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;\n#endif\n\n \/\/------------------- CONTAINERS ------------------------\n\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/ outputFileName += \":Rsn\";\n Printf(\"AddAnalysisTaskPhiPbPb5TeVRun2 - Set OutputFileName : \\n %s\\n\",outputFileName.Data());\n\n AliAnalysisDataContainer* output=mgr->CreateContainer(Form(\"RsnOut_%s\",outNameSuffix.Data()),\n\t\t\t\t\t\t\tTList::Class(),\n\t\t\t\t\t\t\tAliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\toutputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n return task;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>nomsg<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRawImageIOTest4.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include <fstream>\n#include \"itkRawImageIO.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImage.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n\n\n\n\n\n\n\/\/ Helper class for reading a file and checking the content \ntemplate< typename TImageType >\nclass RawImageIOReadFileTester\n{\n\npublic:\n\/\/ Only single method of this class\nint Read( const char *filename , bool ReadBigEndian, unsigned int dims[] )\n {\n\n const unsigned int ImageDimension = TImageType::ImageDimension;\n\n typedef typename TImageType::PixelType PixelType;\n typedef itk::ImageFileReader<TImageType> ReaderType;\n typedef itk::RawImageIO<PixelType,ImageDimension> IOType;\n\n typename IOType::Pointer io = IOType::New();\n\n io->SetFileTypeToBinary();\n \n if( ReadBigEndian )\n {\n io->SetByteOrderToBigEndian();\n }\n else \n {\n io->SetByteOrderToLittleEndian();\n }\n\n\n for( unsigned int j = 0; j < TImageType::ImageDimension; j++ )\n {\n io->SetDimensions( j, dims[j] );\n }\n\n\n \n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( filename );\n reader->SetImageIO( io );\n reader->Update();\n\n\n typedef itk::ImageLinearIteratorWithIndex<TImageType> Iterator;\n Iterator it( reader->GetOutput(), reader->GetOutput()->GetBufferedRegion() );\n\n it.GoToBegin();\n it.SetDirection( 0 ); \n\n\n PixelType value = itk::NumericTraits< PixelType >::Zero;\n while ( !it.IsAtEnd() )\n {\n while ( !it.IsAtEndOfLine() )\n {\n PixelType readValue = it.Get();\n std::cout << readValue << \" \";\n if( readValue != value )\n {\n std::cerr << \"At index \" << it.GetIndex() << std::endl;\n std::cerr << \"the value \" << value << \" was expected \" << std::endl;\n std::cerr << \"but value \" << readValue << \" was read \" << std::endl;\n return EXIT_FAILURE;\n }\n ++it;\n ++value;\n }\n std::cout << std::endl;\n it.NextLine();\n }\n return EXIT_SUCCESS;\n }\n\n};\n\n\n\n\n\n\n\n\n\nint itkRawImageIOTest4(int, char**)\n{\n\n typedef unsigned short PixelType;\n const unsigned int ImageDimension = 2;\n\n typedef itk::RawImageIO<PixelType,ImageDimension> IOType;\n typedef itk::Image<PixelType,ImageDimension> ImageType;\n\n char filenameBigEndian[] = \"testBinaryBigEndian.raw\";\n char filenameLittleEndian[] = \"testBinaryLittleEndian.raw\";\n\n unsigned int dims[ImageDimension] = { 5, 5 };\n\n typedef itk::PixelTraits< PixelType >::ValueType ComponentType;\n typedef itk::ByteSwapper< ComponentType > ByteSwapperType;\n\n PixelType value = itk::NumericTraits< PixelType >::Zero;\n unsigned int numberOfPixels = dims[0] * dims[1];\n\n\n\n\n \/\/ Create the BigEndian binary file\n std::ofstream outputFile1;\n#ifdef _WIN32\n outputFile1.open( filenameBigEndian , std::ios::out | std::ios::binary );\n#else\n outputFile1.open( filenameBigEndian );\n#endif\n\n if( outputFile1.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n for( unsigned int i = 0; i < numberOfPixels; i++ )\n {\n PixelType swappedValue = value;\n \/\/ make sure that the file is written in \n \/\/ BigEndian regardless of the platform\n ByteSwapperType::SwapFromSystemToBigEndian( &swappedValue );\n outputFile1.write( reinterpret_cast<char*>(&swappedValue), \n sizeof(swappedValue) );\n ++value;\n }\n outputFile1.close();\n \n if( outputFile1.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n \/\/ Create the LittleEndian binary file\n std::ofstream outputFile2;\n#ifdef _WIN32\n outputFile2.open( filenameLittleEndian , std::ios::out | std::ios::binary );\n#else\n outputFile2.open( filenameLittleEndian );\n#endif\n\n if( outputFile2.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n value = itk::NumericTraits< PixelType >::Zero;\n for( unsigned int i = 0; i < numberOfPixels; i++ )\n {\n PixelType swappedValue = value;\n \/\/ make sure that the file is written in \n \/\/ LittleEndian regardless of the platform\n ByteSwapperType::SwapFromSystemToLittleEndian( &swappedValue );\n outputFile2.write( reinterpret_cast<char*>(&swappedValue), \n sizeof(swappedValue) );\n ++value;\n }\n outputFile2.close();\n \n if( outputFile2.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n RawImageIOReadFileTester<ImageType> readTester;\n\n\n int status = EXIT_FAILURE;\n\n std::cout << \"Testing read of Big Endian File\" << std::endl;\n bool fileIsBigEndian = true;\n status = readTester.Read( filenameBigEndian, fileIsBigEndian, dims );\n if( status==EXIT_FAILURE )\n {\n std::cerr << \"Reading Raw BigEndian FAILED !!\" << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Reading Raw BigEndian PASSED !!\" << std::endl << std::endl;\n }\n\n std::cout << \"Testing read of Little Endian File\" << std::endl;\n fileIsBigEndian = false;\n status = readTester.Read( filenameLittleEndian, fileIsBigEndian, dims );\n if( status==EXIT_FAILURE )\n {\n std::cerr << \"Reading Raw LittleEndian FAILED !!\" << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Reading Raw LittleEndian PASSED !!\" << std::endl << std::endl;\n }\n\n std::cout << \"Test PASSED !!\" << std::endl << std::endl;\n\n return EXIT_SUCCESS;\n\n}\n\n\n<commit_msg>ERR: warnings.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRawImageIOTest4.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include <fstream>\n#include \"itkRawImageIO.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImage.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n\n\n\n\n\n\n\/\/ Helper class for reading a file and checking the content \ntemplate< typename TImageType >\nclass RawImageIOReadFileTester\n{\n\npublic:\n\/\/ Only single method of this class\nint Read( const char *filename , bool ReadBigEndian, unsigned int dims[] )\n {\n\n const unsigned int ImageDimension = TImageType::ImageDimension;\n\n typedef typename TImageType::PixelType PixelType;\n typedef itk::ImageFileReader<TImageType> ReaderType;\n typedef itk::RawImageIO<PixelType,ImageDimension> IOType;\n\n typename IOType::Pointer io = IOType::New();\n\n io->SetFileTypeToBinary();\n \n if( ReadBigEndian )\n {\n io->SetByteOrderToBigEndian();\n }\n else \n {\n io->SetByteOrderToLittleEndian();\n }\n\n\n for( unsigned int j = 0; j < TImageType::ImageDimension; j++ )\n {\n io->SetDimensions( j, dims[j] );\n }\n\n\n \n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( filename );\n reader->SetImageIO( io );\n reader->Update();\n\n\n typedef itk::ImageLinearIteratorWithIndex<TImageType> Iterator;\n Iterator it( reader->GetOutput(), reader->GetOutput()->GetBufferedRegion() );\n\n it.GoToBegin();\n it.SetDirection( 0 ); \n\n\n PixelType value = itk::NumericTraits< PixelType >::Zero;\n while ( !it.IsAtEnd() )\n {\n while ( !it.IsAtEndOfLine() )\n {\n PixelType readValue = it.Get();\n std::cout << readValue << \" \";\n if( readValue != value )\n {\n std::cerr << \"At index \" << it.GetIndex() << std::endl;\n std::cerr << \"the value \" << value << \" was expected \" << std::endl;\n std::cerr << \"but value \" << readValue << \" was read \" << std::endl;\n return EXIT_FAILURE;\n }\n ++it;\n ++value;\n }\n std::cout << std::endl;\n it.NextLine();\n }\n return EXIT_SUCCESS;\n }\n\n};\n\n\n\n\n\n\n\n\n\nint itkRawImageIOTest4(int, char**)\n{\n\n typedef unsigned short PixelType;\n const unsigned int ImageDimension = 2;\n\n typedef itk::RawImageIO<PixelType,ImageDimension> IOType;\n typedef itk::Image<PixelType,ImageDimension> ImageType;\n\n char filenameBigEndian[] = \"testBinaryBigEndian.raw\";\n char filenameLittleEndian[] = \"testBinaryLittleEndian.raw\";\n\n unsigned int dims[ImageDimension] = { 5, 5 };\n\n typedef itk::PixelTraits< PixelType >::ValueType ComponentType;\n typedef itk::ByteSwapper< ComponentType > ByteSwapperType;\n\n PixelType value = itk::NumericTraits< PixelType >::Zero;\n unsigned int numberOfPixels = dims[0] * dims[1];\n\n\n\n\n \/\/ Create the BigEndian binary file\n std::ofstream outputFile1;\n#ifdef _WIN32\n outputFile1.open( filenameBigEndian , std::ios::out | std::ios::binary );\n#else\n outputFile1.open( filenameBigEndian );\n#endif\n\n if( outputFile1.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n for( unsigned int i = 0; i < numberOfPixels; i++ )\n {\n PixelType swappedValue = value;\n \/\/ make sure that the file is written in \n \/\/ BigEndian regardless of the platform\n ByteSwapperType::SwapFromSystemToBigEndian( &swappedValue );\n outputFile1.write( reinterpret_cast<char*>(&swappedValue), \n sizeof(swappedValue) );\n ++value;\n }\n outputFile1.close();\n \n if( outputFile1.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n\n \/\/ Create the LittleEndian binary file\n std::ofstream outputFile2;\n#ifdef _WIN32\n outputFile2.open( filenameLittleEndian , std::ios::out | std::ios::binary );\n#else\n outputFile2.open( filenameLittleEndian );\n#endif\n\n if( outputFile2.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n value = itk::NumericTraits< PixelType >::Zero;\n for( unsigned int i = 0; i < numberOfPixels; i++ )\n {\n PixelType swappedValue = value;\n \/\/ make sure that the file is written in \n \/\/ LittleEndian regardless of the platform\n ByteSwapperType::SwapFromSystemToLittleEndian( &swappedValue );\n outputFile2.write( reinterpret_cast<char*>(&swappedValue), \n sizeof(swappedValue) );\n ++value;\n }\n outputFile2.close();\n \n if( outputFile2.fail() )\n {\n std::cerr << \"itkRawImageIOTest4:Error writing the test file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n\n RawImageIOReadFileTester<ImageType> readTester;\n\n\n int status;\n\n std::cout << \"Testing read of Big Endian File\" << std::endl;\n bool fileIsBigEndian = true;\n status = readTester.Read( filenameBigEndian, fileIsBigEndian, dims );\n if( status==EXIT_FAILURE )\n {\n std::cerr << \"Reading Raw BigEndian FAILED !!\" << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Reading Raw BigEndian PASSED !!\" << std::endl << std::endl;\n }\n\n std::cout << \"Testing read of Little Endian File\" << std::endl;\n fileIsBigEndian = false;\n status = readTester.Read( filenameLittleEndian, fileIsBigEndian, dims );\n if( status==EXIT_FAILURE )\n {\n std::cerr << \"Reading Raw LittleEndian FAILED !!\" << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Reading Raw LittleEndian PASSED !!\" << std::endl << std::endl;\n }\n\n std::cout << \"Test PASSED !!\" << std::endl << std::endl;\n\n return EXIT_SUCCESS;\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef PITO_INTERCEPTOR_APPLICATION_HPP\n#define PITO_INTERCEPTOR_APPLICATION_HPP\n\n#include <pito\/config.hpp>\n#include <pito\/interceptor\/jail\/environment.hpp>\n\nnamespace pito { namespace interceptor {\n\nnamespace detail {\n void search_for_preload_library(std::string const& libraryFileName, std::string& preloadLibrary) {\n char const *ldPath = jail::getenv(PITO_LD_LIBRARY_PATH);\n if (ldPath) {\n char const *ldPathEnd = ldPath;\n while (*(++ldPathEnd) != '\\0') {}\n\n char const *colon = ldPath;\n do {\n colon = std::find(colon, ldPathEnd, ':');\n if (colon != ldPath) {\n preloadLibrary.assign(ldPath, colon);\n preloadLibrary.append(\"\/\").append(libraryFileName);\n if (! access(preloadLibrary.c_str(), R_OK)) return;\n else preloadLibrary = \"\";\n }\n ldPath = ++colon; \n } while (colon < ldPathEnd);\n }\n\n preloadLibrary = PITO_LIB_PREFIX;\n preloadLibrary.append(libraryFileName);\n if (access(preloadLibrary.c_str(), R_OK)) preloadLibrary = \"\";\n else {\n \/\/ make the library an absolute path\n if (*jail::preload.begin() != '\/') {\n char buff_[512];\n getcwd(buff_, sizeof(buff_));\n std::string newLibraryPath = buff_;\n newLibraryPath.append(\"\/\").append(jail::preload);\n jail::preload = newLibraryPath;\n }\n }\n }\n}\n\nvoid search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary) {\n libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);\n detail::search_for_preload_library(libraryFileName, preloadLibrary);\n}\n\n\n\/\/ search in $LD_LIBRARY_PATH, then installed location\nvoid search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary, std::string const& pathOverride) {\n libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);\n if (! pathOverride.empty()) {\n if ('\/' != *(preloadLibrary.end() - 1)) preloadLibrary.append(\"\/\");\n preloadLibrary.append(libraryFileName);\n if (! access(preloadLibrary.c_str(), R_OK)) return;\n }\n detail::search_for_preload_library(libraryFileName, preloadLibrary);\n}\n\n} }\n\n#endif\n<commit_msg>some missing stuffs<commit_after>#ifndef PITO_INTERCEPTOR_APPLICATION_HPP\n#define PITO_INTERCEPTOR_APPLICATION_HPP\n\n#include <pito\/config.hpp>\n#include <pito\/interceptor\/jail\/environment.hpp>\n\nnamespace pito { namespace interceptor {\n\nnamespace detail {\n void search_for_preload_library(std::string const& libraryFileName, std::string& preloadLibrary) {\n char const *ldPath = jail::getenv(PITO_LD_LIBRARY_PATH);\n if (ldPath) {\n char const *ldPathEnd = ldPath;\n while (*(++ldPathEnd) != '\\0') {}\n\n char const *colon = ldPath;\n do {\n colon = std::find(colon, ldPathEnd, ':');\n if (colon != ldPath) {\n preloadLibrary.assign(ldPath, colon);\n preloadLibrary.append(\"\/\").append(libraryFileName);\n if (! access(preloadLibrary.c_str(), R_OK)) break;\n else preloadLibrary = \"\";\n }\n ldPath = ++colon; \n } while (colon < ldPathEnd);\n }\n\n preloadLibrary = PITO_LIB_PREFIX;\n preloadLibrary.append(libraryFileName);\n if (access(preloadLibrary.c_str(), R_OK)) preloadLibrary = \"\";\n else {\n \/\/ make the library an absolute path\n if (*preloadLibrary.begin() != '\/') {\n char buff_[512];\n getcwd(buff_, sizeof(buff_));\n std::string newLibraryPath = buff_;\n newLibraryPath.append(\"\/\").append(preloadLibrary);\n preloadLibrary = newLibraryPath;\n }\n }\n }\n}\n\nvoid search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary) {\n libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);\n detail::search_for_preload_library(libraryFileName, preloadLibrary);\n}\n\n\n\/\/ search in $LD_LIBRARY_PATH, then installed location\nvoid search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary, std::string const& pathOverride) {\n libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);\n if (! pathOverride.empty()) {\n if ('\/' != *(preloadLibrary.end() - 1)) preloadLibrary.append(\"\/\");\n preloadLibrary.append(libraryFileName);\n if (! access(preloadLibrary.c_str(), R_OK)) return;\n }\n detail::search_for_preload_library(libraryFileName, preloadLibrary);\n}\n\n} }\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2017 Huy Cuong Nguyen\n* Copyright 2017 Axel Waggershauser\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n#include \"BitMatrixIO.h\"\n#include \"BitArray.h\"\n\n#include <fstream>\n\nnamespace ZXing {\n\nstd::string ToString(const BitMatrix& matrix, char one, char zero, bool addSpace, bool printAsCString)\n{\n\tstd::string result;\n\tresult.reserve((addSpace ? 2 : 1) * (matrix.width() * matrix.height()) + matrix.height());\n\tfor (int y = 0; y < matrix.height(); ++y) {\n\t\tBitArray row;\n\t\tmatrix.getRow(y, row);\n\t\tif (printAsCString)\n\t\t\tresult += '\"';\n\t\tfor (auto bit : row) {\n\t\t\tresult += bit ? one : zero;\n\t\t\tif (addSpace)\n\t\t\t\tresult += ' ';\n\t\t}\n\t\tif (printAsCString)\n\t\t\tresult += \"\\\\n\\\"\";\n\t\tresult += '\\n';\n\t}\n\treturn result;\n}\n\nBitMatrix ParseBitMatrix(const std::string& str, char one, bool expectSpace)\n{\n\tauto lineLength = str.find('\\n');\n\tif (lineLength == std::string::npos)\n\t\treturn {};\n\n\tint height = static_cast<int>(str.length() \/ (lineLength + 1));\n\tint width = static_cast<int>(expectSpace ? lineLength \/ 2 : lineLength);\n\tBitMatrix mat(width, height);\n\tfor (int y = 0; y < height; ++y) {\n\t\tsize_t offset = y * (lineLength + 1);\n\t\tfor (int x = 0; x < width; ++x) {\n\t\t\tif (str.at(offset) == one)\n\t\t\t\tmat.set(x, y);\n\t\t\toffset += expectSpace ? 2 : 1;\n\t\t}\n\t}\n\treturn mat;\n}\n\nvoid SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quiteZone)\n{\n\tauto out = Inflate(matrix.copy(), 0, 0, quiteZone);\n\tstd::ofstream file(filename);\n\tfile << \"P1\\n\" << out.width() << ' ' << out.height() << '\\n';\n\tfile << ToString(out, '1', '0', true);\n}\n\n} \/\/ ZXing\n<commit_msg>BitMatrixIO: code simplification<commit_after>\/*\n* Copyright 2017 Huy Cuong Nguyen\n* Copyright 2017 Axel Waggershauser\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n#include \"BitMatrixIO.h\"\n#include \"BitArray.h\"\n\n#include <fstream>\n\nnamespace ZXing {\n\nstd::string ToString(const BitMatrix& matrix, char one, char zero, bool addSpace, bool printAsCString)\n{\n\tstd::string result;\n\tresult.reserve((addSpace ? 2 : 1) * (matrix.width() * matrix.height()) + matrix.height());\n\tfor (int y = 0; y < matrix.height(); ++y) {\n\t\tBitArray row;\n\t\tmatrix.getRow(y, row);\n\t\tif (printAsCString)\n\t\t\tresult += '\"';\n\t\tfor (auto bit : row) {\n\t\t\tresult += bit ? one : zero;\n\t\t\tif (addSpace)\n\t\t\t\tresult += ' ';\n\t\t}\n\t\tif (printAsCString)\n\t\t\tresult += \"\\\\n\\\"\";\n\t\tresult += '\\n';\n\t}\n\treturn result;\n}\n\nBitMatrix ParseBitMatrix(const std::string& str, char one, bool expectSpace)\n{\n\tauto lineLength = str.find('\\n');\n\tif (lineLength == std::string::npos)\n\t\treturn {};\n\n\tint strStride = expectSpace ? 2 : 1;\n\tint height = static_cast<int>(str.length() \/ (lineLength + 1));\n\tint width = static_cast<int>(lineLength \/ strStride);\n\tBitMatrix mat(width, height);\n\tfor (int y = 0; y < height; ++y) {\n\t\tsize_t offset = y * (lineLength + 1);\n\t\tfor (int x = 0; x < width; ++x, offset += strStride) {\n\t\t\tif (str[offset] == one)\n\t\t\t\tmat.set(x, y);\n\t\t}\n\t}\n\treturn mat;\n}\n\nvoid SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quiteZone)\n{\n\tauto out = Inflate(matrix.copy(), 0, 0, quiteZone);\n\tstd::ofstream file(filename);\n\tfile << \"P1\\n\" << out.width() << ' ' << out.height() << '\\n';\n\tfile << ToString(out, '1', '0', true);\n}\n\n} \/\/ ZXing\n<|endoftext|>"} {"text":"<commit_before>#include \"style.h\"\n\n#include \"scene\/scene.h\"\n#include \"scene\/sceneLayer.h\"\n#include \"scene\/light.h\"\n#include \"tile\/tile.h\"\n#include \"gl\/vboMesh.h\"\n#include \"view\/view.h\"\n\nnamespace Tangram {\n\n Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :\n m_name(_name),\n m_blend(_blendMode),\n m_drawMode(_drawMode),\n m_contextLost(true) {\n}\n\nStyle::~Style() {}\n\nvoid Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {\n\n constructVertexLayout();\n constructShaderProgram();\n\n switch (m_lightingType) {\n case LightingType::vertex:\n m_shaderProgram->addSourceBlock(\"defines\", \"#define TANGRAM_LIGHTING_VERTEX\\n\", false);\n break;\n case LightingType::fragment:\n m_shaderProgram->addSourceBlock(\"defines\", \"#define TANGRAM_LIGHTING_FRAGMENT\\n\", false);\n break;\n default:\n break;\n }\n\n m_material->injectOnProgram(*m_shaderProgram);\n\n for (auto& light : _lights) {\n light->injectOnProgram(*m_shaderProgram);\n }\n\n}\n\nvoid Style::setMaterial(const std::shared_ptr<Material>& _material) {\n\n m_material = _material;\n\n}\n\nvoid Style::setLightingType(LightingType _type){\n\n m_lightingType = _type;\n\n}\n\nvoid Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const {\n\n auto& mesh = _tile.getMesh(*this);\n\n if (!mesh) {\n mesh.reset(newMesh());\n }\n\n switch (_feat.geometryType) {\n case GeometryType::points:\n for (auto& point : _feat.points) {\n buildPoint(point, _rule, _feat.props, *mesh, _tile);\n }\n break;\n case GeometryType::lines:\n for (auto& line : _feat.lines) {\n buildLine(line, _rule, _feat.props, *mesh, _tile);\n }\n break;\n case GeometryType::polygons:\n for (auto& polygon : _feat.polygons) {\n buildPolygon(polygon, _rule, _feat.props, *mesh, _tile);\n }\n break;\n default:\n break;\n }\n\n}\n\nvoid Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) {\n for (const auto& uniformPair : m_styleUniforms) {\n const auto& name = uniformPair.first;\n const auto& value = uniformPair.second;\n\n auto& textures = _scene.textures();\n\n if (value.is<std::string>()) {\n\n auto& tex = textures[value.get<std::string>()];\n\n tex->update(_textureUnit);\n tex->bind(_textureUnit);\n\n if (_update) {\n m_shaderProgram->setUniformi(name, _textureUnit);\n }\n\n _textureUnit++;\n\n } else {\n if (!_update) { continue; }\n\n if (value.is<bool>()) {\n m_shaderProgram->setUniformi(name, value.get<bool>());\n } else if(value.is<float>()) {\n m_shaderProgram->setUniformf(name, value.get<float>());\n } else if(value.is<glm::vec2>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec2>());\n } else if(value.is<glm::vec3>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec3>());\n } else if(value.is<glm::vec4>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec4>());\n } else {\n \/\/ TODO: Throw away uniform on loading!\n \/\/ none_type\n }\n }\n }\n}\n\nvoid Style::onBeginDrawFrame(const View& _view, Scene& _scene) {\n\n bool contextLost = glContextLost();\n\n m_material->setupProgram(*m_shaderProgram);\n\n \/\/ Set up lights\n for (const auto& light : _scene.lights()) {\n light->setupProgram(_view, *m_shaderProgram);\n }\n\n \/\/ Set Map Position\n if (m_dirtyViewport) {\n const auto& mapPos = _view.getPosition();\n m_shaderProgram->setUniformf(\"u_resolution\", _view.getWidth(), _view.getHeight());\n m_shaderProgram->setUniformf(\"u_map_position\", mapPos.x, mapPos.y, _view.getZoom());\n }\n\n setupShaderUniforms(0, contextLost, _scene);\n\n \/\/ Configure render state\n switch (m_blend) {\n case Blending::none:\n RenderState::blending(GL_FALSE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_TRUE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::add:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_ONE, GL_ONE);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::multiply:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::overlay:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_FALSE);\n break;\n case Blending::inlay:\n \/\/ TODO: inlay does not behave correctly for labels because they don't have a z position\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_TRUE);\n RenderState::depthWrite(GL_FALSE);\n break;\n default:\n break;\n }\n}\n\nvoid Style::onBeginBuildTile(Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::onEndBuildTile(Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nbool Style::glContextLost() {\n bool contextLost = m_contextLost;\n if (m_contextLost) {\n m_contextLost = false;\n }\n return contextLost;\n}\n\n}\n<commit_msg>Respect 'visible' draw rule<commit_after>#include \"style.h\"\n\n#include \"scene\/scene.h\"\n#include \"scene\/sceneLayer.h\"\n#include \"scene\/light.h\"\n#include \"scene\/styleParam.h\"\n#include \"tile\/tile.h\"\n#include \"gl\/vboMesh.h\"\n#include \"view\/view.h\"\n\nnamespace Tangram {\n\n Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :\n m_name(_name),\n m_blend(_blendMode),\n m_drawMode(_drawMode),\n m_contextLost(true) {\n}\n\nStyle::~Style() {}\n\nvoid Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {\n\n constructVertexLayout();\n constructShaderProgram();\n\n switch (m_lightingType) {\n case LightingType::vertex:\n m_shaderProgram->addSourceBlock(\"defines\", \"#define TANGRAM_LIGHTING_VERTEX\\n\", false);\n break;\n case LightingType::fragment:\n m_shaderProgram->addSourceBlock(\"defines\", \"#define TANGRAM_LIGHTING_FRAGMENT\\n\", false);\n break;\n default:\n break;\n }\n\n m_material->injectOnProgram(*m_shaderProgram);\n\n for (auto& light : _lights) {\n light->injectOnProgram(*m_shaderProgram);\n }\n\n}\n\nvoid Style::setMaterial(const std::shared_ptr<Material>& _material) {\n\n m_material = _material;\n\n}\n\nvoid Style::setLightingType(LightingType _type){\n\n m_lightingType = _type;\n\n}\n\nvoid Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const {\n\n bool visible;\n if (_rule.get(StyleParamKey::visible, visible) && !visible) {\n return;\n }\n\n auto& mesh = _tile.getMesh(*this);\n\n if (!mesh) {\n mesh.reset(newMesh());\n }\n\n switch (_feat.geometryType) {\n case GeometryType::points:\n for (auto& point : _feat.points) {\n buildPoint(point, _rule, _feat.props, *mesh, _tile);\n }\n break;\n case GeometryType::lines:\n for (auto& line : _feat.lines) {\n buildLine(line, _rule, _feat.props, *mesh, _tile);\n }\n break;\n case GeometryType::polygons:\n for (auto& polygon : _feat.polygons) {\n buildPolygon(polygon, _rule, _feat.props, *mesh, _tile);\n }\n break;\n default:\n break;\n }\n\n}\n\nvoid Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) {\n for (const auto& uniformPair : m_styleUniforms) {\n const auto& name = uniformPair.first;\n const auto& value = uniformPair.second;\n\n auto& textures = _scene.textures();\n\n if (value.is<std::string>()) {\n\n auto& tex = textures[value.get<std::string>()];\n\n tex->update(_textureUnit);\n tex->bind(_textureUnit);\n\n if (_update) {\n m_shaderProgram->setUniformi(name, _textureUnit);\n }\n\n _textureUnit++;\n\n } else {\n if (!_update) { continue; }\n\n if (value.is<bool>()) {\n m_shaderProgram->setUniformi(name, value.get<bool>());\n } else if(value.is<float>()) {\n m_shaderProgram->setUniformf(name, value.get<float>());\n } else if(value.is<glm::vec2>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec2>());\n } else if(value.is<glm::vec3>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec3>());\n } else if(value.is<glm::vec4>()) {\n m_shaderProgram->setUniformf(name, value.get<glm::vec4>());\n } else {\n \/\/ TODO: Throw away uniform on loading!\n \/\/ none_type\n }\n }\n }\n}\n\nvoid Style::onBeginDrawFrame(const View& _view, Scene& _scene) {\n\n bool contextLost = glContextLost();\n\n m_material->setupProgram(*m_shaderProgram);\n\n \/\/ Set up lights\n for (const auto& light : _scene.lights()) {\n light->setupProgram(_view, *m_shaderProgram);\n }\n\n \/\/ Set Map Position\n if (m_dirtyViewport) {\n const auto& mapPos = _view.getPosition();\n m_shaderProgram->setUniformf(\"u_resolution\", _view.getWidth(), _view.getHeight());\n m_shaderProgram->setUniformf(\"u_map_position\", mapPos.x, mapPos.y, _view.getZoom());\n }\n\n setupShaderUniforms(0, contextLost, _scene);\n\n \/\/ Configure render state\n switch (m_blend) {\n case Blending::none:\n RenderState::blending(GL_FALSE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_TRUE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::add:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_ONE, GL_ONE);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::multiply:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_TRUE);\n break;\n case Blending::overlay:\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_FALSE);\n RenderState::depthWrite(GL_FALSE);\n break;\n case Blending::inlay:\n \/\/ TODO: inlay does not behave correctly for labels because they don't have a z position\n RenderState::blending(GL_TRUE);\n RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n RenderState::depthTest(GL_TRUE);\n RenderState::depthWrite(GL_FALSE);\n break;\n default:\n break;\n }\n}\n\nvoid Style::onBeginBuildTile(Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::onEndBuildTile(Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nvoid Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {\n \/\/ No-op by default\n}\n\nbool Style::glContextLost() {\n bool contextLost = m_contextLost;\n if (m_contextLost) {\n m_contextLost = false;\n }\n return contextLost;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=-- Profilesummary.cpp - Profile summary computation ----------------------=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains support for computing profile summary data.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Metadata.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/ProfileData\/InstrProf.h\"\n#include \"llvm\/ProfileData\/ProfileCommon.h\"\n#include \"llvm\/ProfileData\/SampleProf.h\"\n#include \"llvm\/Support\/Casting.h\"\n\nusing namespace llvm;\n\n\/\/ A set of cutoff values. Each value, when divided by ProfileSummary::Scale\n\/\/ (which is 1000000) is a desired percentile of total counts.\nconst std::vector<uint32_t> ProfileSummary::DefaultCutoffs(\n {10000, \/* 1% *\/\n 100000, \/* 10% *\/\n 200000, 300000, 400000, 500000, 600000, 500000, 600000, 700000, 800000,\n 900000, 950000, 990000, 999000, 999900, 999990, 999999});\nconst char *ProfileSummary::KindStr[2] = {\"InstrProf\", \"SampleProfile\"};\n\nvoid InstrProfSummary::addRecord(const InstrProfRecord &R) {\n addEntryCount(R.Counts[0]);\n for (size_t I = 1, E = R.Counts.size(); I < E; ++I)\n addInternalCount(R.Counts[I]);\n}\n\n\/\/ To compute the detailed summary, we consider each line containing samples as\n\/\/ equivalent to a block with a count in the instrumented profile.\nvoid SampleProfileSummary::addRecord(const sampleprof::FunctionSamples &FS) {\n NumFunctions++;\n if (FS.getHeadSamples() > MaxFunctionCount)\n MaxFunctionCount = FS.getHeadSamples();\n for (const auto &I : FS.getBodySamples())\n addCount(I.second.getSamples());\n}\n\n\/\/ The argument to this method is a vector of cutoff percentages and the return\n\/\/ value is a vector of (Cutoff, MinCount, NumCounts) triplets.\nvoid ProfileSummary::computeDetailedSummary() {\n if (DetailedSummaryCutoffs.empty())\n return;\n auto Iter = CountFrequencies.begin();\n auto End = CountFrequencies.end();\n std::sort(DetailedSummaryCutoffs.begin(), DetailedSummaryCutoffs.end());\n\n uint32_t CountsSeen = 0;\n uint64_t CurrSum = 0, Count = 0;\n\n for (uint32_t Cutoff : DetailedSummaryCutoffs) {\n assert(Cutoff <= 999999);\n APInt Temp(128, TotalCount);\n APInt N(128, Cutoff);\n APInt D(128, ProfileSummary::Scale);\n Temp *= N;\n Temp = Temp.sdiv(D);\n uint64_t DesiredCount = Temp.getZExtValue();\n assert(DesiredCount <= TotalCount);\n while (CurrSum < DesiredCount && Iter != End) {\n Count = Iter->first;\n uint32_t Freq = Iter->second;\n CurrSum += (Count * Freq);\n CountsSeen += Freq;\n Iter++;\n }\n assert(CurrSum >= DesiredCount);\n ProfileSummaryEntry PSE = {Cutoff, Count, CountsSeen};\n DetailedSummary.push_back(PSE);\n }\n}\n\n\/\/ Returns true if the function is a hot function.\nbool ProfileSummary::isFunctionHot(const Function *F) {\n \/\/ FIXME: update when summary data is stored in module's metadata.\n return false;\n}\n\n\/\/ Returns true if the function is a cold function.\nbool ProfileSummary::isFunctionUnlikely(const Function *F) {\n if (F->hasFnAttribute(Attribute::Cold)) {\n return true;\n }\n if (!F->getEntryCount()) {\n return false;\n }\n \/\/ FIXME: update when summary data is stored in module's metadata.\n return (*F->getEntryCount()) == 0;\n}\n\nInstrProfSummary::InstrProfSummary(const IndexedInstrProf::Summary &S)\n : ProfileSummary(PSK_Instr),\n MaxInternalBlockCount(\n S.get(IndexedInstrProf::Summary::MaxInternalBlockCount)) {\n\n TotalCount = S.get(IndexedInstrProf::Summary::TotalBlockCount);\n MaxCount = S.get(IndexedInstrProf::Summary::MaxBlockCount);\n MaxFunctionCount = S.get(IndexedInstrProf::Summary::MaxFunctionCount);\n NumCounts = S.get(IndexedInstrProf::Summary::TotalNumBlocks);\n NumFunctions = S.get(IndexedInstrProf::Summary::TotalNumFunctions);\n\n for (unsigned I = 0; I < S.NumCutoffEntries; I++) {\n const IndexedInstrProf::Summary::Entry &Ent = S.getEntry(I);\n DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,\n Ent.NumBlocks);\n }\n}\n\nvoid InstrProfSummary::addEntryCount(uint64_t Count) {\n addCount(Count);\n NumFunctions++;\n if (Count > MaxFunctionCount)\n MaxFunctionCount = Count;\n}\n\nvoid InstrProfSummary::addInternalCount(uint64_t Count) {\n addCount(Count);\n if (Count > MaxInternalBlockCount)\n MaxInternalBlockCount = Count;\n}\n\n\/\/ Return an MDTuple with two elements. The first element is a string Key and\n\/\/ the second is a uint64_t Value.\nstatic Metadata *getKeyValMD(LLVMContext &Context, const char *Key,\n uint64_t Val) {\n Type *Int64Ty = Type::getInt64Ty(Context);\n Metadata *Ops[2] = {MDString::get(Context, Key),\n ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Val))};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ Return an MDTuple with two elements. The first element is a string Key and\n\/\/ the second is a string Value.\nstatic Metadata *getKeyValMD(LLVMContext &Context, const char *Key,\n const char *Val) {\n Metadata *Ops[2] = {MDString::get(Context, Key), MDString::get(Context, Val)};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ This returns an MDTuple representing the detiled summary. The tuple has two\n\/\/ elements: a string \"DetailedSummary\" and an MDTuple representing the value\n\/\/ of the detailed summary. Each element of this tuple is again an MDTuple whose\n\/\/ elements are the (Cutoff, MinCount, NumCounts) triplet of the\n\/\/ DetailedSummaryEntry.\nMetadata *ProfileSummary::getDetailedSummaryMD(LLVMContext &Context) {\n std::vector<Metadata *> Entries;\n Type *Int32Ty = Type::getInt32Ty(Context);\n Type *Int64Ty = Type::getInt64Ty(Context);\n for (auto &Entry : DetailedSummary) {\n Metadata *EntryMD[3] = {\n ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.Cutoff)),\n ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Entry.MinCount)),\n ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.NumCounts))};\n Entries.push_back(MDTuple::get(Context, EntryMD));\n }\n Metadata *Ops[2] = {MDString::get(Context, \"DetailedSummary\"),\n MDTuple::get(Context, Entries)};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ This returns an MDTuple representing this ProfileSummary object. The first\n\/\/ entry of this tuple is another MDTuple of two elements: a string\n\/\/ \"ProfileFormat\" and a string representing the format (\"InstrProf\" or\n\/\/ \"SampleProfile\"). The rest of the elements of the outer MDTuple are specific\n\/\/ to the kind of profile summary as returned by getFormatSpecificMD.\nMetadata *ProfileSummary::getMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n Components.push_back(getKeyValMD(Context, \"ProfileFormat\", getKindStr()));\n std::vector<Metadata *> Res = getFormatSpecificMD(Context);\n Components.insert(Components.end(), Res.begin(), Res.end());\n return MDTuple::get(Context, Components);\n}\n\n\/\/ Returns a vector of MDTuples specific to InstrProfSummary. The first six\n\/\/ elements of this vector are (Key, Val) pairs of the six scalar fields of\n\/\/ InstrProfSummary (TotalCount, MaxBlockCount, MaxInternalBlockCount,\n\/\/ MaxFunctionCount, NumBlocks, NumFunctions). The last element of this vector\n\/\/ is an MDTuple returned by getDetailedSummaryMD.\nstd::vector<Metadata *>\nInstrProfSummary::getFormatSpecificMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n\n Components.push_back(getKeyValMD(Context, \"TotalCount\", getTotalCount()));\n Components.push_back(\n getKeyValMD(Context, \"MaxBlockCount\", getMaxBlockCount()));\n Components.push_back(getKeyValMD(Context, \"MaxInternalBlockCount\",\n getMaxInternalBlockCount()));\n Components.push_back(\n getKeyValMD(Context, \"MaxFunctionCount\", getMaxFunctionCount()));\n Components.push_back(getKeyValMD(Context, \"NumBlocks\", getNumBlocks()));\n Components.push_back(getKeyValMD(Context, \"NumFunctions\", getNumFunctions()));\n\n Components.push_back(getDetailedSummaryMD(Context));\n return Components;\n}\n\nstd::vector<Metadata *>\nSampleProfileSummary::getFormatSpecificMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n\n Components.push_back(getKeyValMD(Context, \"TotalSamples\", getTotalSamples()));\n Components.push_back(\n getKeyValMD(Context, \"MaxSamplesPerLine\", getMaxSamplesPerLine()));\n Components.push_back(\n getKeyValMD(Context, \"MaxFunctionCount\", getMaxFunctionCount()));\n Components.push_back(\n getKeyValMD(Context, \"NumLinesWithSamples\", getNumLinesWithSamples()));\n Components.push_back(getKeyValMD(Context, \"NumFunctions\", NumFunctions));\n\n Components.push_back(getDetailedSummaryMD(Context));\n return Components;\n}\n\n\/\/ Parse an MDTuple representing (Key, Val) pair.\nstatic bool getVal(MDTuple *MD, const char *Key, uint64_t &Val) {\n if (!MD)\n return false;\n if (MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n ConstantAsMetadata *ValMD = dyn_cast<ConstantAsMetadata>(MD->getOperand(1));\n if (!KeyMD || !ValMD)\n return false;\n if (!KeyMD->getString().equals(Key))\n return false;\n Val = cast<ConstantInt>(ValMD->getValue())->getZExtValue();\n return true;\n}\n\n\/\/ Check if an MDTuple represents a (Key, Val) pair.\nstatic bool isKeyValuePair(MDTuple *MD, const char *Key, const char *Val) {\n if (!MD || MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n MDString *ValMD = dyn_cast<MDString>(MD->getOperand(1));\n if (!KeyMD || !ValMD)\n return false;\n if (!KeyMD->getString().equals(Key) || !ValMD->getString().equals(Val))\n return false;\n return true;\n}\n\n\/\/ Parse an MDTuple representing detailed summary.\nstatic bool getSummaryFromMD(MDTuple *MD, SummaryEntryVector &Summary) {\n if (!MD || MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n if (!KeyMD || !KeyMD->getString().equals(\"DetailedSummary\"))\n return false;\n MDTuple *EntriesMD = dyn_cast<MDTuple>(MD->getOperand(1));\n if (!EntriesMD)\n return false;\n for (auto &&MDOp : EntriesMD->operands()) {\n MDTuple *EntryMD = dyn_cast<MDTuple>(MDOp);\n if (!EntryMD || EntryMD->getNumOperands() != 3)\n return false;\n ConstantAsMetadata *Op0 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(0));\n ConstantAsMetadata *Op1 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(1));\n ConstantAsMetadata *Op2 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(2));\n\n if (!Op0 || !Op1 || !Op2)\n return false;\n Summary.emplace_back(cast<ConstantInt>(Op0->getValue())->getZExtValue(),\n cast<ConstantInt>(Op1->getValue())->getZExtValue(),\n cast<ConstantInt>(Op2->getValue())->getZExtValue());\n }\n return true;\n}\n\n\/\/ Parse an MDTuple representing an InstrProfSummary object.\nstatic ProfileSummary *getInstrProfSummaryFromMD(MDTuple *Tuple) {\n uint64_t NumBlocks, TotalCount, NumFunctions, MaxFunctionCount, MaxBlockCount,\n MaxInternalBlockCount;\n SummaryEntryVector Summary;\n\n if (Tuple->getNumOperands() != 8)\n return nullptr;\n\n \/\/ Skip operand 0 which has been already parsed in the caller\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), \"TotalCount\",\n TotalCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), \"MaxBlockCount\",\n MaxBlockCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), \"MaxInternalBlockCount\",\n MaxInternalBlockCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), \"MaxFunctionCount\",\n MaxFunctionCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), \"NumBlocks\", NumBlocks))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(6)), \"NumFunctions\",\n NumFunctions))\n return nullptr;\n if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(7)), Summary))\n return nullptr;\n return new InstrProfSummary(TotalCount, MaxBlockCount, MaxInternalBlockCount,\n MaxFunctionCount, NumBlocks, NumFunctions,\n Summary);\n}\n\n\/\/ Parse an MDTuple representing a SampleProfileSummary object.\nstatic ProfileSummary *getSampleProfileSummaryFromMD(MDTuple *Tuple) {\n uint64_t TotalSamples, MaxSamplesPerLine, MaxFunctionCount,\n NumLinesWithSamples, NumFunctions;\n SummaryEntryVector Summary;\n\n if (Tuple->getNumOperands() != 7)\n return nullptr;\n\n \/\/ Skip operand 0 which has been already parsed in the caller\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), \"TotalSamples\",\n TotalSamples))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), \"MaxSamplesPerLine\",\n MaxSamplesPerLine))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), \"MaxFunctionCount\",\n MaxFunctionCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), \"NumLinesWithSamples\",\n NumLinesWithSamples))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), \"NumFunctions\",\n NumFunctions))\n return nullptr;\n if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(6)), Summary))\n return nullptr;\n return new SampleProfileSummary(TotalSamples, MaxSamplesPerLine,\n MaxFunctionCount, NumLinesWithSamples,\n NumFunctions, Summary);\n}\n\nProfileSummary *ProfileSummary::getFromMD(Metadata *MD) {\n if (!isa<MDTuple>(MD))\n return nullptr;\n MDTuple *Tuple = cast<MDTuple>(MD);\n auto &FormatMD = Tuple->getOperand(0);\n if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), \"ProfileFormat\",\n \"SampleProfile\"))\n return getSampleProfileSummaryFromMD(Tuple);\n else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), \"ProfileFormat\",\n \"InstrProf\"))\n return getInstrProfSummaryFromMD(Tuple);\n else\n return nullptr;\n}\n<commit_msg>Add a note about the \"entry count\" used the profile summary<commit_after>\/\/=-- Profilesummary.cpp - Profile summary computation ----------------------=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains support for computing profile summary data.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Metadata.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/ProfileData\/InstrProf.h\"\n#include \"llvm\/ProfileData\/ProfileCommon.h\"\n#include \"llvm\/ProfileData\/SampleProf.h\"\n#include \"llvm\/Support\/Casting.h\"\n\nusing namespace llvm;\n\n\/\/ A set of cutoff values. Each value, when divided by ProfileSummary::Scale\n\/\/ (which is 1000000) is a desired percentile of total counts.\nconst std::vector<uint32_t> ProfileSummary::DefaultCutoffs(\n {10000, \/* 1% *\/\n 100000, \/* 10% *\/\n 200000, 300000, 400000, 500000, 600000, 500000, 600000, 700000, 800000,\n 900000, 950000, 990000, 999000, 999900, 999990, 999999});\nconst char *ProfileSummary::KindStr[2] = {\"InstrProf\", \"SampleProfile\"};\n\nvoid InstrProfSummary::addRecord(const InstrProfRecord &R) {\n \/\/ The first counter is not necessarily an entry count for IR\n \/\/ instrumentation profiles.\n \/\/ Eventually MaxFunctionCount will become obsolete and this can be\n \/\/ removed.\n addEntryCount(R.Counts[0]);\n for (size_t I = 1, E = R.Counts.size(); I < E; ++I)\n addInternalCount(R.Counts[I]);\n}\n\n\/\/ To compute the detailed summary, we consider each line containing samples as\n\/\/ equivalent to a block with a count in the instrumented profile.\nvoid SampleProfileSummary::addRecord(const sampleprof::FunctionSamples &FS) {\n NumFunctions++;\n if (FS.getHeadSamples() > MaxFunctionCount)\n MaxFunctionCount = FS.getHeadSamples();\n for (const auto &I : FS.getBodySamples())\n addCount(I.second.getSamples());\n}\n\n\/\/ The argument to this method is a vector of cutoff percentages and the return\n\/\/ value is a vector of (Cutoff, MinCount, NumCounts) triplets.\nvoid ProfileSummary::computeDetailedSummary() {\n if (DetailedSummaryCutoffs.empty())\n return;\n auto Iter = CountFrequencies.begin();\n auto End = CountFrequencies.end();\n std::sort(DetailedSummaryCutoffs.begin(), DetailedSummaryCutoffs.end());\n\n uint32_t CountsSeen = 0;\n uint64_t CurrSum = 0, Count = 0;\n\n for (uint32_t Cutoff : DetailedSummaryCutoffs) {\n assert(Cutoff <= 999999);\n APInt Temp(128, TotalCount);\n APInt N(128, Cutoff);\n APInt D(128, ProfileSummary::Scale);\n Temp *= N;\n Temp = Temp.sdiv(D);\n uint64_t DesiredCount = Temp.getZExtValue();\n assert(DesiredCount <= TotalCount);\n while (CurrSum < DesiredCount && Iter != End) {\n Count = Iter->first;\n uint32_t Freq = Iter->second;\n CurrSum += (Count * Freq);\n CountsSeen += Freq;\n Iter++;\n }\n assert(CurrSum >= DesiredCount);\n ProfileSummaryEntry PSE = {Cutoff, Count, CountsSeen};\n DetailedSummary.push_back(PSE);\n }\n}\n\n\/\/ Returns true if the function is a hot function.\nbool ProfileSummary::isFunctionHot(const Function *F) {\n \/\/ FIXME: update when summary data is stored in module's metadata.\n return false;\n}\n\n\/\/ Returns true if the function is a cold function.\nbool ProfileSummary::isFunctionUnlikely(const Function *F) {\n if (F->hasFnAttribute(Attribute::Cold)) {\n return true;\n }\n if (!F->getEntryCount()) {\n return false;\n }\n \/\/ FIXME: update when summary data is stored in module's metadata.\n return (*F->getEntryCount()) == 0;\n}\n\nInstrProfSummary::InstrProfSummary(const IndexedInstrProf::Summary &S)\n : ProfileSummary(PSK_Instr),\n MaxInternalBlockCount(\n S.get(IndexedInstrProf::Summary::MaxInternalBlockCount)) {\n\n TotalCount = S.get(IndexedInstrProf::Summary::TotalBlockCount);\n MaxCount = S.get(IndexedInstrProf::Summary::MaxBlockCount);\n MaxFunctionCount = S.get(IndexedInstrProf::Summary::MaxFunctionCount);\n NumCounts = S.get(IndexedInstrProf::Summary::TotalNumBlocks);\n NumFunctions = S.get(IndexedInstrProf::Summary::TotalNumFunctions);\n\n for (unsigned I = 0; I < S.NumCutoffEntries; I++) {\n const IndexedInstrProf::Summary::Entry &Ent = S.getEntry(I);\n DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,\n Ent.NumBlocks);\n }\n}\n\nvoid InstrProfSummary::addEntryCount(uint64_t Count) {\n addCount(Count);\n NumFunctions++;\n if (Count > MaxFunctionCount)\n MaxFunctionCount = Count;\n}\n\nvoid InstrProfSummary::addInternalCount(uint64_t Count) {\n addCount(Count);\n if (Count > MaxInternalBlockCount)\n MaxInternalBlockCount = Count;\n}\n\n\/\/ Return an MDTuple with two elements. The first element is a string Key and\n\/\/ the second is a uint64_t Value.\nstatic Metadata *getKeyValMD(LLVMContext &Context, const char *Key,\n uint64_t Val) {\n Type *Int64Ty = Type::getInt64Ty(Context);\n Metadata *Ops[2] = {MDString::get(Context, Key),\n ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Val))};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ Return an MDTuple with two elements. The first element is a string Key and\n\/\/ the second is a string Value.\nstatic Metadata *getKeyValMD(LLVMContext &Context, const char *Key,\n const char *Val) {\n Metadata *Ops[2] = {MDString::get(Context, Key), MDString::get(Context, Val)};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ This returns an MDTuple representing the detiled summary. The tuple has two\n\/\/ elements: a string \"DetailedSummary\" and an MDTuple representing the value\n\/\/ of the detailed summary. Each element of this tuple is again an MDTuple whose\n\/\/ elements are the (Cutoff, MinCount, NumCounts) triplet of the\n\/\/ DetailedSummaryEntry.\nMetadata *ProfileSummary::getDetailedSummaryMD(LLVMContext &Context) {\n std::vector<Metadata *> Entries;\n Type *Int32Ty = Type::getInt32Ty(Context);\n Type *Int64Ty = Type::getInt64Ty(Context);\n for (auto &Entry : DetailedSummary) {\n Metadata *EntryMD[3] = {\n ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.Cutoff)),\n ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Entry.MinCount)),\n ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.NumCounts))};\n Entries.push_back(MDTuple::get(Context, EntryMD));\n }\n Metadata *Ops[2] = {MDString::get(Context, \"DetailedSummary\"),\n MDTuple::get(Context, Entries)};\n return MDTuple::get(Context, Ops);\n}\n\n\/\/ This returns an MDTuple representing this ProfileSummary object. The first\n\/\/ entry of this tuple is another MDTuple of two elements: a string\n\/\/ \"ProfileFormat\" and a string representing the format (\"InstrProf\" or\n\/\/ \"SampleProfile\"). The rest of the elements of the outer MDTuple are specific\n\/\/ to the kind of profile summary as returned by getFormatSpecificMD.\nMetadata *ProfileSummary::getMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n Components.push_back(getKeyValMD(Context, \"ProfileFormat\", getKindStr()));\n std::vector<Metadata *> Res = getFormatSpecificMD(Context);\n Components.insert(Components.end(), Res.begin(), Res.end());\n return MDTuple::get(Context, Components);\n}\n\n\/\/ Returns a vector of MDTuples specific to InstrProfSummary. The first six\n\/\/ elements of this vector are (Key, Val) pairs of the six scalar fields of\n\/\/ InstrProfSummary (TotalCount, MaxBlockCount, MaxInternalBlockCount,\n\/\/ MaxFunctionCount, NumBlocks, NumFunctions). The last element of this vector\n\/\/ is an MDTuple returned by getDetailedSummaryMD.\nstd::vector<Metadata *>\nInstrProfSummary::getFormatSpecificMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n\n Components.push_back(getKeyValMD(Context, \"TotalCount\", getTotalCount()));\n Components.push_back(\n getKeyValMD(Context, \"MaxBlockCount\", getMaxBlockCount()));\n Components.push_back(getKeyValMD(Context, \"MaxInternalBlockCount\",\n getMaxInternalBlockCount()));\n Components.push_back(\n getKeyValMD(Context, \"MaxFunctionCount\", getMaxFunctionCount()));\n Components.push_back(getKeyValMD(Context, \"NumBlocks\", getNumBlocks()));\n Components.push_back(getKeyValMD(Context, \"NumFunctions\", getNumFunctions()));\n\n Components.push_back(getDetailedSummaryMD(Context));\n return Components;\n}\n\nstd::vector<Metadata *>\nSampleProfileSummary::getFormatSpecificMD(LLVMContext &Context) {\n std::vector<Metadata *> Components;\n\n Components.push_back(getKeyValMD(Context, \"TotalSamples\", getTotalSamples()));\n Components.push_back(\n getKeyValMD(Context, \"MaxSamplesPerLine\", getMaxSamplesPerLine()));\n Components.push_back(\n getKeyValMD(Context, \"MaxFunctionCount\", getMaxFunctionCount()));\n Components.push_back(\n getKeyValMD(Context, \"NumLinesWithSamples\", getNumLinesWithSamples()));\n Components.push_back(getKeyValMD(Context, \"NumFunctions\", NumFunctions));\n\n Components.push_back(getDetailedSummaryMD(Context));\n return Components;\n}\n\n\/\/ Parse an MDTuple representing (Key, Val) pair.\nstatic bool getVal(MDTuple *MD, const char *Key, uint64_t &Val) {\n if (!MD)\n return false;\n if (MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n ConstantAsMetadata *ValMD = dyn_cast<ConstantAsMetadata>(MD->getOperand(1));\n if (!KeyMD || !ValMD)\n return false;\n if (!KeyMD->getString().equals(Key))\n return false;\n Val = cast<ConstantInt>(ValMD->getValue())->getZExtValue();\n return true;\n}\n\n\/\/ Check if an MDTuple represents a (Key, Val) pair.\nstatic bool isKeyValuePair(MDTuple *MD, const char *Key, const char *Val) {\n if (!MD || MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n MDString *ValMD = dyn_cast<MDString>(MD->getOperand(1));\n if (!KeyMD || !ValMD)\n return false;\n if (!KeyMD->getString().equals(Key) || !ValMD->getString().equals(Val))\n return false;\n return true;\n}\n\n\/\/ Parse an MDTuple representing detailed summary.\nstatic bool getSummaryFromMD(MDTuple *MD, SummaryEntryVector &Summary) {\n if (!MD || MD->getNumOperands() != 2)\n return false;\n MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));\n if (!KeyMD || !KeyMD->getString().equals(\"DetailedSummary\"))\n return false;\n MDTuple *EntriesMD = dyn_cast<MDTuple>(MD->getOperand(1));\n if (!EntriesMD)\n return false;\n for (auto &&MDOp : EntriesMD->operands()) {\n MDTuple *EntryMD = dyn_cast<MDTuple>(MDOp);\n if (!EntryMD || EntryMD->getNumOperands() != 3)\n return false;\n ConstantAsMetadata *Op0 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(0));\n ConstantAsMetadata *Op1 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(1));\n ConstantAsMetadata *Op2 =\n dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(2));\n\n if (!Op0 || !Op1 || !Op2)\n return false;\n Summary.emplace_back(cast<ConstantInt>(Op0->getValue())->getZExtValue(),\n cast<ConstantInt>(Op1->getValue())->getZExtValue(),\n cast<ConstantInt>(Op2->getValue())->getZExtValue());\n }\n return true;\n}\n\n\/\/ Parse an MDTuple representing an InstrProfSummary object.\nstatic ProfileSummary *getInstrProfSummaryFromMD(MDTuple *Tuple) {\n uint64_t NumBlocks, TotalCount, NumFunctions, MaxFunctionCount, MaxBlockCount,\n MaxInternalBlockCount;\n SummaryEntryVector Summary;\n\n if (Tuple->getNumOperands() != 8)\n return nullptr;\n\n \/\/ Skip operand 0 which has been already parsed in the caller\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), \"TotalCount\",\n TotalCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), \"MaxBlockCount\",\n MaxBlockCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), \"MaxInternalBlockCount\",\n MaxInternalBlockCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), \"MaxFunctionCount\",\n MaxFunctionCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), \"NumBlocks\", NumBlocks))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(6)), \"NumFunctions\",\n NumFunctions))\n return nullptr;\n if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(7)), Summary))\n return nullptr;\n return new InstrProfSummary(TotalCount, MaxBlockCount, MaxInternalBlockCount,\n MaxFunctionCount, NumBlocks, NumFunctions,\n Summary);\n}\n\n\/\/ Parse an MDTuple representing a SampleProfileSummary object.\nstatic ProfileSummary *getSampleProfileSummaryFromMD(MDTuple *Tuple) {\n uint64_t TotalSamples, MaxSamplesPerLine, MaxFunctionCount,\n NumLinesWithSamples, NumFunctions;\n SummaryEntryVector Summary;\n\n if (Tuple->getNumOperands() != 7)\n return nullptr;\n\n \/\/ Skip operand 0 which has been already parsed in the caller\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), \"TotalSamples\",\n TotalSamples))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), \"MaxSamplesPerLine\",\n MaxSamplesPerLine))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), \"MaxFunctionCount\",\n MaxFunctionCount))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), \"NumLinesWithSamples\",\n NumLinesWithSamples))\n return nullptr;\n if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), \"NumFunctions\",\n NumFunctions))\n return nullptr;\n if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(6)), Summary))\n return nullptr;\n return new SampleProfileSummary(TotalSamples, MaxSamplesPerLine,\n MaxFunctionCount, NumLinesWithSamples,\n NumFunctions, Summary);\n}\n\nProfileSummary *ProfileSummary::getFromMD(Metadata *MD) {\n if (!isa<MDTuple>(MD))\n return nullptr;\n MDTuple *Tuple = cast<MDTuple>(MD);\n auto &FormatMD = Tuple->getOperand(0);\n if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), \"ProfileFormat\",\n \"SampleProfile\"))\n return getSampleProfileSummaryFromMD(Tuple);\n else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), \"ProfileFormat\",\n \"InstrProf\"))\n return getInstrProfSummaryFromMD(Tuple);\n else\n return nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STOCHASTIC_NODE\n#define STOCHASTIC_NODE\n#include <memory>\n#include <vector>\n#include <future>\n#include <numeric>\n#include <map>\n#include \"error_handler.hpp\"\n#include \"mcmc_traits.hpp\"\n#include \"arms.hpp\"\n#include \"slicer.hpp\"\n#include \"base_urand.hpp\"\n#include \"discrete_sample.hpp\"\n#include \"continuous_sample.hpp\"\n#include \"node.hpp\"\n#include \"ptransform.hpp\"\nnamespace mcmc_utilities\n{\n template <typename T,template <typename TE> class T_vector>\n class stochastic_node\n :public node<T,T_vector>\n {\n private:\n T_vector<T> v;\/\/store current value(s) of this node\n T_vector<int> observed;\n size_t current_idx;\n public:\n stochastic_node(size_t nparents,const T_vector<T>& v_)\n :node<T,T_vector>(nparents,get_size(v_)),\n v{v_},observed(get_size(v_)),current_idx(0)\n {\n }\n\n stochastic_node(size_t nparents,T v_)\n :node<T,T_vector>(nparents,1),\n v(1),observed(get_size(v)),current_idx(0)\n {\n \/\/v[0]=v_;\n set_element(v,0,v_);\n }\n \n\n stochastic_node()=delete;\n stochastic_node(const stochastic_node<T,T_vector>& )=delete;\n stochastic_node<T,T_vector>& operator=(const stochastic_node<T,T_vector>&)=delete;\n public:\n bool is_observed(size_t n)const\n {\n \/\/return observed[n]!=0;\n return get_element(observed,n)!=0;\n }\n\n void set_observed(size_t n,bool b)\n {\n \/\/observed[n]=b?1:0;\n set_element(observed,n,b?1:0);\n }\n\n size_t num_of_observed()const\n {\n return std::accumulate(std::begin(observed),\n\t\t\t std::end(observed),\n\t\t\t 0,\n\t\t\t [](int x1,int x2){return x1+x2;});\n }\n\n size_t num_of_unobserved()const\n {\n return this->num_of_dims()-num_of_observed();\n }\n \n T log_posterior_prob()const\n {\n return log_prob()+this->log_likelihood();\n }\n\n T eval_log(const T& x)const\n {\n set_element(const_cast<stochastic_node*>(this)->v,current_idx,x);\n return log_posterior_prob();\n }\n\n void set_current_idx(size_t i)\n {\n current_idx=i;\n }\n\n size_t get_current_idx()const\n {\n return current_idx;\n }\n\n T log_likelihood()const\n {\n T result=static_cast<T>(0);\n auto& ss=this->get_all_stochastic_children();\n T_vector<T> results(get_size(ss));\n \/\/\/\/followings are the current implementation of computing the log likelihood\n \/\/\n#if defined USE_STD_TRANSFORM\n std::transform(std::begin(ss),std::end(ss),std::begin(results),[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();});\n#elif defined USE_TRANSFORM_THREAD\n pvec_transform_thread(ss,results,[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();},10);\n#else\n pvec_transform_omp(ss,results,[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();},10);\n#endif\n result=std::accumulate(std::begin(results),std::end(results),static_cast<T>(0));\n return result;\n }\n \n T log_prob()const\n {\n return do_log_prob();\n }\n\n void set_value(size_t idx,const T& v_)\n {\n this->set_initialized(idx,true);\n set_element(v,idx,this->regulate(idx,v_));\n }\n\n T regulate(size_t idx,const T& x)const\n {\n return do_regulate(idx,x);\n }\n\n\n\n public:\n void sample(base_urand<T>& urand)\n {\n do_sample(urand);\n }\n\n public:\n void default_sample(base_urand<T>& urand)\n {\n for(size_t i=0;i<this->num_of_dims();++i)\n\t{\n\t if(is_observed(i))\n\t {\n\t continue;\n\t }\n\t this->set_current_idx(i);\n\t T xprev=this->value(i);\n\t std::pair<T,T> xrange(this->do_var_range());\n\t \n\t \/\/xprev=xprev<xrange.first?xrange.first:xprev;\n\t \/\/xprev=xprev>xrange.second?xrange.second:xprev;\n\t \n\t if(xprev<xrange.first||xprev>xrange.second)\n\t {\n\t this->init_value(i);\n\t xprev=this->value(i);\n\t }\n\t \n\t \/\/arms_simple(*this,xprev,xsamp,dometrop(),rnd);\n\t \n\t if(is_continuous(i))\n\t {\n\t T_vector<T> init_x(this->do_init_points());\n\t xprev=continuous_sample([&](const T& x){return this->eval_log(x);},xrange,init_x, xprev,1,urand);\n\t }\n\t else\n\t {\n\t T_vector<T> candidate_points(this->do_candidate_points());\n\t xprev=discrete_sample([&](const T& x){return this->eval_log(x);},xrange, candidate_points, xprev,10,urand);\n\t }\n\t \n\t this->set_value(i,xprev);\n\t}\n }\n \n private:\n virtual void do_sample(base_urand<T>& urand)\n {\n default_sample(urand);\n }\n \n virtual T do_log_prob()const=0;\n T do_value(size_t idx)const override final\n {\n \/\/return v[idx];\n return get_element(v,idx);\n }\n\n \n void do_connect_to_parent(node<T,T_vector>* rhs,size_t n,size_t idx) override\n {\n \/\/set_element(this->parents,n,std::make_pair(rhs,idx));\n this->set_parent(n,std::make_pair(rhs,idx));\n rhs->add_stochastic_child(this);\n }\n\n virtual T do_regulate(size_t idx,const T& x)const\n {\n return x;\n }\n\n virtual bool is_continuous(size_t idx)const=0;\n\n virtual std::pair<T,T> do_var_range()const=0;\n\n virtual T_vector<T> do_init_points()const\n {\n T_vector<T> result(5);\n std::pair<T,T> xrange(do_var_range());\n T xl=xrange.first,xr=xrange.second;\n for(size_t n=0;n<get_size(result);++n)\n\t{\t \n\t set_element(result,n,xl+(xr-xl)\/(get_size(result)+1)*(n+1));\n\t}\n return result;\n }\n\n virtual T_vector<T> do_candidate_points()const\n {\n return T_vector<T>();\n }\n }; \n}\n\n\n#endif\n<commit_msg>\t修改: core\/stochastic_node.hpp<commit_after>#ifndef STOCHASTIC_NODE\n#define STOCHASTIC_NODE\n#include <memory>\n#include <vector>\n#include <future>\n#include <numeric>\n#include <map>\n#include \"error_handler.hpp\"\n#include \"mcmc_traits.hpp\"\n#include \"arms.hpp\"\n#include \"slicer.hpp\"\n#include \"base_urand.hpp\"\n#include \"discrete_sample.hpp\"\n#include \"continuous_sample.hpp\"\n#include \"node.hpp\"\n#include \"ptransform.hpp\"\nnamespace mcmc_utilities\n{\n template <typename T,template <typename TE> class T_vector>\n class stochastic_node\n :public node<T,T_vector>\n {\n private:\n T_vector<T> v;\/\/store current value(s) of this node\n T_vector<int> observed;\n size_t current_idx;\n public:\n stochastic_node(size_t nparents,const T_vector<T>& v_)\n :node<T,T_vector>(nparents,get_size(v_)),\n v{v_},observed(get_size(v_)),current_idx(0)\n {\n }\n\n stochastic_node(size_t nparents,T v_)\n :node<T,T_vector>(nparents,1),\n v(1),observed(get_size(v)),current_idx(0)\n {\n \/\/v[0]=v_;\n set_element(v,0,v_);\n }\n \n\n stochastic_node()=delete;\n stochastic_node(const stochastic_node<T,T_vector>& )=delete;\n stochastic_node<T,T_vector>& operator=(const stochastic_node<T,T_vector>&)=delete;\n public:\n bool is_observed(size_t n)const\n {\n \/\/return observed[n]!=0;\n return get_element(observed,n)!=0;\n }\n\n void set_observed(size_t n,bool b)\n {\n \/\/observed[n]=b?1:0;\n set_element(observed,n,b?1:0);\n }\n\n size_t num_of_observed()const\n {\n return std::accumulate(std::begin(observed),\n\t\t\t std::end(observed),\n\t\t\t 0,\n\t\t\t [](int x1,int x2){return x1+x2;});\n }\n\n size_t num_of_unobserved()const\n {\n return this->num_of_dims()-num_of_observed();\n }\n \n T log_posterior_prob()const\n {\n return log_prob()+this->log_likelihood();\n }\n\n T eval_log(const T& x)const\n {\n set_element(const_cast<stochastic_node*>(this)->v,current_idx,x);\n return log_posterior_prob();\n }\n\n void set_current_idx(size_t i)\n {\n current_idx=i;\n }\n\n size_t get_current_idx()const\n {\n return current_idx;\n }\n\n T log_likelihood()const\n {\n T result=static_cast<T>(0);\n auto& ss=this->get_all_stochastic_children();\n T_vector<T> results(get_size(ss));\n \/\/\/\/followings are the current implementation of computing the log likelihood\n \/\/\n#if defined USE_OMP_TRANSFORM\n pvec_transform_omp(ss,results,[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();},10); \n#elif defined USE_THREAD_TRANSFORM\n pvec_transform_thread(ss,results,[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();},10);\n#else\n std::transform(std::begin(ss),std::end(ss),std::begin(results),[](const stochastic_node<T,T_vector>* const& p){return p->log_prob();});\n#endif\n result=std::accumulate(std::begin(results),std::end(results),static_cast<T>(0));\n return result;\n }\n \n T log_prob()const\n {\n return do_log_prob();\n }\n\n void set_value(size_t idx,const T& v_)\n {\n this->set_initialized(idx,true);\n set_element(v,idx,this->regulate(idx,v_));\n }\n\n T regulate(size_t idx,const T& x)const\n {\n return do_regulate(idx,x);\n }\n\n\n\n public:\n void sample(base_urand<T>& urand)\n {\n do_sample(urand);\n }\n\n public:\n void default_sample(base_urand<T>& urand)\n {\n for(size_t i=0;i<this->num_of_dims();++i)\n\t{\n\t if(is_observed(i))\n\t {\n\t continue;\n\t }\n\t this->set_current_idx(i);\n\t T xprev=this->value(i);\n\t std::pair<T,T> xrange(this->do_var_range());\n\t \n\t \/\/xprev=xprev<xrange.first?xrange.first:xprev;\n\t \/\/xprev=xprev>xrange.second?xrange.second:xprev;\n\t \n\t if(xprev<xrange.first||xprev>xrange.second)\n\t {\n\t this->init_value(i);\n\t xprev=this->value(i);\n\t }\n\t \n\t \/\/arms_simple(*this,xprev,xsamp,dometrop(),rnd);\n\t \n\t if(is_continuous(i))\n\t {\n\t T_vector<T> init_x(this->do_init_points());\n\t xprev=continuous_sample([&](const T& x){return this->eval_log(x);},xrange,init_x, xprev,1,urand);\n\t }\n\t else\n\t {\n\t T_vector<T> candidate_points(this->do_candidate_points());\n\t xprev=discrete_sample([&](const T& x){return this->eval_log(x);},xrange, candidate_points, xprev,10,urand);\n\t }\n\t \n\t this->set_value(i,xprev);\n\t}\n }\n \n private:\n virtual void do_sample(base_urand<T>& urand)\n {\n default_sample(urand);\n }\n \n virtual T do_log_prob()const=0;\n T do_value(size_t idx)const override final\n {\n \/\/return v[idx];\n return get_element(v,idx);\n }\n\n \n void do_connect_to_parent(node<T,T_vector>* rhs,size_t n,size_t idx) override\n {\n \/\/set_element(this->parents,n,std::make_pair(rhs,idx));\n this->set_parent(n,std::make_pair(rhs,idx));\n rhs->add_stochastic_child(this);\n }\n\n virtual T do_regulate(size_t idx,const T& x)const\n {\n return x;\n }\n\n virtual bool is_continuous(size_t idx)const=0;\n\n virtual std::pair<T,T> do_var_range()const=0;\n\n virtual T_vector<T> do_init_points()const\n {\n T_vector<T> result(5);\n std::pair<T,T> xrange(do_var_range());\n T xl=xrange.first,xr=xrange.second;\n for(size_t n=0;n<get_size(result);++n)\n\t{\t \n\t set_element(result,n,xl+(xr-xl)\/(get_size(result)+1)*(n+1));\n\t}\n return result;\n }\n\n virtual T_vector<T> do_candidate_points()const\n {\n return T_vector<T>();\n }\n }; \n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * sample_nodelet_class.cpp\n *\n * Created on: 2016\/10\/30\n * Author: dandelion1124\n *\/\n#include \"sample_nodelet_class.h\"\n#include <pluginlib\/class_list_macros.h>\n\nnamespace sample_nodelet_ns\n{\nSampleNodeletClass::SampleNodeletClass()\n{\n ROS_INFO(\"SampleNodeletClass Constructor\");\n}\n\nSampleNodeletClass::~SampleNodeletClass()\n{\n ROS_INFO(\"SampleNodeletClass Destructor\");\n}\n\nvoid SampleNodeletClass::onInit()\n{\n nh = getNodeHandle();\n timer = nh.createTimer(ros::Duration(10.0), boost::bind(&SampleNodeletClass::timerCb, this));\n NODELET_INFO(\"SampleNodeletClass - %s\", __FUNCTION__);\n}\n\nvoid SampleNodeletClass::timerCb()\n{\n NODELET_INFO(\"SampleNodeletClass - %s\", __FUNCTION__);\n}\n} \/\/ namespace sample_nodelet_ns\n\nPLUGINLIB_EXPORT_CLASS(sample_nodelet_ns::SampleNodeletClass, nodelet::Nodelet)\n<commit_msg>timerの時間を変更<commit_after>\/*\n * sample_nodelet_class.cpp\n *\n * Created on: 2016\/10\/30\n * Author: dandelion1124\n *\/\n#include \"sample_nodelet_class.h\"\n#include <pluginlib\/class_list_macros.h>\n\nnamespace sample_nodelet_ns\n{\nSampleNodeletClass::SampleNodeletClass()\n{\n ROS_INFO(\"SampleNodeletClass Constructor\");\n}\n\nSampleNodeletClass::~SampleNodeletClass()\n{\n ROS_INFO(\"SampleNodeletClass Destructor\");\n}\n\nvoid SampleNodeletClass::onInit()\n{\n nh = getNodeHandle();\n timer = nh.createTimer(ros::Duration(1.0), boost::bind(&SampleNodeletClass::timerCb, this));\n NODELET_INFO(\"SampleNodeletClass - %s\", __FUNCTION__);\n}\n\nvoid SampleNodeletClass::timerCb()\n{\n NODELET_INFO(\"SampleNodeletClass - %s\", __FUNCTION__);\n}\n} \/\/ namespace sample_nodelet_ns\n\nPLUGINLIB_EXPORT_CLASS(sample_nodelet_ns::SampleNodeletClass, nodelet::Nodelet)\n<|endoftext|>"} {"text":"<commit_before>#include \"GameScreenState.h\"\n#include <algorithm>\n#include <SFML\/Graphics.hpp>\n\n\/\/const int TOP = 1;\n\/\/const int BOTTOM = 2;\n\/\/const int LEFT = 4;\n\/\/const int RIGHT = 8;\nconst unsigned char TOP = 0;\nconst unsigned char BOTTOM = 1;\nconst unsigned char LEFT = 2;\nconst unsigned char RIGHT = 3;\n\ninline float clamp(float x, float min, float max) {\n\t return std::max(std::min(x, max), min);\n}\n\nGameScreenState::GameScreenState() {\n\tpos = sf::Vector2f(300, 100);\n\tvelocity = sf::Vector2f(0, 0);\n\tacceleration = sf::Vector2f(0, 0);\n\tlevel_bbox = rectangle(0, 0, 3000, 600);\n\tfor (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;\n\tlevel.push_back(rectangle(200, 400, 400, 450, 2));\n\tlevel.push_back(rectangle(400, 260, 450, 450, 3));\n\tlevel.push_back(rectangle(100, 200, 200, 450, 1));\n\tlevel.push_back(rectangle(95, 200, 100, 455, 2));\n\tlevel.push_back(rectangle(200, 200, 205, 455, 2));\n\tlevel.push_back(rectangle(100, 450, 200, 455, 2));\n\tlevel.push_back(rectangle(600, 450, 1000, 500, 2));\n\tlevel.push_back(rectangle(1200, 300, 2500, 350, 2));\n\n\tlevel.push_back(rectangle(0, 0, 3000, 2, 3));\n\tlevel.push_back(rectangle(0, 0, 2, 600, 3));\n\tlevel.push_back(rectangle(2998, 0, 3000, 600, 3));\n\tlevel.push_back(rectangle(0, 598, 3000, 600, 3));\n\tupdateSprites();\n}\n\nvoid GameScreenState::event(const sf::Event& event) {\n\n}\n\nvoid GameScreenState::updateSprites() {\n\tsprites.clear();\n\tsprites.resize(level.size() + 1);\n\tstatic sf::Color colors[4] = {sf::Color::White, sf::Color::Blue, sf::Color::Black, sf::Color::Yellow};\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tsf::RectangleShape sprite;\n\t\t\/\/sf::Sprite sprite;\n\t\t\/\/sf::Texture tex;\n\t\tsprite.setSize(level[i].maxp - level[i].minp);\n\t\tsprite.setFillColor(colors[level[i].color]);\n\t\t\/\/sprite.setTextureRect(sf::IntRect(0, 0,\n\t\t\/\/\t(int)(level[i].maxp.x - level[i].minp.x),\n\t\t\/\/\t(int)(level[i].maxp.y - level[i].minp.y)));\n\t\t\/\/tex.create((int)(level[i].maxp.x - level[i].minp.x),\n\t\t\/\/\t\t\t(int)(level[i].maxp.y - level[i].minp.y));\n\t\t\/\/sprite.setTexture(tex);\n\t\tsprite.setPosition(level[i].minp);\n\t\tsprites.push_back(sprite);\n\t}\n\tsf::RectangleShape sprite;\n\tsprite.setSize(sf::Vector2f(40, 40));\n\tsprite.setFillColor(sf::Color::Red);\n\tsprite.setPosition(pos - sf::Vector2f(20, 20));\n\tsprites.push_back(sprite);\n}\n\nvoid GameScreenState::render(sf::RenderTarget& target) {\n\tupdateSprites();\n\tsf::View view = target.getDefaultView();\n\tsf::Vector2f size = view.getSize();\n\tsf::Vector2f center\n\t\t(clamp(pos.x, level_bbox.minp.x + size.x \/ 2,\n\t\t\tlevel_bbox.maxp.x - size.x \/ 2),\n\t\tclamp(pos.y, level_bbox.minp.y + size.y \/ 2,\n\t\t\tlevel_bbox.maxp.y - size.y \/ 2));\n\tview.setCenter(center);\n\ttarget.setView(view);\n\ttarget.clear(sf::Color::White);\n\tfor (unsigned int i = 0; i < sprites.size(); i++) {\n\t\ttarget.draw(sprites[i]);\n\t}\n}\n\n\nvoid GameScreenState::update(const sf::Time& time) {\n\tfloat s = time.asSeconds();\n\tpos += velocity * s + ((float) 0.5) * s * s * acceleration;\n\tsf::Vector2f oldv = velocity + ((float) 0.5) * s * acceleration;\n\tvelocity += s * acceleration;\n\tacceleration = sf::Vector2f(0, 240);\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {\n\t\tvelocity.x = std::min(velocity.x + 400 * s, (float)200);\n } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {\n\t\tvelocity.x = std::max(velocity.x - 400 * s, (float)-200);\n\t} else {\n\t\t\/\/velocity.x = 0;\n\t}\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {\n\t\tswitch (touching_walls[BOTTOM]) {\n\t\t\tcase 1:\n\t\t\t\tvelocity.y -= 500 * s;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\tvelocity.y -= 150;\n\t\t}\n\t}\n\tvelocity.x = std::max(std::min(velocity.x, (float)1500), (float)-1500);\n\tvelocity.y = std::max(std::min(velocity.y, (float)1500), (float)-1500);\n\trectangle me_ex = rectangle(pos - sf::Vector2f(20, 19.9), pos + sf::Vector2f(20, 19.9));\n\trectangle me_ey = rectangle(pos - sf::Vector2f(19.9, 20), pos + sf::Vector2f(19.9, 20));\n\tfor (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tif (level[i].color < 2) continue; \/\/ Not solid\n\t\tif (level[i].intersects(me_ex)) {\n\t\t\tif (me_ey.maxp.x >= level[i].maxp.x) {\n\t\t\t\tif (me_ey.minp.x >= level[i].maxp.x + oldv.x * s) {\n\t\t\t\t\tfloat d = std::max(level[i].maxp.x - me_ex.minp.x, (float)0);\n\t\t\t\t\tpos.x += d;\n\t\t\t\t\tme_ex.movex(d);\n\t\t\t\t\tme_ey.movex(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (me_ey.minp.x <= level[i].minp.x) {\n\t\t\t\tif (me_ey.maxp.x <= level[i].minp.x + oldv.x * s) {\n\t\t\t\t\tfloat d = std::min(level[i].minp.x - me_ex.maxp.x, (float)0);\n\t\t\t\t\tpos.x += d;\n\t\t\t\t\tme_ex.movex(d);\n\t\t\t\t\tme_ey.movex(d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (level[i].intersects(me_ey)) {\n\t\t\tif (me_ex.maxp.y >= level[i].maxp.y) {\n\t\t\t\tif (me_ex.minp.y >= level[i].maxp.y + oldv.y * s) {\n\t\t\t\t\tfloat d = std::max(level[i].maxp.y - me_ey.minp.y, (float)0);\n\t\t\t\t\tpos.y += d;\n\t\t\t\t\tme_ex.movey(d);\n\t\t\t\t\tme_ey.movey(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (me_ex.minp.y <= level[i].minp.y) {\n\t\t\t\tif (me_ex.maxp.y <= level[i].minp.y + oldv.y * s) {\n\t\t\t\t\tfloat d = std::min(level[i].minp.y - me_ey.maxp.y, (float)0); \n\t\t\t\t\tpos.y += d;\n\t\t\t\t\tme_ex.movey(d);\n\t\t\t\t\tme_ey.movey(d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tif (level[i].intersects(me_ex)) {\n\t\t\tif (me_ey.minp.x >= level[i].minp.x) {\n\t\t\t\ttouching_walls[LEFT] = std::max(touching_walls[LEFT], level[i].color);\n\t\t\t}\n\t\t\tif (me_ey.maxp.x <= level[i].maxp.x) {\n\t\t\t\ttouching_walls[RIGHT] = std::max(touching_walls[RIGHT], level[i].color);\n\t\t\t}\n\t\t}\n\t\tif (level[i].intersects(me_ey)) {\n\t\t\tif (me_ex.minp.y >= level[i].minp.y) {\n\t\t\t\ttouching_walls[TOP] = std::max(touching_walls[TOP], level[i].color);\n\t\t\t}\n\t\t\tif (me_ex.maxp.y <= level[i].maxp.y) {\n\t\t\t\ttouching_walls[BOTTOM] = std::max(touching_walls[BOTTOM], level[i].color);\n\t\t\t}\n\t\t}\n\t}\n\tfloat visc = 0.01;\n\tswitch (touching_walls[LEFT]) {\n\t\tcase 1:\n\t\t\tif (velocity.x < 0) velocity.x *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.x = std::max(velocity.x, (float)0);\n\t\t\tacceleration.x = std::max(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.x = std::max(velocity.x, -velocity.x);\n\t\t\tacceleration.x = std::max(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[RIGHT]) {\n\t\tcase 1:\n\t\t\tif (velocity.x > 0) velocity.x *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.x = std::min(velocity.x, (float)0);\n\t\t\tacceleration.x = std::min(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.x = std::min(velocity.x, -velocity.x);\n\t\t\tacceleration.x = std::min(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[TOP]) {\n\t\tcase 1:\n\t\t\tif (velocity.y < 0) velocity.y *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.y = std::max(velocity.y, (float)0);\n\t\t\tacceleration.y = std::max(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.y = std::max(velocity.y, -velocity.y);\n\t\t\tacceleration.y = std::max(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[BOTTOM]) {\n\t\tcase 1:\n\t\t\tif (velocity.y > 0) velocity.y *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.y = std::min(velocity.y, (float)0);\n\t\t\tacceleration.y = std::min(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.y = std::min(velocity.y, -velocity.y);\n\t\t\tacceleration.y = std::min(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n}\n<commit_msg>Physics part VII: add TIME_SPEED<commit_after>#include \"GameScreenState.h\"\n#include <algorithm>\n#include <SFML\/Graphics.hpp>\n\n\/\/const int TOP = 1;\n\/\/const int BOTTOM = 2;\n\/\/const int LEFT = 4;\n\/\/const int RIGHT = 8;\nconst unsigned char TOP = 0;\nconst unsigned char BOTTOM = 1;\nconst unsigned char LEFT = 2;\nconst unsigned char RIGHT = 3;\n\ninline float clamp(float x, float min, float max) {\n\t return std::max(std::min(x, max), min);\n}\n\nGameScreenState::GameScreenState() {\n\tpos = sf::Vector2f(300, 100);\n\tvelocity = sf::Vector2f(0, 0);\n\tacceleration = sf::Vector2f(0, 0);\n\tlevel_bbox = rectangle(0, 0, 3000, 600);\n\tfor (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;\n\tlevel.push_back(rectangle(200, 400, 400, 450, 2));\n\tlevel.push_back(rectangle(400, 260, 450, 450, 3));\n\tlevel.push_back(rectangle(100, 200, 200, 450, 1));\n\tlevel.push_back(rectangle(95, 200, 100, 455, 2));\n\tlevel.push_back(rectangle(200, 200, 205, 455, 2));\n\tlevel.push_back(rectangle(100, 450, 200, 455, 2));\n\tlevel.push_back(rectangle(600, 450, 1000, 500, 2));\n\tlevel.push_back(rectangle(1200, 300, 2500, 350, 2));\n\n\tlevel.push_back(rectangle(0, 0, 3000, 2, 3));\n\tlevel.push_back(rectangle(0, 0, 2, 600, 3));\n\tlevel.push_back(rectangle(2998, 0, 3000, 600, 3));\n\tlevel.push_back(rectangle(0, 598, 3000, 600, 3));\n\tupdateSprites();\n}\n\nvoid GameScreenState::event(const sf::Event& event) {\n\n}\n\nvoid GameScreenState::updateSprites() {\n\tsprites.clear();\n\tsprites.resize(level.size() + 1);\n\tstatic sf::Color colors[4] = {sf::Color::White, sf::Color::Blue, sf::Color::Black, sf::Color::Yellow};\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tsf::RectangleShape sprite;\n\t\t\/\/sf::Sprite sprite;\n\t\t\/\/sf::Texture tex;\n\t\tsprite.setSize(level[i].maxp - level[i].minp);\n\t\tsprite.setFillColor(colors[level[i].color]);\n\t\t\/\/sprite.setTextureRect(sf::IntRect(0, 0,\n\t\t\/\/\t(int)(level[i].maxp.x - level[i].minp.x),\n\t\t\/\/\t(int)(level[i].maxp.y - level[i].minp.y)));\n\t\t\/\/tex.create((int)(level[i].maxp.x - level[i].minp.x),\n\t\t\/\/\t\t\t(int)(level[i].maxp.y - level[i].minp.y));\n\t\t\/\/sprite.setTexture(tex);\n\t\tsprite.setPosition(level[i].minp);\n\t\tsprites.push_back(sprite);\n\t}\n\tsf::RectangleShape sprite;\n\tsprite.setSize(sf::Vector2f(40, 40));\n\tsprite.setFillColor(sf::Color::Red);\n\tsprite.setPosition(pos - sf::Vector2f(20, 20));\n\tsprites.push_back(sprite);\n}\n\nvoid GameScreenState::render(sf::RenderTarget& target) {\n\tupdateSprites();\n\tsf::View view = target.getDefaultView();\n\tsf::Vector2f size = view.getSize();\n\tsf::Vector2f center\n\t\t(clamp(pos.x, level_bbox.minp.x + size.x \/ 2,\n\t\t\tlevel_bbox.maxp.x - size.x \/ 2),\n\t\tclamp(pos.y, level_bbox.minp.y + size.y \/ 2,\n\t\t\tlevel_bbox.maxp.y - size.y \/ 2));\n\tview.setCenter(center);\n\ttarget.setView(view);\n\ttarget.clear(sf::Color::White);\n\tfor (unsigned int i = 0; i < sprites.size(); i++) {\n\t\ttarget.draw(sprites[i]);\n\t}\n}\n\n\nconst float TIME_SPEED = 3;\nvoid GameScreenState::update(const sf::Time& time) {\n\tfloat s = time.asSeconds() * TIME_SPEED;\n\tpos += velocity * s + ((float) 0.5) * s * s * acceleration;\n\tsf::Vector2f oldv = velocity + ((float) 0.5) * s * acceleration;\n\tvelocity += s * acceleration;\n\tacceleration = sf::Vector2f(0, 240);\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {\n\t\tvelocity.x = std::min(velocity.x + (float)400 * s, (float)200);\n } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {\n\t\tvelocity.x = std::max(velocity.x - (float)400 * s, (float)-200);\n\t} else {\n\t\t\/\/velocity.x = 0;\n\t}\n\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {\n\t\tswitch (touching_walls[BOTTOM]) {\n\t\t\tcase 1:\n\t\t\t\tvelocity.y -= 500 * s;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tcase 3:\n\t\t\t\tvelocity.y -= 150;\n\t\t}\n\t}\n\tvelocity.x = std::max(std::min(velocity.x, (float)1500), (float)-1500);\n\tvelocity.y = std::max(std::min(velocity.y, (float)1500), (float)-1500);\n\trectangle me_ex = rectangle(pos - sf::Vector2f(20, 19.9), pos + sf::Vector2f(20, 19.9));\n\trectangle me_ey = rectangle(pos - sf::Vector2f(19.9, 20), pos + sf::Vector2f(19.9, 20));\n\tfor (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tif (level[i].color < 2) continue; \/\/ Not solid\n\t\tif (level[i].intersects(me_ex)) {\n\t\t\tif (me_ey.maxp.x >= level[i].maxp.x) {\n\t\t\t\tif (me_ey.minp.x >= level[i].maxp.x + oldv.x * s) {\n\t\t\t\t\tfloat d = std::max(level[i].maxp.x - me_ex.minp.x, (float)0);\n\t\t\t\t\tpos.x += d;\n\t\t\t\t\tme_ex.movex(d);\n\t\t\t\t\tme_ey.movex(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (me_ey.minp.x <= level[i].minp.x) {\n\t\t\t\tif (me_ey.maxp.x <= level[i].minp.x + oldv.x * s) {\n\t\t\t\t\tfloat d = std::min(level[i].minp.x - me_ex.maxp.x, (float)0);\n\t\t\t\t\tpos.x += d;\n\t\t\t\t\tme_ex.movex(d);\n\t\t\t\t\tme_ey.movex(d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (level[i].intersects(me_ey)) {\n\t\t\tif (me_ex.maxp.y >= level[i].maxp.y) {\n\t\t\t\tif (me_ex.minp.y >= level[i].maxp.y + oldv.y * s) {\n\t\t\t\t\tfloat d = std::max(level[i].maxp.y - me_ey.minp.y, (float)0);\n\t\t\t\t\tpos.y += d;\n\t\t\t\t\tme_ex.movey(d);\n\t\t\t\t\tme_ey.movey(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (me_ex.minp.y <= level[i].minp.y) {\n\t\t\t\tif (me_ex.maxp.y <= level[i].minp.y + oldv.y * s) {\n\t\t\t\t\tfloat d = std::min(level[i].minp.y - me_ey.maxp.y, (float)0); \n\t\t\t\t\tpos.y += d;\n\t\t\t\t\tme_ex.movey(d);\n\t\t\t\t\tme_ey.movey(d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (unsigned int i = 0; i < level.size(); i++) {\n\t\tif (level[i].intersects(me_ex)) {\n\t\t\tif (me_ey.minp.x >= level[i].minp.x) {\n\t\t\t\ttouching_walls[LEFT] = std::max(touching_walls[LEFT], level[i].color);\n\t\t\t}\n\t\t\tif (me_ey.maxp.x <= level[i].maxp.x) {\n\t\t\t\ttouching_walls[RIGHT] = std::max(touching_walls[RIGHT], level[i].color);\n\t\t\t}\n\t\t}\n\t\tif (level[i].intersects(me_ey)) {\n\t\t\tif (me_ex.minp.y >= level[i].minp.y) {\n\t\t\t\ttouching_walls[TOP] = std::max(touching_walls[TOP], level[i].color);\n\t\t\t}\n\t\t\tif (me_ex.maxp.y <= level[i].maxp.y) {\n\t\t\t\ttouching_walls[BOTTOM] = std::max(touching_walls[BOTTOM], level[i].color);\n\t\t\t}\n\t\t}\n\t}\n\tfloat visc = 0.01;\n\tswitch (touching_walls[LEFT]) {\n\t\tcase 1:\n\t\t\tif (velocity.x < 0) velocity.x *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.x = std::max(velocity.x, (float)0);\n\t\t\tacceleration.x = std::max(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.x = std::max(velocity.x, -velocity.x);\n\t\t\tacceleration.x = std::max(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[RIGHT]) {\n\t\tcase 1:\n\t\t\tif (velocity.x > 0) velocity.x *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.x = std::min(velocity.x, (float)0);\n\t\t\tacceleration.x = std::min(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.x = std::min(velocity.x, -velocity.x);\n\t\t\tacceleration.x = std::min(acceleration.x, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[TOP]) {\n\t\tcase 1:\n\t\t\tif (velocity.y < 0) velocity.y *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.y = std::max(velocity.y, (float)0);\n\t\t\tacceleration.y = std::max(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.y = std::max(velocity.y, -velocity.y);\n\t\t\tacceleration.y = std::max(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tswitch (touching_walls[BOTTOM]) {\n\t\tcase 1:\n\t\t\tif (velocity.y > 0) velocity.y *= pow(visc, s);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tvelocity.y = std::min(velocity.y, (float)0);\n\t\t\tacceleration.y = std::min(acceleration.y, (float)0);\n\t\t\tif (velocity.x > 0) {\n\t\t\t\tvelocity.x = std::max((float)0, velocity.x - (float)100 * s);\n\t\t\t} else {\n\t\t\t\tvelocity.x = std::min((float)0, velocity.x + (float)100 * s);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tvelocity.y = std::min(velocity.y, -velocity.y);\n\t\t\tacceleration.y = std::min(acceleration.y, (float)0);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\tvelocity.x *= pow(0.2, s);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n\tThis file is owned by Murtaza Alexandru and may not be distributed, edited or used without written permission of the owner\r\n\tWhen using this work you accept to keep this header\r\n\tE-mails from murtaza_alexandru73@yahoo.com with permissions can be seen as valid.\r\n*\/\r\n\r\n\r\n\r\n#include \"TextureMappedFont.hpp\"\r\n#include \"StringEx.hpp\"\r\n#include \"Render.hpp\"\r\n#include \"Vertex.hpp\"\r\n#include \"Image.hpp\"\r\n#include \"Types.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace MPACK::Core;\r\nusing namespace MPACK::Math;\r\n\r\nnamespace MPACK\r\n{\r\n\tnamespace Graphics\r\n\t{\r\n\t\tTextureMappedFont::TextureMappedFont()\r\n\t\t\t: m_layer(1000.0f), m_fontSize(40.0f),\r\n\t\t\t m_charSpacing(0.6f), m_charPadding(0.05f),\r\n\t\t\t m_monospaced(false), m_caseType(NONE),\r\n\t\t\t m_formatType(RGB_MAGNITUDE)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetMonospaced(bool monospaced)\r\n\t\t{\r\n\t\t\tm_monospaced = monospaced;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SendString(string str, GLfloat x, GLfloat y, AlignType alignType, vector<Math::Vector4f> *colorPattern)\r\n\t\t{\r\n\t\t\tswitch(m_caseType)\r\n\t\t\t{\r\n\t\t\t\tcase LOWERCASE:\r\n\t\t\t\t\tstr=StringEx::ToLower(str);\r\n\t\t\t\tbreak;\r\n\t\t\t\tcase UPPERCASE:\r\n\t\t\t\t\tstr=StringEx::ToUpper(str);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(alignType==ALIGN_CENTER)\r\n\t\t\t{\r\n\t\t\t\tGLfloat width=GetTextWidth(str);\r\n\t\t\t\tGLfloat height=m_fontSize;\r\n\r\n\t\t\t\tx-=width*0.5;\r\n\t\t\t\ty-=height*0.5;\r\n\t\t\t}\r\n\r\n\t\t\tGLfloat spacing(m_fontSize*m_charSpacing);\r\n\r\n\t\t\tvector<SpriteVertex> quadData;\r\n\t\t\tSpriteVertex vertex;\r\n\t\t\tif(m_formatType == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tvertex.stype=SpriteVertex::ALPHA_TEST;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvertex.stype=SpriteVertex::ALPHA_BLEND;\r\n\t\t\t}\r\n\r\n\t\t\tint ind=0;\r\n\t\t\tfor(string::size_type i = 0; i < str.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tconst GLfloat oneOverSixteen = 1.0f \/ 16.0f;\r\n\r\n\t\t\t\tGLuint ch = GLuint(str[i]);\r\n\t\t\t\tGLuint chX = ch \/ 16;\r\n\t\t\t\tGLuint chY = ch % 16;\r\n\t\t\t\tGLfloat xPos = GLfloat(ch % 16) * oneOverSixteen;\r\n\t\t\t\tGLfloat yPos = GLfloat(ch \/ 16) * oneOverSixteen;\r\n\r\n\t\t\t\tif(!m_monospaced)\r\n\t\t\t\t{\r\n\t\t\t\t\tx-=m_fontSize*m_cellSpacing[chX][chY].left;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\t\t\tvertex.x=x;\r\n\t\t\t\tvertex.y=y+m_fontSize;\r\n\t\t\t\tvertex.s=xPos;\r\n\t\t\t\tvertex.t=1.0f-yPos-oneOverSixteen;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x+m_fontSize;\r\n\t\t\t\tvertex.y=y+m_fontSize;\r\n\t\t\t\tvertex.s=xPos+oneOverSixteen;\r\n\t\t\t\tvertex.t=1.0f-yPos-oneOverSixteen;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x+m_fontSize;\r\n\t\t\t\tvertex.y=y;\r\n\t\t\t\tvertex.s=xPos+oneOverSixteen;\r\n\t\t\t\tvertex.t=1.0f-yPos;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x;\r\n\t\t\t\tvertex.y=y;\r\n\t\t\t\tvertex.s=xPos;\r\n\t\t\t\tvertex.t=1.0f-yPos;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tif(!m_monospaced)\r\n\t\t\t\t{\r\n\t\t\t\t\tx+=m_fontSize*(1-m_cellSpacing[chX][chY].right)+m_charPadding*m_fontSize;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tx+=spacing;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tBatcher::SendSpriteVertexQuad(&quadData[0],quadData.size(),&m_texture,IndexData::TRIANGLES,m_layer);\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCase(CaseType caseType)\r\n\t\t{\r\n\t\t\tm_caseType=caseType;\r\n\t\t}\r\n\r\n\t\tTextureMappedFont::CaseType TextureMappedFont::GetCase() const\r\n\t\t{\r\n\t\t\treturn m_caseType;\r\n\t\t}\r\n\r\n\t\tTextureMappedFont::FormatType TextureMappedFont::GetFormat() const\r\n\t\t{\r\n\t\t\treturn m_formatType;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCharPadding(GLfloat charPadding)\r\n\t\t{\r\n\t\t\tm_charPadding = charPadding;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetCharPadding() const\r\n\t\t{\r\n\t\t\treturn m_charPadding;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::AutoCalibrate()\r\n\t\t{\r\n\t\t\tif(m_formatType == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tm_charPadding = 0.0f;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tm_charPadding = 0.05f;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetFontSize(GLfloat fontSize)\r\n\t\t{\r\n\t\t\tm_fontSize=fontSize;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCharSpacing(GLfloat charSpacing)\r\n\t\t{\r\n\t\t\tm_charSpacing=charSpacing;\r\n\t\t}\r\n\r\n\t\tbool TextureMappedFont::Load(const string& textureName, FormatType format)\r\n\t\t{\r\n\t\t\tImage *pFontImage = LoadImage(textureName.c_str());\r\n\t\t\tif(pFontImage->Load(textureName.c_str())==RETURN_VALUE_KO)\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"TextureMappedFont::Load() could not load the font texture: %s\",textureName.c_str());\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(format == ALPHA && !pFontImage->HaveAlphaChannel())\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"TextureMappedFont::Load() format is set to ALPHA but font image does not have alpha channel!\");\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tm_formatType = format;\r\n\r\n\t\t\tpFontImage->FlipVertical();\r\n\r\n\t\t\tif(format == ALPHA)\r\n\t\t\t{\r\n\t\t\t\tBuildCellSpacing_ALPHA(pFontImage);\r\n\t\t\t}\r\n\t\t\telse if(format == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tBuildCellSpacing_RGB_MAGNITUDE(pFontImage);\r\n\t\t\t}\r\n\r\n\t\t\tpFontImage->FlipVertical();\r\n\t\t\tif (!m_texture.Load(pFontImage, Bilinear))\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"Texture Mapped Font: Could not load font image to texture memory: %s\",textureName.c_str());\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tdelete pFontImage;\r\n\r\n\t\t\tAutoCalibrate();\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tTexture2D* TextureMappedFont::GetTexturePointer()\r\n\t\t{\r\n\t\t\treturn &m_texture;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetFontSize() const\r\n\t\t{\r\n\t\t\treturn m_fontSize;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetTextWidth(const std::string &str)\r\n\t\t{\r\n\t\t\tGLfloat width=0.0f;\r\n\t\t\tif(m_monospaced)\r\n\t\t\t{\r\n\t\t\t\tGLfloat spacing(m_fontSize*m_charSpacing);\r\n\t\t\t\tfor(register int i=0;i<str.size();++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(str[i]==' ')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twidth+=spacing;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twidth+=m_fontSize;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tGLfloat x=0.0f;\r\n\t\t\t\tfor(string::size_type i = 0; i < str.size(); ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tconst GLfloat oneOverSixteen = 1.0f \/ 16.0f;\r\n\r\n\t\t\t\t\tGLuint ch = GLuint(str[i]);\r\n\t\t\t\t\tGLuint chX = ch \/ 16;\r\n\t\t\t\t\tGLuint chY = ch % 16;\r\n\t\t\t\t\tGLfloat xPos = GLfloat(ch % 16) * oneOverSixteen;\r\n\t\t\t\t\tGLfloat yPos = GLfloat(ch \/ 16) * oneOverSixteen;\r\n\r\n\t\t\t\t\twidth-=m_fontSize*m_cellSpacing[chX][chY].left;\r\n\t\t\t\t\twidth+=m_fontSize*(1-m_cellSpacing[chX][chY].right);\r\n\t\t\t\t}\r\n\t\t\t\twidth+=m_fontSize*m_charPadding*(str.size()-1);\r\n\t\t\t}\r\n\t\t\treturn width;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::BuildCellSpacing_RGB_MAGNITUDE(Image *pFontImage)\r\n\t\t{\r\n\t\t\tGLuint width=pFontImage->GetWidth();\r\n\t\t\tGLuint height=pFontImage->GetHeight();\r\n\t\t\tGLuint cellWidth=width>>4;\r\n\t\t\tGLuint cellHeight=height>>4;\r\n\t\t\tconst float OneOver255=1.0f\/255.0f;\r\n\t\t\tfloat OneOverCellWidth=1.0f\/(GLfloat)(cellWidth);\r\n\t\t\tfloat OneOverCellHeight=1.0f\/(GLfloat)(cellHeight);\r\n\t\t\tAABB2Df cell;\r\n\t\t\tfor(register GLuint i=0;i<16;++i)\r\n\t\t\t{\r\n\t\t\t\tfor(register GLuint j=0;j<16;++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell.Clear();\r\n\t\t\t\t\tfor(register GLuint ci=0;ci<cellWidth;++ci)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor(register GLuint cj=0;cj<cellHeight;++cj)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tGLuint ri=i*cellWidth+ci;\r\n\t\t\t\t\t\t\tGLuint rj=j*cellHeight+cj;\r\n\t\t\t\t\t\t\tColor c=pFontImage->GetPixel(ri,rj);\r\n\t\t\t\t\t\t\tBYTE b=c.b;\r\n\t\t\t\t\t\t\tBYTE g=c.g;\r\n\t\t\t\t\t\t\tBYTE r=c.r;\r\n\t\t\t\t\t\t\tMath::Vector3f color((GLfloat)(r)*OneOver255,(GLfloat)(g)*OneOver255,(GLfloat)(b)*OneOver255);\r\n\r\n\t\t\t\t\t\t\tif(color.Magnitude()>=FORMATTYPE_RGB_MAGNITUDE_THRESHOLD)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcell.AddPoint(Vector2f((GLfloat)(cj),(GLfloat)(ci)));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(cell.m_xmin>cellWidth)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=(GLfloat)(cell.m_xmin)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=(GLfloat)(cellWidth-cell.m_xmax)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=(GLfloat)(cell.m_ymin)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=(GLfloat)(cellHeight-cell.m_ymax)*OneOverCellHeight;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tGLuint chX = GLuint(' ') \/ 16;\r\n\t\t\tGLuint chY = GLuint(' ') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\r\n\t\t\tchX = GLuint('\\t') \/ 16;\r\n\t\t\tchY = GLuint('\\t') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::BuildCellSpacing_ALPHA(Image *pFontImage)\r\n\t\t{\r\n\t\t\tGLuint width=pFontImage->GetWidth();\r\n\t\t\tGLuint height=pFontImage->GetHeight();\r\n\t\t\tGLuint cellWidth=width>>4;\r\n\t\t\tGLuint cellHeight=height>>4;\r\n\t\t\tconst float OneOver255=1.0f\/255.0f;\r\n\t\t\tfloat OneOverCellWidth=1.0f\/(GLfloat)(cellWidth);\r\n\t\t\tfloat OneOverCellHeight=1.0f\/(GLfloat)(cellHeight);\r\n\t\t\tAABB2Df cell;\r\n\t\t\tfor(register GLuint i=0;i<16;++i)\r\n\t\t\t{\r\n\t\t\t\tfor(register GLuint j=0;j<16;++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell.Clear();\r\n\t\t\t\t\tfor(register GLuint ci=0;ci<cellWidth;++ci)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor(register GLuint cj=0;cj<cellHeight;++cj)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tGLuint ri=i*cellWidth+ci;\r\n\t\t\t\t\t\t\tGLuint rj=j*cellHeight+cj;\r\n\t\t\t\t\t\t\tColor c=pFontImage->GetPixel(ri,rj);\r\n\t\t\t\t\t\t\tBYTE alpha=c.a;\r\n\r\n\t\t\t\t\t\t\tif(alpha>=FORMATTYPE_ALPHA_THRESHOLD)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcell.AddPoint(Vector2f((GLfloat)(cj),(GLfloat)(ci)));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(cell.m_xmin>cellWidth)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=(GLfloat)(cell.m_xmin)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=(GLfloat)(cellWidth-cell.m_xmax)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=(GLfloat)(cell.m_ymin)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=(GLfloat)(cellHeight-cell.m_ymax)*OneOverCellWidth;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tGLuint chX = GLuint(' ') \/ 16;\r\n\t\t\tGLuint chY = GLuint(' ') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\r\n\t\t\tchX = GLuint('\\t') \/ 16;\r\n\t\t\tchY = GLuint('\\t') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\t\t}\r\n\t}\r\n}\r\n<commit_msg>Fix TextureMappedFont memory leak<commit_after>\/*\r\n\tThis file is owned by Murtaza Alexandru and may not be distributed, edited or used without written permission of the owner\r\n\tWhen using this work you accept to keep this header\r\n\tE-mails from murtaza_alexandru73@yahoo.com with permissions can be seen as valid.\r\n*\/\r\n\r\n\r\n\r\n#include \"TextureMappedFont.hpp\"\r\n#include \"StringEx.hpp\"\r\n#include \"Render.hpp\"\r\n#include \"Vertex.hpp\"\r\n#include \"Image.hpp\"\r\n#include \"Types.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace MPACK::Core;\r\nusing namespace MPACK::Math;\r\n\r\nnamespace MPACK\r\n{\r\n\tnamespace Graphics\r\n\t{\r\n\t\tTextureMappedFont::TextureMappedFont()\r\n\t\t\t: m_layer(1000.0f), m_fontSize(40.0f),\r\n\t\t\t m_charSpacing(0.6f), m_charPadding(0.05f),\r\n\t\t\t m_monospaced(false), m_caseType(NONE),\r\n\t\t\t m_formatType(RGB_MAGNITUDE)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetMonospaced(bool monospaced)\r\n\t\t{\r\n\t\t\tm_monospaced = monospaced;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SendString(string str, GLfloat x, GLfloat y, AlignType alignType, vector<Math::Vector4f> *colorPattern)\r\n\t\t{\r\n\t\t\tswitch(m_caseType)\r\n\t\t\t{\r\n\t\t\t\tcase LOWERCASE:\r\n\t\t\t\t\tstr=StringEx::ToLower(str);\r\n\t\t\t\tbreak;\r\n\t\t\t\tcase UPPERCASE:\r\n\t\t\t\t\tstr=StringEx::ToUpper(str);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(alignType==ALIGN_CENTER)\r\n\t\t\t{\r\n\t\t\t\tGLfloat width=GetTextWidth(str);\r\n\t\t\t\tGLfloat height=m_fontSize;\r\n\r\n\t\t\t\tx-=width*0.5;\r\n\t\t\t\ty-=height*0.5;\r\n\t\t\t}\r\n\r\n\t\t\tGLfloat spacing(m_fontSize*m_charSpacing);\r\n\r\n\t\t\tvector<SpriteVertex> quadData;\r\n\t\t\tSpriteVertex vertex;\r\n\t\t\tif(m_formatType == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tvertex.stype=SpriteVertex::ALPHA_TEST;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvertex.stype=SpriteVertex::ALPHA_BLEND;\r\n\t\t\t}\r\n\r\n\t\t\tint ind=0;\r\n\t\t\tfor(string::size_type i = 0; i < str.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tconst GLfloat oneOverSixteen = 1.0f \/ 16.0f;\r\n\r\n\t\t\t\tGLuint ch = GLuint(str[i]);\r\n\t\t\t\tGLuint chX = ch \/ 16;\r\n\t\t\t\tGLuint chY = ch % 16;\r\n\t\t\t\tGLfloat xPos = GLfloat(ch % 16) * oneOverSixteen;\r\n\t\t\t\tGLfloat yPos = GLfloat(ch \/ 16) * oneOverSixteen;\r\n\r\n\t\t\t\tif(!m_monospaced)\r\n\t\t\t\t{\r\n\t\t\t\t\tx-=m_fontSize*m_cellSpacing[chX][chY].left;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\t\t\tvertex.x=x;\r\n\t\t\t\tvertex.y=y+m_fontSize;\r\n\t\t\t\tvertex.s=xPos;\r\n\t\t\t\tvertex.t=1.0f-yPos-oneOverSixteen;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x+m_fontSize;\r\n\t\t\t\tvertex.y=y+m_fontSize;\r\n\t\t\t\tvertex.s=xPos+oneOverSixteen;\r\n\t\t\t\tvertex.t=1.0f-yPos-oneOverSixteen;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x+m_fontSize;\r\n\t\t\t\tvertex.y=y;\r\n\t\t\t\tvertex.s=xPos+oneOverSixteen;\r\n\t\t\t\tvertex.t=1.0f-yPos;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tvertex.x=x;\r\n\t\t\t\tvertex.y=y;\r\n\t\t\t\tvertex.s=xPos;\r\n\t\t\t\tvertex.t=1.0f-yPos;\r\n\t\t\t\tif(!colorPattern)\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=vertex.g=vertex.b=vertex.a=1.0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvertex.r=(*colorPattern)[ind].x;\r\n\t\t\t\t\tvertex.g=(*colorPattern)[ind].y;\r\n\t\t\t\t\tvertex.b=(*colorPattern)[ind].z;\r\n\t\t\t\t\tvertex.a=(*colorPattern)[ind].w;\r\n\t\t\t\t\t++ind;\r\n\t\t\t\t\tif(ind==colorPattern->size())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tind=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tquadData.push_back(vertex);\r\n\r\n\t\t\t\tif(!m_monospaced)\r\n\t\t\t\t{\r\n\t\t\t\t\tx+=m_fontSize*(1-m_cellSpacing[chX][chY].right)+m_charPadding*m_fontSize;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tx+=spacing;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tBatcher::SendSpriteVertexQuad(&quadData[0],quadData.size(),&m_texture,IndexData::TRIANGLES,m_layer);\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCase(CaseType caseType)\r\n\t\t{\r\n\t\t\tm_caseType=caseType;\r\n\t\t}\r\n\r\n\t\tTextureMappedFont::CaseType TextureMappedFont::GetCase() const\r\n\t\t{\r\n\t\t\treturn m_caseType;\r\n\t\t}\r\n\r\n\t\tTextureMappedFont::FormatType TextureMappedFont::GetFormat() const\r\n\t\t{\r\n\t\t\treturn m_formatType;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCharPadding(GLfloat charPadding)\r\n\t\t{\r\n\t\t\tm_charPadding = charPadding;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetCharPadding() const\r\n\t\t{\r\n\t\t\treturn m_charPadding;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::AutoCalibrate()\r\n\t\t{\r\n\t\t\tif(m_formatType == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tm_charPadding = 0.0f;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tm_charPadding = 0.05f;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetFontSize(GLfloat fontSize)\r\n\t\t{\r\n\t\t\tm_fontSize=fontSize;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::SetCharSpacing(GLfloat charSpacing)\r\n\t\t{\r\n\t\t\tm_charSpacing=charSpacing;\r\n\t\t}\r\n\r\n\t\tbool TextureMappedFont::Load(const string& textureName, FormatType format)\r\n\t\t{\r\n\t\t\tImage *pFontImage = LoadImage(textureName.c_str());\r\n\t\t\tif(!pFontImage)\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"TextureMappedFont::Load() could not load the font texture: %s\",textureName.c_str());\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tif(format == ALPHA && !pFontImage->HaveAlphaChannel())\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"TextureMappedFont::Load() format is set to ALPHA but font image does not have alpha channel!\");\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tm_formatType = format;\r\n\r\n\t\t\tpFontImage->FlipVertical();\r\n\r\n\t\t\tif(format == ALPHA)\r\n\t\t\t{\r\n\t\t\t\tBuildCellSpacing_ALPHA(pFontImage);\r\n\t\t\t}\r\n\t\t\telse if(format == RGB_MAGNITUDE)\r\n\t\t\t{\r\n\t\t\t\tBuildCellSpacing_RGB_MAGNITUDE(pFontImage);\r\n\t\t\t}\r\n\r\n\t\t\tpFontImage->FlipVertical();\r\n\t\t\tif (!m_texture.Load(pFontImage, Bilinear))\r\n\t\t\t{\r\n\t\t\t\tLOGE(\"Texture Mapped Font: Could not load font image to texture memory: %s\",textureName.c_str());\r\n\t\t\t\tdelete pFontImage;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tdelete pFontImage;\r\n\r\n\t\t\tAutoCalibrate();\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tTexture2D* TextureMappedFont::GetTexturePointer()\r\n\t\t{\r\n\t\t\treturn &m_texture;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetFontSize() const\r\n\t\t{\r\n\t\t\treturn m_fontSize;\r\n\t\t}\r\n\r\n\t\tGLfloat TextureMappedFont::GetTextWidth(const std::string &str)\r\n\t\t{\r\n\t\t\tGLfloat width=0.0f;\r\n\t\t\tif(m_monospaced)\r\n\t\t\t{\r\n\t\t\t\tGLfloat spacing(m_fontSize*m_charSpacing);\r\n\t\t\t\tfor(register int i=0;i<str.size();++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(str[i]==' ')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twidth+=spacing;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twidth+=m_fontSize;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tGLfloat x=0.0f;\r\n\t\t\t\tfor(string::size_type i = 0; i < str.size(); ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tconst GLfloat oneOverSixteen = 1.0f \/ 16.0f;\r\n\r\n\t\t\t\t\tGLuint ch = GLuint(str[i]);\r\n\t\t\t\t\tGLuint chX = ch \/ 16;\r\n\t\t\t\t\tGLuint chY = ch % 16;\r\n\t\t\t\t\tGLfloat xPos = GLfloat(ch % 16) * oneOverSixteen;\r\n\t\t\t\t\tGLfloat yPos = GLfloat(ch \/ 16) * oneOverSixteen;\r\n\r\n\t\t\t\t\twidth-=m_fontSize*m_cellSpacing[chX][chY].left;\r\n\t\t\t\t\twidth+=m_fontSize*(1-m_cellSpacing[chX][chY].right);\r\n\t\t\t\t}\r\n\t\t\t\twidth+=m_fontSize*m_charPadding*(str.size()-1);\r\n\t\t\t}\r\n\t\t\treturn width;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::BuildCellSpacing_RGB_MAGNITUDE(Image *pFontImage)\r\n\t\t{\r\n\t\t\tGLuint width=pFontImage->GetWidth();\r\n\t\t\tGLuint height=pFontImage->GetHeight();\r\n\t\t\tGLuint cellWidth=width>>4;\r\n\t\t\tGLuint cellHeight=height>>4;\r\n\t\t\tconst float OneOver255=1.0f\/255.0f;\r\n\t\t\tfloat OneOverCellWidth=1.0f\/(GLfloat)(cellWidth);\r\n\t\t\tfloat OneOverCellHeight=1.0f\/(GLfloat)(cellHeight);\r\n\t\t\tAABB2Df cell;\r\n\t\t\tfor(register GLuint i=0;i<16;++i)\r\n\t\t\t{\r\n\t\t\t\tfor(register GLuint j=0;j<16;++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell.Clear();\r\n\t\t\t\t\tfor(register GLuint ci=0;ci<cellWidth;++ci)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor(register GLuint cj=0;cj<cellHeight;++cj)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tGLuint ri=i*cellWidth+ci;\r\n\t\t\t\t\t\t\tGLuint rj=j*cellHeight+cj;\r\n\t\t\t\t\t\t\tColor c=pFontImage->GetPixel(ri,rj);\r\n\t\t\t\t\t\t\tBYTE b=c.b;\r\n\t\t\t\t\t\t\tBYTE g=c.g;\r\n\t\t\t\t\t\t\tBYTE r=c.r;\r\n\t\t\t\t\t\t\tMath::Vector3f color((GLfloat)(r)*OneOver255,(GLfloat)(g)*OneOver255,(GLfloat)(b)*OneOver255);\r\n\r\n\t\t\t\t\t\t\tif(color.Magnitude()>=FORMATTYPE_RGB_MAGNITUDE_THRESHOLD)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcell.AddPoint(Vector2f((GLfloat)(cj),(GLfloat)(ci)));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(cell.m_xmin>cellWidth)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=(GLfloat)(cell.m_xmin)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=(GLfloat)(cellWidth-cell.m_xmax)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=(GLfloat)(cell.m_ymin)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=(GLfloat)(cellHeight-cell.m_ymax)*OneOverCellHeight;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tGLuint chX = GLuint(' ') \/ 16;\r\n\t\t\tGLuint chY = GLuint(' ') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\r\n\t\t\tchX = GLuint('\\t') \/ 16;\r\n\t\t\tchY = GLuint('\\t') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\t\t}\r\n\r\n\t\tvoid TextureMappedFont::BuildCellSpacing_ALPHA(Image *pFontImage)\r\n\t\t{\r\n\t\t\tGLuint width=pFontImage->GetWidth();\r\n\t\t\tGLuint height=pFontImage->GetHeight();\r\n\t\t\tGLuint cellWidth=width>>4;\r\n\t\t\tGLuint cellHeight=height>>4;\r\n\t\t\tconst float OneOver255=1.0f\/255.0f;\r\n\t\t\tfloat OneOverCellWidth=1.0f\/(GLfloat)(cellWidth);\r\n\t\t\tfloat OneOverCellHeight=1.0f\/(GLfloat)(cellHeight);\r\n\t\t\tAABB2Df cell;\r\n\t\t\tfor(register GLuint i=0;i<16;++i)\r\n\t\t\t{\r\n\t\t\t\tfor(register GLuint j=0;j<16;++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell.Clear();\r\n\t\t\t\t\tfor(register GLuint ci=0;ci<cellWidth;++ci)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor(register GLuint cj=0;cj<cellHeight;++cj)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tGLuint ri=i*cellWidth+ci;\r\n\t\t\t\t\t\t\tGLuint rj=j*cellHeight+cj;\r\n\t\t\t\t\t\t\tColor c=pFontImage->GetPixel(ri,rj);\r\n\t\t\t\t\t\t\tBYTE alpha=c.a;\r\n\r\n\t\t\t\t\t\t\tif(alpha>=FORMATTYPE_ALPHA_THRESHOLD)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcell.AddPoint(Vector2f((GLfloat)(cj),(GLfloat)(ci)));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(cell.m_xmin>cellWidth)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=OneOverCellWidth*(cellWidth>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=OneOverCellWidth*(cellHeight>>1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_cellSpacing[i][j].left=(GLfloat)(cell.m_xmin)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].right=(GLfloat)(cellWidth-cell.m_xmax)*OneOverCellHeight;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].top=(GLfloat)(cell.m_ymin)*OneOverCellWidth;\r\n\t\t\t\t\t\tm_cellSpacing[i][j].bottom=(GLfloat)(cellHeight-cell.m_ymax)*OneOverCellWidth;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tGLuint chX = GLuint(' ') \/ 16;\r\n\t\t\tGLuint chY = GLuint(' ') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\r\n\t\t\tchX = GLuint('\\t') \/ 16;\r\n\t\t\tchY = GLuint('\\t') % 16;\r\n\t\t\tm_cellSpacing[chX][chY].right=m_cellSpacing[chX][chY].bottom=0.0f;\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * despot1_main.cpp\n *\n * Created by Tobias Wood on 23\/01\/2012.\n * Copyright 2012 Tobias Wood. All rights reserved.\n *\n *\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/NonLinearOptimization>\n\n#include \"NiftiImage.h\"\n#include \"DESPOT.h\"\n#include \"DESPOT_Functors.h\"\n#include \"RegionContraction.h\"\n\n#define USE_PROCPAR\n#ifdef USE_PROCPAR\n\t#include \"procpar.h\"\n\tusing namespace Recon;\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string credit {\n\"despot2 - Written by tobias.wood@kcl.ac.uk, based on work by Sean Deoni. \\n\\\nAcknowledgements greatfully received, grant discussions welcome.\"\n};\n\nconst string usage {\n\"Usage is: despot2 [options] output_prefix T1_map ssfp_files\\n\\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message.\\n\\\n\t--mask, -m file : Mask input with specified file.\\n\\\n\t--B0 file : B0 Map file.\\n\\\n\t--B1 file : B1 Map file.\\n\\\n\t--M0 file : Proton density file.\\n\\\n\t--verbose, -v : Print slice processing times.\\n\\\n\t--start_slice N : Start processing from slice N.\\n\\\n\t--end_slice N : Finish processing at slice N.\\n\\\n\t--tesla, -t 3 : Enables DESPOT-FM with boundaries suitable for 3T\\n\\\n\t 7 : Boundaries suitable for 7T (default)\\n\\\n\t u : User specified boundaries from stdin.\\n\"\n\n};\n\n\/\/ tesla == 0 means NO DESPOT-FM\nstatic int tesla = 0, fitB0 = false, verbose = false, start_slice = -1, end_slice = -1;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"B0\", required_argument, 0, '0'},\n\t{\"B1\", required_argument, 0, '1'},\n\t{\"M0\", required_argument, 0, 'M'},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"tesla\", optional_argument, 0, 'f'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"start_slice\", required_argument, 0, 'S'},\n\t{\"end_slice\", required_argument, 0, 'E'},\n\t{0, 0, 0, 0}\n};\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv)\n{\n\t\/\/**************************************************************************\n\t\/\/ Argument Processing\n\t\/\/**************************************************************************\n\tcout << credit << endl;\n\tif (argc < 4) {\n\t\tcout << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tEigen::initParallel();\n\tNiftiImage inFile, savedHeader;\n\tdouble *maskData = NULL, *B0Data = NULL, *B1Data = NULL, *T1Data = NULL,\n\t *M0Data = NULL;\n\tstring procPath;\n\t\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"hm:vz\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'm':\n\t\t\t\tcout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tmaskData = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase '0':\n\t\t\t\tcout << \"Reading B0 file \" << optarg << endl;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tB0Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tcout << \"Reading B1 file \" << optarg;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tB1Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase 'M':\n\t\t\t\tcout << \"Reading M0 file \" << optarg;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tM0Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tswitch (*optarg) {\n\t\t\t\t\tcase '3': tesla = 3; break;\n\t\t\t\t\tcase '7': tesla = 7; break;\n\t\t\t\t\tcase 'u': tesla = -1; break;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcout << \"Unknown boundaries type \" << optarg << endl;\n\t\t\t\t\t\tabort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcout << \"Using \" << tesla << \"T boundaries.\" << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tverbose = true;\n\t\t\t\tbreak;\n\t\t\tcase 'S':\n\t\t\t\tstart_slice = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'E':\n\t\t\t\tend_slice = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\t\/\/ Just a flag\n\t\t\t\tbreak;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\t\t\t\t\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((tesla != 0) && !B0Data)\n\t\tfitB0 = true;\n\tcout << \"Output prefix will be: \" << argv[optind] << endl;\n\toutPrefix = argv[optind++];\n\tcout << \"Reading T1 Map from: \" << argv[optind] << endl;\n\tinFile.open(argv[optind++], 'r');\n\tT1Data = inFile.readVolume<double>(0);\n\tinFile.close();\n\tsavedHeader = inFile;\n\t\/\/**************************************************************************\n\t\/\/ Gather SSFP Data\n\t\/\/**************************************************************************\n\tint nFlip, nPhases;\n\tdouble ssfpTR;\n\tnPhases = argc - optind;\n\tvector<double> ssfpPhases(nPhases);\n\tVectorXd ssfpAngles;\n\tint voxelsPerSlice, voxelsPerVolume;\n\tdouble **ssfpData = (double **)malloc(nPhases * sizeof(double *));\n\tfor (size_t p = 0; p < nPhases; p++)\n\t{\n\t\tcout << \"Reading SSFP header from \" << argv[optind] << endl;\n\t\tinFile.open(argv[optind], 'r');\n\t\tif (p == 0)\n\t\t{\t\/\/ Read nFlip, TR and flip angles from first file\n\t\t\tnFlip = inFile.dim(4);\n\t\t\tvoxelsPerSlice = inFile.voxelsPerSlice();\n\t\t\tvoxelsPerVolume = inFile.voxelsPerVolume();\n\t\t\tssfpAngles.resize(nFlip, 1);\n\t\t\t\n\t\t\t#ifdef USE_PROCPAR\n\t\t\tParameterList pars;\n\t\t\tif (ReadProcpar(inFile.basename() + \".procpar\", pars)) {\n\t\t\t\tssfpTR = RealValue(pars, \"tr\");\n\t\t\t\tfor (int i = 0; i < nFlip; i++)\n\t\t\t\t\tssfpAngles[i] = RealValue(pars, \"flip1\", i);\n\t\t\t} else\n\t\t\t#endif\n\t\t\t{\n\t\t\t\tcout << \"Enter SSFP TR (s): \" << flush;\n\t\t\t\tcin >> ssfpTR;\n\t\t\t\tcout << \"Enter \" << nFlip << \" flip angles (degrees): \" << flush;\n\t\t\t\tfor (int i = 0; i < ssfpAngles.size(); i++)\n\t\t\t\t\tcin >> ssfpAngles[i];\n\t\t\t}\n\t\t}\n\t\t#ifdef USE_PROCPAR\n\t\tParameterList pars;\n\t\tif (ReadProcpar(inFile.basename() + \".procpar\", pars)) {\n\t\t\tssfpPhases[p] = RealValue(pars, \"rfphase\") * M_PI \/ 180.;\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\tcout << \"Enter phase-cycling (degrees): \" << flush;\n\t\t\tcin >> ssfpPhases[p]; ssfpPhases[p] *= M_PI \/ 180.;\n\t\t}\n\t\tcout << \"Reading SSFP data...\" << endl;\n\t\tssfpData[p] = inFile.readAllVolumes<double>();\n\t\t\/\/ Don't close the first header because we've saved it to write the\n\t\t\/\/ results, and FSLIO gets fussy about cloning closed headers\n\t\tinFile.close();\n\t\toptind++;\n\t}\n\tssfpAngles *= M_PI \/ 180.;\n\t\n\tif (optind != argc) {\n\t\tcerr << \"Unprocessed arguments supplied.\\n\" << usage;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\t\/\/ Set up boundaries for DESPOT-FM if needed\n\tDESPOT2FM::ParamType loBounds, hiBounds;\n\tif (tesla != 0) {\n\t\tif (tesla > 0) {\n\t\t\tloBounds = DESPOT2FM::loBounds(tesla);\n\t\t\thiBounds = DESPOT2FM::hiBounds(tesla);\n\t\t} else if (tesla < 0) {\n\t\t\tcout << \"Enter \" << DESPOT2FM::nP << \" parameter pairs (low then high): \" << flush;\n\t\t\tfor (int i = 0; i < DESPOT2FM::nP; i++) cin >> loBounds[i] >> hiBounds[i];\n\t\t}\n\t\t\/\/ If fitting, give a suitable range and allocate results memory\n\t\tif (fitB0) {\n\t\t\tloBounds[DESPOT2FM::nP - 1] = -0.5 \/ ssfpTR;\n\t\t\thiBounds[DESPOT2FM::nP - 1] = 0.5 \/ ssfpTR;\n\t\t\tB0Data = new double[voxelsPerVolume];\n\t\t} else { \/\/ Otherwise fix and let functors pick up the specified value\n\t\t\tloBounds[DESPOT2FM::nP - 1] = 0.;\n\t\t\thiBounds[DESPOT2FM::nP - 1] = 0.;\n\t\t}\n\t}\n\t\n\tif (verbose) {\n\t\tcout << \"SSFP Angles (deg): \" << ssfpAngles.transpose() * 180 \/ M_PI << endl;\n\t\tif (tesla != 0)\n\t\t\tcout << \"Low bounds: \" << loBounds.transpose() << endl\n\t\t\t\t << \"Hi bounds: \" << hiBounds.transpose() << endl;\n\t}\n\t\/\/**************************************************************************\n\t\/\/ Set up results data\n\t\/\/**************************************************************************\n\tdouble *residualData = new double[voxelsPerVolume];\n\tdouble *PDData = new double[voxelsPerVolume];\n\tdouble *T2Data = new double[voxelsPerVolume];\n\t\/\/**************************************************************************\n\t\/\/ Do the fitting\n\t\/\/**************************************************************************\n time_t procStart = time(NULL);\n\tif ((start_slice < 0) || (start_slice >= inFile.dim(4)))\n\t\tstart_slice = 0;\n\tif ((end_slice < 0) || (end_slice > inFile.dim(4)))\n\t\tend_slice = inFile.dim(4);\n\tfor (int slice = start_slice; slice < end_slice; slice++) {\n\t\t\/\/ Read in data\n\t\tif (verbose)\n\t\t\tcout << \"Starting slice \" << slice << \"...\" << flush;\n\t\t\n\t\tatomic<int> voxCount{0};\n\t\tconst int sliceOffset = slice * voxelsPerSlice;\n\t\tclock_t loopStart = clock();\n\t\tfunction<void (const int&)> processVox = [&] (const int &vox) {\n\t\t\t\/\/ Set up parameters and constants\n\t\t\tdouble M0 = 0., T1 = 0., T2 = 0., B0 = 0, B1 = 1., residual = 0.;\n\t\t\tif (!maskData || ((maskData[sliceOffset + vox] > 0.) && (T1Data[sliceOffset + vox] > 0.)))\n\t\t\t{\t\/\/ Zero T1 causes zero-pivot error.\n\t\t\t\tvoxCount++;\n\t\t\t\tT1 = T1Data[sliceOffset + vox];\n\t\t\t\tif (B0Data) B0 = B0Data[sliceOffset + vox];\n\t\t\t\tif (B1Data)\tB1 = B1Data[sliceOffset + vox];\n\t\t\t\t\/\/ Gather signals.\n\t\t\t\tvector<VectorXd> signals;\n\t\t\t\tfor (int p = 0; p < nPhases; p++)\n\t\t\t\t{\n\t\t\t\t\tVectorXd temp(nFlip);\n\t\t\t\t\tfor (int i = 0; i < nFlip; i++)\n\t\t\t\t\t\ttemp(i) = ssfpData[p][i*voxelsPerVolume + sliceOffset + vox];\n\t\t\t\t\tsignals.push_back(temp);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (tesla == 0) {\n\t\t\t\t\t\/\/ Choose phase with accumulated phase closest to 180 and then classic DESPOT2\n\t\t\t\t\tint index = 0;\n\t\t\t\t\tdouble bestPhase = DBL_MAX;\n\t\t\t\t\tfor (int p = 0; p < nPhases; p++) {\n\t\t\t\t\t\tdouble thisPhase = (B0 * ssfpTR * 2 * M_PI) + ssfpPhases[p];\n\t\t\t\t\t\tif (fabs(fmod(thisPhase - M_PI, 2 * M_PI)) < bestPhase) {\n\t\t\t\t\t\t\tbestPhase = fabs(fmod(thisPhase - M_PI, 2 * M_PI));\n\t\t\t\t\t\t\tindex = p;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresidual = classicDESPOT2(ssfpAngles, signals[index], ssfpTR, T1, B1, M0, T2);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ DESPOT2-FM\n\t\t\t\t\tVectorXd allB0(nFlip), allB1(nFlip);\n\t\t\t\t\tallB0.setConstant(B0);\n\t\t\t\t\tallB1.setConstant(B1);\n\t\t\t\t\tDESPOT2FM tc(ssfpAngles, ssfpPhases, signals,\n\t\t\t\t allB0, allB1, ssfpTR, false, fitB0);\n\t\t\t\t\tDESPOT2FM::ParamType params(DESPOT2FM::nP);\n\t\t\t\t\tresidual = regionContraction<DESPOT2FM>(params, tc, loBounds, hiBounds);\n\t\t\t\t\tM0 = params[0];\n\t\t\t\t\tT2 = params[1];\n\t\t\t\t\tif (fitB0)\n\t\t\t\t\t\tB0 = params[2];\n\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tPDData[sliceOffset + vox] = clamp(M0, 0., 5.e3);\n\t\t\tT2Data[sliceOffset + vox] = clamp(T2, 0., 0.5);\n\t\t\tif (fitB0)\n\t\t\t\tB0Data[sliceOffset + vox] = B0;\n\t\t\tresidualData[sliceOffset + vox] = residual;\n\t\t};\n\t\tapply_for(voxelsPerSlice, processVox);\n\t\t\n\t\tif (verbose) {\n\t\t\tclock_t loopEnd = clock();\n\t\t\tif (voxCount > 0)\n\t\t\t\tcout << voxCount << \" unmasked voxels, CPU time per voxel was \"\n\t\t\t\t << ((loopEnd - loopStart) \/ ((float)voxCount * CLOCKS_PER_SEC)) << \" s, \";\n\t\t\tcout << \"finished.\" << endl;\n\t\t}\n\t}\n time_t procEnd = time(NULL);\n struct tm *localEnd = localtime(&procEnd);\n\tchar theTime[512];\n strftime(theTime, 512, \"%H:%M:%S\", localEnd);\n\tcout << \"Finished processing at \" << theTime << \". Run-time was \" \n\t << difftime(procEnd, procStart) << \" s.\" << endl;\n\tsavedHeader.setDim(4, 1);\n\tsavedHeader.setDatatype(NIFTI_TYPE_FLOAT32);\n\tsavedHeader.open(outPrefix + \"_T2.nii.gz\", NiftiImage::NIFTI_WRITE);\n\tsavedHeader.writeVolume(0, T2Data);\n\tsavedHeader.close();\n\tsavedHeader.open(outPrefix + \"_PD.nii.gz\", NiftiImage::NIFTI_WRITE);\n\tsavedHeader.writeVolume(0, PDData);\n\tsavedHeader.close();\n\tif (fitB0) {\n\t\tsavedHeader.open(outPrefix + \"_B0.nii.gz\", NiftiImage::NIFTI_WRITE);\n\t\tsavedHeader.writeVolume(0, B0Data);\n\t\tsavedHeader.close();\n\t}\n\t\/\/ Clean up memory\n\tfor (int p = 0; p < nPhases; p++)\n\t\tfree(ssfpData[p]);\n\tif (B0Data)\n\t\tfree(B0Data);\n\tif (B1Data)\n\t\tfree(B1Data);\n\tif (maskData)\n\t\tfree(maskData);\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Start and end slices in despot2 were being incorrectly taken from 4th dimension instead of 3rd.<commit_after>\/*\n * despot1_main.cpp\n *\n * Created by Tobias Wood on 23\/01\/2012.\n * Copyright 2012 Tobias Wood. All rights reserved.\n *\n *\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/NonLinearOptimization>\n\n#include \"NiftiImage.h\"\n#include \"DESPOT.h\"\n#include \"DESPOT_Functors.h\"\n#include \"RegionContraction.h\"\n\n#define USE_PROCPAR\n#ifdef USE_PROCPAR\n\t#include \"procpar.h\"\n\tusing namespace Recon;\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string credit {\n\"despot2 - Written by tobias.wood@kcl.ac.uk, based on work by Sean Deoni. \\n\\\nAcknowledgements greatfully received, grant discussions welcome.\"\n};\n\nconst string usage {\n\"Usage is: despot2 [options] output_prefix T1_map ssfp_files\\n\\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message.\\n\\\n\t--mask, -m file : Mask input with specified file.\\n\\\n\t--B0 file : B0 Map file.\\n\\\n\t--B1 file : B1 Map file.\\n\\\n\t--M0 file : Proton density file.\\n\\\n\t--verbose, -v : Print slice processing times.\\n\\\n\t--start_slice N : Start processing from slice N.\\n\\\n\t--end_slice N : Finish processing at slice N.\\n\\\n\t--tesla, -t 3 : Enables DESPOT-FM with boundaries suitable for 3T\\n\\\n\t 7 : Boundaries suitable for 7T (default)\\n\\\n\t u : User specified boundaries from stdin.\\n\"\n\n};\n\n\/\/ tesla == 0 means NO DESPOT-FM\nstatic int tesla = 0, fitB0 = false, verbose = false, start_slice = -1, end_slice = -1;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"B0\", required_argument, 0, '0'},\n\t{\"B1\", required_argument, 0, '1'},\n\t{\"M0\", required_argument, 0, 'M'},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"tesla\", optional_argument, 0, 'f'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"start_slice\", required_argument, 0, 'S'},\n\t{\"end_slice\", required_argument, 0, 'E'},\n\t{0, 0, 0, 0}\n};\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv)\n{\n\t\/\/**************************************************************************\n\t\/\/ Argument Processing\n\t\/\/**************************************************************************\n\tcout << credit << endl;\n\tif (argc < 4) {\n\t\tcout << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tEigen::initParallel();\n\tNiftiImage inFile, savedHeader;\n\tdouble *maskData = NULL, *B0Data = NULL, *B1Data = NULL, *T1Data = NULL,\n\t *M0Data = NULL;\n\tstring procPath;\n\t\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"hm:vz\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'm':\n\t\t\t\tcout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tmaskData = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase '0':\n\t\t\t\tcout << \"Reading B0 file \" << optarg << endl;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tB0Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase '1':\n\t\t\t\tcout << \"Reading B1 file \" << optarg;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tB1Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase 'M':\n\t\t\t\tcout << \"Reading M0 file \" << optarg;\n\t\t\t\tinFile.open(optarg, 'r');\n\t\t\t\tM0Data = inFile.readVolume<double>(0);\n\t\t\t\tinFile.close();\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tswitch (*optarg) {\n\t\t\t\t\tcase '3': tesla = 3; break;\n\t\t\t\t\tcase '7': tesla = 7; break;\n\t\t\t\t\tcase 'u': tesla = -1; break;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcout << \"Unknown boundaries type \" << optarg << endl;\n\t\t\t\t\t\tabort();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcout << \"Using \" << tesla << \"T boundaries.\" << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'v':\n\t\t\t\tverbose = true;\n\t\t\t\tbreak;\n\t\t\tcase 'S':\n\t\t\t\tstart_slice = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'E':\n\t\t\t\tend_slice = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\t\/\/ Just a flag\n\t\t\t\tbreak;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\t\t\t\t\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((tesla != 0) && !B0Data)\n\t\tfitB0 = true;\n\tcout << \"Output prefix will be: \" << argv[optind] << endl;\n\toutPrefix = argv[optind++];\n\tcout << \"Reading T1 Map from: \" << argv[optind] << endl;\n\tinFile.open(argv[optind++], 'r');\n\tT1Data = inFile.readVolume<double>(0);\n\tinFile.close();\n\tsavedHeader = inFile;\n\t\/\/**************************************************************************\n\t\/\/ Gather SSFP Data\n\t\/\/**************************************************************************\n\tint nFlip, nPhases;\n\tdouble ssfpTR;\n\tnPhases = argc - optind;\n\tvector<double> ssfpPhases(nPhases);\n\tVectorXd ssfpAngles;\n\tint voxelsPerSlice, voxelsPerVolume;\n\tdouble **ssfpData = (double **)malloc(nPhases * sizeof(double *));\n\tfor (size_t p = 0; p < nPhases; p++)\n\t{\n\t\tcout << \"Reading SSFP header from \" << argv[optind] << endl;\n\t\tinFile.open(argv[optind], 'r');\n\t\tif (p == 0)\n\t\t{\t\/\/ Read nFlip, TR and flip angles from first file\n\t\t\tnFlip = inFile.dim(4);\n\t\t\tvoxelsPerSlice = inFile.voxelsPerSlice();\n\t\t\tvoxelsPerVolume = inFile.voxelsPerVolume();\n\t\t\tssfpAngles.resize(nFlip, 1);\n\t\t\t\n\t\t\t#ifdef USE_PROCPAR\n\t\t\tParameterList pars;\n\t\t\tif (ReadProcpar(inFile.basename() + \".procpar\", pars)) {\n\t\t\t\tssfpTR = RealValue(pars, \"tr\");\n\t\t\t\tfor (int i = 0; i < nFlip; i++)\n\t\t\t\t\tssfpAngles[i] = RealValue(pars, \"flip1\", i);\n\t\t\t} else\n\t\t\t#endif\n\t\t\t{\n\t\t\t\tcout << \"Enter SSFP TR (s): \" << flush;\n\t\t\t\tcin >> ssfpTR;\n\t\t\t\tcout << \"Enter \" << nFlip << \" flip angles (degrees): \" << flush;\n\t\t\t\tfor (int i = 0; i < ssfpAngles.size(); i++)\n\t\t\t\t\tcin >> ssfpAngles[i];\n\t\t\t}\n\t\t}\n\t\t#ifdef USE_PROCPAR\n\t\tParameterList pars;\n\t\tif (ReadProcpar(inFile.basename() + \".procpar\", pars)) {\n\t\t\tssfpPhases[p] = RealValue(pars, \"rfphase\") * M_PI \/ 180.;\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\tcout << \"Enter phase-cycling (degrees): \" << flush;\n\t\t\tcin >> ssfpPhases[p]; ssfpPhases[p] *= M_PI \/ 180.;\n\t\t}\n\t\tcout << \"Reading SSFP data...\" << endl;\n\t\tssfpData[p] = inFile.readAllVolumes<double>();\n\t\t\/\/ Don't close the first header because we've saved it to write the\n\t\t\/\/ results, and FSLIO gets fussy about cloning closed headers\n\t\tinFile.close();\n\t\toptind++;\n\t}\n\tssfpAngles *= M_PI \/ 180.;\n\t\n\tif (optind != argc) {\n\t\tcerr << \"Unprocessed arguments supplied.\\n\" << usage;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\t\/\/ Set up boundaries for DESPOT-FM if needed\n\tDESPOT2FM::ParamType loBounds, hiBounds;\n\tif (tesla != 0) {\n\t\tif (tesla > 0) {\n\t\t\tloBounds = DESPOT2FM::loBounds(tesla);\n\t\t\thiBounds = DESPOT2FM::hiBounds(tesla);\n\t\t} else if (tesla < 0) {\n\t\t\tcout << \"Enter \" << DESPOT2FM::nP << \" parameter pairs (low then high): \" << flush;\n\t\t\tfor (int i = 0; i < DESPOT2FM::nP; i++) cin >> loBounds[i] >> hiBounds[i];\n\t\t}\n\t\t\/\/ If fitting, give a suitable range and allocate results memory\n\t\tif (fitB0) {\n\t\t\tloBounds[DESPOT2FM::nP - 1] = -0.5 \/ ssfpTR;\n\t\t\thiBounds[DESPOT2FM::nP - 1] = 0.5 \/ ssfpTR;\n\t\t\tB0Data = new double[voxelsPerVolume];\n\t\t} else { \/\/ Otherwise fix and let functors pick up the specified value\n\t\t\tloBounds[DESPOT2FM::nP - 1] = 0.;\n\t\t\thiBounds[DESPOT2FM::nP - 1] = 0.;\n\t\t}\n\t}\n\t\n\tif (verbose) {\n\t\tcout << \"SSFP Angles (deg): \" << ssfpAngles.transpose() * 180 \/ M_PI << endl;\n\t\tif (tesla != 0)\n\t\t\tcout << \"Low bounds: \" << loBounds.transpose() << endl\n\t\t\t\t << \"Hi bounds: \" << hiBounds.transpose() << endl;\n\t}\n\t\/\/**************************************************************************\n\t\/\/ Set up results data\n\t\/\/**************************************************************************\n\tdouble *residualData = new double[voxelsPerVolume];\n\tdouble *PDData = new double[voxelsPerVolume];\n\tdouble *T2Data = new double[voxelsPerVolume];\n\t\/\/**************************************************************************\n\t\/\/ Do the fitting\n\t\/\/**************************************************************************\n time_t procStart = time(NULL);\n\tif ((start_slice < 0) || (start_slice >= inFile.dim(3)))\n\t\tstart_slice = 0;\n\tif ((end_slice < 0) || (end_slice > inFile.dim(3)))\n\t\tend_slice = inFile.dim(4);\n\tfor (int slice = start_slice; slice < end_slice; slice++) {\n\t\t\/\/ Read in data\n\t\tif (verbose)\n\t\t\tcout << \"Starting slice \" << slice << \"...\" << flush;\n\t\t\n\t\tatomic<int> voxCount{0};\n\t\tconst int sliceOffset = slice * voxelsPerSlice;\n\t\tclock_t loopStart = clock();\n\t\tfunction<void (const int&)> processVox = [&] (const int &vox) {\n\t\t\t\/\/ Set up parameters and constants\n\t\t\tdouble M0 = 0., T1 = 0., T2 = 0., B0 = 0, B1 = 1., residual = 0.;\n\t\t\tif (!maskData || ((maskData[sliceOffset + vox] > 0.) && (T1Data[sliceOffset + vox] > 0.)))\n\t\t\t{\t\/\/ Zero T1 causes zero-pivot error.\n\t\t\t\tvoxCount++;\n\t\t\t\tT1 = T1Data[sliceOffset + vox];\n\t\t\t\tif (B0Data) B0 = B0Data[sliceOffset + vox];\n\t\t\t\tif (B1Data)\tB1 = B1Data[sliceOffset + vox];\n\t\t\t\t\/\/ Gather signals.\n\t\t\t\tvector<VectorXd> signals;\n\t\t\t\tfor (int p = 0; p < nPhases; p++)\n\t\t\t\t{\n\t\t\t\t\tVectorXd temp(nFlip);\n\t\t\t\t\tfor (int i = 0; i < nFlip; i++)\n\t\t\t\t\t\ttemp(i) = ssfpData[p][i*voxelsPerVolume + sliceOffset + vox];\n\t\t\t\t\tsignals.push_back(temp);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (tesla == 0) {\n\t\t\t\t\t\/\/ Choose phase with accumulated phase closest to 180 and then classic DESPOT2\n\t\t\t\t\tint index = 0;\n\t\t\t\t\tdouble bestPhase = DBL_MAX;\n\t\t\t\t\tfor (int p = 0; p < nPhases; p++) {\n\t\t\t\t\t\tdouble thisPhase = (B0 * ssfpTR * 2 * M_PI) + ssfpPhases[p];\n\t\t\t\t\t\tif (fabs(fmod(thisPhase - M_PI, 2 * M_PI)) < bestPhase) {\n\t\t\t\t\t\t\tbestPhase = fabs(fmod(thisPhase - M_PI, 2 * M_PI));\n\t\t\t\t\t\t\tindex = p;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tresidual = classicDESPOT2(ssfpAngles, signals[index], ssfpTR, T1, B1, M0, T2);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ DESPOT2-FM\n\t\t\t\t\tVectorXd allB0(nFlip), allB1(nFlip);\n\t\t\t\t\tallB0.setConstant(B0);\n\t\t\t\t\tallB1.setConstant(B1);\n\t\t\t\t\tDESPOT2FM tc(ssfpAngles, ssfpPhases, signals,\n\t\t\t\t allB0, allB1, ssfpTR, false, fitB0);\n\t\t\t\t\tDESPOT2FM::ParamType params(DESPOT2FM::nP);\n\t\t\t\t\tresidual = regionContraction<DESPOT2FM>(params, tc, loBounds, hiBounds);\n\t\t\t\t\tM0 = params[0];\n\t\t\t\t\tT2 = params[1];\n\t\t\t\t\tif (fitB0)\n\t\t\t\t\t\tB0 = params[2];\n\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tPDData[sliceOffset + vox] = clamp(M0, 0., 5.e3);\n\t\t\tT2Data[sliceOffset + vox] = clamp(T2, 0., 0.5);\n\t\t\tif (fitB0)\n\t\t\t\tB0Data[sliceOffset + vox] = B0;\n\t\t\tresidualData[sliceOffset + vox] = residual;\n\t\t};\n\t\tapply_for(voxelsPerSlice, processVox);\n\t\t\n\t\tif (verbose) {\n\t\t\tclock_t loopEnd = clock();\n\t\t\tif (voxCount > 0)\n\t\t\t\tcout << voxCount << \" unmasked voxels, CPU time per voxel was \"\n\t\t\t\t << ((loopEnd - loopStart) \/ ((float)voxCount * CLOCKS_PER_SEC)) << \" s, \";\n\t\t\tcout << \"finished.\" << endl;\n\t\t}\n\t}\n time_t procEnd = time(NULL);\n struct tm *localEnd = localtime(&procEnd);\n\tchar theTime[512];\n strftime(theTime, 512, \"%H:%M:%S\", localEnd);\n\tcout << \"Finished processing at \" << theTime << \". Run-time was \" \n\t << difftime(procEnd, procStart) << \" s.\" << endl;\n\tsavedHeader.setDim(4, 1);\n\tsavedHeader.setDatatype(NIFTI_TYPE_FLOAT32);\n\tsavedHeader.open(outPrefix + \"_T2.nii.gz\", NiftiImage::NIFTI_WRITE);\n\tsavedHeader.writeVolume(0, T2Data);\n\tsavedHeader.close();\n\tsavedHeader.open(outPrefix + \"_PD.nii.gz\", NiftiImage::NIFTI_WRITE);\n\tsavedHeader.writeVolume(0, PDData);\n\tsavedHeader.close();\n\tif (fitB0) {\n\t\tsavedHeader.open(outPrefix + \"_B0.nii.gz\", NiftiImage::NIFTI_WRITE);\n\t\tsavedHeader.writeVolume(0, B0Data);\n\t\tsavedHeader.close();\n\t}\n\t\/\/ Clean up memory\n\tfor (int p = 0; p < nPhases; p++)\n\t\tfree(ssfpData[p]);\n\tif (B0Data)\n\t\tfree(B0Data);\n\tif (B1Data)\n\t\tfree(B1Data);\n\tif (maskData)\n\t\tfree(maskData);\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of Clockwork.\n *\n * Copyright (c) 2014-2016 Jeremy Othieno.\n *\n * The MIT License (MIT)\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#ifndef CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n#define CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n\n#include \"RenderingAlgorithm.hh\"\n#include \"Point4.hh\"\n#include \"Varying.hh\"\n\n\nnamespace clockwork {\nnamespace detail {\n\/**\n * The VertexShaderOutput is the result of a per-vertex operation (vertex shader)\n * on a set of vertex attributes.\n *\/\ntemplate<RenderingAlgorithm algorithm>\nstruct VertexShaderOutput {\n\t\/**\n\t * The vertex position in clip space.\n\t *\/\n\tPoint4 position;\n\t\/**\n\t * The vertex's varying variables.\n\t *\/\n\tVarying<algorithm> varying;\n};\n} \/\/ namespace detail\n} \/\/ namespace clockwork\n\n#endif \/\/ CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n<commit_msg>Implement the GenericVertexShaderOutput struct<commit_after>\/*\n * This file is part of Clockwork.\n *\n * Copyright (c) 2014-2016 Jeremy Othieno.\n *\n * The MIT License (MIT)\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#ifndef CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n#define CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n\n#include \"RenderingAlgorithm.hh\"\n#include \"Point4.hh\"\n#include \"Varying.hh\"\n\n\nnamespace clockwork {\nnamespace detail {\nnamespace {\n\/**\n * The GenericVertexShaderOutput contains the minimum set of results obtained from\n * a per-vertex operation (vertex shader) applied to a set of vertex attributes.\n *\/\nstruct GenericVertexShaderOutput {\n\t\/**\n\t * The vertex position in clipping space.\n\t *\/\n\tPoint4 position;\n};\n} \/\/ namespace\n\/**\n *\n *\/\ntemplate<RenderingAlgorithm algorithm>\nstruct VertexShaderOutput : GenericVertexShaderOutput {\n\t\/**\n\t * The vertex's varying variables.\n\t *\/\n\tVarying<algorithm> varying;\n};\n} \/\/ namespace detail\n} \/\/ namespace clockwork\n\n#endif \/\/ CLOCKWORK_VERTEX_SHADER_OUTPUT_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ a ray tracer in C++\n\n\n\/\/ libraries, namespace\n#include <thread>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <random>\n#include \"library\/loadXML.cpp\"\n#include \"library\/scene.cpp\"\nusing namespace std;\n\n\n\/\/ scene to load (project #) + all ray tracing options & settings\nstring xml = \"scenes\/prj11-1.xml\";\nbool printXML = false;\nbool zBuffer = false;\nbool sampleCount = false;\nint bounceCount = 5;\nint sampleMin = 4;\nint sampleMax = 32;\nfloat sampleThreshold = 0.001;\nint shadowMin = 8;\nint shadowMax = 32;\nbool gammaCorr = true;\nbool globalIllum = true;\nbool irradMap = true;\nint samplesGI = 16;\n\n\n\/\/ variables for ray tracing\nint w;\nint h;\nint size;\nColor24* img;\nfloat* zImg;\nfloat* sampleImg;\nIrradianceMap im;\n\n\n\/\/ variables for anti-aliasing brightness calculations (XYZ, Lab)\nfloat perR = 0.2126;\nfloat perG = 0.7152;\nfloat perB = 0.0722;\nfloat Ycutoff = pow(6.0 \/ 29.0, 3.0);\nfloat Yprecalc = (1.0 \/ 3.0) * pow(29.0 \/ 6.0, 2.0);\n\n\n\/\/ setup threading\nstatic const int numThreads = 8;\nvoid rayTracing(int i);\n\n\n\/\/ for camera ray generation\nvoid cameraRayVars();\nfloat imageDistance = 1.0;\nPoint *imageTopLeftV;\nPoint *dXV;\nPoint *dYV;\nPoint *dVx;\nPoint *dVy;\nPoint firstPixel;\nTransformation* c;\nPoint cameraRay(float pX, float pY, Point offset);\n\n\n\/\/ ray tracer\nint main(){\n \n \/\/ load scene: root node, camera, image (and set shadow casting variables)\n loadScene(xml, printXML, shadowMin, shadowMax, globalIllum, samplesGI);\n \n \/\/ set the scene as the root node\n setScene(rootNode);\n \n \/\/ set variables for ray tracing\n w = render.getWidth();\n h = render.getHeight();\n size = render.getSize();\n img = render.getRender();\n zImg = render.getZBuffer();\n sampleImg = render.getSample();\n im.Initialize(w, h);\n \n \/\/ set variables for generating camera rays\n cameraRayVars();\n \n \/\/ start ray tracing loop (in parallel with threads)\n thread t[numThreads];\n for(int i = 0; i < numThreads; i++)\n t[i] = thread(rayTracing, i);\n \n \/\/ when finished, join all threads back to main\n for(int i = 0; i < numThreads; i++)\n t[i].join();\n \n \/\/ output ray-traced image & z-buffer & sample count image (if set)\n render.save(\"images\/image.ppm\");\n if(zBuffer){\n render.computeZImage();\n render.saveZImage(\"images\/imageZ.ppm\");\n }\n if(sampleCount){\n render.computeSampleImage();\n render.saveSampleImage(\"images\/imageSample.ppm\");\n }\n}\n\n\n\/\/ ray tracing loop (for an individual pixel)\nvoid rayTracing(int i){\n \n \/\/ initial starting pixel\n int pixel = i;\n \n \/\/ setup random generator for anti-aliasing & depth-of-field\n mt19937 rnd;\n uniform_real_distribution<float> dist{0.0, 1.0};\n \n \/\/ thread continuation condition\n while(pixel < size){\n \n \/\/ number of samples\n int s = 0;\n \n \/\/ establish pixel location (center)\n float pX = pixel % w;\n float pY = pixel \/ w;\n \n \/\/ color values to store across samples\n Color col;\n Color colAvg;\n float zAvg = 0.0;\n float rVar = 0.0;\n float gVar = 0.0;\n float bVar = 0.0;\n float var = sampleThreshold;\n float brightness = 0.0;\n \n \/\/ random rotation of Halton sequence on circle of confusion\n float dcR = dist(rnd) * 2.0 * M_PI;\n \n \/\/ compute multi-adaptive sampling for each pixel (anti-aliasing)\n while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){\n \n \/\/ grab Halton sequence to shift point by on image plane\n float dpX = centerHalton(Halton(s, 3));\n float dpY = centerHalton(Halton(s, 2));\n \n \/\/ grab Halton sequence to shift point along circle of confusion\n float dcS = sqrt(Halton(s, 2)) * camera.dof;\n \n \/\/ grab Halton sequence to shift point around circle of confusion\n float dcT = Halton(s, 3) * 2.0 * M_PI;\n \n \/\/ compute the offset for depth of field sampling\n Point posOffset = (*dVx * cos(dcR + dcT) + *dVy * sin(dcR + dcT)) * dcS;\n \n \/\/ transform ray into world space (offset by Halton seqeunce for sampling)\n Point rayDir = cameraRay(pX + dpX, pY + dpY, posOffset);\n Cone *ray = new Cone();\n ray->pos = camera.pos + c->transformFrom(posOffset);\n ray->dir = c->transformFrom(rayDir);\n ray->radius = 0.0;\n ray->tan = dXV->x \/ (2.0 * imageDistance);\n \n \/\/ traverse through scene DOM\n \/\/ transform rays into model space\n \/\/ detect ray intersections and get back HitInfo\n HitInfo hi = HitInfo();\n bool hit = traceRay(*ray, hi);\n \n \/\/ update z-buffer, if necessary\n if(zBuffer)\n zAvg = (zAvg * s + hi.z) \/ (float) (s + 1);\n \n \/\/ if hit, get the node's material\n if(hit){\n Node *n = hi.node;\n Material *m;\n if(n)\n m = n->getMaterial();\n \n \/\/ if there is a material, shade the pixel\n \/\/ 5-passes for reflections and refractions\n if(m)\n col = m->shade(*ray, hi, lights, bounceCount);\n \n \/\/ otherwise color it white (as a hit)\n else\n col.Set(0.929, 0.929, 0.929);\n \n \/\/ if we hit nothing, draw the background\n }else{\n Point p = Point((float) pX \/ w, (float) pY \/ h, 0.0);\n Color b = background.sample(p);\n col = b;\n }\n \n \/\/ compute average color\n float rAvg = (colAvg.r * s + col.r) \/ (float) (s + 1);\n float gAvg = (colAvg.g * s + col.g) \/ (float) (s + 1);\n float bAvg = (colAvg.b * s + col.b) \/ (float) (s + 1);\n colAvg.Set(rAvg, gAvg, bAvg);\n \n \/\/ compute color variances\n rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) \/ (float) (s + 1);\n gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) \/ (float) (s + 1);\n bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) \/ (float) (s + 1);\n \n \/\/ calculate and update brightness average using XYZ and Lab space\n float Y = perR * rAvg + perG * gAvg + perB * bAvg;\n float Y13 = Y;\n if(Y13 > Ycutoff)\n Y13 = pow(Y13, 1.0 \/ 3.0);\n else\n Y13 = Yprecalc * Y13 + (4.0 \/ 29.0);\n brightness = (116.0 * Y13 - 16.0) \/ 100.0;\n \n \/\/ increment sample count\n s++;\n \n \/\/ watch for errors at any individual sample, terminate thread if so\n if(colAvg[0] != colAvg[0] || colAvg[1] != colAvg[1] || colAvg[2] != colAvg[2]){\n cout << \"ERROR - pixel \" << pixel << \" & sample \" << s << endl;\n s = sampleMax;\n pixel = size;\n }\n }\n \n \/\/ gamma correction\n if(gammaCorr){\n colAvg.r = pow(colAvg.r, 1.0 \/ 2.2);\n colAvg.g = pow(colAvg.g, 1.0 \/ 2.2);\n colAvg.b = pow(colAvg.b, 1.0 \/ 2.2);\n }\n \n \/\/ color the pixel image\n img[pixel] = Color24(colAvg);\n \n \/\/ update the z-buffer image, if necessary\n if(zBuffer)\n zImg[pixel] = zAvg;\n \n \/\/ update the sample count image, if necessary\n if(sampleCount)\n sampleImg[pixel] = s;\n \n \/\/ re-assign next pixel (naive, but works)\n pixel += numThreads;\n }\n}\n\n\n\/\/ create variables for camera ray generation\nvoid cameraRayVars(){\n float fov = camera.fov * M_PI \/ 180.0;\n float aspectRatio = (float) w \/ (float) h;\n imageDistance = camera.focalDist;\n float imageTipY = imageDistance * tan(fov \/ 2.0);\n float imageTipX = imageTipY * aspectRatio;\n float dX = (2.0 * imageTipX) \/ (float) w;\n float dY = (2.0 * imageTipY) \/ (float) h;\n imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);\n dXV = new Point(dX, 0.0, 0.0);\n dYV = new Point(0.0, -dY, 0.0);\n firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);\n \n \/\/ set up camera transformation (only need to rotate coordinates)\n c = new Transformation();\n Matrix *rotate = new cyMatrix3f();\n rotate->Set(camera.cross, camera.up, -camera.dir);\n c->transform(*rotate);\n \n \/\/ get normalized rays on the focal plane\n dVx = new Point(1.0, 0.0, 0.0);\n dVy = new Point(0.0, 1.0, 0.0);\n}\n\n\n\/\/ compute camera ray direction\nPoint cameraRay(float pX, float pY, Point offset){\n Point ray = firstPixel + (*dXV * pX) + (*dYV * pY) - offset;\n ray.Normalize();\n return ray;\n}\n<commit_msg>begin adding initialization and subdivision of the irradiance map<commit_after>\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ a ray tracer in C++\n\n\n\/\/ libraries, namespace\n#include <thread>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <random>\n#include \"library\/loadXML.cpp\"\n#include \"library\/scene.cpp\"\nusing namespace std;\n\n\n\/\/ scene to load (project #) + all ray tracing options & settings\nstring xml = \"scenes\/prj11-1.xml\";\nbool printXML = false;\nbool zBuffer = false;\nbool sampleCount = false;\nint bounceCount = 5;\nint sampleMin = 4;\nint sampleMax = 32;\nfloat sampleThreshold = 0.001;\nint shadowMin = 8;\nint shadowMax = 32;\nbool gammaCorr = true;\nbool globalIllum = true;\nbool irradMap = true;\nint samplesGI = 16;\n\n\n\/\/ variables for ray tracing\nint w;\nint h;\nint size;\nColor24* img;\nfloat* zImg;\nfloat* sampleImg;\nIrradianceMap im;\n\n\n\/\/ variables for anti-aliasing brightness calculations (XYZ, Lab)\nfloat perR = 0.2126;\nfloat perG = 0.7152;\nfloat perB = 0.0722;\nfloat Ycutoff = pow(6.0 \/ 29.0, 3.0);\nfloat Yprecalc = (1.0 \/ 3.0) * pow(29.0 \/ 6.0, 2.0);\n\n\n\/\/ setup threading\nstatic const int numThreads = 8;\nvoid rayTracing(int i);\n\n\n\/\/ for camera ray generation\nvoid cameraRayVars();\nfloat imageDistance = 1.0;\nPoint *imageTopLeftV;\nPoint *dXV;\nPoint *dYV;\nPoint *dVx;\nPoint *dVy;\nPoint firstPixel;\nTransformation* c;\nPoint cameraRay(float pX, float pY, Point offset);\n\n\n\/\/ ray tracer\nint main(){\n \n \/\/ load scene: root node, camera, image (and set shadow casting variables)\n loadScene(xml, printXML, shadowMin, shadowMax, globalIllum, samplesGI);\n \n \/\/ set the scene as the root node\n setScene(rootNode);\n \n \/\/ set variables for ray tracing\n w = render.getWidth();\n h = render.getHeight();\n size = render.getSize();\n img = render.getRender();\n zImg = render.getZBuffer();\n sampleImg = render.getSample();\n if(irradMap)\n im.Initialize(w, h);\n \n \/\/ set variables for generating camera rays\n cameraRayVars();\n \n \/\/ start irradiance map computation\n if(irradMap){\n \n \/\/ subdivide our image to compute indirect illumination\n bool subdivide = true;\n while(subdivide){\n \n \/\/ check if we are on final subdivide\n if(im.GetSubdivLevel() == 0)\n subdivide = false;\n \n \/\/ calculate indirect illumination\n \n \/\/ subdivide (if necessary)\n if(subdivide)\n im.Subdivide();\n }\n }\n \n \/\/ sample test output (know irrad map done)\n cout << \"onto ray tracing!\" << endl;\n \n \/\/ start ray tracing loop (in parallel with threads)\n thread t[numThreads];\n for(int i = 0; i < numThreads; i++)\n t[i] = thread(rayTracing, i);\n \n \/\/ when finished, join all threads back to main\n for(int i = 0; i < numThreads; i++)\n t[i].join();\n \n \/\/ output ray-traced image & z-buffer & sample count image (if set)\n render.save(\"images\/image.ppm\");\n if(zBuffer){\n render.computeZImage();\n render.saveZImage(\"images\/imageZ.ppm\");\n }\n if(sampleCount){\n render.computeSampleImage();\n render.saveSampleImage(\"images\/imageSample.ppm\");\n }\n}\n\n\n\/\/ ray tracing loop (for an individual pixel)\nvoid rayTracing(int i){\n \n \/\/ initial starting pixel\n int pixel = i;\n \n \/\/ setup random generator for anti-aliasing & depth-of-field\n mt19937 rnd;\n uniform_real_distribution<float> dist{0.0, 1.0};\n \n \/\/ thread continuation condition\n while(pixel < size){\n \n \/\/ number of samples\n int s = 0;\n \n \/\/ establish pixel location (center)\n float pX = pixel % w;\n float pY = pixel \/ w;\n \n \/\/ color values to store across samples\n Color col;\n Color colAvg;\n float zAvg = 0.0;\n float rVar = 0.0;\n float gVar = 0.0;\n float bVar = 0.0;\n float var = sampleThreshold;\n float brightness = 0.0;\n \n \/\/ random rotation of Halton sequence on circle of confusion\n float dcR = dist(rnd) * 2.0 * M_PI;\n \n \/\/ compute multi-adaptive sampling for each pixel (anti-aliasing)\n while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){\n \n \/\/ grab Halton sequence to shift point by on image plane\n float dpX = centerHalton(Halton(s, 3));\n float dpY = centerHalton(Halton(s, 2));\n \n \/\/ grab Halton sequence to shift point along circle of confusion\n float dcS = sqrt(Halton(s, 2)) * camera.dof;\n \n \/\/ grab Halton sequence to shift point around circle of confusion\n float dcT = Halton(s, 3) * 2.0 * M_PI;\n \n \/\/ compute the offset for depth of field sampling\n Point posOffset = (*dVx * cos(dcR + dcT) + *dVy * sin(dcR + dcT)) * dcS;\n \n \/\/ transform ray into world space (offset by Halton seqeunce for sampling)\n Point rayDir = cameraRay(pX + dpX, pY + dpY, posOffset);\n Cone *ray = new Cone();\n ray->pos = camera.pos + c->transformFrom(posOffset);\n ray->dir = c->transformFrom(rayDir);\n ray->radius = 0.0;\n ray->tan = dXV->x \/ (2.0 * imageDistance);\n \n \/\/ traverse through scene DOM\n \/\/ transform rays into model space\n \/\/ detect ray intersections and get back HitInfo\n HitInfo hi = HitInfo();\n bool hit = traceRay(*ray, hi);\n \n \/\/ update z-buffer, if necessary\n if(zBuffer)\n zAvg = (zAvg * s + hi.z) \/ (float) (s + 1);\n \n \/\/ if hit, get the node's material\n if(hit){\n Node *n = hi.node;\n Material *m;\n if(n)\n m = n->getMaterial();\n \n \/\/ if there is a material, shade the pixel\n \/\/ 5-passes for reflections and refractions\n if(m)\n col = m->shade(*ray, hi, lights, bounceCount);\n \n \/\/ otherwise color it white (as a hit)\n else\n col.Set(0.929, 0.929, 0.929);\n \n \/\/ if we hit nothing, draw the background\n }else{\n Point p = Point((float) pX \/ w, (float) pY \/ h, 0.0);\n Color b = background.sample(p);\n col = b;\n }\n \n \/\/ compute average color\n float rAvg = (colAvg.r * s + col.r) \/ (float) (s + 1);\n float gAvg = (colAvg.g * s + col.g) \/ (float) (s + 1);\n float bAvg = (colAvg.b * s + col.b) \/ (float) (s + 1);\n colAvg.Set(rAvg, gAvg, bAvg);\n \n \/\/ compute color variances\n rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) \/ (float) (s + 1);\n gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) \/ (float) (s + 1);\n bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) \/ (float) (s + 1);\n \n \/\/ calculate and update brightness average using XYZ and Lab space\n float Y = perR * rAvg + perG * gAvg + perB * bAvg;\n float Y13 = Y;\n if(Y13 > Ycutoff)\n Y13 = pow(Y13, 1.0 \/ 3.0);\n else\n Y13 = Yprecalc * Y13 + (4.0 \/ 29.0);\n brightness = (116.0 * Y13 - 16.0) \/ 100.0;\n \n \/\/ increment sample count\n s++;\n \n \/\/ watch for errors at any individual sample, terminate thread if so\n if(colAvg[0] != colAvg[0] || colAvg[1] != colAvg[1] || colAvg[2] != colAvg[2]){\n cout << \"ERROR - pixel \" << pixel << \" & sample \" << s << endl;\n s = sampleMax;\n pixel = size;\n }\n }\n \n \/\/ gamma correction\n if(gammaCorr){\n colAvg.r = pow(colAvg.r, 1.0 \/ 2.2);\n colAvg.g = pow(colAvg.g, 1.0 \/ 2.2);\n colAvg.b = pow(colAvg.b, 1.0 \/ 2.2);\n }\n \n \/\/ color the pixel image\n img[pixel] = Color24(colAvg);\n \n \/\/ update the z-buffer image, if necessary\n if(zBuffer)\n zImg[pixel] = zAvg;\n \n \/\/ update the sample count image, if necessary\n if(sampleCount)\n sampleImg[pixel] = s;\n \n \/\/ re-assign next pixel (naive, but works)\n pixel += numThreads;\n }\n}\n\n\n\/\/ create variables for camera ray generation\nvoid cameraRayVars(){\n float fov = camera.fov * M_PI \/ 180.0;\n float aspectRatio = (float) w \/ (float) h;\n imageDistance = camera.focalDist;\n float imageTipY = imageDistance * tan(fov \/ 2.0);\n float imageTipX = imageTipY * aspectRatio;\n float dX = (2.0 * imageTipX) \/ (float) w;\n float dY = (2.0 * imageTipY) \/ (float) h;\n imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);\n dXV = new Point(dX, 0.0, 0.0);\n dYV = new Point(0.0, -dY, 0.0);\n firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);\n \n \/\/ set up camera transformation (only need to rotate coordinates)\n c = new Transformation();\n Matrix *rotate = new cyMatrix3f();\n rotate->Set(camera.cross, camera.up, -camera.dir);\n c->transform(*rotate);\n \n \/\/ get normalized rays on the focal plane\n dVx = new Point(1.0, 0.0, 0.0);\n dVy = new Point(0.0, 1.0, 0.0);\n}\n\n\n\/\/ compute camera ray direction\nPoint cameraRay(float pX, float pY, Point offset){\n Point ray = firstPixel + (*dXV * pX) + (*dYV * pY) - offset;\n ray.Normalize();\n return ray;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/error_scope.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2012,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file error_scope.H\n * @brief definitions which create a scope for automatic error handling\n *\/\n\n#ifndef __FAPI2_ERROR_SCOPE__\n#define __FAPI2_ERROR_SCOPE__\n\n#include <stdint.h>\n#include <thread>\n#include <stdio.h>\n#include <return_code.H>\n\n\/\/\/ @cond\n#define FAPI_VA_NARGS_IMPL(_1, _2, _3, _4, _5, N, ...) N\n#define FAPI_VA_NARGS(...) FAPI_VA_NARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)\n\n#define FAPI_TRY_IMPL2(count, ...) FAPI_TRY ## count (__VA_ARGS__)\n#define FAPI_TRY_IMPL(count, ...) FAPI_TRY_IMPL2(count, __VA_ARGS__)\n\n#define FAPI_TRY_NO_TRACE( __operation__ ) \\\n if ((fapi2::current_err = (__operation__)) != fapi2::FAPI2_RC_SUCCESS) \\\n { \\\n goto clean_up; \\\n }\n\n\/\/ Why debug? Because this isn't a mechanism to gather FFDC\n\/\/ one should be using FAPI_ASSERT. However, it is nice to\n\/\/ have a conditional trace in the event of a failure in the\n\/\/ operation, so that's why this is here.\n#define FAPI_TRY_TRACE( __operation__, ... ) \\\n if ((fapi2::current_err = (__operation__)) != fapi2::FAPI2_RC_SUCCESS) \\\n { \\\n FAPI_DBG(__VA_ARGS__); \\\n goto clean_up; \\\n }\n\n#define FAPI_TRY1 FAPI_TRY_NO_TRACE\n#define FAPI_TRY2 FAPI_TRY_TRACE\n#define FAPI_TRY3 FAPI_TRY_TRACE\n#define FAPI_TRY4 FAPI_TRY_TRACE\n#define FAPI_TRY5 FAPI_TRY_TRACE\n\/\/\/ @endcond\n\n\/\/\/\n\/\/\/ @brief Wrapper to check an operation for an error state\n\/\/\/ and jump to the label cleam_up if there is an error.\n\/\/\/ @param[in] __operation__ an operation which returns a fapi::ReturnCode\n\/\/\/ @param[in] Optional vararg format\/agruments for trace output.\n\/\/\/ @note This implementation does not support PIB error masks or\n\/\/\/ FSP operational states.\n\/\/\/ @warning The trace information is only going to be seen during\n\/\/\/ debug, it's not an error or informational trace. This is because\n\/\/\/ traces might not be seen in the field. If you want information\n\/\/\/ you will see on a field error, use FAPI_ASSERT.\n\/\/\/\n#ifdef DOXYGEN\n#define FAPI_TRY(__operation__, ...) FAPI_TRY_IMPL\n#else\n#define FAPI_TRY(...) FAPI_TRY_IMPL(FAPI_VA_NARGS(__VA_ARGS__), __VA_ARGS__)\n#endif\n\n\/\/\/\n\/\/\/ @brief Assert a conditional is true.\n\/\/\/ If it is not, the FFDC gathering function is called and the\n\/\/\/ trace is output as a FAPI error trace.\n\/\/\/ @param[in] __conditional__ the condition to assert\n\/\/\/ @param[in] __ffdc__ the FFDC gathering function\n\/\/\/ @param[in] ... varargs, as input to FAPI_ERR\n\/\/\/\n#define FAPI_ASSERT( __conditional__, __ffdc__, ... ) \\\n if (! (__conditional__)) \\\n { \\\n (__ffdc__).execute(); \\\n FAPI_ERR(__VA_ARGS__); \\\n goto clean_up; \\\n }\n\n\n#endif\n<commit_msg>Add doxygen fapi2 tooling, doc clean up<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/error_scope.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2012,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file error_scope.H\n * @brief definitions which create a scope for automatic error handling\n *\/\n\n#ifndef __FAPI2_ERROR_SCOPE__\n#define __FAPI2_ERROR_SCOPE__\n\n#include <stdint.h>\n#include <thread>\n#include <stdio.h>\n#include <return_code.H>\n\n\/\/\/ @cond\n#define FAPI_VA_NARGS_IMPL(_1, _2, _3, _4, _5, N, ...) N\n#define FAPI_VA_NARGS(...) FAPI_VA_NARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)\n\n#define FAPI_TRY_IMPL2(count, ...) FAPI_TRY ## count (__VA_ARGS__)\n#define FAPI_TRY_IMPL(count, ...) FAPI_TRY_IMPL2(count, __VA_ARGS__)\n\n#define FAPI_TRY_NO_TRACE( __operation__ ) \\\n if ((fapi2::current_err = (__operation__)) != fapi2::FAPI2_RC_SUCCESS) \\\n { \\\n goto clean_up; \\\n }\n\n\/\/ Why debug? Because this isn't a mechanism to gather FFDC\n\/\/ one should be using FAPI_ASSERT. However, it is nice to\n\/\/ have a conditional trace in the event of a failure in the\n\/\/ operation, so that's why this is here.\n#define FAPI_TRY_TRACE( __operation__, ... ) \\\n if ((fapi2::current_err = (__operation__)) != fapi2::FAPI2_RC_SUCCESS) \\\n { \\\n FAPI_DBG(__VA_ARGS__); \\\n goto clean_up; \\\n }\n\n#define FAPI_TRY1 FAPI_TRY_NO_TRACE\n#define FAPI_TRY2 FAPI_TRY_TRACE\n#define FAPI_TRY3 FAPI_TRY_TRACE\n#define FAPI_TRY4 FAPI_TRY_TRACE\n#define FAPI_TRY5 FAPI_TRY_TRACE\n\/\/\/ @endcond\n\n\/\/\/\n\/\/\/ @brief Wrapper to check an operation for an error state\n\/\/\/ and jump to the label cleam_up if there is an error.\n\/\/\/ @param[in] __operation__ an operation which returns a fapi::ReturnCode\n\/\/\/ @param[in] ... vararg format\/agruments for trace output (optional)\n\/\/\/ @note This implementation does not support PIB error masks or\n\/\/\/ FSP operational states.\n\/\/\/ @warning The trace information is only going to be seen during\n\/\/\/ debug, it's not an error or informational trace. This is because\n\/\/\/ traces might not be seen in the field. If you want information\n\/\/\/ you will see on a field error, use FAPI_ASSERT.\n\/\/\/\n#ifdef DOXYGEN\n#define FAPI_TRY(__operation__, ...) FAPI_TRY_IMPL\n#else\n#define FAPI_TRY(...) FAPI_TRY_IMPL(FAPI_VA_NARGS(__VA_ARGS__), __VA_ARGS__)\n#endif\n\n\/\/\/\n\/\/\/ @brief Assert a conditional is true.\n\/\/\/ If it is not, the FFDC gathering function is called and the\n\/\/\/ trace is output as a FAPI error trace.\n\/\/\/ @param[in] __conditional__ the condition to assert\n\/\/\/ @param[in] __ffdc__ the FFDC gathering function\n\/\/\/ @param[in] ... varargs, as input to FAPI_ERR\n\/\/\/\n#define FAPI_ASSERT( __conditional__, __ffdc__, ... ) \\\n if (! (__conditional__)) \\\n { \\\n (__ffdc__).execute(); \\\n FAPI_ERR(__VA_ARGS__); \\\n goto clean_up; \\\n }\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SIAddIMGInit.cpp - Add any required IMG inits ---------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/\/ Any MIMG instructions that use tfe or lwe require an initialization of the\n\/\/\/ result register that will be written in the case of a memory access failure\n\/\/\/ The required code is also added to tie this init code to the result of the\n\/\/\/ img instruction\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\n#define DEBUG_TYPE \"si-img-init\"\n#include \"AMDGPU.h\"\n#include \"AMDGPUSubtarget.h\"\n#include \"SIInstrInfo.h\"\n#include \"MCTargetDesc\/AMDGPUMCTargetDesc.h\"\n#include \"Utils\/AMDGPULaneDominator.h\"\n#include \"llvm\/CodeGen\/LiveIntervals.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nclass SIAddIMGInit : public MachineFunctionPass {\npublic:\n static char ID;\n\npublic:\n SIAddIMGInit() : MachineFunctionPass(ID) {\n initializeSIAddIMGInitPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override { return \"SI Add IMG init\"; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\n} \/\/ End anonymous namespace.\n\nINITIALIZE_PASS(SIAddIMGInit, DEBUG_TYPE,\n \"SI Add IMG Init\", false, false)\n\nchar SIAddIMGInit::ID = 0;\n\nchar &llvm::SIAddIMGInitID = SIAddIMGInit::ID;\n\nFunctionPass *llvm::createSIAddIMGInitPass() {\n return new SIAddIMGInit();\n}\n\nbool SIAddIMGInit::runOnMachineFunction(MachineFunction &MF) {\n MachineRegisterInfo &MRI = MF.getRegInfo();\n const SISubtarget &ST = MF.getSubtarget<SISubtarget>();\n const SIInstrInfo *TII = ST.getInstrInfo();\n const SIRegisterInfo *RI = ST.getRegisterInfo();\n bool Changed = false;\n\n for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();\n BI != BE; ++BI) {\n MachineBasicBlock &MBB = *BI;\n MachineBasicBlock::iterator I, Next;\n for (I = MBB.begin(); I != MBB.end(); I = Next) {\n Next = std::next(I);\n MachineInstr &MI = *I;\n\n auto Opcode = MI.getOpcode();\n if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore()) {\n MachineOperand *tfe = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);\n MachineOperand *lwe = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);\n MachineOperand *d16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);\n\n \/\/ Abandon attempts for instructions that don't have tfe or lwe fields\n \/\/ Shouldn't be any at this point, but this will allow for future\n \/\/ variants.\n if (!tfe && !lwe)\n continue;\n\n unsigned tfeVal = tfe->getImm();\n unsigned lweVal = lwe->getImm();\n unsigned d16Val = d16 ? d16->getImm() : 0;\n\n if (tfeVal || lweVal) {\n \/\/ At least one of TFE or LWE are non-zero\n \/\/ We have to insert a suitable initialization of the result value and\n \/\/ tie this to the dest of the image instruction.\n\n const DebugLoc &DL = MI.getDebugLoc();\n\n int dstIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),\n AMDGPU::OpName::vdata);\n\n \/\/ Calculate which dword we have to initialize to 0.\n MachineOperand *MO_Dmask =\n TII->getNamedOperand(MI, AMDGPU::OpName::dmask);\n \/\/ Abandon attempt if no dmask operand is found.\n if (!MO_Dmask) continue;\n\n unsigned dmask = MO_Dmask->getImm();\n \/\/ Determine the number of active lanes taking into account the\n \/\/ Gather4 special case\n unsigned activeLanes =\n TII->isGather4(Opcode) ? 4 : countPopulation(dmask);\n \/\/ Subreg indices are counted from 1\n \/\/ When D16 then we want next whole VGPR after write data.\n bool Packed = !ST.hasUnpackedD16VMem();\n unsigned initIdx =\n d16Val && Packed ? ((activeLanes + 1) >> 1) + 1\n : activeLanes + 1;\n\n \/\/ Abandon attempt if the dst size isn't large enough\n \/\/ - this is in fact an error but this is picked up elsewhere and\n \/\/ reported correctly.\n uint32_t dstSize =\n RI->getRegSizeInBits(*TII->getOpRegClass(MI, dstIdx)) \/ 32;\n if (dstSize < initIdx) continue;\n\n \/\/ Create a register for the intialization value.\n unsigned prevDst =\n MRI.createVirtualRegister(TII->getOpRegClass(MI, dstIdx));\n BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), prevDst);\n\n unsigned newDst = 0; \/\/ Final initialized value will be in here\n\n \/\/ If PRTStrictNull feature is enabled (the default) then initialize\n \/\/ all the result registers to 0, otherwise just the error indication\n \/\/ register (VGPRn+1)\n unsigned sizeLeft = ST.usePRTStrictNull() ? initIdx : 1;\n unsigned currIdx = ST.usePRTStrictNull() ? 1 : initIdx;\n\n for ( ; sizeLeft ; sizeLeft--, currIdx++ ) {\n newDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, dstIdx));\n \/\/ Initialize dword\n unsigned subReg =\n MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);\n BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), subReg)\n .addImm(0);\n \/\/ Insert into the super-reg\n BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), newDst)\n .addReg(prevDst)\n .addReg(subReg)\n .addImm(currIdx);\n\n prevDst = newDst;\n }\n\n \/\/ Add as an implicit operand\n MachineInstrBuilder(MF,MI).addReg(newDst, RegState::Implicit);\n\n \/\/ Tie the just added implicit operand to the dst\n MI.tieOperands(dstIdx, MI.getNumOperands() - 1);\n\n Changed = true;\n }\n }\n }\n }\n\n return Changed;\n}\n<commit_msg>[AMDGPU] Fixes in the image instruction init pass<commit_after>\/\/===-- SIAddIMGInit.cpp - Add any required IMG inits ---------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/\/ Any MIMG instructions that use tfe or lwe require an initialization of the\n\/\/\/ result register that will be written in the case of a memory access failure\n\/\/\/ The required code is also added to tie this init code to the result of the\n\/\/\/ img instruction\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\n#define DEBUG_TYPE \"si-img-init\"\n#include \"AMDGPU.h\"\n#include \"AMDGPUSubtarget.h\"\n#include \"SIInstrInfo.h\"\n#include \"MCTargetDesc\/AMDGPUMCTargetDesc.h\"\n#include \"Utils\/AMDGPULaneDominator.h\"\n#include \"llvm\/CodeGen\/LiveIntervals.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nclass SIAddIMGInit : public MachineFunctionPass {\npublic:\n static char ID;\n\npublic:\n SIAddIMGInit() : MachineFunctionPass(ID) {\n initializeSIAddIMGInitPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override { return \"SI Add IMG init\"; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\n} \/\/ End anonymous namespace.\n\nINITIALIZE_PASS(SIAddIMGInit, DEBUG_TYPE,\n \"SI Add IMG Init\", false, false)\n\nchar SIAddIMGInit::ID = 0;\n\nchar &llvm::SIAddIMGInitID = SIAddIMGInit::ID;\n\nFunctionPass *llvm::createSIAddIMGInitPass() {\n return new SIAddIMGInit();\n}\n\nbool SIAddIMGInit::runOnMachineFunction(MachineFunction &MF) {\n MachineRegisterInfo &MRI = MF.getRegInfo();\n const SISubtarget &ST = MF.getSubtarget<SISubtarget>();\n const SIInstrInfo *TII = ST.getInstrInfo();\n const SIRegisterInfo *RI = ST.getRegisterInfo();\n bool Changed = false;\n\n for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();\n BI != BE; ++BI) {\n MachineBasicBlock &MBB = *BI;\n MachineBasicBlock::iterator I, Next;\n for (I = MBB.begin(); I != MBB.end(); I = Next) {\n Next = std::next(I);\n MachineInstr &MI = *I;\n\n auto Opcode = MI.getOpcode();\n if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore()) {\n MachineOperand *tfe = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);\n MachineOperand *lwe = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);\n MachineOperand *d16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);\n\n \/\/ Abandon attempts for instructions that don't have tfe or lwe fields\n \/\/ Shouldn't be any at this point, but this will allow for future\n \/\/ variants.\n if (!tfe && !lwe)\n continue;\n\n unsigned tfeVal = tfe->getImm();\n unsigned lweVal = lwe->getImm();\n unsigned d16Val = d16 ? d16->getImm() : 0;\n\n if (tfeVal || lweVal) {\n \/\/ At least one of TFE or LWE are non-zero\n \/\/ We have to insert a suitable initialization of the result value and\n \/\/ tie this to the dest of the image instruction.\n\n const DebugLoc &DL = MI.getDebugLoc();\n\n int dstIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),\n AMDGPU::OpName::vdata);\n\n \/\/ Calculate which dword we have to initialize to 0.\n MachineOperand *MO_Dmask =\n TII->getNamedOperand(MI, AMDGPU::OpName::dmask);\n \/\/ Abandon attempt if no dmask operand is found.\n if (!MO_Dmask) continue;\n\n unsigned dmask = MO_Dmask->getImm();\n \/\/ Determine the number of active lanes taking into account the\n \/\/ Gather4 special case\n unsigned activeLanes =\n TII->isGather4(Opcode) ? 4 : countPopulation(dmask);\n \/\/ Subreg indices are counted from 1\n \/\/ When D16 then we want next whole VGPR after write data.\n bool Packed = !ST.hasUnpackedD16VMem();\n unsigned initIdx =\n d16Val && Packed ? ((activeLanes + 1) >> 1) + 1\n : activeLanes + 1;\n\n \/\/ Abandon attempt if the dst size isn't large enough\n \/\/ - this is in fact an error but this is picked up elsewhere and\n \/\/ reported correctly.\n uint32_t dstSize =\n RI->getRegSizeInBits(*TII->getOpRegClass(MI, dstIdx)) \/ 32;\n if (dstSize < initIdx) continue;\n\n \/\/ Create a register for the intialization value.\n unsigned prevDst =\n MRI.createVirtualRegister(TII->getOpRegClass(MI, dstIdx));\n unsigned newDst = 0; \/\/ Final initialized value will be in here\n\n \/\/ If PRTStrictNull feature is enabled (the default) then initialize\n \/\/ all the result registers to 0, otherwise just the error indication\n \/\/ register (VGPRn+1)\n unsigned sizeLeft = ST.usePRTStrictNull() ? initIdx : 1;\n unsigned currIdx = ST.usePRTStrictNull() ? 1 : initIdx;\n\n if (dstSize == 1) {\n \/\/ In this case we can just initialize the result directly\n BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), prevDst)\n .addImm(0);\n newDst = prevDst;\n } else {\n BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), prevDst);\n for (; sizeLeft; sizeLeft--, currIdx++) {\n newDst =\n MRI.createVirtualRegister(TII->getOpRegClass(MI, dstIdx));\n \/\/ Initialize dword\n unsigned subReg =\n MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);\n BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), subReg)\n .addImm(0);\n \/\/ Insert into the super-reg\n BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), newDst)\n .addReg(prevDst)\n .addReg(subReg)\n .addImm(currIdx);\n\n prevDst = newDst;\n }\n }\n\n \/\/ Add as an implicit operand\n MachineInstrBuilder(MF,MI).addReg(newDst, RegState::Implicit);\n\n \/\/ Tie the just added implicit operand to the dst\n MI.tieOperands(dstIdx, MI.getNumOperands() - 1);\n\n Changed = true;\n }\n }\n }\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/gamepad_shared_memory_reader.h\"\n\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"content\/common\/gamepad_messages.h\"\n#include \"content\/public\/renderer\/render_thread.h\"\n#include \"content\/common\/gamepad_hardware_buffer.h\"\n#include \"ipc\/ipc_sync_message_filter.h\"\n\nnamespace content {\n\nGamepadSharedMemoryReader::GamepadSharedMemoryReader() {\n memset(ever_interacted_with_, 0, sizeof(ever_interacted_with_));\n CHECK(RenderThread::Get()->Send(new GamepadHostMsg_StartPolling(\n &renderer_shared_memory_handle_)));\n \/\/ If we don't get a valid handle from the browser, don't try to Map (we're\n \/\/ probably out of memory or file handles).\n bool valid_handle = base::SharedMemory::IsHandleValid(\n renderer_shared_memory_handle_);\n UMA_HISTOGRAM_BOOLEAN(\"Gamepad.ValidSharedMemoryHandle\", valid_handle);\n if (!valid_handle)\n return;\n renderer_shared_memory_.reset(\n new base::SharedMemory(renderer_shared_memory_handle_, true));\n CHECK(renderer_shared_memory_->Map(sizeof(GamepadHardwareBuffer)));\n void *memory = renderer_shared_memory_->memory();\n CHECK(memory);\n gamepad_hardware_buffer_ =\n static_cast<GamepadHardwareBuffer*>(memory);\n}\n\nvoid GamepadSharedMemoryReader::SampleGamepads(WebKit::WebGamepads& gamepads) {\n WebKit::WebGamepads read_into;\n TRACE_EVENT0(\"GAMEPAD\", \"SampleGamepads\");\n\n if (!base::SharedMemory::IsHandleValid(renderer_shared_memory_handle_))\n return;\n\n \/\/ Only try to read this many times before failing to avoid waiting here\n \/\/ very long in case of contention with the writer. TODO(scottmg) Tune this\n \/\/ number (as low as 1?) if histogram shows distribution as mostly\n \/\/ 0-and-maximum.\n const int kMaximumContentionCount = 10;\n int contention_count = -1;\n base::subtle::Atomic32 version;\n do {\n version = gamepad_hardware_buffer_->sequence.ReadBegin();\n memcpy(&read_into, &gamepad_hardware_buffer_->buffer, sizeof(read_into));\n ++contention_count;\n if (contention_count == kMaximumContentionCount)\n break;\n } while (gamepad_hardware_buffer_->sequence.ReadRetry(version));\n UMA_HISTOGRAM_COUNTS(\"Gamepad.ReadContentionCount\", contention_count);\n\n if (contention_count >= kMaximumContentionCount) {\n \/\/ We failed to successfully read, presumably because the hardware\n \/\/ thread was taking unusually long. Don't copy the data to the output\n \/\/ buffer, and simply leave what was there before.\n return;\n }\n\n \/\/ New data was read successfully, copy it into the output buffer.\n memcpy(&gamepads, &read_into, sizeof(gamepads));\n\n \/\/ Override the \"connected\" with false until the user has interacted\n \/\/ with the gamepad. This is to prevent fingerprinting on drive-by pages.\n for (unsigned i = 0; i < WebKit::WebGamepads::itemsLengthCap; ++i) {\n WebKit::WebGamepad& pad = gamepads.items[i];\n \/\/ If the device is physically connected, then check if we should\n \/\/ keep it disabled. We track if any of the primary 4 buttons have been\n \/\/ pressed to determine a reasonable intentional interaction from the user.\n if (pad.connected) {\n if (ever_interacted_with_[i])\n continue;\n const unsigned kPrimaryInteractionButtons = 4;\n for (unsigned j = 0; j < kPrimaryInteractionButtons; ++j)\n ever_interacted_with_[i] |= pad.buttons[j] > 0.5f;\n \/\/ If we've not previously set, and the user still hasn't touched\n \/\/ these buttons, then don't pass the data on to the Chromium port.\n if (!ever_interacted_with_[i])\n pad.connected = false;\n }\n }\n}\n\nGamepadSharedMemoryReader::~GamepadSharedMemoryReader() {\n RenderThread::Get()->Send(new GamepadHostMsg_StopPolling());\n}\n\n} \/\/ namespace content\n<commit_msg>Coverity: Initialize a member variable.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/gamepad_shared_memory_reader.h\"\n\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"content\/common\/gamepad_messages.h\"\n#include \"content\/public\/renderer\/render_thread.h\"\n#include \"content\/common\/gamepad_hardware_buffer.h\"\n#include \"ipc\/ipc_sync_message_filter.h\"\n\nnamespace content {\n\nGamepadSharedMemoryReader::GamepadSharedMemoryReader()\n : gamepad_hardware_buffer_(NULL) {\n memset(ever_interacted_with_, 0, sizeof(ever_interacted_with_));\n CHECK(RenderThread::Get()->Send(new GamepadHostMsg_StartPolling(\n &renderer_shared_memory_handle_)));\n \/\/ If we don't get a valid handle from the browser, don't try to Map (we're\n \/\/ probably out of memory or file handles).\n bool valid_handle = base::SharedMemory::IsHandleValid(\n renderer_shared_memory_handle_);\n UMA_HISTOGRAM_BOOLEAN(\"Gamepad.ValidSharedMemoryHandle\", valid_handle);\n if (!valid_handle)\n return;\n renderer_shared_memory_.reset(\n new base::SharedMemory(renderer_shared_memory_handle_, true));\n CHECK(renderer_shared_memory_->Map(sizeof(GamepadHardwareBuffer)));\n void *memory = renderer_shared_memory_->memory();\n CHECK(memory);\n gamepad_hardware_buffer_ =\n static_cast<GamepadHardwareBuffer*>(memory);\n}\n\nvoid GamepadSharedMemoryReader::SampleGamepads(WebKit::WebGamepads& gamepads) {\n WebKit::WebGamepads read_into;\n TRACE_EVENT0(\"GAMEPAD\", \"SampleGamepads\");\n\n if (!base::SharedMemory::IsHandleValid(renderer_shared_memory_handle_))\n return;\n\n \/\/ Only try to read this many times before failing to avoid waiting here\n \/\/ very long in case of contention with the writer. TODO(scottmg) Tune this\n \/\/ number (as low as 1?) if histogram shows distribution as mostly\n \/\/ 0-and-maximum.\n const int kMaximumContentionCount = 10;\n int contention_count = -1;\n base::subtle::Atomic32 version;\n do {\n version = gamepad_hardware_buffer_->sequence.ReadBegin();\n memcpy(&read_into, &gamepad_hardware_buffer_->buffer, sizeof(read_into));\n ++contention_count;\n if (contention_count == kMaximumContentionCount)\n break;\n } while (gamepad_hardware_buffer_->sequence.ReadRetry(version));\n UMA_HISTOGRAM_COUNTS(\"Gamepad.ReadContentionCount\", contention_count);\n\n if (contention_count >= kMaximumContentionCount) {\n \/\/ We failed to successfully read, presumably because the hardware\n \/\/ thread was taking unusually long. Don't copy the data to the output\n \/\/ buffer, and simply leave what was there before.\n return;\n }\n\n \/\/ New data was read successfully, copy it into the output buffer.\n memcpy(&gamepads, &read_into, sizeof(gamepads));\n\n \/\/ Override the \"connected\" with false until the user has interacted\n \/\/ with the gamepad. This is to prevent fingerprinting on drive-by pages.\n for (unsigned i = 0; i < WebKit::WebGamepads::itemsLengthCap; ++i) {\n WebKit::WebGamepad& pad = gamepads.items[i];\n \/\/ If the device is physically connected, then check if we should\n \/\/ keep it disabled. We track if any of the primary 4 buttons have been\n \/\/ pressed to determine a reasonable intentional interaction from the user.\n if (pad.connected) {\n if (ever_interacted_with_[i])\n continue;\n const unsigned kPrimaryInteractionButtons = 4;\n for (unsigned j = 0; j < kPrimaryInteractionButtons; ++j)\n ever_interacted_with_[i] |= pad.buttons[j] > 0.5f;\n \/\/ If we've not previously set, and the user still hasn't touched\n \/\/ these buttons, then don't pass the data on to the Chromium port.\n if (!ever_interacted_with_[i])\n pad.connected = false;\n }\n }\n}\n\nGamepadSharedMemoryReader::~GamepadSharedMemoryReader() {\n RenderThread::Get()->Send(new GamepadHostMsg_StopPolling());\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n *\n * Copyright (C) 2018 Robert Heller D\/B\/A Deepwoods Software\n *\t\t\t51 Locke Hill Road\n *\t\t\tWendell, MA 01379-9728\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * \\file LinuxGpio.hxx\n *\n * Defines GPIO pins using the Linux sysfs ABI.\n * \n * \\section HOWTOUSE How to use\n * \n * You need to use the GPIO_PIN macro at the bottom, like this:\n * \n * GPIO_PIN(LED1, GpioOutputSafeLow, 27); \/\/ Defines LED1_Pin, for GPIO 27, initialized low. \n * GPIO_PIN(CSLow, GpioOutputSafeHighInvert, 5); \/\/ Defines CSLow_Pin, for GPIO 5, initialized high, with the set logic inverted. \n * GPIO_PIN(Button1, GpioInputActiveLow, 20); \/\/ Defines Button1_Pin, for GPIO 20, avtive low -- return true when shorted to ground. \n *\n * Classes available for the second macro parameter are:\n * \n * - GpioOutputSafeLow Output initialized low, true = high\n * - GpioOutputSafeLowInvert Output initialized low, true = low\n * - GpioOutputSafeHigh Output initialized high, true = high\n * - GpioOutputSafeHighInvert Output initialized high, true = high\n * - GpioInputActiveHigh Input, high = true\n * - GpioInputActiveLow Input, low = true\n * \n * Be sure to use GpioInitializer to create an Initializer class:\n * \n * typedef GpioInitializer<LED1_Pin, CSLow_Pin, Button1_Pin> GpioInit;\n * \n * somewhere in main.cxx, and then in appl_main():\n * \n * GpioInit::hw_init();\n * \n * This makes sure the GPIO pins are properly set up (eg exported to \/sys\/class\/gpio\/).\n * Also, the process running the node needs to be in group gpio.\n * \n * @author Robert Heller\n * @date 10 October 2018\n *\/\n\n#ifndef __LINUXGPIO_HXX\n#define __LINUXGPIO_HXX\n\n#include \"freertos_drivers\/common\/GpioWrapper.hxx\"\n#include \"os\/Gpio.hxx\"\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n\n\/\/\/ Defines a GPIO output pin. Writes to this structure will change the output\n\/\/\/ level of the pin. Reads will return the pin's current level.\n\/\/\/ Uses Linux sysfs ABI\n\/\/\/\n\/\/\/ The pin is set to output at initialization time, with the level defined by\n\/\/\/ `SAFE_VALUE'.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <int PIN_NUM> class LinuxGpio\n{\npublic:\n \/\/\/ Number of the pin\n static constexpr const uint32_t PIN = PIN_NUM;\n \n \/\/\/ Export pin\n static void export_pin()\n {\n FILE *fp = fopen(\"\/sys\/class\/gpio\/export\",\"w\");\n fprintf(fp,\"%d\\n\",PIN);\n fclose(fp);\n \/\/ 50ms delay IS needed while kernel changes ownership of created GPIO directory\n usleep(50000); \n }\n \n \/\/\/ Sets pin to output.\n static void set_output()\n {\n char dirname[40];\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = open(dirname,O_WRONLY);\n write(dfd,\"out\\n\",4);\n close(dfd);\n }\n \/\/\/ Sets pin to input.\n static void set_input()\n {\n char dirname[40];\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = open(dirname,O_WRONLY);\n write(dfd,\"in\\n\",3);\n close(dfd);\n }\n \/\/\/ Sets output to HIGH.\n static void set_on()\n {\n char valname[40];\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_WRONLY);\n write(vfd,\"1\\n\",2);\n close(vfd);\n }\n \/\/\/ Sets output to LOW.\n static void set_off()\n {\n char valname[40];\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_WRONLY);\n write(vfd,\"0\\n\",2);\n close(vfd);\n }\n \/\/\/ @return input pin level.\n static bool get()\n {\n char valname[40], c;\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_RDONLY);\n read(vfd,&c,1);\n close(vfd);\n return (c != '0');\n }\n \/\/\/ Set output pin level. @param value is the level to set to.\n static void set(bool value)\n {\n if (value)\n {\n set_on();\n }\n else\n {\n set_off();\n }\n }\n\n \/\/\/ Toggles output pin value.\n static void toggle()\n {\n set(!get());\n }\n\n \/\/\/ @return true if pin is configured as an output pin.\n static bool is_output()\n {\n char dirname[40], c;\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = open(dirname,O_RDONLY);\n read(dfd,&c,1);\n close(dfd);\n return (c == 'o');\n }\n};\n\n\n\/\/\/ Generic output pin\ntemplate <class Base, bool SAFE_VALUE, bool INVERT = false> \nstruct GpioOutputPin : public Base\n{\npublic:\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n Base::export_pin();\n Base::set_output();\n Base::set(SAFE_VALUE);\n }\n \/\/\/ Sets the hardware pin to a safe value.\n static void hw_set_to_safe()\n {\n Base::set(SAFE_VALUE);\n }\n \/\/\/ Sets the output pinm @param value if true, output is set to HIGH, if\n \/\/\/ false, output is set to LOW.\n static void set(bool value)\n {\n if (INVERT)\n {\n Base::set(!value);\n }\n else\n {\n Base::set(value);\n }\n }\n \/\/\/ @return the static Gpio instance.\n static constexpr const Gpio *instance()\n {\n return GpioWrapper<GpioOutputPin<Base,SAFE_VALUE,INVERT>>::instance();\n }\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeLow : public GpioOutputPin<Defs, false>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low\n\/\/\/ level. All set() commands are acted upon by inverting the value.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeLowInvert : public GpioOutputPin<Defs, false, true>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeHigh : public GpioOutputPin<Defs, true>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high\n\/\/\/ level. All set() commands are acted upon by inverting the value.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeHighInvert : public GpioOutputPin<Defs, true, true>\n{\n};\n\/\/\/ Generic input pin\ntemplate <class Base, bool ACTIVE_HIGH = true> \nstruct GpioInputPin : public Base\n{\npublic:\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n Base::export_pin();\n Base::set_input();\n }\n \/\/\/ Sets the hardware pin to a safe state. \n static void hw_set_to_safe()\n {\n hw_init();\n }\n \/\/\/ @return the static Gpio instance.\n static const Gpio *instance()\n {\n return GpioWrapper<GpioInputPin<Base>>::instance();\n }\n static bool get()\n {\n if (ACTIVE_HIGH)\n {\n return Base::get();\n }\n else\n {\n return !Base::get();\n }\n }\n};\n\n\/\/\/ Defines a GPIO input pin, Active High (High == true).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioInputActiveHigh : public GpioInputPin<Defs, true>\n{\n};\n\n\/\/\/ Defines a GPIO input pin, Active Low (Low == true).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioInputActiveLow : public GpioInputPin<Defs, false>\n{\n};\n\n\n\n\/\/\/ Helper macro for defining GPIO pins on Linux-based microcontrollers (like the Raspberry Pi or Bagle Bone.\n\/\/\/\n\/\/\/ @param NAME is the basename of the declaration. For NAME==FOO the macro\n\/\/\/ declared FOO_Pin as a structure on which the read-write functions will be\n\/\/\/ available.\n\/\/\/\n\/\/\/ @param BaseClass is the initialization structure, such as @ref LedPin, or\n\/\/\/ @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.\n\/\/\/\n\/\/\/ @param NUM is the pin number, such as 3 \n\/\/\/\n\/\/\/ Example:\n\/\/\/ GPIO_PIN(FOO, GpioOutputSafeLow, 3);\n\/\/\/ ...\n\/\/\/ FOO_Pin::set(true);\n#define GPIO_PIN(NAME, BaseClass, NUM) \\\n typedef BaseClass<LinuxGpio<NUM>> NAME##_Pin\n\n#endif \/\/ __LINUXGPIO_HXX\n\n<commit_msg>Updates to LinuxGPIO.hxx to handle slower Linux ARM boards, like the Beagles. (#299)<commit_after>\/** \\copyright\n *\n * Copyright (C) 2018 Robert Heller D\/B\/A Deepwoods Software\n *\t\t\t51 Locke Hill Road\n *\t\t\tWendell, MA 01379-9728\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * \\file LinuxGpio.hxx\n *\n * Defines GPIO pins using the Linux sysfs ABI.\n * \n * \\section HOWTOUSE How to use\n * \n * You need to use the GPIO_PIN macro at the bottom, like this:\n * \n * GPIO_PIN(LED1, GpioOutputSafeLow, 27); \/\/ Defines LED1_Pin, for GPIO 27, initialized low. \n * GPIO_PIN(CSLow, GpioOutputSafeHighInvert, 5); \/\/ Defines CSLow_Pin, for GPIO 5, initialized high, with the set logic inverted. \n * GPIO_PIN(Button1, GpioInputActiveLow, 20); \/\/ Defines Button1_Pin, for GPIO 20, avtive low -- return true when shorted to ground. \n *\n * Classes available for the second macro parameter are:\n * \n * - GpioOutputSafeLow Output initialized low, true = high\n * - GpioOutputSafeLowInvert Output initialized low, true = low\n * - GpioOutputSafeHigh Output initialized high, true = high\n * - GpioOutputSafeHighInvert Output initialized high, true = high\n * - GpioInputActiveHigh Input, high = true\n * - GpioInputActiveLow Input, low = true\n * \n * Be sure to use GpioInitializer to create an Initializer class:\n * \n * typedef GpioInitializer<LED1_Pin, CSLow_Pin, Button1_Pin> GpioInit;\n * \n * somewhere in main.cxx, and then in appl_main():\n * \n * GpioInit::hw_init();\n * \n * This makes sure the GPIO pins are properly set up (eg exported to \/sys\/class\/gpio\/).\n * Also, the process running the node needs to be in group gpio.\n * \n * @author Robert Heller\n * @date 10 October 2018\n *\/\n\n#ifndef __LINUXGPIO_HXX\n#define __LINUXGPIO_HXX\n\n#include \"freertos_drivers\/common\/GpioWrapper.hxx\"\n#include \"os\/Gpio.hxx\"\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <unistd.h>\n\n\/\/\/ Defines a GPIO output pin. Writes to this structure will change the output\n\/\/\/ level of the pin. Reads will return the pin's current level.\n\/\/\/ Uses Linux sysfs ABI\n\/\/\/\n\/\/\/ The pin is set to output at initialization time, with the level defined by\n\/\/\/ `SAFE_VALUE'.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <int PIN_NUM> class LinuxGpio\n{\npublic:\n \/\/\/ Number of the pin\n static constexpr const uint32_t PIN = PIN_NUM;\n \n \/\/\/ Export pin\n static void export_pin()\n {\n FILE *fp = fopen(\"\/sys\/class\/gpio\/export\",\"w\");\n fprintf(fp,\"%d\\n\",PIN);\n fclose(fp);\n \/\/ 50ms delay IS needed while kernel changes ownership of created GPIO directory\n usleep(50000); \n }\n \n \/\/\/ Sets pin to output.\n static void set_output()\n {\n char dirname[40];\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = -1;\n while ((dfd = open(dirname,O_WRONLY)) < 0) {\n export_pin();\n }\n write(dfd,\"out\\n\",4);\n close(dfd);\n }\n \/\/\/ Sets pin to input.\n static void set_input()\n {\n char dirname[40];\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = -1;\n while ((dfd = open(dirname,O_WRONLY)) < 0) {\n export_pin();\n }\n write(dfd,\"in\\n\",3);\n close(dfd);\n }\n \/\/\/ Sets output to HIGH.\n static void set_on()\n {\n char valname[40];\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_WRONLY);\n write(vfd,\"1\\n\",2);\n close(vfd);\n }\n \/\/\/ Sets output to LOW.\n static void set_off()\n {\n char valname[40];\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_WRONLY);\n write(vfd,\"0\\n\",2);\n close(vfd);\n }\n \/\/\/ @return input pin level.\n static bool get()\n {\n char valname[40], c;\n snprintf(valname,sizeof(valname),\"\/sys\/class\/gpio\/gpio%d\/value\",PIN);\n int vfd = open(valname,O_RDONLY);\n read(vfd,&c,1);\n close(vfd);\n return (c != '0');\n }\n \/\/\/ Set output pin level. @param value is the level to set to.\n static void set(bool value)\n {\n if (value)\n {\n set_on();\n }\n else\n {\n set_off();\n }\n }\n\n \/\/\/ Toggles output pin value.\n static void toggle()\n {\n set(!get());\n }\n\n \/\/\/ @return true if pin is configured as an output pin.\n static bool is_output()\n {\n char dirname[40], c;\n snprintf(dirname,sizeof(dirname),\"\/sys\/class\/gpio\/gpio%d\/direction\",PIN);\n int dfd = open(dirname,O_RDONLY);\n read(dfd,&c,1);\n close(dfd);\n return (c == 'o');\n }\n};\n\n\n\/\/\/ Generic output pin\ntemplate <class Base, bool SAFE_VALUE, bool INVERT = false> \nstruct GpioOutputPin : public Base\n{\npublic:\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n Base::export_pin();\n Base::set_output();\n Base::set(SAFE_VALUE);\n }\n \/\/\/ Sets the hardware pin to a safe value.\n static void hw_set_to_safe()\n {\n Base::set(SAFE_VALUE);\n }\n \/\/\/ Sets the output pinm @param value if true, output is set to HIGH, if\n \/\/\/ false, output is set to LOW.\n static void set(bool value)\n {\n if (INVERT)\n {\n Base::set(!value);\n }\n else\n {\n Base::set(value);\n }\n }\n \/\/\/ @return the static Gpio instance.\n static constexpr const Gpio *instance()\n {\n return GpioWrapper<GpioOutputPin<Base,SAFE_VALUE,INVERT>>::instance();\n }\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeLow : public GpioOutputPin<Defs, false>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low\n\/\/\/ level. All set() commands are acted upon by inverting the value.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeLowInvert : public GpioOutputPin<Defs, false, true>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeHigh : public GpioOutputPin<Defs, true>\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high\n\/\/\/ level. All set() commands are acted upon by inverting the value.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioOutputSafeHighInvert : public GpioOutputPin<Defs, true, true>\n{\n};\n\/\/\/ Generic input pin\ntemplate <class Base, bool ACTIVE_HIGH = true> \nstruct GpioInputPin : public Base\n{\npublic:\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n Base::export_pin();\n Base::set_input();\n }\n \/\/\/ Sets the hardware pin to a safe state. \n static void hw_set_to_safe()\n {\n hw_init();\n }\n \/\/\/ @return the static Gpio instance.\n static const Gpio *instance()\n {\n return GpioWrapper<GpioInputPin<Base>>::instance();\n }\n static bool get()\n {\n if (ACTIVE_HIGH)\n {\n return Base::get();\n }\n else\n {\n return !Base::get();\n }\n }\n};\n\n\/\/\/ Defines a GPIO input pin, Active High (High == true).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioInputActiveHigh : public GpioInputPin<Defs, true>\n{\n};\n\n\/\/\/ Defines a GPIO input pin, Active Low (Low == true).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate <class Defs>\nstruct GpioInputActiveLow : public GpioInputPin<Defs, false>\n{\n};\n\n\n\n\/\/\/ Helper macro for defining GPIO pins on Linux-based microcontrollers (like the Raspberry Pi or Bagle Bone.\n\/\/\/\n\/\/\/ @param NAME is the basename of the declaration. For NAME==FOO the macro\n\/\/\/ declared FOO_Pin as a structure on which the read-write functions will be\n\/\/\/ available.\n\/\/\/\n\/\/\/ @param BaseClass is the initialization structure, such as @ref LedPin, or\n\/\/\/ @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.\n\/\/\/\n\/\/\/ @param NUM is the pin number, such as 3 \n\/\/\/\n\/\/\/ Example:\n\/\/\/ GPIO_PIN(FOO, GpioOutputSafeLow, 3);\n\/\/\/ ...\n\/\/\/ FOO_Pin::set(true);\n#define GPIO_PIN(NAME, BaseClass, NUM) \\\n typedef BaseClass<LinuxGpio<NUM>> NAME##_Pin\n\n#endif \/\/ __LINUXGPIO_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include \"LogConfigReader.hpp\"\n#include \"LogManager.hpp\"\n#include \"LogRotationManager.hpp\"\n#include <yaml-cpp\/yaml.h>\n#include <fmt\/format.h>\n\n\nstatic const std::string CONFIG_FILE_NAME = \"log-config.yml\";\n\nbool ParseLogLevel(YAML::Node const &level_node, LogLevel &dest, std::string const &error_msg)\n{\n\tstatic const std::unordered_map<std::string, LogLevel> loglevel_str_map = {\n\t\t{ \"Debug\", LogLevel::DEBUG },\n\t\t{ \"Info\", LogLevel::INFO },\n\t\t{ \"Warning\", LogLevel::WARNING },\n\t\t{ \"Error\", LogLevel::ERROR },\n\t\t{ \"Fatal\", LogLevel::FATAL },\n\t\t{ \"Verbose\", LogLevel::VERBOSE },\n\t\t{ \"All\", LogLevel::ALL }\n\t};\n\n\tauto const &level_str = level_node.as<std::string>(std::string());\n\tif (level_str.empty())\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\tfmt::format(\"{}: invalid log level specified\", error_msg));\n\t\treturn false;\n\t}\n\n\tauto const &it = loglevel_str_map.find(level_str);\n\tif (it == loglevel_str_map.end())\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\tfmt::format(\"{}: invalid log level '{}'\", error_msg, level_str));\n\t\treturn false;\n\t}\n\n\tdest |= (*it).second;\n\treturn true;\n}\n\nbool ParseDuration(std::string duration, LogRotationTimeType &dest)\n{\n\tstd::transform(duration.begin(), duration.end(), duration.begin(), tolower);\n\tif (duration == \"daily\")\n\t\tdest = LogRotationTimeType::DAILY;\n\telse if (duration == \"weekly\")\n\t\tdest = LogRotationTimeType::WEEKLY;\n\telse if (duration == \"monthly\")\n\t\tdest = LogRotationTimeType::MONTHLY;\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nbool ParseFileSize(std::string const &size, unsigned int &dest_in_kb)\n{\n\tauto type_idx = size.find_first_not_of(\"0123456789\");\n\tif (type_idx == std::string::npos || type_idx == 0)\n\t\treturn false;\n\n\tint size_val = std::stoi(size); \/\/ works as long as the string starts with a number\n\tif (size.length() != (type_idx + 2) || tolower(size.at(type_idx + 1)) != 'b')\n\t\treturn false;\n\n\tswitch (tolower(size.at(type_idx)))\n\t{\n\tcase 'k':\n\t\tdest_in_kb = size_val;\n\t\tbreak;\n\tcase 'm':\n\t\tdest_in_kb = size_val * 1000;\n\t\tbreak;\n\tcase 'g':\n\t\tdest_in_kb = size_val * 1000 * 1000;\n\t\tbreak;\n\tdefault:\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nLoggerConfig GetInternalLogConfig()\n{\n\tLoggerConfig config;\n\tconfig.Level = LogLevel::ALL;\n\tconfig.PrintToConsole = true;\n\treturn config;\n}\n\n\nvoid LogConfig::ParseConfigFile()\n{\n\tYAML::Node root;\n\ttry\n\t{\n\t\troot = YAML::LoadFile(CONFIG_FILE_NAME);\n\t}\n\tcatch (const YAML::ParserException& e)\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::ERROR, \n\t\t\tfmt::format(\"could not parse log config file: {}\", e.what()));\n\t\treturn;\n\t}\n\tcatch (const YAML::BadFile&)\n\t{\n\t\t\/\/ file likely doesn't exist, ignore\n\t\treturn;\n\t}\n\n\tstd::lock_guard<std::mutex> lock(_configLock);\n\n\t_loggerConfigs.clear();\n\n\t\/\/ default settings for log-core logger\n\t_loggerConfigs.emplace(\"log-core\", GetInternalLogConfig());\n\n\tYAML::Node const &loggers = root[\"Logger\"];\n\tfor (YAML::const_iterator y_it = loggers.begin(); y_it != loggers.end(); ++y_it)\n\t{\n\t\tauto module_name = y_it->first.as<std::string>(std::string());\n\t\tif (module_name.empty() || module_name == \"log-core\")\n\t\t{\n\t\t\tLogManager::Get()->LogInternal(LogLevel::ERROR,\n\t\t\t\tfmt::format(\"could not parse logger config: invalid logger name\"));\n\t\t\tcontinue;\n\t\t}\n\t\tLoggerConfig config;\n\n\t\tstd::string const error_msg_loglevel = fmt::format(\n\t\t\t\"could not parse log level setting for logger '{}'\", module_name);\n\t\tYAML::Node const &log_levels = y_it->second[\"LogLevel\"];\n\t\tif (log_levels && !log_levels.IsNull()) \/\/ log level is specified, remove default log level\n\t\t\tconfig.Level = LogLevel::NONE;\n\n\t\tif (log_levels.IsSequence())\n\t\t{\n\t\t\tfor (YAML::const_iterator y_it_level = log_levels.begin();\n\t\t\t\ty_it_level != log_levels.end(); ++y_it_level)\n\t\t\t{\n\t\t\t\tParseLogLevel(*y_it_level, config.Level, error_msg_loglevel);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tParseLogLevel(log_levels, config.Level, error_msg_loglevel);\n\t\t}\n\n\t\tYAML::Node const &log_rotation = y_it->second[\"LogRotation\"];\n\t\tif (log_rotation)\n\t\t{\n\t\t\tYAML::Node const\n\t\t\t\t&type = log_rotation[\"Type\"],\n\t\t\t\t&trigger = log_rotation[\"Trigger\"];\n\t\t\tif (type && trigger)\n\t\t\t{\n\t\t\t\tstatic const std::unordered_map<std::string, LogRotationType>\n\t\t\t\t\tlogrotation_type_str_map = {\n\t\t\t\t\t{ \"Date\", LogRotationType::DATE },\n\t\t\t\t\t{ \"Size\", LogRotationType::SIZE }\n\t\t\t\t};\n\t\t\t\tauto const &type_str = type.as<std::string>();\n\t\t\t\tauto const &it = logrotation_type_str_map.find(type_str);\n\t\t\t\tif (it != logrotation_type_str_map.end())\n\t\t\t\t{\n\t\t\t\t\tconfig.Rotation.Type = it->second;\n\t\t\t\t\tswitch (config.Rotation.Type)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase LogRotationType::DATE:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto time_str = trigger.as<std::string>(\"Daily\");\n\t\t\t\t\t\t\tif (!ParseDuration(time_str, config.Rotation.Value.Date))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig.Rotation.Value.Date = LogRotationTimeType::DAILY;\n\t\t\t\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\t\t\t\"could not parse date log rotation duration \" \\\n\t\t\t\t\t\t\t\t\t\t\"for logger '{}': invalid duration \\\"{}\\\"\",\n\t\t\t\t\t\t\t\t\t\tmodule_name, time_str));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase LogRotationType::SIZE:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto size_str = trigger.as<std::string>(\"100MB\");\n\t\t\t\t\t\t\tif (!ParseFileSize(size_str, config.Rotation.Value.FileSize))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig.Rotation.Value.FileSize = 100;\n\t\t\t\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\t\t\t\"could not parse file log rotation size \" \\\n\t\t\t\t\t\t\t\t\t\t\"for logger '{}': invalid size \\\"{}\\\"\",\n\t\t\t\t\t\t\t\t\t\tmodule_name, size_str));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} break;\n\t\t\t\t\t}\n\n\t\t\t\t\tYAML::Node const &backup_count = log_rotation[\"BackupCount\"];\n\t\t\t\t\tif (backup_count && backup_count.IsScalar())\n\t\t\t\t\t\tconfig.Rotation.BackupCount = backup_count.as<int>(config.Rotation.BackupCount);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\"could not parse log rotation setting for logger '{}': \" \\\n\t\t\t\t\t\t\t\"invalid log rotation type '{}'\", \n\t\t\t\t\t\t\tmodule_name, type_str));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\"could not parse log rotation setting for logger '{}': \" \\\n\t\t\t\t\t\t\"log rotation not completely specified\",\n\t\t\t\t\t\tmodule_name));\n\t\t\t}\n\t\t}\n\n\t\tYAML::Node const &console_print = y_it->second[\"PrintToConsole\"];\n\t\tif (console_print && console_print.IsScalar())\n\t\t\tconfig.PrintToConsole = console_print.as<bool>(config.PrintToConsole);\n\n\t\tYAML::Node const &append_logs = y_it->second[\"Append\"];\n\t\tif (append_logs && append_logs.IsScalar())\n\t\t\tconfig.Append = append_logs.as<bool>(config.Append);\n\n\t\t_loggerConfigs.emplace(module_name, std::move(config));\n\t}\n\n\t_levelConfigs.clear();\n\tYAML::Node const &levels = root[\"LogLevel\"];\n\tfor (YAML::const_iterator y_it = levels.begin(); y_it != levels.end(); ++y_it)\n\t{\n\t\tLogLevel level = static_cast<LogLevel>(0); \/\/ initialize to zero as ParseLogLevel OR's levels\n\t\tif (!ParseLogLevel(y_it->first, level, \"could not parse log level setting\"))\n\t\t\tcontinue;\n\n\t\tLogLevelConfig config;\n\t\tYAML::Node const &console_print_opt = y_it->second[\"PrintToConsole\"];\n\t\tif (console_print_opt && console_print_opt.IsScalar())\n\t\t\tconfig.PrintToConsole = console_print_opt.as<bool>(config.PrintToConsole);\n\n\t\t_levelConfigs.emplace(level, std::move(config));\n\t}\n\n\t\/\/global config settings\n\t_globalConfig = GlobalConfig();\n\tYAML::Node const &logtime_format = root[\"LogTimeFormat\"];\n\tif (logtime_format && logtime_format.IsScalar())\n\t\t_globalConfig.LogTimeFormat = logtime_format.as<std::string>(_globalConfig.LogTimeFormat);\n\n\tYAML::Node const &enable_colors = root[\"EnableColors\"];\n\tif (enable_colors && enable_colors.IsScalar())\n\t\t_globalConfig.EnableColors = enable_colors.as<bool>(_globalConfig.EnableColors);\n\n\tYAML::Node const &disable_debug = root[\"DisableDebugInfo\"];\n\tif (disable_debug && disable_debug.IsScalar())\n\t\t_globalConfig.DisableDebugInfo = disable_debug.as<bool>(_globalConfig.DisableDebugInfo);\n}\n\nvoid LogConfig::Initialize()\n{\n\tParseConfigFile();\n\t_fileWatcher.reset(new FileChangeDetector(CONFIG_FILE_NAME, [this]()\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::INFO, \n\t\t\t\"config file change detected, reloading...\");\n\t\tParseConfigFile();\n\t\tLogManager::Get()->LogInternal(LogLevel::INFO,\n\t\t\t\"reloading finished\");\n\t}));\n}\n<commit_msg>validate log time format string<commit_after>#include \"LogConfigReader.hpp\"\n#include \"LogManager.hpp\"\n#include \"LogRotationManager.hpp\"\n#include <yaml-cpp\/yaml.h>\n#include <fmt\/format.h>\n\n\nstatic const std::string CONFIG_FILE_NAME = \"log-config.yml\";\n\nbool ParseLogLevel(YAML::Node const &level_node, LogLevel &dest, std::string const &error_msg)\n{\n\tstatic const std::unordered_map<std::string, LogLevel> loglevel_str_map = {\n\t\t{ \"Debug\", LogLevel::DEBUG },\n\t\t{ \"Info\", LogLevel::INFO },\n\t\t{ \"Warning\", LogLevel::WARNING },\n\t\t{ \"Error\", LogLevel::ERROR },\n\t\t{ \"Fatal\", LogLevel::FATAL },\n\t\t{ \"Verbose\", LogLevel::VERBOSE },\n\t\t{ \"All\", LogLevel::ALL }\n\t};\n\n\tauto const &level_str = level_node.as<std::string>(std::string());\n\tif (level_str.empty())\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\tfmt::format(\"{}: invalid log level specified\", error_msg));\n\t\treturn false;\n\t}\n\n\tauto const &it = loglevel_str_map.find(level_str);\n\tif (it == loglevel_str_map.end())\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\tfmt::format(\"{}: invalid log level '{}'\", error_msg, level_str));\n\t\treturn false;\n\t}\n\n\tdest |= (*it).second;\n\treturn true;\n}\n\nbool ParseDuration(std::string duration, LogRotationTimeType &dest)\n{\n\tstd::transform(duration.begin(), duration.end(), duration.begin(), tolower);\n\tif (duration == \"daily\")\n\t\tdest = LogRotationTimeType::DAILY;\n\telse if (duration == \"weekly\")\n\t\tdest = LogRotationTimeType::WEEKLY;\n\telse if (duration == \"monthly\")\n\t\tdest = LogRotationTimeType::MONTHLY;\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nbool ParseFileSize(std::string const &size, unsigned int &dest_in_kb)\n{\n\tauto type_idx = size.find_first_not_of(\"0123456789\");\n\tif (type_idx == std::string::npos || type_idx == 0)\n\t\treturn false;\n\n\tint size_val = std::stoi(size); \/\/ works as long as the string starts with a number\n\tif (size.length() != (type_idx + 2) || tolower(size.at(type_idx + 1)) != 'b')\n\t\treturn false;\n\n\tswitch (tolower(size.at(type_idx)))\n\t{\n\tcase 'k':\n\t\tdest_in_kb = size_val;\n\t\tbreak;\n\tcase 'm':\n\t\tdest_in_kb = size_val * 1000;\n\t\tbreak;\n\tcase 'g':\n\t\tdest_in_kb = size_val * 1000 * 1000;\n\t\tbreak;\n\tdefault:\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nLoggerConfig GetInternalLogConfig()\n{\n\tLoggerConfig config;\n\tconfig.Level = LogLevel::ALL;\n\tconfig.PrintToConsole = true;\n\treturn config;\n}\n\nbool ValidateTimeFormat(std::string const &format)\n{\n\tsize_t idx = 0;\n\twhile (idx < format.size())\n\t{\n\t\tif (format.at(idx++) != '%')\n\t\t\tcontinue;\n\n\t\tswitch (format.at(idx++))\n\t\t{\n\t\tcase 'a':\n\t\tcase 'A':\n\t\tcase 'b':\n\t\tcase 'B':\n\t\tcase 'c':\n\t\tcase 'C':\n\t\tcase 'd':\n\t\tcase 'D':\n\t\tcase 'e':\n\t\tcase 'F':\n\t\tcase 'g':\n\t\tcase 'G':\n\t\tcase 'h':\n\t\tcase 'H':\n\t\tcase 'I':\n\t\tcase 'j':\n\t\tcase 'm':\n\t\tcase 'M':\n\t\tcase 'n':\n\t\tcase 'p':\n\t\tcase 'r':\n\t\tcase 'R':\n\t\tcase 'S':\n\t\tcase 't':\n\t\tcase 'T':\n\t\tcase 'u':\n\t\tcase 'U':\n\t\tcase 'V':\n\t\tcase 'w':\n\t\tcase 'W':\n\t\tcase 'x':\n\t\tcase 'X':\n\t\tcase 'y':\n\t\tcase 'Y':\n\t\tcase 'z':\n\t\tcase 'Z':\n\t\tcase '%':\n\t\t\tcontinue;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n\nvoid LogConfig::ParseConfigFile()\n{\n\tYAML::Node root;\n\ttry\n\t{\n\t\troot = YAML::LoadFile(CONFIG_FILE_NAME);\n\t}\n\tcatch (const YAML::ParserException& e)\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::ERROR, \n\t\t\tfmt::format(\"could not parse log config file: {}\", e.what()));\n\t\treturn;\n\t}\n\tcatch (const YAML::BadFile&)\n\t{\n\t\t\/\/ file likely doesn't exist, ignore\n\t\treturn;\n\t}\n\n\tstd::lock_guard<std::mutex> lock(_configLock);\n\n\t_loggerConfigs.clear();\n\n\t\/\/ default settings for log-core logger\n\t_loggerConfigs.emplace(\"log-core\", GetInternalLogConfig());\n\n\tYAML::Node const &loggers = root[\"Logger\"];\n\tfor (YAML::const_iterator y_it = loggers.begin(); y_it != loggers.end(); ++y_it)\n\t{\n\t\tauto module_name = y_it->first.as<std::string>(std::string());\n\t\tif (module_name.empty() || module_name == \"log-core\")\n\t\t{\n\t\t\tLogManager::Get()->LogInternal(LogLevel::ERROR,\n\t\t\t\tfmt::format(\"could not parse logger config: invalid logger name\"));\n\t\t\tcontinue;\n\t\t}\n\t\tLoggerConfig config;\n\n\t\tstd::string const error_msg_loglevel = fmt::format(\n\t\t\t\"could not parse log level setting for logger '{}'\", module_name);\n\t\tYAML::Node const &log_levels = y_it->second[\"LogLevel\"];\n\t\tif (log_levels && !log_levels.IsNull()) \/\/ log level is specified, remove default log level\n\t\t\tconfig.Level = LogLevel::NONE;\n\n\t\tif (log_levels.IsSequence())\n\t\t{\n\t\t\tfor (YAML::const_iterator y_it_level = log_levels.begin();\n\t\t\t\ty_it_level != log_levels.end(); ++y_it_level)\n\t\t\t{\n\t\t\t\tParseLogLevel(*y_it_level, config.Level, error_msg_loglevel);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tParseLogLevel(log_levels, config.Level, error_msg_loglevel);\n\t\t}\n\n\t\tYAML::Node const &log_rotation = y_it->second[\"LogRotation\"];\n\t\tif (log_rotation)\n\t\t{\n\t\t\tYAML::Node const\n\t\t\t\t&type = log_rotation[\"Type\"],\n\t\t\t\t&trigger = log_rotation[\"Trigger\"];\n\t\t\tif (type && trigger)\n\t\t\t{\n\t\t\t\tstatic const std::unordered_map<std::string, LogRotationType>\n\t\t\t\t\tlogrotation_type_str_map = {\n\t\t\t\t\t{ \"Date\", LogRotationType::DATE },\n\t\t\t\t\t{ \"Size\", LogRotationType::SIZE }\n\t\t\t\t};\n\t\t\t\tauto const &type_str = type.as<std::string>();\n\t\t\t\tauto const &it = logrotation_type_str_map.find(type_str);\n\t\t\t\tif (it != logrotation_type_str_map.end())\n\t\t\t\t{\n\t\t\t\t\tconfig.Rotation.Type = it->second;\n\t\t\t\t\tswitch (config.Rotation.Type)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase LogRotationType::DATE:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto time_str = trigger.as<std::string>(\"Daily\");\n\t\t\t\t\t\t\tif (!ParseDuration(time_str, config.Rotation.Value.Date))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig.Rotation.Value.Date = LogRotationTimeType::DAILY;\n\t\t\t\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\t\t\t\"could not parse date log rotation duration \" \\\n\t\t\t\t\t\t\t\t\t\t\"for logger '{}': invalid duration \\\"{}\\\"\",\n\t\t\t\t\t\t\t\t\t\tmodule_name, time_str));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} break;\n\t\t\t\t\t\tcase LogRotationType::SIZE:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto size_str = trigger.as<std::string>(\"100MB\");\n\t\t\t\t\t\t\tif (!ParseFileSize(size_str, config.Rotation.Value.FileSize))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfig.Rotation.Value.FileSize = 100;\n\t\t\t\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\t\t\t\"could not parse file log rotation size \" \\\n\t\t\t\t\t\t\t\t\t\t\"for logger '{}': invalid size \\\"{}\\\"\",\n\t\t\t\t\t\t\t\t\t\tmodule_name, size_str));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} break;\n\t\t\t\t\t}\n\n\t\t\t\t\tYAML::Node const &backup_count = log_rotation[\"BackupCount\"];\n\t\t\t\t\tif (backup_count && backup_count.IsScalar())\n\t\t\t\t\t\tconfig.Rotation.BackupCount = backup_count.as<int>(config.Rotation.BackupCount);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\t\"could not parse log rotation setting for logger '{}': \" \\\n\t\t\t\t\t\t\t\"invalid log rotation type '{}'\", \n\t\t\t\t\t\t\tmodule_name, type_str));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING,\n\t\t\t\t\tfmt::format(\n\t\t\t\t\t\t\"could not parse log rotation setting for logger '{}': \" \\\n\t\t\t\t\t\t\"log rotation not completely specified\",\n\t\t\t\t\t\tmodule_name));\n\t\t\t}\n\t\t}\n\n\t\tYAML::Node const &console_print = y_it->second[\"PrintToConsole\"];\n\t\tif (console_print && console_print.IsScalar())\n\t\t\tconfig.PrintToConsole = console_print.as<bool>(config.PrintToConsole);\n\n\t\tYAML::Node const &append_logs = y_it->second[\"Append\"];\n\t\tif (append_logs && append_logs.IsScalar())\n\t\t\tconfig.Append = append_logs.as<bool>(config.Append);\n\n\t\t_loggerConfigs.emplace(module_name, std::move(config));\n\t}\n\n\t_levelConfigs.clear();\n\tYAML::Node const &levels = root[\"LogLevel\"];\n\tfor (YAML::const_iterator y_it = levels.begin(); y_it != levels.end(); ++y_it)\n\t{\n\t\tLogLevel level = static_cast<LogLevel>(0); \/\/ initialize to zero as ParseLogLevel OR's levels\n\t\tif (!ParseLogLevel(y_it->first, level, \"could not parse log level setting\"))\n\t\t\tcontinue;\n\n\t\tLogLevelConfig config;\n\t\tYAML::Node const &console_print_opt = y_it->second[\"PrintToConsole\"];\n\t\tif (console_print_opt && console_print_opt.IsScalar())\n\t\t\tconfig.PrintToConsole = console_print_opt.as<bool>(config.PrintToConsole);\n\n\t\t_levelConfigs.emplace(level, std::move(config));\n\t}\n\n\t\/\/global config settings\n\t_globalConfig = GlobalConfig();\n\tYAML::Node const &logtime_format = root[\"LogTimeFormat\"];\n\tif (logtime_format && logtime_format.IsScalar())\n\t{\n\t\tauto const time_format = logtime_format.as<std::string>(_globalConfig.LogTimeFormat);\n\t\tif (ValidateTimeFormat(time_format))\n\t\t{\n\t\t\t_globalConfig.LogTimeFormat = time_format;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLogManager::Get()->LogInternal(LogLevel::WARNING, fmt::format(\n\t\t\t\t\"could not parse log time format: '{:s}' \" \\\n\t\t\t\t\"is not a valid time format string\", time_format));\n\t\t}\n\t}\n\n\tYAML::Node const &enable_colors = root[\"EnableColors\"];\n\tif (enable_colors && enable_colors.IsScalar())\n\t\t_globalConfig.EnableColors = enable_colors.as<bool>(_globalConfig.EnableColors);\n\n\tYAML::Node const &disable_debug = root[\"DisableDebugInfo\"];\n\tif (disable_debug && disable_debug.IsScalar())\n\t\t_globalConfig.DisableDebugInfo = disable_debug.as<bool>(_globalConfig.DisableDebugInfo);\n}\n\nvoid LogConfig::Initialize()\n{\n\tParseConfigFile();\n\t_fileWatcher.reset(new FileChangeDetector(CONFIG_FILE_NAME, [this]()\n\t{\n\t\tLogManager::Get()->LogInternal(LogLevel::INFO, \n\t\t\t\"config file change detected, reloading...\");\n\t\tParseConfigFile();\n\t\tLogManager::Get()->LogInternal(LogLevel::INFO,\n\t\t\t\"reloading finished\");\n\t}));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n#include \"jnc_ct_ScheduleLauncherFunction.h\"\n#include \"jnc_ct_Module.h\"\n\nnamespace jnc {\nnamespace ct {\n\n\/\/.............................................................................\n\nbool\nScheduleLauncherFunction::compile ()\n{\n\tbool result;\n\n\tsize_t argCount = m_type->getArgArray ().getCount ();\n\n\tchar buffer [256];\n\tsl::Array <Value> argValueArray (ref::BufKind_Stack, buffer, sizeof (buffer));\n\targValueArray.setCount (argCount);\n\n\tm_module->m_functionMgr.internalPrologue (this, argValueArray, argCount);\n\n\tValue functionPtrValue = argValueArray [0];\n\tValue schedulerValue = argValueArray [1];\n\tValue scheduleValue;\n\n\tresult = m_module->m_operatorMgr.memberOperator (schedulerValue, \"schedule\", &scheduleValue);\n\tif (!result)\n\t\treturn false;\n\n\tif (argCount > 2)\n\t{\n\t\tsl::BoxList <Value> argList;\n\t\tfor (size_t i = 2; i < argCount; i++)\n\t\t\targList.insertTail (argValueArray [i]);\n\n\t\tresult = m_module->m_operatorMgr.closureOperator (&functionPtrValue, &argList);\n\t\tif (!result)\n\t\t\treturn false;\n\t}\n\n\tresult = m_module->m_operatorMgr.callOperator (scheduleValue, functionPtrValue);\n\tif (!result)\n\t\treturn false;\n\n\tm_module->m_functionMgr.internalEpilogue ();\n\treturn true;\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace ct\n} \/\/ namespace jnc\n<commit_msg>[jancy] critical update: schedule launcher functions should mark gc-root arguments (otherwise it's extremely error-prone when calling scheduled function pointers from C++)<commit_after>#include \"pch.h\"\n#include \"jnc_ct_ScheduleLauncherFunction.h\"\n#include \"jnc_ct_Module.h\"\n\nnamespace jnc {\nnamespace ct {\n\n\/\/.............................................................................\n\nbool\nScheduleLauncherFunction::compile ()\n{\n\tbool result;\n\n\tsize_t argCount = m_type->getArgArray ().getCount ();\n\n\tchar buffer [256];\n\tsl::Array <Value> argValueArray (ref::BufKind_Stack, buffer, sizeof (buffer));\n\targValueArray.setCount (argCount);\n\n\tm_module->m_functionMgr.internalPrologue (this, argValueArray, argCount);\n\n\tValue functionPtrValue = argValueArray [0];\n\tValue schedulerValue = argValueArray [1];\n\tValue scheduleValue;\n\n\tresult = m_module->m_operatorMgr.memberOperator (schedulerValue, \"schedule\", &scheduleValue);\n\tif (!result)\n\t\treturn false;\n\n\tif (argCount > 2)\n\t{\n\t\tsl::BoxList <Value> argList;\n\t\tfor (size_t i = 2; i < argCount; i++)\n\t\t{\n\t\t\tValue argValue = argValueArray [i];\n\t\t\targList.insertTail (argValue);\n\n\t\t\tType* argType = argValue.getType ();\n\t\t\tif (argType->getFlags () & TypeFlag_GcRoot)\n\t\t\t{\n\t\t\t\tValue argVariable;\n\t\t\t\tm_module->m_llvmIrBuilder.createAlloca (argType, \"gcRoot\", NULL, &argVariable);\n\t\t\t\tm_module->m_llvmIrBuilder.createStore (argValue, argVariable);\n\t\t\t\tm_module->m_gcShadowStackMgr.markGcRoot (argVariable, argType);\n\t\t\t}\n\t\t}\n\n\t\tresult = m_module->m_operatorMgr.closureOperator (&functionPtrValue, &argList);\n\t\tif (!result)\n\t\t\treturn false;\n\t}\n\n\tresult = m_module->m_operatorMgr.callOperator (scheduleValue, functionPtrValue);\n\tif (!result)\n\t\treturn false;\n\n\tm_module->m_functionMgr.internalEpilogue ();\n\treturn true;\n}\n\n\/\/.............................................................................\n\n} \/\/ namespace ct\n} \/\/ namespace jnc\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#include \"port\/likely.h\"\n#include \"util\/mutexlock.h\"\n#include \"util\/thread_status_impl.h\"\n\nnamespace rocksdb {\n\nThreadStatusImpl thread_local_status;\n\n#if ROCKSDB_USING_THREAD_STATUS\n__thread ThreadStatusData* ThreadStatusImpl::thread_status_data_ = nullptr;\nstd::mutex ThreadStatusImpl::thread_list_mutex_;\nstd::unordered_set<ThreadStatusData*> ThreadStatusImpl::thread_data_set_;\nstd::unordered_map<const void*, ConstantColumnFamilyInfo*>\n ThreadStatusImpl::cf_info_map_;\nstd::unordered_map<const void*, std::unordered_set<const void*>>\n ThreadStatusImpl::db_key_map_;\n\nThreadStatusImpl::~ThreadStatusImpl() {\n assert(thread_data_set_.size() == 0);\n}\n\nvoid ThreadStatusImpl::UnregisterThread() {\n if (thread_status_data_ != nullptr) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n thread_data_set_.erase(thread_status_data_);\n delete thread_status_data_;\n thread_status_data_ = nullptr;\n }\n}\n\nvoid ThreadStatusImpl::SetThreadType(\n ThreadStatus::ThreadType ttype) {\n auto* data = InitAndGet();\n data->thread_type.store(ttype, std::memory_order_relaxed);\n}\n\nvoid ThreadStatusImpl::SetColumnFamilyInfoKey(\n const void* cf_key) {\n auto* data = InitAndGet();\n data->cf_key.store(cf_key, std::memory_order_relaxed);\n}\n\nvoid ThreadStatusImpl::SetEventInfoPtr(\n const ThreadEventInfo* event_info) {\n auto* data = InitAndGet();\n data->event_info.store(event_info, std::memory_order_relaxed);\n}\n\nStatus ThreadStatusImpl::GetThreadList(\n std::vector<ThreadStatus>* thread_list) const {\n thread_list->clear();\n std::vector<std::shared_ptr<ThreadStatusData>> valid_list;\n\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n for (auto* thread_data : thread_data_set_) {\n assert(thread_data);\n auto thread_type = thread_data->thread_type.load(\n std::memory_order_relaxed);\n auto cf_key = thread_data->cf_key.load(\n std::memory_order_relaxed);\n auto iter = cf_info_map_.find(cf_key);\n assert(cf_key == 0 || iter != cf_info_map_.end());\n auto* cf_info = iter != cf_info_map_.end() ?\n iter->second : nullptr;\n auto* event_info = thread_data->event_info.load(\n std::memory_order_relaxed);\n const std::string* db_name = nullptr;\n const std::string* cf_name = nullptr;\n const std::string* event_name = nullptr;\n if (cf_info != nullptr) {\n db_name = &cf_info->db_name;\n cf_name = &cf_info->cf_name;\n \/\/ display lower-level info only when higher-level info is available.\n if (event_info != nullptr) {\n event_name = &event_info->event_name;\n }\n }\n thread_list->emplace_back(\n thread_data->thread_id, thread_type,\n db_name ? *db_name : \"\",\n cf_name ? *cf_name : \"\",\n event_name ? *event_name : \"\");\n }\n\n return Status::OK();\n}\n\nThreadStatusData* ThreadStatusImpl::InitAndGet() {\n if (UNLIKELY(thread_status_data_ == nullptr)) {\n thread_status_data_ = new ThreadStatusData();\n thread_status_data_->thread_id = reinterpret_cast<uint64_t>(\n thread_status_data_);\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n thread_data_set_.insert(thread_status_data_);\n }\n return thread_status_data_;\n}\n\nvoid ThreadStatusImpl::NewColumnFamilyInfo(\n const void* db_key, const std::string& db_name,\n const void* cf_key, const std::string& cf_name) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n\n cf_info_map_[cf_key] = new ConstantColumnFamilyInfo(db_key, db_name, cf_name);\n db_key_map_[db_key].insert(cf_key);\n}\n\nvoid ThreadStatusImpl::EraseColumnFamilyInfo(const void* cf_key) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n auto cf_pair = cf_info_map_.find(cf_key);\n assert(cf_pair != cf_info_map_.end());\n\n auto* cf_info = cf_pair->second;\n assert(cf_info);\n\n \/\/ Remove its entry from db_key_map_ by the following steps:\n \/\/ 1. Obtain the entry in db_key_map_ whose set contains cf_key\n \/\/ 2. Remove it from the set.\n auto db_pair = db_key_map_.find(cf_info->db_key);\n assert(db_pair != db_key_map_.end());\n size_t result __attribute__((unused)) = db_pair->second.erase(cf_key);\n assert(result);\n\n delete cf_info;\n result = cf_info_map_.erase(cf_key);\n assert(result);\n}\n\nvoid ThreadStatusImpl::EraseDatabaseInfo(const void* db_key) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n auto db_pair = db_key_map_.find(db_key);\n if (UNLIKELY(db_pair == db_key_map_.end())) {\n \/\/ In some occasional cases such as DB::Open fails, we won't\n \/\/ register ColumnFamilyInfo for a db.\n return;\n }\n\n size_t result __attribute__((unused)) = 0;\n for (auto cf_key : db_pair->second) {\n auto cf_pair = cf_info_map_.find(cf_key);\n assert(cf_pair != cf_info_map_.end());\n delete cf_pair->second;\n result = cf_info_map_.erase(cf_key);\n assert(result);\n }\n db_key_map_.erase(db_key);\n}\n\n#else\n\nThreadStatusImpl::~ThreadStatusImpl() {\n}\n\nvoid ThreadStatusImpl::UnregisterThread() {\n}\n\nvoid ThreadStatusImpl::SetThreadType(\n ThreadStatus::ThreadType ttype) {\n}\n\nvoid ThreadStatusImpl::SetColumnFamilyInfoKey(\n const void* cf_key) {\n}\n\nvoid ThreadStatusImpl::SetEventInfoPtr(\n const ThreadEventInfo* event_info) {\n}\n\nStatus ThreadStatusImpl::GetThreadList(\n std::vector<ThreadStatus>* thread_list) const {\n return Status::NotSupported(\n \"GetThreadList is not supported in the current running environment.\");\n}\n\nvoid ThreadStatusImpl::NewColumnFamilyInfo(\n const void* db_key, const std::string& db_name,\n const void* cf_key, const std::string& cf_name) {\n}\n\nvoid ThreadStatusImpl::EraseColumnFamilyInfo(const void* cf_key) {\n}\n\nvoid ThreadStatusImpl::EraseDatabaseInfo(const void* db_key) {\n}\n\n#endif \/\/ ROCKSDB_USING_THREAD_STATUS\n} \/\/ namespace rocksdb\n<commit_msg>Fixed the destruction order of static variables in ThreadStatusImpl.<commit_after>\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#include \"port\/likely.h\"\n#include \"util\/mutexlock.h\"\n#include \"util\/thread_status_impl.h\"\n\nnamespace rocksdb {\n\n#if ROCKSDB_USING_THREAD_STATUS\n__thread ThreadStatusData* ThreadStatusImpl::thread_status_data_ = nullptr;\nstd::mutex ThreadStatusImpl::thread_list_mutex_;\nstd::unordered_set<ThreadStatusData*> ThreadStatusImpl::thread_data_set_;\nstd::unordered_map<const void*, ConstantColumnFamilyInfo*>\n ThreadStatusImpl::cf_info_map_;\nstd::unordered_map<const void*, std::unordered_set<const void*>>\n ThreadStatusImpl::db_key_map_;\n\nThreadStatusImpl thread_local_status;\n\nThreadStatusImpl::~ThreadStatusImpl() {\n assert(thread_data_set_.size() == 0);\n}\n\nvoid ThreadStatusImpl::UnregisterThread() {\n if (thread_status_data_ != nullptr) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n thread_data_set_.erase(thread_status_data_);\n delete thread_status_data_;\n thread_status_data_ = nullptr;\n }\n}\n\nvoid ThreadStatusImpl::SetThreadType(\n ThreadStatus::ThreadType ttype) {\n auto* data = InitAndGet();\n data->thread_type.store(ttype, std::memory_order_relaxed);\n}\n\nvoid ThreadStatusImpl::SetColumnFamilyInfoKey(\n const void* cf_key) {\n auto* data = InitAndGet();\n data->cf_key.store(cf_key, std::memory_order_relaxed);\n}\n\nvoid ThreadStatusImpl::SetEventInfoPtr(\n const ThreadEventInfo* event_info) {\n auto* data = InitAndGet();\n data->event_info.store(event_info, std::memory_order_relaxed);\n}\n\nStatus ThreadStatusImpl::GetThreadList(\n std::vector<ThreadStatus>* thread_list) const {\n thread_list->clear();\n std::vector<std::shared_ptr<ThreadStatusData>> valid_list;\n\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n for (auto* thread_data : thread_data_set_) {\n assert(thread_data);\n auto thread_type = thread_data->thread_type.load(\n std::memory_order_relaxed);\n auto cf_key = thread_data->cf_key.load(\n std::memory_order_relaxed);\n auto iter = cf_info_map_.find(cf_key);\n assert(cf_key == 0 || iter != cf_info_map_.end());\n auto* cf_info = iter != cf_info_map_.end() ?\n iter->second : nullptr;\n auto* event_info = thread_data->event_info.load(\n std::memory_order_relaxed);\n const std::string* db_name = nullptr;\n const std::string* cf_name = nullptr;\n const std::string* event_name = nullptr;\n if (cf_info != nullptr) {\n db_name = &cf_info->db_name;\n cf_name = &cf_info->cf_name;\n \/\/ display lower-level info only when higher-level info is available.\n if (event_info != nullptr) {\n event_name = &event_info->event_name;\n }\n }\n thread_list->emplace_back(\n thread_data->thread_id, thread_type,\n db_name ? *db_name : \"\",\n cf_name ? *cf_name : \"\",\n event_name ? *event_name : \"\");\n }\n\n return Status::OK();\n}\n\nThreadStatusData* ThreadStatusImpl::InitAndGet() {\n if (UNLIKELY(thread_status_data_ == nullptr)) {\n thread_status_data_ = new ThreadStatusData();\n thread_status_data_->thread_id = reinterpret_cast<uint64_t>(\n thread_status_data_);\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n thread_data_set_.insert(thread_status_data_);\n }\n return thread_status_data_;\n}\n\nvoid ThreadStatusImpl::NewColumnFamilyInfo(\n const void* db_key, const std::string& db_name,\n const void* cf_key, const std::string& cf_name) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n\n cf_info_map_[cf_key] = new ConstantColumnFamilyInfo(db_key, db_name, cf_name);\n db_key_map_[db_key].insert(cf_key);\n}\n\nvoid ThreadStatusImpl::EraseColumnFamilyInfo(const void* cf_key) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n auto cf_pair = cf_info_map_.find(cf_key);\n assert(cf_pair != cf_info_map_.end());\n\n auto* cf_info = cf_pair->second;\n assert(cf_info);\n\n \/\/ Remove its entry from db_key_map_ by the following steps:\n \/\/ 1. Obtain the entry in db_key_map_ whose set contains cf_key\n \/\/ 2. Remove it from the set.\n auto db_pair = db_key_map_.find(cf_info->db_key);\n assert(db_pair != db_key_map_.end());\n size_t result __attribute__((unused)) = db_pair->second.erase(cf_key);\n assert(result);\n\n delete cf_info;\n result = cf_info_map_.erase(cf_key);\n assert(result);\n}\n\nvoid ThreadStatusImpl::EraseDatabaseInfo(const void* db_key) {\n std::lock_guard<std::mutex> lck(thread_list_mutex_);\n auto db_pair = db_key_map_.find(db_key);\n if (UNLIKELY(db_pair == db_key_map_.end())) {\n \/\/ In some occasional cases such as DB::Open fails, we won't\n \/\/ register ColumnFamilyInfo for a db.\n return;\n }\n\n size_t result __attribute__((unused)) = 0;\n for (auto cf_key : db_pair->second) {\n auto cf_pair = cf_info_map_.find(cf_key);\n assert(cf_pair != cf_info_map_.end());\n delete cf_pair->second;\n result = cf_info_map_.erase(cf_key);\n assert(result);\n }\n db_key_map_.erase(db_key);\n}\n\n#else\n\nThreadStatusImpl::~ThreadStatusImpl() {\n}\n\nvoid ThreadStatusImpl::UnregisterThread() {\n}\n\nvoid ThreadStatusImpl::SetThreadType(\n ThreadStatus::ThreadType ttype) {\n}\n\nvoid ThreadStatusImpl::SetColumnFamilyInfoKey(\n const void* cf_key) {\n}\n\nvoid ThreadStatusImpl::SetEventInfoPtr(\n const ThreadEventInfo* event_info) {\n}\n\nStatus ThreadStatusImpl::GetThreadList(\n std::vector<ThreadStatus>* thread_list) const {\n return Status::NotSupported(\n \"GetThreadList is not supported in the current running environment.\");\n}\n\nvoid ThreadStatusImpl::NewColumnFamilyInfo(\n const void* db_key, const std::string& db_name,\n const void* cf_key, const std::string& cf_name) {\n}\n\nvoid ThreadStatusImpl::EraseColumnFamilyInfo(const void* cf_key) {\n}\n\nvoid ThreadStatusImpl::EraseDatabaseInfo(const void* db_key) {\n}\n\nThreadStatusImpl thread_local_status;\n#endif \/\/ ROCKSDB_USING_THREAD_STATUS\n} \/\/ namespace rocksdb\n<|endoftext|>"} {"text":"<commit_before>#include \"SimpleAudioEngine.h\"\n#include \"AppDelegate.h\"\n#include \"MenuScene.h\"\n#include \"Path.h\"\n\nUSING_NS_CC;\nusing CocosDenshion::SimpleAudioEngine;\n\nAppDelegate::AppDelegate() { }\n\nAppDelegate::~AppDelegate() { }\n\n\/\/if you want a different context,just modify the value of glContextAttrs\n\/\/it will takes effect on all platforms\nvoid AppDelegate::initGLContextAttrs()\n{\n \/\/set OpenGL context attributions,now can only set six attributions:\n \/\/red,green,blue,alpha,depth,stencil\n GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};\n\n GLView::setGLContextAttrs(glContextAttrs);\n}\n\n\/\/ If you want to use packages manager to install more packages,\n\/\/ don't modify or remove this function\nstatic int register_all_packages()\n{\n return 0; \/\/flag for packages manager\n}\n\nbool AppDelegate::applicationDidFinishLaunching() {\n \/\/ initialize director\n auto director = Director::getInstance();\n auto glview = director->getOpenGLView();\n if(!glview) {\n glview = GLViewImpl::create(\"Flappy Bird\");\n glview->setFrameSize(360, 640);\n director->setOpenGLView(glview);\n }\n\n glview->setDesignResolutionSize(288, 512, ResolutionPolicy::NO_BORDER);\n\n \/\/ turn on display FPS\n director->setDisplayStats(true);\n\n \/\/ set FPS. the default value is 1.0\/60 if you don't call this\n director->setAnimationInterval(1.0 \/ 60);\n\n register_all_packages();\n\n srand(time(NULL));\n\n preloadSFX();\n\n \/\/ create a scene. it's an autorelease object\n auto scene = MenuScene::createScene();\n\n \/\/ run\n director->runWithScene(scene);\n\n return true;\n}\n\/\/ This function will be called when the app is inactive. When comes a phone call,it's be invoked too\nvoid AppDelegate::applicationDidEnterBackground()\n{\n Director::getInstance()->stopAnimation();\n\n \/\/ if you use SimpleAudioEngine, it must be pause\n SimpleAudioEngine::getInstance()->pauseBackgroundMusic();\n}\n\n\/\/ this function will be called when the app is active again\nvoid AppDelegate::applicationWillEnterForeground()\n{\n Director::getInstance()->startAnimation();\n\n \/\/ if you use SimpleAudioEngine, it must resume here\n SimpleAudioEngine::getInstance()->resumeBackgroundMusic();\n}\n\nvoid AppDelegate::preloadSFX()\n{\n auto audioEngine = SimpleAudioEngine::getInstance();\n\n audioEngine->preloadEffect(SFX_DIE);\n audioEngine->preloadEffect(SFX_HIT);\n audioEngine->preloadEffect(SFX_POINT);\n audioEngine->preloadEffect(SFX_SWOOSHING);\n audioEngine->preloadEffect(SFX_WING);\n\n audioEngine->setEffectsVolume(0.4f);\n}\n\n<commit_msg>Turn off display FPS<commit_after>#include \"SimpleAudioEngine.h\"\n#include \"AppDelegate.h\"\n#include \"MenuScene.h\"\n#include \"Path.h\"\n\nUSING_NS_CC;\nusing CocosDenshion::SimpleAudioEngine;\n\nAppDelegate::AppDelegate() { }\n\nAppDelegate::~AppDelegate() { }\n\n\/\/if you want a different context,just modify the value of glContextAttrs\n\/\/it will takes effect on all platforms\nvoid AppDelegate::initGLContextAttrs()\n{\n \/\/set OpenGL context attributions,now can only set six attributions:\n \/\/red,green,blue,alpha,depth,stencil\n GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};\n\n GLView::setGLContextAttrs(glContextAttrs);\n}\n\n\/\/ If you want to use packages manager to install more packages,\n\/\/ don't modify or remove this function\nstatic int register_all_packages()\n{\n return 0; \/\/flag for packages manager\n}\n\nbool AppDelegate::applicationDidFinishLaunching() {\n \/\/ initialize director\n auto director = Director::getInstance();\n auto glview = director->getOpenGLView();\n if(!glview) {\n glview = GLViewImpl::create(\"Flappy Bird\");\n glview->setFrameSize(360, 640);\n director->setOpenGLView(glview);\n }\n\n glview->setDesignResolutionSize(288, 512, ResolutionPolicy::NO_BORDER);\n\n \/\/ turn on display FPS\n director->setDisplayStats(false);\n\n \/\/ set FPS. the default value is 1.0\/60 if you don't call this\n director->setAnimationInterval(1.0 \/ 60);\n\n register_all_packages();\n\n srand(time(NULL));\n\n preloadSFX();\n\n \/\/ create a scene. it's an autorelease object\n auto scene = MenuScene::createScene();\n\n \/\/ run\n director->runWithScene(scene);\n\n return true;\n}\n\/\/ This function will be called when the app is inactive. When comes a phone call,it's be invoked too\nvoid AppDelegate::applicationDidEnterBackground()\n{\n Director::getInstance()->stopAnimation();\n\n \/\/ if you use SimpleAudioEngine, it must be pause\n SimpleAudioEngine::getInstance()->pauseBackgroundMusic();\n}\n\n\/\/ this function will be called when the app is active again\nvoid AppDelegate::applicationWillEnterForeground()\n{\n Director::getInstance()->startAnimation();\n\n \/\/ if you use SimpleAudioEngine, it must resume here\n SimpleAudioEngine::getInstance()->resumeBackgroundMusic();\n}\n\nvoid AppDelegate::preloadSFX()\n{\n auto audioEngine = SimpleAudioEngine::getInstance();\n\n audioEngine->preloadEffect(SFX_DIE);\n audioEngine->preloadEffect(SFX_HIT);\n audioEngine->preloadEffect(SFX_POINT);\n audioEngine->preloadEffect(SFX_SWOOSHING);\n audioEngine->preloadEffect(SFX_WING);\n\n audioEngine->setEffectsVolume(0.4f);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include \"floppy.h\"\n\nusing namespace Device;\n\nvoid Floppy::Open(const std::string &fname){\n\tstd::stringstream ss;\n\tfs.open(fname, std::ios::in | std::ios::out |std::ios::binary);\n\tif(fs.fail()){\n\t\tss << \"Floppy: cannot open file \\'\"\n\t\t\t<<fname\n\t\t\t<<\"\\'\";\n\t\tthrow ss.str();\n\t}\n\n\t\/\/ ファイルサイズのチェック\n\tsize_t size;\n\t{\n\t\tfs.seekg(0, std::fstream::end);\n\t\tauto end = fs.tellg();\n\t\tfs.clear();\n\t\tfs.seekg(0, std::fstream::beg);\n\t\tauto start = fs.tellg();\n\t\tsize = end - start;\n\t}\n\tDOUT(\"Floppy: file size=\"<<size\/KB<<\"KB\"<<std::endl);\n\tif(size\/KB != 1440) throw \"Floppy: file size is not 1440KB\";\n}\n\nbool Floppy::Seek(const Floppy::Setting &set){\n\tif(set.cylinder > 79){\n\t\tDOUT(\"Floppy: cylinder error: \"<<static_cast<uint32_t>(set.cylinder)<<std::endl);\n\t\treturn false;\n\t}\n\tif(set.sector==0 || set.sector > 18){\n\t\tDOUT(\"Floppy: sector error: \"<<static_cast<uint32_t>(set.sector)<<std::endl);\n\t\treturn false;\n\t}\n\n\tDOUT(\"Floppy: Seek: drive=\"<<std::dec<<static_cast<uint32_t>(set.drive)\n\t\t\t<<\", head=\"<<set.head\n\t\t\t<<\", cylinder=\"<<static_cast<uint32_t>(set.cylinder)\n\t\t\t<<\", sector=\"<<static_cast<uint32_t>(set.sector)\n\t\t\t<<std::endl);\n\tthis->set = set;\n\n\tfs.seekg(0, std::fstream::beg);\n\tif(set.head)\n\t\tfs.seekg(512*18, std::fstream::cur);\n\tif(set.cylinder)\n\t\tfs.seekg(set.cylinder*512*36, std::fstream::cur);\n\tfs.seekg(512*(set.sector-1), std::fstream::cur);\n\/\/\tstd::cout<<set.head*18 + set.cylinder*36 + (set.sector -1)<<std::endl;\n\tif(fs.fail()) return false;\n\treturn true;\n}\n\nbool Floppy::Read(Memory *mem, uint32_t addr, uint8_t sector_num){\n\tDOUT(\"Floppy: Read: sector num=\"<<static_cast<uint32_t>(sector_num)<<std::endl);\n\tLoad(mem, addr, 512*sector_num);\n\treturn true;\n}\n\nvoid Floppy::Load(Memory *mem, uint32_t addr, uint32_t size){\n\tDOUT(\"Floppy: loading to memory... addr=0x\"<<std::hex<<addr<<\", size=0x\"<<size<<std::endl);\n\tfs.read((char*)&mem->GetRaw()[addr], size);\n}\n<commit_msg>[UPDATE]<commit_after>#include <iostream>\n#include <sstream>\n#include \"floppy.h\"\n\nusing namespace Device;\n\nvoid Floppy::Open(const std::string &fname){\n\tstd::stringstream ss;\n\tfs.open(fname, std::ios::in | std::ios::out |std::ios::binary);\n\tif(fs.fail()){\n\t\tss << \"Floppy: cannot open file \\'\"\n\t\t\t<<fname\n\t\t\t<<\"\\'\";\n\t\tthrow ss.str();\n\t}\n\n\t\/\/ ファイルサイズのチェック\n\tsize_t size;\n\t{\n\t\tfs.seekg(0, std::fstream::end);\n\t\tauto end = fs.tellg();\n\t\tfs.clear();\n\t\tfs.seekg(0, std::fstream::beg);\n\t\tauto start = fs.tellg();\n\t\tsize = end - start;\n\t}\n\tDOUT(\"Floppy: file size=\"<<size\/KB<<\"KB\"<<std::endl);\n\tif(size != 1440 * KB)\n\t\tstd::cerr<<\"warning: Floppy: file size is not 1440KB\"<<std::endl;\n}\n\nbool Floppy::Seek(const Floppy::Setting &set){\n\tif(set.cylinder > 79){\n\t\tDOUT(\"Floppy: cylinder error: \"<<static_cast<uint32_t>(set.cylinder)<<std::endl);\n\t\treturn false;\n\t}\n\tif(set.sector==0 || set.sector > 18){\n\t\tDOUT(\"Floppy: sector error: \"<<static_cast<uint32_t>(set.sector)<<std::endl);\n\t\treturn false;\n\t}\n\n\tDOUT(\"Floppy: Seek: drive=\"<<std::dec<<static_cast<uint32_t>(set.drive)\n\t\t\t<<\", head=\"<<set.head\n\t\t\t<<\", cylinder=\"<<static_cast<uint32_t>(set.cylinder)\n\t\t\t<<\", sector=\"<<static_cast<uint32_t>(set.sector)\n\t\t\t<<std::endl);\n\tthis->set = set;\n\n\tfs.seekg(0, std::fstream::beg);\n\tif(set.head)\n\t\tfs.seekg(512*18, std::fstream::cur);\n\tif(set.cylinder)\n\t\tfs.seekg(set.cylinder*512*36, std::fstream::cur);\n\tfs.seekg(512*(set.sector-1), std::fstream::cur);\n\/\/\tstd::cout<<set.head*18 + set.cylinder*36 + (set.sector -1)<<std::endl;\n\tif(fs.fail()) return false;\n\treturn true;\n}\n\nbool Floppy::Read(Memory *mem, uint32_t addr, uint8_t sector_num){\n\tDOUT(\"Floppy: Read: sector num=\"<<static_cast<uint32_t>(sector_num)<<std::endl);\n\tLoad(mem, addr, 512*sector_num);\n\treturn true;\n}\n\nvoid Floppy::Load(Memory *mem, uint32_t addr, uint32_t size){\n\tDOUT(\"Floppy: loading to memory... addr=0x\"<<std::hex<<addr<<\", size=0x\"<<size<<std::endl);\n\tfs.read((char*)&mem->GetRaw()[addr], size);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\nCopyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.\r\nThis software is subject to the Apache v2.0 License.\r\n*\/\r\n\r\n\/************************************************************\/\r\n#include \"buildnum.h\"\r\n#include \"fwVideo.h\"\r\n#include \"FwSharedCode.h\"\r\n#include \"FwSharedCode_SSE2.h\"\r\n\r\n#include <iostream>\r\n\r\nusing namespace OPT_LEVEL;\r\n\r\nextern const unsigned int NUM_COLS;\r\nextern const unsigned int NUM_ELEMS;\r\n\r\nnamespace OPT_LEVEL\r\n{\r\n\r\nFwStatus SYS_INLINE quantInvIntra_MPEG2(Fw16s *pSrcDst, int &QP, Fw16s *pQPMatrix)\r\n{\r\n\tif(FW_REF::PtrNotOK(pSrcDst, pQPMatrix))return fwStsNullPtrErr;\r\n\r\n\tswitch(Dispatch::Type<DT_SSE2>())\r\n\t{\r\n\tcase DT_SSE3:\r\n\tcase DT_SSE2:\r\n\t\t{\r\n\t\t\tconst bool bSrcDstIsAligned = FW_REF::IsAligned(pSrcDst,16);\r\n\t\t\tconst bool bQPMatrixIsAligned = FW_REF::IsAligned(pQPMatrix,16);\r\n\t\t\t__m128i qpConst = _mm_set_epi16(CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP));\r\n\t\t\t__m128i row;\r\n\t\t\t__m128i qpRow;\r\n XMM128 mismatch;\r\n __m128i mask_negative;\r\n __m128i zero = _mm_setzero_si128();\r\n mismatch.i = _mm_setzero_si128();\r\n Fw16s src1 = pSrcDst[0];\r\n\r\n mismatch.s16[0] = pSrcDst[0] ^ 1;\r\n pSrcDst[0]= 0;\r\n \r\n\t\t\tfor(unsigned int I = 0; I < NUM_COLS; I++)\r\n\t\t\t{\r\n\t\t\t\trow = (bSrcDstIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pSrcDst) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pSrcDst) + I);\r\n\t\t\t\tqpRow = (bQPMatrixIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I);\r\n\r\n mask_negative = _mm_cmplt_epi16(row, zero);\r\n\r\n __m128i negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n\t\t\t\t__m128i low = _mm_mullo_epi16(row, qpRow);\r\n\t\t\t\t__m128i high = _mm_mulhi_epi16(row, qpRow);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\t__m128i tmpHigh = _mm_unpackhi_epi16(low, high);\r\n\t\t\t\tFW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n\t\t\t\tlow = _mm_mullo_epi16(row, qpConst);\r\n\t\t\t\thigh = _mm_mulhi_epi16(row, qpConst);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\ttmpHigh = _mm_unpackhi_epi16(low, high);\r\n FW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n row = _mm_srli_epi16(row, 4); \r\n negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\t\t\t\t\r\n mismatch.i = _mm_xor_si128(row,mismatch.i);\r\n\r\n\t\t\t\t__m128i* p128i = reinterpret_cast<__m128i*>(pSrcDst);\r\n\t\t\t\tif(bSrcDstIsAligned)\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_store_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_storeu_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tmismatch.s16[0] ^= mismatch.s16[1] ^ mismatch.s16[2] ^ mismatch.s16[3] ^ mismatch.s16[4];\r\n\t\t\tpSrcDst[63] ^= (mismatch.s16[0] ^ mismatch.s16[5] ^ mismatch.s16[6] ^ mismatch.s16[7]) & 1;\r\n pSrcDst[0] = src1;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DT_REFR:\r\n\tdefault:\r\n {\r\n int mismatch;\r\n mismatch = pSrcDst[0] ^ 1;\r\n\r\n\t\tfor(unsigned int I = 1; I < NUM_ELEMS; I++)\r\n\t\t{\r\n int AcCoefficient;\r\n\r\n if(pSrcDst[I]<0)\r\n {\r\n AcCoefficient = CBL_LIBRARY::Limits<Fw16s>::Sat((-pSrcDst[I] * QP * pQPMatrix[I])>>4);\r\n AcCoefficient = -AcCoefficient;\r\n }\r\n else\r\n AcCoefficient = CBL_LIBRARY::Limits<Fw16s>::Sat((pSrcDst[I] * QP * pQPMatrix[I])>>4);\r\n\r\n mismatch^= AcCoefficient;\r\n pSrcDst[I] = (Fw16s)AcCoefficient;\r\n }\r\n pSrcDst[63]^= mismatch&1;\r\n break;\r\n }\r\n }\r\n\treturn fwStsNoErr;\r\n}\r\n\r\nFwStatus SYS_INLINE quantInv_MPEG2(Fw16s *pSrcDst, int &QP, Fw16s *pQPMatrix)\r\n{\r\n\tif(FW_REF::PtrNotOK(pSrcDst, pQPMatrix))return fwStsNullPtrErr;\r\n\r\n\tswitch(Dispatch::Type<DT_SSE2>())\r\n\t{\r\n\tcase DT_SSE3:\r\n\tcase DT_SSE2:\r\n\t\t{\r\n\t\t\tconst bool bSrcDstIsAligned = FW_REF::IsAligned(pSrcDst,16);\r\n\t\t\tconst bool bQPMatrixIsAligned = FW_REF::IsAligned(pQPMatrix,16);\r\n\t\t\t__m128i qpConst = _mm_set1_epi16(CBL_LIBRARY::Limits<Fw16s>::Sat(QP));\r\n\t\t\t__m128i row;\r\n\t\t\t__m128i qpRow;\r\n __m128i mask_zero, mask_negative;\r\n\t\t\tstatic const __m128i one = _mm_set1_epi16(1);\r\n static const __m128i zero = _mm_setzero_si128();\r\n\r\n\t\t\tXMM128 mismatch;\r\n\t\t\tmismatch.i= _mm_set_epi16(0,0,0,0,0,0,0,1);\r\n\t\t\tfor(unsigned int I = 0; I < NUM_COLS; I++)\r\n\t\t\t{\r\n\t\t\t\trow = (bSrcDstIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pSrcDst) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pSrcDst) + I);\r\n\t\t\t\tqpRow = (bQPMatrixIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I);\r\n\t\t\t\t\r\n mask_zero = _mm_cmpeq_epi16(row, zero);\r\n mask_negative = _mm_cmplt_epi16(row, zero);\r\n\r\n __m128i negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n\t\t\t\trow = _mm_adds_epi16(row,row);\r\n\t\t\t\trow = _mm_adds_epi16(row,one);\r\n\r\n\t\t\t\t__m128i low = _mm_mullo_epi16(row, qpRow);\r\n\t\t\t\t__m128i high = _mm_mulhi_epi16(row, qpRow);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\t__m128i tmpHigh = _mm_unpackhi_epi16(low, high);\r\n\t\t\t\tFW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n\t\t\t\tlow = _mm_mullo_epi16(row, qpConst);\r\n\t\t\t\thigh = _mm_mulhi_epi16(row, qpConst);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\ttmpHigh = _mm_unpackhi_epi16(low, high);\r\n FW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n row = _mm_srli_epi16(row, 5); \r\n negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n row = _mm_andnot_si128(mask_zero, row);\r\n\t\t\t\tmismatch.i = _mm_xor_si128(row,mismatch.i);\r\n\r\n\t\t\t\t__m128i* p128i = reinterpret_cast<__m128i*>(pSrcDst);\r\n\t\t\t\tif(bSrcDstIsAligned)\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_store_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_storeu_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n mismatch.s16[0] ^= mismatch.s16[1] ^ mismatch.s16[2] ^ mismatch.s16[3] ^ mismatch.s16[4];\r\n\t\t\tpSrcDst[63] ^= (mismatch.s16[0] ^ mismatch.s16[5] ^ mismatch.s16[6] ^ mismatch.s16[7]) & 1;\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DT_REFR:\r\n\tdefault:\r\n {\r\n int mismatch = 1;\r\n\r\n for(unsigned int I = 0; I < NUM_ELEMS; I++)\r\n\t\t{\r\n int coefficient;\r\n \r\n if(pSrcDst[I]==0)\r\n coefficient = 0;\r\n else if(pSrcDst[I]<0)\r\n {\r\n coefficient = CBL_LIBRARY::Limits<Fw16s>::Sat((( 2*(-pSrcDst[I]) + 1) * QP * pQPMatrix[I])>>5);\r\n coefficient = -coefficient;\r\n }\r\n else\r\n coefficient = CBL_LIBRARY::Limits<Fw16s>::Sat(((2 * pSrcDst[I] + 1) * QP * pQPMatrix[I])>>5);\r\n\r\n mismatch^= coefficient;\r\n pSrcDst[I] = (Fw16s)coefficient;\r\n }\r\n pSrcDst[63]^= mismatch&1;\r\n break;\r\n }\r\n }\r\n\treturn fwStsNoErr;\r\n\r\n}\r\n} \/\/ end namespace OPT_LEVEL\r\n\/************************************************************\/\r\nFwStatus STDCALL PREFIX_OPT(OPT_PREFIX, fwiQuantInvIntra_MPEG2_16s_C1I)(Fw16s *pSrcDst, int QP, Fw16s *pQPMatrix)\r\n{\r\n\treturn quantInvIntra_MPEG2(pSrcDst, QP, pQPMatrix);\r\n}\r\n\r\nFwStatus STDCALL PREFIX_OPT(OPT_PREFIX, fwiQuantInv_MPEG2_16s_C1I)(Fw16s *pSrcDst, int QP, Fw16s *pQPMatrix)\r\n{\r\n\treturn quantInv_MPEG2(pSrcDst, QP, pQPMatrix);\r\n}\r\n\r\n\r\n\r\n\r\n\/\/ Please do NOT remove the above line for CPP files that need to be multipass compiled\r\n\/\/ OREFR OSSE2 \r\n<commit_msg>Summary: corrected 2 invQuant functions for the BUGS 1943626 and 1943625 <commit_after>\/*\r\nCopyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.\r\nThis software is subject to the Apache v2.0 License.\r\n*\/\r\n\r\n\/************************************************************\/\r\n#include \"buildnum.h\"\r\n#include \"fwVideo.h\"\r\n#include \"FwSharedCode.h\"\r\n#include \"FwSharedCode_SSE2.h\"\r\n\r\n#include <iostream>\r\n\r\nusing namespace OPT_LEVEL;\r\n\r\nextern const unsigned int NUM_COLS;\r\nextern const unsigned int NUM_ELEMS;\r\n\r\nnamespace OPT_LEVEL\r\n{\r\n\r\nFwStatus SYS_INLINE quantInvIntra_MPEG2(Fw16s *pSrcDst, int &QP, Fw16s *pQPMatrix)\r\n{\r\n\tif(FW_REF::PtrNotOK(pSrcDst, pQPMatrix))return fwStsNullPtrErr;\r\n\r\n\tswitch(Dispatch::Type<DT_SSE2>())\r\n\t{\r\n\tcase DT_SSE3:\r\n\tcase DT_SSE2:\r\n\t\t{\r\n\t\t\tconst bool bSrcDstIsAligned = FW_REF::IsAligned(pSrcDst,16);\r\n\t\t\tconst bool bQPMatrixIsAligned = FW_REF::IsAligned(pQPMatrix,16);\r\n\t\t\t__m128i qpConst = _mm_set_epi16(CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP), CBL_LIBRARY::Limits<Fw16s>::Sat(QP));\r\n\t\t\t__m128i row;\r\n\t\t\t__m128i qpRow;\r\n XMM128 mismatch;\r\n __m128i mask_negative;\r\n __m128i zero = _mm_setzero_si128();\r\n mismatch.i = _mm_setzero_si128();\r\n Fw16s src1 = pSrcDst[0];\r\n\r\n mismatch.s16[0] = pSrcDst[0] ^ 1;\r\n pSrcDst[0]= 0;\r\n \r\n\t\t\tfor(unsigned int I = 0; I < NUM_COLS; I++)\r\n\t\t\t{\r\n\t\t\t\trow = (bSrcDstIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pSrcDst) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pSrcDst) + I);\r\n\t\t\t\tqpRow = (bQPMatrixIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I);\r\n\r\n\t\t\t\t__m128i low = _mm_mullo_epi16(row, qpRow);\r\n\t\t\t\t__m128i high = _mm_mulhi_epi16(row, qpRow);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\t__m128i tmpHigh = _mm_unpackhi_epi16(low, high);\r\n\t\t\t\tFW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n\t\t\t\tlow = _mm_mullo_epi16(row, qpConst);\r\n\t\t\t\thigh = _mm_mulhi_epi16(row, qpConst);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\ttmpHigh = _mm_unpackhi_epi16(low, high);\r\n FW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n mask_negative = _mm_cmplt_epi16(row, zero);\r\n __m128i negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n row = _mm_srli_epi16(row, 4); \r\n negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\t\t\t\t\r\n mismatch.i = _mm_xor_si128(row,mismatch.i);\r\n\r\n\t\t\t\t__m128i* p128i = reinterpret_cast<__m128i*>(pSrcDst);\r\n\t\t\t\tif(bSrcDstIsAligned)\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_store_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_storeu_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tmismatch.s16[0] ^= mismatch.s16[1] ^ mismatch.s16[2] ^ mismatch.s16[3] ^ mismatch.s16[4];\r\n\t\t\tpSrcDst[63] ^= (mismatch.s16[0] ^ mismatch.s16[5] ^ mismatch.s16[6] ^ mismatch.s16[7]) & 1;\r\n pSrcDst[0] = src1;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DT_REFR:\r\n\tdefault:\r\n {\r\n int mismatch;\r\n mismatch = pSrcDst[0] ^ 1;\r\n\r\n\t\tfor(unsigned int I = 1; I < NUM_ELEMS; I++)\r\n\t\t{\r\n int AcCoefficient;\r\n float fl_AcCoefficient;\r\n\r\n fl_AcCoefficient = (float)pSrcDst[I] * QP * (float)pQPMatrix[I];\r\n (fl_AcCoefficient < -CBL_LIBRARY::Limits<S16>::MaxValue()) ? AcCoefficient = -CBL_LIBRARY::Limits<S16>::MaxValue() : (fl_AcCoefficient > CBL_LIBRARY::Limits<S16>::MaxValue()) ? AcCoefficient = CBL_LIBRARY::Limits<S16>::MaxValue() : AcCoefficient = (int)fl_AcCoefficient;\r\n\r\n if(AcCoefficient < 0)\r\n {\r\n AcCoefficient = (-AcCoefficient) >> 4;\r\n AcCoefficient = -AcCoefficient;\r\n }\r\n else\r\n AcCoefficient = AcCoefficient >> 4;\r\n\r\n mismatch^= AcCoefficient;\r\n pSrcDst[I] = (Fw16s)AcCoefficient;\r\n }\r\n pSrcDst[63]^= mismatch&1;\r\n break;\r\n }\r\n }\r\n\treturn fwStsNoErr;\r\n}\r\n\r\nFwStatus SYS_INLINE quantInv_MPEG2(Fw16s *pSrcDst, int &QP, Fw16s *pQPMatrix)\r\n{\r\n\tif(FW_REF::PtrNotOK(pSrcDst, pQPMatrix))return fwStsNullPtrErr;\r\n\r\n\tswitch(Dispatch::Type<DT_SSE2>())\r\n\t{\r\n\tcase DT_SSE3:\r\n\tcase DT_SSE2:\r\n\t\t{\r\n\t\t\tconst bool bSrcDstIsAligned = FW_REF::IsAligned(pSrcDst,16);\r\n\t\t\tconst bool bQPMatrixIsAligned = FW_REF::IsAligned(pQPMatrix,16);\r\n\t\t\t__m128i qpConst = _mm_set1_epi16(CBL_LIBRARY::Limits<Fw16s>::Sat(QP));\r\n\t\t\t__m128i row;\r\n\t\t\t__m128i qpRow;\r\n __m128i mask_zero, mask_negative;\r\n\t\t\tstatic const __m128i one = _mm_set1_epi16(1);\r\n static const __m128i zero = _mm_setzero_si128();\r\n\r\n\t\t\tXMM128 mismatch;\r\n\t\t\tmismatch.i= _mm_set_epi16(0,0,0,0,0,0,0,1);\r\n\t\t\tfor(unsigned int I = 0; I < NUM_COLS; I++)\r\n\t\t\t{\r\n\t\t\t\trow = (bSrcDstIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pSrcDst) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pSrcDst) + I);\r\n\t\t\t\tqpRow = (bQPMatrixIsAligned)? _mm_load_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I) : _mm_loadu_si128(reinterpret_cast<__m128i*>(pQPMatrix) + I);\r\n\t\t\t\t\r\n mask_zero = _mm_cmpeq_epi16(row, zero);\r\n\r\n\t\t\t\trow = _mm_adds_epi16(row,row);\r\n\t\t\t\trow = _mm_adds_epi16(row,one);\r\n\r\n\t\t\t\t__m128i low = _mm_mullo_epi16(row, qpRow);\r\n\t\t\t\t__m128i high = _mm_mulhi_epi16(row, qpRow);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\t__m128i tmpHigh = _mm_unpackhi_epi16(low, high);\r\n\t\t\t\tFW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n\t\t\t\tlow = _mm_mullo_epi16(row, qpConst);\r\n\t\t\t\thigh = _mm_mulhi_epi16(row, qpConst);\r\n\t\t\t\trow = _mm_unpacklo_epi16(low, high);\r\n\t\t\t\ttmpHigh = _mm_unpackhi_epi16(low, high);\r\n FW_SSE2::pack32STo16S(row, tmpHigh);\r\n\r\n mask_negative = _mm_cmplt_epi16(row, zero);\r\n __m128i negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n row = _mm_srli_epi16(row, 5); \r\n negative_nums = _mm_and_si128(mask_negative, row);\r\n negative_nums = _mm_subs_epi16(zero, negative_nums);\r\n row = _mm_andnot_si128(mask_negative, row);\r\n row = _mm_or_si128(row, negative_nums);\r\n\r\n row = _mm_andnot_si128(mask_zero, row);\r\n\t\t\t\tmismatch.i = _mm_xor_si128(row,mismatch.i);\r\n\r\n\t\t\t\t__m128i* p128i = reinterpret_cast<__m128i*>(pSrcDst);\r\n\t\t\t\tif(bSrcDstIsAligned)\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_store_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t_mm_storeu_si128(&p128i[I], row);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n mismatch.s16[0] ^= mismatch.s16[1] ^ mismatch.s16[2] ^ mismatch.s16[3] ^ mismatch.s16[4];\r\n\t\t\tpSrcDst[63] ^= (mismatch.s16[0] ^ mismatch.s16[5] ^ mismatch.s16[6] ^ mismatch.s16[7]) & 1;\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DT_REFR:\r\n\tdefault:\r\n {\r\n int mismatch = 1;\r\n\r\n for(unsigned int I = 0; I < NUM_ELEMS; I++)\r\n\t\t{\r\n int coefficient;\r\n float fl_coefficient;\r\n \r\n if(pSrcDst[I]==0)\r\n coefficient = 0;\r\n else\r\n {\r\n fl_coefficient = (2 * (float)pSrcDst[I] + 1) * QP * (float)pQPMatrix[I];\r\n (fl_coefficient < -CBL_LIBRARY::Limits<S16>::MaxValue()) ? coefficient = -CBL_LIBRARY::Limits<S16>::MaxValue() : (fl_coefficient > CBL_LIBRARY::Limits<S16>::MaxValue()) ? coefficient = CBL_LIBRARY::Limits<S16>::MaxValue() : coefficient = (int)fl_coefficient;\r\n if(coefficient < 0)\r\n {\r\n coefficient = (-coefficient)>>5;\r\n coefficient = -coefficient;\r\n }\r\n else\r\n coefficient = coefficient >> 5;\r\n }\r\n\r\n mismatch^= coefficient;\r\n pSrcDst[I] = (Fw16s)coefficient;\r\n }\r\n pSrcDst[63]^= mismatch&1;\r\n break;\r\n }\r\n }\r\n\treturn fwStsNoErr;\r\n\r\n}\r\n} \/\/ end namespace OPT_LEVEL\r\n\/************************************************************\/\r\nFwStatus STDCALL PREFIX_OPT(OPT_PREFIX, fwiQuantInvIntra_MPEG2_16s_C1I)(Fw16s *pSrcDst, int QP, Fw16s *pQPMatrix)\r\n{\r\n\treturn quantInvIntra_MPEG2(pSrcDst, QP, pQPMatrix);\r\n}\r\n\r\nFwStatus STDCALL PREFIX_OPT(OPT_PREFIX, fwiQuantInv_MPEG2_16s_C1I)(Fw16s *pSrcDst, int QP, Fw16s *pQPMatrix)\r\n{\r\n\treturn quantInv_MPEG2(pSrcDst, QP, pQPMatrix);\r\n}\r\n\r\n\r\n\r\n\r\n\/\/ Please do NOT remove the above line for CPP files that need to be multipass compiled\r\n\/\/ OREFR OSSE2 \r\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ nkuiWrapper.cc\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#define NK_IMPLEMENTATION\n#include \"nkuiWrapper.h\"\n#include \"Core\/Memory\/Memory.h\"\n#include \"Input\/Input.h\"\n#include \"NKUIShaders.h\"\n#include \"glm\/mat4x4.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\nnamespace Oryol {\nnamespace _priv {\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Setup(const NKUISetup& setup) {\n o_assert_dbg(!this->isValid);\n this->isValid = true;\n\n \/\/ create resources\n this->gfxResLabel = Gfx::PushResourceLabel();\n this->createDefaultFont(setup);\n this->createMeshAndPipeline();\n Gfx::PopResourceLabel();\n\n \/\/ initialize nuklear\n nk_init_default(&this->ctx, &this->defaultFont->handle);\n nk_buffer_init_default(&this->cmds);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Discard() {\n o_assert_dbg(this->isValid);\n this->defaultFont = nullptr;\n nk_buffer_free(&this->cmds);\n nk_font_atlas_clear(&this->atlas);\n nk_free(&this->ctx);\n Gfx::DestroyResources(this->gfxResLabel);\n this->isValid = false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::createDefaultFont(const NKUISetup& setup) {\n o_assert_dbg(nullptr == this->defaultFont);\n\n \/\/ let Nuklear create a font bitmap\n nk_font_atlas_init_default(&this->atlas);\n nk_font_atlas_begin(&this->atlas);\n this->defaultFont = nk_font_atlas_add_default(&this->atlas, 13, 0);\n int imgWidth, imgHeight;\n const void* imgData = nk_font_atlas_bake(&this->atlas, &imgWidth, &imgHeight, NK_FONT_ATLAS_RGBA32);\n\n \/\/ create Oryol Gfx texture from font image data\n auto texSetup = TextureSetup::FromPixelData(imgWidth, imgHeight, 1, TextureType::Texture2D, PixelFormat::RGBA8);\n texSetup.Sampler.WrapU = TextureWrapMode::ClampToEdge;\n texSetup.Sampler.WrapV = TextureWrapMode::ClampToEdge;\n texSetup.Sampler.MinFilter = TextureFilterMode::Nearest;\n texSetup.Sampler.MagFilter = TextureFilterMode::Nearest;\n const int imgSize = imgWidth*imgHeight * PixelFormat::ByteSize(PixelFormat::RGBA8);\n texSetup.ImageData.Sizes[0][0] = imgSize;\n int texId = this->curTexId++;\n this->textures[texId] = Gfx::CreateResource(texSetup, imgData, imgSize);\n nk_font_atlas_end(&this->atlas, nk_handle_id(texId), &this->nullTex);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::createMeshAndPipeline() {\n\n \/\/ create mesh with dynamic vertex- and index-buffer\n auto mshSetup = MeshSetup::Empty(MaxNumVertices, Usage::Stream, IndexType::Index16, MaxNumIndices, Usage::Stream);\n mshSetup.Layout\n .Add(VertexAttr::Position, VertexFormat::Float2)\n .Add(VertexAttr::TexCoord0, VertexFormat::Float2)\n .Add(VertexAttr::Color0, VertexFormat::UByte4N);\n o_assert_dbg(mshSetup.Layout.ByteSize() == sizeof(struct nk_draw_vertex));\n this->drawState.Mesh[0] = Gfx::CreateResource(mshSetup);\n\n \/\/ create pipeline state object\n Id shd = Gfx::CreateResource(NKUIShader::Setup());\n auto ps = PipelineSetup::FromLayoutAndShader(mshSetup.Layout, shd);\n ps.DepthStencilState.DepthWriteEnabled = false;\n ps.DepthStencilState.DepthCmpFunc = CompareFunc::Always;\n ps.BlendState.BlendEnabled = true;\n ps.BlendState.SrcFactorRGB = BlendFactor::SrcAlpha;\n ps.BlendState.DstFactorRGB = BlendFactor::OneMinusSrcAlpha;\n ps.BlendState.ColorFormat = Gfx::DisplayAttrs().ColorPixelFormat;\n ps.BlendState.DepthFormat = Gfx::DisplayAttrs().DepthPixelFormat;\n ps.BlendState.ColorWriteMask = PixelChannel::RGB;\n ps.RasterizerState.ScissorTestEnabled = true;\n ps.RasterizerState.CullFaceEnabled = false;\n ps.RasterizerState.SampleCount = Gfx::DisplayAttrs().SampleCount;\n this->drawState.Pipeline = Gfx::CreateResource(ps);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::NewFrame() {\n nk_input_begin(&this->ctx);\n if (Input::KeyboardAttached()) {\n nk_input_key(&this->ctx, NK_KEY_DEL, Input::KeyDown(Key::Delete));\n nk_input_key(&this->ctx, NK_KEY_ENTER, Input::KeyDown(Key::Enter));\n nk_input_key(&this->ctx, NK_KEY_TAB, Input::KeyDown(Key::Tab));\n nk_input_key(&this->ctx, NK_KEY_BACKSPACE, Input::KeyDown(Key::BackSpace));\n nk_input_key(&this->ctx, NK_KEY_LEFT, Input::KeyDown(Key::Left));\n nk_input_key(&this->ctx, NK_KEY_RIGHT, Input::KeyDown(Key::Right));\n nk_input_key(&this->ctx, NK_KEY_UP, Input::KeyDown(Key::Up));\n nk_input_key(&this->ctx, NK_KEY_DOWN, Input::KeyDown(Key::Down));\n if (Input::KeyPressed(Key::LeftControl) || Input::KeyPressed(Key::RightControl)) {\n nk_input_key(&this->ctx, NK_KEY_COPY, Input::KeyDown(Key::C));\n nk_input_key(&this->ctx, NK_KEY_PASTE, Input::KeyDown(Key::V));\n nk_input_key(&this->ctx, NK_KEY_CUT, Input::KeyDown(Key::X));\n }\n else {\n nk_input_key(&this->ctx, NK_KEY_COPY, 0);\n nk_input_key(&this->ctx, NK_KEY_PASTE, 0);\n nk_input_key(&this->ctx, NK_KEY_CUT, 0);\n }\n }\n if (Input::MouseAttached()) {\n const glm::vec2& mousePos = Input::MousePosition();\n int x = int(mousePos.x);\n int y = int(mousePos.y);\n bool lmb = Input::MouseButtonPressed(MouseButton::Left)|Input::MouseButtonDown(MouseButton::Left);\n bool mmb = Input::MouseButtonPressed(MouseButton::Middle)|Input::MouseButtonDown(MouseButton::Middle);\n bool rmb = Input::MouseButtonPressed(MouseButton::Right)|Input::MouseButtonDown(MouseButton::Right);\n nk_input_motion(&this->ctx, x, y);\n nk_input_button(&this->ctx, NK_BUTTON_LEFT, x, y, lmb);\n nk_input_button(&this->ctx, NK_BUTTON_MIDDLE, x, y, mmb);\n nk_input_button(&this->ctx, NK_BUTTON_RIGHT, x, y, rmb);\n }\n nk_input_end(&this->ctx);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Draw() {\n\n \/\/ upload vertex and index data\n nk_convert_config config = { };\n config.global_alpha = 1.0f;\n config.shape_AA = NK_ANTI_ALIASING_ON;\n config.line_AA = NK_ANTI_ALIASING_ON;\n config.circle_segment_count = 22;\n config.curve_segment_count = 22;\n config.arc_segment_count = 22;\n config.null = this->nullTex;\n struct nk_buffer vbuf, ibuf;\n nk_buffer_init_fixed(&vbuf, this->vertexData, sizeof(this->vertexData));\n nk_buffer_init_fixed(&ibuf, this->indexData, sizeof(this->indexData));\n nk_convert(&this->ctx, &this->cmds, &vbuf, &ibuf, &config);\n if (vbuf.needed > 0) {\n Gfx::UpdateVertices(this->drawState.Mesh[0], this->vertexData, vbuf.needed);\n }\n if (ibuf.needed > 0) {\n Gfx::UpdateIndices(this->drawState.Mesh[0], this->indexData, ibuf.needed);\n }\n\n \/\/ compute projection matrix\n const DisplayAttrs& attrs = Gfx::DisplayAttrs();\n const float width = float(attrs.FramebufferWidth);\n const float height = float(attrs.FramebufferHeight);\n NKUIShader::VSParams vsParams;\n vsParams.Proj = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f);\n\n \/\/ render draw commands\n Id curTexture;\n const struct nk_draw_command* cmd = nullptr;\n int elm_offset = 0;\n nk_draw_foreach(cmd, &this->ctx, &this->cmds) {\n const Id& newTexture = this->textures[(int)cmd->texture.id];\n if (curTexture != newTexture) {\n this->drawState.FSTexture[NKUITextures::Texture] = newTexture;\n curTexture = newTexture;\n Gfx::ApplyDrawState(this->drawState);\n Gfx::ApplyUniformBlock(vsParams);\n }\n Gfx::ApplyScissorRect((int)cmd->clip_rect.x,\n (int)(height - (cmd->clip_rect.y + cmd->clip_rect.h)),\n (int)(cmd->clip_rect.w),\n (int)(cmd->clip_rect.h));\n Gfx::Draw(PrimitiveGroup(elm_offset, cmd->elem_count));\n elm_offset += cmd->elem_count;\n }\n nk_clear(&this->ctx);\n}\n\n} \/\/ namespace _priv\n} \/\/ namespace Oryol\n<commit_msg>Warning fixes<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ nkuiWrapper.cc\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#define NK_IMPLEMENTATION\n#include \"nkuiWrapper.h\"\n#include \"Core\/Memory\/Memory.h\"\n#include \"Input\/Input.h\"\n#include \"NKUIShaders.h\"\n#include \"glm\/mat4x4.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\nnamespace Oryol {\nnamespace _priv {\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Setup(const NKUISetup& setup) {\n o_assert_dbg(!this->isValid);\n this->isValid = true;\n\n \/\/ create resources\n this->gfxResLabel = Gfx::PushResourceLabel();\n this->createDefaultFont(setup);\n this->createMeshAndPipeline();\n Gfx::PopResourceLabel();\n\n \/\/ initialize nuklear\n nk_init_default(&this->ctx, &this->defaultFont->handle);\n nk_buffer_init_default(&this->cmds);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Discard() {\n o_assert_dbg(this->isValid);\n this->defaultFont = nullptr;\n nk_buffer_free(&this->cmds);\n nk_font_atlas_clear(&this->atlas);\n nk_free(&this->ctx);\n Gfx::DestroyResources(this->gfxResLabel);\n this->isValid = false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::createDefaultFont(const NKUISetup& setup) {\n o_assert_dbg(nullptr == this->defaultFont);\n\n \/\/ let Nuklear create a font bitmap\n nk_font_atlas_init_default(&this->atlas);\n nk_font_atlas_begin(&this->atlas);\n this->defaultFont = nk_font_atlas_add_default(&this->atlas, 13, 0);\n int imgWidth, imgHeight;\n const void* imgData = nk_font_atlas_bake(&this->atlas, &imgWidth, &imgHeight, NK_FONT_ATLAS_RGBA32);\n\n \/\/ create Oryol Gfx texture from font image data\n auto texSetup = TextureSetup::FromPixelData(imgWidth, imgHeight, 1, TextureType::Texture2D, PixelFormat::RGBA8);\n texSetup.Sampler.WrapU = TextureWrapMode::ClampToEdge;\n texSetup.Sampler.WrapV = TextureWrapMode::ClampToEdge;\n texSetup.Sampler.MinFilter = TextureFilterMode::Nearest;\n texSetup.Sampler.MagFilter = TextureFilterMode::Nearest;\n const int imgSize = imgWidth*imgHeight * PixelFormat::ByteSize(PixelFormat::RGBA8);\n texSetup.ImageData.Sizes[0][0] = imgSize;\n int texId = this->curTexId++;\n this->textures[texId] = Gfx::CreateResource(texSetup, imgData, imgSize);\n nk_font_atlas_end(&this->atlas, nk_handle_id(texId), &this->nullTex);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::createMeshAndPipeline() {\n\n \/\/ create mesh with dynamic vertex- and index-buffer\n auto mshSetup = MeshSetup::Empty(MaxNumVertices, Usage::Stream, IndexType::Index16, MaxNumIndices, Usage::Stream);\n mshSetup.Layout\n .Add(VertexAttr::Position, VertexFormat::Float2)\n .Add(VertexAttr::TexCoord0, VertexFormat::Float2)\n .Add(VertexAttr::Color0, VertexFormat::UByte4N);\n o_assert_dbg(mshSetup.Layout.ByteSize() == sizeof(struct nk_draw_vertex));\n this->drawState.Mesh[0] = Gfx::CreateResource(mshSetup);\n\n \/\/ create pipeline state object\n Id shd = Gfx::CreateResource(NKUIShader::Setup());\n auto ps = PipelineSetup::FromLayoutAndShader(mshSetup.Layout, shd);\n ps.DepthStencilState.DepthWriteEnabled = false;\n ps.DepthStencilState.DepthCmpFunc = CompareFunc::Always;\n ps.BlendState.BlendEnabled = true;\n ps.BlendState.SrcFactorRGB = BlendFactor::SrcAlpha;\n ps.BlendState.DstFactorRGB = BlendFactor::OneMinusSrcAlpha;\n ps.BlendState.ColorFormat = Gfx::DisplayAttrs().ColorPixelFormat;\n ps.BlendState.DepthFormat = Gfx::DisplayAttrs().DepthPixelFormat;\n ps.BlendState.ColorWriteMask = PixelChannel::RGB;\n ps.RasterizerState.ScissorTestEnabled = true;\n ps.RasterizerState.CullFaceEnabled = false;\n ps.RasterizerState.SampleCount = Gfx::DisplayAttrs().SampleCount;\n this->drawState.Pipeline = Gfx::CreateResource(ps);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::NewFrame() {\n nk_input_begin(&this->ctx);\n if (Input::KeyboardAttached()) {\n nk_input_key(&this->ctx, NK_KEY_DEL, Input::KeyDown(Key::Delete));\n nk_input_key(&this->ctx, NK_KEY_ENTER, Input::KeyDown(Key::Enter));\n nk_input_key(&this->ctx, NK_KEY_TAB, Input::KeyDown(Key::Tab));\n nk_input_key(&this->ctx, NK_KEY_BACKSPACE, Input::KeyDown(Key::BackSpace));\n nk_input_key(&this->ctx, NK_KEY_LEFT, Input::KeyDown(Key::Left));\n nk_input_key(&this->ctx, NK_KEY_RIGHT, Input::KeyDown(Key::Right));\n nk_input_key(&this->ctx, NK_KEY_UP, Input::KeyDown(Key::Up));\n nk_input_key(&this->ctx, NK_KEY_DOWN, Input::KeyDown(Key::Down));\n if (Input::KeyPressed(Key::LeftControl) || Input::KeyPressed(Key::RightControl)) {\n nk_input_key(&this->ctx, NK_KEY_COPY, Input::KeyDown(Key::C));\n nk_input_key(&this->ctx, NK_KEY_PASTE, Input::KeyDown(Key::V));\n nk_input_key(&this->ctx, NK_KEY_CUT, Input::KeyDown(Key::X));\n }\n else {\n nk_input_key(&this->ctx, NK_KEY_COPY, 0);\n nk_input_key(&this->ctx, NK_KEY_PASTE, 0);\n nk_input_key(&this->ctx, NK_KEY_CUT, 0);\n }\n }\n if (Input::MouseAttached()) {\n const glm::vec2& mousePos = Input::MousePosition();\n int x = int(mousePos.x);\n int y = int(mousePos.y);\n bool lmb = Input::MouseButtonPressed(MouseButton::Left)|Input::MouseButtonDown(MouseButton::Left);\n bool mmb = Input::MouseButtonPressed(MouseButton::Middle)|Input::MouseButtonDown(MouseButton::Middle);\n bool rmb = Input::MouseButtonPressed(MouseButton::Right)|Input::MouseButtonDown(MouseButton::Right);\n nk_input_motion(&this->ctx, x, y);\n nk_input_button(&this->ctx, NK_BUTTON_LEFT, x, y, lmb);\n nk_input_button(&this->ctx, NK_BUTTON_MIDDLE, x, y, mmb);\n nk_input_button(&this->ctx, NK_BUTTON_RIGHT, x, y, rmb);\n }\n nk_input_end(&this->ctx);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nnkuiWrapper::Draw() {\n\n \/\/ upload vertex and index data\n nk_convert_config config;\n Memory::Clear(&config, sizeof(config));\n config.global_alpha = 1.0f;\n config.shape_AA = NK_ANTI_ALIASING_ON;\n config.line_AA = NK_ANTI_ALIASING_ON;\n config.circle_segment_count = 22;\n config.curve_segment_count = 22;\n config.arc_segment_count = 22;\n config.null = this->nullTex;\n struct nk_buffer vbuf, ibuf;\n nk_buffer_init_fixed(&vbuf, this->vertexData, sizeof(this->vertexData));\n nk_buffer_init_fixed(&ibuf, this->indexData, sizeof(this->indexData));\n nk_convert(&this->ctx, &this->cmds, &vbuf, &ibuf, &config);\n if (vbuf.needed > 0) {\n Gfx::UpdateVertices(this->drawState.Mesh[0], this->vertexData, int(vbuf.needed));\n }\n if (ibuf.needed > 0) {\n Gfx::UpdateIndices(this->drawState.Mesh[0], this->indexData, int(ibuf.needed));\n }\n\n \/\/ compute projection matrix\n const DisplayAttrs& attrs = Gfx::DisplayAttrs();\n const float width = float(attrs.FramebufferWidth);\n const float height = float(attrs.FramebufferHeight);\n NKUIShader::VSParams vsParams;\n vsParams.Proj = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f);\n\n \/\/ render draw commands\n Id curTexture;\n const struct nk_draw_command* cmd = nullptr;\n int elm_offset = 0;\n nk_draw_foreach(cmd, &this->ctx, &this->cmds) {\n const Id& newTexture = this->textures[(int)cmd->texture.id];\n if (curTexture != newTexture) {\n this->drawState.FSTexture[NKUITextures::Texture] = newTexture;\n curTexture = newTexture;\n Gfx::ApplyDrawState(this->drawState);\n Gfx::ApplyUniformBlock(vsParams);\n }\n Gfx::ApplyScissorRect((int)cmd->clip_rect.x,\n (int)(height - (cmd->clip_rect.y + cmd->clip_rect.h)),\n (int)(cmd->clip_rect.w),\n (int)(cmd->clip_rect.h));\n Gfx::Draw(PrimitiveGroup(elm_offset, cmd->elem_count));\n elm_offset += cmd->elem_count;\n }\n nk_clear(&this->ctx);\n}\n\n} \/\/ namespace _priv\n} \/\/ namespace Oryol\n<|endoftext|>"} {"text":"<commit_before>\/*\n * libtins is a net packet wrapper library for crafting and\n * interpreting sniffed packets.\n *\n * Copyright (C) 2011 Nasel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#ifndef WIN32\n #include <sys\/socket.h>\n #include <sys\/select.h>\n #include <arpa\/inet.h>\n #include <unistd.h>\n #include <linux\/if_ether.h>\n #include <linux\/if_packet.h>\n #include <netdb.h>\n#endif\n#include <assert.h>\n#include <errno.h>\n#include <string.h>\n#include <ctime>\n#include \"packetsender.h\"\n\n\nconst int Tins::PacketSender::INVALID_RAW_SOCKET = -1;\nconst uint32_t Tins::PacketSender::DEFAULT_TIMEOUT = 2;\n\nTins::PacketSender::PacketSender(uint32_t recv_timeout, uint32_t usec) : \n _sockets(SOCKETS_END, INVALID_RAW_SOCKET), _timeout(recv_timeout), _timeout_usec(usec) {\n _types[IP_SOCKET] = IPPROTO_RAW;\n _types[ICMP_SOCKET] = IPPROTO_ICMP;\n}\n\nTins::PacketSender::~PacketSender() {\n for(unsigned i(0); i < _sockets.size(); ++i) {\n if(_sockets[i] != INVALID_RAW_SOCKET)\n ::close(_sockets[i]);\n }\n}\n\nbool Tins::PacketSender::open_l2_socket() {\n if (_sockets[ETHER_SOCKET] != INVALID_RAW_SOCKET)\n return true;\n int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));\n if (sock == -1)\n return false;\n _sockets[ETHER_SOCKET] = sock;\n return true;\n}\n\nbool Tins::PacketSender::open_l3_socket(SocketType type) {\n int socktype = find_type(type);\n if(socktype == -1)\n return false;\n if(_sockets[type] != INVALID_RAW_SOCKET)\n return true;\n int sockfd;\n sockfd = socket(AF_INET, SOCK_RAW, socktype);\n if (sockfd < 0)\n return false;\n\n const int on = 1;\n setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL,(const void *)&on,sizeof(on));\n\n _sockets[type] = sockfd;\n return true;\n}\n\nbool Tins::PacketSender::close_socket(uint32_t flag) {\n if(flag >= SOCKETS_END || _sockets[flag] == INVALID_RAW_SOCKET)\n return false;\n close(_sockets[flag]);\n _sockets[flag] = INVALID_RAW_SOCKET;\n return true;\n}\n\nbool Tins::PacketSender::send(PDU *pdu) {\n return pdu->send(this);\n}\n\nTins::PDU *Tins::PacketSender::send_recv(PDU *pdu) {\n if(!pdu->send(this))\n return 0;\n return pdu->recv_response(this);\n}\n\nbool Tins::PacketSender::send_l2(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr) {\n\n if(!open_l2_socket())\n return false;\n\n uint32_t sz;\n int sock = _sockets[ETHER_SOCKET];\n uint8_t *buffer = pdu->serialize(sz);\n bool ret_val = (sendto(sock, buffer, sz, 0, link_addr, len_addr) != -1);\n delete[] buffer;\n\n return ret_val;\n}\n\nTins::PDU *Tins::PacketSender::recv_l2(PDU *pdu, struct sockaddr *link_addr, uint32_t len_addr) {\n if(!open_l2_socket())\n return 0;\n return recv_match_loop(_sockets[ETHER_SOCKET], pdu, link_addr, len_addr);\n}\n\nTins::PDU *Tins::PacketSender::recv_l3(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr, SocketType type) {\n if(!open_l3_socket(type))\n return 0;\n return recv_match_loop(_sockets[type], pdu, link_addr, len_addr);\n}\n\nbool Tins::PacketSender::send_l3(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr, SocketType type) {\n bool ret_val = true;\n if(!open_l3_socket(type))\n ret_val = false;\n if (ret_val) {\n uint32_t sz;\n int sock = _sockets[type];\n uint8_t *buffer = pdu->serialize(sz);\n ret_val = (sendto(sock, buffer, sz, 0, link_addr, len_addr) != -1);\n delete[] buffer;\n }\n return ret_val;\n}\n\nTins::PDU *Tins::PacketSender::recv_match_loop(int sock, PDU *pdu, struct sockaddr* link_addr, socklen_t addrlen) {\n fd_set readfds;\n struct timeval timeout;\n int read;\n uint8_t buffer[2048];\n time_t end_time = time(0) + _timeout;\n timeout.tv_sec = _timeout;\n timeout.tv_usec = _timeout_usec;\n while(true) {\n FD_ZERO(&readfds);\n FD_SET(sock, &readfds);\n if((read = select(sock + 1, &readfds, 0, 0, &timeout)) == -1)\n return 0;\n if(FD_ISSET(sock, &readfds)) {\n ssize_t size = recvfrom(sock, buffer, 2048, 0, link_addr, &addrlen);\n if(pdu->matches_response(buffer, size))\n return pdu->clone_packet(buffer, size);\n }\n time_t this_time = time(0);\n if(end_time <= this_time)\n return 0;\n timeout.tv_sec = end_time - this_time;\n }\n return 0;\n}\n\nint Tins::PacketSender::find_type(SocketType type) {\n SocketTypeMap::iterator it = _types.find(type);\n if(it == _types.end())\n return -1;\n else\n return it->second;\n}\n<commit_msg>Fixed bug when using microsecond presition on PacketSender::recv_match_loop.<commit_after>\/*\n * libtins is a net packet wrapper library for crafting and\n * interpreting sniffed packets.\n *\n * Copyright (C) 2011 Nasel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#ifndef WIN32\n #include <sys\/socket.h>\n #include <sys\/select.h>\n #include <sys\/time.h>\n #include <arpa\/inet.h>\n #include <unistd.h>\n #include <linux\/if_ether.h>\n #include <linux\/if_packet.h>\n #include <netdb.h>\n#endif\n#include <assert.h>\n#include <errno.h>\n#include <string.h>\n#include <ctime>\n#include \"packetsender.h\"\n\n\nconst int Tins::PacketSender::INVALID_RAW_SOCKET = -1;\nconst uint32_t Tins::PacketSender::DEFAULT_TIMEOUT = 2;\n\nTins::PacketSender::PacketSender(uint32_t recv_timeout, uint32_t usec) : \n _sockets(SOCKETS_END, INVALID_RAW_SOCKET), _timeout(recv_timeout), _timeout_usec(usec) {\n _types[IP_SOCKET] = IPPROTO_RAW;\n _types[ICMP_SOCKET] = IPPROTO_ICMP;\n}\n\nTins::PacketSender::~PacketSender() {\n for(unsigned i(0); i < _sockets.size(); ++i) {\n if(_sockets[i] != INVALID_RAW_SOCKET)\n ::close(_sockets[i]);\n }\n}\n\nbool Tins::PacketSender::open_l2_socket() {\n if (_sockets[ETHER_SOCKET] != INVALID_RAW_SOCKET)\n return true;\n int sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));\n if (sock == -1)\n return false;\n _sockets[ETHER_SOCKET] = sock;\n return true;\n}\n\nbool Tins::PacketSender::open_l3_socket(SocketType type) {\n int socktype = find_type(type);\n if(socktype == -1)\n return false;\n if(_sockets[type] != INVALID_RAW_SOCKET)\n return true;\n int sockfd;\n sockfd = socket(AF_INET, SOCK_RAW, socktype);\n if (sockfd < 0)\n return false;\n\n const int on = 1;\n setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL,(const void *)&on,sizeof(on));\n\n _sockets[type] = sockfd;\n return true;\n}\n\nbool Tins::PacketSender::close_socket(uint32_t flag) {\n if(flag >= SOCKETS_END || _sockets[flag] == INVALID_RAW_SOCKET)\n return false;\n close(_sockets[flag]);\n _sockets[flag] = INVALID_RAW_SOCKET;\n return true;\n}\n\nbool Tins::PacketSender::send(PDU *pdu) {\n return pdu->send(this);\n}\n\nTins::PDU *Tins::PacketSender::send_recv(PDU *pdu) {\n if(!pdu->send(this))\n return 0;\n return pdu->recv_response(this);\n}\n\nbool Tins::PacketSender::send_l2(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr) {\n\n if(!open_l2_socket())\n return false;\n\n uint32_t sz;\n int sock = _sockets[ETHER_SOCKET];\n uint8_t *buffer = pdu->serialize(sz);\n bool ret_val = (sendto(sock, buffer, sz, 0, link_addr, len_addr) != -1);\n delete[] buffer;\n\n return ret_val;\n}\n\nTins::PDU *Tins::PacketSender::recv_l2(PDU *pdu, struct sockaddr *link_addr, uint32_t len_addr) {\n if(!open_l2_socket())\n return 0;\n return recv_match_loop(_sockets[ETHER_SOCKET], pdu, link_addr, len_addr);\n}\n\nTins::PDU *Tins::PacketSender::recv_l3(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr, SocketType type) {\n if(!open_l3_socket(type))\n return 0;\n return recv_match_loop(_sockets[type], pdu, link_addr, len_addr);\n}\n\nbool Tins::PacketSender::send_l3(PDU *pdu, struct sockaddr* link_addr, uint32_t len_addr, SocketType type) {\n bool ret_val = true;\n if(!open_l3_socket(type))\n ret_val = false;\n if (ret_val) {\n uint32_t sz;\n int sock = _sockets[type];\n uint8_t *buffer = pdu->serialize(sz);\n ret_val = (sendto(sock, buffer, sz, 0, link_addr, len_addr) != -1);\n delete[] buffer;\n }\n return ret_val;\n}\n\nTins::PDU *Tins::PacketSender::recv_match_loop(int sock, PDU *pdu, struct sockaddr* link_addr, socklen_t addrlen) {\n fd_set readfds;\n struct timeval timeout, end_time;\n int read;\n uint8_t buffer[2048];\n timeout.tv_sec = _timeout;\n end_time.tv_sec = time(0) + _timeout; \n end_time.tv_usec = timeout.tv_usec = _timeout_usec;\n while(true) {\n FD_ZERO(&readfds);\n FD_SET(sock, &readfds);\n if((read = select(sock + 1, &readfds, 0, 0, &timeout)) == -1)\n return 0;\n if(FD_ISSET(sock, &readfds)) {\n ssize_t size = recvfrom(sock, buffer, 2048, 0, link_addr, &addrlen);\n if(pdu->matches_response(buffer, size))\n return pdu->clone_packet(buffer, size);\n }\n struct timeval this_time;\n gettimeofday(&this_time, 0);\n if(end_time.tv_sec <= this_time.tv_sec && end_time.tv_usec <= this_time.tv_usec)\n return 0;\n timeout.tv_sec = end_time.tv_sec - this_time.tv_sec;\n timeout.tv_usec = end_time.tv_usec;\n }\n return 0;\n}\n\nint Tins::PacketSender::find_type(SocketType type) {\n SocketTypeMap::iterator it = _types.find(type);\n if(it == _types.end())\n return -1;\n else\n return it->second;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ nifti_hdr.cpp\n\/\/ NiftiImage\n\/\/\n\/\/ Created by Tobias Wood on 08\/07\/2013.\n\/\/ Copyright (c) 2013 Tobias Wood. All rights reserved.\n\/\/\n\n#include <memory>\n#include <vector>\n#include <iostream>\n#include <getopt.h>\n\n#include \"Nifti.h\"\n\nusing namespace std;\n\nconst string usage = \"nifti_hdr - A utility for getting information from Nifti headers.\\n\\\n\\n\\\nUsage: nifti_hdr [options] file1 [other files]\\n\\\nBy default the abbreviated header will be printed for each file.\\n\\\nAbbreviated, full and compare modes are mutually exclusive.\\n\\\n\\n\\\nOptions:\\n\\\n\t-d, --dims : Print the size of each dimension for each file.\\n\\\n\t-v, --vox : Print the voxel sizes for each file (with units). \\n\\\n\t-t, --trans : Print the XForm to physical space with precedence.\\n\\\n\t-a, --abbrev: Print the abbreviated header.\\n\\\n\t-f, --full: Print the entire header.\\n\\\n\t-c, --comp: Compare first file to all others and print message if the.\\n\\\n\t physical spaces are different.\\n\\\n\t-h, --help: Print this message and quit.\\n\\\n\";\n\nenum Modes {\n\tNothing = 0,\n\tAbbreviated,\n\tFull,\n\tCompare\n};\n\nstatic int mode = Nothing;\nstatic int printDims = false, printVoxdims = false, printSize = false, printData = false,\n printTransform = false, printExtensions = false;\n\nstatic struct option long_options[] =\n{\n\t{\"dims\", no_argument, &printDims, true},\n\t{\"vox\", no_argument, &printVoxdims, true},\n\t{\"form\", no_argument, &printTransform, true},\n\t{\"size\", no_argument, &printSize, true},\n\t{\"data\", no_argument, &printData, true},\n\t{\"abbrev\", no_argument, &mode, Abbreviated},\n\t{\"full\", no_argument, &mode, Full},\n\t{\"comp\", no_argument, &mode, Compare},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"ext\", no_argument, 0, 'e'},\n\t{0, 0, 0, 0}\n};\n\nstring voxMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Voxel sizes: \" << im.voxDims().transpose() << \" \" << im.spaceUnits();\n\tif (im.voxDims().rows() > 3) {\n\t\tm << \"\/\" << im.timeUnits();\n\t}\n\treturn m.str();\n}\n\nstring sizeMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Voxels per slice, per volume, total: \"\n << im.voxelsPerSlice() << \", \" << im.voxelsPerVolume() << \", \" << im.voxelsTotal();\n\treturn m.str();\n}\n\nstring dataMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Datatype: \" << Nifti::TypeInfo(im.datatype()).name << \", size in bytes: \" << Nifti::TypeInfo(im.datatype()).size;\n\treturn m.str();\n}\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"dvtafchse\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'd': printDims = true; break;\n\t\t\tcase 'v': printVoxdims = true; break;\n\t\t\tcase 't': printTransform = true; break;\n\t\t\tcase 's': printSize = true; break;\n\t\t\tcase 'e': printExtensions = true; break;\n\t\t\tcase 'a': mode = Abbreviated; break;\n\t\t\tcase 'f': mode = Full; break;\n\t\t\tcase 'c': mode = Compare; break;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) <= 0 ) {\n\t\tcerr << \"No input image file specified.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (optind == 1) { \/\/ No options specified, default is short header\n\t\tmode = Abbreviated;\n\t}\n\tvector<Nifti> images;\n\timages.reserve(argc - optind); \/\/ emplace_back can still trigger copies if the vector has to be resized\n\tfor (;optind < argc; optind++) {\n\t\timages.emplace_back(argv[optind], Nifti::Mode::ReadHeader);\n\t}\n\n\tif (mode == Compare) { \/\/ Compare first image to all others and check headers are compatible\n\t\tfor (auto im = images.begin() + 1; im != images.end(); im++) {\n\t\t\tif (!images[0].matchesSpace(*im)) {\n\t\t\t\tcout << \"Header does not match against file: \" << im->imagePath() << endl;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (auto& im: images) {\n\t\tif (printDims) cout << im.dims().transpose() << endl;\n\t\tif (printVoxdims) cout << voxMessage(im) << endl;\n\t\tif (printTransform) cout << im.transform().matrix() << endl;\n\t\tif (printSize) cout << sizeMessage(im) << endl;\n\t\tif (printData) cout << dataMessage(im) << endl;\n\t\t\n\t\tif (mode == Abbreviated) {\n\t\t\tcout << \"Short Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << \"Dimensions: \" << im.dims().transpose() << endl;\n\t\t\tcout << voxMessage(im) << endl;\n\t\t\tcout << \"XForm matrix: \" << endl << im.transform().matrix() << endl;\n\t\t\tcout << \"Number of extensions: \" << im.extensions().size() << endl;\n\t\t} else if (mode == Full) {\n\t\t\tcout << \"Full Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << dataMessage(im) << endl;\n\t\t\tcout << \"Dimensions: \" << im.dims().transpose() << endl;\n\t\t\tcout << voxMessage(im) << endl;\n\t\t\t\n\t\t\tcout << \"Calibration (min, max): \" << im.calibration_min << \", \" << im.calibration_max << endl;\n\t\t\tcout << \"Scaling (slope, inter): \" << im.scaling_slope << \", \" << im.scaling_inter << endl;\n\t\t\tcout << \"Dimension labels (Phase, Freq, Slice): \" << im.phase_dim << \", \" << im.freq_dim << \", \" << im.slice_dim << endl;\n\t\t\tcout << \"Slice info (Code, Start, End, Duration): \" << \", \" << im.slice_code << \", \" << im.slice_start << \", \" << im.slice_end << \", \" << im.slice_duration << endl;\n\t\t\tcout << \"Slice name: \" << im.sliceName() << endl;\n\t\t\tcout << \"Time offset: \" << im.toffset << endl;\n\t\t\t\n\t\t\tcout << \"Intent name: \" << im.intent_name << endl;\n\t\t\tcout << \"Intent code: \" << im.intentName() << endl;\n\t\t\tcout << \"Intent params: \" << im.intent_p1 << \", \" << im.intent_p2 << \", \" << im.intent_p3 << endl;\n\t\t\tcout << \"Description: \" << im.description << endl;\n\t\t\tcout << \"Aux File: \" << im.aux_file << endl;\n\t\t\tcout << \"QForm: \" << Nifti::XFormName(im.qcode()) << endl;\n\t\t\tcout << im.qform().matrix() << endl;\n\t\t\tcout << \"SForm: \" << Nifti::XFormName(im.scode()) << endl;\n\t\t\tcout << im.sform().matrix() << endl;\n\t\t\tcout << \"Extensions: \" << endl;\n\t\t\tfor (auto &e : im.extensions()) {\n\t\t\t\tcout << \"Extension Code: \" << e.code() << endl;\n\t\t\t\tstring out(e.data().begin(), e.data().end());\n\t\t\t\tcout << out << endl;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n\n<commit_msg>Temporary changes to nifti_hdr to test changes to read\/write interface.<commit_after>\/\/\n\/\/ nifti_hdr.cpp\n\/\/ NiftiImage\n\/\/\n\/\/ Created by Tobias Wood on 08\/07\/2013.\n\/\/ Copyright (c) 2013 Tobias Wood. All rights reserved.\n\/\/\n\n#include <memory>\n#include <vector>\n#include <iostream>\n#include <getopt.h>\n\n#include \"Nifti.h\"\n\nusing namespace std;\n\nconst string usage = \"nifti_hdr - A utility for getting information from Nifti headers.\\n\\\n\\n\\\nUsage: nifti_hdr [options] file1 [other files]\\n\\\nBy default the abbreviated header will be printed for each file.\\n\\\nAbbreviated, full and compare modes are mutually exclusive.\\n\\\n\\n\\\nOptions:\\n\\\n\t-d, --dims : Print the size of each dimension for each file.\\n\\\n\t-v, --vox : Print the voxel sizes for each file (with units). \\n\\\n\t-t, --trans : Print the XForm to physical space with precedence.\\n\\\n\t-a, --abbrev: Print the abbreviated header.\\n\\\n\t-f, --full: Print the entire header.\\n\\\n\t-c, --comp: Compare first file to all others and print message if the.\\n\\\n\t physical spaces are different.\\n\\\n\t-h, --help: Print this message and quit.\\n\\\n\";\n\nenum Modes {\n\tNothing = 0,\n\tAbbreviated,\n\tFull,\n\tCompare\n};\n\nstatic int mode = Nothing;\nstatic int printDims = false, printVoxdims = false, printSize = false, printData = false,\n printTransform = false, printExtensions = false;\n\nstatic struct option long_options[] =\n{\n\t{\"dims\", no_argument, &printDims, true},\n\t{\"vox\", no_argument, &printVoxdims, true},\n\t{\"form\", no_argument, &printTransform, true},\n\t{\"size\", no_argument, &printSize, true},\n\t{\"data\", no_argument, &printData, true},\n\t{\"abbrev\", no_argument, &mode, Abbreviated},\n\t{\"full\", no_argument, &mode, Full},\n\t{\"comp\", no_argument, &mode, Compare},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"ext\", no_argument, 0, 'e'},\n\t{0, 0, 0, 0}\n};\n\nstring voxMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Voxel sizes: \" << im.voxDims().transpose() << \" \" << im.spaceUnits();\n\tif (im.voxDims().rows() > 3) {\n\t\tm << \"\/\" << im.timeUnits();\n\t}\n\treturn m.str();\n}\n\nstring sizeMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Voxels per slice, per volume, total: \"\n << im.voxelsPerSlice() << \", \" << im.voxelsPerVolume() << \", \" << im.voxelsTotal();\n\treturn m.str();\n}\n\nstring dataMessage(const Nifti &im) {\n\tstringstream m;\n\tm << \"Datatype: \" << Nifti::TypeInfo(im.datatype()).name << \", size in bytes: \" << Nifti::TypeInfo(im.datatype()).size;\n\treturn m.str();\n}\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"dvtafchse\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'd': printDims = true; break;\n\t\t\tcase 'v': printVoxdims = true; break;\n\t\t\tcase 't': printTransform = true; break;\n\t\t\tcase 's': printSize = true; break;\n\t\t\tcase 'e': printExtensions = true; break;\n\t\t\tcase 'a': mode = Abbreviated; break;\n\t\t\tcase 'f': mode = Full; break;\n\t\t\tcase 'c': mode = Compare; break;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) <= 0 ) {\n\t\tcerr << \"No input image file specified.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (optind == 1) { \/\/ No options specified, default is short header\n\t\tmode = Abbreviated;\n\t}\n\tvector<Nifti> images;\n\timages.reserve(argc - optind); \/\/ emplace_back can still trigger copies if the vector has to be resized\n\tfor (;optind < argc; optind++) {\n\t\timages.emplace_back(argv[optind], Nifti::Mode::Read);\n\t}\n\n\tif (mode == Compare) { \/\/ Compare first image to all others and check headers are compatible\n\t\tfor (auto im = images.begin() + 1; im != images.end(); im++) {\n\t\t\tif (!images[0].matchesSpace(*im)) {\n\t\t\t\tcout << \"Header does not match against file: \" << im->imagePath() << endl;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (auto& im: images) {\n\t\tif (printDims) cout << im.dims().transpose() << endl;\n\t\tif (printVoxdims) cout << voxMessage(im) << endl;\n\t\tif (printTransform) cout << im.transform().matrix() << endl;\n\t\tif (printSize) cout << sizeMessage(im) << endl;\n\t\tif (printData) cout << dataMessage(im) << endl;\n\t\t\n\t\tif (mode == Abbreviated) {\n\t\t\tcout << \"Short Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << \"Dimensions: \" << im.dims().transpose() << endl;\n\t\t\tcout << voxMessage(im) << endl;\n\t\t\tcout << \"XForm matrix: \" << endl << im.transform().matrix() << endl;\n\t\t\tcout << \"Number of extensions: \" << im.extensions().size() << endl;\n\t\t} else if (mode == Full) {\n\t\t\tcout << \"Full Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << dataMessage(im) << endl;\n\t\t\tcout << \"Dimensions: \" << im.dims().transpose() << endl;\n\t\t\tcout << voxMessage(im) << endl;\n\t\t\t\n\t\t\tcout << \"Calibration (min, max): \" << im.calibration_min << \", \" << im.calibration_max << endl;\n\t\t\tcout << \"Scaling (slope, inter): \" << im.scaling_slope << \", \" << im.scaling_inter << endl;\n\t\t\tcout << \"Dimension labels (Phase, Freq, Slice): \" << im.phase_dim << \", \" << im.freq_dim << \", \" << im.slice_dim << endl;\n\t\t\tcout << \"Slice info (Code, Start, End, Duration): \" << \", \" << im.slice_code << \", \" << im.slice_start << \", \" << im.slice_end << \", \" << im.slice_duration << endl;\n\t\t\tcout << \"Slice name: \" << im.sliceName() << endl;\n\t\t\tcout << \"Time offset: \" << im.toffset << endl;\n\t\t\t\n\t\t\tcout << \"Intent name: \" << im.intent_name << endl;\n\t\t\tcout << \"Intent code: \" << im.intentName() << endl;\n\t\t\tcout << \"Intent params: \" << im.intent_p1 << \", \" << im.intent_p2 << \", \" << im.intent_p3 << endl;\n\t\t\tcout << \"Description: \" << im.description << endl;\n\t\t\tcout << \"Aux File: \" << im.aux_file << endl;\n\t\t\tcout << \"QForm: \" << Nifti::XFormName(im.qcode()) << endl;\n\t\t\tcout << im.qform().matrix() << endl;\n\t\t\tcout << \"SForm: \" << Nifti::XFormName(im.scode()) << endl;\n\t\t\tcout << im.sform().matrix() << endl;\n\t\t\tcout << \"Extensions: \" << endl;\n\t\t\tfor (auto &e : im.extensions()) {\n\t\t\t\tcout << \"Extension Code: \" << e.code() << endl;\n\t\t\t\tstring out(e.data().begin(), e.data().end());\n\t\t\t\tcout << out << endl;\n\t\t\t}\n\t\t}\n\t\tvector<float> data(8);\n\t\tNifti::ArrayXs start(3); Nifti::ArrayXs size(3);\n\t\tstart << 4, 2, 10;\n\t\tsize << 4, 2, 1;\n\t\tcout << \"Before size: \" << data.size() << endl;\n\t\tim.readWriteVoxels(start, size, data);\n\t\tcout << \"After size: \" << data.size() << endl;\n\t\tfor (size_t i = 0; i < 8; i++) cout << data.at(i) << \"\\t\";\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ParallelContext.hpp\"\n\n#include \"Options.hpp\"\n\nusing namespace std;\n\n\/\/ This is just a default size; the buffer will be resized later according to #part and #threads\n#define PARALLEL_BUF_SIZE (128 * 1024)\n\nsize_t ParallelContext::_num_threads = 1;\nsize_t ParallelContext::_num_ranks = 1;\nsize_t ParallelContext::_rank_id = 0;\nthread_local size_t ParallelContext::_thread_id = 0;\nstd::vector<ThreadType> ParallelContext::_threads;\nstd::vector<char> ParallelContext::_parallel_buf;\nstd::unordered_map<ThreadIDType, ParallelContext> ParallelContext::_thread_ctx_map;\nMutexType ParallelContext::mtx;\n\n#ifdef _RAXML_MPI\nMPI_Comm ParallelContext::_comm = MPI_COMM_WORLD;\nbool ParallelContext::_owns_comm = true;\n#endif\n\nvoid ParallelContext::init_mpi(int argc, char * argv[], void * comm)\n{\n#ifdef _RAXML_MPI\n {\n int tmp;\n\n if (comm)\n {\n \/\/ TODO we should think how to get rid of this ugly cast!\n _comm = *((MPI_Comm*) comm);\n _owns_comm = false;\n }\n else\n {\n _comm = MPI_COMM_WORLD;\n _owns_comm = true;\n MPI_Init(&argc, &argv);\n }\n\n MPI_Comm_rank(_comm, &tmp);\n _rank_id = (size_t) tmp;\n MPI_Comm_size(_comm, &tmp);\n _num_ranks = (size_t) tmp;\n\/\/ printf(\"size: %lu, rank: %lu\\n\", _num_ranks, _rank_id);\n }\n#else\n RAXML_UNUSED(argc);\n RAXML_UNUSED(argv);\n RAXML_UNUSED(comm);\n#endif\n}\n\nvoid ParallelContext::start_thread(size_t thread_id, const std::function<void()>& thread_main)\n{\n ParallelContext::_thread_id = thread_id;\n thread_main();\n}\n\nvoid ParallelContext::init_pthreads(const Options& opts, const std::function<void()>& thread_main)\n{\n _num_threads = opts.num_threads;\n _parallel_buf.reserve(PARALLEL_BUF_SIZE);\n\n#ifdef _RAXML_PTHREADS\n \/* Launch threads *\/\n for (size_t i = 1; i < _num_threads; ++i)\n {\n _threads.emplace_back(ParallelContext::start_thread, i, thread_main);\n }\n#endif\n}\n\nvoid ParallelContext::resize_buffer(size_t size)\n{\n _parallel_buf.reserve(size);\n}\n\nvoid ParallelContext::finalize(bool force)\n{\n#ifdef _RAXML_PTHREADS\n for (thread& t: _threads)\n {\n if (force)\n t.detach();\n else\n t.join();\n }\n _threads.clear();\n#endif\n\n#ifdef _RAXML_MPI\n if (_owns_comm)\n {\n if (force)\n MPI_Abort(_comm, -1);\n else\n MPI_Barrier(_comm);\n\n MPI_Finalize();\n }\n else\n MPI_Barrier(_comm);\n#endif\n}\n\nvoid ParallelContext::barrier()\n{\n#ifdef _RAXML_MPI\n mpi_barrier();\n#endif\n\n#ifdef _RAXML_PTHREADS\n thread_barrier();\n#endif\n}\n\nvoid ParallelContext::mpi_barrier()\n{\n#ifdef _RAXML_MPI\n if (_thread_id == 0 && _num_ranks > 1)\n MPI_Barrier(_comm);\n#endif\n}\n\nvoid ParallelContext::thread_barrier()\n{\n static volatile unsigned int barrier_counter = 0;\n static thread_local volatile int myCycle = 0;\n static volatile int proceed = 0;\n\n __sync_fetch_and_add( &barrier_counter, 1);\n\n if(_thread_id == 0)\n {\n while(barrier_counter != ParallelContext::_num_threads);\n barrier_counter = 0;\n proceed = !proceed;\n }\n else\n {\n while(myCycle == proceed);\n myCycle = !myCycle;\n }\n}\n\nvoid ParallelContext::thread_reduce(double * data, size_t size, int op)\n{\n \/* synchronize *\/\n thread_barrier();\n\n double *double_buf = (double*) _parallel_buf.data();\n\n \/* collect data from threads *\/\n size_t i, j;\n for (i = 0; i < size; ++i)\n double_buf[_thread_id * size + i] = data[i];\n\n \/* synchronize *\/\n thread_barrier();\n\n \/* reduce *\/\n for (i = 0; i < size; ++i)\n {\n switch(op)\n {\n case PLLMOD_COMMON_REDUCE_SUM:\n {\n data[i] = 0.;\n for (j = 0; j < ParallelContext::_num_threads; ++j)\n data[i] += double_buf[j * size + i];\n }\n break;\n case PLLMOD_COMMON_REDUCE_MAX:\n {\n data[i] = _parallel_buf[i];\n for (j = 1; j < ParallelContext::_num_threads; ++j)\n data[i] = max(data[i], double_buf[j * size + i]);\n }\n break;\n case PLLMOD_COMMON_REDUCE_MIN:\n {\n data[i] = _parallel_buf[i];\n for (j = 1; j < ParallelContext::_num_threads; ++j)\n data[i] = min(data[i], double_buf[j * size + i]);\n }\n break;\n }\n }\n\n \/\/needed?\n\/\/ parallel_barrier(useropt);\n}\n\n\nvoid ParallelContext::parallel_reduce(double * data, size_t size, int op)\n{\n#ifdef _RAXML_PTHREADS\n if (_num_threads > 1)\n thread_reduce(data, size, op);\n#endif\n\n#ifdef _RAXML_MPI\n if (_num_ranks > 1)\n {\n thread_barrier();\n\n if (_thread_id == 0)\n {\n MPI_Op reduce_op;\n if (op == PLLMOD_COMMON_REDUCE_SUM)\n reduce_op = MPI_SUM;\n else if (op == PLLMOD_COMMON_REDUCE_MAX)\n reduce_op = MPI_MAX;\n else if (op == PLLMOD_COMMON_REDUCE_MIN)\n reduce_op = MPI_MIN;\n else\n assert(0);\n\n#if 1\n MPI_Allreduce(MPI_IN_PLACE, data, size, MPI_DOUBLE, reduce_op, _comm);\n#else\n \/\/ not sure if MPI_IN_PLACE will work in all cases...\n MPI_Allreduce(data, _parallel_buf.data(), size, MPI_DOUBLE, reduce_op, _comm);\n memcpy(data, _parallel_buf.data(), size * sizeof(double));\n#endif\n }\n\n if (_num_threads > 1)\n thread_broadcast(0, data, size * sizeof(double));\n }\n#endif\n}\n\nvoid ParallelContext::parallel_reduce_cb(void * context, double * data, size_t size, int op)\n{\n ParallelContext::parallel_reduce(data, size, op);\n RAXML_UNUSED(context);\n}\n\nvoid ParallelContext::thread_broadcast(size_t source_id, void * data, size_t size)\n{\n \/* write to buf *\/\n if (_thread_id == source_id)\n {\n memcpy((void *) _parallel_buf.data(), data, size);\n }\n\n \/* synchronize *\/\n thread_barrier();\n\n\/\/ pthread_barrier_wait(&barrier);\n __sync_synchronize();\n\n \/* read from buf*\/\n if (_thread_id != source_id)\n {\n memcpy(data, (void *) _parallel_buf.data(), size);\n }\n\n thread_barrier();\n}\n\nvoid ParallelContext::thread_send_master(size_t source_id, void * data, size_t size) const\n{\n \/* write to buf *\/\n if (_thread_id == source_id && data && size)\n {\n memcpy((void *) _parallel_buf.data(), data, size);\n }\n\n \/* synchronize *\/\n barrier();\n\n\/\/ pthread_barrier_wait(&barrier);\n __sync_synchronize();\n\n \/* read from buf*\/\n if (_thread_id == 0)\n {\n memcpy(data, (void *) _parallel_buf.data(), size);\n }\n\n barrier();\n}\n\nvoid ParallelContext::mpi_gather_custom(std::function<int(void*,int)> prepare_send_cb,\n std::function<void(void*,int)> process_recv_cb)\n{\n#ifdef _RAXML_MPI\n \/* we're gonna use _parallel_buf, so make sure other threads don't interfere... *\/\n UniqueLock lock;\n\n if (_rank_id == 0)\n {\n for (size_t r = 1; r < _num_ranks; ++r)\n {\n int recv_size;\n MPI_Status status;\n MPI_Probe(r, 0, _comm, &status);\n MPI_Get_count(&status, MPI_BYTE, &recv_size);\n\n\/\/ printf(\"recv: %lu\\n\", recv_size);\n\n _parallel_buf.reserve(recv_size);\n\n MPI_Recv((void*) _parallel_buf.data(), recv_size, MPI_BYTE,\n r, 0, _comm, MPI_STATUS_IGNORE);\n\n process_recv_cb(_parallel_buf.data(), recv_size);\n }\n }\n else\n {\n auto send_size = prepare_send_cb(_parallel_buf.data(), _parallel_buf.capacity());\n\/\/ printf(\"sent: %lu\\n\", send_size);\n\n MPI_Send(_parallel_buf.data(), send_size, MPI_BYTE, 0, 0, _comm);\n }\n#else\n RAXML_UNUSED(prepare_send_cb);\n RAXML_UNUSED(process_recv_cb);\n#endif\n}\n\n<commit_msg>fix pthread min\/max reduction<commit_after>#include \"ParallelContext.hpp\"\n\n#include \"Options.hpp\"\n\nusing namespace std;\n\n\/\/ This is just a default size; the buffer will be resized later according to #part and #threads\n#define PARALLEL_BUF_SIZE (128 * 1024)\n\nsize_t ParallelContext::_num_threads = 1;\nsize_t ParallelContext::_num_ranks = 1;\nsize_t ParallelContext::_rank_id = 0;\nthread_local size_t ParallelContext::_thread_id = 0;\nstd::vector<ThreadType> ParallelContext::_threads;\nstd::vector<char> ParallelContext::_parallel_buf;\nstd::unordered_map<ThreadIDType, ParallelContext> ParallelContext::_thread_ctx_map;\nMutexType ParallelContext::mtx;\n\n#ifdef _RAXML_MPI\nMPI_Comm ParallelContext::_comm = MPI_COMM_WORLD;\nbool ParallelContext::_owns_comm = true;\n#endif\n\nvoid ParallelContext::init_mpi(int argc, char * argv[], void * comm)\n{\n#ifdef _RAXML_MPI\n {\n int tmp;\n\n if (comm)\n {\n \/\/ TODO we should think how to get rid of this ugly cast!\n _comm = *((MPI_Comm*) comm);\n _owns_comm = false;\n }\n else\n {\n _comm = MPI_COMM_WORLD;\n _owns_comm = true;\n MPI_Init(&argc, &argv);\n }\n\n MPI_Comm_rank(_comm, &tmp);\n _rank_id = (size_t) tmp;\n MPI_Comm_size(_comm, &tmp);\n _num_ranks = (size_t) tmp;\n\/\/ printf(\"size: %lu, rank: %lu\\n\", _num_ranks, _rank_id);\n }\n#else\n RAXML_UNUSED(argc);\n RAXML_UNUSED(argv);\n RAXML_UNUSED(comm);\n#endif\n}\n\nvoid ParallelContext::start_thread(size_t thread_id, const std::function<void()>& thread_main)\n{\n ParallelContext::_thread_id = thread_id;\n thread_main();\n}\n\nvoid ParallelContext::init_pthreads(const Options& opts, const std::function<void()>& thread_main)\n{\n _num_threads = opts.num_threads;\n _parallel_buf.reserve(PARALLEL_BUF_SIZE);\n\n#ifdef _RAXML_PTHREADS\n \/* Launch threads *\/\n for (size_t i = 1; i < _num_threads; ++i)\n {\n _threads.emplace_back(ParallelContext::start_thread, i, thread_main);\n }\n#endif\n}\n\nvoid ParallelContext::resize_buffer(size_t size)\n{\n _parallel_buf.reserve(size);\n}\n\nvoid ParallelContext::finalize(bool force)\n{\n#ifdef _RAXML_PTHREADS\n for (thread& t: _threads)\n {\n if (force)\n t.detach();\n else\n t.join();\n }\n _threads.clear();\n#endif\n\n#ifdef _RAXML_MPI\n if (_owns_comm)\n {\n if (force)\n MPI_Abort(_comm, -1);\n else\n MPI_Barrier(_comm);\n\n MPI_Finalize();\n }\n else\n MPI_Barrier(_comm);\n#endif\n}\n\nvoid ParallelContext::barrier()\n{\n#ifdef _RAXML_MPI\n mpi_barrier();\n#endif\n\n#ifdef _RAXML_PTHREADS\n thread_barrier();\n#endif\n}\n\nvoid ParallelContext::mpi_barrier()\n{\n#ifdef _RAXML_MPI\n if (_thread_id == 0 && _num_ranks > 1)\n MPI_Barrier(_comm);\n#endif\n}\n\nvoid ParallelContext::thread_barrier()\n{\n static volatile unsigned int barrier_counter = 0;\n static thread_local volatile int myCycle = 0;\n static volatile int proceed = 0;\n\n __sync_fetch_and_add( &barrier_counter, 1);\n\n if(_thread_id == 0)\n {\n while(barrier_counter != ParallelContext::_num_threads);\n barrier_counter = 0;\n proceed = !proceed;\n }\n else\n {\n while(myCycle == proceed);\n myCycle = !myCycle;\n }\n}\n\nvoid ParallelContext::thread_reduce(double * data, size_t size, int op)\n{\n \/* synchronize *\/\n thread_barrier();\n\n double *double_buf = (double*) _parallel_buf.data();\n\n \/* collect data from threads *\/\n size_t i, j;\n for (i = 0; i < size; ++i)\n double_buf[_thread_id * size + i] = data[i];\n\n \/* synchronize *\/\n thread_barrier();\n\n \/* reduce *\/\n for (i = 0; i < size; ++i)\n {\n switch(op)\n {\n case PLLMOD_COMMON_REDUCE_SUM:\n {\n data[i] = 0.;\n for (j = 0; j < ParallelContext::_num_threads; ++j)\n data[i] += double_buf[j * size + i];\n }\n break;\n case PLLMOD_COMMON_REDUCE_MAX:\n {\n data[i] = double_buf[i];\n for (j = 1; j < ParallelContext::_num_threads; ++j)\n data[i] = max(data[i], double_buf[j * size + i]);\n }\n break;\n case PLLMOD_COMMON_REDUCE_MIN:\n {\n data[i] = double_buf[i];\n for (j = 1; j < ParallelContext::_num_threads; ++j)\n data[i] = min(data[i], double_buf[j * size + i]);\n }\n break;\n }\n }\n\n \/\/needed?\n\/\/ parallel_barrier(useropt);\n}\n\n\nvoid ParallelContext::parallel_reduce(double * data, size_t size, int op)\n{\n#ifdef _RAXML_PTHREADS\n if (_num_threads > 1)\n thread_reduce(data, size, op);\n#endif\n\n#ifdef _RAXML_MPI\n if (_num_ranks > 1)\n {\n thread_barrier();\n\n if (_thread_id == 0)\n {\n MPI_Op reduce_op;\n if (op == PLLMOD_COMMON_REDUCE_SUM)\n reduce_op = MPI_SUM;\n else if (op == PLLMOD_COMMON_REDUCE_MAX)\n reduce_op = MPI_MAX;\n else if (op == PLLMOD_COMMON_REDUCE_MIN)\n reduce_op = MPI_MIN;\n else\n assert(0);\n\n#if 1\n MPI_Allreduce(MPI_IN_PLACE, data, size, MPI_DOUBLE, reduce_op, _comm);\n#else\n \/\/ not sure if MPI_IN_PLACE will work in all cases...\n MPI_Allreduce(data, _parallel_buf.data(), size, MPI_DOUBLE, reduce_op, _comm);\n memcpy(data, _parallel_buf.data(), size * sizeof(double));\n#endif\n }\n\n if (_num_threads > 1)\n thread_broadcast(0, data, size * sizeof(double));\n }\n#endif\n}\n\nvoid ParallelContext::parallel_reduce_cb(void * context, double * data, size_t size, int op)\n{\n ParallelContext::parallel_reduce(data, size, op);\n RAXML_UNUSED(context);\n}\n\nvoid ParallelContext::thread_broadcast(size_t source_id, void * data, size_t size)\n{\n \/* write to buf *\/\n if (_thread_id == source_id)\n {\n memcpy((void *) _parallel_buf.data(), data, size);\n }\n\n \/* synchronize *\/\n thread_barrier();\n\n\/\/ pthread_barrier_wait(&barrier);\n __sync_synchronize();\n\n \/* read from buf*\/\n if (_thread_id != source_id)\n {\n memcpy(data, (void *) _parallel_buf.data(), size);\n }\n\n thread_barrier();\n}\n\nvoid ParallelContext::thread_send_master(size_t source_id, void * data, size_t size) const\n{\n \/* write to buf *\/\n if (_thread_id == source_id && data && size)\n {\n memcpy((void *) _parallel_buf.data(), data, size);\n }\n\n \/* synchronize *\/\n barrier();\n\n\/\/ pthread_barrier_wait(&barrier);\n __sync_synchronize();\n\n \/* read from buf*\/\n if (_thread_id == 0)\n {\n memcpy(data, (void *) _parallel_buf.data(), size);\n }\n\n barrier();\n}\n\nvoid ParallelContext::mpi_gather_custom(std::function<int(void*,int)> prepare_send_cb,\n std::function<void(void*,int)> process_recv_cb)\n{\n#ifdef _RAXML_MPI\n \/* we're gonna use _parallel_buf, so make sure other threads don't interfere... *\/\n UniqueLock lock;\n\n if (_rank_id == 0)\n {\n for (size_t r = 1; r < _num_ranks; ++r)\n {\n int recv_size;\n MPI_Status status;\n MPI_Probe(r, 0, _comm, &status);\n MPI_Get_count(&status, MPI_BYTE, &recv_size);\n\n\/\/ printf(\"recv: %lu\\n\", recv_size);\n\n _parallel_buf.reserve(recv_size);\n\n MPI_Recv((void*) _parallel_buf.data(), recv_size, MPI_BYTE,\n r, 0, _comm, MPI_STATUS_IGNORE);\n\n process_recv_cb(_parallel_buf.data(), recv_size);\n }\n }\n else\n {\n auto send_size = prepare_send_cb(_parallel_buf.data(), _parallel_buf.capacity());\n\/\/ printf(\"sent: %lu\\n\", send_size);\n\n MPI_Send(_parallel_buf.data(), send_size, MPI_BYTE, 0, 0, _comm);\n }\n#else\n RAXML_UNUSED(prepare_send_cb);\n RAXML_UNUSED(process_recv_cb);\n#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ PlaylistChooser.cpp\n\/\/ Kepler\n\/\/\n\/\/ Created by Tom Carden on 7\/10\/11.\n\/\/ Copyright 2011 Bloom Studio, Inc. All rights reserved.\n\/\/\n\n#include <string>\n#include \"cinder\/Vector.h\"\n#include \"cinder\/PolyLine.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/Path2d.h\"\n#include \"PlaylistChooser.h\"\n#include \"NodeArtist.h\"\n#include \"BloomScene.h\"\n#include \"Globals.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nvoid PlaylistChooser::setup( const Font &font, const Vec2f &interfaceSize )\n{\n mFont\t\t\t\t\t= font;\n mFontHeight = mFont.getAscent() + mFont.getDescent();\n\n mTouchDragId\t\t\t= 0;\n mTouchDragStartPos\t\t= Vec2i( 0, 0 );\n mTouchDragStartOffset\t= 0.0f;\n mTouchDragPlaylistIndex\t= -1;\n \n\tmTouchVel\t\t\t\t= 0.0f;\n\tmTouchPos\t\t\t\t= Vec2i( 0, 0 );\n\tmTouchPrevPos\t\t\t= Vec2i( 0, 0 );\n \n mOffsetX\t\t\t\t= 0.0f;\n\t\n\tmNumPlaylists\t\t\t= 0;\n\tmIsDragging\t\t\t\t= false;\n\t\n\tmPlaylistSize\t\t\t= Vec2f( 150.f, 30.0f );\n\tmSpacerWidth\t\t\t= 15.0f;\n\tmStartY\t\t\t\t\t= 11.0f;\n\n\tmPrevIndex\t\t\t\t= -1;\n\tmCurrentIndex\t\t\t= 0;\n\t\n mInterfaceSize = interfaceSize;\n \n mFullRect.set( 0, 0, mInterfaceSize.x, mStartY + mFontHeight + mStartY );\n}\n\nbool PlaylistChooser::touchBegan( ci::app::TouchEvent::Touch touch )\n{\n if( mData == NULL || mTouchDragPlaylistIndex >= 0 ) return false;\n\t\n mIsDragging\t\t= false;\n\tmTouchPrevPos\t= mTouchPos;\n\tmTouchPos\t\t= globalToLocal( touch.getPos() );\n\tmTouchVel\t\t= 0.0f;\n\t\n Vec2f padding\t= Vec2f( 10.0f, 10.0f );\n \n \/\/ see if we're touching a specific button\n mTouchDragPlaylistIndex = -1;\n\tfor( int i = 0; i < mPlaylistRects.size(); i++ ){\n\t\tif( mPlaylistRects[i] && mPlaylistRects[i]->inflated( padding ).contains( mTouchPos ) ){\n\t\t\tmTouchDragPlaylistIndex = i;\n break;\n }\n\t}\n \n \/\/ allow dragging (but not selection) inside the whole panel as well\n if( mTouchDragPlaylistIndex >= 0 || mFullRect.contains(mTouchPos) ) {\n mTouchDragId\t\t\t= touch.getId();\n mTouchDragStartPos\t\t= mTouchPos;\n mTouchDragStartOffset\t= mOffsetX; \n return true;\n }\n\n return false;\n}\n\nbool PlaylistChooser::touchMoved( ci::app::TouchEvent::Touch touch )\n{\n if (mData == NULL) return false;\n \n mIsDragging = true;\n\t\n mTouchPrevPos\t= mTouchPos;\n mTouchPos\t\t= globalToLocal( touch.getPos() );\n mOffsetX\t\t= mTouchDragStartOffset + (mTouchPos.x - mTouchDragStartPos.x); \n mTouchVel\t\t= mTouchPos.x - mTouchPrevPos.x;\n \n return true;\n}\n\nbool PlaylistChooser::touchEnded( ci::app::TouchEvent::Touch touch )\n{\n if (mData == NULL) return false;\n\n\tmIsDragging\t\t= false;\n\n mTouchPos\t\t= globalToLocal( touch.getPos() );\n mOffsetX\t\t= mTouchDragStartOffset + (mTouchPos.x - mTouchDragStartPos.x); \n \n if (mTouchDragPlaylistIndex >= 0) {\n \n float movement\t= mTouchDragStartPos.distance( mTouchPos );\n if (movement < 15.0f) {\n \/\/ TODO: also measure time and don't allow long selection gaps\n mCurrentIndex = mTouchDragPlaylistIndex;\n mPrevIndex = mCurrentIndex; \/\/ set this so that we won't fire the callback twice\n mCbPlaylistSelected.call( mData->mPlaylists[mTouchDragPlaylistIndex] );\n mCbPlaylistTouched.call( mData->mPlaylists[mTouchDragPlaylistIndex] );\n }\n }\n \n mTouchDragId\t\t\t= 0;\n mTouchDragPlaylistIndex = -1;\n mTouchDragStartPos\t\t= mTouchPos;\n mTouchDragStartOffset\t= mOffsetX;\n \n return true;\n}\n\n\nvoid PlaylistChooser::update()\n{ \n if (mData == NULL) return;\n \n mInterfaceSize = getRoot()->getInterfaceSize();\n \n \/\/ update full rect for layout, hit testing etc.\n mFullRect.set( 0, 0, mInterfaceSize.x, mStartY + mFontHeight + mStartY );\n\n \/\/ total size of all playlist labels + spaces\n float totalWidth = (mPlaylistSize.x * mNumPlaylists) + (mSpacerWidth * (mNumPlaylists+1));\n totalWidth = max( totalWidth, mInterfaceSize.x );\n \n \/\/ min\/max drag positions to leave things in the center\n\/\/ float maxOffsetX = (mInterfaceSize.x \/ 2.0f) - (mPlaylistSize.x \/ 2.0f); \/\/ when dragging right\n\/\/ float minOffsetX = (mPlaylistSize.x \/ 2.0f) + (mInterfaceSize.x \/ 2.0f) - totalWidth; \/\/ when dragging left\n \/\/ min\/max drag positions to keep things on screen\n float maxOffsetX = 0.0f; \/\/ when dragging right\n float minOffsetX = mPlaylistSize.x - totalWidth; \/\/ when dragging left\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\n \n\tif( !mIsDragging ){\n \/\/ carry on with inertia\/momentum scrolling\n\t\tmOffsetX += mTouchVel;\n\t\t\n \/\/ spring back if we've gone too far\n\t\tif( mOffsetX < minOffsetX ){\n\t\t\tmTouchVel = 0.0f;\n\t\t\tmOffsetX += ( minOffsetX - mOffsetX ) * 0.2f;\n\t\t} \n else if( mOffsetX > maxOffsetX ){\n\t\t\tmTouchVel = 0.0f;\n\t\t\tmOffsetX += ( maxOffsetX - mOffsetX ) * 0.2f;\n\t\t}\n\t\t \n if( abs( mTouchVel ) > 1.0f ) {\n \/\/ slow down if we're moving fast:\n mTouchVel *= 0.95f;\n }\n else {\n \/\/ otherwise we're slow enough to think again\n \/\/ so cancel momentum completely:\n\t\t\tmTouchVel\t\t = 0.0f;\n\t\t}\n\t}\n \n \/\/\/\/\/\/\/\/\/\/ update placement rects\n \n mPlaylistRects.clear();\n\n const float y = mStartY;\n const float h = mFontHeight;\n\n float xPos = mOffsetX + mSpacerWidth;\n \n for( int i = 0; i < mNumPlaylists; i++ )\n\t{\t\n if( xPos < mInterfaceSize.x && xPos + mPlaylistSize.x > 0.0f )\n\t\t{ \n\t\t\tif (!mTextures[i]) {\n\t\t\t\tmakeTexture( i, mData->mPlaylists[i] );\n } \n \/\/ put texture rect at center of playlist rect\n\t\t\tconst float cx = xPos + mPlaylistSize.x * 0.5f;\n\t\t\tconst float w2 = mTextures[i].getWidth() * 0.5f;\n\t\t\tmPlaylistRects.push_back( RectRef( new Rectf( cx - w2, y, cx + w2, y + h ) ) );\n } \n else {\n\t\t\tmPlaylistRects.push_back( RectRef() );\n\t\t}\n\t\t\n xPos += mSpacerWidth + mPlaylistSize.x;\n } \n}\n\n\nvoid PlaylistChooser::draw()\n{\n\tif( mData == NULL ) return;\n\t\n\tgl::disableDepthRead();\n\tgl::disableDepthWrite();\n\tgl::enableAlphaBlending();\n\tgl::enableAdditiveBlending();\n\n float r = BRIGHT_BLUE.r;\n float g = BRIGHT_BLUE.g;\n float b = BRIGHT_BLUE.b;\n \/\/ opacity is supplied by UiLayer::draw\n \n gl::color( ColorA( r, g, b, mOpacity * 0.125f ) );\n gl::drawLine( Vec2f(0,0), Vec2f(mInterfaceSize.x,0) );\n\n\/\/ float xPos = mOffsetX + mSpacerWidth;\n \n for( int i = 0; i < mNumPlaylists; i++ )\n\t{\t\n RectRef rect = mPlaylistRects[i];\n if( rect && rect->x1 < mInterfaceSize.x && rect->x2 > 0.0f )\n { \n if ( i == mCurrentIndex ) {\n gl::color( ColorA( BRIGHT_BLUE, mOpacity ) );\n } \n else if ( i == mTouchDragPlaylistIndex ) {\n gl::color( ColorA( 1, 1, 1, mOpacity ) );\n } \n else {\n gl::color( ColorA( BLUE, mOpacity ) );\n }\n \n gl::draw( mTextures[i], rect->getUpperLeft() );\n \n\/\/ gl::color( Color::white() );\n\/\/ gl::drawStrokedRect( *rect ); \n }\n \n\/\/ gl::color( Color::white() );\n\/\/ gl::drawStrokedRect( Rectf( xPos, mStartY, xPos + mPlaylistSize.x, mStartY + mFontHeight ) ); \n\/\/\n\/\/ xPos += mPlaylistSize.x + mSpacerWidth;\n }\n \n\/\/ Rectf center( (mInterfaceSize.x - mPlaylistSize.x) \/ 2.0f, 0.0f, \n\/\/ (mInterfaceSize.x + mPlaylistSize.x) \/ 2.0f, mFullRect.getHeight() );\n\/\/\n\/\/ gl::color( ColorA( BRIGHT_BLUE, alpha * 0.15f ) );\n\/\/ gl::drawSolidRect( center );\n\/\/ \n\/\/ gl::color( ColorA( BRIGHT_BLUE, alpha * 0.5f ) );\n\/\/ gl::drawSolidRect( Rectf( center.x1, center.y1 + 0.0f, center.x2, center.y1 + 3.0f ) );\n\/\/ gl::drawSolidRect( Rectf( center.x1, center.y2 - 3.0f, center.x2, center.y2 - 0.0f ) );\n \n\tgl::disableDepthRead();\n\tgl::disableDepthWrite();\n\tgl::enableAlphaBlending();\n}\n\nvoid PlaylistChooser::makeTexture( int index, ipod::PlaylistRef playlist )\n{\n \/\/ FIXME: measure the texture and shorten the name if needed\n\tstring name = playlist->getPlaylistName();\n\tif( name.length() > 19 ){\n\t\tname = name.substr( 0, 18 );\n\t\tname += \"...\";\n\t}\n\tTextLayout layout;\n\tlayout.setFont( mFont );\n\tlayout.setColor( Color::white() );\n\tlayout.addLine( name );\n\tmTextures[index] = gl::Texture( layout.render( true, false ) );\n}\n\nfloat PlaylistChooser::getAlpha( float x )\n{\n\tfloat per\t\t= x \/ mInterfaceSize.x;\n\tfloat invCos\t= ( 1.0f - (float)cos( per * TWO_PI ) ) * 0.5f;\n\tfloat cosPer\t= pow( invCos, 0.5f );\n\treturn cosPer;\n}\n\nvoid PlaylistChooser::setDataWorldCam( Data *data, World *world, CameraPersp *cam )\n{\n mData\t\t\t= data;\n mWorld\t\t\t= world;\n mCam\t\t\t= cam;\n\tmNumPlaylists\t= mData->mPlaylists.size();\n mTextures.resize(mNumPlaylists);\n}\n\nfloat PlaylistChooser::getHeight()\n{\n return mFullRect.getHeight();\n}\n\n\n<commit_msg>fix drag limits for small numbers of playlists<commit_after>\/\/\n\/\/ PlaylistChooser.cpp\n\/\/ Kepler\n\/\/\n\/\/ Created by Tom Carden on 7\/10\/11.\n\/\/ Copyright 2011 Bloom Studio, Inc. All rights reserved.\n\/\/\n\n#include <string>\n#include \"cinder\/Vector.h\"\n#include \"cinder\/PolyLine.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/Path2d.h\"\n#include \"PlaylistChooser.h\"\n#include \"NodeArtist.h\"\n#include \"BloomScene.h\"\n#include \"Globals.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nvoid PlaylistChooser::setup( const Font &font, const Vec2f &interfaceSize )\n{\n mFont\t\t\t\t\t= font;\n mFontHeight = mFont.getAscent() + mFont.getDescent();\n\n mTouchDragId\t\t\t= 0;\n mTouchDragStartPos\t\t= Vec2i( 0, 0 );\n mTouchDragStartOffset\t= 0.0f;\n mTouchDragPlaylistIndex\t= -1;\n \n\tmTouchVel\t\t\t\t= 0.0f;\n\tmTouchPos\t\t\t\t= Vec2i( 0, 0 );\n\tmTouchPrevPos\t\t\t= Vec2i( 0, 0 );\n \n mOffsetX\t\t\t\t= 0.0f;\n\t\n\tmNumPlaylists\t\t\t= 0;\n\tmIsDragging\t\t\t\t= false;\n\t\n\tmPlaylistSize\t\t\t= Vec2f( 150.f, 30.0f );\n\tmSpacerWidth\t\t\t= 15.0f;\n\tmStartY\t\t\t\t\t= 11.0f;\n\n\tmPrevIndex\t\t\t\t= -1;\n\tmCurrentIndex\t\t\t= 0;\n\t\n mInterfaceSize = interfaceSize;\n \n mFullRect.set( 0, 0, mInterfaceSize.x, mStartY + mFontHeight + mStartY );\n}\n\nbool PlaylistChooser::touchBegan( ci::app::TouchEvent::Touch touch )\n{\n if( mData == NULL || mTouchDragPlaylistIndex >= 0 ) return false;\n\t\n mIsDragging\t\t= false;\n\tmTouchPrevPos\t= mTouchPos;\n\tmTouchPos\t\t= globalToLocal( touch.getPos() );\n\tmTouchVel\t\t= 0.0f;\n\t\n Vec2f padding\t= Vec2f( 10.0f, 10.0f );\n \n \/\/ see if we're touching a specific button\n mTouchDragPlaylistIndex = -1;\n\tfor( int i = 0; i < mPlaylistRects.size(); i++ ){\n\t\tif( mPlaylistRects[i] && mPlaylistRects[i]->inflated( padding ).contains( mTouchPos ) ){\n\t\t\tmTouchDragPlaylistIndex = i;\n break;\n }\n\t}\n \n \/\/ allow dragging (but not selection) inside the whole panel as well\n if( mTouchDragPlaylistIndex >= 0 || mFullRect.contains(mTouchPos) ) {\n mTouchDragId\t\t\t= touch.getId();\n mTouchDragStartPos\t\t= mTouchPos;\n mTouchDragStartOffset\t= mOffsetX; \n return true;\n }\n\n return false;\n}\n\nbool PlaylistChooser::touchMoved( ci::app::TouchEvent::Touch touch )\n{\n if (mData == NULL) return false;\n \n mIsDragging = true;\n\t\n mTouchPrevPos\t= mTouchPos;\n mTouchPos\t\t= globalToLocal( touch.getPos() );\n mOffsetX\t\t= mTouchDragStartOffset + (mTouchPos.x - mTouchDragStartPos.x); \n mTouchVel\t\t= mTouchPos.x - mTouchPrevPos.x;\n \n return true;\n}\n\nbool PlaylistChooser::touchEnded( ci::app::TouchEvent::Touch touch )\n{\n if (mData == NULL) return false;\n\n\tmIsDragging\t\t= false;\n\n mTouchPos\t\t= globalToLocal( touch.getPos() );\n mOffsetX\t\t= mTouchDragStartOffset + (mTouchPos.x - mTouchDragStartPos.x); \n \n if (mTouchDragPlaylistIndex >= 0) {\n \n float movement\t= mTouchDragStartPos.distance( mTouchPos );\n if (movement < 15.0f) {\n \/\/ TODO: also measure time and don't allow long selection gaps\n mCurrentIndex = mTouchDragPlaylistIndex;\n mPrevIndex = mCurrentIndex; \/\/ set this so that we won't fire the callback twice\n mCbPlaylistSelected.call( mData->mPlaylists[mTouchDragPlaylistIndex] );\n mCbPlaylistTouched.call( mData->mPlaylists[mTouchDragPlaylistIndex] );\n }\n }\n \n mTouchDragId\t\t\t= 0;\n mTouchDragPlaylistIndex = -1;\n mTouchDragStartPos\t\t= mTouchPos;\n mTouchDragStartOffset\t= mOffsetX;\n \n return true;\n}\n\n\nvoid PlaylistChooser::update()\n{ \n if (mData == NULL) return;\n \n mInterfaceSize = getRoot()->getInterfaceSize();\n \n \/\/ update full rect for layout, hit testing etc.\n mFullRect.set( 0, 0, mInterfaceSize.x, mStartY + mFontHeight + mStartY );\n\n \/\/ total size of all playlist labels + spaces\n float totalWidth = (mPlaylistSize.x * mNumPlaylists) + (mSpacerWidth * (mNumPlaylists+1));\n float maxOffsetX = 0.0f;\n float minOffsetX = 0.0f;\n \n if ( totalWidth < mInterfaceSize.x) {\n maxOffsetX = mInterfaceSize.x - totalWidth;\n }\n else {\n minOffsetX = mInterfaceSize.x - totalWidth;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\n \n\tif( !mIsDragging ){\n \/\/ carry on with inertia\/momentum scrolling\n\t\tmOffsetX += mTouchVel;\n\t\t\n \/\/ spring back if we've gone too far\n\t\tif( mOffsetX < minOffsetX ){\n\t\t\tmTouchVel = 0.0f;\n\t\t\tmOffsetX += ( minOffsetX - mOffsetX ) * 0.2f;\n\t\t} \n else if( mOffsetX > maxOffsetX ){\n\t\t\tmTouchVel = 0.0f;\n\t\t\tmOffsetX += ( maxOffsetX - mOffsetX ) * 0.2f;\n\t\t}\n\t\t \n if( abs( mTouchVel ) > 1.0f ) {\n \/\/ slow down if we're moving fast:\n mTouchVel *= 0.95f;\n }\n else {\n \/\/ otherwise we're slow enough to think again\n \/\/ so cancel momentum completely:\n\t\t\tmTouchVel\t\t = 0.0f;\n\t\t}\n\t}\n \n \/\/\/\/\/\/\/\/\/\/ update placement rects\n \n mPlaylistRects.clear();\n\n const float y = mStartY;\n const float h = mFontHeight;\n\n float xPos = mOffsetX + mSpacerWidth;\n \n for( int i = 0; i < mNumPlaylists; i++ )\n\t{\t\n if( xPos < mInterfaceSize.x && xPos + mPlaylistSize.x > 0.0f )\n\t\t{ \n\t\t\tif (!mTextures[i]) {\n\t\t\t\tmakeTexture( i, mData->mPlaylists[i] );\n } \n \/\/ put texture rect at center of playlist rect\n\t\t\tconst float cx = xPos + mPlaylistSize.x * 0.5f;\n\t\t\tconst float w2 = mTextures[i].getWidth() * 0.5f;\n\t\t\tmPlaylistRects.push_back( RectRef( new Rectf( cx - w2, y, cx + w2, y + h ) ) );\n } \n else {\n\t\t\tmPlaylistRects.push_back( RectRef() );\n\t\t}\n\t\t\n xPos += mSpacerWidth + mPlaylistSize.x;\n } \n}\n\n\nvoid PlaylistChooser::draw()\n{\n\tif( mData == NULL ) return;\n\t\n\tgl::disableDepthRead();\n\tgl::disableDepthWrite();\n\tgl::enableAlphaBlending();\n\tgl::enableAdditiveBlending();\n\n float r = BRIGHT_BLUE.r;\n float g = BRIGHT_BLUE.g;\n float b = BRIGHT_BLUE.b;\n \/\/ opacity is supplied by UiLayer::draw\n \n gl::color( ColorA( r, g, b, mOpacity * 0.125f ) );\n gl::drawLine( Vec2f(0,0), Vec2f(mInterfaceSize.x,0) );\n\n\/\/ float xPos = mOffsetX + mSpacerWidth;\n \n for( int i = 0; i < mNumPlaylists; i++ )\n\t{\t\n RectRef rect = mPlaylistRects[i];\n if( rect && rect->x1 < mInterfaceSize.x && rect->x2 > 0.0f )\n { \n if ( i == mCurrentIndex ) {\n gl::color( ColorA( BRIGHT_BLUE, mOpacity ) );\n } \n else if ( i == mTouchDragPlaylistIndex ) {\n gl::color( ColorA( 1, 1, 1, mOpacity ) );\n } \n else {\n gl::color( ColorA( BLUE, mOpacity ) );\n }\n \n gl::draw( mTextures[i], rect->getUpperLeft() );\n \n\/\/ gl::color( Color::white() );\n\/\/ gl::drawStrokedRect( *rect ); \n }\n \n\/\/ gl::color( Color::white() );\n\/\/ gl::drawStrokedRect( Rectf( xPos, mStartY, xPos + mPlaylistSize.x, mStartY + mFontHeight ) ); \n\/\/\n\/\/ xPos += mPlaylistSize.x + mSpacerWidth;\n }\n \n\/\/ Rectf center( (mInterfaceSize.x - mPlaylistSize.x) \/ 2.0f, 0.0f, \n\/\/ (mInterfaceSize.x + mPlaylistSize.x) \/ 2.0f, mFullRect.getHeight() );\n\/\/\n\/\/ gl::color( ColorA( BRIGHT_BLUE, alpha * 0.15f ) );\n\/\/ gl::drawSolidRect( center );\n\/\/ \n\/\/ gl::color( ColorA( BRIGHT_BLUE, alpha * 0.5f ) );\n\/\/ gl::drawSolidRect( Rectf( center.x1, center.y1 + 0.0f, center.x2, center.y1 + 3.0f ) );\n\/\/ gl::drawSolidRect( Rectf( center.x1, center.y2 - 3.0f, center.x2, center.y2 - 0.0f ) );\n \n\tgl::disableDepthRead();\n\tgl::disableDepthWrite();\n\tgl::enableAlphaBlending();\n}\n\nvoid PlaylistChooser::makeTexture( int index, ipod::PlaylistRef playlist )\n{\n \/\/ FIXME: measure the texture and shorten the name if needed\n\tstring name = playlist->getPlaylistName();\n\tif( name.length() > 19 ){\n\t\tname = name.substr( 0, 18 );\n\t\tname += \"...\";\n\t}\n\tTextLayout layout;\n\tlayout.setFont( mFont );\n\tlayout.setColor( Color::white() );\n\tlayout.addLine( name );\n\tmTextures[index] = gl::Texture( layout.render( true, false ) );\n}\n\nfloat PlaylistChooser::getAlpha( float x )\n{\n\tfloat per\t\t= x \/ mInterfaceSize.x;\n\tfloat invCos\t= ( 1.0f - (float)cos( per * TWO_PI ) ) * 0.5f;\n\tfloat cosPer\t= pow( invCos, 0.5f );\n\treturn cosPer;\n}\n\nvoid PlaylistChooser::setDataWorldCam( Data *data, World *world, CameraPersp *cam )\n{\n mData\t\t\t= data;\n mWorld\t\t\t= world;\n mCam\t\t\t= cam;\n\tmNumPlaylists\t= mData->mPlaylists.size();\n mTextures.resize(mNumPlaylists);\n}\n\nfloat PlaylistChooser::getHeight()\n{\n return mFullRect.getHeight();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: componentcontext.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: ihi $ $Date: 2006-08-28 15:10:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_COMPONENTCONTEXT_HXX\n#define COMPHELPER_COMPONENTCONTEXT_HXX\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include <comphelper\/comphelperdllapi.h>\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n \/\/====================================================================\n \/\/= ComponentContext\n \/\/====================================================================\n \/** a helper class for working with a component context\n *\/\n class COMPHELPER_DLLPUBLIC ComponentContext\n {\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB;\n\n public:\n \/** constructs an instance\n @param _rxContext\n the component context to manage\n @throws ::com::sun::star::lang::NullPointerException\n if the given context, or its component factory, are <NULL\/>\n *\/\n ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );\n\n \/** constructs an instance\n @param _rxLegacyFactory\n the legacy service factor to obtain the <type scope=\"com::sun::star::uno\">XComponentContext<\/type> from\n @throws ::com::sun::star::uno::RuntimeException\n if the given factory or does not have a DefaultContext property to obtain\n a component context\n @throws ::com::sun::star::lang::NullPointerException\n if the given factory is <NULL\/>, or provides a component context being <NULL\/>, or provides\n a component context whose component factory is <NULL\/>\n *\/\n ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory );\n\n \/** returns the ->XComponentContext interface\n *\/\n inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >\n getUNOContext() const { return m_xContext; }\n\n \/** determines whether the context is not <NULL\/>\n *\/\n inline sal_Bool is() const\n {\n return m_xContext.is();\n }\n\n \/** creates a component using our component factory\/context\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n _out_rxComponent.clear();\n _out_rxComponent = _out_rxComponent.query(\n m_xORB->createInstanceWithContext( _rServiceName, m_xContext )\n );\n return _out_rxComponent.is();\n }\n\n \/** creates a component using our component factory\/context\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent );\n }\n\n \/** creates a component using our component factory\/context, passing creation arguments\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n _out_rxComponent.clear();\n _out_rxComponent = _out_rxComponent.query(\n m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext )\n );\n return _out_rxComponent.is();\n }\n\n \/** creates a component using our component factory\/context, passing creation arguments\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent );\n }\n\n \/** creates a component using our component factory\/context\n\n @throws ::com::sun::star::lang::ServiceNotRegisteredException\n if the given service is not registered\n @throws Exception\n if an exception occured during creating the component\n @return\n the newly created component. Is never <NULL\/>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const;\n\n \/** creates a component using our component factory\/context\n\n @throws ::com::sun::star::lang::ServiceNotRegisteredException\n if the given service is not registered\n @throws Exception\n if an exception occured during creating the component\n @return\n the newly created component. Is never <NULL\/>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const\n {\n return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) );\n }\n\n \/** retrieves a singleton instance from the context\n\n Singletons are collected below the <code>\/singletons<\/code> key in a component context,\n so accessing them means retrieving the value under <code>\/singletons\/<instance_name><\/code>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName );\n\n \/** retrieves a singleton instance from the context\n\n Singletons are collected below the <code>\/singletons<\/code> key in a component context,\n so accessing them means retrieving the value under <code>\/singletons\/<instance_name><\/code>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName )\n {\n return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) );\n }\n\n \/** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to\n older code which does not yet support ->XMultiComponentFactory\n @throws ::com::sun::star::uno::RuntimeException\n if our our component factory does not support this interface\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n getLegacyServiceFactory() const;\n\n \/** retrieves a value from our component context\n @param _rName\n the name of the value to retrieve\n @return\n the context value with the given name\n @seealso XComponentContext::getValueByName\n @seealso getContextValueByAsciiName\n *\/\n ::com::sun::star::uno::Any\n getContextValueByName( const ::rtl::OUString& _rName ) const;\n\n \/** retrieves a value from our component context, specified by 8-bit ASCII string\n @param _rName\n the name of the value to retrieve, as ASCII character string\n @return\n the context value with the given name\n @seealso XComponentContext::getValueByName\n @seealso getContextValueByName\n *\/\n inline ::com::sun::star::uno::Any\n getContextValueByAsciiName( const sal_Char* _pAsciiName ) const\n {\n return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) );\n }\n\n };\n\n\/\/........................................................................\n} \/\/ namespace comphelper\n\/\/........................................................................\n\n#endif \/\/ COMPHELPER_COMPONENTCONTEXT_HXX\n\n<commit_msg>INTEGRATION: CWS sdblogging (1.3.58); FILE MERGED 2007\/04\/11 08:48:02 fs 1.3.58.1: getSingleton should be const<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: componentcontext.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 14:53:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_COMPONENTCONTEXT_HXX\n#define COMPHELPER_COMPONENTCONTEXT_HXX\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include <comphelper\/comphelperdllapi.h>\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n \/\/====================================================================\n \/\/= ComponentContext\n \/\/====================================================================\n \/** a helper class for working with a component context\n *\/\n class COMPHELPER_DLLPUBLIC ComponentContext\n {\n private:\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB;\n\n public:\n \/** constructs an instance\n @param _rxContext\n the component context to manage\n @throws ::com::sun::star::lang::NullPointerException\n if the given context, or its component factory, are <NULL\/>\n *\/\n ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext );\n\n \/** constructs an instance\n @param _rxLegacyFactory\n the legacy service factor to obtain the <type scope=\"com::sun::star::uno\">XComponentContext<\/type> from\n @throws ::com::sun::star::uno::RuntimeException\n if the given factory or does not have a DefaultContext property to obtain\n a component context\n @throws ::com::sun::star::lang::NullPointerException\n if the given factory is <NULL\/>, or provides a component context being <NULL\/>, or provides\n a component context whose component factory is <NULL\/>\n *\/\n ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory );\n\n \/** returns the ->XComponentContext interface\n *\/\n inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >\n getUNOContext() const { return m_xContext; }\n\n \/** determines whether the context is not <NULL\/>\n *\/\n inline sal_Bool is() const\n {\n return m_xContext.is();\n }\n\n \/** creates a component using our component factory\/context\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n _out_rxComponent.clear();\n _out_rxComponent = _out_rxComponent.query(\n m_xORB->createInstanceWithContext( _rServiceName, m_xContext )\n );\n return _out_rxComponent.is();\n }\n\n \/** creates a component using our component factory\/context\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent );\n }\n\n \/** creates a component using our component factory\/context, passing creation arguments\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n _out_rxComponent.clear();\n _out_rxComponent = _out_rxComponent.query(\n m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext )\n );\n return _out_rxComponent.is();\n }\n\n \/** creates a component using our component factory\/context, passing creation arguments\n @throws ::com::sun::star::uno::Exception\n @return\n <TRUE\/> if and only if the component could be successfully created\n *\/\n template < typename INTERFACE >\n bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const\n {\n return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent );\n }\n\n \/** creates a component using our component factory\/context\n\n @throws ::com::sun::star::lang::ServiceNotRegisteredException\n if the given service is not registered\n @throws Exception\n if an exception occured during creating the component\n @return\n the newly created component. Is never <NULL\/>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const;\n\n \/** creates a component using our component factory\/context\n\n @throws ::com::sun::star::lang::ServiceNotRegisteredException\n if the given service is not registered\n @throws Exception\n if an exception occured during creating the component\n @return\n the newly created component. Is never <NULL\/>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const\n {\n return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) );\n }\n\n \/** retrieves a singleton instance from the context\n\n Singletons are collected below the <code>\/singletons<\/code> key in a component context,\n so accessing them means retrieving the value under <code>\/singletons\/<instance_name><\/code>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName ) const;\n\n \/** retrieves a singleton instance from the context\n\n Singletons are collected below the <code>\/singletons<\/code> key in a component context,\n so accessing them means retrieving the value under <code>\/singletons\/<instance_name><\/code>.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName ) const\n {\n return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) );\n }\n\n \/** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to\n older code which does not yet support ->XMultiComponentFactory\n @throws ::com::sun::star::uno::RuntimeException\n if our our component factory does not support this interface\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n getLegacyServiceFactory() const;\n\n \/** retrieves a value from our component context\n @param _rName\n the name of the value to retrieve\n @return\n the context value with the given name\n @seealso XComponentContext::getValueByName\n @seealso getContextValueByAsciiName\n *\/\n ::com::sun::star::uno::Any\n getContextValueByName( const ::rtl::OUString& _rName ) const;\n\n \/** retrieves a value from our component context, specified by 8-bit ASCII string\n @param _rName\n the name of the value to retrieve, as ASCII character string\n @return\n the context value with the given name\n @seealso XComponentContext::getValueByName\n @seealso getContextValueByName\n *\/\n inline ::com::sun::star::uno::Any\n getContextValueByAsciiName( const sal_Char* _pAsciiName ) const\n {\n return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) );\n }\n\n };\n\n\/\/........................................................................\n} \/\/ namespace comphelper\n\/\/........................................................................\n\n#endif \/\/ COMPHELPER_COMPONENTCONTEXT_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include \"File.h\"\n\n#include <fstream>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n\nusing namespace std;\n\nnamespace File\n{\n size_t FindFile(char const* path, char const* mask, std::function<void(char const*, size_t)> functor)\n {\n WIN32_FIND_DATA fileData;\n HANDLE hFiles;\n\n string search = path;\n search += \"\/\";\n search += mask;\n\n hFiles = FindFirstFile(search.c_str(), &fileData);\n\n if (INVALID_HANDLE_VALUE == hFiles)\n {\n return 0;\n }\n\n size_t count = 0;\n\n do\n {\n if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\n {\n \/\/ recursive option?\n }\n else\n {\n string filename = path;\n filename += \"\/\";\n filename += fileData.cFileName;\n if (sizeof(size_t) == 4)\n {\n if (fileData.nFileSizeHigh)\n continue;\n\n functor(filename.c_str(), fileData.nFileSizeLow);\n }\n else\n {\n functor(filename.c_str(), (__int64)fileData.nFileSizeHigh << 32 | fileData.nFileSizeLow);\n }\n ++count;\n }\n } while (FindNextFile(hFiles, &fileData) != 0);\n\n return count;\n }\n\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFileData(fstream& file, size_t bytes)\n {\n bytes = bytes < UINT32_MAX ? bytes : UINT32_MAX;\n\n vector<char> data;\n data.resize(bytes);\n file.read(data.data(), bytes);\n\n if (file.gcount() < bytes)\n data.resize((unsigned int)file.gcount());\n return data;\n }\n\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFile(char const* filename)\n {\n fstream file(filename, fstream::binary | fstream::in);\n\n file.seekg(fstream::end);\n size_t bytes = (size_t)file.tellg();\n file.seekg(fstream::beg);\n\n return ReadFileData(file, bytes);\n }\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFile(char const* filename, size_t bytes)\n {\n return ReadFileData(fstream(filename, fstream::binary | fstream::in), bytes);\n }\n}<commit_msg>Fix compiler warning<commit_after>#include \"File.h\"\n\n#include <fstream>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n\nusing namespace std;\n\nnamespace File\n{\n size_t FindFile(char const* path, char const* mask, std::function<void(char const*, size_t)> functor)\n {\n WIN32_FIND_DATA fileData;\n HANDLE hFiles;\n\n string search = path;\n search += \"\/\";\n search += mask;\n\n hFiles = FindFirstFile(search.c_str(), &fileData);\n\n if (INVALID_HANDLE_VALUE == hFiles)\n {\n return 0;\n }\n\n size_t count = 0;\n\n do\n {\n if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\n {\n \/\/ recursive option?\n }\n else\n {\n string filename = path;\n filename += \"\/\";\n filename += fileData.cFileName;\n if (sizeof(size_t) == 4)\n {\n if (fileData.nFileSizeHigh)\n continue;\n\n functor(filename.c_str(), fileData.nFileSizeLow);\n }\n else\n {\n functor(filename.c_str(), (__int64)fileData.nFileSizeHigh << 32 | fileData.nFileSizeLow);\n }\n ++count;\n }\n } while (FindNextFile(hFiles, &fileData) != 0);\n\n return count;\n }\n\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFileData(fstream& file, size_t bytes)\n {\n bytes = bytes < UINT32_MAX ? bytes : UINT32_MAX;\n\n vector<char> data;\n data.resize(bytes);\n file.read(data.data(), bytes);\n\n if (file.gcount() >= 0 && (size_t)file.gcount() < bytes)\n data.resize((unsigned int)file.gcount());\n return data;\n }\n\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFile(char const* filename)\n {\n fstream file(filename, fstream::binary | fstream::in);\n\n file.seekg(fstream::end);\n size_t bytes = (size_t)file.tellg();\n file.seekg(fstream::beg);\n\n return ReadFileData(file, bytes);\n }\n \/\/----------------------------------------------------------------------------------------\n vector<char> ReadFile(char const* filename, size_t bytes)\n {\n return ReadFileData(fstream(filename, fstream::binary | fstream::in), bytes);\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppClient.h\"\n#include \"QXmppConstants.h\"\n#include \"QXmppInvokable.h\"\n#include \"QXmppRemoteMethod.h\"\n#include \"QXmppRpcIq.h\"\n#include \"QXmppRpcManager.h\"\n\n\/\/\/ Constructs a QXmppRpcManager.\n\nQXmppRpcManager::QXmppRpcManager()\n{\n}\n\n\/\/\/ Adds a local interface which can be queried using RPC.\n\/\/\/\n\/\/\/ \\param interface\n\nvoid QXmppRpcManager::addInvokableInterface( QXmppInvokable *interface )\n{\n m_interfaces[ interface->metaObject()->className() ] = interface;\n}\n\n\/\/\/ Invokes a remote interface using RPC.\n\/\/\/\n\/\/\/ \\param iq\n\nvoid QXmppRpcManager::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq )\n{\n QXmppStanza::Error error;\n \n const QStringList methodBits = iq.method().split('.');\n if (methodBits.size() != 2)\n return;\n const QString interface = methodBits.first();\n const QString method = methodBits.last();\n QXmppInvokable *iface = m_interfaces.value(interface);\n if (iface)\n {\n if ( iface->isAuthorized( iq.from() ) )\n {\n\n if ( iface->interfaces().contains(method) )\n {\n QVariant result = iface->dispatch(method.toLatin1(),\n iq.arguments() );\n QXmppRpcResponseIq resultIq;\n resultIq.setId(iq.id());\n resultIq.setTo(iq.from());\n resultIq.setValues(QVariantList() << result);\n client()->sendPacket( resultIq );\n return;\n }\n else\n {\n error.setType(QXmppStanza::Error::Cancel);\n error.setCondition(QXmppStanza::Error::ItemNotFound);\n }\n }\n else\n {\n error.setType(QXmppStanza::Error::Auth);\n error.setCondition(QXmppStanza::Error::Forbidden);\n }\n }\n else\n {\n error.setType(QXmppStanza::Error::Cancel);\n error.setCondition(QXmppStanza::Error::ItemNotFound);\n }\n QXmppRpcErrorIq errorIq;\n errorIq.setId(iq.id());\n errorIq.setTo(iq.from());\n errorIq.setQuery(iq);\n errorIq.setError(error);\n client()->sendPacket(errorIq);\n}\n\n\/\/\/ Call a remote method using RPC with the specified arguments.\n\nQXmppRemoteMethodResult QXmppRpcManager::callRemoteMethod( const QString &jid,\n const QString &interface,\n const QVariant &arg1,\n const QVariant &arg2,\n const QVariant &arg3,\n const QVariant &arg4,\n const QVariant &arg5,\n const QVariant &arg6,\n const QVariant &arg7,\n const QVariant &arg8,\n const QVariant &arg9,\n const QVariant &arg10 )\n{\n QVariantList args;\n if( arg1.isValid() ) args << arg1;\n if( arg2.isValid() ) args << arg2;\n if( arg3.isValid() ) args << arg3;\n if( arg4.isValid() ) args << arg4;\n if( arg5.isValid() ) args << arg5;\n if( arg6.isValid() ) args << arg6;\n if( arg7.isValid() ) args << arg7;\n if( arg8.isValid() ) args << arg8;\n if( arg9.isValid() ) args << arg9;\n if( arg10.isValid() ) args << arg10;\n\n QXmppRemoteMethod method( jid, interface, args, client() );\n connect(this, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)),\n &method, SLOT(gotResult(QXmppRpcResponseIq)));\n connect(this, SIGNAL(rpcCallError(QXmppRpcErrorIq)),\n &method, SLOT(gotError(QXmppRpcErrorIq)));\n\n return method.call();\n}\n\nQStringList QXmppRpcManager::discoveryFeatures() const\n{\n \/\/ XEP-0009: Jabber-RPC\n return QStringList() << ns_rpc;\n}\n\nQList<QXmppDiscoveryIq::Identity> QXmppRpcManager::discoveryIdentities() const\n{\n QXmppDiscoveryIq::Identity identity;\n identity.setCategory(\"automation\");\n identity.setType(\"rpc\");\n return QList<QXmppDiscoveryIq::Identity>() << identity;\n}\n\nbool QXmppRpcManager::handleStanza(const QDomElement &element)\n{\n \/\/ XEP-0009: Jabber-RPC\n if (QXmppRpcInvokeIq::isRpcInvokeIq(element))\n {\n QXmppRpcInvokeIq rpcIqPacket;\n rpcIqPacket.parse(element);\n invokeInterfaceMethod(rpcIqPacket);\n return true;\n }\n else if(QXmppRpcResponseIq::isRpcResponseIq(element))\n {\n QXmppRpcResponseIq rpcResponseIq;\n rpcResponseIq.parse(element);\n emit rpcCallResponse(rpcResponseIq);\n return true;\n }\n else if(QXmppRpcErrorIq::isRpcErrorIq(element))\n {\n QXmppRpcErrorIq rpcErrorIq;\n rpcErrorIq.parse(element);\n emit rpcCallError(rpcErrorIq);\n return true;\n }\n return false;\n}\n\n<commit_msg>add a warning about QXmppRpcManager::callRemoteMethod() in code documentation<commit_after>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Jeremy Lainé\n *\n * Source:\n * http:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"QXmppClient.h\"\n#include \"QXmppConstants.h\"\n#include \"QXmppInvokable.h\"\n#include \"QXmppRemoteMethod.h\"\n#include \"QXmppRpcIq.h\"\n#include \"QXmppRpcManager.h\"\n\n\/\/\/ Constructs a QXmppRpcManager.\n\nQXmppRpcManager::QXmppRpcManager()\n{\n}\n\n\/\/\/ Adds a local interface which can be queried using RPC.\n\/\/\/\n\/\/\/ \\param interface\n\nvoid QXmppRpcManager::addInvokableInterface( QXmppInvokable *interface )\n{\n m_interfaces[ interface->metaObject()->className() ] = interface;\n}\n\n\/\/\/ Invokes a remote interface using RPC.\n\/\/\/\n\/\/\/ \\param iq\n\nvoid QXmppRpcManager::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq )\n{\n QXmppStanza::Error error;\n \n const QStringList methodBits = iq.method().split('.');\n if (methodBits.size() != 2)\n return;\n const QString interface = methodBits.first();\n const QString method = methodBits.last();\n QXmppInvokable *iface = m_interfaces.value(interface);\n if (iface)\n {\n if ( iface->isAuthorized( iq.from() ) )\n {\n\n if ( iface->interfaces().contains(method) )\n {\n QVariant result = iface->dispatch(method.toLatin1(),\n iq.arguments() );\n QXmppRpcResponseIq resultIq;\n resultIq.setId(iq.id());\n resultIq.setTo(iq.from());\n resultIq.setValues(QVariantList() << result);\n client()->sendPacket( resultIq );\n return;\n }\n else\n {\n error.setType(QXmppStanza::Error::Cancel);\n error.setCondition(QXmppStanza::Error::ItemNotFound);\n }\n }\n else\n {\n error.setType(QXmppStanza::Error::Auth);\n error.setCondition(QXmppStanza::Error::Forbidden);\n }\n }\n else\n {\n error.setType(QXmppStanza::Error::Cancel);\n error.setCondition(QXmppStanza::Error::ItemNotFound);\n }\n QXmppRpcErrorIq errorIq;\n errorIq.setId(iq.id());\n errorIq.setTo(iq.from());\n errorIq.setQuery(iq);\n errorIq.setError(error);\n client()->sendPacket(errorIq);\n}\n\n\/\/\/ Calls a remote method using RPC with the specified arguments.\n\/\/\/\n\/\/\/ \\note This method blocks until the response is received, and it may\n\/\/\/ cause XMPP stanzas to be lost!\n\nQXmppRemoteMethodResult QXmppRpcManager::callRemoteMethod( const QString &jid,\n const QString &interface,\n const QVariant &arg1,\n const QVariant &arg2,\n const QVariant &arg3,\n const QVariant &arg4,\n const QVariant &arg5,\n const QVariant &arg6,\n const QVariant &arg7,\n const QVariant &arg8,\n const QVariant &arg9,\n const QVariant &arg10 )\n{\n QVariantList args;\n if( arg1.isValid() ) args << arg1;\n if( arg2.isValid() ) args << arg2;\n if( arg3.isValid() ) args << arg3;\n if( arg4.isValid() ) args << arg4;\n if( arg5.isValid() ) args << arg5;\n if( arg6.isValid() ) args << arg6;\n if( arg7.isValid() ) args << arg7;\n if( arg8.isValid() ) args << arg8;\n if( arg9.isValid() ) args << arg9;\n if( arg10.isValid() ) args << arg10;\n\n QXmppRemoteMethod method( jid, interface, args, client() );\n connect(this, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)),\n &method, SLOT(gotResult(QXmppRpcResponseIq)));\n connect(this, SIGNAL(rpcCallError(QXmppRpcErrorIq)),\n &method, SLOT(gotError(QXmppRpcErrorIq)));\n\n return method.call();\n}\n\nQStringList QXmppRpcManager::discoveryFeatures() const\n{\n \/\/ XEP-0009: Jabber-RPC\n return QStringList() << ns_rpc;\n}\n\nQList<QXmppDiscoveryIq::Identity> QXmppRpcManager::discoveryIdentities() const\n{\n QXmppDiscoveryIq::Identity identity;\n identity.setCategory(\"automation\");\n identity.setType(\"rpc\");\n return QList<QXmppDiscoveryIq::Identity>() << identity;\n}\n\nbool QXmppRpcManager::handleStanza(const QDomElement &element)\n{\n \/\/ XEP-0009: Jabber-RPC\n if (QXmppRpcInvokeIq::isRpcInvokeIq(element))\n {\n QXmppRpcInvokeIq rpcIqPacket;\n rpcIqPacket.parse(element);\n invokeInterfaceMethod(rpcIqPacket);\n return true;\n }\n else if(QXmppRpcResponseIq::isRpcResponseIq(element))\n {\n QXmppRpcResponseIq rpcResponseIq;\n rpcResponseIq.parse(element);\n emit rpcCallResponse(rpcResponseIq);\n return true;\n }\n else if(QXmppRpcErrorIq::isRpcErrorIq(element))\n {\n QXmppRpcErrorIq rpcErrorIq;\n rpcErrorIq.parse(element);\n emit rpcCallError(rpcErrorIq);\n return true;\n }\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>drop unneeded include<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef PBLOG_SERVER_BROKER_HPP_\n#define PBLOG_SERVER_BROKER_HPP_\n\n#include <pblog\/pblog.h>\n#include <pblog\/server.hpp>\n#include <pblog\/store.hpp>\n\n#include <vector>\n#include <zmq.hpp>\n\nnamespace pblog {\nnamespace server {\n\nusing ::pblog::Store;\nusing ::std::string;\nusing ::std::vector;\nusing ::zmq::context_t;\nusing ::zmq::socket_t;\n\ntypedef struct broker_config {\n broker_config();\n string store_path;\n vector<string> listen_endpoints;\n} broker_config;\n\n\/\/ the broker is a ZMQ device that provides the core message routing component\n\/\/ of pblogd. it binds to a number of sockets and coordinates all the workers\n\/\/ in the system\nclass PBLOG_EXPORT Broker {\n public:\n Broker(const string config_file_path);\n Broker(Store *store);\n Broker(Store *store, context_t *ctx);\n\n ~Broker();\n\n void run();\n\n protected:\n context_t * zctx;\n socket_t * workers_sock;\n socket_t * clients_external_sock;\n vector<socket_t *> listen_sockets;\n vector<socket_t *> listen_proxy_sockets;\n vector<void *> worker_threads;\n Store * store;\n bool active;\n request_processor_start_data *worker_start_data;\n broker_config config;\n\n static bool ParseConfig(const string path, broker_config &config, string &error);\n\n void init();\n void create_worker_threads();\n void setup_internal_sockets();\n void setup_listener_sockets();\n\n\n};\n\n}} \/\/ namespaces\n\n#endif<commit_msg>stub code for store watcher<commit_after>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef PBLOG_SERVER_BROKER_HPP_\n#define PBLOG_SERVER_BROKER_HPP_\n\n#include <pblog\/pblog.h>\n#include <pblog\/server.hpp>\n#include <pblog\/store.hpp>\n#include <pblog\/store_watcher.hpp>\n\n#include <vector>\n#include <zmq.hpp>\n\nnamespace pblog {\nnamespace server {\n\nusing ::pblog::Store;\nusing ::std::string;\nusing ::std::vector;\nusing ::zmq::context_t;\nusing ::zmq::socket_t;\n\ntypedef struct broker_config {\n broker_config();\n string store_path;\n vector<string> listen_endpoints;\n} broker_config;\n\ntypedef struct store_watcher_start_data {\n context_t *zctx;\n Store *store;\n char *endpoint;\n} store_watcher_start_data;\n\n\/\/ the broker is a ZMQ device that provides the core message routing component\n\/\/ of pblogd. it binds to a number of sockets and coordinates all the workers\n\/\/ in the system\nclass PBLOG_EXPORT Broker {\n public:\n Broker(const string config_file_path);\n Broker(Store *store);\n Broker(Store *store, context_t *ctx);\n\n ~Broker();\n\n void run();\n\n protected:\n context_t * zctx;\n socket_t * workers_sock;\n socket_t * clients_external_sock;\n vector<socket_t *> listen_sockets;\n vector<socket_t *> listen_proxy_sockets;\n vector<void *> worker_threads;\n Store * store;\n bool active;\n request_processor_start_data * worker_start_data;\n broker_config config;\n void * store_watcher_thread;\n store_watcher_start_data * store_watcher_start;\n\n static bool ParseConfig(const string path, broker_config &config, string &error);\n static void * __stdcall StoreWatcherStart(void *data);\n\n void init();\n void create_worker_threads();\n void create_store_watcher();\n void setup_internal_sockets();\n void setup_listener_sockets();\n\n\n};\n\n}} \/\/ namespaces\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/debugging level 0 = nothing\n\/\/debugging level 1 = critical errors\n\/\/debugging level 2 = errors\n\/\/debugging level 3 = status information\n\/\/debugging level 4 = extremely verbose status information\n#define DEBUG 3\n\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/epoll.h>\n#include <getopt.h>\n\nenum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};\n\n#define DEFAULT_PORT 80\n#include \"..\/util\/server_setup.cpp\"\n#include \"..\/util\/http_parser.cpp\"\n\nint mainHandler(int CONN_fd){\n int handler = HANDLER_PROGRESSIVE;\n bool ready4data = false;\/\/set to true when streaming starts\n bool inited = false;\n bool progressive_has_sent_header = false;\n int ss;\n std::string streamname;\n FLV_Pack * tag = 0;\n HTTPReader HTTP_R, HTTP_S;\/\/HTTP Receiver en HTTP Sender.\n\n int retval;\n int poller = epoll_create(1);\n int sspoller = epoll_create(1);\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = CONN_fd;\n epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);\n struct epoll_event events[1];\n\n std::string Movie = \"\";\n std::string Quality = \"\";\n int Segment = -1;\n int Fragment = -1;\n int temp;\n\n while (!socketError && !All_Hell_Broke_Loose){\n \/\/only parse input if available or not yet init'ed\n retval = epoll_wait(poller, events, 1, 1);\n if ((retval > 0) || !ready4data){\n if (HTTP_R.ReadSocket(CONN_fd)){\n if( (HTTP_R.url.find(\"Seg\") != std::string::npos) &&\n (HTTP_R.url.find(\"Frag\") != std::string::npos) ) {\n handler = HANDLER_FLASH;\n }\n if(handler == HANDLER_FLASH) {\n Movie = HTTP_R.url.substr(1);\n Movie = Movie.substr(0,Movie.find(\"\/\"));\n Quality = HTTP_R.url.substr( HTTP_R.url.find(\"\/\",1)+1 );\n Quality = Quality.substr(0, Quality.find(\"Seg\"));\n temp = HTTP_R.url.find(\"Seg\") + 3;\n Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find(\"-\",temp)-temp).c_str());\n temp = HTTP_R.url.find(\"Frag\") + 4;\n Fragment = atoi( HTTP_R.url.substr(temp).c_str() );\n\n printf( \"URL: %s\\n\", HTTP_R.url.c_str());\n printf( \"Movie Identifier: %s\\n\", Movie.c_str() );\n printf( \"Quality Modifier: %s\\n\", Quality.c_str() );\n printf( \"Segment: %d\\n\", Segment );\n printf( \"Fragment: %d\\n\", Fragment );\n streamname = \"\/tmp\/shared_socket_\";\n streamname += Movie.c_str();\n\n ready4data = true;\n }\/\/FLASH handler\n \/\/ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar\n \/\/ERIK: bijvoorbeeld HTTP_R.GetHeader(\"headernaam\") (voor headers) of HTTP_R.GetVar(\"varnaam\") (voor GET\/POST vars)\n \/\/ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....\n \/\/ERIK: zie ook ..\/util\/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je\n\n \/\/ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.\n \/\/ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.\n \/\/ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.\n if (handler == HANDLER_PROGRESSIVE){\n \/\/in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter\n streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);\/\/strip de .flv\n for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){\n if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}\/\/strip nonalphanumeric\n }\n streamname = \"\/tmp\/shared_socket_\" + streamname;\/\/dit is dan onze shared_socket\n \/\/normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos\n ready4data = true;\n }\/\/PROGRESSIVE handler\n HTTP_R.Clean(); \/\/maak schoon na verwerken voor eventuele volgende requests...\n }\n }\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n ss = DDV_OpenUnix(streamname);\n if (ss <= 0){\n #if DEBUG >= 1\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n socketError = 1;\n break;\n }\n ev.events = EPOLLIN;\n ev.data.fd = ss;\n epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);\n #if DEBUG >= 3\n fprintf(stderr, \"Everything connected, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n \n retval = epoll_wait(sspoller, events, 1, 1);\n switch (DDV_ready(ss)){\n case 0:\n socketError = true;\n #if DEBUG >= 1\n fprintf(stderr, \"Source socket is disconnected.\\n\");\n #endif\n break;\n case -1: break;\/\/not ready yet\n default:\n if (FLV_GetPacket(tag, ss)){\/\/able to read a full packet?\n \/\/ERIK: \"tag\" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.\n \/\/ERIK: Dit is het punt waarop je eventueel data mag\/kan gaan sturen en\/of parsen. Leef je uit.\n \/\/ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)\n \/\/ERIK: en dan met de .BuildResponse(\"200\", \"OK\"); call een std::string met de hele response maken, klaar voor versturen\n \/\/ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!\n if (handler == HANDLER_PROGRESSIVE){\n if (!progressive_has_sent_header){\n HTTP_S.Clean();\/\/troep opruimen die misschien aanwezig is...\n HTTP_S.SetHeader(\"Content-Type\", \"video\/x-flv\");\/\/FLV files hebben altijd dit content-type.\n std::string tmpresp = HTTP_S.BuildResponse(\"200\", \"OK\");\/\/geen SetBody = unknown length! Dat willen we hier.\n DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);\/\/schrijf de HTTP response header\n DDV_write(FLVHeader, 13, CONN_fd);\/\/schrijf de FLV header, altijd 13 chars lang\n progressive_has_sent_header = true;\n }\n DDV_write(tag->data, tag->len, CONN_fd);\/\/schrijf deze FLV tag onbewerkt weg\n }\/\/PROGRESSIVE handler\n }\n break;\n }\n }\n }\n close(CONN_fd);\n if (inited) close(ss);\n #if DEBUG >= 1\n if (All_Hell_Broke_Loose){fprintf(stderr, \"All Hell Broke Loose\\n\");}\n fprintf(stderr, \"User %i disconnected.\\n\", CONN_fd);\n if (inited){\n fprintf(stderr, \"Status was: inited\\n\");\n }else{\n if (ready4data){\n fprintf(stderr, \"Status was: ready4data\\n\");\n }else{\n fprintf(stderr, \"Status was: connected\\n\");\n }\n }\n #endif\n return 0;\n}\n\n<commit_msg>adjustments to HTTP connector<commit_after>\/\/debugging level 0 = nothing\n\/\/debugging level 1 = critical errors\n\/\/debugging level 2 = errors\n\/\/debugging level 3 = status information\n\/\/debugging level 4 = extremely verbose status information\n#define DEBUG 3\n\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/epoll.h>\n#include <getopt.h>\n\nenum {HANDLER_PROGRESSIVE, HANDLER_FLASH, HANDLER_APPLE, HANDLER_MICRO};\n\n#define DEFAULT_PORT 80\n#include \"..\/util\/server_setup.cpp\"\n#include \"..\/util\/http_parser.cpp\"\n\nint mainHandler(int CONN_fd){\n int handler = HANDLER_PROGRESSIVE;\n bool ready4data = false;\/\/set to true when streaming starts\n bool inited = false;\n bool progressive_has_sent_header = false;\n int ss;\n std::string streamname;\n FLV_Pack * tag = 0;\n HTTPReader HTTP_R, HTTP_S;\/\/HTTP Receiver en HTTP Sender.\n\n int retval;\n int poller = epoll_create(1);\n int sspoller = epoll_create(1);\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = CONN_fd;\n epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);\n struct epoll_event events[1];\n\n std::string Movie = \"\";\n std::string Quality = \"\";\n int Segment = -1;\n int Fragment = -1;\n int temp;\n\n while (!socketError && !All_Hell_Broke_Loose){\n \/\/only parse input if available or not yet init'ed\n retval = epoll_wait(poller, events, 1, 1);\n if ((retval > 0) || !ready4data){\n if (HTTP_R.ReadSocket(CONN_fd)){\n if( (HTTP_R.url.find(\"Seg\") != std::string::npos) &&\n (HTTP_R.url.find(\"Frag\") != std::string::npos) ) {\n handler = HANDLER_FLASH;\n }\n printf( \"Handler: %d\\n\", handler );\n if(handler == HANDLER_FLASH) {\n Movie = HTTP_R.url.substr(1);\n Movie = Movie.substr(0,Movie.find(\"\/\"));\n Quality = HTTP_R.url.substr( HTTP_R.url.find(\"\/\",1)+1 );\n Quality = Quality.substr(0, Quality.find(\"Seg\"));\n temp = HTTP_R.url.find(\"Seg\") + 3;\n Segment = atoi( HTTP_R.url.substr(temp,HTTP_R.url.find(\"-\",temp)-temp).c_str());\n temp = HTTP_R.url.find(\"Frag\") + 4;\n Fragment = atoi( HTTP_R.url.substr(temp).c_str() );\n\n printf( \"URL: %s\\n\", HTTP_R.url.c_str());\n printf( \"Movie Identifier: %s\\n\", Movie.c_str() );\n printf( \"Quality Modifier: %s\\n\", Quality.c_str() );\n printf( \"Segment: %d\\n\", Segment );\n printf( \"Fragment: %d\\n\", Fragment );\n streamname = \"\/tmp\/shared_socket_\";\n streamname += Movie.c_str();\n\n ready4data = true;\n }\/\/FLASH handler\n \/\/ERIK: we hebben nu een hele HTTP request geparsed - verwerken mag hier, door aanroepen naar\n \/\/ERIK: bijvoorbeeld HTTP_R.GetHeader(\"headernaam\") (voor headers) of HTTP_R.GetVar(\"varnaam\") (voor GET\/POST vars)\n \/\/ERIK: of HTTP_R.method of HTTP_R.url of HTTP_R.protocol....\n \/\/ERIK: zie ook ..\/util\/http_parser.cpp - de class definitie bovenaan zou genoeg moeten zijn voor je\n\n \/\/ERIK: Ik heb een handler variabele gemaakt die moet setten naar bijv HANDLER_FLASH in jouw geval.\n \/\/ERIK: Als de handler niet is geset, is hij by default PROGRESSIVE, en daarvoor heb ik de verwerking al gecode.\n \/\/ERIK: Je eigen handler instellen voorkomt dus dat mijn code hem handled alsof hij progressive is.\n if (handler == HANDLER_PROGRESSIVE){\n \/\/in het geval progressive nemen we aan dat de URL de streamname is, met .flv erachter\n streamname = HTTP_R.url.substr(0, HTTP_R.url.size()-4);\/\/strip de .flv\n for (std::string::iterator i=streamname.end()-1; i>=streamname.begin(); --i){\n if (!isalpha(*i) && !isdigit(*i)){streamname.erase(i);}else{*i=tolower(*i);}\/\/strip nonalphanumeric\n }\n streamname = \"\/tmp\/shared_socket_\" + streamname;\/\/dit is dan onze shared_socket\n \/\/normaal zouden we ook een position uitlezen uit de URL, maar bij LIVE streams is dat zinloos\n printf( \"Streamname: %s\\n\", streamname.c_str() );\n ready4data = true;\n }\/\/PROGRESSIVE handler\n HTTP_R.Clean(); \/\/maak schoon na verwerken voor eventuele volgende requests...\n }\n }\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n ss = DDV_OpenUnix(streamname);\n if (ss <= 0){\n #if DEBUG >= 1\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n socketError = 1;\n break;\n }\n ev.events = EPOLLIN;\n ev.data.fd = ss;\n epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);\n #if DEBUG >= 3\n fprintf(stderr, \"Everything connected, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n \n retval = epoll_wait(sspoller, events, 1, 1);\n switch (DDV_ready(ss)){\n case 0:\n socketError = true;\n #if DEBUG >= 1\n fprintf(stderr, \"Source socket is disconnected.\\n\");\n #endif\n break;\n case -1: break;\/\/not ready yet\n default:\n if (FLV_GetPacket(tag, ss)){\/\/able to read a full packet?\n \/\/ERIK: \"tag\" bevat nu een FLV tag (video, audio, of metadata), de header hebben we al weggelezen, np.\n \/\/ERIK: Dit is het punt waarop je eventueel data mag\/kan gaan sturen en\/of parsen. Leef je uit.\n \/\/ERIK: je kan een HTTP_S gebruiken om je HTTP request op te bouwen (via SetBody, SetHeader, etc)\n \/\/ERIK: en dan met de .BuildResponse(\"200\", \"OK\"); call een std::string met de hele response maken, klaar voor versturen\n \/\/ERIK: Note: hergebruik echter NIET de HTTP_R die ik al heb gemaakt hierboven, want er kunnen meerdere requests binnenkomen!\n if (handler == HANDLER_PROGRESSIVE){\n if (!progressive_has_sent_header){\n HTTP_S.Clean();\/\/troep opruimen die misschien aanwezig is...\n HTTP_S.SetHeader(\"Content-Type\", \"video\/x-flv\");\/\/FLV files hebben altijd dit content-type.\n std::string tmpresp = HTTP_S.BuildResponse(\"200\", \"OK\");\/\/geen SetBody = unknown length! Dat willen we hier.\n DDV_write(tmpresp.c_str(), tmpresp.size(), CONN_fd);\/\/schrijf de HTTP response header\n DDV_write(FLVHeader, 13, CONN_fd);\/\/schrijf de FLV header, altijd 13 chars lang\n progressive_has_sent_header = true;\n }\n DDV_write(tag->data, tag->len, CONN_fd);\/\/schrijf deze FLV tag onbewerkt weg\n }\/\/PROGRESSIVE handler\n }\n break;\n }\n }\n }\n close(CONN_fd);\n if (inited) close(ss);\n #if DEBUG >= 1\n if (All_Hell_Broke_Loose){fprintf(stderr, \"All Hell Broke Loose\\n\");}\n fprintf(stderr, \"User %i disconnected.\\n\", CONN_fd);\n if (inited){\n fprintf(stderr, \"Status was: inited\\n\");\n }else{\n if (ready4data){\n fprintf(stderr, \"Status was: ready4data\\n\");\n }else{\n fprintf(stderr, \"Status was: connected\\n\");\n }\n }\n #endif\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"core\/block.h\"\n#include \"core\/transaction.h\"\n#include \"main.h\"\n#include \"rpcserver.h\"\n#include \"streams.h\"\n#include \"sync.h\"\n#include \"utilstrencodings.h\"\n#include \"version.h\"\n\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace json_spirit;\n\nenum RetFormat {\n RF_BINARY,\n RF_HEX,\n RF_JSON,\n};\n\nstatic const struct {\n enum RetFormat rf;\n const char *name;\n} rf_names[] = {\n { RF_BINARY, \"binary\" }, \/\/ default, if match not found\n { RF_HEX, \"hex\" },\n { RF_JSON, \"json\" },\n};\n\nclass RestErr {\npublic:\n enum HTTPStatusCode status;\n string message;\n};\n\nextern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);\nextern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex);\n\nstatic RestErr RESTERR(enum HTTPStatusCode status, string message)\n{\n RestErr re;\n re.status = status;\n re.message = message;\n return re;\n}\n\nstatic enum RetFormat ParseDataFormat(const string& format)\n{\n for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)\n if (format == rf_names[i].name)\n return rf_names[i].rf;\n\n return rf_names[0].rf;\n}\n\nstatic bool ParseHashStr(const string& strReq, uint256& v)\n{\n if (!IsHex(strReq) || (strReq.size() != 64))\n return false;\n\n v.SetHex(strReq);\n return true;\n}\n\nstatic bool rest_block(AcceptedConnection *conn,\n string& strReq,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n vector<string> params;\n boost::split(params, strReq, boost::is_any_of(\"\/\"));\n\n enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string(\"\"));\n\n string hashStr = params[0];\n uint256 hash;\n if (!ParseHashStr(hashStr, hash))\n throw RESTERR(HTTP_BAD_REQUEST, \"Invalid hash: \" + hashStr);\n\n CBlock block;\n CBlockIndex* pblockindex = NULL;\n {\n LOCK(cs_main);\n if (mapBlockIndex.count(hash) == 0)\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n\n pblockindex = mapBlockIndex[hash];\n if (!ReadBlockFromDisk(block, pblockindex))\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n }\n\n CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);\n ssBlock << block;\n\n switch (rf) {\n case RF_BINARY: {\n string binaryBlock = ssBlock.str();\n conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), \"application\/octet-stream\") << binaryBlock << std::flush;\n return true;\n }\n\n case RF_HEX: {\n string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + \"\\n\";;\n conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, \"text\/plain\") << std::flush;\n return true;\n }\n\n case RF_JSON: {\n Object objBlock = blockToJSON(block, pblockindex);\n string strJSON = write_string(Value(objBlock), false) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;\n return true;\n }\n }\n\n \/\/ not reached\n return true; \/\/ continue to process further HTTP reqs on this cxn\n}\n\nstatic bool rest_tx(AcceptedConnection *conn,\n string& strReq,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n vector<string> params;\n boost::split(params, strReq, boost::is_any_of(\"\/\"));\n\n enum RetFormat rf = ParseDataFormat(params.size() > 1 ? params[1] : string(\"\"));\n\n string hashStr = params[0];\n uint256 hash;\n if (!ParseHashStr(hashStr, hash))\n throw RESTERR(HTTP_BAD_REQUEST, \"Invalid hash: \" + hashStr);\n\n CTransaction tx;\n uint256 hashBlock = 0;\n if (!GetTransaction(hash, tx, hashBlock, true))\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n\n CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n ssTx << tx;\n\n switch (rf) {\n case RF_BINARY: {\n string binaryTx = ssTx.str();\n conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), \"application\/octet-stream\") << binaryTx << std::flush;\n return true;\n }\n\n case RF_HEX: {\n string strHex = HexStr(ssTx.begin(), ssTx.end()) + \"\\n\";;\n conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, \"text\/plain\") << std::flush;\n return true;\n }\n\n case RF_JSON: {\n Object objTx;\n TxToJSON(tx, hashBlock, objTx);\n string strJSON = write_string(Value(objTx), false) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;\n return true;\n }\n }\n\n \/\/ not reached\n return true; \/\/ continue to process further HTTP reqs on this cxn\n}\n\nstatic const struct {\n const char *prefix;\n bool (*handler)(AcceptedConnection *conn,\n string& strURI,\n map<string, string>& mapHeaders,\n bool fRun);\n} uri_prefixes[] = {\n { \"\/rest\/tx\/\", rest_tx },\n { \"\/rest\/block\/\", rest_block },\n};\n\nbool HTTPReq_REST(AcceptedConnection *conn,\n string& strURI,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n try {\n std::string statusmessage;\n if(RPCIsInWarmup(&statusmessage))\n throw RESTERR(HTTP_SERVICE_UNAVAILABLE, \"Service temporarily unavailable: \"+statusmessage);\n \n for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) {\n unsigned int plen = strlen(uri_prefixes[i].prefix);\n if (strURI.substr(0, plen) == uri_prefixes[i].prefix) {\n string strReq = strURI.substr(plen);\n return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun);\n }\n }\n }\n catch (RestErr& re) {\n conn->stream() << HTTPReply(re.status, re.message + \"\\r\\n\", false, false, \"text\/plain\") << std::flush;\n return false;\n }\n\n conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;\n return false;\n}\n<commit_msg>[REST] make selection of output-format mandatory, support dot url syntax<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"core\/block.h\"\n#include \"core\/transaction.h\"\n#include \"main.h\"\n#include \"rpcserver.h\"\n#include \"streams.h\"\n#include \"sync.h\"\n#include \"utilstrencodings.h\"\n#include \"version.h\"\n\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace json_spirit;\n\nenum RetFormat {\n RF_UNDEF,\n RF_BINARY,\n RF_HEX,\n RF_JSON,\n};\n\nstatic const struct {\n enum RetFormat rf;\n const char* name;\n} rf_names[] = {\n {RF_UNDEF, \"\"},\n {RF_BINARY, \"bin\"},\n {RF_HEX, \"hex\"},\n {RF_JSON, \"json\"},\n};\n\nclass RestErr\n{\npublic:\n enum HTTPStatusCode status;\n string message;\n};\n\nextern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);\nextern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex);\n\nstatic RestErr RESTERR(enum HTTPStatusCode status, string message)\n{\n RestErr re;\n re.status = status;\n re.message = message;\n return re;\n}\n\nstatic enum RetFormat ParseDataFormat(vector<string>& params, const string strReq)\n{\n boost::split(params, strReq, boost::is_any_of(\".\"));\n if (params.size() > 1) {\n for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)\n if (params[1] == rf_names[i].name)\n return rf_names[i].rf;\n }\n\n return rf_names[0].rf;\n}\n\nstatic string AvailableDataFormatsString()\n{\n string formats = \"\";\n for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)\n if (strlen(rf_names[i].name) > 0) {\n formats.append(\".\");\n formats.append(rf_names[i].name);\n formats.append(\", \");\n }\n\n if (formats.length() > 0)\n return formats.substr(0, formats.length() - 2);\n\n return formats;\n}\n\nstatic bool ParseHashStr(const string& strReq, uint256& v)\n{\n if (!IsHex(strReq) || (strReq.size() != 64))\n return false;\n\n v.SetHex(strReq);\n return true;\n}\n\nstatic bool rest_block(AcceptedConnection* conn,\n string& strReq,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n vector<string> params;\n enum RetFormat rf = ParseDataFormat(params, strReq);\n\n string hashStr = params[0];\n uint256 hash;\n if (!ParseHashStr(hashStr, hash))\n throw RESTERR(HTTP_BAD_REQUEST, \"Invalid hash: \" + hashStr);\n\n CBlock block;\n CBlockIndex* pblockindex = NULL;\n {\n LOCK(cs_main);\n if (mapBlockIndex.count(hash) == 0)\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n\n pblockindex = mapBlockIndex[hash];\n if (!ReadBlockFromDisk(block, pblockindex))\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n }\n\n CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);\n ssBlock << block;\n\n switch (rf) {\n case RF_BINARY: {\n string binaryBlock = ssBlock.str();\n conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), \"application\/octet-stream\") << binaryBlock << std::flush;\n return true;\n }\n\n case RF_HEX: {\n string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, \"text\/plain\") << std::flush;\n return true;\n }\n\n case RF_JSON: {\n Object objBlock = blockToJSON(block, pblockindex);\n string strJSON = write_string(Value(objBlock), false) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;\n return true;\n }\n\n default: {\n throw RESTERR(HTTP_NOT_FOUND, \"output format not found (available: \" + AvailableDataFormatsString() + \")\");\n }\n }\n\n \/\/ not reached\n return true; \/\/ continue to process further HTTP reqs on this cxn\n}\n\nstatic bool rest_tx(AcceptedConnection* conn,\n string& strReq,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n vector<string> params;\n enum RetFormat rf = ParseDataFormat(params, strReq);\n\n string hashStr = params[0];\n uint256 hash;\n if (!ParseHashStr(hashStr, hash))\n throw RESTERR(HTTP_BAD_REQUEST, \"Invalid hash: \" + hashStr);\n\n CTransaction tx;\n uint256 hashBlock = 0;\n if (!GetTransaction(hash, tx, hashBlock, true))\n throw RESTERR(HTTP_NOT_FOUND, hashStr + \" not found\");\n\n CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n ssTx << tx;\n\n switch (rf) {\n case RF_BINARY: {\n string binaryTx = ssTx.str();\n conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), \"application\/octet-stream\") << binaryTx << std::flush;\n return true;\n }\n\n case RF_HEX: {\n string strHex = HexStr(ssTx.begin(), ssTx.end()) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, \"text\/plain\") << std::flush;\n return true;\n }\n\n case RF_JSON: {\n Object objTx;\n TxToJSON(tx, hashBlock, objTx);\n string strJSON = write_string(Value(objTx), false) + \"\\n\";\n conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;\n return true;\n }\n\n default: {\n throw RESTERR(HTTP_NOT_FOUND, \"output format not found (available: \" + AvailableDataFormatsString() + \")\");\n }\n }\n\n \/\/ not reached\n return true; \/\/ continue to process further HTTP reqs on this cxn\n}\n\nstatic const struct {\n const char* prefix;\n bool (*handler)(AcceptedConnection* conn,\n string& strURI,\n map<string, string>& mapHeaders,\n bool fRun);\n} uri_prefixes[] = {\n {\"\/rest\/tx\/\", rest_tx},\n {\"\/rest\/block\/\", rest_block},\n};\n\nbool HTTPReq_REST(AcceptedConnection* conn,\n string& strURI,\n map<string, string>& mapHeaders,\n bool fRun)\n{\n try {\n std::string statusmessage;\n if (RPCIsInWarmup(&statusmessage))\n throw RESTERR(HTTP_SERVICE_UNAVAILABLE, \"Service temporarily unavailable: \" + statusmessage);\n\n for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) {\n unsigned int plen = strlen(uri_prefixes[i].prefix);\n if (strURI.substr(0, plen) == uri_prefixes[i].prefix) {\n string strReq = strURI.substr(plen);\n return uri_prefixes[i].handler(conn, strReq, mapHeaders, fRun);\n }\n }\n } catch (RestErr& re) {\n conn->stream() << HTTPReply(re.status, re.message + \"\\r\\n\", false, false, \"text\/plain\") << std::flush;\n return false;\n }\n\n conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Sh: A GPU metaprogramming language.\n\/\/\n\/\/ Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory\n\/\/ Project administrator: Michael D. McCool\n\/\/ Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,\n\/\/ Michael D. McCool\n\/\/ \n\/\/ This software is provided 'as-is', without any express or implied\n\/\/ warranty. In no event will the authors be held liable for any damages\n\/\/ arising from the use of this software.\n\/\/ \n\/\/ Permission is granted to anyone to use this software for any purpose,\n\/\/ including commercial applications, and to alter it and redistribute it\n\/\/ freely, subject to the following restrictions:\n\/\/ \n\/\/ 1. The origin of this software must not be misrepresented; you must\n\/\/ not claim that you wrote the original software. If you use this\n\/\/ software in a product, an acknowledgment in the product documentation\n\/\/ would be appreciated but is not required.\n\/\/ \n\/\/ 2. Altered source versions must be plainly marked as such, and must\n\/\/ not be misrepresented as being the original software.\n\/\/ \n\/\/ 3. This notice may not be removed or altered from any source\n\/\/ distribution.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <sh\/sh.hpp>\n#include <sh\/shutil.hpp>\n#include <iostream>\n#include \"Shader.hpp\"\n#include \"Globals.hpp\"\n\nusing namespace SH;\nusing namespace ShUtil;\n\n#include \"util.hpp\"\n\nclass LuciteShader : public Shader {\npublic:\n ShProgram vsh, fsh;\n\n LuciteShader();\n ~LuciteShader();\n\n bool init();\n\n ShProgram vertex() { return vsh;}\n ShProgram fragment() { return fsh;}\n};\n\nLuciteShader::LuciteShader()\n : Shader(\"Refraction: Lucite\")\n{\n}\n\nLuciteShader::~LuciteShader()\n{\n}\n\nbool LuciteShader::init()\n{\n std::cerr << \"Initializing \" << name() << std::endl;\n\n std::string imageNames[6] = {\"left\", \"right\", \"top\", \"bottom\", \"back\", \"front\"};\n ShImage test_image;\n test_image.loadPng(std::string(SHMEDIA_DIR \"\/envmaps\/aniroom\/\") + imageNames[0] + \".png\");\n\n ShTextureCube<ShColor4f> cubemap(test_image.width(), test_image.height());\n {\n for (int i = 0; i < 6; i++) {\n ShImage image;\n image.loadPng(std::string(SHMEDIA_DIR \"\/envmaps\/aniroom\/\") + imageNames[i] + \".png\");\n cubemap.memory(image.memory(), static_cast<ShCubeDirection>(i));\n }\n }\n\n ShAttrib3f theta = ShAttrib3f(1.32f,1.3f,1.28f);\n theta.name(\"relative indices of refraction\");\n theta.range(0.0f,2.0f);\n\n vsh = SH_BEGIN_PROGRAM(\"gpu:vertex\") {\n ShInputPosition4f ipos;\n ShInputNormal3f inorm;\n \n ShOutputPosition4f opos; \/\/ Position in NDC\n ShOutputNormal3f onorm; \/\/ view-space normal\n ShOutputVector3f reflv; \/\/ reflection vector\n ShOutputVector3f refrv[3]; \/\/ refraction vectors (per RGB channel)\n ShOutputAttrib3f fres; \/\/ fresnel terms (per RGB channel)\n\n opos = Globals::mvp | ipos; \/\/ Compute NDC position\n onorm = Globals::mv | inorm; \/\/ Compute view-space normal\n onorm = normalize(onorm);\n ShPoint3f posv = (Globals::mv | ipos)(0,1,2); \/\/ Compute view-space position\n ShPoint3f viewv = -normalize(posv); \/\/ Compute view vector\n\n reflv = reflect(viewv,onorm); \/\/ Compute reflection vector\n\n \/\/ actually do reflection lookup in model space\n reflv = Globals::mv_inverse | reflv;\n\n for (int i=0; i<3; i++) {\n \trefrv[i] = refract(viewv,onorm,theta[i]); \/\/ Compute refraction vectors\n\n \/\/ actually do refraction lookup in model space\n refrv[i] = Globals::mv_inverse | refrv[i];\n\n fres[i] = fresnel(viewv,onorm,theta[i]); \/\/ Compute fresnel term\n }\n } SH_END;\n \n fsh = SH_BEGIN_PROGRAM(\"gpu:fragment\") {\n ShInputPosition4f posh;\n ShInputNormal3f n; \/\/ normal\n ShInputVector3f reflv; \/\/ reflection vector\n ShInputVector3f refrv[3]; \/\/ refraction vectors (per RGB channel)\n ShInputAttrib3f fres; \/\/ fresnel terms (per RGB channel)\n\n ShOutputColor3f result;\n \n result = fres*cubemap(reflv)(0,1,2);\n for (int i=0; i<3; i++) {\n result[i] += (1.0f-fres[i])*cubemap(refrv[i])(i); \n }\n } SH_END;\n\n return true;\n}\n\n\nLuciteShader the_lucite_shader;\n<commit_msg>added more name and variable documentation (so can use this shader as an example in shrike when showing output code). uncovered a few bugs... get a crash if a program is named before it is initialized, title and desc are not documented in doxygen.<commit_after>\/\/ Sh: A GPU metaprogramming language.\n\/\/\n\/\/ Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory\n\/\/ Project administrator: Michael D. McCool\n\/\/ Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,\n\/\/ Michael D. McCool\n\/\/ \n\/\/ This software is provided 'as-is', without any express or implied\n\/\/ warranty. In no event will the authors be held liable for any damages\n\/\/ arising from the use of this software.\n\/\/ \n\/\/ Permission is granted to anyone to use this software for any purpose,\n\/\/ including commercial applications, and to alter it and redistribute it\n\/\/ freely, subject to the following restrictions:\n\/\/ \n\/\/ 1. The origin of this software must not be misrepresented; you must\n\/\/ not claim that you wrote the original software. If you use this\n\/\/ software in a product, an acknowledgment in the product documentation\n\/\/ would be appreciated but is not required.\n\/\/ \n\/\/ 2. Altered source versions must be plainly marked as such, and must\n\/\/ not be misrepresented as being the original software.\n\/\/ \n\/\/ 3. This notice may not be removed or altered from any source\n\/\/ distribution.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <sh\/sh.hpp>\n#include <sh\/shutil.hpp>\n#include <iostream>\n#include \"Shader.hpp\"\n#include \"Globals.hpp\"\n\nusing namespace SH;\nusing namespace ShUtil;\n\n#include \"util.hpp\"\n\nclass LuciteShader : public Shader {\npublic:\n ShProgram vsh, fsh;\n\n LuciteShader();\n ~LuciteShader();\n\n bool init();\n\n ShProgram vertex() { return vsh;}\n ShProgram fragment() { return fsh;}\n};\n\nLuciteShader::LuciteShader()\n : Shader(\"Refraction: Lucite\")\n{\n}\n\nLuciteShader::~LuciteShader()\n{\n}\n\nbool LuciteShader::init()\n{\n std::cerr << \"Initializing \" << name() << std::endl;\n\n std::string imageNames[6] = {\"left\", \"right\", \"top\", \"bottom\", \"back\", \"front\"};\n ShImage test_image;\n test_image.loadPng(std::string(SHMEDIA_DIR \"\/envmaps\/aniroom\/\") + imageNames[0] + \".png\");\n\n ShTextureCube<ShColor4f> SH_DECL(cubemap) =\n\t ShTextureCube<ShColor4f>(test_image.width(), test_image.height());\n {\n for (int i = 0; i < 6; i++) {\n ShImage image;\n image.loadPng(std::string(SHMEDIA_DIR \"\/envmaps\/aniroom\/\") + imageNames[i] + \".png\");\n cubemap.memory(image.memory(), static_cast<ShCubeDirection>(i));\n }\n }\n\n ShAttrib3f SH_DECL(eta) = ShAttrib3f(1.32f,1.3f,1.28f);\n eta.title(\"relative indices of refraction\");\n eta.description(\"relative indices of refraction for each color component to model dispersion\");\n eta.range(0.0f,2.0f);\n\n vsh = SH_BEGIN_PROGRAM(\"gpu:vertex\") {\n ShInputPosition4f SH_DECL(ipos);\n ShInputNormal3f SH_DECL(inorm);\n \n ShOutputPosition4f SH_DECL(opos); \/\/ Position in NDC\n ShOutputNormal3f SH_DECL(onorm); \/\/ view-space normal\n ShOutputVector3f SH_DECL(reflv); \/\/ reflection vector\n ShOutputVector3f refrv[3]; \/\/ refraction vectors (per RGB channel)\n refrv[0].name(\"refrv[0]\"); \/\/ should be nicer way to name these\n refrv[1].name(\"refrv[1]\");\n refrv[2].name(\"refrv[2]\");\n ShOutputAttrib3f SH_DECL(fres); \/\/ fresnel terms (per RGB channel)\n\n opos = Globals::mvp | ipos; \/\/ Compute NDC position\n onorm = Globals::mv | inorm; \/\/ Compute view-space normal\n onorm = normalize(onorm);\n ShPoint3f SH_DECL(posv) = (Globals::mv | ipos)(0,1,2); \/\/ Compute view-space position\n ShPoint3f SH_DECL(viewv) = -normalize(posv); \/\/ Compute view vector\n\n reflv = reflect(viewv,onorm); \/\/ Compute reflection vector\n\n \/\/ actually do reflection lookup in model space\n reflv = Globals::mv_inverse | reflv;\n\n for (int i=0; i<3; i++) {\n \trefrv[i] = refract(viewv,onorm,eta[i]); \/\/ Compute refraction vectors\n\n \/\/ actually do refraction lookup in model space\n refrv[i] = Globals::mv_inverse | refrv[i];\n\n fres[i] = fresnel(viewv,onorm,eta[i]); \/\/ Compute fresnel term\n }\n } SH_END;\n vsh.name(\"LuciteShader::vsh\");\n \n fsh = SH_BEGIN_PROGRAM(\"gpu:fragment\") {\n ShInputPosition4f SH_DECL(posh);\n ShInputNormal3f SH_DECL(n); \/\/ normal\n ShInputVector3f SH_DECL(reflv); \/\/ reflection vector\n ShInputVector3f refrv[3]; \/\/ refraction vectors (per RGB channel)\n refrv[0].name(\"refrv[0]\"); \/\/ should be nicer way to name these\n refrv[1].name(\"refrv[1]\");\n refrv[2].name(\"refrv[2]\");\n ShInputAttrib3f SH_DECL(fres); \/\/ fresnel terms (per RGB channel)\n\n ShOutputColor3f SH_DECL(result);\n \n result = fres*cubemap(reflv)(0,1,2);\n for (int i=0; i<3; i++) {\n result[i] += (1.0f-fres[i])*cubemap(refrv[i])(i); \n }\n } SH_END;\n fsh.name(\"LuciteShader::fsh\");\n\n return true;\n}\n\n\nLuciteShader the_lucite_shader;\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n#include \"CtrlrPanelViewport.h\"\r\n#include \"CtrlrPanel\/CtrlrPanel.h\"\r\n#include \"CtrlrPanelEditor.h\"\r\n#include \"CtrlrManager\/CtrlrManager.h\"\r\n\r\n\/**\r\n *\/\r\n\r\nCtrlrPanelViewport::CtrlrPanelViewport (CtrlrPanelEditor &_owner)\r\n\t: owner(_owner), isSpaceDown(false)\r\n{\r\n\tcurrentZoom = 1.0;\r\n\r\n\tcanvasList.add (new CtrlrPanelCanvas (owner));\r\n\r\n\tmagnifier = new CtrlrMagnifierComponent (canvasList[0]);\r\n\taddAndMakeVisible (viewport = new CtrlrViewportImpl(this));\r\n\tviewport->setViewedComponent (magnifier);\r\n\r\n setSize (512, 512);\r\n}\r\n\r\nCtrlrPanelViewport::~CtrlrPanelViewport()\r\n{\r\n\tcanvasList.clear (false);\r\n\tdeleteAndZero (viewport);\r\n}\r\n\r\n\r\nvoid CtrlrPanelViewport::paint (Graphics& g)\r\n{\r\n\tg.fillAll (Colours::transparentBlack);\r\n}\r\n\r\nvoid CtrlrPanelViewport::resized()\r\n{\r\n\tviewport->setBounds\t(0, 0, getWidth(), getHeight());\r\n}\r\n\r\nbool CtrlrPanelViewport::keyStateChanged (const bool isKeyDown)\r\n{\r\n\tif (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))\r\n\t{\r\n\t\tdragKeyHeldDown (true);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdragKeyHeldDown (false);\r\n\t}\r\n return false;\r\n}\r\n\r\nvoid CtrlrPanelViewport::setZoom (const double zoom, int anchorX, int anchorY)\r\n{\r\n\tif (zoom < 0.5)\r\n\t\treturn;\r\n\r\n\tcurrentZoom = zoom;\r\n\r\n\tPoint<int> anchor (getCurrentCanvas()->getLocalPoint (viewport, Point<int> (anchorX, anchorY)));\r\n\r\n\tresized();\r\n\tanchor = viewport->getLocalPoint (getCurrentCanvas(), anchor);\r\n\r\n\tviewport->setViewPosition (jlimit (0, jmax (0, viewport->getViewedComponent()->getWidth() - viewport->getViewWidth()),\r\n viewport->getViewPositionX() + anchor.getX() - anchorX),\r\n jlimit (0, jmax (0, viewport->getViewedComponent()->getHeight() - viewport->getViewHeight()),\r\n viewport->getViewPositionY() + anchor.getY() - anchorY));\r\n\tmagnifier->setScaleFactor (currentZoom);\r\n}\r\n\r\nconst double CtrlrPanelViewport::getZoom ()\r\n{\r\n\treturn (currentZoom);\r\n}\r\n\r\nvoid CtrlrPanelViewport::dragKeyHeldDown (const bool isKeyDown)\r\n{\r\n\tif (isSpaceDown != isKeyDown)\r\n\t{\r\n\t\tisSpaceDown = isKeyDown;\r\n\r\n\t\tif (isSpaceDown)\r\n\t\t{\r\n\t\t\tCtrlrDraggerOverlayComp* const dc = new CtrlrDraggerOverlayComp(viewport);\r\n\t\t\taddAndMakeVisible (dc);\r\n\t\t\tdc->setBounds (0, 0, getWidth(), getHeight());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (int i = getNumChildComponents(); --i >= 0;)\r\n\t\t\t{\r\n\t\t\t\tif (dynamic_cast <CtrlrDraggerOverlayComp*> (getChildComponent (i)) != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdelete getChildComponent (i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nCtrlrViewportImpl::CtrlrViewportImpl(CtrlrPanelViewport *_panelViewport) : panelViewport(_panelViewport)\r\n{\r\n}\r\n\r\nCtrlrViewportImpl::~CtrlrViewportImpl()\r\n{\r\n}\r\n\r\nvoid CtrlrViewportImpl::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)\r\n{\r\n if (e.mods.isCtrlDown() || e.mods.isAltDown())\r\n\t{\r\n\t const double factor = (wheel.deltaY > 0) ? 2.0 : 0.5;\r\n\r\n\t\tpanelViewport->setZoom (panelViewport->getZoom() * factor, e.x, e.y);\r\n }\r\n else\r\n {\r\n\t\tCtrlrViewport::mouseWheelMove (e, wheel);\r\n\t}\r\n}\r\n\r\nbool CtrlrViewportImpl::keyPressed (const KeyPress &key, Component *originatingComponent)\r\n{\r\n\treturn (false);\r\n}\r\n\r\nbool CtrlrViewportImpl::keyStateChanged (bool isKeyDown, Component *originatingComponent)\r\n{\r\n\treturn (false);\r\n}\r\n\r\nvoid CtrlrPanelViewport::setCurrentEditedCanvas(const int canvasIndex)\r\n{\r\n}\r\n\r\nvoid CtrlrPanelViewport::addCanvas(const String &canvasName)\r\n{\r\n\tCtrlrPanelCanvas *c = new CtrlrPanelCanvas (owner);\r\n\tc->setProperty (Ids::uiPanelCanvasLayerName, canvasName);\r\n\tc->setProperty (Ids::uiPanelCanvasLayerIndex, canvasList.size());\r\n\r\n\tcanvasList.add (c);\r\n}\r\n\r\nvoid CtrlrPanelViewport::removeCanvas(const int canvasIndex)\r\n{\r\n}\r\n\r\nconst int CtrlrPanelViewport::getNumCanvases()\r\n{\r\n\treturn (canvasList.size());\r\n}\r\n\r\nvoid CtrlrPanelViewport::moveCanvasUp(const int canvasIndex)\r\n{\r\n}\r\n\r\nvoid CtrlrPanelViewport::moveCanvasDown(const int canvasIndex)\r\n{\r\n}\r\n\r\nCtrlrPanelCanvas *CtrlrPanelViewport::getCurrentCanvas()\r\n{\r\n\treturn (canvasList[0]);\r\n}\r\n\r\nvoid CtrlrPanelViewport::lookAndFeelChanged()\r\n{\r\n\tresized();\r\n}\r\n<commit_msg>zoomin and zoomout corrected.<commit_after>#include \"stdafx.h\"\r\n#include \"CtrlrPanelViewport.h\"\r\n#include \"CtrlrPanel\/CtrlrPanel.h\"\r\n#include \"CtrlrPanelEditor.h\"\r\n#include \"CtrlrManager\/CtrlrManager.h\"\r\n\r\n\/**\r\n *\/\r\n\r\nCtrlrPanelViewport::CtrlrPanelViewport (CtrlrPanelEditor &_owner)\r\n\t: owner(_owner), isSpaceDown(false)\r\n{\r\n\tcurrentZoom = 1.0;\r\n\r\n\tcanvasList.add (new CtrlrPanelCanvas (owner));\r\n\r\n\tmagnifier = new CtrlrMagnifierComponent (canvasList[0]);\r\n\taddAndMakeVisible (viewport = new CtrlrViewportImpl(this));\r\n\tviewport->setViewedComponent (magnifier);\r\n\r\n setSize (512, 512);\r\n}\r\n\r\nCtrlrPanelViewport::~CtrlrPanelViewport()\r\n{\r\n\tcanvasList.clear (false);\r\n\tdeleteAndZero (viewport);\r\n}\r\n\r\n\r\nvoid CtrlrPanelViewport::paint (Graphics& g)\r\n{\r\n\tg.fillAll (Colours::transparentBlack);\r\n}\r\n\r\nvoid CtrlrPanelViewport::resized()\r\n{\r\n\tviewport->setBounds\t(0, 0, getWidth(), getHeight());\r\n}\r\n\r\nbool CtrlrPanelViewport::keyStateChanged (const bool isKeyDown)\r\n{\r\n\tif (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))\r\n\t{\r\n\t\tdragKeyHeldDown (true);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdragKeyHeldDown (false);\r\n\t}\r\n return false;\r\n}\r\n\r\nvoid CtrlrPanelViewport::setZoom (const double zoom, int anchorX, int anchorY)\r\n{\r\n\tif (zoom < 0.5)\r\n\t\treturn;\r\n\r\n\tcurrentZoom = zoom;\r\n\r\n\tPoint<int> anchor (getCurrentCanvas()->getLocalPoint (viewport, Point<int> (anchorX, anchorY)));\r\n\r\n\tresized();\r\n\tanchor = viewport->getLocalPoint (getCurrentCanvas(), anchor);\r\n\r\n\tviewport->setViewPosition (jlimit (0, jmax (0, viewport->getViewedComponent()->getWidth() - viewport->getViewWidth()),\r\n viewport->getViewPositionX() + anchor.getX() - anchorX),\r\n jlimit (0, jmax (0, viewport->getViewedComponent()->getHeight() - viewport->getViewHeight()),\r\n viewport->getViewPositionY() + anchor.getY() - anchorY));\r\n\tmagnifier->setScaleFactor (currentZoom);\r\n}\r\n\r\nconst double CtrlrPanelViewport::getZoom ()\r\n{\r\n\treturn (currentZoom);\r\n}\r\n\r\nvoid CtrlrPanelViewport::dragKeyHeldDown (const bool isKeyDown)\r\n{\r\n\tif (isSpaceDown != isKeyDown)\r\n\t{\r\n\t\tisSpaceDown = isKeyDown;\r\n\r\n\t\tif (isSpaceDown)\r\n\t\t{\r\n\t\t\tCtrlrDraggerOverlayComp* const dc = new CtrlrDraggerOverlayComp(viewport);\r\n\t\t\taddAndMakeVisible (dc);\r\n\t\t\tdc->setBounds (0, 0, getWidth(), getHeight());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (int i = getNumChildComponents(); --i >= 0;)\r\n\t\t\t{\r\n\t\t\t\tif (dynamic_cast <CtrlrDraggerOverlayComp*> (getChildComponent (i)) != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdelete getChildComponent (i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nCtrlrViewportImpl::CtrlrViewportImpl(CtrlrPanelViewport *_panelViewport) : panelViewport(_panelViewport)\r\n{\r\n}\r\n\r\nCtrlrViewportImpl::~CtrlrViewportImpl()\r\n{\r\n}\r\n\r\nvoid CtrlrViewportImpl::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)\r\n{\r\n if (e.mods.isCtrlDown() || e.mods.isAltDown())\r\n\t{\r\n\t\tconst double factor = (wheel.deltaY > 0) ? 1.10 : 0.90;\n\t\tpanelViewport->setZoom (panelViewport->getZoom() * factor, e.x, e.y);\r\n }\r\n else\r\n {\r\n\t\tCtrlrViewport::mouseWheelMove (e, wheel);\r\n\t}\r\n}\r\n\r\nbool CtrlrViewportImpl::keyPressed (const KeyPress &key, Component *originatingComponent)\r\n{\r\n\treturn (false);\r\n}\r\n\r\nbool CtrlrViewportImpl::keyStateChanged (bool isKeyDown, Component *originatingComponent)\r\n{\r\n\treturn (false);\r\n}\r\n\r\nvoid CtrlrPanelViewport::setCurrentEditedCanvas(const int canvasIndex)\r\n{\r\n}\r\n\r\nvoid CtrlrPanelViewport::addCanvas(const String &canvasName)\r\n{\r\n\tCtrlrPanelCanvas *c = new CtrlrPanelCanvas (owner);\r\n\tc->setProperty (Ids::uiPanelCanvasLayerName, canvasName);\r\n\tc->setProperty (Ids::uiPanelCanvasLayerIndex, canvasList.size());\r\n\r\n\tcanvasList.add (c);\r\n}\r\n\r\nvoid CtrlrPanelViewport::removeCanvas(const int canvasIndex)\r\n{\r\n}\r\n\r\nconst int CtrlrPanelViewport::getNumCanvases()\r\n{\r\n\treturn (canvasList.size());\r\n}\r\n\r\nvoid CtrlrPanelViewport::moveCanvasUp(const int canvasIndex)\r\n{\r\n}\r\n\r\nvoid CtrlrPanelViewport::moveCanvasDown(const int canvasIndex)\r\n{\r\n}\r\n\r\nCtrlrPanelCanvas *CtrlrPanelViewport::getCurrentCanvas()\r\n{\r\n\treturn (canvasList[0]);\r\n}\r\n\r\nvoid CtrlrPanelViewport::lookAndFeelChanged()\r\n{\r\n\tresized();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- HexagonISelLoweringHVX.cpp --- Lowering HVX operations ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"HexagonISelLowering.h\"\n#include \"HexagonRegisterInfo.h\"\n#include \"HexagonSubtarget.h\"\n\nusing namespace llvm;\n\nSDValue\nHexagonTargetLowering::getInt(unsigned IntId, MVT ResTy, ArrayRef<SDValue> Ops,\n const SDLoc &dl, SelectionDAG &DAG) const {\n SmallVector<SDValue,4> IntOps;\n IntOps.push_back(DAG.getConstant(IntId, dl, MVT::i32));\n for (const SDValue &Op : Ops)\n IntOps.push_back(Op);\n return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, ResTy, IntOps);\n}\n\nMVT\nHexagonTargetLowering::typeJoin(const TypePair &Tys) const {\n assert(Tys.first.getVectorElementType() == Tys.second.getVectorElementType());\n\n MVT ElemTy = Tys.first.getVectorElementType();\n return MVT::getVectorVT(ElemTy, Tys.first.getVectorNumElements() +\n Tys.second.getVectorNumElements());\n}\n\nHexagonTargetLowering::TypePair\nHexagonTargetLowering::typeSplit(MVT VecTy) const {\n assert(VecTy.isVector());\n unsigned NumElem = VecTy.getVectorNumElements();\n assert((NumElem % 2) == 0 && \"Expecting even-sized vector type\");\n MVT HalfTy = MVT::getVectorVT(VecTy.getVectorElementType(), NumElem\/2);\n return { HalfTy, HalfTy };\n}\n\nMVT\nHexagonTargetLowering::typeExtElem(MVT VecTy, unsigned Factor) const {\n MVT ElemTy = VecTy.getVectorElementType();\n MVT NewElemTy = MVT::getIntegerVT(ElemTy.getSizeInBits() * Factor);\n return MVT::getVectorVT(NewElemTy, VecTy.getVectorNumElements());\n}\n\nMVT\nHexagonTargetLowering::typeTruncElem(MVT VecTy, unsigned Factor) const {\n MVT ElemTy = VecTy.getVectorElementType();\n MVT NewElemTy = MVT::getIntegerVT(ElemTy.getSizeInBits() \/ Factor);\n return MVT::getVectorVT(NewElemTy, VecTy.getVectorNumElements());\n}\n\nSDValue\nHexagonTargetLowering::opCastElem(SDValue Vec, MVT ElemTy,\n SelectionDAG &DAG) const {\n if (ty(Vec).getVectorElementType() == ElemTy)\n return Vec;\n MVT CastTy = tyVector(Vec.getValueType().getSimpleVT(), ElemTy);\n return DAG.getBitcast(CastTy, Vec);\n}\n\nSDValue\nHexagonTargetLowering::opJoin(const VectorPair &Ops, const SDLoc &dl,\n SelectionDAG &DAG) const {\n return DAG.getNode(ISD::CONCAT_VECTORS, dl, typeJoin(ty(Ops)),\n Ops.second, Ops.first);\n}\n\nHexagonTargetLowering::VectorPair\nHexagonTargetLowering::opSplit(SDValue Vec, const SDLoc &dl,\n SelectionDAG &DAG) const {\n TypePair Tys = typeSplit(ty(Vec));\n return DAG.SplitVector(Vec, dl, Tys.first, Tys.second);\n}\n\nSDValue\nHexagonTargetLowering::convertToByteIndex(SDValue ElemIdx, MVT ElemTy,\n SelectionDAG &DAG) const {\n if (ElemIdx.getValueType().getSimpleVT() != MVT::i32)\n ElemIdx = DAG.getBitcast(MVT::i32, ElemIdx);\n\n unsigned ElemWidth = ElemTy.getSizeInBits();\n if (ElemWidth == 8)\n return ElemIdx;\n\n unsigned L = Log2_32(ElemWidth\/8);\n const SDLoc &dl(ElemIdx);\n return DAG.getNode(ISD::SHL, dl, MVT::i32,\n {ElemIdx, DAG.getConstant(L, dl, MVT::i32)});\n}\n\nSDValue\nHexagonTargetLowering::getIndexInWord32(SDValue Idx, MVT ElemTy,\n SelectionDAG &DAG) const {\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32);\n if (ElemWidth == 32)\n return Idx;\n\n if (ty(Idx) != MVT::i32)\n Idx = DAG.getBitcast(MVT::i32, Idx);\n const SDLoc &dl(Idx);\n SDValue Mask = DAG.getConstant(32\/ElemWidth - 1, dl, MVT::i32);\n SDValue SubIdx = DAG.getNode(ISD::AND, dl, MVT::i32, {Idx, Mask});\n return SubIdx;\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxBuildVector(SDValue Op, SelectionDAG &DAG)\n const {\n const SDLoc &dl(Op);\n BuildVectorSDNode *BN = cast<BuildVectorSDNode>(Op.getNode());\n bool IsConst = BN->isConstant();\n MachineFunction &MF = DAG.getMachineFunction();\n MVT VecTy = ty(Op);\n\n if (IsConst) {\n SmallVector<Constant*, 128> Elems;\n for (SDValue V : BN->op_values()) {\n if (auto *C = dyn_cast<ConstantSDNode>(V.getNode()))\n Elems.push_back(const_cast<ConstantInt*>(C->getConstantIntValue()));\n }\n Constant *CV = ConstantVector::get(Elems);\n unsigned Align = VecTy.getSizeInBits() \/ 8;\n SDValue CP = LowerConstantPool(DAG.getConstantPool(CV, VecTy, Align), DAG);\n return DAG.getLoad(VecTy, dl, DAG.getEntryNode(), CP,\n MachinePointerInfo::getConstantPool(MF), Align);\n }\n\n unsigned NumOps = Op.getNumOperands();\n unsigned HwLen = Subtarget.getVectorLength();\n unsigned ElemSize = VecTy.getVectorElementType().getSizeInBits() \/ 8;\n assert(ElemSize*NumOps == HwLen);\n\n SmallVector<SDValue,32> Words;\n SmallVector<SDValue,32> Ops;\n for (unsigned i = 0; i != NumOps; ++i)\n Ops.push_back(Op.getOperand(i));\n\n if (VecTy.getVectorElementType() != MVT::i32) {\n assert(ElemSize < 4 && \"vNi64 should have been promoted to vNi32\");\n assert((ElemSize == 1 || ElemSize == 2) && \"Invalid element size\");\n unsigned OpsPerWord = (ElemSize == 1) ? 4 : 2;\n MVT PartVT = MVT::getVectorVT(VecTy.getVectorElementType(), OpsPerWord);\n for (unsigned i = 0; i != NumOps; i += OpsPerWord) {\n SDValue W = buildVector32({&Ops[i], OpsPerWord}, dl, PartVT, DAG);\n Words.push_back(DAG.getBitcast(MVT::i32, W));\n }\n } else {\n Words.assign(Ops.begin(), Ops.end());\n }\n\n \/\/ Construct two halves in parallel, then or them together.\n assert(4*Words.size() == Subtarget.getVectorLength());\n SDValue HalfV0 = getNode(Hexagon::V6_vd0, dl, VecTy, {}, DAG);\n SDValue HalfV1 = getNode(Hexagon::V6_vd0, dl, VecTy, {}, DAG);\n SDValue S = DAG.getConstant(4, dl, MVT::i32);\n unsigned NumWords = Words.size();\n for (unsigned i = 0; i != NumWords\/2; ++i) {\n SDValue N = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy,\n {HalfV0, Words[i]});\n SDValue M = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy,\n {HalfV1, Words[i+NumWords\/2]});\n HalfV0 = DAG.getNode(HexagonISD::VROR, dl, VecTy, {N, S});\n HalfV1 = DAG.getNode(HexagonISD::VROR, dl, VecTy, {M, S});\n }\n\n HalfV0 = DAG.getNode(HexagonISD::VROR, dl, VecTy,\n {HalfV0, DAG.getConstant(HwLen\/2, dl, MVT::i32)});\n SDValue DstV = DAG.getNode(ISD::OR, dl, VecTy, {HalfV0, HalfV1});\n return DstV;\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxExtractElement(SDValue Op, SelectionDAG &DAG)\n const {\n \/\/ Change the type of the extracted element to i32.\n SDValue VecV = Op.getOperand(0);\n MVT ElemTy = ty(VecV).getVectorElementType();\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32); \/\/ TODO i64\n\n const SDLoc &dl(Op);\n SDValue IdxV = Op.getOperand(1);\n if (ty(IdxV) != MVT::i32)\n IdxV = DAG.getBitcast(MVT::i32, IdxV);\n\n SDValue ByteIdx = convertToByteIndex(IdxV, ElemTy, DAG);\n SDValue ExWord = DAG.getNode(HexagonISD::VEXTRACTW, dl, MVT::i32,\n {VecV, ByteIdx});\n if (ElemTy == MVT::i32)\n return ExWord;\n\n \/\/ Have an extracted word, need to extract the smaller element out of it.\n \/\/ 1. Extract the bits of (the original) IdxV that correspond to the index\n \/\/ of the desired element in the 32-bit word.\n SDValue SubIdx = getIndexInWord32(IdxV, ElemTy, DAG);\n \/\/ 2. Extract the element from the word.\n SDValue ExVec = DAG.getBitcast(tyVector(ty(ExWord), ElemTy), ExWord);\n return extractVector(ExVec, SubIdx, dl, ElemTy, MVT::i32, DAG);\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxInsertElement(SDValue Op, SelectionDAG &DAG)\n const {\n const SDLoc &dl(Op);\n SDValue VecV = Op.getOperand(0);\n SDValue ValV = Op.getOperand(1);\n SDValue IdxV = Op.getOperand(2);\n MVT ElemTy = ty(VecV).getVectorElementType();\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32); \/\/ TODO i64\n\n auto InsertWord = [&DAG,&dl,this] (SDValue VecV, SDValue ValV,\n SDValue ByteIdxV) {\n MVT VecTy = ty(VecV);\n unsigned HwLen = Subtarget.getVectorLength();\n SDValue MaskV = DAG.getNode(ISD::AND, dl, MVT::i32,\n {ByteIdxV, DAG.getConstant(-4, dl, MVT::i32)});\n SDValue RotV = DAG.getNode(HexagonISD::VROR, dl, VecTy, {VecV, MaskV});\n SDValue InsV = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy, {RotV, ValV});\n SDValue SubV = DAG.getNode(ISD::SUB, dl, MVT::i32,\n {DAG.getConstant(HwLen\/4, dl, MVT::i32), MaskV});\n SDValue TorV = DAG.getNode(HexagonISD::VROR, dl, VecTy, {InsV, SubV});\n return TorV;\n };\n\n SDValue ByteIdx = convertToByteIndex(IdxV, ElemTy, DAG);\n if (ElemTy == MVT::i32)\n return InsertWord(VecV, ValV, ByteIdx);\n\n \/\/ If this is not inserting a 32-bit word, convert it into such a thing.\n \/\/ 1. Extract the existing word from the target vector.\n SDValue WordIdx = DAG.getNode(ISD::SRL, dl, MVT::i32,\n {ByteIdx, DAG.getConstant(2, dl, MVT::i32)});\n SDValue Ex0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,\n {opCastElem(VecV, MVT::i32, DAG), WordIdx});\n SDValue Ext = LowerHvxExtractElement(Ex0, DAG);\n\n \/\/ 2. Treating the extracted word as a 32-bit vector, insert the given\n \/\/ value into it.\n SDValue SubIdx = getIndexInWord32(IdxV, ElemTy, DAG);\n MVT SubVecTy = tyVector(ty(Ext), ElemTy);\n SDValue Ins = insertVector(DAG.getBitcast(SubVecTy, Ext),\n ValV, SubIdx, dl, SubVecTy, DAG);\n\n \/\/ 3. Insert the 32-bit word back into the original vector.\n return InsertWord(VecV, Ins, ByteIdx);\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxExtractSubvector(SDValue Op, SelectionDAG &DAG)\n const {\n SDValue SrcV = Op.getOperand(0);\n MVT SrcTy = ty(SrcV);\n unsigned SrcElems = SrcTy.getVectorNumElements();\n SDValue IdxV = Op.getOperand(1);\n unsigned Idx = cast<ConstantSDNode>(IdxV.getNode())->getZExtValue();\n MVT DstTy = ty(Op);\n assert(Idx == 0 || DstTy.getVectorNumElements() % Idx == 0);\n const SDLoc &dl(Op);\n if (Idx == 0)\n return DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, DstTy, SrcV);\n if (Idx == SrcElems\/2)\n return DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, DstTy, SrcV);\n return SDValue();\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxInsertSubvector(SDValue Op, SelectionDAG &DAG)\n const {\n \/\/ Idx may be variable\n SDValue IdxV = Op.getOperand(2);\n auto *IdxN = dyn_cast<ConstantSDNode>(IdxV.getNode());\n if (!IdxN)\n return SDValue();\n unsigned Idx = IdxN->getZExtValue();\n\n SDValue DstV = Op.getOperand(0);\n SDValue SrcV = Op.getOperand(1);\n MVT DstTy = ty(DstV);\n MVT SrcTy = ty(SrcV);\n unsigned DstElems = DstTy.getVectorNumElements();\n unsigned SrcElems = SrcTy.getVectorNumElements();\n if (2*SrcElems != DstElems)\n return SDValue();\n\n const SDLoc &dl(Op);\n if (Idx == 0)\n return DAG.getTargetInsertSubreg(Hexagon::vsub_lo, dl, DstTy, DstV, SrcV);\n if (Idx == SrcElems)\n return DAG.getTargetInsertSubreg(Hexagon::vsub_hi, dl, DstTy, DstV, SrcV);\n return SDValue();\n}\n<commit_msg>[Hexagon] Suppress warnings on unused variables defind for asserts.<commit_after>\/\/===-- HexagonISelLoweringHVX.cpp --- Lowering HVX operations ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"HexagonISelLowering.h\"\n#include \"HexagonRegisterInfo.h\"\n#include \"HexagonSubtarget.h\"\n\nusing namespace llvm;\n\nSDValue\nHexagonTargetLowering::getInt(unsigned IntId, MVT ResTy, ArrayRef<SDValue> Ops,\n const SDLoc &dl, SelectionDAG &DAG) const {\n SmallVector<SDValue,4> IntOps;\n IntOps.push_back(DAG.getConstant(IntId, dl, MVT::i32));\n for (const SDValue &Op : Ops)\n IntOps.push_back(Op);\n return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, ResTy, IntOps);\n}\n\nMVT\nHexagonTargetLowering::typeJoin(const TypePair &Tys) const {\n assert(Tys.first.getVectorElementType() == Tys.second.getVectorElementType());\n\n MVT ElemTy = Tys.first.getVectorElementType();\n return MVT::getVectorVT(ElemTy, Tys.first.getVectorNumElements() +\n Tys.second.getVectorNumElements());\n}\n\nHexagonTargetLowering::TypePair\nHexagonTargetLowering::typeSplit(MVT VecTy) const {\n assert(VecTy.isVector());\n unsigned NumElem = VecTy.getVectorNumElements();\n assert((NumElem % 2) == 0 && \"Expecting even-sized vector type\");\n MVT HalfTy = MVT::getVectorVT(VecTy.getVectorElementType(), NumElem\/2);\n return { HalfTy, HalfTy };\n}\n\nMVT\nHexagonTargetLowering::typeExtElem(MVT VecTy, unsigned Factor) const {\n MVT ElemTy = VecTy.getVectorElementType();\n MVT NewElemTy = MVT::getIntegerVT(ElemTy.getSizeInBits() * Factor);\n return MVT::getVectorVT(NewElemTy, VecTy.getVectorNumElements());\n}\n\nMVT\nHexagonTargetLowering::typeTruncElem(MVT VecTy, unsigned Factor) const {\n MVT ElemTy = VecTy.getVectorElementType();\n MVT NewElemTy = MVT::getIntegerVT(ElemTy.getSizeInBits() \/ Factor);\n return MVT::getVectorVT(NewElemTy, VecTy.getVectorNumElements());\n}\n\nSDValue\nHexagonTargetLowering::opCastElem(SDValue Vec, MVT ElemTy,\n SelectionDAG &DAG) const {\n if (ty(Vec).getVectorElementType() == ElemTy)\n return Vec;\n MVT CastTy = tyVector(Vec.getValueType().getSimpleVT(), ElemTy);\n return DAG.getBitcast(CastTy, Vec);\n}\n\nSDValue\nHexagonTargetLowering::opJoin(const VectorPair &Ops, const SDLoc &dl,\n SelectionDAG &DAG) const {\n return DAG.getNode(ISD::CONCAT_VECTORS, dl, typeJoin(ty(Ops)),\n Ops.second, Ops.first);\n}\n\nHexagonTargetLowering::VectorPair\nHexagonTargetLowering::opSplit(SDValue Vec, const SDLoc &dl,\n SelectionDAG &DAG) const {\n TypePair Tys = typeSplit(ty(Vec));\n return DAG.SplitVector(Vec, dl, Tys.first, Tys.second);\n}\n\nSDValue\nHexagonTargetLowering::convertToByteIndex(SDValue ElemIdx, MVT ElemTy,\n SelectionDAG &DAG) const {\n if (ElemIdx.getValueType().getSimpleVT() != MVT::i32)\n ElemIdx = DAG.getBitcast(MVT::i32, ElemIdx);\n\n unsigned ElemWidth = ElemTy.getSizeInBits();\n if (ElemWidth == 8)\n return ElemIdx;\n\n unsigned L = Log2_32(ElemWidth\/8);\n const SDLoc &dl(ElemIdx);\n return DAG.getNode(ISD::SHL, dl, MVT::i32,\n {ElemIdx, DAG.getConstant(L, dl, MVT::i32)});\n}\n\nSDValue\nHexagonTargetLowering::getIndexInWord32(SDValue Idx, MVT ElemTy,\n SelectionDAG &DAG) const {\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32);\n if (ElemWidth == 32)\n return Idx;\n\n if (ty(Idx) != MVT::i32)\n Idx = DAG.getBitcast(MVT::i32, Idx);\n const SDLoc &dl(Idx);\n SDValue Mask = DAG.getConstant(32\/ElemWidth - 1, dl, MVT::i32);\n SDValue SubIdx = DAG.getNode(ISD::AND, dl, MVT::i32, {Idx, Mask});\n return SubIdx;\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxBuildVector(SDValue Op, SelectionDAG &DAG)\n const {\n const SDLoc &dl(Op);\n BuildVectorSDNode *BN = cast<BuildVectorSDNode>(Op.getNode());\n bool IsConst = BN->isConstant();\n MachineFunction &MF = DAG.getMachineFunction();\n MVT VecTy = ty(Op);\n\n if (IsConst) {\n SmallVector<Constant*, 128> Elems;\n for (SDValue V : BN->op_values()) {\n if (auto *C = dyn_cast<ConstantSDNode>(V.getNode()))\n Elems.push_back(const_cast<ConstantInt*>(C->getConstantIntValue()));\n }\n Constant *CV = ConstantVector::get(Elems);\n unsigned Align = VecTy.getSizeInBits() \/ 8;\n SDValue CP = LowerConstantPool(DAG.getConstantPool(CV, VecTy, Align), DAG);\n return DAG.getLoad(VecTy, dl, DAG.getEntryNode(), CP,\n MachinePointerInfo::getConstantPool(MF), Align);\n }\n\n unsigned NumOps = Op.getNumOperands();\n unsigned HwLen = Subtarget.getVectorLength();\n unsigned ElemSize = VecTy.getVectorElementType().getSizeInBits() \/ 8;\n assert(ElemSize*NumOps == HwLen);\n\n SmallVector<SDValue,32> Words;\n SmallVector<SDValue,32> Ops;\n for (unsigned i = 0; i != NumOps; ++i)\n Ops.push_back(Op.getOperand(i));\n\n if (VecTy.getVectorElementType() != MVT::i32) {\n assert(ElemSize < 4 && \"vNi64 should have been promoted to vNi32\");\n assert((ElemSize == 1 || ElemSize == 2) && \"Invalid element size\");\n unsigned OpsPerWord = (ElemSize == 1) ? 4 : 2;\n MVT PartVT = MVT::getVectorVT(VecTy.getVectorElementType(), OpsPerWord);\n for (unsigned i = 0; i != NumOps; i += OpsPerWord) {\n SDValue W = buildVector32({&Ops[i], OpsPerWord}, dl, PartVT, DAG);\n Words.push_back(DAG.getBitcast(MVT::i32, W));\n }\n } else {\n Words.assign(Ops.begin(), Ops.end());\n }\n\n \/\/ Construct two halves in parallel, then or them together.\n assert(4*Words.size() == Subtarget.getVectorLength());\n SDValue HalfV0 = getNode(Hexagon::V6_vd0, dl, VecTy, {}, DAG);\n SDValue HalfV1 = getNode(Hexagon::V6_vd0, dl, VecTy, {}, DAG);\n SDValue S = DAG.getConstant(4, dl, MVT::i32);\n unsigned NumWords = Words.size();\n for (unsigned i = 0; i != NumWords\/2; ++i) {\n SDValue N = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy,\n {HalfV0, Words[i]});\n SDValue M = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy,\n {HalfV1, Words[i+NumWords\/2]});\n HalfV0 = DAG.getNode(HexagonISD::VROR, dl, VecTy, {N, S});\n HalfV1 = DAG.getNode(HexagonISD::VROR, dl, VecTy, {M, S});\n }\n\n HalfV0 = DAG.getNode(HexagonISD::VROR, dl, VecTy,\n {HalfV0, DAG.getConstant(HwLen\/2, dl, MVT::i32)});\n SDValue DstV = DAG.getNode(ISD::OR, dl, VecTy, {HalfV0, HalfV1});\n return DstV;\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxExtractElement(SDValue Op, SelectionDAG &DAG)\n const {\n \/\/ Change the type of the extracted element to i32.\n SDValue VecV = Op.getOperand(0);\n MVT ElemTy = ty(VecV).getVectorElementType();\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32); \/\/ TODO i64\n (void)ElemWidth;\n\n const SDLoc &dl(Op);\n SDValue IdxV = Op.getOperand(1);\n if (ty(IdxV) != MVT::i32)\n IdxV = DAG.getBitcast(MVT::i32, IdxV);\n\n SDValue ByteIdx = convertToByteIndex(IdxV, ElemTy, DAG);\n SDValue ExWord = DAG.getNode(HexagonISD::VEXTRACTW, dl, MVT::i32,\n {VecV, ByteIdx});\n if (ElemTy == MVT::i32)\n return ExWord;\n\n \/\/ Have an extracted word, need to extract the smaller element out of it.\n \/\/ 1. Extract the bits of (the original) IdxV that correspond to the index\n \/\/ of the desired element in the 32-bit word.\n SDValue SubIdx = getIndexInWord32(IdxV, ElemTy, DAG);\n \/\/ 2. Extract the element from the word.\n SDValue ExVec = DAG.getBitcast(tyVector(ty(ExWord), ElemTy), ExWord);\n return extractVector(ExVec, SubIdx, dl, ElemTy, MVT::i32, DAG);\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxInsertElement(SDValue Op, SelectionDAG &DAG)\n const {\n const SDLoc &dl(Op);\n SDValue VecV = Op.getOperand(0);\n SDValue ValV = Op.getOperand(1);\n SDValue IdxV = Op.getOperand(2);\n MVT ElemTy = ty(VecV).getVectorElementType();\n unsigned ElemWidth = ElemTy.getSizeInBits();\n assert(ElemWidth >= 8 && ElemWidth <= 32); \/\/ TODO i64\n (void)ElemWidth;\n\n auto InsertWord = [&DAG,&dl,this] (SDValue VecV, SDValue ValV,\n SDValue ByteIdxV) {\n MVT VecTy = ty(VecV);\n unsigned HwLen = Subtarget.getVectorLength();\n SDValue MaskV = DAG.getNode(ISD::AND, dl, MVT::i32,\n {ByteIdxV, DAG.getConstant(-4, dl, MVT::i32)});\n SDValue RotV = DAG.getNode(HexagonISD::VROR, dl, VecTy, {VecV, MaskV});\n SDValue InsV = DAG.getNode(HexagonISD::VINSERTW0, dl, VecTy, {RotV, ValV});\n SDValue SubV = DAG.getNode(ISD::SUB, dl, MVT::i32,\n {DAG.getConstant(HwLen\/4, dl, MVT::i32), MaskV});\n SDValue TorV = DAG.getNode(HexagonISD::VROR, dl, VecTy, {InsV, SubV});\n return TorV;\n };\n\n SDValue ByteIdx = convertToByteIndex(IdxV, ElemTy, DAG);\n if (ElemTy == MVT::i32)\n return InsertWord(VecV, ValV, ByteIdx);\n\n \/\/ If this is not inserting a 32-bit word, convert it into such a thing.\n \/\/ 1. Extract the existing word from the target vector.\n SDValue WordIdx = DAG.getNode(ISD::SRL, dl, MVT::i32,\n {ByteIdx, DAG.getConstant(2, dl, MVT::i32)});\n SDValue Ex0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,\n {opCastElem(VecV, MVT::i32, DAG), WordIdx});\n SDValue Ext = LowerHvxExtractElement(Ex0, DAG);\n\n \/\/ 2. Treating the extracted word as a 32-bit vector, insert the given\n \/\/ value into it.\n SDValue SubIdx = getIndexInWord32(IdxV, ElemTy, DAG);\n MVT SubVecTy = tyVector(ty(Ext), ElemTy);\n SDValue Ins = insertVector(DAG.getBitcast(SubVecTy, Ext),\n ValV, SubIdx, dl, SubVecTy, DAG);\n\n \/\/ 3. Insert the 32-bit word back into the original vector.\n return InsertWord(VecV, Ins, ByteIdx);\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxExtractSubvector(SDValue Op, SelectionDAG &DAG)\n const {\n SDValue SrcV = Op.getOperand(0);\n MVT SrcTy = ty(SrcV);\n unsigned SrcElems = SrcTy.getVectorNumElements();\n SDValue IdxV = Op.getOperand(1);\n unsigned Idx = cast<ConstantSDNode>(IdxV.getNode())->getZExtValue();\n MVT DstTy = ty(Op);\n assert(Idx == 0 || DstTy.getVectorNumElements() % Idx == 0);\n const SDLoc &dl(Op);\n if (Idx == 0)\n return DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, DstTy, SrcV);\n if (Idx == SrcElems\/2)\n return DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, DstTy, SrcV);\n return SDValue();\n}\n\nSDValue\nHexagonTargetLowering::LowerHvxInsertSubvector(SDValue Op, SelectionDAG &DAG)\n const {\n \/\/ Idx may be variable\n SDValue IdxV = Op.getOperand(2);\n auto *IdxN = dyn_cast<ConstantSDNode>(IdxV.getNode());\n if (!IdxN)\n return SDValue();\n unsigned Idx = IdxN->getZExtValue();\n\n SDValue DstV = Op.getOperand(0);\n SDValue SrcV = Op.getOperand(1);\n MVT DstTy = ty(DstV);\n MVT SrcTy = ty(SrcV);\n unsigned DstElems = DstTy.getVectorNumElements();\n unsigned SrcElems = SrcTy.getVectorNumElements();\n if (2*SrcElems != DstElems)\n return SDValue();\n\n const SDLoc &dl(Op);\n if (Idx == 0)\n return DAG.getTargetInsertSubreg(Hexagon::vsub_lo, dl, DstTy, DstV, SrcV);\n if (Idx == SrcElems)\n return DAG.getTargetInsertSubreg(Hexagon::vsub_hi, dl, DstTy, DstV, SrcV);\n return SDValue();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GUI_Utils.hpp\"\n\n#include <algorithm>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/format.hpp>\n\n#ifdef _WIN32\n#include <Windows.h>\n#endif\n\n#include <wx\/toplevel.h>\n#include <wx\/sizer.h>\n#include <wx\/checkbox.h>\n#include <wx\/dcclient.h>\n#include <wx\/font.h>\n#include <wx\/fontutil.h>\n\n#include \"libslic3r\/Config.hpp\"\n\n\nnamespace Slic3r {\nnamespace GUI {\n\n\nwxTopLevelWindow* find_toplevel_parent(wxWindow *window)\n{\n for (; window != nullptr; window = window->GetParent()) {\n if (window->IsTopLevel()) {\n return dynamic_cast<wxTopLevelWindow*>(window);\n }\n }\n\n return nullptr;\n}\n\nvoid on_window_geometry(wxTopLevelWindow *tlw, std::function<void()> callback)\n{\n#ifdef _WIN32\n \/\/ On windows, the wxEVT_SHOW is not received if the window is created maximized\n \/\/ cf. https:\/\/groups.google.com\/forum\/#!topic\/wx-users\/c7ntMt6piRI\n \/\/ OTOH the geometry is available very soon, so we can call the callback right away\n callback();\n#elif defined __linux__\n tlw->Bind(wxEVT_SHOW, [=](wxShowEvent &evt) {\n \/\/ On Linux, the geometry is only available after wxEVT_SHOW + CallAfter\n \/\/ cf. https:\/\/groups.google.com\/forum\/?pli=1#!topic\/wx-users\/fERSXdpVwAI\n tlw->CallAfter([=]() { callback(); });\n evt.Skip();\n });\n#elif defined __APPLE__\n tlw->Bind(wxEVT_SHOW, [=](wxShowEvent &evt) {\n callback();\n evt.Skip();\n });\n#endif\n}\n\nwxDEFINE_EVENT(EVT_DPI_CHANGED_SLICER, DpiChangedEvent);\n\n#ifdef _WIN32\ntemplate<class F> typename F::FN winapi_get_function(const wchar_t *dll, const char *fn_name) {\n static HINSTANCE dll_handle = LoadLibraryExW(dll, nullptr, 0);\n\n if (dll_handle == nullptr) { return nullptr; }\n return (typename F::FN)GetProcAddress(dll_handle, fn_name);\n}\n#endif\n\n\/\/ If called with nullptr, a DPI for the primary monitor is returned.\nint get_dpi_for_window(wxWindow *window)\n{\n#ifdef _WIN32\n enum MONITOR_DPI_TYPE_ {\n \/\/ This enum is inlined here to avoid build-time dependency\n MDT_EFFECTIVE_DPI_ = 0,\n MDT_ANGULAR_DPI_ = 1,\n MDT_RAW_DPI_ = 2,\n MDT_DEFAULT_ = MDT_EFFECTIVE_DPI_,\n };\n\n \/\/ Need strong types for winapi_get_function() to work\n struct GetDpiForWindow_t { typedef HRESULT (WINAPI *FN)(HWND hwnd); };\n struct GetDpiForMonitor_t { typedef HRESULT (WINAPI *FN)(HMONITOR hmonitor, MONITOR_DPI_TYPE_ dpiType, UINT *dpiX, UINT *dpiY); };\n\n static auto GetDpiForWindow_fn = winapi_get_function<GetDpiForWindow_t>(L\"User32.dll\", \"GetDpiForWindow\");\n static auto GetDpiForMonitor_fn = winapi_get_function<GetDpiForMonitor_t>(L\"Shcore.dll\", \"GetDpiForMonitor\");\n\n\t\/\/ Desktop Window is the window of the primary monitor.\n\tconst HWND hwnd = (window == nullptr) ? ::GetDesktopWindow() : window->GetHandle();\n\n if (GetDpiForWindow_fn != nullptr) {\n \/\/ We're on Windows 10, we have per-screen DPI settings\n return GetDpiForWindow_fn(hwnd);\n } else if (GetDpiForMonitor_fn != nullptr) {\n \/\/ We're on Windows 8.1, we have per-system DPI\n \/\/ Note: MonitorFromWindow() is available on all Windows.\n\n const HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);\n UINT dpiX;\n UINT dpiY;\n return GetDpiForMonitor_fn(monitor, MDT_EFFECTIVE_DPI_, &dpiX, &dpiY) == S_OK ? dpiX : DPI_DEFAULT;\n } else {\n \/\/ We're on Windows earlier than 8.1, use DC\n\n const HDC hdc = GetDC(hwnd);\n if (hdc == NULL) { return DPI_DEFAULT; }\n return GetDeviceCaps(hdc, LOGPIXELSX);\n }\n#elif defined __linux__\n \/\/ TODO\n return DPI_DEFAULT;\n#elif defined __APPLE__\n \/\/ TODO\n return DPI_DEFAULT;\n#endif\n}\n\nwxFont get_default_font_for_dpi(int dpi)\n{\n#ifdef _WIN32\n \/\/ First try to load the font with the Windows 10 specific way.\n struct SystemParametersInfoForDpi_t { typedef BOOL (WINAPI *FN)(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni, UINT dpi); };\n static auto SystemParametersInfoForDpi_fn = winapi_get_function<SystemParametersInfoForDpi_t>(L\"User32.dll\", \"SystemParametersInfoForDpi\");\n if (SystemParametersInfoForDpi_fn != nullptr) {\n NONCLIENTMETRICS nm;\n memset(&nm, 0, sizeof(NONCLIENTMETRICS));\n nm.cbSize = sizeof(NONCLIENTMETRICS);\n\t\tif (SystemParametersInfoForDpi_fn(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nm, 0, dpi)) {\n wxNativeFontInfo info;\n info.lf = nm.lfMessageFont;\n return wxFont(info);\n }\n }\n \/\/ Then try to guesstimate the font DPI scaling on Windows 8.\n \/\/ Let's hope that the font returned by the SystemParametersInfo(), which is used by wxWidgets internally, makes sense.\n int dpi_primary = get_dpi_for_window(nullptr);\n if (dpi_primary != dpi) {\n \/\/ Rescale the font.\n return wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT).Scaled(float(dpi) \/ float(dpi_primary));\n }\n#endif\n return wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n}\n\nCheckboxFileDialog::ExtraPanel::ExtraPanel(wxWindow *parent)\n : wxPanel(parent, wxID_ANY)\n{\n \/\/ WARN: wxMSW does some extra shenanigans to calc the extra control size.\n \/\/ It first calls the create function with a dummy empty wxDialog parent and saves its size.\n \/\/ Afterwards, the create function is called again with the real parent.\n \/\/ Additionally there's no way to pass any extra data to the create function (no closure),\n \/\/ which is why we have to this stuff here. Grrr!\n auto *dlg = dynamic_cast<CheckboxFileDialog*>(parent);\n const wxString checkbox_label(dlg != nullptr ? dlg->checkbox_label : wxString(\"String long enough to contain dlg->checkbox_label\"));\n\n auto* sizer = new wxBoxSizer(wxHORIZONTAL);\n cbox = new wxCheckBox(this, wxID_ANY, checkbox_label);\n cbox->SetValue(true);\n sizer->AddSpacer(5);\n sizer->Add(this->cbox, 0, wxEXPAND | wxALL, 5);\n SetSizer(sizer);\n sizer->SetSizeHints(this);\n}\n\nwxWindow* CheckboxFileDialog::ExtraPanel::ctor(wxWindow *parent) {\n return new ExtraPanel(parent);\n}\n\nCheckboxFileDialog::CheckboxFileDialog(wxWindow *parent,\n const wxString &checkbox_label,\n bool checkbox_value,\n const wxString &message,\n const wxString &default_dir,\n const wxString &default_file,\n const wxString &wildcard,\n long style,\n const wxPoint &pos,\n const wxSize &size,\n const wxString &name\n)\n : wxFileDialog(parent, message, default_dir, default_file, wildcard, style, pos, size, name)\n , checkbox_label(checkbox_label)\n{\n if (checkbox_label.IsEmpty()) {\n return;\n }\n\n SetExtraControlCreator(ExtraPanel::ctor);\n}\n\nbool CheckboxFileDialog::get_checkbox_value() const\n{\n auto *extra_panel = dynamic_cast<ExtraPanel*>(GetExtraControl());\n return extra_panel != nullptr ? extra_panel->cbox->GetValue() : false;\n}\n\n\nWindowMetrics WindowMetrics::from_window(wxTopLevelWindow *window)\n{\n WindowMetrics res;\n res.rect = window->GetScreenRect();\n res.maximized = window->IsMaximized();\n return res;\n}\n\nboost::optional<WindowMetrics> WindowMetrics::deserialize(const std::string &str)\n{\n std::vector<std::string> metrics_str;\n metrics_str.reserve(5);\n\n if (!unescape_strings_cstyle(str, metrics_str) || metrics_str.size() != 5) {\n return boost::none;\n }\n\n int metrics[5];\n try {\n for (size_t i = 0; i < 5; i++) {\n metrics[i] = boost::lexical_cast<int>(metrics_str[i]);\n }\n } catch(const boost::bad_lexical_cast &) {\n return boost::none;\n }\n\n if ((metrics[4] & ~1) != 0) { \/\/ Checks if the maximized flag is 1 or 0\n metrics[4] = 0;\n }\n\n WindowMetrics res;\n res.rect = wxRect(metrics[0], metrics[1], metrics[2], metrics[3]);\n res.maximized = metrics[4] != 0;\n\n return res;\n}\n\nvoid WindowMetrics::sanitize_for_display(const wxRect &screen_rect)\n{\n rect = rect.Intersect(screen_rect);\n\n \/\/ Prevent the window from going too far towards the right and\/or bottom edge\n \/\/ It's hardcoded here that the threshold is 80% of the screen size\n rect.x = std::min(rect.x, screen_rect.x + 4*screen_rect.width\/5);\n rect.y = std::min(rect.y, screen_rect.y + 4*screen_rect.height\/5);\n}\n\nstd::string WindowMetrics::serialize() const\n{\n return (boost::format(\"%1%; %2%; %3%; %4%; %5%\")\n % rect.x\n % rect.y\n % rect.width\n % rect.height\n % static_cast<int>(maximized)\n ).str();\n}\n\nstd::ostream& operator<<(std::ostream &os, const WindowMetrics& metrics)\n{\n return os << '(' << metrics.serialize() << ')';\n}\n\n\n}\n}\n<commit_msg>One more fix for Make compile and works for FreeBSD (#3556)<commit_after>#include \"GUI_Utils.hpp\"\n\n#include <algorithm>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/format.hpp>\n\n#ifdef _WIN32\n#include <Windows.h>\n#endif\n\n#include <wx\/toplevel.h>\n#include <wx\/sizer.h>\n#include <wx\/checkbox.h>\n#include <wx\/dcclient.h>\n#include <wx\/font.h>\n#include <wx\/fontutil.h>\n\n#include \"libslic3r\/Config.hpp\"\n\n\nnamespace Slic3r {\nnamespace GUI {\n\n\nwxTopLevelWindow* find_toplevel_parent(wxWindow *window)\n{\n for (; window != nullptr; window = window->GetParent()) {\n if (window->IsTopLevel()) {\n return dynamic_cast<wxTopLevelWindow*>(window);\n }\n }\n\n return nullptr;\n}\n\nvoid on_window_geometry(wxTopLevelWindow *tlw, std::function<void()> callback)\n{\n#ifdef _WIN32\n \/\/ On windows, the wxEVT_SHOW is not received if the window is created maximized\n \/\/ cf. https:\/\/groups.google.com\/forum\/#!topic\/wx-users\/c7ntMt6piRI\n \/\/ OTOH the geometry is available very soon, so we can call the callback right away\n callback();\n#elif defined __linux__\n tlw->Bind(wxEVT_SHOW, [=](wxShowEvent &evt) {\n \/\/ On Linux, the geometry is only available after wxEVT_SHOW + CallAfter\n \/\/ cf. https:\/\/groups.google.com\/forum\/?pli=1#!topic\/wx-users\/fERSXdpVwAI\n tlw->CallAfter([=]() { callback(); });\n evt.Skip();\n });\n#elif defined __APPLE__\n tlw->Bind(wxEVT_SHOW, [=](wxShowEvent &evt) {\n callback();\n evt.Skip();\n });\n#endif\n}\n\nwxDEFINE_EVENT(EVT_DPI_CHANGED_SLICER, DpiChangedEvent);\n\n#ifdef _WIN32\ntemplate<class F> typename F::FN winapi_get_function(const wchar_t *dll, const char *fn_name) {\n static HINSTANCE dll_handle = LoadLibraryExW(dll, nullptr, 0);\n\n if (dll_handle == nullptr) { return nullptr; }\n return (typename F::FN)GetProcAddress(dll_handle, fn_name);\n}\n#endif\n\n\/\/ If called with nullptr, a DPI for the primary monitor is returned.\nint get_dpi_for_window(wxWindow *window)\n{\n#ifdef _WIN32\n enum MONITOR_DPI_TYPE_ {\n \/\/ This enum is inlined here to avoid build-time dependency\n MDT_EFFECTIVE_DPI_ = 0,\n MDT_ANGULAR_DPI_ = 1,\n MDT_RAW_DPI_ = 2,\n MDT_DEFAULT_ = MDT_EFFECTIVE_DPI_,\n };\n\n \/\/ Need strong types for winapi_get_function() to work\n struct GetDpiForWindow_t { typedef HRESULT (WINAPI *FN)(HWND hwnd); };\n struct GetDpiForMonitor_t { typedef HRESULT (WINAPI *FN)(HMONITOR hmonitor, MONITOR_DPI_TYPE_ dpiType, UINT *dpiX, UINT *dpiY); };\n\n static auto GetDpiForWindow_fn = winapi_get_function<GetDpiForWindow_t>(L\"User32.dll\", \"GetDpiForWindow\");\n static auto GetDpiForMonitor_fn = winapi_get_function<GetDpiForMonitor_t>(L\"Shcore.dll\", \"GetDpiForMonitor\");\n\n\t\/\/ Desktop Window is the window of the primary monitor.\n\tconst HWND hwnd = (window == nullptr) ? ::GetDesktopWindow() : window->GetHandle();\n\n if (GetDpiForWindow_fn != nullptr) {\n \/\/ We're on Windows 10, we have per-screen DPI settings\n return GetDpiForWindow_fn(hwnd);\n } else if (GetDpiForMonitor_fn != nullptr) {\n \/\/ We're on Windows 8.1, we have per-system DPI\n \/\/ Note: MonitorFromWindow() is available on all Windows.\n\n const HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);\n UINT dpiX;\n UINT dpiY;\n return GetDpiForMonitor_fn(monitor, MDT_EFFECTIVE_DPI_, &dpiX, &dpiY) == S_OK ? dpiX : DPI_DEFAULT;\n } else {\n \/\/ We're on Windows earlier than 8.1, use DC\n\n const HDC hdc = GetDC(hwnd);\n if (hdc == NULL) { return DPI_DEFAULT; }\n return GetDeviceCaps(hdc, LOGPIXELSX);\n }\n#elif defined __linux__\n \/\/ TODO\n return DPI_DEFAULT;\n#elif defined __APPLE__\n \/\/ TODO\n return DPI_DEFAULT;\n#else \/\/ freebsd and others\n \/\/ TODO\n return DPI_DEFAULT;\n#endif\n}\n\nwxFont get_default_font_for_dpi(int dpi)\n{\n#ifdef _WIN32\n \/\/ First try to load the font with the Windows 10 specific way.\n struct SystemParametersInfoForDpi_t { typedef BOOL (WINAPI *FN)(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni, UINT dpi); };\n static auto SystemParametersInfoForDpi_fn = winapi_get_function<SystemParametersInfoForDpi_t>(L\"User32.dll\", \"SystemParametersInfoForDpi\");\n if (SystemParametersInfoForDpi_fn != nullptr) {\n NONCLIENTMETRICS nm;\n memset(&nm, 0, sizeof(NONCLIENTMETRICS));\n nm.cbSize = sizeof(NONCLIENTMETRICS);\n\t\tif (SystemParametersInfoForDpi_fn(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nm, 0, dpi)) {\n wxNativeFontInfo info;\n info.lf = nm.lfMessageFont;\n return wxFont(info);\n }\n }\n \/\/ Then try to guesstimate the font DPI scaling on Windows 8.\n \/\/ Let's hope that the font returned by the SystemParametersInfo(), which is used by wxWidgets internally, makes sense.\n int dpi_primary = get_dpi_for_window(nullptr);\n if (dpi_primary != dpi) {\n \/\/ Rescale the font.\n return wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT).Scaled(float(dpi) \/ float(dpi_primary));\n }\n#endif\n return wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n}\n\nCheckboxFileDialog::ExtraPanel::ExtraPanel(wxWindow *parent)\n : wxPanel(parent, wxID_ANY)\n{\n \/\/ WARN: wxMSW does some extra shenanigans to calc the extra control size.\n \/\/ It first calls the create function with a dummy empty wxDialog parent and saves its size.\n \/\/ Afterwards, the create function is called again with the real parent.\n \/\/ Additionally there's no way to pass any extra data to the create function (no closure),\n \/\/ which is why we have to this stuff here. Grrr!\n auto *dlg = dynamic_cast<CheckboxFileDialog*>(parent);\n const wxString checkbox_label(dlg != nullptr ? dlg->checkbox_label : wxString(\"String long enough to contain dlg->checkbox_label\"));\n\n auto* sizer = new wxBoxSizer(wxHORIZONTAL);\n cbox = new wxCheckBox(this, wxID_ANY, checkbox_label);\n cbox->SetValue(true);\n sizer->AddSpacer(5);\n sizer->Add(this->cbox, 0, wxEXPAND | wxALL, 5);\n SetSizer(sizer);\n sizer->SetSizeHints(this);\n}\n\nwxWindow* CheckboxFileDialog::ExtraPanel::ctor(wxWindow *parent) {\n return new ExtraPanel(parent);\n}\n\nCheckboxFileDialog::CheckboxFileDialog(wxWindow *parent,\n const wxString &checkbox_label,\n bool checkbox_value,\n const wxString &message,\n const wxString &default_dir,\n const wxString &default_file,\n const wxString &wildcard,\n long style,\n const wxPoint &pos,\n const wxSize &size,\n const wxString &name\n)\n : wxFileDialog(parent, message, default_dir, default_file, wildcard, style, pos, size, name)\n , checkbox_label(checkbox_label)\n{\n if (checkbox_label.IsEmpty()) {\n return;\n }\n\n SetExtraControlCreator(ExtraPanel::ctor);\n}\n\nbool CheckboxFileDialog::get_checkbox_value() const\n{\n auto *extra_panel = dynamic_cast<ExtraPanel*>(GetExtraControl());\n return extra_panel != nullptr ? extra_panel->cbox->GetValue() : false;\n}\n\n\nWindowMetrics WindowMetrics::from_window(wxTopLevelWindow *window)\n{\n WindowMetrics res;\n res.rect = window->GetScreenRect();\n res.maximized = window->IsMaximized();\n return res;\n}\n\nboost::optional<WindowMetrics> WindowMetrics::deserialize(const std::string &str)\n{\n std::vector<std::string> metrics_str;\n metrics_str.reserve(5);\n\n if (!unescape_strings_cstyle(str, metrics_str) || metrics_str.size() != 5) {\n return boost::none;\n }\n\n int metrics[5];\n try {\n for (size_t i = 0; i < 5; i++) {\n metrics[i] = boost::lexical_cast<int>(metrics_str[i]);\n }\n } catch(const boost::bad_lexical_cast &) {\n return boost::none;\n }\n\n if ((metrics[4] & ~1) != 0) { \/\/ Checks if the maximized flag is 1 or 0\n metrics[4] = 0;\n }\n\n WindowMetrics res;\n res.rect = wxRect(metrics[0], metrics[1], metrics[2], metrics[3]);\n res.maximized = metrics[4] != 0;\n\n return res;\n}\n\nvoid WindowMetrics::sanitize_for_display(const wxRect &screen_rect)\n{\n rect = rect.Intersect(screen_rect);\n\n \/\/ Prevent the window from going too far towards the right and\/or bottom edge\n \/\/ It's hardcoded here that the threshold is 80% of the screen size\n rect.x = std::min(rect.x, screen_rect.x + 4*screen_rect.width\/5);\n rect.y = std::min(rect.y, screen_rect.y + 4*screen_rect.height\/5);\n}\n\nstd::string WindowMetrics::serialize() const\n{\n return (boost::format(\"%1%; %2%; %3%; %4%; %5%\")\n % rect.x\n % rect.y\n % rect.width\n % rect.height\n % static_cast<int>(maximized)\n ).str();\n}\n\nstd::ostream& operator<<(std::ostream &os, const WindowMetrics& metrics)\n{\n return os << '(' << metrics.serialize() << ')';\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TextInputWidget.hpp\"\n#include <iostream>\n\ngsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)\n: ChildWidget{ width, height }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_minBreakCharCnt{ 0 }\n{\n std::unique_ptr<TextWidget> text{ \n std::make_unique<TextWidget>(\"\", font, m_charSize, sf::Color::Black) };\n std::unique_ptr<ScrollableWidget> scrollabe{ \n std::make_unique<ScrollableWidget>(width, height) };\n m_scrollable = scrollabe.get();\n m_text = text.get();\n scrollabe->setBackgroundColor(sf::Color::Transparent);\n scrollabe->attachChild(std::move(text));\n \/\/attachChild(std::move(text));\n attachChild(std::move(scrollabe));\n m_cursor.setFillColor(sf::Color::Black);\n}\n\nvoid gsf::TextInputWidget::setIsEditable(bool isEditable)\n{\n m_isEditable = isEditable;\n}\n\nbool gsf::TextInputWidget::isEditable() const\n{\n return m_isEditable;\n}\n\nvoid gsf::TextInputWidget::setText(const std::wstring &text)\n{\n m_currentText = text;\n m_text->setText(m_currentText);\n \/\/ Move cursor to end of text\n m_cursorPos = m_currentText.size();\n \/\/ Adjust text so that it fits the scrollbar when horizontal scrolling is disabled\n adjustShownText();\n m_scrollable->recalculateScroll();\n m_scrollable->scrollToBottom();\n}\n\nstd::wstring gsf::TextInputWidget::getText() const\n{\n \/\/return m_text->getText().toWideString();\n return m_currentText;\n}\n\nvoid gsf::TextInputWidget::setCharacterSize(const unsigned int size)\n{\n m_text->setCharacterSize(size);\n m_charSize = size;\n m_cursor.setCharacterSize(size);\n}\n\nunsigned int gsf::TextInputWidget::getCharacterSize() const\n{\n return m_charSize;\n}\n\nvoid gsf::TextInputWidget::setTextColor(const sf::Color color)\n{\n m_text->setTextColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getTextColor() const\n{\n return m_text->getTextColor();\n}\n\nvoid gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted)\n{\n m_acceptNewLines = isAccepted;\n}\n\nbool gsf::TextInputWidget::getIsNewLineAccepted() const\n{\n return m_acceptNewLines;\n}\n\nbool gsf::TextInputWidget::isFocused() const\n{\n return m_isFocused;\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)\n{\n m_scrollable->setIsVerticalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isVerticalScrollEnabled() const\n{\n return m_scrollable->isVerticalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)\n{\n m_scrollable->setIsHorizontalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isHorizontalScrollEnabled() const\n{\n return m_scrollable->isHorizontalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn)\n{\n m_scrollable->setIsVerticalScrollbarDrawn(isDrawn);\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn)\n{\n m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn);\n}\nvoid gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target, \n sf::RenderStates states) const\n{\n\n}\n\nvoid gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n sf::RenderStates states) const\n{ \n \/\/ Draw cursor after children, so that children are not drawn over cursor\n if (m_isCursorShown && m_isEditable)\n {\n target.draw(m_cursor, states);\n }\n}\n\nvoid gsf::TextInputWidget::updateCurrent(float dt)\n{\n if (!m_isEditable)\n {\n \/\/ Nothing to do\n return;\n }\n \n \/\/ Update cursor stuff\n m_lastBlinkTime += dt;\n if (m_lastBlinkTime >= m_blinkFreq)\n {\n m_isCursorShown = !m_isCursorShown;\n m_lastBlinkTime = 0.f;\n }\n\n m_cursor.setPosition(m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur));\n \/\/std::wstring text{ m_currentText };\n \/\/std::wstring text{ m_shownText };\n \/\/m_text->setText(text); \n}\n\nbool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)\n{\n if (!m_isEditable)\n {\n \/\/ Nothing to do\n return false;\n }\n \/\/bool handled{ ChildWidget::handleEvent(event) };\/*|| \n \/\/ m_scrollable->handleEventWidget(event) };*\/\n \/\/ Check if actual Widget is focused\n if (event.type == sf::Event::MouseButtonPressed)\n { \n sf::Vector2f mousePos{ (float) event.mouseButton.x, \n (float) event.mouseButton.y };\n \n \/\/sf::Vector2f localPos{ mousePos.x - getWorldPosition().x,\n \/\/ mousePos.y - getWorldPosition().y };\n \/\/std::cout << \"pressed on: \" << findIndexOfCharOnPos(localPos);\n\n bool isMouseInShownArea{ getShownArea().contains(mousePos) };\n bool intersecting{ isIntersecting(mousePos) };\n if (isMouseInShownArea && intersecting)\n {\n m_isFocused = true;\n }\n else\n {\n m_isFocused = false;\n }\n }\n if (event.type == sf::Event::KeyPressed && m_isFocused)\n {\n switch (event.key.code)\n {\n case sf::Keyboard::Left:\n if (m_cursorPos > 0)\n {\n m_cursorPos--;\n }\n \/\/ when cursor is moved it should be drawn so we reset its status\n resetCursorStatus();\n adjustShownText();\n \/\/m_cursor.setPosition(\n \/\/ m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n return true;\n case sf::Keyboard::Right: \n if (m_cursorPos < m_currentText.length())\n {\n m_cursorPos++;\n }\n resetCursorStatus();\n adjustShownText();\n \/\/m_cursor.setPosition\n \/\/ (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n return true;\n default: break;\n }\n }\n \/\/ If Widget is focused and Text entered, handle entered text\n if (m_isFocused && event.type == sf::Event::TextEntered)\n {\n \/\/ To handle umlauts and other 'exotic' chars we use widestring\n \/\/ and wide char\n \/\/std::wstring actualTxt{ m_text.getString().toWideString() };\n wchar_t c{ static_cast<wchar_t>(event.text.unicode) };\n std::cout << \"Entered: \" << c << std::endl;\n switch (c)\n {\n \/\/ Backspace\n case 8: \n if (m_currentText.length() > 0) \n {\n \/\/ Remove chars right of cursor when there are chars\n if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())\n {\n m_currentText.erase(m_cursorPos - 1, 1);\n m_cursorPos--;\n }\n \/\/ When cursos is at the end of the text, p\n \/\/ place cursor behind char which we want to delete,\n else if (m_cursorPos == m_currentText.length())\n {\n \/\/ Delete last char\n m_currentText.pop_back();\n m_cursorPos--;\n }\n }\n break;\n \/\/ Delete Pressed\n case 127: \n if (m_currentText.length() > 0 && \n m_cursorPos < m_currentText.length())\n {\n m_currentText.erase(m_cursorPos, 1);\n }\n break;\n \/\/ Enter key\n case 13: \n \/\/ Dont add new line, when new lines are not accepted\n if (!m_acceptNewLines)\n {\n return false;\n }\n m_currentText.insert(m_cursorPos, L\"\\n\"); m_cursorPos++; \n break;\n \/\/ Add char to text\n default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;\n }\n resetCursorStatus();\n m_shownText = m_currentText;\n m_text->setText(m_shownText);\n adjustShownText();\n \/\/m_cursor.setPosition\n \/\/(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n m_scrollable->recalculateScroll();\n m_scrollable->scrollToRight();\n m_scrollable->scrollToBottom();\n return true;\n }\n return false;\n \/\/return handled;\n}\n\nvoid gsf::TextInputWidget::adjustShownText()\n{\n if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0)\n {\n m_lBreaksBefCur = 0;\n std::wstring shownString{ L\"\" };\n \/\/ The chars which are in the actual line\n unsigned int charCntLine{ 0 };\n \/\/ The total width of all chars in the current line\n float lineWidth{ 0.f };\n for (unsigned int i{ 0 }; i < m_currentText.size(); i++)\n {\n wchar_t c{ m_currentText[i] };\n \/\/ Width of the current char\n float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; \n lineWidth += cWidth;\n \/\/ When Text is out of scrollable widget, we have to add a new line \n if (lineWidth > m_scrollable->getWidth())\n {\n if (i < m_cursorPos)\n {\n \/\/ We have to increase the \"line breaks befor cursor\" counter\n \/\/ so we add the cursor later on the right position\n m_lBreaksBefCur++;\n }\n \/\/shownString += m_currentText.substr(i - charCntLine, charCntLine);\n \/\/ Add new line\n shownString += L\"\\n\";\n \/\/ add the char with which the line was to wide in the new line\n shownString += c;\n \/\/ We have added the char c in the new line, \n \/\/ so we have now 1 char in the current line\n charCntLine = 1;\n lineWidth = cWidth;\n }\n else\n {\n charCntLine++;\n shownString += c;\n }\n }\n m_shownText = shownString;\n m_text->setText(m_shownText);\n }\n}\n\n\/\/ Use binary search to get the right position\nint gsf::TextInputWidget::findIndexOfCharOnPos(sf::Vector2f localPos) const\n{\n return findCharOnPosBinary(localPos, 0, m_text->getWideText().size() - 1);\n}\n\nint gsf::TextInputWidget::findCharOnPosBinary(sf::Vector2f localPos, std::size_t l, \n std::size_t r) const\n{\n \/\/ Nothing found\n if (r <= l)\n {\n return -1;\n }\n \/\/ Get center as index\n \/\/std::size_t i{ static_cast<std::size_t>( (r - l) \/ 2 )};\n int i = (r - l) \/ 2;\n std::cout << \"Index: \" << i << std::endl;\n sf::FloatRect cRect{ m_text->getLocalBoundsOfChar(i) };\n \n \/\/ ++++++++\n \/\/ ++++c---\n \/\/ --------\n \/\/ \n \/\/ c : index of i\n \/\/ + : left of i\n \/\/ - : right of i\n \n \/\/ Found char (case c)\n if (cRect.contains(localPos))\n {\n return i;\n }\n \/\/ Left of i (case +)\n if ( (localPos.x < cRect.left && localPos.y <= cRect.top + cRect.height) ||\n (localPos.x > cRect.left && localPos.y < cRect.top) )\n {\n return findCharOnPosBinary(localPos, l, i - 1);\n }\n \/\/ Right of i (case -)\n else\n {\n return findCharOnPosBinary(localPos, i + 1, r);\n }\n}\n\nvoid gsf::TextInputWidget::resetCursorStatus()\n{\n m_lastBlinkTime = 0.f;\n m_isCursorShown = true;\n}\n<commit_msg>Better adjusting of the text in TextInputWidget<commit_after>#include \"TextInputWidget.hpp\"\n#include <iostream>\n\ngsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)\n: ChildWidget{ width, height }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_minBreakCharCnt{ 0 }\n{\n std::unique_ptr<TextWidget> text{ \n std::make_unique<TextWidget>(\"\", font, m_charSize, sf::Color::Black) };\n std::unique_ptr<ScrollableWidget> scrollabe{ \n std::make_unique<ScrollableWidget>(width, height) };\n m_scrollable = scrollabe.get();\n m_text = text.get();\n scrollabe->setBackgroundColor(sf::Color::Transparent);\n scrollabe->attachChild(std::move(text));\n \/\/attachChild(std::move(text));\n attachChild(std::move(scrollabe));\n m_cursor.setFillColor(sf::Color::Black);\n}\n\nvoid gsf::TextInputWidget::setIsEditable(bool isEditable)\n{\n m_isEditable = isEditable;\n}\n\nbool gsf::TextInputWidget::isEditable() const\n{\n return m_isEditable;\n}\n\nvoid gsf::TextInputWidget::setText(const std::wstring &text)\n{\n m_currentText = text;\n m_text->setText(m_currentText);\n \/\/ Move cursor to end of text\n m_cursorPos = m_currentText.size();\n \/\/ Adjust text so that it fits the scrollbar when horizontal scrolling is disabled\n adjustShownText();\n m_scrollable->recalculateScroll();\n m_scrollable->scrollToBottom();\n}\n\nstd::wstring gsf::TextInputWidget::getText() const\n{\n \/\/return m_text->getText().toWideString();\n return m_currentText;\n}\n\nvoid gsf::TextInputWidget::setCharacterSize(const unsigned int size)\n{\n m_text->setCharacterSize(size);\n m_charSize = size;\n m_cursor.setCharacterSize(size);\n}\n\nunsigned int gsf::TextInputWidget::getCharacterSize() const\n{\n return m_charSize;\n}\n\nvoid gsf::TextInputWidget::setTextColor(const sf::Color color)\n{\n m_text->setTextColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getTextColor() const\n{\n return m_text->getTextColor();\n}\n\nvoid gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted)\n{\n m_acceptNewLines = isAccepted;\n}\n\nbool gsf::TextInputWidget::getIsNewLineAccepted() const\n{\n return m_acceptNewLines;\n}\n\nbool gsf::TextInputWidget::isFocused() const\n{\n return m_isFocused;\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)\n{\n m_scrollable->setIsVerticalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isVerticalScrollEnabled() const\n{\n return m_scrollable->isVerticalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)\n{\n m_scrollable->setIsHorizontalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isHorizontalScrollEnabled() const\n{\n return m_scrollable->isHorizontalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn)\n{\n m_scrollable->setIsVerticalScrollbarDrawn(isDrawn);\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn)\n{\n m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn);\n}\nvoid gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target, \n sf::RenderStates states) const\n{\n\n}\n\nvoid gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n sf::RenderStates states) const\n{ \n \/\/ Draw cursor after children, so that children are not drawn over cursor\n if (m_isCursorShown && m_isEditable)\n {\n target.draw(m_cursor, states);\n }\n}\n\nvoid gsf::TextInputWidget::updateCurrent(float dt)\n{\n if (!m_isEditable)\n {\n \/\/ Nothing to do\n return;\n }\n \n \/\/ Update cursor stuff\n m_lastBlinkTime += dt;\n if (m_lastBlinkTime >= m_blinkFreq)\n {\n m_isCursorShown = !m_isCursorShown;\n m_lastBlinkTime = 0.f;\n }\n\n m_cursor.setPosition(m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur));\n \/\/std::wstring text{ m_currentText };\n \/\/std::wstring text{ m_shownText };\n \/\/m_text->setText(text); \n}\n\nbool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)\n{\n if (!m_isEditable)\n {\n \/\/ Nothing to do\n return false;\n }\n \/\/bool handled{ ChildWidget::handleEvent(event) };\/*|| \n \/\/ m_scrollable->handleEventWidget(event) };*\/\n \/\/ Check if actual Widget is focused\n if (event.type == sf::Event::MouseButtonPressed)\n { \n sf::Vector2f mousePos{ (float) event.mouseButton.x, \n (float) event.mouseButton.y };\n \n \/\/sf::Vector2f localPos{ mousePos.x - getWorldPosition().x,\n \/\/ mousePos.y - getWorldPosition().y };\n \/\/std::cout << \"pressed on: \" << findIndexOfCharOnPos(localPos);\n\n bool isMouseInShownArea{ getShownArea().contains(mousePos) };\n bool intersecting{ isIntersecting(mousePos) };\n if (isMouseInShownArea && intersecting)\n {\n m_isFocused = true;\n }\n else\n {\n m_isFocused = false;\n }\n }\n if (event.type == sf::Event::KeyPressed && m_isFocused)\n {\n switch (event.key.code)\n {\n case sf::Keyboard::Left:\n if (m_cursorPos > 0)\n {\n m_cursorPos--;\n }\n \/\/ when cursor is moved it should be drawn so we reset its status\n resetCursorStatus();\n adjustShownText();\n \/\/m_cursor.setPosition(\n \/\/ m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n return true;\n case sf::Keyboard::Right: \n if (m_cursorPos < m_currentText.length())\n {\n m_cursorPos++;\n }\n resetCursorStatus();\n adjustShownText();\n \/\/m_cursor.setPosition\n \/\/ (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n return true;\n default: break;\n }\n }\n \/\/ If Widget is focused and Text entered, handle entered text\n if (m_isFocused && event.type == sf::Event::TextEntered)\n {\n \/\/ To handle umlauts and other 'exotic' chars we use widestring\n \/\/ and wide char\n \/\/std::wstring actualTxt{ m_text.getString().toWideString() };\n wchar_t c{ static_cast<wchar_t>(event.text.unicode) };\n std::cout << \"Entered: \" << c << std::endl;\n switch (c)\n {\n \/\/ Backspace\n case 8: \n if (m_currentText.length() > 0) \n {\n \/\/ Remove chars right of cursor when there are chars\n if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())\n {\n m_currentText.erase(m_cursorPos - 1, 1);\n m_cursorPos--;\n }\n \/\/ When cursos is at the end of the text, p\n \/\/ place cursor behind char which we want to delete,\n else if (m_cursorPos == m_currentText.length())\n {\n \/\/ Delete last char\n m_currentText.pop_back();\n m_cursorPos--;\n }\n }\n break;\n \/\/ Delete Pressed\n case 127: \n if (m_currentText.length() > 0 && \n m_cursorPos < m_currentText.length())\n {\n m_currentText.erase(m_cursorPos, 1);\n }\n break;\n \/\/ Enter key\n case 13: \n \/\/ Dont add new line, when new lines are not accepted\n if (!m_acceptNewLines)\n {\n return false;\n }\n m_currentText.insert(m_cursorPos, L\"\\n\"); m_cursorPos++; \n break;\n \/\/ Add char to text\n default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;\n }\n resetCursorStatus();\n m_shownText = m_currentText;\n m_text->setText(m_shownText);\n adjustShownText();\n \/\/m_cursor.setPosition\n \/\/(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n m_scrollable->recalculateScroll();\n m_scrollable->scrollToRight();\n m_scrollable->scrollToBottom();\n return true;\n }\n return false;\n \/\/return handled;\n}\n\nvoid gsf::TextInputWidget::adjustShownText()\n{\n if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0)\n {\n m_lBreaksBefCur = 0;\n std::wstring shownString{ L\"\" };\n \/\/ The chars which are in the actual line\n unsigned int charCntLine{ 0 };\n \/\/ The total width of all chars in the current line\n float lineWidth{ 0.f };\n for (unsigned int i{ 0 }; i < m_currentText.size(); i++)\n {\n wchar_t c{ m_currentText[i] };\n \/\/ If we have a new line as char we can set the lineWidth and charCntLine\n \/\/ to 0 because there is no need to handle the chars in this line\n \/\/ (It is already handled by user width the new line char)\n if (c == '\\n')\n {\n lineWidth = 0.f;\n charCntLine = 0;\n shownString += c;\n continue;\n }\n \/\/ Width of the current char\n float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; \n lineWidth += cWidth;\n \/\/ When Text is out of scrollable widget, we have to add a new line \n if (lineWidth > m_scrollable->getWidth())\n {\n if (i < m_cursorPos)\n {\n \/\/ We have to increase the \"line breaks befor cursor\" counter\n \/\/ so we add the cursor later on the right position\n m_lBreaksBefCur++;\n }\n \/\/shownString += m_currentText.substr(i - charCntLine, charCntLine);\n \/\/ Add new line\n shownString += L\"\\n\";\n \/\/ add the char with which the line was to wide in the new line\n shownString += c;\n \/\/ We have added the char c in the new line, \n \/\/ so we have now 1 char in the current line\n charCntLine = 1;\n lineWidth = cWidth;\n }\n else\n {\n charCntLine++;\n shownString += c;\n }\n }\n m_shownText = shownString;\n m_text->setText(m_shownText);\n }\n}\n\n\/\/ Use binary search to get the right position\nint gsf::TextInputWidget::findIndexOfCharOnPos(sf::Vector2f localPos) const\n{\n return findCharOnPosBinary(localPos, 0, m_text->getWideText().size() - 1);\n}\n\nint gsf::TextInputWidget::findCharOnPosBinary(sf::Vector2f localPos, std::size_t l, \n std::size_t r) const\n{\n \/\/ Nothing found\n if (r <= l)\n {\n return -1;\n }\n \/\/ Get center as index\n \/\/std::size_t i{ static_cast<std::size_t>( (r - l) \/ 2 )};\n int i = (r - l) \/ 2;\n std::cout << \"Index: \" << i << std::endl;\n sf::FloatRect cRect{ m_text->getLocalBoundsOfChar(i) };\n \n \/\/ ++++++++\n \/\/ ++++c---\n \/\/ --------\n \/\/ \n \/\/ c : index of i\n \/\/ + : left of i\n \/\/ - : right of i\n \n \/\/ Found char (case c)\n if (cRect.contains(localPos))\n {\n return i;\n }\n \/\/ Left of i (case +)\n if ( (localPos.x < cRect.left && localPos.y <= cRect.top + cRect.height) ||\n (localPos.x > cRect.left && localPos.y < cRect.top) )\n {\n return findCharOnPosBinary(localPos, l, i - 1);\n }\n \/\/ Right of i (case -)\n else\n {\n return findCharOnPosBinary(localPos, i + 1, r);\n }\n}\n\nvoid gsf::TextInputWidget::resetCursorStatus()\n{\n m_lastBlinkTime = 0.f;\n m_isCursorShown = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gtest\/gtest.h>\n\n#include <string>\n\n#include <SurgSim\/Physics\/FixedRepresentation.h>\nusing SurgSim::Physics::Representation;\nusing SurgSim::Physics::FixedRepresentation;\n\n#include <SurgSim\/Math\/Vector.h>\n#include <SurgSim\/Math\/Quaternion.h>\n#include <SurgSim\/Math\/RigidTransform.h>\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\n\nclass FixedRepresentationTest : public ::testing::Test\n{\npublic:\n\tvoid SetUp()\n\t{\n\t\tQuaterniond q;\n\t\tVector3d t;\n\n\t\tq.coeffs().setRandom();\n\t\tq.normalize();\n\t\tt.setRandom();\n\t\tm_initialTransformation = SurgSim::Math::makeRigidTransform(q, t);\n\n\t\tdo\n\t\t{\n\t\t\tq.coeffs().setRandom();\n\t\t\tq.normalize();\n\t\t\tt.setRandom();\n\t\t\tm_currentTransformation = SurgSim::Math::makeRigidTransform(q, t);\n\t\t} while (m_initialTransformation.isApprox(m_currentTransformation));\n\n\t\tm_identityTransformation.setIdentity();\n\t}\n\n\tvoid TearDown()\n\t{\n\t}\n\n\t\/\/ Fixed representation initialization pose\n\tRigidTransform3d m_initialTransformation;\n\n\t\/\/ Fixed representation current pose\n\tRigidTransform3d m_currentTransformation;\n\n\t\/\/ Identity pose (no translation\/rotation)\n\tRigidTransform3d m_identityTransformation;\n};\n\nTEST_F(FixedRepresentationTest, ConstructorTest)\n{\n\tASSERT_NO_THROW( {FixedRepresentation fixedRepresentation(\"FixedRepresentation\");});\n}\n\nTEST_F(FixedRepresentationTest, ResetStateTest)\n{\n\t\/\/ Create the rigid body\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\tfixedRepresentation->setIsActive(false);\n\tfixedRepresentation->setIsGravityEnabled(false);\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\t\/\/ Initial = Current = Previous = Final = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getInitialPose().isApprox(m_initialTransformation));\n\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\t\/\/ setCurrent is supposed to backup current in previous and set current\n\t\/\/ Therefore it should not affect initial nor final\n\t\/\/ Initial = Final = Previous = m_initialTransformation\n\t\/\/ Current = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getFinalPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\t\/\/ setCurrent is supposed to backup current in previous and set current\n\t\/\/ Therefore it should not affect initial nor final\n\t\/\/ Initial = Final = m_initialTransformation\n\t\/\/ Previous = Current = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_FALSE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_FALSE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getFinalPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tfixedRepresentation->afterUpdate(1.0);\n\t\/\/ afterUpdate simply backs up the current into the final\n\t\/\/ Initial = m_initialTransformation\n\t\/\/ Previous = Current = Final = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tstd::shared_ptr<Representation> representation = fixedRepresentation;\n\t\/\/ reset the representation (NOT THE FIXED ACTOR, test polymorphism)\n\trepresentation->resetState();\n\n\t\/\/ isActive flag unchanged\n\tEXPECT_FALSE(fixedRepresentation->isActive());\n\t\/\/ isGravityEnable flag unchanged\n\tEXPECT_FALSE(fixedRepresentation->isGravityEnabled());\n\t\/\/ The current rigid state should be exactly the initial rigid state\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getInitialPose().isApprox(m_initialTransformation));\n\t\/\/ The previous rigid state should be exactly the initial rigid state\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(m_initialTransformation));\n}\n\nTEST_F(FixedRepresentationTest, SetGetAndDefaultValueTest)\n{\n\t\/\/ Create the fixed representation\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\t\/\/ Get\/Set active flag [default = true]\n\tEXPECT_TRUE(fixedRepresentation->isActive());\n\tfixedRepresentation->setIsActive(false);\n\tASSERT_FALSE(fixedRepresentation->isActive());\n\tfixedRepresentation->setIsActive(true);\n\tASSERT_TRUE(fixedRepresentation->isActive());\n\n\t\/\/ Get numDof = 0\n\tASSERT_EQ(0u, fixedRepresentation->getNumDof());\n\n\t\/\/ Set\/Get isGravityEnabled [default = true]\n\tEXPECT_TRUE(fixedRepresentation->isGravityEnabled());\n\tfixedRepresentation->setIsGravityEnabled(false);\n\tASSERT_FALSE(fixedRepresentation->isGravityEnabled());\n\tfixedRepresentation->setIsGravityEnabled(true);\n\tASSERT_TRUE(fixedRepresentation->isGravityEnabled());\n\n\t\/\/ Set\/Get current pose [default = no translation, no rotation]\n\tEXPECT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\tfixedRepresentation->afterUpdate(1.0); \/\/ afterUpdate backs up current into final\n\tASSERT_TRUE(m_currentTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\tfixedRepresentation->setCurrentPose(m_identityTransformation);\n\tfixedRepresentation->afterUpdate(1.0); \/\/ afterUpdate backs up current into final\n\tASSERT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\n\t\/\/ Set\/Get initial pose [default = no translation, no rotation]\n\tEXPECT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getInitialPose()));\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\tASSERT_TRUE(m_initialTransformation.isApprox(fixedRepresentation->getInitialPose()));\n\tfixedRepresentation->setInitialPose(m_identityTransformation);\n\tASSERT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getInitialPose()));\n}\n\nTEST_F(FixedRepresentationTest, UpdateTest)\n{\n\t\/\/ Create the fixed representation\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\tdouble dt = 1.0;\n\n\t\/\/ Sets Initial state and reset all other state with initial state\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\t\/\/ Backs up current state into previous state and set the current\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\n\t\/\/ Does not do anything\n\tfixedRepresentation->beforeUpdate(dt);\n\t\/\/ Does not do anything\n\tfixedRepresentation->update(dt);\n\t\/\/ Backs up current state into final state\n\tfixedRepresentation->afterUpdate(dt);\n\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getPreviousPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n}\n<commit_msg>One last ACTOR to REPRESENTATION rename.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gtest\/gtest.h>\n\n#include <string>\n\n#include <SurgSim\/Physics\/FixedRepresentation.h>\nusing SurgSim::Physics::Representation;\nusing SurgSim::Physics::FixedRepresentation;\n\n#include <SurgSim\/Math\/Vector.h>\n#include <SurgSim\/Math\/Quaternion.h>\n#include <SurgSim\/Math\/RigidTransform.h>\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\n\nclass FixedRepresentationTest : public ::testing::Test\n{\npublic:\n\tvoid SetUp()\n\t{\n\t\tQuaterniond q;\n\t\tVector3d t;\n\n\t\tq.coeffs().setRandom();\n\t\tq.normalize();\n\t\tt.setRandom();\n\t\tm_initialTransformation = SurgSim::Math::makeRigidTransform(q, t);\n\n\t\tdo\n\t\t{\n\t\t\tq.coeffs().setRandom();\n\t\t\tq.normalize();\n\t\t\tt.setRandom();\n\t\t\tm_currentTransformation = SurgSim::Math::makeRigidTransform(q, t);\n\t\t} while (m_initialTransformation.isApprox(m_currentTransformation));\n\n\t\tm_identityTransformation.setIdentity();\n\t}\n\n\tvoid TearDown()\n\t{\n\t}\n\n\t\/\/ Fixed representation initialization pose\n\tRigidTransform3d m_initialTransformation;\n\n\t\/\/ Fixed representation current pose\n\tRigidTransform3d m_currentTransformation;\n\n\t\/\/ Identity pose (no translation\/rotation)\n\tRigidTransform3d m_identityTransformation;\n};\n\nTEST_F(FixedRepresentationTest, ConstructorTest)\n{\n\tASSERT_NO_THROW( {FixedRepresentation fixedRepresentation(\"FixedRepresentation\");});\n}\n\nTEST_F(FixedRepresentationTest, ResetStateTest)\n{\n\t\/\/ Create the rigid body\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\tfixedRepresentation->setIsActive(false);\n\tfixedRepresentation->setIsGravityEnabled(false);\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\t\/\/ Initial = Current = Previous = Final = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getInitialPose().isApprox(m_initialTransformation));\n\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\t\/\/ setCurrent is supposed to backup current in previous and set current\n\t\/\/ Therefore it should not affect initial nor final\n\t\/\/ Initial = Final = Previous = m_initialTransformation\n\t\/\/ Current = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getFinalPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\t\/\/ setCurrent is supposed to backup current in previous and set current\n\t\/\/ Therefore it should not affect initial nor final\n\t\/\/ Initial = Final = m_initialTransformation\n\t\/\/ Previous = Current = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_FALSE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_FALSE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getFinalPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tfixedRepresentation->afterUpdate(1.0);\n\t\/\/ afterUpdate simply backs up the current into the final\n\t\/\/ Initial = m_initialTransformation\n\t\/\/ Previous = Current = Final = m_initialTransformation\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_currentTransformation));\n\n\tstd::shared_ptr<Representation> representation = fixedRepresentation;\n\t\/\/ reset the representation (NOT THE FIXED REPRESENTATION, test polymorphism)\n\trepresentation->resetState();\n\n\t\/\/ isActive flag unchanged\n\tEXPECT_FALSE(fixedRepresentation->isActive());\n\t\/\/ isGravityEnable flag unchanged\n\tEXPECT_FALSE(fixedRepresentation->isGravityEnabled());\n\t\/\/ The current rigid state should be exactly the initial rigid state\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getFinalPose().isApprox(m_initialTransformation));\n\tEXPECT_TRUE(fixedRepresentation->getInitialPose().isApprox(m_initialTransformation));\n\t\/\/ The previous rigid state should be exactly the initial rigid state\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(m_initialTransformation));\n}\n\nTEST_F(FixedRepresentationTest, SetGetAndDefaultValueTest)\n{\n\t\/\/ Create the fixed representation\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\t\/\/ Get\/Set active flag [default = true]\n\tEXPECT_TRUE(fixedRepresentation->isActive());\n\tfixedRepresentation->setIsActive(false);\n\tASSERT_FALSE(fixedRepresentation->isActive());\n\tfixedRepresentation->setIsActive(true);\n\tASSERT_TRUE(fixedRepresentation->isActive());\n\n\t\/\/ Get numDof = 0\n\tASSERT_EQ(0u, fixedRepresentation->getNumDof());\n\n\t\/\/ Set\/Get isGravityEnabled [default = true]\n\tEXPECT_TRUE(fixedRepresentation->isGravityEnabled());\n\tfixedRepresentation->setIsGravityEnabled(false);\n\tASSERT_FALSE(fixedRepresentation->isGravityEnabled());\n\tfixedRepresentation->setIsGravityEnabled(true);\n\tASSERT_TRUE(fixedRepresentation->isGravityEnabled());\n\n\t\/\/ Set\/Get current pose [default = no translation, no rotation]\n\tEXPECT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\tfixedRepresentation->afterUpdate(1.0); \/\/ afterUpdate backs up current into final\n\tASSERT_TRUE(m_currentTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\tfixedRepresentation->setCurrentPose(m_identityTransformation);\n\tfixedRepresentation->afterUpdate(1.0); \/\/ afterUpdate backs up current into final\n\tASSERT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getFinalPose()));\n\n\t\/\/ Set\/Get initial pose [default = no translation, no rotation]\n\tEXPECT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getInitialPose()));\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\tASSERT_TRUE(m_initialTransformation.isApprox(fixedRepresentation->getInitialPose()));\n\tfixedRepresentation->setInitialPose(m_identityTransformation);\n\tASSERT_TRUE(m_identityTransformation.isApprox(fixedRepresentation->getInitialPose()));\n}\n\nTEST_F(FixedRepresentationTest, UpdateTest)\n{\n\t\/\/ Create the fixed representation\n\tstd::shared_ptr<FixedRepresentation> fixedRepresentation = std::make_shared<FixedRepresentation>(\"FixedRepresentation\");\n\n\tdouble dt = 1.0;\n\n\t\/\/ Sets Initial state and reset all other state with initial state\n\tfixedRepresentation->setInitialPose(m_initialTransformation);\n\t\/\/ Backs up current state into previous state and set the current\n\tfixedRepresentation->setCurrentPose(m_currentTransformation);\n\n\t\/\/ Does not do anything\n\tfixedRepresentation->beforeUpdate(dt);\n\t\/\/ Does not do anything\n\tfixedRepresentation->update(dt);\n\t\/\/ Backs up current state into final state\n\tfixedRepresentation->afterUpdate(dt);\n\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getPreviousPose()));\n\tEXPECT_FALSE(fixedRepresentation->getFinalPose().isApprox(fixedRepresentation->getInitialPose()));\n\tEXPECT_TRUE(fixedRepresentation->getPreviousPose().isApprox(fixedRepresentation->getInitialPose()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ See LICENSE file for copyright and license details.\n\n#include <cassert>\n#include \"visualizer\/vertexArray.hpp\"\n\nVertexArray::VertexArray(PrimitiveType primitiveType)\n : vertices(),\n textureCoordinates(),\n colors(),\n mPrimitiveType(primitiveType),\n mTextureID(0),\n mColor(1.0f, 1.0f, 1.0f),\n mHaveColor(false)\n{\n}\n\nVertexArray::VertexArray(const Color& color, PrimitiveType primitiveType)\n : vertices(),\n textureCoordinates(),\n colors(),\n mPrimitiveType(primitiveType),\n mTextureID(0),\n mColor(color),\n mHaveColor(true)\n{\n}\n\nvoid VertexArray::draw() {\n \/\/ enable everything\n {\n if (!textureCoordinates.empty()) {\n glEnable(GL_TEXTURE_2D);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glBindTexture(GL_TEXTURE_2D, mTextureID);\n glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates.data());\n }\n if (!vertices.empty()) {\n glEnableClientState(GL_VERTEX_ARRAY);\n }\n if (!colors.empty()) {\n glEnableClientState(GL_COLOR_ARRAY);\n glColorPointer(3, GL_UNSIGNED_BYTE, 0, colors.data());\n }\n if (mHaveColor) {\n glColor3f(mColor.red(), mColor.green(), mColor.blue());\n } else {\n glColor3f(1.0f, 1.0f, 1.0f);\n }\n }\n \/\/ draw\n {\n glVertexPointer(3, GL_FLOAT, 0, vertices.data());\n switch (mPrimitiveType) {\n case PrimitiveType::Triangles:\n glDrawArrays(GL_TRIANGLES, 0, vertices.size() \/ 3);\n break;\n case PrimitiveType::Lines:\n glDrawArrays(GL_LINES, 0, vertices.size() \/ 3);\n break;\n default:\n throw std::logic_error(\"default case\");\n }\n }\n \/\/ disable everything\n {\n if (!textureCoordinates.empty()) {\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n glDisable(GL_TEXTURE_2D);\n }\n if (!vertices.empty()) {\n glDisableClientState(GL_VERTEX_ARRAY);\n }\n if (!colors.empty()) {\n glDisableClientState(GL_COLOR_ARRAY);\n }\n }\n}\n\nvoid appendV2f(std::vector<float>* vertices, const V2f& vertex) {\n assert(vertices);\n vertices->push_back(vertex.x());\n vertices->push_back(vertex.y());\n}\n\nvoid appendV3f(std::vector<float>* vertices, const V3f& vertex) {\n assert(vertices);\n vertices->push_back(vertex.x());\n vertices->push_back(vertex.y());\n vertices->push_back(vertex.z());\n}\n\nvoid appendRGB(std::vector<GLubyte>* colors, GLubyte r, GLubyte g, GLubyte b) {\n assert(colors);\n colors->push_back(r);\n colors->push_back(g);\n colors->push_back(b);\n}\n\nvoid appendRGB(std::vector<GLubyte>* colors, int r, int g, int b) {\n assert(r >= 0 && r < 256);\n assert(g >= 0 && g < 256);\n assert(b >= 0 && b < 256);\n assert(colors);\n appendRGB(colors,\n static_cast<GLubyte>(r),\n static_cast<GLubyte>(g),\n static_cast<GLubyte>(b));\n}\n<commit_msg>Fixed compilation error in visualizer\/vertexArray.cpp<commit_after>\/\/ See LICENSE file for copyright and license details.\n\n#include <cassert>\n#include <stdexcept>\n#include \"visualizer\/vertexArray.hpp\"\n\nVertexArray::VertexArray(PrimitiveType primitiveType)\n : vertices(),\n textureCoordinates(),\n colors(),\n mPrimitiveType(primitiveType),\n mTextureID(0),\n mColor(1.0f, 1.0f, 1.0f),\n mHaveColor(false)\n{\n}\n\nVertexArray::VertexArray(const Color& color, PrimitiveType primitiveType)\n : vertices(),\n textureCoordinates(),\n colors(),\n mPrimitiveType(primitiveType),\n mTextureID(0),\n mColor(color),\n mHaveColor(true)\n{\n}\n\nvoid VertexArray::draw() {\n \/\/ enable everything\n {\n if (!textureCoordinates.empty()) {\n glEnable(GL_TEXTURE_2D);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glBindTexture(GL_TEXTURE_2D, mTextureID);\n glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates.data());\n }\n if (!vertices.empty()) {\n glEnableClientState(GL_VERTEX_ARRAY);\n }\n if (!colors.empty()) {\n glEnableClientState(GL_COLOR_ARRAY);\n glColorPointer(3, GL_UNSIGNED_BYTE, 0, colors.data());\n }\n if (mHaveColor) {\n glColor3f(mColor.red(), mColor.green(), mColor.blue());\n } else {\n glColor3f(1.0f, 1.0f, 1.0f);\n }\n }\n \/\/ draw\n {\n glVertexPointer(3, GL_FLOAT, 0, vertices.data());\n switch (mPrimitiveType) {\n case PrimitiveType::Triangles:\n glDrawArrays(GL_TRIANGLES, 0, vertices.size() \/ 3);\n break;\n case PrimitiveType::Lines:\n glDrawArrays(GL_LINES, 0, vertices.size() \/ 3);\n break;\n default:\n throw std::logic_error(\"default case\");\n }\n }\n \/\/ disable everything\n {\n if (!textureCoordinates.empty()) {\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n glDisable(GL_TEXTURE_2D);\n }\n if (!vertices.empty()) {\n glDisableClientState(GL_VERTEX_ARRAY);\n }\n if (!colors.empty()) {\n glDisableClientState(GL_COLOR_ARRAY);\n }\n }\n}\n\nvoid appendV2f(std::vector<float>* vertices, const V2f& vertex) {\n assert(vertices);\n vertices->push_back(vertex.x());\n vertices->push_back(vertex.y());\n}\n\nvoid appendV3f(std::vector<float>* vertices, const V3f& vertex) {\n assert(vertices);\n vertices->push_back(vertex.x());\n vertices->push_back(vertex.y());\n vertices->push_back(vertex.z());\n}\n\nvoid appendRGB(std::vector<GLubyte>* colors, GLubyte r, GLubyte g, GLubyte b) {\n assert(colors);\n colors->push_back(r);\n colors->push_back(g);\n colors->push_back(b);\n}\n\nvoid appendRGB(std::vector<GLubyte>* colors, int r, int g, int b) {\n assert(r >= 0 && r < 256);\n assert(g >= 0 && g < 256);\n assert(b >= 0 && b < 256);\n assert(colors);\n appendRGB(colors,\n static_cast<GLubyte>(r),\n static_cast<GLubyte>(g),\n static_cast<GLubyte>(b));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include \"nbind\/api.h\"\n#include \"control.h\"\n#include \"ui.h\"\n\nclass UiMultilineEntry : public UiControl {\n\tDEFINE_EVENT(onChanged)\n\n public:\n\tUiMultilineEntry();\n\tDEFINE_CONTROL_METHODS()\n\tvoid setText(std::string text);\n\tstd::string getText();\n\tvoid setReadOnly(bool readOnly);\n\tbool getReadOnly();\n\tvoid append(std::string text);\n\t~UiMultilineEntry();\n\tvoid onDestroy(uiControl *control) override;\n};\n\nUiMultilineEntry::~UiMultilineEntry() {\n\t\/\/ printf(\"UiMultilineEntry %p destroyed with wrapper %p.\\n\", getHandle(),\n\t\/\/ \t this);\n}\n\nvoid UiMultilineEntry::onDestroy(uiControl *control) {\n\t\/*\n\t\tfreeing event callbacks to allow JS to garbage collect this class\n\t\twhen there are no references to it left in JS code.\n\t*\/\n\tDISPOSE_EVENT(onChanged);\n}\nUiMultilineEntry::UiMultilineEntry()\n\t: UiControl(uiControl(uiNewNonWrappingMultilineEntry())) {}\n\nINHERITS_CONTROL_METHODS(UiMultilineEntry)\n\nIMPLEMENT_EVENT(UiMultilineEntry, uiMultilineEntry, onChanged,\n\t\t\t\tuiMultilineEntryOnChanged)\n\nvoid UiMultilineEntry::setText(std::string text) {\n\tuiMultilineEntrySetText(uiMultilineEntry(getHandle()), text.c_str());\n\tif (onChangedCallback != NULL) {\n\t\t(*onChangedCallback)();\n\t}\n}\n\nstd::string UiMultilineEntry::getText() {\n\tchar *char_ptr = uiMultilineEntryText(uiMultilineEntry(getHandle()));\n\tstd::string s(char_ptr);\n\tuiFreeText(char_ptr);\n\treturn s;\n}\n\nvoid UiMultilineEntry::setReadOnly(bool readOnly) {\n\tuiMultilineEntrySetReadOnly(uiMultilineEntry(getHandle()), readOnly);\n}\n\nbool UiMultilineEntry::getReadOnly() {\n\treturn uiMultilineEntryReadOnly(uiMultilineEntry(getHandle()));\n}\n\nvoid UiMultilineEntry::append(std::string text) {\n\tuiMultilineEntryAppend(uiMultilineEntry(getHandle()), text.c_str());\n}\n\nNBIND_CLASS(UiMultilineEntry) {\n\tconstruct<>();\n\tDECLARE_CHILD_CONTROL_METHODS()\n\tgetset(getText, setText);\n\tgetset(getReadOnly, setReadOnly);\n\tmethod(getText);\n\tmethod(setText);\n\tmethod(getReadOnly);\n\tmethod(setReadOnly);\n\tmethod(append);\n\tmethod(onChanged);\n}\n<commit_msg>removed macro -> UiMultilineEntry<commit_after>#include <string>\n#include \"nbind\/api.h\"\n#include \"control.h\"\n#include \"ui.h\"\n\nclass UiMultilineEntry : public UiControl {\n\tDEFINE_EVENT(onChanged)\n\n public:\n\tUiMultilineEntry();\n\tvoid setText(std::string text);\n\tstd::string getText();\n\tvoid setReadOnly(bool readOnly);\n\tbool getReadOnly();\n\tvoid append(std::string text);\n\t~UiMultilineEntry();\n\tvoid onDestroy(uiControl *control) override;\n};\n\nUiMultilineEntry::~UiMultilineEntry() {\n\t\/\/ printf(\"UiMultilineEntry %p destroyed with wrapper %p.\\n\", getHandle(),\n\t\/\/ \t this);\n}\n\nvoid UiMultilineEntry::onDestroy(uiControl *control) {\n\t\/*\n\t\tfreeing event callbacks to allow JS to garbage collect this class\n\t\twhen there are no references to it left in JS code.\n\t*\/\n\tDISPOSE_EVENT(onChanged);\n}\nUiMultilineEntry::UiMultilineEntry()\n\t: UiControl(uiControl(uiNewNonWrappingMultilineEntry())) {}\n\nIMPLEMENT_EVENT(UiMultilineEntry, uiMultilineEntry, onChanged,\n\t\t\t\tuiMultilineEntryOnChanged)\n\nvoid UiMultilineEntry::setText(std::string text) {\n\tuiMultilineEntrySetText(uiMultilineEntry(getHandle()), text.c_str());\n\tif (onChangedCallback != NULL) {\n\t\t(*onChangedCallback)();\n\t}\n}\n\nstd::string UiMultilineEntry::getText() {\n\tchar *char_ptr = uiMultilineEntryText(uiMultilineEntry(getHandle()));\n\tstd::string s(char_ptr);\n\tuiFreeText(char_ptr);\n\treturn s;\n}\n\nvoid UiMultilineEntry::setReadOnly(bool readOnly) {\n\tuiMultilineEntrySetReadOnly(uiMultilineEntry(getHandle()), readOnly);\n}\n\nbool UiMultilineEntry::getReadOnly() {\n\treturn uiMultilineEntryReadOnly(uiMultilineEntry(getHandle()));\n}\n\nvoid UiMultilineEntry::append(std::string text) {\n\tuiMultilineEntryAppend(uiMultilineEntry(getHandle()), text.c_str());\n}\n\nNBIND_CLASS(UiMultilineEntry) {\n\tinherit(UiControl);\n\tconstruct<>();\n\tgetset(getText, setText);\n\tgetset(getReadOnly, setReadOnly);\n\tmethod(getText);\n\tmethod(setText);\n\tmethod(getReadOnly);\n\tmethod(setReadOnly);\n\tmethod(append);\n\tmethod(onChanged);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SnapFind\n * An interactive image search application\n * Version 1\n *\n * Copyright (c) 2002-2005 Intel Corporation\n * Copyright (c) 2007 Carnegie Mellon University\n * All Rights Reserved.\n *\n * This software is distributed under the terms of the Eclipse Public\n * License, Version 1.0 which can be found in the file named LICENSE.\n * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES\n * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT\n *\/\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <pthread.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <math.h>\n#include <libgen.h>\n#include <stdint.h>\n#include <limits.h>\n#include <ctype.h>\n#include <assert.h>\n\n#include \"diamond_types.h\"\n#include \"searchlet_api.h\"\n#include \"lib_results.h\"\n#include \"lib_sfimage.h\"\n#include \"sf_consts.h\"\n#include \"face_search.h\"\n#include \"search_set.h\"\n#include \"sfind_search.h\"\n#include \"plugin.h\"\n#include \"snapfind.h\"\n\n#include \"lib_scope.h\"\n\n\/*\n * this need to be global because we share it with the main\n * GUI. XXX hack, do it right later.\n *\/\nls_search_handle_t shandle;\napp_stats_t\tastats;\n\n\/*\n * state the is global to all of these functions.\n *\/\n\/* XXX global for status window, fix this someday *\/\nint search_active = 0;\nstatic int active = 0;\nint search_number = 0;\nstruct timeval\tsearch_start;\n\nstatic search_set *sset = NULL;\n\n\n\n\/*\n * This initializes the search state.\n *\/\n\nvoid\ninit_search()\n{\n\tshandle = ls_init_search();\n\tif (shandle == NULL) {\n\t\tprintf(\"failed to initialize: !! \\n\");\n\t\texit(1);\n\t}\n}\n\n\n\/*\n * This function initiates the search by building a filter\n * specification, setting the searchlet and then starting the search.\n *\/\n\nvoid\ndo_search(gid_list_t * main_region, char *fspec)\n{\n\tint err;\n\tchar *filter_name;\n\tchar *dir_name;\n\tvoid \t *cookie;\n\tsearch_iter_t iter;\n\n\tif (!fspec) {\n\t\tfspec = sset->build_filter_spec(NULL);\n\t\tif (fspec == NULL) {\n\t\t\tprintf(\"failed to build filter specification \\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tdir_name = (char *) malloc(SF_MAX_PATH);\n\tif (dir_name == NULL) {\n\t\texit(1); \/* XXX *\/\n\t}\n\n\terr = ls_set_searchlist(shandle, main_region->ngids,\n\t\t\t\tmain_region->gids);\n\tif (err) {\n\t\tprintf(\"Failed to set searchlist on err %d \\n\", err);\n\t\texit(1);\n\t}\n\n\tfilter_name = first_searchlet_lib(&cookie);\n\tif (filter_name == NULL) {\n\t\tfprintf(stderr, \"No filter libraries are defined \\n\");\n\t\tassert(0);\n\t}\n\n\n\terr = ls_set_searchlet(shandle, DEV_ISA_IA32, filter_name, fspec);\n\tif (err) {\n\t\tprintf(\"Failed to set searchlet on err %d \\n\", err);\n\t\texit(1);\n\t}\n\tfree(filter_name);\n\n\twhile ((filter_name = next_searchlet_lib(&cookie)) != NULL) {\n\t\terr = ls_add_filter_file(shandle, DEV_ISA_IA32, filter_name);\n\t\tfree(filter_name);\n\t}\n\n\t\/* Attach auxiliary data for this search. *\/\n\tsset->write_blobs(shandle);\n\t \n\t\/* reset application statistics *\/\n\tastats.as_objs_queued = 0;\n\tastats.as_objs_presented = 0;\n\t \n\t\/* Go ahead and start the search. *\/\n\terr = ls_start_search(shandle);\n\tif (err) {\n\t\tprintf(\"Failed to start search on err %d \\n\", err);\n\t\texit(1);\n\t}\n}\n\n\/*\n * Defines a scope for a new search.\n *\/\nstatic void\ndefine_scope(void *data)\n{\n\tint err;\n\n\terr = ls_define_scope();\n\tif (err != 0) {\n\t\tprintf(\"XXX failed to define scope \\n\");\n\t}\n}\n\n\/*\n * Stops a currently executing search.\n *\/\nstatic void\nstop_search(void *data)\n{\n\tint err;\n\n\tstatic int\t\told_total = 0;\n\t\n\tastats.as_objs_presented = user_measurement.total_seen - old_total;\n\told_total = user_measurement.total_seen;\n\terr = ls_terminate_search_extended(shandle, &astats);\n\tif (err != 0) {\n\t\tprintf(\"XXX failed to terminate search \\n\");\n\t\texit(1);\n\t}\n}\n\n\nvoid\ndrain_ring(GAsyncQueue * ring)\n{\n\tg_async_queue_lock(ring);\n\n\tgpointer msg;\n\twhile ((msg = g_async_queue_try_pop_unlocked(ring))) {\n\t\tfree(msg);\n\t}\n\tg_async_queue_unlock(ring);\n}\n\n\nvoid\nset_user_state(user_state_t state)\n{\n\tint err;\n\tlog_message(LOGT_APP, LOGL_TRACE, \"snapfind: user is %s\", \n\t\t\t\tstate==USER_BUSY?\"busy\":\"waiting\");\n\terr = ls_set_user_state(shandle, state);\n\tif (err) {\n\t\tprintf(\"failed to set user state: %d\", err);\n\t\texit(1);\n\t}\n}\n\n\n\/*\n * This processes a message (command) from the interface\n * GUI to control the processing.\n *\/\n\nvoid\nhandle_message(message_t * new_message)\n{\n\tstruct timezone tz;\n\tint\t\t\t\terr;\n\n\tswitch (new_message->type) {\n\t\tcase START_SEARCH:\n\n\t\t\t\/*\n\t\t\t * delete old msgs \n\t\t\t *\/\n\t\t\tdrain_ring(from_search_thread);\n\t\t\tdo_search((gid_list_t *) new_message->data, NULL);\n\t\t\tactive = 1;\n\t\t\tsearch_active = 1;\n\t\t\tsearch_number++;\n\t\t\terr = gettimeofday(&search_start, &tz);\n\t\t\tassert(err == 0);\n\t\t\tbreak;\n\n\t\tcase TERM_SEARCH:\n\t\t\tstop_search(new_message->data);\n\t\t\tsearch_active = 0;\n\t\t\tbreak;\n\n\t\tcase DEFINE_SCOPE:\n\t\t\tdefine_scope(new_message->data);\n\t\t\tbreak;\n\n\t\t\t\/*\n\t\t\t * XXX get stats ??? \n\t\t\t *\/\n\t\tcase SET_USER_BUSY:\n\t\t\tset_user_state(USER_BUSY);\n\t\t\tbreak;\n\t\t\n\t\tcase SET_USER_WAITING:\n\t\t\tset_user_state(USER_WAITING);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tprintf(\"XXX unknown message %d \\n\", new_message->type);\n\t\t\tassert(0);\n\t\t\tbreak;\n\t}\n}\n\n\n\nvoid\nupdate_stats()\n{\n\tint num_dev;\n\tls_dev_handle_t dev_list[SF_MAX_DEVICES];\n\tint i, err, len;\n\tdev_stats_t *dstats;\n\tint tobj = 0, sobj = 0, dobj = 0;\n\n\tdstats = (dev_stats_t *) malloc(DEV_STATS_SIZE(SF_MAX_FILTERS));\n\tassert(dstats);\n\n\tnum_dev = SF_MAX_DEVICES;\n\n\terr = ls_get_dev_list(shandle, dev_list, &num_dev);\n\tif (err != 0) {\n\t\tprintf(\"update states: %d \\n\", err);\n\t\texit(1);\n\t}\n\n\tfor (i = 0; i < num_dev; i++) {\n\t\tlen = DEV_STATS_SIZE(SF_MAX_FILTERS);\n\t\terr = ls_get_dev_stats(shandle, dev_list[i], dstats, &len);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to get dev stats \\n\");\n\t\t\texit(1);\n\t\t}\n\t\ttobj += dstats->ds_objs_total;\n\t\tsobj += dstats->ds_objs_processed;\n\t\tdobj += dstats->ds_objs_dropped;\n\t}\n\tfree(dstats);\n\n\ttobj_cnt = tobj;\n\tsobj_cnt = sobj;\n\tdobj_cnt = dobj;\n}\n\n\n\/*\n * This is main function that is called thread interacting with the\n * search subsystem. \n *\/\n\nvoid *\nsfind_search_main(void *foo)\n{\n\n\tmessage_t *message;\n\tls_obj_handle_t cur_obj;\n\tint err;\n\tint temp;\n\tint\t\tany;\n\n\tstruct timespec timeout;\n\n\tsset = (search_set *)foo;\n\n\t\/*\n\t * XXX init_search(); \n\t *\/\n\n\twhile (1) {\n\t\tany = 0;\n\t\tmessage = (message_t *) g_async_queue_try_pop(to_search_thread);\n\t\tif (message != NULL) {\n\t\t\tany = 1;\n\t\t\thandle_message(message);\n\t\t\tfree(message);\n\t\t}\n\t\tif ((active) && \n\t\t\t(g_async_queue_length(from_search_thread) < THUMBNAIL_DISPLAY_SIZE+1)) {\n\t\t\terr = ls_next_object(shandle, &cur_obj, LSEARCH_NO_BLOCK);\n\t\t\tif (err == ENOENT) {\n\t\t\t\tfprintf(stderr, \"No more objects \\n\"); \/* XXX *\/\n\t\t\t\tsearch_active = 0;\n\t\t\t\tactive = 0;\n\t\t\t\tmessage = (message_t *) malloc(sizeof(*message));\n\t\t\t\tif (message == NULL) {\n\t\t\t\t\tfprintf(stderr, \"non mem\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tmessage->type = DONE_OBJECTS;\n\t\t\t\tmessage->data = NULL;\n\n\t\t\t\tg_async_queue_push(from_search_thread, message);\n\t\t\t} else if ((err != 0) && (err != EWOULDBLOCK)) {\n\t\t\t\t\/*\n\t\t\t\t * XXX \n\t\t\t\t *\/\n\t\t\t\tfprintf(stderr, \"get_next_obj: failed on %d \\n\", err);\n\t\t\t\texit(1);\n\t\t\t} else if (err == 0) {\n\t\t\t\tany = 1;\n\t\t\t\tmessage = (message_t *) malloc(sizeof(*message));\n\t\t\t\tassert(message != NULL);\n\n\t\t\t\tmessage->type = NEXT_OBJECT;\n\t\t\t\tmessage->data = cur_obj;\n\t\t\t\tg_async_queue_push(from_search_thread, message);\n\t\t\t\tastats.as_objs_queued++;\n\t\t\t}\n\t\t} \n\t\terr = ls_num_objects(shandle, &temp);\n\t\ttemp += g_async_queue_length(from_search_thread);\n\n\t\tpend_obj_cnt = temp;\n\t\tupdate_stats();\n\t\tif (any == 0) {\n\t\t\ttimeout.tv_sec = 0;\n\t\t\ttimeout.tv_nsec = 100000000; \/* XXX 100ms ?? *\/\n\t\t\tnanosleep(&timeout, NULL);\n\t\t}\n\t}\n\treturn (0);\n}\n<commit_msg>Make set_user_state failure non-fatal<commit_after>\/*\n * SnapFind\n * An interactive image search application\n * Version 1\n *\n * Copyright (c) 2002-2005 Intel Corporation\n * Copyright (c) 2007 Carnegie Mellon University\n * All Rights Reserved.\n *\n * This software is distributed under the terms of the Eclipse Public\n * License, Version 1.0 which can be found in the file named LICENSE.\n * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES\n * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT\n *\/\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <pthread.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <math.h>\n#include <libgen.h>\n#include <stdint.h>\n#include <limits.h>\n#include <ctype.h>\n#include <assert.h>\n\n#include \"diamond_types.h\"\n#include \"searchlet_api.h\"\n#include \"lib_results.h\"\n#include \"lib_sfimage.h\"\n#include \"sf_consts.h\"\n#include \"face_search.h\"\n#include \"search_set.h\"\n#include \"sfind_search.h\"\n#include \"plugin.h\"\n#include \"snapfind.h\"\n\n#include \"lib_scope.h\"\n\n\/*\n * this need to be global because we share it with the main\n * GUI. XXX hack, do it right later.\n *\/\nls_search_handle_t shandle;\napp_stats_t\tastats;\n\n\/*\n * state the is global to all of these functions.\n *\/\n\/* XXX global for status window, fix this someday *\/\nint search_active = 0;\nstatic int active = 0;\nint search_number = 0;\nstruct timeval\tsearch_start;\n\nstatic search_set *sset = NULL;\n\n\n\n\/*\n * This initializes the search state.\n *\/\n\nvoid\ninit_search()\n{\n\tshandle = ls_init_search();\n\tif (shandle == NULL) {\n\t\tprintf(\"failed to initialize: !! \\n\");\n\t\texit(1);\n\t}\n}\n\n\n\/*\n * This function initiates the search by building a filter\n * specification, setting the searchlet and then starting the search.\n *\/\n\nvoid\ndo_search(gid_list_t * main_region, char *fspec)\n{\n\tint err;\n\tchar *filter_name;\n\tchar *dir_name;\n\tvoid \t *cookie;\n\tsearch_iter_t iter;\n\n\tif (!fspec) {\n\t\tfspec = sset->build_filter_spec(NULL);\n\t\tif (fspec == NULL) {\n\t\t\tprintf(\"failed to build filter specification \\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tdir_name = (char *) malloc(SF_MAX_PATH);\n\tif (dir_name == NULL) {\n\t\texit(1); \/* XXX *\/\n\t}\n\n\terr = ls_set_searchlist(shandle, main_region->ngids,\n\t\t\t\tmain_region->gids);\n\tif (err) {\n\t\tprintf(\"Failed to set searchlist on err %d \\n\", err);\n\t\texit(1);\n\t}\n\n\tfilter_name = first_searchlet_lib(&cookie);\n\tif (filter_name == NULL) {\n\t\tfprintf(stderr, \"No filter libraries are defined \\n\");\n\t\tassert(0);\n\t}\n\n\n\terr = ls_set_searchlet(shandle, DEV_ISA_IA32, filter_name, fspec);\n\tif (err) {\n\t\tprintf(\"Failed to set searchlet on err %d \\n\", err);\n\t\texit(1);\n\t}\n\tfree(filter_name);\n\n\twhile ((filter_name = next_searchlet_lib(&cookie)) != NULL) {\n\t\terr = ls_add_filter_file(shandle, DEV_ISA_IA32, filter_name);\n\t\tfree(filter_name);\n\t}\n\n\t\/* Attach auxiliary data for this search. *\/\n\tsset->write_blobs(shandle);\n\t \n\t\/* reset application statistics *\/\n\tastats.as_objs_queued = 0;\n\tastats.as_objs_presented = 0;\n\t \n\t\/* Go ahead and start the search. *\/\n\terr = ls_start_search(shandle);\n\tif (err) {\n\t\tprintf(\"Failed to start search on err %d \\n\", err);\n\t\texit(1);\n\t}\n}\n\n\/*\n * Defines a scope for a new search.\n *\/\nstatic void\ndefine_scope(void *data)\n{\n\tint err;\n\n\terr = ls_define_scope();\n\tif (err != 0) {\n\t\tprintf(\"XXX failed to define scope \\n\");\n\t}\n}\n\n\/*\n * Stops a currently executing search.\n *\/\nstatic void\nstop_search(void *data)\n{\n\tint err;\n\n\tstatic int\t\told_total = 0;\n\t\n\tastats.as_objs_presented = user_measurement.total_seen - old_total;\n\told_total = user_measurement.total_seen;\n\terr = ls_terminate_search_extended(shandle, &astats);\n\tif (err != 0) {\n\t\tprintf(\"XXX failed to terminate search \\n\");\n\t\texit(1);\n\t}\n}\n\n\nvoid\ndrain_ring(GAsyncQueue * ring)\n{\n\tg_async_queue_lock(ring);\n\n\tgpointer msg;\n\twhile ((msg = g_async_queue_try_pop_unlocked(ring))) {\n\t\tfree(msg);\n\t}\n\tg_async_queue_unlock(ring);\n}\n\n\nvoid\nset_user_state(user_state_t state)\n{\n\tint err;\n\tlog_message(LOGT_APP, LOGL_TRACE, \"snapfind: user is %s\", \n\t\t\t\tstate==USER_BUSY?\"busy\":\"waiting\");\n\terr = ls_set_user_state(shandle, state);\n\tif (err) {\n\t\tprintf(\"failed to set user state: %d\", err);\n\t\t\/\/exit(1);\n\t}\n}\n\n\n\/*\n * This processes a message (command) from the interface\n * GUI to control the processing.\n *\/\n\nvoid\nhandle_message(message_t * new_message)\n{\n\tstruct timezone tz;\n\tint\t\t\t\terr;\n\n\tswitch (new_message->type) {\n\t\tcase START_SEARCH:\n\n\t\t\t\/*\n\t\t\t * delete old msgs \n\t\t\t *\/\n\t\t\tdrain_ring(from_search_thread);\n\t\t\tdo_search((gid_list_t *) new_message->data, NULL);\n\t\t\tactive = 1;\n\t\t\tsearch_active = 1;\n\t\t\tsearch_number++;\n\t\t\terr = gettimeofday(&search_start, &tz);\n\t\t\tassert(err == 0);\n\t\t\tbreak;\n\n\t\tcase TERM_SEARCH:\n\t\t\tstop_search(new_message->data);\n\t\t\tsearch_active = 0;\n\t\t\tbreak;\n\n\t\tcase DEFINE_SCOPE:\n\t\t\tdefine_scope(new_message->data);\n\t\t\tbreak;\n\n\t\t\t\/*\n\t\t\t * XXX get stats ??? \n\t\t\t *\/\n\t\tcase SET_USER_BUSY:\n\t\t\tset_user_state(USER_BUSY);\n\t\t\tbreak;\n\t\t\n\t\tcase SET_USER_WAITING:\n\t\t\tset_user_state(USER_WAITING);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tprintf(\"XXX unknown message %d \\n\", new_message->type);\n\t\t\tassert(0);\n\t\t\tbreak;\n\t}\n}\n\n\n\nvoid\nupdate_stats()\n{\n\tint num_dev;\n\tls_dev_handle_t dev_list[SF_MAX_DEVICES];\n\tint i, err, len;\n\tdev_stats_t *dstats;\n\tint tobj = 0, sobj = 0, dobj = 0;\n\n\tdstats = (dev_stats_t *) malloc(DEV_STATS_SIZE(SF_MAX_FILTERS));\n\tassert(dstats);\n\n\tnum_dev = SF_MAX_DEVICES;\n\n\terr = ls_get_dev_list(shandle, dev_list, &num_dev);\n\tif (err != 0) {\n\t\tprintf(\"update states: %d \\n\", err);\n\t\texit(1);\n\t}\n\n\tfor (i = 0; i < num_dev; i++) {\n\t\tlen = DEV_STATS_SIZE(SF_MAX_FILTERS);\n\t\terr = ls_get_dev_stats(shandle, dev_list[i], dstats, &len);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to get dev stats \\n\");\n\t\t\texit(1);\n\t\t}\n\t\ttobj += dstats->ds_objs_total;\n\t\tsobj += dstats->ds_objs_processed;\n\t\tdobj += dstats->ds_objs_dropped;\n\t}\n\tfree(dstats);\n\n\ttobj_cnt = tobj;\n\tsobj_cnt = sobj;\n\tdobj_cnt = dobj;\n}\n\n\n\/*\n * This is main function that is called thread interacting with the\n * search subsystem. \n *\/\n\nvoid *\nsfind_search_main(void *foo)\n{\n\n\tmessage_t *message;\n\tls_obj_handle_t cur_obj;\n\tint err;\n\tint temp;\n\tint\t\tany;\n\n\tstruct timespec timeout;\n\n\tsset = (search_set *)foo;\n\n\t\/*\n\t * XXX init_search(); \n\t *\/\n\n\twhile (1) {\n\t\tany = 0;\n\t\tmessage = (message_t *) g_async_queue_try_pop(to_search_thread);\n\t\tif (message != NULL) {\n\t\t\tany = 1;\n\t\t\thandle_message(message);\n\t\t\tfree(message);\n\t\t}\n\t\tif ((active) && \n\t\t\t(g_async_queue_length(from_search_thread) < THUMBNAIL_DISPLAY_SIZE+1)) {\n\t\t\terr = ls_next_object(shandle, &cur_obj, LSEARCH_NO_BLOCK);\n\t\t\tif (err == ENOENT) {\n\t\t\t\tfprintf(stderr, \"No more objects \\n\"); \/* XXX *\/\n\t\t\t\tsearch_active = 0;\n\t\t\t\tactive = 0;\n\t\t\t\tmessage = (message_t *) malloc(sizeof(*message));\n\t\t\t\tif (message == NULL) {\n\t\t\t\t\tfprintf(stderr, \"non mem\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tmessage->type = DONE_OBJECTS;\n\t\t\t\tmessage->data = NULL;\n\n\t\t\t\tg_async_queue_push(from_search_thread, message);\n\t\t\t} else if ((err != 0) && (err != EWOULDBLOCK)) {\n\t\t\t\t\/*\n\t\t\t\t * XXX \n\t\t\t\t *\/\n\t\t\t\tfprintf(stderr, \"get_next_obj: failed on %d \\n\", err);\n\t\t\t\texit(1);\n\t\t\t} else if (err == 0) {\n\t\t\t\tany = 1;\n\t\t\t\tmessage = (message_t *) malloc(sizeof(*message));\n\t\t\t\tassert(message != NULL);\n\n\t\t\t\tmessage->type = NEXT_OBJECT;\n\t\t\t\tmessage->data = cur_obj;\n\t\t\t\tg_async_queue_push(from_search_thread, message);\n\t\t\t\tastats.as_objs_queued++;\n\t\t\t}\n\t\t} \n\t\terr = ls_num_objects(shandle, &temp);\n\t\ttemp += g_async_queue_length(from_search_thread);\n\n\t\tpend_obj_cnt = temp;\n\t\tupdate_stats();\n\t\tif (any == 0) {\n\t\t\ttimeout.tv_sec = 0;\n\t\t\ttimeout.tv_nsec = 100000000; \/* XXX 100ms ?? *\/\n\t\t\tnanosleep(&timeout, NULL);\n\t\t}\n\t}\n\treturn (0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"raytracer.h\"\n\nRayTracer::RayTracer( Camera &camera,\n const Scene &scene,\n const glm::vec3 background_color,\n const size_t samples,\n const size_t maximum_depth,\n Buffer &buffer ) :\n camera_( camera ),\n scene_( scene ),\n background_color_{ background_color },\n samples_{ samples},\n maximum_depth_{ maximum_depth },\n buffer_( buffer )\n{}\n\nRay RayTracer::get_new_ray( IntersectionRecord intersection_record )\n{\n float r1 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float r2 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float theta = glm::acos( 1 - r1 );\n float phi = 2 * M_PI * r2;\n ONB onb_;\n\n onb_.setFromV(intersection_record.normal_);\n\n glm::vec3 cartesian_coordinate{ cosf(phi)*sinf(theta), cosf(theta), sinf(phi)*sinf(theta) };\n\n return Ray{ intersection_record.position_ + (intersection_record.normal_*0.001f), onb_.getBasisMatrix() * cartesian_coordinate };\n}\n\n\nRay RayTracer::get_reflection(IntersectionRecord intersection_record, Ray ray)\n{\n ONB onb_;\n\n onb_.setFromV(intersection_record.normal_);\n\n Ray newray;\n\n glm::vec3 newdir = glm::transpose(onb_.getBasisMatrix()) * ray.direction_;\n newdir = { newdir.x, -newdir.y, newdir.z };\n newray = { intersection_record.position_ + (intersection_record.normal_*0.001f), onb_.getBasisMatrix() * newdir };\n\n return newray;\n}\n\ndouble RayTracer::rSchlick1(const glm::vec3 normal, glm::vec3 incident, double n1, double n2)\n{\n double r0 = (n1 - n2) \/(n1 + n2);\n r0 *= r0;\n double cosX = -glm::dot(normal, incident);\n if (n1 > n2) {\n const double n = n1\/n2;\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n cosX = sqrt(1.0 - sinT2);\n }\n const double x = 1.0 - cosX;\n return r0 + ( 1.0 - r0 ) * x * x * x * x * x;\n}\n\n\ndouble RayTracer::rSchlick2(const glm::vec3 normal, glm::vec3 incident, double n1, double n2){\n\n double r0 = (n1 - n2) \/(n1 + n2);\n r0 *= r0;\n double cosX = -glm::dot(normal, incident);\n if (n1 > n2) {\n const double n = n1\/n2;\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n if(sinT2 > 1.0) return 1.0;\/\/TIR\n cosX = sqrt(1.0 - sinT2);\n }\n const double x = 1.0 - cosX;\n return r0 + ( 1.0 - r0 ) * x * x * x * x * x;\n}\n\nglm::dvec3 RayTracer::cook_torrance( glm::dvec3 wi, glm::dvec3 wo, IntersectionRecord intersection_record )\n{\n<<<<<<< HEAD\n glm::dvec3 h = glm::normalize( (wo - wi) \/ 2.0 );\n double nh = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), h));\n double nwo = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), wo ));\n double nwi = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), -wi ));\n double hwo = glm::abs( glm::dot( h, wo ));\n double hwi = glm::abs( glm::dot( h, -wi ));\n=======\n \n ONB tangent_frame;\n tangent_frame.setFromV( (glm::dvec3) intersection_record.normal_ );\n\n glm::dmat3x3 tangent_to_universe_space = tangent_frame.getBasisMatrix();\n glm::dmat3x3 universe_to_tangent_space = glm::transpose( tangent_to_universe_space );\n\n glm::dvec3 w_i = universe_to_tangent_space * (glm::dvec3)-wi;\n\n glm::dvec3 w_o = universe_to_tangent_space * (glm::dvec3)wo;\n \n glm::dvec3 h = glm::normalize((w_i + w_o));\n double nh = glm::abs( h.y );\n double nwo = glm::abs( w_o.y );\n double nwi = glm::abs( w_i.y );\n double hwo = glm::abs( glm::dot( h, w_o ));\n double hwi = glm::abs( glm::dot( h, w_i ));\n>>>>>>> 79379bf16612739e6b8837579d91b5dacf6583c5\n\n \/\/Beckmann\n\n double m = 0.35;\n double nh2 = nh * nh;\n double m2 = m * m;\n double d1 = 1.0 \/ ( M_PI * m2 * nh2 * nh2);\n double d2 = ( nh2 - 1.0 ) \/ (m2 * nh2 );\n double D = d1 * exp( d2 );\n\n \/\/Geometric term\n\n double g1 = 2.0 * nh \/ hwi;\n double G = glm::min( 1.0, glm::min(g1 * nwo, g1 * nwi ));\n\n \/\/Fresnel term\n\n<<<<<<< HEAD\n double one_minus_hwi_5 = ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi );\n glm::dvec3 F = M_PI * glm::dvec3( intersection_record.brdf_ ) + ( glm::dvec3(1.0) - ( M_PI * glm::dvec3( intersection_record.brdf_ ) ) ) * one_minus_hwi_5;\n\n=======\n double one_minus_hwi_5 = (1.0 - hwo) * (1.0 - hwo) * (1.0 - hwo) * (1.0 - hwo) * (1.0 - hwo);\n glm::dvec3 F = (M_PI)*(glm::dvec3)intersection_record.brdf_ + ( 1.0 - (M_PI)*(glm::dvec3)intersection_record.brdf_) * one_minus_hwi_5;\n \/\/printf(\"\\n(%.2f, %.2f, %.2f)\", F.x, F.y, F.z);\n>>>>>>> 79379bf16612739e6b8837579d91b5dacf6583c5\n \/\/Cook-Torrance\n\n return ( F * D * G) \/ ( 4.0 * nwo * nwi );\n}\n\n\nglm::vec3 RayTracer::L( Ray ray, IntersectionRecord intersection_record, size_t curr_depth ) \/\/Rendering equation\n{\n glm::vec3 Lo{ 0.0f, 0.0f, 0.0f };\n \n Ray refl_ray;\n \n intersection_record.t_ = std::numeric_limits< double >::max();\n\n if ( curr_depth < maximum_depth_ )\n {\n if ( scene_.intersect ( ray, intersection_record ))\n { \n if( intersection_record.pmirror_ )\/\/if its a mirror\n {\n refl_ray = get_reflection(intersection_record, ray);\n\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n \n }\n\n else if( intersection_record.glass_ )\/\/if its glass\n {\n float n1, n2;\n \n if(glm::dot(ray.direction_,intersection_record.normal_)<0){\/\/ENTRANDO NO VIDRO\n\n n1 = 1.0f;\n n2 = 2.0f;\n\n double fresnel = rSchlick1(intersection_record.normal_, (ray.direction_), n1, n2);\n double r = (double) (rand()) \/ (double) (RAND_MAX);\n \n if(r<fresnel){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n } \n \n else{\n const float n = n1\/n2;\n const float cosI = -glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosI * cosI);\n const float cosT = glm::sqrt(1.0 - sinT2);\n \n refl_ray.direction_ = glm::normalize( n * ray.direction_ + (n*cosI - cosT) * intersection_record.normal_);\n refl_ray.origin_ = intersection_record.position_ + (0.001f*refl_ray.direction_);\n \n Lo = L(refl_ray, intersection_record, ++curr_depth);\n } \n }\n else{\/\/SAINDO DO VIDRO\n n1 = 2.0f;\n n2 = 1.0f;\n\n const float n = n1\/n2;\n double cosX = -glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n\n if(sinT2 > 1.0){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n else{\n double fresnel = rSchlick2(intersection_record.normal_, (ray.direction_), n1, n2);\n double r = (double) (rand()) \/ (double) (RAND_MAX+1.0); \n\n if(r<fresnel){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n else{\n const float n = n1\/n2;\n const float cosI = glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosI * cosI);\n const float cosT = glm::sqrt(1.0 - sinT2);\n \n refl_ray.direction_ = glm::normalize(n * ray.direction_ + (n * cosI - cosT) * intersection_record.normal_);\n refl_ray.origin_ = intersection_record.position_ + (0.001f*refl_ray.direction_);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n } \n }\n }\n\n else if( intersection_record.metal_ )\/\/if its metal\n {\n refl_ray = get_new_ray( intersection_record );\n Lo = intersection_record.emittance_ + glm::vec3( cook_torrance( glm::dvec3( refl_ray.direction_ ), glm::dvec3( ray.direction_ ), intersection_record )) *\n L( refl_ray, intersection_record, ++curr_depth ) * glm::dot( intersection_record.normal_, refl_ray.direction_ );\n }\n\n else\/\/if its diffuse \n { \n refl_ray = get_new_ray( intersection_record );\n\n Lo = intersection_record.emittance_ + 2.0f * ((float) M_PI) * intersection_record.brdf_ *\n L( refl_ray, intersection_record, ++curr_depth ) * glm::dot( intersection_record.normal_, refl_ray.direction_ ); \n }\n } \n }\n return Lo;\n}\n \nvoid RayTracer::integrate( void )\n{\n \/\/Image space origin (i.e. x = 0 and y = 0) at the top left corner.\n\n Ray ray;\n IntersectionRecord intersection_record;\n\n #pragma omp parallel for schedule(dynamic, 1) private(ray, intersection_record)\n\n \/\/ Loops over image rows\n for ( std::size_t y = 0; y < buffer_.v_resolution_; y++ )\n {\n std::stringstream progress_stream;\n progress_stream << \"\\r progress .........................: \"\n << std::fixed << std::setw( 6 )\n << std::setprecision( 2 )\n << 100.0 * y \/ ( buffer_.v_resolution_ - 1 )\n << \"%\";\n\n std::clog << progress_stream.str();\n\n srand(std::time(0));\n\n \/\/ Loops over image columns\n for ( std::size_t x = 0; x < buffer_.h_resolution_; x++ )\n {\n for(std::size_t i = 0; i < samples_; i++ )\n { \n \/\/intersection_record.t_ = std::numeric_limits< double >::max();\n\n float rand1 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float rand2 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n\n \/\/Ray ray{ camera_.getWorldSpaceRay( glm::vec2{ x + 0.5f, y + 0.5f } ) };\n ray = { camera_.getWorldSpaceRay( glm::vec2{ x + rand1, y + rand2 } ) };\n\n \/\/if ( scene_.intersect( ray, intersection_record ) )\n \/\/buffer_.buffer_data_[x][y] = glm::vec3{ intersection_record.t_ * 0.2f };\n \/\/final_color = final_color + intersection_record.color_;\n buffer_.buffer_data_[x][y] += L( ray, intersection_record, 0 ); \n }\n buffer_.buffer_data_[x][y] \/= static_cast <float> (samples_);\n }\n }\n\n std::clog << std::endl;\n}\n\n<commit_msg>Fixed failed merge<commit_after>#include \"raytracer.h\"\n\nRayTracer::RayTracer( Camera &camera,\n const Scene &scene,\n const glm::vec3 background_color,\n const size_t samples,\n const size_t maximum_depth,\n Buffer &buffer ) :\n camera_( camera ),\n scene_( scene ),\n background_color_{ background_color },\n samples_{ samples},\n maximum_depth_{ maximum_depth },\n buffer_( buffer )\n{}\n\nRay RayTracer::get_new_ray( IntersectionRecord intersection_record )\n{\n float r1 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float r2 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float theta = glm::acos( 1 - r1 );\n float phi = 2 * M_PI * r2;\n ONB onb_;\n\n onb_.setFromV(intersection_record.normal_);\n\n glm::vec3 cartesian_coordinate{ cosf(phi)*sinf(theta), cosf(theta), sinf(phi)*sinf(theta) };\n\n return Ray{ intersection_record.position_ + (intersection_record.normal_*0.001f), onb_.getBasisMatrix() * cartesian_coordinate };\n}\n\n\nRay RayTracer::get_reflection(IntersectionRecord intersection_record, Ray ray)\n{\n ONB onb_;\n\n onb_.setFromV(intersection_record.normal_);\n\n Ray newray;\n\n glm::vec3 newdir = glm::transpose(onb_.getBasisMatrix()) * ray.direction_;\n newdir = { newdir.x, -newdir.y, newdir.z };\n newray = { intersection_record.position_ + (intersection_record.normal_*0.001f), onb_.getBasisMatrix() * newdir };\n\n return newray;\n}\n\ndouble RayTracer::rSchlick1(const glm::vec3 normal, glm::vec3 incident, double n1, double n2)\n{\n double r0 = (n1 - n2) \/(n1 + n2);\n r0 *= r0;\n double cosX = -glm::dot(normal, incident);\n if (n1 > n2) {\n const double n = n1\/n2;\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n cosX = sqrt(1.0 - sinT2);\n }\n const double x = 1.0 - cosX;\n return r0 + ( 1.0 - r0 ) * x * x * x * x * x;\n}\n\n\ndouble RayTracer::rSchlick2(const glm::vec3 normal, glm::vec3 incident, double n1, double n2){\n\n double r0 = (n1 - n2) \/(n1 + n2);\n r0 *= r0;\n double cosX = -glm::dot(normal, incident);\n if (n1 > n2) {\n const double n = n1\/n2;\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n if(sinT2 > 1.0) return 1.0;\/\/TIR\n cosX = sqrt(1.0 - sinT2);\n }\n const double x = 1.0 - cosX;\n return r0 + ( 1.0 - r0 ) * x * x * x * x * x;\n}\n\nglm::dvec3 RayTracer::cook_torrance( glm::dvec3 wi, glm::dvec3 wo, IntersectionRecord intersection_record )\n{\n glm::dvec3 h = glm::normalize( (wo - wi) \/ 2.0 );\n double nh = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), h));\n double nwo = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), wo ));\n double nwi = glm::abs( glm::dot( glm::dvec3( intersection_record.normal_ ), -wi ));\n double hwo = glm::abs( glm::dot( h, wo ));\n double hwi = glm::abs( glm::dot( h, -wi ));\n\n \/\/Beckmann\n\n double m = 0.35;\n double nh2 = nh * nh;\n double m2 = m * m;\n double d1 = 1.0 \/ ( M_PI * m2 * nh2 * nh2);\n double d2 = ( nh2 - 1.0 ) \/ (m2 * nh2 );\n double D = d1 * glm::exp( d2 );\n\n \/\/Geometric term\n\n double g1 = 2.0 * nh \/ hwo;\n double G = glm::min( 1.0, glm::min(g1 * nwo, g1 * nwi ));\n\n \/\/Fresnel term\n\n double one_minus_hwi_5 = ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi ) * ( 1.0 - hwi );\n glm::dvec3 F = M_PI * glm::dvec3( intersection_record.brdf_ ) + ( glm::dvec3(1.0) - ( M_PI * glm::dvec3( intersection_record.brdf_ ) ) ) * one_minus_hwi_5;\n\n \/\/Cook-Torrance\n\n return ( F * D * G) \/ ( 4.0 * nwo * nwi );\n}\n\n\nglm::vec3 RayTracer::L( Ray ray, IntersectionRecord intersection_record, size_t curr_depth ) \/\/Rendering equation\n{\n glm::vec3 Lo{ 0.0f, 0.0f, 0.0f };\n \n Ray refl_ray;\n \n intersection_record.t_ = std::numeric_limits< double >::max();\n\n if ( curr_depth < maximum_depth_ )\n {\n if ( scene_.intersect ( ray, intersection_record ))\n { \n if( intersection_record.pmirror_ )\/\/if its a mirror\n {\n refl_ray = get_reflection(intersection_record, ray);\n\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n \n }\n\n else if( intersection_record.glass_ )\/\/if its glass\n {\n float n1, n2;\n \n if(glm::dot(ray.direction_,intersection_record.normal_)<0){\/\/ENTRANDO NO VIDRO\n\n n1 = 1.0f;\n n2 = 2.0f;\n\n double fresnel = rSchlick1(intersection_record.normal_, (ray.direction_), n1, n2);\n double r = (double) (rand()) \/ (double) (RAND_MAX);\n \n if(r<fresnel){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n } \n \n else{\n const float n = n1\/n2;\n const float cosI = -glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosI * cosI);\n const float cosT = glm::sqrt(1.0 - sinT2);\n \n refl_ray.direction_ = glm::normalize( n * ray.direction_ + (n*cosI - cosT) * intersection_record.normal_);\n refl_ray.origin_ = intersection_record.position_ + (0.001f*refl_ray.direction_);\n \n Lo = L(refl_ray, intersection_record, ++curr_depth);\n } \n }\n else{\/\/SAINDO DO VIDRO\n n1 = 2.0f;\n n2 = 1.0f;\n\n const float n = n1\/n2;\n double cosX = -glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosX * cosX);\n\n if(sinT2 > 1.0){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n else{\n double fresnel = rSchlick2(intersection_record.normal_, (ray.direction_), n1, n2);\n double r = (double) (rand()) \/ (double) (RAND_MAX+1.0); \n\n if(r<fresnel){\n refl_ray = get_reflection(intersection_record, ray);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n else{\n const float n = n1\/n2;\n const float cosI = glm::dot(intersection_record.normal_, ray.direction_);\n const double sinT2 = n * n * (1.0 - cosI * cosI);\n const float cosT = glm::sqrt(1.0 - sinT2);\n \n refl_ray.direction_ = glm::normalize(n * ray.direction_ + (n * cosI - cosT) * intersection_record.normal_);\n refl_ray.origin_ = intersection_record.position_ + (0.001f*refl_ray.direction_);\n Lo = L(refl_ray, intersection_record, ++curr_depth);\n }\n } \n }\n }\n\n else if( intersection_record.metal_ )\/\/if its metal\n {\n refl_ray = get_new_ray( intersection_record );\n Lo = intersection_record.emittance_ + glm::vec3( cook_torrance( glm::dvec3( refl_ray.direction_ ), glm::dvec3( ray.direction_ ), intersection_record )) *\n L( refl_ray, intersection_record, ++curr_depth ) * glm::dot( intersection_record.normal_, refl_ray.direction_ );\n }\n\n else\/\/if its diffuse \n { \n refl_ray = get_new_ray( intersection_record );\n\n Lo = intersection_record.emittance_ + 2.0f * ((float) M_PI) * intersection_record.brdf_ *\n L( refl_ray, intersection_record, ++curr_depth ) * glm::dot( intersection_record.normal_, refl_ray.direction_ ); \n }\n } \n }\n return Lo;\n}\n \nvoid RayTracer::integrate( void )\n{\n \/\/Image space origin (i.e. x = 0 and y = 0) at the top left corner.\n\n Ray ray;\n IntersectionRecord intersection_record;\n\n #pragma omp parallel for schedule(dynamic, 1) private(ray, intersection_record)\n\n \/\/ Loops over image rows\n for ( std::size_t y = 0; y < buffer_.v_resolution_; y++ )\n {\n std::stringstream progress_stream;\n progress_stream << \"\\r progress .........................: \"\n << std::fixed << std::setw( 6 )\n << std::setprecision( 2 )\n << 100.0 * y \/ ( buffer_.v_resolution_ - 1 )\n << \"%\";\n\n std::clog << progress_stream.str();\n\n srand(std::time(0));\n\n \/\/ Loops over image columns\n for ( std::size_t x = 0; x < buffer_.h_resolution_; x++ )\n {\n for(std::size_t i = 0; i < samples_; i++ )\n { \n \/\/intersection_record.t_ = std::numeric_limits< double >::max();\n\n float rand1 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n float rand2 = static_cast <float> (rand()) \/ static_cast <float> (RAND_MAX);\n\n \/\/Ray ray{ camera_.getWorldSpaceRay( glm::vec2{ x + 0.5f, y + 0.5f } ) };\n ray = { camera_.getWorldSpaceRay( glm::vec2{ x + rand1, y + rand2 } ) };\n\n \/\/if ( scene_.intersect( ray, intersection_record ) )\n \/\/buffer_.buffer_data_[x][y] = glm::vec3{ intersection_record.t_ * 0.2f };\n \/\/final_color = final_color + intersection_record.color_;\n buffer_.buffer_data_[x][y] += L( ray, intersection_record, 0 ); \n }\n buffer_.buffer_data_[x][y] \/= static_cast <float> (samples_);\n }\n }\n\n std::clog << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —\n Vladimír Vondruš <mosra@centrum.cz>\n 2018 — scturtle <scturtle@gmail.com>\n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Magnum\/Image.h>\n#include <Magnum\/GL\/Buffer.h>\n#include <Magnum\/GL\/DefaultFramebuffer.h>\n#include <Magnum\/GL\/Mesh.h>\n#include <Magnum\/GL\/PixelFormat.h>\n#include <Magnum\/GL\/Renderer.h>\n#include <Magnum\/MeshTools\/Compile.h>\n#include <Magnum\/Platform\/Sdl2Application.h>\n#include <Magnum\/Primitives\/Grid.h>\n#include <Magnum\/SceneGraph\/Camera.h>\n#include <Magnum\/SceneGraph\/Drawable.h>\n#include <Magnum\/SceneGraph\/MatrixTransformation3D.h>\n#include <Magnum\/SceneGraph\/Object.h>\n#include <Magnum\/SceneGraph\/Scene.h>\n#include <Magnum\/Shaders\/Flat.h>\n#include <Magnum\/Shaders\/VertexColor.h>\n#include <Magnum\/Trade\/MeshData3D.h>\n\nnamespace Magnum { namespace Examples {\n\nusing Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>;\nusing Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>;\n\nusing namespace Math::Literals;\n\nclass MouseInteractionExample: public Platform::Application {\n public:\n explicit MouseInteractionExample(const Arguments& arguments);\n\n private:\n Float depthAt(const Vector2i& position);\n Vector3 unproject(const Vector2i& position, Float depth) const;\n\n void keyPressEvent(KeyEvent& event) override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n void mouseScrollEvent(MouseScrollEvent& event) override;\n void drawEvent() override;\n\n Shaders::VertexColor3D _vertexColorShader{NoCreate};\n Shaders::Flat3D _flatShader{NoCreate};\n GL::Mesh _mesh{NoCreate}, _grid{NoCreate};\n\n Scene3D _scene;\n SceneGraph::DrawableGroup3D _drawables;\n Object3D* _cameraObject;\n SceneGraph::Camera3D* _camera;\n\n Float _lastDepth;\n Vector2i _lastPosition{-1};\n Vector3 _rotationPoint, _translationPoint;\n};\n\nclass VertexColorDrawable: public SceneGraph::Drawable3D {\n public:\n explicit VertexColorDrawable(Object3D& object, Shaders::VertexColor3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {}\n\n void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {\n _shader.setTransformationProjectionMatrix(camera.projectionMatrix()*transformation);\n _mesh.draw(_shader);\n }\n\n private:\n Shaders::VertexColor3D& _shader;\n GL::Mesh& _mesh;\n};\n\nclass FlatDrawable: public SceneGraph::Drawable3D {\n public:\n explicit FlatDrawable(Object3D& object, Shaders::Flat3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {}\n\n void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {\n _shader.setColor(0x747474_rgbf)\n .setTransformationProjectionMatrix(camera.projectionMatrix()*transformation);\n _mesh.draw(_shader);\n }\n\n private:\n Shaders::Flat3D& _shader;\n GL::Mesh& _mesh;\n};\n\nMouseInteractionExample::MouseInteractionExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} {\n \/* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x\n MSAA if we have enough DPI. *\/\n {\n const Vector2 dpiScaling = this->dpiScaling({});\n Configuration conf;\n conf.setTitle(\"Magnum Mouse Interaction Example\")\n .setSize(conf.size(), dpiScaling);\n GLConfiguration glConf;\n glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);\n if(!tryCreate(conf, glConf))\n create(conf, glConf.setSampleCount(0));\n }\n\n \/* Shaders, renderer setup *\/\n _vertexColorShader = Shaders::VertexColor3D{};\n _flatShader = Shaders::Flat3D{};\n GL::Renderer::enable(GL::Renderer::Feature::DepthTest);\n\n \/* Triangle data *\/\n const struct {\n Vector3 pos;\n Color3 color;\n } data[]{{{-1.0f, -1.0f, 0.0f}, 0xff0000_rgbf},\n {{ 1.0f, -1.0f, 0.0f}, 0x00ff00_rgbf},\n {{ 0.0f, 1.0f, 0.0f}, 0x0000ff_rgbf}};\n\n \/* Triangle mesh *\/\n GL::Buffer buffer;\n buffer.setData(data);\n _mesh = GL::Mesh{};\n _mesh.setCount(3)\n .addVertexBuffer(std::move(buffer), 0,\n Shaders::VertexColor3D::Position{},\n Shaders::VertexColor3D::Color3{});\n\n \/* Triangle object *\/\n auto triangle = new Object3D{&_scene};\n new VertexColorDrawable{*triangle, _vertexColorShader, _mesh, _drawables};\n\n \/* Grid *\/\n _grid = MeshTools::compile(Primitives::grid3DWireframe({15, 15}));\n auto grid = new Object3D{&_scene};\n (*grid)\n .rotateX(90.0_degf)\n .scale(Vector3{8.0f});\n new FlatDrawable{*grid, _flatShader, _grid, _drawables};\n\n \/* Set up the camera *\/\n _cameraObject = new Object3D{&_scene};\n (*_cameraObject)\n .translate(Vector3::zAxis(5.0f))\n .rotateX(-15.0_degf)\n .rotateY(30.0_degf);\n _camera = new SceneGraph::Camera3D{*_cameraObject};\n _camera->setProjectionMatrix(Matrix4::perspectiveProjection(\n 45.0_degf, Vector2{windowSize()}.aspectRatio(), 0.01f, 100.0f));\n\n \/* Initialize initial depth to the value at scene center *\/\n _lastDepth = ((_camera->projectionMatrix()*_camera->cameraMatrix()).transformPoint({}).z() + 1.0f)*0.5f;\n}\n\nFloat MouseInteractionExample::depthAt(const Vector2i& position) {\n const Vector2i fbPosition{position.x(), GL::defaultFramebuffer.viewport().sizeY() - position.y() - 1};\n\n GL::defaultFramebuffer.mapForRead(GL::DefaultFramebuffer::ReadAttachment::Front);\n Image2D data = GL::defaultFramebuffer.read(\n Range2Di::fromSize(fbPosition, Vector2i{1}).padded(Vector2i{2}),\n {GL::PixelFormat::DepthComponent, GL::PixelType::Float});\n\n return Math::min(Containers::arrayCast<const Float>(data.data()));\n}\n\nVector3 MouseInteractionExample::unproject(const Vector2i& position, Float depth) const {\n const Range2Di view = GL::defaultFramebuffer.viewport();\n const Vector2i fbPosition{position.x(), view.sizeY() - position.y() - 1};\n const Vector3 in{2*Vector2{fbPosition - view.min()}\/Vector2{view.size()} - Vector2{1.0f}, depth*2.0f - 1.0f};\n\n \/*\n Use the following to get global coordinates instead of camera-relative:\n\n (_cameraObject->absoluteTransformationMatrix()*_camera->projectionMatrix().inverted()).transformPoint(in)\n *\/\n return _camera->projectionMatrix().inverted().transformPoint(in);\n}\n\nvoid MouseInteractionExample::keyPressEvent(KeyEvent& event) {\n \/* Reset the transformation to the original view *\/\n if(event.key() == KeyEvent::Key::NumZero) {\n (*_cameraObject)\n .resetTransformation()\n .translate(Vector3::zAxis(5.0f))\n .rotateX(-15.0_degf)\n .rotateY(30.0_degf);\n redraw();\n return;\n\n \/* Axis-aligned view *\/\n } else if(event.key() == KeyEvent::Key::NumOne ||\n event.key() == KeyEvent::Key::NumThree ||\n event.key() == KeyEvent::Key::NumSeven)\n {\n \/* Start with current camera translation with the rotation inverted *\/\n const Vector3 viewTranslation = _cameraObject->transformation().rotationScaling().inverted()*_cameraObject->transformation().translation();\n\n \/* Front\/back *\/\n const Float multiplier = event.modifiers() & KeyEvent::Modifier::Ctrl ? -1.0f : 1.0f;\n\n Matrix4 transformation;\n if(event.key() == KeyEvent::Key::NumSeven) \/* Top\/bottom *\/\n transformation = Matrix4::rotationX(-90.0_degf*multiplier);\n else if(event.key() == KeyEvent::Key::NumOne) \/* Front\/back *\/\n transformation = Matrix4::rotationY(90.0_degf - 90.0_degf*multiplier);\n else if(event.key() == KeyEvent::Key::NumThree) \/* Right\/left *\/\n transformation = Matrix4::rotationY(90.0_degf*multiplier);\n else CORRADE_ASSERT_UNREACHABLE();\n\n _cameraObject->setTransformation(transformation*Matrix4::translation(viewTranslation));\n redraw();\n }\n}\n\nvoid MouseInteractionExample::mousePressEvent(MouseEvent& event) {\n \/* Due to compatibility reasons, scroll is also reported as a press event,\n so filter that out. Could be removed once MouseEvent::Button::Wheel is\n gone from Magnum. *\/\n if(event.button() != MouseEvent::Button::Left &&\n event.button() != MouseEvent::Button::Middle)\n return;\n\n const Float currentDepth = depthAt(event.position());\n const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth;\n _translationPoint = unproject(event.position(), depth);\n \/* Update the rotation point only if we're not zooming against infinite\n depth or if the original rotation point is not yet initialized *\/\n if(currentDepth != 1.0f || _rotationPoint.isZero()) {\n _rotationPoint = _translationPoint;\n _lastDepth = depth;\n }\n}\n\nvoid MouseInteractionExample::mouseMoveEvent(MouseMoveEvent& event) {\n if(_lastPosition == Vector2i{-1}) _lastPosition = event.position();\n const Vector2i delta = event.position() - _lastPosition;\n _lastPosition = event.position();\n\n if(!event.buttons()) return;\n\n \/* Translate *\/\n if(event.modifiers() & MouseMoveEvent::Modifier::Shift) {\n const Vector3 p = unproject(event.position(), _lastDepth);\n _cameraObject->translateLocal(_translationPoint - p); \/* is Z always 0? *\/\n _translationPoint = p;\n\n \/* Rotate around rotation point *\/\n } else _cameraObject->transformLocal(\n Matrix4::translation(_rotationPoint)*\n Matrix4::rotationX(-0.01_radf*delta.y())*\n Matrix4::rotationY(-0.01_radf*delta.x())*\n Matrix4::translation(-_rotationPoint));\n\n redraw();\n}\n\nvoid MouseInteractionExample::mouseScrollEvent(MouseScrollEvent& event) {\n const Float currentDepth = depthAt(event.position());\n const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth;\n const Vector3 p = unproject(event.position(), depth);\n \/* Update the rotation point only if we're not zooming against infinite\n depth or if the original rotation point is not yet initialized *\/\n if(currentDepth != 1.0f || _rotationPoint.isZero()) {\n _rotationPoint = p;\n _lastDepth = depth;\n }\n\n const Int direction = event.offset().y();\n if(!direction) return;\n\n \/* Move towards\/backwards the rotation point in cam coords *\/\n _cameraObject->translateLocal(_rotationPoint*(direction < 0 ? -1.0f : 1.0f)*0.1f);\n\n redraw();\n}\n\nvoid MouseInteractionExample::drawEvent() {\n GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth);\n\n _camera->draw(_drawables);\n\n swapBuffers();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::MouseInteractionExample)\n<commit_msg>mouseinteraction: fix build without deprecated APIs.<commit_after>\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —\n Vladimír Vondruš <mosra@centrum.cz>\n 2018 — scturtle <scturtle@gmail.com>\n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Magnum\/Image.h>\n#include <Magnum\/GL\/Buffer.h>\n#include <Magnum\/GL\/DefaultFramebuffer.h>\n#include <Magnum\/GL\/Mesh.h>\n#include <Magnum\/GL\/PixelFormat.h>\n#include <Magnum\/GL\/Renderer.h>\n#include <Magnum\/Math\/FunctionsBatch.h>\n#include <Magnum\/MeshTools\/Compile.h>\n#include <Magnum\/Platform\/Sdl2Application.h>\n#include <Magnum\/Primitives\/Grid.h>\n#include <Magnum\/SceneGraph\/Camera.h>\n#include <Magnum\/SceneGraph\/Drawable.h>\n#include <Magnum\/SceneGraph\/MatrixTransformation3D.h>\n#include <Magnum\/SceneGraph\/Object.h>\n#include <Magnum\/SceneGraph\/Scene.h>\n#include <Magnum\/Shaders\/Flat.h>\n#include <Magnum\/Shaders\/VertexColor.h>\n#include <Magnum\/Trade\/MeshData3D.h>\n\nnamespace Magnum { namespace Examples {\n\nusing Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>;\nusing Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>;\n\nusing namespace Math::Literals;\n\nclass MouseInteractionExample: public Platform::Application {\n public:\n explicit MouseInteractionExample(const Arguments& arguments);\n\n private:\n Float depthAt(const Vector2i& position);\n Vector3 unproject(const Vector2i& position, Float depth) const;\n\n void keyPressEvent(KeyEvent& event) override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n void mouseScrollEvent(MouseScrollEvent& event) override;\n void drawEvent() override;\n\n Shaders::VertexColor3D _vertexColorShader{NoCreate};\n Shaders::Flat3D _flatShader{NoCreate};\n GL::Mesh _mesh{NoCreate}, _grid{NoCreate};\n\n Scene3D _scene;\n SceneGraph::DrawableGroup3D _drawables;\n Object3D* _cameraObject;\n SceneGraph::Camera3D* _camera;\n\n Float _lastDepth;\n Vector2i _lastPosition{-1};\n Vector3 _rotationPoint, _translationPoint;\n};\n\nclass VertexColorDrawable: public SceneGraph::Drawable3D {\n public:\n explicit VertexColorDrawable(Object3D& object, Shaders::VertexColor3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {}\n\n void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {\n _shader.setTransformationProjectionMatrix(camera.projectionMatrix()*transformation);\n _mesh.draw(_shader);\n }\n\n private:\n Shaders::VertexColor3D& _shader;\n GL::Mesh& _mesh;\n};\n\nclass FlatDrawable: public SceneGraph::Drawable3D {\n public:\n explicit FlatDrawable(Object3D& object, Shaders::Flat3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {}\n\n void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {\n _shader.setColor(0x747474_rgbf)\n .setTransformationProjectionMatrix(camera.projectionMatrix()*transformation);\n _mesh.draw(_shader);\n }\n\n private:\n Shaders::Flat3D& _shader;\n GL::Mesh& _mesh;\n};\n\nMouseInteractionExample::MouseInteractionExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} {\n \/* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x\n MSAA if we have enough DPI. *\/\n {\n const Vector2 dpiScaling = this->dpiScaling({});\n Configuration conf;\n conf.setTitle(\"Magnum Mouse Interaction Example\")\n .setSize(conf.size(), dpiScaling);\n GLConfiguration glConf;\n glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);\n if(!tryCreate(conf, glConf))\n create(conf, glConf.setSampleCount(0));\n }\n\n \/* Shaders, renderer setup *\/\n _vertexColorShader = Shaders::VertexColor3D{};\n _flatShader = Shaders::Flat3D{};\n GL::Renderer::enable(GL::Renderer::Feature::DepthTest);\n\n \/* Triangle data *\/\n const struct {\n Vector3 pos;\n Color3 color;\n } data[]{{{-1.0f, -1.0f, 0.0f}, 0xff0000_rgbf},\n {{ 1.0f, -1.0f, 0.0f}, 0x00ff00_rgbf},\n {{ 0.0f, 1.0f, 0.0f}, 0x0000ff_rgbf}};\n\n \/* Triangle mesh *\/\n GL::Buffer buffer;\n buffer.setData(data);\n _mesh = GL::Mesh{};\n _mesh.setCount(3)\n .addVertexBuffer(std::move(buffer), 0,\n Shaders::VertexColor3D::Position{},\n Shaders::VertexColor3D::Color3{});\n\n \/* Triangle object *\/\n auto triangle = new Object3D{&_scene};\n new VertexColorDrawable{*triangle, _vertexColorShader, _mesh, _drawables};\n\n \/* Grid *\/\n _grid = MeshTools::compile(Primitives::grid3DWireframe({15, 15}));\n auto grid = new Object3D{&_scene};\n (*grid)\n .rotateX(90.0_degf)\n .scale(Vector3{8.0f});\n new FlatDrawable{*grid, _flatShader, _grid, _drawables};\n\n \/* Set up the camera *\/\n _cameraObject = new Object3D{&_scene};\n (*_cameraObject)\n .translate(Vector3::zAxis(5.0f))\n .rotateX(-15.0_degf)\n .rotateY(30.0_degf);\n _camera = new SceneGraph::Camera3D{*_cameraObject};\n _camera->setProjectionMatrix(Matrix4::perspectiveProjection(\n 45.0_degf, Vector2{windowSize()}.aspectRatio(), 0.01f, 100.0f));\n\n \/* Initialize initial depth to the value at scene center *\/\n _lastDepth = ((_camera->projectionMatrix()*_camera->cameraMatrix()).transformPoint({}).z() + 1.0f)*0.5f;\n}\n\nFloat MouseInteractionExample::depthAt(const Vector2i& position) {\n const Vector2i fbPosition{position.x(), GL::defaultFramebuffer.viewport().sizeY() - position.y() - 1};\n\n GL::defaultFramebuffer.mapForRead(GL::DefaultFramebuffer::ReadAttachment::Front);\n Image2D data = GL::defaultFramebuffer.read(\n Range2Di::fromSize(fbPosition, Vector2i{1}).padded(Vector2i{2}),\n {GL::PixelFormat::DepthComponent, GL::PixelType::Float});\n\n return Math::min(Containers::arrayCast<const Float>(data.data()));\n}\n\nVector3 MouseInteractionExample::unproject(const Vector2i& position, Float depth) const {\n const Range2Di view = GL::defaultFramebuffer.viewport();\n const Vector2i fbPosition{position.x(), view.sizeY() - position.y() - 1};\n const Vector3 in{2*Vector2{fbPosition - view.min()}\/Vector2{view.size()} - Vector2{1.0f}, depth*2.0f - 1.0f};\n\n \/*\n Use the following to get global coordinates instead of camera-relative:\n\n (_cameraObject->absoluteTransformationMatrix()*_camera->projectionMatrix().inverted()).transformPoint(in)\n *\/\n return _camera->projectionMatrix().inverted().transformPoint(in);\n}\n\nvoid MouseInteractionExample::keyPressEvent(KeyEvent& event) {\n \/* Reset the transformation to the original view *\/\n if(event.key() == KeyEvent::Key::NumZero) {\n (*_cameraObject)\n .resetTransformation()\n .translate(Vector3::zAxis(5.0f))\n .rotateX(-15.0_degf)\n .rotateY(30.0_degf);\n redraw();\n return;\n\n \/* Axis-aligned view *\/\n } else if(event.key() == KeyEvent::Key::NumOne ||\n event.key() == KeyEvent::Key::NumThree ||\n event.key() == KeyEvent::Key::NumSeven)\n {\n \/* Start with current camera translation with the rotation inverted *\/\n const Vector3 viewTranslation = _cameraObject->transformation().rotationScaling().inverted()*_cameraObject->transformation().translation();\n\n \/* Front\/back *\/\n const Float multiplier = event.modifiers() & KeyEvent::Modifier::Ctrl ? -1.0f : 1.0f;\n\n Matrix4 transformation;\n if(event.key() == KeyEvent::Key::NumSeven) \/* Top\/bottom *\/\n transformation = Matrix4::rotationX(-90.0_degf*multiplier);\n else if(event.key() == KeyEvent::Key::NumOne) \/* Front\/back *\/\n transformation = Matrix4::rotationY(90.0_degf - 90.0_degf*multiplier);\n else if(event.key() == KeyEvent::Key::NumThree) \/* Right\/left *\/\n transformation = Matrix4::rotationY(90.0_degf*multiplier);\n else CORRADE_ASSERT_UNREACHABLE();\n\n _cameraObject->setTransformation(transformation*Matrix4::translation(viewTranslation));\n redraw();\n }\n}\n\nvoid MouseInteractionExample::mousePressEvent(MouseEvent& event) {\n \/* Due to compatibility reasons, scroll is also reported as a press event,\n so filter that out. Could be removed once MouseEvent::Button::Wheel is\n gone from Magnum. *\/\n if(event.button() != MouseEvent::Button::Left &&\n event.button() != MouseEvent::Button::Middle)\n return;\n\n const Float currentDepth = depthAt(event.position());\n const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth;\n _translationPoint = unproject(event.position(), depth);\n \/* Update the rotation point only if we're not zooming against infinite\n depth or if the original rotation point is not yet initialized *\/\n if(currentDepth != 1.0f || _rotationPoint.isZero()) {\n _rotationPoint = _translationPoint;\n _lastDepth = depth;\n }\n}\n\nvoid MouseInteractionExample::mouseMoveEvent(MouseMoveEvent& event) {\n if(_lastPosition == Vector2i{-1}) _lastPosition = event.position();\n const Vector2i delta = event.position() - _lastPosition;\n _lastPosition = event.position();\n\n if(!event.buttons()) return;\n\n \/* Translate *\/\n if(event.modifiers() & MouseMoveEvent::Modifier::Shift) {\n const Vector3 p = unproject(event.position(), _lastDepth);\n _cameraObject->translateLocal(_translationPoint - p); \/* is Z always 0? *\/\n _translationPoint = p;\n\n \/* Rotate around rotation point *\/\n } else _cameraObject->transformLocal(\n Matrix4::translation(_rotationPoint)*\n Matrix4::rotationX(-0.01_radf*delta.y())*\n Matrix4::rotationY(-0.01_radf*delta.x())*\n Matrix4::translation(-_rotationPoint));\n\n redraw();\n}\n\nvoid MouseInteractionExample::mouseScrollEvent(MouseScrollEvent& event) {\n const Float currentDepth = depthAt(event.position());\n const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth;\n const Vector3 p = unproject(event.position(), depth);\n \/* Update the rotation point only if we're not zooming against infinite\n depth or if the original rotation point is not yet initialized *\/\n if(currentDepth != 1.0f || _rotationPoint.isZero()) {\n _rotationPoint = p;\n _lastDepth = depth;\n }\n\n const Int direction = event.offset().y();\n if(!direction) return;\n\n \/* Move towards\/backwards the rotation point in cam coords *\/\n _cameraObject->translateLocal(_rotationPoint*(direction < 0 ? -1.0f : 1.0f)*0.1f);\n\n redraw();\n}\n\nvoid MouseInteractionExample::drawEvent() {\n GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth);\n\n _camera->draw(_drawables);\n\n swapBuffers();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::MouseInteractionExample)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef VK_OBJECT_HPP_\n#define VK_OBJECT_HPP_\n\n#include \"VkConfig.h\"\n#include \"VkDebug.hpp\"\n#include \"VkMemory.h\"\n\n#include <vulkan\/vulkan_core.h>\n#include <vulkan\/vk_icd.h>\n\nnamespace vk\n{\n\/\/ For use in the placement new to make it verbose that we're allocating an object using device memory\nstatic constexpr VkAllocationCallbacks* DEVICE_MEMORY = nullptr;\n\ntemplate<typename T, typename VkT, typename CreateInfo>\nstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n{\n\t*outObject = VK_NULL_HANDLE;\n\n\tsize_t size = T::ComputeRequiredAllocationSize(pCreateInfo);\n\tvoid* memory = nullptr;\n\tif(size)\n\t{\n\t\tmemory = vk::allocate(size, REQUIRED_MEMORY_ALIGNMENT, pAllocator, T::GetAllocationScope());\n\t\tif(!memory)\n\t\t{\n\t\t\treturn VK_ERROR_OUT_OF_HOST_MEMORY;\n\t\t}\n\t}\n\n\tauto object = new (pAllocator) T(pCreateInfo, memory);\n\n\tif(!object)\n\t{\n\t\tvk::deallocate(memory, pAllocator);\n\t\treturn VK_ERROR_OUT_OF_HOST_MEMORY;\n\t}\n\n\t*outObject = *object;\n\n\treturn VK_SUCCESS;\n}\n\ntemplate<typename T, typename VkT>\nclass ObjectBase\n{\npublic:\n\tusing VkType = VkT;\n\n\tvoid destroy(const VkAllocationCallbacks* pAllocator) {} \/\/ Method defined by objects to delete their content, if necessary\n\n\tvoid* operator new(size_t count, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\treturn vk::allocate(count, alignof(T), pAllocator, T::GetAllocationScope());\n\t}\n\n\tvoid operator delete(void* ptr, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\t\/\/ Should never happen\n\t\tASSERT(false);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n\t{\n\t\treturn vk::Create<T, VkT, CreateInfo>(pAllocator, pCreateInfo, outObject);\n\t}\n\n\tstatic constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_OBJECT; }\n\nprotected:\n\t\/\/ All derived classes should have deleted destructors\n\t~ObjectBase() {}\n};\n\ntemplate<typename T, typename VkT>\nclass Object : public ObjectBase<T, VkT>\n{\npublic:\n\toperator VkT()\n\t{\n\t\treturn reinterpret_cast<VkT>(this);\n\t}\n};\n\ntemplate<typename T, typename VkT>\nclass DispatchableObject\n{\n\tVK_LOADER_DATA loaderData = { ICD_LOADER_MAGIC };\n\n\tT object;\npublic:\n\tstatic constexpr VkSystemAllocationScope GetAllocationScope() { return T::GetAllocationScope(); }\n\n\ttemplate<typename ...Args>\n\tDispatchableObject(Args... args) : object(args...)\n\t{\n\t}\n\n\t~DispatchableObject() = delete;\n\n\tvoid destroy(const VkAllocationCallbacks* pAllocator)\n\t{\n\t\tobject.destroy(pAllocator);\n\t}\n\n\tvoid* operator new(size_t count, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\treturn vk::allocate(count, alignof(T), pAllocator, T::GetAllocationScope());\n\t}\n\n\tvoid operator delete(void* ptr, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\t\/\/ Should never happen\n\t\tASSERT(false);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n\t{\n\t\treturn vk::Create<DispatchableObject<T, VkT>, VkT, CreateInfo>(pAllocator, pCreateInfo, outObject);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic size_t ComputeRequiredAllocationSize(const CreateInfo* pCreateInfo)\n\t{\n\t\treturn T::ComputeRequiredAllocationSize(pCreateInfo);\n\t}\n\n\tstatic inline T* Cast(VkT vkObject)\n\t{\n\t\treturn &(reinterpret_cast<DispatchableObject<T, VkT>*>(vkObject)->object);\n\t}\n\n\toperator VkT()\n\t{\n\t\treturn reinterpret_cast<VkT>(this);\n\t}\n};\n\n} \/\/ namespace vk\n\n#endif \/\/ VK_OBJECT_HPP_\n<commit_msg>Allow null dispatchable objects<commit_after>\/\/ Copyright 2018 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef VK_OBJECT_HPP_\n#define VK_OBJECT_HPP_\n\n#include \"VkConfig.h\"\n#include \"VkDebug.hpp\"\n#include \"VkMemory.h\"\n\n#include <vulkan\/vulkan_core.h>\n#include <vulkan\/vk_icd.h>\n\nnamespace vk\n{\n\/\/ For use in the placement new to make it verbose that we're allocating an object using device memory\nstatic constexpr VkAllocationCallbacks* DEVICE_MEMORY = nullptr;\n\ntemplate<typename T, typename VkT, typename CreateInfo>\nstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n{\n\t*outObject = VK_NULL_HANDLE;\n\n\tsize_t size = T::ComputeRequiredAllocationSize(pCreateInfo);\n\tvoid* memory = nullptr;\n\tif(size)\n\t{\n\t\tmemory = vk::allocate(size, REQUIRED_MEMORY_ALIGNMENT, pAllocator, T::GetAllocationScope());\n\t\tif(!memory)\n\t\t{\n\t\t\treturn VK_ERROR_OUT_OF_HOST_MEMORY;\n\t\t}\n\t}\n\n\tauto object = new (pAllocator) T(pCreateInfo, memory);\n\n\tif(!object)\n\t{\n\t\tvk::deallocate(memory, pAllocator);\n\t\treturn VK_ERROR_OUT_OF_HOST_MEMORY;\n\t}\n\n\t*outObject = *object;\n\n\treturn VK_SUCCESS;\n}\n\ntemplate<typename T, typename VkT>\nclass ObjectBase\n{\npublic:\n\tusing VkType = VkT;\n\n\tvoid destroy(const VkAllocationCallbacks* pAllocator) {} \/\/ Method defined by objects to delete their content, if necessary\n\n\tvoid* operator new(size_t count, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\treturn vk::allocate(count, alignof(T), pAllocator, T::GetAllocationScope());\n\t}\n\n\tvoid operator delete(void* ptr, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\t\/\/ Should never happen\n\t\tASSERT(false);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n\t{\n\t\treturn vk::Create<T, VkT, CreateInfo>(pAllocator, pCreateInfo, outObject);\n\t}\n\n\tstatic constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_OBJECT; }\n\nprotected:\n\t\/\/ All derived classes should have deleted destructors\n\t~ObjectBase() {}\n};\n\ntemplate<typename T, typename VkT>\nclass Object : public ObjectBase<T, VkT>\n{\npublic:\n\toperator VkT()\n\t{\n\t\treturn reinterpret_cast<VkT>(this);\n\t}\n};\n\ntemplate<typename T, typename VkT>\nclass DispatchableObject\n{\n\tVK_LOADER_DATA loaderData = { ICD_LOADER_MAGIC };\n\n\tT object;\npublic:\n\tstatic constexpr VkSystemAllocationScope GetAllocationScope() { return T::GetAllocationScope(); }\n\n\ttemplate<typename ...Args>\n\tDispatchableObject(Args... args) : object(args...)\n\t{\n\t}\n\n\t~DispatchableObject() = delete;\n\n\tvoid destroy(const VkAllocationCallbacks* pAllocator)\n\t{\n\t\tobject.destroy(pAllocator);\n\t}\n\n\tvoid* operator new(size_t count, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\treturn vk::allocate(count, alignof(T), pAllocator, T::GetAllocationScope());\n\t}\n\n\tvoid operator delete(void* ptr, const VkAllocationCallbacks* pAllocator)\n\t{\n\t\t\/\/ Should never happen\n\t\tASSERT(false);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic VkResult Create(const VkAllocationCallbacks* pAllocator, const CreateInfo* pCreateInfo, VkT* outObject)\n\t{\n\t\treturn vk::Create<DispatchableObject<T, VkT>, VkT, CreateInfo>(pAllocator, pCreateInfo, outObject);\n\t}\n\n\ttemplate<typename CreateInfo>\n\tstatic size_t ComputeRequiredAllocationSize(const CreateInfo* pCreateInfo)\n\t{\n\t\treturn T::ComputeRequiredAllocationSize(pCreateInfo);\n\t}\n\n\tstatic inline T* Cast(VkT vkObject)\n\t{\n\t\treturn (vkObject == VK_NULL_HANDLE) ? nullptr :\n\t\t &(reinterpret_cast<DispatchableObject<T, VkT>*>(vkObject)->object);\n\t}\n\n\toperator VkT()\n\t{\n\t\treturn reinterpret_cast<VkT>(this);\n\t}\n};\n\n} \/\/ namespace vk\n\n#endif \/\/ VK_OBJECT_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"oop.hpp\"\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n#include \"gc\/inflated_headers.hpp\"\n\n#include <iostream>\n\nnamespace rubinius {\n \/**\n * Allocates a new InflatedHeader object for the specified obj ObjectHeader.\n *\n * \/param obj The ObjectHeader that is to be inflated.\n * \/returns the InflatedHeader representing the new inflated object header.\n *\/\n InflatedHeader* InflatedHeaders::allocate(ObjectHeader* obj) {\n bool needs_gc = false;\n InflatedHeader* header = allocator_->allocate(&needs_gc);\n header->set_object(obj);\n if(needs_gc) {\n state_->om->collect_mature_now = true;\n }\n return header;\n }\n\n \/**\n * Scans the list of InflatedHeader objects checking to see which are in use.\n * Those that do not have the appropriate mark value set are cleared and\n * added back to the free list. Chunks that are completely unused are removed\n * from the linked list.\n *\n * \/param mark The current value of the mark; only InflatedHeaders that bear\n * this mark will be retained.\n *\/\n void InflatedHeaders::deallocate_headers(int mark) {\n std::vector<bool> chunk_marks(allocator_->chunks_.size(), false);\n for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) {\n InflatedHeader* chunk = allocator_->chunks_[i];\n\n for(size_t j = 0; j < allocator_->cChunkSize; j++) {\n InflatedHeader* header = &chunk[j];\n\n if(header->in_use_p()) {\n if(header->marked_p(mark)) {\n chunk_marks[i] = true;\n break;\n } else {\n header->clear();\n }\n }\n }\n }\n\n allocator_->rebuild_freelist(&chunk_marks);\n }\n}\n<commit_msg>Don't break the loop when cleaning up handles<commit_after>#include \"oop.hpp\"\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n#include \"gc\/inflated_headers.hpp\"\n\n#include <iostream>\n\nnamespace rubinius {\n \/**\n * Allocates a new InflatedHeader object for the specified obj ObjectHeader.\n *\n * \/param obj The ObjectHeader that is to be inflated.\n * \/returns the InflatedHeader representing the new inflated object header.\n *\/\n InflatedHeader* InflatedHeaders::allocate(ObjectHeader* obj) {\n bool needs_gc = false;\n InflatedHeader* header = allocator_->allocate(&needs_gc);\n header->set_object(obj);\n if(needs_gc) {\n state_->om->collect_mature_now = true;\n }\n return header;\n }\n\n \/**\n * Scans the list of InflatedHeader objects checking to see which are in use.\n * Those that do not have the appropriate mark value set are cleared and\n * added back to the free list. Chunks that are completely unused are removed\n * from the linked list.\n *\n * \/param mark The current value of the mark; only InflatedHeaders that bear\n * this mark will be retained.\n *\/\n void InflatedHeaders::deallocate_headers(int mark) {\n std::vector<bool> chunk_marks(allocator_->chunks_.size(), false);\n for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) {\n InflatedHeader* chunk = allocator_->chunks_[i];\n\n for(size_t j = 0; j < allocator_->cChunkSize; j++) {\n InflatedHeader* header = &chunk[j];\n\n if(header->in_use_p()) {\n if(header->marked_p(mark)) {\n chunk_marks[i] = true;\n } else {\n header->clear();\n }\n }\n }\n }\n\n allocator_->rebuild_freelist(&chunk_marks);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"voyager\/rpc\/rpc_channel.h\"\n\n#include <string>\n\nnamespace voyager {\n\nRpcChannel::RpcChannel(EventLoop* loop)\n : loop_(loop),\n micros_(5 * 1000 * 1000) {\n}\n\nRpcChannel::~RpcChannel() {\n for (auto it : call_map_) {\n delete it.second.response;\n delete it.second.done;\n loop_->RemoveTimer(it.second.timer);\n }\n}\n\nvoid RpcChannel::CallMethod(const google::protobuf::MethodDescriptor* method,\n google::protobuf::RpcController* controller,\n const google::protobuf::Message* request,\n google::protobuf::Message* response,\n google::protobuf::Closure* done) {\n int id = num_.GetNext();\n RpcMessage msg;\n msg.set_id(id);\n msg.set_service_name(method->service()->full_name());\n msg.set_method_name(method->name());\n msg.set_data(request->SerializeAsString());\n\n std::string s;\n if (codec_.SerializeToString(msg, &s)) {\n conn_->SendMessage(s);\n Timer* t = loop_->RunAfter(\n micros_, std::bind(&RpcChannel::TimeoutHandler, this, id));\n port::MutexLock lock(&mutex_);\n call_map_[id] = CallData(response, done, t);\n } else {\n if (error_cb_) {\n error_cb_(ERROR_CODE_UNKNOWN);\n }\n delete response;\n delete done;\n }\n}\n\nvoid RpcChannel::OnMessage(const TcpConnectionPtr& p, Buffer* buf) {\n RpcMessage msg;\n bool res = codec_.ParseFromBuffer(buf, &msg);\n while (res) {\n OnResponse(msg);\n res = codec_.ParseFromBuffer(buf, &msg);\n }\n}\n\nvoid RpcChannel::TimeoutHandler(int id) {\n {\n port::MutexLock lock(&mutex_);\n auto it = call_map_.find(id);\n if (it != call_map_.end()) {\n delete it->second.response;\n delete it->second.done;\n call_map_.erase(it);\n }\n }\n if (error_cb_) {\n error_cb_(ERROR_CODE_TIMEOUT);\n }\n}\n\nvoid RpcChannel::OnResponse(const RpcMessage& msg) {\n int id = msg.id();\n CallData data;\n {\n port::MutexLock lock(&mutex_);\n auto it = call_map_.find(id);\n if (it != call_map_.end()) {\n data = it->second;\n call_map_.erase(it);\n }\n }\n loop_->RemoveTimer(data.timer);\n\n if (msg.error() == ERROR_CODE_OK) {\n if (data.response) {\n data.response->ParseFromString(msg.data());\n }\n if (data.done) {\n data.done->Run();\n }\n } else {\n if (error_cb_) {\n error_cb_(msg.error());\n }\n delete data.done;\n }\n delete data.response;\n}\n\n} \/\/ namespace voyager\n<commit_msg>fix rpc timer<commit_after>\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"voyager\/rpc\/rpc_channel.h\"\n\n#include <string>\n\nnamespace voyager {\n\nRpcChannel::RpcChannel(EventLoop* loop)\n : loop_(loop),\n micros_(0) {\n}\n\nRpcChannel::~RpcChannel() {\n for (auto it : call_map_) {\n delete it.second.response;\n delete it.second.done;\n if (it.second.timer) {\n loop_->RemoveTimer(it.second.timer);\n }\n }\n}\n\nvoid RpcChannel::CallMethod(const google::protobuf::MethodDescriptor* method,\n google::protobuf::RpcController* controller,\n const google::protobuf::Message* request,\n google::protobuf::Message* response,\n google::protobuf::Closure* done) {\n int id = num_.GetNext();\n RpcMessage msg;\n msg.set_id(id);\n msg.set_service_name(method->service()->full_name());\n msg.set_method_name(method->name());\n msg.set_data(request->SerializeAsString());\n\n std::string s;\n if (codec_.SerializeToString(msg, &s)) {\n conn_->SendMessage(s);\n Timer* t = nullptr;\n if (micros_ > 0) {\n loop_->RunAfter(\n micros_, std::bind(&RpcChannel::TimeoutHandler, this, id));\n }\n port::MutexLock lock(&mutex_);\n call_map_[id] = CallData(response, done, t);\n } else {\n if (error_cb_) {\n error_cb_(ERROR_CODE_UNKNOWN);\n }\n delete response;\n delete done;\n }\n}\n\nvoid RpcChannel::OnMessage(const TcpConnectionPtr& p, Buffer* buf) {\n RpcMessage msg;\n bool res = codec_.ParseFromBuffer(buf, &msg);\n while (res) {\n OnResponse(msg);\n res = codec_.ParseFromBuffer(buf, &msg);\n }\n}\n\nvoid RpcChannel::TimeoutHandler(int id) {\n {\n port::MutexLock lock(&mutex_);\n auto it = call_map_.find(id);\n if (it != call_map_.end()) {\n delete it->second.response;\n delete it->second.done;\n call_map_.erase(it);\n }\n }\n if (error_cb_) {\n error_cb_(ERROR_CODE_TIMEOUT);\n }\n}\n\nvoid RpcChannel::OnResponse(const RpcMessage& msg) {\n int id = msg.id();\n CallData data;\n {\n port::MutexLock lock(&mutex_);\n auto it = call_map_.find(id);\n if (it != call_map_.end()) {\n data = it->second;\n call_map_.erase(it);\n }\n }\n if (data.timer) {\n loop_->RemoveTimer(data.timer);\n }\n if (msg.error() == ERROR_CODE_OK) {\n if (data.response) {\n data.response->ParseFromString(msg.data());\n }\n if (data.done) {\n data.done->Run();\n }\n } else {\n if (error_cb_) {\n error_cb_(msg.error());\n }\n delete data.done;\n }\n delete data.response;\n}\n\n} \/\/ namespace voyager\n<|endoftext|>"} {"text":"<commit_before>\/** \\file call_main.cpp\n *\n * Defines the \"vg call\" subcommand, which calls variation from a graph and a pileup.\n *\/\n\n#include <omp.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include <list>\n#include <fstream>\n\n#include \"subcommand.hpp\"\n\n#include \"..\/vg.hpp\"\n#include \"..\/caller.hpp\"\n\n\n\nusing namespace std;\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_call(char** argv) {\n cerr << \"usage: \" << argv[0] << \" call [options] <graph.vg> <pileup.vgpu> > output.vcf\" << endl\n << \"Output variant calls in VCF format given a graph and pileup\" << endl\n << endl\n << \"options:\" << endl\n << \" -d, --min_depth INT minimum depth of pileup [\" << Caller::Default_min_depth <<\"]\" << endl\n << \" -e, --max_depth INT maximum depth of pileup [\" << Caller::Default_max_depth <<\"]\" << endl\n << \" -s, --min_support INT minimum number of reads required to support snp [\" << Caller::Default_min_support <<\"]\" << endl\n << \" -f, --min_frac FLOAT minimum percentage of reads required to support snp[\" << Caller::Default_min_frac <<\"]\" << endl\n << \" -q, --default_read_qual N phred quality score to use if none found in the pileup [\"\n << (int)Caller::Default_default_quality << \"]\" << endl\n << \" -b, --max_strand_bias FLOAT limit to absolute difference between 0.5 and proportion of supporting reads on reverse strand. [\" << Caller::Default_max_strand_bias << \"]\" << endl\n << \" -a, --link-alts add all possible edges between adjacent alts\" << endl\n << \" -A, --aug-graph FILE write out the agumented graph in vg format\" << endl\n << \" -r, --ref PATH use the given path name as the reference path\" << endl\n << \" -c, --contig NAME use the given name as the VCF contig name\" << endl\n << \" -S, --sample NAME name the sample in the VCF with the given name [SAMPLE]\" << endl\n << \" -o, --offset INT offset variant positions by this amount in VCF [0]\" << endl\n << \" -l, --length INT override total sequence length in VCF\" << endl\n << \" -U, --subgraph expect a subgraph and ignore extra pileup entries outside it\" << endl\n << \" -P, --pileup write pileup under VCF lines (for debugging, output not valid VCF)\" << endl\n << \" -D, --depth INT maximum depth for path search [default 10 nodes]\" << endl\n << \" -F, --min_cov_frac FLOAT min fraction of average coverage at which to call [0.0]\" << endl\n << \" -H, --max_het_bias FLOAT max imbalance factor between alts to call heterozygous [3]\" << endl\n << \" -R, --max_ref_bias FLOAT max imbalance factor between ref and alts to call heterozygous ref [4]\" << endl\n << \" -M, --bias_mult FLOAT multiplier for bias limits for indels as opposed to substitutions [1]\" << endl\n << \" -n, --min_count INT min total supporting read count to call a variant [1]\" << endl\n << \" -B, --bin_size INT bin size used for counting coverage [250]\" << endl\n << \" -C, --exp_coverage INT specify expected coverage (instead of computing on reference)\" << endl\n << \" -O, --no_overlap don't emit new variants that overlap old ones\" << endl\n << \" -u, --use_avg_support use average instead of minimum support\" << endl\n << \" -I, --singleallelic disable support for multiallelic sites\" << endl\n << \" -E, --min_mad min. minimum allele depth required to PASS filter [5]\" << endl\n << \" -h, --help print this help message\" << endl\n << \" -p, --progress show progress\" << endl\n << \" -v, --verbose print information and warnings about vcf generation\" << endl\n << \" -t, --threads N number of threads to use\" << endl;\n}\n\nint main_call(int argc, char** argv) {\n\n if (argc <= 3) {\n help_call(argv);\n return 1;\n }\n\n double het_prior = Caller::Default_het_prior;\n int min_depth = Caller::Default_min_depth;\n int max_depth = Caller::Default_max_depth;\n int min_support = Caller::Default_min_support;\n double min_frac = Caller::Default_min_frac;\n int default_read_qual = Caller::Default_default_quality;\n double max_strand_bias = Caller::Default_max_strand_bias;\n string aug_file;\n bool bridge_alts = false;\n \n \n \n \/\/ Should we expect a subgraph and ignore pileups for missing nodes\/edges?\n bool expectSubgraph = false;\n \n \/\/ Should we annotate the VCF with pileup info?\n bool pileupAnnotate = false;\n\n \/\/ This manages conversion from an augmented graph to a VCF, and makes the\n \/\/ actual calls.\n Call2Vcf call2vcf;\n\n bool show_progress = false;\n int thread_count = 1;\n\n int c;\n optind = 2; \/\/ force optind past command positional arguments\n while (true) {\n static struct option long_options[] =\n {\n {\"min_depth\", required_argument, 0, 'd'},\n {\"max_depth\", required_argument, 0, 'e'},\n {\"min_support\", required_argument, 0, 's'},\n {\"min_frac\", required_argument, 0, 'f'},\n {\"default_read_qual\", required_argument, 0, 'q'},\n {\"max_strand_bias\", required_argument, 0, 'b'},\n {\"aug_graph\", required_argument, 0, 'A'},\n {\"link-alts\", no_argument, 0, 'a'},\n {\"progress\", no_argument, 0, 'p'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"threads\", required_argument, 0, 't'},\n {\"ref\", required_argument, 0, 'r'},\n {\"contig\", required_argument, 0, 'c'},\n {\"sample\", required_argument, 0, 'S'},\n {\"offset\", required_argument, 0, 'o'},\n {\"depth\", required_argument, 0, 'D'},\n {\"length\", required_argument, 0, 'l'},\n {\"subgraph\", no_argument, 0, 'U'},\n {\"pileup\", no_argument, 0, 'P'},\n {\"min_cov_frac\", required_argument, 0, 'F'},\n {\"max_het_bias\", required_argument, 0, 'H'},\n {\"max_ref_bias\", required_argument, 0, 'R'},\n {\"bias_mult\", required_argument, 0, 'M'},\n {\"min_count\", required_argument, 0, 'n'},\n {\"bin_size\", required_argument, 0, 'B'},\n {\"avg_coverage\", required_argument, 0, 'C'},\n {\"no_overlap\", no_argument, 0, 'O'},\n {\"use_avg_support\", no_argument, 0, 'u'},\n {\"min_mad\", required_argument, 0, 'E'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n };\n\n int option_index = 0;\n c = getopt_long (argc, argv, \"d:e:s:f:q:b:A:apvt:r:c:S:o:D:l:UPF:H:R:M:n:B:C:OuE:h\",\n long_options, &option_index);\n\n \/* Detect the end of the options. *\/\n if (c == -1)\n break;\n\n switch (c)\n {\n case 'd':\n min_depth = atoi(optarg);\n break;\n case 'e':\n max_depth = atoi(optarg);\n break;\n case 's':\n min_support = atoi(optarg);\n break;\n case 'f':\n min_frac = atof(optarg);\n break;\n case 'q':\n default_read_qual = atoi(optarg);\n break;\n case 'b':\n max_strand_bias = atof(optarg);\n break;\n case 'A':\n aug_file = optarg;\n break;\n case 'a':\n bridge_alts = true;\n break;\n \/\/ old glenn2vcf opts start here\n case 'r':\n \/\/ Set the reference path name\n call2vcf.refPathName = optarg;\n break;\n case 'c':\n \/\/ Set the contig name\n call2vcf.contigName = optarg;\n break;\n case 'S':\n \/\/ Set the sample name\n call2vcf.sampleName = optarg;\n break;\n case 'o':\n \/\/ Offset variants\n call2vcf.variantOffset = std::stoll(optarg);\n break;\n case 'D':\n \/\/ Limit max depth for pathing to primary path\n call2vcf.maxDepth = std::stoll(optarg);\n break;\n case 'l':\n \/\/ Set a length override\n call2vcf.lengthOverride = std::stoll(optarg);\n break;\n case 'U':\n expectSubgraph = true;\n break;\n case 'P':\n pileupAnnotate = true;\n break;\n case 'F':\n \/\/ Set min fraction of average coverage for a call\n call2vcf.minFractionForCall = std::stod(optarg);\n break;\n case 'H':\n \/\/ Set max factor between reads on one alt and reads on the other\n \/\/ alt for calling a het.\n call2vcf.maxHetBias = std::stod(optarg);\n break;\n case 'R':\n \/\/ Set max factor between reads on ref and reads on the other\n \/\/ alt for calling a homo ref.\n call2vcf.maxRefHetBias = std::stod(optarg);\n break;\n case 'M':\n \/\/ Set multiplier for bias limits for indels\n call2vcf.indelBiasMultiple = std::stod(optarg);\n break;\n case 'n':\n \/\/ How many reads need to touch an allele before we are willing to\n \/\/ call it?\n call2vcf.minTotalSupportForCall = std::stoll(optarg);\n break;\n case 'B':\n \/\/ Set the reference bin size\n call2vcf.refBinSize = std::stoll(optarg);\n break;\n case 'C':\n \/\/ Override expected coverage\n call2vcf.expCoverage = std::stoll(optarg);\n break;\n case 'O':\n \/\/ Suppress variants that overlap others\n call2vcf.suppress_overlaps = true;\n break;\n case 'u':\n \/\/ Average (isntead of min) support\n call2vcf.useAverageSupport = true;\n break;\n case 'E':\n \/\/ Minimum min-allele-depth required to give Filter column a PASS\n call2vcf.min_mad_for_filter = std::stoi(optarg);\n break;\n case 'p':\n show_progress = true;\n break;\n case 'v':\n call2vcf.verbose = true;\n break;\n case 't':\n thread_count = atoi(optarg);\n break;\n case 'h':\n case '?':\n \/* getopt_long already printed an error message. *\/\n help_call(argv);\n exit(1);\n break;\n default:\n abort ();\n }\n }\n omp_set_num_threads(thread_count);\n thread_count = get_thread_count();\n\n \/\/ Parse the arguments\n if (optind >= argc) {\n help_call(argv);\n return 1;\n }\n string graph_file_name = get_input_file_name(optind, argc, argv);\n if (optind >= argc) {\n help_call(argv);\n return 1;\n }\n string pileup_file_name = get_input_file_name(optind, argc, argv);\n \n if (pileup_file_name == \"-\" && graph_file_name == \"-\") {\n cerr << \"error: graph and pileup can't both be from stdin.\" << endl;\n exit(1);\n }\n \n \/\/ read the graph\n if (show_progress) {\n cerr << \"Reading input graph\" << endl;\n }\n VG* graph;\n get_input_file(graph_file_name, [&](istream& in) {\n graph = new VG(in);\n });\n\n if (show_progress) {\n cerr << \"Computing augmented graph\" << endl;\n }\n Caller caller(graph,\n het_prior, min_depth, max_depth, min_support,\n min_frac, Caller::Default_min_log_likelihood,\n default_read_qual, max_strand_bias, bridge_alts);\n\n \/\/ setup pileup stream\n get_input_file(pileup_file_name, [&](istream& pileup_stream) {\n \/\/ compute the augmented graph\n function<void(Pileup&)> lambda = [&](Pileup& pileup) {\n for (int i = 0; i < pileup.node_pileups_size(); ++i) {\n if (!graph->has_node(pileup.node_pileups(i).node_id())) {\n \/\/ This pileup doesn't belong in this graph\n if(!expectSubgraph) {\n throw runtime_error(\"Found pileup for nonexistent node \" + to_string(pileup.node_pileups(i).node_id()));\n }\n \/\/ If that's expected, just skip it\n continue;\n }\n \/\/ Send approved pileups to the caller\n caller.call_node_pileup(pileup.node_pileups(i));\n }\n for (int i = 0; i < pileup.edge_pileups_size(); ++i) {\n if (!graph->has_edge(pileup.edge_pileups(i).edge())) {\n \/\/ This pileup doesn't belong in this graph\n if(!expectSubgraph) {\n throw runtime_error(\"Found pileup for nonexistent edge \" + pb2json(pileup.edge_pileups(i).edge()));\n }\n \/\/ If that's expected, just skip it\n continue;\n }\n \/\/ Send approved pileups to the caller\n caller.call_edge_pileup(pileup.edge_pileups(i));\n }\n };\n stream::for_each(pileup_stream, lambda);\n });\n \n \/\/ map the edges from original graph\n if (show_progress) {\n cerr << \"Mapping edges into augmented graph\" << endl;\n }\n caller.update_augmented_graph();\n\n \/\/ map the paths from the original graph\n if (show_progress) {\n cerr << \"Mapping paths into augmented graph\" << endl;\n }\n caller.map_paths();\n\n if (!aug_file.empty()) {\n \/\/ write the augmented graph\n if (show_progress) {\n cerr << \"Writing augmented graph\" << endl;\n }\n ofstream aug_stream(aug_file.c_str());\n caller.write_augmented_graph(aug_stream, false);\n }\n \n if (show_progress) {\n cerr << \"Calling variants\" << endl;\n }\n\n \/\/ project the augmented graph to a reference path\n \/\/ in order to create a VCF of calls.\n call2vcf.call(caller._augmented_graph,\n pileupAnnotate ? pileup_file_name : string());\n\n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_call(\"call\", \"call variants on a graph from a pileup\", main_call);\n\n<commit_msg>Change underscore options to dashes like the other subcommands use<commit_after>\/** \\file call_main.cpp\n *\n * Defines the \"vg call\" subcommand, which calls variation from a graph and a pileup.\n *\/\n\n#include <omp.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include <list>\n#include <fstream>\n\n#include \"subcommand.hpp\"\n\n#include \"..\/vg.hpp\"\n#include \"..\/caller.hpp\"\n\n\n\nusing namespace std;\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_call(char** argv) {\n cerr << \"usage: \" << argv[0] << \" call [options] <graph.vg> <pileup.vgpu> > output.vcf\" << endl\n << \"Output variant calls in VCF format given a graph and pileup\" << endl\n << endl\n << \"options:\" << endl\n << \" -d, --min-depth INT minimum depth of pileup [\" << Caller::Default_min_depth <<\"]\" << endl\n << \" -e, --max-depth INT maximum depth of pileup [\" << Caller::Default_max_depth <<\"]\" << endl\n << \" -s, --min-support INT minimum number of reads required to support snp [\" << Caller::Default_min_support <<\"]\" << endl\n << \" -f, --min-frac FLOAT minimum percentage of reads required to support snp[\" << Caller::Default_min_frac <<\"]\" << endl\n << \" -q, --default-read-qual N phred quality score to use if none found in the pileup [\"\n << (int)Caller::Default_default_quality << \"]\" << endl\n << \" -b, --max-strand-bias FLOAT limit to absolute difference between 0.5 and proportion of supporting reads on reverse strand. [\" << Caller::Default_max_strand_bias << \"]\" << endl\n << \" -a, --link-alts add all possible edges between adjacent alts\" << endl\n << \" -A, --aug-graph FILE write out the agumented graph in vg format\" << endl\n << \" -r, --ref PATH use the given path name as the reference path\" << endl\n << \" -c, --contig NAME use the given name as the VCF contig name\" << endl\n << \" -S, --sample NAME name the sample in the VCF with the given name [SAMPLE]\" << endl\n << \" -o, --offset INT offset variant positions by this amount in VCF [0]\" << endl\n << \" -l, --length INT override total sequence length in VCF\" << endl\n << \" -U, --subgraph expect a subgraph and ignore extra pileup entries outside it\" << endl\n << \" -P, --pileup write pileup under VCF lines (for debugging, output not valid VCF)\" << endl\n << \" -D, --depth INT maximum depth for path search [default 10 nodes]\" << endl\n << \" -F, --min-cov-frac FLOAT min fraction of average coverage at which to call [0.0]\" << endl\n << \" -H, --max-het-bias FLOAT max imbalance factor between alts to call heterozygous [3]\" << endl\n << \" -R, --max-ref-bias FLOAT max imbalance factor between ref and alts to call heterozygous ref [4]\" << endl\n << \" -M, --bias-mult FLOAT multiplier for bias limits for indels as opposed to substitutions [1]\" << endl\n << \" -n, --min-count INT min total supporting read count to call a variant [1]\" << endl\n << \" -B, --bin-size INT bin size used for counting coverage [250]\" << endl\n << \" -C, --exp-coverage INT specify expected coverage (instead of computing on reference)\" << endl\n << \" -O, --no-overlap don't emit new variants that overlap old ones\" << endl\n << \" -u, --use-avg-support use average instead of minimum support\" << endl\n << \" -I, --singleallelic disable support for multiallelic sites\" << endl\n << \" -E, --min_mad min. minimum allele depth required to PASS filter [5]\" << endl\n << \" -h, --help print this help message\" << endl\n << \" -p, --progress show progress\" << endl\n << \" -v, --verbose print information and warnings about vcf generation\" << endl\n << \" -t, --threads N number of threads to use\" << endl;\n}\n\nint main_call(int argc, char** argv) {\n\n if (argc <= 3) {\n help_call(argv);\n return 1;\n }\n\n double het_prior = Caller::Default_het_prior;\n int min_depth = Caller::Default_min_depth;\n int max_depth = Caller::Default_max_depth;\n int min_support = Caller::Default_min_support;\n double min_frac = Caller::Default_min_frac;\n int default_read_qual = Caller::Default_default_quality;\n double max_strand_bias = Caller::Default_max_strand_bias;\n string aug_file;\n bool bridge_alts = false;\n \n \n \n \/\/ Should we expect a subgraph and ignore pileups for missing nodes\/edges?\n bool expectSubgraph = false;\n \n \/\/ Should we annotate the VCF with pileup info?\n bool pileupAnnotate = false;\n\n \/\/ This manages conversion from an augmented graph to a VCF, and makes the\n \/\/ actual calls.\n Call2Vcf call2vcf;\n\n bool show_progress = false;\n int thread_count = 1;\n\n int c;\n optind = 2; \/\/ force optind past command positional arguments\n while (true) {\n static struct option long_options[] =\n {\n {\"min-depth\", required_argument, 0, 'd'},\n {\"max-depth\", required_argument, 0, 'e'},\n {\"min-support\", required_argument, 0, 's'},\n {\"min-frac\", required_argument, 0, 'f'},\n {\"default-read-qual\", required_argument, 0, 'q'},\n {\"max-strand-bias\", required_argument, 0, 'b'},\n {\"aug-graph\", required_argument, 0, 'A'},\n {\"link-alts\", no_argument, 0, 'a'},\n {\"progress\", no_argument, 0, 'p'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"threads\", required_argument, 0, 't'},\n {\"ref\", required_argument, 0, 'r'},\n {\"contig\", required_argument, 0, 'c'},\n {\"sample\", required_argument, 0, 'S'},\n {\"offset\", required_argument, 0, 'o'},\n {\"depth\", required_argument, 0, 'D'},\n {\"length\", required_argument, 0, 'l'},\n {\"subgraph\", no_argument, 0, 'U'},\n {\"pileup\", no_argument, 0, 'P'},\n {\"min-cov-frac\", required_argument, 0, 'F'},\n {\"max-het-bias\", required_argument, 0, 'H'},\n {\"max-ref-bias\", required_argument, 0, 'R'},\n {\"bias-mult\", required_argument, 0, 'M'},\n {\"min-count\", required_argument, 0, 'n'},\n {\"bin-size\", required_argument, 0, 'B'},\n {\"avg-coverage\", required_argument, 0, 'C'},\n {\"no-overlap\", no_argument, 0, 'O'},\n {\"use-avg-support\", no_argument, 0, 'u'},\n {\"min-mad\", required_argument, 0, 'E'},\n {\"help\", no_argument, 0, 'h'},\n {0, 0, 0, 0}\n };\n\n int option_index = 0;\n c = getopt_long (argc, argv, \"d:e:s:f:q:b:A:apvt:r:c:S:o:D:l:UPF:H:R:M:n:B:C:OuE:h\",\n long_options, &option_index);\n\n \/* Detect the end of the options. *\/\n if (c == -1)\n break;\n\n switch (c)\n {\n case 'd':\n min_depth = atoi(optarg);\n break;\n case 'e':\n max_depth = atoi(optarg);\n break;\n case 's':\n min_support = atoi(optarg);\n break;\n case 'f':\n min_frac = atof(optarg);\n break;\n case 'q':\n default_read_qual = atoi(optarg);\n break;\n case 'b':\n max_strand_bias = atof(optarg);\n break;\n case 'A':\n aug_file = optarg;\n break;\n case 'a':\n bridge_alts = true;\n break;\n \/\/ old glenn2vcf opts start here\n case 'r':\n \/\/ Set the reference path name\n call2vcf.refPathName = optarg;\n break;\n case 'c':\n \/\/ Set the contig name\n call2vcf.contigName = optarg;\n break;\n case 'S':\n \/\/ Set the sample name\n call2vcf.sampleName = optarg;\n break;\n case 'o':\n \/\/ Offset variants\n call2vcf.variantOffset = std::stoll(optarg);\n break;\n case 'D':\n \/\/ Limit max depth for pathing to primary path\n call2vcf.maxDepth = std::stoll(optarg);\n break;\n case 'l':\n \/\/ Set a length override\n call2vcf.lengthOverride = std::stoll(optarg);\n break;\n case 'U':\n expectSubgraph = true;\n break;\n case 'P':\n pileupAnnotate = true;\n break;\n case 'F':\n \/\/ Set min fraction of average coverage for a call\n call2vcf.minFractionForCall = std::stod(optarg);\n break;\n case 'H':\n \/\/ Set max factor between reads on one alt and reads on the other\n \/\/ alt for calling a het.\n call2vcf.maxHetBias = std::stod(optarg);\n break;\n case 'R':\n \/\/ Set max factor between reads on ref and reads on the other\n \/\/ alt for calling a homo ref.\n call2vcf.maxRefHetBias = std::stod(optarg);\n break;\n case 'M':\n \/\/ Set multiplier for bias limits for indels\n call2vcf.indelBiasMultiple = std::stod(optarg);\n break;\n case 'n':\n \/\/ How many reads need to touch an allele before we are willing to\n \/\/ call it?\n call2vcf.minTotalSupportForCall = std::stoll(optarg);\n break;\n case 'B':\n \/\/ Set the reference bin size\n call2vcf.refBinSize = std::stoll(optarg);\n break;\n case 'C':\n \/\/ Override expected coverage\n call2vcf.expCoverage = std::stoll(optarg);\n break;\n case 'O':\n \/\/ Suppress variants that overlap others\n call2vcf.suppress_overlaps = true;\n break;\n case 'u':\n \/\/ Average (isntead of min) support\n call2vcf.useAverageSupport = true;\n break;\n case 'E':\n \/\/ Minimum min-allele-depth required to give Filter column a PASS\n call2vcf.min_mad_for_filter = std::stoi(optarg);\n break;\n case 'p':\n show_progress = true;\n break;\n case 'v':\n call2vcf.verbose = true;\n break;\n case 't':\n thread_count = atoi(optarg);\n break;\n case 'h':\n case '?':\n \/* getopt_long already printed an error message. *\/\n help_call(argv);\n exit(1);\n break;\n default:\n abort ();\n }\n }\n omp_set_num_threads(thread_count);\n thread_count = get_thread_count();\n\n \/\/ Parse the arguments\n if (optind >= argc) {\n help_call(argv);\n return 1;\n }\n string graph_file_name = get_input_file_name(optind, argc, argv);\n if (optind >= argc) {\n help_call(argv);\n return 1;\n }\n string pileup_file_name = get_input_file_name(optind, argc, argv);\n \n if (pileup_file_name == \"-\" && graph_file_name == \"-\") {\n cerr << \"error: graph and pileup can't both be from stdin.\" << endl;\n exit(1);\n }\n \n \/\/ read the graph\n if (show_progress) {\n cerr << \"Reading input graph\" << endl;\n }\n VG* graph;\n get_input_file(graph_file_name, [&](istream& in) {\n graph = new VG(in);\n });\n\n if (show_progress) {\n cerr << \"Computing augmented graph\" << endl;\n }\n Caller caller(graph,\n het_prior, min_depth, max_depth, min_support,\n min_frac, Caller::Default_min_log_likelihood,\n default_read_qual, max_strand_bias, bridge_alts);\n\n \/\/ setup pileup stream\n get_input_file(pileup_file_name, [&](istream& pileup_stream) {\n \/\/ compute the augmented graph\n function<void(Pileup&)> lambda = [&](Pileup& pileup) {\n for (int i = 0; i < pileup.node_pileups_size(); ++i) {\n if (!graph->has_node(pileup.node_pileups(i).node_id())) {\n \/\/ This pileup doesn't belong in this graph\n if(!expectSubgraph) {\n throw runtime_error(\"Found pileup for nonexistent node \" + to_string(pileup.node_pileups(i).node_id()));\n }\n \/\/ If that's expected, just skip it\n continue;\n }\n \/\/ Send approved pileups to the caller\n caller.call_node_pileup(pileup.node_pileups(i));\n }\n for (int i = 0; i < pileup.edge_pileups_size(); ++i) {\n if (!graph->has_edge(pileup.edge_pileups(i).edge())) {\n \/\/ This pileup doesn't belong in this graph\n if(!expectSubgraph) {\n throw runtime_error(\"Found pileup for nonexistent edge \" + pb2json(pileup.edge_pileups(i).edge()));\n }\n \/\/ If that's expected, just skip it\n continue;\n }\n \/\/ Send approved pileups to the caller\n caller.call_edge_pileup(pileup.edge_pileups(i));\n }\n };\n stream::for_each(pileup_stream, lambda);\n });\n \n \/\/ map the edges from original graph\n if (show_progress) {\n cerr << \"Mapping edges into augmented graph\" << endl;\n }\n caller.update_augmented_graph();\n\n \/\/ map the paths from the original graph\n if (show_progress) {\n cerr << \"Mapping paths into augmented graph\" << endl;\n }\n caller.map_paths();\n\n if (!aug_file.empty()) {\n \/\/ write the augmented graph\n if (show_progress) {\n cerr << \"Writing augmented graph\" << endl;\n }\n ofstream aug_stream(aug_file.c_str());\n caller.write_augmented_graph(aug_stream, false);\n }\n \n if (show_progress) {\n cerr << \"Calling variants\" << endl;\n }\n\n \/\/ project the augmented graph to a reference path\n \/\/ in order to create a VCF of calls.\n call2vcf.call(caller._augmented_graph,\n pileupAnnotate ? pileup_file_name : string());\n\n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_call(\"call\", \"call variants on a graph from a pileup\", main_call);\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ROCKET_SYSTEM_HPP_\n#define ROCKET_SYSTEM_HPP_\n\n#include \"system\/vehicle_system.hpp\"\n#include \"util\/optional.hpp\"\n\n\/\/ Communication\n#include \"communication\/communicator.hpp\"\n#include \"communication\/message_listener.hpp\"\n\n\/\/ Control\n#include \"controller\/position_controller.hpp\"\n#include \"controller\/controller_pipeline.hpp\"\n#include \"controller\/setpoint_types.hpp\"\n#include \"controller\/zero_controller.hpp\"\n#include \"input\/input_source.hpp\"\n#include \"motor\/motor_mapper.hpp\"\n#include \"motor\/pwm_device_group.hpp\"\n\n\/\/ Filesystem\n#include \"filesystem\/logger.hpp\"\n\n\/\/ Platform\n#include \"variant\/digital_platform.hpp\"\n#include \"variant\/pwm_platform.hpp\"\n#include \"variant\/platform.hpp\"\n\n\/\/ World estimation\n#include \"estimator\/world_estimator.hpp\"\n\n\/\/ Sensors\n#include \"sensor\/sensor_measurements.hpp\"\n\nenum class RocketState {\n DISARMED,\n PRE_ARM,\n ARMED,\n FLIGHT,\n APOGEE,\n MICROGRAVITY, \/\/ Dummy state to keep state numbers the same as payload. Firmware doesn't care, but this makes the current ground station simpler. It all needs to be rethought anyway.\n DESCENT,\n RECOVERY\n};\n\nclass RocketSystem : public VehicleSystem, public MessageListener {\npublic:\n RocketSystem(\n Accelerometer& accel,\n optional<Accelerometer *> accelH,\n optional<Barometer *> bar,\n optional<Geiger *> ggr,\n optional<GPS *> gps,\n Gyroscope& gyr,\n optional<Magnetometer *> mag,\n WorldEstimator& estimator, InputSource& inputSource,\n MotorMapper& motorMapper, Communicator& communicator, Logger& logger,\n Platform& platform);\n\n void update() override;\n bool healthy();\n\n void on(const protocol::message::set_arm_state_message_t& m) override;\n\nprivate:\n Accelerometer& accel;\n optional<Accelerometer *> accelH;\n optional<Barometer *> bar;\n optional<Geiger *> ggr;\n optional<GPS *> gps;\n Gyroscope& gyr;\n optional<Magnetometer *> mag;\n\n WorldEstimator& estimator;\n InputSource& inputSource;\n\n PositionController posController;\n ControllerPipeline<ActuatorSetpoint> pipeline;\n\n ZeroController<ActuatorSetpoint> zeroController;\n\n MotorMapper& motorMapper;\n Platform& platform;\n\n RateLimitedStream systemStream;\n Logger& logger;\n\n void updateStreams(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Pin config\n *\/\n \/\/ ADC\n const uint8_t PIN_EXT_TEMP_THERM_CH = 0; \/\/ PC0\n \/\/ Digital\n const uint8_t PIN_DROGUE_CH = 2; \/\/ PC4\n const uint8_t PIN_MAIN_CH = 3; \/\/ PC5\n\n \/**\n * For now, we proceed directly to PRE_ARM.\n *\/\n RocketState DisarmedState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Full data stream to ground station begins here.\n * Sensor calibration should be performed, hopefully with physical access to\n * the board.\n *\n * Proceed to ARMED on meeting all of the following conditions:\n *\n * 1. Sensor health checks passed\n * 2. GPS lock\n * 3. Software arm signal received from GS\n *\/\n RocketState PreArmState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Sensor calibration should be finished.\n *\n * Proceed to FLIGHT if X accel exceeds 1.1g.\n *\/\n RocketState ArmedState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Begin onboard data logging.\n * NOTE(yoos): Unfortunately, we do not have onboard logging yet.\n *\n * Detect apogee based mainly on four measurements:\n *\n * 1. Pressure rate of change\n * 2. Net acceleration magnitude\n * 3. Non-roll rotation rate magnitude\n * 4. Orientation\n *\n * We first determine possible apogee based on the altitude rate of change,\n * which is estimated from the barometer and GPS. (Currently, only the\n * barometer is used for altitude.)\n *\n * We check for the motor cutoff acceleration drop to negative. If we sense\n * we are falling faster than -40 m\/s, we transition to APOGEE. Otherwise, we\n * check for the ideal case of zero altitude change and that we are not\n * observing a false apogee during a subsonic transition.\n *\n * We do not track powered and coasting portions of flight in separate states\n * because a mach transition may happen at an unknowable time, and it's\n * probably easier to track state variables this way.\n *\/\n RocketState FlightState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Deploy drogue chute. If magnitude of net proper acceleration does not\n * change within 5 seconds, deploy main.\n *\/\n RocketState ApogeeState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Deploy main chute at 1500' AGL.\n *\/\n RocketState DescentState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Turn off all telemetry (maybe?) except GPS.\n *\n * Try to conserve power.\n *\/\n RocketState RecoveryState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * RGB LED stuff.\n *\/\n void SetLED(float r, float g, float b);\n void BlinkLED(float r, float g, float b, float freq);\n void PulseLED(float r, float g, float b, float freq);\n void RGBLED(float freq);\n\n \/**\n * In-class global vars\n *\/\n RocketState state;\n float motorDC;\n\n \/**\n * Per-launch calibration\n *\/\n float groundAltitude;\n float velocity;\n};\n\n#endif\n<commit_msg>Comment out drogue pin definition in rocket.<commit_after>#ifndef ROCKET_SYSTEM_HPP_\n#define ROCKET_SYSTEM_HPP_\n\n#include \"system\/vehicle_system.hpp\"\n#include \"util\/optional.hpp\"\n\n\/\/ Communication\n#include \"communication\/communicator.hpp\"\n#include \"communication\/message_listener.hpp\"\n\n\/\/ Control\n#include \"controller\/position_controller.hpp\"\n#include \"controller\/controller_pipeline.hpp\"\n#include \"controller\/setpoint_types.hpp\"\n#include \"controller\/zero_controller.hpp\"\n#include \"input\/input_source.hpp\"\n#include \"motor\/motor_mapper.hpp\"\n#include \"motor\/pwm_device_group.hpp\"\n\n\/\/ Filesystem\n#include \"filesystem\/logger.hpp\"\n\n\/\/ Platform\n#include \"variant\/digital_platform.hpp\"\n#include \"variant\/pwm_platform.hpp\"\n#include \"variant\/platform.hpp\"\n\n\/\/ World estimation\n#include \"estimator\/world_estimator.hpp\"\n\n\/\/ Sensors\n#include \"sensor\/sensor_measurements.hpp\"\n\nenum class RocketState {\n DISARMED,\n PRE_ARM,\n ARMED,\n FLIGHT,\n APOGEE,\n MICROGRAVITY, \/\/ Dummy state to keep state numbers the same as payload. Firmware doesn't care, but this makes the current ground station simpler. It all needs to be rethought anyway.\n DESCENT,\n RECOVERY\n};\n\nclass RocketSystem : public VehicleSystem, public MessageListener {\npublic:\n RocketSystem(\n Accelerometer& accel,\n optional<Accelerometer *> accelH,\n optional<Barometer *> bar,\n optional<Geiger *> ggr,\n optional<GPS *> gps,\n Gyroscope& gyr,\n optional<Magnetometer *> mag,\n WorldEstimator& estimator, InputSource& inputSource,\n MotorMapper& motorMapper, Communicator& communicator, Logger& logger,\n Platform& platform);\n\n void update() override;\n bool healthy();\n\n void on(const protocol::message::set_arm_state_message_t& m) override;\n\nprivate:\n Accelerometer& accel;\n optional<Accelerometer *> accelH;\n optional<Barometer *> bar;\n optional<Geiger *> ggr;\n optional<GPS *> gps;\n Gyroscope& gyr;\n optional<Magnetometer *> mag;\n\n WorldEstimator& estimator;\n InputSource& inputSource;\n\n PositionController posController;\n ControllerPipeline<ActuatorSetpoint> pipeline;\n\n ZeroController<ActuatorSetpoint> zeroController;\n\n MotorMapper& motorMapper;\n Platform& platform;\n\n RateLimitedStream systemStream;\n Logger& logger;\n\n void updateStreams(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Pin config\n *\/\n \/\/ ADC\n const uint8_t PIN_EXT_TEMP_THERM_CH = 0; \/\/ PC0\n \/\/ Digital\n \/\/const uint8_t PIN_DROGUE_CH = 2; \/\/ PC4\n const uint8_t PIN_MAIN_CH = 3; \/\/ PC5\n\n \/**\n * For now, we proceed directly to PRE_ARM.\n *\/\n RocketState DisarmedState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Full data stream to ground station begins here.\n * Sensor calibration should be performed, hopefully with physical access to\n * the board.\n *\n * Proceed to ARMED on meeting all of the following conditions:\n *\n * 1. Sensor health checks passed\n * 2. GPS lock\n * 3. Software arm signal received from GS\n *\/\n RocketState PreArmState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Sensor calibration should be finished.\n *\n * Proceed to FLIGHT if X accel exceeds 1.1g.\n *\/\n RocketState ArmedState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Begin onboard data logging.\n * NOTE(yoos): Unfortunately, we do not have onboard logging yet.\n *\n * Detect apogee based mainly on four measurements:\n *\n * 1. Pressure rate of change\n * 2. Net acceleration magnitude\n * 3. Non-roll rotation rate magnitude\n * 4. Orientation\n *\n * We first determine possible apogee based on the altitude rate of change,\n * which is estimated from the barometer and GPS. (Currently, only the\n * barometer is used for altitude.)\n *\n * We check for the motor cutoff acceleration drop to negative. If we sense\n * we are falling faster than -40 m\/s, we transition to APOGEE. Otherwise, we\n * check for the ideal case of zero altitude change and that we are not\n * observing a false apogee during a subsonic transition.\n *\n * We do not track powered and coasting portions of flight in separate states\n * because a mach transition may happen at an unknowable time, and it's\n * probably easier to track state variables this way.\n *\/\n RocketState FlightState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Deploy drogue chute. If magnitude of net proper acceleration does not\n * change within 5 seconds, deploy main.\n *\/\n RocketState ApogeeState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Deploy main chute at 1500' AGL.\n *\/\n RocketState DescentState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * Turn off all telemetry (maybe?) except GPS.\n *\n * Try to conserve power.\n *\/\n RocketState RecoveryState(SensorMeasurements meas, WorldEstimate est, ActuatorSetpoint& sp);\n\n \/**\n * RGB LED stuff.\n *\/\n void SetLED(float r, float g, float b);\n void BlinkLED(float r, float g, float b, float freq);\n void PulseLED(float r, float g, float b, float freq);\n void RGBLED(float freq);\n\n \/**\n * In-class global vars\n *\/\n RocketState state;\n float motorDC;\n\n \/**\n * Per-launch calibration\n *\/\n float groundAltitude;\n float velocity;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <cstdio> \/\/ debug\n#include <algorithm>\n#include <iostream>\n\n#include <tightdb\/utilities.hpp>\n#include <tightdb\/column.hpp>\n#include <tightdb\/array_string.hpp>\n\nusing namespace std;\n\nnamespace {\n\nconst int max_width = 64;\n\n\/\/ When len = 0 returns 0\n\/\/ When len = 1 returns 4\n\/\/ When 2 <= len < 256, returns 2**ceil(log2(len+1)).\n\/\/ Thus, 0 < len < 256 implies that len < round_up(len).\nsize_t round_up(size_t len)\n{\n if (len < 2) return len << 2;\n len |= len >> 1;\n len |= len >> 2;\n len |= len >> 4;\n ++len;\n return len;\n}\n\n} \/\/ anonymous namespace\n\n\nnamespace tightdb {\n\n\nvoid ArrayString::set(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx < m_len);\n TIGHTDB_ASSERT(value.size() < size_t(max_width)); \/\/ otherwise we have to use another column type\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ Make room for the new value plus a zero-termination\n if (m_width <= value.size()) {\n if (value.size() == 0 && m_width == 0) return;\n\n TIGHTDB_ASSERT(0 < value.size());\n\n \/\/ Calc min column width\n size_t new_width = ::round_up(value.size());\n\n TIGHTDB_ASSERT(value.size() < new_width);\n\n \/\/ FIXME: Should we try to avoid double copying when realloc fails to preserve the address?\n Alloc(m_len, new_width); \/\/ Throws\n\n char* base = m_data;\n char* new_end = base + m_len*new_width;\n\n \/\/ Expand the old values in reverse order\n if (0 < m_width) {\n const char* old_end = base + m_len*m_width;\n while (new_end != base) {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin = new_end - (new_width-m_width);\n fill(new_begin, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n }\n else {\n while (new_end != base) {\n *--new_end = char(new_width-1);\n {\n char* new_begin = new_end - (new_width-1);\n fill(new_begin, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin;\n }\n }\n }\n\n m_width = new_width;\n }\n\n TIGHTDB_ASSERT(0 < m_width);\n\n \/\/ Set the value\n char* begin = m_data + (ndx * m_width);\n char* end = begin + (m_width-1);\n begin = copy(value.data(), value.data()+value.size(), begin);\n fill(begin, end, 0); \/\/ Pad with zero bytes\n TIGHTDB_STATIC_ASSERT(max_width <= 128, \"Padding size must fit in 7-bits\");\n TIGHTDB_ASSERT(end - begin < max_width);\n int pad_size = int(end - begin);\n *end = char(pad_size);\n}\n\n\nvoid ArrayString::insert(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx <= m_len);\n TIGHTDB_ASSERT(value.size() < size_t(max_width)); \/\/ otherwise we have to use another column type\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ Calc min column width (incl trailing zero-byte)\n size_t new_width = max(m_width, ::round_up(value.size()));\n\n \/\/ Make room for the new value\n Alloc(m_len+1, new_width); \/\/ Throws\n\n if (0 < value.size() || 0 < m_width) {\n char* base = m_data;\n const char* old_end = base + m_len*m_width;\n char* new_end = base + m_len*new_width + new_width;\n\n \/\/ Move values after insertion point (may expand)\n if (ndx != m_len) {\n if (TIGHTDB_UNLIKELY(m_width < new_width)) {\n char* const new_begin = base + ndx*new_width + new_width;\n if (0 < m_width) {\n \/\/ Expand the old values\n do {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin2 = new_end - (new_width-m_width);\n fill(new_begin2, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin2;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n while (new_end != new_begin);\n }\n else {\n do {\n *--new_end = char(new_width-1);\n {\n char* new_begin2 = new_end - (new_width-1);\n fill(new_begin2, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin2;\n }\n }\n while (new_end != new_begin);\n }\n }\n else {\n \/\/ when no expansion just move the following entries forward\n const char* old_begin = base + ndx*m_width;\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n\n \/\/ Set the value\n {\n char* new_begin = new_end - new_width;\n char* pad_begin = copy(value.data(), value.data()+value.size(), new_begin);\n --new_end;\n fill(pad_begin, new_end, 0); \/\/ Pad with zero bytes\n TIGHTDB_STATIC_ASSERT(max_width <= 128, \"Padding size must fit in 7-bits\");\n TIGHTDB_ASSERT(new_end - pad_begin < max_width);\n int pad_size = int(new_end - pad_begin);\n *new_end = char(pad_size);\n new_end = new_begin;\n }\n\n \/\/ Expand values before insertion point\n if (TIGHTDB_UNLIKELY(m_width < new_width)) {\n if (0 < m_width) {\n while (new_end != base) {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin = new_end - (new_width-m_width);\n fill(new_begin, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n }\n else {\n while (new_end != base) {\n *--new_end = char(new_width-1);\n {\n char* new_begin = new_end - (new_width-1);\n fill(new_begin, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin;\n }\n }\n }\n m_width = new_width;\n }\n }\n\n ++m_len;\n}\n\nvoid ArrayString::erase(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < m_len);\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ move data backwards after deletion\n if (ndx < m_len-1) {\n char* const new_begin = m_data + ndx*m_width;\n char* const old_begin = new_begin + m_width;\n char* const old_end = m_data + m_len*m_width;\n copy(old_begin, old_end, new_begin);\n }\n\n --m_len;\n\n \/\/ Update length in header\n set_header_len(m_len);\n}\n\nsize_t ArrayString::CalcByteLen(size_t count, size_t width) const\n{\n \/\/ FIXME: This arithemtic could overflow. Consider using <tightdb\/overflow.hpp>\n return 8 + (count * width);\n}\n\nsize_t ArrayString::CalcItemCount(size_t bytes, size_t width) const TIGHTDB_NOEXCEPT\n{\n if (width == 0) return size_t(-1); \/\/ zero-width gives infinite space\n\n const size_t bytes_without_header = bytes - 8;\n return bytes_without_header \/ width;\n}\n\nsize_t ArrayString::count(StringData value, size_t begin, size_t end) const\n{\n size_t count = 0;\n\n size_t lastmatch = begin - 1;\n for (;;) {\n lastmatch = find_first(value, lastmatch+1, end);\n if (lastmatch != not_found)\n ++count;\n else break;\n }\n\n return count;\n}\n\nsize_t ArrayString::find_first(StringData value, size_t begin, size_t end) const\n{\n if (end == size_t(-1)) end = m_len;\n TIGHTDB_ASSERT(begin <= m_len && end <= m_len && begin <= end);\n\n \/\/ A string can never be wider than the column width\n if (m_width <= value.size()) return size_t(-1);\n\n if (m_width == 0) {\n return value.size() == 0 && begin < end ? begin : -1;\n }\n\n for (size_t i=begin; i<end; ++i) {\n const char* data = m_data + (i * m_width);\n std::size_t size = (m_width-1) - data[m_width-1];\n if (StringData(data, size) == value) return i;\n }\n\n return size_t(-1); \/\/ not found\n}\n\nvoid ArrayString::find_all(Array& result, StringData value, size_t add_offset,\n size_t begin, size_t end)\n{\n size_t first = begin - 1;\n for (;;) {\n first = find_first(value, first + 1, end);\n if (first != size_t(-1))\n result.add(first + add_offset);\n else break;\n }\n}\n\nbool ArrayString::Compare(const ArrayString& c) const\n{\n if (c.size() != size()) return false;\n\n for (size_t i = 0; i < size(); ++i) {\n if (get(i) != c.get(i)) return false;\n }\n\n return true;\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ArrayString::StringStats() const\n{\n size_t total = 0;\n size_t longest = 0;\n\n for (size_t i = 0; i < m_len; ++i) {\n StringData str = get(i);\n const size_t len = str.size() + 1;\n total += len;\n if (len > longest) longest = len;\n }\n\n const size_t size = m_len * m_width;\n const size_t zeroes = size - total;\n const size_t zavg = zeroes \/ (m_len ? m_len : 1); \/\/ avoid possible div by zero\n\n cout << \"Count: \" << m_len << \"\\n\";\n cout << \"Width: \" << m_width << \"\\n\";\n cout << \"Total: \" << size << \"\\n\";\n cout << \"Capacity: \" << m_capacity << \"\\n\\n\";\n cout << \"Bytes string: \" << total << \"\\n\";\n cout << \" longest: \" << longest << \"\\n\";\n cout << \"Bytes zeroes: \" << zeroes << \"\\n\";\n cout << \" avg: \" << zavg << \"\\n\";\n}\n\n\/*\nvoid ArrayString::ToDot(FILE* f) const\n{\n const size_t ref = getRef();\n\n fprintf(f, \"n%zx [label=\\\"\", ref);\n\n for (size_t i = 0; i < m_len; ++i) {\n if (i > 0) fprintf(f, \" | \");\n\n fprintf(f, \"%s\", get_c_str(i));\n }\n\n fprintf(f, \"\\\"];\\n\");\n}\n*\/\n\nvoid ArrayString::ToDot(ostream& out, StringData title) const\n{\n const size_t ref = GetRef();\n\n if (0 < title.size()) {\n out << \"subgraph cluster_\" << ref << \" {\" << endl;\n out << \" label = \\\"\" << title << \"\\\";\" << endl;\n out << \" color = white;\" << endl;\n }\n\n out << \"n\" << hex << ref << dec << \"[shape=none,label=<\";\n out << \"<TABLE BORDER=\\\"0\\\" CELLBORDER=\\\"1\\\" CELLSPACING=\\\"0\\\" CELLPADDING=\\\"4\\\"><TR>\" << endl;\n\n \/\/ Header\n out << \"<TD BGCOLOR=\\\"lightgrey\\\"><FONT POINT-SIZE=\\\"7\\\">\";\n out << \"0x\" << hex << ref << dec << \"<\/FONT><\/TD>\" << endl;\n\n for (size_t i = 0; i < m_len; ++i) {\n out << \"<TD>\\\"\" << get(i) << \"\\\"<\/TD>\" << endl;\n }\n\n out << \"<\/TR><\/TABLE>>];\" << endl;\n if (0 < title.size()) out << \"}\" << endl;\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n}\n<commit_msg>Fixed performance issue when searching in short string array<commit_after>#include <cstdlib>\n#include <cstdio> \/\/ debug\n#include <algorithm>\n#include <iostream>\n\n#include <tightdb\/utilities.hpp>\n#include <tightdb\/column.hpp>\n#include <tightdb\/array_string.hpp>\n\nusing namespace std;\n\nnamespace {\n\nconst int max_width = 64;\n\n\/\/ When len = 0 returns 0\n\/\/ When len = 1 returns 4\n\/\/ When 2 <= len < 256, returns 2**ceil(log2(len+1)).\n\/\/ Thus, 0 < len < 256 implies that len < round_up(len).\nsize_t round_up(size_t len)\n{\n if (len < 2) return len << 2;\n len |= len >> 1;\n len |= len >> 2;\n len |= len >> 4;\n ++len;\n return len;\n}\n\n} \/\/ anonymous namespace\n\n\nnamespace tightdb {\n\n\nvoid ArrayString::set(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx < m_len);\n TIGHTDB_ASSERT(value.size() < size_t(max_width)); \/\/ otherwise we have to use another column type\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ Make room for the new value plus a zero-termination\n if (m_width <= value.size()) {\n if (value.size() == 0 && m_width == 0) return;\n\n TIGHTDB_ASSERT(0 < value.size());\n\n \/\/ Calc min column width\n size_t new_width = ::round_up(value.size());\n\n TIGHTDB_ASSERT(value.size() < new_width);\n\n \/\/ FIXME: Should we try to avoid double copying when realloc fails to preserve the address?\n Alloc(m_len, new_width); \/\/ Throws\n\n char* base = m_data;\n char* new_end = base + m_len*new_width;\n\n \/\/ Expand the old values in reverse order\n if (0 < m_width) {\n const char* old_end = base + m_len*m_width;\n while (new_end != base) {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin = new_end - (new_width-m_width);\n fill(new_begin, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n }\n else {\n while (new_end != base) {\n *--new_end = char(new_width-1);\n {\n char* new_begin = new_end - (new_width-1);\n fill(new_begin, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin;\n }\n }\n }\n\n m_width = new_width;\n }\n\n TIGHTDB_ASSERT(0 < m_width);\n\n \/\/ Set the value\n char* begin = m_data + (ndx * m_width);\n char* end = begin + (m_width-1);\n begin = copy(value.data(), value.data()+value.size(), begin);\n fill(begin, end, 0); \/\/ Pad with zero bytes\n TIGHTDB_STATIC_ASSERT(max_width <= 128, \"Padding size must fit in 7-bits\");\n TIGHTDB_ASSERT(end - begin < max_width);\n int pad_size = int(end - begin);\n *end = char(pad_size);\n}\n\n\nvoid ArrayString::insert(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx <= m_len);\n TIGHTDB_ASSERT(value.size() < size_t(max_width)); \/\/ otherwise we have to use another column type\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ Calc min column width (incl trailing zero-byte)\n size_t new_width = max(m_width, ::round_up(value.size()));\n\n \/\/ Make room for the new value\n Alloc(m_len+1, new_width); \/\/ Throws\n\n if (0 < value.size() || 0 < m_width) {\n char* base = m_data;\n const char* old_end = base + m_len*m_width;\n char* new_end = base + m_len*new_width + new_width;\n\n \/\/ Move values after insertion point (may expand)\n if (ndx != m_len) {\n if (TIGHTDB_UNLIKELY(m_width < new_width)) {\n char* const new_begin = base + ndx*new_width + new_width;\n if (0 < m_width) {\n \/\/ Expand the old values\n do {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin2 = new_end - (new_width-m_width);\n fill(new_begin2, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin2;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n while (new_end != new_begin);\n }\n else {\n do {\n *--new_end = char(new_width-1);\n {\n char* new_begin2 = new_end - (new_width-1);\n fill(new_begin2, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin2;\n }\n }\n while (new_end != new_begin);\n }\n }\n else {\n \/\/ when no expansion just move the following entries forward\n const char* old_begin = base + ndx*m_width;\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n\n \/\/ Set the value\n {\n char* new_begin = new_end - new_width;\n char* pad_begin = copy(value.data(), value.data()+value.size(), new_begin);\n --new_end;\n fill(pad_begin, new_end, 0); \/\/ Pad with zero bytes\n TIGHTDB_STATIC_ASSERT(max_width <= 128, \"Padding size must fit in 7-bits\");\n TIGHTDB_ASSERT(new_end - pad_begin < max_width);\n int pad_size = int(new_end - pad_begin);\n *new_end = char(pad_size);\n new_end = new_begin;\n }\n\n \/\/ Expand values before insertion point\n if (TIGHTDB_UNLIKELY(m_width < new_width)) {\n if (0 < m_width) {\n while (new_end != base) {\n *--new_end = char(*--old_end + (new_width-m_width));\n {\n char* new_begin = new_end - (new_width-m_width);\n fill(new_begin, new_end, 0); \/\/ Extend padding with zero bytes\n new_end = new_begin;\n }\n {\n const char* old_begin = old_end - (m_width-1);\n new_end = copy_backward(old_begin, old_end, new_end);\n old_end = old_begin;\n }\n }\n }\n else {\n while (new_end != base) {\n *--new_end = char(new_width-1);\n {\n char* new_begin = new_end - (new_width-1);\n fill(new_begin, new_end, 0); \/\/ Fill with zero bytes\n new_end = new_begin;\n }\n }\n }\n m_width = new_width;\n }\n }\n\n ++m_len;\n}\n\nvoid ArrayString::erase(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < m_len);\n\n \/\/ Check if we need to copy before modifying\n CopyOnWrite(); \/\/ Throws\n\n \/\/ move data backwards after deletion\n if (ndx < m_len-1) {\n char* const new_begin = m_data + ndx*m_width;\n char* const old_begin = new_begin + m_width;\n char* const old_end = m_data + m_len*m_width;\n copy(old_begin, old_end, new_begin);\n }\n\n --m_len;\n\n \/\/ Update length in header\n set_header_len(m_len);\n}\n\nsize_t ArrayString::CalcByteLen(size_t count, size_t width) const\n{\n \/\/ FIXME: This arithemtic could overflow. Consider using <tightdb\/overflow.hpp>\n return 8 + (count * width);\n}\n\nsize_t ArrayString::CalcItemCount(size_t bytes, size_t width) const TIGHTDB_NOEXCEPT\n{\n if (width == 0) return size_t(-1); \/\/ zero-width gives infinite space\n\n const size_t bytes_without_header = bytes - 8;\n return bytes_without_header \/ width;\n}\n\nsize_t ArrayString::count(StringData value, size_t begin, size_t end) const\n{\n size_t count = 0;\n\n size_t lastmatch = begin - 1;\n for (;;) {\n lastmatch = find_first(value, lastmatch+1, end);\n if (lastmatch != not_found)\n ++count;\n else break;\n }\n\n return count;\n}\n\nsize_t ArrayString::find_first(StringData value, size_t begin, size_t end) const\n{\n if (end == size_t(-1)) end = m_len;\n TIGHTDB_ASSERT(begin <= m_len && end <= m_len && begin <= end);\n\n \/\/ A string can never be wider than the column width\n if (m_width <= value.size()) return size_t(-1);\n\n if (m_width == 0) {\n return value.size() == 0 && begin < end ? begin : -1;\n }\n\n if (value.size() == 0) {\n const char* data = m_data + (m_width-1);\n for (size_t i = begin; i != end; ++i) {\n size_t size = (m_width-1) - data[i * m_width];\n if (size == 0) return i;\n }\n }\n else {\n for (size_t i = begin; i != end; ++i) {\n const char* data = m_data + (i * m_width);\n size_t j = 0;\n for (;;) {\n if (TIGHTDB_LIKELY(data[j] != value[j])) break;\n ++j;\n if (TIGHTDB_UNLIKELY(j == value.size())) {\n size_t size = (m_width-1) - data[m_width-1];\n if (TIGHTDB_LIKELY(size == value.size())) return i;\n break;\n }\n }\n }\n }\n\n return size_t(-1); \/\/ not found\n}\n\nvoid ArrayString::find_all(Array& result, StringData value, size_t add_offset,\n size_t begin, size_t end)\n{\n size_t first = begin - 1;\n for (;;) {\n first = find_first(value, first + 1, end);\n if (first != size_t(-1))\n result.add(first + add_offset);\n else break;\n }\n}\n\nbool ArrayString::Compare(const ArrayString& c) const\n{\n if (c.size() != size()) return false;\n\n for (size_t i = 0; i < size(); ++i) {\n if (get(i) != c.get(i)) return false;\n }\n\n return true;\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ArrayString::StringStats() const\n{\n size_t total = 0;\n size_t longest = 0;\n\n for (size_t i = 0; i < m_len; ++i) {\n StringData str = get(i);\n const size_t len = str.size() + 1;\n total += len;\n if (len > longest) longest = len;\n }\n\n const size_t size = m_len * m_width;\n const size_t zeroes = size - total;\n const size_t zavg = zeroes \/ (m_len ? m_len : 1); \/\/ avoid possible div by zero\n\n cout << \"Count: \" << m_len << \"\\n\";\n cout << \"Width: \" << m_width << \"\\n\";\n cout << \"Total: \" << size << \"\\n\";\n cout << \"Capacity: \" << m_capacity << \"\\n\\n\";\n cout << \"Bytes string: \" << total << \"\\n\";\n cout << \" longest: \" << longest << \"\\n\";\n cout << \"Bytes zeroes: \" << zeroes << \"\\n\";\n cout << \" avg: \" << zavg << \"\\n\";\n}\n\n\/*\nvoid ArrayString::ToDot(FILE* f) const\n{\n const size_t ref = getRef();\n\n fprintf(f, \"n%zx [label=\\\"\", ref);\n\n for (size_t i = 0; i < m_len; ++i) {\n if (i > 0) fprintf(f, \" | \");\n\n fprintf(f, \"%s\", get_c_str(i));\n }\n\n fprintf(f, \"\\\"];\\n\");\n}\n*\/\n\nvoid ArrayString::ToDot(ostream& out, StringData title) const\n{\n const size_t ref = GetRef();\n\n if (0 < title.size()) {\n out << \"subgraph cluster_\" << ref << \" {\" << endl;\n out << \" label = \\\"\" << title << \"\\\";\" << endl;\n out << \" color = white;\" << endl;\n }\n\n out << \"n\" << hex << ref << dec << \"[shape=none,label=<\";\n out << \"<TABLE BORDER=\\\"0\\\" CELLBORDER=\\\"1\\\" CELLSPACING=\\\"0\\\" CELLPADDING=\\\"4\\\"><TR>\" << endl;\n\n \/\/ Header\n out << \"<TD BGCOLOR=\\\"lightgrey\\\"><FONT POINT-SIZE=\\\"7\\\">\";\n out << \"0x\" << hex << ref << dec << \"<\/FONT><\/TD>\" << endl;\n\n for (size_t i = 0; i < m_len; ++i) {\n out << \"<TD>\\\"\" << get(i) << \"\\\"<\/TD>\" << endl;\n }\n\n out << \"<\/TR><\/TABLE>>];\" << endl;\n if (0 < title.size()) out << \"}\" << endl;\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2018 by contributors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/------------------------------------------------------------------------------\n\n\/*\nThis file is the implementation of Reader class.\n*\/\n\n#include \"src\/reader\/reader.h\"\n\n#include <string.h>\n#include <algorithm> \/\/ for random_shuffle\n\n#include \"src\/base\/file_util.h\"\n#include \"src\/base\/split_string.h\"\n#include \"src\/base\/format_print.h\"\n\nnamespace xLearn {\n\n\/\/------------------------------------------------------------------------------\n\/\/ Class register\n\/\/------------------------------------------------------------------------------\nCLASS_REGISTER_IMPLEMENT_REGISTRY(xLearn_reader_registry, Reader);\nREGISTER_READER(\"memory\", InmemReader);\nREGISTER_READER(\"disk\", OndiskReader);\n\n\/\/ Check current file format and\n\/\/ return 'libsvm', 'libffm', or 'csv'.\n\/\/ This function will also check if current\n\/\/ data has the label y.\nstd::string Reader::check_file_format() {\n FILE* file = OpenFileOrDie(filename_.c_str(), \"r\");\n \/\/ get the first line of data\n std::string data_line;\n GetLine(file, data_line);\n Close(file);\n \/\/ Find the split string\n int space_count = 0;\n int table_count = 0;\n int comma_count = 0;\n for (size_t i = 0; i < data_line.size(); ++i) {\n if (data_line[i] == ' ') {\n space_count++;\n } else if (data_line[i] == '\\t') {\n table_count++;\n } else if (data_line[i] == ',') {\n comma_count++;\n }\n }\n if (space_count > table_count && \n space_count > comma_count) {\n splitor_ = \" \";\n } else if (table_count > space_count &&\n table_count > comma_count) {\n splitor_ = \"\\t\";\n } else if (comma_count > space_count &&\n comma_count > table_count) {\n splitor_ = \",\";\n } else {\n LOG(FATAL) << \"File format error!\";\n }\n \/\/ Split the first line of data\n std::vector<std::string> str_list;\n SplitStringUsing(data_line, splitor_.c_str(), &str_list);\n \/\/ has y?\n size_t found = str_list[0].find(\":\");\n if (found != std::string::npos) { \/\/ find \":\", no label\n has_label_ = false;\n } else {\n has_label_ = true;\n }\n \/\/ check file format\n int count = 0;\n for (int i = 0; i < str_list[1].size(); ++i) {\n if (str_list[1][i] == ':') {\n count++;\n }\n }\n if (count == 1) {\n return \"libsvm\";\n } else if (count == 2) {\n return \"libffm\";\n } else if (count == 0){\n return \"csv\";\n }\n Color::print_error(\"Unknow file format\");\n exit(0);\n}\n\n\/\/ Find the last '\\n' in block, and shrink back file pointer\nvoid Reader::shrink_block(char* block, size_t* ret, FILE* file) {\n \/\/ Find the last '\\n'\n size_t index = *ret-1;\n while (block[index] != '\\n') { index--; }\n \/\/ Shrink back file pointer\n fseek(file, index-*ret+1, SEEK_CUR);\n \/\/ The real size of block\n *ret = index + 1;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Implementation of InmemReader\n\/\/------------------------------------------------------------------------------\n\n\/\/ Pre-load all the data into memory buffer (data_buf_).\n\/\/ Note that this funtion will first check whether we \n\/\/ can use the existing binary file. If not, reader will \n\/\/ generate one automatically.\nvoid InmemReader::Initialize(const std::string& filename) {\n CHECK_NE(filename.empty(), true)\n filename_ = filename;\n Color::print_info(\"First check if the text file has been already \"\n \"converted to binary format.\");\n \/\/ HashBinary() will read the first two hash value\n \/\/ and then check it whether equal to the hash value generated\n \/\/ by HashFile() function from current txt file.\n if (hash_binary(filename_)) {\n Color::print_info(\n StringPrintf(\"Binary file (%s.bin) found. \"\n \"Skip converting text to binary.\",\n filename_.c_str())\n );\n filename_ += \".bin\";\n init_from_binary();\n } else {\n Color::print_info(\n StringPrintf(\"Binary file (%s.bin) NOT found. Convert text \"\n \"file to binary file.\",\n filename_.c_str())\n );\n \/\/ Allocate memory for block\n try {\n this->block_ = (char*)malloc(block_size_*1024*1024);\n } catch (std::bad_alloc&) {\n LOG(FATAL) << \"Cannot allocate enough memory for data \\\n block. Block size: \" \n << block_size_ << \"MB. \"\n << \"You set change the block size via configuration.\";\n }\n init_from_txt();\n }\n}\n\n\/\/ Check wheter current path has a binary file.\n\/\/ We use double check here, that is, we first check \n\/\/ the hash value of a small data block, then check the whole file.\nbool InmemReader::hash_binary(const std::string& filename) {\n std::string bin_file = filename + \".bin\";\n \/\/ If the \".bin\" file does not exists, return false.\n if (!FileExist(bin_file.c_str())) { return false; }\n FILE* file = OpenFileOrDie(bin_file.c_str(), \"r\");\n \/\/ Check the first hash value\n uint64 hash_1 = 0;\n ReadDataFromDisk(file, (char*)&hash_1, sizeof(hash_1));\n if (hash_1 != HashFile(filename, true)) {\n Close(file);\n return false;\n }\n \/\/ Check the second hash value\n uint64 hash_2 = 0;\n ReadDataFromDisk(file, (char*)&hash_2, sizeof(hash_2));\n if (hash_2 != HashFile(filename, false)) {\n Close(file);\n return false;\n }\n Close(file);\n return true;\n}\n\n\/\/ In-memory Reader can be initialized from binary file.\nvoid InmemReader::init_from_binary() {\n \/\/ Init data_buf_ \n data_buf_.Deserialize(filename_);\n has_label_ = data_buf_.has_label;\n \/\/ Init data_samples_\n num_samples_ = data_buf_.row_length;\n data_samples_.ReAlloc(num_samples_);\n \/\/ for shuffle\n order_.resize(num_samples_);\n for (int i = 0; i < order_.size(); ++i) {\n order_[i] = i;\n }\n}\n\n\/\/ Pre-load all the data to memory buffer from txt file.\nvoid InmemReader::init_from_txt() {\n \/\/ Init parser_ \n parser_ = CreateParser(check_file_format().c_str());\n if (has_label_) parser_->setLabel(true);\n else parser_->setLabel(false);\n \/\/ Set splitor\n parser_->setSplitor(this->splitor_);\n \/\/ Convert MB to Byte\n uint64 read_byte = block_size_ * 1024 * 1024;\n \/\/ Open file\n FILE* file = OpenFileOrDie(filename_.c_str(), \"r\");\n \/\/ Read until the end of file\n for (;;) {\n \/\/ Read a block of data from disk file\n size_t ret = ReadDataFromDisk(file, block_, read_byte);\n if (ret == 0) {\n break;\n } else if (ret == read_byte) {\n \/\/ Find the last '\\n', and shrink back file pointer\n this->shrink_block(block_, &ret, file);\n } \/\/ else ret < read_byte: we don't need shrink_block()\n parser_->Parse(block_, ret, data_buf_, false);\n }\n data_buf_.SetHash(HashFile(filename_, true),\n HashFile(filename_, false));\n data_buf_.has_label = has_label_;\n \/\/ Init data_samples_ \n num_samples_ = data_buf_.row_length;\n data_samples_.ReAlloc(num_samples_, has_label_);\n \/\/ for shuffle\n order_.resize(num_samples_);\n for (int i = 0; i < order_.size(); ++i) {\n order_[i] = i;\n }\n \/\/ Deserialize in-memory buffer to disk file.\n std::string bin_file = filename_ + \".bin\";\n data_buf_.Serialize(bin_file);\n delete [] block_;\n Close(file);\n}\n\n\/\/ Smaple data from memory buffer.\nindex_t InmemReader::Samples(DMatrix* &matrix) {\n for (int i = 0; i < num_samples_; ++i) {\n if (pos_ >= data_buf_.row_length) {\n \/\/ End of the data buffer\n if (i == 0) {\n if (shuffle_) {\n random_shuffle(order_.begin(), order_.end());\n }\n matrix = nullptr;\n return 0;\n }\n break;\n }\n \/\/ Copy data between different DMatrix.\n data_samples_.row[i] = data_buf_.row[order_[pos_]];\n data_samples_.Y[i] = data_buf_.Y[order_[pos_]];\n data_samples_.norm[i] = data_buf_.norm[order_[pos_]];\n pos_++;\n }\n matrix = &data_samples_;\n return num_samples_;\n}\n\n\/\/ Return to the begining of the data buffer.\nvoid InmemReader::Reset() { pos_ = 0; }\n\n\/\/------------------------------------------------------------------------------\n\/\/ Implementation of OndiskReader.\n\/\/------------------------------------------------------------------------------\n\n\/\/ Create parser and open file\nvoid OndiskReader::Initialize(const std::string& filename) {\n CHECK_NE(filename.empty(), true);\n this->filename_ = filename;\n \/\/ Init parser_ \n parser_ = CreateParser(check_file_format().c_str());\n if (has_label_) parser_->setLabel(true);\n else parser_->setLabel(false);\n \/\/ Set splitor\n parser_->setSplitor(this->splitor_);\n \/\/ Allocate memory for block\n try {\n this->block_ = (char*)malloc(block_size_*1024*1024);\n } catch (std::bad_alloc&) {\n LOG(FATAL) << \"Cannot allocate enough memory for data \\\n block. Block size: \" \n << block_size_ << \"MB. \"\n << \"You set change the block size via configuration.\";\n }\n \/\/ Open file\n file_ptr_ = OpenFileOrDie(filename_.c_str(), \"r\");\n}\n\n\/\/ Return to the begining of the file\nvoid OndiskReader::Reset() {\n int ret = fseek(file_ptr_, 0, SEEK_SET);\n if (ret != 0) {\n LOG(FATAL) << \"Fail to return to the head of file.\";\n }\n}\n\n\/\/ Sample data from disk file.\nindex_t OndiskReader::Samples(DMatrix* &matrix) {\n \/\/ Convert MB to Byte\n uint64 read_byte = block_size_ * 1024 * 1024;\n \/\/ Read a block of data from disk file\n size_t ret = ReadDataFromDisk(file_ptr_, block_, read_byte);\n if (ret == 0) {\n matrix = nullptr;\n return 0;\n } else if (ret == read_byte) {\n \/\/ Find the last '\\n', and shrink back file pointer\n shrink_block(block_, &ret, file_ptr_);\n } \/\/ else ret < read_byte: we don't need shrink_block()\n \/\/ Parse block to data_sample_\n parser_->Parse(block_, ret, data_samples_, true);\n matrix = &data_samples_;\n return data_samples_.row_length;\n}\n\n} \/\/ namespace xLearn\n<commit_msg>small fix<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2018 by contributors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/------------------------------------------------------------------------------\n\n\/*\nThis file is the implementation of Reader class.\n*\/\n\n#include \"src\/reader\/reader.h\"\n\n#include <string.h>\n#include <algorithm> \/\/ for random_shuffle\n\n#include \"src\/base\/file_util.h\"\n#include \"src\/base\/split_string.h\"\n#include \"src\/base\/format_print.h\"\n\nnamespace xLearn {\n\n\/\/------------------------------------------------------------------------------\n\/\/ Class register\n\/\/------------------------------------------------------------------------------\nCLASS_REGISTER_IMPLEMENT_REGISTRY(xLearn_reader_registry, Reader);\nREGISTER_READER(\"memory\", InmemReader);\nREGISTER_READER(\"disk\", OndiskReader);\n\n\/\/ Check current file format and\n\/\/ return 'libsvm', 'libffm', or 'csv'.\n\/\/ This function will also check if current\n\/\/ data has the label y.\nstd::string Reader::check_file_format() {\n FILE* file = OpenFileOrDie(filename_.c_str(), \"r\");\n \/\/ get the first line of data\n std::string data_line;\n GetLine(file, data_line);\n Close(file);\n \/\/ Find the split string\n int space_count = 0;\n int table_count = 0;\n int comma_count = 0;\n for (size_t i = 0; i < data_line.size(); ++i) {\n if (data_line[i] == ' ') {\n space_count++;\n } else if (data_line[i] == '\\t') {\n table_count++;\n } else if (data_line[i] == ',') {\n comma_count++;\n }\n }\n if (space_count > table_count && \n space_count > comma_count) {\n splitor_ = \" \";\n } else if (table_count > space_count &&\n table_count > comma_count) {\n splitor_ = \"\\t\";\n } else if (comma_count > space_count &&\n comma_count > table_count) {\n splitor_ = \",\";\n } else {\n LOG(FATAL) << \"File format error!\";\n }\n \/\/ Split the first line of data\n std::vector<std::string> str_list;\n SplitStringUsing(data_line, splitor_.c_str(), &str_list);\n \/\/ has y?\n size_t found = str_list[0].find(\":\");\n if (found != std::string::npos) { \/\/ find \":\", no label\n has_label_ = false;\n } else {\n has_label_ = true;\n }\n \/\/ check file format\n int count = 0;\n for (int i = 0; i < str_list[1].size(); ++i) {\n if (str_list[1][i] == ':') {\n count++;\n }\n }\n if (count == 1) {\n return \"libsvm\";\n } else if (count == 2) {\n return \"libffm\";\n } else if (count == 0){\n return \"csv\";\n }\n Color::print_error(\"Unknow file format\");\n exit(0);\n}\n\n\/\/ Find the last '\\n' in block, and shrink back file pointer\nvoid Reader::shrink_block(char* block, size_t* ret, FILE* file) {\n \/\/ Find the last '\\n'\n size_t index = *ret-1;\n while (block[index] != '\\n') { index--; }\n \/\/ Shrink back file pointer\n fseek(file, index-*ret+1, SEEK_CUR);\n \/\/ The real size of block\n *ret = index + 1;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Implementation of InmemReader\n\/\/------------------------------------------------------------------------------\n\n\/\/ Pre-load all the data into memory buffer (data_buf_).\n\/\/ Note that this funtion will first check whether we \n\/\/ can use the existing binary file. If not, reader will \n\/\/ generate one automatically.\nvoid InmemReader::Initialize(const std::string& filename) {\n CHECK_NE(filename.empty(), true)\n filename_ = filename;\n Color::print_info(\"First check if the text file has been already \"\n \"converted to binary format.\");\n \/\/ HashBinary() will read the first two hash value\n \/\/ and then check it whether equal to the hash value generated\n \/\/ by HashFile() function from current txt file.\n if (hash_binary(filename_)) {\n Color::print_info(\n StringPrintf(\"Binary file (%s.bin) found. \"\n \"Skip converting text to binary.\",\n filename_.c_str())\n );\n filename_ += \".bin\";\n init_from_binary();\n } else {\n Color::print_info(\n StringPrintf(\"Binary file (%s.bin) NOT found. Convert text \"\n \"file to binary file.\",\n filename_.c_str())\n );\n \/\/ Allocate memory for block\n try {\n this->block_ = (char*)malloc(block_size_*1024*1024);\n } catch (std::bad_alloc&) {\n LOG(FATAL) << \"Cannot allocate enough memory for data \\\n block. Block size: \" \n << block_size_ << \"MB. \"\n << \"You set change the block size via configuration.\";\n }\n init_from_txt();\n }\n}\n\n\/\/ Check wheter current path has a binary file.\n\/\/ We use double check here, that is, we first check \n\/\/ the hash value of a small data block, then check the whole file.\nbool InmemReader::hash_binary(const std::string& filename) {\n std::string bin_file = filename + \".bin\";\n \/\/ If the \".bin\" file does not exists, return false.\n if (!FileExist(bin_file.c_str())) { return false; }\n FILE* file = OpenFileOrDie(bin_file.c_str(), \"r\");\n \/\/ Check the first hash value\n uint64 hash_1 = 0;\n ReadDataFromDisk(file, (char*)&hash_1, sizeof(hash_1));\n if (hash_1 != HashFile(filename, true)) {\n Close(file);\n return false;\n }\n \/\/ Check the second hash value\n uint64 hash_2 = 0;\n ReadDataFromDisk(file, (char*)&hash_2, sizeof(hash_2));\n if (hash_2 != HashFile(filename, false)) {\n Close(file);\n return false;\n }\n Close(file);\n return true;\n}\n\n\/\/ In-memory Reader can be initialized from binary file.\nvoid InmemReader::init_from_binary() {\n \/\/ Init data_buf_ \n data_buf_.Deserialize(filename_);\n has_label_ = data_buf_.has_label;\n \/\/ Init data_samples_\n num_samples_ = data_buf_.row_length;\n data_samples_.ReAlloc(num_samples_);\n \/\/ for shuffle\n order_.resize(num_samples_);\n for (int i = 0; i < order_.size(); ++i) {\n order_[i] = i;\n }\n}\n\n\/\/ Pre-load all the data to memory buffer from txt file.\nvoid InmemReader::init_from_txt() {\n \/\/ Init parser_ \n parser_ = CreateParser(check_file_format().c_str());\n if (has_label_) parser_->setLabel(true);\n else parser_->setLabel(false);\n \/\/ Set splitor\n parser_->setSplitor(this->splitor_);\n \/\/ Convert MB to Byte\n uint64 read_byte = block_size_ * 1024 * 1024;\n \/\/ Open file\n FILE* file = OpenFileOrDie(filename_.c_str(), \"r\");\n \/\/ Read until the end of file\n for (;;) {\n \/\/ Read a block of data from disk file\n size_t ret = ReadDataFromDisk(file, block_, read_byte);\n if (ret == 0) {\n break;\n } else if (ret == read_byte) {\n \/\/ Find the last '\\n', and shrink back file pointer\n this->shrink_block(block_, &ret, file);\n } \/\/ else ret < read_byte: we don't need shrink_block()\n parser_->Parse(block_, ret, data_buf_, false);\n }\n data_buf_.SetHash(HashFile(filename_, true),\n HashFile(filename_, false));\n data_buf_.has_label = has_label_;\n \/\/ Init data_samples_ \n num_samples_ = data_buf_.row_length;\n data_samples_.ReAlloc(num_samples_, has_label_);\n \/\/ for shuffle\n order_.resize(num_samples_);\n for (int i = 0; i < order_.size(); ++i) {\n order_[i] = i;\n }\n \/\/ Deserialize in-memory buffer to disk file.\n std::string bin_file = filename_ + \".bin\";\n data_buf_.Serialize(bin_file);\n delete [] block_;\n Close(file);\n}\n\n\/\/ Smaple data from memory buffer.\nindex_t InmemReader::Samples(DMatrix* &matrix) {\n for (int i = 0; i < num_samples_; ++i) {\n if (pos_ >= data_buf_.row_length) {\n \/\/ End of the data buffer\n if (i == 0) {\n if (shuffle_) {\n random_shuffle(order_.begin(), order_.end());\n }\n matrix = nullptr;\n return 0;\n }\n break;\n }\n \/\/ Copy data between different DMatrix.\n data_samples_.row[i] = data_buf_.row[order_[pos_]];\n data_samples_.Y[i] = data_buf_.Y[order_[pos_]];\n data_samples_.norm[i] = data_buf_.norm[order_[pos_]];\n pos_++;\n }\n matrix = &data_samples_;\n return num_samples_;\n}\n\n\/\/ Return to the begining of the data buffer.\nvoid InmemReader::Reset() { pos_ = 0; }\n\n\/\/------------------------------------------------------------------------------\n\/\/ Implementation of OndiskReader.\n\/\/------------------------------------------------------------------------------\n\n\/\/ Create parser and open file\nvoid OndiskReader::Initialize(const std::string& filename) {\n CHECK_NE(filename.empty(), true);\n this->filename_ = filename;\n \/\/ Init parser_ \n parser_ = CreateParser(check_file_format().c_str());\n if (has_label_) parser_->setLabel(true);\n else parser_->setLabel(false);\n \/\/ Set splitor\n parser_->setSplitor(this->splitor_);\n \/\/ Allocate memory for block\n try {\n this->block_ = (char*)malloc(block_size_*1024*1024);\n } catch (std::bad_alloc&) {\n LOG(FATAL) << \"Cannot allocate enough memory for data \\\n block. Block size: \" \n << block_size_ << \"MB. \"\n << \"You set change the block size via configuration.\";\n }\n \/\/ Open file\n file_ptr_ = OpenFileOrDie(filename_.c_str(), \"r\");\n}\n\n\/\/ Return to the begining of the file\nvoid OndiskReader::Reset() {\n int ret = fseek(file_ptr_, 0, SEEK_SET);\n if (ret != 0) {\n LOG(FATAL) << \"Fail to return to the head of file.\";\n }\n}\n\n\/\/ Sample data from disk file.\nindex_t OndiskReader::Samples(DMatrix* &matrix) {\n \/\/ Convert MB to Byte\n uint64 read_byte = block_size_ * 1024 * 1024;\n \/\/ Read a block of data from disk file\n size_t ret = ReadDataFromDisk(file_ptr_, block_, read_byte);\n if (ret == 0) {\n matrix = nullptr;\n return 0;\n } else if (ret == read_byte) {\n \/\/ Find the last '\\n', and shrink back file pointer\n shrink_block(block_, &ret, file_ptr_);\n } \/\/ else ret < read_byte: we don't need shrink_block()\n \/\/ Parse block to data_sample_\n parser_->Parse(block_, ret, data_samples_, true);\n matrix = &data_samples_;\n return data_samples_.row_length;\n}\n\n} \/\/ namespace xLearn\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010, Antonie Jovanoski\n *\n * All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>\n *\/\n\n#include <QDateTime>\n#include \"qtweetuser.h\"\n\nQTweetUser::QTweetUser()\n{\n}\n\nvoid QTweetUser::setId(qint64 id)\n{\n m_userInfo.insert(QTweetUser::Id, id);\n}\n\nqint64 QTweetUser::id() const\n{\n return m_userInfo.value(QTweetUser::Id).toLongLong();\n}\n\nvoid QTweetUser::setName(const QString &name)\n{\n m_userInfo.insert(QTweetUser::Name, name);\n}\n\nQString QTweetUser::name() const\n{\n return m_userInfo.value(QTweetUser::Name).toString();\n}\n\nvoid QTweetUser::setScreenName(const QString &screenName)\n{\n m_userInfo.insert(QTweetUser::ScreenName, screenName);\n}\n\nQString QTweetUser::screenName() const\n{\n return m_userInfo.value(QTweetUser::ScreenName).toString();\n}\n\nvoid QTweetUser::setLocation(const QString &location)\n{\n m_userInfo.insert(QTweetUser::Location, location);\n}\n\nQString QTweetUser::location() const\n{\n return m_userInfo.value(QTweetUser::Location).toString();\n}\n\nvoid QTweetUser::setDescription(const QString &desc)\n{\n m_userInfo.insert(QTweetUser::Description, desc);\n}\n\nQString QTweetUser::description() const\n{\n return m_userInfo.value(QTweetUser::Description).toString();\n}\n\nvoid QTweetUser::setprofileImageUrl(const QString &url)\n{\n m_userInfo.insert(QTweetUser::ProfileImageUrl, url);\n}\n\nQString QTweetUser::profileImageUrl() const\n{\n return m_userInfo.value(QTweetUser::ProfileImageUrl).toString();\n}\n\nvoid QTweetUser::setUrl(const QString &url)\n{\n m_userInfo.insert(QTweetUser::Url, url);\n}\n\nQString QTweetUser::url() const\n{\n return m_userInfo.value(QTweetUser::Url).toString();\n}\n\nvoid QTweetUser::setProtected(bool protected_)\n{\n m_userInfo.insert(QTweetUser::Protected, protected_);\n}\n\nbool QTweetUser::isProtected() const\n{\n return m_userInfo.value(QTweetUser::Protected).toBool();\n}\n\nvoid QTweetUser::setFollowersCount(int count)\n{\n m_userInfo.insert(QTweetUser::FollowersCount, count);\n}\n\nint QTweetUser::followersCount() const\n{\n return m_userInfo.value(QTweetUser::FollowersCount).toInt();\n}\n\nvoid QTweetUser::setFriendsCount(int count)\n{\n m_userInfo.insert(QTweetUser::FriendsCount, count);\n}\n\nint QTweetUser::friendsCount() const\n{\n return m_userInfo.value(QTweetUser::FriendsCount).toInt();\n}\n\nvoid QTweetUser::setCreatedAt(const QString &twitterDate)\n{\n QDateTime datetime = twitterDateToQDateTime(twitterDate);\n\n m_userInfo.insert(QTweetUser::CreatedAt, datetime);\n}\n\nQDateTime QTweetUser::createdAt() const\n{\n return m_userInfo.value(QTweetUser::CreatedAt).toDateTime();\n}\n\nvoid QTweetUser::setFavouritesCount(int count)\n{\n m_userInfo.insert(QTweetUser::FavouritesCount, count);\n}\n\nint QTweetUser::favouritesCount() const\n{\n return m_userInfo.value(QTweetUser::FavouritesCount).toInt();\n}\n\nvoid QTweetUser::setUtcOffset(int sec)\n{\n m_userInfo.insert(QTweetUser::UtcOffset, sec);\n}\n\nint QTweetUser::utcOffset() const\n{\n return m_userInfo.value(QTweetUser::UtcOffset).toInt();\n}\n\nvoid QTweetUser::setTimezone(const QString &timezone)\n{\n m_userInfo.insert(QTweetUser::TimeZone, timezone);\n}\n\nQString QTweetUser::timezone() const\n{\n return m_userInfo.value(QTweetUser::TimeZone).toString();\n}\n\nvoid QTweetUser::setGeoEnabled(bool isGeoEnabled)\n{\n m_userInfo.insert(QTweetUser::GeoEnabled, isGeoEnabled);\n}\n\nbool QTweetUser::isGeoEnabled() const\n{\n return m_userInfo.value(QTweetUser::GeoEnabled, false).toBool();\n}\n\nvoid QTweetUser::setVerified(bool verified)\n{\n m_userInfo.insert(QTweetUser::Verified, verified);\n}\n\nbool QTweetUser::isVerified() const\n{\n return m_userInfo.value(QTweetUser::Verified, false).toBool();\n}\n\nvoid QTweetUser::setFollowing(bool following)\n{\n m_userInfo.insert(QTweetUser::Following, following);\n}\n\nbool QTweetUser::isFollowing() const\n{\n return m_userInfo.value(QTweetUser::Following, false).toBool();\n}\n\nvoid QTweetUser::setStatusesCount(int count)\n{\n m_userInfo.insert(QTweetUser::StatusesCount, count);\n}\n\nint QTweetUser::statusesCount() const\n{\n return m_userInfo.value(QTweetUser::StatusesCount).toInt();\n}\n\nQDateTime QTweetUser::twitterDateToQDateTime(const QString &twitterDate)\n{\n \/\/Twitter Date Format: 'Wed Sep 01 11:27:25 +0000 2010' UTC\n QString dateString = twitterDate.left(10) + twitterDate.right(4);\n QString timeString = twitterDate.mid(11, 8);\n\n QDate date = QDate::fromString(dateString);\n QTime time = QTime::fromString(timeString);\n\n if (date.isValid() && time.isValid())\n return QDateTime(date, time, Qt::UTC);\n else\n return QDateTime();\n}\n<commit_msg>Fixed parsing twitter date (fixed by Rui Zhang).<commit_after>\/* Copyright (c) 2010, Antonie Jovanoski\n *\n * All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>\n *\/\n\n#include <QDateTime>\n#include \"qtweetuser.h\"\n\nQTweetUser::QTweetUser()\n{\n}\n\nvoid QTweetUser::setId(qint64 id)\n{\n m_userInfo.insert(QTweetUser::Id, id);\n}\n\nqint64 QTweetUser::id() const\n{\n return m_userInfo.value(QTweetUser::Id).toLongLong();\n}\n\nvoid QTweetUser::setName(const QString &name)\n{\n m_userInfo.insert(QTweetUser::Name, name);\n}\n\nQString QTweetUser::name() const\n{\n return m_userInfo.value(QTweetUser::Name).toString();\n}\n\nvoid QTweetUser::setScreenName(const QString &screenName)\n{\n m_userInfo.insert(QTweetUser::ScreenName, screenName);\n}\n\nQString QTweetUser::screenName() const\n{\n return m_userInfo.value(QTweetUser::ScreenName).toString();\n}\n\nvoid QTweetUser::setLocation(const QString &location)\n{\n m_userInfo.insert(QTweetUser::Location, location);\n}\n\nQString QTweetUser::location() const\n{\n return m_userInfo.value(QTweetUser::Location).toString();\n}\n\nvoid QTweetUser::setDescription(const QString &desc)\n{\n m_userInfo.insert(QTweetUser::Description, desc);\n}\n\nQString QTweetUser::description() const\n{\n return m_userInfo.value(QTweetUser::Description).toString();\n}\n\nvoid QTweetUser::setprofileImageUrl(const QString &url)\n{\n m_userInfo.insert(QTweetUser::ProfileImageUrl, url);\n}\n\nQString QTweetUser::profileImageUrl() const\n{\n return m_userInfo.value(QTweetUser::ProfileImageUrl).toString();\n}\n\nvoid QTweetUser::setUrl(const QString &url)\n{\n m_userInfo.insert(QTweetUser::Url, url);\n}\n\nQString QTweetUser::url() const\n{\n return m_userInfo.value(QTweetUser::Url).toString();\n}\n\nvoid QTweetUser::setProtected(bool protected_)\n{\n m_userInfo.insert(QTweetUser::Protected, protected_);\n}\n\nbool QTweetUser::isProtected() const\n{\n return m_userInfo.value(QTweetUser::Protected).toBool();\n}\n\nvoid QTweetUser::setFollowersCount(int count)\n{\n m_userInfo.insert(QTweetUser::FollowersCount, count);\n}\n\nint QTweetUser::followersCount() const\n{\n return m_userInfo.value(QTweetUser::FollowersCount).toInt();\n}\n\nvoid QTweetUser::setFriendsCount(int count)\n{\n m_userInfo.insert(QTweetUser::FriendsCount, count);\n}\n\nint QTweetUser::friendsCount() const\n{\n return m_userInfo.value(QTweetUser::FriendsCount).toInt();\n}\n\nvoid QTweetUser::setCreatedAt(const QString &twitterDate)\n{\n QDateTime datetime = twitterDateToQDateTime(twitterDate);\n\n m_userInfo.insert(QTweetUser::CreatedAt, datetime);\n}\n\nQDateTime QTweetUser::createdAt() const\n{\n return m_userInfo.value(QTweetUser::CreatedAt).toDateTime();\n}\n\nvoid QTweetUser::setFavouritesCount(int count)\n{\n m_userInfo.insert(QTweetUser::FavouritesCount, count);\n}\n\nint QTweetUser::favouritesCount() const\n{\n return m_userInfo.value(QTweetUser::FavouritesCount).toInt();\n}\n\nvoid QTweetUser::setUtcOffset(int sec)\n{\n m_userInfo.insert(QTweetUser::UtcOffset, sec);\n}\n\nint QTweetUser::utcOffset() const\n{\n return m_userInfo.value(QTweetUser::UtcOffset).toInt();\n}\n\nvoid QTweetUser::setTimezone(const QString &timezone)\n{\n m_userInfo.insert(QTweetUser::TimeZone, timezone);\n}\n\nQString QTweetUser::timezone() const\n{\n return m_userInfo.value(QTweetUser::TimeZone).toString();\n}\n\nvoid QTweetUser::setGeoEnabled(bool isGeoEnabled)\n{\n m_userInfo.insert(QTweetUser::GeoEnabled, isGeoEnabled);\n}\n\nbool QTweetUser::isGeoEnabled() const\n{\n return m_userInfo.value(QTweetUser::GeoEnabled, false).toBool();\n}\n\nvoid QTweetUser::setVerified(bool verified)\n{\n m_userInfo.insert(QTweetUser::Verified, verified);\n}\n\nbool QTweetUser::isVerified() const\n{\n return m_userInfo.value(QTweetUser::Verified, false).toBool();\n}\n\nvoid QTweetUser::setFollowing(bool following)\n{\n m_userInfo.insert(QTweetUser::Following, following);\n}\n\nbool QTweetUser::isFollowing() const\n{\n return m_userInfo.value(QTweetUser::Following, false).toBool();\n}\n\nvoid QTweetUser::setStatusesCount(int count)\n{\n m_userInfo.insert(QTweetUser::StatusesCount, count);\n}\n\nint QTweetUser::statusesCount() const\n{\n return m_userInfo.value(QTweetUser::StatusesCount).toInt();\n}\n\nQDateTime QTweetUser::twitterDateToQDateTime(const QString &twitterDate)\n{\n \/\/Twitter Date Format: 'Wed Sep 01 11:27:25 +0000 2010' UTC\n QString dateString = twitterDate.left(11) + twitterDate.right(4);\n QString timeString = twitterDate.mid(11, 8);\n\n QDate date = QDate::fromString(dateString);\n QTime time = QTime::fromString(timeString);\n\n if (date.isValid() && time.isValid())\n return QDateTime(date, time, Qt::UTC);\n else\n return QDateTime();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Eigen\/Geometry>\n#include <ros\/ros.h>\n#include <tf\/transform_datatypes.h>\n#include <tf\/transform_broadcaster.h>\n#include <tf\/transform_listener.h>\n#include <tf\/transform_broadcaster.h>\n#include <tf_conversions\/tf_eigen.h>\n#include <geometry_msgs\/QuaternionStamped.h>\n#include <nav_msgs\/Odometry.h>\n#include <sensor_msgs\/Imu.h>\n#include <robot_kf\/robot_kf.h>\n\nstatic double const big = 99999.0;\n\nstatic boost::shared_ptr<tf::TransformListener> sub_tf;\nstatic boost::shared_ptr<tf::TransformBroadcaster> pub_tf;\nstatic ros::Subscriber sub_compass, sub_encoders, sub_gps;\nstatic ros::Publisher pub_fused;\n\nstatic robot_kf::KalmanFilter kf;\nstatic geometry_msgs::Twist velocity;\n\nstatic bool watch_compass, watch_encoders, watch_gps;\nstatic std::string global_frame_id, odom_frame_id, base_frame_id;\n\nstatic void publish(ros::Time stamp)\n{\n Eigen::Vector3d const state = kf.getState();\n \n \/\/ Wrap the fused state estimate in a ROS message.\n geometry_msgs::PoseStamped fused_base;\n fused_base.header.stamp = stamp;\n fused_base.header.frame_id = base_frame_id;\n fused_base.pose.position.x = state[0];\n fused_base.pose.position.y = state[1];\n fused_base.pose.position.z = 0.0;\n fused_base.pose.orientation = tf::createQuaternionMsgFromYaw(state[2]);\n\n \/\/ We can't directly publish the transformation from global_frame_id to\n \/\/ base_frame_id because it would create a cycle in the TF tree. Instead,\n \/\/ we publish a transform from global_frame_id to odom_frame_id. This is\n \/\/ equivalent to transforming from base_frame_id to odom_frame_id.\n geometry_msgs::PoseStamped fused_odom;\n sub_tf->transformPose(odom_frame_id, fused_base, fused_odom);\n\n \/\/ Publish the odometry message.\n nav_msgs::Odometry msg;\n msg.header.stamp = stamp;\n msg.header.frame_id = global_frame_id;\n msg.child_frame_id = odom_frame_id;\n msg.pose.pose = fused_odom.pose;\n msg.pose.covariance[0] = -1;\n msg.twist.twist = velocity;\n msg.twist.covariance[0] = -1;\n pub_fused.publish(msg);\n\n\n \/\/ Transformation.\n geometry_msgs::TransformStamped transform;\n transform.header.stamp = stamp;\n transform.header.frame_id = global_frame_id;\n transform.child_frame_id = odom_frame_id;\n transform.transform.translation.x = fused_odom.pose.position.x;\n transform.transform.translation.y = fused_odom.pose.position.y;\n transform.transform.translation.z = fused_odom.pose.position.z;\n transform.transform.rotation = fused_odom.pose.orientation;\n pub_tf->sendTransform(transform);\n}\n\nstatic void updateCompass(sensor_msgs::Imu const &msg)\n{\n ros::Time const stamp = msg.header.stamp;\n std::string const frame_id = msg.header.frame_id;\n\n \/\/ Transform the orientation into the base coordinate frame.\n geometry_msgs::QuaternionStamped stamped_in, stamped_out;\n stamped_in.header.frame_id = frame_id;\n stamped_in.header.stamp = stamp;\n stamped_in.quaternion = msg.orientation;\n sub_tf->transformQuaternion(base_frame_id, stamped_in, stamped_out);\n\n \/\/ Rotate the covariance matrix according to the transformation.\n tf::StampedTransform transform;\n Eigen::Affine3d eigen_transform;\n sub_tf->lookupTransform(base_frame_id, frame_id, stamp, transform);\n tf::TransformTFToEigen(transform, eigen_transform);\n\n Eigen::Matrix3d const rotation = eigen_transform.rotation();\n Eigen::Map<Eigen::Matrix3d const> cov_raw(&msg.orientation_covariance.front());\n Eigen::Matrix3d const cov = rotation.transpose() * cov_raw * rotation;\n\n kf.update_compass(tf::getYaw(stamped_out.quaternion), cov(2, 2));\n if (watch_compass) publish(stamp);\n}\n\nstatic void updateEncoders(nav_msgs::Odometry const &msg)\n{\n if (msg.header.frame_id != odom_frame_id\n || msg.child_frame_id != base_frame_id) {\n ROS_ERROR_THROTTLE(10,\n \"Odometry message must have a frame_id '%s' and child_frame_id '%s'\",\n odom_frame_id.c_str(), base_frame_id.c_str()\n );\n return;\n }\n\n Eigen::Vector3d const z = (Eigen::Vector3d() <<\n msg.pose.pose.position.x,\n msg.pose.pose.position.y,\n tf::getYaw(msg.pose.pose.orientation)\n ).finished();\n Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n &msg.pose.covariance.front()\n );\n\n Eigen::Matrix3d cov_z = Eigen::Matrix3d::Zero();\n cov_z.topLeftCorner<2, 2>() = cov_raw.topLeftCorner<2, 2>();\n cov_z(2, 2) = cov_raw(5, 5);\n\n \/\/ Save the current velocity to republish later. This is necessary because\n \/\/ no other sensors measure velocity.\n velocity = msg.twist.twist;\n\n kf.update_encoders(z, cov_z);\n if (watch_encoders) publish(msg.header.stamp);\n}\n\nstatic void updateGps(nav_msgs::Odometry const &msg)\n{\n try {\n ros::Time const stamp = msg.header.stamp;\n std::string const frame_id = msg.child_frame_id;\n\n \/\/ Transform the position into the base coordinate frame.\n geometry_msgs::PointStamped stamped_in, stamped_out;\n stamped_in.header.stamp = stamp;\n stamped_in.header.frame_id = frame_id;\n stamped_in.point = msg.pose.pose.position;\n sub_tf->transformPoint(base_frame_id, stamped_in, stamped_out);\n\n Eigen::Vector2d const z = (Eigen::Vector2d() <<\n stamped_out.point.x, stamped_out.point.y).finished();\n Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n &msg.pose.covariance.front()\n );\n Eigen::Matrix3d const cov3_raw = cov_raw.topLeftCorner<3, 3>();\n\n \/\/ Rotate the covariance matrix according to the transformation.\n tf::StampedTransform transform;\n Eigen::Affine3d eigen_transform;\n sub_tf->lookupTransform(base_frame_id, frame_id, stamp, transform);\n tf::TransformTFToEigen(transform, eigen_transform);\n\n Eigen::Matrix3d const rotation = eigen_transform.rotation();\n Eigen::Matrix3d const cov3 = rotation.transpose() * cov3_raw * rotation;\n Eigen::Matrix2d const cov = cov3.topLeftCorner<2, 2>();\n\n kf.update_gps(z, cov);\n if (watch_gps) publish(msg.header.stamp);\n } catch (tf::ExtrapolationException const &e) {\n ROS_WARN(\"%s\", e.what());\n }\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"robot_kf_node\");\n\n ros::NodeHandle nh, nh_node(\"~\");\n nh_node.param<bool>(\"watch_compass\", watch_compass, true);\n nh_node.param<bool>(\"watch_encoders\", watch_encoders, true);\n nh_node.param<bool>(\"watch_gps\", watch_gps, true);\n nh_node.param<std::string>(\"global_frame_id\", global_frame_id, \"\/map\");\n nh_node.param<std::string>(\"odom_frame_id\", odom_frame_id, \"\/odom\");\n nh_node.param<std::string>(\"base_frame_id\", base_frame_id, \"\/base_footprint\");\n\n sub_tf = boost::make_shared<tf::TransformListener>();\n pub_tf = boost::make_shared<tf::TransformBroadcaster>();\n \/\/sub_compass = nh.subscribe(\"compass\", 1, &updateCompass);\n \/\/sub_encoders = nh.subscribe(\"odom\", 1, &updateEncoders);\n sub_gps = nh.subscribe(\"gps\", 1, &updateGps);\n pub_fused = nh.advertise<nav_msgs::Odometry>(\"odom_fused\", 100);\n\n ros::spin();\n return 0;\n}\n<commit_msg>added try\/catch blocks<commit_after>#include <Eigen\/Geometry>\n#include <ros\/ros.h>\n#include <tf\/transform_datatypes.h>\n#include <tf\/transform_broadcaster.h>\n#include <tf\/transform_listener.h>\n#include <tf\/transform_broadcaster.h>\n#include <tf_conversions\/tf_eigen.h>\n#include <geometry_msgs\/QuaternionStamped.h>\n#include <nav_msgs\/Odometry.h>\n#include <sensor_msgs\/Imu.h>\n#include <robot_kf\/robot_kf.h>\n\nstatic double const big = 99999.0;\n\nstatic boost::shared_ptr<tf::TransformListener> sub_tf;\nstatic boost::shared_ptr<tf::TransformBroadcaster> pub_tf;\nstatic ros::Subscriber sub_compass, sub_encoders, sub_gps;\nstatic ros::Publisher pub_fused;\n\nstatic robot_kf::KalmanFilter kf;\nstatic geometry_msgs::Twist velocity;\n\nstatic bool watch_compass, watch_encoders, watch_gps;\nstatic std::string global_frame_id, odom_frame_id, base_frame_id;\n\nstatic void publish(ros::Time stamp)\n{\n Eigen::Vector3d const state = kf.getState();\n \n \/\/ Wrap the fused state estimate in a ROS message.\n geometry_msgs::PoseStamped fused_base;\n fused_base.header.stamp = stamp;\n fused_base.header.frame_id = base_frame_id;\n fused_base.pose.position.x = state[0];\n fused_base.pose.position.y = state[1];\n fused_base.pose.position.z = 0.0;\n fused_base.pose.orientation = tf::createQuaternionMsgFromYaw(state[2]);\n\n \/\/ We can't directly publish the transformation from global_frame_id to\n \/\/ base_frame_id because it would create a cycle in the TF tree. Instead,\n \/\/ we publish a transform from global_frame_id to odom_frame_id. This is\n \/\/ equivalent to transforming from base_frame_id to odom_frame_id.\n geometry_msgs::PoseStamped fused_odom;\n sub_tf->transformPose(odom_frame_id, fused_base, fused_odom);\n\n \/\/ Publish the odometry message.\n nav_msgs::Odometry msg;\n msg.header.stamp = stamp;\n msg.header.frame_id = global_frame_id;\n msg.child_frame_id = odom_frame_id;\n msg.pose.pose = fused_odom.pose;\n msg.pose.covariance[0] = -1;\n msg.twist.twist = velocity;\n msg.twist.covariance[0] = -1;\n pub_fused.publish(msg);\n\n\n \/\/ Transformation.\n geometry_msgs::TransformStamped transform;\n transform.header.stamp = stamp;\n transform.header.frame_id = global_frame_id;\n transform.child_frame_id = odom_frame_id;\n transform.transform.translation.x = fused_odom.pose.position.x;\n transform.transform.translation.y = fused_odom.pose.position.y;\n transform.transform.translation.z = fused_odom.pose.position.z;\n transform.transform.rotation = fused_odom.pose.orientation;\n pub_tf->sendTransform(transform);\n}\n\nstatic void updateCompass(sensor_msgs::Imu const &msg)\n{\n try {\n ros::Time const stamp = msg.header.stamp;\n std::string const frame_id = msg.header.frame_id;\n\n \/\/ Transform the orientation into the base coordinate frame.\n geometry_msgs::QuaternionStamped stamped_in, stamped_out;\n stamped_in.header.frame_id = frame_id;\n stamped_in.header.stamp = stamp;\n stamped_in.quaternion = msg.orientation;\n sub_tf->transformQuaternion(base_frame_id, stamped_in, stamped_out);\n\n \/\/ Rotate the covariance matrix according to the transformation.\n tf::StampedTransform transform;\n Eigen::Affine3d eigen_transform;\n sub_tf->lookupTransform(base_frame_id, frame_id, stamp, transform);\n tf::TransformTFToEigen(transform, eigen_transform);\n\n Eigen::Matrix3d const rotation = eigen_transform.rotation();\n Eigen::Map<Eigen::Matrix3d const> cov_raw(&msg.orientation_covariance.front());\n Eigen::Matrix3d const cov = rotation.transpose() * cov_raw * rotation;\n\n kf.update_compass(tf::getYaw(stamped_out.quaternion), cov(2, 2));\n if (watch_compass) publish(stamp);\n } catch (tf::ExtrapolationException const &e) {\n ROS_WARN(\"%s\", e.what());\n }\n}\n\nstatic void updateEncoders(nav_msgs::Odometry const &msg)\n{\n if (msg.header.frame_id != odom_frame_id\n || msg.child_frame_id != base_frame_id) {\n ROS_ERROR_THROTTLE(10,\n \"Odometry message must have a frame_id '%s' and child_frame_id '%s'\",\n odom_frame_id.c_str(), base_frame_id.c_str()\n );\n return;\n }\n\n Eigen::Vector3d const z = (Eigen::Vector3d() <<\n msg.pose.pose.position.x,\n msg.pose.pose.position.y,\n tf::getYaw(msg.pose.pose.orientation)\n ).finished();\n Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n &msg.pose.covariance.front()\n );\n\n Eigen::Matrix3d cov_z = Eigen::Matrix3d::Zero();\n cov_z.topLeftCorner<2, 2>() = cov_raw.topLeftCorner<2, 2>();\n cov_z(2, 2) = cov_raw(5, 5);\n\n \/\/ Save the current velocity to republish later. This is necessary because\n \/\/ no other sensors measure velocity.\n velocity = msg.twist.twist;\n\n kf.update_encoders(z, cov_z);\n if (watch_encoders) publish(msg.header.stamp);\n}\n\nstatic void updateGps(nav_msgs::Odometry const &msg)\n{\n try {\n ros::Time const stamp = msg.header.stamp;\n std::string const frame_id = msg.child_frame_id;\n\n \/\/ Transform the position into the base coordinate frame.\n geometry_msgs::PointStamped stamped_in, stamped_out;\n stamped_in.header.stamp = stamp;\n stamped_in.header.frame_id = frame_id;\n stamped_in.point = msg.pose.pose.position;\n sub_tf->transformPoint(base_frame_id, stamped_in, stamped_out);\n\n Eigen::Vector2d const z = (Eigen::Vector2d() <<\n stamped_out.point.x, stamped_out.point.y).finished();\n Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n &msg.pose.covariance.front()\n );\n Eigen::Matrix3d const cov3_raw = cov_raw.topLeftCorner<3, 3>();\n\n \/\/ Rotate the covariance matrix according to the transformation.\n tf::StampedTransform transform;\n Eigen::Affine3d eigen_transform;\n sub_tf->lookupTransform(base_frame_id, frame_id, stamp, transform);\n tf::TransformTFToEigen(transform, eigen_transform);\n\n Eigen::Matrix3d const rotation = eigen_transform.rotation();\n Eigen::Matrix3d const cov3 = rotation.transpose() * cov3_raw * rotation;\n Eigen::Matrix2d const cov = cov3.topLeftCorner<2, 2>();\n\n kf.update_gps(z, cov);\n if (watch_gps) publish(msg.header.stamp);\n } catch (tf::ExtrapolationException const &e) {\n ROS_WARN(\"%s\", e.what());\n }\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"robot_kf_node\");\n\n ros::NodeHandle nh, nh_node(\"~\");\n nh_node.param<bool>(\"watch_compass\", watch_compass, true);\n nh_node.param<bool>(\"watch_encoders\", watch_encoders, true);\n nh_node.param<bool>(\"watch_gps\", watch_gps, true);\n nh_node.param<std::string>(\"global_frame_id\", global_frame_id, \"\/map\");\n nh_node.param<std::string>(\"odom_frame_id\", odom_frame_id, \"\/odom\");\n nh_node.param<std::string>(\"base_frame_id\", base_frame_id, \"\/base_footprint\");\n\n sub_tf = boost::make_shared<tf::TransformListener>();\n pub_tf = boost::make_shared<tf::TransformBroadcaster>();\n sub_compass = nh.subscribe(\"compass\", 1, &updateCompass);\n \/\/sub_encoders = nh.subscribe(\"odom\", 1, &updateEncoders);\n sub_gps = nh.subscribe(\"gps\", 1, &updateGps);\n pub_fused = nh.advertise<nav_msgs::Odometry>(\"odom_fused\", 100);\n\n ros::spin();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Heiko Strathmann\n *\/\n\n#include <shogun\/statistics\/TwoSampleTestStatistic.h>\n#include <shogun\/features\/Features.h>\n\nusing namespace shogun;\n\nCTwoSampleTestStatistic::CTwoSampleTestStatistic() : CTestStatistic()\n{\n\tinit();\n}\n\nCTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p_and_q,\n\t\tindex_t q_start) :\n\t\tCTestStatistic()\n{\n\tinit();\n\n\tm_p_and_q=p_and_q;\n\tSG_REF(m_p_and_q);\n\n\tm_q_start=q_start;\n}\n\nCTwoSampleTestStatistic::~CTwoSampleTestStatistic()\n{\n\tSG_UNREF(m_p_and_q);\n}\n\nvoid CTwoSampleTestStatistic::init()\n{\n\t\/* TODO register parameters *\/\n\tm_p_and_q=NULL;\n\tm_q_start=0;\n\tm_bootstrap_iterations=100;\n\tm_p_value_method=BOOTSTRAP;\n}\n\nvoid CTwoSampleTestStatistic::set_p_value_method(EPValueMethod p_value_method)\n{\n\tm_p_value_method=p_value_method;\n}\n\nSGVector<float64_t> CTwoSampleTestStatistic::bootstrap_null()\n{\n\t\/* compute bootstrap statistics for null distribution *\/\n\tSGVector<float64_t> results(m_bootstrap_iterations);\n\n\t\/* memory for index permutations, (would slow down loop) *\/\n\tSGVector<index_t> ind_permutation(m_p_and_q->get_num_vectors());\n\tind_permutation.range_fill();\n\n\tfor (index_t i=0; i<m_bootstrap_iterations; ++i)\n\t{\n\t\t\/* idea: merge features of p and q, shuffle, and compute statistic.\n\t\t * This is done using subsets here *\/\n\n\t\t\/* create index permutation and add as subset. This will mix samples\n\t\t * from p and q *\/\n\t\tSGVector<int32_t>::permute_vector(ind_permutation);\n\t\tm_p_and_q->add_subset(ind_permutation);\n\n\t\t\/* compute statistic for this permutation of mixed samples *\/\n\t\tresults.vector[i]=compute_statistic();\n\n\t\t\/* clean up *\/\n\t\tm_p_and_q->remove_subset();\n\t}\n\n\t\/* clean up and return *\/\n\treturn results;\n}\n\nvoid CTwoSampleTestStatistic::set_bootstrap_iterations(index_t bootstrap_iterations)\n{\n\tm_bootstrap_iterations=bootstrap_iterations;\n}\n\nfloat64_t CTwoSampleTestStatistic::compute_p_value(float64_t statistic)\n{\n\tfloat64_t result=0;\n\n\tif (m_p_value_method==BOOTSTRAP)\n\t{\n\t\t\/* bootstrap a bunch of MMD values from null distribution *\/\n\t\tSGVector<float64_t> values=bootstrap_null();\n\n\t\t\/* find out percentile of parameter \"statistic\" in null distribution *\/\n\t\tCMath::qsort(values);\n\t\tfloat64_t i=CMath::find_position_to_insert(values, statistic);\n\n\t\t\/* return corresponding p-value *\/\n\t\tresult=1.0-i\/values.vlen;\n\t}\n\telse\n\t{\n\t\tSG_ERROR(\"%s::compute_p_value(): Unknown method to compute\"\n\t\t\t\t\" p-value!\\n\");\n\t}\n\n\treturn result;\n}\n\n<commit_msg>moved some code outside loop to gain performance<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Heiko Strathmann\n *\/\n\n#include <shogun\/statistics\/TwoSampleTestStatistic.h>\n#include <shogun\/features\/Features.h>\n\nusing namespace shogun;\n\nCTwoSampleTestStatistic::CTwoSampleTestStatistic() : CTestStatistic()\n{\n\tinit();\n}\n\nCTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p_and_q,\n\t\tindex_t q_start) :\n\t\tCTestStatistic()\n{\n\tinit();\n\n\tm_p_and_q=p_and_q;\n\tSG_REF(m_p_and_q);\n\n\tm_q_start=q_start;\n}\n\nCTwoSampleTestStatistic::~CTwoSampleTestStatistic()\n{\n\tSG_UNREF(m_p_and_q);\n}\n\nvoid CTwoSampleTestStatistic::init()\n{\n\t\/* TODO register parameters *\/\n\tm_p_and_q=NULL;\n\tm_q_start=0;\n\tm_bootstrap_iterations=100;\n\tm_p_value_method=BOOTSTRAP;\n}\n\nvoid CTwoSampleTestStatistic::set_p_value_method(EPValueMethod p_value_method)\n{\n\tm_p_value_method=p_value_method;\n}\n\nSGVector<float64_t> CTwoSampleTestStatistic::bootstrap_null()\n{\n\t\/* compute bootstrap statistics for null distribution *\/\n\tSGVector<float64_t> results(m_bootstrap_iterations);\n\n\t\/* memory for index permutations, (would slow down loop) *\/\n\tSGVector<index_t> ind_permutation(m_p_and_q->get_num_vectors());\n\tind_permutation.range_fill();\n\tm_p_and_q->add_subset(ind_permutation);\n\n\tfor (index_t i=0; i<m_bootstrap_iterations; ++i)\n\t{\n\t\t\/* idea: merge features of p and q, shuffle, and compute statistic.\n\t\t * This is done using subsets here *\/\n\n\t\t\/* create index permutation and add as subset. This will mix samples\n\t\t * from p and q *\/\n\t\tSGVector<int32_t>::permute_vector(ind_permutation);\n\n\t\t\/* compute statistic for this permutation of mixed samples *\/\n\t\tresults.vector[i]=compute_statistic();\n\t}\n\n\t\/* clean up *\/\n\tm_p_and_q->remove_subset();\n\n\t\/* clean up and return *\/\n\treturn results;\n}\n\nvoid CTwoSampleTestStatistic::set_bootstrap_iterations(index_t bootstrap_iterations)\n{\n\tm_bootstrap_iterations=bootstrap_iterations;\n}\n\nfloat64_t CTwoSampleTestStatistic::compute_p_value(float64_t statistic)\n{\n\tfloat64_t result=0;\n\n\tif (m_p_value_method==BOOTSTRAP)\n\t{\n\t\t\/* bootstrap a bunch of MMD values from null distribution *\/\n\t\tSGVector<float64_t> values=bootstrap_null();\n\n\t\t\/* find out percentile of parameter \"statistic\" in null distribution *\/\n\t\tCMath::qsort(values);\n\t\tfloat64_t i=CMath::find_position_to_insert(values, statistic);\n\n\t\t\/* return corresponding p-value *\/\n\t\tresult=1.0-i\/values.vlen;\n\t}\n\telse\n\t{\n\t\tSG_ERROR(\"%s::compute_p_value(): Unknown method to compute\"\n\t\t\t\t\" p-value!\\n\");\n\t}\n\n\treturn result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <SDL\/SDL.h>\n#include <SDL\/SDL_image.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <math.h>\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <assert.h>\n#include \"test.h\"\n\n#include \"narf\/camera.h\"\n#include \"narf\/entity.h\"\n#include \"narf\/input.h\"\n#include \"narf\/vector.h\"\n#include \"narf\/world.h\"\n#include \"narf\/config\/config.h\"\n\n#include \"narf\/gl\/gl.h\"\n\n\/\/ TODO: this is all hacky test code - refactor into nicely modularized code\n\nnarf::Entity *player;\nnarf::Entity *bouncy_block; \/\/ temp hack\n\nnarf::config::ConfigManager configmanager;\n\nnarf::Camera cam;\n\nconst float movespeed = 25.0f;\n\nnarf::World *world;\n\n#define WORLD_X_MAX 64\n#define WORLD_Y_MAX 64\n#define WORLD_Z_MAX 64\n\nSDL_Surface *tiles_surf;\n\nnarf::gl::Context *display;\nnarf::gl::Texture *tiles_tex;\n\nboost::filesystem::path data_dir;\n\n\nfloat clampf(float val, float min, float max)\n{\n\tif (val < min) val = min;\n\tif (val > max) val = max;\n\treturn val;\n}\n\n\nbool init_video(int w, int h, int bpp, bool fullscreen)\n{\n\tdisplay = new narf::gl::Context();\n\tif (!display->set_display_mode(w, h, bpp, fullscreen)) {\n\t\treturn false;\n\t}\n\n\t\/\/ viewer projection\n\tglMatrixMode(GL_PROJECTION);\n\t\/\/float fovx = 90.0f; \/\/ degrees\n\tfloat fovy = 60.0f; \/\/ degrees\n\tfloat aspect = (float)w \/ (float)h ; \/\/ TODO: include fovx in calculation\n\tgluPerspective(fovy, aspect, 0.1, 1000.0f);\n\tglMatrixMode(GL_MODELVIEW);\n\n\tglEnable(GL_DEPTH_TEST);\n\n\tglEnable(GL_TEXTURE_2D);\n\n\t\/\/ for drawing outlines\n\tglPolygonOffset(1.0, 2);\n\tglEnable(GL_POLYGON_OFFSET_FILL);\n\n\tglClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\tglClearDepth(1.0f);\n\n\treturn true;\n}\n\n\nbool init_textures()\n{\n\tconst std::string terrain_file = configmanager.get<std::string>(\"test.terrain\");\n\ttiles_surf = IMG_Load((data_dir \/ terrain_file).string().c_str());\n\tif (!tiles_surf) {\n\t\tfprintf(stderr, \"%s not found!\\n\", terrain_file.c_str());\n\t\tSDL_Quit();\n\t}\n\n\ttiles_tex = new narf::gl::Texture(display);\n\tif (!tiles_tex->upload(tiles_surf)) {\n\t\tassert(0);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\nvoid draw()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tworld->render(tiles_tex, &cam);\n\n\t\/\/ temp hack: draw an entity as a cube for physics demo\n\tvoid draw_cube(float x, float y, float z, uint8_t type, unsigned draw_face_mask);\n\tdraw_cube(bouncy_block->position.x, bouncy_block->position.y, bouncy_block->position.z, 1, 0xFF);\n\n\tSDL_GL_SwapBuffers();\n}\n\n\nvoid poll_input(narf::Input *input)\n{\n\tSDL_Event e;\n\n\tinput->begin_sample();\n\twhile (SDL_PollEvent(&e)) {\n\t\tinput->process_event(&e);\n\t}\n\tinput->end_sample();\n}\n\n\nvoid sim_frame(const narf::Input &input, double t, double dt)\n{\n\t\/\/ TODO: decouple player direction and camera direction\n\tcam.yaw += input.look_rel().x;\n\tcam.yaw = fmodf(cam.yaw, (float)M_PI * 2.0f);\n\n\tcam.pitch += input.look_rel().y;\n\tcam.pitch = clampf(cam.pitch, -(float)M_PI \/ 2, (float)M_PI \/ 2);\n\n\tnarf::Vector3f vel_rel(0.0f, 0.0f, 0.0f);\n\n\tif (input.move_forward()) {\n\t\tvel_rel -= narf::Vector3f(cosf(cam.yaw + (float)M_PI \/ 2), 0.0f, sinf(cam.yaw + (float)M_PI \/ 2));\n\t} else if (input.move_backward()) {\n\t\tvel_rel += narf::Vector3f(cosf(cam.yaw + (float)M_PI \/ 2), 0.0f, sinf(cam.yaw + (float)M_PI \/ 2));\n\t}\n\n\tif (input.strafe_left()) {\n\t\tvel_rel -= narf::Vector3f(cosf(cam.yaw), 0.0f, sinf(cam.yaw));\n\t} else if (input.strafe_right()) {\n\t\tvel_rel += narf::Vector3f(cosf(cam.yaw), 0.0f, sinf(cam.yaw));\n\t}\n\n\t\/\/ normalize so that diagonal movement is not faster than cardinal directions\n\tvel_rel = vel_rel.normalize() * movespeed;\n\n\tif (input.jump()) {\n\t\tvel_rel += narf::Vector3f(0.0f, 8.0f, 0.0f);\n\t}\n\n\t\/\/ hax\n\tplayer->velocity.x = vel_rel.x;\n\tplayer->velocity.y += vel_rel.y;\n\tplayer->velocity.z = vel_rel.z;\n\n\tplayer->update(t, dt);\n\n\t\/\/ lock camera to player\n\tcam.position = player->position;\n\tcam.position.y += 2.0f;\n\n\tbouncy_block->update(t, dt);\n}\n\n\ndouble get_time()\n{\n\treturn (double)SDL_GetTicks() * 0.001; \/\/ SDL tick is a millisecond; convert to seconds\n}\n\n\nvoid game_loop()\n{\n\tconst double input_divider = configmanager.get<double>(\"test.input_divider\");\n\tnarf::Input input(1.0f \/ input_divider, 1.0f \/ input_divider);\n\tdouble t = 0.0;\n\tdouble t1 = get_time();\n\tconst double physics_tick_step = configmanager.get<double>(\"test.physics_tick_step\"); \/\/ fixed time step\n\tconst double max_frame_time = configmanager.get<double>(\"test.max_frame_time\");\n\n\tdouble t_accum = 0.0;\n\n\tdouble fps_t1 = get_time();\n\tunsigned physics_steps = 0;\n\tunsigned draws = 0;\n\n\twhile (1) {\n\t\tdouble t2 = get_time();\n\t\tdouble frame_time = t2 - t1;\n\n\t\tif (frame_time > max_frame_time) {\n\t\t\tframe_time = max_frame_time;\n\t\t}\n\n\t\tt1 = t2;\n\n\t\tt_accum += frame_time;\n\n\t\twhile (t_accum >= physics_tick_step)\n\t\t{\n\t\t\tpoll_input(&input);\n\t\t\tif (input.exit()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsim_frame(input, t, physics_tick_step);\n\t\t\tphysics_steps++;\n\n\t\t\tt_accum -= physics_tick_step;\n\t\t\tt += physics_tick_step;\n\t\t}\n\n\t\tdouble fps_dt = get_time() - fps_t1;\n\t\tif (fps_dt >= 1.0) {\n\t\t\t\/\/ update fps counter\n\t\t\tprintf(\"%f physics steps\/%f renders per second (dt %f)\\n\", (double)physics_steps \/ fps_dt, (double)draws \/ fps_dt, fps_dt);\n\t\t\tfps_t1 = get_time();\n\t\t\tdraws = physics_steps = 0;\n\t\t}\n\n\t\tdraw();\n\t\tdraws++;\n\t}\n}\n\n\nfloat randf(float min, float max)\n{\n\treturn ((float)rand() \/ (float)RAND_MAX) * (max - min + 1.0f) + min;\n}\n\nint randi(int min, int max)\n{\n\treturn (int)randf(min, max); \/\/ HAX\n}\n\n\nvoid gen_world()\n{\n\tworld = new narf::World(WORLD_X_MAX, WORLD_Y_MAX, WORLD_Z_MAX, 16, 16, 16);\n\n\t\/\/ first fill a plane at y = 0\n\tfor (int z = 0; z < WORLD_Z_MAX; z++) {\n\t\tfor (int x = 0; x < WORLD_X_MAX; x++) {\n\t\t\tnarf::Block b;\n\t\t\tb.id = 2; \/\/ grass\n\t\t\tworld->put_block(&b, x, 0, z);\n\t\t}\n\t}\n\n\t\/\/ generate some random blocks above the ground\n\tfor (int i = 0; i < 1000; i++) {\n\t\tint x = randi(0, WORLD_X_MAX - 1);\n\t\tint y = randi(1, 10);\n\t\tint z = randi(0, WORLD_Z_MAX - 1);\n\t\tnarf::Block b;\n\t\tb.id = randi(1, 3);\n\t\tworld->put_block(&b, x, y, z);\n\t}\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tnarf::Block b;\n\t\tb.id = 16;\n\t\tworld->put_block(&b, 5 + i, 1, 5);\n\t\tworld->put_block(&b, 5, 1, 5 + i);\n\t\tworld->put_block(&b, 5 + i, 1, 15);\n\t}\n\n\tworld->set_gravity(-9.8f);\n}\n\n\nextern \"C\" int main(int argc, char **argv)\n{\n\tprintf(\"Version: %d.%d%s\\n\", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE);\n\n\tdata_dir = boost::filesystem::current_path();\n\n\t\/\/ walk up the path until data directory is found\n\tfor (auto dir = boost::filesystem::current_path(); dir != dir.root_path(); dir = dir.parent_path()) {\n\t\tdata_dir = dir \/ \"data\";\n\t\tif (boost::filesystem::is_directory(data_dir)) {\n\t\t\tprintf(\"Found data directory: %s\\n\", data_dir.string().c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Will explode if things don't exist\n\tconfigmanager.load(\"test\", (data_dir \/ \"test.yaml\").string());\n\tnarf::config::Property bar = configmanager.get(\"test.foo.bar\");\n\tprintf(\"ConfigManager test: test.foo.bar = %d\\n\", bar.as<int>());\n\n\tif (SDL_Init(SDL_INIT_EVERYTHING) < 0) {\n\t\tprintf(\"SDL_Init(SDL_INIT_EVERYTHING) failed: %s\\n\", SDL_GetError());\n\t\tSDL_Quit();\n\t\treturn 1;\n\t}\n\n\tconst SDL_VideoInfo *vid_info = SDL_GetVideoInfo();\n\n\tprintf(\"Current video mode is %dx%dx%d\\n\", vid_info->current_w, vid_info->current_h, vid_info->vfmt->BitsPerPixel);\n\n\tint w = vid_info->current_w;\n\tint h = vid_info->current_h;\n\tint bpp = vid_info->vfmt->BitsPerPixel;\n\tbool fullscreen = true;\n\n\t\/\/ TODO: read w, h, bpp from config file to override defaults\n\n\tSDL_WM_SetCaption(\"NarfBlock\", \"NarfBlock\");\n\n\tif (!init_video(w, h, bpp, fullscreen)) {\n\t\tfprintf(stderr, \"Error: could not set OpenGL video mode %dx%d@%d bpp\\n\", w, h, bpp);\n\t\tSDL_Quit();\n\t\treturn 1;\n\t}\n\n\tsrand(0x1234);\n\tgen_world();\n\n\tplayer = new narf::Entity(world);\n\n\t\/\/ initial player position\n\tplayer->position = narf::Vector3f(15.0f, 1.0f, 10.0f);\n\n\t\/\/ initialize camera to look at origin\n\tcam.yaw = atan2f(cam.position.z, cam.position.x) - (float)M_PI \/ 2;\n\tcam.pitch = 0.0f;\n\n\tbouncy_block = new narf::Entity(world);\n\tbouncy_block->position = narf::Vector3f(10.0f, 5.0f, 10.0f);\n\tbouncy_block->bouncy = true;\n\n\tinit_textures();\n\n\tSDL_ShowCursor(0);\n\tSDL_WM_GrabInput(SDL_GRAB_ON);\n\n\tgame_loop();\n\n\tSDL_Quit();\n\treturn 0;\n}\n<commit_msg>Reverting silly change to test.cpp<commit_after>#include <SDL\/SDL.h>\n#include <SDL\/SDL_image.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <math.h>\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <assert.h>\n#include \"test.h\"\n\n#include \"narf\/camera.h\"\n#include \"narf\/entity.h\"\n#include \"narf\/input.h\"\n#include \"narf\/vector.h\"\n#include \"narf\/world.h\"\n#include \"narf\/config\/config.h\"\n\n#include \"narf\/gl\/gl.h\"\n\n\/\/ TODO: this is all hacky test code - refactor into nicely modularized code\n\nnarf::Entity *player;\nnarf::Entity *bouncy_block; \/\/ temp hack\n\nnarf::config::ConfigManager configmanager;\n\nnarf::Camera cam;\n\nconst float movespeed = 25.0f;\n\nnarf::World *world;\n\n#define WORLD_X_MAX 64\n#define WORLD_Y_MAX 64\n#define WORLD_Z_MAX 64\n\nSDL_Surface *tiles_surf;\n\nnarf::gl::Context *display;\nnarf::gl::Texture *tiles_tex;\n\nboost::filesystem::path data_dir;\n\n\nfloat clampf(float val, float min, float max)\n{\n\tif (val < min) val = min;\n\tif (val > max) val = max;\n\treturn val;\n}\n\n\nbool init_video(int w, int h, int bpp, bool fullscreen)\n{\n\tdisplay = new narf::gl::Context();\n\tif (!display->set_display_mode(w, h, bpp, fullscreen)) {\n\t\treturn false;\n\t}\n\n\t\/\/ viewer projection\n\tglMatrixMode(GL_PROJECTION);\n\t\/\/float fovx = 90.0f; \/\/ degrees\n\tfloat fovy = 60.0f; \/\/ degrees\n\tfloat aspect = (float)w \/ (float)h ; \/\/ TODO: include fovx in calculation\n\tgluPerspective(fovy, aspect, 0.1, 1000.0f);\n\tglMatrixMode(GL_MODELVIEW);\n\n\tglEnable(GL_DEPTH_TEST);\n\n\tglEnable(GL_TEXTURE_2D);\n\n\t\/\/ for drawing outlines\n\tglPolygonOffset(1.0, 2);\n\tglEnable(GL_POLYGON_OFFSET_FILL);\n\n\tglClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\tglClearDepth(1.0f);\n\n\treturn true;\n}\n\n\nbool init_textures()\n{\n\tconst std::string terrain_file = configmanager.get<std::string>(\"test.terrain\");\n\ttiles_surf = IMG_Load((data_dir \/ terrain_file).string().c_str());\n\tif (!tiles_surf) {\n\t\tfprintf(stderr, \"%s not found!\\n\", terrain_file.c_str());\n\t\tSDL_Quit();\n\t}\n\n\ttiles_tex = new narf::gl::Texture(display);\n\tif (!tiles_tex->upload(tiles_surf)) {\n\t\tassert(0);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\nvoid draw()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tworld->render(tiles_tex, &cam);\n\n\t\/\/ temp hack: draw an entity as a cube for physics demo\n\tvoid draw_cube(float x, float y, float z, uint8_t type, unsigned draw_face_mask);\n\tdraw_cube(bouncy_block->position.x, bouncy_block->position.y, bouncy_block->position.z, 1, 0xFF);\n\n\tSDL_GL_SwapBuffers();\n}\n\n\nvoid poll_input(narf::Input *input)\n{\n\tSDL_Event e;\n\n\tinput->begin_sample();\n\twhile (SDL_PollEvent(&e)) {\n\t\tinput->process_event(&e);\n\t}\n\tinput->end_sample();\n}\n\n\nvoid sim_frame(const narf::Input &input, double t, double dt)\n{\n\t\/\/ TODO: decouple player direction and camera direction\n\tcam.yaw += input.look_rel().x;\n\tcam.yaw = fmodf(cam.yaw, (float)M_PI * 2.0f);\n\n\tcam.pitch += input.look_rel().y;\n\tcam.pitch = clampf(cam.pitch, -(float)M_PI \/ 2, (float)M_PI \/ 2);\n\n\tnarf::Vector3f vel_rel(0.0f, 0.0f, 0.0f);\n\n\tif (input.move_forward()) {\n\t\tvel_rel -= narf::Vector3f(cosf(cam.yaw + (float)M_PI \/ 2), 0.0f, sinf(cam.yaw + (float)M_PI \/ 2));\n\t} else if (input.move_backward()) {\n\t\tvel_rel += narf::Vector3f(cosf(cam.yaw + (float)M_PI \/ 2), 0.0f, sinf(cam.yaw + (float)M_PI \/ 2));\n\t}\n\n\tif (input.strafe_left()) {\n\t\tvel_rel -= narf::Vector3f(cosf(cam.yaw), 0.0f, sinf(cam.yaw));\n\t} else if (input.strafe_right()) {\n\t\tvel_rel += narf::Vector3f(cosf(cam.yaw), 0.0f, sinf(cam.yaw));\n\t}\n\n\t\/\/ normalize so that diagonal movement is not faster than cardinal directions\n\tvel_rel = vel_rel.normalize() * movespeed;\n\n\tif (input.jump()) {\n\t\tvel_rel += narf::Vector3f(0.0f, 8.0f, 0.0f);\n\t}\n\n\t\/\/ hax\n\tplayer->velocity.x = vel_rel.x;\n\tplayer->velocity.y += vel_rel.y;\n\tplayer->velocity.z = vel_rel.z;\n\n\tplayer->update(t, dt);\n\n\t\/\/ lock camera to player\n\tcam.position = player->position;\n\tcam.position.y += 2.0f;\n\n\tbouncy_block->update(t, dt);\n}\n\n\ndouble get_time()\n{\n\treturn (double)SDL_GetTicks() * 0.001; \/\/ SDL tick is a millisecond; convert to seconds\n}\n\n\nvoid game_loop()\n{\n\tconst double input_divider = configmanager.get<double>(\"test.input_divider\");\n\tnarf::Input input(1.0f \/ input_divider, 1.0f \/ input_divider);\n\tdouble t = 0.0;\n\tdouble t1 = get_time();\n\tconst double physics_rate = configmanager.get<double>(\"test.physics_rate\");\n\tconst double physics_tick_step = 1.0 \/ physics_rate; \/\/ fixed time step\n\tconst double max_frame_time = configmanager.get<double>(\"test.max_frame_time\");\n\n\tdouble t_accum = 0.0;\n\n\tdouble fps_t1 = get_time();\n\tunsigned physics_steps = 0;\n\tunsigned draws = 0;\n\n\twhile (1) {\n\t\tdouble t2 = get_time();\n\t\tdouble frame_time = t2 - t1;\n\n\t\tif (frame_time > max_frame_time) {\n\t\t\tframe_time = max_frame_time;\n\t\t}\n\n\t\tt1 = t2;\n\n\t\tt_accum += frame_time;\n\n\t\twhile (t_accum >= physics_tick_step)\n\t\t{\n\t\t\tpoll_input(&input);\n\t\t\tif (input.exit()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsim_frame(input, t, physics_tick_step);\n\t\t\tphysics_steps++;\n\n\t\t\tt_accum -= physics_tick_step;\n\t\t\tt += physics_tick_step;\n\t\t}\n\n\t\tdouble fps_dt = get_time() - fps_t1;\n\t\tif (fps_dt >= 1.0) {\n\t\t\t\/\/ update fps counter\n\t\t\tprintf(\"%f physics steps\/%f renders per second (dt %f)\\n\", (double)physics_steps \/ fps_dt, (double)draws \/ fps_dt, fps_dt);\n\t\t\tfps_t1 = get_time();\n\t\t\tdraws = physics_steps = 0;\n\t\t}\n\n\t\tdraw();\n\t\tdraws++;\n\t}\n}\n\n\nfloat randf(float min, float max)\n{\n\treturn ((float)rand() \/ (float)RAND_MAX) * (max - min + 1.0f) + min;\n}\n\nint randi(int min, int max)\n{\n\treturn (int)randf(min, max); \/\/ HAX\n}\n\n\nvoid gen_world()\n{\n\tworld = new narf::World(WORLD_X_MAX, WORLD_Y_MAX, WORLD_Z_MAX, 16, 16, 16);\n\n\t\/\/ first fill a plane at y = 0\n\tfor (int z = 0; z < WORLD_Z_MAX; z++) {\n\t\tfor (int x = 0; x < WORLD_X_MAX; x++) {\n\t\t\tnarf::Block b;\n\t\t\tb.id = 2; \/\/ grass\n\t\t\tworld->put_block(&b, x, 0, z);\n\t\t}\n\t}\n\n\t\/\/ generate some random blocks above the ground\n\tfor (int i = 0; i < 1000; i++) {\n\t\tint x = randi(0, WORLD_X_MAX - 1);\n\t\tint y = randi(1, 10);\n\t\tint z = randi(0, WORLD_Z_MAX - 1);\n\t\tnarf::Block b;\n\t\tb.id = randi(1, 3);\n\t\tworld->put_block(&b, x, y, z);\n\t}\n\n\tfor (int i = 0; i < 10; i++) {\n\t\tnarf::Block b;\n\t\tb.id = 16;\n\t\tworld->put_block(&b, 5 + i, 1, 5);\n\t\tworld->put_block(&b, 5, 1, 5 + i);\n\t\tworld->put_block(&b, 5 + i, 1, 15);\n\t}\n\n\tworld->set_gravity(-9.8f);\n}\n\n\nextern \"C\" int main(int argc, char **argv)\n{\n\tprintf(\"Version: %d.%d%s\\n\", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE);\n\n\tdata_dir = boost::filesystem::current_path();\n\n\t\/\/ walk up the path until data directory is found\n\tfor (auto dir = boost::filesystem::current_path(); dir != dir.root_path(); dir = dir.parent_path()) {\n\t\tdata_dir = dir \/ \"data\";\n\t\tif (boost::filesystem::is_directory(data_dir)) {\n\t\t\tprintf(\"Found data directory: %s\\n\", data_dir.string().c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Will explode if things don't exist\n\tconfigmanager.load(\"test\", (data_dir \/ \"test.yaml\").string());\n\tnarf::config::Property bar = configmanager.get(\"test.foo.bar\");\n\tprintf(\"ConfigManager test: test.foo.bar = %d\\n\", bar.as<int>());\n\n\tif (SDL_Init(SDL_INIT_EVERYTHING) < 0) {\n\t\tprintf(\"SDL_Init(SDL_INIT_EVERYTHING) failed: %s\\n\", SDL_GetError());\n\t\tSDL_Quit();\n\t\treturn 1;\n\t}\n\n\tconst SDL_VideoInfo *vid_info = SDL_GetVideoInfo();\n\n\tprintf(\"Current video mode is %dx%dx%d\\n\", vid_info->current_w, vid_info->current_h, vid_info->vfmt->BitsPerPixel);\n\n\tint w = vid_info->current_w;\n\tint h = vid_info->current_h;\n\tint bpp = vid_info->vfmt->BitsPerPixel;\n\tbool fullscreen = true;\n\n\t\/\/ TODO: read w, h, bpp from config file to override defaults\n\n\tSDL_WM_SetCaption(\"NarfBlock\", \"NarfBlock\");\n\n\tif (!init_video(w, h, bpp, fullscreen)) {\n\t\tfprintf(stderr, \"Error: could not set OpenGL video mode %dx%d@%d bpp\\n\", w, h, bpp);\n\t\tSDL_Quit();\n\t\treturn 1;\n\t}\n\n\tsrand(0x1234);\n\tgen_world();\n\n\tplayer = new narf::Entity(world);\n\n\t\/\/ initial player position\n\tplayer->position = narf::Vector3f(15.0f, 1.0f, 10.0f);\n\n\t\/\/ initialize camera to look at origin\n\tcam.yaw = atan2f(cam.position.z, cam.position.x) - (float)M_PI \/ 2;\n\tcam.pitch = 0.0f;\n\n\tbouncy_block = new narf::Entity(world);\n\tbouncy_block->position = narf::Vector3f(10.0f, 5.0f, 10.0f);\n\tbouncy_block->bouncy = true;\n\n\tinit_textures();\n\n\tSDL_ShowCursor(0);\n\tSDL_WM_GrabInput(SDL_GRAB_ON);\n\n\tgame_loop();\n\n\tSDL_Quit();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <ctime>\n#include <string>\n#include <cstdio>\n#include <boost\/limits.hpp>\n#include <boost\/version.hpp>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/time.hpp\"\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\t\/\/ used to cache the current time\n\t\t\/\/ every 100 ms. This is cheaper\n\t\t\/\/ than a system call and can be\n\t\t\/\/ used where more accurate time\n\t\t\/\/ is not necessary\n\t\tptime g_current_time;\n\t}\n\n\tptime const& TORRENT_EXPORT time_now() { return aux::g_current_time; }\n\n\tchar const* time_now_string()\n\t{\n\/\/\t\ttime_t t = std::time(0);\n\/\/\t\ttm* timeinfo = std::localtime(&t);\n\/\/\t\tstatic char str[200];\n\/\/\t\tstd::strftime(str, 200, \"%b %d %X\", timeinfo);\n\/\/\t\treturn str;\n\n\t\tstatic const ptime start = time_now_hires();\n\t\tstatic char ret[200];\n\t\tint t = total_milliseconds(time_now_hires() - start);\n\t\tint h = t \/ 1000 \/ 60 \/ 60;\n\t\tt -= h * 60 * 60 * 1000;\n\t\tint m = t \/ 1000 \/ 60;\n\t\tt -= m * 60 * 1000;\n\t\tint s = t \/ 1000;\n\t\tt -= s * 1000;\n\t\tint ms = t;\n\t\tsnprintf(ret, sizeof(ret), \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t\treturn ret;\n\t}\n\n\tstd::string log_time()\n\t{\n\t\tstatic const ptime start = time_now_hires();\n\t\tchar ret[200];\n\t\tsnprintf(ret, sizeof(ret), \"%\"PRId64, total_microseconds(time_now_hires() - start));\n\t\treturn ret;\n\t}\n}\n\n#if defined TORRENT_USE_BOOST_DATE_TIME\n\n#include <boost\/date_time\/microsec_time_clock.hpp>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return boost::date_time::microsec_clock<ptime>::universal_time(); }\n\tptime min_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }\n\tptime max_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }\n\ttime_duration seconds(int s) { return boost::posix_time::seconds(s); }\n\ttime_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }\n\ttime_duration microsec(int s) { return boost::posix_time::microsec(s); }\n\ttime_duration minutes(int s) { return boost::posix_time::minutes(s); }\n\ttime_duration hours(int s) { return boost::posix_time::hours(s); }\n\n\tint total_seconds(time_duration td)\n\t{ return td.total_seconds(); }\n\tint total_milliseconds(time_duration td)\n\t{ return td.total_milliseconds(); }\n\tboost::int64_t total_microseconds(time_duration td)\n\t{ return td.total_microseconds(); }\n}\n\n#else \/\/ TORRENT_USE_BOOST_DATE_TIME\n\nnamespace libtorrent\n{\n\tptime min_time() { return ptime(0); }\n\tptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }\n}\n\n#if defined TORRENT_USE_ABSOLUTE_TIME\n\n#include <mach\/mach_time.h>\n#include <boost\/cstdint.hpp>\n#include \"libtorrent\/assert.hpp\"\n\n\/\/ high precision timer for darwin intel and ppc\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\tstatic mach_timebase_info_data_t timebase_info = {0,0};\n\t\tif (timebase_info.denom == 0)\n\t\t\tmach_timebase_info(&timebase_info);\n\t\tboost::uint64_t at = mach_absolute_time();\n\t\t\/\/ make sure we don't overflow\n\t\tTORRENT_ASSERT((at >= 0 && at >= at \/ 1000 * timebase_info.numer \/ timebase_info.denom)\n\t\t\t|| (at < 0 && at < at \/ 1000 * timebase_info.numer \/ timebase_info.denom));\n\t\treturn ptime(at \/ 1000 * timebase_info.numer \/ timebase_info.denom);\n\t}\n}\n#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER\n\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n#include <windows.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tboost::int64_t performance_counter_to_microseconds(boost::int64_t pc)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t\tTORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));\n#endif\n\t\t\treturn (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t}\n\n\t\tboost::int64_t microseconds_to_performance_counter(boost::int64_t ms)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t\tTORRENT_ASSERT((ms >= 0 && ms <= ret)\n\t\t\t\t|| (ms < 0 && ms > ret));\n#endif\n\t\t\treturn (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t}\n\t}\n\n\tptime time_now_hires()\n\t{\n\t\tLARGE_INTEGER now;\n\t\tQueryPerformanceCounter(&now);\n\t\treturn ptime(now.QuadPart);\n\t}\n}\n\n#elif defined TORRENT_USE_CLOCK_GETTIME\n\n#include <time.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\ttimespec ts;\n\t\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\t\treturn ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000);\n\t}\n}\n\n#elif defined TORRENT_USE_SYSTEM_TIME\n\n#include <kernel\/OS.h>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return ptime(system_time()); }\n}\n\n#endif \/\/ TORRENT_USE_SYSTEM_TIME\n\n#endif \/\/ TORRENT_USE_BOOST_DATE_TIME\n\n<commit_msg>fix windows DLL build<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <ctime>\n#include <string>\n#include <cstdio>\n#include <boost\/limits.hpp>\n#include <boost\/version.hpp>\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/time.hpp\"\n\n#ifndef _WIN32\n#include <unistd.h>\n#endif\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\t\/\/ used to cache the current time\n\t\t\/\/ every 100 ms. This is cheaper\n\t\t\/\/ than a system call and can be\n\t\t\/\/ used where more accurate time\n\t\t\/\/ is not necessary\n\t\tptime g_current_time;\n\t}\n\n\tTORRENT_EXPORT ptime const& time_now() { return aux::g_current_time; }\n\n\tchar const* time_now_string()\n\t{\n\/\/\t\ttime_t t = std::time(0);\n\/\/\t\ttm* timeinfo = std::localtime(&t);\n\/\/\t\tstatic char str[200];\n\/\/\t\tstd::strftime(str, 200, \"%b %d %X\", timeinfo);\n\/\/\t\treturn str;\n\n\t\tstatic const ptime start = time_now_hires();\n\t\tstatic char ret[200];\n\t\tint t = total_milliseconds(time_now_hires() - start);\n\t\tint h = t \/ 1000 \/ 60 \/ 60;\n\t\tt -= h * 60 * 60 * 1000;\n\t\tint m = t \/ 1000 \/ 60;\n\t\tt -= m * 60 * 1000;\n\t\tint s = t \/ 1000;\n\t\tt -= s * 1000;\n\t\tint ms = t;\n\t\tsnprintf(ret, sizeof(ret), \"%02d:%02d:%02d.%03d\", h, m, s, ms);\n\t\treturn ret;\n\t}\n\n\tstd::string log_time()\n\t{\n\t\tstatic const ptime start = time_now_hires();\n\t\tchar ret[200];\n\t\tsnprintf(ret, sizeof(ret), \"%\"PRId64, total_microseconds(time_now_hires() - start));\n\t\treturn ret;\n\t}\n}\n\n#if defined TORRENT_USE_BOOST_DATE_TIME\n\n#include <boost\/date_time\/microsec_time_clock.hpp>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return boost::date_time::microsec_clock<ptime>::universal_time(); }\n\tptime min_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }\n\tptime max_time()\n\t{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }\n\ttime_duration seconds(int s) { return boost::posix_time::seconds(s); }\n\ttime_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }\n\ttime_duration microsec(int s) { return boost::posix_time::microsec(s); }\n\ttime_duration minutes(int s) { return boost::posix_time::minutes(s); }\n\ttime_duration hours(int s) { return boost::posix_time::hours(s); }\n\n\tint total_seconds(time_duration td)\n\t{ return td.total_seconds(); }\n\tint total_milliseconds(time_duration td)\n\t{ return td.total_milliseconds(); }\n\tboost::int64_t total_microseconds(time_duration td)\n\t{ return td.total_microseconds(); }\n}\n\n#else \/\/ TORRENT_USE_BOOST_DATE_TIME\n\nnamespace libtorrent\n{\n\tptime min_time() { return ptime(0); }\n\tptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }\n}\n\n#if defined TORRENT_USE_ABSOLUTE_TIME\n\n#include <mach\/mach_time.h>\n#include <boost\/cstdint.hpp>\n#include \"libtorrent\/assert.hpp\"\n\n\/\/ high precision timer for darwin intel and ppc\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\tstatic mach_timebase_info_data_t timebase_info = {0,0};\n\t\tif (timebase_info.denom == 0)\n\t\t\tmach_timebase_info(&timebase_info);\n\t\tboost::uint64_t at = mach_absolute_time();\n\t\t\/\/ make sure we don't overflow\n\t\tTORRENT_ASSERT((at >= 0 && at >= at \/ 1000 * timebase_info.numer \/ timebase_info.denom)\n\t\t\t|| (at < 0 && at < at \/ 1000 * timebase_info.numer \/ timebase_info.denom));\n\t\treturn ptime(at \/ 1000 * timebase_info.numer \/ timebase_info.denom);\n\t}\n}\n#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER\n\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n#include <windows.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tboost::int64_t performance_counter_to_microseconds(boost::int64_t pc)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t\tTORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));\n#endif\n\t\t\treturn (pc * 1000 \/ performace_counter_frequency.QuadPart) * 1000;\n\t\t}\n\n\t\tboost::int64_t microseconds_to_performance_counter(boost::int64_t ms)\n\t\t{\n\t\t\tstatic LARGE_INTEGER performace_counter_frequency = {0,0};\n\t\t\tif (performace_counter_frequency.QuadPart == 0)\n\t\t\t\tQueryPerformanceFrequency(&performace_counter_frequency);\n#ifdef TORRENT_DEBUG\n\t\t\t\/\/ make sure we don't overflow\n\t\t\tboost::int64_t ret = (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t\tTORRENT_ASSERT((ms >= 0 && ms <= ret)\n\t\t\t\t|| (ms < 0 && ms > ret));\n#endif\n\t\t\treturn (ms \/ 1000) * performace_counter_frequency.QuadPart \/ 1000;\n\t\t}\n\t}\n\n\tptime time_now_hires()\n\t{\n\t\tLARGE_INTEGER now;\n\t\tQueryPerformanceCounter(&now);\n\t\treturn ptime(now.QuadPart);\n\t}\n}\n\n#elif defined TORRENT_USE_CLOCK_GETTIME\n\n#include <time.h>\n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{\n\t\ttimespec ts;\n\t\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\t\treturn ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000);\n\t}\n}\n\n#elif defined TORRENT_USE_SYSTEM_TIME\n\n#include <kernel\/OS.h>\n\nnamespace libtorrent\n{\n\tptime time_now_hires()\n\t{ return ptime(system_time()); }\n}\n\n#endif \/\/ TORRENT_USE_SYSTEM_TIME\n\n#endif \/\/ TORRENT_USE_BOOST_DATE_TIME\n\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/string_cast.hpp>\n\n#include <zombye\/core\/game.hpp>\n#include <zombye\/rendering\/mesh.hpp>\n#include <zombye\/rendering\/rendering_system.hpp>\n#include <zombye\/utils\/component_helper.hpp>\n#include <zombye\/utils\/logger.hpp>\n\nnamespace zombye {\n rendering_system::rendering_system(game& game, SDL_Window* window)\n : game_{game}, window_{window}, mesh_manager_{game_}, shader_manager_{game_}, skinned_mesh_manager_{game_},\n skeleton_manager_{game_}, texture_manager_{game_}, active_camera_{0}, projection_{1.f}, view_{1.f} {\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\n context_ = SDL_GL_CreateContext(window_);\n auto error = std::string{SDL_GetError()};\n if (error != \"\") {\n log(LOG_FATAL, \"could not create OpenGL context with version 3.1: \" + error);\n }\n SDL_ClearError();\n\n SDL_GL_SetSwapInterval(1);\n\n glewExperimental = GL_TRUE;\n if (glewInit() != GLEW_OK) {\n log(LOG_FATAL, \"could not initialize glew\");\n }\n\n auto version = std::string{reinterpret_cast<const char*>(glGetString(GL_VERSION))};\n log(\"OpenGL version \" + version);\n\n glEnable(GL_DEPTH_TEST);\n clear_color(0.4, 0.5, 0.9, 1.0);\n\n auto vertex_shader = shader_manager_.load(\"shader\/staticmesh.vs\", GL_VERTEX_SHADER);\n auto fragment_shader = shader_manager_.load(\"shader\/staticmesh.fs\", GL_FRAGMENT_SHADER);\n\n staticmesh_program_ = std::make_unique<program>();\n staticmesh_program_->attach_shader(vertex_shader);\n staticmesh_program_->attach_shader(fragment_shader);\n\n staticmesh_layout_.emplace_back(\"position\", 3, GL_FLOAT, GL_FALSE, sizeof(vertex), 0);\n staticmesh_layout_.emplace_back(\"texcoord\", 2, GL_FLOAT, GL_FALSE, sizeof(vertex), 3 * sizeof(float));\n staticmesh_layout_.emplace_back(\"normal\", 3, GL_FLOAT, GL_FALSE, sizeof(vertex), 5 * sizeof(float));\n\n staticmesh_layout_.setup_program(*staticmesh_program_, \"fragcolor\");\n staticmesh_program_->link();\n\n vertex_shader = shader_manager_.load(\"shader\/animation.vs\", GL_VERTEX_SHADER);\n fragment_shader = shader_manager_.load(\"shader\/animation.fs\", GL_FRAGMENT_SHADER);\n\n animation_program_ = std::make_unique<program>();\n animation_program_->attach_shader(vertex_shader);\n animation_program_->attach_shader(fragment_shader);\n\n skinnedmesh_layout_.emplace_back(\"position\", 3, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 0);\n skinnedmesh_layout_.emplace_back(\"texcoord\", 2, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 3 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"normal\", 3, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 5 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"index\", 4, GL_INT, GL_FALSE, sizeof(skinned_vertex), 8 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"weight\", 4, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 12 * sizeof(float));\n\n skinnedmesh_layout_.setup_program(*animation_program_, \"fragcolor\");\n animation_program_->link();\n\n float fovy = 45.f * 3.1415f \/ 180.f;\n auto width = float(game_.width());\n auto height = float(game_.height());\n float aspect = width \/ height;\n float near = 0.01f;\n float far = 1000.f;\n projection_ = glm::perspective(fovy, aspect, near, far);\n ortho_projection_ = glm::ortho(0.f, width, 0.f, height);\n\n g_buffer_ = std::make_unique<framebuffer>();\n g_buffer_->attach(GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, GL_DEPTH_COMPONENT24, width, height, GL_DEPTH_COMPONENT, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n\n g_buffer_->bind();\n glClearColor(0.4f, 0.6f, 0.9f, 1.f);\n GLenum buf[5] = {\n GL_COLOR_ATTACHMENT0,\n GL_COLOR_ATTACHMENT1,\n GL_COLOR_ATTACHMENT2,\n GL_NONE\n };\n glDrawBuffers(5, buf);\n g_buffer_->bind_default();\n }\n\n rendering_system::~rendering_system() {\n window_ = nullptr;\n SDL_GL_DeleteContext(context_);\n }\n\n void rendering_system::begin_scene() {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n }\n\n void rendering_system::end_scene() {\n SDL_GL_SwapWindow(window_);\n }\n\n void rendering_system::update(float delta_time) {\n auto camera = camera_components_.find(active_camera_);\n view_ = glm::mat4{1.f};\n auto camera_position = glm::vec3{0.f};\n if (camera != camera_components_.end()) {\n view_ = camera->second->transform();\n camera_position = camera->second->owner().position();\n }\n\n std::vector<glm::vec3> light_positions;\n std::vector<glm::vec3> light_colors;\n std::vector<float> light_distances;\n auto i = 0;\n for (auto& l : light_components_) {\n if (i > 15) {\n break;\n }\n light_positions.emplace_back(l->owner().position());\n light_colors.emplace_back(l->color());\n light_distances.emplace_back(l->distance());\n }\n int light_count = light_positions.size();\n\n staticmesh_program_->use();\n staticmesh_program_->uniform(\"diffuse_sampler\", 0);\n staticmesh_program_->uniform(\"specular_sampler\", 1);\n staticmesh_program_->uniform(\"light_count\", light_count);\n staticmesh_program_->uniform(\"light_position\", light_count, light_positions);\n staticmesh_program_->uniform(\"light_color\", light_count, light_colors);\n staticmesh_program_->uniform(\"light_distance\", light_count, light_distances);\n staticmesh_program_->uniform(\"view\", camera_position);\n for (auto& s : staticmesh_components_) {\n auto model = s->owner().transform();\n auto model_it = glm::inverse(glm::transpose(model));\n staticmesh_program_->uniform(\"m\", false, model);\n staticmesh_program_->uniform(\"mit\", false, model_it);\n staticmesh_program_->uniform(\"mvp\", false, projection_ * view_ * model);\n s->draw();\n }\n\n animation_program_->use();\n animation_program_->uniform(\"diffuse_sampler\", 0);\n animation_program_->uniform(\"specular_sampler\", 1);\n animation_program_->uniform(\"light_count\", light_count);\n animation_program_->uniform(\"light_position\", light_count, light_positions);\n animation_program_->uniform(\"light_color\", light_count, light_colors);\n animation_program_->uniform(\"light_distance\", light_count, light_distances);\n animation_program_->uniform(\"view\", camera_position);\n for (auto& a: animation_components_) {\n auto model = a->owner().transform();\n auto model_it = glm::inverse(glm::transpose(model));\n animation_program_->uniform(\"m\", false, model);\n animation_program_->uniform(\"mit\", false, model_it);\n animation_program_->uniform(\"mvp\", false, projection_ * view_ * model);\n animation_program_->uniform(\"pose\", a->pose().size(), false, a->pose());\n a->draw();\n }\n }\n\n void rendering_system::clear_color(float red, float green, float blue, float alpha) {\n glClearColor(red, green, blue, alpha);\n }\n\n void rendering_system::register_component(animation_component* component) {\n animation_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(animation_component* component) {\n remove(animation_components_, component);\n }\n\n void rendering_system::register_component(camera_component* component) {\n camera_components_.insert(std::make_pair(component->owner().id(), component));\n }\n\n void rendering_system::unregister_component(camera_component* component) {\n auto it = camera_components_.find(component->owner().id());\n if (it != camera_components_.end()) {\n camera_components_.erase(it);\n }\n }\n\n void rendering_system::register_component(light_component* component) {\n light_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(light_component* component) {\n remove(light_components_, component);\n }\n\n void rendering_system::register_component(staticmesh_component* component) {\n staticmesh_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(staticmesh_component* component) {\n remove(staticmesh_components_, component);\n }\n}\n<commit_msg>init debug screen quads<commit_after>#include <string>\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/string_cast.hpp>\n\n#include <zombye\/core\/game.hpp>\n#include <zombye\/rendering\/mesh.hpp>\n#include <zombye\/rendering\/rendering_system.hpp>\n#include <zombye\/utils\/component_helper.hpp>\n#include <zombye\/utils\/logger.hpp>\n\nnamespace zombye {\n rendering_system::rendering_system(game& game, SDL_Window* window)\n : game_{game}, window_{window}, mesh_manager_{game_}, shader_manager_{game_}, skinned_mesh_manager_{game_},\n skeleton_manager_{game_}, texture_manager_{game_}, active_camera_{0}, projection_{1.f}, view_{1.f} {\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\n context_ = SDL_GL_CreateContext(window_);\n auto error = std::string{SDL_GetError()};\n if (error != \"\") {\n log(LOG_FATAL, \"could not create OpenGL context with version 3.1: \" + error);\n }\n SDL_ClearError();\n\n SDL_GL_SetSwapInterval(1);\n\n glewExperimental = GL_TRUE;\n if (glewInit() != GLEW_OK) {\n log(LOG_FATAL, \"could not initialize glew\");\n }\n\n auto version = std::string{reinterpret_cast<const char*>(glGetString(GL_VERSION))};\n log(\"OpenGL version \" + version);\n\n glEnable(GL_DEPTH_TEST);\n clear_color(0.4, 0.5, 0.9, 1.0);\n\n auto vertex_shader = shader_manager_.load(\"shader\/staticmesh.vs\", GL_VERTEX_SHADER);\n auto fragment_shader = shader_manager_.load(\"shader\/staticmesh.fs\", GL_FRAGMENT_SHADER);\n\n staticmesh_program_ = std::make_unique<program>();\n staticmesh_program_->attach_shader(vertex_shader);\n staticmesh_program_->attach_shader(fragment_shader);\n\n staticmesh_layout_.emplace_back(\"position\", 3, GL_FLOAT, GL_FALSE, sizeof(vertex), 0);\n staticmesh_layout_.emplace_back(\"texcoord\", 2, GL_FLOAT, GL_FALSE, sizeof(vertex), 3 * sizeof(float));\n staticmesh_layout_.emplace_back(\"normal\", 3, GL_FLOAT, GL_FALSE, sizeof(vertex), 5 * sizeof(float));\n\n staticmesh_layout_.setup_program(*staticmesh_program_, \"fragcolor\");\n staticmesh_program_->link();\n\n vertex_shader = shader_manager_.load(\"shader\/animation.vs\", GL_VERTEX_SHADER);\n fragment_shader = shader_manager_.load(\"shader\/animation.fs\", GL_FRAGMENT_SHADER);\n\n animation_program_ = std::make_unique<program>();\n animation_program_->attach_shader(vertex_shader);\n animation_program_->attach_shader(fragment_shader);\n\n skinnedmesh_layout_.emplace_back(\"position\", 3, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 0);\n skinnedmesh_layout_.emplace_back(\"texcoord\", 2, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 3 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"normal\", 3, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 5 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"index\", 4, GL_INT, GL_FALSE, sizeof(skinned_vertex), 8 * sizeof(float));\n skinnedmesh_layout_.emplace_back(\"weight\", 4, GL_FLOAT, GL_FALSE, sizeof(skinned_vertex), 12 * sizeof(float));\n\n skinnedmesh_layout_.setup_program(*animation_program_, \"fragcolor\");\n animation_program_->link();\n\n float fovy = 45.f * 3.1415f \/ 180.f;\n auto width = float(game_.width());\n auto height = float(game_.height());\n float aspect = width \/ height;\n float near = 0.01f;\n float far = 1000.f;\n projection_ = glm::perspective(fovy, aspect, near, far);\n ortho_projection_ = glm::ortho(0.f, width, 0.f, height);\n\n g_buffer_ = std::make_unique<framebuffer>();\n g_buffer_->attach(GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, GL_DEPTH_COMPONENT24, width, height, GL_DEPTH_COMPONENT, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n g_buffer_->attach(GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, GL_RGBA32F, width, height, GL_RGBA, GL_FLOAT);\n\n g_buffer_->bind();\n glClearColor(0.4f, 0.6f, 0.9f, 1.f);\n GLenum buf[5] = {\n GL_COLOR_ATTACHMENT0,\n GL_COLOR_ATTACHMENT1,\n GL_COLOR_ATTACHMENT2,\n GL_NONE\n };\n glDrawBuffers(5, buf);\n g_buffer_->bind_default();\n\n screen_quad_program_ = std::make_unique<program>();\n vertex_shader = shader_manager_.load(\"shader\/screen_quad.vs\", GL_VERTEX_SHADER);\n if (!vertex_shader) {\n throw std::runtime_error{\"could not load screen_quad.vs\"};\n }\n screen_quad_program_->attach_shader(vertex_shader);\n fragment_shader = shader_manager_.load(\"shader\/screen_quad.fs\", GL_FRAGMENT_SHADER);\n if (!fragment_shader) {\n throw std::runtime_error{\"could not load screen_quad.fs\"};\n }\n screen_quad_program_->attach_shader(fragment_shader);\n staticmesh_layout_.setup_program(*screen_quad_program_, \"frag_color\");\n screen_quad_program_->link();\n\n for (auto i = 0; i < 4; ++i) {\n debug_screen_quads_.emplace_back(std::make_unique<screen_quad>(\n staticmesh_layout_,\n glm::vec2{(i * width \/ 4.f) + 0.01f * width, (3 * height \/ 4) + 0.01f * height},\n glm::vec2{((i + 1) * width \/ 4.f) - 0.01f * width, height - 0.01f * height}\n ));\n }\n }\n\n rendering_system::~rendering_system() {\n window_ = nullptr;\n SDL_GL_DeleteContext(context_);\n }\n\n void rendering_system::begin_scene() {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n }\n\n void rendering_system::end_scene() {\n SDL_GL_SwapWindow(window_);\n }\n\n void rendering_system::update(float delta_time) {\n auto camera = camera_components_.find(active_camera_);\n view_ = glm::mat4{1.f};\n auto camera_position = glm::vec3{0.f};\n if (camera != camera_components_.end()) {\n view_ = camera->second->transform();\n camera_position = camera->second->owner().position();\n }\n\n std::vector<glm::vec3> light_positions;\n std::vector<glm::vec3> light_colors;\n std::vector<float> light_distances;\n auto i = 0;\n for (auto& l : light_components_) {\n if (i > 15) {\n break;\n }\n light_positions.emplace_back(l->owner().position());\n light_colors.emplace_back(l->color());\n light_distances.emplace_back(l->distance());\n }\n int light_count = light_positions.size();\n\n staticmesh_program_->use();\n staticmesh_program_->uniform(\"diffuse_sampler\", 0);\n staticmesh_program_->uniform(\"specular_sampler\", 1);\n staticmesh_program_->uniform(\"light_count\", light_count);\n staticmesh_program_->uniform(\"light_position\", light_count, light_positions);\n staticmesh_program_->uniform(\"light_color\", light_count, light_colors);\n staticmesh_program_->uniform(\"light_distance\", light_count, light_distances);\n staticmesh_program_->uniform(\"view\", camera_position);\n for (auto& s : staticmesh_components_) {\n auto model = s->owner().transform();\n auto model_it = glm::inverse(glm::transpose(model));\n staticmesh_program_->uniform(\"m\", false, model);\n staticmesh_program_->uniform(\"mit\", false, model_it);\n staticmesh_program_->uniform(\"mvp\", false, projection_ * view_ * model);\n s->draw();\n }\n\n animation_program_->use();\n animation_program_->uniform(\"diffuse_sampler\", 0);\n animation_program_->uniform(\"specular_sampler\", 1);\n animation_program_->uniform(\"light_count\", light_count);\n animation_program_->uniform(\"light_position\", light_count, light_positions);\n animation_program_->uniform(\"light_color\", light_count, light_colors);\n animation_program_->uniform(\"light_distance\", light_count, light_distances);\n animation_program_->uniform(\"view\", camera_position);\n for (auto& a: animation_components_) {\n auto model = a->owner().transform();\n auto model_it = glm::inverse(glm::transpose(model));\n animation_program_->uniform(\"m\", false, model);\n animation_program_->uniform(\"mit\", false, model_it);\n animation_program_->uniform(\"mvp\", false, projection_ * view_ * model);\n animation_program_->uniform(\"pose\", a->pose().size(), false, a->pose());\n a->draw();\n }\n }\n\n void rendering_system::clear_color(float red, float green, float blue, float alpha) {\n glClearColor(red, green, blue, alpha);\n }\n\n void rendering_system::register_component(animation_component* component) {\n animation_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(animation_component* component) {\n remove(animation_components_, component);\n }\n\n void rendering_system::register_component(camera_component* component) {\n camera_components_.insert(std::make_pair(component->owner().id(), component));\n }\n\n void rendering_system::unregister_component(camera_component* component) {\n auto it = camera_components_.find(component->owner().id());\n if (it != camera_components_.end()) {\n camera_components_.erase(it);\n }\n }\n\n void rendering_system::register_component(light_component* component) {\n light_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(light_component* component) {\n remove(light_components_, component);\n }\n\n void rendering_system::register_component(staticmesh_component* component) {\n staticmesh_components_.emplace_back(component);\n }\n\n void rendering_system::unregister_component(staticmesh_component* component) {\n remove(staticmesh_components_, component);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"util.h\"\n\n#include <iomanip>\n#include <ostream>\n\n\/\/ TODO: Currently throwing compiler exceptions by pointer in order\n\/\/ to maintain alignment requirements of BID_UINT128 type on some\n\/\/ platforms. See https:\/\/stackoverflow.com\/questions\/30885997\/clang-runtime-fault-when-throwing-aligned-type-compiler-bug\n\/\/ for full explanation.\n\nvoid abort_error(const char *compiler_file, int compiler_line, int number, const Token &token, const std::string &message)\n{\n throw new SourceError(compiler_file, compiler_line, number, token, message);\n}\n\nvoid abort_error_a(const char *compiler_file, int compiler_line, int number, const Token &token_before, const Token &token, const std::string &message)\n{\n if (token_before.line == token.line) {\n throw new SourceError(compiler_file, compiler_line, number, token, message);\n }\n Token tok = token_before;\n tok.column = static_cast<int>(1 + tok.source.length());\n if (tok.source[tok.source.length()-1] != ' ') {\n tok.column++;\n }\n throw new SourceError(compiler_file, compiler_line, number, tok, message);\n}\n\nvoid abort_error(const char *compiler_file, int compiler_line, int number, const Token &token, const std::string &message, const Token &token2, const std::string &message2)\n{\n throw new SourceError(compiler_file, compiler_line, number, token, message, token2, message2);\n}\n\nvoid abort_internal_error(const char *compiler_file, int compiler_line, const std::string &message)\n{\n throw new InternalError(compiler_file, compiler_line, message);\n}\n\nvoid InternalError::write(std::ostream &out)\n{\n out << \"Compiler Internal Error: \" << message << \" (\" << compiler_file << \":\" << compiler_line << \")\\n\";\n}\n\nvoid SourceError::write(std::ostream &out)\n{\n out << \"Error in file: \" << token.file << \"\\n\";\n out << \"\\n\";\n out << token.line << \"| \" << token.source << \"\\n\";\n out << std::setw(std::to_string(token.line).length()+2+token.column) << \"^\" << \"\\n\";\n out << \"Error N\" << number << \": \" << token.line << \":\" << token.column << \" \" << message << \" (\" << compiler_file << \":\" << compiler_line << \")\\n\";\n if (token2.type != NONE) {\n out << \"\\n\";\n out << \"Related line information:\\n\";\n out << \"\\n\";\n out << token2.line << \"| \" << token2.source << \"\\n\";\n out << std::setw(std::to_string(token2.line).length()+2+token2.column) << \"^\" << \"\\n\";\n out << \"Error N\" << number << \": \" << token2.line << \":\" << token2.column << \" \" << message2 << \"\\n\";\n }\n}\n<commit_msg>Remove compiler source line information from error messages<commit_after>#include \"util.h\"\n\n#include <iomanip>\n#include <ostream>\n\n\/\/ TODO: Currently throwing compiler exceptions by pointer in order\n\/\/ to maintain alignment requirements of BID_UINT128 type on some\n\/\/ platforms. See https:\/\/stackoverflow.com\/questions\/30885997\/clang-runtime-fault-when-throwing-aligned-type-compiler-bug\n\/\/ for full explanation.\n\nvoid abort_error(const char *compiler_file, int compiler_line, int number, const Token &token, const std::string &message)\n{\n throw new SourceError(compiler_file, compiler_line, number, token, message);\n}\n\nvoid abort_error_a(const char *compiler_file, int compiler_line, int number, const Token &token_before, const Token &token, const std::string &message)\n{\n if (token_before.line == token.line) {\n throw new SourceError(compiler_file, compiler_line, number, token, message);\n }\n Token tok = token_before;\n tok.column = static_cast<int>(1 + tok.source.length());\n if (tok.source[tok.source.length()-1] != ' ') {\n tok.column++;\n }\n throw new SourceError(compiler_file, compiler_line, number, tok, message);\n}\n\nvoid abort_error(const char *compiler_file, int compiler_line, int number, const Token &token, const std::string &message, const Token &token2, const std::string &message2)\n{\n throw new SourceError(compiler_file, compiler_line, number, token, message, token2, message2);\n}\n\nvoid abort_internal_error(const char *compiler_file, int compiler_line, const std::string &message)\n{\n throw new InternalError(compiler_file, compiler_line, message);\n}\n\nvoid InternalError::write(std::ostream &out)\n{\n out << \"Compiler Internal Error: \" << message << \" (\" << compiler_file << \":\" << compiler_line << \")\\n\";\n}\n\nvoid SourceError::write(std::ostream &out)\n{\n out << \"Error in file: \" << token.file << \"\\n\";\n out << \"\\n\";\n out << token.line << \"| \" << token.source << \"\\n\";\n out << std::setw(std::to_string(token.line).length()+2+token.column) << \"^\" << \"\\n\";\n out << \"Error N\" << number << \": \" << token.line << \":\" << token.column << \" \" << message << \"\\n\";\n if (token2.type != NONE) {\n out << \"\\n\";\n out << \"Related line information:\\n\";\n out << \"\\n\";\n out << token2.line << \"| \" << token2.source << \"\\n\";\n out << std::setw(std::to_string(token2.line).length()+2+token2.column) << \"^\" << \"\\n\";\n out << \"Error N\" << number << \": \" << token2.line << \":\" << token2.column << \" \" << message2 << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Rcpp.h>\n\n#if defined(_WIN32)\n#undef Realloc\n#undef Free\n#include <Windows.h>\n\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/param.h>\n#if defined(BSD)\n#include <sys\/sysctl.h>\n#endif\n\n#endif\n\n#include <sys\/time.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <time.h>\n#include <errno.h>\n#include <fcntl.h>\n\nextern \"C\" {\n #include \"scrypt_platform.h\"\n #include \"crypto\/crypto_scrypt.h\"\n}\n\n#include \"util.hpp\"\n\n#ifdef HAVE_CLOCK_GETTIME\n\nstatic clock_t clocktouse;\n\nstatic int getclockres(double *resd)\n{\n struct timespec res;\n\n \/*\n * Try clocks in order of preference until we find one which works.\n * (We assume that if clock_getres works, clock_gettime will, too.)\n * The use of if\/else\/if\/else\/if\/else rather than if\/elif\/elif\/else\n * is ugly but legal, and allows us to #ifdef things appropriately.\n *\/\n#ifdef CLOCK_VIRTUAL\n if (clock_getres(CLOCK_VIRTUAL, &res) == 0)\n clocktouse = CLOCK_VIRTUAL;\n else\n#endif\n#ifdef CLOCK_MONOTONIC\n if (clock_getres(CLOCK_MONOTONIC, &res) == 0)\n clocktouse = CLOCK_MONOTONIC;\n else\n#endif\n if (clock_getres(CLOCK_REALTIME, &res) == 0)\n clocktouse = CLOCK_REALTIME;\n else\n return (-1);\n\n \/* Convert clock resolution to a double. *\/\n *resd = res.tv_sec + res.tv_nsec * 0.000000001;\n\n return (0);\n}\n\nstatic int getclocktime(struct timespec *ts)\n{\n\n#ifdef DEBUG\n REprintf(\"Using clock_gettime()\\n\");\n#endif\n\n if (clock_gettime(clocktouse, ts))\n return (-1);\n\n return (0);\n}\n\n#else\n\nstatic int getclockres(double *resd)\n{\n\n#ifdef DEBUG\n REprintf(\"Using gettimeofday()\\n\");\n#endif\n\n *resd = 1.0 \/ CLOCKS_PER_SEC;\n\n return (0);\n}\n\nstatic int getclocktime(struct timespec *ts)\n{\n struct timeval tv;\n\n if (gettimeofday(&tv, NULL))\n return (-1);\n ts->tv_sec = tv.tv_sec;\n ts->tv_nsec = tv.tv_usec * 1000;\n\n return (0);\n}\n\n#endif\n\nstatic int getclockdiff(struct timespec * st, double * diffd)\n{\n struct timespec en;\n\n if (getclocktime(&en))\n return (1);\n *diffd = (en.tv_nsec - st->tv_nsec) * 0.000000001 +\n (en.tv_sec - st->tv_sec);\n\n return (0);\n}\n\n\/*\n * Get CPU performance\n *\n * This function is derived from Colin Percival's scrypt reference code\n *\/\nint getcpuperf(double *opps)\n{\n struct timespec st;\n double resd, diffd;\n uint64_t i = 0;\n\n \/* Get the clock resolution. *\/\n if (getclockres(&resd))\n return (2);\n\n#ifdef DEBUG\n REprintf(\"Clock resolution is %f\\n\", resd);\n#endif\n\n \/* Loop until the clock ticks. *\/\n if (getclocktime(&st))\n return (2);\n do {\n \/* Do an scrypt. *\/\n if (crypto_scrypt(NULL, 0, NULL, 0, 16, 1, 1, NULL, 0))\n return (3);\n\n \/* Has the clock ticked? *\/\n if (getclockdiff(&st, &diffd))\n return (2);\n if (diffd > 0)\n break;\n } while (1);\n\n \/* Could how many scryps we can do before the next tick. *\/\n if (getclocktime(&st))\n return (2);\n do {\n \/* Do an scrypt. *\/\n if (crypto_scrypt(NULL, 0, NULL, 0, 128, 1, 1, NULL, 0))\n return (3);\n\n \/* We invoked the salsa20\/8 core 512 times. *\/\n i += 512;\n\n \/* Check if we have looped for long enough. *\/\n if (getclockdiff(&st, &diffd))\n return (2);\n if (diffd > resd)\n break;\n } while (1);\n\n#ifdef DEBUG\n REprintf(\"%ju salsa20\/8 cores performed in %f seconds\\n\", \n (uintmax_t)i, diffd);\n#endif\n\n \/* We can do approximately i salsa20\/8 cores per diffd seconds. *\/\n *opps = i \/ diffd;\n return (0);\n}\n\n\/*\n * Get available memory\n *\n * This function is dervied from:\n * http:\/\/nadeausoftware.com\/articles\/2012\/09\/c_c_tip_how_get_physical_memory_size_system\n *\/\nint getmemlimit(size_t *memlimit) {\n\n#if defined(_WIN32) && (defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW__) || defined(__MINGW32__) )\n \/* Cygwin under Windows. ------------------------------------ *\/\n \/* New 64-bit MEMORYSTATUSEX isn't available. Use old 32.bit *\/\n MEMORYSTATUS status;\n status.dwLength = sizeof(status);\n GlobalMemoryStatus( &status );\n *memlimit = (size_t)status.dwTotalPhys;\n return 0;\n\n#elif defined(_WIN32)\n \/* Windows. ------------------------------------------------- *\/\n \/* Use new 64-bit MEMORYSTATUSEX, not old 32-bit MEMORYSTATUS *\/\n MEMORYSTATUSEX status;\n status.dwLength = sizeof(status);\n GlobalMemoryStatusEx( &status );\n *memlimit = (size_t)status.ullTotalPhys;\n return 0;\n\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n \/* UNIX variants. ------------------------------------------- *\/\n\n#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_MEMSIZE)\n mib[1] = HW_MEMSIZE; \/\/ OSX\n#elif defined(HW_PHYSMEM64)\n mib[1] = HW_PHYSMEM64; \/\/ NetBSD, OpenBSD\n#endif\n int64_t size = 0; \/\/ 64-bit\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n *memlimit = (size_t)size;\n return 0;\n }\n return -1; \/\/ Failure\n\n#elif defined(_SC_AIX_REALMEM)\n \/* AIX. ----------------------------------------------------- *\/\n *memlimit = (size_t)sysconf( _SC_AIX_REALMEM ) * (size_t)1024L;\n return 0;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)\n \/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- *\/\n *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGESIZE );\n return 0;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)\n \/* Legacy. -------------------------------------------------- *\/\n *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE );\n return 0;\n\n#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))\n \/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- *\/\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_REALMEM)\n mib[1] = HW_REALMEM; \/\/ FreeBSD\n#elif defined(HW_PYSMEM)\n mib[1] = HW_PHYSMEM; \/\/ Others\n#endif\n unsigned int size = 0; \/\/ 32-bit\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n *memlimit = (size_t)size;\n return 0;\n }\n return -1; \/\/ Failure\n#endif\n\n#else\n return -2; \/\/ Unknown OS\n#endif\n\n}\n\n\/*\n * Obtains salt for password hash.\n * This function is derived from Colin Percival's scrypt reference code\n *\/\nint getsalt(uint8_t salt[32]) {\n\n uint8_t *buf = salt;\n size_t buflen = 32;\n\n#if defined(_WIN32)\n\n HCRYPTPROV hCryptCtx;\n\n if (CryptAcquireContext(&hCryptCtx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {\n if (!CryptGenRandom(hCryptCtx, buflen, buf))\n goto err;\n CryptReleaseContext(hCryptCtx, 0);\n } else {\n goto err;\n }\n \n \/* Success! *\/\n return (0);\n \n#else\n\n int fd;\n ssize_t lenread;\n\n \/* Open \/dev\/urandom *\/\n if ((fd = open(\"\/dev\/urandom\", O_RDONLY)) == -1)\n goto err;\n\n \/* Read bytes until we have filled the buffer *\/\n while (buflen > 0) {\n if ((lenread = read(fd, buf, buflen)) == -1)\n goto close;\n\n \/* The random device should never EOF *\/\n if (lenread == 0)\n goto close;\n\n \/* We're partly done *\/\n buf += lenread;\n buflen -= lenread;\n }\n\n \/* Close the device *\/\n while (close(fd) == -1) {\n if (errno != EINTR)\n goto err;\n }\n\n \/* Success! *\/\n return (0);\n\nclose:\n close(fd);\n\n#endif\n\nerr:\n \/* Failure! *\/\n return (4);\n}\n\n<commit_msg>Add comment re strange #undefs<commit_after>#include <Rcpp.h>\n\n#if defined(_WIN32)\n\/\/ See: http:\/\/stackoverflow.com\/questions\/11588765\/using-rcpp-with-windows-specific-includes\n#undef Realloc\n#undef Free\n#include <Windows.h>\n\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/param.h>\n#if defined(BSD)\n#include <sys\/sysctl.h>\n#endif\n\n#endif\n\n#include <sys\/time.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <time.h>\n#include <errno.h>\n#include <fcntl.h>\n\nextern \"C\" {\n #include \"scrypt_platform.h\"\n #include \"crypto\/crypto_scrypt.h\"\n}\n\n#include \"util.hpp\"\n\n#ifdef HAVE_CLOCK_GETTIME\n\nstatic clock_t clocktouse;\n\nstatic int getclockres(double *resd)\n{\n struct timespec res;\n\n \/*\n * Try clocks in order of preference until we find one which works.\n * (We assume that if clock_getres works, clock_gettime will, too.)\n * The use of if\/else\/if\/else\/if\/else rather than if\/elif\/elif\/else\n * is ugly but legal, and allows us to #ifdef things appropriately.\n *\/\n#ifdef CLOCK_VIRTUAL\n if (clock_getres(CLOCK_VIRTUAL, &res) == 0)\n clocktouse = CLOCK_VIRTUAL;\n else\n#endif\n#ifdef CLOCK_MONOTONIC\n if (clock_getres(CLOCK_MONOTONIC, &res) == 0)\n clocktouse = CLOCK_MONOTONIC;\n else\n#endif\n if (clock_getres(CLOCK_REALTIME, &res) == 0)\n clocktouse = CLOCK_REALTIME;\n else\n return (-1);\n\n \/* Convert clock resolution to a double. *\/\n *resd = res.tv_sec + res.tv_nsec * 0.000000001;\n\n return (0);\n}\n\nstatic int getclocktime(struct timespec *ts)\n{\n\n#ifdef DEBUG\n REprintf(\"Using clock_gettime()\\n\");\n#endif\n\n if (clock_gettime(clocktouse, ts))\n return (-1);\n\n return (0);\n}\n\n#else\n\nstatic int getclockres(double *resd)\n{\n\n#ifdef DEBUG\n REprintf(\"Using gettimeofday()\\n\");\n#endif\n\n *resd = 1.0 \/ CLOCKS_PER_SEC;\n\n return (0);\n}\n\nstatic int getclocktime(struct timespec *ts)\n{\n struct timeval tv;\n\n if (gettimeofday(&tv, NULL))\n return (-1);\n ts->tv_sec = tv.tv_sec;\n ts->tv_nsec = tv.tv_usec * 1000;\n\n return (0);\n}\n\n#endif\n\nstatic int getclockdiff(struct timespec * st, double * diffd)\n{\n struct timespec en;\n\n if (getclocktime(&en))\n return (1);\n *diffd = (en.tv_nsec - st->tv_nsec) * 0.000000001 +\n (en.tv_sec - st->tv_sec);\n\n return (0);\n}\n\n\/*\n * Get CPU performance\n *\n * This function is derived from Colin Percival's scrypt reference code\n *\/\nint getcpuperf(double *opps)\n{\n struct timespec st;\n double resd, diffd;\n uint64_t i = 0;\n\n \/* Get the clock resolution. *\/\n if (getclockres(&resd))\n return (2);\n\n#ifdef DEBUG\n REprintf(\"Clock resolution is %f\\n\", resd);\n#endif\n\n \/* Loop until the clock ticks. *\/\n if (getclocktime(&st))\n return (2);\n do {\n \/* Do an scrypt. *\/\n if (crypto_scrypt(NULL, 0, NULL, 0, 16, 1, 1, NULL, 0))\n return (3);\n\n \/* Has the clock ticked? *\/\n if (getclockdiff(&st, &diffd))\n return (2);\n if (diffd > 0)\n break;\n } while (1);\n\n \/* Could how many scryps we can do before the next tick. *\/\n if (getclocktime(&st))\n return (2);\n do {\n \/* Do an scrypt. *\/\n if (crypto_scrypt(NULL, 0, NULL, 0, 128, 1, 1, NULL, 0))\n return (3);\n\n \/* We invoked the salsa20\/8 core 512 times. *\/\n i += 512;\n\n \/* Check if we have looped for long enough. *\/\n if (getclockdiff(&st, &diffd))\n return (2);\n if (diffd > resd)\n break;\n } while (1);\n\n#ifdef DEBUG\n REprintf(\"%ju salsa20\/8 cores performed in %f seconds\\n\", \n (uintmax_t)i, diffd);\n#endif\n\n \/* We can do approximately i salsa20\/8 cores per diffd seconds. *\/\n *opps = i \/ diffd;\n return (0);\n}\n\n\/*\n * Get available memory\n *\n * This function is dervied from:\n * http:\/\/nadeausoftware.com\/articles\/2012\/09\/c_c_tip_how_get_physical_memory_size_system\n *\/\nint getmemlimit(size_t *memlimit) {\n\n#if defined(_WIN32) && (defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__MINGW__) || defined(__MINGW32__) )\n \/* Cygwin under Windows. ------------------------------------ *\/\n \/* New 64-bit MEMORYSTATUSEX isn't available. Use old 32.bit *\/\n MEMORYSTATUS status;\n status.dwLength = sizeof(status);\n GlobalMemoryStatus( &status );\n *memlimit = (size_t)status.dwTotalPhys;\n return 0;\n\n#elif defined(_WIN32)\n \/* Windows. ------------------------------------------------- *\/\n \/* Use new 64-bit MEMORYSTATUSEX, not old 32-bit MEMORYSTATUS *\/\n MEMORYSTATUSEX status;\n status.dwLength = sizeof(status);\n GlobalMemoryStatusEx( &status );\n *memlimit = (size_t)status.ullTotalPhys;\n return 0;\n\n#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))\n \/* UNIX variants. ------------------------------------------- *\/\n\n#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_MEMSIZE)\n mib[1] = HW_MEMSIZE; \/\/ OSX\n#elif defined(HW_PHYSMEM64)\n mib[1] = HW_PHYSMEM64; \/\/ NetBSD, OpenBSD\n#endif\n int64_t size = 0; \/\/ 64-bit\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n *memlimit = (size_t)size;\n return 0;\n }\n return -1; \/\/ Failure\n\n#elif defined(_SC_AIX_REALMEM)\n \/* AIX. ----------------------------------------------------- *\/\n *memlimit = (size_t)sysconf( _SC_AIX_REALMEM ) * (size_t)1024L;\n return 0;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)\n \/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- *\/\n *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGESIZE );\n return 0;\n\n#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)\n \/* Legacy. -------------------------------------------------- *\/\n *memlimit = (size_t)sysconf( _SC_PHYS_PAGES ) * (size_t)sysconf( _SC_PAGE_SIZE );\n return 0;\n\n#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))\n \/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- *\/\n int mib[2];\n mib[0] = CTL_HW;\n#if defined(HW_REALMEM)\n mib[1] = HW_REALMEM; \/\/ FreeBSD\n#elif defined(HW_PYSMEM)\n mib[1] = HW_PHYSMEM; \/\/ Others\n#endif\n unsigned int size = 0; \/\/ 32-bit\n size_t len = sizeof( size );\n if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 ) {\n *memlimit = (size_t)size;\n return 0;\n }\n return -1; \/\/ Failure\n#endif\n\n#else\n return -2; \/\/ Unknown OS\n#endif\n\n}\n\n\/*\n * Obtains salt for password hash.\n * This function is derived from Colin Percival's scrypt reference code\n *\/\nint getsalt(uint8_t salt[32]) {\n\n uint8_t *buf = salt;\n size_t buflen = 32;\n\n#if defined(_WIN32)\n\n HCRYPTPROV hCryptCtx;\n\n if (CryptAcquireContext(&hCryptCtx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {\n if (!CryptGenRandom(hCryptCtx, buflen, buf))\n goto err;\n CryptReleaseContext(hCryptCtx, 0);\n } else {\n goto err;\n }\n \n \/* Success! *\/\n return (0);\n \n#else\n\n int fd;\n ssize_t lenread;\n\n \/* Open \/dev\/urandom *\/\n if ((fd = open(\"\/dev\/urandom\", O_RDONLY)) == -1)\n goto err;\n\n \/* Read bytes until we have filled the buffer *\/\n while (buflen > 0) {\n if ((lenread = read(fd, buf, buflen)) == -1)\n goto close;\n\n \/* The random device should never EOF *\/\n if (lenread == 0)\n goto close;\n\n \/* We're partly done *\/\n buf += lenread;\n buflen -= lenread;\n }\n\n \/* Close the device *\/\n while (close(fd) == -1) {\n if (errno != EINTR)\n goto err;\n }\n\n \/* Success! *\/\n return (0);\n\nclose:\n close(fd);\n\n#endif\n\nerr:\n \/* Failure! *\/\n return (4);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"shell_manager.hh\"\n\n#include \"context.hh\"\n#include \"debug.hh\"\n#include \"event_manager.hh\"\n#include \"file.hh\"\n\n#include <cstring>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\nnamespace Kakoune\n{\n\nstatic const Regex env_var_regex(R\"(\\bkak_(\\w+)\\b)\");\n\nShellManager::ShellManager()\n{\n const char* path = getenv(\"PATH\");\n String new_path;\n if (path)\n new_path = path + \":\"_str;\n\n String kak_path = get_kak_binary_path();\n StringView kak_dir = kak_path.substr(0_byte, (int)kak_path.find_last_of('\/'));\n new_path += kak_dir;\n setenv(\"PATH\", new_path.c_str(), 1);\n}\n\nString ShellManager::eval(StringView cmdline, const Context& context,\n memoryview<String> params,\n const EnvVarMap& env_vars,\n int* exit_status)\n{\n return pipe(\"\", cmdline, context, params, env_vars, exit_status);\n}\n\nString ShellManager::pipe(StringView input,\n StringView cmdline, const Context& context,\n memoryview<String> params,\n const EnvVarMap& env_vars,\n int* exit_status)\n{\n int write_pipe[2]; \/\/ child stdin\n int read_pipe[2]; \/\/ child stdout\n int error_pipe[2]; \/\/ child stderr\n\n ::pipe(write_pipe);\n ::pipe(read_pipe);\n ::pipe(error_pipe);\n\n String output;\n if (pid_t pid = fork())\n {\n close(write_pipe[0]);\n close(read_pipe[1]);\n close(error_pipe[1]);\n\n write(write_pipe[1], input.data(), (int)input.length());\n close(write_pipe[1]);\n\n String error;\n {\n auto pipe_reader = [](String& output, bool& closed) {\n return [&output, &closed](FDWatcher& watcher, EventMode) {\n if (closed)\n return;\n const int fd = watcher.fd();\n char buffer[1024];\n size_t size = read(fd, buffer, 1024);\n if (size <= 0)\n {\n close(fd);\n closed = true;\n }\n output += String(buffer, buffer+size);\n };\n };\n\n bool stdout_closed = false, stderr_closed = false;\n FDWatcher stdout_watcher{read_pipe[0], pipe_reader(output, stdout_closed)};\n FDWatcher stderr_watcher{error_pipe[0], pipe_reader(error, stderr_closed)};\n\n while (not stdout_closed or not stderr_closed)\n EventManager::instance().handle_next_events(EventMode::Urgent);\n }\n\n if (not error.empty())\n write_debug(\"shell stderr: <<<\\n\" + error + \">>>\");\n\n waitpid(pid, exit_status, 0);\n if (exit_status)\n {\n if (WIFEXITED(*exit_status))\n *exit_status = WEXITSTATUS(*exit_status);\n else\n *exit_status = -1;\n }\n }\n else try\n {\n close(write_pipe[1]);\n close(read_pipe[0]);\n close(error_pipe[0]);\n\n dup2(read_pipe[1], 1); close(read_pipe[1]);\n dup2(error_pipe[1], 2); close(error_pipe[1]);\n dup2(write_pipe[0], 0); close(write_pipe[0]);\n\n RegexIterator<StringView::iterator> it(cmdline.begin(), cmdline.end(), env_var_regex);\n RegexIterator<StringView::iterator> end;\n\n while (it != end)\n {\n auto& match = *it;\n\n StringView name = StringView(match[1].first, match[1].second);\n kak_assert(name.length() > 0);\n\n auto local_var = env_vars.find(name);\n if (local_var != env_vars.end())\n setenv((\"kak_\" + name).c_str(), local_var->second.c_str(), 1);\n else\n {\n try\n {\n String value = get_val(name, context);\n setenv((\"kak_\"_str + name).c_str(), value.c_str(), 1);\n }\n catch (runtime_error&) {}\n }\n\n ++it;\n }\n const char* shell = \"\/bin\/sh\";\n auto cmdlinezstr = cmdline.zstr();\n std::vector<const char*> execparams = { shell, \"-c\", cmdlinezstr };\n if (not params.empty())\n execparams.push_back(shell);\n for (auto& param : params)\n execparams.push_back(param.c_str());\n execparams.push_back(nullptr);\n\n execvp(shell, (char* const*)execparams.data());\n exit(-1);\n }\n catch (...) { exit(-1); }\n return output;\n}\n\nvoid ShellManager::register_env_var(StringView regex,\n EnvVarRetriever retriever)\n{\n m_env_vars.push_back({ Regex(regex.begin(), regex.end()), std::move(retriever) });\n}\n\nString ShellManager::get_val(StringView name, const Context& context) const\n{\n auto env_var = std::find_if(\n m_env_vars.begin(), m_env_vars.end(),\n [&](const std::pair<Regex, EnvVarRetriever>& pair)\n { return regex_match(name.begin(), name.end(), pair.first); });\n\n if (env_var == m_env_vars.end())\n throw runtime_error(\"no such env var: \" + name);\n return env_var->second(name, context);\n}\n\n}\n<commit_msg>Handle SIGCHLD signals when piping<commit_after>#include \"shell_manager.hh\"\n\n#include \"context.hh\"\n#include \"debug.hh\"\n#include \"event_manager.hh\"\n#include \"file.hh\"\n\n#include <cstring>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\nnamespace Kakoune\n{\n\nstatic const Regex env_var_regex(R\"(\\bkak_(\\w+)\\b)\");\n\nShellManager::ShellManager()\n{\n const char* path = getenv(\"PATH\");\n String new_path;\n if (path)\n new_path = path + \":\"_str;\n\n String kak_path = get_kak_binary_path();\n StringView kak_dir = kak_path.substr(0_byte, (int)kak_path.find_last_of('\/'));\n new_path += kak_dir;\n setenv(\"PATH\", new_path.c_str(), 1);\n}\n\nString ShellManager::eval(StringView cmdline, const Context& context,\n memoryview<String> params,\n const EnvVarMap& env_vars,\n int* exit_status)\n{\n return pipe(\"\", cmdline, context, params, env_vars, exit_status);\n}\n\nString ShellManager::pipe(StringView input,\n StringView cmdline, const Context& context,\n memoryview<String> params,\n const EnvVarMap& env_vars,\n int* exit_status)\n{\n int write_pipe[2]; \/\/ child stdin\n int read_pipe[2]; \/\/ child stdout\n int error_pipe[2]; \/\/ child stderr\n\n ::pipe(write_pipe);\n ::pipe(read_pipe);\n ::pipe(error_pipe);\n\n static sig_atomic_t exited; exited = 0;\n static sig_atomic_t sig_exit_status;\n signal(SIGCHLD, [](int) { wait(&sig_exit_status); exited = 1; });\n\n String output;\n if (pid_t pid = fork())\n {\n close(write_pipe[0]);\n close(read_pipe[1]);\n close(error_pipe[1]);\n\n write(write_pipe[1], input.data(), (int)input.length());\n close(write_pipe[1]);\n\n String error;\n {\n auto pipe_reader = [](String& output, bool& closed) {\n return [&output, &closed](FDWatcher& watcher, EventMode) {\n if (closed)\n return;\n const int fd = watcher.fd();\n char buffer[1024];\n size_t size = read(fd, buffer, 1024);\n if (size <= 0)\n {\n close(fd);\n closed = true;\n }\n output += String(buffer, buffer+size);\n };\n };\n\n bool stdout_closed = false, stderr_closed = false;\n FDWatcher stdout_watcher{read_pipe[0], pipe_reader(output, stdout_closed)};\n FDWatcher stderr_watcher{error_pipe[0], pipe_reader(error, stderr_closed)};\n\n while (not stdout_closed or not stderr_closed)\n EventManager::instance().handle_next_events(EventMode::Urgent);\n }\n\n if (not error.empty())\n write_debug(\"shell stderr: <<<\\n\" + error + \">>>\");\n\n signal(SIGCHLD, SIG_DFL);\n\n if (not exited)\n waitpid(pid, exit_status, 0);\n else if (exit_status)\n *exit_status = sig_exit_status;\n\n if (exit_status)\n {\n if (WIFEXITED(*exit_status))\n *exit_status = WEXITSTATUS(*exit_status);\n else\n *exit_status = -1;\n }\n }\n else try\n {\n close(write_pipe[1]);\n close(read_pipe[0]);\n close(error_pipe[0]);\n\n dup2(read_pipe[1], 1); close(read_pipe[1]);\n dup2(error_pipe[1], 2); close(error_pipe[1]);\n dup2(write_pipe[0], 0); close(write_pipe[0]);\n\n RegexIterator<StringView::iterator> it(cmdline.begin(), cmdline.end(), env_var_regex);\n RegexIterator<StringView::iterator> end;\n\n while (it != end)\n {\n auto& match = *it;\n\n StringView name = StringView(match[1].first, match[1].second);\n kak_assert(name.length() > 0);\n\n auto local_var = env_vars.find(name);\n if (local_var != env_vars.end())\n setenv((\"kak_\" + name).c_str(), local_var->second.c_str(), 1);\n else\n {\n try\n {\n String value = get_val(name, context);\n setenv((\"kak_\"_str + name).c_str(), value.c_str(), 1);\n }\n catch (runtime_error&) {}\n }\n\n ++it;\n }\n const char* shell = \"\/bin\/sh\";\n auto cmdlinezstr = cmdline.zstr();\n std::vector<const char*> execparams = { shell, \"-c\", cmdlinezstr };\n if (not params.empty())\n execparams.push_back(shell);\n for (auto& param : params)\n execparams.push_back(param.c_str());\n execparams.push_back(nullptr);\n\n execvp(shell, (char* const*)execparams.data());\n exit(-1);\n }\n catch (...) { exit(-1); }\n return output;\n}\n\nvoid ShellManager::register_env_var(StringView regex,\n EnvVarRetriever retriever)\n{\n m_env_vars.push_back({ Regex(regex.begin(), regex.end()), std::move(retriever) });\n}\n\nString ShellManager::get_val(StringView name, const Context& context) const\n{\n auto env_var = std::find_if(\n m_env_vars.begin(), m_env_vars.end(),\n [&](const std::pair<Regex, EnvVarRetriever>& pair)\n { return regex_match(name.begin(), name.end(), pair.first); });\n\n if (env_var == m_env_vars.end())\n throw runtime_error(\"no such env var: \" + name);\n return env_var->second(name, context);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h>\n#include <std_msgs\/String.h>\n#include <geometry_msgs\/PointStamped.h>\n#include <geometry_msgs\/PoseStamped.h>\n#include <move_base_msgs\/MoveBaseAction.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <tf\/tf.h>\n#include <tf\/transform_listener.h>\n\n#include <yaml-cpp\/yaml.h>\n\n#include <vector>\n#include <fstream>\n#include <string>\n\nclass WaypointsNavigation{\npublic:\n WaypointsNavigation() :\n has_activate_(false),\n move_base_action_(\"move_base\", true),\n rate_(10)\n {\n while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))\n {\n ROS_INFO(\"Waiting...\");\n }\n \n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"robot_frame\", robot_frame_, std::string(\"\/base_link\"));\n private_nh.param(\"world_frame\", world_frame_, std::string(\"\/map\"));\n \n double max_update_rate;\n private_nh.param(\"max_update_rate\", max_update_rate, 10.0);\n rate_ = ros::Rate(max_update_rate);\n std::string filename = \"\";\n private_nh.param(\"filename\", filename, filename);\n if(filename != \"\"){\n ROS_INFO_STREAM(\"Read waypoints data from \" << filename);\n readFile(filename);\n }\n for(int i=0; i < waypoints_.size(); i++){\n ROS_INFO_STREAM(\"waypoints \\n\" << waypoints_[i]);\n }\n ros::NodeHandle nh;\n\n syscommand_sub_ = nh.subscribe(\"syscommand\", 1, &WaypointsNavigation::syscommandCallback, this);\n }\n\n void syscommandCallback(const std_msgs::String &msg){\n if(msg.data == \"start\"){\n has_activate_ = true;\n }\n }\n\n bool readFile(const std::string &filename){\n waypoints_.clear();\n try{\n std::ifstream ifs(filename.c_str(), std::ifstream::in);\n if(ifs.good() == false){\n return false;\n }\n\n YAML::Node node;\n node = YAML::Load(ifs);\n const YAML::Node &wp_node_tmp = node[\"waypoints\"];\n const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;\n if(wp_node != NULL){\n for(int i=0; i < wp_node->size(); i++){\n geometry_msgs::PointStamped point;\n\n point.point.x = (*wp_node)[i][\"point\"][\"x\"].as<double>();\n point.point.y = (*wp_node)[i][\"point\"][\"y\"].as<double>();\n point.point.z = (*wp_node)[i][\"point\"][\"z\"].as<double>();\n\n waypoints_.push_back(point);\n\n }\n }else{\n return false;\n }\n\n const YAML::Node &fp_node_tmp = node[\"finish_pose\"];\n const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;\n\n if(fp_node != NULL){\n finish_pose_.position.x = (*fp_node)[\"pose\"][\"position\"][\"x\"].as<double>();\n finish_pose_.position.y = (*fp_node)[\"pose\"][\"position\"][\"y\"].as<double>();\n finish_pose_.position.z = (*fp_node)[\"pose\"][\"position\"][\"z\"].as<double>();\n\n finish_pose_.orientation.x = (*fp_node)[\"pose\"][\"orientation\"][\"x\"].as<double>();\n finish_pose_.orientation.y = (*fp_node)[\"pose\"][\"orientation\"][\"y\"].as<double>();\n finish_pose_.orientation.z = (*fp_node)[\"pose\"][\"orientation\"][\"z\"].as<double>();\n finish_pose_.orientation.w = (*fp_node)[\"pose\"][\"orientation\"][\"w\"].as<double>();\n }else{\n return false;\n }\n\n }catch(YAML::ParserException &e){\n return false;\n\n }catch(YAML::RepresentationException &e){\n return false;\n }\n\n return true;\n }\n\n bool shouldSendGoal(){\n bool ret = true;\n actionlib::SimpleClientGoalState state = move_base_action_.getState();\n if((state != actionlib::SimpleClientGoalState::ACTIVE) &&\n (state != actionlib::SimpleClientGoalState::PENDING) && \n (state != actionlib::SimpleClientGoalState::RECALLED) &&\n (state != actionlib::SimpleClientGoalState::PREEMPTED))\n {\n ret = false;\n }\n\n if(waypoints_.empty()){\n ret = false;\n }\n\n return ret;\n }\n\n bool navigationFinished(){\n return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;\n }\n\n bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){\n tf::StampedTransform robot_gl;\n try{\n tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n }catch(tf::TransformException &e){\n ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n }\n const double wx = dest.x;\n const double wy = dest.y;\n const double rx = robot_gl.getOrigin().x();\n const double ry = robot_gl.getOrigin().y();\n const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));\n\n return dist < dist_err;\n }\n\n void sleep(){\n rate_.sleep();\n ros::spinOnce();\n }\n\n void startNavigationGL(const geometry_msgs::Point &dest){\n geometry_msgs::Pose pose;\n pose.position = dest;\n pose.orientation = tf::createQuaternionMsgFromYaw(0.0);\n startNavigationGL(pose);\n }\n\n void startNavigationGL(const geometry_msgs::Pose &dest){\n move_base_msgs::MoveBaseGoal move_base_goal;\n move_base_goal.target_pose.header.stamp = ros::Time::now();\n move_base_goal.target_pose.header.frame_id = world_frame_;\n move_base_goal.target_pose.pose.position = dest.position;\n move_base_goal.target_pose.pose.orientation = dest.orientation;\n \n move_base_action_.sendGoal(move_base_goal);\n }\n\n void run(){\n while(ros::ok()){\n if(has_activate_){\n for(int i=0; i < waypoints_.size(); i++){\n ROS_INFO_STREAM(\"waypoint = \" << waypoints_[i]);\n if(!ros::ok()) break;\n \n startNavigationGL(waypoints_[i].point);\n while(!onNavigationPoint(waypoints_[i].point)) sleep();\n }\n waypoints_.clear();\n startNavigationGL(finish_pose_);\n while(!navigationFinished() && ros::ok()) sleep();\n has_activate_ = false;\n }\n\n sleep();\n }\n }\n\nprivate:\n actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;\n std::vector<geometry_msgs::PointStamped> waypoints_;\n geometry_msgs::Pose finish_pose_;\n bool has_activate_;\n std::string robot_frame_, world_frame_;\n tf::TransformListener tf_listener_;\n ros::Rate rate_;\n ros::Subscriber syscommand_sub_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, ROS_PACKAGE_NAME);\n WaypointsNavigation w_nav;\n w_nav.run();\n\n return 0;\n}\n<commit_msg>Avoid error that the 'Aborting because a valid plan could not be found'<commit_after>#include <ros\/ros.h>\n#include <std_msgs\/String.h>\n#include <geometry_msgs\/PointStamped.h>\n#include <geometry_msgs\/PoseStamped.h>\n#include <move_base_msgs\/MoveBaseAction.h>\n#include <actionlib\/client\/simple_action_client.h>\n#include <tf\/tf.h>\n#include <tf\/transform_listener.h>\n\n#include <yaml-cpp\/yaml.h>\n\n#include <vector>\n#include <fstream>\n#include <string>\n\nclass WaypointsNavigation{\npublic:\n WaypointsNavigation() :\n has_activate_(false),\n move_base_action_(\"move_base\", true),\n rate_(10)\n {\n while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))\n {\n ROS_INFO(\"Waiting...\");\n }\n \n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"robot_frame\", robot_frame_, std::string(\"\/base_link\"));\n private_nh.param(\"world_frame\", world_frame_, std::string(\"\/map\"));\n \n double max_update_rate;\n private_nh.param(\"max_update_rate\", max_update_rate, 10.0);\n rate_ = ros::Rate(max_update_rate);\n std::string filename = \"\";\n private_nh.param(\"filename\", filename, filename);\n if(filename != \"\"){\n ROS_INFO_STREAM(\"Read waypoints data from \" << filename);\n readFile(filename);\n }\n for(int i=0; i < waypoints_.size(); i++){\n ROS_INFO_STREAM(\"waypoints \\n\" << waypoints_[i]);\n }\n ros::NodeHandle nh;\n\n syscommand_sub_ = nh.subscribe(\"syscommand\", 1, &WaypointsNavigation::syscommandCallback, this);\n }\n\n void syscommandCallback(const std_msgs::String &msg){\n if(msg.data == \"start\"){\n has_activate_ = true;\n }\n }\n\n bool readFile(const std::string &filename){\n waypoints_.clear();\n try{\n std::ifstream ifs(filename.c_str(), std::ifstream::in);\n if(ifs.good() == false){\n return false;\n }\n\n YAML::Node node;\n node = YAML::Load(ifs);\n const YAML::Node &wp_node_tmp = node[\"waypoints\"];\n const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;\n if(wp_node != NULL){\n for(int i=0; i < wp_node->size(); i++){\n geometry_msgs::PointStamped point;\n\n point.point.x = (*wp_node)[i][\"point\"][\"x\"].as<double>();\n point.point.y = (*wp_node)[i][\"point\"][\"y\"].as<double>();\n point.point.z = (*wp_node)[i][\"point\"][\"z\"].as<double>();\n\n waypoints_.push_back(point);\n\n }\n }else{\n return false;\n }\n\n const YAML::Node &fp_node_tmp = node[\"finish_pose\"];\n const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;\n\n if(fp_node != NULL){\n finish_pose_.position.x = (*fp_node)[\"pose\"][\"position\"][\"x\"].as<double>();\n finish_pose_.position.y = (*fp_node)[\"pose\"][\"position\"][\"y\"].as<double>();\n finish_pose_.position.z = (*fp_node)[\"pose\"][\"position\"][\"z\"].as<double>();\n\n finish_pose_.orientation.x = (*fp_node)[\"pose\"][\"orientation\"][\"x\"].as<double>();\n finish_pose_.orientation.y = (*fp_node)[\"pose\"][\"orientation\"][\"y\"].as<double>();\n finish_pose_.orientation.z = (*fp_node)[\"pose\"][\"orientation\"][\"z\"].as<double>();\n finish_pose_.orientation.w = (*fp_node)[\"pose\"][\"orientation\"][\"w\"].as<double>();\n }else{\n return false;\n }\n\n }catch(YAML::ParserException &e){\n return false;\n\n }catch(YAML::RepresentationException &e){\n return false;\n }\n\n return true;\n }\n\n bool shouldSendGoal(){\n bool ret = true;\n actionlib::SimpleClientGoalState state = move_base_action_.getState();\n if((state != actionlib::SimpleClientGoalState::ACTIVE) &&\n (state != actionlib::SimpleClientGoalState::PENDING) && \n (state != actionlib::SimpleClientGoalState::RECALLED) &&\n (state != actionlib::SimpleClientGoalState::PREEMPTED))\n {\n ret = false;\n }\n\n if(waypoints_.empty()){\n ret = false;\n }\n\n return ret;\n }\n\n bool navigationFinished(){\n return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;\n }\n\n bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){\n tf::StampedTransform robot_gl;\n try{\n tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n }catch(tf::TransformException &e){\n ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n }\n const double wx = dest.x;\n const double wy = dest.y;\n const double rx = robot_gl.getOrigin().x();\n const double ry = robot_gl.getOrigin().y();\n const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));\n\n return dist < dist_err;\n }\n\n void sleep(){\n rate_.sleep();\n ros::spinOnce();\n }\n\n void startNavigationGL(const geometry_msgs::Point &dest){\n geometry_msgs::Pose pose;\n pose.position = dest;\n pose.orientation = tf::createQuaternionMsgFromYaw(0.0);\n startNavigationGL(pose);\n }\n\n void startNavigationGL(const geometry_msgs::Pose &dest){\n move_base_msgs::MoveBaseGoal move_base_goal;\n move_base_goal.target_pose.header.stamp = ros::Time::now();\n move_base_goal.target_pose.header.frame_id = world_frame_;\n move_base_goal.target_pose.pose.position = dest.position;\n move_base_goal.target_pose.pose.orientation = dest.orientation;\n \n move_base_action_.sendGoal(move_base_goal);\n }\n\n void run(){\n while(ros::ok()){\n if(has_activate_){\n for(int i=0; i < waypoints_.size(); i++){\n ROS_INFO_STREAM(\"waypoint = \" << waypoints_[i]);\n if(!ros::ok()) break;\n \n startNavigationGL(waypoints_[i].point);\n double start_nav_time = ros::Time::now().toSec();\n while(!onNavigationPoint(waypoints_[i].point)){\n if(ros::Time::now().toSec() - start_nav_time > 10.0){\n ROS_INFO(\"Resend the navigation goal.\");\n startNavigationGL(waypoints_[i].point);\n start_nav_time = ros::Time::now().toSec();\n }\n actionlib::SimpleClientGoalState state = move_base_action_.getState();\n sleep();\n }\n ROS_INFO(\"waypoint goal\");\n }\n ROS_INFO(\"waypoints clear\");\n waypoints_.clear();\n startNavigationGL(finish_pose_);\n while(!navigationFinished() && ros::ok()) sleep();\n has_activate_ = false;\n }\n\n sleep();\n }\n }\n\nprivate:\n actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;\n std::vector<geometry_msgs::PointStamped> waypoints_;\n geometry_msgs::Pose finish_pose_;\n bool has_activate_;\n std::string robot_frame_, world_frame_;\n tf::TransformListener tf_listener_;\n ros::Rate rate_;\n ros::Subscriber syscommand_sub_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, ROS_PACKAGE_NAME);\n WaypointsNavigation w_nav;\n w_nav.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ trace.cpp\n\/\/ kuma\n\/\/\n\/\/ Created by Fengping Bao <jamol@live.com> on 11\/12\/14.\n\/\/ Copyright (c) 2014. All rights reserved.\n\/\/\n\n#include \"kmtrace.h\"\n#include \"util.h\"\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <thread>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <chrono>\n\n#ifdef KUMA_OS_WIN\n# include <Windows.h>\n#endif\n\nKUMA_NS_BEGIN\n\n#ifdef KUMA_OS_WIN\n#define VSNPRINTF(d, dl, fmt, ...) _vsnprintf_s(d, dl, _TRUNCATE, fmt, ##__VA_ARGS__)\n#define LOCALTIME_R(timep, result) localtime_s(result, timep)\n#else\n#define VSNPRINTF vsnprintf\n#define LOCALTIME_R localtime_r\n#endif\n\nstd::function<void(int, const char*)> trace_func;\nvoid setTraceFunc(std::function<void(int, const char*)> func)\n{\n trace_func = func;\n}\n\nvoid TracePrint(int level, const char* szMessage, ...)\n{\n va_list VAList;\n char szMsgBuf[2048] = {0};\n va_start(VAList, szMessage);\n VSNPRINTF(szMsgBuf, sizeof(szMsgBuf)-1, szMessage, VAList);\n \n std::stringstream ss;\n \n auto now_p = std::chrono::system_clock::now();\n auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now_p.time_since_epoch());\n auto now_c = std::chrono::system_clock::to_time_t(now_p);\n struct tm tm_buf;\n LOCALTIME_R(&now_c, &tm_buf);\n ss << std::put_time(&tm_buf, \"%F %T.\");\n ss.width(3);\n ss.fill('0');\n ss << (now_ms.count()%1000);\n switch(level)\n {\n case KUMA_TRACE_LEVEL_INFO:\n ss << \" INFO: \";\n break;\n case KUMA_TRACE_LEVEL_WARN:\n ss << \" WARN: \";\n break;\n case KUMA_TRACE_LEVEL_ERROR:\n ss << \" ERROR: \";\n break;\n case KUMA_TRACE_LEVEL_DEBUG:\n ss << \" DEBUG: \";\n break;\n default:\n ss << \" INFO: \";\n break;\n }\n ss << \"[\" << getCurrentThreadId() << \"] \" << szMsgBuf;\n if (trace_func) {\n trace_func(level, ss.str().c_str());\n } else {\n#ifdef KUMA_OS_WIN\n OutputDebugString(ss.str().c_str());\n#else\n printf(\"%s\\n\", ss.str().c_str());\n#endif\n }\n}\n\nKUMA_NS_END\n<commit_msg>remove date on log since most of log tool will print date automatically<commit_after>\/\/\n\/\/ trace.cpp\n\/\/ kuma\n\/\/\n\/\/ Created by Fengping Bao <jamol@live.com> on 11\/12\/14.\n\/\/ Copyright (c) 2014. All rights reserved.\n\/\/\n\n#include \"kmtrace.h\"\n#include \"util.h\"\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <thread>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <chrono>\n\n#ifdef KUMA_OS_WIN\n# include <Windows.h>\n#endif\n\nKUMA_NS_BEGIN\n\n#ifdef KUMA_OS_WIN\n#define VSNPRINTF(d, dl, fmt, ...) _vsnprintf_s(d, dl, _TRUNCATE, fmt, ##__VA_ARGS__)\n#define LOCALTIME_R(timep, result) localtime_s(result, timep)\n#else\n#define VSNPRINTF vsnprintf\n#define LOCALTIME_R localtime_r\n#endif\n\nstd::function<void(int, const char*)> trace_func;\nvoid setTraceFunc(std::function<void(int, const char*)> func)\n{\n trace_func = func;\n}\n\nvoid TracePrint(int level, const char* szMessage, ...)\n{\n va_list VAList;\n char szMsgBuf[2048] = {0};\n va_start(VAList, szMessage);\n VSNPRINTF(szMsgBuf, sizeof(szMsgBuf)-1, szMessage, VAList);\n \n std::stringstream ss;\n \n \/*auto now_p = std::chrono::system_clock::now();\n auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now_p.time_since_epoch());\n auto now_c = std::chrono::system_clock::to_time_t(now_p);\n struct tm tm_buf;\n LOCALTIME_R(&now_c, &tm_buf);\n ss << std::put_time(&tm_buf, \"%F %T.\");\n ss.width(3);\n ss.fill('0');\n ss << (now_ms.count()%1000) << \" \";*\/\n switch(level)\n {\n case KUMA_TRACE_LEVEL_INFO:\n ss << \"INFO: \";\n break;\n case KUMA_TRACE_LEVEL_WARN:\n ss << \"WARN: \";\n break;\n case KUMA_TRACE_LEVEL_ERROR:\n ss << \"ERROR: \";\n break;\n case KUMA_TRACE_LEVEL_DEBUG:\n ss << \"DEBUG: \";\n break;\n default:\n ss << \"INFO: \";\n break;\n }\n ss << \"[\" << getCurrentThreadId() << \"] \" << szMsgBuf;\n if (trace_func) {\n trace_func(level, ss.str().c_str());\n } else {\n#ifdef KUMA_OS_WIN\n OutputDebugString(ss.str().c_str());\n#else\n printf(\"%s\\n\", ss.str().c_str());\n#endif\n }\n}\n\nKUMA_NS_END\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ libevent_server.cpp\n\/\/\n\/\/ Identification: src\/wire\/libevent_server.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include <fstream>\n#include \"wire\/libevent_server.h\"\n#include \"common\/macros.h\"\n#include \"common\/init.h\"\n#include \"common\/config.h\"\n#include \"common\/thread_pool.h\"\n#include <fcntl.h>\n#include <sys\/socket.h>\n\nnamespace peloton {\nnamespace wire {\n\nstd::vector<std::unique_ptr<LibeventSocket>> &\nLibeventServer::GetGlobalSocketList() {\n static std::vector<std::unique_ptr<LibeventSocket>>\n \/\/ 2 fd's per thread for pipe and 1 listening socket\n global_socket_list(FLAGS_max_connections +\n QUERY_THREAD_COUNT * 2 + 1);\n return global_socket_list;\n}\n\nLibeventSocket *LibeventServer::GetConn(const int &connfd) {\n auto &global_socket_list = GetGlobalSocketList();\n return global_socket_list[connfd].get();\n}\n\nvoid LibeventServer::CreateNewConn(const int &connfd, short ev_flags,\n LibeventThread *thread,\n ConnState init_state) {\n auto &global_socket_list = GetGlobalSocketList();\n global_socket_list[connfd]\n .reset(new LibeventSocket(connfd, ev_flags, thread, init_state));\n}\n\n\/**\n * Stop signal handling\n *\/\nvoid Signal_Callback(UNUSED_ATTRIBUTE evutil_socket_t fd,\n UNUSED_ATTRIBUTE short what, void *arg) {\n struct event_base *base = (event_base *)arg;\n LOG_INFO(\"stop\");\n event_base_loopexit(base, NULL);\n}\n\nLibeventServer::LibeventServer() {\n struct event_base *base = event_base_new();\n struct event *evstop;\n\n \/\/ Create our event base\n if (!base) {\n LOG_INFO(\"Couldn't open event base\");\n exit(EXIT_FAILURE);\n }\n \/\/ Add hang up signal event\n evstop = evsignal_new(base, SIGHUP, Signal_Callback, base);\n evsignal_add(evstop, NULL);\n\n \/\/ TODO: Make pool size a global\n std::shared_ptr<LibeventThread> master_thread(\n new LibeventMasterThread(QUERY_THREAD_COUNT, base));\n\n port_ = FLAGS_port;\n max_connections_ = FLAGS_max_connections;\n\n \/\/ For logging purposes\n \/\/ event_enable_debug_mode();\n \/\/ event_set_log_callback(LogCallback);\n\n \/\/ Commented because it's not in the libevent version we're using\n \/\/ When we upgrade this should be uncommented\n \/\/ event_enable_debug_logging(EVENT_DBG_ALL);\n\n \/\/ Ignore the broken pipe signal\n \/\/ We don't want to exit on write when the client disconnects\n signal(SIGPIPE, SIG_IGN);\n\n if (FLAGS_socket_family == \"AF_INET\") {\n struct sockaddr_in sin;\n PL_MEMSET(&sin, 0, sizeof(sin));\n sin.sin_family = AF_INET;\n sin.sin_addr.s_addr = INADDR_ANY;\n sin.sin_port = htons(port_);\n\n int listen_fd;\n\n listen_fd = socket(AF_INET, SOCK_STREAM, 0);\n\n if (listen_fd < 0) {\n LOG_ERROR(\"Failed to create listen socket\");\n exit(EXIT_FAILURE);\n }\n\n int reuse = 1;\n setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));\n\n if (bind(listen_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {\n LOG_ERROR(\"Failed to bind\");\n exit(EXIT_FAILURE);\n }\n\n int conn_backlog = 12;\n if (listen(listen_fd, conn_backlog) < 0) {\n LOG_ERROR(\"Failed to listen to socket\");\n exit(EXIT_FAILURE);\n }\n\n LibeventServer::CreateNewConn(listen_fd, EV_READ | EV_PERSIST,\n master_thread.get(), CONN_LISTENING);\n\n event_base_dispatch(base);\n event_free(evstop);\n event_base_free(base);\n }\n\n \/\/ This socket family code is not implemented yet\n else {\n LOG_ERROR(\"Unsupported socket family\");\n exit(1);\n }\n}\n}\n}\n<commit_msg>We now tell you what port the system failed to bind on in LibeventServer #350<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ libevent_server.cpp\n\/\/\n\/\/ Identification: src\/wire\/libevent_server.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"wire\/libevent_server.h\"\n#include <fcntl.h>\n#include <inttypes.h>\n#include <sys\/socket.h>\n#include <fstream>\n#include \"common\/config.h\"\n#include \"common\/init.h\"\n#include \"common\/macros.h\"\n#include \"common\/thread_pool.h\"\n\nnamespace peloton {\nnamespace wire {\n\nstd::vector<std::unique_ptr<LibeventSocket>>\n &LibeventServer::GetGlobalSocketList() {\n static std::vector<std::unique_ptr<LibeventSocket>>\n \/\/ 2 fd's per thread for pipe and 1 listening socket\n global_socket_list(FLAGS_max_connections + QUERY_THREAD_COUNT * 2 + 1);\n return global_socket_list;\n}\n\nLibeventSocket *LibeventServer::GetConn(const int &connfd) {\n auto &global_socket_list = GetGlobalSocketList();\n return global_socket_list[connfd].get();\n}\n\nvoid LibeventServer::CreateNewConn(const int &connfd, short ev_flags,\n LibeventThread *thread,\n ConnState init_state) {\n auto &global_socket_list = GetGlobalSocketList();\n global_socket_list[connfd].reset(\n new LibeventSocket(connfd, ev_flags, thread, init_state));\n}\n\n\/**\n * Stop signal handling\n *\/\nvoid Signal_Callback(UNUSED_ATTRIBUTE evutil_socket_t fd,\n UNUSED_ATTRIBUTE short what, void *arg) {\n struct event_base *base = (event_base *)arg;\n LOG_INFO(\"stop\");\n event_base_loopexit(base, NULL);\n}\n\nLibeventServer::LibeventServer() {\n struct event_base *base = event_base_new();\n struct event *evstop;\n\n \/\/ Create our event base\n if (!base) {\n LOG_INFO(\"Couldn't open event base\");\n exit(EXIT_FAILURE);\n }\n \/\/ Add hang up signal event\n evstop = evsignal_new(base, SIGHUP, Signal_Callback, base);\n evsignal_add(evstop, NULL);\n\n \/\/ TODO: Make pool size a global\n std::shared_ptr<LibeventThread> master_thread(\n new LibeventMasterThread(QUERY_THREAD_COUNT, base));\n\n port_ = FLAGS_port;\n max_connections_ = FLAGS_max_connections;\n\n \/\/ For logging purposes\n \/\/ event_enable_debug_mode();\n \/\/ event_set_log_callback(LogCallback);\n\n \/\/ Commented because it's not in the libevent version we're using\n \/\/ When we upgrade this should be uncommented\n \/\/ event_enable_debug_logging(EVENT_DBG_ALL);\n\n \/\/ Ignore the broken pipe signal\n \/\/ We don't want to exit on write when the client disconnects\n signal(SIGPIPE, SIG_IGN);\n\n if (FLAGS_socket_family == \"AF_INET\") {\n struct sockaddr_in sin;\n PL_MEMSET(&sin, 0, sizeof(sin));\n sin.sin_family = AF_INET;\n sin.sin_addr.s_addr = INADDR_ANY;\n sin.sin_port = htons(port_);\n\n int listen_fd;\n\n listen_fd = socket(AF_INET, SOCK_STREAM, 0);\n\n if (listen_fd < 0) {\n LOG_ERROR(\"Failed to create listen socket\");\n exit(EXIT_FAILURE);\n }\n\n int reuse = 1;\n setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));\n\n if (bind(listen_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {\n LOG_ERROR(\"Failed to bind socket to port %\" PRIu64, port_);\n exit(EXIT_FAILURE);\n }\n\n int conn_backlog = 12;\n if (listen(listen_fd, conn_backlog) < 0) {\n LOG_ERROR(\"Failed to listen to socket\");\n exit(EXIT_FAILURE);\n }\n\n LibeventServer::CreateNewConn(listen_fd, EV_READ | EV_PERSIST,\n master_thread.get(), CONN_LISTENING);\n\n event_base_dispatch(base);\n event_free(evstop);\n event_base_free(base);\n }\n\n \/\/ This socket family code is not implemented yet\n else {\n LOG_ERROR(\"Unsupported socket family\");\n exit(1);\n }\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * v8cgi main file. Loosely based on V8's \"shell\" sample app.\n *\/\n\n#define _STRING(x) #x\n#define STRING(x) _STRING(x)\n\n#include <sstream>\n#include <stdlib.h>\n#include <v8.h>\n#include <map>\n\n#ifdef FASTCGI\n# include <fcgi_stdio.h>\n#endif\n\n#include \"js_system.h\"\n#include \"js_io.h\"\n#include \"js_socket.h\"\n#include \"js_common.h\"\n#include \"js_macros.h\"\n#include \"js_cache.h\"\n\n#ifndef windows\n# include <dlfcn.h>\n#else\n# include <windows.h>\n# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)\n#endif\n\n\/\/ chdir()\n#ifndef HAVE_CHDIR\n#\tinclude <direct.h>\n#\tdefine chdir(name) _chdir(name)\n#endif\n\n\/\/ getcwd()\n#ifndef HAVE_GETCWD\n#\tinclude <direct.h>\n#\tdefine getcwd(name, bytes) _getcwd(name, bytes)\n#endif\n\nv8::Handle<v8::Array> __onexit; \/* what to do on exit *\/\nconst char * cfgfile = NULL; \/* config file *\/\nconst char * execfile = NULL; \/* command-line specified file *\/\nCache cache;\n\nint total = 0; \/* fcgi debug *\/\n\nvoid js_error(const char * message) {\n\tint cgi = 0;\n\tv8::Local<v8::Function> fun;\n\tv8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"response\"));\n\tif (context->IsObject()) {\n\t\tv8::Local<v8::Value> print = context->ToObject()->Get(JS_STR(\"error\"));\n\t\tif (print->IsObject()) {\n\t\t\tfun = v8::Local<v8::Function>::Cast(print);\n\t\t\tcgi = 1;\n\t\t}\n\t}\n\tif (!cgi) {\n\t\tcontext = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"System\"));\n\t\tfun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR(\"stdout\")));\n\t}\n\t\n\tv8::Handle<v8::Value> data[1];\n\tdata[0] = JS_STR(message);\n\tfun->Call(context->ToObject(), 1, data);\n}\n\nvoid js_exception(v8::TryCatch* try_catch) {\n\tv8::HandleScope handle_scope;\n\tv8::String::Utf8Value exception(try_catch->Exception());\n\tv8::Handle<v8::Message> message = try_catch->Message();\n\tstd::string msgstring = \"\";\n\tstd::stringstream ss;\n\n\tif (message.IsEmpty()) {\n\t\tmsgstring += *exception;\n\t\tmsgstring += \"\\n\";\n\t} else {\n\t\tv8::String::Utf8Value filename(message->GetScriptResourceName());\n\t\tint linenum = message->GetLineNumber();\n\t\tmsgstring += *filename;\n\t\tmsgstring += \":\";\n\t\tss << linenum;\n\t\tmsgstring += ss.str();\n\t\tmsgstring += \": \";\n\t\tmsgstring += *exception;\n\t\tmsgstring += \"\\n\";\n\t}\n\t\n\tjs_error(msgstring.c_str());\n}\n\nv8::Handle<v8::String> js_read(const char* name) {\n\tstd::string n = name;\n\tstd::string source = cache.getJS(n);\n\treturn JS_STR(source.c_str());\n}\n\nint js_execute(const char * str, bool change) {\n\tv8::HandleScope handle_scope;\n\tv8::TryCatch try_catch;\n\tv8::Handle<v8::String> name = JS_STR(str);\n\tv8::Handle<v8::String> source = js_read(str);\n\n\tif (source.IsEmpty()) {\n\t\tstd::string s = \"Error reading '\";\n\t\ts += str;\n\t\ts += \"'\\n\";\n\t\tjs_error(s.c_str());\n\t\treturn 1;\n\t}\n\t\n\tv8::Handle<v8::Script> script = v8::Script::Compile(source, name);\n\tif (script.IsEmpty()) {\n\t\tjs_exception(&try_catch);\n\t\treturn 1;\n\t} else {\n\t\tstd::string oldcwd = getcwd(NULL, 0);\n\t\tstd::string newcwd = str;\n\t\tsize_t pos = newcwd.find_last_of('\/');\n\t\tif (pos == std::string::npos) { pos = newcwd.find_last_of('\\\\'); }\n\t\tif (pos != std::string::npos && change) {\n\t\t\tnewcwd.erase(pos, newcwd.length()-pos);\n \t\tchdir(newcwd.c_str());\n\t\t}\n\t\t\n\t\tv8::Handle<v8::Value> result = script->Run();\n\t\t\n\t\tif (change) { chdir(oldcwd.c_str()); }\n\t\tif (result.IsEmpty()) {\n\t\t\tjs_exception(&try_catch);\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint js_library(char * name) {\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR(\"libraryPath\"));\n\tv8::String::Utf8Value pfx(prefix);\n\tstd::string path = \"\";\n\tstd::string error;\n\t\n\tpath += *pfx;\n\tpath += \"\/\";\n\tpath += name;\n\t\n\tif (path.find(\".so\") != std::string::npos || path.find(\".dll\") != std::string::npos) {\n\t\tvoid * handle = cache.getHandle(path);\n\t\tif (handle == NULL) {\n\t\t\terror = \"Cannot load shared library '\";\n\t\t\terror += path;\n\t\t\terror += \"'\\n\";\n\t\t\tjs_error(error.c_str());\n\t\t\treturn 1;\n\t\t}\n\n\t\tvoid (*func) (v8::Handle<v8::Object>);\n\t\tfunc = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, \"init\"));\n\t\tif (!func) {\n\t\t\terror = \"Cannot initialize shared library '\";\n\t\t\terror += path;\n\t\t\terror += \"'\\n\";\n\t\t\tjs_error(error.c_str());\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tfunc(v8::Context::GetCurrent()->Global());\n\t\treturn 0;\t\t\t\t\t\t\t\t\t\n\t} else {\n\t\treturn js_execute(path.c_str(), false);\n\t}\n}\n\nint js_autoload() {\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR(\"libraryAutoload\")));\n\tint cnt = list->Length();\n\tfor (int i=0;i<cnt;i++) {\n\t\tv8::Handle<v8::Value> item = list->Get(JS_INT(i));\n\t\tv8::String::Utf8Value name(item);\n\t\tif (js_library(*name)) { return 1; }\n\t}\n\treturn 0;\n}\n\nv8::Handle<v8::Value> _include(const v8::Arguments& args) {\n\tbool ok = true;\n\tint result;\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope;\n\t\tv8::String::Utf8Value file(args[i]);\n\t\tresult = js_execute(*file, true);\n\t\tif (result != 0) { ok = false; }\n\t}\n\treturn JS_BOOL(ok);\n}\n\nv8::Handle<v8::Value> _library(const v8::Arguments & args) {\n\tv8::HandleScope handle_scope;\n\tbool ok = true;\n\tint result;\n\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR(\"libraryPath\"));\n\tv8::String::Utf8Value pfx(prefix);\n\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope;\n\t\tv8::String::Utf8Value file(args[i]);\n\t\tresult = js_library(*file);\n\t\tif (result != 0) { ok = false; }\n\t}\n\treturn JS_BOOL(ok);\n}\n\nv8::Handle<v8::Value> _onexit(const v8::Arguments& args) {\n\t__onexit->Set(JS_INT(__onexit->Length()), args[0]);\n\treturn v8::Undefined();\n}\n\nvoid main_terminate() {\t\n}\n\nvoid main_finish() {\n\tv8::HandleScope handle_scope;\n\tuint32_t max = __onexit->Length();\n\tv8::Handle<v8::Function> fun;\n\tfor (unsigned int i=0;i<max;i++) {\n\t\tfun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));\n\t\tfun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);\n\t}\n}\n\nint main_execute() {\n\tv8::HandleScope handle_scope;\n\tconst char * name = execfile;\n\n\tif (name == NULL) { \/\/ try the PATH_TRANSLATED env var\n\t\tv8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"System\"));\n\t\tv8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR(\"env\"));\n\t\tv8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR(\"PATH_TRANSLATED\"));\n\t\tif (pt->IsString()) {\n\t\t\tv8::String::Utf8Value jsname(pt);\n\t\t\tname = *jsname;\n\t\t}\n\t}\n\t\n\tif (name == NULL) {\n\t\tjs_error(\"Nothing to do.\\n\");\n\t\treturn 1;\n\t} else {\n\t\treturn js_execute(name, true);\n\t}\n\t\n}\n\nint main_prepare(char ** envp) {\n\t__onexit = v8::Array::New();\n\tv8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();\n\tg->Set(JS_STR(\"library\"), v8::FunctionTemplate::New(_library)->GetFunction());\n\tg->Set(JS_STR(\"include\"), v8::FunctionTemplate::New(_include)->GetFunction());\n\tg->Set(JS_STR(\"onexit\"), v8::FunctionTemplate::New(_onexit)->GetFunction());\n\tg->Set(JS_STR(\"total\"), JS_INT(total++));\n\tg->Set(JS_STR(\"global\"), g);\n\tg->Set(JS_STR(\"Config\"), v8::Object::New());\n\n\tsetup_system(envp, g);\n\tsetup_io(g);\t\n\tsetup_socket(g);\n\t\n\tif (js_execute(cfgfile, false)) { \n\t\tjs_error(\"Cannot load configuration, quitting...\\n\");\n\t\treturn 1;\n\t}\n\n\tif (js_autoload()) { \n\t\tjs_error(\"Cannot load default libraries, quitting...\\n\"); \n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nint main_initialize(int argc, char ** argv) {\n\tv8::V8::SetFlagsFromCommandLine(&argc, argv, true);\n\tcfgfile = STRING(CONFIG_PATH);\n\t\n\tint argptr = 0;\n\tfor (int i = 1; i < argc; i++) {\n\t\tconst char* str = argv[i];\n\t\targptr = i;\n\t\tif (strcmp(str, \"-c\") == 0 && i + 1 < argc) {\n\t\t\tcfgfile = argv[i+1];\n\t\t\targptr = 0;\n\t\t\ti++;\n\t\t}\n\t}\n\t\n\tif (argptr) { execfile = argv[argptr]; }\n\t\n\tFILE* file = fopen(cfgfile, \"rb\");\n\tif (file == NULL) { \n\t\tprintf(\"Invalid configuration file.\\n\");\n\t\treturn 1;\n\t}\n\tfclose(file);\n\treturn 0;\n}\n\nint main_cycle(char ** envp) {\n\tint result = 0;\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Context> context = v8::Context::New(NULL, global);\n\tv8::Context::Scope context_scope(context);\n\n\tresult = main_prepare(envp);\n\tif (result == 0) {\n\t\tresult = main_execute();\n\t}\n\tmain_finish();\n\treturn result;\n}\n\nint main(int argc, char ** argv, char ** envp) {\n\tint result = 0;\n\tresult = main_initialize(argc, argv);\n\tif (result) { exit(1); }\n\n#ifdef FASTCGI\n\twhile(FCGI_Accept() >= 0) {\n#endif\n\n\tresult = main_cycle(envp);\n\t\n#ifdef FASTCGI\n\tFCGI_SetExitStatus(result);\n#endif\n\t\n#ifdef FASTCGI\n\t}\n#endif\n\n\tmain_terminate();\n\treturn result;\n}\n<commit_msg>main code cleanup<commit_after>\/*\n * v8cgi main file. Loosely based on V8's \"shell\" sample app.\n *\/\n\n#define _STRING(x) #x\n#define STRING(x) _STRING(x)\n\n#include <sstream>\n#include <stdlib.h>\n#include <v8.h>\n#include <map>\n\n#ifdef FASTCGI\n# include <fcgi_stdio.h>\n#endif\n\n#include \"js_system.h\"\n#include \"js_io.h\"\n#include \"js_socket.h\"\n#include \"js_common.h\"\n#include \"js_macros.h\"\n#include \"js_cache.h\"\n\n#ifndef windows\n# include <dlfcn.h>\n#else\n# include <windows.h>\n# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)\n#endif\n\n\/\/ chdir()\n#ifndef HAVE_CHDIR\n#\tinclude <direct.h>\n#\tdefine chdir(name) _chdir(name)\n#endif\n\n\/\/ getcwd()\n#ifndef HAVE_GETCWD\n#\tinclude <direct.h>\n#\tdefine getcwd(name, bytes) _getcwd(name, bytes)\n#endif\n\nv8::Handle<v8::Array> __onexit; \/* what to do on exit *\/\nconst char * cfgfile = NULL; \/* config file *\/\nconst char * execfile = NULL; \/* command-line specified file *\/\nCache cache;\n\nint total = 0; \/* fcgi debug *\/\n\nvoid js_error(const char * message) {\n\tint cgi = 0;\n\tv8::Local<v8::Function> fun;\n\tv8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"response\"));\n\tif (context->IsObject()) {\n\t\tv8::Local<v8::Value> print = context->ToObject()->Get(JS_STR(\"error\"));\n\t\tif (print->IsObject()) {\n\t\t\tfun = v8::Local<v8::Function>::Cast(print);\n\t\t\tcgi = 1;\n\t\t}\n\t}\n\tif (!cgi) {\n\t\tcontext = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"System\"));\n\t\tfun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR(\"stdout\")));\n\t}\n\t\n\tv8::Handle<v8::Value> data[1];\n\tdata[0] = JS_STR(message);\n\tfun->Call(context->ToObject(), 1, data);\n}\n\nvoid js_exception(v8::TryCatch* try_catch) {\n\tv8::HandleScope handle_scope;\n\tv8::String::Utf8Value exception(try_catch->Exception());\n\tv8::Handle<v8::Message> message = try_catch->Message();\n\tstd::string msgstring = \"\";\n\tstd::stringstream ss;\n\n\tif (message.IsEmpty()) {\n\t\tmsgstring += *exception;\n\t\tmsgstring += \"\\n\";\n\t} else {\n\t\tv8::String::Utf8Value filename(message->GetScriptResourceName());\n\t\tint linenum = message->GetLineNumber();\n\t\tmsgstring += *filename;\n\t\tmsgstring += \":\";\n\t\tss << linenum;\n\t\tmsgstring += ss.str();\n\t\tmsgstring += \": \";\n\t\tmsgstring += *exception;\n\t\tmsgstring += \"\\n\";\n\t}\n\t\n\tjs_error(msgstring.c_str());\n}\n\nv8::Handle<v8::String> js_read(const char* name) {\n\tstd::string n = name;\n\tstd::string source = cache.getJS(n);\n\treturn JS_STR(source.c_str());\n}\n\nint js_execute(const char * str, bool change) {\n\tv8::HandleScope handle_scope;\n\tv8::TryCatch try_catch;\n\tv8::Handle<v8::String> name = JS_STR(str);\n\tv8::Handle<v8::String> source = js_read(str);\n\n\tif (source.IsEmpty()) {\n\t\tstd::string s = \"Error reading '\";\n\t\ts += str;\n\t\ts += \"'\\n\";\n\t\tjs_error(s.c_str());\n\t\treturn 1;\n\t}\n\t\n\tv8::Handle<v8::Script> script = v8::Script::Compile(source, name);\n\tif (script.IsEmpty()) {\n\t\tjs_exception(&try_catch);\n\t\treturn 1;\n\t} else {\n\t\tstd::string oldcwd = getcwd(NULL, 0);\n\t\tstd::string newcwd = str;\n\t\tsize_t pos = newcwd.find_last_of('\/');\n\t\tif (pos == std::string::npos) { pos = newcwd.find_last_of('\\\\'); }\n\t\tif (pos != std::string::npos && change) {\n\t\t\tnewcwd.erase(pos, newcwd.length()-pos);\n \t\tchdir(newcwd.c_str());\n\t\t}\n\t\t\n\t\tv8::Handle<v8::Value> result = script->Run();\n\t\t\n\t\tif (change) { chdir(oldcwd.c_str()); }\n\t\tif (result.IsEmpty()) {\n\t\t\tjs_exception(&try_catch);\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint js_library(char * name) {\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR(\"libraryPath\"));\n\tv8::String::Utf8Value pfx(prefix);\n\tstd::string path = \"\";\n\tstd::string error;\n\t\n\tpath += *pfx;\n\tpath += \"\/\";\n\tpath += name;\n\t\n\tif (path.find(\".so\") != std::string::npos || path.find(\".dll\") != std::string::npos) {\n\t\tvoid * handle = cache.getHandle(path);\n\t\tif (handle == NULL) {\n\t\t\terror = \"Cannot load shared library '\";\n\t\t\terror += path;\n\t\t\terror += \"'\\n\";\n\t\t\tjs_error(error.c_str());\n\t\t\treturn 1;\n\t\t}\n\n\t\tvoid (*func) (v8::Handle<v8::Object>);\n\t\tfunc = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, \"init\"));\n\t\tif (!func) {\n\t\t\terror = \"Cannot initialize shared library '\";\n\t\t\terror += path;\n\t\t\terror += \"'\\n\";\n\t\t\tjs_error(error.c_str());\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\tfunc(v8::Context::GetCurrent()->Global());\n\t\treturn 0;\t\t\t\t\t\t\t\t\t\n\t} else {\n\t\treturn js_execute(path.c_str(), false);\n\t}\n}\n\nint js_autoload() {\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR(\"libraryAutoload\")));\n\tint cnt = list->Length();\n\tfor (int i=0;i<cnt;i++) {\n\t\tv8::Handle<v8::Value> item = list->Get(JS_INT(i));\n\t\tv8::String::Utf8Value name(item);\n\t\tif (js_library(*name)) { return 1; }\n\t}\n\treturn 0;\n}\n\nJS_METHOD(_include) {\n\tbool ok = true;\n\tint result;\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope;\n\t\tv8::String::Utf8Value file(args[i]);\n\t\tresult = js_execute(*file, true);\n\t\tif (result != 0) { ok = false; }\n\t}\n\treturn JS_BOOL(ok);\n}\n\nJS_METHOD(_library) {\n\tv8::HandleScope handle_scope;\n\tbool ok = true;\n\tint result;\n\n\tv8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"Config\"));\n\tv8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR(\"libraryPath\"));\n\tv8::String::Utf8Value pfx(prefix);\n\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope;\n\t\tv8::String::Utf8Value file(args[i]);\n\t\tresult = js_library(*file);\n\t\tif (result != 0) { ok = false; }\n\t}\n\treturn JS_BOOL(ok);\n}\n\nJS_METHOD(_onexit) {\n\t__onexit->Set(JS_INT(__onexit->Length()), args[0]);\n\treturn v8::Undefined();\n}\n\nvoid main_terminate() {\t\n}\n\nvoid main_finish() {\n\tv8::HandleScope handle_scope;\n\tuint32_t max = __onexit->Length();\n\tv8::Handle<v8::Function> fun;\n\tfor (unsigned int i=0;i<max;i++) {\n\t\tfun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));\n\t\tfun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);\n\t}\n}\n\nint main_execute() {\n\tv8::HandleScope handle_scope;\n\tconst char * name = execfile;\n\n\tif (name == NULL) { \/\/ try the PATH_TRANSLATED env var\n\t\tv8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR(\"System\"));\n\t\tv8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR(\"env\"));\n\t\tv8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR(\"PATH_TRANSLATED\"));\n\t\tif (pt->IsString()) {\n\t\t\tv8::String::Utf8Value jsname(pt);\n\t\t\tname = *jsname;\n\t\t}\n\t}\n\t\n\tif (name == NULL) {\n\t\tjs_error(\"Nothing to do.\\n\");\n\t\treturn 1;\n\t} else {\n\t\treturn js_execute(name, true);\n\t}\n\t\n}\n\nint main_prepare(char ** envp) {\n\t__onexit = v8::Array::New();\n\tv8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();\n\tg->Set(JS_STR(\"library\"), v8::FunctionTemplate::New(_library)->GetFunction());\n\tg->Set(JS_STR(\"include\"), v8::FunctionTemplate::New(_include)->GetFunction());\n\tg->Set(JS_STR(\"onexit\"), v8::FunctionTemplate::New(_onexit)->GetFunction());\n\tg->Set(JS_STR(\"total\"), JS_INT(total++));\n\tg->Set(JS_STR(\"global\"), g);\n\tg->Set(JS_STR(\"Config\"), v8::Object::New());\n\n\tsetup_system(envp, g);\n\tsetup_io(g);\t\n\tsetup_socket(g);\n\t\n\tif (js_execute(cfgfile, false)) { \n\t\tjs_error(\"Cannot load configuration, quitting...\\n\");\n\t\treturn 1;\n\t}\n\n\tif (js_autoload()) { \n\t\tjs_error(\"Cannot load default libraries, quitting...\\n\"); \n\t\treturn 1;\n\t}\n\t\n\treturn 0;\n}\n\nint main_initialize(int argc, char ** argv) {\n\tv8::V8::SetFlagsFromCommandLine(&argc, argv, true);\n\tcfgfile = STRING(CONFIG_PATH);\n\t\n\tint argptr = 0;\n\tfor (int i = 1; i < argc; i++) {\n\t\tconst char* str = argv[i];\n\t\targptr = i;\n\t\tif (strcmp(str, \"-c\") == 0 && i + 1 < argc) {\n\t\t\tcfgfile = argv[i+1];\n\t\t\targptr = 0;\n\t\t\ti++;\n\t\t}\n\t}\n\t\n\tif (argptr) { execfile = argv[argptr]; }\n\t\n\tFILE* file = fopen(cfgfile, \"rb\");\n\tif (file == NULL) { \n\t\tprintf(\"Invalid configuration file.\\n\");\n\t\treturn 1;\n\t}\n\tfclose(file);\n\treturn 0;\n}\n\nint main_cycle(char ** envp) {\n\tint result = 0;\n\tv8::HandleScope handle_scope;\n\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();\n\tv8::Handle<v8::Context> context = v8::Context::New(NULL, global);\n\tv8::Context::Scope context_scope(context);\n\n\tresult = main_prepare(envp);\n\tif (result == 0) {\n\t\tresult = main_execute();\n\t}\n\tmain_finish();\n\treturn result;\n}\n\nint main(int argc, char ** argv, char ** envp) {\n\tint result = 0;\n\tresult = main_initialize(argc, argv);\n\tif (result) { exit(1); }\n\n#ifdef FASTCGI\n\twhile(FCGI_Accept() >= 0) {\n#endif\n\n\tresult = main_cycle(envp);\n\t\n#ifdef FASTCGI\n\tFCGI_SetExitStatus(result);\n#endif\n\t\n#ifdef FASTCGI\n\t}\n#endif\n\n\tmain_terminate();\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * IceWM\n *\n * Copyright (C) 1997-2001 Marko Macek\n *\/\n#include \"config.h\"\n#include \"yfull.h\"\n#include \"ypixbuf.h\"\n#include \"ypaint.h\"\n#include \"yicon.h\"\n#include \"yapp.h\"\n#include \"sysdep.h\"\n#include \"prefs.h\"\n#include \"yprefs.h\"\n#include \"wmprog.h\" \/\/ !!! remove this\n\n#include \"intl.h\"\n\n#ifndef LITE\n\nstatic bool didInit = false;\nstatic ref<YResourcePaths> iconPaths;\n\nvoid initIcons() {\n if (!didInit) {\n didInit = true;\n iconPaths = YResourcePaths::subdirs(\"icons\/\");\n }\n}\n\n\nYIcon::YIcon(upath filename):\n fSmall(null), fLarge(null), fHuge(null),\n loadedS(false), loadedL(false), loadedH(false),\n fPath(filename), fCached(false)\n{\n}\n\nYIcon::YIcon(ref<YImage> small, ref<YImage> large, ref<YImage> huge) :\n fSmall(small), fLarge(large), fHuge(huge),\n loadedS(small != null), loadedL(large != null), loadedH(huge != null),\n fPath(NULL), fCached(false)\n{\n}\n\nYIcon::~YIcon() {\n fHuge = null;\n fLarge = null;\n fSmall = null;\n}\n\nstatic upath joinPath(upath dir, upath name) {\n if (dir == null)\n return name;\n\n if (name.isAbsolute())\n return name;\n\n return dir.relative(name);\n}\n\nupath YIcon::findIcon(upath dir, upath base, unsigned size) {\n char icons_size[1024];\n upath fullpath;\n\n fullpath = joinPath(dir, base);\n if (fullpath.fileExists())\n return fullpath;\n\n sprintf(icons_size, \"%s_%dx%d.xpm\", cstring(base.path()).c_str(), size, size);\n fullpath = joinPath(dir, icons_size);\n if (fullpath.fileExists())\n return fullpath;\n\n fullpath = joinPath(dir, base.addExtension(\"xpm\"));\n if (fullpath.fileExists())\n return fullpath;\n\n fullpath = joinPath(dir, base.addExtension(\"png\"));\n if (fullpath.fileExists())\n return fullpath;\n\n return 0;\n}\n\nupath YIcon::findIcon(int size) {\n cstring cs(fPath.path());\n initIcons();\n\n if (iconPath != 0 && iconPath[0] != 0) {\n for (char const *p = iconPath, *q = iconPath; *q; q = p) {\n while (*p && *p != PATHSEP) p++;\n\n unsigned len(p - q);\n if (*p) ++p;\n\n upath path = upath(newstr(q, len));\n\n upath fullpath = findIcon(path.path(), fPath, size);\n if (fullpath != null) {\n return fullpath;\n }\n }\n }\n\n for (int i = 0; i < iconPaths->getCount(); i++) {\n upath path = iconPaths->getPath(i)->joinPath(upath(\"\/icons\/\"));\n upath fullpath = findIcon(path.path(), fPath, size);\n if (fullpath != null)\n return fullpath;\n }\n\n MSG((\"Icon \\\"%s\\\" not found.\", cs.c_str()));\n\n return null;\n}\n\nref<YImage> YIcon::loadIcon(int size) {\n ref<YImage> icon;\n\n if (fPath != null) {\n upath fullPath;\n upath loadPath;\n\n if (fPath.isAbsolute() && fPath.fileExists()) {\n loadPath = fPath;\n } else {\n fullPath = findIcon(size);\n if (fullPath != null) {\n loadPath = fullPath;\n } else if (size != hugeSize() && (fullPath = findIcon(hugeSize())) != null) {\n loadPath = fullPath;\n } else if (size != largeSize() && (fullPath = findIcon(largeSize())) != null) {\n loadPath = fullPath;\n } else if (size != smallSize() && (fullPath = findIcon(smallSize())) != null) {\n loadPath = fullPath;\n }\n }\n if (loadPath != null) {\n cstring cs(loadPath.path());\n icon = YImage::load(cs.c_str());\n if (icon == null)\n warn(_(\"Out of memory for pixmap \\\"%s\\\"\"), cs.c_str());\n }\n }\n#if 1\n if (icon != null) {\n icon = icon->scale(size, size);\n }\n#endif\n return icon;\n}\n\nref<YImage> YIcon::huge() {\n if (fHuge == null && !loadedH) {\n fHuge = loadIcon(hugeSize());\n loadedH = true;\n\n\tif (fHuge == null && large() != null)\n fHuge = large()->scale(hugeSize(), hugeSize());\n\n\tif (fHuge == null && small() != null)\n fHuge = small()->scale(hugeSize(), hugeSize());\n }\n\n return fHuge;\n}\n\nref<YImage> YIcon::large() {\n if (fLarge == null && !loadedL) {\n fLarge = loadIcon(largeSize());\n loadedL = true;\n\n\tif (fLarge == null && huge() != null)\n fLarge = huge()->scale(largeSize(), largeSize());\n\n\tif (fLarge == null && small() != null)\n\t fLarge = small()->scale(largeSize(), largeSize());\n }\n\n return fLarge;\n}\n\nref<YImage> YIcon::small() {\n if (fSmall == null && !loadedS) {\n fSmall = loadIcon(smallSize());\n loadedS = true;\n\n if (fSmall == null && large() != null)\n fSmall = large()->scale(smallSize(), smallSize());\n\tif (fSmall == null && huge() != null)\n fSmall = huge()->scale(smallSize(), smallSize());\n }\n\n return fSmall;\n}\n\nref<YImage> YIcon::getScaledIcon(int size) {\n ref<YImage> base = null;\n\n#if 1\n if (size == smallSize())\n base = small();\n else if (size == largeSize())\n base = large();\n else if (size == hugeSize())\n base = huge();\n#endif\n\n if (base == null)\n base = huge();\n if (base == null)\n base = large();\n if (base == null)\n base = small();\n\n if (base != null) {\n ref<YImage> img = base->scale(size, size);\n return img;\n }\n return base;\n}\n\n\nstatic YRefArray<YIcon> iconCache;\n\nvoid YIcon::removeFromCache() {\n int n = cacheFind(iconName());\n if (n >= 0) {\n fPath = null;\n iconCache.remove(n);\n }\n}\n\nint YIcon::cacheFind(upath name) {\n int l, r, m;\n\n l = 0;\n r = iconCache.getCount();\n while (l < r) {\n m = (l + r) \/ 2;\n ref<YIcon> found = iconCache.getItem(m);\n int cmp = name.path().compareTo(found->iconName().path());\n if (cmp == 0) {\n return m;\n } else if (cmp < 0)\n r = m;\n else\n l = m + 1;\n }\n return -(l + 1);\n}\n\nref<YIcon> YIcon::getIcon(const char *name) {\n int n = cacheFind(name);\n if (n >= 0)\n return iconCache.getItem(n);\n\n ref<YIcon>newicon;\n newicon.init(new YIcon(name));\n if (newicon != null) {\n newicon->setCached(true);\n iconCache.insert(-n - 1, newicon);\n }\n return getIcon(name);\n}\n\nvoid YIcon::freeIcons() {\n while (iconCache.getCount() > 0)\n iconCache.getItem(0)->removeFromCache();\n}\n\nint YIcon::smallSize() {\n return smallIconSize;\n}\n\nint YIcon::largeSize() {\n return largeIconSize;\n}\n\nint YIcon::hugeSize() {\n return hugeIconSize;\n}\n\nvoid YIcon::draw(Graphics &g, int x, int y, int size) {\n ref<YImage> image = getScaledIcon(size);\n if (image != null) {\n if (!doubleBuffer) {\n g.drawImage(image, x, y);\n } else {\n g.compositeImage(image, 0, 0, size, size, x, y);\n }\n }\n}\n\n#endif\n<commit_msg>fix icon search (.xpm .png)<commit_after>\/*\n * IceWM\n *\n * Copyright (C) 1997-2001 Marko Macek\n *\/\n#include \"config.h\"\n#include \"yfull.h\"\n#include \"ypixbuf.h\"\n#include \"ypaint.h\"\n#include \"yicon.h\"\n#include \"yapp.h\"\n#include \"sysdep.h\"\n#include \"prefs.h\"\n#include \"yprefs.h\"\n#include \"wmprog.h\" \/\/ !!! remove this\n\n#include \"intl.h\"\n\n#ifndef LITE\n\nstatic bool didInit = false;\nstatic ref<YResourcePaths> iconPaths;\n\nvoid initIcons() {\n if (!didInit) {\n didInit = true;\n iconPaths = YResourcePaths::subdirs(\"icons\/\");\n }\n}\n\n\nYIcon::YIcon(upath filename):\n fSmall(null), fLarge(null), fHuge(null),\n loadedS(false), loadedL(false), loadedH(false),\n fPath(filename), fCached(false)\n{\n}\n\nYIcon::YIcon(ref<YImage> small, ref<YImage> large, ref<YImage> huge) :\n fSmall(small), fLarge(large), fHuge(huge),\n loadedS(small != null), loadedL(large != null), loadedH(huge != null),\n fPath(NULL), fCached(false)\n{\n}\n\nYIcon::~YIcon() {\n fHuge = null;\n fLarge = null;\n fSmall = null;\n}\n\nstatic upath joinPath(upath dir, upath name) {\n if (dir == null)\n return name;\n\n if (name.isAbsolute())\n return name;\n\n return dir.relative(name);\n}\n\nupath YIcon::findIcon(upath dir, upath base, unsigned size) {\n char icons_size[1024];\n upath fullpath;\n\n fullpath = joinPath(dir, base);\n if (fullpath.fileExists())\n return fullpath;\n\n sprintf(icons_size, \"%s_%dx%d.xpm\", cstring(base.path()).c_str(), size, size);\n fullpath = joinPath(dir, icons_size);\n if (fullpath.fileExists())\n return fullpath;\n\n fullpath = joinPath(dir, base.addExtension(\".xpm\"));\n if (fullpath.fileExists())\n return fullpath;\n\n fullpath = joinPath(dir, base.addExtension(\".png\"));\n if (fullpath.fileExists())\n return fullpath;\n\n return 0;\n}\n\nupath YIcon::findIcon(int size) {\n cstring cs(fPath.path());\n initIcons();\n\n if (iconPath != 0 && iconPath[0] != 0) {\n for (char const *p = iconPath, *q = iconPath; *q; q = p) {\n while (*p && *p != PATHSEP) p++;\n\n unsigned len(p - q);\n if (*p) ++p;\n\n upath path = upath(newstr(q, len));\n\n upath fullpath = findIcon(path.path(), fPath, size);\n if (fullpath != null) {\n return fullpath;\n }\n }\n }\n\n for (int i = 0; i < iconPaths->getCount(); i++) {\n upath path = iconPaths->getPath(i)->joinPath(upath(\"\/icons\/\"));\n upath fullpath = findIcon(path.path(), fPath, size);\n if (fullpath != null)\n return fullpath;\n }\n\n MSG((\"Icon \\\"%s\\\" not found.\", cs.c_str()));\n\n return null;\n}\n\nref<YImage> YIcon::loadIcon(int size) {\n ref<YImage> icon;\n\n if (fPath != null) {\n upath fullPath;\n upath loadPath;\n\n if (fPath.isAbsolute() && fPath.fileExists()) {\n loadPath = fPath;\n } else {\n fullPath = findIcon(size);\n if (fullPath != null) {\n loadPath = fullPath;\n } else if (size != hugeSize() && (fullPath = findIcon(hugeSize())) != null) {\n loadPath = fullPath;\n } else if (size != largeSize() && (fullPath = findIcon(largeSize())) != null) {\n loadPath = fullPath;\n } else if (size != smallSize() && (fullPath = findIcon(smallSize())) != null) {\n loadPath = fullPath;\n }\n }\n if (loadPath != null) {\n cstring cs(loadPath.path());\n icon = YImage::load(cs.c_str());\n if (icon == null)\n warn(_(\"Out of memory for pixmap \\\"%s\\\"\"), cs.c_str());\n }\n }\n#if 1\n if (icon != null) {\n icon = icon->scale(size, size);\n }\n#endif\n return icon;\n}\n\nref<YImage> YIcon::huge() {\n if (fHuge == null && !loadedH) {\n fHuge = loadIcon(hugeSize());\n loadedH = true;\n\n\tif (fHuge == null && large() != null)\n fHuge = large()->scale(hugeSize(), hugeSize());\n\n\tif (fHuge == null && small() != null)\n fHuge = small()->scale(hugeSize(), hugeSize());\n }\n\n return fHuge;\n}\n\nref<YImage> YIcon::large() {\n if (fLarge == null && !loadedL) {\n fLarge = loadIcon(largeSize());\n loadedL = true;\n\n\tif (fLarge == null && huge() != null)\n fLarge = huge()->scale(largeSize(), largeSize());\n\n\tif (fLarge == null && small() != null)\n\t fLarge = small()->scale(largeSize(), largeSize());\n }\n\n return fLarge;\n}\n\nref<YImage> YIcon::small() {\n if (fSmall == null && !loadedS) {\n fSmall = loadIcon(smallSize());\n loadedS = true;\n\n if (fSmall == null && large() != null)\n fSmall = large()->scale(smallSize(), smallSize());\n\tif (fSmall == null && huge() != null)\n fSmall = huge()->scale(smallSize(), smallSize());\n }\n\n return fSmall;\n}\n\nref<YImage> YIcon::getScaledIcon(int size) {\n ref<YImage> base = null;\n\n#if 1\n if (size == smallSize())\n base = small();\n else if (size == largeSize())\n base = large();\n else if (size == hugeSize())\n base = huge();\n#endif\n\n if (base == null)\n base = huge();\n if (base == null)\n base = large();\n if (base == null)\n base = small();\n\n if (base != null) {\n ref<YImage> img = base->scale(size, size);\n return img;\n }\n return base;\n}\n\n\nstatic YRefArray<YIcon> iconCache;\n\nvoid YIcon::removeFromCache() {\n int n = cacheFind(iconName());\n if (n >= 0) {\n fPath = null;\n iconCache.remove(n);\n }\n}\n\nint YIcon::cacheFind(upath name) {\n int l, r, m;\n\n l = 0;\n r = iconCache.getCount();\n while (l < r) {\n m = (l + r) \/ 2;\n ref<YIcon> found = iconCache.getItem(m);\n int cmp = name.path().compareTo(found->iconName().path());\n if (cmp == 0) {\n return m;\n } else if (cmp < 0)\n r = m;\n else\n l = m + 1;\n }\n return -(l + 1);\n}\n\nref<YIcon> YIcon::getIcon(const char *name) {\n int n = cacheFind(name);\n if (n >= 0)\n return iconCache.getItem(n);\n\n ref<YIcon>newicon;\n newicon.init(new YIcon(name));\n if (newicon != null) {\n newicon->setCached(true);\n iconCache.insert(-n - 1, newicon);\n }\n return getIcon(name);\n}\n\nvoid YIcon::freeIcons() {\n while (iconCache.getCount() > 0)\n iconCache.getItem(0)->removeFromCache();\n}\n\nint YIcon::smallSize() {\n return smallIconSize;\n}\n\nint YIcon::largeSize() {\n return largeIconSize;\n}\n\nint YIcon::hugeSize() {\n return hugeIconSize;\n}\n\nvoid YIcon::draw(Graphics &g, int x, int y, int size) {\n ref<YImage> image = getScaledIcon(size);\n if (image != null) {\n if (!doubleBuffer) {\n g.drawImage(image, x, y);\n } else {\n g.compositeImage(image, 0, 0, size, size, x, y);\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"get.h\"\n\nvoid tags(std::string location, std::string cover_folder, Library *library) {\n Local<Object> record = Nan::New<Object>();\n\n TagLib::FileRef f(location.c_str());\n TagLib::Tag *tag = f.tag();\n TagLib::AudioProperties *properties = f.audioProperties();\n\n TagLib::String title = tag->title();\n TagLib::String artist = tag->artist();\n TagLib::String album = tag->album();\n TagLib::String genre = tag->genre();\n\n \/\/ Set the default title based on the file's location\n \/\/ if there's no tags for the file.\n if (!title.length()) {\n std::string::size_type slash = location.rfind('\/');\n std::string::size_type dot = location.rfind('.');\n\n std::string default_title = location.substr(slash+1, dot - slash - 1);\n\n for (std::string::iterator it = default_title.begin(); it != default_title.end(); it++)\n title += *it;\n }\n\n record->Set(string(\"title\"), string(title.toCString(true)));\n record->Set(string(\"artist\"), string(artist.toCString(true)));\n record->Set(string(\"genre\"), string(genre.toCString(true)));\n record->Set(string(\"id\"), string(location));\n record->Set(string(\"track\"), Nan::New(tag->track()));\n record->Set(string(\"duration\"), Nan::New(properties->length()));\n\n if (cover_folder.length())\n extractPicture(location, cover_folder, title, album, artist, record);\n\n if (album.length())\n library->AddTrack(artist.toCString(true), album.toCString(true), record);\n else\n library->AddSingle(artist.toCString(true), record);\n}\n\nvoid inline extractPicture(std::string location, std::string cover_folder,\n TagLib::String title, TagLib::String album,\n TagLib::String artist, Local<Object> record) {\n std::string extension = location.substr(location.length() - 3, 3);\n\n if (extension == \"mp3\")\n mp3Picture(location, cover_folder, record);\n else if (extension == \"m4a\")\n mp4Picture(location, cover_folder, record);\n}\n\nvoid mp3Picture(std::string location, std::string cover_folder, Local<Object> record) {\n TagLib::MPEG::File mp3_file(location.c_str());\n TagLib::ID3v2::Tag *mp3_tag = mp3_file.ID3v2Tag(true);\n TagLib::ID3v2::FrameList pictures = mp3_tag->frameList(\"APIC\");\n\n if (pictures.isEmpty())\n return;\n\n TagLib::ID3v2::AttachedPictureFrame *picture_frame = static_cast<TagLib::ID3v2::AttachedPictureFrame *> (*pictures.begin());;\n\n unsigned int checksum = picture_frame->picture().checksum();\n\n std::stringstream path_stream;\n\n path_stream << cover_folder;\n path_stream << \"\/\";\n path_stream << checksum;\n\n std::string img_path = path_stream.str();\n\n if (picture_frame->mimeType() == \"image\/png\")\n img_path.append(\".png\");\n else\n img_path.append(\".jpg\");\n\n if (!exist(img_path)) {\n size_t image_size = picture_frame->picture().size();\n const char *data = picture_frame->picture().data();\n FILE *cover_file = fopen(img_path.c_str(), \"wb\");\n\n fwrite(data, image_size, 1, cover_file);\n fclose(cover_file);\n }\n\n record->Set(string(\"icon\"), string(img_path));\n}\n\nvoid mp4Picture(std::string location, std::string cover_folder, Local<Object> record) {\n TagLib::MP4::File mp4_file(location.c_str());\n TagLib::MP4::Tag *mp4_tag = mp4_file.tag();\n\n if (!mp4_tag->contains(\"covr\"))\n return;\n\n TagLib::MP4::CoverArtList covert_art_list = mp4_tag->item(\"covr\").toCoverArtList();\n\n if (covert_art_list.isEmpty())\n return;\n\n TagLib::MP4::CoverArt cover_art = covert_art_list[0];\n\n unsigned int checksum = cover_art.data().checksum();\n\n std::stringstream path_stream;\n\n path_stream << cover_folder;\n path_stream << \"\/\";\n path_stream << checksum;\n\n std::string img_path = path_stream.str();\n\n img_path.append(\".jpg\");\n\n if (!exist(img_path)) {\n size_t image_size = cover_art.data().size();\n const char *data = cover_art.data().data();\n FILE *cover_file = fopen(img_path.c_str(), \"wb\");\n\n fwrite(data, image_size, 1, cover_file);\n fclose(cover_file);\n }\n\n record->Set(string(\"icon\"), string(img_path));\n}\n<commit_msg>Remove an extra semi-colon<commit_after>#include \"get.h\"\n\nvoid tags(std::string location, std::string cover_folder, Library *library) {\n Local<Object> record = Nan::New<Object>();\n\n TagLib::FileRef f(location.c_str());\n TagLib::Tag *tag = f.tag();\n TagLib::AudioProperties *properties = f.audioProperties();\n\n TagLib::String title = tag->title();\n TagLib::String artist = tag->artist();\n TagLib::String album = tag->album();\n TagLib::String genre = tag->genre();\n\n \/\/ Set the default title based on the file's location\n \/\/ if there's no tags for the file.\n if (!title.length()) {\n std::string::size_type slash = location.rfind('\/');\n std::string::size_type dot = location.rfind('.');\n\n std::string default_title = location.substr(slash+1, dot - slash - 1);\n\n for (std::string::iterator it = default_title.begin(); it != default_title.end(); it++)\n title += *it;\n }\n\n record->Set(string(\"title\"), string(title.toCString(true)));\n record->Set(string(\"artist\"), string(artist.toCString(true)));\n record->Set(string(\"genre\"), string(genre.toCString(true)));\n record->Set(string(\"id\"), string(location));\n record->Set(string(\"track\"), Nan::New(tag->track()));\n record->Set(string(\"duration\"), Nan::New(properties->length()));\n\n if (cover_folder.length())\n extractPicture(location, cover_folder, title, album, artist, record);\n\n if (album.length())\n library->AddTrack(artist.toCString(true), album.toCString(true), record);\n else\n library->AddSingle(artist.toCString(true), record);\n}\n\nvoid inline extractPicture(std::string location, std::string cover_folder,\n TagLib::String title, TagLib::String album,\n TagLib::String artist, Local<Object> record) {\n std::string extension = location.substr(location.length() - 3, 3);\n\n if (extension == \"mp3\")\n mp3Picture(location, cover_folder, record);\n else if (extension == \"m4a\")\n mp4Picture(location, cover_folder, record);\n}\n\nvoid mp3Picture(std::string location, std::string cover_folder, Local<Object> record) {\n TagLib::MPEG::File mp3_file(location.c_str());\n TagLib::ID3v2::Tag *mp3_tag = mp3_file.ID3v2Tag(true);\n TagLib::ID3v2::FrameList pictures = mp3_tag->frameList(\"APIC\");\n\n if (pictures.isEmpty())\n return;\n\n TagLib::ID3v2::AttachedPictureFrame *picture_frame = static_cast<TagLib::ID3v2::AttachedPictureFrame *> (*pictures.begin());\n\n unsigned int checksum = picture_frame->picture().checksum();\n\n std::stringstream path_stream;\n\n path_stream << cover_folder;\n path_stream << \"\/\";\n path_stream << checksum;\n\n std::string img_path = path_stream.str();\n\n if (picture_frame->mimeType() == \"image\/png\")\n img_path.append(\".png\");\n else\n img_path.append(\".jpg\");\n\n if (!exist(img_path)) {\n size_t image_size = picture_frame->picture().size();\n const char *data = picture_frame->picture().data();\n FILE *cover_file = fopen(img_path.c_str(), \"wb\");\n\n fwrite(data, image_size, 1, cover_file);\n fclose(cover_file);\n }\n\n record->Set(string(\"icon\"), string(img_path));\n}\n\nvoid mp4Picture(std::string location, std::string cover_folder, Local<Object> record) {\n TagLib::MP4::File mp4_file(location.c_str());\n TagLib::MP4::Tag *mp4_tag = mp4_file.tag();\n\n if (!mp4_tag->contains(\"covr\"))\n return;\n\n TagLib::MP4::CoverArtList covert_art_list = mp4_tag->item(\"covr\").toCoverArtList();\n\n if (covert_art_list.isEmpty())\n return;\n\n TagLib::MP4::CoverArt cover_art = covert_art_list[0];\n\n unsigned int checksum = cover_art.data().checksum();\n\n std::stringstream path_stream;\n\n path_stream << cover_folder;\n path_stream << \"\/\";\n path_stream << checksum;\n\n std::string img_path = path_stream.str();\n\n img_path.append(\".jpg\");\n\n if (!exist(img_path)) {\n size_t image_size = cover_art.data().size();\n const char *data = cover_art.data().data();\n FILE *cover_file = fopen(img_path.c_str(), \"wb\");\n\n fwrite(data, image_size, 1, cover_file);\n fclose(cover_file);\n }\n\n record->Set(string(\"icon\"), string(img_path));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"context.h\"\n#include \"logging.h\"\n#include \"manager.h\"\n#include \"manageradaptor.h\"\n#include \"sconnect.h\"\n#include \"loggingfeatures.h\"\n\nusing namespace ContextProvider;\n\n\/*!\n \\class Context\n\n \\brief The main class used to provide context data.\n\n Typically, to provide some keys you would:\n\n \\code\n QStringList keys;\n keys.append(\"Some.Key1\");\n keys.append(\"Some.Key2\");\n\n Context::initService(QDBusConnection::SessionBus, \"org.test.somename\", keys);\n Context someKey1(\"Some.Key1\");\n Context someKey2(\"Some.Key2\");\n \/\/ Do something with someKey1, someKey2...\n \\endcode\n\n \\c Context::initService initializes a new bus connection with a specified service name\n and creates a Manager object on it. The clients obtain Subscriber objects through this\n Manager. \n\n For each service there is one Manager object.\n*\/\n\nQHash<QString, Manager*> Context::busesToManagers;\nQHash<QString, QDBusConnection*> Context::busesToConnections;\nQHash<QString, Manager*> Context::keysToManagers;\n\n\/\/\/ Constructor. This creates a new context property that should\n\/\/\/ be used to provide\/set values and get notified about subscribers appearing.\nContext::Context(const QString &k, QObject* parent)\n : QObject(parent), key(k)\n{\n contextDebug() << F_CONTEXT << \"Creating new Context for key:\" << key;\n\n manager = keysToManagers.value(key);\n if (manager == NULL) {\n contextCritical() << key << \"is currently not provided by any service\";\n return;\n }\n\n sconnect(manager, SIGNAL(firstSubscriberAppeared(const QString&)),\n this, SLOT(onManagerFirstSubscriberAppeared(const QString&)));\n\n sconnect(manager, SIGNAL(lastSubscriberDisappeared(const QString&)),\n this, SLOT(onManagerLastSubscriberDisappeared(const QString&)));\n}\n\n\/\/\/ Checks if a Context is valid (can be set\/get\/manipulated), prints an error message if not.\n\/\/\/ Returns true if the Context is valid. False otherwise. Helper for the Context::set \n\/\/\/ and Context::get familly of functions.\nbool Context::keyCheck() const\n{\n if (manager == NULL) {\n contextWarning() << \"Trying to manipulate an invalid key:\" << key;\n return false;\n } else\n return true;\n}\n\n\/\/\/ Returns true if the key is valid.\nbool Context::isValid() const\n{\n return (manager != NULL);\n}\n\n\/\/\/ Returns true if the key is set (it's value is determined).\nbool Context::isSet() const\n{\n if (! keyCheck())\n return false;\n \n return (manager->getKeyValue(key) != QVariant());\n}\n\n\/\/\/ Returns the name of the key this Context represents.\nQString Context::getKey() const\n{\n return key;\n}\n\n\/\/\/ Unsets the key value. The key value becomes undetermined.\nvoid Context::unset()\n{\n if (! keyCheck())\n return;\n\n manager->setKeyValue(key, QVariant());\n}\n\n \n\/\/\/ Sets the key value to QVariant \\a v.\nvoid Context::set(const QVariant &v)\n{\n if (! keyCheck())\n return;\n \n manager->setKeyValue(key, v);\n}\n\n\/\/\/ Returns the current value of the key. The returned QVariant is invalid \n\/\/\/ if the key value is undetermined or the Context is invalid.\nQVariant Context::get()\n{\n if (! keyCheck())\n return QVariant();\n \n return manager->getKeyValue(key);\n}\n\n\/\/\/ Called by Manager when first subscriber appears. Delegated if \n\/\/\/ this concerns us.\nvoid Context::onManagerFirstSubscriberAppeared(const QString &key)\n{\n if (key == this->key) {\n contextDebug() << F_SIGNALS << F_CONTEXT << \"First subscriber appeared for key:\" << key;\n emit firstSubscriberAppeared(key);\n }\n}\n\n\/\/\/ Called by Manager when last subscriber disappears. Delegate if\n\/\/\/ this concerns us.\nvoid Context::onManagerLastSubscriberDisappeared(const QString &key)\n{\n if (key == this->key) {\n contextDebug() << F_SIGNALS << F_CONTEXT << \"Last subscriber disappeared for key:\" << key;\n emit lastSubscriberDisappeared(key);\n }\n}\n\n\/\/\/ Destructor.\nContext::~Context()\n{\n contextDebug() << F_CONTEXT << F_DESTROY << \"Destroying Context for key:\" << key;\n}\n\n\/\/\/ Initialize a new service on a bus \\a busType with service name \\a busName and a given\n\/\/\/ set of \\a keys. This is the main method used to setup\/bootstrap the keys that \n\/\/\/ we want to provide. \n\/\/\/ Returns true if service was registered, false otherwise.\nbool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys)\n{\n contextDebug() << F_CONTEXT << \"Initializing service for bus:\" << busName;\n\n \/\/ Basic sanity check\n if (busesToManagers.contains(busName)) {\n contextCritical() << busName << \"service is already registered\";\n return false;\n }\n \n QDBusConnection *connection = new QDBusConnection(QDBusConnection::connectToBus(busType, busName));\n\n Manager *manager = new Manager(keys);\n ManagerAdaptor *managerAdaptor = new ManagerAdaptor(manager, connection);\n\n \/\/ Register service\n if (! connection->registerService(busName)) {\n contextCritical() << \"Failed to register service with name\" << busName;\n return false;\n }\n\n \/\/ Register object\n if (managerAdaptor && !connection->registerObject(\"\/org\/freedesktop\/ContextKit\/Manager\", manager)) {\n contextCritical() << \"Failed to register the Manager object for\" << busName;\n return false;\n }\n\n busesToManagers.insert(busName, manager);\n busesToConnections.insert(busName, connection);\n\n \/\/ Add a mapping for all the keys -> manager\n foreach(QString key, keys) {\n if (keysToManagers.contains(key)) {\n contextCritical() << key << \"is already provided by another manager\/service!\";\n return false;\n } else {\n keysToManagers.insert(key, manager);\n }\n }\n\n return true;\n}\n\n\/\/\/ Stops the previously started (with initService) service with the given \\a busName.\nvoid Context::stopService(const QString &busName)\n{\n contextDebug() << F_CONTEXT << \"Stopping service for bus:\" << busName;\n\n \/\/ Basic sanity check\n if (! busesToManagers.contains(busName)) {\n contextCritical() << busName << \"service is not started!\";\n return;\n }\n\n \/\/ The manager...\n Manager *manager = busesToManagers.value(busName);\n\n \/\/ Remove all key mappings\n foreach(QString key, QStringList(manager->getKeys())) {\n keysToManagers.remove(key);\n }\n\n \/\/ The connection...\n QDBusConnection *connection = busesToConnections.value(busName);\n\n \/\/ Unregister\n connection->unregisterObject(\"\/org\/freedesktop\/ContextKit\/Manager\");\n connection->unregisterService(busName);\n\n \/\/ Remove the remaining mappings\n busesToManagers.remove(busName);\n busesToConnections.remove(busName);\n\n \/\/ Dealloc\n delete manager;\n delete connection;\n}\n\n<commit_msg>Updating the documentation about Context objects.<commit_after>\/*\n * Copyright (C) 2008, 2009 Nokia Corporation.\n *\n * Contact: Marius Vollmer <marius.vollmer@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include \"context.h\"\n#include \"logging.h\"\n#include \"manager.h\"\n#include \"manageradaptor.h\"\n#include \"sconnect.h\"\n#include \"loggingfeatures.h\"\n\nusing namespace ContextProvider;\n\n\/*!\n \\class Context\n\n \\brief The main class used to provide context data.\n\n Typically, to provide some keys you would:\n\n \\code\n QStringList keys;\n keys.append(\"Some.Key1\");\n keys.append(\"Some.Key2\");\n\n Context::initService(QDBusConnection::SessionBus, \"org.test.somename\", keys);\n Context someKey1(\"Some.Key1\");\n Context someKey2(\"Some.Key2\");\n \/\/ Do something with someKey1, someKey2...\n \\endcode\n\n \\c Context::initService initializes a new bus connection with a specified service name\n and creates a Manager object on it. The clients obtain Subscriber objects through this\n Manager. \n\n The Context objects are proxy interfaces to actual keys. It's recommended that you create\n Context objects to represent keys and keep them around in your class\/object. Remember that\n once the Context object is destroyed, it will not fire the proper signals about\n subscription status changing. \n\n For each service there is one Manager object.\n*\/\n\nQHash<QString, Manager*> Context::busesToManagers;\nQHash<QString, QDBusConnection*> Context::busesToConnections;\nQHash<QString, Manager*> Context::keysToManagers;\n\n\/\/\/ Constructor. This creates a new context property that should\n\/\/\/ be used to provide\/set values and get notified about subscribers appearing.\nContext::Context(const QString &k, QObject* parent)\n : QObject(parent), key(k)\n{\n contextDebug() << F_CONTEXT << \"Creating new Context for key:\" << key;\n\n manager = keysToManagers.value(key);\n if (manager == NULL) {\n contextCritical() << key << \"is currently not provided by any service\";\n return;\n }\n\n sconnect(manager, SIGNAL(firstSubscriberAppeared(const QString&)),\n this, SLOT(onManagerFirstSubscriberAppeared(const QString&)));\n\n sconnect(manager, SIGNAL(lastSubscriberDisappeared(const QString&)),\n this, SLOT(onManagerLastSubscriberDisappeared(const QString&)));\n}\n\n\/\/\/ Checks if a Context is valid (can be set\/get\/manipulated), prints an error message if not.\n\/\/\/ Returns true if the Context is valid. False otherwise. Helper for the Context::set \n\/\/\/ and Context::get familly of functions.\nbool Context::keyCheck() const\n{\n if (manager == NULL) {\n contextWarning() << \"Trying to manipulate an invalid key:\" << key;\n return false;\n } else\n return true;\n}\n\n\/\/\/ Returns true if the key is valid.\nbool Context::isValid() const\n{\n return (manager != NULL);\n}\n\n\/\/\/ Returns true if the key is set (it's value is determined).\nbool Context::isSet() const\n{\n if (! keyCheck())\n return false;\n \n return (manager->getKeyValue(key) != QVariant());\n}\n\n\/\/\/ Returns the name of the key this Context represents.\nQString Context::getKey() const\n{\n return key;\n}\n\n\/\/\/ Unsets the key value. The key value becomes undetermined.\nvoid Context::unset()\n{\n if (! keyCheck())\n return;\n\n manager->setKeyValue(key, QVariant());\n}\n\n \n\/\/\/ Sets the key value to QVariant \\a v.\nvoid Context::set(const QVariant &v)\n{\n if (! keyCheck())\n return;\n \n manager->setKeyValue(key, v);\n}\n\n\/\/\/ Returns the current value of the key. The returned QVariant is invalid \n\/\/\/ if the key value is undetermined or the Context is invalid.\nQVariant Context::get()\n{\n if (! keyCheck())\n return QVariant();\n \n return manager->getKeyValue(key);\n}\n\n\/\/\/ Called by Manager when first subscriber appears. Delegated if \n\/\/\/ this concerns us.\nvoid Context::onManagerFirstSubscriberAppeared(const QString &key)\n{\n if (key == this->key) {\n contextDebug() << F_SIGNALS << F_CONTEXT << \"First subscriber appeared for key:\" << key;\n emit firstSubscriberAppeared(key);\n }\n}\n\n\/\/\/ Called by Manager when last subscriber disappears. Delegate if\n\/\/\/ this concerns us.\nvoid Context::onManagerLastSubscriberDisappeared(const QString &key)\n{\n if (key == this->key) {\n contextDebug() << F_SIGNALS << F_CONTEXT << \"Last subscriber disappeared for key:\" << key;\n emit lastSubscriberDisappeared(key);\n }\n}\n\n\/\/\/ Destructor.\nContext::~Context()\n{\n contextDebug() << F_CONTEXT << F_DESTROY << \"Destroying Context for key:\" << key;\n}\n\n\/\/\/ Initialize a new service on a bus \\a busType with service name \\a busName and a given\n\/\/\/ set of \\a keys. This is the main method used to setup\/bootstrap the keys that \n\/\/\/ we want to provide. \n\/\/\/ Returns true if service was registered, false otherwise.\nbool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys)\n{\n contextDebug() << F_CONTEXT << \"Initializing service for bus:\" << busName;\n\n \/\/ Basic sanity check\n if (busesToManagers.contains(busName)) {\n contextCritical() << busName << \"service is already registered\";\n return false;\n }\n \n QDBusConnection *connection = new QDBusConnection(QDBusConnection::connectToBus(busType, busName));\n\n Manager *manager = new Manager(keys);\n ManagerAdaptor *managerAdaptor = new ManagerAdaptor(manager, connection);\n\n \/\/ Register service\n if (! connection->registerService(busName)) {\n contextCritical() << \"Failed to register service with name\" << busName;\n return false;\n }\n\n \/\/ Register object\n if (managerAdaptor && !connection->registerObject(\"\/org\/freedesktop\/ContextKit\/Manager\", manager)) {\n contextCritical() << \"Failed to register the Manager object for\" << busName;\n return false;\n }\n\n busesToManagers.insert(busName, manager);\n busesToConnections.insert(busName, connection);\n\n \/\/ Add a mapping for all the keys -> manager\n foreach(QString key, keys) {\n if (keysToManagers.contains(key)) {\n contextCritical() << key << \"is already provided by another manager\/service!\";\n return false;\n } else {\n keysToManagers.insert(key, manager);\n }\n }\n\n return true;\n}\n\n\/\/\/ Stops the previously started (with initService) service with the given \\a busName.\nvoid Context::stopService(const QString &busName)\n{\n contextDebug() << F_CONTEXT << \"Stopping service for bus:\" << busName;\n\n \/\/ Basic sanity check\n if (! busesToManagers.contains(busName)) {\n contextCritical() << busName << \"service is not started!\";\n return;\n }\n\n \/\/ The manager...\n Manager *manager = busesToManagers.value(busName);\n\n \/\/ Remove all key mappings\n foreach(QString key, QStringList(manager->getKeys())) {\n keysToManagers.remove(key);\n }\n\n \/\/ The connection...\n QDBusConnection *connection = busesToConnections.value(busName);\n\n \/\/ Unregister\n connection->unregisterObject(\"\/org\/freedesktop\/ContextKit\/Manager\");\n connection->unregisterService(busName);\n\n \/\/ Remove the remaining mappings\n busesToManagers.remove(busName);\n busesToConnections.remove(busName);\n\n \/\/ Dealloc\n delete manager;\n delete connection;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"flag.h\"\n\n#include <cassert>\n#include <limits>\n#include <sstream>\n\nusing namespace dariadb::compression::v2;\n\nFlagCompressor::FlagCompressor(const ByteBuffer_Ptr &bw_)\n : BaseCompressor(bw_){\n\t_is_first = true;\n}\n\nbool FlagCompressor::append(dariadb::Flag v) {\n\tstatic_assert(sizeof(dariadb::Flag) == 4, \"Flag no x32 value\");\n\tif (_is_first) {\n\t\t_first = v;\n\t\t_is_first = false;\n\t\treturn true;\n\t}\n\t\/\/TODO calc size before write for better space usage.\n\tif (bw->free_size() < 8) {\n\t\treturn false;\n\t}\n\t\/\/ LEB128\n\tauto x = v;\n\tdo {\n\t\t\n\t\tauto sub_res = x & 0x7fU;\n\t\tif (x >>= 7)\n\t\t\tsub_res |= 0x80U;\n\t\tbw->write<uint8_t>(sub_res);\n\t} while (x);\n\n\treturn true;\n}\n\n\nFlagDeCompressor::FlagDeCompressor(const ByteBuffer_Ptr &bw_, dariadb::Flag first):BaseCompressor(bw_)\n{\n\t_first = first;\n\t_is_first = true;;\n}\n\ndariadb::Flag FlagDeCompressor::read() {\n static_assert(sizeof(dariadb::Flag) == 4, \"Flag no x32 value\");\n \/* if (_is_first) {\n\t _is_first = false;\n\t return _first;\n }*\/\n dariadb::Flag result(0);\n \n size_t bytes = 0;\n while (true) {\n\t auto readed = bw->read<uint8_t>();\n\t result |= (readed & 0x7fULL) << (7 * bytes++);\n\t if (!(readed & 0x80U))\n\t\t break;\n }\n return result;\n}\n<commit_msg>leb128 refact.<commit_after>#include \"flag.h\"\n\n#include <cassert>\n#include <limits>\n#include <sstream>\n\nusing namespace dariadb::compression::v2;\n\nFlagCompressor::FlagCompressor(const ByteBuffer_Ptr &bw_)\n : BaseCompressor(bw_) {\n _is_first = true;\n}\n\nbool FlagCompressor::append(dariadb::Flag v) {\n static_assert(sizeof(dariadb::Flag) == 4, \"Flag no x32 value\");\n if (_is_first) {\n _first = v;\n _is_first = false;\n return true;\n }\n\n \/\/ LEB128\n auto x = v;\n do {\n if (bw->free_size() < 1) {\n return false;\n }\n auto sub_res = x & 0x7fU;\n if (x >>= 7)\n sub_res |= 0x80U;\n bw->write<uint8_t>(sub_res);\n } while (x);\n\n return true;\n}\n\nFlagDeCompressor::FlagDeCompressor(const ByteBuffer_Ptr &bw_,\n dariadb::Flag first)\n : BaseCompressor(bw_) {\n _first = first;\n _is_first = true;\n ;\n}\n\ndariadb::Flag FlagDeCompressor::read() {\n static_assert(sizeof(dariadb::Flag) == 4, \"Flag no x32 value\");\n dariadb::Flag result(0);\n\n size_t bytes = 0;\n while (true) {\n auto readed = bw->read<uint8_t>();\n result |= (readed & 0x7fULL) << (7 * bytes++);\n if (!(readed & 0x80U))\n break;\n }\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Author(s):\n** - Laurent LEC <llec@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <iostream>\n#include <iomanip>\n#include <istream>\n#include <sstream>\n\n#include <qitype\/genericobject.hpp>\n#include <qi\/future.hpp>\n#include <qimessaging\/session.hpp>\n\nqi::Session session;\nstd::map<const std::string, qi::ObjectPtr> services;\n\ntypedef std::vector<std::string> command;\n\nstatic int calcOffsetMethod(const qi::MetaObject::MethodMap &mmaps) {\n qi::MetaObject::MethodMap::const_iterator it;\n int max = 0;\n for (it = mmaps.begin(); it != mmaps.end(); ++it) {\n int cur = it->second.sigreturn().size();\n if (cur > max)\n max = cur;\n }\n return max;\n}\n\n\/****************\n* SERVICE *\n****************\/\nstatic void cmd_service(const command &cmd,\n command::const_iterator &it)\n{\n if (it == cmd.end())\n {\n std::cerr << \"service: not enough parameters\" << std::endl;\n return;\n }\n\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n if (servs[i].name() != *it)\n continue;\n std::cout << servs[i].name() << std::endl\n << \" id: \" << servs[i].serviceId() << std::endl\n << \" machine: \" << servs[i].machineId() << std::endl\n << \" process: \" << servs[i].processId() << std::endl\n << \" endpoints:\" << std::endl;\n for (std::vector<std::string>::const_iterator it2 = servs[i].endpoints().begin();\n it2 != servs[i].endpoints().end();\n ++it2)\n {\n std::cout << \" \" << *it2 << std::endl;\n }\n\n std::cout << \" methods:\" << std::endl;\n qi::Future<qi::ObjectPtr> fut = session.service(*it);\n if (fut.hasError()) {\n std::cerr << \"service: could not get object: \" << fut.error() << std::endl;\n continue;\n }\n\n qi::ObjectPtr obj = fut.value();\n services[*it] = obj;\n\n const qi::MetaObject &mobj = obj->metaObject();\n qi::MetaObject::MethodMap methods = mobj.methodMap();\n int offset = calcOffsetMethod(methods);\n qi::MetaObject::MethodMap::const_iterator it2;\n for (it2 = methods.begin(); it2 != methods.end(); ++it2) {\n std::cout << \" \" << std::right << std::setfill('0') << std::setw(3) << it2->second.uid() << std::setw(0) << \" \"\n << std::left << std::setfill(' ') << std::setw(offset) << it2->second.sigreturn() << std::setw(0)\n << \" \" << it2->second.signature() << std::endl;\n }\n std::cout << \" events:\" << std::endl;\n qi::MetaObject::SignalMap events = mobj.signalMap();\n qi::MetaObject::SignalMap::const_iterator it3;\n for (it3 = events.begin(); it3 != events.end(); ++it3) {\n std::cout << \" \" << std::right << std::setfill('0') << std::setw(3) << it3->second.uid() << std::setw(0) << \" \"\n << std::left << std::setfill(' ') << std::setw(offset) << \"\" << std::setw(0)\n << \" \" << it3->second.signature() << std::endl;\n }\n }\n}\n\n\/****************\n* SERVICES *\n****************\/\nstatic void cmd_services(const command &cmd,\n command::const_iterator &QI_UNUSED(it))\n{\n bool enum_all = false;\n if (std::find(cmd.begin(), cmd.end(), \"-v\") != cmd.end())\n enum_all = true;\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n std::cout << \"[\" << servs[i].serviceId() << \"] \"\n << servs[i].name() << std::endl;\n if (enum_all) {\n command ncmd;\n command::const_iterator it;\n\n ncmd.push_back(servs[i].name());\n it = ncmd.begin();\n cmd_service(ncmd, it);\n std::cout << std::endl;\n }\n }\n}\n\n\/****************\n* SESSION *\n****************\/\nstatic void cmd_session(const command &cmd,\n command::const_iterator &it)\n{\n if (it == cmd.end())\n {\n std::cerr << \"session: not enough parameters\" << std::endl;\n return;\n }\n\n if (*it == \"connect\")\n {\n ++it;\n if (it == cmd.end())\n {\n std::cerr << \"session connect: not enough parameters\" << std::endl;\n return;\n }\n else\n {\n session.connect(*it);\n }\n }\n else if (*it == \"services\")\n {\n ++it;\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n std::cout << \"[\" << servs[i].serviceId() << \"] \"\n << servs[i].name() << std::endl;\n }\n }\n else\n {\n std::cerr << \"unexpected token: \" << *it << std::endl;\n }\n}\n\nstatic void execute(const command &cmd)\n{\n command::const_iterator it = cmd.begin();\n\n if (it == cmd.end())\n {\n return;\n }\n\n if (*it == \"session\")\n {\n cmd_session(cmd, ++it);\n }\n else if (*it == \"service\")\n {\n cmd_service(cmd, ++it);\n }\n else if (*it == \"services\")\n {\n cmd_services(cmd, ++it);\n }\n else\n {\n std::cerr << \"unexpected token: \" << *it << std::endl;\n }\n}\n\nstatic void from_stdin()\n{\n char line[8192];\n\n std::cout << \"% \";\n while (std::cin.getline(line, sizeof(line)))\n {\n std::stringstream ssin(line, std::stringstream::in);\n command cmd;\n std::string input;\n\n while (ssin >> input)\n {\n cmd.push_back(input);\n }\n\n execute(cmd);\n\n std::cout << \"% \";\n }\n}\n\nstatic void from_argv(int argc,\n char *argv[])\n{\n command cmd;\n\n session.connect(argv[1]);\n\n for (int i = 2;\n i < argc;\n ++i)\n {\n cmd.push_back(argv[i]);\n }\n\n execute(cmd);\n}\n\nstatic void usage(char *argv0)\n{\n std::cout << \"Usage: \" << argv0 << \" [ADDRESS CMD]\" << std::endl;\n std::cout << \" connect ADDRESS\" << std::endl\n << \" services [-v]\" << std::endl\n << \" service SERVICE\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n if (argc == 2 &&\n (strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0))\n {\n usage(argv[0]);\n return (0);\n }\n\n if (argc == 1)\n {\n from_stdin();\n }\n else\n {\n from_argv(argc, argv);\n }\n\n session.close();\n return (0);\n}\n<commit_msg>qicli: use qi::details::printMetaObject<commit_after>\/*\n** Author(s):\n** - Laurent LEC <llec@aldebaran-robotics.com>\n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include <iostream>\n#include <iomanip>\n#include <istream>\n#include <sstream>\n\n#include <qitype\/genericobject.hpp>\n#include <qi\/future.hpp>\n#include <qimessaging\/session.hpp>\n\nqi::Session session;\nstd::map<const std::string, qi::ObjectPtr> services;\n\ntypedef std::vector<std::string> command;\n\nstatic int calcOffsetMethod(const qi::MetaObject::MethodMap &mmaps) {\n qi::MetaObject::MethodMap::const_iterator it;\n int max = 0;\n for (it = mmaps.begin(); it != mmaps.end(); ++it) {\n int cur = it->second.sigreturn().size();\n if (cur > max)\n max = cur;\n }\n return max;\n}\n\n\/****************\n* SERVICE *\n****************\/\nstatic void cmd_service(const command &cmd,\n command::const_iterator &it)\n{\n if (it == cmd.end())\n {\n std::cerr << \"service: not enough parameters\" << std::endl;\n return;\n }\n\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n if (servs[i].name() != *it)\n continue;\n std::cout << servs[i].name() << std::endl\n << \" id: \" << servs[i].serviceId() << std::endl\n << \" machine: \" << servs[i].machineId() << std::endl\n << \" process: \" << servs[i].processId() << std::endl\n << \" endpoints:\" << std::endl;\n for (std::vector<std::string>::const_iterator it2 = servs[i].endpoints().begin();\n it2 != servs[i].endpoints().end();\n ++it2)\n {\n std::cout << \" \" << *it2 << std::endl;\n }\n\n qi::Future<qi::ObjectPtr> fut = session.service(*it);\n if (fut.hasError()) {\n std::cerr << \"service: could not get object: \" << fut.error() << std::endl;\n continue;\n }\n\n qi::ObjectPtr obj = fut.value();\n services[*it] = obj;\n\n qi::details::printMetaObject(std::cout, obj->metaObject());\n }\n}\n\n\/****************\n* SERVICES *\n****************\/\nstatic void cmd_services(const command &cmd,\n command::const_iterator &QI_UNUSED(it))\n{\n bool enum_all = false;\n if (std::find(cmd.begin(), cmd.end(), \"-v\") != cmd.end())\n enum_all = true;\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n if (enum_all) {\n command ncmd;\n command::const_iterator it;\n\n ncmd.push_back(servs[i].name());\n it = ncmd.begin();\n cmd_service(ncmd, it);\n std::cout << std::endl;\n continue;\n }\n std::cout << \"[\" << servs[i].serviceId() << \"] \"\n << servs[i].name() << std::endl;\n\n }\n}\n\n\/****************\n* SESSION *\n****************\/\nstatic void cmd_session(const command &cmd,\n command::const_iterator &it)\n{\n if (it == cmd.end())\n {\n std::cerr << \"session: not enough parameters\" << std::endl;\n return;\n }\n\n if (*it == \"connect\")\n {\n ++it;\n if (it == cmd.end())\n {\n std::cerr << \"session connect: not enough parameters\" << std::endl;\n return;\n }\n else\n {\n session.connect(*it);\n }\n }\n else if (*it == \"services\")\n {\n ++it;\n std::vector<qi::ServiceInfo> servs = session.services();\n for (unsigned int i = 0; i < servs.size(); ++i)\n {\n std::cout << \"[\" << servs[i].serviceId() << \"] \"\n << servs[i].name() << std::endl;\n }\n }\n else\n {\n std::cerr << \"unexpected token: \" << *it << std::endl;\n }\n}\n\nstatic void execute(const command &cmd)\n{\n command::const_iterator it = cmd.begin();\n\n if (it == cmd.end())\n {\n return;\n }\n\n if (*it == \"session\")\n {\n cmd_session(cmd, ++it);\n }\n else if (*it == \"service\")\n {\n cmd_service(cmd, ++it);\n }\n else if (*it == \"services\")\n {\n cmd_services(cmd, ++it);\n }\n else\n {\n std::cerr << \"unexpected token: \" << *it << std::endl;\n }\n}\n\nstatic void from_stdin()\n{\n char line[8192];\n\n std::cout << \"% \";\n while (std::cin.getline(line, sizeof(line)))\n {\n std::stringstream ssin(line, std::stringstream::in);\n command cmd;\n std::string input;\n\n while (ssin >> input)\n {\n cmd.push_back(input);\n }\n\n execute(cmd);\n\n std::cout << \"% \";\n }\n}\n\nstatic void from_argv(int argc,\n char *argv[])\n{\n command cmd;\n\n session.connect(argv[1]);\n\n for (int i = 2;\n i < argc;\n ++i)\n {\n cmd.push_back(argv[i]);\n }\n\n execute(cmd);\n}\n\nstatic void usage(char *argv0)\n{\n std::cout << \"Usage: \" << argv0 << \" [ADDRESS CMD]\" << std::endl;\n std::cout << \" connect ADDRESS\" << std::endl\n << \" services [-v]\" << std::endl\n << \" service SERVICE\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n if (argc == 2 &&\n (strcmp(argv[1], \"-h\") == 0 || strcmp(argv[1], \"--help\") == 0))\n {\n usage(argv[0]);\n return (0);\n }\n\n if (argc == 1)\n {\n from_stdin();\n }\n else\n {\n from_argv(argc, argv);\n }\n\n session.close();\n return (0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- PDB.cpp ------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Driver.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include <memory>\n\nusing namespace llvm;\n\nconst int PageSize = 4096;\nconst uint8_t Magic[32] = \"Microsoft C\/C++ MSF 7.00\\r\\n\\032DS\\0\\0\";\n\nvoid lld::coff::createPDB(StringRef Path) {\n \/\/ Create a file.\n size_t FileSize = PageSize * 3;\n ErrorOr<std::unique_ptr<FileOutputBuffer>> BufOrErr =\n FileOutputBuffer::create(Path, FileSize);\n error(BufOrErr, Twine(\"failed to open \") + Path);\n std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufOrErr);\n\n \/\/ Write the file magic.\n uint8_t *P = Buf->getBufferStart();\n memcpy(P, Magic, sizeof(Magic));\n}\n<commit_msg>COFF: Create an empty but valid PDF file.<commit_after>\/\/===- PDB.cpp ------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Driver.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include <memory>\n\nusing namespace llvm;\nusing namespace llvm::support;\nusing namespace llvm::support::endian;\n\nconst int PageSize = 4096;\nconst uint8_t Magic[32] = \"Microsoft C\/C++ MSF 7.00\\r\\n\\032DS\\0\\0\";\n\nnamespace {\nstruct PDBHeader {\n uint8_t Magic[32];\n ulittle32_t PageSize;\n ulittle32_t FpmPage;\n ulittle32_t PageCount;\n ulittle32_t RootSize;\n ulittle32_t Reserved;\n ulittle32_t RootPointer;\n};\n}\n\nvoid lld::coff::createPDB(StringRef Path) {\n \/\/ Create a file.\n size_t FileSize = PageSize * 3;\n ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =\n FileOutputBuffer::create(Path, FileSize);\n error(BufferOrErr, Twine(\"failed to open \") + Path);\n std::unique_ptr<FileOutputBuffer> Buffer = std::move(*BufferOrErr);\n\n \/\/ Write the file header.\n uint8_t *Buf = Buffer->getBufferStart();\n auto *Hdr = reinterpret_cast<PDBHeader *>(Buf);\n memcpy(Hdr->Magic, Magic, sizeof(Magic));\n Hdr->PageSize = PageSize;\n \/\/ I don't know what FpmPage field means, but it must not be 0.\n Hdr->FpmPage = 1;\n Hdr->PageCount = FileSize \/ PageSize;\n \/\/ Root directory is empty, containing only the length field.\n Hdr->RootSize = 4;\n \/\/ Root directory is on page 1.\n Hdr->RootPointer = 1;\n\n \/\/ Write the root directory. Root stream is on page 2.\n write32le(Buf + PageSize, 2);\n Buffer->commit();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstring>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <errno.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/param.h>\n#include <stdlib.h>\n#include <cstdlib>\n\nusing namespace std;\n\nvoid stringParse(string usrinput, vector<string> &vec)\n{\n\tchar *cstr = new char[usrinput.size()+1];\n\tstrcpy(cstr,usrinput.c_str());\n\tchar *pch = strtok(cstr, \" \");\n\twhile(pch != NULL)\n\t{\n\t\tvec.push_back(pch);\n\t\tpch = strtok(NULL, \" \");\n\t}\n}\n\nvoid executeCommands(const char *path, char** in, bool ampersand)\n{\n\tint pid;\n\tif((pid = fork()) == -1)\n\t\tperror(\"fork failed\");\n\tif(pid == 0)\n\t{\n\t\tif(-1 == execv(path, in))\n\t\t\tperror(\"exevp failed\");\n\t}\n\tif(!ampersand)\n\t{\n\t\tif(wait(0) == -1)\n\t\t\tperror(\"wait failed\");\n\t}\n}\n\nvoid parsepath(char *path, vector<string> &p)\n{\n\tstring parsedpath;\n\tint i;\n\tfor(i = 0; path[i] != '\\0'; ++i)\n\t{\n\t\tif(path[i] == ':')\n\t\t{\n\t\t\tp.push_back(parsedpath);\n\t\t\tparsedpath = \"\";\n\t\t}\n\t\telse\n\t\t\tparsedpath += path[i];\n\t\t\n\t}\n\tparsedpath += path[i];\n\tp.push_back(parsedpath);\n\t\t\n}\n\nvoid changec(int i)\n{\n\tsignal(SIGINT,SIG_IGN);\n\tcout << endl;\n}\n\nint main()\n{\n\tstring input;\n\tbool amper = false;\n\tvector<string> strvec;\n\tvector<string> pathvec;\n\tvector<string> concatpath;\n\tchar *temp = getenv(\"PATH\");\n\tif(temp == NULL)\n\t\tperror(\"no path\");\n\/\/\tchar *temp2;\n\/\/\tchar *temp3;\n\tchar *concatstrpath;\n\tstring concatstrpath2;\n\tstring correctpath;\n\tint openInt = 0;\n\tstring cd = \"cd\";\n\n\twhile(1)\n\t{\n\t\tcout << \"$ \";\n\t\tgetline(cin, input);\n\t\tif(SIG_ERR == signal(SIGINT,changec))\n\t\t\tperror(\"signal failed\");\n\t\tif(input == \"exit\")\n\t\t\tbreak;\n\t\tstringParse(input, strvec);\n\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t{\n\t\t\tif(strvec.at(i) == \"&\")\n\t\t\t\tamper = true;\n\t\t\tif(strvec.at(i) == \"#\")\n\t\t\t\tstrvec.erase(strvec.begin()+i,strvec.end());\n\n\t\t}\n\n\t\tchar **usrIn = new char *[strvec.size()+1];\n\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t{\n\t\t\tusrIn[i] = new char[strvec.at(i).size()+1];\n\t\t\tstrcpy(usrIn[i], strvec.at(i).c_str());\n\t\t}\n\t\tusrIn[strvec.size()] = '\\0';\n\t\tif(strcmp(usrIn[0],cd.c_str()) == 0)\n\t\t{\n\t\t\tchar *abpath = new char[1024];\n\t\t\tif(usrIn[1] != NULL)\n\t\t\t{\n\t\t\t\tif(getcwd(abpath,1024) == NULL)\n\t\t\t\t\tperror(\"getcwd failed\");\n\t\t\t\tstrcat(abpath,\"\/\");\n\t\t\t\tstrcat(abpath,usrIn[1]);\n\t\t\t\tcout << abpath << endl;\n\t\t\t\tif(chdir(abpath) == -1)\n\t\t\t\t\tperror(\"directory change failed\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar *home = getenv(\"HOME\");\n\t\t\t\tif(home == NULL)\n\t\t\t\t\tperror(\"getenv failed\");\n\/\/\t\t\t\tcout << home << endl;\n\t\t\t\tif(chdir(home) == -1)\n\t\t\t\t\tperror(\"directory change failed\");\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\n\t\t\tparsepath(temp,pathvec);\n\n\t\t\tfor(unsigned int i = 0; i < pathvec.size(); ++i)\n\t\t\t{\n\t\t\t\tchar buf[1024];\n\t\t\t\tstrcpy(buf,pathvec.at(i).c_str());\n\t\t\t\tbuf[pathvec.at(i).size()+1] = '\\0';\n\t\t\t\tconcatstrpath = strncat(buf,\"\/\",1024);\n\t\t\t\tconcatstrpath2 = strncat(concatstrpath, usrIn[0],1024);\n\t\t\t\tconcatpath.push_back(concatstrpath2);\t\n\t\t\t\n\n\t\t\t\tif((openInt = open(concatpath.at(i).c_str(), O_RDONLY)) != -1)\n\t\t\t\t{\n\t\t\t\t\tcorrectpath = concatpath.at(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(openInt == -1)\n\t\t\t\tperror(\"open failed\");\n\t\t\tchar **fin = new char *[1024];\t\t\n\t\t\tunsigned int j;\n\t\t\tfor(j = 0; usrIn[j] != '\\0'; ++j)\n\t\t\t{\n\t\t\t\tfin[j] = new char[1024];\n\t\t\t\tstrcpy(fin[j],usrIn[j]);\n\t\t\t}\n\t\t\tfin[j] = '\\0';\n\t\t\texecuteCommands(correctpath.c_str(), fin, amper);\n\t\t\tdelete [] fin;\n\t\t}\n\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t\tdelete usrIn[i];\n\t\tstrvec.clear();\n\t\tdelete [] usrIn;\n\t\tinput = \"\";\n\t\tcorrectpath = \"\";\n\t\tpathvec.clear();\n\t\tconcatpath.clear();\n\t}\n\t\t\n}\n<commit_msg>everything works<commit_after>#include <cstring>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <errno.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/param.h>\n#include <stdlib.h>\n#include <cstdlib>\n\nusing namespace std;\n\nvoid stringParse(string usrinput, vector<string> &vec)\n{\n\tchar *cstr = new char[usrinput.size()+1];\n\tstrcpy(cstr,usrinput.c_str());\n\tchar *pch = strtok(cstr, \" \");\n\twhile(pch != NULL)\n\t{\n\t\tvec.push_back(pch);\n\t\tpch = strtok(NULL, \" \");\n\t}\n}\n\nvoid executeCommands(const char *path, char** in, bool ampersand)\n{\n\tint pid;\n\tif((pid = fork()) == -1)\n\t\tperror(\"fork failed\");\n\tif(pid == 0)\n\t{\n\t\tif(-1 == execv(path, in))\n\t\t\tperror(\"exevp failed\");\n\t}\n\tif(!ampersand)\n\t{\n\t\tif(wait(0) == -1)\n\t\t\tperror(\"wait failed\");\n\t}\n}\n\nvoid parsepath(char *path, vector<string> &p)\n{\n\tstring parsedpath;\n\tint i;\n\tfor(i = 0; path[i] != '\\0'; ++i)\n\t{\n\t\tif(path[i] == ':')\n\t\t{\n\t\t\tp.push_back(parsedpath);\n\t\t\tparsedpath = \"\";\n\t\t}\n\t\telse\n\t\t\tparsedpath += path[i];\n\t\t\n\t}\n\tparsedpath += path[i];\n\tp.push_back(parsedpath);\n\t\t\n}\n\nvoid changec(int i)\n{\n\tsignal(SIGINT,SIG_IGN);\n\tcout << endl;\n}\n\nint main()\n{\n\tstring input;\n\tbool amper = false;\n\tvector<string> strvec;\n\tvector<string> pathvec;\n\tvector<string> concatpath;\n\tchar *temp = getenv(\"PATH\");\n\tif(temp == NULL)\n\t\tperror(\"no path\");\n\/\/\tchar *temp2;\n\/\/\tchar *temp3;\n\tchar *concatstrpath;\n\tstring concatstrpath2;\n\tstring correctpath;\n\tint openInt = 0;\n\tstring cd = \"cd\";\n\n\twhile(1)\n\t{\n\t\tcout << \"$ \";\n\t\tgetline(cin, input);\n\t\tif(input != \"\")\n\t\t{\n\t\t\tif(SIG_ERR == signal(SIGINT,changec))\n\t\t\t\tperror(\"signal failed\");\n\t\t\n\t\t\tif(input == \"exit\")\n\t\t\t\texit(1);\n\t\t\tstringParse(input, strvec);\n\t\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t\t{\n\t\t\t\tif(strvec.at(i) == \"&\")\n\t\t\t\t\tamper = true;\n\t\t\t\tif(strvec.at(i) == \"#\")\n\t\t\t\t\tstrvec.erase(strvec.begin()+i,strvec.end());\n\n\t\t\t}\t\n\n\t\t\tchar **usrIn = new char *[strvec.size()+1];\n\t\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t\t{\n\t\t\t\tusrIn[i] = new char[strvec.at(i).size()+1];\n\t\t\t\tstrcpy(usrIn[i], strvec.at(i).c_str());\n\t\t\t}\n\t\t\tusrIn[strvec.size()] = '\\0';\n\t\t\tif(strcmp(usrIn[0],cd.c_str()) == 0)\n\t\t\t{\n\t\t\t\tchar *abpath = new char[1024];\n\t\t\t\tif(usrIn[1] != NULL)\n\t\t\t\t{\n\t\t\t\t\tif(getcwd(abpath,1024) == NULL)\n\t\t\t\t\t\tperror(\"getcwd failed\");\n\t\t\t\t\tstrcat(abpath,\"\/\");\n\t\t\t\t\tstrcat(abpath,usrIn[1]);\n\t\t\t\t\tcout << abpath << endl;\n\t\t\t\t\tif(chdir(abpath) == -1)\n\t\t\t\t\t\tperror(\"directory change failed\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tchar *home = getenv(\"HOME\");\n\t\t\t\t\tif(home == NULL)\n\t\t\t\t\t\tperror(\"getenv failed\");\n\/\/\t\t\t\tcout << home << endl;\n\t\t\t\t\tif(chdir(home) == -1)\n\t\t\t\t\t\tperror(\"directory change failed\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\tparsepath(temp,pathvec);\n\n\t\t\t\tfor(unsigned int i = 0; i < pathvec.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tchar buf[1024];\n\t\t\t\t\tstrcpy(buf,pathvec.at(i).c_str());\n\t\t\t\t\tbuf[pathvec.at(i).size()+1] = '\\0';\n\t\t\t\t\tconcatstrpath = strncat(buf,\"\/\",1024);\n\t\t\t\t\tconcatstrpath2 = strncat(concatstrpath, usrIn[0],1024);\n\t\t\t\t\tconcatpath.push_back(concatstrpath2);\t\n\t\t\t\n\n\t\t\t\t\tif((openInt = open(concatpath.at(i).c_str(), O_RDONLY)) != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tcorrectpath = concatpath.at(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t\tif(openInt == -1)\n\t\t\t\t\tperror(\"open failed\");\n\t\t\t\tchar **fin = new char *[1024];\t\t\n\t\t\t\tunsigned int j;\n\t\t\t\tfor(j = 0; usrIn[j] != '\\0'; ++j)\n\t\t\t\t{\n\t\t\t\t\tfin[j] = new char[1024];\n\t\t\t\t\tstrcpy(fin[j],usrIn[j]);\n\t\t\t\t}\n\t\t\t\tfin[j] = '\\0';\n\t\t\t\texecuteCommands(correctpath.c_str(), fin, amper);\n\t\t\t\tdelete [] fin;\n\t\t\t}\n\t\t\tfor(unsigned int i = 0; i < strvec.size(); ++i)\n\t\t\t\tdelete usrIn[i];\n\t\t\tstrvec.clear();\n\t\t\tdelete [] usrIn;\n\t\t\tinput = \"\";\n\t\t\tcorrectpath = \"\";\n\t\t\tpathvec.clear();\n\t\t\tconcatpath.clear();\n\t\t}\n\t}\n\t\t\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Daniel Wallin 2008. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#ifndef LUABIND_INSTANCE_HOLDER_081024_HPP\n# define LUABIND_INSTANCE_HOLDER_081024_HPP\n\n# include <luabind\/detail\/inheritance.hpp>\n# include <luabind\/pointer_traits.hpp>\n# include <luabind\/typeid.hpp>\n# include <stdexcept>\n\nnamespace luabind { \n\tnamespace detail {\n\n\t\tclass instance_holder\n\t\t{\n\t\tpublic:\n\t\t\tinstance_holder(bool pointee_const)\n\t\t\t : m_pointee_const(pointee_const)\n\t\t\t{}\n\n\t\t\tvirtual ~instance_holder()\n\t\t\t{}\n\n\t\t\tvirtual std::pair<void*, int> get(cast_graph const& casts, class_id target) const = 0;\n\t\t\tvirtual void release() = 0;\n\n\t\t\tbool pointee_const() const\n\t\t\t{\n\t\t\t\treturn m_pointee_const;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbool m_pointee_const;\n\t\t};\n\n\t\ttemplate <class P, class Pointee = void const>\n\t\tclass pointer_holder : public instance_holder\n\t\t{\n\t\tpublic:\n\t\t\tpointer_holder( P p, class_id dynamic_id, void* dynamic_ptr ) :\n\t\t\t\tinstance_holder( detail::is_pointer_to_const<P>() ),\n\t\t\t\tp(std::move(p)), weak(0), dynamic_id(dynamic_id), dynamic_ptr(dynamic_ptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const\n\t\t\t{\n\t\t\t\t\/\/ if somebody wants the smart-ptr, he can get a reference to it\n\t\t\t\tif (target == registered_class<P>::id) return std::pair<void*, int>(&this->p, 0);\n\n\t\t\t\tvoid* naked_ptr = const_cast<void*>(static_cast<void const*>(weak ? weak : get_pointer(p)));\n\t\t\t\tif (!naked_ptr) return std::pair<void*, int>(nullptr, 0);\n\n\t\t\t\ttypedef typename std::remove_cv<typename std::remove_reference<decltype(*get_pointer(p))>::type>::type pointee_type;\n\n\t\t\t\treturn casts.cast( naked_ptr,\n\t\t\t\t\t\t\t\t registered_class< pointee_type >::id\n\t\t\t\t\t\t\t\t , target, dynamic_id, dynamic_ptr );\n\t\t\t}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn p ? true : false;\n\t\t\t}\n\n\t\t\tvoid release()\n\t\t\t{\n\t\t\t\tweak = const_cast<void*>(static_cast<void const*>(get_pointer(p)));\n\t\t\t\trelease_ownership(p);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tmutable P p;\n\t\t\t\/\/ weak will hold a possibly stale pointer to the object owned\n\t\t\t\/\/ by p once p has released it's owership. This is a workaround\n\t\t\t\/\/ to make adopt() work with virtual function wrapper classes.\n\t\t\tvoid* weak;\n\t\t\tclass_id dynamic_id;\n\t\t\tvoid* dynamic_ptr;\n\t\t};\n\n\t\ttemplate <class ValueType>\n\t\tclass value_holder : \n\t\t\tpublic instance_holder\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ No need for dynamic_id \/ dynamic_ptr, since we always get the most derived type\n value_holder(lua_State* \/*L*\/, ValueType val)\n\t\t\t\t: instance_holder(false), val_(std::move(val))\n\t\t\t{}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const\n\t\t\t{\n\t\t\t\tconst auto this_id = registered_class<ValueType>::id;\n\t\t\t\tvoid* const naked_ptr = const_cast<void*>((const void*)&val_);\n\t\t\t\tif(target==this_id) return std::pair<void*, int>(naked_ptr, 0);\n\t\t\t\treturn casts.cast(naked_ptr, this_id, target, this_id, naked_ptr);\n\t\t\t}\n\n\t\t\tvoid release() override\n\t\t\t{}\n\n\t\tprivate:\n\t\t\tValueType val_;\n\t\t};\n\n\t\t\/*\n\t\t\tPointer types should automatically convert to reference types\n\t\t*\/\n\t\ttemplate <class ValueType>\n\t\tclass pointer_like_holder : \n\t\t\tpublic instance_holder\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ No need for dynamic_id \/ dynamic_ptr, since we always get the most derived type\n pointer_like_holder(lua_State* \/*L*\/, ValueType val, class_id dynamic_id, void* dynamic_ptr)\n\t\t\t\t: \n\t\t\t\tinstance_holder(std::is_const< decltype(*get_pointer(val)) >::value),\n\t\t\t\tval_(std::move(val)),\n\t\t\t\tdynamic_id_(dynamic_id),\n\t\t\t\tdynamic_ptr_(dynamic_ptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn val_ ? true : false;\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const\n\t\t\t{\n\t\t\t\tconst auto value_id = registered_class<ValueType>::id;\n\t\t\t\tvoid* const naked_value_ptr = const_cast<void*>((const void*) &val_);\n\t\t\t\tif(target==value_id) return std::pair<void*, int>(naked_value_ptr, 0);\n\t\t\t\t\/\/ If we were to support automatic pointer conversion, this would be the place\n\n\t\t\t\ttypedef typename std::remove_cv<typename std::remove_reference<decltype(*get_pointer(val_))>::type >::type pointee_type;\n\t\t\t\tconst auto pointee_id = registered_class< pointee_type >::id;\n\t\t\t\tvoid* const naked_pointee_ptr = const_cast<void*>((const void*) get_pointer(val_));\n\t\t\t\treturn casts.cast(naked_pointee_ptr, pointee_id, target, dynamic_id_, dynamic_ptr_);\n\t\t\t}\n\n\t\t\tvoid release() override\n\t\t\t{}\n\n\t\tprivate:\n\t\t\tValueType val_;\n\t\t\tclass_id dynamic_id_;\n\t\t\tvoid* dynamic_ptr_;\n\t\t\t\/\/ weak? must understand what the comment up there really means\n\t\t};\n\n\t}\n\n} \/\/ namespace luabind::detail\n\n#endif \/\/ LUABIND_INSTANCE_HOLDER_081024_HPP\n\n<commit_msg>Added missing overrides in instance_holder.hpp<commit_after>\/\/ Copyright Daniel Wallin 2008. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#ifndef LUABIND_INSTANCE_HOLDER_081024_HPP\n# define LUABIND_INSTANCE_HOLDER_081024_HPP\n\n# include <luabind\/detail\/inheritance.hpp>\n# include <luabind\/pointer_traits.hpp>\n# include <luabind\/typeid.hpp>\n# include <stdexcept>\n\nnamespace luabind { \n\tnamespace detail {\n\n\t\tclass instance_holder\n\t\t{\n\t\tpublic:\n\t\t\tinstance_holder(bool pointee_const)\n\t\t\t : m_pointee_const(pointee_const)\n\t\t\t{}\n\n\t\t\tvirtual ~instance_holder()\n\t\t\t{}\n\n\t\t\tvirtual std::pair<void*, int> get(cast_graph const& casts, class_id target) const = 0;\n\t\t\tvirtual void release() = 0;\n\n\t\t\tbool pointee_const() const\n\t\t\t{\n\t\t\t\treturn m_pointee_const;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbool m_pointee_const;\n\t\t};\n\n\t\ttemplate <class P, class Pointee = void const>\n\t\tclass pointer_holder : public instance_holder\n\t\t{\n\t\tpublic:\n\t\t\tpointer_holder( P p, class_id dynamic_id, void* dynamic_ptr ) :\n\t\t\t\tinstance_holder( detail::is_pointer_to_const<P>() ),\n\t\t\t\tp(std::move(p)), weak(0), dynamic_id(dynamic_id), dynamic_ptr(dynamic_ptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const override\n\t\t\t{\n\t\t\t\t\/\/ if somebody wants the smart-ptr, he can get a reference to it\n\t\t\t\tif (target == registered_class<P>::id) return std::pair<void*, int>(&this->p, 0);\n\n\t\t\t\tvoid* naked_ptr = const_cast<void*>(static_cast<void const*>(weak ? weak : get_pointer(p)));\n\t\t\t\tif (!naked_ptr) return std::pair<void*, int>(nullptr, 0);\n\n\t\t\t\ttypedef typename std::remove_cv<typename std::remove_reference<decltype(*get_pointer(p))>::type>::type pointee_type;\n\n\t\t\t\treturn casts.cast( naked_ptr,\n\t\t\t\t\t\t\t\t registered_class< pointee_type >::id\n\t\t\t\t\t\t\t\t , target, dynamic_id, dynamic_ptr );\n\t\t\t}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn p ? true : false;\n\t\t\t}\n\n\t\t\tvoid release()\n\t\t\t{\n\t\t\t\tweak = const_cast<void*>(static_cast<void const*>(get_pointer(p)));\n\t\t\t\trelease_ownership(p);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tmutable P p;\n\t\t\t\/\/ weak will hold a possibly stale pointer to the object owned\n\t\t\t\/\/ by p once p has released it's owership. This is a workaround\n\t\t\t\/\/ to make adopt() work with virtual function wrapper classes.\n\t\t\tvoid* weak;\n\t\t\tclass_id dynamic_id;\n\t\t\tvoid* dynamic_ptr;\n\t\t};\n\n\t\ttemplate <class ValueType>\n\t\tclass value_holder : \n\t\t\tpublic instance_holder\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ No need for dynamic_id \/ dynamic_ptr, since we always get the most derived type\n value_holder(lua_State* \/*L*\/, ValueType val)\n\t\t\t\t: instance_holder(false), val_(std::move(val))\n\t\t\t{}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const override\n\t\t\t{\n\t\t\t\tconst auto this_id = registered_class<ValueType>::id;\n\t\t\t\tvoid* const naked_ptr = const_cast<void*>((const void*)&val_);\n\t\t\t\tif(target==this_id) return std::pair<void*, int>(naked_ptr, 0);\n\t\t\t\treturn casts.cast(naked_ptr, this_id, target, this_id, naked_ptr);\n\t\t\t}\n\n\t\t\tvoid release() override\n\t\t\t{}\n\n\t\tprivate:\n\t\t\tValueType val_;\n\t\t};\n\n\t\t\/*\n\t\t\tPointer types should automatically convert to reference types\n\t\t*\/\n\t\ttemplate <class ValueType>\n\t\tclass pointer_like_holder : \n\t\t\tpublic instance_holder\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ No need for dynamic_id \/ dynamic_ptr, since we always get the most derived type\n pointer_like_holder(lua_State* \/*L*\/, ValueType val, class_id dynamic_id, void* dynamic_ptr)\n\t\t\t\t: \n\t\t\t\tinstance_holder(std::is_const< decltype(*get_pointer(val)) >::value),\n\t\t\t\tval_(std::move(val)),\n\t\t\t\tdynamic_id_(dynamic_id),\n\t\t\t\tdynamic_ptr_(dynamic_ptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit operator bool() const\n\t\t\t{\n\t\t\t\treturn val_ ? true : false;\n\t\t\t}\n\n\t\t\tstd::pair<void*, int> get(cast_graph const& casts, class_id target) const override\n\t\t\t{\n\t\t\t\tconst auto value_id = registered_class<ValueType>::id;\n\t\t\t\tvoid* const naked_value_ptr = const_cast<void*>((const void*) &val_);\n\t\t\t\tif(target==value_id) return std::pair<void*, int>(naked_value_ptr, 0);\n\t\t\t\t\/\/ If we were to support automatic pointer conversion, this would be the place\n\n\t\t\t\ttypedef typename std::remove_cv<typename std::remove_reference<decltype(*get_pointer(val_))>::type >::type pointee_type;\n\t\t\t\tconst auto pointee_id = registered_class< pointee_type >::id;\n\t\t\t\tvoid* const naked_pointee_ptr = const_cast<void*>((const void*) get_pointer(val_));\n\t\t\t\treturn casts.cast(naked_pointee_ptr, pointee_id, target, dynamic_id_, dynamic_ptr_);\n\t\t\t}\n\n\t\t\tvoid release() override\n\t\t\t{}\n\n\t\tprivate:\n\t\t\tValueType val_;\n\t\t\tclass_id dynamic_id_;\n\t\t\tvoid* dynamic_ptr_;\n\t\t\t\/\/ weak? must understand what the comment up there really means\n\t\t};\n\n\t}\n\n} \/\/ namespace luabind::detail\n\n#endif \/\/ LUABIND_INSTANCE_HOLDER_081024_HPP\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of loaddap.\n\n\n\/\/ Copyright (c) 2005 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ \n\/\/ This software is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n\/\/ (c) COPYRIGHT URI\/MIT 1996\n\/\/ Please read the full copyright statement in the file COPYRIGH. \n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation for ClientStr. See ClientByte.cc\n\/\/\n\/\/ jhrg 9\/25\/96\n\n#include <assert.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include \"config_writedap.h\"\t\/\/ was first caused LITTLE_ENDIAN error\n\n#include <iostream>\n#include <string>\n\n#include <GNURegex.h>\n\n#include \"InternalErr.h\"\n#include \"ClientStr.h\"\n#include \"name_map.h\"\n\n\/\/ We *should* be using <nan.h> to handle generating NaN. However, many\n\/\/ machines don't have a function that can be used to generate NaN so I've\n\/\/ written my own (which uses its own bastardized version of the FP union).\n\/\/ 2\/5\/97 jhrg\n\n#include \"nan_hack.h\"\n\nstatic double\nMakeNaN() \n{ \n dnan X;\n X.nan.exponent = 0x7ff; \n X.nan.qnan_bit = 0x1; \n \n return X.d;\n}\n\nextern name_map names;\nextern bool translate;\nextern bool ascii;\nextern bool string_to_float;\nextern bool verbose;\nextern bool warning;\n\nStr *\nNewStr(const string &n)\n{\n return new ClientStr(n);\n}\n\nClientStr::ClientStr(const string &n) : Str(n)\n{\n set_matlab_name(n);\n}\n\nBaseType *\nClientStr::ptr_duplicate()\n{\n return new ClientStr(*this);\n}\n\nbool\nClientStr::read(const string &)\n{\n throw InternalErr(__FILE__, __LINE__, \"Called unimplemented read method\");\n}\n\nvoid \nClientStr::print_val(FILE *os, string, bool print_decl_p)\n{\n bool print_as_float = false;\n double val = 0.0;\n\n \/\/ Translate all string variables to Floats. jhrg 1\/9\/98.\n if (string_to_float) {\n\tchar *ptr = NULL;\n\tconst char *str = _buf.c_str();\n\tval = strtod(str, &ptr);\n\tprint_as_float = !(val == 0.0 && (ptr == str));\n\n\tif (!print_as_float) {\n\t val = MakeNaN();\n\t print_as_float = true;\n\t if (warning) {\n\t\tcerr << \"Could not translate `\" << _buf << \"' to a Float64,\"\n\t\t << endl;\n\t\tcerr << \"interning as NaN (not a number: \" << val \n\t\t << \")\" << endl;\n\t }\n\t}\n }\n\n if (print_as_float) {\n\tif (print_decl_p)\n fprintf(os, \"Float64\\n%s\\n\", get_matlab_name().c_str());\n\/\/\t ss << \"Float64\" << endl << get_matlab_name() << endl;\n\n\n\tif (ascii)\n fprintf(os, \"%lf \", val);\n\/\/\t ss << val << \" \";\n\telse\n fwrite((void *)&val, sizeof(double), 1, os);\n\/\/\t os.write((char *)&val, sizeof(double));\n }\n else {\n\tif (print_decl_p)\n fprintf(os, \"%s\\n%s\\n\", type_name(), get_matlab_name().c_str());\n\/\/\t os << type_name() << endl << get_matlab_name() << endl;\n\n \/\/ There's no special case for ASCII since this is a String.\n fprintf(os, \"%s \", _buf.c_str());\n\/\/\tos << _buf << endl;\n }\n}\n\nAttrTable &\nClientStr::getAttrTable()\n{\n return _attr;\n}\n\nvoid \nClientStr::setAttrTable(AttrTable &attr)\n{\n _attr = attr;\n}\n\nvoid\nClientStr::set_name(const string &n)\n{\n BaseType::set_name(n);\n set_matlab_name(n);\n}\n\nstring \nClientStr::get_matlab_name() const\n{\n return _matlabName; \n}\n\nvoid \nClientStr::set_matlab_name(const string &name)\n{ \n _matlabName = names.lookup(name, translate);\n}\n\n\/\/ $Log: ClientStr.cc,v $\n\/\/ Revision 1.3 2003\/12\/08 17:59:49 edavis\n\/\/ Merge release-3-4 into trunk\n\/\/\n\/\/ Revision 1.1.1.1 2003\/10\/22 19:43:19 dan\n\/\/ Version of the Matlab CommandLine client which uses Matlab Structure\n\/\/ variables to maintain the shape of the underlying DODS data.\n\/\/ Revision 1.1.1.1.2.2 2003\/10\/29 19:03:21 dan\n\/\/ Removed 'pragma interface' directive from all subclass\n\/\/ source files.\n\/\/\n\/\/ Revision 1.1.1.1.2.1 2003\/10\/27 16:41:30 dan\n\/\/ Changed config include to 'config_writedap.h' to designate\n\/\/ new version of 'writeval' now called 'writedap'. The only\n\/\/ substantive change in 'writedap' is that nested sequence\n\/\/ variables are now supported.\n\/\/\n\/\/ Revision 1.2 2003\/10\/23 18:34:02 dan\n\/\/ Changed config include to config_writedap.h from config_writeval.h\n\/\/ This is to remain consistent with the renaming used from loaddods\n\/\/ to loaddap. To support nested sequences writeval was modified\n\/\/ to send an end-of-sequence marker to delimit sequence instances.\n\/\/\n\/\/\n\/\/ Revision 1.29 2003\/05\/02 17:16:17 jimg\n\/\/ I replaced the cast is ostream::write that was (void *) to (char *) to\n\/\/ get this code to compile with gcc 3.2. This change is also needed for\n\/\/ VC++, so I was able to remove some of the ifdef WIN32 lines. Also, in\n\/\/ name_map I added a using namespace std; line.\n\/\/\n\/\/ Revision 1.28 2003\/01\/29 15:43:52 dan\n\/\/ Resolved conflict on merge, caused by PWEST's removal\n\/\/ of the SLLIST includes in a previous update on the trunk.\n\/\/\n\/\/ Revision 1.27 2001\/08\/27 18:06:57 jimg\n\/\/ Merged release-3-2-5.\n\/\/\n\/\/ Revision 1.26.2.2 2002\/09\/05 22:26:49 pwest\n\/\/ Removed includes to SLList and DLList. These are not necessary and no longer\n\/\/ supported.\n\/\/\n\/\/ Revision 1.26.2.1 2001\/08\/21 16:49:18 dan\n\/\/ Added set\/accessor methods for a new local member, matlab_name\n\/\/ which stores the translated name of the variable so that it does\n\/\/ not have to be translated during serialization. This optimizes\n\/\/ the amount of time spent in variable name translation to a single\n\/\/ instance.\n\/\/\n\/\/ Added a local method, set_name() which works with the BaseType\n\/\/ pointer to update both the BaseType name member and local matlab_name\n\/\/ member.\n\/\/\n\/\/ Revision 1.26 2000\/10\/03 22:24:17 jimg\n\/\/ Reorganized the CVS Log entries.\n\/\/ Changed the read() mfunc definitions to match the 3.2 dap++ library.\n\/\/\n\/\/ Revision 1.25 2000\/07\/21 10:21:56 rmorris\n\/\/ Merged with win32-mlclient-branch.\n\/\/\n\/\/ Revision 1.24.2.2 2000\/07\/09 22:26:32 rmorris\n\/\/ Mod's to increase portability, minimize ifdef's for win32.\n\/\/\n\/\/ Revision 1.24.2.1 2000\/06\/26 22:54:26 rmorris\n\/\/ Mods for port to win32.\n\/\/\n\/\/ Revision 1.24 2000\/06\/07 00:28:31 jimg\n\/\/ Merged changes from version 3.1.4\n\/\/\n\/\/ Revision 1.22.2.3 2000\/06\/02 23:03:32 jimg\n\/\/ Fixes for AttrTables with no entries.\n\/\/ Added support for name translation and a DODS_ML_Real_Name attribute.\n\/\/ Changed the `size' attribtue's name to DODS_ML_Size.\n\/\/\n\/\/ Revision 1.22.2.2 2000\/05\/26 22:15:54 jimg\n\/\/ Removed the old DMS time processing code.\n\/\/\n\/\/ Revision 1.23 2000\/04\/20 23:38:12 jimg\n\/\/ Merged with release 3.1.3\n\/\/\n\/\/ Revision 1.22.2.1 2000\/04\/11 21:46:21 jimg\n\/\/ Removed old code.\n\/\/\n\/\/ Revision 1.22 1999\/07\/24 00:10:28 jimg\n\/\/ Merged the release-3-0-2 branch\n\/\/\n\/\/ Revision 1.21 1999\/04\/30 17:06:55 jimg\n\/\/ Merged with no-gnu and release-2-24\n\/\/\n\/\/ Revision 1.20 1999\/03\/24 06:23:43 brent\n\/\/ convert String.h to std lib <string>, convert to packages regex -- B^2\n\/\/\n\/\/ Revision 1.19 1998\/11\/25 01:16:19 jimg\n\/\/ Now processes -w for warnings. This means that verbose (-v) mode is\n\/\/ information and -w is for warnings only.\n\/\/\n\/\/ Revision 1.18 1998\/11\/20 08:41:22 jimg\n\/\/ Fixed the fix for the extra newline separators; it was broken for arrays\n\/\/\n\/\/ Revision 1.17 1998\/11\/19 20:53:33 jimg\n\/\/ Fixed the extra newline bug.\n\/\/\n\/\/ Revision 1.16 1998\/09\/16 23:02:22 jimg\n\/\/ Removed write_val() and replaced it with print_val() and print_all_vals()\n\/\/\n\/\/ Revision 1.15 1998\/08\/03 16:39:50 jimg\n\/\/ Fixed write_val mfunc so that outermost is no longer used\n\/\/\n\/\/ Revision 1.14 1998\/06\/09 04:09:13 jimg\n\/\/ Made some of the diagnostic output about interning NaNs part of the verbose\n\/\/ option. It will only print when writeval is called with the -v option.\n\/\/\n\/\/ Revision 1.13 1998\/02\/05 20:14:50 jimg\n\/\/ DODS now compiles with gcc 2.8.x\n\/\/\n\/\/ Revision 1.12 1997\/12\/02 20:34:37 jimg\n\/\/ Fixed\/Removed the automatic conversion of strings to numbers. This was a\n\/\/ bad idea.\n\/\/\n\/\/ Revision 1.11 1997\/10\/04 00:40:06 jimg\n\/\/ Added changes to support the new deserialize() mfunc and write_val().\n\/\/\n\/\/ Revision 1.10 1997\/06\/06 04:02:07 jimg\n\/\/ Added ASCII output option to writeval. Uses a global `flag'.\n\/\/\n\/\/ Revision 1.9 1997\/04\/19 00:54:58 jimg\n\/\/ Changed ouput stream to simplify reading (for loaddods).\n\/\/\n\/\/ Revision 1.8 1997\/02\/06 19:42:39 jimg\n\/\/ When converting strings to Float64 values, any string that cannot be\n\/\/ converted is externalized as NaN.\n\/\/\n\/\/ Revision 1.7 1997\/01\/13 18:01:50 jimg\n\/\/ Fixed a bug when the degree part of a DDDMMSSH string has only one or two\n\/\/ digits.\n\/\/\n\/\/ Revision 1.6 1997\/01\/10 06:49:37 jimg\n\/\/ Changed call to name_map::lookup() so that non-alphanumerics are mapped to\n\/\/ underscore. \n\/\/\n\/\/ Revision 1.5 1996\/11\/23 05:12:13 jimg\n\/\/ Added support for variable renaming via the name_map object.\n\/\/\n\/\/ Revision 1.4 1996\/11\/13 18:02:54 jimg\n\/\/ Fixed bad usage of strtod(). When strtod() returns 0.0, the pointer passed\n\/\/ as a second argument must be compared to the pointer to the string to be\n\/\/ converted instead of testing only that it is not null. If the pointer is not\n\/\/ equal to the string argument then the number *has* converted successfully\n\/\/ (to 0.0). Otherwise, the string did not convert.\n\/\/\n\/\/ Revision 1.3 1996\/10\/23 23:46:44 jimg\n\/\/ Modified so that writeval outputs a `recursive' data stream. Thus any\n\/\/ data type can be written and later read without being flattened. This\n\/\/ change was made so that the NSCAT data which is represented as a Sequence\n\/\/ of Structures.\n\/\/\n\/\/ Revision 1.2 1996\/10\/07 21:00:29 jimg\n\/\/ Fixed Headers.\n\/\/\n\/\/ Revision 1.1 1996\/09\/30 23:59:18 jimg\n\/\/ Added.\n<commit_msg>Fixed print_val(), fprintf in if(print_decl_p) condition requires a EOL character after writing _buf.<commit_after>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of loaddap.\n\n\n\/\/ Copyright (c) 2005 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ \n\/\/ This software is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n\/\/ (c) COPYRIGHT URI\/MIT 1996\n\/\/ Please read the full copyright statement in the file COPYRIGH. \n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation for ClientStr. See ClientByte.cc\n\/\/\n\/\/ jhrg 9\/25\/96\n\n#include <assert.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include \"config_writedap.h\"\t\/\/ was first caused LITTLE_ENDIAN error\n\n#include <iostream>\n#include <string>\n\n#include <GNURegex.h>\n\n#include \"InternalErr.h\"\n#include \"ClientStr.h\"\n#include \"name_map.h\"\n\n\/\/ We *should* be using <nan.h> to handle generating NaN. However, many\n\/\/ machines don't have a function that can be used to generate NaN so I've\n\/\/ written my own (which uses its own bastardized version of the FP union).\n\/\/ 2\/5\/97 jhrg\n\n#include \"nan_hack.h\"\n\nstatic double\nMakeNaN() \n{ \n dnan X;\n X.nan.exponent = 0x7ff; \n X.nan.qnan_bit = 0x1; \n \n return X.d;\n}\n\nextern name_map names;\nextern bool translate;\nextern bool ascii;\nextern bool string_to_float;\nextern bool verbose;\nextern bool warning;\n\nStr *\nNewStr(const string &n)\n{\n return new ClientStr(n);\n}\n\nClientStr::ClientStr(const string &n) : Str(n)\n{\n set_matlab_name(n);\n}\n\nBaseType *\nClientStr::ptr_duplicate()\n{\n return new ClientStr(*this);\n}\n\nbool\nClientStr::read(const string &)\n{\n throw InternalErr(__FILE__, __LINE__, \"Called unimplemented read method\");\n}\n\nvoid \nClientStr::print_val(FILE *os, string, bool print_decl_p)\n{\n bool print_as_float = false;\n double val = 0.0;\n\n \/\/ Translate all string variables to Floats. jhrg 1\/9\/98.\n if (string_to_float) {\n\tchar *ptr = NULL;\n\tconst char *str = _buf.c_str();\n\tval = strtod(str, &ptr);\n\tprint_as_float = !(val == 0.0 && (ptr == str));\n\n\tif (!print_as_float) {\n\t val = MakeNaN();\n\t print_as_float = true;\n\t if (warning) {\n\t\tcerr << \"Could not translate `\" << _buf << \"' to a Float64,\"\n\t\t << endl;\n\t\tcerr << \"interning as NaN (not a number: \" << val \n\t\t << \")\" << endl;\n\t }\n\t}\n }\n\n if (print_as_float) {\n\tif (print_decl_p)\n fprintf(os, \"Float64\\n%s\\n\", get_matlab_name().c_str());\n\/\/\t ss << \"Float64\" << endl << get_matlab_name() << endl;\n\n\n\tif (ascii)\n fprintf(os, \"%lf \", val);\n\/\/\t ss << val << \" \";\n\telse\n\t fwrite((void *)&val, sizeof(double), 1, os);\n\/\/\t os.write((char *)&val, sizeof(double));\n }\n else {\n\tif (print_decl_p)\n fprintf(os, \"%s\\n%s\\n\", type_name().c_str(), get_matlab_name().c_str());\n\/\/\t os << type_name() << endl << get_matlab_name() << endl;\n\n \/\/ There's no special case for ASCII since this is a String.\n fprintf(os, \"%s\\n\", _buf.c_str());\n\/\/\tos << _buf << endl;\n }\n}\n\nAttrTable &\nClientStr::getAttrTable()\n{\n return _attr;\n}\n\nvoid \nClientStr::setAttrTable(AttrTable &attr)\n{\n _attr = attr;\n}\n\nvoid\nClientStr::set_name(const string &n)\n{\n BaseType::set_name(n);\n set_matlab_name(n);\n}\n\nstring \nClientStr::get_matlab_name() const\n{\n return _matlabName; \n}\n\nvoid \nClientStr::set_matlab_name(const string &name)\n{ \n _matlabName = names.lookup(name, translate);\n}\n\n\/\/ $Log: ClientStr.cc,v $\n\/\/ Revision 1.3 2003\/12\/08 17:59:49 edavis\n\/\/ Merge release-3-4 into trunk\n\/\/\n\/\/ Revision 1.1.1.1 2003\/10\/22 19:43:19 dan\n\/\/ Version of the Matlab CommandLine client which uses Matlab Structure\n\/\/ variables to maintain the shape of the underlying DODS data.\n\/\/ Revision 1.1.1.1.2.2 2003\/10\/29 19:03:21 dan\n\/\/ Removed 'pragma interface' directive from all subclass\n\/\/ source files.\n\/\/\n\/\/ Revision 1.1.1.1.2.1 2003\/10\/27 16:41:30 dan\n\/\/ Changed config include to 'config_writedap.h' to designate\n\/\/ new version of 'writeval' now called 'writedap'. The only\n\/\/ substantive change in 'writedap' is that nested sequence\n\/\/ variables are now supported.\n\/\/\n\/\/ Revision 1.2 2003\/10\/23 18:34:02 dan\n\/\/ Changed config include to config_writedap.h from config_writeval.h\n\/\/ This is to remain consistent with the renaming used from loaddods\n\/\/ to loaddap. To support nested sequences writeval was modified\n\/\/ to send an end-of-sequence marker to delimit sequence instances.\n\/\/\n\/\/\n\/\/ Revision 1.29 2003\/05\/02 17:16:17 jimg\n\/\/ I replaced the cast is ostream::write that was (void *) to (char *) to\n\/\/ get this code to compile with gcc 3.2. This change is also needed for\n\/\/ VC++, so I was able to remove some of the ifdef WIN32 lines. Also, in\n\/\/ name_map I added a using namespace std; line.\n\/\/\n\/\/ Revision 1.28 2003\/01\/29 15:43:52 dan\n\/\/ Resolved conflict on merge, caused by PWEST's removal\n\/\/ of the SLLIST includes in a previous update on the trunk.\n\/\/\n\/\/ Revision 1.27 2001\/08\/27 18:06:57 jimg\n\/\/ Merged release-3-2-5.\n\/\/\n\/\/ Revision 1.26.2.2 2002\/09\/05 22:26:49 pwest\n\/\/ Removed includes to SLList and DLList. These are not necessary and no longer\n\/\/ supported.\n\/\/\n\/\/ Revision 1.26.2.1 2001\/08\/21 16:49:18 dan\n\/\/ Added set\/accessor methods for a new local member, matlab_name\n\/\/ which stores the translated name of the variable so that it does\n\/\/ not have to be translated during serialization. This optimizes\n\/\/ the amount of time spent in variable name translation to a single\n\/\/ instance.\n\/\/\n\/\/ Added a local method, set_name() which works with the BaseType\n\/\/ pointer to update both the BaseType name member and local matlab_name\n\/\/ member.\n\/\/\n\/\/ Revision 1.26 2000\/10\/03 22:24:17 jimg\n\/\/ Reorganized the CVS Log entries.\n\/\/ Changed the read() mfunc definitions to match the 3.2 dap++ library.\n\/\/\n\/\/ Revision 1.25 2000\/07\/21 10:21:56 rmorris\n\/\/ Merged with win32-mlclient-branch.\n\/\/\n\/\/ Revision 1.24.2.2 2000\/07\/09 22:26:32 rmorris\n\/\/ Mod's to increase portability, minimize ifdef's for win32.\n\/\/\n\/\/ Revision 1.24.2.1 2000\/06\/26 22:54:26 rmorris\n\/\/ Mods for port to win32.\n\/\/\n\/\/ Revision 1.24 2000\/06\/07 00:28:31 jimg\n\/\/ Merged changes from version 3.1.4\n\/\/\n\/\/ Revision 1.22.2.3 2000\/06\/02 23:03:32 jimg\n\/\/ Fixes for AttrTables with no entries.\n\/\/ Added support for name translation and a DODS_ML_Real_Name attribute.\n\/\/ Changed the `size' attribtue's name to DODS_ML_Size.\n\/\/\n\/\/ Revision 1.22.2.2 2000\/05\/26 22:15:54 jimg\n\/\/ Removed the old DMS time processing code.\n\/\/\n\/\/ Revision 1.23 2000\/04\/20 23:38:12 jimg\n\/\/ Merged with release 3.1.3\n\/\/\n\/\/ Revision 1.22.2.1 2000\/04\/11 21:46:21 jimg\n\/\/ Removed old code.\n\/\/\n\/\/ Revision 1.22 1999\/07\/24 00:10:28 jimg\n\/\/ Merged the release-3-0-2 branch\n\/\/\n\/\/ Revision 1.21 1999\/04\/30 17:06:55 jimg\n\/\/ Merged with no-gnu and release-2-24\n\/\/\n\/\/ Revision 1.20 1999\/03\/24 06:23:43 brent\n\/\/ convert String.h to std lib <string>, convert to packages regex -- B^2\n\/\/\n\/\/ Revision 1.19 1998\/11\/25 01:16:19 jimg\n\/\/ Now processes -w for warnings. This means that verbose (-v) mode is\n\/\/ information and -w is for warnings only.\n\/\/\n\/\/ Revision 1.18 1998\/11\/20 08:41:22 jimg\n\/\/ Fixed the fix for the extra newline separators; it was broken for arrays\n\/\/\n\/\/ Revision 1.17 1998\/11\/19 20:53:33 jimg\n\/\/ Fixed the extra newline bug.\n\/\/\n\/\/ Revision 1.16 1998\/09\/16 23:02:22 jimg\n\/\/ Removed write_val() and replaced it with print_val() and print_all_vals()\n\/\/\n\/\/ Revision 1.15 1998\/08\/03 16:39:50 jimg\n\/\/ Fixed write_val mfunc so that outermost is no longer used\n\/\/\n\/\/ Revision 1.14 1998\/06\/09 04:09:13 jimg\n\/\/ Made some of the diagnostic output about interning NaNs part of the verbose\n\/\/ option. It will only print when writeval is called with the -v option.\n\/\/\n\/\/ Revision 1.13 1998\/02\/05 20:14:50 jimg\n\/\/ DODS now compiles with gcc 2.8.x\n\/\/\n\/\/ Revision 1.12 1997\/12\/02 20:34:37 jimg\n\/\/ Fixed\/Removed the automatic conversion of strings to numbers. This was a\n\/\/ bad idea.\n\/\/\n\/\/ Revision 1.11 1997\/10\/04 00:40:06 jimg\n\/\/ Added changes to support the new deserialize() mfunc and write_val().\n\/\/\n\/\/ Revision 1.10 1997\/06\/06 04:02:07 jimg\n\/\/ Added ASCII output option to writeval. Uses a global `flag'.\n\/\/\n\/\/ Revision 1.9 1997\/04\/19 00:54:58 jimg\n\/\/ Changed ouput stream to simplify reading (for loaddods).\n\/\/\n\/\/ Revision 1.8 1997\/02\/06 19:42:39 jimg\n\/\/ When converting strings to Float64 values, any string that cannot be\n\/\/ converted is externalized as NaN.\n\/\/\n\/\/ Revision 1.7 1997\/01\/13 18:01:50 jimg\n\/\/ Fixed a bug when the degree part of a DDDMMSSH string has only one or two\n\/\/ digits.\n\/\/\n\/\/ Revision 1.6 1997\/01\/10 06:49:37 jimg\n\/\/ Changed call to name_map::lookup() so that non-alphanumerics are mapped to\n\/\/ underscore. \n\/\/\n\/\/ Revision 1.5 1996\/11\/23 05:12:13 jimg\n\/\/ Added support for variable renaming via the name_map object.\n\/\/\n\/\/ Revision 1.4 1996\/11\/13 18:02:54 jimg\n\/\/ Fixed bad usage of strtod(). When strtod() returns 0.0, the pointer passed\n\/\/ as a second argument must be compared to the pointer to the string to be\n\/\/ converted instead of testing only that it is not null. If the pointer is not\n\/\/ equal to the string argument then the number *has* converted successfully\n\/\/ (to 0.0). Otherwise, the string did not convert.\n\/\/\n\/\/ Revision 1.3 1996\/10\/23 23:46:44 jimg\n\/\/ Modified so that writeval outputs a `recursive' data stream. Thus any\n\/\/ data type can be written and later read without being flattened. This\n\/\/ change was made so that the NSCAT data which is represented as a Sequence\n\/\/ of Structures.\n\/\/\n\/\/ Revision 1.2 1996\/10\/07 21:00:29 jimg\n\/\/ Fixed Headers.\n\/\/\n\/\/ Revision 1.1 1996\/09\/30 23:59:18 jimg\n\/\/ Added.\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015,2016 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"log.h\"\n\n#include \"datetime.h\"\n#include \"utils.h\"\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define BUFFER_SIZE (10 * 1024)\n#define STACKED_SEP \"<sep>\"\n\n\nconst std::regex filter_re(\"\\033\\\\[[;\\\\d]*m\");\nstd::mutex Log::stack_mtx;\nstd::unordered_map<std::thread::id, unsigned> Log::stack_levels;\n\n\nconst char *priorities[] = {\n\tEMERG_COL \"█\" NO_COL, \/\/ LOG_EMERG 0 = System is unusable\n\tALERT_COL \"▉\" NO_COL, \/\/ LOG_ALERT 1 = Action must be taken immediately\n\tCRIT_COL \"▊\" NO_COL, \/\/ LOG_CRIT 2 = Critical conditions\n\tERR_COL \"▋\" NO_COL, \/\/ LOG_ERR 3 = Error conditions\n\tWARNING_COL \"▌\" NO_COL, \/\/ LOG_WARNING 4 = Warning conditions\n\tNOTICE_COL \"▍\" NO_COL, \/\/ LOG_NOTICE 5 = Normal but significant condition\n\tINFO_COL \"▎\" NO_COL, \/\/ LOG_INFO 6 = Informational\n\tDEBUG_COL \"▏\" NO_COL, \/\/ LOG_DEBUG 7 = Debug-level messages\n};\n\n\nvoid\nStreamLogger::log(int priority, const std::string& str)\n{\n\tofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\") << std::endl;\n}\n\n\nvoid\nStderrLogger::log(int priority, const std::string& str)\n{\n\tif (isatty(fileno(stderr))) {\n\t\tstd::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;\n\t} else {\n\t\tstd::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\") << std::endl;\n\t}\n}\n\n\nSysLog::SysLog(const char *ident, int option, int facility)\n{\n\topenlog(ident, option, facility);\n}\n\n\nSysLog::~SysLog()\n{\n\tcloselog();\n}\n\n\nvoid\nSysLog::log(int priority, const std::string& str)\n{\n\tsyslog(priority, \"%s\", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\").c_str());\n}\n\n\nLog::Log(const std::string& str, bool clean_, bool stacked_, std::chrono::time_point<std::chrono::system_clock> wakeup_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)\n\t: stack_level(0),\n\t stacked(stacked_),\n\t clean(clean_),\n\t created_at(created_at_),\n\t wakeup(wakeup_),\n\t str_start(str),\n\t priority(priority_),\n\t finished(false),\n\t cleaned(false) {\n\n\tif (stacked) {\n\t\tstd::lock_guard<std::mutex> lk(stack_mtx);\n\t\tthread_id = std::this_thread::get_id();\n\t\ttry {\n\t\t\tstack_level = ++stack_levels.at(thread_id);\n\t\t} catch (const std::out_of_range&) {\n\t\t\tstack_levels[thread_id] = 0;\n\t\t}\n\t}\n}\n\nLog::~Log()\n{\n\tcleanup();\n}\n\n\nvoid\nLog::cleanup()\n{\n\tbool f = false;\n\tfinished.compare_exchange_strong(f, clean);\n\n\tif (!cleaned.exchange(true)) {\n\t\tif (stacked) {\n\t\t\tstd::lock_guard<std::mutex> lk(stack_mtx);\n\t\t\tif (stack_levels.at(thread_id)-- == 0) {\n\t\t\t\tstack_levels.erase(thread_id);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nlong double\nLog::age()\n{\n\treturn std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - created_at).count();\n}\n\n\n\/*\n * https:\/\/isocpp.org\/wiki\/faq\/ctors#static-init-order\n * Avoid the \"static initialization order fiasco\"\n *\/\n\nLogThread&\nLog::_thread()\n{\n\tstatic LogThread* thread = new LogThread();\n\treturn *thread;\n}\n\n\nint&\nLog::_log_level()\n{\n\tstatic auto* log_level = new int(DEFAULT_LOG_LEVEL);\n\treturn *log_level;\n}\n\n\nDLList<const std::unique_ptr<Logger>>&\nLog::_handlers()\n{\n\tstatic auto* handlers = new DLList<const std::unique_ptr<Logger>>();\n\treturn *handlers;\n}\n\n\nstd::string\nLog::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)\n{\n\tchar* buffer = new char[BUFFER_SIZE];\n\tvsnprintf(buffer, BUFFER_SIZE, format, argptr);\n\tstd::string msg(buffer);\n\tauto iso8601 = \"[\" + Datetime::to_string(std::chrono::system_clock::now()) + \"]\";\n\tauto tid = \" (\" + get_thread_name() + \")\";\n\tstd::string result = iso8601 + tid;\n#ifdef LOG_OBJ_ADDRESS\n\tif (obj) {\n\t\tsnprintf(buffer, BUFFER_SIZE, \" [%p]\", obj);\n\t\tresult += buffer;\n\t}\n#endif\n#ifdef TRACEBACK\n\tauto location = (priority >= LOCATION_LOG_LEVEL) ? \" \" + std::string(file) + \":\" + std::to_string(line) : std::string();\n\tresult += location + \": \";\n#else\n\tresult += \" \";\n\t(void)obj;\n#endif\n\tif (stacked) {\n\t\tresult += STACKED_SEP;\n\t}\n\tresult += prefix + msg + suffix;\n\tdelete []buffer;\n\tif (priority < 0) {\n\t\tif (exc.empty()) {\n\t\t\tresult += DARK_GREY + traceback(file, line) + NO_COL;\n\t\t} else {\n\t\t\tresult += NO_COL + exc + NO_COL;\n\t\t}\n\t}\n\treturn result;\n}\n\n\nLogWrapper\nLog::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)\n{\n\tva_list argptr;\n\tva_start(argptr, format);\n\tstd::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr));\n\tva_end(argptr);\n\n\treturn print(str, clean, stacked, wakeup, priority);\n}\n\n\nbool\nLog::clear()\n{\n\treturn finished.exchange(true);\n}\n\n\nbool\nLog::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)\n{\n\tif (finished.exchange(true)) {\n\t\tva_list argptr;\n\t\tva_start(argptr, format);\n\t\tstd::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr));\n\t\tva_end(argptr);\n\n\t\tprint(str, false, stacked, 0, priority, created_at);\n\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nLogWrapper\nLog::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)\n{\n\tauto l_ptr = std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at);\n\n\tstatic LogThread& thread = _thread();\n\tthread.add(l_ptr);\n\n\treturn LogWrapper(l_ptr);\n}\n\n\nvoid\nLog::log(int priority, const std::string& str)\n{\n\tstatic std::mutex log_mutex;\n\tstd::lock_guard<std::mutex> lk(log_mutex);\n\tstatic auto& handlers = _handlers();\n\tfor (auto& handler : handlers) {\n\t\thandler->log(priority, str);\n\t}\n}\n\n\nLogWrapper\nLog::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)\n{\n\tstatic auto& log_level = _log_level();\n\tif (priority > log_level) {\n\t\treturn LogWrapper(std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at));\n\t}\n\n\tstatic auto& handlers = _handlers();\n\tif (!handlers.size()) {\n\t\thandlers.push_back(std::make_unique<StderrLogger>());\n\t}\n\n\tif (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {\n\t\treturn add(str, clean, stacked, wakeup, priority, created_at);\n\t} else {\n\t\tlog(priority, str);\n\t\treturn LogWrapper(std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at));\n\t}\n}\n\n\nvoid\nLog::finish(int wait)\n{\n\tstatic LogThread& thread = _thread();\n\tthread.finish(wait);\n}\n\n\nLogThread::LogThread()\n\t: running(-1),\n\t inner_thread(&LogThread::thread_function, this, std::ref(log_list)) { }\n\n\nLogThread::~LogThread()\n{\n\tfinish(true);\n}\n\n\nvoid\nLogThread::finish(int wait)\n{\n\trunning = wait;\n\twakeup_signal.notify_all();\n\tif (wait) {\n\t\ttry {\n\t\t\tinner_thread.join();\n\t\t} catch (const std::system_error&) { }\n\t}\n}\n\n\nvoid\nLogThread::add(const std::shared_ptr<Log>& l_ptr)\n{\n\tif (running != 0) {\n\t\tlog_list.push_back(l_ptr);\n\n\t\tif (std::chrono::system_clock::from_time_t(wakeup) >= l_ptr->wakeup) {\n\t\t\twakeup_signal.notify_all();\n\t\t}\n\t}\n}\n\n\nvoid\nLogThread::thread_function(DLList<const std::shared_ptr<Log>>& _log_list)\n{\n\tstd::mutex mtx;\n\tstd::unique_lock<std::mutex> lk(mtx);\n\n\tauto now = std::chrono::system_clock::now();\n\tauto next_wakeup = now + 3s;\n\n\twhile (running != 0) {\n\t\tif (--running < 0) {\n\t\t\trunning = -1;\n\t\t}\n\n\t\twakeup = std::chrono::system_clock::to_time_t(next_wakeup);\n\t\twakeup_signal.wait_until(lk, next_wakeup);\n\n\t\tnow = std::chrono::system_clock::now();\n\t\tnext_wakeup = now + (running < 0 ? 3s : 100ms);\n\n\t\tfor (auto it = _log_list.begin(); it != _log_list.end(); ) {\n\t\t\tauto& l_ptr = *it;\n\t\t\tif (l_ptr->finished) {\n\t\t\t\tit = _log_list.erase(it);\n\t\t\t} else if (l_ptr->wakeup <= now) {\n\t\t\t\tl_ptr->finished = true;\n\t\t\t\tauto msg = l_ptr->str_start;\n\t\t\t\tauto age = l_ptr->age();\n\t\t\t\tif (age > 2e8) {\n\t\t\t\t\tmsg += \" ~\" + delta_string(age, true);\n\t\t\t\t}\n\t\t\t\tif (l_ptr->stacked) {\n\t\t\t\t\tmsg.replace(msg.find(STACKED_SEP), sizeof(STACKED_SEP) - 1, std::string(l_ptr->stack_level * 2, ' '));\n\t\t\t\t}\n\t\t\t\tLog::log(l_ptr->priority, msg);\n\t\t\t\tit = _log_list.erase(it);\n\t\t\t} else if (next_wakeup > l_ptr->wakeup) {\n\t\t\t\tnext_wakeup = l_ptr->wakeup;\n\t\t\t\t++it;\n\t\t\t} else {\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\n\t\tif (next_wakeup < now + 100ms) {\n\t\t\tnext_wakeup = now + 100ms;\n\t\t}\n\n\t\tif (running >= 0 && !log_list.size()) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<commit_msg>Do not print delta time (for the moment)<commit_after>\/*\n * Copyright (C) 2015,2016 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"log.h\"\n\n#include \"datetime.h\"\n#include \"utils.h\"\n\n#include <stdarg.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define BUFFER_SIZE (10 * 1024)\n#define STACKED_SEP \"<sep>\"\n\n\nconst std::regex filter_re(\"\\033\\\\[[;\\\\d]*m\");\nstd::mutex Log::stack_mtx;\nstd::unordered_map<std::thread::id, unsigned> Log::stack_levels;\n\n\nconst char *priorities[] = {\n\tEMERG_COL \"█\" NO_COL, \/\/ LOG_EMERG 0 = System is unusable\n\tALERT_COL \"▉\" NO_COL, \/\/ LOG_ALERT 1 = Action must be taken immediately\n\tCRIT_COL \"▊\" NO_COL, \/\/ LOG_CRIT 2 = Critical conditions\n\tERR_COL \"▋\" NO_COL, \/\/ LOG_ERR 3 = Error conditions\n\tWARNING_COL \"▌\" NO_COL, \/\/ LOG_WARNING 4 = Warning conditions\n\tNOTICE_COL \"▍\" NO_COL, \/\/ LOG_NOTICE 5 = Normal but significant condition\n\tINFO_COL \"▎\" NO_COL, \/\/ LOG_INFO 6 = Informational\n\tDEBUG_COL \"▏\" NO_COL, \/\/ LOG_DEBUG 7 = Debug-level messages\n};\n\n\nvoid\nStreamLogger::log(int priority, const std::string& str)\n{\n\tofs << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\") << std::endl;\n}\n\n\nvoid\nStderrLogger::log(int priority, const std::string& str)\n{\n\tif (isatty(fileno(stderr))) {\n\t\tstd::cerr << priorities[priority < 0 ? -priority : priority] + str << std::endl;\n\t} else {\n\t\tstd::cerr << std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\") << std::endl;\n\t}\n}\n\n\nSysLog::SysLog(const char *ident, int option, int facility)\n{\n\topenlog(ident, option, facility);\n}\n\n\nSysLog::~SysLog()\n{\n\tcloselog();\n}\n\n\nvoid\nSysLog::log(int priority, const std::string& str)\n{\n\tsyslog(priority, \"%s\", std::regex_replace(priorities[priority < 0 ? -priority : priority] + str, filter_re, \"\").c_str());\n}\n\n\nLog::Log(const std::string& str, bool clean_, bool stacked_, std::chrono::time_point<std::chrono::system_clock> wakeup_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)\n\t: stack_level(0),\n\t stacked(stacked_),\n\t clean(clean_),\n\t created_at(created_at_),\n\t wakeup(wakeup_),\n\t str_start(str),\n\t priority(priority_),\n\t finished(false),\n\t cleaned(false) {\n\n\tif (stacked) {\n\t\tstd::lock_guard<std::mutex> lk(stack_mtx);\n\t\tthread_id = std::this_thread::get_id();\n\t\ttry {\n\t\t\tstack_level = ++stack_levels.at(thread_id);\n\t\t} catch (const std::out_of_range&) {\n\t\t\tstack_levels[thread_id] = 0;\n\t\t}\n\t}\n}\n\nLog::~Log()\n{\n\tcleanup();\n}\n\n\nvoid\nLog::cleanup()\n{\n\tbool f = false;\n\tfinished.compare_exchange_strong(f, clean);\n\n\tif (!cleaned.exchange(true)) {\n\t\tif (stacked) {\n\t\t\tstd::lock_guard<std::mutex> lk(stack_mtx);\n\t\t\tif (stack_levels.at(thread_id)-- == 0) {\n\t\t\t\tstack_levels.erase(thread_id);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nlong double\nLog::age()\n{\n\treturn std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - created_at).count();\n}\n\n\n\/*\n * https:\/\/isocpp.org\/wiki\/faq\/ctors#static-init-order\n * Avoid the \"static initialization order fiasco\"\n *\/\n\nLogThread&\nLog::_thread()\n{\n\tstatic LogThread* thread = new LogThread();\n\treturn *thread;\n}\n\n\nint&\nLog::_log_level()\n{\n\tstatic auto* log_level = new int(DEFAULT_LOG_LEVEL);\n\treturn *log_level;\n}\n\n\nDLList<const std::unique_ptr<Logger>>&\nLog::_handlers()\n{\n\tstatic auto* handlers = new DLList<const std::unique_ptr<Logger>>();\n\treturn *handlers;\n}\n\n\nstd::string\nLog::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr)\n{\n\tchar* buffer = new char[BUFFER_SIZE];\n\tvsnprintf(buffer, BUFFER_SIZE, format, argptr);\n\tstd::string msg(buffer);\n\tauto iso8601 = \"[\" + Datetime::to_string(std::chrono::system_clock::now()) + \"]\";\n\tauto tid = \" (\" + get_thread_name() + \")\";\n\tstd::string result = iso8601 + tid;\n#ifdef LOG_OBJ_ADDRESS\n\tif (obj) {\n\t\tsnprintf(buffer, BUFFER_SIZE, \" [%p]\", obj);\n\t\tresult += buffer;\n\t}\n#endif\n#ifdef TRACEBACK\n\tauto location = (priority >= LOCATION_LOG_LEVEL) ? \" \" + std::string(file) + \":\" + std::to_string(line) : std::string();\n\tresult += location + \": \";\n#else\n\tresult += \" \";\n\t(void)obj;\n#endif\n\tif (stacked) {\n\t\tresult += STACKED_SEP;\n\t}\n\tresult += prefix + msg + suffix;\n\tdelete []buffer;\n\tif (priority < 0) {\n\t\tif (exc.empty()) {\n\t\t\tresult += DARK_GREY + traceback(file, line) + NO_COL;\n\t\t} else {\n\t\t\tresult += NO_COL + exc + NO_COL;\n\t\t}\n\t}\n\treturn result;\n}\n\n\nLogWrapper\nLog::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)\n{\n\tva_list argptr;\n\tva_start(argptr, format);\n\tstd::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr));\n\tva_end(argptr);\n\n\treturn print(str, clean, stacked, wakeup, priority);\n}\n\n\nbool\nLog::clear()\n{\n\treturn finished.exchange(true);\n}\n\n\nbool\nLog::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)\n{\n\tif (finished.exchange(true)) {\n\t\tva_list argptr;\n\t\tva_start(argptr, format);\n\t\tstd::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr));\n\t\tva_end(argptr);\n\n\t\tprint(str, false, stacked, 0, priority, created_at);\n\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nLogWrapper\nLog::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)\n{\n\tauto l_ptr = std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at);\n\n\tstatic LogThread& thread = _thread();\n\tthread.add(l_ptr);\n\n\treturn LogWrapper(l_ptr);\n}\n\n\nvoid\nLog::log(int priority, const std::string& str)\n{\n\tstatic std::mutex log_mutex;\n\tstd::lock_guard<std::mutex> lk(log_mutex);\n\tstatic auto& handlers = _handlers();\n\tfor (auto& handler : handlers) {\n\t\thandler->log(priority, str);\n\t}\n}\n\n\nLogWrapper\nLog::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)\n{\n\tstatic auto& log_level = _log_level();\n\tif (priority > log_level) {\n\t\treturn LogWrapper(std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at));\n\t}\n\n\tstatic auto& handlers = _handlers();\n\tif (!handlers.size()) {\n\t\thandlers.push_back(std::make_unique<StderrLogger>());\n\t}\n\n\tif (priority >= ASYNC_LOG_LEVEL || wakeup > std::chrono::system_clock::now()) {\n\t\treturn add(str, clean, stacked, wakeup, priority, created_at);\n\t} else {\n\t\tlog(priority, str);\n\t\treturn LogWrapper(std::make_shared<Log>(str, clean, stacked, wakeup, priority, created_at));\n\t}\n}\n\n\nvoid\nLog::finish(int wait)\n{\n\tstatic LogThread& thread = _thread();\n\tthread.finish(wait);\n}\n\n\nLogThread::LogThread()\n\t: running(-1),\n\t inner_thread(&LogThread::thread_function, this, std::ref(log_list)) { }\n\n\nLogThread::~LogThread()\n{\n\tfinish(true);\n}\n\n\nvoid\nLogThread::finish(int wait)\n{\n\trunning = wait;\n\twakeup_signal.notify_all();\n\tif (wait) {\n\t\ttry {\n\t\t\tinner_thread.join();\n\t\t} catch (const std::system_error&) { }\n\t}\n}\n\n\nvoid\nLogThread::add(const std::shared_ptr<Log>& l_ptr)\n{\n\tif (running != 0) {\n\t\tlog_list.push_back(l_ptr);\n\n\t\tif (std::chrono::system_clock::from_time_t(wakeup) >= l_ptr->wakeup) {\n\t\t\twakeup_signal.notify_all();\n\t\t}\n\t}\n}\n\n\nvoid\nLogThread::thread_function(DLList<const std::shared_ptr<Log>>& _log_list)\n{\n\tstd::mutex mtx;\n\tstd::unique_lock<std::mutex> lk(mtx);\n\n\tauto now = std::chrono::system_clock::now();\n\tauto next_wakeup = now + 3s;\n\n\twhile (running != 0) {\n\t\tif (--running < 0) {\n\t\t\trunning = -1;\n\t\t}\n\n\t\twakeup = std::chrono::system_clock::to_time_t(next_wakeup);\n\t\twakeup_signal.wait_until(lk, next_wakeup);\n\n\t\tnow = std::chrono::system_clock::now();\n\t\tnext_wakeup = now + (running < 0 ? 3s : 100ms);\n\n\t\tfor (auto it = _log_list.begin(); it != _log_list.end(); ) {\n\t\t\tauto& l_ptr = *it;\n\t\t\tif (l_ptr->finished) {\n\t\t\t\tit = _log_list.erase(it);\n\t\t\t} else if (l_ptr->wakeup <= now) {\n\t\t\t\tl_ptr->finished = true;\n\t\t\t\tauto msg = l_ptr->str_start;\n\t\t\t\tif (l_ptr->stacked) {\n\t\t\t\t\tmsg.replace(msg.find(STACKED_SEP), sizeof(STACKED_SEP) - 1, std::string(l_ptr->stack_level * 2, ' '));\n\t\t\t\t}\n\t\t\t\t\/\/ auto age = l_ptr->age();\n\t\t\t\t\/\/ if (age > 2e8) {\n\t\t\t\t\/\/ \tmsg += \" ~\" + delta_string(age, true);\n\t\t\t\t\/\/ }\n\t\t\t\tLog::log(l_ptr->priority, msg);\n\t\t\t\tit = _log_list.erase(it);\n\t\t\t} else if (next_wakeup > l_ptr->wakeup) {\n\t\t\t\tnext_wakeup = l_ptr->wakeup;\n\t\t\t\t++it;\n\t\t\t} else {\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\n\t\tif (next_wakeup < now + 100ms) {\n\t\t\tnext_wakeup = now + 100ms;\n\t\t}\n\n\t\tif (running >= 0 && !log_list.size()) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <mpd\/client.h>\n#include <memory>\n#include \"consumer.hh\"\n\nclass connection : public std::unique_ptr<mpd_connection,\n void (*)(mpd_connection*)> {\n template <class Fun, class Con, class... Args>\n static auto wrap_error(Fun f, Con con, Args&&... args)\n -> decltype(f(con, std::forward<Args>(args)...)) {\n auto x = f(con, std::forward<Args>(args)...);\n if (!x) {\n throw std::runtime_error(\n mpd_connection_get_error_message(con));\n }\n return x;\n }\n\n using super = std::unique_ptr<mpd_connection,\n void (*)(mpd_connection*)>;\n\npublic:\n connection(const char* name, int port, int delay)\n : super(mpd_connection_new(name, port, delay),\n mpd_connection_free) {}\n void run_clear() {\n wrap_error(mpd_run_clear, get());\n }\n\n void run_update(const char* path = nullptr) {\n wrap_error(mpd_run_update, get(), path);\n }\n};\nvoid Consumer::_run_mpd_() {\n connection con(\"localhost\", 6600, 1000);\n con.run_clear();\n con.run_update();\n for (const auto& s : _playlist_lines_) {\n if (!mpd_run_add(con.get(), s.c_str())) {\n fprintf(stderr, \"ERROR adding file: %s\\n\", s.c_str());\n }\n }\n}\n<commit_msg>Make mpd class local to mpd.cc<commit_after>#include <mpd\/client.h>\n#include <memory>\n#include \"consumer.hh\"\n\nnamespace {\nclass connection : public std::unique_ptr<mpd_connection,\n void (*)(mpd_connection*)> {\n template <class Fun, class Con, class... Args>\n static auto wrap_error(Fun f, Con con, Args&&... args)\n -> decltype(f(con, std::forward<Args>(args)...)) {\n auto x = f(con, std::forward<Args>(args)...);\n if (!x) {\n throw std::runtime_error(\n mpd_connection_get_error_message(con));\n }\n return x;\n }\n\n using super = std::unique_ptr<mpd_connection,\n void (*)(mpd_connection*)>;\n\npublic:\n connection(const char* name, int port, int delay)\n : super(mpd_connection_new(name, port, delay),\n mpd_connection_free) {}\n void run_clear() {\n wrap_error(mpd_run_clear, get());\n }\n\n void run_update(const char* path = nullptr) {\n wrap_error(mpd_run_update, get(), path);\n }\n};\n}\n\nvoid Consumer::_run_mpd_() {\n connection con(\"localhost\", 6600, 1000);\n con.run_clear();\n con.run_update();\n for (const auto& s : _playlist_lines_) {\n if (!mpd_run_add(con.get(), s.c_str())) {\n fprintf(stderr, \"ERROR adding file: %s\\n\", s.c_str());\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n\t@file\r\n\t@author\t\tEvmenov Georgiy\r\n\t@date\t\t01\/2008\r\n\t@module\r\n*\/\r\n\r\n#include \"RenderBoxScene.h\"\r\n\r\nnamespace wraps\r\n{\r\n\r\n\tRenderBoxScene::RenderBoxScene() :\r\n\t\tmCameraNode(nullptr),\r\n\t\tmCamera(nullptr),\r\n\t\tmEntity(nullptr),\r\n\t\tmAnimationState(nullptr),\r\n\t\tmRotationSpeed(RENDER_BOX_AUTO_ROTATION_SPEED),\r\n\t\tmMouseRotation(false),\r\n\t\tmLastPointerX(0),\r\n\t\tmLeftPressed(false),\r\n\t\tmAutoRotation(false),\r\n\t\tmFrameAdvise(false),\r\n\t\tmScene(nullptr),\r\n\t\tmNode(nullptr)\r\n\t{\r\n\t}\r\n\r\n\tRenderBoxScene::~RenderBoxScene()\r\n\t{\r\n\t}\r\n\r\n\tvoid RenderBoxScene::destroy()\r\n\t{\r\n\t\tclearScene();\r\n\r\n\t\tif (mCanvas)\r\n\t\t{\r\n\t\t\tframeAdvise(false);\r\n\r\n\t\t\tmCanvas->eventMouseDrag = nullptr;\r\n\t\t\tmCanvas->eventMouseButtonPressed = nullptr;\r\n\t\t\tmCanvas->eventMouseButtonReleased = nullptr;\r\n\r\n\t\t\tOgre::Root* root = Ogre::Root::getSingletonPtr();\r\n\t\t\tif (root && mScene)\r\n\t\t\t\troot->destroySceneManager(mScene);\r\n\t\t\tmScene= nullptr;\r\n\t\t}\r\n\r\n\t\tRenderBox::destroy();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setCanvas(MyGUI::CanvasPtr _value)\r\n\t{\r\n\t\tRenderBox::setCanvas(_value);\r\n\r\n\t\tmCanvas->eventMouseDrag = newDelegate(this, &RenderBoxScene::notifyMouseDrag);\r\n\t\tmCanvas->eventMouseButtonPressed = newDelegate(this, &RenderBoxScene::notifyMouseButtonPressed);\r\n\t\tmCanvas->eventMouseButtonReleased = newDelegate(this, &RenderBoxScene::notifyMouseButtonReleased);\r\n\r\n\t\tcreateScene();\r\n\t}\r\n\r\n\t\/\/ , \r\n\tvoid RenderBoxScene::injectObject(const Ogre::String& _meshName, const Ogre::Vector3 & _position, const Ogre::Quaternion & _orientation, const Ogre::Vector3 & _scale)\r\n\t{\r\n\t\tclearScene();\r\n\r\n\t\tstatic size_t num = 0;\r\n\t\tmEntity = mScene->createEntity(MyGUI::utility::toString(this, \"_RenderBoxMesh_\", _meshName, num++), _meshName);\r\n\t\tOgre::SceneNode * node = mNode->createChildSceneNode(_position, _orientation);\r\n\t\tnode->attachObject(mEntity);\r\n\r\n\t\tupdateViewport();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAnimation(const Ogre::String& _animation)\r\n\t{\r\n\t\tif (mEntity == nullptr)\r\n\t\t\treturn;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tmAnimationState = mEntity->getAnimationState(_animation);\r\n\t\t\tmAnimationState->setEnabled(true);\r\n\t\t\tmAnimationState->setLoop(true);\r\n\t\t\tmAnimationState->setWeight(1);\r\n\t\t}\r\n\t\tcatch (Ogre::ItemIdentityException&)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tframeAdvise(needFrameUpdate());\r\n\t}\r\n\r\n\t\/\/ \r\n\tvoid RenderBoxScene::clearScene()\r\n\t{\r\n\t\tsetRotationAngle(Ogre::Degree(0));\r\n\r\n\t\tif (mScene)\r\n\t\t{\r\n\t\t\tmScene->destroyAllEntities();\r\n\t\t\tmNode->removeAndDestroyAllChildren();\r\n\t\t}\r\n\r\n\t\tmEntity = nullptr;\r\n\t\tmAnimationState = nullptr;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAutoRotationSpeed(int _value)\r\n\t{\r\n\t\tmRotationSpeed = _value;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setRotationAngle(const Ogre::Degree& _value)\r\n\t{\r\n\t\tif (mNode)\r\n\t\t{\r\n\t\t\tmNode->resetOrientation();\r\n\t\t\tmNode->yaw(Ogre::Radian(_value));\r\n\t\t}\r\n\t}\r\n\r\n\tOgre::Degree RenderBoxScene::getRotationAngle()\r\n\t{\r\n\t\treturn Ogre::Degree(mNode->getOrientation().getYaw());\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setMouseRotation(bool _enable)\r\n\t{\r\n\t\tmMouseRotation = _enable;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::frameEntered(float _time)\r\n\t{\r\n\t\tif (!mLeftPressed)\r\n\t\t{\r\n\t\t\tif (mAutoRotation)\r\n\t\t\t\tmNode->yaw(Ogre::Radian(Ogre::Degree(_time * mRotationSpeed)));\r\n\t\t}\r\n\t\tif (mAnimationState)\r\n\t\t\tmAnimationState->addTime(_time);\r\n\t}\r\n\r\n\tvoid RenderBoxScene::createScene()\r\n\t{\r\n\t\t\/\/ \r\n\t\tmScene = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, MyGUI::utility::toString(this, \"_SceneManagerRenderBox\"));\r\n\r\n\t\t\/\/ \r\n\t\tmNode = mScene->getRootSceneNode()->createChildSceneNode();\r\n\r\n\t\tmScene->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8));\r\n\r\n\t\t\/\/ \r\n\t\tOgre::Vector3 dir(-1, -1, 0.5);\r\n\t\tdir.normalise();\r\n\t\tOgre::Light * light = mScene->createLight(MyGUI::utility::toString(this, \"_LightRenderBox\"));\r\n\t\tlight->setType(Ogre::Light::LT_DIRECTIONAL);\r\n\t\tlight->setDirection(dir);\r\n\r\n\t\tstd::string camera(MyGUI::utility::toString(this, \"_CameraRenderBox\"));\r\n\t\tmCamera = mScene->createCamera(camera);\r\n\t\tmCamera->setNearClipDistance(1);\r\n\r\n\t\tmCameraNode = mScene->getRootSceneNode()->createChildSceneNode(camera);\r\n\t\tmCameraNode->attachObject(mCamera);\r\n\r\n\t\tif (mCanvas->getHeight() == 0)\r\n\t\t\tmCamera->setAspectRatio(1);\r\n\t\telse\r\n\t\t\tmCamera->setAspectRatio( float(mCanvas->getWidth()) \/ float(mCanvas->getHeight()) );\r\n\r\n\t\tsetViewport(mCamera);\r\n\t}\r\n\r\n\tvoid RenderBoxScene::updateViewport()\r\n\t{\r\n\t\t\/\/ \r\n\t\tif ((mCanvas->getWidth() <= 1) || (mCanvas->getHeight() <= 1))\r\n\t\t\treturn;\r\n\r\n\t\tif ((nullptr != mEntity) && (nullptr != mCamera))\r\n\t\t{\r\n\t\t\t\/\/ , , \r\n\t\t\tmCamera->setAspectRatio((float)mCanvas->getWidth() \/ (float)mCanvas->getHeight());\r\n\r\n\t\t\t\/\/ , \r\n\t\t\tOgre::AxisAlignedBox box;\r\n\r\n\t\t\tbox.merge(mEntity->getBoundingBox().getMinimum() + mEntity->getParentSceneNode()->_getDerivedPosition());\r\n\t\t\tbox.merge(mEntity->getBoundingBox().getMaximum() + mEntity->getParentSceneNode()->_getDerivedPosition());\r\n\r\n\t\t\tif (box.isNull()) return;\r\n\r\n\t\t\tOgre::Vector3 vec = box.getSize();\r\n\r\n\t\t\tfloat width = sqrt(vec.x*vec.x + vec.z*vec.z); \/\/ - ( )\r\n\t\t\tfloat len2 = width \/ mCamera->getAspectRatio();\r\n\t\t\tfloat height = vec.y;\r\n\t\t\tfloat len1 = height;\r\n\t\t\tif (len1 < len2) len1 = len2;\r\n\t\t\tlen1 \/= 0.86; \/\/ [sqrt(3)\/2] for 60 degrees field of view\r\n\t\t\t\/\/ + , BoundingBox' + \r\n\t\t\tOgre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z\/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);\r\n\t\t\tOgre::Vector3 look = Ogre::Vector3(0, box.getCenter().y \/*+ box.getCenter().y * (1-mCurrentScale)*\/, 0);\r\n\r\n\t\t\tmCameraNode->setPosition(result);\r\n\t\t\tmCameraNode->lookAt(look, Ogre::Node::TS_WORLD);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAutoRotation(bool _auto)\r\n\t{\r\n\t\tmAutoRotation = _auto;\r\n\t\tframeAdvise(needFrameUpdate());\r\n\t}\r\n\r\n\tvoid RenderBoxScene::requestUpdateCanvas(MyGUI::CanvasPtr _canvas, MyGUI::Canvas::Event _event)\r\n\t{\r\n\t\tRenderBox::requestUpdateCanvas(_canvas, _event);\r\n\r\n\t\tupdateViewport();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::frameAdvise(bool _advise)\r\n\t{\r\n\t\tif (_advise && !mFrameAdvise && needFrameUpdate())\r\n\t\t{\r\n\t\t\tMyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate(this, &RenderBoxScene::frameEntered);\r\n\t\t\tmFrameAdvise = true;\r\n\t\t}\r\n\t\telse if (!_advise && mFrameAdvise && !needFrameUpdate())\r\n\t\t{\r\n\t\t\tMyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate(this, &RenderBoxScene::frameEntered);\r\n\t\t\tmFrameAdvise = false;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseDrag(MyGUI::WidgetPtr _sender, int _left, int _top)\r\n\t{\r\n\t\tif (mMouseRotation)\r\n\t\t{\r\n\t\t\tmNode->yaw(Ogre::Radian(Ogre::Degree(_left - mLastPointerX)));\r\n\t\t\tmLastPointerX = _left;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseButtonPressed(MyGUI::WidgetPtr _sender, int _left, int _top, MyGUI::MouseButton _id)\r\n\t{\r\n\t\tif (_id == MyGUI::MouseButton::Left)\r\n\t\t{\r\n\t\t\tif (mMouseRotation)\r\n\t\t\t{\r\n\t\t\t\tconst MyGUI::IntPoint & point = MyGUI::InputManager::getInstance().getLastLeftPressed();\r\n\t\t\t\tmLastPointerX = point.left;\r\n\t\t\t\tmLeftPressed = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseButtonReleased(MyGUI::WidgetPtr _sender, int _left, int _top, MyGUI::MouseButton _id)\r\n\t{\r\n\t\tif (MyGUI::MouseButton::Left == _id) mLeftPressed = false;\r\n\t}\r\n\r\n} \/\/ namespace wraps\r\n<commit_msg>fix RenderBoxScene<commit_after>\/*!\r\n\t@file\r\n\t@author\t\tEvmenov Georgiy\r\n\t@date\t\t01\/2008\r\n\t@module\r\n*\/\r\n\r\n#include \"RenderBoxScene.h\"\r\n\r\nnamespace wraps\r\n{\r\n\r\n\tRenderBoxScene::RenderBoxScene() :\r\n\t\tmCameraNode(nullptr),\r\n\t\tmCamera(nullptr),\r\n\t\tmEntity(nullptr),\r\n\t\tmAnimationState(nullptr),\r\n\t\tmRotationSpeed(RENDER_BOX_AUTO_ROTATION_SPEED),\r\n\t\tmMouseRotation(false),\r\n\t\tmLastPointerX(0),\r\n\t\tmLeftPressed(false),\r\n\t\tmAutoRotation(false),\r\n\t\tmFrameAdvise(false),\r\n\t\tmScene(nullptr),\r\n\t\tmNode(nullptr)\r\n\t{\r\n\t}\r\n\r\n\tRenderBoxScene::~RenderBoxScene()\r\n\t{\r\n\t}\r\n\r\n\tvoid RenderBoxScene::destroy()\r\n\t{\r\n\t\tclearScene();\r\n\r\n\t\tif (mCanvas)\r\n\t\t{\r\n\t\t\tframeAdvise(false);\r\n\r\n\t\t\tmCanvas->eventMouseDrag = nullptr;\r\n\t\t\tmCanvas->eventMouseButtonPressed = nullptr;\r\n\t\t\tmCanvas->eventMouseButtonReleased = nullptr;\r\n\t\t\tmCanvas = nullptr;\r\n\r\n\t\t\tOgre::Root* root = Ogre::Root::getSingletonPtr();\r\n\t\t\tif (root && mScene)\r\n\t\t\t\troot->destroySceneManager(mScene);\r\n\t\t\tmScene = nullptr;\r\n\t\t\tmNode = nullptr;\r\n\t\t}\r\n\r\n\t\tRenderBox::destroy();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setCanvas(MyGUI::CanvasPtr _value)\r\n\t{\r\n\t\tRenderBox::setCanvas(_value);\r\n\r\n\t\tmCanvas->eventMouseDrag = newDelegate(this, &RenderBoxScene::notifyMouseDrag);\r\n\t\tmCanvas->eventMouseButtonPressed = newDelegate(this, &RenderBoxScene::notifyMouseButtonPressed);\r\n\t\tmCanvas->eventMouseButtonReleased = newDelegate(this, &RenderBoxScene::notifyMouseButtonReleased);\r\n\r\n\t\tcreateScene();\r\n\t}\r\n\r\n\t\/\/ , \r\n\tvoid RenderBoxScene::injectObject(const Ogre::String& _meshName, const Ogre::Vector3 & _position, const Ogre::Quaternion & _orientation, const Ogre::Vector3 & _scale)\r\n\t{\r\n\t\tclearScene();\r\n\r\n\t\tstatic size_t num = 0;\r\n\t\tmEntity = mScene->createEntity(MyGUI::utility::toString(this, \"_RenderBoxMesh_\", _meshName, num++), _meshName);\r\n\t\tOgre::SceneNode * node = mNode->createChildSceneNode(_position, _orientation);\r\n\t\tnode->attachObject(mEntity);\r\n\r\n\t\tupdateViewport();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAnimation(const Ogre::String& _animation)\r\n\t{\r\n\t\tif (mEntity == nullptr)\r\n\t\t\treturn;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tmAnimationState = mEntity->getAnimationState(_animation);\r\n\t\t\tmAnimationState->setEnabled(true);\r\n\t\t\tmAnimationState->setLoop(true);\r\n\t\t\tmAnimationState->setWeight(1);\r\n\t\t}\r\n\t\tcatch (Ogre::ItemIdentityException&)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tframeAdvise(needFrameUpdate());\r\n\t}\r\n\r\n\t\/\/ \r\n\tvoid RenderBoxScene::clearScene()\r\n\t{\r\n\t\tsetRotationAngle(Ogre::Degree(0));\r\n\r\n\t\tif (mScene)\r\n\t\t{\r\n\t\t\tmScene->destroyAllEntities();\r\n\t\t\tmNode->removeAndDestroyAllChildren();\r\n\t\t}\r\n\r\n\t\tmEntity = nullptr;\r\n\t\tmAnimationState = nullptr;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAutoRotationSpeed(int _value)\r\n\t{\r\n\t\tmRotationSpeed = _value;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setRotationAngle(const Ogre::Degree& _value)\r\n\t{\r\n\t\tif (mNode)\r\n\t\t{\r\n\t\t\tmNode->resetOrientation();\r\n\t\t\tmNode->yaw(Ogre::Radian(_value));\r\n\t\t}\r\n\t}\r\n\r\n\tOgre::Degree RenderBoxScene::getRotationAngle()\r\n\t{\r\n\t\treturn Ogre::Degree(mNode->getOrientation().getYaw());\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setMouseRotation(bool _enable)\r\n\t{\r\n\t\tmMouseRotation = _enable;\r\n\t}\r\n\r\n\tvoid RenderBoxScene::frameEntered(float _time)\r\n\t{\r\n\t\tif (!mLeftPressed)\r\n\t\t{\r\n\t\t\tif (mAutoRotation && mNode)\r\n\t\t\t\tmNode->yaw(Ogre::Radian(Ogre::Degree(_time * mRotationSpeed)));\r\n\t\t}\r\n\t\tif (mAnimationState)\r\n\t\t\tmAnimationState->addTime(_time);\r\n\t}\r\n\r\n\tvoid RenderBoxScene::createScene()\r\n\t{\r\n\t\t\/\/ \r\n\t\tmScene = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, MyGUI::utility::toString(this, \"_SceneManagerRenderBox\"));\r\n\r\n\t\t\/\/ \r\n\t\tmNode = mScene->getRootSceneNode()->createChildSceneNode();\r\n\r\n\t\tmScene->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8));\r\n\r\n\t\t\/\/ \r\n\t\tOgre::Vector3 dir(-1, -1, 0.5);\r\n\t\tdir.normalise();\r\n\t\tOgre::Light * light = mScene->createLight(MyGUI::utility::toString(this, \"_LightRenderBox\"));\r\n\t\tlight->setType(Ogre::Light::LT_DIRECTIONAL);\r\n\t\tlight->setDirection(dir);\r\n\r\n\t\tstd::string camera(MyGUI::utility::toString(this, \"_CameraRenderBox\"));\r\n\t\tmCamera = mScene->createCamera(camera);\r\n\t\tmCamera->setNearClipDistance(1);\r\n\r\n\t\tmCameraNode = mScene->getRootSceneNode()->createChildSceneNode(camera);\r\n\t\tmCameraNode->attachObject(mCamera);\r\n\r\n\t\tif (mCanvas->getHeight() == 0)\r\n\t\t\tmCamera->setAspectRatio(1);\r\n\t\telse\r\n\t\t\tmCamera->setAspectRatio( float(mCanvas->getWidth()) \/ float(mCanvas->getHeight()) );\r\n\r\n\t\tsetViewport(mCamera);\r\n\t}\r\n\r\n\tvoid RenderBoxScene::updateViewport()\r\n\t{\r\n\t\t\/\/ \r\n\t\tif ((mCanvas->getWidth() <= 1) || (mCanvas->getHeight() <= 1))\r\n\t\t\treturn;\r\n\r\n\t\tif ((nullptr != mEntity) && (nullptr != mCamera))\r\n\t\t{\r\n\t\t\t\/\/ , , \r\n\t\t\tmCamera->setAspectRatio((float)mCanvas->getWidth() \/ (float)mCanvas->getHeight());\r\n\r\n\t\t\t\/\/ , \r\n\t\t\tOgre::AxisAlignedBox box;\r\n\r\n\t\t\tbox.merge(mEntity->getBoundingBox().getMinimum() + mEntity->getParentSceneNode()->_getDerivedPosition());\r\n\t\t\tbox.merge(mEntity->getBoundingBox().getMaximum() + mEntity->getParentSceneNode()->_getDerivedPosition());\r\n\r\n\t\t\tif (box.isNull()) return;\r\n\r\n\t\t\tOgre::Vector3 vec = box.getSize();\r\n\r\n\t\t\tfloat width = sqrt(vec.x*vec.x + vec.z*vec.z); \/\/ - ( )\r\n\t\t\tfloat len2 = width \/ mCamera->getAspectRatio();\r\n\t\t\tfloat height = vec.y;\r\n\t\t\tfloat len1 = height;\r\n\t\t\tif (len1 < len2) len1 = len2;\r\n\t\t\tlen1 \/= 0.86; \/\/ [sqrt(3)\/2] for 60 degrees field of view\r\n\t\t\t\/\/ + , BoundingBox' + \r\n\t\t\tOgre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z\/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);\r\n\t\t\tOgre::Vector3 look = Ogre::Vector3(0, box.getCenter().y \/*+ box.getCenter().y * (1-mCurrentScale)*\/, 0);\r\n\r\n\t\t\tmCameraNode->setPosition(result);\r\n\t\t\tmCameraNode->lookAt(look, Ogre::Node::TS_WORLD);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::setAutoRotation(bool _auto)\r\n\t{\r\n\t\tmAutoRotation = _auto;\r\n\t\tframeAdvise(needFrameUpdate());\r\n\t}\r\n\r\n\tvoid RenderBoxScene::requestUpdateCanvas(MyGUI::CanvasPtr _canvas, MyGUI::Canvas::Event _event)\r\n\t{\r\n\t\tRenderBox::requestUpdateCanvas(_canvas, _event);\r\n\r\n\t\tupdateViewport();\r\n\t}\r\n\r\n\tvoid RenderBoxScene::frameAdvise(bool _advise)\r\n\t{\r\n\t\tif (_advise && !mFrameAdvise && needFrameUpdate())\r\n\t\t{\r\n\t\t\tMyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate(this, &RenderBoxScene::frameEntered);\r\n\t\t\tmFrameAdvise = true;\r\n\t\t}\r\n\t\telse if (!_advise && mFrameAdvise && !needFrameUpdate())\r\n\t\t{\r\n\t\t\tMyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate(this, &RenderBoxScene::frameEntered);\r\n\t\t\tmFrameAdvise = false;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseDrag(MyGUI::WidgetPtr _sender, int _left, int _top)\r\n\t{\r\n\t\tif (mMouseRotation)\r\n\t\t{\r\n\t\t\tif (mNode)\r\n\t\t\t\tmNode->yaw(Ogre::Radian(Ogre::Degree(_left - mLastPointerX)));\r\n\t\t\tmLastPointerX = _left;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseButtonPressed(MyGUI::WidgetPtr _sender, int _left, int _top, MyGUI::MouseButton _id)\r\n\t{\r\n\t\tif (_id == MyGUI::MouseButton::Left)\r\n\t\t{\r\n\t\t\tif (mMouseRotation)\r\n\t\t\t{\r\n\t\t\t\tconst MyGUI::IntPoint & point = MyGUI::InputManager::getInstance().getLastLeftPressed();\r\n\t\t\t\tmLastPointerX = point.left;\r\n\t\t\t\tmLeftPressed = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid RenderBoxScene::notifyMouseButtonReleased(MyGUI::WidgetPtr _sender, int _left, int _top, MyGUI::MouseButton _id)\r\n\t{\r\n\t\tif (MyGUI::MouseButton::Left == _id) mLeftPressed = false;\r\n\t}\r\n\r\n} \/\/ namespace wraps\r\n<|endoftext|>"} {"text":"<commit_before>#include \"ride\/projectexplorer.h\"\n\n#include <vector>\n\n#include <wx\/dir.h>\n#include <wx\/filename.h>\n\n#include \"ride\/mainwindow.h\"\n\nProjectExplorer::ProjectExplorer(MainWindow* main)\n : wxTreeCtrl(main, wxID_ANY, wxDefaultPosition, wxDefaultSize,\n wxTR_HAS_BUTTONS\n | wxTR_TWIST_BUTTONS\n | wxTR_MULTIPLE\n | wxTR_LINES_AT_ROOT\n ), main_(main) {\n UpdateColors();\n}\n\nvoid ProjectExplorer::UpdateColors() {\n const ride::Style& style = main_->settings().fonts_and_colors().default_style();\n this->SetBackgroundColour(C(style.background()));\n this->SetForegroundColour(C(style.foreground()));\n}\n\nvoid ProjectExplorer::SetFolder(const wxString& folder) {\n folder_ = folder;\n UpdateFolderStructure();\n}\n\nbool IsDiretory(const wxFileName& root, const wxString directory) {\n wxFileName temp = root;\n temp.AppendDir(directory);\n const wxString full_path = temp.GetFullPath();\n const bool ret = wxDir::Exists(full_path);\n return ret;\n}\n\nvoid ProjectExplorer::UpdateFolderStructure() {\n this->AppendItem(this->GetRootItem(), \"Project\");\n\n const int flags = wxDIR_FILES | wxDIR_DIRS; \/\/ walk files and folders\n const wxString filespec = \"\";\n\n SubUpdateFolderStructure(folder_, this->GetRootItem(), filespec, flags);\n\n this->ExpandAll();\n}\n\n\nstd::vector<wxString> TraverseFilesAndFolders(const wxFileName& root, const wxString filespec, const int flags) {\n std::vector<wxString> ret;\n const wxString root_full_path = root.GetFullPath();\n\n wxDir directory(root_full_path);\n\n directory.Open(root_full_path);\n\n wxString file_or_directory_name;\n bool cont = directory.GetFirst(&file_or_directory_name, filespec, flags);\n while (cont)\n {\n ret.push_back(file_or_directory_name);\n cont = directory.GetNext(&file_or_directory_name);\n }\n\n directory.Close();\n return ret;\n}\n\nvoid ProjectExplorer::SubUpdateFolderStructure(const wxFileName& root, wxTreeItemId parent, const wxString filespec, const int flags)\n{\n const wxString root_full_path = root.GetFullPath();\n const std::vector<wxString> files_and_folders = TraverseFilesAndFolders(root, filespec, flags);\n for (const wxString file_or_directory_name : files_and_folders)\n {\n wxTreeItemId child = this->AppendItem(parent, file_or_directory_name);\n if (IsDiretory(root, file_or_directory_name)) {\n wxFileName child_name(root);\n child_name.AppendDir(file_or_directory_name);\n SubUpdateFolderStructure(child_name, child, filespec, flags);\n }\n }\n}\n<commit_msg>Refactored some code<commit_after>#include \"ride\/projectexplorer.h\"\n\n#include <vector>\n\n#include <wx\/dir.h>\n#include <wx\/filename.h>\n\n#include \"ride\/mainwindow.h\"\n\nProjectExplorer::ProjectExplorer(MainWindow* main)\n : wxTreeCtrl(main, wxID_ANY, wxDefaultPosition, wxDefaultSize,\n wxTR_HAS_BUTTONS\n | wxTR_TWIST_BUTTONS\n | wxTR_MULTIPLE\n | wxTR_LINES_AT_ROOT\n ), main_(main) {\n UpdateColors();\n}\n\nvoid ProjectExplorer::UpdateColors() {\n const ride::Style& style = main_->settings().fonts_and_colors().default_style();\n this->SetBackgroundColour(C(style.background()));\n this->SetForegroundColour(C(style.foreground()));\n}\n\nvoid ProjectExplorer::SetFolder(const wxString& folder) {\n folder_ = folder;\n UpdateFolderStructure();\n}\n\nwxFileName SubFolder(const wxFileName& root, const wxString& sub_folder) {\n wxFileName folder(root);\n folder.AppendDir(sub_folder);\n return folder;\n}\n\nbool IsDiretory(const wxFileName& root, const wxString directory) {\n const wxFileName temp = SubFolder(root, directory);\n const wxString full_path = temp.GetFullPath();\n const bool ret = wxDir::Exists(full_path);\n return ret;\n}\n\nvoid ProjectExplorer::UpdateFolderStructure() {\n this->AppendItem(this->GetRootItem(), \"Project\");\n\n const int flags = wxDIR_FILES | wxDIR_DIRS; \/\/ walk files and folders\n const wxString filespec = \"\";\n\n SubUpdateFolderStructure(folder_, this->GetRootItem(), filespec, flags);\n\n this->ExpandAll();\n}\n\n\nstd::vector<wxString> TraverseFilesAndFolders(const wxFileName& root, const wxString filespec, const int flags) {\n std::vector<wxString> ret;\n const wxString root_full_path = root.GetFullPath();\n\n wxDir directory(root_full_path);\n\n directory.Open(root_full_path);\n\n wxString file_or_directory_name;\n bool cont = directory.GetFirst(&file_or_directory_name, filespec, flags);\n while (cont)\n {\n ret.push_back(file_or_directory_name);\n cont = directory.GetNext(&file_or_directory_name);\n }\n\n directory.Close();\n return ret;\n}\n\nvoid ProjectExplorer::SubUpdateFolderStructure(const wxFileName& root, wxTreeItemId parent, const wxString filespec, const int flags)\n{\n const wxString root_full_path = root.GetFullPath();\n const std::vector<wxString> files_and_folders = TraverseFilesAndFolders(root, filespec, flags);\n for (const wxString file_or_directory_name : files_and_folders)\n {\n wxTreeItemId child = this->AppendItem(parent, file_or_directory_name);\n if (IsDiretory(root, file_or_directory_name)) {\n const wxFileName child_name = SubFolder(root, file_or_directory_name);\n SubUpdateFolderStructure(child_name, child, filespec, flags);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/shell\/shell_content_renderer_client.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/public\/common\/content_constants.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"content\/public\/test\/layouttest_support.h\"\n#include \"content\/shell\/shell_render_process_observer.h\"\n#include \"content\/shell\/shell_switches.h\"\n#include \"content\/shell\/webkit_test_runner.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPluginParams.h\"\n#include \"third_party\/WebKit\/Tools\/DumpRenderTree\/chromium\/TestRunner\/public\/WebTestProxy.h\"\n#include \"v8\/include\/v8.h\"\n\nusing WebKit::WebFrame;\nusing WebTestRunner::WebTestProxyBase;\n\nnamespace content {\n\nnamespace {\n\nbool IsLocalhost(const std::string& host) {\n return host == \"127.0.0.1\" || host == \"localhost\";\n}\n\nbool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {\n return host == \"255.255.255.255\";\n}\n\nbool IsExternalPage(const GURL& url) {\n return !url.host().empty() &&\n (url.SchemeIs(chrome::kHttpScheme) ||\n url.SchemeIs(chrome::kHttpsScheme)) &&\n !IsLocalhost(url.host()) &&\n !HostIsUsedBySomeTestsToGenerateError(url.host());\n}\n\n} \/\/ namespace\n\nShellContentRendererClient::ShellContentRendererClient() {\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) {\n EnableWebTestProxyCreation(\n base::Bind(&ShellContentRendererClient::WebTestProxyCreated,\n base::Unretained(this)));\n }\n}\n\nShellContentRendererClient::~ShellContentRendererClient() {\n}\n\nvoid ShellContentRendererClient::RenderThreadStarted() {\n shell_observer_.reset(new ShellRenderProcessObserver());\n}\n\nbool ShellContentRendererClient::OverrideCreatePlugin(\n RenderView* render_view,\n WebKit::WebFrame* frame,\n const WebKit::WebPluginParams& params,\n WebKit::WebPlugin** plugin) {\n std::string mime_type = params.mimeType.utf8();\n if (mime_type == content::kBrowserPluginMimeType) {\n \/\/ Allow browser plugin in content_shell only if it is forced by flag.\n \/\/ Returning true here disables the plugin.\n return !CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableBrowserPluginForAllViewTypes);\n }\n return false;\n}\n\nbool ShellContentRendererClient::WillSendRequest(\n WebFrame* frame,\n PageTransition transition_type,\n const GURL& url,\n const GURL& first_party_for_cookies,\n GURL* new_url) {\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n if (!command_line->HasSwitch(switches::kDumpRenderTree))\n return false;\n if (!command_line->HasSwitch(switches::kAllowExternalPages) &&\n IsExternalPage(url) && !IsExternalPage(first_party_for_cookies)) {\n ShellRenderProcessObserver::GetInstance()->test_delegate()->printMessage(\n std::string(\"Blocked access to external URL \" + url.spec() + \"\\n\"));\n *new_url = GURL();\n return true;\n }\n *new_url = RewriteLayoutTestsURL(url);\n return true;\n}\n\nvoid ShellContentRendererClient::WebTestProxyCreated(RenderView* render_view,\n WebTestProxyBase* proxy) {\n WebKitTestRunner* test_runner = new WebKitTestRunner(render_view);\n if (!ShellRenderProcessObserver::GetInstance()->test_delegate()) {\n ShellRenderProcessObserver::GetInstance()->SetMainWindow(render_view,\n test_runner,\n test_runner);\n }\n test_runner->set_proxy(proxy);\n proxy->setDelegate(\n ShellRenderProcessObserver::GetInstance()->test_delegate());\n proxy->setInterfaces(\n ShellRenderProcessObserver::GetInstance()->test_interfaces());\n}\n\nGURL ShellContentRendererClient::RewriteLayoutTestsURL(const GURL& url) {\n const char kPrefix[] = \"file:\/\/\/tmp\/LayoutTests\/\";\n const int kPrefixLen = arraysize(kPrefix) - 1;\n\n if (url.spec().compare(0, kPrefixLen, kPrefix, kPrefixLen))\n return url;\n\n FilePath replace_path =\n ShellRenderProcessObserver::GetInstance()->webkit_source_dir().Append(\n FILE_PATH_LITERAL(\"LayoutTests\/\"));\n#if defined(OS_WIN)\n std::string utf8_path = WideToUTF8(replace_path.value());\n#else\n std::string utf8_path =\n WideToUTF8(base::SysNativeMBToWide(replace_path.value()));\n#endif\n std::string new_url =\n std::string(\"file:\/\/\") + utf8_path + url.spec().substr(kPrefixLen);\n return GURL(new_url);\n}\n\n} \/\/ namespace content\n<commit_msg>[content shell] add support for the WebTestPlugin<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/shell\/shell_content_renderer_client.h\"\n\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/public\/common\/content_constants.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"content\/public\/test\/layouttest_support.h\"\n#include \"content\/shell\/shell_render_process_observer.h\"\n#include \"content\/shell\/shell_switches.h\"\n#include \"content\/shell\/webkit_test_runner.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebPluginParams.h\"\n#include \"third_party\/WebKit\/Tools\/DumpRenderTree\/chromium\/TestRunner\/public\/WebTestPlugin.h\"\n#include \"third_party\/WebKit\/Tools\/DumpRenderTree\/chromium\/TestRunner\/public\/WebTestProxy.h\"\n#include \"v8\/include\/v8.h\"\n\nusing WebKit::WebFrame;\nusing WebTestRunner::WebTestPlugin;\nusing WebTestRunner::WebTestProxyBase;\n\nnamespace content {\n\nnamespace {\n\nbool IsLocalhost(const std::string& host) {\n return host == \"127.0.0.1\" || host == \"localhost\";\n}\n\nbool HostIsUsedBySomeTestsToGenerateError(const std::string& host) {\n return host == \"255.255.255.255\";\n}\n\nbool IsExternalPage(const GURL& url) {\n return !url.host().empty() &&\n (url.SchemeIs(chrome::kHttpScheme) ||\n url.SchemeIs(chrome::kHttpsScheme)) &&\n !IsLocalhost(url.host()) &&\n !HostIsUsedBySomeTestsToGenerateError(url.host());\n}\n\n} \/\/ namespace\n\nShellContentRendererClient::ShellContentRendererClient() {\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) {\n EnableWebTestProxyCreation(\n base::Bind(&ShellContentRendererClient::WebTestProxyCreated,\n base::Unretained(this)));\n }\n}\n\nShellContentRendererClient::~ShellContentRendererClient() {\n}\n\nvoid ShellContentRendererClient::RenderThreadStarted() {\n shell_observer_.reset(new ShellRenderProcessObserver());\n}\n\nbool ShellContentRendererClient::OverrideCreatePlugin(\n RenderView* render_view,\n WebKit::WebFrame* frame,\n const WebKit::WebPluginParams& params,\n WebKit::WebPlugin** plugin) {\n std::string mime_type = params.mimeType.utf8();\n if (mime_type == content::kBrowserPluginMimeType) {\n \/\/ Allow browser plugin in content_shell only if it is forced by flag.\n \/\/ Returning true here disables the plugin.\n return !CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kEnableBrowserPluginForAllViewTypes);\n }\n if (params.mimeType == WebTestPlugin::mimeType()) {\n *plugin = WebTestPlugin::create(\n frame,\n params,\n ShellRenderProcessObserver::GetInstance()->test_delegate());\n return true;\n }\n return false;\n}\n\nbool ShellContentRendererClient::WillSendRequest(\n WebFrame* frame,\n PageTransition transition_type,\n const GURL& url,\n const GURL& first_party_for_cookies,\n GURL* new_url) {\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n if (!command_line->HasSwitch(switches::kDumpRenderTree))\n return false;\n if (!command_line->HasSwitch(switches::kAllowExternalPages) &&\n IsExternalPage(url) && !IsExternalPage(first_party_for_cookies)) {\n ShellRenderProcessObserver::GetInstance()->test_delegate()->printMessage(\n std::string(\"Blocked access to external URL \" + url.spec() + \"\\n\"));\n *new_url = GURL();\n return true;\n }\n *new_url = RewriteLayoutTestsURL(url);\n return true;\n}\n\nvoid ShellContentRendererClient::WebTestProxyCreated(RenderView* render_view,\n WebTestProxyBase* proxy) {\n WebKitTestRunner* test_runner = new WebKitTestRunner(render_view);\n if (!ShellRenderProcessObserver::GetInstance()->test_delegate()) {\n ShellRenderProcessObserver::GetInstance()->SetMainWindow(render_view,\n test_runner,\n test_runner);\n }\n test_runner->set_proxy(proxy);\n proxy->setDelegate(\n ShellRenderProcessObserver::GetInstance()->test_delegate());\n proxy->setInterfaces(\n ShellRenderProcessObserver::GetInstance()->test_interfaces());\n}\n\nGURL ShellContentRendererClient::RewriteLayoutTestsURL(const GURL& url) {\n const char kPrefix[] = \"file:\/\/\/tmp\/LayoutTests\/\";\n const int kPrefixLen = arraysize(kPrefix) - 1;\n\n if (url.spec().compare(0, kPrefixLen, kPrefix, kPrefixLen))\n return url;\n\n FilePath replace_path =\n ShellRenderProcessObserver::GetInstance()->webkit_source_dir().Append(\n FILE_PATH_LITERAL(\"LayoutTests\/\"));\n#if defined(OS_WIN)\n std::string utf8_path = WideToUTF8(replace_path.value());\n#else\n std::string utf8_path =\n WideToUTF8(base::SysNativeMBToWide(replace_path.value()));\n#endif\n std::string new_url =\n std::string(\"file:\/\/\") + utf8_path + url.spec().substr(kPrefixLen);\n return GURL(new_url);\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <clocale>\n#include <string>\n#include <iomanip>\n#include <ctime>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr; using std::vector;\n\nclass Text {\nprivate:\n bool isinit=false;\n bool readDataFile(string inputfile) {\n std::wifstream txtfile(inputfile, std::ios::binary);\n if (!txtfile.is_open()) {\n return false;\n }\n txtfile.imbue(std::locale(\"en_US.UTF-8\"));\n wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n std::istreambuf_iterator<wchar_t>());\n txtfile.close();\n text=ttext;\n filename=inputfile;\n return true;\n }\npublic:\n wstring text;\n string filename;\n std::map<wchar_t,int> freq;\n std::map<wchar_t,int> w2v;\n std::map<int,wchar_t> v2w;\n Text(string filename) {\n if (readDataFile(filename)) {\n for (auto wc : text) {\n freq[wc]++;\n }\n int it=0;\n for (auto wc : freq) {\n w2v[wc.first]=it;\n v2w[it]=wc.first;\n ++it;\n }\n isinit=true;\n cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n }\n }\n ~Text() {\n\n }\n bool isInit() {\n return isinit;\n }\n int vocsize() {\n if (!isinit) return 0;\n return (int)v2w.size();\n }\n\n wstring sample(int len) {\n int p=std::rand()%(text.size()-len);\n return text.substr(p,len);\n }\n};\n\nvoid currentDateTime(wstring& timestr) {\n time_t now = time(0);\n struct tm tstruct;\n char buf[80];\n tstruct = *localtime(&now);\n \/\/ Visit http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n \/\/ for more information about date\/time format\n strftime(buf, sizeof(buf), \"%Y-%m-%d.%X\", &tstruct);\n timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);\n}\n\nint main(int argc, char *argv[]) {\n#ifndef __APPLE__\n std::setlocale(LC_ALL, \"\");\n#else\n setlocale(LC_ALL, \"\");\n std::wcout.imbue(std::locale(\"en_US.UTF-8\"));\n#endif\n wcout << L\"Rnn-Readär\" << std::endl;\n\n bool allOk=true;\n if (argc!=2) {\n cerr << L\"rnnreader <path-to-text-file>\" << endl;\n exit(-1);\n }\n Text txt(argv[1]);\n if (!txt.isInit()) {\n cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n exit(-1);\n }\n\n wcout << L\"Text size: \" << txt.text.size() << endl;\n\n wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/* for (auto f : txt.freq) {\n int c=(int)f.first;\n wstring wc(1,f.first);\n wcout << wc << L\"|\" << wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec << f.second << endl;\n }\n*\/\n Color::Modifier red(Color::FG_RED);\n Color::Modifier green(Color::FG_GREEN);\n Color::Modifier def(Color::FG_DEFAULT);\n\n int T=96;\n\n int N=(int)txt.text.size() \/ (T+1);\n cerr << N << \" Max datasets\" << endl;\n MatrixN Xr(N,T);\n MatrixN yr(N,T);\n\n wstring chunk,chunky;\n int n=0;\n for (int i=0; i<N; i++) {\n wstring smp = txt.sample(T+1);\n chunk=smp.substr(0,T);\n chunky=smp.substr(1,T);\n for (int t=0; t<T; t++) {\n Xr(i,t)=txt.w2v[chunk[t]];\n yr(i,t)=txt.w2v[chunky[t]];\n }\n ++n;\n }\n\n int maxN = 100000;\n if (n>maxN) n=maxN;\n int n1=n*0.9;\n int dn=(n-n1)\/2;\n if (n1+2*dn > n) {\n cerr << \"Math doesn't work out.\" << endl;\n }\n\n cerr << n1 << \" datasets, \" << dn << \" test-sets, \" << dn << \" validation-sets\" << endl;\n\n\/* MatrixN X(n1,T);\n MatrixN y(n1,T);\n MatrixN Xv(dn,T);\n MatrixN yv(dn,T);\n MatrixN Xt(dn,T);\n MatrixN yt(dn,T);\n*\/\n MatrixN X=Xr.block(0,0,n1,T);\n MatrixN y=yr.block(0,0,n1,T);\n MatrixN Xv=Xr.block(n1,0,dn,T);\n MatrixN yv=yr.block(n1,0,dn,T);\n MatrixN Xt=Xr.block(n1+dn,0,dn,T);\n MatrixN yt=yr.block(n1+dn,0,dn,T);\n \n unsigned int ctm=(unsigned int)std::time(0);\n std::srand(ctm);\n\n cpInitCompute(\"Rnnreader\");\n registerLayers();\n\n LayerBlockOldStyle lb(R\"({\"name\":\"rnnreader\",\"init\":\"orthonormal\"})\"_json);\n int VS=txt.vocsize();\n int H=128; \/\/ 400;\n int BS=64; \/\/ 96;\n float clip=5.0;\n\n \/\/int D=64;\n \/\/ CpParams cp0;\n \/\/ cp0.setPar(\"inputShape\",vector<int>{T});\n \/\/ cp0.setPar(\"V\",VS);\n \/\/ cp0.setPar(\"D\",D);\n \/\/ cp0.setPar(\"clip\",clip);\n \/\/ cp0.setPar(\"init\",(string)\"orthonormal\");\n \/\/ lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n string rnntype=\"LSTM\"; \/\/ or \"RNN\"\n cerr << \"RNN-type: \" << rnntype << endl;\n\n json j0;\n string oName{\"OH0\"};\n j0[\"inputShape\"]=vector<int>{T};\n j0[\"V\"]=VS;\n lb.addLayer(\"OneHot\",oName,j0,{\"input\"});\n\n string nName;\n json j1;\n j1[\"inputShape\"]=vector<int>{VS,T};\n j1[\"N\"]=BS;\n j1[\"H\"]=H;\n j1[\"forgetgateinitones\"]=true;\n \/\/j1[\"forgetbias\"]=0.10;\n j1[\"clip\"]=clip;\n int layer_depth1=2; \/\/ 6;\n j1[\"H\"]=H;\n for (auto l=0; l<layer_depth1; l++) {\n if (l>0) j1[\"inputShape\"]=vector<int>{H,T};\n nName=\"lstm\"+std::to_string(l);\n lb.addLayer(rnntype,nName,j1,{oName});\n oName=nName;\n }\n\n json j10;\n j10[\"inputShape\"]=vector<int>{H,T};\n j10[\"M\"]=VS;\n lb.addLayer(\"TemporalAffine\",\"af1\",j10,{oName});\n\n json j11;\n j11[\"inputShape\"]=vector<int>{VS,T};\n lb.addLayer(\"TemporalSoftmax\",\"sm1\",j11,{\"af1\"});\n\n if (!lb.checkTopology(true)) {\n allOk=false;\n cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n } else {\n cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n }\n\n \/\/json jc;\n \/\/lb.getLayerConfiguration(jc);\n \/\/cerr << jc.dump(4) << endl;\n\n \/\/ preseverstates no longer necessary for training!\n json jo(R\"({\"verbose\":true,\"shuffle\":false,\"preservestates\":false,\"notests\":false,\"nofragmentbatches\":true,\"epsilon\":1e-8})\"_json);\n jo[\"lossfactor\"]=1.0\/(floatN)T; \/\/ Allows to normalize the loss with T.\n json j_opt(R\"({\"learning_rate\":2.2e-2})\"_json);\n j_opt[\"inputShape\"]=vector<int>{H,T};\n json j_loss(R\"({\"name\":\"temporalsoftmax\"})\"_json);\n j_loss[\"inputShape\"]=vector<int>{H,T};\n floatN dep=3.0; \/\/ 70.0;\n floatN sep=0.0;\n jo[\"epochs\"]=(floatN)dep;\n jo[\"batch_size\"]=BS;\n floatN lr_decay = 0.99; \/\/ 0.15;\n\n Optimizer *pOpt=optimizerFactory(\"Adam\",j_opt);\n t_cppl OptimizerState{};\n Loss *pLoss=lossFactory(\"TemporalCrossEntropy\",j_loss);\n\n for (int i=0; i<1000; i++) {\n jo[\"startepoch\"]=(floatN)sep;\n j_opt[\"learning_rate\"] = floatN(j_opt[\"learning_rate\"]) * lr_decay;\n pOpt->updateOptimizerParameters(j_opt);\n t_cppl states;\n t_cppl statesv;\n states[\"y\"] = new MatrixN(y);\n statesv[\"y\"] = new MatrixN(yv);\n lb.train(X, &states, Xv, &statesv, pOpt, &OptimizerState, pLoss, jo);\n cppl_delete(&states);\n cppl_delete(&statesv);\n\n sep+=dep;\n\n int pos=rand() % 1000 + 5000;\n wstring instr=txt.text.substr(pos,T);\n\n MatrixN xg(1,T);\n for (int i=0; i<T; i++) {\n xg(0,i)=txt.w2v[instr[i]];\n }\n wstring sout{};\n Layer* plstm0=lb.layerMap[\"lstm0\"];\n t_cppl statesg{};\n plstm0->genZeroStates(&statesg, 1);\n\n int g,t,v;\n for (g=0; g<300; g++) {\n t_cppl cache{};\n\n \/* MatrixN probs_xx=*\/ lb.forward(xg,&cache, &statesg);\n \/\/ Forward generates the 'wrong' permutation of output. QUick-hack is abusing the 'cache' to get the permutation.\n if (cache.find(\"sm1-probst\")==cache.end()) {\n cerr << \"probst didn't make it, FATAL\" << endl;\n exit(1);\n }\n MatrixN probst=*(cache[\"sm1-probst\"]); \/\/ XXX check if temporal softmax uses redundant morpher!\n MatrixN probsd=MatrixN(T,VS);\n for (t=0; t<T; t++) {\n for (v=0; v<VS; v++) {\n probsd(t,v)=probst(0,t*VS+v);\n }\n }\n int li = -1;\n for (t=0; t<T; t++) {\n vector<floatN> probs(VS);\n vector<floatN> index(VS);\n for (v=0; v<VS; v++) {\n probs[v]=probsd(t,v);\n index[v]=v;\n }\n li=(int)index[randomChoice(index, probs)];\n }\n cppl_delete(&cache);\n\n for (int t=0; t<T-1; t++) {\n xg(0,t)=xg(0,t+1);\n }\n xg(0,T-1)=li;\n sout += txt.v2w[li];\n }\n wcout << \"output: \" << sout << endl;\n wstring timestr;\n currentDateTime(timestr);\n std::wofstream fl(\"rnnreader.txt\", std::ios_base::app);\n fl << \"---- \" << timestr << \", ep:\" << sep << \" ---\" << endl;\n fl << sout << endl;\n fl.close();\n cppl_delete(&statesg);\n }\n delete pOpt;\n cppl_delete(&OptimizerState);\n delete pLoss;\n}\n<commit_msg>default lr_decay algo<commit_after>#include <iostream>\n#include <fstream>\n#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <clocale>\n#include <string>\n#include <iomanip>\n#include <ctime>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr; using std::vector;\n\nclass Text {\nprivate:\n bool isinit=false;\n bool readDataFile(string inputfile) {\n std::wifstream txtfile(inputfile, std::ios::binary);\n if (!txtfile.is_open()) {\n return false;\n }\n txtfile.imbue(std::locale(\"en_US.UTF-8\"));\n wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n std::istreambuf_iterator<wchar_t>());\n txtfile.close();\n text=ttext;\n filename=inputfile;\n return true;\n }\npublic:\n wstring text;\n string filename;\n std::map<wchar_t,int> freq;\n std::map<wchar_t,int> w2v;\n std::map<int,wchar_t> v2w;\n Text(string filename) {\n if (readDataFile(filename)) {\n for (auto wc : text) {\n freq[wc]++;\n }\n int it=0;\n for (auto wc : freq) {\n w2v[wc.first]=it;\n v2w[it]=wc.first;\n ++it;\n }\n isinit=true;\n cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n }\n }\n ~Text() {\n\n }\n bool isInit() {\n return isinit;\n }\n int vocsize() {\n if (!isinit) return 0;\n return (int)v2w.size();\n }\n\n wstring sample(int len) {\n int p=std::rand()%(text.size()-len);\n return text.substr(p,len);\n }\n};\n\nvoid currentDateTime(wstring& timestr) {\n time_t now = time(0);\n struct tm tstruct;\n char buf[80];\n tstruct = *localtime(&now);\n \/\/ Visit http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n \/\/ for more information about date\/time format\n strftime(buf, sizeof(buf), \"%Y-%m-%d.%X\", &tstruct);\n timestr=std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(buf);\n}\n\nint main(int argc, char *argv[]) {\n#ifndef __APPLE__\n std::setlocale(LC_ALL, \"\");\n#else\n setlocale(LC_ALL, \"\");\n std::wcout.imbue(std::locale(\"en_US.UTF-8\"));\n#endif\n wcout << L\"Rnn-Readär\" << std::endl;\n\n bool allOk=true;\n if (argc!=2) {\n cerr << L\"rnnreader <path-to-text-file>\" << endl;\n exit(-1);\n }\n Text txt(argv[1]);\n if (!txt.isInit()) {\n cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n exit(-1);\n }\n\n wcout << L\"Text size: \" << txt.text.size() << endl;\n\n wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/* for (auto f : txt.freq) {\n int c=(int)f.first;\n wstring wc(1,f.first);\n wcout << wc << L\"|\" << wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec << f.second << endl;\n }\n*\/\n Color::Modifier red(Color::FG_RED);\n Color::Modifier green(Color::FG_GREEN);\n Color::Modifier def(Color::FG_DEFAULT);\n\n int T=96;\n\n int N=(int)txt.text.size() \/ (T+1);\n cerr << N << \" Max datasets\" << endl;\n MatrixN Xr(N,T);\n MatrixN yr(N,T);\n\n wstring chunk,chunky;\n int n=0;\n for (int i=0; i<N; i++) {\n wstring smp = txt.sample(T+1);\n chunk=smp.substr(0,T);\n chunky=smp.substr(1,T);\n for (int t=0; t<T; t++) {\n Xr(i,t)=txt.w2v[chunk[t]];\n yr(i,t)=txt.w2v[chunky[t]];\n }\n ++n;\n }\n\n int maxN = 100000;\n if (n>maxN) n=maxN;\n int n1=n*0.9;\n int dn=(n-n1)\/2;\n if (n1+2*dn > n) {\n cerr << \"Math doesn't work out.\" << endl;\n }\n\n cerr << n1 << \" datasets, \" << dn << \" test-sets, \" << dn << \" validation-sets\" << endl;\n\n\/* MatrixN X(n1,T);\n MatrixN y(n1,T);\n MatrixN Xv(dn,T);\n MatrixN yv(dn,T);\n MatrixN Xt(dn,T);\n MatrixN yt(dn,T);\n*\/\n MatrixN X=Xr.block(0,0,n1,T);\n MatrixN y=yr.block(0,0,n1,T);\n MatrixN Xv=Xr.block(n1,0,dn,T);\n MatrixN yv=yr.block(n1,0,dn,T);\n MatrixN Xt=Xr.block(n1+dn,0,dn,T);\n MatrixN yt=yr.block(n1+dn,0,dn,T);\n \n unsigned int ctm=(unsigned int)std::time(0);\n std::srand(ctm);\n\n cpInitCompute(\"Rnnreader\");\n registerLayers();\n\n LayerBlockOldStyle lb(R\"({\"name\":\"rnnreader\",\"init\":\"orthonormal\"})\"_json);\n int VS=txt.vocsize();\n int H=128; \/\/ 400;\n int BS=64; \/\/ 96;\n float clip=5.0;\n\n \/\/int D=64;\n \/\/ CpParams cp0;\n \/\/ cp0.setPar(\"inputShape\",vector<int>{T});\n \/\/ cp0.setPar(\"V\",VS);\n \/\/ cp0.setPar(\"D\",D);\n \/\/ cp0.setPar(\"clip\",clip);\n \/\/ cp0.setPar(\"init\",(string)\"orthonormal\");\n \/\/ lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n string rnntype=\"LSTM\"; \/\/ or \"RNN\"\n cerr << \"RNN-type: \" << rnntype << endl;\n\n json j0;\n string oName{\"OH0\"};\n j0[\"inputShape\"]=vector<int>{T};\n j0[\"V\"]=VS;\n lb.addLayer(\"OneHot\",oName,j0,{\"input\"});\n\n string nName;\n json j1;\n j1[\"inputShape\"]=vector<int>{VS,T};\n j1[\"N\"]=BS;\n j1[\"H\"]=H;\n j1[\"forgetgateinitones\"]=true;\n \/\/j1[\"forgetbias\"]=0.10;\n j1[\"clip\"]=clip;\n int layer_depth1=2; \/\/ 6;\n j1[\"H\"]=H;\n for (auto l=0; l<layer_depth1; l++) {\n if (l>0) j1[\"inputShape\"]=vector<int>{H,T};\n nName=\"lstm\"+std::to_string(l);\n lb.addLayer(rnntype,nName,j1,{oName});\n oName=nName;\n }\n\n json j10;\n j10[\"inputShape\"]=vector<int>{H,T};\n j10[\"M\"]=VS;\n lb.addLayer(\"TemporalAffine\",\"af1\",j10,{oName});\n\n json j11;\n j11[\"inputShape\"]=vector<int>{VS,T};\n lb.addLayer(\"TemporalSoftmax\",\"sm1\",j11,{\"af1\"});\n\n if (!lb.checkTopology(true)) {\n allOk=false;\n cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n } else {\n cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n }\n\n \/\/json jc;\n \/\/lb.getLayerConfiguration(jc);\n \/\/cerr << jc.dump(4) << endl;\n\n \/\/ preseverstates no longer necessary for training!\n json jo(R\"({\"verbose\":true,\"shuffle\":false,\"preservestates\":false,\"notests\":false,\"nofragmentbatches\":true,\"epsilon\":1e-8})\"_json);\n jo[\"lossfactor\"]=1.0\/(floatN)T; \/\/ Allows to normalize the loss with T.\n json j_opt(R\"({\"learning_rate\":5.e-2})\"_json);\n j_opt[\"inputShape\"]=vector<int>{H,T};\n json j_loss(R\"({\"name\":\"temporalsoftmax\"})\"_json);\n j_loss[\"inputShape\"]=vector<int>{H,T};\n floatN dep=3.0; \/\/ 70.0;\n floatN sep=0.0;\n jo[\"epochs\"]=(floatN)dep;\n jo[\"batch_size\"]=BS;\n jo[\"lr_decay\"] = 0.99;\n \/\/ XXX: regularization crashes the training.\n \/\/jo[\"regularization\"]=1e-5;\n \/\/jo[\"regularization_decay\"]=0.95;\n\n Optimizer *pOpt=optimizerFactory(\"Adam\",j_opt);\n t_cppl OptimizerState{};\n Loss *pLoss=lossFactory(\"TemporalCrossEntropy\",j_loss);\n\n for (int i=0; i<1000; i++) {\n jo[\"startepoch\"]=(floatN)sep;\n t_cppl states;\n t_cppl statesv;\n states[\"y\"] = new MatrixN(y);\n statesv[\"y\"] = new MatrixN(yv);\n lb.train(X, &states, Xv, &statesv, pOpt, &OptimizerState, pLoss, jo);\n cppl_delete(&states);\n cppl_delete(&statesv);\n\n sep+=dep;\n\n int pos=rand() % 1000 + 5000;\n wstring instr=txt.text.substr(pos,T);\n\n MatrixN xg(1,T);\n for (int i=0; i<T; i++) {\n xg(0,i)=txt.w2v[instr[i]];\n }\n wstring sout{};\n Layer* plstm0=lb.layerMap[\"lstm0\"];\n t_cppl statesg{};\n plstm0->genZeroStates(&statesg, 1);\n\n int g,t,v;\n for (g=0; g<300; g++) {\n t_cppl cache{};\n\n \/* MatrixN probs_xx=*\/ lb.forward(xg,&cache, &statesg);\n \/\/ Forward generates the 'wrong' permutation of output. QUick-hack is abusing the 'cache' to get the permutation.\n if (cache.find(\"sm1-probst\")==cache.end()) {\n cerr << \"probst didn't make it, FATAL\" << endl;\n exit(1);\n }\n MatrixN probst=*(cache[\"sm1-probst\"]); \/\/ XXX check if temporal softmax uses redundant morpher!\n MatrixN probsd=MatrixN(T,VS);\n for (t=0; t<T; t++) {\n for (v=0; v<VS; v++) {\n probsd(t,v)=probst(0,t*VS+v);\n }\n }\n int li = -1;\n for (t=0; t<T; t++) {\n vector<floatN> probs(VS);\n vector<floatN> index(VS);\n for (v=0; v<VS; v++) {\n probs[v]=probsd(t,v);\n index[v]=v;\n }\n li=(int)index[randomChoice(index, probs)];\n }\n cppl_delete(&cache);\n\n for (int t=0; t<T-1; t++) {\n xg(0,t)=xg(0,t+1);\n }\n xg(0,T-1)=li;\n sout += txt.v2w[li];\n }\n wcout << \"output: \" << sout << endl;\n wstring timestr;\n currentDateTime(timestr);\n std::wofstream fl(\"rnnreader.txt\", std::ios_base::app);\n fl << \"---- \" << timestr << \", ep:\" << sep << \" ---\" << endl;\n fl << sout << endl;\n fl.close();\n cppl_delete(&statesg);\n }\n delete pOpt;\n cppl_delete(&OptimizerState);\n delete pLoss;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n\/\/#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <string>\n#include <iomanip>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr; using std::vector;\n\nclass Text {\nprivate:\n bool isinit=false;\n bool readDataFile(string inputfile) {\n std::wifstream txtfile(inputfile, std::ios::binary);\n if (!txtfile.is_open()) {\n return false;\n }\n txtfile.imbue(std::locale(\"en_US.UTF8\"));\n wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n std::istreambuf_iterator<wchar_t>());\n txtfile.close();\n text=ttext;\n filename=inputfile;\n return true;\n }\npublic:\n wstring text;\n string filename;\n std::map<wchar_t,int> freq;\n std::map<wchar_t,int> w2v;\n std::map<int,wchar_t> v2w;\n Text(string filename) {\n if (readDataFile(filename)) {\n for (auto wc : text) {\n freq[wc]++;\n }\n int it=0;\n for (auto wc : freq) {\n w2v[wc.first]=it;\n v2w[it]=wc.first;\n ++it;\n }\n isinit=true;\n cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n }\n }\n ~Text() {\n\n }\n bool isInit() {\n return isinit;\n }\n int vocsize() {\n if (!isinit) return 0;\n return v2w.size();\n }\n};\n\nint main(int argc, char *argv[]) {\n std::setlocale (LC_ALL, \"\");\n wcout << L\"Rnn-Readär\" << std::endl;\n\n bool allOk=true;\n if (argc!=2) {\n cerr << \"rnnreader <path-to-text-file>\" << endl;\n exit(-1);\n }\n Text txt(argv[1]);\n if (!txt.isInit()) {\n cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n exit(-1);\n }\n\n wcout << L\"Text size: \" << txt.text.size() << endl;\n\n wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/* for (auto f : txt.freq) {\n int c=(int)f.first;\n wstring wc(1,f.first);\n wcout << wc << L\"|\" << wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec << f.second << endl;\n }\n*\/\n Color::Modifier red(Color::FG_RED);\n Color::Modifier green(Color::FG_GREEN);\n Color::Modifier def(Color::FG_DEFAULT);\n\n int T=1;\n int N=txt.text.size()-T-1;\n\n MatrixN Xr(N,T);\n MatrixN yr(N,T);\n\n wstring chunk,chunky;\n int n=0;\n for (int i=0; i<N-T-1; i+=T) {\n chunk=txt.text.substr(i,T);\n chunky=txt.text.substr(i+1,T);\n for (int t=0; t<T; t++) {\n Xr(i,t)=txt.w2v[chunk[t]];\n yr(i,t)=txt.w2v[chunky[t]];\n ++n;\n }\n }\n\n int maxN = 50000;\n if (n>maxN) n=maxN;\n int n1=n*0.9;\n int dn=(n-n1)\/2;\n\n cerr << n1 << \" datasets\" << endl;\n\n\/* MatrixN X(n1,T);\n MatrixN y(n1,T);\n MatrixN Xv(dn,T);\n MatrixN yv(dn,T);\n MatrixN Xt(dn,T);\n MatrixN yt(dn,T);\n*\/\n MatrixN X=Xr.block(0,0,n1,T);\n MatrixN y=yr.block(0,0,n1,T);\n MatrixN Xv=Xr.block(n1,0,dn,T);\n MatrixN yv=yr.block(n1,0,dn,T);\n MatrixN Xt=Xr.block(n1+dn,0,dn,T);\n MatrixN yt=yr.block(n1+dn,0,dn,T);\n\/*\n\n X=Xr.block(0,0,100000,T);\n y=yr.block(0,0,100000,T);\n Xv=Xr.block(100000,0,10000,T);\n yv=yr.block(100000,0,10000,T);\n Xt=Xr.block(110000,0,10000,T);\n yt=yr.block(110000,0,10000,T);\n*\/\n\/*\n X=Xr.block(0,0,10000,T);\n y=yr.block(0,0,10000,T);\n Xv=Xr.block(10000,0,1000,T);\n yv=yr.block(10000,0,1000,T);\n Xt=Xr.block(11000,0,1000,T);\n yt=yr.block(11000,0,1000,T);\n*\/\n cpInitCompute(\"Rnnreader\");\n registerLayers();\n\n LayerBlock lb(\"{name='rnnreader';init='orthonormal';initfactor=0.001}\");\n int VS=txt.vocsize();\n int H=64;\n int D=128;\n int BS=64;\n float clip=5.0;\n\n CpParams cp0;\n cp0.setPar(\"inputShape\",vector<int>{T});\n cp0.setPar(\"V\",VS);\n cp0.setPar(\"D\",D);\n lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n CpParams cp1;\n cp1.setPar(\"inputShape\",vector<int>{D,T});\n cp1.setPar(\"N\",BS);\n cp1.setPar(\"H\",H);\n cp1.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn1\",cp1,{\"WE0\"});\n\n CpParams cp2;\n cp2.setPar(\"inputShape\",vector<int>{H,T});\n cp2.setPar(\"N\",BS);\n cp2.setPar(\"H\",H);\n cp2.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn2\",cp2,{\"rnn1\"});\n\n CpParams cp3;\n cp3.setPar(\"inputShape\",vector<int>{H,T});\n cp3.setPar(\"N\",BS);\n cp3.setPar(\"H\",H);\n cp3.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn3\",cp3,{\"rnn2\"});\n\n CpParams cp10;\n cp10.setPar(\"inputShape\",vector<int>{H,T});\n \/\/cp10.setPar(\"T\",T);\n \/\/cp10.setPar(\"D\",H);\n cp10.setPar(\"M\",VS);\n lb.addLayer(\"TemporalAffine\",\"af1\",cp10,{\"rnn3\"});\n\n CpParams cp11;\n cp11.setPar(\"inputShape\",vector<int>{VS,T});\n lb.addLayer(\"TemporalSoftmax\",\"sm1\",cp11,{\"af1\"});\n\n if (!lb.checkTopology(true)) {\n allOk=false;\n cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n } else {\n cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n }\n\n\/* wstring chunk;\n chunk = txt.text.substr(512,128);\n wcout << chunk << endl;\n*\/\n \/\/ CpParams cpo(\"{verbose=true;epsilon=1e-8}\");\n CpParams cpo(\"{verbose=false;epsilon=1e-8}\");\n cpo.setPar(\"learning_rate\", (floatN)1e-2); \/\/2.2e-2);\n cpo.setPar(\"lr_decay\", (floatN)0.95);\n \/\/cpo.setPar(\"regularization\", (floatN)1.);\n\n floatN dep=1.0;\n floatN sep=0.0;\n cpo.setPar(\"epochs\",(floatN)dep);\n cpo.setPar(\"batch_size\",BS);\n\n MatrixN xg(1,T);\n MatrixN xg2(1,T);\n wstring sg;\n for (int i=0; i<10000; i++) {\n\n cpo.setPar(\"startepoch\", (floatN)sep);\n cpo.setPar(\"maxthreads\", (int)1); \/\/ RNN can't cope with threads.\n\n Layer *prnn1=lb.layerMap[\"rnn1\"];\n prnn1->params[\"ho\"]->setZero();\n \/*Layer *prnn2=lb.layerMap[\"rnn2\"];\n prnn2->params[\"ho\"]->setZero();\n Layer *prnn3=lb.layerMap[\"rnn3\"];\n prnn3->params[\"ho\"]->setZero();\n*\/\n floatN cAcc=lb.train(X, y, Xv, yv, \"Adam\", cpo);\n sep+=dep;\n\n int pos=rand() % 1000 + 5000;\n wstring instr=txt.text.substr(pos,T);\n\n for (int i=0; i<T; i++) {\n if (i<instr.size()) {\n xg(0,i)=txt.w2v[instr[i]];\n } else {\n xg(0,i)=txt.w2v[L' '];\n }\n }\n \/*\n for (auto wc : instr) {\n sg[0]=wc;\n xg(0,0)=txt.w2v[sg[0]];\n MatrixN z(0,0);\n MatrixN yg=lb.forward(xg,z,nullptr);\n }\n *\/\n \/\/xg(0,0)=txt.w2v[sg[0]];\n for (int rep=0; rep<3; rep++) {\n \/\/Layer *prnn=lb.layerMap[\"rnn1\"];\n \/\/prnn->params[\"ho\"]->setZero();\n cerr << \"------------\" << rep << \"--------------------------\" << endl;\n for (int g=0; g<200; g++) {\n \/\/wcout << g << L\">\";\n MatrixN z(0,0);\n\n\n \/\/for (int i; i<xg.cols(); i++) wcout << txt.v2w[xg(0,i)];\n \/\/wcout << L\"<\" << endl << L\">\";\n\n MatrixN yg=lb.forward(xg,z,nullptr);\n for (int t=0; t<T; t++) {\n vector<floatN> probs(D);\n vector<floatN> index(D);\n for (int d=0; d<D; d++) {\n probs[d]=yg(0,t*D+d);\n index[d]=d;\n }\n int ind=(int)index[randomChoice(index, probs)];\n\/* float mx=-1000.0;\n int ind=-1;\n for (int d=0; d<VS; d++) {\n floatN p=yg(0,t*D+d);\n floatN pr=p*((floatN)(rand()%100)\/5000.0+0.98);\n if (pr>mx) {\n mx=pr; \/\/ yg(0,t*D+d);\n ind=d;\n }\n }\n*\/\n wchar_t cw=txt.v2w[ind];\n \/\/if (t==0) wcout << L\"[\" << cw << L\"<\";\n \/\/wcout << L\"<\" << cw << L\">\";\n wcout << cw;\n xg2(0,t)=ind;\n }\n \/\/wcout << L\"<\" << endl;\n for (int t=T-1; t>0; t--) xg(0,t)=xg(0,t-1);\n xg(0,0)=xg2(0,0);\n \/\/xg=xg2;\n }\n wcout << endl;\n }\n }\n \/*\n floatN train_err, val_err, test_err;\n bool evalFinal=true;\n if (evalFinal) {\n train_err=lb.test(X, y, cpo.getPar(\"batch_size\", 50));\n val_err=lb.test(Xv, yv, cpo.getPar(\"batch_size\", 50));\n test_err=lb.test(Xt, yt, cpo.getPar(\"batch_size\", 50));\n\n cerr << \"Final results on RnnReader after \" << cpo.getPar(\"epochs\",(floatN)0.0) << \" epochs:\" << endl;\n cerr << \" Train-error: \" << train_err << \" train-acc: \" << 1.0-train_err << endl;\n cerr << \" Validation-error: \" << val_err << \" val-acc: \" << 1.0-val_err << endl;\n cerr << \" Test-error: \" << test_err << \" test-acc: \" << 1.0-test_err << endl;\n }\n \/\/return cAcc;\n *\/\n cpExitCompute();\n}\n<commit_msg>smaller hidden vector<commit_after>#include <iostream>\n#include <fstream>\n\/\/#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <string>\n#include <iomanip>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr; using std::vector;\n\nclass Text {\nprivate:\n bool isinit=false;\n bool readDataFile(string inputfile) {\n std::wifstream txtfile(inputfile, std::ios::binary);\n if (!txtfile.is_open()) {\n return false;\n }\n txtfile.imbue(std::locale(\"en_US.UTF8\"));\n wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n std::istreambuf_iterator<wchar_t>());\n txtfile.close();\n text=ttext;\n filename=inputfile;\n return true;\n }\npublic:\n wstring text;\n string filename;\n std::map<wchar_t,int> freq;\n std::map<wchar_t,int> w2v;\n std::map<int,wchar_t> v2w;\n Text(string filename) {\n if (readDataFile(filename)) {\n for (auto wc : text) {\n freq[wc]++;\n }\n int it=0;\n for (auto wc : freq) {\n w2v[wc.first]=it;\n v2w[it]=wc.first;\n ++it;\n }\n isinit=true;\n cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n }\n }\n ~Text() {\n\n }\n bool isInit() {\n return isinit;\n }\n int vocsize() {\n if (!isinit) return 0;\n return v2w.size();\n }\n};\n\nint main(int argc, char *argv[]) {\n std::setlocale (LC_ALL, \"\");\n wcout << L\"Rnn-Readär\" << std::endl;\n\n bool allOk=true;\n if (argc!=2) {\n cerr << \"rnnreader <path-to-text-file>\" << endl;\n exit(-1);\n }\n Text txt(argv[1]);\n if (!txt.isInit()) {\n cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n exit(-1);\n }\n\n wcout << L\"Text size: \" << txt.text.size() << endl;\n\n wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/* for (auto f : txt.freq) {\n int c=(int)f.first;\n wstring wc(1,f.first);\n wcout << wc << L\"|\" << wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec << f.second << endl;\n }\n*\/\n Color::Modifier red(Color::FG_RED);\n Color::Modifier green(Color::FG_GREEN);\n Color::Modifier def(Color::FG_DEFAULT);\n\n int T=1;\n int N=txt.text.size()-T-1;\n\n MatrixN Xr(N,T);\n MatrixN yr(N,T);\n\n wstring chunk,chunky;\n int n=0;\n for (int i=0; i<N-T-1; i+=T) {\n chunk=txt.text.substr(i,T);\n chunky=txt.text.substr(i+1,T);\n for (int t=0; t<T; t++) {\n Xr(i,t)=txt.w2v[chunk[t]];\n yr(i,t)=txt.w2v[chunky[t]];\n ++n;\n }\n }\n\n int maxN = 50000;\n if (n>maxN) n=maxN;\n int n1=n*0.9;\n int dn=(n-n1)\/2;\n\n cerr << n1 << \" datasets\" << endl;\n\n\/* MatrixN X(n1,T);\n MatrixN y(n1,T);\n MatrixN Xv(dn,T);\n MatrixN yv(dn,T);\n MatrixN Xt(dn,T);\n MatrixN yt(dn,T);\n*\/\n MatrixN X=Xr.block(0,0,n1,T);\n MatrixN y=yr.block(0,0,n1,T);\n MatrixN Xv=Xr.block(n1,0,dn,T);\n MatrixN yv=yr.block(n1,0,dn,T);\n MatrixN Xt=Xr.block(n1+dn,0,dn,T);\n MatrixN yt=yr.block(n1+dn,0,dn,T);\n\/*\n\n X=Xr.block(0,0,100000,T);\n y=yr.block(0,0,100000,T);\n Xv=Xr.block(100000,0,10000,T);\n yv=yr.block(100000,0,10000,T);\n Xt=Xr.block(110000,0,10000,T);\n yt=yr.block(110000,0,10000,T);\n*\/\n\/*\n X=Xr.block(0,0,10000,T);\n y=yr.block(0,0,10000,T);\n Xv=Xr.block(10000,0,1000,T);\n yv=yr.block(10000,0,1000,T);\n Xt=Xr.block(11000,0,1000,T);\n yt=yr.block(11000,0,1000,T);\n*\/\n cpInitCompute(\"Rnnreader\");\n registerLayers();\n\n LayerBlock lb(\"{name='rnnreader';init='orthonormal';initfactor=0.001}\");\n int VS=txt.vocsize();\n int H=192;\n int D=128;\n int BS=64;\n float clip=5.0;\n\n CpParams cp0;\n cp0.setPar(\"inputShape\",vector<int>{T});\n cp0.setPar(\"V\",VS);\n cp0.setPar(\"D\",D);\n lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n CpParams cp1;\n cp1.setPar(\"inputShape\",vector<int>{D,T});\n cp1.setPar(\"N\",BS);\n cp1.setPar(\"H\",H);\n cp1.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn1\",cp1,{\"WE0\"});\n\n CpParams cp2;\n cp2.setPar(\"inputShape\",vector<int>{H,T});\n cp2.setPar(\"N\",BS);\n cp2.setPar(\"H\",H);\n cp2.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn2\",cp2,{\"rnn1\"});\n\n CpParams cp3;\n cp3.setPar(\"inputShape\",vector<int>{H,T});\n cp3.setPar(\"N\",BS);\n cp3.setPar(\"H\",H);\n cp3.setPar(\"clip\",clip);\n lb.addLayer(\"RNN\",\"rnn3\",cp3,{\"rnn2\"});\n\n CpParams cp10;\n cp10.setPar(\"inputShape\",vector<int>{H,T});\n \/\/cp10.setPar(\"T\",T);\n \/\/cp10.setPar(\"D\",H);\n cp10.setPar(\"M\",VS);\n lb.addLayer(\"TemporalAffine\",\"af1\",cp10,{\"rnn3\"});\n\n CpParams cp11;\n cp11.setPar(\"inputShape\",vector<int>{VS,T});\n lb.addLayer(\"TemporalSoftmax\",\"sm1\",cp11,{\"af1\"});\n\n if (!lb.checkTopology(true)) {\n allOk=false;\n cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n } else {\n cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n }\n\n\/* wstring chunk;\n chunk = txt.text.substr(512,128);\n wcout << chunk << endl;\n*\/\n \/\/ CpParams cpo(\"{verbose=true;epsilon=1e-8}\");\n CpParams cpo(\"{verbose=false;epsilon=1e-8}\");\n cpo.setPar(\"learning_rate\", (floatN)1e-2); \/\/2.2e-2);\n cpo.setPar(\"lr_decay\", (floatN)0.95);\n \/\/cpo.setPar(\"regularization\", (floatN)1.);\n\n floatN dep=1.0;\n floatN sep=0.0;\n cpo.setPar(\"epochs\",(floatN)dep);\n cpo.setPar(\"batch_size\",BS);\n\n MatrixN xg(1,T);\n MatrixN xg2(1,T);\n wstring sg;\n for (int i=0; i<10000; i++) {\n\n cpo.setPar(\"startepoch\", (floatN)sep);\n cpo.setPar(\"maxthreads\", (int)1); \/\/ RNN can't cope with threads.\n\n Layer *prnn1=lb.layerMap[\"rnn1\"];\n prnn1->params[\"ho\"]->setZero();\n \/*Layer *prnn2=lb.layerMap[\"rnn2\"];\n prnn2->params[\"ho\"]->setZero();\n Layer *prnn3=lb.layerMap[\"rnn3\"];\n prnn3->params[\"ho\"]->setZero();\n*\/\n floatN cAcc=lb.train(X, y, Xv, yv, \"Adam\", cpo);\n sep+=dep;\n\n int pos=rand() % 1000 + 5000;\n wstring instr=txt.text.substr(pos,T);\n\n for (int i=0; i<T; i++) {\n if (i<instr.size()) {\n xg(0,i)=txt.w2v[instr[i]];\n } else {\n xg(0,i)=txt.w2v[L' '];\n }\n }\n \/*\n for (auto wc : instr) {\n sg[0]=wc;\n xg(0,0)=txt.w2v[sg[0]];\n MatrixN z(0,0);\n MatrixN yg=lb.forward(xg,z,nullptr);\n }\n *\/\n \/\/xg(0,0)=txt.w2v[sg[0]];\n for (int rep=0; rep<3; rep++) {\n \/\/Layer *prnn=lb.layerMap[\"rnn1\"];\n \/\/prnn->params[\"ho\"]->setZero();\n cerr << \"------------\" << rep << \"--------------------------\" << endl;\n for (int g=0; g<200; g++) {\n \/\/wcout << g << L\">\";\n MatrixN z(0,0);\n\n\n \/\/for (int i; i<xg.cols(); i++) wcout << txt.v2w[xg(0,i)];\n \/\/wcout << L\"<\" << endl << L\">\";\n\n MatrixN yg=lb.forward(xg,z,nullptr);\n for (int t=0; t<T; t++) {\n vector<floatN> probs(D);\n vector<floatN> index(D);\n for (int d=0; d<D; d++) {\n probs[d]=yg(0,t*D+d);\n index[d]=d;\n }\n int ind=(int)index[randomChoice(index, probs)];\n\/* float mx=-1000.0;\n int ind=-1;\n for (int d=0; d<VS; d++) {\n floatN p=yg(0,t*D+d);\n floatN pr=p*((floatN)(rand()%100)\/5000.0+0.98);\n if (pr>mx) {\n mx=pr; \/\/ yg(0,t*D+d);\n ind=d;\n }\n }\n*\/\n wchar_t cw=txt.v2w[ind];\n \/\/if (t==0) wcout << L\"[\" << cw << L\"<\";\n \/\/wcout << L\"<\" << cw << L\">\";\n wcout << cw;\n xg2(0,t)=ind;\n }\n \/\/wcout << L\"<\" << endl;\n for (int t=T-1; t>0; t--) xg(0,t)=xg(0,t-1);\n xg(0,0)=xg2(0,0);\n \/\/xg=xg2;\n }\n wcout << endl;\n }\n }\n \/*\n floatN train_err, val_err, test_err;\n bool evalFinal=true;\n if (evalFinal) {\n train_err=lb.test(X, y, cpo.getPar(\"batch_size\", 50));\n val_err=lb.test(Xv, yv, cpo.getPar(\"batch_size\", 50));\n test_err=lb.test(Xt, yt, cpo.getPar(\"batch_size\", 50));\n\n cerr << \"Final results on RnnReader after \" << cpo.getPar(\"epochs\",(floatN)0.0) << \" epochs:\" << endl;\n cerr << \" Train-error: \" << train_err << \" train-acc: \" << 1.0-train_err << endl;\n cerr << \" Validation-error: \" << val_err << \" val-acc: \" << 1.0-val_err << endl;\n cerr << \" Test-error: \" << test_err << \" test-acc: \" << 1.0-test_err << endl;\n }\n \/\/return cAcc;\n *\/\n cpExitCompute();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iterator>\n\n#include \"coverage.h\"\n#include \"geos\/geom\/Geometry.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"table.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n\nusing namespace Ilwis;\n\nFeatureIterator::FeatureIterator() :\n _isInitial(true)\n{\n}\n\nFeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage, quint32 level) : _fcoverage(fcoverage), _isInitial(true),_types(itFEATURE), _level(level)\n{\n init();\n}\n\nFeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const std::vector<quint32> &subset, quint32 level) :\n _fcoverage(fcoverage),\n _isInitial(true),\n _subset(subset),\n _types(itFEATURE),\n _level(level)\n{\n init();\n}\n\nFeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, IlwisTypes types, quint32 level) :\n _fcoverage(fcoverage),\n _isInitial(true),\n _types(types),\n _level(level)\n{\n\n}\nFeatureIterator::FeatureIterator(const FeatureIterator &iter)\n{\n _fcoverage = iter._fcoverage;\n _isInitial = iter._isInitial;\n _iterFeatures = iter._iterFeatures;\n _subset = iter._subset;\n _iterPosition = iter._iterPosition;\n _types = iter._types;\n _level = iter._level;\n _flow = iter._flow;\n}\n\nFeatureIterator &FeatureIterator::operator ++()\n{\n if (!init()){\n move();\n }\n return *this;\n}\n\n\nFeatureIterator FeatureIterator::operator ++(int)\n{\n init();\n FeatureIterator temp(*this);\n if(!move())\n return end();\n return temp;\n}\n\nFeatureIterator &FeatureIterator::operator +(int distance)\n{\n if(!init()) {\n move(distance);\n }\n return *this;\n\n}\n\nFeatureIterator &FeatureIterator::operator -(int distance)\n{\n if(!init()) {\n move(-distance);\n }\n return *this;\n}\n\nbool FeatureIterator::operator ==(const FeatureIterator &iter)\n{\n return _iterFeatures == iter._iterFeatures;\n}\n\nbool FeatureIterator::operator !=(const FeatureIterator &iter)\n{\n return _iterFeatures != iter._iterFeatures;\n}\n\nSPFeatureI FeatureIterator::operator *()\n{\n init();\n if ( _currentLevel == 0)\n return *_iterFeatures;\n else if ( _currentIndexes.size() > 0) {\n quint32 raw = (*_subIterator).first; \/\/ index of domain value for subfeature\n QString domvalue = _fcoverage->attributeDefinitionsRef(_currentLevel).index(raw);\n return (*_iterFeatures)[domvalue];\n }\n\n return SPFeatureI();\n}\n\nFeatureIterator FeatureIterator::end() const\n{\n FeatureIterator temp(*this);\n temp._iterFeatures = _fcoverage->_features.end();\n return temp;\n}\n\nFeatureIterator FeatureIterator::end()\n{\n FeatureIterator temp(*this);\n temp._iterFeatures = _fcoverage->_features.end();\n return temp;\n}\n\n\nbool FeatureIterator::init()\n{\n if ( _isInitial) {\n const qint32 rootLevel = 0;\n _currentIndexes = _fcoverage->attributeDefinitions(rootLevel).indexes();\n _currentLevel = _level;\n _useVectorIter = _subset.size() == 0 || _subset.size() == _fcoverage->featureCount();\n _isInitial = false;\n if ( !_fcoverage->connector()->dataIsLoaded()) {\n bool ok = _fcoverage->connector()->loadData(_fcoverage.ptr());\n if (!ok)\n return false;\n }\n if ( _fcoverage->_features.size() > 0 ) {\n _iterPosition = 0;\n _iterFeatures = _fcoverage->_features.begin();\n Feature *feature = static_cast<Feature *>(_fcoverage->_features[rootLevel].get());\n _subIterator = feature->_subFeatures.begin();\n if ( _subset.size() > 0) {\n _iterFeatures += _subset[_iterPosition];\n }\n }\n } else\n return false;\n return true;\n}\n\nbool FeatureIterator::moveFlat(qint32 distance){\n if ( _currentLevel != 0)\n return moveBreadthFirst(distance);\n\n if (_useVectorIter){\n _iterFeatures += distance;\n if ( _iterFeatures == _fcoverage->_features.end()) {\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n if (_types != itFEATURE ){ \/\/ if we only want to include certain geometry types we need to move until we encounter one\n while (!hasType((*_iterFeatures)->geometryType(),_types))\n move(1);\n }\n }else {\n if ( (qint32)_iterPosition + distance < 0) {\n _iterPosition = 0;\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n _iterPosition += distance;\n if ( _iterPosition >= _subset.size()) {\n _iterPosition = _subset.size();\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n _iterFeatures = _fcoverage->_features.begin() + _subset[_iterPosition];\n\n }\n return true;\n}\n\nbool FeatureIterator::moveBreadthFirst(qint32 distance){\n \/\/ TODO : only one level deep atm, is the most used case if at all. later a full breadth first\n\n ++_iterFeatures; \/\/ move the main feature, as the subiterator is constant this should access level x in the subiterator\n if (_iterFeatures == _fcoverage->_features.end()){ \/\/ completed one level, move to next level\n ++_currentLevel;\n _iterFeatures = _fcoverage->_features.begin(); \/\/ main feature iterator back to beginning\n ++_subIterator; \/\/ next level of subfeatures\n }\n Feature *feature = static_cast<Feature *>((*_iterFeatures).get());\n if ( !feature)\n return false;\n\n \/\/ move fails if there are no more features to iterate on\n return !atEndOfFeatures();\n}\n\nbool FeatureIterator::moveDepthFirst(qint32 distance){\n\n if ( _currentLevel != 0)\n ++_subIterator; \/\/ move on subfeatures\n ++_currentLevel;\n Feature *feature = static_cast<Feature *>((*_iterFeatures).get());\n if ( _subIterator == feature->_subFeatures.end()){\n ++_iterFeatures; \/\/ to next level 0 feature\n _currentLevel = 0;\n if ( !atEndOfFeatures()) {\n \/\/ reset iteration state of subfeatures\n feature = static_cast<Feature *>((*_iterFeatures).get());\n _subIterator = feature->_subFeatures.begin();\n }\n\n }\n\n \/\/ move fails if there are no more features to iterate on\n return !atEndOfFeatures();\n\n}\n\nbool FeatureIterator::atEndOfFeatures()\n{\n return _iterFeatures == _fcoverage->_features.end();\n}\n\nbool FeatureIterator::move(qint32 distance) {\n bool ok = false;\n switch ( _flow){\n case fFLAT:\n ok = moveFlat(distance);\n break;\n case fBREADTHFIRST:\n ok = moveBreadthFirst(distance);\n break;\n case fDEPTHFIRST:\n ok = moveDepthFirst(distance);\n break;\n }\n return ok;\n}\nFeatureIterator::Flow FeatureIterator::flow() const\n{\n return _flow;\n}\n\nvoid FeatureIterator::flow(const Flow &flow)\n{\n _flow = flow;\n}\n\n<commit_msg>added guard<commit_after>#include <iterator>\n\n#include \"coverage.h\"\n#include \"geos\/geom\/Geometry.h\"\n#include \"numericrange.h\"\n#include \"numericdomain.h\"\n#include \"table.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n\nusing namespace Ilwis;\n\nFeatureIterator::FeatureIterator() :\n _isInitial(true)\n{\n}\n\nFeatureIterator::FeatureIterator(const IFeatureCoverage& fcoverage, quint32 level) : _fcoverage(fcoverage), _isInitial(true),_types(itFEATURE), _level(level)\n{\n init();\n}\n\nFeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, const std::vector<quint32> &subset, quint32 level) :\n _fcoverage(fcoverage),\n _isInitial(true),\n _subset(subset),\n _types(itFEATURE),\n _level(level)\n{\n init();\n}\n\nFeatureIterator::FeatureIterator(const Ilwis::IFeatureCoverage &fcoverage, IlwisTypes types, quint32 level) :\n _fcoverage(fcoverage),\n _isInitial(true),\n _types(types),\n _level(level)\n{\n\n}\nFeatureIterator::FeatureIterator(const FeatureIterator &iter)\n{\n _fcoverage = iter._fcoverage;\n _isInitial = iter._isInitial;\n _iterFeatures = iter._iterFeatures;\n _subset = iter._subset;\n _iterPosition = iter._iterPosition;\n _types = iter._types;\n _level = iter._level;\n _flow = iter._flow;\n}\n\nFeatureIterator &FeatureIterator::operator ++()\n{\n if (!init()){\n move();\n }\n return *this;\n}\n\n\nFeatureIterator FeatureIterator::operator ++(int)\n{\n init();\n FeatureIterator temp(*this);\n if(!move())\n return end();\n return temp;\n}\n\nFeatureIterator &FeatureIterator::operator +(int distance)\n{\n if(!init()) {\n move(distance);\n }\n return *this;\n\n}\n\nFeatureIterator &FeatureIterator::operator -(int distance)\n{\n if(!init()) {\n move(-distance);\n }\n return *this;\n}\n\nbool FeatureIterator::operator ==(const FeatureIterator &iter)\n{\n return _iterFeatures == iter._iterFeatures;\n}\n\nbool FeatureIterator::operator !=(const FeatureIterator &iter)\n{\n return _iterFeatures != iter._iterFeatures;\n}\n\nSPFeatureI FeatureIterator::operator *()\n{\n init();\n if ( _currentLevel == 0){\n if (_iterFeatures == _fcoverage->_features.end())\n return SPFeatureI();\n return *_iterFeatures;\n }\n else if ( _currentIndexes.size() > 0) {\n quint32 raw = (*_subIterator).first; \/\/ index of domain value for subfeature\n QString domvalue = _fcoverage->attributeDefinitionsRef(_currentLevel).index(raw);\n return (*_iterFeatures)[domvalue];\n }\n\n return SPFeatureI();\n}\n\nFeatureIterator FeatureIterator::end() const\n{\n FeatureIterator temp(*this);\n temp._iterFeatures = _fcoverage->_features.end();\n return temp;\n}\n\nFeatureIterator FeatureIterator::end()\n{\n FeatureIterator temp(*this);\n temp._iterFeatures = _fcoverage->_features.end();\n return temp;\n}\n\n\nbool FeatureIterator::init()\n{\n if ( _isInitial) {\n const qint32 rootLevel = 0;\n _currentIndexes = _fcoverage->attributeDefinitions(rootLevel).indexes();\n _currentLevel = _level;\n _useVectorIter = _subset.size() == 0 || _subset.size() == _fcoverage->featureCount();\n _isInitial = false;\n if ( !_fcoverage->connector()->dataIsLoaded()) {\n bool ok = _fcoverage->connector()->loadData(_fcoverage.ptr());\n if (!ok)\n return false;\n }\n if ( _fcoverage->_features.size() > 0 ) {\n _iterPosition = 0;\n _iterFeatures = _fcoverage->_features.begin();\n Feature *feature = static_cast<Feature *>(_fcoverage->_features[rootLevel].get());\n _subIterator = feature->_subFeatures.begin();\n if ( _subset.size() > 0) {\n _iterFeatures += _subset[_iterPosition];\n }\n }\n } else\n return false;\n return true;\n}\n\nbool FeatureIterator::moveFlat(qint32 distance){\n if ( _currentLevel != 0)\n return moveBreadthFirst(distance);\n\n if (_useVectorIter){\n _iterFeatures += distance;\n if ( _iterFeatures == _fcoverage->_features.end()) {\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n if (_types != itFEATURE ){ \/\/ if we only want to include certain geometry types we need to move until we encounter one\n while (!hasType((*_iterFeatures)->geometryType(),_types))\n move(1);\n }\n }else {\n if ( (qint32)_iterPosition + distance < 0) {\n _iterPosition = 0;\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n _iterPosition += distance;\n if ( _iterPosition >= _subset.size()) {\n _iterPosition = _subset.size();\n _iterFeatures = _fcoverage->_features.end();\n return false;\n }\n _iterFeatures = _fcoverage->_features.begin() + _subset[_iterPosition];\n\n }\n return true;\n}\n\nbool FeatureIterator::moveBreadthFirst(qint32 distance){\n \/\/ TODO : only one level deep atm, is the most used case if at all. later a full breadth first\n\n ++_iterFeatures; \/\/ move the main feature, as the subiterator is constant this should access level x in the subiterator\n if (_iterFeatures == _fcoverage->_features.end()){ \/\/ completed one level, move to next level\n ++_currentLevel;\n _iterFeatures = _fcoverage->_features.begin(); \/\/ main feature iterator back to beginning\n ++_subIterator; \/\/ next level of subfeatures\n }\n Feature *feature = static_cast<Feature *>((*_iterFeatures).get());\n if ( !feature)\n return false;\n\n \/\/ move fails if there are no more features to iterate on\n return !atEndOfFeatures();\n}\n\nbool FeatureIterator::moveDepthFirst(qint32 distance){\n\n if ( _currentLevel != 0)\n ++_subIterator; \/\/ move on subfeatures\n ++_currentLevel;\n Feature *feature = static_cast<Feature *>((*_iterFeatures).get());\n if ( _subIterator == feature->_subFeatures.end()){\n ++_iterFeatures; \/\/ to next level 0 feature\n _currentLevel = 0;\n if ( !atEndOfFeatures()) {\n \/\/ reset iteration state of subfeatures\n feature = static_cast<Feature *>((*_iterFeatures).get());\n _subIterator = feature->_subFeatures.begin();\n }\n\n }\n\n \/\/ move fails if there are no more features to iterate on\n return !atEndOfFeatures();\n\n}\n\nbool FeatureIterator::atEndOfFeatures()\n{\n return _iterFeatures == _fcoverage->_features.end();\n}\n\nbool FeatureIterator::move(qint32 distance) {\n bool ok = false;\n switch ( _flow){\n case fFLAT:\n ok = moveFlat(distance);\n break;\n case fBREADTHFIRST:\n ok = moveBreadthFirst(distance);\n break;\n case fDEPTHFIRST:\n ok = moveDepthFirst(distance);\n break;\n }\n return ok;\n}\nFeatureIterator::Flow FeatureIterator::flow() const\n{\n return _flow;\n}\n\nvoid FeatureIterator::flow(const Flow &flow)\n{\n _flow = flow;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2011 by Rio Yokota, Simon Layton, Lorena Barba\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include <FMM_plan.hpp>\n#include <SphericalLaplaceKernel.hpp>\n#include <UnitKernel.hpp>\n\/\/ #include <CartesianLaplaceKernel.hpp>\n#include <CartesianLaplaceKernel2.hpp>\n#include <CartesianYukawaKernel.hpp>\n\n\/\/ modify error checking for counting kernel\n\/\/ TODO: Do this much better...\n\/\/ #define UNIT_KERNEL\n\/\/#define SPH_KERNEL\n\/\/#define CART_KERNEL\n#define YUKAWA_KERNEL\n\ntemplate <typename Box>\nvoid print_box(const Box& b, std::string padding = std::string()) {\n std::cout << padding << \"Box \" << b.index()\n << \" (Level \" << b.level() << \", Parent \" << b.parent().index() << \"): \"\n << b.morton_index() << \" \" << b.center() << \"\\n\";\n\n padding.append(2,' ');\n if (!b.is_leaf()) {\n for (auto ci = b.child_begin(); ci != b.child_end(); ++ci)\n print_box(*ci, padding);\n } else {\n for (auto ci = b.body_begin(); ci != b.body_end(); ++ci)\n std::cout << padding << \"Point \" << ci->index() << \": \"\n\t\t<< ci->morton_index() << \"\\t\" << ci->point() << \"\\n\";\n }\n}\n\n\/\/ Random number in [0,1)\ninline double drand() {\n return ::drand48();\n}\n\nint main(int argc, char **argv)\n{\n int numBodies = 100;\n bool checkErrors = true;\n bool printBox = false;\n FMMOptions opts;\n opts.set_theta(1 \/ sqrtf(4)); \/\/ Multipole acceptance criteria\n opts.NCRIT = 10;\n\n \/\/ parse command line args\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i],\"-N\") == 0) {\n i++;\n numBodies = atoi(argv[i]);\n } else if (strcmp(argv[i],\"-theta\") == 0) {\n i++;\n opts.THETA = (double)atof(argv[i]);\n opts.set_theta(opts.THETA);\n } else if (strcmp(argv[i],\"-nocheck\") == 0) {\n checkErrors = false;\n } else if (strcmp(argv[i],\"-bottomup\") == 0) {\n opts.tree = FMMOptions::BOTTOMUP;\n } else if (strcmp(argv[i],\"-evaluator\") == 0) {\n i++;\n if (strcmp(argv[i],\"FMM\") == 0) {\n opts.evaluator = FMMOptions::FMM;\n } else if (strcmp(argv[i],\"TREECODE\") == 0) {\n opts.evaluator = FMMOptions::TREECODE;\n } else {\n printf(\"[W]: Unknown evaluator type: \\\"%s\\\"\\n\",argv[i]);\n }\n } else if (strcmp(argv[i],\"-ncrit\") == 0) {\n i++;\n opts.NCRIT = (unsigned)atoi(argv[i]);\n } else if (strcmp(argv[i],\"-printbox\") == 0) {\n printBox = true;\n } else {\n printf(\"[W]: Unknown command line arg: \\\"%s\\\"\\n\",argv[i]);\n }\n }\n\n \/\/ Init the FMM Kernel\n#ifdef SPH_KERNEL\n typedef SphericalLaplaceKernel kernel_type;\n kernel_type K(5);\n#endif\n#ifdef CART_KERNEL\n typedef CartesianLaplaceKernel<5> kernel_type;\n kernel_type K;\n#endif\n#ifdef YUKAWA_KERNEL\n typedef CartesianYukawaKernel kernel_type;\n kernel_type K(6,0.5);\n#endif\n#ifdef UNIT_KERNEL\n typedef UnitKernel kernel_type;\n kernel_type K;\n#endif\n typedef kernel_type::point_type point_type;\n typedef kernel_type::charge_type charge_type;\n typedef kernel_type::result_type result_type;\n\n\n \/\/ Init points and charges\n std::vector<point_type> points(numBodies);\n for (int k = 0; k < numBodies; ++k)\n points[k] = point_type(drand(), drand(), drand());\n \/\/std::vector<point_type> target_points = points;\n\n std::vector<charge_type> charges(numBodies);\n for (int k = 0; k < numBodies; ++k)\n charges[k] = drand();\n\n \/\/ Build the FMM\n \/\/fmm_plan plan = fmm_plan(K, bodies, opts);\n FMM_plan<kernel_type> plan = FMM_plan<kernel_type>(K, points, opts);\n if (printBox) {\n print_box(plan.otree.root());\n }\n\n \/\/ Execute the FMM\n \/\/fmm_execute(plan, charges, target_points);\n std::vector<result_type> result = plan.execute(charges, points);\n\n \/\/ Check the result\n \/\/ TODO: More elegant\n if (checkErrors) {\n std::vector<result_type> exact(numBodies);\n\n \/\/ Compute the result with a direct matrix-vector multiplication\n Direct::matvec(K, points, charges, exact);\n\n#if defined(SPH_KERNEL) || defined(CART_KERNEL) || defined(YUKAWA_KERNEL)\n result_type rdiff, rnorm;\n for (unsigned k = 0; k < result.size(); ++k) {\n printf(\"[%03d] exact: %lg, FMM: %lg\\n\", k, exact[k][0], result[k][0]);\n\n rdiff = (result[k] - exact[k]) * (result[k] - exact[k]);\n rnorm = exact[k] * exact[k];\n }\n\n printf(\"Error (pot) : %.4e\\n\", sqrt(rdiff[0] \/ rnorm[0]));\n printf(\"Error (acc) : %.4e\\n\", sqrt((rdiff[1]+rdiff[2]+rdiff[3]) \/\n\t\t\t\t\t(rnorm[1]+rnorm[2]+rnorm[3])));\n#endif\n#ifdef UNIT_KERNEL\n int wrong_results = 0;\n for (unsigned k = 0; k < result.size(); ++k) {\n printf(\"[%03d] exact: %lg, FMM: %lg\\n\", k, exact[k], result[k]);\n\n if ((exact[k] - result[k]) \/ exact[k] > 1e-13)\n\t++wrong_results;\n }\n printf(\"Wrong counts: %d\\n\", wrong_results);\n#endif\n }\n}\n<commit_msg>Added command line parameter for P<commit_after>\/*\nCopyright (C) 2011 by Rio Yokota, Simon Layton, Lorena Barba\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include <FMM_plan.hpp>\n#include <SphericalLaplaceKernel.hpp>\n#include <UnitKernel.hpp>\n\/\/ #include <CartesianLaplaceKernel.hpp>\n#include <CartesianLaplaceKernel2.hpp>\n#include <CartesianYukawaKernel.hpp>\n\n\/\/ modify error checking for counting kernel\n\/\/ TODO: Do this much better...\n\/\/ #define UNIT_KERNEL\n\/\/#define SPH_KERNEL\n\/\/#define CART_KERNEL\n#define YUKAWA_KERNEL\n\ntemplate <typename Box>\nvoid print_box(const Box& b, std::string padding = std::string()) {\n std::cout << padding << \"Box \" << b.index()\n << \" (Level \" << b.level() << \", Parent \" << b.parent().index() << \"): \"\n << b.morton_index() << \" \" << b.center() << \"\\n\";\n\n padding.append(2,' ');\n if (!b.is_leaf()) {\n for (auto ci = b.child_begin(); ci != b.child_end(); ++ci)\n print_box(*ci, padding);\n } else {\n for (auto ci = b.body_begin(); ci != b.body_end(); ++ci)\n std::cout << padding << \"Point \" << ci->index() << \": \"\n\t\t<< ci->morton_index() << \"\\t\" << ci->point() << \"\\n\";\n }\n}\n\n\/\/ Random number in [0,1)\ninline double drand() {\n return ::drand48();\n}\n\nint main(int argc, char **argv)\n{\n int numBodies = 100;\n bool checkErrors = true;\n bool printBox = false;\n FMMOptions opts;\n opts.set_theta(1 \/ sqrtf(4)); \/\/ Multipole acceptance criteria\n opts.NCRIT = 10;\n unsigned P = 6; \/\/ default truncation #\n\n \/\/ parse command line args\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i],\"-N\") == 0) {\n i++;\n numBodies = atoi(argv[i]);\n } else if (strcmp(argv[i],\"-theta\") == 0) {\n i++;\n opts.THETA = (double)atof(argv[i]);\n opts.set_theta(opts.THETA);\n } else if (strcmp(argv[i],\"-nocheck\") == 0) {\n checkErrors = false;\n } else if (strcmp(argv[i],\"-bottomup\") == 0) {\n opts.tree = FMMOptions::BOTTOMUP;\n } else if (strcmp(argv[i],\"-evaluator\") == 0) {\n i++;\n if (strcmp(argv[i],\"FMM\") == 0) {\n opts.evaluator = FMMOptions::FMM;\n } else if (strcmp(argv[i],\"TREECODE\") == 0) {\n opts.evaluator = FMMOptions::TREECODE;\n } else {\n printf(\"[W]: Unknown evaluator type: \\\"%s\\\"\\n\",argv[i]);\n }\n } else if (strcmp(argv[i],\"-ncrit\") == 0) {\n i++;\n opts.NCRIT = (unsigned)atoi(argv[i]);\n } else if (strcmp(argv[i],\"-printbox\") == 0) {\n printBox = true;\n } else if (strcmp(argv[i],\"-P\") == 0) {\n i++;\n P = atoi(argv[i]);\n } else {\n printf(\"[W]: Unknown command line arg: \\\"%s\\\"\\n\",argv[i]);\n }\n }\n\n \/\/ Init the FMM Kernel\n#ifdef SPH_KERNEL\n typedef SphericalLaplaceKernel kernel_type;\n kernel_type K(P);\n#endif\n#ifdef CART_KERNEL\n (void) P;\n typedef CartesianLaplaceKernel<5> kernel_type;\n kernel_type K;\n#endif\n#ifdef YUKAWA_KERNEL\n typedef CartesianYukawaKernel kernel_type;\n kernel_type K(P,0.5);\n#endif\n#ifdef UNIT_KERNEL\n typedef UnitKernel kernel_type;\n kernel_type K;\n#endif\n typedef kernel_type::point_type point_type;\n typedef kernel_type::charge_type charge_type;\n typedef kernel_type::result_type result_type;\n\n\n \/\/ Init points and charges\n std::vector<point_type> points(numBodies);\n for (int k = 0; k < numBodies; ++k)\n points[k] = point_type(drand(), drand(), drand());\n \/\/std::vector<point_type> target_points = points;\n\n std::vector<charge_type> charges(numBodies);\n for (int k = 0; k < numBodies; ++k)\n charges[k] = drand();\n\n \/\/ Build the FMM\n \/\/fmm_plan plan = fmm_plan(K, bodies, opts);\n FMM_plan<kernel_type> plan = FMM_plan<kernel_type>(K, points, opts);\n if (printBox) {\n print_box(plan.otree.root());\n }\n\n \/\/ Execute the FMM\n \/\/fmm_execute(plan, charges, target_points);\n std::vector<result_type> result = plan.execute(charges, points);\n\n \/\/ Check the result\n \/\/ TODO: More elegant\n if (checkErrors) {\n std::vector<result_type> exact(numBodies);\n\n \/\/ Compute the result with a direct matrix-vector multiplication\n Direct::matvec(K, points, charges, exact);\n\n#if defined(SPH_KERNEL) || defined(CART_KERNEL) || defined(YUKAWA_KERNEL)\n result_type rdiff, rnorm;\n for (unsigned k = 0; k < result.size(); ++k) {\n printf(\"[%03d] exact: %lg, FMM: %lg\\n\", k, exact[k][0], result[k][0]);\n\n rdiff = (result[k] - exact[k]) * (result[k] - exact[k]);\n rnorm = exact[k] * exact[k];\n }\n\n printf(\"Error (pot) : %.4e\\n\", sqrt(rdiff[0] \/ rnorm[0]));\n printf(\"Error (acc) : %.4e\\n\", sqrt((rdiff[1]+rdiff[2]+rdiff[3]) \/\n\t\t\t\t\t(rnorm[1]+rnorm[2]+rnorm[3])));\n#endif\n#ifdef UNIT_KERNEL\n int wrong_results = 0;\n for (unsigned k = 0; k < result.size(); ++k) {\n printf(\"[%03d] exact: %lg, FMM: %lg\\n\", k, exact[k], result[k]);\n\n if ((exact[k] - result[k]) \/ exact[k] > 1e-13)\n\t++wrong_results;\n }\n printf(\"Wrong counts: %d\\n\", wrong_results);\n#endif\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GamepadController.hpp\"\n#include <algorithm>\n\nusing namespace std;\n\nnamespace {\nconstexpr auto Dribble_Step_Time = RJ::Seconds(0.125);\nconstexpr auto Kicker_Step_Time = RJ::Seconds(0.125);\nconst float AXIS_MAX = 32768.0f;\n\/\/ cutoff for counting triggers as 'on'\nconst float TRIGGER_CUTOFF = 0.9;\n}\n\nstd::vector<int> GamepadController::controllersInUse = {};\nint GamepadController::joystickRemoved = -1;\n\nGamepadController::GamepadController()\n : _controller(nullptr), _lastDribblerTime(), _lastKickerTime() {\n \/\/ initialize using the SDL joystick\n if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {\n cerr << \"ERROR: SDL could not initialize game controller system! SDL \"\n \"Error: \" << SDL_GetError() << endl;\n return;\n }\n\n \/\/ Attempt to add additional mappings (relative to run)\n if (SDL_GameControllerAddMappingsFromFile(\n ApplicationRunDirectory()\n .filePath(\"..\/external\/sdlcontrollerdb\/gamecontrollerdb.txt\")\n .toStdString()\n .c_str()) == -1) {\n cout << \"Failed adding additional SDL Gamecontroller Mappings: \"\n << SDL_GetError() << endl;\n }\n\n \/\/ Controllers will be detected later if needed.\n connected = false;\n controllerId = -1;\n robotId = -1;\n openJoystick();\n}\n\nGamepadController::~GamepadController() {\n QMutexLocker(&mutex());\n SDL_GameControllerClose(_controller);\n _controller = nullptr;\n SDL_Quit();\n}\n\nvoid GamepadController::openJoystick() {\n if (SDL_NumJoysticks()) {\n \/\/ Open the first available controller\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n \/\/ setup the joystick as a game controller if available\n if (std::find(controllersInUse.begin(), controllersInUse.end(),\n i) == controllersInUse.end() &&\n SDL_IsGameController(i)) {\n std::cout << i << std::endl;\n SDL_GameController* controller;\n controller = SDL_GameControllerOpen(i);\n\n if (controller != nullptr) {\n _controller = controller;\n connected = true;\n controllerId = i;\n controllersInUse.push_back(i);\n sort(controllersInUse.begin(), controllersInUse.end());\n cout << \"Using \" << SDL_GameControllerName(_controller)\n << \" game controller as controller # \"\n << controllersInUse.size() << endl;\n break;\n } else {\n cerr << \"ERROR: Could not open controller! SDL Error: \"\n << SDL_GetError() << endl;\n }\n return;\n }\n }\n }\n}\n\nvoid GamepadController::closeJoystick() {\n cout << \"Closing \" << SDL_GameControllerName(_controller) << endl;\n SDL_GameControllerClose(_controller);\n auto index =\n find(controllersInUse.begin(), controllersInUse.end(), controllerId);\n if (index != controllersInUse.end()) {\n for (auto i = index + 1; i != controllersInUse.end(); i++) {\n *i -= 1;\n }\n controllersInUse.erase(index);\n }\n controllerId = -1;\n\n robotId = -1;\n connected = false;\n}\n\nbool GamepadController::valid() const { return connected; }\n\nvoid GamepadController::update() {\n QMutexLocker(&mutex());\n SDL_GameControllerUpdate();\n\n RJ::Time now = RJ::now();\n\n if (connected) {\n \/\/ Check if dc\n if (joystickRemoved > 0 && controllerId > joystickRemoved) {\n controllerId -= 1;\n }\n if (!SDL_GameControllerGetAttached(_controller)) {\n closeJoystick();\n return;\n }\n } else {\n \/\/ Check if new controller found\n \/\/ TODO use the SDL event API to only run this if we receive a connected\n \/\/ event.\n openJoystick();\n if (!connected) {\n return;\n }\n }\n\n \/*\n * DRIBBLER ON\/OFF\n *\/\n if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {\n _controls.dribble = true;\n } else if (SDL_GameControllerGetAxis(_controller,\n SDL_CONTROLLER_AXIS_TRIGGERLEFT) \/\n AXIS_MAX >\n TRIGGER_CUTOFF) {\n _controls.dribble = false;\n }\n\n \/*\n * DRIBBLER POWER\n *\/\n if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_A)) {\n if ((now - _lastDribblerTime) >= Dribble_Step_Time) {\n _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);\n _lastDribblerTime = now;\n }\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_Y)) {\n if ((now - _lastDribblerTime) >= Dribble_Step_Time) {\n _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);\n _lastDribblerTime = now;\n }\n } else {\n \/\/ Let dribbler speed change immediately\n _lastDribblerTime = now - Dribble_Step_Time;\n }\n\n \/*\n * KICKER POWER\n *\/\n if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_X)) {\n if ((now - _lastKickerTime) >= Kicker_Step_Time) {\n _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);\n _lastKickerTime = now;\n }\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_B)) {\n if ((now - _lastKickerTime) >= Kicker_Step_Time) {\n _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);\n _lastKickerTime = now;\n }\n } else {\n _lastKickerTime = now - Kicker_Step_Time;\n }\n\n \/*\n * KICK TRUE\/FALSE\n *\/\n _controls.kick = SDL_GameControllerGetButton(\n _controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);\n\n \/*\n * CHIP TRUE\/FALSE\n *\/\n _controls.chip = SDL_GameControllerGetAxis(\n _controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) \/\n AXIS_MAX >\n TRIGGER_CUTOFF;\n\n \/*\n * VELOCITY ROTATION\n *\/\n \/\/ Logitech F310 Controller\n _controls.rotation =\n -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) \/\n AXIS_MAX;\n\n \/*\n * VELOCITY TRANSLATION\n *\/\n auto rightX =\n SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) \/\n AXIS_MAX;\n auto rightY =\n -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) \/\n AXIS_MAX;\n\n Geometry2d::Point input(rightX, rightY);\n\n \/\/ Align along an axis using the DPAD as modifier buttons\n if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {\n input.y() = -fabs(rightY);\n input.x() = 0;\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_UP)) {\n input.y() = fabs(rightY);\n input.x() = 0;\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {\n input.y() = 0;\n input.x() = -fabs(rightX);\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {\n input.y() = 0;\n input.x() = fabs(rightX);\n }\n\n \/\/ Floating point precision error rounding\n if (_controls.kickPower < 1e-1) _controls.kickPower = 0;\n if (_controls.dribblerPower < 1e-1) _controls.dribblerPower = 0;\n if (fabs(_controls.rotation) < 5e-2) _controls.rotation = 0;\n if (fabs(input.y()) < 5e-2) input.y() = 0;\n if (fabs(input.x()) < 5e-2) input.x() = 0;\n\n _controls.translation = Geometry2d::Point(input.x(), input.y());\n}\n\nJoystickControlValues GamepadController::getJoystickControlValues() {\n QMutexLocker(&mutex());\n return _controls;\n}\n\nvoid GamepadController::reset() {\n QMutexLocker(&mutex());\n _controls.dribble = false;\n}\n<commit_msg>this probably won't help<commit_after>#include \"GamepadController.hpp\"\n#include <algorithm>\n\nusing namespace std;\n\nnamespace {\nconstexpr auto Dribble_Step_Time = RJ::Seconds(0.125);\nconstexpr auto Kicker_Step_Time = RJ::Seconds(0.125);\nconst float AXIS_MAX = 32768.0f;\n\/\/ cutoff for counting triggers as 'on'\nconst float TRIGGER_CUTOFF = 0.9;\n}\n\nstd::vector<int> GamepadController::controllersInUse = {};\nint GamepadController::joystickRemoved = -1;\n\nGamepadController::GamepadController()\n : _controller(nullptr), _lastDribblerTime(), _lastKickerTime() {\n \/\/ initialize using the SDL joystick\n if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {\n cerr << \"ERROR: SDL could not initialize game controller system! SDL \"\n \"Error: \" << SDL_GetError() << endl;\n return;\n }\n\n \/\/ Attempt to add additional mappings (relative to run)\n if (SDL_GameControllerAddMappingsFromFile(\n ApplicationRunDirectory()\n .filePath(\"..\/external\/sdlcontrollerdb\/gamecontrollerdb.txt\")\n .toStdString()\n .c_str()) == -1) {\n cout << \"Failed adding additional SDL Gamecontroller Mappings: \"\n << SDL_GetError() << endl;\n }\n\n \/\/ Controllers will be detected later if needed.\n connected = false;\n controllerId = -1;\n robotId = -1;\n openJoystick();\n}\n\nGamepadController::~GamepadController() {\n QMutexLocker(&mutex());\n SDL_GameControllerClose(_controller);\n _controller = nullptr;\n SDL_Quit();\n}\n\nvoid GamepadController::openJoystick() {\n if (SDL_NumJoysticks()) {\n \/\/ Open the first available controller\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n \/\/ setup the joystick as a game controller if available\n if (std::find(controllersInUse.begin(), controllersInUse.end(),\n i) == controllersInUse.end() &&\n SDL_IsGameController(i)) {\n std::cout << i << std::endl;\n SDL_GameController* controller;\n controller = SDL_GameControllerOpen(i);\n\n if (controller != nullptr) {\n _controller = controller;\n connected = true;\n controllerId = i;\n controllersInUse.push_back(i);\n sort(controllersInUse.begin(), controllersInUse.end());\n cout << \"Using \" << SDL_GameControllerName(_controller)\n << \" game controller as controller # \"\n << controllersInUse.size() << endl;\n break;\n } else {\n cerr << \"ERROR: Could not open controller! SDL Error: \"\n << SDL_GetError() << endl;\n }\n return;\n }\n }\n }\n}\n\nvoid GamepadController::closeJoystick() {\n cout << \"Closing \" << SDL_GameControllerName(_controller) << endl;\n SDL_GameControllerClose(_controller);\n auto index =\n find(controllersInUse.begin(), controllersInUse.end(), controllerId);\n if (index != controllersInUse.end()) {\n controllersInUse.erase(index);\n std::cout<<\"controllers in use: \"<<std::endl;\n for (; index != controllersInUse.end(); index++) {\n std::cout<<*index<<std::endl;\n *index -= 1;\n }\n }\n controllerId = -1;\n\n robotId = -1;\n connected = false;\n}\n\nbool GamepadController::valid() const { return connected; }\n\nvoid GamepadController::update() {\n QMutexLocker(&mutex());\n SDL_GameControllerUpdate();\n\n RJ::Time now = RJ::now();\n\n if (connected) {\n \/\/ Check if dc\n if (joystickRemoved > 0 && controllerId > joystickRemoved) {\n controllerId -= 1;\n }\n if (!SDL_GameControllerGetAttached(_controller)) {\n closeJoystick();\n return;\n }\n } else {\n \/\/ Check if new controller found\n \/\/ TODO use the SDL event API to only run this if we receive a connected\n \/\/ event.\n openJoystick();\n if (!connected) {\n return;\n }\n }\n\n \/*\n * DRIBBLER ON\/OFF\n *\/\n if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {\n _controls.dribble = true;\n } else if (SDL_GameControllerGetAxis(_controller,\n SDL_CONTROLLER_AXIS_TRIGGERLEFT) \/\n AXIS_MAX >\n TRIGGER_CUTOFF) {\n _controls.dribble = false;\n }\n\n \/*\n * DRIBBLER POWER\n *\/\n if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_A)) {\n if ((now - _lastDribblerTime) >= Dribble_Step_Time) {\n _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);\n _lastDribblerTime = now;\n }\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_Y)) {\n if ((now - _lastDribblerTime) >= Dribble_Step_Time) {\n _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);\n _lastDribblerTime = now;\n }\n } else {\n \/\/ Let dribbler speed change immediately\n _lastDribblerTime = now - Dribble_Step_Time;\n }\n\n \/*\n * KICKER POWER\n *\/\n if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_X)) {\n if ((now - _lastKickerTime) >= Kicker_Step_Time) {\n _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);\n _lastKickerTime = now;\n }\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_B)) {\n if ((now - _lastKickerTime) >= Kicker_Step_Time) {\n _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);\n _lastKickerTime = now;\n }\n } else {\n _lastKickerTime = now - Kicker_Step_Time;\n }\n\n \/*\n * KICK TRUE\/FALSE\n *\/\n _controls.kick = SDL_GameControllerGetButton(\n _controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);\n\n \/*\n * CHIP TRUE\/FALSE\n *\/\n _controls.chip = SDL_GameControllerGetAxis(\n _controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) \/\n AXIS_MAX >\n TRIGGER_CUTOFF;\n\n \/*\n * VELOCITY ROTATION\n *\/\n \/\/ Logitech F310 Controller\n _controls.rotation =\n -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) \/\n AXIS_MAX;\n\n \/*\n * VELOCITY TRANSLATION\n *\/\n auto rightX =\n SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) \/\n AXIS_MAX;\n auto rightY =\n -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) \/\n AXIS_MAX;\n\n Geometry2d::Point input(rightX, rightY);\n\n \/\/ Align along an axis using the DPAD as modifier buttons\n if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {\n input.y() = -fabs(rightY);\n input.x() = 0;\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_UP)) {\n input.y() = fabs(rightY);\n input.x() = 0;\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {\n input.y() = 0;\n input.x() = -fabs(rightX);\n } else if (SDL_GameControllerGetButton(_controller,\n SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {\n input.y() = 0;\n input.x() = fabs(rightX);\n }\n\n \/\/ Floating point precision error rounding\n if (_controls.kickPower < 1e-1) _controls.kickPower = 0;\n if (_controls.dribblerPower < 1e-1) _controls.dribblerPower = 0;\n if (fabs(_controls.rotation) < 5e-2) _controls.rotation = 0;\n if (fabs(input.y()) < 5e-2) input.y() = 0;\n if (fabs(input.x()) < 5e-2) input.x() = 0;\n\n _controls.translation = Geometry2d::Point(input.x(), input.y());\n}\n\nJoystickControlValues GamepadController::getJoystickControlValues() {\n QMutexLocker(&mutex());\n return _controls;\n}\n\nvoid GamepadController::reset() {\n QMutexLocker(&mutex());\n _controls.dribble = false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nclass HeapSort {\nprivate:\n\tvector<int> data;\n\tvoid Heapify();\n\tvoid HeapifyDown(int root, int bottom);\n\tbool HasChildren(int root, int bottom) const;\npublic:\n\tHeapSort(vector<int> input);\n\tvoid Sort();\n};\n\nvoid HeapSort::Heapify() {\n\t\/\/Element at (length\/2 - 1) is guaranteed to be the last node with children\n\tfor (int i=(data.size()\/2)-1; i>=0; --i) {\n\t\tHeapifyDown(i, data.size()-1);\n\t}\n}\n\nvoid HeapSort::HeapifyDown(int root, int bottom) {\n\twhile (HasChildren(root, bottom)) {\n\t\t\/\/Sift down until we reach a childless node\n\t\tint maxChild = root * 2 + 1;\n\t\t\/\/Left child definitely exists, check if right child does\n\t\tint rightChildPos = root * 2 + 2;\n\t\tif (rightChildPos <= bottom) {\n\t\t\t\/\/Check if right child is bigger\n\t\t\tif (data.at(rightChildPos) > data.at(maxChild)) {\n\t\t\t\tmaxChild = rightChildPos;\n\t\t\t}\n\t\t}\n\t\t\/\/Now we have the greatest child, check if it's larger than the root\n\t\tif (data.at(root) < data.at(maxChild)) {\n\t\t\t\/\/Child is bigger, swap them\n\t\t\titer_swap(data.begin()+root, data.begin()+maxChild);\n\t\t\t\/\/Set the root now to that child\n\t\t\troot = maxChild;\n\t\t} else {\n\t\t\t\/\/Root is already the largest, we're done\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nbool HeapSort::HasChildren(int root, int bottom) const {\n\t\/\/Return if a left child exists\n\treturn (root*2 + 1) <= bottom;\n}\n\nHeapSort::HeapSort(vector<int> input) : data(input) {}\n\nvoid HeapSort::Sort() {\n\tHeapify();\n\tint endPos = data.size()-1;\n\twhile (endPos >= 0) {\n\t\t\/\/Top of the heap is the greatest, swap it with the back\n\t\titer_swap(data.begin(), data.begin()+endPos);\n\t\t\/\/Step the back down one because that element is now in the sorted position\n\t\t--endPos;\n\t\t\/\/Now heapify down the new root element\n\t\tHeapifyDown(0, endPos);\n\t}\n\tfor (auto i : data) {\n\t\tcout << i << \" \";\n\t}\n\tcout << endl;\n}\n\nint main() {\n\tvector<int> inputNumbers;\n\t\n\t\/\/Read numbers\n\tint num;\n\twhile (cin >> num) {\n\t\tinputNumbers.emplace_back(num);\n\t}\n\n\tHeapSort heapSort(inputNumbers);\n\theapSort.Sort();\n\n\treturn 0;\n}\n<commit_msg>removed old versions<commit_after><|endoftext|>"} {"text":"<commit_before>\/* $Id$ *\/\n\n\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ This helper macros creates a chain of ESD files for you. Source can be either a text\n\/\/ file with the file paths or a directory. In the latter case all ESD files in all subdirectories\n\/\/ are considered.\n\/\/\n\/\/ Author: Jan.Fiete.Grosse-Oetringhaus@cern.ch\n\nTChain* CreateESDChain(const char* aDataDir = \"ESDfiles.txt\", Int_t aRuns = 20, Int_t offset = 0, Bool_t addFileName = kFALSE, Bool_t addFriend = kFALSE, Bool_t check = kFALSE)\n{\n \/\/ creates chain of files in a given directory or file containing a list.\n \/\/ In case of directory the structure is expected as:\n \/\/ <aDataDir>\/<dir0>\/AliESDs.root\n \/\/ <aDataDir>\/<dir1>\/AliESDs.root\n \/\/ ...\n \/\/\n \/\/ if addFileName is true the list only needs to contain the directories that contain the AliESDs.root files\n \/\/ if addFriend is true a file AliESDfriends.root is expected in the same directory and added to the chain as friend\n\n if (!aDataDir)\n return 0;\n\n Long_t id, size, flags, modtime;\n if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))\n {\n printf(\"%s not found.\\n\", aDataDir);\n return 0;\n }\n\n TChain* chain = new TChain(\"esdTree\");\n TChain* chainFriend = 0;\n \n if (addFriend)\n chainFriend = new TChain(\"esdFriendTree\");\n\n if (flags & 2)\n {\n TString execDir(gSystem->pwd());\n TSystemDirectory* baseDir = new TSystemDirectory(\".\", aDataDir);\n TList* dirList = baseDir->GetListOfFiles();\n Int_t nDirs = dirList->GetEntries();\n gSystem->cd(execDir);\n\n Int_t count = 0;\n\n for (Int_t iDir=0; iDir<nDirs; ++iDir)\n {\n TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);\n if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), \".\") == 0 || strcmp(presentDir->GetName(), \"..\") == 0)\n continue;\n\n if (offset > 0)\n {\n --offset;\n continue;\n }\n\n if (count++ == aRuns)\n break;\n\n TString presentDirName(aDataDir);\n presentDirName += \"\/\";\n presentDirName += presentDir->GetName();\n\n chain->Add(presentDirName + \"\/AliESDs.root\/esdTree\");\n }\n }\n else\n {\n \/\/ Open the input stream\n ifstream in;\n in.open(aDataDir);\n\n Int_t count = 0;\n\n \/\/ Read the input list of files and add them to the chain\n TString line;\n while(in.good()) \n {\n in >> line;\n \n if (line.Length() == 0)\n continue; \n \n if (offset > 0)\n {\n --offset;\n continue;\n }\n\n if (count++ == aRuns)\n break;\n\n TString esdFile(line);\n\n if (addFileName)\n esdFile += \"\/AliESDs.root\";\n \n TString esdFileFriend(esdFile);\n esdFileFriend.ReplaceAll(\"AliESDs.root\", \"AliESDfriends.root\");\n \n if (check)\n {\n TFile* file = TFile::Open(esdFile);\n if (!file)\n continue;\n file->Close();\n \n if (chainFriend)\n {\n TFile* file = TFile::Open(esdFileFriend);\n if (!file)\n continue;\n file->Close();\n }\n \n printf(\"%s\\n\", line.Data());\n } \n \n \/\/ add esd file\n chain->Add(esdFile);\n\n \/\/ add file\n if (chainFriend)\n chainFriend->Add(esdFileFriend);\n }\n\n in.close();\n }\n \n if (chainFriend)\n chain->AddFriend(chainFriend);\n\n return chain;\n}\n\nvoid ChainToTextFile(TChain* chain, const char* target)\n{\n \/\/ write a text list of the files in the chain\n \n TObjArray* list = chain->GetListOfFiles();\n TIterator* iter = list->MakeIterator();\n TObject* obj = 0;\n\n ofstream outfile;\n outfile.open(target);\n\n while ((obj = iter->Next())) {\n TString fileName(obj->GetTitle());\n \n fileName.Remove(fileName.Length()-13);\n\n cout << fileName.Data() << endl;\n outfile << fileName.Data() << endl;\n }\n\n outfile.close();\n\n delete iter;\n} \n\nvoid LookupWrite(TChain* chain, const char* target)\n{\n \/\/ looks up the chain and writes the remaining files to the text file target\n\n chain->Lookup();\n\n ChainToTextFile(chain, target);\n}\n\n\n\nTChain* CreateRawChain(const char* aDataDir, Int_t aRuns = 20) {\n\n TChain* chain = new TChain(\"RAW\");\n \n \/\/ ########################################################\n \/\/ get the data dir \n Char_t execDir[256];\n sprintf(execDir,gSystem->pwd());\n TSystemDirectory* baseDir = new TSystemDirectory(\".\",aDataDir);\n TList* fileList = baseDir->GetListOfFiles();\n Int_t nFiles = fileList->GetEntries();\n \/\/ go back to the dir where this script is executed\n gSystem->cd(execDir);\n\n \/\/ ########################################################\n \/\/ loop over files \n Int_t counter = 0;\n for (Int_t r=0; r<nFiles; r++) {\n \n if (counter>aRuns)\n break;\n \n TSystemFile* presentFile = (TSystemFile*)fileList->At(r);\n if (!presentFile || presentFile->IsDirectory())\n continue;\n \n if (!(TString(presentFile->GetName()).Contains(\".root\")))\n continue;\n \n counter++;\n \n \/\/cout << Form(\"%s\/%s\",aDataDir,presentFile->GetName()) << endl;\n \n chain->AddFile(Form(\"%s\/%s\",aDataDir,presentFile->GetName()));\n }\n\n\n\n}\n<commit_msg>adding function to create general chain<commit_after>\/* $Id$ *\/\n\n\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ This helper macros creates a chain of ESD files for you. Source can be either a text\n\/\/ file with the file paths or a directory. In the latter case all ESD files in all subdirectories\n\/\/ are considered.\n\/\/\n\/\/ Author: Jan.Fiete.Grosse-Oetringhaus@cern.ch\n\nTChain* CreateESDChain(const char* aDataDir = \"ESDfiles.txt\", Int_t aRuns = 20, Int_t offset = 0, Bool_t addFileName = kFALSE, Bool_t addFriend = kFALSE, const char* check = 0)\n{\n \/\/ creates chain of files in a given directory or file containing a list.\n \/\/ In case of directory the structure is expected as:\n \/\/ <aDataDir>\/<dir0>\/AliESDs.root\n \/\/ <aDataDir>\/<dir1>\/AliESDs.root\n \/\/ ...\n \/\/\n \/\/ if addFileName is true the list only needs to contain the directories that contain the AliESDs.root files\n \/\/ if addFriend is true a file AliESDfriends.root is expected in the same directory and added to the chain as friend\n \/\/ if check is != 0 the files that work are written back into the textfile with the name check\n\n if (!aDataDir)\n return 0;\n\n Long_t id, size, flags, modtime;\n if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))\n {\n printf(\"%s not found.\\n\", aDataDir);\n return 0;\n }\n\n TChain* chain = new TChain(\"esdTree\");\n TChain* chainFriend = 0;\n \n if (addFriend)\n chainFriend = new TChain(\"esdFriendTree\");\n\n if (flags & 2)\n {\n TString execDir(gSystem->pwd());\n TSystemDirectory* baseDir = new TSystemDirectory(\".\", aDataDir);\n TList* dirList = baseDir->GetListOfFiles();\n Int_t nDirs = dirList->GetEntries();\n gSystem->cd(execDir);\n\n Int_t count = 0;\n\n for (Int_t iDir=0; iDir<nDirs; ++iDir)\n {\n TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);\n if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), \".\") == 0 || strcmp(presentDir->GetName(), \"..\") == 0)\n continue;\n\n if (offset > 0)\n {\n --offset;\n continue;\n }\n\n if (count++ == aRuns)\n break;\n\n TString presentDirName(aDataDir);\n presentDirName += \"\/\";\n presentDirName += presentDir->GetName();\n\n chain->Add(presentDirName + \"\/AliESDs.root\/esdTree\");\n }\n }\n else\n {\n \/\/ Open the input stream\n ifstream in;\n in.open(aDataDir);\n\n ofstream outfile;\n if (check)\n outfile.open(check);\n\n Int_t count = 0;\n\n \/\/ Read the input list of files and add them to the chain\n TString line;\n while(in.good()) \n {\n in >> line;\n \n if (line.Length() == 0)\n continue; \n \n if (offset > 0)\n {\n --offset;\n continue;\n }\n\n if (count++ == aRuns)\n break;\n\n TString esdFile(line);\n\n if (addFileName)\n esdFile += \"\/AliESDs.root\";\n \n TString esdFileFriend(esdFile);\n esdFileFriend.ReplaceAll(\"AliESDs.root\", \"AliESDfriends.root\");\n \n if (check)\n {\n TFile* file = TFile::Open(esdFile);\n if (!file)\n continue;\n file->Close();\n \n if (chainFriend)\n {\n TFile* file = TFile::Open(esdFileFriend);\n if (!file)\n continue;\n file->Close();\n }\n \n outfile << line.Data() << endl;\n printf(\"%s\\n\", line.Data());\n } \n \n \/\/ add esd file\n chain->Add(esdFile);\n\n \/\/ add file\n if (chainFriend)\n chainFriend->Add(esdFileFriend);\n }\n\n in.close();\n \n if (check)\n outFile.close();\n }\n \n if (chainFriend)\n chain->AddFriend(chainFriend);\n\n return chain;\n}\n\nvoid ChainToTextFile(TChain* chain, const char* target)\n{\n \/\/ write a text list of the files in the chain\n \n TObjArray* list = chain->GetListOfFiles();\n TIterator* iter = list->MakeIterator();\n TObject* obj = 0;\n\n ofstream outfile;\n outfile.open(target);\n\n while ((obj = iter->Next())) {\n TString fileName(obj->GetTitle());\n \n fileName.Remove(fileName.Length()-13);\n\n outfile << fileName.Data() << endl;\n }\n\n outfile.close();\n\n delete iter;\n} \n\nvoid LookupWrite(TChain* chain, const char* target)\n{\n \/\/ looks up the chain and writes the remaining files to the text file target\n\n chain->Lookup();\n\n ChainToTextFile(chain, target);\n}\n\nTChain* CreateChain(const char* treeName, const char* aDataDir, Int_t aRuns, Int_t offset = 0)\n{\n \/\/ creates chain of files in a given directory or file containing a list.\n\n if (!treeName || !aDataDir)\n return 0;\n\n TChain* chain = new TChain(treeName);\n \n \/\/ Open the input stream\n ifstream in;\n in.open(aDataDir);\n\n Int_t count = 0;\n\n \/\/ Read the input list of files and add them to the chain\n TString line;\n while(in.good()) \n {\n in >> line;\n \n if (line.Length() == 0)\n continue; \n \n if (offset > 0)\n {\n --offset;\n continue;\n }\n\n if (count++ == aRuns)\n break;\n\n chain->Add(line);\n }\n\n in.close();\n\n return chain;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SoloFeature.h\"\n#include \"streamFuns.h\"\n#include \"TimeFunctions.h\"\n#include \"serviceFuns.cpp\"\n#include <unordered_map>\n#include \"SoloCommon.h\"\n#include <bitset>\n\n#define def_MarkNoColor (uint32) -1\n\ninline int funCompareSolo1 (const void *a, const void *b) {\n uint32 *va= (uint32*) a;\n uint32 *vb= (uint32*) b;\n\n if (va[1]>vb[1]) {\n return 1;\n } else if (va[1]<vb[1]) {\n return -1;\n } else if (va[0]>vb[0]){\n return 1;\n } else if (va[0]<vb[0]){\n return -1;\n } else {\n return 0;\n };\n};\n\nvoid SoloFeature::collapseUMI_CR(uint32 iCB, uint32 *umiArray) \n{\n \n uint32 *rGU=rCBp[iCB];\n uint32 rN=nReadPerCB[iCB]; \n \n qsort(rGU,rN,rguStride*sizeof(uint32),funCompareNumbers<uint32>); \/\/sort by gene index\n\n \/\/compact reads per gene\n uint32 gid1=-1;\/\/current gID\n uint32 nGenes=0; \/\/number of genes\n uint32 *gID = new uint32[min(featuresNumber,rN)+1]; \/\/gene IDs\n uint32 *gReadS = new uint32[min(featuresNumber,rN)+1]; \/\/start of gene reads TODO: allocate this array in the 2nd half of rGU\n for (uint32 iR=0; iR<rN*rguStride; iR+=rguStride) {\n if (rGU[iR+rguG]!=gid1) {\/\/record gene boundary\n gReadS[nGenes]=iR;\n gid1=rGU[iR+rguG];\n gID[nGenes]=gid1;\n ++nGenes;\n };\n };\n gReadS[nGenes]=rguStride*rN;\/\/so that gReadS[nGenes]-gReadS[nGenes-1] is the number of reads for nGenes, see below in qsort\n\n unordered_map<uint32, uint32> umiMaxGeneCount;\/\/for each umi, max counts of reads per gene\n \n unordered_map <uint32, unordered_map<uint32,uint32>> umiGeneHash, umiGeneHash0;\n \/\/UMI \/\/Gene \/\/Count\n unordered_map <uint32,uint32> geneCounts;\n\n if (countCellGeneUMI.size() < countCellGeneUMIindex[iCB] + nGenes*countMatStride) \/\/allocated vector too small\n countCellGeneUMI.resize(countCellGeneUMI.size()*2);\n \n nGenePerCB[iCB]=0;\n nUMIperCB[iCB]=0;\n countCellGeneUMIindex[iCB+1]=countCellGeneUMIindex[iCB];\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/ main cycle over genes\n for (uint32 iG=0; iG<nGenes; iG++) {\/\/collapse UMIs for each gene\n uint32 *rGU1=rGU+gReadS[iG];\n\n if (gReadS[iG+1]==gReadS[iG])\n continue; \/\/no reads\n\n qsort(rGU1, (gReadS[iG+1]-gReadS[iG])\/rguStride, rguStride*sizeof(uint32), funCompareTypeShift<uint32,rguU>);\n \n \/\/exact collapse\n uint32 iR1=-umiArrayStride; \/\/number of distinct UMIs for this gene\n uint32 u1=-1;\n for (uint32 iR=rguU; iR<gReadS[iG+1]-gReadS[iG]; iR+=rguStride) {\/\/count and collapse identical UMIs\n \n if (rGU1[iR]!=u1) {\n iR1 += umiArrayStride;\n u1=rGU1[iR];\n umiArray[iR1]=u1;\n umiArray[iR1+1]=0;\n };\n umiArray[iR1+1]++;\n \/\/if ( umiArray[iR1+1]>nRumiMax) nRumiMax=umiArray[iR1+1];\n };\n\n uint32 nU0=(iR1+umiArrayStride)\/umiArrayStride;\n uint32 nU1=nU0;\/\/2 types of 1MM collapsing\n \n if (pSolo.umiFiltering.MultiGeneUMI) {\n for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n umiGeneHash0[umiArray[iu+0]][gID[iG]]+=umiArray[iu+1];\/\/this sums read counts over UMIs that were collapsed\n };\n }; \n \n qsort(umiArray, nU0, umiArrayStride*sizeof(uint32), funCompareSolo1);\n for (uint64 iu=0; iu<(nU0-1)*umiArrayStride; iu+=umiArrayStride) {\n uint64 iuu;\n for (iuu=(nU0-1)*umiArrayStride; iuu>iu; iuu-=umiArrayStride) {\n\n uint32 uuXor=umiArray[iu+0] ^ umiArray[iuu+0];\n\n if ( (uuXor >> (__builtin_ctz(uuXor)\/2)*2) <= 3 ) {\/\/1MM\n umiArray[iu+0]=umiArray[iuu+0];\/\/replace this one with the previous one\n break; \/\/1MM\n };\n };\n };\n\n if (pSolo.umiFiltering.MultiGeneUMI) {\n for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n umiGeneHash[umiArray[iu+0]][gID[iG]]+=umiArray[iu+1];\/\/this sums read counts over UMIs that were collapsed\n };\n } else {\n qsort(umiArray, nU0, umiArrayStride*sizeof(uint32), funCompareNumbers<uint32>);\n nU1=1;\n for (uint64 iu=umiArrayStride; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n if (umiArray[iu+0]!=umiArray[iu+0-umiArrayStride]) {\n nU1++;\n };\n };\n nGenePerCB[iCB]++;\n nUMIperCB[iCB]+=nU1;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+0]=gID[iG];\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+1]=nU1;\n countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;\/\/iCB+1 accumulates the index\n };\n };\n\n if (pSolo.umiFiltering.MultiGeneUMI) {\n \n for (auto &iu: umiGeneHash) {\n \n uint32 maxu=0, maxg=-1;\n for (auto &ig : iu.second) {\n if (ig.second>maxu) {\n maxu=ig.second;\n maxg=ig.first;\n } else if (ig.second==maxu) {\n maxg=-1;\n };\n };\n if ( maxg+1==0 )\n continue; \/\/this umi is not counted for any gene\n \n for (auto &ig : umiGeneHash0[iu.first]) {\/\/check that this umi\/gene had also top count for uncorrected umis\n if (ig.second>umiGeneHash0[iu.first][maxg]) {\n maxg=-1;\n break;\n };\n };\n if ( maxg+1!=0 )\n geneCounts[maxg]++;\n \n };\n\n for (auto &ig: geneCounts) {\n nGenePerCB[iCB]++;\n nUMIperCB[iCB]+=ig.second;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+0]=ig.first;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+1]=ig.second;\n countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;\/\/iCB+1 accumulates the index\n };\n\n };\n};\n<commit_msg>And another attempt to match CR3.<commit_after>#include \"SoloFeature.h\"\n#include \"streamFuns.h\"\n#include \"TimeFunctions.h\"\n#include \"serviceFuns.cpp\"\n#include <unordered_map>\n#include \"SoloCommon.h\"\n#include <bitset>\n\n#define def_MarkNoColor (uint32) -1\n\ninline int funCompareSolo1 (const void *a, const void *b) {\n uint32 *va= (uint32*) a;\n uint32 *vb= (uint32*) b;\n\n if (va[1]>vb[1]) {\n return 1;\n } else if (va[1]<vb[1]) {\n return -1;\n } else if (va[0]>vb[0]){\n return 1;\n } else if (va[0]<vb[0]){\n return -1;\n } else {\n return 0;\n };\n};\n\nvoid SoloFeature::collapseUMI_CR(uint32 iCB, uint32 *umiArray) \n{\n \n uint32 *rGU=rCBp[iCB];\n uint32 rN=nReadPerCB[iCB]; \n \n qsort(rGU,rN,rguStride*sizeof(uint32),funCompareNumbers<uint32>); \/\/sort by gene index\n\n \/\/compact reads per gene\n uint32 gid1=-1;\/\/current gID\n uint32 nGenes=0; \/\/number of genes\n uint32 *gID = new uint32[min(featuresNumber,rN)+1]; \/\/gene IDs\n uint32 *gReadS = new uint32[min(featuresNumber,rN)+1]; \/\/start of gene reads TODO: allocate this array in the 2nd half of rGU\n for (uint32 iR=0; iR<rN*rguStride; iR+=rguStride) {\n if (rGU[iR+rguG]!=gid1) {\/\/record gene boundary\n gReadS[nGenes]=iR;\n gid1=rGU[iR+rguG];\n gID[nGenes]=gid1;\n ++nGenes;\n };\n };\n gReadS[nGenes]=rguStride*rN;\/\/so that gReadS[nGenes]-gReadS[nGenes-1] is the number of reads for nGenes, see below in qsort\n\n unordered_map<uint32, uint32> umiMaxGeneCount;\/\/for each umi, max counts of reads per gene\n \n unordered_map <uint32, unordered_map<uint32,uint32>> umiGeneHash, umiGeneHash0;\n \/\/UMI \/\/Gene \/\/Count\n unordered_map <uint32,uint32> geneCounts;\n\n if (countCellGeneUMI.size() < countCellGeneUMIindex[iCB] + nGenes*countMatStride) \/\/allocated vector too small\n countCellGeneUMI.resize(countCellGeneUMI.size()*2);\n \n nGenePerCB[iCB]=0;\n nUMIperCB[iCB]=0;\n countCellGeneUMIindex[iCB+1]=countCellGeneUMIindex[iCB];\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/ main cycle over genes\n for (uint32 iG=0; iG<nGenes; iG++) {\/\/collapse UMIs for each gene\n uint32 *rGU1=rGU+gReadS[iG];\n\n if (gReadS[iG+1]==gReadS[iG])\n continue; \/\/no reads\n\n qsort(rGU1, (gReadS[iG+1]-gReadS[iG])\/rguStride, rguStride*sizeof(uint32), funCompareTypeShift<uint32,rguU>);\n \n \/\/exact collapse\n uint32 iR1=-umiArrayStride; \/\/number of distinct UMIs for this gene\n uint32 u1=-1;\n for (uint32 iR=rguU; iR<gReadS[iG+1]-gReadS[iG]; iR+=rguStride) {\/\/count and collapse identical UMIs\n \n if (rGU1[iR]!=u1) {\n iR1 += umiArrayStride;\n u1=rGU1[iR];\n umiArray[iR1]=u1;\n umiArray[iR1+1]=0;\n };\n umiArray[iR1+1]++;\n \/\/if ( umiArray[iR1+1]>nRumiMax) nRumiMax=umiArray[iR1+1];\n };\n\n uint32 nU0=(iR1+umiArrayStride)\/umiArrayStride;\n uint32 nU1=nU0;\/\/2 types of 1MM collapsing\n \n if (pSolo.umiFiltering.MultiGeneUMI) {\n for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n umiGeneHash0[umiArray[iu+0]][gID[iG]]+=umiArray[iu+1];\/\/this sums read counts over UMIs that were collapsed\n };\n }; \n \n qsort(umiArray, nU0, umiArrayStride*sizeof(uint32), funCompareSolo1);\n for (uint64 iu=0; iu<(nU0-1)*umiArrayStride; iu+=umiArrayStride) {\n uint64 iuu;\n for (iuu=(nU0-1)*umiArrayStride; iuu>iu; iuu-=umiArrayStride) {\n\n uint32 uuXor=umiArray[iu+0] ^ umiArray[iuu+0];\n\n if ( (uuXor >> (__builtin_ctz(uuXor)\/2)*2) <= 3 ) {\/\/1MM\n umiArray[iu+0]=umiArray[iuu+0];\/\/replace this one with the previous one\n break; \/\/1MM\n };\n };\n };\n\n if (pSolo.umiFiltering.MultiGeneUMI) {\n for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n umiGeneHash[umiArray[iu+0]][gID[iG]]+=umiArray[iu+1];\/\/this sums read counts over UMIs that were collapsed\n };\n } else {\n qsort(umiArray, nU0, umiArrayStride*sizeof(uint32), funCompareNumbers<uint32>);\n nU1=1;\n for (uint64 iu=umiArrayStride; iu<nU0*umiArrayStride; iu+=umiArrayStride) {\n if (umiArray[iu+0]!=umiArray[iu+0-umiArrayStride]) {\n nU1++;\n };\n };\n nGenePerCB[iCB]++;\n nUMIperCB[iCB]+=nU1;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+0]=gID[iG];\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+1]=nU1;\n countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;\/\/iCB+1 accumulates the index\n };\n };\n\n if (pSolo.umiFiltering.MultiGeneUMI) {\n \n for (auto &iu: umiGeneHash) {\n \n uint32 maxu=0, maxg=-1;\n for (auto &ig : iu.second) {\n if (ig.second>maxu) {\n maxu=ig.second;\n maxg=ig.first;\n } else if (ig.second==maxu) {\n maxg=-1;\n };\n };\n if ( maxg+1==0 )\n continue; \/\/this umi is not counted for any gene\n \n for (auto &ig : umiGeneHash0[iu.first]) {\/\/check that this umi\/gene has >= read count than any uncorrected\n if (ig.second>maxu && ig.first!=maxg) {\n maxg=-1;\n break;\n };\n };\n if ( maxg+1!=0 )\n geneCounts[maxg]++;\n \n };\n\n for (auto &ig: geneCounts) {\n nGenePerCB[iCB]++;\n nUMIperCB[iCB]+=ig.second;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+0]=ig.first;\n countCellGeneUMI[countCellGeneUMIindex[iCB+1]+1]=ig.second;\n countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;\/\/iCB+1 accumulates the index\n };\n\n };\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ThreadPlanStepRange.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Target\/ThreadPlanStepRange.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Thread.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanStepRange: Step through a stack range, either stepping over or into\n\/\/ based on the value of \\a type.\n\/\/----------------------------------------------------------------------\n\nThreadPlanStepRange::ThreadPlanStepRange (ThreadPlanKind kind, const char *name, Thread &thread, const AddressRange &range, const SymbolContext &addr_context, lldb::RunMode stop_others) :\n ThreadPlan (kind, name, thread, eVoteNoOpinion, eVoteNoOpinion),\n m_addr_context (addr_context),\n m_address_range (range),\n m_stop_others (stop_others),\n m_stack_depth (0),\n m_stack_id (),\n m_no_more_plans (false),\n m_first_run_event (true)\n{\n m_stack_depth = m_thread.GetStackFrameCount();\n m_stack_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();\n}\n\nThreadPlanStepRange::~ThreadPlanStepRange ()\n{\n}\n\nbool\nThreadPlanStepRange::ValidatePlan (Stream *error)\n{\n return true;\n}\n\nbool\nThreadPlanStepRange::PlanExplainsStop ()\n{\n \/\/ We don't explain signals or breakpoints (breakpoints that handle stepping in or\n \/\/ out will be handled by a child plan.\n StopInfoSP stop_info_sp = GetPrivateStopReason();\n if (stop_info_sp)\n {\n StopReason reason = stop_info_sp->GetStopReason();\n\n switch (reason)\n {\n case eStopReasonBreakpoint:\n case eStopReasonWatchpoint:\n case eStopReasonSignal:\n case eStopReasonException:\n return false;\n default:\n return true;\n }\n }\n return true;\n}\n\nVote\nThreadPlanStepRange::ShouldReportStop (Event *event_ptr)\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n\n const Vote vote = IsPlanComplete() ? eVoteYes : eVoteNo;\n if (log)\n log->Printf (\"ThreadPlanStepRange::ShouldReportStop() returning vote %i\\n\", eVoteYes);\n return vote;\n}\n\nbool\nThreadPlanStepRange::InRange ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n bool ret_value = false;\n\n lldb::addr_t pc_load_addr = m_thread.GetRegisterContext()->GetPC();\n\n ret_value = m_address_range.ContainsLoadAddress(pc_load_addr, &m_thread.GetProcess().GetTarget());\n \n if (!ret_value)\n {\n \/\/ See if we've just stepped to another part of the same line number...\n StackFrame *frame = m_thread.GetStackFrameAtIndex(0).get();\n \n SymbolContext new_context(frame->GetSymbolContext(eSymbolContextEverything));\n if (m_addr_context.line_entry.IsValid() && new_context.line_entry.IsValid())\n {\n if ((m_addr_context.line_entry.file == new_context.line_entry.file)\n && (m_addr_context.line_entry.line == new_context.line_entry.line))\n {\n m_addr_context = new_context;\n m_address_range = m_addr_context.line_entry.range;\n ret_value = true;\n if (log)\n {\n StreamString s;\n m_address_range.Dump (&s, &m_thread.GetProcess().GetTarget(), Address::DumpStyleLoadAddress);\n\n log->Printf (\"Step range plan stepped to another range of same line: %s\", s.GetData());\n }\n }\n }\n \n }\n\n if (!ret_value && log)\n log->Printf (\"Step range plan out of range to 0x%llx\", pc_load_addr);\n\n return ret_value;\n}\n\nbool\nThreadPlanStepRange::InSymbol()\n{\n lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();\n if (m_addr_context.function != NULL)\n {\n return m_addr_context.function->GetAddressRange().ContainsLoadAddress (cur_pc, &m_thread.GetProcess().GetTarget());\n }\n else if (m_addr_context.symbol != NULL)\n {\n return m_addr_context.symbol->GetAddressRangeRef().ContainsLoadAddress (cur_pc, &m_thread.GetProcess().GetTarget());\n }\n return false;\n}\n\n\/\/ FIXME: This should also handle inlining if we aren't going to do inlining in the\n\/\/ main stack.\n\/\/\n\/\/ Ideally we should remember the whole stack frame list, and then compare that\n\/\/ to the current list.\n\nbool\nThreadPlanStepRange::FrameIsYounger ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n \n \/\/ FIXME: Might be better to do this by storing the FrameID we started in and seeing if that is still above\n \/\/ us on the stack. Counting the whole stack could be expensive.\n \n uint32_t current_depth = m_thread.GetStackFrameCount();\n if (current_depth == m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger still in start function.\");\n return false;\n }\n else if (current_depth < m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger stepped out: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return false;\n }\n else\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger stepped in: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return true;\n }\n}\n\nbool\nThreadPlanStepRange::FrameIsOlder ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n uint32_t current_depth = m_thread.GetStackFrameCount();\n if (current_depth == m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder still in start function.\");\n return false;\n }\n else if (current_depth < m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder stepped out: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return true;\n }\n else\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder stepped in: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return false;\n }\n}\n\nbool\nThreadPlanStepRange::StopOthers ()\n{\n if (m_stop_others == lldb::eOnlyThisThread\n || m_stop_others == lldb::eOnlyDuringStepping)\n return true;\n else\n return false;\n}\n\nbool\nThreadPlanStepRange::WillStop ()\n{\n return true;\n}\n\nStateType\nThreadPlanStepRange::GetPlanRunState ()\n{\n return eStateStepping;\n}\n\nbool\nThreadPlanStepRange::MischiefManaged ()\n{\n bool done = true;\n if (!IsPlanComplete())\n {\n if (InRange())\n {\n done = false;\n }\n else if (!FrameIsOlder())\n {\n if (m_no_more_plans)\n done = true;\n else\n done = false;\n }\n else\n done = true;\n }\n\n if (done)\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf(\"Completed step through range plan.\");\n ThreadPlan::MischiefManaged ();\n return true;\n }\n else\n {\n return false;\n }\n\n}\n<commit_msg>Fixed incorrect logging printf (patch from Stephen Wilson).<commit_after>\/\/===-- ThreadPlanStepRange.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Target\/ThreadPlanStepRange.h\"\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n\n#include \"lldb\/lldb-private-log.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/Symbol.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Target\/RegisterContext.h\"\n#include \"lldb\/Target\/StopInfo.h\"\n#include \"lldb\/Target\/Thread.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\n\/\/----------------------------------------------------------------------\n\/\/ ThreadPlanStepRange: Step through a stack range, either stepping over or into\n\/\/ based on the value of \\a type.\n\/\/----------------------------------------------------------------------\n\nThreadPlanStepRange::ThreadPlanStepRange (ThreadPlanKind kind, const char *name, Thread &thread, const AddressRange &range, const SymbolContext &addr_context, lldb::RunMode stop_others) :\n ThreadPlan (kind, name, thread, eVoteNoOpinion, eVoteNoOpinion),\n m_addr_context (addr_context),\n m_address_range (range),\n m_stop_others (stop_others),\n m_stack_depth (0),\n m_stack_id (),\n m_no_more_plans (false),\n m_first_run_event (true)\n{\n m_stack_depth = m_thread.GetStackFrameCount();\n m_stack_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();\n}\n\nThreadPlanStepRange::~ThreadPlanStepRange ()\n{\n}\n\nbool\nThreadPlanStepRange::ValidatePlan (Stream *error)\n{\n return true;\n}\n\nbool\nThreadPlanStepRange::PlanExplainsStop ()\n{\n \/\/ We don't explain signals or breakpoints (breakpoints that handle stepping in or\n \/\/ out will be handled by a child plan.\n StopInfoSP stop_info_sp = GetPrivateStopReason();\n if (stop_info_sp)\n {\n StopReason reason = stop_info_sp->GetStopReason();\n\n switch (reason)\n {\n case eStopReasonBreakpoint:\n case eStopReasonWatchpoint:\n case eStopReasonSignal:\n case eStopReasonException:\n return false;\n default:\n return true;\n }\n }\n return true;\n}\n\nVote\nThreadPlanStepRange::ShouldReportStop (Event *event_ptr)\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n\n const Vote vote = IsPlanComplete() ? eVoteYes : eVoteNo;\n if (log)\n log->Printf (\"ThreadPlanStepRange::ShouldReportStop() returning vote %i\\n\", vote);\n return vote;\n}\n\nbool\nThreadPlanStepRange::InRange ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n bool ret_value = false;\n\n lldb::addr_t pc_load_addr = m_thread.GetRegisterContext()->GetPC();\n\n ret_value = m_address_range.ContainsLoadAddress(pc_load_addr, &m_thread.GetProcess().GetTarget());\n \n if (!ret_value)\n {\n \/\/ See if we've just stepped to another part of the same line number...\n StackFrame *frame = m_thread.GetStackFrameAtIndex(0).get();\n \n SymbolContext new_context(frame->GetSymbolContext(eSymbolContextEverything));\n if (m_addr_context.line_entry.IsValid() && new_context.line_entry.IsValid())\n {\n if ((m_addr_context.line_entry.file == new_context.line_entry.file)\n && (m_addr_context.line_entry.line == new_context.line_entry.line))\n {\n m_addr_context = new_context;\n m_address_range = m_addr_context.line_entry.range;\n ret_value = true;\n if (log)\n {\n StreamString s;\n m_address_range.Dump (&s, &m_thread.GetProcess().GetTarget(), Address::DumpStyleLoadAddress);\n\n log->Printf (\"Step range plan stepped to another range of same line: %s\", s.GetData());\n }\n }\n }\n \n }\n\n if (!ret_value && log)\n log->Printf (\"Step range plan out of range to 0x%llx\", pc_load_addr);\n\n return ret_value;\n}\n\nbool\nThreadPlanStepRange::InSymbol()\n{\n lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();\n if (m_addr_context.function != NULL)\n {\n return m_addr_context.function->GetAddressRange().ContainsLoadAddress (cur_pc, &m_thread.GetProcess().GetTarget());\n }\n else if (m_addr_context.symbol != NULL)\n {\n return m_addr_context.symbol->GetAddressRangeRef().ContainsLoadAddress (cur_pc, &m_thread.GetProcess().GetTarget());\n }\n return false;\n}\n\n\/\/ FIXME: This should also handle inlining if we aren't going to do inlining in the\n\/\/ main stack.\n\/\/\n\/\/ Ideally we should remember the whole stack frame list, and then compare that\n\/\/ to the current list.\n\nbool\nThreadPlanStepRange::FrameIsYounger ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n \n \/\/ FIXME: Might be better to do this by storing the FrameID we started in and seeing if that is still above\n \/\/ us on the stack. Counting the whole stack could be expensive.\n \n uint32_t current_depth = m_thread.GetStackFrameCount();\n if (current_depth == m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger still in start function.\");\n return false;\n }\n else if (current_depth < m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger stepped out: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return false;\n }\n else\n {\n if (log)\n log->Printf (\"Step range FrameIsYounger stepped in: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return true;\n }\n}\n\nbool\nThreadPlanStepRange::FrameIsOlder ()\n{\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n uint32_t current_depth = m_thread.GetStackFrameCount();\n if (current_depth == m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder still in start function.\");\n return false;\n }\n else if (current_depth < m_stack_depth)\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder stepped out: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return true;\n }\n else\n {\n if (log)\n log->Printf (\"Step range FrameIsOlder stepped in: start depth: %d current depth %d.\", m_stack_depth, current_depth);\n return false;\n }\n}\n\nbool\nThreadPlanStepRange::StopOthers ()\n{\n if (m_stop_others == lldb::eOnlyThisThread\n || m_stop_others == lldb::eOnlyDuringStepping)\n return true;\n else\n return false;\n}\n\nbool\nThreadPlanStepRange::WillStop ()\n{\n return true;\n}\n\nStateType\nThreadPlanStepRange::GetPlanRunState ()\n{\n return eStateStepping;\n}\n\nbool\nThreadPlanStepRange::MischiefManaged ()\n{\n bool done = true;\n if (!IsPlanComplete())\n {\n if (InRange())\n {\n done = false;\n }\n else if (!FrameIsOlder())\n {\n if (m_no_more_plans)\n done = true;\n else\n done = false;\n }\n else\n done = true;\n }\n\n if (done)\n {\n LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));\n if (log)\n log->Printf(\"Completed step through range plan.\");\n ThreadPlan::MischiefManaged ();\n return true;\n }\n else\n {\n return false;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ PROJECT: Aspia\n\/\/ FILE: console\/address_book_dialog.cc\n\/\/ LICENSE: GNU General Public License 3\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\n\/\/\n\n#include \"console\/address_book_dialog.h\"\n\n#include <QAbstractButton>\n#include <QMessageBox>\n\n#include \"crypto\/data_encryptor.h\"\n#include \"crypto\/random.h\"\n\nnamespace aspia {\n\nnamespace {\n\nconstexpr int kMaxNameLength = 64;\nconstexpr int kMinNameLength = 1;\nconstexpr int kMinPasswordLength = 8;\nconstexpr int kMaxPasswordLength = 64;\nconstexpr int kMaxCommentLength = 2048;\n\n} \/\/ namespace\n\nAddressBookDialog::AddressBookDialog(QWidget* parent, proto::address_book::File* file,\n proto::address_book::Data* data, QByteArray* key)\n : QDialog(parent), file_(file), data_(data), key_(key)\n{\n ui.setupUi(this);\n\n connect(ui.button_box, &QDialogButtonBox::clicked, this, &AddressBookDialog::buttonBoxClicked);\n\n connect(ui.combo_encryption, QOverload<int>::of(&QComboBox::currentIndexChanged), this,\n &AddressBookDialog::encryptionTypedChanged);\n\n ui.combo_encryption->addItem(tr(\"Without Encryption\"),\n QVariant(proto::address_book::ENCRYPTION_TYPE_NONE));\n ui.combo_encryption->addItem(tr(\"XChaCha20 + Poly1305 (256-bit key)\"),\n QVariant(proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305));\n\n ui.edit_name->setText(QString::fromStdString(data_->root_group().name()));\n ui.edit_comment->setPlainText(QString::fromStdString(data_->root_group().comment()));\n\n int current = ui.combo_encryption->findData(QVariant(file->encryption_type()));\n if (current != -1)\n ui.combo_encryption->setCurrentIndex(current);\n\n if (file->encryption_type() == proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305)\n {\n if (!key_->isEmpty())\n {\n QString text = tr(\"Double-click to change\");\n\n ui.edit_password->setText(text);\n ui.edit_password_repeat->setText(text);\n\n ui.edit_password->setEnabled(false);\n ui.edit_password_repeat->setEnabled(false);\n\n ui.edit_password->setEchoMode(QLineEdit::Normal);\n ui.edit_password->setInputMethodHints(Qt::ImhNone);\n\n ui.edit_password_repeat->setEchoMode(QLineEdit::Normal);\n ui.edit_password_repeat->setInputMethodHints(Qt::ImhNone);\n\n ui.edit_password->installEventFilter(this);\n ui.edit_password_repeat->installEventFilter(this);\n\n ui.spinbox_password_salt->setValue(file_->hashing_salt().size());\n ui.spinbox_hashing_rounds->setValue(file_->hashing_rounds());\n\n ui.spinbox_salt_before->setValue(data_->salt1().size());\n ui.spinbox_salt_after->setValue(data_->salt2().size());\n\n password_changed_ = false;\n }\n }\n else\n {\n Q_ASSERT(file->encryption_type() == proto::address_book::ENCRYPTION_TYPE_NONE);\n\n ui.edit_password->setEnabled(false);\n\n \/\/ Disable Advanced tab.\n ui.tab_widget->setTabEnabled(1, false);\n }\n\n connect(ui.spinbox_hashing_rounds, QOverload<int>::of(&QSpinBox::valueChanged), this,\n &AddressBookDialog::hashingRoundsChanged);\n\n connect(ui.spinbox_password_salt, QOverload<int>::of(&QSpinBox::valueChanged), this,\n &AddressBookDialog::hashingSaltChanged);\n}\n\nAddressBookDialog::~AddressBookDialog() = default;\n\nbool AddressBookDialog::eventFilter(QObject* object, QEvent* event)\n{\n if (event->type() == QEvent::MouseButtonDblClick &&\n (object == ui.edit_password || object == ui.edit_password_repeat))\n {\n setPasswordChanged();\n }\n\n return false;\n}\n\nvoid AddressBookDialog::buttonBoxClicked(QAbstractButton* button)\n{\n if (ui.button_box->standardButton(button) != QDialogButtonBox::Ok)\n {\n reject();\n close();\n return;\n }\n\n QString name = ui.edit_name->text();\n if (name.length() > kMaxNameLength)\n {\n showError(tr(\"Too long name. The maximum length of the name is 64 characters.\"));\n return;\n }\n else if (name.length() < kMinNameLength)\n {\n showError(tr(\"Name can not be empty.\"));\n return;\n }\n\n QString comment = ui.edit_comment->toPlainText();\n if (comment.length() > kMaxCommentLength)\n {\n showError(tr(\"Too long comment. The maximum length of the comment is 2048 characters.\"));\n return;\n }\n\n proto::address_book::EncryptionType encryption_type =\n static_cast<proto::address_book::EncryptionType>(\n ui.combo_encryption->currentData().toInt());\n\n switch (encryption_type)\n {\n case proto::address_book::ENCRYPTION_TYPE_NONE:\n {\n file_->mutable_hashing_salt()->clear();\n file_->set_hashing_rounds(0);\n\n data_->mutable_salt1()->clear();\n data_->mutable_salt2()->clear();\n }\n break;\n\n case proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305:\n {\n if (password_changed_)\n {\n QString password = ui.edit_password->text();\n QString password_repeat = ui.edit_password_repeat->text();\n\n if (password != password_repeat)\n {\n showError(tr(\"The passwords you entered do not match.\"));\n return;\n }\n\n if (password.length() < kMinPasswordLength)\n {\n showError(tr(\"Password can not be shorter than 8 characters.\"));\n return;\n }\n\n \/\/ Generate salt, which is added after each iteration of the hashing.\n \/\/ New salt is generated each time the password is changed.\n QByteArray hashing_salt =\n Random::generateBuffer(ui.spinbox_password_salt->value());\n\n \/\/ Save the salt and the number of hashing iterations.\n file_->set_hashing_rounds(ui.spinbox_hashing_rounds->value());\n *file_->mutable_hashing_salt() = hashing_salt.toStdString();\n\n \/\/ Now generate a key for encryption\/decryption.\n *key_ = DataEncryptor::createKey(password.toUtf8(), hashing_salt,\n file_->hashing_rounds());\n }\n\n int salt_before_size = ui.spinbox_salt_before->value();\n int salt_after_size = ui.spinbox_salt_after->value();\n\n if (salt_before_size != data_->salt1().size())\n *data_->mutable_salt1() = Random::generateBuffer(salt_before_size).toStdString();\n\n if (salt_after_size != data_->salt2().size())\n *data_->mutable_salt2() = Random::generateBuffer(salt_after_size).toStdString();\n }\n break;\n\n default:\n qFatal(\"Unexpected encryption type: %d\", encryption_type);\n return;\n }\n\n data_->mutable_root_group()->set_name(name.toStdString());\n data_->mutable_root_group()->set_comment(comment.toStdString());\n\n file_->set_encryption_type(encryption_type);\n\n accept();\n close();\n}\n\nvoid AddressBookDialog::encryptionTypedChanged(int item_index)\n{\n proto::address_book::EncryptionType encryption_type =\n static_cast<proto::address_book::EncryptionType>(\n ui.combo_encryption->itemData(item_index).toInt());\n\n switch (encryption_type)\n {\n case proto::address_book::ENCRYPTION_TYPE_NONE:\n {\n ui.edit_password->setEnabled(false);\n ui.edit_password_repeat->setEnabled(false);\n\n ui.edit_password->clear();\n ui.edit_password_repeat->clear();\n\n \/\/ Disable Advanced tab.\n ui.tab_widget->setTabEnabled(1, false);\n }\n break;\n\n case proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305:\n {\n ui.edit_password->setEnabled(true);\n ui.edit_password_repeat->setEnabled(true);\n\n \/\/ Enable Advanced tab.\n ui.tab_widget->setTabEnabled(1, true);\n }\n break;\n\n default:\n qFatal(\"Unexpected encryption type: %d\", encryption_type);\n break;\n }\n}\n\nvoid AddressBookDialog::hashingRoundsChanged(int \/* value *\/)\n{\n if (password_changed_ || value_reverting_)\n return;\n\n if (QMessageBox::question(\n this,\n tr(\"Confirmation\"),\n tr(\"At change the number of hashing iterations, you will need to re-enter the password. Continue?\"),\n QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)\n {\n setPasswordChanged();\n }\n else\n {\n \/\/ Revert value.\n value_reverting_ = true;\n ui.spinbox_hashing_rounds->setValue(file_->hashing_rounds());\n value_reverting_ = false;\n }\n}\n\nvoid AddressBookDialog::hashingSaltChanged(int \/* value *\/)\n{\n if (password_changed_ || value_reverting_)\n return;\n\n if (QMessageBox::question(\n this,\n tr(\"Confirmation\"),\n tr(\"At change the size of hashing salt, you will need to re-enter the password. Continue?\"),\n QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)\n {\n setPasswordChanged();\n }\n else\n {\n \/\/ Revert value.\n value_reverting_ = true;\n ui.spinbox_password_salt->setValue(file_->hashing_salt().size());\n value_reverting_ = false;\n }\n}\n\nvoid AddressBookDialog::setPasswordChanged()\n{\n password_changed_ = true;\n\n ui.edit_password->setEnabled(true);\n ui.edit_password_repeat->setEnabled(true);\n\n ui.edit_password->clear();\n ui.edit_password_repeat->clear();\n\n Qt::InputMethodHints hints = Qt::ImhHiddenText | Qt::ImhSensitiveData |\n Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText;\n\n ui.edit_password->setEchoMode(QLineEdit::Password);\n ui.edit_password->setInputMethodHints(hints);\n\n ui.edit_password_repeat->setEchoMode(QLineEdit::Password);\n ui.edit_password_repeat->setInputMethodHints(hints);\n\n ui.edit_password->setFocus();\n}\n\nvoid AddressBookDialog::showError(const QString& message)\n{\n QMessageBox(QMessageBox::Warning, tr(\"Warning\"), message, QMessageBox::Ok, this).exec();\n}\n\n} \/\/ namespace aspia\n<commit_msg>- Do not enable password input controls if encryption is not enabled.<commit_after>\/\/\n\/\/ PROJECT: Aspia\n\/\/ FILE: console\/address_book_dialog.cc\n\/\/ LICENSE: GNU General Public License 3\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\n\/\/\n\n#include \"console\/address_book_dialog.h\"\n\n#include <QAbstractButton>\n#include <QMessageBox>\n\n#include \"crypto\/data_encryptor.h\"\n#include \"crypto\/random.h\"\n\nnamespace aspia {\n\nnamespace {\n\nconstexpr int kMaxNameLength = 64;\nconstexpr int kMinNameLength = 1;\nconstexpr int kMinPasswordLength = 8;\nconstexpr int kMaxPasswordLength = 64;\nconstexpr int kMaxCommentLength = 2048;\n\n} \/\/ namespace\n\nAddressBookDialog::AddressBookDialog(QWidget* parent, proto::address_book::File* file,\n proto::address_book::Data* data, QByteArray* key)\n : QDialog(parent), file_(file), data_(data), key_(key)\n{\n ui.setupUi(this);\n\n connect(ui.button_box, &QDialogButtonBox::clicked, this, &AddressBookDialog::buttonBoxClicked);\n\n connect(ui.combo_encryption, QOverload<int>::of(&QComboBox::currentIndexChanged), this,\n &AddressBookDialog::encryptionTypedChanged);\n\n ui.combo_encryption->addItem(tr(\"Without Encryption\"),\n QVariant(proto::address_book::ENCRYPTION_TYPE_NONE));\n ui.combo_encryption->addItem(tr(\"XChaCha20 + Poly1305 (256-bit key)\"),\n QVariant(proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305));\n\n ui.edit_name->setText(QString::fromStdString(data_->root_group().name()));\n ui.edit_comment->setPlainText(QString::fromStdString(data_->root_group().comment()));\n\n int current = ui.combo_encryption->findData(QVariant(file->encryption_type()));\n if (current != -1)\n ui.combo_encryption->setCurrentIndex(current);\n\n if (file->encryption_type() == proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305)\n {\n if (!key_->isEmpty())\n {\n QString text = tr(\"Double-click to change\");\n\n ui.edit_password->setText(text);\n ui.edit_password_repeat->setText(text);\n\n ui.edit_password->setEnabled(false);\n ui.edit_password_repeat->setEnabled(false);\n\n ui.edit_password->setEchoMode(QLineEdit::Normal);\n ui.edit_password->setInputMethodHints(Qt::ImhNone);\n\n ui.edit_password_repeat->setEchoMode(QLineEdit::Normal);\n ui.edit_password_repeat->setInputMethodHints(Qt::ImhNone);\n\n ui.edit_password->installEventFilter(this);\n ui.edit_password_repeat->installEventFilter(this);\n\n ui.spinbox_password_salt->setValue(file_->hashing_salt().size());\n ui.spinbox_hashing_rounds->setValue(file_->hashing_rounds());\n\n ui.spinbox_salt_before->setValue(data_->salt1().size());\n ui.spinbox_salt_after->setValue(data_->salt2().size());\n\n password_changed_ = false;\n }\n }\n else\n {\n Q_ASSERT(file->encryption_type() == proto::address_book::ENCRYPTION_TYPE_NONE);\n\n ui.edit_password->setEnabled(false);\n\n \/\/ Disable Advanced tab.\n ui.tab_widget->setTabEnabled(1, false);\n }\n\n connect(ui.spinbox_hashing_rounds, QOverload<int>::of(&QSpinBox::valueChanged), this,\n &AddressBookDialog::hashingRoundsChanged);\n\n connect(ui.spinbox_password_salt, QOverload<int>::of(&QSpinBox::valueChanged), this,\n &AddressBookDialog::hashingSaltChanged);\n}\n\nAddressBookDialog::~AddressBookDialog() = default;\n\nbool AddressBookDialog::eventFilter(QObject* object, QEvent* event)\n{\n if (event->type() == QEvent::MouseButtonDblClick &&\n (object == ui.edit_password || object == ui.edit_password_repeat))\n {\n proto::address_book::EncryptionType encryption_type =\n static_cast<proto::address_book::EncryptionType>(\n ui.combo_encryption->currentData().toInt());\n\n if (encryption_type == proto::address_book::ENCRYPTION_TYPE_NONE)\n return false;\n\n setPasswordChanged();\n }\n\n return false;\n}\n\nvoid AddressBookDialog::buttonBoxClicked(QAbstractButton* button)\n{\n if (ui.button_box->standardButton(button) != QDialogButtonBox::Ok)\n {\n reject();\n close();\n return;\n }\n\n QString name = ui.edit_name->text();\n if (name.length() > kMaxNameLength)\n {\n showError(tr(\"Too long name. The maximum length of the name is 64 characters.\"));\n return;\n }\n else if (name.length() < kMinNameLength)\n {\n showError(tr(\"Name can not be empty.\"));\n return;\n }\n\n QString comment = ui.edit_comment->toPlainText();\n if (comment.length() > kMaxCommentLength)\n {\n showError(tr(\"Too long comment. The maximum length of the comment is 2048 characters.\"));\n return;\n }\n\n proto::address_book::EncryptionType encryption_type =\n static_cast<proto::address_book::EncryptionType>(\n ui.combo_encryption->currentData().toInt());\n\n switch (encryption_type)\n {\n case proto::address_book::ENCRYPTION_TYPE_NONE:\n {\n file_->mutable_hashing_salt()->clear();\n file_->set_hashing_rounds(0);\n\n data_->mutable_salt1()->clear();\n data_->mutable_salt2()->clear();\n }\n break;\n\n case proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305:\n {\n if (password_changed_)\n {\n QString password = ui.edit_password->text();\n QString password_repeat = ui.edit_password_repeat->text();\n\n if (password != password_repeat)\n {\n showError(tr(\"The passwords you entered do not match.\"));\n return;\n }\n\n if (password.length() < kMinPasswordLength)\n {\n showError(tr(\"Password can not be shorter than 8 characters.\"));\n return;\n }\n\n \/\/ Generate salt, which is added after each iteration of the hashing.\n \/\/ New salt is generated each time the password is changed.\n QByteArray hashing_salt =\n Random::generateBuffer(ui.spinbox_password_salt->value());\n\n \/\/ Save the salt and the number of hashing iterations.\n file_->set_hashing_rounds(ui.spinbox_hashing_rounds->value());\n *file_->mutable_hashing_salt() = hashing_salt.toStdString();\n\n \/\/ Now generate a key for encryption\/decryption.\n *key_ = DataEncryptor::createKey(password.toUtf8(), hashing_salt,\n file_->hashing_rounds());\n }\n\n int salt_before_size = ui.spinbox_salt_before->value();\n int salt_after_size = ui.spinbox_salt_after->value();\n\n if (salt_before_size != data_->salt1().size())\n *data_->mutable_salt1() = Random::generateBuffer(salt_before_size).toStdString();\n\n if (salt_after_size != data_->salt2().size())\n *data_->mutable_salt2() = Random::generateBuffer(salt_after_size).toStdString();\n }\n break;\n\n default:\n qFatal(\"Unexpected encryption type: %d\", encryption_type);\n return;\n }\n\n data_->mutable_root_group()->set_name(name.toStdString());\n data_->mutable_root_group()->set_comment(comment.toStdString());\n\n file_->set_encryption_type(encryption_type);\n\n accept();\n close();\n}\n\nvoid AddressBookDialog::encryptionTypedChanged(int item_index)\n{\n proto::address_book::EncryptionType encryption_type =\n static_cast<proto::address_book::EncryptionType>(\n ui.combo_encryption->itemData(item_index).toInt());\n\n switch (encryption_type)\n {\n case proto::address_book::ENCRYPTION_TYPE_NONE:\n {\n ui.edit_password->setEnabled(false);\n ui.edit_password_repeat->setEnabled(false);\n\n ui.edit_password->clear();\n ui.edit_password_repeat->clear();\n\n \/\/ Disable Advanced tab.\n ui.tab_widget->setTabEnabled(1, false);\n }\n break;\n\n case proto::address_book::ENCRYPTION_TYPE_XCHACHA20_POLY1305:\n {\n ui.edit_password->setEnabled(true);\n ui.edit_password_repeat->setEnabled(true);\n\n \/\/ Enable Advanced tab.\n ui.tab_widget->setTabEnabled(1, true);\n }\n break;\n\n default:\n qFatal(\"Unexpected encryption type: %d\", encryption_type);\n break;\n }\n}\n\nvoid AddressBookDialog::hashingRoundsChanged(int \/* value *\/)\n{\n if (password_changed_ || value_reverting_)\n return;\n\n if (QMessageBox::question(\n this,\n tr(\"Confirmation\"),\n tr(\"At change the number of hashing iterations, you will need to re-enter the password. Continue?\"),\n QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)\n {\n setPasswordChanged();\n }\n else\n {\n \/\/ Revert value.\n value_reverting_ = true;\n ui.spinbox_hashing_rounds->setValue(file_->hashing_rounds());\n value_reverting_ = false;\n }\n}\n\nvoid AddressBookDialog::hashingSaltChanged(int \/* value *\/)\n{\n if (password_changed_ || value_reverting_)\n return;\n\n if (QMessageBox::question(\n this,\n tr(\"Confirmation\"),\n tr(\"At change the size of hashing salt, you will need to re-enter the password. Continue?\"),\n QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)\n {\n setPasswordChanged();\n }\n else\n {\n \/\/ Revert value.\n value_reverting_ = true;\n ui.spinbox_password_salt->setValue(file_->hashing_salt().size());\n value_reverting_ = false;\n }\n}\n\nvoid AddressBookDialog::setPasswordChanged()\n{\n password_changed_ = true;\n\n ui.edit_password->setEnabled(true);\n ui.edit_password_repeat->setEnabled(true);\n\n ui.edit_password->clear();\n ui.edit_password_repeat->clear();\n\n Qt::InputMethodHints hints = Qt::ImhHiddenText | Qt::ImhSensitiveData |\n Qt::ImhNoAutoUppercase | Qt::ImhNoPredictiveText;\n\n ui.edit_password->setEchoMode(QLineEdit::Password);\n ui.edit_password->setInputMethodHints(hints);\n\n ui.edit_password_repeat->setEchoMode(QLineEdit::Password);\n ui.edit_password_repeat->setInputMethodHints(hints);\n\n ui.edit_password->setFocus();\n}\n\nvoid AddressBookDialog::showError(const QString& message)\n{\n QMessageBox(QMessageBox::Warning, tr(\"Warning\"), message, QMessageBox::Ok, this).exec();\n}\n\n} \/\/ namespace aspia\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: AppDetailPageHelper.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 15:28:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_APPDETAILPAGEHELPER_HXX\n#define DBAUI_APPDETAILPAGEHELPER_HXX\n\n#include <vector>\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XDatabaseMetaData.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_\n#include <com\/sun\/star\/ucb\/XContent.hpp>\n#endif\n#ifndef DBAUI_APPELEMENTTYPE_HXX\n#include \"AppElementType.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include <svtools\/svtreebx.hxx>\n#endif\n#ifndef SVTOOLS_DOCUMENTINFOPREVIEW_HXX\n#include <svtools\/DocumentInfoPreview.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include <vcl\/toolbox.hxx>\n#endif\n#ifndef _SV_CVTGRF_HXX\n#include <vcl\/cvtgrf.hxx>\n#endif\n#ifndef _SV_GRAPH_HXX\n#include <vcl\/graph.hxx>\n#endif\n#ifndef _GRFMGR_HXX\n#include <goodies\/grfmgr.hxx>\n#endif\n#include <memory>\n\nnamespace com{ namespace sun { namespace star { namespace awt { class XWindow; } } } };\nnamespace com{ namespace sun { namespace star { namespace frame { class XFrame; } } } };\nnamespace com{ namespace sun { namespace star { namespace io { class XPersist; } } } };\n\n#define CONTROL_COUNT 4\n\nnamespace dbaui\n{\n class OAppBorderWindow;\n class DBTreeListBox;\n\n class OPreviewWindow : public Window\n {\n GraphicObject m_aGraphicObj;\n Rectangle m_aPreviewRect;\n\n \/** gets the graphic cnter rect\n @param rGraphic\n the graphic\n @param rResultRect\n the resulting rectangle\n\n @return\n <TRUE\/> when successfull\n *\/\n BOOL ImplGetGraphicCenterRect( const Graphic& rGraphic, Rectangle& rResultRect ) const;\n public:\n OPreviewWindow(Window* _pParent) : Window(_pParent){}\n\n \/\/ window overloads\n virtual void Paint(const Rectangle& rRect);\n\n void setGraphic(const Graphic& _rGraphic ) { m_aGraphicObj.SetGraphic(_rGraphic); }\n };\n \/\/==================================================================\n \/\/ A helper class for the controls in the detail page.\n \/\/ Combines general functionality.\n \/\/==================================================================\n class OAppDetailPageHelper : public Window\n {\n DBTreeListBox* m_pLists[CONTROL_COUNT];\n OAppBorderWindow* m_pBorderWin;\n FixedLine m_aFL;\n ToolBox m_aTBPreview;\n Window m_aBorder;\n OPreviewWindow m_aPreview;\n ::svtools::ODocumentInfoPreview\n m_aDocumentInfo;\n Window* m_pTablePreview;\n Timer m_aPreviewTimer;\n ::std::auto_ptr<PopupMenu> m_aMenu;\n PreviewMode m_ePreviewMode;\n ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >\n m_xFrame;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XPersist >\n m_xDocInfo;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >\n m_xWindow;\n\n \/\/\/ returns the index of the visible control\n int getVisibleControlIndex() const;\n\n \/** sorts the entries in the tree list box.\n @param _nPos\n Which list should be sorted.\n @param _eSortMode\n How should be sorted.\n *\/\n void sort(int _nPos,SvSortMode _eSortMode );\n\n \/** fills the names in the listbox\n @param _xContainer\n This can either be the queries, forms or report names.\n @param _rList\n The tree list box to fill\n @param _pParent\n The parent of the entries to be inserted.\n *\/\n void fillNames( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer\n ,DBTreeListBox& _rList\n ,USHORT _nImageId\n ,SvLBoxEntry* _pParent = NULL);\n \/** sets the detail page\n @param _pWindow\n The control which should be visible.\n *\/\n void setDetailPage(Window* _pWindow);\n\n \/** sets all HandleCallbacks\n @param _pTreeView\n The newly created DBTreeListBox\n @param _nCollapsedBitmap\n The collapsed bitmap resource id\n @param _nCollapsedBitmap_HI\n The collapsed bitmap resource id for high contrast.\n @return\n The new tree.\n *\/\n DBTreeListBox* createTree(DBTreeListBox* _pTreeView,USHORT _nCollapsedBitmap,USHORT _nCollapsedBitmap_HI);\n\n \/** creates the tree and sets all HandleCallbacks\n @param _nHelpId\n The help id of the control\n @param _nCollapsedBitmap\n The collapsed bitmap resource id\n @param _nCollapsedBitmap_HI\n The collapsed bitmap resource id for high contrast.\n @return\n The new tree.\n *\/\n DBTreeListBox* createSimpleTree(ULONG _nHelpId, USHORT _nCollapsedBitmap,USHORT _nCollapsedBitmap_HI);\n\n DECL_LINK( OnEntryDoubleClick, SvTreeListBox* );\n DECL_LINK( OnDeSelectHdl, SvTreeListBox* );\n\n DECL_LINK( OnEntrySelectHdl, SvLBoxEntry* );\n\n DECL_LINK( OnCutEntry, SvLBoxEntry* );\n DECL_LINK( OnCopyEntry, SvLBoxEntry* );\n DECL_LINK( OnPasteEntry, SvLBoxEntry* );\n DECL_LINK( OnDeleteEntry, SvLBoxEntry* );\n\n DECL_LINK(PreviewChangeHdl, void*);\n \/\/ click a TB slot\n DECL_LINK(OnToolBoxSelected, ToolBox*);\n DECL_LINK(OnToolBoxClicked, ToolBox*);\n\n inline OAppBorderWindow* getBorderWin() const { return m_pBorderWin; }\n\n public:\n OAppDetailPageHelper(Window* _pParent,OAppBorderWindow* _pBorderWin);\n virtual ~OAppDetailPageHelper();\n\n \/\/ window overloads\n virtual void Resize();\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n sal_Bool isCutAllowed();\n sal_Bool isCopyAllowed();\n sal_Bool isPasteAllowed();\n void copy();\n void cut();\n void paste();\n\n \/** creates the tables page\n @param _xConnection\n The connection to get the table names\n *\/\n void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);\n\n \/** creates the page for the specific type.\n @param _eType\n The type which should be created. E_TABLE isn't allowed.\n @param _xContainer\n The container of the elements to be inserted.\n *\/\n void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);\n\n \/** returns the current visible tree list box\n *\/\n inline DBTreeListBox* getCurrentView() const\n {\n ElementType eType = getElementType();\n return (eType != E_NONE ) ? m_pLists[static_cast<sal_Int32>(eType)] : NULL;\n }\n\n \/\/\/ select all entries in the visible control\n void selectAll();\n\n \/\/\/ returns <TRUE\/> if it sorts ascending\n sal_Bool isSortUp() const;\n\n \/\/\/ sorts all entries ascending\n void sortDown();\n\n \/\/\/ sorts all entries descending\n void sortUp();\n\n \/** returns the element names which are selected\n @param _rNames\n The list will be filled.\n @param _xMetaData\n Will be used when the table list should be filled.\n *\/\n void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const;\n\n \/** return the qualified name.\n @param _pEntry\n The entry of a table, or query, form, report to get the qualified name.\n If the entry is <NULL\/>, the first selected is chosen.\n @param _xMetaData\n The meta data are used to create the table name, otherwise this may also be <NULL\/>\n @return\n the qualified name\n *\/\n ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const;\n\n \/\/\/ return the element of currently select entry\n ElementType getElementType() const;\n\n \/\/\/ returns the count of selected entries\n sal_Int32 getSelectionCount();\n\n \/\/\/ returns the count of entries\n sal_Int32 getElementCount();\n\n \/** returns if an entry is a leaf\n @param _pEntry\n The entry to check\n @return\n <TRUE\/> if the entry is a leaf, otherwise <FALSE\/>\n *\/\n sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;\n\n \/** returns if one of the selected entries is a leaf\n @return\n <TRUE\/> if the entry is a leaf, otherwise <FALSE\/>\n *\/\n sal_Bool isALeafSelected() const;\n\n SvLBoxEntry* getEntry( const Point& _aPosPixel ) const;\n\n \/\/\/ clears the detail pages\n void clearPages();\n\n \/\/\/ returns <TRUE\/> when a detail page was filled\n sal_Bool isFilled() const;\n\n \/** adds a new object to the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the object to be inserted\n @param _rObject\n The object to add.\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n SvLBoxEntry* elementAdded(ElementType eType\n ,const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Any& _rObject\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);\n\n \/** replaces a objects name with a new one\n @param _eType\n The type where the entry shold be appended.\n @param _rOldName\n The old name of the object to be replaced\n @param _rNewName\n The new name of the object to be replaced\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n void elementReplaced(ElementType eType\n ,const ::rtl::OUString& _rOldName\n ,const ::rtl::OUString& _rNewName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);\n\n \/** removes an element from the detail page.\n @param _rName\n The name of the element to be removed.\n @param _rxConn\n If we remove a table, the connection must be set.\n *\/\n void elementRemoved(const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);\n\n\n \/\/\/ returns the preview mode\n PreviewMode getPreviewMode();\n\n \/\/\/ <TRUE\/> if the preview is enabled\n sal_Bool isPreviewEnabled();\n\n \/\/\/ switches the current preview\n void switchPreview();\n\n \/** switches to the given preview mode\n @param _eMode\n the mode to set for the preview\n @param _bForce\n Force the preview to be resetted\n *\/\n void switchPreview(PreviewMode _eMode,BOOL _bForce = FALSE);\n\n \/** shows the Preview of the content when it is enabled.\n @param _xContent\n The content which must support the \"preview\" command.\n *\/\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);\n\n \/** shows the Preview of a table or query\n @param _sDataSourceName\n the name of the data source\n @param _xConnection\n the connection which will be shared\n @param _sName\n the name of table or query\n @param _bTable\n <TRUE\/> if it is a table, otherwise <FALSE\/>\n @return void\n *\/\n void showPreview( const ::rtl::OUString& _sDataSourceName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const ::rtl::OUString& _sName,\n sal_Bool _bTable);\n\n \/** disable the controls\n @param _bDisable\n if <TRUE\/> then the controls will be disabled otherwise they will be enabled.\n *\/\n void disableControls(sal_Bool _bDisable);\n };\n}\n#endif \/\/ DBAUI_APPDETAILPAGEHELPER_HXX\n\n<commit_msg>INTEGRATION: CWS insight02 (1.2.2); FILE MERGED 2004\/08\/11 12:26:35 oj 1.2.2.1: #i30379# click on preview correct<commit_after>\/*************************************************************************\n *\n * $RCSfile: AppDetailPageHelper.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-09-09 09:39:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_APPDETAILPAGEHELPER_HXX\n#define DBAUI_APPDETAILPAGEHELPER_HXX\n\n#include <vector>\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XDatabaseMetaData.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_\n#include <com\/sun\/star\/ucb\/XContent.hpp>\n#endif\n#ifndef DBAUI_APPELEMENTTYPE_HXX\n#include \"AppElementType.hxx\"\n#endif\n#ifndef _SVTREEBOX_HXX\n#include <svtools\/svtreebx.hxx>\n#endif\n#ifndef SVTOOLS_DOCUMENTINFOPREVIEW_HXX\n#include <svtools\/DocumentInfoPreview.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include <vcl\/toolbox.hxx>\n#endif\n#ifndef _SV_CVTGRF_HXX\n#include <vcl\/cvtgrf.hxx>\n#endif\n#ifndef _SV_GRAPH_HXX\n#include <vcl\/graph.hxx>\n#endif\n#ifndef _GRFMGR_HXX\n#include <goodies\/grfmgr.hxx>\n#endif\n#include <memory>\n\nnamespace com{ namespace sun { namespace star { namespace awt { class XWindow; } } } };\nnamespace com{ namespace sun { namespace star { namespace frame { class XFrame; } } } };\nnamespace com{ namespace sun { namespace star { namespace io { class XPersist; } } } };\n\n#define CONTROL_COUNT 4\n\nnamespace dbaui\n{\n class OAppBorderWindow;\n class DBTreeListBox;\n\n class OPreviewWindow : public Window\n {\n GraphicObject m_aGraphicObj;\n Rectangle m_aPreviewRect;\n\n \/** gets the graphic cnter rect\n @param rGraphic\n the graphic\n @param rResultRect\n the resulting rectangle\n\n @return\n <TRUE\/> when successfull\n *\/\n BOOL ImplGetGraphicCenterRect( const Graphic& rGraphic, Rectangle& rResultRect ) const;\n public:\n OPreviewWindow(Window* _pParent) : Window(_pParent){}\n\n \/\/ window overloads\n virtual void Paint(const Rectangle& rRect);\n\n void setGraphic(const Graphic& _rGraphic ) { m_aGraphicObj.SetGraphic(_rGraphic); }\n };\n \/\/==================================================================\n \/\/ A helper class for the controls in the detail page.\n \/\/ Combines general functionality.\n \/\/==================================================================\n class OAppDetailPageHelper : public Window\n {\n DBTreeListBox* m_pLists[CONTROL_COUNT];\n OAppBorderWindow* m_pBorderWin;\n FixedLine m_aFL;\n ToolBox m_aTBPreview;\n Window m_aBorder;\n OPreviewWindow m_aPreview;\n ::svtools::ODocumentInfoPreview\n m_aDocumentInfo;\n Window* m_pTablePreview;\n ::std::auto_ptr<PopupMenu> m_aMenu;\n PreviewMode m_ePreviewMode;\n ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >\n m_xFrame;\n ::com::sun::star::uno::Reference < ::com::sun::star::io::XPersist >\n m_xDocInfo;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >\n m_xWindow;\n\n \/\/\/ returns the index of the visible control\n int getVisibleControlIndex() const;\n\n \/** sorts the entries in the tree list box.\n @param _nPos\n Which list should be sorted.\n @param _eSortMode\n How should be sorted.\n *\/\n void sort(int _nPos,SvSortMode _eSortMode );\n\n \/** fills the names in the listbox\n @param _xContainer\n This can either be the queries, forms or report names.\n @param _rList\n The tree list box to fill\n @param _pParent\n The parent of the entries to be inserted.\n *\/\n void fillNames( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer\n ,DBTreeListBox& _rList\n ,USHORT _nImageId\n ,SvLBoxEntry* _pParent = NULL);\n \/** sets the detail page\n @param _pWindow\n The control which should be visible.\n *\/\n void setDetailPage(Window* _pWindow);\n\n \/** sets all HandleCallbacks\n @param _pTreeView\n The newly created DBTreeListBox\n @param _nCollapsedBitmap\n The collapsed bitmap resource id\n @param _nCollapsedBitmap_HI\n The collapsed bitmap resource id for high contrast.\n @return\n The new tree.\n *\/\n DBTreeListBox* createTree(DBTreeListBox* _pTreeView,USHORT _nCollapsedBitmap,USHORT _nCollapsedBitmap_HI);\n\n \/** creates the tree and sets all HandleCallbacks\n @param _nHelpId\n The help id of the control\n @param _nCollapsedBitmap\n The collapsed bitmap resource id\n @param _nCollapsedBitmap_HI\n The collapsed bitmap resource id for high contrast.\n @return\n The new tree.\n *\/\n DBTreeListBox* createSimpleTree(ULONG _nHelpId, USHORT _nCollapsedBitmap,USHORT _nCollapsedBitmap_HI);\n\n DECL_LINK( OnEntryDoubleClick, SvTreeListBox* );\n DECL_LINK( OnDeSelectHdl, SvTreeListBox* );\n\n DECL_LINK( OnEntrySelectHdl, SvLBoxEntry* );\n\n DECL_LINK( OnCutEntry, SvLBoxEntry* );\n DECL_LINK( OnCopyEntry, SvLBoxEntry* );\n DECL_LINK( OnPasteEntry, SvLBoxEntry* );\n DECL_LINK( OnDeleteEntry, SvLBoxEntry* );\n\n DECL_LINK(PreviewChangeHdl, void*);\n \/\/ click a TB slot\n DECL_LINK(OnDropdownClickHdl, ToolBox*);\n\n inline OAppBorderWindow* getBorderWin() const { return m_pBorderWin; }\n\n public:\n OAppDetailPageHelper(Window* _pParent,OAppBorderWindow* _pBorderWin);\n virtual ~OAppDetailPageHelper();\n\n \/\/ window overloads\n virtual void Resize();\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n sal_Bool isCutAllowed();\n sal_Bool isCopyAllowed();\n sal_Bool isPasteAllowed();\n void copy();\n void cut();\n void paste();\n\n \/** creates the tables page\n @param _xConnection\n The connection to get the table names\n *\/\n void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);\n\n \/** creates the page for the specific type.\n @param _eType\n The type which should be created. E_TABLE isn't allowed.\n @param _xContainer\n The container of the elements to be inserted.\n *\/\n void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);\n\n \/** returns the current visible tree list box\n *\/\n inline DBTreeListBox* getCurrentView() const\n {\n ElementType eType = getElementType();\n return (eType != E_NONE ) ? m_pLists[static_cast<sal_Int32>(eType)] : NULL;\n }\n\n \/\/\/ select all entries in the visible control\n void selectAll();\n\n \/\/\/ returns <TRUE\/> if it sorts ascending\n sal_Bool isSortUp() const;\n\n \/\/\/ sorts all entries ascending\n void sortDown();\n\n \/\/\/ sorts all entries descending\n void sortUp();\n\n \/** returns the element names which are selected\n @param _rNames\n The list will be filled.\n @param _xMetaData\n Will be used when the table list should be filled.\n *\/\n void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const;\n\n \/** return the qualified name.\n @param _pEntry\n The entry of a table, or query, form, report to get the qualified name.\n If the entry is <NULL\/>, the first selected is chosen.\n @param _xMetaData\n The meta data are used to create the table name, otherwise this may also be <NULL\/>\n @return\n the qualified name\n *\/\n ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const;\n\n \/\/\/ return the element of currently select entry\n ElementType getElementType() const;\n\n \/\/\/ returns the count of selected entries\n sal_Int32 getSelectionCount();\n\n \/\/\/ returns the count of entries\n sal_Int32 getElementCount();\n\n \/** returns if an entry is a leaf\n @param _pEntry\n The entry to check\n @return\n <TRUE\/> if the entry is a leaf, otherwise <FALSE\/>\n *\/\n sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;\n\n \/** returns if one of the selected entries is a leaf\n @return\n <TRUE\/> if the entry is a leaf, otherwise <FALSE\/>\n *\/\n sal_Bool isALeafSelected() const;\n\n SvLBoxEntry* getEntry( const Point& _aPosPixel ) const;\n\n \/\/\/ clears the detail pages\n void clearPages();\n\n \/\/\/ returns <TRUE\/> when a detail page was filled\n sal_Bool isFilled() const;\n\n \/** adds a new object to the detail page.\n @param _eType\n The type where the entry shold be appended.\n @param _rName\n The name of the object to be inserted\n @param _rObject\n The object to add.\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n SvLBoxEntry* elementAdded(ElementType eType\n ,const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Any& _rObject\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);\n\n \/** replaces a objects name with a new one\n @param _eType\n The type where the entry shold be appended.\n @param _rOldName\n The old name of the object to be replaced\n @param _rNewName\n The new name of the object to be replaced\n @param _rxConn\n If we insert a table, the connection must be set.\n *\/\n void elementReplaced(ElementType eType\n ,const ::rtl::OUString& _rOldName\n ,const ::rtl::OUString& _rNewName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);\n\n \/** removes an element from the detail page.\n @param _rName\n The name of the element to be removed.\n @param _rxConn\n If we remove a table, the connection must be set.\n *\/\n void elementRemoved(const ::rtl::OUString& _rName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);\n\n\n \/\/\/ returns the preview mode\n PreviewMode getPreviewMode();\n\n \/\/\/ <TRUE\/> if the preview is enabled\n sal_Bool isPreviewEnabled();\n\n \/\/\/ switches the current preview\n void switchPreview();\n\n \/** switches to the given preview mode\n @param _eMode\n the mode to set for the preview\n @param _bForce\n Force the preview to be resetted\n *\/\n void switchPreview(PreviewMode _eMode,BOOL _bForce = FALSE);\n\n \/** shows the Preview of the content when it is enabled.\n @param _xContent\n The content which must support the \"preview\" command.\n *\/\n void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);\n\n \/** shows the Preview of a table or query\n @param _sDataSourceName\n the name of the data source\n @param _xConnection\n the connection which will be shared\n @param _sName\n the name of table or query\n @param _bTable\n <TRUE\/> if it is a table, otherwise <FALSE\/>\n @return void\n *\/\n void showPreview( const ::rtl::OUString& _sDataSourceName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const ::rtl::OUString& _sName,\n sal_Bool _bTable);\n\n \/** disable the controls\n @param _bDisable\n if <TRUE\/> then the controls will be disabled otherwise they will be enabled.\n *\/\n void disableControls(sal_Bool _bDisable);\n };\n}\n#endif \/\/ DBAUI_APPDETAILPAGEHELPER_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include \"generator.h\"\n\n#include <cassert>\n#include <cstring>\n#include <deque>\n#include <iostream>\n#include <map>\n\n#include \"dictionary.h\"\n#include \"label.h\"\n\nstatic void compileCall(FILE* f, const char* wordName, bool tailCall, Dictionary* dictionary) {\n fprintf(f, tailCall ? \"\\tjmp %s\\n\" : \"\\tjsr %s\\n\", label(wordName).c_str());\n dictionary->markAsUsed(wordName);\n}\n\nvoid generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) {\n std::deque<int> stack;\n int localLabel = 0;\n bool state = false;\n std::set<int> undefinedVariables;\n int variableLabel = 0;\n std::map<std::string, int> variableLabels;\n\n for (auto it = tokens.begin(); it != tokens.end(); ++it) {\n switch (it->type) {\n case Cells:\n if (state) {\n ++it;\n bool tailCall = (it != tokens.end() && it->type == SemiColon);\n --it;\n compileCall(f, \"2*\", tailCall, dictionary);\n if (tailCall) {\n ++it; \/\/ Skips ;\n state = false;\n }\n } else {\n stack.back() *= 2;\n }\n break;\n case Allot:\n assert(!stack.empty());\n fprintf(f, \"* = * + %i\\n\", stack.back());\n stack.pop_back();\n break;\n case Create:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"create must be followed by a word name!\");\n exit(1);\n }\n \/\/ printf(\"Create '%s'\\n\", it->stringData);\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n free(it->stringData);\n break;\n case String:\n fprintf(f, \"\\tjsr litstring\\n!byte %i\\n!text \\\"%s\\\"\\n\",\n (int)strlen(it->stringData), it->stringData);\n dictionary->markAsUsed(\"litstring\");\n free(it->stringData);\n break;\n case Variable:\n \/\/ puts(\"Variable\");\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"variable must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #<+\\n\\tldy #>+\\n\\tjmp pushya\\n+\\n!word vl_%i\\n\", variableLabel);\n undefinedVariables.insert(variableLabel);\n variableLabels[it->stringData] = variableLabel;\n ++variableLabel;\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n case Store:\n if (!state) {\n int variableLabel = stack.back();\n stack.pop_back();\n int value = stack.back();\n stack.pop_back();\n fprintf(f, \"vl_%i = %i\\n\", variableLabel, value);\n undefinedVariables.erase(variableLabel);\n break;\n } else {\n ++it;\n bool tailCall = (it != tokens.end() && it->type == SemiColon);\n --it;\n compileCall(f, \"!\", tailCall, dictionary);\n if (tailCall) {\n ++it; \/\/ Skips ;\n state = false;\n }\n }\n break;\n case WordName:\n \/\/ printf(\"WordName %s\\n\", it->stringData);\n assert(it->stringData);\n if (state) {\n ++it;\n bool tailCall = (it != tokens.end() && it->type == SemiColon);\n --it;\n compileCall(f, it->stringData, tailCall, dictionary);\n if (tailCall) {\n ++it; \/\/ Skips ;\n state = false;\n }\n free(it->stringData);\n } else {\n char* wordName = it->stringData;\n if (variableLabels.find(wordName) != variableLabels.end()) {\n stack.push_back(variableLabels[wordName]);\n free(it->stringData);\n } else {\n fprintf(stderr, \"Variable '%s' not defined\\n\", wordName);\n exit(1);\n }\n }\n break;\n case Number:\n \/\/ puts(\"Number\");\n if (state) {\n dictionary->markAsUsed(\"lit\");\n fprintf(f, \"\\tjsr lit\\n\\t!word %i\\n\", it->intData);\n } else {\n stack.push_back(it->intData);\n }\n break;\n case Code:\n \/\/ puts(\"Code\");\n {\n char* p = it->stringData;\n std::string wordName;\n while (!isspace(*p)) {\n wordName.push_back(*p);\n ++p;\n }\n dictionary->addWord(wordName.c_str());\n if (*p == '\\n') {\n ++p;\n }\n if (label(wordName.c_str()) != wordName) {\n fprintf(f, \"%s:\\t; %s\\n%s\\n\", label(wordName.c_str()).c_str(),\n wordName.c_str(), p);\n } else {\n fprintf(f, \"%s:\\n%s\\n\", wordName.c_str(), p);\n }\n }\n free(it->stringData);\n break;\n case Colon:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \": must be followed by a word name! (is type %i)\\n\", it->type);\n exit(1);\n }\n fprintf(f, \"\\n%s:\", label(it->stringData).c_str());\n \/\/ printf(\"Colon %s\\n\", it->stringData);\n dictionary->addWord(it->stringData);\n if (it->stringData != label(it->stringData)) {\n fprintf(f, \"\\t; %s\", it->stringData);\n }\n fprintf(f, \"\\n\");\n free(it->stringData);\n state = true;\n break;\n case Drop:\n fputs(\"\\tinx\\t; drop\\n\", f);\n break;\n case SemiColon:\n fputs(\"\\trts\\n\", f);\n state = false;\n break;\n case If:\n fprintf(f, \"\\tjsr ifcmp\\n\\tbeq .l%i\\n\", localLabel);\n dictionary->markAsUsed(\"ifcmp\");\n stack.push_back(localLabel++);\n break;\n case Else:\n fprintf(f, \"\\tjmp .l%i\\n.l%i:\\n\", localLabel, stack.back());\n stack.pop_back();\n stack.push_back(localLabel++);\n break;\n case Then:\n fprintf(f, \".l%i:\\n\", stack.back());\n stack.pop_back();\n break;\n case Begin:\n stack.push_back(localLabel);\n fprintf(f, \".l%i:\\n\", localLabel++);\n break;\n case Again:\n fprintf(f, \"\\tjmp .l%i\\n\", stack.back());\n stack.pop_back();\n break;\n case Value:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"value must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #%i\\n\", stack.back() & 0xff);\n fprintf(f, \"\\tldy #%i\\n\", stack.back() >> 8);\n fprintf(f, \"\\tjmp pushya\\n\");\n stack.pop_back();\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n }\n }\n}\n<commit_msg>refactoring<commit_after>#include \"generator.h\"\n\n#include <cassert>\n#include <cstring>\n#include <deque>\n#include <iostream>\n#include <map>\n\n#include \"dictionary.h\"\n#include \"label.h\"\n\nstatic void compileCall(FILE* f, const char* wordName, const Tokens& tokens,\n Tokens::const_iterator* it, bool* state, Dictionary* dictionary) {\n ++*it;\n bool tailCall = (*it != tokens.end() && (*it)->type == SemiColon);\n --*it;\n fprintf(f, tailCall ? \"\\tjmp %s\\n\" : \"\\tjsr %s\\n\", label(wordName).c_str());\n if (tailCall) {\n ++*it; \/\/ Skips ;\n *state = false;\n }\n dictionary->markAsUsed(wordName);\n}\n\nvoid generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) {\n std::deque<int> stack;\n int localLabel = 0;\n bool state = false;\n std::set<int> undefinedVariables;\n int variableLabel = 0;\n std::map<std::string, int> variableLabels;\n\n for (auto it = tokens.begin(); it != tokens.end(); ++it) {\n switch (it->type) {\n case Cells:\n if (state) {\n compileCall(f, \"2*\", tokens, &it, &state, dictionary);\n } else {\n stack.back() *= 2;\n }\n break;\n case Allot:\n assert(!stack.empty());\n fprintf(f, \"* = * + %i\\n\", stack.back());\n stack.pop_back();\n break;\n case Create:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"create must be followed by a word name!\");\n exit(1);\n }\n \/\/ printf(\"Create '%s'\\n\", it->stringData);\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n free(it->stringData);\n break;\n case String:\n fprintf(f, \"\\tjsr litstring\\n!byte %i\\n!text \\\"%s\\\"\\n\",\n (int)strlen(it->stringData), it->stringData);\n dictionary->markAsUsed(\"litstring\");\n free(it->stringData);\n break;\n case Variable:\n \/\/ puts(\"Variable\");\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"variable must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #<+\\n\\tldy #>+\\n\\tjmp pushya\\n+\\n!word vl_%i\\n\", variableLabel);\n undefinedVariables.insert(variableLabel);\n variableLabels[it->stringData] = variableLabel;\n ++variableLabel;\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n case Store:\n if (!state) {\n int variableLabel = stack.back();\n stack.pop_back();\n int value = stack.back();\n stack.pop_back();\n fprintf(f, \"vl_%i = %i\\n\", variableLabel, value);\n undefinedVariables.erase(variableLabel);\n break;\n } else {\n compileCall(f, \"!\", tokens, &it, &state, dictionary);\n }\n break;\n case WordName:\n \/\/ printf(\"WordName %s\\n\", it->stringData);\n assert(it->stringData);\n if (state) {\n compileCall(f, it->stringData, tokens, &it, &state, dictionary);\n free(it->stringData);\n } else {\n char* wordName = it->stringData;\n if (variableLabels.find(wordName) != variableLabels.end()) {\n stack.push_back(variableLabels[wordName]);\n free(it->stringData);\n } else {\n fprintf(stderr, \"Variable '%s' not defined\\n\", wordName);\n exit(1);\n }\n }\n break;\n case Number:\n \/\/ puts(\"Number\");\n if (state) {\n dictionary->markAsUsed(\"lit\");\n fprintf(f, \"\\tjsr lit\\n\\t!word %i\\n\", it->intData);\n } else {\n stack.push_back(it->intData);\n }\n break;\n case Code:\n \/\/ puts(\"Code\");\n {\n char* p = it->stringData;\n std::string wordName;\n while (!isspace(*p)) {\n wordName.push_back(*p);\n ++p;\n }\n dictionary->addWord(wordName.c_str());\n if (*p == '\\n') {\n ++p;\n }\n if (label(wordName.c_str()) != wordName) {\n fprintf(f, \"%s:\\t; %s\\n%s\\n\", label(wordName.c_str()).c_str(),\n wordName.c_str(), p);\n } else {\n fprintf(f, \"%s:\\n%s\\n\", wordName.c_str(), p);\n }\n }\n free(it->stringData);\n break;\n case Colon:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \": must be followed by a word name! (is type %i)\\n\", it->type);\n exit(1);\n }\n fprintf(f, \"\\n%s:\", label(it->stringData).c_str());\n \/\/ printf(\"Colon %s\\n\", it->stringData);\n dictionary->addWord(it->stringData);\n if (it->stringData != label(it->stringData)) {\n fprintf(f, \"\\t; %s\", it->stringData);\n }\n fprintf(f, \"\\n\");\n free(it->stringData);\n state = true;\n break;\n case Drop:\n fputs(\"\\tinx\\t; drop\\n\", f);\n break;\n case SemiColon:\n fputs(\"\\trts\\n\", f);\n state = false;\n break;\n case If:\n fprintf(f, \"\\tjsr ifcmp\\n\\tbeq .l%i\\n\", localLabel);\n dictionary->markAsUsed(\"ifcmp\");\n stack.push_back(localLabel++);\n break;\n case Else:\n fprintf(f, \"\\tjmp .l%i\\n.l%i:\\n\", localLabel, stack.back());\n stack.pop_back();\n stack.push_back(localLabel++);\n break;\n case Then:\n fprintf(f, \".l%i:\\n\", stack.back());\n stack.pop_back();\n break;\n case Begin:\n stack.push_back(localLabel);\n fprintf(f, \".l%i:\\n\", localLabel++);\n break;\n case Again:\n fprintf(f, \"\\tjmp .l%i\\n\", stack.back());\n stack.pop_back();\n break;\n case Value:\n ++it;\n if (it == tokens.end() || it->type != WordName) {\n fprintf(stderr, \"value must be followed by a word name!\");\n exit(1);\n }\n fprintf(f, \"\\n%s:\\n\", label(it->stringData).c_str());\n dictionary->addWord(it->stringData);\n fprintf(f, \"\\tlda #%i\\n\", stack.back() & 0xff);\n fprintf(f, \"\\tldy #%i\\n\", stack.back() >> 8);\n fprintf(f, \"\\tjmp pushya\\n\");\n stack.pop_back();\n dictionary->markAsUsed(\"pushya\");\n free(it->stringData);\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <functional>\n#include <glm\/glm.hpp>\n#include <memory>\n#include <Utility\/LockBox.hpp>\n#include <vector>\n#include \"..\/Entity\/ComponentContainer.hpp\"\n#include \"..\/linking.hpp\"\n\nnamespace Component {\n class RigidBody;\n class Shape;\n}\n\nnamespace Physics {\n class Shape;\n class Trigger;\n}\n\nnamespace Json {\n class Value;\n}\n\nclass btBroadphaseInterface;\nclass btDefaultCollisionConfiguration;\nclass btCollisionDispatcher;\nclass btSequentialImpulseConstraintSolver;\nclass btDiscreteDynamicsWorld;\nclass Entity;\n\n\/\/\/ Updates the physics of the world.\nclass PhysicsManager {\n friend class Hub;\n\n public:\n \/\/\/ Moves entities and updates the physics component.\n \/**\n * @param deltaTime Time since last frame (in seconds).\n *\/\n ENGINE_API void Update(float deltaTime);\n \n \/\/\/ Update transforms of entities according to positions of physics\n \/\/\/ components.\n ENGINE_API void UpdateEntityTransforms();\n \n \/\/\/ Set up listener for when |object| has entered |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to enter the trigger volume.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| has entered |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Set up listener for when |object| is intersecting |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to cause trigger to fire.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| is intersecting |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Set up listener for when |object| has left |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to cause trigger to fire.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| has left |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Create rigid body component.\n \/**\n * @param owner The %Entity that will own the component.\n * @return The created component.\n *\/\n ENGINE_API Component::RigidBody* CreateRigidBody(Entity* owner);\n\n \/\/\/ Create rigid body component.\n \/**\n * @param owner The %Entity that will own the component.\n * @param node Json node from which to load component definition.\n * @return The created component.\n *\/\n ENGINE_API Component::RigidBody* CreateRigidBody(Entity* owner, const Json::Value& node);\n\n \/\/\/ Create a component that represents a physical shape.\n \/**\n * @param owner The %Entity that will own the component.\n * @return The created component.\n *\/\n ENGINE_API Component::Shape* CreateShape(Entity* owner);\n\n \/\/\/ Create a component that represents a physical shape.\n \/**\n * @param owner The %Entity that will own the component.\n * @param node Json node from which to load component definition.\n * @return The created component.\n *\/\n ENGINE_API Component::Shape* CreateShape(Entity* owner, const Json::Value& node);\n\n \/\/\/ Create a trigger volume that can be used to check intersection\n \/\/\/ events against physics bodies.\n \/**\n * @param shape Shape of the trigger volume.\n * @return A reference to the internal trigger.\n *\/\n ENGINE_API Utility::LockBox<Physics::Trigger> CreateTrigger(std::shared_ptr<Physics::Shape> shape);\n\n \/\/\/ Set the position of a trigger volume.\n \/**\n * @param trigger Volume to reposition.\n * @param position New position in world space.\n *\/\n ENGINE_API void SetPosition(Utility::LockBox<Physics::Trigger> trigger, const glm::vec3& position);\n\n \/\/\/ Set the shape of a given Component::Shape component.\n \/**\n * @param comp The component on which to set the shape.\n * @param shape A Physics::Shape object that holds the shape definition.\n *\/\n ENGINE_API void SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape);\n\n \/\/\/ Get the mass of a rigid body component.\n \/**\n * @param comp Rigid body component to get mass of.\n * @return Mass in kilograms.\n *\/\n ENGINE_API float GetMass(Component::RigidBody* comp);\n\n \/\/\/ Set the volume shape of a trigger.\n \/**\n * @param trigger Trigger to alter shape of.\n * @param shape Shape definition.\n *\/\n ENGINE_API void SetShape(Utility::LockBox<Physics::Trigger> trigger, std::shared_ptr<Physics::Shape> shape);\n\n \/\/\/ Set the mass of a Component::RigidBody component.\n \/**\n * @param comp The component on which to set mass.\n * @param mass Mass in kilograms.\n *\/\n ENGINE_API void SetMass(Component::RigidBody* comp, float mass);\n\n \/\/\/ Set the friction coefficient of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the rolling friction coefficient of a Component::RigidBody\n \/\/\/ component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetRollingFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the spinning friction coefficient of a Component::RigidBody\n \/\/\/ component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetSpinningFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the restitution (bounciness) of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param cor Coefficient of restitution.\n *\/\n ENGINE_API void SetRestitution(Component::RigidBody* comp, float cor);\n\n \/\/\/ Set the linear damping factor of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param damping Linear damping.\n *\/\n ENGINE_API void SetLinearDamping(Component::RigidBody* comp, float damping);\n\n \/\/\/ Set the angular damping factor of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param damping Angular damping.\n *\/\n ENGINE_API void SetAngularDamping(Component::RigidBody* comp, float damping);\n\n \/\/\/ Turn a rigid body into a kinematic object, putting movement in the\n \/\/\/ control of the programmer.\n \/**\n * @param comp Rigid body to make kinematic.\n *\/\n ENGINE_API void MakeKinematic(Component::RigidBody* comp);\n\n \/\/\/ Turn a rigid body into a dynamic object.\n \/**\n * @param comp Rigid body to make dynamic.\n *\/\n ENGINE_API void MakeDynamic(Component::RigidBody* comp);\n\n \/\/\/ Enables\/disables ghost functionality on a rigid body.\n \/**\n * @param comp Rigid body to alter state of.\n * @param ghost True: makes the rigid object a ghost, disregarding all\n collisions. False: disables ghost state, reverting to kinematic or\n dynamic as before.\n *\/\n ENGINE_API void SetGhost(Component::RigidBody* comp, bool ghost);\n\n \/\/\/ Forces a dynamic rigid body to synchronize its transform with that\n \/\/\/ of its owning entity during the next simulation iteration.\n \/**\n * @param comp Rigid body to synchronize.\n *\/\n ENGINE_API void ForceTransformSync(Component::RigidBody* comp);\n\n \/\/\/ Halts movement of a kinematic rigid body.\n \/**\n * @param comp Rigid body to halt.\n *\/\n ENGINE_API void HaltMovement(Component::RigidBody* comp);\n\n \/\/\/ Get all shape components.\n \/**\n * @return All shape components.\n *\/\n ENGINE_API const std::vector<Component::Shape*>& GetShapeComponents() const;\n \n \/\/\/ Remove all killed components.\n ENGINE_API void ClearKilledComponents();\n \n private:\n PhysicsManager();\n ~PhysicsManager();\n PhysicsManager(PhysicsManager const&) = delete;\n void operator=(PhysicsManager const&) = delete;\n\n glm::vec3 gravity = glm::vec3(0.f, -9.82f, 0.f);\n\n ComponentContainer<Component::RigidBody> rigidBodyComponents;\n ComponentContainer<Component::Shape> shapeComponents;\n \n btBroadphaseInterface* broadphase = nullptr;\n btDefaultCollisionConfiguration* collisionConfiguration = nullptr;\n btCollisionDispatcher* dispatcher = nullptr;\n btSequentialImpulseConstraintSolver* solver = nullptr;\n btDiscreteDynamicsWorld* dynamicsWorld = nullptr;\n\n std::shared_ptr<Utility::LockBox<Physics::Trigger>::Key> triggerLockBoxKey;\n std::vector<::Physics::Trigger*> triggers;\n};\n<commit_msg>Align asterisks in doxygen comment.<commit_after>#pragma once\n\n#include <functional>\n#include <glm\/glm.hpp>\n#include <memory>\n#include <Utility\/LockBox.hpp>\n#include <vector>\n#include \"..\/Entity\/ComponentContainer.hpp\"\n#include \"..\/linking.hpp\"\n\nnamespace Component {\n class RigidBody;\n class Shape;\n}\n\nnamespace Physics {\n class Shape;\n class Trigger;\n}\n\nnamespace Json {\n class Value;\n}\n\nclass btBroadphaseInterface;\nclass btDefaultCollisionConfiguration;\nclass btCollisionDispatcher;\nclass btSequentialImpulseConstraintSolver;\nclass btDiscreteDynamicsWorld;\nclass Entity;\n\n\/\/\/ Updates the physics of the world.\nclass PhysicsManager {\n friend class Hub;\n\n public:\n \/\/\/ Moves entities and updates the physics component.\n \/**\n * @param deltaTime Time since last frame (in seconds).\n *\/\n ENGINE_API void Update(float deltaTime);\n \n \/\/\/ Update transforms of entities according to positions of physics\n \/\/\/ components.\n ENGINE_API void UpdateEntityTransforms();\n \n \/\/\/ Set up listener for when |object| has entered |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to enter the trigger volume.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| has entered |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerEnter(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Set up listener for when |object| is intersecting |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to cause trigger to fire.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| is intersecting |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerRetain(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Set up listener for when |object| has left |trigger|.\n \/**\n * @param trigger What trigger to check against.\n * @param object Body that is to cause trigger to fire.\n * @param callback Function to call when resolving event.\n *\/\n ENGINE_API void OnTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object, std::function<void()> callback);\n\n \/\/\/ Stop listening for when |object| has left |trigger|.\n \/**\n * @param trigger What trigger to stop listening on.\n * @param object Body that is to be forgotten.\n *\/\n ENGINE_API void ForgetTriggerLeave(Utility::LockBox<Physics::Trigger> trigger, Component::RigidBody* object);\n\n \/\/\/ Create rigid body component.\n \/**\n * @param owner The %Entity that will own the component.\n * @return The created component.\n *\/\n ENGINE_API Component::RigidBody* CreateRigidBody(Entity* owner);\n\n \/\/\/ Create rigid body component.\n \/**\n * @param owner The %Entity that will own the component.\n * @param node Json node from which to load component definition.\n * @return The created component.\n *\/\n ENGINE_API Component::RigidBody* CreateRigidBody(Entity* owner, const Json::Value& node);\n\n \/\/\/ Create a component that represents a physical shape.\n \/**\n * @param owner The %Entity that will own the component.\n * @return The created component.\n *\/\n ENGINE_API Component::Shape* CreateShape(Entity* owner);\n\n \/\/\/ Create a component that represents a physical shape.\n \/**\n * @param owner The %Entity that will own the component.\n * @param node Json node from which to load component definition.\n * @return The created component.\n *\/\n ENGINE_API Component::Shape* CreateShape(Entity* owner, const Json::Value& node);\n\n \/\/\/ Create a trigger volume that can be used to check intersection\n \/\/\/ events against physics bodies.\n \/**\n * @param shape Shape of the trigger volume.\n * @return A reference to the internal trigger.\n *\/\n ENGINE_API Utility::LockBox<Physics::Trigger> CreateTrigger(std::shared_ptr<Physics::Shape> shape);\n\n \/\/\/ Set the position of a trigger volume.\n \/**\n * @param trigger Volume to reposition.\n * @param position New position in world space.\n *\/\n ENGINE_API void SetPosition(Utility::LockBox<Physics::Trigger> trigger, const glm::vec3& position);\n\n \/\/\/ Set the shape of a given Component::Shape component.\n \/**\n * @param comp The component on which to set the shape.\n * @param shape A Physics::Shape object that holds the shape definition.\n *\/\n ENGINE_API void SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape);\n\n \/\/\/ Get the mass of a rigid body component.\n \/**\n * @param comp Rigid body component to get mass of.\n * @return Mass in kilograms.\n *\/\n ENGINE_API float GetMass(Component::RigidBody* comp);\n\n \/\/\/ Set the volume shape of a trigger.\n \/**\n * @param trigger Trigger to alter shape of.\n * @param shape Shape definition.\n *\/\n ENGINE_API void SetShape(Utility::LockBox<Physics::Trigger> trigger, std::shared_ptr<Physics::Shape> shape);\n\n \/\/\/ Set the mass of a Component::RigidBody component.\n \/**\n * @param comp The component on which to set mass.\n * @param mass Mass in kilograms.\n *\/\n ENGINE_API void SetMass(Component::RigidBody* comp, float mass);\n\n \/\/\/ Set the friction coefficient of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the rolling friction coefficient of a Component::RigidBody\n \/\/\/ component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetRollingFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the spinning friction coefficient of a Component::RigidBody\n \/\/\/ component.\n \/**\n * @param comp Rigid body to alter.\n * @param friction Friction coefficient.\n *\/\n ENGINE_API void SetSpinningFriction(Component::RigidBody* comp, float friction);\n\n \/\/\/ Set the restitution (bounciness) of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param cor Coefficient of restitution.\n *\/\n ENGINE_API void SetRestitution(Component::RigidBody* comp, float cor);\n\n \/\/\/ Set the linear damping factor of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param damping Linear damping.\n *\/\n ENGINE_API void SetLinearDamping(Component::RigidBody* comp, float damping);\n\n \/\/\/ Set the angular damping factor of a Component::RigidBody component.\n \/**\n * @param comp Rigid body to alter.\n * @param damping Angular damping.\n *\/\n ENGINE_API void SetAngularDamping(Component::RigidBody* comp, float damping);\n\n \/\/\/ Turn a rigid body into a kinematic object, putting movement in the\n \/\/\/ control of the programmer.\n \/**\n * @param comp Rigid body to make kinematic.\n *\/\n ENGINE_API void MakeKinematic(Component::RigidBody* comp);\n\n \/\/\/ Turn a rigid body into a dynamic object.\n \/**\n * @param comp Rigid body to make dynamic.\n *\/\n ENGINE_API void MakeDynamic(Component::RigidBody* comp);\n\n \/\/\/ Enables\/disables ghost functionality on a rigid body.\n \/**\n * @param comp Rigid body to alter state of.\n * @param ghost True: makes the rigid object a ghost, disregarding all\n * collisions. False: disables ghost state, reverting to kinematic or\n * dynamic as before.\n *\/\n ENGINE_API void SetGhost(Component::RigidBody* comp, bool ghost);\n\n \/\/\/ Forces a dynamic rigid body to synchronize its transform with that\n \/\/\/ of its owning entity during the next simulation iteration.\n \/**\n * @param comp Rigid body to synchronize.\n *\/\n ENGINE_API void ForceTransformSync(Component::RigidBody* comp);\n\n \/\/\/ Halts movement of a kinematic rigid body.\n \/**\n * @param comp Rigid body to halt.\n *\/\n ENGINE_API void HaltMovement(Component::RigidBody* comp);\n\n \/\/\/ Get all shape components.\n \/**\n * @return All shape components.\n *\/\n ENGINE_API const std::vector<Component::Shape*>& GetShapeComponents() const;\n \n \/\/\/ Remove all killed components.\n ENGINE_API void ClearKilledComponents();\n \n private:\n PhysicsManager();\n ~PhysicsManager();\n PhysicsManager(PhysicsManager const&) = delete;\n void operator=(PhysicsManager const&) = delete;\n\n glm::vec3 gravity = glm::vec3(0.f, -9.82f, 0.f);\n\n ComponentContainer<Component::RigidBody> rigidBodyComponents;\n ComponentContainer<Component::Shape> shapeComponents;\n \n btBroadphaseInterface* broadphase = nullptr;\n btDefaultCollisionConfiguration* collisionConfiguration = nullptr;\n btCollisionDispatcher* dispatcher = nullptr;\n btSequentialImpulseConstraintSolver* solver = nullptr;\n btDiscreteDynamicsWorld* dynamicsWorld = nullptr;\n\n std::shared_ptr<Utility::LockBox<Physics::Trigger>::Key> triggerLockBoxKey;\n std::vector<::Physics::Trigger*> triggers;\n};\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\r\n * Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net> *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <Inventor\/nodes\/SoGroup.h>\r\n#endif\r\n\r\n#include \"ViewProvider.h\"\r\n#include <ItemAssembly.h>\r\n#include <Gui\/Command.h>\r\n\/\/#include <Gui\/Document.h>\r\n\r\n\r\nusing namespace AssemblyGui;\r\n\r\nPROPERTY_SOURCE(AssemblyGui::ViewProviderItem,Gui::ViewProviderGeometryObject)\r\n\r\nViewProviderItem::ViewProviderItem()\r\n{\r\n pcChildren = new SoGroup();\r\n pcChildren->ref();\r\n\r\n}\r\n\r\nViewProviderItem::~ViewProviderItem()\r\n{\r\n pcChildren->unref();\r\n pcChildren = 0;\r\n}\r\n\r\nbool ViewProviderItem::doubleClicked(void)\r\n{\r\n return true;\r\n}\r\n\r\n<commit_msg>small fix<commit_after>\/***************************************************************************\r\n * Copyright (c) 2011 Juergen Riegel <FreeCAD@juergen-riegel.net> *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <Inventor\/nodes\/SoGroup.h>\r\n#endif\r\n\r\n#include \"ViewProvider.h\"\r\n#include <Item.h>\r\n#include <Gui\/Command.h>\r\n\/\/#include <Gui\/Document.h>\r\n\r\n\r\nusing namespace AssemblyGui;\r\n\r\nPROPERTY_SOURCE(AssemblyGui::ViewProviderItem,Gui::ViewProviderGeometryObject)\r\n\r\nViewProviderItem::ViewProviderItem()\r\n{\r\n pcChildren = new SoGroup();\r\n pcChildren->ref();\r\n\r\n}\r\n\r\nViewProviderItem::~ViewProviderItem()\r\n{\r\n pcChildren->unref();\r\n pcChildren = 0;\r\n}\r\n\r\nbool ViewProviderItem::doubleClicked(void)\r\n{\r\n return true;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"DiceRoll\/Operations\/GetNumberOperation.hpp\"\n\nGetNumberOperation::GetNumberOperation(int number)\n : IOperation(nullptr), _number(number)\n{\n _count = 0;\n}\n\nstd::unique_ptr<RollResult> GetNumberOperation::evaluate()\n{\n return execute();\n}\n\nstd::unique_ptr<RollResult> GetNumberOperation::execute() \n{ \n _elements.push_back(_number);\n _count = 1;\n\n \/\/For now, return dummy RollResult\n return std::make_unique<RollResult>();\n}\n<commit_msg>Replaced dummy RollResult in execute() with real one.<commit_after>#include \"DiceRoll\/Operations\/GetNumberOperation.hpp\"\n\nGetNumberOperation::GetNumberOperation(int number)\n : IOperation(nullptr), _number(number)\n{\n _count = 0;\n}\n\nstd::unique_ptr<RollResult> GetNumberOperation::evaluate()\n{\n return execute();\n}\n\nstd::unique_ptr<RollResult> GetNumberOperation::execute() \n{\n \/\/ DELETE THIS\n _elements.push_back(_number);\n _count = 1;\n \/\/ END OF DELETE\n\n \/\/For now, return dummy RollResult\n auto result = std::make_unique<RollResult>();\n result->appendLastResult(_number);\n result->setOperationLog(std::to_string(_number));\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CameraInfoDlg.cpp Camera info dialog\n\/\/\n\n\/\/ includes\n#include \"StdAfx.h\"\n#include \"resource.h\"\n#include \"CameraInfoDlg.hpp\"\n#include \"Instance.hpp\"\n#include \"CameraException.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n\nLRESULT CameraInfoDlg::OnInitDialog(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& \/*bHandled*\/)\n{\n DoDataExchange(DDX_LOAD);\n\n CenterWindow(GetParent());\n\n DlgResize_Init(false, false);\n\n CString cszText;\n try\n {\n cszText = CollectCameraInfo();\n }\n catch(CameraException& ex)\n {\n cszText.AppendFormat(_T(\"\\nError while collecting camera info: %s\\n\"), ex.Message().GetString());\n }\n\n cszText.Replace(_T(\"\\n\"), _T(\"\\r\\n\"));\n m_ecCameraInfo.SetWindowText(cszText);\n\n return TRUE;\n}\n\nCString CameraInfoDlg::CollectCameraInfo()\n{\n CString cszText;\n\n cszText = _T(\"Camera model: \") + m_sourceDevice.ModelName() + _T(\"\\n\");\n cszText += _T(\"Serial number: \") + m_sourceDevice.SerialNumber() + _T(\"\\n\\n\");\n\n \/\/ get available device properties\n CollectDeviceProperties(cszText);\n\n \/\/ check if device supports remote release control\n if (!m_sourceDevice.GetDeviceCapability(SourceDevice::capRemoteReleaseControl))\n {\n cszText += _T(\"Camera doesn't support remote release control\");\n return cszText;\n }\n\n std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl = m_sourceDevice.EnterReleaseControl();\n\n CollectCapabilities(spRemoteReleaseControl, cszText);\n CollectImageProperties(spRemoteReleaseControl, cszText);\n\n CollectShootingModeInfos(spRemoteReleaseControl, cszText);\n\n return cszText;\n}\n\nvoid CameraInfoDlg::CollectDeviceProperties(CString& cszText)\n{\n cszText += _T(\"Supported device properties:\\n\");\n\n std::vector<unsigned int> vecProperties;\n try\n {\n vecProperties = m_sourceDevice.EnumDeviceProperties();\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating device properties: %s\\n\"),\n ex.Message().GetString());\n }\n\n for (size_t i=0, iMax = vecProperties.size(); i<iMax; i++)\n {\n try\n {\n unsigned int uiPropertyId = vecProperties[i];\n DeviceProperty p = m_sourceDevice.GetDeviceProperty(uiPropertyId);\n\n cszText.AppendFormat(_T(\"Property %s (%08x): [%s]\\n\"),\n p.Name().GetString(), uiPropertyId, p.AsString().GetString());\n }\n catch(CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while evaluating property %08x: %s\\n\"),\n vecProperties[i], ex.Message().GetString());\n }\n }\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectCapabilities(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Remote release control capabilities:\\n\");\n\n cszText += _T(\"- can change shooting parameter: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingParameter) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can change shooting mode: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can control zoom: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capZoomControl) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- supports viewfinder: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capViewfinder) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can release while viewfinder is on: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capReleaseWhileViewfinder) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can lock\/unlock AF: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capAFLock) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectImageProperties(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Supported image properties:\\n\");\n\n std::vector<unsigned int> vecImageProperties = spRemoteReleaseControl->EnumImageProperties();\n\n if (vecImageProperties.empty())\n {\n cszText += _T(\"no image properties found.\\n\");\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecImageProperties[i];\n\n try\n {\n ImageProperty ip = spRemoteReleaseControl->GetImageProperty(uiPropertyId);\n\n cszText.AppendFormat(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n try\n {\n std::vector<ImageProperty> vecValues;\n spRemoteReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)\n {\n const ImageProperty& ip2 = vecValues[j];\n cszText.AppendFormat(_T(\" Valid value: %s (%s)\\n\"),\n ip2.Value().ToString().GetString(),\n ip.ValueAsString(ip2.Value()).GetString());\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating device property values for %08x: %s\\n\"),\n uiPropertyId, ex.Message().GetString());\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while getting device property %08x: %s\\n\"),\n uiPropertyId, ex.Message().GetString());\n }\n }\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectShootingModeInfos(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Supported shooting modes:\\n\");\n\n try\n {\n if (!spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode))\n {\n cszText += _T(\"(Switching shooting modes not supported, can only dump current mode)\\n\");\n\n unsigned int uiShootingModePropertyId =\n spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propShootingMode);\n\n \/\/ no, just dump current shooting mode\n ImageProperty currentShootingMode = spRemoteReleaseControl->GetImageProperty(uiShootingModePropertyId);\n\n CollectShootingModeDetails(spRemoteReleaseControl, currentShootingMode, cszText);\n }\n else\n {\n \/\/ switch through all shooting modes and dump\n std::vector<ImageProperty> vecShootingModes;\n unsigned int uiPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propShootingMode);\n spRemoteReleaseControl->EnumImagePropertyValues(uiPropertyId, vecShootingModes);\n\n if (vecShootingModes.empty())\n cszText += _T(\"(No shooting modes found)\\n\");\n\n std::for_each(vecShootingModes.begin(), vecShootingModes.end(), [&](const ImageProperty& ip)\n {\n spRemoteReleaseControl->SetImageProperty(ip);\n\n CollectShootingModeDetails(spRemoteReleaseControl, ip, cszText);\n });\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating shooting modes: %s\\n\"),\n ex.Message().GetString());\n }\n}\n\nvoid CameraInfoDlg::CollectShootingModeDetails(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,\n const ImageProperty& shootingMode, CString& cszText)\n{\n cszText.AppendFormat(_T(\"Shooting mode: %s\\n\"), shootingMode.AsString().GetString());\n\n \/\/ get Av values\n {\n std::vector<ImageProperty> vecAvValues;\n unsigned int uiAvPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propAv);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiAvPropertyId, vecAvValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating Av values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecAvValues.empty())\n {\n cszText += _T(\" Available aperture values: \");\n for (size_t i=0, iMax=vecAvValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecAvValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n \/\/ get Tv values\n {\n std::vector<ImageProperty> vecTvValues;\n unsigned int uiTvPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propTv);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiTvPropertyId, vecTvValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Exception while enumerating Tv values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecTvValues.empty())\n {\n cszText += _T(\" Available shutter speed values: \");\n for (size_t i=0, iMax=vecTvValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecTvValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n \/\/ get exposure compensation values\n {\n std::vector<ImageProperty> vecEcValues;\n unsigned int uiEcPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propExposureCompensation);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiEcPropertyId, vecEcValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating exposure compensation values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecEcValues.empty())\n {\n cszText += _T(\" Available exposure compensation values: \");\n for (size_t i=0, iMax=vecEcValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecEcValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n cszText += _T(\"\\n\");\n}\n<commit_msg>added missing remote capabilities in camera info dialog<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CameraInfoDlg.cpp Camera info dialog\n\/\/\n\n\/\/ includes\n#include \"StdAfx.h\"\n#include \"resource.h\"\n#include \"CameraInfoDlg.hpp\"\n#include \"Instance.hpp\"\n#include \"CameraException.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n\nLRESULT CameraInfoDlg::OnInitDialog(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& \/*bHandled*\/)\n{\n DoDataExchange(DDX_LOAD);\n\n CenterWindow(GetParent());\n\n DlgResize_Init(false, false);\n\n CString cszText;\n try\n {\n cszText = CollectCameraInfo();\n }\n catch(CameraException& ex)\n {\n cszText.AppendFormat(_T(\"\\nError while collecting camera info: %s\\n\"), ex.Message().GetString());\n }\n\n cszText.Replace(_T(\"\\n\"), _T(\"\\r\\n\"));\n m_ecCameraInfo.SetWindowText(cszText);\n\n return TRUE;\n}\n\nCString CameraInfoDlg::CollectCameraInfo()\n{\n CString cszText;\n\n cszText = _T(\"Camera model: \") + m_sourceDevice.ModelName() + _T(\"\\n\");\n cszText += _T(\"Serial number: \") + m_sourceDevice.SerialNumber() + _T(\"\\n\\n\");\n\n \/\/ get available device properties\n CollectDeviceProperties(cszText);\n\n \/\/ check if device supports remote release control\n if (!m_sourceDevice.GetDeviceCapability(SourceDevice::capRemoteReleaseControl))\n {\n cszText += _T(\"Camera doesn't support remote release control\");\n return cszText;\n }\n\n std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl = m_sourceDevice.EnterReleaseControl();\n\n CollectCapabilities(spRemoteReleaseControl, cszText);\n CollectImageProperties(spRemoteReleaseControl, cszText);\n\n CollectShootingModeInfos(spRemoteReleaseControl, cszText);\n\n return cszText;\n}\n\nvoid CameraInfoDlg::CollectDeviceProperties(CString& cszText)\n{\n cszText += _T(\"Supported device properties:\\n\");\n\n std::vector<unsigned int> vecProperties;\n try\n {\n vecProperties = m_sourceDevice.EnumDeviceProperties();\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating device properties: %s\\n\"),\n ex.Message().GetString());\n }\n\n for (size_t i=0, iMax = vecProperties.size(); i<iMax; i++)\n {\n try\n {\n unsigned int uiPropertyId = vecProperties[i];\n DeviceProperty p = m_sourceDevice.GetDeviceProperty(uiPropertyId);\n\n cszText.AppendFormat(_T(\"Property %s (%08x): [%s]\\n\"),\n p.Name().GetString(), uiPropertyId, p.AsString().GetString());\n }\n catch(CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while evaluating property %08x: %s\\n\"),\n vecProperties[i], ex.Message().GetString());\n }\n }\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectCapabilities(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Remote release control capabilities:\\n\");\n\n cszText += _T(\"- can change shooting parameter: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingParameter) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can change shooting mode: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can control zoom: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capZoomControl) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- supports viewfinder: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capViewfinder) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can release while viewfinder is on: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capReleaseWhileViewfinder) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can lock\/unlock AF: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capAFLock) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can use Bulb mode: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capBulbMode) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"- can lock\/unlock user interface: \");\n cszText += spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capUILock) ? _T(\"Yes\") : _T(\"NO\");\n cszText += _T(\"\\n\");\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectImageProperties(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Supported image properties:\\n\");\n\n std::vector<unsigned int> vecImageProperties = spRemoteReleaseControl->EnumImageProperties();\n\n if (vecImageProperties.empty())\n {\n cszText += _T(\"no image properties found.\\n\");\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecImageProperties[i];\n\n try\n {\n ImageProperty ip = spRemoteReleaseControl->GetImageProperty(uiPropertyId);\n\n cszText.AppendFormat(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n try\n {\n std::vector<ImageProperty> vecValues;\n spRemoteReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)\n {\n const ImageProperty& ip2 = vecValues[j];\n cszText.AppendFormat(_T(\" Valid value: %s (%s)\\n\"),\n ip2.Value().ToString().GetString(),\n ip.ValueAsString(ip2.Value()).GetString());\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating device property values for %08x: %s\\n\"),\n uiPropertyId, ex.Message().GetString());\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while getting device property %08x: %s\\n\"),\n uiPropertyId, ex.Message().GetString());\n }\n }\n\n cszText += _T(\"\\n\");\n}\n\nvoid CameraInfoDlg::CollectShootingModeInfos(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl, CString& cszText)\n{\n cszText += _T(\"Supported shooting modes:\\n\");\n\n try\n {\n if (!spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode))\n {\n cszText += _T(\"(Switching shooting modes not supported, can only dump current mode)\\n\");\n\n unsigned int uiShootingModePropertyId =\n spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propShootingMode);\n\n \/\/ no, just dump current shooting mode\n ImageProperty currentShootingMode = spRemoteReleaseControl->GetImageProperty(uiShootingModePropertyId);\n\n CollectShootingModeDetails(spRemoteReleaseControl, currentShootingMode, cszText);\n }\n else\n {\n \/\/ switch through all shooting modes and dump\n std::vector<ImageProperty> vecShootingModes;\n unsigned int uiPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propShootingMode);\n spRemoteReleaseControl->EnumImagePropertyValues(uiPropertyId, vecShootingModes);\n\n if (vecShootingModes.empty())\n cszText += _T(\"(No shooting modes found)\\n\");\n\n std::for_each(vecShootingModes.begin(), vecShootingModes.end(), [&](const ImageProperty& ip)\n {\n spRemoteReleaseControl->SetImageProperty(ip);\n\n CollectShootingModeDetails(spRemoteReleaseControl, ip, cszText);\n });\n }\n }\n catch (CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating shooting modes: %s\\n\"),\n ex.Message().GetString());\n }\n}\n\nvoid CameraInfoDlg::CollectShootingModeDetails(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl,\n const ImageProperty& shootingMode, CString& cszText)\n{\n cszText.AppendFormat(_T(\"Shooting mode: %s\\n\"), shootingMode.AsString().GetString());\n\n \/\/ get Av values\n {\n std::vector<ImageProperty> vecAvValues;\n unsigned int uiAvPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propAv);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiAvPropertyId, vecAvValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating Av values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecAvValues.empty())\n {\n cszText += _T(\" Available aperture values: \");\n for (size_t i=0, iMax=vecAvValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecAvValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n \/\/ get Tv values\n {\n std::vector<ImageProperty> vecTvValues;\n unsigned int uiTvPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propTv);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiTvPropertyId, vecTvValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Exception while enumerating Tv values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecTvValues.empty())\n {\n cszText += _T(\" Available shutter speed values: \");\n for (size_t i=0, iMax=vecTvValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecTvValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n \/\/ get exposure compensation values\n {\n std::vector<ImageProperty> vecEcValues;\n unsigned int uiEcPropertyId = spRemoteReleaseControl->MapImagePropertyTypeToId(T_enImagePropertyType::propExposureCompensation);\n\n try\n {\n spRemoteReleaseControl->EnumImagePropertyValues(uiEcPropertyId, vecEcValues);\n }\n catch(const CameraException& ex)\n {\n cszText.AppendFormat(_T(\"Error while enumerating exposure compensation values: %s\\n\"), ex.Message().GetString());\n }\n\n if (!vecEcValues.empty())\n {\n cszText += _T(\" Available exposure compensation values: \");\n for (size_t i=0, iMax=vecEcValues.size(); i<iMax; i++)\n {\n const ImageProperty& val = vecEcValues[i];\n\n cszText.AppendFormat(_T(\"%s%s\"), i==0 ? _T(\"\") : _T(\", \"), val.AsString().GetString());\n }\n cszText += _T(\"\\n\");\n }\n }\n\n cszText += _T(\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main_menu_view.cc\n\/\/ AirHockey\n\/\/\n\/\/ Created by Jon Sharkey on 2010-04-30.\n\/\/ Copyright 2010 Sharkable. All rights reserved.\n\/\/\n\n#include \"airhockey\/views\/main_menu_view.h\"\n\n#include <map>\n#include <sstream>\nusing std::map;\nusing std::string;\n\n#include \"gameengine\/entities\/simple_item.h\"\n#include \"gameengine\/modules\/ad_engine.h\"\n#include \"gameengine\/modules\/analytics_engine.h\"\n#include \"gameengine\/modules\/local_store.h\"\n#include \"gameengine\/coordinate_types.h\"\n#include \"gameengine\/game_engine.h\"\n#include \"gameengine\/sprite.h\"\n\n#include \"airhockey\/entities\/rink_overlay.h\"\n#include \"airhockey\/entities\/sound_slider.h\"\n#include \"airhockey\/views\/play_view.h\"\n#include \"airhockey\/views\/settings_view.h\"\n#include \"airhockey\/views\/story_view.h\"\n\nstatic const int kAnimateOutTicks = 15;\n\n\/\/ Local Store keys\nconst string kLocalStoreMainMenuViewCount = \"ls_main_menu_view_count\";\nconst string kLocalStoreUpgraded = \"ls_upgraded\";\n\ninline string to_string(int i) {\n std::stringstream ss;\n ss << i;\n return ss.str();\n}\n\nvoid fade_in(Animatable *entity) {\n entity->set_alpha(0);\n entity->AnimateToAlpha(1, kAnimationTypeLinear, 15);\n}\n\nvoid fade_out(Animatable *entity) {\n entity->AnimateToAlpha(0, kAnimationTypeLinear, 15);\n}\n\nMainMenuView::MainMenuView(GameEngine *game_engine) : EngineView(game_engine) {\n show_upgrade_button_ = game_engine->app_store_engine()->IsImplemented();\n supports_2_player_ = game_engine->platform_type() != kPlatformTypePC;\n\n InitializeSettings();\n state_ = kMainMenuStateRunning;\n\n rink_overlay_.reset(new RinkOverlay(game_engine));\n AddEntity(rink_overlay_);\n\n Sprite title_sprite(game_engine, \"title\");\n title_.reset(new SimpleItem(title_sprite, game_engine->position(\"title\")));\n AddEntity(title_);\n title_->set_zoom(1.3);\n title_->AnimateToZoom(1, kAnimationTypeCubicEaseOut, 900);\n title_->set_alpha(0);\n title_->AnimateToAlpha(1, kAnimationTypeCubicEaseOut, 900);\n\n char const *start_button;\n char const *start_button_pressed;\n if (supports_2_player_) {\n start_button = \"start_1_player_button\";\n start_button_pressed = \"start_1_player_button_pressed\";\n } else {\n start_button = \"start_button\";\n start_button_pressed = \"start_button_pressed\";\n }\n Sprite start_1_player_button_image(game_engine, start_button);\n Sprite start_1_player_button_pressed_image(game_engine, start_button_pressed);\n start_1_player_button_.reset(new Button());\n start_1_player_button_->set_normal_sprite(start_1_player_button_image);\n start_1_player_button_->set_pressed_sprite(start_1_player_button_pressed_image);\n GamePoint player_1_position = game_engine->position(\"start_1_player_button\");\n if (!show_upgrade_button_) {\n player_1_position.y += 90;\n }\n start_1_player_button_->set_position(player_1_position);\n start_1_player_button_->set_delegate(this);\n AddEntity(start_1_player_button_);\n fade_in(start_1_player_button_.get());\n\n if (supports_2_player_) {\n Sprite start_2_player_button_image(game_engine, \"start_2_player_button\");\n Sprite start_2_player_button_pressed_image(game_engine, \"start_2_player_button_pressed\");\n start_2_player_button_.reset(new Button());\n start_2_player_button_->set_normal_sprite(start_2_player_button_image);\n start_2_player_button_->set_pressed_sprite(start_2_player_button_pressed_image);\n GamePoint player_2_position = game_engine->position(\"start_2_player_button\");\n if (!show_upgrade_button_) {\n player_2_position.y += 90;\n }\n start_2_player_button_->set_position(player_2_position);\n start_2_player_button_->set_delegate(this);\n AddEntity(start_2_player_button_);\n fade_in(start_2_player_button_.get());\n }\n\n Sprite settings_button_image(game_engine, \"settings_button\");\n Sprite settings_button_pressed_image(game_engine, \"settings_button_pressed\");\n settings_button_.reset(new Button());\n settings_button_->set_normal_sprite(settings_button_image);\n settings_button_->set_pressed_sprite(settings_button_pressed_image);\n settings_button_->set_position(game_engine->position(\"settings_button\"));\n settings_button_->set_delegate(this);\n AddEntity(settings_button_);\n fade_in(settings_button_.get());\n\n Sprite story_button_image(game_engine, \"story_button\");\n Sprite story_button_pressed_image(game_engine, \"story_button_pressed\");\n story_button_.reset(new Button());\n story_button_->set_normal_sprite(story_button_image);\n story_button_->set_pressed_sprite(story_button_pressed_image);\n story_button_->set_position(game_engine->position(\"story_button\"));\n story_button_->set_delegate(this);\n AddEntity(story_button_);\n fade_in(story_button_.get());\n\n if (show_upgrade_button_) {\n Sprite upgrade_button_image(game_engine, \"upgrade_button\");\n Sprite upgrade_button_pressed_image(game_engine, \"upgrade_button_pressed\");\n upgrade_button_.reset(new Button());\n upgrade_button_->set_normal_sprite(upgrade_button_image);\n upgrade_button_->set_pressed_sprite(upgrade_button_pressed_image);\n upgrade_button_->set_position(game_engine->position(\"upgrade_button\"));\n upgrade_button_->set_delegate(this);\n if (!game_engine->local_store()->BoolForKey(kLocalStoreUpgraded)) {\n AddEntity(upgrade_button_);\n }\n fade_in(upgrade_button_.get());\n }\n\n sound_slider_.reset(new SoundSlider(game_engine,\n game_engine->position(\"sound_slider_main_menu\")));\n AddEntity(sound_slider_);\n}\n\n\n\/\/ EngineView\n\nvoid MainMenuView::ViewDidGainFocus() {\n if (show_upgrade_button_) {\n \/\/ Force the popup for rating and upgrading just once.\n int main_menu_view_count =\n game_engine()->local_store()->IntegerForKey(kLocalStoreMainMenuViewCount) + 1;\n game_engine()->local_store()->SetInteger(main_menu_view_count, kLocalStoreMainMenuViewCount);\n if (main_menu_view_count == 10) {\n PressedUpgrade();\n }\n }\n}\n\nvoid MainMenuView::Update() {\n EngineView::Update();\n if (state_ == kMainMenuStateAnimatingOut) {\n animating_out_ticks_left_--;\n \/\/ TODO This sometimes causes a brief overlap with the overlap in PlayView.\n if (animating_out_ticks_left_ == kAnimateOutTicks) {\n RemoveEntity(rink_overlay_);\n }\n if (animating_out_ticks_left_ <= 0) {\n game_engine()->RemoveView(this);\n }\n }\n}\n\n\n\/\/ AppStoreEngineDelegate\n\nvoid MainMenuView::UpgradeSucceeded() {\n game_engine()->local_store()->SetBool(true, kLocalStoreUpgraded);\n RemoveEntity(upgrade_button_);\n}\n\n\n\/\/ ButtonDelegate\n\nvoid MainMenuView::ButtonPressed(Button *button) {\n if (button == start_1_player_button_.get()) {\n PressedStart(1);\n } else if (button == start_2_player_button_.get()) {\n PressedStart(2);\n } else if (button == settings_button_.get()) {\n PressedSettings();\n } else if (button == story_button_.get()) {\n PressedStory();\n } else if (button == upgrade_button_.get()) {\n PressedUpgrade();\n }\n}\n\n\n\/\/ private\n\nvoid MainMenuView::InitializeSettings() {\n if (!game_engine()->local_store()->HasEntryForKey(kLocalStoreDifficulty)) {\n game_engine()->local_store()->SetInteger(kComputerAIBad, kLocalStoreDifficulty);\n game_engine()->local_store()->SetInteger(kPaddleSizeLarge, kLocalStorePaddleSize);\n }\n}\n\nvoid MainMenuView::AnimateOut() {\n state_ = kMainMenuStateAnimatingOut;\n\n title_->AnimateToZoom(0, kAnimationTypeLinear, 15);\n fade_out(start_1_player_button_.get());\n if (supports_2_player_) {\n fade_out(start_2_player_button_.get());\n }\n fade_out(settings_button_.get());\n fade_out(story_button_.get());\n if (show_upgrade_button_) {\n fade_out(upgrade_button_.get());\n }\n RemoveEntity(sound_slider_);\n\n animating_out_ticks_left_ = kAnimateOutTicks;\n}\n\nvoid MainMenuView::PressedStart(int num_players) {\n if (game_engine()->platform_type() == kPlatformTypeTablet) {\n game_engine()->ad_engine()->RemoveAd();\n }\n\n \/\/ The stored number of pucks is one less than the desired value. Not ideal. This is for:\n \/\/ 1) Legacy.\n \/\/ 2) Defaults to 0, which means 1 puck.\n int num_pucks = game_engine()->local_store()->IntegerForKey(kLocalStoreNumPucks) + 1;\n ComputerAI difficulty =\n (ComputerAI)game_engine()->local_store()->IntegerForKey(kLocalStoreDifficulty);\n PaddleSize paddle_size =\n (PaddleSize)game_engine()->local_store()->IntegerForKey(kLocalStorePaddleSize);\n map<string, string> analytics_params;\n analytics_params[\"NumPlayers\"] = to_string(num_players);\n analytics_params[\"NumPucks\"] = to_string(num_pucks);\n analytics_params[\"Difficulty\"] = to_string(difficulty);\n analytics_params[\"PaddleSize\"] = to_string(paddle_size);\n game_engine()->analytics_engine()->LogEvent(\"START_GAME\", analytics_params);\n\n PlayView *play_view = new PlayView(game_engine(),\n num_players,\n num_pucks,\n difficulty,\n paddle_size);\n AnimateOut();\n game_engine()->PushView(sp<EngineView>(play_view));\n}\n\nvoid MainMenuView::PressedSettings() {\n game_engine()->PushView(sp<SettingsView>(new SettingsView(game_engine())));\n}\n\nvoid MainMenuView::PressedStory() {\n game_engine()->analytics_engine()->LogEvent(\"STORY_PRESSED\");\n if (game_engine()->platform_type() == kPlatformTypeTablet) {\n game_engine()->ad_engine()->RemoveAd();\n }\n game_engine()->PushView(sp<EngineView>(new StoryView(game_engine())));\n}\n\nvoid MainMenuView::PressedUpgrade() {\n if (!game_engine()->local_store()->BoolForKey(kLocalStoreUpgraded)) {\n game_engine()->app_store_engine()->AskForUpgrade(\"Glide Hockey HD\", \"GlideHockeyHDUpgrade\",\n this);\n }\n}\n<commit_msg>Default to medium paddle size on everything except a phone.<commit_after>\/\/\n\/\/ main_menu_view.cc\n\/\/ AirHockey\n\/\/\n\/\/ Created by Jon Sharkey on 2010-04-30.\n\/\/ Copyright 2010 Sharkable. All rights reserved.\n\/\/\n\n#include \"airhockey\/views\/main_menu_view.h\"\n\n#include <map>\n#include <sstream>\nusing std::map;\nusing std::string;\n\n#include \"gameengine\/entities\/simple_item.h\"\n#include \"gameengine\/modules\/ad_engine.h\"\n#include \"gameengine\/modules\/analytics_engine.h\"\n#include \"gameengine\/modules\/local_store.h\"\n#include \"gameengine\/coordinate_types.h\"\n#include \"gameengine\/game_engine.h\"\n#include \"gameengine\/sprite.h\"\n\n#include \"airhockey\/entities\/rink_overlay.h\"\n#include \"airhockey\/entities\/sound_slider.h\"\n#include \"airhockey\/views\/play_view.h\"\n#include \"airhockey\/views\/settings_view.h\"\n#include \"airhockey\/views\/story_view.h\"\n\nstatic const int kAnimateOutTicks = 15;\n\n\/\/ Local Store keys\nconst string kLocalStoreMainMenuViewCount = \"ls_main_menu_view_count\";\nconst string kLocalStoreUpgraded = \"ls_upgraded\";\n\ninline string to_string(int i) {\n std::stringstream ss;\n ss << i;\n return ss.str();\n}\n\nvoid fade_in(Animatable *entity) {\n entity->set_alpha(0);\n entity->AnimateToAlpha(1, kAnimationTypeLinear, 15);\n}\n\nvoid fade_out(Animatable *entity) {\n entity->AnimateToAlpha(0, kAnimationTypeLinear, 15);\n}\n\nMainMenuView::MainMenuView(GameEngine *game_engine) : EngineView(game_engine) {\n show_upgrade_button_ = game_engine->app_store_engine()->IsImplemented();\n supports_2_player_ = game_engine->platform_type() != kPlatformTypePC;\n\n InitializeSettings();\n state_ = kMainMenuStateRunning;\n\n rink_overlay_.reset(new RinkOverlay(game_engine));\n AddEntity(rink_overlay_);\n\n Sprite title_sprite(game_engine, \"title\");\n title_.reset(new SimpleItem(title_sprite, game_engine->position(\"title\")));\n AddEntity(title_);\n title_->set_zoom(1.3);\n title_->AnimateToZoom(1, kAnimationTypeCubicEaseOut, 900);\n title_->set_alpha(0);\n title_->AnimateToAlpha(1, kAnimationTypeCubicEaseOut, 900);\n\n char const *start_button;\n char const *start_button_pressed;\n if (supports_2_player_) {\n start_button = \"start_1_player_button\";\n start_button_pressed = \"start_1_player_button_pressed\";\n } else {\n start_button = \"start_button\";\n start_button_pressed = \"start_button_pressed\";\n }\n Sprite start_1_player_button_image(game_engine, start_button);\n Sprite start_1_player_button_pressed_image(game_engine, start_button_pressed);\n start_1_player_button_.reset(new Button());\n start_1_player_button_->set_normal_sprite(start_1_player_button_image);\n start_1_player_button_->set_pressed_sprite(start_1_player_button_pressed_image);\n GamePoint player_1_position = game_engine->position(\"start_1_player_button\");\n if (!show_upgrade_button_) {\n player_1_position.y += 90;\n }\n start_1_player_button_->set_position(player_1_position);\n start_1_player_button_->set_delegate(this);\n AddEntity(start_1_player_button_);\n fade_in(start_1_player_button_.get());\n\n if (supports_2_player_) {\n Sprite start_2_player_button_image(game_engine, \"start_2_player_button\");\n Sprite start_2_player_button_pressed_image(game_engine, \"start_2_player_button_pressed\");\n start_2_player_button_.reset(new Button());\n start_2_player_button_->set_normal_sprite(start_2_player_button_image);\n start_2_player_button_->set_pressed_sprite(start_2_player_button_pressed_image);\n GamePoint player_2_position = game_engine->position(\"start_2_player_button\");\n if (!show_upgrade_button_) {\n player_2_position.y += 90;\n }\n start_2_player_button_->set_position(player_2_position);\n start_2_player_button_->set_delegate(this);\n AddEntity(start_2_player_button_);\n fade_in(start_2_player_button_.get());\n }\n\n Sprite settings_button_image(game_engine, \"settings_button\");\n Sprite settings_button_pressed_image(game_engine, \"settings_button_pressed\");\n settings_button_.reset(new Button());\n settings_button_->set_normal_sprite(settings_button_image);\n settings_button_->set_pressed_sprite(settings_button_pressed_image);\n settings_button_->set_position(game_engine->position(\"settings_button\"));\n settings_button_->set_delegate(this);\n AddEntity(settings_button_);\n fade_in(settings_button_.get());\n\n Sprite story_button_image(game_engine, \"story_button\");\n Sprite story_button_pressed_image(game_engine, \"story_button_pressed\");\n story_button_.reset(new Button());\n story_button_->set_normal_sprite(story_button_image);\n story_button_->set_pressed_sprite(story_button_pressed_image);\n story_button_->set_position(game_engine->position(\"story_button\"));\n story_button_->set_delegate(this);\n AddEntity(story_button_);\n fade_in(story_button_.get());\n\n if (show_upgrade_button_) {\n Sprite upgrade_button_image(game_engine, \"upgrade_button\");\n Sprite upgrade_button_pressed_image(game_engine, \"upgrade_button_pressed\");\n upgrade_button_.reset(new Button());\n upgrade_button_->set_normal_sprite(upgrade_button_image);\n upgrade_button_->set_pressed_sprite(upgrade_button_pressed_image);\n upgrade_button_->set_position(game_engine->position(\"upgrade_button\"));\n upgrade_button_->set_delegate(this);\n if (!game_engine->local_store()->BoolForKey(kLocalStoreUpgraded)) {\n AddEntity(upgrade_button_);\n }\n fade_in(upgrade_button_.get());\n }\n\n sound_slider_.reset(new SoundSlider(game_engine,\n game_engine->position(\"sound_slider_main_menu\")));\n AddEntity(sound_slider_);\n}\n\n\n\/\/ EngineView\n\nvoid MainMenuView::ViewDidGainFocus() {\n if (show_upgrade_button_) {\n \/\/ Force the popup for rating and upgrading just once.\n int main_menu_view_count =\n game_engine()->local_store()->IntegerForKey(kLocalStoreMainMenuViewCount) + 1;\n game_engine()->local_store()->SetInteger(main_menu_view_count, kLocalStoreMainMenuViewCount);\n if (main_menu_view_count == 10) {\n PressedUpgrade();\n }\n }\n}\n\nvoid MainMenuView::Update() {\n EngineView::Update();\n if (state_ == kMainMenuStateAnimatingOut) {\n animating_out_ticks_left_--;\n \/\/ TODO This sometimes causes a brief overlap with the overlap in PlayView.\n if (animating_out_ticks_left_ == kAnimateOutTicks) {\n RemoveEntity(rink_overlay_);\n }\n if (animating_out_ticks_left_ <= 0) {\n game_engine()->RemoveView(this);\n }\n }\n}\n\n\n\/\/ AppStoreEngineDelegate\n\nvoid MainMenuView::UpgradeSucceeded() {\n game_engine()->local_store()->SetBool(true, kLocalStoreUpgraded);\n RemoveEntity(upgrade_button_);\n}\n\n\n\/\/ ButtonDelegate\n\nvoid MainMenuView::ButtonPressed(Button *button) {\n if (button == start_1_player_button_.get()) {\n PressedStart(1);\n } else if (button == start_2_player_button_.get()) {\n PressedStart(2);\n } else if (button == settings_button_.get()) {\n PressedSettings();\n } else if (button == story_button_.get()) {\n PressedStory();\n } else if (button == upgrade_button_.get()) {\n PressedUpgrade();\n }\n}\n\n\n\/\/ private\n\nvoid MainMenuView::InitializeSettings() {\n if (!game_engine()->local_store()->HasEntryForKey(kLocalStoreDifficulty)) {\n game_engine()->local_store()->SetInteger(kComputerAIBad, kLocalStoreDifficulty);\n PaddleSize default_size = kPaddleSizeMedium;\n if (game_engine()->platform_type() == kPlatformTypePhone) {\n default_size = kPaddleSizeLarge;\n }\n game_engine()->local_store()->SetInteger(default_size, kLocalStorePaddleSize);\n }\n}\n\nvoid MainMenuView::AnimateOut() {\n state_ = kMainMenuStateAnimatingOut;\n\n title_->AnimateToZoom(0, kAnimationTypeLinear, 15);\n fade_out(start_1_player_button_.get());\n if (supports_2_player_) {\n fade_out(start_2_player_button_.get());\n }\n fade_out(settings_button_.get());\n fade_out(story_button_.get());\n if (show_upgrade_button_) {\n fade_out(upgrade_button_.get());\n }\n RemoveEntity(sound_slider_);\n\n animating_out_ticks_left_ = kAnimateOutTicks;\n}\n\nvoid MainMenuView::PressedStart(int num_players) {\n if (game_engine()->platform_type() == kPlatformTypeTablet) {\n game_engine()->ad_engine()->RemoveAd();\n }\n\n \/\/ The stored number of pucks is one less than the desired value. Not ideal. This is for:\n \/\/ 1) Legacy.\n \/\/ 2) Defaults to 0, which means 1 puck.\n int num_pucks = game_engine()->local_store()->IntegerForKey(kLocalStoreNumPucks) + 1;\n ComputerAI difficulty =\n (ComputerAI)game_engine()->local_store()->IntegerForKey(kLocalStoreDifficulty);\n PaddleSize paddle_size =\n (PaddleSize)game_engine()->local_store()->IntegerForKey(kLocalStorePaddleSize);\n map<string, string> analytics_params;\n analytics_params[\"NumPlayers\"] = to_string(num_players);\n analytics_params[\"NumPucks\"] = to_string(num_pucks);\n analytics_params[\"Difficulty\"] = to_string(difficulty);\n analytics_params[\"PaddleSize\"] = to_string(paddle_size);\n game_engine()->analytics_engine()->LogEvent(\"START_GAME\", analytics_params);\n\n PlayView *play_view = new PlayView(game_engine(),\n num_players,\n num_pucks,\n difficulty,\n paddle_size);\n AnimateOut();\n game_engine()->PushView(sp<EngineView>(play_view));\n}\n\nvoid MainMenuView::PressedSettings() {\n game_engine()->PushView(sp<SettingsView>(new SettingsView(game_engine())));\n}\n\nvoid MainMenuView::PressedStory() {\n game_engine()->analytics_engine()->LogEvent(\"STORY_PRESSED\");\n if (game_engine()->platform_type() == kPlatformTypeTablet) {\n game_engine()->ad_engine()->RemoveAd();\n }\n game_engine()->PushView(sp<EngineView>(new StoryView(game_engine())));\n}\n\nvoid MainMenuView::PressedUpgrade() {\n if (!game_engine()->local_store()->BoolForKey(kLocalStoreUpgraded)) {\n game_engine()->app_store_engine()->AskForUpgrade(\"Glide Hockey HD\", \"GlideHockeyHDUpgrade\",\n this);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"emboxvcwindowsurface.h\"\n#include <QtCore\/qdebug.h>\n#include <QtGui\/private\/qapplication_p.h>\n#include <QWindowSystemInterface>\n#include <QMouseEvent>\n\nQT_BEGIN_NAMESPACE\n\nstatic QList<QEmboxVCWindowSurface*> __emboxVCcollection;\nextern QEmboxVC *globalEmboxVC;\n\n\/\/static QEmboxVCWindowSurface * __emboxVC(struct vc *vc) {\n\/\/\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\/\/\t\tQEmboxVCWindowSurface *emvc = __emboxVCcollection.at(i);\n\/\/\t\tif (&(emvc->emboxVC) == vc) {\n\/\/\t\t\treturn emvc;\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\treturn NULL;\n\/\/}\n\nstatic void flushAll() {\n\tQRegion region;\n\tQPoint point;\n\n\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\t\t__emboxVCcollection.at(i)->flush(0, region, point);\n\t}\n}\n\nstatic int visibleWidgetsCount() {\n\tint cnt = 0;\n\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\t\tcnt += __emboxVCcollection.at(i)->window()->isVisible() ? 1 : 0;\n\t}\n\treturn cnt;\n}\n\nstatic void __emboxVCsetMode(struct vc *vc, int mode) {\n\tglobalEmboxVC->emboxVCvisualized = mode;\n}\n\nstatic void __visualization(struct vc *vc, struct fb_info *info) {\n\tQ_UNUSED(info);\n\n\tQEmboxVCWindowSurface *surf;\n\n\t__emboxVCsetMode(vc, 1);\n\t\/\/surf = __emboxVC(vc);\n\t\/\/surf->flush(NULL, region, point);\n\tflushAll();\n\n\tforeach (QWidget *widget, QApplication::allWidgets()) {\n\t\twidget->update();\n\t}\n}\n\nQEmboxVCMouseHandler::QEmboxVCMouseHandler() {\n\tint pipefd[2];\n\n\tif (pipe(pipefd) < 0) {\n\t\treturn;\n\t}\n\n\tmouseFD = pipefd[0];\n\tinputFD = pipefd[1];\n\n\tfcntl(mouseFD, F_SETFD, O_NONBLOCK);\n\tfcntl(inputFD, F_SETFD, O_NONBLOCK);\n\n mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this);\n connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData()));\n}\n\nQEmboxVCMouseHandler::~QEmboxVCMouseHandler() {\n\n}\n\nvoid QEmboxVCMouseHandler::storeData(void *data, int datalen) {\n\twrite(inputFD, data, datalen);\n}\n\nvoid QEmboxVCMouseHandler::readMouseData() {\n\tstruct vc *vc;\n\tstruct input_event ev;\n\tshort x, y;\n\tint bstate;\n\tQEmboxVC *emvc;\n\n\twhile (read(mouseFD, &vc, sizeof(struct vc *)) > 0) {\n\n\t\tread(mouseFD, &ev, sizeof(struct input_event));\n\n\t\temvc = globalEmboxVC;\n\n\t\tbstate = Qt::NoButton;\n\n\t\tif (ev.type & 1) {\n\t\t\tbstate = Qt::LeftButton;\n\t\t} else if (ev.type & 2) {\n\t\t\tbstate = Qt::RightButton;\n\t\t}\n\n\t\tx = ev.value >> 16;\n\t\ty = ev.value & 0xffff;\n\n\t\temvc->mouseX += x;\n\t\temvc->mouseY += -y;\n\n\t\tint xres = emvc->emboxVC.fb->var.xres;\n\t\tint yres = emvc->emboxVC.fb->var.yres;\n\n\t\temvc->mouseX = emvc->mouseX > 0 ? emvc->mouseX : 0;\n\t\temvc->mouseY = emvc->mouseY > 0 ? emvc->mouseY : 0;\n\n\t\temvc->mouseX = emvc->mouseX > xres ? xres : emvc->mouseX;\n\t\temvc->mouseY = emvc->mouseY > yres ? yres : emvc->mouseY;\n\n\t\tQWindowSystemInterface::handleMouseEvent(0, QPoint(emvc->mouseX, emvc->mouseY),\n\t\t\t\tQPoint(emvc->mouseX, emvc->mouseY), Qt::MouseButtons(bstate));\n\n\t\tif (!emvc->emboxVC.fb || !emvc->emboxVCvisualized) {\n\t\t\treturn;\n\t\t}\n\n\t\temvc->cursor->emboxCursorRedraw(emvc->emboxVC.fb, emvc->mouseX, emvc->mouseY);\n\t}\n}\n\nQEmboxVCKeyboardHandler::QEmboxVCKeyboardHandler() {\n\tint pipefd[2];\n\n\tif (pipe(pipefd) < 0) {\n\t\treturn;\n\t}\n\n\tkeyboardFD = pipefd[0];\n\tinputFD = pipefd[1];\n\n\tfcntl(keyboardFD, F_SETFD, O_NONBLOCK);\n\tfcntl(inputFD, F_SETFD, O_NONBLOCK);\n\n keyboardNotifier = new QSocketNotifier(keyboardFD, QSocketNotifier::Read, this);\n connect(keyboardNotifier, SIGNAL(activated(int)),this, SLOT(readKeyboardData()));\n}\n\nQEmboxVCKeyboardHandler::~QEmboxVCKeyboardHandler() {\n\n}\n\nvoid QEmboxVCKeyboardHandler::storeData(void *data, int datalen) {\n\twrite(inputFD, data, datalen);\n}\n\nvoid QEmboxVCKeyboardHandler::readKeyboardData() {\n\tstruct vc *vc;\n\tstruct input_event ev;\n\n\twhile (read(keyboardFD, &vc, sizeof(struct vc *)) > 0) {\n\t\tQEvent::Type type;\n\t\tunsigned char ascii[4];\n\t\tQt::KeyboardModifiers modifier = 0;\n\n\t\tread(keyboardFD, &ev, sizeof(struct input_event));\n\n\t\ttype = ev.type & KEY_PRESSED ? QEvent::KeyPress : QEvent::KeyRelease;\n\n\t\tif (ev.value & SHIFT_PRESSED) {\n\t\t\tmodifier = Qt::ShiftModifier;\n\t\t} else if (ev.value & ALT_PRESSED) {\n\t\t\tmodifier = Qt::AltModifier;\n\t\t} else if (ev.value & CTRL_PRESSED) {\n\t\t\tmodifier = Qt::ControlModifier;\n\t\t}\n\n\t\tint len = keymap_to_ascii(&ev, ascii);\n\n\/\/\t\tQString key\n\/\/\t\tfor (int i = 0; i < len; i++) {\n\/\/\t\t\tkey += QChar(ascii[i]);\n\/\/\t\t}\n\n\t\tQWindowSystemInterface::handleKeyEvent(0, type, ascii[0], modifier, QString(QChar(ascii[0])));\n\t}\n}\n\nstatic void __handle_input_event(struct vc *vc, struct input_event *ev) {\n\tQEmboxVC *emvc = globalEmboxVC;\n\n\tif (ev->devtype == INPUT_DEV_MOUSE) {\n\t\temvc->mouseHandler->storeData(&vc, sizeof(struct vc *));\n\t\temvc->mouseHandler->storeData(ev, sizeof(struct input_event));\n\t} else if (ev->devtype == INPUT_DEV_KBD) {\n\t\temvc->keyboardHandler->storeData(&vc, sizeof(struct vc *));\n\t\temvc->keyboardHandler->storeData(ev, sizeof(struct input_event));\n\t}\n}\n\nstatic void __scheduleDevisualization(struct vc *vc) {\n\tprintf(\">>__scheduleDevisualization\\n\");\n\t__emboxVCsetMode(vc, 0);\n\n\tmpx_devisualized(vc);\n}\n\nQEmboxVC::QEmboxVC()\n : emboxVCvisualized(0), mouseX(0), mouseY(0)\n{\n\tcursor = new QEmboxCursor();\n\n\tmouseHandler = new QEmboxVCMouseHandler();\n\tkeyboardHandler = new QEmboxVCKeyboardHandler();\n\n\temboxVCcallbacks.visualized = __visualization;\n\temboxVCcallbacks.schedule_devisualization = __scheduleDevisualization;\n\temboxVCcallbacks.handle_input_event = __handle_input_event;\n\n\temboxVC.callbacks = &emboxVCcallbacks;\n\temboxVC.name = \"emboxvc\";\n\n\tmpx_register_vc(&emboxVC);\n}\n\nQEmboxVC::~QEmboxVC() {\n}\n\nQEmboxVCWindowSurface::QEmboxVCWindowSurface(QWidget *window)\n : QWindowSurface(window)\n{\n\tmImage = QImage(QSize(window->width(), window->height()), QImage::Format_RGB16);\n\n\tvc = globalEmboxVC;\n\n\t__emboxVCcollection.append(this);\n}\n\nQEmboxVCWindowSurface::~QEmboxVCWindowSurface()\n{\n\t__emboxVCcollection.removeAll(this);\n}\n\nQPaintDevice *QEmboxVCWindowSurface::paintDevice()\n{\n return &mImage;\n}\n\nvoid QEmboxVCWindowSurface::flush(QWidget *widget, const QRegion ®ion, const QPoint &offset)\n{\n Q_UNUSED(widget);\n Q_UNUSED(region);\n Q_UNUSED(offset);\n\n int i, shift;\n\n int x = widget->pos().x();\n int y = widget->pos().y();\n\n if (!vc->emboxVC.fb || !vc->emboxVCvisualized) {\n \treturn;\n }\n\n int bpp = vc->emboxVC.fb->var.bits_per_pixel \/ 8;\n char *begin = vc->emboxVC.fb->screen_base + (y * vc->emboxVC.fb->var.xres + x) * bpp;\n\n \/* Draw image *\/\n for (i = 0, shift = 0; i < mImage.height(); i++ , shift += vc->emboxVC.fb->var.xres * bpp) {\n \tmemcpy(begin + shift, (const void *)mImage.constScanLine(i), mImage.bytesPerLine());\n }\n\n \/* Reset cursor on new image and redraw *\/\n vc->cursor->emboxCursorReset(vc->emboxVC.fb);\n vc->cursor->emboxCursorRedraw(vc->emboxVC.fb, vc->mouseX, vc->mouseY);\n}\n\nvoid QEmboxVCWindowSurface::resize(const QSize &size)\n{\n \/\/qDebug() << \"QMinimalWindowSurface::setGeometry:\" << (long)this << rect;\n \/\/QWindowSurface::resize(size);\n \/\/QImage::Format format = QApplicationPrivate::platformIntegration()->screens().first()->format();\n \/\/if (mImage.size() != size)\n \/\/[> XXX <]\n \/\/mImage = QImage(size, QImage::Format_RGB16);\n}\n\nQEmboxVCPlatformWindow::QEmboxVCPlatformWindow(QWidget *widget)\n: QPlatformWindow(widget)\n{\n}\n\nQEmboxVCPlatformWindow::~QEmboxVCPlatformWindow()\n{\n}\n\nWId QEmboxVCPlatformWindow::winId() const {\n\treturn WId(1);\n}\n\nvoid QEmboxVCPlatformWindow::setParent(const QPlatformWindow *window) {\n\t\/\/if (widget() && window->widget()) {\n\t\/\/\twidget()->setParent(window->widget());\n\t\/\/}\n}\n\nQT_END_NAMESPACE\n<commit_msg>qt: support for control characters handling<commit_after>#include \"emboxvcwindowsurface.h\"\n#include <QtCore\/qdebug.h>\n#include <QtGui\/private\/qapplication_p.h>\n#include <QWindowSystemInterface>\n#include <QMouseEvent>\n\nQT_BEGIN_NAMESPACE\n\n\/* From VNC *\/\nstatic const struct {\n int keysym;\n int keycode;\n} emboxKeyMap[] = {\n { 0x08, Qt::Key_Backspace },\n { 0x09, Qt::Key_Tab },\n { 0x0d, Qt::Key_Return },\n { 0x1b, Qt::Key_Escape },\n { 0x63, Qt::Key_Insert },\n { 0xff, Qt::Key_Delete },\n { 0x50, Qt::Key_Home },\n { 0x57, Qt::Key_End },\n { 0x55, Qt::Key_PageUp },\n { 0x56, Qt::Key_PageDown },\n { 0x51, Qt::Key_Left },\n { 0x52, Qt::Key_Up },\n { 0x53, Qt::Key_Right },\n { 0x54, Qt::Key_Down },\n { 0xbe, Qt::Key_F1 },\n { 0xbf, Qt::Key_F2 },\n { 0xc0, Qt::Key_F3 },\n { 0xc1, Qt::Key_F4 },\n { 0xc2, Qt::Key_F5 },\n { 0xc3, Qt::Key_F6 },\n { 0xc4, Qt::Key_F7 },\n { 0xc5, Qt::Key_F8 },\n { 0xc6, Qt::Key_F9 },\n { 0xc7, Qt::Key_F10 },\n { 0xc8, Qt::Key_F11 },\n { 0xc9, Qt::Key_F12 },\n { 0xe1, Qt::Key_Shift },\n { 0xe2, Qt::Key_Shift },\n { 0xe3, Qt::Key_Control },\n { 0xe4, Qt::Key_Control },\n { 0xe7, Qt::Key_Meta },\n { 0xe8, Qt::Key_Meta },\n { 0xe9, Qt::Key_Alt },\n { 0xea, Qt::Key_Alt },\n { 0, 0 }\n};\n\nstatic QList<QEmboxVCWindowSurface*> __emboxVCcollection;\nextern QEmboxVC *globalEmboxVC;\n\n\/\/static QEmboxVCWindowSurface * __emboxVC(struct vc *vc) {\n\/\/\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\/\/\t\tQEmboxVCWindowSurface *emvc = __emboxVCcollection.at(i);\n\/\/\t\tif (&(emvc->emboxVC) == vc) {\n\/\/\t\t\treturn emvc;\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\treturn NULL;\n\/\/}\n\nstatic void flushAll() {\n\tQRegion region;\n\tQPoint point;\n\n\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\t\t__emboxVCcollection.at(i)->flush(0, region, point);\n\t}\n}\n\nstatic int visibleWidgetsCount() {\n\tint cnt = 0;\n\tfor (int i = 0; i < __emboxVCcollection.size(); ++i) {\n\t\tcnt += __emboxVCcollection.at(i)->window()->isVisible() ? 1 : 0;\n\t}\n\treturn cnt;\n}\n\nstatic void __emboxVCsetMode(struct vc *vc, int mode) {\n\tglobalEmboxVC->emboxVCvisualized = mode;\n}\n\nstatic void __visualization(struct vc *vc, struct fb_info *info) {\n\tQ_UNUSED(info);\n\n\tQEmboxVCWindowSurface *surf;\n\n\t__emboxVCsetMode(vc, 1);\n\t\/\/surf = __emboxVC(vc);\n\t\/\/surf->flush(NULL, region, point);\n\tflushAll();\n\n\tforeach (QWidget *widget, QApplication::allWidgets()) {\n\t\twidget->update();\n\t}\n}\n\nQEmboxVCMouseHandler::QEmboxVCMouseHandler() {\n\tint pipefd[2];\n\n\tif (pipe(pipefd) < 0) {\n\t\treturn;\n\t}\n\n\tmouseFD = pipefd[0];\n\tinputFD = pipefd[1];\n\n\tfcntl(mouseFD, F_SETFD, O_NONBLOCK);\n\tfcntl(inputFD, F_SETFD, O_NONBLOCK);\n\n mouseNotifier = new QSocketNotifier(mouseFD, QSocketNotifier::Read, this);\n connect(mouseNotifier, SIGNAL(activated(int)),this, SLOT(readMouseData()));\n}\n\nQEmboxVCMouseHandler::~QEmboxVCMouseHandler() {\n\n}\n\nvoid QEmboxVCMouseHandler::storeData(void *data, int datalen) {\n\twrite(inputFD, data, datalen);\n}\n\nvoid QEmboxVCMouseHandler::readMouseData() {\n\tstruct vc *vc;\n\tstruct input_event ev;\n\tshort x, y;\n\tint bstate;\n\tQEmboxVC *emvc;\n\n\twhile (read(mouseFD, &vc, sizeof(struct vc *)) > 0) {\n\n\t\tread(mouseFD, &ev, sizeof(struct input_event));\n\n\t\temvc = globalEmboxVC;\n\n\t\tbstate = Qt::NoButton;\n\n\t\tif (ev.type & 1) {\n\t\t\tbstate = Qt::LeftButton;\n\t\t} else if (ev.type & 2) {\n\t\t\tbstate = Qt::RightButton;\n\t\t}\n\n\t\tx = ev.value >> 16;\n\t\ty = ev.value & 0xffff;\n\n\t\temvc->mouseX += x;\n\t\temvc->mouseY += -y;\n\n\t\tint xres = emvc->emboxVC.fb->var.xres;\n\t\tint yres = emvc->emboxVC.fb->var.yres;\n\n\t\temvc->mouseX = emvc->mouseX > 0 ? emvc->mouseX : 0;\n\t\temvc->mouseY = emvc->mouseY > 0 ? emvc->mouseY : 0;\n\n\t\temvc->mouseX = emvc->mouseX > xres ? xres : emvc->mouseX;\n\t\temvc->mouseY = emvc->mouseY > yres ? yres : emvc->mouseY;\n\n\t\tQWindowSystemInterface::handleMouseEvent(0, QPoint(emvc->mouseX, emvc->mouseY),\n\t\t\t\tQPoint(emvc->mouseX, emvc->mouseY), Qt::MouseButtons(bstate));\n\n\t\tif (!emvc->emboxVC.fb || !emvc->emboxVCvisualized) {\n\t\t\treturn;\n\t\t}\n\n\t\temvc->cursor->emboxCursorRedraw(emvc->emboxVC.fb, emvc->mouseX, emvc->mouseY);\n\t}\n}\n\nQEmboxVCKeyboardHandler::QEmboxVCKeyboardHandler() {\n\tint pipefd[2];\n\n\tif (pipe(pipefd) < 0) {\n\t\treturn;\n\t}\n\n\tkeyboardFD = pipefd[0];\n\tinputFD = pipefd[1];\n\n\tfcntl(keyboardFD, F_SETFD, O_NONBLOCK);\n\tfcntl(inputFD, F_SETFD, O_NONBLOCK);\n\n keyboardNotifier = new QSocketNotifier(keyboardFD, QSocketNotifier::Read, this);\n connect(keyboardNotifier, SIGNAL(activated(int)),this, SLOT(readKeyboardData()));\n}\n\nQEmboxVCKeyboardHandler::~QEmboxVCKeyboardHandler() {\n\n}\n\nvoid QEmboxVCKeyboardHandler::storeData(void *data, int datalen) {\n\twrite(inputFD, data, datalen);\n}\n\nvoid QEmboxVCKeyboardHandler::readKeyboardData() {\n\tstruct vc *vc;\n\tstruct input_event ev;\n\n\twhile (read(keyboardFD, &vc, sizeof(struct vc *)) > 0) {\n\t\tQEvent::Type type;\n\t\tunsigned char ascii[4];\n\t\tint key;\n\t\tint i = 0;\n\t\tQt::KeyboardModifiers modifier = 0;\n\n\t\tread(keyboardFD, &ev, sizeof(struct input_event));\n\n\t\ttype = ev.type & KEY_PRESSED ? QEvent::KeyPress : QEvent::KeyRelease;\n\n\t\tif (ev.value & SHIFT_PRESSED) {\n\t\t\tmodifier = Qt::ShiftModifier;\n\t\t} else if (ev.value & ALT_PRESSED) {\n\t\t\tmodifier = Qt::AltModifier;\n\t\t} else if (ev.value & CTRL_PRESSED) {\n\t\t\tmodifier = Qt::ControlModifier;\n\t\t}\n\n\t\tint len = keymap_to_ascii(&ev, ascii);\n\n\t\twhile (emboxKeyMap[i].keysym != 0) {\n\t\t\tif (emboxKeyMap[i].keysym == ascii[i]) {\n\t\t\t\tkey = emboxKeyMap[i].keycode;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\n\t\tQWindowSystemInterface::handleKeyEvent(0, type, key, modifier, QString(QChar(ascii[0])));\n\t}\n}\n\nstatic void __handle_input_event(struct vc *vc, struct input_event *ev) {\n\tQEmboxVC *emvc = globalEmboxVC;\n\n\tif (ev->devtype == INPUT_DEV_MOUSE) {\n\t\temvc->mouseHandler->storeData(&vc, sizeof(struct vc *));\n\t\temvc->mouseHandler->storeData(ev, sizeof(struct input_event));\n\t} else if (ev->devtype == INPUT_DEV_KBD) {\n\t\temvc->keyboardHandler->storeData(&vc, sizeof(struct vc *));\n\t\temvc->keyboardHandler->storeData(ev, sizeof(struct input_event));\n\t}\n}\n\nstatic void __scheduleDevisualization(struct vc *vc) {\n\tprintf(\">>__scheduleDevisualization\\n\");\n\t__emboxVCsetMode(vc, 0);\n\n\tmpx_devisualized(vc);\n}\n\nQEmboxVC::QEmboxVC()\n : emboxVCvisualized(0), mouseX(0), mouseY(0)\n{\n\tcursor = new QEmboxCursor();\n\n\tmouseHandler = new QEmboxVCMouseHandler();\n\tkeyboardHandler = new QEmboxVCKeyboardHandler();\n\n\temboxVCcallbacks.visualized = __visualization;\n\temboxVCcallbacks.schedule_devisualization = __scheduleDevisualization;\n\temboxVCcallbacks.handle_input_event = __handle_input_event;\n\n\temboxVC.callbacks = &emboxVCcallbacks;\n\temboxVC.name = \"emboxvc\";\n\n\tmpx_register_vc(&emboxVC);\n}\n\nQEmboxVC::~QEmboxVC() {\n}\n\nQEmboxVCWindowSurface::QEmboxVCWindowSurface(QWidget *window)\n : QWindowSurface(window)\n{\n\tmImage = QImage(QSize(window->width(), window->height()), QImage::Format_RGB16);\n\n\tvc = globalEmboxVC;\n\n\t__emboxVCcollection.append(this);\n}\n\nQEmboxVCWindowSurface::~QEmboxVCWindowSurface()\n{\n\t__emboxVCcollection.removeAll(this);\n}\n\nQPaintDevice *QEmboxVCWindowSurface::paintDevice()\n{\n return &mImage;\n}\n\nvoid QEmboxVCWindowSurface::flush(QWidget *widget, const QRegion ®ion, const QPoint &offset)\n{\n Q_UNUSED(widget);\n Q_UNUSED(region);\n Q_UNUSED(offset);\n\n int i, shift;\n\n int x = widget->pos().x();\n int y = widget->pos().y();\n\n if (!vc->emboxVC.fb || !vc->emboxVCvisualized) {\n \treturn;\n }\n\n int bpp = vc->emboxVC.fb->var.bits_per_pixel \/ 8;\n char *begin = vc->emboxVC.fb->screen_base + (y * vc->emboxVC.fb->var.xres + x) * bpp;\n\n \/* Draw image *\/\n for (i = 0, shift = 0; i < mImage.height(); i++ , shift += vc->emboxVC.fb->var.xres * bpp) {\n \tmemcpy(begin + shift, (const void *)mImage.constScanLine(i), mImage.bytesPerLine());\n }\n\n \/* Reset cursor on new image and redraw *\/\n vc->cursor->emboxCursorReset(vc->emboxVC.fb);\n vc->cursor->emboxCursorRedraw(vc->emboxVC.fb, vc->mouseX, vc->mouseY);\n}\n\nvoid QEmboxVCWindowSurface::resize(const QSize &size)\n{\n \/\/qDebug() << \"QMinimalWindowSurface::setGeometry:\" << (long)this << rect;\n \/\/QWindowSurface::resize(size);\n \/\/QImage::Format format = QApplicationPrivate::platformIntegration()->screens().first()->format();\n \/\/if (mImage.size() != size)\n \/\/[> XXX <]\n \/\/mImage = QImage(size, QImage::Format_RGB16);\n}\n\nQEmboxVCPlatformWindow::QEmboxVCPlatformWindow(QWidget *widget)\n: QPlatformWindow(widget)\n{\n}\n\nQEmboxVCPlatformWindow::~QEmboxVCPlatformWindow()\n{\n}\n\nWId QEmboxVCPlatformWindow::winId() const {\n\treturn WId(1);\n}\n\nvoid QEmboxVCPlatformWindow::setParent(const QPlatformWindow *window) {\n\t\/\/if (widget() && window->widget()) {\n\t\/\/\twidget()->setParent(window->widget());\n\t\/\/}\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/\/ Author: morlovich@google.com (Maksim Orlovich)\n\n\/\/ Unit tests for out-of-memory handling in Image class\n\n#include \"net\/instaweb\/rewriter\/public\/image.h\"\n\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include \"net\/instaweb\/rewriter\/image_types.pb.h\"\n#include \"net\/instaweb\/rewriter\/public\/image_test_base.h\"\n#include \"net\/instaweb\/util\/public\/dynamic_annotations.h\" \/\/ RunningOnValgrind\n#include \"net\/instaweb\/util\/public\/gtest.h\"\n#include \"net\/instaweb\/util\/public\/mock_timer.h\"\n#include \"net\/instaweb\/util\/public\/scoped_ptr.h\"\n#include \"net\/instaweb\/util\/public\/string.h\"\n#include \"pagespeed\/kernel\/base\/mock_message_handler.h\"\n\nnamespace net_instaweb {\nnamespace {\n\nconst char kLargeJpeg[] = \"Large.jpg\";\n\nclass ImageOomTest : public ImageTestBase {\n public:\n virtual void SetUp() {\n ImageTestBase::SetUp();\n\n \/\/ All of these tests need to be disabled under valgrind since\n \/\/ valgrind and setrlimit don't get along\n if (!RunningOnValgrind()) {\n getrlimit(RLIMIT_AS, &old_mem_limit_);\n\n \/\/ Limit ourselves to about 100 million bytes of memory --- not enough\n \/\/ to fit in the 10000x10000 image (which has 100 million pixels).\n rlimit new_mem_limit = old_mem_limit_;\n new_mem_limit.rlim_cur = 100000000;\n setrlimit(RLIMIT_AS, &new_mem_limit);\n }\n }\n\n virtual void TearDown() {\n if (!RunningOnValgrind()) {\n \/\/ Restore previous rlimit\n setrlimit(RLIMIT_AS, &old_mem_limit_);\n }\n ImageTestBase::TearDown();\n }\n\n private:\n rlimit old_mem_limit_;\n};\n\nTEST_F(ImageOomTest, BlankImageTooLarge) {\n if (RunningOnValgrind()) {\n return;\n }\n\n#ifndef NDEBUG\n return;\n#endif\n\n Image::CompressionOptions* options = new Image::CompressionOptions();\n \/\/ Make sure creating gigantic image fails cleanly.\n ImagePtr giant(BlankImageWithOptions(10000000, 10000, IMAGE_PNG,\n GTestTempDir(), &timer_,\n &message_handler_, options));\n EXPECT_EQ(NULL, giant.get());\n}\n\nTEST_F(ImageOomTest, BlankImageNotTooLarge) {\n if (RunningOnValgrind()) {\n return;\n }\n\n#ifndef NDEBUG\n return;\n#endif\n\n Image::CompressionOptions* options = new Image::CompressionOptions();\n ImagePtr not_too_large(BlankImageWithOptions(4000, 4000, IMAGE_PNG,\n GTestTempDir(), &timer_,\n &message_handler_, options));\n \/\/ Image of this size can be created.\n EXPECT_NE(static_cast<net_instaweb::Image*>(NULL), not_too_large.get());\n}\n\nTEST_F(ImageOomTest, LoadLargeJpeg) {\n if (RunningOnValgrind()) {\n return;\n }\n\n GoogleString buf;\n bool not_progressive = false;\n ImagePtr giant(ReadImageFromFile(IMAGE_JPEG, kLargeJpeg, &buf,\n not_progressive));\n \/\/ We do not rewrite JPEG images of such large size, so the input and output\n \/\/ images have the same length.\n EXPECT_EQ(buf.length(), giant->output_size());\n}\n\nTEST_F(ImageOomTest, LoadLargePng) {\n if (RunningOnValgrind()) {\n return;\n }\n\n GoogleString buf;\n bool not_progressive = true;\n ImagePtr image(ReadImageFromFile(IMAGE_PNG, kLarge, &buf,\n not_progressive));\n \/\/ PNG images needs less memory to rewrite than JPEG. After rewriting\n \/\/ this image shrinks.\n EXPECT_GT(buf.length(), image->output_size());\n}\n\n} \/\/ namespace\n} \/\/ namespace net_instaweb\n<commit_msg>Backport change r4228 to branch 32.<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/\/ Author: morlovich@google.com (Maksim Orlovich)\n\n\/\/ Unit tests for out-of-memory handling in Image class\n\n#include \"net\/instaweb\/rewriter\/public\/image.h\"\n\n#include <sys\/time.h>\n#include <sys\/resource.h>\n\n#include \"net\/instaweb\/rewriter\/image_types.pb.h\"\n#include \"net\/instaweb\/rewriter\/public\/image_test_base.h\"\n#include \"net\/instaweb\/util\/public\/dynamic_annotations.h\" \/\/ RunningOnValgrind\n#include \"net\/instaweb\/util\/public\/gtest.h\"\n#include \"net\/instaweb\/util\/public\/mock_timer.h\"\n#include \"net\/instaweb\/util\/public\/scoped_ptr.h\"\n#include \"net\/instaweb\/util\/public\/string.h\"\n#include \"pagespeed\/kernel\/base\/mock_message_handler.h\"\n\nnamespace net_instaweb {\nnamespace {\n\nconst char kLargeJpeg[] = \"Large.jpg\";\n\nclass ImageOomTest : public ImageTestBase {\n public:\n virtual void SetUp() {\n ImageTestBase::SetUp();\n\n \/\/ All of these tests need to be disabled under valgrind since\n \/\/ valgrind and setrlimit don't get along\n if (!RunningOnValgrind()) {\n getrlimit(RLIMIT_AS, &old_mem_limit_);\n\n \/\/ Limit ourselves to about 100 million bytes of memory --- not enough\n \/\/ to fit in the 10000x10000 image (which has 100 million pixels).\n rlimit new_mem_limit = old_mem_limit_;\n new_mem_limit.rlim_cur = 100000000;\n setrlimit(RLIMIT_AS, &new_mem_limit);\n }\n }\n\n virtual void TearDown() {\n if (!RunningOnValgrind()) {\n \/\/ Restore previous rlimit\n setrlimit(RLIMIT_AS, &old_mem_limit_);\n }\n ImageTestBase::TearDown();\n }\n\n private:\n rlimit old_mem_limit_;\n};\n\nTEST_F(ImageOomTest, BlankImageTooLarge) {\n if (RunningOnValgrind()) {\n return;\n }\n\n#ifndef NDEBUG\n return;\n#endif\n\n Image::CompressionOptions* options = new Image::CompressionOptions();\n \/\/ Make sure creating gigantic image fails cleanly.\n ImagePtr giant(BlankImageWithOptions(10000000, 10000, IMAGE_PNG,\n GTestTempDir(), &timer_,\n &message_handler_, options));\n EXPECT_EQ(NULL, giant.get());\n}\n\nTEST_F(ImageOomTest, BlankImageNotTooLarge) {\n if (RunningOnValgrind()) {\n return;\n }\n\n#ifndef NDEBUG\n return;\n#endif\n\n Image::CompressionOptions* options = new Image::CompressionOptions();\n ImagePtr not_too_large(BlankImageWithOptions(4096, 2048, IMAGE_PNG,\n GTestTempDir(), &timer_,\n &message_handler_, options));\n \/\/ Image of this size can be created.\n EXPECT_NE(static_cast<net_instaweb::Image*>(NULL), not_too_large.get());\n}\n\nTEST_F(ImageOomTest, LoadLargeJpeg) {\n if (RunningOnValgrind()) {\n return;\n }\n\n GoogleString buf;\n bool not_progressive = false;\n ImagePtr giant(ReadImageFromFile(IMAGE_JPEG, kLargeJpeg, &buf,\n not_progressive));\n \/\/ We do not rewrite JPEG images of such large size, so the input and output\n \/\/ images have the same length.\n EXPECT_EQ(buf.length(), giant->output_size());\n}\n\nTEST_F(ImageOomTest, LoadLargePng) {\n if (RunningOnValgrind()) {\n return;\n }\n\n GoogleString buf;\n bool not_progressive = true;\n ImagePtr image(ReadImageFromFile(IMAGE_PNG, kLarge, &buf,\n not_progressive));\n \/\/ PNG images needs less memory to rewrite than JPEG. After rewriting\n \/\/ this image shrinks.\n EXPECT_GT(buf.length(), image->output_size());\n}\n\n} \/\/ namespace\n} \/\/ namespace net_instaweb\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\n#include \"op\/conv.hpp\"\n\n#include \"ngraph\/op\/add.hpp\"\n#include \"ngraph\/op\/broadcast.hpp\"\n#include \"ngraph\/op\/concat.hpp\"\n#include \"ngraph\/op\/convolution.hpp\"\n#include \"ngraph\/op\/slice.hpp\"\n\n#include \"ngraph\/frontend\/onnx_import\/exceptions.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/op\/conv.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/utils\/broadcasting.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/utils\/convpool.hpp\"\n\nnamespace ngraph\n{\n namespace onnx_import\n {\n namespace op\n {\n namespace\n {\n std::shared_ptr<ngraph::op::Op>\n make_ng_convolution(const std::shared_ptr<ngraph::Node>& data,\n const std::shared_ptr<ngraph::Node>& filters,\n const ngraph::Strides& strides,\n const ngraph::Strides& dilations,\n const ngraph::CoordinateDiff& padding_below,\n const ngraph::CoordinateDiff& padding_above,\n int groups)\n {\n if (groups > 1)\n {\n \/\/ Split one convolution op to N ops where N is the number of groups\n \/\/ and concat results after computation.\n \/\/ reference: https:\/\/github.com\/NervanaSystems\/ngraph-mxnet\/blob\/fdd692\/src\/ngraph\/ngraph_emitter.cc#L822-L856\n std::size_t n_data_channels{data->get_shape().at(1)};\n std::size_t n_filters_channels{filters->get_shape().at(0)};\n \/\/ TODO: ensure n_data_channels % groups = 0\n std::size_t data_group_size{n_data_channels \/ groups};\n std::size_t filters_group_size{n_filters_channels \/ groups};\n NodeVector convolution_nodes;\n\n \/\/ initial bounds for splice\n std::vector<std::size_t> data_lower_bounds(data->get_shape().size());\n std::vector<std::size_t> data_upper_bounds{data->get_shape()};\n std::vector<std::size_t> filters_lower_bounds(filters->get_shape().size());\n std::vector<std::size_t> filters_upper_bounds{filters->get_shape()};\n\n for (std::size_t group{0}; group < groups; ++group)\n {\n \/\/ slice data\n data_lower_bounds[1] = group * data_group_size;\n data_upper_bounds[1] = (group + 1) * data_group_size;\n auto sliced_data = std::make_shared<ngraph::op::Slice>(\n data, data_lower_bounds, data_upper_bounds);\n \/\/ slice filters\n filters_lower_bounds[0] = group * filters_group_size;\n filters_upper_bounds[0] = (group + 1) * filters_group_size;\n auto sliced_filters = std::make_shared<ngraph::op::Slice>(\n filters, filters_lower_bounds, filters_upper_bounds);\n\n convolution_nodes.push_back(\n std::make_shared<ngraph::op::Convolution>(sliced_data,\n sliced_filters,\n strides,\n dilations,\n padding_below,\n padding_above));\n }\n std::size_t concatenation_axis = 1;\n return std::make_shared<ngraph::op::Concat>(convolution_nodes,\n concatenation_axis);\n }\n else\n {\n return std::make_shared<ngraph::op::Convolution>(\n data, filters, strides, dilations, padding_below, padding_above);\n }\n }\n\n } \/\/ namespace\n\n NodeVector conv(const Node& node)\n {\n const NodeVector& inputs = node.get_ng_inputs();\n auto data = inputs.at(0);\n auto filters = inputs.at(1);\n\n int groups{node.get_attribute_value<int>(\"group\", 1)};\n\n \/\/ TODO: update to ASSERTION CHECK\n if (groups < 0 || groups > data->get_shape().at(1) ||\n groups > filters->get_shape().at(0))\n {\n throw error::parameter::Value{\"Conv\",\n node.get_name(),\n \"incorrect value of 'group' attribute: \" +\n std::to_string(groups)};\n }\n\n auto strides = convpool::get_strides(node);\n auto dilations = convpool::get_dilations(node);\n auto paddings = convpool::get_pads(node);\n const auto& padding_below = paddings.first;\n const auto& padding_above = paddings.second;\n\n auto conv_node = make_ng_convolution(\n data, filters, strides, dilations, padding_below, padding_above, groups);\n\n \/\/ no bias param\n if (inputs.size() < 3)\n {\n return {conv_node};\n }\n\n auto bias = inputs.at(2);\n const Shape& new_shape = conv_node->get_shape();\n\n auto broadcasted_bias = std::make_shared<ngraph::op::Broadcast>(\n bias, new_shape, calculate_broadcast_axes(new_shape, bias->get_shape(), 1));\n return {std::make_shared<ngraph::op::Add>(conv_node, broadcasted_bias)};\n }\n\n } \/\/ namespace op\n\n } \/\/ namespace onnx_import\n\n} \/\/ namespace ngraph\n<commit_msg>Fix for Conv op (#1556)<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\n#include \"op\/conv.hpp\"\n\n#include \"ngraph\/op\/add.hpp\"\n#include \"ngraph\/op\/broadcast.hpp\"\n#include \"ngraph\/op\/concat.hpp\"\n#include \"ngraph\/op\/convolution.hpp\"\n#include \"ngraph\/op\/slice.hpp\"\n\n#include \"ngraph\/frontend\/onnx_import\/exceptions.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/op\/conv.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/utils\/broadcasting.hpp\"\n#include \"ngraph\/frontend\/onnx_import\/utils\/convpool.hpp\"\n\nnamespace ngraph\n{\n namespace onnx_import\n {\n namespace op\n {\n namespace\n {\n std::shared_ptr<ngraph::op::Op>\n make_ng_convolution(const std::shared_ptr<ngraph::Node>& data,\n const std::shared_ptr<ngraph::Node>& filters,\n const ngraph::Strides& strides,\n const ngraph::Strides& dilations,\n const ngraph::CoordinateDiff& padding_below,\n const ngraph::CoordinateDiff& padding_above,\n int groups)\n {\n if (groups > 1)\n {\n \/\/ Split one convolution op to N ops where N is the number of groups\n \/\/ and concat results after computation.\n \/\/ reference: https:\/\/github.com\/NervanaSystems\/ngraph-mxnet\/blob\/fdd692\/src\/ngraph\/ngraph_emitter.cc#L822-L856\n std::size_t n_data_channels{data->get_shape().at(1)};\n std::size_t n_filters_channels{filters->get_shape().at(0)};\n \/\/ TODO: ensure n_data_channels % groups = 0\n std::size_t data_group_size{n_data_channels \/ groups};\n std::size_t filters_group_size{n_filters_channels \/ groups};\n NodeVector convolution_nodes;\n\n \/\/ initial bounds for splice\n std::vector<std::size_t> data_lower_bounds(data->get_shape().size());\n std::vector<std::size_t> data_upper_bounds{data->get_shape()};\n std::vector<std::size_t> filters_lower_bounds(filters->get_shape().size());\n std::vector<std::size_t> filters_upper_bounds{filters->get_shape()};\n\n for (std::size_t group{0}; group < groups; ++group)\n {\n \/\/ slice data\n data_lower_bounds[1] = group * data_group_size;\n data_upper_bounds[1] = (group + 1) * data_group_size;\n auto sliced_data = std::make_shared<ngraph::op::Slice>(\n data, data_lower_bounds, data_upper_bounds);\n \/\/ slice filters\n filters_lower_bounds[0] = group * filters_group_size;\n filters_upper_bounds[0] = (group + 1) * filters_group_size;\n auto sliced_filters = std::make_shared<ngraph::op::Slice>(\n filters, filters_lower_bounds, filters_upper_bounds);\n\n convolution_nodes.push_back(\n std::make_shared<ngraph::op::Convolution>(sliced_data,\n sliced_filters,\n strides,\n dilations,\n padding_below,\n padding_above));\n }\n std::size_t concatenation_axis = 1;\n return std::make_shared<ngraph::op::Concat>(convolution_nodes,\n concatenation_axis);\n }\n else\n {\n return std::make_shared<ngraph::op::Convolution>(\n data, filters, strides, dilations, padding_below, padding_above);\n }\n }\n\n } \/\/ namespace\n\n NodeVector conv(const Node& node)\n {\n const NodeVector& inputs = node.get_ng_inputs();\n auto data = inputs.at(0);\n auto filters = inputs.at(1);\n\n int64_t groups{node.get_attribute_value<int64_t>(\"group\", 1)};\n\n \/\/ TODO: update to ASSERTION CHECK\n if (groups < 0 || groups > data->get_shape().at(1) ||\n groups > filters->get_shape().at(0))\n {\n throw error::parameter::Value{\"Conv\",\n node.get_name(),\n \"incorrect value of 'group' attribute: \" +\n std::to_string(groups)};\n }\n\n auto strides = convpool::get_strides(node);\n auto dilations = convpool::get_dilations(node);\n auto paddings = convpool::get_pads(node);\n const auto& padding_below = paddings.first;\n const auto& padding_above = paddings.second;\n\n auto conv_node = make_ng_convolution(\n data, filters, strides, dilations, padding_below, padding_above, groups);\n\n \/\/ no bias param\n if (inputs.size() < 3)\n {\n return {conv_node};\n }\n\n auto bias = inputs.at(2);\n const Shape& new_shape = conv_node->get_shape();\n\n auto broadcasted_bias = std::make_shared<ngraph::op::Broadcast>(\n bias, new_shape, calculate_broadcast_axes(new_shape, bias->get_shape(), 1));\n return {std::make_shared<ngraph::op::Add>(conv_node, broadcasted_bias)};\n }\n\n } \/\/ namespace op\n\n } \/\/ namespace onnx_import\n\n} \/\/ namespace ngraph\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* Copyright 2018 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include \"ngraph\/runtime\/cpu\/kernel\/max_pool.hpp\"\n#include \"ngraph\/op\/max_pool.hpp\"\n#include \"ngraph\/runtime\/cpu\/cpu_builder.hpp\"\n#include \"ngraph\/runtime\/cpu\/mkldnn_invoke.hpp\"\n#include \"ngraph\/runtime\/cpu\/mkldnn_utils.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n template <>\n void Builder::BUILDER_DECL(ngraph::op::MaxPool)\n {\n auto max_pool = static_cast<const ngraph::op::MaxPool*>(node);\n\n auto& functors = external_function->get_functors();\n auto& tensor_data = external_function->get_tensor_data();\n\n auto arg0_shape = args[0].get_shape();\n auto out_shape = out[0].get_shape();\n\n auto& arg0_tensor = tensor_data[args[0].get_name()];\n auto& out_tensor = tensor_data[out[0].get_name()];\n\n auto window_shape = max_pool->get_window_shape();\n auto window_movement_strides = max_pool->get_window_movement_strides();\n auto padding_below = max_pool->get_padding_below();\n auto padding_above = max_pool->get_padding_above();\n\n if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))\n {\n auto& mkldnn_emitter = external_function->get_mkldnn_emitter();\n auto input_desc = mkldnn_emitter->build_memory_descriptor(\n args[0], runtime::cpu::mkldnn_utils::get_input_mkldnn_format(node, 0));\n auto result_desc = mkldnn_emitter->build_memory_descriptor(\n out[0], runtime::cpu::mkldnn_utils::get_output_mkldnn_format(node, 0));\n\n size_t max_pool_index =\n mkldnn_emitter->build_pooling_forward(mkldnn::algorithm::pooling_max,\n input_desc,\n result_desc,\n window_movement_strides,\n window_shape,\n padding_below,\n padding_above);\n\n auto& deps = mkldnn_emitter->get_primitive_deps(max_pool_index);\n\n auto functor = [&, max_pool_index](CPURuntimeContext* ctx) {\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[0], arg0_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[1], out_tensor);\n cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, max_pool_index);\n };\n functors.emplace_back(functor);\n }\n else\n {\n std::function<decltype(runtime::cpu::kernel::max_pool<float>)> kernel;\n\n SELECT_KERNEL(\n kernel, out[0].get_element_type(), runtime::cpu::kernel::max_pool);\n\n auto functor = [&,\n kernel,\n arg0_shape,\n out_shape,\n window_shape,\n window_movement_strides,\n padding_below,\n padding_above](CPURuntimeContext* ctx) {\n kernel(arg0_tensor,\n out_tensor,\n arg0_shape,\n out_shape,\n window_shape,\n window_movement_strides,\n padding_below,\n padding_above);\n };\n functors.emplace_back(functor);\n }\n }\n\n REGISTER_OP_BUILDER(MaxPool);\n }\n }\n}\n<commit_msg>DEX MaxPoolWithIndices (#1299)<commit_after>\/*******************************************************************************\n* Copyright 2018 Intel Corporation\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*******************************************************************************\/\n\n#include \"ngraph\/runtime\/cpu\/kernel\/max_pool.hpp\"\n#include \"ngraph\/op\/max_pool.hpp\"\n#include \"ngraph\/runtime\/cpu\/cpu_builder.hpp\"\n#include \"ngraph\/runtime\/cpu\/mkldnn_invoke.hpp\"\n#include \"ngraph\/runtime\/cpu\/mkldnn_utils.hpp\"\n#include \"ngraph\/runtime\/cpu\/op\/max_pool_with_indices.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n template <>\n void Builder::BUILDER_DECL(ngraph::op::MaxPool)\n {\n auto max_pool = static_cast<const ngraph::op::MaxPool*>(node);\n\n auto& functors = external_function->get_functors();\n auto& tensor_data = external_function->get_tensor_data();\n\n auto arg0_shape = args[0].get_shape();\n auto out_shape = out[0].get_shape();\n\n auto& arg0_tensor = tensor_data[args[0].get_name()];\n auto& out_tensor = tensor_data[out[0].get_name()];\n\n auto window_shape = max_pool->get_window_shape();\n auto window_movement_strides = max_pool->get_window_movement_strides();\n auto padding_below = max_pool->get_padding_below();\n auto padding_above = max_pool->get_padding_above();\n\n if (runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))\n {\n auto& mkldnn_emitter = external_function->get_mkldnn_emitter();\n auto input_desc = mkldnn_emitter->build_memory_descriptor(\n args[0], runtime::cpu::mkldnn_utils::get_input_mkldnn_format(node, 0));\n auto result_desc = mkldnn_emitter->build_memory_descriptor(\n out[0], runtime::cpu::mkldnn_utils::get_output_mkldnn_format(node, 0));\n\n size_t max_pool_index =\n mkldnn_emitter->build_pooling_forward(mkldnn::algorithm::pooling_max,\n input_desc,\n result_desc,\n window_movement_strides,\n window_shape,\n padding_below,\n padding_above);\n\n auto& deps = mkldnn_emitter->get_primitive_deps(max_pool_index);\n\n auto functor = [&, max_pool_index](CPURuntimeContext* ctx) {\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[0], arg0_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[1], out_tensor);\n cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, max_pool_index);\n };\n functors.emplace_back(functor);\n }\n else\n {\n std::function<decltype(runtime::cpu::kernel::max_pool<float>)> kernel;\n\n SELECT_KERNEL(\n kernel, out[0].get_element_type(), runtime::cpu::kernel::max_pool);\n\n auto functor = [&,\n kernel,\n arg0_shape,\n out_shape,\n window_shape,\n window_movement_strides,\n padding_below,\n padding_above](CPURuntimeContext* ctx) {\n kernel(arg0_tensor,\n out_tensor,\n arg0_shape,\n out_shape,\n window_shape,\n window_movement_strides,\n padding_below,\n padding_above);\n };\n functors.emplace_back(functor);\n }\n }\n\n template <>\n void Builder::BUILDER_DECL(ngraph::op::MaxPoolWithIndices)\n {\n if (!runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))\n {\n throw ngraph_error(\"MaxPoolWithIndices isn't supported\");\n }\n\n auto max_pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);\n\n auto& functors = external_function->get_functors();\n auto& tensor_data = external_function->get_tensor_data();\n\n auto& arg0_tensor = tensor_data[args[0].get_name()];\n auto& out0_tensor = tensor_data[out[0].get_name()];\n auto& out1_tensor = tensor_data[out[1].get_name()];\n\n auto& mkldnn_emitter = external_function->get_mkldnn_emitter();\n auto input_desc = mkldnn_emitter->build_memory_descriptor(\n args[0], runtime::cpu::mkldnn_utils::get_input_mkldnn_format(node, 0));\n auto result_desc = mkldnn_emitter->build_memory_descriptor(\n out[0], runtime::cpu::mkldnn_utils::get_output_mkldnn_format(node, 0));\n\n size_t max_pool_index = mkldnn_emitter->build_max_pooling_with_indices_forward(\n mkldnn::algorithm::pooling_max,\n input_desc,\n result_desc,\n max_pool->get_window_movement_strides(),\n max_pool->get_window_shape(),\n max_pool->get_padding_below(),\n max_pool->get_padding_above());\n\n auto& deps = mkldnn_emitter->get_primitive_deps(max_pool_index);\n\n auto functor = [&, max_pool_index](CPURuntimeContext* ctx) {\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[0], arg0_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[1], out0_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[2], out1_tensor);\n cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, max_pool_index);\n };\n functors.emplace_back(functor);\n }\n\n template <>\n void Builder::BUILDER_DECL(ngraph::op::MaxPoolWithIndicesBackprop)\n {\n if (!runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node))\n {\n throw ngraph_error(\"MaxPoolWithIndicesBackprop isn't supported\");\n }\n\n auto& functors = external_function->get_functors();\n auto& tensor_data = external_function->get_tensor_data();\n\n auto& arg1_tensor = tensor_data[args[1].get_name()];\n auto& arg2_tensor = tensor_data[args[2].get_name()];\n auto& out_tensor = tensor_data[out[0].get_name()];\n\n auto mpb = static_cast<const ngraph::op::MaxPoolWithIndicesBackprop*>(node);\n\n auto& mkldnn_emitter = external_function->get_mkldnn_emitter();\n auto diff_dst_desc = mkldnn_emitter->build_memory_descriptor(\n args[1], runtime::cpu::mkldnn_utils::get_input_mkldnn_format(node, 1));\n auto diff_src_desc = mkldnn_emitter->build_memory_descriptor(\n out[0], runtime::cpu::mkldnn_utils::get_output_mkldnn_format(node, 0));\n\n size_t max_pool_index = mkldnn_emitter->build_max_pooling_with_indices_backward(\n mkldnn::algorithm::pooling_max,\n diff_dst_desc,\n diff_src_desc,\n mpb->get_window_movement_strides(),\n mpb->get_window_shape(),\n mpb->get_padding_below(),\n mpb->get_padding_above());\n\n auto& deps = mkldnn_emitter->get_primitive_deps(max_pool_index);\n\n auto functor = [&, max_pool_index](CPURuntimeContext* ctx) {\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[0], arg1_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[1], arg2_tensor);\n cpu::mkldnn_utils::set_memory_ptr(ctx, deps[2], out_tensor);\n cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, max_pool_index);\n };\n functors.emplace_back(functor);\n }\n\n REGISTER_OP_BUILDER(MaxPool);\n REGISTER_OP_BUILDER(MaxPoolWithIndices);\n REGISTER_OP_BUILDER(MaxPoolWithIndicesBackprop);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: BlueBerry Platform\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"berryProvisioningInfo.h\"\n\n#include <berryLog.h>\n\n#include <QFile>\n#include <QFileInfo>\n#include <QTextStream>\n#include <QCoreApplication>\n\nnamespace berry {\n\n#ifdef CMAKE_INTDIR\nconst QString ProvisioningInfo::intermediateOutDir = QString(CMAKE_INTDIR);\n#else\nconst QString ProvisioningInfo::intermediateOutDir = QString();\n#endif\n\nProvisioningInfo::ProvisioningInfo(const QString& file)\n{\n this->readProvisioningFile(file);\n}\n\nQStringList ProvisioningInfo::getPluginDirs() const\n{\n return pluginDirs.toList();\n}\n\nQList<QUrl> ProvisioningInfo::getPluginsToInstall() const\n{\n return pluginsToInstall;\n}\n\nQList<QUrl> ProvisioningInfo::getPluginsToStart() const\n{\n return pluginsToStart;\n}\n\nvoid ProvisioningInfo::readProvisioningFile(const QString& filePath)\n{\n QFile file(filePath);\n file.open(QFile::ReadOnly);\n QTextStream fileStream(&file);\n QRegExp sep(\"\\\\s+\");\n QString line;\n int count = 1;\n do {\n line = fileStream.readLine().trimmed();\n if (!line.isEmpty() && !line.startsWith('#'))\n {\n QString keyword = line.section(sep, 0, 0);\n QString value = line.mid(keyword.size()).trimmed();\n value = substituteKeywords(value);\n\n if (keyword.isEmpty())\n {\n BERRY_WARN << \"Keyword missing in line \" << count\n << \" of provisioning file \" << filePath.toStdString();\n continue;\n }\n\n Keyword key = UNKNOWN;\n if (keyword.compare(\"READ\", Qt::CaseInsensitive) == 0)\n {\n key = READ;\n }\n else if (keyword.compare(\"INSTALL\", Qt::CaseInsensitive) == 0)\n {\n key = INSTALL;\n }\n else if (keyword.compare(\"START\", Qt::CaseInsensitive) == 0)\n {\n key = START;\n }\n else if (keyword.compare(\"STOP\", Qt::CaseInsensitive) == 0)\n {\n key = STOP;\n }\n\n if (key == UNKNOWN)\n {\n BERRY_WARN << \"Keyword \" << keyword.toStdString() << \" in line \"\n << count << \" of provisioning file \"\n << filePath.toStdString() << \" unknown\";\n continue;\n }\n\n if (value.isEmpty())\n {\n BERRY_WARN << \"Value after keyword \" << keyword.toStdString()\n << \" missing in line \" << count\n << \" of provisioning file \" << filePath.toStdString();\n continue;\n }\n\n switch (key)\n {\n case READ:\n {\n QUrl readFileUrl(value);\n if (!readFileUrl.isValid())\n {\n BERRY_WARN << \"The READ URL \" << value.toStdString()\n << \"is invalid: \" << readFileUrl.errorString().toStdString();\n break;\n }\n this->readProvisioningFile(readFileUrl.toLocalFile());\n break;\n }\n case INSTALL:\n {\n this->addPluginToInstall(value);\n break;\n }\n case START:\n {\n this->addPluginToStart(value);\n break;\n }\n case STOP:\n {\n break;\n }\n }\n }\n ++count;\n } while (!line.isNull());\n}\n\nQUrl ProvisioningInfo::addPluginToInstall(const QString& file)\n{\n QUrl pluginUrl(file);\n if (!pluginUrl.isValid())\n {\n BERRY_WARN << \"The plugin URL \" << file.toStdString() << \" is invalid:\"\n << pluginUrl.errorString().toStdString();\n return QUrl();\n }\n\n QFileInfo fileInfo(pluginUrl.toLocalFile());\n if (!fileInfo.exists())\n {\n QString fileName = fileInfo.fileName();\n QString filePath = fileInfo.absolutePath();\n if (!intermediateOutDir.isEmpty())\n {\n \/\/ search in the intermediate output dir\n QString filePath2 = filePath + \"\/\" + intermediateOutDir;\n fileInfo = QFileInfo(filePath2 + \"\/\" + fileName);\n if (!fileInfo.exists())\n {\n BERRY_WARN << \"The plugin \" << fileName.toStdString() << \" was not found in \"\n << filePath.toStdString() << \" or \" << filePath2.toStdString();\n return QUrl();\n }\n pluginUrl = QUrl::fromLocalFile(fileInfo.canonicalFilePath());\n pluginDirs.insert(fileInfo.canonicalPath());\n }\n else\n {\n BERRY_WARN << \"The plugin \" << fileName.toStdString() << \" was not found in \"\n << filePath.toStdString();\n return QUrl();\n }\n }\n else\n {\n pluginDirs.insert(fileInfo.canonicalPath());\n }\n\n pluginsToInstall.append(pluginUrl);\n return pluginUrl;\n}\n\nvoid ProvisioningInfo::addPluginToStart(const QString& file)\n{\n QUrl pluginUrl = this->addPluginToInstall(file);\n if (!pluginUrl.isEmpty())\n {\n pluginsToStart.append(pluginUrl);\n }\n}\n\nQString ProvisioningInfo::substituteKeywords(const QString& value) const\n{\n QString appPath = QCoreApplication::applicationDirPath();\n if (appPath.endsWith('\/'))\n {\n appPath.chop(1);\n }\n\n#ifdef CMAKE_INTDIR\n \/\/ Strip the intermediate dir from the application path\n QString intDir(CMAKE_INTDIR);\n appPath.chop(intDir.size()+1);\n#endif\n\n return QString(value).replace(\"@EXECUTABLE_DIR\", appPath, Qt::CaseInsensitive);\n}\n\n}\n<commit_msg>Fix some issues when starting BlueBerry apps in an install tree.<commit_after>\/*=========================================================================\n\nProgram: BlueBerry Platform\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"berryProvisioningInfo.h\"\n\n#include <berryLog.h>\n\n#include <QFile>\n#include <QFileInfo>\n#include <QTextStream>\n#include <QCoreApplication>\n\nnamespace berry {\n\n#ifdef CMAKE_INTDIR\nconst QString ProvisioningInfo::intermediateOutDir = QString(CMAKE_INTDIR);\n#else\nconst QString ProvisioningInfo::intermediateOutDir = QString();\n#endif\n\nProvisioningInfo::ProvisioningInfo(const QString& file)\n{\n this->readProvisioningFile(file);\n}\n\nQStringList ProvisioningInfo::getPluginDirs() const\n{\n return pluginDirs.toList();\n}\n\nQList<QUrl> ProvisioningInfo::getPluginsToInstall() const\n{\n return pluginsToInstall;\n}\n\nQList<QUrl> ProvisioningInfo::getPluginsToStart() const\n{\n return pluginsToStart;\n}\n\nvoid ProvisioningInfo::readProvisioningFile(const QString& filePath)\n{\n QFile file(filePath);\n file.open(QFile::ReadOnly);\n QTextStream fileStream(&file);\n QRegExp sep(\"\\\\s+\");\n QString line;\n int count = 1;\n do {\n line = fileStream.readLine().trimmed();\n if (!line.isEmpty() && !line.startsWith('#'))\n {\n QString keyword = line.section(sep, 0, 0);\n QString value = line.mid(keyword.size()).trimmed();\n value = substituteKeywords(value);\n\n if (keyword.isEmpty())\n {\n BERRY_WARN << \"Keyword missing in line \" << count\n << \" of provisioning file \" << filePath.toStdString();\n continue;\n }\n\n Keyword key = UNKNOWN;\n if (keyword.compare(\"READ\", Qt::CaseInsensitive) == 0)\n {\n key = READ;\n }\n else if (keyword.compare(\"INSTALL\", Qt::CaseInsensitive) == 0)\n {\n key = INSTALL;\n }\n else if (keyword.compare(\"START\", Qt::CaseInsensitive) == 0)\n {\n key = START;\n }\n else if (keyword.compare(\"STOP\", Qt::CaseInsensitive) == 0)\n {\n key = STOP;\n }\n\n if (key == UNKNOWN)\n {\n BERRY_WARN << \"Keyword \" << keyword.toStdString() << \" in line \"\n << count << \" of provisioning file \"\n << filePath.toStdString() << \" unknown\";\n continue;\n }\n\n if (value.isEmpty())\n {\n BERRY_WARN << \"Value after keyword \" << keyword.toStdString()\n << \" missing in line \" << count\n << \" of provisioning file \" << filePath.toStdString();\n continue;\n }\n\n switch (key)\n {\n case READ:\n {\n QUrl readFileUrl(value);\n if (!readFileUrl.isValid())\n {\n BERRY_WARN << \"The READ URL \" << value.toStdString()\n << \"is invalid: \" << readFileUrl.errorString().toStdString();\n break;\n }\n this->readProvisioningFile(readFileUrl.toLocalFile());\n break;\n }\n case INSTALL:\n {\n this->addPluginToInstall(value);\n break;\n }\n case START:\n {\n this->addPluginToStart(value);\n break;\n }\n case STOP:\n {\n break;\n }\n }\n }\n ++count;\n } while (!line.isNull());\n}\n\nQUrl ProvisioningInfo::addPluginToInstall(const QString& file)\n{\n QUrl pluginUrl(file);\n if (!pluginUrl.isValid())\n {\n BERRY_WARN << \"The plugin URL \" << file.toStdString() << \" is invalid:\"\n << pluginUrl.errorString().toStdString();\n return QUrl();\n }\n\n QFileInfo fileInfo(pluginUrl.toLocalFile());\n if (!fileInfo.exists())\n {\n QString fileName = fileInfo.fileName();\n QString filePath = fileInfo.absolutePath();\n if (!intermediateOutDir.isEmpty())\n {\n \/\/ search in the intermediate output dir\n QString filePath2 = filePath + \"\/\" + intermediateOutDir;\n fileInfo = QFileInfo(filePath2 + \"\/\" + fileName);\n if (!fileInfo.exists())\n {\n BERRY_WARN << \"The plugin \" << fileName.toStdString() << \" was not found in \"\n << filePath.toStdString() << \" or \" << filePath2.toStdString();\n return QUrl();\n }\n pluginUrl = QUrl::fromLocalFile(fileInfo.canonicalFilePath());\n pluginDirs.insert(fileInfo.canonicalPath());\n }\n else\n {\n BERRY_WARN << \"The plugin \" << fileName.toStdString() << \" was not found in \"\n << filePath.toStdString();\n return QUrl();\n }\n }\n else\n {\n pluginDirs.insert(fileInfo.canonicalPath());\n }\n\n pluginsToInstall.append(pluginUrl);\n return pluginUrl;\n}\n\nvoid ProvisioningInfo::addPluginToStart(const QString& file)\n{\n QUrl pluginUrl = this->addPluginToInstall(file);\n if (!pluginUrl.isEmpty())\n {\n pluginsToStart.append(pluginUrl);\n }\n}\n\nQString ProvisioningInfo::substituteKeywords(const QString& value) const\n{\n QString appPath = QCoreApplication::applicationDirPath();\n if (appPath.endsWith('\/'))\n {\n appPath.chop(1);\n }\n\n#ifdef CMAKE_INTDIR\n \/\/ Strip the intermediate dir from the application path\n QString intDir(CMAKE_INTDIR);\n if (appPath.endsWith(intDir))\n {\n appPath.chop(intDir.size()+1);\n }\n#endif\n \n#ifdef _WIN32\n if (value.contains(\"@EXECUTABLE_DIR\") && value.contains(\"blueberry_osgi\"))\n {\n \/\/ special case for org_blueberry_osgi in install trees for Windows\n return QString(value).replace(\"@EXECUTABLE_DIR\", appPath, Qt::CaseInsensitive).replace(\"plugins\/\", \"\");\n }\n#endif\n\n return QString(value).replace(\"@EXECUTABLE_DIR\", appPath, Qt::CaseInsensitive);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-\n * Copyright (c) 2014 Peter Tworek\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the author nor the names of any co-contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include \"YTWebFontLoader.h\"\n\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QStandardPaths>\n#include <QNetworkReply>\n#include <QFontDatabase>\n#include <QFile>\n#include <QDebug>\n\n\nstatic QUrl kYouTubeWebFontURL = QUrl(\"https:\/\/www.youtube.com\/s\/tv\/fonts\/youtube-icons.ttf\");\n\nextern QSharedPointer<QNetworkAccessManager> GetNetworkAccessManager();\n\nYTWebFontLoader::YTWebFontLoader(QObject *parent)\n : QObject(parent)\n , _loaded(false)\n , _network_access_manager(GetNetworkAccessManager())\n{\n _fontPath = QStandardPaths::writableLocation(\n QStandardPaths::DataLocation).append(\"\/youtube-icons.ttf\");\n}\n\nYTWebFontLoader::~YTWebFontLoader()\n{\n}\n\nvoid\nYTWebFontLoader::load()\n{\n QNetworkRequest request(kYouTubeWebFontURL);\n if (QFile::exists(_fontPath) && installFont()) {\n return;\n }\n _reply = _network_access_manager->get(request);\n connect(_reply, SIGNAL(finished()), this, SLOT(onFinished()));\n}\n\nbool\nYTWebFontLoader::installFont()\n{\n if (QFontDatabase::addApplicationFont(_fontPath) < 0) {\n qCritical() << \"Failed to install YouTube web font\";\n return false;\n }\n _loaded = true;\n emit loadedChanged(true);\n return true;\n}\n\nvoid\nYTWebFontLoader::onFinished()\n{\n QFile fontFile(_fontPath);\n\n if (fontFile.open(QIODevice::WriteOnly)) {\n if (_reply->error() == QNetworkReply::NoError) {\n fontFile.write(_reply->readAll());\n fontFile.close();\n installFont();\n } else {\n qCritical() << \"Failed to download font file, error: \" << _reply->error();\n emit error();\n }\n } else {\n qCritical() << \"Failed to open font file for writing: \" << _fontPath;\n emit error();\n }\n\n _reply->deleteLater();\n _reply = NULL;\n}\n<commit_msg>YTWebFontLoader: Make sure the font is not loaded twice.<commit_after>\/*-\n * Copyright (c) 2014 Peter Tworek\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the author nor the names of any co-contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include \"YTWebFontLoader.h\"\n\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QStandardPaths>\n#include <QNetworkReply>\n#include <QFontDatabase>\n#include <QFile>\n#include <QDebug>\n\n\nstatic QUrl kYouTubeWebFontURL = QUrl(\"https:\/\/www.youtube.com\/s\/tv\/fonts\/youtube-icons.ttf\");\n\nextern QSharedPointer<QNetworkAccessManager> GetNetworkAccessManager();\n\nYTWebFontLoader::YTWebFontLoader(QObject *parent)\n : QObject(parent)\n , _loaded(false)\n , _network_access_manager(GetNetworkAccessManager())\n{\n _fontPath = QStandardPaths::writableLocation(\n QStandardPaths::DataLocation).append(\"\/youtube-icons.ttf\");\n}\n\nYTWebFontLoader::~YTWebFontLoader()\n{\n}\n\nvoid\nYTWebFontLoader::load()\n{\n if (_loaded) {\n return;\n }\n\n if (QFile::exists(_fontPath) && installFont()) {\n return;\n }\n\n QNetworkRequest request(kYouTubeWebFontURL);\n _reply = _network_access_manager->get(request);\n connect(_reply, SIGNAL(finished()), this, SLOT(onFinished()));\n}\n\nbool\nYTWebFontLoader::installFont()\n{\n if (QFontDatabase::addApplicationFont(_fontPath) < 0) {\n qCritical() << \"Failed to install YouTube web font\";\n return false;\n }\n _loaded = true;\n emit loadedChanged(true);\n return true;\n}\n\nvoid\nYTWebFontLoader::onFinished()\n{\n QFile fontFile(_fontPath);\n\n if (fontFile.open(QIODevice::WriteOnly)) {\n if (_reply->error() == QNetworkReply::NoError) {\n fontFile.write(_reply->readAll());\n fontFile.close();\n installFont();\n } else {\n qCritical() << \"Failed to download font file, error: \" << _reply->error();\n emit error();\n }\n } else {\n qCritical() << \"Failed to open font file for writing: \" << _fontPath;\n emit error();\n }\n\n _reply->deleteLater();\n _reply = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"helloworldplugin.h\"\n\n#include <coreplugin\/actionmanager\/actionmanagerinterface.h>\n#include <coreplugin\/basemode.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/modemanager.h>\n#include <coreplugin\/uniqueidmanager.h>\n#include <extensionsystem\/pluginmanager.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QtPlugin>\n#include <QtGui\/QAction>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QPushButton>\n\nusing namespace HelloWorld::Internal;\n\n\/*! Constructs the Hello World plugin. Normally plugins don't do anything in\n their constructor except for initializing their member variables. The\n actual work is done later, in the initialize() and extensionsInitialized()\n methods.\n*\/\nHelloWorldPlugin::HelloWorldPlugin()\n{\n}\n\n\/*! Plugins are responsible for deleting objects they created on the heap, and\n to unregister objects from the plugin manager that they registered there.\n*\/\nHelloWorldPlugin::~HelloWorldPlugin()\n{\n}\n\n\/*! Initializes the plugin. Returns true on success.\n Plugins want to register objects with the plugin manager here.\n\n \\a error_message can be used to pass an error message to the plugin system,\n if there was any.\n*\/\nbool HelloWorldPlugin::initialize(const QStringList &arguments, QString *error_message)\n{\n Q_UNUSED(arguments)\n Q_UNUSED(error_message)\n\n \/\/ Get the primary access point to the workbench.\n Core::ICore *core = ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>();\n\n \/\/ Create a unique context id for our own view, that will be used for the\n \/\/ menu entry later.\n QList<int> context = QList<int>()\n << core->uniqueIDManager()->uniqueIdentifier(\n QLatin1String(\"HelloWorld.MainView\"));\n\n \/\/ Create an action to be triggered by a menu entry\n QAction *helloWorldAction = new QAction(\"Say \\\"&Hello World!\\\"\", this);\n connect(helloWorldAction, SIGNAL(triggered()), SLOT(sayHelloWorld()));\n\n \/\/ Register the action with the action manager\n Core::ActionManager *actionManager = core->actionManager();\n Core::Command *command =\n actionManager->registerAction(\n helloWorldAction, \"HelloWorld.HelloWorldAction\", context);\n\n \/\/ Create our own menu to place in the Tools menu\n Core::ActionContainer *helloWorldMenu =\n actionManager->createMenu(\"HelloWorld.HelloWorldMenu\");\n QMenu *menu = helloWorldMenu->menu();\n menu->setTitle(tr(\"&Hello World\"));\n menu->setEnabled(true);\n\n \/\/ Add the Hello World action command to the menu\n helloWorldMenu->addAction(command);\n\n \/\/ Request the Tools menu and add the Hello World menu to it\n Core::IActionContainer *toolsMenu =\n actionManager->actionContainer(Core::Constants::M_TOOLS);\n toolsMenu->addMenu(helloWorldMenu);\n\n \/\/ Add a mode with a push button based on BaseMode. Like the BaseView,\n \/\/ it will unregister itself from the plugin manager when it is deleted.\n Core::BaseMode *baseMode = new Core::BaseMode;\n baseMode->setUniqueModeName(\"HelloWorld.HelloWorldMode\");\n baseMode->setName(tr(\"Hello world!\"));\n baseMode->setIcon(QIcon());\n baseMode->setPriority(0);\n baseMode->setWidget(new QPushButton(tr(\"Hello World PushButton!\")));\n addAutoReleasedObject(baseMode);\n\n \/\/ Add the Hello World action command to the mode manager (with 0 priority)\n Core::ModeManager *modeManager = core->modeManager();\n modeManager->addAction(command, 0);\n\n return true;\n}\n\n\/*! Notification that all extensions that this plugin depends on have been\n initialized. The dependencies are defined in the plugins .qwp file.\n\n Normally this method is used for things that rely on other plugins to have\n added objects to the plugin manager, that implement interfaces that we're\n interested in. These objects can now be requested through the\n PluginManagerInterface.\n\n The HelloWorldPlugin doesn't need things from other plugins, so it does\n nothing here.\n*\/\nvoid HelloWorldPlugin::extensionsInitialized()\n{\n}\n\nvoid HelloWorldPlugin::sayHelloWorld()\n{\n \/\/ When passing 0 for the parent, the message box becomes an\n \/\/ application-global modal dialog box\n QMessageBox::information(\n 0, \"Hello World!\", \"Hello World! Beautiful day today, isn't it?\");\n}\n\nQ_EXPORT_PLUGIN(HelloWorldPlugin)\n<commit_msg>Fixes: - HelloWorld compilation<commit_after>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"helloworldplugin.h\"\n\n#include <coreplugin\/actionmanager\/actionmanager.h>\n#include <coreplugin\/basemode.h>\n#include <coreplugin\/coreconstants.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/modemanager.h>\n#include <coreplugin\/uniqueidmanager.h>\n#include <extensionsystem\/pluginmanager.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QtPlugin>\n#include <QtGui\/QAction>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QPushButton>\n\nusing namespace HelloWorld::Internal;\n\n\/*! Constructs the Hello World plugin. Normally plugins don't do anything in\n their constructor except for initializing their member variables. The\n actual work is done later, in the initialize() and extensionsInitialized()\n methods.\n*\/\nHelloWorldPlugin::HelloWorldPlugin()\n{\n}\n\n\/*! Plugins are responsible for deleting objects they created on the heap, and\n to unregister objects from the plugin manager that they registered there.\n*\/\nHelloWorldPlugin::~HelloWorldPlugin()\n{\n}\n\n\/*! Initializes the plugin. Returns true on success.\n Plugins want to register objects with the plugin manager here.\n\n \\a error_message can be used to pass an error message to the plugin system,\n if there was any.\n*\/\nbool HelloWorldPlugin::initialize(const QStringList &arguments, QString *error_message)\n{\n Q_UNUSED(arguments)\n Q_UNUSED(error_message)\n\n \/\/ Get the primary access point to the workbench.\n Core::ICore *core = ExtensionSystem::PluginManager::instance()->getObject<Core::ICore>();\n\n \/\/ Create a unique context id for our own view, that will be used for the\n \/\/ menu entry later.\n QList<int> context = QList<int>()\n << core->uniqueIDManager()->uniqueIdentifier(\n QLatin1String(\"HelloWorld.MainView\"));\n\n \/\/ Create an action to be triggered by a menu entry\n QAction *helloWorldAction = new QAction(\"Say \\\"&Hello World!\\\"\", this);\n connect(helloWorldAction, SIGNAL(triggered()), SLOT(sayHelloWorld()));\n\n \/\/ Register the action with the action manager\n Core::ActionManager *actionManager = core->actionManager();\n Core::Command *command =\n actionManager->registerAction(\n helloWorldAction, \"HelloWorld.HelloWorldAction\", context);\n\n \/\/ Create our own menu to place in the Tools menu\n Core::ActionContainer *helloWorldMenu =\n actionManager->createMenu(\"HelloWorld.HelloWorldMenu\");\n QMenu *menu = helloWorldMenu->menu();\n menu->setTitle(tr(\"&Hello World\"));\n menu->setEnabled(true);\n\n \/\/ Add the Hello World action command to the menu\n helloWorldMenu->addAction(command);\n\n \/\/ Request the Tools menu and add the Hello World menu to it\n Core::ActionContainer *toolsMenu =\n actionManager->actionContainer(Core::Constants::M_TOOLS);\n toolsMenu->addMenu(helloWorldMenu);\n\n \/\/ Add a mode with a push button based on BaseMode. Like the BaseView,\n \/\/ it will unregister itself from the plugin manager when it is deleted.\n Core::BaseMode *baseMode = new Core::BaseMode;\n baseMode->setUniqueModeName(\"HelloWorld.HelloWorldMode\");\n baseMode->setName(tr(\"Hello world!\"));\n baseMode->setIcon(QIcon());\n baseMode->setPriority(0);\n baseMode->setWidget(new QPushButton(tr(\"Hello World PushButton!\")));\n addAutoReleasedObject(baseMode);\n\n \/\/ Add the Hello World action command to the mode manager (with 0 priority)\n Core::ModeManager *modeManager = core->modeManager();\n modeManager->addAction(command, 0);\n\n return true;\n}\n\n\/*! Notification that all extensions that this plugin depends on have been\n initialized. The dependencies are defined in the plugins .qwp file.\n\n Normally this method is used for things that rely on other plugins to have\n added objects to the plugin manager, that implement interfaces that we're\n interested in. These objects can now be requested through the\n PluginManagerInterface.\n\n The HelloWorldPlugin doesn't need things from other plugins, so it does\n nothing here.\n*\/\nvoid HelloWorldPlugin::extensionsInitialized()\n{\n}\n\nvoid HelloWorldPlugin::sayHelloWorld()\n{\n \/\/ When passing 0 for the parent, the message box becomes an\n \/\/ application-global modal dialog box\n QMessageBox::information(\n 0, \"Hello World!\", \"Hello World! Beautiful day today, isn't it?\");\n}\n\nQ_EXPORT_PLUGIN(HelloWorldPlugin)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2010 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"img_websearch.h\"\n#include \"img_sort_rank.h\"\n#include \"websearch.h\" \/\/ websearch plugin.\n#include \"errlog.h\"\n#include \"cgi.h\"\n#include \"cgisimple.h\"\n#include \"miscutil.h\"\n#include \"json_renderer.h\"\n#include \"static_renderer.h\"\n#include \"seeks_proxy.h\"\n\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <sys\/times.h>\n\nusing namespace sp;\n\nnamespace seeks_plugins\n{\n img_websearch_configuration* img_websearch::_iwconfig = NULL;\n hash_map<uint32_t,query_context*,id_hash_uint> img_websearch::_active_img_qcontexts\n = hash_map<uint32_t,query_context*,id_hash_uint>();\n \n img_websearch::img_websearch()\n : plugin()\n {\n\t _name = \"img_websearch\";\n\t _version_major = \"0\";\n\t _version_minor = \"1\";\n\t \n\t \/\/ config filename.\n\t if (seeks_proxy::_datadir.empty())\n\t _config_filename = plugin_manager::_plugin_repository + \"img_websearch\/img-websearch-config\";\n\t else _config_filename = seeks_proxy::_datadir + \"\/plugins\/img_websearch\/img-websearch-config\";\n\t \n#ifdef SEEKS_CONFIGDIR\n\t struct stat stFileInfo;\n\t if (!stat(_config_filename.c_str(), &stFileInfo) == 0)\n\t {\n\t _config_filename = SEEKS_CONFIGDIR \"\/img-websearch-config\";\n\t }\n#endif\n\t \n\t if (img_websearch::_iwconfig == NULL)\n\t img_websearch::_iwconfig = new img_websearch_configuration(_config_filename);\n\t \n\t \/\/ cgi dispatchers.\n\t _cgi_dispatchers.reserve(2);\n\t \n\t cgi_dispatcher *cgid_wb_seeks_img_search_css\n\t = new cgi_dispatcher(\"seeks_img_search.css\", &img_websearch::cgi_img_websearch_search_css, NULL, TRUE);\n\t _cgi_dispatchers.push_back(cgid_wb_seeks_img_search_css);\n\t \n\t cgi_dispatcher *cgid_img_wb_search\n\t = new cgi_dispatcher(\"search_img\", &img_websearch::cgi_img_websearch_search, NULL, TRUE);\n\t _cgi_dispatchers.push_back(cgid_img_wb_search);\n }\n \n img_websearch::~img_websearch()\n {\n }\n \n \/\/ CGI calls.\n sp_err img_websearch::cgi_img_websearch_search_css(client_state *csp,\n\t\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)\n {\n\tassert(csp);\n\tassert(rsp);\n\tassert(parameters);\n\t\n\tstd::string seeks_search_css_str = \"img_websearch\/templates\/css\/seeks_img_search.css\";\n\thash_map<const char*,const char*,hash<const char*>,eqstr> *exports\n\t = static_renderer::websearch_exports(csp);\n\tcsp->_content_type = CT_CSS;\n\tsp_err err = cgi::template_fill_for_cgi_str(csp,seeks_search_css_str.c_str(),\n\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository.c_str()\n\t\t\t\t\t\t : std::string(seeks_proxy::_datadir + \"plugins\/\").c_str()),\n\t\t\t\t\t\t exports,rsp);\n\tif (err != SP_ERR_OK)\n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"Could not load seeks_img_search.css\");\n\t }\n\trsp->_is_static = 1;\n\t\n\treturn SP_ERR_OK;\n }\n \n sp_err img_websearch::cgi_img_websearch_search(client_state *csp,\n\t\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)\n {\n\tif (!parameters->empty())\n\t {\n\t const char *query = miscutil::lookup(parameters,\"q\"); \/\/ grab the query.\n\t if (!query || strlen(query) == 0)\n\t {\n\t\t \/\/ return websearch homepage instead.\n\t\t return websearch::cgi_websearch_hp(csp,rsp,parameters);\n\t }\n\t else se_handler::preprocess_parameters(parameters); \/\/ preprocess the query...\n\t \n\t \/\/ perform websearch or other requested action.\n\t const char *action = miscutil::lookup(parameters,\"action\");\n\t if (!action)\n\t return websearch::cgi_websearch_hp(csp,rsp,parameters);\n\t \n\t sp_err err = SP_ERR_OK;\n\t if (strcmp(action,\"expand\") == 0 || strcmp(action,\"page\") == 0)\n\t err = img_websearch::perform_img_websearch(csp,rsp,parameters);\n#ifdef FEATURE_OPENCV2\n\t else if (strcmp(action,\"similarity\") == 0)\n\t err = img_websearch::cgi_img_websearch_similarity(csp,rsp,parameters);\n#endif\n\t return err;\n\t }\n\telse return SP_ERR_OK;\n }\t\t\t \n \n#ifdef FEATURE_OPENCV2\n sp_err img_websearch::cgi_img_websearch_similarity(client_state *csp, http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)\n {\n\tstatic std::string tmpl_name = \"templates\/seeks_result_template.html\";\n\t\n\tif (!parameters->empty())\n\t {\n\t img_query_context *qc = dynamic_cast<img_query_context*>(websearch::lookup_qc(parameters,csp,_active_img_qcontexts));\n\t \n\t if (!qc)\n\t {\n\t\t \/\/ no cache, (re)do the websearch first.\n\t\t sp_err err = img_websearch::perform_img_websearch(csp,rsp,parameters,false);\n\t\t if (err != SP_ERR_OK)\n\t\t return err;\n\t\t qc = dynamic_cast<img_query_context*>(websearch::lookup_qc(parameters,csp,_active_img_qcontexts));\n\t\t if (!qc)\n\t\t return SP_ERR_MEMORY;\n\t }\n\t const char *id = miscutil::lookup(parameters,\"id\");\n\t \n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t img_search_snippet *ref_sp = NULL;\n\t \n\t img_sort_rank::score_and_sort_by_similarity(qc,id,ref_sp,qc->_cached_snippets);\n\t \n\t if (!ref_sp)\n\t {\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t\t return SP_ERR_OK;\n\t }\n\t \n\t const char *output = miscutil::lookup(parameters,\"output\");\n\t sp_err err = SP_ERR_OK;\n\t if (!output || strcmp(output,\"html\")==0)\n\t {\n\t\t \/\/ sets the number of images per page, if not already set.\n\t\t const char *rpp = miscutil::lookup(parameters,\"rpp\");\n\t\t if (!rpp)\n\t\t {\n\t\t miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),\"rpp\",1,\n\t\t\t\t\t miscutil::to_string(img_websearch_configuration::_img_wconfig->_N).c_str(),1);\n\t\t }\n\t\t err = static_renderer::render_result_page_static(qc->_cached_snippets,\n\t\t\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository + tmpl_name\n\t\t\t\t\t\t\t\t : std::string(seeks_proxy::_datadir) + \"plugins\/img_websearch\/\" + tmpl_name),\n\t\t\t\t\t\t\t\t \"\/search_img?\");\n\t }\n\t else\n\t {\n\t\t csp->_content_type = CT_JSON;\n\t\t err = json_renderer::render_json_results(qc->_cached_snippets,\n\t\t\t\t\t\t\t csp,rsp,parameters,qc,0.0);\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t\t return err;\n\t }\n\t \n\t \/\/ reset scores.\n\t std::vector<search_snippet*>::iterator vit = qc->_cached_snippets.begin();\n\t while(vit!=qc->_cached_snippets.end())\n\t {\n\t\t (*vit)->_seeks_ir = 0;\n\t\t ++vit;\n\t }\n\t ref_sp->set_similarity_link(); \/\/ reset sim_link.\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t return err;\n\t }\n\telse return SP_ERR_OK;\n }\n#endif\n \n \/\/ internal functions.\n sp_err img_websearch::perform_img_websearch(client_state *csp,\n\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,\n\t\t\t\t\t bool render)\n {\n\tstatic std::string tmpl_name = \"templates\/seeks_result_template.html\";\n\t\n\t\/\/ time measure, returned.\n\t\/\/ XXX: not sure whether it is functional on all *nix platforms.\n\tstruct tms st_cpu;\n\tstruct tms en_cpu;\n\tclock_t start_time = times(&st_cpu);\n\t\t\n\t\/\/ lookup a cached context for the incoming query.\n\tquery_context *vqc = websearch::lookup_qc(parameters,csp,_active_img_qcontexts);\n\timg_query_context *qc = NULL;\n\tif (vqc)\n\t qc = dynamic_cast<img_query_context*>(vqc);\n\t\t\n\t\/\/ check whether search is expanding or the user is leafing through pages.\n\tconst char *action = miscutil::lookup(parameters,\"action\");\n\t\n\t\/\/ expansion: we fetch more pages from every search engine.\n\tbool expanded = false;\n\tif (qc) \/\/ we already had a context for this query.\n\t {\n\t if (strcmp(action,\"expand\") == 0)\n\t {\n\t\t expanded = true;\n\t\t \n\t\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t\t qc->_lock = true;\n\t\t qc->generate(csp,rsp,parameters,expanded);\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t else if (strcmp(action,\"page\") == 0)\n\t {\n\t\t \/\/ XXX: update other parameters, as needed, qc vs parameters.\n\t\t qc->update_parameters(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters));\n\t }\n\t }\n\telse\n\t {\n\t \/\/ new context, whether we're expanding or not doesn't matter, we need\n\t \/\/ to generate snippets first.\n\t expanded = true;\n\t qc = new img_query_context(parameters,csp->_headers);\n\t qc->register_qc();\n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t qc->generate(csp,rsp,parameters,expanded);\n\t qc->_lock = false; \n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t\n\t\/\/ sort and rank search snippets.\n\tif (expanded)\n\t {\n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t img_sort_rank::sort_rank_and_merge_snippets(qc,qc->_cached_snippets);\n\t qc->_compute_tfidf_features = true;\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t\t\n\t\/\/ rendering.\n\tseeks_proxy::mutex_lock(&qc->_qc_mutex);\n\tqc->_lock = true;\n\t\n\t\/\/ time measured before rendering, since we need to write it down.\n\tclock_t end_time = times(&en_cpu);\n\tdouble qtime = (end_time-start_time)\/websearch::_cl_sec;\n\tif (qtime<0)\n\t qtime = -1.0; \/\/ unavailable.\n\t\n\tif (!render)\n\t {\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex); \n\t return SP_ERR_OK;\n\t }\n\tconst char *output = miscutil::lookup(parameters,\"output\");\n\tsp_err err = SP_ERR_OK;\n\tif (!output || strcmp(output,\"html\")==0)\n\t {\n\t \/\/ sets the number of images per page, if not already set.\n\t const char *rpp = miscutil::lookup(parameters,\"rpp\");\n\t if (!rpp)\n\t {\n\t\t miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),\"rpp\",1,\n\t\t\t\t\t miscutil::to_string(img_websearch_configuration::_img_wconfig->_N).c_str(),1);\n\t }\n\t err = static_renderer::render_result_page_static(qc->_cached_snippets,\n\t\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository + tmpl_name \n\t\t\t\t\t\t\t : std::string(seeks_proxy::_datadir) + \"plugins\/img_websearch\/\" + tmpl_name),\n\t\t\t\t\t\t\t \"\/search_img?\");\n\t }\n\telse\n\t {\n\t csp->_content_type = CT_JSON;\n\t err = json_renderer::render_json_results(qc->_cached_snippets,\n\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t qtime);\n\t }\n\t\n\t\/\/ unlock or destroy the query context.\n\tqc->_lock = false;\n\tseeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t\/* if (qc->empty())\n\t delete qc; *\/\n\t\n\treturn err;\n }\n\n \/* auto-registration. *\/\n extern \"C\"\n {\n\tplugin* makeiw()\n\t {\n\t return new img_websearch;\n\t }\n }\n \n class proxy_autoiw\n {\n public:\n\tproxy_autoiw()\n\t {\n\t plugin_manager::_factory[\"image-websearch\"] = makeiw;\n\t }\n };\n \n proxy_autoiw _p; \/\/ one instance, instanciated when dl-opening.\n \n} \/* end of namespace. *\/\n<commit_msg>immediate deletion of image query context when no results<commit_after>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2010 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"img_websearch.h\"\n#include \"img_sort_rank.h\"\n#include \"websearch.h\" \/\/ websearch plugin.\n#include \"errlog.h\"\n#include \"cgi.h\"\n#include \"cgisimple.h\"\n#include \"miscutil.h\"\n#include \"json_renderer.h\"\n#include \"static_renderer.h\"\n#include \"seeks_proxy.h\"\n\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <sys\/times.h>\n\nusing namespace sp;\n\nnamespace seeks_plugins\n{\n img_websearch_configuration* img_websearch::_iwconfig = NULL;\n hash_map<uint32_t,query_context*,id_hash_uint> img_websearch::_active_img_qcontexts\n = hash_map<uint32_t,query_context*,id_hash_uint>();\n \n img_websearch::img_websearch()\n : plugin()\n {\n\t _name = \"img_websearch\";\n\t _version_major = \"0\";\n\t _version_minor = \"1\";\n\t \n\t \/\/ config filename.\n\t if (seeks_proxy::_datadir.empty())\n\t _config_filename = plugin_manager::_plugin_repository + \"img_websearch\/img-websearch-config\";\n\t else _config_filename = seeks_proxy::_datadir + \"\/plugins\/img_websearch\/img-websearch-config\";\n\t \n#ifdef SEEKS_CONFIGDIR\n\t struct stat stFileInfo;\n\t if (!stat(_config_filename.c_str(), &stFileInfo) == 0)\n\t {\n\t _config_filename = SEEKS_CONFIGDIR \"\/img-websearch-config\";\n\t }\n#endif\n\t \n\t if (img_websearch::_iwconfig == NULL)\n\t img_websearch::_iwconfig = new img_websearch_configuration(_config_filename);\n\t \n\t \/\/ cgi dispatchers.\n\t _cgi_dispatchers.reserve(2);\n\t \n\t cgi_dispatcher *cgid_wb_seeks_img_search_css\n\t = new cgi_dispatcher(\"seeks_img_search.css\", &img_websearch::cgi_img_websearch_search_css, NULL, TRUE);\n\t _cgi_dispatchers.push_back(cgid_wb_seeks_img_search_css);\n\t \n\t cgi_dispatcher *cgid_img_wb_search\n\t = new cgi_dispatcher(\"search_img\", &img_websearch::cgi_img_websearch_search, NULL, TRUE);\n\t _cgi_dispatchers.push_back(cgid_img_wb_search);\n }\n \n img_websearch::~img_websearch()\n {\n }\n \n \/\/ CGI calls.\n sp_err img_websearch::cgi_img_websearch_search_css(client_state *csp,\n\t\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)\n {\n\tassert(csp);\n\tassert(rsp);\n\tassert(parameters);\n\t\n\tstd::string seeks_search_css_str = \"img_websearch\/templates\/css\/seeks_img_search.css\";\n\thash_map<const char*,const char*,hash<const char*>,eqstr> *exports\n\t = static_renderer::websearch_exports(csp);\n\tcsp->_content_type = CT_CSS;\n\tsp_err err = cgi::template_fill_for_cgi_str(csp,seeks_search_css_str.c_str(),\n\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository.c_str()\n\t\t\t\t\t\t : std::string(seeks_proxy::_datadir + \"plugins\/\").c_str()),\n\t\t\t\t\t\t exports,rsp);\n\tif (err != SP_ERR_OK)\n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"Could not load seeks_img_search.css\");\n\t }\n\trsp->_is_static = 1;\n\t\n\treturn SP_ERR_OK;\n }\n \n sp_err img_websearch::cgi_img_websearch_search(client_state *csp,\n\t\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)\n {\n\tif (!parameters->empty())\n\t {\n\t const char *query = miscutil::lookup(parameters,\"q\"); \/\/ grab the query.\n\t if (!query || strlen(query) == 0)\n\t {\n\t\t \/\/ return websearch homepage instead.\n\t\t return websearch::cgi_websearch_hp(csp,rsp,parameters);\n\t }\n\t else se_handler::preprocess_parameters(parameters); \/\/ preprocess the query...\n\t \n\t \/\/ perform websearch or other requested action.\n\t const char *action = miscutil::lookup(parameters,\"action\");\n\t if (!action)\n\t return websearch::cgi_websearch_hp(csp,rsp,parameters);\n\t \n\t sp_err err = SP_ERR_OK;\n\t if (strcmp(action,\"expand\") == 0 || strcmp(action,\"page\") == 0)\n\t err = img_websearch::perform_img_websearch(csp,rsp,parameters);\n#ifdef FEATURE_OPENCV2\n\t else if (strcmp(action,\"similarity\") == 0)\n\t err = img_websearch::cgi_img_websearch_similarity(csp,rsp,parameters);\n#endif\n\t return err;\n\t }\n\telse return SP_ERR_OK;\n }\t\t\t \n \n#ifdef FEATURE_OPENCV2\n sp_err img_websearch::cgi_img_websearch_similarity(client_state *csp, http_response *rsp,\n\t\t\t\t\t\t const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)\n {\n\tstatic std::string tmpl_name = \"templates\/seeks_result_template.html\";\n\t\n\tif (!parameters->empty())\n\t {\n\t img_query_context *qc = dynamic_cast<img_query_context*>(websearch::lookup_qc(parameters,csp,_active_img_qcontexts));\n\t \n\t if (!qc)\n\t {\n\t\t \/\/ no cache, (re)do the websearch first.\n\t\t sp_err err = img_websearch::perform_img_websearch(csp,rsp,parameters,false);\n\t\t if (err != SP_ERR_OK)\n\t\t return err;\n\t\t qc = dynamic_cast<img_query_context*>(websearch::lookup_qc(parameters,csp,_active_img_qcontexts));\n\t\t if (!qc)\n\t\t return SP_ERR_MEMORY;\n\t }\n\t const char *id = miscutil::lookup(parameters,\"id\");\n\t \n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t img_search_snippet *ref_sp = NULL;\n\t \n\t img_sort_rank::score_and_sort_by_similarity(qc,id,ref_sp,qc->_cached_snippets);\n\t \n\t if (!ref_sp)\n\t {\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t\t return SP_ERR_OK;\n\t }\n\t \n\t const char *output = miscutil::lookup(parameters,\"output\");\n\t sp_err err = SP_ERR_OK;\n\t if (!output || strcmp(output,\"html\")==0)\n\t {\n\t\t \/\/ sets the number of images per page, if not already set.\n\t\t const char *rpp = miscutil::lookup(parameters,\"rpp\");\n\t\t if (!rpp)\n\t\t {\n\t\t miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),\"rpp\",1,\n\t\t\t\t\t miscutil::to_string(img_websearch_configuration::_img_wconfig->_N).c_str(),1);\n\t\t }\n\t\t err = static_renderer::render_result_page_static(qc->_cached_snippets,\n\t\t\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository + tmpl_name\n\t\t\t\t\t\t\t\t : std::string(seeks_proxy::_datadir) + \"plugins\/img_websearch\/\" + tmpl_name),\n\t\t\t\t\t\t\t\t \"\/search_img?\");\n\t }\n\t else\n\t {\n\t\t csp->_content_type = CT_JSON;\n\t\t err = json_renderer::render_json_results(qc->_cached_snippets,\n\t\t\t\t\t\t\t csp,rsp,parameters,qc,0.0);\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t\t return err;\n\t }\n\t \n\t \/\/ reset scores.\n\t std::vector<search_snippet*>::iterator vit = qc->_cached_snippets.begin();\n\t while(vit!=qc->_cached_snippets.end())\n\t {\n\t\t (*vit)->_seeks_ir = 0;\n\t\t ++vit;\n\t }\n\t ref_sp->set_similarity_link(); \/\/ reset sim_link.\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t return err;\n\t }\n\telse return SP_ERR_OK;\n }\n#endif\n \n \/\/ internal functions.\n sp_err img_websearch::perform_img_websearch(client_state *csp,\n\t\t\t\t\t http_response *rsp,\n\t\t\t\t\t const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,\n\t\t\t\t\t bool render)\n {\n\tstatic std::string tmpl_name = \"templates\/seeks_result_template.html\";\n\t\n\t\/\/ time measure, returned.\n\t\/\/ XXX: not sure whether it is functional on all *nix platforms.\n\tstruct tms st_cpu;\n\tstruct tms en_cpu;\n\tclock_t start_time = times(&st_cpu);\n\t\t\n\t\/\/ lookup a cached context for the incoming query.\n\tquery_context *vqc = websearch::lookup_qc(parameters,csp,_active_img_qcontexts);\n\timg_query_context *qc = NULL;\n\tif (vqc)\n\t qc = dynamic_cast<img_query_context*>(vqc);\n\t\t\n\t\/\/ check whether search is expanding or the user is leafing through pages.\n\tconst char *action = miscutil::lookup(parameters,\"action\");\n\t\n\t\/\/ expansion: we fetch more pages from every search engine.\n\tbool expanded = false;\n\tif (qc) \/\/ we already had a context for this query.\n\t {\n\t if (strcmp(action,\"expand\") == 0)\n\t {\n\t\t expanded = true;\n\t\t \n\t\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t\t qc->_lock = true;\n\t\t qc->generate(csp,rsp,parameters,expanded);\n\t\t qc->_lock = false;\n\t\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t else if (strcmp(action,\"page\") == 0)\n\t {\n\t\t \/\/ XXX: update other parameters, as needed, qc vs parameters.\n\t\t qc->update_parameters(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters));\n\t }\n\t }\n\telse\n\t {\n\t \/\/ new context, whether we're expanding or not doesn't matter, we need\n\t \/\/ to generate snippets first.\n\t expanded = true;\n\t qc = new img_query_context(parameters,csp->_headers);\n\t qc->register_qc();\n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t qc->generate(csp,rsp,parameters,expanded);\n\t qc->_lock = false; \n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t\n\t\/\/ sort and rank search snippets.\n\tif (expanded)\n\t {\n\t seeks_proxy::mutex_lock(&qc->_qc_mutex);\n\t qc->_lock = true;\n\t img_sort_rank::sort_rank_and_merge_snippets(qc,qc->_cached_snippets);\n\t qc->_compute_tfidf_features = true;\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\t }\n\t\t\n\t\/\/ rendering.\n\tseeks_proxy::mutex_lock(&qc->_qc_mutex);\n\tqc->_lock = true;\n\t\n\t\/\/ time measured before rendering, since we need to write it down.\n\tclock_t end_time = times(&en_cpu);\n\tdouble qtime = (end_time-start_time)\/websearch::_cl_sec;\n\tif (qtime<0)\n\t qtime = -1.0; \/\/ unavailable.\n\t\n\tif (!render)\n\t {\n\t qc->_lock = false;\n\t seeks_proxy::mutex_unlock(&qc->_qc_mutex); \n\t return SP_ERR_OK;\n\t }\n\tconst char *output = miscutil::lookup(parameters,\"output\");\n\tsp_err err = SP_ERR_OK;\n\tif (!output || strcmp(output,\"html\")==0)\n\t {\n\t \/\/ sets the number of images per page, if not already set.\n\t const char *rpp = miscutil::lookup(parameters,\"rpp\");\n\t if (!rpp)\n\t {\n\t\t miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),\"rpp\",1,\n\t\t\t\t\t miscutil::to_string(img_websearch_configuration::_img_wconfig->_N).c_str(),1);\n\t }\n\t err = static_renderer::render_result_page_static(qc->_cached_snippets,\n\t\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t\t (seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository + tmpl_name \n\t\t\t\t\t\t\t : std::string(seeks_proxy::_datadir) + \"plugins\/img_websearch\/\" + tmpl_name),\n\t\t\t\t\t\t\t \"\/search_img?\");\n\t }\n\telse\n\t {\n\t csp->_content_type = CT_JSON;\n\t err = json_renderer::render_json_results(qc->_cached_snippets,\n\t\t\t\t\t\t csp,rsp,parameters,qc,\n\t\t\t\t\t\t qtime);\n\t }\n\t\n\t\/\/ unlock or destroy the query context.\n\tqc->_lock = false;\n\tseeks_proxy::mutex_unlock(&qc->_qc_mutex);\n\tsweeper::unregister_sweepable(qc);\n\tif (qc->empty())\n\t delete qc;\n\t\n\treturn err;\n }\n\n \/* auto-registration. *\/\n extern \"C\"\n {\n\tplugin* makeiw()\n\t {\n\t return new img_websearch;\n\t }\n }\n \n class proxy_autoiw\n {\n public:\n\tproxy_autoiw()\n\t {\n\t plugin_manager::_factory[\"image-websearch\"] = makeiw;\n\t }\n };\n \n proxy_autoiw _p; \/\/ one instance, instanciated when dl-opening.\n \n} \/* end of namespace. *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <util\/XMLUniDefs.hpp>\n#include <util\/XMLUni.hpp>\n#include \"IconvTransService.hpp\"\n#include <wchar.h>\n#if defined (XML_GCC) || defined (XML_PTX) || defined (XML_IBMVAOS2)\n#include <wctype.h>\n#endif\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local, const data\n\/\/ ---------------------------------------------------------------------------\nstatic const int gTempBuffArraySize = 1024;\nstatic const XMLCh gMyServiceId[] =\n{\n chLatin_I, chLatin_C, chLatin_o, chLatin_n, chLatin_v, chNull\n};\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local methods\n\/\/ ---------------------------------------------------------------------------\nstatic unsigned int getWideCharLength(const XMLCh* const src)\n{\n if (!src)\n return 0;\n\n unsigned int len = 0;\n const XMLCh* pTmp = src;\n while (*pTmp++)\n len++;\n return len;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvTransService::IconvTransService()\n{\n}\n\nIconvTransService::~IconvTransService()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: The virtual transcoding service API\n\/\/ ---------------------------------------------------------------------------\nint IconvTransService::compareIString( const XMLCh* const comp1\n , const XMLCh* const comp2)\n{\n const XMLCh* cptr1 = comp1;\n const XMLCh* cptr2 = comp2;\n\n while ( (*cptr1 != 0) && (*cptr2 != 0) )\n {\n wint_t wch1 = towupper(*cptr1);\n wint_t wch2 = towupper(*cptr2);\n if (wch1 != wch2)\n break;\n\n cptr1++;\n cptr2++;\n }\n return (int) ( towupper(*cptr1) - towupper(*cptr2) );\n}\n\n\nint IconvTransService::compareNIString( const XMLCh* const comp1\n , const XMLCh* const comp2\n , const unsigned int maxChars)\n{\n unsigned int n = 0;\n const XMLCh* cptr1 = comp1;\n const XMLCh* cptr2 = comp2;\n\n while ( (*cptr1 != 0) && (*cptr2 != 0) && (n < maxChars) )\n {\n wint_t wch1 = towupper(*cptr1);\n wint_t wch2 = towupper(*cptr2);\n if (wch1 != wch2)\n break;\n\n cptr1++;\n cptr2++;\n n++;\n }\n return (int) ( towupper(*cptr1) - towupper(*cptr2) );\n}\n\n\nconst XMLCh* IconvTransService::getId() const\n{\n return gMyServiceId;\n}\n\n\nbool IconvTransService::isSpace(const XMLCh toCheck) const\n{\n return (iswspace(toCheck) != 0);\n}\n\n\nXMLLCPTranscoder* IconvTransService::makeNewLCPTranscoder()\n{\n \/\/ Just allocate a new transcoder of our type\n return new IconvLCPTranscoder;\n}\n\nbool IconvTransService::supportsSrcOfs() const\n{\n return true;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: The protected virtual transcoding service API\n\/\/ ---------------------------------------------------------------------------\nXMLTranscoder*\nIconvTransService::makeNewXMLTranscoder(const XMLCh* const encodingName\n , XMLTransService::Codes& resValue\n , const unsigned int )\n{\n \/\/\n \/\/ NOTE: We don't use the block size here\n \/\/\n \/\/ This is a minimalist transcoding service, that only supports a local\n \/\/ default transcoder. All named encodings return zero as a failure,\n \/\/ which means that only the intrinsic encodings supported by the parser\n \/\/ itself will work for XML data.\n \/\/\n resValue = XMLTransService::UnsupportedEncoding;\n return 0;\n}\n\nvoid IconvTransService::upperCase(XMLCh* const toUpperCase) const\n{\n XMLCh* outPtr = toUpperCase;\n while (*outPtr)\n {\n *outPtr = towupper(*outPtr);\n outPtr++;\n }\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvLCPTranscoder: The virtual transcoder API\n\/\/ ---------------------------------------------------------------------------\nunsigned int IconvLCPTranscoder::calcRequiredSize(const char* const srcText)\n{\n if (!srcText)\n return 0;\n\n const unsigned int retVal = ::mbstowcs(NULL, srcText, 0);\n\n if (retVal == ~0)\n return 0;\n return retVal;\n}\n\n\nunsigned int IconvLCPTranscoder::calcRequiredSize(const XMLCh* const srcText)\n{\n if (!srcText)\n return 0;\n\n unsigned int wLent = getWideCharLength(srcText);\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (wLent >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[wLent + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < wLent; i++)\n {\n wideCharBuf[i] = srcText[i];\n }\n wideCharBuf[wLent] = 0x00;\n\n const unsigned int retVal = ::wcstombs(NULL, wideCharBuf, 0);\n delete [] allocatedArray;\n\n if (retVal == ~0)\n return 0;\n return retVal;\n}\n\n\nchar* IconvLCPTranscoder::transcode(const XMLCh* const toTranscode)\n{\n if (!toTranscode)\n return 0;\n\n char* retVal = 0;\n if (toTranscode)\n {\n unsigned int wLent = getWideCharLength(toTranscode);\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (wLent >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[wLent + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < wLent; i++)\n {\n wideCharBuf[i] = toTranscode[i];\n }\n wideCharBuf[wLent] = 0x00;\n\n \/\/ Calc the needed size.\n const size_t neededLen = ::wcstombs(NULL, wideCharBuf, 0);\n if (neededLen == -1)\n {\n delete [] allocatedArray;\n return 0;\n }\n\n retVal = new char[neededLen + 1];\n ::wcstombs(retVal, wideCharBuf, neededLen);\n retVal[neededLen] = 0;\n delete [] allocatedArray;\n }\n else\n {\n retVal = new char[1];\n retVal[0] = 0;\n }\n return retVal;\n}\n\n\nbool IconvLCPTranscoder::transcode( const XMLCh* const toTranscode\n , char* const toFill\n , const unsigned int maxBytes)\n{\n \/\/ Watch for a couple of pyscho corner cases\n if (!toTranscode || !maxBytes)\n {\n toFill[0] = 0;\n return true;\n }\n\n if (!*toTranscode)\n {\n toFill[0] = 0;\n return true;\n }\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (maxBytes >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[maxBytes + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < maxBytes; i++)\n {\n wideCharBuf[i] = toTranscode[i];\n }\n wideCharBuf[maxBytes] = 0x00;\n\n \/\/ Ok, go ahead and try the transcoding. If it fails, then ...\n if (::wcstombs(toFill, wideCharBuf, maxBytes) == -1)\n {\n delete [] allocatedArray;\n return false;\n }\n\n \/\/ Cap it off just in case\n toFill[maxBytes] = 0;\n delete [] allocatedArray;\n return true;\n}\n\n\n\nXMLCh* IconvLCPTranscoder::transcode(const char* const toTranscode)\n{\n XMLCh* retVal = 0;\n if (toTranscode)\n {\n const unsigned int len = calcRequiredSize(toTranscode);\n if (len == 0)\n {\n retVal = new XMLCh[1];\n retVal[0] = 0;\n return retVal;\n }\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (len >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[len + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n ::mbstowcs(wideCharBuf, toTranscode, len);\n retVal = new XMLCh[len + 1];\n for (unsigned int i = 0; i < len; i++)\n {\n retVal[i] = (XMLCh) wideCharBuf[i];\n }\n retVal[len] = 0x00;\n delete [] allocatedArray;\n }\n else\n {\n retVal = new XMLCh[1];\n retVal[0] = 0;\n }\n return retVal;\n}\n\n\nbool IconvLCPTranscoder::transcode( const char* const toTranscode\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n \/\/ Check for a couple of psycho corner cases\n if (!toTranscode || !maxChars)\n {\n toFill[0] = 0;\n return true;\n }\n\n if (!*toTranscode)\n {\n toFill[0] = 0;\n return true;\n }\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (maxChars >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[maxChars + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n if (::mbstowcs(wideCharBuf, toTranscode, maxChars) == -1)\n {\n delete [] allocatedArray;\n return false;\n }\n\n for (unsigned int i = 0; i < maxChars; i++)\n {\n toFill[i] = (XMLCh) wideCharBuf[i];\n }\n toFill[maxChars] = 0x00;\n delete [] allocatedArray;\n return true;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvLCPTranscoder: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvLCPTranscoder::IconvLCPTranscoder()\n{\n}\n\nIconvLCPTranscoder::~IconvLCPTranscoder()\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTranscoder: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvTranscoder::IconvTranscoder(const XMLCh* const encodingName\n , const unsigned int blockSize) :\n\n XMLTranscoder(encodingName, blockSize)\n{\n}\n\nIconvTranscoder::~IconvTranscoder()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTranscoder: Implementation of the virtual transcoder API\n\/\/ ---------------------------------------------------------------------------\nXMLCh IconvTranscoder::transcodeOne(const XMLByte* const srcData\n , const unsigned int srcBytes\n , unsigned int& bytesEaten)\n{\n wchar_t toFill;\n int eaten = ::mbtowc(&toFill, (const char*)srcData, srcBytes);\n if (eaten == -1)\n {\n bytesEaten = 0;\n return 0;\n }\n\n \/\/ Return the bytes we ate and the resulting char.\n bytesEaten = eaten;\n return toFill;\n}\n\n\nunsigned int\nIconvTranscoder::transcodeXML( const XMLByte* const srcData\n , const unsigned int srcCount\n , XMLCh* const toFill\n , const unsigned int maxChars\n , unsigned int& bytesEaten\n , unsigned char* const charSizes)\n{\n \/\/\n \/\/ For this one, because we have to maintain the offset table, we have\n \/\/ to do them one char at a time until we run out of source data.\n \/\/\n unsigned int countIn = 0;\n unsigned int countOut = 0;\n while (countOut < maxChars)\n {\n wchar_t oneWideChar;\n const int bytesEaten =\n ::mbtowc(&oneWideChar, (const char*)&srcData[countIn], srcCount - countIn);\n\n \/\/ We are done, so break out\n if (bytesEaten == -1)\n break;\n toFill[countOut] = (XMLCh) oneWideChar;\n countIn += (unsigned int) bytesEaten;\n countOut++;\n }\n\n \/\/ Give back the counts of eaten and transcoded\n bytesEaten = countIn;\n return countOut;\n}\n<commit_msg>Bug fix - handle maxBytes > length(toTranscode)<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <util\/XMLUniDefs.hpp>\n#include <util\/XMLUni.hpp>\n#include \"IconvTransService.hpp\"\n#include <wchar.h>\n#if defined (XML_GCC) || defined (XML_PTX) || defined (XML_IBMVAOS2)\n#include <wctype.h>\n#endif\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local, const data\n\/\/ ---------------------------------------------------------------------------\nstatic const int gTempBuffArraySize = 1024;\nstatic const XMLCh gMyServiceId[] =\n{\n chLatin_I, chLatin_C, chLatin_o, chLatin_n, chLatin_v, chNull\n};\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local methods\n\/\/ ---------------------------------------------------------------------------\nstatic unsigned int getWideCharLength(const XMLCh* const src)\n{\n if (!src)\n return 0;\n\n unsigned int len = 0;\n const XMLCh* pTmp = src;\n while (*pTmp++)\n len++;\n return len;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvTransService::IconvTransService()\n{\n}\n\nIconvTransService::~IconvTransService()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: The virtual transcoding service API\n\/\/ ---------------------------------------------------------------------------\nint IconvTransService::compareIString( const XMLCh* const comp1\n , const XMLCh* const comp2)\n{\n const XMLCh* cptr1 = comp1;\n const XMLCh* cptr2 = comp2;\n\n while ( (*cptr1 != 0) && (*cptr2 != 0) )\n {\n wint_t wch1 = towupper(*cptr1);\n wint_t wch2 = towupper(*cptr2);\n if (wch1 != wch2)\n break;\n\n cptr1++;\n cptr2++;\n }\n return (int) ( towupper(*cptr1) - towupper(*cptr2) );\n}\n\n\nint IconvTransService::compareNIString( const XMLCh* const comp1\n , const XMLCh* const comp2\n , const unsigned int maxChars)\n{\n unsigned int n = 0;\n const XMLCh* cptr1 = comp1;\n const XMLCh* cptr2 = comp2;\n\n while ( (*cptr1 != 0) && (*cptr2 != 0) && (n < maxChars) )\n {\n wint_t wch1 = towupper(*cptr1);\n wint_t wch2 = towupper(*cptr2);\n if (wch1 != wch2)\n break;\n\n cptr1++;\n cptr2++;\n n++;\n }\n return (int) ( towupper(*cptr1) - towupper(*cptr2) );\n}\n\n\nconst XMLCh* IconvTransService::getId() const\n{\n return gMyServiceId;\n}\n\n\nbool IconvTransService::isSpace(const XMLCh toCheck) const\n{\n return (iswspace(toCheck) != 0);\n}\n\n\nXMLLCPTranscoder* IconvTransService::makeNewLCPTranscoder()\n{\n \/\/ Just allocate a new transcoder of our type\n return new IconvLCPTranscoder;\n}\n\nbool IconvTransService::supportsSrcOfs() const\n{\n return true;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTransService: The protected virtual transcoding service API\n\/\/ ---------------------------------------------------------------------------\nXMLTranscoder*\nIconvTransService::makeNewXMLTranscoder(const XMLCh* const encodingName\n , XMLTransService::Codes& resValue\n , const unsigned int )\n{\n \/\/\n \/\/ NOTE: We don't use the block size here\n \/\/\n \/\/ This is a minimalist transcoding service, that only supports a local\n \/\/ default transcoder. All named encodings return zero as a failure,\n \/\/ which means that only the intrinsic encodings supported by the parser\n \/\/ itself will work for XML data.\n \/\/\n resValue = XMLTransService::UnsupportedEncoding;\n return 0;\n}\n\nvoid IconvTransService::upperCase(XMLCh* const toUpperCase) const\n{\n XMLCh* outPtr = toUpperCase;\n while (*outPtr)\n {\n *outPtr = towupper(*outPtr);\n outPtr++;\n }\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvLCPTranscoder: The virtual transcoder API\n\/\/ ---------------------------------------------------------------------------\nunsigned int IconvLCPTranscoder::calcRequiredSize(const char* const srcText)\n{\n if (!srcText)\n return 0;\n\n const unsigned int retVal = ::mbstowcs(NULL, srcText, 0);\n\n if (retVal == ~0)\n return 0;\n return retVal;\n}\n\n\nunsigned int IconvLCPTranscoder::calcRequiredSize(const XMLCh* const srcText)\n{\n if (!srcText)\n return 0;\n\n unsigned int wLent = getWideCharLength(srcText);\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (wLent >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[wLent + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < wLent; i++)\n {\n wideCharBuf[i] = srcText[i];\n }\n wideCharBuf[wLent] = 0x00;\n\n const unsigned int retVal = ::wcstombs(NULL, wideCharBuf, 0);\n delete [] allocatedArray;\n\n if (retVal == ~0)\n return 0;\n return retVal;\n}\n\n\nchar* IconvLCPTranscoder::transcode(const XMLCh* const toTranscode)\n{\n if (!toTranscode)\n return 0;\n\n char* retVal = 0;\n if (toTranscode)\n {\n unsigned int wLent = getWideCharLength(toTranscode);\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (wLent >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[wLent + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < wLent; i++)\n {\n wideCharBuf[i] = toTranscode[i];\n }\n wideCharBuf[wLent] = 0x00;\n\n \/\/ Calc the needed size.\n const size_t neededLen = ::wcstombs(NULL, wideCharBuf, 0);\n if (neededLen == -1)\n {\n delete [] allocatedArray;\n return 0;\n }\n\n retVal = new char[neededLen + 1];\n ::wcstombs(retVal, wideCharBuf, neededLen);\n retVal[neededLen] = 0;\n delete [] allocatedArray;\n }\n else\n {\n retVal = new char[1];\n retVal[0] = 0;\n }\n return retVal;\n}\n\n\nbool IconvLCPTranscoder::transcode( const XMLCh* const toTranscode\n , char* const toFill\n , const unsigned int maxBytes)\n{\n \/\/ Watch for a couple of pyscho corner cases\n if (!toTranscode || !maxBytes)\n {\n toFill[0] = 0;\n return true;\n }\n\n if (!*toTranscode)\n {\n toFill[0] = 0;\n return true;\n }\n\n unsigned int wLent = getWideCharLength(toTranscode);\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (wLent > maxBytes) {\n wLent = maxBytes;\n }\n\n if (maxBytes >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[maxBytes + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n for (unsigned int i = 0; i < wLent; i++)\n {\n wideCharBuf[i] = toTranscode[i];\n }\n wideCharBuf[wLent] = 0x00;\n\n \/\/ Ok, go ahead and try the transcoding. If it fails, then ...\n if (::wcstombs(toFill, wideCharBuf, maxBytes) == -1)\n {\n delete [] allocatedArray;\n return false;\n }\n\n \/\/ Cap it off just in case\n toFill[wLent] = 0;\n delete [] allocatedArray;\n return true;\n}\n\n\n\nXMLCh* IconvLCPTranscoder::transcode(const char* const toTranscode)\n{\n XMLCh* retVal = 0;\n if (toTranscode)\n {\n const unsigned int len = calcRequiredSize(toTranscode);\n if (len == 0)\n {\n retVal = new XMLCh[1];\n retVal[0] = 0;\n return retVal;\n }\n\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (len >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[len + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n ::mbstowcs(wideCharBuf, toTranscode, len);\n retVal = new XMLCh[len + 1];\n for (unsigned int i = 0; i < len; i++)\n {\n retVal[i] = (XMLCh) wideCharBuf[i];\n }\n retVal[len] = 0x00;\n delete [] allocatedArray;\n }\n else\n {\n retVal = new XMLCh[1];\n retVal[0] = 0;\n }\n return retVal;\n}\n\n\nbool IconvLCPTranscoder::transcode( const char* const toTranscode\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n \/\/ Check for a couple of psycho corner cases\n if (!toTranscode || !maxChars)\n {\n toFill[0] = 0;\n return true;\n }\n\n if (!*toTranscode)\n {\n toFill[0] = 0;\n return true;\n }\n\n unsigned int len = calcRequiredSize(toTranscode);\n wchar_t tmpWideCharArr[gTempBuffArraySize];\n wchar_t* allocatedArray = 0;\n wchar_t* wideCharBuf = 0;\n\n if (len > maxChars) {\n len = maxChars;\n }\n\n if (maxChars >= gTempBuffArraySize)\n wideCharBuf = allocatedArray = new wchar_t[maxChars + 1];\n else\n wideCharBuf = tmpWideCharArr;\n\n if (::mbstowcs(wideCharBuf, toTranscode, maxChars) == -1)\n {\n delete [] allocatedArray;\n return false;\n }\n\n for (unsigned int i = 0; i < len; i++)\n {\n toFill[i] = (XMLCh) wideCharBuf[i];\n }\n toFill[len] = 0x00;\n delete [] allocatedArray;\n return true;\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvLCPTranscoder: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvLCPTranscoder::IconvLCPTranscoder()\n{\n}\n\nIconvLCPTranscoder::~IconvLCPTranscoder()\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTranscoder: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nIconvTranscoder::IconvTranscoder(const XMLCh* const encodingName\n , const unsigned int blockSize) :\n\n XMLTranscoder(encodingName, blockSize)\n{\n}\n\nIconvTranscoder::~IconvTranscoder()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ IconvTranscoder: Implementation of the virtual transcoder API\n\/\/ ---------------------------------------------------------------------------\nXMLCh IconvTranscoder::transcodeOne(const XMLByte* const srcData\n , const unsigned int srcBytes\n , unsigned int& bytesEaten)\n{\n wchar_t toFill;\n int eaten = ::mbtowc(&toFill, (const char*)srcData, srcBytes);\n if (eaten == -1)\n {\n bytesEaten = 0;\n return 0;\n }\n\n \/\/ Return the bytes we ate and the resulting char.\n bytesEaten = eaten;\n return toFill;\n}\n\n\nunsigned int\nIconvTranscoder::transcodeXML( const XMLByte* const srcData\n , const unsigned int srcCount\n , XMLCh* const toFill\n , const unsigned int maxChars\n , unsigned int& bytesEaten\n , unsigned char* const charSizes)\n{\n \/\/\n \/\/ For this one, because we have to maintain the offset table, we have\n \/\/ to do them one char at a time until we run out of source data.\n \/\/\n unsigned int countIn = 0;\n unsigned int countOut = 0;\n while (countOut < maxChars)\n {\n wchar_t oneWideChar;\n const int bytesEaten =\n ::mbtowc(&oneWideChar, (const char*)&srcData[countIn], srcCount - countIn);\n\n \/\/ We are done, so break out\n if (bytesEaten == -1)\n break;\n toFill[countOut] = (XMLCh) oneWideChar;\n countIn += (unsigned int) bytesEaten;\n countOut++;\n }\n\n \/\/ Give back the counts of eaten and transcoded\n bytesEaten = countIn;\n return countOut;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"completionwidget.h\"\n#include \"completionsupport.h\"\n#include \"icompletioncollector.h\"\n\n#include <texteditor\/itexteditable.h>\n\n#include <utils\/faketooltip.h>\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QEvent>\n#include <QtGui\/QApplication>\n#include <QtGui\/QDesktopWidget>\n#include <QtGui\/QKeyEvent>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QScrollBar>\n#include <QtGui\/QLabel>\n#include <QtGui\/QStylePainter>\n#include <QtGui\/QToolTip>\n\n#include <limits.h>\n\nusing namespace TextEditor;\nusing namespace TextEditor::Internal;\n\n#define NUMBER_OF_VISIBLE_ITEMS 10\n\nnamespace TextEditor {\nnamespace Internal {\n\nclass AutoCompletionModel : public QAbstractListModel\n{\npublic:\n AutoCompletionModel(QObject *parent);\n\n inline const CompletionItem &itemAt(const QModelIndex &index) const\n { return m_items.at(index.row()); }\n\n void setItems(const QList<CompletionItem> &items);\n\n int rowCount(const QModelIndex &parent = QModelIndex()) const;\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;\n\nprivate:\n QList<CompletionItem> m_items;\n};\n\n\nclass CompletionInfoFrame : public Utils::FakeToolTip\n{\npublic:\n CompletionInfoFrame(QWidget *parent = 0) :\n Utils::FakeToolTip(parent),\n m_label(new QLabel(this))\n {\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setMargin(0);\n layout->setSpacing(0);\n layout->addWidget(m_label);\n\n m_label->setForegroundRole(QPalette::ToolTipText);\n m_label->setBackgroundRole(QPalette::ToolTipBase);\n }\n\n void setText(const QString &text)\n {\n m_label->setText(text);\n }\n\nprivate:\n QLabel *m_label;\n};\n\n\n} \/\/ namespace Internal\n} \/\/ namespace TextEditor\n\n\nAutoCompletionModel::AutoCompletionModel(QObject *parent)\n : QAbstractListModel(parent)\n{\n}\n\nvoid AutoCompletionModel::setItems(const QList<CompletionItem> &items)\n{\n m_items = items;\n reset();\n}\n\nint AutoCompletionModel::rowCount(const QModelIndex &) const\n{\n return m_items.count();\n}\n\nQVariant AutoCompletionModel::data(const QModelIndex &index, int role) const\n{\n if (index.row() >= m_items.count())\n return QVariant();\n\n if (role == Qt::DisplayRole) {\n return itemAt(index).text;\n } else if (role == Qt::DecorationRole) {\n return itemAt(index).icon;\n } else if (role == Qt::WhatsThisRole) {\n return itemAt(index).details;\n }\n\n return QVariant();\n}\n\n\nCompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor)\n : QFrame(0, Qt::Popup),\n m_support(support),\n m_editor(editor),\n m_completionListView(new CompletionListView(support, editor, this))\n{\n \/\/ We disable the frame on this list view and use a QFrame around it instead.\n \/\/ This improves the look with QGTKStyle.\n#ifndef Q_WS_MAC\n setFrameStyle(m_completionListView->frameStyle());\n#endif\n m_completionListView->setFrameStyle(QFrame::NoFrame);\n\n setObjectName(QLatin1String(\"m_popupFrame\"));\n setAttribute(Qt::WA_DeleteOnClose);\n setMinimumSize(1, 1);\n\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setMargin(0);\n\n layout->addWidget(m_completionListView);\n setFocusProxy(m_completionListView);\n\n connect(m_completionListView, SIGNAL(itemSelected(TextEditor::CompletionItem)),\n this, SIGNAL(itemSelected(TextEditor::CompletionItem)));\n connect(m_completionListView, SIGNAL(completionListClosed()),\n this, SIGNAL(completionListClosed()));\n connect(m_completionListView, SIGNAL(activated(QModelIndex)),\n SLOT(closeList(QModelIndex)));\n connect(editor, SIGNAL(contentsChangedBecauseOfUndo()),\n this, SLOT(closeList()));\n}\n\nCompletionWidget::~CompletionWidget()\n{\n}\n\nvoid CompletionWidget::setQuickFix(bool quickFix)\n{\n m_completionListView->setQuickFix(quickFix);\n}\n\nvoid CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionitems)\n{\n m_completionListView->setCompletionItems(completionitems);\n}\n\nvoid CompletionWidget::closeList(const QModelIndex &index)\n{\n m_completionListView->closeList(index);\n close();\n}\n\nvoid CompletionWidget::showCompletions(int startPos)\n{\n ensurePolished();\n updatePositionAndSize(startPos);\n show();\n setFocus();\n}\n\nvoid CompletionWidget::updatePositionAndSize(int startPos)\n{\n \/\/ Determine size by calculating the space of the visible items\n QAbstractItemModel *model = m_completionListView->model();\n int visibleItems = model->rowCount();\n if (visibleItems > NUMBER_OF_VISIBLE_ITEMS)\n visibleItems = NUMBER_OF_VISIBLE_ITEMS;\n\n const QStyleOptionViewItem &option = m_completionListView->viewOptions();\n\n QSize shint;\n for (int i = 0; i < visibleItems; ++i) {\n QSize tmp = m_completionListView->itemDelegate()->sizeHint(option, model->index(i, 0));\n if (shint.width() < tmp.width())\n shint = tmp;\n }\n\n const int fw = frameWidth();\n const int width = shint.width() + fw * 2 + 30;\n const int height = shint.height() * visibleItems + fw * 2;\n\n \/\/ Determine the position, keeping the popup on the screen\n const QRect cursorRect = m_editor->cursorRect(startPos);\n const QDesktopWidget *desktop = QApplication::desktop();\n\n QWidget *editorWidget = m_editor->widget();\n\n#ifdef Q_WS_MAC\n const QRect screen = desktop->availableGeometry(desktop->screenNumber(editorWidget));\n#else\n const QRect screen = desktop->screenGeometry(desktop->screenNumber(editorWidget));\n#endif\n\n QPoint pos = cursorRect.bottomLeft();\n pos.rx() -= 16 + fw; \/\/ Space for the icons\n\n if (pos.y() + height > screen.bottom())\n pos.setY(cursorRect.top() - height);\n\n if (pos.x() + width > screen.right())\n pos.setX(screen.right() - width);\n\n setGeometry(pos.x(), pos.y(), width, height);\n}\n\nCompletionListView::CompletionListView(CompletionSupport *support, ITextEditable *editor, CompletionWidget *completionWidget)\n : QListView(completionWidget),\n m_blockFocusOut(false),\n m_quickFix(false),\n m_editor(editor),\n m_editorWidget(editor->widget()),\n m_completionWidget(completionWidget),\n m_model(new AutoCompletionModel(this)),\n m_support(support)\n{\n QTC_ASSERT(m_editorWidget, return);\n\n m_infoTimer.setInterval(1000);\n m_infoTimer.setSingleShot(true);\n connect(&m_infoTimer, SIGNAL(timeout()), SLOT(maybeShowInfoTip()));\n\n setAttribute(Qt::WA_MacShowFocusRect, false);\n setUniformItemSizes(true);\n setSelectionBehavior(QAbstractItemView::SelectItems);\n setSelectionMode(QAbstractItemView::SingleSelection);\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setMinimumSize(1, 1);\n setModel(m_model);\n#ifdef Q_WS_MAC\n if (horizontalScrollBar())\n horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);\n if (verticalScrollBar())\n verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);\n#endif\n}\n\nCompletionListView::~CompletionListView()\n{\n}\n\nvoid CompletionListView::maybeShowInfoTip()\n{\n QModelIndex current = currentIndex();\n if (!current.isValid())\n return;\n QString infoTip = current.data(Qt::WhatsThisRole).toString();\n\n if (infoTip.isEmpty()) {\n delete m_infoFrame.data();\n m_infoTimer.setInterval(200);\n return;\n }\n\n if (m_infoFrame.isNull())\n m_infoFrame = new CompletionInfoFrame(this);\n\n\n QRect r = rectForIndex(current);\n m_infoFrame->move(\n (parentWidget()->mapToGlobal(\n parentWidget()->rect().topRight())).x() + 3,\n mapToGlobal(r.topRight()).y() - verticalOffset()\n );\n m_infoFrame->setText(infoTip);\n m_infoFrame->adjustSize();\n m_infoFrame->show();\n m_infoFrame->raise();\n\n m_infoTimer.setInterval(0);\n}\n\nvoid CompletionListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)\n{\n QListView::currentChanged(current, previous);\n m_infoTimer.start();\n}\n\n\nbool CompletionListView::event(QEvent *e)\n{\n if (m_blockFocusOut)\n return QListView::event(e);\n\n bool forwardKeys = true;\n if (e->type() == QEvent::FocusOut) {\n QModelIndex index;\n#if defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA)\n QFocusEvent *fe = static_cast<QFocusEvent *>(e);\n if (fe->reason() == Qt::OtherFocusReason) {\n \/\/ Qt\/carbon workaround\n \/\/ focus out is received before the key press event.\n index = currentIndex();\n }\n#endif\n m_completionWidget->closeList(index);\n return true;\n } else if (e->type() == QEvent::ShortcutOverride) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(e);\n switch (ke->key()) {\n case Qt::Key_N:\n case Qt::Key_P:\n \/\/ select next\/previous completion\n if (ke->modifiers() == Qt::ControlModifier)\n {\n e->accept();\n int change = (ke->key() == Qt::Key_N) ? 1 : -1;\n int nrows = model()->rowCount();\n int row = currentIndex().row();\n int newRow = (row + change + nrows) % nrows;\n if (newRow == row + change || !ke->isAutoRepeat())\n setCurrentIndex(m_model->index(newRow));\n return true;\n }\n }\n } else if (e->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(e);\n switch (ke->key()) {\n case Qt::Key_N:\n case Qt::Key_P:\n \/\/ select next\/previous completion - so don't pass on to editor\n if (ke->modifiers() == Qt::ControlModifier)\n forwardKeys = false;\n break;\n\n case Qt::Key_Escape:\n m_completionWidget->closeList();\n return true;\n\n case Qt::Key_Right:\n case Qt::Key_Left:\n break;\n\n case Qt::Key_Tab:\n case Qt::Key_Return:\n \/\/independently from style, accept current entry if return is pressed\n if (qApp->focusWidget() == this)\n m_completionWidget->closeList(currentIndex());\n return true;\n\n case Qt::Key_Up:\n if (!ke->isAutoRepeat()\n && currentIndex().row() == 0) {\n setCurrentIndex(model()->index(model()->rowCount()-1, 0));\n return true;\n }\n forwardKeys = false;\n break;\n\n case Qt::Key_Down:\n if (!ke->isAutoRepeat()\n && currentIndex().row() == model()->rowCount()-1) {\n setCurrentIndex(model()->index(0, 0));\n return true;\n }\n forwardKeys = false;\n break;\n\n case Qt::Key_Enter:\n case Qt::Key_PageDown:\n case Qt::Key_PageUp:\n forwardKeys = false;\n break;\n\n default:\n \/\/ if a key is forwarded, completion widget is re-opened and selected item is reset to first,\n \/\/ so only forward keys that insert text and refine the completed item\n forwardKeys = !ke->text().isEmpty();\n break;\n }\n\n if (forwardKeys && ! m_quickFix) {\n m_blockFocusOut = true;\n QApplication::sendEvent(m_editorWidget, e);\n m_blockFocusOut = false;\n\n \/\/ Have the completion support update the list of items\n m_support->autoComplete(m_editor, false);\n\n return true;\n }\n }\n return QListView::event(e);\n}\n\nvoid CompletionListView::keyboardSearch(const QString &search)\n{\n Q_UNUSED(search)\n}\n\nvoid CompletionListView::setQuickFix(bool quickFix)\n{\n m_quickFix = quickFix;\n}\n\nvoid CompletionListView::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems)\n{\n m_model->setItems(completionItems);\n\n \/\/ Select the first of the most relevant completion items\n int relevance = INT_MIN;\n int mostRelevantIndex = 0;\n for (int i = 0; i < completionItems.size(); ++i) {\n const CompletionItem &item = completionItems.at(i);\n if (item.relevance > relevance) {\n relevance = item.relevance;\n mostRelevantIndex = i;\n }\n }\n\n setCurrentIndex(m_model->index(mostRelevantIndex));\n}\n\nvoid CompletionListView::closeList(const QModelIndex &index)\n{\n m_blockFocusOut = true;\n\n if (index.isValid())\n emit itemSelected(m_model->itemAt(index));\n\n emit completionListClosed();\n\n m_blockFocusOut = false;\n}\n<commit_msg>Forward Home and End keys to the editor when completing<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"completionwidget.h\"\n#include \"completionsupport.h\"\n#include \"icompletioncollector.h\"\n\n#include <texteditor\/itexteditable.h>\n\n#include <utils\/faketooltip.h>\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QEvent>\n#include <QtGui\/QApplication>\n#include <QtGui\/QDesktopWidget>\n#include <QtGui\/QKeyEvent>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QScrollBar>\n#include <QtGui\/QLabel>\n#include <QtGui\/QStylePainter>\n#include <QtGui\/QToolTip>\n\n#include <limits.h>\n\nusing namespace TextEditor;\nusing namespace TextEditor::Internal;\n\n#define NUMBER_OF_VISIBLE_ITEMS 10\n\nnamespace TextEditor {\nnamespace Internal {\n\nclass AutoCompletionModel : public QAbstractListModel\n{\npublic:\n AutoCompletionModel(QObject *parent);\n\n inline const CompletionItem &itemAt(const QModelIndex &index) const\n { return m_items.at(index.row()); }\n\n void setItems(const QList<CompletionItem> &items);\n\n int rowCount(const QModelIndex &parent = QModelIndex()) const;\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;\n\nprivate:\n QList<CompletionItem> m_items;\n};\n\n\nclass CompletionInfoFrame : public Utils::FakeToolTip\n{\npublic:\n CompletionInfoFrame(QWidget *parent = 0) :\n Utils::FakeToolTip(parent),\n m_label(new QLabel(this))\n {\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setMargin(0);\n layout->setSpacing(0);\n layout->addWidget(m_label);\n\n m_label->setForegroundRole(QPalette::ToolTipText);\n m_label->setBackgroundRole(QPalette::ToolTipBase);\n }\n\n void setText(const QString &text)\n {\n m_label->setText(text);\n }\n\nprivate:\n QLabel *m_label;\n};\n\n\n} \/\/ namespace Internal\n} \/\/ namespace TextEditor\n\n\nAutoCompletionModel::AutoCompletionModel(QObject *parent)\n : QAbstractListModel(parent)\n{\n}\n\nvoid AutoCompletionModel::setItems(const QList<CompletionItem> &items)\n{\n m_items = items;\n reset();\n}\n\nint AutoCompletionModel::rowCount(const QModelIndex &) const\n{\n return m_items.count();\n}\n\nQVariant AutoCompletionModel::data(const QModelIndex &index, int role) const\n{\n if (index.row() >= m_items.count())\n return QVariant();\n\n if (role == Qt::DisplayRole) {\n return itemAt(index).text;\n } else if (role == Qt::DecorationRole) {\n return itemAt(index).icon;\n } else if (role == Qt::WhatsThisRole) {\n return itemAt(index).details;\n }\n\n return QVariant();\n}\n\n\nCompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor)\n : QFrame(0, Qt::Popup),\n m_support(support),\n m_editor(editor),\n m_completionListView(new CompletionListView(support, editor, this))\n{\n \/\/ We disable the frame on this list view and use a QFrame around it instead.\n \/\/ This improves the look with QGTKStyle.\n#ifndef Q_WS_MAC\n setFrameStyle(m_completionListView->frameStyle());\n#endif\n m_completionListView->setFrameStyle(QFrame::NoFrame);\n\n setObjectName(QLatin1String(\"m_popupFrame\"));\n setAttribute(Qt::WA_DeleteOnClose);\n setMinimumSize(1, 1);\n\n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setMargin(0);\n\n layout->addWidget(m_completionListView);\n setFocusProxy(m_completionListView);\n\n connect(m_completionListView, SIGNAL(itemSelected(TextEditor::CompletionItem)),\n this, SIGNAL(itemSelected(TextEditor::CompletionItem)));\n connect(m_completionListView, SIGNAL(completionListClosed()),\n this, SIGNAL(completionListClosed()));\n connect(m_completionListView, SIGNAL(activated(QModelIndex)),\n SLOT(closeList(QModelIndex)));\n connect(editor, SIGNAL(contentsChangedBecauseOfUndo()),\n this, SLOT(closeList()));\n}\n\nCompletionWidget::~CompletionWidget()\n{\n}\n\nvoid CompletionWidget::setQuickFix(bool quickFix)\n{\n m_completionListView->setQuickFix(quickFix);\n}\n\nvoid CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionitems)\n{\n m_completionListView->setCompletionItems(completionitems);\n}\n\nvoid CompletionWidget::closeList(const QModelIndex &index)\n{\n m_completionListView->closeList(index);\n close();\n}\n\nvoid CompletionWidget::showCompletions(int startPos)\n{\n ensurePolished();\n updatePositionAndSize(startPos);\n show();\n setFocus();\n}\n\nvoid CompletionWidget::updatePositionAndSize(int startPos)\n{\n \/\/ Determine size by calculating the space of the visible items\n QAbstractItemModel *model = m_completionListView->model();\n int visibleItems = model->rowCount();\n if (visibleItems > NUMBER_OF_VISIBLE_ITEMS)\n visibleItems = NUMBER_OF_VISIBLE_ITEMS;\n\n const QStyleOptionViewItem &option = m_completionListView->viewOptions();\n\n QSize shint;\n for (int i = 0; i < visibleItems; ++i) {\n QSize tmp = m_completionListView->itemDelegate()->sizeHint(option, model->index(i, 0));\n if (shint.width() < tmp.width())\n shint = tmp;\n }\n\n const int fw = frameWidth();\n const int width = shint.width() + fw * 2 + 30;\n const int height = shint.height() * visibleItems + fw * 2;\n\n \/\/ Determine the position, keeping the popup on the screen\n const QRect cursorRect = m_editor->cursorRect(startPos);\n const QDesktopWidget *desktop = QApplication::desktop();\n\n QWidget *editorWidget = m_editor->widget();\n\n#ifdef Q_WS_MAC\n const QRect screen = desktop->availableGeometry(desktop->screenNumber(editorWidget));\n#else\n const QRect screen = desktop->screenGeometry(desktop->screenNumber(editorWidget));\n#endif\n\n QPoint pos = cursorRect.bottomLeft();\n pos.rx() -= 16 + fw; \/\/ Space for the icons\n\n if (pos.y() + height > screen.bottom())\n pos.setY(cursorRect.top() - height);\n\n if (pos.x() + width > screen.right())\n pos.setX(screen.right() - width);\n\n setGeometry(pos.x(), pos.y(), width, height);\n}\n\nCompletionListView::CompletionListView(CompletionSupport *support, ITextEditable *editor, CompletionWidget *completionWidget)\n : QListView(completionWidget),\n m_blockFocusOut(false),\n m_quickFix(false),\n m_editor(editor),\n m_editorWidget(editor->widget()),\n m_completionWidget(completionWidget),\n m_model(new AutoCompletionModel(this)),\n m_support(support)\n{\n QTC_ASSERT(m_editorWidget, return);\n\n m_infoTimer.setInterval(1000);\n m_infoTimer.setSingleShot(true);\n connect(&m_infoTimer, SIGNAL(timeout()), SLOT(maybeShowInfoTip()));\n\n setAttribute(Qt::WA_MacShowFocusRect, false);\n setUniformItemSizes(true);\n setSelectionBehavior(QAbstractItemView::SelectItems);\n setSelectionMode(QAbstractItemView::SingleSelection);\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setMinimumSize(1, 1);\n setModel(m_model);\n#ifdef Q_WS_MAC\n if (horizontalScrollBar())\n horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);\n if (verticalScrollBar())\n verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);\n#endif\n}\n\nCompletionListView::~CompletionListView()\n{\n}\n\nvoid CompletionListView::maybeShowInfoTip()\n{\n QModelIndex current = currentIndex();\n if (!current.isValid())\n return;\n QString infoTip = current.data(Qt::WhatsThisRole).toString();\n\n if (infoTip.isEmpty()) {\n delete m_infoFrame.data();\n m_infoTimer.setInterval(200);\n return;\n }\n\n if (m_infoFrame.isNull())\n m_infoFrame = new CompletionInfoFrame(this);\n\n\n QRect r = rectForIndex(current);\n m_infoFrame->move(\n (parentWidget()->mapToGlobal(\n parentWidget()->rect().topRight())).x() + 3,\n mapToGlobal(r.topRight()).y() - verticalOffset()\n );\n m_infoFrame->setText(infoTip);\n m_infoFrame->adjustSize();\n m_infoFrame->show();\n m_infoFrame->raise();\n\n m_infoTimer.setInterval(0);\n}\n\nvoid CompletionListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)\n{\n QListView::currentChanged(current, previous);\n m_infoTimer.start();\n}\n\n\nbool CompletionListView::event(QEvent *e)\n{\n if (m_blockFocusOut)\n return QListView::event(e);\n\n bool forwardKeys = true;\n if (e->type() == QEvent::FocusOut) {\n QModelIndex index;\n#if defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA)\n QFocusEvent *fe = static_cast<QFocusEvent *>(e);\n if (fe->reason() == Qt::OtherFocusReason) {\n \/\/ Qt\/carbon workaround\n \/\/ focus out is received before the key press event.\n index = currentIndex();\n }\n#endif\n m_completionWidget->closeList(index);\n return true;\n } else if (e->type() == QEvent::ShortcutOverride) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(e);\n switch (ke->key()) {\n case Qt::Key_N:\n case Qt::Key_P:\n \/\/ select next\/previous completion\n if (ke->modifiers() == Qt::ControlModifier)\n {\n e->accept();\n int change = (ke->key() == Qt::Key_N) ? 1 : -1;\n int nrows = model()->rowCount();\n int row = currentIndex().row();\n int newRow = (row + change + nrows) % nrows;\n if (newRow == row + change || !ke->isAutoRepeat())\n setCurrentIndex(m_model->index(newRow));\n return true;\n }\n }\n } else if (e->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast<QKeyEvent *>(e);\n switch (ke->key()) {\n case Qt::Key_N:\n case Qt::Key_P:\n \/\/ select next\/previous completion - so don't pass on to editor\n if (ke->modifiers() == Qt::ControlModifier)\n forwardKeys = false;\n break;\n\n case Qt::Key_Escape:\n m_completionWidget->closeList();\n return true;\n\n case Qt::Key_Right:\n case Qt::Key_Left:\n case Qt::Key_Home:\n case Qt::Key_End:\n \/\/ We want these navigation keys to work in the editor, so forward them\n break;\n\n case Qt::Key_Tab:\n case Qt::Key_Return:\n \/\/independently from style, accept current entry if return is pressed\n if (qApp->focusWidget() == this)\n m_completionWidget->closeList(currentIndex());\n return true;\n\n case Qt::Key_Up:\n if (!ke->isAutoRepeat()\n && currentIndex().row() == 0) {\n setCurrentIndex(model()->index(model()->rowCount()-1, 0));\n return true;\n }\n forwardKeys = false;\n break;\n\n case Qt::Key_Down:\n if (!ke->isAutoRepeat()\n && currentIndex().row() == model()->rowCount()-1) {\n setCurrentIndex(model()->index(0, 0));\n return true;\n }\n forwardKeys = false;\n break;\n\n case Qt::Key_Enter:\n case Qt::Key_PageDown:\n case Qt::Key_PageUp:\n forwardKeys = false;\n break;\n\n default:\n \/\/ if a key is forwarded, completion widget is re-opened and selected item is reset to first,\n \/\/ so only forward keys that insert text and refine the completed item\n forwardKeys = !ke->text().isEmpty();\n break;\n }\n\n if (forwardKeys && ! m_quickFix) {\n m_blockFocusOut = true;\n QApplication::sendEvent(m_editorWidget, e);\n m_blockFocusOut = false;\n\n \/\/ Have the completion support update the list of items\n m_support->autoComplete(m_editor, false);\n\n return true;\n }\n }\n return QListView::event(e);\n}\n\nvoid CompletionListView::keyboardSearch(const QString &search)\n{\n Q_UNUSED(search)\n}\n\nvoid CompletionListView::setQuickFix(bool quickFix)\n{\n m_quickFix = quickFix;\n}\n\nvoid CompletionListView::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems)\n{\n m_model->setItems(completionItems);\n\n \/\/ Select the first of the most relevant completion items\n int relevance = INT_MIN;\n int mostRelevantIndex = 0;\n for (int i = 0; i < completionItems.size(); ++i) {\n const CompletionItem &item = completionItems.at(i);\n if (item.relevance > relevance) {\n relevance = item.relevance;\n mostRelevantIndex = i;\n }\n }\n\n setCurrentIndex(m_model->index(mostRelevantIndex));\n}\n\nvoid CompletionListView::closeList(const QModelIndex &index)\n{\n m_blockFocusOut = true;\n\n if (index.isValid())\n emit itemSelected(m_model->itemAt(index));\n\n emit completionListClosed();\n\n m_blockFocusOut = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include \"ICUMsgLoader.hpp\"\n\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) \n:fRootBundle(0)\n,fDomainBundle(0)\n{\n \/\/ validation on msgDomain\n if (XMLString::compareString(msgDomain, XMLUni::fgXMLErrDomain)\n && XMLString::compareString(msgDomain, XMLUni::fgExceptDomain)\n && XMLString::compareString(msgDomain, XMLUni::fgValidityDomain))\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/\/\n \/\/ we hardcode the path for \"root.res\" for now\n \/\/ assuming that Makefile would copy root.res from $ICUROOT\/bin to $XERCESCROOT\/bin\n \/\/\n char tempBuf[1024];\n strcpy(tempBuf, getenv(\"XERCESCROOT\"));\n strcat(tempBuf, \"\/bin\/root.res\");\n \n UErrorCode err = U_ZERO_ERROR;\n fRootBundle = ures_open(tempBuf, 0, &err);\n if (!U_SUCCESS(err) || fRootBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n \n \/\/strip off path information, if any\n int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n char *domainName = XMLString::transcode(&(msgDomain[index + 1]));\n\n \/\/ get the resource bundle for the domain\n fDomainBundle = ures_getByKey(fRootBundle, domainName, NULL, &err);\n\n delete [] domainName;\n \n if (!U_SUCCESS(err) || fDomainBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fRootBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n<commit_msg>XMLString::equals() to replace XMLString::compareString()<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.3 2002\/10\/02 17:08:50 peiyongz\n * XMLString::equals() to replace XMLString::compareString()\n *\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include \"ICUMsgLoader.hpp\"\n\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) \n:fRootBundle(0)\n,fDomainBundle(0)\n{\n \/\/ validation on msgDomain\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/\/\n \/\/ we hardcode the path for \"root.res\" for now\n \/\/ assuming that Makefile would copy root.res from $ICUROOT\/bin to $XERCESCROOT\/bin\n \/\/\n char tempBuf[1024];\n strcpy(tempBuf, getenv(\"XERCESCROOT\"));\n strcat(tempBuf, \"\/bin\/root.res\");\n \n UErrorCode err = U_ZERO_ERROR;\n fRootBundle = ures_open(tempBuf, 0, &err);\n if (!U_SUCCESS(err) || fRootBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n \n \/\/strip off path information, if any\n int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n char *domainName = XMLString::transcode(&(msgDomain[index + 1]));\n\n \/\/ get the resource bundle for the domain\n fDomainBundle = ures_getByKey(fRootBundle, domainName, NULL, &err);\n\n delete [] domainName;\n \n if (!U_SUCCESS(err) || fDomainBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fRootBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_consistent_sizes.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive_finite.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_nonnegative.hpp>\n#include <stan\/math\/prim\/scal\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/scal\/fun\/multiply_log.hpp>\n#include <stan\/math\/prim\/scal\/fun\/digamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/scal\/prob\/poisson_lpmf.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n \/\/Exposing to let me us this in tests\n constexpr double neg_binomial_2_phi_cutoff = 1e5;\n}\n\n\/\/ NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0]\ntemplate <bool propto, typename T_n, typename T_location, typename T_precision>\nreturn_type_t<T_location, T_precision> neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n using T_partials_return = partials_return_t<T_n, T_location, T_precision>;\n\n static const char* function = \"neg_binomial_2_lpmf\";\n\n if (size_zero(n, mu, phi)) {\n return 0.0;\n }\n\n T_partials_return logp(0.0);\n check_nonnegative(function, \"Failures variable\", n);\n check_positive_finite(function, \"Location parameter\", mu);\n check_positive_finite(function, \"Precision parameter\", phi);\n check_consistent_sizes(function, \"Failures variable\", n, \"Location parameter\",\n mu, \"Precision parameter\", phi);\n\n if (!include_summand<propto, T_location, T_precision>::value) {\n return 0.0;\n }\n\n using std::log;\n\n scalar_seq_view<T_n> n_vec(n);\n scalar_seq_view<T_location> mu_vec(mu);\n scalar_seq_view<T_precision> phi_vec(phi);\n size_t size = max_size(n, mu, phi);\n\n operands_and_partials<T_location, T_precision> ops_partials(mu, phi);\n\n size_t len_ep = max_size(mu, phi);\n size_t len_np = max_size(n, phi);\n\n VectorBuilder<true, T_partials_return, T_location> mu__(length(mu));\n for (size_t i = 0, size = length(mu); i < size; ++i) {\n mu__[i] = value_of(mu_vec[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_precision> phi__(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n phi__[i] = value_of(phi_vec[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_precision> log_phi(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n log_phi[i] = log(phi__[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_location, T_precision>\n log_mu_plus_phi(len_ep);\n for (size_t i = 0; i < len_ep; ++i) {\n log_mu_plus_phi[i] = log(mu__[i] + phi__[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np);\n for (size_t i = 0; i < len_np; ++i) {\n n_plus_phi[i] = n_vec[i] + phi__[i];\n }\n\n for (size_t i = 0; i < size; i++) {\n if (include_summand<propto>::value) {\n logp -= lgamma(n_vec[i] + 1.0);\n }\n if (include_summand<propto, T_precision>::value) {\n logp += multiply_log(phi__[i], phi__[i]) - lgamma(phi__[i]);\n }\n if (include_summand<propto, T_location, T_precision>::value) {\n logp -= (n_plus_phi[i]) * log_mu_plus_phi[i];\n }\n if (include_summand<propto, T_location>::value) {\n logp += multiply_log(n_vec[i], mu__[i]);\n }\n if (include_summand<propto, T_precision>::value) {\n logp += lgamma(n_plus_phi[i]);\n }\n\n \/\/ if phi is large we probably overflow, defer to Poisson:\n if (phi__[i] > internal::neg_binomial_2_phi_cutoff) {\n logp = poisson_lpmf(n_vec[i], mu__[i]);\n }\n\n if (!is_constant_all<T_location>::value) {\n ops_partials.edge1_.partials_[i]\n += n_vec[i] \/ mu__[i] - (n_vec[i] + phi__[i]) \/ (mu__[i] + phi__[i]);\n }\n if (!is_constant_all<T_precision>::value) {\n ops_partials.edge2_.partials_[i]\n += 1.0 - n_plus_phi[i] \/ (mu__[i] + phi__[i]) + log_phi[i]\n - log_mu_plus_phi[i] - digamma(phi__[i]) + digamma(n_plus_phi[i]);\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_location, typename T_precision>\ninline return_type_t<T_location, T_precision> neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n return neg_binomial_2_lpmf<false>(n, mu, phi);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>Phi cutoff no longer overrides logp accumulator<commit_after>#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_consistent_sizes.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_positive_finite.hpp>\n#include <stan\/math\/prim\/scal\/err\/check_nonnegative.hpp>\n#include <stan\/math\/prim\/scal\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/scal\/fun\/multiply_log.hpp>\n#include <stan\/math\/prim\/scal\/fun\/digamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/scal\/prob\/poisson_lpmf.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n \/\/Exposing to let me us this in tests\n constexpr double neg_binomial_2_phi_cutoff = 1e5;\n}\n\n\/\/ NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0]\ntemplate <bool propto, typename T_n, typename T_location, typename T_precision>\nreturn_type_t<T_location, T_precision> neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n using T_partials_return = partials_return_t<T_n, T_location, T_precision>;\n\n static const char* function = \"neg_binomial_2_lpmf\";\n\n if (size_zero(n, mu, phi)) {\n return 0.0;\n }\n\n T_partials_return logp(0.0);\n check_nonnegative(function, \"Failures variable\", n);\n check_positive_finite(function, \"Location parameter\", mu);\n check_positive_finite(function, \"Precision parameter\", phi);\n check_consistent_sizes(function, \"Failures variable\", n, \"Location parameter\",\n mu, \"Precision parameter\", phi);\n\n if (!include_summand<propto, T_location, T_precision>::value) {\n return 0.0;\n }\n\n using std::log;\n\n scalar_seq_view<T_n> n_vec(n);\n scalar_seq_view<T_location> mu_vec(mu);\n scalar_seq_view<T_precision> phi_vec(phi);\n size_t size = max_size(n, mu, phi);\n\n operands_and_partials<T_location, T_precision> ops_partials(mu, phi);\n\n size_t len_ep = max_size(mu, phi);\n size_t len_np = max_size(n, phi);\n\n VectorBuilder<true, T_partials_return, T_location> mu__(length(mu));\n for (size_t i = 0, size = length(mu); i < size; ++i) {\n mu__[i] = value_of(mu_vec[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_precision> phi__(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n phi__[i] = value_of(phi_vec[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_precision> log_phi(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n log_phi[i] = log(phi__[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_location, T_precision>\n log_mu_plus_phi(len_ep);\n for (size_t i = 0; i < len_ep; ++i) {\n log_mu_plus_phi[i] = log(mu__[i] + phi__[i]);\n }\n\n VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np);\n for (size_t i = 0; i < len_np; ++i) {\n n_plus_phi[i] = n_vec[i] + phi__[i];\n }\n\n for (size_t i = 0; i < size; i++) {\n \/\/ if phi is large we probably overflow, defer to Poisson:\n if (phi__[i] > internal::neg_binomial_2_phi_cutoff) {\n logp += poisson_lpmf(n_vec[i], mu__[i]);\n continue;\n }\n\n if (include_summand<propto>::value) {\n logp -= lgamma(n_vec[i] + 1.0);\n }\n if (include_summand<propto, T_precision>::value) {\n logp += multiply_log(phi__[i], phi__[i]) - lgamma(phi__[i]);\n }\n if (include_summand<propto, T_location, T_precision>::value) {\n logp -= (n_plus_phi[i]) * log_mu_plus_phi[i];\n }\n if (include_summand<propto, T_location>::value) {\n logp += multiply_log(n_vec[i], mu__[i]);\n }\n if (include_summand<propto, T_precision>::value) {\n logp += lgamma(n_plus_phi[i]);\n }\n\n if (!is_constant_all<T_location>::value) {\n ops_partials.edge1_.partials_[i]\n += n_vec[i] \/ mu__[i] - (n_vec[i] + phi__[i]) \/ (mu__[i] + phi__[i]);\n }\n if (!is_constant_all<T_precision>::value) {\n ops_partials.edge2_.partials_[i]\n += 1.0 - n_plus_phi[i] \/ (mu__[i] + phi__[i]) + log_phi[i]\n - log_mu_plus_phi[i] - digamma(phi__[i]) + digamma(n_plus_phi[i]);\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_location, typename T_precision>\ninline return_type_t<T_location, T_precision> neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n return neg_binomial_2_lpmf<false>(n, mu, phi);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ Implementation for the DebugLog() function that prints to the UART on the\n\/\/ SparkFun Edge microcontroller. The same should work for other targets using\n\/\/ the Ambiq Apollo 3.\n\n#include \"tensorflow\/lite\/micro\/debug_log.h\"\n#include \"hx_drv_tflm.h\"\n\nextern \"C\" void DebugLog(const char* s) {\n static bool is_initialized = false;\n if (!is_initialized) {\n hx_drv_uart_initial();\n is_initialized = true;\n }\n\n hx_drv_uart_print(\"%s\", s);\n}\n<commit_msg>remove unuse comment<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/micro\/debug_log.h\"\n#include \"hx_drv_tflm.h\"\n\nextern \"C\" void DebugLog(const char* s) {\n static bool is_initialized = false;\n if (!is_initialized) {\n hx_drv_uart_initial();\n is_initialized = true;\n }\n\n hx_drv_uart_print(\"%s\", s);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"writer\/verilog\/axi\/slave_controller.h\"\n\n#include \"writer\/verilog\/axi\/slave_port.h\"\n#include \"writer\/verilog\/module.h\"\n#include \"writer\/verilog\/ports.h\"\n\nnamespace iroha {\nnamespace writer {\nnamespace verilog {\nnamespace axi { \n\nSlaveController::SlaveController(const IResource &res,\n\t\t\t\t bool reset_polarity)\n : AxiController(res, reset_polarity) {\n ports_.reset(new Ports);\n}\n\nSlaveController::~SlaveController() {\n}\n\nvoid SlaveController::Write(ostream &os) {\n string name = SlavePort::ControllerName(res_, reset_polarity_);\n os << \"\/\/ slave controller: \"\n << name << \"\\n\";\n AddSramPorts();\n string initials;\n GenReadChannel(cfg_, false, nullptr, ports_.get(), &initials);\n GenWriteChannel(cfg_, false, nullptr, ports_.get(), &initials);\n os << \"module \" << name << \"(\";\n ports_->Output(Ports::PORT_NAME, os);\n os << \");\\n\";\n ports_->Output(Ports::PORT_TYPE, os);\n\n os << \" `define S_IDLE 0\\n\"\n << \" `define S_READ 1\\n\"\n << \" `define S_WRITE 2\\n\";\n os << \" reg [1:0] st;\\n\\n\";\n os << \" reg [\" << sram_addr_width_ << \":0] idx;\\n\\n\";\n os << \" reg first_addr;\";\n os << \" reg [1:0] rlen;\\n\\n\";\n\n os << \" always @(posedge clk) begin\\n\"\n << \" if (\" << (reset_polarity_ ? \"\" : \"!\")\n << ResetName(reset_polarity_) << \") begin\\n\"\n << \" st <= `S_IDLE;\\n\"\n << \" first_addr <= 0;\\n\"\n << \" rlen <= 0;\\n\";\n os << initials\n << \" end else begin\\n\";\n OutputFSM(os);\n os << \" end\\n\"\n << \" end\\n\"\n << \"endmodule\\n\";\n}\n\nvoid SlaveController::AddPorts(const PortConfig &cfg, Module *mod, string *s) {\n Ports *ports = mod->GetPorts();\n GenWriteChannel(cfg, false, mod, ports, s);\n GenReadChannel(cfg, false, mod, ports, s);\n}\n\nvoid SlaveController::OutputFSM(ostream &os) {\n os << \" sram_wen <= (st == `S_WRITE && WVALID);\\n\"\n << \" RLAST <= (st == `S_READ && rlen == 0);\\n\";\n os << \" case (st)\\n\"\n << \" `S_IDLE: begin\\n\"\n << \" if (ARVALID) begin\\n\"\n << \" st <= `S_READ;\\n\"\n << \" ARREADY <= 1;\\n\"\n << \" sram_addr <= ARADDR[\" << (sram_addr_width_ - 1) << \":0];\\n\"\n << \" rlen <= ARLEN;\\n\"\n << \" end else if (AWVALID) begin\\n\"\n << \" st <= `S_WRITE;\\n\"\n << \" AWREADY <= 1;\\n\"\n << \" first_addr <= 1;\\n\"\n << \" sram_addr <= AWADDR[\" << (sram_addr_width_ - 1) << \":0];\\n\"\n << \" WREADY <= 1;\\n\"\n << \" end\\n\"\n << \" end\\n\"\n << \" `S_READ: begin\\n\"\n << \" ARREADY <= 0;\\n\"\n << \" RVALID <= 1;\\n\"\n << \" if (RREADY) begin\\n\"\n << \" sram_addr <= sram_addr + 1;\\n\"\n << \" rlen <= rlen - 1;\\n\"\n << \" end\\n\"\n << \" RDATA <= sram_rdata;\\n\"\n << \" end\\n\"\n << \" `S_WRITE: begin\\n\"\n << \" AWREADY <= 0;\\n\"\n << \" if (WVALID) begin\\n\"\n << \" sram_wdata <= WDATA;\\n\"\n << \" if (first_addr) begin\\n\"\n << \" first_addr <= 0;\\n\"\n << \" end else begin\\n\"\n << \" sram_addr <= sram_addr + 1;\\n\"\n << \" end\\n\"\n << \" end\\n\"\n << \" if (WLAST && WVALID) begin\\n\"\n << \" st <= `S_IDLE;\\n\"\n << \" WREADY <= 0;\\n\"\n << \" end\\n\"\n << \" end\\n\";\n os << \" endcase\\n\";\n}\n\n} \/\/ namespace axi\n} \/\/ namespace verilog\n} \/\/ namespace writer\n} \/\/ namespace iroha\n<commit_msg>Fix AXI read state to finish properly.<commit_after>#include \"writer\/verilog\/axi\/slave_controller.h\"\n\n#include \"writer\/verilog\/axi\/slave_port.h\"\n#include \"writer\/verilog\/module.h\"\n#include \"writer\/verilog\/ports.h\"\n\nnamespace iroha {\nnamespace writer {\nnamespace verilog {\nnamespace axi { \n\nSlaveController::SlaveController(const IResource &res,\n\t\t\t\t bool reset_polarity)\n : AxiController(res, reset_polarity) {\n ports_.reset(new Ports);\n}\n\nSlaveController::~SlaveController() {\n}\n\nvoid SlaveController::Write(ostream &os) {\n string name = SlavePort::ControllerName(res_, reset_polarity_);\n os << \"\/\/ slave controller: \"\n << name << \"\\n\";\n AddSramPorts();\n string initials;\n GenReadChannel(cfg_, false, nullptr, ports_.get(), &initials);\n GenWriteChannel(cfg_, false, nullptr, ports_.get(), &initials);\n os << \"module \" << name << \"(\";\n ports_->Output(Ports::PORT_NAME, os);\n os << \");\\n\";\n ports_->Output(Ports::PORT_TYPE, os);\n\n os << \" `define S_IDLE 0\\n\"\n << \" `define S_READ 1\\n\"\n << \" `define S_WRITE 2\\n\";\n os << \" reg [1:0] st;\\n\\n\";\n os << \" reg [\" << sram_addr_width_ << \":0] idx;\\n\\n\";\n os << \" reg first_addr;\";\n os << \" reg [7:0] rlen;\\n\\n\";\n\n os << \" always @(posedge clk) begin\\n\"\n << \" if (\" << (reset_polarity_ ? \"\" : \"!\")\n << ResetName(reset_polarity_) << \") begin\\n\"\n << \" st <= `S_IDLE;\\n\"\n << \" first_addr <= 0;\\n\"\n << \" rlen <= 0;\\n\";\n os << initials\n << \" end else begin\\n\";\n OutputFSM(os);\n os << \" end\\n\"\n << \" end\\n\"\n << \"endmodule\\n\";\n}\n\nvoid SlaveController::AddPorts(const PortConfig &cfg, Module *mod, string *s) {\n Ports *ports = mod->GetPorts();\n GenWriteChannel(cfg, false, mod, ports, s);\n GenReadChannel(cfg, false, mod, ports, s);\n}\n\nvoid SlaveController::OutputFSM(ostream &os) {\n os << \" sram_wen <= (st == `S_WRITE && WVALID);\\n\"\n << \" RLAST <= (st == `S_READ && rlen == 0);\\n\";\n os << \" case (st)\\n\"\n << \" `S_IDLE: begin\\n\"\n << \" if (ARVALID) begin\\n\"\n << \" st <= `S_READ;\\n\"\n << \" ARREADY <= 1;\\n\"\n << \" sram_addr <= ARADDR[\" << (sram_addr_width_ - 1) << \":0];\\n\"\n << \" rlen <= ARLEN;\\n\"\n << \" end else if (AWVALID) begin\\n\"\n << \" st <= `S_WRITE;\\n\"\n << \" AWREADY <= 1;\\n\"\n << \" first_addr <= 1;\\n\"\n << \" sram_addr <= AWADDR[\" << (sram_addr_width_ - 1) << \":0];\\n\"\n << \" WREADY <= 1;\\n\"\n << \" end\\n\"\n << \" end\\n\"\n << \" `S_READ: begin\\n\"\n << \" ARREADY <= 0;\\n\"\n << \" RVALID <= 1;\\n\"\n << \" if (RREADY && RVALID) begin\\n\"\n << \" sram_addr <= sram_addr + 1;\\n\"\n << \" rlen <= rlen - 1;\\n\"\n << \" if (rlen == 0) begin\\n\"\n << \" st <= `S_IDLE;\\n\"\n << \" end\\n\"\n << \" end\\n\"\n << \" RDATA <= sram_rdata;\\n\"\n << \" end\\n\"\n << \" `S_WRITE: begin\\n\"\n << \" AWREADY <= 0;\\n\"\n << \" if (WVALID) begin\\n\"\n << \" sram_wdata <= WDATA;\\n\"\n << \" if (first_addr) begin\\n\"\n << \" first_addr <= 0;\\n\"\n << \" end else begin\\n\"\n << \" sram_addr <= sram_addr + 1;\\n\"\n << \" end\\n\"\n << \" end\\n\"\n << \" if (WLAST && WVALID) begin\\n\"\n << \" st <= `S_IDLE;\\n\"\n << \" WREADY <= 0;\\n\"\n << \" end\\n\"\n << \" end\\n\";\n os << \" endcase\\n\";\n}\n\n} \/\/ namespace axi\n} \/\/ namespace verilog\n} \/\/ namespace writer\n} \/\/ namespace iroha\n<|endoftext|>"} {"text":"<commit_before>#include \"test.h\"\n\nstatic_BOX(box3, 1, sizeof(unsigned));\n\nstatic unsigned sent;\n\nstatic void proc3()\n{\n\tunsigned received;\n\tunsigned event;\n\n \tevent = box_wait(box3, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box2, &received); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc2()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk3);\n\t tsk_startFrom(tsk3, proc3);\n \tevent = box_wait(box2, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box3, &received); assert_success(event);\n \tevent = box_wait(box2, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box1, &received); assert_success(event);\n\tevent = tsk_join(tsk3); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc1()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk2);\n\t tsk_startFrom(tsk2, proc2);\n \tevent = box_wait(box1, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box2, &received); assert_success(event);\n \tevent = box_wait(box1, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(&box0, &received); assert_success(event);\n\tevent = tsk_join(tsk2); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc0()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk1);\n\t tsk_startFrom(tsk1, proc1);\n\t sent = rand();\n\tevent = box_give(box1, &sent); assert_success(event);\n \tevent = box_wait(&box0, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = tsk_join(tsk1); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void test()\n{\n\tunsigned event;\n\t\t assert_dead(&tsk0);\n\t tsk_startFrom(&tsk0, proc0);\n\tevent = tsk_join(&tsk0); assert_success(event);\n}\n\nextern \"C\"\nvoid test_mailbox_queue_2()\n{\n\tTEST_Notify();\n\tTEST_Call();\n}\n<commit_msg>Update test_mailbox_queue_2.cpp<commit_after>#include \"test.h\"\n\nstatic_BOX(box3, 1, sizeof(unsigned));\n\nstatic unsigned sent;\n\nstatic void proc3()\n{\n\tunsigned received;\n\tunsigned event;\n\n \tevent = box_wait(box3, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box2, &received); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc2()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk3);\n\t tsk_startFrom(tsk3, proc3); assert_ready(tsk3);\n \tevent = box_wait(box2, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box3, &received); assert_success(event);\n \tevent = box_wait(box2, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box1, &received); assert_success(event);\n\tevent = tsk_join(tsk3); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc1()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk2);\n\t tsk_startFrom(tsk2, proc2); assert_ready(tsk2);\n \tevent = box_wait(box1, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box2, &received); assert_success(event);\n \tevent = box_wait(box1, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(&box0, &received); assert_success(event);\n\tevent = tsk_join(tsk2); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void proc0()\n{\n\tunsigned received;\n\tunsigned event;\n\t\t assert_dead(tsk1);\n\t tsk_startFrom(tsk1, proc1); assert_ready(tsk1);\n \tevent = box_wait(&box0, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = box_give(box1, &received); assert_success(event);\n \tevent = box_wait(&box0, &received); assert_success(event);\n \t assert(received == sent);\n\tevent = tsk_join(tsk1); assert_success(event);\n\t tsk_stop();\n}\n\nstatic void test()\n{\n\tunsigned event;\n\t\t assert_dead(&tsk0);\n\t tsk_startFrom(&tsk0, proc0); assert_ready(&tsk0);\n\t tsk_yield();\n\t tsk_yield();\n\t sent = rand();\n\tevent = box_give(&box0, &sent); assert_success(event);\n\tevent = tsk_join(&tsk0); assert_success(event);\n}\n\nextern \"C\"\nvoid test_mailbox_queue_2()\n{\n\tTEST_Notify();\n\tTEST_Call();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP\n#define STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP\n\n#include <stan\/math\/prim\/err\/invalid_argument.hpp>\n\n#include <boost\/lexical_cast.hpp>\n\n#include <tbb\/tbb_stddef.h>\n\n#if TBB_VERSION_MAJOR == 2020\n#ifndef TBB_INTERFACE_NEW\n#define TBB_INTERFACE_NEW\n#endif\n#endif\n\n#ifdef TBB_INTERFACE_NEW\n#include <tbb\/global_control.h>\n#include <tbb\/task_arena.h>\n#else\n#include <tbb\/task_scheduler_init.h>\n#endif\n\n#include <cstdlib>\n#include <thread>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/**\n * Get number of threads to use. The function uses the environment\n * variable STAN_NUM_THREADS and follows these conventions:\n *\n * - STAN_NUM_THREADS is not defined => num_threads=1\n * - STAN_NUM_THREADS is positive => num_threads is set to the\n * specified number\n * - STAN_NUM_THREADS is set to -1 => num_threads is the number of\n * available cores on the machine\n * - STAN_NUM_THREADS < -1, STAN_NUM_THREADS = 0 or STAN_NUM_THREADS is\n * not numeric => throws an exception\n *\n * @return number of threads to use\n * @throws std::invalid_argument if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline int get_num_threads() {\n int num_threads = 1;\n const char* env_stan_num_threads = std::getenv(\"STAN_NUM_THREADS\");\n if (env_stan_num_threads != nullptr) {\n try {\n const int env_num_threads\n = boost::lexical_cast<int>(env_stan_num_threads);\n if (env_num_threads > 0) {\n num_threads = env_num_threads;\n } else if (env_num_threads == -1) {\n num_threads = std::thread::hardware_concurrency();\n } else {\n invalid_argument(\"get_num_threads(int)\", \"STAN_NUM_THREADS\",\n env_stan_num_threads,\n \"The STAN_NUM_THREADS environment variable is '\",\n \"' but it must be positive or -1\");\n }\n } catch (const boost::bad_lexical_cast&) {\n invalid_argument(\"get_num_threads(int)\", \"STAN_NUM_THREADS\",\n env_stan_num_threads,\n \"The STAN_NUM_THREADS environment variable is '\",\n \"' but it must be a positive number or -1\");\n }\n }\n return num_threads;\n}\n\n} \/\/ namespace internal\n\n#ifdef TBB_INTERFACE_NEW\n\/**\n * Initialize the Intel TBB threadpool and global scheduler through\n * the tbb::task_arena object. In case an instance of the\n * tbb::task_scheduler_object has been instantiated prior to calling\n * this function, then any subsequent initialization is ignored by the\n * Intel TBB.\n *\n * The maximal number of threads is read from the environment variable\n * STAN_NUM_THREADS using internal::get_num_threads. See conventions\n * of get_num_threads. The TBB scheduler will be activated by calling\n * this function.\n *\n * The function returns a reference to the static\n * tbb::global_control instance.\n *\n * @return reference to the static tbb::global_control\n * @throws std::runtime_error if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline tbb::task_arena& init_threadpool_tbb() {\n int tbb_max_threads = internal::get_num_threads();\n static tbb::global_control tbb_gc(\n tbb::global_control::max_allowed_parallelism, tbb_max_threads);\n\n static tbb::task_arena tbb_arena(tbb_max_threads, 1);\n tbb_arena.initialize();\n\n return tbb_arena;\n}\n#else\n\/**\n * Initialize the Intel TBB threadpool and global scheduler through\n * the tbb::task_scheduler_init object. In case an instance of the\n * tbb::task_scheduler_object has been instantiated prior to calling\n * this function, then any subsequent initialization is ignored by the\n * Intel TBB.\n *\n * The maximal number of threads is read from the environment variable\n * STAN_NUM_THREADS using internal::get_num_threads. See conventions\n * of get_num_threads. The TBB scheduler will be activated by calling\n * this function.\n *\n * The function returns a reference to the static\n * tbb::task_scheduler_init instance.\n *\n * @param stack_size sets the stack size of each thread; the default 0\n * let's the TBB choose the stack size\n * @return reference to the static tbb::task_scheduler_init\n * @throws std::runtime_error if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline tbb::task_scheduler_init& init_threadpool_tbb(\n tbb::stack_size_type stack_size = 0) {\n int tbb_max_threads = internal::get_num_threads();\n\n static tbb::task_scheduler_init tbb_scheduler(tbb_max_threads, stack_size);\n\n return tbb_scheduler;\n}\n#endif\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<commit_msg>use tbb version major macro for deciding to use new interface<commit_after>#ifndef STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP\n#define STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP\n\n#include <stan\/math\/prim\/err\/invalid_argument.hpp>\n\n#include <boost\/lexical_cast.hpp>\n\n#include <tbb\/tbb_stddef.h>\n\n#if TBB_VERSION_MAJOR >= 2020\n#ifndef TBB_INTERFACE_NEW\n#define TBB_INTERFACE_NEW\n#endif\n#endif\n\n#ifdef TBB_INTERFACE_NEW\n#include <tbb\/global_control.h>\n#include <tbb\/task_arena.h>\n#else\n#include <tbb\/task_scheduler_init.h>\n#endif\n\n#include <cstdlib>\n#include <thread>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/**\n * Get number of threads to use. The function uses the environment\n * variable STAN_NUM_THREADS and follows these conventions:\n *\n * - STAN_NUM_THREADS is not defined => num_threads=1\n * - STAN_NUM_THREADS is positive => num_threads is set to the\n * specified number\n * - STAN_NUM_THREADS is set to -1 => num_threads is the number of\n * available cores on the machine\n * - STAN_NUM_THREADS < -1, STAN_NUM_THREADS = 0 or STAN_NUM_THREADS is\n * not numeric => throws an exception\n *\n * @return number of threads to use\n * @throws std::invalid_argument if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline int get_num_threads() {\n int num_threads = 1;\n const char* env_stan_num_threads = std::getenv(\"STAN_NUM_THREADS\");\n if (env_stan_num_threads != nullptr) {\n try {\n const int env_num_threads\n = boost::lexical_cast<int>(env_stan_num_threads);\n if (env_num_threads > 0) {\n num_threads = env_num_threads;\n } else if (env_num_threads == -1) {\n num_threads = std::thread::hardware_concurrency();\n } else {\n invalid_argument(\"get_num_threads(int)\", \"STAN_NUM_THREADS\",\n env_stan_num_threads,\n \"The STAN_NUM_THREADS environment variable is '\",\n \"' but it must be positive or -1\");\n }\n } catch (const boost::bad_lexical_cast&) {\n invalid_argument(\"get_num_threads(int)\", \"STAN_NUM_THREADS\",\n env_stan_num_threads,\n \"The STAN_NUM_THREADS environment variable is '\",\n \"' but it must be a positive number or -1\");\n }\n }\n return num_threads;\n}\n\n} \/\/ namespace internal\n\n#ifdef TBB_INTERFACE_NEW\n\/**\n * Initialize the Intel TBB threadpool and global scheduler through\n * the tbb::task_arena object. In case an instance of the\n * tbb::task_scheduler_object has been instantiated prior to calling\n * this function, then any subsequent initialization is ignored by the\n * Intel TBB.\n *\n * The maximal number of threads is read from the environment variable\n * STAN_NUM_THREADS using internal::get_num_threads. See conventions\n * of get_num_threads. The TBB scheduler will be activated by calling\n * this function.\n *\n * The function returns a reference to the static\n * tbb::global_control instance.\n *\n * @return reference to the static tbb::global_control\n * @throws std::runtime_error if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline tbb::task_arena& init_threadpool_tbb() {\n int tbb_max_threads = internal::get_num_threads();\n static tbb::global_control tbb_gc(\n tbb::global_control::max_allowed_parallelism, tbb_max_threads);\n\n static tbb::task_arena tbb_arena(tbb_max_threads, 1);\n tbb_arena.initialize();\n\n return tbb_arena;\n}\n#else\n\/**\n * Initialize the Intel TBB threadpool and global scheduler through\n * the tbb::task_scheduler_init object. In case an instance of the\n * tbb::task_scheduler_object has been instantiated prior to calling\n * this function, then any subsequent initialization is ignored by the\n * Intel TBB.\n *\n * The maximal number of threads is read from the environment variable\n * STAN_NUM_THREADS using internal::get_num_threads. See conventions\n * of get_num_threads. The TBB scheduler will be activated by calling\n * this function.\n *\n * The function returns a reference to the static\n * tbb::task_scheduler_init instance.\n *\n * @param stack_size sets the stack size of each thread; the default 0\n * let's the TBB choose the stack size\n * @return reference to the static tbb::task_scheduler_init\n * @throws std::runtime_error if the value of STAN_NUM_THREADS env. variable\n * is invalid\n *\/\ninline tbb::task_scheduler_init& init_threadpool_tbb(\n tbb::stack_size_type stack_size = 0) {\n int tbb_max_threads = internal::get_num_threads();\n\n static tbb::task_scheduler_init tbb_scheduler(tbb_max_threads, stack_size);\n\n return tbb_scheduler;\n}\n#endif\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <unistd.h>\n\n#include \"Hydro.hpp\"\n\nusing namespace std;\n\nconst int W = 200, H = 200;\n\nvoid dump (string fn, Hydro &sim) {\n ofstream ofs (fn.c_str()); \n for (int iy = 0; iy < H; ++iy) {\n for (int ix = 0; ix < W; ++ix) {\n double x = sim.dR0() * (ix+0.5);\n double y = sim.dR0() * (iy+0.5);\n int i = W * iy + ix;\n ofs << x << \" \" << y << \" \"\n << sim.density()[i] << \" \"\n << sim.velocity0()[i] << \" \"\n << sim.velocity1()[i] << \" \"\n << sim.pressure()[i] << endl;\n }\n }\n}\n\nint main () {\n Hydro sim(W, H);\n sim.time() = 0;\n sim.extent0() = 1.0;\n sim.extent1() = 1.0;\n sim.dR0() = sim.extent0() \/ W;\n sim.dR1() = sim.extent1() \/ H;\n sim.init_kh();\n dump(\"begin.txt\", sim);\n for (;;) {\n cerr << sim.time() << endl;\n sim.proceed();\n if (sim.time() >1.0) break;\n }\n dump(\"end.txt\", sim);\n}\n<commit_msg>Anime generator .<commit_after>#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <unistd.h>\n\n#include \"Hydro.hpp\"\n\nusing namespace std;\n\nconst int W = 200, H = 200;\n\nvoid dump (string fn, Hydro &sim) {\n ofstream ofs (fn.c_str()); \n for (int iy = 0; iy < H; ++iy) {\n for (int ix = 0; ix < W; ++ix) {\n double x = sim.dR0() * (ix+0.5);\n double y = sim.dR0() * (iy+0.5);\n int i = W * iy + ix;\n ofs << x << \" \" << y << \" \"\n << sim.density()[i] << \" \"\n << sim.velocity0()[i] << \" \"\n << sim.velocity1()[i] << \" \"\n << sim.pressure()[i] << endl;\n }\n }\n}\n\nint main () {\n Hydro sim(W, H);\n sim.time() = 0;\n sim.extent0() = 1.0;\n sim.extent1() = 1.0;\n sim.dR0() = sim.extent0() \/ W;\n sim.dR1() = sim.extent1() \/ H;\n sim.init_kh();\n int ctr = 0;\n system(\"mkdir -p output\");\n while (ctr <= 100) {\n cerr << sim.time() << endl;\n sim.proceed();\n if (sim.time() > 0.1 * ctr) {\n char buf[256];\n sprintf(buf, \"output\/snapshot%04d\", ctr);\n dump(buf, sim);\n ++ctr;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ngtcp2\n *\n * Copyright (c) 2017 ngtcp2 contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"crypto.h\"\n\n#if !defined(OPENSSL_IS_BORINGSSL)\n\n# include <cassert>\n\n# include <openssl\/evp.h>\n# include <openssl\/kdf.h>\n\n# include \"template.h\"\n\nnamespace ngtcp2 {\n\nnamespace crypto {\n\nint negotiated_prf(Context &ctx, SSL *ssl) {\n switch (SSL_CIPHER_get_id(SSL_get_current_cipher(ssl))) {\n case 0x03001301u: \/\/ TLS_AES_128_GCM_SHA256\n case 0x03001303u: \/\/ TLS_CHACHA20_POLY1305_SHA256\n ctx.prf = EVP_sha256();\n return 0;\n case 0x03001302u: \/\/ TLS_AES_256_GCM_SHA384\n ctx.prf = EVP_sha384();\n return 0;\n default:\n return -1;\n }\n}\n\nint negotiated_aead(Context &ctx, SSL *ssl) {\n switch (SSL_CIPHER_get_id(SSL_get_current_cipher(ssl))) {\n case 0x03001301u: \/\/ TLS_AES_128_GCM_SHA256\n ctx.aead = EVP_aes_128_gcm();\n ctx.hp = EVP_aes_128_ecb();\n return 0;\n case 0x03001302u: \/\/ TLS_AES_256_GCM_SHA384\n ctx.aead = EVP_aes_256_gcm();\n ctx.hp = EVP_aes_256_ecb();\n return 0;\n case 0x03001303u: \/\/ TLS_CHACHA20_POLY1305_SHA256\n ctx.aead = EVP_chacha20_poly1305();\n ctx.hp = EVP_chacha20();\n return 0;\n default:\n return -1;\n }\n}\n\nstatic size_t aead_tag_length(const Context &ctx) {\n if (ctx.aead == EVP_aes_128_gcm() || ctx.aead == EVP_aes_256_gcm()) {\n return EVP_GCM_TLS_TAG_LEN;\n }\n if (ctx.aead == EVP_chacha20_poly1305()) {\n return EVP_CHACHAPOLY_TLS_TAG_LEN;\n }\n assert(0);\n}\n\nssize_t encrypt(uint8_t *dest, size_t destlen, const uint8_t *plaintext,\n size_t plaintextlen, const Context &ctx, const uint8_t *key,\n size_t keylen, const uint8_t *nonce, size_t noncelen,\n const uint8_t *ad, size_t adlen) {\n auto taglen = aead_tag_length(ctx);\n\n if (destlen < plaintextlen + taglen) {\n return -1;\n }\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (EVP_EncryptInit_ex(actx, ctx.aead, nullptr, nullptr, nullptr) != 1) {\n return -1;\n }\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_IVLEN, noncelen, nullptr) !=\n 1) {\n return -1;\n }\n\n if (EVP_EncryptInit_ex(actx, nullptr, nullptr, key, nonce) != 1) {\n return -1;\n }\n\n size_t outlen = 0;\n int len;\n\n if (EVP_EncryptUpdate(actx, nullptr, &len, ad, adlen) != 1) {\n return -1;\n }\n\n if (EVP_EncryptUpdate(actx, dest, &len, plaintext, plaintextlen) != 1) {\n return -1;\n }\n\n outlen = len;\n\n if (EVP_EncryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n outlen += len;\n\n assert(outlen + taglen <= destlen);\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_GET_TAG, taglen, dest + outlen) !=\n 1) {\n return -1;\n }\n\n outlen += taglen;\n\n return outlen;\n}\n\nssize_t decrypt(uint8_t *dest, size_t destlen, const uint8_t *ciphertext,\n size_t ciphertextlen, const Context &ctx, const uint8_t *key,\n size_t keylen, const uint8_t *nonce, size_t noncelen,\n const uint8_t *ad, size_t adlen) {\n auto taglen = aead_tag_length(ctx);\n\n if (taglen > ciphertextlen || destlen + taglen < ciphertextlen) {\n return -1;\n }\n\n ciphertextlen -= taglen;\n auto tag = ciphertext + ciphertextlen;\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (EVP_DecryptInit_ex(actx, ctx.aead, nullptr, nullptr, nullptr) != 1) {\n return -1;\n }\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_IVLEN, noncelen, nullptr) !=\n 1) {\n return -1;\n }\n\n if (EVP_DecryptInit_ex(actx, nullptr, nullptr, key, nonce) != 1) {\n return -1;\n }\n\n size_t outlen;\n int len;\n\n if (EVP_DecryptUpdate(actx, nullptr, &len, ad, adlen) != 1) {\n return -1;\n }\n\n if (EVP_DecryptUpdate(actx, dest, &len, ciphertext, ciphertextlen) != 1) {\n return -1;\n }\n\n outlen = len;\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_TAG, taglen,\n const_cast<uint8_t *>(tag)) != 1) {\n return -1;\n }\n\n if (EVP_DecryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n outlen += len;\n\n return outlen;\n}\n\nsize_t aead_max_overhead(const Context &ctx) { return aead_tag_length(ctx); }\n\nsize_t aead_key_length(const Context &ctx) {\n return EVP_CIPHER_key_length(ctx.aead);\n}\n\nsize_t aead_nonce_length(const Context &ctx) {\n return EVP_CIPHER_iv_length(ctx.aead);\n}\n\nssize_t hp_mask(uint8_t *dest, size_t destlen, const Context &ctx,\n const uint8_t *key, size_t keylen, const uint8_t *sample,\n size_t samplelen) {\n static constexpr uint8_t CHACHA_INPUT[] = \"\\x00\\x00\\x00\\x00\\x00\";\n const uint8_t *iv = nullptr;\n const uint8_t *plaintext;\n size_t plaintextlen;\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (ctx.hp == EVP_chacha20()) {\n iv = sample;\n plaintext = CHACHA_INPUT;\n plaintextlen = sizeof(CHACHA_INPUT) - 1;\n } else {\n plaintext = sample;\n plaintextlen = samplelen;\n }\n\n if (EVP_EncryptInit_ex(actx, ctx.hp, nullptr, key, iv) != 1) {\n return -1;\n }\n if (EVP_CIPHER_CTX_set_padding(actx, 0) != 1) {\n return -1;\n }\n\n size_t outlen = 0;\n int len;\n\n if (EVP_EncryptUpdate(actx, dest, &len, plaintext, plaintextlen) != 1) {\n return -1;\n }\n\n assert(len > 0);\n\n outlen = len;\n\n if (EVP_EncryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n assert(len == 0);\n\n return outlen;\n}\n\nint hkdf_expand(uint8_t *dest, size_t destlen, const uint8_t *secret,\n size_t secretlen, const uint8_t *info, size_t infolen,\n const Context &ctx) {\n auto pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);\n if (pctx == nullptr) {\n return -1;\n }\n\n auto pctx_d = defer(EVP_PKEY_CTX_free, pctx);\n\n if (EVP_PKEY_derive_init(pctx) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set_hkdf_md(pctx, ctx.prf) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, \"\", 0) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infolen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_derive(pctx, dest, &destlen) != 1) {\n return -1;\n }\n\n return 0;\n}\n\nint hkdf_extract(uint8_t *dest, size_t destlen, const uint8_t *secret,\n size_t secretlen, const uint8_t *salt, size_t saltlen,\n const Context &ctx) {\n auto pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);\n if (pctx == nullptr) {\n return -1;\n }\n\n auto pctx_d = defer(EVP_PKEY_CTX_free, pctx);\n\n if (EVP_PKEY_derive_init(pctx) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set_hkdf_md(pctx, ctx.prf) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_derive(pctx, dest, &destlen) != 1) {\n return -1;\n }\n\n return 0;\n}\n\nvoid prf_sha256(Context &ctx) { ctx.prf = EVP_sha256(); }\n\nvoid aead_aes_128_gcm(Context &ctx) {\n ctx.aead = EVP_aes_128_gcm();\n ctx.hp = EVP_aes_128_ecb();\n}\n\nint message_digest(uint8_t *res, const EVP_MD *meth, const uint8_t *data,\n size_t len) {\n int rv;\n\n auto ctx = EVP_MD_CTX_new();\n if (ctx == nullptr) {\n return -1;\n }\n\n auto ctx_deleter = defer(EVP_MD_CTX_free, ctx);\n\n rv = EVP_DigestInit_ex(ctx, meth, nullptr);\n if (rv != 1) {\n return -1;\n }\n\n rv = EVP_DigestUpdate(ctx, data, len);\n if (rv != 1) {\n return -1;\n }\n\n unsigned int mdlen = EVP_MD_size(meth);\n\n rv = EVP_DigestFinal_ex(ctx, res, &mdlen);\n if (rv != 1) {\n return -1;\n }\n\n return 0;\n}\n\n} \/\/ namespace crypto\n\n} \/\/ namespace ngtcp2\n\n#endif \/\/ !defined(OPENSSL_IS_BORINGSSL)\n<commit_msg>Just use AES-CTR for simplicity<commit_after>\/*\n * ngtcp2\n *\n * Copyright (c) 2017 ngtcp2 contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"crypto.h\"\n\n#if !defined(OPENSSL_IS_BORINGSSL)\n\n# include <cassert>\n\n# include <openssl\/evp.h>\n# include <openssl\/kdf.h>\n\n# include \"template.h\"\n\nnamespace ngtcp2 {\n\nnamespace crypto {\n\nint negotiated_prf(Context &ctx, SSL *ssl) {\n switch (SSL_CIPHER_get_id(SSL_get_current_cipher(ssl))) {\n case 0x03001301u: \/\/ TLS_AES_128_GCM_SHA256\n case 0x03001303u: \/\/ TLS_CHACHA20_POLY1305_SHA256\n ctx.prf = EVP_sha256();\n return 0;\n case 0x03001302u: \/\/ TLS_AES_256_GCM_SHA384\n ctx.prf = EVP_sha384();\n return 0;\n default:\n return -1;\n }\n}\n\nint negotiated_aead(Context &ctx, SSL *ssl) {\n switch (SSL_CIPHER_get_id(SSL_get_current_cipher(ssl))) {\n case 0x03001301u: \/\/ TLS_AES_128_GCM_SHA256\n ctx.aead = EVP_aes_128_gcm();\n ctx.hp = EVP_aes_128_ctr();\n return 0;\n case 0x03001302u: \/\/ TLS_AES_256_GCM_SHA384\n ctx.aead = EVP_aes_256_gcm();\n ctx.hp = EVP_aes_256_ctr();\n return 0;\n case 0x03001303u: \/\/ TLS_CHACHA20_POLY1305_SHA256\n ctx.aead = EVP_chacha20_poly1305();\n ctx.hp = EVP_chacha20();\n return 0;\n default:\n return -1;\n }\n}\n\nstatic size_t aead_tag_length(const Context &ctx) {\n if (ctx.aead == EVP_aes_128_gcm() || ctx.aead == EVP_aes_256_gcm()) {\n return EVP_GCM_TLS_TAG_LEN;\n }\n if (ctx.aead == EVP_chacha20_poly1305()) {\n return EVP_CHACHAPOLY_TLS_TAG_LEN;\n }\n assert(0);\n}\n\nssize_t encrypt(uint8_t *dest, size_t destlen, const uint8_t *plaintext,\n size_t plaintextlen, const Context &ctx, const uint8_t *key,\n size_t keylen, const uint8_t *nonce, size_t noncelen,\n const uint8_t *ad, size_t adlen) {\n auto taglen = aead_tag_length(ctx);\n\n if (destlen < plaintextlen + taglen) {\n return -1;\n }\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (EVP_EncryptInit_ex(actx, ctx.aead, nullptr, nullptr, nullptr) != 1) {\n return -1;\n }\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_IVLEN, noncelen, nullptr) !=\n 1) {\n return -1;\n }\n\n if (EVP_EncryptInit_ex(actx, nullptr, nullptr, key, nonce) != 1) {\n return -1;\n }\n\n size_t outlen = 0;\n int len;\n\n if (EVP_EncryptUpdate(actx, nullptr, &len, ad, adlen) != 1) {\n return -1;\n }\n\n if (EVP_EncryptUpdate(actx, dest, &len, plaintext, plaintextlen) != 1) {\n return -1;\n }\n\n outlen = len;\n\n if (EVP_EncryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n outlen += len;\n\n assert(outlen + taglen <= destlen);\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_GET_TAG, taglen, dest + outlen) !=\n 1) {\n return -1;\n }\n\n outlen += taglen;\n\n return outlen;\n}\n\nssize_t decrypt(uint8_t *dest, size_t destlen, const uint8_t *ciphertext,\n size_t ciphertextlen, const Context &ctx, const uint8_t *key,\n size_t keylen, const uint8_t *nonce, size_t noncelen,\n const uint8_t *ad, size_t adlen) {\n auto taglen = aead_tag_length(ctx);\n\n if (taglen > ciphertextlen || destlen + taglen < ciphertextlen) {\n return -1;\n }\n\n ciphertextlen -= taglen;\n auto tag = ciphertext + ciphertextlen;\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (EVP_DecryptInit_ex(actx, ctx.aead, nullptr, nullptr, nullptr) != 1) {\n return -1;\n }\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_IVLEN, noncelen, nullptr) !=\n 1) {\n return -1;\n }\n\n if (EVP_DecryptInit_ex(actx, nullptr, nullptr, key, nonce) != 1) {\n return -1;\n }\n\n size_t outlen;\n int len;\n\n if (EVP_DecryptUpdate(actx, nullptr, &len, ad, adlen) != 1) {\n return -1;\n }\n\n if (EVP_DecryptUpdate(actx, dest, &len, ciphertext, ciphertextlen) != 1) {\n return -1;\n }\n\n outlen = len;\n\n if (EVP_CIPHER_CTX_ctrl(actx, EVP_CTRL_AEAD_SET_TAG, taglen,\n const_cast<uint8_t *>(tag)) != 1) {\n return -1;\n }\n\n if (EVP_DecryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n outlen += len;\n\n return outlen;\n}\n\nsize_t aead_max_overhead(const Context &ctx) { return aead_tag_length(ctx); }\n\nsize_t aead_key_length(const Context &ctx) {\n return EVP_CIPHER_key_length(ctx.aead);\n}\n\nsize_t aead_nonce_length(const Context &ctx) {\n return EVP_CIPHER_iv_length(ctx.aead);\n}\n\nssize_t hp_mask(uint8_t *dest, size_t destlen, const Context &ctx,\n const uint8_t *key, size_t keylen, const uint8_t *sample,\n size_t samplelen) {\n static constexpr uint8_t PLAINTEXT[] = \"\\x00\\x00\\x00\\x00\\x00\";\n\n auto actx = EVP_CIPHER_CTX_new();\n if (actx == nullptr) {\n return -1;\n }\n\n auto actx_d = defer(EVP_CIPHER_CTX_free, actx);\n\n if (EVP_EncryptInit_ex(actx, ctx.hp, nullptr, key, sample) != 1) {\n return -1;\n }\n\n size_t outlen = 0;\n int len;\n\n if (EVP_EncryptUpdate(actx, dest, &len, PLAINTEXT, str_size(PLAINTEXT)) !=\n 1) {\n return -1;\n }\n\n assert(len == 5);\n\n outlen = len;\n\n if (EVP_EncryptFinal_ex(actx, dest + outlen, &len) != 1) {\n return -1;\n }\n\n assert(len == 0);\n\n return outlen;\n}\n\nint hkdf_expand(uint8_t *dest, size_t destlen, const uint8_t *secret,\n size_t secretlen, const uint8_t *info, size_t infolen,\n const Context &ctx) {\n auto pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);\n if (pctx == nullptr) {\n return -1;\n }\n\n auto pctx_d = defer(EVP_PKEY_CTX_free, pctx);\n\n if (EVP_PKEY_derive_init(pctx) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set_hkdf_md(pctx, ctx.prf) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, \"\", 0) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infolen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_derive(pctx, dest, &destlen) != 1) {\n return -1;\n }\n\n return 0;\n}\n\nint hkdf_extract(uint8_t *dest, size_t destlen, const uint8_t *secret,\n size_t secretlen, const uint8_t *salt, size_t saltlen,\n const Context &ctx) {\n auto pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);\n if (pctx == nullptr) {\n return -1;\n }\n\n auto pctx_d = defer(EVP_PKEY_CTX_free, pctx);\n\n if (EVP_PKEY_derive_init(pctx) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set_hkdf_md(pctx, ctx.prf) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretlen) != 1) {\n return -1;\n }\n\n if (EVP_PKEY_derive(pctx, dest, &destlen) != 1) {\n return -1;\n }\n\n return 0;\n}\n\nvoid prf_sha256(Context &ctx) { ctx.prf = EVP_sha256(); }\n\nvoid aead_aes_128_gcm(Context &ctx) {\n ctx.aead = EVP_aes_128_gcm();\n ctx.hp = EVP_aes_128_ctr();\n}\n\nint message_digest(uint8_t *res, const EVP_MD *meth, const uint8_t *data,\n size_t len) {\n int rv;\n\n auto ctx = EVP_MD_CTX_new();\n if (ctx == nullptr) {\n return -1;\n }\n\n auto ctx_deleter = defer(EVP_MD_CTX_free, ctx);\n\n rv = EVP_DigestInit_ex(ctx, meth, nullptr);\n if (rv != 1) {\n return -1;\n }\n\n rv = EVP_DigestUpdate(ctx, data, len);\n if (rv != 1) {\n return -1;\n }\n\n unsigned int mdlen = EVP_MD_size(meth);\n\n rv = EVP_DigestFinal_ex(ctx, res, &mdlen);\n if (rv != 1) {\n return -1;\n }\n\n return 0;\n}\n\n} \/\/ namespace crypto\n\n} \/\/ namespace ngtcp2\n\n#endif \/\/ !defined(OPENSSL_IS_BORINGSSL)\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2016 P.L. Lucas <selairi@gmail.com>\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"brightnesssettings.h\"\n#include \"outputwidget.h\"\n#include <QMessageBox>\n#include <QPushButton>\n\nBrightnessSettings::BrightnessSettings(QWidget *parent):QDialog(parent)\n{\n ui = new Ui::BrightnessSettings();\n ui->setupUi(this);\n \n mBrightness = new XRandrBrightness();\n mMonitors = mBrightness->getMonitorsInfo();\n mBacklight = new LXQt::Backlight(this);\n \n ui->backlightSlider->setEnabled(mBacklight->isBacklightAvailable());\n if(mBacklight->isBacklightAvailable()) {\n ui->backlightSlider->setMaximum(mBacklight->getMaxBacklight());\n ui->backlightSlider->setValue(mLastBacklightValue = mBacklight->getBacklight());\n connect(ui->backlightSlider, &QSlider::valueChanged, this, &BrightnessSettings::setBacklight);\n }\n\n for(const MonitorInfo &monitor: qAsConst(mMonitors))\n {\n OutputWidget *output = new OutputWidget(monitor, this);\n ui->layout->addWidget(output);\n output->show();\n connect(output, SIGNAL(changed(MonitorInfo)), this, SLOT(monitorSettingsChanged(MonitorInfo)));\n connect(this, &BrightnessSettings::monitorReverted, output, &OutputWidget::setRevertedValues);\n }\n\n mConfirmRequestTimer.setSingleShot(true);\n mConfirmRequestTimer.setInterval(1000);\n connect(&mConfirmRequestTimer, &QTimer::timeout, this, &BrightnessSettings::requestConfirmation);\n \n}\n\nvoid BrightnessSettings::setBacklight(int value)\n{\n mBacklight->setBacklight(value);\n mConfirmRequestTimer.start();\n}\n\nvoid BrightnessSettings::monitorSettingsChanged(MonitorInfo monitor)\n{\n mBrightness->setMonitorsSettings(QList<MonitorInfo>{} << monitor);\n if (ui->confirmCB->isChecked())\n {\n mConfirmRequestTimer.start();\n } else\n {\n for (auto & m : mMonitors)\n {\n if (m.id() == monitor.id() && m.name() == monitor.name())\n {\n m.setBacklight(monitor.backlight());\n m.setBrightness(monitor.brightness());\n }\n }\n }\n}\n\nvoid BrightnessSettings::requestConfirmation()\n{\n QMessageBox msg{QMessageBox::Question, tr(\"Brightness settings changed\")\n , tr(\"Confirmation required. Are the settings correct?\")\n , QMessageBox::Yes | QMessageBox::No};\n int timeout = 5; \/\/ seconds\n QString no_text = msg.button(QMessageBox::No)->text();\n no_text += QStringLiteral(\"(%1)\");\n msg.setButtonText(QMessageBox::No, no_text.arg(timeout));\n msg.setDefaultButton(QMessageBox::No);\n\n QTimer timeoutTimer;\n timeoutTimer.setSingleShot(false);\n timeoutTimer.setInterval(1000);\n connect(&timeoutTimer, &QTimer::timeout, [&] {\n msg.setButtonText(QMessageBox::No, no_text.arg(--timeout));\n if (timeout == 0)\n {\n timeoutTimer.stop();\n msg.reject();\n }\n });\n timeoutTimer.start();\n\n if (QMessageBox::Yes == msg.exec())\n {\n \/\/ re-read current values\n if(mBacklight->isBacklightAvailable()) \n mLastBacklightValue = mBacklight->getBacklight();\n \n mMonitors = mBrightness->getMonitorsInfo();\n } else\n {\n \/\/ revert the changes\n if(mBacklight->isBacklightAvailable()) {\n mBacklight->setBacklight(mLastBacklightValue);\n ui->backlightSlider->setValue(mLastBacklightValue);\n }\n \n mBrightness->setMonitorsSettings(mMonitors);\n for (const auto & monitor : qAsConst(mMonitors))\n emit monitorReverted(monitor);\n }\n}\n<commit_msg>Backlight can not be under 2%.<commit_after>\/*\n Copyright (C) 2016 P.L. Lucas <selairi@gmail.com>\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"brightnesssettings.h\"\n#include \"outputwidget.h\"\n#include <QMessageBox>\n#include <QPushButton>\n\nBrightnessSettings::BrightnessSettings(QWidget *parent):QDialog(parent)\n{\n ui = new Ui::BrightnessSettings();\n ui->setupUi(this);\n \n mBrightness = new XRandrBrightness();\n mMonitors = mBrightness->getMonitorsInfo();\n mBacklight = new LXQt::Backlight(this);\n \n ui->backlightSlider->setEnabled(mBacklight->isBacklightAvailable());\n if(mBacklight->isBacklightAvailable()) {\n ui->backlightSlider->setMaximum(mBacklight->getMaxBacklight());\n ui->backlightSlider->setMinimum((float)(mBacklight->getMaxBacklight())*0.02);\n ui->backlightSlider->setValue(mLastBacklightValue = mBacklight->getBacklight());\n connect(ui->backlightSlider, &QSlider::valueChanged, this, &BrightnessSettings::setBacklight);\n }\n\n for(const MonitorInfo &monitor: qAsConst(mMonitors))\n {\n OutputWidget *output = new OutputWidget(monitor, this);\n ui->layout->addWidget(output);\n output->show();\n connect(output, SIGNAL(changed(MonitorInfo)), this, SLOT(monitorSettingsChanged(MonitorInfo)));\n connect(this, &BrightnessSettings::monitorReverted, output, &OutputWidget::setRevertedValues);\n }\n\n mConfirmRequestTimer.setSingleShot(true);\n mConfirmRequestTimer.setInterval(1000);\n connect(&mConfirmRequestTimer, &QTimer::timeout, this, &BrightnessSettings::requestConfirmation);\n \n}\n\nvoid BrightnessSettings::setBacklight(int value)\n{\n mBacklight->setBacklight(value);\n mConfirmRequestTimer.start();\n}\n\nvoid BrightnessSettings::monitorSettingsChanged(MonitorInfo monitor)\n{\n mBrightness->setMonitorsSettings(QList<MonitorInfo>{} << monitor);\n if (ui->confirmCB->isChecked())\n {\n mConfirmRequestTimer.start();\n } else\n {\n for (auto & m : mMonitors)\n {\n if (m.id() == monitor.id() && m.name() == monitor.name())\n {\n m.setBacklight(monitor.backlight());\n m.setBrightness(monitor.brightness());\n }\n }\n }\n}\n\nvoid BrightnessSettings::requestConfirmation()\n{\n QMessageBox msg{QMessageBox::Question, tr(\"Brightness settings changed\")\n , tr(\"Confirmation required. Are the settings correct?\")\n , QMessageBox::Yes | QMessageBox::No};\n int timeout = 5; \/\/ seconds\n QString no_text = msg.button(QMessageBox::No)->text();\n no_text += QStringLiteral(\"(%1)\");\n msg.setButtonText(QMessageBox::No, no_text.arg(timeout));\n msg.setDefaultButton(QMessageBox::No);\n\n QTimer timeoutTimer;\n timeoutTimer.setSingleShot(false);\n timeoutTimer.setInterval(1000);\n connect(&timeoutTimer, &QTimer::timeout, [&] {\n msg.setButtonText(QMessageBox::No, no_text.arg(--timeout));\n if (timeout == 0)\n {\n timeoutTimer.stop();\n msg.reject();\n }\n });\n timeoutTimer.start();\n\n if (QMessageBox::Yes == msg.exec())\n {\n \/\/ re-read current values\n if(mBacklight->isBacklightAvailable()) \n mLastBacklightValue = mBacklight->getBacklight();\n \n mMonitors = mBrightness->getMonitorsInfo();\n } else\n {\n \/\/ revert the changes\n if(mBacklight->isBacklightAvailable()) {\n disconnect(ui->backlightSlider, &QSlider::valueChanged, this, &BrightnessSettings::setBacklight);\n mBacklight->setBacklight(mLastBacklightValue);\n ui->backlightSlider->setValue(mLastBacklightValue);\n connect(ui->backlightSlider, &QSlider::valueChanged, this, &BrightnessSettings::setBacklight);\n }\n \n mBrightness->setMonitorsSettings(mMonitors);\n for (const auto & monitor : qAsConst(mMonitors))\n emit monitorReverted(monitor);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stingraykit\/string\/regex.h>\n\n#ifdef PLATFORM_POSIX\n#\tinclude <regex.h>\n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include <stingraykit\/exception.h>\n#include <stingraykit\/string\/StringUtils.h>\n#include <stingraykit\/string\/ToString.h>\n#include <stingraykit\/variant.h>\n\n\nnamespace stingray\n{\n\n\tstruct RegexMatch\n\t{\n\t\tint\tBegin;\n\t\tint\tEnd;\n\n\t\tRegexMatch() : Begin(0), End(0) { }\n\n\t\tint GetLength() const\n\t\t{\n\t\t\tint len = End - Begin;\n\t\t\tSTINGRAYKIT_CHECK(len > 0, \"Submatch length is negative!\");\n\t\t\treturn len;\n\t\t}\n\n\t\tstd::string ToString() const { return StringBuilder() % \"(\" % Begin % \", \" % End % \")\"; }\n\t};\n\n\ttypedef std::vector<RegexMatch>\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant<TypeList<std::string, int>::type>\tReplacementEntry;\n\ttypedef std::vector<ReplacementEntry>\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor<std::string>\n\t{\n\tprivate:\n\t\tconst char*\t\t\t\t_srcString;\n\t\tconst RegexMatchVec&\t_matches;\n\n\tpublic:\n\t\tReplacementEntryVisitor(const char* srcString, const RegexMatchVec& matches)\n\t\t\t: _srcString(srcString), _matches(matches)\n\t\t{ }\n\n\t\tstd::string operator () (int matchNumber) const\n\t\t{\n\t\t\tint i = matchNumber;\n\t\t\tSTINGRAYKIT_CHECK(i >= 0 && i < (int)_matches.size(), IndexOutOfRangeException(i, _matches.size()));\n\t\t\tstd::string res = std::string(_srcString + _matches[i].Begin, _matches[i].GetLength());\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::string operator () (const std::string& str) const\n\t\t{ return str; }\n\t};\n\n\ttemplate < typename PlatformRegex >\n\tclass BasicRegexImpl : public PlatformRegex\n\t{\n\tpublic:\n\t\tBasicRegexImpl(const std::string& str)\n\t\t\t: PlatformRegex(str)\n\t\t{ }\n\n\t\tbool Search(const std::string& str, smatch& m, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tm._results.clear();\n\t\t\tm._positions.clear();\n\n\t\t\tSTINGRAYKIT_CHECK(flags == regex_constants::match_default, NotImplementedException());\n\n\t\t\tRegexMatchVec matches;\n\t\t\tif (!this->DoMatch(str.c_str(), matches))\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t i = 0; i < matches.size(); ++i)\n\t\t\t{\n\t\t\t\tRegexMatch& submatch = matches[i];\n\t\t\t\tm._results.push_back(str.substr(submatch.Begin, submatch.GetLength()));\n\t\t\t\tm._positions.push_back(submatch.Begin);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::string Replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tSTINGRAYKIT_CHECK((flags & ~regex_constants::format_first_only) == 0, NotImplementedException());\n\n\t\t\tReplacementEntryVec replacement_entries;\n\t\t\tPlatformRegex group_regex(\"\\\\\\\\(\\\\d+)\"); \/\/ TODO: cache this somewhere\n\t\t\tRegexMatchVec group_matches;\n\n\t\t\tsize_t replacement_begin = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!group_regex.DoMatch(replacement.c_str() + replacement_begin, group_matches))\n\t\t\t\t{\n\t\t\t\t\tif (replacement_begin < replacement.size())\n\t\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (group_matches.at(0).Begin > 0)\n\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin, group_matches.at(0).Begin));\n\t\t\t\treplacement_entries.push_back(FromString<int>(replacement.substr(group_matches.at(1).Begin, group_matches.at(1).GetLength())));\n\t\t\t\treplacement_begin += group_matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\tint begin = 0;\n\t\t\tstd::string result;\n\n\t\t\tRegexMatchVec matches;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!this->DoMatch(str.c_str() + begin, matches))\n\t\t\t\t{\n\t\t\t\t\tresult += str.substr(begin);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tReplacementEntryVisitor visitor(str.c_str() + begin, matches);\n\n\t\t\t\tresult += str.substr(begin, matches.at(0).Begin);\n\t\t\t\tfor (ReplacementEntryVec::const_iterator it = replacement_entries.begin(); it != replacement_entries.end(); ++it)\n\t\t\t\t\tresult += apply_visitor(visitor, *it);\n\t\t\t\tbegin += matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\treturn result;\n\t\t}\n\t};\n\n#ifdef PLATFORM_POSIX\n\tclass PosixRegexImpl\n\t{\n\tprivate:\n\t\tstd::string\t_str;\n\t\tregex_t\t\t_regex;\n\n\tpublic:\n\t\tPosixRegexImpl(const std::string& str)\n\t\t\t: _str(str)\n\t\t{\n\t\t\tReplaceAll(_str, \"\\\\d\", \"[0-9]\");\n\t\t\tReplaceAll(_str, \"\\\\w\", \"[a-zA-Z0-9_]\");\n\n\t\t\tint ret = regcomp(&_regex, _str.c_str(), REG_EXTENDED);\n\t\t\tSTINGRAYKIT_CHECK(ret == 0, StringBuilder() % \"Could not compile regex '\" % _str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\t\t}\n\n\t\t~PosixRegexImpl()\n\t\t{ regfree(&_regex); }\n\n\t\tbool DoMatch(const char* str, RegexMatchVec& matches) const\n\t\t{\n\t\t\tstd::vector<regmatch_t> posix_matches(32);\n\t\t\tint ret = regexec(&_regex, str, posix_matches.size(), posix_matches.data(), 0);\n\n\t\t\tif (ret == REG_NOMATCH)\n\t\t\t\treturn false;\n\n\t\t\tif (ret != 0)\n\t\t\t\tSTINGRAYKIT_THROW(StringBuilder() % \"Could not execute regex '\" % _str % \"' for string '\" % str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\n\t\t\tint count = 0;\n\t\t\twhile (posix_matches[count].rm_so >= 0)\n\t\t\t\t++count;\n\n\n\t\t\tmatches.resize(count);\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tmatches[i].Begin = posix_matches[i].rm_so;\n\t\t\t\tmatches[i].End = posix_matches[i].rm_eo;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstatic std::string GetRegexError(const regex_t& regex, int errCode)\n\t\t{\n\t\t\tstd::string result(256, '~');\n\t\t\tresult.resize(regerror(errCode, ®ex, &result[0], result.size()));\n\t\t\treturn result;\n\t\t}\n\t};\n\n\ttypedef PosixRegexImpl\tPlatformRegexImpl;\n#endif\n\n\tclass regex::Impl : public BasicRegexImpl<PlatformRegexImpl>\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl<PlatformRegexImpl>(str) { }\n\t};\n\n\n\tregex::regex(const std::string& str)\n\t\t: _impl(new Impl(str))\n\t{ }\n\n\tregex::regex(const regex& other)\n\t\t: _impl(other._impl)\n\t{ }\n\n\tregex::~regex()\n\t{ }\n\n\tregex& regex::operator = (const regex& other)\n\t{\n\t\t_impl = other._impl;\n\t\treturn *this;\n\t}\n\n\n\tbool regex_search(const std::string& str, smatch& m, const regex& re, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Search(str, m, flags);\n\t}\n\n\n\tstd::string regex_replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Replace(str, re, replacement, flags);\n\t}\n\n}\n<commit_msg>fix submatch length comparison<commit_after>#include <stingraykit\/string\/regex.h>\n\n#ifdef PLATFORM_POSIX\n#\tinclude <regex.h>\n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include <stingraykit\/exception.h>\n#include <stingraykit\/string\/StringUtils.h>\n#include <stingraykit\/string\/ToString.h>\n#include <stingraykit\/variant.h>\n\n\nnamespace stingray\n{\n\n\tstruct RegexMatch\n\t{\n\t\tint\tBegin;\n\t\tint\tEnd;\n\n\t\tRegexMatch() : Begin(0), End(0) { }\n\n\t\tint GetLength() const\n\t\t{\n\t\t\tint len = End - Begin;\n\t\t\tSTINGRAYKIT_CHECK(len >= 0, \"Submatch length is negative!\");\n\t\t\treturn len;\n\t\t}\n\n\t\tstd::string ToString() const { return StringBuilder() % \"(\" % Begin % \", \" % End % \")\"; }\n\t};\n\n\ttypedef std::vector<RegexMatch>\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant<TypeList<std::string, int>::type>\tReplacementEntry;\n\ttypedef std::vector<ReplacementEntry>\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor<std::string>\n\t{\n\tprivate:\n\t\tconst char*\t\t\t\t_srcString;\n\t\tconst RegexMatchVec&\t_matches;\n\n\tpublic:\n\t\tReplacementEntryVisitor(const char* srcString, const RegexMatchVec& matches)\n\t\t\t: _srcString(srcString), _matches(matches)\n\t\t{ }\n\n\t\tstd::string operator () (int matchNumber) const\n\t\t{\n\t\t\tint i = matchNumber;\n\t\t\tSTINGRAYKIT_CHECK(i >= 0 && i < (int)_matches.size(), IndexOutOfRangeException(i, _matches.size()));\n\t\t\tstd::string res = std::string(_srcString + _matches[i].Begin, _matches[i].GetLength());\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::string operator () (const std::string& str) const\n\t\t{ return str; }\n\t};\n\n\ttemplate < typename PlatformRegex >\n\tclass BasicRegexImpl : public PlatformRegex\n\t{\n\tpublic:\n\t\tBasicRegexImpl(const std::string& str)\n\t\t\t: PlatformRegex(str)\n\t\t{ }\n\n\t\tbool Search(const std::string& str, smatch& m, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tm._results.clear();\n\t\t\tm._positions.clear();\n\n\t\t\tSTINGRAYKIT_CHECK(flags == regex_constants::match_default, NotImplementedException());\n\n\t\t\tRegexMatchVec matches;\n\t\t\tif (!this->DoMatch(str.c_str(), matches))\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t i = 0; i < matches.size(); ++i)\n\t\t\t{\n\t\t\t\tRegexMatch& submatch = matches[i];\n\t\t\t\tm._results.push_back(str.substr(submatch.Begin, submatch.GetLength()));\n\t\t\t\tm._positions.push_back(submatch.Begin);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::string Replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tSTINGRAYKIT_CHECK((flags & ~regex_constants::format_first_only) == 0, NotImplementedException());\n\n\t\t\tReplacementEntryVec replacement_entries;\n\t\t\tPlatformRegex group_regex(\"\\\\\\\\(\\\\d+)\"); \/\/ TODO: cache this somewhere\n\t\t\tRegexMatchVec group_matches;\n\n\t\t\tsize_t replacement_begin = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!group_regex.DoMatch(replacement.c_str() + replacement_begin, group_matches))\n\t\t\t\t{\n\t\t\t\t\tif (replacement_begin < replacement.size())\n\t\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (group_matches.at(0).Begin > 0)\n\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin, group_matches.at(0).Begin));\n\t\t\t\treplacement_entries.push_back(FromString<int>(replacement.substr(group_matches.at(1).Begin, group_matches.at(1).GetLength())));\n\t\t\t\treplacement_begin += group_matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\tint begin = 0;\n\t\t\tstd::string result;\n\n\t\t\tRegexMatchVec matches;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!this->DoMatch(str.c_str() + begin, matches))\n\t\t\t\t{\n\t\t\t\t\tresult += str.substr(begin);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tReplacementEntryVisitor visitor(str.c_str() + begin, matches);\n\n\t\t\t\tresult += str.substr(begin, matches.at(0).Begin);\n\t\t\t\tfor (ReplacementEntryVec::const_iterator it = replacement_entries.begin(); it != replacement_entries.end(); ++it)\n\t\t\t\t\tresult += apply_visitor(visitor, *it);\n\t\t\t\tbegin += matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\treturn result;\n\t\t}\n\t};\n\n#ifdef PLATFORM_POSIX\n\tclass PosixRegexImpl\n\t{\n\tprivate:\n\t\tstd::string\t_str;\n\t\tregex_t\t\t_regex;\n\n\tpublic:\n\t\tPosixRegexImpl(const std::string& str)\n\t\t\t: _str(str)\n\t\t{\n\t\t\tReplaceAll(_str, \"\\\\d\", \"[0-9]\");\n\t\t\tReplaceAll(_str, \"\\\\w\", \"[a-zA-Z0-9_]\");\n\n\t\t\tint ret = regcomp(&_regex, _str.c_str(), REG_EXTENDED);\n\t\t\tSTINGRAYKIT_CHECK(ret == 0, StringBuilder() % \"Could not compile regex '\" % _str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\t\t}\n\n\t\t~PosixRegexImpl()\n\t\t{ regfree(&_regex); }\n\n\t\tbool DoMatch(const char* str, RegexMatchVec& matches) const\n\t\t{\n\t\t\tstd::vector<regmatch_t> posix_matches(32);\n\t\t\tint ret = regexec(&_regex, str, posix_matches.size(), posix_matches.data(), 0);\n\n\t\t\tif (ret == REG_NOMATCH)\n\t\t\t\treturn false;\n\n\t\t\tif (ret != 0)\n\t\t\t\tSTINGRAYKIT_THROW(StringBuilder() % \"Could not execute regex '\" % _str % \"' for string '\" % str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\n\t\t\tint count = 0;\n\t\t\twhile (posix_matches[count].rm_so >= 0)\n\t\t\t\t++count;\n\n\n\t\t\tmatches.resize(count);\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tmatches[i].Begin = posix_matches[i].rm_so;\n\t\t\t\tmatches[i].End = posix_matches[i].rm_eo;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstatic std::string GetRegexError(const regex_t& regex, int errCode)\n\t\t{\n\t\t\tstd::string result(256, '~');\n\t\t\tresult.resize(regerror(errCode, ®ex, &result[0], result.size()));\n\t\t\treturn result;\n\t\t}\n\t};\n\n\ttypedef PosixRegexImpl\tPlatformRegexImpl;\n#endif\n\n\tclass regex::Impl : public BasicRegexImpl<PlatformRegexImpl>\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl<PlatformRegexImpl>(str) { }\n\t};\n\n\n\tregex::regex(const std::string& str)\n\t\t: _impl(new Impl(str))\n\t{ }\n\n\tregex::regex(const regex& other)\n\t\t: _impl(other._impl)\n\t{ }\n\n\tregex::~regex()\n\t{ }\n\n\tregex& regex::operator = (const regex& other)\n\t{\n\t\t_impl = other._impl;\n\t\treturn *this;\n\t}\n\n\n\tbool regex_search(const std::string& str, smatch& m, const regex& re, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Search(str, m, flags);\n\t}\n\n\n\tstd::string regex_replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Replace(str, re, replacement, flags);\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"XmlReader.h\"\n\n#include \"Exception.h\"\n#include \"Factory.h\"\n#include \"Data.h\"\n#include \"Stream.h\"\n#include \"Operator.h\"\n\n#include \"impl\/XmlUtilities.h\"\n\n#include <xercesc\/parsers\/XercesDOMParser.hpp>\n#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/sax\/HandlerBase.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n\n#include <iostream>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/filesystem.hpp>\n\nnamespace stream\n{\n using namespace xercesc;\n using namespace impl;\n\n Stream*const XmlReader::read(const std::string & filename)\n { \n cleanUp();\n \n m_currentPath = computePath(filename);\n \n try\n {\n XMLPlatformUtils::Initialize(); \/\/ Initialize Xerces infrastructure\n }\n catch (const XMLException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.getMessage());\n \n FileAccessFailed ex(filename, \"Failed to initialize xerces-c: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n \n XercesDOMParser* parser = new XercesDOMParser();\n parser->setValidationScheme(XercesDOMParser::Val_Always);\n parser->setDoNamespaces(true); \/\/ optional\n\n ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();\n parser->setErrorHandler(errHandler);\n\n const char* xmlFile = filename.c_str();\n\n try\n {\n parser->parse(xmlFile);\n }\n catch (const XMLException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.getMessage());\n \n FileAccessFailed ex(filename, \"XML exception: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n catch (const DOMException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.msg);\n \n FileAccessFailed ex(filename, \"DOM exception: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n catch (...)\n {\n throw FileAccessFailed(filename, \"Unexpected exception.\");\n }\n \n try\n {\n m_stream = new Stream();\n \n DOMDocument* doc = parser->getDocument();\n DOMElement* stream = doc->getDocumentElement();\n \n Xml2Str name(stream->getAttribute(Str2Xml(\"name\")));\n m_stream->setName(std::string(name));\n \n DOMNodeList* operators = stream->getElementsByTagName(Str2Xml(\"Operator\"));\n XMLSize_t numOperators = operators->getLength();\n \n for(unsigned int i = 0; i < numOperators; ++i)\n {\n DOMElement* op = dynamic_cast<DOMElement*>(operators->item(i));\n readOperator(op);\n }\n }\n catch(xercesc::XMLException&)\n {\n delete m_stream;\n throw FileAccessFailed(filename, \"Failed to read XML file.\");\n }\n catch(stream::Exception& e)\n {\n delete m_stream;\n throw FileAccessFailed(filename, e.what());\n }\n catch(boost::bad_lexical_cast e)\n {\n delete m_stream;\n throw FileAccessFailed(filename, e.what());\n }\n\n delete parser;\n delete errHandler;\n \n try\n {\n XMLPlatformUtils::Terminate(); \/\/ Terminate after release of memory\n }\n catch(XMLException&)\n {\n }\n \n Stream* retValue = m_stream;\n \n cleanUp();\n \n return retValue;\n } \n \n XmlReader::~XmlReader()\n {\n cleanUp();\n }\n \n void XmlReader::readOperator(DOMElement*const opElement)\n {\n Xml2Str name(opElement->getAttribute(Str2Xml(\"name\")));\n Xml2Str idStr(opElement->getAttribute(Str2Xml(\"id\")));\n Xml2Str type(opElement->getAttribute(Str2Xml(\"type\")));\n Xml2Str package(opElement->getAttribute(Str2Xml(\"package\")));\n \n unsigned int id = boost::lexical_cast<unsigned int>((const char*)(idStr));\n \n if(m_id2OperatorMap.count(id))\n throw XmlError(\"Multiple operators with the same ID.\");\n \n Operator* op = m_factory->newOperator(std::string(package), std::string(type));\n op->setName(std::string(name));\n \n m_id2OperatorMap[id] = op;\n \n DOMNodeList* parameters = opElement->getElementsByTagName(Str2Xml(\"Parameter\"));\n XMLSize_t numParameters = parameters->getLength();\n \n for(unsigned int i = 0; i < numParameters; ++i)\n {\n DOMElement* paramElement = dynamic_cast<DOMElement*>(parameters->item(i));\n readParameter(paramElement);\n }\n }\n \n void XmlReader::readParameter(DOMElement*const paramElement)\n {\n Xml2Str idStr(paramElement->getAttribute(Str2Xml(\"id\")));\n \n unsigned int id = boost::lexical_cast<unsigned int>((const char*)(idStr));\n \n DOMNodeList* dataElements = paramElement->getElementsByTagName(Str2Xml(\"Data\"));\n XMLSize_t numDataElements = dataElements->getLength();\n \n if(! numDataElements)\n return;\n \n if(numDataElements != 1)\n throw XmlError(\"More than one <Data\/> elements for parameter.\");\n \n DOMElement* dataElement = dynamic_cast<DOMElement*>(dataElements->item(0));\n Data* data = readData(dataElement);\n \n if(m_id2DataMap.count(id))\n throw XmlError(\"Multiple parameters with the same ID.\");\n \n m_id2DataMap[id] = data;\n }\n \n Data* XmlReader::readData(DOMElement*const dataElement)\n {\n Xml2Str type(dataElement->getAttribute(Str2Xml(\"type\")));\n Xml2Str package(dataElement->getAttribute(Str2Xml(\"package\")));\n \n DOMNodeList* dataTextElements = dataElement->getChildNodes();\n XMLSize_t numDataTextElements = dataTextElements->getLength();\n std::string dataString;\n \n if(numDataTextElements > 1)\n throw XmlError(\"More than one children of <Data\/>.\");\n \n if(numDataTextElements)\n {\n DOMNode* node = dataTextElements->item(0);\n if(node->getNodeType() != DOMNode::TEXT_NODE)\n throw XmlError(\"Child of <Data\/> must be a text node.\");\n \n dataString = std::string(Xml2Str(node->getNodeValue()));\n }\n \n Data* data = m_factory->newData(std::string(package), std::string(type));\n \n try\n {\n data->deserialize(dataString, m_currentPath);\n }\n catch(Exception& e)\n {\n delete data;\n throw e;\n }\n \n return data;\n }\n\n const std::string XmlReader::computePath(const std::string& filename)\n {\n boost::filesystem::path filepath(filename);\n boost::filesystem::path parentpath = filepath.parent_path();\n std::string pathSeparator;\n \n if(! parentpath.empty())\n pathSeparator = boost::filesystem::path(\"\/\").file_string();\n \n return parentpath.file_string() + pathSeparator;\n }\n \n void XmlReader::cleanUp()\n {\n m_stream = 0;\n m_currentPath = \"\";\n \n for(std::map<unsigned int, Operator*>::iterator iter = m_id2OperatorMap.begin();\n iter != m_id2OperatorMap.end();\n ++iter)\n {\n delete iter->second;\n }\n \n m_id2OperatorMap.clear();\n \n for(std::map<unsigned int, Data*>::iterator iter = m_id2DataMap.begin();\n iter != m_id2DataMap.end();\n ++iter)\n {\n delete iter->second;\n }\n \n m_id2DataMap.clear();\n \n }\n}\n<commit_msg>Read parameters to buffer before actually setting them<commit_after>#include \"XmlReader.h\"\n\n#include \"Exception.h\"\n#include \"Factory.h\"\n#include \"Data.h\"\n#include \"Stream.h\"\n#include \"Operator.h\"\n\n#include \"impl\/XmlUtilities.h\"\n\n#include <xercesc\/parsers\/XercesDOMParser.hpp>\n#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/sax\/HandlerBase.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n\n#include <iostream>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/filesystem.hpp>\n\nnamespace stream\n{\n using namespace xercesc;\n using namespace impl;\n\n Stream*const XmlReader::read(const std::string & filename)\n { \n cleanUp();\n \n m_currentPath = computePath(filename);\n \n try\n {\n XMLPlatformUtils::Initialize(); \/\/ Initialize Xerces infrastructure\n }\n catch (const XMLException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.getMessage());\n \n FileAccessFailed ex(filename, \"Failed to initialize xerces-c: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n \n XercesDOMParser* parser = new XercesDOMParser();\n parser->setValidationScheme(XercesDOMParser::Val_Always);\n parser->setDoNamespaces(true); \/\/ optional\n\n ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();\n parser->setErrorHandler(errHandler);\n\n const char* xmlFile = filename.c_str();\n\n try\n {\n parser->parse(xmlFile);\n }\n catch (const XMLException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.getMessage());\n \n FileAccessFailed ex(filename, \"XML exception: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n catch (const DOMException& toCatch)\n {\n char* message = XMLString::transcode(toCatch.msg);\n \n FileAccessFailed ex(filename, \"DOM exception: \" + std::string(message));\n XMLString::release(&message);\n throw ex;\n }\n catch (...)\n {\n throw FileAccessFailed(filename, \"Unexpected exception.\");\n }\n \n try\n {\n m_stream = new Stream();\n \n DOMDocument* doc = parser->getDocument();\n DOMElement* stream = doc->getDocumentElement();\n \n Xml2Str name(stream->getAttribute(Str2Xml(\"name\")));\n m_stream->setName(std::string(name));\n \n DOMNodeList* operators = stream->getElementsByTagName(Str2Xml(\"Operator\"));\n XMLSize_t numOperators = operators->getLength();\n \n for(unsigned int i = 0; i < numOperators; ++i)\n {\n DOMElement* op = dynamic_cast<DOMElement*>(operators->item(i));\n readOperator(op);\n }\n }\n catch(xercesc::XMLException&)\n {\n delete m_stream;\n throw FileAccessFailed(filename, \"Failed to read XML file.\");\n }\n catch(stream::Exception& e)\n {\n delete m_stream;\n throw FileAccessFailed(filename, e.what());\n }\n catch(boost::bad_lexical_cast e)\n {\n delete m_stream;\n throw FileAccessFailed(filename, e.what());\n }\n\n delete parser;\n delete errHandler;\n \n try\n {\n XMLPlatformUtils::Terminate(); \/\/ Terminate after release of memory\n }\n catch(XMLException&)\n {\n }\n \n Stream* retValue = m_stream;\n \n cleanUp();\n \n return retValue;\n } \n \n XmlReader::~XmlReader()\n {\n cleanUp();\n }\n \n void XmlReader::readOperator(DOMElement*const opElement)\n {\n Xml2Str name(opElement->getAttribute(Str2Xml(\"name\")));\n Xml2Str idStr(opElement->getAttribute(Str2Xml(\"id\")));\n Xml2Str type(opElement->getAttribute(Str2Xml(\"type\")));\n Xml2Str package(opElement->getAttribute(Str2Xml(\"package\")));\n \n unsigned int id = boost::lexical_cast<unsigned int>((const char*)(idStr));\n \n if(m_id2OperatorMap.count(id))\n throw XmlError(\"Multiple operators with the same ID.\");\n \n Operator* op = m_factory->newOperator(std::string(package), std::string(type));\n op->setName(std::string(name));\n \n m_id2OperatorMap[id] = op;\n \n DOMNodeList* parameters = opElement->getElementsByTagName(Str2Xml(\"Parameter\"));\n XMLSize_t numParameters = parameters->getLength();\n \n for(unsigned int i = 0; i < numParameters; ++i)\n {\n DOMElement* paramElement = dynamic_cast<DOMElement*>(parameters->item(i));\n readParameter(paramElement);\n }\n }\n \n void XmlReader::readParameter(DOMElement*const paramElement)\n {\n Xml2Str idStr(paramElement->getAttribute(Str2Xml(\"id\")));\n \n unsigned int id = boost::lexical_cast<unsigned int>((const char*)(idStr));\n \n DOMNodeList* dataElements = paramElement->getElementsByTagName(Str2Xml(\"Data\"));\n XMLSize_t numDataElements = dataElements->getLength();\n \n if(! numDataElements)\n return;\n \n if(numDataElements != 1)\n throw XmlError(\"More than one <Data\/> elements for parameter.\");\n \n DOMElement* dataElement = dynamic_cast<DOMElement*>(dataElements->item(0));\n Data* data = readData(dataElement);\n \n if(m_id2DataMap.count(id))\n throw XmlError(\"Multiple parameters with the same ID.\");\n \n m_id2DataMap[id] = data;\n }\n \n Data* XmlReader::readData(DOMElement*const dataElement)\n {\n Xml2Str type(dataElement->getAttribute(Str2Xml(\"type\")));\n Xml2Str package(dataElement->getAttribute(Str2Xml(\"package\")));\n \n DOMNodeList* dataTextElements = dataElement->getChildNodes();\n XMLSize_t numDataTextElements = dataTextElements->getLength();\n std::string dataString;\n \n if(numDataTextElements > 1)\n throw XmlError(\"More than one children of <Data\/>.\");\n \n if(numDataTextElements)\n {\n DOMNode* node = dataTextElements->item(0);\n if(node->getNodeType() != DOMNode::TEXT_NODE)\n throw XmlError(\"Child of <Data\/> must be a text node.\");\n \n dataString = std::string(Xml2Str(node->getNodeValue()));\n }\n \n Data* data = m_factory->newData(std::string(package), std::string(type));\n \n try\n {\n data->deserialize(dataString, m_currentPath);\n }\n catch(Exception& e)\n {\n delete data;\n throw e;\n }\n \n return data;\n }\n\n const std::string XmlReader::computePath(const std::string& filename)\n {\n boost::filesystem::path filepath(filename);\n boost::filesystem::path parentpath = filepath.parent_path();\n std::string pathSeparator;\n \n if(! parentpath.empty())\n pathSeparator = boost::filesystem::path(\"\/\").file_string();\n \n return parentpath.file_string() + pathSeparator;\n }\n \n void XmlReader::cleanUp()\n {\n m_stream = 0;\n m_currentPath = \"\";\n \n m_id2OperatorMap.clear();\n \n for(std::map<unsigned int, Data*>::iterator iter = m_id2DataMap.begin();\n iter != m_id2DataMap.end();\n ++iter)\n {\n delete iter->second;\n }\n \n m_id2DataMap.clear();\n \n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016-2017 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: David Guillen Fandos\n *\/\n\n#include \"sim\/power\/mathexpr_powermodel.hh\"\n\n#include \"base\/statistics.hh\"\n#include \"params\/MathExprPowerModel.hh\"\n#include \"sim\/mathexpr.hh\"\n#include \"sim\/power\/thermal_model.hh\"\n#include \"sim\/sim_object.hh\"\n\nMathExprPowerModel::MathExprPowerModel(const Params *p)\n : PowerModelState(p), dyn_expr(p->dyn), st_expr(p->st), failed(false)\n{\n \/\/ Calculate the name of the object we belong to\n std::vector<std::string> path;\n tokenize(path, name(), '.', true);\n \/\/ It's something like xyz.power_model.pm2\n assert(path.size() > 2);\n for (unsigned i = 0; i < path.size() - 2; i++)\n basename += path[i] + \".\";\n}\n\nvoid\nMathExprPowerModel::startup()\n{\n \/\/ Create a map with stats and pointers for quick access\n \/\/ Has to be done here, since we need access to the statsList\n for (auto & i: Stats::statsList())\n if (i->name.find(basename) == 0)\n stats_map[i->name.substr(basename.size())] = i;\n\n tryEval(st_expr);\n const bool st_failed = failed;\n\n tryEval(dyn_expr);\n const bool dyn_failed = failed;\n\n if (st_failed || dyn_failed) {\n const auto *p = dynamic_cast<const Params *>(params());\n assert(p);\n\n fatal(\"Failed to evaluate power expressions:\\n%s%s%s\\n\",\n st_failed ? p->st : \"\",\n st_failed && dyn_failed ? \"\\n\" : \"\",\n dyn_failed ? p->dyn : \"\");\n }\n}\n\ndouble\nMathExprPowerModel::eval(const MathExpr &expr) const\n{\n const double value = tryEval(expr);\n\n \/\/ This shouldn't happen unless something went wrong the equations\n \/\/ were verified in startup().\n panic_if(failed, \"Failed to evaluate power expression '%s'\\n\",\n expr.toStr());\n\n return value;\n}\n\ndouble\nMathExprPowerModel::tryEval(const MathExpr &expr) const\n{\n failed = false;\n const double value = expr.eval(\n std::bind(&MathExprPowerModel::getStatValue,\n this, std::placeholders::_1)\n );\n\n return value;\n}\n\n\ndouble\nMathExprPowerModel::getStatValue(const std::string &name) const\n{\n using namespace Stats;\n\n \/\/ Automatic variables:\n if (name == \"temp\")\n return _temp;\n\n \/\/ Try to cast the stat, only these are supported right now\n const auto it = stats_map.find(name);\n if (it == stats_map.cend()) {\n warn(\"Failed to find stat '%s'\\n\", name);\n failed = true;\n return 0;\n }\n\n const Info *info = it->second;\n\n auto si = dynamic_cast<const ScalarInfo *>(info);\n if (si)\n return si->value();\n auto fi = dynamic_cast<const FormulaInfo *>(info);\n if (fi)\n return fi->total();\n\n panic(\"Unknown stat type!\\n\");\n}\n\nvoid\nMathExprPowerModel::regStats()\n{\n PowerModelState::regStats();\n}\n\nMathExprPowerModel*\nMathExprPowerModelParams::create()\n{\n return new MathExprPowerModel(this);\n}\n<commit_msg>power: Add a voltage variable to power expressions<commit_after>\/*\n * Copyright (c) 2016-2017 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: David Guillen Fandos\n *\/\n\n#include \"sim\/power\/mathexpr_powermodel.hh\"\n\n#include \"base\/statistics.hh\"\n#include \"params\/MathExprPowerModel.hh\"\n#include \"sim\/mathexpr.hh\"\n#include \"sim\/power\/thermal_model.hh\"\n#include \"sim\/sim_object.hh\"\n\nMathExprPowerModel::MathExprPowerModel(const Params *p)\n : PowerModelState(p), dyn_expr(p->dyn), st_expr(p->st), failed(false)\n{\n \/\/ Calculate the name of the object we belong to\n std::vector<std::string> path;\n tokenize(path, name(), '.', true);\n \/\/ It's something like xyz.power_model.pm2\n assert(path.size() > 2);\n for (unsigned i = 0; i < path.size() - 2; i++)\n basename += path[i] + \".\";\n}\n\nvoid\nMathExprPowerModel::startup()\n{\n \/\/ Create a map with stats and pointers for quick access\n \/\/ Has to be done here, since we need access to the statsList\n for (auto & i: Stats::statsList())\n if (i->name.find(basename) == 0)\n stats_map[i->name.substr(basename.size())] = i;\n\n tryEval(st_expr);\n const bool st_failed = failed;\n\n tryEval(dyn_expr);\n const bool dyn_failed = failed;\n\n if (st_failed || dyn_failed) {\n const auto *p = dynamic_cast<const Params *>(params());\n assert(p);\n\n fatal(\"Failed to evaluate power expressions:\\n%s%s%s\\n\",\n st_failed ? p->st : \"\",\n st_failed && dyn_failed ? \"\\n\" : \"\",\n dyn_failed ? p->dyn : \"\");\n }\n}\n\ndouble\nMathExprPowerModel::eval(const MathExpr &expr) const\n{\n const double value = tryEval(expr);\n\n \/\/ This shouldn't happen unless something went wrong the equations\n \/\/ were verified in startup().\n panic_if(failed, \"Failed to evaluate power expression '%s'\\n\",\n expr.toStr());\n\n return value;\n}\n\ndouble\nMathExprPowerModel::tryEval(const MathExpr &expr) const\n{\n failed = false;\n const double value = expr.eval(\n std::bind(&MathExprPowerModel::getStatValue,\n this, std::placeholders::_1)\n );\n\n return value;\n}\n\n\ndouble\nMathExprPowerModel::getStatValue(const std::string &name) const\n{\n using namespace Stats;\n\n \/\/ Automatic variables:\n if (name == \"temp\") {\n return _temp;\n } else if (name == \"voltage\") {\n return clocked_object->voltage();\n }\n\n \/\/ Try to cast the stat, only these are supported right now\n const auto it = stats_map.find(name);\n if (it == stats_map.cend()) {\n warn(\"Failed to find stat '%s'\\n\", name);\n failed = true;\n return 0;\n }\n\n const Info *info = it->second;\n\n auto si = dynamic_cast<const ScalarInfo *>(info);\n if (si)\n return si->value();\n auto fi = dynamic_cast<const FormulaInfo *>(info);\n if (fi)\n return fi->total();\n\n panic(\"Unknown stat type!\\n\");\n}\n\nvoid\nMathExprPowerModel::regStats()\n{\n PowerModelState::regStats();\n}\n\nMathExprPowerModel*\nMathExprPowerModelParams::create()\n{\n return new MathExprPowerModel(this);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/renderer_host\/accelerated_surface_container_linux.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"content\/browser\/renderer_host\/image_transport_client.h\"\n#include \"ui\/gfx\/compositor\/compositor_cc.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/transform.h\"\n\nnamespace {\n\nclass AcceleratedSurfaceContainerLinuxCC\n : public AcceleratedSurfaceContainerLinux, public ui::TextureCC {\n public:\n explicit AcceleratedSurfaceContainerLinuxCC(const gfx::Size& size)\n : size_(size),\n acquired_(false) {\n }\n\n virtual ~AcceleratedSurfaceContainerLinuxCC() {\n if (image_transport_client_.get())\n image_transport_client_->Release();\n }\n\n virtual void AddRef() { ui::TextureCC::AddRef(); }\n virtual void Release() { ui::TextureCC::Release(); }\n\n virtual bool Initialize(uint64* surface_id) OVERRIDE {\n ui::SharedResourcesCC* instance = ui::SharedResourcesCC::GetInstance();\n DCHECK(instance);\n image_transport_client_.reset(\n ImageTransportClient::Create(instance, size_));\n if (!image_transport_client_.get())\n return false;\n\n texture_id_ = image_transport_client_->Initialize(surface_id);\n if (!texture_id_) {\n image_transport_client_.reset();\n return false;\n }\n flipped_ = image_transport_client_->Flipped();\n return true;\n }\n\n \/\/ TextureCC implementation\n virtual void Update() OVERRIDE {\n ui::SharedResourcesCC* instance = ui::SharedResourcesCC::GetInstance();\n DCHECK(instance);\n instance->MakeSharedContextCurrent();\n if (acquired_)\n image_transport_client_->Release();\n else\n acquired_ = true;\n image_transport_client_->Acquire();\n }\n\n virtual TransportDIB::Handle Handle() const {\n return image_transport_client_->Handle();\n }\n\n virtual ui::Texture* GetTexture() { return this; }\n\n private:\n scoped_ptr<ImageTransportClient> image_transport_client_;\n gfx::Size size_;\n bool acquired_;\n DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerLinuxCC);\n};\n\n} \/\/ namespace\n\n\/\/ static\nAcceleratedSurfaceContainerLinux*\nAcceleratedSurfaceContainerLinux::Create(const gfx::Size& size) {\n return new AcceleratedSurfaceContainerLinuxCC(size);\n}\n<commit_msg>aura\/cc: Fix GPU leak on resize.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/renderer_host\/accelerated_surface_container_linux.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"content\/browser\/renderer_host\/image_transport_client.h\"\n#include \"ui\/gfx\/compositor\/compositor_cc.h\"\n#include \"ui\/gfx\/gl\/gl_bindings.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/transform.h\"\n\nnamespace {\n\nclass AcceleratedSurfaceContainerLinuxCC\n : public AcceleratedSurfaceContainerLinux, public ui::TextureCC {\n public:\n explicit AcceleratedSurfaceContainerLinuxCC(const gfx::Size& size)\n : size_(size),\n acquired_(false) {\n }\n\n virtual ~AcceleratedSurfaceContainerLinuxCC() {\n if (texture_id_) {\n ui::SharedResourcesCC* instance = ui::SharedResourcesCC::GetInstance();\n DCHECK(instance);\n instance->MakeSharedContextCurrent();\n glDeleteTextures(1, &texture_id_);\n }\n\n if (image_transport_client_.get())\n image_transport_client_->Release();\n }\n\n virtual void AddRef() { ui::TextureCC::AddRef(); }\n virtual void Release() { ui::TextureCC::Release(); }\n\n virtual bool Initialize(uint64* surface_id) OVERRIDE {\n ui::SharedResourcesCC* instance = ui::SharedResourcesCC::GetInstance();\n DCHECK(instance);\n image_transport_client_.reset(\n ImageTransportClient::Create(instance, size_));\n if (!image_transport_client_.get())\n return false;\n\n texture_id_ = image_transport_client_->Initialize(surface_id);\n if (!texture_id_) {\n image_transport_client_.reset();\n return false;\n }\n flipped_ = image_transport_client_->Flipped();\n return true;\n }\n\n \/\/ TextureCC implementation\n virtual void Update() OVERRIDE {\n ui::SharedResourcesCC* instance = ui::SharedResourcesCC::GetInstance();\n DCHECK(instance);\n instance->MakeSharedContextCurrent();\n if (acquired_)\n image_transport_client_->Release();\n else\n acquired_ = true;\n image_transport_client_->Acquire();\n }\n\n virtual TransportDIB::Handle Handle() const {\n return image_transport_client_->Handle();\n }\n\n virtual ui::Texture* GetTexture() { return this; }\n\n private:\n scoped_ptr<ImageTransportClient> image_transport_client_;\n gfx::Size size_;\n bool acquired_;\n DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerLinuxCC);\n};\n\n} \/\/ namespace\n\n\/\/ static\nAcceleratedSurfaceContainerLinux*\nAcceleratedSurfaceContainerLinux::Create(const gfx::Size& size) {\n return new AcceleratedSurfaceContainerLinuxCC(size);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2009-2012, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NGT platform is licensed under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance with the\n\/\/ License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ __END_LICENSE__\n\n\n#include <asp\/Core\/InterestPointMatching.h>\n\nusing namespace vw;\n\nnamespace asp {\n\n Vector3 datum_intersection( cartography::Datum const& datum,\n camera::CameraModel* model,\n Vector2 const& pix ) {\n using namespace vw;\n\n \/\/ Intersect the ray back-projected from the camera with the\n \/\/ datum, which is a spheroid. To simplify the calculations, scale\n \/\/ everything in such a way that the spheroid becomes a\n \/\/ sphere. Scale back at the end of computation.\n\n double z_scale = datum.semi_major_axis() \/ datum.semi_minor_axis();\n\n Vector3 ccenter = model->camera_center( pix );\n Vector3 cvec = model->pixel_to_vector( pix );\n ccenter.z() *= z_scale;\n cvec.z() *= z_scale;\n cvec = normalize(cvec);\n double radius_2 = datum.semi_major_axis() *\n datum.semi_major_axis();\n double alpha = -dot_prod(ccenter, cvec );\n Vector3 projection = ccenter + alpha*cvec;\n if ( norm_2_sqr(projection) > radius_2 ) {\n \/\/ did not intersect\n return Vector3();\n }\n\n alpha -= sqrt( radius_2 -\n norm_2_sqr(projection) );\n return elem_prod(ccenter + alpha * cvec, Vector3(1,1,1.0\/z_scale));\n }\n\n \/\/ Find a rough homography that maps right to left using the camera\n \/\/ and datum information.\n Matrix<double>\n rough_homography_fit( camera::CameraModel* cam1,\n camera::CameraModel* cam2,\n BBox2i const& box1, BBox2i const& box2,\n cartography::Datum const& datum ) {\n\n \/\/ Bounce several points off the datum and fit an affine.\n std::vector<Vector3> left_points, right_points;\n left_points.reserve(20000);\n right_points.reserve(20000);\n for ( size_t i = 0; i < 100; i++ ) {\n for ( size_t j = 0; j < 100; j++ ) {\n try {\n Vector2 l( double(box1.width() - 1) * i \/ 99.0,\n double(box1.height() - 1) * j \/ 99.0 );\n\n Vector3 intersection =\n datum_intersection( datum, cam1, l );\n if ( intersection == Vector3() )\n continue;\n\n Vector2 r = cam2->point_to_pixel( intersection );\n\n if ( box2.contains( r ) ) {\n left_points.push_back( Vector3(l[0],l[1],1) );\n right_points.push_back( Vector3(r[0],r[1],1) );\n }\n } catch (camera::PixelToRayErr const& e ) {}\n try {\n Vector2 r( double(box2.width() - 1) * i \/ 99.0,\n double(box2.height() - 1) * j \/ 99.0 );\n\n Vector3 intersection =\n datum_intersection( datum, cam2, r );\n if ( intersection == Vector3() )\n continue;\n\n Vector2 l = cam1->point_to_pixel( intersection );\n\n if ( box1.contains( l ) ) {\n left_points.push_back( Vector3(l[0],l[1],1) );\n right_points.push_back( Vector3(r[0],r[1],1) );\n }\n } catch (camera::PixelToRayErr const& e ) {}\n }\n }\n\n VW_OUT( DebugMessage, \"asp\" ) << \"Projected \" << left_points.size()\n << \" rays for rough homography.\\n\";\n\n typedef math::HomographyFittingFunctor hfit_func;\n math::RandomSampleConsensus<hfit_func, math::InterestPointErrorMetric> ransac( hfit_func(), math::InterestPointErrorMetric(), norm_2(Vector2(box1.height(),box1.width())) \/ 10 );\n Matrix<double> H = ransac( right_points, left_points );\n std::vector<size_t> indices = ransac.inlier_indices(H, right_points, left_points);\n\n if ( indices.size() < std::min( right_points.size(), left_points.size() )\/3 ){\n vw_throw( ArgumentErr() << \"InterestPointMatching: The number of inliers is less than 1\/3 of the number of points. The homography fit is inaccurate.\\n\" );\n }\n \n double det = H(0, 0)*H(1, 1) - H(0, 1)*H(1, 0);\n if (det <= 0.0 || det > 2.0){\n vw_throw( ArgumentErr() << \"InterestPointMatching: The determinant of homography matrix is negative or too large. The homography fit is inaccurate.\\n\" );\n }\n \n return H;\n }\n\n vw::Matrix<double>\n homography_fit( std::vector<vw::ip::InterestPoint> const& ip1,\n std::vector<vw::ip::InterestPoint> const& ip2,\n vw::BBox2i const& image_size ) {\n using namespace vw;\n\n typedef math::HomographyFittingFunctor hfit_func;\n math::RandomSampleConsensus<hfit_func, math::InterestPointErrorMetric> ransac( hfit_func(), math::InterestPointErrorMetric(), norm_2(Vector2(image_size.width(),image_size.height())) \/ 10 );\n std::vector<Vector3> copy1, copy2;\n copy1.reserve( ip1.size() );\n copy2.reserve( ip1.size() );\n for ( size_t i = 0; i < ip1.size(); i++ ) {\n copy1.push_back( Vector3(ip1[i].x, ip1[i].y, 1) );\n copy2.push_back( Vector3(ip2[i].x, ip2[i].y, 1) );\n }\n Matrix<double> ransac_result = ransac(copy1,copy2);\n return hfit_func()(copy1,copy2,ransac_result);\n }\n\n}\n<commit_msg>InterestPointMatching: Add comments.<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (c) 2009-2012, United States Government as represented by the\n\/\/ Administrator of the National Aeronautics and Space Administration. All\n\/\/ rights reserved.\n\/\/\n\/\/ The NGT platform is licensed under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance with the\n\/\/ License. You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ __END_LICENSE__\n\n\n#include <asp\/Core\/InterestPointMatching.h>\n\nusing namespace vw;\n\nnamespace asp {\n\n Vector3 datum_intersection( cartography::Datum const& datum,\n camera::CameraModel* model,\n Vector2 const& pix ) {\n using namespace vw;\n\n \/\/ Intersect the ray back-projected from the camera with the\n \/\/ datum, which is a spheroid. To simplify the calculations, scale\n \/\/ everything in such a way that the spheroid becomes a\n \/\/ sphere. Scale back at the end of computation.\n\n double z_scale = datum.semi_major_axis() \/ datum.semi_minor_axis();\n\n Vector3 ccenter = model->camera_center( pix );\n Vector3 cvec = model->pixel_to_vector( pix );\n ccenter.z() *= z_scale;\n cvec.z() *= z_scale;\n cvec = normalize(cvec);\n double radius_2 = datum.semi_major_axis() *\n datum.semi_major_axis();\n double alpha = -dot_prod(ccenter, cvec );\n Vector3 projection = ccenter + alpha*cvec;\n if ( norm_2_sqr(projection) > radius_2 ) {\n \/\/ did not intersect\n return Vector3();\n }\n\n alpha -= sqrt( radius_2 -\n norm_2_sqr(projection) );\n return elem_prod(ccenter + alpha * cvec, Vector3(1,1,1.0\/z_scale));\n }\n\n \/\/ Find a rough homography that maps right to left using the camera\n \/\/ and datum information.\n Matrix<double>\n rough_homography_fit( camera::CameraModel* cam1,\n camera::CameraModel* cam2,\n BBox2i const& box1, BBox2i const& box2,\n cartography::Datum const& datum ) {\n\n \/\/ Bounce several points off the datum and fit an affine.\n std::vector<Vector3> left_points, right_points;\n left_points.reserve(20000);\n right_points.reserve(20000);\n for ( size_t i = 0; i < 100; i++ ) {\n for ( size_t j = 0; j < 100; j++ ) {\n try {\n Vector2 l( double(box1.width() - 1) * i \/ 99.0,\n double(box1.height() - 1) * j \/ 99.0 );\n\n Vector3 intersection =\n datum_intersection( datum, cam1, l );\n if ( intersection == Vector3() )\n continue;\n\n Vector2 r = cam2->point_to_pixel( intersection );\n\n if ( box2.contains( r ) ) {\n left_points.push_back( Vector3(l[0],l[1],1) );\n right_points.push_back( Vector3(r[0],r[1],1) );\n }\n } catch (camera::PixelToRayErr const& e ) {}\n try {\n Vector2 r( double(box2.width() - 1) * i \/ 99.0,\n double(box2.height() - 1) * j \/ 99.0 );\n\n Vector3 intersection =\n datum_intersection( datum, cam2, r );\n if ( intersection == Vector3() )\n continue;\n\n Vector2 l = cam1->point_to_pixel( intersection );\n\n if ( box1.contains( l ) ) {\n left_points.push_back( Vector3(l[0],l[1],1) );\n right_points.push_back( Vector3(r[0],r[1],1) );\n }\n } catch (camera::PixelToRayErr const& e ) {}\n }\n }\n\n VW_OUT( DebugMessage, \"asp\" ) << \"Projected \" << left_points.size()\n << \" rays for rough homography.\\n\";\n\n typedef math::HomographyFittingFunctor hfit_func;\n math::RandomSampleConsensus<hfit_func, math::InterestPointErrorMetric> ransac( hfit_func(), math::InterestPointErrorMetric(), norm_2(Vector2(box1.height(),box1.width())) \/ 10 );\n Matrix<double> H = ransac( right_points, left_points );\n std::vector<size_t> indices = ransac.inlier_indices(H, right_points, left_points);\n\n \/\/ Sanity checks. If these fail, most likely the two images are too different\n \/\/ for stereo to succeed.\n if ( indices.size() < std::min( right_points.size(), left_points.size() )\/3 ){\n vw_throw( ArgumentErr() << \"InterestPointMatching: The number of inliers is less than 1\/3 of the number of points. The homography fit is inaccurate.\\n\" );\n }\n \n double det = H(0, 0)*H(1, 1) - H(0, 1)*H(1, 0);\n if (det <= 0.0 || det > 2.0){\n vw_throw( ArgumentErr() << \"InterestPointMatching: The determinant of homography matrix is negative or too large. The homography fit is inaccurate.\\n\" );\n }\n \n return H;\n }\n\n vw::Matrix<double>\n homography_fit( std::vector<vw::ip::InterestPoint> const& ip1,\n std::vector<vw::ip::InterestPoint> const& ip2,\n vw::BBox2i const& image_size ) {\n using namespace vw;\n\n typedef math::HomographyFittingFunctor hfit_func;\n math::RandomSampleConsensus<hfit_func, math::InterestPointErrorMetric> ransac( hfit_func(), math::InterestPointErrorMetric(), norm_2(Vector2(image_size.width(),image_size.height())) \/ 10 );\n std::vector<Vector3> copy1, copy2;\n copy1.reserve( ip1.size() );\n copy2.reserve( ip1.size() );\n for ( size_t i = 0; i < ip1.size(); i++ ) {\n copy1.push_back( Vector3(ip1[i].x, ip1[i].y, 1) );\n copy2.push_back( Vector3(ip2[i].x, ip2[i].y, 1) );\n }\n Matrix<double> ransac_result = ransac(copy1,copy2);\n return hfit_func()(copy1,copy2,ransac_result);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * RIppleLikeTransactionDatabaseHelper\n *\n * Created by El Khalil Bellakrid on 06\/01\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n\n#include \"RippleLikeTransactionDatabaseHelper.h\"\n#include <database\/soci-option.h>\n#include <database\/soci-date.h>\n#include <database\/soci-number.h>\n#include <crypto\/SHA256.hpp>\n#include <wallet\/common\/database\/BlockDatabaseHelper.h>\n\nusing namespace soci;\n\nnamespace ledger {\n namespace core {\n\n bool RippleLikeTransactionDatabaseHelper::getTransactionByHash(soci::session &sql,\n const std::string &hash,\n RippleLikeBlockchainExplorerTransaction &tx) {\n\n rowset<row> rows = (sql.prepare << \"SELECT tx.hash, tx.value, tx.time, \"\n \" tx.sender, tx.receiver, tx.fees, tx.confirmations, \"\n \"block.height, block.hash, block.time, block.currency_name, \"\n \"memo.data, memo.fmt, memo.ty \"\n \"FROM ripple_transactions AS tx \"\n \"LEFT JOIN blocks AS block ON tx.block_uid = block.uid \"\n \"LEFT JOIN ripple_memos AS memo ON memo.transaction_uid = tx.transaction_uid \"\n \"WHERE tx.hash = :hash \"\n \"ORDER BY memo.array_index ASC\", use(hash));\n\n for (auto &row : rows) {\n inflateTransaction(sql, row, tx);\n return true;\n }\n\n return false;\n }\n\n bool RippleLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql,\n const soci::row &row,\n RippleLikeBlockchainExplorerTransaction &tx) {\n tx.hash = row.get<std::string>(0);\n tx.value = BigInt::fromHex(row.get<std::string>(1));\n tx.receivedAt = row.get<std::chrono::system_clock::time_point>(2);\n tx.sender = row.get<std::string>(3);\n tx.receiver = row.get<std::string>(4);\n tx.fees = BigInt::fromHex(row.get<std::string>(5));\n tx.confirmations = get_number<uint64_t>(row, 6);\n if (row.get_indicator(7) != i_null) {\n RippleLikeBlockchainExplorer::Block block;\n block.height = get_number<uint64_t>(row, 7);\n block.hash = row.get<std::string>(8);\n block.time = row.get<std::chrono::system_clock::time_point>(9);\n block.currencyName = row.get<std::string>(10);\n tx.block = block;\n }\n\n if (row.get_indicator(11) != i_null &&\n row.get_indicator(12) != i_null &&\n row.get_indicator(13) != i_null) {\n tx.memos.push_back(api::RippleLikeMemo(\n row.get<std::string>(11),\n row.get<std::string>(12),\n row.get<std::string>(13)\n ));\n }\n\n return true;\n }\n\n bool RippleLikeTransactionDatabaseHelper::transactionExists(soci::session &sql,\n const std::string &rippleTxUid) {\n int32_t count = 0;\n sql << \"SELECT COUNT(*) FROM ripple_transactions WHERE transaction_uid = :rippleTxUid\", use(rippleTxUid), into(\n count);\n return count == 1;\n }\n\n std::string RippleLikeTransactionDatabaseHelper::createRippleTransactionUid(const std::string &accountUid,\n const std::string &txHash) {\n auto result = SHA256::stringToHexHash(fmt::format(\"uid:{}+{}\", accountUid, txHash));\n return result;\n }\n\n std::string RippleLikeTransactionDatabaseHelper::putTransaction(soci::session &sql,\n const std::string &accountUid,\n const RippleLikeBlockchainExplorerTransaction &tx) {\n auto blockUid = tx.block.map<std::string>([](const RippleLikeBlockchainExplorer::Block &block) {\n return block.getUid();\n });\n\n auto rippleTxUid = createRippleTransactionUid(accountUid, tx.hash);\n\n if (transactionExists(sql, rippleTxUid)) {\n \/\/ UPDATE (we only update block information)\n if (tx.block.nonEmpty()) {\n sql << \"UPDATE ripple_transactions SET block_uid = :uid WHERE hash = :tx_hash\",\n use(blockUid), use(tx.hash);\n }\n return rippleTxUid;\n } else {\n \/\/ Insert\n if (tx.block.nonEmpty()) {\n BlockDatabaseHelper::putBlock(sql, tx.block.getValue());\n }\n auto hexValue = tx.value.toHexString();\n auto hexFees = tx.fees.toHexString();\n sql\n << \"INSERT INTO ripple_transactions VALUES(:tx_uid, :hash, :value, :block_uid, :time, :sender, :receiver, :fees, :confirmations)\",\n use(rippleTxUid),\n use(tx.hash),\n use(hexValue),\n use(blockUid),\n use(tx.receivedAt),\n use(tx.sender),\n use(tx.receiver),\n use(hexFees),\n use(tx.confirmations);\n\n int fieldIndex = 0;\n for (auto& memo : tx.memos) {\n sql << \"INSERT INTO ripple_memos VALUES (:tx_uid, :data, :fmt, :ty, :i)\",\n use(rippleTxUid),\n use(memo.data),\n use(memo.fmt),\n use(memo.ty),\n use(fieldIndex);\n\n ++fieldIndex;\n }\n\n return rippleTxUid;\n }\n }\n }\n}\n<commit_msg>Get sequence when inflating XRP transaction.<commit_after>\/*\n *\n * RIppleLikeTransactionDatabaseHelper\n *\n * Created by El Khalil Bellakrid on 06\/01\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n\n#include \"RippleLikeTransactionDatabaseHelper.h\"\n#include <database\/soci-option.h>\n#include <database\/soci-date.h>\n#include <database\/soci-number.h>\n#include <crypto\/SHA256.hpp>\n#include <wallet\/common\/database\/BlockDatabaseHelper.h>\n\nusing namespace soci;\n\nnamespace ledger {\n namespace core {\n\n bool RippleLikeTransactionDatabaseHelper::getTransactionByHash(soci::session &sql,\n const std::string &hash,\n RippleLikeBlockchainExplorerTransaction &tx) {\n\n rowset<row> rows = (sql.prepare << \"SELECT tx.hash, tx.value, tx.time, \"\n \" tx.sender, tx.receiver, tx.fees, tx.confirmations, \"\n \"block.height, block.hash, block.time, block.currency_name, \"\n \"memo.data, memo.fmt, memo.ty, tx.sequence \"\n \"FROM ripple_transactions AS tx \"\n \"LEFT JOIN blocks AS block ON tx.block_uid = block.uid \"\n \"LEFT JOIN ripple_memos AS memo ON memo.transaction_uid = tx.transaction_uid \"\n \"WHERE tx.hash = :hash \"\n \"ORDER BY memo.array_index ASC\", use(hash));\n\n for (auto &row : rows) {\n inflateTransaction(sql, row, tx);\n return true;\n }\n\n return false;\n }\n\n bool RippleLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql,\n const soci::row &row,\n RippleLikeBlockchainExplorerTransaction &tx) {\n tx.hash = row.get<std::string>(0);\n tx.value = BigInt::fromHex(row.get<std::string>(1));\n tx.receivedAt = row.get<std::chrono::system_clock::time_point>(2);\n tx.sender = row.get<std::string>(3);\n tx.receiver = row.get<std::string>(4);\n tx.fees = BigInt::fromHex(row.get<std::string>(5));\n tx.confirmations = get_number<uint64_t>(row, 6);\n if (row.get_indicator(7) != i_null) {\n RippleLikeBlockchainExplorer::Block block;\n block.height = get_number<uint64_t>(row, 7);\n block.hash = row.get<std::string>(8);\n block.time = row.get<std::chrono::system_clock::time_point>(9);\n block.currencyName = row.get<std::string>(10);\n tx.block = block;\n }\n\n if (row.get_indicator(11) != i_null &&\n row.get_indicator(12) != i_null &&\n row.get_indicator(13) != i_null) {\n tx.memos.push_back(api::RippleLikeMemo(\n row.get<std::string>(11),\n row.get<std::string>(12),\n row.get<std::string>(13)\n ));\n }\n\n tx.sequence = BigInt(row.get<std::string>(14));\n\n return true;\n }\n\n bool RippleLikeTransactionDatabaseHelper::transactionExists(soci::session &sql,\n const std::string &rippleTxUid) {\n int32_t count = 0;\n sql << \"SELECT COUNT(*) FROM ripple_transactions WHERE transaction_uid = :rippleTxUid\", use(rippleTxUid), into(\n count);\n return count == 1;\n }\n\n std::string RippleLikeTransactionDatabaseHelper::createRippleTransactionUid(const std::string &accountUid,\n const std::string &txHash) {\n auto result = SHA256::stringToHexHash(fmt::format(\"uid:{}+{}\", accountUid, txHash));\n return result;\n }\n\n std::string RippleLikeTransactionDatabaseHelper::putTransaction(soci::session &sql,\n const std::string &accountUid,\n const RippleLikeBlockchainExplorerTransaction &tx) {\n auto blockUid = tx.block.map<std::string>([](const RippleLikeBlockchainExplorer::Block &block) {\n return block.getUid();\n });\n\n auto rippleTxUid = createRippleTransactionUid(accountUid, tx.hash);\n\n if (transactionExists(sql, rippleTxUid)) {\n \/\/ UPDATE (we only update block information)\n if (tx.block.nonEmpty()) {\n sql << \"UPDATE ripple_transactions SET block_uid = :uid WHERE hash = :tx_hash\",\n use(blockUid), use(tx.hash);\n }\n return rippleTxUid;\n } else {\n \/\/ Insert\n if (tx.block.nonEmpty()) {\n BlockDatabaseHelper::putBlock(sql, tx.block.getValue());\n }\n auto hexValue = tx.value.toHexString();\n auto hexFees = tx.fees.toHexString();\n sql\n << \"INSERT INTO ripple_transactions VALUES(:tx_uid, :hash, :value, :block_uid, :time, :sender, :receiver, :fees, :confirmations)\",\n use(rippleTxUid),\n use(tx.hash),\n use(hexValue),\n use(blockUid),\n use(tx.receivedAt),\n use(tx.sender),\n use(tx.receiver),\n use(hexFees),\n use(tx.confirmations);\n\n int fieldIndex = 0;\n for (auto& memo : tx.memos) {\n sql << \"INSERT INTO ripple_memos VALUES (:tx_uid, :data, :fmt, :ty, :i)\",\n use(rippleTxUid),\n use(memo.data),\n use(memo.fmt),\n use(memo.ty),\n use(fieldIndex);\n\n ++fieldIndex;\n }\n\n return rippleTxUid;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2022 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \"modules\/server\/include\/topics\/skybrowsertopic.h\"\n\n#include <modules\/server\/include\/connection.h>\n#include <modules\/server\/servermodule.h>\n#include <modules\/skybrowser\/skybrowsermodule.h>\n#include <modules\/skybrowser\/include\/targetbrowserpair.h>\n#include <openspace\/engine\/moduleengine.h>\n#include <openspace\/engine\/globals.h>\n#include <openspace\/properties\/property.h>\n#include <openspace\/query\/query.h>\n#include <ghoul\/logging\/logmanager.h>\n\nnamespace {\n constexpr const char* EventKey = \"event\";\n constexpr const char* SubscribeEvent = \"start_subscription\";\n constexpr const char* UnsubscribeEvent = \"stop_subscription\";\n} \/\/ namespace\n\nusing nlohmann::json;\n\nnamespace openspace {\n\nSkyBrowserTopic::SkyBrowserTopic()\n : _lastUpdateTime(std::chrono::system_clock::now())\n{\n ServerModule* module = global::moduleEngine->module<ServerModule>();\n if (module) {\n _skyBrowserUpdateTime = std::chrono::milliseconds(module->skyBrowserUpdateTime());\n }\n}\n\nSkyBrowserTopic::~SkyBrowserTopic() {\n if (_targetDataCallbackHandle != UnsetOnChangeHandle) {\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n module->removePreSyncCallback(_targetDataCallbackHandle);\n }\n}\n\nbool SkyBrowserTopic::isDone() const {\n return _isDone;\n}\n\nvoid SkyBrowserTopic::handleJson(const nlohmann::json& json) {\n std::string event = json.at(EventKey).get<std::string>();\n if (event == UnsubscribeEvent) {\n _isDone = true;\n return;\n }\n\n if (event != SubscribeEvent) {\n _isDone = true;\n return;\n }\n\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n _targetDataCallbackHandle = module->addPreSyncCallback([this]() {\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n if (now - _lastUpdateTime > _skyBrowserUpdateTime) {\n sendBrowserData();\n _lastUpdateTime = std::chrono::system_clock::now();\n }\n });\n}\n\nvoid SkyBrowserTopic::sendBrowserData() {\n using namespace openspace;\n\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n ghoul::Dictionary data;\n\n \/\/ The current viewport data for OpenSpace\n ghoul::Dictionary openSpace;\n\n \/\/ Set general data\n data.setValue(\"selectedBrowserId\", module->selectedBrowserId());\n data.setValue(\"cameraInSolarSystem\", module->isCameraInSolarSystem());\n\n \/\/ Pass data for all the browsers and the corresponding targets\n if (module->isCameraInSolarSystem()) {\n const std::vector<std::unique_ptr<TargetBrowserPair>>& pairs = module->getPairs();\n ghoul::Dictionary targets;\n for (const std::unique_ptr<TargetBrowserPair>& pair : pairs) {\n std::string id = pair->browserId();\n \/\/ Convert deque to vector so ghoul can read it\n std::vector<int> selectedImagesVector;\n const std::deque<int> selectedImages = pair->selectedImages();\n std::for_each(\n selectedImages.begin(),\n selectedImages.end(),\n [&](int i) {\n selectedImagesVector.push_back(i);\n }\n );\n\n glm::dvec2 spherical = pair->targetDirectionEquatorial();\n glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical);\n\n ghoul::Dictionary target;\n \/\/ Set (\"Key\", value)\n target.setValue(\"id\", id);\n target.setValue(\"name\", pair->browserGuiName());\n target.setValue(\"fov\", static_cast<double>(pair->verticalFov()));\n target.setValue(\"ra\", spherical.x);\n target.setValue(\"dec\", spherical.y);\n target.setValue(\"roll\", pair->targetRoll());\n target.setValue(\"color\", pair->borderColor());\n target.setValue(\"cartesianDirection\", cartesian);\n target.setValue(\"ratio\", static_cast<double>(pair->browserRatio()));\n target.setValue(\"isFacingCamera\", pair->isFacingCamera());\n target.setValue(\"isUsingRae\", pair->isUsingRadiusAzimuthElevation());\n target.setValue(\"selectedImages\", selectedImagesVector);\n\n std::vector<std::pair<std::string, glm::dvec3>> copies = pair->renderCopies();\n ghoul::Dictionary copiesData;\n for (size_t i = 0; i < copies.size(); i++) {\n copiesData.setValue(copies[i].first, copies[i].second);\n }\n \/\/ Set table for the current target\n target.setValue(\"renderCopies\", copiesData);\n targets.setValue(id, target);\n }\n data.setValue(\"browsers\", targets);\n }\n std::string jsonString = ghoul::formatJson(data);\n json jsonData = json::parse(jsonString.begin(), jsonString.end());\n _connection->sendJson(wrappedPayload(jsonData));\n}\n\n} \/\/ namespace openspace\n<commit_msg>Don't try to access module if it no longer exists<commit_after>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2022 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \"modules\/server\/include\/topics\/skybrowsertopic.h\"\n\n#include <modules\/server\/include\/connection.h>\n#include <modules\/server\/servermodule.h>\n#include <modules\/skybrowser\/skybrowsermodule.h>\n#include <modules\/skybrowser\/include\/targetbrowserpair.h>\n#include <openspace\/engine\/moduleengine.h>\n#include <openspace\/engine\/globals.h>\n#include <openspace\/properties\/property.h>\n#include <openspace\/query\/query.h>\n#include <ghoul\/logging\/logmanager.h>\n\nnamespace {\n constexpr const char* EventKey = \"event\";\n constexpr const char* SubscribeEvent = \"start_subscription\";\n constexpr const char* UnsubscribeEvent = \"stop_subscription\";\n} \/\/ namespace\n\nusing nlohmann::json;\n\nnamespace openspace {\n\nSkyBrowserTopic::SkyBrowserTopic()\n : _lastUpdateTime(std::chrono::system_clock::now())\n{\n ServerModule* module = global::moduleEngine->module<ServerModule>();\n if (module) {\n _skyBrowserUpdateTime = std::chrono::milliseconds(module->skyBrowserUpdateTime());\n }\n}\n\nSkyBrowserTopic::~SkyBrowserTopic() {\n if (_targetDataCallbackHandle != UnsetOnChangeHandle) {\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n if (module) {\n module->removePreSyncCallback(_targetDataCallbackHandle);\n }\n }\n}\n\nbool SkyBrowserTopic::isDone() const {\n return _isDone;\n}\n\nvoid SkyBrowserTopic::handleJson(const nlohmann::json& json) {\n std::string event = json.at(EventKey).get<std::string>();\n if (event == UnsubscribeEvent) {\n _isDone = true;\n return;\n }\n\n if (event != SubscribeEvent) {\n _isDone = true;\n return;\n }\n\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n _targetDataCallbackHandle = module->addPreSyncCallback([this]() {\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n if (now - _lastUpdateTime > _skyBrowserUpdateTime) {\n sendBrowserData();\n _lastUpdateTime = std::chrono::system_clock::now();\n }\n });\n}\n\nvoid SkyBrowserTopic::sendBrowserData() {\n using namespace openspace;\n\n SkyBrowserModule* module = global::moduleEngine->module<SkyBrowserModule>();\n ghoul::Dictionary data;\n\n \/\/ The current viewport data for OpenSpace\n ghoul::Dictionary openSpace;\n\n \/\/ Set general data\n data.setValue(\"selectedBrowserId\", module->selectedBrowserId());\n data.setValue(\"cameraInSolarSystem\", module->isCameraInSolarSystem());\n\n \/\/ Pass data for all the browsers and the corresponding targets\n if (module->isCameraInSolarSystem()) {\n const std::vector<std::unique_ptr<TargetBrowserPair>>& pairs = module->getPairs();\n ghoul::Dictionary targets;\n for (const std::unique_ptr<TargetBrowserPair>& pair : pairs) {\n std::string id = pair->browserId();\n \/\/ Convert deque to vector so ghoul can read it\n std::vector<int> selectedImagesVector;\n const std::deque<int> selectedImages = pair->selectedImages();\n std::for_each(\n selectedImages.begin(),\n selectedImages.end(),\n [&](int i) {\n selectedImagesVector.push_back(i);\n }\n );\n\n glm::dvec2 spherical = pair->targetDirectionEquatorial();\n glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical);\n\n ghoul::Dictionary target;\n \/\/ Set (\"Key\", value)\n target.setValue(\"id\", id);\n target.setValue(\"name\", pair->browserGuiName());\n target.setValue(\"fov\", static_cast<double>(pair->verticalFov()));\n target.setValue(\"ra\", spherical.x);\n target.setValue(\"dec\", spherical.y);\n target.setValue(\"roll\", pair->targetRoll());\n target.setValue(\"color\", pair->borderColor());\n target.setValue(\"cartesianDirection\", cartesian);\n target.setValue(\"ratio\", static_cast<double>(pair->browserRatio()));\n target.setValue(\"isFacingCamera\", pair->isFacingCamera());\n target.setValue(\"isUsingRae\", pair->isUsingRadiusAzimuthElevation());\n target.setValue(\"selectedImages\", selectedImagesVector);\n\n std::vector<std::pair<std::string, glm::dvec3>> copies = pair->renderCopies();\n ghoul::Dictionary copiesData;\n for (size_t i = 0; i < copies.size(); i++) {\n copiesData.setValue(copies[i].first, copies[i].second);\n }\n \/\/ Set table for the current target\n target.setValue(\"renderCopies\", copiesData);\n targets.setValue(id, target);\n }\n data.setValue(\"browsers\", targets);\n }\n std::string jsonString = ghoul::formatJson(data);\n json jsonData = json::parse(jsonString.begin(), jsonString.end());\n _connection->sendJson(wrappedPayload(jsonData));\n}\n\n} \/\/ namespace openspace\n<|endoftext|>"} {"text":"<commit_before>#ifndef slic3r_Mouse3DController_hpp_\n#define slic3r_Mouse3DController_hpp_\n\n\/\/ Enabled debug output to console and extended imgui dialog\n#define ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT 0\n\n#include \"libslic3r\/Point.hpp\"\n\n#include \"hidapi.h\"\n\n#include <queue>\n#include <thread>\n#include <vector>\n#include <chrono>\n\n#include <tbb\/mutex.h>\n\nnamespace Slic3r {\n\nclass AppConfig;\n\nnamespace GUI {\n\nstruct Camera;\nclass GLCanvas3D;\n\nclass Mouse3DController\n{\n\t\/\/ Parameters, which are configured by the ImGUI dialog when pressing Ctrl+M.\n\t\/\/ The UI thread modifies a copy of the parameters and indicates to the background thread that there was a change\n\t\/\/ to copy the parameters.\n\tstruct Params\n\t{\n\t\tstatic constexpr double DefaultTranslationScale = 2.5;\n\t\tstatic constexpr double MaxTranslationDeadzone = 0.2;\n\t\tstatic constexpr double DefaultTranslationDeadzone = 0.5 * MaxTranslationDeadzone;\n\t\tstatic constexpr float DefaultRotationScale = 1.0f;\n\t\tstatic constexpr float MaxRotationDeadzone = 0.2f;\n\t\tstatic constexpr float DefaultRotationDeadzone = 0.5f * MaxRotationDeadzone;\n\t\tstatic constexpr double DefaultZoomScale = 0.1;\n\n template <typename Number>\n struct CustomParameters\n {\n Number scale;\n Number deadzone;\n };\n\n CustomParameters<double> translation { DefaultTranslationScale, DefaultTranslationDeadzone };\n CustomParameters<float> rotation { DefaultRotationScale, DefaultRotationDeadzone };\n CustomParameters<double> zoom { DefaultZoomScale, 0.0 };\n \/\/ Do not process button presses from 3DConnexion device, let the user map the 3DConnexion keys in 3DConnexion driver.\n bool \t\t\t\t\t buttons_enabled { false };\n \/\/ The default value of 15 for max_size seems to work fine on all platforms\n \/\/ The effects of changing this value can be tested by setting ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT to 1\n \/\/ and playing with the imgui dialog which shows by pressing CTRL+M\n size_t \t\t\t\t\t input_queue_max_size { 15 };\n\t};\n\n\t\/\/ Queue of the 3DConnexion input events (translations, rotations, button presses).\n class State\n {\n public:\n struct QueueItem {\n static QueueItem translation(const Vec3d &translation) { QueueItem out; out.vector = translation; out.type_or_buttons = TranslationType; return out; }\n static QueueItem rotation(const Vec3d &rotation) { QueueItem out; out.vector = rotation; out.type_or_buttons = RotationType; return out; }\n static QueueItem buttons(unsigned int buttons) { QueueItem out; out.type_or_buttons = buttons; return out; }\n\n bool \t\t\t is_translation() const { return this->type_or_buttons == TranslationType; }\n bool \t\t\t is_rotation() const { return this->type_or_buttons == RotationType; }\n bool \t\t\t is_buttons() const { return ! this->is_translation() && ! this->is_rotation(); }\n\n Vec3d \t vector;\n unsigned int \t type_or_buttons;\n\n static constexpr unsigned int TranslationType = std::numeric_limits<unsigned int>::max();\n static constexpr unsigned int RotationType = TranslationType - 1;\n };\n\n private:\n \t\/\/ m_input_queue is accessed by the background thread and by the UI thread. Access to m_input_queue\n \t\/\/ is guarded with m_input_queue_mutex.\n std::deque<QueueItem> m_input_queue;\n mutable tbb::mutex\t m_input_queue_mutex;\n\n#ifdef WIN32\n \/\/ When the 3Dconnexion driver is running the system gets, by default, mouse wheel events when rotations around the X axis are detected.\n \/\/ We want to filter these out because we are getting the data directly from the device, bypassing the driver, and those mouse wheel events interfere\n \/\/ by triggering unwanted zoom in\/out of the scene\n \/\/ The following variable is used to count the potential mouse wheel events triggered and is updated by: \n \/\/ Mouse3DController::collect_input() through the call to the append_rotation() method\n \/\/ GLCanvas3D::on_mouse_wheel() through the call to the process_mouse_wheel() method\n \/\/ GLCanvas3D::on_idle() through the call to the apply() method\n unsigned int \t\t m_mouse_wheel_counter { 0 };\n#endif \/* WIN32 *\/\n\n public:\n \/\/ Called by the background thread or by by Mouse3DHandlerMac.mm when a new event is received from 3DConnexion device.\n void append_translation(const Vec3d& translation, size_t input_queue_max_size);\n void append_rotation(const Vec3f& rotation, size_t input_queue_max_size);\n void append_button(unsigned int id, size_t input_queue_max_size);\n\n#ifdef WIN32\n \/\/ Called by GLCanvas3D::on_mouse_wheel(wxMouseEvent& evt)\n \/\/ to filter out spurious mouse scroll events produced by the 3DConnexion driver on Windows.\n bool process_mouse_wheel();\n#endif \/* WIN32 *\/\n\n#if ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT\n Vec3d get_first_vector_of_type(unsigned int type) const {\n tbb::mutex::scoped_lock lock(m_input_queue_mutex);\n auto it = std::find_if(m_input_queue.begin(), m_input_queue.end(), [type](const QueueItem& item) { return item.type_or_buttons == type; });\n return (it == m_input_queue.end()) ? Vec3d::Zero() : it->vector;\n }\n size_t input_queue_size_current() const { \n \ttbb::mutex::scoped_lock lock(m_input_queue_mutex); \n \treturn m_input_queue.size(); \n }\n std::atomic<size_t> input_queue_max_size_achieved;\n#endif \/\/ ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT\n\n \/\/ Apply the 3DConnexion events stored in the input queue, reset the input queue.\n \/\/ Returns true if any change to the camera took place.\n bool apply(const Params ¶ms, Camera& camera);\n };\n\n \/\/ Background thread works with this copy.\n Params \t\t\t\tm_params;\n \/\/ UI thread will read \/ write this copy.\n Params \t\t\t\tm_params_ui;\n bool \t m_params_ui_changed { false };\n mutable tbb::mutex\tm_params_ui_mutex;\n\n \/\/ This is a database of parametes of all 3DConnexion devices ever connected.\n \/\/ This database is loaded from AppConfig on application start and it is stored to AppConfig on application exit.\n \/\/ We need to do that as the AppConfig is not thread safe and we need read the parameters on device connect \/ disconnect,\n \/\/ which is now done by a background thread.\n std::map<std::string, Params> m_params_by_device;\n\n mutable State \t\tm_state;\n std::atomic<bool> \tm_connected;\n std::string \t\tm_device_str;\n\n#if ! __APPLE__\n \/\/ Worker thread for enumerating devices, connecting, reading data from the device and closing the device.\n std::thread \t\tm_thread;\n hid_device* \t\tm_device { nullptr };\n \/\/ Using m_stop_condition_mutex to synchronize m_stop.\n bool\t\t\t\tm_stop { false };\n \/\/ Mutex and condition variable for sleeping during the detection of 3DConnexion devices by polling while allowing\n \/\/ cancellation before the end of the polling interval.\n\tstd::mutex \t\t\tm_stop_condition_mutex;\n \tstd::condition_variable m_stop_condition;\n#endif\n\n \t\/\/ Is the ImGUI dialog shown? Accessed from UI thread only.\n mutable bool \t\tm_show_settings_dialog { false };\n \/\/ Set to true when ther user closes the dialog by clicking on [X] or [Close] buttons. Accessed from UI thread only.\n mutable bool \t\tm_settings_dialog_closed_by_user { false };\n\npublic:\n\t\/\/ Load the device parameter database from appconfig. To be called on application startup.\n\tvoid load_config(const AppConfig &appconfig);\n\t\/\/ Store the device parameter database back to appconfig. To be called on application closeup.\n\tvoid save_config(AppConfig &appconfig) const;\n\t\/\/ Start the background thread to detect and connect to a HID device (Windows and Linux).\n\t\/\/ Connect to a 3DConnextion driver (OSX).\n\t\/\/ Call load_config() before init().\n void init();\n\t\/\/ Stop the background thread (Windows and Linux).\n\t\/\/ Disconnect from a 3DConnextion driver (OSX).\n\t\/\/ Call save_config() after shutdown().\n void shutdown();\n\n bool connected() const { return m_connected; }\n\n#if __APPLE__\n \/\/ Interfacing with the Objective C code (MouseHandlerMac.mm)\n void connected(std::string device_name);\n void disconnected();\n typedef std::array<double, 6> DataPacketAxis;\n\t\/\/ Unpack a 3DConnexion packet provided by the 3DConnexion driver into m_state. Called by Mouse3DHandlerMac.mm\n bool handle_input(const DataPacketAxis& packet);\n#endif \/\/ __APPLE__\n\n#ifdef WIN32\n \/\/ On Windows, the 3DConnexion driver sends out mouse wheel rotation events to an active application\n \/\/ if the application does not register at the driver. This is a workaround to ignore these superfluous\n \/\/ mouse wheel events.\n bool process_mouse_wheel() { return m_state.process_mouse_wheel(); }\n#endif \/\/ WIN32\n\n \/\/ Apply the received 3DConnexion mouse events to the camera. Called from the UI rendering thread.\n bool apply(Camera& camera);\n\n bool is_settings_dialog_shown() const { return m_show_settings_dialog; }\n void show_settings_dialog(bool show) { m_show_settings_dialog = show && this->connected(); }\n void render_settings_dialog(GLCanvas3D& canvas) const;\n\n#if ! __APPLE__\nprivate:\n bool connect_device();\n void disconnect_device();\n\n \/\/ secondary thread methods\n void run();\n void collect_input();\n\n typedef std::array<unsigned char, 13> DataPacketRaw;\n\n\t\/\/ Unpack raw 3DConnexion HID packet of a wired 3D mouse into m_state. Called by the worker thread.\n static bool handle_input(const DataPacketRaw& packet, const int packet_lenght, const Params ¶ms, State &state_in_out);\n \/\/ The following is called by handle_input() from the worker thread.\n static bool handle_packet(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_wireless_packet(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_packet_translation(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_packet_rotation(const DataPacketRaw& packet, unsigned int first_byte, const Params ¶ms, State &state_in_out);\n static bool handle_packet_button(const DataPacketRaw& packet, unsigned int packet_size, const Params ¶ms, State &state_in_out);\n#endif \/* __APPLE__ *\/\n};\n\n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n\n#endif \/\/ slic3r_Mouse3DController_hpp_\n<commit_msg>Added a missing include<commit_after>#ifndef slic3r_Mouse3DController_hpp_\n#define slic3r_Mouse3DController_hpp_\n\n\/\/ Enabled debug output to console and extended imgui dialog\n#define ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT 0\n\n#include \"libslic3r\/Point.hpp\"\n\n#include \"hidapi.h\"\n\n#include <queue>\n#include <thread>\n#include <vector>\n#include <chrono>\n#include <condition_variable>\n\n#include <tbb\/mutex.h>\n\nnamespace Slic3r {\n\nclass AppConfig;\n\nnamespace GUI {\n\nstruct Camera;\nclass GLCanvas3D;\n\nclass Mouse3DController\n{\n\t\/\/ Parameters, which are configured by the ImGUI dialog when pressing Ctrl+M.\n\t\/\/ The UI thread modifies a copy of the parameters and indicates to the background thread that there was a change\n\t\/\/ to copy the parameters.\n\tstruct Params\n\t{\n\t\tstatic constexpr double DefaultTranslationScale = 2.5;\n\t\tstatic constexpr double MaxTranslationDeadzone = 0.2;\n\t\tstatic constexpr double DefaultTranslationDeadzone = 0.5 * MaxTranslationDeadzone;\n\t\tstatic constexpr float DefaultRotationScale = 1.0f;\n\t\tstatic constexpr float MaxRotationDeadzone = 0.2f;\n\t\tstatic constexpr float DefaultRotationDeadzone = 0.5f * MaxRotationDeadzone;\n\t\tstatic constexpr double DefaultZoomScale = 0.1;\n\n template <typename Number>\n struct CustomParameters\n {\n Number scale;\n Number deadzone;\n };\n\n CustomParameters<double> translation { DefaultTranslationScale, DefaultTranslationDeadzone };\n CustomParameters<float> rotation { DefaultRotationScale, DefaultRotationDeadzone };\n CustomParameters<double> zoom { DefaultZoomScale, 0.0 };\n \/\/ Do not process button presses from 3DConnexion device, let the user map the 3DConnexion keys in 3DConnexion driver.\n bool \t\t\t\t\t buttons_enabled { false };\n \/\/ The default value of 15 for max_size seems to work fine on all platforms\n \/\/ The effects of changing this value can be tested by setting ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT to 1\n \/\/ and playing with the imgui dialog which shows by pressing CTRL+M\n size_t \t\t\t\t\t input_queue_max_size { 15 };\n\t};\n\n\t\/\/ Queue of the 3DConnexion input events (translations, rotations, button presses).\n class State\n {\n public:\n struct QueueItem {\n static QueueItem translation(const Vec3d &translation) { QueueItem out; out.vector = translation; out.type_or_buttons = TranslationType; return out; }\n static QueueItem rotation(const Vec3d &rotation) { QueueItem out; out.vector = rotation; out.type_or_buttons = RotationType; return out; }\n static QueueItem buttons(unsigned int buttons) { QueueItem out; out.type_or_buttons = buttons; return out; }\n\n bool \t\t\t is_translation() const { return this->type_or_buttons == TranslationType; }\n bool \t\t\t is_rotation() const { return this->type_or_buttons == RotationType; }\n bool \t\t\t is_buttons() const { return ! this->is_translation() && ! this->is_rotation(); }\n\n Vec3d \t vector;\n unsigned int \t type_or_buttons;\n\n static constexpr unsigned int TranslationType = std::numeric_limits<unsigned int>::max();\n static constexpr unsigned int RotationType = TranslationType - 1;\n };\n\n private:\n \t\/\/ m_input_queue is accessed by the background thread and by the UI thread. Access to m_input_queue\n \t\/\/ is guarded with m_input_queue_mutex.\n std::deque<QueueItem> m_input_queue;\n mutable tbb::mutex\t m_input_queue_mutex;\n\n#ifdef WIN32\n \/\/ When the 3Dconnexion driver is running the system gets, by default, mouse wheel events when rotations around the X axis are detected.\n \/\/ We want to filter these out because we are getting the data directly from the device, bypassing the driver, and those mouse wheel events interfere\n \/\/ by triggering unwanted zoom in\/out of the scene\n \/\/ The following variable is used to count the potential mouse wheel events triggered and is updated by: \n \/\/ Mouse3DController::collect_input() through the call to the append_rotation() method\n \/\/ GLCanvas3D::on_mouse_wheel() through the call to the process_mouse_wheel() method\n \/\/ GLCanvas3D::on_idle() through the call to the apply() method\n unsigned int \t\t m_mouse_wheel_counter { 0 };\n#endif \/* WIN32 *\/\n\n public:\n \/\/ Called by the background thread or by by Mouse3DHandlerMac.mm when a new event is received from 3DConnexion device.\n void append_translation(const Vec3d& translation, size_t input_queue_max_size);\n void append_rotation(const Vec3f& rotation, size_t input_queue_max_size);\n void append_button(unsigned int id, size_t input_queue_max_size);\n\n#ifdef WIN32\n \/\/ Called by GLCanvas3D::on_mouse_wheel(wxMouseEvent& evt)\n \/\/ to filter out spurious mouse scroll events produced by the 3DConnexion driver on Windows.\n bool process_mouse_wheel();\n#endif \/* WIN32 *\/\n\n#if ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT\n Vec3d get_first_vector_of_type(unsigned int type) const {\n tbb::mutex::scoped_lock lock(m_input_queue_mutex);\n auto it = std::find_if(m_input_queue.begin(), m_input_queue.end(), [type](const QueueItem& item) { return item.type_or_buttons == type; });\n return (it == m_input_queue.end()) ? Vec3d::Zero() : it->vector;\n }\n size_t input_queue_size_current() const { \n \ttbb::mutex::scoped_lock lock(m_input_queue_mutex); \n \treturn m_input_queue.size(); \n }\n std::atomic<size_t> input_queue_max_size_achieved;\n#endif \/\/ ENABLE_3DCONNEXION_DEVICES_DEBUG_OUTPUT\n\n \/\/ Apply the 3DConnexion events stored in the input queue, reset the input queue.\n \/\/ Returns true if any change to the camera took place.\n bool apply(const Params ¶ms, Camera& camera);\n };\n\n \/\/ Background thread works with this copy.\n Params \t\t\t\tm_params;\n \/\/ UI thread will read \/ write this copy.\n Params \t\t\t\tm_params_ui;\n bool \t m_params_ui_changed { false };\n mutable tbb::mutex\tm_params_ui_mutex;\n\n \/\/ This is a database of parametes of all 3DConnexion devices ever connected.\n \/\/ This database is loaded from AppConfig on application start and it is stored to AppConfig on application exit.\n \/\/ We need to do that as the AppConfig is not thread safe and we need read the parameters on device connect \/ disconnect,\n \/\/ which is now done by a background thread.\n std::map<std::string, Params> m_params_by_device;\n\n mutable State \t\tm_state;\n std::atomic<bool> \tm_connected;\n std::string \t\tm_device_str;\n\n#if ! __APPLE__\n \/\/ Worker thread for enumerating devices, connecting, reading data from the device and closing the device.\n std::thread \t\tm_thread;\n hid_device* \t\tm_device { nullptr };\n \/\/ Using m_stop_condition_mutex to synchronize m_stop.\n bool\t\t\t\tm_stop { false };\n \/\/ Mutex and condition variable for sleeping during the detection of 3DConnexion devices by polling while allowing\n \/\/ cancellation before the end of the polling interval.\n\tstd::mutex \t\t\tm_stop_condition_mutex;\n \tstd::condition_variable m_stop_condition;\n#endif\n\n \t\/\/ Is the ImGUI dialog shown? Accessed from UI thread only.\n mutable bool \t\tm_show_settings_dialog { false };\n \/\/ Set to true when ther user closes the dialog by clicking on [X] or [Close] buttons. Accessed from UI thread only.\n mutable bool \t\tm_settings_dialog_closed_by_user { false };\n\npublic:\n\t\/\/ Load the device parameter database from appconfig. To be called on application startup.\n\tvoid load_config(const AppConfig &appconfig);\n\t\/\/ Store the device parameter database back to appconfig. To be called on application closeup.\n\tvoid save_config(AppConfig &appconfig) const;\n\t\/\/ Start the background thread to detect and connect to a HID device (Windows and Linux).\n\t\/\/ Connect to a 3DConnextion driver (OSX).\n\t\/\/ Call load_config() before init().\n void init();\n\t\/\/ Stop the background thread (Windows and Linux).\n\t\/\/ Disconnect from a 3DConnextion driver (OSX).\n\t\/\/ Call save_config() after shutdown().\n void shutdown();\n\n bool connected() const { return m_connected; }\n\n#if __APPLE__\n \/\/ Interfacing with the Objective C code (MouseHandlerMac.mm)\n void connected(std::string device_name);\n void disconnected();\n typedef std::array<double, 6> DataPacketAxis;\n\t\/\/ Unpack a 3DConnexion packet provided by the 3DConnexion driver into m_state. Called by Mouse3DHandlerMac.mm\n bool handle_input(const DataPacketAxis& packet);\n#endif \/\/ __APPLE__\n\n#ifdef WIN32\n \/\/ On Windows, the 3DConnexion driver sends out mouse wheel rotation events to an active application\n \/\/ if the application does not register at the driver. This is a workaround to ignore these superfluous\n \/\/ mouse wheel events.\n bool process_mouse_wheel() { return m_state.process_mouse_wheel(); }\n#endif \/\/ WIN32\n\n \/\/ Apply the received 3DConnexion mouse events to the camera. Called from the UI rendering thread.\n bool apply(Camera& camera);\n\n bool is_settings_dialog_shown() const { return m_show_settings_dialog; }\n void show_settings_dialog(bool show) { m_show_settings_dialog = show && this->connected(); }\n void render_settings_dialog(GLCanvas3D& canvas) const;\n\n#if ! __APPLE__\nprivate:\n bool connect_device();\n void disconnect_device();\n\n \/\/ secondary thread methods\n void run();\n void collect_input();\n\n typedef std::array<unsigned char, 13> DataPacketRaw;\n\n\t\/\/ Unpack raw 3DConnexion HID packet of a wired 3D mouse into m_state. Called by the worker thread.\n static bool handle_input(const DataPacketRaw& packet, const int packet_lenght, const Params ¶ms, State &state_in_out);\n \/\/ The following is called by handle_input() from the worker thread.\n static bool handle_packet(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_wireless_packet(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_packet_translation(const DataPacketRaw& packet, const Params ¶ms, State &state_in_out);\n static bool handle_packet_rotation(const DataPacketRaw& packet, unsigned int first_byte, const Params ¶ms, State &state_in_out);\n static bool handle_packet_button(const DataPacketRaw& packet, unsigned int packet_size, const Params ¶ms, State &state_in_out);\n#endif \/* __APPLE__ *\/\n};\n\n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n\n#endif \/\/ slic3r_Mouse3DController_hpp_\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Potential build problem fix.<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2008 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\/*\n Utility program that encapsulates process creation, monitoring\n and bulletproof process cleanup\n\n Usage:\n safe_process [options to safe_process] -- progname arg1 ... argn\n\n To safeguard mysqld you would invoke safe_process with a few options\n for safe_process itself followed by a double dash to indicate start\n of the command line for the program you really want to start\n\n $> safe_process --output=output.log -- mysqld --datadir=var\/data1 ...\n\n This would redirect output to output.log and then start mysqld,\n once it has done that it will continue to monitor the child as well\n as the parent.\n\n The safe_process then checks the follwing things:\n 1. Child exits, propagate the childs return code to the parent\n by exiting with the same return code as the child.\n\n 2. Parent dies, immediately kill the child and exit, thus the\n parent does not need to properly cleanup any child, it is handled\n automatically.\n\n 3. Signal's recieced by the process will trigger same action as 2)\n\n*\/\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <string.h>\n#include <errno.h>\n\nint verbose= 0;\nint terminated= 0;\npid_t child_pid= -1;\nchar safe_process_name[32]= {0};\n\n\nstatic void message(const char* fmt, ...)\n{\n if (!verbose)\n return;\n va_list args;\n fprintf(stderr, \"%s: \", safe_process_name);\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n fflush(stderr);\n}\n\n\nstatic void die(const char* fmt, ...)\n{\n va_list args;\n fprintf(stderr, \"%s: FATAL ERROR, \", safe_process_name);\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n if (int last_err= errno)\n fprintf(stderr, \"error: %d, %s\\n\", last_err, strerror(last_err));\n exit(1);\n}\n\n\nstatic void kill_child (void)\n{\n int exit_code= 1;\n int status= 0;\n\n message(\"Killing child: %d\", child_pid);\n \/\/ Terminate whole process group\n kill(-child_pid, SIGKILL);\n\n pid_t ret_pid= waitpid(child_pid, &status, 0);\n if (ret_pid == child_pid)\n {\n if (WIFEXITED(status))\n {\n \/\/ Process has exited, collect return status\n exit_code= WEXITSTATUS(status);\n message(\"Child exit: %d\", exit_code);\n \/\/ Exit with exit status of the child\n exit(exit_code);\n }\n\n if (WIFSIGNALED(status))\n message(\"Child killed by signal: %d\", WTERMSIG(status));\n\n exit(exit_code);\n }\n exit(exit_code);\n}\n\n\nstatic void handle_signal (int sig)\n{\n message(\"Got signal %d, child_pid: %d\", sig, child_pid);\n terminated= 1;\n\n \/\/ Ignore further signals\n signal(SIGTERM, SIG_IGN);\n signal(SIGINT, SIG_IGN);\n signal(SIGCHLD, SIG_IGN);\n\n if (child_pid > 0)\n kill_child();\n\n \/\/ Continune execution, allow the child to be started and\n \/\/ finally terminated by monitor loop\n}\n\n\nint main(int argc, char* const argv[] )\n{\n char* const* child_argv= 0;\n pid_t own_pid= getpid();\n pid_t parent_pid= getppid();\n\n \/* Install signal handlers *\/\n signal(SIGTERM, handle_signal);\n signal(SIGINT, handle_signal);\n signal(SIGCHLD, handle_signal);\n\n sprintf(safe_process_name, \"safe_process[%d]\", own_pid);\n\n message(\"Started\");\n\n \/* Parse arguments *\/\n for (int i= 1; i < argc; i++) {\n const char* arg= argv[i];\n if (strcmp(arg, \"--\") == 0 && strlen(arg) == 2) {\n \/* Got the \"--\" delimiter *\/\n if (i >= argc)\n die(\"No real args -> nothing to do\");\n child_argv= &argv[i+1];\n break;\n } else {\n if ( strcmp(arg, \"--verbose\") == 0 )\n verbose++;\n else if ( strncmp(arg, \"--parent-pid\", 10) == 0 )\n {\n \/* Override parent_pid with a value provided by user *\/\n const char* start;\n if ((start= strstr(arg, \"=\")) == NULL)\n die(\"Could not find start of option value in '%s'\", arg);\n start++; \/* Step past = *\/\n if ((parent_pid= atoi(start)) == 0)\n die(\"Invalid value '%s' passed to --parent-id\", start);\n }\n else\n die(\"Unknown option: %s\", arg);\n }\n }\n if (!child_argv || *child_argv == 0)\n die(\"nothing to do\");\n\n message(\"parent_pid: %d\", parent_pid);\n if (parent_pid == own_pid)\n die(\"parent_pid is equal to own pid!\");\n\n char buf;\n int pfd[2];\n if (pipe(pfd) == -1)\n die(\"Failed to create pipe\");\n\n \/* Create the child process *\/\n while((child_pid= fork()) == -1)\n {\n message(\"fork failed\");\n sleep(1);\n }\n\n if (child_pid == 0)\n {\n close(pfd[0]); \/\/ Close unused read end\n\n \/\/ Use default signal handlers in child\n signal(SIGTERM, SIG_DFL);\n signal(SIGINT, SIG_DFL);\n signal(SIGCHLD, SIG_DFL);\n\n \/\/ Make this process it's own process group to be able to kill\n \/\/ it and any childs(that hasn't changed group themself)\n setpgid(0, 0);\n\n \/\/ Signal that child is ready\n buf= 37;\n write(pfd[1], &buf, 1);\n \/\/ Close write end\n close(pfd[1]);\n\n if (execvp(child_argv[0], child_argv) < 0)\n die(\"Failed to exec child\");\n }\n\n close(pfd[1]); \/\/ Close unused write end\n\n \/\/ Wait for child to signal it's ready\n read(pfd[0], &buf, 1);\n if(buf != 37)\n die(\"Didn't get 37 from pipe\");\n close(pfd[0]); \/\/ Close read end\n\n \/* Monitor loop *\/\n message(\"Started child %d, terminated: %d\", child_pid, terminated);\n\n while(!terminated)\n {\n \/\/ Check if parent is still alive\n if (kill(parent_pid, 0) != 0){\n message(\"Parent is not alive anymore\");\n break;\n }\n\n \/\/ Check if child has exited, normally this wil be\n \/\/ detected immediately with SIGCHLD handler\n int status= 0;\n pid_t ret_pid= waitpid(child_pid, &status, WNOHANG);\n if (ret_pid == child_pid)\n {\n int ret_code= 2;\n if (WIFEXITED(status))\n {\n \/\/ Process has exited, collect return status\n int ret_code= WEXITSTATUS(status);\n message(\"Child exit: %d\", ret_code);\n \/\/ Exit with exit status of the child\n exit(ret_code);\n }\n\n if (WIFSIGNALED(status))\n message(\"Child killed by signal: %d\", WTERMSIG(status));\n\n exit(ret_code);\n }\n sleep(1);\n }\n kill_child();\n\n exit(1);\n}\n\n<commit_msg>Don't ignore SIGCHLD since that affects waitpid on some platforms Fix spelling error Move exit_code into local scope<commit_after>\/* Copyright (C) 2008 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\/*\n Utility program that encapsulates process creation, monitoring\n and bulletproof process cleanup\n\n Usage:\n safe_process [options to safe_process] -- progname arg1 ... argn\n\n To safeguard mysqld you would invoke safe_process with a few options\n for safe_process itself followed by a double dash to indicate start\n of the command line for the program you really want to start\n\n $> safe_process --output=output.log -- mysqld --datadir=var\/data1 ...\n\n This would redirect output to output.log and then start mysqld,\n once it has done that it will continue to monitor the child as well\n as the parent.\n\n The safe_process then checks the follwing things:\n 1. Child exits, propagate the childs return code to the parent\n by exiting with the same return code as the child.\n\n 2. Parent dies, immediately kill the child and exit, thus the\n parent does not need to properly cleanup any child, it is handled\n automatically.\n\n 3. Signal's recieced by the process will trigger same action as 2)\n\n*\/\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <string.h>\n#include <errno.h>\n\nint verbose= 0;\nint terminated= 0;\npid_t child_pid= -1;\nchar safe_process_name[32]= {0};\n\n\nstatic void message(const char* fmt, ...)\n{\n if (!verbose)\n return;\n va_list args;\n fprintf(stderr, \"%s: \", safe_process_name);\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n fflush(stderr);\n}\n\n\nstatic void die(const char* fmt, ...)\n{\n va_list args;\n fprintf(stderr, \"%s: FATAL ERROR, \", safe_process_name);\n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n if (int last_err= errno)\n fprintf(stderr, \"error: %d, %s\\n\", last_err, strerror(last_err));\n exit(1);\n}\n\n\nstatic void kill_child (void)\n{\n int status= 0;\n\n message(\"Killing child: %d\", child_pid);\n \/\/ Terminate whole process group\n kill(-child_pid, SIGKILL);\n\n pid_t ret_pid= waitpid(child_pid, &status, 0);\n if (ret_pid == child_pid)\n {\n int exit_code= 1;\n if (WIFEXITED(status))\n {\n \/\/ Process has exited, collect return status\n exit_code= WEXITSTATUS(status);\n message(\"Child exit: %d\", exit_code);\n \/\/ Exit with exit status of the child\n exit(exit_code);\n }\n\n if (WIFSIGNALED(status))\n message(\"Child killed by signal: %d\", WTERMSIG(status));\n\n exit(exit_code);\n }\n exit(1);\n}\n\n\nstatic void handle_signal (int sig)\n{\n message(\"Got signal %d, child_pid: %d\", sig, child_pid);\n terminated= 1;\n\n if (child_pid > 0)\n kill_child();\n\n \/\/ Ignore further signals\n signal(SIGTERM, SIG_IGN);\n signal(SIGINT, SIG_IGN);\n\n \/\/ Continune execution, allow the child to be started and\n \/\/ finally terminated by monitor loop\n}\n\n\nint main(int argc, char* const argv[] )\n{\n char* const* child_argv= 0;\n pid_t own_pid= getpid();\n pid_t parent_pid= getppid();\n\n \/* Install signal handlers *\/\n signal(SIGTERM, handle_signal);\n signal(SIGINT, handle_signal);\n signal(SIGCHLD, handle_signal);\n\n sprintf(safe_process_name, \"safe_process[%d]\", own_pid);\n\n message(\"Started\");\n\n \/* Parse arguments *\/\n for (int i= 1; i < argc; i++) {\n const char* arg= argv[i];\n if (strcmp(arg, \"--\") == 0 && strlen(arg) == 2) {\n \/* Got the \"--\" delimiter *\/\n if (i >= argc)\n die(\"No real args -> nothing to do\");\n child_argv= &argv[i+1];\n break;\n } else {\n if ( strcmp(arg, \"--verbose\") == 0 )\n verbose++;\n else if ( strncmp(arg, \"--parent-pid\", 10) == 0 )\n {\n \/* Override parent_pid with a value provided by user *\/\n const char* start;\n if ((start= strstr(arg, \"=\")) == NULL)\n die(\"Could not find start of option value in '%s'\", arg);\n start++; \/* Step past = *\/\n if ((parent_pid= atoi(start)) == 0)\n die(\"Invalid value '%s' passed to --parent-id\", start);\n }\n else\n die(\"Unknown option: %s\", arg);\n }\n }\n if (!child_argv || *child_argv == 0)\n die(\"nothing to do\");\n\n message(\"parent_pid: %d\", parent_pid);\n if (parent_pid == own_pid)\n die(\"parent_pid is equal to own pid!\");\n\n char buf;\n int pfd[2];\n if (pipe(pfd) == -1)\n die(\"Failed to create pipe\");\n\n \/* Create the child process *\/\n while((child_pid= fork()) == -1)\n {\n message(\"fork failed\");\n sleep(1);\n }\n\n if (child_pid == 0)\n {\n close(pfd[0]); \/\/ Close unused read end\n\n \/\/ Use default signal handlers in child\n signal(SIGTERM, SIG_DFL);\n signal(SIGINT, SIG_DFL);\n signal(SIGCHLD, SIG_DFL);\n\n \/\/ Make this process it's own process group to be able to kill\n \/\/ it and any childs(that hasn't changed group themself)\n setpgid(0, 0);\n\n \/\/ Signal that child is ready\n buf= 37;\n write(pfd[1], &buf, 1);\n \/\/ Close write end\n close(pfd[1]);\n\n if (execvp(child_argv[0], child_argv) < 0)\n die(\"Failed to exec child\");\n }\n\n close(pfd[1]); \/\/ Close unused write end\n\n \/\/ Wait for child to signal it's ready\n read(pfd[0], &buf, 1);\n if(buf != 37)\n die(\"Didn't get 37 from pipe\");\n close(pfd[0]); \/\/ Close read end\n\n \/* Monitor loop *\/\n message(\"Started child %d, terminated: %d\", child_pid, terminated);\n\n while(!terminated)\n {\n \/\/ Check if parent is still alive\n if (kill(parent_pid, 0) != 0){\n message(\"Parent is not alive anymore\");\n break;\n }\n\n \/\/ Check if child has exited, normally this will be\n \/\/ detected immediately with SIGCHLD handler\n int status= 0;\n pid_t ret_pid= waitpid(child_pid, &status, WNOHANG);\n if (ret_pid == child_pid)\n {\n int ret_code= 2;\n if (WIFEXITED(status))\n {\n \/\/ Process has exited, collect return status\n int ret_code= WEXITSTATUS(status);\n message(\"Child exit: %d\", ret_code);\n \/\/ Exit with exit status of the child\n exit(ret_code);\n }\n\n if (WIFSIGNALED(status))\n message(\"Child killed by signal: %d\", WTERMSIG(status));\n\n exit(ret_code);\n }\n sleep(1);\n }\n kill_child();\n\n exit(1);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n filename: CEGUIOpenGLGeometryBuffer.cpp\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include <GL\/glew.h>\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/quaternion.hpp\"\n#include \"glm\/gtc\/type_ptr.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RenderEffect.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/StateChangeWrapper.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :\n OpenGLGeometryBufferBase(owner),\n d_shader(owner.getShaderStandard()),\n d_shaderPosLoc(owner.getShaderStandardPositionLoc()),\n d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),\n d_shaderColourLoc(owner.getShaderStandardColourLoc()),\n d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),\n d_glStateChanger(owner.getOpenGLStateChanger()),\n d_bufferSize(0)\n{\n initialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()\n{\n deinitialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::draw() const\n{\n CEGUI::Rectf viewPort = d_owner->getActiveViewPort();\n\n d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),\n static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),\n static_cast<GLint>(d_clipRect.getWidth()),\n static_cast<GLint>(d_clipRect.getHeight()));\n\n \/\/ apply the transformations we need to use.\n if (!d_matrixValid)\n updateMatrix();\n\n \/\/ Send ModelViewProjection matrix to shader\n glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;\n glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));\n\n \/\/ activate desired blending mode\n d_owner->setupRenderingBlendMode(d_blendMode);\n\n \/\/ Bind our vao\n d_glStateChanger->bindVertexArray(d_verticesVAO);\n\n const int pass_count = d_effect ? d_effect->getPassCount() : 1;\n size_t pos = 0;\n for (int pass = 0; pass < pass_count; ++pass)\n {\n \/\/ set up RenderEffect\n if (d_effect)\n d_effect->performPreRenderFunctions(pass);\n\n \/\/ draw the batches\n \n BatchList::const_iterator i = d_batches.begin();\n for ( ; i != d_batches.end(); ++i)\n {\n const BatchInfo& currentBatch = *i;\n\n if (currentBatch.clip)\n glEnable(GL_SCISSOR_TEST);\n else\n glDisable(GL_SCISSOR_TEST);\n\n glBindTexture(GL_TEXTURE_2D, currentBatch.texture);\n\n \/\/ draw the geometry\n const unsigned int numVertices = currentBatch.vertexCount;\n glDrawArrays(GL_TRIANGLES, pos, numVertices);\n\n pos += numVertices;\n }\n }\n\n \/\/ clean up RenderEffect\n if (d_effect)\n d_effect->performPostRenderFunctions();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,\n uint vertex_count)\n{\n OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::reset()\n{\n OpenGLGeometryBufferBase::reset();\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::initialiseOpenGLBuffers()\n{\n glGenVertexArrays(1, &d_verticesVAO);\n glBindVertexArray(d_verticesVAO);\n\n \/\/ Generate and bind position vbo\n glGenBuffers(1, &d_verticesVBO);\n glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);\n\n d_shader->bind();\n \n GLsizei stride = 9 * sizeof(GL_FLOAT);\n\n glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);\n glEnableVertexAttribArray(d_shaderTexCoordLoc);\n\n glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));\n glEnableVertexAttribArray(d_shaderColourLoc);\n\n glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));\n glEnableVertexAttribArray(d_shaderPosLoc);\n\n d_shader->unbind();\n\n \/\/ Unbind Vertex Attribute Array (VAO)\n glBindVertexArray(0);\n\n \/\/ Unbind array and element array buffers\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()\n{\n glDeleteVertexArrays(1, &d_verticesVAO);\n glDeleteBuffers(1, &d_verticesVBO);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::updateOpenGLBuffers()\n{\n bool needNewBuffer = false;\n unsigned int vertexCount = d_vertices.size();\n\n if(d_bufferSize < vertexCount)\n {\n needNewBuffer = true;\n d_bufferSize = vertexCount;\n }\n\n d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n GLsizei dataSize = d_bufferSize * sizeof(GLVertex);\n\n if(needNewBuffer)\n {\n glBufferData(GL_ARRAY_BUFFER, dataSize, d_vertices.data(), GL_DYNAMIC_DRAW);\n }\n else\n {\n glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, d_vertices.data());\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\n<commit_msg>FIX: Don't use std::vector::data since it only exists for C++11<commit_after>\/***********************************************************************\n filename: CEGUIOpenGLGeometryBuffer.cpp\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include <GL\/glew.h>\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/quaternion.hpp\"\n#include \"glm\/gtc\/type_ptr.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RenderEffect.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/StateChangeWrapper.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :\n OpenGLGeometryBufferBase(owner),\n d_shader(owner.getShaderStandard()),\n d_shaderPosLoc(owner.getShaderStandardPositionLoc()),\n d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),\n d_shaderColourLoc(owner.getShaderStandardColourLoc()),\n d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),\n d_glStateChanger(owner.getOpenGLStateChanger()),\n d_bufferSize(0)\n{\n initialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()\n{\n deinitialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::draw() const\n{\n CEGUI::Rectf viewPort = d_owner->getActiveViewPort();\n\n d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),\n static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),\n static_cast<GLint>(d_clipRect.getWidth()),\n static_cast<GLint>(d_clipRect.getHeight()));\n\n \/\/ apply the transformations we need to use.\n if (!d_matrixValid)\n updateMatrix();\n\n \/\/ Send ModelViewProjection matrix to shader\n glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;\n glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));\n\n \/\/ activate desired blending mode\n d_owner->setupRenderingBlendMode(d_blendMode);\n\n \/\/ Bind our vao\n d_glStateChanger->bindVertexArray(d_verticesVAO);\n\n const int pass_count = d_effect ? d_effect->getPassCount() : 1;\n size_t pos = 0;\n for (int pass = 0; pass < pass_count; ++pass)\n {\n \/\/ set up RenderEffect\n if (d_effect)\n d_effect->performPreRenderFunctions(pass);\n\n \/\/ draw the batches\n \n BatchList::const_iterator i = d_batches.begin();\n for ( ; i != d_batches.end(); ++i)\n {\n const BatchInfo& currentBatch = *i;\n\n if (currentBatch.clip)\n glEnable(GL_SCISSOR_TEST);\n else\n glDisable(GL_SCISSOR_TEST);\n\n glBindTexture(GL_TEXTURE_2D, currentBatch.texture);\n\n \/\/ draw the geometry\n const unsigned int numVertices = currentBatch.vertexCount;\n glDrawArrays(GL_TRIANGLES, pos, numVertices);\n\n pos += numVertices;\n }\n }\n\n \/\/ clean up RenderEffect\n if (d_effect)\n d_effect->performPostRenderFunctions();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,\n uint vertex_count)\n{\n OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::reset()\n{\n OpenGLGeometryBufferBase::reset();\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::initialiseOpenGLBuffers()\n{\n glGenVertexArrays(1, &d_verticesVAO);\n glBindVertexArray(d_verticesVAO);\n\n \/\/ Generate and bind position vbo\n glGenBuffers(1, &d_verticesVBO);\n glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);\n\n d_shader->bind();\n \n GLsizei stride = 9 * sizeof(GL_FLOAT);\n\n glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);\n glEnableVertexAttribArray(d_shaderTexCoordLoc);\n\n glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));\n glEnableVertexAttribArray(d_shaderColourLoc);\n\n glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));\n glEnableVertexAttribArray(d_shaderPosLoc);\n\n d_shader->unbind();\n\n \/\/ Unbind Vertex Attribute Array (VAO)\n glBindVertexArray(0);\n\n \/\/ Unbind array and element array buffers\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()\n{\n glDeleteVertexArrays(1, &d_verticesVAO);\n glDeleteBuffers(1, &d_verticesVBO);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::updateOpenGLBuffers()\n{\n bool needNewBuffer = false;\n unsigned int vertexCount = d_vertices.size();\n\n if(d_bufferSize < vertexCount)\n {\n needNewBuffer = true;\n d_bufferSize = vertexCount;\n }\n\n d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n GLsizei dataSize = d_bufferSize * sizeof(GLVertex);\n\n if(needNewBuffer)\n {\n glBufferData(GL_ARRAY_BUFFER, dataSize, &d_vertices.front(), GL_DYNAMIC_DRAW);\n }\n else\n {\n glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, &d_vertices.front());\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/GL.h\"\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/quaternion.hpp\"\n#include \"glm\/gtc\/type_ptr.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RenderEffect.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/StateChangeWrapper.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :\n OpenGLGeometryBufferBase(owner),\n d_shader(owner.getShaderStandard()),\n d_shaderPosLoc(owner.getShaderStandardPositionLoc()),\n d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),\n d_shaderColourLoc(owner.getShaderStandardColourLoc()),\n d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),\n d_glStateChanger(owner.getOpenGLStateChanger()),\n d_bufferSize(0)\n{\n initialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()\n{\n deinitialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::draw() const\n{\n CEGUI::Rectf viewPort = d_owner->getActiveViewPort();\n\n d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),\n static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),\n static_cast<GLint>(d_clipRect.getWidth()),\n static_cast<GLint>(d_clipRect.getHeight()));\n\n \/\/ apply the transformations we need to use.\n if (!d_matrixValid)\n updateMatrix();\n\n \/\/ Send ModelViewProjection matrix to shader\n glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;\n glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));\n\n \/\/ activate desired blending mode\n d_owner->setupRenderingBlendMode(d_blendMode);\n\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n \/\/ Bind our vao\n d_glStateChanger->bindVertexArray(d_verticesVAO);\n }\n else\n {\n \/\/ We need to emulate a VAO.\n configureVertexArray();\n }\n\n const int pass_count = d_effect ? d_effect->getPassCount() : 1;\n size_t pos = 0;\n for (int pass = 0; pass < pass_count; ++pass)\n {\n \/\/ set up RenderEffect\n if (d_effect)\n d_effect->performPreRenderFunctions(pass);\n\n \/\/ draw the batches\n \n BatchList::const_iterator i = d_batches.begin();\n for ( ; i != d_batches.end(); ++i)\n {\n const BatchInfo& currentBatch = *i;\n\n if (currentBatch.clip)\n glEnable(GL_SCISSOR_TEST);\n else\n glDisable(GL_SCISSOR_TEST);\n\n glBindTexture(GL_TEXTURE_2D, currentBatch.texture);\n\n \/\/ draw the geometry\n const unsigned int numVertices = currentBatch.vertexCount;\n glDrawArrays(GL_TRIANGLES, pos, numVertices);\n\n pos += numVertices;\n }\n }\n\n \/\/ clean up RenderEffect\n if (d_effect)\n d_effect->performPostRenderFunctions();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,\n uint vertex_count)\n{\n OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::reset()\n{\n OpenGLGeometryBufferBase::reset();\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::initialiseOpenGLBuffers()\n{\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n glGenVertexArrays(1, &d_verticesVAO);\n glBindVertexArray(d_verticesVAO);\n }\n\n \/\/ Generate position vbo\n glGenBuffers(1, &d_verticesVBO);\n\n d_shader->bind();\n configureVertexArray();\n glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);\n d_shader->unbind();\n\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n \/\/ Unbind Vertex Attribute Array (VAO)\n glBindVertexArray(0);\n }\n\n \/\/ Unbind array and element array buffers\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::configureVertexArray() const\n{\n glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n GLsizei stride = 9 * sizeof(GLfloat);\n\n glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);\n glEnableVertexAttribArray(d_shaderTexCoordLoc);\n\n glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GLfloat)));\n glEnableVertexAttribArray(d_shaderColourLoc);\n\n glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GLfloat)));\n glEnableVertexAttribArray(d_shaderPosLoc);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()\n{\n if (OpenGLInfo::getSingleton().isVaoSupported())\n glDeleteVertexArrays(1, &d_verticesVAO);\n glDeleteBuffers(1, &d_verticesVBO);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::updateOpenGLBuffers()\n{\n bool needNewBuffer = false;\n unsigned int vertexCount = d_vertices.size();\n\n if(d_bufferSize < vertexCount)\n {\n needNewBuffer = true;\n d_bufferSize = vertexCount;\n }\n\n d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n GLsizei dataSize = vertexCount * sizeof(GLVertex);\n\n GLVertex* data;\n if(d_vertices.empty())\n data = 0;\n else\n data = &d_vertices[0];\n\n if(needNewBuffer)\n {\n glBufferData(GL_ARRAY_BUFFER, dataSize, data, GL_DYNAMIC_DRAW);\n }\n else\n {\n glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, data);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\n<commit_msg>MOD: Adding vbo buffer binding before initialisation thereof<commit_after>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/GL.h\"\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/quaternion.hpp\"\n#include \"glm\/gtc\/type_ptr.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RenderEffect.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Texture.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/StateChangeWrapper.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#define BUFFER_OFFSET(i) ((char *)NULL + (i))\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :\n OpenGLGeometryBufferBase(owner),\n d_shader(owner.getShaderStandard()),\n d_shaderPosLoc(owner.getShaderStandardPositionLoc()),\n d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),\n d_shaderColourLoc(owner.getShaderStandardColourLoc()),\n d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),\n d_glStateChanger(owner.getOpenGLStateChanger()),\n d_bufferSize(0)\n{\n initialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()\n{\n deinitialiseOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::draw() const\n{\n CEGUI::Rectf viewPort = d_owner->getActiveViewPort();\n\n d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),\n static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),\n static_cast<GLint>(d_clipRect.getWidth()),\n static_cast<GLint>(d_clipRect.getHeight()));\n\n \/\/ apply the transformations we need to use.\n if (!d_matrixValid)\n updateMatrix();\n\n \/\/ Send ModelViewProjection matrix to shader\n glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;\n glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));\n\n \/\/ activate desired blending mode\n d_owner->setupRenderingBlendMode(d_blendMode);\n\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n \/\/ Bind our vao\n d_glStateChanger->bindVertexArray(d_verticesVAO);\n }\n else\n {\n \/\/ We need to emulate a VAO.\n configureVertexArray();\n }\n\n const int pass_count = d_effect ? d_effect->getPassCount() : 1;\n size_t pos = 0;\n for (int pass = 0; pass < pass_count; ++pass)\n {\n \/\/ set up RenderEffect\n if (d_effect)\n d_effect->performPreRenderFunctions(pass);\n\n \/\/ draw the batches\n \n BatchList::const_iterator i = d_batches.begin();\n for ( ; i != d_batches.end(); ++i)\n {\n const BatchInfo& currentBatch = *i;\n\n if (currentBatch.clip)\n glEnable(GL_SCISSOR_TEST);\n else\n glDisable(GL_SCISSOR_TEST);\n\n glBindTexture(GL_TEXTURE_2D, currentBatch.texture);\n\n \/\/ draw the geometry\n const unsigned int numVertices = currentBatch.vertexCount;\n glDrawArrays(GL_TRIANGLES, pos, numVertices);\n\n pos += numVertices;\n }\n }\n\n \/\/ clean up RenderEffect\n if (d_effect)\n d_effect->performPostRenderFunctions();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,\n uint vertex_count)\n{\n OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::reset()\n{\n OpenGLGeometryBufferBase::reset();\n updateOpenGLBuffers();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::initialiseOpenGLBuffers()\n{\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n glGenVertexArrays(1, &d_verticesVAO);\n glBindVertexArray(d_verticesVAO);\n }\n\n \/\/ Generate position vbo\n glGenBuffers(1, &d_verticesVBO);\n glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n d_shader->bind();\n configureVertexArray();\n glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);\n d_shader->unbind();\n\n if (OpenGLInfo::getSingleton().isVaoSupported())\n {\n \/\/ Unbind Vertex Attribute Array (VAO)\n glBindVertexArray(0);\n }\n\n \/\/ Unbind array and element array buffers\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::configureVertexArray() const\n{\n glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n GLsizei stride = 9 * sizeof(GLfloat);\n\n glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);\n glEnableVertexAttribArray(d_shaderTexCoordLoc);\n\n glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GLfloat)));\n glEnableVertexAttribArray(d_shaderColourLoc);\n\n glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GLfloat)));\n glEnableVertexAttribArray(d_shaderPosLoc);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()\n{\n if (OpenGLInfo::getSingleton().isVaoSupported())\n glDeleteVertexArrays(1, &d_verticesVAO);\n glDeleteBuffers(1, &d_verticesVBO);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3GeometryBuffer::updateOpenGLBuffers()\n{\n bool needNewBuffer = false;\n unsigned int vertexCount = d_vertices.size();\n\n if(d_bufferSize < vertexCount)\n {\n needNewBuffer = true;\n d_bufferSize = vertexCount;\n }\n\n d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);\n\n GLsizei dataSize = vertexCount * sizeof(GLVertex);\n\n GLVertex* data;\n if(d_vertices.empty())\n data = 0;\n else\n data = &d_vertices[0];\n\n if(needNewBuffer)\n {\n glBufferData(GL_ARRAY_BUFFER, dataSize, data, GL_DYNAMIC_DRAW);\n }\n else\n {\n glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, data);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n\n<|endoftext|>"} {"text":"<commit_before>#include \"rule_executor.hpp\"\n\nRuleExecutor::RuleExecutor(const char * const rawRule) {\n\tparseRule(rawRule);\n}\n\nbool RuleExecutor::isError() const noexcept {\n\treturn m_error;\n}\n\nstd::string RuleExecutor::executeAll() {\n\tif (m_error) return \"\";\n\tstd::stringstream ss;\n\n\tfor (auto&& it = m_rules.begin(); it != m_rules.end(); it++) {\n\t\tuint16_t length = (*it).second.get()->getQuantity();\n\n\t\tfor (uint16_t i = 0; i < length; ++i) {\n\t\t\tss << std::noskipws << (*it).first.get()->getChar();\n\t\t}\n\t}\n\n\tss << '\\0';\n\treturn ss.str();\n}\n\nvoid RuleExecutor::parseRule(const char * const rawRule) {\n\tconst char *it = rawRule;\n\tbool isExclusion = false;\n\n\tfor (; *it != '\\0' && !m_error; it++) {\n\t\tExecutionPair pair;\n\t\tif (*it == '\\\\') {\n\t\t\tit++;\n\t\t\tif (isSlashRule(*it)) {\n\t\t\t\tpair.first = slashToRange(*it, isExclusion);\n\t\t\t} else if (*it == '\\0') {\n\t\t\t\tpair.first = std::make_shared<RangeRule>((it - 1), 2, isExclusion);\n\t\t\t} else {\n\t\t\t\tpair.first = std::make_shared<RangeRule>(it, 2, isExclusion);\n\t\t\t}\n\t\t\tpair.second = CONST_ONE;\n\t\t\tisExclusion = false;\n\t\t\tm_rules.push_back(pair);\n\t\t} else if (*it == '^') {\n\t\t\tisExclusion = true;\n\t\t} else if (*it == '[') {\n\t\t\tit++;\n\t\t\tm_error = parseRange(&it, pair, isExclusion);\n\t\t\tif (m_error) break;\n\t\t\tm_rules.push_back(pair);\n\t\t\tisExclusion = false;\n\t\t} else if (*it == '{') {\n\t\t\tit++;\n\t\t\tuint16_t first = 0, last = 0;\n\t\t\tm_error = parseQuantity(&it, first, last);\n\t\t\tif (m_error) break;\n\t\t\tm_rules.back().second = std::make_shared<QuantityRule>(first, last);\n\t\t} else {\n\t\t\tpair.first = std::make_shared<RangeRule>(it, 2, isExclusion);\n\t\t\tpair.second = CONST_ONE;\n\t\t\tm_rules.push_back(pair);\n\t\t\tisExclusion = false;\n\t\t}\n\t}\n}\n\nbool RuleExecutor::parseRange(const char **it, ExecutionPair& pair, const bool isWholeExclusion) const {\n\tif (**it == '\\0' || **it == ']') {\n\t\treturn true;\n\t}\n\tbool isExclusion = false || isWholeExclusion;\n\tif (**it == '^') {\n\t\t(*it)++;\n\t\tisExclusion = true;\n\t}\n\n\tstd::stringstream ss;\n\n\twhile (**it != ']' && **it != '\\0') {\n\t\tss << **it;\n\t\t(*it)++;\n\t}\n\tss << '\\0';\n\t\n\tpair.first = std::make_shared<RangeRule>(\n\t\t\tss.str().c_str(),\n\t\t\tstatic_cast<uint16_t>(ss.str().length()),\n\t\t\tisExclusion\n\t\t);\n\n\tpair.second = CONST_ONE;\n\n\treturn false;\n}\n\nbool RuleExecutor::parseQuantity(const char **it, uint16_t& first, uint16_t& last) const {\n\tif (m_rules.size() <= 0) {\n\t\treturn true;\n\t}\n\n\tstd::stringstream ss;\n\n\tif (**it == '}' || **it == ',' || **it == '\\0') {\n\t\treturn true;\n\t}\n\n\twhile (**it != '}' && **it != ',' && **it != '\\0') {\n\t\tss << **it;\n\t\t(*it)++;\n\t}\n\tss << '\\0';\n\n\tint value = std::stoi(ss.str());\n\n\tfirst = static_cast<uint16_t>(value);\n\tlast = first;\n\t\n\tss.str(\"\");\n\tif (**it == ',') {\n\t\t(*it)++;\n\n\t\twhile (**it != '}' && **it != '\\0') {\n\t\t\tss << **it;\n\t\t\t(*it)++;\n\t\t}\n\t\t\n\t\tss << '\\0';\n\t\tvalue = std::stoi(ss.str());\n\t\tlast = static_cast<uint16_t>(value);\n\t}\n\n\treturn false;\n}\n\nbool RuleExecutor::isSlashRule(const char c) const noexcept {\n\tswitch (c) {\n\t\tcase 'd': return true;\n\t\tcase 'D': return true;\n\t\tcase 'w': return true;\n\t\tcase 'W': return true;\n\t\tcase 's': return true;\n\t\tcase 'S': return true;\n\t\tcase '.': return true;\n\t\tdefault: return false;\n\t}\n}\n\nstd::shared_ptr<RangeRule> RuleExecutor::slashToRange(const char c, const bool isExclusion) const noexcept {\n\tswitch (c) {\n\t\tcase 'd': return isExclusion ? RULE_DIGIT_EX : RULE_DIGIT;\n\t\tcase 'D': return isExclusion ? RULE_DIGIT : RULE_DIGIT_EX;\n\t\tcase 'w': return isExclusion ? RULE_WORD_EX : RULE_WORD;\n\t\tcase 'W': return isExclusion ? RULE_WORD : RULE_WORD_EX;\n\t\tcase 's': return isExclusion ? RULE_SPACE_EX : RULE_SPACE;\n\t\tcase 'S': return isExclusion ? RULE_SPACE : RULE_SPACE_EX;\n\t\tcase '.': return RULE_DOT;\n\t\tdefault: return RULE_SPACE_EX;\n\t}\n}\n<commit_msg>Added support for wildcard. See issue #1.<commit_after>#include \"rule_executor.hpp\"\n\nRuleExecutor::RuleExecutor(const char * const rawRule) {\n\tparseRule(rawRule);\n}\n\nbool RuleExecutor::isError() const noexcept {\n\treturn m_error;\n}\n\nstd::string RuleExecutor::executeAll() {\n\tif (m_error) return \"\";\n\tstd::stringstream ss;\n\n\tfor (auto&& it = m_rules.begin(); it != m_rules.end(); it++) {\n\t\tuint16_t length = (*it).second.get()->getQuantity();\n\n\t\tfor (uint16_t i = 0; i < length; ++i) {\n\t\t\tss << std::noskipws << (*it).first.get()->getChar();\n\t\t}\n\t}\n\n\tss << '\\0';\n\treturn ss.str();\n}\n\nvoid RuleExecutor::parseRule(const char * const rawRule) {\n\tconst char *it = rawRule;\n\tbool isExclusion = false;\n\n\tfor (; *it != '\\0' && !m_error; it++) {\n\t\tExecutionPair pair;\n\t\tif (*it == '\\\\') {\n\t\t\tit++;\n\t\t\tif (isSlashRule(*it)) {\n\t\t\t\tpair.first = slashToRange(*it, isExclusion);\n\t\t\t} else if (*it == '\\0') {\n\t\t\t\tpair.first = std::make_shared<RangeRule>((it - 1), 2, isExclusion);\n\t\t\t} else {\n\t\t\t\tpair.first = std::make_shared<RangeRule>(it, 2, isExclusion);\n\t\t\t}\n\t\t\tpair.second = CONST_ONE;\n\t\t\tisExclusion = false;\n\t\t\tm_rules.push_back(pair);\n\t\t} else if (*it == '^') {\n\t\t\tisExclusion = true;\n\t\t} else if (*it == '[') {\n\t\t\tit++;\n\t\t\tm_error = parseRange(&it, pair, isExclusion);\n\t\t\tif (m_error) break;\n\t\t\tm_rules.push_back(pair);\n\t\t\tisExclusion = false;\n\t\t} else if (*it == '{') {\n\t\t\tit++;\n\t\t\tuint16_t first = 0, last = 0;\n\t\t\tm_error = parseQuantity(&it, first, last);\n\t\t\tif (m_error) break;\n\t\t\tm_rules.back().second = std::make_shared<QuantityRule>(first, last);\n\t\t} else if (*it == '.') {\n\t\t\t\/\/ The dot cannot be excluded as per \\. is already defined.\n\t\t\tpair.first = std::make_shared<RangeRule>(true);\n\t\t\tpair.second = CONST_ONE;\n\t\t\tm_rules.push_back(pair);\n\t\t} else {\n\t\t\tpair.first = std::make_shared<RangeRule>(it, 2, isExclusion);\n\t\t\tpair.second = CONST_ONE;\n\t\t\tm_rules.push_back(pair);\n\t\t\tisExclusion = false;\n\t\t}\n\t}\n}\n\nbool RuleExecutor::parseRange(const char **it, ExecutionPair& pair, const bool isWholeExclusion) const {\n\tif (**it == '\\0' || **it == ']') {\n\t\treturn true;\n\t}\n\tbool isExclusion = false || isWholeExclusion;\n\tif (**it == '^') {\n\t\t(*it)++;\n\t\tisExclusion = true;\n\t}\n\n\tstd::stringstream ss;\n\n\twhile (**it != ']' && **it != '\\0') {\n\t\tss << **it;\n\t\t(*it)++;\n\t}\n\tss << '\\0';\n\t\n\tpair.first = std::make_shared<RangeRule>(\n\t\t\tss.str().c_str(),\n\t\t\tstatic_cast<uint16_t>(ss.str().length()),\n\t\t\tisExclusion\n\t\t);\n\n\tpair.second = CONST_ONE;\n\n\treturn false;\n}\n\nbool RuleExecutor::parseQuantity(const char **it, uint16_t& first, uint16_t& last) const {\n\tif (m_rules.size() <= 0) {\n\t\treturn true;\n\t}\n\n\tstd::stringstream ss;\n\n\tif (**it == '}' || **it == ',' || **it == '\\0') {\n\t\treturn true;\n\t}\n\n\twhile (**it != '}' && **it != ',' && **it != '\\0') {\n\t\tss << **it;\n\t\t(*it)++;\n\t}\n\tss << '\\0';\n\n\tint value = std::stoi(ss.str());\n\n\tfirst = static_cast<uint16_t>(value);\n\tlast = first;\n\t\n\tss.str(\"\");\n\tif (**it == ',') {\n\t\t(*it)++;\n\n\t\twhile (**it != '}' && **it != '\\0') {\n\t\t\tss << **it;\n\t\t\t(*it)++;\n\t\t}\n\t\t\n\t\tss << '\\0';\n\t\tvalue = std::stoi(ss.str());\n\t\tlast = static_cast<uint16_t>(value);\n\t}\n\n\treturn false;\n}\n\nbool RuleExecutor::isSlashRule(const char c) const noexcept {\n\tswitch (c) {\n\t\tcase 'd': return true;\n\t\tcase 'D': return true;\n\t\tcase 'w': return true;\n\t\tcase 'W': return true;\n\t\tcase 's': return true;\n\t\tcase 'S': return true;\n\t\tcase '.': return true;\n\t\tdefault: return false;\n\t}\n}\n\nstd::shared_ptr<RangeRule> RuleExecutor::slashToRange(const char c, const bool isExclusion) const noexcept {\n\tswitch (c) {\n\t\tcase 'd': return isExclusion ? RULE_DIGIT_EX : RULE_DIGIT;\n\t\tcase 'D': return isExclusion ? RULE_DIGIT : RULE_DIGIT_EX;\n\t\tcase 'w': return isExclusion ? RULE_WORD_EX : RULE_WORD;\n\t\tcase 'W': return isExclusion ? RULE_WORD : RULE_WORD_EX;\n\t\tcase 's': return isExclusion ? RULE_SPACE_EX : RULE_SPACE;\n\t\tcase 'S': return isExclusion ? RULE_SPACE : RULE_SPACE_EX;\n\t\tcase '.': return RULE_DOT;\n\t\tdefault: return RULE_SPACE_EX;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This utility program exists to process the False Start blacklist file into\n\/\/ a static hash table so that it can be efficiently queried by Chrome.\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <set>\n#include <string>\n#include <vector>\n\n#include \"base\/basictypes.h\"\n#include \"net\/base\/ssl_false_start_blacklist.h\"\n\nusing net::SSLFalseStartBlacklist;\n\nstatic const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets;\n\nstatic bool verbose = false;\n\nstatic int\nusage(const char* argv0) {\n fprintf(stderr, \"Usage: %s <blacklist file> <output .c file>\\n\", argv0);\n return 1;\n}\n\n\/\/ StripWWWPrefix removes \"www.\" from the beginning of any elements of the\n\/\/ vector.\nstatic void StripWWWPrefix(std::vector<std::string>* hosts) {\n static const char kPrefix[] = \"www.\";\n static const unsigned kPrefixLen = sizeof(kPrefix) - 1;\n\n for (size_t i = 0; i < hosts->size(); i++) {\n const std::string& h = (*hosts)[i];\n if (h.size() >= kPrefixLen &&\n memcmp(h.data(), kPrefix, kPrefixLen) == 0) {\n (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen);\n }\n }\n}\n\n\/\/ RemoveDuplicateEntries removes all duplicates from |hosts|.\nstatic void RemoveDuplicateEntries(std::vector<std::string>* hosts) {\n std::set<std::string> hosts_set;\n std::vector<std::string> ret;\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n if (hosts_set.count(*i)) {\n if (verbose)\n fprintf(stderr, \"Removing duplicate entry for %s\\n\", i->c_str());\n continue;\n }\n hosts_set.insert(*i);\n ret.push_back(*i);\n }\n\n hosts->swap(ret);\n}\n\n\/\/ ParentDomain returns the parent domain for a given domain name or the empty\n\/\/ string if the name is a top-level domain.\nstatic std::string ParentDomain(const std::string& in) {\n for (size_t i = 0; i < in.size(); i++) {\n if (in[i] == '.') {\n return in.substr(i + 1, in.size() - i - 1);\n }\n }\n\n return std::string();\n}\n\n\/\/ RemoveRedundantEntries removes any entries which are subdomains of other\n\/\/ entries. (i.e. foo.example.com would be removed if example.com were also\n\/\/ included.)\nstatic void RemoveRedundantEntries(std::vector<std::string>* hosts) {\n std::set<std::string> hosts_set;\n std::vector<std::string> ret;\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n hosts_set.insert(*i);\n }\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n std::string parent = ParentDomain(*i);\n while (!parent.empty()) {\n if (hosts_set.count(parent))\n break;\n parent = ParentDomain(parent);\n }\n if (parent.empty()) {\n ret.push_back(*i);\n } else {\n if (verbose)\n fprintf(stderr, \"Removing %s as redundant\\n\", i->c_str());\n }\n }\n\n hosts->swap(ret);\n}\n\n\/\/ CheckLengths returns true iff every host is less than 256 bytes long (not\n\/\/ including the terminating NUL) and contains two or more labels.\nstatic bool CheckLengths(const std::vector<std::string>& hosts) {\n for (std::vector<std::string>::const_iterator\n i = hosts.begin(); i != hosts.end(); i++) {\n if (i->size() >= 256) {\n fprintf(stderr, \"Entry %s is too large\\n\", i->c_str());\n return false;\n }\n if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) {\n fprintf(stderr, \"Entry %s contains too few labels\\n\", i->c_str());\n return false;\n }\n }\n\n return true;\n}\n\nint main(int argc, char** argv) {\n if (argc != 3)\n return usage(argv[0]);\n\n const char* input_file = argv[1];\n const char* output_file = argv[2];\n FILE* input = fopen(input_file, \"r\");\n if (!input) {\n perror(\"open\");\n return usage(argv[0]);\n }\n\n if (fseek(input, 0, SEEK_END)) {\n perror(\"fseek\");\n return 1;\n }\n\n const long input_size = ftell(input);\n\n if (fseek(input, 0, SEEK_SET)) {\n perror(\"fseek\");\n return 1;\n }\n\n char* buffer = static_cast<char*>(malloc(input_size));\n if (fread(buffer, input_size, 1, input) != 1) {\n perror(\"fread\");\n free(buffer);\n fclose(input);\n return 1;\n }\n fclose(input);\n\n std::vector<std::string> hosts;\n\n off_t line_start = 0;\n bool is_comment = false;\n bool non_whitespace_seen = false;\n for (long i = 0; i <= input_size; i++) {\n if (i == input_size || buffer[i] == '\\n') {\n if (!is_comment && non_whitespace_seen)\n hosts.push_back(std::string(&buffer[line_start], i - line_start));\n is_comment = false;\n non_whitespace_seen = false;\n line_start = i + 1;\n continue;\n }\n\n if (i == line_start && buffer[i] == '#')\n is_comment = true;\n if (buffer[i] != ' ' && buffer[i] != '\\t')\n non_whitespace_seen = true;\n }\n free(buffer);\n\n fprintf(stderr, \"Have %d hosts after parse\\n\", (int) hosts.size());\n StripWWWPrefix(&hosts);\n RemoveDuplicateEntries(&hosts);\n fprintf(stderr, \"Have %d hosts after removing duplicates\\n\", (int) hosts.size());\n RemoveRedundantEntries(&hosts);\n fprintf(stderr, \"Have %d hosts after removing redundants\\n\", (int) hosts.size());\n if (!CheckLengths(hosts)) {\n fprintf(stderr, \"One or more entries is too large or too small\\n\");\n return 2;\n }\n\n fprintf(stderr, \"Using %d entry hash table\\n\", kBuckets);\n uint32 table[kBuckets];\n std::vector<std::string> buckets[kBuckets];\n\n for (std::vector<std::string>::const_iterator\n i = hosts.begin(); i != hosts.end(); i++) {\n const char* last_two_labels =\n SSLFalseStartBlacklist::LastTwoLabels(i->c_str());\n const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels);\n buckets[h & (kBuckets - 1)].push_back(*i);\n }\n\n std::string table_data;\n unsigned max_bucket_size = 0;\n for (unsigned i = 0; i < kBuckets; i++) {\n if (buckets[i].size() > max_bucket_size)\n max_bucket_size = buckets[i].size();\n\n table[i] = table_data.size();\n for (std::vector<std::string>::const_iterator\n j = buckets[i].begin(); j != buckets[i].end(); j++) {\n table_data.push_back((char) j->size());\n table_data.append(*j);\n }\n }\n\n fprintf(stderr, \"Largest bucket has %d entries\\n\", max_bucket_size);\n\n FILE* out = fopen(output_file, \"w+\");\n if (!out) {\n perror(\"opening output file\");\n return 4;\n }\n\n fprintf(out, \"\/\/ Copyright (c) 2010 The Chromium Authors. All rights \"\n \"reserved.\\n\/\/ Use of this source code is governed by a BSD-style \"\n \"license that can be\\n\/\/ found in the LICENSE file.\\n\\n\");\n fprintf(out, \"\/\/ WARNING: this code is generated by\\n\"\n \"\/\/ ssl_false_start_blacklist_process.cc. Do not edit.\\n\\n\");\n fprintf(out, \"#include \\\"base\/basictypes.h\\\"\\n\\n\");\n fprintf(out, \"#include \\\"net\/base\/ssl_false_start_blacklist.h\\\"\\n\\n\");\n fprintf(out, \"namespace net {\\n\\n\");\n fprintf(out, \"const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\\n\",\n kBuckets);\n for (unsigned i = 0; i < kBuckets; i++) {\n fprintf(out, \" %u,\\n\", (unsigned) table[i]);\n }\n fprintf(out, \" %u,\\n\", (unsigned) table_data.size());\n fprintf(out, \"};\\n\\n\");\n\n fprintf(out, \"const char SSLFalseStartBlacklist::kHashData[] = {\\n\");\n for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) {\n if (line_length == 0)\n fprintf(out, \" \");\n uint8 c = static_cast<uint8>(table_data[i]);\n line_length += fprintf(out, \"%d, \", c);\n if (i == table_data.size() - 1) {\n fprintf(out, \"\\n};\\n\");\n } else if (line_length >= 70) {\n fprintf(out, \"\\n\");\n line_length = 0;\n }\n }\n fprintf(out, \"\\n} \/\/ namespace net\\n\");\n fclose(out);\n\n return 0;\n}\n<commit_msg>net: update False Start blacklist processing for \\r\\n<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This utility program exists to process the False Start blacklist file into\n\/\/ a static hash table so that it can be efficiently queried by Chrome.\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <set>\n#include <string>\n#include <vector>\n\n#include \"base\/basictypes.h\"\n#include \"net\/base\/ssl_false_start_blacklist.h\"\n\nusing net::SSLFalseStartBlacklist;\n\nstatic const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets;\n\nstatic bool verbose = false;\n\nstatic int\nusage(const char* argv0) {\n fprintf(stderr, \"Usage: %s <blacklist file> <output .c file>\\n\", argv0);\n return 1;\n}\n\n\/\/ StripWWWPrefix removes \"www.\" from the beginning of any elements of the\n\/\/ vector.\nstatic void StripWWWPrefix(std::vector<std::string>* hosts) {\n static const char kPrefix[] = \"www.\";\n static const unsigned kPrefixLen = sizeof(kPrefix) - 1;\n\n for (size_t i = 0; i < hosts->size(); i++) {\n const std::string& h = (*hosts)[i];\n if (h.size() >= kPrefixLen &&\n memcmp(h.data(), kPrefix, kPrefixLen) == 0) {\n (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen);\n }\n }\n}\n\n\/\/ RemoveDuplicateEntries removes all duplicates from |hosts|.\nstatic void RemoveDuplicateEntries(std::vector<std::string>* hosts) {\n std::set<std::string> hosts_set;\n std::vector<std::string> ret;\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n if (hosts_set.count(*i)) {\n if (verbose)\n fprintf(stderr, \"Removing duplicate entry for %s\\n\", i->c_str());\n continue;\n }\n hosts_set.insert(*i);\n ret.push_back(*i);\n }\n\n hosts->swap(ret);\n}\n\n\/\/ ParentDomain returns the parent domain for a given domain name or the empty\n\/\/ string if the name is a top-level domain.\nstatic std::string ParentDomain(const std::string& in) {\n for (size_t i = 0; i < in.size(); i++) {\n if (in[i] == '.') {\n return in.substr(i + 1, in.size() - i - 1);\n }\n }\n\n return std::string();\n}\n\n\/\/ RemoveRedundantEntries removes any entries which are subdomains of other\n\/\/ entries. (i.e. foo.example.com would be removed if example.com were also\n\/\/ included.)\nstatic void RemoveRedundantEntries(std::vector<std::string>* hosts) {\n std::set<std::string> hosts_set;\n std::vector<std::string> ret;\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n hosts_set.insert(*i);\n }\n\n for (std::vector<std::string>::const_iterator\n i = hosts->begin(); i != hosts->end(); i++) {\n std::string parent = ParentDomain(*i);\n while (!parent.empty()) {\n if (hosts_set.count(parent))\n break;\n parent = ParentDomain(parent);\n }\n if (parent.empty()) {\n ret.push_back(*i);\n } else {\n if (verbose)\n fprintf(stderr, \"Removing %s as redundant\\n\", i->c_str());\n }\n }\n\n hosts->swap(ret);\n}\n\n\/\/ CheckLengths returns true iff every host is less than 256 bytes long (not\n\/\/ including the terminating NUL) and contains two or more labels.\nstatic bool CheckLengths(const std::vector<std::string>& hosts) {\n for (std::vector<std::string>::const_iterator\n i = hosts.begin(); i != hosts.end(); i++) {\n if (i->size() >= 256) {\n fprintf(stderr, \"Entry %s is too large\\n\", i->c_str());\n return false;\n }\n if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) {\n fprintf(stderr, \"Entry %s contains too few labels\\n\", i->c_str());\n return false;\n }\n }\n\n return true;\n}\n\nint main(int argc, char** argv) {\n if (argc != 3)\n return usage(argv[0]);\n\n const char* input_file = argv[1];\n const char* output_file = argv[2];\n FILE* input = fopen(input_file, \"rb\");\n if (!input) {\n perror(\"open\");\n return usage(argv[0]);\n }\n\n if (fseek(input, 0, SEEK_END)) {\n perror(\"fseek\");\n return 1;\n }\n\n const long input_size = ftell(input);\n\n if (fseek(input, 0, SEEK_SET)) {\n perror(\"fseek\");\n return 1;\n }\n\n char* buffer = static_cast<char*>(malloc(input_size));\n long done = 0;\n while (done < input_size) {\n size_t n = fread(buffer + done, 1, input_size - done, input);\n if (n == 0) {\n perror(\"fread\");\n free(buffer);\n fclose(input);\n return 1;\n }\n done += n;\n }\n fclose(input);\n\n std::vector<std::string> hosts;\n\n off_t line_start = 0;\n bool is_comment = false;\n bool non_whitespace_seen = false;\n for (long i = 0; i <= input_size; i++) {\n if (i == input_size || buffer[i] == '\\n') {\n if (!is_comment && non_whitespace_seen) {\n long len = i - line_start;\n if (i > 0 && buffer[i-1] == '\\r')\n len--;\n hosts.push_back(std::string(&buffer[line_start], len));\n }\n is_comment = false;\n non_whitespace_seen = false;\n line_start = i + 1;\n continue;\n }\n\n if (i == line_start && buffer[i] == '#')\n is_comment = true;\n if (buffer[i] != ' ' && buffer[i] != '\\t' && buffer[i] != '\\r')\n non_whitespace_seen = true;\n }\n free(buffer);\n\n fprintf(stderr, \"Have %d hosts after parse\\n\", (int) hosts.size());\n StripWWWPrefix(&hosts);\n RemoveDuplicateEntries(&hosts);\n fprintf(stderr, \"Have %d hosts after removing duplicates\\n\", (int) hosts.size());\n RemoveRedundantEntries(&hosts);\n fprintf(stderr, \"Have %d hosts after removing redundants\\n\", (int) hosts.size());\n if (!CheckLengths(hosts)) {\n fprintf(stderr, \"One or more entries is too large or too small\\n\");\n return 2;\n }\n\n fprintf(stderr, \"Using %d entry hash table\\n\", kBuckets);\n uint32 table[kBuckets];\n std::vector<std::string> buckets[kBuckets];\n\n for (std::vector<std::string>::const_iterator\n i = hosts.begin(); i != hosts.end(); i++) {\n const char* last_two_labels =\n SSLFalseStartBlacklist::LastTwoLabels(i->c_str());\n const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels);\n buckets[h & (kBuckets - 1)].push_back(*i);\n }\n\n std::string table_data;\n unsigned max_bucket_size = 0;\n for (unsigned i = 0; i < kBuckets; i++) {\n if (buckets[i].size() > max_bucket_size)\n max_bucket_size = buckets[i].size();\n\n table[i] = table_data.size();\n for (std::vector<std::string>::const_iterator\n j = buckets[i].begin(); j != buckets[i].end(); j++) {\n table_data.push_back((char) j->size());\n table_data.append(*j);\n }\n }\n\n fprintf(stderr, \"Largest bucket has %d entries\\n\", max_bucket_size);\n\n FILE* out = fopen(output_file, \"w+\");\n if (!out) {\n perror(\"opening output file\");\n return 4;\n }\n\n fprintf(out, \"\/\/ Copyright (c) 2010 The Chromium Authors. All rights \"\n \"reserved.\\n\/\/ Use of this source code is governed by a BSD-style \"\n \"license that can be\\n\/\/ found in the LICENSE file.\\n\\n\");\n fprintf(out, \"\/\/ WARNING: this code is generated by\\n\"\n \"\/\/ ssl_false_start_blacklist_process.cc. Do not edit.\\n\\n\");\n fprintf(out, \"#include \\\"base\/basictypes.h\\\"\\n\\n\");\n fprintf(out, \"#include \\\"net\/base\/ssl_false_start_blacklist.h\\\"\\n\\n\");\n fprintf(out, \"namespace net {\\n\\n\");\n fprintf(out, \"const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\\n\",\n kBuckets);\n for (unsigned i = 0; i < kBuckets; i++) {\n fprintf(out, \" %u,\\n\", (unsigned) table[i]);\n }\n fprintf(out, \" %u,\\n\", (unsigned) table_data.size());\n fprintf(out, \"};\\n\\n\");\n\n fprintf(out, \"const char SSLFalseStartBlacklist::kHashData[] = {\\n\");\n for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) {\n if (line_length == 0)\n fprintf(out, \" \");\n uint8 c = static_cast<uint8>(table_data[i]);\n line_length += fprintf(out, \"%d, \", c);\n if (i == table_data.size() - 1) {\n fprintf(out, \"\\n};\\n\");\n } else if (line_length >= 70) {\n fprintf(out, \"\\n\");\n line_length = 0;\n }\n }\n fprintf(out, \"\\n} \/\/ namespace net\\n\");\n fclose(out);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_main_extra_parts_aura.h\"\n\n#include \"ash\/accelerators\/accelerator_controller.h\"\n#include \"ash\/shell.h\"\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/caps_lock_handler.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/chrome_shell_delegate.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/screen_orientation_listener.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/screenshot_taker.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/status_area_host_aura.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/root_window.h\"\n#include \"ui\/gfx\/compositor\/compositor_setup.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/ui\/views\/aura\/brightness_controller_chromeos.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/volume_controller_chromeos.h\"\n#include \"chrome\/browser\/chromeos\/input_method\/input_method_manager.h\"\n#include \"chrome\/browser\/chromeos\/system\/runtime_environment.h\"\n#endif\n\nChromeBrowserMainExtraPartsAura::ChromeBrowserMainExtraPartsAura()\n : ChromeBrowserMainExtraParts() {\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PreProfileInit() {\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestCompositor)) {\n ui::SetupTestCompositor();\n }\n\n#if defined(OS_CHROMEOS)\n if (chromeos::system::runtime_environment::IsRunningOnChromeOS())\n aura::RootWindow::set_use_fullscreen_host_window(true);\n aura::RootWindow::set_hide_host_cursor(true);\n#endif\n\n \/\/ Shell takes ownership of ChromeShellDelegate.\n ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate);\n shell->accelerator_controller()->SetScreenshotDelegate(\n scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass());\n#if defined(OS_CHROMEOS)\n shell->accelerator_controller()->SetBrightnessControlDelegate(\n scoped_ptr<ash::BrightnessControlDelegate>(\n new BrightnessController).Pass());\n chromeos::input_method::XKeyboard* xkeyboard =\n chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard();\n shell->accelerator_controller()->SetCapsLockDelegate(\n scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass());\n shell->accelerator_controller()->SetVolumeControlDelegate(\n scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass());\n#endif\n\n \/\/ Make sure the singleton ScreenOrientationListener object is created.\n ScreenOrientationListener::GetInstance();\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PostProfileInit() {\n \/\/ Add the status area buttons after Profile has been initialized.\n ChromeShellDelegate::instance()->status_area_host()->AddButtons();\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PostMainMessageLoopRun() {\n ash::Shell::DeleteInstance();\n aura::RootWindow::DeleteInstance();\n aura::Env::DeleteInstance();\n}\n<commit_msg>aura: Fix bug that hid cursor on Linux workstations.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_main_extra_parts_aura.h\"\n\n#include \"ash\/accelerators\/accelerator_controller.h\"\n#include \"ash\/shell.h\"\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/caps_lock_handler.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/chrome_shell_delegate.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/screen_orientation_listener.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/screenshot_taker.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/status_area_host_aura.h\"\n#include \"ui\/aura\/env.h\"\n#include \"ui\/aura\/root_window.h\"\n#include \"ui\/gfx\/compositor\/compositor_setup.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/ui\/views\/aura\/brightness_controller_chromeos.h\"\n#include \"chrome\/browser\/ui\/views\/aura\/volume_controller_chromeos.h\"\n#include \"chrome\/browser\/chromeos\/input_method\/input_method_manager.h\"\n#include \"chrome\/browser\/chromeos\/system\/runtime_environment.h\"\n#endif\n\nChromeBrowserMainExtraPartsAura::ChromeBrowserMainExtraPartsAura()\n : ChromeBrowserMainExtraParts() {\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PreProfileInit() {\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestCompositor)) {\n ui::SetupTestCompositor();\n }\n\n#if defined(OS_CHROMEOS)\n if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {\n aura::RootWindow::set_use_fullscreen_host_window(true);\n aura::RootWindow::set_hide_host_cursor(true);\n }\n#endif\n\n \/\/ Shell takes ownership of ChromeShellDelegate.\n ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate);\n shell->accelerator_controller()->SetScreenshotDelegate(\n scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass());\n#if defined(OS_CHROMEOS)\n shell->accelerator_controller()->SetBrightnessControlDelegate(\n scoped_ptr<ash::BrightnessControlDelegate>(\n new BrightnessController).Pass());\n chromeos::input_method::XKeyboard* xkeyboard =\n chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard();\n shell->accelerator_controller()->SetCapsLockDelegate(\n scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass());\n shell->accelerator_controller()->SetVolumeControlDelegate(\n scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass());\n#endif\n\n \/\/ Make sure the singleton ScreenOrientationListener object is created.\n ScreenOrientationListener::GetInstance();\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PostProfileInit() {\n \/\/ Add the status area buttons after Profile has been initialized.\n ChromeShellDelegate::instance()->status_area_host()->AddButtons();\n}\n\nvoid ChromeBrowserMainExtraPartsAura::PostMainMessageLoopRun() {\n ash::Shell::DeleteInstance();\n aura::RootWindow::DeleteInstance();\n aura::Env::DeleteInstance();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {\n ASSERT_TRUE(RunExtensionTest(\"storage\")) << message_;\n}\n<commit_msg>Mark ExtensionApiTest.Storage as failing, it always fails on Windows after r110181.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\n#if defined(OS_WIN)\n\/\/ Always fails on Windows after r110181: http:\/\/crbug.com\/104419.\n#define MAYBE_Storage FAILS_Storage\n#else\n#define MAYBE_Storage Storage\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {\n ASSERT_TRUE(RunExtensionTest(\"storage\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/file_system\/file_system_host_context.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nFileSystemHostContext::FileSystemHostContext(\n const FilePath& data_path, bool is_incognito)\n : quota_manager_(new fileapi::FileSystemQuota()),\n path_manager_(new fileapi::FileSystemPathManager(\n BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),\n data_path, is_incognito, allow_file_access_from_files_)) {\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n allow_file_access_from_files_ =\n command_line->HasSwitch(switches::kAllowFileAccessFromFiles);\n unlimited_quota_ =\n command_line->HasSwitch(switches::kUnlimitedQuotaForFiles);\n}\n\nbool FileSystemHostContext::CheckOriginQuota(const GURL& url, int64 growth) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n \/\/ If allow-file-access-from-files flag is explicitly given and the scheme\n \/\/ is file, or if unlimited quota for this process was explicitly requested,\n \/\/ return true.\n if (unlimited_quota_ ||\n (url.SchemeIsFile() && allow_file_access_from_files_))\n return true;\n return quota_manager_->CheckOriginQuota(url, growth);\n}\n\nvoid FileSystemHostContext::SetOriginQuotaUnlimited(const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n quota_manager_->SetOriginQuotaUnlimited(url);\n}\n\nvoid FileSystemHostContext::ResetOriginQuotaUnlimited(const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n quota_manager_->ResetOriginQuotaUnlimited(url);\n}\n\nFileSystemHostContext::~FileSystemHostContext() {}\n<commit_msg>Use allow_file_access_from_files after it's initialized.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/file_system\/file_system_host_context.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nFileSystemHostContext::FileSystemHostContext(\n const FilePath& data_path, bool is_incognito)\n : quota_manager_(new fileapi::FileSystemQuota()) {\n CommandLine* command_line = CommandLine::ForCurrentProcess();\n allow_file_access_from_files_ =\n command_line->HasSwitch(switches::kAllowFileAccessFromFiles);\n unlimited_quota_ =\n command_line->HasSwitch(switches::kUnlimitedQuotaForFiles);\n path_manager_.reset(new fileapi::FileSystemPathManager(\n BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),\n data_path, is_incognito, allow_file_access_from_files_));\n}\n\nbool FileSystemHostContext::CheckOriginQuota(const GURL& url, int64 growth) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n \/\/ If allow-file-access-from-files flag is explicitly given and the scheme\n \/\/ is file, or if unlimited quota for this process was explicitly requested,\n \/\/ return true.\n if (unlimited_quota_ ||\n (url.SchemeIsFile() && allow_file_access_from_files_))\n return true;\n return quota_manager_->CheckOriginQuota(url, growth);\n}\n\nvoid FileSystemHostContext::SetOriginQuotaUnlimited(const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n quota_manager_->SetOriginQuotaUnlimited(url);\n}\n\nvoid FileSystemHostContext::ResetOriginQuotaUnlimited(const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n quota_manager_->ResetOriginQuotaUnlimited(url);\n}\n\nFileSystemHostContext::~FileSystemHostContext() {}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(jorlow): Reenable when https:\/\/bugs.webkit.org\/show_bug.cgi?id=28094\n\/\/ is fixed. Until then, this will cause crashes even if the\n\/\/ individual tests are disabled.\n#if 0\n\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\n\/\/static const char* kTopLevelFiles[] = {\n \/\/\"window-attributes-exist.html\"\n\/\/};\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\nstatic const char* kSubDirFiles[] = {\n \"clear.html\",\n \"delete-removal.html\",\n \"enumerate-storage.html\",\n \"enumerate-with-length-and-key.html\",\n \/\/\"iframe-events.html\",\n \/\/\"index-get-and-set.html\",\n \/\/\"onstorage-attribute-markup.html\",\n \/\/\"onstorage-attribute-setattribute.html\",\n \/\/\"localstorage\/onstorage-attribute-setwindow.html\",\n \/\/\"simple-events.html\",\n \"simple-usage.html\",\n \/\/\"string-conversion.html\",\n\/\/ \"window-open.html\"\n};\n\nclass DOMStorageTest : public UILayoutTest {\n protected:\n DOMStorageTest()\n : UILayoutTest(),\n test_dir_(FilePath().AppendASCII(\"LayoutTests\").\n AppendASCII(\"storage\").AppendASCII(\"domstorage\"))\n {\n }\n\n virtual ~DOMStorageTest() { }\n\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);\n launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);\n UILayoutTest::SetUp();\n }\n\n FilePath test_dir_;\n};\n\nTEST_F(DOMStorageTest, DOMStorageLayoutTests) {\n \/\/ TODO(jorlow): Enable these tests when we remove them from the\n \/\/ test_exceptions.txt file.\n \/\/InitializeForLayoutTest(test_dir_, FilePath(), false);\n \/\/for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)\n \/\/ RunLayoutTest(kTopLevelFiles[i], false, true);\n}\n\nTEST_F(DOMStorageTest, LocalStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"localstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\nTEST_F(DOMStorageTest, SessionStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"sessionstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\n#endif\n<commit_msg>Re-enable the DOM Storage ui tests that worked orginally. Next step: enable ones that should work, but (for some reason) don't.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\n\/\/static const char* kTopLevelFiles[] = {\n \/\/\"window-attributes-exist.html\"\n\/\/};\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\nstatic const char* kSubDirFiles[] = {\n \/\/\"clear.html\",\n \"delete-removal.html\",\n \"enumerate-storage.html\",\n \"enumerate-with-length-and-key.html\",\n \/\/\"iframe-events.html\",\n \/\/\"index-get-and-set.html\",\n \/\/\"onstorage-attribute-markup.html\",\n \/\/\"onstorage-attribute-setattribute.html\",\n \/\/\"localstorage\/onstorage-attribute-setwindow.html\",\n \/\/\"simple-events.html\",\n \"simple-usage.html\",\n \/\/\"string-conversion.html\",\n \/\/\"window-open.html\"\n};\n\nclass DOMStorageTest : public UILayoutTest {\n protected:\n DOMStorageTest()\n : UILayoutTest(),\n test_dir_(FilePath().AppendASCII(\"LayoutTests\").\n AppendASCII(\"storage\").AppendASCII(\"domstorage\"))\n {\n }\n\n virtual ~DOMStorageTest() { }\n\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);\n launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);\n UILayoutTest::SetUp();\n }\n\n FilePath test_dir_;\n};\n\nTEST_F(DOMStorageTest, DOMStorageLayoutTests) {\n \/\/ TODO(jorlow): Enable these tests when we remove them from the\n \/\/ test_exceptions.txt file.\n \/\/InitializeForLayoutTest(test_dir_, FilePath(), false);\n \/\/for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)\n \/\/ RunLayoutTest(kTopLevelFiles[i], false, true);\n}\n\nTEST_F(DOMStorageTest, LocalStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"localstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\nTEST_F(DOMStorageTest, SessionStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"sessionstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <cstdio>\n#include <string>\n\n#include \"base\/at_exit.h\"\n#include \"base\/base64.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier_factory.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier_observer.h\"\n#include \"chrome\/browser\/sync\/syncable\/model_type.h\"\n#include \"chrome\/browser\/sync\/syncable\/model_type_payload_map.h\"\n#include \"chrome\/test\/test_url_request_context_getter.h\"\n#include \"content\/browser\/browser_thread.h\"\n\n\/\/ This is a simple utility that initializes a sync notifier and\n\/\/ listens to any received notifications.\n\nnamespace {\n\n\/\/ Class to print received notifications events.\nclass NotificationPrinter : public sync_notifier::SyncNotifierObserver {\n public:\n NotificationPrinter() {}\n virtual ~NotificationPrinter() {}\n\n virtual void OnIncomingNotification(\n const syncable::ModelTypePayloadMap& type_payloads) {\n for (syncable::ModelTypePayloadMap::const_iterator it =\n type_payloads.begin(); it != type_payloads.end(); ++it) {\n LOG(INFO) << \"Notification: type = \"\n << syncable::ModelTypeToString(it->first)\n << \", payload = \" << it->second;\n }\n }\n\n virtual void OnNotificationStateChange(bool notifications_enabled) {\n LOG(INFO) << \"Notifications enabled: \" << notifications_enabled;\n }\n\n virtual void StoreState(const std::string& state) {\n std::string base64_state;\n CHECK(base::Base64Encode(state, &base64_state));\n LOG(INFO) << \"Got state to store: \" << base64_state;\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(NotificationPrinter);\n};\n\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n base::AtExitManager exit_manager;\n scoped_refptr<TestURLRequestContextGetter> request_context_getter(\n new TestURLRequestContextGetter);\n BrowserThread io_thread(BrowserThread::IO);\n base::Thread::Options options;\n options.message_loop_type = MessageLoop::TYPE_IO;\n io_thread.StartWithOptions(options);\n CommandLine::Init(argc, argv);\n logging::InitLogging(\n NULL,\n logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE,\n logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);\n\n \/\/ Parse command line.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string email = command_line.GetSwitchValueASCII(\"email\");\n std::string token = command_line.GetSwitchValueASCII(\"token\");\n \/\/ TODO(akalin): Write a wrapper script that gets a token for an\n \/\/ email and password and passes that in to this utility.\n if (email.empty() || token.empty()) {\n std::printf(\"Usage: %s --email=foo@bar.com --token=token\\n\\n\"\n \"See sync_notifier_factory.cc for more switches.\\n\\n\"\n \"Run chrome and set a breakpoint on \"\n \"sync_api::SyncManager::SyncInternal::UpdateCredentials() \"\n \"after logging into sync to get the token to pass into this \"\n \"utility.\\n\",\n argv[0]);\n return -1;\n }\n\n \/\/ Needed by the SyncNotifier implementations.\n MessageLoop main_loop;\n\n const char kClientInfo[] = \"sync_listen_notifications\";\n sync_notifier::SyncNotifierFactory sync_notifier_factory(\n kClientInfo, request_context_getter.get(), command_line);\n scoped_ptr<sync_notifier::SyncNotifier> sync_notifier(\n sync_notifier_factory.CreateSyncNotifier());\n NotificationPrinter notification_printer;\n sync_notifier->AddObserver(¬ification_printer);\n\n sync_notifier->UpdateCredentials(email, token);\n {\n \/\/ Listen for notifications for all known types.\n syncable::ModelTypeSet types;\n for (int i = syncable::FIRST_REAL_MODEL_TYPE;\n i < syncable::MODEL_TYPE_COUNT; ++i) {\n types.insert(syncable::ModelTypeFromInt(i));\n }\n sync_notifier->UpdateEnabledTypes(types);\n }\n\n main_loop.Run();\n\n sync_notifier->RemoveObserver(¬ification_printer);\n io_thread.Stop();\n return 0;\n}\n<commit_msg>[Sync] Add UI thread to sync_listen_notifications utility.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <cstdio>\n#include <string>\n\n#include \"base\/at_exit.h\"\n#include \"base\/base64.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier_factory.h\"\n#include \"chrome\/browser\/sync\/notifier\/sync_notifier_observer.h\"\n#include \"chrome\/browser\/sync\/syncable\/model_type.h\"\n#include \"chrome\/browser\/sync\/syncable\/model_type_payload_map.h\"\n#include \"chrome\/test\/test_url_request_context_getter.h\"\n#include \"content\/browser\/browser_thread.h\"\n\n\/\/ This is a simple utility that initializes a sync notifier and\n\/\/ listens to any received notifications.\n\nnamespace {\n\n\/\/ Class to print received notifications events.\nclass NotificationPrinter : public sync_notifier::SyncNotifierObserver {\n public:\n NotificationPrinter() {}\n virtual ~NotificationPrinter() {}\n\n virtual void OnIncomingNotification(\n const syncable::ModelTypePayloadMap& type_payloads) {\n for (syncable::ModelTypePayloadMap::const_iterator it =\n type_payloads.begin(); it != type_payloads.end(); ++it) {\n LOG(INFO) << \"Notification: type = \"\n << syncable::ModelTypeToString(it->first)\n << \", payload = \" << it->second;\n }\n }\n\n virtual void OnNotificationStateChange(bool notifications_enabled) {\n LOG(INFO) << \"Notifications enabled: \" << notifications_enabled;\n }\n\n virtual void StoreState(const std::string& state) {\n std::string base64_state;\n CHECK(base::Base64Encode(state, &base64_state));\n LOG(INFO) << \"Got state to store: \" << base64_state;\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(NotificationPrinter);\n};\n\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n base::AtExitManager exit_manager;\n CommandLine::Init(argc, argv);\n logging::InitLogging(\n NULL,\n logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE,\n logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);\n\n MessageLoop ui_loop;\n BrowserThread ui_thread(BrowserThread::UI, &ui_loop);\n\n BrowserThread io_thread(BrowserThread::IO);\n base::Thread::Options options;\n options.message_loop_type = MessageLoop::TYPE_IO;\n io_thread.StartWithOptions(options);\n\n \/\/ Parse command line.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string email = command_line.GetSwitchValueASCII(\"email\");\n std::string token = command_line.GetSwitchValueASCII(\"token\");\n \/\/ TODO(akalin): Write a wrapper script that gets a token for an\n \/\/ email and password and passes that in to this utility.\n if (email.empty() || token.empty()) {\n std::printf(\"Usage: %s --email=foo@bar.com --token=token\\n\\n\"\n \"See sync_notifier_factory.cc for more switches.\\n\\n\"\n \"Run chrome and set a breakpoint on \"\n \"sync_api::SyncManager::SyncInternal::UpdateCredentials() \"\n \"after logging into sync to get the token to pass into this \"\n \"utility.\\n\",\n argv[0]);\n return -1;\n }\n\n const char kClientInfo[] = \"sync_listen_notifications\";\n scoped_refptr<TestURLRequestContextGetter> request_context_getter(\n new TestURLRequestContextGetter());\n sync_notifier::SyncNotifierFactory sync_notifier_factory(\n kClientInfo, request_context_getter, command_line);\n scoped_ptr<sync_notifier::SyncNotifier> sync_notifier(\n sync_notifier_factory.CreateSyncNotifier());\n NotificationPrinter notification_printer;\n sync_notifier->AddObserver(¬ification_printer);\n\n sync_notifier->UpdateCredentials(email, token);\n {\n \/\/ Listen for notifications for all known types.\n syncable::ModelTypeSet types;\n for (int i = syncable::FIRST_REAL_MODEL_TYPE;\n i < syncable::MODEL_TYPE_COUNT; ++i) {\n types.insert(syncable::ModelTypeFromInt(i));\n }\n sync_notifier->UpdateEnabledTypes(types);\n }\n\n ui_loop.Run();\n\n sync_notifier->RemoveObserver(¬ification_printer);\n io_thread.Stop();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010, Intel Corporation. All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are \n * met:\n * \n * * Redistributions of source code must retain the above copyright \n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above \n * copyright notice, this list of conditions and the following disclaimer \n * in the documentation and\/or other materials provided with the \n * distribution.\n * * Neither the name of Intel Corporation nor the names of its \n * contributors may be used to endorse or promote products derived from \n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR \n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"chrome\/browser\/ui\/meegotouch\/back_forward_button_qt.h\"\n#include \"chrome\/browser\/ui\/meegotouch\/browser_window_qt.h\"\n#include \"chrome\/browser\/ui\/meegotouch\/browser_toolbar_qt.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/navigation_entry.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/registry_controlled_domain.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n\n#include <QGraphicsItem>\n#include <QGraphicsSceneMouseEvent>\n#include <QVector>\n#include <QList>\n#include <QTimer>\n#include <algorithm>\n#include <QGraphicsSceneResizeEvent>\n#include <QGraphicsWidget>\n#include <QEvent>\n#include <QDebug>\n\/\/#include <QTapAndHoldGesture>\n\n#include <QDeclarativeEngine>\n#include <QDeclarativeView>\n#include <QDeclarativeContext>\n#include <QDeclarativeItem>\n#include <QDeclarativeImageProvider>\n#include <QAbstractListModel>\n\n\/\/ Image provider, managing to provide image to QML\n\/\/ for history view\n\/\/ Due to qml limitation, the id of image is suffixed with\n\/\/ a static increaser, which forces using new image source\n\/\/ each time\nclass HistoryImageProvider : public QDeclarativeImageProvider \n{\npublic:\n HistoryImageProvider()\n : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)\n {}\n\n \/\/ clear all images in image hashmap\n void clear()\n {\n imageList_.clear();\n }\n\n \/\/ overrided function, inherited from QDeclarativeImageProvider\n virtual QImage requestImage(const QString& id,\n QSize* size,\n const QSize& requestedSize)\n {\n DLOG(INFO) << \"requesting image id: \" << id.toStdString();\n int finded = id.indexOf(\"_\");\n if (finded != -1) {\n QImage& image = imageList_[id.left(finded)];\n if (!image.isNull()) {\n \/\/QImage scaled = image.scaled(requestedSize);\n *size = image.size();\n return image;\n }\n }\n *size = QSize(0, 0);\n return QImage();\n }\n\n \/\/ add a new image\n void addImage(const QString& id, const QImage &image)\n {\n imageList_.insert(id, image);\n }\n\nprivate:\n QMap<QString, QImage> imageList_;\n};\n\nclass HistoryStackModel;\n\n\/\/ history entry to represent one history data\nclass HistoryEntry \n{\npublic:\n \n \/\/ constructor\n \/\/ @param index the index in history stack\n \/\/ @param hiProvider image provider for history stack\n \/\/ @param entry representation of navigation entry in browser\n \/\/ @param controller current navigation controller in browser\n \/\/ @param model history stack model\n HistoryEntry(const int index, \n HistoryImageProvider& hiProvider,\n NavigationEntry* entry,\n NavigationController* controller,\n HistoryStackModel* model)\n : index_(index), hiProvider_(hiProvider), entry_(entry), model_(model)\n {\n \/\/ get image\n HistoryService* hs = controller->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);\n hs->GetPageThumbnail(entry->url(), \n &consumer_,\n NewCallback(static_cast<HistoryEntry*>(this),\n &HistoryEntry::onThumbnailDataAvailable));\n \n std::wstring title_str = UTF16ToWide(entry->title());\n title_ = QString::fromStdWString(title_str);\n }\n\n void imgURLGen() \n {\n static QString prefix(\"image:\/\/historystack\/\");\n imageSrc_ = prefix + QString::number(index_) + \"_\" + QString::number(reloadNumber_);\n }\n\n \/\/ callback to get the image data from browser\n void onThumbnailDataAvailable(HistoryService::Handle request_handle,\n scoped_refptr<RefCountedBytes> jpeg_data); \n\n NavigationEntry* entry() { return entry_; }\n QString image() { return imageSrc_; }\n QString title() { return title_; }\n\n static void incReloadNumber() { reloadNumber_++; }\n static unsigned long reloadNumber() { return reloadNumber_; }\n\nprivate:\n \/\/ static increaser to generate unique image source \n static unsigned long reloadNumber_;\n\n int index_;\n HistoryImageProvider& hiProvider_;\n NavigationEntry* entry_;\n HistoryStackModel* model_;\n \/\/ image source\n QString imageSrc_;\n \/\/ history title\n QString title_;\n CancelableRequestConsumer consumer_;\n};\n\nunsigned long HistoryEntry::reloadNumber_ = 0;\n\n\/\/ represent list model used in QML to store history data\nclass HistoryStackModel: public QAbstractListModel\n{\n Q_OBJECT\n enum HistoryRole {\n IMAGE_ROLE = Qt::UserRole + 1,\n TITLE_ROLE\n };\n\npublic:\n HistoryStackModel(BackForwardButtonQtImpl* backForward)\n : back_forward_(backForward), returnedImages_(0)\n {\n QHash<int, QByteArray> roles;\n roles[IMAGE_ROLE] = \"thumbSrc\";\n roles[TITLE_ROLE] = \"title\";\n setRoleNames(roles);\n }\n\n ~HistoryStackModel()\n {\n clear();\n }\n\n \/\/ clear saved data\n void clear()\n {\n returnedImages_ = 0;\n beginResetModel();\n for(int i = 0; i < entryList_.count(); i++) {\n delete entryList_[i];\n }\n entryList_.clear();\n hiProvider_.clear();\n endResetModel();\n }\n\n \/\/ wrapper to check whether browser returns all images of history\n \/\/ so we can reset model to avoid resetting model many times\n void beginReset()\n {\n \/\/ begin reset if necessary\n returnedImages_++;\n if (returnedImages_ == rowCount()) {\n DLOG(INFO) << \"begin reset history stack model\";\n \/\/ generate new number to create new image url\n HistoryEntry::incReloadNumber();\n for(int i = 0; i < entryList_.count(); i++) {\n HistoryEntry* entry = entryList_[i];\n entry->imgURLGen();\n }\n beginResetModel();\n }\n }\n\n void endReset()\n {\n \/\/ end reset if necessary\n if (returnedImages_ == rowCount()) {\n DLOG(INFO) << \"end reset history stack model\";\n endResetModel();\n }\n }\n\n int rowCount(const QModelIndex& parent = QModelIndex()) const\n {\n return entryList_.count();\n }\n\n QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const\n {\n DLOG(INFO) << \"read list model data: row = \" << index.row() << \", column = \" << index.column();\n if(index.row() < 0 || index.row() > entryList_.count())\n return QVariant();\n HistoryEntry* entry = entryList_[index.row()];\n switch(role) {\n case IMAGE_ROLE:\n return entry->image();\n case TITLE_ROLE:\n return entry->title();\n default:\n return QVariant();\n }\n }\n\n void appendEntry(NavigationController* controller, NavigationEntry *entry)\n {\n HistoryEntry* historyEntry \n = new HistoryEntry(entryList_.count(),\n hiProvider_,\n entry, \n controller,\n this);\n beginInsertRows(QModelIndex(), rowCount(), rowCount());\n entryList_.push_back(historyEntry);\n endInsertRows();\n }\n\n \/\/ emit a showHistory signal to QML\n void show() { emit showHistory(); }\n\n \/\/ emit a hideHistory signal to QML\n void hide() { emit hideHistory(); }\n\n \/\/ emit a current selected(focused) history entry\n void setCurrent(int index) { emit current(index); }\n\n HistoryImageProvider* hiProvider() { return &hiProvider_; }\n\nQ_SIGNALS:\n \/\/ three signals used to notify QML\n void showHistory();\n void hideHistory();\n void current(int index);\n\npublic Q_SLOTS:\n \/\/ open specific page, called by QML element\n \/\/ It's called by QML element when user clicks one history entry in QML view\n void openPage(const int index);\n\nprivate:\n BackForwardButtonQtImpl* back_forward_;\n \/\/ list to hold entries\n QList<HistoryEntry*> entryList_;\n HistoryImageProvider hiProvider_;\n \/\/ count of returned images from browser\n int returnedImages_;\n};\n\nclass BackForwardButtonQtImpl\n{\npublic:\n enum NaviState {\n ONLY_BACK = 0,\n ONLY_FORWARD,\n BACK_FORWARD\n };\n\n \/\/ constructor\n BackForwardButtonQtImpl(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)\n :toolbar_(toolbar), browser_(browser), model_(this), \n state_(ONLY_BACK), active_(false)\n {\n QDeclarativeView* view = window->DeclarativeView();\n QDeclarativeContext *context = view->rootContext();\n context->setContextProperty(\"historyStackModel\", &model_);\n context->engine()->addImageProvider(QLatin1String(\"historystack\"), model_.hiProvider());\n }\n\n NavigationController* currentController()\n {\n return &(browser_->GetSelectedTabContents()->controller());\n }\n\n void openPage(NavigationEntry *entry)\n {\n currentController()->GoToIndex(currentController()->GetIndexOfEntry(entry));\n updateStatus();\n }\n\n void updateStatus()\n {\n if(currentController()->GetCurrentEntryIndex() == currentController()->entry_count() - 1)\n {\n state_ = ONLY_BACK;\n if (currentController()->entry_count() > 1) {\n active_ = true;\n } else {\n active_ = false;\n }\n } else if (currentController()->GetCurrentEntryIndex() == 0\n && currentController()->entry_count() > 0) {\n state_ = ONLY_FORWARD;\n } else if (currentController()->CanGoBack() && currentController()->CanGoForward()) {\n state_ = BACK_FORWARD;\n } else {\n state_ = ONLY_BACK;\n active_ = false;\n }\n \/\/ update button status in qml\n updateButton();\n DLOG(INFO) << \"In C++, updateStatus is invoked\\n\";\n }\n\n \/\/ update back-forward button icon\n void updateButton() { toolbar_->updateBfButton((int)state_, active_); }\n\n void tap()\n {\n DLOG(INFO) << \"In C++, tap is invoked\";\n switch(state_) {\n case ONLY_BACK:\n if (currentController()->CanGoBack()) {\n currentController()->GoBack();\n }\n break;\n case ONLY_FORWARD:\n if (currentController()->entry_count() == 2) {\n if (currentController()->CanGoForward()) {\n currentController()->GoForward();\n }\n } else {\n prepareAndShowHistory();\n }\n break;\n case BACK_FORWARD:\n prepareAndShowHistory();\n break;\n default:\n break;\n }\n }\n\n void tapAndHold()\n {\n switch(state_) {\n case ONLY_BACK:\n prepareAndShowHistory();\n break;\n case ONLY_FORWARD:\n if (currentController()->entry_count() == 2) {\n if (currentController()->CanGoForward()) {\n currentController()->GoForward();\n }\n } else {\n prepareAndShowHistory();\n }\n break;\n case BACK_FORWARD:\n prepareAndShowHistory();\n break;\n default:\n break;\n }\n updateStatus();\n }\n\n \/\/prepare c++ list model and emit signal to QML to show it\n void prepareAndShowHistory()\n {\n model_.clear();\n int count = currentController()->entry_count();\n int curr = -1;\n for(int i = count - 1; i >= 0; i--)\n {\n DLOG(INFO) << \"page index: ---\" << i << \"---\\n\";\n NavigationEntry* navEntry = currentController()->GetEntryAtIndex(i);\n \/\/ don't skip 'newtab' now, if yes, we do not only skip newtab here\n \/\/ but also skip count calculation for 'updateStatus'\n \/*\n if (navEntry->url().HostNoBrackets() == \"newtab\") {\n \/\/ skip 'newtab'\n continue;\n }*\/\n model_.appendEntry(currentController(), navEntry);\n curr++;\n if(currentController()->GetCurrentEntryIndex() == i) {\n model_.setCurrent(curr);\n }\n }\n model_.show();\n toolbar_->showHistory();\n }\n\nprivate:\n BrowserToolbarQt* toolbar_;\n Browser* browser_;\n HistoryStackModel model_;\n\n \/\/ current navigation state\n NaviState state_;\n \/\/ whether the backward\/forward button is active\n bool active_;\n};\n\nBackForwardButtonQt::BackForwardButtonQt(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)\n{\n impl_ = new BackForwardButtonQtImpl(toolbar, browser, window);\n}\n\nBackForwardButtonQt::~BackForwardButtonQt()\n{\n delete impl_;\n}\n\nvoid BackForwardButtonQt::tap()\n{\n impl_->tap();\n}\n\nvoid BackForwardButtonQt::tapAndHold()\n{\n impl_->tapAndHold();\n}\n\nvoid BackForwardButtonQt::updateStatus()\n{\n impl_->updateStatus();\n}\n\nvoid HistoryEntry::onThumbnailDataAvailable(HistoryService::Handle request_handle,\n scoped_refptr<RefCountedBytes> jpeg_data) \n{\n model_->beginReset();\n if (jpeg_data.get()) {\n DLOG(INFO) << \"get image id: \" << index_;\n std::vector<unsigned char> thumbnail_data;\n std::copy(jpeg_data->data.begin(), jpeg_data->data.end(),\n std::back_inserter(thumbnail_data));\n QImage image = QImage::fromData(thumbnail_data.data(), thumbnail_data.size());\n hiProvider_.addImage(QString::number(index_), image);\n }\n model_->endReset();\n}\n\nvoid HistoryStackModel::openPage(const int index)\n{\n back_forward_->openPage(entryList_[index]->entry());\n hide();\n}\n\n#include \"moc_back_forward_button_qt.cc\"\n<commit_msg>History: get thumbnails from TopSites<commit_after>\/*\n * Copyright (c) 2010, Intel Corporation. All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are \n * met:\n * \n * * Redistributions of source code must retain the above copyright \n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above \n * copyright notice, this list of conditions and the following disclaimer \n * in the documentation and\/or other materials provided with the \n * distribution.\n * * Neither the name of Intel Corporation nor the names of its \n * contributors may be used to endorse or promote products derived from \n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR \n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"chrome\/browser\/ui\/meegotouch\/back_forward_button_qt.h\"\n#include \"chrome\/browser\/ui\/meegotouch\/browser_window_qt.h\"\n#include \"chrome\/browser\/ui\/meegotouch\/browser_toolbar_qt.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/navigation_entry.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/registry_controlled_domain.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n\n#include <QGraphicsItem>\n#include <QGraphicsSceneMouseEvent>\n#include <QVector>\n#include <QList>\n#include <QTimer>\n#include <algorithm>\n#include <QGraphicsSceneResizeEvent>\n#include <QGraphicsWidget>\n#include <QEvent>\n#include <QDebug>\n\/\/#include <QTapAndHoldGesture>\n\n#include <QDeclarativeEngine>\n#include <QDeclarativeView>\n#include <QDeclarativeContext>\n#include <QDeclarativeItem>\n#include <QDeclarativeImageProvider>\n#include <QAbstractListModel>\n\n\/\/ Image provider, managing to provide image to QML\n\/\/ for history view\n\/\/ Due to qml limitation, the id of image is suffixed with\n\/\/ a static increaser, which forces using new image source\n\/\/ each time\nclass HistoryImageProvider : public QDeclarativeImageProvider \n{\npublic:\n HistoryImageProvider()\n : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)\n {}\n\n \/\/ clear all images in image hashmap\n void clear()\n {\n imageList_.clear();\n }\n\n \/\/ overrided function, inherited from QDeclarativeImageProvider\n virtual QImage requestImage(const QString& id,\n QSize* size,\n const QSize& requestedSize)\n {\n DLOG(INFO) << \"requesting image id: \" << id.toStdString();\n int finded = id.indexOf(\"_\");\n if (finded != -1) {\n QImage& image = imageList_[id.left(finded)];\n if (!image.isNull()) {\n \/\/QImage scaled = image.scaled(requestedSize);\n *size = image.size();\n return image;\n }\n }\n *size = QSize(0, 0);\n return QImage();\n }\n\n \/\/ add a new image\n void addImage(const QString& id, const QImage &image)\n {\n imageList_.insert(id, image);\n }\n\nprivate:\n QMap<QString, QImage> imageList_;\n};\n\nclass HistoryStackModel;\n\n\/\/ history entry to represent one history data\nclass HistoryEntry \n{\npublic:\n \n \/\/ constructor\n \/\/ @param index the index in history stack\n \/\/ @param hiProvider image provider for history stack\n \/\/ @param entry representation of navigation entry in browser\n \/\/ @param controller current navigation controller in browser\n \/\/ @param model history stack model\n HistoryEntry(const int index, \n HistoryImageProvider& hiProvider,\n NavigationEntry* entry,\n NavigationController* controller,\n HistoryStackModel* model)\n : index_(index), hiProvider_(hiProvider), entry_(entry), model_(model)\n {\n \/\/ get image\n getThumbnailData(controller);\n std::wstring title_str = UTF16ToWide(entry->title());\n title_ = QString::fromStdWString(title_str);\n }\n\n void imgURLGen() \n {\n static QString prefix(\"image:\/\/historystack\/\");\n imageSrc_ = prefix + QString::number(index_) + \"_\" + QString::number(reloadNumber_);\n }\n\n void getThumbnailData(NavigationController *controller);\n\n NavigationEntry* entry() { return entry_; }\n QString image() { return imageSrc_; }\n QString title() { return title_; }\n\n static void incReloadNumber() { reloadNumber_++; }\n static unsigned long reloadNumber() { return reloadNumber_; }\n\nprivate:\n \/\/ static increaser to generate unique image source \n static unsigned long reloadNumber_;\n\n int index_;\n HistoryImageProvider& hiProvider_;\n NavigationEntry* entry_;\n HistoryStackModel* model_;\n \/\/ image source\n QString imageSrc_;\n \/\/ history title\n QString title_;\n CancelableRequestConsumer consumer_;\n};\n\nunsigned long HistoryEntry::reloadNumber_ = 0;\n\n\/\/ represent list model used in QML to store history data\nclass HistoryStackModel: public QAbstractListModel\n{\n Q_OBJECT\n enum HistoryRole {\n IMAGE_ROLE = Qt::UserRole + 1,\n TITLE_ROLE\n };\n\npublic:\n HistoryStackModel(BackForwardButtonQtImpl* backForward)\n : back_forward_(backForward), returnedImages_(0)\n {\n QHash<int, QByteArray> roles;\n roles[IMAGE_ROLE] = \"thumbSrc\";\n roles[TITLE_ROLE] = \"title\";\n setRoleNames(roles);\n }\n\n ~HistoryStackModel()\n {\n clear();\n }\n\n \/\/ clear saved data\n void clear()\n {\n returnedImages_ = 0;\n beginResetModel();\n for(int i = 0; i < entryList_.count(); i++) {\n delete entryList_[i];\n }\n entryList_.clear();\n hiProvider_.clear();\n endResetModel();\n }\n\n int rowCount(const QModelIndex& parent = QModelIndex()) const\n {\n return entryList_.count();\n }\n\n QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const\n {\n DLOG(INFO) << \"read list model data: row = \" << index.row() << \", column = \" << index.column();\n if(index.row() < 0 || index.row() > entryList_.count())\n return QVariant();\n HistoryEntry* entry = entryList_[index.row()];\n switch(role) {\n case IMAGE_ROLE:\n return entry->image();\n case TITLE_ROLE:\n return entry->title();\n default:\n return QVariant();\n }\n }\n\n void appendEntry(NavigationController* controller, NavigationEntry *entry)\n {\n HistoryEntry* historyEntry \n = new HistoryEntry(entryList_.count(),\n hiProvider_,\n entry, \n controller,\n this);\n historyEntry->imgURLGen();\n beginInsertRows(QModelIndex(), rowCount(), rowCount());\n entryList_.push_back(historyEntry);\n endInsertRows();\n }\n\n \/\/ emit a showHistory signal to QML\n void show() { emit showHistory(); }\n\n \/\/ emit a hideHistory signal to QML\n void hide() { emit hideHistory(); }\n\n \/\/ emit a current selected(focused) history entry\n void setCurrent(int index) { emit current(index); }\n\n HistoryImageProvider* hiProvider() { return &hiProvider_; }\n\nQ_SIGNALS:\n \/\/ three signals used to notify QML\n void showHistory();\n void hideHistory();\n void current(int index);\n\npublic Q_SLOTS:\n \/\/ open specific page, called by QML element\n \/\/ It's called by QML element when user clicks one history entry in QML view\n void openPage(const int index);\n\nprivate:\n BackForwardButtonQtImpl* back_forward_;\n \/\/ list to hold entries\n QList<HistoryEntry*> entryList_;\n HistoryImageProvider hiProvider_;\n \/\/ count of returned images from browser\n int returnedImages_;\n};\n\nclass BackForwardButtonQtImpl\n{\npublic:\n enum NaviState {\n ONLY_BACK = 0,\n ONLY_FORWARD,\n BACK_FORWARD\n };\n\n \/\/ constructor\n BackForwardButtonQtImpl(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)\n :toolbar_(toolbar), browser_(browser), model_(this), \n state_(ONLY_BACK), active_(false)\n {\n QDeclarativeView* view = window->DeclarativeView();\n QDeclarativeContext *context = view->rootContext();\n context->setContextProperty(\"historyStackModel\", &model_);\n context->engine()->addImageProvider(QLatin1String(\"historystack\"), model_.hiProvider());\n }\n\n NavigationController* currentController()\n {\n return &(browser_->GetSelectedTabContents()->controller());\n }\n\n void openPage(NavigationEntry *entry)\n {\n currentController()->GoToIndex(currentController()->GetIndexOfEntry(entry));\n updateStatus();\n }\n\n void updateStatus()\n {\n if(currentController()->GetCurrentEntryIndex() == currentController()->entry_count() - 1)\n {\n state_ = ONLY_BACK;\n if (currentController()->entry_count() > 1) {\n active_ = true;\n } else {\n active_ = false;\n }\n } else if (currentController()->GetCurrentEntryIndex() == 0\n && currentController()->entry_count() > 0) {\n state_ = ONLY_FORWARD;\n } else if (currentController()->CanGoBack() && currentController()->CanGoForward()) {\n state_ = BACK_FORWARD;\n } else {\n state_ = ONLY_BACK;\n active_ = false;\n }\n \/\/ update button status in qml\n updateButton();\n DLOG(INFO) << \"In C++, updateStatus is invoked\\n\";\n }\n\n \/\/ update back-forward button icon\n void updateButton() { toolbar_->updateBfButton((int)state_, active_); }\n\n void tap()\n {\n DLOG(INFO) << \"In C++, tap is invoked\";\n switch(state_) {\n case ONLY_BACK:\n if (currentController()->CanGoBack()) {\n currentController()->GoBack();\n }\n break;\n case ONLY_FORWARD:\n if (currentController()->entry_count() == 2) {\n if (currentController()->CanGoForward()) {\n currentController()->GoForward();\n }\n } else {\n prepareAndShowHistory();\n }\n break;\n case BACK_FORWARD:\n prepareAndShowHistory();\n break;\n default:\n break;\n }\n }\n\n void tapAndHold()\n {\n switch(state_) {\n case ONLY_BACK:\n prepareAndShowHistory();\n break;\n case ONLY_FORWARD:\n if (currentController()->entry_count() == 2) {\n if (currentController()->CanGoForward()) {\n currentController()->GoForward();\n }\n } else {\n prepareAndShowHistory();\n }\n break;\n case BACK_FORWARD:\n prepareAndShowHistory();\n break;\n default:\n break;\n }\n updateStatus();\n }\n\n \/\/prepare c++ list model and emit signal to QML to show it\n void prepareAndShowHistory()\n {\n model_.clear();\n int count = currentController()->entry_count();\n int curr = -1;\n HistoryEntry::incReloadNumber();\n for(int i = count - 1; i >= 0; i--)\n {\n DLOG(INFO) << \"page index: ---\" << i << \"---\\n\";\n NavigationEntry* navEntry = currentController()->GetEntryAtIndex(i);\n \/\/ don't skip 'newtab' now, if yes, we do not only skip newtab here\n \/\/ but also skip count calculation for 'updateStatus'\n \/*\n if (navEntry->url().HostNoBrackets() == \"newtab\") {\n \/\/ skip 'newtab'\n continue;\n }*\/\n model_.appendEntry(currentController(), navEntry);\n curr++;\n if(currentController()->GetCurrentEntryIndex() == i) {\n model_.setCurrent(curr);\n }\n }\n model_.show();\n toolbar_->showHistory();\n }\n\nprivate:\n BrowserToolbarQt* toolbar_;\n Browser* browser_;\n HistoryStackModel model_;\n\n \/\/ current navigation state\n NaviState state_;\n \/\/ whether the backward\/forward button is active\n bool active_;\n};\n\nBackForwardButtonQt::BackForwardButtonQt(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)\n{\n impl_ = new BackForwardButtonQtImpl(toolbar, browser, window);\n}\n\nBackForwardButtonQt::~BackForwardButtonQt()\n{\n delete impl_;\n}\n\nvoid BackForwardButtonQt::tap()\n{\n impl_->tap();\n}\n\nvoid BackForwardButtonQt::tapAndHold()\n{\n impl_->tapAndHold();\n}\n\nvoid BackForwardButtonQt::updateStatus()\n{\n impl_->updateStatus();\n}\n\nvoid HistoryEntry::getThumbnailData(NavigationController *controller)\n{\n history::TopSites* ts = controller->profile()->GetTopSites();\n if (ts) {\n scoped_refptr<RefCountedBytes> thumbnail_data;\n ts->GetPageThumbnail(entry_->url(), &thumbnail_data);\n if (thumbnail_data.get()) {\n std::vector <unsigned char> jpeg;\n std::copy(thumbnail_data->data.begin(), \n thumbnail_data->data.end(),\n std::back_inserter(jpeg));\n QImage image = QImage::fromData(jpeg.data(), jpeg.size());\n DLOG(INFO) << \"image size ===== \" << jpeg.size();\n hiProvider_.addImage(QString::number(index_), image);\n }\n }\n}\n\nvoid HistoryStackModel::openPage(const int index)\n{\n back_forward_->openPage(entryList_[index]->entry());\n hide();\n}\n\n#include \"moc_back_forward_button_qt.cc\"\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: asiancfg.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:16:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_ASIANCFG_HXX\n#define _SVX_ASIANCFG_HXX\n\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/Sequence.h>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\nnamespace com{namespace sun{namespace star{\nnamespace lang{\n struct Locale;\n}}}}\n\/\/-----------------------------------------------------------------------------\nstruct SvxAsianConfig_Impl;\nclass SVX_DLLPUBLIC SvxAsianConfig : public utl::ConfigItem\n{\n SvxAsianConfig_Impl* pImpl;\n\npublic:\n SvxAsianConfig(sal_Bool bEnableNotify = sal_True);\n virtual ~SvxAsianConfig();\n\n void Load();\n virtual void Commit();\n virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);\n\n sal_Bool IsKerningWesternTextOnly() const;\n void SetKerningWesternTextOnly(sal_Bool bSet);\n\n sal_Int16 GetCharDistanceCompression() const;\n void SetCharDistanceCompression(sal_Int16 nSet);\n\n com::sun::star::uno::Sequence<com::sun::star::lang::Locale>\n GetStartEndCharLocales();\n\n sal_Bool GetStartEndChars( const com::sun::star::lang::Locale& rLocale,\n rtl::OUString& rStartChars,\n rtl::OUString& rEndChars );\n void SetStartEndChars( const com::sun::star::lang::Locale& rLocale,\n const rtl::OUString* pStartChars,\n const rtl::OUString* pEndChars );\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.1256); FILE MERGED 2008\/04\/01 15:49:10 thb 1.3.1256.3: #i85898# Stripping all external header guards 2008\/04\/01 12:46:17 thb 1.3.1256.2: #i85898# Stripping all external header guards 2008\/03\/31 14:17:53 rt 1.3.1256.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: asiancfg.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_ASIANCFG_HXX\n#define _SVX_ASIANCFG_HXX\n\n#include <unotools\/configitem.hxx>\n#include <com\/sun\/star\/uno\/Sequence.h>\n#include \"svx\/svxdllapi.h\"\n\nnamespace com{namespace sun{namespace star{\nnamespace lang{\n struct Locale;\n}}}}\n\/\/-----------------------------------------------------------------------------\nstruct SvxAsianConfig_Impl;\nclass SVX_DLLPUBLIC SvxAsianConfig : public utl::ConfigItem\n{\n SvxAsianConfig_Impl* pImpl;\n\npublic:\n SvxAsianConfig(sal_Bool bEnableNotify = sal_True);\n virtual ~SvxAsianConfig();\n\n void Load();\n virtual void Commit();\n virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);\n\n sal_Bool IsKerningWesternTextOnly() const;\n void SetKerningWesternTextOnly(sal_Bool bSet);\n\n sal_Int16 GetCharDistanceCompression() const;\n void SetCharDistanceCompression(sal_Int16 nSet);\n\n com::sun::star::uno::Sequence<com::sun::star::lang::Locale>\n GetStartEndCharLocales();\n\n sal_Bool GetStartEndChars( const com::sun::star::lang::Locale& rLocale,\n rtl::OUString& rStartChars,\n rtl::OUString& rEndChars );\n void SetStartEndChars( const com::sun::star::lang::Locale& rLocale,\n const rtl::OUString* pStartChars,\n const rtl::OUString* pEndChars );\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <stdio.h>\n#include <locale>\n#include <string>\n#include <vector>\n\n#include \"base\/at_exit.h\"\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_local.h\"\n#include \"chrome\/test\/chromedriver\/logging.h\"\n#include \"chrome\/test\/chromedriver\/net\/port_server.h\"\n#include \"chrome\/test\/chromedriver\/server\/http_handler.h\"\n#include \"chrome\/test\/chromedriver\/version.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/server\/http_server.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/server\/http_server_response_info.h\"\n#include \"net\/socket\/tcp_listen_socket.h\"\n\nnamespace {\n\ntypedef base::Callback<\n void(const net::HttpServerRequestInfo&, const HttpResponseSenderFunc&)>\n HttpRequestHandlerFunc;\n\nclass HttpServer : public net::HttpServer::Delegate {\n public:\n explicit HttpServer(const HttpRequestHandlerFunc& handle_request_func)\n : handle_request_func_(handle_request_func),\n weak_factory_(this) {}\n\n virtual ~HttpServer() {}\n\n bool Start(int port) {\n server_ = new net::HttpServer(\n net::TCPListenSocketFactory(\"0.0.0.0\", port), this);\n net::IPEndPoint address;\n return server_->GetLocalAddress(&address) == net::OK;\n }\n\n \/\/ Overridden from net::HttpServer::Delegate:\n virtual void OnHttpRequest(int connection_id,\n const net::HttpServerRequestInfo& info) OVERRIDE {\n handle_request_func_.Run(\n info,\n base::Bind(&HttpServer::OnResponse,\n weak_factory_.GetWeakPtr(),\n connection_id));\n }\n virtual void OnWebSocketRequest(\n int connection_id,\n const net::HttpServerRequestInfo& info) OVERRIDE {}\n virtual void OnWebSocketMessage(int connection_id,\n const std::string& data) OVERRIDE {}\n virtual void OnClose(int connection_id) OVERRIDE {}\n\n private:\n void OnResponse(int connection_id,\n scoped_ptr<net::HttpServerResponseInfo> response) {\n \/\/ Don't support keep-alive, since there's no way to detect if the\n \/\/ client is HTTP\/1.0. In such cases, the client may hang waiting for\n \/\/ the connection to close (e.g., python 2.7 urllib).\n response->AddHeader(\"Connection\", \"close\");\n server_->SendResponse(connection_id, *response);\n server_->Close(connection_id);\n }\n\n HttpRequestHandlerFunc handle_request_func_;\n scoped_refptr<net::HttpServer> server_;\n base::WeakPtrFactory<HttpServer> weak_factory_; \/\/ Should be last.\n};\n\nvoid SendResponseOnCmdThread(\n const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,\n const HttpResponseSenderFunc& send_response_on_io_func,\n scoped_ptr<net::HttpServerResponseInfo> response) {\n io_task_runner->PostTask(\n FROM_HERE, base::Bind(send_response_on_io_func, base::Passed(&response)));\n}\n\nvoid HandleRequestOnCmdThread(\n HttpHandler* handler,\n const net::HttpServerRequestInfo& request,\n const HttpResponseSenderFunc& send_response_func) {\n handler->Handle(request, send_response_func);\n}\n\nvoid HandleRequestOnIOThread(\n const scoped_refptr<base::SingleThreadTaskRunner>& cmd_task_runner,\n const HttpRequestHandlerFunc& handle_request_on_cmd_func,\n const net::HttpServerRequestInfo& request,\n const HttpResponseSenderFunc& send_response_func) {\n cmd_task_runner->PostTask(\n FROM_HERE,\n base::Bind(handle_request_on_cmd_func,\n request,\n base::Bind(&SendResponseOnCmdThread,\n base::MessageLoopProxy::current(),\n send_response_func)));\n}\n\nbase::LazyInstance<base::ThreadLocalPointer<HttpServer> >\n lazy_tls_server = LAZY_INSTANCE_INITIALIZER;\n\nvoid StopServerOnIOThread() {\n \/\/ Note, |server| may be NULL.\n HttpServer* server = lazy_tls_server.Pointer()->Get();\n lazy_tls_server.Pointer()->Set(NULL);\n delete server;\n}\n\nvoid StartServerOnIOThread(int port,\n const HttpRequestHandlerFunc& handle_request_func) {\n scoped_ptr<HttpServer> temp_server(new HttpServer(handle_request_func));\n if (!temp_server->Start(port)) {\n printf(\"Port not available. Exiting...\\n\");\n exit(1);\n }\n lazy_tls_server.Pointer()->Set(temp_server.release());\n}\n\nvoid RunServer(int port,\n const std::string& url_base,\n int adb_port,\n scoped_ptr<PortServer> port_server) {\n base::Thread io_thread(\"ChromeDriver IO\");\n CHECK(io_thread.StartWithOptions(\n base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));\n\n base::MessageLoop cmd_loop;\n base::RunLoop cmd_run_loop;\n HttpHandler handler(cmd_run_loop.QuitClosure(),\n io_thread.message_loop_proxy(),\n url_base,\n adb_port,\n port_server.Pass());\n HttpRequestHandlerFunc handle_request_func =\n base::Bind(&HandleRequestOnCmdThread, &handler);\n\n io_thread.message_loop()\n ->PostTask(FROM_HERE,\n base::Bind(&StartServerOnIOThread,\n port,\n base::Bind(&HandleRequestOnIOThread,\n cmd_loop.message_loop_proxy(),\n handle_request_func)));\n \/\/ Run the command loop. This loop is quit after the response for a shutdown\n \/\/ request is posted to the IO loop. After the command loop quits, a task\n \/\/ is posted to the IO loop to stop the server. Lastly, the IO thread is\n \/\/ destroyed, which waits until all pending tasks have been completed.\n \/\/ This assumes the response is sent synchronously as part of the IO task.\n cmd_run_loop.Run();\n io_thread.message_loop()\n ->PostTask(FROM_HERE, base::Bind(&StopServerOnIOThread));\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n\n base::AtExitManager at_exit;\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n\n#if defined(OS_LINUX)\n \/\/ Select the locale from the environment by passing an empty string instead\n \/\/ of the default \"C\" locale. This is particularly needed for the keycode\n \/\/ conversion code to work.\n std::setlocale(LC_ALL, \"\");\n#endif\n\n \/\/ Parse command line flags.\n int port = 9515;\n int adb_port = 5037;\n std::string url_base;\n scoped_ptr<PortServer> port_server;\n if (cmd_line->HasSwitch(\"h\") || cmd_line->HasSwitch(\"help\")) {\n std::string options;\n const char* kOptionAndDescriptions[] = {\n \"port=PORT\", \"port to listen on\",\n \"adb-port=PORT\", \"adb server port\",\n \"log-path=FILE\", \"write server log to file instead of stderr, \"\n \"increases log level to INFO\",\n \"verbose\", \"log verbosely\",\n \"silent\", \"log nothing\",\n \"url-base\", \"base URL path prefix for commands, e.g. wd\/url\",\n \"port-server\", \"address of server to contact for reserving a port\",\n };\n for (size_t i = 0; i < arraysize(kOptionAndDescriptions) - 1; i += 2) {\n options += base::StringPrintf(\n \" --%-30s%s\\n\",\n kOptionAndDescriptions[i], kOptionAndDescriptions[i + 1]);\n }\n printf(\"Usage: %s [OPTIONS]\\n\\nOptions\\n%s\", argv[0], options.c_str());\n return 0;\n }\n if (cmd_line->HasSwitch(\"port\")) {\n if (!base::StringToInt(cmd_line->GetSwitchValueASCII(\"port\"), &port)) {\n printf(\"Invalid port. Exiting...\\n\");\n return 1;\n }\n }\n if (cmd_line->HasSwitch(\"adb-port\")) {\n if (!base::StringToInt(cmd_line->GetSwitchValueASCII(\"adb-port\"),\n &adb_port)) {\n printf(\"Invalid adb-port. Exiting...\\n\");\n return 1;\n }\n }\n if (cmd_line->HasSwitch(\"port-server\")) {\n#if defined(OS_LINUX)\n std::string address = cmd_line->GetSwitchValueASCII(\"port-server\");\n if (address.empty() || address[0] != '@') {\n printf(\"Invalid port-server. Exiting...\\n\");\n return 1;\n }\n std::string path;\n \/\/ First character of path is \\0 to use Linux's abstract namespace.\n path.push_back(0);\n path += address.substr(1);\n port_server.reset(new PortServer(path));\n#else\n printf(\"Warning: port-server not implemented for this platform.\\n\");\n#endif\n }\n if (cmd_line->HasSwitch(\"url-base\"))\n url_base = cmd_line->GetSwitchValueASCII(\"url-base\");\n if (url_base.empty() || url_base[0] != '\/')\n url_base = \"\/\" + url_base;\n if (url_base[url_base.length() - 1] != '\/')\n url_base = url_base + \"\/\";\n if (!cmd_line->HasSwitch(\"silent\")) {\n printf(\n \"Starting ChromeDriver (v%s) on port %d\\n\", kChromeDriverVersion, port);\n fflush(stdout);\n }\n\n if (!InitLogging()) {\n printf(\"Unable to initialize logging. Exiting...\\n\");\n return 1;\n }\n RunServer(port, url_base, adb_port, port_server.Pass());\n return 0;\n}\n<commit_msg>Add a switch to print the version and exit<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <stdio.h>\n#include <locale>\n#include <string>\n#include <vector>\n\n#include \"base\/at_exit.h\"\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_local.h\"\n#include \"chrome\/test\/chromedriver\/logging.h\"\n#include \"chrome\/test\/chromedriver\/net\/port_server.h\"\n#include \"chrome\/test\/chromedriver\/server\/http_handler.h\"\n#include \"chrome\/test\/chromedriver\/version.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/server\/http_server.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/server\/http_server_response_info.h\"\n#include \"net\/socket\/tcp_listen_socket.h\"\n\nnamespace {\n\ntypedef base::Callback<\n void(const net::HttpServerRequestInfo&, const HttpResponseSenderFunc&)>\n HttpRequestHandlerFunc;\n\nclass HttpServer : public net::HttpServer::Delegate {\n public:\n explicit HttpServer(const HttpRequestHandlerFunc& handle_request_func)\n : handle_request_func_(handle_request_func),\n weak_factory_(this) {}\n\n virtual ~HttpServer() {}\n\n bool Start(int port) {\n server_ = new net::HttpServer(\n net::TCPListenSocketFactory(\"0.0.0.0\", port), this);\n net::IPEndPoint address;\n return server_->GetLocalAddress(&address) == net::OK;\n }\n\n \/\/ Overridden from net::HttpServer::Delegate:\n virtual void OnHttpRequest(int connection_id,\n const net::HttpServerRequestInfo& info) OVERRIDE {\n handle_request_func_.Run(\n info,\n base::Bind(&HttpServer::OnResponse,\n weak_factory_.GetWeakPtr(),\n connection_id));\n }\n virtual void OnWebSocketRequest(\n int connection_id,\n const net::HttpServerRequestInfo& info) OVERRIDE {}\n virtual void OnWebSocketMessage(int connection_id,\n const std::string& data) OVERRIDE {}\n virtual void OnClose(int connection_id) OVERRIDE {}\n\n private:\n void OnResponse(int connection_id,\n scoped_ptr<net::HttpServerResponseInfo> response) {\n \/\/ Don't support keep-alive, since there's no way to detect if the\n \/\/ client is HTTP\/1.0. In such cases, the client may hang waiting for\n \/\/ the connection to close (e.g., python 2.7 urllib).\n response->AddHeader(\"Connection\", \"close\");\n server_->SendResponse(connection_id, *response);\n server_->Close(connection_id);\n }\n\n HttpRequestHandlerFunc handle_request_func_;\n scoped_refptr<net::HttpServer> server_;\n base::WeakPtrFactory<HttpServer> weak_factory_; \/\/ Should be last.\n};\n\nvoid SendResponseOnCmdThread(\n const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,\n const HttpResponseSenderFunc& send_response_on_io_func,\n scoped_ptr<net::HttpServerResponseInfo> response) {\n io_task_runner->PostTask(\n FROM_HERE, base::Bind(send_response_on_io_func, base::Passed(&response)));\n}\n\nvoid HandleRequestOnCmdThread(\n HttpHandler* handler,\n const net::HttpServerRequestInfo& request,\n const HttpResponseSenderFunc& send_response_func) {\n handler->Handle(request, send_response_func);\n}\n\nvoid HandleRequestOnIOThread(\n const scoped_refptr<base::SingleThreadTaskRunner>& cmd_task_runner,\n const HttpRequestHandlerFunc& handle_request_on_cmd_func,\n const net::HttpServerRequestInfo& request,\n const HttpResponseSenderFunc& send_response_func) {\n cmd_task_runner->PostTask(\n FROM_HERE,\n base::Bind(handle_request_on_cmd_func,\n request,\n base::Bind(&SendResponseOnCmdThread,\n base::MessageLoopProxy::current(),\n send_response_func)));\n}\n\nbase::LazyInstance<base::ThreadLocalPointer<HttpServer> >\n lazy_tls_server = LAZY_INSTANCE_INITIALIZER;\n\nvoid StopServerOnIOThread() {\n \/\/ Note, |server| may be NULL.\n HttpServer* server = lazy_tls_server.Pointer()->Get();\n lazy_tls_server.Pointer()->Set(NULL);\n delete server;\n}\n\nvoid StartServerOnIOThread(int port,\n const HttpRequestHandlerFunc& handle_request_func) {\n scoped_ptr<HttpServer> temp_server(new HttpServer(handle_request_func));\n if (!temp_server->Start(port)) {\n printf(\"Port not available. Exiting...\\n\");\n exit(1);\n }\n lazy_tls_server.Pointer()->Set(temp_server.release());\n}\n\nvoid RunServer(int port,\n const std::string& url_base,\n int adb_port,\n scoped_ptr<PortServer> port_server) {\n base::Thread io_thread(\"ChromeDriver IO\");\n CHECK(io_thread.StartWithOptions(\n base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));\n\n base::MessageLoop cmd_loop;\n base::RunLoop cmd_run_loop;\n HttpHandler handler(cmd_run_loop.QuitClosure(),\n io_thread.message_loop_proxy(),\n url_base,\n adb_port,\n port_server.Pass());\n HttpRequestHandlerFunc handle_request_func =\n base::Bind(&HandleRequestOnCmdThread, &handler);\n\n io_thread.message_loop()\n ->PostTask(FROM_HERE,\n base::Bind(&StartServerOnIOThread,\n port,\n base::Bind(&HandleRequestOnIOThread,\n cmd_loop.message_loop_proxy(),\n handle_request_func)));\n \/\/ Run the command loop. This loop is quit after the response for a shutdown\n \/\/ request is posted to the IO loop. After the command loop quits, a task\n \/\/ is posted to the IO loop to stop the server. Lastly, the IO thread is\n \/\/ destroyed, which waits until all pending tasks have been completed.\n \/\/ This assumes the response is sent synchronously as part of the IO task.\n cmd_run_loop.Run();\n io_thread.message_loop()\n ->PostTask(FROM_HERE, base::Bind(&StopServerOnIOThread));\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n CommandLine::Init(argc, argv);\n\n base::AtExitManager at_exit;\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n\n#if defined(OS_LINUX)\n \/\/ Select the locale from the environment by passing an empty string instead\n \/\/ of the default \"C\" locale. This is particularly needed for the keycode\n \/\/ conversion code to work.\n std::setlocale(LC_ALL, \"\");\n#endif\n\n \/\/ Parse command line flags.\n int port = 9515;\n int adb_port = 5037;\n std::string url_base;\n scoped_ptr<PortServer> port_server;\n if (cmd_line->HasSwitch(\"h\") || cmd_line->HasSwitch(\"help\")) {\n std::string options;\n const char* kOptionAndDescriptions[] = {\n \"port=PORT\", \"port to listen on\",\n \"adb-port=PORT\", \"adb server port\",\n \"log-path=FILE\", \"write server log to file instead of stderr, \"\n \"increases log level to INFO\",\n \"verbose\", \"log verbosely\",\n \"version\", \"print the version number and exit\",\n \"silent\", \"log nothing\",\n \"url-base\", \"base URL path prefix for commands, e.g. wd\/url\",\n \"port-server\", \"address of server to contact for reserving a port\",\n };\n for (size_t i = 0; i < arraysize(kOptionAndDescriptions) - 1; i += 2) {\n options += base::StringPrintf(\n \" --%-30s%s\\n\",\n kOptionAndDescriptions[i], kOptionAndDescriptions[i + 1]);\n }\n printf(\"Usage: %s [OPTIONS]\\n\\nOptions\\n%s\", argv[0], options.c_str());\n return 0;\n }\n if (cmd_line->HasSwitch(\"v\") || cmd_line->HasSwitch(\"version\")) {\n printf(\"ChromeDriver %s\\n\", kChromeDriverVersion);\n return 0;\n }\n if (cmd_line->HasSwitch(\"port\")) {\n if (!base::StringToInt(cmd_line->GetSwitchValueASCII(\"port\"), &port)) {\n printf(\"Invalid port. Exiting...\\n\");\n return 1;\n }\n }\n if (cmd_line->HasSwitch(\"adb-port\")) {\n if (!base::StringToInt(cmd_line->GetSwitchValueASCII(\"adb-port\"),\n &adb_port)) {\n printf(\"Invalid adb-port. Exiting...\\n\");\n return 1;\n }\n }\n if (cmd_line->HasSwitch(\"port-server\")) {\n#if defined(OS_LINUX)\n std::string address = cmd_line->GetSwitchValueASCII(\"port-server\");\n if (address.empty() || address[0] != '@') {\n printf(\"Invalid port-server. Exiting...\\n\");\n return 1;\n }\n std::string path;\n \/\/ First character of path is \\0 to use Linux's abstract namespace.\n path.push_back(0);\n path += address.substr(1);\n port_server.reset(new PortServer(path));\n#else\n printf(\"Warning: port-server not implemented for this platform.\\n\");\n#endif\n }\n if (cmd_line->HasSwitch(\"url-base\"))\n url_base = cmd_line->GetSwitchValueASCII(\"url-base\");\n if (url_base.empty() || url_base[0] != '\/')\n url_base = \"\/\" + url_base;\n if (url_base[url_base.length() - 1] != '\/')\n url_base = url_base + \"\/\";\n if (!cmd_line->HasSwitch(\"silent\")) {\n printf(\n \"Starting ChromeDriver (v%s) on port %d\\n\", kChromeDriverVersion, port);\n fflush(stdout);\n }\n\n if (!InitLogging()) {\n printf(\"Unable to initialize logging. Exiting...\\n\");\n return 1;\n }\n RunServer(port, url_base, adb_port, port_server.Pass());\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pfiledlg.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:17:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_PFILEDLG_HXX\n#define _SVX_PFILEDLG_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/*************************************************************************\n|*\n|* Filedialog to insert Plugin-Fileformats\n|*\n\\************************************************************************\/\n\nclass SVX_DLLPUBLIC SvxPluginFileDlg\n{\nprivate:\n sfx2::FileDialogHelper maFileDlg;\n\npublic:\n \/\/ with nKind = SID_INSERT_SOUND or\n \/\/ nKind = SID_INSERT_VIDEO\n SvxPluginFileDlg (Window *pParent, USHORT nKind );\n ~SvxPluginFileDlg ();\n\n ErrCode Execute();\n String GetPath() const;\n\n static BOOL IsAvailable (USHORT nKind);\n\n \/\/ setting HelpId and\/or context of FileDialogHelper\n void SetDialogHelpId( const sal_Int32 nHelpId );\n void SetContext( sfx2::FileDialogHelper::Context eNewContext );\n};\n\n#endif \/\/ _SVX_PFILEDLG_HXX\n\n\n<commit_msg>INTEGRATION: CWS sb59 (1.5.486); FILE MERGED 2006\/08\/18 12:02:42 sb 1.5.486.1: #i67487# Made code warning-free (wntmsci10).<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pfiledlg.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 11:47:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_PFILEDLG_HXX\n#define _SVX_PFILEDLG_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/*************************************************************************\n|*\n|* Filedialog to insert Plugin-Fileformats\n|*\n\\************************************************************************\/\n\nclass SVX_DLLPUBLIC SvxPluginFileDlg\n{\nprivate:\n sfx2::FileDialogHelper maFileDlg;\n\npublic:\n \/\/ with nKind = SID_INSERT_SOUND or\n \/\/ nKind = SID_INSERT_VIDEO\n SvxPluginFileDlg (Window *pParent, USHORT nKind );\n ~SvxPluginFileDlg ();\n\n ErrCode Execute();\n String GetPath() const;\n\n static bool IsAvailable (USHORT nKind);\n\n \/\/ setting HelpId and\/or context of FileDialogHelper\n void SetDialogHelpId( const sal_Int32 nHelpId );\n void SetContext( sfx2::FileDialogHelper::Context eNewContext );\n};\n\n#endif \/\/ _SVX_PFILEDLG_HXX\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: svdshort.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-07-12 14:28:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#error svdshort wird nicht mehr verwendet!\n\n#ifndef _SVDSHORT_HXX\n#define _SVDSHORT_HXX\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef Weg_Mit_Den_Doofen_Abkuerzungen\n \/\/ Statistik - Stand 02-03-1995\n \/\/ Haeufigkeit Ersparnis\n#define SdrObjSurrogate SdrSU\n#define SdrHelpLineKind SdrFLK \/* HL ist schon besetzt *\/\n#define SdrHelpLineList SdrFLL \/* HL ist schon besetzt *\/\n#define SdrHelpLine SdrFL \/* HL ist schon besetzt *\/\n\/\/#define SdrMasterPageDescriptorList SdrMPL\n\/\/#define SdrMasterPageDescriptor SdrMP\n#define SdrObjTransformInfoRec SdrTI\n#define SdrDragCrook SdrDC\n#define SdrDragMirror SdrDI\n#define SdrDragMovHdl SdrDH\n#define SdrDragResize SdrDZ\n#define SdrDragRotate SdrDR\n#define SdrDragShear SdrDE\n#define SdrDragMove SdrDM\n#define SdrCreateCmd SdrCC\n#define SdrUndoAttrObj SdrAU\n#define SdrObjKind SdrOK\n#define SdrUndoGroup SdrUG\n#define SdrUndoAction SdrUA\n#define SdrAttrObj SdrAO\n#define SdrGrafObj SdrGO\n#define SdrMarkList SdrML\n#define SdrHdlList SdrHL\n#define SdrLayerAdmin SdrLA\n\/\/#define SdrObjEditRec SdrER\n#define SdrObjIOHeader SdrOH\n#define SdrObjUserCall SdrUC\n#define SdrObjUnknown SdrUO\n#define SdrExchangeView SdrXV\n#define SdrCreateView SdrCV\n#define SdrOle2Obj SdrOO\n#define SdrObjGeoData SdrGD\n#define SdrDragView SdrDV\n#define SdrSnapView SdrSV\n#define SdrObjList SdrOL\n#define SdrEdgeObj SdrEO\n#define SdrCircObj SdrCO\n#define SdrObjGroup SdrOG\n#define SdrPage SdrPg\n#define SdrObjEditView SdrOV\n#define SdrModel SdrMD\n#define ExtOutputDevice SdrXO\n#define SdrEditView SdrEV\n#define SdrPaintView SdrNV\n#define SdrPolyObj SdrPO\n#define SdrRectObj SdrRO\n#define SdrTextObj SdrTO\n#define SdrMarkView SdrMV\n#define SdrPathObj SdrBO\n#define SdrPageView SdrPV\n#define SdrDragStat SdrDS\n#define SdrVirtObj SdrVO\n#define SdrObject SdrO\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SVDSHORT_HXX\n\n<commit_msg>INTEGRATION: CWS aw019 (1.2.138); FILE MERGED 2004\/10\/06 16:17:50 aw 1.2.138.2: #i34831# 2004\/09\/28 15:52:17 aw 1.2.138.1: #i11190#<commit_after>\/*************************************************************************\n *\n * $RCSfile: svdshort.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-03 10:23:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#error svdshort wird nicht mehr verwendet!\n\n#ifndef _SVDSHORT_HXX\n#define _SVDSHORT_HXX\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef Weg_Mit_Den_Doofen_Abkuerzungen\n \/\/ Statistik - Stand 02-03-1995\n \/\/ Haeufigkeit Ersparnis\n\/\/BFS01#define SdrObjSurrogate SdrSU\n#define SdrHelpLineKind SdrFLK \/* HL ist schon besetzt *\/\n#define SdrHelpLineList SdrFLL \/* HL ist schon besetzt *\/\n#define SdrHelpLine SdrFL \/* HL ist schon besetzt *\/\n\/\/#define SdrMasterPageDescriptorList SdrMPL\n\/\/#define SdrMasterPageDescriptor SdrMP\n#define SdrObjTransformInfoRec SdrTI\n#define SdrDragCrook SdrDC\n#define SdrDragMirror SdrDI\n#define SdrDragMovHdl SdrDH\n#define SdrDragResize SdrDZ\n#define SdrDragRotate SdrDR\n#define SdrDragShear SdrDE\n#define SdrDragMove SdrDM\n#define SdrCreateCmd SdrCC\n#define SdrUndoAttrObj SdrAU\n#define SdrObjKind SdrOK\n#define SdrUndoGroup SdrUG\n#define SdrUndoAction SdrUA\n#define SdrAttrObj SdrAO\n#define SdrGrafObj SdrGO\n#define SdrMarkList SdrML\n#define SdrHdlList SdrHL\n#define SdrLayerAdmin SdrLA\n\/\/#define SdrObjEditRec SdrER\n\/\/BFS01#define SdrObjIOHeader SdrOH\n#define SdrObjUserCall SdrUC\n#define SdrObjUnknown SdrUO\n#define SdrExchangeView SdrXV\n#define SdrCreateView SdrCV\n#define SdrOle2Obj SdrOO\n#define SdrObjGeoData SdrGD\n#define SdrDragView SdrDV\n#define SdrSnapView SdrSV\n#define SdrObjList SdrOL\n#define SdrEdgeObj SdrEO\n#define SdrCircObj SdrCO\n#define SdrObjGroup SdrOG\n#define SdrPage SdrPg\n#define SdrObjEditView SdrOV\n#define SdrModel SdrMD\n#define XOutputDevice SdrXO\n#define SdrEditView SdrEV\n#define SdrPaintView SdrNV\n#define SdrPolyObj SdrPO\n#define SdrRectObj SdrRO\n#define SdrTextObj SdrTO\n#define SdrMarkView SdrMV\n#define SdrPathObj SdrBO\n#define SdrPageView SdrPV\n#define SdrDragStat SdrDS\n#define SdrVirtObj SdrVO\n#define SdrObject SdrO\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SVDSHORT_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: xmleohlp.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLEOHLP_HXX\n#define _XMLEOHLP_HXX\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n#include <sot\/storage.hxx>\n#include <map>\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_\n#include <com\/sun\/star\/document\/XEmbeddedObjectResolver.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/\/ -----------------------------\n\/\/ - SvXMLEmbeddedObjectHelper -\n\/\/ -----------------------------\n\nenum SvXMLEmbeddedObjectHelperMode\n{\n EMBEDDEDOBJECTHELPER_MODE_READ = 0,\n EMBEDDEDOBJECTHELPER_MODE_WRITE = 1\n};\n\n\/\/ -----------------------------\n\/\/ - SvXMLEmbeddedObjectHelper -\n\/\/ -----------------------------\n\nclass SfxObjectShell;\nclass SvGlobalName;\nstruct OUStringLess;\nclass OutputStorageWrapper_Impl;\n\nclass SVX_DLLPUBLIC SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2<\n ::com::sun::star::document::XEmbeddedObjectResolver,\n ::com::sun::star::container::XNameAccess >\n{\n typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*,\n OUStringLess > SvXMLEmbeddedObjectHelper_Impl;\nprivate:\n\n ::osl::Mutex maMutex;\n\n const ::rtl::OUString maReplacementGraphicsContainerStorageName;\n const ::rtl::OUString maReplacementGraphicsContainerStorageName60;\n ::rtl::OUString maCurContainerStorageName;\n\n\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage; \/\/ package\n SfxObjectShell* mpDocPersist;\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; \/\/ container sub package for\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxTempStorage; \/\/ package\n \/\/ objects\n SvXMLEmbeddedObjectHelperMode meCreateMode;\n SvXMLEmbeddedObjectHelper_Impl *mpStreamMap;\n\n SVX_DLLPRIVATE sal_Bool ImplGetStorageNames(\n const ::rtl::OUString& rURLStr,\n ::rtl::OUString& rContainerStorageName,\n ::rtl::OUString& rObjectStorageName,\n sal_Bool bInternalToExternal,\n sal_Bool *pGraphicRepl=0 ) const;\n\n SVX_DLLPRIVATE com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage(\n const ::rtl::OUString& rStorageName );\n\n SVX_DLLPRIVATE String ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const;\n SVX_DLLPRIVATE sal_Bool ImplReadObject(\n const ::rtl::OUString& rContainerStorageName,\n ::rtl::OUString& rObjName,\n const SvGlobalName *pClassId,\n SvStream* pTemp );\n\n SVX_DLLPRIVATE ::rtl::OUString ImplInsertEmbeddedObjectURL(\n const ::rtl::OUString& rURLStr );\n\nprotected:\n\n SvXMLEmbeddedObjectHelper();\n ~SvXMLEmbeddedObjectHelper();\n void Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n\n virtual void SAL_CALL disposing();\n\npublic:\n SvXMLEmbeddedObjectHelper(\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n\n static SvXMLEmbeddedObjectHelper* Create(\n const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode,\n sal_Bool bDirect = sal_True );\n static SvXMLEmbeddedObjectHelper* Create(\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n static void Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper );\n\n void Flush();\n\n \/\/ XEmbeddedObjectResolver\n virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException);\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.10.420); FILE MERGED 2005\/09\/05 14:17:18 rt 1.10.420.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmleohlp.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:49:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLEOHLP_HXX\n#define _XMLEOHLP_HXX\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n#include <sot\/storage.hxx>\n#include <map>\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_\n#include <com\/sun\/star\/document\/XEmbeddedObjectResolver.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/\/ -----------------------------\n\/\/ - SvXMLEmbeddedObjectHelper -\n\/\/ -----------------------------\n\nenum SvXMLEmbeddedObjectHelperMode\n{\n EMBEDDEDOBJECTHELPER_MODE_READ = 0,\n EMBEDDEDOBJECTHELPER_MODE_WRITE = 1\n};\n\n\/\/ -----------------------------\n\/\/ - SvXMLEmbeddedObjectHelper -\n\/\/ -----------------------------\n\nclass SfxObjectShell;\nclass SvGlobalName;\nstruct OUStringLess;\nclass OutputStorageWrapper_Impl;\n\nclass SVX_DLLPUBLIC SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2<\n ::com::sun::star::document::XEmbeddedObjectResolver,\n ::com::sun::star::container::XNameAccess >\n{\n typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*,\n OUStringLess > SvXMLEmbeddedObjectHelper_Impl;\nprivate:\n\n ::osl::Mutex maMutex;\n\n const ::rtl::OUString maReplacementGraphicsContainerStorageName;\n const ::rtl::OUString maReplacementGraphicsContainerStorageName60;\n ::rtl::OUString maCurContainerStorageName;\n\n\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage; \/\/ package\n SfxObjectShell* mpDocPersist;\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; \/\/ container sub package for\n com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxTempStorage; \/\/ package\n \/\/ objects\n SvXMLEmbeddedObjectHelperMode meCreateMode;\n SvXMLEmbeddedObjectHelper_Impl *mpStreamMap;\n\n SVX_DLLPRIVATE sal_Bool ImplGetStorageNames(\n const ::rtl::OUString& rURLStr,\n ::rtl::OUString& rContainerStorageName,\n ::rtl::OUString& rObjectStorageName,\n sal_Bool bInternalToExternal,\n sal_Bool *pGraphicRepl=0 ) const;\n\n SVX_DLLPRIVATE com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage(\n const ::rtl::OUString& rStorageName );\n\n SVX_DLLPRIVATE String ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const;\n SVX_DLLPRIVATE sal_Bool ImplReadObject(\n const ::rtl::OUString& rContainerStorageName,\n ::rtl::OUString& rObjName,\n const SvGlobalName *pClassId,\n SvStream* pTemp );\n\n SVX_DLLPRIVATE ::rtl::OUString ImplInsertEmbeddedObjectURL(\n const ::rtl::OUString& rURLStr );\n\nprotected:\n\n SvXMLEmbeddedObjectHelper();\n ~SvXMLEmbeddedObjectHelper();\n void Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n\n virtual void SAL_CALL disposing();\n\npublic:\n SvXMLEmbeddedObjectHelper(\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n\n static SvXMLEmbeddedObjectHelper* Create(\n const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode,\n sal_Bool bDirect = sal_True );\n static SvXMLEmbeddedObjectHelper* Create(\n SfxObjectShell& rDocPersist,\n SvXMLEmbeddedObjectHelperMode eCreateMode );\n static void Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper );\n\n void Flush();\n\n \/\/ XEmbeddedObjectResolver\n virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XNameAccess\n virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException);\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SwNodeNum.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2006-05-05 09:12:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SW_NODE_NUM_HXX\n#define _SW_NODE_NUM_HXX\n\n#include <SwNumberTree.hxx>\n\nclass SwTxtNode;\nstruct SwPosition;\nclass SwNumRule;\nclass SwNumFmt;\n\nclass SW_DLLPUBLIC SwNodeNum : public SwNumberTreeNode\n{\n SwTxtNode * mpTxtNode;\n SwNumRule * mpNumRule;\n\n tSwNumTreeNumber mnStart;\n bool mbRestart;\n\n \/\/ --> OD 2006-03-07 #131436#\n static void _UnregisterMeAndChildrenDueToRootDelete( SwNodeNum& rNodeNum );\n \/\/ <--\nprotected:\n void SetTxtNode(SwTxtNode * pTxtNode);\n SwTxtNode * GetTxtNode() const;\n\n void SetNumRule(SwNumRule * pRule);\n SwNumRule * GetNumRule() const;\n\n \/\/ --> OD 2006-04-26 #i64010#\n virtual bool HasCountedChildren() const;\n virtual bool IsCountedForNumbering() const;\n \/\/ <--\n\npublic:\n SwNodeNum();\n SwNodeNum(const SwNodeNum & rNodeNum);\n virtual ~SwNodeNum();\n\n virtual SwNumberTreeNode * Create() const;\n\n virtual SwNumberTreeNode * Copy() const;\n\n virtual void RemoveChild(SwNumberTreeNode * pChild);\n\n virtual bool IsNotifiable() const;\n\n virtual bool IsContinuous() const;\n\n virtual bool IsCounted() const;\n\n virtual bool IsCountPhantoms() const;\n\n virtual void NotifyNode();\n\n virtual bool LessThan(const SwNumberTreeNode & rNode) const;\n\n void SetRestart(bool bRestart);\n\n virtual bool IsRestart() const;\n\n void SetStart(tSwNumTreeNumber nStart);\n\n virtual tSwNumTreeNumber GetStart() const;\n\n String ToString() const;\n\n void SetLevel(unsigned int nLevel);\n\n SwPosition GetPosition() const;\n\n const SwNumFmt * GetNumFmt() const;\n\n friend class SwTxtNode;\n friend class SwNumRule;\n\n \/\/ --> OD 2005-11-16 #i57919# - direct access on <mnStart>, needed for HTML export\n inline const tSwNumTreeNumber GetStartValue() const\n {\n return mnStart;\n }\n \/\/ <--\n\n \/\/ --> OD 2006-03-07 #131436#\n \/\/ The number tree root node is deleted, when the corresponding numbering\n \/\/ rule is deleted. In this situation the number tree should be empty -\n \/\/ still registered text nodes aren't allowed. But it is possible, that\n \/\/ text nodes of the undo nodes array are still registered. These will be\n \/\/ unregistered.\n \/\/ Text nodes of the document nodes array aren't allowed to be registered\n \/\/ in this situation - this will be asserted.\n static void HandleNumberTreeRootNodeDelete( SwNodeNum& rNodeNum );\n \/\/ <--\n};\n\n#endif \/\/ _SW_NODE_NUM_HXX\n<commit_msg>INTEGRATION: CWS swautomatic01 (1.5.84); FILE MERGED 2006\/09\/11 12:04:46 ama 1.5.84.1: #i65476#: Automatic Styles, numbering<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SwNodeNum.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2006-12-01 15:31:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SW_NODE_NUM_HXX\n#define _SW_NODE_NUM_HXX\n\n#include <SwNumberTree.hxx>\n\nclass SwTxtNode;\nstruct SwPosition;\nclass SwNumRule;\nclass SwNumFmt;\n\nclass SW_DLLPUBLIC SwNodeNum : public SwNumberTreeNode\n{\n SwTxtNode * mpTxtNode;\n SwNumRule * mpNumRule;\n\n tSwNumTreeNumber mnStart;\n bool mbRestart;\n\n \/\/ --> OD 2006-03-07 #131436#\n static void _UnregisterMeAndChildrenDueToRootDelete( SwNodeNum& rNodeNum );\n \/\/ <--\nprotected:\n void SetTxtNode(SwTxtNode * pTxtNode);\n SwTxtNode * GetTxtNode() const;\n\n void SetNumRule(SwNumRule * pRule);\n SwNumRule * GetNumRule() const;\n\n \/\/ --> OD 2006-04-26 #i64010#\n virtual bool HasCountedChildren() const;\n virtual bool IsCountedForNumbering() const;\n \/\/ <--\n\npublic:\n SwNodeNum();\n SwNodeNum(const SwNodeNum & rNodeNum);\n virtual ~SwNodeNum();\n\n virtual SwNumberTreeNode * Create() const;\n\n virtual SwNumberTreeNode * Copy() const;\n\n virtual void RemoveChild(SwNumberTreeNode * pChild);\n\n virtual bool IsNotifiable() const;\n\n virtual bool IsNotificationEnabled() const;\n\n virtual bool IsContinuous() const;\n\n virtual bool IsCounted() const;\n\n virtual bool IsCountPhantoms() const;\n\n virtual void NotifyNode();\n\n virtual bool LessThan(const SwNumberTreeNode & rNode) const;\n\n void SetRestart(bool bRestart);\n\n virtual bool IsRestart() const;\n\n void SetStart(tSwNumTreeNumber nStart);\n\n virtual tSwNumTreeNumber GetStart() const;\n\n String ToString() const;\n\n void SetLevel(unsigned int nLevel);\n\n SwPosition GetPosition() const;\n\n const SwNumFmt * GetNumFmt() const;\n\n friend class SwTxtNode;\n friend class SwNumRule;\n\n \/\/ --> OD 2005-11-16 #i57919# - direct access on <mnStart>, needed for HTML export\n inline const tSwNumTreeNumber GetStartValue() const\n {\n return mnStart;\n }\n \/\/ <--\n\n \/\/ --> OD 2006-03-07 #131436#\n \/\/ The number tree root node is deleted, when the corresponding numbering\n \/\/ rule is deleted. In this situation the number tree should be empty -\n \/\/ still registered text nodes aren't allowed. But it is possible, that\n \/\/ text nodes of the undo nodes array are still registered. These will be\n \/\/ unregistered.\n \/\/ Text nodes of the document nodes array aren't allowed to be registered\n \/\/ in this situation - this will be asserted.\n static void HandleNumberTreeRootNodeDelete( SwNodeNum& rNodeNum );\n \/\/ <--\n};\n\n#endif \/\/ _SW_NODE_NUM_HXX\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include <utility>\n\n#include \"atom\/browser\/atom_browser_context.h\"\n\n#include \"atom\/browser\/api\/atom_api_protocol.h\"\n#include \"atom\/browser\/atom_browser_main_parts.h\"\n#include \"atom\/browser\/atom_download_manager_delegate.h\"\n#include \"atom\/browser\/atom_permission_manager.h\"\n#include \"atom\/browser\/browser.h\"\n#include \"atom\/browser\/net\/asar\/asar_protocol_handler.h\"\n#include \"atom\/browser\/net\/atom_cert_verifier.h\"\n#include \"atom\/browser\/net\/atom_network_delegate.h\"\n#include \"atom\/browser\/net\/atom_ssl_config_service.h\"\n#include \"atom\/browser\/net\/atom_url_request_job_factory.h\"\n#include \"atom\/browser\/net\/http_protocol_handler.h\"\n#include \"atom\/common\/atom_version.h\"\n#include \"atom\/common\/options_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/memory\/ptr_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_version.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_registry_simple.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"net\/ftp\/ftp_network_layer.h\"\n#include \"net\/url_request\/data_protocol_handler.h\"\n#include \"net\/url_request\/ftp_protocol_handler.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_intercepting_job_factory.h\"\n#include \"url\/url_constants.h\"\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nclass NoCacheBackend : public net::HttpCache::BackendFactory {\n int CreateBackend(net::NetLog* net_log,\n std::unique_ptr<disk_cache::Backend>* backend,\n const net::CompletionCallback& callback) override {\n return net::ERR_FAILED;\n }\n};\n\n} \/\/ namespace\n\nAtomBrowserContext::AtomBrowserContext(\n const std::string& partition, bool in_memory,\n const base::DictionaryValue& options)\n : brightray::BrowserContext(partition, in_memory),\n network_delegate_(new AtomNetworkDelegate) {\n \/\/ Read options.\n use_cache_ = true;\n options.GetBoolean(\"cache\", &use_cache_);\n\n \/\/ Initialize Pref Registry in brightray.\n \/\/ InitPrefs();\n}\n\nAtomBrowserContext::~AtomBrowserContext() {\n}\n\nnet::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() {\n return network_delegate_;\n}\n\nstd::unique_ptr<net::URLRequestJobFactory>\nAtomBrowserContext::CreateURLRequestJobFactory(\n content::ProtocolHandlerMap* protocol_handlers) {\n std::unique_ptr<AtomURLRequestJobFactory> job_factory(\n new AtomURLRequestJobFactory);\n\n for (auto& it : *protocol_handlers) {\n job_factory->SetProtocolHandler(it.first,\n base::WrapUnique(it.second.release()));\n }\n protocol_handlers->clear();\n\n job_factory->SetProtocolHandler(\n url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));\n job_factory->SetProtocolHandler(\n url::kFileScheme, base::WrapUnique(new asar::AsarProtocolHandler(\n BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(\n base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));\n job_factory->SetProtocolHandler(\n url::kHttpScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kHttpScheme)));\n job_factory->SetProtocolHandler(\n url::kHttpsScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kHttpsScheme)));\n job_factory->SetProtocolHandler(\n url::kWsScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kWsScheme)));\n job_factory->SetProtocolHandler(\n url::kWssScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kWssScheme)));\n\n auto host_resolver =\n url_request_context_getter()->GetURLRequestContext()->host_resolver();\n job_factory->SetProtocolHandler(\n url::kFtpScheme,\n base::WrapUnique(new net::FtpProtocolHandler(\n new net::FtpNetworkLayer(host_resolver))));\n\n return std::move(job_factory);\n}\n\nnet::HttpCache::BackendFactory*\nAtomBrowserContext::CreateHttpCacheBackendFactory(\n const base::FilePath& base_path) {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n if (!use_cache_ || command_line->HasSwitch(switches::kDisableHttpCache))\n return new NoCacheBackend;\n else\n return brightray::BrowserContext::CreateHttpCacheBackendFactory(base_path);\n}\n\ncontent::DownloadManagerDelegate*\nAtomBrowserContext::GetDownloadManagerDelegate() {\n if (!download_manager_delegate_.get()) {\n auto download_manager = content::BrowserContext::GetDownloadManager(this);\n download_manager_delegate_.reset(\n new AtomDownloadManagerDelegate(download_manager));\n }\n return download_manager_delegate_.get();\n}\n\ncontent::PermissionManager* AtomBrowserContext::GetPermissionManager() {\n if (!permission_manager_.get())\n permission_manager_.reset(new AtomPermissionManager);\n return permission_manager_.get();\n}\n\nstd::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {\n return base::WrapUnique(new AtomCertVerifier);\n}\n\nnet::SSLConfigService* AtomBrowserContext::CreateSSLConfigService() {\n return new AtomSSLConfigService;\n}\n\nstd::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {\n auto default_schemes = brightray::BrowserContext::GetCookieableSchemes();\n const auto& standard_schemes = atom::api::GetStandardSchemes();\n default_schemes.insert(default_schemes.end(),\n standard_schemes.begin(), standard_schemes.end());\n return default_schemes;\n}\n\nvoid AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {\n pref_registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,\n base::FilePath());\n base::FilePath download_dir;\n PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir);\n pref_registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,\n download_dir);\n pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);\n}\n\n} \/\/ namespace atom\n<commit_msg>Apply changes to \"Clean up FtpTransactionFacory ownership.\" https:\/\/chromium.googlesource.com\/chromium\/src.git\/+\/cd4c75339e11e32ef36da7a856a19ca8ee3976f1<commit_after>\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include <utility>\n\n#include \"atom\/browser\/atom_browser_context.h\"\n\n#include \"atom\/browser\/api\/atom_api_protocol.h\"\n#include \"atom\/browser\/atom_browser_main_parts.h\"\n#include \"atom\/browser\/atom_download_manager_delegate.h\"\n#include \"atom\/browser\/atom_permission_manager.h\"\n#include \"atom\/browser\/browser.h\"\n#include \"atom\/browser\/net\/asar\/asar_protocol_handler.h\"\n#include \"atom\/browser\/net\/atom_cert_verifier.h\"\n#include \"atom\/browser\/net\/atom_network_delegate.h\"\n#include \"atom\/browser\/net\/atom_ssl_config_service.h\"\n#include \"atom\/browser\/net\/atom_url_request_job_factory.h\"\n#include \"atom\/browser\/net\/http_protocol_handler.h\"\n#include \"atom\/common\/atom_version.h\"\n#include \"atom\/common\/options_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/memory\/ptr_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_version.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_registry_simple.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"net\/ftp\/ftp_network_layer.h\"\n#include \"net\/url_request\/data_protocol_handler.h\"\n#include \"net\/url_request\/ftp_protocol_handler.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_intercepting_job_factory.h\"\n#include \"url\/url_constants.h\"\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nclass NoCacheBackend : public net::HttpCache::BackendFactory {\n int CreateBackend(net::NetLog* net_log,\n std::unique_ptr<disk_cache::Backend>* backend,\n const net::CompletionCallback& callback) override {\n return net::ERR_FAILED;\n }\n};\n\n} \/\/ namespace\n\nAtomBrowserContext::AtomBrowserContext(\n const std::string& partition, bool in_memory,\n const base::DictionaryValue& options)\n : brightray::BrowserContext(partition, in_memory),\n network_delegate_(new AtomNetworkDelegate) {\n \/\/ Read options.\n use_cache_ = true;\n options.GetBoolean(\"cache\", &use_cache_);\n\n \/\/ Initialize Pref Registry in brightray.\n \/\/ InitPrefs();\n}\n\nAtomBrowserContext::~AtomBrowserContext() {\n}\n\nnet::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() {\n return network_delegate_;\n}\n\nstd::unique_ptr<net::URLRequestJobFactory>\nAtomBrowserContext::CreateURLRequestJobFactory(\n content::ProtocolHandlerMap* protocol_handlers) {\n std::unique_ptr<AtomURLRequestJobFactory> job_factory(\n new AtomURLRequestJobFactory);\n\n for (auto& it : *protocol_handlers) {\n job_factory->SetProtocolHandler(it.first,\n base::WrapUnique(it.second.release()));\n }\n protocol_handlers->clear();\n\n job_factory->SetProtocolHandler(\n url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));\n job_factory->SetProtocolHandler(\n url::kFileScheme, base::WrapUnique(new asar::AsarProtocolHandler(\n BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(\n base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));\n job_factory->SetProtocolHandler(\n url::kHttpScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kHttpScheme)));\n job_factory->SetProtocolHandler(\n url::kHttpsScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kHttpsScheme)));\n job_factory->SetProtocolHandler(\n url::kWsScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kWsScheme)));\n job_factory->SetProtocolHandler(\n url::kWssScheme,\n base::WrapUnique(new HttpProtocolHandler(url::kWssScheme)));\n\n auto host_resolver =\n url_request_context_getter()->GetURLRequestContext()->host_resolver();\n job_factory->SetProtocolHandler(\n url::kFtpScheme,\n net::FtpProtocolHandler::Create(host_resolver));\n\n return std::move(job_factory);\n}\n\nnet::HttpCache::BackendFactory*\nAtomBrowserContext::CreateHttpCacheBackendFactory(\n const base::FilePath& base_path) {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n if (!use_cache_ || command_line->HasSwitch(switches::kDisableHttpCache))\n return new NoCacheBackend;\n else\n return brightray::BrowserContext::CreateHttpCacheBackendFactory(base_path);\n}\n\ncontent::DownloadManagerDelegate*\nAtomBrowserContext::GetDownloadManagerDelegate() {\n if (!download_manager_delegate_.get()) {\n auto download_manager = content::BrowserContext::GetDownloadManager(this);\n download_manager_delegate_.reset(\n new AtomDownloadManagerDelegate(download_manager));\n }\n return download_manager_delegate_.get();\n}\n\ncontent::PermissionManager* AtomBrowserContext::GetPermissionManager() {\n if (!permission_manager_.get())\n permission_manager_.reset(new AtomPermissionManager);\n return permission_manager_.get();\n}\n\nstd::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {\n return base::WrapUnique(new AtomCertVerifier);\n}\n\nnet::SSLConfigService* AtomBrowserContext::CreateSSLConfigService() {\n return new AtomSSLConfigService;\n}\n\nstd::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {\n auto default_schemes = brightray::BrowserContext::GetCookieableSchemes();\n const auto& standard_schemes = atom::api::GetStandardSchemes();\n default_schemes.insert(default_schemes.end(),\n standard_schemes.begin(), standard_schemes.end());\n return default_schemes;\n}\n\nvoid AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {\n pref_registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,\n base::FilePath());\n base::FilePath download_dir;\n PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir);\n pref_registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,\n download_dir);\n pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: dsp_html_std.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: np $ $Date: 2002-11-01 17:12:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef AUTODOC_DSP_HTML_STD_HXX\n#define AUTODOC_DSP_HTML_STD_HXX\n\n\n\nnamespace ary\n{\n namespace cpp\n {\n class DisplayGate;\n }\n namespace idl\n {\n class Gate;\n }\n}\n\nnamespace display\n{\n class CorporateFrame;\n}\n\n\nnamespace autodoc\n{\n\n\nclass HtmlDisplay_UdkStd\n{\n public:\n virtual ~HtmlDisplay_UdkStd() {}\n\n \/** Displays the names of several C++ code entities within the\n given namespace (or the global namespace as default). All\n subnamespaces are included.\n\n Output has following format:\n\n =========================================================================\n OutputDirectory\n index.html\n def-all.html\n prj\\\n sal\\\n index.html \/\/ Overview about project\n\n f-FileName[1,2,...] \/\/ Overview about file\n f-OtherFileName[1,2,...]\n ...\n def-FileName[1,2,...] \/\/ #defines and macros in file\n def-OtherFileName[1,2,...]\n ...\n rtl\\\n ...\n cppu\\\n ...\n cppuhelper\\\n ...\n ...\n ix\\\n ix-a.html\n ix-b.html\n ...\n ix-z.html\n ix-_.html\n ix-other.html\n\n cpp\\\n index.html \/\/ Overview about global namespace\n\n Namespace_A\\\n Namespace_C\\\n index.html \/\/ Overview about namespace C\n ...\n ...\n\n index.html \/\/ Overview about namespace A\n\n c-ClassName_X.html \/\/ Description of class\n ...\n e-EnumName.html \/\/ Description of enum\n ...\n t-TypedefName.html \/\/ Description of typedef\n ...\n o-Filename.html \/\/ Descriptions of operations in this file in this namespace\n ...\n d-Filename.html \/\/ Descriptions of data in this file in this namespace\n ...\n\n ClassName_X\\\n c-ClassName_Y.html\n e-EnumName.html\n t-TypedefName.html\n o.html \/\/ Descriptions of operations in class X\n d.html \/\/ Descriptions of data in class X\n\n ClassName_Y\\\n ...\n ...\n\n idl\\\n ...\n java\\\n ...\n =========================================================================\n\n\n @param i_sOutputDirectory\n Directory for output. Path must be given in correct\n syntax for the actual operating system without final\n path delimiter. If this is 0 or \"\", the current\n working directory is chosen.\n @param i_rAryGate\n The access to the Autodoc Repository.\n @param i_rLayout\n Gives parameters for the appearance of the HTML output.\n @param i_pProjectList\n If this is != 0, then only code entities which are declared\n in this projects are displayed.\n *\/\n void Run(\n const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout,\n const StringVector *\n i_pProjectList = 0 );\n private:\n virtual void do_Run(\n const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout,\n const StringVector *\n i_pProjectList ) = 0;\n};\n\n\/\/ IMPLEMENTATION\n\ninline void\nHtmlDisplay_UdkStd::Run( const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate & i_rAryGate,\n const display::CorporateFrame & i_rLayout,\n const StringVector * i_pProjectList )\n{\n do_Run( i_sOutputDirectory, i_rAryGate, i_rLayout, i_pProjectList );\n}\n\n\n\n\/\/ class HtmlDisplay_Idl_Ifc\n\nclass HtmlDisplay_Idl_Ifc\n{\n public:\n virtual ~HtmlDisplay_Idl_Ifc() {}\n\n void Run(\n const char * i_sOutputDirectory,\n const ary::idl::Gate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout );\n private:\n virtual void do_Run(\n const char * i_sOutputDirectory,\n const ary::idl::Gate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout ) = 0;\n};\n\n\/\/ IMPLEMENTATION\n\ninline void\nHtmlDisplay_Idl_Ifc::Run( const char * i_sOutputDirectory,\n const ary::idl::Gate & i_rAryGate,\n const display::CorporateFrame & i_rLayout )\n{\n do_Run( i_sOutputDirectory, i_rAryGate, i_rLayout );\n}\n\n\n} \/\/ namespace autodoc\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.130); FILE MERGED 2005\/09\/05 13:09:40 rt 1.3.130.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dsp_html_std.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 16:26:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef AUTODOC_DSP_HTML_STD_HXX\n#define AUTODOC_DSP_HTML_STD_HXX\n\n\n\nnamespace ary\n{\n namespace cpp\n {\n class DisplayGate;\n }\n namespace idl\n {\n class Gate;\n }\n}\n\nnamespace display\n{\n class CorporateFrame;\n}\n\n\nnamespace autodoc\n{\n\n\nclass HtmlDisplay_UdkStd\n{\n public:\n virtual ~HtmlDisplay_UdkStd() {}\n\n \/** Displays the names of several C++ code entities within the\n given namespace (or the global namespace as default). All\n subnamespaces are included.\n\n Output has following format:\n\n =========================================================================\n OutputDirectory\n index.html\n def-all.html\n prj\\\n sal\\\n index.html \/\/ Overview about project\n\n f-FileName[1,2,...] \/\/ Overview about file\n f-OtherFileName[1,2,...]\n ...\n def-FileName[1,2,...] \/\/ #defines and macros in file\n def-OtherFileName[1,2,...]\n ...\n rtl\\\n ...\n cppu\\\n ...\n cppuhelper\\\n ...\n ...\n ix\\\n ix-a.html\n ix-b.html\n ...\n ix-z.html\n ix-_.html\n ix-other.html\n\n cpp\\\n index.html \/\/ Overview about global namespace\n\n Namespace_A\\\n Namespace_C\\\n index.html \/\/ Overview about namespace C\n ...\n ...\n\n index.html \/\/ Overview about namespace A\n\n c-ClassName_X.html \/\/ Description of class\n ...\n e-EnumName.html \/\/ Description of enum\n ...\n t-TypedefName.html \/\/ Description of typedef\n ...\n o-Filename.html \/\/ Descriptions of operations in this file in this namespace\n ...\n d-Filename.html \/\/ Descriptions of data in this file in this namespace\n ...\n\n ClassName_X\\\n c-ClassName_Y.html\n e-EnumName.html\n t-TypedefName.html\n o.html \/\/ Descriptions of operations in class X\n d.html \/\/ Descriptions of data in class X\n\n ClassName_Y\\\n ...\n ...\n\n idl\\\n ...\n java\\\n ...\n =========================================================================\n\n\n @param i_sOutputDirectory\n Directory for output. Path must be given in correct\n syntax for the actual operating system without final\n path delimiter. If this is 0 or \"\", the current\n working directory is chosen.\n @param i_rAryGate\n The access to the Autodoc Repository.\n @param i_rLayout\n Gives parameters for the appearance of the HTML output.\n @param i_pProjectList\n If this is != 0, then only code entities which are declared\n in this projects are displayed.\n *\/\n void Run(\n const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout,\n const StringVector *\n i_pProjectList = 0 );\n private:\n virtual void do_Run(\n const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout,\n const StringVector *\n i_pProjectList ) = 0;\n};\n\n\/\/ IMPLEMENTATION\n\ninline void\nHtmlDisplay_UdkStd::Run( const char * i_sOutputDirectory,\n const ary::cpp::DisplayGate & i_rAryGate,\n const display::CorporateFrame & i_rLayout,\n const StringVector * i_pProjectList )\n{\n do_Run( i_sOutputDirectory, i_rAryGate, i_rLayout, i_pProjectList );\n}\n\n\n\n\/\/ class HtmlDisplay_Idl_Ifc\n\nclass HtmlDisplay_Idl_Ifc\n{\n public:\n virtual ~HtmlDisplay_Idl_Ifc() {}\n\n void Run(\n const char * i_sOutputDirectory,\n const ary::idl::Gate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout );\n private:\n virtual void do_Run(\n const char * i_sOutputDirectory,\n const ary::idl::Gate &\n i_rAryGate,\n const display::CorporateFrame &\n i_rLayout ) = 0;\n};\n\n\/\/ IMPLEMENTATION\n\ninline void\nHtmlDisplay_Idl_Ifc::Run( const char * i_sOutputDirectory,\n const ary::idl::Gate & i_rAryGate,\n const display::CorporateFrame & i_rLayout )\n{\n do_Run( i_sOutputDirectory, i_rAryGate, i_rLayout );\n}\n\n\n} \/\/ namespace autodoc\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP\n\n#include <stan\/math\/prim\/mat\/fun\/typedefs.hpp>\n\nnamespace stan {\n namespace math {\n\n \/**\n * Returns the result of multiplying the lower triangular\n * portion of the input matrix by its own transpose.\n * @param L Matrix to multiply.\n * @return The lower triangular values in L times their own\n * transpose.\n * @throw std::domain_error If the input matrix is not square.\n *\/\n inline matrix_d\n multiply_lower_tri_self_transpose(const matrix_d& L) {\n int K = L.rows();\n if (K == 0)\n return L;\n if (K == 1) {\n matrix_d result(1, 1);\n result(0) = square(L(0)); \/\/ first elt, so don't need double idx\n return result;\n }\n int J = L.cols();\n matrix_d LLt(K, K);\n matrix_d Lt = L.transpose();\n for (int m = 0; m < K; ++m) {\n int k = (J < m + 1) ? J : m + 1;\n LLt(m, m) = Lt.col(m).head(k).squaredNorm();\n for (int n = (m + 1); n < K; ++n)\n LLt(n, m) = LLt(m, n) = Lt.col(m).head(k).dot(Lt.col(n).head(k));\n }\n return LLt;\n }\n\n }\n}\n#endif\n<commit_msg>Adding missing header<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MULTIPLY_LOWER_TRI_SELF_TRANSPOSE_HPP\n\n#include <stan\/math\/prim\/mat\/fun\/typedefs.hpp>\n#include <stan\/math\/prim\/scal\/fun\/square.hpp>\n\nnamespace stan {\n namespace math {\n\n \/**\n * Returns the result of multiplying the lower triangular\n * portion of the input matrix by its own transpose.\n * @param L Matrix to multiply.\n * @return The lower triangular values in L times their own\n * transpose.\n * @throw std::domain_error If the input matrix is not square.\n *\/\n inline matrix_d\n multiply_lower_tri_self_transpose(const matrix_d& L) {\n int K = L.rows();\n if (K == 0)\n return L;\n if (K == 1) {\n matrix_d result(1, 1);\n result(0) = square(L(0)); \/\/ first elt, so don't need double idx\n return result;\n }\n int J = L.cols();\n matrix_d LLt(K, K);\n matrix_d Lt = L.transpose();\n for (int m = 0; m < K; ++m) {\n int k = (J < m + 1) ? J : m + 1;\n LLt(m, m) = Lt.col(m).head(k).squaredNorm();\n for (int n = (m + 1); n < K; ++n)\n LLt(n, m) = LLt(m, n) = Lt.col(m).head(k).dot(Lt.col(n).head(k));\n }\n return LLt;\n }\n\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkTestingMacros.h>\n#include <mitkTestFixture.h>\n#include \"mitkIOUtil.h\"\n#include <cmath>\n\n#include <mitkGIFVolumetricStatistics.h>\n\nclass mitkGIFVolumetricStatisticsTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFVolumetricStatisticsTestSuite);\n\n MITK_TEST(ImageDescription_PhantomTest);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n mitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest()\n {\n mitk::GIFVolumetricStatistics::Pointer featureCalculator = mitk::GIFVolumetricStatistics::New();\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Volume Statistic should calculate 33 features.\", std::size_t(38), featureList.size());\n\n \/\/ These values are obtained in cooperation with IBSI\n \/\/ Default accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (mesh based) with Large IBSI Phantom Image\", 556, results[\"Volumetric Features::Volume (mesh based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image\", 592, results[\"Volumetric Features::Volume (voxel based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface (mesh based) with Large IBSI Phantom Image\", 388, results[\"Volumetric Features::Surface (mesh based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface to volume ratio (mesh based) with Large IBSI Phantom Image\", 0.698, results[\"Volumetric Features::Surface to volume ratio (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 (mesh based) with Large IBSI Phantom Image\", 0.0437, results[\"Volumetric Features::Compactness 1 (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 2 (mesh based) with Large IBSI Phantom Image\", 0.678, results[\"Volumetric Features::Compactness 2 (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Spherical disproportion (mesh based) with Large IBSI Phantom Image\", 1.14, results[\"Volumetric Features::Spherical disproportion (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Sphericity (mesh based) with Large IBSI Phantom Image\", 0.879, results[\"Volumetric Features::Sphericity (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image\", 0.138, results[\"Volumetric Features::Asphericity (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Ceentre of mass shift with Large IBSI Phantom Image\", 0.672, results[\"Volumetric Features::Centre of mass shift\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Maximum 3D diameter with Large IBSI Phantom Image\", 11.66, results[\"Volumetric Features::Maximum 3D diameter\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Major axis length with Large IBSI Phantom Image\", 11.40, results[\"Volumetric Features::PCA Major axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Minor axis length with Large IBSI Phantom Image\", 9.31, results[\"Volumetric Features::PCA Minor axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Least axis length with Large IBSI Phantom Image\", 8.54, results[\"Volumetric Features::PCA Least axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Elongation with Large IBSI Phantom Image\", 0.816, results[\"Volumetric Features::PCA Elongation\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Flatness with Large IBSI Phantom Image\", 0.749, results[\"Volumetric Features::PCA Flatness\"], 0.01);\n\n \/\/ These values are obtained by running the filter\n \/\/ They might be wrong!\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Voxel Volume with Large IBSI Phantom Image\", 8, results[\"Volumetric Features::Voxel Volume\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image\", 592, results[\"Volumetric Features::Volume (voxel based)\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface (voxel based) with Large IBSI Phantom Image\", 488, results[\"Volumetric Features::Surface (voxel based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Centre of mass shift (uncorrected) with Large IBSI Phantom Image\", 0.672, results[\"Volumetric Features::Centre of mass shift (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Bounding Box Volume with Large IBSI Phantom Image\", 288, results[\"Volumetric Features::Bounding Box Volume\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface to volume ratio (voxel based) with Large IBSI Phantom Image\", 0.824, results[\"Volumetric Features::Surface to volume ratio (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Sphericity (voxel based) with Large IBSI Phantom Image\", 0.699, results[\"Volumetric Features::Sphericity (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (voxel based) with Large IBSI Phantom Image\", 0.431, results[\"Volumetric Features::Asphericity (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 (voxel based) with Large IBSI Phantom Image\", 0.031, results[\"Volumetric Features::Compactness 1 (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 old (voxel based) with Large IBSI Phantom Image\", 5.388, results[\"Volumetric Features::Compactness 1 old (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 2 (voxel based) with Large IBSI Phantom Image\", 0.341, results[\"Volumetric Features::Compactness 2 (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Spherical disproportion (voxel based) with Large IBSI Phantom Image\", 1.43, results[\"Volumetric Features::Spherical disproportion (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Major axis length (uncorrected) with Large IBSI Phantom Image\", 11.40, results[\"Volumetric Features::PCA Major axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Minor axis length (uncorrected) with Large IBSI Phantom Image\", 9.31, results[\"Volumetric Features::PCA Minor axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Least axis length (uncorrected) with Large IBSI Phantom Image\", 8.54, results[\"Volumetric Features::PCA Least axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Elongation (uncorrected) with Large IBSI Phantom Image\", 0.816, results[\"Volumetric Features::PCA Elongation (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Flatness (uncorrected) with Large IBSI Phantom Image\", 0.749, results[\"Volumetric Features::PCA Flatness (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 old (mesh based) with Large IBSI Phantom Image\", 6.278, results[\"Volumetric Features::Compactness 1 old (mesh based)\"], 0.01);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFVolumetricStatistics )<commit_msg>Added missing features<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkTestingMacros.h>\n#include <mitkTestFixture.h>\n#include \"mitkIOUtil.h\"\n#include <cmath>\n\n#include <mitkGIFVolumetricStatistics.h>\n\nclass mitkGIFVolumetricStatisticsTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFVolumetricStatisticsTestSuite);\n\n MITK_TEST(ImageDescription_PhantomTest);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n mitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::Load<mitk::Image>(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest()\n {\n mitk::GIFVolumetricStatistics::Pointer featureCalculator = mitk::GIFVolumetricStatistics::New();\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map<std::string, double> results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Volume Statistic should calculate 33 features.\", std::size_t(38), featureList.size());\n\n \/\/ These values are obtained in cooperation with IBSI\n \/\/ Default accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (mesh based) with Large IBSI Phantom Image\", 556, results[\"Volumetric Features::Volume (mesh based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image\", 592, results[\"Volumetric Features::Volume (voxel based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface (mesh based) with Large IBSI Phantom Image\", 388, results[\"Volumetric Features::Surface (mesh based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface to volume ratio (mesh based) with Large IBSI Phantom Image\", 0.698, results[\"Volumetric Features::Surface to volume ratio (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 (mesh, mesh based) with Large IBSI Phantom Image\", 0.04105, results[\"Volumetric Features::Compactness 1 (mesh, mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 2 (mesh, mesh based) with Large IBSI Phantom Image\", 0.599, results[\"Volumetric Features::Compactness 2 (mesh, mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Spherical disproportion (mesh, mesh based) with Large IBSI Phantom Image\", 1.18, results[\"Volumetric Features::Spherical disproportion (mesh, mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Sphericity (mesh, mesh based) with Large IBSI Phantom Image\", 0.843, results[\"Volumetric Features::Sphericity (mesh, mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image\", 0.186, results[\"Volumetric Features::Asphericity (mesh, mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Ceentre of mass shift with Large IBSI Phantom Image\", 0.672, results[\"Volumetric Features::Centre of mass shift\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Maximum 3D diameter with Large IBSI Phantom Image\", 11.66, results[\"Volumetric Features::Maximum 3D diameter\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Major axis length with Large IBSI Phantom Image\", 11.40, results[\"Volumetric Features::PCA Major axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Minor axis length with Large IBSI Phantom Image\", 9.31, results[\"Volumetric Features::PCA Minor axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Least axis length with Large IBSI Phantom Image\", 8.54, results[\"Volumetric Features::PCA Least axis length\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Elongation with Large IBSI Phantom Image\", 0.816, results[\"Volumetric Features::PCA Elongation\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Flatness with Large IBSI Phantom Image\", 0.749, results[\"Volumetric Features::PCA Flatness\"], 0.01);\n\n \/\/ These values are obtained by running the filter\n \/\/ They might be wrong!\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Voxel Volume with Large IBSI Phantom Image\", 8, results[\"Volumetric Features::Voxel Volume\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image\", 592, results[\"Volumetric Features::Volume (voxel based)\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface (voxel based) with Large IBSI Phantom Image\", 488, results[\"Volumetric Features::Surface (voxel based)\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Centre of mass shift (uncorrected) with Large IBSI Phantom Image\", 0.672, results[\"Volumetric Features::Centre of mass shift (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Bounding Box Volume with Large IBSI Phantom Image\", 288, results[\"Volumetric Features::Bounding Box Volume\"], 1.0);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Surface to volume ratio (voxel based) with Large IBSI Phantom Image\", 0.824, results[\"Volumetric Features::Surface to volume ratio (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Sphericity (voxel based) with Large IBSI Phantom Image\", 0.699, results[\"Volumetric Features::Sphericity (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (voxel based) with Large IBSI Phantom Image\", 0.431, results[\"Volumetric Features::Asphericity (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Sphericity (mesh based) with Large IBSI Phantom Image\", 0.879, results[\"Volumetric Features::Sphericity (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image\", 0.138, results[\"Volumetric Features::Asphericity (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image\", 0.138, results[\"Volumetric Features::Asphericity (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 (voxel based) with Large IBSI Phantom Image\", 0.031, results[\"Volumetric Features::Compactness 1 (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 old (voxel based) with Large IBSI Phantom Image\", 5.388, results[\"Volumetric Features::Compactness 1 old (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 2 (voxel based) with Large IBSI Phantom Image\", 0.341, results[\"Volumetric Features::Compactness 2 (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 (mesh based) with Large IBSI Phantom Image\", 0.0437, results[\"Volumetric Features::Compactness 1 (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 2 (mesh based) with Large IBSI Phantom Image\", 0.678, results[\"Volumetric Features::Compactness 2 (mesh based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Spherical disproportion (voxel based) with Large IBSI Phantom Image\", 1.43, results[\"Volumetric Features::Spherical disproportion (voxel based)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Major axis length (uncorrected) with Large IBSI Phantom Image\", 11.40, results[\"Volumetric Features::PCA Major axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Minor axis length (uncorrected) with Large IBSI Phantom Image\", 9.31, results[\"Volumetric Features::PCA Minor axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Least axis length (uncorrected) with Large IBSI Phantom Image\", 8.54, results[\"Volumetric Features::PCA Least axis length (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Elongation (uncorrected) with Large IBSI Phantom Image\", 0.816, results[\"Volumetric Features::PCA Elongation (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::PCA Flatness (uncorrected) with Large IBSI Phantom Image\", 0.749, results[\"Volumetric Features::PCA Flatness (uncorrected)\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Volumetric Features::Compactness 1 old (mesh based) with Large IBSI Phantom Image\", 6.278, results[\"Volumetric Features::Compactness 1 old (mesh based)\"], 0.01);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFVolumetricStatistics )<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_algorithm_picker.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/backend_configs.pb.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/buffer_comparator.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_thunk.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/stream_executor_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instructions.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/logger.h\"\n#include \"tensorflow\/core\/protobuf\/autotuning.pb.h\"\n#include \"tensorflow\/core\/util\/proto\/proto_utils.h\"\n#include \"tensorflow\/stream_executor\/blas.h\"\n#include \"tensorflow\/stream_executor\/cuda\/redzone_allocator.h\"\n#include \"tensorflow\/stream_executor\/device_memory.h\"\n#include \"tensorflow\/stream_executor\/device_memory_allocator.h\"\n\nnamespace xla {\nnamespace gpu {\n\nusing tensorflow::AutotuneResult;\n\nusing GemmCacheKey =\n std::tuple<se::StreamExecutor*, Shape, Shape, Shape, std::string>;\n\nstatic tensorflow::mutex autotune_cache_mu(tensorflow::LINKER_INITIALIZED);\nstatic auto& autotune_cache GUARDED_BY(autotune_cache_mu) =\n *new absl::flat_hash_map<GemmCacheKey,\n absl::optional<se::blas::AlgorithmType>>();\nstatic int64 cache_hits GUARDED_BY(autotune_cache_mu) = 0;\nstatic int64 cache_misses GUARDED_BY(autotune_cache_mu) = 0;\n\n\/\/ Experimentally tries to pick the best algorithm for the given gemm.\n\/\/\n\/\/ This may fail under perfectly normal circumstances. In particular, it will\n\/\/ fail if the program was built with < CUDA 8 or if we're using a gpu older\n\/\/ than sm_50 -- in both cases, cublas doesn't support gemm-with-algorithm at\n\/\/ all.\nstatic StatusOr<absl::optional<se::blas::AlgorithmType>> DoUncachedGemmAutotune(\n const HloInstruction* gemm, se::DeviceMemoryBase lhs_buffer,\n se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer,\n se::DeviceMemoryBase reference_result_buffer,\n se::DeviceMemoryBase output_ref_buffer, se::Stream* stream,\n const se::cuda::RedzoneAllocator& allocator,\n const BufferComparator& comparator, bool crash_on_checking_failure) {\n TF_RETURN_IF_ERROR(stream->BlockHostUntilDone());\n\n VLOG(3) << \"Starting autotune of GemmThunk \" << gemm->ToString();\n\n std::vector<se::blas::AlgorithmType> algorithms;\n CHECK(stream->parent()->GetBlasGemmAlgorithms(&algorithms));\n\n absl::optional<se::blas::AlgorithmType> first_algorithm;\n std::vector<AutotuneResult> profile_results;\n\n for (se::blas::AlgorithmType algorithm : algorithms) {\n \/\/ Output buffer always starts with an initial value of output_ref_buffer.\n stream->ThenMemcpy(&output_buffer, output_ref_buffer, output_buffer.size());\n se::blas::ProfileResult profile_result;\n\n \/\/ We expect GemmWithAlgorithm to fail sometimes -- in fact, it will fail\n \/\/ for all algorithms if we're targeting < sm_50. But because we pass a\n \/\/ non-null ProfileResult, DoGemmWithAlgorithm should always return true,\n \/\/ and the actual success-ness is returned in ProfileResult::is_valid.\n CHECK(RunGemm(gemm, lhs_buffer, rhs_buffer, output_buffer, stream,\n \/*implements_whole_instruction=*\/true,\n \/*profiler=*\/nullptr,\n \/*profile_result=*\/&profile_result, algorithm)\n .ok());\n\n if (!profile_result.is_valid()) {\n \/\/ Unsupported algorithm.\n continue;\n }\n\n profile_results.emplace_back();\n AutotuneResult& result = profile_results.back();\n result.mutable_gemm()->set_algorithm(algorithm);\n\n VLOG(2) << \"cublas gemm algorithm \" << algorithm << \" took \"\n << profile_result.elapsed_time_in_ms() << \"ms\" << std::endl;\n\n *result.mutable_run_time() = tensorflow::proto_utils::ToDurationProto(\n absl::Milliseconds(profile_result.elapsed_time_in_ms()));\n\n TF_ASSIGN_OR_RETURN(\n se::cuda::RedzoneAllocator::RedzoneCheckStatus rz_check_status,\n allocator.CheckRedzones(stream));\n if (!rz_check_status.ok()) {\n result.mutable_failure()->set_kind(AutotuneResult::REDZONE_MODIFIED);\n *result.mutable_failure()->mutable_msg() =\n rz_check_status.RedzoneFailureMsg();\n LOG(ERROR) << \"Detected cuBLAS out-of-bounds write in gemm buffer\";\n CHECK(!crash_on_checking_failure);\n continue;\n }\n\n if (!first_algorithm) {\n \/\/ First run: set the reference result buffer.\n CHECK(reference_result_buffer.size() == output_buffer.size());\n stream->ThenMemcpy(&reference_result_buffer, output_buffer,\n output_buffer.size());\n first_algorithm.emplace(algorithm);\n } else {\n \/\/ Perform the comparison.\n TF_ASSIGN_OR_RETURN(bool compare_result,\n comparator.CompareEqual(stream, output_buffer,\n reference_result_buffer));\n if (!compare_result) {\n LOG(ERROR) << \"Results mismatch between different GEMM algorithms. \"\n << \"This is likely a bug\/unexpected loss of precision \"\n << \"in cuBLAS.\";\n CHECK(!crash_on_checking_failure);\n\n result.mutable_failure()->set_kind(AutotuneResult::WRONG_RESULT);\n result.mutable_failure()->mutable_reference_gemm()->set_algorithm(\n *first_algorithm);\n }\n }\n }\n\n tensorflow::AutotuningLog log;\n for (const AutotuneResult& profile : profile_results) {\n *log.add_results() = profile;\n }\n if (!crash_on_checking_failure) {\n tensorflow::Logger::Singleton()->LogProto(log);\n }\n\n \/\/ Choose fastest correct GEMM, but allow for incorrect results (since the\n \/\/ reference result is chosen arbitrary).\n auto has_failure = [](const AutotuneResult& r) {\n return r.has_failure() &&\n r.failure().kind() != AutotuneResult::WRONG_RESULT;\n };\n\n auto result_comparison_key = [&has_failure](const AutotuneResult& r) {\n return std::make_tuple(\n has_failure(r),\n tensorflow::proto_utils::FromDurationProto(r.run_time()));\n };\n const auto& best_result = absl::c_min_element(\n profile_results,\n [&](const AutotuneResult& lhs, const AutotuneResult& rhs) {\n return result_comparison_key(lhs) < result_comparison_key(rhs);\n });\n\n if (best_result != profile_results.end() && !has_failure(*best_result)) {\n return {best_result->gemm().algorithm()};\n }\n\n VLOG(1) << \"Unable to autotune cuBLAS gemm on stream \" << stream\n << \" none of the \" << algorithms.size() << \" ran successfully\";\n return {absl::nullopt};\n}\n\nstatic StatusOr<absl::optional<se::blas::AlgorithmType>> DoGemmAutotune(\n const HloInstruction* instr, const HloInstruction* lhs,\n const HloInstruction* rhs, se::DeviceMemoryBase lhs_buffer,\n se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer,\n se::DeviceMemoryBase reference_result_buffer,\n se::DeviceMemoryBase output_ref_buffer, se::Stream* stream,\n bool crash_on_checking_failure, const se::cuda::RedzoneAllocator& allocator,\n const BufferComparator& comparator) {\n \/\/ Don't run autotuning concurrently on the same GPU.\n tensorflow::mutex_lock gpu_lock = LockGpu(stream->parent());\n\n GemmBackendConfig gemm_config =\n instr->backend_config<GemmBackendConfig>().ValueOrDie();\n\n GemmCacheKey key =\n std::make_tuple(stream->parent(), lhs->shape(), rhs->shape(),\n instr->shape(), gemm_config.SerializeAsString());\n\n tensorflow::mutex_lock cache_lock(autotune_cache_mu);\n auto it = autotune_cache.find(key);\n int64 autotuning_requests = cache_hits + cache_misses;\n if (autotuning_requests && autotuning_requests % 10 == 0) {\n VLOG(2) << \"Autotuning cache hits\/(hits + misses): \" << cache_hits << \"\/\"\n << autotuning_requests;\n }\n\n if (it != autotune_cache.end()) {\n cache_hits++;\n VLOG(4) << \"Autotuning cache hit, using algorithm: \"\n << (it->second.has_value() ? absl::StrCat(it->second.value())\n : \"<generic>\");\n return it->second;\n }\n cache_misses++;\n VLOG(4) << \"Autotuning cache miss\";\n\n int64 batch_size = gemm_config.batch_size();\n absl::optional<se::blas::AlgorithmType> result;\n if (batch_size != 1) {\n \/\/ TODO(b\/112111608): Implement auto tune for batched gemm.\n VLOG(2) << \"Batch size is non-singular, using generic algorithm\";\n result = absl::nullopt;\n } else {\n TF_ASSIGN_OR_RETURN(\n result, DoUncachedGemmAutotune(instr, lhs_buffer, rhs_buffer,\n output_buffer, reference_result_buffer,\n output_ref_buffer, stream, allocator,\n comparator, crash_on_checking_failure));\n }\n\n CHECK(autotune_cache.emplace(key, result).second);\n return result;\n}\n\nstatic StatusOr<bool> RunOnInstruction(HloInstruction* instr,\n se::StreamExecutor* executor,\n se::DeviceMemoryAllocator* allocator) {\n se::Stream stream{executor};\n stream.Init();\n\n if (allocator == nullptr) {\n allocator = executor->GetAllocator();\n }\n\n const HloModuleConfig& hlo_module_config = instr->GetModule()->config();\n se::cuda::RedzoneAllocator input_output_allocator(\n executor->device_ordinal(), allocator,\n PtxOptsFromConfig(hlo_module_config));\n\n BufferComparator comparator(instr->shape(), hlo_module_config);\n\n int64 rng_state = 0;\n auto get_initialized_buffer =\n [&](const HloInstruction* op) -> StatusOr<se::DeviceMemoryBase> {\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase buffer,\n input_output_allocator.AllocateBytes(\n &stream, ShapeUtil::ByteSizeOf(op->shape())));\n InitializeFloatBuffer(&stream, op->shape().element_type(), &rng_state,\n buffer);\n return buffer;\n };\n\n GemmBackendConfig gemm_config =\n instr->backend_config<GemmBackendConfig>().ValueOrDie();\n const HloInstruction* lhs = instr->operand(0);\n const HloInstruction* rhs = instr->operand(1);\n\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase lhs_buffer,\n get_initialized_buffer(lhs));\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase rhs_buffer,\n get_initialized_buffer(rhs));\n TF_ASSIGN_OR_RETURN( \/\/ FIXME initialization not necessary\n se::DeviceMemoryBase output_buffer, get_initialized_buffer(instr));\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase reference_result_buffer,\n get_initialized_buffer(instr));\n TF_ASSIGN_OR_RETURN( \/\/ FIXME initialization not necessary\n se::DeviceMemoryBase output_ref_buffer, get_initialized_buffer(instr));\n\n const DebugOptions& debug_options =\n instr->GetModule()->config().debug_options();\n\n const bool crash_on_checking_failure =\n debug_options.xla_gpu_crash_on_verification_failures();\n\n TF_ASSIGN_OR_RETURN(\n absl::optional<se::blas::AlgorithmType> gemm_algorithm,\n DoGemmAutotune(instr, lhs, rhs, lhs_buffer, rhs_buffer, output_buffer,\n reference_result_buffer, output_ref_buffer, &stream,\n crash_on_checking_failure, input_output_allocator,\n comparator));\n\n \/\/ We update instruction->backend_config(); if no algorithms are supported,\n \/\/ a different API is used, which does not require specifying an algorithm.\n GemmBackendConfig updated_config = gemm_config;\n if (gemm_algorithm) {\n updated_config.set_selected_algorithm(*gemm_algorithm);\n }\n TF_RETURN_IF_ERROR(instr->set_backend_config(updated_config));\n return updated_config.SerializeAsString() != gemm_config.SerializeAsString();\n}\n\nstatic StatusOr<bool> RunOnComputation(HloComputation* computation,\n se::StreamExecutor* se,\n se::DeviceMemoryAllocator* allocator) {\n bool changed = false;\n for (HloInstruction* instr : computation->instructions()) {\n if (IsCublasGemm(*instr)) {\n TF_ASSIGN_OR_RETURN(bool result, RunOnInstruction(instr, se, allocator));\n changed |= result;\n }\n }\n return changed;\n}\n\nStatusOr<bool> GemmAlgorithmPicker::Run(HloModule* module) {\n XLA_SCOPED_LOGGING_TIMER(\"GemmAlgorithmPicker\");\n\n if (module->config().debug_options().xla_gpu_disable_autotune()) {\n VLOG(2) << \"GEMM auto-tuning disabled, GemmAlgorithmPicker returning early\";\n return false;\n }\n\n bool changed = false;\n for (HloComputation* computation : module->MakeNonfusionComputations()) {\n TF_ASSIGN_OR_RETURN(\n bool result, RunOnComputation(computation, stream_exec_, allocator_));\n changed |= result;\n }\n return changed;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<commit_msg>[XLA GPU] Do not allocate the reference output buffer during GEMM autotuning<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_algorithm_picker.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/backend_configs.pb.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/buffer_comparator.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_thunk.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/stream_executor_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instructions.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/logger.h\"\n#include \"tensorflow\/core\/protobuf\/autotuning.pb.h\"\n#include \"tensorflow\/core\/util\/proto\/proto_utils.h\"\n#include \"tensorflow\/stream_executor\/blas.h\"\n#include \"tensorflow\/stream_executor\/cuda\/redzone_allocator.h\"\n#include \"tensorflow\/stream_executor\/device_memory.h\"\n#include \"tensorflow\/stream_executor\/device_memory_allocator.h\"\n\nnamespace xla {\nnamespace gpu {\n\nusing tensorflow::AutotuneResult;\n\nusing GemmCacheKey =\n std::tuple<se::StreamExecutor*, Shape, Shape, Shape, std::string>;\n\nstatic tensorflow::mutex autotune_cache_mu(tensorflow::LINKER_INITIALIZED);\nstatic auto& autotune_cache GUARDED_BY(autotune_cache_mu) =\n *new absl::flat_hash_map<GemmCacheKey,\n absl::optional<se::blas::AlgorithmType>>();\nstatic int64 cache_hits GUARDED_BY(autotune_cache_mu) = 0;\nstatic int64 cache_misses GUARDED_BY(autotune_cache_mu) = 0;\n\n\/\/ Experimentally tries to pick the best algorithm for the given gemm.\n\/\/\n\/\/ This may fail under perfectly normal circumstances. In particular, it will\n\/\/ fail if the program was built with < CUDA 8 or if we're using a gpu older\n\/\/ than sm_50 -- in both cases, cublas doesn't support gemm-with-algorithm at\n\/\/ all.\nstatic StatusOr<absl::optional<se::blas::AlgorithmType>> DoUncachedGemmAutotune(\n const HloInstruction* gemm, se::DeviceMemoryBase lhs_buffer,\n se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer,\n se::DeviceMemoryBase reference_result_buffer, se::Stream* stream,\n const se::cuda::RedzoneAllocator& allocator,\n const BufferComparator& comparator, bool crash_on_checking_failure) {\n TF_RETURN_IF_ERROR(stream->BlockHostUntilDone());\n\n VLOG(3) << \"Starting autotune of GemmThunk \" << gemm->ToString();\n\n std::vector<se::blas::AlgorithmType> algorithms;\n CHECK(stream->parent()->GetBlasGemmAlgorithms(&algorithms));\n\n absl::optional<se::blas::AlgorithmType> first_algorithm;\n std::vector<AutotuneResult> profile_results;\n\n for (se::blas::AlgorithmType algorithm : algorithms) {\n \/\/ Make sure the output buffer always has the same value if we use\n \/\/ the bias parameter.\n if (gemm->backend_config<GemmBackendConfig>().ValueOrDie().beta() != 0) {\n int64 rng_state = 0;\n InitializeFloatBuffer(stream, gemm->shape().element_type(), &rng_state,\n output_buffer);\n }\n se::blas::ProfileResult profile_result;\n\n \/\/ We expect GemmWithAlgorithm to fail sometimes -- in fact, it will fail\n \/\/ for all algorithms if we're targeting < sm_50. But because we pass a\n \/\/ non-null ProfileResult, DoGemmWithAlgorithm should always return true,\n \/\/ and the actual success-ness is returned in ProfileResult::is_valid.\n CHECK(RunGemm(gemm, lhs_buffer, rhs_buffer, output_buffer, stream,\n \/*implements_whole_instruction=*\/true,\n \/*profiler=*\/nullptr,\n \/*profile_result=*\/&profile_result, algorithm)\n .ok());\n\n if (!profile_result.is_valid()) {\n \/\/ Unsupported algorithm.\n continue;\n }\n\n profile_results.emplace_back();\n AutotuneResult& result = profile_results.back();\n result.mutable_gemm()->set_algorithm(algorithm);\n\n VLOG(2) << \"cublas gemm algorithm \" << algorithm << \" took \"\n << profile_result.elapsed_time_in_ms() << \"ms\" << std::endl;\n\n *result.mutable_run_time() = tensorflow::proto_utils::ToDurationProto(\n absl::Milliseconds(profile_result.elapsed_time_in_ms()));\n\n TF_ASSIGN_OR_RETURN(\n se::cuda::RedzoneAllocator::RedzoneCheckStatus rz_check_status,\n allocator.CheckRedzones(stream));\n if (!rz_check_status.ok()) {\n result.mutable_failure()->set_kind(AutotuneResult::REDZONE_MODIFIED);\n *result.mutable_failure()->mutable_msg() =\n rz_check_status.RedzoneFailureMsg();\n LOG(ERROR) << \"Detected cuBLAS out-of-bounds write in gemm buffer\";\n CHECK(!crash_on_checking_failure);\n continue;\n }\n\n if (!first_algorithm) {\n \/\/ First run: set the reference result buffer.\n CHECK(reference_result_buffer.size() == output_buffer.size());\n stream->ThenMemcpy(&reference_result_buffer, output_buffer,\n output_buffer.size());\n first_algorithm.emplace(algorithm);\n } else {\n \/\/ Perform the comparison.\n TF_ASSIGN_OR_RETURN(bool compare_result,\n comparator.CompareEqual(stream, output_buffer,\n reference_result_buffer));\n if (!compare_result) {\n LOG(ERROR) << \"Results mismatch between different GEMM algorithms. \"\n << \"This is likely a bug\/unexpected loss of precision \"\n << \"in cuBLAS.\";\n CHECK(!crash_on_checking_failure);\n\n result.mutable_failure()->set_kind(AutotuneResult::WRONG_RESULT);\n result.mutable_failure()->mutable_reference_gemm()->set_algorithm(\n *first_algorithm);\n }\n }\n }\n\n tensorflow::AutotuningLog log;\n for (const AutotuneResult& profile : profile_results) {\n *log.add_results() = profile;\n }\n if (!crash_on_checking_failure) {\n tensorflow::Logger::Singleton()->LogProto(log);\n }\n\n \/\/ Choose fastest correct GEMM, but allow for incorrect results (since the\n \/\/ reference result is chosen arbitrary).\n auto has_failure = [](const AutotuneResult& r) {\n return r.has_failure() &&\n r.failure().kind() != AutotuneResult::WRONG_RESULT;\n };\n\n auto result_comparison_key = [&has_failure](const AutotuneResult& r) {\n return std::make_tuple(\n has_failure(r),\n tensorflow::proto_utils::FromDurationProto(r.run_time()));\n };\n const auto& best_result = absl::c_min_element(\n profile_results,\n [&](const AutotuneResult& lhs, const AutotuneResult& rhs) {\n return result_comparison_key(lhs) < result_comparison_key(rhs);\n });\n\n if (best_result != profile_results.end() && !has_failure(*best_result)) {\n return {best_result->gemm().algorithm()};\n }\n\n VLOG(1) << \"Unable to autotune cuBLAS gemm on stream \" << stream\n << \" none of the \" << algorithms.size() << \" ran successfully\";\n return {absl::nullopt};\n}\n\nstatic StatusOr<absl::optional<se::blas::AlgorithmType>> DoGemmAutotune(\n const HloInstruction* instr, const HloInstruction* lhs,\n const HloInstruction* rhs, se::DeviceMemoryBase lhs_buffer,\n se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer,\n se::DeviceMemoryBase reference_result_buffer, se::Stream* stream,\n bool crash_on_checking_failure, const se::cuda::RedzoneAllocator& allocator,\n const BufferComparator& comparator) {\n \/\/ Don't run autotuning concurrently on the same GPU.\n tensorflow::mutex_lock gpu_lock = LockGpu(stream->parent());\n\n GemmBackendConfig gemm_config =\n instr->backend_config<GemmBackendConfig>().ValueOrDie();\n\n GemmCacheKey key =\n std::make_tuple(stream->parent(), lhs->shape(), rhs->shape(),\n instr->shape(), gemm_config.SerializeAsString());\n\n tensorflow::mutex_lock cache_lock(autotune_cache_mu);\n auto it = autotune_cache.find(key);\n int64 autotuning_requests = cache_hits + cache_misses;\n if (autotuning_requests && autotuning_requests % 10 == 0) {\n VLOG(2) << \"Autotuning cache hits\/(hits + misses): \" << cache_hits << \"\/\"\n << autotuning_requests;\n }\n\n if (it != autotune_cache.end()) {\n cache_hits++;\n VLOG(4) << \"Autotuning cache hit, using algorithm: \"\n << (it->second.has_value() ? absl::StrCat(it->second.value())\n : \"<generic>\");\n return it->second;\n }\n cache_misses++;\n VLOG(4) << \"Autotuning cache miss\";\n\n int64 batch_size = gemm_config.batch_size();\n absl::optional<se::blas::AlgorithmType> result;\n if (batch_size != 1) {\n \/\/ TODO(b\/112111608): Implement auto tune for batched gemm.\n VLOG(2) << \"Batch size is non-singular, using generic algorithm\";\n result = absl::nullopt;\n } else {\n TF_ASSIGN_OR_RETURN(\n result,\n DoUncachedGemmAutotune(instr, lhs_buffer, rhs_buffer, output_buffer,\n reference_result_buffer, stream, allocator,\n comparator, crash_on_checking_failure));\n }\n\n CHECK(autotune_cache.emplace(key, result).second);\n return result;\n}\n\nstatic StatusOr<bool> RunOnInstruction(HloInstruction* instr,\n se::StreamExecutor* executor,\n se::DeviceMemoryAllocator* allocator) {\n se::Stream stream{executor};\n stream.Init();\n\n if (allocator == nullptr) {\n allocator = executor->GetAllocator();\n }\n\n const HloModuleConfig& hlo_module_config = instr->GetModule()->config();\n se::cuda::RedzoneAllocator input_output_allocator(\n executor->device_ordinal(), allocator,\n PtxOptsFromConfig(hlo_module_config));\n\n BufferComparator comparator(instr->shape(), hlo_module_config);\n\n int64 rng_state = 0;\n auto get_initialized_buffer =\n [&](const HloInstruction* op) -> StatusOr<se::DeviceMemoryBase> {\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase buffer,\n input_output_allocator.AllocateBytes(\n &stream, ShapeUtil::ByteSizeOf(op->shape())));\n InitializeFloatBuffer(&stream, op->shape().element_type(), &rng_state,\n buffer);\n return buffer;\n };\n\n GemmBackendConfig gemm_config =\n instr->backend_config<GemmBackendConfig>().ValueOrDie();\n const HloInstruction* lhs = instr->operand(0);\n const HloInstruction* rhs = instr->operand(1);\n\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase lhs_buffer,\n get_initialized_buffer(lhs));\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase rhs_buffer,\n get_initialized_buffer(rhs));\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase output_buffer,\n get_initialized_buffer(instr));\n TF_ASSIGN_OR_RETURN(se::DeviceMemoryBase reference_result_buffer,\n get_initialized_buffer(instr));\n\n const DebugOptions& debug_options =\n instr->GetModule()->config().debug_options();\n\n const bool crash_on_checking_failure =\n debug_options.xla_gpu_crash_on_verification_failures();\n\n TF_ASSIGN_OR_RETURN(absl::optional<se::blas::AlgorithmType> gemm_algorithm,\n DoGemmAutotune(instr, lhs, rhs, lhs_buffer, rhs_buffer,\n output_buffer, reference_result_buffer,\n &stream, crash_on_checking_failure,\n input_output_allocator, comparator));\n\n \/\/ We update instruction->backend_config(); if no algorithms are supported,\n \/\/ a different API is used, which does not require specifying an algorithm.\n GemmBackendConfig updated_config = gemm_config;\n if (gemm_algorithm) {\n updated_config.set_selected_algorithm(*gemm_algorithm);\n }\n TF_RETURN_IF_ERROR(instr->set_backend_config(updated_config));\n return updated_config.SerializeAsString() != gemm_config.SerializeAsString();\n}\n\nstatic StatusOr<bool> RunOnComputation(HloComputation* computation,\n se::StreamExecutor* se,\n se::DeviceMemoryAllocator* allocator) {\n bool changed = false;\n for (HloInstruction* instr : computation->instructions()) {\n if (IsCublasGemm(*instr)) {\n TF_ASSIGN_OR_RETURN(bool result, RunOnInstruction(instr, se, allocator));\n changed |= result;\n }\n }\n return changed;\n}\n\nStatusOr<bool> GemmAlgorithmPicker::Run(HloModule* module) {\n XLA_SCOPED_LOGGING_TIMER(\"GemmAlgorithmPicker\");\n\n if (module->config().debug_options().xla_gpu_disable_autotune()) {\n VLOG(2) << \"GEMM auto-tuning disabled, GemmAlgorithmPicker returning early\";\n return false;\n }\n\n bool changed = false;\n for (HloComputation* computation : module->MakeNonfusionComputations()) {\n TF_ASSIGN_OR_RETURN(\n bool result, RunOnComputation(computation, stream_exec_, allocator_));\n changed |= result;\n }\n return changed;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/learning\/PatternMiner\/PatternMiner.h\n *\n * Copyright (C) 2012 by OpenCog Foundation\n * All Rights Reserved\n *\n * Written by Shujing Ke <rainkekekeke@gmail.com> Scott Jones <troy.scott.j@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n#include <thread>\n#include <sstream>\n#include <map>\n#include <iterator>\n#include <opencog\/atomspace\/atom_types.h>\n#include <opencog\/util\/StringManipulator.h>\n#include <opencog\/util\/foreach.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"PatternMiner.h\"\n\nusing namespace opencog::PatternMining;\nusing namespace opencog;\n\nPatternMiner::PatternMiner(AtomSpace* _originalAtomSpace): originalAtomSpace(_originalAtomSpace)\n{\n htree = new HTree();\n atomSpace = new AtomSpace();\n\n unsigned int system_thread_num = std::thread::hardware_concurrency();\n if (system_thread_num > 2)\n THREAD_NUM = system_thread_num - 2;\n else\n THREAD_NUM = 1;\n\n threads = new thread[THREAD_NUM];\n}\n\nvoid PatternMiner::generateIndexesOfSharedVars(Handle& link, vector<Handle>& orderedHandles, vector < vector<int> >& indexes)\n{\n HandleSeq outgoingLinks = atomSpace->getOutgoing(link);\n foreach (Handle h, outgoingLinks)\n {\n if (atomSpace->isNode(h))\n {\n if (atomSpace->getType(h) == opencog::VARIABLE_NODE)\n {\n string var_name = atomSpace->getName(h);\n\n vector<int> indexesForCurVar;\n int index = 0;\n\n foreach (Handle oh,orderedHandles)\n {\n string ohStr = atomSpace->atomAsString(oh);\n if (ohStr.find(var_name) != std::string::npos)\n {\n indexesForCurVar.push_back(index);\n }\n\n index ++;\n }\n\n indexes.push_back(indexesForCurVar);\n }\n }\n else\n generateIndexesOfSharedVars(h,orderedHandles,indexes);\n }\n}\n\nvoid PatternMiner::findAndRenameVariablesForOneLink(Handle link, map<Handle,Handle>& varNameMap, HandleSeq& renameOutgoingLinks)\n{\n\n HandleSeq outgoingLinks = atomSpace->getOutgoing(link);\n\n foreach (Handle h, outgoingLinks)\n {\n if (atomSpace->isNode(h))\n {\n if (atomSpace->getType(h) == opencog::VARIABLE_NODE)\n {\n if (varNameMap.find(h) != varNameMap.end())\n {\n renameOutgoingLinks.push_back(varNameMap[h]);\n }\n else\n {\n string var_name = \"$var_\" + toString(varNameMap.size() + 1);\n Handle var_node = atomSpace->addNode(opencog::VARIABLE_NODE, var_name, TruthValue::TRUE_TV());\n varNameMap.insert(std::pair<Handle,Handle>(h,var_node));\n renameOutgoingLinks.push_back(var_node);\n\n }\n\n }\n }\n else\n {\n HandleSeq _renameOutgoingLinks;\n findAndRenameVariablesForOneLink(h, varNameMap, _renameOutgoingLinks);\n Handle reLink = atomSpace->addLink(atomSpace->getType(h),_renameOutgoingLinks,TruthValue::TRUE_TV());\n renameOutgoingLinks.push_back(reLink);\n\n }\n\n }\n\n}\n\nvector<Handle> PatternMiner::RebindVariableNames(vector<Handle>& orderedPattern)\n{\n map<Handle,Handle> varNameMap;\n vector<Handle> rebindedPattern;\n\n foreach (Handle link, orderedPattern)\n {\n HandleSeq renameOutgoingLinks;\n findAndRenameVariablesForOneLink(link, varNameMap, renameOutgoingLinks);\n Handle rebindedLink = atomSpace->addLink(atomSpace->getType(link),renameOutgoingLinks,TruthValue::TRUE_TV());\n rebindedPattern.push_back(rebindedLink);\n }\n\n return rebindedPattern;\n}\n\n\/\/ the input links should be like: only specify the const node, all the variable node name should not be specified:\nvector<Handle> PatternMiner::UnifyPatternOrder(vector<Handle>& inputPattern)\n{\n\n \/\/ Step 1: take away all the variable names, make the pattern into such format string:\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (ConceptNode \"Animal\")\n\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (VariableNode )\n\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (VariableNode )\n\n \/\/ (EvaluationLink (stv 1 1)\n \/\/ (PredicateNode \"like_food\")\n \/\/ (ListLink\n \/\/ (VariableNode )\n \/\/ (ConceptNode \"meat\")\n \/\/ )\n \/\/ )\n\n multimap<string, Handle> nonVarStrToHandleMap;\n\n foreach (Handle inputH, inputPattern)\n {\n string str = atomSpace->atomAsString(inputH);\n string nonVarNameString = \"\";\n std::stringstream stream(str);\n string oneLine;\n\n while(std::getline(stream, oneLine,'\\n'))\n {\n if (oneLine.find(\"VariableNode\")==std::string::npos)\n {\n \/\/ this node is not a VariableNode, just keep this line\n nonVarNameString += oneLine;\n }\n else\n {\n \/\/ this node is an VariableNode, remove the name, just keep \"VariableNode\"\n nonVarNameString += \"VariableNode\\n\";\n }\n }\n\n nonVarStrToHandleMap.insert(std::pair<string, Handle>(nonVarNameString,inputH));\n }\n\n \/\/ Step 2: sort the order of all the handls do not share the same string key with other handls\n \/\/ becasue the strings are put into a map , so they are already sorted.\n \/\/ now print the Handles that do not share the same key with other Handles into a vector, left the Handles share the same keys\n\n vector<Handle> orderedHandles;\n vector<string> duplicateStrs;\n multimap<string, Handle>::iterator it;\n for(it = nonVarStrToHandleMap.begin(); it != nonVarStrToHandleMap.end();)\n {\n int count = nonVarStrToHandleMap.count(it->first);\n if (count == 1)\n {\n \/\/ if this key string has only one record , just put the corresponding handle to the end of orderedHandles\n orderedHandles.push_back(it->second);\n it ++;\n }\n else\n {\n \/\/ this key string has multiple handles to it, not put these handles into the orderedHandles,\n \/\/ insteadly put this key string into duplicateStrs\n duplicateStrs.push_back(it->first);\n it = nonVarStrToHandleMap.upper_bound(it->first);\n }\n\n }\n\n \/\/ Step 3: sort the order of the handls share the same string key with other handles\n foreach (string keyString, duplicateStrs)\n {\n \/\/ get all the corresponding handles for this key string\n multimap<string, Handle>::iterator kit;\n vector<_non_ordered_pattern> sharedSameKeyPatterns;\n for (kit = nonVarStrToHandleMap.lower_bound(keyString); kit != nonVarStrToHandleMap.upper_bound(keyString); ++ kit)\n {\n _non_ordered_pattern p;\n p.link = kit->second;\n generateIndexesOfSharedVars(p.link, orderedHandles, p.indexesOfSharedVars);\n sharedSameKeyPatterns.push_back(p);\n }\n\n std::sort(sharedSameKeyPatterns.begin(), sharedSameKeyPatterns.end());\n foreach (_non_ordered_pattern np, sharedSameKeyPatterns)\n {\n orderedHandles.push_back(np.link);\n }\n }\n\n return orderedHandles;\n\n}\n\nbool PatternMiner::checkPatternExist(const string& patternKeyStr)\n{\n if (keyStrToHTreeNodeMap.find(patternKeyStr) == keyStrToHTreeNodeMap.end())\n return false;\n else\n return true;\n\n}\n\nvoid PatternMiner::extenOnePatternTask()\n{\n static unsigned cur_gram = 1;\n\n static HandleSeq allLinks;\n originalAtomSpace.getHandlesByType(back_inserter(allLinks), (Type) LINK, true );\n\n \/\/ randomly choose one link as start\n int firstLinkIndex = rand() \/ allLinks.size() ;\n Handle firstLink = allLinks[firstLinkIndex];\n\n}\n\nvoid PatternMiner::runPatternMiner(unsigned int max_gram)\n{\n MAX_GRAM = max_gram;\n\n for (unsigned int i = 0; i < THREAD_NUM; ++ i)\n {\n threads[i] = std::thread([this]{this->extenOnePatternTask();}); \/\/ using C++11 lambda-expression\n threads[i].join();\n }\n\n srand(time(NULL));\n}\n<commit_msg>If the start atom is a ListLink, try to get another non-listlink atom as starting atom.<commit_after>\/*\n * opencog\/learning\/PatternMiner\/PatternMiner.h\n *\n * Copyright (C) 2012 by OpenCog Foundation\n * All Rights Reserved\n *\n * Written by Shujing Ke <rainkekekeke@gmail.com> Scott Jones <troy.scott.j@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n#include <thread>\n#include <sstream>\n#include <map>\n#include <iterator>\n#include <opencog\/atomspace\/atom_types.h>\n#include <opencog\/util\/StringManipulator.h>\n#include <opencog\/util\/foreach.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"PatternMiner.h\"\n\nusing namespace opencog::PatternMining;\nusing namespace opencog;\n\nPatternMiner::PatternMiner(AtomSpace* _originalAtomSpace): originalAtomSpace(_originalAtomSpace)\n{\n htree = new HTree();\n atomSpace = new AtomSpace();\n\n unsigned int system_thread_num = std::thread::hardware_concurrency();\n if (system_thread_num > 2)\n THREAD_NUM = system_thread_num - 2;\n else\n THREAD_NUM = 1;\n\n threads = new thread[THREAD_NUM];\n}\n\nvoid PatternMiner::generateIndexesOfSharedVars(Handle& link, vector<Handle>& orderedHandles, vector < vector<int> >& indexes)\n{\n HandleSeq outgoingLinks = atomSpace->getOutgoing(link);\n foreach (Handle h, outgoingLinks)\n {\n if (atomSpace->isNode(h))\n {\n if (atomSpace->getType(h) == opencog::VARIABLE_NODE)\n {\n string var_name = atomSpace->getName(h);\n\n vector<int> indexesForCurVar;\n int index = 0;\n\n foreach (Handle oh,orderedHandles)\n {\n string ohStr = atomSpace->atomAsString(oh);\n if (ohStr.find(var_name) != std::string::npos)\n {\n indexesForCurVar.push_back(index);\n }\n\n index ++;\n }\n\n indexes.push_back(indexesForCurVar);\n }\n }\n else\n generateIndexesOfSharedVars(h,orderedHandles,indexes);\n }\n}\n\nvoid PatternMiner::findAndRenameVariablesForOneLink(Handle link, map<Handle,Handle>& varNameMap, HandleSeq& renameOutgoingLinks)\n{\n\n HandleSeq outgoingLinks = atomSpace->getOutgoing(link);\n\n foreach (Handle h, outgoingLinks)\n {\n if (atomSpace->isNode(h))\n {\n if (atomSpace->getType(h) == opencog::VARIABLE_NODE)\n {\n if (varNameMap.find(h) != varNameMap.end())\n {\n renameOutgoingLinks.push_back(varNameMap[h]);\n }\n else\n {\n string var_name = \"$var_\" + toString(varNameMap.size() + 1);\n Handle var_node = atomSpace->addNode(opencog::VARIABLE_NODE, var_name, TruthValue::TRUE_TV());\n varNameMap.insert(std::pair<Handle,Handle>(h,var_node));\n renameOutgoingLinks.push_back(var_node);\n\n }\n\n }\n }\n else\n {\n HandleSeq _renameOutgoingLinks;\n findAndRenameVariablesForOneLink(h, varNameMap, _renameOutgoingLinks);\n Handle reLink = atomSpace->addLink(atomSpace->getType(h),_renameOutgoingLinks,TruthValue::TRUE_TV());\n renameOutgoingLinks.push_back(reLink);\n\n }\n\n }\n\n}\n\nvector<Handle> PatternMiner::RebindVariableNames(vector<Handle>& orderedPattern)\n{\n map<Handle,Handle> varNameMap;\n vector<Handle> rebindedPattern;\n\n foreach (Handle link, orderedPattern)\n {\n HandleSeq renameOutgoingLinks;\n findAndRenameVariablesForOneLink(link, varNameMap, renameOutgoingLinks);\n Handle rebindedLink = atomSpace->addLink(atomSpace->getType(link),renameOutgoingLinks,TruthValue::TRUE_TV());\n rebindedPattern.push_back(rebindedLink);\n }\n\n return rebindedPattern;\n}\n\n\/\/ the input links should be like: only specify the const node, all the variable node name should not be specified:\nvector<Handle> PatternMiner::UnifyPatternOrder(vector<Handle>& inputPattern)\n{\n\n \/\/ Step 1: take away all the variable names, make the pattern into such format string:\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (ConceptNode \"Animal\")\n\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (VariableNode )\n\n \/\/ (InheritanceLink\n \/\/ (VariableNode )\n \/\/ (VariableNode )\n\n \/\/ (EvaluationLink (stv 1 1)\n \/\/ (PredicateNode \"like_food\")\n \/\/ (ListLink\n \/\/ (VariableNode )\n \/\/ (ConceptNode \"meat\")\n \/\/ )\n \/\/ )\n\n multimap<string, Handle> nonVarStrToHandleMap;\n\n foreach (Handle inputH, inputPattern)\n {\n string str = atomSpace->atomAsString(inputH);\n string nonVarNameString = \"\";\n std::stringstream stream(str);\n string oneLine;\n\n while(std::getline(stream, oneLine,'\\n'))\n {\n if (oneLine.find(\"VariableNode\")==std::string::npos)\n {\n \/\/ this node is not a VariableNode, just keep this line\n nonVarNameString += oneLine;\n }\n else\n {\n \/\/ this node is an VariableNode, remove the name, just keep \"VariableNode\"\n nonVarNameString += \"VariableNode\\n\";\n }\n }\n\n nonVarStrToHandleMap.insert(std::pair<string, Handle>(nonVarNameString,inputH));\n }\n\n \/\/ Step 2: sort the order of all the handls do not share the same string key with other handls\n \/\/ becasue the strings are put into a map , so they are already sorted.\n \/\/ now print the Handles that do not share the same key with other Handles into a vector, left the Handles share the same keys\n\n vector<Handle> orderedHandles;\n vector<string> duplicateStrs;\n multimap<string, Handle>::iterator it;\n for(it = nonVarStrToHandleMap.begin(); it != nonVarStrToHandleMap.end();)\n {\n int count = nonVarStrToHandleMap.count(it->first);\n if (count == 1)\n {\n \/\/ if this key string has only one record , just put the corresponding handle to the end of orderedHandles\n orderedHandles.push_back(it->second);\n it ++;\n }\n else\n {\n \/\/ this key string has multiple handles to it, not put these handles into the orderedHandles,\n \/\/ insteadly put this key string into duplicateStrs\n duplicateStrs.push_back(it->first);\n it = nonVarStrToHandleMap.upper_bound(it->first);\n }\n\n }\n\n \/\/ Step 3: sort the order of the handls share the same string key with other handles\n foreach (string keyString, duplicateStrs)\n {\n \/\/ get all the corresponding handles for this key string\n multimap<string, Handle>::iterator kit;\n vector<_non_ordered_pattern> sharedSameKeyPatterns;\n for (kit = nonVarStrToHandleMap.lower_bound(keyString); kit != nonVarStrToHandleMap.upper_bound(keyString); ++ kit)\n {\n _non_ordered_pattern p;\n p.link = kit->second;\n generateIndexesOfSharedVars(p.link, orderedHandles, p.indexesOfSharedVars);\n sharedSameKeyPatterns.push_back(p);\n }\n\n std::sort(sharedSameKeyPatterns.begin(), sharedSameKeyPatterns.end());\n foreach (_non_ordered_pattern np, sharedSameKeyPatterns)\n {\n orderedHandles.push_back(np.link);\n }\n }\n\n return orderedHandles;\n\n}\n\nbool PatternMiner::checkPatternExist(const string& patternKeyStr)\n{\n if (keyStrToHTreeNodeMap.find(patternKeyStr) == keyStrToHTreeNodeMap.end())\n return false;\n else\n return true;\n\n}\n\nvoid PatternMiner::extenOnePatternTask()\n{\n static unsigned cur_gram = 1;\n\n static HandleSeq allLinks;\n originalAtomSpace.getHandlesByType(back_inserter(allLinks), (Type) LINK, true );\n\n \/\/ randomly choose one link for start\n Handle startLink;\n\n while(true)\n {\n int startLinkIndex = rand() \/ allLinks.size() ;\n startLink = allLinks[startLinkIndex];\n\n \/\/ if this link is listlink, try another time until get a link that is not listlink\n if (originalAtomSpace->getType(startLink) != opencog::LIST_LINK)\n break;\n }\n\n}\n\nvoid PatternMiner::runPatternMiner(unsigned int max_gram)\n{\n MAX_GRAM = max_gram;\n\n for (unsigned int i = 0; i < THREAD_NUM; ++ i)\n {\n threads[i] = std::thread([this]{this->extenOnePatternTask();}); \/\/ using C++11 lambda-expression\n threads[i].join();\n }\n\n srand(time(NULL));\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2011 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"sal\/config.h\"\n\n#include <list>\n#include <vector>\n\n#include \"boost\/noncopyable.hpp\"\n#include \"com\/sun\/star\/bridge\/XInstanceProvider.hpp\"\n#include \"cppuhelper\/exc_hlp.hxx\"\n#include \"rtl\/byteseq.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"typelib\/typedescription.hxx\"\n#include \"uno\/dispatcher.hxx\"\n\n#include \"binaryany.hxx\"\n#include \"bridge.hxx\"\n#include \"currentcontext.hxx\"\n#include \"incomingrequest.hxx\"\n#include \"specialfunctionids.hxx\"\n\nnamespace binaryurp {\n\nnamespace {\n\nnamespace css = com::sun::star;\n\n}\n\nIncomingRequest::IncomingRequest(\n rtl::Reference< Bridge > const & bridge, rtl::ByteSequence const & tid,\n rtl::OUString const & oid, css::uno::UnoInterfaceReference const & object,\n css::uno::TypeDescription const & type, sal_uInt16 functionId,\n bool synchronous, css::uno::TypeDescription const & member, bool setter,\n std::vector< BinaryAny > const & inArguments, bool currentContextMode,\n css::uno::UnoInterfaceReference const & currentContext):\n bridge_(bridge), tid_(tid), oid_(oid), object_(object), type_(type),\n functionId_(functionId), synchronous_(synchronous), member_(member),\n setter_(setter), inArguments_(inArguments),\n currentContextMode_(currentContextMode), currentContext_(currentContext)\n{\n OSL_ASSERT(bridge.is() && member.is() && member.get()->bComplete);\n}\n\nIncomingRequest::~IncomingRequest() {}\n\nvoid IncomingRequest::execute() const {\n BinaryAny ret;\n std::vector< BinaryAny > outArgs;\n bool isExc;\n try {\n bool resetCc = false;\n css::uno::UnoInterfaceReference oldCc;\n if (currentContextMode_) {\n oldCc = current_context::get();\n current_context::set(currentContext_);\n resetCc = true;\n }\n try {\n try {\n isExc = !execute_throw(&ret, &outArgs);\n } catch (std::exception & e) {\n throw css::uno::RuntimeException(\n (rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"caught C++ exception: \")) +\n rtl::OStringToOUString(\n rtl::OString(e.what()), RTL_TEXTENCODING_ASCII_US)),\n css::uno::Reference< css::uno::XInterface >());\n \/\/ best-effort string conversion\n }\n } catch (css::uno::RuntimeException &) {\n css::uno::Any exc(cppu::getCaughtException());\n ret = bridge_->mapCppToBinaryAny(exc);\n isExc = true;\n }\n if (resetCc) {\n current_context::set(oldCc);\n }\n } catch (css::uno::RuntimeException &) {\n css::uno::Any exc(cppu::getCaughtException());\n ret = bridge_->mapCppToBinaryAny(exc);\n isExc = true;\n }\n if (synchronous_) {\n bridge_->decrementActiveCalls();\n try {\n bridge_->getWriter()->queueReply(\n tid_, member_, setter_, isExc, ret, outArgs, false);\n return;\n } catch (css::uno::RuntimeException & e) {\n OSL_TRACE(\n OSL_LOG_PREFIX \"caught UNO runtime exception '%s'\",\n (rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).\n getStr()));\n } catch (std::exception & e) {\n OSL_TRACE(OSL_LOG_PREFIX \"caught C++ exception '%s'\", e.what());\n }\n bridge_->terminate();\n } else {\n if (isExc) {\n OSL_TRACE(OSL_LOG_PREFIX \"oneway method raised exception\");\n }\n bridge_->decrementCalls();\n }\n}\n\nstatic size_t size_t_round(size_t val)\n{\n return (val + (sizeof(size_t)-1)) & ~(sizeof(size_t)-1);\n}\n\nbool IncomingRequest::execute_throw(\n BinaryAny * returnValue, std::vector< BinaryAny > * outArguments) const\n{\n OSL_ASSERT(\n returnValue != 0 &&\n returnValue->getType().equals(\n css::uno::TypeDescription(\n cppu::UnoType< cppu::UnoVoidType >::get())) &&\n outArguments != 0 && outArguments->empty());\n bool isExc = false;\n switch (functionId_) {\n case SPECIAL_FUNCTION_ID_RESERVED:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n case SPECIAL_FUNCTION_ID_RELEASE:\n bridge_->releaseStub(oid_, type_);\n break;\n case SPECIAL_FUNCTION_ID_QUERY_INTERFACE:\n if (!object_.is()) {\n css::uno::Reference< css::uno::XInterface > ifc;\n css::uno::Reference< css::bridge::XInstanceProvider > prov(\n bridge_->getProvider());\n if (prov.is()) {\n try {\n ifc = prov->getInstance(oid_);\n } catch (css::container::NoSuchElementException & e) {\n OSL_TRACE(\n (OSL_LOG_PREFIX \"initial element '%s':\"\n \" NoSuchElementException '%s'\"),\n (rtl::OUStringToOString(oid_, RTL_TEXTENCODING_UTF8).\n getStr()),\n (rtl::OUStringToOString(\n e.Message, RTL_TEXTENCODING_UTF8).\n getStr()));\n }\n }\n if (ifc.is()) {\n css::uno::UnoInterfaceReference unoIfc(\n static_cast< uno_Interface * >(\n bridge_->getCppToBinaryMapping().mapInterface(\n ifc.get(),\n (css::uno::TypeDescription(\n cppu::UnoType<\n css::uno::Reference<\n css::uno::XInterface > >::get()).\n get()))),\n SAL_NO_ACQUIRE);\n *returnValue = BinaryAny(\n css::uno::TypeDescription(\n cppu::UnoType<\n css::uno::Reference<\n css::uno::XInterface > >::get()),\n &unoIfc.m_pUnoI);\n }\n break;\n }\n \/\/ fall through\n default:\n {\n OSL_ASSERT(object_.is());\n css::uno::TypeDescription retType;\n std::list< std::vector< char > > outBufs;\n std::vector< void * > args;\n switch (member_.get()->eTypeClass) {\n case typelib_TypeClass_INTERFACE_ATTRIBUTE:\n {\n css::uno::TypeDescription t(\n reinterpret_cast<\n typelib_InterfaceAttributeTypeDescription * >(\n member_.get())->\n pAttributeTypeRef);\n if (setter_) {\n OSL_ASSERT(inArguments_.size() == 1);\n args.push_back(inArguments_[0].getValue(t));\n } else {\n OSL_ASSERT(inArguments_.empty());\n retType = t;\n }\n break;\n }\n case typelib_TypeClass_INTERFACE_METHOD:\n {\n typelib_InterfaceMethodTypeDescription * mtd =\n reinterpret_cast<\n typelib_InterfaceMethodTypeDescription * >(\n member_.get());\n retType = css::uno::TypeDescription(mtd->pReturnTypeRef);\n std::vector< BinaryAny >::const_iterator i(\n inArguments_.begin());\n for (sal_Int32 j = 0; j != mtd->nParams; ++j) {\n void * p;\n if (mtd->pParams[j].bIn) {\n p = i++->getValue(\n css::uno::TypeDescription(\n mtd->pParams[j].pTypeRef));\n } else {\n outBufs.push_back(\n std::vector< char >(\n css::uno::TypeDescription(\n mtd->pParams[j].pTypeRef).\n get()->nSize));\n p = &outBufs.back()[0];\n }\n args.push_back(p);\n if (mtd->pParams[j].bOut) {\n outArguments->push_back(BinaryAny());\n }\n }\n OSL_ASSERT(i == inArguments_.end());\n break;\n }\n default:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n }\n size_t nSize = 0;\n if (retType.is())\n nSize = size_t_round(retType.get()->nSize);\n std::vector< char > retBuf(nSize);\n uno_Any exc;\n uno_Any * pexc = &exc;\n (*object_.get()->pDispatcher)(\n object_.get(), member_.get(), retBuf.empty() ? 0 : &retBuf[0],\n args.empty() ? 0 : &args[0], &pexc);\n isExc = pexc != 0;\n if (isExc) {\n *returnValue = BinaryAny(\n css::uno::TypeDescription(\n cppu::UnoType< css::uno::Any >::get()),\n &exc);\n uno_any_destruct(&exc, 0);\n } else {\n if (!retBuf.empty()) {\n *returnValue = BinaryAny(retType, &retBuf[0]);\n uno_destructData(&retBuf[0], retType.get(), 0);\n }\n if (!outArguments->empty()) {\n OSL_ASSERT(\n member_.get()->eTypeClass ==\n typelib_TypeClass_INTERFACE_METHOD);\n typelib_InterfaceMethodTypeDescription * mtd =\n reinterpret_cast<\n typelib_InterfaceMethodTypeDescription * >(\n member_.get());\n std::vector< BinaryAny >::iterator i(outArguments->begin());\n std::list< std::vector< char > >::iterator j(\n outBufs.begin());\n for (sal_Int32 k = 0; k != mtd->nParams; ++k) {\n if (mtd->pParams[k].bOut) {\n *i++ = BinaryAny(\n css::uno::TypeDescription(\n mtd->pParams[k].pTypeRef),\n args[k]);\n }\n if (!mtd->pParams[k].bIn) {\n uno_type_destructData(\n &(*j++)[0], mtd->pParams[k].pTypeRef, 0);\n }\n }\n OSL_ASSERT(i == outArguments->end());\n OSL_ASSERT(j == outBufs.end());\n }\n }\n break;\n }\n }\n return !isExc;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>round this one up too to get forms to pass<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2011 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"sal\/config.h\"\n\n#include <list>\n#include <vector>\n\n#include \"boost\/noncopyable.hpp\"\n#include \"com\/sun\/star\/bridge\/XInstanceProvider.hpp\"\n#include \"cppuhelper\/exc_hlp.hxx\"\n#include \"rtl\/byteseq.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"typelib\/typedescription.hxx\"\n#include \"uno\/dispatcher.hxx\"\n\n#include \"binaryany.hxx\"\n#include \"bridge.hxx\"\n#include \"currentcontext.hxx\"\n#include \"incomingrequest.hxx\"\n#include \"specialfunctionids.hxx\"\n\nnamespace binaryurp {\n\nnamespace {\n\nnamespace css = com::sun::star;\n\n}\n\nIncomingRequest::IncomingRequest(\n rtl::Reference< Bridge > const & bridge, rtl::ByteSequence const & tid,\n rtl::OUString const & oid, css::uno::UnoInterfaceReference const & object,\n css::uno::TypeDescription const & type, sal_uInt16 functionId,\n bool synchronous, css::uno::TypeDescription const & member, bool setter,\n std::vector< BinaryAny > const & inArguments, bool currentContextMode,\n css::uno::UnoInterfaceReference const & currentContext):\n bridge_(bridge), tid_(tid), oid_(oid), object_(object), type_(type),\n functionId_(functionId), synchronous_(synchronous), member_(member),\n setter_(setter), inArguments_(inArguments),\n currentContextMode_(currentContextMode), currentContext_(currentContext)\n{\n OSL_ASSERT(bridge.is() && member.is() && member.get()->bComplete);\n}\n\nIncomingRequest::~IncomingRequest() {}\n\nvoid IncomingRequest::execute() const {\n BinaryAny ret;\n std::vector< BinaryAny > outArgs;\n bool isExc;\n try {\n bool resetCc = false;\n css::uno::UnoInterfaceReference oldCc;\n if (currentContextMode_) {\n oldCc = current_context::get();\n current_context::set(currentContext_);\n resetCc = true;\n }\n try {\n try {\n isExc = !execute_throw(&ret, &outArgs);\n } catch (std::exception & e) {\n throw css::uno::RuntimeException(\n (rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"caught C++ exception: \")) +\n rtl::OStringToOUString(\n rtl::OString(e.what()), RTL_TEXTENCODING_ASCII_US)),\n css::uno::Reference< css::uno::XInterface >());\n \/\/ best-effort string conversion\n }\n } catch (css::uno::RuntimeException &) {\n css::uno::Any exc(cppu::getCaughtException());\n ret = bridge_->mapCppToBinaryAny(exc);\n isExc = true;\n }\n if (resetCc) {\n current_context::set(oldCc);\n }\n } catch (css::uno::RuntimeException &) {\n css::uno::Any exc(cppu::getCaughtException());\n ret = bridge_->mapCppToBinaryAny(exc);\n isExc = true;\n }\n if (synchronous_) {\n bridge_->decrementActiveCalls();\n try {\n bridge_->getWriter()->queueReply(\n tid_, member_, setter_, isExc, ret, outArgs, false);\n return;\n } catch (css::uno::RuntimeException & e) {\n OSL_TRACE(\n OSL_LOG_PREFIX \"caught UNO runtime exception '%s'\",\n (rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).\n getStr()));\n } catch (std::exception & e) {\n OSL_TRACE(OSL_LOG_PREFIX \"caught C++ exception '%s'\", e.what());\n }\n bridge_->terminate();\n } else {\n if (isExc) {\n OSL_TRACE(OSL_LOG_PREFIX \"oneway method raised exception\");\n }\n bridge_->decrementCalls();\n }\n}\n\nstatic size_t size_t_round(size_t val)\n{\n return (val + (sizeof(size_t)-1)) & ~(sizeof(size_t)-1);\n}\n\nbool IncomingRequest::execute_throw(\n BinaryAny * returnValue, std::vector< BinaryAny > * outArguments) const\n{\n OSL_ASSERT(\n returnValue != 0 &&\n returnValue->getType().equals(\n css::uno::TypeDescription(\n cppu::UnoType< cppu::UnoVoidType >::get())) &&\n outArguments != 0 && outArguments->empty());\n bool isExc = false;\n switch (functionId_) {\n case SPECIAL_FUNCTION_ID_RESERVED:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n case SPECIAL_FUNCTION_ID_RELEASE:\n bridge_->releaseStub(oid_, type_);\n break;\n case SPECIAL_FUNCTION_ID_QUERY_INTERFACE:\n if (!object_.is()) {\n css::uno::Reference< css::uno::XInterface > ifc;\n css::uno::Reference< css::bridge::XInstanceProvider > prov(\n bridge_->getProvider());\n if (prov.is()) {\n try {\n ifc = prov->getInstance(oid_);\n } catch (css::container::NoSuchElementException & e) {\n OSL_TRACE(\n (OSL_LOG_PREFIX \"initial element '%s':\"\n \" NoSuchElementException '%s'\"),\n (rtl::OUStringToOString(oid_, RTL_TEXTENCODING_UTF8).\n getStr()),\n (rtl::OUStringToOString(\n e.Message, RTL_TEXTENCODING_UTF8).\n getStr()));\n }\n }\n if (ifc.is()) {\n css::uno::UnoInterfaceReference unoIfc(\n static_cast< uno_Interface * >(\n bridge_->getCppToBinaryMapping().mapInterface(\n ifc.get(),\n (css::uno::TypeDescription(\n cppu::UnoType<\n css::uno::Reference<\n css::uno::XInterface > >::get()).\n get()))),\n SAL_NO_ACQUIRE);\n *returnValue = BinaryAny(\n css::uno::TypeDescription(\n cppu::UnoType<\n css::uno::Reference<\n css::uno::XInterface > >::get()),\n &unoIfc.m_pUnoI);\n }\n break;\n }\n \/\/ fall through\n default:\n {\n OSL_ASSERT(object_.is());\n css::uno::TypeDescription retType;\n std::list< std::vector< char > > outBufs;\n std::vector< void * > args;\n switch (member_.get()->eTypeClass) {\n case typelib_TypeClass_INTERFACE_ATTRIBUTE:\n {\n css::uno::TypeDescription t(\n reinterpret_cast<\n typelib_InterfaceAttributeTypeDescription * >(\n member_.get())->\n pAttributeTypeRef);\n if (setter_) {\n OSL_ASSERT(inArguments_.size() == 1);\n args.push_back(inArguments_[0].getValue(t));\n } else {\n OSL_ASSERT(inArguments_.empty());\n retType = t;\n }\n break;\n }\n case typelib_TypeClass_INTERFACE_METHOD:\n {\n typelib_InterfaceMethodTypeDescription * mtd =\n reinterpret_cast<\n typelib_InterfaceMethodTypeDescription * >(\n member_.get());\n retType = css::uno::TypeDescription(mtd->pReturnTypeRef);\n std::vector< BinaryAny >::const_iterator i(\n inArguments_.begin());\n for (sal_Int32 j = 0; j != mtd->nParams; ++j) {\n void * p;\n if (mtd->pParams[j].bIn) {\n p = i++->getValue(\n css::uno::TypeDescription(\n mtd->pParams[j].pTypeRef));\n } else {\n outBufs.push_back(\n std::vector< char >(size_t_round(\n css::uno::TypeDescription(\n mtd->pParams[j].pTypeRef).\n get()->nSize)));\n p = &outBufs.back()[0];\n }\n args.push_back(p);\n if (mtd->pParams[j].bOut) {\n outArguments->push_back(BinaryAny());\n }\n }\n OSL_ASSERT(i == inArguments_.end());\n break;\n }\n default:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n }\n size_t nSize = 0;\n if (retType.is())\n nSize = size_t_round(retType.get()->nSize);\n std::vector< char > retBuf(nSize);\n uno_Any exc;\n uno_Any * pexc = &exc;\n (*object_.get()->pDispatcher)(\n object_.get(), member_.get(), retBuf.empty() ? 0 : &retBuf[0],\n args.empty() ? 0 : &args[0], &pexc);\n isExc = pexc != 0;\n if (isExc) {\n *returnValue = BinaryAny(\n css::uno::TypeDescription(\n cppu::UnoType< css::uno::Any >::get()),\n &exc);\n uno_any_destruct(&exc, 0);\n } else {\n if (!retBuf.empty()) {\n *returnValue = BinaryAny(retType, &retBuf[0]);\n uno_destructData(&retBuf[0], retType.get(), 0);\n }\n if (!outArguments->empty()) {\n OSL_ASSERT(\n member_.get()->eTypeClass ==\n typelib_TypeClass_INTERFACE_METHOD);\n typelib_InterfaceMethodTypeDescription * mtd =\n reinterpret_cast<\n typelib_InterfaceMethodTypeDescription * >(\n member_.get());\n std::vector< BinaryAny >::iterator i(outArguments->begin());\n std::list< std::vector< char > >::iterator j(\n outBufs.begin());\n for (sal_Int32 k = 0; k != mtd->nParams; ++k) {\n if (mtd->pParams[k].bOut) {\n *i++ = BinaryAny(\n css::uno::TypeDescription(\n mtd->pParams[k].pTypeRef),\n args[k]);\n }\n if (!mtd->pParams[k].bIn) {\n uno_type_destructData(\n &(*j++)[0], mtd->pParams[k].pTypeRef, 0);\n }\n }\n OSL_ASSERT(i == outArguments->end());\n OSL_ASSERT(j == outBufs.end());\n }\n }\n break;\n }\n }\n return !isExc;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_MAIN\n#include \"..\/..\/..\/catch\/catch.hpp\"\n\n#include <algorithm>\n\nTEST_CASE(\"std::mismatch\") {\n std::string s = \"Was it a car or a cat I saw\";\n\n auto pair = std::mismatch(s.begin(), s.end(), s.rbegin());\n\n REQUIRE(s.begin() == pair.first);\n REQUIRE(s.rbegin() == pair.second);\n\n std::string v1 = { 2, 3, 4, 5, 6, 7, 8 };\n std::string v2 = { 2, 3, 4, 4, 6, 7, 8 };\n\n auto pair2 = std::mismatch(v1.begin(), v1.end(), v2.begin(), v2.end());\n REQUIRE(v1.begin()+3 == pair2.first);\n REQUIRE(v2.begin()+3 == pair2.second);\n}\n\n<commit_msg>Fixed std::mismatch<commit_after>#define CATCH_CONFIG_MAIN\n#include \"..\/..\/..\/catch\/catch.hpp\"\n\n#include <algorithm>\n\nTEST_CASE(\"std::mismatch\") {\n std::string s = \"wasitacaroracatisaw\";\n\n auto pair = std::mismatch(s.begin(), s.end(), s.rbegin());\n\n REQUIRE(s.end() == pair.first);\n REQUIRE(s.rend() == pair.second);\n\n std::string v1 = { 2, 3, 4, 5, 6, 7, 8 };\n std::string v2 = { 2, 3, 4, 4, 6, 7, 8 };\n\n auto pair2 = std::mismatch(v1.begin(), v1.end(), v2.begin(), v2.end());\n REQUIRE(v1.begin()+3 == pair2.first);\n REQUIRE(v2.begin()+3 == pair2.second);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\author A0112054Y\n#include \"stdafx.h\"\n\n#include \"..\/task_builder.h\"\n#include \"..\/task_serializer.h\"\n#include \"..\/state.h\"\n#include \"update_task.h\"\n\nnamespace You {\nnamespace QueryEngine {\nnamespace Internal {\nnamespace Action {\n\nResponse UpdateTask::execute(State& tasks) {\n\tauto builder = TaskBuilder::get().id(this->id);\n\tauto current = tasks.get().graph().getTask(this->id);\n\tif (this->description == Task::DEFAULT_DESCRIPTION) {\n\t\tbuilder.description(current.getDescription());\n\t} else {\n\t\tbuilder.description(this->description);\n\t}\n\tif (this->deadline != Task::DEFAULT_DEADLINE) {\n\t\tbuilder.deadline(this->deadline);\n\t}\n\tif (this->priority != Task::DEFAULT_PRIORITY) {\n\t\tbuilder.priority(this->priority);\n\t}\n\tif (this->dependencies != Task::DEFAULT_DEPENDENCIES) {\n\t\tbuilder.dependencies(this->dependencies);\n\t}\n\tTask newTask = builder;\n\tnewTask.setCompleted(this->completed);\n\ttasks.get().graph().updateTask(newTask);\n\treturn newTask;\n}\n\n} \/\/ namespace Action\n} \/\/ namespace Internal\n} \/\/ namespace QueryEngine\n} \/\/ namespace You\n<commit_msg>Fix bug in edit<commit_after>\/\/\/ \\author A0112054Y\n#include \"stdafx.h\"\n\n#include \"..\/task_builder.h\"\n#include \"..\/task_serializer.h\"\n#include \"..\/state.h\"\n#include \"update_task.h\"\n\nnamespace You {\nnamespace QueryEngine {\nnamespace Internal {\nnamespace Action {\n\nResponse UpdateTask::execute(State& tasks) {\n\tauto current = tasks.get().graph().getTask(this->id);\n\tauto builder = TaskBuilder::fromTask(current);\n\tif (this->description == Task::DEFAULT_DESCRIPTION) {\n\t\tbuilder.description(current.getDescription());\n\t} else {\n\t\tbuilder.description(this->description);\n\t}\n\tif (this->deadline != Task::DEFAULT_DEADLINE) {\n\t\tbuilder.deadline(this->deadline);\n\t}\n\tif (this->priority != Task::DEFAULT_PRIORITY) {\n\t\tbuilder.priority(this->priority);\n\t}\n\tif (this->dependencies != Task::DEFAULT_DEPENDENCIES) {\n\t\tbuilder.dependencies(this->dependencies);\n\t}\n\tTask newTask = builder;\n\tnewTask.setCompleted(this->completed);\n\ttasks.get().graph().updateTask(newTask);\n\treturn newTask;\n}\n\n} \/\/ namespace Action\n} \/\/ namespace Internal\n} \/\/ namespace QueryEngine\n} \/\/ namespace You\n<|endoftext|>"} {"text":"<commit_before>\/*------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2016 The Khronos Group Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Synchronization fence basic tests\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktSynchronizationBasicFenceTests.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vktSynchronizationUtil.hpp\"\n\n#include \"vkDefs.hpp\"\n#include \"vkPlatform.hpp\"\n#include \"vkRef.hpp\"\n#include \"vkCmdUtil.hpp\"\n\nnamespace vkt\n{\nnamespace synchronization\n{\nnamespace\n{\nusing namespace vk;\n\nstatic const deUint64\tSHORT_FENCE_WAIT\t= 1000ull;\nstatic const deUint64\tLONG_FENCE_WAIT\t\t= ~0ull;\n\ntcu::TestStatus basicOneFenceCase (Context& context)\n{\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Unique<VkFence>\t\t\tfence\t\t\t\t(createFence(vk, device, &fenceInfo));\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Created fence should be in unsignaled state\");\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 1u, &fence.get(), VK_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT\");\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Created fence should be in unsignaled state\");\n\n\tbeginCommandBuffer(vk, *cmdBuffer);\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence.get(), DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\tif (VK_SUCCESS != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Fence should be in signaled state\");\n\n\tif (VK_SUCCESS != vk.resetFences(device, 1u, &fence.get()))\n\t\treturn tcu::TestStatus::fail(\"Couldn't reset the fence\");\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Fence after reset should be in unsignaled state\");\n\n\treturn tcu::TestStatus::pass(\"Basic one fence tests passed\");\n}\n\ntcu::TestStatus basicMultiFenceCase (Context& context)\n{\n\tenum\n\t{\n\t\tFIRST_FENCE = 0,\n\t\tSECOND_FENCE\n\t};\n\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Move<VkFence>\t\t\t\tptrFence[2]\t\t\t=\n\t{\n\t\tcreateFence(vk, device, &fenceInfo),\n\t\tcreateFence(vk, device, &fenceInfo)\n\t};\n\n\tconst VkFence\t\t\t\t\tfence[2]\t\t\t=\n\t{\n\t\t*ptrFence[FIRST_FENCE],\n\t\t*ptrFence[SECOND_FENCE]\n\t};\n\n\tconst VkCommandBufferBeginInfo\tinfo\t\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\tVK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,\t\/\/ VkCommandBufferUsageFlags flags;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const VkCommandBufferInheritanceInfo* pInheritanceInfo;\n\t};\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tVK_CHECK(vk.beginCommandBuffer(*cmdBuffer, &info));\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence[FIRST_FENCE], DE_FALSE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\tif (VK_SUCCESS != vk.resetFences(device, 1u, &fence[FIRST_FENCE]))\n\t\treturn tcu::TestStatus::fail(\"Couldn't reset the fence\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[SECOND_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\treturn tcu::TestStatus::pass(\"Basic multi fence tests passed\");\n}\n\ntcu::TestStatus emptySubmitCase (Context& context)\n{\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\n\tconst VkFenceCreateInfo\t\t\tfenceCreateInfo\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t(VkFenceCreateFlags)0,\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Unique<VkFence>\t\t\tfence\t\t\t\t(createFence(vk, device, &fenceCreateInfo));\n\n\tVK_CHECK(vk.queueSubmit(queue, 0u, DE_NULL, *fence));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence.get(), DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\treturn tcu::TestStatus::pass(\"OK\");\n}\n\ntcu::TestStatus basicMultiFenceWaitAllFalseCase (Context& context)\n{\n\tenum\n\t{\n\t\tFIRST_FENCE = 0,\n\t\tSECOND_FENCE\n\t};\n\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Move<VkFence>\t\t\t\tptrFence[2]\t\t\t=\n\t{\n\t\tcreateFence(vk, device, &fenceInfo),\n\t\tcreateFence(vk, device, &fenceInfo)\n\t};\n\n\tconst VkFence\t\t\t\t\tfence[2]\t\t\t=\n\t{\n\t\t*ptrFence[FIRST_FENCE],\n\t\t*ptrFence[SECOND_FENCE]\n\t};\n\n\tconst VkCommandBufferBeginInfo\tinfo\t\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\tVK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,\t\/\/ VkCommandBufferUsageFlags flags;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const VkCommandBufferInheritanceInfo* pInheritanceInfo;\n\t};\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tVK_CHECK(vk.beginCommandBuffer(*cmdBuffer, &info));\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[SECOND_FENCE]));\n\n\t\/\/ Wait for any fence\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_FALSE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\t\/\/ Wait for all fences\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\treturn tcu::TestStatus::pass(\"Basic multi fence test without waitAll passed\");\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup* createBasicFenceTests (tcu::TestContext& testCtx)\n{\n\tde::MovePtr<tcu::TestCaseGroup> basicFenceTests(new tcu::TestCaseGroup(testCtx, \"fence\", \"Basic fence tests\"));\n\taddFunctionCase(basicFenceTests.get(),\t\"one\",\t\t\t\t\t\"Basic one fence tests\",\t\t\t\t\t\t\tbasicOneFenceCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"multi\",\t\t\t\t\"Basic multi fence tests\",\t\t\t\t\t\t\tbasicMultiFenceCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"empty_submit\",\t\t\t\"Signal a fence after an empty queue submission\",\temptySubmitCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"multi_waitall_false\",\t\"Basic multi fence test without waitAll\",\t\t\tbasicMultiFenceWaitAllFalseCase);\n\n\treturn basicFenceTests.release();\n}\n\n} \/\/ synchronization\n} \/\/ vkt\n<commit_msg>Fix basicMultiFenceWaitAllFalseCase test<commit_after>\/*------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2016 The Khronos Group Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Synchronization fence basic tests\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktSynchronizationBasicFenceTests.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vktSynchronizationUtil.hpp\"\n\n#include \"vkDefs.hpp\"\n#include \"vkPlatform.hpp\"\n#include \"vkRef.hpp\"\n#include \"vkCmdUtil.hpp\"\n\nnamespace vkt\n{\nnamespace synchronization\n{\nnamespace\n{\nusing namespace vk;\n\nstatic const deUint64\tSHORT_FENCE_WAIT\t= 1000ull;\nstatic const deUint64\tLONG_FENCE_WAIT\t\t= 10000000ull;\n\ntcu::TestStatus basicOneFenceCase (Context& context)\n{\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Unique<VkFence>\t\t\tfence\t\t\t\t(createFence(vk, device, &fenceInfo));\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Created fence should be in unsignaled state\");\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 1u, &fence.get(), VK_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT\");\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Created fence should be in unsignaled state\");\n\n\tbeginCommandBuffer(vk, *cmdBuffer);\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence.get(), DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\tif (VK_SUCCESS != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Fence should be in signaled state\");\n\n\tif (VK_SUCCESS != vk.resetFences(device, 1u, &fence.get()))\n\t\treturn tcu::TestStatus::fail(\"Couldn't reset the fence\");\n\n\tif (VK_NOT_READY != vk.getFenceStatus(device, *fence))\n\t\treturn tcu::TestStatus::fail(\"Fence after reset should be in unsignaled state\");\n\n\treturn tcu::TestStatus::pass(\"Basic one fence tests passed\");\n}\n\ntcu::TestStatus basicMultiFenceCase (Context& context)\n{\n\tenum\n\t{\n\t\tFIRST_FENCE = 0,\n\t\tSECOND_FENCE\n\t};\n\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Move<VkFence>\t\t\t\tptrFence[2]\t\t\t=\n\t{\n\t\tcreateFence(vk, device, &fenceInfo),\n\t\tcreateFence(vk, device, &fenceInfo)\n\t};\n\n\tconst VkFence\t\t\t\t\tfence[2]\t\t\t=\n\t{\n\t\t*ptrFence[FIRST_FENCE],\n\t\t*ptrFence[SECOND_FENCE]\n\t};\n\n\tconst VkCommandBufferBeginInfo\tinfo\t\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\tVK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,\t\/\/ VkCommandBufferUsageFlags flags;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const VkCommandBufferInheritanceInfo* pInheritanceInfo;\n\t};\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tVK_CHECK(vk.beginCommandBuffer(*cmdBuffer, &info));\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence[FIRST_FENCE], DE_FALSE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\tif (VK_SUCCESS != vk.resetFences(device, 1u, &fence[FIRST_FENCE]))\n\t\treturn tcu::TestStatus::fail(\"Couldn't reset the fence\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[SECOND_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\treturn tcu::TestStatus::pass(\"Basic multi fence tests passed\");\n}\n\ntcu::TestStatus emptySubmitCase (Context& context)\n{\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\n\tconst VkFenceCreateInfo\t\t\tfenceCreateInfo\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t(VkFenceCreateFlags)0,\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Unique<VkFence>\t\t\tfence\t\t\t\t(createFence(vk, device, &fenceCreateInfo));\n\n\tVK_CHECK(vk.queueSubmit(queue, 0u, DE_NULL, *fence));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 1u, &fence.get(), DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS\");\n\n\treturn tcu::TestStatus::pass(\"OK\");\n}\n\ntcu::TestStatus basicMultiFenceWaitAllFalseCase (Context& context)\n{\n\tenum\n\t{\n\t\tFIRST_FENCE = 0,\n\t\tSECOND_FENCE\n\t};\n\n\tconst DeviceInterface&\t\t\tvk\t\t\t\t\t= context.getDeviceInterface();\n\tconst VkDevice\t\t\t\t\tdevice\t\t\t\t= context.getDevice();\n\tconst VkQueue\t\t\t\t\tqueue\t\t\t\t= context.getUniversalQueue();\n\tconst deUint32\t\t\t\t\tqueueFamilyIndex\t= context.getUniversalQueueFamilyIndex();\n\tconst Unique<VkCommandPool>\t\tcmdPool\t\t\t\t(createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));\n\tconst Unique<VkCommandBuffer>\tcmdBuffer\t\t\t(makeCommandBuffer(vk, device, *cmdPool));\n\n\tconst VkFenceCreateInfo\t\t\tfenceInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_FENCE_CREATE_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ VkFenceCreateFlags flags;\n\t};\n\n\tconst Move<VkFence>\t\t\t\tptrFence[2]\t\t\t=\n\t{\n\t\tcreateFence(vk, device, &fenceInfo),\n\t\tcreateFence(vk, device, &fenceInfo)\n\t};\n\n\tconst VkFence\t\t\t\t\tfence[2]\t\t\t=\n\t{\n\t\t*ptrFence[FIRST_FENCE],\n\t\t*ptrFence[SECOND_FENCE]\n\t};\n\n\tconst VkCommandBufferBeginInfo\tinfo\t\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\tVK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,\t\/\/ VkCommandBufferUsageFlags flags;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\t\t\/\/ const VkCommandBufferInheritanceInfo* pInheritanceInfo;\n\t};\n\n\tconst VkSubmitInfo\t\t\t\tsubmitInfo\t\t\t=\n\t{\n\t\tVK_STRUCTURE_TYPE_SUBMIT_INFO,\t\t\t\/\/ VkStructureType sType;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const void* pNext;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 waitSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pWaitSemaphores;\n\t\t(const VkPipelineStageFlags*)DE_NULL,\t\/\/ const VkPipelineStageFlags* pWaitDstStageMask;\n\t\t1u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 commandBufferCount;\n\t\t&cmdBuffer.get(),\t\t\t\t\t\t\/\/ const VkCommandBuffer* pCommandBuffers;\n\t\t0u,\t\t\t\t\t\t\t\t\t\t\/\/ deUint32 signalSemaphoreCount;\n\t\tDE_NULL,\t\t\t\t\t\t\t\t\/\/ const VkSemaphore* pSignalSemaphores;\n\t};\n\n\tVK_CHECK(vk.beginCommandBuffer(*cmdBuffer, &info));\n\tendCommandBuffer(vk, *cmdBuffer);\n\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_FALSE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT for case: Wait for any fence (No fence has been signaled)\");\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT for case: Wait for all fences (No fence has been signaled)\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[SECOND_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_FALSE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS for case: Wait for any fence (Only second fence signaled)\");\n\n\tif (VK_TIMEOUT != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, SHORT_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_TIMEOUT for case: Wait for all fences (Only second fence signaled)\");\n\n\tVK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, fence[FIRST_FENCE]));\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_FALSE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS for case: Wait for any fence (All fences signaled)\");\n\n\tif (VK_SUCCESS != vk.waitForFences(device, 2u, &fence[FIRST_FENCE], DE_TRUE, LONG_FENCE_WAIT))\n\t\treturn tcu::TestStatus::fail(\"vkWaitForFences should return VK_SUCCESS for case: Wait for all fences (All fences signaled)\");\n\n\treturn tcu::TestStatus::pass(\"Basic multi fence test without waitAll passed\");\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup* createBasicFenceTests (tcu::TestContext& testCtx)\n{\n\tde::MovePtr<tcu::TestCaseGroup> basicFenceTests(new tcu::TestCaseGroup(testCtx, \"fence\", \"Basic fence tests\"));\n\taddFunctionCase(basicFenceTests.get(),\t\"one\",\t\t\t\t\t\"Basic one fence tests\",\t\t\t\t\t\t\tbasicOneFenceCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"multi\",\t\t\t\t\"Basic multi fence tests\",\t\t\t\t\t\t\tbasicMultiFenceCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"empty_submit\",\t\t\t\"Signal a fence after an empty queue submission\",\temptySubmitCase);\n\taddFunctionCase(basicFenceTests.get(),\t\"multi_waitall_false\",\t\"Basic multi fence test without waitAll\",\t\t\tbasicMultiFenceWaitAllFalseCase);\n\n\treturn basicFenceTests.release();\n}\n\n} \/\/ synchronization\n} \/\/ vkt\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\\\n**\n** tOutput.cpp: Functions for output classes tOutput and tLOutput\n**\n** (see tOutput.h for a description of these classes)\n**\n** $Id: tOutput.cpp,v 1.28 2000-06-05 21:10:00 daniel Exp $\n\\*************************************************************************\/\n\n#include \"tOutput.h\"\n\n\n\/*************************************************************************\\\n**\n** Constructor\n**\n** The constructor takes two arguments, a pointer to the mesh and\n** a reference to an open input file. It reads the base name for the\n** output files from the input file, and opens and initializes these.\n**\n** Input: meshPtr -- pointer to a tMesh object (or descendant), assumed\n** valid\n** infile -- reference to an open input file, assumed valid\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\ntOutput<tSubNode>::tOutput( tMesh<tSubNode> * meshPtr, tInputFile &infile )\n{\n assert( meshPtr > 0 );\n m = meshPtr;\n\n infile.ReadItem( baseName, \"OUTFILENAME\" );\n\n CreateAndOpenFile( &nodeofs, \".nodes\" );\n CreateAndOpenFile( &edgofs, \".edges\" );\n CreateAndOpenFile( &triofs, \".tri\" );\n CreateAndOpenFile( &zofs, \".z\" );\n CreateAndOpenFile( &vaofs, \".varea\" );\n \n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::CreateAndOpenFile\n**\n** Opens the output file stream pointed to by theOFStream, giving it the\n** name <baseName><extension>, and checks to make sure that the ofstream\n** is valid.\n**\n** Input: theOFStream -- ptr to an ofstream object\n** extension -- file name extension (e.g., \".nodes\")\n** Output: theOFStream is initialized to create an open output file\n** Assumes: extension is a null-terminated string, and the length of\n** baseName plus extension doesn't exceed kMaxNameSize+6\n** (ie, the extension is expected to be <= 6 characters)\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,\n char *extension )\n{\n char fullName[kMaxNameSize+6]; \/\/ name of file to be created\n \n strcpy( fullName, baseName );\n strcat( fullName, extension );\n theOFStream->open( fullName );\n\n if( !theOFStream->good() )\n ReportFatalError(\n \"I can't create files for output. Storage space may be exhausted.\");\n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteOutput\n**\n** This function writes information about the mesh to four files called\n** name.nodes, name.edges, name.tri, and name.z, where \"name\" is a\n** name that the user has specified in the input file and which is\n** stored in the data member baseName.\n**\n** Input: time -- time of the current output time-slice\n** Output: the node, edge, and triangle ID numbers are modified so that\n** they are numbered according to their position on the list\n** Assumes: the four file ofstreams have been opened by the constructor\n** and are valid\n**\n** TODO: deal with option for once-only printing of mesh when mesh not\n** deforming\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteOutput( double time )\n{\n tMeshListIter<tSubNode> niter( m->getNodeList() ); \/\/ node list iterator\n tMeshListIter<tEdge> eiter( m->getEdgeList() ); \/\/ edge list iterator\n tPtrListIter<tTriangle> titer( m->getTriList() ); \/\/ tri list iterator\n tNode * cn; \/\/ current node\n tEdge * ce; \/\/ current edge\n tTriangle * ct; \/\/ current triangle\n int id; \/\/ id of element (node, edge, or triangle)\n int nnodes = m->getNodeList()->getSize(); \/\/ # of nodes on list\n int nedges = m->getEdgeList()->getSize(); \/\/ \" edges \"\n int ntri = m->getTriList()->getSize(); \/\/ \" triangles \"\n\n cout << \"tOutput::WriteOutput()\\n\" << flush;\n \n \/\/ Renumber IDs in order by position on list\n for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )\n cn->setID( id );\n for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )\n ce->setID( id );\n for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )\n ct->setID( id );\n\n \/\/ Write node file, z file, and varea file\n nodeofs << \" \" << time << endl << nnodes << endl;\n zofs << \" \" << time << endl << nnodes << endl;\n vaofs << \" \" << time << endl << nnodes << endl;\n for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )\n {\n nodeofs << cn->getX() << \" \" << cn->getY() << \" \"\n << cn->getEdg()->getID() << \" \" << cn->getBoundaryFlag() << endl;\n zofs << cn->getZ() << endl;\n vaofs << cn->getVArea() << endl;\n }\n \n \/\/ Write edge file\n edgofs << \" \" << time << endl << nedges << endl;\n for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )\n edgofs << ce->getOriginPtrNC()->getID() << \" \"\n << ce->getDestinationPtrNC()->getID() << \" \"\n << ce->getCCWEdg()->getID() << endl;\n \n \/\/ Write triangle file\n int i;\n triofs << \" \" << time << endl << ntri << endl;\n for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )\n {\n for( i=0; i<=2; i++ )\n triofs << ct->pPtr(i)->getID() << \" \";\n for( i=0; i<=2; i++ )\n {\n if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << \" \";\n else triofs << \"-1 \";\n }\n triofs << ct->ePtr(0)->getID() << \" \" \n << ct->ePtr(1)->getID() << \" \" \n << ct->ePtr(2)->getID() << endl;\n }\n\n \/\/ Call virtual function to write any additional data\n WriteNodeData( time );\n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteNodeData\n**\n** This is a virtual function which can be overridden to write any\n** additional node data. The base class version does nothing.\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteNodeData( double time ) \n{}\n\n\n\/*************************************************************************\\\n**\n** tLOutput constructor\n**\n** Creates and opens a series of files for drainage areas, slopes, etc.\n**\n** Modifications:\n** - 1\/00 added \"opOpt\" and creation of veg output file (GT)\n** - added flow depth output file (GT 1\/00)\n\\*************************************************************************\/\ntemplate< class tSubNode >\ntLOutput<tSubNode>::tLOutput( tMesh<tSubNode> *meshPtr, tInputFile &infile ) \n : tOutput<tSubNode>( meshPtr, infile ) \/\/ call base-class constructor\n{\n int opOpt; \/\/ Optional modules: only output stuff when needed\n \n CreateAndOpenFile( &drareaofs, \".area\" );\n CreateAndOpenFile( &netofs, \".net\" );\n CreateAndOpenFile( &slpofs, \".slp\" );\n CreateAndOpenFile( &qofs, \".q\" );\n CreateAndOpenFile( &layofs, \".lay\" );\n CreateAndOpenFile( &texofs, \".tx\" );\n if( (opOpt = infile.ReadItem( opOpt, \"OPTVEG\" ) ) )\n CreateAndOpenFile( &vegofs, \".veg\" );\n if( (opOpt = infile.ReadItem( opOpt, \"OPTKINWAVE\" ) ) )\n CreateAndOpenFile( &flowdepofs, \".dep\" );\n if( (optTSOutput = infile.ReadItem( optTSOutput, \"OPTTSOUTPUT\" ) ) )\n CreateAndOpenFile( &vols, \".vols\" );\n \n \n}\n\n\n\/*************************************************************************\\\n**\n** tLOutput::WriteNodeData\n**\n** This overridden virtual function writes output for tLNodes, including\n** drainage areas, flow pathways, slopes, discharges, layer info, etc.\n**\n** Modifications:\n** - 1\/00 added output to veg output file (GT)\n** - added output of flow depth; made slope output for all nodes (GT 1\/00)\n\\*************************************************************************\/\n\/\/TODO: should output boundary points as well so they'll map up with nodes\n\/\/ for plotting. Means changing getSlope so it returns zero if flowedg\n\/\/ undefined\ntemplate< class tSubNode >\nvoid tLOutput<tSubNode>::WriteNodeData( double time )\n{\n tMeshListIter<tSubNode> ni( m->getNodeList() ); \/\/ node list iterator\n tSubNode *cn; \/\/ current node\n int nActiveNodes = m->getNodeList()->getActiveSize(); \/\/ # active nodes\n int nnodes = m->getNodeList()->getSize(); \/\/ total # nodes\n int i, j; \/\/ counters\n\n \/\/ Write current time in each file\n drareaofs << \" \" << time << \"\\n \" << nActiveNodes << endl;\n netofs << \" \" << time << \"\\n \" << nActiveNodes << endl;\n slpofs << \" \" << time << \"\\n \" << nnodes << endl;\n qofs << \" \" << time << \"\\n \" << nnodes << endl;\n layofs << \" \" << time << \"\\n\" << nActiveNodes << endl;\n texofs << \" \" << time << \"\\n\" << nnodes << endl;\n if( vegofs.good() ) vegofs << \" \" << time << \"\\n\" << nnodes << endl;\n if( flowdepofs.good() ) flowdepofs << \" \" << time << \"\\n\" << nnodes << endl;\n\n \/\/ Write data, including layer info\n for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )\n {\n assert( cn>0 );\n drareaofs << cn->getDrArea() << endl;\n if( cn->getDownstrmNbr() )\n netofs << cn->getDownstrmNbr()->getID() << endl;\n layofs << \" \" << cn->getNumLayer() << endl;\n i=0;\n while(i<cn->getNumLayer()){\n layofs << cn->getLayerCtime(i) << \" \" << cn->getLayerRtime(i) << \" \" << cn->getLayerEtime(i) << endl;\n layofs << cn->getLayerDepth(i) << \" \" << cn->getLayerErody(i) << \" \" << cn->getLayerSed(i) << endl;\n j=0;\n while(j<cn->getNumg()){\n layofs << cn->getLayerDgrade(i,j) << \" \";\n j++;\n }\n layofs << endl;\n i++;\n }\n }\n\n \/\/ Write discharge, vegetation, & texture data\n for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() )\n {\n if( !cn->getBoundaryFlag() ) slpofs << cn->getSlope() << endl;\n else slpofs << 0 << endl;\n qofs << cn->getQ() << endl;\n if( vegofs.good() ) vegofs << cn->getVegCover().getVeg() << endl;\n if( flowdepofs.good() ) \n flowdepofs << cn->getHydrDepth() << endl;\n if( cn->getNumg()>1 ) \/\/ temporary hack TODO\n {\n texofs << cn->getLayerDgrade(0,0)\/cn->getLayerDepth(0) << endl;\n }\n \n }\n \n}\n\n\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteTSOutput\n** This function writes the total volume of the DEM above the datum to\n** a file called name.vols, where \"name\" is a name that the user has \n** specified in the input file and which is stored in the data member\n** baseName.\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteTSOutput( double time )\n{\n tMeshListIter<tSubNode> niter( m->getNodeList() ); \/\/ node list iterator\n\n tNode * cn; \/\/ current node\n\n double volume = 0;\n\n cout << \"tOutput::WriteTSOutput()\\n\" << flush;\n \n for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )\n volume += cn.getZ()*cn.getVArea();\n \n vols << volume << endl;\n \n}\n\n<commit_msg>*** empty log message ***<commit_after>\/*************************************************************************\\\n**\n** tOutput.cpp: Functions for output classes tOutput and tLOutput\n**\n** (see tOutput.h for a description of these classes)\n**\n** $Id: tOutput.cpp,v 1.29 2000-06-05 21:14:59 daniel Exp $\n\\*************************************************************************\/\n\n#include \"tOutput.h\"\n\n\n\/*************************************************************************\\\n**\n** Constructor\n**\n** The constructor takes two arguments, a pointer to the mesh and\n** a reference to an open input file. It reads the base name for the\n** output files from the input file, and opens and initializes these.\n**\n** Input: meshPtr -- pointer to a tMesh object (or descendant), assumed\n** valid\n** infile -- reference to an open input file, assumed valid\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\ntOutput<tSubNode>::tOutput( tMesh<tSubNode> * meshPtr, tInputFile &infile )\n{\n assert( meshPtr > 0 );\n m = meshPtr;\n\n infile.ReadItem( baseName, \"OUTFILENAME\" );\n\n CreateAndOpenFile( &nodeofs, \".nodes\" );\n CreateAndOpenFile( &edgofs, \".edges\" );\n CreateAndOpenFile( &triofs, \".tri\" );\n CreateAndOpenFile( &zofs, \".z\" );\n CreateAndOpenFile( &vaofs, \".varea\" );\n \n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::CreateAndOpenFile\n**\n** Opens the output file stream pointed to by theOFStream, giving it the\n** name <baseName><extension>, and checks to make sure that the ofstream\n** is valid.\n**\n** Input: theOFStream -- ptr to an ofstream object\n** extension -- file name extension (e.g., \".nodes\")\n** Output: theOFStream is initialized to create an open output file\n** Assumes: extension is a null-terminated string, and the length of\n** baseName plus extension doesn't exceed kMaxNameSize+6\n** (ie, the extension is expected to be <= 6 characters)\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream,\n char *extension )\n{\n char fullName[kMaxNameSize+6]; \/\/ name of file to be created\n \n strcpy( fullName, baseName );\n strcat( fullName, extension );\n theOFStream->open( fullName );\n\n if( !theOFStream->good() )\n ReportFatalError(\n \"I can't create files for output. Storage space may be exhausted.\");\n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteOutput\n**\n** This function writes information about the mesh to four files called\n** name.nodes, name.edges, name.tri, and name.z, where \"name\" is a\n** name that the user has specified in the input file and which is\n** stored in the data member baseName.\n**\n** Input: time -- time of the current output time-slice\n** Output: the node, edge, and triangle ID numbers are modified so that\n** they are numbered according to their position on the list\n** Assumes: the four file ofstreams have been opened by the constructor\n** and are valid\n**\n** TODO: deal with option for once-only printing of mesh when mesh not\n** deforming\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteOutput( double time )\n{\n tMeshListIter<tSubNode> niter( m->getNodeList() ); \/\/ node list iterator\n tMeshListIter<tEdge> eiter( m->getEdgeList() ); \/\/ edge list iterator\n tPtrListIter<tTriangle> titer( m->getTriList() ); \/\/ tri list iterator\n tNode * cn; \/\/ current node\n tEdge * ce; \/\/ current edge\n tTriangle * ct; \/\/ current triangle\n int id; \/\/ id of element (node, edge, or triangle)\n int nnodes = m->getNodeList()->getSize(); \/\/ # of nodes on list\n int nedges = m->getEdgeList()->getSize(); \/\/ \" edges \"\n int ntri = m->getTriList()->getSize(); \/\/ \" triangles \"\n\n cout << \"tOutput::WriteOutput()\\n\" << flush;\n \n \/\/ Renumber IDs in order by position on list\n for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ )\n cn->setID( id );\n for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ )\n ce->setID( id );\n for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ )\n ct->setID( id );\n\n \/\/ Write node file, z file, and varea file\n nodeofs << \" \" << time << endl << nnodes << endl;\n zofs << \" \" << time << endl << nnodes << endl;\n vaofs << \" \" << time << endl << nnodes << endl;\n for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )\n {\n nodeofs << cn->getX() << \" \" << cn->getY() << \" \"\n << cn->getEdg()->getID() << \" \" << cn->getBoundaryFlag() << endl;\n zofs << cn->getZ() << endl;\n vaofs << cn->getVArea() << endl;\n }\n \n \/\/ Write edge file\n edgofs << \" \" << time << endl << nedges << endl;\n for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() )\n edgofs << ce->getOriginPtrNC()->getID() << \" \"\n << ce->getDestinationPtrNC()->getID() << \" \"\n << ce->getCCWEdg()->getID() << endl;\n \n \/\/ Write triangle file\n int i;\n triofs << \" \" << time << endl << ntri << endl;\n for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() )\n {\n for( i=0; i<=2; i++ )\n triofs << ct->pPtr(i)->getID() << \" \";\n for( i=0; i<=2; i++ )\n {\n if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << \" \";\n else triofs << \"-1 \";\n }\n triofs << ct->ePtr(0)->getID() << \" \" \n << ct->ePtr(1)->getID() << \" \" \n << ct->ePtr(2)->getID() << endl;\n }\n\n \/\/ Call virtual function to write any additional data\n WriteNodeData( time );\n \n}\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteNodeData\n**\n** This is a virtual function which can be overridden to write any\n** additional node data. The base class version does nothing.\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteNodeData( double time ) \n{}\n\n\n\/*************************************************************************\\\n**\n** tLOutput constructor\n**\n** Creates and opens a series of files for drainage areas, slopes, etc.\n**\n** Modifications:\n** - 1\/00 added \"opOpt\" and creation of veg output file (GT)\n** - added flow depth output file (GT 1\/00)\n\\*************************************************************************\/\ntemplate< class tSubNode >\ntLOutput<tSubNode>::tLOutput( tMesh<tSubNode> *meshPtr, tInputFile &infile ) \n : tOutput<tSubNode>( meshPtr, infile ) \/\/ call base-class constructor\n{\n int opOpt; \/\/ Optional modules: only output stuff when needed\n \n CreateAndOpenFile( &drareaofs, \".area\" );\n CreateAndOpenFile( &netofs, \".net\" );\n CreateAndOpenFile( &slpofs, \".slp\" );\n CreateAndOpenFile( &qofs, \".q\" );\n CreateAndOpenFile( &layofs, \".lay\" );\n CreateAndOpenFile( &texofs, \".tx\" );\n if( (opOpt = infile.ReadItem( opOpt, \"OPTVEG\" ) ) )\n CreateAndOpenFile( &vegofs, \".veg\" );\n if( (opOpt = infile.ReadItem( opOpt, \"OPTKINWAVE\" ) ) )\n CreateAndOpenFile( &flowdepofs, \".dep\" );\n if( (optTSOutput = infile.ReadItem( optTSOutput, \"OPTTSOUTPUT\" ) ) )\n CreateAndOpenFile( &vols, \".vols\" );\n \n \n}\n\n\n\/*************************************************************************\\\n**\n** tLOutput::WriteNodeData\n**\n** This overridden virtual function writes output for tLNodes, including\n** drainage areas, flow pathways, slopes, discharges, layer info, etc.\n**\n** Modifications:\n** - 1\/00 added output to veg output file (GT)\n** - added output of flow depth; made slope output for all nodes (GT 1\/00)\n\\*************************************************************************\/\n\/\/TODO: should output boundary points as well so they'll map up with nodes\n\/\/ for plotting. Means changing getSlope so it returns zero if flowedg\n\/\/ undefined\ntemplate< class tSubNode >\nvoid tLOutput<tSubNode>::WriteNodeData( double time )\n{\n tMeshListIter<tSubNode> ni( m->getNodeList() ); \/\/ node list iterator\n tSubNode *cn; \/\/ current node\n int nActiveNodes = m->getNodeList()->getActiveSize(); \/\/ # active nodes\n int nnodes = m->getNodeList()->getSize(); \/\/ total # nodes\n int i, j; \/\/ counters\n\n \/\/ Write current time in each file\n drareaofs << \" \" << time << \"\\n \" << nActiveNodes << endl;\n netofs << \" \" << time << \"\\n \" << nActiveNodes << endl;\n slpofs << \" \" << time << \"\\n \" << nnodes << endl;\n qofs << \" \" << time << \"\\n \" << nnodes << endl;\n layofs << \" \" << time << \"\\n\" << nActiveNodes << endl;\n texofs << \" \" << time << \"\\n\" << nnodes << endl;\n if( vegofs.good() ) vegofs << \" \" << time << \"\\n\" << nnodes << endl;\n if( flowdepofs.good() ) flowdepofs << \" \" << time << \"\\n\" << nnodes << endl;\n\n \/\/ Write data, including layer info\n for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )\n {\n assert( cn>0 );\n drareaofs << cn->getDrArea() << endl;\n if( cn->getDownstrmNbr() )\n netofs << cn->getDownstrmNbr()->getID() << endl;\n layofs << \" \" << cn->getNumLayer() << endl;\n i=0;\n while(i<cn->getNumLayer()){\n layofs << cn->getLayerCtime(i) << \" \" << cn->getLayerRtime(i) << \" \" << cn->getLayerEtime(i) << endl;\n layofs << cn->getLayerDepth(i) << \" \" << cn->getLayerErody(i) << \" \" << cn->getLayerSed(i) << endl;\n j=0;\n while(j<cn->getNumg()){\n layofs << cn->getLayerDgrade(i,j) << \" \";\n j++;\n }\n layofs << endl;\n i++;\n }\n }\n\n \/\/ Write discharge, vegetation, & texture data\n for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() )\n {\n if( !cn->getBoundaryFlag() ) slpofs << cn->getSlope() << endl;\n else slpofs << 0 << endl;\n qofs << cn->getQ() << endl;\n if( vegofs.good() ) vegofs << cn->getVegCover().getVeg() << endl;\n if( flowdepofs.good() ) \n flowdepofs << cn->getHydrDepth() << endl;\n if( cn->getNumg()>1 ) \/\/ temporary hack TODO\n {\n texofs << cn->getLayerDgrade(0,0)\/cn->getLayerDepth(0) << endl;\n }\n \n }\n \n}\n\n\n\n\n\/*************************************************************************\\\n**\n** tOutput::WriteTSOutput\n** This function writes the total volume of the DEM above the datum to\n** a file called name.vols, where \"name\" is a name that the user has \n** specified in the input file and which is stored in the data member\n** baseName.\n**\n\\*************************************************************************\/\ntemplate< class tSubNode >\nvoid tOutput<tSubNode>::WriteTSOutput( double time )\n{\n tMeshListIter<tSubNode> niter( m->getNodeList() ); \/\/ node list iterator\n\n tNode * cn; \/\/ current node\n\n double volume = 0;\n\n cout << \"tOutput::WriteTSOutput()\\n\" << flush;\n \n for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() )\n volume += cn->getZ()*cn->getVArea();\n \n vols << volume << endl;\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ AY-3-8910.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"AY38910.hpp\"\n\nusing namespace GI;\n\nAY38910::AY38910() :\n\t\tselected_register_(0),\n\t\ttone_counters_{0, 0, 0}, tone_periods_{0, 0, 0}, tone_outputs_{0, 0, 0},\n\t\tnoise_shift_register_(0xffff), noise_period_(0), noise_counter_(0), noise_output_(0),\n\t\tenvelope_divider_(0), envelope_period_(0), envelope_position_(0),\n\t\tmaster_divider_(0),\n\t\toutput_registers_{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} {\n\toutput_registers_[8] = output_registers_[9] = output_registers_[10] = 0;\n\n\t\/\/ set up envelope lookup tables\n\tfor(int c = 0; c < 16; c++) {\n\t\tfor(int p = 0; p < 32; p++) {\n\t\t\tswitch(c) {\n\t\t\t\tcase 0: case 1: case 2: case 3: case 9:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? (p^0xf) : 0;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t\tcase 4: case 5: case 6: case 7: case 15:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? p : 0;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 8:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 10:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ ((p < 16) ? 0xf : 0x0);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ ((p < 16) ? 0x0 : 0xf);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 11:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? (p^0xf) : 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? p : 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ set up volume lookup table\n\tfloat max_volume = 8192;\n\tfloat root_two = sqrtf(2.0f);\n\tfor(int v = 0; v < 16; v++) {\n\t\tvolumes_[v] = (int)(max_volume \/ powf(root_two, (float)(v ^ 0xf)));\n\t}\n\tvolumes_[0] = 0;\n}\n\nvoid AY38910::set_clock_rate(double clock_rate) {\n\tset_input_rate((float)clock_rate);\n}\n\nvoid AY38910::get_samples(unsigned int number_of_samples, int16_t *target) {\n\tunsigned int c = 0;\n\twhile((master_divider_&7) && c < number_of_samples) {\n\t\ttarget[c] = output_volume_;\n\t\tmaster_divider_++;\n\t\tc++;\n\t}\n\n\twhile(c < number_of_samples) {\n#define step_channel(c) \\\n\tif(tone_counters_[c]) tone_counters_[c]--;\\\n\telse {\\\n\t\ttone_outputs_[c] ^= 1;\\\n\t\ttone_counters_[c] = tone_periods_[c];\\\n\t}\n\n\t\t\/\/ update the tone channels\n\t\tstep_channel(0);\n\t\tstep_channel(1);\n\t\tstep_channel(2);\n\n#undef step_channel\n\n\t\t\/\/ ... the noise generator. This recomputes the new bit repeatedly but harmlessly, only shifting\n\t\t\/\/ it into the official 17 upon divider underflow.\n\t\tif(noise_counter_) noise_counter_--;\n\t\telse {\n\t\t\tnoise_counter_ = noise_period_;\n\t\t\tnoise_output_ ^= noise_shift_register_&1;\n\t\t\tnoise_shift_register_ |= ((noise_shift_register_ ^ (noise_shift_register_ >> 3))&1) << 17;\n\t\t\tnoise_shift_register_ >>= 1;\n\t\t}\n\n\t\t\/\/ ... and the envelope generator. Table based for pattern lookup, with a 'refill' step — a way of\n\t\t\/\/ implementing non-repeating patterns by locking them to table position 0x1f.\n\t\tif(envelope_divider_) envelope_divider_--;\n\t\telse {\n\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\tenvelope_position_ ++;\n\t\t\tif(envelope_position_ == 32) envelope_position_ = envelope_overflow_masks_[output_registers_[13]];\n\t\t}\n\n\t\tevaluate_output_volume();\n\n\t\tfor(int ic = 0; ic < 8 && c < number_of_samples; ic++) {\n\t\t\ttarget[c] = output_volume_;\n\t\t\tc++;\n\t\t\tmaster_divider_++;\n\t\t}\n\t}\n\n\tmaster_divider_ &= 7;\n}\n\nvoid AY38910::evaluate_output_volume() {\n\tint envelope_volume = envelope_shapes_[output_registers_[13]][envelope_position_];\n\n\t\/\/ The output level for a channel is:\n\t\/\/\t1 if neither tone nor noise is enabled;\n\t\/\/\t0 if either tone or noise is enabled and its value is low.\n\t\/\/ The tone\/noise enable bits use inverse logic — 0 = on, 1 = off — permitting the OR logic below.\n#define tone_level(c, tone_bit)\t\t(tone_outputs_[c] | (output_registers_[7] >> tone_bit))\n#define noise_level(c, noise_bit)\t(noise_output_ | (output_registers_[7] >> noise_bit))\n\n#define level(c, tone_bit, noise_bit)\ttone_level(c, tone_bit) & noise_level(c, noise_bit) & 1\n\tconst int channel_levels[3] = {\n\t\tlevel(0, 0, 3),\n\t\tlevel(1, 1, 4),\n\t\tlevel(2, 2, 5),\n\t};\n#undef level\n\n\t\t\/\/ Channel volume is a simple selection: if the bit at 0x10 is set, use the envelope volume; otherwise use the lower four bits\n#define channel_volume(c)\t\\\n\t((output_registers_[c] >> 4)&1) * envelope_volume + (((output_registers_[c] >> 4)&1)^1) * (output_registers_[c]&0xf)\n\n\tconst int volumes[3] = {\n\t\tchannel_volume(8),\n\t\tchannel_volume(9),\n\t\tchannel_volume(10)\n\t};\n#undef channel_volume\n\n\t\/\/ Mix additively.\n\toutput_volume_ = (int16_t)(\n\t\tvolumes_[volumes[0]] * channel_levels[0] +\n\t\tvolumes_[volumes[1]] * channel_levels[1] +\n\t\tvolumes_[volumes[2]] * channel_levels[2]\n\t);\n}\n\n#pragma mark - Register manipulation\n\nvoid AY38910::select_register(uint8_t r) {\n\tselected_register_ = r;\n}\n\nvoid AY38910::set_register_value(uint8_t value) {\n\tif(selected_register_ > 15) return;\n\tregisters_[selected_register_] = value;\n\tif(selected_register_ < 14) {\n\t\tint selected_register = selected_register_;\n\t\tenqueue([=] () {\n\t\t\tuint8_t masked_value = value;\n\t\t\tswitch(selected_register) {\n\t\t\t\tcase 0: case 2: case 4:\n\t\t\t\tcase 1: case 3: case 5: {\n\t\t\t\t\tint channel = selected_register >> 1;\n\n\t\t\t\t\tif(selected_register & 1)\n\t\t\t\t\t\ttone_periods_[channel] = (tone_periods_[channel] & 0xff) | (uint16_t)((value&0xf) << 8);\n\t\t\t\t\telse\n\t\t\t\t\t\ttone_periods_[channel] = (tone_periods_[channel] & ~0xff) | value;\n\t\t\t\t\ttone_counters_[channel] = tone_periods_[channel];\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 6:\n\t\t\t\t\tnoise_period_ = value & 0x1f;\n\t\t\t\t\tnoise_counter_ = noise_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 11:\n\t\t\t\t\tenvelope_period_ = (envelope_period_ & ~0xff) | value;\n\t\t\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 12:\n\t\t\t\t\tenvelope_period_ = (envelope_period_ & 0xff) | (int)(value << 8);\n\t\t\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 13:\n\t\t\t\t\tmasked_value &= 0xf;\n\t\t\t\t\tenvelope_position_ = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutput_registers_[selected_register] = masked_value;\n\t\t\tevaluate_output_volume();\n\t\t});\n\t}\n}\n\nuint8_t AY38910::get_register_value() {\n\t\/\/ This table ensures that bits that aren't defined within the AY are returned as 1s\n\t\/\/ when read. I can't find documentation on this and don't have a machine to test, so\n\t\/\/ this is provisionally a guess. TODO: investigate.\n\tconst uint8_t register_masks[16] = {\n\t\t0x00, 0xf0, 0x00, 0xf0, 0x00, 0xf0, 0xe0, 0x00,\n\t\t0xe0, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x00\n\t};\n\n\tif(selected_register_ > 15) return 0xff;\n\tswitch(selected_register_) {\n\t\tdefault:\treturn registers_[selected_register_] & ~register_masks[selected_register_];\n\t\tcase 14:\treturn (registers_[0x7] & 0x40) ? registers_[14] : port_inputs_[0];\n\t\tcase 15:\treturn (registers_[0x7] & 0x80) ? registers_[15] : port_inputs_[1];\n\t}\n}\n\n#pragma mark - Port handling\n\nuint8_t AY38910::get_port_output(bool port_b) {\n\treturn registers_[port_b ? 15 : 14];\n}\n\nvoid AY38910::set_port_input(bool port_b, uint8_t value) {\n\tport_inputs_[port_b ? 1 : 0] = value;\n\tupdate_bus();\n}\n\n#pragma mark - Bus handling\n\nvoid AY38910::set_data_input(uint8_t r) {\n\tdata_input_ = r;\n\tupdate_bus();\n}\n\nuint8_t AY38910::get_data_output() {\n\treturn data_output_;\n}\n\nvoid AY38910::set_control_lines(ControlLines control_lines) {\n\tswitch((int)control_lines) {\n\t\tdefault:\t\t\t\t\tcontrol_state_ = Inactive;\t\tbreak;\n\n\t\tcase (int)(BDIR | BC2 | BC1):\n\t\tcase BDIR:\n\t\tcase BC1:\t\t\t\t\tcontrol_state_ = LatchAddress;\tbreak;\n\n\t\tcase (int)(BC2 | BC1):\t\tcontrol_state_ = Read;\t\t\tbreak;\n\t\tcase (int)(BDIR | BC2):\t\tcontrol_state_ = Write;\t\t\tbreak;\n\t}\n\n\tupdate_bus();\n}\n\nvoid AY38910::update_bus() {\n\tswitch(control_state_) {\n\t\tdefault: break;\n\t\tcase LatchAddress:\tselect_register(data_input_);\t\t\tbreak;\n\t\tcase Write:\t\t\tset_register_value(data_input_);\t\tbreak;\n\t\tcase Read:\t\t\tdata_output_ = get_register_value();\tbreak;\n\t}\n}\n<commit_msg>Subjectively, this might be more correct. It definitely prevents intermediate frequencies. More research required.<commit_after>\/\/\n\/\/ AY-3-8910.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"AY38910.hpp\"\n\nusing namespace GI;\n\nAY38910::AY38910() :\n\t\tselected_register_(0),\n\t\ttone_counters_{0, 0, 0}, tone_periods_{0, 0, 0}, tone_outputs_{0, 0, 0},\n\t\tnoise_shift_register_(0xffff), noise_period_(0), noise_counter_(0), noise_output_(0),\n\t\tenvelope_divider_(0), envelope_period_(0), envelope_position_(0),\n\t\tmaster_divider_(0),\n\t\toutput_registers_{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} {\n\toutput_registers_[8] = output_registers_[9] = output_registers_[10] = 0;\n\n\t\/\/ set up envelope lookup tables\n\tfor(int c = 0; c < 16; c++) {\n\t\tfor(int p = 0; p < 32; p++) {\n\t\t\tswitch(c) {\n\t\t\t\tcase 0: case 1: case 2: case 3: case 9:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? (p^0xf) : 0;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t\tcase 4: case 5: case 6: case 7: case 15:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? p : 0;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 8:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 10:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ ((p < 16) ? 0xf : 0x0);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p & 0xf) ^ ((p < 16) ? 0x0 : 0xf);\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x00;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 11:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? (p^0xf) : 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tenvelope_shapes_[c][p] = (p < 16) ? p : 0xf;\n\t\t\t\t\tenvelope_overflow_masks_[c] = 0x1f;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ set up volume lookup table\n\tfloat max_volume = 8192;\n\tfloat root_two = sqrtf(2.0f);\n\tfor(int v = 0; v < 16; v++) {\n\t\tvolumes_[v] = (int)(max_volume \/ powf(root_two, (float)(v ^ 0xf)));\n\t}\n\tvolumes_[0] = 0;\n}\n\nvoid AY38910::set_clock_rate(double clock_rate) {\n\tset_input_rate((float)clock_rate);\n}\n\nvoid AY38910::get_samples(unsigned int number_of_samples, int16_t *target) {\n\tunsigned int c = 0;\n\twhile((master_divider_&7) && c < number_of_samples) {\n\t\ttarget[c] = output_volume_;\n\t\tmaster_divider_++;\n\t\tc++;\n\t}\n\n\twhile(c < number_of_samples) {\n#define step_channel(c) \\\n\tif(tone_counters_[c]) tone_counters_[c]--;\\\n\telse {\\\n\t\ttone_outputs_[c] ^= 1;\\\n\t\ttone_counters_[c] = tone_periods_[c];\\\n\t}\n\n\t\t\/\/ update the tone channels\n\t\tstep_channel(0);\n\t\tstep_channel(1);\n\t\tstep_channel(2);\n\n#undef step_channel\n\n\t\t\/\/ ... the noise generator. This recomputes the new bit repeatedly but harmlessly, only shifting\n\t\t\/\/ it into the official 17 upon divider underflow.\n\t\tif(noise_counter_) noise_counter_--;\n\t\telse {\n\t\t\tnoise_counter_ = noise_period_;\n\t\t\tnoise_output_ ^= noise_shift_register_&1;\n\t\t\tnoise_shift_register_ |= ((noise_shift_register_ ^ (noise_shift_register_ >> 3))&1) << 17;\n\t\t\tnoise_shift_register_ >>= 1;\n\t\t}\n\n\t\t\/\/ ... and the envelope generator. Table based for pattern lookup, with a 'refill' step — a way of\n\t\t\/\/ implementing non-repeating patterns by locking them to table position 0x1f.\n\t\tif(envelope_divider_) envelope_divider_--;\n\t\telse {\n\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\tenvelope_position_ ++;\n\t\t\tif(envelope_position_ == 32) envelope_position_ = envelope_overflow_masks_[output_registers_[13]];\n\t\t}\n\n\t\tevaluate_output_volume();\n\n\t\tfor(int ic = 0; ic < 8 && c < number_of_samples; ic++) {\n\t\t\ttarget[c] = output_volume_;\n\t\t\tc++;\n\t\t\tmaster_divider_++;\n\t\t}\n\t}\n\n\tmaster_divider_ &= 7;\n}\n\nvoid AY38910::evaluate_output_volume() {\n\tint envelope_volume = envelope_shapes_[output_registers_[13]][envelope_position_];\n\n\t\/\/ The output level for a channel is:\n\t\/\/\t1 if neither tone nor noise is enabled;\n\t\/\/\t0 if either tone or noise is enabled and its value is low.\n\t\/\/ The tone\/noise enable bits use inverse logic — 0 = on, 1 = off — permitting the OR logic below.\n#define tone_level(c, tone_bit)\t\t(tone_outputs_[c] | (output_registers_[7] >> tone_bit))\n#define noise_level(c, noise_bit)\t(noise_output_ | (output_registers_[7] >> noise_bit))\n\n#define level(c, tone_bit, noise_bit)\ttone_level(c, tone_bit) & noise_level(c, noise_bit) & 1\n\tconst int channel_levels[3] = {\n\t\tlevel(0, 0, 3),\n\t\tlevel(1, 1, 4),\n\t\tlevel(2, 2, 5),\n\t};\n#undef level\n\n\t\t\/\/ Channel volume is a simple selection: if the bit at 0x10 is set, use the envelope volume; otherwise use the lower four bits\n#define channel_volume(c)\t\\\n\t((output_registers_[c] >> 4)&1) * envelope_volume + (((output_registers_[c] >> 4)&1)^1) * (output_registers_[c]&0xf)\n\n\tconst int volumes[3] = {\n\t\tchannel_volume(8),\n\t\tchannel_volume(9),\n\t\tchannel_volume(10)\n\t};\n#undef channel_volume\n\n\t\/\/ Mix additively.\n\toutput_volume_ = (int16_t)(\n\t\tvolumes_[volumes[0]] * channel_levels[0] +\n\t\tvolumes_[volumes[1]] * channel_levels[1] +\n\t\tvolumes_[volumes[2]] * channel_levels[2]\n\t);\n}\n\n#pragma mark - Register manipulation\n\nvoid AY38910::select_register(uint8_t r) {\n\tselected_register_ = r;\n}\n\nvoid AY38910::set_register_value(uint8_t value) {\n\tif(selected_register_ > 15) return;\n\tregisters_[selected_register_] = value;\n\tif(selected_register_ < 14) {\n\t\tint selected_register = selected_register_;\n\t\tenqueue([=] () {\n\t\t\tuint8_t masked_value = value;\n\t\t\tswitch(selected_register) {\n\t\t\t\tcase 0: case 2: case 4:\n\t\t\t\tcase 1: case 3: case 5: {\n\t\t\t\t\tint channel = selected_register >> 1;\n\n\t\t\t\t\tif(selected_register & 1)\n\t\t\t\t\t\ttone_periods_[channel] = (tone_periods_[channel] & 0xff) | (uint16_t)((value&0xf) << 8);\n\t\t\t\t\telse\n\t\t\t\t\t\ttone_periods_[channel] = (tone_periods_[channel] & ~0xff) | value;\n\/\/\t\t\t\t\ttone_counters_[channel] = tone_periods_[channel];\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 6:\n\t\t\t\t\tnoise_period_ = value & 0x1f;\n\/\/\t\t\t\t\tnoise_counter_ = noise_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 11:\n\t\t\t\t\tenvelope_period_ = (envelope_period_ & ~0xff) | value;\n\/\/\t\t\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 12:\n\t\t\t\t\tenvelope_period_ = (envelope_period_ & 0xff) | (int)(value << 8);\n\/\/\t\t\t\t\tenvelope_divider_ = envelope_period_;\n\t\t\t\tbreak;\n\n\t\t\t\tcase 13:\n\t\t\t\t\tmasked_value &= 0xf;\n\t\t\t\t\tenvelope_position_ = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutput_registers_[selected_register] = masked_value;\n\t\t\tevaluate_output_volume();\n\t\t});\n\t}\n}\n\nuint8_t AY38910::get_register_value() {\n\t\/\/ This table ensures that bits that aren't defined within the AY are returned as 1s\n\t\/\/ when read. I can't find documentation on this and don't have a machine to test, so\n\t\/\/ this is provisionally a guess. TODO: investigate.\n\tconst uint8_t register_masks[16] = {\n\t\t0x00, 0xf0, 0x00, 0xf0, 0x00, 0xf0, 0xe0, 0x00,\n\t\t0xe0, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x00\n\t};\n\n\tif(selected_register_ > 15) return 0xff;\n\tswitch(selected_register_) {\n\t\tdefault:\treturn registers_[selected_register_] & ~register_masks[selected_register_];\n\t\tcase 14:\treturn (registers_[0x7] & 0x40) ? registers_[14] : port_inputs_[0];\n\t\tcase 15:\treturn (registers_[0x7] & 0x80) ? registers_[15] : port_inputs_[1];\n\t}\n}\n\n#pragma mark - Port handling\n\nuint8_t AY38910::get_port_output(bool port_b) {\n\treturn registers_[port_b ? 15 : 14];\n}\n\nvoid AY38910::set_port_input(bool port_b, uint8_t value) {\n\tport_inputs_[port_b ? 1 : 0] = value;\n\tupdate_bus();\n}\n\n#pragma mark - Bus handling\n\nvoid AY38910::set_data_input(uint8_t r) {\n\tdata_input_ = r;\n\tupdate_bus();\n}\n\nuint8_t AY38910::get_data_output() {\n\treturn data_output_;\n}\n\nvoid AY38910::set_control_lines(ControlLines control_lines) {\n\tswitch((int)control_lines) {\n\t\tdefault:\t\t\t\t\tcontrol_state_ = Inactive;\t\tbreak;\n\n\t\tcase (int)(BDIR | BC2 | BC1):\n\t\tcase BDIR:\n\t\tcase BC1:\t\t\t\t\tcontrol_state_ = LatchAddress;\tbreak;\n\n\t\tcase (int)(BC2 | BC1):\t\tcontrol_state_ = Read;\t\t\tbreak;\n\t\tcase (int)(BDIR | BC2):\t\tcontrol_state_ = Write;\t\t\tbreak;\n\t}\n\n\tupdate_bus();\n}\n\nvoid AY38910::update_bus() {\n\tswitch(control_state_) {\n\t\tdefault: break;\n\t\tcase LatchAddress:\tselect_register(data_input_);\t\t\tbreak;\n\t\tcase Write:\t\t\tset_register_value(data_input_);\t\tbreak;\n\t\tcase Read:\t\t\tdata_output_ = get_register_value();\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ AY-3-8910.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/10\/2016.\n\/\/ Copyright 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef AY_3_8910_hpp\n#define AY_3_8910_hpp\n\n#include \"..\/..\/Outputs\/Speaker\/Implementation\/SampleSource.hpp\"\n#include \"..\/..\/Concurrency\/AsyncTaskQueue.hpp\"\n\nnamespace GI {\nnamespace AY38910 {\n\n\/*!\n\tA port handler provides all input for an AY's two 8-bit ports, and may optionally receive\n\tactive notification of changes in output.\n\n\tMachines with an AY without ports or with nothing wired to them need not supply a port handler.\n\tMachines that use the AY ports as output but for which polling for changes is acceptable can\n\tinstead use AY38910.get_port_output.\n*\/\nclass PortHandler {\n\tpublic:\n\t\t\/*!\n\t\t\tRequests the current input on an AY port.\n\n\t\t\t@param port_b @c true if the input being queried is Port B. @c false if it is Port A.\n\t\t*\/\n\t\tvirtual uint8_t get_port_input(bool port_b) {\n\t\t\treturn 0xff;\n\t\t}\n\n\t\t\/*!\n\t\t\tRequests the current input on an AY port.\n\n\t\t\t@param port_b @c true if the input being queried is Port B. @c false if it is Port A.\n\t\t*\/\n\t\tvirtual void set_port_output(bool port_b, uint8_t value) {}\n};\n\n\/*!\n\tNames the control lines used as input to the AY, which uses CP1600 bus semantics.\n*\/\nenum ControlLines {\n\tBC1\t\t= (1 << 0),\n\tBC2\t\t= (1 << 1),\n\tBDIR\t= (1 << 2)\n};\n\n\/*!\n\tProvides emulation of an AY-3-8910 \/ YM2149, which is a three-channel sound chip with a\n\tnoise generator and a volume envelope generator, which also provides two bidirectional\n\tinterface ports.\n*\/\nclass AY38910: public ::Outputs::Speaker::SampleSource {\n\tpublic:\n\t\t\/\/\/ Creates a new AY38910.\n\t\tAY38910(Concurrency::DeferringAsyncTaskQueue &task_queue);\n\n\t\t\/\/\/ Sets the value the AY would read from its data lines if it were not outputting.\n\t\tvoid set_data_input(uint8_t r);\n\n\t\t\/\/\/ Gets the value that would appear on the data lines if only the AY is outputting.\n\t\tuint8_t get_data_output();\n\n\t\t\/\/\/ Sets the current control line state, as a bit field.\n\t\tvoid set_control_lines(ControlLines control_lines);\n\n\t\t\/*!\n\t\t\tGets the value that would appear on the requested interface port if it were in output mode.\n\t\t\t@parameter port_b @c true to get the value for Port B, @c false to get the value for Port A.\n\t\t*\/\n\t\tuint8_t get_port_output(bool port_b);\n\n\t\t\/*!\n\t\t\tSets the port handler, which will receive a call every time the AY either wants to sample\n\t\t\tinput or else declare new output. As a convenience, current port output can be obtained\n\t\t\twithout installing a port handler via get_port_output.\n\t\t*\/\n\t\tvoid set_port_handler(PortHandler *);\n\n\t\t\/\/ to satisfy ::Outputs::Speaker (included via ::Outputs::Filter.\n\t\tvoid get_samples(std::size_t number_of_samples, int16_t *target);\n\t\tbool is_zero_level();\n\t\tvoid set_sample_volume_range(std::int16_t range);\n\n\tprivate:\n\t\tConcurrency::DeferringAsyncTaskQueue &task_queue_;\n\n\t\tint selected_register_ = 0;\n\t\tuint8_t registers_[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\t\tuint8_t output_registers_[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\n\t\tint master_divider_ = 0;\n\n\t\tint tone_periods_[3] = {0, 0, 0};\n\t\tint tone_counters_[3] = {0, 0, 0};\n\t\tint tone_outputs_[3] = {0, 0, 0};\n\n\t\tint noise_period_ = 0;\n\t\tint noise_counter_ = 0;\n\t\tint noise_shift_register_ = 0xffff;\n\t\tint noise_output_ = 0;\n\n\t\tint envelope_period_ = 0;\n\t\tint envelope_divider_ = 0;\n\t\tint envelope_position_ = 0;\n\t\tint envelope_shapes_[16][32];\n\t\tint envelope_overflow_masks_[16];\n\n\t\tint volumes_[16];\n\n\t\tenum ControlState {\n\t\t\tInactive,\n\t\t\tLatchAddress,\n\t\t\tRead,\n\t\t\tWrite\n\t\t} control_state_;\n\n\t\tvoid select_register(uint8_t r);\n\t\tvoid set_register_value(uint8_t value);\n\t\tuint8_t get_register_value();\n\n\t\tuint8_t data_input_, data_output_;\n\n\t\tint16_t output_volume_;\n\t\tvoid evaluate_output_volume();\n\n\t\tvoid update_bus();\n\t\tPortHandler *port_handler_ = nullptr;\n\t\tvoid set_port_output(bool port_b);\n};\n\n}\n}\n\n#endif \/* AY_3_8910_hpp *\/\n<commit_msg>Corrects documentation error.<commit_after>\/\/\n\/\/ AY-3-8910.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 14\/10\/2016.\n\/\/ Copyright 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef AY_3_8910_hpp\n#define AY_3_8910_hpp\n\n#include \"..\/..\/Outputs\/Speaker\/Implementation\/SampleSource.hpp\"\n#include \"..\/..\/Concurrency\/AsyncTaskQueue.hpp\"\n\nnamespace GI {\nnamespace AY38910 {\n\n\/*!\n\tA port handler provides all input for an AY's two 8-bit ports, and may optionally receive\n\tactive notification of changes in output.\n\n\tMachines with an AY without ports or with nothing wired to them need not supply a port handler.\n\tMachines that use the AY ports as output but for which polling for changes is acceptable can\n\tinstead use AY38910.get_port_output.\n*\/\nclass PortHandler {\n\tpublic:\n\t\t\/*!\n\t\t\tRequests the current input on an AY port.\n\n\t\t\t@param port_b @c true if the input being queried is Port B. @c false if it is Port A.\n\t\t*\/\n\t\tvirtual uint8_t get_port_input(bool port_b) {\n\t\t\treturn 0xff;\n\t\t}\n\n\t\t\/*!\n\t\t\tSets the current output on an AY port.\n\n\t\t\t@param port_b @c true if the output being posted is Port B. @c false if it is Port A.\n\t\t\t@param value the value now being output.\n\t\t*\/\n\t\tvirtual void set_port_output(bool port_b, uint8_t value) {}\n};\n\n\/*!\n\tNames the control lines used as input to the AY, which uses CP1600 bus semantics.\n*\/\nenum ControlLines {\n\tBC1\t\t= (1 << 0),\n\tBC2\t\t= (1 << 1),\n\tBDIR\t= (1 << 2)\n};\n\n\/*!\n\tProvides emulation of an AY-3-8910 \/ YM2149, which is a three-channel sound chip with a\n\tnoise generator and a volume envelope generator, which also provides two bidirectional\n\tinterface ports.\n*\/\nclass AY38910: public ::Outputs::Speaker::SampleSource {\n\tpublic:\n\t\t\/\/\/ Creates a new AY38910.\n\t\tAY38910(Concurrency::DeferringAsyncTaskQueue &task_queue);\n\n\t\t\/\/\/ Sets the value the AY would read from its data lines if it were not outputting.\n\t\tvoid set_data_input(uint8_t r);\n\n\t\t\/\/\/ Gets the value that would appear on the data lines if only the AY is outputting.\n\t\tuint8_t get_data_output();\n\n\t\t\/\/\/ Sets the current control line state, as a bit field.\n\t\tvoid set_control_lines(ControlLines control_lines);\n\n\t\t\/*!\n\t\t\tGets the value that would appear on the requested interface port if it were in output mode.\n\t\t\t@parameter port_b @c true to get the value for Port B, @c false to get the value for Port A.\n\t\t*\/\n\t\tuint8_t get_port_output(bool port_b);\n\n\t\t\/*!\n\t\t\tSets the port handler, which will receive a call every time the AY either wants to sample\n\t\t\tinput or else declare new output. As a convenience, current port output can be obtained\n\t\t\twithout installing a port handler via get_port_output.\n\t\t*\/\n\t\tvoid set_port_handler(PortHandler *);\n\n\t\t\/\/ to satisfy ::Outputs::Speaker (included via ::Outputs::Filter.\n\t\tvoid get_samples(std::size_t number_of_samples, int16_t *target);\n\t\tbool is_zero_level();\n\t\tvoid set_sample_volume_range(std::int16_t range);\n\n\tprivate:\n\t\tConcurrency::DeferringAsyncTaskQueue &task_queue_;\n\n\t\tint selected_register_ = 0;\n\t\tuint8_t registers_[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\t\tuint8_t output_registers_[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\n\t\tint master_divider_ = 0;\n\n\t\tint tone_periods_[3] = {0, 0, 0};\n\t\tint tone_counters_[3] = {0, 0, 0};\n\t\tint tone_outputs_[3] = {0, 0, 0};\n\n\t\tint noise_period_ = 0;\n\t\tint noise_counter_ = 0;\n\t\tint noise_shift_register_ = 0xffff;\n\t\tint noise_output_ = 0;\n\n\t\tint envelope_period_ = 0;\n\t\tint envelope_divider_ = 0;\n\t\tint envelope_position_ = 0;\n\t\tint envelope_shapes_[16][32];\n\t\tint envelope_overflow_masks_[16];\n\n\t\tint volumes_[16];\n\n\t\tenum ControlState {\n\t\t\tInactive,\n\t\t\tLatchAddress,\n\t\t\tRead,\n\t\t\tWrite\n\t\t} control_state_;\n\n\t\tvoid select_register(uint8_t r);\n\t\tvoid set_register_value(uint8_t value);\n\t\tuint8_t get_register_value();\n\n\t\tuint8_t data_input_, data_output_;\n\n\t\tint16_t output_volume_;\n\t\tvoid evaluate_output_volume();\n\n\t\tvoid update_bus();\n\t\tPortHandler *port_handler_ = nullptr;\n\t\tvoid set_port_output(bool port_b);\n};\n\n}\n}\n\n#endif \/* AY_3_8910_hpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkIpPic.h\"\n#include \"mitkPixelType.h\"\n#include <itkVector.h>\n#include <itkRGBPixel.h>\n#include <itkRGBAPixel.h>\n#include <itkCovariantVector.h>\n#include \"itkDiffusionTensor3D.h\"\n\n#define HUNDRED_VECS(HUN) \\\n TEN_VECS(HUN) \\\n TEN_VECS(HUN+10) \\\n TEN_VECS(HUN+20) \\\n TEN_VECS(HUN+30) \\\n TEN_VECS(HUN+40) \\\n TEN_VECS(HUN+50) \\\n TEN_VECS(HUN+60) \\\n TEN_VECS(HUN+70) \\\n TEN_VECS(HUN+80) \\\n TEN_VECS(HUN+90) \\\n\n#define TEN_VECS(TEN) \\\n if(false){} \\\n N_VEC(TEN+ 1) \\\n N_VEC(TEN+ 2) \\\n N_VEC(TEN+ 3) \\\n N_VEC(TEN+ 4) \\\n N_VEC(TEN+ 5) \\\n N_VEC(TEN+ 6) \\\n N_VEC(TEN+ 7) \\\n N_VEC(TEN+ 8) \\\n N_VEC(TEN+ 9) \\\n N_VEC(TEN+10) \\\n\n#define N_VEC(N_DIRS) \\\n _N_VEC(N_DIRS,double) \\\n _N_VEC(N_DIRS,float) \\\n\n#define _N_VEC(N_DIRS,PIXTYPE) \\\n else if ( *m_TypeId == typeid( itk::Vector<PIXTYPE,N_DIRS> )) \\\n { \\\n found = true; \\\n m_TypeId = & typeid( PIXTYPE ); \\\n m_NumberOfComponents *= N_DIRS; \\\n m_Type = mitkIpPicFloat; \\\n m_Bpe = sizeof(PIXTYPE) * 8 * m_NumberOfComponents; \\\n m_ItkTypeId = &typeid( itk::Vector<PIXTYPE,N_DIRS> ); \\\n } \\\n\n\nmitk::PixelType::PixelType() : m_TypeId( NULL ), m_Type( mitkIpPicUnknown ), m_Bpe( 0 ), m_NumberOfComponents( 1 )\n{\n\n}\n\nmitk::PixelType::PixelType( const mitk::PixelType& aPixelType )\n{\n Initialize( *aPixelType.GetTypeId(), aPixelType.GetNumberOfComponents() );\n}\n\nmitk::PixelType::PixelType( const std::type_info& aTypeId, int numberOfComponents, ItkIOPixelType anItkIoPixelType ) : m_TypeId( &aTypeId ), m_NumberOfComponents( numberOfComponents )\n{\n Initialize( aTypeId, numberOfComponents, anItkIoPixelType );\n}\n\nmitk::PixelType::PixelType( mitkIpPicType_t type, int bpe, int numberOfComponents ) : m_Type( type ), m_Bpe( bpe ), m_NumberOfComponents( numberOfComponents )\n{\n Initialize( type, bpe, numberOfComponents );\n}\n\nmitk::PixelType::PixelType( const mitkIpPicDescriptor* pic ) : m_NumberOfComponents( 1 )\n{\n if ( pic != NULL )\n Initialize( pic->type, pic->bpe );\n else\n {\n m_TypeId = NULL;\n \/\/ itkExceptionMacro(\"pic.IsNull() has no pixel type.\");\n }\n}\n\nbool mitk::PixelType::operator==(const mitk::PixelType& rhs) const\n{\n LOG_INFO << \"operator==\" << std::endl;\n\nLOG_INFO << \"m_Type = \" << m_Type << \" \" << rhs.m_Type << std::endl;\nLOG_INFO << \"m_Bpe = \" << m_Bpe << \" \" << rhs.m_Bpe << std::endl;\nLOG_INFO << \"m_NumberOfComponents = \" << m_NumberOfComponents << \" \" << rhs.m_NumberOfComponents << std::endl;\nLOG_INFO << \"m_BitsPerComponent = \" << m_BitsPerComponent << \" \" << rhs.m_BitsPerComponent << std::endl;\n\n return (\n *(this->m_TypeId) == *(rhs.m_TypeId)\n && this->m_Type == rhs.m_Type\n && this->m_Bpe == rhs.m_Bpe\n && this->m_NumberOfComponents == rhs.m_NumberOfComponents\n && this->m_BitsPerComponent == rhs.m_BitsPerComponent\n );\n}\n\nbool mitk::PixelType::operator!=(const mitk::PixelType& rhs) const\n{\n return !(this->operator==(rhs));\n}\n\nbool mitk::PixelType::operator==(const std::type_info& typeId) const\n{\n if (GetItkTypeId() == NULL)\n return false;\n return (*GetItkTypeId() == typeId);\n}\n\nbool mitk::PixelType::operator!=(const std::type_info& typeId) const\n{\n return !(this->operator==(typeId));\n}\n\n#define SET_ITK_TYPE_ID(anItkIoPixelType_test, numberOfComponents_test, ITK_TYPE) \\\n if ( (itk::ImageIOBase::anItkIoPixelType_test == anItkIoPixelType ) && \\\n (numberOfComponents_test == m_NumberOfComponents) \\\n ) \\\n { \\\n m_ItkTypeId = &typeid(ITK_TYPE); \\\n }\n\n#define SET_TYPE(TYPE, IPPIC_TYPE) \\\n if ( *m_TypeId == typeid( TYPE ) ) \\\n { \\\n m_Type = IPPIC_TYPE; \\\n m_Bpe = sizeof(TYPE) * 8 * m_NumberOfComponents; \\\n \\\n typedef itk::Vector<TYPE, 3> Vector3Type; \\\n typedef itk::CovariantVector<TYPE, 3> CovariantVector3Type; \\\n typedef itk::Point<TYPE, 3> Point3Type; \\\n typedef itk::Vector<TYPE, 2> Vector2Type; \\\n typedef itk::CovariantVector<TYPE, 2> CovariantVector2Type; \\\n typedef itk::Point<TYPE, 2> Point2Type; \\\n \\\n SET_ITK_TYPE_ID(UNKNOWNPIXELTYPE, 1, TYPE ) else \\\n SET_ITK_TYPE_ID(SCALAR, 1, TYPE ) else \\\n \\\n SET_ITK_TYPE_ID(VECTOR, 2, Vector2Type ) else \\\n SET_ITK_TYPE_ID(COVARIANTVECTOR, 2, CovariantVector2Type ) else \\\n SET_ITK_TYPE_ID(POINT, 2, Point2Type ) else \\\n \\\n SET_ITK_TYPE_ID(RGB, 3, itk::RGBPixel<TYPE> ) else \\\n \/*SET_ITK_TYPE_ID(DIFFUSIONTENSOR3D, 6, itk::DiffusionTensor3D<TYPE> ) else *\/ \\\n SET_ITK_TYPE_ID(VECTOR, 3, Vector3Type ) else \\\n SET_ITK_TYPE_ID(COVARIANTVECTOR, 3, CovariantVector3Type ) else \\\n SET_ITK_TYPE_ID(POINT, 3, Point3Type ) else \\\n \\\n SET_ITK_TYPE_ID(RGBA, 4, itk::RGBAPixel<TYPE> ) else \\\n { \\\n } \\\n } \\\n else \n\nvoid mitk::PixelType::Initialize( const std::type_info& aTypeId, int numberOfComponents, ItkIOPixelType anItkIoPixelType )\n{\n m_TypeId = &aTypeId;\n m_NumberOfComponents = numberOfComponents;\n if(m_NumberOfComponents == 1)\n m_ItkTypeId = &aTypeId;\n else\n m_ItkTypeId = NULL;\n SET_TYPE(double, mitkIpPicFloat)\n SET_TYPE(float, mitkIpPicFloat)\n SET_TYPE(long, mitkIpPicInt)\n SET_TYPE(unsigned long, mitkIpPicUInt)\n SET_TYPE(int, mitkIpPicInt)\n SET_TYPE(unsigned int, mitkIpPicUInt)\n SET_TYPE(short, mitkIpPicInt)\n SET_TYPE(unsigned short, mitkIpPicUInt)\n SET_TYPE(char, mitkIpPicInt)\n SET_TYPE(unsigned char, mitkIpPicUInt)\n\n \n if ( *m_TypeId == typeid( itk::DiffusionTensor3D<float> ) )\n {\n m_TypeId = & typeid( float );\n m_NumberOfComponents *= 6;\n m_Type = mitkIpPicFloat;\n m_Bpe = sizeof(float) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::DiffusionTensor3D<float> );\n }\n else if ( *m_TypeId == typeid( itk::DiffusionTensor3D<double> ) )\n {\n m_TypeId = & typeid( double );\n m_NumberOfComponents *= 6;\n m_Type = mitkIpPicFloat;\n m_Bpe = sizeof(double) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::DiffusionTensor3D<double> );\n }\n else if ( *m_TypeId == typeid( itk::RGBPixel<unsigned char> ) )\n {\n m_Type = mitkIpPicUInt;\n m_NumberOfComponents = 3;\n m_Bpe = sizeof(unsigned char) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::RGBPixel<unsigned char> );\n }\n else if ( *m_TypeId == typeid( itk::RGBAPixel<unsigned char> ) )\n {\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n else\n {\n bool found = false;\n \n \/\/ the following lines allow for fixed-size vector images up to a certain size limit\n \/\/ (commented out for shorter compile times)\n \/\/HUNDRED_VECS(000)\n \/\/HUNDRED_VECS(100)\n \/\/HUNDRED_VECS(200)\n \/\/HUNDRED_VECS(300)\n \/\/HUNDRED_VECS(400)\n \/\/HUNDRED_VECS(500)\n \/\/HUNDRED_VECS(600)\n \/\/HUNDRED_VECS(700)\n\n \/\/ allow for fixed-size vectors of specific length\n \/\/ (inspired by itkPointshell.cpp, precompiled q-ball configs)\n \/\/TEN_VECS(0)\n \/\/N_VEC(11)\n \/\/N_VEC(12)\n if(false){}\n N_VEC(3)\n N_VEC(6)\n N_VEC(42)\n N_VEC(92)\n N_VEC(162)\n N_VEC(252)\n N_VEC(362)\n \/\/N_VEC(492)\n \/\/N_VEC(642)\n \/\/N_VEC(812)\n \/\/N_VEC(1002)\n\n if(!found)\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n m_BitsPerComponent = m_Bpe \/ m_NumberOfComponents;\n}\n\nvoid mitk::PixelType::Initialize( mitkIpPicType_t type, int bpe, int numberOfComponents )\n{\n m_Type = type;\n m_Bpe = bpe;\n m_NumberOfComponents = numberOfComponents;\n switch ( type )\n {\n case mitkIpPicUnknown:\n m_TypeId = &typeid( void* );\n break;\n case mitkIpPicBool:\n m_TypeId = &typeid( bool );\n m_Bpe = sizeof(bool) * 8 * numberOfComponents;\n break;\n case mitkIpPicASCII:\n m_TypeId = &typeid( char );\n m_Bpe = sizeof(char) * 8 * numberOfComponents;\n break;\n case mitkIpPicInt:\n switch ( bpe \/ numberOfComponents )\n {\n case 8:\n m_TypeId = &typeid( char );\n break;\n case 16:\n m_TypeId = &typeid( short );\n break;\n case 32:\n m_TypeId = &typeid( int );\n break;\n case 64:\n m_TypeId = &typeid( long );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicUInt:\n switch ( bpe \/ numberOfComponents )\n {\n case 8:\n m_TypeId = &typeid( unsigned char );\n break;\n case 16:\n m_TypeId = &typeid( unsigned short );\n break;\n case 24:\n m_TypeId = &typeid( unsigned char );\n m_NumberOfComponents = numberOfComponents = 3;\n break;\n case 32:\n m_TypeId = &typeid( unsigned int );\n break;\n case 64:\n m_TypeId = &typeid( unsigned long );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicFloat:\n switch ( bpe \/ numberOfComponents )\n {\n case 32:\n m_TypeId = &typeid( float );\n break;\n case 64:\n m_TypeId = &typeid( double );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicNonUniform:\n m_TypeId = &typeid( void* );\n break;\n case mitkIpPicTSV:\n m_TypeId = &typeid( void* );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n break;\n }\n m_BitsPerComponent = m_Bpe \/ numberOfComponents;\n\n if(m_NumberOfComponents == 1)\n m_ItkTypeId = m_TypeId;\n else\n m_ItkTypeId = NULL;\n}\n\nstd::string mitk::PixelType::GetItkTypeAsString() const\n{\n if (GetItkTypeId()==NULL)\n {\n return \"unknown\";\n }\n else\n {\n return GetItkTypeId()->name();\n }\n}\n<commit_msg>FIX (#2893): added additional vector sizes<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkIpPic.h\"\n#include \"mitkPixelType.h\"\n#include <itkVector.h>\n#include <itkRGBPixel.h>\n#include <itkRGBAPixel.h>\n#include <itkCovariantVector.h>\n#include \"itkDiffusionTensor3D.h\"\n\n#define HUNDRED_VECS(HUN) \\\n TEN_VECS(HUN) \\\n TEN_VECS(HUN+10) \\\n TEN_VECS(HUN+20) \\\n TEN_VECS(HUN+30) \\\n TEN_VECS(HUN+40) \\\n TEN_VECS(HUN+50) \\\n TEN_VECS(HUN+60) \\\n TEN_VECS(HUN+70) \\\n TEN_VECS(HUN+80) \\\n TEN_VECS(HUN+90) \\\n\n#define TEN_VECS(TEN) \\\n if(false){} \\\n N_VEC(TEN+ 1) \\\n N_VEC(TEN+ 2) \\\n N_VEC(TEN+ 3) \\\n N_VEC(TEN+ 4) \\\n N_VEC(TEN+ 5) \\\n N_VEC(TEN+ 6) \\\n N_VEC(TEN+ 7) \\\n N_VEC(TEN+ 8) \\\n N_VEC(TEN+ 9) \\\n N_VEC(TEN+10) \\\n\n#define N_VEC(N_DIRS) \\\n _N_VEC(N_DIRS,double) \\\n _N_VEC(N_DIRS,float) \\\n\n#define _N_VEC(N_DIRS,PIXTYPE) \\\n else if ( *m_TypeId == typeid( itk::Vector<PIXTYPE,N_DIRS> )) \\\n { \\\n found = true; \\\n m_TypeId = & typeid( PIXTYPE ); \\\n m_NumberOfComponents *= N_DIRS; \\\n m_Type = mitkIpPicFloat; \\\n m_Bpe = sizeof(PIXTYPE) * 8 * m_NumberOfComponents; \\\n m_ItkTypeId = &typeid( itk::Vector<PIXTYPE,N_DIRS> ); \\\n } \\\n\n\nmitk::PixelType::PixelType() : m_TypeId( NULL ), m_Type( mitkIpPicUnknown ), m_Bpe( 0 ), m_NumberOfComponents( 1 )\n{\n\n}\n\nmitk::PixelType::PixelType( const mitk::PixelType& aPixelType )\n{\n Initialize( *aPixelType.GetTypeId(), aPixelType.GetNumberOfComponents() );\n}\n\nmitk::PixelType::PixelType( const std::type_info& aTypeId, int numberOfComponents, ItkIOPixelType anItkIoPixelType ) : m_TypeId( &aTypeId ), m_NumberOfComponents( numberOfComponents )\n{\n Initialize( aTypeId, numberOfComponents, anItkIoPixelType );\n}\n\nmitk::PixelType::PixelType( mitkIpPicType_t type, int bpe, int numberOfComponents ) : m_Type( type ), m_Bpe( bpe ), m_NumberOfComponents( numberOfComponents )\n{\n Initialize( type, bpe, numberOfComponents );\n}\n\nmitk::PixelType::PixelType( const mitkIpPicDescriptor* pic ) : m_NumberOfComponents( 1 )\n{\n if ( pic != NULL )\n Initialize( pic->type, pic->bpe );\n else\n {\n m_TypeId = NULL;\n \/\/ itkExceptionMacro(\"pic.IsNull() has no pixel type.\");\n }\n}\n\nbool mitk::PixelType::operator==(const mitk::PixelType& rhs) const\n{\n LOG_INFO << \"operator==\" << std::endl;\n\nLOG_INFO << \"m_Type = \" << m_Type << \" \" << rhs.m_Type << std::endl;\nLOG_INFO << \"m_Bpe = \" << m_Bpe << \" \" << rhs.m_Bpe << std::endl;\nLOG_INFO << \"m_NumberOfComponents = \" << m_NumberOfComponents << \" \" << rhs.m_NumberOfComponents << std::endl;\nLOG_INFO << \"m_BitsPerComponent = \" << m_BitsPerComponent << \" \" << rhs.m_BitsPerComponent << std::endl;\n\n return (\n *(this->m_TypeId) == *(rhs.m_TypeId)\n && this->m_Type == rhs.m_Type\n && this->m_Bpe == rhs.m_Bpe\n && this->m_NumberOfComponents == rhs.m_NumberOfComponents\n && this->m_BitsPerComponent == rhs.m_BitsPerComponent\n );\n}\n\nbool mitk::PixelType::operator!=(const mitk::PixelType& rhs) const\n{\n return !(this->operator==(rhs));\n}\n\nbool mitk::PixelType::operator==(const std::type_info& typeId) const\n{\n if (GetItkTypeId() == NULL)\n return false;\n return (*GetItkTypeId() == typeId);\n}\n\nbool mitk::PixelType::operator!=(const std::type_info& typeId) const\n{\n return !(this->operator==(typeId));\n}\n\n#define SET_ITK_TYPE_ID(anItkIoPixelType_test, numberOfComponents_test, ITK_TYPE) \\\n if ( (itk::ImageIOBase::anItkIoPixelType_test == anItkIoPixelType ) && \\\n (numberOfComponents_test == m_NumberOfComponents) \\\n ) \\\n { \\\n m_ItkTypeId = &typeid(ITK_TYPE); \\\n }\n\n#define SET_TYPE(TYPE, IPPIC_TYPE) \\\n if ( *m_TypeId == typeid( TYPE ) ) \\\n { \\\n m_Type = IPPIC_TYPE; \\\n m_Bpe = sizeof(TYPE) * 8 * m_NumberOfComponents; \\\n \\\n typedef itk::Vector<TYPE, 3> Vector3Type; \\\n typedef itk::CovariantVector<TYPE, 3> CovariantVector3Type; \\\n typedef itk::Point<TYPE, 3> Point3Type; \\\n typedef itk::Vector<TYPE, 2> Vector2Type; \\\n typedef itk::CovariantVector<TYPE, 2> CovariantVector2Type; \\\n typedef itk::Point<TYPE, 2> Point2Type; \\\n \\\n SET_ITK_TYPE_ID(UNKNOWNPIXELTYPE, 1, TYPE ) else \\\n SET_ITK_TYPE_ID(SCALAR, 1, TYPE ) else \\\n \\\n SET_ITK_TYPE_ID(VECTOR, 2, Vector2Type ) else \\\n SET_ITK_TYPE_ID(COVARIANTVECTOR, 2, CovariantVector2Type ) else \\\n SET_ITK_TYPE_ID(POINT, 2, Point2Type ) else \\\n \\\n SET_ITK_TYPE_ID(RGB, 3, itk::RGBPixel<TYPE> ) else \\\n \/*SET_ITK_TYPE_ID(DIFFUSIONTENSOR3D, 6, itk::DiffusionTensor3D<TYPE> ) else *\/ \\\n SET_ITK_TYPE_ID(VECTOR, 3, Vector3Type ) else \\\n SET_ITK_TYPE_ID(COVARIANTVECTOR, 3, CovariantVector3Type ) else \\\n SET_ITK_TYPE_ID(POINT, 3, Point3Type ) else \\\n \\\n SET_ITK_TYPE_ID(RGBA, 4, itk::RGBAPixel<TYPE> ) else \\\n { \\\n } \\\n } \\\n else \n\nvoid mitk::PixelType::Initialize( const std::type_info& aTypeId, int numberOfComponents, ItkIOPixelType anItkIoPixelType )\n{\n m_TypeId = &aTypeId;\n m_NumberOfComponents = numberOfComponents;\n if(m_NumberOfComponents == 1)\n m_ItkTypeId = &aTypeId;\n else\n m_ItkTypeId = NULL;\n SET_TYPE(double, mitkIpPicFloat)\n SET_TYPE(float, mitkIpPicFloat)\n SET_TYPE(long, mitkIpPicInt)\n SET_TYPE(unsigned long, mitkIpPicUInt)\n SET_TYPE(int, mitkIpPicInt)\n SET_TYPE(unsigned int, mitkIpPicUInt)\n SET_TYPE(short, mitkIpPicInt)\n SET_TYPE(unsigned short, mitkIpPicUInt)\n SET_TYPE(char, mitkIpPicInt)\n SET_TYPE(unsigned char, mitkIpPicUInt)\n\n \n if ( *m_TypeId == typeid( itk::DiffusionTensor3D<float> ) )\n {\n m_TypeId = & typeid( float );\n m_NumberOfComponents *= 6;\n m_Type = mitkIpPicFloat;\n m_Bpe = sizeof(float) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::DiffusionTensor3D<float> );\n }\n else if ( *m_TypeId == typeid( itk::DiffusionTensor3D<double> ) )\n {\n m_TypeId = & typeid( double );\n m_NumberOfComponents *= 6;\n m_Type = mitkIpPicFloat;\n m_Bpe = sizeof(double) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::DiffusionTensor3D<double> );\n }\n else if ( *m_TypeId == typeid( itk::RGBPixel<unsigned char> ) )\n {\n m_Type = mitkIpPicUInt;\n m_NumberOfComponents = 3;\n m_Bpe = sizeof(unsigned char) * 8 * m_NumberOfComponents;\n m_ItkTypeId = &typeid( itk::RGBPixel<unsigned char> );\n }\n else if ( *m_TypeId == typeid( itk::RGBAPixel<unsigned char> ) )\n {\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n else\n {\n bool found = false;\n \n \/\/ the following lines allow for fixed-size vector images up to a certain size limit\n \/\/ (commented out for shorter compile times)\n \/\/HUNDRED_VECS(000)\n \/\/HUNDRED_VECS(100)\n \/\/HUNDRED_VECS(200)\n \/\/HUNDRED_VECS(300)\n \/\/HUNDRED_VECS(400)\n \/\/HUNDRED_VECS(500)\n \/\/HUNDRED_VECS(600)\n \/\/HUNDRED_VECS(700)\n\n \/\/ allow for fixed-size vectors of specific length\n \/\/ (inspired by itkPointshell.cpp, precompiled q-ball configs)\n \/\/TEN_VECS(0)\n \/\/N_VEC(11)\n \/\/N_VEC(12)\n if(false){}\n N_VEC(3)\n N_VEC(6)\n N_VEC(42)\n N_VEC(92)\n N_VEC(162)\n N_VEC(252)\n N_VEC(362)\n N_VEC(492)\n N_VEC(642)\n N_VEC(812)\n N_VEC(1002)\n\n if(!found)\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n m_BitsPerComponent = m_Bpe \/ m_NumberOfComponents;\n}\n\nvoid mitk::PixelType::Initialize( mitkIpPicType_t type, int bpe, int numberOfComponents )\n{\n m_Type = type;\n m_Bpe = bpe;\n m_NumberOfComponents = numberOfComponents;\n switch ( type )\n {\n case mitkIpPicUnknown:\n m_TypeId = &typeid( void* );\n break;\n case mitkIpPicBool:\n m_TypeId = &typeid( bool );\n m_Bpe = sizeof(bool) * 8 * numberOfComponents;\n break;\n case mitkIpPicASCII:\n m_TypeId = &typeid( char );\n m_Bpe = sizeof(char) * 8 * numberOfComponents;\n break;\n case mitkIpPicInt:\n switch ( bpe \/ numberOfComponents )\n {\n case 8:\n m_TypeId = &typeid( char );\n break;\n case 16:\n m_TypeId = &typeid( short );\n break;\n case 32:\n m_TypeId = &typeid( int );\n break;\n case 64:\n m_TypeId = &typeid( long );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicUInt:\n switch ( bpe \/ numberOfComponents )\n {\n case 8:\n m_TypeId = &typeid( unsigned char );\n break;\n case 16:\n m_TypeId = &typeid( unsigned short );\n break;\n case 24:\n m_TypeId = &typeid( unsigned char );\n m_NumberOfComponents = numberOfComponents = 3;\n break;\n case 32:\n m_TypeId = &typeid( unsigned int );\n break;\n case 64:\n m_TypeId = &typeid( unsigned long );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicFloat:\n switch ( bpe \/ numberOfComponents )\n {\n case 32:\n m_TypeId = &typeid( float );\n break;\n case 64:\n m_TypeId = &typeid( double );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n }\n break;\n case mitkIpPicNonUniform:\n m_TypeId = &typeid( void* );\n break;\n case mitkIpPicTSV:\n m_TypeId = &typeid( void* );\n break;\n default:\n m_TypeId = NULL;\n itkExceptionMacro( \"Pixel type currently not supported.\" );\n break;\n }\n m_BitsPerComponent = m_Bpe \/ numberOfComponents;\n\n if(m_NumberOfComponents == 1)\n m_ItkTypeId = m_TypeId;\n else\n m_ItkTypeId = NULL;\n}\n\nstd::string mitk::PixelType::GetItkTypeAsString() const\n{\n if (GetItkTypeId()==NULL)\n {\n return \"unknown\";\n }\n else\n {\n return GetItkTypeId()->name();\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fix build error...<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"Color.h\"\n#include \"Quaternion.h\"\n#include \"Transform.h\"\n#include \"Vector3D.h\"\n#include \"Matrix4.h\"\n\n#include <QScriptEngine>\n#include <QColor>\n#include <QVector3D>\n#include <QQuaternion>\n\nQScriptValue toScriptValueColor(QScriptEngine *engine, const Color &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"r\", QScriptValue(engine, s.r));\n obj.setProperty(\"g\", QScriptValue(engine, s.g));\n obj.setProperty(\"b\", QScriptValue(engine, s.b));\n obj.setProperty(\"a\", QScriptValue(engine, s.a));\n return obj;\n}\n \nvoid fromScriptValueColor(const QScriptValue &obj, Color &s)\n{\n s.r = (float)obj.property(\"r\").toNumber();\n s.g = (float)obj.property(\"g\").toNumber();\n s.b = (float)obj.property(\"b\").toNumber();\n s.a = (float)obj.property(\"a\").toNumber();\n}\n\nQScriptValue toScriptValueQColor(QScriptEngine *engine, const QColor &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"r\", QScriptValue(engine, s.red()));\n obj.setProperty(\"g\", QScriptValue(engine, s.green()));\n obj.setProperty(\"b\", QScriptValue(engine, s.blue()));\n obj.setProperty(\"a\", QScriptValue(engine, s.alpha()));\n return obj;\n}\n \nvoid fromScriptValueQColor(const QScriptValue &obj, QColor &s)\n{\n s.setRed((float)obj.property(\"r\").toNumber());\n s.setGreen((float)obj.property(\"g\").toNumber());\n s.setBlue((float)obj.property(\"b\").toNumber());\n s.setAlpha((float)obj.property(\"a\").toNumber());\n}\n\n\nQScriptValue toScriptValueVector3(QScriptEngine *engine, const Vector3df &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x));\n obj.setProperty(\"y\", QScriptValue(engine, s.y));\n obj.setProperty(\"z\", QScriptValue(engine, s.z));\n return obj;\n}\n \nvoid fromScriptValueVector3(const QScriptValue &obj, Vector3df &s)\n{\n s.x = (float)obj.property(\"x\").toNumber();\n s.y = (float)obj.property(\"y\").toNumber();\n s.z = (float)obj.property(\"z\").toNumber();\n}\n\nQScriptValue toScriptValueQVector3D(QScriptEngine *engine, const QVector3D &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x()));\n obj.setProperty(\"y\", QScriptValue(engine, s.y()));\n obj.setProperty(\"z\", QScriptValue(engine, s.z()));\n return obj;\n}\n \nvoid fromScriptValueQVector3D(const QScriptValue &obj, QVector3D &s)\n{\n s.setX((float)obj.property(\"x\").toNumber());\n s.setY((float)obj.property(\"y\").toNumber());\n s.setZ((float)obj.property(\"z\").toNumber());\n}\n\n\nQScriptValue toScriptValueQuaternion(QScriptEngine *engine, const Quaternion &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x));\n obj.setProperty(\"y\", QScriptValue(engine, s.y));\n obj.setProperty(\"z\", QScriptValue(engine, s.z));\n obj.setProperty(\"w\", QScriptValue(engine, s.w));\n return obj;\n}\n \nvoid fromScriptValueQuaternion(const QScriptValue &obj, Quaternion &s)\n{\n s.x = (float)obj.property(\"x\").toNumber();\n s.y = (float)obj.property(\"y\").toNumber();\n s.z = (float)obj.property(\"z\").toNumber();\n s.w = (float)obj.property(\"w\").toNumber();\n}\n\nQScriptValue toScriptValueQQuaternion(QScriptEngine *engine, const QQuaternion &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x()));\n obj.setProperty(\"y\", QScriptValue(engine, s.y()));\n obj.setProperty(\"z\", QScriptValue(engine, s.z()));\n obj.setProperty(\"w\", QScriptValue(engine, s.scalar()));\n return obj;\n}\n \nvoid fromScriptValueQQuaternion(const QScriptValue &obj, QQuaternion &s)\n{\n s.setX((float)obj.property(\"x\").toNumber());\n s.setY((float)obj.property(\"y\").toNumber());\n s.setZ((float)obj.property(\"z\").toNumber());\n s.setScalar((float)obj.property(\"w\").toNumber());\n}\n\nQScriptValue toScriptValueTransform(QScriptEngine *engine, const Transform &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"pos\", toScriptValueVector3(engine, s.position));\n obj.setProperty(\"rot\", toScriptValueVector3(engine, s.rotation));\n obj.setProperty(\"scale\", toScriptValueVector3(engine, s.scale));\n return obj;\n}\n\nvoid fromScriptValueTransform(const QScriptValue &obj, Transform &s)\n{\n fromScriptValueVector3(obj.property(\"pos\"), s.position);\n fromScriptValueVector3(obj.property(\"rot\"), s.rotation);\n fromScriptValueVector3(obj.property(\"scale\"), s.scale);\n}\n\nvoid RegisterNaaliCoreMetaTypes()\n{\n qRegisterMetaType<Color>(\"Color\");\n qRegisterMetaType<Vector3df>(\"Vector3df\");\n qRegisterMetaType<Quaternion>(\"Quaternion\");\n qRegisterMetaType<Transform>(\"Transform\");\n}\n\nvoid ExposeNaaliCoreTypes(QScriptEngine *engine)\n{\n qScriptRegisterMetaType(engine, toScriptValueColor, fromScriptValueColor);\n qScriptRegisterMetaType(engine, toScriptValueQColor, fromScriptValueQColor);\n qScriptRegisterMetaType(engine, toScriptValueVector3, fromScriptValueVector3);\n qScriptRegisterMetaType(engine, toScriptValueQVector3D, fromScriptValueQVector3D);\n qScriptRegisterMetaType(engine, toScriptValueQuaternion, fromScriptValueQuaternion);\n qScriptRegisterMetaType(engine, toScriptValueQQuaternion, fromScriptValueQQuaternion);\n qScriptRegisterMetaType(engine, toScriptValueTransform, fromScriptValueTransform);\n}\n<commit_msg>Fixed missing include stableheaders<commit_after>#include \"StableHeaders.h\"\n#include \"Color.h\"\n#include \"Quaternion.h\"\n#include \"Transform.h\"\n#include \"Vector3D.h\"\n#include \"Matrix4.h\"\n\n\n#include <QScriptEngine>\n#include <QColor>\n#include <QVector3D>\n#include <QQuaternion>\n\nQScriptValue toScriptValueColor(QScriptEngine *engine, const Color &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"r\", QScriptValue(engine, s.r));\n obj.setProperty(\"g\", QScriptValue(engine, s.g));\n obj.setProperty(\"b\", QScriptValue(engine, s.b));\n obj.setProperty(\"a\", QScriptValue(engine, s.a));\n return obj;\n}\n \nvoid fromScriptValueColor(const QScriptValue &obj, Color &s)\n{\n s.r = (float)obj.property(\"r\").toNumber();\n s.g = (float)obj.property(\"g\").toNumber();\n s.b = (float)obj.property(\"b\").toNumber();\n s.a = (float)obj.property(\"a\").toNumber();\n}\n\nQScriptValue toScriptValueQColor(QScriptEngine *engine, const QColor &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"r\", QScriptValue(engine, s.red()));\n obj.setProperty(\"g\", QScriptValue(engine, s.green()));\n obj.setProperty(\"b\", QScriptValue(engine, s.blue()));\n obj.setProperty(\"a\", QScriptValue(engine, s.alpha()));\n return obj;\n}\n \nvoid fromScriptValueQColor(const QScriptValue &obj, QColor &s)\n{\n s.setRed((float)obj.property(\"r\").toNumber());\n s.setGreen((float)obj.property(\"g\").toNumber());\n s.setBlue((float)obj.property(\"b\").toNumber());\n s.setAlpha((float)obj.property(\"a\").toNumber());\n}\n\n\nQScriptValue toScriptValueVector3(QScriptEngine *engine, const Vector3df &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x));\n obj.setProperty(\"y\", QScriptValue(engine, s.y));\n obj.setProperty(\"z\", QScriptValue(engine, s.z));\n return obj;\n}\n \nvoid fromScriptValueVector3(const QScriptValue &obj, Vector3df &s)\n{\n s.x = (float)obj.property(\"x\").toNumber();\n s.y = (float)obj.property(\"y\").toNumber();\n s.z = (float)obj.property(\"z\").toNumber();\n}\n\nQScriptValue toScriptValueQVector3D(QScriptEngine *engine, const QVector3D &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x()));\n obj.setProperty(\"y\", QScriptValue(engine, s.y()));\n obj.setProperty(\"z\", QScriptValue(engine, s.z()));\n return obj;\n}\n \nvoid fromScriptValueQVector3D(const QScriptValue &obj, QVector3D &s)\n{\n s.setX((float)obj.property(\"x\").toNumber());\n s.setY((float)obj.property(\"y\").toNumber());\n s.setZ((float)obj.property(\"z\").toNumber());\n}\n\n\nQScriptValue toScriptValueQuaternion(QScriptEngine *engine, const Quaternion &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x));\n obj.setProperty(\"y\", QScriptValue(engine, s.y));\n obj.setProperty(\"z\", QScriptValue(engine, s.z));\n obj.setProperty(\"w\", QScriptValue(engine, s.w));\n return obj;\n}\n \nvoid fromScriptValueQuaternion(const QScriptValue &obj, Quaternion &s)\n{\n s.x = (float)obj.property(\"x\").toNumber();\n s.y = (float)obj.property(\"y\").toNumber();\n s.z = (float)obj.property(\"z\").toNumber();\n s.w = (float)obj.property(\"w\").toNumber();\n}\n\nQScriptValue toScriptValueQQuaternion(QScriptEngine *engine, const QQuaternion &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"x\", QScriptValue(engine, s.x()));\n obj.setProperty(\"y\", QScriptValue(engine, s.y()));\n obj.setProperty(\"z\", QScriptValue(engine, s.z()));\n obj.setProperty(\"w\", QScriptValue(engine, s.scalar()));\n return obj;\n}\n \nvoid fromScriptValueQQuaternion(const QScriptValue &obj, QQuaternion &s)\n{\n s.setX((float)obj.property(\"x\").toNumber());\n s.setY((float)obj.property(\"y\").toNumber());\n s.setZ((float)obj.property(\"z\").toNumber());\n s.setScalar((float)obj.property(\"w\").toNumber());\n}\n\nQScriptValue toScriptValueTransform(QScriptEngine *engine, const Transform &s)\n{\n QScriptValue obj = engine->newObject();\n obj.setProperty(\"pos\", toScriptValueVector3(engine, s.position));\n obj.setProperty(\"rot\", toScriptValueVector3(engine, s.rotation));\n obj.setProperty(\"scale\", toScriptValueVector3(engine, s.scale));\n return obj;\n}\n\nvoid fromScriptValueTransform(const QScriptValue &obj, Transform &s)\n{\n fromScriptValueVector3(obj.property(\"pos\"), s.position);\n fromScriptValueVector3(obj.property(\"rot\"), s.rotation);\n fromScriptValueVector3(obj.property(\"scale\"), s.scale);\n}\n\nvoid RegisterNaaliCoreMetaTypes()\n{\n qRegisterMetaType<Color>(\"Color\");\n qRegisterMetaType<Vector3df>(\"Vector3df\");\n qRegisterMetaType<Quaternion>(\"Quaternion\");\n qRegisterMetaType<Transform>(\"Transform\");\n}\n\nvoid ExposeNaaliCoreTypes(QScriptEngine *engine)\n{\n qScriptRegisterMetaType(engine, toScriptValueColor, fromScriptValueColor);\n qScriptRegisterMetaType(engine, toScriptValueQColor, fromScriptValueQColor);\n qScriptRegisterMetaType(engine, toScriptValueVector3, fromScriptValueVector3);\n qScriptRegisterMetaType(engine, toScriptValueQVector3D, fromScriptValueQVector3D);\n qScriptRegisterMetaType(engine, toScriptValueQuaternion, fromScriptValueQuaternion);\n qScriptRegisterMetaType(engine, toScriptValueQQuaternion, fromScriptValueQQuaternion);\n qScriptRegisterMetaType(engine, toScriptValueTransform, fromScriptValueTransform);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * OpenSim: testInitState.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2017 Stanford University and the Authors *\n * Author(s): Peter Eastman, Ajay Seth *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include <stdint.h>\n#include <OpenSim\/Simulation\/Manager\/Manager.h>\n#include <OpenSim\/Simulation\/Control\/ControlSetController.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Auxiliary\/auxiliaryTestFunctions.h>\n\nusing namespace OpenSim;\nusing namespace std;\n\n\/\/==============================================================================\n\/\/ testInitState tests that a Model consistently generates the same default \n\/\/ state from its initSystem() method. It also tests that when the properties\n\/\/ are updated (after a simulation) that the defaults match the values in the \n\/\/ new state.\n\/\/==============================================================================\nvoid testStates(const string& modelFile);\n\/\/==============================================================================\n\/\/ testMemoryUsage tests that repeated initialization of the state does not \n\/\/ cause the memory footprint of the process to increase significantly.\n\/\/==============================================================================\nvoid testMemoryUsage(const string& modelFile);\n\nstatic const int MAX_N_TRIES = 100;\n\nint main()\n{\n try {\n LoadOpenSimLibrary(\"osimActuators\");\n testStates(\"arm26.osim\");\n testMemoryUsage(\"arm26.osim\");\n testMemoryUsage(\"PushUpToesOnGroundWithMuscles.osim\");\n }\n catch (const Exception& e) {\n cout << \"testInitState failed: \";\n e.print(cout); \n return 1;\n }\n catch (const std::exception& e) {\n cout << \"testInitState failed: \" << e.what() << endl;\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n\n\/\/==============================================================================\n\/\/ Test Cases\n\/\/==============================================================================\nvoid testStates(const string& modelFile)\n{\n using namespace SimTK;\n\n \/\/==========================================================================\n \/\/ Setup OpenSim model\n Model model(modelFile);\n ControlSetController* controller = new ControlSetController();\n controller->setControlSetFileName(\"arm26_StaticOptimization_controls.xml\");\n \n model.addController( controller );\n \/\/ original default state\n State& state = model.initSystem();\n\n \/\/ hold on to original default continuous state variables\n Vector y1 = state.getY();\n y1 = state.getY();\n \/\/y1.dump(\"y1: Initial state:\");\n\n \/\/ update state to contain muscle states that yield muscle equilibrium\n model.equilibrateMuscles(state);\n state.getY().dump(\"y1: State after equilibrateMuscles:\");\n \/\/==========================================================================\n \/\/ Compute the force and torque at the specified times.\n\n RungeKuttaMersonIntegrator integrator(model.getMultibodySystem());\n Manager manager(model, integrator);\n manager.setInitialTime(0.0);\n manager.setFinalTime(0.05);\n\n \/\/ update state after a short simulation forward in time\n manager.integrate(state);\n\n \/\/ continuous state variables after simulation\n Vector y2 = state.getY();\n \/\/y2.dump(\"y2: State after integration:\");\n\n \/\/ reset model working state to default state\n State& state2 = model.initializeState();\n\n \/\/ another version of default continuous state variables \n \/\/ should be unaffected by simulation of the system\n Vector y3 = state2.getY();\n \/\/y3.dump(\"y3: Model reset to Initial state:\");\n\n \/\/ update state to contain muscle states that yield muscle equilibrium\n model.equilibrateMuscles(state2);\n state.getY().dump(\"y3: State after equilibrateMuscles:\");\n \/\/==========================================================================\n \/\/ Compute the force and torque at the specified times.\n\n RungeKuttaMersonIntegrator integrator2(model.getMultibodySystem());\n Manager manager2(model, integrator);\n manager2.setInitialTime(0.0);\n manager2.setFinalTime(0.05);\n\n \/\/ update state after a short simulation forward in time\n manager2.integrate(state2);\n\n \/\/ get the default continuous state variables updated\n \/\/ from the state after the simulation\n Vector y4 = state2.getY();\n \n \/\/y4.dump(\"y4: Default State after second simulation:\");\n\n for (int i = 0; i < y1.size(); i++) \n {\n cout << i <<\" : y1[i] = \" << y1[i] << \" :: y3[i] = \" << y3[i] << endl;\n ASSERT_EQUAL(y1[i], y3[i], 1e-5,__FILE__, __LINE__, \n \"Model failed to maintain default state after simulation.\");\n cout << i <<\" : y2[i] = \" << y2[i] << \" :: y4[i] = \" << y4[i] << endl;\n ASSERT_EQUAL(y2[i], y4[i], 1e-5,__FILE__, __LINE__, \n \"Model failed to properly update default state after simulation.\");\n }\n ASSERT(max(abs(y1-y2)) > 1e-4);\n}\n\nvoid testMemoryUsage(const string& modelFile)\n{\n using namespace SimTK;\n\n \/\/ Throw an exception if we cannot validate estimates\n \/\/ of memory with current instrumentation\n validateMemoryUseEstimates(20);\n\n \/\/=========================================================================\n \/\/ Estimate the size of the model when loaded into memory\n auto creator = [modelFile]() { \n Model* model = new Model(modelFile);\n model->finalizeFromProperties();\n return model;\n };\n\n size_t model_size = \n estimateMemoryChangeForCreator<Model>(creator, 5);\n\n OPENSIM_THROW_IF(model_size == 0, OpenSim::Exception,\n \"Model size was estimated to be zero.\");\n\n Model model(modelFile);\n State& state = model.initSystem();\n\n \/\/ also time how long initializing the state takes\n clock_t startTime = clock();\n\n \/\/ determine the change in memory usage due to invoking model.initialiState\n auto command = [&model, state]() mutable { state = model.initializeState(); };\n const size_t leak = estimateMemoryChangeForCommand(command, MAX_N_TRIES);\n\n long double leak_percent = 100.0 * double(leak) \/ model_size;\n\n long double dT = (long double)(clock() - startTime) \/ CLOCKS_PER_SEC;\n long double meanT = 1.0e3 * dT \/ MAX_N_TRIES; \/\/ in ms\n\n cout << \"Approximate leak size: \" << leak \/ 1024.0 << \"KB or \" <<\n leak_percent << \"% of model size.\" << endl;\n cout << \"Average initialization time: \" << meanT << \"ms\" << endl;\n\n \/\/ If we are leaking more than 0.5% of the model's footprint that is significant\n ASSERT((leak_percent) < 0.5, __FILE__, __LINE__,\n \"testMemoryUsage: state initialization leak > 0.5% of model memory footprint.\");\n}\n<commit_msg>Remove custom nSamples for memory use estimate<commit_after>\/* -------------------------------------------------------------------------- *\n * OpenSim: testInitState.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2017 Stanford University and the Authors *\n * Author(s): Peter Eastman, Ajay Seth *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include <stdint.h>\n#include <OpenSim\/Simulation\/Manager\/Manager.h>\n#include <OpenSim\/Simulation\/Control\/ControlSetController.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Auxiliary\/auxiliaryTestFunctions.h>\n\nusing namespace OpenSim;\nusing namespace std;\n\n\/\/==============================================================================\n\/\/ testInitState tests that a Model consistently generates the same default \n\/\/ state from its initSystem() method. It also tests that when the properties\n\/\/ are updated (after a simulation) that the defaults match the values in the \n\/\/ new state.\n\/\/==============================================================================\nvoid testStates(const string& modelFile);\n\/\/==============================================================================\n\/\/ testMemoryUsage tests that repeated initialization of the state does not \n\/\/ cause the memory footprint of the process to increase significantly.\n\/\/==============================================================================\nvoid testMemoryUsage(const string& modelFile);\n\nstatic const int MAX_N_TRIES = 100;\n\nint main()\n{\n try {\n LoadOpenSimLibrary(\"osimActuators\");\n testStates(\"arm26.osim\");\n testMemoryUsage(\"arm26.osim\");\n testMemoryUsage(\"PushUpToesOnGroundWithMuscles.osim\");\n }\n catch (const Exception& e) {\n cout << \"testInitState failed: \";\n e.print(cout); \n return 1;\n }\n catch (const std::exception& e) {\n cout << \"testInitState failed: \" << e.what() << endl;\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n\n\/\/==============================================================================\n\/\/ Test Cases\n\/\/==============================================================================\nvoid testStates(const string& modelFile)\n{\n using namespace SimTK;\n\n \/\/==========================================================================\n \/\/ Setup OpenSim model\n Model model(modelFile);\n ControlSetController* controller = new ControlSetController();\n controller->setControlSetFileName(\"arm26_StaticOptimization_controls.xml\");\n \n model.addController( controller );\n \/\/ original default state\n State& state = model.initSystem();\n\n \/\/ hold on to original default continuous state variables\n Vector y1 = state.getY();\n y1 = state.getY();\n \/\/y1.dump(\"y1: Initial state:\");\n\n \/\/ update state to contain muscle states that yield muscle equilibrium\n model.equilibrateMuscles(state);\n state.getY().dump(\"y1: State after equilibrateMuscles:\");\n \/\/==========================================================================\n \/\/ Compute the force and torque at the specified times.\n\n RungeKuttaMersonIntegrator integrator(model.getMultibodySystem());\n Manager manager(model, integrator);\n manager.setInitialTime(0.0);\n manager.setFinalTime(0.05);\n\n \/\/ update state after a short simulation forward in time\n manager.integrate(state);\n\n \/\/ continuous state variables after simulation\n Vector y2 = state.getY();\n \/\/y2.dump(\"y2: State after integration:\");\n\n \/\/ reset model working state to default state\n State& state2 = model.initializeState();\n\n \/\/ another version of default continuous state variables \n \/\/ should be unaffected by simulation of the system\n Vector y3 = state2.getY();\n \/\/y3.dump(\"y3: Model reset to Initial state:\");\n\n \/\/ update state to contain muscle states that yield muscle equilibrium\n model.equilibrateMuscles(state2);\n state.getY().dump(\"y3: State after equilibrateMuscles:\");\n \/\/==========================================================================\n \/\/ Compute the force and torque at the specified times.\n\n RungeKuttaMersonIntegrator integrator2(model.getMultibodySystem());\n Manager manager2(model, integrator);\n manager2.setInitialTime(0.0);\n manager2.setFinalTime(0.05);\n\n \/\/ update state after a short simulation forward in time\n manager2.integrate(state2);\n\n \/\/ get the default continuous state variables updated\n \/\/ from the state after the simulation\n Vector y4 = state2.getY();\n \n \/\/y4.dump(\"y4: Default State after second simulation:\");\n\n for (int i = 0; i < y1.size(); i++) \n {\n cout << i <<\" : y1[i] = \" << y1[i] << \" :: y3[i] = \" << y3[i] << endl;\n ASSERT_EQUAL(y1[i], y3[i], 1e-5,__FILE__, __LINE__, \n \"Model failed to maintain default state after simulation.\");\n cout << i <<\" : y2[i] = \" << y2[i] << \" :: y4[i] = \" << y4[i] << endl;\n ASSERT_EQUAL(y2[i], y4[i], 1e-5,__FILE__, __LINE__, \n \"Model failed to properly update default state after simulation.\");\n }\n ASSERT(max(abs(y1-y2)) > 1e-4);\n}\n\nvoid testMemoryUsage(const string& modelFile)\n{\n using namespace SimTK;\n\n \/\/ Throw an exception if we cannot validate estimates\n \/\/ of memory with current instrumentation\n validateMemoryUseEstimates();\n\n \/\/=========================================================================\n \/\/ Estimate the size of the model when loaded into memory\n auto creator = [modelFile]() { \n Model* model = new Model(modelFile);\n model->finalizeFromProperties();\n return model;\n };\n\n size_t model_size = \n estimateMemoryChangeForCreator<Model>(creator, 5);\n\n OPENSIM_THROW_IF(model_size == 0, OpenSim::Exception,\n \"Model size was estimated to be zero.\");\n\n Model model(modelFile);\n State& state = model.initSystem();\n\n \/\/ also time how long initializing the state takes\n clock_t startTime = clock();\n\n \/\/ determine the change in memory usage due to invoking model.initialiState\n auto command = [&model, state]() mutable { state = model.initializeState(); };\n const size_t leak = estimateMemoryChangeForCommand(command, MAX_N_TRIES);\n\n long double leak_percent = 100.0 * double(leak) \/ model_size;\n\n long double dT = (long double)(clock() - startTime) \/ CLOCKS_PER_SEC;\n long double meanT = 1.0e3 * dT \/ MAX_N_TRIES; \/\/ in ms\n\n cout << \"Approximate leak size: \" << leak \/ 1024.0 << \"KB or \" <<\n leak_percent << \"% of model size.\" << endl;\n cout << \"Average initialization time: \" << meanT << \"ms\" << endl;\n\n \/\/ If we are leaking more than 0.5% of the model's footprint that is significant\n ASSERT((leak_percent) < 0.5, __FILE__, __LINE__,\n \"testMemoryUsage: state initialization leak > 0.5% of model memory footprint.\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestAMRUtilities.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include <iostream>\n#include <cassert>\n#include <mpi.h>\n\n#include \"vtkAMRUtilities.h\"\n#include \"vtkAMRBox.h\"\n#include \"vtkHierarchicalBoxDataSet.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkUniformGrid.h\"\n#include \"vtkImageToStructuredGrid.h\"\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ H E L P E R M E T H O D S & M A C R O S\n\/\/-----------------------------------------------------------------------------\n#define CHECK_TEST( P, testName, rval ) { \\\n if( !P ) { \\\n std::cerr << \"ERROR:\" << testName << \" FAILED!\\n\"; \\\n std::cerr << \"Location:\" << __FILE__ << \":\" << __LINE__ << std::endl; \\\n ++rval; \\\n } \\\n}\n\n\/\/ Description:\n\/\/ Gets the grid for the given process\nvoid WriteUniformGrid( vtkUniformGrid *myGrid, std::string prefix )\n{\n assert( \"Input Grid is not NULL\" && (myGrid != NULL) );\n\n vtkImageToStructuredGrid* myImage2StructuredGridFilter =\n vtkImageToStructuredGrid::New();\n assert( \"Image-2-StructuredGridFilter\" &&\n (myImage2StructuredGridFilter != NULL) );\n\n myImage2StructuredGridFilter->SetInput( myGrid );\n myImage2StructuredGridFilter->Update();\n vtkStructuredGrid* myStructuredGrid =\n myImage2StructuredGridFilter->GetOutput();\n\n}\n\n\/\/ Description:\n\/\/ Gets the grid for the given process\nvoid GetGrid( vtkUniformGrid *myGrid, int &level, int &index,\n vtkMultiProcessController *myController )\n{\n assert( \"Input Grid is not NULL\" && (myGrid != NULL) );\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n switch( myController->GetLocalProcessId() )\n {\n case 0:\n {\n level=index=0;\n double myOrigin[3] = {0.0,0.0,0.0};\n int ndim[3] = {4,4,0};\n double spacing[3] = {1,1,1};\n myGrid->Initialize();\n myGrid->SetOrigin( myOrigin );\n myGrid->SetSpacing( spacing );\n myGrid->SetDimensions( ndim );\n }\n break;\n case 1:\n {\n level=1;index=0;\n double myOrigin[3] = {1.0,1.0,0.0};\n int ndim[3] = {7,4,0};\n double spacing[3] = {1\/3,1\/3,1\/3};\n myGrid->Initialize();\n myGrid->SetOrigin( myOrigin );\n myGrid->SetSpacing( spacing );\n myGrid->SetDimensions( ndim );\n }\n break;\n default:\n std::cerr << \"Undefined process!\\n\";\n std::cerr.flush();\n myGrid->Delete();\n myGrid=NULL;\n }\n\n}\n\n\/\/ Description:\n\/\/ Get the AMR data-structure for the given process\nvoid GetAMRDataSet(\n vtkHierarchicalBoxDataSet *amrData,\n vtkMultiProcessController *myController )\n{\n assert( \"Input AMR Data is NULL!\" && (amrData != NULL) );\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n int level = -1;\n int index = -1;\n vtkUniformGrid* myGrid = vtkUniformGrid::New();\n GetGrid( myGrid, level, index, myController );\n assert( \"Invalid level\" && (level >= 0) );\n assert( \"Invalid index\" && (index >= 0) );\n\n amrData->SetDataSet( level, index, myGrid );\n myGrid->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ T E S T M E T H O D S\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Description:\n\/\/ Tests the functionality for computing the global data-set origin.\nbool TestComputeDataSetOrigin( vtkMultiProcessController *myController )\n{\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n myController->Barrier();\n\n vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();\n GetAMRDataSet( myAMRData, myController );\n double origin[3];\n vtkAMRUtilities::ComputeDataSetOrigin( origin, myAMRData, myController );\n myAMRData->Delete();\n\n myController->Barrier();\n std::cout << myController->GetLocalProcessId() << \": \";\n std::cout << origin[0] << \", \" << origin[1] << \", \" << origin[2] << std::endl;\n std::cout.flush();\n myController->Barrier();\n\n if( (origin[0] == 0.0) && (origin[1] == 0.0) && (origin[2] == 0.0) )\n return true;\n else\n return false;\n}\n\n\/\/ Description:\n\/\/ Main Test driver\nint TestAMRUtilities(int,char*[])\n{\n vtkMultiProcessController *myController =\n vtkMultiProcessController::GetGlobalController();\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n \/\/ Synchronize Processes\n myController->Barrier();\n\n int rval=0;\n CHECK_TEST( TestComputeDataSetOrigin(myController),\"ComputeOrigin\", rval );\n\n \/\/ Synchronize Processes\n myController->Barrier();\n return( rval );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ P R O G R A M M A I N\n\/\/-----------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n MPI_Init(&argc,&argv);\n\n vtkMPIController* contr = vtkMPIController::New();\n contr->Initialize( &argc, &argv, 1);\n\n vtkMultiProcessController::SetGlobalController(contr);\n\n int rc = TestAMRUtilities( argc, argv );\n contr->Barrier();\n\n contr->Finalize();\n contr->Delete();\n return rc;\n}\n<commit_msg>BUGFIX: Fix 2-D vtkUniformGrid Construction<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestAMRUtilities.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include <iostream>\n#include <sstream>\n#include <cassert>\n#include <mpi.h>\n\n#include \"vtkAMRUtilities.h\"\n#include \"vtkAMRBox.h\"\n#include \"vtkHierarchicalBoxDataSet.h\"\n#include \"vtkMultiProcessController.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkUniformGrid.h\"\n#include \"vtkImageToStructuredGrid.h\"\n#include \"vtkStructuredGridWriter.h\"\n\n\/\/-----------------------------------------------------------------------------\n\/\/ H E L P E R M E T H O D S & M A C R O S\n\/\/-----------------------------------------------------------------------------\n#define CHECK_TEST( P, testName, rval ) { \\\n if( !P ) { \\\n std::cerr << \"ERROR:\" << testName << \" FAILED!\\n\"; \\\n std::cerr << \"Location:\" << __FILE__ << \":\" << __LINE__ << std::endl; \\\n ++rval; \\\n } \\\n}\n\n\/\/ Description:\n\/\/ Gets the grid for the given process\nvoid WriteUniformGrid( vtkUniformGrid *myGrid, std::string prefix )\n{\n assert( \"Input Grid is not NULL\" && (myGrid != NULL) );\n\n vtkImageToStructuredGrid* myImage2StructuredGridFilter =\n vtkImageToStructuredGrid::New();\n assert( \"Cannot create Image2StructuredGridFilter\" &&\n (myImage2StructuredGridFilter != NULL) );\n\n myImage2StructuredGridFilter->SetInput( myGrid );\n myImage2StructuredGridFilter->Update();\n vtkStructuredGrid* myStructuredGrid =\n myImage2StructuredGridFilter->GetOutput();\n assert( \"Structured Grid output is NULL!\" &&\n (myStructuredGrid != NULL) );\n\n vtkStructuredGridWriter *myWriter = vtkStructuredGridWriter::New();\n myWriter->SetFileName( prefix.c_str() );\n myWriter->SetInput( myStructuredGrid );\n myWriter->Update();\n myWriter->Delete();\n myImage2StructuredGridFilter->Delete();\n}\n\n\/\/ Description:\n\/\/ Gets the grid for the given process\nvoid GetGrid( vtkUniformGrid *myGrid, int &level, int &index,\n vtkMultiProcessController *myController )\n{\n assert( \"Input Grid is not NULL\" && (myGrid != NULL) );\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n switch( myController->GetLocalProcessId() )\n {\n case 0:\n {\n level=index=0;\n double myOrigin[3] = {0.0,0.0,0.0};\n int ndim[3] = {4,4,1};\n double spacing[3] = {1,1,1};\n myGrid->Initialize();\n myGrid->SetOrigin( myOrigin );\n myGrid->SetSpacing( spacing );\n myGrid->SetDimensions( ndim );\n }\n break;\n case 1:\n {\n level=1;index=0;\n double myOrigin[3] = {1.0,1.0,0.0};\n int ndim[3] = {5,3,1};\n double spacing[3] = {0.5,0.5,0.5};\n myGrid->Initialize();\n myGrid->SetOrigin( myOrigin );\n myGrid->SetSpacing( spacing );\n myGrid->SetDimensions( ndim );\n }\n break;\n default:\n std::cerr << \"Undefined process!\\n\";\n std::cerr.flush();\n myGrid->Delete();\n myGrid=NULL;\n }\n\n}\n\n\/\/ Description:\n\/\/ Get the AMR data-structure for the given process\nvoid GetAMRDataSet(\n vtkHierarchicalBoxDataSet *amrData,\n vtkMultiProcessController *myController )\n{\n assert( \"Input AMR Data is NULL!\" && (amrData != NULL) );\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n int level = -1;\n int index = -1;\n vtkUniformGrid* myGrid = vtkUniformGrid::New();\n GetGrid( myGrid, level, index, myController );\n assert( \"Invalid level\" && (level >= 0) );\n assert( \"Invalid index\" && (index >= 0) );\n std::ostringstream oss;\n oss.clear();\n oss.str(\"\");\n oss << \"Process_\" << myController->GetLocalProcessId() << \"_GRID_\";\n oss << \"L\" << level << \"_\" << index << \".vtk\";\n WriteUniformGrid( myGrid, oss.str( ) );\n\n amrData->SetDataSet( level, index, myGrid );\n myGrid->Delete();\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ T E S T M E T H O D S\n\/\/-----------------------------------------------------------------------------\n\n\/\/ Description:\n\/\/ Tests the functionality for computing the global data-set origin.\nbool TestComputeDataSetOrigin( vtkMultiProcessController *myController )\n{\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n myController->Barrier();\n\n vtkHierarchicalBoxDataSet* myAMRData = vtkHierarchicalBoxDataSet::New();\n GetAMRDataSet( myAMRData, myController );\n double origin[3];\n vtkAMRUtilities::ComputeDataSetOrigin( origin, myAMRData, myController );\n myAMRData->Delete();\n\n myController->Barrier();\n std::cout << myController->GetLocalProcessId() << \": \";\n std::cout << origin[0] << \", \" << origin[1] << \", \" << origin[2] << std::endl;\n std::cout.flush();\n myController->Barrier();\n\n if( (origin[0] == 0.0) && (origin[1] == 0.0) && (origin[2] == 0.0) )\n return true;\n else\n return false;\n}\n\n\/\/ Description:\n\/\/ Main Test driver\nint TestAMRUtilities(int,char*[])\n{\n vtkMultiProcessController *myController =\n vtkMultiProcessController::GetGlobalController();\n assert( \"Null Multi-process controller encountered\" &&\n (myController != NULL) );\n\n \/\/ Synchronize Processes\n myController->Barrier();\n\n int rval=0;\n CHECK_TEST( TestComputeDataSetOrigin(myController),\"ComputeOrigin\", rval );\n\n \/\/ Synchronize Processes\n myController->Barrier();\n return( rval );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ P R O G R A M M A I N\n\/\/-----------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n MPI_Init(&argc,&argv);\n\n vtkMPIController* contr = vtkMPIController::New();\n contr->Initialize( &argc, &argv, 1);\n\n vtkMultiProcessController::SetGlobalController(contr);\n\n int rc = TestAMRUtilities( argc, argv );\n contr->Barrier();\n\n contr->Finalize();\n contr->Delete();\n return rc;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* FasTC\n * Copyright (c) 2014 University of North Carolina at Chapel Hill.\n * All rights reserved.\n *\n * Permission to use, copy, modify, and distribute this software and its\n * documentation for educational, research, and non-profit purposes, without\n * fee, and without a written agreement is hereby granted, provided that the\n * above copyright notice, this paragraph, and the following four paragraphs\n * appear in all copies.\n *\n * Permission to incorporate this software into commercial products may be\n * obtained by contacting the authors or the Office of Technology Development\n * at the University of North Carolina at Chapel Hill <otd@unc.edu>.\n *\n * This software program and documentation are copyrighted by the University of\n * North Carolina at Chapel Hill. The software program and documentation are\n * supplied \"as is,\" without any accompanying services from the University of\n * North Carolina at Chapel Hill or the authors. The University of North\n * Carolina at Chapel Hill and the authors do not warrant that the operation of\n * the program will be uninterrupted or error-free. The end-user understands\n * that the program was developed for research purposes and is advised not to\n * rely exclusively on the program for any reason.\n *\n * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE\n * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,\n * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF\n * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA\n * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\n * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY\n * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY \n * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON\n * AN \"AS IS\" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND\n * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, \n * ENHANCEMENTS, OR MODIFICATIONS.\n *\n * Please send all BUG REPORTS to <pavel@cs.unc.edu>.\n *\n * The authors may be contacted via:\n *\n * Pavel Krajcevski\n * Dept of Computer Science\n * 201 S Columbia St\n * Frederick P. Brooks, Jr. Computer Science Bldg\n * Chapel Hill, NC 27599-3175\n * USA\n * \n * <http:\/\/gamma.cs.unc.edu\/FasTC\/>\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"MatrixBase.h\"\n\nstatic const float kEpsilon = 1e-6;\n\nTEST(MatrixBase, Constructors) {\n FasTC::MatrixBase<float, 3, 4> m3f;\n FasTC::MatrixBase<double, 1, 1> m1d;\n FasTC::MatrixBase<int, 7, 200> m7i;\n FasTC::MatrixBase<unsigned, 16, 16> m16u;\n\n#define TEST_VECTOR_COPY_CONS(mat, t, n, m) \\\n do { \\\n FasTC::MatrixBase<t, n, m> d##mat (mat); \\\n for(int i = 0; i < n*m; i++) { \\\n EXPECT_EQ(d##mat [i], mat[i]); \\\n } \\\n } while(0) \\\n\n TEST_VECTOR_COPY_CONS(m3f, float, 3, 4);\n TEST_VECTOR_COPY_CONS(m1d, double, 1, 1);\n TEST_VECTOR_COPY_CONS(m7i, int, 7, 200);\n TEST_VECTOR_COPY_CONS(m16u, unsigned, 16, 16);\n\n#undef TEST_VECTOR_COPY_CONS\n}\n\nTEST(MatrixBase, Accessors) {\n FasTC::MatrixBase<float, 3, 1> v3f;\n v3f[0] = 1.0f;\n v3f[1] = -2.3f;\n v3f[2] = 1000;\n\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f[i], v3f(i));\n }\n\n v3f(0) = -1.0f;\n v3f(1) = 2.3f;\n v3f(2) = -1000;\n\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f(i), v3f[i]);\n }\n}\n\nTEST(MatrixBase, PointerConversion) {\n FasTC::MatrixBase<float, 2, 3> v3f;\n v3f(0,0) = 1.0f;\n v3f(0,1) = -2.3f;\n v3f(0,2) = 1000.0f;\n v3f(1,0) = 1.0f;\n v3f(1,1) = -2.3f;\n v3f(1,2) = 1000.0f;\n\n float cmp[6] = { 1.0f, -2.3f, 1000.0f, 1.0f, -2.3f, 1000.0f };\n const float *v3fp = v3f;\n int result = memcmp(cmp, v3fp, 6 * sizeof(float));\n EXPECT_EQ(result, 0);\n\n cmp[0] = -1.0f;\n cmp[1] = 2.3f;\n cmp[2] = 1000.0f;\n cmp[3] = -1.0f;\n cmp[4] = 2.3f;\n cmp[5] = 1000.0f;\n v3f = cmp;\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f[i], cmp[i]);\n }\n}\n\nTEST(MatrixBase, CastVector) {\n FasTC::MatrixBase<float, 3, 2> v3f;\n FasTC::MatrixBase<double, 3, 2> v3d = v3f;\n FasTC::MatrixBase<int, 3, 2> v3i = v3f;\n for(int i = 0; i < 3*2; i++) {\n EXPECT_EQ(v3d(i), static_cast<double>(v3f(i)));\n EXPECT_EQ(v3i(i), static_cast<int>(v3f(i)));\n }\n}\n\nTEST(MatrixBase, MatrixMultiplication) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(MatrixBase, VectorMultiplication) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(MatrixSquare, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(MatrixSquare, EigenvalueCalculation) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix2x2, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix3x3, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix4x4, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\n<commit_msg>Add matrix multiplication test<commit_after>\/* FasTC\n * Copyright (c) 2014 University of North Carolina at Chapel Hill.\n * All rights reserved.\n *\n * Permission to use, copy, modify, and distribute this software and its\n * documentation for educational, research, and non-profit purposes, without\n * fee, and without a written agreement is hereby granted, provided that the\n * above copyright notice, this paragraph, and the following four paragraphs\n * appear in all copies.\n *\n * Permission to incorporate this software into commercial products may be\n * obtained by contacting the authors or the Office of Technology Development\n * at the University of North Carolina at Chapel Hill <otd@unc.edu>.\n *\n * This software program and documentation are copyrighted by the University of\n * North Carolina at Chapel Hill. The software program and documentation are\n * supplied \"as is,\" without any accompanying services from the University of\n * North Carolina at Chapel Hill or the authors. The University of North\n * Carolina at Chapel Hill and the authors do not warrant that the operation of\n * the program will be uninterrupted or error-free. The end-user understands\n * that the program was developed for research purposes and is advised not to\n * rely exclusively on the program for any reason.\n *\n * IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE\n * AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL,\n * OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF\n * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA\n * AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\n * THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY\n * DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY \n * STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON\n * AN \"AS IS\" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND\n * THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, \n * ENHANCEMENTS, OR MODIFICATIONS.\n *\n * Please send all BUG REPORTS to <pavel@cs.unc.edu>.\n *\n * The authors may be contacted via:\n *\n * Pavel Krajcevski\n * Dept of Computer Science\n * 201 S Columbia St\n * Frederick P. Brooks, Jr. Computer Science Bldg\n * Chapel Hill, NC 27599-3175\n * USA\n * \n * <http:\/\/gamma.cs.unc.edu\/FasTC\/>\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"MatrixBase.h\"\n\nstatic const float kEpsilon = 1e-6;\n\nTEST(MatrixBase, Constructors) {\n FasTC::MatrixBase<float, 3, 4> m3f;\n FasTC::MatrixBase<double, 1, 1> m1d;\n FasTC::MatrixBase<int, 7, 200> m7i;\n FasTC::MatrixBase<unsigned, 16, 16> m16u;\n\n#define TEST_VECTOR_COPY_CONS(mat, t, n, m) \\\n do { \\\n FasTC::MatrixBase<t, n, m> d##mat (mat); \\\n for(int i = 0; i < n*m; i++) { \\\n EXPECT_EQ(d##mat [i], mat[i]); \\\n } \\\n } while(0) \\\n\n TEST_VECTOR_COPY_CONS(m3f, float, 3, 4);\n TEST_VECTOR_COPY_CONS(m1d, double, 1, 1);\n TEST_VECTOR_COPY_CONS(m7i, int, 7, 200);\n TEST_VECTOR_COPY_CONS(m16u, unsigned, 16, 16);\n\n#undef TEST_VECTOR_COPY_CONS\n}\n\nTEST(MatrixBase, Accessors) {\n FasTC::MatrixBase<float, 3, 1> v3f;\n v3f[0] = 1.0f;\n v3f[1] = -2.3f;\n v3f[2] = 1000;\n\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f[i], v3f(i));\n }\n\n v3f(0) = -1.0f;\n v3f(1) = 2.3f;\n v3f(2) = -1000;\n\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f(i), v3f[i]);\n }\n}\n\nTEST(MatrixBase, PointerConversion) {\n FasTC::MatrixBase<float, 2, 3> v3f;\n v3f(0,0) = 1.0f;\n v3f(0,1) = -2.3f;\n v3f(0,2) = 1000.0f;\n v3f(1,0) = 1.0f;\n v3f(1,1) = -2.3f;\n v3f(1,2) = 1000.0f;\n\n float cmp[6] = { 1.0f, -2.3f, 1000.0f, 1.0f, -2.3f, 1000.0f };\n const float *v3fp = v3f;\n int result = memcmp(cmp, v3fp, 6 * sizeof(float));\n EXPECT_EQ(result, 0);\n\n cmp[0] = -1.0f;\n cmp[1] = 2.3f;\n cmp[2] = 1000.0f;\n cmp[3] = -1.0f;\n cmp[4] = 2.3f;\n cmp[5] = 1000.0f;\n v3f = cmp;\n for(int i = 0; i < 3; i++) {\n EXPECT_EQ(v3f[i], cmp[i]);\n }\n}\n\nTEST(MatrixBase, CastVector) {\n FasTC::MatrixBase<float, 3, 2> v3f;\n FasTC::MatrixBase<double, 3, 2> v3d = v3f;\n FasTC::MatrixBase<int, 3, 2> v3i = v3f;\n for(int i = 0; i < 3*2; i++) {\n EXPECT_EQ(v3d(i), static_cast<double>(v3f(i)));\n EXPECT_EQ(v3i(i), static_cast<int>(v3f(i)));\n }\n}\n\nTEST(MatrixBase, MatrixMultiplication) {\n FasTC::MatrixBase<int, 2, 3> a;\n a(0, 0) = 1; a(0, 1) = 2; a(0, 2) = 3;\n a(1, 0) = 4; a(1, 1) = 5; a(1, 2) = 6;\n\n FasTC::MatrixBase<int, 3, 5> b;\n b(0, 0) = -1; b(0, 1) = 2; b(0, 2) = -4; b(0, 3) = 5; b(0, 4) = 0; \n b(1, 0) = 1; b(1, 1) = 2; b(1, 2) = 4; b(1, 3) = 6; b(1, 4) = 3; \n b(2, 0) = -1; b(2, 1) = -2; b(2, 2) = -3; b(2, 3) = -4; b(2, 4) = 5; \n\n FasTC::MatrixBase<float, 2, 5> amb = a * b;\n EXPECT_NEAR(amb(0, 0), -2, kEpsilon);\n EXPECT_NEAR(amb(0, 1), 0, kEpsilon);\n EXPECT_NEAR(amb(0, 2), -5, kEpsilon);\n EXPECT_NEAR(amb(0, 3), 5, kEpsilon);\n EXPECT_NEAR(amb(0, 4), 21, kEpsilon);\n\n EXPECT_NEAR(amb(1, 0), -5, kEpsilon);\n EXPECT_NEAR(amb(1, 1), 6, kEpsilon);\n EXPECT_NEAR(amb(1, 2), -14, kEpsilon);\n EXPECT_NEAR(amb(1, 3), 26, kEpsilon);\n EXPECT_NEAR(amb(1, 4), 45, kEpsilon);\n}\n\nTEST(MatrixBase, VectorMultiplication) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(MatrixSquare, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(MatrixSquare, EigenvalueCalculation) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix2x2, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix3x3, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\nTEST(Matrix4x4, Constructors) {\n \/\/ Stub\n EXPECT_EQ(0, 1);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#include \"Berlin\/RegionImpl.hh\"\n#include \"Berlin\/TransformImpl.hh\"\n#include \"Berlin\/Math.hh\"\n#include <iomanip>\n#include <cassert>\n\nusing namespace Warsaw;\nusing namespace Math;\n\nRegionImpl::RegionImpl()\n : valid(false), xalign(0.), yalign(0.), zalign(0.), _this_valid(false)\n{\n lower.x = lower.y = 0.;\n upper.x = upper.y = 0.;\n lower.z = upper.z = 0.;\n}\n\nRegionImpl::RegionImpl(const RegionImpl ®ion)\n : valid(region.valid),\n lower(region.lower),\n upper(region.upper),\n xalign(region.xalign),\n yalign(region.yalign),\n zalign(region.zalign),\n _this_valid(false)\n{}\n\nRegionImpl::RegionImpl(Region_ptr region)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n}\n\nRegionImpl::RegionImpl(Region_ptr region, Transform_ptr transformation)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n if (!CORBA::is_nil(transformation) && !transformation->identity())\n RegionImpl::apply_transform(transformation);\n}\n\nRegionImpl::RegionImpl(Region_ptr region, TransformImpl *transformation)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n if (!transformation->identity())\n RegionImpl::apply_transform(transformation->matrix());\n}\n\nRegionImpl::~RegionImpl() {}\n\nRegionImpl &RegionImpl::operator = (const RegionImpl ®ion)\n{\n assert(_active);\n valid = region.valid;\n lower = region.lower;\n upper = region.upper;\n xalign = region.xalign;\n yalign = region.yalign;\n zalign = region.zalign;\n return *this;\n}\n\nCORBA::Boolean RegionImpl::defined() { return valid;}\nvoid RegionImpl::clear() { valid = false;}\n\nCORBA::Boolean RegionImpl::contains(const Vertex &v)\n{\n return (valid &&\n\t v.x >= lower.x && v.x <= upper.x &&\n\t v.y >= lower.y && v.y <= upper.y &&\n\t v.z >= lower.z && v.z <= upper.z\n\t );\n}\n\nCORBA::Boolean RegionImpl::contains_plane(const Vertex &v, Axis a)\n{\n bool b = false;\n if (valid)\n {\n switch (a)\n\t{\n\tcase xaxis:\n\t b = (v.y >= lower.y && v.y <= upper.y &&\n\t v.z >= lower.z && v.z <= upper.z);\n\t break;\n\tcase yaxis:\n\t b = (v.x >= lower.x && v.x <= upper.x &&\n\t v.z >= lower.z && v.z <= upper.z);\n\t break;\n\tcase zaxis:\n\t b = (v.x >= lower.x && v.x <= upper.x &&\n\t v.y >= lower.y && v.y <= upper.y);\n\t break;\n\t}\n }\n return b;\n}\n\nCORBA::Boolean RegionImpl::intersects(Region_ptr region)\n{\n if (valid)\n {\n Vertex l, u;\n region->bounds(l, u);\n return lower.x <= u.x && upper.x >= l.x && lower.y <= u.y && upper.y >= l.y;\n }\n return false;\n}\n\nCORBA::Boolean RegionImpl::intersects(const RegionImpl ®ion) const\n{\n if (valid && region.valid)\n return (lower.x <= region.upper.x &&\n\t upper.x >= region.lower.x &&\n\t lower.y <= region.upper.y &&\n\t upper.y >= region.lower.y);\n else return false;\n}\n\nvoid RegionImpl::copy(Region_ptr region)\n{\n if (!CORBA::is_nil(region) && region->defined())\n {\n Warsaw::Region::Allotment x, y, z;\n region->span(xaxis, x);\n region->span(yaxis, y);\n region->span(zaxis, z);\n valid = true;\n lower.x = x.begin;\n lower.y = y.begin;\n lower.z = z.begin;\n upper.x = x.end;\n upper.y = y.end;\n upper.z = z.end;\n xalign = x.align;\n yalign = y.align;\n zalign = z.align;\n }\n}\n\nvoid RegionImpl::merge_intersect(Region_ptr region)\n{\n if (region->defined())\n {\n if (valid)\n\t{\n\t Vertex l, u;\n\t region->bounds(l, u);\n\t merge_max(lower, l);\n\t merge_min(upper, u);\n }\n else copy(region);\n }\n}\n\nvoid RegionImpl::merge_union(Region_ptr region)\n{\n if (region->defined())\n {\n if (valid)\n\t{\n\t Vertex l, u;\n\t region->bounds(l, u);\n\t merge_min(lower, l);\n\t merge_max(upper, u);\n }\n else copy(region);\n }\n}\n\nvoid RegionImpl::subtract(Region_ptr region)\n{\n \/\/ not implemented\n}\n\nvoid RegionImpl::apply_transform(Transform_ptr transformation)\n{\n if (!valid) return;\n Transform::Matrix matrix;\n transformation->store_matrix(matrix);\n apply_transform(matrix);\n};\n\n\/*\n * note: the new region is the bounding box of the transformed\n * old region\n *\n * This algorithm takes advantage of some\n * interesting properties of affine transformations: i.e., opposite sides\n * are always parallel and same in length. Another property of\n * affine transformation is that the transformed center of a box\n * is equal to the center of the transformed box. Realizing these\n * properties, finding the transformed box can be broken down as finding\n * the effective width, height, depth, and center. The last is easy.\n * Each of the other three values is found by first breaking down\n * each of the transformed axis vectors into x, y, and z vectors.\n * Joining all the absolute vectors on a certain axis gives you\n * the size of the box on that axis. Width, for example,\n * forms a (w, 0, 0) vector. After transformation, it becomes\n * (Xw, Yw, Zw). The new width is then given as abs(Xw) + abs(Xh) + abs(Xd)\n *\/\nvoid RegionImpl::apply_transform(const Transform::Matrix &matrix)\n{\n Vertex o;\n\n origin(o);\n o *= matrix;\n\n Coord lx = upper.x - lower.x;\n Coord ly = upper.y - lower.y;\n Coord lz = upper.z - lower.z;\n \n Vertex center;\n center.x = (upper.x + lower.x) * 0.5;\n center.y = (upper.y + lower.y) * 0.5;\n center.z = (upper.z + lower.z) * 0.5;\n \n \/\/ transform the center\n center *= matrix;\n \n \/\/ optimized computation of new width and height\n Coord nlx = Math::abs(lx * matrix[0][0]) + Math::abs(ly * matrix[0][1]) + Math::abs(lz * matrix[0][2]);\n Coord nly = Math::abs(lx * matrix[1][0]) + Math::abs(ly * matrix[1][1]) + Math::abs(lz * matrix[1][2]);\n Coord nlz = Math::abs(lx * matrix[2][0]) + Math::abs(ly * matrix[2][1]) + Math::abs(lz * matrix[2][2]);\n \n \/\/ form the new box\n lower.x = center.x - nlx * 0.5;\n upper.x = center.x + nlx * 0.5;\n lower.y = center.y - nly * 0.5;\n upper.y = center.y + nly * 0.5;\n lower.z = center.z - nlz * 0.5;\n upper.z = center.z + nlz * 0.5;\n \n if (!Math::equal(nlx, 0., 1e-4)) xalign = (o.x - lower.x) \/ nlx;\n if (!Math::equal(nly, 0., 1e-4)) yalign = (o.y - lower.y) \/ nly;\n if (!Math::equal(nlz, 0., 1e-4)) zalign = (o.z - lower.z) \/ nlz;\n}\n\nvoid RegionImpl::bounds(Vertex &l, Vertex &u)\n{\n l = lower;\n u = upper;\n}\n\nvoid RegionImpl::center(Vertex &c)\n{\n c.x = (lower.x + upper.x) * 0.5;\n c.y = (lower.y + upper.y) * 0.5;\n c.z = 0.0;\n}\n\nvoid RegionImpl::origin(Vertex &v)\n{\n v.x = span_origin(lower.x, upper.x, xalign);\n v.y = span_origin(lower.y, upper.y, yalign);\n v.z = span_origin(lower.z, upper.z, zalign);\n}\n\nvoid RegionImpl::span(Axis a, Warsaw::Region::Allotment &s)\n{\n switch (a)\n {\n case xaxis:\n s.begin = lower.x;\n s.end = upper.x;\n s.align = xalign;\n break;\n case yaxis:\n s.begin = lower.y;\n s.end = upper.y;\n s.align = yalign;\n break;\n case zaxis:\n s.begin = lower.z;\n s.end = upper.z;\n s.align = zalign;\n break;\n }\n}\n\nvoid RegionImpl::outline(Path_out)\n{\n};\n\nstd::ostream &operator << (std::ostream &os, const RegionImpl ®ion)\n{\n os << \"X(\" << region.lower.x << ',' << region.upper.x;\n if (!Math::equal(region.xalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.xalign;\n os << \"), Y(\" << region.lower.y << ',' << region.upper.y;\n if (!Math::equal(region.yalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.yalign;\n os << \"), Z(\" << region.lower.z << ',' << region.upper.z;\n if (!Math::equal(region.zalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.zalign;\n os << ')';\n return os;\n}\n<commit_msg>fixed little omission<commit_after>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#include \"Berlin\/RegionImpl.hh\"\n#include \"Berlin\/TransformImpl.hh\"\n#include \"Berlin\/Math.hh\"\n#include <iomanip>\n#include <cassert>\n\nusing namespace Warsaw;\nusing namespace Math;\n\nRegionImpl::RegionImpl()\n : valid(false), xalign(0.), yalign(0.), zalign(0.), _this_valid(false)\n{\n lower.x = lower.y = 0.;\n upper.x = upper.y = 0.;\n lower.z = upper.z = 0.;\n}\n\nRegionImpl::RegionImpl(const RegionImpl ®ion)\n : valid(region.valid),\n lower(region.lower),\n upper(region.upper),\n xalign(region.xalign),\n yalign(region.yalign),\n zalign(region.zalign),\n _this_valid(false)\n{}\n\nRegionImpl::RegionImpl(Region_ptr region)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n}\n\nRegionImpl::RegionImpl(Region_ptr region, Transform_ptr transformation)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n if (!CORBA::is_nil(transformation) && !transformation->identity())\n RegionImpl::apply_transform(transformation);\n}\n\nRegionImpl::RegionImpl(Region_ptr region, TransformImpl *transformation)\n : _this_valid(false)\n{\n RegionImpl::copy(region);\n if (!transformation->identity())\n RegionImpl::apply_transform(transformation->matrix());\n}\n\nRegionImpl::~RegionImpl() {}\n\nRegionImpl &RegionImpl::operator = (const RegionImpl ®ion)\n{\n assert(_active);\n valid = region.valid;\n lower = region.lower;\n upper = region.upper;\n xalign = region.xalign;\n yalign = region.yalign;\n zalign = region.zalign;\n return *this;\n}\n\nCORBA::Boolean RegionImpl::defined() { return valid;}\nvoid RegionImpl::clear() { valid = false;}\n\nCORBA::Boolean RegionImpl::contains(const Vertex &v)\n{\n return (valid &&\n\t v.x >= lower.x && v.x <= upper.x &&\n\t v.y >= lower.y && v.y <= upper.y &&\n\t v.z >= lower.z && v.z <= upper.z\n\t );\n}\n\nCORBA::Boolean RegionImpl::contains_plane(const Vertex &v, Axis a)\n{\n bool b = false;\n if (valid)\n {\n switch (a)\n\t{\n\tcase xaxis:\n\t b = (v.y >= lower.y && v.y <= upper.y &&\n\t v.z >= lower.z && v.z <= upper.z);\n\t break;\n\tcase yaxis:\n\t b = (v.x >= lower.x && v.x <= upper.x &&\n\t v.z >= lower.z && v.z <= upper.z);\n\t break;\n\tcase zaxis:\n\t b = (v.x >= lower.x && v.x <= upper.x &&\n\t v.y >= lower.y && v.y <= upper.y);\n\t break;\n\t}\n }\n return b;\n}\n\nCORBA::Boolean RegionImpl::intersects(Region_ptr region)\n{\n if (valid)\n {\n Vertex l, u;\n region->bounds(l, u);\n return lower.x <= u.x && upper.x >= l.x && lower.y <= u.y && upper.y >= l.y;\n }\n return false;\n}\n\nCORBA::Boolean RegionImpl::intersects(const RegionImpl ®ion) const\n{\n if (valid && region.valid)\n return (lower.x <= region.upper.x &&\n\t upper.x >= region.lower.x &&\n\t lower.y <= region.upper.y &&\n\t upper.y >= region.lower.y);\n else return false;\n}\n\nvoid RegionImpl::copy(Region_ptr region)\n{\n if (!CORBA::is_nil(region) && region->defined())\n {\n Warsaw::Region::Allotment x, y, z;\n region->span(xaxis, x);\n region->span(yaxis, y);\n region->span(zaxis, z);\n valid = true;\n lower.x = x.begin;\n lower.y = y.begin;\n lower.z = z.begin;\n upper.x = x.end;\n upper.y = y.end;\n upper.z = z.end;\n xalign = x.align;\n yalign = y.align;\n zalign = z.align;\n }\n}\n\nvoid RegionImpl::merge_intersect(Region_ptr region)\n{\n if (region->defined())\n {\n if (valid)\n\t{\n\t Vertex l, u;\n\t region->bounds(l, u);\n\t merge_max(lower, l);\n\t merge_min(upper, u);\n }\n else copy(region);\n }\n}\n\nvoid RegionImpl::merge_union(Region_ptr region)\n{\n if (region->defined())\n {\n if (valid)\n\t{\n\t Vertex l, u;\n\t region->bounds(l, u);\n\t merge_min(lower, l);\n\t merge_max(upper, u);\n }\n else copy(region);\n }\n}\n\nvoid RegionImpl::subtract(Region_ptr region)\n{\n \/\/ not implemented\n}\n\nvoid RegionImpl::apply_transform(Transform_ptr transformation)\n{\n if (!valid) return;\n Transform::Matrix matrix;\n transformation->store_matrix(matrix);\n apply_transform(matrix);\n};\n\n\/*\n * note: the new region is the bounding box of the transformed\n * old region\n *\n * This algorithm takes advantage of some\n * interesting properties of affine transformations: i.e., opposite sides\n * are always parallel and same in length. Another property of\n * affine transformation is that the transformed center of a box\n * is equal to the center of the transformed box. Realizing these\n * properties, finding the transformed box can be broken down as finding\n * the effective width, height, depth, and center. The last is easy.\n * Each of the other three values is found by first breaking down\n * each of the transformed axis vectors into x, y, and z vectors.\n * Joining all the absolute vectors on a certain axis gives you\n * the size of the box on that axis. Width, for example,\n * forms a (w, 0, 0) vector. After transformation, it becomes\n * (Xw, Yw, Zw). The new width is then given as abs(Xw) + abs(Xh) + abs(Xd)\n *\/\nvoid RegionImpl::apply_transform(const Transform::Matrix &matrix)\n{\n Vertex o;\n\n origin(o);\n o *= matrix;\n\n Coord lx = upper.x - lower.x;\n Coord ly = upper.y - lower.y;\n Coord lz = upper.z - lower.z;\n \n Vertex center;\n center.x = (upper.x + lower.x) * 0.5;\n center.y = (upper.y + lower.y) * 0.5;\n center.z = (upper.z + lower.z) * 0.5;\n \n \/\/ transform the center\n center *= matrix;\n \n \/\/ optimized computation of new width and height\n Coord nlx = Math::abs(lx * matrix[0][0]) + Math::abs(ly * matrix[0][1]) + Math::abs(lz * matrix[0][2]);\n Coord nly = Math::abs(lx * matrix[1][0]) + Math::abs(ly * matrix[1][1]) + Math::abs(lz * matrix[1][2]);\n Coord nlz = Math::abs(lx * matrix[2][0]) + Math::abs(ly * matrix[2][1]) + Math::abs(lz * matrix[2][2]);\n \n \/\/ form the new box\n lower.x = center.x - nlx * 0.5;\n upper.x = center.x + nlx * 0.5;\n lower.y = center.y - nly * 0.5;\n upper.y = center.y + nly * 0.5;\n lower.z = center.z - nlz * 0.5;\n upper.z = center.z + nlz * 0.5;\n \n if (!Math::equal(nlx, 0., 1e-4)) xalign = (o.x - lower.x) \/ nlx;\n if (!Math::equal(nly, 0., 1e-4)) yalign = (o.y - lower.y) \/ nly;\n if (!Math::equal(nlz, 0., 1e-4)) zalign = (o.z - lower.z) \/ nlz;\n}\n\nvoid RegionImpl::bounds(Vertex &l, Vertex &u)\n{\n l = lower;\n u = upper;\n}\n\nvoid RegionImpl::center(Vertex &c)\n{\n c.x = (lower.x + upper.x) * 0.5;\n c.y = (lower.y + upper.y) * 0.5;\n c.z = 0.0;\n}\n\nvoid RegionImpl::origin(Vertex &v)\n{\n v.x = span_origin(lower.x, upper.x, xalign);\n v.y = span_origin(lower.y, upper.y, yalign);\n v.z = span_origin(lower.z, upper.z, zalign);\n}\n\nvoid RegionImpl::span(Axis a, Warsaw::Region::Allotment &s)\n{\n switch (a)\n {\n case xaxis:\n s.begin = lower.x;\n s.end = upper.x;\n s.align = xalign;\n break;\n case yaxis:\n s.begin = lower.y;\n s.end = upper.y;\n s.align = yalign;\n break;\n case zaxis:\n s.begin = lower.z;\n s.end = upper.z;\n s.align = zalign;\n break;\n }\n}\n\nvoid RegionImpl::outline(Path_out)\n{\n};\n\nstd::ostream &operator << (std::ostream &os, const RegionImpl ®ion)\n{\n if (!region.valid) os << \"undef\";\n else\n {\n os << \"X(\" << region.lower.x << ',' << region.upper.x;\n if (!Math::equal(region.xalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.xalign;\n os << \"), Y(\" << region.lower.y << ',' << region.upper.y;\n if (!Math::equal(region.yalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.yalign;\n os << \"), Z(\" << region.lower.z << ',' << region.upper.z;\n if (!Math::equal(region.zalign, 0., 1e-2)) os << \" @ \" << std::setprecision(1) << region.zalign;\n os << ')';\n }\n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(|V| + |E|)\n\/\/ Space: O(|V|)\n\nclass Solution {\npublic:\n struct node {\n int parent;\n vector<int>neighbors;\n };\n bool validTree(int n, vector<pair<int, int>>& edges) {\n if (edges.size() != n - 1) {\n return false;\n }\n\n unordered_map<int,node> nodes;\n unordered_set<int> visited;\n for (const auto& edge : edges) {\n nodes[edge.first].neighbors.emplace_back(edge.second);\n nodes[edge.second].neighbors.emplace_back(edge.first);\n }\n for (int i = 0; i < n; ++i) {\n nodes[i].parent = -1;\n }\n\n queue<int> q;\n q.emplace(0);\n visited.insert(0);\n while (!q.empty()) {\n int i = q.front();\n q.pop();\n for (const auto& n : nodes[i].neighbors) {\n if (n != nodes[i].parent) {\n if (visited.find(n) != visited.end()) {\n return false;\n } else {\n visited.insert(n);\n nodes[n].parent = i;\n q.emplace(n);\n }\n }\n }\n }\n return true;\n }\n};\n<commit_msg>Update graph-valid-tree.cpp<commit_after>\/\/ Time: O(|V| + |E|)\n\/\/ Space: O(|V|)\n\nclass Solution {\npublic:\n struct node {\n int parent;\n vector<int>neighbors;\n };\n bool validTree(int n, vector<pair<int, int>>& edges) {\n if (edges.size() != n - 1) {\n return false;\n }\n\n unordered_map<int,node> nodes;\n for (const auto& edge : edges) {\n nodes[edge.first].neighbors.emplace_back(edge.second);\n nodes[edge.second].neighbors.emplace_back(edge.first);\n }\n for (int i = 0; i < n; ++i) {\n nodes[i].parent = -1;\n }\n\n unordered_set<int> visited;\n queue<int> q;\n q.emplace(0);\n while (!q.empty()) {\n int i = q.front();\n q.pop();\n visited.insert(i);\n for (const auto& n : nodes[i].neighbors) {\n if (n != nodes[i].parent) {\n if (visited.find(n) != visited.end()) {\n return false;\n } else {\n visited.insert(n);\n nodes[n].parent = i;\n q.emplace(n);\n }\n }\n }\n }\n return true;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#include <iostream>\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"auth.h\"\n#include \"tao\/util.h\"\n\nusing std::string;\n\nusing tao::Base64WEncode;\nusing tao::InitializeApp;\nusing tao::MarshalKeyPrin;\nusing tao::MarshalSpeaksfor;\n\nint main(int argc, char **argv) {\n InitializeApp(&argc, &argv, false);\n\n \/\/ A fake key for the parent.\n string taoKeyName(\"test tao key\");\n string taoName;\n if (!MarshalKeyPrin(taoKeyName, &taoName)) {\n LOG(FATAL) << \"Could not marshal a fake key auth.Prin value\";\n }\n\n \/\/ A dummy key string to encode as bytes in MarshalSpeaksfor\n string testKey(\"test key\");\n string speaksfor;\n if (!MarshalSpeaksfor(testKey, taoName, &speaksfor)) {\n LOG(FATAL) << \"Could not marshal a speaksfor statement\";\n }\n\n string encoded;\n if (!Base64WEncode(speaksfor, &encoded)) {\n LOG(FATAL) << \"Could not encode the speaksfor in Base64W\";\n }\n\n std::cout << encoded << std::endl;\n return 0;\n}\n<commit_msg>Add a test of the generated marshalling code.<commit_after>\/\/ Copyright (c) 2014, Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#include <iostream>\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n#include <google\/protobuf\/io\/coded_stream.h>\n#include <google\/protobuf\/io\/zero_copy_stream_impl_lite.h>\n#include <google\/protobuf\/stubs\/common.h>\n\n#include \"auth.h\"\n#include \"tao\/util.h\"\n\nusing google::protobuf::io::CodedOutputStream;\nusing google::protobuf::io::StringOutputStream;\nusing std::string;\nusing tao::Base64WEncode;\nusing tao::Bytes;\nusing tao::InitializeApp;\nusing tao::MarshalKeyPrin;\nusing tao::MarshalSpeaksfor;\nusing tao::Prin;\nusing tao::PrinExt;\nusing tao::SubPrin;\n\nnamespace {\n\/\/ This is the canonical implementation of make_unique for C++11. It is wrapped\n\/\/ in an anonymous namespace to keep it from conflicting with the real thing if\n\/\/ it exists.\ntemplate<typename T, typename ...Args>\nstd::unique_ptr<T> make_unique( Args&& ...args )\n{\n return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );\n}\n} \/\/ namespace\n\n\nint main(int argc, char **argv) {\n InitializeApp(&argc, &argv, false);\n\n Prin p;\n p.type_ = \"key\";\n\n auto bytes = make_unique<Bytes>();\n bytes->elt_ = \"These are not key bytes\";\n p.key_ = std::move(bytes);\n\n p.ext_ = make_unique<SubPrin>();\n auto ext = make_unique<PrinExt>();\n ext->name_ = \"Validated\";\n p.ext_->elts_.emplace_back(std::move(ext));\n\n string serialized_prin;\n {\n StringOutputStream raw_output_stream(&serialized_prin);\n CodedOutputStream output_stream(&raw_output_stream);\n p.Marshal(&output_stream);\n }\n\n string encoded_prin;\n if (!Base64WEncode(serialized_prin, &encoded_prin)) {\n LOG(FATAL) << \"Could not encode the prin in Base64W\";\n }\n\n std::cout << \"A Prin encoded with Base64W:\" << std::endl;\n std::cout << encoded_prin << std::endl;\n\n \/\/ A fake key for the parent.\n string taoKeyName(\"test tao key\");\n string taoName;\n if (!MarshalKeyPrin(taoKeyName, &taoName)) {\n LOG(FATAL) << \"Could not marshal a fake key auth.Prin value\";\n }\n\n \/\/ A dummy key string to encode as bytes in MarshalSpeaksfor\n string testKey(\"test key\");\n string speaksfor;\n if (!MarshalSpeaksfor(testKey, taoName, &speaksfor)) {\n LOG(FATAL) << \"Could not marshal a speaksfor statement\";\n }\n\n string encoded;\n if (!Base64WEncode(speaksfor, &encoded)) {\n LOG(FATAL) << \"Could not encode the speaksfor in Base64W\";\n }\n\n std::cout << \"A Speaksfor encoded with Base64W:\" << std::endl;\n std::cout << encoded << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_REGFILE_HH__\n#define __ARCH_X86_REGFILE_HH__\n\n#include \"arch\/x86\/floatregfile.hh\"\n#include \"arch\/x86\/intregfile.hh\"\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"arch\/x86\/miscregfile.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"sim\/host.hh\"\n\n#include <string>\n\nclass Checkpoint;\n\nnamespace X86ISA\n{\n class RegFile\n {\n protected:\n Addr rip; \/\/Program Counter\n Addr nextRip; \/\/Next Program Counter\n\n public:\n Addr readPC();\n void SetPC(Addr val);\n\n Addr readNextPC();\n void setNextPC(Addr val);\n\n Addr readNextNPC();\n void setNextNPC(Addr val);\n\n protected:\n IntRegFile intRegFile; \/\/ integer register file\n FloatRegFile floatRegFile; \/\/ floating point register file\n MiscRegFile miscRegFile; \/\/ control register file\n\n public:\n\n void clear();\n\n int FlattenIntIndex(int reg);\n\n MiscReg readMiscReg(int miscReg);\n\n MiscReg readMiscRegWithEffect(int miscReg, ThreadContext *tc);\n\n void setMiscReg(int miscReg, const MiscReg &val);\n\n void setMiscRegWithEffect(int miscReg, const MiscReg &val,\n ThreadContext * tc);\n\n int instAsid()\n {\n \/\/XXX This doesn't make sense in x86\n return 0;\n }\n\n int dataAsid()\n {\n \/\/XXX This doesn't make sense in x86\n return 0;\n }\n\n FloatReg readFloatReg(int floatReg, int width);\n\n FloatReg readFloatReg(int floatReg);\n\n FloatRegBits readFloatRegBits(int floatReg, int width);\n\n FloatRegBits readFloatRegBits(int floatReg);\n\n void setFloatReg(int floatReg, const FloatReg &val, int width);\n\n void setFloatReg(int floatReg, const FloatReg &val);\n\n void setFloatRegBits(int floatReg, const FloatRegBits &val, int width);\n\n void setFloatRegBits(int floatReg, const FloatRegBits &val);\n\n IntReg readIntReg(int intReg);\n\n void setIntReg(int intReg, const IntReg &val);\n\n void serialize(std::ostream &os);\n void unserialize(Checkpoint *cp, const std::string §ion);\n\n public:\n\n void changeContext(RegContextParam param, RegContextVal val);\n };\n\n int flattenIntIndex(ThreadContext * tc, int reg);\n\n void copyRegs(ThreadContext *src, ThreadContext *dest);\n\n void copyMiscRegs(ThreadContext *src, ThreadContext *dest);\n\n int InterruptLevel(uint64_t softint);\n\n}; \/\/ namespace X86ISA\n\n#endif \/\/ __ARCH_X86_REGFILE_HH__\n<commit_msg>Correct a typo<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_REGFILE_HH__\n#define __ARCH_X86_REGFILE_HH__\n\n#include \"arch\/x86\/floatregfile.hh\"\n#include \"arch\/x86\/intregfile.hh\"\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"arch\/x86\/miscregfile.hh\"\n#include \"arch\/x86\/types.hh\"\n#include \"sim\/host.hh\"\n\n#include <string>\n\nclass Checkpoint;\n\nnamespace X86ISA\n{\n class RegFile\n {\n protected:\n Addr rip; \/\/Program Counter\n Addr nextRip; \/\/Next Program Counter\n\n public:\n Addr readPC();\n void setPC(Addr val);\n\n Addr readNextPC();\n void setNextPC(Addr val);\n\n Addr readNextNPC();\n void setNextNPC(Addr val);\n\n protected:\n IntRegFile intRegFile; \/\/ integer register file\n FloatRegFile floatRegFile; \/\/ floating point register file\n MiscRegFile miscRegFile; \/\/ control register file\n\n public:\n\n void clear();\n\n int FlattenIntIndex(int reg);\n\n MiscReg readMiscReg(int miscReg);\n\n MiscReg readMiscRegWithEffect(int miscReg, ThreadContext *tc);\n\n void setMiscReg(int miscReg, const MiscReg &val);\n\n void setMiscRegWithEffect(int miscReg, const MiscReg &val,\n ThreadContext * tc);\n\n int instAsid()\n {\n \/\/XXX This doesn't make sense in x86\n return 0;\n }\n\n int dataAsid()\n {\n \/\/XXX This doesn't make sense in x86\n return 0;\n }\n\n FloatReg readFloatReg(int floatReg, int width);\n\n FloatReg readFloatReg(int floatReg);\n\n FloatRegBits readFloatRegBits(int floatReg, int width);\n\n FloatRegBits readFloatRegBits(int floatReg);\n\n void setFloatReg(int floatReg, const FloatReg &val, int width);\n\n void setFloatReg(int floatReg, const FloatReg &val);\n\n void setFloatRegBits(int floatReg, const FloatRegBits &val, int width);\n\n void setFloatRegBits(int floatReg, const FloatRegBits &val);\n\n IntReg readIntReg(int intReg);\n\n void setIntReg(int intReg, const IntReg &val);\n\n void serialize(std::ostream &os);\n void unserialize(Checkpoint *cp, const std::string §ion);\n\n public:\n\n void changeContext(RegContextParam param, RegContextVal val);\n };\n\n int flattenIntIndex(ThreadContext * tc, int reg);\n\n void copyRegs(ThreadContext *src, ThreadContext *dest);\n\n void copyMiscRegs(ThreadContext *src, ThreadContext *dest);\n\n int InterruptLevel(uint64_t softint);\n\n}; \/\/ namespace X86ISA\n\n#endif \/\/ __ARCH_X86_REGFILE_HH__\n<|endoftext|>"} {"text":"<commit_before>#include \"details\/compiler\/compiler.h\"\n#include \"details\/compiler\/compdb.h\"\n#include \"details\/program\/program.h\"\n#include \"details\/reporting\/report.h\"\n#include \"details\/errors\/errors.h\"\n#include \"details\/pass\/a-src2ast\/ast-from-source.h\"\n#include \"details\/pass\/b-ast-normalize\/normalize.h\"\n#include \"details\/pass\/c-ast2ir\/source-ast-to-ir.h\"\n#include \"details\/pass\/d-object-map\/attach.h\"\n#include \"details\/semantic\/atom-factory.h\"\n#include \"details\/intrinsic\/std.core.h\"\n#include \"libnanyc-config.h\"\n#include \"libnanyc-traces.h\"\n#include \"embed-nsl.hxx\" \/\/ generated\n#include <yuni\/io\/file.h>\n#include <libnanyc.h>\n#include <utility>\n#include <memory>\n#include <iostream>\n\nnamespace ny {\nnamespace compiler {\n\nnamespace {\n\nconstexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;\n\nLogs::Report buildGenerateReport(void* ptr, Logs::Level level) {\n\treturn (*((ny::Logs::Report*) ptr)).fromErrLevel(level);\n}\n\nvoid copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tif (opts.filename.len != 0) {\n\t\tif (unlikely(opts.filename.len > memoryHardlimit))\n\t\t\tthrow \"input filename bigger than internal limit\";\n\t\tyuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});\n\t\tsource.filename = source.storageFilename;\n\t}\n\tif (opts.content.len != 0) {\n\t\tif (unlikely(opts.content.len > memoryHardlimit))\n\t\t\tthrow \"input source content bigger than internal limit\";\n\t\tsource.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));\n\t\tsource.content = source.storageContent;\n\t}\n}\n\nbool compileSource(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts) {\n\tauto report = mainreport.subgroup();\n\treport.data().origins.location.filename = source.filename;\n\treport.data().origins.location.target.clear();\n\tbool compiled = true;\n\tcompiled &= makeASTFromSource(source);\n\tcompiled &= passDuplicateAndNormalizeAST(source, report);\n\tcompiled &= passTransformASTToIR(source, report, gopts);\n\tcompiled = compiled and attach(compdb, source);\n\treturn compiled;\n}\n\nbool importSourceAndCompile(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts, const nysource_opts_t& opts) {\n\tcopySourceOpts(source, opts);\n\treturn compileSource(mainreport, compdb, source, gopts);\n}\n\nAtom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {\n\tAtom* atom = nullptr;\n\troot.eachChild(entrypoint, [&](Atom & child) -> bool {\n\t\tif (unlikely(atom != nullptr))\n\t\t\tthrow \"': multiple entry points found\";\n\t\tatom = &child;\n\t\treturn true;\n\t});\n\tif (unlikely(!atom))\n\t\tthrow \"()': function not found\";\n\tif (unlikely(not atom->isFunction() or atom->isClassMember()))\n\t\tthrow \"': the atom is not a function\";\n\treturn *atom;\n}\n\nbool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {\n\tusing ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);\n\ttry {\n\t\tauto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);\n\t\tParameterList params;\n\t\tParameterList tmplparams;\n\t\tClassdefTableView cdeftblView{compdb.cdeftable};\n\t\tny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);\n\t\tbool instanciated = ny::semantic::instanciateAtom(settings);\n\t\treport.appendEntry(settings.report);\n\t\tif (config::traces::atomTable)\n\t\t\tcompdb.cdeftable.atoms.root.printTree(compdb.cdeftable);\n\t\tif (likely(instanciated)) {\n\t\t\tcompdb.entrypoint.atomid = atom.atomid;\n\t\t\tcompdb.entrypoint.instanceid = settings.instanceid;\n\t\t\treturn true;\n\t\t}\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << \"failed to instanciate '\" << entrypoint << e;\n\t}\n\tcompdb.entrypoint.atomid = (uint32_t) -1;\n\tcompdb.entrypoint.instanceid = (uint32_t) -1;\n\treturn false;\n}\n\nstd::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {\n\tny::Logs::Report report{compdb.messages};\n\tLogs::Handler errorHandler{&report, &buildGenerateReport};\n\ttry {\n\t\tauto& opts = compdb.opts;\n\t\tuint32_t scount = opts.sources.count;\n\t\tif (unlikely(scount == 0))\n\t\t\tthrow \"no input source code\";\n\t\tif (config::importNSL)\n\t\t\tny::intrinsic::import::all(compdb.intrinsics);\n\t\tif (config::importNSL)\n\t\t\tscount += corefilesCount;\n\t\tif (unlikely(opts.with_nsl_unittests == nytrue))\n\t\t\tscount += unittestCount;\n\t\tauto& sources = compdb.sources;\n\t\tsources.count = scount;\n\t\tsources.items = std::make_unique<Source[]>(scount);\n\t\tbool compiled = true;\n\t\tuint32_t offset = 0;\n\t\tif (config::importNSL) {\n\t\t\tregisterNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {\n\t\t\t\tcompiled &= compileSource(report, compdb, source, opts);\n\t\t\t});\n\t\t}\n\t\tif (opts.with_nsl_unittests == nytrue) {\n\t\t\tregisterUnittestFiles(sources, offset, [&](ny::compiler::Source& source) {\n\t\t\t\tcompiled &= compileSource(report, compdb, source, opts);\n\t\t\t});\n\t\t}\n\t\tfor (uint32_t i = 0; i != opts.sources.count; ++i) {\n\t\t\tauto& source = sources[offset + i];\n\t\t\tcompiled &= importSourceAndCompile(report, compdb, source, opts, opts.sources.items[i]);\n\t\t}\n\t\tcompiled = compiled\n\t\t\tand compdb.cdeftable.atoms.fetchAndIndexCoreObjects() \/\/ indexing bool, u32, f64...\n\t\t\tand ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); \/\/ typedef\n\t\tif (config::traces::preAtomTable)\n\t\t\tcompdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});\n\t\tif (unlikely(not compiled))\n\t\t\treturn nullptr;\n\t\tauto& entrypoint = compdb.opts.entrypoint;\n\t\tif (unlikely(entrypoint.len == 0))\n\t\t\treturn nullptr;\n\t\tbool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));\n\t\tif (unlikely(not epinst))\n\t\t\treturn nullptr;\n\t\treturn std::make_unique<ny::Program>();\n\t}\n\tcatch (const std::bad_alloc& e) {\n\t\treport.ice() << \"not enough memory when compiling\";\n\t}\n\tcatch (const std::exception& e) {\n\t\treport.ice() << \"exception: \" << e.what();\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << e;\n\t}\n\tcatch (...) {\n\t\treport.ice() << \"uncaught exception when compiling\";\n\t}\n\treturn nullptr;\n}\n\n} \/\/ namespace\n\nnyprogram_t* compile(nycompile_opts_t& opts) {\n\ttry {\n\t\tif (opts.on_build_start)\n\t\t\topts.userdata = opts.on_build_start(opts.userdata);\n\t\tauto compdb = std::make_unique<Compdb>(opts);\n\t\tauto program = compile(*compdb);\n\t\tif (opts.on_build_stop)\n\t\t\topts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));\n\t\tif (opts.on_report and not compdb->messages.entries.empty())\n\t\t\topts.on_report(opts.userdata, reinterpret_cast<const nyreport_t*>(&compdb->messages));\n\t\tif (unlikely(!program))\n\t\t\treturn nullptr;\n\t\tprogram->compdb = std::move(compdb);\n\t\treturn ny::Program::pointer(program.release());\n\t}\n\tcatch (...) {\n\t}\n\tif (opts.on_build_stop)\n\t\topts.on_build_stop(opts.userdata, nyfalse);\n\treturn nullptr;\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace ny\n<commit_msg>fix warning unused variable<commit_after>#include \"details\/compiler\/compiler.h\"\n#include \"details\/compiler\/compdb.h\"\n#include \"details\/program\/program.h\"\n#include \"details\/reporting\/report.h\"\n#include \"details\/errors\/errors.h\"\n#include \"details\/pass\/a-src2ast\/ast-from-source.h\"\n#include \"details\/pass\/b-ast-normalize\/normalize.h\"\n#include \"details\/pass\/c-ast2ir\/source-ast-to-ir.h\"\n#include \"details\/pass\/d-object-map\/attach.h\"\n#include \"details\/semantic\/atom-factory.h\"\n#include \"details\/intrinsic\/std.core.h\"\n#include \"libnanyc-config.h\"\n#include \"libnanyc-traces.h\"\n#include \"embed-nsl.hxx\" \/\/ generated\n#include <yuni\/io\/file.h>\n#include <libnanyc.h>\n#include <utility>\n#include <memory>\n#include <iostream>\n\nnamespace ny {\nnamespace compiler {\n\nnamespace {\n\nconstexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;\n\nLogs::Report buildGenerateReport(void* ptr, Logs::Level level) {\n\treturn (*((ny::Logs::Report*) ptr)).fromErrLevel(level);\n}\n\nvoid copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {\n\tif (opts.filename.len != 0) {\n\t\tif (unlikely(opts.filename.len > memoryHardlimit))\n\t\t\tthrow \"input filename bigger than internal limit\";\n\t\tyuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});\n\t\tsource.filename = source.storageFilename;\n\t}\n\tif (opts.content.len != 0) {\n\t\tif (unlikely(opts.content.len > memoryHardlimit))\n\t\t\tthrow \"input source content bigger than internal limit\";\n\t\tsource.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));\n\t\tsource.content = source.storageContent;\n\t}\n}\n\nbool compileSource(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts) {\n\tauto report = mainreport.subgroup();\n\treport.data().origins.location.filename = source.filename;\n\treport.data().origins.location.target.clear();\n\tbool compiled = true;\n\tcompiled &= makeASTFromSource(source);\n\tcompiled &= passDuplicateAndNormalizeAST(source, report);\n\tcompiled &= passTransformASTToIR(source, report, gopts);\n\tcompiled = compiled and attach(compdb, source);\n\treturn compiled;\n}\n\nbool importSourceAndCompile(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts, const nysource_opts_t& opts) {\n\tcopySourceOpts(source, opts);\n\treturn compileSource(mainreport, compdb, source, gopts);\n}\n\nAtom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {\n\tAtom* atom = nullptr;\n\troot.eachChild(entrypoint, [&](Atom & child) -> bool {\n\t\tif (unlikely(atom != nullptr))\n\t\t\tthrow \"': multiple entry points found\";\n\t\tatom = &child;\n\t\treturn true;\n\t});\n\tif (unlikely(!atom))\n\t\tthrow \"()': function not found\";\n\tif (unlikely(not atom->isFunction() or atom->isClassMember()))\n\t\tthrow \"': the atom is not a function\";\n\treturn *atom;\n}\n\nbool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {\n\tusing ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);\n\ttry {\n\t\tauto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);\n\t\tParameterList params;\n\t\tParameterList tmplparams;\n\t\tClassdefTableView cdeftblView{compdb.cdeftable};\n\t\tny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);\n\t\tbool instanciated = ny::semantic::instanciateAtom(settings);\n\t\treport.appendEntry(settings.report);\n\t\tif (config::traces::atomTable)\n\t\t\tcompdb.cdeftable.atoms.root.printTree(compdb.cdeftable);\n\t\tif (likely(instanciated)) {\n\t\t\tcompdb.entrypoint.atomid = atom.atomid;\n\t\t\tcompdb.entrypoint.instanceid = settings.instanceid;\n\t\t\treturn true;\n\t\t}\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << \"failed to instanciate '\" << entrypoint << e;\n\t}\n\tcompdb.entrypoint.atomid = (uint32_t) -1;\n\tcompdb.entrypoint.instanceid = (uint32_t) -1;\n\treturn false;\n}\n\nstd::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {\n\tny::Logs::Report report{compdb.messages};\n\tLogs::Handler errorHandler{&report, &buildGenerateReport};\n\ttry {\n\t\tauto& opts = compdb.opts;\n\t\tuint32_t scount = opts.sources.count;\n\t\tif (unlikely(scount == 0))\n\t\t\tthrow \"no input source code\";\n\t\tif (config::importNSL)\n\t\t\tny::intrinsic::import::all(compdb.intrinsics);\n\t\tif (config::importNSL)\n\t\t\tscount += corefilesCount;\n\t\tif (unlikely(opts.with_nsl_unittests == nytrue))\n\t\t\tscount += unittestCount;\n\t\tauto& sources = compdb.sources;\n\t\tsources.count = scount;\n\t\tsources.items = std::make_unique<Source[]>(scount);\n\t\tbool compiled = true;\n\t\tuint32_t offset = 0;\n\t\tif (config::importNSL) {\n\t\t\tregisterNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {\n\t\t\t\tcompiled &= compileSource(report, compdb, source, opts);\n\t\t\t});\n\t\t}\n\t\tif (opts.with_nsl_unittests == nytrue) {\n\t\t\tregisterUnittestFiles(sources, offset, [&](ny::compiler::Source& source) {\n\t\t\t\tcompiled &= compileSource(report, compdb, source, opts);\n\t\t\t});\n\t\t}\n\t\tfor (uint32_t i = 0; i != opts.sources.count; ++i) {\n\t\t\tauto& source = sources[offset + i];\n\t\t\tcompiled &= importSourceAndCompile(report, compdb, source, opts, opts.sources.items[i]);\n\t\t}\n\t\tcompiled = compiled\n\t\t\tand compdb.cdeftable.atoms.fetchAndIndexCoreObjects() \/\/ indexing bool, u32, f64...\n\t\t\tand ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); \/\/ typedef\n\t\tif (config::traces::preAtomTable)\n\t\t\tcompdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});\n\t\tif (unlikely(not compiled))\n\t\t\treturn nullptr;\n\t\tauto& entrypoint = compdb.opts.entrypoint;\n\t\tif (unlikely(entrypoint.len == 0))\n\t\t\treturn nullptr;\n\t\tbool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));\n\t\tif (unlikely(not epinst))\n\t\t\treturn nullptr;\n\t\treturn std::make_unique<ny::Program>();\n\t}\n\tcatch (const std::bad_alloc&) {\n\t\treport.ice() << \"not enough memory when compiling\";\n\t}\n\tcatch (const std::exception& e) {\n\t\treport.ice() << \"exception: \" << e.what();\n\t}\n\tcatch (const char* e) {\n\t\treport.error() << e;\n\t}\n\tcatch (...) {\n\t\treport.ice() << \"uncaught exception when compiling\";\n\t}\n\treturn nullptr;\n}\n\n} \/\/ namespace\n\nnyprogram_t* compile(nycompile_opts_t& opts) {\n\ttry {\n\t\tif (opts.on_build_start)\n\t\t\topts.userdata = opts.on_build_start(opts.userdata);\n\t\tauto compdb = std::make_unique<Compdb>(opts);\n\t\tauto program = compile(*compdb);\n\t\tif (opts.on_build_stop)\n\t\t\topts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));\n\t\tif (opts.on_report and not compdb->messages.entries.empty())\n\t\t\topts.on_report(opts.userdata, reinterpret_cast<const nyreport_t*>(&compdb->messages));\n\t\tif (unlikely(!program))\n\t\t\treturn nullptr;\n\t\tprogram->compdb = std::move(compdb);\n\t\treturn ny::Program::pointer(program.release());\n\t}\n\tcatch (...) {\n\t}\n\tif (opts.on_build_stop)\n\t\topts.on_build_stop(opts.userdata, nyfalse);\n\treturn nullptr;\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace ny\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Emilian Cioca\nnamespace Jwl\n{\n\tnamespace detail\n\t{\n\t\t\/\/ Index of all Entities for each component and tag type.\n\t\t\/\/ Sorted to allow for logical operations, such as ANDing, between multiple tables in the index.\n\t\textern std::unordered_map<unsigned, std::vector<Entity*>> entityIndex;\n\n\t\t\/\/ Index of all Components of a particular type.\n\t\t\/\/ Not sorted since no logical operations are performed using these tables.\n\t\textern std::unordered_map<unsigned, std::vector<ComponentBase*>> componentIndex;\n\n\t\t\/\/ A lightweight tag representing the end of a query's range. We use this rather than creating another\n\t\t\/\/ potentially large end-iterator. Our custom iterators already have all the information they need to\n\t\t\/\/ detect if they have expired, so we use this tag to ask them when they has finished enumerating the range.\n\t\tstruct RangeEndSentinel {};\n\n\t\t\/\/ Enumerates a table of the componentIndex while performing a cast and a dereference.\n\t\ttemplate<class Component>\n\t\tclass ComponentIterator : public std::iterator<std::forward_iterator_tag, Component>\n\t\t{\n\t\t\tusing Iterator = std::vector<ComponentBase*>::iterator;\n\t\tpublic:\n\t\t\tComponentIterator(Iterator _itr, Iterator _itrEnd)\n\t\t\t\t: itr(_itr), itrEnd(_itrEnd)\n\t\t\t{}\n\n\t\t\tComponentIterator& operator++()\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\t++itr;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tComponent& operator*() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *static_cast<Component*>(*itr);\n\t\t\t}\n\n\t\t\tbool operator==(RangeEndSentinel) const { return IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !IsTerminated(); }\n\n\t\t\tbool IsTerminated() const { return itr == itrEnd; }\n\n\t\tprivate:\n\t\t\t\/\/ The current position in the target table.\n\t\t\tIterator itr;\n\t\t\t\/\/ Ensures that we don't surpass the table while we are skipping items.\n\t\t\tconst Iterator itrEnd;\n\t\t};\n\n\t\t\/\/ A safe iterator used to enumerate the entityIndex tables.\n\t\t\/\/ Although it models a single iterator, it knows when it has reached the end of the table.\n\t\tclass SafeIterator : public std::iterator<std::forward_iterator_tag, Entity*>\n\t\t{\n\t\t\tusing Iterator = std::vector<Entity*>::iterator;\n\t\tpublic:\n\t\t\tSafeIterator(Iterator _itr, Iterator _itrEnd)\n\t\t\t\t: itr(_itr), itrEnd(_itrEnd)\n\t\t\t{}\n\n\t\t\tSafeIterator& operator++()\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\t++itr;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tEntity& operator*() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *(*itr);\n\t\t\t}\n\n\t\t\tEntity* Get() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *itr;\n\t\t\t}\n\n\t\t\tbool operator==(RangeEndSentinel) const { return IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !IsTerminated(); }\n\n\t\t\tbool IsTerminated() const { return itr == itrEnd; }\n\t\t\tvoid Terminate() { itr = itrEnd; }\n\n\t\tprivate:\n\t\t\t\/\/ The current position in the table.\n\t\t\tIterator itr;\n\t\t\t\/\/ Ensures that we don't surpass the table while we are skipping items.\n\t\t\tconst Iterator itrEnd;\n\t\t};\n\n\t\t\/\/ Provides functions to advance two SafeIterators as a logical AND of two entityIndex tables.\n\t\t\/\/ This provider pattern will allow us to add more operations in the future.\n\t\tstruct Intersection\n\t\t{\n\t\t\tstatic void FindFirst(SafeIterator& itr1, SafeIterator& itr2)\n\t\t\t{\n\t\t\t\twhile (!(itr1.IsTerminated() || itr2.IsTerminated()))\n\t\t\t\t{\n\t\t\t\t\tEntity* p1 = itr1.Get();\n\t\t\t\t\tEntity* p2 = itr2.Get();\n\n\t\t\t\t\tif (p1 < p2)\n\t\t\t\t\t{\n\t\t\t\t\t\t++itr1;\n\t\t\t\t\t}\n\t\t\t\t\telse if (p1 > p2)\n\t\t\t\t\t{\n\t\t\t\t\t\t++itr2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Itr1 is the one that is checked for death, so propagate the termination if Itr2 finished first.\n\t\t\t\tif (itr2.IsTerminated())\n\t\t\t\t{\n\t\t\t\t\titr1.Terminate();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatic void FindNext(SafeIterator& itr1, SafeIterator& itr2)\n\t\t\t{\n\t\t\t\tFindFirst(++itr1, itr2);\n\t\t\t}\n\t\t};\n\n\t\t\/\/ Enumerates a SafeIterator and a templated iterator while performing a logical operation between them.\n\t\t\/\/ The templated iterator expands into a subtree of more LogicalIterators.\n\t\ttemplate<class Iterator, class Operation>\n\t\tclass LogicalIterator : public std::iterator<std::forward_iterator_tag, Entity*>\n\t\t{\n\t\tpublic:\n\t\t\tLogicalIterator(SafeIterator _itr1, Iterator _itr2)\n\t\t\t\t: itr1(_itr1), itr2(_itr2)\n\t\t\t{\n\t\t\t\tOperation::FindFirst(itr1, itr2.GetCurrentItr());\n\t\t\t}\n\n\t\t\tLogicalIterator& operator++()\n\t\t\t{\n\t\t\t\t\/\/ Update the right-hand side of the iterator hierarchy.\n\t\t\t\t++itr2;\n\n\t\t\t\t\/\/ Intersect the result of the subtree with our left-hand SafeIterator.\n\t\t\t\tOperation::FindNext(itr1, itr2.GetCurrentItr());\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSafeIterator& GetCurrentItr() { return itr1; }\n\n\t\t\tEntity& operator*() const { return *itr1; }\n\n\t\t\tbool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }\n\n\t\tprivate:\n\t\t\tSafeIterator itr1;\n\t\t\tIterator itr2;\n\t\t};\n\n\t\t\/\/ LogicalIterator specialization for the bottom of the hierarchy.\n\t\t\/\/ Directly operates on two SafeIterators.\n\t\ttemplate<class Operation>\n\t\tclass LogicalIterator<SafeIterator, Operation> : public std::iterator<std::forward_iterator_tag, Entity*>\n\t\t{\n\t\tpublic:\n\t\t\tLogicalIterator(SafeIterator _itr1, SafeIterator _itr2)\n\t\t\t\t: itr1(_itr1), itr2(_itr2)\n\t\t\t{\n\t\t\t\tOperation::FindFirst(itr1, itr2);\n\t\t\t}\n\n\t\t\tLogicalIterator& operator++()\n\t\t\t{\n\t\t\t\tOperation::FindNext(itr1, itr2);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSafeIterator& GetCurrentItr() { return itr1; }\n\n\t\t\tEntity& operator*() const { return *itr1; }\n\n\t\t\tbool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }\n\n\t\tprivate:\n\t\t\tSafeIterator itr1;\n\t\t\tSafeIterator itr2;\n\t\t};\n\n\t\t\/\/ Represents a lazy-evaluated range that can be used in a range-based for loop.\n\t\ttemplate<class RootIterator>\n\t\tclass Range\n\t\t{\n\t\tpublic:\n\t\t\tRange(RootIterator _itr)\n\t\t\t\t: itr(_itr)\n\t\t\t{}\n\n\t\t\tRootIterator& begin()\n\t\t\t{\n\t\t\t\treturn itr;\n\t\t\t}\n\n\t\t\tRangeEndSentinel end() const\n\t\t\t{\n\t\t\t\treturn {};\n\t\t\t}\n\n\t\tprivate:\n\t\t\t\/\/ The starting position of the range.\n\t\t\tRootIterator itr;\n\t\t};\n\n\t\t\/\/ Template deduction assisted construction.\n\t\ttemplate<class Iterator>\n\t\tauto BuildLogicalIterator(SafeIterator&& set1, Iterator&& set2)\n\t\t{\n\t\t\treturn LogicalIterator<Iterator, Intersection>(set1, set2);\n\t\t}\n\n\t\t\/\/ Constructs a logical iterator representing the start of the sequence.\n\t\ttemplate<typename Arg1, typename Arg2, typename... Args>\n\t\tauto BuildRootIterator()\n\t\t{\n\t\t\tauto& index = entityIndex[Arg1::GetComponentId()];\n\t\t\tauto begin = index.begin();\n\t\t\tauto end = index.end();\n\n\t\t\treturn BuildLogicalIterator(SafeIterator(begin, end), BuildRootIterator<Arg2, Args...>());\n\t\t}\n\n\t\t\/\/ BuildRootIterator() base case.\n\t\ttemplate<typename Arg>\n\t\tSafeIterator BuildRootIterator()\n\t\t{\n\t\t\tauto& index = entityIndex[Arg::GetComponentId()];\n\t\t\tauto begin = index.begin();\n\t\t\tauto end = index.end();\n\n\t\t\treturn SafeIterator(begin, end);\n\t\t}\n\t}\n\n\t\/\/ Returns an enumerable range of all enabled Components of the specified type.\n\t\/\/ By providing you the Component directly you don't have to waste time calling Entity.Get<>().\n\t\/\/ This is a faster option than With<>() but it only allows you to specify a single Component type.\n\ttemplate<class Component>\n\tauto All()\n\t{\n\t\tstatic_assert(std::is_base_of_v<ComponentBase, Component>,\n\t\t\t\"Template argument must be a Component.\");\n\n\t\tstatic_assert(!std::is_base_of_v<TagBase, Component>,\n\t\t\t\"Cannot query tags with All<>(). Use With<>() instead.\");\n\n\t\tstatic_assert(std::is_same_v<Component, typename Component::StaticComponentType>,\n\t\t\t\"Only a direct inheritor from Component<> can be used in a query.\");\n\n\t\tusing namespace detail;\n\t\tauto& index = componentIndex[Component::GetComponentId()];\n\t\tauto itr = ComponentIterator<Component>(index.begin(), index.end());\n\n\t\treturn detail::Range(itr);\n\t}\n\n\t\/\/ Returns an enumerable range of all Entities which have an active instance of each specified Component\/Tag.\n\t\/\/ Disabled Components and Components belonging to disabled Entities are not considered.\n\t\/\/ * Adding\/Removing Components or Tags of the queried types will invalidate the returned Range *\n\t\/\/ For this reason, you must not do this until after you are finished using the Range.\n\ttemplate<typename... Args>\n\tauto With()\n\t{\n\t\tstatic_assert(sizeof...(Args),\n\t\t\t\"With<>() must receive at least one template argument.\");\n\n\t\tstatic_assert(Meta::all_of_v<std::is_base_of<ComponentBase, Args>::value...>,\n\t\t\t\"All template arguments must be either Components or Tags.\");\n\n\t\tstatic_assert(Meta::all_of_v<std::is_same<Args, typename Args::StaticComponentType>::value...>,\n\t\t\t\"Only a direct inheritor from Component<> can be used in a query.\");\n\n\t\tusing namespace detail;\n\t\tauto&& itr = BuildRootIterator<Args...>();\n\n\t\treturn detail::Range(itr);\n\t}\n\n\t\/\/ Returns all Entities which have an active instance of each specified Component\/Tag.\n\t\/\/ Disabled Components and Components belonging to disabled Entities are not considered.\n\t\/\/ Unlike With<>(), adding or removing Components\/Tags of the queried type will NOT invalidate the returned Range.\n\t\/\/ * This should only be used if necessary, as it is much slower than using With<>() *\n\ttemplate<typename Arg1, typename... Args>\n\tstd::vector<Entity::Ptr> CaptureWith()\n\t{\n\t\tstd::vector<Entity::Ptr> result;\n\t\tif constexpr (sizeof...(Args) == 0)\n\t\t{\n\t\t\tusing namespace detail;\n\t\t\tresult.reserve(entityIndex[Arg1::GetComponentId()].size());\n\t\t}\n\n\t\tfor (Entity& ent : With<Arg1, Args...>())\n\t\t{\n\t\t\tresult.emplace_back(ent.GetPtr());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t\/\/ Returns the raw vector container of the specified Component.\n\t\/\/ This can be useful in special cases when you need custom iterator logic.\n\ttemplate<class Component>\n\tstd::vector<ComponentBase*>& GetComponentIndex()\n\t{\n\t\tusing namespace detail;\n\t\treturn componentIndex[Component::GetComponentId()];\n\t}\n}\n<commit_msg>Simplified the implementation of LogicalIterator<commit_after>\/\/ Copyright (c) 2017 Emilian Cioca\nnamespace Jwl\n{\n\tnamespace detail\n\t{\n\t\t\/\/ Index of all Entities for each component and tag type.\n\t\t\/\/ Sorted to allow for logical operations, such as ANDing, between multiple tables in the index.\n\t\textern std::unordered_map<unsigned, std::vector<Entity*>> entityIndex;\n\n\t\t\/\/ Index of all Components of a particular type.\n\t\t\/\/ Not sorted since no logical operations are performed using these tables.\n\t\textern std::unordered_map<unsigned, std::vector<ComponentBase*>> componentIndex;\n\n\t\t\/\/ A lightweight tag representing the end of a query's range. We use this rather than creating another\n\t\t\/\/ potentially large end-iterator. Our custom iterators already have all the information they need to\n\t\t\/\/ detect if they have expired, so we use this tag to ask them when they has finished enumerating the range.\n\t\tstruct RangeEndSentinel {};\n\n\t\t\/\/ Enumerates a table of the componentIndex while performing a cast and a dereference.\n\t\ttemplate<class Component>\n\t\tclass ComponentIterator : public std::iterator<std::forward_iterator_tag, Component>\n\t\t{\n\t\t\tusing Iterator = std::vector<ComponentBase*>::iterator;\n\t\tpublic:\n\t\t\tComponentIterator(Iterator _itr, Iterator _itrEnd)\n\t\t\t\t: itr(_itr), itrEnd(_itrEnd)\n\t\t\t{}\n\n\t\t\tComponentIterator& operator++()\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\t++itr;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tComponent& operator*() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *static_cast<Component*>(*itr);\n\t\t\t}\n\n\t\t\tbool operator==(RangeEndSentinel) const { return IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !IsTerminated(); }\n\n\t\t\tbool IsTerminated() const { return itr == itrEnd; }\n\n\t\tprivate:\n\t\t\t\/\/ The current position in the target table.\n\t\t\tIterator itr;\n\t\t\t\/\/ Ensures that we don't surpass the table while we are skipping items.\n\t\t\tconst Iterator itrEnd;\n\t\t};\n\n\t\t\/\/ A safe iterator used to enumerate the entityIndex tables.\n\t\t\/\/ Although it models a single iterator, it knows when it has reached the end of the table.\n\t\tclass SafeIterator : public std::iterator<std::forward_iterator_tag, Entity*>\n\t\t{\n\t\t\tusing Iterator = std::vector<Entity*>::iterator;\n\t\tpublic:\n\t\t\tSafeIterator(Iterator _itr, Iterator _itrEnd)\n\t\t\t\t: itr(_itr), itrEnd(_itrEnd)\n\t\t\t{}\n\n\t\t\tSafeIterator& operator++()\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\t++itr;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tEntity& operator*() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *(*itr);\n\t\t\t}\n\n\t\t\tEntity* Get() const\n\t\t\t{\n\t\t\t\tASSERT(!IsTerminated(), \"Invalid range is in use.\");\n\t\t\t\treturn *itr;\n\t\t\t}\n\n\t\t\tbool operator==(RangeEndSentinel) const { return IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !IsTerminated(); }\n\n\t\t\tbool IsTerminated() const { return itr == itrEnd; }\n\t\t\tvoid Terminate() { itr = itrEnd; }\n\n\t\tprivate:\n\t\t\t\/\/ The current position in the table.\n\t\t\tIterator itr;\n\t\t\t\/\/ Ensures that we don't surpass the table while we are skipping items.\n\t\t\tconst Iterator itrEnd;\n\t\t};\n\n\t\t\/\/ Provides functions to advance two SafeIterators as a logical AND of two entityIndex tables.\n\t\t\/\/ This provider pattern will allow us to add more operations in the future.\n\t\tstruct Intersection\n\t\t{\n\t\t\tstatic void FindFirst(SafeIterator& itr1, SafeIterator& itr2)\n\t\t\t{\n\t\t\t\twhile (!(itr1.IsTerminated() || itr2.IsTerminated()))\n\t\t\t\t{\n\t\t\t\t\tEntity* p1 = itr1.Get();\n\t\t\t\t\tEntity* p2 = itr2.Get();\n\n\t\t\t\t\tif (p1 < p2)\n\t\t\t\t\t{\n\t\t\t\t\t\t++itr1;\n\t\t\t\t\t}\n\t\t\t\t\telse if (p1 > p2)\n\t\t\t\t\t{\n\t\t\t\t\t\t++itr2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Itr1 is the one that is checked for death, so propagate the termination if Itr2 finished first.\n\t\t\t\tif (itr2.IsTerminated())\n\t\t\t\t{\n\t\t\t\t\titr1.Terminate();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatic void FindNext(SafeIterator& itr1, SafeIterator& itr2)\n\t\t\t{\n\t\t\t\tFindFirst(++itr1, itr2);\n\t\t\t}\n\t\t};\n\n\t\t\/\/ Enumerates a SafeIterator and a templated iterator while performing a logical operation between them.\n\t\t\/\/ The templated iterator can expand into a subtree of more LogicalIterators, or be a SafeIterator itself.\n\t\ttemplate<class Iterator, class Operation>\n\t\tclass LogicalIterator : public std::iterator<std::forward_iterator_tag, Entity*>\n\t\t{\n\t\t\tstatic constexpr bool isLeaf = std::is_same_v<Iterator, SafeIterator>;\n\t\tpublic:\n\t\t\tLogicalIterator(SafeIterator _itr1, Iterator _itr2)\n\t\t\t\t: itr1(_itr1), itr2(_itr2)\n\t\t\t{\n\t\t\t\tif constexpr (isLeaf)\n\t\t\t\t{\n\t\t\t\t\tOperation::FindFirst(itr1, itr2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tOperation::FindFirst(itr1, itr2.GetCurrentItr());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLogicalIterator& operator++()\n\t\t\t{\n\t\t\t\tif constexpr (isLeaf)\n\t\t\t\t{\n\t\t\t\t\tOperation::FindNext(itr1, itr2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ Intersect the result of the right-hand subtree with our left-hand SafeIterator.\n\t\t\t\t\t++itr2;\n\t\t\t\t\tOperation::FindNext(itr1, itr2.GetCurrentItr());\n\t\t\t\t}\n\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSafeIterator& GetCurrentItr() { return itr1; }\n\t\t\tEntity& operator*() const { return *itr1; }\n\n\t\t\tbool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }\n\t\t\tbool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }\n\n\t\tprivate:\n\t\t\tSafeIterator itr1;\n\t\t\tIterator itr2;\n\t\t};\n\n\t\t\/\/ Represents a lazy-evaluated range that can be used in a range-based for loop.\n\t\ttemplate<class RootIterator>\n\t\tclass Range\n\t\t{\n\t\tpublic:\n\t\t\tRange(RootIterator _itr)\n\t\t\t\t: itr(_itr)\n\t\t\t{}\n\n\t\t\tRootIterator& begin()\n\t\t\t{\n\t\t\t\treturn itr;\n\t\t\t}\n\n\t\t\tRangeEndSentinel end() const\n\t\t\t{\n\t\t\t\treturn {};\n\t\t\t}\n\n\t\tprivate:\n\t\t\t\/\/ The starting position of the range.\n\t\t\tRootIterator itr;\n\t\t};\n\n\t\t\/\/ Template deduction assisted construction.\n\t\ttemplate<class Iterator>\n\t\tauto BuildLogicalIterator(SafeIterator&& set1, Iterator&& set2)\n\t\t{\n\t\t\treturn LogicalIterator<Iterator, Intersection>(set1, set2);\n\t\t}\n\n\t\t\/\/ Constructs a logical iterator representing the start of the sequence.\n\t\ttemplate<typename Arg1, typename Arg2, typename... Args>\n\t\tauto BuildRootIterator()\n\t\t{\n\t\t\tauto& index = entityIndex[Arg1::GetComponentId()];\n\t\t\tauto begin = index.begin();\n\t\t\tauto end = index.end();\n\n\t\t\treturn BuildLogicalIterator(SafeIterator(begin, end), BuildRootIterator<Arg2, Args...>());\n\t\t}\n\n\t\t\/\/ BuildRootIterator() base case.\n\t\ttemplate<typename Arg>\n\t\tSafeIterator BuildRootIterator()\n\t\t{\n\t\t\tauto& index = entityIndex[Arg::GetComponentId()];\n\t\t\tauto begin = index.begin();\n\t\t\tauto end = index.end();\n\n\t\t\treturn SafeIterator(begin, end);\n\t\t}\n\t}\n\n\t\/\/ Returns an enumerable range of all enabled Components of the specified type.\n\t\/\/ By providing you the Component directly you don't have to waste time calling Entity.Get<>().\n\t\/\/ This is a faster option than With<>() but it only allows you to specify a single Component type.\n\ttemplate<class Component>\n\tauto All()\n\t{\n\t\tstatic_assert(std::is_base_of_v<ComponentBase, Component>,\n\t\t\t\"Template argument must be a Component.\");\n\n\t\tstatic_assert(!std::is_base_of_v<TagBase, Component>,\n\t\t\t\"Cannot query tags with All<>(). Use With<>() instead.\");\n\n\t\tstatic_assert(std::is_same_v<Component, typename Component::StaticComponentType>,\n\t\t\t\"Only a direct inheritor from Component<> can be used in a query.\");\n\n\t\tusing namespace detail;\n\t\tauto& index = componentIndex[Component::GetComponentId()];\n\t\tauto itr = ComponentIterator<Component>(index.begin(), index.end());\n\n\t\treturn detail::Range(itr);\n\t}\n\n\t\/\/ Returns an enumerable range of all Entities which have an active instance of each specified Component\/Tag.\n\t\/\/ Disabled Components and Components belonging to disabled Entities are not considered.\n\t\/\/ * Adding\/Removing Components or Tags of the queried types will invalidate the returned Range *\n\t\/\/ For this reason, you must not do this until after you are finished using the Range.\n\ttemplate<typename... Args>\n\tauto With()\n\t{\n\t\tstatic_assert(sizeof...(Args),\n\t\t\t\"With<>() must receive at least one template argument.\");\n\n\t\tstatic_assert(Meta::all_of_v<std::is_base_of<ComponentBase, Args>::value...>,\n\t\t\t\"All template arguments must be either Components or Tags.\");\n\n\t\tstatic_assert(Meta::all_of_v<std::is_same<Args, typename Args::StaticComponentType>::value...>,\n\t\t\t\"Only a direct inheritor from Component<> can be used in a query.\");\n\n\t\tusing namespace detail;\n\t\tauto&& itr = BuildRootIterator<Args...>();\n\n\t\treturn detail::Range(itr);\n\t}\n\n\t\/\/ Returns all Entities which have an active instance of each specified Component\/Tag.\n\t\/\/ Disabled Components and Components belonging to disabled Entities are not considered.\n\t\/\/ Unlike With<>(), adding or removing Components\/Tags of the queried type will NOT invalidate the returned Range.\n\t\/\/ * This should only be used if necessary, as it is much slower than using With<>() *\n\ttemplate<typename Arg1, typename... Args>\n\tstd::vector<Entity::Ptr> CaptureWith()\n\t{\n\t\tstd::vector<Entity::Ptr> result;\n\t\tif constexpr (sizeof...(Args) == 0)\n\t\t{\n\t\t\tusing namespace detail;\n\t\t\tresult.reserve(entityIndex[Arg1::GetComponentId()].size());\n\t\t}\n\n\t\tfor (Entity& ent : With<Arg1, Args...>())\n\t\t{\n\t\t\tresult.emplace_back(ent.GetPtr());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t\/\/ Returns the raw vector container of the specified Component.\n\t\/\/ This can be useful in special cases when you need custom iterator logic.\n\ttemplate<class Component>\n\tstd::vector<ComponentBase*>& GetComponentIndex()\n\t{\n\t\tusing namespace detail;\n\t\treturn componentIndex[Component::GetComponentId()];\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>## Main type definition\n\n# Based on\n# https:\/\/github.com\/NaaS\/system\/blob\/master\/naasferatu\/front-end\/hadoop*.naas\n# More recent version of target code available at\n# https:\/\/lsds.doc.ic.ac.uk\/gitlab\/naas\/naas-box-system\/tree\/master\/src\/applications\/hadoop_data_model\n\ntype hadoop_wc : record\n key_len : integer\n { signed = true,\n # FIXME not sure if the target allows us to specify endianness at present.\n #endianness = big,\n # \"size\" in bytes\n byte_size = 2 }\n key : string\n { byte_size = \"hadoop_wc.key_len\" }\n value : integer\n { signed = false,\n #endianness = big,\n byte_size = 8 }\n<commit_msg>not using FQNs to simplify name handling in the compiler for such references;<commit_after>## Main type definition\n\n# Based on\n# https:\/\/github.com\/NaaS\/system\/blob\/master\/naasferatu\/front-end\/hadoop*.naas\n# More recent version of target code available at\n# https:\/\/lsds.doc.ic.ac.uk\/gitlab\/naas\/naas-box-system\/tree\/master\/src\/applications\/hadoop_data_model\n\ntype hadoop_wc : record\n key_len : integer\n { signed = true,\n # FIXME not sure if the target allows us to specify endianness at present.\n #endianness = big,\n # \"size\" in bytes\n byte_size = 2 }\n key : string\n { byte_size = key_len }\n value : integer\n { signed = false,\n #endianness = big,\n byte_size = 8 }\n<|endoftext|>"} {"text":"<commit_before>#include \"segments.hpp\"\n#include \"..\/utils\/utils.hpp\"\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n\nusing namespace geom2d;\n\nstatic unsigned int Nsegs = 10;\nstatic unsigned int Width = 100;\nstatic unsigned int Height = 100;\nstatic unsigned int Nangles = 32;\nstatic unsigned long Nsteps = 1000000;\nstatic double MaxR = 15;\nstatic double MinR = 1;\n\nvoid parseargs(int, const char*[]);\nvoid helpmsg(int);\nvoid mkinst(FILE*);\n\nint main(int argc, const char *argv[]) {\n\tparseargs(argc, argv);\n\tmkinst(stdout);\n\treturn 0;\n}\n\nvoid parseargs(int argc, const char *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (i < argc-1 && strcmp(argv[i], \"nsegs\") == 0) {\n\t\t\tNsegs = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"width\") == 0) {\n\t\t\tWidth = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"height\") == 0) {\n\t\t\tHeight = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"nangles\") == 0) {\n\t\t\tNangles = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"nsteps\") == 0) {\n\t\t\tNsteps = strtoul(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"maxr\") == 0) {\n\t\t\tMaxR = strtod(argv[++i], NULL);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"minr\") == 0) {\n\t\t\tMinR = strtod(argv[++i], NULL);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"h\") == 0) {\n\t\t\thelpmsg(0);\n\n\t\t} else {\n\t\t\thelpmsg(1);\n\t\t}\n\t}\n}\n\nvoid helpmsg(int status) {\n\tputs(\"Usage: mkinst [options]\");\n\tprintf(\"-nsegs\tthe number of segments (default: %u)\\n\", Nsegs);\n\tprintf(\"-width\twidth of the grid (default: %u)\\n\", Width);\n\tprintf(\"-height\theight of the grid (default: %u)\\n\", Height);\n\tprintf(\"-nangles\tthe number of angles (must be even, default: %u)\\n\", Nangles);\n\tprintf(\"-nsteps\tnumber of steps in the random walk (default: %lu)\\n\", Nsteps);\n\tprintf(\"-maxr\tthe max segment radius (default: %g)\\n\", MaxR);\n\tprintf(\"-minr\tthe min segment radius (default: %g)\\n\", MinR);\n\texit(status);\n}\n\nvoid mkinst(FILE *out) {\n\tSegments dom(Width, Height, Nangles, std::vector<Segments::Seg>());\n\n\tstd::vector<LineSg> lines;\n\tfor (unsigned int i = 0; i < Nsegs; i++) {\n\tredo:\n\t\tSegments::Seg seg;\n\t\tseg.radius = randgen.real()*(MaxR-MinR) + MinR;\n\t\tseg.start.rot = randgen.integer(0, Nangles-1);\n\t\tseg.start.x = randgen.integer(1, Width - 2);\n\t\tseg.start.y = randgen.integer(1, Height - 2);\n\n\t\tLineSg line = dom.line(seg, seg.start);\n\t\tfor (auto l = lines.begin(); l != lines.end(); l++) {\n\t\t\tif (l->hits(line))\n\t\t\t\tgoto redo;\n\t\t}\n\n\t\tlines.push_back(line);\n\t\tdom.segs.push_back(seg);\n\t}\n\n\tSegments::State st = dom.initialstate();\n\tfor (unsigned int i = 0; i < Nsteps; i++) {\n\t\tSegments::Operators ops(dom, st);\n\t\tif (ops.size() == 0)\n\t\t\tbreak;\n\t\tunsigned int n = randgen.integer(0, ops.size()-1);\n\t\tSegments::Edge e(dom, st, ops[n]);\n\t\tst = e.state;\n\t}\n\n\tfprintf(out, \"%u %u %u\\n\", Width, Height, Nangles);\n\tfprintf(out, \"%u\\n\", Nsegs);\n\tfor (unsigned int i = 0; i < dom.segs.size(); i++) {\n\t\tconst Segments::Pose &goal = st.poses[i];\n\t\tconst Segments::Seg &sg = dom.segs[i];\n\t\tfprintf(out, \"%g \", sg.radius);\n\t\tfprintf(out, \"%u %u %u \", sg.start.x, sg.start.y, sg.start.rot);\n\t\tfprintf(out, \"%u %u %u\\n\", goal.x, goal.y, goal.rot);\n\t}\n\n}\n<commit_msg>segments: options have a leading -.<commit_after>#include \"segments.hpp\"\n#include \"..\/utils\/utils.hpp\"\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n\nusing namespace geom2d;\n\nstatic unsigned int Nsegs = 10;\nstatic unsigned int Width = 100;\nstatic unsigned int Height = 100;\nstatic unsigned int Nangles = 32;\nstatic unsigned long Nsteps = 1000000;\nstatic double MaxR = 15;\nstatic double MinR = 1;\n\nvoid parseargs(int, const char*[]);\nvoid helpmsg(int);\nvoid mkinst(FILE*);\n\nint main(int argc, const char *argv[]) {\n\tparseargs(argc, argv);\n\tmkinst(stdout);\n\treturn 0;\n}\n\nvoid parseargs(int argc, const char *argv[]) {\n\tfor (int i = 1; i < argc; i++) {\n\t\tif (i < argc-1 && strcmp(argv[i], \"-nsegs\") == 0) {\n\t\t\tNsegs = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-width\") == 0) {\n\t\t\tWidth = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-height\") == 0) {\n\t\t\tHeight = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-nangles\") == 0) {\n\t\t\tNangles = strtol(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-nsteps\") == 0) {\n\t\t\tNsteps = strtoul(argv[++i], NULL, 10);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-maxr\") == 0) {\n\t\t\tMaxR = strtod(argv[++i], NULL);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-minr\") == 0) {\n\t\t\tMinR = strtod(argv[++i], NULL);\n\n\t\t} else if (i < argc-1 && strcmp(argv[i], \"-h\") == 0) {\n\t\t\thelpmsg(0);\n\n\t\t} else {\n\t\t\thelpmsg(1);\n\t\t}\n\t}\n}\n\nvoid helpmsg(int status) {\n\tputs(\"Usage: mkinst [options]\");\n\tprintf(\"-nsegs\tthe number of segments (default: %u)\\n\", Nsegs);\n\tprintf(\"-width\twidth of the grid (default: %u)\\n\", Width);\n\tprintf(\"-height\theight of the grid (default: %u)\\n\", Height);\n\tprintf(\"-nangles\tthe number of angles (must be even, default: %u)\\n\", Nangles);\n\tprintf(\"-nsteps\tnumber of steps in the random walk (default: %lu)\\n\", Nsteps);\n\tprintf(\"-maxr\tthe max segment radius (default: %g)\\n\", MaxR);\n\tprintf(\"-minr\tthe min segment radius (default: %g)\\n\", MinR);\n\texit(status);\n}\n\nvoid mkinst(FILE *out) {\n\tSegments dom(Width, Height, Nangles, std::vector<Segments::Seg>());\n\n\tstd::vector<LineSg> lines;\n\tfor (unsigned int i = 0; i < Nsegs; i++) {\n\tredo:\n\t\tSegments::Seg seg;\n\t\tseg.radius = randgen.real()*(MaxR-MinR) + MinR;\n\t\tseg.start.rot = randgen.integer(0, Nangles-1);\n\t\tseg.start.x = randgen.integer(1, Width - 2);\n\t\tseg.start.y = randgen.integer(1, Height - 2);\n\n\t\tLineSg line = dom.line(seg, seg.start);\n\t\tfor (auto l = lines.begin(); l != lines.end(); l++) {\n\t\t\tif (l->hits(line))\n\t\t\t\tgoto redo;\n\t\t}\n\n\t\tlines.push_back(line);\n\t\tdom.segs.push_back(seg);\n\t}\n\n\tSegments::State st = dom.initialstate();\n\tfor (unsigned int i = 0; i < Nsteps; i++) {\n\t\tSegments::Operators ops(dom, st);\n\t\tif (ops.size() == 0)\n\t\t\tbreak;\n\t\tunsigned int n = randgen.integer(0, ops.size()-1);\n\t\tSegments::Edge e(dom, st, ops[n]);\n\t\tst = e.state;\n\t}\n\n\tfprintf(out, \"%u %u %u\\n\", Width, Height, Nangles);\n\tfprintf(out, \"%u\\n\", Nsegs);\n\tfor (unsigned int i = 0; i < dom.segs.size(); i++) {\n\t\tconst Segments::Pose &goal = st.poses[i];\n\t\tconst Segments::Seg &sg = dom.segs[i];\n\t\tfprintf(out, \"%g \", sg.radius);\n\t\tfprintf(out, \"%u %u %u \", sg.start.x, sg.start.y, sg.start.rot);\n\t\tfprintf(out, \"%u %u %u\\n\", goal.x, goal.y, goal.rot);\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"VulkanFragmentShader.h\"\n\n#include <stdio.h>\n\nvoid VulkanFragmentShader::LoadShader(const int8* ShaderFileName)\n{\n\tArray<int8> Glsl;\n\tFILE* file = fopen(ShaderFileName, \"r\");\n\n\tArray<uint32> Spirv = CompileGLSL(ShaderFileName, ShaderType::FragmentShader, Glsl);\n}\n<commit_msg>Closed file in FragmentShader.cpp<commit_after>#include \"VulkanFragmentShader.h\"\n\n#include <stdio.h>\n\nvoid VulkanFragmentShader::LoadShader(const int8* ShaderFileName)\n{\n\tArray<int8> Glsl;\n\tFILE* file = fopen(ShaderFileName, \"r\");\n\n\tArray<uint32> Spirv = CompileGLSL(ShaderFileName, ShaderType::FragmentShader, Glsl);\n\tfclose(file);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <osgWidget\/VncClient>\n\n#include <osgDB\/Registry>\n#include <osgViewer\/Viewer>\n#include <osgViewer\/ViewerEventHandlers>\n\nclass EscapeHandler : public osgGA::GUIEventHandler\n{\n public:\n\n EscapeHandler() {}\n\n bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)\n {\n if (ea.getHandled()) return false;\n\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYUP):\n {\n if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Escape)\n {\n osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);\n if (view) view->getViewerBase()->setDone(true);\n\n return true;\n }\n }\n\n default:\n return false;\n }\n return false;\n }\n};\n\nint main(int argc,char** argv)\n{\n osg::ArgumentParser arguments(&argc, argv);\n arguments.getApplicationUsage()->addCommandLineOption(\"--login <url> <username> <password>\", \"Provide authentication information for http file access.\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--password <password>\", \"Provide password for any vnc url on command line not mentioned in --login.\");\n osgViewer::Viewer viewer(arguments);\n\n osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),\n osg::Vec3(1.0f,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,1.0f),\n osg::Vec4(1.0f,1.0f,1.0f,1.0f),\n osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);\n\n osg::ref_ptr<osg::Group> group = new osg::Group;\n\n std::string password;\n while(arguments.read(\"--password\",password))\n {\n }\n\n std::string url, username, password;\n while (arguments.read(\"--login\", url, username, password))\n {\n osgDB::Registry::instance()->getOrCreateAuthenticationMap()->addAuthenticationDetails(\n url,\n new osgDB::AuthenticationDetails(username, password)\n );\n }\n\n for(int i=1; i<arguments.argc(); ++i)\n {\n if (!arguments.isOption(i))\n {\n std::string hostname = arguments[i];\n\n if (!password.empty())\n {\n const osgDB::AuthenticationMap* authenticationMap = osgDB::Registry::instance()->getOrCreateAuthenticationMap();\n const osgDB::AuthenticationDetails* details = authenticationMap->getAuthenticationDetails(hostname);\n if (details == NULL)\n {\n authenticationMap->addAuthenticationDetails(hostname, new osgDB::AuthenticationDetails(\"\", password));\n }\n }\n\n osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient;\n if (vncClient->connect(arguments[i], hints))\n {\n group->addChild(vncClient.get());\n\n hints.position.x() += 1.1f;\n }\n }\n }\n\n viewer.setSceneData(group.get());\n\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n \/\/ add a custom escape handler, but disable the standard viewer one to enable the vnc images to handle\n \/\/ the escape without it getting caught by the viewer.\n viewer.addEventHandler(new EscapeHandler); \n viewer.setKeyEventSetsDone(0);\n\n return viewer.run();\n}\n\n<commit_msg>Build fix<commit_after>#include <osgWidget\/VncClient>\n\n#include <osgDB\/Registry>\n#include <osgViewer\/Viewer>\n#include <osgViewer\/ViewerEventHandlers>\n\nclass EscapeHandler : public osgGA::GUIEventHandler\n{\n public:\n\n EscapeHandler() {}\n\n bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)\n {\n if (ea.getHandled()) return false;\n\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYUP):\n {\n if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Escape)\n {\n osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);\n if (view) view->getViewerBase()->setDone(true);\n\n return true;\n }\n }\n\n default:\n return false;\n }\n return false;\n }\n};\n\nint main(int argc,char** argv)\n{\n osg::ArgumentParser arguments(&argc, argv);\n arguments.getApplicationUsage()->addCommandLineOption(\"--login <url> <username> <password>\", \"Provide authentication information for http file access.\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--password <password>\", \"Provide password for any vnc url on command line not mentioned in --login.\");\n osgViewer::Viewer viewer(arguments);\n\n osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),\n osg::Vec3(1.0f,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,1.0f),\n osg::Vec4(1.0f,1.0f,1.0f,1.0f),\n osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);\n\n osg::ref_ptr<osg::Group> group = new osg::Group;\n\n std::string password;\n while(arguments.read(\"--password\",password))\n {\n }\n\n std::string url, username;\n while (arguments.read(\"--login\", url, username, password))\n {\n osgDB::Registry::instance()->getOrCreateAuthenticationMap()->addAuthenticationDetails(\n url,\n new osgDB::AuthenticationDetails(username, password)\n );\n }\n\n for(int i=1; i<arguments.argc(); ++i)\n {\n if (!arguments.isOption(i))\n {\n std::string hostname = arguments[i];\n\n if (!password.empty())\n {\n osgDB::AuthenticationMap* authenticationMap = osgDB::Registry::instance()->getOrCreateAuthenticationMap();\n const osgDB::AuthenticationDetails* details = authenticationMap->getAuthenticationDetails(hostname);\n if (details == NULL)\n {\n authenticationMap->addAuthenticationDetails(hostname, new osgDB::AuthenticationDetails(\"\", password));\n }\n }\n\n osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient;\n if (vncClient->connect(arguments[i], hints))\n {\n group->addChild(vncClient.get());\n\n hints.position.x() += 1.1f;\n }\n }\n }\n\n viewer.setSceneData(group.get());\n\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n \/\/ add a custom escape handler, but disable the standard viewer one to enable the vnc images to handle\n \/\/ the escape without it getting caught by the viewer.\n viewer.addEventHandler(new EscapeHandler); \n viewer.setKeyEventSetsDone(0);\n\n return viewer.run();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: frmload.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: mba $ $Date: 2002-07-18 15:02:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_FRMLOAD_HXX\n#define _SFX_FRMLOAD_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XLoadEventListener.hpp>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XSYNCHRONOUSFRAMELOADER_HPP_\n#include <com\/sun\/star\/frame\/XSynchronousFrameLoader.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_\n#include <com\/sun\/star\/document\/XExtendedFilterDetection.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <cppuhelper\/factory.hxx>\n#include <tools\/link.hxx>\n#include <tools\/string.hxx>\n\nclass SfxObjectFactory;\nclass SfxFilterMatcher;\nclass LoadEnvironment_Impl;\nclass SfxMedium;\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace uno\n {\n class Any;\n }\n namespace lang\n {\n class XMultiServiceFactory;\n }\n namespace frame\n {\n class XFrame;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\n#include \"sfxuno.hxx\"\n\n#define REFERENCE ::com::sun::star::uno::Reference\n#define SEQUENCE ::com::sun::star::uno::Sequence\n#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException\n\nclass SfxFrameLoader_Impl : public ::cppu::WeakImplHelper3< ::com::sun::star::frame::XSynchronousFrameLoader, ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo >\n{\n REFERENCE < ::com::sun::star::frame::XFrame > xFrame;\n REFERENCE < ::com::sun::star::frame::XLoadEventListener > xListener;\n LoadEnvironment_Impl* pLoader;\n SfxFilterMatcher* pMatcher;\n String aFilterName;\n SfxMedium* pMedium;\n sal_Bool bLoadDone;\n sal_Bool bLoadState;\n\n DECL_LINK( LoadDone_Impl, void* );\n\npublic:\n SfxFrameLoader_Impl( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );\n virtual ~SfxFrameLoader_Impl();\n\n SFX_DECL_XSERVICEINFO\n\n \/\/----------------------------------------------------------------------------------\n \/\/ XSynchronousFrameLoader\n \/\/----------------------------------------------------------------------------------\n virtual sal_Bool SAL_CALL load( const SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor, const REFERENCE< ::com::sun::star::frame::XFrame >& xFrame ) throw( RUNTIME_EXCEPTION );\n virtual void SAL_CALL cancel() throw( RUNTIME_EXCEPTION );\n\n \/\/----------------------------------------------------------------------------------\n \/\/ XExtendedFilterDetect\n \/\/----------------------------------------------------------------------------------\n virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION );\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS fwkq1 (1.8.214); FILE MERGED 2003\/07\/14 17:59:16 mba 1.8.214.1: #110843#: get rid of factories<commit_after>\/*************************************************************************\n *\n * $RCSfile: frmload.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 07:53:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_FRMLOAD_HXX\n#define _SFX_FRMLOAD_HXX\n\n#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XLoadEventListener.hpp>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XSYNCHRONOUSFRAMELOADER_HPP_\n#include <com\/sun\/star\/frame\/XSynchronousFrameLoader.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_\n#include <com\/sun\/star\/document\/XExtendedFilterDetection.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <cppuhelper\/factory.hxx>\n#include <tools\/link.hxx>\n#include <tools\/string.hxx>\n\nclass SfxObjectFactory;\nclass SfxFilterMatcher;\nclass LoadEnvironment_Impl;\nclass SfxMedium;\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace uno\n {\n class Any;\n }\n namespace lang\n {\n class XMultiServiceFactory;\n }\n namespace frame\n {\n class XFrame;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\n#include \"sfxuno.hxx\"\n\n#define REFERENCE ::com::sun::star::uno::Reference\n#define SEQUENCE ::com::sun::star::uno::Sequence\n#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException\n\nclass SfxFrameLoader_Impl : public ::cppu::WeakImplHelper2< ::com::sun::star::frame::XSynchronousFrameLoader, ::com::sun::star::lang::XServiceInfo >\n{\n REFERENCE < ::com::sun::star::frame::XFrame > xFrame;\n REFERENCE < ::com::sun::star::frame::XLoadEventListener > xListener;\n LoadEnvironment_Impl* pLoader;\n SfxFilterMatcher* pMatcher;\n String aFilterName;\n SfxMedium* pMedium;\n sal_Bool bLoadDone;\n sal_Bool bLoadState;\n\n DECL_LINK( LoadDone_Impl, void* );\n\npublic:\n SfxFrameLoader_Impl( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );\n virtual ~SfxFrameLoader_Impl();\n\n SFX_DECL_XSERVICEINFO\n\n \/\/----------------------------------------------------------------------------------\n \/\/ XSynchronousFrameLoader\n \/\/----------------------------------------------------------------------------------\n virtual sal_Bool SAL_CALL load( const SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor, const REFERENCE< ::com::sun::star::frame::XFrame >& xFrame ) throw( RUNTIME_EXCEPTION );\n virtual void SAL_CALL cancel() throw( RUNTIME_EXCEPTION );\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sorgitm.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 17:18:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SFX_SORGITM_HXX\n#define _SFX_SORGITM_HXX\n\n#ifndef _SFXSTRITEM_HXX \/\/autogen wg. SfxStringItem\n#include <svtools\/stritem.hxx>\n#endif\n\n\/\/ class SfxScriptOrganizerItem ---------------------------------------------\n\nclass SfxScriptOrganizerItem : public SfxStringItem\n{\nprivate:\n String aLanguage;\n\npublic:\n TYPEINFO();\n SfxScriptOrganizerItem();\n SfxScriptOrganizerItem( const String &rLanguage );\n SfxScriptOrganizerItem( const SfxScriptOrganizerItem& );\n virtual ~SfxScriptOrganizerItem();\n\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;\n virtual int operator==( const SfxPoolItem& ) const;\n virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n String getLanguage() { return aLanguage; };\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.730); FILE MERGED 2008\/04\/01 15:38:17 thb 1.3.730.2: #i85898# Stripping all external header guards 2008\/03\/31 13:37:54 rt 1.3.730.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sorgitm.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SFX_SORGITM_HXX\n#define _SFX_SORGITM_HXX\n\n#include <svtools\/stritem.hxx>\n\n\/\/ class SfxScriptOrganizerItem ---------------------------------------------\n\nclass SfxScriptOrganizerItem : public SfxStringItem\n{\nprivate:\n String aLanguage;\n\npublic:\n TYPEINFO();\n SfxScriptOrganizerItem();\n SfxScriptOrganizerItem( const String &rLanguage );\n SfxScriptOrganizerItem( const SfxScriptOrganizerItem& );\n virtual ~SfxScriptOrganizerItem();\n\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;\n virtual int operator==( const SfxPoolItem& ) const;\n virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n String getLanguage() { return aLanguage; };\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#include <iostream>\n\n#include <pegtl.hh>\n#include <pegtl\/analyze.hh>\n#include <pegtl\/read_parser.hh>\n\nnamespace sexpr\n{\n using namespace pegtl;\n\n struct hash_comment\n : until< eolf > {};\n\n struct list;\n\n struct list_comment\n : if_must< at_one< '(' >, disable< list > > {};\n\n struct read_include\n : seq< one< ' ' >, one< '\"' >, plus< not_one< '\"' > >, one< '\"' > > {};\n\n struct hash_include\n : if_must< string< 'i', 'n', 'c', 'l', 'u', 'd', 'e' >, read_include > {};\n\n struct hashed\n : if_must< one< '#' >, sor< hash_include, list_comment, hash_comment > > {};\n\n struct number\n : plus< digit > {};\n\n struct symbol\n : identifier {};\n\n struct atom\n : sor< number, symbol > {};\n\n struct anything;\n\n struct list\n : if_must< one< '(' >, until< one< ')' >, anything > > {};\n\n struct normal\n : sor< atom, list > {};\n\n struct anything\n : sor< space, hashed, normal > {};\n\n struct main\n : until< eof, anything > {};\n\n template< typename Rule > struct action\n : public nothing< Rule > {};\n\n template<>\n struct action< plus< not_one< '\"' > > >\n {\n template< typename Input >\n static void apply( const Input & in, std::string & fn )\n {\n fn = in.string();\n }\n };\n\n template<>\n struct action< hash_include >\n {\n template< typename Input >\n static void apply( const Input & in, std::string & fn )\n {\n std::string f2;\n read_parser( fn, in ).parse< main, action >( f2 );\n }\n };\n\n} \/\/ sexpr\n\nint main( int argc, char ** argv )\n{\n pegtl::analyze< sexpr::main >();\n\n for ( int i = 1; i < argc; ++i ) {\n std::string fn;\n pegtl::parse< sexpr::main, sexpr::action >( i, argv, fn );\n }\n return 0;\n}\n<commit_msg>Fixed illegal code found by Clang 3.5<commit_after>\/\/ Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/ColinH\/PEGTL\/\n\n#include <iostream>\n\n#include <pegtl.hh>\n#include <pegtl\/analyze.hh>\n#include <pegtl\/read_parser.hh>\n\nnamespace sexpr\n{\n using namespace pegtl;\n\n struct hash_comment\n : until< eolf > {};\n\n struct list;\n\n struct list_comment\n : if_must< at_one< '(' >, disable< list > > {};\n\n struct read_include\n : seq< one< ' ' >, one< '\"' >, plus< not_one< '\"' > >, one< '\"' > > {};\n\n struct hash_include\n : if_must< string< 'i', 'n', 'c', 'l', 'u', 'd', 'e' >, read_include > {};\n\n struct hashed\n : if_must< one< '#' >, sor< hash_include, list_comment, hash_comment > > {};\n\n struct number\n : plus< digit > {};\n\n struct symbol\n : identifier {};\n\n struct atom\n : sor< number, symbol > {};\n\n struct anything;\n\n struct list\n : if_must< one< '(' >, until< one< ')' >, anything > > {};\n\n struct normal\n : sor< atom, list > {};\n\n struct anything\n : sor< space, hashed, normal > {};\n\n struct main\n : until< eof, anything > {};\n\n template< typename Rule > struct action\n : public nothing< Rule > {};\n\n template<>\n struct action< plus< not_one< '\"' > > >\n {\n template< typename Input >\n static void apply( const Input & in, std::string & fn )\n {\n fn = in.string();\n }\n };\n\n template<>\n struct action< hash_include >\n {\n template< typename Input >\n static void apply( const Input & in, std::string & fn )\n {\n std::string f2;\n read_parser( fn, in ).parse< main, sexpr::action >( f2 );\n }\n };\n\n} \/\/ sexpr\n\nint main( int argc, char ** argv )\n{\n pegtl::analyze< sexpr::main >();\n\n for ( int i = 1; i < argc; ++i ) {\n std::string fn;\n pegtl::parse< sexpr::main, sexpr::action >( i, argv, fn );\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.hpp\"\n\n#include <functional>\n\n#include \"CppUnitTest.h\"\n#include \"..\\TestUtilities\\TestUtilities.hpp\"\n#include \"..\\TestUtilities\\QuantityComparisons.hpp\"\n#include \"..\\TestUtilities\\GeometryComparisons.hpp\"\n#include \"..\\TestUtilities\\Algebra.hpp\"\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"..\\Quantities\\SI.hpp\"\n#include \"..\\Quantities\\Constants.hpp\"\n#include \"..\\Quantities\\UK.hpp\"\n#include \"..\\Quantities\\BIPM.hpp\"\n#include \"..\\Quantities\\Astronomy.hpp\"\n#include \"..\\Geometry\\R3Element.hpp\"\n#include \"..\\Geometry\\Grassmann.hpp\"\n#include \"..\\Quantities\\ElementaryFunctions.hpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace Principia {\nnamespace GeometryTests\n{\nusing namespace Geometry;\nusing namespace Quantities;\nusing namespace SI;\nusing namespace UK;\nusing namespace BIPM;\nusing namespace Astronomy;\nusing namespace Constants;\nusing namespace TestUtilities;\n\nTEST_CLASS(GeometryTests)\n{\n public:\n struct World;\n TEST_METHOD(Dumb3Vector) {\n R3Element<Speed> nullVector(0 * Metre \/ Second,\n 0 * Metre \/ Second,\n 0 * Metre \/ Second);\n R3Element<Speed> u(1 * Metre \/ Second,\n 120 * Kilo(Metre) \/ Hour,\n -SpeedOfLight);\n R3Element<Speed> v(-20 * Knot,\n 2 * π * AstronomicalUnit \/ JulianYear,\n 1 * Admiralty::NauticalMile \/ Hour);\n R3Element<Speed> w(-1 * Mile \/ Hour, -2 * Foot \/ Second, -3 * Knot);\n R3Element<Speed> a(88 * Mile \/ Hour, 300 * Metre \/ Second, 46 * Knot);\n AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));\n TestVectorSpace<R3Element<Speed>,\n Dimensionless>(nullVector, u, v, w, Dimensionless(0),\n Dimensionless(1), e, Dimensionless(42));\n TestAlternatingBilinearMap(Cross<Speed, Speed>, u,\n v, w, a, Dimensionless(42));\n TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,\n u, v, w, a, Dimensionless(42));\n }\n\n TEST_METHOD(SpecialOrthogonalLieAlgebra) {\n R3Element<Dimensionless> u(3, -42, 0);\n R3Element<Dimensionless> v(-π, -e, -1);\n R3Element<Dimensionless> w(2, 2, 2);\n R3Element<Dimensionless> a(1.2, 2.3, 3.4);\n TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,\n Bivector<Dimensionless, World>(u),\n Bivector<Dimensionless, World>(v),\n Bivector<Dimensionless, World>(w),\n Bivector<Dimensionless, World>(a), Dimensionless(0.42));\n }\n\n TEST_METHOD(VectorSpaces) {\n R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);\n R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);\n R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);\n R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);\n R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);\n {\n std::function<Area(Vector<Length, World>,\n Vector<Length, World>)> vectorInnerProduct =\n [](Vector<Length, World> a, Vector<Length, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Area(Bivector<Length, World>,\n Bivector<Length, World>)> bivectorInnerProduct =\n [](Bivector<Length, World> a, Bivector<Length, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Area(Trivector<Length, World>,\n Trivector<Length, World>)> trivectorInnerProduct =\n [](Trivector<Length, World> a, Trivector<Length, World> b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector<Length, World>(nullDisplacement),\n Vector<Length, World>(u), Vector<Length, World>(v),\n Vector<Length, World>(w), Vector<Length, World>(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector<Length, World>(nullDisplacement),\n Bivector<Length, World>(u),\n Bivector<Length, World>(v),\n Bivector<Length, World>(w),\n Bivector<Length, World>(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector<Length, World>(nullDisplacement.x),\n Trivector<Length, World>(u.y),\n Trivector<Length, World>(v.z),\n Trivector<Length, World>(w.x),\n Trivector<Length, World>(a.y),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n {\n std::function<Dimensionless(Vector<Dimensionless, World>,\n Vector<Dimensionless, World>)>\n vectorInnerProduct = [](Vector<Dimensionless, World> a,\n Vector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Dimensionless(Bivector<Dimensionless, World>,\n Bivector<Dimensionless, World>)>\n bivectorInnerProduct = [](Bivector<Dimensionless, World> a,\n Bivector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Dimensionless(Trivector<Dimensionless, World>,\n Trivector<Dimensionless, World>)>\n trivectorInnerProduct = [](Trivector<Dimensionless, World> a,\n Trivector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector<Dimensionless,\n World>(nullDisplacement \/ Metre),\n Vector<Dimensionless, World>(u \/ Metre),\n Vector<Dimensionless, World>(v \/ Metre),\n Vector<Dimensionless, World>(w \/ Metre),\n Vector<Dimensionless, World>(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector<Dimensionless,\n World>(nullDisplacement \/ Metre),\n Bivector<Dimensionless, World>(u \/ Metre),\n Bivector<Dimensionless, World>(v \/ Metre),\n Bivector<Dimensionless, World>(w \/ Metre),\n Bivector<Dimensionless, World>(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector<Dimensionless,\n World>(nullDisplacement.x \/ Metre),\n Trivector<Dimensionless, World>(u.y \/ Metre),\n Trivector<Dimensionless, World>(v.z \/ Metre),\n Trivector<Dimensionless, World>(w.x \/ Metre),\n Trivector<Dimensionless, World>(a.y \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n }\n};\n} \/\/ namespace GeometryTests\n} \/\/ namespace Principia\n<commit_msg>Tiny test.<commit_after>#include \"stdafx.hpp\"\n\n#include <functional>\n\n#include \"CppUnitTest.h\"\n#include \"..\\TestUtilities\\TestUtilities.hpp\"\n#include \"..\\TestUtilities\\QuantityComparisons.hpp\"\n#include \"..\\TestUtilities\\GeometryComparisons.hpp\"\n#include \"..\\TestUtilities\\Algebra.hpp\"\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"..\\Quantities\\SI.hpp\"\n#include \"..\\Quantities\\Constants.hpp\"\n#include \"..\\Quantities\\UK.hpp\"\n#include \"..\\Quantities\\BIPM.hpp\"\n#include \"..\\Quantities\\Astronomy.hpp\"\n#include \"..\\Geometry\\R3Element.hpp\"\n#include \"..\\Geometry\\Grassmann.hpp\"\n#include \"..\\Quantities\\ElementaryFunctions.hpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace Principia {\nnamespace GeometryTests\n{\nusing namespace Geometry;\nusing namespace Quantities;\nusing namespace SI;\nusing namespace UK;\nusing namespace BIPM;\nusing namespace Astronomy;\nusing namespace Constants;\nusing namespace TestUtilities;\n\nTEST_CLASS(GeometryTests)\n{\n public:\n struct World;\n TEST_METHOD(Dumb3Vector) {\n R3Element<Speed> nullVector(0 * Metre \/ Second,\n 0 * Metre \/ Second,\n 0 * Metre \/ Second);\n R3Element<Speed> u(1 * Metre \/ Second,\n 120 * Kilo(Metre) \/ Hour,\n -SpeedOfLight);\n R3Element<Speed> v(-20 * Knot,\n 2 * π * AstronomicalUnit \/ JulianYear,\n 1 * Admiralty::NauticalMile \/ Hour);\n R3Element<Speed> w(-1 * Mile \/ Hour, -2 * Foot \/ Second, -3 * Knot);\n R3Element<Speed> a(88 * Mile \/ Hour, 300 * Metre \/ Second, 46 * Knot);\n AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));\n TestVectorSpace<R3Element<Speed>,\n Dimensionless>(nullVector, u, v, w, Dimensionless(0),\n Dimensionless(1), e, Dimensionless(42));\n TestAlternatingBilinearMap(Cross<Speed, Speed>, u,\n v, w, a, Dimensionless(42));\n TestSymmetricPositiveDefiniteBilinearMap(Dot<Speed, Speed>,\n u, v, w, a, Dimensionless(42));\n }\n\n TEST_METHOD(SpecialOrthogonalLieAlgebra) {\n R3Element<Dimensionless> u(3, -42, 0);\n R3Element<Dimensionless> v(-π, -e, -1);\n R3Element<Dimensionless> w(2, 2, 2);\n R3Element<Dimensionless> a(1.2, 2.3, 3.4);\n TestLieBracket(Commutator<Dimensionless, Dimensionless, World>,\n Bivector<Dimensionless, World>(u),\n Bivector<Dimensionless, World>(v),\n Bivector<Dimensionless, World>(w),\n Bivector<Dimensionless, World>(a), Dimensionless(0.42));\n }\n\n TEST_METHOD(VectorSpaces) {\n R3Element<Length> nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);\n R3Element<Length> u(3 * Metre, -42 * Metre, 0 * Metre);\n R3Element<Length> v(-π * Metre, -e * Metre, -1 * Metre);\n R3Element<Length> w(2 * Metre, 2 * Metre, 2 * Metre);\n R3Element<Length> a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);\n {\n std::function<Area(Vector<Length, World>,\n Vector<Length, World>)> vectorInnerProduct =\n [](Vector<Length, World> a, Vector<Length, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Area(Bivector<Length, World>,\n Bivector<Length, World>)> bivectorInnerProduct =\n [](Bivector<Length, World> a, Bivector<Length, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Area(Trivector<Length, World>,\n Trivector<Length, World>)> trivectorInnerProduct =\n [](Trivector<Length, World> a, Trivector<Length, World> b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector<Length, World>(nullDisplacement),\n Vector<Length, World>(u), Vector<Length, World>(v),\n Vector<Length, World>(w), Vector<Length, World>(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector<Length, World>(nullDisplacement),\n Bivector<Length, World>(u),\n Bivector<Length, World>(v),\n Bivector<Length, World>(w),\n Bivector<Length, World>(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector<Length, World>(nullDisplacement.x),\n Trivector<Length, World>(u.y),\n Trivector<Length, World>(v.z),\n Trivector<Length, World>(w.x),\n Trivector<Length, World>(a.y),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n {\n std::function<Dimensionless(Vector<Dimensionless, World>,\n Vector<Dimensionless, World>)>\n vectorInnerProduct = [](Vector<Dimensionless, World> a,\n Vector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Dimensionless(Bivector<Dimensionless, World>,\n Bivector<Dimensionless, World>)>\n bivectorInnerProduct = [](Bivector<Dimensionless, World> a,\n Bivector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n std::function<Dimensionless(Trivector<Dimensionless, World>,\n Trivector<Dimensionless, World>)>\n trivectorInnerProduct = [](Trivector<Dimensionless, World> a,\n Trivector<Dimensionless, World> b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector<Dimensionless,\n World>(nullDisplacement \/ Metre),\n Vector<Dimensionless, World>(u \/ Metre),\n Vector<Dimensionless, World>(v \/ Metre),\n Vector<Dimensionless, World>(w \/ Metre),\n Vector<Dimensionless, World>(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector<Dimensionless,\n World>(nullDisplacement \/ Metre),\n Bivector<Dimensionless, World>(u \/ Metre),\n Bivector<Dimensionless, World>(v \/ Metre),\n Bivector<Dimensionless, World>(w \/ Metre),\n Bivector<Dimensionless, World>(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector<Dimensionless,\n World>(nullDisplacement.x \/ Metre),\n Trivector<Dimensionless, World>(u.y \/ Metre),\n Trivector<Dimensionless, World>(v.z \/ Metre),\n Trivector<Dimensionless, World>(w.x \/ Metre),\n Trivector<Dimensionless, World>(a.y \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n }\n TEST_METHOD(GrassmannAlgebra) {\n R3Element<Dimensionless> u(3, -42, 0);\n R3Element<Dimensionless> v(-π, -e, -1);\n R3Element<Dimensionless> w(2, 2, 2);\n R3Element<Dimensionless> a(1.2, 2.3, 3.4);\n std::function<Bivector<Dimensionless,\n World>(Vector<Dimensionless, World>,\n Vector<Dimensionless, World>)> vectorWedge =\n [](Vector<Dimensionless, World> a, Vector<Dimensionless, World> b) {\n return Wedge(a, b);\n };\n TestAlternatingBilinearMap(vectorWedge, Vector<Dimensionless, World>(u),\n Vector<Dimensionless, World>(u),\n Vector<Dimensionless, World>(u),\n Vector<Dimensionless, World>(u),\n Dimensionless(6 * 9));\n }\n};\n} \/\/ namespace GeometryTests\n} \/\/ namespace Principia\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2011-2012 Google\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"base\/hash.h\"\n#include \"base\/map-util.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/random.h\"\n#include \"constraint_solver\/constraint_solveri.h\"\n#include \"constraint_solver\/constraint_solver.h\"\n\nDEFINE_int32(vsize, 5, \"Number of variables\");\nDEFINE_int32(csize, 5, \"Number of variables\");\nDEFINE_int32(slack, 4, \"Slack in cardinalities\");\nDEFINE_int32(seed, 1, \"Random seed\");\n\nnamespace operations_research {\nextern Constraint* Gcc(Solver* const solver,\n const std::vector<IntVar*>& vars,\n int64 first_domain_value,\n const std::vector<int>& min_occurrences,\n const std::vector<int>& max_occurrences);\n\nint64 TestGcc(int vsize, int csize, int slack, int seed, bool use_gcc) {\n if (vsize > csize + slack) {\n LOG(INFO) << \"Cannot create problem\";\n return 0;\n }\n ACMRandom rgen(seed); \/\/ defines a random generator\n\n std::vector<int> card_min(csize, 0);\n std::vector<int> card_max(csize, 0);\n for (int i = 0; i< vsize - slack; ++i) {\n const int index = rgen.Uniform(csize);\n card_min[index]++;\n card_max[index]++;\n }\n for (int i = 0; i < slack; ++i) {\n const int index = rgen.Uniform(csize);\n card_max[index]++;\n }\n\n LOG(INFO) << (use_gcc ? \"Gcc constraint:\" : \"Distribute constraint:\");\n LOG(INFO) << \" - num variables = \" << vsize;\n LOG(INFO) << \" - num values = \" << csize;\n LOG(INFO) << \" - slack = \" << slack;\n LOG(INFO) << \" - seed = \" << seed;\n Solver solver(\"TestGcc\");\n std::vector<IntVar*> vars;\n solver.MakeIntVarArray(vsize, 0, csize - 1, &vars);\n Constraint* const gcc = use_gcc ?\n Gcc(&solver, vars, 0, card_min, card_max) :\n solver.MakeDistribute(vars, card_min, card_max);\n solver.AddConstraint(gcc);\n DecisionBuilder* const db = solver.MakePhase(vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE);\n\n LOG(INFO) << \"Start search\";\n CycleTimer t;\n t.Start();\n solver.NewSearch(db);\n int counter = 0;\n while(solver.NextSolution()) {\n counter++;\n }\n solver.EndSearch();\n t.Stop();\n\n LOG(INFO) << \"test time : \" << t.GetInUsec() << \" micro seconds\";\n LOG(INFO) << \"Found \" << counter << \" solutions\";\n return counter;\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char** argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n CHECK_EQ(operations_research::TestGcc(FLAGS_vsize,\n FLAGS_csize,\n FLAGS_slack,\n FLAGS_seed,\n false),\n operations_research::TestGcc(FLAGS_vsize,\n FLAGS_csize,\n FLAGS_slack,\n FLAGS_seed,\n true));\n return 0;\n}\n<commit_msg>improve example<commit_after>\/\/ Copyright 2011-2012 Google\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"base\/hash.h\"\n#include \"base\/map-util.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/random.h\"\n#include \"constraint_solver\/constraint_solveri.h\"\n#include \"constraint_solver\/constraint_solver.h\"\n\nDEFINE_int32(vsize, 5, \"Number of variables\");\nDEFINE_int32(csize, 5, \"Number of variables\");\nDEFINE_int32(slack, 4, \"Slack in cardinalities\");\nDEFINE_int32(seed, 1, \"Random seed\");\n\nnamespace operations_research {\nextern Constraint* Gcc(Solver* const solver,\n const std::vector<IntVar*>& vars,\n int64 first_domain_value,\n const std::vector<int>& min_occurrences,\n const std::vector<int>& max_occurrences);\n\nint64 TestGcc(int vsize, int csize, int slack, int seed, bool use_gcc) {\n if (vsize > csize + slack) {\n LOG(INFO) << \"Cannot create problem\";\n return 0;\n }\n ACMRandom rgen(seed); \/\/ defines a random generator\n\n std::vector<int> card_min(csize, 0);\n std::vector<int> card_max(csize, 0);\n for (int i = 0; i< vsize - slack; ++i) {\n const int index = rgen.Uniform(csize);\n card_min[index]++;\n card_max[index]++;\n }\n for (int i = 0; i < 2 * slack; ++i) {\n card_max[rgen.Uniform(csize)]++;\n }\n\n LOG(INFO) << (use_gcc ? \"Gcc constraint:\" : \"Distribute constraint:\");\n LOG(INFO) << \" - num variables = \" << vsize;\n LOG(INFO) << \" - num values = \" << csize;\n LOG(INFO) << \" - slack = \" << slack;\n LOG(INFO) << \" - seed = \" << seed;\n\n Solver solver(\"TestGcc\");\n std::vector<IntVar*> vars;\n solver.MakeIntVarArray(vsize, 0, csize - 1, &vars);\n Constraint* const gcc = use_gcc ?\n Gcc(&solver, vars, 0, card_min, card_max) :\n solver.MakeDistribute(vars, card_min, card_max);\n solver.AddConstraint(gcc);\n DecisionBuilder* const db = solver.MakePhase(vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE);\n\n LOG(INFO) << \"Start search\";\n CycleTimer t;\n t.Start();\n solver.NewSearch(db);\n int counter = 0;\n while(solver.NextSolution()) {\n counter++;\n }\n solver.EndSearch();\n t.Stop();\n\n LOG(INFO) << \"test time : \" << t.GetInUsec() << \" micro seconds\";\n LOG(INFO) << \"Found \" << counter << \" solutions\";\n return counter;\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char** argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n CHECK_EQ(operations_research::TestGcc(FLAGS_vsize,\n FLAGS_csize,\n FLAGS_slack,\n FLAGS_seed,\n false),\n operations_research::TestGcc(FLAGS_vsize,\n FLAGS_csize,\n FLAGS_slack,\n FLAGS_seed,\n true));\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/*\n * Example macro to run the HLT Conformal mapping tracker embedded into\n * AliRoot reconstruction. The reconstruction is done from the TPC raw\n * data.\n *\n * Usage:\n * <pre>\n * aliroot -b -q rec-hlt-tpc.C | tee rec-hlt-tpc.log\n * aliroot -b -q rec-hlt-tpc.C'(\".\/\",\"decoder All\")' | tee rec-hlt-tpc.log\n * <\/pre>\n *\n * The macro asumes raw data to be available in the rawx folders, either\n * simulated or real data. A different input can be specified as parameter\n * <pre>\n * aliroot -b -q rec-hlt-tpc.C'(\"input.root\")'\n * <\/pre>\n *\n * The ClusterFinder uses the offline altro decoder v3 by default. The former\n * CF components can be selected by means of the second parameter:\n * - decoder, uses TPCClusterFinderDecoder. This is default.\n * - packed, uses TPCClusterFinderPacked\n *\n * Also in the second parameter you can set which output you would like to have:\n * - ESD, gives you an ESD file. This is default.\n * - TrackHistogram, will run the TrackHistogram component, and give \n * root files with histograms.\n * - TrackDump, dumps the track struct to a text file.\n * - ClusterHisto, gives you histograms of the cluster.\n * - ClusterDump, dumps the cluster struct to text flie.\n * - All, gives you all 3 output.\n *\n * In the first section, an analysis chain is defined. The scale of the\n * chain can be defined by choosing the range of sectors and partitions.\n *\n * The reconstruction is steered by the AliReconstruction object in the\n * usual way.\n *\n * @ingroup alihlt_tpc\n * @author Matthias.Richter@ift.uib.no\n *\/\nvoid rec_hlt_tpc(const char* input=\".\/\", char* opt=\"decoder ESD\")\n{\n \n if(!gSystem->AccessPathName(\"galice.root\")){\n cerr << \"please delete the galice.root or run at different place.\" << endl;\n return;\n }\n\n if (!input) {\n cerr << \"please specify input or run without arguments\" << endl;\n return;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ init the HLT system in order to define the analysis chain below\n \/\/\n AliHLTSystem* gHLT=AliHLTPluginBase::GetInstance();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Setting up which output to give\n \/\/\n int clusterFinderType=0; \/\/ 0 = v3; 1 = decoder; 2 = packed (offline v1)\n bool bUseCA=true; \/\/ use the CA tracker and merger\n TString option=\"libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so loglevel=0x7c chains=\";\n Bool_t esdout=kFALSE, dumpout=kFALSE, histout=kFALSE, chout=kFALSE, cdout=kFALSE;\n TString allArgs=opt;\n TString argument;\n TObjArray* pTokens=allArgs.Tokenize(\" \");\n if (pTokens) {\n for (int i=0; i<pTokens->GetEntries(); i++) {\n argument=((TObjString*)pTokens->At(i))->GetString();\n if (argument.IsNull()) continue;\n \n if (argument.Contains(\"-statistics=\")) {\n\targument.ReplaceAll(\"-statistics=\", \"\");\n\tif (argument.Contains(\"root\")) {\n\t if (option.Length()>0) option+=\",\";\n\t option+=\"statroot\";\n\t}\n\tif (argument.Contains(\"raw\")) {\n\t if (option.Length()>0) option+=\",\";\n\t option+=\"statraw\";\n\t}\n\tcontinue;\n }\n if (argument.CompareTo(\"ca\", TString::kIgnoreCase)==0) {\n\tbUseCA=true;\n\tcontinue;\n } \n if (argument.CompareTo(\"cm\", TString::kIgnoreCase)==0) {\n\tbUseCA=false;\n\tcontinue;\n }\n if (argument.CompareTo(\"decoder\",TString::kIgnoreCase)==0) {\n\tclusterFinderType = 1;\n\tcontinue;\n }\n if (argument.CompareTo(\"packed\",TString::kIgnoreCase)==0) {\n\tclusterFinderType = 2;\n\tcontinue;\n }\n if (argument.CompareTo(\"trackhistogram\",TString::kIgnoreCase)==0) {\n\thistout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"histFile\";\n\tcontinue;\n }\n if (argument.CompareTo(\"trackdump\",TString::kIgnoreCase)==0) {\n\tdumpout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"dump\";\n\tcontinue;\n }\n if (argument.CompareTo(\"esd\",TString::kIgnoreCase)==0) {\n\tesdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esd-converter\";\n\tcontinue;\n }\n if (argument.CompareTo(\"esdwrite\",TString::kIgnoreCase)==0) {\n\tesdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esdfile\";\n\tcontinue;\n }\n if (argument.CompareTo(\"clusterdump\",TString::kIgnoreCase)==0) {\n\tcdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"cdump\";\n\tcontinue;\n } \n if (argument.CompareTo(\"clusterhisto\",TString::kIgnoreCase)==0) {\n\tchout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"chhisto\";\n\tcontinue;\n } \n if (argument.CompareTo(\"all\",TString::kIgnoreCase)==0) {\n\thistout = kTRUE;\n\tdumpout = kTRUE;\n\tesdout = kTRUE;\n\tchout = kTRUE;\n\tcdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esd-converter,histFile,dump,cdump,chhisto\";\n\tcontinue;\n }\n else {\n\tbreak;\n }\n }\n }\n if (!histout && !dumpout && !esdout && !chout && !cdout) {\n cout << \"you need to specify an output option, on or more out of: ESD, TrackHistogram, TrackDump, ClusterHisto, ClusterDump\" << endl;\n return;\n }\n if ((option.Contains(\"statroot\") || option.Contains(\"statraw\")) && !esdout) {\n cout << \"!!!!!!!! Warning: HLT statistics are only collected for output type ESD !!!!!!!!\" << endl;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ define the analysis chain to be run\n \/\/\n int iMinSlice=0;\n int iMaxSlice=35;\n int iMinPart=0;\n int iMaxPart=5;\n TString writerInput;\n TString mergerInput;\n TString histoInput;\n TString histogramHandlerInputClusterFinder;\n TString cdumpInput;\n for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {\n TString trackerInput;\n for (int part=iMinPart; part<=iMaxPart; part++) {\n TString arg, publisher, cf;\n TString clusterHistoOutput;\n \/\/ raw data publisher components\n int ddlno=768;\n if (part>1) ddlno+=72+4*slice+(part-2);\n else ddlno+=2*slice+part;\n arg.Form(\"-minid %d -datatype 'DDL_RAW ' 'TPC ' -dataspec 0x%02x%02x%02x%02x -verbose\", ddlno, slice, slice, part, part);\n publisher.Form(\"DP_%02d_%d\", slice, part);\n AliHLTConfiguration pubconf(publisher.Data(), \"AliRawReaderPublisher\", NULL , arg.Data());\n\n \/\/ cluster finder components\n cf.Form(\"CF_%02d_%d\", slice, part);\n if (clusterFinderType==1) {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinderDecoder\", publisher.Data(), \"-timebins 1001\");\n } else if (clusterFinderType==2) {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinderPacked\", publisher.Data(), \"-timebins 1001 -sorted\");\n } else {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinder32bit\", publisher.Data(), \"-timebins 1001\");\n }\n if (trackerInput.Length()>0) trackerInput+=\" \";\n trackerInput+=cf;\n if (writerInput.Length()>0) writerInput+=\" \";\n writerInput+=cf;\n if (histoInput.Length()>0) histoInput+=\" \";\n histoInput+=cf;\n if (cdumpInput.Length()>0) cdumpInput+=\" \";\n cdumpInput+=cf;\n\n if(chout){\n\tclusterHistoOutput.Form(\"CH_%02d_%d\", slice, part);\n\tAliHLTConfiguration cfconf(clusterHistoOutput.Data(), \"TPCClusterHisto\", cf.Data(), \"\");\n\tif (histogramHandlerInputClusterFinder.Length()>0) histogramHandlerInputClusterFinder+=\" \";\n\thistogramHandlerInputClusterFinder+=clusterHistoOutput;\n }\n }\n TString tracker;\n \/\/ tracker components\n tracker.Form(\"TR_%02d\", slice);\n if (bUseCA) {\n AliHLTConfiguration trackerconf(tracker.Data(), \"TPCCATracker\", trackerInput.Data(), \"\");\n } else {\n AliHLTConfiguration trackerconf(tracker.Data(), \"TPCSliceTracker\", trackerInput.Data(), \"-pp-run\");\n }\n\n if (writerInput.Length()>0) writerInput+=\" \";\n writerInput+=tracker;\n if (mergerInput.Length()>0) mergerInput+=\" \";\n mergerInput+=tracker;\n \/\/add all slice tracks to histo input\n \/\/if (histoInput.Length()>0) histoInput+=\" \";\n \/\/histoInput+=tracker;\n }\n\n \/\/ GlobalMerger component\n if (bUseCA) {\n AliHLTConfiguration mergerconf(\"globalmerger\",\"TPCCAGlobalMerger\",mergerInput.Data(),\"\");\n } else {\n AliHLTConfiguration mergerconf(\"globalmerger\",\"TPCGlobalMerger\",mergerInput.Data(),\"\");\n }\n \n \/\/add all global tracks to histo input\n if (histoInput.Length()>0) histoInput+=\" \";\n histoInput+=\"globalmerger\";\n \n \/\/ specify whether to write all blocks separately or merge the tracks\n \/\/ and convert to ESD\n bool writeBlocks=false;\n\n if(esdout){\n if (writeBlocks) {\n \/\/ the writer configuration\n AliHLTConfiguration fwconf(\"esdfile\", \"FileWriter\" , writerInput.Data(), \"-specfmt=_%d -subdir=out_%d -blcknofmt=_0x%x -idfmt=_0x%08x\");\n } else {\n \n \/\/ the esd converter configuration\n AliHLTConfiguration esdcconf(\"esd-converter\", \"TPCEsdConverter\" , \"globalmerger\", \"\");\n \n \/\/ the root file writer configuration\n AliHLTConfiguration sink(\"esdfile\", \"EsdCollector\" , \"esd-converter\", \"-directory hlt-tpc-esd\");\n\n \/\/ optional component statistics\n AliHLTConfiguration statroot(\"statroot\", \"StatisticsCollector\" , \"esd-converter\", \"-file HLT.statistics.root -publish 0\");\n AliHLTConfiguration statraw(\"statraw\", \"FileWriter\" , \"esd-converter\", \"-datatype COMPSTAT PRIV -datafile HLT.statistics.raw -concatenate-blocks -concatenate-events\");\n }\n }\n \/\/Chain with Track Histogram\n if(histout){\n AliHLTConfiguration histoconf(\"histo\",\"TPCTrackHisto\",histoInput.Data(),\"\"); \n AliHLTConfiguration fwconf(\"histFile\", \"ROOTFileWriter\" , \"histo\", \"-datafile TrackHisto -concatenate-events -overwrite\");\n }\n \/\/Chain with Track Dump\n if(dumpout){\n AliHLTConfiguration dumpconf(\"dump\",\"TPCTrackDump\",\"globalmerger\",\"-directory TrackDump\");\n }\n if(chout){\n AliHLTConfiguration cfconf(\"HHCF\", \"TPCHistogramHandler\", histogramHandlerInputClusterFinder.Data(), \"-use-general\");\n AliHLTConfiguration rootFileWriterClusters(\"chhisto\", \"ROOTFileWriter\", \"HHCF\" , \"-datafile histogramHandlerClusterFinder -concatenate-events -overwrite\");\n }\n if(cdout){\n AliHLTConfiguration cdumpconf(\"cdump\",\"TPCClusterDump\",cdumpInput.Data(),\"-directory ClusterDump\");\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Init and run the reconstruction\n \/\/ All but HLT reconstructio is switched off\n \/\/\n AliReconstruction rec;\n rec.SetInput(input);\n rec.SetRunVertexFinder(kFALSE);\n rec.SetRunReconstruction(\"HLT\");\n rec.SetLoadAlignFromCDB(0);\n rec.SetRunQA(\":\");\n rec.SetOption(\"HLT\", option);\n rec.Run();\n}\n<commit_msg>Bugfix: lowercase b should be upper case B for component id: TPCClusterFinder32Bit<commit_after>\/\/ $Id$\n\/*\n * Example macro to run the HLT Conformal mapping tracker embedded into\n * AliRoot reconstruction. The reconstruction is done from the TPC raw\n * data.\n *\n * Usage:\n * <pre>\n * aliroot -b -q rec-hlt-tpc.C | tee rec-hlt-tpc.log\n * aliroot -b -q rec-hlt-tpc.C'(\".\/\",\"decoder All\")' | tee rec-hlt-tpc.log\n * <\/pre>\n *\n * The macro asumes raw data to be available in the rawx folders, either\n * simulated or real data. A different input can be specified as parameter\n * <pre>\n * aliroot -b -q rec-hlt-tpc.C'(\"input.root\")'\n * <\/pre>\n *\n * The ClusterFinder uses the offline altro decoder v3 by default. The former\n * CF components can be selected by means of the second parameter:\n * - decoder, uses TPCClusterFinderDecoder. This is default.\n * - packed, uses TPCClusterFinderPacked\n *\n * Also in the second parameter you can set which output you would like to have:\n * - ESD, gives you an ESD file. This is default.\n * - TrackHistogram, will run the TrackHistogram component, and give \n * root files with histograms.\n * - TrackDump, dumps the track struct to a text file.\n * - ClusterHisto, gives you histograms of the cluster.\n * - ClusterDump, dumps the cluster struct to text flie.\n * - All, gives you all 3 output.\n *\n * In the first section, an analysis chain is defined. The scale of the\n * chain can be defined by choosing the range of sectors and partitions.\n *\n * The reconstruction is steered by the AliReconstruction object in the\n * usual way.\n *\n * @ingroup alihlt_tpc\n * @author Matthias.Richter@ift.uib.no\n *\/\nvoid rec_hlt_tpc(const char* input=\".\/\", char* opt=\"decoder ESD\")\n{\n \n if(!gSystem->AccessPathName(\"galice.root\")){\n cerr << \"please delete the galice.root or run at different place.\" << endl;\n return;\n }\n\n if (!input) {\n cerr << \"please specify input or run without arguments\" << endl;\n return;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ init the HLT system in order to define the analysis chain below\n \/\/\n AliHLTSystem* gHLT=AliHLTPluginBase::GetInstance();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Setting up which output to give\n \/\/\n int clusterFinderType=0; \/\/ 0 = v3; 1 = decoder; 2 = packed (offline v1)\n bool bUseCA=true; \/\/ use the CA tracker and merger\n TString option=\"libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so loglevel=0x7c chains=\";\n Bool_t esdout=kFALSE, dumpout=kFALSE, histout=kFALSE, chout=kFALSE, cdout=kFALSE;\n TString allArgs=opt;\n TString argument;\n TObjArray* pTokens=allArgs.Tokenize(\" \");\n if (pTokens) {\n for (int i=0; i<pTokens->GetEntries(); i++) {\n argument=((TObjString*)pTokens->At(i))->GetString();\n if (argument.IsNull()) continue;\n \n if (argument.Contains(\"-statistics=\")) {\n\targument.ReplaceAll(\"-statistics=\", \"\");\n\tif (argument.Contains(\"root\")) {\n\t if (option.Length()>0) option+=\",\";\n\t option+=\"statroot\";\n\t}\n\tif (argument.Contains(\"raw\")) {\n\t if (option.Length()>0) option+=\",\";\n\t option+=\"statraw\";\n\t}\n\tcontinue;\n }\n if (argument.CompareTo(\"ca\", TString::kIgnoreCase)==0) {\n\tbUseCA=true;\n\tcontinue;\n } \n if (argument.CompareTo(\"cm\", TString::kIgnoreCase)==0) {\n\tbUseCA=false;\n\tcontinue;\n }\n if (argument.CompareTo(\"decoder\",TString::kIgnoreCase)==0) {\n\tclusterFinderType = 1;\n\tcontinue;\n }\n if (argument.CompareTo(\"packed\",TString::kIgnoreCase)==0) {\n\tclusterFinderType = 2;\n\tcontinue;\n }\n if (argument.CompareTo(\"trackhistogram\",TString::kIgnoreCase)==0) {\n\thistout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"histFile\";\n\tcontinue;\n }\n if (argument.CompareTo(\"trackdump\",TString::kIgnoreCase)==0) {\n\tdumpout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"dump\";\n\tcontinue;\n }\n if (argument.CompareTo(\"esd\",TString::kIgnoreCase)==0) {\n\tesdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esd-converter\";\n\tcontinue;\n }\n if (argument.CompareTo(\"esdwrite\",TString::kIgnoreCase)==0) {\n\tesdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esdfile\";\n\tcontinue;\n }\n if (argument.CompareTo(\"clusterdump\",TString::kIgnoreCase)==0) {\n\tcdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"cdump\";\n\tcontinue;\n } \n if (argument.CompareTo(\"clusterhisto\",TString::kIgnoreCase)==0) {\n\tchout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"chhisto\";\n\tcontinue;\n } \n if (argument.CompareTo(\"all\",TString::kIgnoreCase)==0) {\n\thistout = kTRUE;\n\tdumpout = kTRUE;\n\tesdout = kTRUE;\n\tchout = kTRUE;\n\tcdout = kTRUE;\n\tif (option.Length()>0) option+=\",\";\n\toption+=\"esd-converter,histFile,dump,cdump,chhisto\";\n\tcontinue;\n }\n else {\n\tbreak;\n }\n }\n }\n if (!histout && !dumpout && !esdout && !chout && !cdout) {\n cout << \"you need to specify an output option, on or more out of: ESD, TrackHistogram, TrackDump, ClusterHisto, ClusterDump\" << endl;\n return;\n }\n if ((option.Contains(\"statroot\") || option.Contains(\"statraw\")) && !esdout) {\n cout << \"!!!!!!!! Warning: HLT statistics are only collected for output type ESD !!!!!!!!\" << endl;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ define the analysis chain to be run\n \/\/\n int iMinSlice=0;\n int iMaxSlice=35;\n int iMinPart=0;\n int iMaxPart=5;\n TString writerInput;\n TString mergerInput;\n TString histoInput;\n TString histogramHandlerInputClusterFinder;\n TString cdumpInput;\n for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {\n TString trackerInput;\n for (int part=iMinPart; part<=iMaxPart; part++) {\n TString arg, publisher, cf;\n TString clusterHistoOutput;\n \/\/ raw data publisher components\n int ddlno=768;\n if (part>1) ddlno+=72+4*slice+(part-2);\n else ddlno+=2*slice+part;\n arg.Form(\"-minid %d -datatype 'DDL_RAW ' 'TPC ' -dataspec 0x%02x%02x%02x%02x -verbose\", ddlno, slice, slice, part, part);\n publisher.Form(\"DP_%02d_%d\", slice, part);\n AliHLTConfiguration pubconf(publisher.Data(), \"AliRawReaderPublisher\", NULL , arg.Data());\n\n \/\/ cluster finder components\n cf.Form(\"CF_%02d_%d\", slice, part);\n if (clusterFinderType==1) {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinderDecoder\", publisher.Data(), \"-timebins 1001\");\n } else if (clusterFinderType==2) {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinderPacked\", publisher.Data(), \"-timebins 1001 -sorted\");\n } else {\n\tAliHLTConfiguration cfconf(cf.Data(), \"TPCClusterFinder32Bit\", publisher.Data(), \"-timebins 1001\");\n }\n if (trackerInput.Length()>0) trackerInput+=\" \";\n trackerInput+=cf;\n if (writerInput.Length()>0) writerInput+=\" \";\n writerInput+=cf;\n if (histoInput.Length()>0) histoInput+=\" \";\n histoInput+=cf;\n if (cdumpInput.Length()>0) cdumpInput+=\" \";\n cdumpInput+=cf;\n\n if(chout){\n\tclusterHistoOutput.Form(\"CH_%02d_%d\", slice, part);\n\tAliHLTConfiguration cfconf(clusterHistoOutput.Data(), \"TPCClusterHisto\", cf.Data(), \"\");\n\tif (histogramHandlerInputClusterFinder.Length()>0) histogramHandlerInputClusterFinder+=\" \";\n\thistogramHandlerInputClusterFinder+=clusterHistoOutput;\n }\n }\n TString tracker;\n \/\/ tracker components\n tracker.Form(\"TR_%02d\", slice);\n if (bUseCA) {\n AliHLTConfiguration trackerconf(tracker.Data(), \"TPCCATracker\", trackerInput.Data(), \"\");\n } else {\n AliHLTConfiguration trackerconf(tracker.Data(), \"TPCSliceTracker\", trackerInput.Data(), \"-pp-run\");\n }\n\n if (writerInput.Length()>0) writerInput+=\" \";\n writerInput+=tracker;\n if (mergerInput.Length()>0) mergerInput+=\" \";\n mergerInput+=tracker;\n \/\/add all slice tracks to histo input\n \/\/if (histoInput.Length()>0) histoInput+=\" \";\n \/\/histoInput+=tracker;\n }\n\n \/\/ GlobalMerger component\n if (bUseCA) {\n AliHLTConfiguration mergerconf(\"globalmerger\",\"TPCCAGlobalMerger\",mergerInput.Data(),\"\");\n } else {\n AliHLTConfiguration mergerconf(\"globalmerger\",\"TPCGlobalMerger\",mergerInput.Data(),\"\");\n }\n \n \/\/add all global tracks to histo input\n if (histoInput.Length()>0) histoInput+=\" \";\n histoInput+=\"globalmerger\";\n \n \/\/ specify whether to write all blocks separately or merge the tracks\n \/\/ and convert to ESD\n bool writeBlocks=false;\n\n if(esdout){\n if (writeBlocks) {\n \/\/ the writer configuration\n AliHLTConfiguration fwconf(\"esdfile\", \"FileWriter\" , writerInput.Data(), \"-specfmt=_%d -subdir=out_%d -blcknofmt=_0x%x -idfmt=_0x%08x\");\n } else {\n \n \/\/ the esd converter configuration\n AliHLTConfiguration esdcconf(\"esd-converter\", \"TPCEsdConverter\" , \"globalmerger\", \"\");\n \n \/\/ the root file writer configuration\n AliHLTConfiguration sink(\"esdfile\", \"EsdCollector\" , \"esd-converter\", \"-directory hlt-tpc-esd\");\n\n \/\/ optional component statistics\n AliHLTConfiguration statroot(\"statroot\", \"StatisticsCollector\" , \"esd-converter\", \"-file HLT.statistics.root -publish 0\");\n AliHLTConfiguration statraw(\"statraw\", \"FileWriter\" , \"esd-converter\", \"-datatype COMPSTAT PRIV -datafile HLT.statistics.raw -concatenate-blocks -concatenate-events\");\n }\n }\n \/\/Chain with Track Histogram\n if(histout){\n AliHLTConfiguration histoconf(\"histo\",\"TPCTrackHisto\",histoInput.Data(),\"\"); \n AliHLTConfiguration fwconf(\"histFile\", \"ROOTFileWriter\" , \"histo\", \"-datafile TrackHisto -concatenate-events -overwrite\");\n }\n \/\/Chain with Track Dump\n if(dumpout){\n AliHLTConfiguration dumpconf(\"dump\",\"TPCTrackDump\",\"globalmerger\",\"-directory TrackDump\");\n }\n if(chout){\n AliHLTConfiguration cfconf(\"HHCF\", \"TPCHistogramHandler\", histogramHandlerInputClusterFinder.Data(), \"-use-general\");\n AliHLTConfiguration rootFileWriterClusters(\"chhisto\", \"ROOTFileWriter\", \"HHCF\" , \"-datafile histogramHandlerClusterFinder -concatenate-events -overwrite\");\n }\n if(cdout){\n AliHLTConfiguration cdumpconf(\"cdump\",\"TPCClusterDump\",cdumpInput.Data(),\"-directory ClusterDump\");\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Init and run the reconstruction\n \/\/ All but HLT reconstructio is switched off\n \/\/\n AliReconstruction rec;\n rec.SetInput(input);\n rec.SetRunVertexFinder(kFALSE);\n rec.SetRunReconstruction(\"HLT\");\n rec.SetLoadAlignFromCDB(0);\n rec.SetRunQA(\":\");\n rec.SetOption(\"HLT\", option);\n rec.Run();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>use offset of 100 instead of negative values to forward return value of AliHLTCreateGRP class (negatives don't work - thanks to Mikolaj)<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/$Id$\n\n\/\/ Author: Anders Vestbo <mailto:vestbo@fi.uib.no>\n\/\/*-- Copyright © ASV \n\n#include <iostream.h>\n#include <math.h>\n#include \"AliL3Logging.h\"\n#include \"AliL3ClustFinderNew.h\"\n#include \"AliL3DigitData.h\"\n#include \"AliL3Transform.h\"\n#include \"AliL3SpacePointData.h\"\n#include \"AliL3MemHandler.h\"\n\n\/\/_____________________________________________________________\n\/\/ AliL3ClustFinderNew\n\/\/\n\/\/ The current cluster finder for HLT\n\/\/ Based on STAR L3\n\nClassImp(AliL3ClustFinderNew)\n\nAliL3ClustFinderNew::AliL3ClustFinderNew()\n{\n fMatch = 4;\n fThreshold =10;\n fDeconvPad = kTRUE;\n fDeconvTime = kTRUE;\n}\n\nAliL3ClustFinderNew::~AliL3ClustFinderNew()\n{\n\n\n}\n\nvoid AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t firstrow, Int_t lastrow,Int_t nmaxpoints)\n{\n fNClusters = 0;\n fMaxNClusters = nmaxpoints;\n fCurrentSlice = slice;\n fCurrentPatch = patch;\n fFirstRow = firstrow;\n fLastRow = lastrow;\n fDeconvTime = kTRUE;\n fDeconvPad = kTRUE;\n}\n\nvoid AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t nmaxpoints)\n{\n fNClusters = 0;\n fMaxNClusters = nmaxpoints;\n fCurrentSlice = slice;\n fCurrentPatch = patch;\n}\n\nvoid AliL3ClustFinderNew::SetOutputArray(AliL3SpacePointData *pt)\n{\n \n fSpacePointData = pt;\n}\n\n\nvoid AliL3ClustFinderNew::Read(UInt_t ndigits,AliL3DigitRowData *ptr)\n{\n fNDigitRowData = ndigits;\n fDigitRowData = ptr;\n \n}\n\nvoid AliL3ClustFinderNew::ProcessDigits()\n{\n \/\/Loop over rows, and call processrow\n \n \n AliL3DigitRowData *tempPt = (AliL3DigitRowData*)fDigitRowData;\n \n for(Int_t i=fFirstRow; i<=fLastRow; i++)\n {\n fCurrentRow = i;\n ProcessRow(tempPt);\n Byte_t *tmp = (Byte_t*)tempPt;\n Int_t size = sizeof(AliL3DigitRowData) + tempPt->fNDigit*sizeof(AliL3DigitData);\n tmp += size;\n tempPt = (AliL3DigitRowData*)tmp;\n }\n LOG(AliL3Log::kInformational,\"AliL3ClustFinderNew::WriteClusters\",\"Space points\")\n <<\"Cluster finder found \"<<fNClusters<<\" clusters in slice \"<<fCurrentSlice\n <<\" patch \"<<fCurrentPatch<<ENDLOG;\n\n\n}\n\n\n\nvoid AliL3ClustFinderNew::ProcessRow(AliL3DigitRowData *tempPt)\n{\n\n UInt_t last_pad = 123456789;\n\n ClusterData *pad1[2500]; \/\/2 lists for internal memory=2pads\n ClusterData *pad2[2500]; \/\/2 lists for internal memory=2pads\n ClusterData clusterlist[5000]; \/\/Clusterlist\n\n ClusterData **currentPt; \/\/List of pointers to the current pad\n ClusterData **previousPt; \/\/List of pointers to the previous pad\n currentPt = pad2;\n previousPt = pad1;\n UInt_t n_previous=0,n_current=0,n_total=0;\n\n \/\/Loop over sequences of this row:\n for(UInt_t bin=0; bin<tempPt->fNDigit; bin++)\n {\n \n AliL3DigitData *data = tempPt->fDigitData;\n if(data[bin].fPad != last_pad)\n\t{\n\t \/\/This is a new pad\n\t \n\t \/\/Switch:\n\t if(currentPt == pad2)\n\t {\n\t currentPt = pad1;\n\t previousPt = pad2;\n\t \n\t }\n\t else \n\t {\n\t currentPt = pad2;\n\t previousPt = pad1;\n\t }\n\t n_previous = n_current;\n\t n_current = 0;\n\t if(bin[data].fPad != last_pad+1)\n\t {\n\t \/\/this happens if there is a pad with no signal.\n\t n_previous = n_current = 0;\n\t }\n\t last_pad = data[bin].fPad;\n\t}\n\n Bool_t new_cluster = kTRUE;\n\n UInt_t seq_charge=0,seq_average=0;\n \n UInt_t last_charge=0,last_was_falling=0;\n Int_t new_bin=-1;\n if(fDeconvTime)\n\t{\n\tredo: \/\/This is a goto.\n\t if(new_bin > -1)\n\t {\n\t bin = new_bin;\n\t new_bin = -1;\n\t }\n\t \n\t last_charge=0;\n\t last_was_falling = 0;\n\t}\n \n\n while(1) \/\/Loop over current sequence\n\t{\n\t if(data[bin].fTime >= AliL3Transform::GetNTimeBins())\n\t {\n\t LOG(AliL3Log::kFatal,\"AliL3ClustFinderNew::ProcessRow\",\"Digits\")\n\t\t<<\"Timebin out of range \"<<(Int_t)data[bin].fTime<<ENDLOG;\n\t break;\n\t }\n\n\t \/\/Get the current ADC-value\n\t UInt_t charge = data[bin].fCharge;\n\t \n\t if(fDeconvTime)\n\t {\n\t \/\/Check if the last pixel in the sequence is smaller than this\n\t if(charge > last_charge)\n\t\t{\n\t\t if(last_was_falling)\n\t\t {\n\t\t new_bin = bin;\n\t\t break;\n\t\t }\n\t\t}\n\t else last_was_falling = 1; \/\/last pixel was larger than this\n\t last_charge = charge;\n\t }\n\t \n\t \/\/Sum the total charge of this sequence\n\t seq_charge += charge;\n\t seq_average += data[bin].fTime*charge;\n\t \n\t \/\/Check where to stop:\n\t if(data[bin+1].fPad != data[bin].fPad) \/\/new pad\n\t break; \n\t if(data[bin+1].fTime != data[bin].fTime+1) \/\/end of sequence\n\t break;\n\t \n\t bin++;\n\t}\/\/end loop over sequence\n \n \/\/Calculate mean of sequence:\n Int_t seq_mean=0;\n if(seq_charge)\n\tseq_mean = seq_average\/seq_charge;\n else\n\t{\n\t LOG(AliL3Log::kFatal,\"AliL3ClustFinderNew::ProcessRow\",\"Data\")\n\t <<\"Error in data given to the cluster finder\"<<ENDLOG;\n\t seq_mean = 1;\n\t seq_charge = 1;\n\t}\n \n \/\/Calculate mean in pad direction:\n Int_t pad_mean = seq_charge*data[bin].fPad;\n\n \/\/Compare with results on previous pad:\n for(UInt_t p=0; p<n_previous; p++)\n\t{\n\t Int_t difference = seq_mean - previousPt[p]->fMean;\n\t if(difference < -fMatch)\n\t break;\n\n\t if(difference <= fMatch)\/\/There is a match here!!\n\t {\n\t \n\t ClusterData *local = previousPt[p];\n\t if(fDeconvPad)\n\t\t{\n\t\t if(seq_charge > local->fLastCharge)\n\t\t {\n\t\t if(local->fChargeFalling)\/\/The previous pad was falling\n\t\t\t{\t\t\t\n\t\t\t break;\/\/create a new cluster\n\t\t\t}\t\t \n\t\t }\n\t\t else\n\t\t local->fChargeFalling = 1;\n\t\t local->fLastCharge = seq_charge;\n\t\t}\n\t \n\t \/\/Don't create a new cluster, because we found a match\n\t new_cluster = kFALSE;\n\t \n\t \/\/Update cluster on current pad with the matching one:\n\t \/\/currentPt[n_current] = previousPt[p];\n\t \n\t local->fTotalCharge += seq_charge;\n\t local->fPad += pad_mean;\n\t local->fTime += seq_average;\n\t local->fMean = seq_mean;\n\t local->fFlags++; \/\/means we have more than one pad \n\t \n\t currentPt[n_current] = local;\n\t n_current++;\n\t \n\t break;\n\t }\/\/Checking for match at previous pad\n\t}\/\/Loop over results on previous pad.\n \n if(new_cluster)\n\t{\n\t \/\/Start a new cluster. Add it to the clusterlist, and update\n\t \/\/the list of pointers to clusters in current pad.\n\t \/\/current pad will be previous pad on next pad.\n\n\t \/\/Add to the clusterlist:\n\t ClusterData *tmp = &clusterlist[n_total];\n\t tmp->fTotalCharge = seq_charge;\n\t tmp->fPad = pad_mean;\n\t tmp->fTime = seq_average;\n\t tmp->fMean = seq_mean;\n\t tmp->fFlags = 0; \/\/flags for 1 pad clusters\n\t if(fDeconvPad)\n\t {\n\t tmp->fChargeFalling = 0;\n\t tmp->fLastCharge = seq_charge;\n\t }\n\n\t \/\/Update list of pointers to previous pad:\n\t currentPt[n_current] = &clusterlist[n_total];\n\t n_total++;\n\t n_current++;\n\t}\n if(fDeconvTime)\n\tif(new_bin >= 0) goto redo;\n \n }\/\/Loop over digits on this padrow\n \n WriteClusters(n_total,clusterlist);\n\n\n}\n\nvoid AliL3ClustFinderNew::WriteClusters(Int_t n_clusters,ClusterData *list)\n{\n Int_t thisrow,thissector;\n UInt_t counter = fNClusters;\n \n for(int j=0; j<n_clusters; j++)\n {\n if(!list[j].fFlags) continue; \/\/discard 1 pad clusters\n if(list[j].fTotalCharge < fThreshold) continue; \/\/noise cluster\n Float_t xyz[3];\n \n Float_t fpad=(Float_t)list[j].fPad\/(Float_t)list[j].fTotalCharge;\n Float_t ftime=(Float_t)list[j].fTime\/(Float_t)list[j].fTotalCharge;\n \/\/printf(\"padrow %d number of pads %d totalcharge %d\\n\",fCurrentRow,list[j].fFlags,list[j].fTotalCharge);\n AliL3Transform::Slice2Sector(fCurrentSlice,fCurrentRow,thissector,thisrow);\n AliL3Transform::Raw2Local(xyz,thissector,thisrow,fpad,ftime);\n if(xyz[0]==0) LOG(AliL3Log::kError,\"AliL3ClustFinder\",\"Cluster Finder\")\n\t<<AliL3Log::kDec<<\"Zero cluster\"<<ENDLOG;\n if(fNClusters >= fMaxNClusters)\n\t{\n\t LOG(AliL3Log::kError,\"AliL3ClustFinder::WriteClusters\",\"Cluster Finder\")\n\t <<AliL3Log::kDec<<\"Too many clusters\"<<ENDLOG;\n\t return;\n\t } \n fSpacePointData[counter].fCharge = list[j].fTotalCharge;\n fSpacePointData[counter].fX = xyz[0];\n fSpacePointData[counter].fY = xyz[1];\n fSpacePointData[counter].fZ = xyz[2];\n fSpacePointData[counter].fPadRow = fCurrentRow;\n fSpacePointData[counter].fXYErr = fXYErr;\n fSpacePointData[counter].fZErr = fZErr;\n fSpacePointData[counter].fID = counter\n\t+((fCurrentSlice&0x7f)<<25)+((fCurrentPatch&0x7)<<22);\/\/uli\n#ifdef do_mc\n Int_t trackID[3];\n GetTrackID((Int_t)rint(fpad),(Int_t)rint(ftime),trackID);\n \/\/cout<<\"padrow \"<<fCurrentRow<<\" pad \"<<(Int_t)rint(fpad)<<\" time \"<<(Int_t)rint(ftime)<<\" Trackid \"<<trackID[0]<<endl;\n fSpacePointData[counter].fTrackID[0] = trackID[0];\n fSpacePointData[counter].fTrackID[1] = trackID[1];\n fSpacePointData[counter].fTrackID[2] = trackID[2];\n#endif\n fNClusters++;\n counter++;\n\n }\n\n \n}\n\n#ifdef do_mc\nvoid AliL3ClustFinderNew::GetTrackID(Int_t pad,Int_t time,Int_t *trackID)\n{\n AliL3DigitRowData *rowPt = (AliL3DigitRowData*)fDigitRowData;\n \n trackID[0]=trackID[1]=trackID[2]=-2;\n \/\/cout<<\"Looking for pad \"<<pad<<\" time \"<<time<<endl;\n for(Int_t i=fFirstRow; i<=fLastRow; i++)\n {\n if(rowPt->fRow < (UInt_t)fCurrentRow)\n\t{\n\t AliL3MemHandler::UpdateRowPointer(rowPt);\n\t continue;\n\t}\n AliL3DigitData *digPt = (AliL3DigitData*)rowPt->fDigitData;\n for(UInt_t j=0; j<rowPt->fNDigit; j++)\n\t{\n\t Int_t cpad = digPt[j].fPad;\n\t Int_t ctime = digPt[j].fTime;\n\t if(cpad != pad) continue;\n\t if(ctime != time) continue;\n\t \/\/if(cpad != pad && ctime != ctime) continue;\n\t \/\/cout<<\"Reading row \"<<fCurrentRow<<\" pad \"<<cpad<<\" time \"<<ctime<<\" trackID \"<<digPt[j].fTrackID[0]<<endl;\n\t trackID[0] = digPt[j].fTrackID[0];\n\t trackID[1] = digPt[j].fTrackID[1];\n\t trackID[2] = digPt[j].fTrackID[2];\n\t break;\n\t \/\/cout<<\"Reading trackID \"<<trackID[0]<<endl;\n\t}\n break;\n }\n \n}\n#endif\n<commit_msg>Commented out cout in WriteClusters<commit_after>\/\/$Id$\n\n\/\/ Author: Anders Vestbo <mailto:vestbo@fi.uib.no>\n\/\/*-- Copyright © ASV \n\n#include <iostream.h>\n#include <math.h>\n#include \"AliL3Logging.h\"\n#include \"AliL3ClustFinderNew.h\"\n#include \"AliL3DigitData.h\"\n#include \"AliL3Transform.h\"\n#include \"AliL3SpacePointData.h\"\n#include \"AliL3MemHandler.h\"\n\n\/\/_____________________________________________________________\n\/\/ AliL3ClustFinderNew\n\/\/\n\/\/ The current cluster finder for HLT\n\/\/ Based on STAR L3\n\nClassImp(AliL3ClustFinderNew)\n\nAliL3ClustFinderNew::AliL3ClustFinderNew()\n{\n fMatch = 4;\n fThreshold =10;\n fDeconvPad = kTRUE;\n fDeconvTime = kTRUE;\n}\n\nAliL3ClustFinderNew::~AliL3ClustFinderNew()\n{\n\n\n}\n\nvoid AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t firstrow, Int_t lastrow,Int_t nmaxpoints)\n{\n fNClusters = 0;\n fMaxNClusters = nmaxpoints;\n fCurrentSlice = slice;\n fCurrentPatch = patch;\n fFirstRow = firstrow;\n fLastRow = lastrow;\n fDeconvTime = kTRUE;\n fDeconvPad = kTRUE;\n}\n\nvoid AliL3ClustFinderNew::InitSlice(Int_t slice,Int_t patch,Int_t nmaxpoints)\n{\n fNClusters = 0;\n fMaxNClusters = nmaxpoints;\n fCurrentSlice = slice;\n fCurrentPatch = patch;\n}\n\nvoid AliL3ClustFinderNew::SetOutputArray(AliL3SpacePointData *pt)\n{\n \n fSpacePointData = pt;\n}\n\n\nvoid AliL3ClustFinderNew::Read(UInt_t ndigits,AliL3DigitRowData *ptr)\n{\n fNDigitRowData = ndigits;\n fDigitRowData = ptr;\n \n}\n\nvoid AliL3ClustFinderNew::ProcessDigits()\n{\n \/\/Loop over rows, and call processrow\n \n \n AliL3DigitRowData *tempPt = (AliL3DigitRowData*)fDigitRowData;\n \n for(Int_t i=fFirstRow; i<=fLastRow; i++)\n {\n fCurrentRow = i;\n ProcessRow(tempPt);\n Byte_t *tmp = (Byte_t*)tempPt;\n Int_t size = sizeof(AliL3DigitRowData) + tempPt->fNDigit*sizeof(AliL3DigitData);\n tmp += size;\n tempPt = (AliL3DigitRowData*)tmp;\n }\n LOG(AliL3Log::kInformational,\"AliL3ClustFinderNew::WriteClusters\",\"Space points\")\n <<\"Cluster finder found \"<<fNClusters<<\" clusters in slice \"<<fCurrentSlice\n <<\" patch \"<<fCurrentPatch<<ENDLOG;\n}\n\nvoid AliL3ClustFinderNew::ProcessRow(AliL3DigitRowData *tempPt)\n{\n\n UInt_t last_pad = 123456789;\n\n ClusterData *pad1[2500]; \/\/2 lists for internal memory=2pads\n ClusterData *pad2[2500]; \/\/2 lists for internal memory=2pads\n ClusterData clusterlist[5000]; \/\/Clusterlist\n\n ClusterData **currentPt; \/\/List of pointers to the current pad\n ClusterData **previousPt; \/\/List of pointers to the previous pad\n currentPt = pad2;\n previousPt = pad1;\n UInt_t n_previous=0,n_current=0,n_total=0;\n\n \/\/Loop over sequences of this row:\n for(UInt_t bin=0; bin<tempPt->fNDigit; bin++)\n {\n \n AliL3DigitData *data = tempPt->fDigitData;\n if(data[bin].fPad != last_pad)\n\t{\n\t \/\/This is a new pad\n\t \n\t \/\/Switch:\n\t if(currentPt == pad2)\n\t {\n\t currentPt = pad1;\n\t previousPt = pad2;\n\t \n\t }\n\t else \n\t {\n\t currentPt = pad2;\n\t previousPt = pad1;\n\t }\n\t n_previous = n_current;\n\t n_current = 0;\n\t if(bin[data].fPad != last_pad+1)\n\t {\n\t \/\/this happens if there is a pad with no signal.\n\t n_previous = n_current = 0;\n\t }\n\t last_pad = data[bin].fPad;\n\t}\n\n Bool_t new_cluster = kTRUE;\n\n UInt_t seq_charge=0,seq_average=0;\n \n UInt_t last_charge=0,last_was_falling=0;\n Int_t new_bin=-1;\n if(fDeconvTime)\n\t{\n\tredo: \/\/This is a goto.\n\t if(new_bin > -1)\n\t {\n\t bin = new_bin;\n\t new_bin = -1;\n\t }\n\t \n\t last_charge=0;\n\t last_was_falling = 0;\n\t}\n \n\n while(1) \/\/Loop over current sequence\n\t{\n\t if(data[bin].fTime >= AliL3Transform::GetNTimeBins())\n\t {\n\t LOG(AliL3Log::kFatal,\"AliL3ClustFinderNew::ProcessRow\",\"Digits\")\n\t\t<<\"Timebin out of range \"<<(Int_t)data[bin].fTime<<ENDLOG;\n\t break;\n\t }\n\n\t \/\/Get the current ADC-value\n\t UInt_t charge = data[bin].fCharge;\n\t \n\t if(fDeconvTime)\n\t {\n\t \/\/Check if the last pixel in the sequence is smaller than this\n\t if(charge > last_charge)\n\t\t{\n\t\t if(last_was_falling)\n\t\t {\n\t\t new_bin = bin;\n\t\t break;\n\t\t }\n\t\t}\n\t else last_was_falling = 1; \/\/last pixel was larger than this\n\t last_charge = charge;\n\t }\n\t \n\t \/\/Sum the total charge of this sequence\n\t seq_charge += charge;\n\t seq_average += data[bin].fTime*charge;\n\t \n\t \/\/Check where to stop:\n\t if(data[bin+1].fPad != data[bin].fPad) \/\/new pad\n\t break; \n\t if(data[bin+1].fTime != data[bin].fTime+1) \/\/end of sequence\n\t break;\n\t \n\t bin++;\n\t}\/\/end loop over sequence\n \n \/\/Calculate mean of sequence:\n Int_t seq_mean=0;\n if(seq_charge)\n\tseq_mean = seq_average\/seq_charge;\n else\n\t{\n\t LOG(AliL3Log::kFatal,\"AliL3ClustFinderNew::ProcessRow\",\"Data\")\n\t <<\"Error in data given to the cluster finder\"<<ENDLOG;\n\t seq_mean = 1;\n\t seq_charge = 1;\n\t}\n \n \/\/Calculate mean in pad direction:\n Int_t pad_mean = seq_charge*data[bin].fPad;\n\n \/\/Compare with results on previous pad:\n for(UInt_t p=0; p<n_previous; p++)\n\t{\n\t Int_t difference = seq_mean - previousPt[p]->fMean;\n\t if(difference < -fMatch)\n\t break;\n\n\t if(difference <= fMatch)\/\/There is a match here!!\n\t {\n\t \n\t ClusterData *local = previousPt[p];\n\t if(fDeconvPad)\n\t\t{\n\t\t if(seq_charge > local->fLastCharge)\n\t\t {\n\t\t if(local->fChargeFalling)\/\/The previous pad was falling\n\t\t\t{\t\t\t\n\t\t\t break;\/\/create a new cluster\n\t\t\t}\t\t \n\t\t }\n\t\t else\n\t\t local->fChargeFalling = 1;\n\t\t local->fLastCharge = seq_charge;\n\t\t}\n\t \n\t \/\/Don't create a new cluster, because we found a match\n\t new_cluster = kFALSE;\n\t \n\t \/\/Update cluster on current pad with the matching one:\n\t \/\/currentPt[n_current] = previousPt[p];\n\t \n\t local->fTotalCharge += seq_charge;\n\t local->fPad += pad_mean;\n\t local->fTime += seq_average;\n\t local->fMean = seq_mean;\n\t local->fFlags++; \/\/means we have more than one pad \n\t \n\t currentPt[n_current] = local;\n\t n_current++;\n\t \n\t break;\n\t }\/\/Checking for match at previous pad\n\t}\/\/Loop over results on previous pad.\n \n if(new_cluster)\n\t{\n\t \/\/Start a new cluster. Add it to the clusterlist, and update\n\t \/\/the list of pointers to clusters in current pad.\n\t \/\/current pad will be previous pad on next pad.\n\n\t \/\/Add to the clusterlist:\n\t ClusterData *tmp = &clusterlist[n_total];\n\t tmp->fTotalCharge = seq_charge;\n\t tmp->fPad = pad_mean;\n\t tmp->fTime = seq_average;\n\t tmp->fMean = seq_mean;\n\t tmp->fFlags = 0; \/\/flags for 1 pad clusters\n\t if(fDeconvPad)\n\t {\n\t tmp->fChargeFalling = 0;\n\t tmp->fLastCharge = seq_charge;\n\t }\n\n\t \/\/Update list of pointers to previous pad:\n\t currentPt[n_current] = &clusterlist[n_total];\n\t n_total++;\n\t n_current++;\n\t}\n if(fDeconvTime)\n\tif(new_bin >= 0) goto redo;\n \n }\/\/Loop over digits on this padrow\n \n WriteClusters(n_total,clusterlist);\n}\n\nvoid AliL3ClustFinderNew::WriteClusters(Int_t n_clusters,ClusterData *list)\n{\n Int_t thisrow,thissector;\n UInt_t counter = fNClusters;\n \n for(int j=0; j<n_clusters; j++)\n {\n if(!list[j].fFlags) continue; \/\/discard 1 pad clusters\n if(list[j].fTotalCharge < fThreshold) continue; \/\/noise cluster\n\n Float_t xyz[3]; \n Float_t fpad=(Float_t)list[j].fPad\/(Float_t)list[j].fTotalCharge;\n Float_t ftime=(Float_t)list[j].fTime\/(Float_t)list[j].fTotalCharge;\n \/\/cout<<\"WriteCluster: padrow \"<<fCurrentRow<<\" pad \"<<fpad<<\" time \"<<ftime<<\" charge \"<<list[j].fTotalCharge<<endl;\n\n \/\/printf(\"padrow %d number of pads %d totalcharge %d\\n\",fCurrentRow,list[j].fFlags,list[j].fTotalCharge);\n AliL3Transform::Slice2Sector(fCurrentSlice,fCurrentRow,thissector,thisrow);\n AliL3Transform::Raw2Local(xyz,thissector,thisrow,fpad,ftime);\n if(xyz[0]==0) LOG(AliL3Log::kError,\"AliL3ClustFinder\",\"Cluster Finder\")\n\t<<AliL3Log::kDec<<\"Zero cluster\"<<ENDLOG;\n if(fNClusters >= fMaxNClusters)\n\t{\n\t LOG(AliL3Log::kError,\"AliL3ClustFinder::WriteClusters\",\"Cluster Finder\")\n\t <<AliL3Log::kDec<<\"Too many clusters\"<<ENDLOG;\n\t return;\n\t} \n fSpacePointData[counter].fCharge = list[j].fTotalCharge;\n fSpacePointData[counter].fX = xyz[0];\n fSpacePointData[counter].fY = xyz[1];\n fSpacePointData[counter].fZ = xyz[2];\n fSpacePointData[counter].fPadRow = fCurrentRow;\n fSpacePointData[counter].fXYErr = fXYErr;\n fSpacePointData[counter].fZErr = fZErr;\n fSpacePointData[counter].fID = counter\n\t+((fCurrentSlice&0x7f)<<25)+((fCurrentPatch&0x7)<<22);\/\/Uli\n#ifdef do_mc\n Int_t trackID[3];\n GetTrackID((Int_t)rint(fpad),(Int_t)rint(ftime),trackID);\n \/\/cout<<\"padrow \"<<fCurrentRow<<\" pad \"<<(Int_t)rint(fpad)<<\" time \"<<(Int_t)rint(ftime)<<\" Trackid \"<<trackID[0]<<endl;\n fSpacePointData[counter].fTrackID[0] = trackID[0];\n fSpacePointData[counter].fTrackID[1] = trackID[1];\n fSpacePointData[counter].fTrackID[2] = trackID[2];\n#endif\n fNClusters++;\n counter++;\n }\n}\n\n#ifdef do_mc\nvoid AliL3ClustFinderNew::GetTrackID(Int_t pad,Int_t time,Int_t *trackID)\n{\n AliL3DigitRowData *rowPt = (AliL3DigitRowData*)fDigitRowData;\n \n trackID[0]=trackID[1]=trackID[2]=-2;\n \/\/cout<<\"Looking for pad \"<<pad<<\" time \"<<time<<endl;\n for(Int_t i=fFirstRow; i<=fLastRow; i++)\n {\n if(rowPt->fRow < (UInt_t)fCurrentRow)\n\t{\n\t AliL3MemHandler::UpdateRowPointer(rowPt);\n\t continue;\n\t}\n AliL3DigitData *digPt = (AliL3DigitData*)rowPt->fDigitData;\n for(UInt_t j=0; j<rowPt->fNDigit; j++)\n\t{\n\t Int_t cpad = digPt[j].fPad;\n\t Int_t ctime = digPt[j].fTime;\n\t if(cpad != pad) continue;\n\t if(ctime != time) continue;\n\t \/\/if(cpad != pad && ctime != ctime) continue;\n\t \/\/cout<<\"Reading row \"<<fCurrentRow<<\" pad \"<<cpad<<\" time \"<<ctime<<\" trackID \"<<digPt[j].fTrackID[0]<<endl;\n\t trackID[0] = digPt[j].fTrackID[0];\n\t trackID[1] = digPt[j].fTrackID[1];\n\t trackID[2] = digPt[j].fTrackID[2];\n\t break;\n\t \/\/cout<<\"Reading trackID \"<<trackID[0]<<endl;\n\t}\n break;\n }\n \n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- clang-wpa.cpp - clang whole program analyzer ---------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tool reads a sequence of precompiled AST files, and do various\n\/\/ cross translation unit analyses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Index\/CallGraph.h\"\n#include \"llvm\/ADT\/IntrusiveRefCntPtr.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\nusing namespace idx;\n\nstatic llvm::cl::list<std::string>\nInputFilenames(llvm::cl::Positional, llvm::cl::desc(\"<input AST files>\"));\n\nstatic llvm::cl::opt<bool> \nViewCallGraph(\"view-call-graph\", llvm::cl::desc(\"Display the call graph.\"));\n\nstatic llvm::cl::opt<std::string>\nAnalyzeFunction(\"analyze-function\", \n llvm::cl::desc(\"Specify the entry function.\"));\n\nint main(int argc, char **argv) {\n llvm::cl::ParseCommandLineOptions(argc, argv, \"clang-wpa\");\n FileManager FileMgr;\n std::vector<ASTUnit*> ASTUnits;\n\n Program Prog;\n\n if (InputFilenames.empty())\n return 0;\n\n DiagnosticOptions DiagOpts;\n llvm::IntrusiveRefCntPtr<Diagnostic> Diags\n = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);\n for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {\n const std::string &InFile = InputFilenames[i];\n llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));\n if (!AST)\n return 1;\n\n ASTUnits.push_back(AST.take());\n }\n\n if (ViewCallGraph) {\n llvm::OwningPtr<CallGraph> CG;\n CG.reset(new CallGraph(Prog));\n\n for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)\n CG->addTU(ASTUnits[i]->getASTContext());\n\n CG->ViewCallGraph();\n return 0;\n }\n\n if (AnalyzeFunction.empty())\n return 0;\n\n llvm::outs() << \"Analyze function: \" << AnalyzeFunction << '\\n';\n return 0;\n}\n<commit_msg>Create a ASTUnitTU class to interface ASTUnit to the Indexer.<commit_after>\/\/===--- clang-wpa.cpp - clang whole program analyzer ---------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tool reads a sequence of precompiled AST files, and do various\n\/\/ cross translation unit analyses.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Index\/CallGraph.h\"\n#include \"clang\/Index\/Indexer.h\"\n#include \"clang\/Index\/TranslationUnit.h\"\n#include \"clang\/Index\/DeclReferenceMap.h\"\n#include \"clang\/Index\/SelectorMap.h\"\n#include \"llvm\/ADT\/IntrusiveRefCntPtr.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace clang;\nusing namespace idx;\n\nstatic llvm::cl::list<std::string>\nInputFilenames(llvm::cl::Positional, llvm::cl::desc(\"<input AST files>\"));\n\nstatic llvm::cl::opt<bool> \nViewCallGraph(\"view-call-graph\", llvm::cl::desc(\"Display the call graph.\"));\n\nstatic llvm::cl::opt<std::string>\nAnalyzeFunction(\"analyze-function\", \n llvm::cl::desc(\"Specify the entry function.\"));\n\nnamespace {\n\/\/ A thin wrapper over ASTUnit implementing the TranslationUnit interface.\nclass ASTUnitTU : public TranslationUnit {\n ASTUnit *AST;\n DeclReferenceMap DeclRefMap;\n SelectorMap SelMap;\n \npublic:\n ASTUnitTU(ASTUnit *ast) \n : AST(ast), DeclRefMap(AST->getASTContext()), SelMap(AST->getASTContext()) {\n }\n\n virtual ASTContext &getASTContext() {\n return AST->getASTContext();\n }\n\n virtual DeclReferenceMap &getDeclReferenceMap() {\n return DeclRefMap;\n }\n\n virtual SelectorMap &getSelectorMap() {\n return SelMap;\n }\n};\n}\n\nint main(int argc, char **argv) {\n llvm::cl::ParseCommandLineOptions(argc, argv, \"clang-wpa\");\n std::vector<ASTUnit*> ASTUnits;\n\n Program Prog;\n Indexer Idxer(Prog);\n\n if (InputFilenames.empty())\n return 0;\n\n DiagnosticOptions DiagOpts;\n llvm::IntrusiveRefCntPtr<Diagnostic> Diags\n = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);\n for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {\n const std::string &InFile = InputFilenames[i];\n llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));\n if (!AST)\n return 1;\n\n ASTUnits.push_back(AST.take());\n }\n\n if (ViewCallGraph) {\n llvm::OwningPtr<CallGraph> CG;\n CG.reset(new CallGraph(Prog));\n\n for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)\n CG->addTU(ASTUnits[i]->getASTContext());\n\n CG->ViewCallGraph();\n return 0;\n }\n\n if (AnalyzeFunction.empty())\n return 0;\n\n \/\/ Feed all ASTUnits to the Indexer.\n for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i) {\n ASTUnitTU TU(ASTUnits[i]);\n Idxer.IndexAST(&TU);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include \"xbyak\/xbyak_util.h\"\n\n#define NUM_OF_ARRAY(x) (sizeof(x) \/ sizeof(x[0]))\n\nstruct PopCountTest : public Xbyak::CodeGenerator {\n\tPopCountTest(int n)\n\t\t: Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE)\n\t{\n\t\tmov(eax, n);\n\t\tpopcnt(eax, eax);\n\t\tret();\n\t}\n};\n\nvoid putCPUinfo(bool onlyCpuidFeature)\n{\n\tusing namespace Xbyak::util;\n\tCpu cpu;\n\tprintf(\"vendor %s\\n\", cpu.has(Cpu::tINTEL) ? \"intel\" : \"amd\");\n\tstatic const struct {\n\t\tCpu::Type type;\n\t\tconst char *str;\n\t} tbl[] = {\n\t\t{ Cpu::tMMX, \"mmx\" },\n\t\t{ Cpu::tMMX2, \"mmx2\" },\n\t\t{ Cpu::tCMOV, \"cmov\" },\n\t\t{ Cpu::tSSE, \"sse\" },\n\t\t{ Cpu::tSSE2, \"sse2\" },\n\t\t{ Cpu::tSSE3, \"sse3\" },\n\t\t{ Cpu::tSSSE3, \"ssse3\" },\n\t\t{ Cpu::tSSE41, \"sse41\" },\n\t\t{ Cpu::tSSE42, \"sse42\" },\n\t\t{ Cpu::tPOPCNT, \"popcnt\" },\n\t\t{ Cpu::t3DN, \"3dn\" },\n\t\t{ Cpu::tE3DN, \"e3dn\" },\n\t\t{ Cpu::tAESNI, \"aesni\" },\n\t\t{ Cpu::tRDTSCP, \"rdtscp\" },\n\t\t{ Cpu::tOSXSAVE, \"osxsave(xgetvb)\" },\n\t\t{ Cpu::tPCLMULQDQ, \"pclmulqdq\" },\n\t\t{ Cpu::tAVX, \"avx\" },\n\t\t{ Cpu::tFMA, \"fma\" },\n\t\t{ Cpu::tAVX2, \"avx2\" },\n\t\t{ Cpu::tBMI1, \"bmi1\" },\n\t\t{ Cpu::tBMI2, \"bmi2\" },\n\t\t{ Cpu::tLZCNT, \"lzcnt\" },\n\t\t{ Cpu::tPREFETCHW, \"prefetchw\" },\n\t\t{ Cpu::tENHANCED_REP, \"enh_rep\" },\n\t\t{ Cpu::tRDRAND, \"rdrand\" },\n\t\t{ Cpu::tADX, \"adx\" },\n\t\t{ Cpu::tRDSEED, \"rdseed\" },\n\t\t{ Cpu::tSMAP, \"smap\" },\n\t\t{ Cpu::tHLE, \"hle\" },\n\t\t{ Cpu::tRTM, \"rtm\" },\n\t\t{ Cpu::tMPX, \"mpx\" },\n\t\t{ Cpu::tSHA, \"sha\" },\n\t\t{ Cpu::tPREFETCHWT1, \"prefetchwt1\" },\n\t\t{ Cpu::tF16C, \"f16c\" },\n\t\t{ Cpu::tMOVBE, \"movbe\" },\n\t\t{ Cpu::tAVX512F, \"avx512f\" },\n\t\t{ Cpu::tAVX512DQ, \"avx512dq\" },\n\t\t{ Cpu::tAVX512IFMA, \"avx512_ifma\" },\n\t\t{ Cpu::tAVX512PF, \"avx512pf\" },\n\t\t{ Cpu::tAVX512ER, \"avx512er\" },\n\t\t{ Cpu::tAVX512CD, \"avx512cd\" },\n\t\t{ Cpu::tAVX512BW, \"avx512bw\" },\n\t\t{ Cpu::tAVX512VL, \"avx512vl\" },\n\t\t{ Cpu::tAVX512VBMI, \"avx512_vbmi\" },\n\t\t{ Cpu::tAVX512_4VNNIW, \"avx512_4vnniw\" },\n\t\t{ Cpu::tAVX512_4FMAPS, \"avx512_4fmaps\" },\n\n\t\t{ Cpu::tAVX512_VBMI2, \"avx512_vbmi2\" },\n\t\t{ Cpu::tGFNI, \"gfni\" },\n\t\t{ Cpu::tVAES, \"vaes\" },\n\t\t{ Cpu::tVPCLMULQDQ, \"vpclmulqdq\" },\n\t\t{ Cpu::tAVX512_VNNI, \"avx512_vnni\" },\n\t\t{ Cpu::tAVX512_BITALG, \"avx512_bitalg\" },\n\t\t{ Cpu::tAVX512_VPOPCNTDQ, \"avx512_vpopcntdq\" },\n\t\t{ Cpu::tAVX512_BF16, \"avx512_bf16\" },\n\t\t{ Cpu::tAVX512_VP2INTERSECT, \"avx512_vp2intersect\" },\n\t\t{ Cpu::tAMX_TILE, \"amx(tile)\" },\n\t\t{ Cpu::tAMX_INT8, \"amx(int8)\" },\n\t\t{ Cpu::tAMX_BF16, \"amx(bf16)\" },\n\t\t{ Cpu::tAVX_VNNI, \"avx_vnni\" },\n\t\t{ Cpu::tAVX512_FP16, \"avx512_fp16\" },\n\t\t{ Cpu::tWAITPKG, \"waitpkg\" },\n\t\t{ Cpu::tCLFLUSHOPT, \"clflushopt\" },\n\t\t{ Cpu::tCLDEMOTE, \"cldemote\" },\n\t\t{ Cpu::tMOVDIRI, \"movdiri\" },\n\t\t{ Cpu::tMOVDIR64B, \"movdir64b\" },\n\t\t{ Cpu::tCLZERO, \"clzero\" },\n\t};\n\tfor (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {\n\t\tif (cpu.has(tbl[i].type)) printf(\" %s\", tbl[i].str);\n\t}\n\tprintf(\"\\n\");\n\tif (onlyCpuidFeature) return;\n\tif (cpu.has(Cpu::tPOPCNT)) {\n\t\tconst int n = 0x12345678; \/\/ bitcount = 13\n\t\tconst int ok = 13;\n\t\tPopCountTest code(n);\n\t\tcode.setProtectModeRE();\n\t\tint (*f)() = code.getCode<int (*)()>();\n\t\tint r = f();\n\t\tif (r == ok) {\n\t\t\tputs(\"popcnt ok\");\n\t\t} else {\n\t\t\tprintf(\"popcnt ng %d %d\\n\", r, ok);\n\t\t}\n\t\tcode.setProtectModeRW();\n\t}\n\t\/*\n\t\t displayFamily displayModel\n\t\tOpteron 2376 10 4\n\t\tCore2 Duo T7100 6 F\n\t\tCore i3-2120T 6 2A\n\t\tCore i7-2600 6 2A\n\t\tXeon X5650 6 2C\n\t\tCore i7-3517 6 3A\n\t\tCore i7-3930K 6 2D\n\t*\/\n\tcpu.putFamily();\n\tif (!cpu.has(Cpu::tINTEL)) return;\n\tfor (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) {\n\t\tprintf(\"cache level=%u data cache size=%u cores sharing data cache=%u\\n\", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i));\n\t}\n\tprintf(\"SmtLevel =%u\\n\", cpu.getNumCores(Xbyak::util::SmtLevel));\n\tprintf(\"CoreLevel=%u\\n\", cpu.getNumCores(Xbyak::util::CoreLevel));\n}\n\nint main(int argc, char *argv[])\n{\n\tbool onlyCpuidFeature = argc == 2 && strcmp(argv[1], \"-cpuid\") == 0;\n\tif (!onlyCpuidFeature) {\n#ifdef XBYAK32\n\t\tputs(\"32bit\");\n#else\n\t\tputs(\"64bit\");\n#endif\n\t}\n\tputCPUinfo(onlyCpuidFeature);\n}\n<commit_msg>[sample] show AMX_FP16\/AVX_VNNI_INT8\/AVX_NE_CONVERT<commit_after>#include <stdio.h>\n#include \"xbyak\/xbyak_util.h\"\n\n#define NUM_OF_ARRAY(x) (sizeof(x) \/ sizeof(x[0]))\n\nstruct PopCountTest : public Xbyak::CodeGenerator {\n\tPopCountTest(int n)\n\t\t: Xbyak::CodeGenerator(4096, Xbyak::DontSetProtectRWE)\n\t{\n\t\tmov(eax, n);\n\t\tpopcnt(eax, eax);\n\t\tret();\n\t}\n};\n\nvoid putCPUinfo(bool onlyCpuidFeature)\n{\n\tusing namespace Xbyak::util;\n\tCpu cpu;\n\tprintf(\"vendor %s\\n\", cpu.has(Cpu::tINTEL) ? \"intel\" : \"amd\");\n\tstatic const struct {\n\t\tCpu::Type type;\n\t\tconst char *str;\n\t} tbl[] = {\n\t\t{ Cpu::tMMX, \"mmx\" },\n\t\t{ Cpu::tMMX2, \"mmx2\" },\n\t\t{ Cpu::tCMOV, \"cmov\" },\n\t\t{ Cpu::tSSE, \"sse\" },\n\t\t{ Cpu::tSSE2, \"sse2\" },\n\t\t{ Cpu::tSSE3, \"sse3\" },\n\t\t{ Cpu::tSSSE3, \"ssse3\" },\n\t\t{ Cpu::tSSE41, \"sse41\" },\n\t\t{ Cpu::tSSE42, \"sse42\" },\n\t\t{ Cpu::tPOPCNT, \"popcnt\" },\n\t\t{ Cpu::t3DN, \"3dn\" },\n\t\t{ Cpu::tE3DN, \"e3dn\" },\n\t\t{ Cpu::tAESNI, \"aesni\" },\n\t\t{ Cpu::tRDTSCP, \"rdtscp\" },\n\t\t{ Cpu::tOSXSAVE, \"osxsave(xgetvb)\" },\n\t\t{ Cpu::tPCLMULQDQ, \"pclmulqdq\" },\n\t\t{ Cpu::tAVX, \"avx\" },\n\t\t{ Cpu::tFMA, \"fma\" },\n\t\t{ Cpu::tAVX2, \"avx2\" },\n\t\t{ Cpu::tBMI1, \"bmi1\" },\n\t\t{ Cpu::tBMI2, \"bmi2\" },\n\t\t{ Cpu::tLZCNT, \"lzcnt\" },\n\t\t{ Cpu::tPREFETCHW, \"prefetchw\" },\n\t\t{ Cpu::tENHANCED_REP, \"enh_rep\" },\n\t\t{ Cpu::tRDRAND, \"rdrand\" },\n\t\t{ Cpu::tADX, \"adx\" },\n\t\t{ Cpu::tRDSEED, \"rdseed\" },\n\t\t{ Cpu::tSMAP, \"smap\" },\n\t\t{ Cpu::tHLE, \"hle\" },\n\t\t{ Cpu::tRTM, \"rtm\" },\n\t\t{ Cpu::tMPX, \"mpx\" },\n\t\t{ Cpu::tSHA, \"sha\" },\n\t\t{ Cpu::tPREFETCHWT1, \"prefetchwt1\" },\n\t\t{ Cpu::tF16C, \"f16c\" },\n\t\t{ Cpu::tMOVBE, \"movbe\" },\n\t\t{ Cpu::tAVX512F, \"avx512f\" },\n\t\t{ Cpu::tAVX512DQ, \"avx512dq\" },\n\t\t{ Cpu::tAVX512IFMA, \"avx512_ifma\" },\n\t\t{ Cpu::tAVX512PF, \"avx512pf\" },\n\t\t{ Cpu::tAVX512ER, \"avx512er\" },\n\t\t{ Cpu::tAVX512CD, \"avx512cd\" },\n\t\t{ Cpu::tAVX512BW, \"avx512bw\" },\n\t\t{ Cpu::tAVX512VL, \"avx512vl\" },\n\t\t{ Cpu::tAVX512VBMI, \"avx512_vbmi\" },\n\t\t{ Cpu::tAVX512_4VNNIW, \"avx512_4vnniw\" },\n\t\t{ Cpu::tAVX512_4FMAPS, \"avx512_4fmaps\" },\n\n\t\t{ Cpu::tAVX512_VBMI2, \"avx512_vbmi2\" },\n\t\t{ Cpu::tGFNI, \"gfni\" },\n\t\t{ Cpu::tVAES, \"vaes\" },\n\t\t{ Cpu::tVPCLMULQDQ, \"vpclmulqdq\" },\n\t\t{ Cpu::tAVX512_VNNI, \"avx512_vnni\" },\n\t\t{ Cpu::tAVX512_BITALG, \"avx512_bitalg\" },\n\t\t{ Cpu::tAVX512_VPOPCNTDQ, \"avx512_vpopcntdq\" },\n\t\t{ Cpu::tAVX512_BF16, \"avx512_bf16\" },\n\t\t{ Cpu::tAVX512_VP2INTERSECT, \"avx512_vp2intersect\" },\n\t\t{ Cpu::tAMX_TILE, \"amx(tile)\" },\n\t\t{ Cpu::tAMX_INT8, \"amx(int8)\" },\n\t\t{ Cpu::tAMX_BF16, \"amx(bf16)\" },\n\t\t{ Cpu::tAVX_VNNI, \"avx_vnni\" },\n\t\t{ Cpu::tAVX512_FP16, \"avx512_fp16\" },\n\t\t{ Cpu::tWAITPKG, \"waitpkg\" },\n\t\t{ Cpu::tCLFLUSHOPT, \"clflushopt\" },\n\t\t{ Cpu::tCLDEMOTE, \"cldemote\" },\n\t\t{ Cpu::tMOVDIRI, \"movdiri\" },\n\t\t{ Cpu::tMOVDIR64B, \"movdir64b\" },\n\t\t{ Cpu::tCLZERO, \"clzero\" },\n\t\t{ Cpu::tAMX_FP16, \"amx_fp16\" },\n\t\t{ Cpu::tAVX_VNNI_INT8, \"avx_vnni_int8\" },\n\t\t{ Cpu::tAVX_NE_CONVERT, \"avx_ne_convert\" },\n\t};\n\tfor (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {\n\t\tif (cpu.has(tbl[i].type)) printf(\" %s\", tbl[i].str);\n\t}\n\tprintf(\"\\n\");\n\tif (onlyCpuidFeature) return;\n\tif (cpu.has(Cpu::tPOPCNT)) {\n\t\tconst int n = 0x12345678; \/\/ bitcount = 13\n\t\tconst int ok = 13;\n\t\tPopCountTest code(n);\n\t\tcode.setProtectModeRE();\n\t\tint (*f)() = code.getCode<int (*)()>();\n\t\tint r = f();\n\t\tif (r == ok) {\n\t\t\tputs(\"popcnt ok\");\n\t\t} else {\n\t\t\tprintf(\"popcnt ng %d %d\\n\", r, ok);\n\t\t}\n\t\tcode.setProtectModeRW();\n\t}\n\t\/*\n\t\t displayFamily displayModel\n\t\tOpteron 2376 10 4\n\t\tCore2 Duo T7100 6 F\n\t\tCore i3-2120T 6 2A\n\t\tCore i7-2600 6 2A\n\t\tXeon X5650 6 2C\n\t\tCore i7-3517 6 3A\n\t\tCore i7-3930K 6 2D\n\t*\/\n\tcpu.putFamily();\n\tif (!cpu.has(Cpu::tINTEL)) return;\n\tfor (unsigned int i = 0; i < cpu.getDataCacheLevels(); i++) {\n\t\tprintf(\"cache level=%u data cache size=%u cores sharing data cache=%u\\n\", i, cpu.getDataCacheSize(i), cpu.getCoresSharingDataCache(i));\n\t}\n\tprintf(\"SmtLevel =%u\\n\", cpu.getNumCores(Xbyak::util::SmtLevel));\n\tprintf(\"CoreLevel=%u\\n\", cpu.getNumCores(Xbyak::util::CoreLevel));\n}\n\nint main(int argc, char *argv[])\n{\n\tbool onlyCpuidFeature = argc == 2 && strcmp(argv[1], \"-cpuid\") == 0;\n\tif (!onlyCpuidFeature) {\n#ifdef XBYAK32\n\t\tputs(\"32bit\");\n#else\n\t\tputs(\"64bit\");\n#endif\n\t}\n\tputCPUinfo(onlyCpuidFeature);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ \n\/\/ Copyright 2013 Jeff Bush\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ \n\n#include \"Debug.h\"\n#include \"RenderTarget.h\"\n#include \"ParameterInterpolator.h\"\n#include \"Rasterizer.h\"\n#include \"PixelShader.h\"\n#include \"utils.h\"\n\n\n#define COLOR_SHADER 1\n\nconst int kMaxTileIndex = (640 \/ 64) * ((480 \/ 64) + 1);\nint nextTileIndex = 0;\n\nstruct Vertex\n{\n\tfloat coord[3];\n\tfloat params[kMaxParams];\n};\n\nclass ColorShader : public PixelShader\n{\npublic:\n\tColorShader(ParameterInterpolator *interp, RenderTarget *target)\n\t\t:\tPixelShader(interp, target)\n\t{}\n\t\n\tvirtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\t\tunsigned short mask);\n};\n\nvoid ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\tunsigned short mask)\n{\n\tfor (int i = 0; i < 3; i++)\n\t\toutParams[i] = inParams[i];\n}\n\nclass CheckerboardShader : public PixelShader\n{\npublic:\n\tCheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)\n\t\t:\tPixelShader(interp, target)\n\t{}\n\t\n\tvirtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\t\tunsigned short mask);\n};\n\nvoid CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\tunsigned short mask)\n{\n\tveci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0))) \n\t\t>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);\n\tveci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0))) \n\t\t>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);\n\n\tveci16 color = u ^ v;\n\t\n\toutParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);\n}\n\nconst int kFbWidth = 640;\nconst int kFbHeight = 480;\n\n\/\/\n\/\/ All threads start execution here\n\/\/\nint main()\n{\n\tRasterizer rasterizer;\n\tRenderTarget renderTarget(0x100000, kFbWidth, kFbHeight);\n\tParameterInterpolator interp(kFbWidth, kFbHeight);\n#if COLOR_SHADER\n\tColorShader shader(&interp, &renderTarget);\n#else\n\tCheckerboardShader shader(&interp, &renderTarget);\n#endif\n\n\tVertex vertices[3] = {\n#if COLOR_SHADER\n\t\t{ { 0.3, 0.1, 0.5 }, { 1.0, 0.0, 0.0 } },\n\t\t{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },\n\t\t{ { 0.1, 0.9, 0.3 }, { 0.0, 0.0, 1.0 } },\n#else\n\t\t{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },\n\t\t{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },\n\t\t{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },\n#endif\n\t};\n\n\twhile (nextTileIndex < kMaxTileIndex)\n\t{\n\t\t\/\/ Grab the next available tile to begin working on.\n\t\tint myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);\n\t\tif (myTileIndex >= kMaxTileIndex)\n\t\t\tbreak;\n\t\n\t\tunsigned int tileX, tileY;\n\t\tudiv(myTileIndex, 10, tileY, tileX);\n\n\t\tinterp.setUpTriangle(\n\t\t\tvertices[0].coord[0], vertices[0].coord[1], vertices[0].coord[2],\n\t\t\tvertices[1].coord[0], vertices[1].coord[1], vertices[1].coord[2],\n\t\t\tvertices[2].coord[0], vertices[2].coord[1], vertices[2].coord[2]);\n\n\t\tfor (int param = 0; param < 3; param++)\n\t\t{\n\t\t\tinterp.setUpParam(param, vertices[0].params[param],\n\t\t\t\tvertices[1].params[param], vertices[2].params[param]);\n\t\t}\n\n\t\t\/\/ Fill a 64x64 tile\n\t\trasterizer.rasterizeTriangle(&shader, tileX * 64, tileY * 64,\n\t\t\t(int)(vertices[0].coord[0] * kFbWidth), \n\t\t\t(int)(vertices[0].coord[1] * kFbHeight), \n\t\t\t(int)(vertices[1].coord[0] * kFbWidth), \n\t\t\t(int)(vertices[1].coord[1] * kFbHeight), \n\t\t\t(int)(vertices[2].coord[0] * kFbWidth), \n\t\t\t(int)(vertices[2].coord[1] * kFbHeight));\n\t}\n\t\t\n\treturn 0;\n}\n\nDebug Debug::debug;\n<commit_msg>Update to use shared geometry buffer<commit_after>\/\/ \n\/\/ Copyright 2013 Jeff Bush\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ \n\n#include \"Debug.h\"\n#include \"RenderTarget.h\"\n#include \"ParameterInterpolator.h\"\n#include \"Rasterizer.h\"\n#include \"PixelShader.h\"\n#include \"utils.h\"\n\n\n#define COLOR_SHADER 0\n\nconst int kMaxTileIndex = (640 \/ 64) * ((480 \/ 64) + 1);\nint nextTileIndex = 0;\n\nstruct Vertex\n{\n\tfloat coord[3];\n\tfloat params[kMaxParams];\n};\n\nclass ColorShader : public PixelShader\n{\npublic:\n\tColorShader(ParameterInterpolator *interp, RenderTarget *target)\n\t\t:\tPixelShader(interp, target)\n\t{}\n\t\n\tvirtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\t\tunsigned short mask);\n};\n\nvoid ColorShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\tunsigned short mask)\n{\n\tfor (int i = 0; i < 3; i++)\n\t\toutParams[i] = inParams[i];\n}\n\nclass CheckerboardShader : public PixelShader\n{\npublic:\n\tCheckerboardShader(ParameterInterpolator *interp, RenderTarget *target)\n\t\t:\tPixelShader(interp, target)\n\t{}\n\t\n\tvirtual void shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\t\tunsigned short mask);\n};\n\nvoid CheckerboardShader::shadePixels(const vecf16 inParams[16], vecf16 outParams[16],\n\tunsigned short mask)\n{\n\tveci16 u = ((__builtin_vp_vftoi(inParams[0] * __builtin_vp_makevectorf(65535.0))) \n\t\t>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);\n\tveci16 v = ((__builtin_vp_vftoi(inParams[1] * __builtin_vp_makevectorf(65535.0))) \n\t\t>> __builtin_vp_makevectori(10)) & __builtin_vp_makevectori(1);\n\n\tveci16 color = u ^ v;\n\t\n\toutParams[0] = outParams[1] = outParams[2] = __builtin_vp_vitof(color);\n}\n\nconst int kFbWidth = 640;\nconst int kFbHeight = 480;\n\n\/\/ Hard-coded for now. This normally would be generated during the geometry phase...\nVertex gVertices[3] = {\n#if COLOR_SHADER\n\t{ { 0.3, 0.1, 0.5 }, { 1.0, 0.0, 0.0 } },\n\t{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0, 0.0 } },\n\t{ { 0.1, 0.9, 0.3 }, { 0.0, 0.0, 1.0 } },\n#else\n\t{ { 0.3, 0.1, 0.6 }, { 0.0, 0.0 } },\n\t{ { 0.9, 0.5, 0.4 }, { 0.0, 1.0 } },\n\t{ { 0.1, 0.9, 0.1 }, { 1.0, 1.0 } },\n#endif\n};\n\nint gNumVertices = 1;\n\n\n\/\/\n\/\/ All threads start execution here\n\/\/\nint main()\n{\n\tRasterizer rasterizer;\n\tRenderTarget renderTarget(0x100000, kFbWidth, kFbHeight);\n\tParameterInterpolator interp(kFbWidth, kFbHeight);\n#if COLOR_SHADER\n\tColorShader shader(&interp, &renderTarget);\n#else\n\tCheckerboardShader shader(&interp, &renderTarget);\n#endif\n\n\twhile (nextTileIndex < kMaxTileIndex)\n\t{\n\t\t\/\/ Grab the next available tile to begin working on.\n\t\tint myTileIndex = __sync_fetch_and_add(&nextTileIndex, 1);\n\t\tif (myTileIndex >= kMaxTileIndex)\n\t\t\tbreak;\n\t\n\t\tunsigned int tileX, tileY;\n\t\tudiv(myTileIndex, 10, tileY, tileX);\n\n\t\t\/\/ Cycle through all triangles and attempt to render into this \n\t\t\/\/ 64x64 tile.\n\t\tfor (int vidx = 0; vidx < gNumVertices; vidx += 3)\n\t\t{\n\t\t\tVertex *vertex = &gVertices[vidx];\n\n\t\t\t\/\/ XXX could do some trivial rejections here for triangles that\n\t\t\t\/\/ obviously aren't in this tile.\n\t\t\n\t\t\tinterp.setUpTriangle(\n\t\t\t\tvertex[0].coord[0], vertex[0].coord[1], vertex[0].coord[2],\n\t\t\t\tvertex[1].coord[0], vertex[1].coord[1], vertex[1].coord[2],\n\t\t\t\tvertex[2].coord[0], vertex[2].coord[1], vertex[2].coord[2]);\n\n\t\t\tfor (int param = 0; param < 3; param++)\n\t\t\t{\n\t\t\t\tinterp.setUpParam(param, vertex[0].params[param],\n\t\t\t\t\tvertex[1].params[param], vertex[2].params[param]);\n\t\t\t}\n\n\t\t\trasterizer.rasterizeTriangle(&shader, tileX * 64, tileY * 64,\n\t\t\t\t(int)(vertex[0].coord[0] * kFbWidth), \n\t\t\t\t(int)(vertex[0].coord[1] * kFbHeight), \n\t\t\t\t(int)(vertex[1].coord[0] * kFbWidth), \n\t\t\t\t(int)(vertex[1].coord[1] * kFbHeight), \n\t\t\t\t(int)(vertex[2].coord[0] * kFbWidth), \n\t\t\t\t(int)(vertex[2].coord[1] * kFbHeight));\n\t\t}\n\t}\n\t\t\n\treturn 0;\n}\n\nDebug Debug::debug;\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/GL.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Texture.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/ImageCodec.h\"\n#include \"CEGUI\/DynamicModule.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ViewportTarget.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/GUIContext.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3FBOTextureTarget.h\"\n#include \"CEGUI\/System.h\"\n#include \"CEGUI\/DefaultResourceProvider.h\"\n#include \"CEGUI\/Logger.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3StateChangeWrapper.h\"\n#include \"CEGUI\/RenderMaterial.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GLBaseShaderWrapper.h\"\n\n#include <algorithm>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ The following are some GL extension \/ version dependant related items.\n\/\/ This is all done totally internally here; no need for external interface\n\/\/ to show any of this.\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ we only really need this with MSVC \/ Windows(?) and by now it should already\n\/\/ be defined on that platform, so we just define it as empty macro so the\n\/\/ compile does not break on other systems.\n#ifndef APIENTRY\n# define APIENTRY\n#endif\n\/\/! Dummy function for if real ones are not present (saves testing each render)\nstatic void APIENTRY activeTextureDummy(GLenum) {}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ template specialised class that does the real work for us\ntemplate<typename T>\nclass OGLTemplateTargetFactory : public OGLTextureTargetFactory\n{\n TextureTarget* create(OpenGLRendererBase& r) const\n { return new T(static_cast<OpenGL3Renderer&>(r)); }\n};\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n if (System::getSingletonPtr())\n throw InvalidRequestException(\n \"CEGUI::System object is already initialised.\");\n\n OpenGL3Renderer& renderer(create());\n DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider();\n System::create(renderer, rp);\n\n return renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const Sizef& display_size,\n const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n if (System::getSingletonPtr())\n throw InvalidRequestException(\n \"CEGUI::System object is already initialised.\");\n\n OpenGL3Renderer& renderer(create(display_size));\n DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider();\n System::create(renderer, rp);\n\n return renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::destroySystem()\n{\n System* sys;\n if (!(sys = System::getSingletonPtr()))\n throw InvalidRequestException(\n \"CEGUI::System object is not created or was already destroyed.\");\n\n OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(sys->getRenderer());\n DefaultResourceProvider* rp =\n static_cast<DefaultResourceProvider*>(sys->getResourceProvider());\n\n System::destroy();\n delete rp;\n destroy(*renderer);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::create(const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n return *new OpenGL3Renderer();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::create(const Sizef& display_size,\n const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n return *new OpenGL3Renderer(display_size);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::destroy(OpenGL3Renderer& renderer)\n{\n delete &renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::OpenGL3Renderer() :\n OpenGLRendererBase(true),\n d_shaderWrapperTextured(0),\n d_openGLStateChanger(0),\n d_shaderManager(0)\n{\n init();\n d_openGLStateChanger = new OpenGL3StateChangeWrapper();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::OpenGL3Renderer(const Sizef& display_size) :\n OpenGLRendererBase(display_size, true),\n d_shaderWrapperTextured(0),\n d_openGLStateChanger(0),\n d_shaderManager(0)\n{\n init();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::init()\n{\n if (OpenGLInfo::getSingleton().isUsingOpenglEs()\n && OpenGLInfo::getSingleton().verMajor() < 2)\n throw RendererException(\"Only version 2 and up of OpenGL ES is \"\n \"supported by this type of renderer.\");\n initialiseRendererIDString();\n d_openGLStateChanger = new OpenGL3StateChangeWrapper();\n initialiseTextureTargetFactory();\n initialiseOpenGLShaders();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::~OpenGL3Renderer()\n{\n delete d_textureTargetFactory;\n delete d_openGLStateChanger;\n delete d_shaderManager;\n\n delete d_shaderWrapperTextured;\n delete d_shaderWrapperSolid;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseRendererIDString()\n{\n d_rendererID = OpenGLInfo::getSingleton().isUsingDesktopOpengl()\n ? \"CEGUI::OpenGL3Renderer - Official OpenGL 3.2 core based \"\n \"renderer module.\"\n : \"CEGUI::OpenGL3Renderer - OpenGL ES 2 renderer module.\";\n}\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial)\n{\n return new OpenGL3GeometryBuffer(*this, renderMaterial);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nTextureTarget* OpenGL3Renderer::createTextureTarget_impl()\n{\n return d_textureTargetFactory->create(*this);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::beginRendering()\n{\n \/\/ Deprecated OpenGL 2 client states may mess up rendering. They are not added here\n \/\/ since they are deprecated and thus do not fit in a OpenGL Core renderer. However\n \/\/ this information may be relevant for people combining deprecated and modern\n \/\/ functions. In that case disable client states like this: glDisableClientState(GL_VERTEX_ARRAY);\n\n \n glEnable(GL_SCISSOR_TEST);\n glEnable(GL_BLEND);\n\n \/\/ force set blending ops to get to a known state.\n setupRenderingBlendMode(BM_NORMAL, true);\n\n \/\/ if enabled, restores a subset of the GL state back to default values.\n if (d_initExtraStates)\n setupExtraStates();\n\n d_openGLStateChanger->reset();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::endRendering()\n{\n glUseProgram(0);\n\n if (d_initExtraStates)\n {\n glDisable(GL_SCISSOR_TEST);\n \n glBlendFunc(GL_ONE, GL_ZERO);\n if (OpenGLInfo::getSingleton().isVaoSupported())\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::setupExtraStates()\n{\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n if (OpenGLInfo::getSingleton().isPolygonModeSupported())\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n\n glUseProgram(0);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseTextureTargetFactory()\n{\n \/\/Use OGL core implementation for FBOs\n d_rendererID += \" TextureTarget support enabled via FBO OGL 3.2 core implementation.\";\n d_textureTargetFactory = new OGLTemplateTargetFactory<OpenGL3FBOTextureTarget>;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode,\n const bool force)\n{\n \/\/ exit if mode is already set up (and update not forced)\n if ((d_activeBlendMode == mode) && !force)\n return;\n\n d_activeBlendMode = mode;\n\n if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)\n {\n d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n }\n else\n {\n d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nSizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz)\n{\n return Sizef(sz);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLBaseStateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger()\n{\n return d_openGLStateChanger;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseOpenGLShaders()\n{\n checkGLErrors();\n d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSL);\n d_shaderManager->initialiseShaders();\n\n initialiseStandardTexturedShaderWrapper();\n initialiseStandardColouredShaderWrapper();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRefCounted<RenderMaterial> OpenGL3Renderer::createRenderMaterial(const DefaultShaderType shaderType) const\n{\n if(shaderType == DS_TEXTURED)\n {\n RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperTextured));\n\n return render_material;\n }\n else if(shaderType == DS_SOLID)\n {\n RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperSolid));\n\n return render_material;\n }\n else\n {\n throw RendererException(\n \"A default shader of this type does not exist.\");\n\n return RefCounted<RenderMaterial>();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseStandardTexturedShaderWrapper()\n{\n OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED);\n d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger);\n\n d_shaderWrapperTextured->addTextureUniformVariable(\"texture0\", 0);\n\n d_shaderWrapperTextured->addUniformVariable(\"modelViewProjMatrix\");\n d_shaderWrapperTextured->addUniformVariable(\"alphaPercentage\");\n\n d_shaderWrapperTextured->addAttributeVariable(\"inPosition\");\n d_shaderWrapperTextured->addAttributeVariable(\"inTexCoord\");\n d_shaderWrapperTextured->addAttributeVariable(\"inColour\");\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseStandardColouredShaderWrapper()\n{\n OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID);\n d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger);\n\n d_shaderWrapperSolid->addUniformVariable(\"modelViewProjMatrix\");\n d_shaderWrapperSolid->addUniformVariable(\"alphaPercentage\");\n\n d_shaderWrapperSolid->addAttributeVariable(\"inPosition\");\n d_shaderWrapperSolid->addAttributeVariable(\"inColour\");\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLTexture* OpenGL3Renderer::createTexture_impl(const String& name)\n{\n return new OpenGL3Texture(*this, name);\n} \n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<commit_msg>FIX: Post-merge bug that resulted in FBOs not being rendered correctly<commit_after>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/GL.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ShaderManager.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Renderer.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3Texture.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/Shader.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/ImageCodec.h\"\n#include \"CEGUI\/DynamicModule.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/ViewportTarget.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3GeometryBuffer.h\"\n#include \"CEGUI\/GUIContext.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3FBOTextureTarget.h\"\n#include \"CEGUI\/System.h\"\n#include \"CEGUI\/DefaultResourceProvider.h\"\n#include \"CEGUI\/Logger.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GL3StateChangeWrapper.h\"\n#include \"CEGUI\/RenderMaterial.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GLBaseShaderWrapper.h\"\n\n#include <algorithm>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ The following are some GL extension \/ version dependant related items.\n\/\/ This is all done totally internally here; no need for external interface\n\/\/ to show any of this.\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ we only really need this with MSVC \/ Windows(?) and by now it should already\n\/\/ be defined on that platform, so we just define it as empty macro so the\n\/\/ compile does not break on other systems.\n#ifndef APIENTRY\n# define APIENTRY\n#endif\n\/\/! Dummy function for if real ones are not present (saves testing each render)\nstatic void APIENTRY activeTextureDummy(GLenum) {}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ template specialised class that does the real work for us\ntemplate<typename T>\nclass OGLTemplateTargetFactory : public OGLTextureTargetFactory\n{\n TextureTarget* create(OpenGLRendererBase& r) const\n { return new T(static_cast<OpenGL3Renderer&>(r)); }\n};\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n if (System::getSingletonPtr())\n throw InvalidRequestException(\n \"CEGUI::System object is already initialised.\");\n\n OpenGL3Renderer& renderer(create());\n DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider();\n System::create(renderer, rp);\n\n return renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const Sizef& display_size,\n const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n if (System::getSingletonPtr())\n throw InvalidRequestException(\n \"CEGUI::System object is already initialised.\");\n\n OpenGL3Renderer& renderer(create(display_size));\n DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider();\n System::create(renderer, rp);\n\n return renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::destroySystem()\n{\n System* sys;\n if (!(sys = System::getSingletonPtr()))\n throw InvalidRequestException(\n \"CEGUI::System object is not created or was already destroyed.\");\n\n OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(sys->getRenderer());\n DefaultResourceProvider* rp =\n static_cast<DefaultResourceProvider*>(sys->getResourceProvider());\n\n System::destroy();\n delete rp;\n destroy(*renderer);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::create(const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n return *new OpenGL3Renderer();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer& OpenGL3Renderer::create(const Sizef& display_size,\n const int abi)\n{\n System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME);\n\n return *new OpenGL3Renderer(display_size);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::destroy(OpenGL3Renderer& renderer)\n{\n delete &renderer;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::OpenGL3Renderer() :\n OpenGLRendererBase(true),\n d_shaderWrapperTextured(0),\n d_openGLStateChanger(0),\n d_shaderManager(0)\n{\n init();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::OpenGL3Renderer(const Sizef& display_size) :\n OpenGLRendererBase(display_size, true),\n d_shaderWrapperTextured(0),\n d_openGLStateChanger(0),\n d_shaderManager(0)\n{\n init();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::init()\n{\n if (OpenGLInfo::getSingleton().isUsingOpenglEs()\n && OpenGLInfo::getSingleton().verMajor() < 2)\n throw RendererException(\"Only version 2 and up of OpenGL ES is \"\n \"supported by this type of renderer.\");\n initialiseRendererIDString();\n d_openGLStateChanger = new OpenGL3StateChangeWrapper();\n initialiseTextureTargetFactory();\n initialiseOpenGLShaders();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGL3Renderer::~OpenGL3Renderer()\n{\n delete d_textureTargetFactory;\n delete d_openGLStateChanger;\n delete d_shaderManager;\n\n delete d_shaderWrapperTextured;\n delete d_shaderWrapperSolid;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseRendererIDString()\n{\n d_rendererID = OpenGLInfo::getSingleton().isUsingDesktopOpengl()\n ? \"CEGUI::OpenGL3Renderer - Official OpenGL 3.2 core based \"\n \"renderer module.\"\n : \"CEGUI::OpenGL3Renderer - OpenGL ES 2 renderer module.\";\n}\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl(CEGUI::RefCounted<RenderMaterial> renderMaterial)\n{\n return new OpenGL3GeometryBuffer(*this, renderMaterial);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nTextureTarget* OpenGL3Renderer::createTextureTarget_impl()\n{\n return d_textureTargetFactory->create(*this);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::beginRendering()\n{\n \/\/ Deprecated OpenGL 2 client states may mess up rendering. They are not added here\n \/\/ since they are deprecated and thus do not fit in a OpenGL Core renderer. However\n \/\/ this information may be relevant for people combining deprecated and modern\n \/\/ functions. In that case disable client states like this: glDisableClientState(GL_VERTEX_ARRAY);\n\n \n glEnable(GL_SCISSOR_TEST);\n glEnable(GL_BLEND);\n\n \/\/ force set blending ops to get to a known state.\n setupRenderingBlendMode(BM_NORMAL, true);\n\n \/\/ if enabled, restores a subset of the GL state back to default values.\n if (d_initExtraStates)\n setupExtraStates();\n\n d_openGLStateChanger->reset();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::endRendering()\n{\n glUseProgram(0);\n\n if (d_initExtraStates)\n {\n glDisable(GL_SCISSOR_TEST);\n \n glBlendFunc(GL_ONE, GL_ZERO);\n if (OpenGLInfo::getSingleton().isVaoSupported())\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::setupExtraStates()\n{\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n if (OpenGLInfo::getSingleton().isPolygonModeSupported())\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n\n glUseProgram(0);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseTextureTargetFactory()\n{\n \/\/Use OGL core implementation for FBOs\n d_rendererID += \" TextureTarget support enabled via FBO OGL 3.2 core implementation.\";\n d_textureTargetFactory = new OGLTemplateTargetFactory<OpenGL3FBOTextureTarget>;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode,\n const bool force)\n{\n \/\/ exit if mode is already set up (and update not forced)\n if ((d_activeBlendMode == mode) && !force)\n return;\n\n d_activeBlendMode = mode;\n\n if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)\n {\n d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);\n }\n else\n {\n d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE);\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nSizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz)\n{\n return Sizef(sz);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLBaseStateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger()\n{\n return d_openGLStateChanger;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseOpenGLShaders()\n{\n checkGLErrors();\n d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSL);\n d_shaderManager->initialiseShaders();\n\n initialiseStandardTexturedShaderWrapper();\n initialiseStandardColouredShaderWrapper();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRefCounted<RenderMaterial> OpenGL3Renderer::createRenderMaterial(const DefaultShaderType shaderType) const\n{\n if(shaderType == DS_TEXTURED)\n {\n RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperTextured));\n\n return render_material;\n }\n else if(shaderType == DS_SOLID)\n {\n RefCounted<RenderMaterial> render_material(new RenderMaterial(d_shaderWrapperSolid));\n\n return render_material;\n }\n else\n {\n throw RendererException(\n \"A default shader of this type does not exist.\");\n\n return RefCounted<RenderMaterial>();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseStandardTexturedShaderWrapper()\n{\n OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED);\n d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger);\n\n d_shaderWrapperTextured->addTextureUniformVariable(\"texture0\", 0);\n\n d_shaderWrapperTextured->addUniformVariable(\"modelViewProjMatrix\");\n d_shaderWrapperTextured->addUniformVariable(\"alphaPercentage\");\n\n d_shaderWrapperTextured->addAttributeVariable(\"inPosition\");\n d_shaderWrapperTextured->addAttributeVariable(\"inTexCoord\");\n d_shaderWrapperTextured->addAttributeVariable(\"inColour\");\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid OpenGL3Renderer::initialiseStandardColouredShaderWrapper()\n{\n OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID);\n d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger);\n\n d_shaderWrapperSolid->addUniformVariable(\"modelViewProjMatrix\");\n d_shaderWrapperSolid->addUniformVariable(\"alphaPercentage\");\n\n d_shaderWrapperSolid->addAttributeVariable(\"inPosition\");\n d_shaderWrapperSolid->addAttributeVariable(\"inColour\");\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nOpenGLTexture* OpenGL3Renderer::createTexture_impl(const String& name)\n{\n return new OpenGL3Texture(*this, name);\n} \n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>\/**\n * lengthPrefixStrings.cpp\n *\n * Author: Patrick Rummage (patrickbrummage@gmail.com)\n *\n * Objective:\n * Implement a string type that stores its length at location[0]. \n * Create functions to append, concatenate, and locate characters\n * within strings of this type.\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\ntypedef char *lengthString;\n\nchar characterAt(lengthString s, int position)\n{\n return s[position + 1];\n}\n\nvoid append(lengthString &s, char c)\n{\n int oldLength = s[0];\n s[oldLength + 1] = c;\n s[0] = oldLength + 1;\n}\n\nvoid concatenate(lengthString &s1, lengthString s2)\n{\n int s1_length = s1[0];\n int s2_length = s2[0];\n int s1_newLength = s1_length + s2_length;\n for (int i = 1; i <= s2_length; i++)\n {\n s1[s1_length + i] = s2[i];\n }\n s1[0] = s1_newLength;\n}\n\nvoid output(lengthString s)\n{\n int length = s[0];\n for(int i = 1; i <= length; i++)\n {\n cout << s[i];\n }\n cout << \"\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n lengthString input1 = new char[0];\n cout << \"Enter a string: \";\n char inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input1, inputChar);\n inputChar = cin.get(); \n }\n output(input1);\n \n lengthString input2 = new char[0];\n cout << \"Enter another string: \";\n inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input2, inputChar);\n inputChar = cin.get(); \n }\n concatenate(input1, input2);\n output(input1);\n \n return 0;\n}\n\n<commit_msg>added substring function<commit_after>\/**\n * lengthPrefixStrings.cpp\n *\n * Author: Patrick Rummage (patrickbrummage@gmail.com)\n *\n * Objective:\n * Implement a string type that stores its length at location[0]. \n * Define functions to append, concatenate, create substrings, and \n * retrieve characters from strings of this type.\n *\/\n#include <iostream>\nusing std::cin;\nusing std::cout;\n\ntypedef char *lengthString;\n\nchar characterAt(lengthString s, int position)\n{\n return s[position + 1];\n}\n\nvoid append(lengthString &s, char c)\n{\n int oldLength = s[0];\n s[oldLength + 1] = c;\n s[0] = oldLength + 1;\n}\n\nvoid concatenate(lengthString &s1, lengthString s2)\n{\n int s1_length = s1[0];\n int s2_length = s2[0];\n int s1_newLength = s1_length + s2_length;\n for (int i = 1; i <= s2_length; i++)\n {\n s1[s1_length + i] = s2[i];\n }\n s1[0] = s1_newLength;\n}\n\nlengthString substring(lengthString s, int position, int length)\n{\n lengthString sub = new char[length + 1];\n sub[0] = length;\n for (int i = 1; i <= length; i++)\n {\n sub[i] = s[position + i];\n }\n return sub;\n}\n\nvoid output(lengthString s)\n{\n int length = s[0];\n for(int i = 1; i <= length; i++)\n {\n cout << s[i];\n }\n cout << \"\\n\";\n}\n\nint main(int argc, char *argv[])\n{\n \/\/Test append()\n lengthString input1 = new char[0];\n cout << \"Enter a string: \";\n char inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input1, inputChar);\n inputChar = cin.get(); \n }\n output(input1);\n\n \/\/Test concatenate()\n lengthString input2 = new char[0];\n cout << \"Enter another string: \";\n inputChar = cin.get();\n while (inputChar != 10)\n {\n append(input2, inputChar);\n inputChar = cin.get(); \n }\n concatenate(input1, input2);\n output(input1);\n\n \/\/Test substring()\n lengthString subString = substring(input1, 3, 4);\n output(subString);\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"config.h\"\n#include <iostream>\n\n#include \"utils\/timer.h\"\n\n#include <fstream>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n#include \"utils\/exception.h\"\n#include \"ed_reader.h\"\n#include \"type\/data.h\"\n#include \"utils\/init.h\"\n\n\nnamespace po = boost::program_options;\nnamespace pt = boost::posix_time;\n\nint main(int argc, char * argv[])\n{\n navitia::init_app();\n auto logger = log4cplus::Logger::getInstance(\"log\");\n std::string output, connection_string, region_name;\n double min_non_connected_graph_ratio;\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Affiche l'aide\")\n (\"version,v\", \"Affiche la version\")\n (\"config-file\", po::value<std::string>(), \"Path to config file\")\n (\"output,o\", po::value<std::string>(&output)->default_value(\"data.nav.lz4\"),\n \"Output file\")\n (\"name,n\", po::value<std::string>(®ion_name)->default_value(\"default\"),\n \"Name of the region you are extracting\")\n (\"min_non_connected_ratio,m\",\n po::value<double>(&min_non_connected_graph_ratio)->default_value(0.1),\n \"min ratio for the size of non connected graph\")\n (\"connection-string\", po::value<std::string>(&connection_string)->required(),\n \"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia\");\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if(vm.count(\"version\")){\n std::cout << argv[0] << \" V\" << NAVITIA_VERSION << \" \" << NAVITIA_BUILD_TYPE << std::endl;\n return 0;\n }\n\n\n if(vm.count(\"config-file\")){\n std::ifstream stream;\n stream.open(vm[\"config-file\"].as<std::string>());\n if(!stream.is_open()){\n throw navitia::exception(\"Unable to load config file\");\n }else{\n po::store(po::parse_config_file(stream, desc), vm);\n }\n }\n\n if(vm.count(\"help\")) {\n std::cout << desc << \"\\n\";\n return 1;\n }\n\n po::notify(vm);\n\n pt::ptime start, now;\n int read, sort, autocomplete, save;\n\n navitia::type::Data data;\n\n \/\/on init now pour le moment à now, à rendre paramétrable pour le debug\n now = start = pt::microsec_clock::local_time();\n\n ed::EdReader reader(connection_string);\n reader.fill(data, min_non_connected_graph_ratio);\n data.build_midnight_interchange();\n read = (pt::microsec_clock::local_time() - start).total_milliseconds();\n\n LOG4CPLUS_INFO(logger, \"line: \" << data.pt_data.lines.size());\n LOG4CPLUS_INFO(logger, \"route: \" << data.pt_data.routes.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern: \" << data.pt_data.journey_patterns.size());\n LOG4CPLUS_INFO(logger, \"stoparea: \" << data.pt_data.stop_areas.size());\n LOG4CPLUS_INFO(logger, \"stoppoint: \" << data.pt_data.stop_points.size());\n LOG4CPLUS_INFO(logger, \"vehiclejourney: \" << data.pt_data.vehicle_journeys.size());\n LOG4CPLUS_INFO(logger, \"stop: \" << data.pt_data.stop_times.size());\n LOG4CPLUS_INFO(logger, \"connection: \" << data.pt_data.stop_point_connections.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern points: \" << data.pt_data.journey_pattern_points.size());\n LOG4CPLUS_INFO(logger, \"modes: \" << data.pt_data.physical_modes.size());\n LOG4CPLUS_INFO(logger, \"validity pattern : \" << data.pt_data.validity_patterns.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern point connections : \" << data.pt_data.journey_pattern_point_connections.size());\n LOG4CPLUS_INFO(logger, \"alias : \" << data.geo_ref.alias.size());\n LOG4CPLUS_INFO(logger, \"synonyms : \" << data.geo_ref.synonymes.size());\n\tLOG4CPLUS_INFO(logger, \"fare tickets: \" << data.fare.fare_map.size());\n LOG4CPLUS_INFO(logger, \"fare transitions: \" << data.fare.nb_transitions());\n LOG4CPLUS_INFO(logger, \"fare od: \" << data.fare.od_tickets.size());\n\n start = pt::microsec_clock::local_time();\n data.pt_data.sort();\n sort = (pt::microsec_clock::local_time() - start).total_milliseconds();\n\n start = pt::microsec_clock::local_time();\n LOG4CPLUS_INFO(logger, \"Building proximity list\");\n data.build_proximity_list();\n LOG4CPLUS_INFO(logger, \"Building uri maps\");\n \/\/construction des map uri => idx\n data.build_uri();\n\n LOG4CPLUS_INFO(logger, \"Building autocomplete\");\n data.build_autocomplete();\n\n \/* ça devrait etre fait avant, à vérifier\n LOG4CPLUS_INFO(logger, \"On va construire les correspondances\");\n {Timer t(\"Construction des correspondances\"); data.pt_data.build_connections();}\n *\/\n autocomplete = (pt::microsec_clock::local_time() - start).total_milliseconds();\n LOG4CPLUS_INFO(logger, \"Begin to save ...\");\n\n start = pt::microsec_clock::local_time();\n try {\n data.save(output);\n } catch(const navitia::exception &e) {\n LOG4CPLUS_ERROR(logger, \"Unable to save\");\n LOG4CPLUS_ERROR(logger, e.what());\n }\n save = (pt::microsec_clock::local_time() - start).total_milliseconds();\n LOG4CPLUS_INFO(logger, \"Data saved\");\n\n LOG4CPLUS_INFO(logger, \"Computing times\");\n LOG4CPLUS_INFO(logger, \"\\t File reading: \" << read << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Sorting data: \" << sort << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Building autocomplete \" << autocomplete << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Data writing: \" << save << \"ms\");\n\n return 0;\n}\n<commit_msg>ed: Delete a tab<commit_after>#include \"config.h\"\n#include <iostream>\n\n#include \"utils\/timer.h\"\n\n#include <fstream>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n#include \"utils\/exception.h\"\n#include \"ed_reader.h\"\n#include \"type\/data.h\"\n#include \"utils\/init.h\"\n\n\nnamespace po = boost::program_options;\nnamespace pt = boost::posix_time;\n\nint main(int argc, char * argv[])\n{\n navitia::init_app();\n auto logger = log4cplus::Logger::getInstance(\"log\");\n std::string output, connection_string, region_name;\n double min_non_connected_graph_ratio;\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Affiche l'aide\")\n (\"version,v\", \"Affiche la version\")\n (\"config-file\", po::value<std::string>(), \"Path to config file\")\n (\"output,o\", po::value<std::string>(&output)->default_value(\"data.nav.lz4\"),\n \"Output file\")\n (\"name,n\", po::value<std::string>(®ion_name)->default_value(\"default\"),\n \"Name of the region you are extracting\")\n (\"min_non_connected_ratio,m\",\n po::value<double>(&min_non_connected_graph_ratio)->default_value(0.1),\n \"min ratio for the size of non connected graph\")\n (\"connection-string\", po::value<std::string>(&connection_string)->required(),\n \"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia\");\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if(vm.count(\"version\")){\n std::cout << argv[0] << \" V\" << NAVITIA_VERSION << \" \" << NAVITIA_BUILD_TYPE << std::endl;\n return 0;\n }\n\n\n if(vm.count(\"config-file\")){\n std::ifstream stream;\n stream.open(vm[\"config-file\"].as<std::string>());\n if(!stream.is_open()){\n throw navitia::exception(\"Unable to load config file\");\n }else{\n po::store(po::parse_config_file(stream, desc), vm);\n }\n }\n\n if(vm.count(\"help\")) {\n std::cout << desc << \"\\n\";\n return 1;\n }\n\n po::notify(vm);\n\n pt::ptime start, now;\n int read, sort, autocomplete, save;\n\n navitia::type::Data data;\n\n \/\/on init now pour le moment à now, à rendre paramétrable pour le debug\n now = start = pt::microsec_clock::local_time();\n\n ed::EdReader reader(connection_string);\n reader.fill(data, min_non_connected_graph_ratio);\n data.build_midnight_interchange();\n read = (pt::microsec_clock::local_time() - start).total_milliseconds();\n\n LOG4CPLUS_INFO(logger, \"line: \" << data.pt_data.lines.size());\n LOG4CPLUS_INFO(logger, \"route: \" << data.pt_data.routes.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern: \" << data.pt_data.journey_patterns.size());\n LOG4CPLUS_INFO(logger, \"stoparea: \" << data.pt_data.stop_areas.size());\n LOG4CPLUS_INFO(logger, \"stoppoint: \" << data.pt_data.stop_points.size());\n LOG4CPLUS_INFO(logger, \"vehiclejourney: \" << data.pt_data.vehicle_journeys.size());\n LOG4CPLUS_INFO(logger, \"stop: \" << data.pt_data.stop_times.size());\n LOG4CPLUS_INFO(logger, \"connection: \" << data.pt_data.stop_point_connections.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern points: \" << data.pt_data.journey_pattern_points.size());\n LOG4CPLUS_INFO(logger, \"modes: \" << data.pt_data.physical_modes.size());\n LOG4CPLUS_INFO(logger, \"validity pattern : \" << data.pt_data.validity_patterns.size());\n LOG4CPLUS_INFO(logger, \"journey_pattern point connections : \" << data.pt_data.journey_pattern_point_connections.size());\n LOG4CPLUS_INFO(logger, \"alias : \" << data.geo_ref.alias.size());\n LOG4CPLUS_INFO(logger, \"synonyms : \" << data.geo_ref.synonymes.size());\n LOG4CPLUS_INFO(logger, \"fare tickets: \" << data.fare.fare_map.size());\n LOG4CPLUS_INFO(logger, \"fare transitions: \" << data.fare.nb_transitions());\n LOG4CPLUS_INFO(logger, \"fare od: \" << data.fare.od_tickets.size());\n\n start = pt::microsec_clock::local_time();\n data.pt_data.sort();\n sort = (pt::microsec_clock::local_time() - start).total_milliseconds();\n\n start = pt::microsec_clock::local_time();\n LOG4CPLUS_INFO(logger, \"Building proximity list\");\n data.build_proximity_list();\n LOG4CPLUS_INFO(logger, \"Building uri maps\");\n \/\/construction des map uri => idx\n data.build_uri();\n\n LOG4CPLUS_INFO(logger, \"Building autocomplete\");\n data.build_autocomplete();\n\n \/* ça devrait etre fait avant, à vérifier\n LOG4CPLUS_INFO(logger, \"On va construire les correspondances\");\n {Timer t(\"Construction des correspondances\"); data.pt_data.build_connections();}\n *\/\n autocomplete = (pt::microsec_clock::local_time() - start).total_milliseconds();\n LOG4CPLUS_INFO(logger, \"Begin to save ...\");\n\n start = pt::microsec_clock::local_time();\n try {\n data.save(output);\n } catch(const navitia::exception &e) {\n LOG4CPLUS_ERROR(logger, \"Unable to save\");\n LOG4CPLUS_ERROR(logger, e.what());\n }\n save = (pt::microsec_clock::local_time() - start).total_milliseconds();\n LOG4CPLUS_INFO(logger, \"Data saved\");\n\n LOG4CPLUS_INFO(logger, \"Computing times\");\n LOG4CPLUS_INFO(logger, \"\\t File reading: \" << read << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Sorting data: \" << sort << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Building autocomplete \" << autocomplete << \"ms\");\n LOG4CPLUS_INFO(logger, \"\\t Data writing: \" << save << \"ms\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/browser_options_handler.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/custom_home_pages_table_model.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/session_startup_pref.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n\nBrowserOptionsHandler::BrowserOptionsHandler()\n : template_url_model_(NULL), startup_custom_pages_table_model_(NULL) {\n#if !defined(OS_MACOSX)\n default_browser_worker_ = new ShellIntegration::DefaultBrowserWorker(this);\n#endif\n}\n\nBrowserOptionsHandler::~BrowserOptionsHandler() {\n if (default_browser_worker_.get())\n default_browser_worker_->ObserverDestroyed();\n if (template_url_model_)\n template_url_model_->RemoveObserver(this);\n}\n\nvoid BrowserOptionsHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n localized_strings->SetString(L\"startupGroupName\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_GROUP_NAME));\n localized_strings->SetString(L\"startupShowDefaultAndNewTab\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_DEFAULT_AND_NEWTAB));\n localized_strings->SetString(L\"startupShowLastSession\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_LAST_SESSION));\n localized_strings->SetString(L\"startupShowPages\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_SHOW_PAGES));\n localized_strings->SetString(L\"startupAddButton\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_ADD_BUTTON));\n localized_strings->SetString(L\"startupRemoveButton\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_REMOVE_BUTTON));\n localized_strings->SetString(L\"startupUseCurrent\",\n l10n_util::GetString(IDS_OPTIONS_STARTUP_USE_CURRENT));\n localized_strings->SetString(L\"homepageGroupName\",\n l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_GROUP_NAME));\n localized_strings->SetString(L\"homepageUseNewTab\",\n l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_USE_NEWTAB));\n localized_strings->SetString(L\"homepageUseURL\",\n l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_USE_URL));\n localized_strings->SetString(L\"homepageShowButton\",\n l10n_util::GetString(IDS_OPTIONS_HOMEPAGE_SHOW_BUTTON));\n localized_strings->SetString(L\"defaultSearchGroupName\",\n l10n_util::GetString(IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME));\n localized_strings->SetString(L\"defaultSearchManageEnginesLink\",\n l10n_util::GetString(IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES_LINK));\n localized_strings->SetString(L\"defaultBrowserGroupName\",\n l10n_util::GetString(IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME));\n localized_strings->SetString(L\"defaultBrowserUnknown\",\n l10n_util::GetStringF(IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN,\n l10n_util::GetString(IDS_PRODUCT_NAME)));\n localized_strings->SetString(L\"defaultBrowserUseAsDefault\",\n l10n_util::GetStringF(IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT,\n l10n_util::GetString(IDS_PRODUCT_NAME)));\n}\n\nvoid BrowserOptionsHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\n \"becomeDefaultBrowser\",\n NewCallback(this, &BrowserOptionsHandler::BecomeDefaultBrowser));\n dom_ui_->RegisterMessageCallback(\n \"setDefaultSearchEngine\",\n NewCallback(this, &BrowserOptionsHandler::SetDefaultSearchEngine));\n dom_ui_->RegisterMessageCallback(\n \"removeStartupPages\",\n NewCallback(this, &BrowserOptionsHandler::RemoveStartupPages));\n dom_ui_->RegisterMessageCallback(\n \"setStartupPagesToCurrentPages\",\n NewCallback(this, &BrowserOptionsHandler::SetStartupPagesToCurrentPages));\n}\n\nvoid BrowserOptionsHandler::Initialize() {\n UpdateDefaultBrowserState();\n UpdateStartupPages();\n UpdateSearchEngines();\n}\n\nvoid BrowserOptionsHandler::UpdateDefaultBrowserState() {\n#if defined(OS_WIN)\n \/\/ Check for side-by-side first.\n if (!BrowserDistribution::GetDistribution()->CanSetAsDefault()) {\n SetDefaultBrowserUIString(IDS_OPTIONS_DEFAULTBROWSER_SXS);\n return;\n }\n#endif\n\n#if defined(OS_MACOSX)\n ShellIntegration::DefaultBrowserState state =\n ShellIntegration::IsDefaultBrowser();\n int status_string_id;\n if (state == ShellIntegration::IS_DEFAULT_BROWSER)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n else if (state == ShellIntegration::NOT_DEFAULT_BROWSER)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n else\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n\n SetDefaultBrowserUIString(status_string_id);\n#else\n default_browser_worker_->StartCheckDefaultBrowser();\n#endif\n}\n\nvoid BrowserOptionsHandler::BecomeDefaultBrowser(const Value* value) {\n#if defined(OS_MACOSX)\n if (ShellIntegration::SetAsDefaultBrowser())\n UpdateDefaultBrowserState();\n#else\n default_browser_worker_->StartSetAsDefaultBrowser();\n \/\/ Callback takes care of updating UI.\n#endif\n}\n\nint BrowserOptionsHandler::StatusStringIdForState(\n ShellIntegration::DefaultBrowserState state) {\n if (state == ShellIntegration::IS_DEFAULT_BROWSER)\n return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n if (state == ShellIntegration::NOT_DEFAULT_BROWSER)\n return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n}\n\nvoid BrowserOptionsHandler::SetDefaultBrowserUIState(\n ShellIntegration::DefaultBrowserUIState state) {\n int status_string_id;\n if (state == ShellIntegration::STATE_IS_DEFAULT)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n else if (state == ShellIntegration::STATE_NOT_DEFAULT)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n else if (state == ShellIntegration::STATE_UNKNOWN)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n else\n return; \/\/ Still processing.\n\n SetDefaultBrowserUIString(status_string_id);\n}\n\nvoid BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) {\n scoped_ptr<Value> status_string(Value::CreateStringValue(\n l10n_util::GetStringF(status_string_id,\n l10n_util::GetString(IDS_PRODUCT_NAME))));\n\n scoped_ptr<Value> is_default(Value::CreateBooleanValue(\n status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT));\n\n dom_ui_->CallJavascriptFunction(\n L\"BrowserOptions.updateDefaultBrowserState\",\n *(status_string.get()), *(is_default.get()));\n}\n\nvoid BrowserOptionsHandler::OnTemplateURLModelChanged() {\n if (!template_url_model_ || !template_url_model_->loaded())\n return;\n\n const TemplateURL* default_url =\n template_url_model_->GetDefaultSearchProvider();\n\n int default_index = 0;\n ListValue search_engines;\n std::vector<const TemplateURL*> model_urls =\n template_url_model_->GetTemplateURLs();\n for (size_t i = 0; i < model_urls.size(); ++i) {\n if (!model_urls[i]->ShowInDefaultList())\n continue;\n\n DictionaryValue* entry = new DictionaryValue();\n entry->SetString(L\"name\", model_urls[i]->short_name());\n entry->SetInteger(L\"index\", i);\n search_engines.Append(entry);\n if (model_urls[i] == default_url)\n default_index = i;\n }\n\n scoped_ptr<Value> default_value(Value::CreateIntegerValue(default_index));\n\n dom_ui_->CallJavascriptFunction(L\"BrowserOptions.updateSearchEngines\",\n search_engines, *(default_value.get()));\n}\n\nvoid BrowserOptionsHandler::SetDefaultSearchEngine(const Value* value) {\n if (!value || !value->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return;\n }\n const ListValue* param_values = static_cast<const ListValue*>(value);\n std::string string_value;\n if (param_values->GetSize() != 1 ||\n !param_values->GetString(0, &string_value)) {\n NOTREACHED();\n return;\n }\n int selected_index;\n base::StringToInt(string_value, &selected_index);\n\n std::vector<const TemplateURL*> model_urls =\n template_url_model_->GetTemplateURLs();\n if (selected_index >= 0 &&\n selected_index < static_cast<int>(model_urls.size()))\n template_url_model_->SetDefaultSearchProvider(model_urls[selected_index]);\n}\n\nvoid BrowserOptionsHandler::UpdateSearchEngines() {\n template_url_model_ = dom_ui_->GetProfile()->GetTemplateURLModel();\n if (template_url_model_) {\n template_url_model_->Load();\n template_url_model_->AddObserver(this);\n OnTemplateURLModelChanged();\n }\n}\n\nvoid BrowserOptionsHandler::UpdateStartupPages() {\n Profile* profile = dom_ui_->GetProfile();\n startup_custom_pages_table_model_.reset(\n new CustomHomePagesTableModel(profile));\n startup_custom_pages_table_model_->SetObserver(this);\n\n const SessionStartupPref startup_pref =\n SessionStartupPref::GetStartupPref(profile->GetPrefs());\n startup_custom_pages_table_model_->SetURLs(startup_pref.urls);\n}\n\nvoid BrowserOptionsHandler::OnModelChanged() {\n \/\/ TODO(stuartmorgan): Add support for showing favicons.\n ListValue startup_pages;\n int page_count = startup_custom_pages_table_model_->RowCount();\n for (int i = 0; i < page_count; ++i) {\n DictionaryValue* entry = new DictionaryValue();\n entry->SetString(L\"title\",\n startup_custom_pages_table_model_->GetText(i, 0));\n entry->SetString(L\"tooltip\",\n startup_custom_pages_table_model_->GetTooltip(i));\n startup_pages.Append(entry);\n }\n\n dom_ui_->CallJavascriptFunction(L\"BrowserOptions.updateStartupPages\",\n startup_pages);\n}\n\nvoid BrowserOptionsHandler::OnItemsChanged(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::OnItemsAdded(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::OnItemsRemoved(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::SetStartupPagesToCurrentPages(const Value* value) {\n startup_custom_pages_table_model_->SetToCurrentlyOpenPages();\n SaveStartupPagesPref();\n}\n\nvoid BrowserOptionsHandler::RemoveStartupPages(const Value* value) {\n if (!value || !value->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return;\n }\n const ListValue* param_values = static_cast<const ListValue*>(value);\n for (int i = param_values->GetSize() - 1; i >= 0; --i) {\n std::string string_value;\n if (!param_values->GetString(i, &string_value)) {\n NOTREACHED();\n return;\n }\n int selected_index;\n base::StringToInt(string_value, &selected_index);\n if (selected_index < 0 ||\n selected_index >= startup_custom_pages_table_model_->RowCount()) {\n NOTREACHED();\n return;\n }\n startup_custom_pages_table_model_->Remove(selected_index);\n }\n\n SaveStartupPagesPref();\n}\n\nvoid BrowserOptionsHandler::SaveStartupPagesPref() {\n PrefService* prefs = dom_ui_->GetProfile()->GetPrefs();\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);\n pref.urls = startup_custom_pages_table_model_->GetURLs();\n\n SessionStartupPref::SetStartupPref(prefs, pref);\n}\n<commit_msg>Convert browser\/dom_ui\/browser_options_handler.cc to stop using wstrings\/wchar_t*s.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/browser_options_handler.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/custom_home_pages_table_model.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/session_startup_pref.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n\nBrowserOptionsHandler::BrowserOptionsHandler()\n : template_url_model_(NULL), startup_custom_pages_table_model_(NULL) {\n#if !defined(OS_MACOSX)\n default_browser_worker_ = new ShellIntegration::DefaultBrowserWorker(this);\n#endif\n}\n\nBrowserOptionsHandler::~BrowserOptionsHandler() {\n if (default_browser_worker_.get())\n default_browser_worker_->ObserverDestroyed();\n if (template_url_model_)\n template_url_model_->RemoveObserver(this);\n}\n\nvoid BrowserOptionsHandler::GetLocalizedValues(\n DictionaryValue* localized_strings) {\n DCHECK(localized_strings);\n localized_strings->SetString(\"startupGroupName\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_GROUP_NAME));\n localized_strings->SetString(\"startupShowDefaultAndNewTab\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_DEFAULT_AND_NEWTAB));\n localized_strings->SetString(\"startupShowLastSession\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_LAST_SESSION));\n localized_strings->SetString(\"startupShowPages\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_SHOW_PAGES));\n localized_strings->SetString(\"startupAddButton\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_ADD_BUTTON));\n localized_strings->SetString(\"startupRemoveButton\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_REMOVE_BUTTON));\n localized_strings->SetString(\"startupUseCurrent\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_STARTUP_USE_CURRENT));\n localized_strings->SetString(\"homepageGroupName\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_GROUP_NAME));\n localized_strings->SetString(\"homepageUseNewTab\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_USE_NEWTAB));\n localized_strings->SetString(\"homepageUseURL\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_USE_URL));\n localized_strings->SetString(\"homepageShowButton\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_HOMEPAGE_SHOW_BUTTON));\n localized_strings->SetString(\"defaultSearchGroupName\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME));\n localized_strings->SetString(\"defaultSearchManageEnginesLink\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES_LINK));\n localized_strings->SetString(\"defaultBrowserGroupName\",\n l10n_util::GetStringUTF16(IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME));\n localized_strings->SetString(\"defaultBrowserUnknown\",\n l10n_util::GetStringFUTF16(IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN,\n l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));\n localized_strings->SetString(\"defaultBrowserUseAsDefault\",\n l10n_util::GetStringFUTF16(IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT,\n l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));\n}\n\nvoid BrowserOptionsHandler::RegisterMessages() {\n dom_ui_->RegisterMessageCallback(\n \"becomeDefaultBrowser\",\n NewCallback(this, &BrowserOptionsHandler::BecomeDefaultBrowser));\n dom_ui_->RegisterMessageCallback(\n \"setDefaultSearchEngine\",\n NewCallback(this, &BrowserOptionsHandler::SetDefaultSearchEngine));\n dom_ui_->RegisterMessageCallback(\n \"removeStartupPages\",\n NewCallback(this, &BrowserOptionsHandler::RemoveStartupPages));\n dom_ui_->RegisterMessageCallback(\n \"setStartupPagesToCurrentPages\",\n NewCallback(this, &BrowserOptionsHandler::SetStartupPagesToCurrentPages));\n}\n\nvoid BrowserOptionsHandler::Initialize() {\n UpdateDefaultBrowserState();\n UpdateStartupPages();\n UpdateSearchEngines();\n}\n\nvoid BrowserOptionsHandler::UpdateDefaultBrowserState() {\n#if defined(OS_WIN)\n \/\/ Check for side-by-side first.\n if (!BrowserDistribution::GetDistribution()->CanSetAsDefault()) {\n SetDefaultBrowserUIString(IDS_OPTIONS_DEFAULTBROWSER_SXS);\n return;\n }\n#endif\n\n#if defined(OS_MACOSX)\n ShellIntegration::DefaultBrowserState state =\n ShellIntegration::IsDefaultBrowser();\n int status_string_id;\n if (state == ShellIntegration::IS_DEFAULT_BROWSER)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n else if (state == ShellIntegration::NOT_DEFAULT_BROWSER)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n else\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n\n SetDefaultBrowserUIString(status_string_id);\n#else\n default_browser_worker_->StartCheckDefaultBrowser();\n#endif\n}\n\nvoid BrowserOptionsHandler::BecomeDefaultBrowser(const Value* value) {\n#if defined(OS_MACOSX)\n if (ShellIntegration::SetAsDefaultBrowser())\n UpdateDefaultBrowserState();\n#else\n default_browser_worker_->StartSetAsDefaultBrowser();\n \/\/ Callback takes care of updating UI.\n#endif\n}\n\nint BrowserOptionsHandler::StatusStringIdForState(\n ShellIntegration::DefaultBrowserState state) {\n if (state == ShellIntegration::IS_DEFAULT_BROWSER)\n return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n if (state == ShellIntegration::NOT_DEFAULT_BROWSER)\n return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n}\n\nvoid BrowserOptionsHandler::SetDefaultBrowserUIState(\n ShellIntegration::DefaultBrowserUIState state) {\n int status_string_id;\n if (state == ShellIntegration::STATE_IS_DEFAULT)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;\n else if (state == ShellIntegration::STATE_NOT_DEFAULT)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;\n else if (state == ShellIntegration::STATE_UNKNOWN)\n status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;\n else\n return; \/\/ Still processing.\n\n SetDefaultBrowserUIString(status_string_id);\n}\n\nvoid BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) {\n scoped_ptr<Value> status_string(Value::CreateStringValue(\n l10n_util::GetStringFUTF16(status_string_id,\n l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))));\n\n scoped_ptr<Value> is_default(Value::CreateBooleanValue(\n status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT));\n\n dom_ui_->CallJavascriptFunction(\n L\"BrowserOptions.updateDefaultBrowserState\",\n *(status_string.get()), *(is_default.get()));\n}\n\nvoid BrowserOptionsHandler::OnTemplateURLModelChanged() {\n if (!template_url_model_ || !template_url_model_->loaded())\n return;\n\n const TemplateURL* default_url =\n template_url_model_->GetDefaultSearchProvider();\n\n int default_index = 0;\n ListValue search_engines;\n std::vector<const TemplateURL*> model_urls =\n template_url_model_->GetTemplateURLs();\n for (size_t i = 0; i < model_urls.size(); ++i) {\n if (!model_urls[i]->ShowInDefaultList())\n continue;\n\n DictionaryValue* entry = new DictionaryValue();\n entry->SetString(\"name\", WideToUTF16Hack(model_urls[i]->short_name()));\n entry->SetInteger(\"index\", i);\n search_engines.Append(entry);\n if (model_urls[i] == default_url)\n default_index = i;\n }\n\n scoped_ptr<Value> default_value(Value::CreateIntegerValue(default_index));\n\n dom_ui_->CallJavascriptFunction(L\"BrowserOptions.updateSearchEngines\",\n search_engines, *(default_value.get()));\n}\n\nvoid BrowserOptionsHandler::SetDefaultSearchEngine(const Value* value) {\n if (!value || !value->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return;\n }\n const ListValue* param_values = static_cast<const ListValue*>(value);\n std::string string_value;\n if (param_values->GetSize() != 1 ||\n !param_values->GetString(0, &string_value)) {\n NOTREACHED();\n return;\n }\n int selected_index;\n base::StringToInt(string_value, &selected_index);\n\n std::vector<const TemplateURL*> model_urls =\n template_url_model_->GetTemplateURLs();\n if (selected_index >= 0 &&\n selected_index < static_cast<int>(model_urls.size()))\n template_url_model_->SetDefaultSearchProvider(model_urls[selected_index]);\n}\n\nvoid BrowserOptionsHandler::UpdateSearchEngines() {\n template_url_model_ = dom_ui_->GetProfile()->GetTemplateURLModel();\n if (template_url_model_) {\n template_url_model_->Load();\n template_url_model_->AddObserver(this);\n OnTemplateURLModelChanged();\n }\n}\n\nvoid BrowserOptionsHandler::UpdateStartupPages() {\n Profile* profile = dom_ui_->GetProfile();\n startup_custom_pages_table_model_.reset(\n new CustomHomePagesTableModel(profile));\n startup_custom_pages_table_model_->SetObserver(this);\n\n const SessionStartupPref startup_pref =\n SessionStartupPref::GetStartupPref(profile->GetPrefs());\n startup_custom_pages_table_model_->SetURLs(startup_pref.urls);\n}\n\nvoid BrowserOptionsHandler::OnModelChanged() {\n \/\/ TODO(stuartmorgan): Add support for showing favicons.\n ListValue startup_pages;\n int page_count = startup_custom_pages_table_model_->RowCount();\n for (int i = 0; i < page_count; ++i) {\n DictionaryValue* entry = new DictionaryValue();\n entry->SetString(\"title\", WideToUTF16Hack(\n startup_custom_pages_table_model_->GetText(i, 0)));\n entry->SetString(\"tooltip\", WideToUTF16Hack(\n startup_custom_pages_table_model_->GetTooltip(i)));\n startup_pages.Append(entry);\n }\n\n dom_ui_->CallJavascriptFunction(L\"BrowserOptions.updateStartupPages\",\n startup_pages);\n}\n\nvoid BrowserOptionsHandler::OnItemsChanged(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::OnItemsAdded(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::OnItemsRemoved(int start, int length) {\n OnModelChanged();\n}\n\nvoid BrowserOptionsHandler::SetStartupPagesToCurrentPages(const Value* value) {\n startup_custom_pages_table_model_->SetToCurrentlyOpenPages();\n SaveStartupPagesPref();\n}\n\nvoid BrowserOptionsHandler::RemoveStartupPages(const Value* value) {\n if (!value || !value->IsType(Value::TYPE_LIST)) {\n NOTREACHED();\n return;\n }\n const ListValue* param_values = static_cast<const ListValue*>(value);\n for (int i = param_values->GetSize() - 1; i >= 0; --i) {\n std::string string_value;\n if (!param_values->GetString(i, &string_value)) {\n NOTREACHED();\n return;\n }\n int selected_index;\n base::StringToInt(string_value, &selected_index);\n if (selected_index < 0 ||\n selected_index >= startup_custom_pages_table_model_->RowCount()) {\n NOTREACHED();\n return;\n }\n startup_custom_pages_table_model_->Remove(selected_index);\n }\n\n SaveStartupPagesPref();\n}\n\nvoid BrowserOptionsHandler::SaveStartupPagesPref() {\n PrefService* prefs = dom_ui_->GetProfile()->GetPrefs();\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);\n pref.urls = startup_custom_pages_table_model_->GetURLs();\n\n SessionStartupPref::SetStartupPref(prefs, pref);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\n#endif \/\/ !defined(OS_MACOSX)\n\nnamespace {\n\nclass SavePageFinishedObserver : public NotificationObserver {\n public:\n SavePageFinishedObserver() {\n registrar_.Add(this, NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n ui_test_utils::RunMessageLoop();\n }\n\n GURL page_url() const { return page_url_; }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED) {\n page_url_ = *Details<GURL>(details).ptr();\n MessageLoopForUI::current()->Quit();\n } else {\n NOTREACHED();\n }\n }\n\n private:\n NotificationRegistrar registrar_;\n\n GURL page_url_;\n\n DISALLOW_COPY_AND_ASSIGN(SavePageFinishedObserver);\n};\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\n#if !defined(OS_MACOSX)\n\/\/ TODO(port): BUG16322\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n} \/\/ namespace\n<commit_msg>Enable browser_tests: SavePageBrowserTest.FileNameFromPageTitle & SavePageBrowserTest.SaveHTMLOnly on the Mac.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/net\/url_request_mock_http_job.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nstatic const FilePath::CharType* kTestDir = FILE_PATH_LITERAL(\"save_page\");\n\nstatic const char* kAppendedExtension =\n#if defined(OS_WIN)\n \".htm\";\n#else\n \".html\";\n#endif\n\nnamespace {\n\nclass SavePageFinishedObserver : public NotificationObserver {\n public:\n SavePageFinishedObserver() {\n registrar_.Add(this, NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED,\n NotificationService::AllSources());\n ui_test_utils::RunMessageLoop();\n }\n\n GURL page_url() const { return page_url_; }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::SAVE_PACKAGE_SUCCESSFULLY_FINISHED) {\n page_url_ = *Details<GURL>(details).ptr();\n MessageLoopForUI::current()->Quit();\n } else {\n NOTREACHED();\n }\n }\n\n private:\n NotificationRegistrar registrar_;\n\n GURL page_url_;\n\n DISALLOW_COPY_AND_ASSIGN(SavePageFinishedObserver);\n};\n\nclass SavePageBrowserTest : public InProcessBrowserTest {\n protected:\n void SetUp() {\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir_));\n ASSERT_TRUE(save_dir_.CreateUniqueTempDir());\n InProcessBrowserTest::SetUp();\n }\n\n \/\/ Path to directory containing test data.\n FilePath test_dir_;\n\n \/\/ Temporary directory we will save pages to.\n ScopedTempDir save_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveHTMLOnly) {\n FilePath file_name(FILE_PATH_LITERAL(\"a.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"a_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_ONLY_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_FALSE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).Append(file_name),\n full_file_name));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, SaveCompleteHTML) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n FilePath full_file_name = save_dir_.path().Append(file_name);\n FilePath dir = save_dir_.path().AppendASCII(\"b_files\");\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved1.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, NoSave) {\n ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));\n ASSERT_TRUE(browser()->command_updater()->SupportsCommand(IDC_SAVE_PAGE));\n EXPECT_FALSE(browser()->command_updater()->IsCommandEnabled(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(SavePageBrowserTest, FileNameFromPageTitle) {\n FilePath file_name(FILE_PATH_LITERAL(\"b.htm\"));\n\n GURL url = URLRequestMockHTTPJob::GetMockUrl(\n FilePath(kTestDir).Append(file_name));\n ui_test_utils::NavigateToURL(browser(), url);\n\n FilePath full_file_name = save_dir_.path().AppendASCII(\n std::string(\"Test page for saving page feature\") + kAppendedExtension);\n FilePath dir = save_dir_.path().AppendASCII(\n \"Test page for saving page feature_files\");\n\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_TRUE(current_tab);\n\n ASSERT_TRUE(current_tab->SavePage(full_file_name, dir,\n SavePackage::SAVE_AS_COMPLETE_HTML));\n SavePageFinishedObserver observer;\n\n EXPECT_EQ(url, observer.page_url());\n EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());\n EXPECT_TRUE(file_util::PathExists(full_file_name));\n EXPECT_TRUE(file_util::PathExists(dir));\n EXPECT_TRUE(file_util::TextContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"b.saved2.htm\"),\n full_file_name));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.png\"),\n dir.AppendASCII(\"1.png\")));\n EXPECT_TRUE(file_util::ContentsEqual(\n test_dir_.Append(FilePath(kTestDir)).AppendASCII(\"1.css\"),\n dir.AppendASCII(\"1.css\")));\n}\n\n} \/\/ namespace\n<|endoftext|>"}